[
  {
    "code": "def _buildItem(self, elem, cls=None, initpath=None):\n        initpath = initpath or self._initpath\n        if cls is not None:\n            return cls(self._server, elem, initpath)\n        etype = elem.attrib.get('type', elem.attrib.get('streamType'))\n        ehash = '%s.%s' % (elem.tag, etype) if etype else elem.tag\n        ecls = utils.PLEXOBJECTS.get(ehash, utils.PLEXOBJECTS.get(elem.tag))\n        if ecls is not None:\n            return ecls(self._server, elem, initpath)\n        raise UnknownType(\"Unknown library type <%s type='%s'../>\" % (elem.tag, etype))",
    "docstring": "Factory function to build objects based on registered PLEXOBJECTS."
  },
  {
    "code": "def connectMSExchange(server):\n    if not sspi:\n        return False, 'No sspi module found.'\n    code, response = server.ehlo()\n    if code != SMTP_EHLO_OKAY:\n        return False, 'Server did not respond to EHLO command.'\n    sspi_client = sspi.ClientAuth('NTLM')\n    sec_buffer = None\n    err, sec_buffer = sspi_client.authorize(sec_buffer)\n    buffer = sec_buffer[0].Buffer\n    ntlm_message = base64.encodestring(buffer).replace('\\n', '')\n    code, response = server.docmd('AUTH', 'NTLM ' + ntlm_message)\n    if code != SMTP_AUTH_CHALLENGE:\n        msg = 'Server did not respond as expected to NTLM negotiate message'\n        return False, msg\n    err, sec_buffer = sspi_client.authorize(base64.decodestring(response))\n    buffer = sec_buffer[0].Buffer\n    ntlm_message = base64.encodestring(buffer).replace('\\n', '')\n    code, response = server.docmd('', ntlm_message)\n    if code != SMTP_AUTH_OKAY:\n        return False, response\n    return True, ''",
    "docstring": "Creates a connection for the inputted server to a Microsoft Exchange server.\n\n    :param      server | <smtplib.SMTP>\n    \n    :usage      |>>> import smtplib\n                |>>> import projex.notify\n                |>>> smtp = smtplib.SMTP('mail.server.com')\n                |>>> projex.notify.connectMSExchange(smtp)\n    \n    :return     (<bool> success, <str> reason)"
  },
  {
    "code": "def load_from_cache(path=user_path):\n    if not path:\n        return\n    try:\n        with open(path, 'rb') as f:\n            dversion, mversion, data = pickle.load(f)\n        if dversion == data_version and mversion == module_version:\n            return data\n    except (FileNotFoundError, ValueError, EOFError):\n        pass",
    "docstring": "Try to load category ranges from userlevel cache file.\n\n    :param path: path to userlevel cache file\n    :type path: str\n    :returns: category ranges dict or None\n    :rtype: None or dict of RangeGroup"
  },
  {
    "code": "def convex_conj(self):\n        conj_exp = conj_exponent(self.pointwise_norm.exponent)\n        return IndicatorGroupL1UnitBall(self.domain, exponent=conj_exp)",
    "docstring": "The convex conjugate functional of the group L1-norm."
  },
  {
    "code": "def extract(self, item):\n        article_candidates = []\n        for extractor in self.extractor_list:\n            article_candidates.append(extractor.extract(item))\n        article_candidates = self.cleaner.clean(article_candidates)\n        article = self.comparer.compare(item, article_candidates)\n        item['article_title'] = article.title\n        item['article_description'] = article.description\n        item['article_text'] = article.text\n        item['article_image'] = article.topimage\n        item['article_author'] = article.author\n        item['article_publish_date'] = article.publish_date\n        item['article_language'] = article.language\n        return item",
    "docstring": "Runs the HTML-response trough a list of initialized extractors, a cleaner and compares the results.\n\n        :param item: NewscrawlerItem to be processed.\n        :return: An updated NewscrawlerItem including the results of the extraction"
  },
  {
    "code": "def _get_ca_certs_paths():\n    ca_certs = []\n    embedded_root = os.path.dirname(os.path.abspath(__file__))\n    for _ in range(10):\n        if os.path.basename(embedded_root) == 'embedded':\n            ca_certs.append(os.path.join(embedded_root, 'ssl', 'certs', 'cacert.pem'))\n            break\n        embedded_root = os.path.dirname(embedded_root)\n    else:\n        raise OSError(\n            'Unable to locate `embedded` directory. Please specify ca_certs in your http yaml configuration file.'\n        )\n    try:\n        import tornado\n    except ImportError:\n        pass\n    else:\n        ca_certs.append(os.path.join(os.path.dirname(tornado.__file__), 'ca-certificates.crt'))\n    ca_certs.append('/etc/ssl/certs/ca-certificates.crt')\n    return ca_certs",
    "docstring": "Get a list of possible paths containing certificates\n\n    Check is installed via pip to:\n     * Windows: embedded/lib/site-packages/datadog_checks/http_check\n     * Linux: embedded/lib/python2.7/site-packages/datadog_checks/http_check\n\n    Certificate is installed to:\n     * embedded/ssl/certs/cacert.pem\n\n    walk up to `embedded`, and back down to ssl/certs to find the certificate file"
  },
  {
    "code": "def trigger_all_callbacks(self, callbacks=None):\n        return [ret\n                for key in self\n                for ret in self.trigger_callbacks(key, callbacks=None)]",
    "docstring": "Trigger callbacks for all keys on all or a subset of subscribers.\n\n        :param Iterable callbacks: list of callbacks or none for all subscribed\n        :rtype: Iterable[tornado.concurrent.Future]"
  },
  {
    "code": "def _parse_log_entry(entry_pb):\n    try:\n        return MessageToDict(entry_pb)\n    except TypeError:\n        if entry_pb.HasField(\"proto_payload\"):\n            proto_payload = entry_pb.proto_payload\n            entry_pb.ClearField(\"proto_payload\")\n            entry_mapping = MessageToDict(entry_pb)\n            entry_mapping[\"protoPayload\"] = proto_payload\n            return entry_mapping\n        else:\n            raise",
    "docstring": "Special helper to parse ``LogEntry`` protobuf into a dictionary.\n\n    The ``proto_payload`` field in ``LogEntry`` is of type ``Any``. This\n    can be problematic if the type URL in the payload isn't in the\n    ``google.protobuf`` registry. To help with parsing unregistered types,\n    this function will remove ``proto_payload`` before parsing.\n\n    :type entry_pb: :class:`.log_entry_pb2.LogEntry`\n    :param entry_pb: Log entry protobuf.\n\n    :rtype: dict\n    :returns: The parsed log entry. The ``protoPayload`` key may contain\n              the raw ``Any`` protobuf from ``entry_pb.proto_payload`` if\n              it could not be parsed."
  },
  {
    "code": "def ssl_context(self, verify=True, cert_reqs=None,\n                    check_hostname=False, certfile=None, keyfile=None,\n                    cafile=None, capath=None, cadata=None, **kw):\n        assert ssl, 'SSL not supported'\n        cafile = cafile or DEFAULT_CA_BUNDLE_PATH\n        if verify is True:\n            cert_reqs = ssl.CERT_REQUIRED\n            check_hostname = True\n        if isinstance(verify, str):\n            cert_reqs = ssl.CERT_REQUIRED\n            if os.path.isfile(verify):\n                cafile = verify\n            elif os.path.isdir(verify):\n                capath = verify\n        return ssl._create_unverified_context(cert_reqs=cert_reqs,\n                                              check_hostname=check_hostname,\n                                              certfile=certfile,\n                                              keyfile=keyfile,\n                                              cafile=cafile,\n                                              capath=capath,\n                                              cadata=cadata)",
    "docstring": "Create a SSL context object.\n\n        This method should not be called by from user code"
  },
  {
    "code": "def empty_wav(wav_path: Union[Path, str]) -> bool:\n    with wave.open(str(wav_path), 'rb') as wav_f:\n        return wav_f.getnframes() == 0",
    "docstring": "Check if a wav contains data"
  },
  {
    "code": "def set_general_setting(key, value, qsettings=None):\n    if not qsettings:\n        qsettings = QSettings()\n    qsettings.setValue(key, deep_convert_dict(value))",
    "docstring": "Set value to QSettings based on key.\n\n    :param key: Unique key for setting.\n    :type key: basestring\n\n    :param value: Value to be saved.\n    :type value: QVariant\n\n    :param qsettings: A custom QSettings to use. If it's not defined, it will\n        use the default one.\n    :type qsettings: qgis.PyQt.QtCore.QSettings"
  },
  {
    "code": "def range_to_numeric(ranges):\n    values, units = zip(*(r.split() for r in ranges))\n    unit = os.path.commonprefix([u[::-1] for u in units])\n    prefixes = (u[:-len(unit)] for u in units)\n    values = [float(v) * SI_PREFIX[p] for v, p in zip(values, prefixes)]\n    return values",
    "docstring": "Converts a sequence of string ranges to a sequence of floats.\n\n    E.g.::\n\n        >>> range_to_numeric(['1 uV', '2 mV', '1 V'])\n        [1E-6, 0.002, 1.0]"
  },
  {
    "code": "def photparse(tab):\n    if 'source_id' not in tab[0].keys():\n        raise KeyError('phot=TRUE requires the source_id columb be included')\n    uniqueid = []\n    for i in range(len(tab)):\n        tmpid = tab[i]['source_id']\n        if tmpid not in uniqueid:\n            uniqueid.append(tmpid)\n    newtab = []\n    for sourceid in uniqueid:\n        tmpdict = photaddline(tab, sourceid)\n        newtab.append(tmpdict)\n    return newtab",
    "docstring": "Parse through a photometry table to group by source_id\n\n    Parameters\n    ----------\n    tab: list\n      SQL query dictionary list from running query_dict.execute()\n\n    Returns\n    -------\n    newtab: list\n      Dictionary list after parsing to group together sources"
  },
  {
    "code": "def get_unique_scan_parameter_combinations(meta_data_array, scan_parameters=None, scan_parameter_columns_only=False):\n    try:\n        last_not_parameter_column = meta_data_array.dtype.names.index('error_code')\n    except ValueError:\n        last_not_parameter_column = meta_data_array.dtype.names.index('error')\n    if last_not_parameter_column == len(meta_data_array.dtype.names) - 1:\n        return\n    if scan_parameters is None:\n        return unique_row(meta_data_array, use_columns=range(4, len(meta_data_array.dtype.names)), selected_columns_only=scan_parameter_columns_only)\n    else:\n        use_columns = []\n        for scan_parameter in scan_parameters:\n            try:\n                use_columns.append(meta_data_array.dtype.names.index(scan_parameter))\n            except ValueError:\n                logging.error('No scan parameter ' + scan_parameter + ' found')\n                raise RuntimeError('Scan parameter not found')\n        return unique_row(meta_data_array, use_columns=use_columns, selected_columns_only=scan_parameter_columns_only)",
    "docstring": "Takes the numpy meta data array and returns the first rows with unique combinations of different scan parameter values for selected scan parameters.\n        If selected columns only is true, the returned histogram only contains the selected columns.\n\n    Parameters\n    ----------\n    meta_data_array : numpy.ndarray\n    scan_parameters : list of string, None\n        Scan parameter names taken. If None all are used.\n    selected_columns_only : bool\n\n    Returns\n    -------\n    numpy.Histogram"
  },
  {
    "code": "def command(command):\n    with cd(env.remote_path):\n        sudo(env.python + ' manage.py %s' % command, user=env.remote_user)",
    "docstring": "Run custom Django management command"
  },
  {
    "code": "def are_budget_data_package_fields_filled_in(self, resource):\n        fields = ['country', 'currency', 'year', 'status']\n        return all([self.in_resource(f, resource) for f in fields])",
    "docstring": "Check if the budget data package fields are all filled in because\n        if not then this can't be a budget data package"
  },
  {
    "code": "def load_data(self, filename, ext):\n        from spyder_kernels.utils.iofuncs import iofunctions\n        from spyder_kernels.utils.misc import fix_reference_name\n        glbs = self._mglobals()\n        load_func = iofunctions.load_funcs[ext]\n        data, error_message = load_func(filename)\n        if error_message:\n            return error_message\n        for key in list(data.keys()):\n            new_key = fix_reference_name(key, blacklist=list(glbs.keys()))\n            if new_key != key:\n                data[new_key] = data.pop(key)\n        try:\n            glbs.update(data)\n        except Exception as error:\n            return str(error)\n        return None",
    "docstring": "Load data from filename"
  },
  {
    "code": "def src_paths(self):\n        return {src for src, summary in self._diff_violations().items()\n                   if len(summary.measured_lines) > 0}",
    "docstring": "Return a list of source files in the diff\n        for which we have coverage information."
  },
  {
    "code": "def explain(self, expr, params=None):\n        if isinstance(expr, ir.Expr):\n            context = self.dialect.make_context(params=params)\n            query_ast = self._build_ast(expr, context)\n            if len(query_ast.queries) > 1:\n                raise Exception('Multi-query expression')\n            query = query_ast.queries[0].compile()\n        else:\n            query = expr\n        statement = 'EXPLAIN {0}'.format(query)\n        with self._execute(statement, results=True) as cur:\n            result = self._get_list(cur)\n        return 'Query:\\n{0}\\n\\n{1}'.format(\n            util.indent(query, 2), '\\n'.join(result)\n        )",
    "docstring": "Query for and return the query plan associated with the indicated\n        expression or SQL query.\n\n        Returns\n        -------\n        plan : string"
  },
  {
    "code": "def DEFINE_boolean(\n    name, default, help, flag_values=_flagvalues.FLAGS, module_name=None,\n    **args):\n  DEFINE_flag(_flag.BooleanFlag(name, default, help, **args),\n              flag_values, module_name)",
    "docstring": "Registers a boolean flag.\n\n  Such a boolean flag does not take an argument.  If a user wants to\n  specify a false value explicitly, the long option beginning with 'no'\n  must be used: i.e. --noflag\n\n  This flag will have a value of None, True or False.  None is possible\n  if default=None and the user does not specify the flag on the command\n  line.\n\n  Args:\n    name: str, the flag name.\n    default: bool|str|None, the default value of the flag.\n    help: str, the help message.\n    flag_values: FlagValues, the FlagValues instance with which the flag will\n        be registered. This should almost never need to be overridden.\n    module_name: str, the name of the Python module declaring this flag.\n        If not provided, it will be computed using the stack trace of this call.\n    **args: dict, the extra keyword args that are passed to Flag __init__."
  },
  {
    "code": "def upload_file(self, abspath, cloud_filename):\n        if not self.test_run:\n            content = open(abspath, \"rb\")\n            content_type = get_content_type(cloud_filename, content)\n            headers = get_headers(cloud_filename, content_type)\n            if headers.get(\"Content-Encoding\") == \"gzip\":\n                content = get_gzipped_contents(content)\n                size = content.size\n            else:\n                size = os.stat(abspath).st_size\n            self.container.create(\n                obj_name=cloud_filename,\n                data=content,\n                content_type=content_type,\n                content_length=size,\n                content_encoding=headers.get(\"Content-Encoding\", None),\n                headers=headers,\n                ttl=CUMULUS[\"FILE_TTL\"],\n                etag=None,\n            )\n        self.upload_count += 1\n        if not self.quiet or self.verbosity > 1:\n            print(\"Uploaded: {0}\".format(cloud_filename))",
    "docstring": "Uploads a file to the container."
  },
  {
    "code": "def GetIndex(self):\n        if self.index is None:\n            return None\n        if self.index:\n            res, ui = chmlib.chm_resolve_object(self.file, self.index)\n            if (res != chmlib.CHM_RESOLVE_SUCCESS):\n                return None\n        size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, ui.length)\n        if (size == 0):\n            sys.stderr.write('GetIndex: file size = 0\\n')\n            return None\n        return text",
    "docstring": "Reads and returns the index tree.\n        This auxiliary function reads and returns the index tree file\n        contents for the CHM archive."
  },
  {
    "code": "def info(ctx):\n    controller = ctx.obj['controller']\n    version = controller.version\n    click.echo(\n        'OATH version: {}.{}.{}'.format(version[0], version[1], version[2]))\n    click.echo('Password protection ' +\n               ('enabled' if controller.locked else 'disabled'))\n    keys = ctx.obj['settings'].get('keys', {})\n    if controller.locked and controller.id in keys:\n        click.echo('The password for this YubiKey is remembered by ykman.')\n    if ctx.obj['dev'].is_fips:\n        click.echo('FIPS Approved Mode: {}'.format(\n            'Yes' if controller.is_in_fips_mode else 'No'))",
    "docstring": "Display status of OATH application."
  },
  {
    "code": "def export_for_training(self, file_path='./export.json'):\n        import json\n        export = {'conversations': self._generate_export_data()}\n        with open(file_path, 'w+') as jsonfile:\n            json.dump(export, jsonfile, ensure_ascii=False)",
    "docstring": "Create a file from the database that can be used to\n        train other chat bots."
  },
  {
    "code": "def subtract(self,range2):\n    outranges = []\n    if self.chr != range2.chr:\n      outranges.append(self.copy())\n      return outranges\n    if not self.overlaps(range2):\n      outranges.append(self.copy())\n      return outranges\n    if range2.start <= self.start and range2.end >= self.end:\n      return outranges\n    if range2.start > self.start:\n      nrng = type(self)(self.chr,self.start+self._start_offset,range2.start-1,self.payload,self.dir)\n      outranges.append(nrng)\n    if range2.end < self.end:\n      nrng = type(self)(self.chr,range2.end+1+self._start_offset,self.end,self.payload,self.dir)\n      outranges.append(nrng)\n    return outranges",
    "docstring": "Take another range, and list of ranges after removing range2, keep options from self\n\n    :param range2:\n    :type range2: GenomicRange\n    :return: List of Genomic Ranges\n    :rtype: GenomicRange[]"
  },
  {
    "code": "async def close(self, *, force_after=30):\n        if self.transport:\n            self.transport.close()\n            try:\n                async with timeout_after(force_after):\n                    await self.closed_event.wait()\n            except TaskTimeout:\n                self.abort()\n                await self.closed_event.wait()",
    "docstring": "Close the connection and return when closed."
  },
  {
    "code": "def validate_contents(file_contents):\n    for name, contents in file_contents.items():\n        if os.path.splitext(name)[1] != '.ipynb':\n            continue\n        if not contents:\n            return False\n        try:\n            json_object = json.loads(contents)\n        except ValueError:\n            return False\n    return True",
    "docstring": "Ensures that all ipynb files in FILE_CONTENTS\n    are valid JSON files."
  },
  {
    "code": "def stop_actions(self):\n        self._stop_actions, value = self.get_attr_set(self._stop_actions, 'stop_actions')\n        return value",
    "docstring": "Gets a list of stop actions. Valid values are `coast`\n        and `brake`."
  },
  {
    "code": "def _gap(src_interval, tar_interval):\n        assert src_interval.bits == tar_interval.bits, \"Number of bits should be same for operands\"\n        s = src_interval\n        t = tar_interval\n        (_, b) = (s.lower_bound, s.upper_bound)\n        (c, _) = (t.lower_bound, t.upper_bound)\n        w = s.bits\n        if (not t._surrounds_member(b)) and (not s._surrounds_member(c)):\n            return StridedInterval(lower_bound=c, upper_bound=b, bits=w, stride=1).complement\n        return StridedInterval.empty(w)",
    "docstring": "Refer section 3.1; gap function.\n\n        :param src_interval: first argument or interval 1\n        :param tar_interval: second argument or interval 2\n        :return: Interval representing gap between two intervals"
  },
  {
    "code": "def calc_across_paths_textnodes(paths_nodes, dbg=False):\r\n    for path_nodes in paths_nodes:\r\n        cnt = len(path_nodes[1][0])\r\n        ttl = sum([len(s) for s in paths_nodes[1][0]])\n        path_nodes[1][1] = cnt\n        path_nodes[1][2] = ttl\n        path_nodes[1][3] = ttl/ cnt\n        if dbg:\r\n            print(path_nodes[1])",
    "docstring": "Given a list of parent paths tupled with children textnodes, plus\r\n    initialized feature values, we calculate the total and average string\r\n    length of the parent's children textnodes."
  },
  {
    "code": "def group(text, size):\n    if size <= 0:\n        raise ValueError(\"n must be a positive integer\")\n    return [text[i:i + size] for i in range(0, len(text), size)]",
    "docstring": "Group ``text`` into blocks of ``size``.\n\n    Example:\n        >>> group(\"test\", 2)\n        ['te', 'st']\n\n    Args:\n        text (str): text to separate\n        size (int): size of groups to split the text into\n\n    Returns:\n        List of n-sized groups of text\n\n    Raises:\n        ValueError: If n is non positive"
  },
  {
    "code": "def destroy(self):\n        if self._running is False:\n            return\n        self._running = False\n        if hasattr(self, 'schedule'):\n            del self.schedule\n        if hasattr(self, 'pub_channel') and self.pub_channel is not None:\n            self.pub_channel.on_recv(None)\n            if hasattr(self.pub_channel, 'close'):\n                self.pub_channel.close()\n            del self.pub_channel\n        if hasattr(self, 'periodic_callbacks'):\n            for cb in six.itervalues(self.periodic_callbacks):\n                cb.stop()",
    "docstring": "Tear down the minion"
  },
  {
    "code": "def pint_multiply(da, q, out_units=None):\n    a = 1 * units2pint(da)\n    f = a * q.to_base_units()\n    if out_units:\n        f = f.to(out_units)\n    out = da * f.magnitude\n    out.attrs['units'] = pint2cfunits(f.units)\n    return out",
    "docstring": "Multiply xarray.DataArray by pint.Quantity.\n\n    Parameters\n    ----------\n    da : xr.DataArray\n      Input array.\n    q : pint.Quantity\n      Multiplicating factor.\n    out_units : str\n      Units the output array should be converted into."
  },
  {
    "code": "def _to_dict(self):\n        physical_prop_names = find_PhysicalProperty(self)\n        physical_prop_vals = [getattr(self, prop) for prop in physical_prop_names]\n        return dict(zip(physical_prop_names, physical_prop_vals))",
    "docstring": "Return a dictionary representation of the current object."
  },
  {
    "code": "def category(**kwargs):\n    if 'series' in kwargs:\n        kwargs.pop('series')\n        path = 'series'\n    else:\n        path = None\n    return Fred().category(path, **kwargs)",
    "docstring": "Get a category."
  },
  {
    "code": "def add_dicts(*args):\n    counters = [Counter(arg) for arg in args]\n    return dict(reduce(operator.add, counters))",
    "docstring": "Adds two or more dicts together. Common keys will have their values added.\n\n    For example::\n\n        >>> t1 = {'a':1, 'b':2}\n        >>> t2 = {'b':1, 'c':3}\n        >>> t3 = {'d':4}\n\n        >>> add_dicts(t1, t2, t3)\n        {'a': 1, 'c': 3, 'b': 3, 'd': 4}"
  },
  {
    "code": "def rename_dimension(self, old_name, new_name):\n    if old_name not in self.dimension_names:\n      raise ValueError(\"Shape %s does not have dimension named %s\"\n                       % (self, old_name))\n    return Shape(\n        [Dimension(new_name, d.size) if d.name == old_name else d\n         for d in self.dims])",
    "docstring": "Returns a copy where one dimension is renamed."
  },
  {
    "code": "def _get_dst_resolution(self, dst_res=None):\n        if dst_res is None:\n            dst_res = min(self._res_indices.keys())\n        return dst_res",
    "docstring": "Get default resolution, i.e. the highest resolution or smallest cell size."
  },
  {
    "code": "def get_instance(self, payload):\n        return EventInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], )",
    "docstring": "Build an instance of EventInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.taskrouter.v1.workspace.event.EventInstance\n        :rtype: twilio.rest.taskrouter.v1.workspace.event.EventInstance"
  },
  {
    "code": "def _find_unchanged(old, new):\n    edges = []\n    old_edges = [set(edge) for edge in old.edges()]\n    new_edges = [set(edge) for edge in new.edges()]\n    for old_edge in old_edges:\n        if old_edge in new_edges:\n            edges.append(set(old_edge))\n    return edges",
    "docstring": "returns edges that are in both old and new"
  },
  {
    "code": "def hazard_extra_keyword(keyword, feature, parent):\n    _ = feature, parent\n    hazard_layer_path = QgsExpressionContextUtils. \\\n        projectScope(QgsProject.instance()).variable(\n          'hazard_layer')\n    hazard_layer = load_layer(hazard_layer_path)[0]\n    keywords = KeywordIO.read_keywords(hazard_layer)\n    extra_keywords = keywords.get('extra_keywords')\n    if extra_keywords:\n        value = extra_keywords.get(keyword)\n        if value:\n            value_definition = definition(value)\n            if value_definition:\n                return value_definition['name']\n            return value\n        else:\n            return tr('Keyword %s is not found' % keyword)\n    return tr('No extra keywords found')",
    "docstring": "Given a keyword, it will return the value of the keyword\n    from the hazard layer's extra keywords.\n\n    For instance:\n    *   hazard_extra_keyword( 'depth' ) -> will return the value of 'depth'\n        in current hazard layer's extra keywords."
  },
  {
    "code": "def parse(text, showToc=True):\n\tp = Parser(show_toc=showToc)\n\treturn p.parse(text)",
    "docstring": "Returns HTML from MediaWiki markup"
  },
  {
    "code": "def handle_request(self, environ, start_response):\n        urls = self.url_map.bind_to_environ(environ)\n        try:\n            endpoint, args = urls.match()\n            environ['pywb.app_prefix'] = environ.get('SCRIPT_NAME')\n            response = endpoint(environ, **args)\n            return response(environ, start_response)\n        except HTTPException as e:\n            redir = self._check_refer_redirect(environ)\n            if redir:\n                return redir(environ, start_response)\n            return e(environ, start_response)\n        except Exception as e:\n            if self.debug:\n                traceback.print_exc()\n            response = self.rewriterapp._error_response(environ, 'Internal Error: ' + str(e), '500 Server Error')\n            return response(environ, start_response)",
    "docstring": "Retrieves the route handler and calls the handler returning its the response\n\n        :param dict environ: The WSGI environment dictionary for the request\n        :param start_response:\n        :return: The WbResponse for the request\n        :rtype: WbResponse"
  },
  {
    "code": "def getLiteral(self):\n        chars = u''\n        c = self.current()\n        while True:\n            if c and c == u\"\\\\\":\n                c = self.next()\n                if c:\n                    chars += c\n                continue\n            elif not c or (c in self.meta_chars):\n                break\n            else:\n                chars += c\n            if self.lookahead() and self.lookahead() in self.meta_chars:\n                break\n            c = self.next()\n        return StringGenerator.Literal(chars)",
    "docstring": "Get a sequence of non-special characters."
  },
  {
    "code": "def dump(self, name: str, inst):\n        \"Save the object instance to the stash.\"\n        self.stash.dump(name, inst)",
    "docstring": "Save the object instance to the stash."
  },
  {
    "code": "def u8(self, name, value=None, align=None):\n        self.uint(1, name, value, align)",
    "docstring": "Add an unsigned 1 byte integer field to template.\n\n        This is an convenience method that simply calls `Uint` keyword with predefined length."
  },
  {
    "code": "def filter_thumbnail_files(chan_path, filenames, metadata_provider):\n    thumbnail_files_to_skip = metadata_provider.get_thumbnail_paths()\n    filenames_cleaned = []\n    for filename in filenames:\n        keep = True\n        chan_filepath = os.path.join(chan_path, filename)\n        chan_filepath_tuple = path_to_tuple(chan_filepath)\n        if chan_filepath_tuple in thumbnail_files_to_skip:\n            keep = False\n        if keep:\n            filenames_cleaned.append(filename)\n    return filenames_cleaned",
    "docstring": "We don't want to create `ContentNode` from thumbnail files."
  },
  {
    "code": "def deprecated_attr(namespace, attr, replacement):\n    _deprecated_attrs.setdefault(namespace, []).append((attr, replacement))",
    "docstring": "Marks a module level attribute as deprecated. Accessing it will emit\n    a PyGIDeprecationWarning warning.\n\n    e.g. for ``deprecated_attr(\"GObject\", \"STATUS_FOO\", \"GLib.Status.FOO\")``\n    accessing GObject.STATUS_FOO will emit:\n\n        \"GObject.STATUS_FOO is deprecated; use GLib.Status.FOO instead\"\n\n    :param str namespace:\n        The namespace of the override this is called in.\n    :param str namespace:\n        The attribute name (which gets added to __all__).\n    :param str replacement:\n        The replacement text which will be included in the warning."
  },
  {
    "code": "def debug_sql(sql: str, *args: Any) -> None:\n    log.debug(\"SQL: %s\" % sql)\n    if args:\n        log.debug(\"Args: %r\" % args)",
    "docstring": "Writes SQL and arguments to the log."
  },
  {
    "code": "def imagenet50(display=False, resolution=224):\n    prefix = github_data_url + \"imagenet50_\"\n    X = np.load(cache(prefix + \"%sx%s.npy\" % (resolution, resolution))).astype(np.float32)\n    y = np.loadtxt(cache(prefix + \"labels.csv\"))\n    return X, y",
    "docstring": "This is a set of 50 images representative of ImageNet images.\n\n    This dataset was collected by randomly finding a working ImageNet link and then pasting the\n    original ImageNet image into Google image search restricted to images licensed for reuse. A\n    similar image (now with rights to reuse) was downloaded as a rough replacment for the original\n    ImageNet image. The point is to have a random sample of ImageNet for use as a background\n    distribution for explaining models trained on ImageNet data.\n\n    Note that because the images are only rough replacements the labels might no longer be correct."
  },
  {
    "code": "def GetFormatterObject(cls, data_type):\n    data_type = data_type.lower()\n    if data_type not in cls._formatter_objects:\n      formatter_object = None\n      if data_type in cls._formatter_classes:\n        formatter_class = cls._formatter_classes[data_type]\n        formatter_object = formatter_class()\n      if not formatter_object:\n        logger.warning(\n            'Using default formatter for data type: {0:s}'.format(data_type))\n        formatter_object = default.DefaultFormatter()\n      cls._formatter_objects[data_type] = formatter_object\n    return cls._formatter_objects[data_type]",
    "docstring": "Retrieves the formatter object for a specific data type.\n\n    Args:\n      data_type (str): data type.\n\n    Returns:\n      EventFormatter: corresponding formatter or the default formatter if\n          not available."
  },
  {
    "code": "def jenkins_rao(target, throat_perimeter='throat.perimeter',\n                throat_area='throat.area',\n                throat_diameter='throat.indiameter'):\n    r\n    P = target[throat_perimeter]\n    A = target[throat_area]\n    r = target[throat_diameter]/2\n    value = (P/A)/(2/r)\n    return value",
    "docstring": "r\"\"\"\n    Jenkins and Rao relate the capillary pressure in an eliptical throat to\n    the aspect ratio\n\n    References\n    ----------\n    Jenkins, R.G. and Rao, M.B., The effect of elliptical pores on\n    mercury porosimetry results. Powder technology, 38(2), pp.177-180. (1984)"
  },
  {
    "code": "def _get_status_descr_by_id(status_id):\n    for status_name, status_data in six.iteritems(LINODE_STATUS):\n        if status_data['code'] == int(status_id):\n            return status_data['descr']\n    return LINODE_STATUS.get(status_id, None)",
    "docstring": "Return linode status by ID\n\n    status_id\n        linode VM status ID"
  },
  {
    "code": "def info(self):\n        info = []\n        for prior_model_name, prior_model in self.prior_model_tuples:\n            info.append(prior_model.name + '\\n')\n            info.extend([f\"{prior_model_name}_{item}\" for item in prior_model.info])\n        return '\\n'.join(info)",
    "docstring": "Use the priors that make up the model_mapper to generate information on each parameter of the overall model.\n\n        This information is extracted from each priors *model_info* property."
  },
  {
    "code": "def attribute_exists(self, name):\n        if name in self:\n            if issubclass(self[name].__class__, Attribute):\n                return True\n        return False",
    "docstring": "Returns if given attribute exists in the node.\n\n        Usage::\n\n            >>>\tnode_a = AbstractNode(\"MyNodeA\", attributeA=Attribute(), attributeB=Attribute())\n            >>> node_a.attribute_exists(\"attributeA\")\n            True\n            >>> node_a.attribute_exists(\"attributeC\")\n            False\n\n        :param name: Attribute name.\n        :type name: unicode\n        :return: Attribute exists.\n        :rtype: bool"
  },
  {
    "code": "def _get_node(self, node_id):\n        self.non_terminated_nodes({})\n        if node_id in self.cached_nodes:\n            return self.cached_nodes[node_id]\n        matches = list(self.ec2.instances.filter(InstanceIds=[node_id]))\n        assert len(matches) == 1, \"Invalid instance id {}\".format(node_id)\n        return matches[0]",
    "docstring": "Refresh and get info for this node, updating the cache."
  },
  {
    "code": "def find_specs(self, directory):\n        specs = []\n        spec_files = self.file_finder.find(directory)\n        for spec_file in spec_files:\n            specs.extend(self.spec_finder.find(spec_file.module))\n        return specs",
    "docstring": "Finds all specs in a given directory. Returns a list of\n        Example and ExampleGroup instances."
  },
  {
    "code": "def interface_direct_class(data_class):\n    if data_class in ASSET:\n        interface = AssetsInterface()\n    elif data_class in PARTY:\n        interface = PartiesInterface()\n    elif data_class in BOOK:\n        interface = BooksInterface()\n    elif data_class in CORPORATE_ACTION:\n        interface = CorporateActionsInterface()\n    elif data_class in MARKET_DATA:\n        interface = MarketDataInterface()\n    elif data_class in TRANSACTION:\n        interface = TransactionsInterface()\n    else:\n        interface = AssetManagersInterface()\n    return interface",
    "docstring": "help to direct to the correct interface interacting with DB by class name only"
  },
  {
    "code": "def get_xyz_2d(self, xcoord, x, ycoord, y, u, v):\n        xy = xcoord.values.ravel() + 1j * ycoord.values.ravel()\n        dist = np.abs(xy - (x + 1j * y))\n        imin = np.nanargmin(dist)\n        xy_min = xy[imin]\n        return (xy_min.real, xy_min.imag, u.values.ravel()[imin],\n                v.values.ravel()[imin])",
    "docstring": "Get closest x, y and z for the given `x` and `y` in `data` for\n        2d coords"
  },
  {
    "code": "def write_xml(self, xmlfile, config=None):\n        root = ElementTree.Element('source_library')\n        root.set('title', 'source_library')\n        for s in self._srcs:\n            s.write_xml(root)\n        if config is not None:\n            srcs = self.create_diffuse_srcs(config)\n            diffuse_srcs = {s.name: s for s in srcs}\n            for s in self._diffuse_srcs:\n                src = copy.deepcopy(diffuse_srcs.get(s.name, s))\n                src.update_spectral_pars(s.spectral_pars)\n                src.write_xml(root)\n        else:\n            for s in self._diffuse_srcs:\n                s.write_xml(root)\n        output_file = open(xmlfile, 'w')\n        output_file.write(utils.prettify_xml(root))",
    "docstring": "Save the ROI model as an XML file."
  },
  {
    "code": "def change_to_workdir(self):\n        logger.info(\"Changing working directory to: %s\", self.workdir)\n        self.check_dir(self.workdir)\n        try:\n            os.chdir(self.workdir)\n        except OSError as exp:\n            self.exit_on_error(\"Error changing to working directory: %s. Error: %s. \"\n                               \"Check the existence of %s and the %s/%s account \"\n                               \"permissions on this directory.\"\n                               % (self.workdir, str(exp), self.workdir, self.user, self.group),\n                               exit_code=3)\n        self.pre_log.append((\"INFO\", \"Using working directory: %s\" % os.path.abspath(self.workdir)))",
    "docstring": "Change working directory to working attribute\n\n        :return: None"
  },
  {
    "code": "def convert_html_to_xml(self):\n        if hasattr(self, 'content') and self.content != '':\n            regex = r'<(?!/)(?!!)'\n            xml_content = re.sub(regex, '<xhtml:', self.content)\n            return xml_content\n        else:\n            return ''",
    "docstring": "Parses the HTML parsed texts and converts its tags to XML valid tags.\n\n        :returns: HTML enabled text in a XML valid format.\n        :rtype: str"
  },
  {
    "code": "def save(self, fname: str):\n        mx.nd.save(fname, self.source + self.target + self.label)",
    "docstring": "Saves the dataset to a binary .npy file."
  },
  {
    "code": "def get_local_roles_for(brain_or_object, user=None):\n    user_id = get_user_id(user)\n    obj = api.get_object(brain_or_object)\n    return sorted(obj.get_local_roles_for_userid(user_id))",
    "docstring": "Get the local defined roles on the context\n\n    Code extracted from `IRoleManager.get_local_roles_for_userid`\n\n    :param brain_or_object: Catalog brain or object\n    :param user: A user ID, user object or None (for the current user)\n    :returns: List of granted local roles on the given object"
  },
  {
    "code": "def maybe_transactional(func):\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        commit = kwargs.get(\"commit\", True)\n        with transaction(commit=commit):\n            return func(*args, **kwargs)\n    return wrapper",
    "docstring": "Variant of `transactional` that will not commit if there's an argument `commit` with a falsey value.\n\n    Useful for dry-run style operations."
  },
  {
    "code": "def random_integers(cls, size, seed=None):\n        if seed is None:\n            seed = abs(hash(\"%0.20f\" % time.time())) % (2 ** 31)\n        return cls.from_sequence(size).hash(seed)",
    "docstring": "Returns an SArray with random integer values."
  },
  {
    "code": "def _ord_to_str(ordinal, weights):\n  chars = []\n  for weight in weights:\n    if ordinal == 0:\n      return \"\".join(chars)\n    ordinal -= 1\n    index, ordinal = divmod(ordinal, weight)\n    chars.append(_ALPHABET[index])\n  return \"\".join(chars)",
    "docstring": "Reverse function of _str_to_ord."
  },
  {
    "code": "def _get_driver(driver_type):\n    if driver_type == 'phantomjs':\n        return webdriver.PhantomJS(service_log_path=os.path.devnull)\n    if driver_type == 'firefox':\n        return webdriver.Firefox(firefox_options=FIREFOXOPTIONS)\n    elif driver_type == 'chrome':\n        chrome_options = webdriver.ChromeOptions()\n        for arg in CHROME_WEBDRIVER_ARGS:\n            chrome_options.add_argument(arg)\n        return webdriver.Chrome(chrome_options=chrome_options)\n    else:\n        raise USPSError('{} not supported'.format(driver_type))",
    "docstring": "Get webdriver."
  },
  {
    "code": "def show_form_for_method(self, view, method, request, obj):\n        if method not in view.allowed_methods:\n            return\n        try:\n            view.check_permissions(request)\n            if obj is not None:\n                view.check_object_permissions(request, obj)\n        except exceptions.APIException:\n            return False\n        return True",
    "docstring": "Returns True if a form should be shown for this method."
  },
  {
    "code": "def getUTC(self, utcoffset):\n        newTime = (self.value - utcoffset.value) % 24\n        return Time(newTime)",
    "docstring": "Returns a new Time object set to UTC given \n        an offset Time object."
  },
  {
    "code": "def custom_server_error(request, template_name='500.html', admin_template_name='500A.html'):\n    trace = None\n    if request.user.is_authenticated() and (request.user.is_staff or request.user.is_superuser):\n        try:\n            import traceback, sys\n            trace = traceback.format_exception(*(sys.exc_info()))\n            if not request.user.is_superuser and trace:\n                trace = trace[-1:]\n            trace = '\\n'.join(trace)\n        except:\n            pass\n    if request.path.startswith('/%s' % admin.site.name):\n        template_name = admin_template_name\n    t = loader.get_template(template_name)\n    return http.HttpResponseServerError(t.render(Context({'trace': trace})))",
    "docstring": "500 error handler. Displays a full trackback for superusers and the first line of the\n    traceback for staff members.\n\n    Templates: `500.html` or `500A.html` (admin)\n    Context: trace\n        Holds the traceback information for debugging."
  },
  {
    "code": "def _option(value):\n    if value in __opts__:\n        return __opts__[value]\n    master_opts = __pillar__.get('master', {})\n    if value in master_opts:\n        return master_opts[value]\n    if value in __pillar__:\n        return __pillar__[value]",
    "docstring": "Look up the value for an option."
  },
  {
    "code": "def value(self, value):\n        try:\n            struct.pack('>' + conf.TYPE_CHAR, value)\n        except struct.error:\n            raise IllegalDataValueError\n        self._value = value",
    "docstring": "Value to be written on register.\n\n        :param value: An integer.\n        :raises: IllegalDataValueError when value isn't in range."
  },
  {
    "code": "def visit_object(self, node):\n        if current_app.debug:\n            return tags.comment('no implementation in {} to render {}'.format(\n                self.__class__.__name__,\n                node.__class__.__name__, ))\n        return ''",
    "docstring": "Fallback rendering for objects.\n\n        If the current application is in debug-mode\n        (``flask.current_app.debug`` is ``True``), an ``<!-- HTML comment\n        -->`` will be rendered, indicating which class is missing a visitation\n        function.\n\n        Outside of debug-mode, returns an empty string."
  },
  {
    "code": "def image_tasks(self):\n        uri = \"/%s/tasks\" % self.uri_base\n        resp, resp_body = self.api.method_get(uri)\n        return resp_body",
    "docstring": "Returns a json-schema document that represents a container of tasks\n        entities."
  },
  {
    "code": "def read(config_values):\n    if not config_values:\n        raise RheaError('Cannot read config_value: `{}`'.format(config_values))\n    config_values = to_list(config_values)\n    config = {}\n    for config_value in config_values:\n        config_value = ConfigSpec.get_from(value=config_value)\n        config_value.check_type()\n        config_results = config_value.read()\n        if config_results and isinstance(config_results, Mapping):\n            config = deep_update(config, config_results)\n        elif config_value.check_if_exists:\n            raise RheaError('Cannot read config_value: `{}`'.format(config_value))\n    return config",
    "docstring": "Reads an ordered list of configuration values and deep merge the values in reverse order."
  },
  {
    "code": "def proportional_weights(self, fraction_stdev=1.0, wmax=100.0,\n                             leave_zero=True):\n        new_weights = []\n        for oval, ow in zip(self.observation_data.obsval,\n                            self.observation_data.weight):\n            if leave_zero and ow == 0.0:\n                ow = 0.0\n            elif oval == 0.0:\n                ow = wmax\n            else:\n                nw = 1.0 / (np.abs(oval) * fraction_stdev)\n                ow = min(wmax, nw)\n            new_weights.append(ow)\n        self.observation_data.weight = new_weights",
    "docstring": "setup  weights inversely proportional to the observation value\n\n        Parameters\n        ----------\n        fraction_stdev : float\n            the fraction portion of the observation\n            val to treat as the standard deviation.  set to 1.0 for\n            inversely proportional\n        wmax : float\n            maximum weight to allow\n        leave_zero : bool\n            flag to leave existing zero weights"
  },
  {
    "code": "def add_resources_to_registry():\n    from deform.widget import default_resource_registry\n    default_resource_registry.set_js_resources(\"jqueryui\", None, None)\n    default_resource_registry.set_js_resources(\"datetimepicker\", None, None)\n    default_resource_registry.set_js_resources(\"custom_dates\", None, None)\n    default_resource_registry.set_js_resources(\n        \"radio_choice_toggle\", None, None\n    )\n    default_resource_registry.set_js_resources(\"checkbox_toggle\", None, None)\n    from js.deform import resource_mapping\n    from js.select2 import select2\n    resource_mapping['select2'] = select2\n    from js.jquery_timepicker_addon import timepicker\n    resource_mapping['datetimepicker'] = timepicker\n    resource_mapping['custom_dates'] = custom_dates\n    resource_mapping['radio_choice_toggle'] = radio_choice_toggle\n    resource_mapping['checkbox_toggle'] = checkbox_toggle",
    "docstring": "Add resources to the deform registry"
  },
  {
    "code": "def _get_user(self, user: Union[User, str]) -> User:\n        user_id: str = getattr(user, 'user_id', user)\n        discovery_room = self._global_rooms.get(\n            make_room_alias(self.network_id, DISCOVERY_DEFAULT_ROOM),\n        )\n        if discovery_room and user_id in discovery_room._members:\n            duser = discovery_room._members[user_id]\n            if getattr(user, 'displayname', None):\n                assert isinstance(user, User)\n                duser.displayname = user.displayname\n            user = duser\n        elif not isinstance(user, User):\n            user = self._client.get_user(user_id)\n        return user",
    "docstring": "Creates an User from an user_id, if none, or fetch a cached User\n\n        As all users are supposed to be in discovery room, its members dict is used for caching"
  },
  {
    "code": "def file_md5(f, size=8192):\n    \"Calculates the MD5 of a file.\"\n    md5 = hashlib.md5()\n    while True:\n        data = f.read(size)\n        if not data:\n            break\n        md5.update(data)\n    return md5.hexdigest()",
    "docstring": "Calculates the MD5 of a file."
  },
  {
    "code": "def add_output_variable(self, var):\n        assert(isinstance(var, Variable))\n        self.output_variable_list.append(var)",
    "docstring": "Adds the argument variable as one of the output variable"
  },
  {
    "code": "def decode(dct, intype='json', raise_error=False):\n    for decoder in get_plugins('decoders').values():\n        if (set(list(decoder.dict_signature)).issubset(dct.keys())\n            and hasattr(decoder, 'from_{}'.format(intype))\n                and getattr(decoder, 'allow_other_keys', False)):\n            return getattr(decoder, 'from_{}'.format(intype))(dct)\n            break\n        elif (sorted(list(decoder.dict_signature)) == sorted(dct.keys())\n              and hasattr(decoder, 'from_{}'.format(intype))):\n            return getattr(decoder, 'from_{}'.format(intype))(dct)\n            break\n    if raise_error:\n        raise ValueError('no suitable plugin found for: {}'.format(dct))\n    else:\n        return dct",
    "docstring": "decode dict objects, via decoder plugins, to new type\n\n    Parameters\n    ----------\n    intype: str\n        use decoder method from_<intype> to encode\n    raise_error : bool\n        if True, raise ValueError if no suitable plugin found\n\n    Examples\n    --------\n    >>> load_builtin_plugins('decoders')\n    []\n\n    >>> from decimal import Decimal\n    >>> decode({'_python_Decimal_':'1.3425345'})\n    Decimal('1.3425345')\n\n    >>> unload_all_plugins()"
  },
  {
    "code": "def find_sink_variables(self):\n        is_sink = {name: True for name in self.variables.keys()}\n        for operator in self.operators.values():\n            for variable in operator.inputs:\n                is_sink[variable.onnx_name] = False\n        return [variable for name, variable in self.variables.items() if is_sink[name]]",
    "docstring": "Find sink variables in this scope"
  },
  {
    "code": "def uploads(self):\n        if self.syncEnabled == True:\n            return Uploads(url=self._url + \"/uploads\",\n                           securityHandler=self._securityHandler,\n                           proxy_url=self._proxy_url,\n                           proxy_port=self._proxy_port)\n        return None",
    "docstring": "returns the class to perform the upload function.  it will\n        only return the uploads class if syncEnabled is True."
  },
  {
    "code": "def _decoder(image, shrink):\n    decoder = dmtxDecodeCreate(image, shrink)\n    if not decoder:\n        raise PyLibDMTXError('Could not create decoder')\n    else:\n        try:\n            yield decoder\n        finally:\n            dmtxDecodeDestroy(byref(decoder))",
    "docstring": "A context manager for `DmtxDecode`, created and destroyed by\n    `dmtxDecodeCreate` and `dmtxDecodeDestroy`.\n\n    Args:\n        image (POINTER(DmtxImage)):\n        shrink (int):\n\n    Yields:\n        POINTER(DmtxDecode): The created decoder\n\n    Raises:\n        PyLibDMTXError: If the decoder could not be created."
  },
  {
    "code": "def _ParseSignatureIdentifiers(self, data_location, signature_identifiers):\n    if not signature_identifiers:\n      return\n    if not data_location:\n      raise ValueError('Missing data location.')\n    path = os.path.join(data_location, 'signatures.conf')\n    if not os.path.exists(path):\n      raise IOError(\n          'No such format specification file: {0:s}'.format(path))\n    try:\n      specification_store = self._ReadSpecificationFile(path)\n    except IOError as exception:\n      raise IOError((\n          'Unable to read format specification file: {0:s} with error: '\n          '{1!s}').format(path, exception))\n    signature_identifiers = signature_identifiers.lower()\n    signature_identifiers = [\n        identifier.strip() for identifier in signature_identifiers.split(',')]\n    file_entry_filter = file_entry_filters.SignaturesFileEntryFilter(\n        specification_store, signature_identifiers)\n    self._filter_collection.AddFilter(file_entry_filter)",
    "docstring": "Parses the signature identifiers.\n\n    Args:\n      data_location (str): location of the format specification file, for\n          example, \"signatures.conf\".\n      signature_identifiers (str): comma separated signature identifiers.\n\n    Raises:\n      IOError: if the format specification file could not be read from\n          the specified data location.\n      OSError: if the format specification file could not be read from\n          the specified data location.\n      ValueError: if no data location was specified."
  },
  {
    "code": "def dumps(self, bucket=None):\n        return [\n            self.file_cls(o, self.filesmap.get(o.key, {})).dumps()\n            for o in sorted_files_from_bucket(bucket or self.bucket, self.keys)\n        ]",
    "docstring": "Serialize files from a bucket.\n\n        :param bucket: Instance of files\n            :class:`invenio_files_rest.models.Bucket`. (Default:\n            ``self.bucket``)\n        :returns: List of serialized files."
  },
  {
    "code": "def centroid(X):\n    C = np.sum(X, axis=0) / len(X)\n    return C",
    "docstring": "Calculate the centroid from a matrix X"
  },
  {
    "code": "def _compile_rules(self):\n        for state, table in self.RULES.items():\n            patterns = list()\n            actions = list()\n            nextstates = list()\n            for i, row in enumerate(table):\n                if len(row) == 2:\n                    pattern, _action = row\n                    nextstate = None\n                elif len(row) == 3:\n                    pattern, _action, nextstate = row\n                else:\n                    fstr = \"invalid RULES: state {}, row {}\"\n                    raise CompileError(fstr.format(state, i))\n                patterns.append(pattern)\n                actions.append(_action)\n                nextstates.append(nextstate)\n            reobj = re.compile('|'.join(\"(\" + p + \")\" for p in patterns))\n            self._rules[state] = (reobj, actions, nextstates)",
    "docstring": "Compile the rules into the internal lexer state."
  },
  {
    "code": "def _store_credentials(self, username, password, remember=False):\n        if username and password and remember:\n            CONF.set('main', 'report_error/username', username)\n            try:\n                keyring.set_password('github', username, password)\n            except Exception:\n                if self._show_msgbox:\n                    QMessageBox.warning(self.parent_widget,\n                                        _('Failed to store password'),\n                                        _('It was not possible to securely '\n                                          'save your password. You will be '\n                                          'prompted for your Github '\n                                          'credentials next time you want '\n                                          'to report an issue.'))\n                remember = False\n        CONF.set('main', 'report_error/remember_me', remember)",
    "docstring": "Store credentials for future use."
  },
  {
    "code": "def update(self, new_email_address, name, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False):\n        validate_consent_to_track(consent_to_track)\n        params = {\"email\": self.email_address}\n        body = {\n            \"EmailAddress\": new_email_address,\n            \"Name\": name,\n            \"CustomFields\": custom_fields,\n            \"Resubscribe\": resubscribe,\n            \"ConsentToTrack\": consent_to_track,\n            \"RestartSubscriptionBasedAutoresponders\": restart_subscription_based_autoresponders}\n        response = self._put(\"/subscribers/%s.json\" % self.list_id,\n                             body=json.dumps(body), params=params)\n        self.email_address = new_email_address",
    "docstring": "Updates any aspect of a subscriber, including email address, name, and\n        custom field data if supplied."
  },
  {
    "code": "def get_groups(self):\n        def process_result(result):\n            return [self.get_group(group) for group in result]\n        return Command('get', [ROOT_GROUPS], process_result=process_result)",
    "docstring": "Return the groups linked to the gateway.\n\n        Returns a Command."
  },
  {
    "code": "def update_type_lookups(self):\n        self.type_to_typestring = dict(zip(self.types,\n                                           self.python_type_strings))\n        self.typestring_to_type = dict(zip(self.python_type_strings,\n                                           self.types))",
    "docstring": "Update type and typestring lookup dicts.\n\n        Must be called once the ``types`` and ``python_type_strings``\n        attributes are set so that ``type_to_typestring`` and\n        ``typestring_to_type`` are constructed.\n\n        .. versionadded:: 0.2\n\n        Notes\n        -----\n        Subclasses need to call this function explicitly."
  },
  {
    "code": "def _read_opt_ilnp(self, code, *, desc):\n        _type = self._read_opt_type(code)\n        _size = self._read_unpack(1)\n        _nval = self._read_fileng(_size)\n        opt = dict(\n            desc=desc,\n            type=_type,\n            length=_size + 2,\n            value=_nval,\n        )\n        return opt",
    "docstring": "Read HOPOPT ILNP Nonce option.\n\n        Structure of HOPOPT ILNP Nonce option [RFC 6744]:\n             0                   1                   2                   3\n             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            | Next Header   | Hdr Ext Len   |  Option Type  | Option Length |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            /                         Nonce Value                           /\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n            Octets      Bits        Name                        Description\n              0           0     hopopt.ilnp.type            Option Type\n              0           0     hopopt.ilnp.type.value      Option Number\n              0           0     hopopt.ilnp.type.action     Action (10)\n              0           2     hopopt.ilnp.type.change     Change Flag (0)\n              1           8     hopopt.ilnp.length          Length of Option Data\n              2          16     hopopt.ilnp.value           Nonce Value"
  },
  {
    "code": "def normalize_json(template):\n    obj = parse_cloudformation_template(template)\n    json_str = json.dumps(\n        obj, sort_keys=True, indent=4, default=str, separators=(',', ': '),\n    )\n    result = []\n    lines = json_str.split(\"\\n\")\n    for line in lines:\n        result.append(line + \"\\n\")\n    return result",
    "docstring": "Normalize our template for diffing.\n\n    Args:\n        template(str): string representing the template\n\n    Returns:\n        list: json representation of the parameters"
  },
  {
    "code": "def group_members(self, group_id, include_orphans=False):\n        params = {'includeOrphans': str(include_orphans).lower()}\n        url = self._service_url(['triggers', 'groups', group_id, 'members'], params=params)\n        return Trigger.list_to_object_list(self._get(url))",
    "docstring": "Find all group member trigger definitions\n\n        :param group_id: group trigger id\n        :param include_orphans: If True, include orphan members\n        :return: list of asociated group members as trigger objects"
  },
  {
    "code": "def create_html(api_key, attrs):\n    gif = get_gif(api_key, attrs['gif_id'])\n    if 'alt' not in attrs.keys():\n        attrs['alt'] = 'source: {}'.format(gif['data']['source'])\n    html_out = '<a href=\"{}\">'.format(gif['data']['url'])\n    html_out += '<img src=\"{}\" alt=\"{}\">'.format(\n        gif['data']['images']['original']['url'],\n        attrs['alt'])\n    html_out += '</a>'\n    return html_out",
    "docstring": "Returns complete html tag string."
  },
  {
    "code": "def run_async(**kwargs):\n    r = init_runner(**kwargs)\n    runner_thread = threading.Thread(target=r.run)\n    runner_thread.start()\n    return runner_thread, r",
    "docstring": "Runs an Ansible Runner task in the background which will start immediately. Returns the thread object and a Runner object.\n\n    This uses the same parameters as :py:func:`ansible_runner.interface.run`\n\n    :returns: A tuple containing a :py:class:`threading.Thread` object and a :py:class:`ansible_runner.runner.Runner` object"
  },
  {
    "code": "def transceive(self, data, timeout=None):\n        log.debug(\">> {0}\".format(hexlify(data)))\n        data = self._dep.exchange(data, timeout)\n        log.debug(\"<< {0}\".format(hexlify(data) if data else \"None\"))\n        return data",
    "docstring": "Transmit arbitrary data and receive the response.\n\n        This is a low level method to send arbitrary data to the\n        tag. While it should almost always be better to use\n        :meth:`send_apdu` this is the only way to force a specific\n        timeout value (which is otherwise derived from the Tag's\n        answer to select). The *timeout* value is expected as a float\n        specifying the seconds to wait."
  },
  {
    "code": "def convert_to_mb(s):\n    s = s.upper()\n    try:\n        if s.endswith('G'):\n            return float(s[:-1].strip()) * 1024\n        elif s.endswith('T'):\n            return float(s[:-1].strip()) * 1024 * 1024\n        else:\n            return float(s[:-1].strip())\n    except (IndexError, ValueError, KeyError, TypeError):\n        errmsg = (\"Invalid memory format: %s\") % s\n        raise exception.SDKInternalError(msg=errmsg)",
    "docstring": "Convert memory size from GB to MB."
  },
  {
    "code": "def load_distant(self):\n        print(\"Loading distant Zotero data...\")\n        self._references = self.get_references()\n        self.reference_types = self.get_reference_types()\n        self.reference_templates = self.get_reference_templates(self.reference_types)\n        print(\"Distant Zotero data loaded.\")\n        self.cache()",
    "docstring": "Load the distant Zotero data."
  },
  {
    "code": "def extract_audio(filename, channels=1, rate=16000):\n    temp = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)\n    if not os.path.isfile(filename):\n        print(\"The given file does not exist: {}\".format(filename))\n        raise Exception(\"Invalid filepath: {}\".format(filename))\n    if not which(\"ffmpeg\"):\n        print(\"ffmpeg: Executable not found on machine.\")\n        raise Exception(\"Dependency not found: ffmpeg\")\n    command = [\"ffmpeg\", \"-y\", \"-i\", filename,\n               \"-ac\", str(channels), \"-ar\", str(rate),\n               \"-loglevel\", \"error\", temp.name]\n    use_shell = True if os.name == \"nt\" else False\n    subprocess.check_output(command, stdin=open(os.devnull), shell=use_shell)\n    return temp.name, rate",
    "docstring": "Extract audio from an input file to a temporary WAV file."
  },
  {
    "code": "def on_any_event(self, event):\n        for delegate in self.delegates:\n            if hasattr(delegate, \"on_any_event\"):\n                delegate.on_any_event(event)",
    "docstring": "On any event method"
  },
  {
    "code": "def processing_blocks(self):\n        sbi_ids = Subarray(self.get_name()).sbi_ids\n        pbs = []\n        for sbi_id in sbi_ids:\n            sbi = SchedulingBlockInstance(sbi_id)\n            pbs.append(sbi.processing_block_ids)\n        return 'PB', pbs",
    "docstring": "Return list of PBs associated with the subarray.\n\n        <http://www.esrf.eu/computing/cs/tango/pytango/v920/server_api/server.html#PyTango.server.pipe>"
  },
  {
    "code": "def write (self, s):\n        if isinstance(s, bytes):\n            s = self._decode(s)\n        for c in s:\n            self.process(c)",
    "docstring": "Process text, writing it to the virtual screen while handling\n        ANSI escape codes."
  },
  {
    "code": "def _get_service_config(self):\n        if not os.path.exists(self.config_path):\n            try:\n                os.makedirs(os.path.dirname(self.config_path))\n            except OSError as exc:\n                if exc.errno != errno.EEXIST:\n                    raise\n            return {}\n        with open(self.config_path, 'r') as data:\n            return json.load(data)",
    "docstring": "Reads in config file of UAA credential information\n        or generates one as a side-effect if not yet\n        initialized."
  },
  {
    "code": "def transform_e1e2(x, y, e1, e2, center_x=0, center_y=0):\n    x_shift = x - center_x\n    y_shift = y - center_y\n    x_ = (1-e1) * x_shift - e2 * y_shift\n    y_ = -e2 * x_shift + (1 + e1) * y_shift\n    det = np.sqrt((1-e1)*(1+e1) + e2**2)\n    return x_ / det, y_ / det",
    "docstring": "maps the coordinates x, y with eccentricities e1 e2 into a new elliptical coordiante system\n\n    :param x:\n    :param y:\n    :param e1:\n    :param e2:\n    :param center_x:\n    :param center_y:\n    :return:"
  },
  {
    "code": "def parse_string(self):\n        word = ''\n        if self.prior_delim:\n            delim = self.prior_delim\n            self.prior_delim = None\n        else:\n            delim = self.char\n            word += self.char\n            self.update_chars()\n        while True:\n            if self.char == delim:\n                self.update_chars()\n                if self.char == delim:\n                    word += 2 * delim\n                    self.update_chars()\n                else:\n                    word += delim\n                    break\n            elif self.char == '\\n':\n                self.prior_delim = delim\n                break\n            else:\n                word += self.char\n                self.update_chars()\n        return word",
    "docstring": "Tokenize a Fortran string."
  },
  {
    "code": "def prepare_read(data, method='readlines', mode='r'):\n    if hasattr(data, 'readlines'):\n        data = getattr(data, method)()\n    elif isinstance(data, list):\n        if method == 'read':\n            return ''.join(data)\n    elif isinstance(data, basestring):\n        data = getattr(open(data, mode), method)()\n    else:\n        raise TypeError('Unable to handle data of type %r' % type(data))\n    return data",
    "docstring": "Prepare various input types for parsing.\n\n    Args:\n        data (iter): Data to read\n        method (str): Method to process data with\n        mode (str): Custom mode to process with, if data is a file\n\n    Returns:\n        list: List suitable for parsing\n\n    Raises:\n        TypeError: Invalid value for data"
  },
  {
    "code": "def set_log_block_num(self, bl):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('CL record not yet initialized!')\n        self.child_log_block_num = bl",
    "docstring": "Set the logical block number for the child.\n\n        Parameters:\n         bl - Logical block number of the child.\n        Returns:\n         Nothing."
  },
  {
    "code": "def get_access_token(self):\n        if self.is_access_token_expired():\n            if is_debug_enabled():\n                debug('requesting new access_token')\n            token = get_access_token(username=self.username,\n                                     password=self.password,\n                                     client_id=self.client_id,\n                                     client_secret=self.client_secret,\n                                     app_url=self.app_url)\n            self.expires_at = time.time() + token['expires_in']/2\n            self.access_token = token['access_token']\n        return self.access_token",
    "docstring": "get a valid access token"
  },
  {
    "code": "def match(self, device):\n        return all(match_value(getattr(device, k), v)\n                   for k, v in self._match.items())",
    "docstring": "Check if the device object matches this filter."
  },
  {
    "code": "def threaded_start(self, no_init=False):\n        thread = Thread(target=self.init_connections, kwargs={\n                        'no_init': no_init})\n        thread.setDaemon(True)\n        thread.start()\n        thread.join()",
    "docstring": "Spawns a worker thread to set up the zookeeper connection"
  },
  {
    "code": "def write(self, destination, filename, template_name, **kwargs):\n        template = self.env.get_template(template_name)\n        content = template.render(kwargs)\n        super(TemplateFileWriter, self).write(destination=destination, filename=filename, content=content)",
    "docstring": "Write a file according to the template name\n\n            Args:\n                destination (string): the destination location\n                filename (string): the filename that will be written\n                template_name (string): the name of the template\n                kwargs (dict): all attribute that will be passed to the template"
  },
  {
    "code": "def _effective_perm_list_from_iter(self, perm_iter):\n        highest_perm_str = self._highest_perm_from_iter(perm_iter)\n        return (\n            self._equal_or_lower_perm_list(highest_perm_str)\n            if highest_perm_str is not None\n            else None\n        )",
    "docstring": "Return list of effective permissions for for highest permission in\n        ``perm_iter``, ordered lower to higher, or None if ``perm_iter`` is empty."
  },
  {
    "code": "def _get_block_publisher(self, state_hash):\n        state_view = self._state_view_factory.create_view(state_hash)\n        try:\n            class BatchPublisher:\n                def send(self, transactions):\n                    raise InvalidGenesisConsensusError(\n                        'Consensus cannot send transactions during genesis.')\n            consensus = ConsensusFactory.get_configured_consensus_module(\n                NULL_BLOCK_IDENTIFIER,\n                state_view)\n            return consensus.BlockPublisher(\n                BlockCache(self._block_store),\n                state_view_factory=self._state_view_factory,\n                batch_publisher=BatchPublisher(),\n                data_dir=self._data_dir,\n                config_dir=self._config_dir,\n                validator_id=self._identity_signer.get_public_key().as_hex())\n        except UnknownConsensusModuleError as e:\n            raise InvalidGenesisStateError(e)",
    "docstring": "Returns the block publisher based on the consensus module set by the\n        \"sawtooth_settings\" transaction family.\n\n        Args:\n            state_hash (str): The current state root hash for reading settings.\n\n        Raises:\n            InvalidGenesisStateError: if any errors occur getting the\n                BlockPublisher."
  },
  {
    "code": "def unlock(self, password: str):\n        if self.locked:\n            self._privkey = decode_keyfile_json(self.keystore, password.encode('UTF-8'))\n            self.locked = False\n            self._fill_address()",
    "docstring": "Unlock the account with a password.\n\n        If the account is already unlocked, nothing happens, even if the password is wrong.\n\n        Raises:\n            ValueError: (originating in ethereum.keys) if the password is wrong\n            (and the account is locked)"
  },
  {
    "code": "def hybrid_meco_frequency(m1, m2, chi1, chi2, qm1=None, qm2=None):\n    if qm1 is None:\n        qm1 = 1\n    if qm2 is None:\n        qm2 = 1\n    return velocity_to_frequency(hybrid_meco_velocity(m1, m2, chi1, chi2, qm1, qm2), m1 + m2)",
    "docstring": "Return the frequency of the hybrid MECO\n\n    Parameters\n    ----------\n    m1 : float\n        Mass of the primary object in solar masses.\n    m2 : float\n        Mass of the secondary object in solar masses.\n    chi1: float\n        Dimensionless spin of the primary object.\n    chi2: float\n        Dimensionless spin of the secondary object.\n    qm1: {None, float}, optional\n        Quadrupole-monopole term of the primary object (1 for black holes).\n        If None, will be set to qm1 = 1.\n    qm2: {None, float}, optional\n        Quadrupole-monopole term of the secondary object (1 for black holes).\n        If None, will be set to qm2 = 1.\n\n    Returns\n    -------\n    f: float\n        The frequency (in Hz) of the hybrid MECO"
  },
  {
    "code": "def write_tex():\n    datadir = livvkit.index_dir\n    outdir = os.path.join(datadir, \"tex\")\n    print(outdir)\n    data_files = glob.glob(datadir + \"/**/*.json\", recursive=True)\n    for each in data_files:\n        data = functions.read_json(each)\n        tex = translate_page(data)\n        outfile = os.path.join(outdir, os.path.basename(each).replace('json', 'tex'))\n        with open(outfile, 'w') as f:\n            f.write(tex)",
    "docstring": "Finds all of the output data files, and writes them out to .tex"
  },
  {
    "code": "def parse_tibiadata_datetime(date_dict) -> Optional[datetime.datetime]:\n    try:\n        t = datetime.datetime.strptime(date_dict[\"date\"], \"%Y-%m-%d %H:%M:%S.%f\")\n    except (KeyError, ValueError, TypeError):\n        return None\n    if date_dict[\"timezone\"] == \"CET\":\n        timezone_offset = 1\n    elif date_dict[\"timezone\"] == \"CEST\":\n        timezone_offset = 2\n    else:\n        return None\n    t = t - datetime.timedelta(hours=timezone_offset)\n    return t.replace(tzinfo=datetime.timezone.utc)",
    "docstring": "Parses time objects from the TibiaData API.\n\n    Time objects are made of a dictionary with three keys:\n        date: contains a string representation of the time\n        timezone: a string representation of the timezone the date time is based on\n        timezone_type: the type of representation used in the timezone key\n\n\n    Parameters\n    ----------\n    date_dict: :class:`dict`\n        Dictionary representing the time object.\n\n    Returns\n    -------\n    :class:`datetime.date`, optional\n        The represented datetime, in UTC."
  },
  {
    "code": "def set_properties(self, pathobj, props, recursive):\n        url = '/'.join([pathobj.drive,\n                        'api/storage',\n                        str(pathobj.relative_to(pathobj.drive)).strip('/')])\n        params = {'properties': encode_properties(props)}\n        if not recursive:\n            params['recursive'] = '0'\n        text, code = self.rest_put(url,\n                                   params=params,\n                                   auth=pathobj.auth,\n                                   verify=pathobj.verify,\n                                   cert=pathobj.cert)\n        if code == 404 and \"Unable to find item\" in text:\n            raise OSError(2, \"No such file or directory: '%s'\" % url)\n        if code != 204:\n            raise RuntimeError(text)",
    "docstring": "Set artifact properties"
  },
  {
    "code": "async def power_on(\n            self, comment: str = None,\n            wait: bool = False, wait_interval: int = 5):\n        params = {\"system_id\": self.system_id}\n        if comment is not None:\n            params[\"comment\"] = comment\n        try:\n            self._data = await self._handler.power_on(**params)\n        except CallError as error:\n            if error.status == HTTPStatus.FORBIDDEN:\n                message = \"Not allowed to power on machine.\"\n                raise OperationNotAllowed(message) from error\n            else:\n                raise\n        if not wait or self.power_state == PowerState.UNKNOWN:\n            return self\n        else:\n            while self.power_state == PowerState.OFF:\n                await asyncio.sleep(wait_interval)\n                self._data = await self._handler.read(system_id=self.system_id)\n            if self.power_state == PowerState.ERROR:\n                msg = \"{hostname} failed to power on.\".format(\n                    hostname=self.hostname\n                )\n                raise PowerError(msg, self)\n            return self",
    "docstring": "Power on.\n\n        :param comment: Reason machine was powered on.\n        :type comment: `str`\n        :param wait: If specified, wait until the machine is powered on.\n        :type wait: `bool`\n        :param wait_interval: How often to poll, defaults to 5 seconds.\n        :type wait_interval: `int`"
  },
  {
    "code": "def handle(self, *args, **options):\n        trigger_id = options.get('trigger_id')\n        trigger = TriggerService.objects.filter(\n            id=int(trigger_id),\n            status=True,\n            user__is_active=True,\n            provider_failed__lt=settings.DJANGO_TH.get('failed_tries', 10),\n            consumer_failed__lt=settings.DJANGO_TH.get('failed_tries', 10)\n        ).select_related('consumer__name', 'provider__name')\n        try:\n            with Pool(processes=1) as pool:\n                r = Read()\n                result = pool.map_async(r.reading, trigger)\n                result.get(timeout=360)\n                p = Pub()\n                result = pool.map_async(p.publishing, trigger)\n                result.get(timeout=360)\n                cache.delete('django_th' + '_fire_trigger_' + str(trigger_id))\n        except TimeoutError as e:\n            logger.warning(e)",
    "docstring": "get the trigger to fire"
  },
  {
    "code": "def from_hising(cls, h, J, offset=None):\n        poly = {(k,): v for k, v in h.items()}\n        poly.update(J)\n        if offset is not None:\n            poly[frozenset([])] = offset\n        return cls(poly, Vartype.SPIN)",
    "docstring": "Construct a binary polynomial from a higher-order Ising problem.\n\n        Args:\n            h (dict):\n                The linear biases.\n\n            J (dict):\n                The higher-order biases.\n\n            offset (optional, default=0.0):\n                Constant offset applied to the model.\n\n        Returns:\n            :obj:`.BinaryPolynomial`\n\n        Examples:\n            >>> poly = dimod.BinaryPolynomial.from_hising({'a': 2}, {'ab': -1}, 0)"
  },
  {
    "code": "def authenticate(self, username, password):\n        r = self._query_('/users/authenticate', 'POST',\n                         params={'username': username,\n                                 'password': password})\n        if r.status_code == 201:\n            return r.text.strip('\"')\n        else:\n            raise ValueError('Authentication invalid.')",
    "docstring": "Authenticates your user and returns an auth token.\n\n        :param str username: Hummingbird username.\n        :param str password: Hummingbird password.\n        :returns: str -- The Auth Token\n        :raises: ValueError -- If the Authentication is wrong"
  },
  {
    "code": "def age(self):\n    aff4_type = self.Get(self.Schema.TYPE)\n    if aff4_type:\n      return aff4_type.age\n    else:\n      return rdfvalue.RDFDatetime.Now()",
    "docstring": "RDFDatetime at which the object was created."
  },
  {
    "code": "def getLogs(self,\n                argument_filters=None,\n                fromBlock=None,\n                toBlock=None,\n                blockHash=None):\n        if not self.address:\n            raise TypeError(\"This method can be only called on \"\n                            \"an instated contract with an address\")\n        abi = self._get_event_abi()\n        if argument_filters is None:\n            argument_filters = dict()\n        _filters = dict(**argument_filters)\n        blkhash_set = blockHash is not None\n        blknum_set = fromBlock is not None or toBlock is not None\n        if blkhash_set and blknum_set:\n            raise ValidationError(\n                'blockHash cannot be set at the same'\n                ' time as fromBlock or toBlock')\n        data_filter_set, event_filter_params = construct_event_filter_params(\n            abi,\n            contract_address=self.address,\n            argument_filters=_filters,\n            fromBlock=fromBlock,\n            toBlock=toBlock,\n            address=self.address,\n        )\n        if blockHash is not None:\n            event_filter_params['blockHash'] = blockHash\n        logs = self.web3.eth.getLogs(event_filter_params)\n        return tuple(get_event_data(abi, entry) for entry in logs)",
    "docstring": "Get events for this contract instance using eth_getLogs API.\n\n        This is a stateless method, as opposed to createFilter.\n        It can be safely called against nodes which do not provide\n        eth_newFilter API, like Infura nodes.\n\n        If there are many events,\n        like ``Transfer`` events for a popular token,\n        the Ethereum node might be overloaded and timeout\n        on the underlying JSON-RPC call.\n\n        Example - how to get all ERC-20 token transactions\n        for the latest 10 blocks:\n\n        .. code-block:: python\n\n            from = max(mycontract.web3.eth.blockNumber - 10, 1)\n            to = mycontract.web3.eth.blockNumber\n\n            events = mycontract.events.Transfer.getLogs(fromBlock=from, toBlock=to)\n\n            for e in events:\n                print(e[\"args\"][\"from\"],\n                    e[\"args\"][\"to\"],\n                    e[\"args\"][\"value\"])\n\n        The returned processed log values will look like:\n\n        .. code-block:: python\n\n            (\n                AttributeDict({\n                 'args': AttributeDict({}),\n                 'event': 'LogNoArguments',\n                 'logIndex': 0,\n                 'transactionIndex': 0,\n                 'transactionHash': HexBytes('...'),\n                 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b',\n                 'blockHash': HexBytes('...'),\n                 'blockNumber': 3\n                }),\n                AttributeDict(...),\n                ...\n            )\n\n        See also: :func:`web3.middleware.filter.local_filter_middleware`.\n\n        :param argument_filters:\n        :param fromBlock: block number or \"latest\", defaults to \"latest\"\n        :param toBlock: block number or \"latest\". Defaults to \"latest\"\n        :param blockHash: block hash. blockHash cannot be set at the\n          same time as fromBlock or toBlock\n        :yield: Tuple of :class:`AttributeDict` instances"
  },
  {
    "code": "def to(self, unit):\n        from astropy.units import au, d\n        return (self.au_per_d * au / d).to(unit)",
    "docstring": "Convert this velocity to the given AstroPy unit."
  },
  {
    "code": "def shape(self) -> Tuple[int, ...]:\n        nmb_place = len(self.sequences)\n        nmb_time = len(hydpy.pub.timegrids.init)\n        nmb_others = collections.deque()\n        for sequence in self.sequences.values():\n            nmb_others.append(sequence.shape)\n        nmb_others_max = tuple(numpy.max(nmb_others, axis=0))\n        return self.sort_timeplaceentries(nmb_time, nmb_place) + nmb_others_max",
    "docstring": "Required shape of |NetCDFVariableDeep.array|.\n\n        For the default configuration, the first axis corresponds to the\n        number of devices, and the second one to the number of timesteps.\n        We show this for the 0-dimensional input sequence |lland_inputs.Nied|:\n\n        >>> from hydpy.core.examples import prepare_io_example_1\n        >>> nodes, elements = prepare_io_example_1()\n        >>> from hydpy.core.netcdftools import NetCDFVariableDeep\n        >>> ncvar = NetCDFVariableDeep('input_nied', isolate=False, timeaxis=1)\n        >>> for element in elements:\n        ...     ncvar.log(element.model.sequences.inputs.nied, None)\n        >>> ncvar.shape\n        (3, 4)\n\n        For higher dimensional sequences, each new entry corresponds\n        to the maximum number of fields the respective sequences require.\n        In the next example, we select the 1-dimensional sequence\n        |lland_fluxes.NKor|.  The maximum number 3 (last value of the\n        returned |tuple|) is due to the third element defining three\n        hydrological response units:\n\n        >>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=False, timeaxis=1)\n        >>> for element in elements:\n        ...     ncvar.log(element.model.sequences.fluxes.nkor, None)\n        >>> ncvar.shape\n        (3, 4, 3)\n\n        When using the first axis for time (`timeaxis=0`) the order of the\n        first two |tuple| entries turns:\n\n        >>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=False, timeaxis=0)\n        >>> for element in elements:\n        ...     ncvar.log(element.model.sequences.fluxes.nkor, None)\n        >>> ncvar.shape\n        (4, 3, 3)"
  },
  {
    "code": "def any_ends_with(self, string_list, pattern):\n        try:\n            s_base = basestring\n        except:\n            s_base = str\n        is_string = isinstance(pattern, s_base)\n        if not is_string:\n            return False\n        for s in string_list:\n            if pattern.endswith(s):\n                return True\n        return False",
    "docstring": "Returns true iff one of the strings in string_list ends in\n        pattern."
  },
  {
    "code": "def tokenize_string(cls, string, separator):\n        results = []\n        token = \"\"\n        found_escape = False\n        for c in string:\n            if found_escape:\n                if c == separator:\n                    token += separator\n                else:\n                    token += \"\\\\\" + c\n                found_escape = False\n                continue\n            if c == \"\\\\\":\n                found_escape = True\n            elif c == separator:\n                results.append(token)\n                token = \"\"\n            else:\n                token += c\n        results.append(token)\n        return results",
    "docstring": "Split string with given separator unless the separator is escaped with backslash"
  },
  {
    "code": "def dispatch(self, method_frame):\n        method = self.dispatch_map.get(method_frame.method_id)\n        if method:\n            callback = self.channel.clear_synchronous_cb(method)\n            callback(method_frame)\n        else:\n            raise self.InvalidMethod(\n                \"no method is registered with id: %d\" % method_frame.method_id)",
    "docstring": "Dispatch a method for this protocol."
  },
  {
    "code": "def jsonld(client, datasets):\n    from renku.models._json import dumps\n    from renku.models._jsonld import asjsonld\n    data = [\n        asjsonld(\n            dataset,\n            basedir=os.path.relpath(\n                '.', start=str(dataset.__reference__.parent)\n            )\n        ) for dataset in datasets\n    ]\n    click.echo(dumps(data, indent=2))",
    "docstring": "Format datasets as JSON-LD."
  },
  {
    "code": "def updateDatasetMenu(self):\n        enabled = True\n        current = self.vtgui.dbs_tree_view.currentIndex()\n        if current:\n            leaf = self.vtgui.dbs_tree_model.nodeFromIndex(current)\n            if leaf.node_kind in (u'group', u'root group'):\n                enabled = False\n        self.plot_action.setEnabled(enabled)",
    "docstring": "Update the `export` QAction when the Dataset menu is pulled down.\n\n        This method is a slot. See class ctor for details."
  },
  {
    "code": "def get_typecast_value(self, value, type):\n    if type == entities.Variable.Type.BOOLEAN:\n      return value == 'true'\n    elif type == entities.Variable.Type.INTEGER:\n      return int(value)\n    elif type == entities.Variable.Type.DOUBLE:\n      return float(value)\n    else:\n      return value",
    "docstring": "Helper method to determine actual value based on type of feature variable.\n\n    Args:\n      value: Value in string form as it was parsed from datafile.\n      type: Type denoting the feature flag type.\n\n    Return:\n      Value type-casted based on type of feature variable."
  },
  {
    "code": "def publish_topology_closed(self, topology_id):\n        event = TopologyClosedEvent(topology_id)\n        for subscriber in self.__topology_listeners:\n            try:\n                subscriber.closed(event)\n            except Exception:\n                _handle_exception()",
    "docstring": "Publish a TopologyClosedEvent to all topology listeners.\n\n        :Parameters:\n         - `topology_id`: A unique identifier for the topology this server\n           is a part of."
  },
  {
    "code": "def _validate_columns(self):\n        geom_cols = {'the_geom', 'the_geom_webmercator', }\n        col_overlap = set(self.style_cols) & geom_cols\n        if col_overlap:\n            raise ValueError('Style columns cannot be geometry '\n                             'columns. `{col}` was chosen.'.format(\n                                 col=','.join(col_overlap)))",
    "docstring": "Validate the options in the styles"
  },
  {
    "code": "def go(gconfig, args):\n    rconfig = gconfig['rejester']\n    which_worker = rconfig.get('worker', 'fork_worker')\n    if which_worker == 'fork_worker':\n        yakonfig.set_default_config([rejester], config=gconfig)\n    else:\n        start_logging(gconfig, args.logpath)\n    return start_worker(which_worker, rconfig)",
    "docstring": "Actually run the worker.\n\n    This does some required housekeeping, like setting up logging for\n    :class:`~rejester.workers.MultiWorker` and establishing the global\n    :mod:`yakonfig` configuration.  This expects to be called with the\n    :mod:`yakonfig` configuration unset.\n\n    :param dict gconfig: the :mod:`yakonfig` global configuration\n    :param args: command-line arguments"
  },
  {
    "code": "def restore(self, hist_uid):\n        if self.check_post_role()['ADMIN']:\n            pass\n        else:\n            return False\n        histinfo = MWikiHist.get_by_uid(hist_uid)\n        if histinfo:\n            pass\n        else:\n            return False\n        postinfo = MWiki.get_by_uid(histinfo.wiki_id)\n        cur_cnt = tornado.escape.xhtml_unescape(postinfo.cnt_md)\n        old_cnt = tornado.escape.xhtml_unescape(histinfo.cnt_md)\n        MWiki.update_cnt(\n            histinfo.wiki_id,\n            {'cnt_md': old_cnt, 'user_name': self.userinfo.user_name}\n        )\n        MWikiHist.update_cnt(\n            histinfo.uid,\n            {'cnt_md': cur_cnt, 'user_name': postinfo.user_name}\n        )\n        if postinfo.kind == '1':\n            self.redirect('/wiki/{0}'.format(postinfo.title))\n        elif postinfo.kind == '2':\n            self.redirect('/page/{0}.html'.format(postinfo.uid))",
    "docstring": "Restore by ID"
  },
  {
    "code": "def can_execute(self):\n        return not self._disabled and all(dep.status == dep.node.S_OK for dep in self.deps)",
    "docstring": "True if we can execute the callback."
  },
  {
    "code": "def get_value(self):\r\n        if self.__is_value_array:\r\n            if self.__bit_size == 8:\n                return list(self.__value)\r\n            else:\r\n                result = []\r\n                for i in range(self.__report_count):\r\n                    result.append(self.__getitem__(i))\r\n                return result\r\n        else:\r\n            return self.__value",
    "docstring": "Retreive usage value within report"
  },
  {
    "code": "def delete_answer(self, answer_id):\n        from dlkit.abstract_osid.id.primitives import Id as ABCId\n        from .objects import Answer\n        collection = JSONClientValidated('assessment',\n                                         collection='Item',\n                                         runtime=self._runtime)\n        if not isinstance(answer_id, ABCId):\n            raise errors.InvalidArgument('the argument is not a valid OSID Id')\n        item = collection.find_one({'answers._id': ObjectId(answer_id.get_identifier())})\n        index = 0\n        found = False\n        for i in item['answers']:\n            if i['_id'] == ObjectId(answer_id.get_identifier()):\n                answer_map = item['answers'].pop(index)\n            index += 1\n            found = True\n        if not found:\n            raise errors.OperationFailed()\n        Answer(\n            osid_object_map=answer_map,\n            runtime=self._runtime,\n            proxy=self._proxy)._delete()\n        collection.save(item)",
    "docstring": "Deletes the ``Answer`` identified by the given ``Id``.\n\n        arg:    answer_id (osid.id.Id): the ``Id`` of the ``Answer`` to\n                delete\n        raise:  NotFound - an ``Answer`` was not found identified by the\n                given ``Id``\n        raise:  NullArgument - ``answer_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def parse_json(target, json, create_sections = False, create_options = False):\r\n is_dict = isinstance(json, dict)\r\n for o in json:\r\n  if is_dict:\r\n   section = o\r\n  else:\r\n   section = o[0]\r\n  if not target.has_section(section):\r\n   if create_sections:\r\n    target.add_section(section)\r\n   else:\r\n    continue\r\n  for k, v in (json[o].items() if is_dict else o[1]):\r\n   if target.has_option(section, k) or create_options:\r\n    target.set(section, k, v)\n return target",
    "docstring": "Given a confmanager object and a dictionary object, import the values from the dictionary into the object, optionally adding sections and options as it goes."
  },
  {
    "code": "def show_error(self, message):\n        assert isinstance(message, string_types)\n        self.post('error', data=message)",
    "docstring": "Send an error message to the active client. The new error will be\n            displayed on any active GUI clients.\n\n            Args:\n                message (str): Plain-text message to display.\n\n            Returns:\n                None\n\n            >>> s = _syncthing()\n            >>> s.system.show_error('my error msg')\n            >>> s.system.errors()[0]\n            ... # doctest: +ELLIPSIS\n            ErrorEvent(when=datetime.datetime(...), message='\"my error msg\"')\n            >>> s.system.clear_errors()\n            >>> s.system.errors()\n            []"
  },
  {
    "code": "def generate_lifetime_subparser(subparsers):\n    parser = subparsers.add_parser(\n        'lifetime', description=constants.LIFETIME_DESCRIPTION,\n        epilog=constants.LIFETIME_EPILOG, formatter_class=ParagraphFormatter,\n        help=constants.LIFETIME_HELP)\n    parser.set_defaults(func=lifetime_report)\n    utils.add_tokenizer_argument(parser)\n    utils.add_common_arguments(parser)\n    utils.add_query_arguments(parser)\n    parser.add_argument('results', help=constants.LIFETIME_RESULTS_HELP,\n                        metavar='RESULTS')\n    parser.add_argument('label', help=constants.LIFETIME_LABEL_HELP,\n                        metavar='LABEL')\n    parser.add_argument('output', help=constants.REPORT_OUTPUT_HELP,\n                        metavar='OUTPUT')",
    "docstring": "Adds a sub-command parser to `subparsers` to make a lifetime report."
  },
  {
    "code": "def results(project, apikey, run, watch, server, output):\n    status = run_get_status(server, project, run, apikey)\n    log(format_run_status(status))\n    if watch:\n        for status in watch_run_status(server, project, run, apikey, 24*60*60):\n            log(format_run_status(status))\n    if status['state'] == 'completed':\n        log(\"Downloading result\")\n        response = run_get_result_text(server, project, run, apikey)\n        log(\"Received result\")\n        print(response, file=output)\n    elif status['state'] == 'error':\n        log(\"There was an error\")\n        error_result = run_get_result_text(server, project, run, apikey)\n        print(error_result, file=output)\n    else:\n        log(\"No result yet\")",
    "docstring": "Check to see if results are available for a particular mapping\n    and if so download.\n\n    Authentication is carried out using the --apikey option which\n    must be provided. Depending on the server operating mode this\n    may return a mask, a linkage table, or a permutation. Consult\n    the entity service documentation for details."
  },
  {
    "code": "def check_cups_allowed(func):\n    @wraps(func)\n    def decorator(*args, **kwargs):\n        cups = kwargs.get('cups')\n        if (cups and current_user.is_authenticated()\n                and not current_user.allowed(cups, 'cups')):\n            return current_app.login_manager.unauthorized()\n        return func(*args, **kwargs)\n    return decorator",
    "docstring": "Check if CUPS is allowd by token"
  },
  {
    "code": "def start(self):\n        yield from self._do_connect()\n        _LOGGER.info('connected to snapserver on %s:%s', self._host, self._port)\n        status = yield from self.status()\n        self.synchronize(status)\n        self._on_server_connect()",
    "docstring": "Initiate server connection."
  },
  {
    "code": "def add_key_filters(self, key_filters):\n        if self._input_mode == 'query':\n            raise ValueError('Key filters are not supported in a query.')\n        self._key_filters.extend(key_filters)\n        return self",
    "docstring": "Adds key filters to the inputs.\n\n        :param key_filters: a list of filters\n        :type key_filters: list\n        :rtype: :class:`RiakMapReduce`"
  },
  {
    "code": "def _emit(self, s):\n    if os.path.exists(self._html_dir):\n      self._report_file.write(s)\n      self._report_file.flush()",
    "docstring": "Append content to the main report file."
  },
  {
    "code": "def get_allow_future(self):\n        qs = self.get_queryset()\n        post_edit_permission = '{}.edit_{}'.format(\n            qs.model._meta.app_label, qs.model._meta.model_name\n        )\n        if self.request.user.has_perm(post_edit_permission):\n            return True\n        return False",
    "docstring": "Only superusers and users with the permission can edit the post."
  },
  {
    "code": "def set_managing_editor(self):\n        try:\n            self.managing_editor = self.soup.find('managingeditor').string\n        except AttributeError:\n            self.managing_editor = None",
    "docstring": "Parses managing editor and set value"
  },
  {
    "code": "def date_this_decade(self, before_today=True, after_today=False):\n        today = date.today()\n        this_decade_start = date(today.year - (today.year % 10), 1, 1)\n        next_decade_start = date(this_decade_start.year + 10, 1, 1)\n        if before_today and after_today:\n            return self.date_between_dates(this_decade_start, next_decade_start)\n        elif not before_today and after_today:\n            return self.date_between_dates(today, next_decade_start)\n        elif not after_today and before_today:\n            return self.date_between_dates(this_decade_start, today)\n        else:\n            return today",
    "docstring": "Gets a Date object for the decade year.\n\n        :param before_today: include days in current decade before today\n        :param after_today: include days in current decade after today\n        :example Date('2012-04-04')\n        :return Date"
  },
  {
    "code": "def binary_op(data, op, other, blen=None, storage=None, create='array',\n              **kwargs):\n    if hasattr(other, 'shape') and len(other.shape) == 0:\n        other = other[()]\n    if np.isscalar(other):\n        def f(block):\n            return op(block, other)\n        return map_blocks(data, f, blen=blen, storage=storage, create=create, **kwargs)\n    elif len(data) == len(other):\n        def f(a, b):\n            return op(a, b)\n        return map_blocks((data, other), f, blen=blen, storage=storage, create=create,\n                          **kwargs)\n    else:\n        raise NotImplementedError('argument type not supported')",
    "docstring": "Compute a binary operation block-wise over `data`."
  },
  {
    "code": "def iter_identities(self, stanza=None):\n        for (category, type_), names in self._identities.items():\n            for lang, name in names.items():\n                yield category, type_, lang, name\n            if not names:\n                yield category, type_, None, None",
    "docstring": "Return an iterator of tuples describing the identities of the node.\n\n        :param stanza: The IQ request stanza\n        :type stanza: :class:`~aioxmpp.IQ` or :data:`None`\n        :rtype: iterable of (:class:`str`, :class:`str`, :class:`str` or\n            :data:`None`, :class:`str` or :data:`None`) tuples\n        :return: :xep:`30` identities of this node\n\n        `stanza` can be the :class:`aioxmpp.IQ` stanza of the request. This can\n        be used to hide a node depending on who is asking. If the returned\n        iterable is empty, the :class:`~.DiscoServer` returns an\n        ``<item-not-found/>`` error.\n\n        `stanza` may be :data:`None` if the identities are queried without\n        a specific request context. In that case, implementors should assume\n        that the result is visible to everybody.\n\n        .. note::\n\n           Subclasses must allow :data:`None` for `stanza` and default it to\n           :data:`None`.\n\n        Return an iterator which yields tuples consisting of the category, the\n        type, the language code and the name of each identity declared in this\n        :class:`Node`.\n\n        Both the language code and the name may be :data:`None`, if no names or\n        a name without language code have been declared."
  },
  {
    "code": "def delete_tenant(self, tenant):\n        tenant_id = utils.get_id(tenant)\n        uri = \"tenants/%s\" % tenant_id\n        resp, resp_body = self.method_delete(uri)\n        if resp.status_code == 404:\n            raise exc.TenantNotFound(\"Tenant '%s' does not exist.\" % tenant)",
    "docstring": "ADMIN ONLY. Removes the tenant from the system. There is no 'undo'\n        available, so you should be certain that the tenant specified is the\n        tenant you wish to delete."
  },
  {
    "code": "def _find_neighbor_and_lambda(neighbor_indices, neighbor_distances,\n                              core_distances, min_samples):\n    neighbor_core_distances = core_distances[neighbor_indices]\n    point_core_distances = neighbor_distances[min_samples] * np.ones(\n        neighbor_indices.shape[0])\n    mr_distances = np.vstack((\n        neighbor_core_distances,\n        point_core_distances,\n        neighbor_distances\n    )).max(axis=0)\n    nn_index = mr_distances.argmin()\n    nearest_neighbor = neighbor_indices[nn_index]\n    if mr_distances[nn_index] > 0.0:\n        lambda_ = 1. / mr_distances[nn_index]\n    else:\n        lambda_ = np.finfo(np.double).max\n    return nearest_neighbor, lambda_",
    "docstring": "Find the nearest mutual reachability neighbor of a point, and  compute\n    the associated lambda value for the point, given the mutual reachability\n    distance to a nearest neighbor.\n\n    Parameters\n    ----------\n    neighbor_indices : array (2 * min_samples, )\n        An array of raw distance based nearest neighbor indices.\n\n    neighbor_distances : array (2 * min_samples, )\n        An array of raw distances to the nearest neighbors.\n\n    core_distances : array (n_samples, )\n        An array of core distances for all points\n\n    min_samples : int\n        The min_samples value used to generate core distances.\n\n    Returns\n    -------\n    neighbor : int\n        The index into the full raw data set of the nearest mutual reachability\n        distance neighbor of the point.\n\n    lambda_ : float\n        The lambda value at which this point joins/merges with `neighbor`."
  },
  {
    "code": "def getNameOwner(self, busName):\n        d = self.callRemote(\n            '/org/freedesktop/DBus',\n            'GetNameOwner',\n            interface='org.freedesktop.DBus',\n            signature='s',\n            body=[busName],\n            destination='org.freedesktop.DBus',\n        )\n        return d",
    "docstring": "Calls org.freedesktop.DBus.GetNameOwner\n        @rtype: L{twisted.internet.defer.Deferred}\n        @returns: a Deferred to the unique connection name owning the bus name"
  },
  {
    "code": "def get_named_graph(identifier, store_id=DEFAULT_STORE, create=True):\n    if not isinstance(identifier, URIRef):\n        identifier = URIRef(identifier)\n    store = DjangoStore(store_id)\n    graph = Graph(store, identifier=identifier)\n    if graph.open(None, create=create) != VALID_STORE:\n        raise ValueError(\"The store identified by {0} is not a valid store\".format(store_id))\n    return graph",
    "docstring": "Returns an open named graph."
  },
  {
    "code": "def DbGetExportdDeviceListForClass(self, argin):\n        self._log.debug(\"In DbGetExportdDeviceListForClass()\")\n        argin = replace_wildcard(argin)\n        return self.db.get_exported_device_list_for_class(argin)",
    "docstring": "Query the database for device exported for the specified class.\n\n        :param argin: Class name\n        :type: tango.DevString\n        :return: Device exported list\n        :rtype: tango.DevVarStringArray"
  },
  {
    "code": "def _compile_to_sklearn(self, expr):\n        sklearn_pipeline_str = generate_pipeline_code(expr_to_tree(expr, self._pset), self.operators)\n        sklearn_pipeline = eval(sklearn_pipeline_str, self.operators_context)\n        sklearn_pipeline.memory = self._memory\n        return sklearn_pipeline",
    "docstring": "Compile a DEAP pipeline into a sklearn pipeline.\n\n        Parameters\n        ----------\n        expr: DEAP individual\n            The DEAP pipeline to be compiled\n\n        Returns\n        -------\n        sklearn_pipeline: sklearn.pipeline.Pipeline"
  },
  {
    "code": "def update_policy(self,defaultHeaders):\n\t\tif self.inputs is not None:\n\t\t\tfor k,v in defaultHeaders.items():\n\t\t\t\tif k not in self.inputs:\n\t\t\t\t\tself.inputs[k] = v\n\t\t\t\tif k == 'pins':\n\t\t\t\t\tself.inputs[k] = self.inputs[k] + defaultHeaders[k]\n\t\t\treturn self.inputs\n\t\telse:\n\t\t\treturn self.inputs",
    "docstring": "rewrite update policy so that additional pins are added and not overwritten"
  },
  {
    "code": "def organization_deidentify_template_path(cls, organization, deidentify_template):\n        return google.api_core.path_template.expand(\n            \"organizations/{organization}/deidentifyTemplates/{deidentify_template}\",\n            organization=organization,\n            deidentify_template=deidentify_template,\n        )",
    "docstring": "Return a fully-qualified organization_deidentify_template string."
  },
  {
    "code": "def show_calltip(self, signature, doc='', parameter='', parameter_doc='',\r\n                     color=_DEFAULT_TITLE_COLOR, is_python=False):\r\n        point = self._calculate_position()\r\n        tiptext, wrapped_lines = self._format_signature(\r\n            signature,\r\n            doc,\r\n            parameter,\r\n            parameter_doc,\r\n            color,\r\n            is_python,\r\n        )\r\n        self._update_stylesheet(self.calltip_widget)\r\n        self.calltip_widget.show_tip(point, tiptext, wrapped_lines)",
    "docstring": "Show calltip.\r\n\r\n        Calltips look like tooltips but will not disappear if mouse hovers\r\n        them. They are useful for displaying signature information on methods\r\n        and functions."
  },
  {
    "code": "def copy_func(func: Callable) -> Callable:\n    copied = types.FunctionType(\n        func.__code__, func.__globals__, name=func.__name__,\n        argdefs=func.__defaults__, closure=func.__closure__)\n    copied = functools.update_wrapper(copied, func)\n    copied.__kwdefaults__ = func.__kwdefaults__\n    return copied",
    "docstring": "Returns a copy of a function.\n\n    :param func: The function to copy.\n    :returns: The copied function."
  },
  {
    "code": "def hyphenation(phrase, format='json'):\n        base_url = Vocabulary.__get_api_link(\"wordnik\")\n        url = base_url.format(word=phrase.lower(), action=\"hyphenation\")\n        json_obj = Vocabulary.__return_json(url)\n        if json_obj:\n            return Response().respond(json_obj, format)\n        else:\n            return False",
    "docstring": "Returns back the stress points in the \"phrase\" passed\n\n        :param phrase: word for which hyphenation is to be found\n        :param format: response structure type. Defaults to: \"json\"\n        :returns: returns a json object as str, False if invalid phrase"
  },
  {
    "code": "def wait(msg='', exceptions=None, timeout=10):\n    exc = [StaleElementReferenceException]\n    if exceptions is not None:\n        try:\n            exc.extend(iter(exceptions))\n        except TypeError:\n            exc.append(exceptions)\n    exc = tuple(exc)\n    if not msg:\n        msg = \"Could not recover from Exception(s): {}\".format(', '.join([e.__name__ for e in exc]))\n    def wrapper(func):\n        def wait_handler(*args, **kwargs):\n            import time\n            poll_freq = 0.5\n            end_time = time.time() + timeout\n            while time.time() <= end_time:\n                try:\n                    value = func(*args, **kwargs)\n                    if value:\n                        return value\n                except exc as e:\n                    LOGGER.debug(e)\n                    pass\n                time.sleep(poll_freq)\n                poll_freq *= 1.25\n            raise RuntimeError(msg)\n        return wait_handler\n    return wrapper",
    "docstring": "Decorator to handle generic waiting situations.\n\n    Will handle StaleElementReferenceErrors.\n\n    :param msg: Error message\n    :param exceptions: Extra exceptions to handle\n    :param timeout: time to keep trying (default: 10 seconds)\n    :return: the result of the decorated function"
  },
  {
    "code": "def rotation(self):\n\t\trotation = self._libinput.libinput_event_tablet_tool_get_rotation(\n\t\t\tself._handle)\n\t\tchanged = self._libinput. \\\n\t\t\tlibinput_event_tablet_tool_rotation_has_changed(self._handle)\n\t\treturn rotation, changed",
    "docstring": "The current Z rotation of the tool in degrees, clockwise\n\t\tfrom the tool's logical neutral position and whether it has changed\n\t\tin this event.\n\n\t\tFor tools of type :attr:`~libinput.constant.TabletToolType.MOUSE`\n\t\tand :attr:`~libinput.constant.TabletToolType.LENS` the logical\n\t\tneutral position is pointing to the current logical north\n\t\tof the tablet. For tools of type\n\t\t:attr:`~libinput.constant.TabletToolType.BRUSH`, the logical\n\t\tneutral position is with the buttons pointing up.\n\n\t\tIf this axis does not exist on the current tool, this property is\n\t\t(0, :obj:`False`).\n\n\t\tReturns:\n\t\t\t(float, bool): The current value of the the axis and whether it has\n\t\t\tchanged."
  },
  {
    "code": "def anscombe():\n    _, ((axa, axb), (axc, axd)) =  plt.subplots(2, 2, sharex='col', sharey='row')\n    colors = get_color_cycle()\n    for arr, ax, color in zip(ANSCOMBE, (axa, axb, axc, axd), colors):\n        x = arr[0]\n        y = arr[1]\n        ax.set_xlim(0, 15)\n        ax.set_ylim(0, 15)\n        ax.scatter(x, y, c=color)\n        draw_best_fit(x, y, ax, c=color)\n    return (axa, axb, axc, axd)",
    "docstring": "Creates 2x2 grid plot of the 4 anscombe datasets for illustration."
  },
  {
    "code": "def create_ui(self):\n        self.entry = gtk.Entry()\n        self.widget.add(self.entry)",
    "docstring": "Create the user interface\n\n           create_ui is a method called during the Delegate's\n           initialisation process, to create, add to, or modify any UI\n           created by GtkBuilder files."
  },
  {
    "code": "def integrate(self, wave=None):\n        if wave is None:\n            wave = self.wave\n        ans = self.trapezoidIntegration(wave, self(wave))\n        return ans",
    "docstring": "Integrate the throughput over the specified wavelength set.\n        If no wavelength set is specified, the built-in one is used.\n\n        Integration is done using :meth:`~Integrator.trapezoidIntegration`\n        with ``x=wave`` and ``y=throughput``.\n        Also see :ref:`pysynphot-formula-equvw`.\n\n        Parameters\n        ----------\n        wave : array_like or `None`\n            Wavelength set for integration.\n\n        Returns\n        -------\n        ans : float\n            Integrated sum."
  },
  {
    "code": "def get_all_parcels(self, view = None):\n    return parcels.get_all_parcels(self._get_resource_root(), self.name, view)",
    "docstring": "Get all parcels in this cluster.\n\n    @return: A list of ApiParcel objects."
  },
  {
    "code": "def get_attr_info(binary_view):\n    global _ATTR_BASIC\n    attr_type, attr_len, non_resident = _ATTR_BASIC.unpack(binary_view[:9])\n    return (AttrTypes(attr_type), attr_len, bool(non_resident))",
    "docstring": "Gets basic information from a binary stream to allow correct processing of\n    the attribute header.\n\n    This function allows the interpretation of the Attribute type, attribute length\n    and if the attribute is non resident.\n\n    Args:\n        binary_view (memoryview of bytearray) - A binary stream with the\n            information of the attribute\n\n    Returns:\n        An tuple with the attribute type, the attribute length, in bytes, and\n        if the attribute is resident or not."
  },
  {
    "code": "def _render_internal_label(self):\n        ncc = self._num_complete_chars\n        bar = self._lbl.center(self.iwidth)\n        cm_chars = self._comp_style(bar[:ncc])\n        em_chars = self._empt_style(bar[ncc:])\n        return f'{self._first}{cm_chars}{em_chars}{self._last}'",
    "docstring": "Render with a label inside the bar graph."
  },
  {
    "code": "def get_action_group_names(self):\n        return self.get_group_names(\n            list(itertools.chain(\n                *[self._get_array('add'),\n                  self._get_array('remove'),\n                  self._get_array('isolation-group')])))",
    "docstring": "Return all the security group names configured in this action."
  },
  {
    "code": "def run():\n    logging.basicConfig(level=logging.DEBUG)\n    load_config.ConfigLoader().load()\n    config.debug = True\n    print(repr(config.engine.item(sys.argv[1])))",
    "docstring": "Module level test."
  },
  {
    "code": "def A_hollow_cylinder(Di, Do, L):\n    r\n    side_o = pi*Do*L\n    side_i = pi*Di*L\n    cap_circle = pi*Do**2/4*2\n    cap_removed = pi*Di**2/4*2\n    return side_o + side_i + cap_circle - cap_removed",
    "docstring": "r'''Returns the surface area of a hollow cylinder.\n\n    .. math::\n        A = \\pi D_o L + \\pi D_i L  + 2\\cdot \\frac{\\pi D_o^2}{4}\n        - 2\\cdot \\frac{\\pi D_i^2}{4}\n\n    Parameters\n    ----------\n    Di : float\n        Diameter of the hollow in the cylinder, [m]\n    Do : float\n        Diameter of the exterior of the cylinder, [m]\n    L : float\n        Length of the cylinder, [m]\n\n    Returns\n    -------\n    A : float\n        Surface area [m^2]\n\n    Examples\n    --------\n    >>> A_hollow_cylinder(0.005, 0.01, 0.1)\n    0.004830198704894308"
  },
  {
    "code": "def update_milestone(self, milestone_id, title, deadline, party_id, notify,\n        move_upcoming_milestones=None,\n        move_upcoming_milestones_off_weekends=None):\n        path = '/milestones/update/%u' % milestone_id\n        req = ET.Element('request')\n        req.append(\n            self._create_milestone_elem(title, deadline, party_id, notify))\n        if move_upcoming_milestones is not None:\n            ET.SubElement(req, 'move-upcoming-milestones').text \\\n                = str(bool()).lower()\n        if move_upcoming_milestones_off_weekends is not None:\n            ET.SubElement(req, 'move-upcoming-milestones-off-weekends').text \\\n                = str(bool()).lower()\n        return self._request(path, req)",
    "docstring": "Modifies a single milestone. You can use this to shift the deadline of\n        a single milestone, and optionally shift the deadlines of subsequent\n        milestones as well."
  },
  {
    "code": "def _read_mode_qsopt(self, size, kind):\n        rvrr = self._read_binary(1)\n        ttld = self._read_unpack(1)\n        noun = self._read_fileng(4)\n        data = dict(\n            kind=kind,\n            length=size,\n            req_rate=int(rvrr[4:], base=2),\n            ttl_diff=ttld,\n            nounce=noun[:-2],\n        )\n        return data",
    "docstring": "Read Quick-Start Response option.\n\n        Positional arguments:\n            * size - int, length of option\n            * kind - int, 27 (Quick-Start Response)\n\n        Returns:\n            * dict -- extracted Quick-Start Response (QS) option\n\n        Structure of TCP QSopt [RFC 4782]:\n             0                   1                   2                   3\n             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |     Kind      |  Length=8     | Resv. | Rate  |   TTL Diff    |\n            |               |               |       |Request|               |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |                   QS Nonce                                | R |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n            Octets      Bits        Name                    Description\n              0           0     tcp.qs.kind             Kind (27)\n              1           8     tcp.qs.length           Length (8)\n              2          16     -                       Reserved (must be zero)\n              2          20     tcp.qs.req_rate         Request Rate\n              3          24     tcp.qs.ttl_diff         TTL Difference\n              4          32     tcp.qs.nounce           QS Nounce\n              7          62     -                       Reserved (must be zero)"
  },
  {
    "code": "def get_item_key(self, item):\n        try:\n            ret = item[item['key']]\n        except KeyError:\n            logger.error(\"No 'key' available in {}\".format(item))\n        if isinstance(ret, list):\n            return ret[0]\n        else:\n            return ret",
    "docstring": "Return the value of the item 'key'."
  },
  {
    "code": "def get_fw_dict(self):\n        fw_dict = {}\n        if self.fw_id is None:\n            return fw_dict\n        fw_dict = {'rules': {}, 'tenant_name': self.tenant_name,\n                   'tenant_id': self.tenant_id, 'fw_id': self.fw_id,\n                   'fw_name': self.fw_name,\n                   'firewall_policy_id': self.active_pol_id,\n                   'fw_type': self.fw_type, 'router_id': self.router_id}\n        if self.active_pol_id not in self.policies:\n            return fw_dict\n        pol_dict = self.policies[self.active_pol_id]\n        for rule in pol_dict['rule_dict']:\n            fw_dict['rules'][rule] = self.rules[rule]\n        return fw_dict",
    "docstring": "This API creates a FW dictionary from the local attributes."
  },
  {
    "code": "def fill_nulls(self, col: str):\n        n = [None, \"\"]\n        try:\n            self.df[col] = self.df[col].replace(n, nan)\n        except Exception as e:\n            self.err(e)",
    "docstring": "Fill all null values with NaN values in a column.\n        Null values are ``None`` or en empty string\n\n        :param col: column name\n        :type col: str\n\n        :example: ``ds.fill_nulls(\"mycol\")``"
  },
  {
    "code": "def search_function(encoding):\n    if encoding in _CACHE:\n        return _CACHE[encoding]\n    norm_encoding = normalize_encoding(encoding)\n    codec = None\n    if norm_encoding in UTF8_VAR_NAMES:\n        from ftfy.bad_codecs.utf8_variants import CODEC_INFO\n        codec = CODEC_INFO\n    elif norm_encoding.startswith('sloppy_'):\n        from ftfy.bad_codecs.sloppy import CODECS\n        codec = CODECS.get(norm_encoding)\n    if codec is not None:\n        _CACHE[encoding] = codec\n    return codec",
    "docstring": "Register our \"bad codecs\" with Python's codecs API. This involves adding\n    a search function that takes in an encoding name, and returns a codec\n    for that encoding if it knows one, or None if it doesn't.\n\n    The encodings this will match are:\n\n    - Encodings of the form 'sloppy-windows-NNNN' or 'sloppy-iso-8859-N',\n      where the non-sloppy version is an encoding that leaves some bytes\n      unmapped to characters.\n    - The 'utf-8-variants' encoding, which has the several aliases seen\n      above."
  },
  {
    "code": "def lock(key, text):\n    return hmac.new(key.encode('utf-8'), text.encode('utf-8')).hexdigest()",
    "docstring": "Locks the given text using the given key and returns the result"
  },
  {
    "code": "def _calc_d(aod700, p):\n    p0 = 101325.\n    dp = 1/(18 + 152*aod700)\n    d = -0.337*aod700**2 + 0.63*aod700 + 0.116 + dp*np.log(p/p0)\n    return d",
    "docstring": "Calculate the d coefficient."
  },
  {
    "code": "def init0(self, dae):\n        dae.y[self.v] = self.v0\n        dae.y[self.q] = mul(self.u, self.qg)",
    "docstring": "Set initial voltage and reactive power for PQ.\n        Overwrites Bus.voltage values"
  },
  {
    "code": "def safe_unicode(string):\n    if not isinstance(string, basestring):\n        string = unicode(string)\n    if isinstance(string, unicode):\n        string = string.encode('utf8')\n    return string",
    "docstring": "Safely transform any object into utf8 encoded bytes"
  },
  {
    "code": "def separate_struct_array(array, dtypes):\n    try:\n        offsets = np.cumsum([np.dtype(dtype).itemsize for dtype in dtypes])\n    except TypeError:\n        dtype_size = np.dtype(dtypes).itemsize\n        num_fields = int(array.nbytes / (array.size * dtype_size))\n        offsets = np.cumsum([dtype_size] * num_fields)\n        dtypes = [dtypes] * num_fields\n    offsets = np.concatenate([[0], offsets]).astype(int)\n    uint_array = array.view(np.uint8).reshape(array.shape + (-1,))\n    return [\n        uint_array[..., offsets[idx]:offsets[idx+1]].flatten().view(dtype)\n        for idx, dtype in enumerate(dtypes)\n    ]",
    "docstring": "Takes an array with a structured dtype, and separates it out into\n    a list of arrays with dtypes coming from the input ``dtypes``.\n    Does the inverse of ``join_struct_arrays``.\n\n    :param np.ndarray array: Structured array.\n    :param dtypes: List of ``np.dtype``, or just a ``np.dtype`` and the number of\n        them is figured out automatically by counting bytes."
  },
  {
    "code": "def write_blockdata(self, obj, parent=None):\n        if type(obj) is str:\n            obj = to_bytes(obj, \"latin-1\")\n        length = len(obj)\n        if length <= 256:\n            self._writeStruct(\">B\", 1, (self.TC_BLOCKDATA,))\n            self._writeStruct(\">B\", 1, (length,))\n        else:\n            self._writeStruct(\">B\", 1, (self.TC_BLOCKDATALONG,))\n            self._writeStruct(\">I\", 1, (length,))\n        self.object_stream.write(obj)",
    "docstring": "Appends a block of data to the serialization stream\n\n        :param obj: String form of the data block"
  },
  {
    "code": "def preproc_directive(self) -> bool:\n    self._stream.save_context()\n    if self.read_until(\"\\n\", '\\\\'):\n        return self._stream.validate_context()\n    return self._stream.restore_context()",
    "docstring": "Consume a preproc directive."
  },
  {
    "code": "def hostname(name, hostname=None):\n    ret = _default_ret(name)\n    current_name = __salt__['cimc.get_hostname']()\n    req_change = False\n    try:\n        if current_name != hostname:\n            req_change = True\n        if req_change:\n            update = __salt__['cimc.set_hostname'](hostname)\n            if not update:\n                ret['result'] = False\n                ret['comment'] = \"Error setting hostname.\"\n                return ret\n            ret['changes']['before'] = current_name\n            ret['changes']['after'] = hostname\n            ret['comment'] = \"Hostname modified.\"\n        else:\n            ret['comment'] = \"Hostname already configured. No changes required.\"\n    except Exception as err:\n        ret['result'] = False\n        ret['comment'] = \"Error occurred setting hostname.\"\n        log.error(err)\n        return ret\n    ret['result'] = True\n    return ret",
    "docstring": "Ensures that the hostname is set to the specified value.\n\n    .. versionadded:: 2019.2.0\n\n    name: The name of the module function to execute.\n\n    hostname(str): The hostname of the server.\n\n    SLS Example:\n\n    .. code-block:: yaml\n\n        set_name:\n          cimc.hostname:\n            - hostname: foobar"
  },
  {
    "code": "def component_acting_parent_tag(parent_tag, tag):\n    if parent_tag.name == \"fig-group\":\n        if (len(tag.find_previous_siblings(\"fig\")) > 0):\n            acting_parent_tag = first(extract_nodes(parent_tag, \"fig\"))\n        else:\n            return None\n    else:\n        acting_parent_tag = parent_tag\n    return acting_parent_tag",
    "docstring": "Only intended for use in getting components, look for tag name of fig-group\n    and if so, find the first fig tag inside it as the acting parent tag"
  },
  {
    "code": "def restore_site_properties(self, site_property=\"ff_map\", filename=None):\n        if not self.control_params[\"filetype\"] == \"pdb\":\n            raise ValueError()\n        filename = filename or self.control_params[\"output\"]\n        bma = BabelMolAdaptor.from_file(filename, \"pdb\")\n        pbm = pb.Molecule(bma._obmol)\n        assert len(pbm.residues) == sum([x[\"number\"]\n                                         for x in self.param_list])\n        packed_mol = self.convert_obatoms_to_molecule(\n            pbm.residues[0].atoms, residue_name=pbm.residues[0].name,\n            site_property=site_property)\n        for resid in pbm.residues[1:]:\n            mol = self.convert_obatoms_to_molecule(\n                resid.atoms, residue_name=resid.name,\n                site_property=site_property)\n            for site in mol:\n                packed_mol.append(site.species, site.coords,\n                                  properties=site.properties)\n        return packed_mol",
    "docstring": "Restore the site properties for the final packed molecule.\n\n        Args:\n            site_property (str):\n            filename (str): path to the final packed molecule.\n\n        Returns:\n            Molecule"
  },
  {
    "code": "def predict_files(self, files):\n        imgs = [0]*len(files)\n        for i, file in enumerate(files):\n            img = cv2.imread(file).astype('float64')\n            img = cv2.resize(img, (224,224))\n            img = preprocess_input(img)\n            if img is None:\n                print('failed to open: {}, continuing...'.format(file))\n            imgs[i] = img\n        return self.model.predict(np.array(imgs))",
    "docstring": "reads files off disk, resizes them\n        and then predicts them, files should\n        be a list or itrerable of file paths\n        that lead to images, they are then\n        loaded with opencv, resized, and predicted"
  },
  {
    "code": "def delete(self, invoice_id, **kwargs):\n        url = \"{}/{}\".format(self.base_url, invoice_id)\n        return self.delete_url(url, {}, **kwargs)",
    "docstring": "Delete an invoice\n        You can delete an invoice which is in the draft state.\n\n        Args:\n            invoice_id : Id for delete the invoice\n        Returns:\n            The response is always be an empty array like this - []"
  },
  {
    "code": "def add_resource(self, resource_id, attributes, parents=[],\n            issuer='default'):\n        assert isinstance(attributes, (dict)), \"attributes expected to be dict\"\n        attrs = []\n        for key in attributes.keys():\n            attrs.append({\n                'issuer': issuer,\n                'name': key,\n                'value': attributes[key]\n                })\n        body = {\n            \"resourceIdentifier\": resource_id,\n            \"parents\": parents,\n            \"attributes\": attrs,\n        }\n        return self._put_resource(resource_id, body)",
    "docstring": "Will add the given resource with a given identifier and attribute\n        dictionary.\n\n            example/\n\n                add_resource('/asset/12', {'id': 12, 'manufacturer': 'GE'})"
  },
  {
    "code": "def register(scraper):\n\tglobal scrapers\n\tlanguage = scraper('').language\n\tif not language:\n\t\traise Exception('No language specified for your scraper.')\n\tif scrapers.has_key(language):\n\t\tscrapers[language].append(scraper)\n\telse:\n\t\tscrapers[language] = [scraper]",
    "docstring": "Registers a scraper to make it available for the generic scraping interface."
  },
  {
    "code": "def _red_listing_validation(key, listing):\n    if listing:\n        try:\n            jsonschema.validate(listing, cwl_job_listing_schema)\n        except ValidationError as e:\n            raise RedValidationError('REDFILE listing of input \"{}\" does not comply with jsonschema: {}'\n                                     .format(key, e.context))",
    "docstring": "Raises an RedValidationError, if the given listing does not comply with cwl_job_listing_schema.\n    If listing is None or an empty list, no exception is thrown.\n\n    :param key: The input key to build an error message if needed.\n    :param listing: The listing to validate\n    :raise RedValidationError: If the given listing does not comply with cwl_job_listing_schema"
  },
  {
    "code": "def get_ilwdchar_class(tbl_name, col_name, namespace = globals()):\n\tkey = (str(tbl_name), str(col_name))\n\tcls_name = \"%s_%s_class\" % key\n\tassert cls_name != \"get_ilwdchar_class\"\n\ttry:\n\t\treturn namespace[cls_name]\n\texcept KeyError:\n\t\tpass\n\tclass new_class(_ilwd.ilwdchar):\n\t\t__slots__ = ()\n\t\ttable_name, column_name = key\n\t\tindex_offset = len(\"%s:%s:\" % key)\n\tnew_class.__name__ = cls_name\n\tnamespace[cls_name] = new_class\n\tcopy_reg.pickle(new_class, lambda x: (ilwdchar, (unicode(x),)))\n\treturn new_class",
    "docstring": "Searches this module's namespace for a subclass of _ilwd.ilwdchar\n\twhose table_name and column_name attributes match those provided.\n\tIf a matching subclass is found it is returned; otherwise a new\n\tclass is defined, added to this module's namespace, and returned.\n\n\tExample:\n\n\t>>> process_id = get_ilwdchar_class(\"process\", \"process_id\")\n\t>>> x = process_id(10)\n\t>>> str(type(x))\n\t\"<class 'pycbc_glue.ligolw.ilwd.process_process_id_class'>\"\n\t>>> str(x)\n\t'process:process_id:10'\n\n\tRetrieving and storing the class provides a convenient mechanism\n\tfor quickly constructing new ID objects.\n\n\tExample:\n\n\t>>> for i in range(10):\n\t...\tprint str(process_id(i))\n\t...\n\tprocess:process_id:0\n\tprocess:process_id:1\n\tprocess:process_id:2\n\tprocess:process_id:3\n\tprocess:process_id:4\n\tprocess:process_id:5\n\tprocess:process_id:6\n\tprocess:process_id:7\n\tprocess:process_id:8\n\tprocess:process_id:9"
  },
  {
    "code": "def _infer_decorator_callchain(node):\n    if not isinstance(node, FunctionDef):\n        return None\n    if not node.parent:\n        return None\n    try:\n        result = next(node.infer_call_result(node.parent))\n    except exceptions.InferenceError:\n        return None\n    if isinstance(result, bases.Instance):\n        result = result._proxied\n    if isinstance(result, ClassDef):\n        if result.is_subtype_of(\"%s.classmethod\" % BUILTINS):\n            return \"classmethod\"\n        if result.is_subtype_of(\"%s.staticmethod\" % BUILTINS):\n            return \"staticmethod\"\n    return None",
    "docstring": "Detect decorator call chaining and see if the end result is a\n    static or a classmethod."
  },
  {
    "code": "def all(cls):\n        account = cls.info()\n        creditusage = cls.creditusage()\n        if not creditusage:\n            return account\n        left = account['credits'] / creditusage\n        years, hours = divmod(left, 365 * 24)\n        months, hours = divmod(hours, 31 * 24)\n        days, hours = divmod(hours, 24)\n        account.update({'credit_usage': creditusage,\n                        'left': (years, months, days, hours)})\n        return account",
    "docstring": "Get all informations about this account"
  },
  {
    "code": "def _compute_site_scaling(self, C, vs30):\n        site_term = np.zeros(len(vs30), dtype=float)\n        site_term[vs30 < 760.0] = C[\"e\"]\n        return site_term",
    "docstring": "Returns the site scaling term as a simple coefficient"
  },
  {
    "code": "def fit(self, data, labels, **kwargs):\n        self._som.train(data, **kwargs)\n        bmus, q_error, t_error = self.bmus_with_errors(data)\n        self.quant_error = q_error\n        self.topog_error = t_error\n        self._bmus = bmus\n        self._calibrate(data, labels)",
    "docstring": "\\\n        Training the SOM on the the data and calibrate itself.\n\n        After the training, `self.quant_error` and `self.topog_error` are \n        respectively set.\n\n        :param data: sparse input matrix (ideal dtype is `numpy.float32`)\n        :type data: :class:`scipy.sparse.csr_matrix`\n        :param labels: the labels associated with data\n        :type labels: iterable\n        :param \\**kwargs: optional parameters for :meth:`train`"
  },
  {
    "code": "def handle(self, handler_name, request, suffix=''):\n        return self.runtime.handle(self, handler_name, request, suffix)",
    "docstring": "Handle `request` with this block's runtime."
  },
  {
    "code": "def should_obfuscate_filename(self):\n        for pattern in self.args.hide_file_names:\n            try:\n                compiled = re.compile(pattern, re.IGNORECASE)\n                if compiled.search(self.entity):\n                    return True\n            except re.error as ex:\n                log.warning(u('Regex error ({msg}) for hide_file_names pattern: {pattern}').format(\n                    msg=u(ex),\n                    pattern=u(pattern),\n                ))\n        return False",
    "docstring": "Returns True if hide_file_names is true or the entity file path\n        matches one in the list of obfuscated file paths."
  },
  {
    "code": "async def _make_connection(self):\n        return await aioredis.create_redis(\n            'redis://{}:{}'.format(\n                self._redis_params.get('host', 'localhost'),\n                self._redis_params.get('port', 6379)\n            ),\n            db=int(self._redis_params.get('db', 1))\n        )",
    "docstring": "Construct a connection to Redis."
  },
  {
    "code": "def sg_seek_streamer(self, index, force, value):\n        force = bool(force)\n        err = self.sensor_graph.acknowledge_streamer(index, value, force)\n        return [err]",
    "docstring": "Ackowledge a streamer."
  },
  {
    "code": "def _bind_method(self, name, unconditionally=False):\n        exists = self.run_func('exist', name)['result'] in [2, 3, 5]\n        if not unconditionally and not exists:\n            raise AttributeError(\"'Matlab' object has no attribute '%s'\" % name)\n        method_instance = MatlabFunction(weakref.ref(self), name)\n        method_instance.__name__ = name\n        if sys.version.startswith('3'):\n            method = types.MethodType(method_instance, weakref.ref(self))\n        else:\n            method = types.MethodType(method_instance, weakref.ref(self),\n                                      _Session)\n        setattr(self, name, method)\n        return getattr(self, name)",
    "docstring": "Generate a Matlab function and bind it to the instance\n\n        This is where the magic happens. When an unknown attribute of the\n        Matlab class is requested, it is assumed to be a call to a\n        Matlab function, and is generated and bound to the instance.\n\n        This works because getattr() falls back to __getattr__ only if no\n        attributes of the requested name can be found through normal\n        routes (__getattribute__, __dict__, class tree).\n\n        bind_method first checks whether the requested name is a callable\n        Matlab function before generating a binding.\n\n        Parameters\n        ----------\n        name : str\n            The name of the Matlab function to call\n                e.g. 'sqrt', 'sum', 'svd', etc\n        unconditionally : bool, optional\n            Bind the method without performing\n                checks. Used to bootstrap methods that are required and\n                know to exist\n\n        Returns\n        -------\n        MatlabFunction\n            A reference to a newly bound MatlabFunction instance if the\n                requested name is determined to be a callable function\n\n        Raises\n        ------\n        AttributeError: if the requested name is not a callable\n                Matlab function"
  },
  {
    "code": "def load_trajectory(name, format=None, skip=1):\n    df = datafile(name, format=format)\n    ret = {}\n    t, coords = df.read('trajectory', skip=skip)\n    boxes = df.read('boxes')\n    ret['t'] = t\n    ret['coords'] = coords\n    ret['boxes'] = boxes\n    return ret",
    "docstring": "Read a trajectory from a file.\n\n    .. seealso:: `chemlab.io.datafile`"
  },
  {
    "code": "def _serve_forever_wrapper(self, _srv, poll_interval=0.1):\n        self.logger.info('Opening tunnel: {0} <> {1}'.format(\n            address_to_str(_srv.local_address),\n            address_to_str(_srv.remote_address))\n        )\n        _srv.serve_forever(poll_interval)\n        self.logger.info('Tunnel: {0} <> {1} released'.format(\n            address_to_str(_srv.local_address),\n            address_to_str(_srv.remote_address))\n        )",
    "docstring": "Wrapper for the server created for a SSH forward"
  },
  {
    "code": "def ctrl_transfer(self,\n                      dev_handle,\n                      bmRequestType,\n                      bRequest,\n                      wValue,\n                      wIndex,\n                      data,\n                      timeout):\n        r\n        _not_implemented(self.ctrl_transfer)",
    "docstring": "r\"\"\"Perform a control transfer on the endpoint 0.\n\n        The direction of the transfer is inferred from the bmRequestType\n        field of the setup packet.\n\n        dev_handle is the value returned by the open_device() method.\n        bmRequestType, bRequest, wValue and wIndex are the same fields\n        of the setup packet. data is an array object, for OUT requests\n        it contains the bytes to transmit in the data stage and for\n        IN requests it is the buffer to hold the data read. The number\n        of bytes requested to transmit or receive is equal to the length\n        of the array times the data.itemsize field. The timeout parameter\n        specifies a time limit to the operation in miliseconds.\n\n        Return the number of bytes written (for OUT transfers) or the data\n        read (for IN transfers), as an array.array object."
  },
  {
    "code": "def get_subscriptions(self, limit=100, offset=0, params={}):\n        url = self.SUBSCRIPTIONS_URL + \"?limit=%s&offset=%s\" % (limit, offset)\n        for key, value in params.items():\n            if key is 'ids':\n                value = \",\".join(value)\n            url += '&%s=%s' % (key, value)\n        connection = Connection(self.token)\n        connection.set_url(self.production, url)\n        return connection.get_request()",
    "docstring": "Get all subscriptions"
  },
  {
    "code": "def read_hdf5_array(source, path=None, array_type=Array):\n    dataset = io_hdf5.find_dataset(source, path=path)\n    attrs = dict(dataset.attrs)\n    try:\n        attrs['channel'] = _unpickle_channel(attrs['channel'])\n    except KeyError:\n        pass\n    for key in attrs:\n        if isinstance(attrs[key], bytes):\n            attrs[key] = attrs[key].decode('utf-8')\n    return array_type(dataset[()], **attrs)",
    "docstring": "Read an `Array` from the given HDF5 object\n\n    Parameters\n    ----------\n    source : `str`, :class:`h5py.HLObject`\n        path to HDF file on disk, or open `h5py.HLObject`.\n\n    path : `str`\n        path in HDF hierarchy of dataset.\n\n    array_type : `type`\n        desired return type"
  },
  {
    "code": "def request_done(self, request):\n        if self._requests is None:\n            return\n        assert request == self._requests[0], \"Unexpected request done\"\n        del self._requests[0]\n        if request.persistent:\n            if self._requests:\n                self._requests[0].activate()\n        else:\n            self.transport.loseConnection()",
    "docstring": "Called by the active request when it is done writing"
  },
  {
    "code": "def symbolize(flt: float) -> sympy.Symbol:\n    try:\n        ratio = rationalize(flt)\n        res = sympy.simplify(ratio)\n    except ValueError:\n        ratio = rationalize(flt/np.pi)\n        res = sympy.simplify(ratio) * sympy.pi\n    return res",
    "docstring": "Attempt to convert a real number into a simpler symbolic\n    representation.\n\n    Returns:\n        A sympy Symbol. (Convert to string with str(sym) or to latex with\n            sympy.latex(sym)\n    Raises:\n        ValueError:     If cannot simplify float"
  },
  {
    "code": "def start_wsgi_server(port, addr='', registry=REGISTRY):\n    app = make_wsgi_app(registry)\n    httpd = make_server(addr, port, app, handler_class=_SilentHandler)\n    t = threading.Thread(target=httpd.serve_forever)\n    t.daemon = True\n    t.start()",
    "docstring": "Starts a WSGI server for prometheus metrics as a daemon thread."
  },
  {
    "code": "def decode_html(html):\n    if isinstance(html, unicode):\n        return html\n    match = CHARSET_META_TAG_PATTERN.search(html)\n    if match:\n        declared_encoding = match.group(1).decode(\"ASCII\")\n        with ignored(LookupError):\n            return html.decode(declared_encoding, \"ignore\")\n    with ignored(UnicodeDecodeError):\n        return html.decode(\"utf8\")\n    text = TAG_MARK_PATTERN.sub(to_bytes(\" \"), html)\n    diff = text.decode(\"utf8\", \"ignore\").encode(\"utf8\")\n    sizes = len(diff), len(text)\n    if abs(len(text) - len(diff)) < max(sizes) * 0.01:\n        return html.decode(\"utf8\", \"ignore\")\n    encoding = \"utf8\"\n    encoding_detector = chardet.detect(text)\n    if encoding_detector[\"encoding\"]:\n        encoding = encoding_detector[\"encoding\"]\n    return html.decode(encoding, \"ignore\")",
    "docstring": "Converts bytes stream containing an HTML page into Unicode.\n    Tries to guess character encoding from meta tag of by \"chardet\" library."
  },
  {
    "code": "def consecutive_ones_property(sets, universe=None):\n    if universe is None:\n        universe = set()\n        for S in sets:\n            universe |= set(S)\n    tree = PQ_tree(universe)\n    try:\n        for S in sets:\n            tree.reduce(S)\n        return tree.border()\n    except IsNotC1P:\n        return None",
    "docstring": "Check the consecutive ones property.\n\n    :param list sets: is a list of subsets of the ground set.\n    :param groundset: is the set of all elements,\n                by default it is the union of the given sets\n    :returns: returns a list of the ordered ground set where\n              every given set is consecutive,\n              or None if there is no solution.\n    :complexity: O(len(groundset) * len(sets))\n    :disclaimer: an optimal implementation would have complexity\n                 O(len(groundset) + len(sets) + sum(map(len,sets))),\n                 and there are more recent easier algorithms for this problem."
  },
  {
    "code": "def translate_labels(val):\n    if not isinstance(val, dict):\n        if not isinstance(val, list):\n            val = split(val)\n        new_val = {}\n        for item in val:\n            if isinstance(item, dict):\n                if len(item) != 1:\n                    raise SaltInvocationError('Invalid label(s)')\n                key = next(iter(item))\n                val = item[key]\n            else:\n                try:\n                    key, val = split(item, '=', 1)\n                except ValueError:\n                    key = item\n                    val = ''\n            if not isinstance(key, six.string_types):\n                key = six.text_type(key)\n            if not isinstance(val, six.string_types):\n                val = six.text_type(val)\n            new_val[key] = val\n        val = new_val\n    return val",
    "docstring": "Can either be a list of label names, or a list of name=value pairs. The API\n    can accept either a list of label names or a dictionary mapping names to\n    values, so the value we translate will be different depending on the input."
  },
  {
    "code": "def filter(args):\n    p = OptionParser(filter.__doc__)\n    p.add_option(\"--less\", default=False, action=\"store_true\",\n                 help=\"filter the sizes < certain cutoff [default: >=]\")\n    p.set_outfile()\n    opts, args = p.parse_args(args)\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n    fastafile, cutoff = args\n    try:\n        cutoff = int(cutoff)\n    except ValueError:\n        sys.exit(not p.print_help())\n    f = Fasta(fastafile, lazy=True)\n    fw = must_open(opts.outfile, \"w\")\n    for name, rec in f.iteritems_ordered():\n        if opts.less and len(rec) >= cutoff:\n            continue\n        if (not opts.less) and len(rec) < cutoff:\n            continue\n        SeqIO.write([rec], fw, \"fasta\")\n        fw.flush()\n    return fw.name",
    "docstring": "%prog filter fastafile 100\n\n    Filter the FASTA file to contain records with size >= or <= certain cutoff."
  },
  {
    "code": "def get_as_nullable_parameters(self, key):\n        value = self.get_as_nullable_map(key)\n        return Parameters(value) if value != None else None",
    "docstring": "Converts map element into an Parameters or returns null if conversion is not possible.\n\n        :param key: a key of element to get.\n\n        :return: Parameters value of the element or null if conversion is not supported."
  },
  {
    "code": "def blast(args):\n    p = OptionParser(blast.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(not p.print_help())\n    btabfile, = args\n    btab = Btab(btabfile)\n    for b in btab:\n        print(b.blastline)",
    "docstring": "%prog blast btabfile\n\n    Convert to BLAST -m8 format."
  },
  {
    "code": "def to_mongo(self):\n        d = copy.copy(self._fields)\n        for k, v in self._slices.items():\n            d[k] = {'$slice': v}\n        return d",
    "docstring": "Translate projection to MongoDB query form.\n\n        :return: Dictionary to put into a MongoDB JSON query\n        :rtype: dict"
  },
  {
    "code": "def isfile(self, path, follow_symlinks=True):\n        return self._is_of_type(path, S_IFREG, follow_symlinks)",
    "docstring": "Determine if path identifies a regular file.\n\n        Args:\n            path: Path to filesystem object.\n\n        Returns:\n            `True` if path points to a regular file (following symlinks).\n\n        Raises:\n            TypeError: if path is None."
  },
  {
    "code": "def fetch(self, raise_exc=True):\n        self._request(GET, raise_exc=raise_exc)\n        self.fetched = True\n        return self.state.copy()",
    "docstring": "Performs a GET request to the uri of this navigator"
  },
  {
    "code": "def update_snapshot_schedule(cls, cluster_id_label, s3_location=None, frequency_unit=None, frequency_num=None, status=None):\n        conn = Qubole.agent(version=Cluster.api_version)\n        data = {}\n        if s3_location is not None:\n            data[\"s3_location\"] = s3_location\n        if frequency_unit is not None:\n            data[\"frequency_unit\"] = frequency_unit\n        if frequency_num is not None:\n            data[\"frequency_num\"] = frequency_num\n        if status is not None:\n            data[\"status\"] = status\n        return conn.put(cls.element_path(cluster_id_label) + \"/snapshot_schedule\", data)",
    "docstring": "Update for snapshot schedule"
  },
  {
    "code": "def migrate(belstr: str) -> str:\n    bo.ast = bel.lang.partialparse.get_ast_obj(belstr, \"2.0.0\")\n    return migrate_ast(bo.ast).to_string()",
    "docstring": "Migrate BEL 1 to 2.0.0\n\n    Args:\n        bel: BEL 1\n\n    Returns:\n        bel: BEL 2"
  },
  {
    "code": "def atanh(x):\n    if isinstance(x, UncertainFunction):\n        mcpts = np.arctanh(x._mcpts)\n        return UncertainFunction(mcpts)\n    else:\n        return np.arctanh(x)",
    "docstring": "Inverse hyperbolic tangent"
  },
  {
    "code": "def prob(self, pw):\n        tokens = self.pcfgtokensofw(pw)\n        S, tokens = tokens[0], tokens[1:]\n        l = len(tokens)\n        assert l % 2 == 0, \"Expecting even number of tokens!. got {}\".format(tokens)\n        p = float(self._T.get(S, 0.0)) / sum(v for k, v in self._T.items('__S__'))\n        for i, t in enumerate(tokens):\n            f = self._T.get(t, 0.0)\n            if f == 0:\n                return 0.0\n            if i < l / 2:\n                p /= f\n            else:\n                p *= f\n        return p",
    "docstring": "Return the probability of pw under the Weir PCFG model.\n        P[{S -> L2D1Y3, L2 -> 'ab', D1 -> '1', Y3 -> '!@#'}]"
  },
  {
    "code": "def connect(self, protocolFactory):\n        deferred = self._startProcess()\n        deferred.addCallback(self._connectRelay, protocolFactory)\n        deferred.addCallback(self._startRelay)\n        return deferred",
    "docstring": "Starts a process and connect a protocol to it."
  },
  {
    "code": "def absolute_magnitude(distance_modulus,g,r,prob=None):\n    V = g - 0.487*(g - r) - 0.0249\n    flux = np.sum(10**(-(V-distance_modulus)/2.5))\n    Mv = -2.5*np.log10(flux)\n    return Mv",
    "docstring": "Calculate the absolute magnitude from a set of bands"
  },
  {
    "code": "def _dict_to_obj(self, d):\n    if JsonEncoder.TYPE_ID not in d:\n      return d\n    type_name = d.pop(JsonEncoder.TYPE_ID)\n    if type_name in _TYPE_NAME_TO_DECODER:\n      decoder = _TYPE_NAME_TO_DECODER[type_name]\n      return decoder(d)\n    else:\n      raise TypeError(\"Invalid type %s.\", type_name)",
    "docstring": "Converts a dictionary of json object to a Python object."
  },
  {
    "code": "def devserver_cmd(argv=sys.argv[1:]):\n    arguments = docopt(devserver_cmd.__doc__, argv=argv)\n    initialize_config()\n    app.run(\n        host=arguments['--host'],\n        port=int(arguments['--port']),\n        debug=int(arguments['--debug']),\n        )",
    "docstring": "\\\nServe the web API for development.\n\nUsage:\n  pld-devserver [options]\n\nOptions:\n  -h --help               Show this screen.\n\n  --host=<host>           The host to use [default: 0.0.0.0].\n\n  --port=<port>           The port to use [default: 5000].\n\n  --debug=<debug>         Whether or not to use debug mode [default: 0]."
  },
  {
    "code": "def canonical_new_peer_list( self, peers_to_add ):\n        new_peers = list(set(self.new_peers + peers_to_add))\n        random.shuffle( new_peers )\n        tmp = []\n        for peer in new_peers:\n            tmp.append( self.canonical_peer(peer) )\n        new_peers = tmp\n        if self.my_hostport in new_peers:\n            new_peers.remove(self.my_hostport)\n        return new_peers",
    "docstring": "Make a list of canonical new peers, using the\n        self.new_peers and the given peers to add\n\n        Return a shuffled list of canonicalized host:port\n        strings."
  },
  {
    "code": "def qteUpdateLogSlot(self):\n        log = self.logHandler.fetch(start=self.qteLogCnt)\n        self.qteLogCnt += len(log)\n        if not len(log):\n            return\n        log_pruned = []\n        last_entry = log[0]\n        num_rep = -1\n        for cur_entry in log:\n            if last_entry.msg == cur_entry.msg:\n                num_rep += 1\n            else:\n                log_pruned.append([last_entry, num_rep])\n                num_rep = 0\n                last_entry = cur_entry\n        log_pruned.append([cur_entry, num_rep])\n        log_formatted = \"\"\n        for cur_entry in log_pruned:\n            log_formatted += self.qteFormatMessage(cur_entry[0], cur_entry[1])\n            log_formatted + '\\n'\n        self.qteText.insertHtml(log_formatted)\n        self.qteMoveToEndOfBuffer()\n        if self.qteAutoActivate:\n            self.qteAutoActivate = False\n            self.qteMain.qteMakeAppletActive(self)",
    "docstring": "Fetch and display the next batch of log messages."
  },
  {
    "code": "def add_alias(agent, prefix, alias):\n    return _broadcast(agent, AddMappingManager, RecordType.record_CNAME,\n                      prefix, alias)",
    "docstring": "Adds an alias mapping with a contract.\n    It has high latency but gives some kind of guarantee."
  },
  {
    "code": "def info_hash_base32(self):\n        if getattr(self, '_data', None):\n            return b32encode(sha1(bencode(self._data['info'])).digest())\n        else:\n            raise exceptions.TorrentNotGeneratedException",
    "docstring": "Returns the base32 info hash of the torrent. Useful for generating\n        magnet links.\n\n        .. note:: ``generate()`` must be called first."
  },
  {
    "code": "def write_content(self, content, destination):\n        directory = os.path.dirname(destination)\n        if directory and not os.path.exists(directory):\n            os.makedirs(directory)\n        with io.open(destination, 'w', encoding='utf-8') as f:\n            f.write(content)\n        return destination",
    "docstring": "Write given content to destination path.\n\n        It will create needed directory structure first if it contain some\n        directories that does not allready exists.\n\n        Args:\n            content (str): Content to write to target file.\n            destination (str): Destination path for target file.\n\n        Returns:\n            str: Path where target file has been written."
  },
  {
    "code": "def all_errors(self, joiner=\"; \"):\n    parts = []\n    for pname, errs in self.errors.items():\n      for err in errs:\n        parts.append(\"{0}: {1}\".format(pname, err))\n    return joiner.join(parts)",
    "docstring": "Returns a string representation of all errors recorded for the instance."
  },
  {
    "code": "def safe_type(self, data, tree):\n        if not isinstance(data, list):\n            name = self.__class__.__name__\n            msg = \"did not pass validation against callable: %s\" % name\n            reason = 'expected a list but got %s' % safe_repr(data)\n            raise Invalid(self.schema, tree, reason=reason, pair='value', msg=msg)",
    "docstring": "Make sure that the incoming data complies with the class type we\n        are expecting it to be. In this case, classes that inherit from this\n        base class expect data to be of type ``list``."
  },
  {
    "code": "def read_git_commit_timestamp_for_file(filepath, repo_path=None):\n    repo = git.repo.base.Repo(path=repo_path, search_parent_directories=True)\n    head_commit = repo.head.commit\n    for commit in head_commit.iter_parents(filepath):\n        return commit.committed_datetime\n    raise IOError('File {} not found'.format(filepath))",
    "docstring": "Obtain the timestamp for the most recent commit to a given file in a\n    Git repository.\n\n    Parameters\n    ----------\n    filepath : `str`\n        Repository-relative path for a file.\n    repo_path : `str`, optional\n        Path to the Git repository. Leave as `None` to use the current working\n        directory.\n\n    Returns\n    -------\n    commit_timestamp : `datetime.datetime`\n        The datetime of a the most recent commit to the given file.\n\n    Raises\n    ------\n    IOError\n        Raised if the ``filepath`` does not exist in the Git repository."
  },
  {
    "code": "def compute_K_analytical(self, spacing):\n        assert isinstance(spacing, Number)\n        K = geometric_factors.compute_K_analytical(self.data, spacing)\n        self.data = geometric_factors.apply_K(self.data, K)\n        fix_sign_with_K(self.data)",
    "docstring": "Assuming an equal electrode spacing, compute the K-factor over a\n        homogeneous half-space.\n\n        For more complex grids, please refer to the module:\n        reda.utils.geometric_factors\n\n        Parameters\n        ----------\n        spacing: float\n            Electrode spacing"
  },
  {
    "code": "def sync_files(self, dataset_key):\n        try:\n            self._datasets_api.sync(*(parse_dataset_key(dataset_key)))\n        except _swagger.rest.ApiException as e:\n            raise RestApiError(cause=e)",
    "docstring": "Trigger synchronization process to update all dataset files linked to\n        source URLs.\n\n        :param dataset_key: Dataset identifier, in the form of owner/id\n        :type dataset_key: str\n        :raises RestApiException: If a server error occurs\n\n        Examples\n        --------\n        >>> import datadotworld as dw\n        >>> api_client = dw.api_client()\n        >>> api_client.sync_files('username/test-dataset')  # doctest: +SKIP"
  },
  {
    "code": "def detect(self, text):\n    t = text.encode(\"utf-8\")\n    reliable, index, top_3_choices = cld2.detect(t, bestEffort=False)\n    if not reliable:\n      self.reliable = False\n      reliable, index, top_3_choices = cld2.detect(t, bestEffort=True)\n      if not self.quiet:\n        if not reliable:\n          raise UnknownLanguage(\"Try passing a longer snippet of text\")\n        else:\n          logger.warning(\"Detector is not able to detect the language reliably.\")\n    self.languages = [Language(x) for x in top_3_choices]\n    self.language = self.languages[0]\n    return self.language",
    "docstring": "Decide which language is used to write the text.\n\n    The method tries first to detect the language with high reliability. If\n    that is not possible, the method switches to best effort strategy.\n\n\n    Args:\n      text (string): A snippet of text, the longer it is the more reliable we\n                     can detect the language used to write the text."
  },
  {
    "code": "def keep_only_update_source_in_field(field, root, head, update):\n    update_sources = {source.lower() for source in get_value(thaw(update), '.'.join([field, 'source']), [])}\n    if len(update_sources) != 1:\n        return root, head, update\n    source = update_sources.pop()\n    if field in root:\n        root = root.set(field, remove_elements_with_source(source, root[field]))\n    if field in head:\n        head = head.set(field, remove_elements_with_source(source, head[field]))\n    return root, head, update",
    "docstring": "Remove elements from root and head where ``source`` matches the update.\n\n    This is useful if the update needs to overwrite all elements with the same\n    source.\n\n    .. note::\n        If the update doesn't contain exactly one source in ``field``, the\n        records are returned with no modifications.\n\n    Args:\n        field (str): the field to filter out.\n        root (pmap): the root record, whose ``field`` will be cleaned.\n        head (pmap): the head record, whose ``field`` will be cleaned.\n        update (pmap): the update record, from which the ``source`` is read.\n\n    Returns:\n        tuple: ``(root, head, update)`` with some elements filtered out from\n            ``root`` and ``head``."
  },
  {
    "code": "def results(self, *args, **kwargs):\n        def worker():\n            kwargs['page'] = 1\n            while True:\n                response = self.client(*args, **kwargs)\n                if isinstance(response, list):\n                    yield response\n                    break\n                elif _is_page(response):\n                    yield response['results']\n                    if response['next']:\n                        kwargs['page'] += 1\n                    else:\n                        break\n                else:\n                    raise NoResultsError(response)\n        return itertools.chain.from_iterable(worker())",
    "docstring": "Return an iterator with all pages of data.\n           Return NoResultsError with response if there is unexpected data."
  },
  {
    "code": "def ContainsNone(self, *values):\n    self._awql = self._CreateMultipleValuesCondition(values, 'CONTAINS_NONE')\n    return self._query_builder",
    "docstring": "Sets the type of the WHERE clause as \"contains none\".\n\n    Args:\n      *values: The values to be used in the WHERE condition.\n\n    Returns:\n      The query builder that this WHERE builder links to."
  },
  {
    "code": "def get_module_attr(module_filename, module_attr, namespace=None):\n    if namespace is None:\n        namespace = {}\n    module_filename = os.path.abspath(module_filename)\n    namespace['__file__'] = module_filename\n    module_dir = os.path.dirname(module_filename)\n    old_cwd = os.getcwd()\n    old_sys_path = sys.path[:]\n    try:\n        os.chdir(module_dir)\n        sys.path.append(module_dir)\n        with open(module_filename, 'r') as mf:\n            exec(compile(mf.read(), module_filename, 'exec'), namespace)\n        return namespace[module_attr]\n    finally:\n        os.chdir(old_cwd)\n        sys.path = old_sys_path",
    "docstring": "Get an attribute from a module.\n\n    This uses exec to load the module with a private namespace, and then\n    plucks and returns the given attribute from that module's namespace.\n\n    Note that, while this method doesn't have any explicit unit tests, it is\n    tested implicitly by the doctor's own documentation. The Sphinx\n    build process will fail to generate docs if this does not work.\n\n    :param str module_filename: Path to the module to execute (e.g.\n        \"../src/app.py\").\n    :param str module_attr: Attribute to pluck from the module's namespace.\n        (e.g. \"app\").\n    :param dict namespace: Optional namespace. If one is not passed, an empty\n        dict will be used instead. Note that this function mutates the passed\n        namespace, so you can inspect a passed dict after calling this method\n        to see how the module changed it.\n    :returns: The attribute from the module.\n    :raises KeyError: if the module doesn't have the given attribute."
  },
  {
    "code": "def __identify_user(self, username, csrf):\n        data = {\n            \"username\": username,\n            \"csrf\": csrf,\n            \"apiClient\": \"WEB\",\n            \"bindDevice\": \"false\",\n            \"skipLinkAccount\": \"false\",\n            \"redirectTo\": \"\",\n            \"skipFirstUse\": \"\",\n            \"referrerId\": \"\",\n        }\n        r = self.post(\"/login/identifyUser\", data)\n        if r.status_code == requests.codes.ok:\n            result = r.json()\n            new_csrf = getSpHeaderValue(result, CSRF_KEY)\n            auth_level = getSpHeaderValue(result, AUTH_LEVEL_KEY)\n            return (new_csrf, auth_level)\n        return (None, None)",
    "docstring": "Returns reusable CSRF code and the auth level as a 2-tuple"
  },
  {
    "code": "def _import_plugins(self):\n        if self.detected:\n            return\n        self.scanLock.acquire()\n        if self.detected:\n            return\n        try:\n            import_apps_submodule(\"content_plugins\")\n            self.detected = True\n        finally:\n            self.scanLock.release()",
    "docstring": "Internal function, ensure all plugin packages are imported."
  },
  {
    "code": "def _vertex_net_cost(vertex, v2n, placements, has_wrap_around_links, machine):\n    total_cost = 0.0\n    for net in v2n[vertex]:\n        total_cost += _net_cost(net, placements, has_wrap_around_links,\n                                machine)\n    return total_cost",
    "docstring": "Get the total cost of the nets connected to the given vertex.\n\n    Parameters\n    ----------\n    vertex\n        The vertex whose nets we're interested in.\n    v2n : {vertex: [:py:class:`rig.netlist.Net`, ...], ...}\n    placements : {vertex: (x, y), ...}\n    has_wrap_around_links : bool\n    machine : :py:class:`rig.place_and_route.Machine`\n\n    Returns\n    -------\n    float"
  },
  {
    "code": "def abort_now ():\n    if os.name == 'posix':\n        import signal\n        os.kill(os.getpid(), signal.SIGTERM)\n        time.sleep(1)\n        os.kill(os.getpid(), signal.SIGKILL)\n    elif os.name == 'nt':\n        os.abort()\n    else:\n        os._exit(3)",
    "docstring": "Force exit of current process without cleanup."
  },
  {
    "code": "def warning(message):\n\timport lltk.config as config\n\tif config['warnings']:\n\t\ttry:\n\t\t\tfrom termcolor import colored\n\t\texcept ImportError:\n\t\t\tdef colored(message, color):\n\t\t\t\treturn message\n\t\tprint colored('@LLTK-WARNING: ' + message, 'red')",
    "docstring": "Prints a message if warning mode is enabled."
  },
  {
    "code": "def search(self,\n               id_list: List,\n               negated_classes: List,\n               limit: Optional[int],\n               method: Optional) -> List[SimResult]:\n        raise NotImplementedError",
    "docstring": "Given an input list of classes or individuals,\n        provides a ranking of similar profiles"
  },
  {
    "code": "def mimf_ferrario(mi):\n    mf=-0.00012336*mi**6+0.003160*mi**5-0.02960*mi**4+\\\n      0.12350*mi**3-0.21550*mi**2+0.19022*mi+0.46575\n    return mf",
    "docstring": "Curvature MiMf from Ferrario etal. 2005MNRAS.361.1131."
  },
  {
    "code": "def GetOptions(self):\n    if self._options:\n      return self._options\n    from google.protobuf import descriptor_pb2\n    try:\n      options_class = getattr(descriptor_pb2, self._options_class_name)\n    except AttributeError:\n      raise RuntimeError('Unknown options class name %s!' %\n                         (self._options_class_name))\n    self._options = options_class()\n    return self._options",
    "docstring": "Retrieves descriptor options.\n\n    This method returns the options set or creates the default options for the\n    descriptor."
  },
  {
    "code": "def actualize_source_type (self, sources, prop_set):\n        assert is_iterable_typed(sources, VirtualTarget)\n        assert isinstance(prop_set, property_set.PropertySet)\n        result = []\n        for i in sources:\n            scanner = None\n            if i.type ():\n                scanner = b2.build.type.get_scanner (i.type (), prop_set)\n            r = i.actualize (scanner)\n            result.append (r)\n        return result",
    "docstring": "Helper for 'actualize_sources'.\n            For each passed source, actualizes it with the appropriate scanner.\n            Returns the actualized virtual targets."
  },
  {
    "code": "def patch_wave_header(body):\n    length = len(body)\n    padded = length + length % 2\n    total = WAVE_HEADER_LENGTH + padded\n    header = copy.copy(WAVE_HEADER)\n    header[4:8] = bytearray(struct.pack('<I', total))\n    header += bytearray(struct.pack('<I', length))\n    data = header + body\n    if length != padded:\n        data = data + bytearray([0])\n    return data",
    "docstring": "Patch header to the given wave body.\n\n    :param body: the wave content body, it should be bytearray."
  },
  {
    "code": "def mifare_classic_read_block(self, block_number):\n        response = self.call_function(PN532_COMMAND_INDATAEXCHANGE,\n                                      params=[0x01, MIFARE_CMD_READ, block_number & 0xFF],\n                                      response_length=17)\n        if response[0] != 0x00:\n            return None\n        return response[1:]",
    "docstring": "Read a block of data from the card.  Block number should be the block\n        to read.  If the block is successfully read a bytearray of length 16 with\n        data starting at the specified block will be returned.  If the block is\n        not read then None will be returned."
  },
  {
    "code": "def pull_full_properties(self):\n        full_properties = self.manager.session.get(self._uri)\n        self._properties = dict(full_properties)\n        self._properties_timestamp = int(time.time())\n        self._full_properties = True",
    "docstring": "Retrieve the full set of resource properties and cache them in this\n        object.\n\n        Authorization requirements:\n\n        * Object-access permission to this resource.\n\n        Raises:\n\n          :exc:`~zhmcclient.HTTPError`\n          :exc:`~zhmcclient.ParseError`\n          :exc:`~zhmcclient.AuthError`\n          :exc:`~zhmcclient.ConnectionError`"
  },
  {
    "code": "def thread(self, value: str):\n        if value is not None and not isinstance(value, str):\n            raise TypeError(\"'thread' MUST be a string\")\n        self._thread = value",
    "docstring": "Set thread id of the message\n\n        Args:\n            value (str): the thread id"
  },
  {
    "code": "def cli_login(self, password='', captcha='', email_code='', twofactor_code='', language='english'):\n        while True:\n            try:\n                return self.login(password, captcha, email_code, twofactor_code, language)\n            except (LoginIncorrect, CaptchaRequired) as exp:\n                email_code = twofactor_code = ''\n                if isinstance(exp, LoginIncorrect):\n                    prompt = (\"Enter password for %s: \" if not password else\n                              \"Invalid password for %s. Enter password: \")\n                    password = getpass(prompt % repr(self.username))\n                if isinstance(exp, CaptchaRequired):\n                    prompt = \"Solve CAPTCHA at %s\\nCAPTCHA code: \" % self.captcha_url\n                    captcha = _cli_input(prompt)\n                else:\n                    captcha = ''\n            except EmailCodeRequired:\n                prompt = (\"Enter email code: \" if not email_code else\n                          \"Incorrect code. Enter email code: \")\n                email_code, twofactor_code = _cli_input(prompt), ''\n            except TwoFactorCodeRequired:\n                prompt = (\"Enter 2FA code: \" if not twofactor_code else\n                          \"Incorrect code. Enter 2FA code: \")\n                email_code, twofactor_code = '', _cli_input(prompt)",
    "docstring": "Generates CLI prompts to perform the entire login process\n\n        :param password: password, if it wasn't provided on instance init\n        :type  password: :class:`str`\n        :param captcha: text reponse for captcha challenge\n        :type  captcha: :class:`str`\n        :param email_code: email code for steam guard\n        :type  email_code: :class:`str`\n        :param twofactor_code: 2FA code for steam guard\n        :type  twofactor_code: :class:`str`\n        :param language: select language for steam web pages (sets language cookie)\n        :type  language: :class:`str`\n        :return: a session on success and :class:`None` otherwise\n        :rtype: :class:`requests.Session`, :class:`None`\n\n        .. code:: python\n\n            In [3]: user.cli_login()\n            Enter password for 'steamuser':\n            Solve CAPTCHA at https://steamcommunity.com/login/rendercaptcha/?gid=1111111111111111111\n            CAPTCHA code: 123456\n            Invalid password for 'steamuser'. Enter password:\n            Solve CAPTCHA at https://steamcommunity.com/login/rendercaptcha/?gid=2222222222222222222\n            CAPTCHA code: abcdef\n            Enter 2FA code: AB123\n            Out[3]: <requests.sessions.Session at 0x6fffe56bef0>"
  },
  {
    "code": "def get_installed_extension(name,\n                            user=None,\n                            host=None,\n                            port=None,\n                            maintenance_db=None,\n                            password=None,\n                            runas=None):\n    return installed_extensions(user=user,\n                                host=host,\n                                port=port,\n                                maintenance_db=maintenance_db,\n                                password=password,\n                                runas=runas).get(name, None)",
    "docstring": "Get info about an installed postgresql extension\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' postgres.get_installed_extension plpgsql"
  },
  {
    "code": "def resource_filename(package_or_requirement, resource_name):\n    if pkg_resources.resource_exists(package_or_requirement, resource_name):\n        return pkg_resources.resource_filename(package_or_requirement, resource_name)\n    path = _search_in_share_folders(package_or_requirement, resource_name)\n    if path:\n        return path\n    raise RuntimeError(\"Resource {} not found in {}\".format(package_or_requirement, resource_name))",
    "docstring": "Similar to pkg_resources.resource_filename but if the resource it not found via pkg_resources\n    it also looks in a predefined list of paths in order to find the resource\n\n    :param package_or_requirement: the module in which the resource resides\n    :param resource_name: the name of the resource\n    :return: the path to the resource\n    :rtype: str"
  },
  {
    "code": "def _CreateDynamicDisplayAdSettings(media_service, opener):\n  image = _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF')\n  logo = {\n      'type': 'IMAGE',\n      'mediaId': image['mediaId'],\n      'xsi_type': 'Image'\n  }\n  dynamic_settings = {\n      'landscapeLogoImage': logo,\n      'pricePrefix': 'as low as',\n      'promoText': 'Free shipping!',\n      'xsi_type': 'DynamicSettings',\n  }\n  return dynamic_settings",
    "docstring": "Creates settings for dynamic display ad.\n\n  Args:\n    media_service: a SudsServiceProxy instance for AdWords's MediaService.\n    opener: an OpenerDirector instance.\n\n  Returns:\n    The dynamic display ad settings."
  },
  {
    "code": "def get_lib_from(search_directory, lib_extension='.so'):\n    for root, dirs, files in walk(search_directory):\n        for file in files:\n            if file.endswith(lib_extension):\n                print('get_lib_from: {}\\n\\t- {}'.format(\n                    search_directory, join(root, file)))\n                return join(root, file)\n    return None",
    "docstring": "Scan directories recursively until find any file with the given\n    extension. The default extension to search is ``.so``."
  },
  {
    "code": "def execute(self, sql, *args, **kwargs):\n    try:\n      self.cursor.execute(sql, *args)\n    except self.sqlite3.InterfaceError, msg:\n      raise self.sqlite3.InterfaceError(unicode(msg) + '\\nTry converting types or pickling.')\n    rows = self.cursor.fetchall()\n    self.__commit_if_necessary(kwargs)\n    if None == self.cursor.description:\n      return None\n    else:\n      colnames = [d[0].decode('utf-8') for d in self.cursor.description]\n      rawdata = [OrderedDict(zip(colnames,row)) for row in rows]\n      return rawdata",
    "docstring": "Run raw SQL on the database, and receive relaxing output.\n    This is sort of the foundational method that most of the\n    others build on."
  },
  {
    "code": "def set_direct(self, address_value_dict):\n        with self._lock:\n            for address, value in address_value_dict.items():\n                self._validate_write(address)\n                if address in self._state:\n                    self._state[address].set_result(result=value)\n                else:\n                    fut = _ContextFuture(address=address)\n                    self._state[address] = fut\n                    fut.set_result(result=value)",
    "docstring": "Called in the context manager's set method to either overwrite the\n        value for an address, or create a new future and immediately set a\n        value in the future.\n\n        Args:\n            address_value_dict (dict of str:bytes): The unique full addresses\n                with bytes to set at that address.\n\n        Raises:\n            AuthorizationException"
  },
  {
    "code": "def reorder(self, dst_order, arr, src_order=None):\n        if dst_order is None:\n            dst_order = self.viewer.rgb_order\n        if src_order is None:\n            src_order = self.rgb_order\n        if src_order != dst_order:\n            arr = trcalc.reorder_image(dst_order, arr, src_order)\n        return arr",
    "docstring": "Reorder the output array to match that needed by the viewer."
  },
  {
    "code": "def execute_once(self, string):\n        for rule in self.rules:\n            if rule[0] in string:\n                pos = string.find(rule[0])\n                self.last_rule = rule\n                return string[:pos] + rule[1] + string[pos+len(rule[0]):]\n        self.last_rule = None\n        return string",
    "docstring": "Execute only one rule."
  },
  {
    "code": "def exit(self):\n        self.client.flush()\n        self.client.close()\n        super(Export, self).exit()",
    "docstring": "Close the Kafka export module."
  },
  {
    "code": "def resolve(self, notes=None):\n        self.set_status(self._redmine.ISSUE_STATUS_ID_RESOLVED, notes=notes)",
    "docstring": "Save all changes and resolve this issue"
  },
  {
    "code": "def force_directed(self,defaultEdgeWeight=None,defaultNodeMass=None,\\\n\t\tdefaultSpringCoefficient=None,defaultSpringLength=None,EdgeAttribute=None,\\\n\t\tisDeterministic=None,maxWeightCutoff=None,minWeightCutoff=None,network=None,\\\n\t\tNodeAttribute=None,nodeList=None,numIterations=None,singlePartition=None,\\\n\t\tType=None,verbose=None):\n\t\tnetwork=check_network(self,network,verbose=verbose)\n\t\tPARAMS=set_param(['defaultEdgeWeight','defaultNodeMass','defaultSpringCoefficient',\\\n\t\t'defaultSpringLength','EdgeAttribute','isDeterministic','maxWeightCutoff',\\\n\t\t'minWeightCutoff','network','NodeAttribute','nodeList','numIterations',\\\n\t\t'singlePartition','Type'],[defaultEdgeWeight,defaultNodeMass,\\\n\t\tdefaultSpringCoefficient,defaultSpringLength,EdgeAttribute,isDeterministic,\\\n\t\tmaxWeightCutoff,minWeightCutoff,network,NodeAttribute,nodeList,numIterations,\\\n\t\tsinglePartition,Type])\n\t\tresponse=api(url=self.__url+\"/force-directed\", PARAMS=PARAMS, method=\"POST\", verbose=verbose)\n\t\treturn response",
    "docstring": "Execute the Prefuse Force Directed Layout on a network\n\n\t\t:param defaultEdgeWeight (string, optional): The default edge weight to con\n\t\t\tsider, default is 0.5\n\t\t:param defaultNodeMass (string, optional): Default Node Mass, in numeric va\n\t\t\tlue\n\t\t:param defaultSpringCoefficient (string, optional): Default Spring Coeffici\n\t\t\tent, in numeric value\n\t\t:param defaultSpringLength (string, optional): Default Spring Length, in nu\n\t\t\tmeric value\n\t\t:param EdgeAttribute (string, optional): The name of the edge column contai\n\t\t\tning numeric values that will be used as weights in the layout algor\n\t\t\tithm. Only columns containing numeric values are shown\n\t\t:param isDeterministic (string, optional): Force deterministic layouts (slo\n\t\t\twer); boolean values only, true or false; defaults to false\n\t\t:param maxWeightCutoff (string, optional): The maximum edge weight to consi\n\t\t\tder, default to the Double.MAX value\n\t\t:param minWeightCutoff (string, optional): The minimum edge weight to consi\n\t\t\tder, numeric values, default is 0\n\t\t:param network (string, optional): Specifies a network by name, or by SUID\n\t\t\tif the prefix SUID: is used. The keyword CURRENT, or a blank value c\n\t\t\tan also be used to specify the current network.\n\t\t:param NodeAttribute (string, optional): The name of the node column contai\n\t\t\tning numeric values that will be used as weights in the layout algor\n\t\t\tithm. Only columns containing numeric values are shown\n\t\t:param nodeList (string, optional): Specifies a list of nodes. The keywords\n\t\t\t\tall, selected, or unselected can be used to specify nodes by their\n\t\t\tselection state. The pattern COLUMN:VALUE sets this parameter to any\n\t\t\t\trows that contain the specified column value; if the COLUMN prefix\n\t\t\tis not used, the NAME column is matched by default. A list of COLUMN\n\t\t\t:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be\n\t\t\tused to match multiple values.\n\t\t:param numIterations (string, optional): Number of Iterations, in numeric v\n\t\t\talue\n\t\t:param singlePartition (string, optional): Don't partition graph before lay\n\t\t\tout; boolean values only, true or false; defaults to false\n\t\t:param Type (string, optional): How to interpret weight values; must be one\n\t\t\t\tof Heuristic, -Log(value), 1 - normalized value and normalized valu\n\t\t\te. Defaults to Heuristic = ['Heuristic', '-Log(value)', '1 - normali\n\t\t\tzed value', 'normalized value']"
  },
  {
    "code": "def multivariate_hypergeometric_expval(n, m):\n    m = np.asarray(m, float)\n    return n * (m / m.sum())",
    "docstring": "Expected value of multivariate hypergeometric distribution.\n\n    Parameters:\n      - `n` : Number of draws.\n      - `m` : Number of items in each categoy."
  },
  {
    "code": "def uninstall_hook(ctx):\n    try:\n        lint_config = ctx.obj[0]\n        hooks.GitHookInstaller.uninstall_commit_msg_hook(lint_config)\n        hook_path = hooks.GitHookInstaller.commit_msg_hook_path(lint_config)\n        click.echo(u\"Successfully uninstalled gitlint commit-msg hook from {0}\".format(hook_path))\n        ctx.exit(0)\n    except hooks.GitHookInstallerError as e:\n        click.echo(ustr(e), err=True)\n        ctx.exit(GIT_CONTEXT_ERROR_CODE)",
    "docstring": "Uninstall gitlint commit-msg hook."
  },
  {
    "code": "def bbox_flip(bbox, d, rows, cols):\n    if d == 0:\n        bbox = bbox_vflip(bbox, rows, cols)\n    elif d == 1:\n        bbox = bbox_hflip(bbox, rows, cols)\n    elif d == -1:\n        bbox = bbox_hflip(bbox, rows, cols)\n        bbox = bbox_vflip(bbox, rows, cols)\n    else:\n        raise ValueError('Invalid d value {}. Valid values are -1, 0 and 1'.format(d))\n    return bbox",
    "docstring": "Flip a bounding box either vertically, horizontally or both depending on the value of `d`.\n\n    Raises:\n        ValueError: if value of `d` is not -1, 0 or 1."
  },
  {
    "code": "def time_estimate(self, duration, **kwargs):\n        path = '%s/%s/time_estimate' % (self.manager.path, self.get_id())\n        data = {'duration': duration}\n        return self.manager.gitlab.http_post(path, post_data=data, **kwargs)",
    "docstring": "Set an estimated time of work for the object.\n\n        Args:\n            duration (str): Duration in human format (e.g. 3h30)\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabTimeTrackingError: If the time tracking update cannot be done"
  },
  {
    "code": "def compare_config(self):\n        if self.ssh_connection is False:\n            self._open_ssh()\n        self.ssh_device.exit_config_mode()\n        diff = self.ssh_device.send_command(\"show config diff\")\n        return diff.strip()",
    "docstring": "Netmiko is being used to obtain config diffs because pan-python\n        doesn't support the needed command."
  },
  {
    "code": "def _init_grps(code2nt):\n        seen = set()\n        seen_add = seen.add\n        groups = [nt.group for nt in code2nt.values()]\n        return [g for g in groups if not (g in seen or seen_add(g))]",
    "docstring": "Return list of groups in same order as in code2nt"
  },
  {
    "code": "def connect(self, signal, slot, transform=None, condition=None):\n        if not signal in self.signals:\n            print(\"WARNING: {0} is trying to connect a slot to an undefined signal: {1}\".format(self.__class__.__name__,\n                                                                                       str(signal)))\n            return\n        if not hasattr(self, 'connections'):\n            self.connections = {}\n        connection = self.connections.setdefault(signal, {})\n        connection = connection.setdefault(condition, {})\n        connection[slot] = transform",
    "docstring": "Defines a connection between this objects signal and another objects slot\n\n           signal: the signal this class will emit, to cause the slot method to be called\n           receiver: the object containing the slot method to be called\n           slot: the slot method to call\n           transform: an optional value override to pass into the slot method as the first variable\n           condition: only call the slot if the value emitted matches the required value or calling required returns True"
  },
  {
    "code": "def InternalExchange(self, cmd, payload_in):\n    self.logger.debug('payload: ' + str(list(payload_in)))\n    payload = bytearray()\n    payload[:] = payload_in\n    for _ in range(2):\n      self.InternalSend(cmd, payload)\n      ret_cmd, ret_payload = self.InternalRecv()\n      if ret_cmd == UsbHidTransport.U2FHID_ERROR:\n        if ret_payload == UsbHidTransport.ERR_CHANNEL_BUSY:\n          time.sleep(0.5)\n          continue\n        raise errors.HidError('Device error: %d' % int(ret_payload[0]))\n      elif ret_cmd != cmd:\n        raise errors.HidError('Command mismatch!')\n      return ret_payload\n    raise errors.HidError('Device Busy.  Please retry')",
    "docstring": "Sends and receives a message from the device."
  },
  {
    "code": "def __learn_oneself(self):\r\n        if not self.__parent_path or not self.__text_nodes:\r\n            raise Exception(\"This error occurred because the step constructor\\\r\n                            had insufficient textnodes or it had empty string\\\r\n                            for its parent xpath\")\r\n        self.tnodes_cnt = len(self.__text_nodes)\r\n        self.ttl_strlen = sum([len(tnode) for tnode in self.__text_nodes])\r\n        self.avg_strlen = self.ttl_strlen/self.tnodes_cnt",
    "docstring": "calculate cardinality, total and average string length"
  },
  {
    "code": "async def open(self) -> '_BaseAgent':\n        LOGGER.debug('_BaseAgent.open >>>')\n        await self.wallet.open()\n        LOGGER.debug('_BaseAgent.open <<<')\n        return self",
    "docstring": "Context manager entry; open wallet.\n        For use when keeping agent open across multiple calls.\n\n        :return: current object"
  },
  {
    "code": "def variance_larger_than_standard_deviation(x):\n    y = np.var(x)\n    return y > np.sqrt(y)",
    "docstring": "Boolean variable denoting if the variance of x is greater than its standard deviation. Is equal to variance of x\n    being larger than 1\n\n    :param x: the time series to calculate the feature of\n    :type x: numpy.ndarray\n    :return: the value of this feature\n    :return type: bool"
  },
  {
    "code": "def getPlaintextLen(self, ciphertext):\n        completeCiphertextHeader = (len(ciphertext) >= 16)\n        if completeCiphertextHeader is False:\n            raise RecoverableDecryptionError('Incomplete ciphertext header.')\n        ciphertext_header = ciphertext[:16]\n        L = self._ecb_enc_K1.decrypt(ciphertext_header)\n        padding_expected = '\\x00\\x00\\x00\\x00'\n        padding_actual = L[-8:-4]\n        validPadding = (padding_actual == padding_expected)\n        if validPadding is False:\n            raise UnrecoverableDecryptionError(\n                'Invalid padding: ' + padding_actual)\n        message_length = fte.bit_ops.bytes_to_long(L[-8:])\n        msgLenNonNegative = (message_length >= 0)\n        if msgLenNonNegative is False:\n            raise UnrecoverableDecryptionError('Negative message length.')\n        return message_length",
    "docstring": "Given a ``ciphertext`` with a valid header, returns the length of the plaintext payload."
  },
  {
    "code": "def _create_mappings(self, spec):\n        ret = dict(zip(set(spec.fields), set(spec.fields)))\n        ret.update(dict([(n, s.alias) for n, s in spec.fields.items() if s.alias]))\n        return ret",
    "docstring": "Create property name map based on aliases."
  },
  {
    "code": "def get_predecessors(self, head):\n        frozen_head = frozenset(head)\n        if frozen_head not in self._predecessors:\n            return set()\n        return set(self._predecessors[frozen_head].values())",
    "docstring": "Given a head set of nodes, get a list of edges of which the node set\n        is the head of each edge.\n\n        :param head: set of nodes that correspond to the heads of some\n                        (possibly empty) set of edges.\n        :returns: set -- hyperedge_ids of the hyperedges that have head\n                in the head."
  },
  {
    "code": "def _remove_existing(self):\n        for key in self._keys:\n            if key in os.environ:\n                LOG.debug('%r: removing old key %r', self, key)\n                del os.environ[key]\n        self._keys = []",
    "docstring": "When a change is detected, remove keys that existed in the old file."
  },
  {
    "code": "def read_stack_frame(self, structure, offset = 0):\n        aProcess  = self.get_process()\n        stackData = aProcess.read_structure(self.get_fp() + offset, structure)\n        return tuple([ stackData.__getattribute__(name)\n                       for (name, type) in stackData._fields_ ])",
    "docstring": "Reads the stack frame of the thread.\n\n        @type  structure: ctypes.Structure\n        @param structure: Structure of the stack frame.\n\n        @type  offset: int\n        @param offset: Offset from the frame pointer to begin reading.\n            The frame pointer is the same returned by the L{get_fp} method.\n\n        @rtype:  tuple\n        @return: Tuple of elements read from the stack frame. The type of each\n            element matches the types in the stack frame structure."
  },
  {
    "code": "def save_callback(sender, instance, created, update_fields, **kwargs):\n    if validate_instance(instance):\n        status = 'add' if created is True else 'change'\n        change = ''\n        if status == 'change' and 'al_chl' in instance.__dict__.keys():\n            changelog = instance.al_chl.modification\n            change = ' to following changed: {}'.format(changelog)\n        processor(status, sender, instance, update_fields, addition=change)",
    "docstring": "Save object & link logging entry"
  },
  {
    "code": "def magnetic_lat(inc):\n    rad = old_div(np.pi, 180.)\n    paleo_lat = old_div(np.arctan(0.5 * np.tan(inc * rad)), rad)\n    return paleo_lat",
    "docstring": "returns magnetic latitude from inclination"
  },
  {
    "code": "def as_list(func):\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        response = func(*args, **kwargs)\n        if isinstance(response, Response):\n            return response\n        return as_json_list(\n            response,\n            **_serializable_params(request.args, check_groupby=True))\n    return wrapper",
    "docstring": "A decorator used to return a JSON response of a list of model\n        objects. It expects the decorated function to return a list\n        of model instances. It then converts the instances to dicts\n        and serializes them into a json response\n\n        Examples:\n\n            >>> @app.route('/api')\n            ... @as_list\n            ... def list_customers():\n            ...     return Customer.all()"
  },
  {
    "code": "def pseudosample(x):\n    BXs = []\n    for k in range(len(x)):\n        ind = random.randint(0, len(x) - 1)\n        BXs.append(x[ind])\n    return BXs",
    "docstring": "draw a bootstrap sample of x"
  },
  {
    "code": "def repair_url(url):\n    url = url.strip('\\n')\n    if not re.match(r\"^http\", url):\n        url = \"http://\" + url\n    if \"?\" in url:\n        url, _ = url.split('?')\n    if not url.endswith(\"/\"):\n        return url + \"/\"\n    else :\n        return url",
    "docstring": "Fixes URL.\n    @param url: url to repair.\n    @param out: instance of StandardOutput as defined in this lib.\n    @return: Newline characters are stripped from the URL string.\n        If the url string parameter does not start with http, it prepends http://\n        If the url string parameter does not end with a slash, appends a slash.\n        If the url contains a query string, it gets removed."
  },
  {
    "code": "def open(self, auto_commit=None, schema=None):\n        if schema is None:\n            schema = self.schema\n        ac = auto_commit if auto_commit is not None else schema.auto_commit\n        exe = ExecutionContext(self.path, schema=schema, auto_commit=ac)\n        if not os.path.isfile(self.path) or os.path.getsize(self.path) == 0:\n            getLogger().warning(\"DB does not exist at {}. Setup is required.\".format(self.path))\n            if schema is not None and schema.setup_files:\n                for file_path in schema.setup_files:\n                    getLogger().debug(\"Executing script file: {}\".format(file_path))\n                    exe.cur.executescript(self.read_file(file_path))\n            if schema.setup_scripts:\n                for script in schema.setup_scripts:\n                    exe.cur.executescript(script)\n        return exe",
    "docstring": "Create a context to execute queries"
  },
  {
    "code": "def beforeSummaryReport(self, event):\n        self.prof.disable()\n        stats = pstats.Stats(self.prof, stream=event.stream).sort_stats(\n            self.sort)\n        event.stream.writeln(nose2.util.ln('Profiling results'))\n        stats.print_stats()\n        if self.pfile:\n            stats.dump_stats(self.pfile)\n        if self.cachegrind:\n            visualize(self.prof.getstats())",
    "docstring": "Output profiling results"
  },
  {
    "code": "def build_grouped_ownership_map(table,\n                                key_from_row,\n                                value_from_row,\n                                group_key):\n    grouped_rows = groupby(\n        group_key,\n        sa.select(table.c).execute().fetchall(),\n    )\n    return {\n        key: _build_ownership_map_from_rows(\n            rows,\n            key_from_row,\n            value_from_row,\n        )\n        for key, rows in grouped_rows.items()\n    }",
    "docstring": "Builds a dict mapping group keys to maps of keys to to lists of\n    OwnershipPeriods, from a db table."
  },
  {
    "code": "def add_aggregate(self, name, data_fac):\n        @self.add_target(name)\n        def wrap(outdir, c):\n            return data_fac()",
    "docstring": "Add an aggregate target to this nest.\n\n\n        Since nests added after the aggregate can access the construct returned\n        by the factory function value, it can be mutated to provide additional\n        values for use when the decorated function is called.\n\n        To do something with the aggregates, you must :meth:`SConsWrap.pop`\n        nest levels created between addition of the aggregate and then can add\n        any normal targets you would like which take advantage of the targets\n        added to the data structure.\n\n        :param name: Name for the target in the nest\n        :param data_fac: a nullary factory function which will be called\n            immediately for each of the current control dictionaries and stored\n            in each dictionary with the given name as in\n            :meth:`SConsWrap.add_target`."
  },
  {
    "code": "def _ps(osdata):\n    grains = {}\n    bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')\n    if osdata['os'] in bsd_choices:\n        grains['ps'] = 'ps auxwww'\n    elif osdata['os_family'] == 'Solaris':\n        grains['ps'] = '/usr/ucb/ps auxwww'\n    elif osdata['os'] == 'Windows':\n        grains['ps'] = 'tasklist.exe'\n    elif osdata.get('virtual', '') == 'openvzhn':\n        grains['ps'] = (\n            'ps -fH -p $(grep -l \\\"^envID:[[:space:]]*0\\\\$\\\" '\n            '/proc/[0-9]*/status | sed -e \\\"s=/proc/\\\\([0-9]*\\\\)/.*=\\\\1=\\\")  '\n            '| awk \\'{ $7=\\\"\\\"; print }\\''\n        )\n    elif osdata['os_family'] == 'AIX':\n        grains['ps'] = '/usr/bin/ps auxww'\n    elif osdata['os_family'] == 'NILinuxRT':\n        grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm'\n    else:\n        grains['ps'] = 'ps -efHww'\n    return grains",
    "docstring": "Return the ps grain"
  },
  {
    "code": "def get_join_parameters(join_kwargs):\n    by = join_kwargs.get('by', None)\n    suffixes = join_kwargs.get('suffixes', ('_x', '_y'))\n    if isinstance(by, tuple):\n        left_on, right_on = by\n    elif isinstance(by, list):\n        by = [x if isinstance(x, tuple) else (x, x) for x in by]\n        left_on, right_on = (list(x) for x in zip(*by))\n    else:\n        left_on, right_on = by, by\n    return left_on, right_on, suffixes",
    "docstring": "Convenience function to determine the columns to join the right and\n    left DataFrames on, as well as any suffixes for the columns."
  },
  {
    "code": "def serial(self):\n        asnint = libcrypto.X509_get_serialNumber(self.cert)\n        bio = Membio()\n        libcrypto.i2a_ASN1_INTEGER(bio.bio, asnint)\n        return int(str(bio), 16)",
    "docstring": "Serial number of certificate as integer"
  },
  {
    "code": "def list_opts():\n    for mod in load_conf_modules():\n        mod_opts = mod.list_opts()\n        if type(mod_opts) is list:\n            for single_mod_opts in mod_opts:\n                yield single_mod_opts[0], single_mod_opts[1]\n        else:\n            yield mod_opts[0], mod_opts[1]",
    "docstring": "List all conf modules opts.\n\n    Goes through all conf modules and yields their opts."
  },
  {
    "code": "def open(self, path, delimiter=None, mode='r', buffering=-1, encoding=None, errors=None,\n             newline=None):\n        if not re.match('^[rbt]{1,3}$', mode):\n            raise ValueError('mode argument must be only have r, b, and t')\n        file_open = get_read_function(path, self.disable_compression)\n        file = file_open(path, mode=mode, buffering=buffering, encoding=encoding, errors=errors,\n                         newline=newline)\n        if delimiter is None:\n            return self(file)\n        else:\n            return self(''.join(list(file)).split(delimiter))",
    "docstring": "Reads and parses input files as defined.\n\n        If delimiter is not None, then the file is read in bulk then split on it. If it is None\n        (the default), then the file is parsed as sequence of lines. The rest of the options are\n        passed directly to builtins.open with the exception that write/append file modes is not\n        allowed.\n\n        >>> seq.open('examples/gear_list.txt').take(1)\n        [u'tent\\\\n']\n\n        :param path: path to file\n        :param delimiter: delimiter to split joined text on. if None, defaults to per line split\n        :param mode: file open mode\n        :param buffering: passed to builtins.open\n        :param encoding: passed to builtins.open\n        :param errors: passed to builtins.open\n        :param newline: passed to builtins.open\n        :return: output of file depending on options wrapped in a Sequence via seq"
  },
  {
    "code": "def source(self):\n        if len(self.sources) == 0:\n            raise ValueError(\"No source associated with %s\" % self.__class__.__name__)\n        elif len(self.sources) > 1:\n            raise ValueError(\"Multiple sources for %s\" % self.__class__.__name__)\n        return list(self.sources)[0]",
    "docstring": "Returns the single source name for a variant collection if it is unique,\n        otherwise raises an error."
  },
  {
    "code": "def json_options_to_metadata(options, add_brackets=True):\n    try:\n        options = loads('{' + options + '}' if add_brackets else options)\n        return options\n    except ValueError:\n        return {}",
    "docstring": "Read metadata from its json representation"
  },
  {
    "code": "def mixerfields(data, commdct):\n    objkey = \"Connector:Mixer\".upper()\n    fieldlists = splittermixerfieldlists(data, commdct, objkey)\n    return extractfields(data, commdct, objkey, fieldlists)",
    "docstring": "get mixer fields to diagram it"
  },
  {
    "code": "def _preprocess(project_dict):\n        handlers = {\n            ('archive',): _list_if_none,\n            ('on-run-start',): _list_if_none_or_string,\n            ('on-run-end',): _list_if_none_or_string,\n        }\n        for k in ('models', 'seeds'):\n            handlers[(k,)] = _dict_if_none\n            handlers[(k, 'vars')] = _dict_if_none\n            handlers[(k, 'pre-hook')] = _list_if_none_or_string\n            handlers[(k, 'post-hook')] = _list_if_none_or_string\n        handlers[('seeds', 'column_types')] = _dict_if_none\n        def converter(value, keypath):\n            if keypath in handlers:\n                handler = handlers[keypath]\n                return handler(value)\n            else:\n                return value\n        return deep_map(converter, project_dict)",
    "docstring": "Pre-process certain special keys to convert them from None values\n        into empty containers, and to turn strings into arrays of strings."
  },
  {
    "code": "def default_depart(self, mdnode):\n        if mdnode.is_container():\n            fn_name = 'visit_{0}'.format(mdnode.t)\n            if not hasattr(self, fn_name):\n                warn(\"Container node skipped: type={0}\".format(mdnode.t))\n            else:\n                self.current_node = self.current_node.parent",
    "docstring": "Default node depart handler\n\n        If there is a matching ``visit_<type>`` method for a container node,\n        then we should make sure to back up to it's parent element when the node\n        is exited."
  },
  {
    "code": "def delete_key(self, key_to_delete):\n        log = logging.getLogger(self.cls_logger + '.delete_key')\n        log.info('Attempting to delete key: {k}'.format(k=key_to_delete))\n        try:\n            self.s3client.delete_object(Bucket=self.bucket_name, Key=key_to_delete)\n        except ClientError:\n            _, ex, trace = sys.exc_info()\n            log.error('ClientError: Unable to delete key: {k}\\n{e}'.format(k=key_to_delete, e=str(ex)))\n            return False\n        else:\n            log.info('Successfully deleted key: {k}'.format(k=key_to_delete))\n            return True",
    "docstring": "Deletes the specified key\n\n        :param key_to_delete:\n        :return:"
  },
  {
    "code": "def _cursor_forward(self, count=1):\n        self.x = min(self.size[1] - 1, self.x + count)",
    "docstring": "Moves cursor right count columns. Cursor stops at right margin."
  },
  {
    "code": "def _byte_pad(data, bound=4):\n    bound = int(bound)\n    if len(data) % bound != 0:\n        pad = bytes(bound - (len(data) % bound))\n        result = bytes().join([data, pad])\n        assert (len(result) % bound) == 0\n        return result\n    return data",
    "docstring": "GLTF wants chunks aligned with 4- byte boundaries\n    so this function will add padding to the end of a\n    chunk of bytes so that it aligns with a specified\n    boundary size\n\n    Parameters\n    --------------\n    data : bytes\n      Data to be padded\n    bound : int\n      Length of desired boundary\n\n    Returns\n    --------------\n    padded : bytes\n      Result where: (len(padded) % bound) == 0"
  },
  {
    "code": "def select_from_drop_down_by_text(self, drop_down_locator, option_locator, option_text, params=None):\n        self.click(drop_down_locator, params['drop_down'] if params else None)\n        for option in self.get_present_elements(option_locator, params['option'] if params else None):\n            if self.get_text(option) == option_text:\n                self.click(option)\n                break",
    "docstring": "Select option from drop down widget using text.\n\n        :param drop_down_locator: locator tuple (if any, params needs to be in place) or WebElement instance\n        :param option_locator: locator tuple (if any, params needs to be in place)\n        :param option_text: text to base option selection on\n        :param params: Dictionary containing dictionary of params\n        :return: None"
  },
  {
    "code": "def deploy_clone_from_vm(self, si, logger, data_holder, vcenter_data_model, reservation_id, cancellation_context):\n        template_resource_model = data_holder.template_resource_model\n        return self._deploy_a_clone(si,\n                                    logger,\n                                    data_holder.app_name,\n                                    template_resource_model.vcenter_vm,\n                                    template_resource_model,\n                                    vcenter_data_model,\n                                    reservation_id,\n                                    cancellation_context)",
    "docstring": "deploy Cloned VM From VM Command, will deploy vm from another vm\n\n        :param cancellation_context:\n        :param reservation_id:\n        :param si:\n        :param logger:\n        :type data_holder:\n        :type vcenter_data_model:\n        :rtype DeployAppResult:\n        :return:"
  },
  {
    "code": "def subscriber_choice_control(self):\n        self.current.task_data['option'] = None\n        self.current.task_data['chosen_subscribers'], names = self.return_selected_form_items(\n            self.input['form']['SubscriberList'])\n        self.current.task_data[\n            'msg'] = \"You should choose at least one subscriber for migration operation.\"\n        if self.current.task_data['chosen_subscribers']:\n            self.current.task_data['option'] = self.input['cmd']\n            del self.current.task_data['msg']",
    "docstring": "It controls subscribers choice and generates\n        error message if there is a non-choice."
  },
  {
    "code": "def create_conversion_event(self, event_key, user_id, attributes, event_tags):\n    params = self._get_common_params(user_id, attributes)\n    conversion_params = self._get_required_params_for_conversion(event_key, event_tags)\n    params[self.EventParams.USERS][0][self.EventParams.SNAPSHOTS].append(conversion_params)\n    return Event(self.EVENTS_URL,\n                 params,\n                 http_verb=self.HTTP_VERB,\n                 headers=self.HTTP_HEADERS)",
    "docstring": "Create conversion Event to be sent to the logging endpoint.\n\n    Args:\n      event_key: Key representing the event which needs to be recorded.\n      user_id: ID for user.\n      attributes: Dict representing user attributes and values.\n      event_tags: Dict representing metadata associated with the event.\n\n    Returns:\n      Event object encapsulating the conversion event."
  },
  {
    "code": "def show(cobertura_file, format, output, source, source_prefix):\n    cobertura = Cobertura(cobertura_file, source=source)\n    Reporter = reporters[format]\n    reporter = Reporter(cobertura)\n    report = reporter.generate()\n    if not isinstance(report, bytes):\n        report = report.encode('utf-8')\n    isatty = True if output is None else output.isatty()\n    click.echo(report, file=output, nl=isatty)",
    "docstring": "show coverage summary of a Cobertura report"
  },
  {
    "code": "def ping(self):\n        msg_code = riak.pb.messages.MSG_CODE_PING_REQ\n        codec = self._get_codec(msg_code)\n        msg = codec.encode_ping()\n        resp_code, _ = self._request(msg, codec)\n        if resp_code == riak.pb.messages.MSG_CODE_PING_RESP:\n            return True\n        else:\n            return False",
    "docstring": "Ping the remote server"
  },
  {
    "code": "def _show_previous_blank_lines(block):\n        pblock = block.previous()\n        while (pblock.text().strip() == '' and\n               pblock.blockNumber() >= 0):\n            pblock.setVisible(True)\n            pblock = pblock.previous()",
    "docstring": "Show the block previous blank lines"
  },
  {
    "code": "def set_time_zone(self, item):\n        i3s_time = item[\"full_text\"].encode(\"UTF-8\", \"replace\")\n        try:\n            i3s_time = i3s_time.decode()\n        except:\n            pass\n        parts = i3s_time.split()\n        i3s_datetime = \" \".join(parts[:2])\n        if len(parts) < 3:\n            return True\n        else:\n            i3s_time_tz = parts[2]\n        date = datetime.strptime(i3s_datetime, TIME_FORMAT)\n        utcnow = datetime.utcnow()\n        delta = datetime(\n            date.year, date.month, date.day, date.hour, date.minute\n        ) - datetime(utcnow.year, utcnow.month, utcnow.day, utcnow.hour, utcnow.minute)\n        try:\n            self.tz = Tz(i3s_time_tz, delta)\n        except ValueError:\n            return False\n        return True",
    "docstring": "Work out the time zone and create a shim tzinfo.\n\n        We return True if all is good or False if there was an issue and we\n        need to re check the time zone.  see issue #1375"
  },
  {
    "code": "def join_resource_name(self, v):\n        d = self.dict\n        d['fragment'] = [v, None]\n        return MetapackResourceUrl(downloader=self._downloader, **d)",
    "docstring": "Return a MetapackResourceUrl that includes a reference to the resource. Returns a\n        MetapackResourceUrl, which will have a fragment"
  },
  {
    "code": "def import_from_netcdf(network, path, skip_time=False):\n    assert has_xarray, \"xarray must be installed for netCDF support.\"\n    basename = os.path.basename(path) if isinstance(path, string_types) else None\n    with ImporterNetCDF(path=path) as importer:\n        _import_from_importer(network, importer, basename=basename,\n                              skip_time=skip_time)",
    "docstring": "Import network data from netCDF file or xarray Dataset at `path`.\n\n    Parameters\n    ----------\n    path : string|xr.Dataset\n        Path to netCDF dataset or instance of xarray Dataset\n    skip_time : bool, default False\n        Skip reading in time dependent attributes"
  },
  {
    "code": "def _cache_loc(self, path, saltenv='base', cachedir=None):\n        cachedir = self.get_cachedir(cachedir)\n        dest = salt.utils.path.join(cachedir,\n                                    'files',\n                                    saltenv,\n                                    path)\n        destdir = os.path.dirname(dest)\n        with salt.utils.files.set_umask(0o077):\n            if os.path.isfile(destdir):\n                os.remove(destdir)\n            try:\n                os.makedirs(destdir)\n            except OSError as exc:\n                if exc.errno != errno.EEXIST:\n                    raise\n            yield dest",
    "docstring": "Return the local location to cache the file, cache dirs will be made"
  },
  {
    "code": "def import_legislators(src):\n    logger.info(\"Importing Legislators From: {0}\".format(src))\n    current = pd.read_csv(\"{0}/{1}/legislators-current.csv\".format(\n        src, LEGISLATOR_DIR))\n    historic = pd.read_csv(\"{0}/{1}/legislators-historic.csv\".format(\n        src, LEGISLATOR_DIR))\n    legislators = current.append(historic)\n    return legislators",
    "docstring": "Read the legislators from the csv files into a single Dataframe. Intended\n    for importing new data."
  },
  {
    "code": "def training_set_multiplication(training_set, mult_queue):\n    logging.info(\"Multiply data...\")\n    for algorithm in mult_queue:\n        new_trning_set = []\n        for recording in training_set:\n            samples = algorithm(recording['handwriting'])\n            for sample in samples:\n                new_trning_set.append({'id': recording['id'],\n                                       'is_in_testset': 0,\n                                       'formula_id': recording['formula_id'],\n                                       'handwriting': sample,\n                                       'formula_in_latex':\n                                       recording['formula_in_latex']})\n        training_set = new_trning_set\n    return new_trning_set",
    "docstring": "Multiply the training set by all methods listed in mult_queue.\n\n    Parameters\n    ----------\n    training_set :\n        set of all recordings that will be used for training\n    mult_queue :\n        list of all algorithms that will take one recording and generate more\n        than one.\n\n    Returns\n    -------\n    mutliple recordings"
  },
  {
    "code": "def create_unique_wcsname(fimg, extnum, wcsname):\n    wnames = list(wcsutil.altwcs.wcsnames(fimg, ext=extnum).values())\n    if wcsname not in wnames:\n        uniqname = wcsname\n    else:\n        rpatt = re.compile(wcsname+'_\\d')\n        index = 0\n        for wname in wnames:\n            rmatch = rpatt.match(wname)\n            if rmatch:\n                n = int(wname[wname.rfind('_')+1:])\n                if n > index: index = 1\n        index += 1\n        uniqname = \"%s_%d\"%(wcsname,index)\n    return uniqname",
    "docstring": "This function evaluates whether the specified wcsname value has\n    already been used in this image.  If so, it automatically modifies\n    the name with a simple version ID using wcsname_NNN format.\n\n    Parameters\n    ----------\n    fimg : obj\n        PyFITS object of image with WCS information to be updated\n\n    extnum : int\n        Index of extension with WCS information to be updated\n\n    wcsname : str\n        Value of WCSNAME specified by user for labelling the new WCS\n\n    Returns\n    -------\n    uniqname : str\n        Unique WCSNAME value"
  },
  {
    "code": "def unpack(s):\n    header = IRHeader(*struct.unpack(_IR_FORMAT, s[:_IR_SIZE]))\n    s = s[_IR_SIZE:]\n    if header.flag > 0:\n        header = header._replace(label=np.frombuffer(s, np.float32, header.flag))\n        s = s[header.flag*4:]\n    return header, s",
    "docstring": "Unpack a MXImageRecord to string.\n\n    Parameters\n    ----------\n    s : str\n        String buffer from ``MXRecordIO.read``.\n\n    Returns\n    -------\n    header : IRHeader\n        Header of the image record.\n    s : str\n        Unpacked string.\n\n    Examples\n    --------\n    >>> record = mx.recordio.MXRecordIO('test.rec', 'r')\n    >>> item = record.read()\n    >>> header, s = mx.recordio.unpack(item)\n    >>> header\n    HEADER(flag=0, label=14.0, id=20129312, id2=0)"
  },
  {
    "code": "def help_heading(self):\n        message = m.Heading(\n            tr('Help for {step_name}').format(step_name=self.step_name),\n            **SUBSECTION_STYLE)\n        return message",
    "docstring": "Helper method that returns just the header.\n\n        :returns: A heading object.\n        :rtype: safe.messaging.heading.Heading"
  },
  {
    "code": "def set_win_wallpaper(img):\n    if \"x86\" in os.environ[\"PROGRAMFILES\"]:\n        ctypes.windll.user32.SystemParametersInfoW(20, 0, img, 3)\n    else:\n        ctypes.windll.user32.SystemParametersInfoA(20, 0, img, 3)",
    "docstring": "Set the wallpaper on Windows."
  },
  {
    "code": "def refresh_fqdn_cache(force=False):\n    if not isinstance(force, bool):\n        raise CommandExecutionError(\"Force option must be boolean.\")\n    if force:\n        query = {'type': 'op',\n                 'cmd': '<request><system><fqdn><refresh><force>yes</force></refresh></fqdn></system></request>'}\n    else:\n        query = {'type': 'op', 'cmd': '<request><system><fqdn><refresh></refresh></fqdn></system></request>'}\n    return __proxy__['panos.call'](query)",
    "docstring": "Force refreshes all FQDNs used in rules.\n\n    force\n        Forces all fqdn refresh\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' panos.refresh_fqdn_cache\n        salt '*' panos.refresh_fqdn_cache force=True"
  },
  {
    "code": "def mbar_log_W_nk(u_kn, N_k, f_k):\n    u_kn, N_k, f_k = validate_inputs(u_kn, N_k, f_k)\n    log_denominator_n = logsumexp(f_k - u_kn.T, b=N_k, axis=1)\n    logW = f_k - u_kn.T - log_denominator_n[:, np.newaxis]\n    return logW",
    "docstring": "Calculate the log weight matrix.\n\n    Parameters\n    ----------\n    u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'\n        The reduced potential energies, i.e. -log unnormalized probabilities\n    N_k : np.ndarray, shape=(n_states), dtype='int'\n        The number of samples in each state\n    f_k : np.ndarray, shape=(n_states), dtype='float'\n        The reduced free energies of each state\n\n    Returns\n    -------\n    logW_nk : np.ndarray, dtype='float', shape=(n_samples, n_states)\n        The normalized log weights.\n\n    Notes\n    -----\n    Equation (9) in JCP MBAR paper."
  },
  {
    "code": "def get_details(app_url=defaults.APP_URL):\n    url = '%s/environment' % app_url\n    response = requests.get(url)\n    if response.status_code == 200:\n        return response.json()\n    else:\n        raise JutException('Unable to retrieve environment details from %s, got %s: %s' %\n                           (url, response.status_code, response.text))",
    "docstring": "returns environment details for the app url specified"
  },
  {
    "code": "def scheme(name, bins, bin_method='quantiles'):\n    return {\n        'name': name,\n        'bins': bins,\n        'bin_method': (bin_method if isinstance(bins, int) else ''),\n    }",
    "docstring": "Return a custom scheme based on CARTOColors.\n\n    Args:\n        name (str): Name of a CARTOColor.\n        bins (int or iterable): If an `int`, the number of bins for classifying\n          data. CARTOColors have 7 bins max for quantitative data, and 11 max\n          for qualitative data. If `bins` is a `list`, it is the upper range\n          for classifying data. E.g., `bins` can be of the form ``(10, 20, 30,\n          40, 50)``.\n        bin_method (str, optional): One of methods in :obj:`BinMethod`.\n          Defaults to ``quantiles``. If `bins` is an interable, then that is\n          the bin method that will be used and this will be ignored.\n\n    .. Warning::\n\n       Input types are particularly sensitive in this function, and little\n       feedback is given for errors. ``name`` and ``bin_method`` arguments\n       are case-sensitive."
  },
  {
    "code": "def stream_directory(directory,\n                     recursive=False,\n                     patterns='**',\n                     chunk_size=default_chunk_size):\n    stream = DirectoryStream(directory,\n                             recursive=recursive,\n                             patterns=patterns,\n                             chunk_size=chunk_size)\n    return stream.body(), stream.headers",
    "docstring": "Gets a buffered generator for streaming directories.\n\n    Returns a buffered generator which encodes a directory as\n    :mimetype:`multipart/form-data` with the corresponding headers.\n\n    Parameters\n    ----------\n    directory : str\n        The filepath of the directory to stream\n    recursive : bool\n        Stream all content within the directory recursively?\n    patterns : str | list\n        Single *glob* pattern or list of *glob* patterns and compiled\n        regular expressions to match the names of the filepaths to keep\n    chunk_size : int\n        Maximum size of each stream chunk"
  },
  {
    "code": "def get_layer_description_from_canvas(self, layer, purpose):\n        if not layer:\n            return \"\"\n        try:\n            keywords = self.keyword_io.read_keywords(layer)\n            if 'layer_purpose' not in keywords:\n                keywords = None\n        except (HashNotFoundError,\n                OperationalError,\n                NoKeywordsFoundError,\n                KeywordNotFoundError,\n                InvalidParameterError,\n                UnsupportedProviderError):\n            keywords = None\n        self.layer = layer\n        if purpose == layer_purpose_hazard['key']:\n            self.hazard_layer = layer\n        elif purpose == layer_purpose_exposure['key']:\n            self.exposure_layer = layer\n        else:\n            self.aggregation_layer = layer\n        if keywords and 'keyword_version' in keywords:\n            kw_ver = str(keywords['keyword_version'])\n            self.is_selected_layer_keywordless = (\n                not is_keyword_version_supported(kw_ver))\n        else:\n            self.is_selected_layer_keywordless = True\n        description = layer_description_html(layer, keywords)\n        return description",
    "docstring": "Obtain the description of a canvas layer selected by user.\n\n        :param layer: The QGIS layer.\n        :type layer: QgsMapLayer\n\n        :param purpose: The layer purpose of the layer to get the description.\n        :type purpose: string\n\n        :returns: description of the selected layer.\n        :rtype: string"
  },
  {
    "code": "def transition(trname='', field='', check=None, before=None, after=None):\n    if is_callable(trname):\n        raise ValueError(\n            \"The @transition decorator should be called as \"\n            \"@transition(['transition_name'], **kwargs)\")\n    if check or before or after:\n        warnings.warn(\n            \"The use of check=, before= and after= in @transition decorators is \"\n            \"deprecated in favor of @transition_check, @before_transition and \"\n            \"@after_transition decorators.\",\n            DeprecationWarning,\n            stacklevel=2)\n    return TransitionWrapper(trname, field=field, check=check, before=before, after=after)",
    "docstring": "Decorator to declare a function as a transition implementation."
  },
  {
    "code": "def _show(self, message, indent=0, enable_verbose=True):\n        if enable_verbose:\n            print(\"    \" * indent + message)",
    "docstring": "Message printer."
  },
  {
    "code": "def move_to(x, y):\n    for b in _button_state:\n        if _button_state[b]:\n            e = Quartz.CGEventCreateMouseEvent(\n                None,\n                _button_mapping[b][3],\n                (x, y),\n                _button_mapping[b][0])\n            break\n    else:\n        e = Quartz.CGEventCreateMouseEvent(\n            None,\n            Quartz.kCGEventMouseMoved,\n            (x, y),\n            Quartz.kCGMouseButtonLeft)\n    Quartz.CGEventPost(Quartz.kCGHIDEventTap, e)",
    "docstring": "Sets the mouse's location to the specified coordinates."
  },
  {
    "code": "def _group(self, group_data):\n        if isinstance(group_data, dict):\n            xid = group_data.get('xid')\n        else:\n            xid = group_data.xid\n        if self.groups.get(xid) is not None:\n            group_data = self.groups.get(xid)\n        elif self.groups_shelf.get(xid) is not None:\n            group_data = self.groups_shelf.get(xid)\n        else:\n            self.groups[xid] = group_data\n        return group_data",
    "docstring": "Return previously stored group or new group.\n\n        Args:\n            group_data (dict|obj): An Group dict or instance of Group object.\n\n        Returns:\n            dict|obj: The new Group dict/object or the previously stored dict/object."
  },
  {
    "code": "def format_variable_map(variable_map, join_lines=True):\n  rows = []\n  rows.append((\"Key\", \"Variable\", \"Shape\", \"Type\", \"Collections\", \"Device\"))\n  var_to_collections = _get_vars_to_collections(variable_map)\n  sort_key = lambda item: (item[0], item[1].name)\n  for key, var in sorted(variable_map_items(variable_map), key=sort_key):\n    shape = \"x\".join(str(dim) for dim in var.get_shape().as_list())\n    dtype = repr(var.dtype.base_dtype).replace(\"tf.\", \"\")\n    coll = \", \".join(sorted(var_to_collections[var]))\n    rows.append((key, var.op.name, shape, dtype, coll, _format_device(var)))\n  return _format_table(rows, join_lines)",
    "docstring": "Takes a key-to-variable map and formats it as a table."
  },
  {
    "code": "def reset_option(self, key, subkey):\n        if not self.open:\n            return\n        key, subkey = _lower_keys(key, subkey)\n        _entry_must_exist(self.gc, key, subkey)\n        df = self.gc[(self.gc[\"k1\"] == key) & (self.gc[\"k2\"] == subkey)]\n        if df[\"locked\"].values[0]:\n            raise ValueError(\"{0}.{1} option is locked\".format(key, subkey))\n        val = df[\"default\"].values[0]\n        self.gc.loc[\n            (self.gc[\"k1\"] == key) &\n            (self.gc[\"k2\"] == subkey), \"value\"] = val",
    "docstring": "Resets a single option to the default values.\n\n        :param str key: First identifier of the option.\n        :param str subkey: Second identifier of the option.\n\n        :raise:\n            :NotRegisteredError: If ``key`` or ``subkey`` do not define any\n                option.\n            :ValueError: If the targeted obtion is locked."
  },
  {
    "code": "def _check_split_list_validity(self):\n        if not (hasattr(self,\"_splitListsSet\") and (self._splitListsSet)):\n            return False\n        elif len(self) != self._splitListsLength:\n            return False\n        else:\n            return True",
    "docstring": "See _temporal_split_list above. This function checks if the current\n        split lists are still valid."
  },
  {
    "code": "def placeholdit(\n    width,\n    height,\n    background_color=\"cccccc\",\n    text_color=\"969696\",\n    text=None,\n    random_background_color=False\n):\n    url = get_placeholdit_url(\n        width,\n        height,\n        background_color=background_color,\n        text_color=text_color,\n        text=text,\n    )\n    return format_html('<img src=\"{}\"/>', url)",
    "docstring": "Creates a placeholder image using placehold.it\n\n    Usage format:\n\n      {% placeholdit [width] [height] [background_color] [text_color] [text] %}\n\n    Example usage:\n\n        Default image at 250 square\n        {% placeholdit 250 %}\n\n        100 wide and 200 high\n        {% placeholdit 100 200 %}\n\n        Custom background and text colors\n        {% placeholdit 100 200 background_color='fff' text_color=000' %}\n\n        Custom text\n        {% placeholdit 100 200 text='Hello LA' %}"
  },
  {
    "code": "def do_state_tomography(preparation_program, nsamples, cxn, qubits=None, use_run=False):\n    return tomography._do_tomography(preparation_program, nsamples, cxn, qubits,\n                                     tomography.MAX_QUBITS_STATE_TOMO,\n                                     StateTomography, state_tomography_programs,\n                                     DEFAULT_STATE_TOMO_SETTINGS, use_run=use_run)",
    "docstring": "Method to perform both a QPU and QVM state tomography, and use the latter as\n    as reference to calculate the fidelity of the former.\n\n    :param Program preparation_program: Program to execute.\n    :param int nsamples: Number of samples to take for the program.\n    :param QVMConnection|QPUConnection cxn: Connection on which to run the program.\n    :param list qubits: List of qubits for the program.\n    to use in the tomography analysis.\n    :param bool use_run: If ``True``, use append measurements on all qubits and use ``cxn.run``\n        instead of ``cxn.run_and_measure``.\n    :return: The state tomogram.\n    :rtype: StateTomography"
  },
  {
    "code": "def finalize(self):\n        if self.total_instances > 1:\n            print('{} of {} instances contained dead code.'\n                  .format(self.dead_code_instances, self.total_instances))",
    "docstring": "Output the number of instances that contained dead code."
  },
  {
    "code": "def max_version(self):\n        data = self.version_downloads\n        if not data:\n            return None, 0\n        return max(data.items(), key=lambda item: item[1])",
    "docstring": "Version with the most downloads.\n\n        :return: A tuple of the form (version, n_downloads)"
  },
  {
    "code": "def ReadTriggers(self, collection_link, options=None):\n        if options is None:\n            options = {}\n        return self.QueryTriggers(collection_link, None, options)",
    "docstring": "Reads all triggers in a collection.\n\n        :param str collection_link:\n            The link to the document collection.\n        :param dict options:\n            The request options for the request.\n\n        :return:\n            Query Iterable of Triggers.\n        :rtype:\n            query_iterable.QueryIterable"
  },
  {
    "code": "def define_saver(exclude=None):\n  variables = []\n  exclude = exclude or []\n  exclude = [re.compile(regex) for regex in exclude]\n  for variable in tf.global_variables():\n    if any(regex.match(variable.name) for regex in exclude):\n      continue\n    variables.append(variable)\n  saver = tf.train.Saver(variables, keep_checkpoint_every_n_hours=5)\n  return saver",
    "docstring": "Create a saver for the variables we want to checkpoint.\n\n  Args:\n    exclude: List of regexes to match variable names to exclude.\n\n  Returns:\n    Saver object."
  },
  {
    "code": "def _add_coverage_bedgraph_to_output(out, data):\n    out_file = \"%s.coverage.bedgraph\" % os.path.splitext(out[\"cns\"])[0]\n    if utils.file_exists(out_file):\n        out[\"bedgraph\"] = out_file\n        return out\n    bam_file = dd.get_align_bam(data)\n    bedtools = config_utils.get_program(\"bedtools\", data[\"config\"])\n    samtools = config_utils.get_program(\"samtools\", data[\"config\"])\n    cns_file = out[\"cns\"]\n    bed_file = tempfile.NamedTemporaryFile(suffix=\".bed\", delete=False).name\n    with file_transaction(data, out_file) as tx_out_file:\n        cmd = (\"sed 1d {cns_file} | cut -f1,2,3 > {bed_file}; \"\n               \"{samtools} view -b -L {bed_file} {bam_file} | \"\n               \"{bedtools} genomecov -bg -ibam - -g {bed_file} >\"\n               \"{tx_out_file}\").format(**locals())\n        do.run(cmd, \"CNVkit bedGraph conversion\")\n        os.remove(bed_file)\n    out[\"bedgraph\"] = out_file\n    return out",
    "docstring": "Add BedGraph representation of coverage to the output"
  },
  {
    "code": "def in_timezone(self, tz):\n        tz = pendulum._safe_timezone(tz)\n        return tz.convert(self, dst_rule=pendulum.POST_TRANSITION)",
    "docstring": "Set the instance's timezone from a string or object."
  },
  {
    "code": "def basic_parse(response, buf_size=ijson.backend.BUFSIZE):\n        lexer = iter(IncrementalJsonParser.lexer(response, buf_size))\n        for value in ijson.backend.parse_value(lexer):\n            yield value\n        try:\n            next(lexer)\n        except StopIteration:\n            pass\n        else:\n            raise ijson.common.JSONError('Additional data')",
    "docstring": "Iterator yielding unprefixed events.\n\n        Parameters:\n\n        - response: a stream response from requests"
  },
  {
    "code": "def _left_zero_blocks(self, r):\n    if not self._include_off_diagonal:\n      return r\n    elif not self._upper:\n      return 0\n    elif self._include_diagonal:\n      return r\n    else:\n      return r + 1",
    "docstring": "Number of blocks with zeros from the left in block row `r`."
  },
  {
    "code": "def is_compatible_with(self, other):\n        other = as_dtype(other)\n        return self._type_enum in (\n            other.as_datatype_enum,\n            other.base_dtype.as_datatype_enum,\n        )",
    "docstring": "Returns True if the `other` DType will be converted to this DType.\n\n        The conversion rules are as follows:\n\n        ```python\n        DType(T)       .is_compatible_with(DType(T))        == True\n        DType(T)       .is_compatible_with(DType(T).as_ref) == True\n        DType(T).as_ref.is_compatible_with(DType(T))        == False\n        DType(T).as_ref.is_compatible_with(DType(T).as_ref) == True\n        ```\n\n        Args:\n          other: A `DType` (or object that may be converted to a `DType`).\n\n        Returns:\n          True if a Tensor of the `other` `DType` will be implicitly converted to\n          this `DType`."
  },
  {
    "code": "def set_rendering_intent(self, rendering_intent):\n        if rendering_intent not in (None,\n                                    PERCEPTUAL,\n                                    RELATIVE_COLORIMETRIC,\n                                    SATURATION,\n                                    ABSOLUTE_COLORIMETRIC):\n            raise FormatError('Unknown redering intent')\n        self.rendering_intent = rendering_intent",
    "docstring": "Set rendering intent variant for sRGB chunk"
  },
  {
    "code": "def proxy_protocol(self, error='raise', default=None, limit=None, authenticate=False):\n        if error not in ('raise', 'unread'):\n            raise ValueError('error=\"{0}\" is not  \"raise\" or \"unread\"\"')\n        if not isinstance(self.request, SocketBuffer):\n            self.request = SocketBuffer(self.request)\n        if default == 'peer':\n            default = ProxyInfo(\n                self.client_address[0], self.client_address[1],\n                self.client_address[0], self.client_address[1],\n            )\n        try:\n            line = read_line(\n                self.request.sock,\n                self.request.buf,\n                limit=limit,\n            )\n        except exc.ReadError:\n            if error == 'raise':\n                raise\n            return default\n        try:\n            info = parse_line(line)\n        except exc.ParseError:\n            if error == 'raise':\n                raise\n            self.request.unread(line)\n            return default\n        if authenticate and not self.proxy_authenticate(info):\n            logger.info('authentication failed - %s', info)\n            return default\n        return info",
    "docstring": "Parses, and optionally authenticates, proxy protocol information from\n        request. Note that ``self.request`` is wrapped by ``SocketBuffer``.\n\n        :param error:\n            How read (``exc.ReadError``) and parse (``exc.ParseError``) errors\n            are handled. One of:\n            - \"raise\" to propagate.\n            - \"unread\" to suppress exceptions and unread back to socket.\n        :param default:\n            What to return when no ``ProxyInfo`` was found. Only meaningful\n            with error \"unread\".\n        :param limit:\n            Maximum number of bytes to read when probing request for\n            ``ProxyInfo``.\n\n        :returns: Parsed ``ProxyInfo`` instance or **default** if none found."
  },
  {
    "code": "def _define_range(self, sequences):\n        sequence_count = 0\n        total_sequence = 0\n        for record in SeqIO.parse(open(sequences), 'fasta'):\n            total_sequence+=1\n            sequence_count+=len(record.seq)\n        max_range = (sequence_count/total_sequence)*1.5\n        return max_range",
    "docstring": "define_range - define the maximum range within which two hits in a db\n        search can be linked. This is defined as 1.5X the average length of all\n        reads in the database.\n\n        Parameters\n        ----------\n        sequences : str\n            A path to the sequences in FASTA format. This fasta file is assumed\n            to be in the correct format. i.e. headers start with '>'\n\n        Returns\n        -------\n        max_range : int\n            As described above, 1.5X the size of the average length of genes\n            within the database"
  },
  {
    "code": "def parser_factory(fake_args=None):\n    parser = ArgumentParser(description='aomi')\n    subparsers = parser.add_subparsers(dest='operation',\n                                       help='Specify the data '\n                                       ' or extraction operation')\n    extract_file_args(subparsers)\n    environment_args(subparsers)\n    aws_env_args(subparsers)\n    seed_args(subparsers)\n    render_args(subparsers)\n    diff_args(subparsers)\n    freeze_args(subparsers)\n    thaw_args(subparsers)\n    template_args(subparsers)\n    password_args(subparsers)\n    token_args(subparsers)\n    help_args(subparsers)\n    export_args(subparsers)\n    if fake_args is None:\n        return parser, parser.parse_args()\n    return parser, parser.parse_args(fake_args)",
    "docstring": "Return a proper contextual OptionParser"
  },
  {
    "code": "def get_whitelist_page(self, page_number=None, page_size=None):\n        params = {\n            'pageNumber': page_number,\n            'pageSize': page_size\n        }\n        resp = self._client.get(\"whitelist\", params=params)\n        return Page.from_dict(resp.json(), content_type=Indicator)",
    "docstring": "Gets a paginated list of indicators that the user's company has whitelisted.\n\n        :param int page_number: the page number to get.\n        :param int page_size: the size of the page to be returned.\n        :return: A |Page| of |Indicator| objects."
  },
  {
    "code": "def _cmp_date(self):\n        dates = sorted(val for val in self.kw.values()\n                       if isinstance(val, CalendarDate))\n        if dates:\n            return dates[0]\n        return CalendarDate()",
    "docstring": "Returns Calendar date used for comparison.\n\n        Use the earliest date out of all CalendarDates in this instance,\n        or some date in the future if there are no CalendarDates (e.g.\n        when Date is a phrase)."
  },
  {
    "code": "def model_base(bind_label=None, info=None):\n    Model = type('Model', (BaseModel,), {'__odm_abstract__': True})\n    info = {}\n    Model.__table_args__ = table_args(info=info)\n    if bind_label:\n        info['bind_label'] = bind_label\n    return Model",
    "docstring": "Create a base declarative class"
  },
  {
    "code": "def sparql_query(self, query, flush=None, limit=None):\n        return self.find_statements(query, language='sparql', type='tuples',\n            flush=flush, limit=limit)",
    "docstring": "Run a Sparql query.\n\n        :param query: sparql query string\n        :rtype: list of dictionary"
  },
  {
    "code": "def query_symbol(self, asset: str) -> str:\n        contract_address = self.get_asset_address(asset)\n        method = 'symbol'\n        invoke_code = build_native_invoke_code(contract_address, b'\\x00', method, bytearray())\n        tx = Transaction(0, 0xd1, int(time()), 0, 0, None, invoke_code, bytearray(), list())\n        response = self.__sdk.rpc.send_raw_transaction_pre_exec(tx)\n        symbol = ContractDataParser.to_utf8_str(response['Result'])\n        return symbol",
    "docstring": "This interface is used to query the asset's symbol of ONT or ONG.\n\n        :param asset: a string which is used to indicate which asset's symbol we want to get.\n        :return: asset's symbol in the form of string."
  },
  {
    "code": "def getStartdatetime(self):\n        return datetime(self.startdate_year, self.startdate_month, self.startdate_day,\n                                 self.starttime_hour, self.starttime_minute, self.starttime_second)",
    "docstring": "Returns the date and starttime as datetime object\n\n        Parameters\n        ----------\n        None\n\n        Examples\n        --------\n        >>> import pyedflib\n        >>> f = pyedflib.data.test_generator()\n        >>> f.getStartdatetime()\n        datetime.datetime(2011, 4, 4, 12, 57, 2)\n        >>> f._close()\n        >>> del f"
  },
  {
    "code": "def paths(self, destination_account, destination_amount, source_account, destination_asset_code,\n              destination_asset_issuer=None):\n        destination_asset = Asset(destination_asset_code, destination_asset_issuer)\n        destination_asset_params = {\n            'destination_asset_type': destination_asset.type,\n            'destination_asset_code': None if destination_asset.is_native() else destination_asset.code,\n            'destination_asset_issuer': destination_asset.issuer\n        }\n        endpoint = '/paths'\n        params = self.__query_params(destination_account=destination_account,\n                                     source_account=source_account,\n                                     destination_amount=destination_amount,\n                                     **destination_asset_params\n                                     )\n        return self.query(endpoint, params)",
    "docstring": "Load a list of assets available to the source account id and find\n        any payment paths from those source assets to the desired\n        destination asset.\n\n        See the below docs for more information on required and optional\n        parameters for further specifying your search.\n\n        `GET /paths\n        <https://www.stellar.org/developers/horizon/reference/endpoints/path-finding.html>`_\n\n        :param str destination_account: The destination account that any returned path should use.\n        :param str destination_amount: The amount, denominated in the destination asset,\n            that any returned path should be able to satisfy.\n        :param str source_account: The sender's account id. Any returned path must use a source that the sender can hold.\n        :param str destination_asset_code: The asset code for the destination.\n        :param destination_asset_issuer: The asset issuer for the destination, if it is a native asset, let it be `None`.\n        :type destination_asset_issuer: str, None\n\n\n        :return: A list of paths that can be used to complete a payment based\n            on a given query.\n        :rtype: dict"
  },
  {
    "code": "def annotate_gemini(data, retriever=None):\n    r = dd.get_variation_resources(data)\n    return all([r.get(k) and objectstore.file_exists_or_remote(r[k]) for k in [\"exac\", \"gnomad_exome\"]])",
    "docstring": "Annotate with population calls if have data installed."
  },
  {
    "code": "def _get_default_router(self, routers, router_name=None):\n        if router_name is None:\n            for router in routers:\n                if router['id'] is not None:\n                    return router['id']\n        else:\n            for router in routers:\n                if router['hostname'] == router_name:\n                    return router['id']\n        raise SoftLayer.SoftLayerError(\"Could not find valid default router\")",
    "docstring": "Returns the default router for ordering a dedicated host."
  },
  {
    "code": "def postags(self):\n        if not self.is_tagged(ANALYSIS):\n            self.tag_analysis()\n        return self.get_analysis_element(POSTAG)",
    "docstring": "The list of word part-of-speech tags.\n\n        Ambiguous cases are separated with pipe character by default.\n        Use :py:meth:`~estnltk.text.Text.get_analysis_element` to specify custom separator for ambiguous entries."
  },
  {
    "code": "def check_existing_results(self, benchmark):\n        if os.path.exists(benchmark.log_folder):\n            sys.exit('Output directory {0} already exists, will not overwrite existing results.'.format(benchmark.log_folder))\n        if os.path.exists(benchmark.log_zip):\n            sys.exit('Output archive {0} already exists, will not overwrite existing results.'.format(benchmark.log_zip))",
    "docstring": "Check and abort if the target directory for the benchmark results\n        already exists in order to avoid overwriting results."
  },
  {
    "code": "def compare(self, compare_recipe, suffix='_compare'):\n        assert isinstance(compare_recipe, Recipe)\n        assert isinstance(suffix, basestring)\n        self.compare_recipe.append(compare_recipe)\n        self.suffix.append(suffix)\n        self.dirty = True\n        return self.recipe",
    "docstring": "Adds a comparison recipe to a base recipe."
  },
  {
    "code": "def dump(props, output):\n    def escape(token):\n      return re.sub(r'([=:\\s])', r'\\\\\\1', token)\n    def write(out):\n      for k, v in props.items():\n        out.write('%s=%s\\n' % (escape(str(k)), escape(str(v))))\n    if hasattr(output, 'write') and callable(output.write):\n      write(output)\n    elif isinstance(output, six.string_types):\n      with open(output, 'w+') as out:\n        write(out)\n    else:\n      raise TypeError('Can only dump data to a path or a writable object, given: %s' % output)",
    "docstring": "Dumps a dict of properties to the specified open stream or file path.\n\n    :API: public"
  },
  {
    "code": "def to_list(self):\n        output = []\n        for i in range(1, len(self.elements), 2):\n            output.append(self.elements[i])\n        return output",
    "docstring": "Converts the vector to an array of the elements within the vector"
  },
  {
    "code": "def assert_trigger(self, session, protocol):\n        try:\n            return self.sessions[session].assert_trigger(protocol)\n        except KeyError:\n            return constants.StatusCode.error_invalid_object",
    "docstring": "Asserts software or hardware trigger.\n\n        Corresponds to viAssertTrigger function of the VISA library.\n\n        :param session: Unique logical identifier to a session.\n        :param protocol: Trigger protocol to use during assertion. (Constants.PROT*)\n        :return: return value of the library call.\n        :rtype: :class:`pyvisa.constants.StatusCode`"
  },
  {
    "code": "def extract_facts(rule):\n    def _extract_facts(ce):\n        if isinstance(ce, Fact):\n            yield ce\n        elif isinstance(ce, TEST):\n            pass\n        else:\n            for e in ce:\n                yield from _extract_facts(e)\n    return set(_extract_facts(rule))",
    "docstring": "Given a rule, return a set containing all rule LHS facts."
  },
  {
    "code": "def render_subgraph(self, ontol, nodes, **args):\n        subont = ontol.subontology(nodes, **args)\n        return self.render(subont, **args)",
    "docstring": "Render a `ontology` object after inducing a subgraph"
  },
  {
    "code": "def get_post(self, slug):\n        cache_key = self.get_cache_key(post_slug=slug)\n        content = cache.get(cache_key)\n        if not content:\n            post = Post.objects.get(slug=slug)\n            content = self._format(post)\n            cache_duration = conf.GOSCALE_CACHE_DURATION if post else 1\n            cache.set(cache_key, content, cache_duration)\n        return content",
    "docstring": "This method returns a single post by slug"
  },
  {
    "code": "def make_blastdb(self):\n        db = os.path.splitext(self.formattedprimers)[0]\n        nhr = '{db}.nhr'.format(db=db)\n        if not os.path.isfile(str(nhr)):\n            command = 'makeblastdb -in {primerfile} -parse_seqids -max_file_sz 2GB -dbtype nucl -out {outfile}'\\\n                .format(primerfile=self.formattedprimers,\n                        outfile=db)\n            run_subprocess(command)",
    "docstring": "Create a BLAST database of the primer file"
  },
  {
    "code": "def to_bytes(s, encoding=\"utf8\"):\n    if PY_VERSION == 2:\n        b = bytes(s)\n    elif PY_VERSION == 3:\n        b = bytes(s, encoding)\n    else:\n        raise ValueError(\"Is Python 4 out already?\")\n    return b",
    "docstring": "Converts str s to bytes"
  },
  {
    "code": "def mmi_to_delimited_file(self, force_flag=True):\n        LOGGER.debug('mmi_to_delimited_text requested.')\n        csv_path = os.path.join(\n            self.output_dir, 'mmi.csv')\n        if os.path.exists(csv_path) and force_flag is not True:\n            return csv_path\n        csv_file = open(csv_path, 'w')\n        csv_file.write(self.mmi_to_delimited_text())\n        csv_file.close()\n        csvt_path = os.path.join(\n            self.output_dir, self.output_basename + '.csvt')\n        csvt_file = open(csvt_path, 'w')\n        csvt_file.write('\"Real\",\"Real\",\"Real\"')\n        csvt_file.close()\n        return csv_path",
    "docstring": "Save mmi_data to delimited text file suitable for gdal_grid.\n\n        The output file will be of the same format as strings returned from\n        :func:`mmi_to_delimited_text`.\n\n        :param force_flag: Whether to force the regeneration of the output\n            file. Defaults to False.\n        :type force_flag: bool\n\n        :returns: The absolute file system path to the delimited text file.\n        :rtype: str\n\n        .. note:: An accompanying .csvt will be created which gdal uses to\n           determine field types. The csvt will contain the following string:\n           \"Real\",\"Real\",\"Real\". These types will be used in other conversion\n           operations. For example to convert the csv to a shp you would do::\n\n              ogr2ogr -select mmi -a_srs EPSG:4326 mmi.shp mmi.vrt mmi"
  },
  {
    "code": "def updateActiveMarkupClass(self):\n\t\tpreviousMarkupClass = self.activeMarkupClass\n\t\tself.activeMarkupClass = find_markup_class_by_name(globalSettings.defaultMarkup)\n\t\tif self._fileName:\n\t\t\tmarkupClass = get_markup_for_file_name(\n\t\t\t\tself._fileName, return_class=True)\n\t\t\tif markupClass:\n\t\t\t\tself.activeMarkupClass = markupClass\n\t\tif self.activeMarkupClass != previousMarkupClass:\n\t\t\tself.highlighter.docType = self.activeMarkupClass.name if self.activeMarkupClass else None\n\t\t\tself.highlighter.rehighlight()\n\t\t\tself.activeMarkupChanged.emit()\n\t\t\tself.triggerPreviewUpdate()",
    "docstring": "Update the active markup class based on the default class and\n\t\tthe current filename. If the active markup class changes, the\n\t\thighlighter is rerun on the input text, the markup object of\n\t\tthis tab is replaced with one of the new class and the\n\t\tactiveMarkupChanged signal is emitted."
  },
  {
    "code": "def copy_assets(self, path='assets'):\n\t\tpath = os.path.join(self.root_path, path)\n\t\tfor root, _, files in os.walk(path):\n\t\t\tfor file in files:\n\t\t\t\tfullpath = os.path.join(root, file)\n\t\t\t\trelpath = os.path.relpath(fullpath, path)\n\t\t\t\tcopy_to = os.path.join(self._get_dist_path(relpath, directory='assets'))\n\t\t\t\tLOG.debug('copying %r to %r', fullpath, copy_to)\n\t\t\t\tshutil.copyfile(fullpath, copy_to)",
    "docstring": "Copy assets into the destination directory."
  },
  {
    "code": "def delete_user(self, id):\n        self.assert_has_permission('scim.write')\n        uri = self.uri + '/Users/%s' % id\n        headers = self._get_headers()\n        logging.debug(\"URI=\" + str(uri))\n        logging.debug(\"HEADERS=\" + str(headers))\n        response = self.session.delete(uri, headers=headers)\n        logging.debug(\"STATUS=\" + str(response.status_code))\n        if response.status_code == 200:\n            return response\n        else:\n            logging.error(response.content)\n            response.raise_for_status()",
    "docstring": "Delete user with given id."
  },
  {
    "code": "def iter_sources(self):\n        for src_id in xrange(self.get_source_count()):\n            yield src_id, self.get_source_name(src_id)",
    "docstring": "Iterates over all source names and IDs."
  },
  {
    "code": "def _realwavelets(s_freq, freqs, dur, width):\n    x = arange(-dur / 2, dur / 2, 1 / s_freq)\n    wavelets = empty((len(freqs), len(x)))\n    g = exp(-(pi * x ** 2) / width ** 2)\n    for i, one_freq in enumerate(freqs):\n        y = cos(2 * pi * x * one_freq)\n        wavelets[i, :] = y * g\n    return wavelets",
    "docstring": "Create real wavelets, for UCSD.\n\n    Parameters\n    ----------\n    s_freq : int\n        sampling frequency\n    freqs : ndarray\n        vector with frequencies of interest\n    dur : float\n        duration of the wavelets in s\n    width : float\n        parameter controlling gaussian shape\n\n    Returns\n    -------\n    ndarray\n        wavelets"
  },
  {
    "code": "def klucher(surface_tilt, surface_azimuth, dhi, ghi, solar_zenith,\n            solar_azimuth):\n    r\n    cos_tt = aoi_projection(surface_tilt, surface_azimuth,\n                            solar_zenith, solar_azimuth)\n    cos_tt = np.maximum(cos_tt, 0)\n    F = 1 - ((dhi / ghi) ** 2)\n    try:\n        F.fillna(0, inplace=True)\n    except AttributeError:\n        F = np.where(np.isnan(F), 0, F)\n    term1 = 0.5 * (1 + tools.cosd(surface_tilt))\n    term2 = 1 + F * (tools.sind(0.5 * surface_tilt) ** 3)\n    term3 = 1 + F * (cos_tt ** 2) * (tools.sind(solar_zenith) ** 3)\n    sky_diffuse = dhi * term1 * term2 * term3\n    return sky_diffuse",
    "docstring": "r'''\n    Determine diffuse irradiance from the sky on a tilted surface\n    using Klucher's 1979 model\n\n    .. math::\n\n       I_{d} = DHI \\frac{1 + \\cos\\beta}{2} (1 + F' \\sin^3(\\beta/2))\n       (1 + F' \\cos^2\\theta\\sin^3\\theta_z)\n\n    where\n\n    .. math::\n\n       F' = 1 - (I_{d0} / GHI)\n\n    Klucher's 1979 model determines the diffuse irradiance from the sky\n    (ground reflected irradiance is not included in this algorithm) on a\n    tilted surface using the surface tilt angle, surface azimuth angle,\n    diffuse horizontal irradiance, direct normal irradiance, global\n    horizontal irradiance, extraterrestrial irradiance, sun zenith\n    angle, and sun azimuth angle.\n\n    Parameters\n    ----------\n    surface_tilt : numeric\n        Surface tilt angles in decimal degrees. surface_tilt must be >=0\n        and <=180. The tilt angle is defined as degrees from horizontal\n        (e.g. surface facing up = 0, surface facing horizon = 90)\n\n    surface_azimuth : numeric\n        Surface azimuth angles in decimal degrees. surface_azimuth must\n        be >=0 and <=360. The Azimuth convention is defined as degrees\n        east of north (e.g. North = 0, South=180 East = 90, West = 270).\n\n    dhi : numeric\n        Diffuse horizontal irradiance in W/m^2. DHI must be >=0.\n\n    ghi : numeric\n        Global irradiance in W/m^2. DNI must be >=0.\n\n    solar_zenith : numeric\n        Apparent (refraction-corrected) zenith angles in decimal\n        degrees. solar_zenith must be >=0 and <=180.\n\n    solar_azimuth : numeric\n        Sun azimuth angles in decimal degrees. solar_azimuth must be >=0\n        and <=360. The Azimuth convention is defined as degrees east of\n        north (e.g. North = 0, East = 90, West = 270).\n\n    Returns\n    -------\n    diffuse : numeric\n        The sky diffuse component of the solar radiation.\n\n    References\n    ----------\n    [1] Loutzenhiser P.G. et. al. \"Empirical validation of models to compute\n    solar irradiance on inclined surfaces for building energy simulation\"\n    2007, Solar Energy vol. 81. pp. 254-267\n\n    [2] Klucher, T.M., 1979. Evaluation of models to predict insolation on\n    tilted surfaces. Solar Energy 23 (2), 111-114."
  },
  {
    "code": "def toggle_badge(self, kind):\n        badge = self.get_badge(kind)\n        if badge:\n            return self.remove_badge(kind)\n        else:\n            return self.add_badge(kind)",
    "docstring": "Toggle a bdage given its kind"
  },
  {
    "code": "def _cache_get_for_dn(self, dn: str) -> Dict[str, bytes]:\n        self._do_with_retry(\n            lambda obj: obj.search(\n                dn,\n                '(objectclass=*)',\n                ldap3.BASE,\n                attributes=['*', '+']))\n        results = self._obj.response\n        if len(results) < 1:\n            raise NoSuchObject(\"No results finding current value\")\n        if len(results) > 1:\n            raise RuntimeError(\"Too many results finding current value\")\n        return results[0]['raw_attributes']",
    "docstring": "Object state is cached. When an update is required the update will be\n        simulated on this cache, so that rollback information can be correct.\n        This function retrieves the cached data."
  },
  {
    "code": "def is_won(grid):\n    \"Did the latest move win the game?\"\n    p, q = grid\n    return any(way == (way & q) for way in ways_to_win)",
    "docstring": "Did the latest move win the game?"
  },
  {
    "code": "def get_id_head(self):\n        id_head = None\n        for target_node in self:\n            if target_node.is_head():\n                id_head = target_node.get_id()\n                break\n        return id_head",
    "docstring": "Returns the id  of the target that is set as \"head\"\n        @rtype: string\n        @return: the target id (or None) of the head target"
  },
  {
    "code": "def assess_content(member,file_filter):\n    member_path = member.name.replace('.','',1)\n    if len(member_path) == 0:\n        return False\n    if \"skip_files\" in file_filter:\n        if member_path in file_filter['skip_files']:\n            return False\n    if \"assess_content\" in file_filter:\n        if member_path in file_filter['assess_content']:\n            return True\n    return False",
    "docstring": "Determine if the filter wants the file to be read for content.\n    In the case of yes, we would then want to add the content to the\n    hash and not the file object."
  },
  {
    "code": "def scale_samples(params, bounds):\n    b = np.array(bounds)\n    lower_bounds = b[:, 0]\n    upper_bounds = b[:, 1]\n    if np.any(lower_bounds >= upper_bounds):\n        raise ValueError(\"Bounds are not legal\")\n    np.add(np.multiply(params,\n                       (upper_bounds - lower_bounds),\n                       out=params),\n           lower_bounds,\n           out=params)",
    "docstring": "Rescale samples in 0-to-1 range to arbitrary bounds\n\n    Arguments\n    ---------\n    bounds : list\n        list of lists of dimensions `num_params`-by-2\n    params : numpy.ndarray\n        numpy array of dimensions `num_params`-by-:math:`N`,\n        where :math:`N` is the number of samples"
  },
  {
    "code": "def get_duration_metadata(self):\n        metadata = dict(self._mdata['duration'])\n        metadata.update({'existing_duration_values': self._my_map['duration']})\n        return Metadata(**metadata)",
    "docstring": "Gets the metadata for the assessment duration.\n\n        return: (osid.Metadata) - metadata for the duration\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _in(ins):\n    output = _16bit_oper(ins.quad[1])\n    output.append('ld b, h')\n    output.append('ld c, l')\n    output.append('in a, (c)')\n    output.append('push af')\n    return output",
    "docstring": "Translates IN to asm."
  },
  {
    "code": "def encrypt(self, s, mac_bytes=10):\n        if isinstance(s, six.text_type):\n            raise ValueError(\n                \"Encode `s` to a bytestring yourself to\" +\n                \" prevent problems with different default encodings\")\n        out = BytesIO()\n        with self.encrypt_to(out, mac_bytes) as f:\n            f.write(s)\n        return out.getvalue()",
    "docstring": "Encrypt `s' for this pubkey."
  },
  {
    "code": "def _metadata_is_invalid(cls, fact):\n        return any(isinstance(token, URIRef) and ' ' in token\n                   for token in fact)",
    "docstring": "Determines if the fact is not well formed."
  },
  {
    "code": "def post(self, path, auth=None, **kwargs):\n        return self._check_ok(self._post(path, auth=auth, **kwargs))",
    "docstring": "Manually make a POST request.\n\n        :param str path: relative url of the request (e.g. `/users/username`)\n        :param auth.Authentication auth: authentication object\n        :param kwargs dict: Extra arguments for the request, as supported by the\n                            `requests <http://docs.python-requests.org/>`_ library.\n        :raises NetworkFailure: if there is an error communicating with the server\n        :raises ApiFailure: if the request cannot be serviced"
  },
  {
    "code": "def add_context_action(self, action):\n        self.main_tab_widget.context_actions.append(action)\n        for child_splitter in self.child_splitters:\n            child_splitter.add_context_action(action)",
    "docstring": "Adds a custom context menu action\n\n        :param action: action to add."
  },
  {
    "code": "def rolling_window_sequences(X, index, window_size, target_size, target_column):\n    out_X = list()\n    out_y = list()\n    X_index = list()\n    y_index = list()\n    target = X[:, target_column]\n    for start in range(len(X) - window_size - target_size + 1):\n        end = start + window_size\n        out_X.append(X[start:end])\n        out_y.append(target[end:end + target_size])\n        X_index.append(index[start])\n        y_index.append(index[end])\n    return np.asarray(out_X), np.asarray(out_y), np.asarray(X_index), np.asarray(y_index)",
    "docstring": "Create rolling window sequences out of timeseries data."
  },
  {
    "code": "def redirect_logging(tqdm_obj, logger=logging.getLogger()):\n  assert(len(logger.handlers) == 1)\n  prev_handler = logger.handlers[0]\n  logger.removeHandler(prev_handler)\n  tqdm_handler = TqdmLoggingHandler(tqdm_obj)\n  if prev_handler.formatter is not None:\n    tqdm_handler.setFormatter(prev_handler.formatter)\n  logger.addHandler(tqdm_handler)\n  try:\n    yield\n  finally:\n    logger.removeHandler(tqdm_handler)\n    logger.addHandler(prev_handler)",
    "docstring": "Context manager to redirect logging to a TqdmLoggingHandler object and then restore the original."
  },
  {
    "code": "def horizon_dashboard_nav(context):\n    if 'request' not in context:\n        return {}\n    dashboard = context['request'].horizon['dashboard']\n    panel_groups = dashboard.get_panel_groups()\n    non_empty_groups = []\n    for group in panel_groups.values():\n        allowed_panels = []\n        for panel in group:\n            if (callable(panel.nav) and panel.nav(context) and\n                    panel.can_access(context)):\n                allowed_panels.append(panel)\n            elif (not callable(panel.nav) and panel.nav and\n                    panel.can_access(context)):\n                allowed_panels.append(panel)\n        if allowed_panels:\n            if group.name is None:\n                non_empty_groups.append((dashboard.name, allowed_panels))\n            else:\n                non_empty_groups.append((group.name, allowed_panels))\n    return {'components': OrderedDict(non_empty_groups),\n            'user': context['request'].user,\n            'current': context['request'].horizon['panel'].slug,\n            'request': context['request']}",
    "docstring": "Generates sub-navigation entries for the current dashboard."
  },
  {
    "code": "def lookup_function(val):\n\t\"Look-up and return a pretty-printer that can print va.\"\n\ttype = val.type\n\tif type.code == gdb.TYPE_CODE_REF:\n\t\ttype = type.target()\n\ttype = type.unqualified().strip_typedefs()\n\ttypename = type.tag\n\tif typename == None:\n\t\treturn None\n\tfor function in pretty_printers_dict:\n\t\tif function.search(typename):\n\t\t\treturn pretty_printers_dict[function](val)\n\treturn None",
    "docstring": "Look-up and return a pretty-printer that can print va."
  },
  {
    "code": "def start(self):\n        self.parse_opt()\n        self.parse_cfg()\n        if self.options.browse or self.options.browse_big or self.options.progress:\n            self.browse()\n            raise SystemExit\n        paramlist = []\n        for exp in self.cfgparser.sections():\n            if not self.options.experiments or exp in self.options.experiments:\n                params = self.items_to_params(self.cfgparser.items(exp))\n                params['name'] = exp\n                paramlist.append(params)\n        self.do_experiment(paramlist)",
    "docstring": "starts the experiments as given in the config file."
  },
  {
    "code": "def date_to_datetime(self, time_input, tz=None):\n        dt = None\n        try:\n            dt = parser.parse(time_input)\n            if tz is not None and tz != dt.tzname():\n                if dt.tzinfo is None:\n                    dt = self._replace_timezone(dt)\n                dt = dt.astimezone(timezone(tz))\n        except IndexError:\n            pass\n        except TypeError:\n            pass\n        except ValueError:\n            pass\n        return dt",
    "docstring": "Convert ISO 8601 and other date strings to datetime.datetime type.\n\n        Args:\n            time_input (string): The time input string (see formats above).\n            tz (string): The time zone for the returned data.\n\n        Returns:\n            (datetime.datetime): Python datetime.datetime object."
  },
  {
    "code": "def _on_wheel_event(self, event):\n        try:\n            delta = event.angleDelta().y()\n        except AttributeError:\n            delta = event.delta()\n        if int(event.modifiers()) & QtCore.Qt.ControlModifier > 0:\n            if delta < self.prev_delta:\n                self.editor.zoom_out()\n                event.accept()\n            else:\n                self.editor.zoom_in()\n                event.accept()",
    "docstring": "Increments or decrements editor fonts settings on mouse wheel event\n        if ctrl modifier is on.\n\n        :param event: wheel event\n        :type event: QWheelEvent"
  },
  {
    "code": "def display_exc(self):\n        errmsg = self.get_error()\n        if errmsg is not None:\n            if self.path is not None:\n                errmsg_lines = [\"in \" + self.path + \":\"]\n                for line in errmsg.splitlines():\n                    if line:\n                        line = \" \" * taberrfmt + line\n                    errmsg_lines.append(line)\n                errmsg = \"\\n\".join(errmsg_lines)\n            printerr(errmsg)",
    "docstring": "Properly prints an exception in the exception context."
  },
  {
    "code": "def load_event_list(filename, **kwargs):\n    return dcase_util.containers.MetaDataContainer().load(filename=filename, **kwargs)",
    "docstring": "Load event list from csv formatted text-file\n\n    Supported formats (see more `dcase_util.containers.MetaDataContainer.load()` method):\n\n    - [event onset (float >= 0)][delimiter][event offset (float >= 0)]\n    - [event onset (float >= 0)][delimiter][event offset (float >= 0)][delimiter][label]\n    - [filename][delimiter][event onset (float >= 0)][delimiter][event offset (float >= 0)][delimiter][event label]\n    - [filename][delimiter][scene_label][delimiter][event onset (float >= 0)][delimiter][event offset (float >= 0)][delimiter][event label]\n    - [filename]\n\n    Supported delimiters: ``,``, ``;``, ``tab``\n\n    Example of event list file::\n\n        21.64715\t23.00552\talert\n        36.91184\t38.27021\talert\n        69.72575\t71.09029\talert\n        63.53990\t64.89827\talert\n        84.25553\t84.83920\talert\n        20.92974\t21.82661\tclearthroat\n        28.39992\t29.29679\tclearthroat\n        80.47837\t81.95937\tclearthroat\n        44.48363\t45.96463\tclearthroat\n        78.13073\t79.05953\tclearthroat\n        15.17031\t16.27235\tcough\n        20.54931\t21.65135\tcough\n        27.79964\t28.90168\tcough\n        75.45959\t76.32490\tcough\n        70.81708\t71.91912\tcough\n        21.23203\t22.55902\tdoorslam\n        7.546220\t9.014880\tdoorslam\n        34.11303\t35.04183\tdoorslam\n        45.86001\t47.32867\tdoorslam\n\n\n    Parameters\n    ----------\n    filename : str\n        Path to the csv-file\n\n    Returns\n    -------\n    list of dict\n        Event list"
  },
  {
    "code": "def iiscgi(application):\n\ttry:\n\t\tfrom wsgiref.handlers import IISCGIHandler\n\texcept ImportError:\n\t\tprint(\"Python 3.2 or newer is required.\")\n\tif not __debug__:\n\t\twarnings.warn(\"Interactive debugging and other persistence-based processes will not work.\")\n\tIISCGIHandler().run(application)",
    "docstring": "A specialized version of the reference WSGI-CGI server to adapt to Microsoft IIS quirks.\n\t\n\tThis is not a production quality interface and will behave badly under load."
  },
  {
    "code": "def emit_containers(self, containers, verbose=True):\n        containers = sorted(containers, key=lambda c: c.get('name'))\n        task_definition = {\n            'family': self.family,\n            'containerDefinitions': containers,\n            'volumes': self.volumes or []\n        }\n        if verbose:\n            return json.dumps(task_definition, indent=4, sort_keys=True)\n        else:\n            return json.dumps(task_definition)",
    "docstring": "Emits the task definition and sorts containers by name\n\n        :param containers: List of the container definitions\n        :type containers: list of dict\n\n        :param verbose: Print out newlines and indented JSON\n        :type verbose: bool\n\n        :returns: The text output\n        :rtype: str"
  },
  {
    "code": "def create_config(name=None,\n                  subvolume=None,\n                  fstype=None,\n                  template=None,\n                  extra_opts=None):\n    def raise_arg_error(argname):\n        raise CommandExecutionError(\n            'You must provide a \"{0}\" for the new configuration'.format(argname)\n        )\n    if not name:\n        raise_arg_error(\"name\")\n    if not subvolume:\n        raise_arg_error(\"subvolume\")\n    if not fstype:\n        raise_arg_error(\"fstype\")\n    if not template:\n        template = \"\"\n    try:\n        snapper.CreateConfig(name, subvolume, fstype, template)\n        if extra_opts:\n            set_config(name, **extra_opts)\n        return get_config(name)\n    except dbus.DBusException as exc:\n        raise CommandExecutionError(\n            'Error encountered while creating the new configuration: {0}'\n            .format(_dbus_exception_to_reason(exc, locals()))\n        )",
    "docstring": "Creates a new Snapper configuration\n\n    name\n        Name of the new Snapper configuration.\n    subvolume\n        Path to the related subvolume.\n    fstype\n        Filesystem type of the subvolume.\n    template\n        Configuration template to use. (Default: default)\n    extra_opts\n        Extra Snapper configuration opts dictionary. It will override the values provided\n        by the given template (if any).\n\n    CLI example:\n\n    .. code-block:: bash\n\n      salt '*' snapper.create_config name=myconfig subvolume=/foo/bar/ fstype=btrfs\n      salt '*' snapper.create_config name=myconfig subvolume=/foo/bar/ fstype=btrfs template=\"default\"\n      salt '*' snapper.create_config name=myconfig subvolume=/foo/bar/ fstype=btrfs extra_opts='{\"NUMBER_CLEANUP\": False}'"
  },
  {
    "code": "def register_components(self):\n        unregistered_components = []\n        for path in self.paths:\n            for file in foundations.walkers.files_walker(path, (\"\\.{0}$\".format(self.__extension),), (\"\\._\",)):\n                if not self.register_component(file):\n                    unregistered_components.append(file)\n        if not unregistered_components:\n            return True\n        else:\n            raise manager.exceptions.ComponentRegistrationError(\n                \"{0} | '{1}' Components failed to register!\".format(self.__class__.__name__,\n                                                                    \", \".join(unregistered_components)))",
    "docstring": "Registers the Components.\n\n        Usage::\n\n            >>> manager = Manager((\"./manager/tests/tests_manager/resources/components/core\",))\n            >>> manager.register_components()\n            True\n            >>> manager.components.keys()\n            [u'core.tests_component_a', u'core.tests_component_b']\n\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def get_all_external_accounts(resource_root, type_name, view=None):\n  return call(resource_root.get,\n      EXTERNAL_ACCOUNT_FETCH_PATH % (\"type\", type_name,),\n      ApiExternalAccount, True, params=view and dict(view=view) or None)",
    "docstring": "Lookup all external accounts of a particular type, by type name.\n  @param resource_root: The root Resource object.\n  @param type_name: Type name\n  @param view: View\n  @return: An ApiList of ApiExternalAccount objects matching the specified type"
  },
  {
    "code": "def addUnexpectedSuccess(self, test):\n        result = self._handle_result(\n            test, TestCompletionStatus.unexpected_success)\n        self.unexpectedSuccesses.append(result)",
    "docstring": "Register a test that passed unexpectedly.\n\n        Parameters\n        ----------\n        test : unittest.TestCase\n            The test that has completed."
  },
  {
    "code": "def get_what_follows_raw(s: str,\n                         prefix: str,\n                         onlyatstart: bool = True,\n                         stripwhitespace: bool = True) -> Tuple[bool, str]:\n    prefixstart = s.find(prefix)\n    if ((prefixstart == 0 and onlyatstart) or\n            (prefixstart != -1 and not onlyatstart)):\n        resultstart = prefixstart + len(prefix)\n        result = s[resultstart:]\n        if stripwhitespace:\n            result = result.strip()\n        return True, result\n    return False, \"\"",
    "docstring": "Find the part of ``s`` that is after ``prefix``.\n\n    Args:\n        s: string to analyse\n        prefix: prefix to find\n        onlyatstart: only accept the prefix if it is right at the start of\n            ``s``\n        stripwhitespace: remove whitespace from the result\n\n    Returns:\n        tuple: ``(found, result)``"
  },
  {
    "code": "def get_all():\n  info_dir = _get_info_dir()\n  results = []\n  for filename in os.listdir(info_dir):\n    filepath = os.path.join(info_dir, filename)\n    try:\n      with open(filepath) as infile:\n        contents = infile.read()\n    except IOError as e:\n      if e.errno == errno.EACCES:\n        continue\n      else:\n        raise\n    try:\n      info = _info_from_string(contents)\n    except ValueError:\n      tb_logging.get_logger().warning(\n          \"invalid info file: %r\",\n          filepath,\n          exc_info=True,\n      )\n    else:\n      results.append(info)\n  return results",
    "docstring": "Return TensorBoardInfo values for running TensorBoard processes.\n\n  This function may not provide a perfect snapshot of the set of running\n  processes. Its result set may be incomplete if the user has cleaned\n  their /tmp/ directory while TensorBoard processes are running. It may\n  contain extraneous entries if TensorBoard processes exited uncleanly\n  (e.g., with SIGKILL or SIGQUIT).\n\n  Returns:\n    A fresh list of `TensorBoardInfo` objects."
  },
  {
    "code": "def drop_columns(self, colnames, **kwargs):\n        new_arr = rfn.drop_fields(\n            self, colnames, usemask=False, asrecarray=True, **kwargs\n        )\n        return self.__class__(\n            new_arr,\n            h5loc=self.h5loc,\n            split_h5=self.split_h5,\n            name=self.name,\n            h5singleton=self.h5singleton\n        )",
    "docstring": "Drop  columns from the table.\n\n        See the docs for ``numpy.lib.recfunctions.drop_fields`` for an\n        explanation of the remaining options."
  },
  {
    "code": "def reference(self):\n    if self.__reference is None:\n      self.__reference = _ConstructReference(self.__class__,\n                                             pairs=self.__pairs,\n                                             app=self.__app,\n                                             namespace=self.__namespace)\n    return self.__reference",
    "docstring": "Return the Reference object for this Key.\n\n    This is a entity_pb.Reference instance -- a protocol buffer class\n    used by the lower-level API to the datastore.\n\n    NOTE: The caller should not mutate the return value."
  },
  {
    "code": "def add_relationship(self, term1, relationship, term2):\n        url = self.base_path + 'term/add-relationship'\n        data = {'term1_id': term1['id'],\n                'relationship_tid': relationship['id'],\n                'term2_id': term2['id'],\n                'term1_version': term1['version'],\n                'relationship_term_version': relationship['version'],\n                'term2_version': term2['version']}\n        return self.post(url, data)",
    "docstring": "Creates a relationship between 3 entities in database"
  },
  {
    "code": "def step(self, provided_inputs):\n        for wire, value in provided_inputs.items():\n            wire = self.block.get_wirevector_by_name(wire) if isinstance(wire, str) else wire\n            if value > wire.bitmask or value < 0:\n                raise PyrtlError(\"Wire {} has value {} which cannot be represented\"\n                                 \" using its bitwidth\".format(wire, value))\n        ins = {self._to_name(wire): value for wire, value in provided_inputs.items()}\n        ins.update(self.regs)\n        ins.update(self.mems)\n        self.regs, self.outs, mem_writes = self.sim_func(ins)\n        for mem, addr, value in mem_writes:\n            self.mems[mem][addr] = value\n        self.context = self.outs.copy()\n        self.context.update(ins)\n        if self.tracer is not None:\n            self.tracer.add_fast_step(self)\n        check_rtl_assertions(self)",
    "docstring": "Run the simulation for a cycle\n\n        :param provided_inputs: a dictionary mapping WireVectors (or their names)\n          to their values for this step\n          eg: {wire: 3, \"wire_name\": 17}"
  },
  {
    "code": "def get_background_sids(self, src_filter):\n        branch_key = self.idx_set[\"grid_key\"]\n        idist = src_filter.integration_distance(DEFAULT_TRT)\n        with h5py.File(self.source_file, 'r') as hdf5:\n            bg_locations = hdf5[\"Grid/Locations\"].value\n            distances = min_geodetic_distance(\n                src_filter.sitecol.xyz,\n                (bg_locations[:, 0], bg_locations[:, 1]))\n            mmax_areas = self.msr.get_median_area(\n                hdf5[\"/\".join([\"Grid\", branch_key, \"MMax\"])].value, 0.0)\n            mmax_lengths = numpy.sqrt(mmax_areas / self.aspect)\n            ok = distances <= (0.5 * mmax_lengths + idist)\n            return numpy.where(ok)[0].tolist()",
    "docstring": "We can apply the filtering of the background sites as a pre-processing\n        step - this is done here rather than in the sampling of the ruptures\n        themselves"
  },
  {
    "code": "def get(self, key, fallback=None):\n        value = None\n        if key in self._config:\n            value = self._config[key]\n            if isinstance(value, Section):\n                value = None\n        if value is None:\n            value = fallback\n        return value",
    "docstring": "look up global config values from alot's config\n\n        :param key: key to look up\n        :type key: str\n        :param fallback: fallback returned if key is not present\n        :type fallback: str\n        :returns: config value with type as specified in the spec-file"
  },
  {
    "code": "def delete(self, db_session=None):\n        db_session = get_db_session(db_session, self)\n        db_session.delete(self)",
    "docstring": "Deletes the object via session, this will permanently delete the\n        object from storage on commit\n\n        :param db_session:\n        :return:"
  },
  {
    "code": "def _range_along_dimension(range_dim, shape):\n  rank = len(shape)\n  if range_dim >= rank:\n    raise ValueError(\"Cannot calculate range along non-existent index.\")\n  indices = tf.range(start=0, limit=shape[range_dim])\n  indices = tf.reshape(\n      indices,\n      shape=[1 if i != range_dim else shape[range_dim] for i in range(rank)])\n  return tf.tile(indices,\n                 [shape[i] if i != range_dim else 1 for i in range(rank)])",
    "docstring": "Construct a Tensor whose values are the index along a dimension.\n\n  Construct a Tensor that counts the distance along a single dimension. This is\n  useful, for example, when constructing an identity matrix,\n\n    >>> x = _range_along_dimension(0, [2, 2]).eval()\n    >>> x\n    array([[0, 0],\n           [1, 1]], dtype=int32)\n\n    >>> y = _range_along_dimension(1, [2, 2]).eval()\n    >>> y\n    array([[0, 1],\n           [0, 1]], dtype=int32)\n\n    >>> tf.cast(tf.equal(x, y), dtype=tf.int32).eval()\n    array([[1, 0],\n           [0, 1]], dtype=int32)\n\n  Args:\n    range_dim: int. Dimension to count indices on.\n    shape: 1D Tensor of ints. Shape of Tensor to construct.\n\n  Returns:\n    A Tensor whose values are the same as the range along dimension range_dim.\n\n  Raises:\n    ValueError: If range_dim isn't a valid dimension."
  },
  {
    "code": "def toggle(path_or_id, badge_kind):\n    if exists(path_or_id):\n        with open(path_or_id) as open_file:\n            for id_or_slug in open_file.readlines():\n                toggle_badge(id_or_slug.strip(), badge_kind)\n    else:\n        toggle_badge(path_or_id, badge_kind)",
    "docstring": "Toggle a `badge_kind` for a given `path_or_id`\n\n    The `path_or_id` is either an id, a slug or a file containing a list\n    of ids or slugs."
  },
  {
    "code": "def GetName(obj):\n  precondition.AssertType(obj, (type, types.FunctionType))\n  if PY2:\n    return obj.__name__.decode(\"ascii\")\n  else:\n    return obj.__name__",
    "docstring": "A compatibility wrapper for getting object's name.\n\n  In Python 2 class names are returned as `bytes` (since class names can contain\n  only ASCII characters) whereas in Python 3 they are `unicode` (since class\n  names can contain arbitrary unicode characters).\n\n  This function makes this behaviour consistent and always returns class name as\n  an unicode string.\n\n  Once support for Python 2 is dropped all invocations of this call can be\n  replaced with ordinary `__name__` access.\n\n  Args:\n    obj: A type or function object to get the name for.\n\n  Returns:\n    Name of the specified class as unicode string."
  },
  {
    "code": "def drop_namespaces(self):\n        self.session.query(NamespaceEntry).delete()\n        self.session.query(Namespace).delete()\n        self.session.commit()",
    "docstring": "Drop all namespaces."
  },
  {
    "code": "def load_file(self, file):\n        if not foundations.common.path_exists(file):\n            raise foundations.exceptions.FileExistsError(\n                \"{0} | '{1}' file doesn't exists!\".format(self.__class__.__name__,\n                                                          file))\n        LOGGER.debug(\"> Loading '{0}' file.\".format(file))\n        reader = foundations.io.File(file)\n        self.setPlainText(reader.read())\n        self.set_file(file)\n        self.__set_document_signals()\n        self.file_loaded.emit()\n        return True",
    "docstring": "Reads and loads given file into the editor.\n\n        :param File: File to load.\n        :type File: unicode\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def deserialize(self, data, status_code):\n        if status_code == 204:\n            return data\n        return serializer.Serializer().deserialize(\n            data)['body']",
    "docstring": "Deserializes a JSON string into a dictionary."
  },
  {
    "code": "def _get_bmu(self, activations):\n        if self.argfunc == 'argmax':\n            activations = -activations\n        sort = np.argsort(activations, 1)\n        return sort.argsort()",
    "docstring": "Get indices of bmus, sorted by their distance from input."
  },
  {
    "code": "def imread(path, grayscale=False, size=None, interpolate=\"bilinear\",\n           channel_first=False, as_uint16=False, num_channels=-1):\n    _imread_before(grayscale, num_channels)\n    r_mode = cv2.IMREAD_GRAYSCALE if grayscale else cv2.IMREAD_UNCHANGED\n    img = _imread_helper(path, r_mode)\n    if as_uint16 and img.dtype != np.uint16:\n        if img.dtype == np.uint8:\n            logger.warning(\"You want to read image as uint16, but the original bit-depth is 8 bit.\"\n                           \"All pixel values are simply increased by 256 times.\")\n            img = img.astype(np.uint16) * 256\n        else:\n            raise ValueError(\n                \"casting {} to uint16 is not safe.\".format(img.dtype))\n    img = _cvtColor_helper(img, num_channels)\n    img = _imread_after(img, size, interpolate, channel_first, imresize)\n    return img",
    "docstring": "Read image by cv2 module.\n\n    Args:\n        path (str or 'file object'): File path or object to read.\n        grayscale (bool):\n        size (tupple of int):\n            (width, height).\n            If None, output img shape depends on the files to read.\n        channel_first (bool):\n            This argument specifies the shape of img is whether (height, width, channel) or (channel, height, width).\n            Default value is False, which means the img shape is (height, width, channel).\n        interpolate (str):\n            must be one of [\"nearest\", \"box\", \"bilinear\", \"hamming\", \"bicubic\", \"lanczos\"].\n        as_uint16 (bool):\n            If True, this function reads image as uint16.\n        num_channels (int):\n            channel size of output array.\n            Default is -1 which preserves raw image shape.\n\n    Returns:\n         numpy.ndarray"
  },
  {
    "code": "def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None):\n        zone_properties = {\"name\": zone_name, \"accountName\": account_name, \"type\": \"PRIMARY\"}\n        if tsig_key is not None and key_value is not None:\n            name_server_info = {\"ip\": master, \"tsigKey\": tsig_key, \"tsigKeyValue\": key_value}\n        else:\n            name_server_info = {\"ip\": master}\n        primary_zone_info = {\"forceImport\": True, \"createType\": \"TRANSFER\", \"nameServer\": name_server_info}\n        zone_data = {\"properties\": zone_properties, \"primaryCreateInfo\": primary_zone_info}\n        return self.rest_api_connection.post(\"/v1/zones\", json.dumps(zone_data))",
    "docstring": "Creates a new primary zone by zone transferring off a master.\n\n        Arguments:\n        account_name -- The name of the account that will contain this zone.\n        zone_name -- The name of the zone.  It must be unique.\n        master -- Primary name server IP address.\n\n        Keyword Arguments:\n        tsig_key -- For TSIG-enabled zones: The transaction signature key.\n                    NOTE: Requires key_value.\n        key_value -- TSIG key secret."
  },
  {
    "code": "def coinc(self, s0, s1, slide, step):\n        loglr = - s0 - s1\n        threshes = [self.fits_by_tid[i]['thresh'] for i in self.ifos]\n        loglr += sum([t**2. / 2. for t in threshes])\n        return (2. * loglr) ** 0.5",
    "docstring": "Calculate the final coinc ranking statistic"
  },
  {
    "code": "def expect(instr, expected, context):\n    if not isinstance(instr, expected):\n        raise DecompilationError(\n            \"Expected a {expected} instruction {context}. Got {instr}.\".format(\n                instr=instr, expected=expected, context=context,\n            )\n        )\n    return instr",
    "docstring": "Check that an instruction is of the expected type."
  },
  {
    "code": "def annotatedcore(self):\n        logging.info('Calculating annotated core')\n        self.total_core()\n        for sample in self.metadata:\n            if sample.general.bestassemblyfile != 'NA':\n                sample[self.analysistype].coreset = set()\n                if sample.general.referencegenus == 'Escherichia':\n                    self.runmetadata.samples.append(sample)\n                    try:\n                        report = sample[self.analysistype].report\n                        self.blastparser(report=report,\n                                         sample=sample,\n                                         fieldnames=self.fieldnames)\n                    except KeyError:\n                        sample[self.analysistype].coreset = list()\n        self.reporter()",
    "docstring": "Calculates the core genome of organisms using custom databases"
  },
  {
    "code": "def attach(self, engine, start=Events.STARTED, pause=Events.COMPLETED, resume=None, step=None):\n        engine.add_event_handler(start, self.reset)\n        engine.add_event_handler(pause, self.pause)\n        if resume is not None:\n            engine.add_event_handler(resume, self.resume)\n        if step is not None:\n            engine.add_event_handler(step, self.step)\n        return self",
    "docstring": "Register callbacks to control the timer.\n\n        Args:\n            engine (Engine):\n                Engine that this timer will be attached to.\n            start (Events):\n                Event which should start (reset) the timer.\n            pause (Events):\n                Event which should pause the timer.\n            resume (Events, optional):\n                Event which should resume the timer.\n            step (Events, optional):\n                Event which should call the `step` method of the counter.\n\n        Returns:\n            self (Timer)"
  },
  {
    "code": "def reactivate(self):\n        self._protocol.connectionLost(None)\n        self._protocol = None\n        self.terminal.reset()\n        self._window.filthy()\n        self._window.repaint()",
    "docstring": "Called when a sub-protocol is finished.  This disconnects the\n        sub-protocol and redraws the main menu UI."
  },
  {
    "code": "def generate_sigv4_auth_request(header_value=None):\n    request = requests.Request(\n        method='POST',\n        url='https://sts.amazonaws.com/',\n        headers={'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'Host': 'sts.amazonaws.com'},\n        data='Action=GetCallerIdentity&Version=2011-06-15',\n    )\n    if header_value:\n        request.headers['X-Vault-AWS-IAM-Server-ID'] = header_value\n    prepared_request = request.prepare()\n    return prepared_request",
    "docstring": "Helper function to prepare a AWS API request to subsequently generate a \"AWS Signature Version 4\" header.\n\n    :param header_value: Vault allows you to require an additional header, X-Vault-AWS-IAM-Server-ID, to be present\n        to mitigate against different types of replay attacks. Depending on the configuration of the AWS auth\n        backend, providing a argument to this optional parameter may be required.\n    :type header_value: str\n    :return: A PreparedRequest instance, optionally containing the provided header value under a\n        'X-Vault-AWS-IAM-Server-ID' header name pointed to AWS's simple token service with action \"GetCallerIdentity\"\n    :rtype: requests.PreparedRequest"
  },
  {
    "code": "def get_descriptions(self, description_type):\n        (desc_type, max_units) = description_type\n        results = [None] * max_units\n        self.elk._descriptions_in_progress[desc_type] = (max_units,\n                                                         results,\n                                                         self._got_desc)\n        self.elk.send(sd_encode(desc_type=desc_type, unit=0))",
    "docstring": "Gets the descriptions for specified type.\n        When complete the callback is called with a list of descriptions"
  },
  {
    "code": "def enter_room(self, sid, namespace, room):\n        if namespace not in self.rooms:\n            self.rooms[namespace] = {}\n        if room not in self.rooms[namespace]:\n            self.rooms[namespace][room] = {}\n        self.rooms[namespace][room][sid] = True",
    "docstring": "Add a client to a room."
  },
  {
    "code": "def hangup(self):\n        if self.active:\n            self._gsmModem.write('ATH')\n            self.answered = False\n            self.active = False\n        if self.id in self._gsmModem.activeCalls:\n            del self._gsmModem.activeCalls[self.id]",
    "docstring": "End the phone call.\n        \n        Does nothing if the call is already inactive."
  },
  {
    "code": "def check(self, feature):\n    found = False\n    for handler in self.handlers:\n      try:\n        if handler(feature):\n           return True\n      except StopCheckingFeatureFlags:\n        return False\n      except NoFeatureFlagFound:\n        pass\n      else:\n        found = True\n    if not found:\n      message = u\"No feature flag defined for {feature}\".format(feature=feature)\n      if current_app.debug and current_app.config.get(RAISE_ERROR_ON_MISSING_FEATURES, False):\n        raise KeyError(message)\n      else:\n        log.info(message)\n        missing_feature.send(self, feature=feature)\n    return False",
    "docstring": "Loop through all our feature flag checkers and return true if any of them are true.\n\n    The order of handlers matters - we will immediately return True if any handler returns true.\n\n    If you want to a handler to return False and stop the chain, raise the StopCheckingFeatureFlags exception."
  },
  {
    "code": "def ordered(self, ord='desc'):\n        if ord not in ('asc', 'desc', ):\n            raise\n        ord_f = getattr(PIDRelation.index, ord)()\n        return self.order_by(ord_f)",
    "docstring": "Order the query result on the relations' indexes."
  },
  {
    "code": "def get_settings(config_file):\n    default_settings = {\n        'general': {\n            'endpoint': 'http://guacamole.antojitos.io/files/',\n            'shortener': 'http://t.antojitos.io/api/v1/urls',\n        }\n    }\n    settings = configparser.ConfigParser()\n    try:\n        settings.read_dict(default_settings)\n    except AttributeError:\n        for section, options in default_settings.items():\n            settings.add_section(section)\n            for option, value in options.items():\n                settings.set(section, option, value)\n    if config_file is not None and os.path.exists(config_file):\n        settings.read(config_file)\n        return settings\n    if os.path.exists(CONFIG_FILE):\n        settings.read(CONFIG_FILE)\n        return settings\n    return settings",
    "docstring": "Search and load a configuration file."
  },
  {
    "code": "def get_colormap(name, *args, **kwargs):\n    if isinstance(name, BaseColormap):\n        cmap = name\n    else:\n        if not isinstance(name, string_types):\n            raise TypeError('colormap must be a Colormap or string name')\n        if name not in _colormaps:\n            raise KeyError('colormap name %s not found' % name)\n        cmap = _colormaps[name]\n        if inspect.isclass(cmap):\n            cmap = cmap(*args, **kwargs)\n    return cmap",
    "docstring": "Obtain a colormap\n\n    Some colormaps can have additional configuration parameters. Refer to\n    their corresponding documentation for more information.\n\n    Parameters\n    ----------\n    name : str | Colormap\n        Colormap name. Can also be a Colormap for pass-through.\n\n    Examples\n    --------\n\n        >>> get_colormap('autumn')\n        >>> get_colormap('single_hue', hue=10)"
  },
  {
    "code": "def rm(pattern):\n    paths = glob.glob(pattern)\n    for path in paths:\n        if path.startswith('.git/'):\n            continue\n        if os.path.isdir(path):\n            def onerror(fun, path, excinfo):\n                exc = excinfo[1]\n                if exc.errno != errno.ENOENT:\n                    raise\n            safe_print(\"rmdir -f %s\" % path)\n            shutil.rmtree(path, onerror=onerror)\n        else:\n            safe_print(\"rm %s\" % path)\n            os.remove(path)",
    "docstring": "Recursively remove a file or dir by pattern."
  },
  {
    "code": "def create_and_configure_wrapper(context_or_world):\n    context_or_world.driver_wrapper = DriverWrappersPool.get_default_wrapper()\n    context_or_world.utils = context_or_world.driver_wrapper.utils\n    try:\n        behave_properties = context_or_world.config.userdata\n    except AttributeError:\n        behave_properties = None\n    context_or_world.driver_wrapper.configure(context_or_world.config_files, behave_properties=behave_properties)\n    context_or_world.toolium_config = context_or_world.driver_wrapper.config\n    context_or_world.logger = logging.getLogger(__name__)",
    "docstring": "Create and configure driver wrapper in behave or lettuce tests\n\n    :param context_or_world: behave context or lettuce world"
  },
  {
    "code": "def iter(self, start=0, end=None):\n        if end is None:\n            end = self._index + 1\n        elif end == 0:\n            raise StopIteration()\n        if start >= end:\n            raise StopIteration()\n        assert 0 <= end <= len(self._history)\n        assert 0 <= start <= end - 1\n        for i in range(start, end):\n            yield self._history[i]",
    "docstring": "Iterate through successive history items.\n\n        Parameters\n        ----------\n        end : int\n            Index of the last item to loop through + 1.\n\n        start : int\n            Initial index for the loop (0 by default)."
  },
  {
    "code": "def _write_to_datastore(self):\n    roots_and_submissions = zip([ATTACKS_ENTITY_KEY,\n                                 TARGET_ATTACKS_ENTITY_KEY,\n                                 DEFENSES_ENTITY_KEY],\n                                [self._attacks,\n                                 self._targeted_attacks,\n                                 self._defenses])\n    client = self._datastore_client\n    with client.no_transact_batch() as batch:\n      for root_key, submissions in roots_and_submissions:\n        batch.put(client.entity(client.key(*root_key)))\n        for k, v in iteritems(submissions):\n          entity = client.entity(client.key(\n              *(root_key + [KIND_SUBMISSION, k])))\n          entity['submission_path'] = v.path\n          entity.update(participant_from_submission_path(v.path))\n          batch.put(entity)",
    "docstring": "Writes all submissions to datastore."
  },
  {
    "code": "def list_to_bytes_list(strList):\n    pList = c_char_p * len(strList)\n    if isinstance(strList, (pList, type(None))):\n        return strList\n    if not isinstance(strList, (list, set, tuple)):\n        raise TypeError(\"strList must be list, set or tuple, not \" +\n                str(type(strList)))\n    pList = pList()\n    for i, elem in enumerate(strList):\n        pList[i] = str_to_bytes(elem)\n    return pList",
    "docstring": "This function turns an array of strings into a pointer array\n    with pointers pointing to the encodings of those strings\n    Possibly contained bytes are kept as they are.\n\n    :param strList: List of strings that shall be converted\n    :type strList: List of strings\n    :returns: Pointer array with pointers pointing to bytes\n    :raises: TypeError if strList is not list, set or tuple"
  },
  {
    "code": "def pop_scope(self):\n        child_scope = self.stack.current.current.copy()\n        self.stack.current.pop()\n        parent_scope = self.stack.current.current.copy()\n        self.stack.current.current = {\n            key: child_scope[key] for key in child_scope if key in parent_scope\n        }",
    "docstring": "Delete the current scope in the current scope."
  },
  {
    "code": "def in_reply_to(self) -> Optional[UnstructuredHeader]:\n        try:\n            return cast(UnstructuredHeader, self[b'in-reply-to'][0])\n        except (KeyError, IndexError):\n            return None",
    "docstring": "The ``In-Reply-To`` header."
  },
  {
    "code": "def is_console(self, users_text):\n        if users_text is None:\n            self.log(\"Console information not collected\")\n            return None\n        for line in users_text.split('\\n'):\n            if '*' in line:\n                match = re.search(self.vty_re, line)\n                if match:\n                    self.log(\"Detected connection to vty\")\n                    return False\n                else:\n                    match = re.search(self.console_re, line)\n                    if match:\n                        self.log(\"Detected connection to console\")\n                        return True\n        self.log(\"Connection port unknown\")\n        return None",
    "docstring": "Return if device is connected over console."
  },
  {
    "code": "def _format_volume_string(self, volume_string):\n        self.actual_volume = int(volume_string.split(self.volume_string)[1].split(',')[0].split()[0])\n        return '[Vol: {}%] '.format(int(100 * self.actual_volume / self.max_volume))",
    "docstring": "format vlc's volume"
  },
  {
    "code": "def vicinity(self):\n        if self._vicinity == '' and self.details != None and 'vicinity' in self.details:\n            self._vicinity = self.details['vicinity']\n        return self._vicinity",
    "docstring": "Returns a feature name of a nearby location.\n\n        Often this feature refers to a street or neighborhood within the given\n        results."
  },
  {
    "code": "def get_messages(self, page=0):\n        endpoint = 'https://outlook.office.com/api/v2.0/me/messages'\n        if page > 0:\n            endpoint = endpoint + '/?%24skip=' + str(page) + '0'\n        log.debug('Getting messages from endpoint: {} with Headers: {}'.format(endpoint, self._headers))\n        r = requests.get(endpoint, headers=self._headers)\n        check_response(r)\n        return Message._json_to_messages(self, r.json())",
    "docstring": "Get first 10 messages in account, across all folders.\n\n        Keyword Args:\n            page (int): Integer representing the 'page' of results to fetch\n\n        Returns:\n            List[:class:`Message <pyOutlook.core.message.Message>`]"
  },
  {
    "code": "def mobile_template(template):\n    def decorator(f):\n        @functools.wraps(f)\n        def wrapper(*args, **kwargs):\n            ctx = stack.top\n            if ctx is not None and hasattr(ctx, 'request'):\n                request = ctx.request\n                is_mobile = getattr(request, 'MOBILE', None)\n                kwargs['template'] = re.sub(r'{(.+?)}',\n                                            r'\\1' if is_mobile else '',\n                                            template)\n            return f(*args, **kwargs)\n        return wrapper\n    return decorator",
    "docstring": "Mark a function as mobile-ready and pass a mobile template if MOBILE.\n\n    For example::\n\n        @mobile_template('a/{mobile/}b.html')\n        def view(template=None):\n            ...\n\n\n    if ``request.MOBILE=True`` the template will be `a/mobile/b.html`.\n    if ``request.MOBILE=False`` the template will be `a/b.html`.\n\n    This function is useful if the mobile view uses the same context but a\n    different template."
  },
  {
    "code": "def DisplayEstimate(message, min_estimate, max_estimate):\n  mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'],\n                                 max_estimate['averageCpc']['microAmount'])\n                  if 'averageCpc' in min_estimate\n                  and min_estimate['averageCpc'] else None)\n  mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'],\n                                 max_estimate['averagePosition'])\n                  if 'averagePosition' in min_estimate\n                  and min_estimate['averagePosition'] else None)\n  mean_clicks = _CalculateMean(min_estimate['clicksPerDay'],\n                               max_estimate['clicksPerDay'])\n  mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'],\n                                   max_estimate['totalCost']['microAmount'])\n  print message\n  print '  Estimated average CPC: %s' % _FormatMean(mean_avg_cpc)\n  print '  Estimated ad position: %s' % _FormatMean(mean_avg_pos)\n  print '  Estimated daily clicks: %s' % _FormatMean(mean_clicks)\n  print '  Estimated daily cost: %s' % _FormatMean(mean_total_cost)",
    "docstring": "Displays mean average cpc, position, clicks, and total cost for estimate.\n\n  Args:\n    message: str message to display for the given estimate.\n    min_estimate: sudsobject containing a minimum estimate from the\n      TrafficEstimatorService response.\n    max_estimate: sudsobject containing a maximum estimate from the\n      TrafficEstimatorService response."
  },
  {
    "code": "def show_tooltip(self, pos, tooltip, _sender_deco=None):\n        if _sender_deco is not None and _sender_deco not in self.decorations:\n            return\n        QtWidgets.QToolTip.showText(pos, tooltip[0: 1024], self)",
    "docstring": "Show a tool tip at the specified position\n\n        :param pos: Tooltip position\n        :param tooltip: Tooltip text\n\n        :param _sender_deco: TextDecoration which is the sender of the show\n            tooltip request. (for internal use only)."
  },
  {
    "code": "def load_reader_options():\n    options = os.environ['PANDOC_READER_OPTIONS']\n    options = json.loads(options, object_pairs_hook=OrderedDict)\n    return options",
    "docstring": "Retrieve Pandoc Reader options from the environment"
  },
  {
    "code": "def _make_minimal(dictionary):\n    new_dict = {}\n    for key, value in dictionary.items():\n        if value is not None:\n            if isinstance(value, dict):\n                new_value = _make_minimal(value)\n                if new_value:\n                    new_dict[key] = new_value\n            else:\n                new_dict[key] = value\n    return new_dict",
    "docstring": "This function removes all the keys whose value is either None or an empty\n    dictionary."
  },
  {
    "code": "def is_valid_vpnv4_prefix(prefix):\n    if not isinstance(prefix, str):\n        return False\n    tokens = prefix.split(':', 2)\n    if len(tokens) != 3:\n        return False\n    if not is_valid_route_dist(':'.join([tokens[0], tokens[1]])):\n        return False\n    return is_valid_ipv4_prefix(tokens[2])",
    "docstring": "Returns True if given prefix is a string represent vpnv4 prefix.\n\n    Vpnv4 prefix is made up of RD:Ipv4, where RD is represents route\n    distinguisher and Ipv4 represents valid dot-decimal ipv4 notation string."
  },
  {
    "code": "def start(self):\n        if not self._done_event.is_set():\n            return\n        self._done_event.clear()\n        nb_pending_tasks = self._queue.qsize()\n        if nb_pending_tasks > self._max_threads:\n            nb_threads = self._max_threads\n            nb_pending_tasks = self._max_threads\n        elif nb_pending_tasks < self._min_threads:\n            nb_threads = self._min_threads\n        else:\n            nb_threads = nb_pending_tasks\n        for _ in range(nb_pending_tasks):\n            self.__nb_pending_task += 1\n            self.__start_thread()\n        for _ in range(nb_threads - nb_pending_tasks):\n            self.__start_thread()",
    "docstring": "Starts the thread pool. Does nothing if the pool is already started."
  },
  {
    "code": "def write(self, file_or_path, append=False, timeout=10):\n        if isinstance(file_or_path, six.string_types):\n            if self.coverage:\n                file_or_path = get_smother_filename(\n                    file_or_path, self.coverage.config.parallel)\n            outfile = Lock(\n                file_or_path, mode='a+',\n                timeout=timeout,\n                fail_when_locked=False\n            )\n        else:\n            outfile = noclose(file_or_path)\n        with outfile as fh:\n            if append:\n                fh.seek(0)\n                try:\n                    other = Smother.load(fh)\n                except ValueError:\n                    pass\n                else:\n                    self |= other\n            fh.seek(0)\n            fh.truncate()\n            json.dump(self.data, fh)",
    "docstring": "Write Smother results to a file.\n\n        Parameters\n        ----------\n        fiile_or_path : str\n            Path to write report to\n        append : bool\n            If True, read an existing smother report from `outpath`\n            and combine it with this file before writing.\n        timeout : int\n            Time in seconds to wait to acquire a file lock, before\n            raising an error.\n\n        Note\n        ----\n        Append mode is atomic when file_or_path is a path,\n        and can be safely run in a multithreaded or\n        multiprocess test environment.\n\n        When using `parallel_mode`, file_or_path is given a unique\n        suffix based on the machine name and process id."
  },
  {
    "code": "def error_log(self, msg='', level=20, traceback=False):\n        sys.stderr.write(msg + '\\n')\n        sys.stderr.flush()\n        if traceback:\n            tblines = traceback_.format_exc()\n            sys.stderr.write(tblines)\n            sys.stderr.flush()",
    "docstring": "Write error message to log.\n\n        Args:\n            msg (str): error message\n            level (int): logging level\n            traceback (bool): add traceback to output or not"
  },
  {
    "code": "def handleOneClientMsg(self, wrappedMsg):\n        try:\n            vmsg = self.validateClientMsg(wrappedMsg)\n            if vmsg:\n                self.unpackClientMsg(*vmsg)\n        except BlowUp:\n            raise\n        except Exception as ex:\n            msg, frm = wrappedMsg\n            friendly = friendlyEx(ex)\n            if isinstance(ex, SuspiciousClient):\n                self.reportSuspiciousClient(frm, friendly)\n            self.handleInvalidClientMsg(ex, wrappedMsg)",
    "docstring": "Validate and process a client message\n\n        :param wrappedMsg: a message from a client"
  },
  {
    "code": "def GetUserinfo(credentials, http=None):\n    http = http or httplib2.Http()\n    url = _GetUserinfoUrl(credentials)\n    response, content = http.request(url)\n    if response.status == http_client.BAD_REQUEST:\n        credentials.refresh(http)\n        url = _GetUserinfoUrl(credentials)\n        response, content = http.request(url)\n    return json.loads(content or '{}')",
    "docstring": "Get the userinfo associated with the given credentials.\n\n    This is dependent on the token having either the userinfo.email or\n    userinfo.profile scope for the given token.\n\n    Args:\n      credentials: (oauth2client.client.Credentials) incoming credentials\n      http: (httplib2.Http, optional) http instance to use\n\n    Returns:\n      The email address for this token, or None if the required scopes\n      aren't available."
  },
  {
    "code": "def compute_colors_for_labels(self, labels):\n        colors = labels[:, None] * self.palette\n        colors = (colors % 255).numpy().astype(\"uint8\")\n        return colors",
    "docstring": "Simple function that adds fixed colors depending on the class"
  },
  {
    "code": "def _process_batch_write_response(request, response, table_crypto_config):\n    try:\n        unprocessed_items = response[\"UnprocessedItems\"]\n    except KeyError:\n        return response\n    for table_name, unprocessed in unprocessed_items.items():\n        original_items = request[table_name]\n        crypto_config = table_crypto_config[table_name]\n        if crypto_config.encryption_context.partition_key_name:\n            items_match = partial(_item_keys_match, crypto_config)\n        else:\n            items_match = partial(_item_attributes_match, crypto_config)\n        for pos, operation in enumerate(unprocessed):\n            for request_type, item in operation.items():\n                if request_type != \"PutRequest\":\n                    continue\n                for plaintext_item in original_items:\n                    if plaintext_item.get(request_type) and items_match(\n                        plaintext_item[request_type][\"Item\"], item[\"Item\"]\n                    ):\n                        unprocessed[pos] = plaintext_item.copy()\n                        break\n    return response",
    "docstring": "Handle unprocessed items in the response from a transparently encrypted write.\n\n    :param dict request: The DynamoDB plaintext request dictionary\n    :param dict response: The DynamoDB response from the batch operation\n    :param Dict[Text, CryptoConfig] table_crypto_config: table level CryptoConfig used in encrypting the request items\n    :return: DynamoDB response, with any unprocessed items reverted back to the original plaintext values\n    :rtype: dict"
  },
  {
    "code": "def publish_server_heartbeat_succeeded(self, connection_id, duration,\n                                           reply):\n        event = ServerHeartbeatSucceededEvent(duration, reply, connection_id)\n        for subscriber in self.__server_heartbeat_listeners:\n            try:\n                subscriber.succeeded(event)\n            except Exception:\n                _handle_exception()",
    "docstring": "Publish a ServerHeartbeatSucceededEvent to all server heartbeat\n        listeners.\n\n        :Parameters:\n         - `connection_id`: The address (host/port pair) of the connection.\n         - `duration`: The execution time of the event in the highest possible\n            resolution for the platform.\n         - `reply`: The command reply."
  },
  {
    "code": "def put(self, body, priority=DEFAULT_PRIORITY, delay=0, ttr=DEFAULT_TTR):\n        assert isinstance(body, str), 'Job body must be a str instance'\n        jid = self._interact_value('put %d %d %d %d\\r\\n%s\\r\\n' % (\n                                       priority, delay, ttr, len(body), body),\n                                   ['INSERTED'],\n                                   ['JOB_TOO_BIG', 'BURIED', 'DRAINING'])\n        return int(jid)",
    "docstring": "Put a job into the current tube. Returns job id."
  },
  {
    "code": "def _char_density(self, c, font=ImageFont.load_default()):\n        image = Image.new('1', font.getsize(c), color=255)\n        draw = ImageDraw.Draw(image)\n        draw.text((0, 0), c, fill=\"white\", font=font)\n        return collections.Counter(image.getdata())[0]",
    "docstring": "Count the number of black pixels in a rendered character."
  },
  {
    "code": "def _tile_ticks(self, frac, tickvec):\n        origins = np.tile(self.axis._vec, (len(frac), 1))\n        origins = self.axis.pos[0].T + (origins.T*frac).T\n        endpoints = tickvec + origins\n        return origins, endpoints",
    "docstring": "Tiles tick marks along the axis."
  },
  {
    "code": "def _peek_buffer(self, i=0):\n        while len(self._buffer) <= i:\n            self._buffer.append(next(self._source))\n        return self._buffer[i]",
    "docstring": "Get the next line without consuming it."
  },
  {
    "code": "def filing_history(self, num, transaction=None, **kwargs):\n        baseuri = self._BASE_URI + \"company/{}/filing-history\".format(num)\n        if transaction is not None:\n            baseuri += \"/{}\".format(transaction)\n        res = self.session.get(baseuri, params=kwargs)\n        self.handle_http_error(res)\n        return res",
    "docstring": "Search for a company's filling history by company number.\n\n        Args:\n          num (str): Company number to search on.\n\n          transaction (Optional[str]): Filing record number.\n          kwargs (dict): additional keywords passed into\n            requests.session.get params keyword."
  },
  {
    "code": "def validate_reaction(self):\n        if self.reaction not in self._reaction_valid_values:\n            raise ValueError(\"reaction should be one of: {valid}\".format(\n                valid=\", \".join(self._reaction_valid_values)\n            ))",
    "docstring": "Ensure reaction is of a certain type.\n\n        Mainly for future expansion."
  },
  {
    "code": "def collection(name=None):\n    if name is None:\n        collection = Collection.query.get_or_404(1)\n    else:\n        collection = Collection.query.filter(\n            Collection.name == name).first_or_404()\n    return render_template([\n        'invenio_collections/collection_{0}.html'.format(collection.id),\n        'invenio_collections/collection_{0}.html'.format(slugify(name, '_')),\n        current_app.config['COLLECTIONS_DEFAULT_TEMPLATE']\n    ], collection=collection)",
    "docstring": "Render the collection page.\n\n    It renders it either with a collection specific template (aka\n    collection_{collection_name}.html) or with the default collection\n    template (collection.html)."
  },
  {
    "code": "def merge(cls, *others):\n        for other in others:\n            for k, v in other:\n                setattr(cls, k, BoundValue(cls, k, v.value))",
    "docstring": "Merge the `others` schema into this instance.\n\n        The values will all be read from the provider of the original object."
  },
  {
    "code": "def extract_params(params):\n    values = []\n    if isinstance(params, dict):\n        for key, value in params.items():\n            values.extend(extract_params(value))\n    elif isinstance(params, list):\n        for value in params:\n            values.extend(extract_params(value))\n    else:\n        values.append(params)\n    return values",
    "docstring": "Extracts the values of a set of parameters, recursing into nested dictionaries."
  },
  {
    "code": "def _check_list_minions(self, expr, greedy, ignore_missing=False):\n        if isinstance(expr, six.string_types):\n            expr = [m for m in expr.split(',') if m]\n        minions = self._pki_minions()\n        return {'minions': [x for x in expr if x in minions],\n                'missing': [] if ignore_missing else [x for x in expr if x not in minions]}",
    "docstring": "Return the minions found by looking via a list"
  },
  {
    "code": "def create_password_reset(cls, email, valid_for=3600) -> str:\r\n        user = cls.where_email(email)\r\n        if user is None:\r\n            return None\r\n        PasswordResetModel.delete_where_user_id(user.id)\r\n        token = JWT().create_token({\r\n            'code': Security.random_string(5),\n            'user_id': user.id},\r\n            token_valid_for=valid_for)\r\n        code = Security.generate_uuid(1) + \"-\" + Security.random_string(5)\r\n        password_reset_model = PasswordResetModel()\r\n        password_reset_model.token = token\r\n        password_reset_model.code = code\r\n        password_reset_model.user_id = user.id\r\n        password_reset_model.save()\r\n        return code",
    "docstring": "Create a password reset request in the user_password_resets\r\n        database table. Hashed code gets stored in the database.\r\n        Returns unhashed reset code"
  },
  {
    "code": "def VerifyStructure(self, parser_mediator, lines):\n    match_generator = self._VERIFICATION_GRAMMAR.scanString(lines, maxMatches=1)\n    return bool(list(match_generator))",
    "docstring": "Verifies that this is a bash history file.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between\n          parsers and other components, such as storage and dfvfs.\n      lines (str): one or more lines from the text file.\n\n    Returns:\n      bool: True if this is the correct parser, False otherwise."
  },
  {
    "code": "def link_sources(self):\n        \"Returns potential Link or Stream sources.\"\n        if isinstance(self, GenericOverlayPlot):\n            zorders = []\n        elif self.batched:\n            zorders = list(range(self.zorder, self.zorder+len(self.hmap.last)))\n        else:\n            zorders = [self.zorder]\n        if isinstance(self, GenericOverlayPlot) and not self.batched:\n            sources = []\n        elif not self.static or isinstance(self.hmap, DynamicMap):\n            sources = [o for i, inputs in self.stream_sources.items()\n                       for o in inputs if i in zorders]\n        else:\n            sources = [self.hmap.last]\n        return sources",
    "docstring": "Returns potential Link or Stream sources."
  },
  {
    "code": "def visit_Call(self, node: AST, dfltChaining: bool = True) -> str:\n        args = node.args\n        try:\n            kwds = node.keywords\n        except AttributeError:\n            kwds = []\n        self.compact = True\n        args_src = (self.visit(arg) for arg in args)\n        kwds_src = (self.visit(kwd) for kwd in kwds)\n        param_src = ', '.join(chain(args_src, kwds_src))\n        src = f\"{self.visit(node.func)}({param_src})\"\n        self.compact = False\n        return src",
    "docstring": "Return `node`s representation as function call."
  },
  {
    "code": "def abundances(self, ids=None):\n        if ids is None:\n            return self.table()\n        else:\n            res = self.table()\n            return res[res[\"tax_id\"].isin(ids)]",
    "docstring": "Query the results table to get abundance data for all or some tax ids"
  },
  {
    "code": "def add_external_reference_to_entity(self,entity_id, external_ref):\n        if self.entity_layer is not None:\n            self.entity_layer.add_external_reference_to_entity(entity_id,external_ref)",
    "docstring": "Adds an external reference to the given entity identifier in the entity layer\n        @type entity_id: string\n        @param entity_id: the entity identifier\n        @param external_ref: an external reference object\n        @type external_ref: L{CexternalReference}"
  },
  {
    "code": "def binOp(op, indx, amap, bmap, fill_vec):\r\n    def op_or_missing(id):\r\n        va = amap.get(id, None)\r\n        vb = bmap.get(id, None)\r\n        if va is None or vb is None:\r\n            result = fill_vec\r\n        else:\r\n            try:\r\n                result = op(va, vb)\r\n            except Exception:\r\n                result = None\r\n            if result is None:\r\n                result = fill_vec\r\n            return result\r\n    seq_arys = map(op_or_missing, indx)\r\n    data = np.vstack(seq_arys)\r\n    return data",
    "docstring": "Combines the values from two map objects using the indx values\r\n    using the op operator. In situations where there is a missing value\r\n    it will use the callable function handle_missing"
  },
  {
    "code": "def update_allowed(self):\n        return self.update_action.allowed(self.column.table.request,\n                                          self.datum,\n                                          self)",
    "docstring": "Determines whether update of given cell is allowed.\n\n        Calls allowed action of defined UpdateAction of the Column."
  },
  {
    "code": "def get_delete_branch_command(self, branch_name, message, author):\n        tokens = ['hg update --rev=%s && hg commit' % quote(branch_name)]\n        if author:\n            tokens.append('--user=%s' % quote(author.combined))\n        tokens.append('--message=%s' % quote(message))\n        tokens.append('--close-branch')\n        return [' '.join(tokens)]",
    "docstring": "Get the command to delete or close a branch in the local repository."
  },
  {
    "code": "def insert(self, index, value):\n        return super(Collection, self).insert(\n            index, self._ensure_value_is_valid(value))",
    "docstring": "Insert an item at a given position."
  },
  {
    "code": "def cli(obj, ids, query, filters, tags):\n    client = obj['client']\n    if ids:\n        total = len(ids)\n    else:\n        if query:\n            query = [('q', query)]\n        else:\n            query = build_query(filters)\n        total, _, _ = client.get_count(query)\n        ids = [a.id for a in client.get_alerts(query)]\n    with click.progressbar(ids, label='Untagging {} alerts'.format(total)) as bar:\n        for id in bar:\n            client.untag_alert(id, tags)",
    "docstring": "Remove tags from alerts."
  },
  {
    "code": "def clean(self):\n        if self.event not in HOOK_EVENTS.keys():\n            raise ValidationError(\n                \"Invalid hook event {evt}.\".format(evt=self.event)\n            )",
    "docstring": "Validation for events."
  },
  {
    "code": "def download_and_bootstrap(src, name, prereq=None):\n    if prereq:\n        prereq_cmd = '{0} -c \"{1}\"'.format(PY_EXE, prereq)\n        rv = os.system(prereq_cmd)\n        if rv == 0:\n            return\n    ulp = urllib2.urlopen(src)\n    fp = open(name, \"wb\")\n    fp.write(ulp.read())\n    fp.close()\n    cmdline = \"{0} {1}\".format(PY_EXE, name)\n    rv = os.system(cmdline)\n    assert rv == 0",
    "docstring": "Download and install something if 'prerequisite' fails"
  },
  {
    "code": "def run(self, start_command_srv):\n        if start_command_srv:\n            self._command_server.start()\n            self._drop_privs()\n        self._task_runner.start()\n        self._reg_sighandlers()\n        while self.running:\n            time.sleep(self._sleep_period)\n        self.shutdown()",
    "docstring": "Setup daemon process, start child forks, and sleep until\n            events are signalled.\n\n            `start_command_srv`\n                Set to ``True`` if command server should be started."
  },
  {
    "code": "def _update_physical_disk_details(raid_config, server):\n    raid_config['physical_disks'] = []\n    physical_drives = server.get_physical_drives()\n    for physical_drive in physical_drives:\n        physical_drive_dict = physical_drive.get_physical_drive_dict()\n        raid_config['physical_disks'].append(physical_drive_dict)",
    "docstring": "Adds the physical disk details to the RAID configuration passed."
  },
  {
    "code": "def _load(self, scale=1.0):\n        LOG.debug(\"File: %s\", str(self.requested_band_filename))\n        ncf = Dataset(self.requested_band_filename, 'r')\n        wvl = ncf.variables['wavelength'][:] * scale\n        resp = ncf.variables['response'][:]\n        self.rsr = {'wavelength': wvl, 'response': resp}",
    "docstring": "Load the SLSTR relative spectral responses"
  },
  {
    "code": "def signRequest(self,\n                    req: Request,\n                    identifier: Identifier=None) -> Request:\n        idr = self.requiredIdr(idr=identifier or req._identifier)\n        req._identifier = idr\n        req.reqId = req.gen_req_id()\n        req.signature = self.signMsg(msg=req.signingPayloadState(identifier=idr),\n                                     identifier=idr,\n                                     otherIdentifier=req.identifier)\n        return req",
    "docstring": "Signs request. Modifies reqId and signature. May modify identifier.\n\n        :param req: request\n        :param requestIdStore: request id generator\n        :param identifier: signer identifier\n        :return: signed request"
  },
  {
    "code": "def matrixToMathTransform(matrix):\n    if isinstance(matrix, ShallowTransform):\n        return matrix\n    off, scl, rot = MathTransform(matrix).decompose()\n    return ShallowTransform(off, scl, rot)",
    "docstring": "Take a 6-tuple and return a ShallowTransform object."
  },
  {
    "code": "def run_and_print_log(workflow, highlight=None):\n    from noodles.run.threading.sqlite3 import run_parallel\n    from noodles import serial\n    import io\n    import logging\n    log = io.StringIO()\n    log_handler = logging.StreamHandler(log)\n    formatter = logging.Formatter('%(asctime)s - %(message)s')\n    log_handler.setFormatter(formatter)\n    logger = logging.getLogger('noodles')\n    logger.setLevel(logging.INFO)\n    logger.handlers = [log_handler]\n    result = run_parallel(\n        workflow, n_threads=4, registry=serial.base, db_file='tutorial.db',\n        always_cache=True, echo_log=False)\n    display_text(log.getvalue(), highlight or [], split_at=40)\n    return result",
    "docstring": "Run workflow on multi-threaded worker cached with Sqlite3.\n\n    :param workflow: workflow to evaluate.\n    :param highlight: highlight these lines."
  },
  {
    "code": "def process_management_config_section(config, management_config):\n    if 'commands' in management_config:\n        for command in management_config['commands']:\n            config.management['commands'].append(command)",
    "docstring": "Processes the management section from a configuration data dict.\n\n    :param config: The config reference of the object that will hold the\n    configuration data from the config_data.\n    :param management_config: Management section from a config data dict."
  },
  {
    "code": "def tangent(obj, params, **kwargs):\n    normalize = kwargs.get('normalize', True)\n    if isinstance(obj, abstract.Curve):\n        if isinstance(params, (list, tuple)):\n            return ops.tangent_curve_single_list(obj, params, normalize)\n        else:\n            return ops.tangent_curve_single(obj, params, normalize)\n    if isinstance(obj, abstract.Surface):\n        if isinstance(params[0], float):\n            return ops.tangent_surface_single(obj, params, normalize)\n        else:\n            return ops.tangent_surface_single_list(obj, params, normalize)",
    "docstring": "Evaluates the tangent vector of the curves or surfaces at the input parameter values.\n\n    This function is designed to evaluate tangent vectors of the B-Spline and NURBS shapes at single or\n    multiple parameter positions.\n\n    :param obj: input shape\n    :type obj: abstract.Curve or abstract.Surface\n    :param params: parameters\n    :type params: float, list or tuple\n    :return: a list containing \"point\" and \"vector\" pairs\n    :rtype: tuple"
  },
  {
    "code": "def get(self, key):  \n        res = self.connection.get(key)\n        print(res)\n        return res",
    "docstring": "get a set of keys from redis"
  },
  {
    "code": "def to_timezone(dt, tzinfo=None):\n    if not dt:\n        return dt\n    tz = pick_timezone(tzinfo, __timezone__)\n    if not tz:\n        return dt\n    dttz = getattr(dt, 'tzinfo', None)\n    if not dttz:\n        return dt.replace(tzinfo=tz)\n    else:\n        return dt.astimezone(tz)",
    "docstring": "Convert a datetime to timezone"
  },
  {
    "code": "def use(module=None, decode=None, encode=None):\n    global _decode, _encode, _initialized, _using\n    if module is not None:\n        if not isinstance(module, basestring):\n            module = module.__name__\n        if module not in ('cjson', 'json', 'simplejson'):\n            raise ValueError('Unsupported JSON module %s' % module)\n        _using = module\n        _initialized = False\n    else:\n        assert decode is not None and encode is not None\n        _using = 'custom'\n        _decode = decode\n        _encode = encode\n        _initialized = True",
    "docstring": "Set the JSON library that should be used, either by specifying a known\n    module name, or by providing a decode and encode function.\n\n    The modules \"simplejson\", \"cjson\", and \"json\" are currently supported for\n    the ``module`` parameter.\n\n    If provided, the ``decode`` parameter must be a callable that accepts a\n    JSON string and returns a corresponding Python data structure. The\n    ``encode`` callable must accept a Python data structure and return the\n    corresponding JSON string. Exceptions raised by decoding and encoding\n    should be propagated up unaltered.\n\n    @param module: the name of the JSON library module to use, or the module\n                   object itself\n    @type module:  str or module\n    @param decode: a function for decoding JSON strings\n    @type decode:  callable\n    @param encode: a function for encoding objects as JSON strings\n    @type encode:  callable"
  },
  {
    "code": "def _copy_new_parent(self, parent):\n        if self.parent == \"undefined\":\n            param = copy.copy(self)\n            param.parent = parent.uid\n            return param\n        else:\n            raise ValueError(\"Cannot copy from non-dummy parent %s.\" % parent)",
    "docstring": "Copy the current param to a new parent, must be a dummy param."
  },
  {
    "code": "def _format_char(char):\n    if char is None:\n        return -1\n    if isinstance(char, _STRTYPES) and len(char) == 1:\n        return ord(char)\n    try:\n        return int(char)\n    except:\n        raise TypeError('char single character string, integer, or None\\nReceived: ' + repr(char))",
    "docstring": "Prepares a single character for passing to ctypes calls, needs to return\n    an integer but can also pass None which will keep the current character\n    instead of overwriting it.\n\n    This is called often and needs to be optimized whenever possible."
  },
  {
    "code": "def _contigs_dict_to_file(self, contigs, fname):\n        f = pyfastaq.utils.open_file_write(fname)\n        for contig in sorted(contigs, key=lambda x:len(contigs[x]), reverse=True):\n            print(contigs[contig], file=f)\n        pyfastaq.utils.close(f)",
    "docstring": "Writes dictionary of contigs to file"
  },
  {
    "code": "def patch(*args, **kwargs):\n    from caliendo.patch import patch as p\n    return p(*args, **kwargs)",
    "docstring": "Deprecated. Patch should now be imported from caliendo.patch.patch"
  },
  {
    "code": "def transform(self, transform, desc=None):\n        if desc is None:\n            desc = u'transform({})'.format(getattr(transform, '__name__', ''))\n        return self.replace(\n            transforms=self.transforms + [transform],\n            desc_stack=self.desc_stack + [desc]\n        )",
    "docstring": "Create a copy of this query, transformed by `transform`.\n\n        Args:\n            transform (callable): Callable that takes an iterable of values and\n                returns an iterable of transformed values.\n\n        Keyword Args:\n            desc (str): A description of the transform, to use in log messages.\n                Defaults to the name of the `transform` function.\n\n        Returns:\n            Query"
  },
  {
    "code": "def transform(self, X, y=None):\n        insuffix = X._libsuffix\n        cast_fn = utils.get_lib_fn('locallyBlurAntsImage%s' % (insuffix))\n        casted_ptr = cast_fn(X.pointer, self.iters, self.conductance)\n        return iio.ANTsImage(pixeltype=X.pixeltype, dimension=X.dimension,\n                             components=X.components, pointer=casted_ptr)",
    "docstring": "Locally blur an image by applying a gradient anisotropic diffusion filter.\n\n        Arguments\n        ---------\n        X : ANTsImage\n            image to transform\n\n        y : ANTsImage (optional)\n            another image to transform.\n\n        Example\n        -------\n        >>> import ants\n        >>> blur = ants.contrib.LocallyBlurIntensity(1,5)\n        >>> img2d = ants.image_read(ants.get_data('r16'))\n        >>> img2d_b = blur.transform(img2d)\n        >>> ants.plot(img2d)\n        >>> ants.plot(img2d_b)\n        >>> img3d = ants.image_read(ants.get_data('mni'))\n        >>> img3d_b = blur.transform(img3d)\n        >>> ants.plot(img3d)\n        >>> ants.plot(img3d_b)"
  },
  {
    "code": "def has_roles(self, *requirements):\n        user_manager = current_app.user_manager\n        role_names = user_manager.db_manager.get_user_roles(self)\n        for requirement in requirements:\n            if isinstance(requirement, (list, tuple)):\n                tuple_of_role_names = requirement\n                authorized = False\n                for role_name in tuple_of_role_names:\n                    if role_name in role_names:\n                        authorized = True\n                        break\n                if not authorized:\n                    return False\n            else:\n                role_name = requirement\n                if not role_name in role_names:\n                    return False\n        return True",
    "docstring": "Return True if the user has all of the specified roles. Return False otherwise.\n\n            has_roles() accepts a list of requirements:\n                has_role(requirement1, requirement2, requirement3).\n\n            Each requirement is either a role_name, or a tuple_of_role_names.\n                role_name example:   'manager'\n                tuple_of_role_names: ('funny', 'witty', 'hilarious')\n            A role_name-requirement is accepted when the user has this role.\n            A tuple_of_role_names-requirement is accepted when the user has ONE of these roles.\n            has_roles() returns true if ALL of the requirements have been accepted.\n\n            For example:\n                has_roles('a', ('b', 'c'), d)\n            Translates to:\n                User has role 'a' AND (role 'b' OR role 'c') AND role 'd"
  },
  {
    "code": "def value(self):\n        if self.filter_.get('field') is not None:\n            try:\n                result = getattr(self.model, self.filter_['field'])\n            except AttributeError:\n                raise InvalidFilters(\"{} has no attribute {}\".format(self.model.__name__, self.filter_['field']))\n            else:\n                return result\n        else:\n            if 'val' not in self.filter_:\n                raise InvalidFilters(\"Can't find value or field in a filter\")\n            return self.filter_['val']",
    "docstring": "Get the value to filter on\n\n        :return: the value to filter on"
  },
  {
    "code": "def results( self ):\n        return self.report(self.parameters(),\n                           self.metadata(),\n                           self.experimentalResults())",
    "docstring": "Return a complete results dict. Only really makes sense for\n        recently-executed experimental runs.\n\n        :returns: the results dict"
  },
  {
    "code": "def setupMovie(self):\n    if self.state == self.INIT:\n      self.sendRtspRequest(self.SETUP)",
    "docstring": "Setup button handler."
  },
  {
    "code": "def transform_dot(self, node, results):\n        module_dot = results.get(\"bare_with_attr\")\n        member = results.get(\"member\")\n        new_name = None\n        if isinstance(member, list):\n            member = member[0]\n        for change in MAPPING[module_dot.value]:\n            if member.value in change[1]:\n                new_name = change[0]\n                break\n        if new_name:\n            module_dot.replace(Name(new_name,\n                                    prefix=module_dot.prefix))\n        else:\n            self.cannot_convert(node, \"This is an invalid module element\")",
    "docstring": "Transform for calls to module members in code."
  },
  {
    "code": "def release_value_set(self):\n        if self._remotelib:\n            self._remotelib.run_keyword('release_value_set', [self._my_id], {})\n        else:\n            _PabotLib.release_value_set(self, self._my_id)",
    "docstring": "Release a reserved value set so that other executions can use it also."
  },
  {
    "code": "def connect_discussion_signals():\n    post_save.connect(\n        count_discussions_handler, sender=comment_model,\n        dispatch_uid=COMMENT_PS_COUNT_DISCUSSIONS)\n    post_delete.connect(\n        count_discussions_handler, sender=comment_model,\n        dispatch_uid=COMMENT_PD_COUNT_DISCUSSIONS)\n    comment_was_flagged.connect(\n        count_discussions_handler, sender=comment_model,\n        dispatch_uid=COMMENT_WF_COUNT_DISCUSSIONS)\n    comment_was_posted.connect(\n        count_comments_handler, sender=comment_model,\n        dispatch_uid=COMMENT_WP_COUNT_COMMENTS)\n    pingback_was_posted.connect(\n        count_pingbacks_handler, sender=comment_model,\n        dispatch_uid=PINGBACK_WF_COUNT_PINGBACKS)\n    trackback_was_posted.connect(\n        count_trackbacks_handler, sender=comment_model,\n        dispatch_uid=TRACKBACK_WF_COUNT_TRACKBACKS)",
    "docstring": "Connect all the signals on the Comment model to\n    maintains a valid discussion count on each entries\n    when an action is done with the comments."
  },
  {
    "code": "def pop_context(self):\n        processor = getattr(self, 'processor', None)\n        if processor is not None:\n            pop_context = getattr(processor, 'pop_context', None)\n            if pop_context is None:\n                pop_context = getattr(processor, 'pop', None)\n            if pop_context is not None:\n                return pop_context()\n        if self._pop_next:\n            self._pop_next = False",
    "docstring": "Pops the last set of keyword arguments provided to the processor."
  },
  {
    "code": "def add_title(self, title, subtitle=None, source=None):\n        title_entry = self._sourced_dict(\n            source,\n            title=title,\n        )\n        if subtitle is not None:\n            title_entry['subtitle'] = subtitle\n        self._append_to('titles', title_entry)",
    "docstring": "Add title.\n\n        :param title: title for the current document\n        :type title: string\n\n        :param subtitle: subtitle for the current document\n        :type subtitle: string\n\n        :param source: source for the given title\n        :type source: string"
  },
  {
    "code": "def get_cardinality(self, node=None):\n        if node:\n            for factor in self.factors:\n                for variable, cardinality in zip(factor.scope(), factor.cardinality):\n                    if node == variable:\n                        return cardinality\n        else:\n            cardinalities = defaultdict(int)\n            for factor in self.factors:\n                for variable, cardinality in zip(factor.scope(), factor.cardinality):\n                    cardinalities[variable] = cardinality\n            return cardinalities",
    "docstring": "Returns the cardinality of the node\n\n        Parameters\n        ----------\n        node: any hashable python object (optional)\n            The node whose cardinality we want. If node is not specified returns a\n            dictionary with the given variable as keys and their respective cardinality\n            as values.\n\n        Returns\n        -------\n        int or dict : If node is specified returns the cardinality of the node.\n                      If node is not specified returns a dictionary with the given\n                      variable as keys and their respective cardinality as values.\n\n\n        Examples\n        --------\n        >>> from pgmpy.models import ClusterGraph\n        >>> from pgmpy.factors.discrete import DiscreteFactor\n        >>> student = ClusterGraph()\n        >>> factor = DiscreteFactor(['Alice', 'Bob'], cardinality=[2, 2],\n        ...                 values=np.random.rand(4))\n        >>> student.add_node(('Alice', 'Bob'))\n        >>> student.add_factors(factor)\n        >>> student.get_cardinality()\n        defaultdict(<class 'int'>, {'Bob': 2, 'Alice': 2})\n\n        >>> student.get_cardinality(node='Alice')\n        2"
  },
  {
    "code": "def _channel_exists_and_not_settled(\n            self,\n            participant1: Address,\n            participant2: Address,\n            block_identifier: BlockSpecification,\n            channel_identifier: ChannelID = None,\n    ) -> bool:\n        try:\n            channel_state = self._get_channel_state(\n                participant1=participant1,\n                participant2=participant2,\n                block_identifier=block_identifier,\n                channel_identifier=channel_identifier,\n            )\n        except RaidenRecoverableError:\n            return False\n        exists_and_not_settled = (\n            channel_state > ChannelState.NONEXISTENT and\n            channel_state < ChannelState.SETTLED\n        )\n        return exists_and_not_settled",
    "docstring": "Returns if the channel exists and is in a non-settled state"
  },
  {
    "code": "def tableiswritable(tablename):\n    result = True\n    try:\n        t = table(tablename, readonly=False, ack=False)\n        result = t.iswritable()\n    except:\n        result = False\n    return result",
    "docstring": "Test if a table is writable."
  },
  {
    "code": "def save(self, path):\n        writer = csv.writer(open(path, 'w', newline=''), delimiter=' ')\n        rows = list(self.items())\n        rows.sort(key=lambda x: x[0])\n        writer.writerows(rows)",
    "docstring": "Saves this catalogue's data to `path`.\n\n        :param path: file path to save catalogue data to\n        :type path: `str`"
  },
  {
    "code": "def verify_firebase_token(id_token, request, audience=None):\n    return verify_token(\n        id_token, request, audience=audience, certs_url=_GOOGLE_APIS_CERTS_URL)",
    "docstring": "Verifies an ID Token issued by Firebase Authentication.\n\n    Args:\n        id_token (Union[str, bytes]): The encoded token.\n        request (google.auth.transport.Request): The object used to make\n            HTTP requests.\n        audience (str): The audience that this token is intended for. This is\n            typically your Firebase application ID. If None then the audience\n            is not verified.\n\n    Returns:\n        Mapping[str, Any]: The decoded token."
  },
  {
    "code": "def _get_serv(ret=None):\n    _options = _get_options(ret)\n    host = _options.get('host')\n    port = _options.get('port')\n    database = _options.get('db')\n    user = _options.get('user')\n    password = _options.get('password')\n    version = _get_version(host, port, user, password)\n    if version and \"v0.8\" in version:\n        return influxdb.influxdb08.InfluxDBClient(host=host,\n                            port=port,\n                            username=user,\n                            password=password,\n                            database=database\n        )\n    else:\n        return influxdb.InfluxDBClient(host=host,\n                            port=port,\n                            username=user,\n                            password=password,\n                            database=database\n        )",
    "docstring": "Return an influxdb client object"
  },
  {
    "code": "def authentication(self, username, password):\n        _auth_text = '{}:{}'.format(username, password)\n        if int(sys.version[0]) > 2:\n            _auth_bin = base64.encodebytes(_auth_text.encode())\n            _auth = _auth_bin.decode()\n            _auth = _auth.replace('\\n', '')\n            self._auth = _auth\n        else:\n            _auth = base64.encodestring(_auth_text)\n            self._auth = str(_auth).replace('\\n', '')\n        _LOGGER.debug('Autentication string is: {}:***'.format(username))",
    "docstring": "Configures the user authentication for eAPI\n\n        This method configures the username and password combination to use\n        for authenticating to eAPI.\n\n        Args:\n            username (str): The username to use to authenticate the eAPI\n                connection with\n            password (str): The password in clear text to use to authenticate\n                the eAPI connection with"
  },
  {
    "code": "def _cfactory(attr, func, argtypes, restype, errcheck=None):\n        meth = getattr(attr, func)\n        meth.argtypes = argtypes\n        meth.restype = restype\n        if errcheck:\n            meth.errcheck = errcheck",
    "docstring": "Factory to create a ctypes function and automatically manage errors."
  },
  {
    "code": "def unlink(self, key, *keys):\n        return wait_convert(self.execute(b'UNLINK', key, *keys), int)",
    "docstring": "Delete a key asynchronously in another thread."
  },
  {
    "code": "def run(self):\n        salt.utils.process.appendproctitle(self.__class__.__name__)\n        salt.daemons.masterapi.clean_fsbackend(self.opts)\n        for interval in self.buckets:\n            self.update_threads[interval] = threading.Thread(\n                target=self.update_fileserver,\n                args=(interval, self.buckets[interval]),\n            )\n            self.update_threads[interval].start()\n        while True:\n            time.sleep(60)",
    "docstring": "Start the update threads"
  },
  {
    "code": "def day_publications_card(date):\n    d = date.strftime(app_settings.DATE_FORMAT)\n    card_title = 'Reading on {}'.format(d)\n    return {\n            'card_title': card_title,\n            'publication_list': day_publications(date=date),\n            }",
    "docstring": "Displays Publications that were being read on `date`.\n    `date` is a date tobject."
  },
  {
    "code": "def clone(self):\n        clone = copy(self)\n        clone.variables = {k: v.clone() for (k, v) in self.variables.items()}\n        return clone",
    "docstring": "Returns a shallow copy of the current instance, except that all\n        variables are deep-cloned."
  },
  {
    "code": "def single_node_env(args):\n  if isinstance(args, list):\n      sys.argv = args\n  elif args.argv:\n      sys.argv = args.argv\n  num_gpus = args.num_gpus if 'num_gpus' in args else 1\n  util.single_node_env(num_gpus)",
    "docstring": "Sets up environment for a single-node TF session.\n\n  Args:\n    :args: command line arguments as either argparse args or argv list"
  },
  {
    "code": "def get_version():\n    reg = re.compile(r'__version__ = [\\'\"]([^\\'\"]*)[\\'\"]')\n    with open('requests_kerberos/__init__.py') as fd:\n        matches = list(filter(lambda x: x, map(reg.match, fd)))\n    if not matches:\n        raise RuntimeError(\n            'Could not find the version information for requests_kerberos'\n            )\n    return matches[0].group(1)",
    "docstring": "Simple function to extract the current version using regular expressions."
  },
  {
    "code": "def swo_start(self, swo_speed=9600):\n        if self.swo_enabled():\n            self.swo_stop()\n        info = structs.JLinkSWOStartInfo()\n        info.Speed = swo_speed\n        res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.START,\n                                             ctypes.byref(info))\n        if res < 0:\n            raise errors.JLinkException(res)\n        self._swo_enabled = True\n        return None",
    "docstring": "Starts collecting SWO data.\n\n        Note:\n          If SWO is already enabled, it will first stop SWO before enabling it\n          again.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          swo_speed (int): the frequency in Hz used by the target to communicate\n\n        Returns:\n          ``None``\n\n        Raises:\n          JLinkException: on error"
  },
  {
    "code": "def _parse_tag(self, el):\n        ns = None\n        tag = el.tag\n        if tag[0] == '{':\n            ns, tag = tag[1:].split('}', 1)\n            if self.ns_map and ns in self.ns_map:\n                ns = self.ns_map[ns]\n        return ns, tag",
    "docstring": "Extract the namespace and tag from an element."
  },
  {
    "code": "def download(self, file_name, save_as=None):\n        self._check_session()\n        try:\n            if save_as:\n                save_as = os.path.normpath(save_as)\n                save_dir = os.path.dirname(save_as)\n                if save_dir:\n                    if not os.path.exists(save_dir):\n                        os.makedirs(save_dir)\n                    elif not os.path.isdir(save_dir):\n                        raise RuntimeError(save_dir + \" is not a directory\")\n            status, save_path, bytes = self._rest.download_file(\n                'files', file_name, save_as, 'application/octet-stream')\n        except resthttp.RestHttpError as e:\n            raise RuntimeError('failed to download \"%s\": %s' % (file_name, e))\n        return save_path, bytes",
    "docstring": "Download the specified file from the server.\n\n        Arguments:\n        file_name -- Name of file resource to save.\n        save_as   -- Optional path name to write file to.  If not specified,\n                     then file named by the last part of the resource path is\n                     downloaded to current directory.\n\n        Return: (save_path, bytes)\n        save_path -- Path where downloaded file was saved.\n        bytes     -- Bytes downloaded."
  },
  {
    "code": "def _peek(self, chars=1):\n        line = self._socket.recv(chars, socket.MSG_PEEK)\n        logger.debug('Server sent (peek): ' + line.rstrip())\n        return line",
    "docstring": "Peek at the data in the server response.\n\n        Peeking should only be done when the response can be predicted.\n        Make sure that the socket will not block by requesting too\n        much data from it while peeking.\n\n        Args:\n        chars -- the number of characters to peek."
  },
  {
    "code": "def good_port_ranges(ports=None, min_range_len=20, border=3):\n    min_range_len += border*2\n    if ports is None:\n        ports = available_ports()\n    ranges = utils.to_ranges(list(ports))\n    lenghts = sorted([(r[1]-r[0], r) for r in ranges], reverse=True)\n    long_ranges = [l[1] for l in lenghts if l[0] >= min_range_len]\n    without_borders = [(low+border, high-border) for low, high in long_ranges]\n    return without_borders",
    "docstring": "Returns a list of 'good' port ranges.\n    Such ranges are large and don't contain ephemeral or well-known ports.\n    Ranges borders are also excluded."
  },
  {
    "code": "def locate(self, pattern):\n        top_matches = self.top.locate(pattern)\n        bottom_matches = self.bottom.locate(pattern)\n        return [top_matches, bottom_matches]",
    "docstring": "Find sequences matching a pattern. For a circular sequence, the\n        search extends over the origin.\n\n        :param pattern: str or NucleicAcidSequence for which to find matches.\n        :type pattern: str or coral.DNA\n        :returns: A list of top and bottom strand indices of matches.\n        :rtype: list of lists of indices (ints)\n        :raises: ValueError if the pattern is longer than either the input\n                 sequence (for linear DNA) or twice as long as the input\n                 sequence (for circular DNA)."
  },
  {
    "code": "def get_multiple_devices(self, rids):\n        headers = {\n                'User-Agent': self.user_agent(),\n                'Content-Type': self.content_type()\n        }\n        headers.update(self.headers())\n        url = self.portals_url()+'/users/_this/devices/' + str(rids).replace(\"'\", \"\").replace(' ','')\n        r = requests.get(   url,\n                            headers=headers,\n                            auth=self.auth())\n        if HTTP_STATUS.OK == r.status_code:\n            return r.json()\n        else:\n            print(\"get_multiple_devices: Something went wrong: <{0}>: {1}\".format(\n                        r.status_code, r.reason))\n            r.raise_for_status()",
    "docstring": "Implements the 'Get Multiple Devices' API.\n\n            Param rids: a python list object of device rids.\n\n            http://docs.exosite.com/portals/#get-multiple-devices"
  },
  {
    "code": "def _update_record_with_id(self, identifier, rtype, content):\n        record = self._create_request_record(identifier, rtype, None, content,\n                                             self._get_lexicon_option('ttl'),\n                                             self._get_lexicon_option('priority'))\n        self._request_modify_dns_record(record)",
    "docstring": "Updates existing record with no sub-domain name changes"
  },
  {
    "code": "def is1d(a:Collection)->bool:\n    \"Return `True` if `a` is one-dimensional\"\n    return len(a.shape) == 1 if hasattr(a, 'shape') else True",
    "docstring": "Return `True` if `a` is one-dimensional"
  },
  {
    "code": "def get_ips_from_string(ip_str):\n    ip_list = []\n    for ip in ip_str.split(','):\n        clean_ip = ip.strip().lower()\n        if clean_ip:\n            ip_list.append(clean_ip)\n    ip_count = len(ip_list)\n    if ip_count > 0:\n        if is_valid_ip(ip_list[0]) and is_valid_ip(ip_list[-1]):\n            return ip_list, ip_count\n    return [], 0",
    "docstring": "Given a string, it returns a list of one or more valid IP addresses"
  },
  {
    "code": "def content_status(self, content_status):\n        if content_status is None:\n            raise ValueError(\"Invalid value for `content_status`, must not be `None`\")\n        allowed_values = [\"INVALID\", \"NOT_LOADED\", \"HIDDEN\", \"VISIBLE\"]\n        if content_status not in allowed_values:\n            raise ValueError(\n                \"Invalid value for `content_status` ({0}), must be one of {1}\"\n                .format(content_status, allowed_values)\n            )\n        self._content_status = content_status",
    "docstring": "Sets the content_status of this IntegrationStatus.\n\n        Status of integration content, e.g. dashboards  # noqa: E501\n\n        :param content_status: The content_status of this IntegrationStatus.  # noqa: E501\n        :type: str"
  },
  {
    "code": "def sanitize(s, strict=True):\n    allowed = ''.join(\n        [\n            'ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n            'abcdefghijklmnopqrstuvwxyz',\n            '0123456789',\n        ]\n    )\n    if not strict:\n        allowed += '-_.'\n    s = str(s).replace(' ', '_')\n    return ''.join([i for i in s if i in allowed])",
    "docstring": "Sanitize a string.\n\n    Spaces are converted to underscore; if strict=True they are then removed.\n\n    Parameters\n    ----------\n    s : str\n        String to sanitize\n\n    strict : bool\n        If True, only alphanumeric characters are allowed. If False, a limited\n        set of additional characters (-._) will be allowed."
  },
  {
    "code": "def get_tag(self, name):\n        res = self.get_request('/tag/' + name)\n        return Tag(cloud_manager=self, **res['tag'])",
    "docstring": "Return the tag as Tag object."
  },
  {
    "code": "def profile_list(**kwargs):\n    ctx = Context(**kwargs)\n    ctx.execute_action('profile:list', **{\n        'storage': ctx.repo.create_secure_service('storage'),\n    })",
    "docstring": "Show uploaded profiles."
  },
  {
    "code": "def _select_in_voltage_range(self, min_voltage=None, max_voltage=None):\n        min_voltage = min_voltage if min_voltage is not None \\\n            else self.min_voltage\n        max_voltage = max_voltage if max_voltage is not None \\\n            else self.max_voltage\n        return list(filter(lambda p: min_voltage <= p.voltage <= max_voltage,\n                           self.voltage_pairs))",
    "docstring": "Selects VoltagePairs within a certain voltage range.\n\n        Args:\n            min_voltage (float): The minimum allowable voltage for a given\n                step.\n            max_voltage (float): The maximum allowable voltage allowable for a\n                given step.\n\n        Returns:\n            A list of VoltagePair objects"
  },
  {
    "code": "def runSharedFeatures(noiseLevel=None, profile=False):\n  exp = L4L2Experiment(\n    \"shared_features\",\n    enableLateralSP=True,\n    enableFeedForwardSP=True\n  )\n  pairs = createThreeObjects()\n  objects = createObjectMachine(\n    machineType=\"simple\",\n    numInputBits=20,\n    sensorInputSize=1024,\n    externalInputSize=1024\n  )\n  for object in pairs:\n    objects.addObject(object)\n  exp.learnObjects(objects.provideObjectsToLearn())\n  if profile:\n    exp.printProfile()\n  inferConfig = {\n    \"numSteps\": 10,\n    \"noiseLevel\": noiseLevel,\n    \"pairs\": {\n      0: zip(range(10), range(10))\n    }\n  }\n  exp.infer(objects.provideObjectToInfer(inferConfig), objectName=0)\n  if profile:\n    exp.printProfile()\n  exp.plotInferenceStats(\n    fields=[\"L2 Representation\",\n            \"Overlap L2 with object\",\n            \"L4 Representation\"],\n  )",
    "docstring": "Runs a simple experiment where three objects share a number of location,\n  feature pairs.\n\n  Parameters:\n  ----------------------------\n  @param    noiseLevel (float)\n            Noise level to add to the locations and features during inference\n\n  @param    profile (bool)\n            If True, the network will be profiled after learning and inference"
  },
  {
    "code": "def search_user(self, user_name, quiet=False, limit=9):\n        result = self.search(user_name, search_type=1002, limit=limit)\n        if result['result']['userprofileCount'] <= 0:\n            LOG.warning('User %s not existed!', user_name)\n            raise SearchNotFound('user {} not existed'.format(user_name))\n        else:\n            users = result['result']['userprofiles']\n            if quiet:\n                user_id, user_name = users[0]['userId'], users[0]['nickname']\n                user = User(user_id, user_name)\n                return user\n            else:\n                return self.display.select_one_user(users)",
    "docstring": "Search user by user name.\n\n        :params user_name: user name.\n        :params quiet: automatically select the best one.\n        :params limit: user count returned by weapi.\n        :return: a User object."
  },
  {
    "code": "def controlled(self, control_qubit):\n        control_qubit = unpack_qubit(control_qubit)\n        self.modifiers.insert(0, \"CONTROLLED\")\n        self.qubits.insert(0, control_qubit)\n        return self",
    "docstring": "Add the CONTROLLED modifier to the gate with the given control qubit."
  },
  {
    "code": "def get_group_usage_link(self):\n        first_element = self.group_list[0]\n        usage_link = getattr(first_element.form, 'usage_link', None)\n        return usage_link",
    "docstring": "Get the usage link for the group element."
  },
  {
    "code": "def rename(self, src_basename, dest_basename, datadir=\"outdir\"):\n        directory = {\n            \"indir\": self.indir,\n            \"outdir\": self.outdir,\n            \"tmpdir\": self.tmpdir,\n        }[datadir]\n        src = directory.path_in(src_basename)\n        dest = directory.path_in(dest_basename)\n        os.rename(src, dest)",
    "docstring": "Rename a file located in datadir.\n\n        src_basename and dest_basename are the basename of the source file\n        and of the destination file, respectively."
  },
  {
    "code": "def parse_number(self):\n        value = self.current_token.value\n        suffix = value[-1].lower()\n        try:\n            if suffix in NUMBER_SUFFIXES:\n                return NUMBER_SUFFIXES[suffix](value[:-1])\n            return Double(value) if '.' in value else Int(value)\n        except (OutOfRange, ValueError):\n            return String(value)",
    "docstring": "Parse a number from the token stream."
  },
  {
    "code": "def recalculate(self, amount, billing_info):\n        order = Order(pk=-1)\n        order.amount = amount\n        order.currency = self.get_currency()\n        country = getattr(billing_info, 'country', None)\n        if not country is None:\n            country = country.code\n        tax_number = getattr(billing_info, 'tax_number', None)\n        tax_session_key = \"tax_%s_%s\" % (tax_number, country)\n        tax = self.request.session.get(tax_session_key)\n        if tax is None:\n            taxation_policy = getattr(settings, 'PLANS_TAXATION_POLICY', None)\n            if not taxation_policy:\n                raise ImproperlyConfigured('PLANS_TAXATION_POLICY is not set')\n            taxation_policy = import_name(taxation_policy)\n            tax = str(taxation_policy.get_tax_rate(tax_number, country))\n            self.request.session[tax_session_key] = tax\n        order.tax = Decimal(tax) if tax != 'None' else None\n        return order",
    "docstring": "Calculates and return pre-filled Order"
  },
  {
    "code": "def remove_entry(data, entry):\n    file_field = entry['fields'].get('file')\n    if file_field:\n        try:\n            os.remove(file_field)\n        except IOError:\n            click.echo('This entry\\'s file was missing')\n    data.remove(entry)",
    "docstring": "Remove an entry in place."
  },
  {
    "code": "def cast2theano_var(self, array_like, name=None):\n        array = np.asarray(array_like)\n        args = (name, array.dtype)\n        ndim = array.ndim\n        if ndim == 0:\n            return T.scalar(*args)\n        elif ndim == 1:\n            return T.vector(*args)\n        elif ndim == 2:\n            return T.matrix(*args)\n        elif ndim == 3:\n            return T.tensor3(*args)\n        elif ndim == 4:\n            return T.tensor4(*args)\n        else:\n            raise ValueError('extheano.jit.Compiler: Unsupported type or shape')",
    "docstring": "Cast `numpy.ndarray` into `theano.tensor` keeping `dtype` and `ndim`\n        compatible"
  },
  {
    "code": "def copy(self, extra=None):\n        if extra is None:\n            extra = dict()\n        newTVS = Params.copy(self, extra)\n        if self.isSet(self.estimator):\n            newTVS.setEstimator(self.getEstimator().copy(extra))\n        if self.isSet(self.evaluator):\n            newTVS.setEvaluator(self.getEvaluator().copy(extra))\n        return newTVS",
    "docstring": "Creates a copy of this instance with a randomly generated uid\n        and some extra params. This copies creates a deep copy of\n        the embedded paramMap, and copies the embedded and extra parameters over.\n\n        :param extra: Extra parameters to copy to the new instance\n        :return: Copy of this instance"
  },
  {
    "code": "def estimate(phenotype, G=None, K=None, covariates=None, overdispersion=True):\n    logger = logging.getLogger(__name__)\n    logger.info('Heritability estimation has started.')\n    G, K = _background_standardize(G, K)\n    if G is None and K is None:\n        raise Exception('G and K cannot be all None.')\n    Q0, Q1, S0 = _background_decomposition(G, K)\n    if covariates is None:\n        logger.debug('Inserting offset covariate.')\n        covariates = ones((phenotype.sample_size, 1))\n    logger.debug('Constructing EP.')\n    from limix_inference.glmm import ExpFamEP\n    ep = ExpFamEP(phenotype.to_likelihood(), covariates, Q0, Q1, S0,\n                  overdispersion)\n    logger.debug('EP optimization.')\n    ep.learn()\n    h2 = ep.heritability\n    logger.info('Found heritability before correction: %.5f.', h2)\n    return h2",
    "docstring": "Estimate the so-called narrow-sense heritability.\n\n    It supports Bernoulli and Binomial phenotypes (see `outcome_type`).\n    The user must specifiy only one of the parameters G, K, and QS for\n    defining the genetic background.\n\n    Let :math:`N` be the sample size, :math:`S` the number of covariates, and\n    :math:`P_b` the number of genetic markers used for Kinship estimation.\n\n    :param numpy.ndarray y: Phenotype. The domain has be the non-negative\n                          integers. Dimension (:math:`N\\\\times 0`).\n    :param numpy.ndarray G: Genetic markers matrix used internally for kinship\n                    estimation. Dimension (:math:`N\\\\times P_b`).\n    :param numpy.ndarray K: Kinship matrix. Dimension (:math:`N\\\\times N`).\n    :param tuple QS: Economic eigen decomposition of the Kinship matrix.\n    :param numpy.ndarray covariate: Covariates. Default is an offset.\n                                  Dimension (:math:`N\\\\times S`).\n    :param object oucome_type: Either :class:`limix_qep.Bernoulli` (default)\n                               or a :class:`limix_qep.Binomial` instance.\n    :param float prevalence: Population rate of cases for dichotomous\n                             phenotypes. Typically useful for case-control\n                             studies.\n    :return: a tuple containing the estimated heritability and additional\n             information, respectively."
  },
  {
    "code": "def checkout_deploy_branch(deploy_branch, canpush=True):\n    create_deploy_branch(deploy_branch, push=canpush)\n    remote_branch = \"doctr_remote/{}\".format(deploy_branch)\n    print(\"Checking out doctr working branch tracking\", remote_branch)\n    clear_working_branch()\n    if run(['git', 'rev-parse', '--verify', remote_branch], exit=False) == 0:\n        extra_args = ['--track', remote_branch]\n    else:\n        extra_args = []\n    run(['git', 'checkout', '-b', DOCTR_WORKING_BRANCH] + extra_args)\n    print(\"Done\")\n    return canpush",
    "docstring": "Checkout the deploy branch, creating it if it doesn't exist."
  },
  {
    "code": "def get_hour_dirs(root=None):\n    root = root or selfplay_dir()\n    return list(filter(lambda s: re.match(r\"\\d{4}-\\d{2}-\\d{2}-\\d{2}\", s),\n                       gfile.ListDirectory(root)))",
    "docstring": "Gets the directories under selfplay_dir that match YYYY-MM-DD-HH."
  },
  {
    "code": "def _find(self, id_):\n        cur = self._connection.cursor()\n        cur.execute(\n            'SELECT fileNumber, offset FROM sequences WHERE id = ?', (id_,))\n        row = cur.fetchone()\n        if row is None:\n            return None\n        else:\n            return self._getFilename(row[0]), row[1]",
    "docstring": "Find the filename and offset of a sequence, given its id.\n\n        @param id_: A C{str} sequence id.\n        @return: A 2-tuple, containing the C{str} file name and C{int} offset\n            within that file of the sequence."
  },
  {
    "code": "def cast_scalar_to_array(shape, value, dtype=None):\n    if dtype is None:\n        dtype, fill_value = infer_dtype_from_scalar(value)\n    else:\n        fill_value = value\n    values = np.empty(shape, dtype=dtype)\n    values.fill(fill_value)\n    return values",
    "docstring": "create np.ndarray of specified shape and dtype, filled with values\n\n    Parameters\n    ----------\n    shape : tuple\n    value : scalar value\n    dtype : np.dtype, optional\n        dtype to coerce\n\n    Returns\n    -------\n    ndarray of shape, filled with value, of specified / inferred dtype"
  },
  {
    "code": "def get_dict_from_response(response):\n    if getattr(response, '_resp') and response._resp.code > 400:\n        raise OAuthResponseError(\n                'Application mis-configuration in Globus', None, response\n            )\n    return response.data",
    "docstring": "Check for errors in the response and return the resulting JSON."
  },
  {
    "code": "def request_finished(key):\n    with event_lock:\n        threads[key] = threads[key][1:]\n        if threads[key]:\n            threads[key][0].run()",
    "docstring": "Remove finished Thread from queue.\n\n    :param key: data source key"
  },
  {
    "code": "def _safemembers(members):\n    base = _resolved(\".\")\n    for finfo in members:\n        if _badpath(finfo.name, base):\n            print(finfo.name, \"is blocked (illegal path)\")\n        elif finfo.issym() and _badlink(finfo, base):\n            print(finfo.name, \"is blocked: Hard link to\", finfo.linkname)\n        elif finfo.islnk() and _badlink(finfo, base):\n            print(finfo.name, \"is blocked: Symlink to\", finfo.linkname)\n        else:\n            yield finfo",
    "docstring": "Check members of a tar archive for safety.\n    Ensure that they do not contain paths or links outside of where we\n    need them - this would only happen if the archive wasn't made by\n    eqcorrscan.\n\n    :type members: :class:`tarfile.TarFile`\n    :param members: an open tarfile."
  },
  {
    "code": "def get_pdos(dos, lm_orbitals=None, atoms=None, elements=None):\n    if not elements:\n        symbols = dos.structure.symbol_set\n        elements = dict(zip(symbols, [None] * len(symbols)))\n    pdos = {}\n    for el in elements:\n        if atoms and el not in atoms:\n            continue\n        element_sites = [site for site in dos.structure.sites\n                         if site.specie == get_el_sp(el)]\n        sites = [site for i, site in enumerate(element_sites)\n                 if not atoms or (el in atoms and i in atoms[el])]\n        lm = lm_orbitals[el] if (lm_orbitals and el in lm_orbitals) else None\n        orbitals = elements[el] if elements and el in elements else None\n        pdos[el] = get_element_pdos(dos, el, sites, lm, orbitals)\n    return pdos",
    "docstring": "Extract the projected density of states from a CompleteDos object.\n\n    Args:\n        dos (:obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The\n            density of states.\n        elements (:obj:`dict`, optional): The elements and orbitals to extract\n            from the projected density of states. Should be provided as a\n            :obj:`dict` with the keys as the element names and corresponding\n            values as a :obj:`tuple` of orbitals. For example, the following\n            would extract the Bi s, px, py and d orbitals::\n\n                {'Bi': ('s', 'px', 'py', 'd')}\n\n            If an element is included with an empty :obj:`tuple`, all orbitals\n            for that species will be extracted. If ``elements`` is not set or\n            set to ``None``, all elements for all species will be extracted.\n        lm_orbitals (:obj:`dict`, optional): The orbitals to decompose into\n            their lm contributions (e.g. p -> px, py, pz). Should be provided\n            as a :obj:`dict`, with the elements names as keys and a\n            :obj:`tuple` of orbitals as the corresponding values. For example,\n            the following would be used to decompose the oxygen p and d\n            orbitals::\n\n                {'O': ('p', 'd')}\n\n        atoms (:obj:`dict`, optional): Which atomic sites to use when\n            calculating the projected density of states. Should be provided as\n            a :obj:`dict`, with the element names as keys and a :obj:`tuple` of\n            :obj:`int` specifying the atomic indices as the corresponding\n            values. The elemental projected density of states will be summed\n            only over the atom indices specified. If an element is included\n            with an empty :obj:`tuple`, then all sites for that element will\n            be included. The indices are 0 based for each element specified in\n            the POSCAR. For example, the following will calculate the density\n            of states for the first 4 Sn atoms and all O atoms in the\n            structure::\n\n                {'Sn': (1, 2, 3, 4), 'O': (, )}\n\n            If ``atoms`` is not set or set to ``None`` then all atomic sites\n            for all elements will be considered.\n\n    Returns:\n        dict: The projected density of states. Formatted as a :obj:`dict` of\n        :obj:`dict` mapping the elements and their orbitals to\n        :obj:`~pymatgen.electronic_structure.dos.Dos` objects. For example::\n\n            {\n                'Bi': {'s': Dos, 'p': Dos ... },\n                'S': {'s': Dos}\n            }"
  },
  {
    "code": "def _convert_dict_inputs(inputs, tensor_info_map):\n  dict_inputs = _prepare_dict_inputs(inputs, tensor_info_map)\n  return tensor_info.convert_dict_to_compatible_tensor(dict_inputs,\n                                                       tensor_info_map)",
    "docstring": "Converts from inputs into dict of input tensors.\n\n  This handles:\n    - putting inputs into a dict, per _prepare_dict_inputs(),\n    - converting all input values into tensors compatible with the\n      expected input tensor (dtype, shape).\n    - check sparse/non-sparse tensor types.\n\n  Args:\n    inputs: inputs fed to Module.__call__().\n    tensor_info_map: A map from string to `tensor_info.ParsedTensorInfo`\n      describing the signature inputs.\n\n  Returns:\n    A dict of tensors to feed to the signature instantiation.\n\n  Raises:\n    TypeError: If it fails to convert the input values into a dict of tensors\n      to feed to the signature instantiation."
  },
  {
    "code": "def run_type(self):\n        METAGGA_TYPES = {\"TPSS\", \"RTPSS\", \"M06L\", \"MBJL\", \"SCAN\", \"MS0\", \"MS1\", \"MS2\"}\n        if self.parameters.get(\"LHFCALC\", False):\n            rt = \"HF\"\n        elif self.parameters.get(\"METAGGA\", \"\").strip().upper() in METAGGA_TYPES:\n            rt = self.parameters[\"METAGGA\"].strip().upper()\n        elif self.parameters.get(\"LUSE_VDW\", False):\n            vdw_gga = {\"RE\": \"DF\", \"OR\": \"optPBE\", \"BO\": \"optB88\",\n                       \"MK\": \"optB86b\", \"ML\": \"DF2\"}\n            gga = self.parameters.get(\"GGA\").upper()\n            rt = \"vdW-\" + vdw_gga[gga]\n        elif self.potcar_symbols[0].split()[0] == 'PAW':\n            rt = \"LDA\"\n        else:\n            rt = \"GGA\"\n        if self.is_hubbard:\n            rt += \"+U\"\n        return rt",
    "docstring": "Returns the run type. Currently supports LDA, GGA, vdW-DF and HF calcs.\n\n        TODO: Fix for other functional types like PW91, other vdW types, etc."
  },
  {
    "code": "def _process_input_wcs_single(fname, wcskey, updatewcs):\n    if wcskey in ['', ' ', 'INDEF', None]:\n        if updatewcs:\n            uw.updatewcs(fname, checkfiles=False)\n    else:\n        numext = fileutil.countExtn(fname)\n        extlist = []\n        for extn in range(1, numext + 1):\n            extlist.append(('SCI', extn))\n        if wcskey in string.ascii_uppercase:\n            wkey = wcskey\n            wname = ' '\n        else:\n            wname = wcskey\n            wkey = ' '\n        altwcs.restoreWCS(fname, extlist, wcskey=wkey, wcsname=wname)\n    if wcskey not in ['', ' ', 'INDEF', None] or updatewcs:\n        wcscorr.init_wcscorr(fname)",
    "docstring": "See docs for _process_input_wcs.\n    This is separated to be spawned in parallel."
  },
  {
    "code": "def run_once(function, state={}, errors={}):\n    @six.wraps(function)\n    def _wrapper(*args, **kwargs):\n        if function in errors:\n            six.reraise(*errors[function])\n        try:\n            return state[function]\n        except KeyError:\n            try:\n                state[function] = result = function(*args, **kwargs)\n                return result\n            except Exception:\n                errors[function] = sys.exc_info()\n                raise\n    return _wrapper",
    "docstring": "A memoization decorator, whose purpose is to cache calls."
  },
  {
    "code": "def preview(self):\n        if self._preview is None:\n            from twilio.rest.preview import Preview\n            self._preview = Preview(self)\n        return self._preview",
    "docstring": "Access the Preview Twilio Domain\n\n        :returns: Preview Twilio Domain\n        :rtype: twilio.rest.preview.Preview"
  },
  {
    "code": "def _create_local_agent_channel(self, io_loop):\n        logger.info('Initializing Jaeger Tracer with UDP reporter')\n        return LocalAgentSender(\n            host=self.local_agent_reporting_host,\n            sampling_port=self.local_agent_sampling_port,\n            reporting_port=self.local_agent_reporting_port,\n            throttling_port=self.throttler_port,\n            io_loop=io_loop\n        )",
    "docstring": "Create an out-of-process channel communicating to local jaeger-agent.\n        Spans are submitted as SOCK_DGRAM Thrift, sampling strategy is polled\n        via JSON HTTP.\n\n        :param self: instance of Config"
  },
  {
    "code": "def _time_request(self, uri, method, **kwargs):\n        start_time = time.time()\n        resp, body = self.request(uri, method, **kwargs)\n        self.times.append((\"%s %s\" % (method, uri),\n                start_time, time.time()))\n        return resp, body",
    "docstring": "Wraps the request call and records the elapsed time."
  },
  {
    "code": "def get_lon_variable(nc):\n    if 'longitude' in nc.variables:\n        return 'longitude'\n    longitudes = nc.get_variables_by_attributes(standard_name=\"longitude\")\n    if longitudes:\n        return longitudes[0].name\n    return None",
    "docstring": "Returns the variable for longitude\n\n    :param netCDF4.Dataset nc: netCDF dataset"
  },
  {
    "code": "def delete(self, uri, default_response=None):\n        url = self.api_url + uri\n        response = requests.delete(\n            url, headers=self.headers, verify=self.verify_ssl,\n            auth=self.auth, timeout=self.timeout)\n        return self.success_or_raise(response, default_response=default_response)",
    "docstring": "Call DELETE on the Gitlab server\n\n        >>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False)\n        >>> gitlab.login(user='root', password='5iveL!fe')\n        >>> gitlab.delete('/users/5')\n\n        :param uri: String with the URI you wish to delete\n        :param default_response: Return value if JSONDecodeError\n        :return: Dictionary containing response data\n        :raise: HttpError: If invalid response returned"
  },
  {
    "code": "def authorized(remote_app=None):\n    if remote_app not in current_oauthclient.handlers:\n        return abort(404)\n    state_token = request.args.get('state')\n    try:\n        assert state_token\n        state = serializer.loads(state_token)\n        assert state['sid'] == _create_identifier()\n        assert state['app'] == remote_app\n        set_session_next_url(remote_app, state['next'])\n    except (AssertionError, BadData):\n        if current_app.config.get('OAUTHCLIENT_STATE_ENABLED', True) or (\n           not(current_app.debug or current_app.testing)):\n            abort(403)\n    try:\n        handler = current_oauthclient.handlers[remote_app]()\n    except OAuthException as e:\n        if e.type == 'invalid_response':\n            abort(500)\n        else:\n            raise\n    return handler",
    "docstring": "Authorized handler callback."
  },
  {
    "code": "def process_associations(self, limit):\n        myfile = '/'.join((self.rawdir, self.files['data']['file']))\n        f = gzip.open(myfile, 'rb')\n        filereader = io.TextIOWrapper(f, newline=\"\")\n        filereader.readline()\n        for event, elem in ET.iterparse(filereader):\n            self.process_xml_table(\n                elem, 'Article_Breed', self._process_article_breed_row, limit)\n            self.process_xml_table(\n                elem, 'Article_Phene', self._process_article_phene_row, limit)\n            self.process_xml_table(\n                elem, 'Breed_Phene', self._process_breed_phene_row, limit)\n            self.process_xml_table(\n                elem, 'Lida_Links', self._process_lida_links_row, limit)\n            self.process_xml_table(\n                elem, 'Phene_Gene', self._process_phene_gene_row, limit)\n            self.process_xml_table(\n                elem, 'Group_MPO', self._process_group_mpo_row, limit)\n        f.close()\n        return",
    "docstring": "Loop through the xml file and process the article-breed, article-phene,\n        breed-phene, phene-gene associations, and the external links to LIDA.\n\n        :param limit:\n        :return:"
  },
  {
    "code": "def upgrade(self, package, force=False):\n        self.install(package, upgrade=True, force=force)",
    "docstring": "Shortcut method to upgrade a package. If `force` is set to True,\n        the package and all of its dependencies will be reinstalled, otherwise\n        if the package is up to date, this command is a no-op."
  },
  {
    "code": "def offset(self, offset):\n        span = self\n        if offset > 0:\n            for i in iter_range(offset):\n                span = span.next_period()\n        elif offset < 0:\n            for i in iter_range(-offset):\n                span = span.prev_period()\n        return span",
    "docstring": "Offset the date range by the given amount of periods.\n\n        This differs from :meth:`~spans.types.OffsetableRangeMixin.offset` on\n        :class:`spans.types.daterange` by not accepting a ``timedelta`` object.\n        Instead it expects an integer to adjust the typed date range by. The\n        given value may be negative as well.\n\n        :param offset: Number of periods to offset this range by. A period is\n                       either a day, week, american week, month, quarter or\n                       year, depending on this range's period type.\n        :return: New offset :class:`~spans.types.PeriodRange`"
  },
  {
    "code": "def state_size(self) -> Sequence[Shape]:\n        return self._sizes(self._compiler.rddl.state_size)",
    "docstring": "Returns the MDP state size."
  },
  {
    "code": "def fill_n(self, values, weights=None, dropna: bool = True):\n        values = np.asarray(values)\n        if dropna:\n            values = values[~np.isnan(values)]\n        if self._binning.is_adaptive():\n            map = self._binning.force_bin_existence(values)\n            self._reshape_data(self._binning.bin_count, map)\n        if weights:\n            weights = np.asarray(weights)\n            self._coerce_dtype(weights.dtype)\n        (frequencies, errors2, underflow, overflow, stats) = \\\n            calculate_frequencies(values, self._binning, dtype=self.dtype,\n                                  weights=weights, validate_bins=False)\n        self._frequencies += frequencies\n        self._errors2 += errors2\n        if self.keep_missed:\n            self.underflow += underflow\n            self.overflow += overflow\n        if self._stats:\n            for key in self._stats:\n                self._stats[key] += stats.get(key, 0.0)",
    "docstring": "Update histograms with a set of values.\n\n        Parameters\n        ----------\n        values: array_like\n        weights: Optional[array_like]\n        drop_na: Optional[bool]\n            If true (default), all nan's are skipped."
  },
  {
    "code": "def get_queue_acl(self, queue_name, timeout=None):\n        _validate_not_none('queue_name', queue_name)\n        request = HTTPRequest()\n        request.method = 'GET'\n        request.host = self._get_host()\n        request.path = _get_path(queue_name)\n        request.query = [\n            ('comp', 'acl'),\n            ('timeout', _int_to_str(timeout)),\n        ]\n        response = self._perform_request(request)\n        return _convert_xml_to_signed_identifiers(response.body)",
    "docstring": "Returns details about any stored access policies specified on the\n        queue that may be used with Shared Access Signatures.\n\n        :param str queue_name:\n            The name of an existing queue.\n        :param int timeout:\n            The server timeout, expressed in seconds.\n        :return: A dictionary of access policies associated with the queue.\n        :rtype: dict of str to :class:`~azure.storage.models.AccessPolicy`"
  },
  {
    "code": "def wait_until_element_has_focus(self, locator, timeout=None):\n\t\tself._info(\"Waiting for focus on '%s'\" % (locator))\n\t\tself._wait_until_no_error(timeout, self._check_element_focus_exp, True, locator, timeout)",
    "docstring": "Waits until the element identified by `locator` has focus.\n\t\tYou might rather want to use `Element Focus Should Be Set`\n\n\t\t| *Argument* | *Description* | *Example* |\n\t\t| locator | Selenium 2 element locator | id=my_id |\n\t\t| timeout | maximum time to wait before the function throws an element not found error (default=None) | 5s |"
  },
  {
    "code": "def distinct(iterable, keyfunc=None):\n    seen = set()\n    for item in iterable:\n        key = item if keyfunc is None else keyfunc(item)\n        if key not in seen:\n            seen.add(key)\n            yield item",
    "docstring": "Yields distinct items from `iterable` in the order that they appear."
  },
  {
    "code": "def get_resources(self):\n        json_resources = self.rest_client.make_request(self.resource_url)['resources']\n        return [RestResource(resource, self.rest_client) for resource in json_resources]",
    "docstring": "Retrieves a list of all known Streams high-level REST resources.\n\n        Returns:\n            :py:obj:`list` of :py:class:`~.rest_primitives.RestResource`: List of all Streams high-level REST resources."
  },
  {
    "code": "def to_pascal_case(s):\n    return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())",
    "docstring": "Transform underscore separated string to pascal case"
  },
  {
    "code": "def argset(name, *args, **kwargs):\n    def _arg(f):\n        if not hasattr(f, '_subcommand_argsets'):\n            f._subcommand_argsets = {}\n        f._subcommand_argsets.setdefault(name, []).append((args, kwargs))\n        return f\n    return _arg",
    "docstring": "Decorator to add sets of required mutually exclusive args to subcommands."
  },
  {
    "code": "def read_features_and_groups(features_path, groups_path):\n    \"Reader for data and groups\"\n    try:\n        if not pexists(features_path):\n            raise ValueError('non-existent features file')\n        if not pexists(groups_path):\n            raise ValueError('non-existent groups file')\n        if isinstance(features_path, str):\n            features = np.genfromtxt(features_path, dtype=float)\n        else:\n            raise ValueError('features input must be a file path ')\n        if isinstance(groups_path, str):\n            groups = np.genfromtxt(groups_path, dtype=str)\n        else:\n            raise ValueError('groups input must be a file path ')\n    except:\n        raise IOError('error reading the specified features and/or groups.')\n    if len(features) != len(groups):\n        raise ValueError(\"lengths of features and groups do not match!\")\n    return features, groups",
    "docstring": "Reader for data and groups"
  },
  {
    "code": "def get_method_name(method):\n    name = get_object_name(method)\n    if name.startswith(\"__\") and not name.endswith(\"__\"):\n        name = \"_{0}{1}\".format(get_object_name(method.im_class), name)\n    return name",
    "docstring": "Returns given method name.\n\n    :param method: Method to retrieve the name.\n    :type method: object\n    :return: Method name.\n    :rtype: unicode"
  },
  {
    "code": "def setup(addr, user, remote_path, local_key=None):\n    port = find_port(addr, user)\n    if not port or not is_alive(addr, user):\n        port = new_port()\n        scp(addr, user, __file__, '~/unixpipe', local_key)\n        ssh_call = ['ssh', '-fL%d:127.0.0.1:12042' % port,\n                    '-o', 'ExitOnForwardFailure=yes',\n                    '-o', 'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d' % port,\n                    '-o', 'ControlMaster=auto',\n                    '%s@%s' % (user, addr,), 'python', '~/unixpipe',\n                    'server', remote_path]\n        if local_key:\n            ssh_call.insert(1, local_key)\n            ssh_call.insert(1, '-i')\n        subprocess.call(ssh_call)\n        time.sleep(1)\n    return port",
    "docstring": "Setup the tunnel"
  },
  {
    "code": "def stamp_allowing_unusual_version_table(\n        config: Config,\n        revision: str,\n        sql: bool = False,\n        tag: str = None,\n        version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> None:\n    script = ScriptDirectory.from_config(config)\n    starting_rev = None\n    if \":\" in revision:\n        if not sql:\n            raise CommandError(\"Range revision not allowed\")\n        starting_rev, revision = revision.split(':', 2)\n    def do_stamp(rev: str, context):\n        return script._stamp_revs(revision, rev)\n    with EnvironmentContext(config,\n                            script,\n                            fn=do_stamp,\n                            as_sql=sql,\n                            destination_rev=revision,\n                            starting_rev=starting_rev,\n                            tag=tag,\n                            version_table=version_table):\n        script.run_env()",
    "docstring": "Stamps the Alembic version table with the given revision; don't run any\n    migrations.\n\n    This function is a clone of ``alembic.command.stamp()``, but allowing\n    ``version_table`` to change. See\n    http://alembic.zzzcomputing.com/en/latest/api/commands.html#alembic.command.stamp"
  },
  {
    "code": "def from_file(cls, path, format='infer'):\n        format = _infer_format(path, format=format)\n        origin = os.path.abspath(os.path.dirname(path))\n        with open(path) as f:\n            data = f.read()\n        if format == 'json':\n            obj = json.loads(data)\n        else:\n            obj = yaml.safe_load(data)\n        return cls.from_dict(obj, _origin=origin)",
    "docstring": "Create an instance from a json or yaml file.\n\n        Parameters\n        ----------\n        path : str\n            The path to the file to load.\n        format : {'infer', 'json', 'yaml'}, optional\n            The file format. By default the format is inferred from the file\n            extension."
  },
  {
    "code": "def _register_bounds_validator_if_needed(parser, name, flag_values):\n  if parser.lower_bound is not None or parser.upper_bound is not None:\n    def checker(value):\n      if value is not None and parser.is_outside_bounds(value):\n        message = '%s is not %s' % (value, parser.syntactic_help)\n        raise _exceptions.ValidationError(message)\n      return True\n    _validators.register_validator(name, checker, flag_values=flag_values)",
    "docstring": "Enforces lower and upper bounds for numeric flags.\n\n  Args:\n    parser: NumericParser (either FloatParser or IntegerParser), provides lower\n        and upper bounds, and help text to display.\n    name: str, name of the flag\n    flag_values: FlagValues."
  },
  {
    "code": "def _set_int(self, commands, name):\n        if name in commands:\n            try:\n                value = int(commands[name])\n                setattr(self, name, value)\n            except ValueError:\n                pass",
    "docstring": "set integer value from commands"
  },
  {
    "code": "def list_source_code(self, context: int = 5) -> None:\n        self._verify_entrypoint_selected()\n        current_trace_frame = self.trace_tuples[\n            self.current_trace_frame_index\n        ].trace_frame\n        filename = os.path.join(self.repository_directory, current_trace_frame.filename)\n        file_lines: List[str] = []\n        try:\n            with open(filename, \"r\") as file:\n                file_lines = file.readlines()\n        except FileNotFoundError:\n            self.warning(f\"Couldn't open {filename}.\")\n            return\n        self._output_file_lines(current_trace_frame, file_lines, context)",
    "docstring": "Show source code around the current trace frame location.\n\n        Parameters:\n            context: int    number of lines to show above and below trace location\n                            (default: 5)"
  },
  {
    "code": "def complete_server(self, text, line, begidx, endidx):\n        return  [i for i in PsiturkShell.server_commands if i.startswith(text)]",
    "docstring": "Tab-complete server command"
  },
  {
    "code": "def contexts(self):\n        if not hasattr(self, \"_contexts\"):\n            cs = {}\n            for cr in self.doc[\"contexts\"]:\n                cs[cr[\"name\"]] = copy.deepcopy(cr[\"context\"])\n            self._contexts = cs\n        return self._contexts",
    "docstring": "Returns known contexts by exposing as a read-only property."
  },
  {
    "code": "def valid_hash_value(hashname):\n    custom_hash_prefix_re = re.compile(r\"^x_\")\n    if hashname in enums.HASH_ALGO_OV or custom_hash_prefix_re.match(hashname):\n        return True\n    else:\n        return False",
    "docstring": "Return true if given value is a valid, recommended hash name according\n    to the STIX 2 specification."
  },
  {
    "code": "def number_of_statements(self, n):\n        stmt_type = n.type\n        if stmt_type == syms.compound_stmt:\n            return 1\n        elif stmt_type == syms.stmt:\n            return self.number_of_statements(n.children[0])\n        elif stmt_type == syms.simple_stmt:\n            return len(n.children) // 2\n        else:\n            raise AssertionError(\"non-statement node\")",
    "docstring": "Compute the number of AST statements contained in a node."
  },
  {
    "code": "def describe_processors(cls):\n        for processor in cls.post_processors(cls):\n            yield {'name': processor.__name__,\n                   'description': processor.__doc__,\n                   'processor': processor}",
    "docstring": "List all postprocessors and their description"
  },
  {
    "code": "def inspect(self):\n        timeout_manager = future_timeout_manager(self.sync_timeout)\n        sensor_index_before = copy.copy(self._sensors_index)\n        request_index_before = copy.copy(self._requests_index)\n        try:\n            request_changes = yield self.inspect_requests(\n                timeout=timeout_manager.remaining())\n            sensor_changes = yield self.inspect_sensors(\n                timeout=timeout_manager.remaining())\n        except Exception:\n            self._sensors_index = sensor_index_before\n            self._requests_index = request_index_before\n            raise\n        model_changes = AttrDict()\n        if request_changes:\n            model_changes.requests = request_changes\n        if sensor_changes:\n            model_changes.sensors = sensor_changes\n        if model_changes:\n            raise Return(model_changes)",
    "docstring": "Inspect device requests and sensors, update model\n\n        Returns\n        -------\n\n        Tornado future that resolves with:\n\n        model_changes : Nested AttrDict or None\n            Contains sets of added/removed request/sensor names\n\n            Example structure:\n\n            {'requests': {\n                'added': set(['req1', 'req2']),\n                'removed': set(['req10', 'req20'])}\n             'sensors': {\n                'added': set(['sens1', 'sens2']),\n                'removed': set(['sens10', 'sens20'])}\n            }\n\n            If there are no changes keys may be omitted. If an item is in both\n            the 'added' and 'removed' sets that means that it changed.\n\n            If neither request not sensor changes are present, None is returned\n            instead of a nested structure."
  },
  {
    "code": "def make_certificate_authority(**name):\n  key = make_pkey()\n  csr = make_certificate_signing_request(key, **name)\n  crt = make_certificate(csr, key, csr, make_serial(), 0, 10 * 365 * 24 * 60 * 60, exts=[crypto.X509Extension(b'basicConstraints', True, b'CA:TRUE')])\n  return key, crt",
    "docstring": "Make a certificate authority.\n\n  A certificate authority can sign certificates. For clients to be able to\n  validate certificates signed by your certificate authorithy, they must trust\n  the certificate returned by this function.\n\n  :param name: Key word arguments containing subject name parts: C, ST, L, O,\n    OU, CN.\n  :return: A root self-signed certificate to act as an authority.\n  :rtype: :class:`OpenSSL.crypto.X509`"
  },
  {
    "code": "def create(self, key=None, label=None):\n        key = '%s' % key\n        url = self.bitbucket.url('SET_SSH_KEY')\n        return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, key=key, label=label)",
    "docstring": "Associate an ssh key with your account and return it."
  },
  {
    "code": "def exec_task(task_path, data):\n    if not data:\n        data = {'data': None, 'path': task_path}\n    elif not isinstance(data, (str, bytes)):\n        data = {'data': json.dumps(data, cls=RequestJSONEncoder),\n                'path': task_path}\n    else:\n        if data is not None and data.startswith(\"file://\"):\n            with open(data[len(\"file://\"):]) as f:\n                data = f.read()\n        data = {'data': data, 'path': task_path}\n    job = Job(data)\n    (task, task_callable) = create_task(task_path)\n    with delegating_job_context(job, task, task_callable) as jc:\n        return jc.task_callable(jc.task_data)",
    "docstring": "Execute task.\n\n    :param task_path: task path\n    :type task_path: str|Callable\n    :param data: task's data\n    :type data: Any\n    :return:"
  },
  {
    "code": "def _validate_folder(self, folder=None):\n        from expfactory.experiment import load_experiment\n        if folder is None:\n            folder=os.path.abspath(os.getcwd())\n        config = load_experiment(folder, return_path=True)\n        if not config:\n            return notvalid(\"%s is not an experiment.\" %(folder))\n        return self._validate_config(folder)",
    "docstring": "validate folder takes a cloned github repo, ensures\n            the existence of the config.json, and validates it."
  },
  {
    "code": "def set_sequestered(self, sequestered):\n        if sequestered is None:\n            raise errors.NullArgument()\n        if self.get_sequestered_metadata().is_read_only():\n            raise errors.NoAccess()\n        if not isinstance(sequestered, bool):\n            raise errors.InvalidArgument()\n        self._my_map['sequestered'] = sequestered",
    "docstring": "Sets the sequestered flag.\n\n        arg:    sequestered (boolean): the new sequestered flag\n        raise:  InvalidArgument - ``sequestered`` is invalid\n        raise:  NoAccess - ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def flatten(self):\n        def _flatten(d):\n            if isinstance(d, dict):\n                for v in d.values():\n                    for nested_v in _flatten(v):\n                        yield nested_v\n            elif isinstance(d, list):\n                for list_v in d:\n                    for nested_v in _flatten(list_v):\n                        yield nested_v\n            else:\n                yield d\n        return self.__class__(list(_flatten(self.items)))",
    "docstring": "Get a flattened list of the items in the collection.\n\n        :rtype: Collection"
  },
  {
    "code": "def extracturls(mesg):\n    lines = NLRE.split(mesg)\n    linechunks = [parse_text_urls(l) for l in lines]\n    return extract_with_context(linechunks,\n                                lambda chunk: len(chunk) > 1 or\n                                (len(chunk) == 1 and chunk[0].url is not None),\n                                1, 1)",
    "docstring": "Given a text message, extract all the URLs found in the message, along\n    with their surrounding context.  The output is a list of sequences of Chunk\n    objects, corresponding to the contextual regions extracted from the string."
  },
  {
    "code": "def render(self, request, instance, **kwargs):\n        if instance.get_item():\n            return super(LinkPlugin, self).render(request, instance, **kwargs)\n        return \"\"",
    "docstring": "Only render the plugin if the item can be shown to the user"
  },
  {
    "code": "def _GenerateZipInfo(self, arcname=None, compress_type=None, st=None):\n    if st is None:\n      st = os.stat_result((0o100644, 0, 0, 0, 0, 0, 0, 0, 0, 0))\n    mtime = time.localtime(st.st_mtime or time.time())\n    date_time = mtime[0:6]\n    if arcname is None:\n      raise ValueError(\"An arcname must be provided.\")\n    zinfo = zipfile.ZipInfo(arcname, date_time)\n    zinfo.external_attr = (st[0] & 0xFFFF) << 16\n    if compress_type is None:\n      zinfo.compress_type = self._compression\n    else:\n      zinfo.compress_type = compress_type\n    zinfo.file_size = 0\n    zinfo.compress_size = 0\n    zinfo.flag_bits = 0x08\n    zinfo.CRC = 0x08074b50\n    zinfo.extra = struct.pack(\n        \"<HHIIHH\",\n        0x5855,\n        12,\n        0,\n        0,\n        0,\n        0)\n    return zinfo",
    "docstring": "Generate ZipInfo instance for the given name, compression and stat.\n\n    Args:\n      arcname: The name in the archive this should take.\n      compress_type: Compression type (zipfile.ZIP_DEFLATED, or ZIP_STORED)\n      st: An optional stat object to be used for setting headers.\n\n    Returns:\n      ZipInfo instance.\n\n    Raises:\n      ValueError: If arcname is not provided."
  },
  {
    "code": "def is_vertical_coordinate(var_name, var):\n    satisfied = var_name.lower() in _possiblez\n    satisfied |= getattr(var, 'standard_name', '') in _possiblez\n    satisfied |= getattr(var, 'axis', '').lower() == 'z'\n    is_pressure = units_convertible(getattr(var, 'units', '1'), 'dbar')\n    satisfied |= is_pressure\n    if not is_pressure:\n        satisfied |= getattr(var, 'positive', '').lower() in ('up', 'down')\n    return satisfied",
    "docstring": "Determines if a variable is a vertical coordinate variable\n\n    4.3\n    A vertical coordinate will be identifiable by: units of pressure; or the presence of the positive attribute with a\n    value of up or down (case insensitive).  Optionally, the vertical type may be indicated additionally by providing\n    the standard_name attribute with an appropriate value, and/or the axis attribute with the value Z."
  },
  {
    "code": "def get_mv_feeder_from_line(line):\n    try:\n        nodes = line.grid.graph.nodes_from_line(line)\n        feeders = {}\n        for node in nodes:\n            if isinstance(node, MVStation):\n                feeders[repr(node)] = None\n            else:\n                feeders[repr(node)] = node.mv_feeder\n        feeder_1 = feeders[repr(nodes[0])]\n        feeder_2 = feeders[repr(nodes[1])]\n        if not feeder_1 is None and not feeder_2 is None:\n            if feeder_1 == feeder_2:\n                return feeder_1\n            else:\n                logging.warning('Different feeders for line {}.'.format(line))\n                return None\n        else:\n            return feeder_1 if feeder_1 is not None else feeder_2\n    except Exception as e:\n        logging.warning('Failed to get MV feeder: {}.'.format(e))\n        return None",
    "docstring": "Determines MV feeder the given line is in.\n\n    MV feeders are identified by the first line segment of the half-ring.\n\n    Parameters\n    ----------\n    line : :class:`~.grid.components.Line`\n        Line to find the MV feeder for.\n\n    Returns\n    -------\n    :class:`~.grid.components.Line`\n        MV feeder identifier (representative of the first line segment\n        of the half-ring)"
  },
  {
    "code": "def _exec_query(self):\n        if not self._solr_locked:\n            if not self.compiled_query:\n                self._compile_query()\n            try:\n                solr_params = self._process_params()\n                if settings.DEBUG:\n                    t1 = time.time()\n                self._solr_cache = self.bucket.search(self.compiled_query,\n                                                      self.index_name,\n                                                      **solr_params)\n                if settings.DEBUG and settings.DEBUG_LEVEL >= 5:\n                    print(\"QRY => %s\\nSOLR_PARAMS => %s\" % (self.compiled_query, solr_params))\n            except riak.RiakError as err:\n                err.value += self._get_debug_data()\n                raise\n            self._solr_locked = True\n            return self._solr_cache['docs']",
    "docstring": "Executes solr query if it hasn't already executed.\n\n        Returns:\n            Self."
  },
  {
    "code": "def clean(self, *args, **kwargs):\n        if not self.pk:\n            if self.node.participation_settings.voting_allowed is not True:\n                raise ValidationError(\"Voting not allowed for this node\")\n            if 'nodeshot.core.layers' in settings.INSTALLED_APPS:\n                layer = self.node.layer\n                if layer.participation_settings.voting_allowed is not True:\n                    raise ValidationError(\"Voting not allowed for this layer\")",
    "docstring": "Check if votes can be inserted for parent node or parent layer"
  },
  {
    "code": "def PlaceSOffsetT(self, x):\n        N.enforce_number(x, N.SOffsetTFlags)\n        self.head = self.head - N.SOffsetTFlags.bytewidth\n        encode.Write(packer.soffset, self.Bytes, self.Head(), x)",
    "docstring": "PlaceSOffsetT prepends a SOffsetT to the Builder, without checking\n        for space."
  },
  {
    "code": "def send(self, msg):\n        if self._conn:\n            self._conn.write_data(msg.message, msg.response_command)",
    "docstring": "Send a message to Elk panel."
  },
  {
    "code": "def _first_of_quarter(self, day_of_week=None):\n        return self.on(self.year, self.quarter * 3 - 2, 1).first_of(\n            \"month\", day_of_week\n        )",
    "docstring": "Modify to the first occurrence of a given day of the week\n        in the current quarter. If no day_of_week is provided,\n        modify to the first day of the quarter. Use the supplied consts\n        to indicate the desired day_of_week, ex. DateTime.MONDAY.\n\n        :type day_of_week: int or None\n\n        :rtype: DateTime"
  },
  {
    "code": "def _spherical_to_cartesian(cls, coord, center):\n        r, theta, phi, r_dot, theta_dot, phi_dot = coord\n        x = r * cos(phi) * cos(theta)\n        y = r * cos(phi) * sin(theta)\n        z = r * sin(phi)\n        vx = r_dot * x / r - y * theta_dot - z * phi_dot * cos(theta)\n        vy = r_dot * y / r + x * theta_dot - z * phi_dot * sin(theta)\n        vz = r_dot * z / r + r * phi_dot * cos(phi)\n        return np.array([x, y, z, vx, vy, vz], dtype=float)",
    "docstring": "Spherical to cartesian conversion"
  },
  {
    "code": "def get(self, namespace, key):\n        cfg = self.dbconfig.get(key, namespace, as_object=True)\n        return self.make_response({\n            'message': None,\n            'config': cfg\n        })",
    "docstring": "Get a specific configuration item"
  },
  {
    "code": "def investment_term(self, investment_term):\n        try:\n            if isinstance(investment_term, (str, int)):\n                self._investment_term = int(investment_term)\n        except Exception:\n            raise ValueError('invalid input of investment type %s, cannot be converted to an int' %\n                             investment_term)",
    "docstring": "This investment term is in months.  This might change to a relative delta."
  },
  {
    "code": "def run(self):\n        LOGGER.debug('Initializing process')\n        self.logging_config = self.setup_logging()\n        self.setup_signal_handlers()\n        try:\n            self.app = self.create_application()\n        except exceptions.NoRoutesException:\n            return\n        self.http_server = self.create_http_server()\n        self.ioloop = ioloop.IOLoop.instance()\n        try:\n            self.ioloop.start()\n        except KeyboardInterrupt:\n            pass",
    "docstring": "Called when the process has started\n\n        :param int port: The HTTP Server port"
  },
  {
    "code": "def check_robotstxt(url, session):\n    roboturl = get_roboturl(url)\n    rp = get_robotstxt_parser(roboturl, session=session)\n    if not rp.can_fetch(UserAgent, str(url)):\n        raise IOError(\"%s is disallowed by %s\" % (url, roboturl))",
    "docstring": "Check if robots.txt allows our user agent for the given URL.\n    @raises: IOError if URL is not allowed"
  },
  {
    "code": "def receiveds_not_parsed(receiveds):\n    log.debug(\"Receiveds for this email are not parsed\")\n    output = []\n    counter = Counter()\n    for i in receiveds[::-1]:\n        j = {\"raw\": i.strip()}\n        j[\"hop\"] = counter[\"hop\"] + 1\n        counter[\"hop\"] += 1\n        output.append(j)\n    else:\n        return output",
    "docstring": "If receiveds are not parsed, makes a new structure with raw\n    field. It's useful to have the same structure of receiveds\n    parsed.\n\n    Args:\n        receiveds (list): list of raw receiveds headers\n\n    Returns:\n        a list of not parsed receiveds headers with first hop in first position"
  },
  {
    "code": "def limit_x(\n        self,\n        limit_lower = None,\n        limit_upper = None\n        ):\n        if limit_lower is None and limit_upper is None:\n            return self._limit_x\n        elif hasattr(limit_lower, \"__iter__\"):\n            self._limit_x = limit_lower[:2]\n        else:\n            self._limit_x = [limit_lower, limit_upper]\n        if self._limit_x[0] == self._limit_x[1]:\n            self._limit_x[1] += 1\n        self._limit_x[0] -= self.mod_x\n        self._limit_x[1] += self.mod_x",
    "docstring": "get or set x limits of the current axes\n\n        x_min, x_max = limit_x() # return the current limit_x\n        limit_x(x_min, x_max)    # set the limit_x to x_min, x_max"
  },
  {
    "code": "def _unbytes(bytestr):\n    return ''.join(chr(int(bytestr[k:k + 2], 16))\n                   for k in range(0, len(bytestr), 2))",
    "docstring": "Returns a bytestring from the human-friendly string returned by `_bytes`.\n\n    >>> _unbytes('123456')\n    '\\x12\\x34\\x56'"
  },
  {
    "code": "def _properties_model_to_dict(properties):\n    result = {}\n    for attr in properties.__dict__:\n        value = getattr(properties, attr)\n        if hasattr(value, '__module__') and 'models' in value.__module__:\n            value = _properties_model_to_dict(value)\n        if not (value is None or (isinstance(value, dict) and not value)):\n            result[attr] = value\n    return result",
    "docstring": "Convert properties model to dict.\n\n    Args:\n        properties: Properties model.\n\n    Returns:\n        dict: Converted model."
  },
  {
    "code": "def _get_datasets(dataset_ids):\n    dataset_dict = {}\n    datasets = []\n    if len(dataset_ids) > qry_in_threshold:\n        idx = 0\n        extent =qry_in_threshold\n        while idx < len(dataset_ids):\n            log.info(\"Querying %s datasets\", len(dataset_ids[idx:extent]))\n            rs = db.DBSession.query(Dataset).filter(Dataset.id.in_(dataset_ids[idx:extent])).all()\n            datasets.extend(rs)\n            idx = idx + qry_in_threshold\n            if idx + qry_in_threshold > len(dataset_ids):\n                extent = len(dataset_ids)\n            else:\n                extent = extent + qry_in_threshold\n    else:\n        datasets = db.DBSession.query(Dataset).filter(Dataset.id.in_(dataset_ids))\n    for r in datasets:\n        dataset_dict[r.id] = r\n    log.info(\"Retrieved %s datasets\", len(dataset_dict))\n    return dataset_dict",
    "docstring": "Get all the datasets in a list of dataset IDS. This must be done in chunks of 999,\n        as sqlite can only handle 'in' with < 1000 elements."
  },
  {
    "code": "def parse_template(template_str):\n    try:\n        return json.loads(template_str, object_pairs_hook=OrderedDict)\n    except ValueError:\n        yaml.SafeLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _dict_constructor)\n        yaml.SafeLoader.add_multi_constructor('!', intrinsics_multi_constructor)\n        return yaml.safe_load(template_str)",
    "docstring": "Parse the SAM template.\n\n    :param template_str: A packaged YAML or json CloudFormation template\n    :type template_str: str\n    :return: Dictionary with keys defined in the template\n    :rtype: dict"
  },
  {
    "code": "def wait_for(self, wait_for, timeout_ms):\n        if not isinstance(wait_for, baseinteger):\n            raise TypeError(\"wait_for can only be an instance of type baseinteger\")\n        if not isinstance(timeout_ms, baseinteger):\n            raise TypeError(\"timeout_ms can only be an instance of type baseinteger\")\n        reason = self._call(\"waitFor\",\n                     in_p=[wait_for, timeout_ms])\n        reason = ProcessWaitResult(reason)\n        return reason",
    "docstring": "Waits for one or more events to happen.\n\n        in wait_for of type int\n            Specifies what to wait for;\n            see :py:class:`ProcessWaitForFlag`  for more information.\n\n        in timeout_ms of type int\n            Timeout (in ms) to wait for the operation to complete.\n            Pass 0 for an infinite timeout.\n\n        return reason of type :class:`ProcessWaitResult`\n            The overall wait result;\n            see :py:class:`ProcessWaitResult`  for more information."
  },
  {
    "code": "def _update_justification(self, justification):\n        states = {\"left\": 2, \"center\": 0, \"right\": 1}\n        self.justify_tb.state = states[justification]\n        self.justify_tb.toggle(None)\n        self.justify_tb.Refresh()",
    "docstring": "Updates horizontal text justification button\n\n        Parameters\n        ----------\n\n        justification: String in [\"left\", \"center\", \"right\"]\n        \\tSwitches button to untoggled if False and toggled if True"
  },
  {
    "code": "def make_choice_validator(\n        choices, default_key=None, normalizer=None):\n    def normalize_all(_choices):\n        if normalizer:\n            _choices = [(normalizer(key), value) for key, value in choices]\n        return _choices\n    choices = normalize_all(choices)\n    def choice_validator(value):\n        if normalizer:\n            value = normalizer(value)\n        if not value and default_key:\n            value = choices[default_key][0]\n        results = []\n        for choice, mapped in choices:\n            if value == choice:\n                return mapped\n            if choice.startswith(value):\n                results.append((choice, mapped))\n        if len(results) == 1:\n            return results[0][1]\n        elif not results:\n            raise ValueError('Invalid choice.')\n        else:\n            raise ValueError(\n                'Choice ambiguous between (%s)' % ', '.join(\n                    k for k, v in normalize_all(results))\n            )\n    return choice_validator",
    "docstring": "Returns a callable that accepts the choices provided.\n\n    Choices should be provided as a list of 2-tuples, where the first\n    element is a string that should match user input (the key); the\n    second being the value associated with the key.\n\n    The callable by default will match, upon complete match the first\n    value associated with the result will be returned.  Partial matches\n    are supported.\n\n    If a default is provided, that value will be returned if the user\n    provided input is empty, i.e. the value that is mapped to the empty\n    string.\n\n    Finally, a normalizer function can be passed.  This normalizes all\n    keys and validation value."
  },
  {
    "code": "def ProcessMessages(self, active_notifications, queue_manager, time_limit=0):\n    now = time.time()\n    processed = 0\n    for notification in active_notifications:\n      if notification.session_id not in self.queued_flows:\n        if time_limit and time.time() - now > time_limit:\n          break\n        processed += 1\n        self.queued_flows.Put(notification.session_id, 1)\n        self.thread_pool.AddTask(\n            target=self._ProcessMessages,\n            args=(notification, queue_manager.Copy()),\n            name=self.__class__.__name__)\n    return processed",
    "docstring": "Processes all the flows in the messages.\n\n    Precondition: All tasks come from the same queue.\n\n    Note that the server actually completes the requests in the\n    flow when receiving the messages from the client. We do not really\n    look at the messages here at all any more - we just work from the\n    completed messages in the flow RDFValue.\n\n    Args:\n        active_notifications: The list of notifications.\n        queue_manager: QueueManager object used to manage notifications,\n          requests and responses.\n        time_limit: If set return as soon as possible after this many seconds.\n\n    Returns:\n        The number of processed flows."
  },
  {
    "code": "def create_tree(self):\n        feature_indices = []\n        for i in self.estimator.tree_.feature:\n            n_features = self.n_features\n            if self.n_features > 1 or (self.n_features == 1 and i >= 0):\n                feature_indices.append([str(j) for j in range(n_features)][i])\n        indentation = 1 if self.target_language in ['java', 'js',\n                                                    'php', 'ruby'] else 0\n        return self.create_branches(\n            self.estimator.tree_.children_left,\n            self.estimator.tree_.children_right,\n            self.estimator.tree_.threshold,\n            self.estimator.tree_.value,\n            feature_indices, 0, indentation)",
    "docstring": "Parse and build the tree branches.\n\n        Returns\n        -------\n        :return : string\n            The tree branches as string."
  },
  {
    "code": "def yaml_to_str(data: Mapping) -> str:\n    return yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper)",
    "docstring": "Return the given given config as YAML str.\n\n    :param data: configuration dict\n    :return: given configuration as yaml str"
  },
  {
    "code": "async def create(self, token):\n        token = encode_token(token)\n        response = await self._api.put(\"/v1/acl/create\", data=token)\n        return response.body",
    "docstring": "Creates a new token with a given policy\n\n        Parameters:\n            token (Object): Token specification\n        Returns:\n            Object: token ID\n\n        The create endpoint is used to make a new token.\n        A token has a name, a type, and a set of ACL rules.\n\n        The request body may take the form::\n\n            {\n                \"Name\": \"my-app-token\",\n                \"Type\": \"client\",\n                \"Rules\": \"\"\n            }\n\n        None of the fields are mandatory. The **Name** and **Rules** fields\n        default to being blank, and the **Type** defaults to \"client\".\n\n        **Name** is opaque to Consul. To aid human operators, it should\n        be a meaningful indicator of the ACL's purpose.\n\n        **Type** is either **client** or **management**. A management token\n        is comparable to a root user and has the ability to perform any action\n        including creating, modifying and deleting ACLs.\n\n        **ID** field may be provided, and if omitted a random UUID will be\n        generated.\n\n        The format of **Rules** is\n        `documented here <https://www.consul.io/docs/internals/acl.html>`_.\n\n        A successful response body will return the **ID** of the newly\n        created ACL, like so::\n\n            {\n                \"ID\": \"adf4238a-882b-9ddc-4a9d-5b6758e4159e\"\n            }"
  },
  {
    "code": "def _get_groups(network_id, template_id=None):\n    extras = {'types':[], 'attributes':[]}\n    group_qry = db.DBSession.query(ResourceGroup).filter(\n                                        ResourceGroup.network_id==network_id,\n                                        ResourceGroup.status=='A').options(\n                                            noload('network')\n                                        )\n    if template_id is not None:\n        group_qry = group_qry.filter(ResourceType.group_id==ResourceGroup.id,\n                                     TemplateType.id==ResourceType.type_id,\n                                     TemplateType.template_id==template_id)\n    group_res = db.DBSession.execute(group_qry.statement).fetchall()\n    groups = []\n    for g in group_res:\n        groups.append(JSONObject(g, extras=extras))\n    return groups",
    "docstring": "Get all the resource groups in a network"
  },
  {
    "code": "def add_child_hash(self, child_hash):\n        if not (isinstance(child_hash,PCABinaryProjections) or isinstance(child_hash,RandomBinaryProjections) or isinstance(child_hash,RandomBinaryProjectionTree)):\n            raise ValueError('Child hashes must generate binary keys')\n        self.child_hashes.append(child_hash)",
    "docstring": "Adds specified child hash.\n\n        The hash must be one of the binary types."
  },
  {
    "code": "def convertfields_old(key_comm, obj, inblock=None):\n    convinidd = ConvInIDD()\n    typefunc = dict(integer=convinidd.integer, real=convinidd.real)\n    types = []\n    for comm in key_comm:\n        types.append(comm.get('type', [None])[0])\n    convs = [typefunc.get(typ, convinidd.no_type) for typ in types]\n    try:\n        inblock = list(inblock)\n    except TypeError as e:\n        inblock = ['does not start with N'] * len(obj)\n    for i, (val, conv, avar) in enumerate(zip(obj, convs, inblock)):\n        if i == 0:\n            pass\n        else:\n            val = conv(val, inblock[i])\n        obj[i] = val\n    return obj",
    "docstring": "convert the float and interger fields"
  },
  {
    "code": "def to_sa_pair_form(self, sparse=True):\n        if self._sa_pair:\n            return self\n        else:\n            s_ind, a_ind = np.where(self.R > - np.inf)\n            RL = self.R[s_ind, a_ind]\n            if sparse:\n                QL = sp.csr_matrix(self.Q[s_ind, a_ind])\n            else:\n                QL = self.Q[s_ind, a_ind]\n            return DiscreteDP(RL, QL, self.beta, s_ind, a_ind)",
    "docstring": "Convert this instance of `DiscreteDP` to SA-pair form\n\n        Parameters\n        ----------\n        sparse : bool, optional(default=True)\n            Should the `Q` matrix be stored as a sparse matrix?\n            If true the CSR format is used\n\n        Returns\n        -------\n        ddp_sa : DiscreteDP\n            The correspnoding DiscreteDP instance in SA-pair form\n\n        Notes\n        -----\n        If this instance is already in SA-pair form then it is returned\n        un-modified"
  },
  {
    "code": "def write_to(self, f):\n        f.write(self.version + \"\\r\\n\")\n        for name, value in self.items():\n            name = name.title()\n            name = name.replace(\"Warc-\", \"WARC-\").replace(\"-Ip-\", \"-IP-\").replace(\"-Id\", \"-ID\").replace(\"-Uri\", \"-URI\")\n            f.write(name)\n            f.write(\": \")\n            f.write(value)\n            f.write(\"\\r\\n\")\n        f.write(\"\\r\\n\")",
    "docstring": "Writes this header to a file, in the format specified by WARC."
  },
  {
    "code": "def get_most_recent_network_by_name(self, name: str) -> Optional[Network]:\n        return self.session.query(Network).filter(Network.name == name).order_by(Network.created.desc()).first()",
    "docstring": "Get the most recently created network with the given name."
  },
  {
    "code": "def fileInfo(self, index):\n        return self._fs_model_source.fileInfo(\n            self._fs_model_proxy.mapToSource(index))",
    "docstring": "Gets the file info of the item at the specified ``index``.\n\n        :param index: item index - QModelIndex\n        :return: QFileInfo"
  },
  {
    "code": "def indication(self, *args, **kwargs):\n        if not self.current_terminal:\n            raise RuntimeError(\"no active terminal\")\n        if not isinstance(self.current_terminal, Server):\n            raise RuntimeError(\"current terminal not a server\")\n        self.current_terminal.indication(*args, **kwargs)",
    "docstring": "Downstream packet, send to current terminal."
  },
  {
    "code": "def labels(self):\n        labels = self._properties.get(\"labels\")\n        if labels is None:\n            return {}\n        return copy.deepcopy(labels)",
    "docstring": "Retrieve or set labels assigned to this bucket.\n\n        See\n        https://cloud.google.com/storage/docs/json_api/v1/buckets#labels\n\n        .. note::\n\n           The getter for this property returns a dict which is a *copy*\n           of the bucket's labels.  Mutating that dict has no effect unless\n           you then re-assign the dict via the setter.  E.g.:\n\n           >>> labels = bucket.labels\n           >>> labels['new_key'] = 'some-label'\n           >>> del labels['old_key']\n           >>> bucket.labels = labels\n           >>> bucket.update()\n\n        :setter: Set labels for this bucket.\n        :getter: Gets the labels for this bucket.\n\n        :rtype: :class:`dict`\n        :returns: Name-value pairs (string->string) labelling the bucket."
  },
  {
    "code": "def group_add(self, name='Ungrouped'):\n        if not hasattr(self, name):\n            self.__dict__[name] = Group(self, name)\n            self.loaded_groups.append(name)",
    "docstring": "Dynamically add a group instance to the system if not exist.\n\n        Parameters\n        ----------\n        name : str, optional ('Ungrouped' as default)\n            Name of the group\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def process(self, document):\n        content = json.dumps(document)\n        versions = {}\n        versions.update({'Spline': Version(VERSION)})\n        versions.update(self.get_version(\"Bash\", self.BASH_VERSION))\n        if content.find('\"docker(container)\":') >= 0 or content.find('\"docker(image)\":') >= 0:\n            versions.update(VersionsCheck.get_version(\"Docker\", self.DOCKER_VERSION))\n        if content.find('\"packer\":') >= 0:\n            versions.update(VersionsCheck.get_version(\"Packer\", self.PACKER_VERSION))\n        if content.find('\"ansible(simple)\":') >= 0:\n            versions.update(VersionsCheck.get_version('Ansible', self.ANSIBLE_VERSION))\n        return versions",
    "docstring": "Logging versions of required tools."
  },
  {
    "code": "def write_metadata(self, fp):\n        fp.attrs['model'] = self.name\n        fp.attrs['variable_params'] = list(self.variable_params)\n        fp.attrs['sampling_params'] = list(self.sampling_params)\n        fp.write_kwargs_to_attrs(fp.attrs, static_params=self.static_params)",
    "docstring": "Writes metadata to the given file handler.\n\n        Parameters\n        ----------\n        fp : pycbc.inference.io.BaseInferenceFile instance\n            The inference file to write to."
  },
  {
    "code": "def build_synchronize_decorator():\n  lock = threading.Lock()\n  def lock_decorator(fn):\n    @functools.wraps(fn)\n    def lock_decorated(*args, **kwargs):\n      with lock:\n        return fn(*args, **kwargs)\n    return lock_decorated\n  return lock_decorator",
    "docstring": "Returns a decorator which prevents concurrent calls to functions.\n\n  Usage:\n    synchronized = build_synchronize_decorator()\n\n    @synchronized\n    def read_value():\n      ...\n\n    @synchronized\n    def write_value(x):\n      ...\n\n  Returns:\n    make_threadsafe (fct): The decorator which lock all functions to which it\n      is applied under a same lock"
  },
  {
    "code": "def read_colorscale(cmap_file):\n    assert isinstance(cmap_file, str)\n    cm = np.loadtxt(cmap_file, delimiter='\\t', dtype=np.float64)\n    rgb = np.int64(cm[:, 1:])\n    n = cm.shape[0]\n    colorscale = []\n    for i in range(n):\n        colorscale.append(\n            [i / float(n - 1),\n             'rgb(%d, %d, %d)' % (rgb[i, 0], rgb[i, 1], rgb[i, 2])]\n        )\n    return colorscale",
    "docstring": "Return a colorscale in the format expected by plotly.\n\n    Parameters\n    ----------\n    cmap_file : str\n        Path of a plain-text file containing the colorscale. \n\n    Returns\n    -------\n    list\n        The colorscale.\n        \n    Notes\n    -----\n    A plotly colorscale is a list where each item is a pair\n    (i.e., a list with two elements) consisting of\n    a decimal number x between 0 and 1 and a corresponding \"rgb(r,g,b)\" string,\n    where r, g, and b are integers between 0 and 255.\n\n    The `cmap_file` is a tab-separated text file containing four columns\n    (x,r,g,b), so that each row corresponds to an entry in the list\n    described above."
  },
  {
    "code": "def recent_photos(request):\n    imgs = []\n    for obj in Image_File.objects.filter(is_image=True).order_by(\"-date_created\"):\n        upurl = \"/\" + obj.upload.url\n        thumburl = \"\"\n        if obj.thumbnail:\n            thumburl = \"/\" + obj.thumbnail.url\n        imgs.append({'src': upurl, 'thumb': thumburl, 'is_image': True})\n    return render_to_response('dashboard/browse.html', {'files': imgs})",
    "docstring": "returns all the images from the data base"
  },
  {
    "code": "def solveConsKinkyPref(solution_next,IncomeDstn,PrefShkDstn,\n                       LivPrb,DiscFac,CRRA,Rboro,Rsave,PermGroFac,BoroCnstArt,\n                       aXtraGrid,vFuncBool,CubicBool):\n    solver = ConsKinkyPrefSolver(solution_next,IncomeDstn,PrefShkDstn,LivPrb,\n                             DiscFac,CRRA,Rboro,Rsave,PermGroFac,BoroCnstArt,\n                             aXtraGrid,vFuncBool,CubicBool)\n    solver.prepareToSolve()\n    solution = solver.solve()\n    return solution",
    "docstring": "Solves a single period of a consumption-saving model with preference shocks\n    to marginal utility and a different interest rate on saving vs borrowing.\n    Problem is solved using the method of endogenous gridpoints.\n\n    Parameters\n    ----------\n    solution_next : ConsumerSolution\n        The solution to the succeeding one period problem.\n    IncomeDstn : [np.array]\n        A list containing three arrays of floats, representing a discrete\n        approximation to the income process between the period being solved\n        and the one immediately following (in solution_next). Order: event\n        probabilities, permanent shocks, transitory shocks.\n    PrefShkDstn : [np.array]\n        Discrete distribution of the multiplicative utility shifter.  Order:\n        probabilities, preference shocks.\n    LivPrb : float\n        Survival probability; likelihood of being alive at the beginning of\n        the succeeding period.\n    DiscFac : float\n        Intertemporal discount factor for future utility.\n    CRRA : float\n        Coefficient of relative risk aversion.\n    Rboro: float\n        Interest factor on assets between this period and the succeeding\n        period when assets are negative.\n    Rsave: float\n        Interest factor on assets between this period and the succeeding\n        period when assets are positive.\n    PermGroGac : float\n        Expected permanent income growth factor at the end of this period.\n    BoroCnstArt: float or None\n        Borrowing constraint for the minimum allowable assets to end the\n        period with.  If it is less than the natural borrowing constraint,\n        then it is irrelevant; BoroCnstArt=None indicates no artificial bor-\n        rowing constraint.\n    aXtraGrid: np.array\n        Array of \"extra\" end-of-period asset values-- assets above the\n        absolute minimum acceptable level.\n    vFuncBool: boolean\n        An indicator for whether the value function should be computed and\n        included in the reported solution.\n    CubicBool: boolean\n        An indicator for whether the solver should use cubic or linear inter-\n        polation.\n\n    Returns\n    -------\n    solution: ConsumerSolution\n        The solution to the single period consumption-saving problem.  Includes\n        a consumption function cFunc (using linear splines), a marginal value\n        function vPfunc, a minimum acceptable level of normalized market re-\n        sources mNrmMin, normalized human wealth hNrm, and bounding MPCs MPCmin\n        and MPCmax.  It might also have a value function vFunc.  The consumption\n        function is defined over normalized market resources and the preference\n        shock, c = cFunc(m,PrefShk), but the (marginal) value function is defined\n        unconditionally on the shock, just before it is revealed."
  },
  {
    "code": "def grant(args):\n    try:\n        role = resources.iam.Role(args.iam_role_or_instance)\n        role.load()\n    except ClientError:\n        role = get_iam_role_for_instance(args.iam_role_or_instance)\n    role.attach_policy(PolicyArn=ensure_deploy_iam_policy().arn)\n    for private_repo in [args.repo] + list(private_submodules(args.repo)):\n        gh_owner_name, gh_repo_name = parse_repo_name(private_repo)\n        secret = secrets.put(argparse.Namespace(secret_name=\"deploy.{}.{}\".format(gh_owner_name, gh_repo_name),\n                                                iam_role=role.name,\n                                                instance_profile=None,\n                                                iam_group=None,\n                                                iam_user=None,\n                                                generate_ssh_key=True))\n        get_repo(private_repo).create_key(__name__ + \".\" + role.name, secret[\"ssh_public_key\"])\n        logger.info(\"Created deploy key %s for IAM role %s to access GitHub repo %s\",\n                    secret[\"ssh_key_fingerprint\"], role.name, private_repo)",
    "docstring": "Given an IAM role or instance name, attach an IAM policy granting\n    appropriate permissions to subscribe to deployments. Given a\n    GitHub repo URL, create and record deployment keys for the repo\n    and any of its private submodules, making the keys accessible to\n    the IAM role."
  },
  {
    "code": "def _create_table(self, table_name):\n        if self.fieldnames:\n            sql_fields = []\n            for field in self._fields:\n                if field != '_id':\n                    if 'dblite' in self._fields[field]:\n                        sql_fields.append(' '.join([field, self._fields[field]['dblite']]))\n                    else:\n                        sql_fields.append(field)\n            sql_fields = ','.join(sql_fields)\n            SQL = 'CREATE TABLE IF NOT EXISTS %s (%s);' % (table_name, sql_fields)\n            try:\n                self._cursor.execute(SQL)\n            except sqlite3.OperationalError, err:\n                raise RuntimeError('Create table error, %s, SQL: %s' % (err, SQL))",
    "docstring": "create sqlite's table for storing simple dictionaries"
  },
  {
    "code": "def on_frame(self, frame_in):\n        if self.rpc.on_frame(frame_in):\n            return\n        if frame_in.name in CONTENT_FRAME:\n            self._inbound.append(frame_in)\n        elif frame_in.name == 'Basic.Cancel':\n            self._basic_cancel(frame_in)\n        elif frame_in.name == 'Basic.CancelOk':\n            self.remove_consumer_tag(frame_in.consumer_tag)\n        elif frame_in.name == 'Basic.ConsumeOk':\n            self.add_consumer_tag(frame_in['consumer_tag'])\n        elif frame_in.name == 'Basic.Return':\n            self._basic_return(frame_in)\n        elif frame_in.name == 'Channel.Close':\n            self._close_channel(frame_in)\n        elif frame_in.name == 'Channel.Flow':\n            self.write_frame(specification.Channel.FlowOk(frame_in.active))\n        else:\n            LOGGER.error(\n                '[Channel%d] Unhandled Frame: %s -- %s',\n                self.channel_id, frame_in.name, dict(frame_in)\n            )",
    "docstring": "Handle frame sent to this specific channel.\n\n        :param pamqp.Frame frame_in: Amqp frame.\n        :return:"
  },
  {
    "code": "def transpose(self, permutation: Optional[List[int]] = None) -> 'TensorFluent':\n        if permutation == []:\n            return self\n        t = tf.transpose(self.tensor, permutation) if permutation != [] else self.tensor\n        scope = self.scope.as_list()\n        batch = self.batch\n        return TensorFluent(t, scope, batch=batch)",
    "docstring": "Returns a TensorFluent for the transpose operation with given `permutation`.\n\n        Args:\n            permutation: The output's shape permutation.\n\n        Returns:\n            A TensorFluent wrapping the transpose operation."
  },
  {
    "code": "def get_maya_location(self, ):\n        import _winreg\n        for ver in MAYA_VERSIONS:\n            try:\n                key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,\n                                      MAYA_REG_KEY.format(mayaversion=ver), 0,\n                                      _winreg.KEY_READ | _winreg.KEY_WOW64_64KEY)\n                value = _winreg.QueryValueEx(key, \"MAYA_INSTALL_LOCATION\")[0]\n            except WindowsError:\n                log.debug('Maya %s installation not found in registry!' % ver)\n        if not value:\n            raise errors.SoftwareNotFoundError('Maya %s installation not found in registry!' % MAYA_VERSIONS)\n        return value",
    "docstring": "Return the installation path to maya\n\n        :returns: path to maya\n        :rtype: str\n        :raises: errors.SoftwareNotFoundError"
  },
  {
    "code": "async def async_get_api_key(session, host, port, username=None, password=None, **kwargs):\n    url = 'http://{host}:{port}/api'.format(host=host, port=str(port))\n    auth = None\n    if username and password:\n        auth = aiohttp.BasicAuth(username, password=password)\n    data = b'{\"devicetype\": \"pydeconz\"}'\n    response = await async_request(session.post, url, auth=auth, data=data)\n    api_key = response[0]['success']['username']\n    _LOGGER.info(\"API key: %s\", api_key)\n    return api_key",
    "docstring": "Get a new API key for devicetype."
  },
  {
    "code": "def take_data_triggered(self, trigger, edge, stop):\n        param = {\n            ('curve', 'rising', 'buffer'): 0,\n            ('point', 'rising', 'buffer'): 1,\n            ('curve', 'falling', 'buffer'): 2,\n            ('point', 'falling', 'buffer'): 3,\n            ('curve', 'rising', 'halt'): 4,\n            ('point', 'rising', 'halt'): 5,\n            ('curve', 'falling', 'halt'): 6,\n            ('point', 'falling', 'halt'): 7,\n            ('curve', 'rising', 'trigger'): 8,\n            ('curve', 'falling', 'trigger'): 9,\n        }\n        self._write(('TDT', Integer), param[(trigger, edge, stop)])",
    "docstring": "Configures data acquisition to start on various trigger conditions.\n\n        :param trigger: The trigger condition, either 'curve' or 'point'.\n\n            ======= =======================================================\n            Value   Description\n            ======= =======================================================\n            'curve' Each trigger signal starts a curve acquisition.\n            'point' A point is stored for each trigger signal. The max\n                    trigger frequency in this mode is 1 kHz.\n            ======= =======================================================\n\n        :param edge: Defines wether a 'rising' or 'falling' edge is interpreted\n            as a trigger signal.\n        :param stop: The stop condition. Valid are 'buffer', 'halt',\n            'rising' and 'falling'.\n\n            ========= ==========================================================\n            Value     Description\n            ========= ==========================================================\n            'buffer'  Data acquisition stops when the number of point\n                      specified in :attr:`~.Buffer.length` is acquired.\n            'halt'    Data acquisition stops when the halt command is issued.\n            'trigger' Takes data for the period of a trigger event. If edge is\n                      'rising' then teh acquisition starts on the rising edge of\n                      the trigger signal and stops on the falling edge and vice\n                      versa\n            ========= =========================================================="
  },
  {
    "code": "def temporary_dir(root_dir=None, cleanup=True, suffix='', permissions=None, prefix=tempfile.template):\n  path = tempfile.mkdtemp(dir=root_dir, suffix=suffix, prefix=prefix)\n  try:\n    if permissions is not None:\n      os.chmod(path, permissions)\n    yield path\n  finally:\n    if cleanup:\n      shutil.rmtree(path, ignore_errors=True)",
    "docstring": "A with-context that creates a temporary directory.\n\n    :API: public\n\n    You may specify the following keyword args:\n    :param string root_dir: The parent directory to create the temporary directory.\n    :param bool cleanup: Whether or not to clean up the temporary directory.\n    :param int permissions: If provided, sets the directory permissions to this mode."
  },
  {
    "code": "def _decompress(self, cmd, s3_snap):\n        compressor = COMPRESSORS.get(s3_snap.compressor)\n        if compressor is None:\n            return cmd\n        decompress_cmd = compressor['decompress']\n        return \"{} | {}\".format(decompress_cmd, cmd)",
    "docstring": "Adds the appropriate command to decompress the zfs stream\n        This is determined from the metadata of the s3_snap."
  },
  {
    "code": "def __get_attribute(node, name, default_value=''):\n    if node.hasAttribute(name):\n        return node.attributes[name].value.strip()\n    else:\n        return default_value",
    "docstring": "Retrieves the attribute of the given name from the node.\n\n    If not present then the default_value is used."
  },
  {
    "code": "def partition_payload(data, key, thresh):\n    data = data[key]\n    for i in range(0, len(data), thresh):\n        yield {key: data[i:i + thresh]}",
    "docstring": "Yield partitions of a payload\n\n    e.g. with a threshold of 2:\n\n    { \"dataElements\": [1, 2, 3] }\n    -->\n    { \"dataElements\": [1, 2] }\n       and\n    { \"dataElements\": [3] }\n\n    :param data: the payload\n    :param key: the key of the dict to partition\n    :param thresh: the maximum value of a chunk\n    :return: a generator where __next__ is a partition of the payload"
  },
  {
    "code": "def grouper(iterable: Iterable, size: int) -> Iterable:\n    it = iter(iterable)\n    while True:\n        chunk = list(itertools.islice(it, size))\n        if not chunk:\n            return\n        yield chunk",
    "docstring": "Collect data into fixed-length chunks or blocks without discarding underfilled chunks or padding them.\n\n    :param iterable: A sequence of inputs.\n    :param size: Chunk size.\n    :return: Sequence of chunks."
  },
  {
    "code": "def use(self, key, value):\n        old_value = self[key]\n        try:\n            self[key] = value\n            yield self\n        finally:\n            self[key] = old_value",
    "docstring": "Temporarily set a parameter value using the with statement.\n        Aliasing allowed."
  },
  {
    "code": "def charges(self, num, charge_id=None, **kwargs):\n        baseuri = self._BASE_URI + \"company/{}/charges\".format(num)\n        if charge_id is not None:\n            baseuri += \"/{}\".format(charge_id)\n            res = self.session.get(baseuri, params=kwargs)\n        else:\n            res = self.session.get(baseuri, params=kwargs)\n        self.handle_http_error(res)\n        return res",
    "docstring": "Search for charges against a company by company number.\n\n        Args:\n          num (str): Company number to search on.\n          transaction (Optional[str]): Filing record number.\n          kwargs (dict): additional keywords passed into\n          requests.session.get params keyword."
  },
  {
    "code": "def define(self):\n        self.collections = []\n        self.camera_collection = \\\n            SimpleCollection(filename=os.path.join(self.directory, \"devices.dat\"),\n                             row_classes=[\n                DataModel.EmptyRow,\n                DataModel.RTSPCameraRow,\n                DataModel.USBCameraRow\n            ]\n            )\n        self.collections.append(self.camera_collection)\n        self.config_collection = \\\n            SimpleCollection(filename=os.path.join(self.directory, \"config.dat\"),\n                             row_classes=[\n                DataModel.MemoryConfigRow\n            ]\n            )\n        self.collections.append(self.config_collection)",
    "docstring": "Define column patterns and collections"
  },
  {
    "code": "def get_prediction(self, u=0):\n        return dot(self.F, self.x) + dot(self.B, u)",
    "docstring": "Predicts the next state of the filter and returns it. Does not\n        alter the state of the filter.\n\n        Parameters\n        ----------\n        u : ndarray\n            optional control input\n\n        Returns\n        -------\n        x : ndarray\n            State vector of the prediction."
  },
  {
    "code": "def call_script(self, script_dict, keys=None, args=None):\n        if keys is None:\n            keys = []\n        if args is None:\n            args = []\n        if 'script_object' not in script_dict:\n            script_dict['script_object'] = self.connection.register_script(script_dict['lua'])\n        return script_dict['script_object'](keys=keys, args=args, client=self.connection)",
    "docstring": "Call a redis script with keys and args\n\n        The first time we call a script, we register it to speed up later calls.\n        We expect a dict with a ``lua`` key having the script, and the dict will be\n        updated with a ``script_object`` key, with the content returned by the\n        the redis-py ``register_script`` command.\n\n        Parameters\n        ----------\n        script_dict: dict\n            A dict with a ``lua`` entry containing the lua code. A new key, ``script_object``\n            will be added after that.\n        keys: list of str\n            List of the keys that will be read/updated by the lua script\n        args: list of str\n            List of all the args expected by the script.\n\n        Returns\n        -------\n        Anything that will be returned by the script"
  },
  {
    "code": "def check_var_units(self, ds):\n        results = []\n        for variable in self.get_applicable_variables(ds):\n            msgs = []\n            unit_check = hasattr(ds.variables[variable], 'units')\n            no_dim_check = (getattr(ds.variables[variable], 'dimensions') == tuple())\n            if no_dim_check:\n                continue\n            if not unit_check:\n                msgs.append(\"units\")\n            results.append(Result(BaseCheck.HIGH, unit_check, self._var_header.format(variable), msgs))\n        return results",
    "docstring": "Checks each applicable variable for the units attribute\n\n        :param netCDF4.Dataset ds: An open netCDF dataset"
  },
  {
    "code": "def modifyReject(LowLayerCompatibility_presence=0,\n                 HighLayerCompatibility_presence=0):\n    a = TpPd(pd=0x3)\n    b = MessageType(mesType=0x13)\n    c = BearerCapability()\n    d = Cause()\n    packet = a / b / c / d\n    if LowLayerCompatibility_presence is 1:\n        e = LowLayerCompatibilityHdr(ieiLLC=0x7C, eightBitLLC=0x0)\n        packet = packet / e\n    if HighLayerCompatibility_presence is 1:\n        f = HighLayerCompatibilityHdr(ieiHLC=0x7D, eightBitHLC=0x0)\n        packet = packet / f\n    return packet",
    "docstring": "MODIFY REJECT Section 9.3.15"
  },
  {
    "code": "def options(self, section):\n        if not self.has_section(section):\n            raise NoSectionError(section) from None\n        return self.__getitem__(section).options()",
    "docstring": "Returns list of configuration options for the named section.\n\n        Args:\n            section (str): name of section\n\n        Returns:\n            list: list of option names"
  },
  {
    "code": "def build_mock_repository(conn_, file_path_list, verbose):\n    for file_path in file_path_list:\n        ext = _os.path.splitext(file_path)[1]\n        if not _os.path.exists(file_path):\n            raise ValueError('File name %s does not exist' % file_path)\n        if ext == '.mof':\n            conn_.compile_mof_file(file_path)\n        elif ext == '.py':\n            try:\n                with open(file_path) as fp:\n                    globalparams = {'CONN': conn_, 'VERBOSE': verbose}\n                    exec(fp.read(), globalparams, None)\n            except Exception as ex:\n                exc_type, exc_value, exc_traceback = _sys.exc_info()\n                tb = repr(traceback.format_exception(exc_type, exc_value,\n                                                     exc_traceback))\n                raise ValueError(\n                    'Exception failure of \"--mock-server\" python script %r '\n                    'with conn %r Exception: %r\\nTraceback\\n%s' %\n                    (file_path, conn, ex, tb))\n        else:\n            raise ValueError('Invalid suffix %s on \"--mock-server\" '\n                             'global parameter %s. Must be \"py\" or \"mof\".'\n                             % (ext, file_path))\n    if verbose:\n        conn_.display_repository()",
    "docstring": "Build the mock repository from the file_path list and fake connection\n    instance.  This allows both mof files and python files to be used to\n    build the repository.\n\n    If verbose is True, it displays the respository after it is build as\n    mof."
  },
  {
    "code": "def _addPub(self, stem, source):\n        key = re.sub(\"[^A-Za-z0-9&]+\", \" \", source).strip().upper()\n        self.sourceDict[key] = stem\n        self.bibstemWords.setdefault(stem, set()).update(\n            key.lower().split())",
    "docstring": "Enters stem as value for source."
  },
  {
    "code": "def to_html(self):\n        id, classes, kvs = self.id, self.classes, self.kvs\n        id_str = 'id=\"{}\"'.format(id) if id else ''\n        class_str = 'class=\"{}\"'.format(' '.join(classes)) if classes else ''\n        key_str = ' '.join('{}={}'.format(k, v) for k, v in kvs.items())\n        return ' '.join((id_str, class_str, key_str)).strip()",
    "docstring": "Returns attributes formatted as html."
  },
  {
    "code": "def validate(self,\n                 asset,\n                 amount,\n                 portfolio,\n                 algo_datetime,\n                 algo_current_data):\n        algo_date = algo_datetime.date()\n        if self.current_date and self.current_date != algo_date:\n            self.orders_placed = 0\n        self.current_date = algo_date\n        if self.orders_placed >= self.max_count:\n            self.handle_violation(asset, amount, algo_datetime)\n        self.orders_placed += 1",
    "docstring": "Fail if we've already placed self.max_count orders today."
  },
  {
    "code": "def _find_reasonable_stepsize(self, position, stepsize_app=1):\n        momentum = np.reshape(np.random.normal(0, 1, len(position)), position.shape)\n        position_bar, momentum_bar, _ =\\\n            self.simulate_dynamics(self.model, position, momentum,\n                                   stepsize_app, self.grad_log_pdf).get_proposed_values()\n        acceptance_prob = self._acceptance_prob(position, position_bar, momentum, momentum_bar)\n        a = 2 * (acceptance_prob > 0.5) - 1\n        condition = self._get_condition(acceptance_prob, a)\n        while condition:\n            stepsize_app = (2 ** a) * stepsize_app\n            position_bar, momentum_bar, _ =\\\n                self.simulate_dynamics(self.model, position, momentum,\n                                       stepsize_app, self.grad_log_pdf).get_proposed_values()\n            acceptance_prob = self._acceptance_prob(position, position_bar, momentum, momentum_bar)\n            condition = self._get_condition(acceptance_prob, a)\n        return stepsize_app",
    "docstring": "Method for choosing initial value of stepsize\n\n        References\n        -----------\n        Matthew D. Hoffman, Andrew Gelman, The No-U-Turn Sampler: Adaptively\n        Setting Path Lengths in Hamiltonian Monte Carlo. Journal of\n        Machine Learning Research 15 (2014) 1351-1381\n        Algorithm 4 : Heuristic for choosing an initial value of epsilon"
  },
  {
    "code": "def map(self,\n            internalize: Callable[[TExternalQubit], TInternalQubit],\n            externalize: Callable[[TInternalQubit], TExternalQubit]\n            ) -> 'QubitOrder':\n        def func(qubits):\n            unwrapped_qubits = [internalize(q) for q in qubits]\n            unwrapped_result = self.order_for(unwrapped_qubits)\n            return tuple(externalize(q) for q in unwrapped_result)\n        return QubitOrder(func)",
    "docstring": "Transforms the Basis so that it applies to wrapped qubits.\n\n        Args:\n            externalize: Converts an internal qubit understood by the underlying\n                basis into an external qubit understood by the caller.\n            internalize: Converts an external qubit understood by the caller\n                into an internal qubit understood by the underlying basis.\n\n        Returns:\n            A basis that transforms qubits understood by the caller into qubits\n            understood by an underlying basis, uses that to order the qubits,\n            then wraps the ordered qubits back up for the caller."
  },
  {
    "code": "def apply_to_field_if_exists(effect, field_name, fn, default):\n    value = getattr(effect, field_name, None)\n    if value is None:\n        return default\n    else:\n        return fn(value)",
    "docstring": "Apply function to specified field of effect if it is not None,\n    otherwise return default."
  },
  {
    "code": "def aer2ecef(az: float, el: float, srange: float,\n             lat0: float, lon0: float, alt0: float,\n             ell=None, deg: bool = True) -> Tuple[float, float, float]:\n    x0, y0, z0 = geodetic2ecef(lat0, lon0, alt0, ell, deg=deg)\n    e1, n1, u1 = aer2enu(az, el, srange, deg=deg)\n    dx, dy, dz = enu2uvw(e1, n1, u1, lat0, lon0, deg=deg)\n    return x0 + dx, y0 + dy, z0 + dz",
    "docstring": "converts target azimuth, elevation, range from observer at lat0,lon0,alt0 to ECEF coordinates.\n\n    Parameters\n    ----------\n    az : float or numpy.ndarray of float\n         azimuth to target\n    el : float or numpy.ndarray of float\n         elevation to target\n    srange : float or numpy.ndarray of float\n         slant range [meters]\n    lat0 : float\n           Observer geodetic latitude\n    lon0 : float\n           Observer geodetic longitude\n    h0 : float\n         observer altitude above geodetic ellipsoid (meters)\n    ell : Ellipsoid, optional\n          reference ellipsoid\n    deg : bool, optional\n          degrees input/output  (False: radians in/out)\n\n    Returns\n    -------\n\n    ECEF (Earth centered, Earth fixed)  x,y,z\n\n    x : float or numpy.ndarray of float\n        ECEF x coordinate (meters)\n    y : float or numpy.ndarray of float\n        ECEF y coordinate (meters)\n    z : float or numpy.ndarray of float\n        ECEF z coordinate (meters)\n\n\n    Notes\n    ------\n    if srange==NaN, z=NaN"
  },
  {
    "code": "def find_subdomains(domain):\n    result = set()\n    response = get('https://findsubdomains.com/subdomains-of/' + domain).text\n    matches = findall(r'(?s)<div class=\"domains js-domain-name\">(.*?)</div>', response)\n    for match in matches:\n        result.add(match.replace(' ', '').replace('\\n', ''))\n    return list(result)",
    "docstring": "Find subdomains according to the TLD."
  },
  {
    "code": "def getCityUsers(self, numberOfThreads=20):\n        if not self.__intervals:\n            self.__logger.debug(\"Calculating best intervals\")\n            self.calculateBestIntervals()\n        self.__end = False\n        self.__threads = set()\n        comprobationURL = self.__getURL()\n        self.__readAPI(comprobationURL)\n        self.__launchThreads(numberOfThreads)\n        self.__logger.debug(\"Launching threads\")\n        for i in self.__intervals:\n            self.__getPeriodUsers(i[0], i[1])\n        self.__end = True\n        for t in self.__threads:\n            t.join()\n        self.__logger.debug(\"Threads joined\")",
    "docstring": "Get all the users from the city.\n\n        :param numberOfThreads: number of threads to run.\n        :type numberOfThreads: int."
  },
  {
    "code": "def start(self):\n        run_by_ui = False\n        if not self.current_user.algo:\n            self._job = Job(self._project.id, self._software.id).save()\n            user_job = User().fetch(self._job.userJob)\n            self.set_credentials(user_job.publicKey, user_job.privateKey)\n        else:\n            self._job = Job().fetch(self.current_user.job)\n            run_by_ui = True\n        self._job.status = Job.RUNNING\n        self._job.update()\n        if not run_by_ui and self._parameters is not None:\n            parameters = vars(self._parameters)\n            for software_param in self._software.parameters:\n                name = software_param[\"name\"]\n                if name in parameters:\n                    value = parameters[name]\n                else:\n                    value = software_param[\"defaultParamValue\"]\n                JobParameter(self._job.id, software_param[\"id\"], value).save()",
    "docstring": "Connect to the Cytomine server and switch to job connection\n        Incurs dataflows"
  },
  {
    "code": "def all_successors(self, node, skip_reached_fixedpoint=False):\n        successors = set()\n        stack = [ node ]\n        while stack:\n            n = stack.pop()\n            successors.add(n)\n            stack.extend(succ for succ in self.successors(n) if\n                         succ not in successors and\n                            (not skip_reached_fixedpoint or succ not in self._reached_fixedpoint)\n                         )\n        return successors",
    "docstring": "Returns all successors to the specific node.\n\n        :param node: A node in the graph.\n        :return:     A set of nodes that are all successors to the given node.\n        :rtype:      set"
  },
  {
    "code": "def save_to_temp(content, file_name=None):\n    temp_dir = tempfile.gettempdir()\n    out_file = os.path.join(temp_dir, file_name)\n    file = open(out_file, 'w')\n    file.write(content)\n    file.close()\n    return out_file",
    "docstring": "Save the contents into a temp file."
  },
  {
    "code": "async def scp_to(self, source, destination, user='ubuntu', proxy=False,\n                     scp_opts=''):\n        if proxy:\n            raise NotImplementedError('proxy option is not implemented')\n        address = self.dns_name\n        destination = '%s@%s:%s' % (user, address, destination)\n        await self._scp(source, destination, scp_opts)",
    "docstring": "Transfer files to this machine.\n\n        :param str source: Local path of file(s) to transfer\n        :param str destination: Remote destination of transferred files\n        :param str user: Remote username\n        :param bool proxy: Proxy through the Juju API server\n        :param scp_opts: Additional options to the `scp` command\n        :type scp_opts: str or list"
  },
  {
    "code": "def transformFromNative(obj):\n        if not obj.isNative:\n            return obj\n        obj.isNative = False\n        obj.value = timedeltaToString(obj.value)\n        return obj",
    "docstring": "Replace the datetime.timedelta in obj.value with an RFC2445 string."
  },
  {
    "code": "def convert(self, targetunits):\n        nunits = units.Units(targetunits)\n        if nunits.isFlux:\n            self.fluxunits = nunits\n        else:\n            self.waveunits = nunits",
    "docstring": "Set new user unit, for either wavelength or flux.\n\n        This effectively converts the spectrum wavelength or flux\n        to given unit. Note that actual data are always kept in\n        internal units (Angstrom and ``photlam``), and only converted\n        to user units by :meth:`getArrays` during actual computation.\n        User units are stored in ``self.waveunits`` and ``self.fluxunits``.\n\n        Parameters\n        ----------\n        targetunits : str\n            New unit name, as accepted by `~pysynphot.units.Units`."
  },
  {
    "code": "def calc_qv_v1(self):\n    con = self.parameters.control.fastaccess\n    flu = self.sequences.fluxes.fastaccess\n    for i in range(2):\n        if (flu.av[i] > 0.) and (flu.uv[i] > 0.):\n            flu.qv[i] = (con.ekv[i]*con.skv[i] *\n                         flu.av[i]**(5./3.)/flu.uv[i]**(2./3.)*con.gef**.5)\n        else:\n            flu.qv[i] = 0.",
    "docstring": "Calculate the discharge of both forelands after Manning-Strickler.\n\n    Required control parameters:\n      |EKV|\n      |SKV|\n      |Gef|\n\n    Required flux sequence:\n      |AV|\n      |UV|\n\n    Calculated flux sequence:\n      |lstream_fluxes.QV|\n\n    Examples:\n\n        For appropriate strictly positive values:\n\n        >>> from hydpy.models.lstream import *\n        >>> parameterstep()\n        >>> ekv(2.0)\n        >>> skv(50.0)\n        >>> gef(0.01)\n        >>> fluxes.av = 3.0\n        >>> fluxes.uv = 7.0\n        >>> model.calc_qv_v1()\n        >>> fluxes.qv\n        qv(17.053102, 17.053102)\n\n        For zero or negative values of the flown through surface or\n        the wetted perimeter:\n\n        >>> fluxes.av = -1.0, 3.0\n        >>> fluxes.uv = 7.0, 0.0\n        >>> model.calc_qv_v1()\n        >>> fluxes.qv\n        qv(0.0, 0.0)"
  },
  {
    "code": "def esxcli(host, user, pwd, cmd, protocol=None, port=None, esxi_host=None, credstore=None):\n    esx_cmd = salt.utils.path.which('esxcli')\n    if not esx_cmd:\n        log.error('Missing dependency: The salt.utils.vmware.esxcli function requires ESXCLI.')\n        return False\n    if port is None:\n        port = 443\n    if protocol is None:\n        protocol = 'https'\n    if credstore:\n        esx_cmd += ' --credstore \\'{0}\\''.format(credstore)\n    if not esxi_host:\n        esx_cmd += ' -s {0} -u {1} -p \\'{2}\\' ' \\\n                   '--protocol={3} --portnumber={4} {5}'.format(host,\n                                                                user,\n                                                                pwd,\n                                                                protocol,\n                                                                port,\n                                                                cmd)\n    else:\n        esx_cmd += ' -s {0} -h {1} -u {2} -p \\'{3}\\' ' \\\n                   '--protocol={4} --portnumber={5} {6}'.format(host,\n                                                                esxi_host,\n                                                                user,\n                                                                pwd,\n                                                                protocol,\n                                                                port,\n                                                                cmd)\n    ret = salt.modules.cmdmod.run_all(esx_cmd, output_loglevel='quiet')\n    return ret",
    "docstring": "Shell out and call the specified esxcli commmand, parse the result\n    and return something sane.\n\n    :param host: ESXi or vCenter host to connect to\n    :param user: User to connect as, usually root\n    :param pwd: Password to connect with\n    :param port: TCP port\n    :param cmd: esxcli command and arguments\n    :param esxi_host: If `host` is a vCenter host, then esxi_host is the\n                      ESXi machine on which to execute this command\n    :param credstore: Optional path to the credential store file\n\n    :return: Dictionary"
  },
  {
    "code": "def get_bases(definition_dict, loader):\n    bases = definition_dict.get('bases', ())\n    if bases:\n        bases = (loader.get_comp_dict(required_version=SPEC_VERSION_TUPLE[0],\n                                      **b)\n                 for b in bases)\n        return SimpleChainmap(definition_dict, *bases)\n    else:\n        return definition_dict",
    "docstring": "Collect dependencies."
  },
  {
    "code": "def _string_from_ip_int(self, ip_int=None):\n        if not ip_int and ip_int != 0:\n            ip_int = int(self._ip)\n        if ip_int > self._ALL_ONES:\n            raise ValueError('IPv6 address is too large')\n        hex_str = '%032x' % ip_int\n        hextets = []\n        for x in range(0, 32, 4):\n            hextets.append('%x' % int(hex_str[x:x+4], 16))\n        hextets = self._compress_hextets(hextets)\n        return ':'.join(hextets)",
    "docstring": "Turns a 128-bit integer into hexadecimal notation.\n\n        Args:\n            ip_int: An integer, the IP address.\n\n        Returns:\n            A string, the hexadecimal representation of the address.\n\n        Raises:\n            ValueError: The address is bigger than 128 bits of all ones."
  },
  {
    "code": "def _check_configure_args(configure_args: Dict[str, Any]) -> Dict[str, Any]:\n    if not configure_args.get('ssid')\\\n       or not isinstance(configure_args['ssid'], str):\n        raise ConfigureArgsError(\"SSID must be specified\")\n    if not configure_args.get('hidden'):\n        configure_args['hidden'] = False\n    elif not isinstance(configure_args['hidden'], bool):\n        raise ConfigureArgsError('If specified, hidden must be a bool')\n    configure_args['securityType'] = _deduce_security(configure_args)\n    if configure_args['securityType'] == nmcli.SECURITY_TYPES.WPA_PSK:\n        if not configure_args.get('psk'):\n            raise ConfigureArgsError(\n                'If securityType is wpa-psk, psk must be specified')\n        return configure_args\n    if configure_args['securityType'] == nmcli.SECURITY_TYPES.WPA_EAP:\n        if not configure_args.get('eapConfig'):\n            raise ConfigureArgsError(\n                'If securityType is wpa-eap, eapConfig must be specified')\n        configure_args['eapConfig']\\\n            = _eap_check_config(configure_args['eapConfig'])\n        return configure_args\n    return configure_args",
    "docstring": "Check the arguments passed to configure.\n\n    Raises an exception on failure. On success, returns a dict of\n    configure_args with any necessary mutations."
  },
  {
    "code": "def random_jpath(depth = 3):\n    chunks = []\n    while depth > 0:\n        length = random.randint(5, 15)\n        ident  = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in range(length))\n        if random.choice((True, False)):\n            index  = random.randint(0, 10)\n            ident = \"{:s}[{:d}]\".format(ident, index)\n        chunks.append(ident)\n        depth -= 1\n    return \".\".join(chunks)",
    "docstring": "Generate random JPath with given node depth."
  },
  {
    "code": "def _process_cell(i, state, finite=False):\n    op_1 = state[i - 1]\n    op_2 = state[i]\n    if i == len(state) - 1:\n        if finite:\n            op_3 = state[0]\n        else:\n            op_3 = 0\n    else:\n        op_3 = state[i + 1]\n    result = 0\n    for i, val in enumerate([op_3, op_2, op_1]):\n        if val:\n            result += 2**i\n    return result",
    "docstring": "Process 3 cells and return a value from 0 to 7."
  },
  {
    "code": "def check_is_an_array(var, allow_none=False):\n    if not is_an_array(var, allow_none=allow_none):\n        raise TypeError(\"var must be a NumPy array, however type(var) is {}\"\n                        .format(type(var)))",
    "docstring": "Calls is_an_array and raises a type error if the check fails."
  },
  {
    "code": "def wait_for(func):\n    def wrapped(*args, **kwargs):\n        timeout = kwargs.pop('timeout', 15)\n        start = time()\n        result = None\n        while time() - start < timeout:\n            result = func(*args, **kwargs)\n            if result:\n                break\n            sleep(0.2)\n        return result\n    return wrapped",
    "docstring": "A decorator to invoke a function periodically until it returns a truthy\n    value."
  },
  {
    "code": "def _store_token(self, token, remember=False):\n        if token and remember:\n            try:\n                keyring.set_password('github', 'token', token)\n            except Exception:\n                if self._show_msgbox:\n                    QMessageBox.warning(self.parent_widget,\n                                        _('Failed to store token'),\n                                        _('It was not possible to securely '\n                                          'save your token. You will be '\n                                          'prompted for your Github token '\n                                          'next time you want to report '\n                                          'an issue.'))\n                remember = False\n        CONF.set('main', 'report_error/remember_token', remember)",
    "docstring": "Store token for future use."
  },
  {
    "code": "def set_last_access(self, tag):\n        import time\n        self.buildstate.access.last = '{}-{}'.format(tag, time.time())\n        self.buildstate.commit()",
    "docstring": "Mark the time that this bundle was last accessed"
  },
  {
    "code": "def links(self):\n        links = super(OffsetLimitPaginatedList, self).links\n        if self._page.offset + self._page.limit < self.count:\n            links[\"next\"] = Link.for_(\n                self._operation,\n                self._ns,\n                qs=self._page.next_page.to_items(),\n                **self._context\n            )\n        if self.offset > 0:\n            links[\"prev\"] = Link.for_(\n                self._operation,\n                self._ns,\n                qs=self._page.prev_page.to_items(),\n                **self._context\n            )\n        return links",
    "docstring": "Include previous and next links."
  },
  {
    "code": "def get_module_uuid(plpy, moduleid):\n    plan = plpy.prepare(\"SELECT uuid FROM modules WHERE moduleid = $1;\",\n                        ('text',))\n    result = plpy.execute(plan, (moduleid,), 1)\n    if result:\n        return result[0]['uuid']",
    "docstring": "Retrieve page uuid from legacy moduleid."
  },
  {
    "code": "def write_to(self, group):\n        items_group = group[self.name]\n        nitems = items_group.shape[0]\n        items_group.resize((nitems + len(self.data),))\n        items_group[nitems:] = self.data",
    "docstring": "Write stored items to the given HDF5 group.\n\n        We assume that self.create() has been called."
  },
  {
    "code": "def _packet_loop(self):\n        while self._is_running:\n            if self.inbox.empty() \\\n                    and not self.new_packet.wait(self._packet_timeout):\n                continue\n            ip, port, packet = self.inbox.get()\n            if self.inbox.empty():\n                self.new_packet.clear()\n            self.debug(u\"{}\".format(packet))\n            if packet.header.message_type == MsgType.CONFIG:\n                self._do_config_packet(packet, ip, port)\n            elif packet.header.message_type == MsgType.UPDATE:\n                self._do_update_packet(packet)",
    "docstring": "Packet processing loop\n\n        :rtype: None"
  },
  {
    "code": "def platform_detect():\n    pi = pi_version()\n    if pi is not None:\n        return RASPBERRY_PI\n    plat = platform.platform()\n    if plat.lower().find('armv7l-with-debian') > -1:\n        return BEAGLEBONE_BLACK\n    elif plat.lower().find('armv7l-with-ubuntu') > -1:\n        return BEAGLEBONE_BLACK\n    elif plat.lower().find('armv7l-with-glibc2.4') > -1:\n        return BEAGLEBONE_BLACK\n    elif plat.lower().find('armv7l-with-arch') > -1:\n        return BEAGLEBONE_BLACK\n    return UNKNOWN",
    "docstring": "Detect if running on the Raspberry Pi or Beaglebone Black and return the\n    platform type.  Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN."
  },
  {
    "code": "def send(self, data):\n        if self._device:\n            if isinstance(data, str):\n                data = str.encode(data)\n            if sys.version_info < (3,):\n                if isinstance(data, unicode):\n                    data = bytes(data)\n            self._device.write(data)",
    "docstring": "Sends data to the `AlarmDecoder`_ device.\n\n        :param data: data to send\n        :type data: string"
  },
  {
    "code": "def url_unquote(string, charset='utf-8', errors='replace', unsafe=''):\n    rv = _unquote_to_bytes(string, unsafe)\n    if charset is not None:\n        rv = rv.decode(charset, errors)\n    return rv",
    "docstring": "URL decode a single string with a given encoding.  If the charset\n    is set to `None` no unicode decoding is performed and raw bytes\n    are returned.\n\n    :param s: the string to unquote.\n    :param charset: the charset of the query string.  If set to `None`\n                    no unicode decoding will take place.\n    :param errors: the error handling for the charset decoding."
  },
  {
    "code": "def push(self, el):\n        count = next(self.counter)\n        heapq.heappush(self._queue, (el, count))",
    "docstring": "Put a new element in the queue."
  },
  {
    "code": "def autoencoder_residual_text():\n  hparams = autoencoder_residual()\n  hparams.bottleneck_bits = 32\n  hparams.batch_size = 1024\n  hparams.hidden_size = 64\n  hparams.max_hidden_size = 512\n  hparams.bottleneck_noise = 0.0\n  hparams.bottom = {\n      \"inputs\": modalities.identity_bottom,\n      \"targets\": modalities.identity_bottom,\n  }\n  hparams.top = {\n      \"targets\": modalities.identity_top,\n  }\n  hparams.autoregressive_mode = \"none\"\n  hparams.sample_width = 1\n  return hparams",
    "docstring": "Residual autoencoder model for text."
  },
  {
    "code": "def isSet(self, param):\n        param = self._resolveParam(param)\n        return param in self._paramMap",
    "docstring": "Checks whether a param is explicitly set by user."
  },
  {
    "code": "def get_hypo_location(self, mesh_spacing, hypo_loc=None):\n        mesh = self.mesh\n        centroid = mesh.get_middle_point()\n        if hypo_loc is None:\n            return centroid\n        total_len_y = (len(mesh.depths) - 1) * mesh_spacing\n        y_distance = hypo_loc[1] * total_len_y\n        y_node = int(numpy.round(y_distance / mesh_spacing))\n        total_len_x = (len(mesh.lons[y_node]) - 1) * mesh_spacing\n        x_distance = hypo_loc[0] * total_len_x\n        x_node = int(numpy.round(x_distance / mesh_spacing))\n        hypocentre = Point(mesh.lons[y_node][x_node],\n                           mesh.lats[y_node][x_node],\n                           mesh.depths[y_node][x_node])\n        return hypocentre",
    "docstring": "The method determines the location of the hypocentre within the rupture\n\n        :param mesh:\n            :class:`~openquake.hazardlib.geo.mesh.Mesh` of points\n        :param mesh_spacing:\n            The desired distance between two adjacent points in source's\n            ruptures' mesh, in km. Mainly this parameter allows to balance\n            the trade-off between time needed to compute the distance\n            between the rupture surface and a site and the precision of that\n            computation.\n        :param hypo_loc:\n            Hypocentre location as fraction of rupture plane, as a tuple of\n            (Along Strike, Down Dip), e.g. a hypocentre located in the centroid\n            of the rupture would be input as (0.5, 0.5), whereas a\n            hypocentre located in a position 3/4 along the length, and 1/4 of\n            the way down dip of the rupture plane would be entered as\n            (0.75, 0.25).\n        :returns:\n            Hypocentre location as instance of\n            :class:`~openquake.hazardlib.geo.point.Point`"
  },
  {
    "code": "def plot_points(points, lattice=None, coords_are_cartesian=False, fold=False,\n                ax=None, **kwargs):\n    ax, fig, plt = get_ax3d_fig_plt(ax)\n    if \"color\" not in kwargs:\n        kwargs[\"color\"] = \"b\"\n    if (not coords_are_cartesian or fold) and lattice is None:\n        raise ValueError(\n            \"coords_are_cartesian False or fold True require the lattice\")\n    for p in points:\n        if fold:\n            p = fold_point(p, lattice,\n                           coords_are_cartesian=coords_are_cartesian)\n        elif not coords_are_cartesian:\n            p = lattice.get_cartesian_coords(p)\n        ax.scatter(*p, **kwargs)\n    return fig, ax",
    "docstring": "Adds Points to a matplotlib Axes\n\n    Args:\n        points: list of coordinates\n        lattice: Lattice object used to convert from reciprocal to cartesian coordinates\n        coords_are_cartesian: Set to True if you are providing\n            coordinates in cartesian coordinates. Defaults to False.\n            Requires lattice if False.\n        fold: whether the points should be folded inside the first Brillouin Zone.\n            Defaults to False. Requires lattice if True.\n        ax: matplotlib :class:`Axes` or None if a new figure should be created.\n        kwargs: kwargs passed to the matplotlib function 'scatter'. Color defaults to blue\n\n    Returns:\n        matplotlib figure and matplotlib ax"
  },
  {
    "code": "def file_or_default(path, default, function = None):\n    try:\n        result = file_get_contents(path)\n        if function != None: return function(result)\n        return result\n    except IOError as e:\n        if e.errno == errno.ENOENT: return default\n        raise",
    "docstring": "Return a default value if a file does not exist"
  },
  {
    "code": "def datetime_parser(s):\n    try:\n        ts = arrow.get(s)\n        if ts.tzinfo == arrow.get().tzinfo:\n            ts = ts.replace(tzinfo='local')\n    except:\n        c = pdt.Calendar()\n        result, what = c.parse(s)\n        ts = None\n        if what in (1, 2, 3):\n            ts = datetime.datetime(*result[:6])\n            ts = arrow.get(ts)\n            ts = ts.replace(tzinfo='local')\n            return ts\n    if ts is None:\n        raise ValueError(\"Cannot parse timestamp '\" + s + \"'\")\n    return ts",
    "docstring": "Parse timestamp s in local time. First the arrow parser is used, if it fails, the parsedatetime parser is used.\n\n    :param s:\n    :return:"
  },
  {
    "code": "def _isna_old(obj):\n    if is_scalar(obj):\n        return libmissing.checknull_old(obj)\n    elif isinstance(obj, ABCMultiIndex):\n        raise NotImplementedError(\"isna is not defined for MultiIndex\")\n    elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass)):\n        return _isna_ndarraylike_old(obj)\n    elif isinstance(obj, ABCGeneric):\n        return obj._constructor(obj._data.isna(func=_isna_old))\n    elif isinstance(obj, list):\n        return _isna_ndarraylike_old(np.asarray(obj, dtype=object))\n    elif hasattr(obj, '__array__'):\n        return _isna_ndarraylike_old(np.asarray(obj))\n    else:\n        return obj is None",
    "docstring": "Detect missing values. Treat None, NaN, INF, -INF as null.\n\n    Parameters\n    ----------\n    arr: ndarray or object value\n\n    Returns\n    -------\n    boolean ndarray or boolean"
  },
  {
    "code": "def get_file(self, fid):\n        url = self.get_file_url(fid)\n        return self.conn.get_raw_data(url)",
    "docstring": "Get file from WeedFS.\n\n        Returns file content. May be problematic for large files as content is\n        stored in memory.\n\n        Args:\n            **fid**: File identifier <volume_id>,<file_name_hash>\n\n        Returns:\n            Content of the file with provided fid or None if file doesn't\n            exist on the server\n\n        .. versionadded:: 0.3.1"
  },
  {
    "code": "def make_tag(cls, tag_name):\n\t\tif cls.cm:\n\t\t\treturn cls.cm.make_tag(tag_name)\n\t\treturn Tag(tag_name.strip())",
    "docstring": "Make a Tag object from a tag name. Registers it with the content manager\n\t\tif possible."
  },
  {
    "code": "def _starts_with(field, filter_value):\n        valid = False\n        if field.startswith(filter_value):\n            valid = True\n        return valid",
    "docstring": "Validate field starts with provided value.\n\n        Args:\n            filter_value (string): A string or list of values.\n\n        Returns:\n            (boolean): Results of validation"
  },
  {
    "code": "def asmono(samples:np.ndarray, channel:Union[int, str]=0) -> np.ndarray:\n    if numchannels(samples) == 1:\n        if isinstance(samples[0], float):\n            return samples\n        elif isinstance(samples[0], np.dnarray):\n            return np.reshape(samples, (len(samples),))\n        else:\n            raise TypeError(\"Samples should be numeric, found: %s\"\n                            % str(type(samples[0])))\n    if isinstance(channel, int):\n        return samples[:, channel]\n    elif channel == 'mix':\n        return _mix(samples, scale_by_numchannels=True)\n    else:\n        raise ValueError(\"channel has to be an integer indicating a channel,\"\n                         \" or 'mix' to mix down all channels\")",
    "docstring": "convert samples to mono if they are not mono already.\n\n    The returned array will always have the shape (numframes,)\n\n    channel: the channel number to use, or 'mix' to mix-down\n             all channels"
  },
  {
    "code": "def create_indices(catalog_slug):\n        mapping = {\n            \"mappings\": {\n                \"layer\": {\n                    \"properties\": {\n                        \"layer_geoshape\": {\n                           \"type\": \"geo_shape\",\n                           \"tree\": \"quadtree\",\n                           \"precision\": REGISTRY_MAPPING_PRECISION\n                        }\n                    }\n                }\n            }\n        }\n        ESHypermap.es.indices.create(catalog_slug, ignore=[400, 404], body=mapping)",
    "docstring": "Create ES core indices"
  },
  {
    "code": "def make_connection(self):\n        \"Make a fresh connection.\"\n        connection = self.connection_class(**self.connection_kwargs)\n        self._connections.append(connection)\n        return connection",
    "docstring": "Make a fresh connection."
  },
  {
    "code": "def points_to_spline_entity(points, smooth=None, count=None):\n    from scipy.interpolate import splprep\n    if count is None:\n        count = len(points)\n    if smooth is None:\n        smooth = 0.002\n    points = np.asanyarray(points, dtype=np.float64)\n    closed = np.linalg.norm(points[0] - points[-1]) < tol.merge\n    knots, control, degree = splprep(points.T, s=smooth)[0]\n    control = np.transpose(control)\n    index = np.arange(len(control))\n    if closed:\n        control[0] = control[[0, -1]].mean(axis=0)\n        control = control[:-1]\n        index[-1] = index[0]\n    entity = entities.BSpline(points=index,\n                              knots=knots,\n                              closed=closed)\n    return entity, control",
    "docstring": "Create a spline entity from a curve in space\n\n    Parameters\n    -----------\n    points: (n, dimension) float, points in space\n    smooth: float, smoothing amount\n    count:  int, number of samples in result\n\n    Returns\n    ---------\n    entity: entities.BSpline object with points indexed at zero\n    control: (m, dimension) float, new vertices for entity"
  },
  {
    "code": "def process(obj):\n    merged = merge(obj)\n    if obj.get('full'):\n        print 'Saving: {} ({:.2f}kB)'.format(obj['full'], len(merged)/1024.0)\n        _save(obj['full'], merged)\n    else:\n        print 'Full merged size: {:.2f}kB'.format(len(merged)/1024.0)\n    if obj.get('jsmin'):\n        jsMin(merged, obj['jsmin'])\n    if obj.get('cssmin'):\n        cssMin(merged, obj['cssmin'])",
    "docstring": "Process each block of the merger object."
  },
  {
    "code": "def isreference(a):\n    return False\n    return id(a) != id(copy.copy(a))\n    check = ('__dict__', '__slots__')\n    for attr in check:\n        try:\n            getattr(a, attr)\n        except (SystemExit, KeyboardInterrupt):\n            raise\n        except:\n            pass\n        else:\n            return True\n    return False",
    "docstring": "Tell whether a variable is an object reference.\n\n    Due to garbage collection, some objects happen to get the id of a distinct variable.\n    As a consequence, linking is not ready yet and `isreference` returns ``False``."
  },
  {
    "code": "def STRUCT_DECL(self, cursor, num=None):\n        return self._record_decl(cursor, typedesc.Structure, num)",
    "docstring": "Handles Structure declaration.\n        Its a wrapper to _record_decl."
  },
  {
    "code": "def pca_overview(adata, **params):\n    show = params['show'] if 'show' in params else None\n    if 'show' in params: del params['show']\n    scatterplots.pca(adata, **params, show=False)\n    pca_loadings(adata, show=False)\n    pca_variance_ratio(adata, show=show)",
    "docstring": "\\\n    Plot PCA results.\n\n    The parameters are the ones of the scatter plot. Call pca_ranking separately\n    if you want to change the default settings.\n\n    Parameters\n    ----------\n    adata : :class:`~anndata.AnnData`\n        Annotated data matrix.\n    color : string or list of strings, optional (default: `None`)\n        Keys for observation/cell annotation either as list `[\"ann1\", \"ann2\"]` or\n        string `\"ann1,ann2,...\"`.\n    use_raw : `bool`, optional (default: `True`)\n        Use `raw` attribute of `adata` if present.\n    {scatter_bulk}\n    show : bool, optional (default: `None`)\n         Show the plot, do not return axis.\n    save : `bool` or `str`, optional (default: `None`)\n        If `True` or a `str`, save the figure. A string is appended to the\n        default filename. Infer the filetype if ending on {{'.pdf', '.png', '.svg'}}."
  },
  {
    "code": "def make_channel(name, samples, data=None, verbose=False):\n    if verbose:\n        llog = log['make_channel']\n        llog.info(\"creating channel {0}\".format(name))\n    chan = Channel('channel_{0}'.format(name))\n    chan.SetStatErrorConfig(0.05, \"Poisson\")\n    if data is not None:\n        if verbose:\n            llog.info(\"setting data\")\n        chan.SetData(data)\n    for sample in samples:\n        if verbose:\n            llog.info(\"adding sample {0}\".format(sample.GetName()))\n        chan.AddSample(sample)\n    return chan",
    "docstring": "Create a Channel from a list of Samples"
  },
  {
    "code": "def disqualified(self, num, natural=True, **kwargs):\n        search_type = 'natural' if natural else 'corporate'\n        baseuri = (self._BASE_URI +\n                   'disqualified-officers/{}/{}'.format(search_type, num))\n        res = self.session.get(baseuri, params=kwargs)\n        self.handle_http_error(res)\n        return res",
    "docstring": "Search for disqualified officers by officer ID.\n\n        Searches for natural disqualifications by default. Specify\n        natural=False to search for corporate disqualifications.\n\n        Args:\n           num (str): Company number to search on.\n           natural (Optional[bool]): Natural or corporate search\n           kwargs (dict): additional keywords passed into\n            requests.session.get *params* keyword."
  },
  {
    "code": "def get(self, item):\n        resource = super(CloudDatabaseManager, self).get(item)\n        resource.volume = CloudDatabaseVolume(resource, resource.volume)\n        return resource",
    "docstring": "This additional code is necessary to properly return the 'volume'\n        attribute of the instance as a CloudDatabaseVolume object instead of\n        a raw dict."
  },
  {
    "code": "def visit_class(rec, cls, op):\n    if isinstance(rec, MutableMapping):\n        if \"class\" in rec and rec.get(\"class\") in cls:\n            op(rec)\n        for d in rec:\n            visit_class(rec[d], cls, op)\n    if isinstance(rec, MutableSequence):\n        for d in rec:\n            visit_class(d, cls, op)",
    "docstring": "Apply a function to with \"class\" in cls."
  },
  {
    "code": "def bar(x, y, **kwargs):\n    kwargs['x'] = x\n    kwargs['y'] = y\n    return _draw_mark(Bars, **kwargs)",
    "docstring": "Draws a bar chart in the current context figure.\n\n    Parameters\n    ----------\n\n    x: numpy.ndarray, 1d\n        The x-coordinates of the data points.\n    y: numpy.ndarray, 1d\n        The y-coordinates of the data pints.\n    options: dict (default: {})\n        Options for the scales to be created. If a scale labeled 'x' is\n        required for that mark, options['x'] contains optional keyword\n        arguments for the constructor of the corresponding scale type.\n    axes_options: dict (default: {})\n        Options for the axes to be created. If an axis labeled 'x' is required\n        for that mark, axes_options['x'] contains optional keyword arguments\n        for the constructor of the corresponding axis type."
  },
  {
    "code": "def fix_return_value(v, method_name, method=None, checker=None):\n    method_name = (method_name or method.__func__.__name__).replace(\"check_\",\"\")\n    if v is None or not isinstance(v, Result):\n        v = Result(value=v, name=method_name)\n    v.name         = v.name or method_name\n    v.checker      = checker\n    v.check_method = method\n    return v",
    "docstring": "Transforms scalar return values into Result."
  },
  {
    "code": "def add_firmware_manifest(self, name, datafile, key_table_file=None, **kwargs):\n        kwargs.update({\n            'name': name,\n            'url': datafile,\n        })\n        if key_table_file is not None:\n            kwargs.update({'key_table_url': key_table_file})\n        firmware_manifest = FirmwareManifest._create_request_map(kwargs)\n        api = self._get_api(update_service.DefaultApi)\n        return FirmwareManifest(\n            api.firmware_manifest_create(**firmware_manifest)\n        )",
    "docstring": "Add a new manifest reference.\n\n        :param str name: Manifest file short name (Required)\n        :param str datafile: The file object or path to the manifest file (Required)\n        :param str key_table_file: The file object or path to the key_table file (Optional)\n        :param str description: Manifest file description\n        :return: the newly created manifest file object\n        :rtype: FirmwareManifest"
  },
  {
    "code": "def add_item(self, item):\n        self.items.append(item)\n        self.last_updated = datetime.datetime.now()",
    "docstring": "Append item to the list.\n\n        :attr:`last_updated` will be set to :py:meth:`datetime.datetime.now`.\n\n        :param item:\n            Something to append to :attr:`items`."
  },
  {
    "code": "def get_clients_per_page(self, per_page=1000, page=1, params=None):\n        return self._get_resource_per_page(resource=CLIENTS, per_page=per_page, page=page, params=params)",
    "docstring": "Get clients per page\n\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :param params: Search parameters. Default: {}\n        :return: list"
  },
  {
    "code": "def is_any_clicked(self):\n        for key in range(len(self.current_state.key_states)):\n            if self.is_clicked(key):\n                return True\n        return False",
    "docstring": "Is any button clicked?"
  },
  {
    "code": "def add_attribute_listener(self, attr_name, *args, **kwargs):\n        attr_name = attr_name.upper()\n        return super(Parameters, self).add_attribute_listener(attr_name, *args, **kwargs)",
    "docstring": "Add a listener callback on a particular parameter.\n\n        The callback can be removed using :py:func:`remove_attribute_listener`.\n\n        .. note::\n\n            The :py:func:`on_attribute` decorator performs the same operation as this method, but with\n            a more elegant syntax. Use ``add_attribute_listener`` only if you will need to remove\n            the observer.\n\n        The callback function is invoked only when the parameter changes.\n\n        The callback arguments are:\n\n        * ``self`` - the associated :py:class:`Parameters`.\n        * ``attr_name`` - the parameter name. This can be used to infer which parameter has triggered\n          if the same callback is used for watching multiple parameters.\n        * ``msg`` - the new parameter value (so you don't need to re-query the vehicle object).\n\n        The example below shows how to get callbacks for the ``THR_MIN`` parameter:\n\n        .. code:: python\n\n            #Callback function for the THR_MIN parameter\n            def thr_min_callback(self, attr_name, value):\n                print \" PARAMETER CALLBACK: %s changed to: %s\" % (attr_name, value)\n\n            #Add observer for the vehicle's THR_MIN parameter\n            vehicle.parameters.add_attribute_listener('THR_MIN', thr_min_callback)\n\n        See :ref:`vehicle_state_observing_parameters` for more information.\n\n        :param String attr_name: The name of the parameter to watch (or '*' to watch all parameters).\n        :param args: The callback to invoke when a change in the parameter is detected."
  },
  {
    "code": "def decamelise(text):\n    s = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', text)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s).lower()",
    "docstring": "Convert CamelCase to lower_and_underscore."
  },
  {
    "code": "def getpeercert(self, binary_form=False):\n        try:\n            peer_cert = _X509(SSL_get_peer_certificate(self._ssl.value))\n        except openssl_error():\n            return\n        if binary_form:\n            return i2d_X509(peer_cert.value)\n        if self._cert_reqs == CERT_NONE:\n            return {}\n        return decode_cert(peer_cert)",
    "docstring": "Retrieve the peer's certificate\n\n        When binary form is requested, the peer's DER-encoded certficate is\n        returned if it was transmitted during the handshake.\n\n        When binary form is not requested, and the peer's certificate has been\n        validated, then a certificate dictionary is returned. If the certificate\n        was not validated, an empty dictionary is returned.\n\n        In all cases, None is returned if no certificate was received from the\n        peer."
  },
  {
    "code": "def copy_doc(klass, fnname):\n    base_meth, base_func = __get_meth_func(klass.__base__, fnname)\n    meth, func = __get_meth_func(klass, fnname)\n    func.__doc__ = base_func.__doc__",
    "docstring": "Copies documentation string of a method from the super class into the\n    rewritten method of the given class"
  },
  {
    "code": "def print_timer(self, timer_name, **kwargs):\n        if hasattr(self, timer_name):\n            _delete_timer = kwargs.get(\"delete\", False)\n            print(\"|-------- {} [Time Log Calculation]-----------------|\".format(\\\n                    timer_name))\n            print(\"StartDiff\\tLastNodeDiff\\tNodeName\")\n            time_log = getattr(self, timer_name)\n            start_time = time_log[0]['time']\n            previous_time = start_time\n            for entry in time_log:\n                time_diff = (entry['time'] - previous_time) *1000\n                time_from_start = (entry['time'] - start_time) * 1000\n                previous_time = entry['time']\n                print(\"{:.1f}\\t\\t{:.1f}\\t\\t{}\".format(time_from_start,\n                                                      time_diff,\n                                                      entry['node']))\n            print(\"|--------------------------------------------------------|\")\n            if _delete_timer:\n                self.delete_timer(timer_name)",
    "docstring": "prints the timer to the terminal\n\n            keyword args:\n                delete -> True/False  -deletes the timer after printing"
  },
  {
    "code": "def newText(content):\n    ret = libxml2mod.xmlNewText(content)\n    if ret is None:raise treeError('xmlNewText() failed')\n    return xmlNode(_obj=ret)",
    "docstring": "Creation of a new text node."
  },
  {
    "code": "def activity(self, *args, **kwargs):\n        _activities = self.activities(*args, **kwargs)\n        if len(_activities) == 0:\n            raise NotFoundError(\"No activity fits criteria\")\n        if len(_activities) != 1:\n            raise MultipleFoundError(\"Multiple activities fit criteria\")\n        return _activities[0]",
    "docstring": "Search for a single activity.\n\n        If additional `keyword=value` arguments are provided, these are added to the request parameters. Please\n        refer to the documentation of the KE-chain API for additional query parameters.\n\n        :param pk: id (primary key) of the activity to retrieve\n        :type pk: basestring or None\n        :param name: filter the activities by name\n        :type name: basestring or None\n        :param scope: filter by scope id\n        :type scope: basestring or None\n        :return: a single :class:`models.Activity`\n        :raises NotFoundError: When no `Activity` is found\n        :raises MultipleFoundError: When more than a single `Activity` is found"
  },
  {
    "code": "def get_coiledcoil_region(self, cc_number=0, cutoff=7.0, min_kihs=2):\n        g = self.filter_graph(self.graph, cutoff=cutoff, min_kihs=min_kihs)\n        ccs = sorted(networkx.connected_component_subgraphs(g, copy=True),\n                                 key=lambda x: len(x.nodes()), reverse=True)\n        cc = ccs[cc_number]\n        helices = [x for x in g.nodes() if x.number in cc.nodes()]\n        assigned_regions = self.get_assigned_regions(helices=helices, include_alt_states=False, complementary_only=True)\n        coiledcoil_monomers = [h.get_slice_from_res_id(*assigned_regions[h.number]) for h in helices]\n        return Assembly(coiledcoil_monomers)",
    "docstring": "Assembly containing only assigned regions (i.e. regions with contiguous KnobsIntoHoles."
  },
  {
    "code": "def generate_thumbnail_download_link_vimeo(video_id_from_shortcode):\n\tvideo_metadata = urlopen(\"https://vimeo.com/api/v2/video/\" + str(video_id_from_shortcode) + \".json\").read()\n\tvideo_metadata_parsed = json.loads(video_metadata.decode('utf-8'))\n\tvideo_thumbnail_large_location = video_metadata_parsed[0]['thumbnail_large']\n\treturn video_thumbnail_large_location",
    "docstring": "Thumbnail URL generator for Vimeo videos."
  },
  {
    "code": "def _delete_membership(self, pipeline=None):\n        Set(self._key['all'], pipeline=pipeline).remove(self.id)",
    "docstring": "Removes the id of the object to the set of all objects of the\n        same class."
  },
  {
    "code": "def identity(self):\n        res = self.app.get_id()\n        res.update({\"start_time\": self.start_time})\n        res.update({\"running_id\": self.running_id})\n        return res",
    "docstring": "Get the daemon identity\n\n        This will return an object containing some properties:\n        - alignak: the Alignak instance name\n        - version: the Alignak version\n        - type: the daemon type\n        - name: the daemon name\n\n        :return: daemon identity\n        :rtype: dict"
  },
  {
    "code": "def close_open_fds(keep_files=[]):\n    keep_fds = set()\n    for file in keep_files:\n        if isinstance(file, int):\n            keep_fds.add(file)\n        else:\n            try:\n                keep_fds.add(file.fileno())\n            except Exception:\n                pass\n    for fd in os.listdir(\"/proc/self/fd\"):\n        fd = int(fd)\n        if fd not in keep_fds:\n            try:\n                os.close(fd)\n            except OSError:\n                pass",
    "docstring": "Close all open file descriptors except those in a given set.\n    @param keep_files: an iterable of file descriptors or file-like objects."
  },
  {
    "code": "def draw360_to_texture(self, cubetexture, **kwargs):\n        assert self.camera.projection.aspect == 1. and self.camera.projection.fov_y == 90\n        if not isinstance(cubetexture, TextureCube):\n            raise ValueError(\"Must render to TextureCube\")\n        old_rotation = self.camera.rotation\n        self.camera.rotation = self.camera.rotation.to_euler(units='deg')\n        for face, rotation in enumerate([[180, -90, 0], [180, 90, 0], [90, 0, 0], [-90, 0, 0], [180, 0, 0], [0, 0, 180]]):\n            self.camera.rotation.xyz = rotation\n            cubetexture.attach_to_fbo(face)\n            self.draw(**kwargs)\n        self.camera.rotation = old_rotation",
    "docstring": "Draw each visible mesh in the scene from the perspective of the scene's camera and lit by its light, and\n        applies it to each face of cubetexture, which should be currently bound to an FBO."
  },
  {
    "code": "def setConfigKey(key, value):\n\t\tconfigFile = ConfigurationManager._configFile()\n\t\treturn JsonDataManager(configFile).setKey(key, value)",
    "docstring": "Sets the config data value for the specified dictionary key"
  },
  {
    "code": "def git_commit(targets, message, force=False, sign=False):\n    root = get_root()\n    target_paths = []\n    for t in targets:\n        target_paths.append(os.path.join(root, t))\n    with chdir(root):\n        result = run_command('git add{} {}'.format(' -f' if force else '', ' '.join(target_paths)))\n        if result.code != 0:\n            return result\n        return run_command('git commit{} -m \"{}\"'.format(' -S' if sign else '', message))",
    "docstring": "Commit the changes for the given targets."
  },
  {
    "code": "def V_(x, requires_grad=False, volatile=False):\n    return create_variable(x, volatile=volatile, requires_grad=requires_grad)",
    "docstring": "equivalent to create_variable, which creates a pytorch tensor"
  },
  {
    "code": "def delayed_redraw(self):\n        with self._defer_lock:\n            whence = self._defer_whence\n            self._defer_whence = self._defer_whence_reset\n            flag = self._defer_flag\n            self._defer_flag = False\n        if flag:\n            self.redraw_now(whence=whence)",
    "docstring": "Handle delayed redrawing of the canvas."
  },
  {
    "code": "def mainloop(self):\n        while self.keep_going:\n            with self.lock:\n                if self.on_connect and not self.readable(2):\n                    self.on_connect()\n                    self.on_connect = None\n                if not self.keep_going:\n                    break\n                self.process_once()",
    "docstring": "Handles events and calls their handler for infinity."
  },
  {
    "code": "def is_extension_supported(request, extension_alias):\n    extensions = list_extensions(request)\n    for extension in extensions:\n        if extension['alias'] == extension_alias:\n            return True\n    else:\n        return False",
    "docstring": "Check if a specified extension is supported.\n\n    :param request: django request object\n    :param extension_alias: neutron extension alias"
  },
  {
    "code": "def __get_value(self, field_name):\r\n        value = request.values.get(field_name)\r\n        if value is None:\r\n            if self.json_form_data is None:\r\n                value = None\r\n            elif field_name in self.json_form_data:\r\n                value = self.json_form_data[field_name]\r\n        return value",
    "docstring": "Get request Json value by field name"
  },
  {
    "code": "def get_certificates(self):\n        for certificate in self.user_data.certificates:\n            certificate['datetime'] = certificate['datetime'].strip()\n        return self.user_data.certificates",
    "docstring": "Get user's certificates."
  },
  {
    "code": "def create(cls, receiver_id, user_id=None):\n        event = cls(id=uuid.uuid4(), receiver_id=receiver_id, user_id=user_id)\n        event.payload = event.receiver.extract_payload()\n        return event",
    "docstring": "Create an event instance."
  },
  {
    "code": "def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_list):\n    cand_indices = []\n    for (i, token) in enumerate(tokens):\n        if token == \"[CLS]\" or token == \"[SEP]\":\n            continue\n        cand_indices.append(i)\n    num_to_mask = min(max_predictions_per_seq,\n                      max(1, int(round(len(tokens) * masked_lm_prob))))\n    shuffle(cand_indices)\n    mask_indices = sorted(sample(cand_indices, num_to_mask))\n    masked_token_labels = []\n    for index in mask_indices:\n        if random() < 0.8:\n            masked_token = \"[MASK]\"\n        else:\n            if random() < 0.5:\n                masked_token = tokens[index]\n            else:\n                masked_token = choice(vocab_list)\n        masked_token_labels.append(tokens[index])\n        tokens[index] = masked_token\n    return tokens, mask_indices, masked_token_labels",
    "docstring": "Creates the predictions for the masked LM objective. This is mostly copied from the Google BERT repo, but\n    with several refactors to clean it up and remove a lot of unnecessary variables."
  },
  {
    "code": "def from_tuple(self, t):\n        if len(t) > 1:\n            self.id = t[0]\n            self.sitting = t[1]\n        else:\n            self.sitting = t[0]\n            self.id = None\n        return self",
    "docstring": "Set this person from tuple\n\n        :param t: Tuple representing a person (sitting[, id])\n        :type t: (bool) | (bool, None | str | unicode | int)\n        :rtype: Person"
  },
  {
    "code": "def undisplay(self):\n        self._tools.pop()\n        self._justClear()\n        for tool in self._tools:\n            self._justDisplay(tool)",
    "docstring": "Undisplays the top tool.\n\n        This actually forces a complete re-render."
  },
  {
    "code": "def get_structure_by_material_id(self, material_id, final=True,\n                                     conventional_unit_cell=False):\n        prop = \"final_structure\" if final else \"initial_structure\"\n        data = self.get_data(material_id, prop=prop)\n        if conventional_unit_cell:\n            data[0][prop] = SpacegroupAnalyzer(data[0][prop]). \\\n                get_conventional_standard_structure()\n        return data[0][prop]",
    "docstring": "Get a Structure corresponding to a material_id.\n\n        Args:\n            material_id (str): Materials Project material_id (a string,\n                e.g., mp-1234).\n            final (bool): Whether to get the final structure, or the initial\n                (pre-relaxation) structure. Defaults to True.\n            conventional_unit_cell (bool): Whether to get the standard\n                conventional unit cell\n\n        Returns:\n            Structure object."
  },
  {
    "code": "def is_predecessor_of_other(self, predecessor, others):\n        return any(predecessor in self._predecessors_by_id[o] for o in others)",
    "docstring": "Returns whether the predecessor is a predecessor or a predecessor\n        of a predecessor...of any of the others.\n\n        Args:\n            predecessor (str): The txn id of the predecessor.\n            others (list(str)): The txn id of the successor.\n\n        Returns:\n            (bool)"
  },
  {
    "code": "def write_strings_on_files_between_markers(filenames: list, strings: list,\n                                           marker: str):\n    r\n    assert len(filenames) == len(strings)\n    if len(filenames) > 0:\n        for f in filenames:\n            assert isinstance(f, str)\n    if len(strings) > 0:\n        for s in strings:\n            assert isinstance(s, str)\n    file_id = 0\n    for f in filenames:\n        write_string_on_file_between_markers(f, strings[file_id], marker)\n        file_id += 1",
    "docstring": "r\"\"\"Write the table of contents on multiple files.\n\n    :parameter filenames: the files that needs to be read or modified.\n    :parameter strings: the strings that will be written on the file. Each\n         string is associated with one file.\n    :parameter marker: a marker that will identify the start\n         and the end of the string.\n    :type filenames: list\n    :type string: list\n    :type marker: str\n    :returns: None\n    :rtype: None\n    :raises: an fpyutils exception or a built-in exception."
  },
  {
    "code": "def TypeFactory(type_):\n    if isinstance(type_, type) and issubclass(type_, Type):\n        return type_\n    for x in __types__:\n        if x.represents(type_):\n            return x.get(type_)\n    raise UnknownType(type_)",
    "docstring": "This function creates a standard form type from a simplified form.\n\n    >>> from datetime import date, datetime\n    >>> from pyws.functions.args import TypeFactory\n    >>> from pyws.functions.args import String, Integer, Float, Date, DateTime\n    >>> TypeFactory(str) == String\n    True\n    >>> TypeFactory(float) == Float\n    True\n    >>> TypeFactory(date) == Date\n    True\n    >>> TypeFactory(datetime) == DateTime\n    True\n\n    >>> from operator import attrgetter\n    >>> from pyws.functions.args import Dict\n    >>> dct = TypeFactory({0: 'HelloWorldDict', 'hello': str, 'world': int})\n    >>> issubclass(dct, Dict)\n    True\n    >>> dct.__name__\n    'HelloWorldDict'\n    >>> fields = sorted(dct.fields, key=attrgetter('name'))\n    >>> len(dct.fields)\n    2\n    >>> fields[0].name == 'hello'\n    True\n    >>> fields[0].type == String\n    True\n    >>> fields[1].name == 'world'\n    True\n    >>> fields[1].type == Integer\n    True\n\n    >>> from pyws.functions.args import List\n    >>> lst = TypeFactory([int])\n    >>> issubclass(lst, List)\n    True\n    >>> lst.__name__\n    'IntegerList'\n    >>> lst.element_type == Integer\n    True"
  },
  {
    "code": "def _viscounts2radiance(counts, slope, offset):\n        rad = counts * slope + offset\n        return rad.clip(min=0)",
    "docstring": "Convert VIS counts to radiance\n\n        References: [VIS]\n\n        Args:\n            counts: Raw detector counts\n            slope: Slope [W m-2 um-1 sr-1]\n            offset: Offset [W m-2 um-1 sr-1]\n        Returns:\n            Radiance [W m-2 um-1 sr-1]"
  },
  {
    "code": "def documents(cls, filter=None, **kwargs):\n        documents = [cls(document) for document in cls.find(filter, **kwargs)]\n        return [document for document in documents if document.document]",
    "docstring": "Returns a list of Documents if any document is filtered"
  },
  {
    "code": "def make_input_from_plain_string(sentence_id: SentenceId, string: str) -> TranslatorInput:\n    return TranslatorInput(sentence_id, tokens=list(data_io.get_tokens(string)), factors=None)",
    "docstring": "Returns a TranslatorInput object from a plain string.\n\n    :param sentence_id: Sentence id.\n    :param string: An input string.\n    :return: A TranslatorInput."
  },
  {
    "code": "def write_to(self, content, content_type):\n    try:\n      self._api.object_upload(self._bucket, self._key, content, content_type)\n    except Exception as e:\n      raise e",
    "docstring": "Writes text content to this item.\n\n    Args:\n      content: the text content to be written.\n      content_type: the type of text content.\n    Raises:\n      Exception if there was an error requesting the item's content."
  },
  {
    "code": "def likelihood_markov_blanket(self, beta):\n        states = beta[self.z_no:self.z_no+self.data_length]\n        parm = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k in range(self.z_no)])\n        scale, shape, skewness = self._get_scale_and_shape(parm)\n        return self.family.markov_blanket(self.data, self.link(states), scale, shape, skewness)",
    "docstring": "Creates likelihood markov blanket of the model\n\n        Parameters\n        ----------\n        beta : np.array\n            Contains untransformed starting values for latent variables\n\n        Returns\n        ----------\n        - Negative loglikelihood"
  },
  {
    "code": "def get_ips(self, interface=None, family=None, scope=None, timeout=0):\n        kwargs = {}\n        if interface:\n            kwargs['interface'] = interface\n        if family:\n            kwargs['family'] = family\n        if scope:\n            kwargs['scope'] = scope\n        ips = None\n        timeout = int(os.environ.get('LXC_GETIP_TIMEOUT', timeout))\n        while not ips:\n            ips = _lxc.Container.get_ips(self, **kwargs)\n            if timeout == 0:\n                break\n            timeout -= 1\n            time.sleep(1)\n        return ips",
    "docstring": "Get a tuple of IPs for the container."
  },
  {
    "code": "def list_uplink_dvportgroup(dvs, service_instance=None):\n    proxy_type = get_proxy_type()\n    if proxy_type == 'esxdatacenter':\n        datacenter = __salt__['esxdatacenter.get_details']()['datacenter']\n        dc_ref = _get_proxy_target(service_instance)\n    elif proxy_type == 'esxcluster':\n        datacenter = __salt__['esxcluster.get_details']()['datacenter']\n        dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)\n    dvs_refs = salt.utils.vmware.get_dvss(dc_ref, dvs_names=[dvs])\n    if not dvs_refs:\n        raise VMwareObjectRetrievalError('DVS \\'{0}\\' was not '\n                                         'retrieved'.format(dvs))\n    uplink_pg_ref = salt.utils.vmware.get_uplink_dvportgroup(dvs_refs[0])\n    return _get_dvportgroup_dict(uplink_pg_ref)",
    "docstring": "Returns the uplink portgroup of a distributed virtual switch.\n\n    dvs\n        Name of the DVS containing the portgroup.\n\n    service_instance\n        Service instance (vim.ServiceInstance) of the vCenter.\n        Default is None.\n\n    .. code-block:: bash\n\n        salt '*' vsphere.list_uplink_dvportgroup dvs=dvs_name"
  },
  {
    "code": "def write(self, file, text, subvars={}, trim_leading_lf=True):\n        file.write(self.substitute(text, subvars=subvars, trim_leading_lf=trim_leading_lf))",
    "docstring": "write to a file with variable substitution"
  },
  {
    "code": "def get_attribute(self, code, default=None):\n        try:\n            return self.get(code=code).value\n        except models.ObjectDoesNotExist:\n            return default",
    "docstring": "Get attribute for user"
  },
  {
    "code": "def simplify(self, e=None):\n        if e is None:\n            return self._solver.simplify()\n        elif isinstance(e, (int, float, bool)):\n            return e\n        elif isinstance(e, claripy.ast.Base) and e.op in claripy.operations.leaf_operations_concrete:\n            return e\n        elif isinstance(e, SimActionObject) and e.op in claripy.operations.leaf_operations_concrete:\n            return e.ast\n        elif not isinstance(e, (SimActionObject, claripy.ast.Base)):\n            return e\n        else:\n            return self._claripy_simplify(e)",
    "docstring": "Simplifies `e`. If `e` is None, simplifies the constraints of this\n        state."
  },
  {
    "code": "def get_area(self):\n        return (self.p2.x-self.p1.x)*(self.p2.y-self.p1.y)",
    "docstring": "Calculate area of bounding box."
  },
  {
    "code": "def checkQueryRange(self, start, end):\n        condition = (\n            (start < 0 or end > self.getLength()) or\n            start > end or start == end)\n        if condition:\n            raise exceptions.ReferenceRangeErrorException(\n                self.getId(), start, end)",
    "docstring": "Checks to ensure that the query range is valid within this reference.\n        If not, raise ReferenceRangeErrorException."
  },
  {
    "code": "def rm(ctx, dataset, kwargs):\n    \"removes the dataset's folder if it exists\"\n    kwargs = parse_kwargs(kwargs)\n    data(dataset, **ctx.obj).rm(**kwargs)",
    "docstring": "removes the dataset's folder if it exists"
  },
  {
    "code": "def pause(ctx):\n    lancet = ctx.obj\n    paused_status = lancet.config.get(\"tracker\", \"paused_status\")\n    issue = get_issue(lancet)\n    transition = get_transition(ctx, lancet, issue, paused_status)\n    set_issue_status(lancet, issue, paused_status, transition)\n    with taskstatus(\"Pausing harvest timer\") as ts:\n        lancet.timer.pause()\n        ts.ok(\"Harvest timer paused\")",
    "docstring": "Pause work on the current issue.\n\n    This command puts the issue in the configured paused status and stops the\n    current Harvest timer."
  },
  {
    "code": "def print_tree(graph, tails, node_id_map):\n    walker = graph.walk()\n    next_block_num, next_parent, next_siblings = next(walker)\n    prev_cliques = []\n    done = False\n    while not done:\n        cliques = {}\n        block_num = next_block_num\n        try:\n            while block_num == next_block_num:\n                cliques[next_parent] = next_siblings\n                next_block_num, next_parent, next_siblings = next(walker)\n        except StopIteration:\n            done = True\n        print_cliques(prev_cliques, cliques, node_id_map)\n        print_block_num_row(block_num, prev_cliques, cliques)\n        print_splits(prev_cliques, cliques)\n        print_folds(prev_cliques, cliques)\n        prev_cliques = build_ordered_cliques(prev_cliques, cliques)\n    print_cliques(prev_cliques, [], node_id_map)",
    "docstring": "Print out a tree of blocks starting from the common ancestor."
  },
  {
    "code": "def get_repository(self, path):\n        parts = path.split('@', 1)\n        if len(parts) == 1:\n            parts = (\"filesystem\", parts[0])\n        repo_type, location = parts\n        if repo_type == \"filesystem\":\n            location = os.path.abspath(location)\n        normalised_path = \"%s@%s\" % (repo_type, location)\n        return self._get_repository(normalised_path)",
    "docstring": "Get a package repository.\n\n        Args:\n            path (str): Entry from the 'packages_path' config setting. This may\n                simply be a path (which is managed by the 'filesystem' package\n                repository plugin), or a string in the form \"type@location\",\n                where 'type' identifies the repository plugin type to use.\n\n        Returns:\n            `PackageRepository` instance."
  },
  {
    "code": "def qnh_estimate(self):\n        alt_gps = self.master.field('GPS_RAW_INT', 'alt', 0) * 0.001\n        pressure2 = self.master.field('SCALED_PRESSURE', 'press_abs', 0)\n        ground_temp = self.get_mav_param('GND_TEMP', 21)\n        temp = ground_temp + 273.15\n        pressure1 = pressure2 / math.exp(math.log(1.0 - (alt_gps / (153.8462 * temp))) / 0.190259)\n        return pressure1",
    "docstring": "estimate QNH pressure from GPS altitude and scaled pressure"
  },
  {
    "code": "def post_tweet_intent_handler(request):\n    tweet = request.get_slot_value(\"Tweet\")\n    tweet = tweet if tweet else \"\"    \n    if tweet:\n        user_state = twitter_cache.get_user_state(request.access_token())\n        def action():\n            return post_tweet(request.access_token(), tweet)\n        message = \"I am ready to post the tweet, {} ,\\n Please say yes to confirm or stop to cancel .\".format(tweet)\n        user_state['pending_action'] = {\"action\" : action,\n                                        \"description\" : message} \n        return r.create_response(message=message, end_session=False)\n    else:\n        message = \" \".join(\n            [\n                \"I'm sorry, I couldn't understand what you wanted to tweet .\",\n                \"Please prepend the message with either post or tweet .\"\n            ]\n        )\n        return alexa.create_response(message=message, end_session=False)",
    "docstring": "Use the 'intent' field in the VoiceHandler to map to the respective intent."
  },
  {
    "code": "def mark_locations(h,section,locs,markspec='or',**kwargs):\n    xyz = get_section_path(h,section)\n    (r,theta,phi) = sequential_spherical(xyz)\n    rcum = np.append(0,np.cumsum(r))\n    if type(locs) is float or type(locs) is np.float64:\n        locs = np.array([locs])\n    if type(locs) is list:\n        locs = np.array(locs)\n    lengths = locs*rcum[-1]\n    xyz_marks = []\n    for targ_length in lengths:\n        xyz_marks.append(find_coord(targ_length,xyz,rcum,theta,phi))\n    xyz_marks = np.array(xyz_marks)\n    line, = plt.plot(xyz_marks[:,0], xyz_marks[:,1], \\\n                     xyz_marks[:,2], markspec, **kwargs)\n    return line",
    "docstring": "Marks one or more locations on along a section. Could be used to\n    mark the location of a recording or electrical stimulation.\n\n    Args:\n        h = hocObject to interface with neuron\n        section = reference to section\n        locs = float between 0 and 1, or array of floats\n        optional arguments specify details of marker\n\n    Returns:\n        line = reference to plotted markers"
  },
  {
    "code": "def reset(self):\n        old_value = self._value\n        old_raw_str_value = self.raw_str_value\n        self._value = not_set\n        self.raw_str_value = not_set\n        new_value = self._value\n        if old_value is not_set:\n            return\n        if self.section:\n            self.section.dispatch_event(\n                self.section.hooks.item_value_changed,\n                item=self,\n                old_value=old_value,\n                new_value=new_value,\n                old_raw_str_value=old_raw_str_value,\n                new_raw_str_value=self.raw_str_value,\n            )",
    "docstring": "Resets the value of config item to its default value."
  },
  {
    "code": "def yaml_dump(dict_to_dump):\n    yaml.SafeDumper.add_representer(OrderedDict, _dict_representer)\n    return yaml.safe_dump(dict_to_dump, default_flow_style=False)",
    "docstring": "Dump the dictionary as a YAML document.\n\n    :param dict_to_dump: Data to be serialized as YAML\n    :type dict_to_dump: dict\n    :return: YAML document\n    :rtype: str"
  },
  {
    "code": "def links(self):\n        links = Links()\n        links[\"self\"] = Link.for_(\n            self._operation,\n            self._ns,\n            qs=self._page.to_items(),\n            **self._context\n        )\n        return links",
    "docstring": "Include a self link."
  },
  {
    "code": "def determine_labels(target_dir: Path, label_type: str) -> Set[str]:\n    logger.info(\"Finding phonemes of type %s in directory %s\", label_type, target_dir)\n    label_dir = target_dir / \"label/\"\n    if not label_dir.is_dir():\n        raise FileNotFoundError(\n            \"The directory {} does not exist.\".format(target_dir))\n    phonemes = set()\n    for fn in os.listdir(str(label_dir)):\n        if fn.endswith(str(label_type)):\n            with (label_dir / fn).open(\"r\", encoding=ENCODING) as f:\n                try:\n                    line_phonemes = set(f.readline().split())\n                except UnicodeDecodeError:\n                    logger.error(\"Unicode decode error on file %s\", fn)\n                    print(\"Unicode decode error on file {}\".format(fn))\n                    raise\n                phonemes = phonemes.union(line_phonemes)\n    return phonemes",
    "docstring": "Returns a set of all phonemes found in the corpus. Assumes that WAV files and\n    label files are split into utterances and segregated in a directory which contains a\n    \"wav\" subdirectory and \"label\" subdirectory.\n\n    Arguments:\n        target_dir: A `Path` to the directory where the corpus data is found\n        label_type: The type of label we are creating the label set from. For example\n                    \"phonemes\" would only search for labels for that type."
  },
  {
    "code": "def perform(self):\n        if self.use_https:\n            conn = client.HTTPSConnection(self.host, self.port)\n        else:\n            conn = client.HTTPConnection(self.host, self.port)\n        conn.request(self.method, self.uri)\n        response = conn.getresponse()\n        conn.close()\n        return bool(response.status >= 200 and response.status < 300)",
    "docstring": "Performs a simple HTTP request against the configured url and returns\n        true if the response has a 2xx code.\n\n        The url can be configured to use https via the \"https\" boolean flag\n        in the config, as well as a custom HTTP method via the \"method\" key.\n\n        The default is to not use https and the GET method."
  },
  {
    "code": "def load(self, table: str):\n        if self._check_db() is False:\n            return\n        if table not in self.db.tables:\n            self.warning(\"The table \" + table + \" does not exists\")\n            return\n        try:\n            self.start(\"Loading data from table \" + table)\n            res = self.db[table].all()\n            self.df = pd.DataFrame(list(res))\n            self.end(\"Data loaded from table \" + table)\n        except Exception as e:\n            self.err(e, \"Can not load table \" + table)",
    "docstring": "Set the main dataframe from a table's data\n\n        :param table: table name\n        :type table: str\n\n        :example: ``ds.load(\"mytable\")``"
  },
  {
    "code": "def execute(self, method, **kwargs):\n        payload = {\n            'id': 1,\n            'jsonrpc': '2.0',\n            'method': method,\n            'params': kwargs\n        }\n        credentials = base64.b64encode('{}:{}'.format(self._username, self._password).encode())\n        auth_header_prefix = 'Basic ' if self._auth_header == DEFAULT_AUTH_HEADER else ''\n        headers = {\n            self._auth_header: auth_header_prefix + credentials.decode(),\n            'Content-Type': 'application/json',\n        }\n        return self._do_request(headers, payload)",
    "docstring": "Call remote API procedure\n\n        Args:\n            method: Procedure name\n            kwargs: Procedure named arguments\n\n        Returns:\n            Procedure result\n\n        Raises:\n            urllib2.HTTPError: Any HTTP error (Python 2)\n            urllib.error.HTTPError: Any HTTP error (Python 3)"
  },
  {
    "code": "def UCRTLibraries(self):\n        if self.vc_ver < 14.0:\n            return []\n        arch_subdir = self.pi.target_dir(x64=True)\n        lib = os.path.join(self.si.UniversalCRTSdkDir, 'lib')\n        ucrtver = self._ucrt_subdir\n        return [os.path.join(lib, '%sucrt%s' % (ucrtver, arch_subdir))]",
    "docstring": "Microsoft Universal C Runtime SDK Libraries"
  },
  {
    "code": "def __open_pidfile(self, write=False):\n        try:\n            self.pre_log.append((\"DEBUG\",\n                                 \"Opening %s pid file: %s\" % ('existing' if\n                                                              os.path.exists(self.pid_filename)\n                                                              else 'missing', self.pid_filename)))\n            if not write and os.path.exists(self.pid_filename):\n                self.fpid = open(self.pid_filename, 'r+')\n            else:\n                self.fpid = open(self.pid_filename, 'w+')\n        except Exception as exp:\n            self.exit_on_error(\"Error opening pid file: %s. Error: %s. \"\n                               \"Check the %s:%s account permissions to write this file.\"\n                               % (self.pid_filename, str(exp), self.user, self.group), exit_code=3)",
    "docstring": "Open pid file in read or write mod\n\n        :param write: boolean to open file in write mod (true = write)\n        :type write: bool\n        :return: None"
  },
  {
    "code": "def get(self, time, interpolate='previous'):\n        try:\n            getter = self.getter_functions[interpolate]\n        except KeyError:\n            msg = (\n                \"unknown value '{}' for interpolate, \"\n                \"valid values are in [{}]\"\n            ).format(interpolate, ', '.join(self.getter_functions))\n            raise ValueError(msg)\n        else:\n            return getter(time)",
    "docstring": "Get the value of the time series, even in-between measured values."
  },
  {
    "code": "def inspect_commit(self, commit):\n        req = proto.InspectCommitRequest(commit=commit_from(commit))\n        return self.stub.InspectCommit(req, metadata=self.metadata)",
    "docstring": "Returns info about a specific Commit.\n\n        Params:\n        * commit: A tuple, string, or Commit object representing the commit."
  },
  {
    "code": "def get_progressbar(self, total, **options):\n        progressbar = ColoredProgressBar(total)\n        progressbar.steps_label = 'Commit'\n        progressbar.elements += ['eta', 'time']\n        return progressbar",
    "docstring": "Returns progress bar instance for a given ``total`` number of clicks\n        it should do."
  },
  {
    "code": "def dpu(self, hash=None, historics_id=None):\n        if hash:\n            return self.request.get('dpu', params=dict(hash=hash))\n        if historics_id:\n            return self.request.get('dpu', params=dict(historics_id=historics_id))",
    "docstring": "Calculate the DPU cost of consuming a stream.\n\n            Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/dpu\n\n            :param hash: target CSDL filter hash\n            :type hash: str\n            :returns: dict with extra response data\n            :rtype: :class:`~datasift.request.DictResponse`\n            :raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`"
  },
  {
    "code": "def blog_reverse(viewname, args=None, kwargs=None, current_app='fluent_blogs', **page_kwargs):\n    return mixed_reverse(viewname, args=args, kwargs=kwargs, current_app=current_app, **page_kwargs)",
    "docstring": "Reverse a URL to the blog, taking various configuration options into account.\n\n    This is a compatibility function to allow django-fluent-blogs to operate stand-alone.\n    Either the app can be hooked in the URLconf directly, or it can be added as a pagetype of *django-fluent-pages*."
  },
  {
    "code": "def dict_to_op(d, index_name, doc_type, op_type='index'):\n    if d is None:\n        return d\n    op_types = ('create', 'delete', 'index', 'update')\n    if op_type not in op_types:\n        msg = 'Unknown operation type \"{}\", must be one of: {}'\n        raise Exception(msg.format(op_type, ', '.join(op_types)))\n    if 'id' not in d:\n        raise Exception('\"id\" key not found')\n    operation = {\n        '_op_type': op_type,\n        '_index': index_name,\n        '_type': doc_type,\n        '_id': d.pop('id'),\n    }\n    operation.update(d)\n    return operation",
    "docstring": "Create a bulk-indexing operation from the given dictionary."
  },
  {
    "code": "def get_complex_attrs(self):\n        return [getattr(self, attr_name) for attr_name in self._attributes if\n                isinstance(getattr(self, attr_name), ComplexSchemaItem)]",
    "docstring": "Returns a dictionary of the complex attributes"
  },
  {
    "code": "def format_sensor(self, sensor):\n        current_val = sensor.current\n        if self.pango_enabled:\n            percentage = self.percentage(sensor.current, sensor.critical)\n            if self.dynamic_color:\n                color = self.colors[int(percentage)]\n                return self.format_pango(color, current_val)\n        return current_val",
    "docstring": "Format a sensor value. If pango is enabled color is per sensor."
  },
  {
    "code": "def latexify(obj, **kwargs):\n    if hasattr(obj, '__pk_latex__'):\n        return obj.__pk_latex__(**kwargs)\n    if isinstance(obj, text_type):\n        from .unicode_to_latex import unicode_to_latex\n        return unicode_to_latex(obj)\n    if isinstance(obj, bool):\n        raise ValueError('no well-defined LaTeXification of bool %r' % obj)\n    if isinstance(obj, float):\n        nplaces = kwargs.get('nplaces')\n        if nplaces is None:\n            return '$%f$' % obj\n        return '$%.*f$' % (nplaces, obj)\n    if isinstance(obj, int):\n        return '$%d$' % obj\n    if isinstance(obj, binary_type):\n        if all(c in _printable_ascii for c in obj):\n            return obj.decode('ascii')\n        raise ValueError('no safe LaTeXification of binary string %r' % obj)\n    raise ValueError('can\\'t LaTeXify %r' % obj)",
    "docstring": "Render an object in LaTeX appropriately."
  },
  {
    "code": "def getcells(self, line):\n        for boundary in self.boundaries:\n            cell = line.lstrip()[boundary].strip()\n            if cell:\n                for cell in re.split('\\s{3,}', cell):\n                    yield cell\n            else:\n                yield None",
    "docstring": "Using self.boundaries, extract cells from the given line."
  },
  {
    "code": "def get_vasp_kpoint_file_sym(structure):\n    output = run_aconvasp_command([\"aconvasp\", \"--kpath\"], structure)\n    if \"ERROR\" in output[1]:\n        raise AconvaspError(output[1])\n    started = False\n    kpoints_string = \"\"\n    for line in output[0].split(\"\\n\"):\n        if started or line.find(\"END\") != -1:\n            kpoints_string = kpoints_string + line + \"\\n\"\n        if line.find(\"KPOINTS TO RUN\") != -1:\n            started = True\n        if line.find(\"END\") != -1:\n            started = False\n    return kpoints_string",
    "docstring": "get a kpoint file ready to be ran in VASP along the symmetry lines of the\n    Brillouin Zone"
  },
  {
    "code": "def apply_cut(self, cut):\n        return MacroSubsystem(\n            self.network,\n            self.network_state,\n            self.micro_node_indices,\n            cut=cut,\n            time_scale=self.time_scale,\n            blackbox=self.blackbox,\n            coarse_grain=self.coarse_grain)",
    "docstring": "Return a cut version of this |MacroSubsystem|.\n\n        Args:\n            cut (Cut): The cut to apply to this |MacroSubsystem|.\n\n        Returns:\n            MacroSubsystem: The cut version of this |MacroSubsystem|."
  },
  {
    "code": "def _get_pid_file_variable(self, db):\n        pid_file = None\n        try:\n            with closing(db.cursor()) as cursor:\n                cursor.execute(\"SHOW VARIABLES LIKE 'pid_file'\")\n                pid_file = cursor.fetchone()[1]\n        except Exception:\n            self.warning(\"Error while fetching pid_file variable of MySQL.\")\n        return pid_file",
    "docstring": "Get the `pid_file` variable"
  },
  {
    "code": "def mirror(self: BaseBoardT) -> BaseBoardT:\n        board = self.transform(flip_vertical)\n        board.occupied_co[WHITE], board.occupied_co[BLACK] = board.occupied_co[BLACK], board.occupied_co[WHITE]\n        return board",
    "docstring": "Returns a mirrored copy of the board.\n\n        The board is mirrored vertically and piece colors are swapped, so that\n        the position is equivalent modulo color."
  },
  {
    "code": "def count_characters(root, out):\n    if os.path.isfile(root):\n        with open(root, 'rb') as in_f:\n            for line in in_f:\n                for char in line:\n                    if char not in out:\n                        out[char] = 0\n                    out[char] = out[char] + 1\n    elif os.path.isdir(root):\n        for filename in os.listdir(root):\n            count_characters(os.path.join(root, filename), out)",
    "docstring": "Count the occurrances of the different characters in the files"
  },
  {
    "code": "def reload(self, encoding):\n        assert os.path.exists(self.path)\n        self.open(self.path, encoding=encoding,\n                  use_cached_encoding=False)",
    "docstring": "Reload the file with another encoding.\n\n        :param encoding: the new encoding to use to reload the file."
  },
  {
    "code": "def wgan(cls, data:DataBunch, generator:nn.Module, critic:nn.Module, switcher:Callback=None, clip:float=0.01, **learn_kwargs):\n        \"Create a WGAN from `data`, `generator` and `critic`.\"\n        return cls(data, generator, critic, NoopLoss(), WassersteinLoss(), switcher=switcher, clip=clip, **learn_kwargs)",
    "docstring": "Create a WGAN from `data`, `generator` and `critic`."
  },
  {
    "code": "def currency_format(cents):\n    try:\n        cents = int(cents)\n    except ValueError:\n        return cents\n    negative = (cents < 0)\n    if negative:\n        cents = -1 * cents\n    if cents < 100:\n        dollars = 0\n    else:\n        dollars = cents / 100\n        cents = cents % 100\n    centstr = str(cents)\n    if len(centstr) < 2:\n        centstr = '0' + centstr\n    if negative:\n        return \"- $%s.%s\" % (intcomma(dollars), centstr)\n    return \"$%s.%s\" % (intcomma(dollars), centstr)",
    "docstring": "Format currency with symbol and decimal points.\n\n    >> currency_format(-600)\n    - $6.00\n\n    TODO: Add localization support."
  },
  {
    "code": "def shell(args):\n    \" A helper command to be used for shell integration \"\n    print\n    print \"\n    print \"\n    print \"export MAKESITE_HOME=%s\" % args.path\n    print \"source %s\" % op.join(settings.BASEDIR, 'shell.sh')\n    print",
    "docstring": "A helper command to be used for shell integration"
  },
  {
    "code": "def add_tags(self, tags):\n        if not isinstance(tags, list):\n            tags = [tags]\n        self._bugsy.request('bug/comment/%s/tags' % self._comment['id'],\n                            method='PUT', json={\"add\": tags})",
    "docstring": "Add tags to the comments"
  },
  {
    "code": "def _twoByteStringToNum(bytestring, numberOfDecimals=0, signed=False):\n    _checkString(bytestring, minlength=2, maxlength=2, description='bytestring')\n    _checkInt(numberOfDecimals, minvalue=0, description='number of decimals')\n    _checkBool(signed, description='signed parameter')\n    formatcode = '>'\n    if signed:\n        formatcode += 'h'\n    else:\n        formatcode += 'H'\n    fullregister = _unpack(formatcode, bytestring)\n    if numberOfDecimals == 0:\n        return fullregister\n    divisor = 10 ** numberOfDecimals\n    return fullregister / float(divisor)",
    "docstring": "Convert a two-byte string to a numerical value, possibly scaling it.\n\n    Args:\n        * bytestring (str): A string of length 2.\n        * numberOfDecimals (int): The number of decimals. Defaults to 0.\n        * signed (bol): Whether large positive values should be interpreted as negative values.\n\n    Returns:\n        The numerical value (int or float) calculated from the ``bytestring``.\n\n    Raises:\n        TypeError, ValueError\n\n    Use the parameter ``signed=True`` if converting a bytestring that can hold\n    negative values. Then upper range data will be automatically converted into\n    negative return values (two's complement).\n\n    Use ``numberOfDecimals=1`` to divide the received data by 10 before returning the value.\n    Similarly ``numberOfDecimals=2`` will divide the received data by 100 before returning the value.\n\n    The byte order is big-endian, meaning that the most significant byte is sent first.\n\n    For example:\n        A string ``\\\\x03\\\\x02`` (which has the length 2) corresponds to 0302 (hex) = 770 (dec). If\n        ``numberOfDecimals = 1``, then this is converted to 77.0 (float)."
  },
  {
    "code": "def get_privileges(self):\n        url = self.url('GET_USER_PRIVILEGES')\n        return self.dispatch('GET', url, auth=self.auth)",
    "docstring": "Get privledges for this user."
  },
  {
    "code": "def get_header(self, name, default=None):\n        return self._handler.headers.get(name, default)",
    "docstring": "Retrieves the value of a header"
  },
  {
    "code": "def random_choice(self, actions=None, random_state=None):\n        random_state = check_random_state(random_state)\n        if actions is not None:\n            n = len(actions)\n        else:\n            n = self.num_actions\n        if n == 1:\n            idx = 0\n        else:\n            idx = random_state.randint(n)\n        if actions is not None:\n            return actions[idx]\n        else:\n            return idx",
    "docstring": "Return a pure action chosen randomly from `actions`.\n\n        Parameters\n        ----------\n        actions : array_like(int), optional(default=None)\n            An array of integers representing pure actions.\n\n        random_state : int or np.random.RandomState, optional\n            Random seed (integer) or np.random.RandomState instance to\n            set the initial state of the random number generator for\n            reproducibility. If None, a randomly initialized RandomState\n            is used.\n\n        Returns\n        -------\n        scalar(int)\n            If `actions` is given, returns an integer representing a\n            pure action chosen randomly from `actions`; if not, an\n            action is chosen randomly from the player's all actions."
  },
  {
    "code": "def _subprocess_method(self, command):\n        p = subprocess.Popen([self._ipmitool_path] + self.args + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n        self.output, self.error = p.communicate()\n        self.status = p.returncode",
    "docstring": "Use the subprocess module to execute ipmitool commands\n        and and set status"
  },
  {
    "code": "def _call(self, x, out=None):\n        if out is None:\n            return self.prod_op(x)[0]\n        else:\n            wrapped_out = self.prod_op.range.element([out], cast=False)\n            pspace_result = self.prod_op(x, out=wrapped_out)\n            return pspace_result[0]",
    "docstring": "Apply operators to ``x`` and sum."
  },
  {
    "code": "def ValidateStopTimesForTrip(self, problems, trip, stop_times):\n    prev_departure_secs = -1\n    consecutive_stop_times_with_potentially_same_time = 0\n    consecutive_stop_times_with_fully_specified_same_time = 0\n    def CheckSameTimeCount():\n      if (prev_departure_secs != -1 and\n          consecutive_stop_times_with_fully_specified_same_time > 5):\n        problems.TooManyConsecutiveStopTimesWithSameTime(trip.trip_id,\n            consecutive_stop_times_with_fully_specified_same_time,\n            prev_departure_secs)\n    for index, st in enumerate(stop_times):\n      if st.arrival_secs is None or st.departure_secs is None:\n        consecutive_stop_times_with_potentially_same_time += 1\n        continue\n      if (prev_departure_secs == st.arrival_secs and\n        st.arrival_secs == st.departure_secs):\n        consecutive_stop_times_with_potentially_same_time += 1\n        consecutive_stop_times_with_fully_specified_same_time = (\n            consecutive_stop_times_with_potentially_same_time)\n      else:\n        CheckSameTimeCount()\n        consecutive_stop_times_with_potentially_same_time = 1\n        consecutive_stop_times_with_fully_specified_same_time = 1\n      prev_departure_secs = st.departure_secs\n    CheckSameTimeCount()",
    "docstring": "Checks for the stop times of a trip.\n\n    Ensure that a trip does not have too many consecutive stop times with the\n    same departure/arrival time."
  },
  {
    "code": "def get_raw_data(self, mac, response_format='json'):\n        data = {\n            self._FORMAT_F: response_format,\n            self._SEARCH_F: mac\n        }\n        response = self.__decode_str(self.__call_api(self.__url, data), 'utf-8')\n        if len(response) > 0:\n            return response\n        raise EmptyResponseException()",
    "docstring": "Get data from API as string.\n\n            Keyword arguments:\n            mac -- MAC address or OUI for searching\n            response_format -- supported types you can see on the https://macaddress.io"
  },
  {
    "code": "def _load_file(self, filename):\n        filename = os.path.abspath(os.path.expanduser(filename))\n        if not os.path.isfile(filename):\n            raise Exception('File %s does not exist' % filename)\n        ext = vtki.get_ext(filename)\n        if ext == '.ply':\n            reader = vtk.vtkPLYReader()\n        elif ext == '.stl':\n            reader = vtk.vtkSTLReader()\n        elif ext == '.vtk':\n            reader = vtk.vtkPolyDataReader()\n        elif ext == '.vtp':\n            reader = vtk.vtkXMLPolyDataReader()\n        elif ext == '.obj':\n            reader = vtk.vtkOBJReader()\n        else:\n            raise TypeError('Filetype must be either \"ply\", \"stl\", \"vtk\", \"vtp\", or \"obj\".')\n        reader.SetFileName(filename)\n        reader.Update()\n        self.ShallowCopy(reader.GetOutput())\n        if not np.any(self.points):\n            raise AssertionError('Empty or invalid file')",
    "docstring": "Load a surface mesh from a mesh file.\n\n        Mesh file may be an ASCII or binary ply, stl, or vtk mesh file.\n\n        Parameters\n        ----------\n        filename : str\n            Filename of mesh to be loaded.  File type is inferred from the\n            extension of the filename\n\n        Notes\n        -----\n        Binary files load much faster than ASCII."
  },
  {
    "code": "def get_display_panel_by_id(self, identifier: str) -> DisplayPanel:\n        display_panel = next(\n            (display_panel for display_panel in self.__document_controller.workspace_controller.display_panels if\n            display_panel.identifier.lower() == identifier.lower()), None)\n        return DisplayPanel(display_panel) if display_panel else None",
    "docstring": "Return display panel with the identifier.\n\n        .. versionadded:: 1.0\n\n        Status: Provisional\n        Scriptable: Yes"
  },
  {
    "code": "def _initialize_client_from_environment():\n    global _client, project_id, write_key, read_key, master_key, base_url\n    if _client is None:\n        project_id = project_id or os.environ.get(\"KEEN_PROJECT_ID\")\n        write_key = write_key or os.environ.get(\"KEEN_WRITE_KEY\")\n        read_key = read_key or os.environ.get(\"KEEN_READ_KEY\")\n        master_key = master_key or os.environ.get(\"KEEN_MASTER_KEY\")\n        base_url = base_url or os.environ.get(\"KEEN_BASE_URL\")\n        if not project_id:\n            raise InvalidEnvironmentError(\"Please set the KEEN_PROJECT_ID environment variable or set keen.project_id!\")\n        _client = KeenClient(project_id,\n                             write_key=write_key,\n                             read_key=read_key,\n                             master_key=master_key,\n                             base_url=base_url)",
    "docstring": "Initialize a KeenClient instance using environment variables."
  },
  {
    "code": "def string_to_enum(value, enumeration, strict=True, default_value=None):\n    if not isinstance(enumeration, Enum):\n        raise ValueError('The specified enumeration is not an instance of Enum')\n    if is_undefined(value):\n        if strict:\n            raise ValueError('The value cannot be null')\n        if default_value is not None and not default_value in enumeration:\n            raise ValueError('The default value must be an item of the specified enumeration')\n        return default_value\n    item = [ item for item in enumeration if str(item) == value]\n    if len(item) == 0:\n        raise ValueError('The specified string \"%s\" does not represent any item of the enumeration' % value)\n    return item[0]",
    "docstring": "Return the item of an enumeration that corresponds to the specified\n    string representation.\n\n    @param value: string representation of an item of a Python\n        enumeration.\n\n    @param enumeration: a Python enumeration.\n\n    @param strict: indicate whether the value must correspond to an\n        item of the specified Python enumeration or if ``None`` value is\n        accepted.\n\n    @return: the item of the Python enumeration the specified string\n        representation corresponds to.\n\n    @raise ValueError: if the enumeration is not an instance of\n        ``Enum``, or if the string representation doesn't correspond\n        to any item of the given Python enumeration, or if the default\n        value is not an item of the given Python enumeration."
  },
  {
    "code": "def __call(self, uri, params=None, method=\"get\"):\n        try:\n            resp = self.__get_response(uri, params, method, False)\n            rjson = resp.json(**self.json_options)\n            assert resp.ok\n        except AssertionError:\n            msg = \"OCode-{}: {}\".format(resp.status_code, rjson[\"message\"])\n            raise BadRequest(msg)\n        except Exception as e:\n            msg = \"Bad response: {}\".format(e)\n            log.error(msg, exc_info=True)\n            raise BadRequest(msg)\n        else:\n            return rjson",
    "docstring": "Only returns the response, nor the status_code"
  },
  {
    "code": "def _getTrafficClassAndFlowLabel(self):\n        if self.tf == 0x0:\n            return (self.tc_ecn << 6) + self.tc_dscp, self.flowlabel\n        elif self.tf == 0x1:\n            return (self.tc_ecn << 6), self.flowlabel\n        elif self.tf == 0x2:\n            return (self.tc_ecn << 6) + self.tc_dscp, 0\n        else:\n            return 0, 0",
    "docstring": "Page 6, draft feb 2011"
  },
  {
    "code": "def parse_qs(qs, keep_blank_values=0, strict_parsing=0, keep_attr_order=True):\n    od = DefaultOrderedDict(list) if keep_attr_order else defaultdict(list)\n    for name, value in parse_qsl(qs, keep_blank_values, strict_parsing):\n        od[name].append(value)\n    return od",
    "docstring": "Kind of like urlparse.parse_qs, except returns an ordered dict.\n    Also avoids replicating that function's bad habit of overriding the\n    built-in 'dict' type.\n\n    Taken from below with modification:\n    <https://bitbucket.org/btubbs/thumpy/raw/8cdece404f15/thumpy.py>"
  },
  {
    "code": "def call_or_cast(self, method, args={}, nowait=False, **kwargs):\n        return (nowait and self.cast or self.call)(method, args, **kwargs)",
    "docstring": "Apply remote `method` asynchronously or synchronously depending\n        on the value of `nowait`.\n\n        :param method: The name of the remote method to perform.\n        :param args: Dictionary of arguments for the method.\n        :keyword nowait: If false the call will block until the result\n           is available and return it (default), if true the call will be\n           non-blocking and no result will be returned.\n        :keyword retry: If set to true then message sending will be retried\n          in the event of connection failures. Default is decided by the\n          :attr:`retry` attributed.\n        :keyword retry_policy: Override retry policies.\n           See :attr:`retry_policy`.  This must be a dictionary, and keys will\n           be merged with the default retry policy.\n        :keyword timeout: Timeout to wait for replies in seconds as a float\n           (**only relevant in blocking mode**).\n        :keyword limit: Limit number of replies to wait for\n           (**only relevant in blocking mode**).\n        :keyword callback: If provided, this callback will be called for every\n          reply received (**only relevant in blocking mode**).\n        :keyword \\*\\*props: Additional message properties.\n           See :meth:`kombu.Producer.publish`."
  },
  {
    "code": "def send_cons3rt_agent_logs(self):\n        log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs')\n        if self.cons3rt_agent_log_dir is None:\n            log.warn('There is not CONS3RT agent log directory on this system')\n            return\n        log.debug('Searching for log files in directory: {d}'.format(d=self.cons3rt_agent_log_dir))\n        for item in os.listdir(self.cons3rt_agent_log_dir):\n            item_path = os.path.join(self.cons3rt_agent_log_dir, item)\n            if os.path.isfile(item_path):\n                log.info('Sending email with cons3rt agent log file: {f}'.format(f=item_path))\n                try:\n                    self.send_text_file(text_file=item_path)\n                except (TypeError, OSError, AssetMailerError):\n                    _, ex, trace = sys.exc_info()\n                    msg = '{n}: There was a problem sending CONS3RT agent log file: {f}\\n{e}'.format(\n                        n=ex.__class__.__name__, f=item_path, e=str(ex))\n                    raise AssetMailerError, msg, trace\n                else:\n                    log.info('Successfully sent email with file: {f}'.format(f=item_path))",
    "docstring": "Send the cons3rt agent log file\n\n        :return:"
  },
  {
    "code": "def get_field_mro(cls, field_name):\n    res = set()\n    if hasattr(cls, '__mro__'):\n        for _class in inspect.getmro(cls):\n            values_ = getattr(_class, field_name, None)\n            if values_ is not None:\n                res = res.union(set(make_list(values_)))\n    return res",
    "docstring": "Goes up the mro and looks for the specified field."
  },
  {
    "code": "def get_market_history(self, market):\n        return self._api_query(path_dict={\n            API_V1_1: '/public/getmarkethistory',\n        }, options={'market': market, 'marketname': market}, protection=PROTECTION_PUB)",
    "docstring": "Used to retrieve the latest trades that have occurred for a\n        specific market.\n\n        Endpoint:\n        1.1 /market/getmarkethistory\n        2.0 NO Equivalent\n\n        Example ::\n            {'success': True,\n            'message': '',\n            'result': [ {'Id': 5625015,\n                         'TimeStamp': '2017-08-31T01:29:50.427',\n                         'Quantity': 7.31008193,\n                         'Price': 0.00177639,\n                         'Total': 0.01298555,\n                         'FillType': 'FILL',\n                         'OrderType': 'BUY'},\n                         ...\n                       ]\n            }\n\n        :param market: String literal for the market (ex: BTC-LTC)\n        :type market: str\n        :return: Market history in JSON\n        :rtype : dict"
  },
  {
    "code": "def _get_current_names(current, dsn, pc):\n    _table_name = \"\"\n    _variable_name = \"\"\n    try:\n        _table_name = current['{}_tableName'.format(pc)]\n        _variable_name = current['{}_variableName'.format(pc)]\n    except Exception as e:\n        print(\"Error: Unable to collapse time series: {}, {}\".format(dsn, e))\n        logger_ts.error(\"get_current: {}, {}\".format(dsn, e))\n    return _table_name, _variable_name",
    "docstring": "Get the table name and variable name from the given time series entry\n\n    :param dict current: Time series entry\n    :param str pc: paleoData or chronData\n    :return str _table_name:\n    :return str _variable_name:"
  },
  {
    "code": "def rpc_call(self, request, method=None, params=None, **kwargs):\n        args = []\n        kwargs = dict()\n        if isinstance(params, dict):\n            kwargs.update(params)\n        else:\n            args = list(as_tuple(params))\n        method_key = \"{0}.{1}\".format(self.scheme_name, method)\n        if method_key not in self.methods:\n            raise AssertionError(\"Unknown method: {0}\".format(method))\n        method = self.methods[method_key]\n        if hasattr(method, 'request'):\n            args.insert(0, request)\n        return method(*args, **kwargs)",
    "docstring": "Call a RPC method.\n\n        return object: a result"
  },
  {
    "code": "def sphlat(r, colat, lons):\n    r = ctypes.c_double(r)\n    colat = ctypes.c_double(colat)\n    lons = ctypes.c_double(lons)\n    radius = ctypes.c_double()\n    lon = ctypes.c_double()\n    lat = ctypes.c_double()\n    libspice.sphcyl_c(r, colat, lons, ctypes.byref(radius), ctypes.byref(lon),\n                      ctypes.byref(lat))\n    return radius.value, lon.value, lat.value",
    "docstring": "Convert from spherical coordinates to latitudinal coordinates.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphlat_c.html\n\n    :param r: Distance of the point from the origin.\n    :type r: float\n    :param colat: Angle of the point from positive z axis (radians).\n    :type colat: float\n    :param lons: Angle of the point from the XZ plane (radians).\n    :type lons: float\n    :return:\n            Distance of a point from the origin,\n            Angle of the point from the XZ plane in radians,\n            Angle of the point from the XY plane in radians.\n    :rtype: tuple"
  },
  {
    "code": "def _set_load_action(self, mem_addr, rec_count, retries,\n                         read_complete=False):\n        if self._have_all_records():\n            mem_addr = None\n            rec_count = 0\n            retries = 0\n        elif read_complete:\n            retries = 0\n            if rec_count:\n                mem_addr = self._next_address(mem_addr)\n            else:\n                mem_addr = self._next_address(mem_addr)\n                rec_count = 1\n                retries = 0\n        elif rec_count and retries < ALDB_RECORD_RETRIES:\n            retries = retries + 1\n        elif not rec_count and retries < ALDB_ALL_RECORD_RETRIES:\n            retries = retries + 1\n        elif not rec_count and retries >= ALDB_ALL_RECORD_RETRIES:\n            mem_addr = self._next_address(mem_addr)\n            rec_count = 1\n            retries = 0\n        else:\n            mem_addr = None\n            rec_count = 0\n            retries = 0\n        self._load_action = LoadAction(mem_addr, rec_count, retries)\n        if mem_addr is not None:\n            _LOGGER.debug('Load action: addr: %04x rec_count: %d retries: %d',\n                          self._load_action.mem_addr,\n                          self._load_action.rec_count,\n                          self._load_action.retries)",
    "docstring": "Calculate the next record to read.\n\n        If the last record was successful and one record was being read then\n        look for the next record until we get to the high water mark.\n\n        If the last read was successful and all records were being read then\n        look for the first record.\n\n        if the last read was unsuccessful and one record was being read then\n        repeat the last read until max retries\n\n        If the last read was unsuccessful and all records were being read then\n        repeat the last read until max retries or look for the first record."
  },
  {
    "code": "def get_ctype(rtype, cfunc, *args):\n    val_p = backend.ffi.new(rtype)\n    args = args + (val_p,)\n    cfunc(*args)\n    return val_p[0]",
    "docstring": "Call a C function that takes a pointer as its last argument and\n        return the C object that it contains after the function has finished.\n\n    :param rtype:   C data type is filled by the function\n    :param cfunc:   C function to call\n    :param args:    Arguments to call function with\n    :return:        A pointer to the specified data type"
  },
  {
    "code": "async def set_config(self, config):\n        app_facade = client.ApplicationFacade.from_connection(self.connection)\n        log.debug(\n            'Setting config for %s: %s', self.name, config)\n        return await app_facade.Set(self.name, config)",
    "docstring": "Set configuration options for this application.\n\n        :param config: Dict of configuration to set"
  },
  {
    "code": "def _fit_and_score_ensemble(self, X, y, cv, **fit_params):\n        fit_params_steps = self._split_fit_params(fit_params)\n        folds = list(cv.split(X, y))\n        base_estimators, kernel_cache = self._get_base_estimators(X)\n        out = Parallel(\n            n_jobs=self.n_jobs, verbose=self.verbose\n        )(\n            delayed(_fit_and_score_fold)(clone(estimator),\n                                         X if i not in kernel_cache else kernel_cache[i],\n                                         y,\n                                         self.scorer,\n                                         train_index, test_index,\n                                         fit_params_steps[name],\n                                         i, fold)\n            for i, (name, estimator) in enumerate(base_estimators)\n            for fold, (train_index, test_index) in enumerate(folds))\n        if len(kernel_cache) > 0:\n            out = self._restore_base_estimators(kernel_cache, out, X, folds)\n        return self._create_base_ensemble(out, len(base_estimators), len(folds))",
    "docstring": "Create a cross-validated model by training a model for each fold with the same model parameters"
  },
  {
    "code": "def content(self, path=None, overwrite=True, encoding='utf-8'):\n        if path:\n            self.download(wait=True, path=path, overwrite=overwrite)\n            with io.open(path, 'r', encoding=encoding) as fp:\n                return fp.read()\n        with tempfile.NamedTemporaryFile() as tmpfile:\n            self.download(wait=True, path=tmpfile.name, overwrite=overwrite)\n            with io.open(tmpfile.name, 'r', encoding=encoding) as fp:\n                return fp.read()",
    "docstring": "Downloads file to the specified path or as temporary file\n        and reads the file content in memory.\n         Should not be used on very large files.\n\n        :param path: Path for file download If omitted tmp file will be used.\n        :param overwrite: Overwrite file if exists locally\n        :param encoding: File encoding, by default it is UTF-8\n        :return: File content."
  },
  {
    "code": "def _get_shade_hdrgos(**kws):\n        if 'shade_hdrgos' in kws:\n            return kws['shade_hdrgos']\n        if 'hdrgo_prt' in kws:\n            return kws['hdrgo_prt']\n        if 'section_sortby' in kws and kws['section_sortby']:\n            return False\n        if 'top_n' in kws and isinstance(kws['top_n'], int):\n            return False\n        return True",
    "docstring": "If no hdrgo_prt specified, and these conditions are present -> hdrgo_prt=F."
  },
  {
    "code": "def top_sections(self):\n        top_line = self.text.split('\\n')[0]\n        sections = len(top_line.split('+')) - 2\n        return sections",
    "docstring": "The number of sections that touch the top side.\n\n        Returns\n        -------\n        sections : int\n            The number of sections on the top"
  },
  {
    "code": "def countok(self):\n        ok = np.ones(len(self.stars)).astype(bool)\n        for name in self.constraints:\n            c = self.constraints[name]\n            if c.name not in self.selectfrac_skip:\n                ok &= c.ok\n        return ok",
    "docstring": "Boolean array showing which stars pass all count constraints.\n\n        A \"count constraint\" is a constraint that affects the number of stars."
  },
  {
    "code": "def do_commit_amends(self):\n        commit_cumalative_count = 0\n        for days in MARKED_DAYS:\n            amend_date = (\n                self.end_date - datetime.timedelta(days)).strftime(\"%Y-%m-%d %H:%M:%S\")\n            for commit_number_in_a_day in xrange(0, self.max_commits):\n                commit_cumalative_count += 1\n                subprocess.check_call(\n                    ['git', 'commit', '--amend', \"--date='<\" + amend_date + \" + 0530 >' \", '-C',\n                     'HEAD~{commit_number}'.format(commit_number=commit_cumalative_count)], cwd=self.repository_name)\n                subprocess.check_call(\n                    ['git', 'pull', '--no-edit'], cwd=self.repository_name)\n                subprocess.check_call(\n                    ['git', 'push', 'origin', 'master'], cwd=self.repository_name)",
    "docstring": "Amends the Commit to form the heart"
  },
  {
    "code": "def disallow(nodes):\n    def disallowed(cls):\n        cls.unsupported_nodes = ()\n        for node in nodes:\n            new_method = _node_not_implemented(node, cls)\n            name = 'visit_{node}'.format(node=node)\n            cls.unsupported_nodes += (name,)\n            setattr(cls, name, new_method)\n        return cls\n    return disallowed",
    "docstring": "Decorator to disallow certain nodes from parsing. Raises a\n    NotImplementedError instead.\n\n    Returns\n    -------\n    disallowed : callable"
  },
  {
    "code": "def get_sh_ids(self, identity, backend_name):\n        identity_tuple = tuple(identity.items())\n        sh_ids = self.__get_sh_ids_cache(identity_tuple, backend_name)\n        return sh_ids",
    "docstring": "Return the Sorting Hat id and uuid for an identity"
  },
  {
    "code": "def _convert_to_degress(self, value):\n        d0 = value[0][0]\n        d1 = value[0][1]\n        d = float(d0) / float(d1)\n        m0 = value[1][0]\n        m1 = value[1][1]\n        m = float(m0) / float(m1)\n        s0 = value[2][0]\n        s1 = value[2][1]\n        s = float(s0) / float(s1)\n        return d + (m / 60.0) + (s / 3600.0)",
    "docstring": "Helper function to convert the GPS coordinates stored in the EXIF to degress in float format"
  },
  {
    "code": "def time_window(self, window_width_ms):\n        op = Operator(\n            _generate_uuid(),\n            OpType.TimeWindow,\n            \"TimeWindow\",\n            num_instances=self.env.config.parallelism,\n            other=window_width_ms)\n        return self.__register(op)",
    "docstring": "Applies a system time window to the stream.\n\n        Attributes:\n             window_width_ms (int): The length of the window in ms."
  },
  {
    "code": "def _geodetic_to_cartesian(cls, lat, lon, alt):\n        C = Earth.r / np.sqrt(1 - (Earth.e * np.sin(lat)) ** 2)\n        S = Earth.r * (1 - Earth.e ** 2) / np.sqrt(1 - (Earth.e * np.sin(lat)) ** 2)\n        r_d = (C + alt) * np.cos(lat)\n        r_k = (S + alt) * np.sin(lat)\n        norm = np.sqrt(r_d ** 2 + r_k ** 2)\n        return norm * np.array([\n            np.cos(lat) * np.cos(lon),\n            np.cos(lat) * np.sin(lon),\n            np.sin(lat)\n        ])",
    "docstring": "Conversion from latitude, longitude and altitude coordinates to\n        cartesian with respect to an ellipsoid\n\n        Args:\n            lat (float): Latitude in radians\n            lon (float): Longitude in radians\n            alt (float): Altitude to sea level in meters\n\n        Return:\n            numpy.array: 3D element (in meters)"
  },
  {
    "code": "def get_interpolated(self, target, extent):\n        result = self.copy()\n        result.interpolate(target, extent)\n        return result",
    "docstring": "Return a new vector that has been moved towards the given target by \n        the given extent.  The extent should be between 0 and 1."
  },
  {
    "code": "def decode(self) -> Iterable:\n        if self.data[0:1] not in (b'd', b'l'):\n            return self.__wrap_with_tuple()\n        return self.__parse()",
    "docstring": "Start of decode process. Returns final results."
  },
  {
    "code": "def _apply_credentials(auto_refresh=True, credentials=None,\n                           headers=None):\n        token = credentials.get_credentials().access_token\n        if auto_refresh is True:\n            if token is None:\n                token = credentials.refresh(\n                    access_token=None, timeout=10)\n            elif credentials.jwt_is_expired():\n                token = credentials.refresh(timeout=10)\n        headers.update(\n            {'Authorization': \"Bearer {}\".format(token)}\n        )",
    "docstring": "Update Authorization header.\n\n        Update request headers with latest `access_token`. Perform token\n        `refresh` if token is ``None``.\n\n        Args:\n            auto_refresh (bool): Perform token refresh if access_token is ``None`` or expired. Defaults to ``True``.\n            credentials (class): Read-only credentials.\n            headers (class): Requests `CaseInsensitiveDict`."
  },
  {
    "code": "def do_random(context, seq):\n    try:\n        return random.choice(seq)\n    except IndexError:\n        return context.environment.undefined('No random item, sequence was empty.')",
    "docstring": "Return a random item from the sequence."
  },
  {
    "code": "async def _sonar_data(self, data):\n        data = data[1:-1]\n        pin_number = data[0]\n        val = int((data[PrivateConstants.MSB] << 7) +\n                  data[PrivateConstants.LSB])\n        reply_data = []\n        sonar_pin_entry = self.active_sonar_map[pin_number]\n        if sonar_pin_entry[0] is not None:\n            if sonar_pin_entry[2] != val:\n                sonar_pin_entry[2] = val\n                self.active_sonar_map[pin_number] = sonar_pin_entry\n                if sonar_pin_entry[0]:\n                    reply_data.append(pin_number)\n                    reply_data.append(val)\n                    if sonar_pin_entry[1]:\n                        await sonar_pin_entry[0](reply_data)\n                    else:\n                        loop = self.loop\n                        loop.call_soon(sonar_pin_entry[0], reply_data)\n        else:\n            sonar_pin_entry[1] = val\n            self.active_sonar_map[pin_number] = sonar_pin_entry\n        await asyncio.sleep(self.sleep_tune)",
    "docstring": "This method handles the incoming sonar data message and stores\n        the data in the response table.\n\n        :param data: Message data from Firmata\n\n        :returns: No return value."
  },
  {
    "code": "def query_names(self, pat):\n        for item in self.chnames.items():\n            if fnmatch.fnmatchcase(item[1], pat):\n                print item",
    "docstring": "pat a shell pattern. See fnmatch.fnmatchcase. Print the\n        results to stdout."
  },
  {
    "code": "def write_json(self):\n        with open(self.results_folder_name + '/results-' + str(self.get_global_count()) + '.json', 'a') as f:\n            json.dump(self.result, f)",
    "docstring": "Dump data into json file."
  },
  {
    "code": "def ref(self):\n        x = RefTrace(self.filehandle,\n                     self.dtype,\n                     len(self),\n                     self.shape,\n                     self.readonly,\n                    )\n        yield x\n        x.flush()",
    "docstring": "A write-back version of Trace\n\n        Returns\n        -------\n        ref : RefTrace\n            `ref` is returned in a context manager, and must be in a ``with``\n            statement\n\n        Notes\n        -----\n        .. versionadded:: 1.6\n\n        Examples\n        --------\n        >>> with trace.ref as ref:\n        ...     ref[10] += 1.617"
  },
  {
    "code": "def translate_state(self, s):\n        if not isinstance(s, basestring):\n            return s\n        s = s.capitalize().replace(\"_\", \" \")\n        return t(_(s))",
    "docstring": "Translate the given state string"
  },
  {
    "code": "def require_bool(self, key: str) -> bool:\n        v = self.get_bool(key)\n        if v is None:\n            raise ConfigMissingError(self.full_key(key))\n        return v",
    "docstring": "Returns a configuration value, as a bool, by its given key.  If it doesn't exist, or the\n        configuration value is not a legal bool, an error is thrown.\n\n        :param str key: The requested configuration key.\n        :return: The configuration key's value.\n        :rtype: bool\n        :raises ConfigMissingError: The configuration value did not exist.\n        :raises ConfigTypeError: The configuration value existed but couldn't be coerced to bool."
  },
  {
    "code": "def tilequeue_rawr_seed_all(cfg, peripherals):\n    rawr_yaml = cfg.yml.get('rawr')\n    assert rawr_yaml is not None, 'Missing rawr configuration in yaml'\n    group_by_zoom = rawr_yaml.get('group-zoom')\n    assert group_by_zoom is not None, 'Missing group-zoom rawr config'\n    max_coord = 2 ** group_by_zoom\n    coords = []\n    for x in xrange(0, max_coord):\n        for y in xrange(0, max_coord):\n            coords.append(Coordinate(zoom=group_by_zoom, column=x, row=y))\n    _tilequeue_rawr_seed(cfg, peripherals, coords)",
    "docstring": "command to enqueue all the tiles at the group-by zoom"
  },
  {
    "code": "def _get_model(self, appname, modelname):\n        app = self._get_app(appname)\n        models = app.get_models()\n        model = None\n        for mod in models:\n            if mod.__name__ == modelname:\n                model = mod\n                return model\n        msg = \"Model \" + modelname + \" not found\"",
    "docstring": "return model or None"
  },
  {
    "code": "def stored_bind(self, instance):\n        if self.id is None:\n            return self.bind(instance)\n        store = self._bound_pangler_store.setdefault(instance, {})\n        p = store.get(self.id)\n        if p is None:\n            p = store[self.id] = self.bind(instance)\n        return p",
    "docstring": "Bind an instance to this Pangler, using the bound Pangler store.\n\n        This method functions identically to `bind`, except that it might\n        return a Pangler which was previously bound to the provided instance."
  },
  {
    "code": "def path_distance(points):\n    vecs = np.diff(points, axis=0)[:, :3]\n    d2 = [np.dot(p, p) for p in vecs]\n    return np.sum(np.sqrt(d2))",
    "docstring": "Compute the path distance from given set of points"
  },
  {
    "code": "def connectivity(measure_names, b, c=None, nfft=512):\n    con = Connectivity(b, c, nfft)\n    try:\n        return getattr(con, measure_names)()\n    except TypeError:\n        return dict((m, getattr(con, m)()) for m in measure_names)",
    "docstring": "Calculate connectivity measures.\n\n    Parameters\n    ----------\n    measure_names : str or list of str\n        Name(s) of the connectivity measure(s) to calculate. See\n        :class:`Connectivity` for supported measures.\n    b : array, shape (n_channels, n_channels * model_order)\n        VAR model coefficients. See :ref:`var-model-coefficients` for details\n        about the arrangement of coefficients.\n    c : array, shape (n_channels, n_channels), optional\n        Covariance matrix of the driving noise process. Identity matrix is used\n        if set to None (default).\n    nfft : int, optional\n        Number of frequency bins to calculate. Note that these points cover the\n        range between 0 and half the sampling rate.\n\n    Returns\n    -------\n    result : array, shape (n_channels, n_channels, `nfft`)\n        An array of shape (m, m, nfft) is returned if measures is a string. If\n        measures is a list of strings, a dictionary is returned, where each key\n        is the name of the measure, and the corresponding values are arrays of\n        shape (m, m, nfft).\n\n    Notes\n    -----\n    When using this function, it is more efficient to get several measures at\n    once than calling the function multiple times.\n\n    Examples\n    --------\n    >>> c = connectivity(['DTF', 'PDC'], [[0.3, 0.6], [0.0, 0.9]])"
  },
  {
    "code": "def count_async(self, limit=None, **q_options):\n    qry = self._fix_namespace()\n    return qry._count_async(limit=limit, **q_options)",
    "docstring": "Count the number of query results, up to a limit.\n\n    This is the asynchronous version of Query.count()."
  },
  {
    "code": "def _uri(self, url):\n        if url and not url.startswith('/'):\n            return url\n        uri = \"{0}://{1}{2}{3}\".format(\n            self._protocol,\n            self.real_connection.host,\n            self._port_postfix(),\n            url,\n        )\n        return uri",
    "docstring": "Returns request absolute URI"
  },
  {
    "code": "def from_object(obj):\n        return obj if isinstance(obj, Contact) \\\n            else Contact(cast.string_to_enum(obj.name, Contact.ContactName),\n                         obj.value,\n                         is_primary=obj.is_primary and cast.string_to_boolean(obj.is_primary, strict=True),\n                         is_verified=obj.is_verified and cast.string_to_boolean(obj.is_verified, strict=True))",
    "docstring": "Convert an object representing a contact information to an instance\n        `Contact`.\n\n\n        @param obj: an object containg the following attributes:\n\n            * `name`: an item of the enumeration `ContactName` representing the\n              type of this contact information.\n\n            * `value`: value of this contact information representing by a string,\n              such as ``+84.01272170781``, the formatted value for a telephone\n              number property.\n\n            * `is_primary`: indicate whether this contact property is the first to\n              be used to contact the entity that this contact information\n              corresponds to.  There is only one primary contact property for a\n              given property name (e.g., `EMAIL`, `PHONE`, `WEBSITE`).\n\n            * `is_verified`: indicate whether this contact information has been\n              verified, whether it has been grabbed from a trusted Social\n              Networking Service (SNS), or whether through a challenge/response\n              process.\n\n\n        @raise ValueError: if the value of this contact information is null."
  },
  {
    "code": "def on_network_adapter_change(self, network_adapter, change_adapter):\n        if not isinstance(network_adapter, INetworkAdapter):\n            raise TypeError(\"network_adapter can only be an instance of type INetworkAdapter\")\n        if not isinstance(change_adapter, bool):\n            raise TypeError(\"change_adapter can only be an instance of type bool\")\n        self._call(\"onNetworkAdapterChange\",\n                     in_p=[network_adapter, change_adapter])",
    "docstring": "Triggered when settings of a network adapter of the\n        associated virtual machine have changed.\n\n        in network_adapter of type :class:`INetworkAdapter`\n\n        in change_adapter of type bool\n\n        raises :class:`VBoxErrorInvalidVmState`\n            Session state prevents operation.\n        \n        raises :class:`VBoxErrorInvalidObjectState`\n            Session type prevents operation."
  },
  {
    "code": "def minutes_in_range(self, start_minute, end_minute):\n        start_idx = searchsorted(self._trading_minutes_nanos,\n                                 start_minute.value)\n        end_idx = searchsorted(self._trading_minutes_nanos,\n                               end_minute.value)\n        if end_minute.value == self._trading_minutes_nanos[end_idx]:\n            end_idx += 1\n        return self.all_minutes[start_idx:end_idx]",
    "docstring": "Given start and end minutes, return all the calendar minutes\n        in that range, inclusive.\n\n        Given minutes don't need to be calendar minutes.\n\n        Parameters\n        ----------\n        start_minute: pd.Timestamp\n            The minute representing the start of the desired range.\n\n        end_minute: pd.Timestamp\n            The minute representing the end of the desired range.\n\n        Returns\n        -------\n        pd.DatetimeIndex\n            The minutes in the desired range."
  },
  {
    "code": "def diffuse_template(self, **kwargs):\n        kwargs_copy = self.base_dict.copy()\n        kwargs_copy.update(**kwargs)\n        self._replace_none(kwargs_copy)        \n        localpath = NameFactory.diffuse_template_format.format(**kwargs_copy)\n        if kwargs.get('fullpath', False):\n            return self.fullpath(localpath=localpath)\n        return localpath",
    "docstring": "return the file name for other diffuse map templates"
  },
  {
    "code": "def _process(self, data):\n        try:\n            packet = json.loads(data)\n        except ValueError:\n            logger.warning('Received invalid JSON from client. Ignoring.')\n            return\n        if packet['cmd'] == 'run-command':\n            self._run_command(packet)\n        elif packet['cmd'] == 'in':\n            self._pipeinput.send_text(packet['data'])\n        elif packet['cmd'] == 'size':\n            data = packet['data']\n            self.size = Size(rows=data[0], columns=data[1])\n            self.pymux.invalidate()\n        elif packet['cmd'] == 'start-gui':\n            detach_other_clients = bool(packet['detach-others'])\n            color_depth = packet['color-depth']\n            term = packet['term']\n            if detach_other_clients:\n                for c in self.pymux.connections:\n                    c.detach_and_close()\n            print('Create app...')\n            self._create_app(color_depth=color_depth, term=term)",
    "docstring": "Process packet received from client."
  },
  {
    "code": "def currency_context(context):\n    request = context['request']\n    currency_code = memoize_nullary(lambda: get_currency_code(request))\n    context['CURRENCIES'] = Currency.active.all()\n    context['CURRENCY_CODE'] = currency_code\n    context['CURRENCY'] = memoize_nullary(lambda: get_currency(currency_code))\n    return ''",
    "docstring": "Use instead of context processor\n    Context variables are only valid within the block scope"
  },
  {
    "code": "def show_tabulated(self, begin, middle, end):\n        internal_assert(len(begin) < info_tabulation, \"info message too long\", begin)\n        self.show(begin + \" \" * (info_tabulation - len(begin)) + middle + \" \" + end)",
    "docstring": "Shows a tabulated message."
  },
  {
    "code": "def create_user(self, claims):\n        email = claims.get('email')\n        username = self.get_username(claims)\n        return self.UserModel.objects.create_user(username, email)",
    "docstring": "Return object for a newly created user account."
  },
  {
    "code": "def unregister(self, command):\n        if command not in self._commands.keys():\n            self.log.warning(\"Can not unregister command %s\" % command)\n        else:\n            del(self._click_root_command.commands[command])\n            del(self._commands[command])\n            self.log.debug(\"Command %s got unregistered\" % command)",
    "docstring": "Unregisters an existing command, so that this command is no longer available on the command line interface.\n\n        This function is mainly used during plugin deactivation.\n\n        :param command: Name of the command"
  },
  {
    "code": "def purge(datasets, reuses, organizations):\n    purge_all = not any((datasets, reuses, organizations))\n    if purge_all or datasets:\n        log.info('Purging datasets')\n        purge_datasets()\n    if purge_all or reuses:\n        log.info('Purging reuses')\n        purge_reuses()\n    if purge_all or organizations:\n        log.info('Purging organizations')\n        purge_organizations()\n    success('Done')",
    "docstring": "Permanently remove data flagged as deleted.\n\n    If no model flag is given, all models are purged."
  },
  {
    "code": "def datapt_to_wcspt(self, datapt, coords='data', naxispath=None):\n        if naxispath:\n            raise NotImplementedError\n        return np.asarray([self.pixtoradec((pt[0], pt[1]), coords=coords)\n                           for pt in datapt])",
    "docstring": "Convert multiple data points to WCS.\n\n        Parameters\n        ----------\n        datapt : array-like\n            Pixel coordinates in the format of\n            ``[[x0, y0, ...], [x1, y1, ...], ..., [xn, yn, ...]]``.\n\n        coords : 'data' or None, optional, default to 'data'\n            Expresses whether the data coordinate is indexed from zero.\n\n        naxispath : list-like or None, optional, defaults to None\n            A sequence defining the pixel indexes > 2D, if any.\n\n        Returns\n        -------\n        wcspt : array-like\n            WCS coordinates in the format of\n            ``[[ra0, dec0], [ra1, dec1], ..., [ran, decn]]``."
  },
  {
    "code": "def move_to_clipboard(self, request, files_queryset, folders_queryset):\n        if not self.has_change_permission(request):\n            raise PermissionDenied\n        if request.method != 'POST':\n            return None\n        clipboard = tools.get_user_clipboard(request.user)\n        check_files_edit_permissions(request, files_queryset)\n        check_folder_edit_permissions(request, folders_queryset)\n        files_count = [0]\n        def move_files(files):\n            files_count[0] += tools.move_file_to_clipboard(files, clipboard)\n        def move_folders(folders):\n            for f in folders:\n                move_files(f.files)\n                move_folders(f.children.all())\n        move_files(files_queryset)\n        move_folders(folders_queryset)\n        self.message_user(request, _(\"Successfully moved %(count)d files to \"\n                                     \"clipboard.\") % {\"count\": files_count[0]})\n        return None",
    "docstring": "Action which moves the selected files and files in selected folders\n        to clipboard."
  },
  {
    "code": "def jwt_required(realm=None):\n    def wrapper(fn):\n        @wraps(fn)\n        def decorator(*args, **kwargs):\n            _jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])\n            return fn(*args, **kwargs)\n        return decorator\n    return wrapper",
    "docstring": "View decorator that requires a valid JWT token to be present in the request\n\n    :param realm: an optional realm"
  },
  {
    "code": "def remove_alert(thing_name, key, session=None):\n    return _request('get', '/remove/alert/for/{0}'.format(thing_name), params={'key': key}, session=session)",
    "docstring": "Remove an alert for the given thing"
  },
  {
    "code": "def dbmin20years(self, value=None):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type float '\n                                 'for field `dbmin20years`'.format(value))\n        self._dbmin20years = value",
    "docstring": "Corresponds to IDD Field `dbmin20years`\n        20-year return period values for minimum extreme dry-bulb temperature\n\n        Args:\n            value (float): value for IDD Field `dbmin20years`\n                Unit: C\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def export(self, node):\n        dictexporter = self.dictexporter or DictExporter()\n        data = dictexporter.export(node)\n        return json.dumps(data, **self.kwargs)",
    "docstring": "Return JSON for tree starting at `node`."
  },
  {
    "code": "def parse_mailto(mailto_str):\n    if mailto_str.startswith('mailto:'):\n        import urllib.parse\n        to_str, parms_str = mailto_str[7:].partition('?')[::2]\n        headers = {}\n        body = u''\n        to = urllib.parse.unquote(to_str)\n        if to:\n            headers['To'] = [to]\n        for s in parms_str.split('&'):\n            key, value = s.partition('=')[::2]\n            key = key.capitalize()\n            if key == 'Body':\n                body = urllib.parse.unquote(value)\n            elif value:\n                headers[key] = [urllib.parse.unquote(value)]\n        return (headers, body)\n    else:\n        return (None, None)",
    "docstring": "Interpret mailto-string\n\n    :param mailto_str: the string to interpret. Must conform to :rfc:2368.\n    :type mailto_str: str\n    :return: the header fields and the body found in the mailto link as a tuple\n        of length two\n    :rtype: tuple(dict(str->list(str)), str)"
  },
  {
    "code": "def getCodecList(self):\n        if self.checkVersion('1.4'):\n            cmd = \"core show codecs\"\n        else:\n            cmd = \"show codecs\"\n        cmdresp = self.executeCommand(cmd)\n        info_dict = {}\n        for line in cmdresp.splitlines():\n            mobj = re.match('\\s*(\\d+)\\s+\\((.+)\\)\\s+\\((.+)\\)\\s+(\\w+)\\s+(\\w+)\\s+\\((.+)\\)$',\n                            line)\n            if mobj:\n                info_dict[mobj.group(5)] = (mobj.group(4), mobj.group(6))\n        return info_dict",
    "docstring": "Query Asterisk Manager Interface for defined codecs.\n        \n        CLI Command - core show codecs\n        \n        @return: Dictionary - Short Name -> (Type, Long Name)"
  },
  {
    "code": "def create_toolbutton(parent, text=None, shortcut=None, icon=None, tip=None,\r\n                      toggled=None, triggered=None,\r\n                      autoraise=True, text_beside_icon=False):\r\n    button = QToolButton(parent)\r\n    if text is not None:\r\n        button.setText(text)\r\n    if icon is not None:\r\n        if is_text_string(icon):\r\n            icon = get_icon(icon)\r\n        button.setIcon(icon)\r\n    if text is not None or tip is not None:\r\n        button.setToolTip(text if tip is None else tip)\r\n    if text_beside_icon:\r\n        button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)\r\n    button.setAutoRaise(autoraise)\r\n    if triggered is not None:\r\n        button.clicked.connect(triggered)\r\n    if toggled is not None:\r\n        button.toggled.connect(toggled)\r\n        button.setCheckable(True)\r\n    if shortcut is not None:\r\n        button.setShortcut(shortcut)\r\n    return button",
    "docstring": "Create a QToolButton"
  },
  {
    "code": "def _ctypes_code_parameter(lines, parameter, position):\n    mdict = {\n        'indices': _ctypes_indices,\n        'variable': _ctypes_variables,\n        'out': _ctypes_out,\n        'regular': _ctypes_regular,\n        'saved': _ctypes_saved,\n        'assign': _ctypes_assign,\n        'clean': _ctypes_clean\n    }\n    line = mdict[position](parameter)\n    if line is not None:\n        value, blank = line\n        lines.append(value)\n        if blank:\n            lines.append(\"\")",
    "docstring": "Returns the code for the specified parameter being written into a subroutine wrapper.\n\n    :arg position: one of ['indices', 'variable', 'out', 'regular', 'saved', 'assign', 'clean']"
  },
  {
    "code": "def set_close_callback(self, callback: Optional[Callable[[], None]]) -> None:\n        self._close_callback = callback\n        self._maybe_add_error_listener()",
    "docstring": "Call the given callback when the stream is closed.\n\n        This mostly is not necessary for applications that use the\n        `.Future` interface; all outstanding ``Futures`` will resolve\n        with a `StreamClosedError` when the stream is closed. However,\n        it is still useful as a way to signal that the stream has been\n        closed while no other read or write is in progress.\n\n        Unlike other callback-based interfaces, ``set_close_callback``\n        was not removed in Tornado 6.0."
  },
  {
    "code": "def read(parts):\n    cur_dir = os.path.abspath(os.path.dirname(__file__))\n    with codecs.open(os.path.join(cur_dir, *parts), \"rb\", \"utf-8\") as f:\n        return f.read()",
    "docstring": "Build an absolute path from parts array and and return the contents\n    of the resulting file.  Assume UTF-8 encoding."
  },
  {
    "code": "def bootstrap_buttons(parser, token):\n    kwargs = parse_token_contents(parser, token)\n    kwargs[\"nodelist\"] = parser.parse((\"endbuttons\",))\n    parser.delete_first_token()\n    return ButtonsNode(**kwargs)",
    "docstring": "Render buttons for form\n\n    **Tag name**::\n\n        buttons\n\n    **Parameters**:\n\n        submit\n            Text for a submit button\n\n        reset\n            Text for a reset button\n\n    **Usage**::\n\n        {% buttons %}{% endbuttons %}\n\n    **Example**::\n\n        {% buttons submit='OK' reset=\"Cancel\" %}{% endbuttons %}"
  },
  {
    "code": "def get_acls_recursive(self, path, depth, include_ephemerals):\n        yield path, self.get_acls(path)[0]\n        if depth == -1:\n            return\n        for tpath, _ in self.tree(path, depth, full_path=True):\n            try:\n                acls, stat = self.get_acls(tpath)\n            except NoNodeError:\n                continue\n            if not include_ephemerals and stat.ephemeralOwner != 0:\n                continue\n            yield tpath, acls",
    "docstring": "A recursive generator wrapper for get_acls\n\n        :param path: path from which to start\n        :param depth: depth of the recursion (-1 no recursion, 0 means no limit)\n        :param include_ephemerals: get ACLs for ephemerals too"
  },
  {
    "code": "def fit_for_distance(self):\n        for prop in self.properties.keys():\n            if prop in self.ic.bands:\n                return True\n        return False",
    "docstring": "``True`` if any of the properties are apparent magnitudes."
  },
  {
    "code": "def assign(self, dst, req, src):\n        if req == 'null':\n            return\n        elif req in ('write', 'inplace'):\n            dst[:] = src\n        elif req == 'add':\n            dst[:] += src",
    "docstring": "Helper function for assigning into dst depending on requirements."
  },
  {
    "code": "def container_instance_from_string(id):\n    try:\n        service, instance = id.rsplit('_', 1)\n        instance = int(instance)\n    except (TypeError, ValueError):\n        raise context.ValueError(\"Invalid container id %r\" % id)\n    return _proto.ContainerInstance(service_name=service, instance=instance)",
    "docstring": "Create a ContainerInstance from an id string"
  },
  {
    "code": "def push_primary_analyses_for_removal(self, analysis_request, analyses):\n        to_remove = self.analyses_to_remove.get(analysis_request, [])\n        to_remove.extend(analyses)\n        self.analyses_to_remove[analysis_request] = list(set(to_remove))",
    "docstring": "Stores the analyses to be removed after partitions creation"
  },
  {
    "code": "def set_focus(self, pos):\n        \"Set the focus in the underlying body widget.\"\n        logging.debug('setting focus to %s ', pos)\n        self.body.set_focus(pos)",
    "docstring": "Set the focus in the underlying body widget."
  },
  {
    "code": "def delete_info(ctx, info):\n    head = ctx.parent.head\n    vcf_handle = ctx.parent.handle\n    outfile = ctx.parent.outfile\n    silent = ctx.parent.silent\n    if not info:\n        logger.error(\"No info provided\")\n        sys.exit(\"Please provide a info string\")\n    if not info in head.info_dict:\n        logger.error(\"Info '{0}' is not specified in vcf header\".format(info))\n        sys.exit(\"Please provide a valid info field\")\n    head.remove_header(info)\n    print_headers(head, outfile=outfile, silent=silent)\n    for line in vcf_handle:\n        line = line.rstrip()\n        new_line = remove_vcf_info(keyword=info, variant_line=line)\n        print_variant(variant_line=new_line, outfile=outfile, silent=silent)",
    "docstring": "Delete a info field from all variants in a vcf"
  },
  {
    "code": "def resize2fs(device):\n    cmd = 'resize2fs {0}'.format(device)\n    try:\n        out = __salt__['cmd.run_all'](cmd, python_shell=False)\n    except subprocess.CalledProcessError as err:\n        return False\n    if out['retcode'] == 0:\n        return True",
    "docstring": "Resizes the filesystem.\n\n    CLI Example:\n    .. code-block:: bash\n\n        salt '*' disk.resize2fs /dev/sda1"
  },
  {
    "code": "def get_object(self):\n        if self._object:\n            return self._object\n        self._object = super().get_object()\n        if not self.AUDITOR_EVENT_TYPES:\n            return self._object\n        method = self.request.method\n        event_type = self.AUDITOR_EVENT_TYPES.get(method)\n        if method == 'GET' and event_type and is_user(self.request.user):\n            auditor.record(event_type=event_type,\n                           instance=self._object,\n                           actor_id=self.request.user.id,\n                           actor_name=self.request.user.username)\n        elif method == 'DELETE' and event_type and is_user(self.request.user):\n            auditor.record(event_type=event_type,\n                           instance=self._object,\n                           actor_id=self.request.user.id,\n                           actor_name=self.request.user.username)\n        return self._object",
    "docstring": "We memoize the access to this function in case a second call is made."
  },
  {
    "code": "def db_exists(cls, impl, working_dir):\n        path = config.get_snapshots_filename(impl, working_dir)\n        return os.path.exists(path)",
    "docstring": "Does the chainstate db exist?"
  },
  {
    "code": "def run_bottleneck_on_image(sess, image_data, image_data_tensor,\n                            decoded_image_tensor, resized_input_tensor,\n                            bottleneck_tensor):\n  resized_input_values = sess.run(decoded_image_tensor,\n                                  {image_data_tensor: image_data})\n  bottleneck_values = sess.run(bottleneck_tensor,\n                               {resized_input_tensor: resized_input_values})\n  bottleneck_values = np.squeeze(bottleneck_values)\n  return bottleneck_values",
    "docstring": "Runs inference on an image to extract the 'bottleneck' summary layer.\n\n  Args:\n    sess: Current active TensorFlow Session.\n    image_data: String of raw JPEG data.\n    image_data_tensor: Input data layer in the graph.\n    decoded_image_tensor: Output of initial image resizing and preprocessing.\n    resized_input_tensor: The input node of the recognition graph.\n    bottleneck_tensor: Layer before the final softmax.\n\n  Returns:\n    Numpy array of bottleneck values."
  },
  {
    "code": "def getElementByWdomId(self, id: Union[str]) -> Optional[WebEventTarget]:\n        elm = getElementByWdomId(id)\n        if elm and elm.ownerDocument is self:\n            return elm\n        return None",
    "docstring": "Get an element node with ``wdom_id``.\n\n        If this document does not have the element with the id, return None."
  },
  {
    "code": "def apply_gates_to_fd(stilde_dict, gates):\n    outdict = dict(stilde_dict.items())\n    strain_dict = dict([[ifo, outdict[ifo].to_timeseries()] for ifo in gates])\n    for ifo,d in apply_gates_to_td(strain_dict, gates).items():\n        outdict[ifo] = d.to_frequencyseries()\n    return outdict",
    "docstring": "Applies the given dictionary of gates to the given dictionary of\n    strain in the frequency domain.\n\n    Gates are applied by IFFT-ing the strain data to the time domain, applying\n    the gate, then FFT-ing back to the frequency domain.\n\n    Parameters\n    ----------\n    stilde_dict : dict\n        Dictionary of frequency-domain strain, keyed by the ifos.\n    gates : dict\n        Dictionary of gates. Keys should be the ifo to apply the data to,\n        values are a tuple giving the central time of the gate, the half\n        duration, and the taper duration.\n\n    Returns\n    -------\n    dict\n        Dictionary of frequency-domain strain with the gates applied."
  },
  {
    "code": "def search_info(self, search_index):\n        ddoc_search_info = self.r_session.get(\n            '/'.join([self.document_url, '_search_info', search_index]))\n        ddoc_search_info.raise_for_status()\n        return response_to_json_dict(ddoc_search_info)",
    "docstring": "Retrieves information about a specified search index within the design\n        document, returns dictionary\n\n        GET databasename/_design/{ddoc}/_search_info/{search_index}"
  },
  {
    "code": "def setup(\n    *,\n    verbose: bool = False,\n    quiet: bool = False,\n    color: str = \"auto\",\n    title: str = \"auto\",\n    timestamp: bool = False\n) -> None:\n    _setup(verbose=verbose, quiet=quiet, color=color, title=title, timestamp=timestamp)",
    "docstring": "Configure behavior of message functions.\n\n    :param verbose: Whether :func:`debug` messages should get printed\n    :param quiet: Hide every message except :func:`warning`, :func:`error`, and\n                  :func:`fatal`\n    :param color: Choices: 'auto', 'always', or 'never'. Whether to color output.\n                  By default ('auto'), only use color when output is a terminal.\n    :param title: Ditto for setting terminal title\n    :param timestamp: Whether to prefix every message with a time stamp"
  },
  {
    "code": "def write(self, text):\n        if text:\n            if text[0] in '(w':\n                self.log.debug(text[:-1])\n                return\n            if self.access_log:\n                self.access_log.write(text)\n            self.log.info(text[:-1])",
    "docstring": "Write to appropriate target."
  },
  {
    "code": "def read_energy_bounds(hdu):\n    nebins = len(hdu.data)\n    ebin_edges = np.ndarray((nebins + 1))\n    try:\n        ebin_edges[0:-1] = np.log10(hdu.data.field(\"E_MIN\")) - 3.\n        ebin_edges[-1] = np.log10(hdu.data.field(\"E_MAX\")[-1]) - 3.\n    except KeyError:\n        ebin_edges[0:-1] = np.log10(hdu.data.field(\"energy_MIN\"))\n        ebin_edges[-1] = np.log10(hdu.data.field(\"energy_MAX\")[-1])\n    return ebin_edges",
    "docstring": "Reads and returns the energy bin edges from a FITs HDU"
  },
  {
    "code": "def impact_check_range(func):\n    @wraps(func)\n    def impact_wrapper(*args,**kwargs):\n        if isinstance(args[1],numpy.ndarray):\n            out= numpy.zeros(len(args[1]))\n            goodIndx= (args[1] < args[0]._deltaAngleTrackImpact)*(args[1] > 0.)\n            out[goodIndx]= func(args[0],args[1][goodIndx])\n            return out\n        elif args[1] >= args[0]._deltaAngleTrackImpact or args[1] <= 0.:\n            return 0.\n        else:\n            return func(*args,**kwargs)\n    return impact_wrapper",
    "docstring": "Decorator to check the range of interpolated kicks"
  },
  {
    "code": "def get_image_size(self, image):\n        if image['size'] is None:\n            args = settings.THUMBNAIL_VIPSHEADER.split(' ')\n            args.append(image['source'])\n            p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n            p.wait()\n            m = size_re.match(str(p.stdout.read()))\n            image['size'] = int(m.group('x')), int(m.group('y'))\n        return image['size']",
    "docstring": "Returns the image width and height as a tuple"
  },
  {
    "code": "def get_as_parameters_with_default(self, key, default_value):\n        result = self.get_as_nullable_parameters(key)\n        return result if result != None else default_value",
    "docstring": "Converts map element into an Parameters or returns default value if conversion is not possible.\n\n        :param key: a key of element to get.\n\n        :param default_value: the default value\n\n        :return: Parameters value of the element or default value if conversion is not supported."
  },
  {
    "code": "def remove_listener(self, listener):\n        internal_listener = self._internal_listeners.pop(listener)\n        return self._client.remove_listener(internal_listener)",
    "docstring": "Remove the given listener from the wrapped client.\n\n        :param listener: A listener previously passed to :meth:`add_listener`."
  },
  {
    "code": "def get_narrow_url(self, instance):\n        text = instance[0]\n        request = self.context[\"request\"]\n        query_params = request.GET.copy()\n        page_query_param = self.get_paginate_by_param()\n        if page_query_param and page_query_param in query_params:\n            del query_params[page_query_param]\n        selected_facets = set(query_params.pop(self.root.facet_query_params_text, []))\n        selected_facets.add(\"%(field)s_exact:%(text)s\" % {\"field\": self.parent_field, \"text\": text})\n        query_params.setlist(self.root.facet_query_params_text, sorted(selected_facets))\n        path = \"%(path)s?%(query)s\" % {\"path\": request.path_info, \"query\": query_params.urlencode()}\n        url = request.build_absolute_uri(path)\n        return serializers.Hyperlink(url, \"narrow-url\")",
    "docstring": "Return a link suitable for narrowing on the current item."
  },
  {
    "code": "def also_restrict_to(self, restriction):\n        if type(restriction) != list:\n            restriction = [ restriction ]\n        self._also_restriction = restriction",
    "docstring": "Works like restict_to but offers an additional restriction.  Playbooks use this\n        to implement serial behavior."
  },
  {
    "code": "def _convert_json(obj):\n    if isinstance(obj, dict):\n        return {_convert_json(key): _convert_json(val)\n                for (key, val) in six.iteritems(obj)}\n    elif isinstance(obj, list) and len(obj) == 2:\n        first = obj[0]\n        second = obj[1]\n        if first == 'set' and isinstance(second, list):\n            return [_convert_json(elem) for elem in second]\n        elif first == 'map' and isinstance(second, list):\n            for elem in second:\n                if not isinstance(elem, list) or len(elem) != 2:\n                    return obj\n            return {elem[0]: _convert_json(elem[1]) for elem in second}\n        else:\n            return obj\n    elif isinstance(obj, list):\n        return [_convert_json(elem) for elem in obj]\n    else:\n        return obj",
    "docstring": "Converts from the JSON output provided by ovs-vsctl into a usable Python\n    object tree. In particular, sets and maps are converted from lists to\n    actual sets or maps.\n\n    Args:\n        obj: Object that shall be recursively converted.\n\n    Returns:\n        Converted version of object."
  },
  {
    "code": "def ex_varassign(name, expr):\n    if not isinstance(expr, ast.expr):\n        expr = ex_literal(expr)\n    return ast.Assign([ex_lvalue(name)], expr)",
    "docstring": "Assign an expression into a single variable. The expression may\n    either be an `ast.expr` object or a value to be used as a literal."
  },
  {
    "code": "def _interpret_ltude(value, name, psuffix, nsuffix):\n    if not isinstance(value, str):\n        return Angle(degrees=_unsexagesimalize(value))\n    value = value.strip().upper()\n    if value.endswith(psuffix):\n        sign = +1.0\n    elif value.endswith(nsuffix):\n        sign = -1.0\n    else:\n        raise ValueError('your {0} string {1!r} does not end with either {2!r}'\n                         ' or {3!r}'.format(name, value, psuffix, nsuffix))\n    try:\n        value = float(value[:-1])\n    except ValueError:\n        raise ValueError('your {0} string {1!r} cannot be parsed as a floating'\n                         ' point number'.format(name, value))\n    return Angle(degrees=sign * value)",
    "docstring": "Interpret a string, float, or tuple as a latitude or longitude angle.\n\n    `value` - The string to interpret.\n    `name` - 'latitude' or 'longitude', for use in exception messages.\n    `positive` - The string that indicates a positive angle ('N' or 'E').\n    `negative` - The string that indicates a negative angle ('S' or 'W')."
  },
  {
    "code": "def aroon_up(data, period):\n    catch_errors.check_for_period_error(data, period)\n    period = int(period)\n    a_up = [((period -\n            list(reversed(data[idx+1-period:idx+1])).index(np.max(data[idx+1-period:idx+1]))) /\n            float(period)) * 100 for idx in range(period-1, len(data))]\n    a_up = fill_for_noncomputable_vals(data, a_up)\n    return a_up",
    "docstring": "Aroon Up.\n\n    Formula:\n    AROONUP = (((PERIOD) - (PERIODS since PERIOD high)) / (PERIOD)) * 100"
  },
  {
    "code": "def _persist_metadata(self):\n        serializable_data = self.get_serializable()\n        try:\n            self._try_persist_metadata(serializable_data)\n        except TypeError:\n            cleaned_data = Script._remove_non_serializable_store_entries(serializable_data[\"store\"])\n            self._try_persist_metadata(cleaned_data)",
    "docstring": "Write all script meta-data, including the persistent script Store.\n        The Store instance might contain arbitrary user data, like function objects, OpenCL contexts, or whatever other\n        non-serializable objects, both as keys or values.\n        Try to serialize the data, and if it fails, fall back to checking the store and removing all non-serializable\n        data."
  },
  {
    "code": "def get_transport_target(cls, instance, timeout, retries):\n        if \"ip_address\" not in instance:\n            raise Exception(\"An IP address needs to be specified\")\n        ip_address = instance[\"ip_address\"]\n        port = int(instance.get(\"port\", 161))\n        return hlapi.UdpTransportTarget((ip_address, port), timeout=timeout, retries=retries)",
    "docstring": "Generate a Transport target object based on the instance's configuration"
  },
  {
    "code": "def parse_datetime(record: str) -> Optional[datetime]:\n    format_strings = {8: '%Y%m%d', 12: '%Y%m%d%H%M', 14: '%Y%m%d%H%M%S'}\n    if record == '':\n        return None\n    return datetime.strptime(record.strip(),\n                                          format_strings[len(record.strip())])",
    "docstring": "Parse a datetime string into a python datetime object"
  },
  {
    "code": "def _start_lst_proc(self,\n                        listener_type,\n                        listener_opts):\n        log.debug('Starting the listener process for %s', listener_type)\n        listener = NapalmLogsListenerProc(self.opts,\n                                          self.address,\n                                          self.port,\n                                          listener_type,\n                                          listener_opts=listener_opts)\n        proc = Process(target=listener.start)\n        proc.start()\n        proc.description = 'Listener process'\n        log.debug('Started listener process as %s with PID %s', proc._name, proc.pid)\n        return proc",
    "docstring": "Start the listener process."
  },
  {
    "code": "def edit_matching_entry(program, arguments):\n    entry = program.select_entry(*arguments)\n    entry.context.execute(\"pass\", \"edit\", entry.name)",
    "docstring": "Edit the matching entry."
  },
  {
    "code": "def _generate_manager(manager_config):\n        if 'class' not in manager_config:\n            raise ValueError(\n                'Manager not fully specified. Give '\n                '\"class:manager_name\", e.g. \"class:MongoDBManager\".')\n        mgr_class_name = manager_config['class']\n        if mgr_class_name.lower()[:5] == 'mongo':\n            from datafs.managers.manager_mongo import (\n                MongoDBManager as mgr_class)\n        elif mgr_class_name.lower()[:6] == 'dynamo':\n            from datafs.managers.manager_dynamo import (\n                DynamoDBManager as mgr_class)\n        else:\n            raise KeyError(\n                'Manager class \"{}\" not recognized. Choose from {}'.format(\n                    mgr_class_name, 'MongoDBManager or DynamoDBManager'))\n        manager = mgr_class(\n            *manager_config.get('args', []),\n            **manager_config.get('kwargs', {}))\n        return manager",
    "docstring": "Generate a manager from a manager_config dictionary\n\n        Parameters\n        ----------\n\n        manager_config : dict\n            Configuration with keys class, args, and kwargs\n            used to generate a new datafs.manager object\n\n        Returns\n        -------\n\n        manager : object\n            datafs.managers.MongoDBManager or\n            datafs.managers.DynamoDBManager object\n            initialized with *args, **kwargs\n\n        Examples\n        --------\n\n        Generate a dynamo manager:\n\n        .. code-block:: python\n\n        >>> mgr = APIConstructor._generate_manager({\n        ...     'class': 'DynamoDBManager',\n        ...     'kwargs': {\n        ...         'table_name': 'data-from-yaml',\n        ...         'session_args': {\n        ...             'aws_access_key_id': \"access-key-id-of-your-choice\",\n        ...             'aws_secret_access_key': \"secret-key-of-your-choice\"},\n        ...         'resource_args': {\n        ...             'endpoint_url':'http://localhost:8000/',\n        ...             'region_name':'us-east-1'}\n        ...     }\n        ... })\n        >>>\n        >>> from datafs.managers.manager_dynamo import DynamoDBManager\n        >>> assert isinstance(mgr, DynamoDBManager)\n        >>>\n        >>> 'data-from-yaml' in mgr.table_names\n        False\n        >>> mgr.create_archive_table('data-from-yaml')\n        >>> 'data-from-yaml' in mgr.table_names\n        True\n        >>> mgr.delete_table('data-from-yaml')"
  },
  {
    "code": "def get_paths(self, theme, icon_size):\n        _size_str = \"x\".join(map(str, icon_size))\n        theme_path = get_program_path() + \"share\" + os.sep + \"icons\" + os.sep\n        icon_path = theme_path + theme + os.sep + _size_str + os.sep\n        action_path = icon_path + \"actions\" + os.sep\n        toggle_path = icon_path + \"toggles\" + os.sep\n        return theme_path, icon_path, action_path, toggle_path",
    "docstring": "Returns tuple of theme, icon, action and toggle paths"
  },
  {
    "code": "def _handle_stderr_event(self, fd, events):\n        assert fd == self.fd_stderr\n        if events & self.ioloop.READ:\n            if not self.headers_sent:\n                payload = self.process.stderr.read()\n                data = 'HTTP/1.1 500 Internal Server Error\\r\\nDate: %s\\r\\nContent-Length: %d\\r\\n\\r\\n' % (get_date_header(), len(payload))\n                self.headers_sent = True\n                data += payload\n            else:\n                logger.error(\"This should not happen (stderr)\")\n                data = self.process.stderr.read()\n            logger.debug('Sending stderr to client: %r', data)\n            self.request.write(data)\n        if events & self.ioloop.ERROR:\n            logger.debug('Error on stderr')\n            if not self.process.stderr.closed:\n                self.process.stderr.close()\n            self.ioloop.remove_handler(self.fd_stderr)\n            return self._graceful_finish()",
    "docstring": "Eventhandler for stderr"
  },
  {
    "code": "def set_published_date(self):\n        try:\n            self.published_date = self.soup.find('pubdate').string\n        except AttributeError:\n            self.published_date = None",
    "docstring": "Parses published date and set value"
  },
  {
    "code": "def bluemix(cls, vcap_services, instance_name=None, service_name=None, **kwargs):\n        service_name = service_name or 'cloudantNoSQLDB'\n        try:\n            service = CloudFoundryService(vcap_services,\n                                          instance_name=instance_name,\n                                          service_name=service_name)\n        except CloudantException:\n            raise CloudantClientException(103)\n        if hasattr(service, 'iam_api_key'):\n            return Cloudant.iam(service.username,\n                                service.iam_api_key,\n                                url=service.url,\n                                **kwargs)\n        return Cloudant(service.username,\n                        service.password,\n                        url=service.url,\n                        **kwargs)",
    "docstring": "Create a Cloudant session using a VCAP_SERVICES environment variable.\n\n        :param vcap_services: VCAP_SERVICES environment variable\n        :type vcap_services: dict or str\n        :param str instance_name: Optional Bluemix instance name. Only required\n            if multiple Cloudant instances are available.\n        :param str service_name: Optional Bluemix service name.\n\n        Example usage:\n\n        .. code-block:: python\n\n            import os\n            from cloudant.client import Cloudant\n\n            client = Cloudant.bluemix(os.getenv('VCAP_SERVICES'),\n                                      'Cloudant NoSQL DB')\n\n            print client.all_dbs()"
  },
  {
    "code": "def get_all_query_traces(self, max_wait_per=None, query_cl=ConsistencyLevel.LOCAL_ONE):\n        if self._query_traces:\n            return [self._get_query_trace(i, max_wait_per, query_cl) for i in range(len(self._query_traces))]\n        return []",
    "docstring": "Fetches and returns the query traces for all query pages, if tracing was enabled.\n\n        See note in :meth:`~.get_query_trace` regarding possible exceptions."
  },
  {
    "code": "def intercept(actions: dict={}):\n    for action in actions.values():\n        if type(action) is not returns and type(action) is not raises:\n            raise InterceptorError('Actions must be declared as `returns` or `raises`')\n    def decorated(f):\n        def wrapped(*args, **kargs):\n            try:\n                return f(*args, **kargs)\n            except Exception as e:\n                if e.__class__ in actions:\n                    return actions[e.__class__](e)\n                else:\n                    raise\n        return wrapped\n    return decorated",
    "docstring": "Decorates a function and handles any exceptions that may rise.\n\n    Args:\n        actions: A dictionary ``<exception type>: <action>``. Available actions\\\n            are :class:`raises` and :class:`returns`.\n\n    Returns:\n        Any value declared using a :class:`returns` action.\n\n    Raises:\n        AnyException: if AnyException is declared together with a\n            :class:`raises` action.\n        InterceptorError: if the decorator is called with something different\n            from a :class:`returns` or :class:`raises` action.\n\n    Interceptors can be declared inline to return a value or raise an exception\n    when the declared exception is risen:\n\n    >>> @intercept({\n    ...    TypeError: returns('intercepted!')\n    ... })\n    ... def fails(foo):\n    ...     if foo:\n    ...         raise TypeError('inner exception')\n    ...     return 'ok'\n    >>> fails(False)\n    'ok'\n    >>> fails(True)\n    'intercepted!'\n\n    >>> @intercept({\n    ...    TypeError: raises(Exception('intercepted!'))\n    ... })\n    ... def fail():\n    ...     raise TypeError('inner exception')\n    >>> fail()\n    Traceback (most recent call last):\n    ...\n    Exception: intercepted!\n\n    But they can also be declared and then used later on:\n\n    >>> intercept0r = intercept({\n    ...    TypeError: returns('intercepted!')\n    ... })\n    >>> @intercept0r\n    ... def fail():\n    ...     raise TypeError('raising error')\n    >>> fail()\n    'intercepted!'\n\n    You can declare also an action that captures the risen exception by passing\n    a callable to the action. This is useful to create a custom error message:\n\n    >>> @intercept({\n    ...    TypeError: returns(lambda e: 'intercepted {}'.format(e))\n    ... })\n    ... def fail():\n    ...     raise TypeError('inner exception')\n    >>> fail()\n    'intercepted inner exception'\n\n    Or to convert captured exceptions into custom errors:\n\n    >>> class CustomError(Exception):\n    ...     pass\n    >>> @intercept({\n    ...    TypeError: raises(lambda e: CustomError(e))\n    ... })\n    ... def fail():\n    ...     raise TypeError('inner exception')\n    >>> fail()\n    Traceback (most recent call last):\n    ...\n    intercept.CustomError: inner exception"
  },
  {
    "code": "def clear_copyright(self):\n        if (self.get_copyright_metadata().is_read_only() or\n                self.get_copyright_metadata().is_required()):\n            raise errors.NoAccess()\n        self._my_map['copyright'] = dict(self._copyright_default)",
    "docstring": "Removes the copyright.\n\n        raise:  NoAccess - ``Metadata.isRequired()`` is ``true`` or\n                ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _evaluate_dimension_fields(self) -> bool:\n        for _, item in self._dimension_fields.items():\n            item.run_evaluate()\n            if item.eval_error:\n                return False\n        return True",
    "docstring": "Evaluates the dimension fields. Returns False if any of the fields could not be evaluated."
  },
  {
    "code": "def findLowest(self, symorders):\n        _range = range(len(symorders))\n        stableSymorders = map(None, symorders, _range)\n        stableSymorders.sort()\n        lowest = None\n        for index in _range:\n            if stableSymorders[index][0] == lowest:\n                return stableSymorders[index-1][1]\n            lowest = stableSymorders[index][0]\n        return -1",
    "docstring": "Find the position of the first lowest tie in a\n        symorder or -1 if there are no ties"
  },
  {
    "code": "def vae(x, z_size, name=None):\n  with tf.variable_scope(name, default_name=\"vae\"):\n    mu = tf.layers.dense(x, z_size, name=\"mu\")\n    log_sigma = tf.layers.dense(x, z_size, name=\"log_sigma\")\n    shape = common_layers.shape_list(x)\n    epsilon = tf.random_normal([shape[0], shape[1], 1, z_size])\n    z = mu + tf.exp(log_sigma / 2) * epsilon\n    kl = 0.5 * tf.reduce_mean(\n        tf.expm1(log_sigma) + tf.square(mu) - log_sigma, axis=-1)\n    free_bits = z_size // 4\n    kl_loss = tf.reduce_mean(tf.maximum(kl - free_bits, 0.0))\n    return z, kl_loss, mu, log_sigma",
    "docstring": "Simple variational autoencoder without discretization.\n\n  Args:\n    x: Input to the discretization bottleneck.\n    z_size: Number of bits, where discrete codes range from 1 to 2**z_size.\n    name: Name for the bottleneck scope.\n\n  Returns:\n    Embedding function, latent, loss, mu and log_simga."
  },
  {
    "code": "def inv(self):\n        self.v = 1/self.v\n        tmp = self.v**2\n        if self.deriv > 1:\n            self.dd[:] = tmp*(2*self.v*np.outer(self.d, self.d) - self.dd)\n        if self.deriv > 0:\n            self.d[:] = -tmp*self.d[:]",
    "docstring": "In place invert"
  },
  {
    "code": "def get_subgraph_by_edge_filter(graph, edge_predicates: Optional[EdgePredicates] = None):\n    rv = graph.fresh_copy()\n    expand_by_edge_filter(graph, rv, edge_predicates=edge_predicates)\n    return rv",
    "docstring": "Induce a sub-graph on all edges that pass the given filters.\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param edge_predicates: An edge predicate or list of edge predicates\n    :return: A BEL sub-graph induced over the edges passing the given filters\n    :rtype: pybel.BELGraph"
  },
  {
    "code": "def readAltWCS(fobj, ext, wcskey=' ', verbose=False):\n    if isinstance(fobj, str):\n        fobj = fits.open(fobj, memmap=False)\n    hdr = altwcs._getheader(fobj, ext)\n    try:\n        original_logging_level = log.level\n        log.setLevel(logutil.logging.WARNING)\n        nwcs = pywcs.WCS(hdr, fobj=fobj, key=wcskey)\n    except KeyError:\n        if verbose:\n            print('readAltWCS: Could not read WCS with key %s' % wcskey)\n            print('            Skipping %s[%s]' % (fobj.filename(), str(ext)))\n        return None\n    finally:\n        log.setLevel(original_logging_level)\n    hwcs = nwcs.to_header()\n    if nwcs.wcs.has_cd():\n        hwcs = altwcs.pc2cd(hwcs, key=wcskey)\n    return hwcs",
    "docstring": "Reads in alternate primary WCS from specified extension.\n\n    Parameters\n    ----------\n    fobj : str, `astropy.io.fits.HDUList`\n        fits filename or fits file object\n        containing alternate/primary WCS(s) to be converted\n    wcskey : str\n        [\" \",A-Z]\n        alternate/primary WCS key that will be replaced by the new key\n    ext : int\n        fits extension number\n    Returns\n    -------\n    hdr: fits.Header\n        header object with ONLY the keywords for specified alternate WCS"
  },
  {
    "code": "def _any_pandas_objects(terms):\n    return any(isinstance(term.value, pd.core.generic.PandasObject)\n               for term in terms)",
    "docstring": "Check a sequence of terms for instances of PandasObject."
  },
  {
    "code": "def _get_batch_representative(items, key):\n    if isinstance(items, dict):\n        return items, items\n    else:\n        vals = set([])\n        out = []\n        for data in items:\n            if key in data:\n                vals.add(data[key])\n                out.append(data)\n        if len(vals) != 1:\n            raise ValueError(\"Incorrect values for %s: %s\" % (key, list(vals)))\n        return out[0], items",
    "docstring": "Retrieve a representative data item from a batch.\n\n    Handles standard bcbio cases (a single data item) and CWL cases with\n    batches that have a consistent variant file."
  },
  {
    "code": "def _is_valid_function(module_name, function):\n    try:\n        functions = __salt__['sys.list_functions'](module_name)\n    except salt.exceptions.SaltException:\n        functions = [\"unable to look up functions\"]\n    return \"{0}.{1}\".format(module_name, function) in functions",
    "docstring": "Determine if a function is valid for a module"
  },
  {
    "code": "def _get_driver(self):\n        ComputeEngine = get_driver(Provider.GCE)\n        return ComputeEngine(\n            self.service_account_email,\n            self.service_account_file,\n            project=self.service_account_project\n        )",
    "docstring": "Get authenticated GCE driver."
  },
  {
    "code": "def family_coff(self):\n        if not self._ptr:\n            raise BfdException(\"BFD not initialized\")\n        return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.FAMILY_COFF)",
    "docstring": "Return the family_coff attribute of the BFD file being processed."
  },
  {
    "code": "def check_padding_around_mutation(given_padding, epitope_lengths):\n    min_required_padding = max(epitope_lengths) - 1\n    if not given_padding:\n        return min_required_padding\n    else:\n        require_integer(given_padding, \"Padding around mutation\")\n        if given_padding < min_required_padding:\n            raise ValueError(\n                \"Padding around mutation %d cannot be less than %d \"\n                \"for epitope lengths %s\" % (\n                    given_padding,\n                    min_required_padding,\n                    epitope_lengths))\n        return given_padding",
    "docstring": "If user doesn't provide any padding around the mutation we need\n    to at least include enough of the surrounding non-mutated\n    esidues to construct candidate epitopes of the specified lengths."
  },
  {
    "code": "def extract(path_to_hex, output_path=None):\n    with open(path_to_hex, 'r') as hex_file:\n        python_script = extract_script(hex_file.read())\n        if output_path:\n            with open(output_path, 'w') as output_file:\n                output_file.write(python_script)\n        else:\n            print(python_script)",
    "docstring": "Given a path_to_hex file this function will attempt to extract the\n    embedded script from it and save it either to output_path or stdout"
  },
  {
    "code": "def remove_cycle_mrkr(self):\n        window_start = self.parent.value('window_start')\n        try:\n            self.annot.remove_cycle_mrkr(window_start)\n        except KeyError:\n            msg = ('The start of the window does not correspond to any cycle '\n                   'marker in sleep scoring file')\n            self.parent.statusBar().showMessage(msg)\n            lg.debug(msg)\n        else:\n            lg.debug('User removed cycle marker at' + str(window_start))\n            self.parent.overview.update(reset=False)\n            self.parent.overview.display_annotations()",
    "docstring": "Remove cycle marker."
  },
  {
    "code": "def set_type(spec, obj_type):\n        if spec is None:\n            raise ValueError('Spec cannot be None')\n        if TemplateFields.generation not in spec:\n            spec[TemplateFields.generation] = {}\n        spec[TemplateFields.generation][TemplateFields.commkey] = \\\n            Gen.CLIENT if (obj_type & (int(1) << TemplateFields.FLAG_COMM_GEN)) > 0 else Gen.LEGACY_RANDOM\n        spec[TemplateFields.generation][TemplateFields.appkey] = \\\n            Gen.CLIENT if (obj_type & (int(1) << TemplateFields.FLAG_APP_GEN)) > 0 else Gen.LEGACY_RANDOM\n        spec[TemplateFields.type] = \"%x\" % obj_type\n        return spec",
    "docstring": "Updates type integer in the cerate UO specification.\n        Type has to already have generations flags set correctly.\n        Generation field is set accordingly.\n\n        :param spec:\n        :param obj_type:\n        :return:"
  },
  {
    "code": "def load_from_file(filename):\n    if os.path.isdir(filename):\n        logger.error(\"Err: File '%s' is a directory\", filename)\n        return None\n    if not os.path.isfile(filename):\n        logger.error(\"Err: File '%s' does not exist\", filename)\n        return None\n    try:\n        with open(filename, 'r') as sourcefile:\n            songs = [line.strip() for line in sourcefile]\n    except IOError as error:\n        logger.exception(error)\n        return None\n    songs = set(Song.from_filename(song) for song in songs)\n    return songs.difference({None})",
    "docstring": "Load a list of filenames from an external text file."
  },
  {
    "code": "def convert(self, value, view):\n        if isinstance(value, int):\n            return value\n        elif isinstance(value, float):\n            return int(value)\n        else:\n            self.fail(u'must be a number', view, True)",
    "docstring": "Check that the value is an integer. Floats are rounded."
  },
  {
    "code": "def build_full_toctree(builder, docname, prune, collapse):\n    env = builder.env\n    doctree = env.get_doctree(env.config.master_doc)\n    toctrees = []\n    for toctreenode in doctree.traverse(addnodes.toctree):\n        toctree = env.resolve_toctree(docname, builder, toctreenode,\n                                      collapse=collapse,\n                                      prune=prune,\n                                      )\n        toctrees.append(toctree)\n    if not toctrees:\n        return None\n    result = toctrees[0]\n    for toctree in toctrees[1:]:\n        if toctree:\n            result.extend(toctree.children)\n    env.resolve_references(result, docname, builder)\n    return result",
    "docstring": "Return a single toctree starting from docname containing all\n    sub-document doctrees."
  },
  {
    "code": "def rename(self, name):\n        if name:\n            rename1, rename2 = callbacks.add(\n                b'rename', self.change_name, False)\n            self.dispatch_command(b'/bin/echo \"' + rename1 + b'\"\"' + rename2 +\n                                  b'\"' + name + b'\\n')\n        else:\n            self.change_name(self.hostname.encode())",
    "docstring": "Send to the remote shell, its new name to be shell expanded"
  },
  {
    "code": "def expand_dataset(X, y_proba, factor=10, random_state=None, extra_arrays=None):\n    rng = check_random_state(random_state)\n    extra_arrays = extra_arrays or []\n    n_classes = y_proba.shape[1]\n    classes = np.arange(n_classes, dtype=int)\n    for el in zip(X, y_proba, *extra_arrays):\n        x, probs = el[0:2]\n        rest = el[2:]\n        for label in rng.choice(classes, size=factor, p=probs):\n            yield (x, label) + rest",
    "docstring": "Convert a dataset with float multiclass probabilities to a dataset\n    with indicator probabilities by duplicating X rows and sampling\n    true labels."
  },
  {
    "code": "def schema(self):\n    if not self._schema:\n      try:\n        self._load_info()\n        self._schema = _schema.Schema(self._info['schema']['fields'])\n      except KeyError:\n        raise Exception('Unexpected table response: missing schema')\n    return self._schema",
    "docstring": "Retrieves the schema of the table.\n\n    Returns:\n      A Schema object containing a list of schema fields and associated metadata.\n    Raises\n      Exception if the request could not be executed or the response was malformed."
  },
  {
    "code": "def patch_sys_version():\n    if '|' in sys.version:\n        sys_version = sys.version.split('|')\n        sys.version = ' '.join([sys_version[0].strip(), sys_version[-1].strip()])",
    "docstring": "Remove Continuum copyright statement to avoid parsing errors in IDLE"
  },
  {
    "code": "def is_installed(self, name: str) -> bool:\n        assert name is not None\n        try:\n            self.__docker.images.get(name)\n            return True\n        except docker.errors.ImageNotFound:\n            return False",
    "docstring": "Indicates a given Docker image is installed on this server.\n\n        Parameters:\n            name: the name of the Docker image.\n\n        Returns:\n            `True` if installed; `False` if not."
  },
  {
    "code": "def _get_by_index(self, index):\n        volume_or_disk = self.parser.get_by_index(index)\n        volume, disk = (volume_or_disk, None) if not isinstance(volume_or_disk, Disk) else (None, volume_or_disk)\n        return volume, disk",
    "docstring": "Returns a volume,disk tuple for the specified index"
  },
  {
    "code": "def start(self):\n        self._timer = Timer(self.time, self.handler)\n        self._timer.daemon = True\n        self._timer.start()\n        return",
    "docstring": "Starts the watchdog timer."
  },
  {
    "code": "def redirect_to(request, url, permanent=True, query_string=False, **kwargs):\n    r\n    args = request.META.get('QUERY_STRING', '')\n    if url is not None:\n        if kwargs:\n            url = url % kwargs\n        if args and query_string:\n            url = \"%s?%s\" % (url, args)\n        klass = (permanent and HttpResponsePermanentRedirect\n                 or HttpResponseRedirect)\n        return klass(url)\n    else:\n        logger.warning(\n            'Gone: %s',\n            request.path,\n            extra={\n                'status_code': 410,\n                'request': request\n            })\n        return HttpResponseGone()",
    "docstring": "r\"\"\"\n    Redirect to a given URL.\n\n    The given url may contain dict-style string formatting, which will be\n    interpolated against the params in the URL.  For example, to redirect from\n    ``/foo/<id>/`` to ``/bar/<id>/``, you could use the following URLconf::\n\n        urlpatterns = patterns('',\n            (r'^foo/(?P<id>\\d+)/$',\n             'django.views.generic.simple.redirect_to',\n             {'url' : '/bar/%(id)s/'}),\n        )\n\n    If the given url is ``None``, a HttpResponseGone (410) will be issued.\n\n    If the ``permanent`` argument is False, then the response will have a 302\n    HTTP status code. Otherwise, the status code will be 301.\n\n    If the ``query_string`` argument is True, then the GET query string\n    from the request is appended to the URL."
  },
  {
    "code": "def update_content_encoding(self, data: Any) -> None:\n        if not data:\n            return\n        enc = self.headers.get(hdrs.CONTENT_ENCODING, '').lower()\n        if enc:\n            if self.compress:\n                raise ValueError(\n                    'compress can not be set '\n                    'if Content-Encoding header is set')\n        elif self.compress:\n            if not isinstance(self.compress, str):\n                self.compress = 'deflate'\n            self.headers[hdrs.CONTENT_ENCODING] = self.compress\n            self.chunked = True",
    "docstring": "Set request content encoding."
  },
  {
    "code": "def find_op_code_sequence(pattern: list, instruction_list: list) -> Generator:\n    for i in range(0, len(instruction_list) - len(pattern) + 1):\n        if is_sequence_match(pattern, instruction_list, i):\n            yield i",
    "docstring": "Returns all indices in instruction_list that point to instruction\n    sequences following a pattern.\n\n    :param pattern: The pattern to look for, e.g. [[\"PUSH1\", \"PUSH2\"], [\"EQ\"]] where [\"PUSH1\", \"EQ\"] satisfies pattern\n    :param instruction_list: List of instructions to look in\n    :return: Indices to the instruction sequences"
  },
  {
    "code": "def detailed_tokens(tokenizer, text):\n    node = tokenizer.parseToNode(text)\n    node = node.next\n    words = []\n    while node.posid != 0:\n        surface = node.surface\n        base = surface\n        parts = node.feature.split(\",\")\n        pos = \",\".join(parts[0:4])\n        if len(parts) > 7:\n            base = parts[7]\n        words.append(ShortUnitWord(surface, base, pos))\n        node = node.next\n    return words",
    "docstring": "Format Mecab output into a nice data structure, based on Janome."
  },
  {
    "code": "def SamplingRoundAddedEventHandler(instance, event):\n    if instance.portal_type != \"SamplingRound\":\n        print(\"How does this happen: type is %s should be SamplingRound\" % instance.portal_type)\n        return\n    renameAfterCreation(instance)\n    num_art = len(instance.ar_templates)\n    destination_url = instance.aq_parent.absolute_url() + \\\n                    \"/portal_factory/\" + \\\n                    \"AnalysisRequest/Request new analyses/ar_add?samplinground=\" + \\\n                    instance.UID() + \"&ar_count=\" + str(num_art)\n    request = getattr(instance, 'REQUEST', None)\n    request.response.redirect(destination_url)",
    "docstring": "Event fired when BikaSetup object gets modified.\n        Since Sampling Round is a dexterity object we have to change the ID by \"hand\"\n        Then we have to redirect the user to the ar add form"
  },
  {
    "code": "def forward(self, inputs, label, begin_state, sampled_values):\n        encoded = self.embedding(inputs)\n        length = inputs.shape[0]\n        batch_size = inputs.shape[1]\n        encoded, out_states = self.encoder.unroll(length, encoded, begin_state,\n                                                  layout='TNC', merge_outputs=True)\n        out, new_target = self.decoder(encoded, sampled_values, label)\n        out = out.reshape((length, batch_size, -1))\n        new_target = new_target.reshape((length, batch_size))\n        return out, out_states, new_target",
    "docstring": "Defines the forward computation.\n\n        Parameters\n        -----------\n        inputs : NDArray\n            input tensor with shape `(sequence_length, batch_size)`\n            when `layout` is \"TNC\".\n        begin_state : list\n            initial recurrent state tensor with length equals to num_layers*2.\n            For each layer the two initial states have shape `(batch_size, num_hidden)`\n            and `(batch_size, num_projection)`\n        sampled_values : list\n            a list of three tensors for `sampled_classes` with shape `(num_samples,)`,\n            `expected_count_sampled` with shape `(num_samples,)`, and\n            `expected_count_true` with shape `(sequence_length, batch_size)`.\n\n        Returns\n        --------\n        out : NDArray\n            output tensor with shape `(sequence_length, batch_size, 1+num_samples)`\n            when `layout` is \"TNC\".\n        out_states : list\n            output recurrent state tensor with length equals to num_layers*2.\n            For each layer the two initial states have shape `(batch_size, num_hidden)`\n            and `(batch_size, num_projection)`\n        new_target : NDArray\n            output tensor with shape `(sequence_length, batch_size)`\n            when `layout` is \"TNC\"."
  },
  {
    "code": "def network_undefine(name, **kwargs):\n    conn = __get_conn(**kwargs)\n    try:\n        net = conn.networkLookupByName(name)\n        return not bool(net.undefine())\n    finally:\n        conn.close()",
    "docstring": "Remove a defined virtual network. This does not stop the virtual network.\n\n    :param name: virtual network name\n    :param connection: libvirt connection URI, overriding defaults\n    :param username: username to connect with, overriding defaults\n    :param password: password to connect with, overriding defaults\n\n    .. versionadded:: 2019.2.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' virt.network_undefine default"
  },
  {
    "code": "def get_path(self):\n        md5_hash = hashlib.md5(self.task_id.encode()).hexdigest()\n        logger.debug('Hash %s corresponds to task %s', md5_hash, self.task_id)\n        return os.path.join(self.temp_dir, str(self.unique.value), md5_hash)",
    "docstring": "Returns a temporary file path based on a MD5 hash generated with the task's name and its arguments"
  },
  {
    "code": "def queue_command(self, command):\n        if self._running:\n            QtCore.QCoreApplication.postEvent(\n                self, ActionEvent(command), QtCore.Qt.LowEventPriority)\n        else:\n            self._incoming.append(command)",
    "docstring": "Put a command on the queue to be called in the component's\n        thread.\n\n        :param callable command: the method to be invoked, e.g.\n            :py:meth:`~Component.new_frame_event`."
  },
  {
    "code": "def _read_with_mask(raster, masked):\n        if masked is None:\n            mask_flags = raster.mask_flag_enums\n            per_dataset_mask = all([rasterio.enums.MaskFlags.per_dataset in flags for flags in mask_flags])\n            masked = per_dataset_mask\n        return masked",
    "docstring": "returns if we should read from rasterio using the masked"
  },
  {
    "code": "def parse_date(date: str, hour_threshold: int = 200):\n    date = date.strip('Z')\n    if len(date) == 4:\n        date += '00'\n    if not (len(date) == 6 and date.isdigit()):\n        return\n    now = datetime.utcnow()\n    guess = now.replace(day=int(date[0:2]),\n                        hour=int(date[2:4]) % 24,\n                        minute=int(date[4:6]) % 60,\n                        second=0, microsecond=0)\n    hourdiff = (guess - now) / timedelta(minutes=1) / 60\n    if hourdiff > hour_threshold:\n        guess += relativedelta(months=-1)\n    elif hourdiff < -hour_threshold:\n        guess += relativedelta(months=+1)\n    return guess",
    "docstring": "Parses a report timestamp in ddhhZ or ddhhmmZ format\n\n    This function assumes the given timestamp is within the hour threshold from current date"
  },
  {
    "code": "def _unicode_sub_super(string, mapping, max_len=None):\n    string = str(string)\n    if string.startswith('(') and string.endswith(')'):\n        len_string = len(string) - 2\n    else:\n        len_string = len(string)\n    if max_len is not None:\n        if len_string > max_len:\n            raise KeyError(\"max_len exceeded\")\n    unicode_letters = []\n    for letter in string:\n        unicode_letters.append(mapping[letter])\n    return ''.join(unicode_letters)",
    "docstring": "Try to render a subscript or superscript string in unicode, fall back on\n    ascii if this is not possible"
  },
  {
    "code": "def function_to_serializable_representation(fn):\n    if type(fn) not in (FunctionType, BuiltinFunctionType):\n        raise ValueError(\n            \"Can't serialize %s : %s, must be globally defined function\" % (\n                fn, type(fn),))\n    if hasattr(fn, \"__closure__\") and fn.__closure__ is not None:\n        raise ValueError(\"No serializable representation for closure %s\" % (fn,))\n    return {\"__module__\": get_module_name(fn), \"__name__\": fn.__name__}",
    "docstring": "Converts a Python function into a serializable representation. Does not\n    currently work for methods or functions with closure data."
  },
  {
    "code": "def weighting(self, landscape=None):\n        if landscape is not None:\n            if len(landscape) > 0:\n                maxy = np.max(landscape[:, 1])\n            else: \n                maxy = 1\n        def linear(interval):\n            d = interval[1]\n            return (1 / maxy) * d if landscape is not None else d\n        def pw_linear(interval):\n            t = interval[1]\n            b = maxy / self.ny\n            if t <= 0:\n                return 0\n            if 0 < t < b:\n                return t / b\n            if b <= t:\n                return 1\n        return linear",
    "docstring": "Define a weighting function, \n                for stability results to hold, the function must be 0 at y=0."
  },
  {
    "code": "def from_name(cls, name):\n        result = cls.list({'items_per_page': 500})\n        webaccs = {}\n        for webacc in result:\n            webaccs[webacc['name']] = webacc['id']\n        return webaccs.get(name)",
    "docstring": "Retrieve webacc id associated to a webacc name."
  },
  {
    "code": "def set_config(self, config):\n    if self.config is None:\n      self.config = { }\n    self.config.update(config_to_api_list(config))",
    "docstring": "Set the service configuration.\n\n    @param config: A dictionary of config key/value"
  },
  {
    "code": "def tnet_to_nx(df, t=None):\n    if t is not None:\n        df = get_network_when(df, t=t)\n    if 'weight' in df.columns:\n        nxobj = nx.from_pandas_edgelist(\n            df, source='i', target='j', edge_attr='weight')\n    else:\n        nxobj = nx.from_pandas_edgelist(df, source='i', target='j')\n    return nxobj",
    "docstring": "Creates undirected networkx object"
  },
  {
    "code": "def get_substances(identifier, namespace='sid', as_dataframe=False, **kwargs):\n    results = get_json(identifier, namespace, 'substance', **kwargs)\n    substances = [Substance(r) for r in results['PC_Substances']] if results else []\n    if as_dataframe:\n        return substances_to_frame(substances)\n    return substances",
    "docstring": "Retrieve the specified substance records from PubChem.\n\n    :param identifier: The substance identifier to use as a search query.\n    :param namespace: (optional) The identifier type, one of sid, name or sourceid/<source name>.\n    :param as_dataframe: (optional) Automatically extract the :class:`~pubchempy.Substance` properties into a pandas\n                         :class:`~pandas.DataFrame` and return that."
  },
  {
    "code": "def _ConvertAttributeContainerToDict(cls, attribute_container):\n    if not isinstance(\n        attribute_container, containers_interface.AttributeContainer):\n      raise TypeError('{0:s} is not an attribute container type.'.format(\n          type(attribute_container)))\n    container_type = getattr(attribute_container, 'CONTAINER_TYPE', None)\n    if not container_type:\n      raise ValueError('Unsupported attribute container type: {0:s}.'.format(\n          type(attribute_container)))\n    json_dict = {\n        '__type__': 'AttributeContainer',\n        '__container_type__': container_type,\n    }\n    for attribute_name, attribute_value in attribute_container.GetAttributes():\n      json_dict[attribute_name] = cls._ConvertAttributeValueToDict(\n          attribute_value)\n    return json_dict",
    "docstring": "Converts an attribute container object into a JSON dictionary.\n\n    The resulting dictionary of the JSON serialized objects consists of:\n    {\n        '__type__': 'AttributeContainer'\n        '__container_type__': ...\n        ...\n    }\n\n    Here '__type__' indicates the object base type. In this case\n    'AttributeContainer'.\n\n    '__container_type__' indicates the container type and rest of the elements\n    of the dictionary make up the attributes of the container.\n\n    Args:\n      attribute_container (AttributeContainer): attribute container.\n\n    Returns:\n      dict[str, object]: JSON serialized objects.\n\n    Raises:\n      TypeError: if not an instance of AttributeContainer.\n      ValueError: if the attribute container type is not supported."
  },
  {
    "code": "def burst_range(psd, snr=8, energy=1e-2, fmin=100, fmax=500):\n    freqs = psd.frequencies.value\n    if not fmin:\n        fmin = psd.f0\n    if not fmax:\n        fmax = psd.span[1]\n    condition = (freqs >= fmin) & (freqs < fmax)\n    integrand = burst_range_spectrum(\n        psd[condition], snr=snr, energy=energy) ** 3\n    result = integrate.trapz(integrand.value, freqs[condition])\n    r = units.Quantity(result / (fmax - fmin), unit=integrand.unit) ** (1/3.)\n    return r.to('Mpc')",
    "docstring": "Calculate the integrated GRB-like GW burst range from a strain PSD\n\n    Parameters\n    ----------\n    psd : `~gwpy.frequencyseries.FrequencySeries`\n        the instrumental power-spectral-density data\n\n    snr : `float`, optional\n        the signal-to-noise ratio for which to calculate range,\n        default: ``8``\n\n    energy : `float`, optional\n        the relative energy output of the GW burst, defaults to ``1e-2``\n        for a GRB-like burst\n\n    fmin : `float`, optional\n        the lower frequency cutoff of the burst range integral,\n        default: ``100 Hz``\n\n    fmax : `float`, optional\n        the upper frequency cutoff of the burst range integral,\n        default: ``500 Hz``\n\n    Returns\n    -------\n    range : `~astropy.units.Quantity`\n        the GRB-like-burst sensitive range [Mpc (default)]\n\n    Examples\n    --------\n    Grab some data for LIGO-Livingston around GW150914 and generate a PSD\n\n    >>> from gwpy.timeseries import TimeSeries\n    >>> hoft = TimeSeries.fetch_open_data('H1', 1126259446, 1126259478)\n    >>> hoff = hoft.psd(fftlength=4)\n\n    Now we can calculate the :func:`burst_range`:\n\n    >>> from gwpy.astro import burst_range\n    >>> r = burst_range(hoff, fmin=30)\n    >>> print(r)\n    42.5055584195 Mpc"
  },
  {
    "code": "def int_dp_g(arr, dp):\n    return integrate(arr, to_pascal(dp, is_dp=True),\n                     vert_coord_name(dp)) / GRAV_EARTH",
    "docstring": "Mass weighted integral."
  },
  {
    "code": "def add_nodes(self, coors, node_low_or_high=None):\n        last = self.lastnode\n        if type(coors) is nm.ndarray:\n            if len(coors.shape) == 1:\n                coors = coors.reshape((1, coors.size))\n            nadd = coors.shape[0]\n            idx = slice(last, last + nadd)\n        else:\n            nadd = 1\n            idx = self.lastnode\n        right_dimension = coors.shape[1]\n        self.nodes[idx, :right_dimension] = coors\n        self.node_flag[idx] = True\n        self.lastnode += nadd\n        self.nnodes += nadd",
    "docstring": "Add new nodes at the end of the list."
  },
  {
    "code": "def dropout_mask(x:Tensor, sz:Collection[int], p:float):\n    \"Return a dropout mask of the same type as `x`, size `sz`, with probability `p` to cancel an element.\"\n    return x.new(*sz).bernoulli_(1-p).div_(1-p)",
    "docstring": "Return a dropout mask of the same type as `x`, size `sz`, with probability `p` to cancel an element."
  },
  {
    "code": "def declare_config_variable(self, name, config_id, type_name, default=None, convert=None):\n        config = ConfigDescriptor(config_id, type_name, default, name=name, python_type=convert)\n        self._config_variables[config_id] = config",
    "docstring": "Declare a config variable that this emulated tile accepts.\n\n        The default value (if passed) may be specified as either a `bytes`\n        object or a python int or list of ints.  If an int or list of ints is\n        passed, it is converted to binary.  Otherwise, the raw binary data is\n        used.\n\n        Passing a unicode string is only allowed if as_string is True and it\n        will be encoded as utf-8 and null terminated for use as a default value.\n\n        Args:\n            name (str): A user friendly name for this config variable so that it can\n                be printed nicely.\n            config_id (int): A 16-bit integer id number to identify the config variable.\n            type_name (str): An encoded type name that will be parsed by parse_size_name()\n            default (object): The default value if there is one.  This should be a\n                python object that will be converted to binary according to the rules for\n                the config variable type specified in type_name.\n            convert (str): whether this variable should be converted to a\n                python string or bool rather than an int or a list of ints.  You can\n                pass either 'bool', 'string' or None"
  },
  {
    "code": "def attr_to_path(node):\n    def get_intrinsic_path(modules, attr):\n        if isinstance(attr, ast.Name):\n            return modules[demangle(attr.id)], (demangle(attr.id),)\n        elif isinstance(attr, ast.Attribute):\n            module, path = get_intrinsic_path(modules, attr.value)\n            return module[attr.attr], path + (attr.attr,)\n    obj, path = get_intrinsic_path(MODULES, node)\n    if not obj.isliteral():\n        path = path[:-1] + ('functor', path[-1])\n    return obj, ('pythonic', ) + path",
    "docstring": "Compute path and final object for an attribute node"
  },
  {
    "code": "def get_authorizations_by_ids(self, authorization_ids):\n        collection = JSONClientValidated('authorization',\n                                         collection='Authorization',\n                                         runtime=self._runtime)\n        object_id_list = []\n        for i in authorization_ids:\n            object_id_list.append(ObjectId(self._get_id(i, 'authorization').get_identifier()))\n        result = collection.find(\n            dict({'_id': {'$in': object_id_list}},\n                 **self._view_filter()))\n        result = list(result)\n        sorted_result = []\n        for object_id in object_id_list:\n            for object_map in result:\n                if object_map['_id'] == object_id:\n                    sorted_result.append(object_map)\n                    break\n        return objects.AuthorizationList(sorted_result, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets an ``AuthorizationList`` corresponding to the given ``IdList``.\n\n        In plenary mode, the returned list contains all of the\n        authorizations specified in the ``Id`` list, in the order of the\n        list, including duplicates, or an error results if an ``Id`` in\n        the supplied list is not found or inaccessible. Otherwise,\n        inaccessible ``Authorizations`` may be omitted from the list and\n        may present the elements in any order including returning a\n        unique set.\n\n        arg:    authorization_ids (osid.id.IdList): the list of ``Ids``\n                to retrieve\n        return: (osid.authorization.AuthorizationList) - the returned\n                ``Authorization list``\n        raise:  NotFound - an ``Id was`` not found\n        raise:  NullArgument - ``authorization_ids`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def has_scope(context=None):\n    if not booted(context):\n        return False\n    _sd_version = version(context)\n    if _sd_version is None:\n        return False\n    return _sd_version >= 205",
    "docstring": "Scopes were introduced in systemd 205, this function returns a boolean\n    which is true when the minion is systemd-booted and running systemd>=205."
  },
  {
    "code": "def read(self, document, iface, *args, **kwargs):\n        try:\n            document = IReadableDocument(document)\n            mime_type = document.mime_type\n            reader = self.lookup_reader(mime_type, iface)\n            if not reader:\n                msg = (\"No adapter found to read object %s from %s document\"\n                       % (iface.__class__.__name__, mime_type))\n                raise NoReaderFoundError(msg)\n            return reader.read(document, *args, **kwargs)\n        except:\n            return defer.fail(Failure())",
    "docstring": "Returns a Deferred that fire the read object."
  },
  {
    "code": "def AgregarReceptor(self, cuit, iibb, nro_socio, nro_fet, **kwargs):\n        \"Agrego un receptor a la liq.\"\n        rcpt = dict(cuit=cuit, iibb=iibb, nroSocio=nro_socio, nroFET=nro_fet)\n        self.solicitud['receptor'] = rcpt\n        return True",
    "docstring": "Agrego un receptor a la liq."
  },
  {
    "code": "def strip_HETATMs(self, only_strip_these_chains = []):\n        if only_strip_these_chains:\n            self.lines = [l for l in self.lines if not(l.startswith('HETATM')) or l[21] not in only_strip_these_chains]\n        else:\n            self.lines = [l for l in self.lines if not(l.startswith('HETATM'))]\n        self._update_structure_lines()",
    "docstring": "Throw away all HETATM lines. If only_strip_these_chains is specified then only strip HETATMs lines for those chains."
  },
  {
    "code": "def contact_methods(self, **kwargs):\n        endpoint = '{0}/{1}/contact_methods'.format(\n            self.endpoint,\n            self['id'],\n        )\n        result = self.request('GET', endpoint=endpoint, query_params=kwargs)\n        return result['contact_methods']",
    "docstring": "Get all contact methods for this user."
  },
  {
    "code": "def transform(self, X=None, y=None):\n        zoom_x, zoom_y= self.zoom\n        self.params = (zoom_x, zoom_y)\n        zoom_matrix = np.array([[zoom_x, 0, 0],\n                                [0, zoom_y, 0]])\n        self.tx.set_parameters(zoom_matrix)\n        if self.lazy or X is None:\n            return self.tx\n        else:\n            return self.tx.apply_to_image(X, reference=self.reference)",
    "docstring": "Transform an image using an Affine transform with the given\n        zoom parameters.   Return the transform if X=None.\n\n        Arguments\n        ---------\n        X : ANTsImage\n            Image to transform\n\n        y : ANTsImage (optional)\n            Another image to transform\n\n        Returns\n        -------\n        ANTsImage if y is None, else a tuple of ANTsImage types\n\n        Examples\n        --------\n        >>> import ants\n        >>> img = ants.image_read(ants.get_data('r16'))\n        >>> tx = ants.contrib.Zoom2D(zoom=(0.8,0.8,0.8))\n        >>> img2 = tx.transform(img)"
  },
  {
    "code": "def issequence(arg):\n    string_behaviour = (\n        isinstance(arg, six.string_types) or\n        isinstance(arg, six.text_type))\n    list_behaviour = hasattr(arg, '__getitem__') or hasattr(arg, '__iter__')\n    return not string_behaviour and list_behaviour",
    "docstring": "Return True if `arg` acts as a list and does not look like a string."
  },
  {
    "code": "def put_name(self, type_, id_, name):\n        cachefile = self.filename(type_, id_)\n        dirname = os.path.dirname(cachefile)\n        try:\n            os.makedirs(dirname)\n        except OSError as e:\n            if e.errno != errno.EEXIST:\n                raise\n        with open(cachefile, 'w') as f:\n            f.write(name)",
    "docstring": "Write a cached name to disk.\n\n        :param type_: str, \"user\" or \"tag\"\n        :param id_: int, eg. 123456\n        :returns: None"
  },
  {
    "code": "def get_ip6_address(interface_name, expand=False):\n    address = _get_address(interface_name, IP6_PATTERN)\n    if address and expand:\n        return ':'.join(_expand_groups(address))\n    return address",
    "docstring": "Extracts the IPv6 address for a particular interface from `ifconfig`.\n\n    :param interface_name: Name of the network interface (e.g. ``eth0``).\n    :type interface_name: unicode\n    :param expand: If set to ``True``, an abbreviated address is expanded to the full address.\n    :type expand: bool\n    :return: IPv6 address; ``None`` if the interface is present but no address could be extracted.\n    :rtype: unicode"
  },
  {
    "code": "def close(self):\n        if self._socket is not None and self._conn is not None:\n            message_input = UnityMessage()\n            message_input.header.status = 400\n            self._communicator_send(message_input.SerializeToString())\n        if self._socket is not None:\n            self._socket.close()\n            self._socket = None\n        if self._socket is not None:\n            self._conn.close()\n            self._conn = None",
    "docstring": "Sends a shutdown signal to the unity environment, and closes the socket connection."
  },
  {
    "code": "def get_remote_file(self, remote_path, local_path):\n        sftp_client = self.transport.open_sftp_client()\n        LOG.debug('Get the remote file. '\n                  'Source=%(src)s. Target=%(target)s.' %\n                  {'src': remote_path, 'target': local_path})\n        try:\n            sftp_client.get(remote_path, local_path)\n        except Exception as ex:\n            LOG.error('Failed to secure copy. Reason: %s.' %\n                      six.text_type(ex))\n            raise SFtpExecutionError(err=ex)",
    "docstring": "Fetch remote File.\n\n        :param remote_path: remote path\n        :param local_path: local path"
  },
  {
    "code": "def GetAll(alias=None,location=None,session=None):\n\t\tif not alias:  alias = clc.v2.Account.GetAlias(session=session)\n\t\tpolicies = []\n\t\tpolicy_resp = clc.v2.API.Call('GET','antiAffinityPolicies/%s' % alias,{},session=session)\n\t\tfor k in policy_resp:\n\t\t\tr_val = policy_resp[k]\n\t\t\tfor r in r_val:\n\t\t\t\tif r.get('location'):\n\t\t\t\t\tif location and r['location'].lower()!=location.lower():  continue\n\t\t\t\t\tservers = [obj['id'] for obj in r['links'] if obj['rel'] == \"server\"]\n\t\t\t\t\tpolicies.append(AntiAffinity(id=r['id'],name=r['name'],location=r['location'],servers=servers,session=session))\n\t\treturn(policies)",
    "docstring": "Gets a list of anti-affinity policies within a given account.\n\n\t\thttps://t3n.zendesk.com/entries/44657214-Get-Anti-Affinity-Policies\n\n\t\t>>> clc.v2.AntiAffinity.GetAll()\n\t\t[<clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65e910>, <clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65ec90>]"
  },
  {
    "code": "def generateCertificate(self, alias,\n                            commonName, organizationalUnit,\n                            city, state, country,\n                            keyalg=\"RSA\", keysize=1024,\n                            sigalg=\"SHA256withRSA\",\n                            validity=90\n                            ):\n        params = {\"f\" : \"json\",\n                  \"alias\" : alias,\n                  \"commonName\" : commonName,\n                  \"organizationalUnit\" : organizationalUnit,\n                  \"city\" : city,\n                  \"state\" : state,\n                  \"country\" : country,\n                  \"keyalg\" : keyalg,\n                  \"keysize\" : keysize,\n                  \"sigalg\" : sigalg,\n                  \"validity\" : validity\n                  }\n        url = self._url + \"/SSLCertificate/ generateCertificate\"\n        return self._post(url=url,\n                          param_dict=params,\n                          proxy_port=self._proxy_port,\n                          proxy_url=self._proxy_url)",
    "docstring": "Use this operation to create a self-signed certificate or as a\n        starting point for getting a production-ready CA-signed\n        certificate. The portal will generate a certificate for you and\n        store it in its keystore."
  },
  {
    "code": "def _fetch_dimensions(self, dataset):\n        yield Dimension(u\"school\")\n        yield Dimension(u\"year\",\n                        datatype=\"year\")\n        yield Dimension(u\"semester\",\n                        datatype=\"academic_term\",\n                        dialect=\"swedish\")\n        yield Dimension(u\"municipality\",\n                        datatype=\"year\",\n                        domain=\"sweden/municipalities\")",
    "docstring": "Iterate through semesters, counties and municipalities."
  },
  {
    "code": "def _handle_config(self, data):\n        self.room.config.update(data)\n        self.conn.enqueue_data(\"config\", data)",
    "docstring": "Handle initial config push and config changes"
  },
  {
    "code": "def pkg_supports(feature, pkg_version, pkg_feat_dict):\n    from pkg_resources import parse_requirements\n    feature = str(feature)\n    pkg_version = str(pkg_version)\n    supp_versions = pkg_feat_dict.get(feature, None)\n    if supp_versions is None:\n        return False\n    if is_string(supp_versions):\n        supp_versions = [supp_versions]\n    ver_specs = ['pkg' + supp_ver for supp_ver in supp_versions]\n    ver_reqs = [list(parse_requirements(ver_spec))[0]\n                for ver_spec in ver_specs]\n    for req in ver_reqs:\n        if req.specifier.contains(pkg_version, prereleases=True):\n            return True\n    return False",
    "docstring": "Return bool indicating whether a package supports ``feature``.\n\n    Parameters\n    ----------\n    feature : str\n        Name of a potential feature of a package.\n    pkg_version : str\n        Version of the package that should be checked for presence of the\n        feature.\n    pkg_feat_dict : dict\n        Specification of features of a package. Each item has the\n        following form::\n\n            feature_name: version_specification\n\n        Here, ``feature_name`` is a string that is matched against\n        ``feature``, and ``version_specification`` is a string or a\n        sequence of strings that specifies version sets. These\n        specifications are the same as for ``setuptools`` requirements,\n        just without the package name.\n        A ``None`` entry signals \"no support in any version\", i.e.,\n        always ``False``.\n        If a sequence of requirements are given, they are OR-ed together.\n        See ``Examples`` for details.\n\n    Returns\n    -------\n    supports : bool\n        ``True`` if ``pkg_version`` of the package in question supports\n        ``feature``, ``False`` otherwise.\n\n    Examples\n    --------\n    >>> feat_dict = {\n    ...     'feat1': '==0.5.1',\n    ...     'feat2': '>0.6, <=0.9',  # both required simultaneously\n    ...     'feat3': ['>0.6', '<=0.9'],  # only one required, i.e. always True\n    ...     'feat4': ['==0.5.1', '>0.6, <=0.9'],\n    ...     'feat5': None\n    ... }\n    >>> pkg_supports('feat1', '0.5.1', feat_dict)\n    True\n    >>> pkg_supports('feat1', '0.4', feat_dict)\n    False\n    >>> pkg_supports('feat2', '0.5.1', feat_dict)\n    False\n    >>> pkg_supports('feat2', '0.6.1', feat_dict)\n    True\n    >>> pkg_supports('feat2', '0.9', feat_dict)\n    True\n    >>> pkg_supports('feat2', '1.0', feat_dict)\n    False\n    >>> pkg_supports('feat3', '0.4', feat_dict)\n    True\n    >>> pkg_supports('feat3', '1.0', feat_dict)\n    True\n    >>> pkg_supports('feat4', '0.5.1', feat_dict)\n    True\n    >>> pkg_supports('feat4', '0.6', feat_dict)\n    False\n    >>> pkg_supports('feat4', '0.6.1', feat_dict)\n    True\n    >>> pkg_supports('feat4', '1.0', feat_dict)\n    False\n    >>> pkg_supports('feat5', '0.6.1', feat_dict)\n    False\n    >>> pkg_supports('feat5', '1.0', feat_dict)\n    False"
  },
  {
    "code": "def configured_class(cls):\n        base = cls.configurable_base()\n        if base.__dict__.get('_Configurable__impl_class') is None:\n            base.__impl_class = cls.configurable_default()\n        return base.__impl_class",
    "docstring": "Returns the currently configured class."
  },
  {
    "code": "def _start_srv_proc(self,\n                        started_os_proc):\n        log.debug('Starting the server process')\n        server = NapalmLogsServerProc(self.opts,\n                                      self.config_dict,\n                                      started_os_proc,\n                                      buffer=self._buffer)\n        proc = Process(target=server.start)\n        proc.start()\n        proc.description = 'Server process'\n        log.debug('Started server process as %s with PID %s', proc._name, proc.pid)\n        return proc",
    "docstring": "Start the server process."
  },
  {
    "code": "def progress_patch(self, _=False):\n        from .progress import ShellProgressView\n        self.cli_ctx.progress_controller.init_progress(ShellProgressView())\n        return self.cli_ctx.progress_controller",
    "docstring": "forces to use the Shell Progress"
  },
  {
    "code": "def _threaded_copy_data(instream, outstream):\n    copy_thread = threading.Thread(target=_copy_data,\n                                   args=(instream, outstream))\n    copy_thread.setDaemon(True)\n    log.debug('%r, %r, %r', copy_thread, instream, outstream)\n    copy_thread.start()\n    return copy_thread",
    "docstring": "Copy data from one stream to another in a separate thread.\n\n    Wraps ``_copy_data()`` in a :class:`threading.Thread`.\n\n    :type instream: :class:`io.BytesIO` or :class:`io.StringIO`\n    :param instream: A byte stream to read from.\n    :param file outstream: The file descriptor of a tmpfile to write to."
  },
  {
    "code": "def _get_params(self):\n        return np.hstack((self.varianceU,self.varianceY, self.lengthscaleU,self.lengthscaleY))",
    "docstring": "return the value of the parameters."
  },
  {
    "code": "def handle_onchain_secretreveal(\n        initiator_state: InitiatorTransferState,\n        state_change: ContractReceiveSecretReveal,\n        channel_state: NettingChannelState,\n        pseudo_random_generator: random.Random,\n) -> TransitionResult[InitiatorTransferState]:\n    iteration: TransitionResult[InitiatorTransferState]\n    secret = state_change.secret\n    secrethash = initiator_state.transfer_description.secrethash\n    is_valid_secret = is_valid_secret_reveal(\n        state_change=state_change,\n        transfer_secrethash=secrethash,\n        secret=secret,\n    )\n    is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED\n    is_lock_expired = state_change.block_number > initiator_state.transfer.lock.expiration\n    is_lock_unlocked = (\n        is_valid_secret and\n        not is_lock_expired\n    )\n    if is_lock_unlocked:\n        channel.register_onchain_secret(\n            channel_state=channel_state,\n            secret=secret,\n            secrethash=secrethash,\n            secret_reveal_block_number=state_change.block_number,\n        )\n    if is_lock_unlocked and is_channel_open:\n        events = events_for_unlock_lock(\n            initiator_state,\n            channel_state,\n            state_change.secret,\n            state_change.secrethash,\n            pseudo_random_generator,\n        )\n        iteration = TransitionResult(None, events)\n    else:\n        events = list()\n        iteration = TransitionResult(initiator_state, events)\n    return iteration",
    "docstring": "When a secret is revealed on-chain all nodes learn the secret.\n\n    This check the on-chain secret corresponds to the one used by the\n    initiator, and if valid a new balance proof is sent to the next hop with\n    the current lock removed from the merkle tree and the transferred amount\n    updated."
  },
  {
    "code": "def stop(self):\n        self.logger.info('Stopping client fuzzer')\n        self._target_control_thread.stop()\n        self.target.signal_mutated()\n        super(ClientFuzzer, self).stop()",
    "docstring": "Stop the fuzzing session"
  },
  {
    "code": "def get_feed_renderer(engines, name):\n    if name not in engines:\n        raise FeedparserError(\"Given feed name '{}' does not exists in 'settings.FEED_RENDER_ENGINES'\".format(name))\n    renderer = safe_import_module(engines[name])\n    return renderer",
    "docstring": "From engine name, load the engine path and return the renderer class\n    \n    Raise 'FeedparserError' if any loading error"
  },
  {
    "code": "def remove_files(self):\n        file_list = [\"molecule.svg\",\"lig.pdb\",\"HIS.pdb\",\"PHE.pdb\",\"TRP.pdb\",\"TYR.pdb\",\"lig.mol\",\"test.xtc\"]\n        for residue in self.topol_data.dict_of_plotted_res.keys():\n            file_list.append(residue[1]+residue[2]+\".svg\")\n        for f in file_list:\n            if os.path.isfile(f)==True:\n                os.remove(f)",
    "docstring": "Removes intermediate files."
  },
  {
    "code": "def getAsWmsDatasetString(self, session):\n        FIRST_VALUE_INDEX = 12\n        if type(self.raster) != type(None):\n            valueGrassRasterString = self.getAsGrassAsciiGrid(session)\n            values = valueGrassRasterString.split()\n            wmsDatasetString = ''\n            for i in range(FIRST_VALUE_INDEX, len(values)):\n                wmsDatasetString += '{0:.6f}\\r\\n'.format(float(values[i]))\n            return wmsDatasetString\n        else:\n            wmsDatasetString = self.rasterText",
    "docstring": "Retrieve the WMS Raster as a string in the WMS Dataset format"
  },
  {
    "code": "def delete_tags(self, archive_name, tags):\n        updated_tag_list = list(self._get_tags(archive_name))\n        for tag in tags:\n            if tag in updated_tag_list:\n                updated_tag_list.remove(tag)\n        self._set_tags(archive_name, updated_tag_list)",
    "docstring": "Delete tags from an archive\n\n        Parameters\n        ----------\n        archive_name:s tr\n            Name of archive\n\n        tags: list or tuple of strings\n            tags to delete from the archive"
  },
  {
    "code": "def add_user(bridge_user):\n    resp = post_resource(admin_uid_url(None) +\n                         (\"?%s\" % CUSTOM_FIELD),\n                         json.dumps(bridge_user.to_json_post(),\n                                    separators=(',', ':')))\n    return _process_json_resp_data(resp, no_custom_fields=True)",
    "docstring": "Add the bridge_user given\n    Return a list of BridgeUser objects with custom fields"
  },
  {
    "code": "def get(self, path_or_index, default=None):\n        err, value = self._resolve(path_or_index)\n        value = default if err else value\n        return err, value",
    "docstring": "Get details about a given result\n\n        :param path_or_index: The path (or index) of the result to fetch.\n        :param default: If the given result does not exist, return this value\n            instead\n        :return: A tuple of `(error, value)`. If the entry does not exist\n            then `(err, default)` is returned, where `err` is the actual error\n            which occurred.\n            You can use :meth:`couchbase.exceptions.CouchbaseError.rc_to_exctype`\n            to convert the error code to a proper exception class\n        :raise: :exc:`IndexError` or :exc:`KeyError` if `path_or_index`\n            is not an initially requested path. This is a programming error\n            as opposed to a constraint error where the path is not found."
  },
  {
    "code": "def followers_org_count(self):\n        from udata.models import Follow\n        return sum(Follow.objects(following=org).count()\n                   for org in self.organizations)",
    "docstring": "Return the number of followers of user's organizations."
  },
  {
    "code": "def get(self, sid):\n        return CertificateContext(self._version, fleet_sid=self._solution['fleet_sid'], sid=sid, )",
    "docstring": "Constructs a CertificateContext\n\n        :param sid: A string that uniquely identifies the Certificate.\n\n        :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateContext\n        :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateContext"
  },
  {
    "code": "def updateSynapses(self, synapses, delta):\n    reached0 = False\n    if delta > 0:\n      for synapse in synapses:\n        self.syns[synapse][2] = newValue = self.syns[synapse][2] + delta\n        if newValue > self.tp.permanenceMax:\n          self.syns[synapse][2] = self.tp.permanenceMax\n    else:\n      for synapse in synapses:\n        self.syns[synapse][2] = newValue = self.syns[synapse][2] + delta\n        if newValue <= 0:\n          self.syns[synapse][2] = 0\n          reached0 = True\n    return reached0",
    "docstring": "Update a set of synapses in the segment.\n\n    @param tp       The owner TP\n    @param synapses List of synapse indices to update\n    @param delta    How much to add to each permanence\n\n    @returns   True if synapse reached 0"
  },
  {
    "code": "def guessImageMetadataFromData(img_data):\n    format, width, height = None, None, None\n    img_stream = io.BytesIO(img_data)\n    try:\n      img = PIL.Image.open(img_stream)\n    except IOError:\n      format = imghdr.what(None, h=img_data)\n      format = SUPPORTED_IMG_FORMATS.get(format, None)\n    else:\n      format = img.format.lower()\n      format = SUPPORTED_IMG_FORMATS.get(format, None)\n      width, height = img.size\n    return format, width, height",
    "docstring": "Identify an image format and size from its first bytes."
  },
  {
    "code": "def get_easter_monday(self, year):\n        \"Return the date of the monday after easter\"\n        sunday = self.get_easter_sunday(year)\n        return sunday + timedelta(days=1)",
    "docstring": "Return the date of the monday after easter"
  },
  {
    "code": "def sort_by_efficiency(self, reverse=True):\n        self._confs.sort(key=lambda c: c.efficiency, reverse=reverse)\n        return self",
    "docstring": "Sort the configurations in place. items with highest efficiency come first"
  },
  {
    "code": "def on_connection_closed(self, connection, reply_code, reply_text):\n        start_state = self.state\n        self.state = self.STATE_CLOSED\n        if self.on_unavailable:\n            self.on_unavailable(self)\n        self.connection = None\n        self.channel = None\n        if start_state != self.STATE_CLOSING:\n            LOGGER.warning('%s closed while %s: (%s) %s',\n                           connection, self.state_description,\n                           reply_code, reply_text)\n            self._reconnect()",
    "docstring": "This method is invoked by pika when the connection to RabbitMQ is\n        closed unexpectedly. Since it is unexpected, we will reconnect to\n        RabbitMQ if it disconnects.\n\n        :param pika.TornadoConnection connection: Closed connection\n        :param int reply_code: The server provided reply_code if given\n        :param str reply_text: The server provided reply_text if given"
  },
  {
    "code": "def _get_selectable(self):\n        cursong = self.loop[self.song][0]\n        if self.dif_song and len(cursong) > 1:\n            s = cursong[0] + cursong[1]\n        else:\n            s = cursong[-1]\n        return s",
    "docstring": "Used internally to get a group of choosable tracks."
  },
  {
    "code": "def _get_component_from_result(self, result, lookup):\n        for component in result['address_components']:\n            if lookup['type'] in component['types']:\n                return component.get(lookup['key'], '')\n        return ''",
    "docstring": "Helper function to get a particular address component from a Google result.\n\n        Since the address components in results are an array of objects containing a types array,\n        we have to search for a particular component rather than being able to look it up directly.\n\n        Returns the first match, so this should be used for unique component types (e.g.\n        'locality'), not for categories (e.g. 'political') that can describe multiple components.\n\n        :arg dict result: A results dict with an 'address_components' key, as returned by the\n                          Google geocoder.\n        :arg dict lookup: The type (e.g. 'street_number') and key ('short_name' or 'long_name') of\n                          the desired address component value.\n        :returns: address component or empty string"
  },
  {
    "code": "def set_colors(self, text='black', background='white'):\n        if self._multiline: self._widget.setStyleSheet(\"QTextEdit {background-color: \"+str(background)+\"; color: \"+str(text)+\"}\")\n        else:               self._widget.setStyleSheet(\"QLineEdit {background-color: \"+str(background)+\"; color: \"+str(text)+\"}\")",
    "docstring": "Sets the colors of the text area."
  },
  {
    "code": "def _extend_object(parent, n, o, otype, fqdn):\n    from inspect import ismodule, isclass\n    pmodule = parent if ismodule(parent) or isclass(parent) else None\n    try:\n        if otype == \"methods\":\n            setattr(o.__func__, \"__acornext__\", None)\n        else:\n            setattr(o, \"__acornext__\", None)\n        fqdn = _fqdn(o, recheck=True, pmodule=pmodule)\n        return o\n    except (TypeError, AttributeError):\n        okey = id(o)\n        if okey not in _extended_objs:\n            xobj = _create_extension(o, otype, fqdn, pmodule)\n            fqdn = _fqdn(xobj, recheck=True, pmodule=pmodule)\n            if xobj is not None:\n                _extended_objs[okey] = xobj\n        try:\n            setattr(parent, n, _extended_objs[okey])\n            return _extended_objs[okey]\n        except KeyError:\n            msg.warn(\"Object extension failed: {} ({}).\".format(o, otype))",
    "docstring": "Extends the specified object if it needs to be extended. The method\n    attempts to add an attribute to the object; if it fails, a new object is\n    created that inherits all of `o` attributes, but is now a regular object\n    that can have attributes set.\n\n    Args:\n        parent: has `n` in its `__dict__` attribute.\n        n (str): object name attribute.\n        o (list): object instances to be extended.\n        otype (str): object types; one of [\"classes\", \"functions\", \"methods\",\n          \"modules\"].\n        fqdn (str): fully qualified name of the package that the object belongs\n          to."
  },
  {
    "code": "def get_parents_letters(self, goobj):\n        parents_all = set.union(self.go2parents[goobj.id])\n        parents_all.add(goobj.id)\n        parents_d1 = parents_all.intersection(self.gos_depth1)\n        return [self.goone2ntletter[g].D1 for g in parents_d1]",
    "docstring": "Get the letters representing all parent terms which are depth-01 GO terms."
  },
  {
    "code": "def get_mute(self):\n        params = '<InstanceID>0</InstanceID><Channel>Master</Channel>'\n        res = self.soap_request(URL_CONTROL_DMR, URN_RENDERING_CONTROL,\n                                'GetMute', params)\n        root = ET.fromstring(res)\n        el_mute = root.find('.//CurrentMute')\n        return el_mute.text != '0'",
    "docstring": "Return if the TV is muted."
  },
  {
    "code": "def apply_rules(self, rules, recursive=True):\n        if recursive:\n            new_args = [_apply_rules(arg, rules) for arg in self.args]\n            new_kwargs = {\n                key: _apply_rules(val, rules)\n                for (key, val) in self.kwargs.items()}\n        else:\n            new_args = self.args\n            new_kwargs = self.kwargs\n        simplified = self.create(*new_args, **new_kwargs)\n        return _apply_rules_no_recurse(simplified, rules)",
    "docstring": "Rebuild the expression while applying a list of rules\n\n        The rules are applied against the instantiated expression, and any\n        sub-expressions if `recursive` is True. Rule application is best though\n        of as a pattern-based substitution. This is different from the\n        *automatic* rules that :meth:`create` uses (see :meth:`add_rule`),\n        which are applied *before* expressions are instantiated.\n\n        Args:\n            rules (list or ~collections.OrderedDict): List of rules or\n                dictionary mapping names to rules, where each rule is a tuple\n                (:class:`Pattern`, replacement callable), cf.\n                :meth:`apply_rule`\n            recursive (bool): If true (default), apply rules to all arguments\n                and keyword arguments of the expression. Otherwise, only the\n                expression itself will be re-instantiated.\n\n        If `rules` is a dictionary, the keys (rules names) are used only for\n        debug logging, to allow an analysis of which rules lead to the final\n        form of an expression."
  },
  {
    "code": "def _pigpio_aio_command(self, cmd,  p1, p2,):\n        with (yield from self._lock):\n            data = struct.pack('IIII', cmd, p1, p2, 0)\n            self._loop.sock_sendall(self.s, data)\n            response = yield from self._loop.sock_recv(self.s, 16)\n            _, res = struct.unpack('12sI', response)\n            return res",
    "docstring": "Runs a pigpio socket command.\n\n        sl:= command socket and lock.\n        cmd:= the command to be executed.\n        p1:= command parameter 1 (if applicable).\n         p2:=  command parameter 2 (if applicable)."
  },
  {
    "code": "def get_repo(self, auth, username, repo_name):\n        path = \"/repos/{u}/{r}\".format(u=username, r=repo_name)\n        response = self.get(path, auth=auth)\n        return GogsRepo.from_json(response.json())",
    "docstring": "Returns a the repository with name ``repo_name`` owned by\n        the user with username ``username``.\n\n        :param auth.Authentication auth: authentication object\n        :param str username: username of owner of repository\n        :param str repo_name: name of repository\n        :return: a representation of the retrieved repository\n        :rtype: GogsRepo\n        :raises NetworkFailure: if there is an error communicating with the server\n        :raises ApiFailure: if the request cannot be serviced"
  },
  {
    "code": "def sign_data(self, name, hash_input, key_version=None, hash_algorithm=\"sha2-256\", context=\"\", prehashed=False,\n                  signature_algorithm=\"pss\", mount_point=DEFAULT_MOUNT_POINT):\n        if hash_algorithm not in transit_constants.ALLOWED_HASH_DATA_ALGORITHMS:\n            error_msg = 'invalid hash_algorithm argument provided \"{arg}\", supported types: \"{allowed_types}\"'\n            raise exceptions.ParamValidationError(error_msg.format(\n                arg=hash_algorithm,\n                allowed_types=', '.join(transit_constants.ALLOWED_HASH_DATA_ALGORITHMS),\n            ))\n        if signature_algorithm not in transit_constants.ALLOWED_SIGNATURE_ALGORITHMS:\n            error_msg = 'invalid signature_algorithm argument provided \"{arg}\", supported types: \"{allowed_types}\"'\n            raise exceptions.ParamValidationError(error_msg.format(\n                arg=signature_algorithm,\n                allowed_types=', '.join(transit_constants.ALLOWED_SIGNATURE_ALGORITHMS),\n            ))\n        params = {\n            'input': hash_input,\n            'key_version': key_version,\n            'hash_algorithm': hash_algorithm,\n            'context': context,\n            'prehashed': prehashed,\n            'signature_algorithm': signature_algorithm,\n        }\n        api_path = '/v1/{mount_point}/sign/{name}'.format(\n            mount_point=mount_point,\n            name=name,\n        )\n        response = self._adapter.post(\n            url=api_path,\n            json=params,\n        )\n        return response.json()",
    "docstring": "Return the cryptographic signature of the given data using the named key and the specified hash algorithm.\n\n        The key must be of a type that supports signing.\n\n        Supported methods:\n            POST: /{mount_point}/sign/{name}(/{hash_algorithm}). Produces: 200 application/json\n\n        :param name: Specifies the name of the encryption key to use for signing. This is specified as part of the URL.\n        :type name: str | unicode\n        :param hash_input: Specifies the base64 encoded input data.\n        :type hash_input: str | unicode\n        :param key_version: Specifies the version of the key to use for signing. If not set, uses the latest version.\n            Must be greater than or equal to the key's min_encryption_version, if set.\n        :type key_version: int\n        :param hash_algorithm: Specifies the hash algorithm to use for supporting key types (notably, not including\n            ed25519 which specifies its own hash algorithm). This can also be specified as part of the URL.\n            Currently-supported algorithms are: sha2-224, sha2-256, sha2-384, sha2-512\n        :type hash_algorithm: str | unicode\n        :param context: Base64 encoded context for key derivation. Required if key derivation is enabled; currently only\n            available with ed25519 keys.\n        :type context: str | unicode\n        :param prehashed: Set to true when the input is already hashed. If the key type is rsa-2048 or rsa-4096, then\n            the algorithm used to hash the input should be indicated by the hash_algorithm parameter. Just as the value\n            to sign should be the base64-encoded representation of the exact binary data you want signed, when set, input\n            is expected to be base64-encoded binary hashed data, not hex-formatted. (As an example, on the command line,\n            you could generate a suitable input via openssl dgst -sha256 -binary | base64.)\n        :type prehashed: bool\n        :param signature_algorithm: When using a RSA key, specifies the RSA signature algorithm to use for signing.\n            Supported signature types are: pss, pkcs1v15\n        :type signature_algorithm: str | unicode\n        :param mount_point: The \"path\" the method/backend was mounted on.\n        :type mount_point: str | unicode\n        :return: The JSON response of the request.\n        :rtype: requests.Response"
  },
  {
    "code": "def parameters(self):\n        return self.block_tl, self.block_br, self.rows, self.cols, self.cells",
    "docstring": "Returns tuple of selection parameters of self\n\n        (self.block_tl, self.block_br, self.rows, self.cols, self.cells)"
  },
  {
    "code": "def fetch(url, binary, outfile, noprint, rendered):\n\twith chrome_context.ChromeContext(binary=binary) as cr:\n\t\tresp = cr.blocking_navigate_and_get_source(url)\n\t\tif rendered:\n\t\t\tresp['content'] = cr.get_rendered_page_source()\n\t\t\tresp['binary'] = False\n\t\t\tresp['mimie'] = 'text/html'\n\tif not noprint:\n\t\tif resp['binary'] is False:\n\t\t\tprint(resp['content'])\n\t\telse:\n\t\t\tprint(\"Response is a binary file\")\n\t\t\tprint(\"Cannot print!\")\n\tif outfile:\n\t\twith open(outfile, \"wb\") as fp:\n\t\t\tif resp['binary']:\n\t\t\t\tfp.write(resp['content'])\n\t\t\telse:\n\t\t\t\tfp.write(resp['content'].encode(\"UTF-8\"))",
    "docstring": "Fetch a specified URL's content, and output it to the console."
  },
  {
    "code": "def add_loss(self, loss, name=None, regularization=False, add_summaries=True):\n    _ = name\n    if regularization:\n      self._g.add_to_collection(GraphKeys.REGULARIZATION_LOSSES, loss)\n    tf.add_to_collection(GraphKeys.LOSSES, loss)\n    if add_summaries:\n      self.add_scalar_summary(loss, 'loss')\n      self.add_average_summary(loss, 'loss_average')",
    "docstring": "Append a loss to the total loss for the network.\n\n    Args:\n      loss: append this loss operation\n      name: The name for this loss, defaults to loss.op.name\n      regularization: Set to True if this is a regularization loss.\n      add_summaries: Set to True if you want to see scalar and average summary."
  },
  {
    "code": "def get_product_target_mappings_for_targets(self, targets):\n    product_target_mappings = []\n    for target in targets:\n      for product in self._products_by_target[target]:\n        product_target_mappings.append((product, target))\n    return product_target_mappings",
    "docstring": "Gets the product-target associations for the given targets, preserving the input order.\n\n    :API: public\n\n    :param targets: The targets to lookup products for.\n    :returns: The ordered (product, target) tuples."
  },
  {
    "code": "def ed25519_private_key_to_string(key):\n    return base64.b64encode(key.private_bytes(\n        encoding=serialization.Encoding.Raw,\n        format=serialization.PrivateFormat.Raw,\n        encryption_algorithm=serialization.NoEncryption()\n    ), None).decode('utf-8')",
    "docstring": "Convert an ed25519 private key to a base64-encoded string.\n\n    Args:\n        key (Ed25519PrivateKey): the key to write to the file.\n\n    Returns:\n        str: the key representation as a str"
  },
  {
    "code": "def custom_background_code():\n    while True:\n        logger.info(\"Block %s / %s\", str(Blockchain.Default().Height), str(Blockchain.Default().HeaderHeight))\n        sleep(15)",
    "docstring": "Custom code run in a background thread. Prints the current block height.\n\n    This function is run in a daemonized thread, which means it can be instantly killed at any\n    moment, whenever the main thread quits. If you need more safety, don't use a  daemonized\n    thread and handle exiting this thread in another way (eg. with signals and events)."
  },
  {
    "code": "def build_sequence(self, xs, masks, init, is_left_to_right):\n        states = []\n        last = init\n        if is_left_to_right:\n            for i, xs_i in enumerate(xs):\n                h = self.build(xs_i, last, masks[i])\n                states.append(h)\n                last = h\n        else:\n            for i in range(len(xs) - 1, -1, -1):\n                h = self.build(xs[i], last, masks[i])\n                states.insert(0, h)\n                last = h\n        return states",
    "docstring": "Build GRU sequence."
  },
  {
    "code": "def available_for_entry_point(self, entry_point):\n        if self.entry_point == ALL or entry_point == ALL:\n            return True\n        return entry_point in ensure_sequence(self.entry_point)",
    "docstring": "Check if the current function can be executed from a request to the given entry point"
  },
  {
    "code": "def mean_date(dt_list):\n    dt_list_sort = sorted(dt_list)\n    dt_list_sort_rel = [dt - dt_list_sort[0] for dt in dt_list_sort]\n    avg_timedelta = sum(dt_list_sort_rel, timedelta())/len(dt_list_sort_rel)\n    return dt_list_sort[0] + avg_timedelta",
    "docstring": "Calcuate mean datetime from datetime list"
  },
  {
    "code": "def correct_transition_matrix(T, reversible=None):\n    r\n    row_sums = T.sum(axis=1).A1\n    max_sum = np.max(row_sums)\n    if max_sum == 0.0:\n         max_sum = 1.0\n    return (T + scipy.sparse.diags(-row_sums+max_sum, 0)) / max_sum",
    "docstring": "r\"\"\"Normalize transition matrix\n\n    Fixes a the row normalization of a transition matrix.\n    To be used with the reversible estimators to fix an almost coverged\n    transition matrix.\n\n    Parameters\n    ----------\n    T : (M, M) ndarray\n        matrix to correct\n    reversible : boolean\n        for future use\n\n    Returns\n    -------\n    (M, M) ndarray\n        corrected transition matrix"
  },
  {
    "code": "def get_attributes(self):\n        attr = ['chr', 'start', 'stop']\n        if self.strandPos is not None:\n            attr.append('strand')\n        if self.otherPos:\n            for i, o in enumerate(self.otherPos):\n                attr.append(o[1])\n        return attr",
    "docstring": "Returns the unordered list of attributes\n\n        :return: list of strings"
  },
  {
    "code": "def _fetch_messages(self):\n        try:\n            [_, msg] = self.socket.recv_multipart(flags=zmq.NOBLOCK)\n            if Global.CONFIG_MANAGER.tracing_mode:\n                Global.LOGGER.debug(\"fetched a new message\")\n            self.fetched = self.fetched + 1\n            obj = pickle.loads(msg)\n            self._deliver_message(obj)\n            return obj\n        except zmq.error.Again:\n            return None\n        except Exception as new_exception:\n            Global.LOGGER.error(new_exception)\n            raise new_exception",
    "docstring": "Get an input message from the socket"
  },
  {
    "code": "def get_tags_of_offer_per_page(self, offer_id, per_page=1000, page=1):\n        return self._get_resource_per_page(\n            resource=OFFER_TAGS,\n            per_page=per_page,\n            page=page,\n            params={'offer_id': offer_id},\n        )",
    "docstring": "Get tags of offer per page\n\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :param offer_id: the offer id\n        :return: list"
  },
  {
    "code": "def node_coord_in_direction(tile_id, direction):\n    tile_coord = tile_id_to_coord(tile_id)\n    for node_coord in nodes_touching_tile(tile_id):\n        if tile_node_offset_to_direction(node_coord - tile_coord) == direction:\n            return node_coord\n    raise ValueError('No node found in direction={} at tile_id={}'.format(\n        direction,\n        tile_id\n    ))",
    "docstring": "Returns the node coordinate in the given direction at the given tile identifier.\n\n    :param tile_id: tile identifier, int\n    :param direction: direction, str\n    :return: node coord, int"
  },
  {
    "code": "def insert(self, storagemodel) -> StorageTableModel:\n        modeldefinition = self.getmodeldefinition(storagemodel, True)\n        try:\n            modeldefinition['tableservice'].insert_or_replace_entity(modeldefinition['tablename'], storagemodel.entity())\n            storagemodel._exists = True\n        except AzureMissingResourceHttpError as e:\n            storagemodel._exists = False\n            log.debug('can not insert or replace table entity:  Table {}, PartitionKey {}, RowKey {} because {!s}'.format(modeldefinition['tablename'], storagemodel.getPartitionKey(), storagemodel.getRowKey(), e))\n        except Exception as e:\n            storagemodel._exists = False\n            msg = 'can not insert or replace table entity:  Table {}, PartitionKey {}, RowKey {} because {!s}'.format(modeldefinition['tablename'], storagemodel.PartitionKey, storagemodel.RowKey, e)\n            raise AzureStorageWrapException(msg=msg)\n        finally:\n            return storagemodel",
    "docstring": "insert model into storage"
  },
  {
    "code": "def item(p_queue, queue_id, host=None):\n    if host is not None:\n        return os.path.join(_path(host, _c.FSQ_QUEUE, root=hosts(p_queue)),\n                            valid_name(queue_id))\n    return os.path.join(_path(p_queue, _c.FSQ_QUEUE), valid_name(queue_id))",
    "docstring": "Construct a path to a queued item"
  },
  {
    "code": "def update(cls, draft_share_invite_api_key_id, status=None, sub_status=None,\n               expiration=None, custom_headers=None):\n        if custom_headers is None:\n            custom_headers = {}\n        api_client = client.ApiClient(cls._get_api_context())\n        request_map = {\n            cls.FIELD_STATUS: status,\n            cls.FIELD_SUB_STATUS: sub_status,\n            cls.FIELD_EXPIRATION: expiration\n        }\n        request_map_string = converter.class_to_json(request_map)\n        request_map_string = cls._remove_field_for_request(request_map_string)\n        request_bytes = request_map_string.encode()\n        endpoint_url = cls._ENDPOINT_URL_UPDATE.format(cls._determine_user_id(),\n                                                       draft_share_invite_api_key_id)\n        response_raw = api_client.put(endpoint_url, request_bytes,\n                                      custom_headers)\n        return BunqResponseDraftShareInviteApiKey.cast_from_bunq_response(\n            cls._from_json(response_raw, cls._OBJECT_TYPE_PUT)\n        )",
    "docstring": "Update a draft share invite. When sending status CANCELLED it is\n        possible to cancel the draft share invite.\n\n        :type user_id: int\n        :type draft_share_invite_api_key_id: int\n        :param status: The status of the draft share invite. Can be CANCELLED\n        (the user cancels the draft share before it's used).\n        :type status: str\n        :param sub_status: The sub-status of the draft share invite. Can be\n        NONE, ACCEPTED or REJECTED.\n        :type sub_status: str\n        :param expiration: The moment when this draft share invite expires.\n        :type expiration: str\n        :type custom_headers: dict[str, str]|None\n\n        :rtype: BunqResponseDraftShareInviteApiKey"
  },
  {
    "code": "def detect(filename, include_confidence=False):\n    f = open(filename)\n    detection = chardet.detect(f.read())\n    f.close()\n    encoding = detection.get('encoding')\n    confidence = detection.get('confidence')\n    if include_confidence:\n        return (encoding, confidence)\n    return encoding",
    "docstring": "Detect the encoding of a file.\n\n    Returns only the predicted current encoding as a string.\n\n    If `include_confidence` is True, \n    Returns tuple containing: (str encoding, float confidence)"
  },
  {
    "code": "def get_request_filename(request):\n    if 'Content-Disposition' in request.info():\n        disposition = request.info()['Content-Disposition']\n        pieces = re.split(r'\\s*;\\s*', disposition)\n        for piece in pieces:\n            if piece.startswith('filename='):\n                filename = piece[len('filename='):]\n                if filename.startswith('\"'):\n                    filename = filename[1:]\n                if filename.endswith('\"'):\n                    filename = filename[:-1]\n                filename = filename.replace('\\\\\"', '\"')\n                return filename\n    return os.path.basename(urlsplit(request.url).path) or 'index.html'",
    "docstring": "Figure out the filename for an HTTP download."
  },
  {
    "code": "def _wait_for_new_tasks(self, timeout=0, batch_timeout=0):\n        new_queue_found = False\n        start_time = batch_exit = time.time()\n        while True:\n            if batch_exit > start_time:\n                pubsub_sleep = batch_exit - time.time()\n            else:\n                pubsub_sleep = start_time + timeout - time.time()\n            message = self._pubsub.get_message(timeout=0 if pubsub_sleep < 0 or\n                                               self._did_work\n                                               else pubsub_sleep)\n            while message:\n                if message['type'] == 'message':\n                    new_queue_found, batch_exit = self._process_queue_message(\n                        message['data'], new_queue_found, batch_exit,\n                        start_time, timeout, batch_timeout\n                    )\n                message = self._pubsub.get_message()\n            if self._did_work:\n                break\n            elif time.time() >= batch_exit and new_queue_found:\n                break\n            elif time.time() - start_time > timeout:\n                break",
    "docstring": "Check activity channel and wait as necessary.\n\n        This method is also used to slow down the main processing loop to reduce\n        the effects of rapidly sending Redis commands.  This method will exit\n        for any of these conditions:\n           1. _did_work is True, suggests there could be more work pending\n           2. Found new queue and after batch timeout. Note batch timeout\n              can be zero so it will exit immediately.\n           3. Timeout seconds have passed, this is the maximum time to stay in\n              this method"
  },
  {
    "code": "def start(self):\n        logger.info('Starting client.')\n        self.dispatcher_greenlets = []\n        for _, entry in self.config['baits'].items():\n            for b in clientbase.ClientBase.__subclasses__():\n                bait_name = b.__name__.lower()\n                if bait_name in entry:\n                    bait_options = entry[bait_name]\n                    dispatcher = BaitDispatcher(b, bait_options)\n                    dispatcher.start()\n                    self.dispatcher_greenlets.append(dispatcher)\n                    logger.info('Adding {0} bait'.format(bait_name))\n                    logger.debug('Bait added with options: {0}'.format(bait_options))\n        gevent.joinall(self.dispatcher_greenlets)",
    "docstring": "Starts sending client bait to the configured Honeypot."
  },
  {
    "code": "def query(self, object_class=None, json=None, **kwargs):\n        path = \"/directory-sync-service/v1/{}\".format(object_class)\n        r = self._httpclient.request(\n            method=\"POST\",\n            url=self.url,\n            json=json,\n            path=path,\n            **kwargs\n        )\n        return r",
    "docstring": "Query data stored in directory.\n\n        Retrieves directory data by querying a Directory Sync Service\n        cloud-based instance. The directory data is stored with the\n        Directory Sync Service instance using an agent that is installed\n        in the customer's network.This agent retrieves directory data\n        from the customer's Active Directory, and then sends it to the\n        cloud-based Directory Sync Service instance.\n\n        Args:\n            object_class (str): Directory object class.\n            json (dict): Payload/request body.\n            **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters.\n\n        Returns:\n            requests.Response: Requests Response() object.\n\n        Examples:\n            Coming soon."
  },
  {
    "code": "def visible_line_width(self, position = Point):\r\n        extra_char_width = len([ None for c in self[:position].line_buffer if 0x2013 <= ord(c) <= 0xFFFD])\r\n        return len(self[:position].quoted_text()) + self[:position].line_buffer.count(u\"\\t\")*7 + extra_char_width",
    "docstring": "Return the visible width of the text in line buffer up to position."
  },
  {
    "code": "def schemaNewValidCtxt(self):\n        ret = libxml2mod.xmlSchemaNewValidCtxt(self._o)\n        if ret is None:raise treeError('xmlSchemaNewValidCtxt() failed')\n        __tmp = SchemaValidCtxt(_obj=ret)\n        __tmp.schema = self\n        return __tmp",
    "docstring": "Create an XML Schemas validation context based on the given\n           schema."
  },
  {
    "code": "def _apply_shadow_vars(avg_grads):\n        ps_var_grads = []\n        for grad, var in avg_grads:\n            assert var.name.startswith('tower'), var.name\n            my_name = '/'.join(var.name.split('/')[1:])\n            my_name = get_op_tensor_name(my_name)[0]\n            new_v = tf.get_variable(my_name, dtype=var.dtype.base_dtype,\n                                    initializer=var.initial_value,\n                                    trainable=True)\n            ps_var_grads.append((grad, new_v))\n        return ps_var_grads",
    "docstring": "Create shadow variables on PS, and replace variables in avg_grads\n        by these shadow variables.\n\n        Args:\n            avg_grads: list of (grad, var) tuples"
  },
  {
    "code": "def get_extended_metadata(self, item_id):\n        response = self.soap_client.call(\n            'getExtendedMetadata',\n            [('id', item_id)])\n        return response.get('getExtendedMetadataResult', None)",
    "docstring": "Get extended metadata for a media item, such as related items.\n\n        Args:\n            item_id (str): The item for which metadata is required.\n\n        Returns:\n            ~collections.OrderedDict: The item's extended metadata or None.\n\n        See also:\n            The Sonos `getExtendedMetadata API\n            <http://musicpartners.sonos.com/node/128>`_"
  },
  {
    "code": "def run_facter(self, key=None):\n        args = [self.facter_path]\n        args.append(\"--puppet\")\n        if self.external_dir is not None:\n            args.append('--external-dir')\n            args.append(self.external_dir)\n        if self.uses_yaml:\n            args.append(\"--yaml\")\n        if key is not None:\n            args.append(key)\n        proc = subprocess.Popen(args, stdout=subprocess.PIPE)\n        results = proc.stdout.read()\n        if self.uses_yaml:\n            parsed_results = yaml.load(results)\n            if key is not None:\n                return parsed_results[key]\n            else:\n                return parsed_results\n        results = results.decode()\n        if key is not None:\n            return results.strip()\n        else:\n            return dict(_parse_cli_facter_results(results))",
    "docstring": "Run the facter executable with an optional specfic\n        fact. Output is parsed to yaml if available and\n        selected. Puppet facts are always selected. Returns a\n        dictionary if no key is given, and the value if a key is\n        passed."
  },
  {
    "code": "def dispatch_hook(cls, s=None, *_args, **_kwds):\n        if s is None:\n            return config.conf.raw_layer\n        fb = orb(s[0])\n        if fb & 0x80 != 0:\n            return HPackIndexedHdr\n        if fb & 0x40 != 0:\n            return HPackLitHdrFldWithIncrIndexing\n        if fb & 0x20 != 0:\n            return HPackDynamicSizeUpdate\n        return HPackLitHdrFldWithoutIndexing",
    "docstring": "dispatch_hook returns the subclass of HPackHeaders that must be used\n        to dissect the string."
  },
  {
    "code": "def _fixpath(root, base):\n    return os.path.abspath(os.path.normpath(os.path.join(root, base)))",
    "docstring": "Return absolute, normalized, joined paths"
  },
  {
    "code": "def _structure(self, source_code):\n        def cutter(seq, block_size):\n            for index in range(0, len(seq), block_size):\n                lexem = seq[index:index+block_size]\n                if len(lexem) == block_size:\n                    yield self.table_struct[seq[index:index+block_size]]\n        return tuple(cutter(source_code, self.idnt_struct_size))",
    "docstring": "return structure in ACDP format."
  },
  {
    "code": "def run(self):\n        stdoutBak = sys.stdout\n        streamResult = StringIO()\n        sys.stdout = streamResult\n        try:\n            pycodestyle.Checker.check_all(self)\n        finally:\n            sys.stdout = stdoutBak",
    "docstring": "Run pycodestyle checker and record warnings."
  },
  {
    "code": "def rmdir(self, pathobj):\n        stat = self.stat(pathobj)\n        if not stat.is_dir:\n            raise OSError(20, \"Not a directory: '%s'\" % str(pathobj))\n        url = str(pathobj) + '/'\n        text, code = self.rest_del(url, session=pathobj.session, verify=pathobj.verify, cert=pathobj.cert)\n        if code not in [200, 202, 204]:\n            raise RuntimeError(\"Failed to delete directory: '%s'\" % text)",
    "docstring": "Removes a directory"
  },
  {
    "code": "def instances_get(opts, plugins, url_file_input, out):\n    instances = OrderedDict()\n    preferred_order = ['wordpress', 'joomla', 'drupal']\n    for cms_name in preferred_order:\n        for plugin in plugins:\n            plugin_name = plugin.__name__.lower()\n            if cms_name == plugin_name:\n                instances[plugin_name] = instance_get(plugin, opts,\n                        url_file_input, out)\n    for plugin in plugins:\n        plugin_name = plugin.__name__.lower()\n        if plugin_name not in preferred_order:\n            instances[plugin_name] = instance_get(plugin, opts,\n                    url_file_input, out)\n    return instances",
    "docstring": "Creates and returns an ordered dictionary containing instances for all available\n    scanning plugins, sort of ordered by popularity.\n    @param opts: options as returned by self._options.\n    @param plugins: plugins as returned by plugins_util.plugins_base_get.\n    @param url_file_input: boolean value which indicates whether we are\n        scanning an individual URL or a file. This is used to determine\n        kwargs required.\n    @param out: self.out"
  },
  {
    "code": "def stop(self):\n        self._cease.set()\n        time.sleep(0.1)\n        self._isRunning = False",
    "docstring": "Stop the periodic runner"
  },
  {
    "code": "def to_dict(self):\n        return {\"address\": self.address,\n                \"port\": self.port,\n                \"condition\": self.condition,\n                \"type\": self.type,\n                \"id\": self.id,\n                }",
    "docstring": "Convert this Node to a dict representation for passing to the API."
  },
  {
    "code": "def read_wav(self, filename):\n        wave_input = None\n        try:\n            wave_input = wave.open(filename, 'r')\n            wave_frames = bytearray(\n                wave_input.readframes(wave_input.getnframes()))\n            self.sample_data = [x >> 4 for x in wave_frames]\n        finally:\n            if wave_input is not None:\n                wave_input.close()",
    "docstring": "Read sample data for this sample from a WAV file.\n\n        :param filename: the file from which to read"
  },
  {
    "code": "def _find_rtd_version():\n    vstr = 'latest'\n    try:\n        import ginga\n        from bs4 import BeautifulSoup\n    except ImportError:\n        return vstr\n    if not minversion(ginga, '2.6.0'):\n        return vstr\n    url = 'https://readthedocs.org/projects/ginga/downloads/'\n    with urllib.request.urlopen(url) as r:\n        soup = BeautifulSoup(r, 'html.parser')\n    all_rtd_vernums = []\n    for link in soup.find_all('a'):\n        href = link.get('href')\n        if 'htmlzip' not in href:\n            continue\n        s = href.split('/')[-2]\n        if s.startswith('v'):\n            all_rtd_vernums.append(s)\n    all_rtd_vernums.sort(reverse=True)\n    ginga_ver = ginga.__version__\n    for rtd_ver in all_rtd_vernums:\n        if ginga_ver > rtd_ver[1:]:\n            break\n        else:\n            vstr = rtd_ver\n    return vstr",
    "docstring": "Find closest RTD doc version."
  },
  {
    "code": "def _check_match(self, name, version_string) -> bool:\n        if not name or not version_string:\n            return False\n        try:\n            version = Version(version_string)\n        except InvalidVersion:\n            logger.debug(f\"Package {name}=={version_string} has an invalid version\")\n            return False\n        for requirement in self.blacklist_release_requirements:\n            if name != requirement.name:\n                continue\n            if version in requirement.specifier:\n                logger.debug(\n                    f\"MATCH: Release {name}=={version} matches specifier \"\n                    f\"{requirement.specifier}\"\n                )\n                return True\n        return False",
    "docstring": "Check if the package name and version matches against a blacklisted\n        package version specifier.\n\n        Parameters\n        ==========\n        name: str\n            Package name\n\n        version: str\n            Package version\n\n        Returns\n        =======\n        bool:\n            True if it matches, False otherwise."
  },
  {
    "code": "def cancel_offer(self, offer_id):\n        return self._create_put_request(\n            resource=OFFERS,\n            billomat_id=offer_id,\n            command=CANCEL,\n        )",
    "docstring": "Cancelles an offer\n\n        :param offer_id: the offer id\n        :return Response"
  },
  {
    "code": "def _schedule(self, action: Callable, seconds: int=0) -> int:\n        self.aid += 1\n        if seconds > 0:\n            nxt = time.perf_counter() + seconds\n            if nxt < self.aqNextCheck:\n                self.aqNextCheck = nxt\n            logger.trace(\"{} scheduling action {} with id {} to run in {} \"\n                         \"seconds\".format(self, get_func_name(action),\n                                          self.aid, seconds))\n            self.aqStash.append((nxt, (action, self.aid)))\n        else:\n            logger.trace(\"{} scheduling action {} with id {} to run now\".\n                         format(self, get_func_name(action), self.aid))\n            self.actionQueue.append((action, self.aid))\n        if action not in self.scheduled:\n            self.scheduled[action] = []\n        self.scheduled[action].append(self.aid)\n        return self.aid",
    "docstring": "Schedule an action to be executed after `seconds` seconds.\n\n        :param action: a callable to be scheduled\n        :param seconds: the time in seconds after which the action must be executed"
  },
  {
    "code": "def addFeatureSet(self, featureSet):\n        id_ = featureSet.getId()\n        self._featureSetIdMap[id_] = featureSet\n        self._featureSetIds.append(id_)\n        name = featureSet.getLocalId()\n        self._featureSetNameMap[name] = featureSet",
    "docstring": "Adds the specified featureSet to this dataset."
  },
  {
    "code": "def _set_route(self, ip_dest, next_hop, **kwargs):\n        commands = self._build_commands(ip_dest, next_hop, **kwargs)\n        delete = kwargs.get('delete', False)\n        default = kwargs.get('default', False)\n        if delete:\n            commands = \"no \" + commands\n        else:\n            if default:\n                commands = \"default \" + commands\n        return self.configure(commands)",
    "docstring": "Configure a static route\n\n        Args:\n            ip_dest (string): The ip address of the destination in the\n                form of A.B.C.D/E\n            next_hop (string): The next hop interface or ip address\n            **kwargs['next_hop_ip'] (string): The next hop address on\n                destination interface\n            **kwargs['distance'] (string): Administrative distance for this\n                route\n            **kwargs['tag'] (string): Route tag\n            **kwargs['route_name'] (string): Route name\n            **kwargs['delete'] (boolean): If true, deletes the specified route\n                instead of creating or setting values for the route\n            **kwargs['default'] (boolean): If true, defaults the specified\n                route instead of creating or setting values for the route\n\n        Returns:\n            True if the operation succeeds, otherwise False."
  },
  {
    "code": "def createRtiFromFileName(fileName):\n    cls, rtiRegItem = detectRtiFromFileName(fileName)\n    if cls is None:\n        logger.warn(\"Unable to import plugin {}: {}\"\n                    .format(rtiRegItem.fullName, rtiRegItem.exception))\n        rti = UnknownFileRti.createFromFileName(fileName)\n        rti.setException(rtiRegItem.exception)\n    else:\n        rti = cls.createFromFileName(fileName)\n    assert rti, \"Sanity check failed (createRtiFromFileName). Please report this bug.\"\n    return rti",
    "docstring": "Determines the type of RepoTreeItem to use given a file name and creates it.\n        Uses a DirectoryRti for directories and an UnknownFileRti if the file\n        extension doesn't match one of the registered RTI extensions."
  },
  {
    "code": "def eigenvalues_rev(T, k, ncv=None, mu=None):\n    r\n    if mu is None:\n        mu = stationary_distribution(T)\n    if np.any(mu <= 0):\n        raise ValueError('Cannot symmetrize transition matrix')\n    smu = np.sqrt(mu)\n    D = diags(smu, 0)\n    Dinv = diags(1.0/smu, 0)\n    S = (D.dot(T)).dot(Dinv)\n    evals = scipy.sparse.linalg.eigsh(S, k=k, ncv=ncv, which='LM', return_eigenvectors=False)\n    return evals",
    "docstring": "r\"\"\"Compute the eigenvalues of a reversible, sparse transition matrix.\n\n    Parameters\n    ----------\n    T : (M, M) scipy.sparse matrix\n        Transition matrix\n    k : int\n        Number of eigenvalues to compute.\n    ncv : int, optional\n        The number of Lanczos vectors generated, `ncv` must be greater than k;\n        it is recommended that ncv > 2*k\n    mu : (M,) ndarray, optional\n        Stationary distribution of T\n\n    Returns\n    -------\n    v : (k,) ndarray\n        Eigenvalues of T\n\n    Raises\n    ------\n    ValueError\n        If stationary distribution is nonpositive.\n\n    Notes\n    -----\n    The first k eigenvalues of largest magnitude are computed."
  },
  {
    "code": "def torrent_from_url(self, url, cache=True, prefetch=False):\n        if self._use_cache(cache) and url in self._torrent_cache:\n            return self._torrent_cache[url]\n        torrent = Torrent(url, cache, prefetch)\n        if cache:\n            self._torrent_cache[url] = torrent\n        return torrent",
    "docstring": "Create a Torrent object from a given URL.\n\n        If the cache option is set, check to see if we already have a Torrent\n        object representing it. If prefetch is set, automatically query the\n        torrent's info page to fill in the torrent object. (If prefetch is\n        false, then the torrent page will be queried lazily on-demand.)"
  },
  {
    "code": "def validate_matrix(self, data):\n        is_grid_search = (\n            data.get('grid_search') is not None or\n            (data.get('grid_search') is None and\n             data.get('random_search') is None and\n             data.get('hyperband') is None and\n             data.get('bo') is None)\n        )\n        is_bo = data.get('bo') is not None\n        validate_matrix(data.get('matrix'), is_grid_search=is_grid_search, is_bo=is_bo)",
    "docstring": "Validates matrix data and creates the config objects"
  },
  {
    "code": "def outputDeflections(self):\n    try:\n      self.wOutFile\n      if self.Verbose:\n        print(\"Output filename provided.\")\n    except:\n      try:\n        self.wOutFile = self.configGet(\"string\", \"output\", \"DeflectionOut\", optional=True)\n      except:\n        if self.Debug:\n          print(\"No output filename provided:\")\n          print(\"  not writing any deflection output to file\")\n    if self.wOutFile:\n        if self.wOutFile[-4:] == '.npy':\n          from numpy import save\n          save(self.wOutFile,self.w)\n        else:\n          from numpy import savetxt\n          savetxt(self.wOutFile,self.w,fmt='%.3f')\n          if self.Verbose:\n            print(\"Saving deflections --> \" + self.wOutFile)",
    "docstring": "Outputs a grid of deflections if an output directory is defined in the \n    configuration file\n    \n    If the filename given in the configuration file ends in \".npy\", then a binary \n    numpy grid will be exported.\n    \n    Otherwise, an ASCII grid will be exported."
  },
  {
    "code": "def removeComments(element):\n    global _num_bytes_saved_in_comments\n    num = 0\n    if isinstance(element, xml.dom.minidom.Comment):\n        _num_bytes_saved_in_comments += len(element.data)\n        element.parentNode.removeChild(element)\n        num += 1\n    else:\n        for subelement in element.childNodes[:]:\n            num += removeComments(subelement)\n    return num",
    "docstring": "Removes comments from the element and its children."
  },
  {
    "code": "def calibration(self):\n    self.calibration_cache_path()\n    if self.job().is_dax():\n      self.add_var_opt('glob-calibration-data','')\n      cache_filename=self.get_calibration()\n      pat = re.compile(r'(file://.*)')\n      f = open(cache_filename, 'r')\n      lines = f.readlines()\n      for line in lines:\n        m = pat.search(line)\n        if not m:\n          raise IOError\n        url = m.group(1)\n        path = urlparse.urlparse(url)[2]\n        calibration_lfn = os.path.basename(path)\n        self.add_input_file(calibration_lfn)\n    else:\n      self.add_var_opt('calibration-cache', self.__calibration_cache)\n      self.__calibration = self.__calibration_cache\n      self.add_input_file(self.__calibration)",
    "docstring": "Set the path to the calibration cache file for the given IFO.\n    During S2 the Hanford 2km IFO had two calibration epochs, so\n    if the start time is during S2, we use the correct cache file."
  },
  {
    "code": "def _ensure_image_registry(self, image):\n        image_with_registry = image.copy()\n        if self.parent_registry:\n            if image.registry and image.registry != self.parent_registry:\n                error = (\n                    \"Registry specified in dockerfile image doesn't match configured one. \"\n                    \"Dockerfile: '%s'; expected registry: '%s'\"\n                    % (image, self.parent_registry))\n                self.log.error(\"%s\", error)\n                raise RuntimeError(error)\n            image_with_registry.registry = self.parent_registry\n        return image_with_registry",
    "docstring": "If plugin configured with a parent registry, ensure the image uses it"
  },
  {
    "code": "def get_next_revision(self, session_id, revision, delta):\n        session = self.sessions[session_id]\n        session.state = State.connected\n        if delta == revision:\n            session.revision = max(session.revision, revision)\n            self.next_revision_available.wait()\n        return self.revision",
    "docstring": "Determine the next revision number for a given session id, revision\n        and delta.\n\n        In case the client is up-to-date, this method will block until the next\n        revision is available.\n\n        :param int session_id: Session identifier\n        :param int revision: Client revision number\n        :param int delta: Client revision delta (old client version number)\n        :return: Next revision number\n        :rtype: int"
  },
  {
    "code": "def _compute_derivatives(self):\n        derivatives = []\n        for i, (timestamp, value) in enumerate(self.time_series_items):\n            if i > 0:\n                pre_item = self.time_series_items[i - 1]\n                pre_timestamp = pre_item[0]\n                pre_value = pre_item[1]\n                td = timestamp - pre_timestamp\n                derivative = (value - pre_value) / td if td != 0 else value - pre_value\n                derivative = abs(derivative)\n                derivatives.append(derivative)\n        if derivatives:\n            derivatives.insert(0, derivatives[0])\n        self.derivatives = derivatives",
    "docstring": "Compute derivatives of the time series."
  },
  {
    "code": "def get_current_word(self, completion=False):\r\n        ret = self.get_current_word_and_position(completion)\r\n        if ret is not None:\r\n            return ret[0]",
    "docstring": "Return current word, i.e. word at cursor position"
  },
  {
    "code": "def iloc(cls, dataset, index):\n        rows, cols = index\n        scalar = False\n        if isinstance(cols, slice):\n            cols = [d.name for d in dataset.dimensions()][cols]\n        elif np.isscalar(cols):\n            scalar = np.isscalar(rows)\n            cols = [dataset.get_dimension(cols).name]\n        else:\n            cols = [dataset.get_dimension(d).name for d in index[1]]\n        if np.isscalar(rows):\n            rows = [rows]\n        data = OrderedDict()\n        for c in cols:\n            data[c] = dataset.data[c].compute().iloc[rows].values\n        if scalar:\n            return data[cols[0]][0]\n        return tuple(data.values())",
    "docstring": "Dask does not support iloc, therefore iloc will execute\n        the call graph and lose the laziness of the operation."
  },
  {
    "code": "def validate(self, ticket=None, raise_=False):\n        rv = Receipt.objects.filter(pk=self.pk).validate(ticket)\n        self.refresh_from_db()\n        if raise_ and rv:\n            raise exceptions.ValidationError(rv[0])\n        return rv",
    "docstring": "Validates this receipt.\n\n        This is a shortcut to :class:`~.ReceiptQuerySet`'s method of the same\n        name. Calling this validates only this instance.\n\n        :param AuthTicket ticket: Use this ticket. If None, one will be loaded\n            or created automatically.\n        :param bool raise_: If True, an exception will be raised when\n            validation fails."
  },
  {
    "code": "def filtered_attrs(module, *, modules=False, private=False, dunder=False,\n                   common=False):\n    attr_names = set()\n    for name, value in module.__dict__.items():\n        if not common and name in STANDARD_MODULE_ATTRS:\n            continue\n        if name.startswith('_'):\n            if name.endswith('_'):\n                if not dunder:\n                    continue\n            elif not private:\n                continue\n        if not modules and isinstance(value, types.ModuleType):\n            continue\n        attr_names.add(name)\n    return frozenset(attr_names)",
    "docstring": "Return a collection of attributes on 'module'.\n\n    If 'modules' is false then module instances are excluded. If 'private' is\n    false then attributes starting with, but not ending in, '_' will be\n    excluded. With 'dunder' set to false then attributes starting and ending\n    with '_' are left out. The 'common' argument controls whether attributes\n    found in STANDARD_MODULE_ATTRS are returned."
  },
  {
    "code": "def _bse_cli_get_versions(args):\n    name = args.basis.lower()\n    metadata = api.get_metadata(args.data_dir)\n    if not name in metadata:\n        raise KeyError(\n            \"Basis set {} does not exist. For a complete list of basis sets, use the 'list-basis-sets' command\".format(\n                name))\n    version_data = {k: v['revdesc'] for k, v in metadata[name]['versions'].items()}\n    if args.no_description:\n        liststr = version_data.keys()\n    else:\n        liststr = format_columns(version_data.items())\n    return '\\n'.join(liststr)",
    "docstring": "Handles the get-versions subcommand"
  },
  {
    "code": "def timestamp(self, timestamp):\n        clone = copy.deepcopy(self)\n        clone._timestamp = timestamp\n        return clone",
    "docstring": "Allows for custom timestamps to be saved with the record."
  },
  {
    "code": "def validate_dispatcher(args):\n    nni_config = Config(get_config_filename(args)).get_config('experimentConfig')\n    if nni_config.get('tuner') and nni_config['tuner'].get('builtinTunerName'):\n        dispatcher_name = nni_config['tuner']['builtinTunerName']\n    elif nni_config.get('advisor') and nni_config['advisor'].get('builtinAdvisorName'):\n        dispatcher_name = nni_config['advisor']['builtinAdvisorName']\n    else:\n        return\n    if dispatcher_name not in TUNERS_SUPPORTING_IMPORT_DATA:\n        if dispatcher_name in TUNERS_NO_NEED_TO_IMPORT_DATA:\n            print_warning(\"There is no need to import data for %s\" % dispatcher_name)\n            exit(0)\n        else:\n            print_error(\"%s does not support importing addtional data\" % dispatcher_name)\n            exit(1)",
    "docstring": "validate if the dispatcher of the experiment supports importing data"
  },
  {
    "code": "def clear_all_events(self):\n        self.lock.acquire()\n        self.event_dict.clear()\n        self.lock.release()",
    "docstring": "Clear all event queues and their cached events."
  },
  {
    "code": "def get_tag_cloud(context, steps=6, min_count=None,\n                  template='zinnia/tags/tag_cloud.html'):\n    tags = Tag.objects.usage_for_queryset(\n        Entry.published.all(), counts=True,\n        min_count=min_count)\n    return {'template': template,\n            'tags': calculate_cloud(tags, steps),\n            'context_tag': context.get('tag')}",
    "docstring": "Return a cloud of published tags."
  },
  {
    "code": "def should_see_id_in_seconds(self, element_id, timeout):\n    def check_element():\n        assert ElementSelector(\n            world.browser,\n            'id(\"%s\")' % element_id,\n            filter_displayed=True,\n        ), \"Expected element with given id.\"\n    wait_for(check_element)(timeout=int(timeout))",
    "docstring": "Assert an element with the given ``id`` is visible within n seconds."
  },
  {
    "code": "def show_guiref(self):\r\n        from qtconsole.usage import gui_reference\r\n        self.main.help.show_rich_text(gui_reference, collapse=True)",
    "docstring": "Show qtconsole help"
  },
  {
    "code": "def loadNetworkbyID(self, id, callback=None, errback=None):\n        import ns1.ipam\n        network = ns1.ipam.Network(self.config, id=id)\n        return network.load(callback=callback, errback=errback)",
    "docstring": "Load an existing Network by ID into a high level Network object\n\n        :param int id: id of an existing Network"
  },
  {
    "code": "def retry(self, retries, task_f, check_f=bool, wait_f=None):\n        for attempt in range(retries):\n            ret = task_f()\n            if check_f(ret):\n                return ret\n            if attempt < retries - 1 and wait_f is not None:\n                wait_f(attempt)\n        raise RetryException(\"Giving up after {} failed attempt(s)\".format(retries))",
    "docstring": "Try a function up to n times.\n        Raise an exception if it does not pass in time\n\n        :param retries int: The number of times to retry\n        :param task_f func: The function to be run and observed\n        :param func()bool check_f: a function to check if task_f is complete\n        :param func()bool wait_f: a function to run between checks"
  },
  {
    "code": "def map_or(self, callback: Callable[[T], U], default: A) -> Union[U, A]:\n        return callback(self._val) if self._is_some else default",
    "docstring": "Applies the ``callback`` to the contained value or returns ``default``.\n\n        Args:\n            callback: The callback to apply to the contained value.\n            default: The default value.\n\n        Returns:\n            The ``callback`` result if the contained value is ``Some``,\n            otherwise ``default``.\n\n        Notes:\n            If you wish to use the result of a function call as ``default``,\n            it is recommended to use :py:meth:`map_or_else` instead.\n\n        Examples:\n            >>> Some(0).map_or(lambda x: x + 1, 1000)\n            1\n            >>> NONE.map_or(lambda x: x * x, 1)\n            1"
  },
  {
    "code": "def display(self):\n        self.pretty(self._timings, 'Raw Redis Commands')\n        print()\n        for key, value in self._commands.items():\n            self.pretty(value, 'Qless \"%s\" Command' % key)\n            print()",
    "docstring": "Print the results of this profiling"
  },
  {
    "code": "def license_cleanup(text):\n    if not text:\n        return None\n    text = text.rsplit(':', 1)[-1]\n    replacements = [\n        'licenses',\n        'license',\n        'licences',\n        'licence',\n        'software',\n        ',',\n    ]\n    for replacement in replacements:\n        text = text.replace(replacement, '')\n    text = text.strip().upper()\n    text = text.replace(' ', '_')\n    text = text.replace('-', '_')\n    if any(trigger.upper() in text for trigger in BAD_LICENSES):\n        return None\n    return text",
    "docstring": "Tidy up a license string\n\n    e.g. \"::OSI::   mit software license\" -> \"MIT\""
  },
  {
    "code": "def _deserialize(self, value, attr, data):\n        token_builder = URLSafeTimedSerializer(\n            current_app.config['SECRET_KEY'],\n            salt=data['verb'],\n        )\n        result = token_builder.loads(value, max_age=current_app.config[\n            'OAISERVER_RESUMPTION_TOKEN_EXPIRE_TIME'])\n        result['token'] = value\n        result['kwargs'] = self.root.load(result['kwargs'], partial=True).data\n        return result",
    "docstring": "Serialize resumption token."
  },
  {
    "code": "def get_label(self, indices=None):\n        if indices is None:\n            indices = list(range(0, self.get_sample_size()))\n        elif isinstance(indices, collections.Iterable):\n            indices = sorted(list(set(indices)))\n        else:\n            indices = [indices]\n        if len(indices) == 0:\n            return []\n        partitions = self.get_partitions(self.persistence)\n        labels = self.X.shape[0] * [None]\n        for label, partition_indices in partitions.items():\n            for idx in np.intersect1d(partition_indices, indices):\n                labels[idx] = label\n        labels = np.array(labels)\n        if len(indices) == 1:\n            return labels[indices][0]\n        return labels[indices]",
    "docstring": "Returns the label pair indices requested by the user\n            @ In, indices, a list of non-negative integers specifying\n            the row indices to return\n            @ Out, a list of integer 2-tuples specifying the minimum and\n            maximum index of the specified rows."
  },
  {
    "code": "def get_pyserial_version(self):\n        pyserial_version = pkg_resources.require(\"pyserial\")[0].version\n        version = 3.0\n        match = self.re_float.search(pyserial_version)\n        if match:\n            try:\n                version = float(match.group(0))\n            except ValueError:\n                version = 3.0\n        return version",
    "docstring": "! Retrieve pyserial module version\n        @return Returns float with pyserial module number"
  },
  {
    "code": "def copy_layer(source, target):\n    out_feature = QgsFeature()\n    target.startEditing()\n    request = QgsFeatureRequest()\n    aggregation_layer = False\n    if source.keywords.get('layer_purpose') == 'aggregation':\n        try:\n            use_selected_only = source.use_selected_features_only\n        except AttributeError:\n            use_selected_only = False\n        if use_selected_only and source.selectedFeatureCount() > 0:\n            request.setFilterFids(source.selectedFeatureIds())\n        aggregation_layer = True\n    for i, feature in enumerate(source.getFeatures(request)):\n        geom = feature.geometry()\n        if aggregation_layer and feature.hasGeometry():\n            was_valid, geom = geometry_checker(geom)\n            if not geom:\n                LOGGER.info(\n                    'One geometry in the aggregation layer is still invalid '\n                    'after cleaning.')\n        out_feature.setGeometry(geom)\n        out_feature.setAttributes(feature.attributes())\n        target.addFeature(out_feature)\n    target.commitChanges()",
    "docstring": "Copy a vector layer to another one.\n\n    :param source: The vector layer to copy.\n    :type source: QgsVectorLayer\n\n    :param target: The destination.\n    :type source: QgsVectorLayer"
  },
  {
    "code": "def size_filter(labeled_grid, min_size):\n        out_grid = np.zeros(labeled_grid.shape, dtype=int)\n        slices = find_objects(labeled_grid)\n        j = 1\n        for i, s in enumerate(slices):\n            box = labeled_grid[s]\n            size = np.count_nonzero(box.ravel() == (i + 1))\n            if size >= min_size and box.shape[0] > 1 and box.shape[1] > 1:\n                out_grid[np.where(labeled_grid == i + 1)] = j\n                j += 1\n        return out_grid",
    "docstring": "Remove labeled objects that do not meet size threshold criteria.\n\n        Args:\n            labeled_grid: 2D output from label method.\n            min_size: minimum size of object in pixels.\n\n        Returns:\n            labeled grid with smaller objects removed."
  },
  {
    "code": "def scan_used_functions(example_file, gallery_conf):\n    example_code_obj = identify_names(example_file)\n    if example_code_obj:\n        codeobj_fname = example_file[:-3] + '_codeobj.pickle.new'\n        with open(codeobj_fname, 'wb') as fid:\n            pickle.dump(example_code_obj, fid, pickle.HIGHEST_PROTOCOL)\n        _replace_md5(codeobj_fname)\n    backrefs = set('{module_short}.{name}'.format(**entry)\n                   for entry in example_code_obj.values()\n                   if entry['module'].startswith(gallery_conf['doc_module']))\n    return backrefs",
    "docstring": "save variables so we can later add links to the documentation"
  },
  {
    "code": "def typewrite(message, interval=0.0, pause=None, _pause=True):\n    interval = float(interval)\n    _failSafeCheck()\n    for c in message:\n        if len(c) > 1:\n            c = c.lower()\n        press(c, _pause=False)\n        time.sleep(interval)\n        _failSafeCheck()\n    _autoPause(pause, _pause)",
    "docstring": "Performs a keyboard key press down, followed by a release, for each of\n    the characters in message.\n\n    The message argument can also be list of strings, in which case any valid\n    keyboard name can be used.\n\n    Since this performs a sequence of keyboard presses and does not hold down\n    keys, it cannot be used to perform keyboard shortcuts. Use the hotkey()\n    function for that.\n\n    Args:\n      message (str, list): If a string, then the characters to be pressed. If a\n        list, then the key names of the keys to press in order. The valid names\n        are listed in KEYBOARD_KEYS.\n      interval (float, optional): The number of seconds in between each press.\n        0.0 by default, for no pause in between presses.\n\n    Returns:\n      None"
  },
  {
    "code": "def _get_app_module(self):\n        def configure(binder):\n            binder.bind(ServiceApplication, to=self, scope=singleton)\n            binder.bind(Config, to=self.config, scope=singleton)\n        return configure",
    "docstring": "Returns a module which binds the current app and configuration.\n\n        :return: configuration callback\n        :rtype: Callable"
  },
  {
    "code": "def get(self, key):\n        check_not_none(key, \"key can't be None\")\n        key_data = self._to_data(key)\n        return self._encode_invoke_on_key(multi_map_get_codec, key_data, key=key_data,\n                                          thread_id=thread_id())",
    "docstring": "Returns the list of values associated with the key. ``None`` if this map does not contain this key.\n\n        **Warning:\n        This method uses hashCode and equals of the binary form of the key, not the actual implementations of hashCode\n        and equals defined in the key's class.**\n\n        **Warning-2:\n        The list is NOT backed by the multimap, so changes to the map are list reflected in the collection, and\n        vice-versa.**\n\n        :param key: (object), the specified key.\n        :return: (Sequence), the list of the values associated with the specified key."
  },
  {
    "code": "def SampleSum(dists, n):\n    pmf = MakePmfFromList(RandomSum(dists) for i in xrange(n))\n    return pmf",
    "docstring": "Draws a sample of sums from a list of distributions.\n\n    dists: sequence of Pmf or Cdf objects\n    n: sample size\n\n    returns: new Pmf of sums"
  },
  {
    "code": "def source(self, value):\n        if not isinstance(value, tuple) or len(value) != 2:\n            raise AttributeError\n        self._source = value",
    "docstring": "Set the source of the message.\n\n        :type value: tuple\n        :param value: (ip, port)\n        :raise AttributeError: if value is not a ip and a port."
  },
  {
    "code": "def set_peer_link(self, value=None, default=False, disable=False):\n        return self._configure_mlag('peer-link', value, default, disable)",
    "docstring": "Configures the mlag peer-link value\n\n        Args:\n            value (str): The value to configure the peer-link\n            default (bool): Configures the peer-link using the\n                default keyword\n            disable (bool): Negates the peer-link using the no keyword\n\n        Returns:\n            bool: Returns True if the commands complete successfully"
  },
  {
    "code": "def _css_helper(self):\n        entries = [entry for entry in self._plugin_manager.call_hook(\"css\") if entry is not None]\n        entries += self._get_ctx()[\"css\"]\n        entries = [\"<link href='\" + entry + \"' rel='stylesheet'>\" for entry in entries]\n        return \"\\n\".join(entries)",
    "docstring": "Add CSS links for the current page and for the plugins"
  },
  {
    "code": "def _get_stats_from_socket(self, name):\n        try:\n            json_blob = subprocess.check_output(\n                [self.config['ceph_binary'],\n                 '--admin-daemon',\n                 name,\n                 'perf',\n                 'dump',\n                 ])\n        except subprocess.CalledProcessError as err:\n            self.log.info('Could not get stats from %s: %s',\n                          name, err)\n            self.log.exception('Could not get stats from %s' % name)\n            return {}\n        try:\n            json_data = json.loads(json_blob)\n        except Exception as err:\n            self.log.info('Could not parse stats from %s: %s',\n                          name, err)\n            self.log.exception('Could not parse stats from %s' % name)\n            return {}\n        return json_data",
    "docstring": "Return the parsed JSON data returned when ceph is told to\n        dump the stats from the named socket.\n\n        In the event of an error error, the exception is logged, and\n        an empty result set is returned."
  },
  {
    "code": "def inventory(self, all=False, ssid=None):\n        if all or self.api_key is None:\n            if ssid is not None:\n                return self._ssid_inventory(self.full_inventory, ssid)\n            else:\n                return self.full_inventory\n        else:\n            if ssid is not None:\n                return self._ssid_inventory(self.self_inventory, ssid)\n            else:\n                return self.self_inventory",
    "docstring": "Returns a node inventory. If an API key is specified, only the nodes\n         provisioned by this key will be returned.\n\n        :return: { inventory }"
  },
  {
    "code": "def __store_cash_balances_per_currency(self, cash_balances):\n        cash = self.model.get_cash_asset_class()\n        for cur_symbol in cash_balances:\n            item = CashBalance(cur_symbol)\n            item.parent = cash\n            quantity = cash_balances[cur_symbol][\"total\"]\n            item.value = Decimal(quantity)\n            item.currency = cur_symbol\n            cash.stocks.append(item)\n            self.model.stocks.append(item)",
    "docstring": "Store balance per currency as Stock records under Cash class"
  },
  {
    "code": "def _create_response_record(self, response):\n        record = dict()\n        record['id'] = response['id']\n        record['type'] = response['type']\n        record['name'] = self._full_name(response['name'])\n        if 'content' in response:\n            record['content'] = response['content'] or \"\"\n        if 'ttl' in response:\n            record['ttl'] = response['ttl']\n        if 'prio' in response:\n            record['priority'] = response['prio']\n        return record",
    "docstring": "Creates record for lexicon API calls"
  },
  {
    "code": "def calcDrawingProbs(self):\n        wmg = self.wmg\n        phi = self.phi\n        weights = []\n        for i in range(0, len(wmg.keys())):\n            weights.append(phi**i)\n        totalWeight = sum(weights)\n        for i in range(0, len(wmg.keys())):\n            weights[i] = weights[i]/totalWeight\n        return weights",
    "docstring": "Returns a vector that contains the probabily of an item being from each position. We say\n        that every item in a order vector is drawn with weight phi^i where i is its position."
  },
  {
    "code": "def generate(env):\n    SCons.Tool.createSharedLibBuilder(env)\n    SCons.Tool.createProgBuilder(env)\n    env['LINK']        = '$CC'\n    env['LINKFLAGS']   = SCons.Util.CLVar('')\n    env['LINKCOM']     = '$LINK -q $LINKFLAGS -e$TARGET $SOURCES $LIBS'\n    env['LIBDIRPREFIX']=''\n    env['LIBDIRSUFFIX']=''\n    env['LIBLINKPREFIX']=''\n    env['LIBLINKSUFFIX']='$LIBSUFFIX'",
    "docstring": "Add Builders and construction variables for Borland ilink to an\n    Environment."
  },
  {
    "code": "def timedelta_seconds(timedelta):\r\n    return (timedelta.total_seconds() if hasattr(timedelta, \"total_seconds\")\r\n            else timedelta.days * 24 * 3600 + timedelta.seconds +\r\n                 timedelta.microseconds / 1000000.)",
    "docstring": "Returns the total timedelta duration in seconds."
  },
  {
    "code": "def group(self):\n        split_count = self._url.lower().find(\"/content/\")\n        len_count = len('/content/')\n        gURL = self._url[:self._url.lower().find(\"/content/\")] + \\\n            \"/community/\" + self._url[split_count+ len_count:]\n        return CommunityGroup(url=gURL,\n                              securityHandler=self._securityHandler,\n                              proxy_url=self._proxy_url,\n                              proxy_port=self._proxy_port)",
    "docstring": "returns the community.Group class for the current group"
  },
  {
    "code": "def get_thermostat_state_by_id(self, id_):\n        return next((state for state in self.thermostat_states\n                     if state.id == id_), None)",
    "docstring": "Retrieves a thermostat state object by its id\n\n        :param id_: The id of the thermostat state\n        :return: The thermostat state object"
  },
  {
    "code": "def get_cluster_port_names(self, cluster_name):\r\n        port_names = list()\r\n        for host_name in self.get_hosts_by_clusters()[cluster_name]:\r\n            port_names.extend(self.get_hosts_by_name(host_name))\r\n        return port_names",
    "docstring": "return a list of the port names under XIV CLuster"
  },
  {
    "code": "def find_link(self, href_pattern, make_absolute=True):\n        if make_absolute:\n            self.tree.make_links_absolute(self.doc.url)\n        if isinstance(href_pattern, six.text_type):\n            raise GrabMisuseError('Method `find_link` accepts only '\n                                  'byte-string argument')\n        href_pattern = make_unicode(href_pattern)\n        for elem, _, link, _ in self.tree.iterlinks():\n            if elem.tag == 'a' and href_pattern in link:\n                return link\n        return None",
    "docstring": "Find link in response body which href value matches ``href_pattern``.\n\n        Returns found url or None."
  },
  {
    "code": "def update(self, **kwargs):\n        ret_val = super(ManagerUtilsQuerySet, self).update(**kwargs)\n        post_bulk_operation.send(sender=self.model, model=self.model)\n        return ret_val",
    "docstring": "Overrides Django's update method to emit a post_bulk_operation signal when it completes."
  },
  {
    "code": "def unsubscribe(self, topic):\n        if self.sock == NC.INVALID_SOCKET:\n            return NC.ERR_NO_CONN\n        self.logger.info(\"UNSUBSCRIBE: %s\", topic)\n        return self.send_unsubscribe(False, [utf8encode(topic)])",
    "docstring": "Unsubscribe to some topic."
  },
  {
    "code": "def write(notebook, file_or_stream, fmt, version=nbformat.NO_CONVERT, **kwargs):\n    text = u'' + writes(notebook, fmt, version, **kwargs)\n    file_or_stream.write(text)\n    if not text.endswith(u'\\n'):\n        file_or_stream.write(u'\\n')",
    "docstring": "Write a notebook to a file"
  },
  {
    "code": "def _parse_signed_int_components(buf):\n    sign_bit = 0\n    value = 0\n    first = True\n    while True:\n        ch = buf.read(1)\n        if ch == b'':\n            break\n        octet = ord(ch)\n        if first:\n            if octet & _SIGNED_INT_SIGN_MASK:\n                sign_bit = 1\n            value = octet & _SIGNED_INT_SIGN_VALUE_MASK\n            first = False\n        else:\n            value <<= 8\n            value |= octet\n    return sign_bit, value",
    "docstring": "Parses the remainder of a file-like object as a signed magnitude value.\n\n    Returns:\n        Returns a pair of the sign bit and the unsigned magnitude."
  },
  {
    "code": "def rprof(self):\n        if self.istep not in self.sdat.rprof.index.levels[0]:\n            return None\n        return self.sdat.rprof.loc[self.istep]",
    "docstring": "Radial profiles data of the time step.\n\n        Set to None if no radial profiles data is available for this time step."
  },
  {
    "code": "def dict_stack(dict_list, key_prefix=''):\n    r\n    dict_stacked_ = defaultdict(list)\n    for dict_ in dict_list:\n        for key, val in six.iteritems(dict_):\n            dict_stacked_[key_prefix + key].append(val)\n    dict_stacked = dict(dict_stacked_)\n    return dict_stacked",
    "docstring": "r\"\"\"\n    stacks values from two dicts into a new dict where the values are list of\n    the input values. the keys are the same.\n\n    DEPRICATE in favor of dict_stack2\n\n    Args:\n        dict_list (list): list of dicts with similar keys\n\n    Returns:\n        dict dict_stacked\n\n    CommandLine:\n        python -m utool.util_dict --test-dict_stack\n        python -m utool.util_dict --test-dict_stack:1\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_dict import *  # NOQA\n        >>> import utool as ut\n        >>> dict1_ = {'a': 1, 'b': 2}\n        >>> dict2_ = {'a': 2, 'b': 3, 'c': 4}\n        >>> dict_stacked = dict_stack([dict1_, dict2_])\n        >>> result = ut.repr2(dict_stacked, sorted_=True)\n        >>> print(result)\n        {'a': [1, 2], 'b': [2, 3], 'c': [4]}\n\n    Example1:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_dict import *  # NOQA\n        >>> import utool as ut\n        >>> # Get equivalent behavior with dict_stack2?\n        >>> # Almost, as long as None is not part of the list\n        >>> dict1_ = {'a': 1, 'b': 2}\n        >>> dict2_ = {'a': 2, 'b': 3, 'c': 4}\n        >>> dict_stacked_ = dict_stack2([dict1_, dict2_])\n        >>> dict_stacked = {key: ut.filter_Nones(val) for key, val in dict_stacked_.items()}\n        >>> result = ut.repr2(dict_stacked, sorted_=True)\n        >>> print(result)\n        {'a': [1, 2], 'b': [2, 3], 'c': [4]}"
  },
  {
    "code": "def within_polygon(self, polygon, distance=None, **kwargs):\n        if distance:\n            zone_polygon = polygon.dilate(distance)\n        else:\n            zone_polygon = polygon\n        upper_depth, lower_depth = _check_depth_limits(kwargs)\n        valid_depth = np.logical_and(\n            self.catalogue.data['depth'] >= upper_depth,\n            self.catalogue.data['depth'] < lower_depth)\n        catalogue_mesh = Mesh(self.catalogue.data['longitude'],\n                              self.catalogue.data['latitude'],\n                              self.catalogue.data['depth'])\n        valid_id = np.logical_and(valid_depth,\n                                  zone_polygon.intersects(catalogue_mesh))\n        return self.select_catalogue(valid_id)",
    "docstring": "Select earthquakes within polygon\n\n        :param polygon:\n            Centre point as instance of nhlib.geo.polygon.Polygon class\n\n        :param float distance:\n            Buffer distance (km) (can take negative values)\n\n        :returns:\n            Instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue`\n            containing only selected events"
  },
  {
    "code": "def annotate(self, sent):\n    preds = []\n    words = []\n    for word, fv in self.sent2examples(sent):\n      probs = self.predictor(fv)\n      tags = probs.argsort()\n      tag = self.ID_TAG[tags[-1]]\n      words.append(word)\n      preds.append(tag)\n    annotations = zip(words, preds)\n    return annotations",
    "docstring": "Annotate a squence of words with entity tags.\n\n    Args:\n      sent: sequence of strings/words."
  },
  {
    "code": "def generate(variables, template):\n  env = jinja2.Environment(undefined=jinja2.StrictUndefined)\n  for c in expand(variables):\n    c['rc'] = rc\n    yield env.from_string(template).render(c)",
    "docstring": "Yields a resolved \"template\" for each config set and dumps on output\n\n  This function will extrapolate the ``template`` file using the contents of\n  ``variables`` and will output individual (extrapolated, expanded) files in\n  the output directory ``output``.\n\n\n  Parameters:\n\n    variables (str): A string stream containing the variables to parse, in YAML\n      format as explained on :py:func:`expand`.\n\n    template (str): A string stream containing the template to extrapolate\n\n\n  Yields:\n\n    str: A generated template you can save\n\n\n  Raises:\n\n    jinja2.UndefinedError: if a variable used in the template is undefined"
  },
  {
    "code": "def transform(self, data=None):\n        if data is None:\n            return self.xform_data\n        else:\n            formatted = format_data(\n                data,\n                semantic=self.semantic,\n                vectorizer=self.vectorizer,\n                corpus=self.corpus,\n                ppca=True)\n            norm = normalizer(formatted, normalize=self.normalize)\n            reduction = reducer(\n                norm,\n                reduce=self.reduce,\n                ndims=self.reduce['params']['n_components'])\n            return aligner(reduction, align=self.align)",
    "docstring": "Return transformed data, or transform new data using the same model\n        parameters\n\n        Parameters\n        ----------\n        data : numpy array, pandas dataframe or list of arrays/dfs\n            The data to transform.  If no data is passed, the xform_data from\n            the DataGeometry object will be returned.\n\n        Returns\n        ----------\n        xformed_data : list of numpy arrays\n            The transformed data"
  },
  {
    "code": "def _function_add_node(self, cfg_node, function_addr):\n        snippet = self._to_snippet(cfg_node=cfg_node)\n        self.kb.functions._add_node(function_addr, snippet)",
    "docstring": "Adds node to function manager, converting address to CodeNode if\n        possible\n\n        :param CFGNode cfg_node:    A CFGNode instance.\n        :param int function_addr:   Address of the current function.\n        :return: None"
  },
  {
    "code": "def _py_ex_argtype(executable):\n    result = []\n    for p in executable.ordered_parameters:\n        atypes = p.argtypes\n        if atypes is not None:\n            result.extend(p.argtypes)\n        else:\n            print((\"No argtypes for: {}\".format(p.definition())))\n    if type(executable).__name__ == \"Function\":\n        result.extend(executable.argtypes)        \n    return result",
    "docstring": "Returns the code to create the argtype to assign to the methods argtypes\n    attribute."
  },
  {
    "code": "def check_config(self, config, name=''):\n        config = config.get(self.config_name, {})\n        extras = set(config.keys()).difference(self.default_config)\n        if 'config' not in self.services and extras:\n            raise ConfigurationError(\n                'Unsupported config options for \"%s\": %s'\n                % (self.config_name, ', '.join(extras)))\n        missing = set(self.default_config).difference(config)\n        if missing:\n            raise ConfigurationError(\n                'Missing config options for \"%s\": %s'\n                % (self.config_name, ', '.join(missing)))\n        duplicates = set(config.keys()).intersection(set(self.services))\n        if duplicates:\n            raise ConfigurationError(\n                'Disallowed config options for \"%s\": %s'\n                % (self.config_name, ', '.join(duplicates)))",
    "docstring": "Check that the configuration for this object is valid.\n\n        This is a more restrictive check than for most :mod:`yakonfig`\n        objects.  It will raise :exc:`yakonfig.ConfigurationError` if\n        `config` contains any keys that are not in the underlying\n        callable's parameter list (that is, extra unused configuration\n        options).  This will also raise an exception if `config`\n        contains keys that duplicate parameters that should be\n        provided by the factory.\n\n        .. note:: This last behavior is subject to change; future\n                  versions of the library may allow configuration to\n                  provide local configuration for a factory-provided\n                  object.\n\n        :param dict config: the parent configuration dictionary,\n          probably contains :attr:`config_name` as a key\n        :param str name: qualified name of this object in the configuration\n        :raise: :exc:`yakonfig.ConfigurationError` if excess parameters exist"
  },
  {
    "code": "def skipline(self):\n        position = self.tell()\n        prefix = self._fix()\n        self.seek(prefix, 1)\n        suffix = self._fix()\n        if prefix != suffix:\n            raise IOError(_FIX_ERROR)\n        return position, prefix",
    "docstring": "Skip the next line and returns position and size of line.\n        Raises IOError if pre- and suffix of line do not match."
  },
  {
    "code": "def unmatched_quotes_in_line(text):\n    text = text.replace(\"\\\\'\", \"\")\n    text = text.replace('\\\\\"', '')\n    if text.count('\"') % 2:\n        return '\"'\n    elif text.count(\"'\") % 2:\n        return \"'\"\n    else:\n        return ''",
    "docstring": "Return whether a string has open quotes.\n\n    This simply counts whether the number of quote characters of either\n    type in the string is odd.\n\n    Take from the IPython project (in IPython/core/completer.py in v0.13)\n    Spyder team: Add some changes to deal with escaped quotes\n\n    - Copyright (C) 2008-2011 IPython Development Team\n    - Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>\n    - Copyright (C) 2001 Python Software Foundation, www.python.org\n\n    Distributed under the terms of the BSD License."
  },
  {
    "code": "def get_processing_block_ids():\n    ids = []\n    for key in sorted(DB.keys(pattern='scheduling_block/*')):\n        config = json.loads(DB.get(key))\n        for processing_block in config['processing_blocks']:\n            ids.append(processing_block['id'])\n    return ids",
    "docstring": "Return an array of Processing Block ids"
  },
  {
    "code": "def _handle_info(self, *args, **kwargs):\n        if 'version' in kwargs:\n            self.api_version = kwargs['version']\n            print(\"Initialized API with version %s\" % self.api_version)\n            return\n        try:\n            info_code = str(kwargs['code'])\n        except KeyError:\n            raise FaultyPayloadError(\"_handle_info: %s\" % kwargs)\n        if not info_code.startswith('2'):\n            raise ValueError(\"Info Code must start with 2! %s\", kwargs)\n        output_msg = \"_handle_info(): %s\" % kwargs\n        log.info(output_msg)\n        try:\n            self._code_handlers[info_code]()\n        except KeyError:\n            raise UnknownWSSInfo(output_msg)",
    "docstring": "Handles info messages and executed corresponding code"
  },
  {
    "code": "def fetch(self):\n        returnResults = []\n        results = self._query.run()\n        for result in results:\n            if self._join:\n                item = self._model.fromRawEntry(**result[\"left\"])\n                joined = self._join.fromRawEntry(**result[\"right\"])\n                item.protectedItems = self._joinedField\n                item[self._joinedField] = joined\n            else:\n                item = self._model.fromRawEntry(**result)\n            returnResults.append(item)\n        self._documents = returnResults\n        return self._documents",
    "docstring": "Fetches the query and then tries to wrap the data in the model, joining\n        as needed, if applicable."
  },
  {
    "code": "def system(self):\n        url = self._url + \"/system\"\n        return _System(url=url,\n                       securityHandler=self._securityHandler,\n                       proxy_url=self._proxy_url,\n                       proxy_port=self._proxy_port)",
    "docstring": "Creates a reference to the System operations for Portal"
  },
  {
    "code": "def get_endpoints_using_catalog_api(domain, token):\n    headers = {\"X-App-Token\": token}\n    uri = \"http://api.us.socrata.com/api/catalog/v1?domains={0}&offset={1}&limit=1000\"\n    ret = []\n    endpoints_thus_far = set()\n    offset = 0\n    while True:\n        try:\n            r = requests.get(uri.format(domain, offset), headers=headers)\n            r.raise_for_status()\n        except requests.HTTPError:\n            raise requests.HTTPError(\"An HTTP error was raised during Socrata API ingestion.\".format(domain))\n        data = r.json()\n        endpoints_returned = {r['resource']['id'] for r in data['results']}\n        new_endpoints = endpoints_returned.difference(endpoints_thus_far)\n        if len(new_endpoints) >= 999:\n            ret += data['results']\n            endpoints_thus_far.update(new_endpoints)\n            offset += 1000\n            continue\n        else:\n            ret += [r for r in data['results'] if r['resource']['id'] in new_endpoints]\n            break\n    return ret",
    "docstring": "Implements a raw HTTP GET against the entire Socrata portal for the domain in question. This method uses the\n    second of the two ways of getting this information, the catalog API.\n\n    Parameters\n    ----------\n    domain: str\n        A Socrata data portal domain. \"data.seattle.gov\" or \"data.cityofnewyork.us\" for example.\n    token: str\n        A Socrata application token. Application tokens can be registered by going onto the Socrata portal in\n        question, creating an account, logging in, going to developer tools, and spawning a token.\n\n    Returns\n    -------\n    Portal dataset metadata from the catalog API."
  },
  {
    "code": "def warp_locations(locations, y_center=None, return_ellipsoid=False, verbose=False):\n    locations = np.asarray(locations)\n    if y_center is None:\n        c, r = _fit_ellipsoid_full(locations)\n    else:\n        c, r = _fit_ellipsoid_partial(locations, y_center)\n    elliptic_locations = _project_on_ellipsoid(c, r, locations)\n    if verbose:\n        print('Head ellipsoid center:', c)\n        print('Head ellipsoid radii:', r)\n        distance = np.sqrt(np.sum((locations - elliptic_locations)**2, axis=1))\n        print('Minimum electrode displacement:', np.min(distance))\n        print('Average electrode displacement:', np.mean(distance))\n        print('Maximum electrode displacement:', np.max(distance))\n    spherical_locations = (elliptic_locations - c) / r\n    if return_ellipsoid:\n        return spherical_locations, c, r\n    return spherical_locations",
    "docstring": "Warp EEG electrode locations to spherical layout.\n\n    EEG Electrodes are warped to a spherical layout in three steps:\n        1. An ellipsoid is least-squares-fitted to the electrode locations.\n        2. Electrodes are displaced to the nearest point on the ellipsoid's surface.\n        3. The ellipsoid is transformed to a sphere, causing the new locations to lie exactly on a spherical surface\n           with unit radius.\n\n    This procedure intends to minimize electrode displacement in the original coordinate space. Simply projecting\n    electrodes on a sphere (e.g. by normalizing the x/y/z coordinates) typically gives much larger displacements.\n\n    Parameters\n    ----------\n    locations : array-like, shape = [n_electrodes, 3]\n        Eeach row of `locations` corresponds to the location of an EEG electrode in cartesian x/y/z coordinates.\n    y_center : float, optional\n        Fix the y-coordinate of the ellipsoid's center to this value (optional). This is useful to align the ellipsoid\n        with the central electrodes.\n    return_ellipsoid : bool, optional\n        If `true` center and radii of the ellipsoid are returned.\n\n    Returns\n    -------\n    newlocs : array-like, shape = [n_electrodes, 3]\n        Electrode locations on unit sphere.\n    c : array-like, shape = [3], (only returned if `return_ellipsoid` evaluates to `True`)\n        Center of the ellipsoid in the original location's coordinate space.\n    r : array-like, shape = [3], (only returned if `return_ellipsoid` evaluates to `True`)\n        Radii (x, y, z) of the ellipsoid in the original location's coordinate space."
  },
  {
    "code": "def all_library_calls(self):\n        if self._all_library_calls is None:\n            self._all_library_calls = self._explore_functions(lambda x: x.library_calls)\n        return self._all_library_calls",
    "docstring": "recursive version of library calls"
  },
  {
    "code": "def reply_inform(cls, req_msg, *args):\n        return cls(cls.INFORM, req_msg.name, args, req_msg.mid)",
    "docstring": "Helper method for creating inform messages in reply to a request.\n\n        Copies the message name and message identifier from request message.\n\n        Parameters\n        ----------\n        req_msg : katcp.core.Message instance\n            The request message that this inform if in reply to\n        args : list of strings\n            The message arguments except name"
  },
  {
    "code": "def cancel_room(self, booking_id):\n        resp = self._request(\"POST\", \"/1.1/space/cancel/{}\".format(booking_id))\n        return resp.json()",
    "docstring": "Cancel a room given a booking id.\n\n        :param booking_id: A booking id or a list of booking ids (separated by commas) to cancel.\n        :type booking_id: str"
  },
  {
    "code": "def build(self):\n        if self.colour:\n            embed = discord.Embed(\n                title=self.title,\n                type='rich',\n                description=self.description,\n                colour=self.colour)\n        else:\n            embed = discord.Embed(\n                title=self.title,\n                type='rich',\n                description=self.description)\n        if self.thumbnail:\n            embed.set_thumbnail(url=self.thumbnail)\n        if self.image:\n            embed.set_image(url=self.image)\n        embed.set_author(\n            name=\"Modis\",\n            url=\"https://musicbyango.com/modis/\",\n            icon_url=\"http://musicbyango.com/modis/dp/modis64t.png\")\n        for pack in self.datapacks:\n            embed.add_field(\n                name=pack[0],\n                value=pack[1],\n                inline=pack[2]\n            )\n        return embed",
    "docstring": "Builds Discord embed GUI\n\n        Returns:\n            discord.Embed: Built GUI"
  },
  {
    "code": "def printParams(paramDictionary, all=False, log=None):\n    if log is not None:\n        def output(msg):\n            log.info(msg)\n    else:\n        def output(msg):\n            print(msg)\n    if not paramDictionary:\n        output('No parameters were supplied')\n    else:\n        for key in sorted(paramDictionary):\n            if all or (not isinstance(paramDictionary[key], dict)) \\\n            and key[0] != '_':\n                output('\\t' + '\\t'.join([str(key) + ' :',\n                                         str(paramDictionary[key])]))\n        if log is None:\n            output('\\n')",
    "docstring": "Print nicely the parameters from the dictionary."
  },
  {
    "code": "def check_num(self, checks, radl):\n        prefixes = {}\n        for f in self.features:\n            if not isinstance(f, Feature):\n                continue\n            (prefix, sep, tail) = f.prop.partition(\".\")\n            if not sep or prefix not in checks:\n                continue\n            checks0 = checks[prefix]\n            (num, sep, suffix) = tail.partition(\".\")\n            try:\n                num = int(num)\n            except:\n                raise RADLParseException(\n                    \"Invalid property name; expected an index.\", line=f.line)\n            if not sep or suffix not in checks0:\n                continue\n            f._check(checks0[suffix], radl)\n            if prefix not in prefixes:\n                prefixes[prefix] = set()\n            prefixes[prefix].add(num)\n        for prefix, nums in prefixes.items():\n            if min(nums) != 0 or max(nums) != len(nums) - 1:\n                raise RADLParseException(\n                    \"Invalid indices values in properties '%s'\" % prefix)\n        return prefixes",
    "docstring": "Check types, operators and units in features with numbers.\n\n        Args:\n\n        - checks(dict of dict of str:tuples): keys are property name prefixes, and the\n          values are dict with keys are property name suffixes and values are iterable\n          as in ``_check_feature``.\n        - radl: passed to ``_check_feature``."
  },
  {
    "code": "def template(self):\n\t\ts = Template(self._IPTABLES_TEMPLATE)\n\t\treturn s.substitute(filtertable='\\n'.join(self.filters),\n\t\t\t\t\t\t\trawtable='\\n'.join(self.raw),\n\t\t\t\t\t\t\tmangletable='\\n'.join(self.mangle),\n\t\t\t\t\t\t\tnattable='\\n'.join(self.nat),\n\t\t\t\t\t\t\tdate=datetime.today())",
    "docstring": "Create a rules file in iptables-restore format"
  },
  {
    "code": "def bb_get_instr_max_width(basic_block):\n    asm_mnemonic_max_width = 0\n    for instr in basic_block:\n        if len(instr.mnemonic) > asm_mnemonic_max_width:\n            asm_mnemonic_max_width = len(instr.mnemonic)\n    return asm_mnemonic_max_width",
    "docstring": "Get maximum instruction mnemonic width"
  },
  {
    "code": "def _get_object_key(self, p_object):\n        matched_key = None\n        matched_index = None\n        if hasattr(p_object, self._searchNames[0]):\n            return getattr(p_object, self._searchNames[0])\n        for x in xrange(len(self._searchNames)):\n            key = self._searchNames[x]\n            if hasattr(p_object, key):\n                matched_key = key\n                matched_index = x\n        if matched_key is None:\n            raise KeyError()\n        if matched_index != 0 and self._searchOptimize:\n            self._searchNames.insert(0, self._searchNames.pop(matched_index))\n        return getattr(p_object, matched_key)",
    "docstring": "Get key from object"
  },
  {
    "code": "def grep_file(query, item):\n    return ['%s: %s' % (item, line) for line in open(item)\n            if re.search(query, line)]",
    "docstring": "This function performs the actual grep on a given file."
  },
  {
    "code": "def _make_sync_method(name):\n  def sync_wrapper(self, *args, **kwds):\n    method = getattr(self, name)\n    future = method(*args, **kwds)\n    return future.get_result()\n  return sync_wrapper",
    "docstring": "Helper to synthesize a synchronous method from an async method name.\n\n  Used by the @add_sync_methods class decorator below.\n\n  Args:\n    name: The name of the synchronous method.\n\n  Returns:\n    A method (with first argument 'self') that retrieves and calls\n    self.<name>, passing its own arguments, expects it to return a\n    Future, and then waits for and returns that Future's result."
  },
  {
    "code": "def save_credentials(self, profile):\n        filename = profile_path(S3_PROFILE_ID, profile)\n        creds = {\n            \"access_key\": self.access_key,\n            \"secret_key\": self.secret_key\n        }\n        dump_to_json(filename, creds)",
    "docstring": "Saves credentials to a dotfile so you can open them grab them later.\n\n        Parameters\n        ----------\n        profile: str\n            name for your profile (i.e. \"dev\", \"prod\")"
  },
  {
    "code": "def _create_serial_ports(serial_ports):\n    ports = []\n    keys = range(-9000, -9050, -1)\n    if serial_ports:\n        devs = [serial['adapter'] for serial in serial_ports]\n        log.trace('Creating serial ports %s', devs)\n        for port, key in zip(serial_ports, keys):\n            serial_port_device = _apply_serial_port(port, key, 'add')\n            ports.append(serial_port_device)\n    return ports",
    "docstring": "Returns a list of vim.vm.device.VirtualDeviceSpec objects representing the\n    serial ports to be created for a virtual machine\n\n    serial_ports\n        Serial port properties"
  },
  {
    "code": "def warning(self, msg, indent=0, **kwargs):\n        return self.logger.warning(self._indent(msg, indent), **kwargs)",
    "docstring": "invoke ``self.logger.warning``"
  },
  {
    "code": "def get_top_tags(self, limit=None, cacheable=True):\n        doc = _Request(self, \"tag.getTopTags\").execute(cacheable)\n        seq = []\n        for node in doc.getElementsByTagName(\"tag\"):\n            if limit and len(seq) >= limit:\n                break\n            tag = Tag(_extract(node, \"name\"), self)\n            weight = _number(_extract(node, \"count\"))\n            seq.append(TopItem(tag, weight))\n        return seq",
    "docstring": "Returns the most used tags as a sequence of TopItem objects."
  },
  {
    "code": "def set_extent_location(self, new_location, main_vd_extent, reserve_vd_extent):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('UDF Anchor Volume Structure not yet initialized')\n        self.new_extent_loc = new_location\n        self.desc_tag.tag_location = new_location\n        self.main_vd_extent = main_vd_extent\n        self.reserve_vd_extent = reserve_vd_extent",
    "docstring": "A method to set a new location for this Anchor Volume Structure.\n\n        Parameters:\n         new_location - The new extent that this Anchor Volume Structure should be located at.\n         main_vd_extent - The extent containing the main Volume Descriptors.\n         reserve_vd_extent - The extent containing the reserve Volume Descriptors.\n        Returns:\n         Nothing."
  },
  {
    "code": "def destination(self):\n        return os.path.join(os.path.abspath(self.outdir), self.filename)",
    "docstring": "Get the destination path.\n\n        This is the property should be calculated every time it is used because\n        a user could change the outdir and filename dynamically."
  },
  {
    "code": "def write(self, obj, **kwargs):\n        super().write(obj, **kwargs)\n        for name, ss in obj.items():\n            key = 'sparse_series_{name}'.format(name=name)\n            if key not in self.group._v_children:\n                node = self._handle.create_group(self.group, key)\n            else:\n                node = getattr(self.group, key)\n            s = SparseSeriesFixed(self.parent, node)\n            s.write(ss)\n        self.attrs.default_fill_value = obj.default_fill_value\n        self.attrs.default_kind = obj.default_kind\n        self.write_index('columns', obj.columns)",
    "docstring": "write it as a collection of individual sparse series"
  },
  {
    "code": "def add2python(self, module=None, up=0, down=None, front=False,\n                   must_exist=True):\n        if module:\n            try:\n                return import_module(module)\n            except ImportError:\n                pass\n        dir = self.dir().ancestor(up)\n        if down:\n            dir = dir.join(*down)\n        if dir.isdir():\n            if dir not in sys.path:\n                if front:\n                    sys.path.insert(0, dir)\n                else:\n                    sys.path.append(dir)\n        elif must_exist:\n            raise ImportError('Directory {0} not available'.format(dir))\n        else:\n            return None\n        if module:\n            try:\n                return import_module(module)\n            except ImportError:\n                if must_exist:\n                    raise",
    "docstring": "Add a directory to the python path.\n\n        :parameter module: Optional module name to try to import once we\n            have found the directory\n        :parameter up: number of level to go up the directory three from\n            :attr:`local_path`.\n        :parameter down: Optional tuple of directory names to travel down\n            once we have gone *up* levels.\n        :parameter front: Boolean indicating if we want to insert the new\n            path at the front of ``sys.path`` using\n            ``sys.path.insert(0,path)``.\n        :parameter must_exist: Boolean indicating if the module must exists."
  },
  {
    "code": "def _linux_stp(br, state):\n    brctl = _tool_path('brctl')\n    return __salt__['cmd.run']('{0} stp {1} {2}'.format(brctl, br, state),\n                               python_shell=False)",
    "docstring": "Internal, sets STP state"
  },
  {
    "code": "def fail_request(self, orig_request, message, start_response):\n    cors_handler = self._create_cors_handler(orig_request)\n    return util.send_wsgi_error_response(\n        message, start_response, cors_handler=cors_handler)",
    "docstring": "Write an immediate failure response to outfile, no redirect.\n\n    This calls start_response and returns the error body.\n\n    Args:\n      orig_request: An ApiRequest, the original request from the user.\n      message: A string containing the error message to be displayed to user.\n      start_response: A function with semantics defined in PEP-333.\n\n    Returns:\n      A string containing the body of the error response."
  },
  {
    "code": "def adj_nodes_aws(aws_nodes):\n    for node in aws_nodes:\n        node.cloud = \"aws\"\n        node.cloud_disp = \"AWS\"\n        node.private_ips = ip_to_str(node.private_ips)\n        node.public_ips = ip_to_str(node.public_ips)\n        node.zone = node.extra['availability']\n        node.size = node.extra['instance_type']\n        node.type = node.extra['instance_lifecycle']\n    return aws_nodes",
    "docstring": "Adjust details specific to AWS."
  },
  {
    "code": "def timestamp(num_params, p_levels, k_choices, N):\n    string = \"_v%s_l%s_gs%s_k%s_N%s_%s.txt\" % (num_params,\n                                               p_levels,\n                                               k_choices,\n                                               N,\n                                               dt.strftime(dt.now(),\n                                                           \"%d%m%y%H%M%S\"))\n    return string",
    "docstring": "Returns a uniform timestamp with parameter values for file identification"
  },
  {
    "code": "def mod(self):\n        if self._mod is None:\n            self._mod = self.compile_and_import_binary()\n        return self._mod",
    "docstring": "Cached compiled binary of the Generic_Code class.\n\n        To clear cache invoke :meth:`clear_mod_cache`."
  },
  {
    "code": "def get_users(self, fetch=True):\n        return Users(self.resource.users, self.client, populate=fetch)",
    "docstring": "Return this Applications's users object, populating it if fetch\n        is True."
  },
  {
    "code": "def setCmd(self, cmd):\n        cmd = cmd.upper()\n        if cmd not in VALID_COMMANDS:\n            raise FrameError(\"The cmd '%s' is not valid! It must be one of '%s' (STOMP v%s).\" % (\n                cmd, VALID_COMMANDS, STOMP_VERSION)\n            )\n        else:\n            self._cmd = cmd",
    "docstring": "Check the cmd is valid, FrameError will be raised if its not."
  },
  {
    "code": "def expression_list_to_conjunction(expression_list):\n    if not isinstance(expression_list, list):\n        raise AssertionError(u'Expected `list`, Received {}.'.format(expression_list))\n    if len(expression_list) == 0:\n        return TrueLiteral\n    if not isinstance(expression_list[0], Expression):\n        raise AssertionError(u'Non-Expression object {} found in expression_list'\n                             .format(expression_list[0]))\n    if len(expression_list) == 1:\n        return expression_list[0]\n    else:\n        return BinaryComposition(u'&&',\n                                 expression_list_to_conjunction(expression_list[1:]),\n                                 expression_list[0])",
    "docstring": "Convert a list of expressions to an Expression that is the conjunction of all of them."
  },
  {
    "code": "def modify(self, vals):\n        self.vals = vals.view(np.ndarray).copy()\n        y = self.model.predict(self.vals)[0]\n        self.data_visualize.modify(y)\n        self.latent_handle.set_data(self.vals[0,self.latent_index[0]], self.vals[0,self.latent_index[1]])\n        self.axes.figure.canvas.draw()",
    "docstring": "When latent values are modified update the latent representation and ulso update the output visualization."
  },
  {
    "code": "def to_feature(self, name=None, feature_type='misc_feature'):\n        if name is None:\n            if not self.name:\n                raise ValueError('name attribute missing from DNA instance'\n                                 ' and arguments')\n            name = self.name\n        return Feature(name, start=0, stop=len(self),\n                       feature_type=feature_type)",
    "docstring": "Create a feature from the current object.\n\n        :param name: Name for the new feature. Must be specified if the DNA\n                     instance has no .name attribute.\n        :type name: str\n        :param feature_type: The type of feature (genbank standard).\n        :type feature_type: str"
  },
  {
    "code": "def account(transition, direction=Direction.BIDIRECTIONAL):\n    if direction != Direction.BIDIRECTIONAL:\n        return directed_account(transition, direction)\n    return Account(directed_account(transition, Direction.CAUSE) +\n                   directed_account(transition, Direction.EFFECT))",
    "docstring": "Return the set of all causal links for a |Transition|.\n\n    Args:\n        transition (Transition): The transition of interest.\n\n    Keyword Args:\n        direction (Direction): By default the account contains actual causes\n            and actual effects."
  },
  {
    "code": "def from_file(cls, filename=\"CTRL\", **kwargs):\n        with zopen(filename, \"rt\") as f:\n            contents = f.read()\n        return LMTOCtrl.from_string(contents, **kwargs)",
    "docstring": "Creates a CTRL file object from an existing file.\n\n        Args:\n            filename: The name of the CTRL file. Defaults to 'CTRL'.\n\n        Returns:\n            An LMTOCtrl object."
  },
  {
    "code": "async def detach_tip(data):\n    global session\n    if not feature_flags.use_protocol_api_v2():\n        pipette = session.pipettes[session.current_mount]\n        if not pipette.tip_attached:\n            log.warning('detach tip called with no tip')\n        pipette._remove_tip(session.tip_length)\n    else:\n        session.adapter.remove_tip(session.current_mount)\n        if session.cp:\n            session.cp = CriticalPoint.NOZZLE\n    session.tip_length = None\n    return web.json_response({'message': \"Tip removed\"}, status=200)",
    "docstring": "Detach the tip from the current pipette\n\n    :param data: Information obtained from a POST request.\n    The content type is application/json.\n    The correct packet form should be as follows:\n    {\n      'token': UUID token from current session start\n      'command': 'detach tip'\n    }"
  },
  {
    "code": "def attention_lm_decoder(decoder_input,\n                         decoder_self_attention_bias,\n                         hparams,\n                         name=\"decoder\"):\n  x = decoder_input\n  with tf.variable_scope(name):\n    for layer in range(hparams.num_hidden_layers):\n      with tf.variable_scope(\"layer_%d\" % layer):\n        with tf.variable_scope(\"self_attention\"):\n          y = common_attention.multihead_attention(\n              common_layers.layer_preprocess(\n                  x, hparams), None, decoder_self_attention_bias,\n              hparams.attention_key_channels or hparams.hidden_size,\n              hparams.attention_value_channels or hparams.hidden_size,\n              hparams.hidden_size, hparams.num_heads, hparams.attention_dropout)\n          x = common_layers.layer_postprocess(x, y, hparams)\n        with tf.variable_scope(\"ffn\"):\n          y = common_layers.conv_hidden_relu(\n              common_layers.layer_preprocess(x, hparams),\n              hparams.filter_size,\n              hparams.hidden_size,\n              dropout=hparams.relu_dropout)\n          x = common_layers.layer_postprocess(x, y, hparams)\n    return common_layers.layer_preprocess(x, hparams)",
    "docstring": "A stack of attention_lm layers.\n\n  Args:\n    decoder_input: a Tensor\n    decoder_self_attention_bias: bias Tensor for self-attention\n      (see common_attention.attention_bias())\n    hparams: hyperparameters for model\n    name: a string\n\n  Returns:\n    y: a Tensors"
  },
  {
    "code": "def partition_ordered(sequence, key=None):\n    yield from ((k, list(g)) for k, g in groupby(sequence, key=key))",
    "docstring": "Partition ordered sequence by key.\n\n    Sequence is expected to already be ordered.\n\n    Parameters\n    ----------\n    sequence: iterable data.\n    key: partition key function\n\n    Yields\n    -------\n    iterable tuple(s) of partition key, data list pairs.\n\n    Examples\n    --------\n    1. By object attributes.\n\n    Partition sequence of objects by a height and weight attributes\n    into an ordered dict.\n\n    >> attributes = ('height', 'weight')\n    >> OrderedDict(partition_ordered(sequence, attrgetter(*attributes)))\n\n    2. By index items.\n\n    Partition sequence by the first character index of each element.\n\n    >> index = 0\n    >> sequence = ['112', '124', '289', '220', 'Z23']\n    >> list(partition_ordered(sequence, itemgetter(index)))"
  },
  {
    "code": "def Rz_matrix(theta):\n    return np.array([\n        [np.cos(theta), -np.sin(theta), 0],\n        [np.sin(theta), np.cos(theta), 0],\n        [0, 0, 1]\n    ])",
    "docstring": "Rotation matrix around the Z axis"
  },
  {
    "code": "def _any(objs, query):\n    for obj in objs:\n        if isinstance(obj, Document):\n            if _any(obj.roots, query):\n                return True\n        else:\n            if any(query(ref) for ref in obj.references()):\n                return True\n    else:\n        return False",
    "docstring": "Whether any of a collection of objects satisfies a given query predicate\n\n    Args:\n        objs (seq[Model or Document]) :\n\n        query (callable)\n\n    Returns:\n        True, if ``query(obj)`` is True for some object in ``objs``, else False"
  },
  {
    "code": "def decrease_user_property(self, user_id, property_name, value=0, headers=None, endpoint_url=None):\n        endpoint_url = endpoint_url or self._endpoint_url\n        url = endpoint_url + \"/users/\" + user_id + \"/properties/\" + property_name + \"/decrease/\" + value.__str__()\n        headers = headers or self._default_headers(content_type=\"\")\n        response = requests.post(url, headers=headers)\n        return response",
    "docstring": "Decrease a user's property by a value.\n\n        :param str user_id: identified user's ID\n        :param str property_name: user property name to increase\n        :param number value: amount by which to decrease the property\n        :param dict headers: custom request headers (if isn't set default values are used)\n        :param str endpoint_url: where to send the request (if isn't set default value is used)\n        :return: Response"
  },
  {
    "code": "def frag2text(endpoint, stype, selector,\n              clean=False, raw=False, verbose=False):\n    try:\n        return main(endpoint, stype, selector, clean, raw, verbose)\n    except StandardError as err:\n        return err",
    "docstring": "returns Markdown text of selected fragment.\n\n    Args:\n        endpoint: URL, file, or HTML string\n        stype: { 'css' | 'xpath' }\n        selector: CSS selector or XPath expression\n    Returns:\n        Markdown text\n    Options:\n        clean: cleans fragment (lxml.html.clean defaults)\n        raw: returns raw HTML fragment\n        verbose: show http status, encoding, headers"
  },
  {
    "code": "def _resolve_subkeys(key, separator=\".\"):\n    parts = key.split(separator, 1)\n    if len(parts) > 1:\n        return parts\n    else:\n        return parts[0], None",
    "docstring": "Resolve a potentially nested key.\n\n    If the key contains the ``separator`` (e.g. ``.``) then the key will be\n    split on the first instance of the subkey::\n\n       >>> _resolve_subkeys('a.b.c')\n       ('a', 'b.c')\n       >>> _resolve_subkeys('d|e|f', separator='|')\n       ('d', 'e|f')\n\n    If not, the subkey will be :data:`None`::\n\n        >>> _resolve_subkeys('foo')\n        ('foo', None)\n\n    Args:\n        key (str): A string that may or may not contain the separator.\n        separator (str): The namespace separator. Defaults to `.`.\n\n    Returns:\n        Tuple[str, str]: The key and subkey(s)."
  },
  {
    "code": "def generalized_negative_binomial(mu=1, alpha=1, shape=_Null, dtype=_Null, **kwargs):\n    return _random_helper(_internal._random_generalized_negative_binomial,\n                          _internal._sample_generalized_negative_binomial,\n                          [mu, alpha], shape, dtype, kwargs)",
    "docstring": "Draw random samples from a generalized negative binomial distribution.\n\n    Samples are distributed according to a generalized negative binomial\n    distribution parametrized by *mu* (mean) and *alpha* (dispersion).\n    *alpha* is defined as *1/k* where *k* is the failure limit of the\n    number of unsuccessful experiments (generalized to real numbers).\n    Samples will always be returned as a floating point data type.\n\n    Parameters\n    ----------\n    mu : float or Symbol, optional\n        Mean of the negative binomial distribution.\n    alpha : float or Symbol, optional\n        Alpha (dispersion) parameter of the negative binomial distribution.\n    shape : int or tuple of ints, optional\n        The number of samples to draw. If shape is, e.g., `(m, n)` and `mu` and\n        `alpha` are scalars, output shape will be `(m, n)`. If `mu` and `alpha`\n        are Symbols with shape, e.g., `(x, y)`, then output will have shape\n        `(x, y, m, n)`, where `m*n` samples are drawn for each `[mu, alpha)` pair.\n    dtype : {'float16', 'float32', 'float64'}, optional\n        Data type of output samples. Default is 'float32'\n\n    Returns\n    -------\n    Symbol\n        If input `shape` has dimensions, e.g., `(m, n)`, and `mu` and\n        `alpha` are scalars, returned Symbol will resolve to shape `(m, n)`. If `mu`\n        and `alpha` are Symbols with shape, e.g., `(x, y)`, returned Symbol will resolve\n        to shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[mu, alpha)` pair."
  },
  {
    "code": "def warning_handler(self, handler):\n        if not self.opened():\n            handler = handler or util.noop\n            self._warning_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)\n            self._dll.JLINKARM_SetWarnOutHandler(self._warning_handler)",
    "docstring": "Setter for the warning handler function.\n\n        If the DLL is open, this function is a no-op, so it should be called\n        prior to calling ``open()``.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          handler (function): function to call on warning messages\n\n        Returns:\n          ``None``"
  },
  {
    "code": "def nansum(values, axis=None, skipna=True, min_count=0, mask=None):\n    values, mask, dtype, dtype_max, _ = _get_values(values,\n                                                    skipna, 0, mask=mask)\n    dtype_sum = dtype_max\n    if is_float_dtype(dtype):\n        dtype_sum = dtype\n    elif is_timedelta64_dtype(dtype):\n        dtype_sum = np.float64\n    the_sum = values.sum(axis, dtype=dtype_sum)\n    the_sum = _maybe_null_out(the_sum, axis, mask, min_count=min_count)\n    return _wrap_results(the_sum, dtype)",
    "docstring": "Sum the elements along an axis ignoring NaNs\n\n    Parameters\n    ----------\n    values : ndarray[dtype]\n    axis: int, optional\n    skipna : bool, default True\n    min_count: int, default 0\n    mask : ndarray[bool], optional\n        nan-mask if known\n\n    Returns\n    -------\n    result : dtype\n\n    Examples\n    --------\n    >>> import pandas.core.nanops as nanops\n    >>> s = pd.Series([1, 2, np.nan])\n    >>> nanops.nansum(s)\n    3.0"
  },
  {
    "code": "def merge_figures(figures):\n\tfigure={}\n\tdata=[]\n\tfor fig in figures:\n\t\tfor trace in fig['data']:\n\t\t\tdata.append(trace)\n\tlayout=get_base_layout(figures)\n\tfigure['data']=data\n\tfigure['layout']=layout\n\treturn figure",
    "docstring": "Generates a single Figure from a list of figures\n\n\tParameters:\n\t-----------\n\t\tfigures : list(Figures)\n\t\t\tList of figures to be merged."
  },
  {
    "code": "def clear_masters(self):\n        packages = []\n        for mas in Utils().remove_dbs(self.packages):\n            if mas not in self.dependencies:\n                packages.append(mas)\n        self.packages = packages",
    "docstring": "Clear master packages if already exist in dependencies\n        or if added to install two or more times"
  },
  {
    "code": "def is_empty(self):\n        return (not self.breakpoint and not self.code_analysis\n                and not self.todo and not self.bookmarks)",
    "docstring": "Return whether the block of user data is empty."
  },
  {
    "code": "def initialize_remaining_constants(self, value=0):\n        remaining = []\n        for node, _inputs, _outputs in self.iterate_bfs():\n            streams = node.input_streams() + [node.stream]\n            for stream in streams:\n                if stream.stream_type is not DataStream.ConstantType:\n                    continue\n                if stream not in self.constant_database:\n                    self.add_constant(stream, value)\n                    remaining.append(stream)\n        return remaining",
    "docstring": "Ensure that all constant streams referenced in the sensor graph have a value.\n\n        Constant streams that are automatically created by the compiler are initialized\n        as part of the compilation process but it's possible that the user references\n        other constant streams but never assigns them an explicit initial value.  This\n        function will initialize them all to a default value (0 if not passed) and\n        return the streams that were so initialized.\n\n        Args:\n            value (int): Optional value to use to initialize all uninitialized constants.\n                Defaults to 0 if not passed.\n\n        Returns:\n            list(DataStream): A list of all of the constant streams that were not previously\n                initialized and were initialized to the given value in this function."
  },
  {
    "code": "def get_default():\n    if not is_configured():\n        raise JutException('No configurations available, please run `jut config add`')\n    for configuration in _CONFIG.sections():\n        if _CONFIG.has_option(configuration, 'default'):\n            return dict(_CONFIG.items(configuration))",
    "docstring": "return the attributes associated with the default configuration"
  },
  {
    "code": "def forward(self, channel, date_s, fragment):\n\t\ttime_s, sep, nick = fragment.rpartition('.')\n\t\ttime = datetime.datetime.strptime(time_s, '%H.%M.%S')\n\t\tdate = datetime.datetime.strptime(date_s, '%Y-%m-%d')\n\t\tdt = datetime.datetime.combine(date, time.time())\n\t\tloc_dt = self.timezone.localize(dt)\n\t\tutc_dt = loc_dt.astimezone(pytz.utc)\n\t\turl_tmpl = '/day/{channel}/{target_date}\n\t\turl = url_tmpl.format(\n\t\t\ttarget_date=utc_dt.date().isoformat(),\n\t\t\ttarget_time=utc_dt.time().strftime('%H.%M.%S'),\n\t\t\t**locals()\n\t\t)\n\t\traise cherrypy.HTTPRedirect(url, 301)",
    "docstring": "Given an HREF in the legacy timezone, redirect to an href for UTC."
  },
  {
    "code": "def FilterMessages(\n        self,\n        Channel,\n        FromID,\n        ToID,\n        Mode):\n        try:\n            res = self.__m_dllBasic.CAN_FilterMessages(Channel,FromID,ToID,Mode)\n            return TPCANStatus(res)\n        except:\n            logger.error(\"Exception on PCANBasic.FilterMessages\")\n            raise",
    "docstring": "Configures the reception filter\n\n        Remarks:\n          The message filter will be expanded with every call to this function.\n          If it is desired to reset the filter, please use the 'SetValue' function.\n\n        Parameters:\n          Channel : A TPCANHandle representing a PCAN Channel\n          FromID  : A c_uint value with the lowest CAN ID to be received\n          ToID    : A c_uint value with the highest CAN ID to be received\n          Mode    : A TPCANMode representing the message type (Standard, 11-bit\n                    identifier, or Extended, 29-bit identifier)\n\n        Returns:\n          A TPCANStatus error code"
  },
  {
    "code": "def _create_token(token_type, value, lineno, lexpos):\n    token = lex.LexToken()\n    token.type = token_type\n    token.value = value\n    token.lineno = lineno\n    token.lexpos = lexpos\n    return token",
    "docstring": "Helper for creating ply.lex.LexToken objects. Unfortunately, LexToken\n    does not have a constructor defined to make settings these values easy."
  },
  {
    "code": "def _accumulate_sufficient_statistics(self, stats, X, framelogprob,\n                                          posteriors, fwdlattice, bwdlattice):\n        stats['nobs'] += 1\n        if 's' in self.params:\n            stats['start'] += posteriors[0]\n        if 't' in self.params:\n            n_samples, n_components = framelogprob.shape\n            if n_samples <= 1:\n                return\n            log_xi_sum = np.full((n_components, n_components), -np.inf)\n            _hmmc._compute_log_xi_sum(n_samples, n_components, fwdlattice,\n                                      log_mask_zero(self.transmat_),\n                                      bwdlattice, framelogprob,\n                                      log_xi_sum)\n            with np.errstate(under=\"ignore\"):\n                stats['trans'] += np.exp(log_xi_sum)",
    "docstring": "Updates sufficient statistics from a given sample.\n\n        Parameters\n        ----------\n        stats : dict\n            Sufficient statistics as returned by\n            :meth:`~base._BaseHMM._initialize_sufficient_statistics`.\n\n        X : array, shape (n_samples, n_features)\n            Sample sequence.\n\n        framelogprob : array, shape (n_samples, n_components)\n            Log-probabilities of each sample under each of the model states.\n\n        posteriors : array, shape (n_samples, n_components)\n            Posterior probabilities of each sample being generated by each\n            of the model states.\n\n        fwdlattice, bwdlattice : array, shape (n_samples, n_components)\n            Log-forward and log-backward probabilities."
  },
  {
    "code": "def find_steam_location():\n  if registry is None:\n    return None\n  key = registry.CreateKey(registry.HKEY_CURRENT_USER,\"Software\\Valve\\Steam\")\n  return registry.QueryValueEx(key,\"SteamPath\")[0]",
    "docstring": "Finds the location of the current Steam installation on Windows machines.\n  Returns None for any non-Windows machines, or for Windows machines where\n  Steam is not installed."
  },
  {
    "code": "def deregister():\n    for type_, cls in get_pairs():\n        if type(units.registry.get(type_)) is cls:\n            units.registry.pop(type_)\n    for unit, formatter in _mpl_units.items():\n        if type(formatter) not in {DatetimeConverter, PeriodConverter,\n                                   TimeConverter}:\n            units.registry[unit] = formatter",
    "docstring": "Remove pandas' formatters and converters\n\n    Removes the custom converters added by :func:`register`. This\n    attempts to set the state of the registry back to the state before\n    pandas registered its own units. Converters for pandas' own types like\n    Timestamp and Period are removed completely. Converters for types\n    pandas overwrites, like ``datetime.datetime``, are restored to their\n    original value.\n\n    See Also\n    --------\n    deregister_matplotlib_converters"
  },
  {
    "code": "def print_rendered_results(results_dict):\n    class _HubComponentEncoder(json.JSONEncoder):\n        def default(self, o):\n            if isinstance(o, base.HubComponent):\n                return repr(o)\n            return json.JSONEncoder.default(self, o)\n    formatted = json.dumps(results_dict, indent=4, cls=_HubComponentEncoder)\n    for s in formatted.splitlines():\n        print(s.rstrip())",
    "docstring": "Pretty-prints the rendered results dictionary.\n\n    Rendered results can be multiply-nested dictionaries; this uses JSON\n    serialization to print a nice representation."
  },
  {
    "code": "def prepare_impact_function(self):\n        impact_function = ImpactFunction()\n        impact_function.callback = self.progress_callback\n        impact_function.hazard = self.parent.hazard_layer\n        impact_function.exposure = self.parent.exposure_layer\n        aggregation = self.parent.aggregation_layer\n        if aggregation:\n            impact_function.aggregation = aggregation\n            impact_function.use_selected_features_only = (\n                setting('useSelectedFeaturesOnly', False, bool))\n        else:\n            impact_function.crs = self.extent.crs\n            mode = setting('analysis_extents_mode')\n            if self.extent.user_extent:\n                wkt = self.extent.user_extent.asWkt()\n                impact_function.requested_extent = wkt_to_rectangle(wkt)\n            elif mode == HAZARD_EXPOSURE_VIEW:\n                impact_function.requested_extent = (\n                    self.iface.mapCanvas().extent())\n            elif mode == EXPOSURE:\n                impact_function.use_exposure_view_only = True\n        impact_function.debug_mode = False\n        return impact_function",
    "docstring": "Create analysis as a representation of current situation of IFCW."
  },
  {
    "code": "def update(self):\n        stats = self.get_init_value()\n        if self.input_method == 'local':\n            stats['cpu'] = cpu_percent.get()\n            stats['percpu'] = cpu_percent.get(percpu=True)\n            stats['mem'] = psutil.virtual_memory().percent\n            stats['swap'] = psutil.swap_memory().percent\n        elif self.input_method == 'snmp':\n            pass\n        if cpuinfo_tag:\n            cpu_info = cpuinfo.get_cpu_info()\n            if cpu_info is not None:\n                stats['cpu_name'] = cpu_info.get('brand', 'CPU')\n                if 'hz_actual_raw' in cpu_info:\n                    stats['cpu_hz_current'] = cpu_info['hz_actual_raw'][0]\n                if 'hz_advertised_raw' in cpu_info:\n                    stats['cpu_hz'] = cpu_info['hz_advertised_raw'][0]\n        self.stats = stats\n        return self.stats",
    "docstring": "Update quicklook stats using the input method."
  },
  {
    "code": "def set_ipcsem_params(self, ftok=None, persistent=None):\n        self._set('ftok', ftok)\n        self._set('persistent-ipcsem', persistent, cast=bool)\n        return self._section",
    "docstring": "Sets ipcsem lock engine params.\n\n        :param str|unicode ftok: Set the ipcsem key via ftok() for avoiding duplicates.\n\n        :param bool persistent: Do not remove ipcsem's on shutdown."
  },
  {
    "code": "def is_broker_action_done(action, rid=None, unit=None):\n    rdata = relation_get(rid, unit) or {}\n    broker_rsp = rdata.get(get_broker_rsp_key())\n    if not broker_rsp:\n        return False\n    rsp = CephBrokerRsp(broker_rsp)\n    unit_name = local_unit().partition('/')[2]\n    key = \"unit_{}_ceph_broker_action.{}\".format(unit_name, action)\n    kvstore = kv()\n    val = kvstore.get(key=key)\n    if val and val == rsp.request_id:\n        return True\n    return False",
    "docstring": "Check whether broker action has completed yet.\n\n    @param action: name of action to be performed\n    @returns True if action complete otherwise False"
  },
  {
    "code": "def get_proficiencies_for_objectives(self, objective_ids):\n        collection = JSONClientValidated('learning',\n                                         collection='Proficiency',\n                                         runtime=self._runtime)\n        result = collection.find(\n            dict({'objectiveId': str(objective_ids)},\n                 **self._view_filter())).sort('_id', ASCENDING)\n        return objects.ProficiencyList(result, runtime=self._runtime)",
    "docstring": "Gets a ``ProficiencyList`` relating to the given objectives.\n\n        arg:    objective_ids (osid.id.IdList): the objective ``Ids``\n        return: (osid.learning.ProficiencyList) - the returned\n                ``Proficiency`` list\n        raise:  NullArgument - ``objective_ids`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_pg_core(connection_string, *, cursor_factory=None, edit_connection=None):\n  import psycopg2 as pq\n  from psycopg2.extras import NamedTupleCursor\n  def opener():\n    cn = pq.connect(connection_string)\n    cn.cursor_factory = cursor_factory or NamedTupleCursor\n    if edit_connection:\n      edit_connection(cn)\n    return cn\n  return InjectedDataAccessCore(\n    opener,\n    default_connection_closer,\n    (\"%({0})s\", \"%s\", \"{0}::{1}\"),\n    empty_params=None,\n    supports_timezones=True,\n    supports_returning_syntax=True,\n    get_autocommit=get_pg_autocommit,\n    set_autocommit=set_pg_autocommit)",
    "docstring": "Creates a simple PostgreSQL core. Requires the psycopg2 library."
  },
  {
    "code": "def getDiskFreeSpace(\n        self,\n        freeBytesAvailable,\n        totalNumberOfBytes,\n        totalNumberOfFreeBytes,\n        dokanFileInfo,\n    ):\n        ret = self.operations('getDiskFreeSpace')\n        ctypes.memmove(\n            freeBytesAvailable,\n            ctypes.byref(ctypes.c_longlong(ret['freeBytesAvailable'])),\n            ctypes.sizeof(ctypes.c_longlong),\n        )\n        ctypes.memmove(\n            totalNumberOfBytes,\n            ctypes.byref(ctypes.c_longlong(ret['totalNumberOfBytes'])),\n            ctypes.sizeof(ctypes.c_longlong),\n        )\n        ctypes.memmove(\n            totalNumberOfFreeBytes,\n            ctypes.byref(ctypes.c_longlong(ret['totalNumberOfFreeBytes'])),\n            ctypes.sizeof(ctypes.c_longlong),\n        )\n        return d1_onedrive.impl.drivers.dokan.const.DOKAN_SUCCESS",
    "docstring": "Get the amount of free space on this volume.\n\n        :param freeBytesAvailable: pointer for free bytes available\n        :type freeBytesAvailable: ctypes.c_void_p\n        :param totalNumberOfBytes: pointer for total number of bytes\n        :type totalNumberOfBytes: ctypes.c_void_p\n        :param totalNumberOfFreeBytes: pointer for total number of free bytes\n        :type totalNumberOfFreeBytes: ctypes.c_void_p\n        :param dokanFileInfo: used by Dokan\n        :type dokanFileInfo: PDOKAN_FILE_INFO\n        :return: error code\n        :rtype: ctypes.c_int"
  },
  {
    "code": "def async_session_handler(self, signal: str) -> None:\n        if signal == 'data':\n            self.async_event_handler(self.websocket.data)\n        elif signal == 'state':\n            if self.async_connection_status_callback:\n                self.async_connection_status_callback(\n                    self.websocket.state == 'running')",
    "docstring": "Signalling from websocket.\n\n           data - new data available for processing.\n           state - network state has changed."
  },
  {
    "code": "def countExtn(fimg, extname='SCI'):\n    closefits = False\n    if isinstance(fimg, string_types):\n        fimg = fits.open(fimg)\n        closefits = True\n    n = 0\n    for e in fimg:\n        if 'extname' in e.header and e.header['extname'] == extname:\n            n += 1\n    if closefits:\n        fimg.close()\n    return n",
    "docstring": "Return the number of 'extname' extensions, defaulting to counting the\n    number of SCI extensions."
  },
  {
    "code": "def frame2string(frame):\n    lineno = frame.f_lineno\n    co = frame.f_code\n    filename = co.co_filename\n    name = co.co_name\n    s = '\\tFile \"{0}\", line {1}, in {2}'.format(filename, lineno, name)\n    line = linecache.getline(filename, lineno, frame.f_globals).lstrip()\n    return s + '\\n\\t\\t' + line",
    "docstring": "Return info about frame.\n\n    Keyword arg:\n        frame\n\n    Return string in format:\n\n    File {file name}, line {line number}, in \n    {name of parent of code object} {newline}\n    Line from file at line number"
  },
  {
    "code": "def __init_url(self):\n        portals_self_url = \"{}/portals/self\".format(self._url)\n        params = {\n            \"f\" :\"json\"\n        }\n        if not self._securityHandler is None:\n            params['token'] = self._securityHandler.token\n        res = self._get(url=portals_self_url,\n                           param_dict=params,\n                           securityHandler=self._securityHandler,\n                           proxy_url=self._proxy_url,\n                           proxy_port=self._proxy_port)\n        if \"helperServices\" in res:\n            helper_services = res.get(\"helperServices\")\n            if \"hydrology\" in helper_services:\n                analysis_service = helper_services.get(\"elevation\")\n                if \"url\" in analysis_service:\n                    self._analysis_url = analysis_service.get(\"url\")\n        self._gpService = GPService(url=self._analysis_url,\n                                    securityHandler=self._securityHandler,\n                                    proxy_url=self._proxy_url,\n                                    proxy_port=self._proxy_port,\n                                    initialize=False)",
    "docstring": "loads the information into the class"
  },
  {
    "code": "def get_ignored_lines(self):\n        ignored_lines = set()\n        for line_number, line in enumerate(self.content.split('\\n'), 1):\n            if (\n                WHITELIST_REGEX['yaml'].search(line)\n                or (\n                    self.exclude_lines_regex and\n                    self.exclude_lines_regex.search(line)\n                )\n            ):\n                ignored_lines.add(line_number)\n        return ignored_lines",
    "docstring": "Return a set of integers that refer to line numbers that were\n        whitelisted by the user and should be ignored.\n\n        We need to parse the file separately from PyYAML parsing because\n        the parser drops the comments (at least up to version 3.13):\n        https://github.com/yaml/pyyaml/blob/a2d481b8dbd2b352cb001f07091ccf669227290f/lib3/yaml/scanner.py#L749\n\n        :return: set"
  },
  {
    "code": "def uuid(self, type, val):\n        picker = lambda x: x.get('uuid', x)\n        return self._get((type, val), picker)",
    "docstring": "Return the item-uuid for a identifier"
  },
  {
    "code": "def fail_hosts(self, hosts_to_fail, activated_count=None):\n        if not hosts_to_fail:\n            return\n        activated_count = activated_count or len(self.activated_hosts)\n        logger.debug('Failing hosts: {0}'.format(', '.join(\n            (host.name for host in hosts_to_fail),\n        )))\n        self.active_hosts -= hosts_to_fail\n        active_hosts = self.active_hosts\n        if not active_hosts:\n            raise PyinfraError('No hosts remaining!')\n        if self.config.FAIL_PERCENT is not None:\n            percent_failed = (\n                1 - len(active_hosts) / activated_count\n            ) * 100\n            if percent_failed > self.config.FAIL_PERCENT:\n                raise PyinfraError('Over {0}% of hosts failed ({1}%)'.format(\n                    self.config.FAIL_PERCENT,\n                    int(round(percent_failed)),\n                ))",
    "docstring": "Flag a ``set`` of hosts as failed, error for ``config.FAIL_PERCENT``."
  },
  {
    "code": "def Initialize(self):\n    super(GRRFlow, self).Initialize()\n    self._client_version = None\n    self._client_os = None\n    self._client_knowledge_base = None\n    if \"r\" in self.mode:\n      state = self.Get(self.Schema.FLOW_STATE_DICT)\n      self.context = self.Get(self.Schema.FLOW_CONTEXT)\n      self.runner_args = self.Get(self.Schema.FLOW_RUNNER_ARGS)\n      args = self.Get(self.Schema.FLOW_ARGS)\n      if args:\n        self.args = args.payload\n      if state:\n        self.state = AttributedDict(state.ToDict())\n      else:\n        self.state = AttributedDict()\n      self.Load()\n    if self.state is None:\n      self.state = AttributedDict()",
    "docstring": "The initialization method."
  },
  {
    "code": "def _delay(self):\n        if not self.next_scheduled:\n            self.next_scheduled = self.clock_func() + self.interval\n            return\n        while True:\n            current = self.clock_func()\n            if current >= self.next_scheduled:\n                extratime = current - self.next_scheduled\n                self.next_scheduled = current + self.interval - extratime\n                return\n            delay_amt = self.next_scheduled - current\n            if self.allow_negative_sleep or delay_amt >= 0: \n                self.sleep_func(self.next_scheduled - current)",
    "docstring": "Delay for between zero and self.interval time units"
  },
  {
    "code": "def OnCellTextRotation(self, event):\n        with undo.group(_(\"Rotation\")):\n            self.grid.actions.toggle_attr(\"angle\")\n        self.grid.ForceRefresh()\n        self.grid.update_attribute_toolbar()\n        if is_gtk():\n            try:\n                wx.Yield()\n            except:\n                pass\n        event.Skip()",
    "docstring": "Cell text rotation event handler"
  },
  {
    "code": "def filter_inactive_ports(query):\n    port_model = models_v2.Port\n    query = (query\n             .filter(port_model.status == n_const.PORT_STATUS_ACTIVE))\n    return query",
    "docstring": "Filter ports that aren't in active status"
  },
  {
    "code": "def _irc_upper(self, in_string):\n        conv_string = self._translate(in_string)\n        if self._upper_trans is not None:\n            conv_string = in_string.translate(self._upper_trans)\n        return str.upper(conv_string)",
    "docstring": "Convert us to our upper-case equivalent, given our std."
  },
  {
    "code": "def drop_all(self):\n        log.info('dropping tables in %s', self.engine.url)\n        self.session.commit()\n        models.Base.metadata.drop_all(self.engine)\n        self.session.commit()",
    "docstring": "Drops all tables in the database"
  },
  {
    "code": "def lookup_announce_alias(name):\n    for alias, urls in announce.items():\n        if alias.lower() == name.lower():\n            return alias, urls\n    raise KeyError(\"Unknown alias %s\" % (name,))",
    "docstring": "Get canonical alias name and announce URL list for the given alias."
  },
  {
    "code": "def parse_client_cert_pair(config_value):\n    if not config_value:\n        return\n    client_cert = config_value.split(':')\n    if len(client_cert) != 2:\n        tips = ('client_cert should be formatted like '\n                '\"/path/to/cert.pem:/path/to/key.pem\"')\n        raise ValueError('{0!r} is invalid.\\n{1}'.format(config_value, tips))\n    return tuple(client_cert)",
    "docstring": "Parses the client cert pair from config item.\n\n    :param config_value: the string value of config item.\n    :returns: tuple or none."
  },
  {
    "code": "def apply(self, node):\n        new_node = self.run(node)\n        return self.update, new_node",
    "docstring": "Apply transformation and return if an update happened."
  },
  {
    "code": "def _check_classes(self):\n        try:\n            self.classes = self.imdbs[0].classes\n            self.num_classes = len(self.classes)\n        except AttributeError:\n            pass\n        if self.num_classes > 0:\n            for db in self.imdbs:\n                assert self.classes == db.classes, \"Multiple imdb must have same classes\"",
    "docstring": "check input imdbs, make sure they have same classes"
  },
  {
    "code": "def _list_paths(self, bucket, prefix):\n        s3 = self.s3\n        kwargs = {\"Bucket\": bucket, \"Prefix\": prefix}\n        if self.list_objects:\n            list_objects_api = \"list_objects\"\n        else:\n            list_objects_api = \"list_objects_v2\"\n        paginator = s3.get_paginator(list_objects_api)\n        for page in paginator.paginate(**kwargs):\n            contents = page.get(\"Contents\", None)\n            if not contents:\n                continue\n            for item in contents:\n                yield item[\"Key\"]",
    "docstring": "Read config for list object api, paginate through list objects."
  },
  {
    "code": "def is_asdf(raw):\n    reverse = raw[::-1]\n    asdf = ''.join(ASDF)\n    return raw in asdf or reverse in asdf",
    "docstring": "If the password is in the order on keyboard."
  },
  {
    "code": "def get_vcl_html(self, service_id, version_number, name):\n\t\tcontent = self._fetch(\"/service/%s/version/%d/vcl/%s/content\" % (service_id, version_number, name))\n\t\treturn content.get(\"content\", None)",
    "docstring": "Get the uploaded VCL for a particular service and version with HTML syntax highlighting."
  },
  {
    "code": "def sideral(date, longitude=0., model='mean', eop_correction=True, terms=106):\n    theta = _sideral(date, longitude, model, eop_correction, terms)\n    return rot3(np.deg2rad(-theta))",
    "docstring": "Sideral time as a rotation matrix"
  },
  {
    "code": "def _setDefaults(self):\n        for configName, configDict in self.configs.items():\n            self._setConfig(configName, configDict['default'])",
    "docstring": "Sets all the expected configuration options on the config object as either the requested default value, or None."
  },
  {
    "code": "def update(uid, post_data):\n        raw_rec = TabTag.get(TabTag.uid == uid)\n        entry = TabTag.update(\n            name=post_data['name'] if 'name' in post_data else raw_rec.name,\n            slug=post_data['slug'] if 'slug' in post_data else raw_rec.slug,\n            order=post_data['order'] if 'order' in post_data else raw_rec.order,\n            kind=post_data['kind'] if 'kind' in post_data else raw_rec.kind,\n            pid=post_data['pid'],\n        ).where(TabTag.uid == uid)\n        entry.execute()",
    "docstring": "Update the category."
  },
  {
    "code": "def save_and_restore(self, _func=None, **config_values):\n    functools = self._modules['functools']\n    if not _func:\n      return functools.partial(self.save_and_restore, **config_values)\n    @functools.wraps(_func)\n    def _saving_wrapper(*args, **kwargs):\n      saved_config = dict(self._loaded_values)\n      try:\n        self.load_from_dict(config_values)\n        return _func(*args, **kwargs)\n      finally:\n        self._loaded_values = saved_config\n    return _saving_wrapper",
    "docstring": "Decorator for saving conf state and restoring it after a function.\n\n    This decorator is primarily for use in tests, where conf keys may be updated\n    for individual test cases, but those values need to be reverted after the\n    test case is done.\n\n    Examples:\n\n      conf.declare('my_conf_key')\n\n      @conf.save_and_restore\n      def MyTestFunc():\n        conf.load(my_conf_key='baz')\n        SomeFuncUnderTestThatUsesMyConfKey()\n\n      conf.load(my_conf_key='foo')\n      MyTestFunc()\n      print conf.my_conf_key  # Prints 'foo', *NOT* 'baz'\n\n      # Without the save_and_restore decorator, MyTestFunc() would have had the\n      # side effect of altering the conf value of 'my_conf_key' to 'baz'.\n\n      # Config keys can also be initialized for the context inline at decoration\n      # time.  This is the same as setting them at the beginning of the\n      # function, but is a little clearer syntax if you know ahead of time what\n      # config keys and values you need to set.\n\n      @conf.save_and_restore(my_conf_key='baz')\n      def MyOtherTestFunc():\n        print conf.my_conf_key  # Prints 'baz'\n\n      MyOtherTestFunc()\n      print conf.my_conf_key  # Prints 'foo' again, for the same reason.\n\n\n    Args:\n      _func: The function to wrap.  The returned wrapper will invoke the\n          function and restore the config to the state it was in at invocation.\n      **config_values: Config keys can be set inline at decoration time, see\n          examples.  Note that config keys can't begin with underscore, so\n          there can be no name collision with _func.\n\n    Returns:\n      Wrapper to replace _func, as per Python decorator semantics."
  },
  {
    "code": "def go_to_next_cell(self):\r\n        cursor = self.textCursor()\r\n        cursor.movePosition(QTextCursor.NextBlock)\r\n        cur_pos = prev_pos = cursor.position()\r\n        while not self.is_cell_separator(cursor):\r\n            cursor.movePosition(QTextCursor.NextBlock)\r\n            prev_pos = cur_pos\r\n            cur_pos = cursor.position()\r\n            if cur_pos == prev_pos:\r\n                return\r\n        self.setTextCursor(cursor)",
    "docstring": "Go to the next cell of lines"
  },
  {
    "code": "def get_tensors(object_):\n    if torch.is_tensor(object_):\n        return [object_]\n    elif isinstance(object_, (str, float, int)):\n        return []\n    tensors = set()\n    if isinstance(object_, collections.abc.Mapping):\n        for value in object_.values():\n            tensors.update(get_tensors(value))\n    elif isinstance(object_, collections.abc.Iterable):\n        for value in object_:\n            tensors.update(get_tensors(value))\n    else:\n        members = [\n            value for key, value in inspect.getmembers(object_)\n            if not isinstance(value, (collections.abc.Callable, type(None)))\n        ]\n        tensors.update(get_tensors(members))\n    return tensors",
    "docstring": "Get all tensors associated with ``object_``\n\n    Args:\n        object_ (any): Any object to look for tensors.\n\n    Returns:\n        (list of torch.tensor): List of tensors that are associated with ``object_``."
  },
  {
    "code": "def validate_description(xml_data):\n    try:\n        root = ET.fromstring('<document>' + xml_data + '</document>')\n    except StdlibParseError as e:\n        raise ParseError(str(e))\n    return _parse_desc(root)",
    "docstring": "Validate the description for validity"
  },
  {
    "code": "def formatfooter(self, previous_month, next_month):\n        footer = '<tfoot><tr>' \\\n                 '<td colspan=\"3\" class=\"prev\">%s</td>' \\\n                 '<td class=\"pad\">&nbsp;</td>' \\\n                 '<td colspan=\"3\" class=\"next\">%s</td>' \\\n                 '</tr></tfoot>'\n        if previous_month:\n            previous_content = '<a href=\"%s\" class=\"previous-month\">%s</a>' % (\n                reverse('zinnia:entry_archive_month', args=[\n                    previous_month.strftime('%Y'),\n                    previous_month.strftime('%m')]),\n                date_format(previous_month, 'YEAR_MONTH_FORMAT'))\n        else:\n            previous_content = '&nbsp;'\n        if next_month:\n            next_content = '<a href=\"%s\" class=\"next-month\">%s</a>' % (\n                reverse('zinnia:entry_archive_month', args=[\n                    next_month.strftime('%Y'),\n                    next_month.strftime('%m')]),\n                date_format(next_month, 'YEAR_MONTH_FORMAT'))\n        else:\n            next_content = '&nbsp;'\n        return footer % (previous_content, next_content)",
    "docstring": "Return a footer for a previous and next month."
  },
  {
    "code": "def second_order_score(y, mean, scale, shape, skewness):\n        return ((y-mean)/float(scale*np.abs(y-mean))) / (-(np.power(y-mean,2) - np.power(np.abs(mean-y),2))/(scale*np.power(np.abs(mean-y),3)))",
    "docstring": "GAS Laplace Update term potentially using second-order information - native Python function\n\n        Parameters\n        ----------\n        y : float\n            datapoint for the time series\n\n        mean : float\n            location parameter for the Laplace distribution\n\n        scale : float\n            scale parameter for the Laplace distribution\n\n        shape : float\n            tail thickness parameter for the Laplace distribution\n\n        skewness : float\n            skewness parameter for the Laplace distribution\n\n        Returns\n        ----------\n        - Adjusted score of the Laplace family"
  },
  {
    "code": "def set_text(self, text):\r\n        text = text.strip()\r\n        new_text = self.text() + text\r\n        self.setText(new_text)",
    "docstring": "Set the filter text."
  },
  {
    "code": "async def start_worker(\n        self,\n        cmd: List[str],\n        input_source: str,\n        output: Optional[str] = None,\n        extra_cmd: Optional[str] = None,\n        pattern: Optional[str] = None,\n        reading: str = FFMPEG_STDERR,\n    ) -> None:\n        if self.is_running:\n            _LOGGER.warning(\"Can't start worker. It is allready running!\")\n            return\n        if reading == FFMPEG_STDERR:\n            stdout = False\n            stderr = True\n        else:\n            stdout = True\n            stderr = False\n        await self.open(\n            cmd=cmd,\n            input_source=input_source,\n            output=output,\n            extra_cmd=extra_cmd,\n            stdout_pipe=stdout,\n            stderr_pipe=stderr,\n        )\n        self._input = await self.get_reader(reading)\n        self._read_task = self._loop.create_task(self._process_lines(pattern))\n        self._loop.create_task(self._worker_process())",
    "docstring": "Start ffmpeg do process data from output."
  },
  {
    "code": "def id_to_root_name(id):\n    name = root_names.get(id)\n    if not name:\n        name = repr(id)\n    return name",
    "docstring": "Convert a PDG ID to a string with root markup."
  },
  {
    "code": "def footer_length(header):\n    footer_length = 0\n    if header.algorithm.signing_algorithm_info is not None:\n        footer_length += 2\n        footer_length += header.algorithm.signature_len\n    return footer_length",
    "docstring": "Calculates the ciphertext message footer length, given a complete header.\n\n    :param header: Complete message header object\n    :type header: aws_encryption_sdk.structures.MessageHeader\n    :rtype: int"
  },
  {
    "code": "def rotate_around(self, axis, theta):\n        x, y, z = self.x, self.y, self.z\n        u, v, w = axis.x, axis.y, axis.z\n        r2 = u**2 + v**2 + w**2\n        r = math.sqrt(r2)\n        ct = math.cos(theta)\n        st = math.sin(theta) / r\n        dt = (u * x + v * y + w * z) * (1 - ct) / r2\n        return Vector3((u * dt + x * ct + (-w * y + v * z) * st),\n                       (v * dt + y * ct + (w * x - u * z) * st),\n                       (w * dt + z * ct + (-v * x + u * y) * st))",
    "docstring": "Return the vector rotated around axis through angle theta.\n\n        Right hand rule applies."
  },
  {
    "code": "def __get_min_reads(current_provisioning, min_provisioned_reads, log_tag):\n    reads = 1\n    if min_provisioned_reads:\n        reads = int(min_provisioned_reads)\n        if reads > int(current_provisioning * 2):\n            reads = int(current_provisioning * 2)\n            logger.debug(\n                '{0} - '\n                'Cannot reach min-provisioned-reads as max scale up '\n                'is 100% of current provisioning'.format(log_tag))\n    logger.debug(\n        '{0} - Setting min provisioned reads to {1}'.format(\n            log_tag, min_provisioned_reads))\n    return reads",
    "docstring": "Get the minimum number of reads to current_provisioning\n\n    :type current_provisioning: int\n    :param current_provisioning: Current provisioned reads\n    :type min_provisioned_reads: int\n    :param min_provisioned_reads: Configured min provisioned reads\n    :type log_tag: str\n    :param log_tag: Prefix for the log\n    :returns: int -- Minimum number of reads"
  },
  {
    "code": "def main(*args):\n    args = args or sys.argv[1:]\n    params = PARSER.parse_args(args)\n    from .log import setup_logging\n    setup_logging(params.level.upper())\n    from .core import Starter\n    starter = Starter(params)\n    if not starter.params.TEMPLATES or starter.params.list:\n        setup_logging('WARN')\n        for t in sorted(starter.iterate_templates()):\n            logging.warn(\"%s -- %s\", t.name, t.params.get(\n                'description', 'no description'))\n        return True\n    try:\n        starter.copy()\n    except Exception as e:\n        logging.error(e)\n        sys.exit(1)",
    "docstring": "Enter point."
  },
  {
    "code": "def create_index(self, indexname=None, index_conf=None):\n        if indexname is None:\n            indexname = self.index_name\n        log.debug(\"Creating new index: '{0}'\".format(indexname))\n        if index_conf is None:\n            index_conf = {'settings': self.settings,\n                          'mappings': {'book': {'properties': self.properties}}}\n        try:\n            self.es.indices.create(index=indexname, body=index_conf)\n        except TransportError as te:\n            if te.error.startswith(\"IndexAlreadyExistsException\"):\n                raise Exception(\"Cannot create index '{}', already exists\".format(indexname))\n            else:\n                raise",
    "docstring": "Create the index\n\n            Create the index with given configuration.\n            If `indexname` is provided it will be used as the new index name\n            instead of the class one (:py:attr:`DB.index_name`)\n\n            :param index_conf: configuration to be used in index creation. If this\n                              is not specified the default index configuration will be used.\n            :raises Exception: if the index already exists."
  },
  {
    "code": "def get_changeset(self, **options):\n        cid = options.get('changeset_id', None)\n        return self.repo.get_changeset(cid)",
    "docstring": "Returns changeset for given ``options``."
  },
  {
    "code": "def setCurrentIndex(self, index):\n        super(XViewPanel, self).setCurrentIndex(index)\n        self.tabBar().setCurrentIndex(index)",
    "docstring": "Sets the current index on self and on the tab bar to keep the two insync.\n\n        :param     index | <int>"
  },
  {
    "code": "def process_checkpoint(self, msg: Checkpoint, sender: str) -> bool:\n        self.logger.info('{} processing checkpoint {} from {}'.format(self, msg, sender))\n        result, reason = self.validator.validate_checkpoint_msg(msg)\n        if result == DISCARD:\n            self.discard(msg, \"{} discard message {} from {} \"\n                              \"with the reason: {}\".format(self, msg, sender, reason),\n                         self.logger.trace)\n        elif result == PROCESS:\n            self._do_process_checkpoint(msg, sender)\n        else:\n            self.logger.debug(\"{} stashing checkpoint message {} with \"\n                              \"the reason: {}\".format(self, msg, reason))\n            self.stasher.stash((msg, sender), result)\n            return False\n        return True",
    "docstring": "Process checkpoint messages\n\n        :return: whether processed (True) or stashed (False)"
  },
  {
    "code": "def get_crimes_no_location(self, force, date=None, category=None):\n        if not isinstance(force, Force):\n            force = Force(self, id=force)\n        if isinstance(category, CrimeCategory):\n            category = category.id\n        kwargs = {\n            'force': force.id,\n            'category': category or 'all-crime',\n        }\n        crimes = []\n        if date is not None:\n            kwargs['date'] = date\n        for c in self.service.request('GET', 'crimes-no-location', **kwargs):\n            crimes.append(NoLocationCrime(self, data=c))\n        return crimes",
    "docstring": "Get crimes with no location for a force. Uses the crimes-no-location_\n        API call.\n\n        .. _crimes-no-location:\n            https://data.police.uk/docs/method/crimes-no-location/\n\n        :rtype: list\n        :param force: The force to get no-location crimes for.\n        :type force: str or Force\n        :param date: The month in which the crimes were reported in the format\n                    ``YYYY-MM`` (the latest date is used if ``None``).\n        :type date: str or None\n        :param category: The category of the crimes to filter by (either by ID\n                         or CrimeCategory object)\n        :type category: str or CrimeCategory\n        :return: A ``list`` of :class:`crime.NoLocationCrime` objects which\n                 were reported in the given month, by the specified force, but\n                 which don't have a location."
  },
  {
    "code": "def _clear_state(self, seed=None):\n        self.start_time = time()\n        self.run_stats = []\n        self.best_index = -1\n        self.best_score = -1\n        self.best_config = None\n        self.search_space = None\n        if seed is not None:\n            self.rng = random.Random(seed)",
    "docstring": "Clears the state, starts clock"
  },
  {
    "code": "def match_events(ref, est, window, distance=None):\n    if distance is not None:\n        hits = np.where(distance(ref, est) <= window)\n    else:\n        hits = _fast_hit_windows(ref, est, window)\n    G = {}\n    for ref_i, est_i in zip(*hits):\n        if est_i not in G:\n            G[est_i] = []\n        G[est_i].append(ref_i)\n    matching = sorted(_bipartite_match(G).items())\n    return matching",
    "docstring": "Compute a maximum matching between reference and estimated event times,\n    subject to a window constraint.\n\n    Given two lists of event times ``ref`` and ``est``, we seek the largest set\n    of correspondences ``(ref[i], est[j])`` such that\n    ``distance(ref[i], est[j]) <= window``, and each\n    ``ref[i]`` and ``est[j]`` is matched at most once.\n\n    This is useful for computing precision/recall metrics in beat tracking,\n    onset detection, and segmentation.\n\n    Parameters\n    ----------\n    ref : np.ndarray, shape=(n,)\n        Array of reference values\n    est : np.ndarray, shape=(m,)\n        Array of estimated values\n    window : float > 0\n        Size of the window.\n    distance : function\n        function that computes the outer distance of ref and est.\n        By default uses ``|ref[i] - est[j]|``\n\n    Returns\n    -------\n    matching : list of tuples\n        A list of matched reference and event numbers.\n        ``matching[i] == (i, j)`` where ``ref[i]`` matches ``est[j]``."
  },
  {
    "code": "def pvector_field(item_type, optional=False, initial=()):\n    return _sequence_field(CheckedPVector, item_type, optional,\n                           initial)",
    "docstring": "Create checked ``PVector`` field.\n\n    :param item_type: The required type for the items in the vector.\n    :param optional: If true, ``None`` can be used as a value for\n        this field.\n    :param initial: Initial value to pass to factory if no value is given\n        for the field.\n\n    :return: A ``field`` containing a ``CheckedPVector`` of the given type."
  },
  {
    "code": "def reprocess_tree_node(self, tree_node, tx_context=None):\n        if not tx_context:\n            tx_context = collections.defaultdict(dict)\n        if tree_node.parent is None:\n            return tx_context\n        if tree_node.timeperiod in tx_context[tree_node.process_name]:\n            return tx_context\n        if tree_node.job_record.is_embryo:\n            pass\n        else:\n            state_machine_name = context.process_context[tree_node.process_name].state_machine_name\n            state_machine = self.state_machines[state_machine_name]\n            state_machine.reprocess_job(tree_node.job_record)\n        tx_context[tree_node.process_name][tree_node.timeperiod] = tree_node\n        self.reprocess_tree_node(tree_node.parent, tx_context)\n        dependant_nodes = self._find_dependant_tree_nodes(tree_node)\n        for node in dependant_nodes:\n            self.reprocess_tree_node(node, tx_context)\n        return tx_context",
    "docstring": "method reprocesses the node and all its dependants and parent nodes"
  },
  {
    "code": "def user_list_membership(self, username, member_type=\"USER\",\n                             recursive=True, max_return_count=999):\n        return self.client.service.getUserListMembership(\n            username,\n            member_type,\n            recursive,\n            max_return_count,\n            self.proxy_id\n        )",
    "docstring": "Get info for lists a user is a member of.\n\n        This is similar to :meth:`user_lists` but with a few differences:\n\n            #. It returns list info objects instead of list names.\n            #. It has an option to fully resolve a user's list hierarchy. That\n               is, if a user is a member of a nested list, this method can\n               retrieve both the nested list and the parent lists that contain\n               the nested list.\n\n        Args:\n            username (str): The MIT username of the user\n            member_type(str): The type of user, \"USER\" or \"STRING\"\n            recursive(bool): Whether to fully resolve the list hierarchy\n            max_return_count(int): limit the number of items returned\n\n        Returns:\n            list of dicts: info dicts, one per list."
  },
  {
    "code": "def remove_rules(self, description):\n        rm = []\n        description = description.lower()\n        for i in range(0, len(self.extract_rules)):\n            if self.extract_rules[i]['regex'].search(description):\n                rm.append(i)\n        for i in rm:\n            self.extract_rules.pop(i)\n        return len(rm)",
    "docstring": "Remove all rules that match a specified description.\n\n        @description - The description to match against.\n\n        Returns the number of rules removed."
  },
  {
    "code": "def get_tags(self):\n        res = self.get_request('/tag')\n        return [Tag(cloud_manager=self, **tag) for tag in res['tags']['tag']]",
    "docstring": "List all tags as Tag objects."
  },
  {
    "code": "def readTempC(self):\n\t\tt = self._device.readU16BE(MCP9808_REG_AMBIENT_TEMP)\n\t\tself._logger.debug('Raw ambient temp register value: 0x{0:04X}'.format(t & 0xFFFF))\n\t\ttemp = (t & 0x0FFF) / 16.0\n\t\tif t & 0x1000:\n\t\t\ttemp -= 256.0\n\t\treturn temp",
    "docstring": "Read sensor and return its value in degrees celsius."
  },
  {
    "code": "def _RecurseKey(self, recur_item, root='', depth=15):\n    if depth < 1:\n      logger.debug('Recursion limit hit for key: {0:s}'.format(root))\n      return\n    if isinstance(recur_item, (list, tuple)):\n      for recur in recur_item:\n        for key in self._RecurseKey(recur, root, depth):\n          yield key\n      return\n    if not hasattr(recur_item, 'iteritems'):\n      return\n    for key, value in iter(recur_item.items()):\n      yield root, key, value\n      if isinstance(value, dict):\n        value = [value]\n      if isinstance(value, list):\n        for item in value:\n          if isinstance(item, dict):\n            for keyval in self._RecurseKey(\n                item, root=root + '/' + key, depth=depth - 1):\n              yield keyval",
    "docstring": "Flattens nested dictionaries and lists by yielding their values.\n\n    The hierarchy of a bencode file is a series of nested dictionaries and\n    lists. This is a helper function helps plugins navigate the structure\n    without having to reimplement their own recursive methods.\n\n    This method implements an overridable depth limit to prevent processing\n    extremely deeply nested dictionaries. If the limit is reached a debug\n    message is logged indicating which key processing stopped on.\n\n    Args:\n      recur_item (object): object to be checked for additional nested items.\n      root (str): the pathname of the current working key.\n      depth (int): a counter to ensure we stop at the maximum recursion depth.\n\n    Yields:\n      tuple: containing:\n          str: root\n          str: key\n          str: value"
  },
  {
    "code": "def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]):\n    try:\n        issue_num = int(text)\n        if issue_num <= 0:\n            raise ValueError\n    except ValueError:\n        msg = inliner.reporter.error(\n            'GitHub issue number must be a number greater than or equal to 1; '\n            '\"%s\" is invalid.' % text, line=lineno)\n        prb = inliner.problematic(rawtext, rawtext, msg)\n        return [prb], [msg]\n    app = inliner.document.settings.env.app\n    if 'pull' in name.lower():\n        category = 'pull'\n    elif 'issue' in name.lower():\n        category = 'issues'\n    else:\n        msg = inliner.reporter.error(\n            'GitHub roles include \"ghpull\" and \"ghissue\", '\n            '\"%s\" is invalid.' % name, line=lineno)\n        prb = inliner.problematic(rawtext, rawtext, msg)\n        return [prb], [msg]\n    node = make_link_node(rawtext, app, category, str(issue_num), options)\n    return [node], []",
    "docstring": "Link to a GitHub issue.\n\n    Returns 2 part tuple containing list of nodes to insert into the\n    document and a list of system messages.  Both are allowed to be\n    empty.\n\n    :param name: The role name used in the document.\n    :param rawtext: The entire markup snippet, with role.\n    :param text: The text marked with the role.\n    :param lineno: The line number where rawtext appears in the input.\n    :param inliner: The inliner instance that called us.\n    :param options: Directive options for customization.\n    :param content: The directive content for customization."
  },
  {
    "code": "def reverse_tree(tree):\n    rtree = defaultdict(list)\n    child_keys = set(c.key for c in flatten(tree.values()))\n    for k, vs in tree.items():\n        for v in vs:\n            node = find_tree_root(rtree, v.key) or v\n            rtree[node].append(k.as_required_by(v))\n        if k.key not in child_keys:\n            rtree[k.as_requirement()] = []\n    return rtree",
    "docstring": "Reverse the dependency tree.\n\n    ie. the keys of the resulting dict are objects of type\n    ReqPackage and the values are lists of DistPackage objects.\n\n    :param dict tree: the pkg dependency tree obtained by calling\n                      `construct_tree` function\n    :returns: reversed tree\n    :rtype: dict"
  },
  {
    "code": "def remove_temp_copy(self):\n        if self.is_temp and self.root_dir is not None:\n            shutil.rmtree(self.root_dir)\n            self.root_dir = None",
    "docstring": "Removes a temporary copy of the MAGICC version shipped with Pymagicc."
  },
  {
    "code": "def parse_cluster(self, global_params, region, cluster):\n        cluster_name = cluster.pop('CacheClusterId')\n        cluster['name'] = cluster_name\n        if 'CacheSubnetGroupName' in cluster:\n            subnet_group = api_clients[region].describe_cache_subnet_groups(CacheSubnetGroupName = cluster['CacheSubnetGroupName'])['CacheSubnetGroups'][0]\n            vpc_id = subnet_group['VpcId']\n        else:\n            vpc_id = ec2_classic\n            subnet_group = None\n        manage_dictionary(self.vpcs, vpc_id, VPCConfig(self.vpc_resource_types))\n        self.vpcs[vpc_id].clusters[cluster_name] = cluster\n        if subnet_group:\n            self.vpcs[vpc_id].subnet_groups[subnet_group['CacheSubnetGroupName']] = subnet_group",
    "docstring": "Parse a single ElastiCache cluster\n\n        :param global_params:           Parameters shared for all regions\n        :param region:                  Name of the AWS region\n        :param cluster:                 ElastiCache cluster"
  },
  {
    "code": "def wrap(self, width):\n        res = []\n        prev_state = set()\n        part = []\n        cwidth = 0\n        for char, _width, state in zip(self._string, self._width, self._state):\n            if cwidth + _width > width:\n                if prev_state:\n                    part.append(self.ANSI_RESET)\n                res.append(\"\".join(part))\n                prev_state = set()\n                part = []\n                cwidth = 0\n            cwidth += _width\n            if prev_state == state:\n                pass\n            elif prev_state <= state:\n                part.extend(state - prev_state)\n            else:\n                part.append(self.ANSI_RESET)\n                part.extend(state)\n            prev_state = state\n            part.append(char)\n        if prev_state:\n            part.append(self.ANSI_RESET)\n        if part:\n            res.append(\"\".join(part))\n        return res",
    "docstring": "Returns a partition of the string based on `width`"
  },
  {
    "code": "def unkown_field(self, value=None):\n        if value is not None:\n            try:\n                value = str(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type str '\n                                 'for field `unkown_field`'.format(value))\n            if ',' in value:\n                raise ValueError('value should not contain a comma '\n                                 'for field `unkown_field`')\n        self._unkown_field = value",
    "docstring": "Corresponds to IDD Field `unkown_field` Empty field in data.\n\n        Args:\n            value (str): value for IDD Field `unkown_field`\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def parse_request_body(self, body):\n        PARSING_FUNCTIONS = {\n            'application/json': json.loads,\n            'text/json': json.loads,\n            'application/x-www-form-urlencoded': self.parse_querystring,\n        }\n        content_type = self.headers.get('content-type', '')\n        do_parse = PARSING_FUNCTIONS.get(content_type, FALLBACK_FUNCTION)\n        try:\n            body = decode_utf8(body)\n            return do_parse(body)\n        except (Exception, BaseException):\n            return body",
    "docstring": "Attempt to parse the post based on the content-type passed.\n        Return the regular body if not\n\n        :param body: string\n        :returns: a python object such as dict or list in case the deserialization suceeded. Else returns the given param ``body``"
  },
  {
    "code": "def handle_current_state(self):\n        if getattr(self, '_current_state_hydrated_changed', False) and self.save_on_change:\n            new_base_state = json.dumps(getattr(self, '_current_state_hydrated', {}))\n            if new_base_state != self.base_state:\n                self.base_state = new_base_state\n                self.save()",
    "docstring": "Check to see if the current hydrated state and the saved state are different.\n\n        If they are, then persist the current state in the database by saving the model instance."
  },
  {
    "code": "def create_superuser(\n            self, username, email, short_name, full_name,\n            institute, password, **extra_fields):\n        return self._create_user(\n            username=username, email=email,\n            institute=institute, password=password,\n            short_name=short_name, full_name=full_name,\n            is_admin=True, **extra_fields)",
    "docstring": "Creates a new person with super powers."
  },
  {
    "code": "def python_value(self, value):\n        value = super(JSONField, self).python_value(value)\n        if value is not None:\n            return flask.json.loads(value, **self._load_kwargs)",
    "docstring": "Return the JSON in the database as a ``dict``.\n\n        Returns:\n            dict: The field run through json.loads"
  },
  {
    "code": "def on_replace_scene(self, event: events.ReplaceScene, signal):\n        self.stop_scene()\n        self.start_scene(event.new_scene, event.kwargs)",
    "docstring": "Replace the running scene with a new one."
  },
  {
    "code": "def set_experiment_winner(experiment):\n    redis = _get_redis_connection()\n    experiment = Experiment.find(redis, experiment)\n    if experiment:\n        alternative_name = request.form.get('alternative')\n        alternative = Alternative(redis, alternative_name, experiment.name)\n        if alternative.name in experiment.alternative_names:\n            experiment.winner = alternative.name\n    return redirect(url_for('.index'))",
    "docstring": "Mark an alternative as the winner of the experiment."
  },
  {
    "code": "def append(self, cls, infer_hidden: bool = False, **kwargs) -> Encoder:\n        params = dict(kwargs)\n        if infer_hidden:\n            params['num_hidden'] = self.get_num_hidden()\n        sig_params = inspect.signature(cls.__init__).parameters\n        if 'dtype' in sig_params and 'dtype' not in kwargs:\n            params['dtype'] = self.dtype\n        encoder = cls(**params)\n        self.encoders.append(encoder)\n        return encoder",
    "docstring": "Extends sequence with new Encoder. 'dtype' gets passed into Encoder instance if not present in parameters\n        and supported by specific Encoder type.\n\n        :param cls: Encoder type.\n        :param infer_hidden: If number of hidden should be inferred from previous encoder.\n        :param kwargs: Named arbitrary parameters for Encoder.\n\n        :return: Instance of Encoder."
  },
  {
    "code": "def _delete_network(self, request, network):\n        try:\n            api.neutron.network_delete(request, network.id)\n            LOG.debug('Delete the created network %s '\n                      'due to subnet creation failure.', network.id)\n            msg = _('Delete the created network \"%s\" '\n                    'due to subnet creation failure.') % network.name\n            redirect = self.get_failure_url()\n            messages.info(request, msg)\n            raise exceptions.Http302(redirect)\n        except Exception as e:\n            LOG.info('Failed to delete network %(id)s: %(exc)s',\n                     {'id': network.id, 'exc': e})\n            msg = _('Failed to delete network \"%s\"') % network.name\n            redirect = self.get_failure_url()\n            exceptions.handle(request, msg, redirect=redirect)",
    "docstring": "Delete the created network when subnet creation failed."
  },
  {
    "code": "def FromMilliseconds(self, millis):\n    self._NormalizeDuration(\n        millis // _MILLIS_PER_SECOND,\n        (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND)",
    "docstring": "Converts milliseconds to Duration."
  },
  {
    "code": "def ready(zone):\n    ret = {'status': True}\n    res = __salt__['cmd.run_all']('zoneadm {zone} ready'.format(\n        zone='-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone),\n    ))\n    ret['status'] = res['retcode'] == 0\n    ret['message'] = res['stdout'] if ret['status'] else res['stderr']\n    ret['message'] = ret['message'].replace('zoneadm: ', '')\n    if ret['message'] == '':\n        del ret['message']\n    return ret",
    "docstring": "Prepares a zone for running applications.\n\n    zone : string\n        name or uuid of the zone\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' zoneadm.ready clementine"
  },
  {
    "code": "def gauss_box_model(x, amplitude=1.0, mean=0.0, stddev=1.0, hpix=0.5):\n    z = (x - mean) / stddev\n    z2 = z + hpix / stddev\n    z1 = z - hpix / stddev\n    return amplitude * (norm.cdf(z2) - norm.cdf(z1))",
    "docstring": "Integrate a Gaussian profile."
  },
  {
    "code": "def _get_rating(self, entry):\n        r_info = ''\n        for string in entry[2].strings:\n            r_info += string\n        rating, share = r_info.split('/')\n        return (rating, share.strip('*'))",
    "docstring": "Get the rating and share for a specific row"
  },
  {
    "code": "def groups(self, user, include=None):\n        return self._query_zendesk(self.endpoint.groups, 'group', id=user, include=include)",
    "docstring": "Retrieve the groups for this user.\n\n        :param include: list of objects to sideload. `Side-loading API Docs \n            <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.\n        :param user: User object or id"
  },
  {
    "code": "def replace_text_dir(self, directory, to_replace, replacement, file_type=None):\n        if not file_type:\n            file_type = \"*.tex\"\n        for file in glob.iglob(os.path.join(directory, file_type)):\n            self.replace_text(file, to_replace, replacement)",
    "docstring": "Replaces a string with its replacement in all the files in the directory\n\n        :param directory: the directory in which the files have to be modified\n        :param to_replace: the string to be replaced in the files\n        :param replacement: the string which replaces 'to_replace' in the files\n        :param file_type: file pattern to match the files in which the string has to be replaced"
  },
  {
    "code": "def raise_error_if_unphysical(f):\n    def wrapper(self, *args, **kwargs):\n        if self.k_vrh < 0 or self.g_vrh < 0:\n            raise ValueError(\"Bulk or shear modulus is negative, property \"\n                             \"cannot be determined\")\n        return f(self, *args, **kwargs)\n    return wrapper",
    "docstring": "Wrapper for functions or properties that should raise an error\n    if tensor is unphysical."
  },
  {
    "code": "def initialize_private_canvas(self, private_canvas):\n        if self.t_.get('show_pan_position', False):\n            self.show_pan_mark(True)\n        if self.t_.get('show_focus_indicator', False):\n            self.show_focus_indicator(True)",
    "docstring": "Initialize the private canvas used by this instance."
  },
  {
    "code": "def stop(self):\n        if not self.running:\n            return\n        self.logger.debug(\"stopping main task of %r\", self, stack_info=True)\n        self._main_task.cancel()",
    "docstring": "Stop the client. This sends a signal to the clients main task which\n        makes it terminate.\n\n        It may take some cycles through the event loop to stop the client\n        task. To check whether the task has actually stopped, query\n        :attr:`running`."
  },
  {
    "code": "def _adjust_nstep(n_step, gamma, obs, actions, rewards, new_obs, dones):\n    assert not any(dones[:-1]), \"Unexpected done in middle of trajectory\"\n    traj_length = len(rewards)\n    for i in range(traj_length):\n        for j in range(1, n_step):\n            if i + j < traj_length:\n                new_obs[i] = new_obs[i + j]\n                dones[i] = dones[i + j]\n                rewards[i] += gamma**j * rewards[i + j]",
    "docstring": "Rewrites the given trajectory fragments to encode n-step rewards.\n\n    reward[i] = (\n        reward[i] * gamma**0 +\n        reward[i+1] * gamma**1 +\n        ... +\n        reward[i+n_step-1] * gamma**(n_step-1))\n\n    The ith new_obs is also adjusted to point to the (i+n_step-1)'th new obs.\n\n    At the end of the trajectory, n is truncated to fit in the traj length."
  },
  {
    "code": "def _cmp_bystrlen_reverse(a, b):\n    if len(a) > len(b):\n        return -1\n    elif len(a) < len(b):\n        return 1\n    else:\n        return 0",
    "docstring": "A private \"cmp\" function to be used by the \"sort\" function of a\n       list when ordering the titles found in a knowledge base by string-\n       length - LONGEST -> SHORTEST.\n       @param a: (string)\n       @param b: (string)\n       @return: (integer) - 0 if len(a) == len(b); 1 if len(a) < len(b);\n        -1 if len(a) > len(b);"
  },
  {
    "code": "def decode(self, data):\n        return Zchunk(lib.zarmour_decode(self._as_parameter_, data), True)",
    "docstring": "Decode an armoured string into a chunk. The decoded output is\nnull-terminated, so it may be treated as a string, if that's what\nit was prior to encoding."
  },
  {
    "code": "def duration(self):\n        if not self.started:\n            return None\n        start = self.started\n        end = self.completed\n        if not end:\n            end = datetime.utcnow()\n        return end - start",
    "docstring": "Return a timedelta for this task.\n\n        Measure the time between this task's start and end time, or \"now\"\n        if the task has not yet finished.\n\n        :returns: timedelta object, or None if the task has not even started."
  },
  {
    "code": "def check_dynamic_route_exists(pattern, routes_to_check, parameters):\n        for ndx, route in enumerate(routes_to_check):\n            if route.pattern == pattern and route.parameters == parameters:\n                return ndx, route\n        else:\n            return -1, None",
    "docstring": "Check if a URL pattern exists in a list of routes provided based on\n        the comparison of URL pattern and the parameters.\n\n        :param pattern: URL parameter pattern\n        :param routes_to_check: list of dynamic routes either hashable or\n            unhashable routes.\n        :param parameters: List of :class:`Parameter` items\n        :return: Tuple of index and route if matching route exists else\n            -1 for index and None for route"
  },
  {
    "code": "def add_hostname_cn(self):\n        ip = unit_get('private-address')\n        addresses = [ip]\n        vip = get_vip_in_network(resolve_network_cidr(ip))\n        if vip:\n            addresses.append(vip)\n        self.hostname_entry = {\n            'cn': get_hostname(ip),\n            'addresses': addresses}",
    "docstring": "Add a request for the hostname of the machine"
  },
  {
    "code": "def generator_to_list(fn):\n    def wrapper(*args, **kw):\n        return list(fn(*args, **kw))\n    return wrapper",
    "docstring": "This decorator is for flat_list function.\n    It converts returned generator to list."
  },
  {
    "code": "def update_voice_model(self,\n                           customization_id,\n                           name=None,\n                           description=None,\n                           words=None,\n                           **kwargs):\n        if customization_id is None:\n            raise ValueError('customization_id must be provided')\n        if words is not None:\n            words = [self._convert_model(x, Word) for x in words]\n        headers = {}\n        if 'headers' in kwargs:\n            headers.update(kwargs.get('headers'))\n        sdk_headers = get_sdk_headers('text_to_speech', 'V1',\n                                      'update_voice_model')\n        headers.update(sdk_headers)\n        data = {'name': name, 'description': description, 'words': words}\n        url = '/v1/customizations/{0}'.format(\n            *self._encode_path_vars(customization_id))\n        response = self.request(\n            method='POST',\n            url=url,\n            headers=headers,\n            json=data,\n            accept_json=True)\n        return response",
    "docstring": "Update a custom model.\n\n        Updates information for the specified custom voice model. You can update metadata\n        such as the name and description of the voice model. You can also update the words\n        in the model and their translations. Adding a new translation for a word that\n        already exists in a custom model overwrites the word's existing translation. A\n        custom model can contain no more than 20,000 entries. You must use credentials for\n        the instance of the service that owns a model to update it.\n        You can define sounds-like or phonetic translations for words. A sounds-like\n        translation consists of one or more words that, when combined, sound like the\n        word. Phonetic translations are based on the SSML phoneme format for representing\n        a word. You can specify them in standard International Phonetic Alphabet (IPA)\n        representation\n          <code>&lt;phoneme alphabet=\\\"ipa\\\"\n        ph=\\\"t&#601;m&#712;&#593;to\\\"&gt;&lt;/phoneme&gt;</code>\n          or in the proprietary IBM Symbolic Phonetic Representation (SPR)\n          <code>&lt;phoneme alphabet=\\\"ibm\\\"\n        ph=\\\"1gAstroEntxrYFXs\\\"&gt;&lt;/phoneme&gt;</code>\n        **Note:** This method is currently a beta release.\n        **See also:**\n        * [Updating a custom\n        model](https://cloud.ibm.com/docs/services/text-to-speech/custom-models.html#cuModelsUpdate)\n        * [Adding words to a Japanese custom\n        model](https://cloud.ibm.com/docs/services/text-to-speech/custom-entries.html#cuJapaneseAdd)\n        * [Understanding\n        customization](https://cloud.ibm.com/docs/services/text-to-speech/custom-intro.html).\n\n        :param str customization_id: The customization ID (GUID) of the custom voice\n        model. You must make the request with service credentials created for the instance\n        of the service that owns the custom model.\n        :param str name: A new name for the custom voice model.\n        :param str description: A new description for the custom voice model.\n        :param list[Word] words: An array of `Word` objects that provides the words and\n        their translations that are to be added or updated for the custom voice model.\n        Pass an empty array to make no additions or updates.\n        :param dict headers: A `dict` containing the request headers\n        :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n        :rtype: DetailedResponse"
  },
  {
    "code": "def _sideral(date, longitude=0., model='mean', eop_correction=True, terms=106):\n    t = date.change_scale('UT1').julian_century\n    theta = 67310.54841 + (876600 * 3600 + 8640184.812866) * t + 0.093104 * t ** 2\\\n        - 6.2e-6 * t ** 3\n    theta /= 240.\n    if model == 'apparent':\n        theta += equinox(date, eop_correction, terms)\n    theta += longitude\n    theta %= 360.\n    return theta",
    "docstring": "Get the sideral time at a defined date\n\n    Args:\n        date (Date):\n        longitude (float): Longitude of the observer (in degrees)\n            East positive/West negative.\n        model (str): 'mean' or 'apparent' for GMST and GAST respectively\n    Return:\n        float: Sideral time in degrees\n\n    GMST: Greenwich Mean Sideral Time\n    LST: Local Sideral Time (Mean)\n    GAST: Greenwich Apparent Sideral Time"
  },
  {
    "code": "def _parse_image_multilogs_string(config, ret, repo):\n    image_logs, infos = [], None\n    if ret and ret.strip().startswith('{') and ret.strip().endswith('}'):\n        pushd = 0\n        buf = ''\n        for char in ret:\n            buf += char\n            if char == '{':\n                pushd += 1\n            if char == '}':\n                pushd -= 1\n            if pushd == 0:\n                try:\n                    buf = json.loads(buf)\n                except Exception:\n                    pass\n                image_logs.append(buf)\n                buf = ''\n        image_logs.reverse()\n        for l in image_logs:\n            if isinstance(l, dict):\n                if l.get('status') == 'Download complete' and l.get('id'):\n                    infos = _get_image_infos(config, repo)\n                    break\n    return image_logs, infos",
    "docstring": "Parse image log strings into grokable data"
  },
  {
    "code": "def shift_up(self, times=1):\n        try:\n            return Location(self._rank + times, self._file)\n        except IndexError as e:\n            raise IndexError(e)",
    "docstring": "Finds Location shifted up by 1\n\n        :rtype: Location"
  },
  {
    "code": "def create_stemmer(self, isDev=False):\n        words = self.get_words(isDev)\n        dictionary = ArrayDictionary(words)\n        stemmer = Stemmer(dictionary)\n        resultCache = ArrayCache()\n        cachedStemmer = CachedStemmer(resultCache, stemmer)\n        return cachedStemmer",
    "docstring": "Returns Stemmer instance"
  },
  {
    "code": "def setup_tree(ctx, verbose=None, root=None, tree_dir=None, modules_dir=None):\n    print('Setting up the tree')\n    ctx.run('python bin/setup_tree.py -t {0} -r {1} -m {2}'.format(tree_dir, root, modules_dir))",
    "docstring": "Sets up the SDSS tree enviroment"
  },
  {
    "code": "def pipeline_id_from_name(name, region=None, key=None, keyid=None, profile=None):\n    r = {}\n    result_pipelines = list_pipelines()\n    if 'error' in result_pipelines:\n        return result_pipelines\n    for pipeline in result_pipelines['result']:\n        if pipeline['name'] == name:\n            r['result'] = pipeline['id']\n            return r\n    r['error'] = 'No pipeline found with name={0}'.format(name)\n    return r",
    "docstring": "Get the pipeline id, if it exists, for the given name.\n\n    CLI example:\n\n    .. code-block:: bash\n\n        salt myminion boto_datapipeline.pipeline_id_from_name my_pipeline_name"
  },
  {
    "code": "def stitchModules(module, fallbackModule):\n    for name, attr in fallbackModule.__dict__.items():\n        if name not in module.__dict__:\n            module.__dict__[name] = attr",
    "docstring": "complete missing attributes with those in fallbackModule\n\n    imagine you have 2 modules: a and b\n    a is some kind of an individualised module of b - but will maybe\n    not contain all attributes of b.\n    in this case a should use the attributes from b\n\n    >>> a.var1 = 'individual 1'\n\n    # what we now want is to all all missing attributes from b to a:\n\n    >>> stitchModules(a,b)\n\n    >>> print a.var1\n    individual 1\n    >>> print a.var2\n    standard 2"
  },
  {
    "code": "def _print_download_progress_msg(self, msg, flush=False):\n    if self._interactive_mode():\n      self._max_prog_str = max(self._max_prog_str, len(msg))\n      sys.stdout.write(\"\\r%-{}s\".format(self._max_prog_str) % msg)\n      sys.stdout.flush()\n      if flush:\n        print(\"\\n\")\n    else:\n      logging.info(msg)",
    "docstring": "Prints a message about download progress either to the console or TF log.\n\n    Args:\n      msg: Message to print.\n      flush: Indicates whether to flush the output (only used in interactive\n             mode)."
  },
  {
    "code": "def template_filter(self, param=None):\n        def deco(func):\n            name = param or func.__name__\n            self.filters[name] = func\n            return func\n        return deco",
    "docstring": "Returns a decorator that adds the wrapped function to dictionary of template filters.\n\n        The wrapped function is keyed by either the supplied param (if supplied)\n        or by the wrapped functions name.\n\n        :param param: Optional name to use instead of the name of the function to be wrapped\n        :return: A decorator to wrap a template filter function\n        :rtype: callable"
  },
  {
    "code": "def update(self):\n        if not self.calendar_id:\n            return False\n        url = self.build_url(self._endpoints.get('calendar'))\n        data = {\n            self._cc('name'): self.name,\n            self._cc('color'): self._cc(self.color.value\n                                        if isinstance(self.color, CalendarColor)\n                                        else self.color)\n        }\n        response = self.con.patch(url, data=data)\n        return bool(response)",
    "docstring": "Updates this calendar. Only name and color can be changed.\n\n        :return: Success / Failure\n        :rtype: bool"
  },
  {
    "code": "def as_child(cls, global_config, parent=None):\n        try:\n            setproctitle('rejester worker')\n            random.seed()\n            yakonfig.set_default_config([yakonfig, dblogger, rejester],\n                                        config=global_config)\n            worker = cls(yakonfig.get_global_config(rejester.config_name))\n            worker.register(parent=parent)\n            did_work = worker.run(set_title=True)\n            worker.unregister()\n            if did_work:\n                sys.exit(cls.EXIT_SUCCESS)\n            else:\n                sys.exit(cls.EXIT_BORED)\n        except Exception, e:\n            if len(logging.root.handlers) > 0:\n                logger.critical('failed to do any work', exc_info=e)\n            sys.exit(cls.EXIT_EXCEPTION)",
    "docstring": "Run a single job in a child process.\n\n        This method never returns; it always calls :func:`sys.exit`\n        with an error code that says what it did."
  },
  {
    "code": "def getDisplayName(self):\n        if self.alias == \"\":\n            return self.name\n        return self.name + \" as \" + self.alias",
    "docstring": "Provides a name for display purpose respecting the alias"
  },
  {
    "code": "def boost_error_level(version, error, segments, eci, is_sa=False):\n    if error not in (consts.ERROR_LEVEL_H, None) and len(segments) == 1:\n        levels = [consts.ERROR_LEVEL_L, consts.ERROR_LEVEL_M,\n                  consts.ERROR_LEVEL_Q, consts.ERROR_LEVEL_H]\n        if version < 1:\n            levels.pop()\n            if version < consts.VERSION_M4:\n                levels.pop()\n        data_length = segments.bit_length_with_overhead(version, eci, is_sa=is_sa)\n        for level in levels[levels.index(error)+1:]:\n            try:\n                found = consts.SYMBOL_CAPACITY[version][level] >= data_length\n            except KeyError:\n                break\n            if found:\n                error = level\n    return error",
    "docstring": "\\\n    Increases the error level if possible.\n\n    :param int version: Version constant.\n    :param int|None error: Error level constant or ``None``\n    :param Segments segments: Instance of :py:class:`Segments`\n    :param bool eci: Indicates if ECI designator should be written.\n    :param bool is_sa: Indicates if Structured Append mode ist used."
  },
  {
    "code": "def get_url(self, datatype, verb, urltype, params={}, api_host=None, api_version=None):\n        api_version = api_version or 'v1'\n        api_host = api_host or self.host\n        subst = params.copy()\n        subst['api_host'] = api_host\n        subst['api_version'] = api_version\n        url = \"https://{api_host}/services/api/{api_version}\"\n        url += self.get_url_path(datatype, verb, urltype, params, api_version)\n        return url.format(**subst)",
    "docstring": "Returns a fully formed url\n\n        :param datatype: a string identifying the data the url will access.\n        :param verb: the HTTP verb needed for use with the url.\n        :param urltype: an adjective used to the nature of the request.\n        :param \\*\\*params: substitution variables for the URL.\n        :return: string\n        :rtype: A fully formed url."
  },
  {
    "code": "def set(self, key: bytes, value: bytes) -> Tuple[Hash32]:\n        validate_is_bytes(key)\n        validate_length(key, self._key_size)\n        validate_is_bytes(value)\n        path = to_int(key)\n        node = value\n        _, branch = self._get(key)\n        proof_update = []\n        target_bit = 1\n        for sibling_node in reversed(branch):\n            node_hash = keccak(node)\n            proof_update.append(node_hash)\n            self.db[node_hash] = node\n            if (path & target_bit):\n                node = sibling_node + node_hash\n            else:\n                node = node_hash + sibling_node\n            target_bit <<= 1\n        self.root_hash = keccak(node)\n        self.db[self.root_hash] = node\n        return tuple(reversed(proof_update))",
    "docstring": "Returns all updated hashes in root->leaf order"
  },
  {
    "code": "def jira(test_key):\n    def decorator(test_item):\n        def modified_test(*args, **kwargs):\n            save_jira_conf()\n            try:\n                test_item(*args, **kwargs)\n            except Exception as e:\n                error_message = get_error_message_from_exception(e)\n                test_comment = \"The test '{}' has failed: {}\".format(args[0].get_method_name(), error_message)\n                add_jira_status(test_key, 'Fail', test_comment)\n                raise\n            add_jira_status(test_key, 'Pass', None)\n        modified_test.__name__ = test_item.__name__\n        return modified_test\n    return decorator",
    "docstring": "Decorator to update test status in Jira\n\n    :param test_key: test case key in Jira\n    :returns: jira test"
  },
  {
    "code": "def destroy(self):\n        if not hasattr(self, 'server') or not self.server:\n            raise Exception(\n)\n        return self.server.cloud_manager.delete_firewall_rule(\n            self.server.uuid,\n            self.position\n        )",
    "docstring": "Remove this FirewallRule from the API.\n\n        This instance must be associated with a server for this method to work,\n        which is done by instantiating via server.get_firewall_rules()."
  },
  {
    "code": "def _attempt_to_raise_license_error(data_dir):\n    if isinstance(data_dir, bytes):\n        data_dir = _decode(data_dir)\n    data_dir = os.path.join(data_dir, 'Data')\n    current_date = dt.date.today().strftime('%Y%m%d')\n    timestamp = dt.datetime.today().strftime('[%Y-%m-%d %H:%M:%S]')\n    data_files = os.listdir(data_dir)\n    for f in data_files:\n        if f == (current_date + '.err'):\n            file_name = os.path.join(data_dir, f)\n            with fopen(file_name) as error_file:\n                for line in error_file:\n                    if not line.startswith(timestamp):\n                        continue\n                    if 'Not valid license' in line:\n                        raise LicenseError('Your license appears to have '\n                                           'expired. Try running \"pynlpir '\n                                           'update\".')\n                    elif 'Can not open License file' in line:\n                        raise LicenseError('Your license appears to be '\n                                           'missing. Try running \"pynlpir '\n                                           'update\".')",
    "docstring": "Raise an error if NLPIR has detected a missing or expired license.\n\n    :param str data_dir: The directory containing NLPIR's `Data` directory.\n    :raises LicenseError: The NLPIR license appears to be missing or expired."
  },
  {
    "code": "def get_smart_invite(self, smart_invite_id, recipient_email):\n        params = {\n            'smart_invite_id': smart_invite_id,\n            'recipient_email': recipient_email\n        }\n        return self.request_handler.get('smart_invites', params=params, use_api_key=True).json()",
    "docstring": "Gets the details for a smart invite.\n\n        :param string smart_invite_id: - A String uniquely identifying the event for your\n                                        application (note: this is NOT an ID generated by Cronofy).\n        :param string recipient_email: - The email address for the recipient to get details for."
  },
  {
    "code": "def circles_pycairo(width, height, color):\n    cairo_color = color / rgb(255, 255, 255)\n    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)\n    ctx = cairo.Context(surface)\n    ctx.new_path()\n    ctx.set_source_rgb(cairo_color.red, cairo_color.green, cairo_color.blue)\n    ctx.arc(width / 2, height / 2, width / 2, 0, 2 * pi)\n    ctx.fill()\n    surface.write_to_png('circles.png')",
    "docstring": "Implementation of circle border with PyCairo."
  },
  {
    "code": "def _append_object_entry(obj, list_name, entry):\n    obj_list = getattr(obj, list_name, None)\n    if obj_list is None:\n        obj_list = []\n        setattr(obj, list_name, obj_list)\n    assert isinstance(obj_list, list)\n    if entry not in obj_list:\n        obj_list.append(entry)",
    "docstring": "Appends the given entry in the given object list.\n    Creates the list field if needed.\n\n    :param obj: The object that contains the list\n    :param list_name: The name of the list member in *obj*\n    :param entry: The entry to be added to the list\n    :raise ValueError: Invalid attribute content"
  },
  {
    "code": "def search(\n            self,\n            q=\"yellow flower\",\n            lang=\"en\",\n            video_type=\"all\",\n            category=\"\",\n            min_width=0,\n            min_height=0,\n            editors_choice=\"false\",\n            safesearch=\"false\",\n            order=\"popular\",\n            page=1,\n            per_page=20,\n            callback=\"\",\n            pretty=\"false\",\n    ):\n        payload = {\n            \"key\": self.api_key,\n            \"q\": q,\n            \"lang\": lang,\n            \"video_type\": video_type,\n            \"category\": category,\n            \"min_width\": min_width,\n            \"min_height\": min_height,\n            \"editors_choice\": editors_choice,\n            \"safesearch\": safesearch,\n            \"order\": order,\n            \"page\": page,\n            \"per_page\": per_page,\n            \"callback\": callback,\n            \"pretty\": pretty,\n        }\n        resp = get(self.root_url + \"videos/\", params=payload)\n        if resp.status_code == 200:\n            return resp.json()\n        else:\n            raise ValueError(resp.text)",
    "docstring": "returns videos API data in dict\n\n        Videos search\n\n        :param q :type str :desc A URL encoded search term. If omitted,\n        all images are returned. This value may not exceed 100 characters.\n        Example: \"yellow+flower\"\n        Default: \"yellow+flower\"\n\n        :param lang :type str :desc Language code of the language to be searched in.\n        Accepted values: cs, da, de, en, es, fr, id, it, hu, nl, no, pl, pt, ro, sk, fi,\n        sv, tr, vi, th, bg, ru, el, ja, ko, zh\n        Default: \"en\"\n        For more info, see https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes\n\n        :param video_type :type str :desc Filter results by video type.\n        Accepted values: \"all\", \"film\", \"animation\"\n        Default: \"all\"\n\n        :param category :type str :desc Filter results by category.\n        Accepted values: fashion, nature, backgrounds, science, education, people,\n        feelings, religion, health, places, animals, industry, food, computer, sports,\n        transportation, travel, buildings, business, music\n\n        :param min_width :type int :desc Minimum image width\n        Default: 0\n\n        :param min_height :type int :desc Minimum image height\n        Default: 0\n\n        :param editors_choice :type bool (python-pixabay use \"true\" and \"false\" string instead)\n        :desc Select images that have received\n        an Editor's Choice award.\n        Accepted values: \"true\", \"false\"\n        Default: \"false\"\n\n        :param safesearch :type bool (python-pixabay use \"true\" and \"false\" string instead)\n        :desc A flag indicating that only images suitable\n        for all ages should be returned.\n        Accepted values: \"true\", \"false\"\n        Default: \"false\"\n\n        :param order :type str :desc How the results should be ordered.\n        Accepted values: \"popular\", \"latest\"\n        Default: \"popular\"\n\n        :param page :type int :desc Returned search results are paginated.\n        Use this parameter to select the page number.\n        Default: 1\n\n        :param per_page :type int :desc Determine the number of results per page.\n        Accepted values: 3 - 200\n        Default: 20\n\n        :param callback :type str :desc JSONP callback function name\n\n        :param pretty :type bool (python-pixabay use \"true\" and \"false\" string instead)\n        :desc Indent JSON output. This option should not\n        be used in production.\n        Accepted values: \"true\", \"false\"\n        Default: \"false\"\n\n        Code Example\n        >>> from pixabay import Video\n        >>>\n        >>> video = Video(\"api_key\")\n        >>> video.search(q=\"apple\", page=1)"
  },
  {
    "code": "def download_spt_forecast(self, extract_directory):\n        needed_vars = (self.spt_watershed_name,\n                       self.spt_subbasin_name,\n                       self.spt_forecast_date_string,\n                       self.ckan_engine_url,\n                       self.ckan_api_key,\n                       self.ckan_owner_organization)\n        if None not in needed_vars:\n            er_manager = ECMWFRAPIDDatasetManager(self.ckan_engine_url,\n                                                  self.ckan_api_key,\n                                                  self.ckan_owner_organization)\n            er_manager.download_prediction_dataset(watershed=self.spt_watershed_name,\n                                                   subbasin=self.spt_subbasin_name,\n                                                   date_string=self.spt_forecast_date_string,\n                                                   extract_directory=extract_directory)\n            return glob(os.path.join(extract_directory, self.spt_forecast_date_string, \"Qout*52.nc\"))[0]\n        elif needed_vars.count(None) == len(needed_vars):\n            log.info(\"Skipping streamflow forecast download ...\")\n            return None\n        else:\n            raise ValueError(\"To download the forecasts, you need to set: \\n\"\n                             \"spt_watershed_name, spt_subbasin_name, spt_forecast_date_string \\n\"\n                             \"ckan_engine_url, ckan_api_key, and ckan_owner_organization.\")",
    "docstring": "Downloads Streamflow Prediction Tool forecast data"
  },
  {
    "code": "def setCenter(self, loc):\n        offset = self.getCenter().getOffset(loc)\n        return self.setLocation(self.getTopLeft().offset(offset))",
    "docstring": "Move this region so it is centered on ``loc``"
  },
  {
    "code": "def get_branding(self, branding_id):\n        connection = Connection(self.token)\n        connection.set_url(self.production, self.BRANDINGS_ID_URL % branding_id)\n        return connection.get_request()",
    "docstring": "Get a concrete branding\n        @branding_id: Id of the branding to fetch\n        @return Branding"
  },
  {
    "code": "def _event_funcs(self, event: str) -> Iterable[Callable]:\n        for func in self._events[event]:\n            yield func",
    "docstring": "Returns an Iterable of the functions subscribed to a event.\n\n        :param event: Name of the event.\n        :type event: str\n\n        :return: A iterable to do things with.\n        :rtype: Iterable"
  },
  {
    "code": "def _api_itemvalue(self, plugin, item, value=None, history=False, nb=0):\n        response.content_type = 'application/json; charset=utf-8'\n        if plugin not in self.plugins_list:\n            abort(400, \"Unknown plugin %s (available plugins: %s)\" % (plugin, self.plugins_list))\n        self.__update__()\n        if value is None:\n            if history:\n                ret = self.stats.get_plugin(plugin).get_stats_history(item, nb=int(nb))\n            else:\n                ret = self.stats.get_plugin(plugin).get_stats_item(item)\n            if ret is None:\n                abort(404, \"Cannot get item %s%s in plugin %s\" % (item, 'history ' if history else '', plugin))\n        else:\n            if history:\n                ret = None\n            else:\n                ret = self.stats.get_plugin(plugin).get_stats_value(item, value)\n            if ret is None:\n                abort(404, \"Cannot get item %s(%s=%s) in plugin %s\" % ('history ' if history else '', item, value, plugin))\n        return ret",
    "docstring": "Father method for _api_item and _api_value."
  },
  {
    "code": "def nonoverlap(item_a, time_a, item_b, time_b, max_value):\n    return np.minimum(1 - item_a.count_overlap(time_a, item_b, time_b), max_value) / float(max_value)",
    "docstring": "Percentage of pixels in each object that do not overlap with the other object\n\n    Args:\n        item_a: STObject from the first set in ObjectMatcher\n        time_a: Time integer being evaluated\n        item_b: STObject from the second set in ObjectMatcher\n        time_b: Time integer being evaluated\n        max_value: Maximum distance value used as scaling value and upper constraint.\n\n    Returns:\n        Distance value between 0 and 1."
  },
  {
    "code": "def focus_first_child(self):\n        w, focuspos = self.get_focus()\n        child = self._tree.first_child_position(focuspos)\n        if child is not None:\n            self.set_focus(child)",
    "docstring": "move focus to first child of currently focussed one"
  },
  {
    "code": "def languages(self, key, value):\n    languages = self.get('languages', [])\n    values = force_list(value.get('a'))\n    for value in values:\n        for language in RE_LANGUAGE.split(value):\n            try:\n                name = language.strip().capitalize()\n                languages.append(pycountry.languages.get(name=name).alpha_2)\n            except KeyError:\n                pass\n    return languages",
    "docstring": "Populate the ``languages`` key."
  },
  {
    "code": "def rightStatus(self, sheet):\n        'Compose right side of status bar.'\n        if sheet.currentThreads:\n            gerund = (' '+sheet.progresses[0].gerund) if sheet.progresses else ''\n            status = '%9d  %2d%%%s' % (len(sheet), sheet.progressPct, gerund)\n        else:\n            status = '%9d %s' % (len(sheet), sheet.rowtype)\n        return status, 'color_status'",
    "docstring": "Compose right side of status bar."
  },
  {
    "code": "def get_consensus_at(self, block_id):\n        query = 'SELECT consensus_hash FROM snapshots WHERE block_id = ?;'\n        args = (block_id,)\n        con = self.db_open(self.impl, self.working_dir)\n        rows = self.db_query_execute(con, query, args, verbose=False)\n        res = None\n        for r in rows:\n            res = r['consensus_hash']\n        con.close()\n        return res",
    "docstring": "Get the consensus hash at a given block.\n        Return the consensus hash if we have one for this block.\n        Return None if we don't"
  },
  {
    "code": "def search(self, params, standardize=False):\n        resp = self._request(ENDPOINTS['SEARCH'], params)\n        if not standardize:\n            return resp\n        for res in resp['result_data']:\n            res = self.standardize(res)\n        return resp",
    "docstring": "Get a list of person objects for the given search params.\n\n        :param params: Dictionary specifying the query parameters\n        :param standardize: Whether to standardize names and other features,\n            currently disabled for backwards compatibility. Currently\n            standardizes names, lowercases emails, and removes faculty label\n            from affiliation.\n\n        >>> people = d.search({'first_name': 'tobias', 'last_name': 'funke'})"
  },
  {
    "code": "def bs_values_df(run_list, estimator_list, estimator_names, n_simulate,\n                 **kwargs):\n    tqdm_kwargs = kwargs.pop('tqdm_kwargs', {'desc': 'bs values'})\n    assert len(estimator_list) == len(estimator_names), (\n        'len(estimator_list) = {0} != len(estimator_names = {1}'\n        .format(len(estimator_list), len(estimator_names)))\n    bs_values_list = pu.parallel_apply(\n        nestcheck.error_analysis.run_bootstrap_values, run_list,\n        func_args=(estimator_list,), func_kwargs={'n_simulate': n_simulate},\n        tqdm_kwargs=tqdm_kwargs, **kwargs)\n    df = pd.DataFrame()\n    for i, name in enumerate(estimator_names):\n        df[name] = [arr[i, :] for arr in bs_values_list]\n    for vals_shape in df.loc[0].apply(lambda x: x.shape).values:\n        assert vals_shape == (n_simulate,), (\n            'Should be n_simulate=' + str(n_simulate) + ' values in ' +\n            'each cell. The cell contains array with shape ' +\n            str(vals_shape))\n    return df",
    "docstring": "Computes a data frame of bootstrap resampled values.\n\n    Parameters\n    ----------\n    run_list: list of dicts\n        List of nested sampling run dicts.\n    estimator_list: list of functions\n        Estimators to apply to runs.\n    estimator_names: list of strs\n        Name of each func in estimator_list.\n    n_simulate: int\n        Number of bootstrap replications to use on each run.\n    kwargs:\n        Kwargs to pass to parallel_apply.\n\n    Returns\n    -------\n    bs_values_df: pandas data frame\n        Columns represent estimators and rows represent runs.\n        Each cell contains a 1d array of bootstrap resampled values for the run\n        and estimator."
  },
  {
    "code": "def createThreeObjects():\n  objectA = zip(range(10), range(10))\n  objectB = [(0, 0), (2, 2), (1, 1), (1, 4), (4, 2), (4, 1)]\n  objectC = [(0, 0), (1, 1), (3, 1), (0, 1)]\n  return [objectA, objectB, objectC]",
    "docstring": "Helper function that creates a set of three objects used for basic\n  experiments.\n\n  :return:   (list(list(tuple))  List of lists of feature / location pairs."
  },
  {
    "code": "def _update_quoting_state(self, ch):\n        is_escaped = self.escaped\n        self.escaped = (not self.escaped and\n                        ch == '\\\\' and\n                        self.quotes != self.SQUOTE)\n        if self.escaped:\n            return ''\n        if is_escaped:\n            if self.quotes == self.DQUOTE:\n                if ch == '\"':\n                    return ch\n                return \"{0}{1}\".format('\\\\', ch)\n            return ch\n        if self.quotes is None:\n            if ch in (self.SQUOTE, self.DQUOTE):\n                self.quotes = ch\n                return ''\n        elif self.quotes == ch:\n            self.quotes = None\n            return ''\n        return ch",
    "docstring": "Update self.quotes and self.escaped\n\n        :param ch: str, current character\n        :return: ch if it was not used to update quoting state, else ''"
  },
  {
    "code": "def handle(self, data, **kwargs):\n        try:\n            if self.many:\n                return self.mapper.many(raw=self.raw, **self.mapper_kwargs).marshal(\n                    data, role=self.role\n                )\n            else:\n                return self.mapper(\n                    data=data,\n                    obj=self.obj,\n                    partial=self.partial,\n                    **self.mapper_kwargs\n                ).marshal(role=self.role)\n        except MappingInvalid as e:\n            self.handle_error(e)",
    "docstring": "Run marshalling for the specified mapper_class.\n\n        Supports both .marshal and .many().marshal Kim interfaces.  Handles errors raised\n        during marshalling and automatically returns a HTTP error response.\n\n        :param data: Data to be marshaled.\n        :returns: Marshaled object according to mapper configuration\n        :raises: :class:`werkzeug.exceptions.UnprocessableEntity`"
  },
  {
    "code": "def path_from_row_pks(row, pks, use_rowid, quote=True):\n    if use_rowid:\n        bits = [row['rowid']]\n    else:\n        bits = [\n            row[pk][\"value\"] if isinstance(row[pk], dict) else row[pk]\n            for pk in pks\n        ]\n    if quote:\n        bits = [urllib.parse.quote_plus(str(bit)) for bit in bits]\n    else:\n        bits = [str(bit) for bit in bits]\n    return ','.join(bits)",
    "docstring": "Generate an optionally URL-quoted unique identifier\n        for a row from its primary keys."
  },
  {
    "code": "def get_int(self):\n        token = self.get().unescape()\n        if not token.is_identifier():\n            raise dns.exception.SyntaxError('expecting an identifier')\n        if not token.value.isdigit():\n            raise dns.exception.SyntaxError('expecting an integer')\n        return int(token.value)",
    "docstring": "Read the next token and interpret it as an integer.\n\n        @raises dns.exception.SyntaxError:\n        @rtype: int"
  },
  {
    "code": "def watch(self, keys, on_watch, filters=None, start_revision=None, return_previous=None):\n        d = self._start_watching(keys, on_watch, filters, start_revision, return_previous)\n        def on_err(*args):\n            if args[0].type not in [CancelledError, ResponseFailed]:\n                self.log.warn('etcd watch terminated with \"{error}\"', error=args[0].type)\n                return args[0]\n        d.addErrback(on_err)\n        return d",
    "docstring": "Watch one or more keys or key sets and invoke a callback.\n\n        Watch watches for events happening or that have happened. The entire event history\n        can be watched starting from the last compaction revision.\n\n        :param keys: Watch these keys / key sets.\n        :type keys: list of bytes or list of instance of :class:`txaioetcd.KeySet`\n\n        :param on_watch: The callback to invoke upon receiving\n            a watch event.\n        :type on_watch: callable\n\n        :param filters: Any filters to apply.\n\n        :param start_revision: start_revision is an optional\n            revision to watch from (inclusive). No start_revision is \"now\".\n        :type start_revision: int\n\n        :param return_previous: Flag to request returning previous values.\n\n        :returns: A deferred that just fires when watching has started successfully,\n            or which fires with an error in case the watching could not be started.\n        :rtype: twisted.internet.Deferred"
  },
  {
    "code": "def _checkReturnTo(self, message, return_to):\n        try:\n            self._verifyReturnToArgs(message.toPostArgs())\n        except ProtocolError as why:\n            logging.exception(\"Verifying return_to arguments: %s\" % (why, ))\n            return False\n        msg_return_to = message.getArg(OPENID_NS, 'return_to')\n        app_parts = urlparse(urinorm.urinorm(return_to))\n        msg_parts = urlparse(urinorm.urinorm(msg_return_to))\n        for part in range(0, 3):\n            if app_parts[part] != msg_parts[part]:\n                return False\n        return True",
    "docstring": "Check an OpenID message and its openid.return_to value\n        against a return_to URL from an application.  Return True on\n        success, False on failure."
  },
  {
    "code": "def structure_repr(self):\n        ret = '{%s}' % ', '.join([str(x) for x in self.elements])\n        return self._wrap_packed(ret)",
    "docstring": "Return the LLVM IR for the structure representation"
  },
  {
    "code": "def in_group(self, group, dn=False):\n        if dn:\n            return group in self.groups()\n        return group.check_member(self)",
    "docstring": "Get whether or not the bound CSH LDAP member object is part of a\n        group.\n\n        Arguments:\n        group -- the CSHGroup object (or distinguished name) of the group to\n                 check membership for"
  },
  {
    "code": "def set_pending_symbol(self, pending_symbol=None):\n        if pending_symbol is None:\n            pending_symbol = CodePointArray()\n        self.value = bytearray()\n        self.pending_symbol = pending_symbol\n        self.line_comment = False\n        return self",
    "docstring": "Sets the context's ``pending_symbol`` with the given unicode sequence and resets the context's ``value``.\n\n        If the input is None, an empty :class:`CodePointArray` is used."
  },
  {
    "code": "def write_params(path, *args, **dicts):\n    path = Path(path)\n    if not path.parent.is_dir():\n        path.parent.mkdir(parents=True)\n    if len(args) == 1:\n        d = args[0]\n        with path.open('w') as f:\n            for key in d:\n                f.write(key + ' = ' + str(d[key]) + '\\n')\n    else:\n        with path.open('w') as f:\n            for k, d in dicts.items():\n                f.write('[' + k + ']\\n')\n                for key, val in d.items():\n                    f.write(key + ' = ' + str(val) + '\\n')",
    "docstring": "Write parameters to file, so that it's readable by read_params.\n\n    Uses INI file format."
  },
  {
    "code": "def check_for_stalled_tasks():\n    from api.models.tasks import Task\n    for task in Task.objects.filter(status_is_running=True):\n        if not task.is_responsive():\n            task.system_error()\n        if task.is_timed_out():\n            task.timeout_error()",
    "docstring": "Check for tasks that are no longer sending a heartbeat"
  },
  {
    "code": "def all(self, paths, access=None):\n        self.failures = [path for path in paths if not\n                         isvalid(path, access, filetype='all')]\n        return not self.failures",
    "docstring": "Verify list of paths"
  },
  {
    "code": "def expanduser(path):\n    if hdfs_fs.default_is_local():\n        return os.path.expanduser(path)\n    m = re.match(r'^~([^/]*)', path)\n    if m is None:\n        return path\n    user = m.groups()[0] or common.DEFAULT_USER\n    return '/user/%s%s' % (user, path[m.end(1):])",
    "docstring": "Replace initial ``~`` or ``~user`` with the user's home directory.\n\n    **NOTE:** if the default file system is HDFS, the ``~user`` form is\n    expanded regardless of the user's existence."
  },
  {
    "code": "def to_dict(obj):\n        json_obj = {'type' : repr(obj)}\n        if obj.is_failed:\n            json_obj['errors'] = obj.errors\n        elif obj.is_success:\n            json_obj['modelOutput'] = obj.model_output\n        return json_obj",
    "docstring": "Generate a JSON serialization for the run state object.\n\n        Returns\n        -------\n        Json-like object\n            Json serialization of model run state object"
  },
  {
    "code": "def _has_argument(func):\n    if hasattr(inspect, 'signature'):\n        sig = inspect.signature(func)\n        return bool(sig.parameters)\n    else:\n        return bool(inspect.getargspec(func).args)",
    "docstring": "Test whether a function expects an argument.\n\n    :param func:\n        The function to be tested for existence of an argument."
  },
  {
    "code": "def authInsert(user, role, group, site):\n    if not role: return True\n    for k, v in user['roles'].iteritems():\n        for g in v['group']:\n            if k in role.get(g, '').split(':'):\n                return True\n    return False",
    "docstring": "Authorization function for general insert"
  },
  {
    "code": "def register_metric_descriptor(self, oc_md):\n        metric_type = self.get_metric_type(oc_md)\n        with self._md_lock:\n            if metric_type in self._md_cache:\n                return self._md_cache[metric_type]\n        descriptor = self.get_metric_descriptor(oc_md)\n        project_name = self.client.project_path(self.options.project_id)\n        sd_md = self.client.create_metric_descriptor(project_name, descriptor)\n        with self._md_lock:\n            self._md_cache[metric_type] = sd_md\n        return sd_md",
    "docstring": "Register a metric descriptor with stackdriver."
  },
  {
    "code": "def group(self):\n        \"Group inherited from items\"\n        if self._group:\n            return self._group\n        group =  get_ndmapping_label(self, 'group') if len(self) else None\n        if group is None:\n            return type(self).__name__\n        return group",
    "docstring": "Group inherited from items"
  },
  {
    "code": "def triads(key):\n    if _triads_cache.has_key(key):\n        return _triads_cache[key]\n    res = map(lambda x: triad(x, key), keys.get_notes(key))\n    _triads_cache[key] = res\n    return res",
    "docstring": "Return all the triads in key.\n\n    Implemented using a cache."
  },
  {
    "code": "def _create_storage_profile(self):\n        if self.image_publisher:\n            storage_profile = {\n                'image_reference': {\n                    'publisher': self.image_publisher,\n                    'offer': self.image_offer,\n                    'sku': self.image_sku,\n                    'version': self.image_version\n                },\n            }\n        else:\n            for image in self.compute.images.list():\n                if image.name == self.image_id:\n                    image_id = image.id\n                    break\n            else:\n                raise AzureCloudException(\n                    'Image with name {0} not found.'.format(self.image_id)\n                )\n            storage_profile = {\n                'image_reference': {\n                    'id': image_id\n                }\n            }\n        return storage_profile",
    "docstring": "Create the storage profile for the instance.\n\n        Image reference can be a custom image name or a published urn."
  },
  {
    "code": "def install_extension(conn, extension: str):\n    query = 'CREATE EXTENSION IF NOT EXISTS \"%s\";'\n    with conn.cursor() as cursor:\n        cursor.execute(query, (AsIs(extension),))\n    installed = check_extension(conn, extension)\n    if not installed:\n        raise psycopg2.ProgrammingError(\n            'Postgres extension failed installation.', extension\n        )",
    "docstring": "Install Postgres extension."
  },
  {
    "code": "def __get_jp(self, extractor_processor, sub_output=None):\n        if sub_output is None and extractor_processor.output_field is None:\n            raise ValueError(\n                \"ExtractorProcessors input paths cannot be unioned across fields.  Please specify either a sub_output or use a single scalar output_field\")\n        if extractor_processor.get_output_jsonpath_with_name(sub_output) is not None:\n            return extractor_processor.get_output_jsonpath_with_name(sub_output)\n        else:\n            return extractor_processor.get_output_jsonpath(sub_output)",
    "docstring": "Tries to get name from ExtractorProcessor to filter on first.\n        Otherwise falls back to filtering based on its metadata"
  },
  {
    "code": "def roll(self, shifts=None, roll_coords=None, **shifts_kwargs):\n        ds = self._to_temp_dataset().roll(\n            shifts=shifts, roll_coords=roll_coords, **shifts_kwargs)\n        return self._from_temp_dataset(ds)",
    "docstring": "Roll this array by an offset along one or more dimensions.\n\n        Unlike shift, roll may rotate all variables, including coordinates\n        if specified. The direction of rotation is consistent with\n        :py:func:`numpy.roll`.\n\n        Parameters\n        ----------\n        roll_coords : bool\n            Indicates whether to  roll the coordinates by the offset\n            The current default of roll_coords (None, equivalent to True) is\n            deprecated and will change to False in a future version.\n            Explicitly pass roll_coords to silence the warning.\n        **shifts : keyword arguments of the form {dim: offset}\n            Integer offset to rotate each of the given dimensions. Positive\n            offsets roll to the right; negative offsets roll to the left.\n\n        Returns\n        -------\n        rolled : DataArray\n            DataArray with the same attributes but rolled data and coordinates.\n\n        See also\n        --------\n        shift\n\n        Examples\n        --------\n\n        >>> arr = xr.DataArray([5, 6, 7], dims='x')\n        >>> arr.roll(x=1)\n        <xarray.DataArray (x: 3)>\n        array([7, 5, 6])\n        Coordinates:\n          * x        (x) int64 2 0 1"
  },
  {
    "code": "def append_surface(self, name, surface, alpha=1.):\n        self.insert_surface(position=self.df_surfaces.index.shape[0],\n                            name=name, surface=surface, alpha=alpha)",
    "docstring": "Append Cairo surface as new layer on top of existing layers.\n\n        Args\n        ----\n\n            name (str) : Name of layer.\n            surface (cairo.ImageSurface) : Surface to render.\n            alpha (float) : Alpha/transparency level in the range `[0, 1]`."
  },
  {
    "code": "def resize(self, targ_sz, new_path='tmp', resume=True, fn=None):\n        new_ds = []\n        dls = [self.trn_dl,self.val_dl,self.fix_dl,self.aug_dl]\n        if self.test_dl: dls += [self.test_dl, self.test_aug_dl]\n        else: dls += [None,None]\n        t = tqdm_notebook(dls)\n        for dl in t: new_ds.append(self.resized(dl, targ_sz, new_path, resume, fn))\n        t.close()\n        return self.__class__(new_ds[0].path, new_ds, self.bs, self.num_workers, self.classes)",
    "docstring": "Resizes all the images in the train, valid, test folders to a given size.\n\n        Arguments:\n        targ_sz (int): the target size\n        new_path (str): the path to save the resized images (default tmp)\n        resume (bool): if True, check for images in the DataSet that haven't been resized yet (useful if a previous resize\n        operation was aborted)\n        fn (function): optional custom resizing function"
  },
  {
    "code": "def deploy(self, machine):\n        log.debug(\"machine id: %s.\" % machine)\n        path = self.path + \"/machines\"\n        value, metadata = yield self.client.get(path)\n        machines = json.loads(value)\n        machines.append(machine)\n        yield self.client.set(path, json.dumps(machines))",
    "docstring": "Deploy service."
  },
  {
    "code": "def query_all(kind='1', by_count=False, by_order=True):\n        if by_count:\n            recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.count.desc())\n        elif by_order:\n            recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.order)\n        else:\n            recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.uid)\n        return recs",
    "docstring": "Qeury all the categories, order by count or defined order."
  },
  {
    "code": "def sample(self, fraction, seed=None, exact=False):\n        if (fraction > 1 or fraction < 0):\n            raise ValueError('Invalid sampling rate: ' + str(fraction))\n        if (len(self) == 0):\n            return SArray()\n        if seed is None:\n            seed = abs(hash(\"%0.20f\" % time.time())) % (2 ** 31)\n        with cython_context():\n            return SArray(_proxy=self.__proxy__.sample(fraction, seed, exact))",
    "docstring": "Create an SArray which contains a subsample of the current SArray.\n\n        Parameters\n        ----------\n        fraction : float\n            Fraction of the rows to fetch. Must be between 0 and 1.\n            if exact is False (default), the number of rows returned is\n            approximately the fraction times the number of rows.\n\n        seed : int, optional\n            The random seed for the random number generator.\n\n        exact: bool, optional\n            Defaults to False. If exact=True, an exact fraction is returned, \n            but at a performance penalty.\n\n        Returns\n        -------\n        out : SArray\n            The new SArray which contains the subsampled rows.\n\n        Examples\n        --------\n        >>> sa = turicreate.SArray(range(10))\n        >>> sa.sample(.3)\n        dtype: int\n        Rows: 3\n        [2, 6, 9]"
  },
  {
    "code": "def create(self, unique_name, domain_suffix=values.unset):\n        data = values.of({'UniqueName': unique_name, 'DomainSuffix': domain_suffix, })\n        payload = self._version.create(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return EnvironmentInstance(self._version, payload, service_sid=self._solution['service_sid'], )",
    "docstring": "Create a new EnvironmentInstance\n\n        :param unicode unique_name: The unique_name\n        :param unicode domain_suffix: The domain_suffix\n\n        :returns: Newly created EnvironmentInstance\n        :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentInstance"
  },
  {
    "code": "def findCampaigns(ra, dec):\n    logger.disabled = True\n    campaigns_visible = []\n    for c in fields.getFieldNumbers():\n        fovobj = fields.getKeplerFov(c)\n        if onSiliconCheck(ra, dec, fovobj):\n            campaigns_visible.append(c)\n    logger.disabled = True\n    return campaigns_visible",
    "docstring": "Returns a list of the campaigns that cover a given position.\n\n    Parameters\n    ----------\n    ra, dec : float, float\n        Position in decimal degrees (J2000).\n\n    Returns\n    -------\n    campaigns : list of int\n        A list of the campaigns that cover the given position."
  },
  {
    "code": "def get_aa_code(aa_letter):\n    aa_code = None\n    if aa_letter != 'X':\n        for key, val in standard_amino_acids.items():\n            if key == aa_letter:\n                aa_code = val\n    return aa_code",
    "docstring": "Get three-letter aa code if possible. If not, return None.\n\n    If three-letter code is None, will have to find this later from the filesystem.\n\n    Parameters\n    ----------\n    aa_letter : str\n        One-letter amino acid code.\n\n    Returns\n    -------\n    aa_code : str, or None\n        Three-letter aa code."
  },
  {
    "code": "def make_bubble_surface(dims=DEFAULT_DIMS, repeat=3):\n    gradients = make_gradients(dims)\n    return (\n        np.sin((gradients[0] - 0.5) * repeat * np.pi) *\n        np.sin((gradients[1] - 0.5) * repeat * np.pi))",
    "docstring": "Makes a surface from the product of sine functions on each axis.\n\n    Args:\n        dims (pair): the dimensions of the surface to create\n        repeat (int): the frequency of the waves is set to ensure this many\n            repetitions of the function\n    \n    Returns:\n        surface: A surface."
  },
  {
    "code": "def relpath(self):\n        cwd = self.__class__(os.getcwd())\n        return cwd.relpathto(self)",
    "docstring": "Return this path as a relative path,\n        based from the current working directory."
  },
  {
    "code": "def process_template(self, sql, **kwargs):\n        template = self.env.from_string(sql)\n        kwargs.update(self.context)\n        return template.render(kwargs)",
    "docstring": "Processes a sql template\n\n        >>> sql = \"SELECT '{{ datetime(2017, 1, 1).isoformat() }}'\"\n        >>> process_template(sql)\n        \"SELECT '2017-01-01T00:00:00'\""
  },
  {
    "code": "def _update_feature_log_prob(self, alpha):\n        smoothed_fc = self.feature_count_ + alpha\n        smoothed_cc = self.class_count_ + alpha * 2\n        self.feature_log_prob_ = (np.log(smoothed_fc) -\n                                  np.log(smoothed_cc.reshape(-1, 1)))",
    "docstring": "Apply smoothing to raw counts and recompute log probabilities"
  },
  {
    "code": "def _options(self):\n        if self._options_cache is None:\n            target_url = self.client.get_url(self._URL_KEY, 'OPTIONS', 'options')\n            r = self.client.request('OPTIONS', target_url)\n            self._options_cache = r.json()\n        return self._options_cache",
    "docstring": "Returns a raw options object\n\n        :rtype: dict"
  },
  {
    "code": "def _output(self, s):\n    if s.lower().startswith(b'host: '):\n        self._buffer.insert(1, s)\n    else:\n        self._buffer.append(s)",
    "docstring": "Host header should always be first"
  },
  {
    "code": "def format_explanation(explanation, original_msg=None):\n    if not conf.is_message_introspection_enabled() and original_msg:\n        return original_msg\n    explanation = ecu(explanation)\n    lines = _split_explanation(explanation)\n    result = _format_lines(lines)\n    return u('\\n').join(result)",
    "docstring": "This formats an explanation\n\n    Normally all embedded newlines are escaped, however there are\n    three exceptions: \\n{, \\n} and \\n~.  The first two are intended\n    cover nested explanations, see function and attribute explanations\n    for examples (.visit_Call(), visit_Attribute()).  The last one is\n    for when one explanation needs to span multiple lines, e.g. when\n    displaying diffs."
  },
  {
    "code": "def packageGraph(self, packagelevel=None):\n        packages = {}\n        for module in self.listModules():\n            package_name = self.packageOf(module.modname, packagelevel)\n            if package_name not in packages:\n                dirname = os.path.dirname(module.filename)\n                packages[package_name] = Module(package_name, dirname)\n            package = packages[package_name]\n            for name in module.imports:\n                package_name = self.packageOf(name, packagelevel)\n                if package_name != package.modname:\n                    package.imports.add(package_name)\n        graph = ModuleGraph()\n        graph.modules = packages\n        return graph",
    "docstring": "Convert a module graph to a package graph."
  },
  {
    "code": "def register_path(self, path, modified_time=None):\n        if not foundations.common.path_exists(path):\n            raise foundations.exceptions.PathExistsError(\"{0} | '{1}' path doesn't exists!\".format(\n                self.__class__.__name__, path))\n        if path in self:\n            raise umbra.exceptions.PathRegistrationError(\"{0} | '{1}' path is already registered!\".format(\n                self.__class__.__name__, path))\n        self.__paths[path] = (self.get_path_modified_time(\n            path) if modified_time is None else modified_time, os.path.isfile(path))\n        return True",
    "docstring": "Registers given path.\n\n        :param path: Path name.\n        :type path: unicode\n        :param modified_time: Custom modified time.\n        :type modified_time: int or float\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def change_and_save(self, update_only_changed_fields=False, **changed_fields):\n        bulk_change_and_save(self, update_only_changed_fields=update_only_changed_fields, **changed_fields)\n        return self.filter()",
    "docstring": "Changes a given `changed_fields` on each object in the queryset, saves objects\n        and returns the changed objects in the queryset."
  },
  {
    "code": "def build_pages(self):\n        for root, _, files in os.walk(self.pages_dir):\n            base_dir = root.replace(self.pages_dir, \"\").lstrip(\"/\")\n            if not base_dir.startswith(\"_\"):\n                for f in files:\n                    src_file = os.path.join(base_dir, f)\n                    self._build_page(src_file)",
    "docstring": "Iterate over the pages_dir and build the pages"
  },
  {
    "code": "def _pass_variable(self):\n        pass_var = []\n        for var in os.environ.keys():\n            expVAR = var.split(\"_\")\n            if expVAR[0] == self.prgnam.upper() and expVAR[1] != \"PATH\":\n                pass_var.append(\"{0}={1}\".format(expVAR[1], os.environ[var]))\n        return pass_var",
    "docstring": "Return enviroment variables"
  },
  {
    "code": "def getAllSecrets(version=\"\", region=None, table=\"credential-store\",\n                  context=None, credential=None, session=None, **kwargs):\n    if session is None:\n        session = get_session(**kwargs)\n    dynamodb = session.resource('dynamodb', region_name=region)\n    kms = session.client('kms', region_name=region)\n    secrets = listSecrets(region, table, **kwargs)\n    if credential and WILDCARD_CHAR in credential:\n        names = set(expand_wildcard(credential,\n                                    [x[\"name\"]\n                                     for x in secrets]))\n    else:\n        names = set(x[\"name\"] for x in secrets)\n    pool = ThreadPool(min(len(names), THREAD_POOL_MAX_SIZE))\n    results = pool.map(\n        lambda credential: getSecret(credential, version, region, table, context, dynamodb, kms, **kwargs),\n        names)\n    pool.close()\n    pool.join()\n    return dict(zip(names, results))",
    "docstring": "fetch and decrypt all secrets"
  },
  {
    "code": "def is_gentarget(self, target):\n    if self.gentarget_type:\n      return isinstance(target, self.gentarget_type)\n    else:\n      raise NotImplementedError",
    "docstring": "Predicate which determines whether the target in question is relevant to this codegen task.\n\n    E.g., the JaxbGen task considers JaxbLibrary targets to be relevant, and nothing else.\n\n    :API: public\n\n    :param Target target: The target to check.\n    :return: True if this class can generate code for the given target, False otherwise."
  },
  {
    "code": "def _parse_throttle(self, tablename, throttle):\n        amount = []\n        desc = self.describe(tablename)\n        throughputs = [desc.read_throughput, desc.write_throughput]\n        for value, throughput in zip(throttle[1:], throughputs):\n            if value == \"*\":\n                amount.append(0)\n            elif value[-1] == \"%\":\n                amount.append(throughput * float(value[:-1]) / 100.0)\n            else:\n                amount.append(float(value))\n        cap = Capacity(*amount)\n        return RateLimit(total=cap, callback=self._on_throttle)",
    "docstring": "Parse a 'throttle' statement and return a RateLimit"
  },
  {
    "code": "def _reset(self, force=False):\n        if not self._closed and (force or self._transaction):\n            try:\n                self.rollback()\n            except Exception:\n                pass",
    "docstring": "Reset a tough connection.\n\n        Rollback if forced or the connection was in a transaction."
  },
  {
    "code": "def perimeter(self):\n        if self._is_completely_masked:\n            return np.nan * u.pix\n        else:\n            from skimage.measure import perimeter\n            return perimeter(~self._total_mask, neighbourhood=4) * u.pix",
    "docstring": "The total perimeter of the source segment, approximated lines\n        through the centers of the border pixels using a 4-connectivity.\n\n        If any masked pixels make holes within the source segment, then\n        the perimeter around the inner hole (e.g. an annulus) will also\n        contribute to the total perimeter."
  },
  {
    "code": "def make_json_formatter(graph):\n    return {\n        \"()\": graph.config.logging.json_formatter.formatter,\n        \"fmt\": graph.config.logging.json_required_keys,\n    }",
    "docstring": "Create the default json formatter."
  },
  {
    "code": "def vault_file(env, default):\n    home = os.environ['HOME'] if 'HOME' in os.environ else \\\n        os.environ['USERPROFILE']\n    filename = os.environ.get(env, os.path.join(home, default))\n    filename = abspath(filename)\n    if os.path.exists(filename):\n        return filename\n    return None",
    "docstring": "The path to a misc Vault file\n    This function will check for the env override on a file\n    path, compute a fully qualified OS appropriate path to\n    the desired file and return it if it exists. Otherwise\n    returns None"
  },
  {
    "code": "def parse_routing_info(cls, records):\n        if len(records) != 1:\n            raise RoutingProtocolError(\"Expected exactly one record\")\n        record = records[0]\n        routers = []\n        readers = []\n        writers = []\n        try:\n            servers = record[\"servers\"]\n            for server in servers:\n                role = server[\"role\"]\n                addresses = []\n                for address in server[\"addresses\"]:\n                    addresses.append(SocketAddress.parse(address, DEFAULT_PORT))\n                if role == \"ROUTE\":\n                    routers.extend(addresses)\n                elif role == \"READ\":\n                    readers.extend(addresses)\n                elif role == \"WRITE\":\n                    writers.extend(addresses)\n            ttl = record[\"ttl\"]\n        except (KeyError, TypeError):\n            raise RoutingProtocolError(\"Cannot parse routing info\")\n        else:\n            return cls(routers, readers, writers, ttl)",
    "docstring": "Parse the records returned from a getServers call and\n        return a new RoutingTable instance."
  },
  {
    "code": "def average_sharded_losses(sharded_losses):\n  losses = {}\n  for loss_name in sorted(sharded_losses[0]):\n    all_shards = [shard_losses[loss_name] for shard_losses in sharded_losses]\n    if isinstance(all_shards[0], tuple):\n      sharded_num, sharded_den = zip(*all_shards)\n      mean_loss = (\n          tf.add_n(sharded_num) / tf.maximum(\n              tf.cast(1.0, sharded_den[0].dtype), tf.add_n(sharded_den)))\n    else:\n      mean_loss = tf.reduce_mean(all_shards)\n    losses[loss_name] = mean_loss\n  return losses",
    "docstring": "Average losses across datashards.\n\n  Args:\n    sharded_losses: list<dict<str loss_name, Tensor loss>>. The loss\n      can be a single Tensor or a 2-tuple (numerator and denominator).\n\n  Returns:\n    losses: dict<str loss_name, Tensor avg_loss>"
  },
  {
    "code": "def load_scene(self, item):\n        scene = Scene.from_config(self.pyvlx, item)\n        self.add(scene)",
    "docstring": "Load scene from json."
  },
  {
    "code": "def get_errors(self):\n        return [{cr.component_name: cr.get_error()}\n                for cr in self.component_results if cr.has_error()]",
    "docstring": "If there were any business errors fetching data for this property,\n        returns the error messages.\n\n        Returns:\n            string - the error message, or None if there was no error."
  },
  {
    "code": "def delete_multireddit(self, name, *args, **kwargs):\n        url = self.config['multireddit_about'].format(user=self.user.name,\n                                                      multi=name)\n        if not self._use_oauth:\n            self.http.headers['x-modhash'] = self.modhash\n        try:\n            self.request(url, data={}, method='DELETE', *args, **kwargs)\n        finally:\n            if not self._use_oauth:\n                del self.http.headers['x-modhash']",
    "docstring": "Delete a Multireddit.\n\n        Any additional parameters are passed directly into\n        :meth:`~praw.__init__.BaseReddit.request`"
  },
  {
    "code": "def update(self):\n        args = {attr: getattr(self, attr) for attr in self.to_update}\n        _perform_command(self, 'user_update', args)",
    "docstring": "Update the user's details on Todoist.\n\n        This method must be called to register any local attribute changes\n        with Todoist.\n\n        >>> from pytodoist import todoist\n        >>> user = todoist.login('john.doe@gmail.com', 'password')\n        >>> user.full_name = 'John Smith'\n        >>> # At this point Todoist still thinks the name is 'John Doe'.\n        >>> user.update()\n        >>> # Now the name has been updated on Todoist."
  },
  {
    "code": "def enable_key(self):\n        print(\"This command will enable a disabled key.\")\n        apiKeyID = input(\"API Key ID: \")\n        try:\n            key = self._curl_bitmex(\"/apiKey/enable\",\n                                    postdict={\"apiKeyID\": apiKeyID})\n            print(\"Key with ID %s enabled.\" % key[\"id\"])\n        except:\n            print(\"Unable to enable key, please try again.\")\n            self.enable_key()",
    "docstring": "Enable an existing API Key."
  },
  {
    "code": "def upload_keys(self, device_keys=None, one_time_keys=None):\n        content = {}\n        if device_keys:\n            content[\"device_keys\"] = device_keys\n        if one_time_keys:\n            content[\"one_time_keys\"] = one_time_keys\n        return self._send(\"POST\", \"/keys/upload\", content=content)",
    "docstring": "Publishes end-to-end encryption keys for the device.\n\n        Said device must be the one used when logging in.\n\n        Args:\n            device_keys (dict): Optional. Identity keys for the device. The required\n                keys are:\n\n                | user_id (str): The ID of the user the device belongs to. Must match\n                    the user ID used when logging in.\n                | device_id (str): The ID of the device these keys belong to. Must match\n                    the device ID used when logging in.\n                | algorithms (list<str>): The encryption algorithms supported by this\n                    device.\n                | keys (dict): Public identity keys. Should be formatted as\n                    <algorithm:device_id>: <key>.\n                | signatures (dict): Signatures for the device key object. Should be\n                    formatted as <user_id>: {<algorithm:device_id>: <key>}\n\n            one_time_keys (dict): Optional. One-time public keys. Should be\n                formatted as <algorithm:key_id>: <key>, the key format being\n                determined by the algorithm."
  },
  {
    "code": "def form(cls, name, type_=Type.String, description=None, required=None, default=None,\n             minimum=None, maximum=None, enum=None, **options):\n        if minimum is not None and maximum is not None and minimum > maximum:\n            raise ValueError(\"Minimum must be less than or equal to the maximum.\")\n        return cls(name, In.Form, type_, None, description,\n                   required=required, default=default,\n                   minimum=minimum, maximum=maximum,\n                   enum=enum, **options)",
    "docstring": "Define form parameter."
  },
  {
    "code": "def answer_approval(self, issue_id_or_key, approval_id, decision):\n        url = 'rest/servicedeskapi/request/{0}/approval/{1}'.format(issue_id_or_key, approval_id)\n        data = {'decision': decision}\n        return self.post(url, headers=self.experimental_headers, data=data)",
    "docstring": "Answer a pending approval\n\n        :param issue_id_or_key: str\n        :param approval_id: str\n        :param decision: str\n        :return:"
  },
  {
    "code": "def html_to_text(html, base_url='', bodywidth=CONFIG_DEFAULT):\n    def _patched_handle_charref(c):\n        self = h\n        charref = self.charref(c)\n        if self.code or self.pre:\n            charref = cgi.escape(charref)\n        self.o(charref, 1)\n    def _patched_handle_entityref(c):\n        self = h\n        entityref = self.entityref(c)\n        if self.code or self.pre:\n            entityref = cgi.escape(entityref)\n        self.o(entityref, 1)\n    h = HTML2Text(baseurl=base_url, bodywidth=config.BODY_WIDTH if bodywidth is CONFIG_DEFAULT else bodywidth)\n    h.handle_entityref = _patched_handle_entityref\n    h.handle_charref = _patched_handle_charref\n    return h.handle(html).rstrip()",
    "docstring": "Convert a HTML mesasge to plain text."
  },
  {
    "code": "def importTTX(self):\n        import os\n        import re\n        prefix = \"com.github.fonttools.ttx\"\n        sfntVersionRE = re.compile('(^<ttFont\\s+)(sfntVersion=\".*\"\\s+)(.*>$)',\n                                   flags=re.MULTILINE)\n        if not hasattr(self.ufo, \"data\"):\n            return\n        if not self.ufo.data.fileNames:\n            return\n        for path in self.ufo.data.fileNames:\n            foldername, filename = os.path.split(path)\n            if (foldername == prefix and filename.endswith(\".ttx\")):\n                ttx = self.ufo.data[path].decode('utf-8')\n                ttx = sfntVersionRE.sub(r'\\1\\3', ttx)\n                fp = BytesIO(ttx.encode('utf-8'))\n                self.otf.importXML(fp)",
    "docstring": "Merge TTX files from data directory \"com.github.fonttools.ttx\"\n\n        **This should not be called externally.** Subclasses\n        may override this method to handle the bounds creation\n        in a different way if desired."
  },
  {
    "code": "def FoldValue(self, value):\n    if value is False and self._data_type_definition.false_value is not None:\n      return self._data_type_definition.false_value\n    if value is True and self._data_type_definition.true_value is not None:\n      return self._data_type_definition.true_value\n    raise ValueError('No matching True and False values')",
    "docstring": "Folds the data type into a value.\n\n    Args:\n      value (object): value.\n\n    Returns:\n      object: folded value.\n\n    Raises:\n      ValueError: if the data type definition cannot be folded into the value."
  },
  {
    "code": "def bounding_ellipses(self):\n        if (self.linear_growth):\n            a1 = self.sma - self.astep / 2.\n            a2 = self.sma + self.astep / 2.\n        else:\n            a1 = self.sma * (1. - self.astep / 2.)\n            a2 = self.sma * (1. + self.astep / 2.)\n        return a1, a2",
    "docstring": "Compute the semimajor axis of the two ellipses that bound the\n        annulus where integrations take place.\n\n        Returns\n        -------\n        sma1, sma2 : float\n            The smaller and larger values of semimajor axis length that\n            define the annulus bounding ellipses."
  },
  {
    "code": "def vectorize_utterance_ohe(self, utterance):\n        for i, word in enumerate(utterance):\n            if not word in self.vocab_list:\n                utterance[i] = '<unk>'\n        ie_utterance = self.swap_pad_and_zero(self.ie.transform(utterance))\n        ohe_utterance = np.array(self.ohe.transform(ie_utterance.reshape(len(ie_utterance), 1)))\n        return ohe_utterance",
    "docstring": "Take in a tokenized utterance and transform it into a sequence of one-hot vectors"
  },
  {
    "code": "def add_data(self, rawdata):\n        for data in rawdata:\n            try:\n                item = data[0]\n                if item[0] == 2:\n                    continue\n                if item[0] != 0:\n                    warnings.warn(f\"Unknown message type '{item[0]}'\", Warning)\n                    continue\n                item = item[1]\n                target = str(item[0])\n                try:\n                    data = item[1]\n                except IndexError:\n                    data = dict()\n                try:\n                    method = getattr(self, self.__head + target)\n                    method(data)\n                except AttributeError:\n                    self._handle_unhandled(target, data)\n            except IndexError:\n                LOGGER.warning(\"Wrongly constructed message received: %r\", data)\n        self.conn.process_queues()",
    "docstring": "Add data to given room's state"
  },
  {
    "code": "def get_high_water_mark(self, mark_type, obstory_name=None):\n        if obstory_name is None:\n            obstory_name = self.obstory_name\n        obstory = self.get_obstory_from_name(obstory_name)\n        key_id = self.get_hwm_key_id(mark_type)\n        self.con.execute('SELECT time FROM archive_highWaterMarks WHERE markType=%s AND observatoryId=%s',\n                         (key_id, obstory['uid']))\n        results = self.con.fetchall()\n        if len(results) > 0:\n            return results[0]['time']\n        return None",
    "docstring": "Retrieves the high water mark for a given obstory, defaulting to the current installation ID\n\n        :param string mark_type:\n            The type of high water mark to set\n        :param string obstory_name:\n            The obstory ID to check for, or the default installation ID if not specified\n        :return:\n            A UTC datetime for the high water mark, or None if none was found."
  },
  {
    "code": "def active_serving_watcher(backend, kitchen, period):\n    err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)\n    if use_kitchen is None:\n        raise click.ClickException(err_str)\n    click.secho('%s - Watching Active OrderRun Changes in Kitchen %s' % (get_datetime(), use_kitchen), fg='green')\n    DKCloudCommandRunner.watch_active_servings(backend.dki, use_kitchen, period)\n    while True:\n        try:\n            DKCloudCommandRunner.join_active_serving_watcher_thread_join()\n            if not DKCloudCommandRunner.watcher_running():\n                break\n        except KeyboardInterrupt:\n            print 'KeyboardInterrupt'\n            exit_gracefully(None, None)\n    exit(0)",
    "docstring": "Watches all cooking Recipes in a Kitchen\n    Provide the kitchen name as an argument or be in a Kitchen folder."
  },
  {
    "code": "def register_phonon_task(self, *args, **kwargs):\n        kwargs[\"task_class\"] = PhononTask\n        return self.register_task(*args, **kwargs)",
    "docstring": "Register a phonon task."
  },
  {
    "code": "def set_blocking(fd, blocking=True):\n    old_flag = fcntl.fcntl(fd, fcntl.F_GETFL)\n    if blocking:\n        new_flag = old_flag & ~ os.O_NONBLOCK\n    else:\n        new_flag = old_flag | os.O_NONBLOCK\n    fcntl.fcntl(fd, fcntl.F_SETFL, new_flag)\n    return not bool(old_flag & os.O_NONBLOCK)",
    "docstring": "Set the given file-descriptor blocking or non-blocking.\n\n    Returns the original blocking status."
  },
  {
    "code": "def posttrans_hook(conduit):\n    if 'SALT_RUNNING' not in os.environ:\n        with open(CK_PATH, 'w') as ck_fh:\n            ck_fh.write('{chksum} {mtime}\\n'.format(chksum=_get_checksum(), mtime=_get_mtime()))",
    "docstring": "Hook after the package installation transaction.\n\n    :param conduit:\n    :return:"
  },
  {
    "code": "def create_magic_packet(macaddress):\n    if len(macaddress) == 12:\n        pass\n    elif len(macaddress) == 17:\n        sep = macaddress[2]\n        macaddress = macaddress.replace(sep, '')\n    else:\n        raise ValueError('Incorrect MAC address format')\n    data = b'FFFFFFFFFFFF' + (macaddress * 16).encode()\n    send_data = b''\n    for i in range(0, len(data), 2):\n        send_data += struct.pack(b'B', int(data[i: i + 2], 16))\n    return send_data",
    "docstring": "Create a magic packet.\n\n    A magic packet is a packet that can be used with the for wake on lan\n    protocol to wake up a computer. The packet is constructed from the\n    mac address given as a parameter.\n\n    Args:\n        macaddress (str): the mac address that should be parsed into a\n            magic packet."
  },
  {
    "code": "def parse_chains(data):\n    chains = odict()\n    for line in data.splitlines(True):\n        m = re_chain.match(line)\n        if m:\n            policy = None\n            if m.group(2) != '-':\n                policy = m.group(2)\n            chains[m.group(1)] = {\n                'policy': policy,\n                'packets': int(m.group(3)),\n                'bytes': int(m.group(4)),\n            }\n    return chains",
    "docstring": "Parse the chain definitions."
  },
  {
    "code": "def stress(ref_cds, est_cds):\n    ref_dists = pdist(ref_cds)\n    est_dists = pdist(est_cds)\n    return np.sqrt(((ref_dists - est_dists)**2).sum() / (ref_dists**2).sum())",
    "docstring": "Kruskal's stress"
  },
  {
    "code": "def response(self, component_id, component=None, **kwargs):\n        if component_id in self._responses:\n            raise DuplicateComponentNameError(\n                'Another response with name \"{}\" is already registered.'.format(\n                    component_id\n                )\n            )\n        component = component or {}\n        ret = component.copy()\n        for plugin in self._plugins:\n            try:\n                ret.update(plugin.response_helper(component, **kwargs) or {})\n            except PluginMethodNotImplementedError:\n                continue\n        self._responses[component_id] = ret\n        return self",
    "docstring": "Add a response which can be referenced.\n\n        :param str component_id: ref_id to use as reference\n        :param dict component: response fields\n        :param dict kwargs: plugin-specific arguments"
  },
  {
    "code": "def DomainFactory(domain_name, cmds):\n    klass = type(str(domain_name), (BaseDomain,), {})\n    for c in cmds:\n        command = get_command(domain_name, c['name'])\n        setattr(klass, c['name'], classmethod(command))\n    return klass",
    "docstring": "Dynamically create Domain class and set it's methods."
  },
  {
    "code": "def zpopmax(self, name, count=None):\n        args = (count is not None) and [count] or []\n        options = {\n            'withscores': True\n        }\n        return self.execute_command('ZPOPMAX', name, *args, **options)",
    "docstring": "Remove and return up to ``count`` members with the highest scores\n        from the sorted set ``name``."
  },
  {
    "code": "async def restart(request):\n    def wait_and_restart():\n        log.info('Restarting server')\n        sleep(1)\n        os.system('kill 1')\n    Thread(target=wait_and_restart).start()\n    return web.json_response({\"message\": \"restarting\"})",
    "docstring": "Returns OK, then waits approximately 1 second and restarts container"
  },
  {
    "code": "def com_google_fonts_check_glyf_unused_data(ttFont):\n  try:\n    expected_glyphs = len(ttFont.getGlyphOrder())\n    actual_glyphs = len(ttFont['glyf'].glyphs)\n    diff = actual_glyphs - expected_glyphs\n    if diff < 0:\n      yield FAIL, Message(\"unreachable-data\",\n                          (\"Glyf table has unreachable data at the end of \"\n                           \" the table. Expected glyf table length {}\"\n                           \" (from loca table), got length\"\n                           \" {} (difference: {})\").format(\n                               expected_glyphs, actual_glyphs, diff))\n    elif not diff:\n      yield PASS, \"There is no unused data at the end of the glyf table.\"\n    else:\n      raise Exception(\"Bug: fontTools did not raise an expected exception.\")\n  except fontTools.ttLib.TTLibError as error:\n    if \"not enough 'glyf' table data\" in format(error):\n      yield FAIL, Message(\"missing-data\",\n                          (\"Loca table references data beyond\"\n                           \" the end of the glyf table.\"\n                           \" Expected glyf table length {}\"\n                           \" (from loca table).\").format(expected_glyphs))\n    else:\n      raise Exception(\"Bug: Unexpected fontTools exception.\")",
    "docstring": "Is there any unused data at the end of the glyf table?"
  },
  {
    "code": "def create_with_dst_resource_provisioning(\n            cls, cli, src_resource_id, dst_resource_config,\n            max_time_out_of_sync, name=None, remote_system=None,\n            src_spa_interface=None, src_spb_interface=None,\n            dst_spa_interface=None, dst_spb_interface=None,\n            dst_resource_element_configs=None, auto_initiate=None,\n            hourly_snap_replication_policy=None,\n            daily_snap_replication_policy=None, replicate_existing_snaps=None):\n        req_body = cli.make_body(\n            srcResourceId=src_resource_id,\n            dstResourceConfig=dst_resource_config,\n            maxTimeOutOfSync=max_time_out_of_sync,\n            name=name, remoteSystem=remote_system,\n            srcSPAInterface=src_spa_interface,\n            srcSPBInterface=src_spb_interface,\n            dstSPAInterface=dst_spa_interface,\n            dstSPBInterface=dst_spb_interface,\n            dstResourceElementConfigs=dst_resource_element_configs,\n            autoInitiate=auto_initiate,\n            hourlySnapReplicationPolicy=hourly_snap_replication_policy,\n            dailySnapReplicationPolicy=daily_snap_replication_policy,\n            replicateExistingSnaps=replicate_existing_snaps)\n        resp = cli.type_action(\n            cls().resource_class,\n            'createReplicationSessionWDestResProvisioning',\n            **req_body)\n        resp.raise_if_err()\n        session_resp = resp.first_content['id']\n        return cls.get(cli, _id=session_resp['id'])",
    "docstring": "Create a replication session along with destination resource\n        provisioning.\n\n        :param cli: the rest cli.\n        :param src_resource_id: id of the replication source, could be\n            lun/fs/cg.\n        :param dst_resource_config: `UnityResourceConfig` object. The user\n            chosen config for destination resource provisioning. `pool_id` and\n            `size` are required for creation.\n        :param max_time_out_of_sync: maximum time to wait before syncing the\n            source and destination. Value `-1` means the automatic sync is not\n            performed. `0` means it is a sync replication.\n        :param name: name of the replication.\n        :param remote_system: `UnityRemoteSystem` object. The remote system to\n            which the replication is being configured. When not specified, it\n            defaults to local system.\n        :param src_spa_interface: `UnityRemoteInterface` object. The\n            replication interface for source SPA.\n        :param src_spb_interface: `UnityRemoteInterface` object. The\n            replication interface for source SPB.\n        :param dst_spa_interface: `UnityRemoteInterface` object. The\n            replication interface for destination SPA.\n        :param dst_spb_interface: `UnityRemoteInterface` object. The\n            replication interface for destination SPB.\n        :param dst_resource_element_configs: List of `UnityResourceConfig`\n            objects. The user chose config for each of the member element of\n            the destination resource.\n        :param auto_initiate: indicates whether to perform the first\n            replication sync automatically.\n            True - perform the first replication sync automatically.\n            False - perform the first replication sync manually.\n        :param hourly_snap_replication_policy: `UnitySnapReplicationPolicy`\n            object. The policy for replicating hourly scheduled snaps of the\n            source resource.\n        :param daily_snap_replication_policy: `UnitySnapReplicationPolicy`\n            object. The policy for replicating daily scheduled snaps of the\n            source resource.\n        :param replicate_existing_snaps: indicates whether or not to replicate\n            snapshots already existing on the resource.\n        :return: the newly created replication session."
  },
  {
    "code": "def render_tree(root, child_func, prune=0, margin=[0], visited=None):\n    rname = str(root)\n    if visited is None:\n        visited = {}\n    children = child_func(root)\n    retval = \"\"\n    for pipe in margin[:-1]:\n        if pipe:\n            retval = retval + \"| \"\n        else:\n            retval = retval + \"  \"\n    if rname in visited:\n        return retval + \"+-[\" + rname + \"]\\n\"\n    retval = retval + \"+-\" + rname + \"\\n\"\n    if not prune:\n        visited = copy.copy(visited)\n    visited[rname] = 1\n    for i in range(len(children)):\n        margin.append(i < len(children)-1)\n        retval = retval + render_tree(children[i], child_func, prune, margin, visited)\n        margin.pop()\n    return retval",
    "docstring": "Render a tree of nodes into an ASCII tree view.\n\n    :Parameters:\n        - `root`:       the root node of the tree\n        - `child_func`: the function called to get the children of a node\n        - `prune`:      don't visit the same node twice\n        - `margin`:     the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe.\n        - `visited`:    a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune."
  },
  {
    "code": "def setups(self):\n        result = []\n        has_options = self.base_object.is_optionhandler\n        enm = javabridge.get_enumeration_wrapper(javabridge.call(self.jobject, \"setups\", \"()Ljava/util/Enumeration;\"))\n        while enm.hasMoreElements():\n            if has_options:\n                result.append(OptionHandler(enm.nextElement()))\n            else:\n                result.append(JavaObject(enm.nextElement()))\n        return result",
    "docstring": "Generates and returns all the setups according to the parameter search space.\n\n        :return: the list of configured objects (of type JavaObject)\n        :rtype: list"
  },
  {
    "code": "def solution_violations(solution, events, slots):\n    array = converter.solution_to_array(solution, events, slots)\n    return array_violations(array, events, slots)",
    "docstring": "Take a solution and return a list of violated constraints\n\n    Parameters\n    ----------\n        solution: list or tuple\n            a schedule in solution form\n        events : list or tuple\n            of resources.Event instances\n        slots : list or tuple\n            of resources.Slot instances\n\n    Returns\n    -------\n        Generator\n            of a list of strings indicating the nature of the violated\n            constraints"
  },
  {
    "code": "def temp_path(file_name=None):\n    if file_name is None:\n        file_name = generate_timestamped_string(\"wtf_temp_file\")\n    return os.path.join(tempfile.gettempdir(), file_name)",
    "docstring": "Gets a temp path.\n\n    Kwargs:\n        file_name (str) : if file name is specified, it gets appended to the temp dir.\n\n    Usage::\n\n        temp_file_path = temp_path(\"myfile\")\n        copyfile(\"myfile\", temp_file_path) # copies 'myfile' to '/tmp/myfile'"
  },
  {
    "code": "def flush(self):\n        for key in self.grouping_info.keys():\n            if self._should_flush(key):\n                self._write_current_buffer_for_group_key(key)",
    "docstring": "Ensure all remaining buffers are written."
  },
  {
    "code": "def screenshot(self):\n        b64data = self.http.get('/screenshot').value\n        raw_data = base64.b64decode(b64data)\n        from PIL import Image\n        buff = io.BytesIO(raw_data)\n        return Image.open(buff)",
    "docstring": "Take screenshot with session check\n\n        Returns:\n            PIL.Image"
  },
  {
    "code": "def load(path, service=None, hostport=None, module_name=None):\n    if not path.endswith('.thrift'):\n        service, path = path, service\n    module = thriftrw.load(path=path, name=module_name)\n    return TChannelThriftModule(service, module, hostport)",
    "docstring": "Loads the Thrift file at the specified path.\n\n    The file is compiled in-memory and a Python module containing the result\n    is returned. It may be used with ``TChannel.thrift``. For example,\n\n    .. code-block:: python\n\n        from tchannel import TChannel, thrift\n\n        # Load our server's interface definition.\n        donuts = thrift.load(path='donuts.thrift')\n\n        # We need to specify a service name or hostport because this is a\n        # downstream service we'll be calling.\n        coffee = thrift.load(path='coffee.thrift', service='coffee')\n\n        tchannel = TChannel('donuts')\n\n        @tchannel.thrift.register(donuts.DonutsService)\n        @tornado.gen.coroutine\n        def submitOrder(request):\n            args = request.body\n\n            if args.coffee:\n                yield tchannel.thrift(\n                    coffee.CoffeeService.order(args.coffee)\n                )\n\n            # ...\n\n    The returned module contains, one top-level type for each struct, enum,\n    union, exeption, and service defined in the Thrift file. For each service,\n    the corresponding class contains a classmethod for each function defined\n    in that service that accepts the arguments for that function and returns a\n    ``ThriftRequest`` capable of being sent via ``TChannel.thrift``.\n\n    For more information on what gets generated by ``load``, see `thriftrw\n    <http://thriftrw.readthedocs.org/en/latest/>`_.\n\n    Note that the ``path`` accepted by ``load`` must be either an absolute\n    path or a path relative to the *the current directory*. If you need to\n    refer to Thrift files relative to the Python module in which ``load`` was\n    called, use the ``__file__`` magic variable.\n\n    .. code-block:: python\n\n        # Given,\n        #\n        #   foo/\n        #     myservice.thrift\n        #     bar/\n        #       x.py\n        #\n        # Inside foo/bar/x.py,\n\n        path = os.path.join(\n            os.path.dirname(__file__), '../myservice.thrift'\n        )\n\n    The returned value is a valid Python module. You can install the module by\n    adding it to the ``sys.modules`` dictionary. This will allow importing\n    items from this module directly. You can use the ``__name__`` magic\n    variable to make the generated module a submodule of the current module.\n    For example,\n\n    .. code-block:: python\n\n        # foo/bar.py\n\n        import sys\n        from tchannel import thrift\n\n        donuts = = thrift.load('donuts.thrift')\n        sys.modules[__name__ + '.donuts'] = donuts\n\n    This installs the module generated for ``donuts.thrift`` as the module\n    ``foo.bar.donuts``. Callers can then import items from that module\n    directly. For example,\n\n    .. code-block:: python\n\n        # foo/baz.py\n\n        from foo.bar.donuts import DonutsService, Order\n\n        def baz(tchannel):\n            return tchannel.thrift(\n                DonutsService.submitOrder(Order(..))\n            )\n\n    :param str service:\n        Name of the service that the Thrift file represents. This name will be\n        used to route requests through Hyperbahn.\n    :param str path:\n        Path to the Thrift file. If this is a relative path, it must be\n        relative to the current directory.\n    :param str hostport:\n        Clients can use this to specify the hostport at which the service can\n        be found. If omitted, TChannel will route the requests through known\n        peers. This value is ignored by servers.\n    :param str module_name:\n        Name used for the generated Python module. Defaults to the name of the\n        Thrift file."
  },
  {
    "code": "def fix_facets(self):\n        facets = self.facets\n        for key in list(facets.keys()):\n            _type = facets[key].get(\"_type\", \"unknown\")\n            if _type == \"date_histogram\":\n                for entry in facets[key].get(\"entries\", []):\n                    for k, v in list(entry.items()):\n                        if k in [\"count\", \"max\", \"min\", \"total_count\", \"mean\", \"total\"]:\n                            continue\n                        if not isinstance(entry[k], datetime):\n                            entry[k] = datetime.utcfromtimestamp(v / 1e3)",
    "docstring": "This function convert date_histogram facets to datetime"
  },
  {
    "code": "def convert_units_to_base_units(units):\n    total_factor = 1\n    new_units = []\n    for unit in units:\n        if unit not in BASE_UNIT_CONVERSIONS:\n            continue\n        factor, new_unit = BASE_UNIT_CONVERSIONS[unit]\n        total_factor *= factor\n        new_units.append(new_unit)\n    new_units.sort()\n    return total_factor, tuple(new_units)",
    "docstring": "Convert a set of units into a set of \"base\" units.\n\n    Returns a 2-tuple of `factor, new_units`."
  },
  {
    "code": "def save_to(self, obj):\n        if isinstance(obj, dict):\n            obj = dict(obj)\n        for key in self.changed_fields:\n            if key in self.cleaned_data:\n                val = self.cleaned_data.get(key)\n                set_obj_value(obj, key, val)\n        return obj",
    "docstring": "Save the cleaned data to an object."
  },
  {
    "code": "def execute_script(self, name, keys, *args, **options):\n        script = get_script(name)\n        if not script:\n            raise redis.RedisError('No such script \"%s\"' % name)\n        address = self.address()\n        if address not in all_loaded_scripts:\n            all_loaded_scripts[address] = set()\n        loaded = all_loaded_scripts[address]\n        toload = script.required_scripts.difference(loaded)\n        for name in toload:\n            s = get_script(name)\n            yield self.script_load(s.script)\n        loaded.update(toload)\n        yield script(self, keys, args, options)",
    "docstring": "Execute a script.\n\n        makes sure all required scripts are loaded."
  },
  {
    "code": "def register_channel_post_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None,\n                                      state=None, run_task=None, **kwargs):\n        filters_set = self.filters_factory.resolve(self.channel_post_handlers,\n                                                   *custom_filters,\n                                                   commands=commands,\n                                                   regexp=regexp,\n                                                   content_types=content_types,\n                                                   state=state,\n                                                   **kwargs)\n        self.channel_post_handlers.register(self._wrap_async_task(callback, run_task), filters_set)",
    "docstring": "Register handler for channel post\n\n        :param callback:\n        :param commands: list of commands\n        :param regexp: REGEXP\n        :param content_types: List of content types.\n        :param state:\n        :param custom_filters: list of custom filters\n        :param run_task: run callback in task (no wait results)\n        :param kwargs:\n        :return: decorated function"
  },
  {
    "code": "def disable_switchport(self, inter_type, inter):\n        config = ET.Element('config')\n        interface = ET.SubElement(config, 'interface',\n                                  xmlns=(\"urn:brocade.com:mgmt:\"\n                                         \"brocade-interface\"))\n        int_type = ET.SubElement(interface, inter_type)\n        name = ET.SubElement(int_type, 'name')\n        name.text = inter\n        ET.SubElement(int_type, 'switchport-basic', operation='delete')\n        try:\n            self._callback(config)\n            return True\n        except Exception as error:\n            logging.error(error)\n            return False",
    "docstring": "Change an interface's operation to L3.\n\n        Args:\n            inter_type: The type of interface you want to configure. Ex.\n                tengigabitethernet, gigabitethernet, fortygigabitethernet.\n            inter: The ID for the interface you want to configure. Ex. 1/0/1\n\n        Returns:\n            True if command completes successfully or False if not.\n\n        Raises:\n            None"
  },
  {
    "code": "def write_intro (self):\n        self.comment(_(\"created by %(app)s at %(time)s\") %\n                    {\"app\": configuration.AppName,\n                     \"time\": strformat.strtime(self.starttime)})\n        self.comment(_(\"Get the newest version at %(url)s\") %\n                     {'url': configuration.Url})\n        self.comment(_(\"Write comments and bugs to %(url)s\") %\n                     {'url': configuration.SupportUrl})\n        self.comment(_(\"Support this project at %(url)s\") %\n                     {'url': configuration.DonateUrl})\n        self.check_date()",
    "docstring": "Write intro comments."
  },
  {
    "code": "def get_field_info(self, field):\n        field_info = self.get_attributes(field)\n        field_info[\"required\"] = getattr(field, \"required\", False)\n        field_info[\"type\"] = self.get_label_lookup(field)\n        if getattr(field, \"child\", None):\n            field_info[\"child\"] = self.get_field_info(field.child)\n        elif getattr(field, \"fields\", None):\n            field_info[\"children\"] = self.get_serializer_info(field)\n        if (not isinstance(field, (serializers.RelatedField, serializers.ManyRelatedField)) and\n                hasattr(field, \"choices\")):\n            field_info[\"choices\"] = [\n                {\n                    \"value\": choice_value,\n                    \"display_name\": force_text(choice_name, strings_only=True)\n                }\n                for choice_value, choice_name in field.choices.items()\n            ]\n        return field_info",
    "docstring": "This method is basically a mirror from rest_framework==3.3.3\n\n        We are currently pinned to rest_framework==3.1.1. If we upgrade,\n        this can be refactored and simplified to rely more heavily on\n        rest_framework's built in logic."
  },
  {
    "code": "def detect_traits(item):\n    return traits.detect_traits(\n        name=item.name, alias=item.alias,\n        filetype=(list(item.fetch(\"kind_51\")) or [None]).pop(),\n    )",
    "docstring": "Build traits list from attributes of the passed item. Currently,\n        \"kind_51\", \"name\" and \"alias\" are considered.\n\n        See pyrocore.util.traits:dectect_traits for more details."
  },
  {
    "code": "def partition(pred, iterable):\n    trues = []\n    falses = []\n    for item in iterable:\n        if pred(item):\n            trues.append(item)\n        else:\n            falses.append(item)\n    return trues, falses",
    "docstring": "split the results of an iterable based on a predicate"
  },
  {
    "code": "def _lint():\n    project_python_files = [filename for filename in get_project_files()\n                            if filename.endswith(b'.py')]\n    retcode = subprocess.call(\n        ['flake8', '--max-complexity=10'] + project_python_files)\n    if retcode == 0:\n        print_success_message('No style errors')\n    return retcode",
    "docstring": "Run lint and return an exit code."
  },
  {
    "code": "def map_sections(fun, neurites, neurite_type=NeuriteType.all, iterator_type=Tree.ipreorder):\n    return map(fun, iter_sections(neurites,\n                                  iterator_type=iterator_type,\n                                  neurite_filter=is_type(neurite_type)))",
    "docstring": "Map `fun` to all the sections in a collection of neurites"
  },
  {
    "code": "def bestfit_func(self, bestfit_x):\n        if not self.bestfit_func:\n            raise KeyError(\"Do do_bestfit first\")\n        return self.args[\"func\"](self.fit_args, bestfit_x)",
    "docstring": "Returns y value"
  },
  {
    "code": "def ekifld(handle, tabnam, ncols, nrows, cnmlen, cnames, declen, decls):\n    handle = ctypes.c_int(handle)\n    tabnam = stypes.stringToCharP(tabnam)\n    ncols = ctypes.c_int(ncols)\n    nrows = ctypes.c_int(nrows)\n    cnmlen = ctypes.c_int(cnmlen)\n    cnames = stypes.listToCharArray(cnames)\n    declen = ctypes.c_int(declen)\n    recptrs = stypes.emptyIntVector(nrows)\n    decls = stypes.listToCharArray(decls)\n    segno = ctypes.c_int()\n    libspice.ekifld_c(handle, tabnam, ncols, nrows, cnmlen, cnames, declen,\n                      decls, ctypes.byref(segno), recptrs)\n    return segno.value, stypes.cVectorToPython(recptrs)",
    "docstring": "Initialize a new E-kernel segment to allow fast writing.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekifld_c.html\n\n    :param handle: File handle.\n    :type handle: int\n    :param tabnam: Table name.\n    :type tabnam: str\n    :param ncols: Number of columns in the segment.\n    :type ncols: int\n    :param nrows: Number of rows in the segment.\n    :type nrows: int\n    :param cnmlen: Length of names in in column name array.\n    :type cnmlen: int\n    :param cnames: Names of columns.\n    :type cnames: list of str.\n    :param declen: Length of declaration strings in declaration array.\n    :type declen: int\n    :param decls: Declarations of columns.\n    :type decls: list of str.\n    :return: Segment number, Array of record pointers.\n    :rtype: tuple"
  },
  {
    "code": "def get_grid_data(xall, yall, zall, nbins=100, method='nearest'):\n    from scipy.interpolate import griddata\n    x, y = _np.meshgrid(\n        _np.linspace(xall.min(), xall.max(), nbins),\n        _np.linspace(yall.min(), yall.max(), nbins),\n        indexing='ij')\n    z = griddata(\n        _np.hstack([xall[:,None], yall[:,None]]),\n        zall, (x, y), method=method)\n    return x, y, z",
    "docstring": "Interpolate unstructured two-dimensional data.\n\n    Parameters\n    ----------\n    xall : ndarray(T)\n        Sample x-coordinates.\n    yall : ndarray(T)\n        Sample y-coordinates.\n    zall : ndarray(T)\n        Sample z-coordinates.\n    nbins : int, optional, default=100\n        Number of histogram bins used in x/y-dimensions.\n    method : str, optional, default='nearest'\n        Assignment method; scipy.interpolate.griddata supports the\n        methods 'nearest', 'linear', and 'cubic'.\n\n    Returns\n    -------\n    x : ndarray(nbins, nbins)\n        The bins' x-coordinates in meshgrid format.\n    y : ndarray(nbins, nbins)\n        The bins' y-coordinates in meshgrid format.\n    z : ndarray(nbins, nbins)\n        Interpolated z-data in meshgrid format."
  },
  {
    "code": "def _onEncoding(self, encString, line, pos, absPosition):\n        self.encoding = Encoding(encString, line, pos, absPosition)",
    "docstring": "Memorizes module encoding"
  },
  {
    "code": "def wait_for_keys(self, *keys, timeout=0):\n        if len(keys) == 1 and _is_iterable(keys[0]):\n            keys = keys[0]\n        return self.listen_until_return(Handler.key_press(keys), timeout=timeout)",
    "docstring": "Waits until one of the specified keys was pressed, and returns \n        which key was pressed.\n\n        :param keys: iterable of integers of pygame-keycodes, or simply \n            multiple keys passed via multiple arguments\n        :type keys: iterable\n        :param timeout: number of seconds to wait till the function returns\n        :type timeout: float\n\n        :returns: The keycode of the pressed key, or None in case of timeout\n        :rtype: int"
  },
  {
    "code": "def tearpage_backend(filename, teared_pages=None):\n    if teared_pages is None:\n        teared_pages = [0]\n    with tempfile.NamedTemporaryFile() as tmp:\n        shutil.copy(filename, tmp.name)\n        try:\n            input_file = PdfFileReader(open(tmp.name, 'rb'))\n        except PdfReadError:\n            fix_pdf(filename, tmp.name)\n            input_file = PdfFileReader(open(tmp.name, 'rb'))\n        num_pages = input_file.getNumPages()\n        output_file = PdfFileWriter()\n        for i in range(num_pages):\n            if i in teared_pages:\n                continue\n            output_file.addPage(input_file.getPage(i))\n        tmp.close()\n        outputStream = open(filename, \"wb\")\n        output_file.write(outputStream)",
    "docstring": "Copy filename to a tempfile, write pages to filename except the teared one.\n\n    ..note ::\n\n        Adapted from sciunto's code, https://github.com/sciunto/tear-pages\n\n    :param filename: PDF filepath\n    :param teared_pages: Numbers of the pages to tear. Default to first page \\\n            only."
  },
  {
    "code": "def is_canonical(version, loosedev=False):\n    if loosedev:\n        return loose440re.match(version) is not None\n    return pep440re.match(version) is not None",
    "docstring": "Return whether or not the version string is canonical according to Pep 440"
  },
  {
    "code": "def __create_preview_object_base(self, dct):\n        if dct.get(\"_id\"):\n            del dct[\"_id\"]\n        preview_object_id = yield self.previews.insert(dct)\n        raise Return(preview_object_id)",
    "docstring": "The starting point for a preview of a future object.\n        This is the object which will have future revisions iterated and applied to.\n\n        :param dict dct: The starting object dictionary\n        :return: The preview object id\n        :rtype: str"
  },
  {
    "code": "def create_spooled_temporary_file(filepath=None, fileobj=None):\n    spooled_file = tempfile.SpooledTemporaryFile(\n        max_size=settings.TMP_FILE_MAX_SIZE,\n        dir=settings.TMP_DIR)\n    if filepath:\n        fileobj = open(filepath, 'r+b')\n    if fileobj is not None:\n        fileobj.seek(0)\n        copyfileobj(fileobj, spooled_file, settings.TMP_FILE_READ_SIZE)\n    return spooled_file",
    "docstring": "Create a spooled temporary file. if ``filepath`` or ``fileobj`` is\n    defined its content will be copied into temporary file.\n\n    :param filepath: Path of input file\n    :type filepath: str\n\n    :param fileobj: Input file object\n    :type fileobj: file\n\n    :returns: Spooled temporary file\n    :rtype: :class:`tempfile.SpooledTemporaryFile`"
  },
  {
    "code": "def padDigitalData(self, dig_data, n):\n        n = int(n)\n        l0 = len(dig_data)\n        if l0 % n == 0:\n            return dig_data\n        else:\n            ladd = n - (l0 % n)\n            dig_data_add = np.zeros(ladd, dtype=\"uint32\")\n            dig_data_add.fill(dig_data[-1])\n            return np.concatenate((dig_data, dig_data_add))",
    "docstring": "Pad dig_data with its last element so that the new array is a\n        multiple of n."
  },
  {
    "code": "def upvotes(self, option):\n    params = join_params(self.parameters, {\"upvotes\": option})\n    return self.__class__(**params)",
    "docstring": "Set whether to filter by a user's upvoted list. Options available are\n    user.ONLY, user.NOT, and None; default is None."
  },
  {
    "code": "def where(self, column_or_label, value_or_predicate=None, other=None):\n        column = self._get_column(column_or_label)\n        if other is not None:\n            assert callable(value_or_predicate), \"Predicate required for 3-arg where\"\n            predicate = value_or_predicate\n            other = self._get_column(other)\n            column = [predicate(y)(x) for x, y in zip(column, other)]\n        elif value_or_predicate is not None:\n            if not callable(value_or_predicate):\n                predicate = _predicates.are.equal_to(value_or_predicate)\n            else:\n                predicate = value_or_predicate\n            column = [predicate(x) for x in column]\n        return self.take(np.nonzero(column)[0])",
    "docstring": "Return a new ``Table`` containing rows where ``value_or_predicate``\n        returns True for values in ``column_or_label``.\n\n        Args:\n            ``column_or_label``: A column of the ``Table`` either as a label\n            (``str``) or an index (``int``). Can also be an array of booleans;\n            only the rows where the array value is ``True`` are kept.\n\n            ``value_or_predicate``: If a function, it is applied to every value\n            in ``column_or_label``. Only the rows where ``value_or_predicate``\n            returns True are kept. If a single value, only the rows where the\n            values in ``column_or_label`` are equal to ``value_or_predicate``\n            are kept.\n\n            ``other``: Optional additional column label for\n            ``value_or_predicate`` to make pairwise comparisons. See the\n            examples below for usage. When ``other`` is supplied,\n            ``value_or_predicate`` must be a callable function.\n\n        Returns:\n            If ``value_or_predicate`` is a function, returns a new ``Table``\n            containing only the rows where ``value_or_predicate(val)`` is True\n            for the ``val``s in ``column_or_label``.\n\n            If ``value_or_predicate`` is a value, returns a new ``Table``\n            containing only the rows where the values in ``column_or_label``\n            are equal to ``value_or_predicate``.\n\n            If ``column_or_label`` is an array of booleans, returns a new\n            ``Table`` containing only the rows where ``column_or_label`` is\n            ``True``.\n\n        >>> marbles = Table().with_columns(\n        ...    \"Color\", make_array(\"Red\", \"Green\", \"Blue\",\n        ...                        \"Red\", \"Green\", \"Green\"),\n        ...    \"Shape\", make_array(\"Round\", \"Rectangular\", \"Rectangular\",\n        ...                        \"Round\", \"Rectangular\", \"Round\"),\n        ...    \"Amount\", make_array(4, 6, 12, 7, 9, 2),\n        ...    \"Price\", make_array(1.30, 1.20, 2.00, 1.75, 0, 3.00))\n\n        >>> marbles\n        Color | Shape       | Amount | Price\n        Red   | Round       | 4      | 1.3\n        Green | Rectangular | 6      | 1.2\n        Blue  | Rectangular | 12     | 2\n        Red   | Round       | 7      | 1.75\n        Green | Rectangular | 9      | 0\n        Green | Round       | 2      | 3\n\n        Use a value to select matching rows\n\n        >>> marbles.where(\"Price\", 1.3)\n        Color | Shape | Amount | Price\n        Red   | Round | 4      | 1.3\n\n        In general, a higher order predicate function such as the functions in\n        ``datascience.predicates.are`` can be used.\n\n        >>> from datascience.predicates import are\n        >>> # equivalent to previous example\n        >>> marbles.where(\"Price\", are.equal_to(1.3))\n        Color | Shape | Amount | Price\n        Red   | Round | 4      | 1.3\n\n        >>> marbles.where(\"Price\", are.above(1.5))\n        Color | Shape       | Amount | Price\n        Blue  | Rectangular | 12     | 2\n        Red   | Round       | 7      | 1.75\n        Green | Round       | 2      | 3\n\n        Use the optional argument ``other`` to apply predicates to compare\n        columns.\n\n        >>> marbles.where(\"Price\", are.above, \"Amount\")\n        Color | Shape | Amount | Price\n        Green | Round | 2      | 3\n\n        >>> marbles.where(\"Price\", are.equal_to, \"Amount\") # empty table\n        Color | Shape | Amount | Price"
  },
  {
    "code": "def every(predicate, *iterables):\n    r\n    try:\n        if len(iterables) == 1: ifilterfalse(predicate, iterables[0]).next()\n        else:                  ifilterfalse(bool, starmap(predicate, izip(*iterables))).next()\n    except StopIteration: return True\n    else: return False",
    "docstring": "r\"\"\"Like `some`, but only returns `True` if all the elements of `iterables`\n    satisfy `predicate`.\n\n    Examples:\n    >>> every(bool, [])\n    True\n    >>> every(bool, [0])\n    False\n    >>> every(bool, [1,1])\n    True\n    >>> every(operator.eq, [1,2,3],[1,2])\n    True\n    >>> every(operator.eq, [1,2,3],[0,2])\n    False"
  },
  {
    "code": "def for_category(self, category, live_only=False):\n        filters = {'tag': category.tag}\n        if live_only:\n            filters.update({'entry__live': True})\n        return self.filter(**filters)",
    "docstring": "Returns queryset of EntryTag instances for specified category.\n\n        :param category: the Category instance.\n        :param live_only: flag to include only \"live\" entries.\n        :rtype: django.db.models.query.QuerySet."
  },
  {
    "code": "def _imagpart(self, f):\n        def f_im(x, **kwargs):\n            result = np.asarray(f(x, **kwargs),\n                                dtype=self.scalar_out_dtype)\n            return result.imag\n        if is_real_dtype(self.out_dtype):\n            return self.zero()\n        else:\n            return self.real_space.element(f_im)",
    "docstring": "Function returning the imaginary part of the result from ``f``."
  },
  {
    "code": "def get_top_artists(self, limit=None, cacheable=True):\n        params = {}\n        if limit:\n            params[\"limit\"] = limit\n        doc = _Request(self, \"chart.getTopArtists\", params).execute(cacheable)\n        return _extract_top_artists(doc, self)",
    "docstring": "Returns the most played artists as a sequence of TopItem objects."
  },
  {
    "code": "def make_directory_if_not_exists(path):\n    try:\n        os.makedirs(path)\n    except OSError, error:\n        if error.errno <> errno.EEXIST:\n            raise error",
    "docstring": "Create the specified path, making all intermediate-level directories\n    needed to contain the leaf directory.  Ignore any error that would\n    occur if the leaf directory already exists.\n\n    @note: all the intermediate-level directories are created with the\n        default mode is 0777 (octal).\n\n    @param path: the path to create.\n\n    @raise OSError: an error that would occur if the path cannot be\n        created."
  },
  {
    "code": "def bulk_record_workunits(self, engine_workunits):\n    for workunit in engine_workunits:\n      duration = workunit['end_timestamp'] - workunit['start_timestamp']\n      span = zipkin_span(\n        service_name=\"pants\",\n        span_name=workunit['name'],\n        duration=duration,\n        span_storage=self.span_storage,\n      )\n      span.zipkin_attrs = ZipkinAttrs(\n        trace_id=self.trace_id,\n        span_id=workunit['span_id'],\n        parent_span_id=workunit.get(\"parent_id\", self.parent_id),\n        flags='0',\n        is_sampled=True,\n      )\n      span.start()\n      span.start_timestamp = workunit['start_timestamp']\n      span.stop()",
    "docstring": "A collection of workunits from v2 engine part"
  },
  {
    "code": "def build_single(mode):\n    if mode == 'force':\n        amode = ['-a']\n    else:\n        amode = []\n    if executable.endswith('uwsgi'):\n        _executable = executable[:-5] + 'python'\n    else:\n        _executable = executable\n    p = subprocess.Popen([_executable, '-m', 'nikola', 'build'] + amode,\n                         stderr=subprocess.PIPE)\n    p.wait()\n    rl = p.stderr.readlines()\n    try:\n        out = ''.join(rl)\n    except TypeError:\n        out = ''.join(l.decode('utf-8') for l in rl)\n    return (p.returncode == 0), out",
    "docstring": "Build, in the single-user mode."
  },
  {
    "code": "def get_assessments_offered_by_search(self, assessment_offered_query, assessment_offered_search):\n        if not self._can('search'):\n            raise PermissionDenied()\n        return self._provider_session.get_assessments_offered_by_search(assessment_offered_query, assessment_offered_search)",
    "docstring": "Pass through to provider AssessmentOfferedSearchSession.get_assessments_offered_by_search"
  },
  {
    "code": "def ToJSonResponse(self, columns_order=None, order_by=(), req_id=0,\n                     response_handler=\"google.visualization.Query.setResponse\"):\n    response_obj = {\n        \"version\": \"0.6\",\n        \"reqId\": str(req_id),\n        \"table\": self._ToJSonObj(columns_order, order_by),\n        \"status\": \"ok\"\n    }\n    encoded_response_str = DataTableJSONEncoder().encode(response_obj)\n    if not isinstance(encoded_response_str, str):\n      encoded_response_str = encoded_response_str.encode(\"utf-8\")\n    return \"%s(%s);\" % (response_handler, encoded_response_str)",
    "docstring": "Writes a table as a JSON response that can be returned as-is to a client.\n\n    This method writes a JSON response to return to a client in response to a\n    Google Visualization API query. This string can be processed by the calling\n    page, and is used to deliver a data table to a visualization hosted on\n    a different page.\n\n    Args:\n      columns_order: Optional. Passed straight to self.ToJSon().\n      order_by: Optional. Passed straight to self.ToJSon().\n      req_id: Optional. The response id, as retrieved by the request.\n      response_handler: Optional. The response handler, as retrieved by the\n          request.\n\n    Returns:\n      A JSON response string to be received by JS the visualization Query\n      object. This response would be translated into a DataTable on the\n      client side.\n      Example result (newlines added for readability):\n       google.visualization.Query.setResponse({\n          'version':'0.6', 'reqId':'0', 'status':'OK',\n          'table': {cols: [...], rows: [...]}});\n\n    Note: The URL returning this string can be used as a data source by Google\n          Visualization Gadgets or from JS code."
  },
  {
    "code": "def to_one_hot(dataY):\n    nc = 1 + np.max(dataY)\n    onehot = [np.zeros(nc, dtype=np.int8) for _ in dataY]\n    for i, j in enumerate(dataY):\n        onehot[i][j] = 1\n    return onehot",
    "docstring": "Convert the vector of labels dataY into one-hot encoding.\n\n    :param dataY: vector of labels\n    :return: one-hot encoded labels"
  },
  {
    "code": "def execfile(fname, variables):\n    with open(fname) as f:\n        code = compile(f.read(), fname, 'exec')\n        exec(code, variables)",
    "docstring": "This is builtin in python2, but we have to roll our own on py3."
  },
  {
    "code": "def SetEventTag(self, event_tag):\n    event_identifier = event_tag.GetEventIdentifier()\n    lookup_key = event_identifier.CopyToString()\n    self._index[lookup_key] = event_tag.GetIdentifier()",
    "docstring": "Sets an event tag in the index.\n\n    Args:\n      event_tag (EventTag): event tag."
  },
  {
    "code": "def inherited_labels(cls):\n        return [scls.__label__ for scls in cls.mro()\n                if hasattr(scls, '__label__') and not hasattr(\n                scls, '__abstract_node__')]",
    "docstring": "Return list of labels from nodes class hierarchy.\n\n        :return: list"
  },
  {
    "code": "def translate(self):\n        value = super().translate()\n        if value is None or (isinstance(value, str) and value.strip() == ''):\n            return None\n        return int(value)",
    "docstring": "Gets the value in the current language, or\n        in the configured fallbck language."
  },
  {
    "code": "def get_absl_log_prefix(record):\n  created_tuple = time.localtime(record.created)\n  created_microsecond = int(record.created % 1.0 * 1e6)\n  critical_prefix = ''\n  level = record.levelno\n  if _is_non_absl_fatal_record(record):\n    level = logging.ERROR\n    critical_prefix = _CRITICAL_PREFIX\n  severity = converter.get_initial_for_level(level)\n  return '%c%02d%02d %02d:%02d:%02d.%06d %5d %s:%d] %s' % (\n      severity,\n      created_tuple.tm_mon,\n      created_tuple.tm_mday,\n      created_tuple.tm_hour,\n      created_tuple.tm_min,\n      created_tuple.tm_sec,\n      created_microsecond,\n      _get_thread_id(),\n      record.filename,\n      record.lineno,\n      critical_prefix)",
    "docstring": "Returns the absl log prefix for the log record.\n\n  Args:\n    record: logging.LogRecord, the record to get prefix for."
  },
  {
    "code": "def userinfo_json(request, user_id):\n    data = {'first_name': '',\n            'last_name': '',\n            'email': '',\n            'slug': '',\n            'bio': '',\n            'phone': '',\n            'is_active': False}\n    try:\n        member = StaffMember.objects.get(pk=user_id)\n        for key in data.keys():\n            if hasattr(member, key):\n                data[key] = getattr(member, key, '')\n    except StaffMember.DoesNotExist:\n        pass\n    return HttpResponse(json.dumps(data),\n                        mimetype='application/json')",
    "docstring": "Return the user's information in a json object"
  },
  {
    "code": "def option(self, *args, **kwargs):\n        args, kwargs = _config_parameter(args, kwargs)\n        return self._click.option(*args, **kwargs)",
    "docstring": "Registers a click.option which falls back to a configmanager Item\n        if user hasn't provided a value in the command line.\n\n        Item must be the last of ``args``.\n\n        Examples::\n\n            config = Config({'greeting': 'Hello'})\n\n            @click.command()\n            @config.click.option('--greeting', config.greeting)\n            def say_hello(greeting):\n                click.echo(greeting)"
  },
  {
    "code": "def white_noise(dur=None, low=-1., high=1.):\n  if dur is None or (isinf(dur) and dur > 0):\n    while True:\n      yield random.uniform(low, high)\n  for x in xrange(rint(dur)):\n    yield random.uniform(low, high)",
    "docstring": "White noise stream generator.\n\n  Parameters\n  ----------\n  dur :\n    Duration, in number of samples; endless if not given (or None).\n  low, high :\n    Lower and higher limits. Defaults to the [-1; 1] range.\n\n  Returns\n  -------\n  Stream yielding random numbers between -1 and 1."
  },
  {
    "code": "def rmse(targets, predictions):\n    r\n    _supervised_evaluation_error_checking(targets, predictions)\n    return _turicreate.extensions._supervised_streaming_evaluator(targets,\n                                       predictions, \"rmse\", {})",
    "docstring": "r\"\"\"\n    Compute the root mean squared error between two SArrays.\n\n    Parameters\n    ----------\n    targets : SArray[float or int]\n        An Sarray of ground truth target values.\n\n    predictions : SArray[float or int]\n        The prediction that corresponds to each target value.\n        This vector must have the same length as ``targets``.\n\n    Returns\n    -------\n    out : float\n        The RMSE between the two SArrays.\n\n    See Also\n    --------\n    max_error\n\n    Notes\n    -----\n    The root mean squared error between two vectors, x and y, is defined as:\n\n    .. math::\n\n        RMSE = \\sqrt{\\frac{1}{N} \\sum_{i=1}^N (x_i - y_i)^2}\n\n    References\n    ----------\n    - `Wikipedia - root-mean-square deviation\n      <http://en.wikipedia.org/wiki/Root-mean-square_deviation>`_\n\n    Examples\n    --------\n    >>> targets = turicreate.SArray([3.14, 0.1, 50, -2.5])\n    >>> predictions = turicreate.SArray([3.1, 0.5, 50.3, -5])\n\n    >>> turicreate.evaluation.rmse(targets, predictions)\n    1.2749117616525465"
  },
  {
    "code": "def verify_edge_segments(edge_infos):\n    if edge_infos is None:\n        return\n    for edge_info in edge_infos:\n        num_segments = len(edge_info)\n        for index in six.moves.xrange(-1, num_segments - 1):\n            index1, start1, end1 = edge_info[index]\n            if not 0.0 <= start1 < end1 <= 1.0:\n                raise ValueError(BAD_SEGMENT_PARAMS, edge_info[index])\n            index2, _, _ = edge_info[index + 1]\n            if index1 == index2:\n                raise ValueError(\n                    SEGMENTS_SAME_EDGE, edge_info[index], edge_info[index + 1]\n                )",
    "docstring": "Verify that the edge segments in an intersection are valid.\n\n    .. note::\n\n       This is a helper used only by :func:`generic_intersect`.\n\n    Args:\n        edge_infos (Optional[list]): List of \"edge info\" lists. Each list\n            represents a curved polygon and contains 3-tuples of edge index,\n            start and end (see the output of :func:`ends_to_curve`).\n\n    Raises:\n        ValueError: If two consecutive edge segments lie on the same edge\n            index.\n        ValueError: If the start and end parameter are \"invalid\" (they should\n            be between 0 and 1 and start should be strictly less than end)."
  },
  {
    "code": "def run(self, func=None):\n        args = self.parser.parse_args()\n        if self.__add_vq is not None and self.__config_logging:\n            self.__config_logging(args)\n        if self.__show_version_func and args.version and callable(self.__show_version_func):\n            self.__show_version_func(self, args)\n        elif args.func is not None:\n            args.func(self, args)\n        elif func is not None:\n            func(self, args)\n        else:\n            self.parser.print_help()",
    "docstring": "Run the app"
  },
  {
    "code": "def dataReceived(self, data):\n        self.bytes_in += (len(data))\n        self.buffer_in = self.buffer_in + data\n        while self.CheckDataReceived():\n            pass",
    "docstring": "Called from Twisted whenever data is received."
  },
  {
    "code": "def has_mixture_channel(val: Any) -> bool:\n    mixture_getter = getattr(val, '_has_mixture_', None)\n    result = NotImplemented if mixture_getter is None else mixture_getter()\n    if result is not NotImplemented:\n        return result\n    result = has_unitary(val)\n    if result is not NotImplemented and result:\n        return result\n    return mixture_channel(val, None) is not None",
    "docstring": "Returns whether the value has a mixture channel representation.\n\n    In contrast to `has_mixture` this method falls back to checking whether\n    the value has a unitary representation via `has_channel`.\n\n    Returns:\n        If `val` has a `_has_mixture_` method and its result is not\n        NotImplemented, that result is returned. Otherwise, if `val` has a\n        `_has_unitary_` method and its results is not NotImplemented, that\n        result is returned. Otherwise, if the value has a `_mixture_` method\n        that is not a non-default value, True is returned. Returns False if none\n        of these functions."
  },
  {
    "code": "def get_compound_pd(self):\n        entry1 = PDEntry(self.entry1.composition, 0)\n        entry2 = PDEntry(self.entry2.composition, 0)\n        cpd = CompoundPhaseDiagram(\n            self.rxn_entries + [entry1, entry2],\n            [Composition(entry1.composition.reduced_formula),\n             Composition(entry2.composition.reduced_formula)],\n            normalize_terminal_compositions=False) \n        return cpd",
    "docstring": "Get the CompoundPhaseDiagram object, which can then be used for\n        plotting.\n\n        Returns:\n            (CompoundPhaseDiagram)"
  },
  {
    "code": "def subpnt(method, target, et, fixref, abcorr, obsrvr):\n    method = stypes.stringToCharP(method)\n    target = stypes.stringToCharP(target)\n    et = ctypes.c_double(et)\n    fixref = stypes.stringToCharP(fixref)\n    abcorr = stypes.stringToCharP(abcorr)\n    obsrvr = stypes.stringToCharP(obsrvr)\n    spoint = stypes.emptyDoubleVector(3)\n    trgepc = ctypes.c_double(0)\n    srfvec = stypes.emptyDoubleVector(3)\n    libspice.subpnt_c(method, target, et, fixref, abcorr, obsrvr, spoint,\n                      ctypes.byref(trgepc), srfvec)\n    return stypes.cVectorToPython(spoint), trgepc.value, stypes.cVectorToPython(\n            srfvec)",
    "docstring": "Compute the rectangular coordinates of the sub-observer point on\n    a target body at a specified epoch, optionally corrected for\n    light time and stellar aberration.\n\n    This routine supersedes :func:`subpt`.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/subpnt_c.html\n\n    :param method: Computation method.\n    :type method: str\n    :param target: Name of target body.\n    :type target: str\n    :param et: Epoch in ephemeris seconds past J2000 TDB.\n    :type et: float\n    :param fixref: Body-fixed, body-centered target body frame.\n    :type fixref: str\n    :param abcorr: Aberration correction.\n    :type abcorr: str\n    :param obsrvr: Name of observing body.\n    :type obsrvr: str\n    :return:\n            Sub-observer point on the target body,\n            Sub-observer point epoch,\n            Vector from observer to sub-observer point.\n    :rtype: tuple"
  },
  {
    "code": "def OnPrintPreview(self, event):\n        print_area = self._get_print_area()\n        print_data = self.main_window.print_data\n        self.main_window.actions.print_preview(print_area, print_data)",
    "docstring": "Print preview handler"
  },
  {
    "code": "def probe_async(self, callback):\n        topics = MQTTTopicValidator(self.prefix)\n        self.client.publish(topics.probe, {'type': 'command', 'operation': 'probe', 'client': self.name})\n        callback(self.id, True, None)",
    "docstring": "Probe for visible devices connected to this DeviceAdapter.\n\n        Args:\n            callback (callable): A callback for when the probe operation has completed.\n                callback should have signature callback(adapter_id, success, failure_reason) where:\n                    success: bool\n                    failure_reason: None if success is True, otherwise a reason for why we could not probe"
  },
  {
    "code": "def proxy(host='localhost', port=4304, flags=0, persistent=False,\n          verbose=False, ):\n    try:\n        gai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM,\n                                 socket.IPPROTO_TCP)\n    except socket.gaierror as err:\n        raise ConnError(*err.args)\n    assert gai\n    for (family, _type, _proto, _, sockaddr) in gai:\n        assert _type is socket.SOCK_STREAM and _proto is socket.IPPROTO_TCP\n        owp = _Proxy(family, sockaddr, flags, verbose)\n        try:\n            owp.ping()\n        except ConnError as err:\n            lasterr = err.args\n            continue\n        else:\n            break\n    else:\n        raise ConnError(*lasterr)\n    owp._init_errcodes()\n    if persistent:\n        owp = clone(owp, persistent=True)\n    assert not isinstance(owp, _PersistentProxy) or owp.conn is None\n    return owp",
    "docstring": "factory function that returns a proxy object for an owserver at\n    host, port."
  },
  {
    "code": "def parse(cls, uri):\n\t\turi_components = urlsplit(uri)\n\t\tadapter_fn = lambda x: x if x is not None and (isinstance(x, str) is False or len(x)) > 0 else None\n\t\treturn cls(\n\t\t\tscheme=adapter_fn(uri_components.scheme),\n\t\t\tusername=adapter_fn(uri_components.username),\n\t\t\tpassword=adapter_fn(uri_components.password),\n\t\t\thostname=adapter_fn(uri_components.hostname),\n\t\t\tport=adapter_fn(uri_components.port),\n\t\t\tpath=adapter_fn(uri_components.path),\n\t\t\tquery=adapter_fn(uri_components.query),\n\t\t\tfragment=adapter_fn(uri_components.fragment),\n\t\t)",
    "docstring": "Parse URI-string and return WURI object\n\n\t\t:param uri: string to parse\n\t\t:return: WURI"
  },
  {
    "code": "def _allow_custom_expire(self, load):\n        expire_override = self.opts.get('token_expire_user_override', False)\n        if expire_override is True:\n            return True\n        if isinstance(expire_override, collections.Mapping):\n            expire_whitelist = expire_override.get(load['eauth'], [])\n            if isinstance(expire_whitelist, collections.Iterable):\n                if load.get('username') in expire_whitelist:\n                    return True\n        return False",
    "docstring": "Return bool if requesting user is allowed to set custom expire"
  },
  {
    "code": "def plural(self, text, count=None):\n        pre, word, post = self.partition_word(text)\n        if not word:\n            return text\n        plural = self.postprocess(\n            word,\n            self._pl_special_adjective(word, count)\n            or self._pl_special_verb(word, count)\n            or self._plnoun(word, count),\n        )\n        return \"{}{}{}\".format(pre, plural, post)",
    "docstring": "Return the plural of text.\n\n        If count supplied, then return text if count is one of:\n            1, a, an, one, each, every, this, that\n        otherwise return the plural.\n\n        Whitespace at the start and end is preserved."
  },
  {
    "code": "def get(self, *args, **kwargs):\n        if not mqueue.qsize():\n            return None\n        message_data, content_type, content_encoding = mqueue.get()\n        return self.Message(backend=self, body=message_data,\n                       content_type=content_type,\n                       content_encoding=content_encoding)",
    "docstring": "Get the next waiting message from the queue.\n\n        :returns: A :class:`Message` instance, or ``None`` if there is\n            no messages waiting."
  },
  {
    "code": "def find(name):\n    if op.exists(name):\n        return name\n    path = op.dirname(__file__) or '.'\n    paths = [path] + config['include_path']\n    for path in paths:\n        filename = op.abspath(op.join(path, name))\n        if op.exists(filename):\n            return filename\n        for d in os.listdir(path):\n            fullpath = op.abspath(op.join(path, d))\n            if op.isdir(fullpath):\n                filename = op.abspath(op.join(fullpath, name))\n                if op.exists(filename):\n                    return filename\n    return None",
    "docstring": "Locate a filename into the shader library."
  },
  {
    "code": "def ref(self, orm_classpath, cls_pk=None):\n        orm_module, orm_class = get_objects(orm_classpath)\n        q = orm_class.query\n        if cls_pk:\n            found = False\n            for fn, f in orm_class.schema.fields.items():\n                cls_ref_s = f.schema\n                if cls_ref_s and self.schema == cls_ref_s:\n                    q.is_field(fn, cls_pk)\n                    found = True\n                    break\n            if not found:\n                raise ValueError(\"Did not find a foreign key field for [{}] in [{}]\".format(\n                    self.orm_class.table_name,\n                    orm_class.table_name,\n                ))\n        return q",
    "docstring": "takes a classpath to allow query-ing from another Orm class\n\n        the reason why it takes string paths is to avoid infinite recursion import \n        problems because an orm class from module A might have a ref from module B\n        and sometimes it is handy to have module B be able to get the objects from\n        module A that correspond to the object in module B, but you can't import\n        module A into module B because module B already imports module A.\n\n        orm_classpath -- string -- a full python class path (eg, foo.bar.Che)\n        cls_pk -- mixed -- automatically set the where field of orm_classpath \n            that references self.orm_class to the value in cls_pk if present\n        return -- Query()"
  },
  {
    "code": "def get_planet(planet_id):\n    result = _get(planet_id, settings.PLANETS)\n    return Planet(result.content)",
    "docstring": "Return a single planet"
  },
  {
    "code": "def close(self):\n        try:\n            self.dut.close()\n        except Exception:\n            logging.warning('Closing DUT was not successful')\n        else:\n            logging.debug('Closed DUT')",
    "docstring": "Releasing hardware resources."
  },
  {
    "code": "def set(self, name, value, overwrite=False):\n        if hasattr(self, name):\n            if overwrite:\n                setattr(self, name, value)\n            else:\n                self._log.warning(\"Configuration parameter %s exists and overwrite not allowed\" % name)\n                raise Exception(\"Configuration parameter %s exists and overwrite not allowed\" % name)\n        else:\n            setattr(self, name, value)\n        return getattr(self, name)",
    "docstring": "Sets a new value for a given configuration parameter.\n\n        If it already exists, an Exception is thrown.\n        To overwrite an existing value, set overwrite to True.\n\n        :param name: Unique name of the parameter\n        :param value: Value of the configuration parameter\n        :param overwrite: If true, an existing parameter of *name* gets overwritten without warning or exception.\n        :type overwrite: boolean"
  },
  {
    "code": "def output(self, value, normal=False, color=None, error=False,\n               arrow=False, indent=None):\n        if error and value and (normal or self.verbose):\n            return self._print(value, color='red', indent=indent)\n        if self.verbose or normal:\n            return self._print(value, color, arrow, indent)\n        return",
    "docstring": "Handles verbosity of this calls.\n        if priority is set to 1, the value is printed\n\n        if class instance verbose is True, the value is printed\n\n        :param value:\n            a string representing the message to be printed\n        :type value:\n            String\n        :param normal:\n            if set to true the message is always printed, otherwise it is only shown if verbosity is set\n        :type normal:\n            boolean\n        :param color:\n            The color of the message, choices: 'red', 'green', 'blue'\n        :type normal:\n            String\n        :param error:\n            if set to true the message appears in red\n        :type error:\n            Boolean\n        :param arrow:\n            if set to true an arrow appears before the message\n        :type arrow:\n            Boolean\n        :param indent:\n            indents the message based on the number provided\n        :type indent:\n            Boolean\n\n        :returns:\n            void"
  },
  {
    "code": "def _set_status_data(self, userdata):\n        self._on_mask = userdata['d3']\n        self._off_mask = userdata['d4']\n        self._x10_house_code = userdata['d5']\n        self._x10_unit = userdata['d6']\n        self._ramp_rate = userdata['d7']\n        self._on_level = userdata['d8']\n        self._led_brightness = userdata['d9']\n        self._non_toggle_mask = userdata['d10']\n        self._led_bit_mask = userdata['d11']\n        self._x10_all_bit_mask = userdata['d12']\n        self._on_off_bit_mask = userdata['d13']\n        self._trigger_group_bit_mask = userdata['d14']",
    "docstring": "Set status properties from userdata response.\n\n        Response values:\n            d3:  On Mask\n            d4:  Off Mask\n            d5:  X10 House Code\n            d6:  X10 Unit\n            d7:  Ramp Rate\n            d8:  On-Level\n            d9:  LED Brightness\n            d10: Non-Toggle Mask\n            d11: LED Bit Mask\n            d12: X10 ALL Bit Mask\n            d13: On/Off Bit Mask"
  },
  {
    "code": "def calculate_manual_reading(basic_data: BasicMeterData) -> Reading:\n    t_start = basic_data.previous_register_read_datetime\n    t_end = basic_data.current_register_read_datetime\n    read_start = basic_data.previous_register_read\n    read_end = basic_data.current_register_read\n    value = basic_data.quantity\n    uom = basic_data.uom\n    quality_method = basic_data.current_quality_method\n    return Reading(t_start, t_end, value, uom, quality_method, \"\", \"\",\n                      read_start, read_end)",
    "docstring": "Calculate the interval between two manual readings"
  },
  {
    "code": "def list_rocs_files(url=ROCS_URL):\n    soup = BeautifulSoup(get(url))\n    if not url.endswith('/'):\n        url += '/'\n    files = []\n    for elem in soup.findAll('a'):\n        if elem['href'].startswith('?'):\n            continue\n        if elem.string.lower() == 'parent directory':\n            continue\n        files.append(url + elem['href'])\n    return files",
    "docstring": "Gets the contents of the given url."
  },
  {
    "code": "def _git_diff(self):\n        if self._diff_dict is None:\n            result_dict = dict()\n            for diff_str in self._get_included_diff_results():\n                diff_dict = self._parse_diff_str(diff_str)\n                for src_path in diff_dict.keys():\n                    if self._is_path_excluded(src_path):\n                        continue\n                    root, extension = os.path.splitext(src_path)\n                    extension = extension[1:].lower()\n                    if not self._supported_extensions or extension in self._supported_extensions:\n                        added_lines, deleted_lines = diff_dict[src_path]\n                        result_dict[src_path] = [\n                            line for line in result_dict.get(src_path, [])\n                            if not line in deleted_lines\n                        ] + added_lines\n            for (src_path, lines) in result_dict.items():\n                result_dict[src_path] = self._unique_ordered_lines(lines)\n            self._diff_dict = result_dict\n        return self._diff_dict",
    "docstring": "Run `git diff` and returns a dict in which the keys\n        are changed file paths and the values are lists of\n        line numbers.\n\n        Guarantees that each line number within a file\n        is unique (no repeats) and in ascending order.\n\n        Returns a cached result if called multiple times.\n\n        Raises a GitDiffError if `git diff` has an error."
  },
  {
    "code": "def environ_setenv(self, tag, data):\n        environ = data.get('environ', None)\n        if environ is None:\n            return False\n        false_unsets = data.get('false_unsets', False)\n        clear_all = data.get('clear_all', False)\n        import salt.modules.environ as mod_environ\n        return mod_environ.setenv(environ, false_unsets, clear_all)",
    "docstring": "Set the salt-minion main process environment according to\n        the data contained in the minion event data"
  },
  {
    "code": "def _create_event(self, event_state, event_type, event_value,\n                      proc_list, proc_desc, peak_time):\n        if event_state == \"WARNING\" or event_state == \"CRITICAL\":\n            self.set_process_sort(event_type)\n            item = [\n                time.mktime(datetime.now().timetuple()),\n                -1,\n                event_state,\n                event_type,\n                event_value,\n                event_value,\n                event_value,\n                event_value,\n                1,\n                [],\n                proc_desc,\n                glances_processes.sort_key]\n            self.events_list.insert(0, item)\n            if self.len() > self.events_max:\n                self.events_list.pop()\n            return True\n        else:\n            return False",
    "docstring": "Add a new item in the log list.\n\n        Item is added only if the criticity (event_state) is WARNING or CRITICAL."
  },
  {
    "code": "def patchURL(self, url, headers, body):\n        return self._load_resource(\"PATCH\", url, headers, body)",
    "docstring": "Request a URL using the HTTP method PATCH."
  },
  {
    "code": "def predict_is(self, h):\n        result = pd.DataFrame([self.run(h=h)[2]]).T  \n        result.index = self.index[-h:]\n        return result",
    "docstring": "Outputs predictions for the Aggregate algorithm on the in-sample data\n\n        Parameters\n        ----------\n        h : int\n            How many steps to run the aggregating algorithm on \n\n        Returns\n        ----------\n        - pd.DataFrame of ensemble predictions"
  },
  {
    "code": "def start_tasks(self):\n        while self.tasks_at_once > len(self.pending_results) and self._has_more_tasks():\n            task, parent_result = self.tasks.popleft()\n            self.execute_task(task, parent_result)",
    "docstring": "Start however many tasks we can based on our limits and what we have left to finish."
  },
  {
    "code": "def re_evaluate(local_dict=None):\n    try:\n        compiled_ex = _numexpr_last['ex']\n    except KeyError:\n        raise RuntimeError(\"not a previous evaluate() execution found\")\n    argnames = _numexpr_last['argnames']\n    args = getArguments(argnames, local_dict)\n    kwargs = _numexpr_last['kwargs']\n    with evaluate_lock:\n        return compiled_ex(*args, **kwargs)",
    "docstring": "Re-evaluate the previous executed array expression without any check.\n\n    This is meant for accelerating loops that are re-evaluating the same\n    expression repeatedly without changing anything else than the operands.\n    If unsure, use evaluate() which is safer.\n\n    Parameters\n    ----------\n\n    local_dict : dictionary, optional\n        A dictionary that replaces the local operands in current frame."
  },
  {
    "code": "def thread_pool(*workers, results=None, end_of_queue=EndOfQueue):\n    if results is None:\n        results = Queue(end_of_queue=end_of_queue)\n    count = thread_counter(results.close)\n    @pull\n    def thread_pool_results(source):\n        for worker in workers:\n            t = threading.Thread(\n                target=count(patch),\n                args=(pull(source) >> worker, results.sink),\n                daemon=True)\n            t.start()\n        yield from results.source()\n    return thread_pool_results",
    "docstring": "Returns a |pull| object, call it ``r``, starting a thread for each given\n    worker.  Each thread pulls from the source that ``r`` is connected to, and\n    the returned results are pushed to a |Queue|.  ``r`` yields from the other\n    end of the same |Queue|.\n\n    The target function for each thread is |patch|, which can be stopped by\n    exhausting the source.\n\n    If all threads have ended, the result queue receives end-of-queue.\n\n    :param results: If results should go somewhere else than a newly\n        constructed |Queue|, a different |Connection| object can be given.\n    :type results: |Connection|\n\n    :param end_of_queue: end-of-queue signal object passed on to the creation\n        of the |Queue| object.\n\n    :rtype: |pull|"
  },
  {
    "code": "def get_value_as_list(self, dictionary, key):\n        if key not in dictionary:\n            return None\n        value = dictionary[key]\n        if not isinstance(value, list):\n            return [value]\n        else:\n            return value",
    "docstring": "Helper function to check and convert a value to list.\n\n        Helper function to check and convert a value to json list.\n        This helps the ribcl data to be generalized across the servers.\n\n        :param dictionary: a dictionary to check in if key is present.\n        :param key: key to be checked if thats present in the given dictionary.\n\n        :returns the data converted to a list."
  },
  {
    "code": "def _get_future_tasks(self):\n        self.alerts = {}\n        now = std_now()\n        for task in objectmodels['task'].find({'alert_time': {'$gt': now}}):\n            self.alerts[task.alert_time] = task\n        self.log('Found', len(self.alerts), 'future tasks')",
    "docstring": "Assemble a list of future alerts"
  },
  {
    "code": "def getAvg(self,varname,**kwds):\n        if hasattr(self,varname):\n            return np.mean(getattr(self,varname),**kwds)\n        else:\n            return np.nan",
    "docstring": "Calculates the average of an attribute of this instance.  Returns NaN if no such attribute.\n\n        Parameters\n        ----------\n        varname : string\n            The name of the attribute whose average is to be calculated.  This attribute must be an\n            np.array or other class compatible with np.mean.\n\n        Returns\n        -------\n        avg : float or np.array\n            The average of this attribute.  Might be an array if the axis keyword is passed."
  },
  {
    "code": "def parse_yaml(self, y):\n        self._targets = []\n        if 'targets' in y:\n            for t in y['targets']:\n                if 'waitTime' in t['condition']:\n                    new_target = WaitTime()\n                elif 'preceding' in t['condition']:\n                    new_target = Preceding()\n                else:\n                    new_target = Condition()\n                new_target.parse_yaml(t)\n                self._targets.append(new_target)\n        return self",
    "docstring": "Parse a YAML speficication of a message sending object into this\n        object."
  },
  {
    "code": "def create_prefix_dir(self, path, fmt):\n        create_prefix_dir(self._get_os_path(path.strip('/')), fmt)",
    "docstring": "Create the prefix dir, if missing"
  },
  {
    "code": "def transform_cur_commands_interactive(_, **kwargs):\n    event_payload = kwargs.get('event_payload', {})\n    cur_commands = event_payload.get('text', '').split(' ')\n    _transform_cur_commands(cur_commands)\n    event_payload.update({\n        'text': ' '.join(cur_commands)\n    })",
    "docstring": "Transform any aliases in current commands in interactive into their respective commands."
  },
  {
    "code": "def alias_package(package, alias, extra_modules={}):\n    path = package.__path__\n    alias_prefix = alias + '.'\n    prefix = package.__name__ + '.'\n    for _, name, _ in pkgutil.walk_packages(path, prefix):\n        if name.startswith('tango.databaseds.db_access.'):\n            continue\n        try:\n            if name not in sys.modules:\n                __import__(name)\n        except ImportError:\n            continue\n        alias_name = name.replace(prefix, alias_prefix)\n        sys.modules[alias_name] = sys.modules[name]\n    for key, value in extra_modules.items():\n        name = prefix + value\n        if name not in sys.modules:\n            __import__(name)\n        if not hasattr(package, key):\n            setattr(package, key, sys.modules[name])\n        sys.modules[alias_prefix + key] = sys.modules[name]\n    sys.modules[alias] = sys.modules[package.__name__]",
    "docstring": "Alias a python package properly.\n\n    It ensures that modules are not duplicated by trying\n    to import and alias all the submodules recursively."
  },
  {
    "code": "def _check(self, args):\n        if sum(bool(args[arg]) for arg in self._mapping) > 1:\n            raise DocoptExit(_('These options are mutually exclusive: {0}',\n                               ', '.join(self._mapping)))",
    "docstring": "Exit in case of multiple exclusive arguments."
  },
  {
    "code": "def get_snapshots(self,**kwargs):\n        commits = self.repository.get_commits(**kwargs)\n        snapshots = []\n        for commit in commits:\n            for key in ('committer_date','author_date'):\n                commit[key] = datetime.datetime.fromtimestamp(commit[key+'_ts'])\n            snapshot = GitSnapshot(commit)\n            hasher = Hasher()\n            hasher.add(snapshot.sha)\n            snapshot.hash = hasher.digest.hexdigest()\n            snapshot.project = self.project\n            snapshot.pk = uuid.uuid4().hex\n            snapshots.append(snapshot)\n        return snapshots",
    "docstring": "Returns a list of snapshots in a given repository."
  },
  {
    "code": "def in_query(expression):\n    def _in(index, expression=expression):\n        ev = expression() if callable(expression) else expression\n        try:\n            iter(ev)\n        except TypeError:\n            raise AttributeError('$in argument must be an iterable!')\n        hashed_ev = [index.get_hash_for(v) for v in ev]\n        store_keys = set()\n        for value in hashed_ev:\n            store_keys |= set(index.get_keys_for(value))\n        return list(store_keys)\n    return _in",
    "docstring": "Match any of the values that exist in an array specified in query."
  },
  {
    "code": "def call(method, *args, **kwargs):\n    kwargs = clean_kwargs(**kwargs)\n    return getattr(pyeapi_device['connection'], method)(*args, **kwargs)",
    "docstring": "Calls an arbitrary pyeapi method."
  },
  {
    "code": "def resizeEvent(self, event):\r\n        curr_item = self.currentItem()\r\n        self.closePersistentEditor(curr_item)\r\n        super(XMultiTagEdit, self).resizeEvent(event)",
    "docstring": "Overloads the resize event to control if we are still editing.\r\n        \r\n        If we are resizing, then we are no longer editing."
  },
  {
    "code": "def server_session(model=None, session_id=None, url=\"default\", relative_urls=False, resources=\"default\"):\n    if session_id is None:\n        raise ValueError(\"Must supply a session_id\")\n    url = _clean_url(url)\n    app_path = _get_app_path(url)\n    elementid = make_id()\n    modelid = \"\" if model is None else model.id\n    src_path = _src_path(url, elementid)\n    src_path += _process_app_path(app_path)\n    src_path += _process_relative_urls(relative_urls, url)\n    src_path += _process_session_id(session_id)\n    src_path += _process_resources(resources)\n    tag = AUTOLOAD_TAG.render(\n        src_path  = src_path,\n        app_path  = app_path,\n        elementid = elementid,\n        modelid   = modelid,\n    )\n    return encode_utf8(tag)",
    "docstring": "Return a script tag that embeds content from a specific existing session on\n    a Bokeh server.\n\n    This function is typically only useful for serving from a a specific session\n    that was previously created using the ``bokeh.client`` API.\n\n    Bokeh apps embedded using these methods will NOT set the browser window title.\n\n    .. note::\n        Typically you will not want to save or re-use the output of this\n        function for different or multiple page loads.\n\n    Args:\n        model (Model or None, optional) :\n            The object to render from the session, or None. (default: None)\n\n            If None, the entire document will be rendered.\n\n        session_id (str) :\n            A server session ID\n\n        url (str, optional) :\n            A URL to a Bokeh application on a Bokeh server (default: \"default\")\n\n            If ``\"default\"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used.\n\n        relative_urls (bool, optional) :\n            Whether to use relative URLs for resources.\n\n            If ``True`` the links generated for resources such a BokehJS\n            JavaScript and CSS will be relative links.\n\n            This should normally be set to ``False``, but must be set to\n            ``True`` in situations where only relative URLs will work. E.g.\n            when running the Bokeh behind reverse-proxies under certain\n            configurations\n\n        resources (str) : A string specifying what resources need to be loaded\n            along with the document.\n\n            If ``default`` then the default JS/CSS bokeh files will be loaded.\n\n            If None then none of the resource files will be loaded. This is\n            useful if you prefer to serve those resource files via other means\n            (e.g. from a caching server). Be careful, however, that the resource\n            files you'll load separately are of the same version as that of the\n            server's, otherwise the rendering may not work correctly.\n\n    Returns:\n        A ``<script>`` tag that will embed content from a Bokeh Server.\n\n        .. warning::\n            It is typically a bad idea to re-use the same ``session_id`` for\n            every page load. This is likely to create scalability and security\n            problems, and will cause \"shared Google doc\" behavior, which is\n            probably not desired."
  },
  {
    "code": "def string_asset(class_obj: type) -> type:\n    assert isinstance(class_obj, type), \"class_obj is not a Class\"\n    global _string_asset_resource_type\n    _string_asset_resource_type = class_obj\n    return class_obj",
    "docstring": "Decorator to annotate the StringAsset class. Registers the decorated class\n    as the StringAsset known type."
  },
  {
    "code": "def from_custom_template(cls, searchpath, name):\n        loader = ChoiceLoader([\n            FileSystemLoader(searchpath),\n            cls.loader,\n        ])\n        class MyStyler(cls):\n            env = Environment(loader=loader)\n            template = env.get_template(name)\n        return MyStyler",
    "docstring": "Factory function for creating a subclass of ``Styler``\n        with a custom template and Jinja environment.\n\n        Parameters\n        ----------\n        searchpath : str or list\n            Path or paths of directories containing the templates\n        name : str\n            Name of your custom template to use for rendering\n\n        Returns\n        -------\n        MyStyler : subclass of Styler\n            Has the correct ``env`` and ``template`` class attributes set."
  },
  {
    "code": "def maybe_pause_consumer(self):\n        if self.load >= 1.0:\n            if self._consumer is not None and not self._consumer.is_paused:\n                _LOGGER.debug(\"Message backlog over load at %.2f, pausing.\", self.load)\n                self._consumer.pause()",
    "docstring": "Check the current load and pause the consumer if needed."
  },
  {
    "code": "def unique(iterable, key=None):\n    ensure_iterable(iterable)\n    key = hash if key is None else ensure_callable(key)\n    def generator():\n        seen = set()\n        for elem in iterable:\n            k = key(elem)\n            if k not in seen:\n                seen.add(k)\n                yield elem\n    return generator()",
    "docstring": "Removes duplicates from given iterable, using given key as criterion.\n\n    :param key: Key function which returns a hashable,\n                uniquely identifying an object.\n\n    :return: Iterable with duplicates removed"
  },
  {
    "code": "def _bsd_addif(br, iface):\n    kernel = __grains__['kernel']\n    if kernel == 'NetBSD':\n        cmd = _tool_path('brconfig')\n        brcmd = 'add'\n    else:\n        cmd = _tool_path('ifconfig')\n        brcmd = 'addem'\n    if not br or not iface:\n        return False\n    return __salt__['cmd.run']('{0} {1} {2} {3}'.format(cmd, br, brcmd, iface),\n                               python_shell=False)",
    "docstring": "Internal, adds an interface to a bridge"
  },
  {
    "code": "def special_validate(data, schema):\n    jsonschema.validate(data, schema)\n    data['special'] = str(data['name'] == 'Garfield').lower()",
    "docstring": "Custom validation function which inserts an special flag depending\n    on the cat's name"
  },
  {
    "code": "def resolve_response_data(head_key, data_key, data):\n        new_data = []\n        if isinstance(data, list):\n            for data_row in data:\n                if head_key in data_row and data_key in data_row[head_key]:\n                    if isinstance(data_row[head_key][data_key], list):\n                        new_data += data_row[head_key][data_key]\n                    else:\n                        new_data.append(data_row[head_key][data_key])\n                elif data_key in data_row:\n                    return data_row[data_key]\n        else:\n            if head_key in data and data_key in data[head_key]:\n                new_data += data[head_key][data_key]\n            elif data_key in data:\n                    return data[data_key]\n        return new_data",
    "docstring": "Resolves the responses you get from billomat\n        If you have done a get_one_element request then you will get a dictionary\n        If you have done a get_all_elements request then you will get a list with all elements in it\n\n        :param head_key: the head key e.g: CLIENTS\n        :param data_key: the data key e.g: CLIENT\n        :param data: the responses you got\n        :return: dict or list"
  },
  {
    "code": "def update(self, version, reason=None):\n        _check_version_format(version)\n        return self.collection.update({'_id': 'manifest'}, {\n            '$set': {'version': version},\n            '$push': {'history': {\n                'timestamp': datetime.utcnow(), 'version': version,\n                'reason': reason}}\n        })",
    "docstring": "Modify the datamodel's manifest\n\n        :param version: New version of the manifest\n        :param reason: Optional reason of the update (i.g. \"Update from x.y.z\")"
  },
  {
    "code": "def get_project(self, project_id):\n        try:\n            UUID(project_id, version=4)\n        except ValueError:\n            raise aiohttp.web.HTTPBadRequest(text=\"Project ID {} is not a valid UUID\".format(project_id))\n        if project_id not in self._projects:\n            raise aiohttp.web.HTTPNotFound(text=\"Project ID {} doesn't exist\".format(project_id))\n        return self._projects[project_id]",
    "docstring": "Returns a Project instance.\n\n        :param project_id: Project identifier\n\n        :returns: Project instance"
  },
  {
    "code": "def getKeplerFov(fieldnum):\n    info = getFieldInfo(fieldnum)\n    ra, dec, scRoll = info[\"ra\"], info[\"dec\"], info[\"roll\"]\n    fovRoll = fov.getFovAngleFromSpacecraftRoll(scRoll)\n    brokenChannels = [5, 6, 7, 8,  17, 18, 19, 20]\n    if fieldnum > 10:\n        brokenChannels.extend([9, 10, 11, 12])\n    if fieldnum == 1000:\n        brokenChannels = []\n    return fov.KeplerFov(ra, dec, fovRoll, brokenChannels=brokenChannels)",
    "docstring": "Returns a `fov.KeplerFov` object for a given campaign.\n\n    Parameters\n    ----------\n    fieldnum : int\n        K2 Campaign number.\n\n    Returns\n    -------\n    fovobj : `fov.KeplerFov` object\n        Details the footprint of the requested K2 campaign."
  },
  {
    "code": "def make_parser():\n    parser = ArgumentParser(\n        description='Start an IRC bot instance from the command line.',\n        formatter_class=ArgumentDefaultsHelpFormatter,\n    )\n    parser.add_argument(\n        '-v', '--version',\n        action='version',\n        version='{0} v{1}'.format(NAME, VERSION)\n    )\n    parser.add_argument(\n        '-s', '--server',\n        metavar='HOST',\n        required=True,\n        help='the host to connect to'\n    )\n    parser.add_argument(\n        '-p', '--port',\n        metavar='PORT',\n        type=int,\n        default=6667,\n        help='the port the server is listening on'\n    )\n    parser.add_argument(\n        '-n', '--nick',\n        metavar='NAME',\n        required=True,\n        help=\"the bot's nickname\"\n    )\n    parser.add_argument(\n        '-N', '--name',\n        metavar='NAME',\n        default=NAME,\n        help=\"the bot's real name\"\n    )\n    parser.add_argument(\n        '-c', '--channels',\n        metavar='CHAN',\n        nargs='*',\n        help='join this channel upon connection'\n    )\n    parser.add_argument(\n        '-l', '--log',\n        metavar='LEVEL',\n        default='INFO',\n        help='minimal level for displayed logging messages'\n    )\n    parser.add_argument(\n        '-S', '--ssl',\n        action='store_true',\n        help='connect to the server using SSL'\n    )\n    return parser",
    "docstring": "Creates an argument parser configured with options to run a bot\n    from the command line.\n\n    :return: configured argument parser\n    :rtype: :class:`argparse.ArgumentParser`"
  },
  {
    "code": "def add_shellwidget(self, shellwidget):\r\n        shellwidget_id = id(shellwidget)\r\n        if shellwidget_id not in self.shellwidgets:\r\n            self.options_button.setVisible(True)\r\n            nsb = NamespaceBrowser(self, options_button=self.options_button)\r\n            nsb.set_shellwidget(shellwidget)\r\n            nsb.setup(**self.get_settings())\r\n            nsb.sig_option_changed.connect(self.change_option)\r\n            nsb.sig_free_memory.connect(self.free_memory)\r\n            self.add_widget(nsb)\r\n            self.shellwidgets[shellwidget_id] = nsb\r\n            self.set_shellwidget_from_id(shellwidget_id)\r\n            return nsb",
    "docstring": "Register shell with variable explorer.\r\n\r\n        This function opens a new NamespaceBrowser for browsing the variables\r\n        in the shell."
  },
  {
    "code": "def chain_tasks(tasks):\n    if tasks:\n        previous_task = None\n        for task in tasks:\n            if task is not None:\n                if previous_task is not None:\n                    task.set_run_after(previous_task)\n                previous_task = task\n    return tasks",
    "docstring": "Chain given tasks. Set each task to run after its previous task.\n\n    :param tasks: Tasks list.\n\n    :return: Given tasks list."
  },
  {
    "code": "async def dict(self, full):\n        node = await self.open(full)\n        return await HiveDict.anit(self, node)",
    "docstring": "Open a HiveDict at the given full path."
  },
  {
    "code": "def write_metadata(self, key, values):\n        values = Series(values)\n        self.parent.put(self._get_metadata_path(key), values, format='table',\n                        encoding=self.encoding, errors=self.errors,\n                        nan_rep=self.nan_rep)",
    "docstring": "write out a meta data array to the key as a fixed-format Series\n\n        Parameters\n        ----------\n        key : string\n        values : ndarray"
  },
  {
    "code": "def cancel(self, request, *args, **kwargs):\n        status = self.get_object()\n        status.cancel()\n        serializer = StatusSerializer(status, context={'request': request})\n        return Response(serializer.data)",
    "docstring": "Cancel the task associated with the specified status record.\n\n        Arguments:\n            request (Request): A POST including a task status record ID\n\n        Returns\n        -------\n            Response: A JSON response indicating whether the cancellation succeeded or not"
  },
  {
    "code": "def write(s, path, encoding=\"utf-8\"):\n    is_gzip = is_gzip_file(path)\n    with open(path, \"wb\") as f:\n        if is_gzip:\n            f.write(zlib.compress(s.encode(encoding)))\n        else:\n            f.write(s.encode(encoding))",
    "docstring": "Write string to text file."
  },
  {
    "code": "def make_timestamp_columns():\n    return (\n        Column('created_at', DateTime, default=func.utcnow(), nullable=False),\n        Column('updated_at', DateTime, default=func.utcnow(), onupdate=func.utcnow(), nullable=False),\n    )",
    "docstring": "Return two columns, created_at and updated_at, with appropriate defaults"
  },
  {
    "code": "def description(filename):\n    with open(filename) as fp:\n        for lineno, line in enumerate(fp):\n            if lineno < 3:\n                continue\n            line = line.strip()\n            if len(line) > 0:\n                return line",
    "docstring": "Provide a short description."
  },
  {
    "code": "def get_rows(self):\n        table = self.soup.find_all('tr')[1:-3]\n        return [row for row in table if row.contents[3].string]",
    "docstring": "Get the rows from a broadcast ratings chart"
  },
  {
    "code": "def __process_gprest_response(self, r=None, restType='GET'):\r\n        if r is None:\r\n            logging.info('No response for REST '+restType+' request')\r\n            return None\r\n        httpStatus = r.status_code\r\n        logging.info('HTTP status code: %s', httpStatus)\r\n        if httpStatus == requests.codes.ok or \\\r\n            httpStatus == requests.codes.created:\r\n            jsonR = r.json()\r\n            if jsonR:\r\n                statusStr = 'REST response status: %s' % \\\r\n                    jsonR.get(self.__RESPONSE_STATUS_KEY)\r\n                msgStr = 'REST response message: %s' % \\\r\n                    jsonR.get(self.__RESPONSE_MESSAGE_KEY)\r\n                logging.info(statusStr)\r\n                logging.info(msgStr)\r\n                return jsonR\r\n            else:\r\n                logging.warning('Unable to parse JSON body.')\r\n                logging.warning(r.text)\r\n                return None\r\n        logging.warning('Invalid HTTP status code.')\r\n        logging.warning(r.text)\r\n        return r.json()",
    "docstring": "Returns the processed response for rest calls"
  },
  {
    "code": "def Header(self):\n        if not self._header:\n            self._header = Header(self.PrevHash, self.MerkleRoot, self.Timestamp,\n                                  self.Index, self.ConsensusData, self.NextConsensus, self.Script)\n        return self._header",
    "docstring": "Get the block header.\n\n        Returns:\n            neo.Core.Header:"
  },
  {
    "code": "def as_json(self,\n                entity_url,\n                context=None):\n        try:\n            urllib.request.urlopen(entity_url)\n        except urllib.error.HTTPError:\n            raise ValueError(\"Cannot open {}\".format(entity_url))\n        entity_graph = self.read(entity_url)\n        entity_json = json.loads(\n            entity_graph.serialize(\n                format='json-ld',\n                context=context).decode())\n        return json.dumps(entity_json)",
    "docstring": "Method takes a entity uri and attempts to return the Fedora Object\n        as a JSON-LD.\n\n        Args:\n            entity_url(str): Fedora Commons URL of Entity\n            context(None): Returns JSON-LD with Context, default is None\n\n        Returns:\n            str: JSON-LD of Fedora Object"
  },
  {
    "code": "def get_all_kernels(self, kernel_ids=None, owners=None):\n        params = {}\n        if kernel_ids:\n            self.build_list_params(params, kernel_ids, 'ImageId')\n        if owners:\n            self.build_list_params(params, owners, 'Owner')\n        filter = {'image-type' : 'kernel'}\n        self.build_filter_params(params, filter)\n        return self.get_list('DescribeImages', params,\n                             [('item', Image)], verb='POST')",
    "docstring": "Retrieve all the EC2 kernels available on your account.\n        Constructs a filter to allow the processing to happen server side.\n\n        :type kernel_ids: list\n        :param kernel_ids: A list of strings with the image IDs wanted\n\n        :type owners: list\n        :param owners: A list of owner IDs\n\n        :rtype: list\n        :return: A list of :class:`boto.ec2.image.Image`"
  },
  {
    "code": "def split_path(path):\n    path = path.split(0, 1)[0]\n    values = path.dimension_values(0)\n    splits = np.concatenate([[0], np.where(np.isnan(values))[0]+1, [None]])\n    subpaths = []\n    data = PandasInterface.as_dframe(path) if pd else path.array()\n    for i in range(len(splits)-1):\n        end = splits[i+1]\n        slc = slice(splits[i], None if end is None else end-1)\n        subpath = data.iloc[slc] if pd else data[slc]\n        if len(subpath):\n            subpaths.append(subpath)\n    return subpaths",
    "docstring": "Split a Path type containing a single NaN separated path into\n    multiple subpaths."
  },
  {
    "code": "def get_token(self):\n        payload = {'grant_type': 'client_credentials', 'client_id': self.client_id, 'client_secret': self.client_secret}\n        r = requests.post(OAUTH_ENDPOINT, data=json.dumps(payload), headers={'content-type': 'application/json'})\n        response = r.json()\n        if r.status_code != 200 and not ERROR_KEY in response:\n            raise GfycatClientError('Error fetching the OAUTH URL', r.status_code)\n        elif ERROR_KEY in response:\n            raise GfycatClientError(response[ERROR_KEY], r.status_code)\n        self.token_type = response['token_type']\n        self.access_token = response['access_token']\n        self.expires_in = response['expires_in']\n        self.expires_at = time.time() + self.expires_in - 5\n        self.headers = {'content-type': 'application/json','Authorization': self.token_type + ' ' + self.access_token}",
    "docstring": "Gets the authorization token"
  },
  {
    "code": "def cli(env, identifier):\n    mgr = SoftLayer.LoadBalancerManager(env.client)\n    _, loadbal_id = loadbal.parse_id(identifier)\n    if not (env.skip_confirmations or\n            formatting.confirm(\"This action will cancel a load balancer. \"\n                               \"Continue?\")):\n        raise exceptions.CLIAbort('Aborted.')\n    mgr.cancel_lb(loadbal_id)\n    env.fout('Load Balancer with id %s is being cancelled!' % identifier)",
    "docstring": "Cancel an existing load balancer."
  },
  {
    "code": "def savepoint(self):\n        if self._last_image:\n            self._savepoints.append(self._last_image)\n            self._last_image = None",
    "docstring": "Copies the last displayed image."
  },
  {
    "code": "def run(self):\n        if self.stdout:\n            sys.stdout.write(\"extracted json data:\\n\" + json.dumps(\n                self.metadata, default=to_str) + \"\\n\")\n        else:\n            extract_dist.class_metadata = self.metadata",
    "docstring": "Sends extracted metadata in json format to stdout if stdout\n        option is specified, assigns metadata dictionary to class_metadata\n        variable otherwise."
  },
  {
    "code": "def make_ggnvp(f, g=lambda x: 1./2*np.sum(x**2, axis=-1), f_argnum=0):\n    @unary_to_nary\n    def _make_ggnvp(f, x):\n        f_vjp, f_x = _make_vjp(f, x)\n        g_hvp, grad_g_x = _make_vjp(grad(g), f_x)\n        f_jvp, _ = _make_vjp(f_vjp, vspace(grad_g_x).zeros())\n        def ggnvp(v): return f_vjp(g_hvp(f_jvp(v)))\n        return ggnvp\n    return _make_ggnvp(f, f_argnum)",
    "docstring": "Builds a function for evaluating generalized-Gauss-Newton-vector products\n    at a point. Slightly more expensive than mixed-mode."
  },
  {
    "code": "def close(self):\n        if self._S is not None:\n            self._S.close()\n            self._S = None\n            self._Q.put_nowait(None)",
    "docstring": "Begin closing subscription."
  },
  {
    "code": "def group(*blueprints, url_prefix=\"\"):\n        def chain(nested):\n            for i in nested:\n                if isinstance(i, (list, tuple)):\n                    yield from chain(i)\n                elif isinstance(i, BlueprintGroup):\n                    yield from i.blueprints\n                else:\n                    yield i\n        bps = BlueprintGroup(url_prefix=url_prefix)\n        for bp in chain(blueprints):\n            if bp.url_prefix is None:\n                bp.url_prefix = \"\"\n            bp.url_prefix = url_prefix + bp.url_prefix\n            bps.append(bp)\n        return bps",
    "docstring": "Create a list of blueprints, optionally grouping them under a\n        general URL prefix.\n\n        :param blueprints: blueprints to be registered as a group\n        :param url_prefix: URL route to be prepended to all sub-prefixes"
  },
  {
    "code": "def install_virtualenv(parser_args):\n    python_version = '.'.join(str(v) for v in sys.version_info[:2])\n    sys.stdout.write('Installing Python {0} virtualenv into {1} \\n'.format(python_version, VE_ROOT))\n    if sys.version_info < (3, 3):\n        install_virtualenv_p2(VE_ROOT, python_version)\n    else:\n        install_virtualenv_p3(VE_ROOT, python_version)",
    "docstring": "Installs virtual environment"
  },
  {
    "code": "def read_file(path):\n    with open(must_exist(path)) as infile:\n        r = infile.read()\n    return r",
    "docstring": "Read file to string.\n\n    Arguments:\n        path (str): Source."
  },
  {
    "code": "def get_win32_short_path_name(long_name):\n    import ctypes\n    from ctypes import wintypes\n    _GetShortPathNameW = ctypes.windll.kernel32.GetShortPathNameW\n    _GetShortPathNameW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD]\n    _GetShortPathNameW.restype = wintypes.DWORD\n    output_buf_size = 0\n    while True:\n        output_buf = ctypes.create_unicode_buffer(output_buf_size)\n        needed = _GetShortPathNameW(long_name, output_buf, output_buf_size)\n        if output_buf_size >= needed:\n            short_name = output_buf.value\n            break\n        else:\n            output_buf_size = needed\n    return short_name",
    "docstring": "Gets the short path name of a given long path.\n\n    References:\n        http://stackoverflow.com/a/23598461/200291\n        http://stackoverflow.com/questions/23598289/get-win-short-fname-python\n\n    Example:\n        >>> # DISABLE_DOCTEST\n        >>> from utool.util_path import *  # NOQA\n        >>> import utool as ut  # NOQA\n        >>> # build test data\n        >>> #long_name = unicode(normpath(ut.get_resource_dir()))\n        >>> long_name = unicode(r'C:/Program Files (x86)')\n        >>> #long_name = unicode(r'C:/Python27')\n        #unicode(normpath(ut.get_resource_dir()))\n        >>> # execute function\n        >>> result = get_win32_short_path_name(long_name)\n        >>> # verify results\n        >>> print(result)\n        C:/PROGRA~2"
  },
  {
    "code": "def to_vobject(self, project=None, uid=None):\n        self._update()\n        vtodos = iCalendar()\n        if uid:\n            uid = uid.split('@')[0]\n            if not project:\n                for p in self._tasks:\n                    if uid in self._tasks[p]:\n                        project = p\n                        break\n            self._gen_vtodo(self._tasks[basename(project)][uid], vtodos.add('vtodo'))\n        elif project:\n            for task in self._tasks[basename(project)].values():\n                self._gen_vtodo(task, vtodos.add('vtodo'))\n        else:\n            for project in self._tasks:\n                for task in self._tasks[project].values():\n                    self._gen_vtodo(task, vtodos.add('vtodo'))\n        return vtodos",
    "docstring": "Return vObject object of Taskwarrior tasks\n        If filename and UID are specified, the vObject only contains that task.\n        If only a filename is specified, the vObject contains all events in the project.\n        Otherwise the vObject contains all all objects of all files associated with the IcsTask object.\n\n        project -- the Taskwarrior project\n        uid -- the UID of the task"
  },
  {
    "code": "def update_scalar_bar_range(self, clim, name=None):\n        if isinstance(clim, float) or isinstance(clim, int):\n            clim = [-clim, clim]\n        if len(clim) != 2:\n            raise TypeError('clim argument must be a length 2 iterable of values: (min, max).')\n        if name is None:\n            if not hasattr(self, 'mapper'):\n                raise RuntimeError('This plotter does not have an active mapper.')\n            return self.mapper.SetScalarRange(*clim)\n        def update_mapper(mapper):\n            return mapper.SetScalarRange(*clim)\n        try:\n            for m in self._scalar_bar_mappers[name]:\n                update_mapper(m)\n        except KeyError:\n            raise KeyError('Name ({}) not valid/not found in this plotter.')\n        return",
    "docstring": "Update the value range of the active or named scalar bar.\n\n        Parameters\n        ----------\n        2 item list\n            The new range of scalar bar. Example: ``[-1, 2]``.\n\n        name : str, optional\n            The title of the scalar bar to update"
  },
  {
    "code": "def memory_usage(self, deep=False):\n        if hasattr(self.array, 'memory_usage'):\n            return self.array.memory_usage(deep=deep)\n        v = self.array.nbytes\n        if deep and is_object_dtype(self) and not PYPY:\n            v += lib.memory_usage_of_objects(self.array)\n        return v",
    "docstring": "Memory usage of the values\n\n        Parameters\n        ----------\n        deep : bool\n            Introspect the data deeply, interrogate\n            `object` dtypes for system-level memory consumption\n\n        Returns\n        -------\n        bytes used\n\n        See Also\n        --------\n        numpy.ndarray.nbytes\n\n        Notes\n        -----\n        Memory usage does not include memory consumed by elements that\n        are not components of the array if deep=False or if used on PyPy"
  },
  {
    "code": "def _higher_function_scope(node):\n    current = node\n    while current.parent and not isinstance(current.parent, nodes.FunctionDef):\n        current = current.parent\n    if current and current.parent:\n        return current.parent\n    return None",
    "docstring": "Search for the first function which encloses the given\n    scope. This can be used for looking up in that function's\n    scope, in case looking up in a lower scope for a particular\n    name fails.\n\n    :param node: A scope node.\n    :returns:\n        ``None``, if no parent function scope was found,\n        otherwise an instance of :class:`astroid.scoped_nodes.Function`,\n        which encloses the given node."
  },
  {
    "code": "def send(self, uid, event, payload=None):\n        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n        if uid in self.controllers.keys():\n            addr = self.controllers[uid][0]\n            port = self.controllers[uid][1]\n            if event == E_MESSAGE:\n                return sock.sendto('/message/{}'.format(payload).encode('utf-8'), (addr, port))\n            elif event == E_RUMBLE:\n                return sock.sendto('/rumble/{}'.format(payload).encode('utf-8'), (addr, port))\n            else:\n                pass\n        else:\n            pass\n        return False",
    "docstring": "Send an event to a connected controller. Use pymlgame event type and correct payload.\n        To send a message to the controller use pymlgame.E_MESSAGE event and a string as payload.\n\n        :param uid: Unique id of the controller\n        :param event: Event type\n        :param payload: Payload of the event\n        :type uid: str\n        :type event: Event\n        :type payload: str\n        :return: Number of bytes send or False\n        :rtype: int"
  },
  {
    "code": "def clean_params(params, drop_nones=True, recursive=True):\n    cleaned = {}\n    for key, value in six.iteritems(params):\n        if drop_nones and value is None:\n            continue\n        if recursive and isinstance(value, dict):\n            value = clean_params(value, drop_nones, recursive)\n        cleaned[key] = value\n    return cleaned",
    "docstring": "Clean up a dict of API parameters to be sent to the Coinbase API.\n\n    Some endpoints require boolean options to be represented as integers. By\n    default, will remove all keys whose value is None, so that they will not be\n    sent to the API endpoint at all."
  },
  {
    "code": "def to_dade_matrix(M, annotations=\"\", filename=None):\n    n, m = M.shape\n    A = np.zeros((n + 1, m + 1))\n    A[1:, 1:] = M\n    if not annotations:\n        annotations = np.array([\"\" for _ in n], dtype=str)\n    A[0, :] = annotations\n    A[:, 0] = annotations.T\n    if filename:\n        try:\n            np.savetxt(filename, A, fmt='%i')\n            print(\"I saved input matrix in dade format as \" + str(filename))\n        except ValueError as e:\n            print(\"I couldn't save input matrix.\")\n            print(str(e))\n        finally:\n            return A\n    return A",
    "docstring": "Returns a Dade matrix from input numpy matrix. Any annotations are added\n    as header. If filename is provided and valid, said matrix is also saved\n    as text."
  },
  {
    "code": "def _ParseVValueString(\n      self, parser_mediator, data, user_information_descriptor):\n    data_start_offset = (\n        user_information_descriptor.offset + self._V_VALUE_STRINGS_OFFSET)\n    data_end_offset = data_start_offset + user_information_descriptor.size\n    descriptor_data = data[data_start_offset:data_end_offset]\n    try:\n      username = descriptor_data.decode('utf-16-le')\n    except (UnicodeDecodeError, UnicodeEncodeError) as exception:\n      username = descriptor_data.decode('utf-16-le', errors='replace')\n      parser_mediator.ProduceExtractionWarning((\n          'unable to decode V value string with error: {0!s}. Characters '\n          'that cannot be decoded will be replaced with \"?\" or '\n          '\"\\\\ufffd\".').format(exception))\n    return username",
    "docstring": "Parses a V value string.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      data (bytes): Windows Registry V value data.\n      user_information_descriptor (user_information_descriptor): V value\n          user information descriptor.\n\n    Returns:\n      str: string value stored in the Windows Registry V value data."
  },
  {
    "code": "def get_raw_default_config_and_read_file_list():\n    global _CONFIG, _READ_DEFAULT_FILES\n    if _CONFIG is not None:\n        return _CONFIG, _READ_DEFAULT_FILES\n    with _CONFIG_LOCK:\n        if _CONFIG is not None:\n            return _CONFIG, _READ_DEFAULT_FILES\n        try:\n            from ConfigParser import SafeConfigParser\n        except ImportError:\n            from configparser import ConfigParser as SafeConfigParser\n        cfg = SafeConfigParser()\n        read_files = cfg.read(get_default_config_filename())\n        _CONFIG, _READ_DEFAULT_FILES = cfg, read_files\n        return _CONFIG, _READ_DEFAULT_FILES",
    "docstring": "Returns a ConfigParser object and a list of filenames that were parsed to initialize it"
  },
  {
    "code": "def datetime(self, field=None, val=None):\n        if val is None:\n            def source():\n                tzinfo = get_default_timezone() if settings.USE_TZ else None\n                return datetime.fromtimestamp(randrange(1, 2100000000),\n                                              tzinfo)\n        else:\n            def source():\n                tzinfo = get_default_timezone() if settings.USE_TZ else None\n                return datetime.fromtimestamp(int(val.strftime(\"%s\")) +\n                                              randrange(-365*24*3600*2, 365*24*3600*2),\n                                              tzinfo)\n        return self.get_allowed_value(source, field)",
    "docstring": "Returns a random datetime. If 'val' is passed, a datetime within two\n        years of that date will be returned."
  },
  {
    "code": "def _all_reachable_tables(t):\n    for k, v in t.items():\n        for tname in _all_reachable_tables(v):\n            yield tname\n        yield k",
    "docstring": "A generator that provides all the names of tables that can be\n    reached via merges starting at the given target table."
  },
  {
    "code": "def get_chembl_id(nlm_mesh):\n    mesh_id = get_mesh_id(nlm_mesh)\n    pcid = get_pcid(mesh_id)\n    url_mesh2pcid = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/' + \\\n                    'cid/%s/synonyms/JSON' % pcid\n    r = requests.get(url_mesh2pcid)\n    res = r.json()\n    synonyms = res['InformationList']['Information'][0]['Synonym']\n    chembl_id = [syn for syn in synonyms\n                 if 'CHEMBL' in syn and 'SCHEMBL' not in syn][0]\n    return chembl_id",
    "docstring": "Get ChEMBL ID from NLM MESH\n\n    Parameters\n    ----------\n    nlm_mesh : str\n\n    Returns\n    -------\n    chembl_id : str"
  },
  {
    "code": "def _interpolated_template(self, templateid):\n        phase, y = self._get_template_by_id(templateid)\n        assert phase.min() >= 0\n        assert phase.max() <= 1\n        phase = np.concatenate([phase[-5:] - 1, phase, phase[:5] + 1])\n        y = np.concatenate([y[-5:], y, y[:5]])\n        return UnivariateSpline(phase, y, s=0, k=5)",
    "docstring": "Return an interpolator for the given template"
  },
  {
    "code": "def generate(regex, Ns):\n    \"Return the strings matching regex whose length is in Ns.\"\n    return sorted(regex_parse(regex)[0](Ns),\n                  key=lambda s: (len(s), s))",
    "docstring": "Return the strings matching regex whose length is in Ns."
  },
  {
    "code": "def create_intent(self,\n                      workspace_id,\n                      intent,\n                      description=None,\n                      examples=None,\n                      **kwargs):\n        if workspace_id is None:\n            raise ValueError('workspace_id must be provided')\n        if intent is None:\n            raise ValueError('intent must be provided')\n        if examples is not None:\n            examples = [self._convert_model(x, Example) for x in examples]\n        headers = {}\n        if 'headers' in kwargs:\n            headers.update(kwargs.get('headers'))\n        sdk_headers = get_sdk_headers('conversation', 'V1', 'create_intent')\n        headers.update(sdk_headers)\n        params = {'version': self.version}\n        data = {\n            'intent': intent,\n            'description': description,\n            'examples': examples\n        }\n        url = '/v1/workspaces/{0}/intents'.format(\n            *self._encode_path_vars(workspace_id))\n        response = self.request(\n            method='POST',\n            url=url,\n            headers=headers,\n            params=params,\n            json=data,\n            accept_json=True)\n        return response",
    "docstring": "Create intent.\n\n        Create a new intent.\n        This operation is limited to 2000 requests per 30 minutes. For more information,\n        see **Rate limiting**.\n\n        :param str workspace_id: Unique identifier of the workspace.\n        :param str intent: The name of the intent. This string must conform to the\n        following restrictions:\n        - It can contain only Unicode alphanumeric, underscore, hyphen, and dot\n        characters.\n        - It cannot begin with the reserved prefix `sys-`.\n        - It must be no longer than 128 characters.\n        :param str description: The description of the intent. This string cannot contain\n        carriage return, newline, or tab characters, and it must be no longer than 128\n        characters.\n        :param list[Example] examples: An array of user input examples for the intent.\n        :param dict headers: A `dict` containing the request headers\n        :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n        :rtype: DetailedResponse"
  },
  {
    "code": "def get_summary(result):\n    summary = {\n        \"success\": result.wasSuccessful(),\n        \"stat\": {\n            'total': result.testsRun,\n            'failures': len(result.failures),\n            'errors': len(result.errors),\n            'skipped': len(result.skipped),\n            'expectedFailures': len(result.expectedFailures),\n            'unexpectedSuccesses': len(result.unexpectedSuccesses)\n        }\n    }\n    summary[\"stat\"][\"successes\"] = summary[\"stat\"][\"total\"] \\\n        - summary[\"stat\"][\"failures\"] \\\n        - summary[\"stat\"][\"errors\"] \\\n        - summary[\"stat\"][\"skipped\"] \\\n        - summary[\"stat\"][\"expectedFailures\"] \\\n        - summary[\"stat\"][\"unexpectedSuccesses\"]\n    summary[\"time\"] = {\n        'start_at': result.start_at,\n        'duration': result.duration\n    }\n    summary[\"records\"] = result.records\n    return summary",
    "docstring": "get summary from test result\n\n    Args:\n        result (instance): HtmlTestResult() instance\n\n    Returns:\n        dict: summary extracted from result.\n\n            {\n                \"success\": True,\n                \"stat\": {},\n                \"time\": {},\n                \"records\": []\n            }"
  },
  {
    "code": "def untrace_function(module, function):\n    if not is_traced(function):\n        return False\n    name = get_object_name(function)\n    setattr(module, name, untracer(function))\n    return True",
    "docstring": "Untraces given module function.\n\n    :param module: Module of the function.\n    :type module: object\n    :param function: Function to untrace.\n    :type function: object\n    :return: Definition success.\n    :rtype: bool"
  },
  {
    "code": "def bz2_pack(source):\n    import bz2, base64\n    out = \"\"\n    first_line = source.split('\\n')[0]\n    if analyze.shebang.match(first_line):\n        if py3:\n            if first_line.rstrip().endswith('python'):\n                first_line = first_line.rstrip()\n                first_line += '3'\n        out = first_line + '\\n'\n    compressed_source = bz2.compress(source.encode('utf-8'))\n    out += 'import bz2, base64\\n'\n    out += \"exec(bz2.decompress(base64.b64decode('\"\n    out += base64.b64encode(compressed_source).decode('utf-8')\n    out += \"')))\\n\"\n    return out",
    "docstring": "Returns 'source' as a bzip2-compressed, self-extracting python script.\n\n    .. note::\n\n        This method uses up more space than the zip_pack method but it has the\n        advantage in that the resulting .py file can still be imported into a\n        python program."
  },
  {
    "code": "async def emit(self, record: LogRecord):\n        if self.writer is None:\n            self.writer = await self._init_writer()\n        try:\n            msg = self.format(record) + self.terminator\n            self.writer.write(msg.encode())\n            await self.writer.drain()\n        except Exception:\n            await self.handleError(record)",
    "docstring": "Actually log the specified logging record to the stream."
  },
  {
    "code": "def generate_phase_1(dim = 40):\n  phase_1 = numpy.random.normal(0, 1, dim)\n  for i in range(dim - 4, dim):\n    phase_1[i] = 1.0\n  return phase_1",
    "docstring": "The first step in creating datapoints in the Poirazi & Mel model.\n  This returns a vector of dimension dim, with the last four values set to\n  1 and the rest drawn from a normal distribution."
  },
  {
    "code": "def bounds(ctx, tile):\n    click.echo(\n        '%s %s %s %s' % TilePyramid(\n            ctx.obj['grid'],\n            tile_size=ctx.obj['tile_size'],\n            metatiling=ctx.obj['metatiling']\n        ).tile(*tile).bounds(pixelbuffer=ctx.obj['pixelbuffer'])\n    )",
    "docstring": "Print Tile bounds."
  },
  {
    "code": "def clip_adaptor(read, adaptor):\n  missmatches = 2\n  adaptor = adaptor.truncate(10)\n  read.clip_end(adaptor, len(adaptor) - missmatches)",
    "docstring": "Clip an adaptor sequence from this sequence. We assume it's in the 3'\n  end. This is basically a convenience wrapper for clipThreePrime. It\n  requires 8 out of 10 of the first bases in the adaptor sequence to match\n  for clipping to occur.\n\n  :param adaptor: sequence to look for. We only use the first 10 bases;\n                  must be a full Sequence object, not just a string."
  },
  {
    "code": "def _check_column_lengths(self):\n        column_lengths_dict = {\n            name: len(xs)\n            for (name, xs)\n            in self.columns_dict.items()\n        }\n        unique_column_lengths = set(column_lengths_dict.values())\n        if len(unique_column_lengths) != 1:\n            raise ValueError(\n                \"Mismatch between lengths of columns: %s\" % (column_lengths_dict,))",
    "docstring": "Make sure columns are of the same length or else DataFrame construction\n        will fail."
  },
  {
    "code": "def get_matching_property_names(self, regex):\n        log = logging.getLogger(self.cls_logger + '.get_matching_property_names')\n        prop_list_matched = []\n        if not isinstance(regex, basestring):\n            log.warn('regex arg is not a string, found type: {t}'.format(t=regex.__class__.__name__))\n            return prop_list_matched\n        log.debug('Finding properties matching regex: {r}'.format(r=regex))\n        for prop_name in self.properties.keys():\n            match = re.search(regex, prop_name)\n            if match:\n                prop_list_matched.append(prop_name)\n        return prop_list_matched",
    "docstring": "Returns a list of property names matching the provided\n        regular expression\n\n        :param regex: Regular expression to search on\n        :return: (list) of property names matching the regex"
  },
  {
    "code": "def export(self, Height=None, options=None, outputFile=None, Resolution=None,\\\n        Units=None, Width=None, Zoom=None, view=\"current\", verbose=False):\n        PARAMS=set_param([\"Height\",\"options\",\"outputFile\",\"Resolution\",\\\n        \"Units\",\"Width\",\"Zoom\",\"view\"],\\\n        [Height,options,outputFile,Resolution,Units,Width,Zoom,view ])\n        response=api(url=self.__url+\"/export\", PARAMS=PARAMS, method=\"POST\", verbose=verbose)\n        return response",
    "docstring": "Exports the current view to a graphics file and returns the path to the\n            saved file. PNG and JPEG formats have options for scaling, while other\n            formats only have the option 'exportTextAsFont'. For the PDF format,\n            exporting text as font does not work for two-byte characters such as\n            Chinese or Japanese. To avoid corrupted texts in the exported PDF,\n            please set false to 'exportTextAsFont' when exporting networks including\n            those non-English characters.\n\n        :param Height (string, optional): The height of the exported image. Valid\n            only for bitmap formats, such as PNG and JPEG.\n        :param options (string, optional): The format of the output file. =\n            ['JPEG (*.jpeg, *.jpg)', 'PDF (*.pdf)', 'PNG (*.png)', 'PostScript (*.ps)',\n             'SVG (*.svg)']\n        :param OutputFile (string, optional): The path name of the file where\n            the view must be saved to. By default, the view's title is used as\n            the file name.\n        :param Resolution (string, optional): The resolution of the exported\n            image, in DPI. Valid only for bitmap formats, when the selected width\n            and height 'units' is inches. The possible values are: 72 (default),\n            100, 150, 300, 600. = ['72', '100', '150', '300', '600']\n        :param Units (string, optional): The units for the 'width' and 'height'\n            values. Valid only for bitmap formats, such as PNG and JPEG. The\n            possible values are: pixels (default), inches. = ['pixels', 'inches']\n        :param Width (string, optional): The width of the exported image. Valid\n            only for bitmap formats, such as PNG and JPEG.\n        :param Zoom (string, optional): The zoom value to proportionally scale\n            the image. The default value is 100.0. Valid only for bitmap formats,\n            such as PNG and JPEG\n        :param verbose: print more\n\n        :returns: path to the saved file"
  },
  {
    "code": "def params_to_dict(params, dct):\n    for param, val in params.items():\n        if val is None:\n            continue\n        dct[param] = val\n    return dct",
    "docstring": "Updates the 'dct' dictionary with the 'params' dictionary, filtering out\n    all those whose param value is None."
  },
  {
    "code": "def taxonomy(value):\n    try:\n        value.encode('ascii')\n    except UnicodeEncodeError:\n        raise ValueError('tag %r is not ASCII' % value)\n    if re.search(r'\\s', value):\n        raise ValueError('The taxonomy %r contains whitespace chars' % value)\n    return value",
    "docstring": "Any ASCII character goes into a taxonomy, except spaces."
  },
  {
    "code": "def install(name=None, refresh=False, version=None, pkgs=None, **kwargs):\n    if refresh:\n        refresh_db()\n    try:\n        pkg_params = __salt__['pkg_resource.parse_targets'](name,\n                                                            pkgs,\n                                                            **kwargs)[0]\n    except MinionError as exc:\n        raise CommandExecutionError(exc)\n    if not pkg_params:\n        return {}\n    if pkgs is None and version and len(pkg_params) == 1:\n        pkg_params = {name: version}\n    targets = []\n    for param, pkgver in six.iteritems(pkg_params):\n        if pkgver is None:\n            targets.append(param)\n        else:\n            targets.append('{0}-{1}'.format(param, pkgver))\n    cmd = '/opt/csw/bin/pkgutil -yu {0}'.format(' '.join(targets))\n    old = list_pkgs()\n    __salt__['cmd.run_all'](cmd)\n    __context__.pop('pkg.list_pkgs', None)\n    new = list_pkgs()\n    return salt.utils.data.compare_dicts(old, new)",
    "docstring": "Install packages using the pkgutil tool.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' pkg.install <package_name>\n        salt '*' pkg.install SMClgcc346\n\n\n    Multiple Package Installation Options:\n\n    pkgs\n        A list of packages to install from OpenCSW. Must be passed as a python\n        list.\n\n        CLI Example:\n\n        .. code-block:: bash\n\n            salt '*' pkg.install pkgs='[\"foo\", \"bar\"]'\n            salt '*' pkg.install pkgs='[\"foo\", {\"bar\": \"1.2.3\"}]'\n\n\n    Returns a dict containing the new package names and versions::\n\n        {'<package>': {'old': '<old-version>',\n                       'new': '<new-version>'}}"
  },
  {
    "code": "def get_target_list(self, scan_id):\n        target_list = []\n        for target, _, _ in self.scans_table[scan_id]['targets']:\n            target_list.append(target)\n        return target_list",
    "docstring": "Get a scan's target list."
  },
  {
    "code": "def load_pickle(file_path):\n    pkl_file = open(file_path, 'rb')\n    data = pickle.load(pkl_file)\n    pkl_file.close()\n    return data",
    "docstring": "Unpickle some data from a given path.\n\n    Input:  - file_path: Target file path.\n\n    Output: - data: The python object that was serialized and stored in disk."
  },
  {
    "code": "def fatalities_range(number):\n    range_format = '{min_range} - {max_range}'\n    more_than_format = '> {min_range}'\n    ranges = [\n        [0, 100],\n        [100, 1000],\n        [1000, 10000],\n        [10000, 100000],\n        [100000, float('inf')]\n    ]\n    for r in ranges:\n        min_range = r[0]\n        max_range = r[1]\n        if max_range == float('inf'):\n            return more_than_format.format(\n                min_range=add_separators(min_range))\n        elif min_range <= number <= max_range:\n            return range_format.format(\n                min_range=add_separators(min_range),\n                max_range=add_separators(max_range))",
    "docstring": "A helper to return fatalities as a range of number.\n\n    See https://github.com/inasafe/inasafe/issues/3666#issuecomment-283565297\n\n    :param number: The exact number. Will be converted as a range.\n    :type number: int, float\n\n    :return: The range of the number.\n    :rtype: str"
  },
  {
    "code": "def get_chunked_content(self, chunksize=4096):\n        r = self.obj.api.getDatastreamDissemination(self.obj.pid, self.id,\n            stream=True,  asOfDateTime=self.as_of_date)\n        for chunk in r.iter_content(chunksize):\n            yield chunk",
    "docstring": "Generator that returns the datastream content in chunks, so\n        larger datastreams can be used without reading the entire\n        contents into memory."
  },
  {
    "code": "def _add_volume(line):\n    section = _analyse_status_type(line)\n    fields = line.strip().split()\n    volume = {}\n    for field in fields:\n        volume[field.split(':')[0]] = field.split(':')[1]\n    if section == 'LOCALDISK':\n        resource['local volumes'].append(volume)\n    else:\n        lastpnodevolumes.append(volume)",
    "docstring": "Analyse the line of volumes of ``drbdadm status``"
  },
  {
    "code": "def run():\n    args = parse_args()\n    if args.verbose:\n        log_level = logging.DEBUG\n    else:\n        log_level = logging.INFO\n    logging.basicConfig(\n        level=log_level,\n        format='%(asctime)s %(levelname)s %(name)s: %(message)s')\n    if not args.verbose:\n        req_logger = logging.getLogger('requests')\n        req_logger.setLevel(logging.WARNING)\n    logger = logging.getLogger(__name__)\n    logger.info('refresh-lsst-bib version {}'.format(__version__))\n    error_count = process_bib_files(args.dir)\n    sys.exit(error_count)",
    "docstring": "Command line entrypoint for the ``refresh-lsst-bib`` program."
  },
  {
    "code": "def Output(self):\n    self.Open()\n    self.Header()\n    self.Body()\n    self.Footer()",
    "docstring": "Output all sections of the page."
  },
  {
    "code": "def disable_requiretty_on_sudoers(log=False):\n    if log:\n        bookshelf2.logging_helpers.log_green(\n            'disabling requiretty on sudo calls')\n    comment_line('/etc/sudoers',\n                 '^Defaults.*requiretty', use_sudo=True)\n    return True",
    "docstring": "allow sudo calls through ssh without a tty"
  },
  {
    "code": "def list_all(self, before_id=None, since_id=None, **kwargs):\n        return self.list(before_id=before_id, since_id=since_id, **kwargs).autopage()",
    "docstring": "Return all direct messages.\n\n        The messages come in reversed order (newest first). Note you can only\n        provide _one_ of ``before_id``, ``since_id``.\n\n        :param str before_id: message ID for paging backwards\n        :param str since_id: message ID for most recent messages since\n        :return: direct messages\n        :rtype: generator"
  },
  {
    "code": "def fullpath(relpath):\n    if (type(relpath) is object or type(relpath) is file):\n        relpath = relpath.name\n    return os.path.abspath(os.path.expanduser(relpath))",
    "docstring": "Relative path to absolute"
  },
  {
    "code": "def space_clone(args):\n    if not args.to_workspace:\n        args.to_workspace = args.workspace\n    if not args.to_project:\n        args.to_project = args.project\n    if (args.project == args.to_project\n        and args.workspace == args.to_workspace):\n        eprint(\"Error: destination project and namespace must differ from\"\n               \" cloned workspace\")\n        return 1\n    r = fapi.clone_workspace(args.project, args.workspace, args.to_project,\n                                                            args.to_workspace)\n    fapi._check_response_code(r, 201)\n    if fcconfig.verbosity:\n        msg = \"{}/{} successfully cloned to {}/{}\".format(\n                                            args.project, args.workspace,\n                                            args.to_project, args.to_workspace)\n        print(msg)\n    return 0",
    "docstring": "Replicate a workspace"
  },
  {
    "code": "def build_response(headers: Headers, key: str) -> None:\n    headers[\"Upgrade\"] = \"websocket\"\n    headers[\"Connection\"] = \"Upgrade\"\n    headers[\"Sec-WebSocket-Accept\"] = accept(key)",
    "docstring": "Build a handshake response to send to the client.\n\n    ``key`` comes from :func:`check_request`."
  },
  {
    "code": "def return_hdr(ts, package):\n    try:\n        fdno = os.open(package, os.O_RDONLY)\n    except OSError:\n        hdr = None\n        return hdr\n    ts.setVSFlags(~(rpm.RPMVSF_NOMD5 | rpm.RPMVSF_NEEDPAYLOAD))\n    try:\n        hdr = ts.hdrFromFdno(fdno)\n    except rpm.error:\n        hdr = None\n        raise rpm.error\n    if type(hdr) != rpm.hdr:\n        hdr = None\n    ts.setVSFlags(0)\n    os.close(fdno)\n    return hdr",
    "docstring": "Hand back the hdr - duh - if the pkg is foobar handback None\n\n    Shamelessly stolen from Seth Vidal\n    http://yum.baseurl.org/download/misc/checksig.py"
  },
  {
    "code": "def create(state, host, ctid, template=None):\n    current_containers = host.fact.openvz_containers\n    if ctid in current_containers:\n        raise OperationError(\n            'An OpenVZ container with CTID {0} already exists'.format(ctid),\n        )\n    args = ['{0}'.format(ctid)]\n    if template:\n        args.append('--ostemplate {0}'.format(template))\n    yield 'vzctl create {0}'.format(' '.join(args))",
    "docstring": "Create OpenVZ containers.\n\n    + ctid: CTID of the container to create"
  },
  {
    "code": "def from_traceback(cls, tb):\n        while tb.tb_next:\n            tb = tb.tb_next\n        return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti)",
    "docstring": "Construct a Bytecode from the given traceback"
  },
  {
    "code": "def filter(self, *args):\n    if len(args) == 1 and isinstance(args[0], Filter):\n      filter = args[0]\n    else:\n      filter = Filter(*args)\n    filter.object_getattr = self.object_getattr\n    self.filters.append(filter)\n    return self",
    "docstring": "Adds a Filter to this query.\n\n    Args:\n      see :py:class:`Filter <datastore.query.Filter>` constructor\n\n    Returns self for JS-like method chaining::\n\n      query.filter('age', '>', 18).filter('sex', '=', 'Female')"
  },
  {
    "code": "def add_directives(kb_app: kb,\n                   sphinx_app: Sphinx,\n                   sphinx_env: BuildEnvironment,\n                   docnames=List[str],\n                   ):\n    for k, v in list(kb_app.config.resources.items()):\n        sphinx_app.add_directive(k, ResourceDirective)",
    "docstring": "For each resource type, register a new Sphinx directive"
  },
  {
    "code": "def local_title(self):\n        name = self.title.partition(\" for \")[0]\n        exceptDate = getLocalDate(self.except_date, self.time_from, self.tz)\n        title = _(\"{exception} for {date}\").format(exception=_(name),\n                                                   date=dateFormat(exceptDate))\n        return title",
    "docstring": "Localised version of the human-readable title of the page."
  },
  {
    "code": "def to_dict(self):\n        attributes = dict(self.attributes.items())\n        if self.style:\n            attributes.update({\"style\": dict(self.style.items())})\n        vdom_dict = {'tagName': self.tag_name, 'attributes': attributes}\n        if self.event_handlers:\n            event_handlers = dict(self.event_handlers.items())\n            for key, value in event_handlers.items():\n                value = create_event_handler(key, value)\n                event_handlers[key] = value\n            vdom_dict['eventHandlers'] = event_handlers\n        if self.key:\n            vdom_dict['key'] = self.key\n        vdom_dict['children'] = [c.to_dict() if isinstance(c, VDOM) else c for c in self.children]\n        return vdom_dict",
    "docstring": "Converts VDOM object to a dictionary that passes our schema"
  },
  {
    "code": "def get_output(self, job_id, outfn):\n        job_info = self.job_info(jobid=job_id)[0]\n        status = int(job_info[\"Status\"])\n        if status != 5:\n            raise Exception(\"The status of job %d is %d (%s)\"\n                    %(job_id, status, self.status_codes[status]))\n        remotefn = job_info[\"OutputLoc\"]\n        r = requests.get(remotefn)\n        code = r.status_code\n        if code != 200:\n            raise Exception(\"Getting file %s yielded status: %d\"\n                    %(remotefn, code))\n        try:\n            outfn.write(r.content)\n        except AttributeError:\n            f = open(outfn, \"wb\")\n            f.write(r.content)\n            f.close()",
    "docstring": "Download an output file given the id of the output request job.\n\n        ## Arguments\n\n        * `job_id` (int): The id of the _output_ job.\n        * `outfn` (str): The file where the output should be stored.\n            May also be a file-like object with a 'write' method."
  },
  {
    "code": "def facets_area(self):\n        area_faces = self.area_faces\n        areas = np.array([sum(area_faces[i])\n                          for i in self.facets],\n                         dtype=np.float64)\n        return areas",
    "docstring": "Return an array containing the area of each facet.\n\n        Returns\n        ---------\n        area : (len(self.facets),) float\n          Total area of each facet (group of faces)"
  },
  {
    "code": "def by_user(config):\n        client = Client()\n        client.prepare_connection()\n        audit_api = API(client)\n        CLI.parse_membership('Groups by User', audit_api.by_user())",
    "docstring": "Display LDAP group membership sorted by user."
  },
  {
    "code": "def clear_layout(layout: QLayout) -> None:\n    if layout is not None:\n        while layout.count():\n            item = layout.takeAt(0)\n            widget = item.widget()\n            if widget is not None:\n                widget.deleteLater()\n            else:\n                clear_layout(item.layout())",
    "docstring": "Clear the layout off all its components"
  },
  {
    "code": "def get_builtin_date(date, date_format=\"%Y-%m-%dT%H:%M:%S\", raise_exception=False):\n    if isinstance(date, datetime.datetime):\n        return date\n    elif isinstance(date, xmlrpc_client.DateTime):\n        return datetime.datetime.strptime(date.value, \"%Y%m%dT%H:%M:%S\")\n    else:\n        try:\n            return datetime.datetime.strptime(date, date_format)\n        except ValueError:\n            if raise_exception:\n                raise\n            else:\n                return None",
    "docstring": "Try to convert a date to a builtin instance of ``datetime.datetime``.\n    The input date can be a ``str``, a ``datetime.datetime``, a ``xmlrpc.client.Datetime`` or a ``xmlrpclib.Datetime``\n    instance. The returned object is a ``datetime.datetime``.\n\n    :param date: The date object to convert.\n    :param date_format: If the given date is a str, format is passed to strptime to parse it\n    :param raise_exception: If set to True, an exception will be raised if the input string cannot be parsed\n    :return: A valid ``datetime.datetime`` instance"
  },
  {
    "code": "def set_default(self, default):\n        if default is not None and len(default) > 1 and default[0] == '\"' and default[-1] == '\"':\n            default = default[1:-1]\n        self.defaultValue = default",
    "docstring": "Set Definition default value.\n\n        :param default: default value; number, str or quoted str (\"value\")"
  },
  {
    "code": "def search(self, start_ts, end_ts):\n        for meta_collection_name in self._meta_collections():\n            meta_coll = self.meta_database[meta_collection_name]\n            for ts_ns_doc in meta_coll.find(\n                {\"_ts\": {\"$lte\": end_ts, \"$gte\": start_ts}}\n            ):\n                yield ts_ns_doc",
    "docstring": "Called to query Mongo for documents in a time range."
  },
  {
    "code": "def _match_to_array(m):\n    return [_cast_biopax_element(m.get(i)) for i in range(m.varSize())]",
    "docstring": "Returns an array consisting of the elements obtained from a pattern\n    search cast into their appropriate classes."
  },
  {
    "code": "def combine_cache_keys(cls, cache_keys):\n    if len(cache_keys) == 1:\n      return cache_keys[0]\n    else:\n      combined_id = Target.maybe_readable_combine_ids(cache_key.id for cache_key in cache_keys)\n      combined_hash = hash_all(sorted(cache_key.hash for cache_key in cache_keys))\n      return cls(combined_id, combined_hash)",
    "docstring": "Returns a cache key for a list of target sets that already have cache keys.\n\n    This operation is 'idempotent' in the sense that if cache_keys contains a single key\n    then that key is returned.\n\n    Note that this operation is commutative but not associative.  We use the term 'combine' rather\n    than 'merge' or 'union' to remind the user of this. Associativity is not a necessary property,\n    in practice."
  },
  {
    "code": "def load_entry_point_system_roles(self, entry_point_group):\n        for ep in pkg_resources.iter_entry_points(group=entry_point_group):\n            self.register_system_role(ep.load())",
    "docstring": "Load system roles from an entry point group.\n\n        :param entry_point_group: The entrypoint for extensions."
  },
  {
    "code": "def closing(image, radius=None, mask=None, footprint = None):\n    dilated_image = grey_dilation(image, radius, mask, footprint)\n    return grey_erosion(dilated_image, radius, mask, footprint)",
    "docstring": "Do a morphological closing\n    \n    image - pixel image to operate on\n    radius - use a structuring element with the given radius. If no structuring\n             element, use an 8-connected structuring element.\n    mask - if present, only use unmasked pixels for operations"
  },
  {
    "code": "def extract_keywords_from_text(index_page, no_items=5):\n    index_page = MLStripper.strip_tags(index_page)\n    tokenized_index = TextBlob(index_page).lower()\n    def to_str(key):\n        if isinstance(key, unicode):\n            return key.encode(\"utf-8\")\n        return key\n    present_keywords = [\n        KEYWORDS_LOWER[key]\n        for key in KEYWORDS_LOWER.keys()\n        if len(key) > 3 and key in tokenized_index\n    ]\n    def to_source_string(key):\n        source = \"Keyword analysis\"\n        try:\n            return SourceString(key, source)\n        except UnicodeEncodeError:\n            return SourceString(key.encode(\"utf-8\"), source)\n    multi_keywords = [\n        to_source_string(key)\n        for key in present_keywords\n        if tokenized_index.words.count(key) >= 1\n    ]\n    multi_keywords = sorted(multi_keywords, key=lambda x: len(x), reverse=True)\n    if len(multi_keywords) > no_items:\n        return multi_keywords[:no_items]\n    return multi_keywords",
    "docstring": "Try to process text on the `index_page` deduce the keywords and then try\n    to match them on the Aleph's dataset.\n\n    Function returns maximally `no_items` items, to prevent spamming the user.\n\n    Args:\n        index_page (str): Content of the page as UTF-8 string\n        no_items (int, default 5): Number of items to return.\n\n    Returns:\n        list: List of :class:`.SourceString` objects."
  },
  {
    "code": "def project_point(cb, msg, attributes=('x', 'y')):\n    if skip(cb, msg, attributes): return msg\n    plot = get_cb_plot(cb)\n    x, y = msg.get('x', 0), msg.get('y', 0)\n    crs = plot.current_frame.crs\n    coordinates = crs.transform_points(plot.projection, np.array([x]), np.array([y]))\n    msg['x'], msg['y'] = coordinates[0, :2]\n    return {k: v for k, v in msg.items() if k in attributes}",
    "docstring": "Projects a single point supplied by a callback"
  },
  {
    "code": "def set_color_in_session(intent, session):\n    card_title = intent['name']\n    session_attributes = {}\n    should_end_session = False\n    if 'Color' in intent['slots']:\n        favorite_color = intent['slots']['Color']['value']\n        session_attributes = create_favorite_color_attributes(favorite_color)\n        speech_output = \"I now know your favorite color is \" + \\\n                        favorite_color + \\\n                        \". You can ask me your favorite color by saying, \" \\\n                        \"what's my favorite color?\"\n        reprompt_text = \"You can ask me your favorite color by saying, \" \\\n                        \"what's my favorite color?\"\n    else:\n        speech_output = \"I'm not sure what your favorite color is. \" \\\n                        \"Please try again.\"\n        reprompt_text = \"I'm not sure what your favorite color is. \" \\\n                        \"You can tell me your favorite color by saying, \" \\\n                        \"my favorite color is red.\"\n    return build_response(session_attributes, build_speechlet_response(\n        card_title, speech_output, reprompt_text, should_end_session))",
    "docstring": "Sets the color in the session and prepares the speech to reply to the\n    user."
  },
  {
    "code": "def flatten(cls, stats):\n        flat_children = {}\n        for _stats in spread_stats(stats):\n            key = (_stats.name, _stats.filename, _stats.lineno, _stats.module)\n            try:\n                flat_stats = flat_children[key]\n            except KeyError:\n                flat_stats = flat_children[key] = cls(*key)\n            flat_stats.own_hits += _stats.own_hits\n            flat_stats.deep_hits += _stats.deep_hits\n            flat_stats.own_time += _stats.own_time\n            flat_stats.deep_time += _stats.deep_time\n        children = list(itervalues(flat_children))\n        return cls(stats.name, stats.filename, stats.lineno, stats.module,\n                   stats.own_hits, stats.deep_hits, stats.own_time,\n                   stats.deep_time, children)",
    "docstring": "Makes a flat statistics from the given statistics."
  },
  {
    "code": "def layers(self):\n        layer = ['NONE'] * len(self.entities)\n        for i, e in enumerate(self.entities):\n            if hasattr(e, 'layer'):\n                layer[i] = str(e.layer)\n        return layer",
    "docstring": "If entities have a layer defined, return it.\n\n        Returns\n        ---------\n        layers: (len(entities), ) list of str"
  },
  {
    "code": "async def delView(self, iden):\n        if iden == self.iden:\n            raise s_exc.SynErr(mesg='cannot delete the main view')\n        view = self.views.pop(iden, None)\n        if view is None:\n            raise s_exc.NoSuchView(iden=iden)\n        await self.hive.pop(('cortex', 'views', iden))\n        await view.fini()",
    "docstring": "Delete a cortex view by iden."
  },
  {
    "code": "def _get_relationships(model):\n    relationships = []\n    for name, relationship in inspect(model).relationships.items():\n        class_ = relationship.mapper.class_\n        if relationship.uselist:\n            rel = ListRelationship(name, relation=class_.__name__)\n        else:\n            rel = Relationship(name, relation=class_.__name__)\n        relationships.append(rel)\n    return tuple(relationships)",
    "docstring": "Gets the necessary relationships for the resource\n    by inspecting the sqlalchemy model for relationships.\n\n    :param DeclarativeMeta model: The SQLAlchemy ORM model.\n    :return: A tuple of Relationship/ListRelationship instances\n        corresponding to the relationships on the Model.\n    :rtype: tuple"
  },
  {
    "code": "def _point_in_bbox(point, bounds):\n    return not(point['coordinates'][1] < bounds[0] or point['coordinates'][1] > bounds[2]\n               or point['coordinates'][0] < bounds[1] or point['coordinates'][0] > bounds[3])",
    "docstring": "valid whether the point is inside the bounding box"
  },
  {
    "code": "def midpoint(self):\n        midpoints = []\n        for segment in self:\n            if len(segment) < 2:\n                midpoints.append([])\n            else:\n                midpoints.append(segment.midpoint())\n        return midpoints",
    "docstring": "Calculate the midpoint between locations in segments.\n\n        Returns:\n            list of Point: Groups of midpoint between points in segments"
  },
  {
    "code": "def post_command(self, command, args):\n        self._loop.log_coroutine(self.send_command(command, args, Verifier()))",
    "docstring": "Post a command asynchronously and don't wait for a response.\n\n        There is no notification of any error that could happen during\n        command execution.  A log message will be generated if an error\n        occurred.  The command's response is discarded.\n\n        This method is thread-safe and may be called from inside or ouside\n        of the background event loop.  If there is no websockets connection,\n        no error will be raised (though an error will be logged).\n\n        Args:\n            command (string): The command name\n            args (dict): Optional arguments"
  },
  {
    "code": "def DiffArrayObjects(self, oldObj, newObj, isElementLinks=False):\n      if oldObj == newObj:\n         return True\n      if not oldObj or not newObj:\n         return False\n      if len(oldObj) != len(newObj):\n         __Log__.debug('DiffArrayObjects: Array lengths do not match %d != %d'\n            % (len(oldObj), len(newObj)))\n         return False\n      firstObj = oldObj[0]\n      if IsPrimitiveType(firstObj):\n         return self.DiffPrimitiveArrays(oldObj, newObj)\n      elif isinstance(firstObj, types.ManagedObject):\n         return self.DiffAnyArrays(oldObj, newObj, isElementLinks)\n      elif isinstance(firstObj, types.DataObject):\n         return self.DiffDoArrays(oldObj, newObj, isElementLinks)\n      else:\n         raise TypeError(\"Unknown type: %s\" % oldObj.__class__)",
    "docstring": "Method which deligates the diffing of arrays based on the type"
  },
  {
    "code": "def look_up_and_get(cellpy_file_name, table_name):\n    root = '/CellpyData'\n    table_path = '/'.join([root, table_name])\n    logging.debug(f\"look_up_and_get({cellpy_file_name}, {table_name}\")\n    store = pd.HDFStore(cellpy_file_name)\n    table = store.select(table_path)\n    store.close()\n    return table",
    "docstring": "Extracts table from cellpy hdf5-file."
  },
  {
    "code": "def encode_space_pad(instr, length, encoding):\n    output = instr.decode('utf-8').encode(encoding)\n    if len(output) > length:\n        raise pycdlibexception.PyCdlibInvalidInput('Input string too long!')\n    encoded_space = ' '.encode(encoding)\n    left = length - len(output)\n    while left > 0:\n        output += encoded_space\n        left -= len(encoded_space)\n    if left < 0:\n        output = output[:left]\n    return output",
    "docstring": "A function to pad out an input string with spaces to the length specified.\n    The space is first encoded into the specified encoding, then appended to\n    the input string until the length is reached.\n\n    Parameters:\n     instr - The input string to encode and pad.\n     length - The length to pad the input string to.\n     encoding - The encoding to use.\n    Returns:\n     The input string encoded in the encoding and padded with encoded spaces."
  },
  {
    "code": "def update(self, newcfg):\n        for key in newcfg.keys():\n            if key not in self._cfg:\n                self._cfg[key] = CaseInsensitiveDict()\n            for skey in newcfg[key]:\n                self._cfg[key][skey] = newcfg[key][skey]",
    "docstring": "Update current config with a dictionary"
  },
  {
    "code": "def write_image(self, img, extname=None, extver=None,\n                    compress=None, tile_dims=None, header=None):\n        self.create_image_hdu(img,\n                              header=header,\n                              extname=extname, extver=extver,\n                              compress=compress, tile_dims=tile_dims)\n        if header is not None:\n            self[-1].write_keys(header)\n            self[-1]._update_info()",
    "docstring": "Create a new image extension and write the data.\n\n        parameters\n        ----------\n        img: ndarray\n            An n-dimensional image.\n        extname: string, optional\n            An optional extension name.\n        extver: integer, optional\n            FITS allows multiple extensions to have the same name (extname).\n            These extensions can optionally specify an EXTVER version number in\n            the header.  Send extver= to set a particular version, which will\n            be represented in the header with keyname EXTVER.  The extver must\n            be an integer > 0.  If extver is not sent, the first one will be\n            selected.  If ext is an integer, the extver is ignored.\n        compress: string, optional\n            A string representing the compression algorithm for images,\n            default None.\n            Can be one of\n                'RICE'\n                'GZIP'\n                'GZIP_2'\n                'PLIO' (no unsigned or negative integers)\n                'HCOMPRESS'\n            (case-insensitive) See the cfitsio manual for details.\n        header: FITSHDR, list, dict, optional\n            A set of header keys to write. Can be one of these:\n                - FITSHDR object\n                - list of dictionaries containing 'name','value' and optionally\n                  a 'comment' field; the order is preserved.\n                - a dictionary of keyword-value pairs; no comments are written\n                  in this case, and the order is arbitrary.\n            Note required keywords such as NAXIS, XTENSION, etc are cleaed out.\n\n\n        restrictions\n        ------------\n        The File must be opened READWRITE"
  },
  {
    "code": "def cutout_shape(self, shape_obj):\n        view, mask = self.get_shape_view(shape_obj)\n        data = self._slice(view)\n        mdata = np.ma.array(data, mask=np.logical_not(mask))\n        return mdata",
    "docstring": "Cut out and return a portion of the data corresponding to `shape_obj`.\n        A masked numpy array is returned, where the pixels not enclosed in\n        the shape are masked out."
  },
  {
    "code": "def setup(__pkg: ModuleType) -> Tuple[Callable[[str], str],\n                                      Callable[[str, str, int], str]]:\n    package_locale = path.join(path.dirname(__pkg.__file__), 'locale')\n    gettext.install(__pkg.__name__, package_locale)\n    return gettext.gettext, gettext.ngettext",
    "docstring": "Configure ``gettext`` for given package.\n\n    Args:\n        __pkg: Package to use as location for :program:`gettext` files\n    Returns:\n        :program:`gettext` functions for singular and plural translations"
  },
  {
    "code": "def copy(self, overrides=None, locked=False):\n        other = copy.copy(self)\n        if overrides is not None:\n            other.overrides = overrides\n        other.locked = locked\n        other._uncache()\n        return other",
    "docstring": "Create a separate copy of this config."
  },
  {
    "code": "def _propagate_incompatibility(\n        self, incompatibility\n    ):\n        unsatisfied = None\n        for term in incompatibility.terms:\n            relation = self._solution.relation(term)\n            if relation == SetRelation.DISJOINT:\n                return\n            elif relation == SetRelation.OVERLAPPING:\n                if unsatisfied is not None:\n                    return\n                unsatisfied = term\n        if unsatisfied is None:\n            return _conflict\n        self._log(\n            \"derived: {}{}\".format(\n                \"not \" if unsatisfied.is_positive() else \"\", unsatisfied.dependency\n            )\n        )\n        self._solution.derive(\n            unsatisfied.dependency, not unsatisfied.is_positive(), incompatibility\n        )\n        return unsatisfied.dependency.name",
    "docstring": "If incompatibility is almost satisfied by _solution, adds the\n        negation of the unsatisfied term to _solution.\n\n        If incompatibility is satisfied by _solution, returns _conflict. If\n        incompatibility is almost satisfied by _solution, returns the\n        unsatisfied term's package name.\n\n        Otherwise, returns None."
  },
  {
    "code": "def prep_parallel(self, binary_args, other_args):\n        if self.length < 100:\n            raise Exception(\"Run this across 1 processor by setting num_processors kwarg to None.\")\n        if self.num_processors == -1:\n            self.num_processors = mp.cpu_count()\n        split_val = int(np.ceil(self.length/self.num_splits))\n        split_inds = [self.num_splits*i for i in np.arange(1, split_val)]\n        inds_split_all = np.split(np.arange(self.length), split_inds)\n        self.args = []\n        for i, ind_split in enumerate(inds_split_all):\n            trans_args = []\n            for arg in binary_args:\n                try:\n                    trans_args.append(arg[ind_split])\n                except TypeError:\n                    trans_args.append(arg)\n            self.args.append((i, tuple(trans_args)) + other_args)\n        return",
    "docstring": "Prepare the parallel calculations\n\n        Prepares the arguments to be run in parallel.\n        It will divide up arrays according to num_splits.\n\n        Args:\n            binary_args (list): List of binary arguments for input into the SNR function.\n            other_args (tuple of obj): tuple of other args for input into parallel snr function."
  },
  {
    "code": "def chunks(arr, size):\n    for i in _range(0, len(arr), size):\n        yield arr[i:i+size]",
    "docstring": "Splits a list into chunks\n\n    :param arr: list to split\n    :type arr: :class:`list`\n    :param size: number of elements in each chunk\n    :type size: :class:`int`\n    :return: generator object\n    :rtype: :class:`generator`"
  },
  {
    "code": "def log_critical(msg, logger=\"TaskLogger\"):\n    tasklogger = get_tasklogger(logger)\n    tasklogger.critical(msg)\n    return tasklogger",
    "docstring": "Log a CRITICAL message\n\n    Convenience function to log a message to the default Logger\n\n    Parameters\n    ----------\n    msg : str\n        Message to be logged\n    name : `str`, optional (default: \"TaskLogger\")\n        Name used to retrieve the unique TaskLogger\n\n    Returns\n    -------\n    logger : TaskLogger"
  },
  {
    "code": "def bind(end_point, socket_type):\n    sock = context.socket(socket_type)\n    try:\n        sock.bind(end_point)\n    except zmq.error.ZMQError as exc:\n        sock.close()\n        raise exc.__class__('%s: %s' % (exc, end_point))\n    return sock",
    "docstring": "Bind to a zmq URL; raise a proper error if the URL is invalid; return\n    a zmq socket."
  },
  {
    "code": "def set_id(self, identifier):\n        self._id = identifier\n        refobj = self.get_refobj()\n        if refobj:\n            self.get_refobjinter().set_id(refobj, identifier)",
    "docstring": "Set the id of the given reftrack\n\n        This will set the id on the refobject\n\n        :param identifier: the identifier number\n        :type identifier: int\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def transition_to_execute_complete(self):\n        assert self.state in [AQStateMachineStates.execute]\n        self.state = AQStateMachineStates.execute_complete",
    "docstring": "Transition to execute complate"
  },
  {
    "code": "def remove_user(config, group, username):\n        client = Client()\n        client.prepare_connection()\n        group_api = API(client)\n        try:\n            group_api.remove_user(group, username)\n        except ldap_tools.exceptions.NoGroupsFound:\n            print(\"Group ({}) not found\".format(group))\n        except ldap_tools.exceptions.TooManyResults:\n            print(\"Query for group ({}) returned multiple results.\".format(\n                group))\n        except ldap3.NO_SUCH_ATTRIBUTE:\n            print(\"{} does not exist in {}\".format(username, group))",
    "docstring": "Remove specified user from specified group."
  },
  {
    "code": "def add_sockets(self, sockets: Iterable[socket.socket]) -> None:\n        for sock in sockets:\n            self._sockets[sock.fileno()] = sock\n            self._handlers[sock.fileno()] = add_accept_handler(\n                sock, self._handle_connection\n            )",
    "docstring": "Makes this server start accepting connections on the given sockets.\n\n        The ``sockets`` parameter is a list of socket objects such as\n        those returned by `~tornado.netutil.bind_sockets`.\n        `add_sockets` is typically used in combination with that\n        method and `tornado.process.fork_processes` to provide greater\n        control over the initialization of a multi-process server."
  },
  {
    "code": "def get_categories(context, template='zinnia/tags/categories.html'):\n    return {'template': template,\n            'categories': Category.published.all().annotate(\n                count_entries_published=Count('entries')),\n            'context_category': context.get('category')}",
    "docstring": "Return the published categories."
  },
  {
    "code": "def compute_empirical(cls, X):\n        z_left = []\n        z_right = []\n        L = []\n        R = []\n        U, V = cls.split_matrix(X)\n        N = len(U)\n        base = np.linspace(EPSILON, 1.0 - EPSILON, COMPUTE_EMPIRICAL_STEPS)\n        for k in range(COMPUTE_EMPIRICAL_STEPS):\n            left = sum(np.logical_and(U <= base[k], V <= base[k])) / N\n            right = sum(np.logical_and(U >= base[k], V >= base[k])) / N\n            if left > 0:\n                z_left.append(base[k])\n                L.append(left / base[k] ** 2)\n            if right > 0:\n                z_right.append(base[k])\n                R.append(right / (1 - z_right[k]) ** 2)\n        return z_left, L, z_right, R",
    "docstring": "Compute empirical distribution."
  },
  {
    "code": "def get_thumbnail(file_, geometry_string, **options):\n    return default.backend.get_thumbnail(file_, geometry_string, **options)",
    "docstring": "A shortcut for the Backend ``get_thumbnail`` method"
  },
  {
    "code": "async def get_tree(self, prefix, *,\n                       dc=None, separator=None, watch=None, consistency=None):\n        response = await self._read(prefix,\n                                    dc=dc,\n                                    recurse=True,\n                                    separator=separator,\n                                    watch=watch,\n                                    consistency=consistency)\n        result = response.body\n        for data in result:\n            data[\"Value\"] = decode_value(data[\"Value\"], data[\"Flags\"])\n        return consul(result, meta=extract_meta(response.headers))",
    "docstring": "Gets all keys with a prefix of Key during the transaction.\n\n        Parameters:\n            prefix (str): Prefix to fetch\n            separator (str): List only up to a given separator\n            dc (str): Specify datacenter that will be used.\n                      Defaults to the agent's local datacenter.\n            watch (Blocking): Do a blocking query\n            consistency (Consistency): Force consistency\n        Returns:\n            CollectionMeta: where value is a list of values\n\n        This does not fail the transaction if the Key doesn't exist. Not\n        all keys may be present in the results if ACLs do not permit them\n        to be read."
  },
  {
    "code": "def check_virtualserver(self, name):\n        vs = self.bigIP.LocalLB.VirtualServer\n        for v in vs.get_list():\n            if v.split('/')[-1] == name:\n                return True\n        return False",
    "docstring": "Check to see if a virtual server exists"
  },
  {
    "code": "def readme():\n\tfrom livereload import Server\n\tserver = Server()\n\tserver.watch(\"README.rst\", \"py cute.py readme_build\")\n\tserver.serve(open_url_delay=1, root=\"build/readme\")",
    "docstring": "Live reload readme"
  },
  {
    "code": "def get_ordered_devices():\n    libcudart = get_libcudart()\n    devices = {}\n    for i in range(0, get_installed_devices()):\n        gpu = get_device_properties(i)\n        pciBusId = ctypes.create_string_buffer(64)\n        libcudart.cudaDeviceGetPCIBusId(ctypes.byref(pciBusId), 64, i)\n        full_id = pciBusId.value.decode('utf-8')\n        gpu['fullId'] = full_id\n        devices[full_id] = gpu\n    ordered = []\n    i = 0\n    for key in sorted(devices):\n        devices[key]['id'] = i\n        ordered.append(devices[key])\n        i += 1\n    del libcudart\n    return ordered",
    "docstring": "Default CUDA_DEVICE_ORDER is not compatible with nvidia-docker.\n    Nvidia-Docker is using CUDA_DEVICE_ORDER=PCI_BUS_ID.\n\n    https://github.com/NVIDIA/nvidia-docker/wiki/nvidia-docker#gpu-isolation"
  },
  {
    "code": "def get_lambda_to_execute(self):\n        def y(update_progress_func, cancel_job_func):\n            func = import_stringified_func(self.func)\n            extrafunckwargs = {}\n            args, kwargs = copy.copy(self.args), copy.copy(self.kwargs)\n            if self.track_progress:\n                extrafunckwargs[\"update_progress\"] = partial(update_progress_func, self.job_id)\n            if self.cancellable:\n                extrafunckwargs[\"check_for_cancel\"] = partial(cancel_job_func, self.job_id)\n            kwargs.update(extrafunckwargs)\n            return func(*args, **kwargs)\n        return y",
    "docstring": "return a function that executes the function assigned to this job.\n\n        If job.track_progress is None (the default), the returned function accepts no argument\n        and simply needs to be called. If job.track_progress is True, an update_progress function\n        is passed in that can be used by the function to provide feedback progress back to the\n        job scheduling system.\n\n        :return: a function that executes the original function assigned to this job."
  },
  {
    "code": "def _single_request(self, method, *args, **kwargs):\n        _method = self._service\n        for item in method.split('.'):\n            if method.endswith(item):\n                _method = getattr(_method, item)(*args, **kwargs)\n            else:\n                _method = getattr(_method, item)()\n        _method.uri = _method.uri.replace('$ENDPOINT', self._endpoint)\n        try:\n            return _method.execute(http=self._http)\n        except googleapiclient.errors.HttpError as exc:\n            response = json.loads(exc.content.decode('utf-8'))['error']\n            raise APIError(code=response['code'], message=response['message'], http_error=exc)",
    "docstring": "Make a single request to the fleet API endpoint\n\n        Args:\n            method (str): A dot delimited string indicating the method to call.  Example: 'Machines.List'\n            *args: Passed directly to the method being called.\n            **kwargs: Passed directly to the method being called.\n\n        Returns:\n            dict: The response from the method called.\n\n        Raises:\n            fleet.v1.errors.APIError: Fleet returned a response code >= 400"
  },
  {
    "code": "def make_variant(cls, converters, re_opts=None, compiled=False, strict=True):\n        assert converters, \"REQUIRE: Non-empty list.\"\n        if len(converters) == 1:\n            return converters[0]\n        if re_opts is None:\n            re_opts = cls.default_re_opts\n        pattern = r\")|(\".join([tc.pattern for tc in converters])\n        pattern = r\"(\"+ pattern + \")\"\n        group_count = len(converters)\n        for converter in converters:\n            group_count += pattern_group_count(converter.pattern)\n        if compiled:\n            convert_variant = cls.__create_convert_variant_compiled(converters,\n                                                                re_opts, strict)\n        else:\n            convert_variant = cls.__create_convert_variant(re_opts, strict)\n        convert_variant.pattern = pattern\n        convert_variant.converters = tuple(converters)\n        convert_variant.regex_group_count = group_count\n        return convert_variant",
    "docstring": "Creates a type converter for a number of type converter alternatives.\n        The first matching type converter is used.\n\n        REQUIRES: type_converter.pattern attribute\n\n        :param converters: List of type converters as alternatives.\n        :param re_opts:  Regular expression options zu use (=default_re_opts).\n        :param compiled: Use compiled regexp matcher, if true (=False).\n        :param strict:   Enable assertion checks.\n        :return: Type converter function object.\n\n        .. note::\n\n            Works only with named fields in :class:`parse.Parser`.\n            Parser needs group_index delta for unnamed/fixed fields.\n            This is not supported for user-defined types.\n            Otherwise, you need to use :class:`parse_type.parse.Parser`\n            (patched version of the :mod:`parse` module)."
  },
  {
    "code": "def save(self, *args, **kwargs):\n        if not self.slug:\n            self.slug = slugify(self.build_slug())[:self._meta.get_field(\"slug\").max_length]\n        if not self.is_indexed:\n            if kwargs is None:\n                kwargs = {}\n            kwargs[\"index\"] = False\n        content = super(Content, self).save(*args, **kwargs)\n        index_content_contributions.delay(self.id)\n        index_content_report_content_proxy.delay(self.id)\n        post_to_instant_articles_api.delay(self.id)\n        return content",
    "docstring": "creates the slug, queues up for indexing and saves the instance\n\n        :param args: inline arguments (optional)\n        :param kwargs: keyword arguments\n        :return: `bulbs.content.Content`"
  },
  {
    "code": "def add(self, documents, boost=None):\n        if not isinstance(documents, list):\n            documents = [documents]\n        documents = [{'doc': d} for d in documents]\n        if boost:\n            for d in documents:\n                d['boost'] = boost\n        self._add_batch.extend(documents)\n        if len(self._add_batch) > SOLR_ADD_BATCH:\n            self._addFlushBatch()",
    "docstring": "Adds documents to Solr index\n        documents - Single item or list of items to add"
  },
  {
    "code": "def _templates_match(t, family_file):\n    return t.name == family_file.split(os.sep)[-1].split('_detections.csv')[0]",
    "docstring": "Return True if a tribe matches a family file path.\n\n    :type t: Tribe\n    :type family_file: str\n    :return: bool"
  },
  {
    "code": "def make_sized_handler(size, const_values, non_minimal_data_handler):\n    const_values = list(const_values)\n    def constant_size_opcode_handler(script, pc, verify_minimal_data=False):\n        pc += 1\n        data = bytes_as_hex(script[pc:pc+size])\n        if len(data) < size:\n            return pc+1, None\n        if verify_minimal_data and data in const_values:\n            non_minimal_data_handler(\"not minimal push of %s\" % repr(data))\n        return pc+size, data\n    return constant_size_opcode_handler",
    "docstring": "Create a handler for a data opcode that returns literal data of a fixed size."
  },
  {
    "code": "def graph_repr(self):\n        final = re.sub(r\"[-+]?\\d*\\.\\d+\",\n                       lambda x: format(float(x.group(0)), '.2E'),\n                       self._expr)\n        return \"Expression:\\\\l  {}\\\\l\".format(\n            final,\n        )",
    "docstring": "Short repr to use when rendering Pipeline graphs."
  },
  {
    "code": "def listen_loop(self, address, family, internal=False):\n        try:\n            sock = eventlet.listen(address, family)\n        except socket.error, e:\n            if e.errno == errno.EADDRINUSE:\n                logging.critical(\"Cannot listen on (%s, %s): already in use\" % (address, family))\n                raise\n            elif e.errno == errno.EACCES and address[1] <= 1024:\n                logging.critical(\"Cannot listen on (%s, %s) (you might need to launch as root)\" % (address, family))\n                return\n            logging.critical(\"Cannot listen on (%s, %s): %s\" % (address, family, e))\n            return\n        eventlet.sleep(0.5)\n        logging.info(\"Listening for requests on %s\" % (address, ))\n        try:\n            eventlet.serve(\n                sock,\n                lambda sock, addr: self.handle(sock, addr, internal),\n                concurrency = 10000,\n            )\n        finally:\n            sock.close()",
    "docstring": "Accepts incoming connections."
  },
  {
    "code": "def update(self, friendly_name=values.unset, voice_fallback_method=values.unset,\n               voice_fallback_url=values.unset, voice_method=values.unset,\n               voice_status_callback_method=values.unset,\n               voice_status_callback_url=values.unset, voice_url=values.unset,\n               sip_registration=values.unset, domain_name=values.unset):\n        return self._proxy.update(\n            friendly_name=friendly_name,\n            voice_fallback_method=voice_fallback_method,\n            voice_fallback_url=voice_fallback_url,\n            voice_method=voice_method,\n            voice_status_callback_method=voice_status_callback_method,\n            voice_status_callback_url=voice_status_callback_url,\n            voice_url=voice_url,\n            sip_registration=sip_registration,\n            domain_name=domain_name,\n        )",
    "docstring": "Update the DomainInstance\n\n        :param unicode friendly_name: A string to describe the resource\n        :param unicode voice_fallback_method: The HTTP method used with voice_fallback_url\n        :param unicode voice_fallback_url: The URL we should call when an error occurs in executing TwiML\n        :param unicode voice_method: The HTTP method we should use with voice_url\n        :param unicode voice_status_callback_method: The HTTP method we should use to call voice_status_callback_url\n        :param unicode voice_status_callback_url: The URL that we should call to pass status updates\n        :param unicode voice_url: The URL we should call when receiving a call\n        :param bool sip_registration: Whether SIP registration is allowed\n        :param unicode domain_name: The unique address on Twilio to route SIP traffic\n\n        :returns: Updated DomainInstance\n        :rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance"
  },
  {
    "code": "def get_all_manifests(image, registry, insecure=False, dockercfg_path=None,\n                      versions=('v1', 'v2', 'v2_list')):\n    digests = {}\n    registry_session = RegistrySession(registry, insecure=insecure, dockercfg_path=dockercfg_path)\n    for version in versions:\n        response, _ = get_manifest(image, registry_session, version)\n        if response:\n            digests[version] = response\n    return digests",
    "docstring": "Return manifest digests for image.\n\n    :param image: ImageName, the remote image to inspect\n    :param registry: str, URI for registry, if URI schema is not provided,\n                          https:// will be used\n    :param insecure: bool, when True registry's cert is not verified\n    :param dockercfg_path: str, dirname of .dockercfg location\n    :param versions: tuple, for which manifest schema versions to fetch manifests\n\n    :return: dict of successful responses, with versions as keys"
  },
  {
    "code": "def run(self,field=None,simple=False,force=False):\n        if field is None: fields = [1,2]\n        else:             fields = [field]\n        for filenames in self.filenames.compress(~self.filenames.mask['catalog']).data:\n            infile = filenames['catalog']\n            for f in fields:\n                outfile = filenames['mask_%i'%f]\n                if os.path.exists(outfile) and not force:\n                    logger.info(\"Found %s; skipping...\"%outfile)\n                    continue\n                pixels,maglims=self.calculate(infile,f,simple)\n                logger.info(\"Creating %s\"%outfile)\n                outdir = mkdir(os.path.dirname(outfile))\n                data = odict()\n                data['PIXEL']=pixels\n                data['MAGLIM']=maglims.astype('f4')\n                ugali.utils.healpix.write_partial_map(outfile,data,\n                                                      self.nside_pixel)",
    "docstring": "Loop through pixels containing catalog objects and calculate\n        the magnitude limit. This gets a bit convoluted due to all\n        the different pixel resolutions..."
  },
  {
    "code": "def _format_linedata(linedata, indent, indent_width):\n    lines = []\n    WIDTH = 78 - indent_width\n    SPACING = 2\n    NAME_WIDTH_LOWER_BOUND = 13\n    NAME_WIDTH_UPPER_BOUND = 30\n    NAME_WIDTH = max([len(s) for s, d in linedata])\n    if NAME_WIDTH < NAME_WIDTH_LOWER_BOUND:\n        NAME_WIDTH = NAME_WIDTH_LOWER_BOUND\n    elif NAME_WIDTH > NAME_WIDTH_UPPER_BOUND:\n        NAME_WIDTH = NAME_WIDTH_UPPER_BOUND\n    DOC_WIDTH = WIDTH - NAME_WIDTH - SPACING\n    for namestr, doc in linedata:\n        line = indent + namestr\n        if len(namestr) <= NAME_WIDTH:\n            line += ' ' * (NAME_WIDTH + SPACING - len(namestr))\n        else:\n            lines.append(line)\n            line = indent + ' ' * (NAME_WIDTH + SPACING)\n        line += _summarize_doc(doc, DOC_WIDTH)\n        lines.append(line.rstrip())\n    return lines",
    "docstring": "Format specific linedata into a pleasant layout.\n\n        \"linedata\" is a list of 2-tuples of the form:\n            (<item-display-string>, <item-docstring>)\n        \"indent\" is a string to use for one level of indentation\n        \"indent_width\" is a number of columns by which the\n            formatted data will be indented when printed.\n\n    The <item-display-string> column is held to 30 columns."
  },
  {
    "code": "def volume_attach(self,\n                      name,\n                      server_name,\n                      device='/dev/xvdb',\n                      timeout=300):\n        try:\n            volume = self.volume_show(name)\n        except KeyError as exc:\n            raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))\n        server = self.server_by_name(server_name)\n        response = self.compute_conn.volumes.create_server_volume(\n            server.id,\n            volume['id'],\n            device=device\n        )\n        trycount = 0\n        start = time.time()\n        while True:\n            trycount += 1\n            try:\n                response = self._volume_get(volume['id'])\n                if response['status'] == 'in-use':\n                    return response\n            except Exception as exc:\n                log.debug('Volume is attaching: %s', name)\n                time.sleep(1)\n                if time.time() - start > timeout:\n                    log.error('Timed out after %s seconds '\n                              'while waiting for data', timeout)\n                    return False\n                log.debug(\n                    'Retrying volume_show() (try %s)', trycount\n                )",
    "docstring": "Attach a block device"
  },
  {
    "code": "def _simpleparsefun(date):\r\n    if hasattr(date, 'year'):\r\n        return date\r\n    try:\r\n        date = datetime.datetime.strptime(date, '%Y-%m-%d')\r\n    except ValueError:\r\n        date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')\r\n    return date",
    "docstring": "Simple date parsing function"
  },
  {
    "code": "def compute_csets_dTRAM(connectivity, count_matrices, nn=None, callback=None):\n    r\n    if connectivity=='post_hoc_RE' or connectivity=='BAR_variance':\n        raise Exception('Connectivity type %s not supported for dTRAM data.'%connectivity)\n    state_counts =  _np.maximum(count_matrices.sum(axis=1), count_matrices.sum(axis=2))\n    return _compute_csets(\n        connectivity, state_counts, count_matrices, None, None, None, nn=nn, callback=callback)",
    "docstring": "r\"\"\"\n    Computes the largest connected sets for dTRAM data.\n\n    Parameters\n    ----------\n    connectivity : string\n        one 'reversible_pathways', 'neighbors', 'summed_count_matrix' or None.\n        Selects the algorithm for measuring overlap between thermodynamic\n        and Markov states.\n\n        * 'reversible_pathways' : requires that every state in the connected set\n          can be reached by following a pathway of reversible transitions. A\n          reversible transition between two Markov states (within the same\n          thermodynamic state k) is a pair of Markov states that belong to the\n          same strongly connected component of the count matrix (from\n          thermodynamic state k). A pathway of reversible transitions is a list of\n          reversible transitions [(i_1, i_2), (i_2, i_3),..., (i_(N-2), i_(N-1)),\n          (i_(N-1), i_N)]. The thermodynamic state where the reversible\n          transitions happen, is ignored in constructing the reversible pathways.\n          This is equivalent to assuming that two ensembles overlap at some Markov\n          state whenever there exist frames from both ensembles in that Markov\n          state.\n\n        * 'largest' : alias for reversible_pathways\n\n        * 'neighbors' : similar to 'reversible_pathways' but with a more strict\n          requirement for the overlap between thermodynamic states. It is required\n          that every state in the connected set can be reached by following a\n          pathway of reversible transitions or jumping between overlapping\n          thermodynamic states while staying in the same Markov state. A reversible\n          transition between two Markov states (within the same thermodynamic\n          state k) is a pair of Markov states that belong to the same strongly\n          connected component of the count matrix (from thermodynamic state k).\n          It is assumed that the data comes from an Umbrella sampling simulation\n          and the number of the thermodynamic state matches the position of the\n          Umbrella along the order parameter. The overlap of thermodynamic states\n          k and l within Markov state n is set according to the value of nn; if\n          there are samples in both product-space states (k,n) and (l,n) and\n          |l-n|<=nn, the states are overlapping.\n\n        * 'summed_count_matrix' : all thermodynamic states are assumed to overlap.\n          The connected set is then computed by summing the count matrices over\n          all thermodynamic states and taking it's largest strongly connected set.\n          Not recommended!\n\n        * None : assume that everything is connected. For debugging.\n\n    count_matrices : numpy.ndarray((T, M, M))\n        Count matrices for all T thermodynamic states.\n    nn : int or None, optional\n        Number of neighbors that are assumed to overlap when\n        connectivity='neighbors'\n\n    Returns\n    -------\n    csets, projected_cset\n    csets : list of numpy.ndarray((M_prime_k,), dtype=int)\n        List indexed by thermodynamic state. Every element csets[k] is\n        the largest connected set at thermodynamic state k.\n    projected_cset : numpy.ndarray(M_prime, dtype=int)\n        The overall connected set. This is the union of the individual\n        connected sets of the thermodynamic states."
  },
  {
    "code": "def _get_subnets_table(subnets):\n    table = formatting.Table(['id',\n                              'network identifier',\n                              'cidr',\n                              'note'])\n    for subnet in subnets:\n        table.add_row([subnet.get('id', ''),\n                       subnet.get('networkIdentifier', ''),\n                       subnet.get('cidr', ''),\n                       subnet.get('note', '')])\n    return table",
    "docstring": "Yields a formatted table to print subnet details.\n\n    :param List[dict] subnets: List of subnets.\n    :return Table: Formatted for subnet output."
  },
  {
    "code": "def delete(name, config=None):\n    storm_ = get_storm_instance(config)\n    try:\n        storm_.delete_entry(name)\n        print(\n            get_formatted_message(\n                'hostname \"{0}\" deleted successfully.'.format(name),\n            'success')\n        )\n    except ValueError as error:\n        print(get_formatted_message(error, 'error'), file=sys.stderr)\n        sys.exit(1)",
    "docstring": "Deletes a single host."
  },
  {
    "code": "def combine_adjacent_lines(line_numbers):\n        combine_template = \"{0}-{1}\"\n        combined_list = []\n        line_numbers.append(None)\n        start = line_numbers[0]\n        end = None\n        for line_number in line_numbers[1:]:\n            if (end if end else start) + 1 == line_number:\n                end = line_number\n            else:\n                if end:\n                    combined_list.append(combine_template.format(start, end))\n                else:\n                    combined_list.append(str(start))\n                start = line_number\n                end = None\n        return combined_list",
    "docstring": "Given a sorted collection of line numbers this will\n        turn them to strings and combine adjacent values\n\n        [1, 2, 5, 6, 100] -> [\"1-2\", \"5-6\", \"100\"]"
  },
  {
    "code": "def get_cgi_parameter_list(form: cgi.FieldStorage, key: str) -> List[str]:\n    return form.getlist(key)",
    "docstring": "Extracts a list of values, all with the same key, from a CGI form."
  },
  {
    "code": "def swap(self, position: int) -> None:\n        idx = -1 * position - 1\n        try:\n            self.values[-1], self.values[idx] = self.values[idx], self.values[-1]\n        except IndexError:\n            raise InsufficientStack(\"Insufficient stack items for SWAP{0}\".format(position))",
    "docstring": "Perform a SWAP operation on the stack."
  },
  {
    "code": "def get_next_scheduled_time(cron_string):\n    itr = croniter.croniter(cron_string, datetime.utcnow())\n    return itr.get_next(datetime)",
    "docstring": "Calculate the next scheduled time by creating a crontab object\n    with a cron string"
  },
  {
    "code": "def _sendFiles(\n        self, files, message=None, thread_id=None, thread_type=ThreadType.USER\n    ):\n        thread_id, thread_type = self._getThread(thread_id, thread_type)\n        data = self._getSendData(\n            message=self._oldMessage(message),\n            thread_id=thread_id,\n            thread_type=thread_type,\n        )\n        data[\"action_type\"] = \"ma-type:user-generated-message\"\n        data[\"has_attachment\"] = True\n        for i, (file_id, mimetype) in enumerate(files):\n            data[\"{}s[{}]\".format(mimetype_to_key(mimetype), i)] = file_id\n        return self._doSendRequest(data)",
    "docstring": "Sends files from file IDs to a thread\n\n        `files` should be a list of tuples, with a file's ID and mimetype"
  },
  {
    "code": "def mount(self, mountpoint, app, into_worker=False):\n        self._set('worker-mount' if into_worker else 'mount', '%s=%s' % (mountpoint, app), multi=True)\n        return self._section",
    "docstring": "Load application under mountpoint.\n\n        Example:\n            * .mount('', 'app0.py') -- Root URL part\n            * .mount('/app1', 'app1.py') -- URL part\n            * .mount('/pinax/here', '/var/www/pinax/deploy/pinax.wsgi')\n            * .mount('the_app3', 'app3.py')  -- Variable value: application alias (can be set by ``UWSGI_APPID``)\n            * .mount('example.com', 'app2.py')  -- Variable value: Hostname (variable set in nginx)\n\n        * http://uwsgi-docs.readthedocs.io/en/latest/Nginx.html#hosting-multiple-apps-in-the-same-process-aka-managing-script-name-and-path-info\n\n        :param str|unicode mountpoint: URL part, or variable value.\n\n            .. note:: In case of URL part you may also want to set ``manage_script_name`` basic param to ``True``.\n\n            .. warning:: In case of URL part a trailing slash may case problems in some cases\n                (e.g. with Django based projects).\n\n        :param str|unicode app: App module/file.\n\n        :param bool into_worker: Load application under mountpoint\n            in the specified worker or after workers spawn."
  },
  {
    "code": "def get_objectives_by_ids(self, objective_ids):\n        collection = JSONClientValidated('learning',\n                                         collection='Objective',\n                                         runtime=self._runtime)\n        object_id_list = []\n        for i in objective_ids:\n            object_id_list.append(ObjectId(self._get_id(i, 'learning').get_identifier()))\n        result = collection.find(\n            dict({'_id': {'$in': object_id_list}},\n                 **self._view_filter()))\n        result = list(result)\n        sorted_result = []\n        for object_id in object_id_list:\n            for object_map in result:\n                if object_map['_id'] == object_id:\n                    sorted_result.append(object_map)\n                    break\n        return objects.ObjectiveList(sorted_result, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets an ``ObjectiveList`` corresponding to the given ``IdList``.\n\n        In plenary mode, the returned list contains all of the\n        objectives specified in the ``Id`` list, in the order of the\n        list, including duplicates, or an error results if an ``Id`` in\n        the supplied list is not found or inaccessible. Otherwise,\n        inaccessible ``Objectives`` may be omitted from the list and may\n        present the elements in any order including returning a unique\n        set.\n\n        arg:    objective_ids (osid.id.IdList): the list of ``Ids`` to\n                retrieve\n        return: (osid.learning.ObjectiveList) - the returned\n                ``Objective`` list\n        raise:  NotFound - an ``Id was`` not found\n        raise:  NullArgument - ``objective_ids`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def plot_counts(df, theme):\n    dates, counts = df['date-observation'], df[theme + \"_count\"]\n    fig, ax = plt.subplots()\n    ax.set_ylabel(\"{} pixel counts\".format(\" \".join(theme.split(\"_\"))))\n    ax.set_xlabel(\"observation date\")\n    ax.plot(dates, counts, '.')\n    fig.autofmt_xdate()\n    plt.show()",
    "docstring": "plot the counts of a given theme from a created database over time"
  },
  {
    "code": "def get_all(self):\n        components = []\n        self._lock.acquire()\n        try:\n            for reference in self._references:\n                components.append(reference.get_component())\n        finally:\n            self._lock.release()\n        return components",
    "docstring": "Gets all component references registered in this reference map.\n\n        :return: a list with component references."
  },
  {
    "code": "def enable_thread_safety(self):\n        if self.threadsafe:\n            return\n        if self._running.isSet():\n            raise RuntimeError('Cannot enable thread safety after start')\n        def _getattr(obj, name):\n            return getattr(obj, name, False) is True\n        for name in dir(self):\n            try:\n                meth = getattr(self, name)\n            except AttributeError:\n                pass\n            if not callable(meth):\n                continue\n            make_threadsafe = _getattr(meth, 'make_threadsafe')\n            make_threadsafe_blocking = _getattr(meth, 'make_threadsafe_blocking')\n            if make_threadsafe:\n                assert not make_threadsafe_blocking\n                meth = self._make_threadsafe(meth)\n                setattr(self, name, meth)\n            elif make_threadsafe_blocking:\n                meth = self._make_threadsafe_blocking(meth)\n                setattr(self, name, meth)\n        self._threadsafe = True",
    "docstring": "Enable thread-safety features.\n\n        Must be called before start()."
  },
  {
    "code": "def head(self, n=5):\n        col = self.copy()\n        col.query.setLIMIT(n)\n        return col.toPandas()",
    "docstring": "Returns first n rows"
  },
  {
    "code": "def _hm_form_message(\r\n            self,\r\n            thermostat_id,\r\n            protocol,\r\n            source,\r\n            function,\r\n            start,\r\n            payload\r\n    ):\r\n        if protocol == constants.HMV3_ID:\r\n            start_low = (start & constants.BYTEMASK)\r\n            start_high = (start >> 8) & constants.BYTEMASK\r\n            if function == constants.FUNC_READ:\r\n                payload_length = 0\r\n                length_low = (constants.RW_LENGTH_ALL & constants.BYTEMASK)\r\n                length_high = (constants.RW_LENGTH_ALL\r\n                               >> 8) & constants.BYTEMASK\r\n            else:\r\n                payload_length = len(payload)\r\n                length_low = (payload_length & constants.BYTEMASK)\r\n                length_high = (payload_length >> 8) & constants.BYTEMASK\r\n            msg = [\r\n                thermostat_id,\r\n                10 + payload_length,\r\n                source,\r\n                function,\r\n                start_low,\r\n                start_high,\r\n                length_low,\r\n                length_high\r\n            ]\r\n            if function == constants.FUNC_WRITE:\r\n                msg = msg + payload\r\n                type(msg)\r\n            return msg\r\n        else:\r\n            assert 0, \"Un-supported protocol found %s\" % protocol",
    "docstring": "Forms a message payload, excluding CRC"
  },
  {
    "code": "def install(pkg, channel=None, refresh=False):\n    args = []\n    ret = {'result': None, 'output': \"\"}\n    if refresh:\n        cmd = 'refresh'\n    else:\n        cmd = 'install'\n    if channel:\n        args.append('--channel=' + channel)\n    try:\n        ret['output'] = subprocess.check_output([SNAP_BINARY_NAME, cmd, pkg] + args, stderr=subprocess.STDOUT)\n        ret['result'] = True\n    except subprocess.CalledProcessError as e:\n        ret['output'] = e.output\n        ret['result'] = False\n    return ret",
    "docstring": "Install the specified snap package from the specified channel.\n    Returns a dictionary of \"result\" and \"output\".\n\n    pkg\n        The snap package name\n\n    channel\n        Optional. The snap channel to install from, eg \"beta\"\n\n    refresh : False\n        If True, use \"snap refresh\" instead of \"snap install\".\n        This allows changing the channel of a previously installed package."
  },
  {
    "code": "def add_scene(self, animation_id, name, color, velocity, config):\n        if animation_id < 0 or animation_id >= len(self.state.animationClasses):\n            err_msg = \"Requested to register scene with invalid Animation ID. Out of range.\"\n            logging.info(err_msg)\n            return(False, 0, err_msg)\n        if self.state.animationClasses[animation_id].check_config(config) is False:\n            err_msg = \"Requested to register scene with invalid configuration.\"\n            logging.info(err_msg)\n            return(False, 0, err_msg)\n        self.state.sceneIdCtr += 1\n        self.state.scenes[self.state.sceneIdCtr] = Scene(animation_id, name, color, velocity, config)\n        sequence_number = self.zmq_publisher.publish_scene_add(self.state.sceneIdCtr, animation_id, name, color, velocity, config)\n        logging.debug(\"Registered new scene.\")\n        if self.state.activeSceneId is None:\n            self.set_scene_active(self.state.sceneIdCtr)\n        return (True, sequence_number, \"OK\")",
    "docstring": "Add a new scene, returns Scene ID"
  },
  {
    "code": "def sid(self):\n        pnames = list(self.terms)+list(self.dterms)\n        pnames.sort()\n        return (self.__class__, tuple([(k, id(self.__dict__[k])) for k in pnames if k in self.__dict__]))",
    "docstring": "Semantic id."
  },
  {
    "code": "def email_addresses595(self, key, value):\n    emails = self.get('email_addresses', [])\n    if value.get('o'):\n        emails.append({\n            'value': value.get('o'),\n            'current': False,\n            'hidden': True,\n        })\n    if value.get('m'):\n        emails.append({\n            'value': value.get('m'),\n            'current': True,\n            'hidden': True,\n        })\n    notes = self.get('_private_notes', [])\n    new_note = (\n        {\n            'source': value.get('9'),\n            'value': _private_note,\n        } for _private_note in force_list(value.get('a'))\n    )\n    notes.extend(new_note)\n    self['_private_notes'] = notes\n    return emails",
    "docstring": "Populates the ``email_addresses`` field using the 595 MARCXML field.\n\n    Also populates ``_private_notes`` as a side effect."
  },
  {
    "code": "def send_signals(self):\n        if self.flag:\n            invalid_ipn_received.send(sender=self)\n            return\n        else:\n            valid_ipn_received.send(sender=self)",
    "docstring": "Shout for the world to hear whether a txn was successful."
  },
  {
    "code": "def _is_valid_cardinal(self, inpt, metadata):\n        if not isinstance(inpt, int):\n            return False\n        if metadata.get_minimum_cardinal() and inpt < metadata.get_maximum_cardinal():\n            return False\n        if metadata.get_maximum_cardinal() and inpt > metadata.get_minimum_cardinal():\n            return False\n        if metadata.get_cardinal_set() and inpt not in metadata.get_cardinal_set():\n            return False\n        else:\n            return True",
    "docstring": "Checks if input is a valid cardinal value"
  },
  {
    "code": "def export_as_file(self, file_path, cv_source):\n        if os.path.exists(file_path):\n            raise exceptions.UserError('{} already exists'.format(file_path))\n        with open(file_path, 'wb') as f:\n            f.write(self.export_as_code(cv_source).encode('utf8'))",
    "docstring": "Export the ensemble as a single Python file and saves it to `file_path`.\n\n        This is EXPERIMENTAL as putting different modules together would probably wreak havoc\n        especially on modules that make heavy use of global variables.\n\n        Args:\n            file_path (str, unicode): Absolute/local path of place to save file in\n\n            cv_source (str, unicode): String containing actual code for base learner\n                cross-validation used to generate secondary meta-features."
  },
  {
    "code": "def pause(self):\n        if self._end_time is not None:\n            return\n        self._end_time = datetime.datetime.now()\n        self._elapsed_time += self._end_time - self._start_time",
    "docstring": "Pause the stopwatch.\n\n        If the stopwatch is already paused, nothing will happen."
  },
  {
    "code": "def generate(cache_fn):\n    if not os.path.exists(cache_fn):\n        print >> sys.stderr, \"Can't access `%s`!\" % cache_fn\n        sys.exit(1)\n    with SqliteDict(cache_fn) as db:\n        for item in _pick_keywords(db):\n            yield item",
    "docstring": "Go thru `cache_fn` and filter keywords. Store them in `keyword_list.json`.\n\n    Args:\n        cache_fn (str): Path to the file with cache.\n\n    Returns:\n        list: List of :class:`KeywordInfo` objects."
  },
  {
    "code": "def get_all_publications(return_namedtuples=True):\n    sources = [\n        ben_cz.get_publications,\n        grada_cz.get_publications,\n        cpress_cz.get_publications,\n        zonerpress_cz.get_publications,\n    ]\n    publications = []\n    for source in sources:\n        publications.extend(\n            filters.filter_publications(source())\n        )\n    if return_namedtuples:\n        publications = map(lambda x: x.to_namedtuple(), publications)\n    return publications",
    "docstring": "Get list publications from all available source.\n\n    Args:\n        return_namedtuples (bool, default True): Convert :class:`.Publication`\n                           structures to namedtuples (used in AMQP\n                           communication).\n\n    Returns:\n        list: List of :class:`.Publication` structures converted to namedtuple."
  },
  {
    "code": "def GetIcmpStatistics():\n    statistics = MIB_ICMP()\n    _GetIcmpStatistics(byref(statistics))\n    results = _struct_to_dict(statistics)\n    del(statistics)\n    return results",
    "docstring": "Return all Windows ICMP stats from iphlpapi"
  },
  {
    "code": "def poisson(data):\n    data = np.hstack(([0.0], np.array(data)))\n    cumm = np.cumsum(data)\n    def cost(s, t):\n        diff = cumm[t]-cumm[s]\n        if diff == 0:\n            return -2 * diff * (- np.log(t-s) - 1)\n        else:\n            return -2 * diff * (np.log(diff) - np.log(t-s) - 1)\n    return cost",
    "docstring": "Creates a segment cost function for a time series with a\n        poisson distribution with changing mean\n\n    Args:\n        data (:obj:`list` of float): 1D time series data\n    Returns:\n        function: Function with signature\n            (int, int) -> float\n            where the first arg is the starting index, and the second\n            is the last arg. Returns the cost of that segment"
  },
  {
    "code": "def sense_dep(self, target):\n        if target.atr_req[15] & 0x30 == 0x30:\n            self.log.warning(\"must reduce the max payload size in atr_req\")\n            target.atr_req[15] = (target.atr_req[15] & 0xCF) | 0x20\n        target = super(Device, self).sense_dep(target)\n        if target is None:\n            return\n        if target.atr_res[16] & 0x30 == 0x30:\n            self.log.warning(\"must reduce the max payload size in atr_res\")\n            target.atr_res[16] = (target.atr_res[16] & 0xCF) | 0x20\n        return target",
    "docstring": "Search for a DEP Target in active communication mode.\n\n        Because the PN531 does not implement the extended frame syntax\n        for host controller communication, it can not support the\n        maximum payload size of 254 byte. The driver handles this by\n        modifying the length-reduction values in atr_req and atr_res."
  },
  {
    "code": "def insert(self, value):\n        if not self.payload or value == self.payload:\n            self.payload = value\n        else:\n            if value <= self.payload:\n                if self.left:\n                    self.left.insert(value)\n                else:\n                    self.left = BinaryTreeNode(value)\n            else:\n                if self.right:\n                    self.right.insert(value)\n                else:\n                    self.right = BinaryTreeNode(value)",
    "docstring": "Insert a value in the tree"
  },
  {
    "code": "def get_authorization_url(self, client_id=None, instance_id=None,\n                              redirect_uri=None, region=None, scope=None,\n                              state=None):\n        client_id = client_id or self.client_id\n        instance_id = instance_id or self.instance_id\n        redirect_uri = redirect_uri or self.redirect_uri\n        region = region or self.region\n        scope = scope or self.scope\n        state = state or str(uuid.uuid4())\n        self.state = state\n        return Request(\n            'GET',\n            self.auth_base_url,\n            params={\n                'client_id': client_id,\n                'instance_id': instance_id,\n                'redirect_uri': redirect_uri,\n                'region': region,\n                'response_type': 'code',\n                'scope': scope,\n                'state': state\n            }\n        ).prepare().url, state",
    "docstring": "Generate authorization URL.\n\n        Args:\n            client_id (str): OAuth2 client ID. Defaults to ``None``.\n            instance_id (str): App Instance ID. Defaults to ``None``.\n            redirect_uri (str): Redirect URI. Defaults to ``None``.\n            region (str): App Region. Defaults to ``None``.\n            scope (str): Permissions. Defaults to ``None``.\n            state (str): UUID to detect CSRF. Defaults to ``None``.\n\n        Returns:\n            str, str: Auth URL, state"
  },
  {
    "code": "def validate_regexp(pattern, flags=0):\n    regex = re.compile(pattern, flags) if isinstance(pattern, str) else pattern\n    def regexp_validator(field, data):\n        if field.value is None:\n            return\n        if regex.match(str(field.value)) is None:\n            raise ValidationError('regexp', pattern=pattern)\n    return regexp_validator",
    "docstring": "Validate the field matches the given regular expression.\n    Should work with anything that supports '==' operator.\n\n    :param pattern: Regular expresion to match. String or regular expression instance.\n    :param pattern: Flags for the regular expression.\n    :raises: ``ValidationError('equal')``"
  },
  {
    "code": "def multiple_files_count_reads_in_windows(bed_files, args):\n    bed_windows = OrderedDict()\n    for bed_file in bed_files:\n        logging.info(\"Binning \" + bed_file)\n        if \".bedpe\" in bed_file:\n            chromosome_dfs = count_reads_in_windows_paired_end(bed_file, args)\n        else:\n            chromosome_dfs = count_reads_in_windows(bed_file, args)\n        bed_windows[bed_file] = chromosome_dfs\n    return bed_windows",
    "docstring": "Use count_reads on multiple files and store result in dict.\n\n    Untested since does the same thing as count reads."
  },
  {
    "code": "def shortcut_app_id(shortcut):\n  algorithm = Crc(width = 32, poly = 0x04C11DB7, reflect_in = True, xor_in = 0xffffffff, reflect_out = True, xor_out = 0xffffffff)\n  crc_input = ''.join([shortcut.exe,shortcut.name])\n  high_32 = algorithm.bit_by_bit(crc_input) | 0x80000000\n  full_64 = (high_32 << 32) | 0x02000000\n  return str(full_64)",
    "docstring": "Generates the app id for a given shortcut. Steam uses app ids as a unique\n  identifier for games, but since shortcuts dont have a canonical serverside\n  representation they need to be generated on the fly. The important part\n  about this function is that it will generate the same app id as Steam does\n  for a given shortcut"
  },
  {
    "code": "def http_session(cookies=None):\n    session = requests.Session()\n    if cookies is not False:\n        session.cookies.update(cookies or cookiejar())\n    session.headers.update({'User-Agent': 'ipsv/{v}'.format(v=ips_vagrant.__version__)})\n    return session",
    "docstring": "Generate a Requests session\n    @param  cookies:    Cookies to load. None loads the app default CookieJar. False disables cookie loading.\n    @type   cookies:    dict, cookielib.LWPCookieJar, None or False\n    @rtype  requests.Session"
  },
  {
    "code": "def risk_evidence(self, domain, **kwargs):\n        return self._results('risk-evidence', '/v1/risk/evidence/', items_path=('components', ), domain=domain,\n                             **kwargs)",
    "docstring": "Returns back the detailed risk evidence associated with a given domain"
  },
  {
    "code": "def volume_usage(self, year=None, month=None):\n        endpoint = '/'.join((\n            self.server_url, '_api', 'v2', 'usage', 'data_volume'))\n        return self._usage_endpoint(endpoint, year, month)",
    "docstring": "Retrieves Cloudant volume usage data, optionally for a given\n        year and month.\n\n        :param int year: Year to query against, for example 2014.\n            Optional parameter.  Defaults to None.  If used, it must be\n            accompanied by ``month``.\n        :param int month: Month to query against that must be an integer\n            between 1 and 12.  Optional parameter.  Defaults to None.\n            If used, it must be accompanied by ``year``.\n\n        :returns: Volume usage data in JSON format"
  },
  {
    "code": "def apply(self, styles=None, verbose=False):\n        PARAMS=set_param([\"styles\"],[styles])\n        response=api(url=self.__url+\"/apply\", PARAMS=PARAMS, method=\"POST\", verbose=verbose)\n        return response",
    "docstring": "Applies the specified style to the selected views and returns the\n        SUIDs of the affected views.\n\n        :param styles (string): Name of Style to be applied to the selected\n            views. = ['Directed', 'BioPAX_SIF', 'Bridging Reads Histogram:unique_0',\n            'PSIMI 25 Style', 'Coverage Histogram:best&unique', 'Minimal',\n            'Bridging Reads Histogram:best&unique_0', 'Coverage Histogram_0',\n            'Big Labels', 'No Histogram:best&unique_0', 'Bridging Reads Histogram:best',\n            'No Histogram_0', 'No Histogram:best&unique', 'Bridging Reads Histogram_0',\n            'Ripple', 'Coverage Histogram:unique_0', 'Nested Network Style',\n            'Coverage Histogram:best', 'Coverage Histogram:best&unique_0',\n            'default black', 'No Histogram:best_0', 'No Histogram:unique',\n            'No Histogram:unique_0', 'Solid', 'Bridging Reads Histogram:unique',\n            'No Histogram:best', 'Coverage Histogram', 'BioPAX', 'Bridging Reads Histogram',\n            'Coverage Histogram:best_0', 'Sample1', 'Universe', 'Bridging Reads Histogram:best_0',\n            'Coverage Histogram:unique', 'Bridging Reads Histogram:best&unique',\n            'No Histogram', 'default']\n        :param verbose: print more\n        :returns: SUIDs of the affected views"
  },
  {
    "code": "def all_domain_events(self):\n        for originator_id in self.record_manager.all_sequence_ids():\n            for domain_event in self.get_domain_events(originator_id=originator_id, page_size=100):\n                yield domain_event",
    "docstring": "Yields all domain events in the event store."
  },
  {
    "code": "def setup_handler(context):\n    if context.readDataFile('senaite.lims.txt') is None:\n        return\n    logger.info(\"SENAITE setup handler [BEGIN]\")\n    portal = context.getSite()\n    setup_html_filter(portal)\n    logger.info(\"SENAITE setup handler [DONE]\")",
    "docstring": "Generic setup handler"
  },
  {
    "code": "def unicode_name(self, name, in_group=False):\n        value = ord(_unicodedata.lookup(name))\n        if (self.is_bytes and value > 0xFF):\n            value = \"\"\n        if not in_group and value == \"\":\n            return '[^%s]' % ('\\x00-\\xff' if self.is_bytes else _uniprops.UNICODE_RANGE)\n        elif value == \"\":\n            return value\n        else:\n            return ['\\\\%03o' % value if value <= 0xFF else chr(value)]",
    "docstring": "Insert Unicode value by its name."
  },
  {
    "code": "def get_related_model(field):\n    model = None\n    if hasattr(field, 'related_model') and field.related_model:\n        model = field.related_model\n    elif hasattr(field, 'rel') and field.rel:\n        model = field.rel.to\n    return model",
    "docstring": "Gets the related model from a related field"
  },
  {
    "code": "def GetUnclaimedCoins(self):\n        unclaimed = []\n        neo = Blockchain.SystemShare().Hash\n        for coin in self.GetCoins():\n            if coin.Output.AssetId == neo and \\\n                    coin.State & CoinState.Confirmed > 0 and \\\n                    coin.State & CoinState.Spent > 0 and \\\n                    coin.State & CoinState.Claimed == 0 and \\\n                    coin.State & CoinState.Frozen == 0 and \\\n                    coin.State & CoinState.WatchOnly == 0:\n                unclaimed.append(coin)\n        return unclaimed",
    "docstring": "Gets coins in the wallet that have not been 'claimed', or redeemed for their gas value on the blockchain.\n\n        Returns:\n            list: a list of ``neo.Wallet.Coin`` that have 'claimable' value"
  },
  {
    "code": "def _maybe_update_cacher(self, clear=False, verify_is_copy=True):\n        cacher = getattr(self, '_cacher', None)\n        if cacher is not None:\n            ref = cacher[1]()\n            if ref is None:\n                del self._cacher\n            else:\n                try:\n                    ref._maybe_cache_changed(cacher[0], self)\n                except Exception:\n                    pass\n        if verify_is_copy:\n            self._check_setitem_copy(stacklevel=5, t='referant')\n        if clear:\n            self._clear_item_cache()",
    "docstring": "See if we need to update our parent cacher if clear, then clear our\n        cache.\n\n        Parameters\n        ----------\n        clear : boolean, default False\n            clear the item cache\n        verify_is_copy : boolean, default True\n            provide is_copy checks"
  },
  {
    "code": "def setup(\n            cls,\n            app_version: str,\n            app_name: str,\n            config_file_path: str,\n            config_sep_str: str,\n            root_path: typing.Optional[typing.List[str]] = None,\n    ):\n        cls.app_version = app_version\n        cls.app_name = app_name\n        cls.config_file_path = config_file_path\n        cls.config_sep_str = config_sep_str\n        cls.root_path = root_path",
    "docstring": "Configures elib_config in one fell swoop\n\n        :param app_version: version of the application\n        :param app_name:name of the application\n        :param config_file_path: path to the config file to use\n        :param config_sep_str: separator for config values paths\n        :param root_path: list of strings that will be pre-pended to *all* config values paths (useful to setup a\n        prefix for the whole app)"
  },
  {
    "code": "def commit_hash(dir='.'):\n    cmd = ['git', 'rev-parse', 'HEAD']\n    try:\n        with open(os.devnull, 'w') as devnull:\n            revision_hash = subprocess.check_output(\n                cmd,\n                cwd=dir,\n                stderr=devnull\n            )\n        if sys.version_info.major > 2:\n            revision_hash = revision_hash.decode('ascii')\n        return revision_hash.strip()\n    except subprocess.CalledProcessError:\n        return None",
    "docstring": "Return commit hash for HEAD of checked out branch of the\n    specified directory."
  },
  {
    "code": "def from_module_dict(cls, environment, module_dict, globals):\n        return cls._from_namespace(environment, module_dict, globals)",
    "docstring": "Creates a template object from a module.  This is used by the\n        module loader to create a template object.\n\n        .. versionadded:: 2.4"
  },
  {
    "code": "def cmd_web_tech(url, no_cache, verbose):\n    response = web_tech(url, no_cache, verbose)\n    print(json.dumps(response, indent=4))",
    "docstring": "Use Wappalyzer apps.json database to identify technologies used on a web application.\n\n    Reference: https://github.com/AliasIO/Wappalyzer\n\n    Note: This tool only sends one request. So, it's stealth and not suspicious.\n\n    \\b\n    $ habu.web.tech https://woocomerce.com\n    {\n        \"Nginx\": {\n            \"categories\": [\n                \"Web Servers\"\n            ]\n        },\n        \"PHP\": {\n            \"categories\": [\n                \"Programming Languages\"\n            ]\n        },\n        \"WooCommerce\": {\n            \"categories\": [\n                \"Ecommerce\"\n            ],\n            \"version\": \"6.3.1\"\n        },\n        \"WordPress\": {\n            \"categories\": [\n                \"CMS\",\n                \"Blogs\"\n            ]\n        },\n    }"
  },
  {
    "code": "def config_shortcut(action, context, name, parent):\n    keystr = get_shortcut(context, name)\n    qsc = QShortcut(QKeySequence(keystr), parent, action)\n    qsc.setContext(Qt.WidgetWithChildrenShortcut)\n    sc = Shortcut(data=(qsc, context, name))\n    return sc",
    "docstring": "Create a Shortcut namedtuple for a widget\n    \n    The data contained in this tuple will be registered in\n    our shortcuts preferences page"
  },
  {
    "code": "def is_executable_file(path):\n    fpath = os.path.realpath(path)\n    if not os.path.isfile(fpath):\n        return False\n    mode = os.stat(fpath).st_mode\n    if (sys.platform.startswith('sunos')\n            and os.getuid() == 0):\n        return bool(mode & (stat.S_IXUSR |\n                            stat.S_IXGRP |\n                            stat.S_IXOTH))\n    return os.access(fpath, os.X_OK)",
    "docstring": "Checks that path is an executable regular file, or a symlink towards one.\n\n    This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``."
  },
  {
    "code": "def ServiceAccountCredentialsFromP12File(\n        service_account_name, private_key_filename, scopes, user_agent):\n    private_key_filename = os.path.expanduser(private_key_filename)\n    scopes = util.NormalizeScopes(scopes)\n    if oauth2client.__version__ > '1.5.2':\n        credentials = (\n            service_account.ServiceAccountCredentials.from_p12_keyfile(\n                service_account_name, private_key_filename, scopes=scopes))\n        if credentials is not None:\n            credentials.user_agent = user_agent\n        return credentials\n    else:\n        with open(private_key_filename, 'rb') as key_file:\n            return oauth2client.client.SignedJwtAssertionCredentials(\n                service_account_name, key_file.read(), scopes,\n                user_agent=user_agent)",
    "docstring": "Create a new credential from the named .p12 keyfile."
  },
  {
    "code": "def set_script(self, script):\n    dist, entry_point = get_entry_point_from_console_script(script, self._distributions)\n    if entry_point:\n      self.set_entry_point(entry_point)\n      TRACER.log('Set entrypoint to console_script %r in %r' % (entry_point, dist))\n      return\n    dist, _, _ = get_script_from_distributions(script, self._distributions)\n    if dist:\n      if self._pex_info.entry_point:\n        raise self.InvalidExecutableSpecification('Cannot set both entry point and script of PEX!')\n      self._pex_info.script = script\n      TRACER.log('Set entrypoint to script %r in %r' % (script, dist))\n      return\n    raise self.InvalidExecutableSpecification(\n        'Could not find script %r in any distribution %s within PEX!' % (\n            script, ', '.join(str(d) for d in self._distributions)))",
    "docstring": "Set the entry point of this PEX environment based upon a distribution script.\n\n    :param script: The script name as defined either by a console script or ordinary\n      script within the setup.py of one of the distributions added to the PEX.\n    :raises: :class:`PEXBuilder.InvalidExecutableSpecification` if the script is not found\n      in any distribution added to the PEX."
  },
  {
    "code": "def setup_network_agents(self):\n        for i in self.env.G.nodes():\n            self.env.G.node[i]['agent'] = self.agent_type(environment=self.env, agent_id=i,\n                                                          state=deepcopy(self.initial_states[i]))",
    "docstring": "Initializes agents on nodes of graph and registers them to the SimPy environment"
  },
  {
    "code": "def get_logo_url(self, obj):\n        if current_app and obj.logo_url:\n            return u'{site_url}{path}'.format(\n                site_url=current_app.config.get('THEME_SITEURL'),\n                path=obj.logo_url,\n            )",
    "docstring": "Get the community logo URL."
  },
  {
    "code": "def to_bytes(self):\n        return struct.pack(Arp._PACKFMT, self._hwtype.value, self._prototype.value, self._hwaddrlen, self._protoaddrlen, self._operation.value, self._senderhwaddr.packed, self._senderprotoaddr.packed, self._targethwaddr.packed, self._targetprotoaddr.packed)",
    "docstring": "Return packed byte representation of the ARP header."
  },
  {
    "code": "def failsafe(func):\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        extra_files = []\n        try:\n            return func(*args, **kwargs)\n        except:\n            exc_type, exc_val, exc_tb = sys.exc_info()\n            traceback.print_exc()\n        tb = exc_tb\n        while tb:\n            filename = tb.tb_frame.f_code.co_filename\n            extra_files.append(filename)\n            tb = tb.tb_next\n        if isinstance(exc_val, SyntaxError):\n            extra_files.append(exc_val.filename)\n        app = _FailSafeFlask(extra_files)\n        app.debug = True\n        @app.route('/')\n        @app.route('/<path:path>')\n        def index(path='/'):\n            reraise(exc_type, exc_val, exc_tb)\n        return app\n    return wrapper",
    "docstring": "Wraps an app factory to provide a fallback in case of import errors.\n\n    Takes a factory function to generate a Flask app. If there is an error\n    creating the app, it will return a dummy app that just returns the Flask\n    error page for the exception.\n\n    This works with the Flask code reloader so that if the app fails during\n    initialization it will still monitor those files for changes and reload\n    the app."
  },
  {
    "code": "def _ParseRegisteredDLLs(self, parser_mediator, registry_key):\n    notify_key = registry_key.GetSubkeyByName('Notify')\n    if not notify_key:\n      return\n    for subkey in notify_key.GetSubkeys():\n      for trigger in self._TRIGGERS:\n        handler_value = subkey.GetValueByName(trigger)\n        if not handler_value:\n          continue\n        values_dict = {\n            'Application': subkey.name,\n            'Handler': handler_value.GetDataAsObject(),\n            'Trigger': trigger}\n        command_value = subkey.GetValueByName('DllName')\n        if command_value:\n          values_dict['Command'] = command_value.GetDataAsObject()\n        event_data = windows_events.WindowsRegistryEventData()\n        event_data.key_path = subkey.path\n        event_data.offset = subkey.offset\n        event_data.regvalue = values_dict\n        event_data.source_append = ': Winlogon'\n        event = time_events.DateTimeValuesEvent(\n            subkey.last_written_time, definitions.TIME_DESCRIPTION_WRITTEN)\n        parser_mediator.ProduceEventWithEventData(event, event_data)",
    "docstring": "Parses the registered DLLs that receive event notifications.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      registry_key (dfwinreg.WinRegistryKey): Windows Registry key."
  },
  {
    "code": "def cctop_check_status(jobid):\n    status = 'http://cctop.enzim.ttk.mta.hu/php/poll.php?jobId={}'.format(jobid)\n    status_text = requests.post(status)\n    return status_text.text",
    "docstring": "Check the status of a CCTOP job ID.\n\n    Args:\n        jobid (str): Job ID obtained when job was submitted\n\n    Returns:\n        str: 'Finished' if the job is finished and results ready to be downloaded, 'Running' if still in progress,\n        'Invalid' for any errors."
  },
  {
    "code": "def copy(self, src, dst, suppress_layouts=False):\n        url = '/'.join([src.drive,\n                        'api/copy',\n                        str(src.relative_to(src.drive)).rstrip('/')])\n        params = {'to': str(dst.relative_to(dst.drive)).rstrip('/'),\n                  'suppressLayouts': int(suppress_layouts)}\n        text, code = self.rest_post(url,\n                                    params=params,\n                                    session=src.session,\n                                    verify=src.verify,\n                                    cert=src.cert)\n        if code not in [200, 201]:\n            raise RuntimeError(\"%s\" % text)",
    "docstring": "Copy artifact from src to dst"
  },
  {
    "code": "def _handle_continue(self, node, scope, ctxt, stream):\n        self._dlog(\"handling continue\")\n        raise errors.InterpContinue()",
    "docstring": "Handle continue node\n\n        :node: TODO\n        :scope: TODO\n        :ctxt: TODO\n        :stream: TODO\n        :returns: TODO"
  },
  {
    "code": "def readout(self):\n        elec = self.simulate_poisson_variate()\n        elec_pre = self.saturate(elec)\n        elec_f = self.pre_readout(elec_pre)\n        adu_r = self.base_readout(elec_f)\n        adu_p = self.post_readout(adu_r)\n        self.clean_up()\n        return adu_p",
    "docstring": "Readout the detector."
  },
  {
    "code": "def setup(self, steps=None, drop_na=False, **kwargs):\n        input_nodes = None\n        selectors = self.model.get('input', {}).copy()\n        selectors.update(kwargs)\n        for i, b in enumerate(self.steps):\n            if steps is not None and i not in steps and b.name not in steps:\n                continue\n            b.setup(input_nodes, drop_na=drop_na, **selectors)\n            input_nodes = b.output_nodes",
    "docstring": "Set up the sequence of steps for analysis.\n\n        Args:\n            steps (list): Optional list of steps to set up. Each element\n                must be either an int giving the index of the step in the\n                JSON config block list, or a str giving the (unique) name of\n                the step, as specified in the JSON config. Steps that do not\n                match either index or name will be skipped.\n            drop_na (bool): Boolean indicating whether or not to automatically\n                drop events that have a n/a amplitude when reading in data\n                from event files."
  },
  {
    "code": "def draw(self, k=1, random_state=None):\n        random_state = check_random_state(random_state)\n        return self.Q.searchsorted(random_state.uniform(0, 1, size=k),\n                                   side='right')",
    "docstring": "Returns k draws from q.\n\n        For each such draw, the value i is returned with probability\n        q[i].\n\n        Parameters\n        -----------\n        k : scalar(int), optional\n            Number of draws to be returned\n\n        random_state : int or np.random.RandomState, optional\n            Random seed (integer) or np.random.RandomState instance to set\n            the initial state of the random number generator for\n            reproducibility. If None, a randomly initialized RandomState is\n            used.\n\n        Returns\n        -------\n        array_like(int)\n            An array of k independent draws from q"
  },
  {
    "code": "def make_formatter(self, width, padding, alignment, overflow=None):\n        if overflow is None:\n            overflow = self.overflow_default\n        if overflow == 'clip':\n            overflower = lambda x: [x.clip(width, self.table.cliptext)]\n        elif overflow == 'wrap':\n            overflower = lambda x: x.wrap(width)\n        elif overflow == 'preformatted':\n            overflower = lambda x: x.split('\\n')\n        else:\n            raise RuntimeError(\"Unexpected overflow mode: %r\" % overflow)\n        align = self.get_aligner(alignment, width)\n        pad = self.get_aligner('center', width + padding)\n        return lambda value: [pad(align(x)) for x in overflower(value)]",
    "docstring": "Create formatter function that factors the width and alignment\n        settings."
  },
  {
    "code": "def flow_pipe(Diam, HeadLoss, Length, Nu, PipeRough, KMinor):\n    if KMinor == 0:\n        FlowRate = flow_pipemajor(Diam, HeadLoss, Length, Nu,\n                                  PipeRough).magnitude\n    else:\n        FlowRatePrev = 0\n        err = 1.0\n        FlowRate = min(flow_pipemajor(Diam, HeadLoss, Length,\n                                      Nu, PipeRough).magnitude,\n                       flow_pipeminor(Diam, HeadLoss, KMinor).magnitude\n                       )\n        while err > 0.01:\n            FlowRatePrev = FlowRate\n            HLFricNew = (HeadLoss * headloss_fric(FlowRate, Diam, Length,\n                                                  Nu, PipeRough).magnitude\n                         / (headloss_fric(FlowRate, Diam, Length,\n                                          Nu, PipeRough).magnitude\n                            + headloss_exp(FlowRate, Diam, KMinor).magnitude\n                            )\n                         )\n            FlowRate = flow_pipemajor(Diam, HLFricNew, Length,\n                                      Nu, PipeRough).magnitude\n            if FlowRate == 0:\n                err = 0.0\n            else:\n                err = (abs(FlowRate - FlowRatePrev)\n                       / ((FlowRate + FlowRatePrev) / 2)\n                       )\n    return FlowRate",
    "docstring": "Return the the flow in a straight pipe.\n\n    This function works for both major and minor losses and\n    works whether the flow is laminar or turbulent."
  },
  {
    "code": "def formfield_for_foreignkey(self, db_field, request=None, **kwargs):\n        db = kwargs.get('using')\n        if db_field.name in self.raw_id_fields:\n            kwargs['widget'] = PolymorphicForeignKeyRawIdWidget(\n                db_field.rel,\n                admin_site=self._get_child_admin_site(db_field.rel),\n                using=db\n            )\n            if 'queryset' not in kwargs:\n                queryset = self.get_field_queryset(db, db_field, request)\n                if queryset is not None:\n                    kwargs['queryset'] = queryset\n            return db_field.formfield(**kwargs)\n        return super(PolymorphicAdminRawIdFix, self).formfield_for_foreignkey(\n            db_field, request=request, **kwargs)",
    "docstring": "Replicates the logic in ModelAdmin.forfield_for_foreignkey, replacing\n        the widget with the patched one above, initialising it with the child\n        admin site."
  },
  {
    "code": "def _StopAnalysisProcesses(self, abort=False):\n    logger.debug('Stopping analysis processes.')\n    self._StopMonitoringProcesses()\n    if abort:\n      self._AbortTerminate()\n    if not self._use_zeromq:\n      logger.debug('Emptying queues.')\n      for event_queue in self._event_queues.values():\n        event_queue.Empty()\n    for event_queue in self._event_queues.values():\n      event_queue.PushItem(plaso_queue.QueueAbort(), block=False)\n    self._AbortJoin(timeout=self._PROCESS_JOIN_TIMEOUT)\n    for event_queue in self._event_queues.values():\n      event_queue.Close(abort=abort)\n    if abort:\n      self._AbortKill()\n    else:\n      self._AbortTerminate()\n      self._AbortJoin(timeout=self._PROCESS_JOIN_TIMEOUT)\n      for event_queue in self._event_queues.values():\n        event_queue.Close(abort=True)",
    "docstring": "Stops the analysis processes.\n\n    Args:\n      abort (bool): True to indicated the stop is issued on abort."
  },
  {
    "code": "def get_value(self):\n        from spyder.utils.system import memory_usage\n        text = '%d%%' % memory_usage()\n        return 'Mem ' + text.rjust(3)",
    "docstring": "Return memory usage."
  },
  {
    "code": "def bins(self) -> List[np.ndarray]:\n        return [binning.bins for binning in self._binnings]",
    "docstring": "List of bin matrices."
  },
  {
    "code": "def install(name, minimum_version=None, required_version=None, scope=None,\n            repository=None):\n    flags = [('Name', name)]\n    if minimum_version is not None:\n        flags.append(('MinimumVersion', minimum_version))\n    if required_version is not None:\n        flags.append(('RequiredVersion', required_version))\n    if scope is not None:\n        flags.append(('Scope', scope))\n    if repository is not None:\n        flags.append(('Repository', repository))\n    params = ''\n    for flag, value in flags:\n        params += '-{0} {1} '.format(flag, value)\n    cmd = 'Install-Module {0} -Force'.format(params)\n    _pshell(cmd)\n    return name in list_modules()",
    "docstring": "Install a Powershell module from powershell gallery on the system.\n\n    :param name: Name of a Powershell module\n    :type  name: ``str``\n\n    :param minimum_version: The maximum version to install, e.g. 1.23.2\n    :type  minimum_version: ``str``\n\n    :param required_version: Install a specific version\n    :type  required_version: ``str``\n\n    :param scope: The scope to install the module to, e.g. CurrentUser, Computer\n    :type  scope: ``str``\n\n    :param repository: The friendly name of a private repository, e.g. MyREpo\n    :type  repository: ``str``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'win01' psget.install PowerPlan"
  },
  {
    "code": "def run(self):\n        self.input_channel.basic_consume(self.handle_message,\n                                         queue=self.INPUT_QUEUE_NAME,\n                                         no_ack=True\n                                         )\n        try:\n            self.input_channel.start_consuming()\n        except (KeyboardInterrupt, SystemExit):\n            log.info(\" Exiting\")\n            self.exit()",
    "docstring": "actual consuming of incoming works starts here"
  },
  {
    "code": "def storage_pools(self):\n        if not self.__storage_pools:\n            self.__storage_pools = StoragePools(self.__connection)\n        return self.__storage_pools",
    "docstring": "Gets the StoragePools API client.\n\n        Returns:\n            StoragePools:"
  },
  {
    "code": "def unpack(self, unpacker):\n        (count, ) = unpacker.unpack_struct(_H)\n        items = [(None, None), ]\n        count -= 1\n        hackpass = False\n        for _i in range(0, count):\n            if hackpass:\n                hackpass = False\n                items.append((None, None))\n            else:\n                item = _unpack_const_item(unpacker)\n                items.append(item)\n                if item[0] in (CONST_Long, CONST_Double):\n                    hackpass = True\n        self.consts = items",
    "docstring": "Unpacks the constant pool from an unpacker stream"
  },
  {
    "code": "def generate_reset_password_token(user):\n    data = [str(user.id), md5(user.password)]\n    return get_serializer(\"reset\").dumps(data)",
    "docstring": "Generate a unique reset password token for the specified user.\n\n    :param user: The user to work with"
  },
  {
    "code": "def extend_values(dictionary, key, items):\n    values = dictionary.get(key, [])\n    try:\n        values.extend(items)\n    except TypeError:\n        raise TypeError('Expected a list, got: %r' % items)\n    dictionary[key] = values",
    "docstring": "Extend the values for that key with the items"
  },
  {
    "code": "def set_intermediates(self, intermediates, betas=None, transition_states=None):\n        self.intermediates = intermediates\n        self.betas = betas\n        self.transition_states = transition_states\n        if self.corrections is None:\n            self.net_corrections = [0.0 for _ in intermediates]\n        if not self.betas:\n            self.betas = [0.0 for _ in intermediates]\n        if not self.transition_states:\n            self.transition_states = [False for _ in intermediates]\n        props = [len(self.intermediates), len(self.net_corrections), len(self.transition_states),\n                 len(self.betas)]\n        if not len(set(props)) <= 1:\n            raise ValueError('intermediate, net_corrections, transition_states and , '\n                             'betas all have to have the same length')\n        self.get_corrections()\n        return(True)",
    "docstring": "Sets up intermediates and specifies whether it's an electrochemical step.\n        Either provide individual contributions or net contributions. If both are given,\n        only the net contributions are used.\n\n        intermediate_list: list of basestrings\n        transition_states: list of True and False\n        electrochemical_steps: list of True and False\n        betas = list of charge transfer coefficients\n        net_corrections: A sum of all contributions per intermediate."
  },
  {
    "code": "def visit_ifexp(self, node, parent):\n        newnode = nodes.IfExp(node.lineno, node.col_offset, parent)\n        newnode.postinit(\n            self.visit(node.test, newnode),\n            self.visit(node.body, newnode),\n            self.visit(node.orelse, newnode),\n        )\n        return newnode",
    "docstring": "visit a IfExp node by returning a fresh instance of it"
  },
  {
    "code": "def _redraw_screen(self, stdscr):\n        with self._lock:\n            stdscr.clear()\n            stdscr.addstr(\n                0, 0, \"workflows service monitor -- quit with Ctrl+C\", curses.A_BOLD\n            )\n            stdscr.refresh()\n            self.message_box = self._boxwin(\n                5, curses.COLS, 2, 0, title=\"last seen message\", color_pair=1\n            )\n            self.message_box.scrollok(True)\n            self.cards = []",
    "docstring": "Redraw screen. This could be to initialize, or to redraw after resizing."
  },
  {
    "code": "def plugin(module, *args, **kwargs):\n    def wrap(f):\n        m = module(f, *args, **kwargs)\n        if inspect.isclass(m):\n            for k, v in m.__dict__.items():\n                if not k.startswith(\"__\"):\n                    setattr(f, k, v)\n        elif inspect.isfunction(m):\n            setattr(f, kls.__name__, m)\n        return f\n    return wrap",
    "docstring": "Decorator to extend a package to a view.\n    The module can be a class or function. It will copy all the methods to the class\n\n    ie:\n        # Your module.py\n        my_ext(view, **kwargs):\n            class MyExtension(object):\n                def my_view(self):\n                    return {}\n\n            return MyExtension\n\n        # Your view.py\n        @plugin(my_ext)\n        class Index(View):\n            pass\n\n    :param module: object\n    :param args:\n    :param kwargs:\n    :return:"
  },
  {
    "code": "def insert_draft_child(self, child_pid):\n        if child_pid.status != PIDStatus.RESERVED:\n            raise PIDRelationConsistencyError(\n                \"Draft child should have status 'RESERVED'\")\n        if not self.draft_child:\n            with db.session.begin_nested():\n                super(PIDNodeVersioning, self).insert_child(child_pid,\n                                                            index=-1)\n        else:\n            raise PIDRelationConsistencyError(\n                \"Draft child already exists for this relation: {0}\".format(\n                    self.draft_child))",
    "docstring": "Insert a draft child to versioning."
  },
  {
    "code": "def connection_made(self):\n        assert self.state == BGP_FSM_CONNECT\n        open_msg = self._peer.create_open_msg()\n        self._holdtime = open_msg.hold_time\n        self.state = BGP_FSM_OPEN_SENT\n        if not self.is_reactive:\n            self._peer.state.bgp_state = self.state\n        self.sent_open_msg = open_msg\n        self.send(open_msg)\n        self._peer.connection_made()",
    "docstring": "Connection to peer handler.\n\n        We send bgp open message to peer and initialize related attributes."
  },
  {
    "code": "def receive_trial_result(self, parameter_id, parameters, value):\n        reward = extract_scalar_reward(value)\n        if parameter_id not in self.total_data:\n            raise RuntimeError('Received parameter_id not in total_data.')\n        params = self.total_data[parameter_id]\n        if self.optimize_mode == OptimizeMode.Minimize:\n            reward = -reward\n        indiv = Individual(config=params, result=reward)\n        self.population.append(indiv)",
    "docstring": "Record the result from a trial\n\n        Parameters\n        ----------\n        parameters: dict\n        value : dict/float\n            if value is dict, it should have \"default\" key.\n            value is final metrics of the trial."
  },
  {
    "code": "def level_order(self) -> Iterator[\"BSP\"]:\n        next = [self]\n        while next:\n            level = next\n            next = []\n            yield from level\n            for node in level:\n                next.extend(node.children)",
    "docstring": "Iterate over this BSP's hierarchy in level order.\n\n        .. versionadded:: 8.3"
  },
  {
    "code": "def parse(self, value):\n        result = {}\n        rest = {}\n        for k, v in value.iteritems():\n            if k in self.fields:\n                if (isinstance(v, dict)\n                        and not self.fields[k].supports_multiple):\n                    if len(v) == 1:\n                        v = v.values()[0]\n                    else:\n                        raise InvalidParameterCombinationError(k)\n                result[k] = self.fields[k].coerce(v)\n            else:\n                rest[k] = v\n        for k, v in self.fields.iteritems():\n            if k not in result:\n                result[k] = v.coerce(None)\n        if rest:\n            raise UnknownParametersError(result, rest)\n        return result",
    "docstring": "Convert a dictionary of raw values to a dictionary of processed values."
  },
  {
    "code": "def setImportDataInterface(self, values):\n        exims = self.getImportDataInterfacesList()\n        new_values = [value for value in values if value in exims]\n        if len(new_values) < len(values):\n            logger.warn(\"Some Interfaces weren't added...\")\n        self.Schema().getField('ImportDataInterface').set(self, new_values)",
    "docstring": "Return the current list of import data interfaces"
  },
  {
    "code": "def house(self):\n        house = self.chart.houses.getObjectHouse(self.obj)\n        return house",
    "docstring": "Returns the object's house."
  },
  {
    "code": "def lighting(im, b, c):\n    if b==0 and c==1: return im\n    mu = np.average(im)\n    return np.clip((im-mu)*c+mu+b,0.,1.).astype(np.float32)",
    "docstring": "Adjust image balance and contrast"
  },
  {
    "code": "def displayStatusMessage(self, msgObj):\n        msg = msgObj.data\n        if not msg.endswith('\\n'):\n            msg = msg + '\\n'\n        self.qteLabel.setText(msg)",
    "docstring": "Display the last status message and partially completed key sequences.\n\n        |Args|\n\n        * ``msgObj`` (**QtmacsMessage**): the data supplied by the hook.\n\n        |Returns|\n\n        * **None**\n\n        |Raises|\n\n        * **None**"
  },
  {
    "code": "def get_shifted_center_blocks(x, indices):\n  center_x = gather_blocks_2d(x, indices)\n  def shift_right_2d_blocks(x):\n    shifted_targets = (\n        tf.pad(x, [[0, 0], [0, 0], [0, 0], [1, 0], [0, 0]])[:, :, :, :-1, :])\n    return shifted_targets\n  x_shifted = shift_right_2d_blocks(center_x)\n  return x_shifted",
    "docstring": "Get right shifted blocks for masked local attention 2d.\n\n  Args:\n    x: A tensor with shape [batch, heads, height, width, depth]\n    indices: The indices to gather blocks\n\n  Returns:\n    x_shifted: a tensor of extracted blocks, each block right shifted along\n      length."
  },
  {
    "code": "def read_scanimage_metadata(fh):\n    fh.seek(0)\n    try:\n        byteorder, version = struct.unpack('<2sH', fh.read(4))\n        if byteorder != b'II' or version != 43:\n            raise Exception\n        fh.seek(16)\n        magic, version, size0, size1 = struct.unpack('<IIII', fh.read(16))\n        if magic != 117637889 or version != 3:\n            raise Exception\n    except Exception:\n        raise ValueError('not a ScanImage BigTIFF v3 file')\n    frame_data = matlabstr2py(bytes2str(fh.read(size0)[:-1]))\n    roi_data = read_json(fh, '<', None, size1, None) if size1 > 1 else {}\n    return frame_data, roi_data",
    "docstring": "Read ScanImage BigTIFF v3 static and ROI metadata from open file.\n\n    Return non-varying frame data as dict and ROI group data as JSON.\n\n    The settings can be used to read image data and metadata without parsing\n    the TIFF file.\n\n    Raise ValueError if file does not contain valid ScanImage v3 metadata."
  },
  {
    "code": "def _install_signal_handler(self, signal_number, signal_name):\n    old_signal_handler = None\n    def handler(handled_signal_number, frame):\n      signal.signal(signal_number, signal.SIG_DFL)\n      sys.stderr.write(\"TensorBoard caught %s; exiting...\\n\" % signal_name)\n      if old_signal_handler not in (signal.SIG_IGN, signal.SIG_DFL):\n        old_signal_handler(handled_signal_number, frame)\n      sys.exit(0)\n    old_signal_handler = signal.signal(signal_number, handler)",
    "docstring": "Set a signal handler to gracefully exit on the given signal.\n\n    When this process receives the given signal, it will run `atexit`\n    handlers and then exit with `0`.\n\n    Args:\n      signal_number: The numeric code for the signal to handle, like\n        `signal.SIGTERM`.\n      signal_name: The human-readable signal name."
  },
  {
    "code": "def _start(self):\n        params = self._translate(self._options)\n        self._resp = self._r_session.get(self._url, params=params, stream=True)\n        self._resp.raise_for_status()\n        self._lines = self._resp.iter_lines(self._chunk_size)",
    "docstring": "Starts streaming the feed using the provided session and feed options."
  },
  {
    "code": "def _get_permission(self, authorizer_name, authorizer_lambda_function_arn):\n        rest_api = ApiGatewayRestApi(self.logical_id, depends_on=self.depends_on, attributes=self.resource_attributes)\n        api_id = rest_api.get_runtime_attr('rest_api_id')\n        partition = ArnGenerator.get_partition_name()\n        resource = '${__ApiId__}/authorizers/*'\n        source_arn = fnSub(ArnGenerator.generate_arn(partition=partition, service='execute-api', resource=resource),\n                           {\"__ApiId__\": api_id})\n        lambda_permission = LambdaPermission(self.logical_id + authorizer_name + 'AuthorizerPermission',\n                                             attributes=self.passthrough_resource_attributes)\n        lambda_permission.Action = 'lambda:invokeFunction'\n        lambda_permission.FunctionName = authorizer_lambda_function_arn\n        lambda_permission.Principal = 'apigateway.amazonaws.com'\n        lambda_permission.SourceArn = source_arn\n        return lambda_permission",
    "docstring": "Constructs and returns the Lambda Permission resource allowing the Authorizer to invoke the function.\n\n        :returns: the permission resource\n        :rtype: model.lambda_.LambdaPermission"
  },
  {
    "code": "def __get_segmentation_path(self, path):\n        startpath, ext = os.path.splitext(path)\n        segmentation_path = startpath + \"_segmentation\" + ext\n        return segmentation_path",
    "docstring": "Create path with \"_segmentation\" suffix and keep extension.\n\n        :param path:\n        :return:"
  },
  {
    "code": "def run_configurations(callback, sections_reader):\n    base = dict(OPTIONS)\n    sections = sections_reader()\n    if sections is None:\n        logger.info(\"Configuration not found in .ini files. \"\n                    \"Running with default settings\")\n        recompile()\n    elif sections == []:\n        logger.info(\"Configuration does not match current runtime. \"\n                    \"Exiting\")\n    results = []\n    for section, options in sections:\n        OPTIONS.clear()\n        OPTIONS.update(base)\n        OPTIONS.update(options)\n        logger.debug(\"Running configuration from section \\\"%s\\\". OPTIONS: %r\",\n                     section, OPTIONS)\n        results.append(callback())\n    return results",
    "docstring": "Parse configurations and execute callback for matching."
  },
  {
    "code": "def items(sanitize=False):\n    if salt.utils.data.is_true(sanitize):\n        out = dict(__grains__)\n        for key, func in six.iteritems(_SANITIZERS):\n            if key in out:\n                out[key] = func(out[key])\n        return out\n    else:\n        return __grains__",
    "docstring": "Return all of the minion's grains\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' grains.items\n\n    Sanitized CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' grains.items sanitize=True"
  },
  {
    "code": "def get_lb_pkgs(self):\n        _filter = {'items': {'description':\n                             utils.query_filter('*Load Balancer*')}}\n        packages = self.prod_pkg.getItems(id=0, filter=_filter)\n        pkgs = []\n        for package in packages:\n            if not package['description'].startswith('Global'):\n                pkgs.append(package)\n        return pkgs",
    "docstring": "Retrieves the local load balancer packages.\n\n        :returns: A dictionary containing the load balancer packages"
  },
  {
    "code": "def construct_for(self, service_name, resource_name, base_class=None):\n        details = self.details_class(\n            self.session,\n            service_name,\n            resource_name,\n            loader=self.loader\n        )\n        attrs = {\n            '_details': details,\n        }\n        klass_name = self._build_class_name(resource_name)\n        attrs.update(self._build_methods(details))\n        if base_class is None:\n            base_class = self.base_resource_class\n        return type(\n            klass_name,\n            (base_class,),\n            attrs\n        )",
    "docstring": "Builds a new, specialized ``Resource`` subclass as part of a given\n        service.\n\n        This will load the ``ResourceJSON``, determine the correct\n        mappings/methods & constructs a brand new class with those methods on\n        it.\n\n        :param service_name: The name of the service to construct a resource\n            for. Ex. ``sqs``, ``sns``, ``dynamodb``, etc.\n        :type service_name: string\n\n        :param resource_name: The name of the ``Resource``. Ex.\n            ``Queue``, ``Notification``, ``Table``, etc.\n        :type resource_name: string\n\n        :returns: A new resource class for that service"
  },
  {
    "code": "def echo_event(data):\n    return click.echo(json.dumps(data, sort_keys=True, indent=2))",
    "docstring": "Echo a json dump of an object using click"
  },
  {
    "code": "def load_lexer_from_file(filename, lexername=\"CustomLexer\", **options):\n    try:\n        custom_namespace = {}\n        exec(open(filename, 'rb').read(), custom_namespace)\n        if lexername not in custom_namespace:\n            raise ClassNotFound('no valid %s class found in %s' %\n                                (lexername, filename))\n        lexer_class = custom_namespace[lexername]\n        return lexer_class(**options)\n    except IOError as err:\n        raise ClassNotFound('cannot read %s' % filename)\n    except ClassNotFound as err:\n        raise\n    except Exception as err:\n        raise ClassNotFound('error when loading custom lexer: %s' % err)",
    "docstring": "Load a lexer from a file.\n\n    This method expects a file located relative to the current working\n    directory, which contains a Lexer class. By default, it expects the\n    Lexer to be name CustomLexer; you can specify your own class name\n    as the second argument to this function.\n\n    Users should be very careful with the input, because this method\n    is equivalent to running eval on the input file.\n\n    Raises ClassNotFound if there are any problems importing the Lexer.\n\n    .. versionadded:: 2.2"
  },
  {
    "code": "def set_status(self, id, status, timeout, update_time, history=None):\n        query = {'_id': {'$regex': '^' + id}}\n        update = {\n            '$set': {'status': status, 'timeout': timeout, 'updateTime': update_time},\n            '$push': {\n                'history': {\n                    '$each': [history.serialize],\n                    '$slice': -abs(current_app.config['HISTORY_LIMIT'])\n                }\n            }\n        }\n        return self.get_db().alerts.find_one_and_update(\n            query,\n            update=update,\n            projection={'history': 0},\n            return_document=ReturnDocument.AFTER\n        )",
    "docstring": "Set status and update history."
  },
  {
    "code": "def move_straight_to(self, x, y, steps):\n        start_x = self._rec_x\n        start_y = self._rec_y\n        for i in range(1, steps + 1):\n            self._add_step((\n                int(start_x + (x - start_x) / float(steps) * i),\n                int(start_y + (y - start_y) / float(steps) * i)))",
    "docstring": "Move straight to the newly specified location - i.e. create a straight\n        line Path from the current location to the specified point.\n\n        :param x:  X coord for the end position.\n        :param y: Y coord for the end position.\n        :param steps: How many steps to take for the move."
  },
  {
    "code": "def sort_sections(self, order):\n        order_lc = [e.lower() for e in order]\n        sections = OrderedDict( (k,self.sections[k]) for k in order_lc if k in self.sections)\n        sections.update( (k,self.sections[k]) for k in self.sections.keys() if k not in order_lc)\n        assert len(self.sections) == len(sections)\n        self.sections = sections",
    "docstring": "Sort sections according to the section names in the order list. All remaining sections\n         are added to the end in their original order\n\n        :param order: Iterable of section names\n        :return:"
  },
  {
    "code": "def create_combination(list_of_sentences):\n  num_sentences = len(list_of_sentences) - 1\n  combinations = []\n  for i, _ in enumerate(list_of_sentences):\n    if i == num_sentences:\n      break\n    num_pairs = num_sentences - i\n    populated = num_pairs * [list_of_sentences[i]]\n    zipped = list(zip(populated, list_of_sentences[i + 1:]))\n    combinations += zipped\n  return combinations",
    "docstring": "Generates all possible pair combinations for the input list of sentences.\n\n  For example:\n\n  input = [\"paraphrase1\", \"paraphrase2\", \"paraphrase3\"]\n\n  output = [(\"paraphrase1\", \"paraphrase2\"),\n            (\"paraphrase1\", \"paraphrase3\"),\n            (\"paraphrase2\", \"paraphrase3\")]\n\n  Args:\n    list_of_sentences: the list of input sentences.\n  Returns:\n    the list of all possible sentence pairs."
  },
  {
    "code": "def from_dict(cls, parm, pool = None):\n        if pool is None:\n            pool = Pool()\n        pool.id = parm['id']\n        pool.name = parm['name']\n        pool.description = parm['description']\n        pool.default_type = parm['default_type']\n        pool.ipv4_default_prefix_length = parm['ipv4_default_prefix_length']\n        pool.ipv6_default_prefix_length = parm['ipv6_default_prefix_length']\n        for val in ('member_prefixes_v4', 'member_prefixes_v6',\n                'used_prefixes_v4', 'used_prefixes_v6', 'free_prefixes_v4',\n                'free_prefixes_v6', 'total_prefixes_v4', 'total_prefixes_v6',\n                'total_addresses_v4', 'total_addresses_v6', 'used_addresses_v4',\n                'used_addresses_v6', 'free_addresses_v4', 'free_addresses_v6'):\n            if parm[val] is not None:\n                setattr(pool, val, int(parm[val]))\n        pool.tags = {}\n        for tag_name in parm['tags']:\n            tag = Tag.from_dict({'name': tag_name })\n            pool.tags[tag_name] = tag\n        pool.avps = parm['avps']\n        if parm['vrf_id'] is not None:\n            pool.vrf = VRF.get(parm['vrf_id'])\n        return pool",
    "docstring": "Create new Pool-object from dict.\n\n            Suitable for creating objects from XML-RPC data.\n            All available keys must exist."
  },
  {
    "code": "def _get_binary_from_ipv6(self, ip_addr):\n        hi, lo = struct.unpack(\"!QQ\", socket.inet_pton(socket.AF_INET6,\n                                                       ip_addr))\n        return (hi << 64) | lo",
    "docstring": "Converts IPv6 address to binary form."
  },
  {
    "code": "def rebind(self, **params):\n        new_params = self.__params.copy()\n        new_params.update(params)\n        return self.__class__(new_params, self.__action)",
    "docstring": "Rebind the parameters into the URI.\n\n        :return: A new `CallAPI` instance with the new parameters."
  },
  {
    "code": "def parse_task_declaration(self, declaration_subAST):\n        var_name = self.parse_declaration_name(declaration_subAST.attr(\"name\"))\n        var_type = self.parse_declaration_type(declaration_subAST.attr(\"type\"))\n        var_expressn = self.parse_declaration_expressn(declaration_subAST.attr(\"expression\"), es='')\n        return (var_name, var_type, var_expressn)",
    "docstring": "Parses the declaration section of the WDL task AST subtree.\n\n        Examples:\n\n        String my_name\n        String your_name\n        Int two_chains_i_mean_names = 0\n\n        :param declaration_subAST: Some subAST representing a task declaration\n                                   like: 'String file_name'\n        :return: var_name, var_type, var_value\n            Example:\n                Input subAST representing:   'String file_name'\n                Output:  var_name='file_name', var_type='String', var_value=None"
  },
  {
    "code": "def filter_dirs(root, dirs, excl_paths):\n    filtered_dirs = []\n    for dirpath in dirs:\n        abspath = os.path.abspath(os.path.join(root, dirpath))\n        if os.path.basename(abspath) in _SKIP_DIRS:\n            continue\n        if abspath not in excl_paths:\n            filtered_dirs.append(dirpath)\n    return filtered_dirs",
    "docstring": "Filter directory paths based on the exclusion rules defined in\n    'excl_paths'."
  },
  {
    "code": "def en_last(self):\n        last_ens = dict()\n        for (k,l) in self.en.items():\n            last_ens.update({ k : l[-1] if l != [] else None })\n        return last_ens",
    "docstring": "Report the energies from the last SCF present in the output.\n\n        Returns a |dict| providing the various energy values from the\n        last SCF cycle performed in the output. Keys are those of\n        :attr:`~opan.output.OrcaOutput.p_en`.\n        Any energy value not relevant to the parsed\n        output is assigned as |None|.\n\n        Returns\n        -------\n        last_ens\n            |dict| of |npfloat_|--\n            Energies from the last SCF present in the output."
  },
  {
    "code": "def glover_dispersion_derivative(tr, oversampling=50, time_length=32.,\n                                 onset=0.):\n    dd = .01\n    dhrf = 1. / dd * (\n        - _gamma_difference_hrf(\n            tr, oversampling, time_length, onset,\n            delay=6, undershoot=12., dispersion=.9 + dd, ratio=.35)\n        + _gamma_difference_hrf(\n            tr, oversampling, time_length, onset, delay=6, undershoot=12.,\n            dispersion=.9, ratio=.35))\n    return dhrf",
    "docstring": "Implementation of the Glover dispersion derivative hrf model\n\n    Parameters\n    ----------\n    tr: float\n        scan repeat time, in seconds\n\n    oversampling: int, optional\n        temporal oversampling factor in seconds\n\n    time_length: float, optional\n        hrf kernel length, in seconds\n\n    onset : float, optional\n        onset of the response in seconds\n\n    Returns\n    -------\n    dhrf: array of shape(length / tr * oversampling), dtype=float\n          dhrf sampling on the oversampled time grid"
  },
  {
    "code": "def context(names):\n    import json\n    contexts = [_context_json(name) for name in set(names)]\n    if contexts:\n        click.echo(\n            json.dumps(\n                contexts[0] if len(contexts) == 1 else contexts,\n                indent=2,\n            )\n        )",
    "docstring": "Show JSON-LD context for repository objects."
  },
  {
    "code": "def fromarray(A):\n    subs = np.nonzero(A)\n    vals = A[subs]\n    return sptensor(subs, vals, shape=A.shape, dtype=A.dtype)",
    "docstring": "Create a sptensor from a dense numpy array"
  },
  {
    "code": "def force_log_type_file_flag(self, logType, flag):\n        assert logType in self.__logTypeStdoutFlags.keys(), \"logType '%s' not defined\" %logType\n        if flag is None:\n            self.__forcedFileLevels.pop(logType, None)\n            self.__update_file_flags()\n        else:\n            assert isinstance(flag, bool), \"flag must be boolean\"\n            self.__logTypeFileFlags[logType] = flag\n            self.__forcedFileLevels[logType] = flag",
    "docstring": "Force a logtype file logging flag despite minimum and maximum logging level boundaries.\n\n        :Parameters:\n           #. logType (string): A defined logging type.\n           #. flag (None, boolean): The file logging flag.\n              If None, logtype existing forced flag is released."
  },
  {
    "code": "def get_sensor_descriptions(self):\n        self.init_sdr()\n        for sensor in self._sdr.get_sensor_numbers():\n            yield {'name': self._sdr.sensors[sensor].name,\n                   'type': self._sdr.sensors[sensor].sensor_type}\n        self.oem_init()\n        for sensor in self._oem.get_sensor_descriptions():\n            yield sensor",
    "docstring": "Get available sensor names\n\n        Iterates over the available sensor descriptions\n\n        :returns: Iterator of dicts describing each sensor"
  },
  {
    "code": "def sanitize_word(s):\n    s = re.sub('[^\\w-]+', '_', s)\n    s = re.sub('__+', '_', s)\n    return s.strip('_')",
    "docstring": "Remove non-alphanumerical characters from metric word.\n    And trim excessive underscores."
  },
  {
    "code": "def _initialize():\n  global _absl_logger, _absl_handler\n  if _absl_logger:\n    return\n  original_logger_class = logging.getLoggerClass()\n  logging.setLoggerClass(ABSLLogger)\n  _absl_logger = logging.getLogger('absl')\n  logging.setLoggerClass(original_logger_class)\n  python_logging_formatter = PythonFormatter()\n  _absl_handler = ABSLHandler(python_logging_formatter)\n  handlers = [\n      h for h in logging.root.handlers\n      if isinstance(h, logging.StreamHandler) and h.stream == sys.stderr]\n  for h in handlers:\n    logging.root.removeHandler(h)\n  if not logging.root.handlers:\n    logging.root.addHandler(_absl_handler)",
    "docstring": "Initializes loggers and handlers."
  },
  {
    "code": "def as_dict(self, replace_value_names=True):\n        old_children = self.children\n        self.children = self.terms\n        d = super(SectionTerm, self).as_dict(replace_value_names)\n        self.children = old_children\n        return d",
    "docstring": "Return the whole section as a dict"
  },
  {
    "code": "def request(self, hash_, quickkey, doc_type, page=None,\n                output=None, size_id=None, metadata=None,\n                request_conversion_only=None):\n        if len(hash_) > 4:\n            hash_ = hash_[:4]\n        query = QueryParams({\n            'quickkey': quickkey,\n            'doc_type': doc_type,\n            'page': page,\n            'output': output,\n            'size_id': size_id,\n            'metadata': metadata,\n            'request_conversion_only': request_conversion_only\n        })\n        url = API_ENDPOINT + '?' + hash_ + '&' + urlencode(query)\n        response = self.http.get(url, stream=True)\n        if response.status_code == 204:\n            raise ConversionServerError(\"Unable to fulfill request. \"\n                                        \"The document will not be converted.\",\n                                        response.status_code)\n        response.raise_for_status()\n        if response.headers['content-type'] == 'application/json':\n            return response.json()\n        return response",
    "docstring": "Query conversion server\n\n        hash_: 4 characters of file hash\n        quickkey: File quickkey\n        doc_type: \"i\" for image, \"d\" for documents\n        page: The page to convert. If page is set to 'initial', the first\n              10 pages of the document will be provided. (document)\n        output: \"pdf\", \"img\", or \"swf\" (document)\n        size_id: 0,1,2 (document)\n                 0-9, a-f, z (image)\n        metadata: Set to 1 to get metadata dict\n        request_conversion_only: Request conversion w/o content"
  },
  {
    "code": "def _round_field(values, name, freq):\n    if isinstance(values, dask_array_type):\n        from dask.array import map_blocks\n        return map_blocks(_round_series,\n                          values, name, freq=freq, dtype=np.datetime64)\n    else:\n        return _round_series(values, name, freq)",
    "docstring": "Indirectly access pandas rounding functions by wrapping data\n    as a Series and calling through `.dt` attribute.\n\n    Parameters\n    ----------\n    values : np.ndarray or dask.array-like\n        Array-like container of datetime-like values\n    name : str (ceil, floor, round)\n        Name of rounding function\n    freq : a freq string indicating the rounding resolution\n\n    Returns\n    -------\n    rounded timestamps : same type as values\n        Array-like of datetime fields accessed for each element in values"
  },
  {
    "code": "def knapsack(items, maxweight, method='recursive'):\n    r\n    if method == 'recursive':\n        return knapsack_recursive(items, maxweight)\n    elif method == 'iterative':\n        return knapsack_iterative(items, maxweight)\n    elif method == 'ilp':\n        return knapsack_ilp(items, maxweight)\n    else:\n        raise NotImplementedError('[util_alg] knapsack method=%r' % (method,))",
    "docstring": "r\"\"\"\n    Solve the knapsack problem by finding the most valuable subsequence of\n    `items` subject that weighs no more than `maxweight`.\n\n    Args:\n        items (tuple): is a sequence of tuples `(value, weight, id_)`, where\n            `value` is a number and `weight` is a non-negative integer, and\n            `id_` is an item identifier.\n\n        maxweight (scalar):  is a non-negative integer.\n\n    Returns:\n        tuple: (total_value, items_subset) - a pair whose first element is the\n            sum of values in the most valuable subsequence, and whose second\n            element is the subsequence. Subset may be different depending on\n            implementation (ie top-odwn recusrive vs bottom-up iterative)\n\n    References:\n        http://codereview.stackexchange.com/questions/20569/dynamic-programming-solution-to-knapsack-problem\n        http://stackoverflow.com/questions/141779/solving-the-np-complete-problem-in-xkcd\n        http://www.es.ele.tue.nl/education/5MC10/Solutions/knapsack.pdf\n\n    CommandLine:\n        python -m utool.util_alg --test-knapsack\n\n        python -m utool.util_alg --test-knapsack:0\n        python -m utool.util_alg --exec-knapsack:1\n\n    Ignore:\n        annots_per_view = 2\n        maxweight = 2\n        items = [\n            (0.7005208343554686, 0.7005208343554686, 0),\n            (0.669270834329427, 0.669270834329427, 1),\n            (0.669270834329427, 0.669270834329427, 2),\n            (0.7005208343554686, 0.7005208343554686, 3),\n            (0.7005208343554686, 0.7005208343554686, 4),\n            (0.669270834329427, 0.669270834329427, 5),\n            (0.669270834329427, 0.669270834329427, 6),\n            (0.669270834329427, 0.669270834329427, 7),\n            (0.669270834329427, 0.669270834329427, 8),\n            (0.669270834329427, 0.669270834329427, 9),\n            (0.669270834329427, 0.669270834329427, 10),\n            (0.669270834329427, 0.669270834329427, 11),\n            (0.669270834329427, 0.669270834329427, 12),\n            (0.669270834329427, 0.669270834329427, 13),\n            (0.669270834329427, 0.669270834329427, 14),\n            (0.669270834329427, 0.669270834329427, 15),\n            (0.669270834329427, 0.669270834329427, 16),\n            (0.669270834329427, 0.669270834329427, 17),\n            (0.7005208343554686, 0.7005208343554686, 18),\n            (0.7005208343554686, 0.7005208343554686, 19),\n            (0.669270834329427, 0.669270834329427, 20),\n            (0.7005208343554686, 0.7005208343554686, 21),\n            (0.669270834329427, 0.669270834329427, 22),\n            (0.669270834329427, 0.669270834329427, 23),\n            (0.669270834329427, 0.669270834329427, 24),\n            (0.669270834329427, 0.669270834329427, 25),\n            (0.669270834329427, 0.669270834329427, 26),\n            (0.669270834329427, 0.669270834329427, 27),\n            (0.669270834329427, 0.669270834329427, 28),\n            (0.7005208343554686, 0.7005208343554686, 29),\n            (0.669270834329427, 0.669270834329427, 30),\n            (0.669270834329427, 0.669270834329427, 31),\n            (0.669270834329427, 0.669270834329427, 32),\n            (0.669270834329427, 0.669270834329427, 33),\n            (0.7005208343554686, 0.7005208343554686, 34),\n            (0.669270834329427, 0.669270834329427, 35),\n            (0.669270834329427, 0.669270834329427, 36),\n            (0.669270834329427, 0.669270834329427, 37),\n            (0.7005208343554686, 0.7005208343554686, 38),\n            (0.669270834329427, 0.669270834329427, 39),\n            (0.669270834329427, 0.669270834329427, 40),\n            (0.7005208343554686, 0.7005208343554686, 41),\n            (0.669270834329427, 0.669270834329427, 42),\n            (0.669270834329427, 0.669270834329427, 43),\n            (0.669270834329427, 0.669270834329427, 44),\n        ]\n        values = ut.take_column(items, 0)\n        weights = ut.take_column(items, 1)\n        indices = ut.take_column(items, 2)\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_alg import *  # NOQA\n        >>> import utool as ut\n        >>> items = [(4, 12, 0), (2, 1, 1), (6, 4, 2), (1, 1, 3), (2, 2, 4)]\n        >>> maxweight = 15\n        >>> total_value, items_subset = knapsack(items, maxweight, method='recursive')\n        >>> total_value1, items_subset1 = knapsack(items, maxweight, method='iterative')\n        >>> result =  'total_value = %.2f\\n' % (total_value,)\n        >>> result += 'items_subset = %r' % (items_subset,)\n        >>> ut.assert_eq(total_value1, total_value)\n        >>> ut.assert_eq(items_subset1, items_subset)\n        >>> print(result)\n        total_value = 11.00\n        items_subset = [(2, 1, 1), (6, 4, 2), (1, 1, 3), (2, 2, 4)]\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_alg import *  # NOQA\n        >>> import utool as ut\n        >>> # Solve https://xkcd.com/287/\n        >>> weights = [2.15, 2.75, 3.35, 3.55, 4.2, 5.8] * 2\n        >>> items = [(w, w, i) for i, w in enumerate(weights)]\n        >>> maxweight = 15.05\n        >>> total_value, items_subset = knapsack(items, maxweight, method='recursive')\n        >>> total_value1, items_subset1 = knapsack(items, maxweight, method='iterative')\n        >>> total_weight = sum([t[1] for t in items_subset])\n        >>> print('total_weight = %r' % (total_weight,))\n        >>> result =  'total_value = %.2f' % (total_value,)\n        >>> print('items_subset = %r' % (items_subset,))\n        >>> print('items_subset1 = %r' % (items_subset1,))\n        >>> #assert items_subset1 == items_subset, 'NOT EQ\\n%r !=\\n%r' % (items_subset1, items_subset)\n        >>> print(result)\n        total_value = 15.05\n\n    Timeit:\n        >>> import utool as ut\n        >>> setup = ut.codeblock(\n        >>>     '''\n                import utool as ut\n                weights = [215, 275, 335, 355, 42, 58] * 40\n                items = [(w, w, i) for i, w in enumerate(weights)]\n                maxweight = 2505\n                #import numba\n                #knapsack_numba = numba.autojit(ut.knapsack_iterative)\n                #knapsack_numba = numba.autojit(ut.knapsack_iterative_numpy)\n                ''')\n        >>> # Test load time\n        >>> stmt_list1 = ut.codeblock(\n        >>>     '''\n                #ut.knapsack_recursive(items, maxweight)\n                ut.knapsack_iterative(items, maxweight)\n                ut.knapsack_ilp(items, maxweight)\n                #knapsack_numba(items, maxweight)\n                #ut.knapsack_iterative_numpy(items, maxweight)\n                ''').split('\\n')\n        >>> ut.util_dev.timeit_compare(stmt_list1, setup, int(5))"
  },
  {
    "code": "def commit_pushdb(self, coordinates, postscript=None):\n    self.scm.commit('pants build committing publish data for push of {coordinates}'\n                    '{postscript}'.format(coordinates=coordinates, postscript=postscript or ''),\n                    verify=self.get_options().verify_commit)",
    "docstring": "Commit changes to the pushdb with a message containing the provided coordinates."
  },
  {
    "code": "def file_get_contents(self, path):\n        with open(self.get_full_file_path(path), 'r') as f: return  f.read()",
    "docstring": "Returns contents of file located at 'path', not changing FS so does\n        not require journaling"
  },
  {
    "code": "def getUserInfo(self):\n        userJson = self.httpGet(ReaderUrl.USER_INFO_URL)\n        result = json.loads(userJson, strict=False)\n        self.userId = result['userId']\n        return result",
    "docstring": "Returns a dictionary of user info that google stores."
  },
  {
    "code": "def _learn(connections, rng, learningSegments, activeInput,\n             potentialOverlaps, initialPermanence, sampleSize,\n             permanenceIncrement, permanenceDecrement, maxSynapsesPerSegment):\n    connections.adjustSynapses(learningSegments, activeInput,\n                               permanenceIncrement, -permanenceDecrement)\n    if sampleSize == -1:\n      maxNew = len(activeInput)\n    else:\n      maxNew = sampleSize - potentialOverlaps[learningSegments]\n    if maxSynapsesPerSegment != -1:\n      synapseCounts = connections.mapSegmentsToSynapseCounts(\n        learningSegments)\n      numSynapsesToReachMax = maxSynapsesPerSegment - synapseCounts\n      maxNew = np.where(maxNew <= numSynapsesToReachMax,\n                        maxNew, numSynapsesToReachMax)\n    connections.growSynapsesToSample(learningSegments, activeInput,\n                                     maxNew, initialPermanence, rng)",
    "docstring": "Adjust synapse permanences, grow new synapses, and grow new segments.\n\n    @param learningActiveSegments (numpy array)\n    @param learningMatchingSegments (numpy array)\n    @param segmentsToPunish (numpy array)\n    @param activeInput (numpy array)\n    @param potentialOverlaps (numpy array)"
  },
  {
    "code": "def read_xml_file(self, xml_file):\n        assert self.__config is not None\n        ffname = self.__file_full_name(xml_file)\n        self.logger.debug(\"Reading xml file: [%s]\", xml_file)\n        decls = self.__dcache.cached_value(ffname, self.__config)\n        if not decls:\n            self.logger.debug(\"File has not been found in cache, parsing...\")\n            decls, _ = self.__parse_xml_file(ffname)\n            self.__dcache.update(ffname, self.__config, decls, [])\n        else:\n            self.logger.debug(\n                \"File has not been changed, reading declarations from cache.\")\n        return decls",
    "docstring": "Read generated XML file.\n\n        :param xml_file: path to xml file\n        :type xml_file: str\n\n        :rtype: declarations tree"
  },
  {
    "code": "def public_dsn(dsn):\n    m = RE_DSN.match(dsn)\n    if not m:\n        log.error('Unable to parse Sentry DSN')\n    public = '{scheme}://{client_id}@{domain}/{site_id}'.format(\n        **m.groupdict())\n    return public",
    "docstring": "Transform a standard Sentry DSN into a public one"
  },
  {
    "code": "def events_log(self, details=False, count=0, timestamp=0):\n        if not count:\n            count = 1 + int(os.environ.get('ALIGNAK_EVENTS_LOG_COUNT',\n                                           self.app.conf.events_log_count))\n        count = int(count)\n        timestamp = float(timestamp)\n        logger.debug('Get max %d events, newer than %s out of %d',\n                     count, timestamp, len(self.app.recent_events))\n        res = []\n        for log in reversed(self.app.recent_events):\n            if timestamp and timestamp > log['timestamp']:\n                break\n            if not count:\n                break\n            if details:\n                res.append(log)\n            else:\n                res.append(\"%s - %s - %s\"\n                           % (log['date'], log['level'][0].upper(), log['message']))\n        logger.debug('Got %d events', len(res))\n        return res",
    "docstring": "Get the most recent Alignak events\n\n        If count is specifies it is the maximum number of events to return.\n\n        If timestamp is specified, events older than this timestamp will not be returned\n\n        The arbiter maintains a list of the most recent Alignak events. This endpoint\n        provides this list.\n\n        The default format is:\n        [\n            \"2018-07-23 15:14:43 - E - SERVICE NOTIFICATION: guest;host_0;dummy_random;CRITICAL;1;\n            notify-service-by-log;Service internal check result: 2\",\n            \"2018-07-23 15:14:43 - E - SERVICE NOTIFICATION: admin;host_0;dummy_random;CRITICAL;1;\n            notify-service-by-log;Service internal check result: 2\",\n            \"2018-07-23 15:14:42 - E - SERVICE ALERT: host_0;dummy_critical;CRITICAL;SOFT;1;\n            host_0-dummy_critical-2\",\n            \"2018-07-23 15:14:42 - E - SERVICE ALERT: host_0;dummy_random;CRITICAL;HARD;2;\n            Service internal check result: 2\",\n            \"2018-07-23 15:14:42 - I - SERVICE ALERT: host_0;dummy_unknown;UNKNOWN;HARD;2;\n            host_0-dummy_unknown-3\"\n        ]\n\n        If you request on this endpoint with the *details* parameter (whatever its value...),\n        you will get a detailed JSON output:\n        [\n            {\n                timestamp: 1535517701.1817362,\n                date: \"2018-07-23 15:16:35\",\n                message: \"SERVICE ALERT: host_11;dummy_echo;UNREACHABLE;HARD;2;\",\n                level: \"info\"\n            },\n            {\n                timestamp: 1535517701.1817362,\n                date: \"2018-07-23 15:16:32\",\n                message: \"SERVICE NOTIFICATION: guest;host_0;dummy_random;OK;0;\n                        notify-service-by-log;Service internal check result: 0\",\n                level: \"info\"\n            },\n            {\n                timestamp: 1535517701.1817362,\n                date: \"2018-07-23 15:16:32\",\n                message: \"SERVICE NOTIFICATION: admin;host_0;dummy_random;OK;0;\n                        notify-service-by-log;Service internal check result: 0\",\n                level: \"info\"\n            },\n            {\n                timestamp: 1535517701.1817362,\n                date: \"2018-07-23 15:16:32\",\n                message: \"SERVICE ALERT: host_0;dummy_random;OK;HARD;2;\n                        Service internal check result: 0\",\n                level: \"info\"\n            },\n            {\n                timestamp: 1535517701.1817362,\n                date: \"2018-07-23 15:16:19\",\n                message: \"SERVICE ALERT: host_11;dummy_random;OK;HARD;2;\n                        Service internal check result: 0\",\n                level: \"info\"\n            }\n        ]\n\n        In this example, only the 5 most recent events are provided whereas the default value is\n        to provide the 100 last events. This default counter may be changed thanks to the\n        ``events_log_count`` configuration variable or\n        ``ALIGNAK_EVENTS_LOG_COUNT`` environment variable.\n\n        The date format may also be changed thanks to the ``events_date_format`` configuration\n        variable.\n\n        :return: list of the most recent events\n        :rtype: list"
  },
  {
    "code": "def gen_support_records(transaction_manager, min_support, **kwargs):\n    max_length = kwargs.get('max_length')\n    _create_next_candidates = kwargs.get(\n        '_create_next_candidates', create_next_candidates)\n    candidates = transaction_manager.initial_candidates()\n    length = 1\n    while candidates:\n        relations = set()\n        for relation_candidate in candidates:\n            support = transaction_manager.calc_support(relation_candidate)\n            if support < min_support:\n                continue\n            candidate_set = frozenset(relation_candidate)\n            relations.add(candidate_set)\n            yield SupportRecord(candidate_set, support)\n        length += 1\n        if max_length and length > max_length:\n            break\n        candidates = _create_next_candidates(relations, length)",
    "docstring": "Returns a generator of support records with given transactions.\n\n    Arguments:\n        transaction_manager -- Transactions as a TransactionManager instance.\n        min_support -- A minimum support (float).\n\n    Keyword arguments:\n        max_length -- The maximum length of relations (integer)."
  },
  {
    "code": "def mark_failed(self, dispatch, error_log):\n        dispatch.error_log = error_log\n        self._st['failed'].append(dispatch)",
    "docstring": "Marks a dispatch as failed.\n\n        Sitemessage won't try to deliver already failed messages.\n\n        Should be used within send().\n\n        :param Dispatch dispatch: a Dispatch\n        :param str error_log: str - error message"
  },
  {
    "code": "def save(self):\n        try:\n            response = requests.post(self._upload_url,\n                                     auth=self.jss.session.auth,\n                                     verify=self.jss.session.verify,\n                                     files=self.resource)\n        except JSSPostError as error:\n            if error.status_code == 409:\n                raise JSSPostError(error)\n            else:\n                raise JSSMethodNotAllowedError(self.__class__.__name__)\n        if response.status_code == 201:\n            if self.jss.verbose:\n                print \"POST: Success\"\n                print response.text.encode(\"utf-8\")\n        elif response.status_code >= 400:\n            error_handler(JSSPostError, response)",
    "docstring": "POST the object to the JSS."
  },
  {
    "code": "def time_to_sec(time_str: str) -> int:\n    total_sec = 0\n    if '-' in time_str:\n        days, time_str = time_str.split('-')\n        total_sec += (int(days) * 24 * 60 * 60)\n    hours_min_raw = time_str.split(':')[:-1]\n    time_parts = [int(round(float(val))) for val in hours_min_raw]\n    total_sec += time_parts[-1] * 60\n    if len(time_parts) > 1:\n        total_sec += time_parts[-2] * 60 * 60\n    return total_sec",
    "docstring": "Convert time in string format to seconds.\n\n    Skipping seconds since sometimes the last column is truncated\n    for entries where >10 days."
  },
  {
    "code": "def register_post_processor(func):\n    global POST_PROCESSORS\n    key = func.__name__\n    POST_PROCESSORS[key] = func\n    return func",
    "docstring": "Register a post processor function to be run as the final step in\n    serialization. The data passed in will already have gone through the\n    sideloading processor.\n\n    Usage:\n        @register_post_processor\n        def my_post_processor(data):\n            # do stuff with `data`\n            return data"
  },
  {
    "code": "def ConsultarRemito(self, cod_remito=None, id_req=None,\n                        tipo_comprobante=None, punto_emision=None, nro_comprobante=None):\n        \"Obtener los datos de un remito generado\"\n        print(self.client.help(\"consultarRemito\"))\n        response = self.client.consultarRemito(\n                                authRequest={'token': self.Token, 'sign': self.Sign, 'cuitRepresentada': self.Cuit},\n                                codRemito=cod_remito,\n                                idReq=id_req,\n                                tipoComprobante=tipo_comprobante,\n                                puntoEmision=punto_emision,\n                                nroComprobante=nro_comprobante)\n        ret = response.get(\"consultarRemitoReturn\", {})\n        id_req = ret.get(\"idReq\", 0)\n        self.remito = rec = ret.get(\"remito\", {})\n        self.__analizar_errores(ret)\n        self.__analizar_observaciones(ret)\n        self.__analizar_evento(ret)\n        self.AnalizarRemito(rec)\n        return id_req",
    "docstring": "Obtener los datos de un remito generado"
  },
  {
    "code": "def plot(config, image, file):\n    image = np.squeeze(image)\n    print(file, image.shape)\n    imsave(file, image)",
    "docstring": "Plot a single CIFAR image."
  },
  {
    "code": "def find_by_username(self, username):\n        data = (db.select(self.table).select('username', 'email', 'real_name',\n                                             'password', 'bio', 'status', 'role', 'uid').\n                condition('username', username).execute()\n                )\n        if data:\n            return self.load(data[0], self.model)",
    "docstring": "Return user by username if find in database otherwise None"
  },
  {
    "code": "def _mask_space(self, data):\n        geomask = get_geostationary_mask(area=self.area)\n        return data.where(geomask)",
    "docstring": "Mask space pixels"
  },
  {
    "code": "def template_name(self, path, base):\n        if not base:\n            path = os.path.basename(path)\n        if path == base:\n            base = os.path.dirname(path)\n        name = re.sub(r\"^%s[\\/\\\\]?(.*)%s$\" % (\n            re.escape(base), re.escape(settings.TEMPLATE_EXT)\n        ), r\"\\1\", path)\n        return re.sub(r\"[\\/\\\\]\", settings.TEMPLATE_SEPARATOR, name)",
    "docstring": "Find out the name of a JS template"
  },
  {
    "code": "def _scrub_method_name(self, method_name):\n        if method_name not in self._scrubbed_method_names:\n            self._scrubbed_method_names[method_name] = (\n                scrub_method_name(method_name))\n        return self._scrubbed_method_names[method_name]",
    "docstring": "Scrubs a method name, returning result from local cache if available.\n\n        This method wraps fitparse.utils.scrub_method_name and memoizes results,\n        as scrubbing a method name is expensive.\n\n        Args:\n            method_name: Method name to scrub.\n\n        Returns:\n            Scrubbed method name."
  },
  {
    "code": "def fit_cmd(argv=sys.argv[1:]):\n    arguments = docopt(fit_cmd.__doc__, argv=argv)\n    no_save = arguments['--no-save']\n    no_activate = arguments['--no-activate']\n    save_if_better_than = arguments['--save-if-better-than']\n    evaluate = arguments['--evaluate'] or bool(save_if_better_than)\n    if save_if_better_than is not None:\n        save_if_better_than = float(save_if_better_than)\n    initialize_config(__mode__='fit')\n    fit(\n        persist=not no_save,\n        activate=not no_activate,\n        evaluate=evaluate,\n        persist_if_better_than=save_if_better_than,\n        )",
    "docstring": "\\\nFit a model and save to database.\n\nWill use 'dataset_loader_train', 'model', and 'model_perister' from\nthe configuration file, to load a dataset to train a model with, and\npersist it.\n\nUsage:\n  pld-fit [options]\n\nOptions:\n  -n --no-save              Don't persist the fitted model to disk.\n\n  --no-activate             Don't activate the fitted model.\n\n  --save-if-better-than=<k> Persist only if test score better than given\n                            value.\n\n  -e --evaluate             Evaluate fitted model on train and test set and\n                            print out results.\n\n  -h --help                 Show this screen."
  },
  {
    "code": "def wrapped_object(self, LayoutClass, fields, *args, **kwargs):\n        if args:\n            if isinstance(fields, list):\n                fields = tuple(fields)\n            else:\n                fields = (fields,)\n            if LayoutClass in self.args_first:\n                arguments = args + fields\n            else:\n                arguments = fields + args\n            return LayoutClass(*arguments, **kwargs)\n        else:\n            if isinstance(fields, list):\n                return LayoutClass(*fields, **kwargs)\n            else:\n                return LayoutClass(fields, **kwargs)",
    "docstring": "Returns a layout object of type `LayoutClass` with `args` and `kwargs` that\n        wraps `fields` inside."
  },
  {
    "code": "def clean_history(self, widget, event=None):\n        self.history_tree_store.clear()\n        selected_sm_m = self.model.get_selected_state_machine_model()\n        if selected_sm_m:\n            if state_machine_execution_engine.finished_or_stopped():\n                selected_sm_m.state_machine.destroy_execution_histories()\n                self.update()",
    "docstring": "Triggered when the 'Clean History' button is clicked.\n\n        Empties the execution history tree by adjusting the start index and updates tree store and view."
  },
  {
    "code": "def initialize_simulation_from_model_specification(model_specification_file: str) -> InteractiveContext:\n    model_specification = build_model_specification(model_specification_file)\n    plugin_config = model_specification.plugins\n    component_config = model_specification.components\n    simulation_config = model_specification.configuration\n    plugin_manager = PluginManager(plugin_config)\n    component_config_parser = plugin_manager.get_plugin('component_configuration_parser')\n    components = component_config_parser.get_components(component_config)\n    return InteractiveContext(simulation_config, components, plugin_manager)",
    "docstring": "Construct a simulation from a model specification file.\n\n    The simulation context returned by this method still needs to be setup by\n    calling its setup method. It is mostly useful for testing and debugging.\n\n    Parameters\n    ----------\n    model_specification_file\n        The path to a model specification file.\n\n    Returns\n    -------\n        An initialized (but not set up) simulation context."
  },
  {
    "code": "def _listdir(pth, extensions):\n    try:\n        return [fname for fname in os.listdir(pth)\n                if os.path.splitext(fname)[1] in extensions]\n    except OSError:\n        pass",
    "docstring": "Non-raising listdir."
  },
  {
    "code": "def transformer_base_vq_ada_32ex_packed():\n  hparams = transformer_base_v2()\n  expert_utils.update_hparams_for_vq_gating(hparams)\n  hparams.moe_num_experts = 32\n  hparams.gating_type = \"vq\"\n  hparams.batch_size = 5072\n  hparams.ffn_layer = \"local_moe\"\n  hparams.shared_embedding_and_softmax_weights = False\n  hparams.learning_rate_warmup_steps = 10000\n  hparams.learning_rate_decay_steps = 27200\n  hparams.num_heads = 4\n  hparams.num_blocks = 1\n  hparams.moe_k = 1\n  hparams.num_decoder_layers = 6\n  hparams.label_smoothing = 0.\n  hparams.layer_prepostprocess_dropout = 0.1\n  hparams.layer_postprocess_sequence = \"dan\"\n  hparams.layer_preprocess_sequence = \"none\"\n  hparams.weight_decay = 1e-06\n  hparams.attention_dropout = 0.1\n  hparams.optimizer = \"Adafactor\"\n  hparams.learning_rate_schedule = \"linear_warmup*rsqrt_decay*linear_decay\"\n  hparams.activation_dtype = \"float32\"\n  hparams.learning_rate = 0.1\n  hparams.learning_rate_constant = 1.0\n  return hparams",
    "docstring": "Set of hyperparameters for lm1b packed following tpu params."
  },
  {
    "code": "def jinja_block_as_fragment_extension(name, tagname=None, classname=None):\n    if tagname is None:\n        tagname = name\n    if classname is None:\n        classname = \"%sBlockFragmentExtension\" % name.capitalize()\n    return type(classname, (BaseJinjaBlockAsFragmentExtension,), {\n        \"tags\": set([tagname]), \"end_tag\": \"end\" + tagname, \"block_name\": name})",
    "docstring": "Creates a fragment extension which will just act as a replacement of the\n    block statement."
  },
  {
    "code": "def site_url(url):\n    base_url = 'http://%s' % socket.gethostname()\n    if server.port is not 80:\n        base_url += ':%d' % server.port\n    return urlparse.urljoin(base_url, url)",
    "docstring": "Determine the server URL."
  },
  {
    "code": "def records(self):\n        output = tempfile.NamedTemporaryFile(suffix='.json')\n        try:\n            log.info(\"Loading table from (%s)...\", self._obj)\n            shutil.copyfileobj(self.fh(), output)\n            output.seek(0)\n            for line in output.file:\n                yield json.loads(line, object_hook=json_hook)\n        finally:\n            try:\n                output.close()\n            except:\n                pass",
    "docstring": "Get each record that has been stored in the table."
  },
  {
    "code": "def multipoint(self, points):\r\n        shapeType = MULTIPOINT\r\n        points = [points]\n        self._shapeparts(parts=points, shapeType=shapeType)",
    "docstring": "Creates a MULTIPOINT shape.\r\n        Points is a list of xy values."
  },
  {
    "code": "def _canonicalize_name(prefix, qvm_type, noisy):\n    if noisy:\n        noise_suffix = '-noisy'\n    else:\n        noise_suffix = ''\n    if qvm_type is None:\n        qvm_suffix = ''\n    elif qvm_type == 'qvm':\n        qvm_suffix = '-qvm'\n    elif qvm_type == 'pyqvm':\n        qvm_suffix = '-pyqvm'\n    else:\n        raise ValueError(f\"Unknown qvm_type {qvm_type}\")\n    name = f'{prefix}{noise_suffix}{qvm_suffix}'\n    return name",
    "docstring": "Take the output of _parse_name to create a canonical name."
  },
  {
    "code": "def main(self, args):\n        if args.action:\n            self.runcmd(args.action, args.arguments)\n        else:\n            self.cmdloop()",
    "docstring": "Run a single command, or else the main shell loop.\n\n        `args` should be the :class:`argparse.Namespace` object after\n        being set up via :meth:`add_arguments`."
  },
  {
    "code": "def elementMaker(name, *children, **attrs):\n    formattedAttrs = ' '.join('{}={}'.format(key, _gvquote(str(value)))\n                              for key, value in sorted(attrs.items()))\n    formattedChildren = ''.join(children)\n    return u'<{name} {attrs}>{children}</{name}>'.format(\n        name=name,\n        attrs=formattedAttrs,\n        children=formattedChildren)",
    "docstring": "Construct a string from the HTML element description."
  },
  {
    "code": "def logger():\n    scriptlogger = logging.getLogger(__program__)\n    if not scriptlogger.hasHandlers():\n        scriptlogger.setLevel(logging.INFO)\n        fmt = '%(name)s:%(levelname)s: %(message)s'\n        streamhandler = logging.StreamHandler()\n        streamhandler.setFormatter(logging.Formatter(fmt))\n        scriptlogger.addHandler(streamhandler)",
    "docstring": "Configure program logger."
  },
  {
    "code": "def render(self, template_name, __data=None, **kw):\n        return self.template.render(template_name,\n                                    **self._vars(__data, **kw))",
    "docstring": "Given a template name and template data.\n        Renders a template and returns as string"
  },
  {
    "code": "def replace(self, to_replace, value, inplace=False, filter=None,\n                regex=False, convert=True):\n        inplace = validate_bool_kwarg(inplace, 'inplace')\n        original_to_replace = to_replace\n        try:\n            values, to_replace = self._try_coerce_args(self.values,\n                                                       to_replace)\n            mask = missing.mask_missing(values, to_replace)\n            if filter is not None:\n                filtered_out = ~self.mgr_locs.isin(filter)\n                mask[filtered_out.nonzero()[0]] = False\n            blocks = self.putmask(mask, value, inplace=inplace)\n            if convert:\n                blocks = [b.convert(by_item=True, numeric=False,\n                                    copy=not inplace) for b in blocks]\n            return blocks\n        except (TypeError, ValueError):\n            if is_object_dtype(self):\n                raise\n            block = self.astype(object)\n            return block.replace(to_replace=original_to_replace,\n                                 value=value,\n                                 inplace=inplace,\n                                 filter=filter,\n                                 regex=regex,\n                                 convert=convert)",
    "docstring": "replace the to_replace value with value, possible to create new\n        blocks here this is just a call to putmask. regex is not used here.\n        It is used in ObjectBlocks.  It is here for API compatibility."
  },
  {
    "code": "def Platform(name = platform_default()):\n    module = platform_module(name)\n    spec = PlatformSpec(name, module.generate)\n    return spec",
    "docstring": "Select a canned Platform specification."
  },
  {
    "code": "def jamo_to_hangul(lead, vowel, tail=''):\n    lead = hcj_to_jamo(lead, \"lead\")\n    vowel = hcj_to_jamo(vowel, \"vowel\")\n    if not tail or ord(tail) == 0:\n        tail = None\n    elif is_hcj(tail):\n        tail = hcj_to_jamo(tail, \"tail\")\n    if (is_jamo(lead) and get_jamo_class(lead) == \"lead\") and\\\n       (is_jamo(vowel) and get_jamo_class(vowel) == \"vowel\") and\\\n       ((not tail) or (is_jamo(tail) and get_jamo_class(tail) == \"tail\")):\n        result = _jamo_to_hangul_char(lead, vowel, tail)\n        if is_hangul_char(result):\n            return result\n    raise InvalidJamoError(\"Could not synthesize characters to Hangul.\",\n                           '\\x00')",
    "docstring": "Return the Hangul character for the given jamo input.\n    Integers corresponding to U+11xx jamo codepoints, U+11xx jamo characters,\n    or HCJ are valid inputs.\n\n    Outputs a one-character Hangul string.\n\n    This function is identical to j2h."
  },
  {
    "code": "def sample_string(self, individual=-1):\n        base = str(self)\n        extra = self.get_sample_info(individual=individual)\n        extra = [':'.join([str(j) for j in i]) for i in zip(*extra.values())]\n        return '\\t'.join([base, '\\t'.join(extra)])",
    "docstring": "Returns the VCF entry as it appears in the vcf file"
  },
  {
    "code": "def get_ladders_metadata(session, parsed):\n    ladders = {}\n    for ladder in parsed.find_all('a', href=re.compile(LADDER_URL_REGEX)):\n        ladders[ladder.text] = get_ladder_metadata(session, ladder['href'])\n    return ladders",
    "docstring": "Get metadata for all ladders."
  },
  {
    "code": "def find_pair(self, crypto=\"\", fiat=\"\", verbose=False):\n        self.fetch_pairs()\n        if not crypto and not fiat:\n            raise Exception(\"Fiat or Crypto required\")\n        def is_matched(crypto, fiat, pair):\n            if crypto and not fiat:\n                return pair.startswith(\"%s-\" % crypto)\n            if crypto and fiat:\n                return pair == \"%s-%s\" % (crypto, fiat)\n            if not crypto:\n                return pair.endswith(\"-%s\" % fiat)\n        matched_pairs = {}\n        for Service, pairs in self._all_pairs.items():\n            matched = [p for p in pairs if is_matched(crypto, fiat, p)]\n            if matched:\n                matched_pairs[Service] = matched\n        return matched_pairs",
    "docstring": "This utility is used to find an exchange that supports a given exchange pair."
  },
  {
    "code": "def _handle_key_value(t_dict, key, value):\n    if key in t_dict:\n        val = t_dict[key]\n        if isinstance(val, str):\n            val = [val]\n        val.append(value)\n        return val\n    return value",
    "docstring": "Function to handle key has multi value, and return the values as list."
  },
  {
    "code": "def payment(self, origin, destination, amount):\n        if type(amount) != Decimal:\n            amount = Decimal(amount)\n        if amount <= 0:\n            raise Exception(\"Amount must be a positive number\")\n        all_addresses = []\n        accounts = self.listaccounts()\n        if origin in accounts:\n            if destination in accounts:\n                with self.openwallet():\n                    result = self.move(origin, destination, amount)\n                return self.record_tx(origin, None, amount,\n                                      result, destination)\n            for account in accounts:\n                addresses = self.getaddressesbyaccount(account)\n                if destination in addresses:\n                    with self.openwallet():\n                        result = self.move(origin, account, amount)\n                    return self.record_tx(origin, destination, amount,\n                                          result, account)\n            else:\n                with self.openwallet():\n                    txhash = self.sendfrom(origin, destination, amount)\n                return self.record_tx(origin, destination, amount, txhash)",
    "docstring": "Convenience method for sending Bitcoins.\n\n        Send coins from origin to destination. Calls record_tx to log the\n        transaction to database.  Uses free, instant \"move\" transfers\n        if addresses are both local (in the same wallet), and standard\n        \"sendfrom\" transactions otherwise.\n\n        The sender is required to be specified by user_id (account label);\n        however, the recipient can be specified either by Bitcoin address\n        (anyone) or user_id (if the user is local).\n\n        Payment tries sending Bitcoins in this order:\n          1. \"move\" from account to account (local)\n          2. \"move\" from account to address (local)\n          3. \"sendfrom\" account to address (broadcast)\n\n        Args:\n          origin (str): user_id of the sender\n          destination (str): coin address or user_id of the recipient\n          amount (str, Decimal, number): amount to send\n\n        Returns:\n          bool: True if successful, False otherwise"
  },
  {
    "code": "def get_mode(self, old_mode=None):\n        if self.mode is not None:\n            return self.mode\n        assert self.can_write, \"This format does not have a supported output mode.\"\n        if old_mode is None:\n            return self.output_modes[0]\n        if old_mode in self.output_modes:\n            return old_mode\n        try:\n            idx = PILLOW_MODES.index(old_mode)\n        except ValueError:\n            return self.output_modes[0]\n        for mode in PILLOW_MODES[idx+1:]:\n            if mode in self.output_modes:\n                return mode\n        opposite = PILLOW_MODES[:idx]\n        opposite.reverse()\n        for mode in opposite:\n            if mode in self.output_modes:\n                return mode",
    "docstring": "Returns output mode. If `mode` not set it will try to guess best\n        mode, or next best mode comparing to old mode"
  },
  {
    "code": "def match(uidentities, matcher, fastmode=False):\n    if not isinstance(matcher, IdentityMatcher):\n        raise TypeError(\"matcher is not an instance of IdentityMatcher\")\n    if fastmode:\n        try:\n            matcher.matching_criteria()\n        except NotImplementedError:\n            name = \"'%s (fast mode)'\" % matcher.__class__.__name__.lower()\n            raise MatcherNotSupportedError(matcher=name)\n    filtered, no_filtered, uuids = \\\n        _filter_unique_identities(uidentities, matcher)\n    if not fastmode:\n        matched = _match(filtered, matcher)\n    else:\n        matched = _match_with_pandas(filtered, matcher)\n    matched = _build_matches(matched, uuids, no_filtered, fastmode)\n    return matched",
    "docstring": "Find matches in a set of unique identities.\n\n    This function looks for possible similar or equal identities from a set\n    of unique identities. The result will be a list of subsets where each\n    subset is a list of matching identities.\n\n    When `fastmode` is set a new and experimental matching algorithm\n    will be used. It consumes more resources (a big amount of memory)\n    but it is, at least, two orders of maginute faster than the\n    classic algorithm.\n\n    :param uidentities: list of unique identities to match\n    :param matcher: instance of the matcher\n    :param fastmode: use a faster algorithm\n\n    :returns: a list of subsets with the matched unique identities\n\n    :raises MatcherNotSupportedError: when matcher does not support fast\n        mode matching\n    :raises TypeError: when matcher is not an instance of\n        IdentityMatcher class"
  },
  {
    "code": "def seek(self, n):\n        if self._mode != \"r\":\n            raise UnsupportedOperation(\"not available in 'w' mode\")\n        if 0 <= n < self._nb_markers:\n            self._n = n\n            self._bed.seek(self._get_seek_position(n))\n        else:\n            raise ValueError(\"invalid position in BED: {}\".format(n))",
    "docstring": "Gets to a certain marker position in the BED file.\n\n        Args:\n            n (int): The index of the marker to seek to."
  },
  {
    "code": "def from_bytes_list(cls, function_descriptor_list):\n        assert isinstance(function_descriptor_list, list)\n        if len(function_descriptor_list) == 0:\n            return FunctionDescriptor.for_driver_task()\n        elif (len(function_descriptor_list) == 3\n              or len(function_descriptor_list) == 4):\n            module_name = ensure_str(function_descriptor_list[0])\n            class_name = ensure_str(function_descriptor_list[1])\n            function_name = ensure_str(function_descriptor_list[2])\n            if len(function_descriptor_list) == 4:\n                return cls(module_name, function_name, class_name,\n                           function_descriptor_list[3])\n            else:\n                return cls(module_name, function_name, class_name)\n        else:\n            raise Exception(\n                \"Invalid input for FunctionDescriptor.from_bytes_list\")",
    "docstring": "Create a FunctionDescriptor instance from list of bytes.\n\n        This function is used to create the function descriptor from\n        backend data.\n\n        Args:\n            cls: Current class which is required argument for classmethod.\n            function_descriptor_list: list of bytes to represent the\n                function descriptor.\n\n        Returns:\n            The FunctionDescriptor instance created from the bytes list."
  },
  {
    "code": "def _parse_qualimap_coverage(table):\n    out = {}\n    for row in table.find_all(\"tr\"):\n        col, val = [x.text for x in row.find_all(\"td\")]\n        if col == \"Mean\":\n            out[\"Coverage (Mean)\"] = val\n    return out",
    "docstring": "Parse summary qualimap coverage metrics."
  },
  {
    "code": "def angle(self, deg=False):\n        if self.dtype.str[1] != 'c':\n            warnings.warn('angle() is intended for complex-valued timeseries',\n                          RuntimeWarning, 1)\n        da = distob.vectorize(np.angle)(self, deg)\n        return _dts_from_da(da, self.tspan, self.labels)",
    "docstring": "Return the angle of a complex Timeseries\n\n        Args:\n          deg (bool, optional):\n            Return angle in degrees if True, radians if False (default).\n\n        Returns:\n          angle (Timeseries):\n            The counterclockwise angle from the positive real axis on\n            the complex plane, with dtype as numpy.float64."
  },
  {
    "code": "def _leaf_stmt(self, stmt: Statement, sctx: SchemaContext) -> None:\n        node = LeafNode()\n        node.type = DataType._resolve_type(\n            stmt.find1(\"type\", required=True), sctx)\n        self._handle_child(node, stmt, sctx)",
    "docstring": "Handle leaf statement."
  },
  {
    "code": "def _tupleCompare(tuple1, ineq, tuple2,\n                 eq=lambda a,b: (a==b),\n                 ander=AND,\n                 orer=OR):\n    orholder = []\n    for limit in range(len(tuple1)):\n        eqconstraint = [\n            eq(elem1, elem2) for elem1, elem2 in zip(tuple1, tuple2)[:limit]]\n        ineqconstraint = ineq(tuple1[limit], tuple2[limit])\n        orholder.append(ander(*(eqconstraint + [ineqconstraint])))\n    return orer(*orholder)",
    "docstring": "Compare two 'in-database tuples'.  Useful when sorting by a compound key\n    and slicing into the middle of that query."
  },
  {
    "code": "def _body(self, paragraphs):\n        body = []\n        for i in range(paragraphs):\n            paragraph = self._paragraph(random.randint(1, 10))\n            body.append(paragraph)\n        return '\\n'.join(body)",
    "docstring": "Generate a body of text"
  },
  {
    "code": "def iter_content(self, chunk_size=1, decode_unicode=False):\n        def generate():\n            try:\n                try:\n                    for chunk in self.raw.stream(chunk_size, decode_content=True):\n                        yield chunk\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n            except AttributeError:\n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n            self._content_consumed = True\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        reused_chunks = iter_slices(self._content, chunk_size)\n        stream_chunks = generate()\n        chunks = reused_chunks if self._content_consumed else stream_chunks\n        if decode_unicode:\n            chunks = stream_decode_response_unicode(chunks, self)\n        return chunks",
    "docstring": "Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        If decode_unicode is True, content will be decoded using the best\n        available encoding based on the response."
  },
  {
    "code": "def cleanup_temporary_directories(self):\n        while self.build_directories:\n            shutil.rmtree(self.build_directories.pop())\n        for requirement in self.reported_requirements:\n            requirement.remove_temporary_source()\n        while self.eggs_links:\n            symbolic_link = self.eggs_links.pop()\n            if os.path.islink(symbolic_link):\n                os.unlink(symbolic_link)",
    "docstring": "Delete the build directories and any temporary directories created by pip."
  },
  {
    "code": "def _relay_data(self):\n        \"relay any data we have\"\n        if self._data:\n            d = self._data\n            self._data = b''\n            self._sender.dataReceived(d)",
    "docstring": "relay any data we have"
  },
  {
    "code": "def get_key(self, section, key):\n        LOGGER.debug(\"> Retrieving '{0}' in '{1}' section.\".format(key, section))\n        self.__settings.beginGroup(section)\n        value = self.__settings.value(key)\n        LOGGER.debug(\"> Key value: '{0}'.\".format(value))\n        self.__settings.endGroup()\n        return value",
    "docstring": "Gets key value from settings file.\n\n        :param section: Current section to retrieve key from.\n        :type section: unicode\n        :param key: Current key to retrieve.\n        :type key: unicode\n        :return: Current key value.\n        :rtype: object"
  },
  {
    "code": "def append_row(self, values, value_input_option='RAW'):\n        params = {\n            'valueInputOption': value_input_option\n        }\n        body = {\n            'values': [values]\n        }\n        return self.spreadsheet.values_append(self.title, params, body)",
    "docstring": "Adds a row to the worksheet and populates it with values.\n        Widens the worksheet if there are more values than columns.\n\n        :param values: List of values for the new row.\n        :param value_input_option: (optional) Determines how input data should\n                                    be interpreted. See `ValueInputOption`_ in\n                                    the Sheets API.\n        :type value_input_option: str\n\n        .. _ValueInputOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption"
  },
  {
    "code": "def redirect_territory(level, code):\n    territory = GeoZone.objects.valid_at(datetime.now()).filter(\n        code=code, level='fr:{level}'.format(level=level)).first()\n    return redirect(url_for('territories.territory', territory=territory))",
    "docstring": "Implicit redirect given the INSEE code.\n\n    Optimistically redirect to the latest valid/known INSEE code."
  },
  {
    "code": "def assertTraceDoesNotContain(response, message):\n    if not hasattr(response, \"verify_trace\"):\n        raise AttributeError(\"Response object does not contain verify_trace method!\")\n    if response.verify_trace(message, False):\n        raise TestStepFail('Assert: Message(s) \"%s\" in response' % message)",
    "docstring": "Raise TestStepFail if response.verify_trace finds message from response traces.\n\n    :param response: Response. Must contain method verify_trace\n    :param message: Message to look for\n    :return: Nothing\n    :raises: AttributeError if response does not contain verify_trace method.\n    TestStepFail if verify_trace returns True."
  },
  {
    "code": "def SensorMetatagsPost(self, sensor_id, metatags, namespace = None):\r\n        ns = \"default\" if namespace is None else namespace\r\n        if self.__SenseApiCall__(\"/sensors/{0}/metatags.json?namespace={1}\".format(sensor_id, ns), \"POST\", parameters = metatags):\r\n            return True\r\n        else:\r\n            self.__error__ = \"api call unsuccessful\"\r\n            return False",
    "docstring": "Attach metatags to a sensor for a specific namespace\r\n            \r\n            @param sensor_id (int) - Id of the sensor to attach metatags to\r\n            @param namespace (string) - Namespace for which to attach metatags\r\n            @param metatags (dictionary) - Metatags to attach to the sensor\r\n            \r\n            @return (bool) - Boolean indicating whether SensorMetatagsPost was successful"
  },
  {
    "code": "def interp_like(self, other, method='linear', assume_sorted=False,\n                    kwargs={}):\n        if self.dtype.kind not in 'uifc':\n            raise TypeError('interp only works for a numeric type array. '\n                            'Given {}.'.format(self.dtype))\n        ds = self._to_temp_dataset().interp_like(\n            other, method=method, kwargs=kwargs, assume_sorted=assume_sorted)\n        return self._from_temp_dataset(ds)",
    "docstring": "Interpolate this object onto the coordinates of another object,\n        filling out of range values with NaN.\n\n        Parameters\n        ----------\n        other : Dataset or DataArray\n            Object with an 'indexes' attribute giving a mapping from dimension\n            names to an 1d array-like, which provides coordinates upon\n            which to index the variables in this dataset.\n        method: string, optional.\n            {'linear', 'nearest'} for multidimensional array,\n            {'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic'}\n            for 1-dimensional array. 'linear' is used by default.\n        assume_sorted: boolean, optional\n            If False, values of coordinates that are interpolated over can be\n            in any order and they are sorted first. If True, interpolated\n            coordinates are assumed to be an array of monotonically increasing\n            values.\n        kwargs: dictionary, optional\n            Additional keyword passed to scipy's interpolator.\n\n        Returns\n        -------\n        interpolated: xr.DataArray\n            Another dataarray by interpolating this dataarray's data along the\n            coordinates of the other object.\n\n        Notes\n        -----\n        scipy is required.\n        If the dataarray has object-type coordinates, reindex is used for these\n        coordinates instead of the interpolation.\n\n        See Also\n        --------\n        DataArray.interp\n        DataArray.reindex_like"
  },
  {
    "code": "def _translate_language_name(self, language_name):\n        languages = self.languages()\n        language_id = None\n        for ideone_index, ideone_language in languages.items():\n            if ideone_language.lower() == language_name.lower():\n                return ideone_index\n        simple_languages = dict((k,v.split('(')[0].strip())\n                                for (k,v) in languages.items())\n        for ideone_index, simple_name in simple_languages.items():\n            if simple_name.lower() == language_name.lower():\n                return ideone_index\n        language_choices = languages.values() + simple_languages.values()\n        similar_choices = difflib.get_close_matches(language_name,\n                                                    language_choices,\n                                                    n=3,\n                                                    cutoff=0.3)\n        similar_choices_string = \", \".join([\"'\" + s + \"'\"\n                                            for s in similar_choices])\n        error_string = (\"Couldn't match '%s' to an Ideone accepted language.\\n\"\n                        \"Did you mean one of the following: %s\")\n        raise IdeoneError(error_string % (language_name, similar_choices_string))",
    "docstring": "Translate a human readable langauge name into its Ideone\n        integer representation.\n\n        Keyword Arguments\n        -----------------\n\n        * langauge_name: a string of the language (e.g. \"c++\")\n\n        Returns\n        -------\n\n        An integer representation of the language.\n\n        Notes\n        -----\n\n        We use a local cache of languages if available, else we grab\n        the list of languages from Ideone.  We test for a string match\n        by comparing prefixes because Ideone includes the language\n        compiler name and version number.  Both strings are converted\n        to lower case before the comparison.\n\n        Examples\n        --------\n\n        >>> ideone_object = Ideone('username', 'password')\n        >>> ideone_object._translate_language_name('ada')\n        7"
  },
  {
    "code": "def _merge_filters(self) -> None:\n        for opts in ([\"-filter:a\", \"-af\"], [\"-filter:v\", \"-vf\"]):\n            filter_list = []\n            new_argv = []\n            cmd_iter = iter(self._argv)\n            for element in cmd_iter:\n                if element in opts:\n                    filter_list.insert(0, next(cmd_iter))\n                else:\n                    new_argv.append(element)\n            if filter_list:\n                new_argv.extend([opts[0], \",\".join(filter_list)])\n                self._argv = new_argv.copy()",
    "docstring": "Merge all filter config in command line."
  },
  {
    "code": "def get_changes(self, changers, in_hierarchy=False, resources=None,\n                    task_handle=taskhandle.NullTaskHandle()):\n        function_changer = _FunctionChangers(self.pyname.get_object(),\n                                             self._definfo(), changers)\n        return self._change_calls(function_changer, in_hierarchy,\n                                  resources, task_handle)",
    "docstring": "Get changes caused by this refactoring\n\n        `changers` is a list of `_ArgumentChanger`\\s.  If `in_hierarchy`\n        is `True` the changers are applyed to all matching methods in\n        the class hierarchy.\n        `resources` can be a list of `rope.base.resource.File`\\s that\n        should be searched for occurrences; if `None` all python files\n        in the project are searched."
  },
  {
    "code": "def cree_ws_lecture(self, champs_ligne):\n        for c in champs_ligne:\n            label = ASSOCIATION[c][0]\n            w = ASSOCIATION[c][3](self.acces[c], False)\n            w.setObjectName(\"champ-lecture-seule-details\")\n            self.widgets[c] = (w, label)",
    "docstring": "Alternative to create read only widgets. They should be set after."
  },
  {
    "code": "def get_sql(self):\n        test_method = [\n            self.is_time,\n            self.is_date,\n            self.is_datetime,\n            self.is_decimal,\n            self.is_year,\n            self.is_tinyint,\n            self.is_smallint,\n            self.is_mediumint,\n            self.is_int,\n            self.is_bigint,\n            self.is_tinytext,\n            self.is_varchar,\n            self.is_mediumtext,\n            self.is_longtext,\n        ]\n        for method in test_method:\n            if method():\n                return self.sql",
    "docstring": "Retrieve the data type for a data record."
  },
  {
    "code": "def align_after(self, offset):\n        f = self.reader\n        if offset <= 0:\n            f.seek(0)\n            self._block_count = 0\n            self._read_header()\n            return\n        sm = self.sync_marker\n        sml = len(sm)\n        pos = offset\n        while pos < self.file_length - sml:\n            f.seek(pos)\n            data = f.read(self.FORWARD_WINDOW_SIZE)\n            sync_offset = data.find(sm)\n            if sync_offset > -1:\n                f.seek(pos + sync_offset)\n                self._block_count = 0\n                return\n            pos += len(data)",
    "docstring": "Search for a sync point after offset and align just after that."
  },
  {
    "code": "def render_form(form, **kwargs):\n    renderer_cls = get_form_renderer(**kwargs)\n    return renderer_cls(form, **kwargs).render()",
    "docstring": "Render a form to a Bootstrap layout"
  },
  {
    "code": "def depart_heading(self, _):\n        assert isinstance(self.current_node, nodes.title)\n        text = self.current_node.astext()\n        if self.translate_section_name:\n            text = self.translate_section_name(text)\n        name = nodes.fully_normalize_name(text)\n        section = self.current_node.parent\n        section['names'].append(name)\n        self.document.note_implicit_target(section, section)\n        self.current_node = section",
    "docstring": "Finish establishing section\n\n        Wrap up title node, but stick in the section node. Add the section names\n        based on all the text nodes added to the title."
  },
  {
    "code": "def bound_spec(self, name):\n        if isinstance(name, BaseData):\n            name = name.name\n        spec = self.data_spec(name)\n        try:\n            bound = self._inputs[name]\n        except KeyError:\n            if not spec.derived and spec.default is None:\n                raise ArcanaMissingDataException(\n                    \"Acquired (i.e. non-generated) fileset '{}' \"\n                    \"was not supplied when the study '{}' was \"\n                    \"initiated\".format(name, self.name))\n            else:\n                try:\n                    bound = self._bound_specs[name]\n                except KeyError:\n                    bound = self._bound_specs[name] = spec.bind(self)\n        return bound",
    "docstring": "Returns an input selector or derived spec bound to the study, i.e.\n        where the repository tree is checked for existing outputs\n\n        Parameters\n        ----------\n        name : Str\n            A name of a fileset or field"
  },
  {
    "code": "def rows(self):\n        from ambry.orm import Config as SAConfig\n        from sqlalchemy import or_\n        rows = []\n        configs = self.dataset.session\\\n            .query(SAConfig)\\\n            .filter(or_(SAConfig.group == 'config', SAConfig.group == 'process'),\n                    SAConfig.d_vid == self.dataset.vid)\\\n            .all()\n        for r in configs:\n            parts = r.key.split('.', 3)\n            if r.group == 'process':\n                parts = ['process'] + parts\n            cr = ((parts[0] if len(parts) > 0 else None,\n                   parts[1] if len(parts) > 1 else None,\n                   parts[2] if len(parts) > 2 else None\n                   ), r.value)\n            rows.append(cr)\n        return rows",
    "docstring": "Return configuration in a form that can be used to reconstitute a\n        Metadata object. Returns all of the rows for a dataset.\n\n        This is distinct from get_config_value, which returns the value\n        for the library."
  },
  {
    "code": "def detect_phantomjs(version='2.1'):\n    if settings.phantomjs_path() is not None:\n        phantomjs_path = settings.phantomjs_path()\n    else:\n        if hasattr(shutil, \"which\"):\n            phantomjs_path = shutil.which(\"phantomjs\") or \"phantomjs\"\n        else:\n            phantomjs_path = \"phantomjs\"\n    try:\n        proc = Popen([phantomjs_path, \"--version\"], stdout=PIPE, stderr=PIPE)\n        proc.wait()\n        out = proc.communicate()\n        if len(out[1]) > 0:\n            raise RuntimeError('Error encountered in PhantomJS detection: %r' % out[1].decode('utf8'))\n        required = V(version)\n        installed = V(out[0].decode('utf8'))\n        if installed < required:\n            raise RuntimeError('PhantomJS version to old. Version>=%s required, installed: %s' % (required, installed))\n    except OSError:\n        raise RuntimeError('PhantomJS is not present in PATH or BOKEH_PHANTOMJS_PATH. Try \"conda install phantomjs\" or \\\n            \"npm install -g phantomjs-prebuilt\"')\n    return phantomjs_path",
    "docstring": "Detect if PhantomJS is avaiable in PATH, at a minimum version.\n\n    Args:\n        version (str, optional) :\n            Required minimum version for PhantomJS (mostly for testing)\n\n    Returns:\n        str, path to PhantomJS"
  },
  {
    "code": "def get_user_groups(name, sid=False):\n    if name == 'SYSTEM':\n        groups = [name]\n    else:\n        groups = win32net.NetUserGetLocalGroups(None, name)\n    if not sid:\n        return groups\n    ret_groups = set()\n    for group in groups:\n        ret_groups.add(get_sid_from_name(group))\n    return ret_groups",
    "docstring": "Get the groups to which a user belongs\n\n    Args:\n        name (str): The user name to query\n        sid (bool): True will return a list of SIDs, False will return a list of\n        group names\n\n    Returns:\n        list: A list of group names or sids"
  },
  {
    "code": "def hashitem(item):\n    norm = normitem(item)\n    byts = s_msgpack.en(norm)\n    return hashlib.md5(byts).hexdigest()",
    "docstring": "Generate a uniq hash for the JSON compatible primitive data structure."
  },
  {
    "code": "def from_ssl(self,\n                 ca_certs,\n                 client_cert,\n                 client_key,\n                 hosts=default.ELASTICSEARCH_HOSTS,\n                 use_ssl=True,\n                 verify_certs=True, **kwargs):\n        self.client = Elasticsearch(hosts=hosts,\n                                    use_ssl=use_ssl,\n                                    verify_certs=verify_certs,\n                                    ca_certs=ca_certs,\n                                    client_cert=client_cert,\n                                    client_key=client_key, **kwargs)\n        logger.info('Initialize SSL Elasticsearch Client: %s.' % self.client)",
    "docstring": "Initialize a Elasticsearch client by SSL.\n\n        :param ca_certs: optional path to CA bundle. See\n        https://urllib3.readthedocs.io/en/latest/security.html#using-certifi-with-urllib3\n        :param client_cert: path to the file containing the private key and the\n        certificate, or cert only if using client_key\n        :param client_key: path to the file containing the private key if using\n        separate cert and key files (client_cert will contain only the cert)\n        :param hosts: hostname of the node\n        :param use_ssl: use ssl for the connection if `True`\n        :param verify_certs: whether to verify SSL certificates\n        :return: void"
  },
  {
    "code": "def _return_base_data(self, url, container, container_object=None,\n                          container_headers=None, object_headers=None):\n        headers = self.job_args['base_headers']\n        headers.update({'X-Auth-Token': self.job_args['os_token']})\n        _container_uri = url.geturl().rstrip('/')\n        if container:\n            _container_uri = '%s/%s' % (\n                _container_uri, cloud_utils.quoter(container)\n            )\n        if container_object:\n            _container_uri = '%s/%s' % (\n                _container_uri, cloud_utils.quoter(container_object)\n            )\n        if object_headers:\n            headers.update(object_headers)\n        if container_headers:\n            headers.update(container_headers)\n        return headers, urlparse.urlparse(_container_uri)",
    "docstring": "Return headers and a parsed url.\n\n        :param url:\n        :param container:\n        :param container_object:\n        :param container_headers:\n        :return: ``tuple``"
  },
  {
    "code": "def add(self, cls_or_branch, *args, **kwargs):\n        if isinstance(cls_or_branch, Branch):\n            self.tasks.append(cls_or_branch)\n        else:\n            self.__validate_task(cls_or_branch, '__init__', args, kwargs)\n            self.tasks.append({'cls_or_branch': cls_or_branch, 'args': args, 'kwargs': kwargs})\n        return self",
    "docstring": "Adds a task or branch to the lane.\n\n        Parameters\n        ----------\n        cls_or_branch : Class\n        *args\n            Variable length argument list to be passed to `cls_or_branch` during instantiation\n        **kwargs\n            Variable length keyword arguments to be passed to `cls_or_branch` during instantiation\n\n        Returns\n        -------\n        self: Returns `self` to allow method chaining"
  },
  {
    "code": "def add_etag(self, overwrite=False, weak=False):\n        if overwrite or \"etag\" not in self.headers:\n            self.set_etag(generate_etag(self.get_data()), weak)",
    "docstring": "Add an etag for the current response if there is none yet."
  },
  {
    "code": "def refresh(self):\n        if lib.EnvRefresh(self._env, self._rule) != 1:\n            raise CLIPSError(self._env)",
    "docstring": "Refresh the Rule.\n\n        The Python equivalent of the CLIPS refresh command."
  },
  {
    "code": "def _update_sid_to_last_existing_pid_map(pid):\n    last_pid = _find_head_or_latest_connected(pid)\n    chain_model = _get_chain_by_pid(last_pid)\n    if not chain_model:\n        return\n    chain_model.head_pid = d1_gmn.app.did.get_or_create_did(last_pid)\n    chain_model.save()",
    "docstring": "Set chain head PID to the last existing object in the chain to which ``pid``\n    belongs. If SID has been set for chain, it resolves to chain head PID.\n\n    Intended to be called in MNStorage.delete() and other chain manipulation.\n\n    Preconditions:\n    - ``pid`` must exist and be verified to be a PID.\n      d1_gmn.app.views.asserts.is_existing_object()"
  },
  {
    "code": "def _stage_input_files(self, file_mapping, dry_run=True):\n        if self._file_stage is None:\n            return\n        self._file_stage.copy_to_scratch(file_mapping, dry_run)",
    "docstring": "Stage the input files to the scratch area and adjust the arguments accordingly"
  },
  {
    "code": "def _add_record(table, data, buffer_size):\n    fields = table.fields\n    for invalid_key in set(data).difference([f.name for f in fields]):\n        del data[invalid_key]\n    table.append(Record.from_dict(fields, data))\n    if buffer_size is not None and table.is_attached():\n        if (len(table) - 1) - table._last_synced_index > buffer_size:\n            table.commit()",
    "docstring": "Prepare and append a Record into its Table; flush to disk if necessary."
  },
  {
    "code": "def predictions(self):\n        for prediction in self.api.predictions(vid=self.vid)['prd']:\n            pobj = Prediction.fromapi(self.api, prediction)\n            pobj._busobj = self\n            yield pobj",
    "docstring": "Generator that yields prediction objects from an API response."
  },
  {
    "code": "def main(argv=None):\n    arguments = cli_common(__doc__, argv=argv)\n    benet = BeNet(arguments['CAMPAIGN_FILE'])\n    benet.run()\n    if argv is not None:\n        return benet",
    "docstring": "ben-nett entry point"
  },
  {
    "code": "def bifurcated_extend(self, corpus, max_size):\n        temp_fd, temp_path = tempfile.mkstemp(text=True)\n        try:\n            self._prepare_bifurcated_extend_data(corpus, max_size, temp_path,\n                                                 temp_fd)\n        finally:\n            try:\n                os.remove(temp_path)\n            except OSError as e:\n                msg = ('Failed to remove temporary file containing unreduced '\n                       'results: {}')\n                self._logger.error(msg.format(e))\n        self._bifurcated_extend()",
    "docstring": "Replaces the results with those n-grams that contain any of the\n        original n-grams, and that represent points at which an n-gram\n        is a constituent of multiple larger n-grams with a lower label\n        count.\n\n        :param corpus: corpus of works to which results belong\n        :type corpus: `Corpus`\n        :param max_size: maximum size of n-gram results to include\n        :type max_size: `int`"
  },
  {
    "code": "def cmd_zf(self, ch=None):\n        viewer = self.get_viewer(ch)\n        if viewer is None:\n            self.log(\"No current viewer/channel.\")\n            return\n        viewer.zoom_fit()\n        cur_lvl = viewer.get_zoom()\n        self.log(\"zoom=%f\" % (cur_lvl))",
    "docstring": "zf ch=chname\n\n        Zoom the image for the given viewer/channel to fit the window."
  },
  {
    "code": "def calc_2d_forces(self,x1,y1,x2,y2,width):\n        if x1>x2:\n            a = x1-x2\n        else:\n            a = x2-x1\n        a_sq=a*a\n        if y1>y2:\n            b = y1-y2\n        else:\n            b = y2-y1\n        b_sq=b*b\n        from math import sqrt\n        c_sq = a_sq+b_sq\n        c = sqrt(c_sq)\n        if c > width:\n            return 0,0\n        else:\n            overlap = width-c\n        return -overlap/2, overlap/2",
    "docstring": "Calculate overlap in 2D space"
  },
  {
    "code": "def on_channel_closed(self, channel, reply_code, reply_text):\n        for future in self.messages.values():\n            future.set_exception(AMQPException(reply_code, reply_text))\n        self.messages = {}\n        if self.closing:\n            LOGGER.debug('Channel %s was intentionally closed (%s) %s',\n                         channel, reply_code, reply_text)\n        else:\n            LOGGER.warning('Channel %s was closed: (%s) %s',\n                           channel, reply_code, reply_text)\n            self.state = self.STATE_BLOCKED\n            if self.on_unavailable:\n                self.on_unavailable(self)\n            self.channel = self._open_channel()",
    "docstring": "Invoked by pika when RabbitMQ unexpectedly closes the channel.\n\n        Channels are usually closed if you attempt to do something that\n        violates the protocol, such as re-declare an exchange or queue with\n        different parameters.\n\n        In this case, we just want to log the error and create a new channel\n        after setting the state back to connecting.\n\n        :param pika.channel.Channel channel: The closed channel\n        :param int reply_code: The numeric reason the channel was closed\n        :param str reply_text: The text reason the channel was closed"
  },
  {
    "code": "def _parsemeta_tmy2(columns, line):\n    rawmeta = \" \".join(line.split()).split(\" \")\n    meta = rawmeta[:3]\n    meta.append(int(rawmeta[3]))\n    longitude = (\n        float(rawmeta[5]) + float(rawmeta[6])/60) * (2*(rawmeta[4] == 'N') - 1)\n    latitude = (\n        float(rawmeta[8]) + float(rawmeta[9])/60) * (2*(rawmeta[7] == 'E') - 1)\n    meta.append(longitude)\n    meta.append(latitude)\n    meta.append(float(rawmeta[10]))\n    meta_dict = dict(zip(columns.split(','), meta))\n    return meta_dict",
    "docstring": "Retrieves metadata from the top line of the tmy2 file.\n\n    Parameters\n    ----------\n    columns : string\n        String of column headings in the header\n\n    line : string\n        Header string containing DataFrame\n\n    Returns\n    -------\n    meta : Dict of metadata contained in the header string"
  },
  {
    "code": "def sqrt(n):\n    if isinstance(n, Rational):\n        n = Constructible(n)\n    elif not isinstance(n, Constructible):\n        raise ValueError('the square root is not implemented for the type %s' % type(n))\n    r = n._try_sqrt()\n    if r is not None:\n        return r\n    return Constructible(Constructible.lift_rational_field(0, n.field),\n                         Constructible.lift_rational_field(1, n.field),\n                         (n, n.field))",
    "docstring": "return the square root of n in an exact representation"
  },
  {
    "code": "def add_markdown_cell(self, content, tags=None):\n        self.notebook[\"cells\"].append(nb.v4.new_markdown_cell(content, **{\"metadata\":\n                                                                          {\"tags\": tags}}))",
    "docstring": "Class method responsible for adding a markdown cell with content 'content' to the\n        Notebook object.\n\n        ----------\n        Parameters\n        ----------\n        content : str\n            Text/HTML code/... to include in the markdown cell (triple quote for multiline text).\n\n        tags : list\n            A list of tags to include in the markdown cell metadata."
  },
  {
    "code": "async def flush(self, request: 'Request'):\n        from bernard.middleware import MiddlewareManager\n        for stack in self._stacks:\n            await stack.convert_media(self.platform)\n        func = MiddlewareManager.instance().get('flush', self._flush)\n        await func(request, self._stacks)",
    "docstring": "Send all queued messages.\n\n        The first step is to convert all media in the stacked layers then the\n        second step is to send all messages as grouped in time as possible."
  },
  {
    "code": "def consume(self):\n        if self.match:\n            self.pos = self.match.end()\n            if self.match.group()[-1] == '\\n':\n                self._update_prefix()\n            self.match = None",
    "docstring": "Consume the body of source. ``pos`` will move forward."
  },
  {
    "code": "def new_iteration(self, prefix):\n        self.flush()\n        self.prefix[-1] = prefix\n        self.reset_formatter()",
    "docstring": "When inside a loop logger, created a new iteration"
  },
  {
    "code": "def quantile(q, variable, weight_variable = None, filter_variable = None):\n    def formula(entity, period):\n        value = entity(variable, period)\n        if weight_variable is not None:\n            weight = entity(weight_variable, period)\n        weight = entity.filled_array(1)\n        if filter_variable is not None:\n            filter_value = entity(filter_variable, period)\n            weight = filter_value * weight\n        labels = arange(1, q + 1)\n        quantile, _ = weightedcalcs_quantiles(\n            value,\n            labels,\n            weight,\n            return_quantiles = True,\n            )\n        if filter_variable is not None:\n            quantile = where(weight > 0, quantile, -1)\n        return quantile\n    return formula",
    "docstring": "Return quantile of a variable with weight provided by a specific wieght variable potentially filtered"
  },
  {
    "code": "def _CheckLegacyPassword(self, password):\n    import crypt\n    salt = self._value[:2]\n    return crypt.crypt(password, salt) == self._value",
    "docstring": "Check password with legacy crypt based method."
  },
  {
    "code": "def common_ancestor(c):\n    span1 = _to_span(c[0])\n    span2 = _to_span(c[1])\n    ancestor1 = np.array(span1.sentence.xpath.split(\"/\"))\n    ancestor2 = np.array(span2.sentence.xpath.split(\"/\"))\n    min_len = min(ancestor1.size, ancestor2.size)\n    return list(ancestor1[: np.argmin(ancestor1[:min_len] == ancestor2[:min_len])])",
    "docstring": "Return the path to the root that is shared between a binary-Mention Candidate.\n\n    In particular, this is the common path of HTML tags.\n\n    :param c: The binary-Mention Candidate to evaluate\n    :rtype: list of strings"
  },
  {
    "code": "def make_pkgng_aware(jname):\n    ret = {'changes': {}}\n    cdir = _config_dir()\n    if not os.path.isdir(cdir):\n        os.makedirs(cdir)\n        if os.path.isdir(cdir):\n            ret['changes'] = 'Created poudriere make file dir {0}'.format(cdir)\n        else:\n            return 'Could not create or find required directory {0}'.format(\n                    cdir)\n    __salt__['file.write']('{0}-make.conf'.format(os.path.join(cdir, jname)), 'WITH_PKGNG=yes')\n    if os.path.isfile(os.path.join(cdir, jname) + '-make.conf'):\n        ret['changes'] = 'Created {0}'.format(\n                os.path.join(cdir, '{0}-make.conf'.format(jname))\n                )\n        return ret\n    else:\n        return 'Looks like file {0} could not be created'.format(\n                os.path.join(cdir, jname + '-make.conf')\n                )",
    "docstring": "Make jail ``jname`` pkgng aware\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' poudriere.make_pkgng_aware <jail name>"
  },
  {
    "code": "def read(self):\n        data = bytearray()\n        while True:\n            incoming_bytes = self.comport.inWaiting()\n            if incoming_bytes == 0:\n                break\n            else:\n                content = self.comport.read(size=incoming_bytes)\n                data.extend(bytearray(content))\n        return data",
    "docstring": "Read data from serial port and returns a ``bytearray``."
  },
  {
    "code": "def find_spectrum_match(spec, spec_lib, method='euclidian'):\n    spec = spec / np.max(spec)\n    if method == 'dot':\n        d1 = (spec_lib * lil_matrix(spec).T).sum(axis=1).A ** 2\n        d2 = np.sum(spec ** 2) * spec_lib.multiply(spec_lib).sum(axis=1).A\n        dist = d1 / d2\n    elif method == 'euclidian':\n        st_spc = dia_matrix((spec, [0]), shape=(len(spec), len(spec)))\n        dist_sp = spec_lib.multiply(spec_lib) - 2 * spec_lib.dot(st_spc)\n        dist = dist_sp.sum(axis=1).A + np.sum(spec ** 2)\n    return (dist.argmin(), dist.min())",
    "docstring": "Find spectrum in spec_lib most similar to spec."
  },
  {
    "code": "def file_id(self):\n        if self.type.lower() == \"directory\":\n            return None\n        if self.file_uuid is None:\n            raise exceptions.MetsError(\n                \"No FILEID: File %s does not have file_uuid set\" % self.path\n            )\n        if self.is_aip:\n            return os.path.splitext(os.path.basename(self.path))[0]\n        return utils.FILE_ID_PREFIX + self.file_uuid",
    "docstring": "Returns the fptr @FILEID if this is not a Directory."
  },
  {
    "code": "def _update_linear_bucket_count(a_float, dist):\n    buckets = dist.linearBuckets\n    if buckets is None:\n        raise ValueError(_BAD_UNSET_BUCKETS % (u'linear buckets'))\n    bucket_counts = dist.bucketCounts\n    num_finite_buckets = buckets.numFiniteBuckets\n    if len(bucket_counts) < num_finite_buckets + 2:\n        raise ValueError(_BAD_LOW_BUCKET_COUNT)\n    width = buckets.width\n    lower = buckets.offset\n    upper = lower + (num_finite_buckets * width)\n    if a_float < lower:\n        index = 0\n    elif a_float >= upper:\n        index = num_finite_buckets + 1\n    else:\n        index = 1 + int(((a_float - lower) / width))\n    bucket_counts[index] += 1\n    _logger.debug(u'upper:%f, lower:%f, width:%f, sample:%f, index:%d',\n                  upper, lower, width, a_float, index)",
    "docstring": "Adds `a_float` to `dist`, updating the its linear buckets.\n\n    Args:\n      a_float (float): a new value\n      dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):\n        the Distribution being updated\n\n    Raises:\n      ValueError: if `dist` does not already have linear buckets defined\n      ValueError: if there are not enough bucket count fields in `dist`"
  },
  {
    "code": "def get_matrix(self):\n        if self.parent:\n            return self.get_local_matrix() * (self._prev_parent_matrix or self.parent.get_matrix())\n        else:\n            return self.get_local_matrix()",
    "docstring": "return sprite's current transformation matrix"
  },
  {
    "code": "def get_parent_id(self, resource, document):\n        parent_type = self._get_parent_type(resource)\n        if parent_type and document:\n            return document.get(parent_type.get('field'))\n        return None",
    "docstring": "Get the Parent Id of the document\n\n        :param resource: resource name\n        :param document: document containing the parent id"
  },
  {
    "code": "def _compute(self, data):\n        local_ts = self._local_ts(*data)\n        dt = local_ts[internal_names.TIME_WEIGHTS_STR]\n        dt = dt / np.timedelta64(1, 'D')\n        return local_ts, dt",
    "docstring": "Perform the calculation."
  },
  {
    "code": "def get_property(self, name):\n        with self.__properties_lock:\n            return self.__properties.get(name, os.getenv(name))",
    "docstring": "Retrieves a framework or system property. As framework properties don't\n        change while it's running, this method don't need to be protected.\n\n        :param name: The property name"
  },
  {
    "code": "def _update_xyz(self, change):\r\n        self.x,self.y,self.z = self.position.X(),self.position.Y(),self.position.Z()",
    "docstring": "Keep x,y,z in sync with position"
  },
  {
    "code": "def profile_loglike(self, x):\n        if self._prof_interp is None:\n            return self._profile_loglike(x)[1]\n        x = np.array(x, ndmin=1)\n        return self._prof_interp(x)",
    "docstring": "Profile log-likelihood.\n\n        Returns ``L_prof(x,y=y_min|z')``  : where y_min is the \n                                            value of y that minimizes \n                                            L for a given x.\n\n        This will used the cached '~fermipy.castro.Interpolator' object \n        if possible, and construct it if needed."
  },
  {
    "code": "def vn_delete(call=None, kwargs=None):\n    if call != 'function':\n        raise SaltCloudSystemExit(\n            'The vn_delete function must be called with -f or --function.'\n        )\n    if kwargs is None:\n        kwargs = {}\n    name = kwargs.get('name', None)\n    vn_id = kwargs.get('vn_id', None)\n    if vn_id:\n        if name:\n            log.warning(\n                'Both the \\'vn_id\\' and \\'name\\' arguments were provided. '\n                '\\'vn_id\\' will take precedence.'\n            )\n    elif name:\n        vn_id = get_vn_id(kwargs={'name': name})\n    else:\n        raise SaltCloudSystemExit(\n            'The vn_delete function requires a \\'name\\' or a \\'vn_id\\' '\n            'to be provided.'\n        )\n    server, user, password = _get_xml_rpc()\n    auth = ':'.join([user, password])\n    response = server.one.vn.delete(auth, int(vn_id))\n    data = {\n        'action': 'vn.delete',\n        'deleted': response[0],\n        'vn_id': response[1],\n        'error_code': response[2],\n    }\n    return data",
    "docstring": "Deletes the given virtual network from OpenNebula. Either a name or a vn_id must\n    be supplied.\n\n    .. versionadded:: 2016.3.0\n\n    name\n        The name of the virtual network to delete. Can be used instead of ``vn_id``.\n\n    vn_id\n        The ID of the virtual network to delete. Can be used instead of ``name``.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -f vn_delete opennebula name=my-virtual-network\n        salt-cloud --function vn_delete opennebula vn_id=3"
  },
  {
    "code": "def get_config(config_file):\n    def load(fp):\n        try:\n            return yaml.safe_load(fp)\n        except yaml.YAMLError as e:\n            sys.stderr.write(text_type(e))\n            sys.exit(1)\n    if config_file == '-':\n        return load(sys.stdin)\n    if not os.path.exists(config_file):\n        sys.stderr.write('ERROR: Must either run next to config.yaml or'\n            ' specify a config file.\\n' + __doc__)\n        sys.exit(2)\n    with open(config_file) as fp:\n        return load(fp)",
    "docstring": "Get configuration from a file."
  },
  {
    "code": "def setKeepAliveTimeOut(self, iTimeOut):\n        print '%s call setKeepAliveTimeOut' % self.port\n        print iTimeOut\n        try:\n            cmd = WPANCTL_CMD + 'setprop NCP:SleepyPollInterval %s' % str(iTimeOut*1000)\n            print cmd\n            return self.__sendCommand(cmd)[0] != 'Fail'\n        except Exception, e:\n            ModuleHelper.WriteIntoDebugLogger('setKeepAliveTimeOut() Error: ' + str(e))",
    "docstring": "set keep alive timeout for device\n           has been deprecated and also set SED polling rate\n\n        Args:\n            iTimeOut: data poll period for sleepy end device\n\n        Returns:\n            True: successful to set the data poll period for SED\n            False: fail to set the data poll period for SED"
  },
  {
    "code": "def disable_if_no_tty(cls):\n        if sys.stdout.isatty() or sys.stderr.isatty():\n            return False\n        cls.disable_all_colors()\n        return True",
    "docstring": "Disable all colors only if there is no TTY available.\n\n        :return: True if colors are disabled, False if stderr or stdout is a TTY.\n        :rtype: bool"
  },
  {
    "code": "def import_class(clspath):\n    modpath, clsname = split_clspath(clspath)\n    __import__(modpath)\n    module = sys.modules[modpath]\n    return getattr(module, clsname)",
    "docstring": "Given a clspath, returns the class.\n\n    Note: This is a really simplistic implementation."
  },
  {
    "code": "def setExpertLevel(self):\n        g = get_root(self).globals\n        level = g.cpars['expert_level']\n        if level == 0:\n            if self.val.get() == 'CCD TECs':\n                self.val.set('Observe')\n                self._changed()\n            self.tecs.grid_forget()\n        else:\n            self.tecs.grid(row=0, column=3, sticky=tk.W)",
    "docstring": "Modifies widget according to expertise level, which in this\n        case is just matter of hiding or revealing the button to\n        set CCD temps"
  },
  {
    "code": "def transform(self, maps):\n        out = {}\n        out[\"chi_p\"] = conversions.chi_p(\n                             maps[parameters.mass1], maps[parameters.mass2],\n                             maps[parameters.spin1x], maps[parameters.spin1y],\n                             maps[parameters.spin2x], maps[parameters.spin2y])\n        return self.format_output(maps, out)",
    "docstring": "This function transforms from component masses and caretsian spins\n        to chi_p.\n\n        Parameters\n        ----------\n        maps : a mapping object\n\n        Examples\n        --------\n        Convert a dict of numpy.array:\n\n        Returns\n        -------\n        out : dict\n            A dict with key as parameter name and value as numpy.array or float\n            of transformed values."
  },
  {
    "code": "def load_metrics(event_dir, epoch):\n  metrics = {}\n  for filename in tf.gfile.ListDirectory(event_dir):\n    path = os.path.join(event_dir, filename)\n    for event in tf.train.summary_iterator(path):\n      if event.step == epoch and event.HasField(\"summary\"):\n        value = event.summary.value[0]\n        metrics[value.tag] = value.simple_value\n  return metrics",
    "docstring": "Loads metrics for this epoch if they have already been written.\n\n  This reads the entire event file but it's small with just per-epoch metrics.\n\n  Args:\n    event_dir: TODO(koz4k): Document this.\n    epoch: TODO(koz4k): Document this.\n\n  Returns:\n    metrics."
  },
  {
    "code": "def create_multiple_replace_func(*args, **kwds):\n    adict = dict(*args, **kwds)\n    rx = re.compile('|'.join(map(re.escape, adict)))\n    def one_xlat(match):\n        return adict[match.group(0)]\n    def xlat(text):\n        return rx.sub(one_xlat, text)\n    return xlat",
    "docstring": "You can call this function and pass it a dictionary, or any other\n    combination of arguments you could pass to built-in dict in order to\n    construct a dictionary. The function will return a xlat closure that\n    takes as its only argument text the string on which the substitutions\n    are desired and returns a copy of text with all the substitutions\n    performed.\n\n    Source: Python Cookbook 2nd ed, Chapter 1.18. Replacing Multiple Patterns\n    in a Single Pass.\n    https://www.safaribooksonline.com/library/view/python-cookbook-2nd/0596007973/ch01s19.html"
  },
  {
    "code": "def _eval(self, v, in_bounds, der):\n        result = np.zeros_like(v, dtype='float')\n        x_indices = np.searchsorted(self._x, v, side='rigth')\n        ids = x_indices[in_bounds] - 1\n        u = v[in_bounds] - self._x[ids]\n        result[in_bounds] = self._poly_eval(u, ids, der)\n        return result",
    "docstring": "Eval polynomial inside bounds."
  },
  {
    "code": "def sanitizeStructTime(struct):\n    maxValues = (9999, 12, 31, 23, 59, 59)\n    minValues = (1, 1, 1, 0, 0, 0)\n    newstruct = []\n    for value, maxValue, minValue in zip(struct[:6], maxValues, minValues):\n        newstruct.append(max(minValue, min(value, maxValue)))\n    return tuple(newstruct) + struct[6:]",
    "docstring": "Convert struct_time tuples with possibly invalid values to valid\n    ones by substituting the closest valid value."
  },
  {
    "code": "def from_table(self, table=None, fields='*', schema=None, **kwargs):\n        self.tables.append(TableFactory(\n            table=table,\n            fields=fields,\n            schema=schema,\n            owner=self,\n            **kwargs\n        ))\n        return self",
    "docstring": "Adds a ``Table`` and any optional fields to the list of tables\n        this query is selecting from.\n\n        :type table: str or dict or :class:`Table <querybuilder.tables.Table>`\n            or :class:`Query <querybuilder.query.Query>` or\n            :class:`ModelBase <django:django.db.models.base.ModelBase>`\n        :param table: The table to select fields from. This can be a string of the table\n            name, a dict of {'alias': table}, a ``Table`` instance, a Query instance, or a\n            django Model instance\n\n        :type fields: str or tuple or list or Field\n        :param fields: The fields to select from ``table``. Defaults to '*'. This can be\n            a single field, a tuple of fields, or a list of fields. Each field can be a string\n            or ``Field`` instance\n\n        :type schema: str\n        :param schema: This is not implemented, but it will be a string of the db schema name\n\n        :param kwargs: Any additional parameters to be passed into the constructor of ``TableFactory``\n\n        :return: self\n        :rtype: :class:`Query <querybuilder.query.Query>`"
  },
  {
    "code": "async def flexible_api_handler(service, action_type, payload, props, **kwds):\n    if action_type == intialize_service_action():\n        model = json.loads(payload) if isinstance(payload, str) else payload\n        models = service._external_service_data['models']\n        connections = service._external_service_data['connections']\n        mutations = service._external_service_data['mutations']\n        if 'connection' in model:\n            if not [conn for conn in connections if conn['name'] == model['name']]:\n                connections.append(model)\n        elif 'fields' in model and not [mod for mod in models if mod['name'] == model['name']]:\n            models.append(model)\n        if 'mutations' in model:\n            for mutation in model['mutations']:\n                if not [mut for mut in mutations if mut['name'] == mutation['name']]:\n                    mutations.append(mutation)\n        if models:\n            service.schema = generate_api_schema(\n                models=models,\n                connections=connections,\n                mutations=mutations,\n            )",
    "docstring": "This query handler builds the dynamic picture of availible services."
  },
  {
    "code": "def build_payload(self, payload):\n        for segment in self.segments:\n            segment.pack(payload, commit=self.autocommit)",
    "docstring": "Build payload of message."
  },
  {
    "code": "def head(self, n=5):\n        self._reset_group_selection()\n        mask = self._cumcount_array() < n\n        return self._selected_obj[mask]",
    "docstring": "Return first n rows of each group.\n\n        Essentially equivalent to ``.apply(lambda x: x.head(n))``,\n        except ignores as_index flag.\n        %(see_also)s\n        Examples\n        --------\n\n        >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]],\n                              columns=['A', 'B'])\n        >>> df.groupby('A', as_index=False).head(1)\n           A  B\n        0  1  2\n        2  5  6\n        >>> df.groupby('A').head(1)\n           A  B\n        0  1  2\n        2  5  6"
  },
  {
    "code": "def disable_busy_cursor():\n    while QgsApplication.instance().overrideCursor() is not None and \\\n            QgsApplication.instance().overrideCursor().shape() == \\\n            QtCore.Qt.WaitCursor:\n        QgsApplication.instance().restoreOverrideCursor()",
    "docstring": "Disable the hourglass cursor and listen for layer changes."
  },
  {
    "code": "def validate_field(field, allowed_keys, allowed_types):\n    for key, value in field.items():\n        if key not in allowed_keys:\n            raise exceptions.ParametersFieldError(key, \"property\")\n        if key == defs.TYPE:\n            if value not in allowed_types:\n                raise exceptions.ParametersFieldError(value, key)\n        if key == defs.VALUE:\n            if not is_valid_field_name(value):\n                raise exceptions.ParametersFieldError(value, \"field name\")",
    "docstring": "Validate field is allowed and valid."
  },
  {
    "code": "def join(self, iterable):\n        return self.__class__(super(ColorStr, self).join(iterable), keep_tags=True)",
    "docstring": "Return a string which is the concatenation of the strings in the iterable.\n\n        :param iterable: Join items in this iterable."
  },
  {
    "code": "def _parse_multifile(self, desired_type: Type[T], obj: PersistedObject,\n                         parsing_plan_for_children: Dict[str, ParsingPlan], logger: Logger,\n                         options: Dict[str, Dict[str, Any]]) -> T:\n        pass",
    "docstring": "First parse all children from the parsing plan, then calls _build_object_from_parsed_children\n\n        :param desired_type:\n        :param obj:\n        :param parsing_plan_for_children:\n        :param logger:\n        :param options:\n        :return:"
  },
  {
    "code": "def ensure_unicoded_and_unique(args_list, application):\n    unicoded_args = []\n    for argument in args_list:\n        argument = (six.u(argument)\n                    if not isinstance(argument, six.text_type) else argument)\n        if argument not in unicoded_args or argument == application:\n            unicoded_args.append(argument)\n    return unicoded_args",
    "docstring": "Iterate over args_list, make it unicode if needed and ensure that there\n    are no duplicates.\n    Returns list of unicoded arguments in the same order."
  },
  {
    "code": "def edge_has_annotation(edge_data: EdgeData, key: str) -> Optional[Any]:\n    annotations = edge_data.get(ANNOTATIONS)\n    if annotations is None:\n        return None\n    return annotations.get(key)",
    "docstring": "Check if an edge has the given annotation.\n\n    :param edge_data: The data dictionary from a BELGraph's edge\n    :param key: An annotation key\n    :return: If the annotation key is present in the current data dictionary\n\n    For example, it might be useful to print all edges that are annotated with 'Subgraph':\n\n    >>> from pybel.examples import sialic_acid_graph\n    >>> for u, v, data in sialic_acid_graph.edges(data=True):\n    >>>     if edge_has_annotation(data, 'Species')\n    >>>         print(u, v, data)"
  },
  {
    "code": "def _mean_dict(dict_list):\n    return {k: np.array([d[k] for d in dict_list]).mean()\n            for k in dict_list[0].keys()}",
    "docstring": "Compute the mean value across a list of dictionaries"
  },
  {
    "code": "def skip_redundant(iterable, skipset=None):\n    if skipset is None:\n        skipset = set()\n    for item in iterable:\n        if item not in skipset:\n            skipset.add(item)\n            yield item",
    "docstring": "Redundant items are repeated items or items in the original skipset."
  },
  {
    "code": "def setNumberRange(key, keyType, start, end):\n    return And(\n        And(keyType, error=SCHEMA_TYPE_ERROR % (key, keyType.__name__)),\n        And(lambda n: start <= n <= end, error=SCHEMA_RANGE_ERROR % (key, '(%s,%s)' % (start, end))),\n    )",
    "docstring": "check number range"
  },
  {
    "code": "def erase_in_display(self, how=0, *args, **kwargs):\n        if how == 0:\n            interval = range(self.cursor.y + 1, self.lines)\n        elif how == 1:\n            interval = range(self.cursor.y)\n        elif how == 2 or how == 3:\n            interval = range(self.lines)\n        self.dirty.update(interval)\n        for y in interval:\n            line = self.buffer[y]\n            for x in line:\n                line[x] = self.cursor.attrs\n        if how == 0 or how == 1:\n            self.erase_in_line(how)",
    "docstring": "Erases display in a specific way.\n\n        Character attributes are set to cursor attributes.\n\n        :param int how: defines the way the line should be erased in:\n\n            * ``0`` -- Erases from cursor to end of screen, including\n              cursor position.\n            * ``1`` -- Erases from beginning of screen to cursor,\n              including cursor position.\n            * ``2`` and ``3`` -- Erases complete display. All lines\n              are erased and changed to single-width. Cursor does not\n              move.\n        :param bool private: when ``True`` only characters marked as\n                             eraseable are affected **not implemented**.\n\n        .. versionchanged:: 0.8.1\n\n           The method accepts any number of positional arguments as some\n           ``clear`` implementations include a ``;`` after the first\n           parameter causing the stream to assume a ``0`` second parameter."
  },
  {
    "code": "def _on_stackexchange_request(self, future, response):\n        content = escape.json_decode(response.body)\n        if 'error' in content:\n            future.set_exception(Exception('StackExchange error: %s' %\n                                           str(content['error'])))\n            return\n        future.set_result(content)",
    "docstring": "Invoked as a response to the StackExchange API request. Will decode\n        the response and set the result for the future to return the callback or\n        raise an exception"
  },
  {
    "code": "def get_node(self, node_name):\n        for node in self.nodes:\n            if node.__name__ == node_name:\n                return node",
    "docstring": "Retrieve node with passed name"
  },
  {
    "code": "def fetch_token(self):\n        grant_type = 'client_credentials'\n        channel = yield self._tvm.ticket_full(\n            self._client_id, self._client_secret, grant_type, {})\n        ticket = yield channel.rx.get()\n        raise gen.Return(self._make_token(ticket))",
    "docstring": "Gains token from secure backend service.\n\n        :return: Token formatted for Cocaine protocol header."
  },
  {
    "code": "def get(self, *args, **kwargs):\n        return self.session.get(*args, **self.get_kwargs(**kwargs))",
    "docstring": "Executes an HTTP GET.\n\n        :Parameters:\n           - `args`: Non-keyword arguments\n           - `kwargs`: Keyword arguments"
  },
  {
    "code": "def get_reservation_ports(session, reservation_id, model_name='Generic Traffic Generator Port'):\n    reservation_ports = []\n    reservation = session.GetReservationDetails(reservation_id).ReservationDescription\n    for resource in reservation.Resources:\n        if resource.ResourceModelName == model_name:\n            reservation_ports.append(resource)\n    return reservation_ports",
    "docstring": "Get all Generic Traffic Generator Port in reservation.\n\n    :return: list of all Generic Traffic Generator Port resource objects in reservation"
  },
  {
    "code": "def _sid_subdir_path(sid):\n    padded_sid = format(sid, '06')\n    return os.path.join(\n        padded_sid[0:2],\n        padded_sid[2:4],\n        \"{0}.bcolz\".format(str(padded_sid))\n    )",
    "docstring": "Format subdir path to limit the number directories in any given\n    subdirectory to 100.\n\n    The number in each directory is designed to support at least 100000\n    equities.\n\n    Parameters\n    ----------\n    sid : int\n        Asset identifier.\n\n    Returns\n    -------\n    out : string\n        A path for the bcolz rootdir, including subdirectory prefixes based on\n        the padded string representation of the given sid.\n\n        e.g. 1 is formatted as 00/00/000001.bcolz"
  },
  {
    "code": "def is_encodable(self, typ: TypeStr, arg: Any) -> bool:\n        encoder = self._registry.get_encoder(typ)\n        try:\n            encoder.validate_value(arg)\n        except EncodingError:\n            return False\n        except AttributeError:\n            try:\n                encoder(arg)\n            except EncodingError:\n                return False\n        return True",
    "docstring": "Determines if the python value ``arg`` is encodable as a value of the\n        ABI type ``typ``.\n\n        :param typ: A string representation for the ABI type against which the\n            python value ``arg`` will be checked e.g. ``'uint256'``,\n            ``'bytes[]'``, ``'(int,int)'``, etc.\n        :param arg: The python value whose encodability should be checked.\n\n        :returns: ``True`` if ``arg`` is encodable as a value of the ABI type\n            ``typ``.  Otherwise, ``False``."
  },
  {
    "code": "def update_health(self, reporter, info):\n        with self.changes_squashed:\n            alarm = info.alarm\n            if alarm.is_ok():\n                self._faults.pop(reporter, None)\n            else:\n                self._faults[reporter] = alarm\n            if self._faults:\n                faults = sorted(self._faults.values(),\n                                key=lambda a: a.severity.value)\n                alarm = faults[-1]\n                text = faults[-1].message\n            else:\n                alarm = None\n                text = \"OK\"\n            self.health.set_value(text, alarm=alarm)",
    "docstring": "Set the health attribute. Called from part"
  },
  {
    "code": "def defocus_blur(x, severity=1):\n  c = [(3, 0.1), (4, 0.5), (6, 0.5), (8, 0.5), (10, 0.5)][severity - 1]\n  x = np.array(x) / 255.\n  kernel = disk(radius=c[0], alias_blur=c[1])\n  channels = []\n  for d in range(3):\n    channels.append(tfds.core.lazy_imports.cv2.filter2D(x[:, :, d], -1, kernel))\n  channels = np.array(channels).transpose((1, 2, 0))\n  x_clip = np.clip(channels, 0, 1) * 255\n  return around_and_astype(x_clip)",
    "docstring": "Defocus blurring to images.\n\n  Apply defocus blurring to images using Gaussian kernel.\n\n  Args:\n    x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].\n    severity: integer, severity of corruption.\n\n  Returns:\n    numpy array, image with uint8 pixels in [0,255]. Applied defocus blur."
  },
  {
    "code": "def _populateBuffer(self, stream, n):\n        try:\n            for x in xrange(n):\n                output = stream.next()\n                self._buffer.write(output)\n        except StopIteration, e:\n            self._deferred.callback(None)\n        except Exception, e:\n            self._deferred.errback(e)\n        else:\n            self.delayedCall = reactor.callLater(CALL_DELAY, self._populateBuffer, stream, n)",
    "docstring": "Iterator that returns N steps of\n        the genshi stream.\n\n        Found that performance really sucks for\n        n = 1 (0.5 requests/second for the root resources\n        versus 80 requests/second for a blocking algorithm).\n\n        Hopefully increasing the number of steps per timeslice will\n        significantly improve performance."
  },
  {
    "code": "def _extract_alphabet(self, grammar):\n        alphabet = set([])\n        for terminal in grammar.Terminals:\n            alphabet |= set([x for x in terminal])\n        self.alphabet = list(alphabet)",
    "docstring": "Extract an alphabet from the given grammar."
  },
  {
    "code": "def Compile(self, filter_implementation):\n    arguments = [self.attribute]\n    for argument in self.args:\n      arguments.append(argument.Compile(filter_implementation))\n    expander = filter_implementation.FILTERS['ValueExpander']\n    context_cls = filter_implementation.FILTERS['Context']\n    return context_cls(arguments=arguments,\n                       value_expander=expander)",
    "docstring": "Compile the expression."
  },
  {
    "code": "def get_users_by_ids(self, user_ids):\n        urls = [urljoin(self.user_url, F\"{i}.json\") for i in user_ids]\n        result = self._run_async(urls=urls)\n        return [User(r) for r in result if r]",
    "docstring": "Given a list of user ids, return all the User objects"
  },
  {
    "code": "def set(self, prop, value):\n        prop_parts = prop.split(\".\")\n        if self.copy_dict:\n            new_dict = copy.deepcopy(self.obj)\n        else:\n            new_dict = self.obj\n        pointer = None\n        parts_length = len(prop_parts) - 1\n        for i, part in enumerate(prop_parts):\n            if pointer is None and i == parts_length:\n                new_dict[part] = value\n            elif pointer is None:\n                pointer = new_dict.get(part)\n            elif i == parts_length:\n                pointer[part] = value\n            else:\n                pointer = pointer.get(part)\n        return new_dict",
    "docstring": "sets the dot notated property to the passed in value\n\n        args:\n            prop: a string of the property to retreive\n                \"a.b.c\" ~ dictionary['a']['b']['c']\n            value: the value to set the prop object"
  },
  {
    "code": "def censor_entity_types(self, entity_types):\n        assert type(entity_types) == set\n        self._entity_types_to_censor = entity_types\n        self._feats_from_spacy_doc = FeatsFromSpacyDoc(\n            use_lemmas=self._use_lemmas,\n            entity_types_to_censor=self._entity_types_to_censor\n        )\n        return self",
    "docstring": "Entity types to exclude from feature construction. Terms matching\n        specificed entities, instead of labeled by their lower case orthographic\n        form or lemma, will be labeled by their entity type.\n\n        Parameters\n        ----------\n        entity_types : set of entity types outputted by spaCy\n          'TIME', 'WORK_OF_ART', 'PERSON', 'MONEY', 'ORG', 'ORDINAL', 'DATE',\n          'CARDINAL', 'LAW', 'QUANTITY', 'GPE', 'PERCENT'\n\n        Returns\n        ---------\n        self"
  },
  {
    "code": "def from_dict(self, document):\n        identifier = str(document['_id'])\n        active = document['active']\n        timestamp = datetime.datetime.strptime(document['timestamp'], '%Y-%m-%dT%H:%M:%S.%f')\n        properties = document['properties']\n        directory = self.get_directory(identifier)\n        return ImageHandle(identifier, properties, directory, timestamp=timestamp, is_active=active)",
    "docstring": "Create image object from JSON document retrieved from database.\n\n        Parameters\n        ----------\n        document : JSON\n            Json document in database\n\n        Returns\n        -------\n        ImageHandle\n            Handle for image object"
  },
  {
    "code": "def get_files(self, file_paths):\n    results = []\n    def get_file_thunk(path, interface):\n      result = error = None \n      try:\n        result = interface.get_file(path)\n      except Exception as err:\n        error = err\n        print(err) \n      content, encoding = result\n      content = compression.decompress(content, encoding)\n      results.append({\n        \"filename\": path,\n        \"content\": content,\n        \"error\": error,\n      })\n    for path in file_paths:\n      if len(self._threads):\n        self.put(partial(get_file_thunk, path))\n      else:\n        get_file_thunk(path, self._interface)\n    desc = 'Downloading' if self.progress else None\n    self.wait(desc)\n    return results",
    "docstring": "returns a list of files faster by using threads"
  },
  {
    "code": "def make_tree(self):\n        self.tree['is_ready'] = False\n        leaf_count = len(self.tree['leaves'])\n        if leaf_count > 0:\n            self._unshift(self.tree['levels'], self.tree['leaves'])\n            while len(self.tree['levels'][0]) > 1:\n                self._unshift(self.tree['levels'], self._calculate_next_level())\n        self.tree['is_ready'] = True",
    "docstring": "Generates the merkle tree."
  },
  {
    "code": "def get_all_hits(self):\n        page_size = 100\n        search_rs = self.search_hits(page_size=page_size)\n        total_records = int(search_rs.TotalNumResults)\n        get_page_hits = lambda(page): self.search_hits(page_size=page_size, page_number=page)\n        page_nums = self._get_pages(page_size, total_records)\n        hit_sets = itertools.imap(get_page_hits, page_nums)\n        return itertools.chain.from_iterable(hit_sets)",
    "docstring": "Return all of a Requester's HITs\n        \n        Despite what search_hits says, it does not return all hits, but\n        instead returns a page of hits. This method will pull the hits\n        from the server 100 at a time, but will yield the results\n        iteratively, so subsequent requests are made on demand."
  },
  {
    "code": "def homepage():\n    if current_user.is_authenticated():\n        if not login_fresh():\n            logging.debug('User needs a fresh token')\n            abort(login.needs_refresh())\n        auth.claim_invitations(current_user)\n    build_list = operations.UserOps(current_user.get_id()).get_builds()\n    return render_template(\n        'home.html',\n        build_list=build_list,\n        show_video_and_promo_text=app.config['SHOW_VIDEO_AND_PROMO_TEXT'])",
    "docstring": "Renders the homepage."
  },
  {
    "code": "def get_switch_macs(self, switch_ip=None, node=None, vlan=None, mac=None, port=None, verbose=0):\n        if (switch_ip == None):\n            if (node == None):\n                raise Exception('get_switch_macs() requires switch_ip or node parameter')\n                return None\n            switch_ip = node.get_ipaddr()\n        mac_obj = natlas_mac(self.config)\n        if (vlan == None):\n            macs = mac_obj.get_macs(switch_ip, verbose)\n        else:\n            macs = mac_obj.get_macs_for_vlan(switch_ip, vlan, verbose)\n        if ((mac == None) & (port == None)):\n            return macs if macs else []\n        ret = []\n        for m in macs:\n            if (mac != None):\n                if (re.match(mac, m.mac) == None):\n                    continue\n            if (port != None):\n                if (re.match(port, m.port) == None):\n                    continue\n            ret.append(m)\n        return ret",
    "docstring": "Get the CAM table from a switch.\n\n        Args:\n            switch_ip           IP address of the device\n            node                natlas_node from new_node()\n            vlan                Filter results by VLAN\n            MAC                 Filter results by MAC address (regex)\n            port                Filter results by port (regex)\n            verbose             Display progress to stdout\n\n            switch_ip or node is required\n\n        Return:\n            Array of natlas_mac objects"
  },
  {
    "code": "def get_cdn_auth_token(self, app_id, hostname):\n        return self.send_job_and_wait(MsgProto(EMsg.ClientGetCDNAuthToken),\n                                      {\n                                       'app_id': app_id,\n                                       'host_name': hostname,\n                                      },\n                                      timeout=15\n                                     )",
    "docstring": "Get CDN authentication token\n\n        :param app_id: app id\n        :type app_id: :class:`int`\n        :param hostname: cdn hostname\n        :type hostname: :class:`str`\n        :return: `CMsgClientGetCDNAuthTokenResponse <https://github.com/ValvePython/steam/blob/39627fe883feeed2206016bacd92cf0e4580ead6/protobufs/steammessages_clientserver_2.proto#L585-L589>`_\n        :rtype: proto message"
  },
  {
    "code": "def normalize_signature(func):\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        if kwargs:\n            args = args, kwargs\n        if len(args) is 1:\n            args = args[0]\n        return func(args)\n    return wrapper",
    "docstring": "Decorator.  Combine args and kwargs. Unpack single item tuples."
  },
  {
    "code": "def get_file_size(file_object):\n    position = file_object.tell()\n    file_object.seek(0, 2)\n    file_size = file_object.tell()\n    file_object.seek(position, 0)\n    return file_size",
    "docstring": "Returns the size, in bytes, of a file. Expects an object that supports\n    seek and tell methods.\n\n    Args:\n        file_object (file_object) - The object that represents the file\n\n    Returns:\n        (int): size of the file, in bytes"
  },
  {
    "code": "def _readse(self, pos):\n        codenum, pos = self._readue(pos)\n        m = (codenum + 1) // 2\n        if not codenum % 2:\n            return -m, pos\n        else:\n            return m, pos",
    "docstring": "Return interpretation of next bits as a signed exponential-Golomb code.\n\n        Advances position to after the read code.\n\n        Raises ReadError if the end of the bitstring is encountered while\n        reading the code."
  },
  {
    "code": "def fetch_class(full_class_name):\n    (module_name, class_name) = full_class_name.rsplit('.', 1)\n    module = importlib.import_module(module_name)\n    return getattr(module, class_name)",
    "docstring": "Fetches the given class.\n\n    :param string full_class_name: Name of the class to be fetched."
  },
  {
    "code": "def tree_render(request, upy_context, vars_dictionary):\n    page = upy_context['PAGE']\n    return render_to_response(page.template.file_name, vars_dictionary, context_instance=RequestContext(request))",
    "docstring": "It renders template defined in upy_context's page passed in arguments"
  },
  {
    "code": "def remove_object_from_list(self, obj, list_element):\n        list_element = self._handle_location(list_element)\n        if isinstance(obj, JSSObject):\n            results = [item for item in list_element.getchildren() if\n                       item.findtext(\"id\") == obj.id]\n        elif isinstance(obj, (int, basestring)):\n            results = [item for item in list_element.getchildren() if\n                       item.findtext(\"id\") == str(obj) or\n                       item.findtext(\"name\") == obj]\n        if len(results) == 1:\n            list_element.remove(results[0])\n        elif len(results) > 1:\n            raise ValueError(\"There is more than one matching object at that \"\n                             \"path!\")",
    "docstring": "Remove an object from a list element.\n\n        Args:\n            obj: Accepts JSSObjects, id's, and names\n            list_element: Accepts an Element or a string path to that\n                element"
  },
  {
    "code": "def cmp(cls, v1: 'VersionBase', v2: 'VersionBase') -> int:\n        if v1._version > v2._version:\n            return 1\n        elif v1._version == v2._version:\n            return 0\n        else:\n            return -1",
    "docstring": "Compares two instances."
  },
  {
    "code": "def frequency(self, context):\n        channels = self._manager.spectral_window_table.getcol(MS.CHAN_FREQ)\n        return channels.reshape(context.shape).astype(context.dtype)",
    "docstring": "Frequency data source"
  },
  {
    "code": "def view_assets_by_site(token, dstore):\n    taxonomies = dstore['assetcol/tagcol/taxonomy'].value\n    assets_by_site = dstore['assetcol'].assets_by_site()\n    data = ['taxonomy mean stddev min max num_sites num_assets'.split()]\n    num_assets = AccumDict()\n    for assets in assets_by_site:\n        num_assets += {k: [len(v)] for k, v in group_array(\n            assets, 'taxonomy').items()}\n    for taxo in sorted(num_assets):\n        val = numpy.array(num_assets[taxo])\n        data.append(stats(taxonomies[taxo], val, val.sum()))\n    if len(num_assets) > 1:\n        n_assets = numpy.array([len(assets) for assets in assets_by_site])\n        data.append(stats('*ALL*', n_assets, n_assets.sum()))\n    return rst_table(data)",
    "docstring": "Display statistical information about the distribution of the assets"
  },
  {
    "code": "def forwards(apps, schema_editor):\n    Event = apps.get_model('spectator_events', 'Event')\n    for ev in Event.objects.filter(kind='movie'):\n        ev.kind = 'cinema'\n        ev.save()\n    for ev in Event.objects.filter(kind='play'):\n        ev.kind = 'theatre'\n        ev.save()",
    "docstring": "Change Events with kind 'movie' to 'cinema'\n    and Events with kind 'play' to 'theatre'.\n\n    Purely for more consistency."
  },
  {
    "code": "def get_subgraph_from_edge_list(graph, edge_list):\n    node_list = get_vertices_from_edge_list(graph, edge_list)\n    subgraph = make_subgraph(graph, node_list, edge_list)\n    return subgraph",
    "docstring": "Transforms a list of edges into a subgraph."
  },
  {
    "code": "def captcha_refresh(request):\n    if not request.is_ajax():\n        raise Http404\n    new_key = CaptchaStore.pick()\n    to_json_response = {\n        'key': new_key,\n        'image_url': captcha_image_url(new_key),\n        'audio_url': captcha_audio_url(new_key) if settings.CAPTCHA_FLITE_PATH else None\n    }\n    return HttpResponse(json.dumps(to_json_response), content_type='application/json')",
    "docstring": "Return json with new captcha for ajax refresh request"
  },
  {
    "code": "def getMapScale(self, latitude, level, dpi=96):\n        dpm = dpi / 0.0254\n        return self.getGroundResolution(latitude, level) * dpm",
    "docstring": "returns the map scale on the dpi of the screen"
  },
  {
    "code": "def reinit_configurations(self, request):\n        now = timezone.now()\n        changed_resources = []\n        for resource_model in CostTrackingRegister.registered_resources:\n            for resource in resource_model.objects.all():\n                try:\n                    pe = models.PriceEstimate.objects.get(scope=resource, month=now.month, year=now.year)\n                except models.PriceEstimate.DoesNotExist:\n                    changed_resources.append(resource)\n                else:\n                    new_configuration = CostTrackingRegister.get_configuration(resource)\n                    if new_configuration != pe.consumption_details.configuration:\n                        changed_resources.append(resource)\n        for resource in changed_resources:\n            models.PriceEstimate.update_resource_estimate(resource, CostTrackingRegister.get_configuration(resource))\n        message = _('Configuration was reinitialized for %(count)s resources') % {'count': len(changed_resources)}\n        self.message_user(request, message)\n        return redirect(reverse('admin:cost_tracking_defaultpricelistitem_changelist'))",
    "docstring": "Re-initialize configuration for resource if it has been changed.\n\n            This method should be called if resource consumption strategy was changed."
  },
  {
    "code": "def postprocess_subject(self, entry):\n        if type(entry.subject) not in [str, unicode]:\n            subject = u' '.join([unicode(k) for k in entry.subject])\n        else:\n            subject = entry.subject\n        entry.subject = [k.strip().upper() for k in subject.split(';')]",
    "docstring": "Parse subject keywords.\n\n        Subject keywords are usually semicolon-delimited."
  },
  {
    "code": "def reset(self, configuration: dict) -> None:\n        self.clean(0)\n        self.backend.store_config(configuration)",
    "docstring": "Whenever there was anything stored in the database or not, purge previous state and start\n        new training process from scratch."
  },
  {
    "code": "def stop_listening(self):\n        self._halt_threads = True\n        for name, queue_waker in self.recieved_signals.items():\n            q, wake_event = queue_waker\n            wake_event.set()",
    "docstring": "Stop listener threads for acquistion queues"
  },
  {
    "code": "def _set_mpl_backend(self, backend, pylab=False):\n        import traceback\n        from IPython.core.getipython import get_ipython\n        generic_error = (\n            \"\\n\" + \"=\"*73 + \"\\n\"\n            \"NOTE: The following error appeared when setting \"\n            \"your Matplotlib backend!!\\n\" + \"=\"*73 + \"\\n\\n\"\n            \"{0}\"\n        )\n        magic = 'pylab' if pylab else 'matplotlib'\n        error = None\n        try:\n            get_ipython().run_line_magic(magic, backend)\n        except RuntimeError as err:\n            if \"GUI eventloops\" in str(err):\n                import matplotlib\n                previous_backend = matplotlib.get_backend()\n                if not backend in previous_backend.lower():\n                    error = (\n                        \"\\n\"\n                        \"NOTE: Spyder *can't* set your selected Matplotlib \"\n                        \"backend because there is a previous backend already \"\n                        \"in use.\\n\\n\"\n                        \"Your backend will be {0}\".format(previous_backend)\n                    )\n                del matplotlib\n            else:\n                error = generic_error.format(traceback.format_exc())\n        except Exception:\n            error = generic_error.format(traceback.format_exc())\n        self._mpl_backend_error = error",
    "docstring": "Set a backend for Matplotlib.\n\n        backend: A parameter that can be passed to %matplotlib\n                 (e.g. 'inline' or 'tk')."
  },
  {
    "code": "def define_new(cls, name, members, is_abstract=False):\n        m = OrderedDict(cls._members)\n        if set(m.keys()) & set(members.keys()):\n            raise ValueError(\"'members' contains keys that overlap with parent\")\n        m.update(members)\n        dct = {\n            '_members' : m,\n            '_is_abstract': is_abstract,\n        }\n        newcls = type(name, (cls,), dct)\n        return newcls",
    "docstring": "Define a new struct type derived from the current type.\n\n        Parameters\n        ----------\n        name: str\n            Name of the struct type\n        members: {member_name : type}\n            Dictionary of struct member types.\n        is_abstract: bool\n            If set, marks the struct as abstract."
  },
  {
    "code": "def format_single_dict(dictionary, output_name):\n        output_payload = {}\n        if dictionary:\n            for (k, v) in dictionary.items():\n                output_payload[output_name + '[' + k + ']'] = v\n        return output_payload",
    "docstring": "Currently used for metadata fields"
  },
  {
    "code": "def abort_keepalive_pings(self) -> None:\n        assert self.state is State.CLOSED\n        exc = ConnectionClosed(self.close_code, self.close_reason)\n        exc.__cause__ = self.transfer_data_exc\n        for ping in self.pings.values():\n            ping.set_exception(exc)\n        if self.pings:\n            pings_hex = \", \".join(\n                binascii.hexlify(ping_id).decode() or \"[empty]\"\n                for ping_id in self.pings\n            )\n            plural = \"s\" if len(self.pings) > 1 else \"\"\n            logger.debug(\n                \"%s - aborted pending ping%s: %s\", self.side, plural, pings_hex\n            )",
    "docstring": "Raise ConnectionClosed in pending keepalive pings.\n\n        They'll never receive a pong once the connection is closed."
  },
  {
    "code": "def verification_digit(numbers):\n        a = sum(numbers[::2])\n        b = a * 3\n        c = sum(numbers[1::2])\n        d = b + c\n        e = d % 10\n        if e == 0:\n            return e\n        return 10 - e",
    "docstring": "Returns the verification digit for a given numbre.\n\n        The verification digit is calculated as follows:\n\n        * A = sum of all even-positioned numbers\n        * B = A * 3\n        * C = sum of all odd-positioned numbers\n        * D = B + C\n        * The results is the smallset number N, such that (D + N) % 10 == 0\n\n        NOTE: Afip's documentation seems to have odd an even mixed up in the\n        explanation, but all examples follow the above algorithm.\n\n        :param list(int) numbers): The numbers for which the digits is to be\n            calculated.\n        :return: int"
  },
  {
    "code": "def map_unicode_string(self, unicode_string, ignore=False, single_char_parsing=False, return_as_list=False, return_can_map=False):\n        if unicode_string is None:\n            return None\n        ipa_string = IPAString(unicode_string=unicode_string, ignore=ignore, single_char_parsing=single_char_parsing)\n        return self.map_ipa_string(\n            ipa_string=ipa_string,\n            ignore=ignore,\n            return_as_list=return_as_list,\n            return_can_map=return_can_map\n        )",
    "docstring": "Convert the given Unicode string, representing an IPA string,\n        to a string containing the corresponding mapped representation.\n\n        Return ``None`` if ``unicode_string`` is ``None``.\n\n        :param str unicode_string: the Unicode string to be parsed\n        :param bool ignore: if ``True``, ignore Unicode characters that are not IPA valid\n        :param bool single_char_parsing: if ``True``, parse one Unicode character at a time\n        :param bool return_as_list: if ``True``, return as a list of strings, one for each IPAChar,\n                                    instead of their concatenation (single str)\n        :param bool return_can_map: if ``True``, return a pair ``(bool, str)``, where the first element\n                                    says if the mapper can map all the IPA characters in the given IPA string,\n                                    and the second element is either ``None`` or the mapped string/list\n        :rtype: str or (bool, str) or (bool, list)"
  },
  {
    "code": "def get_values(self, config_manager, ignore_mismatches, obj_hook=DotDict):\n        if self.delayed_parser_instantiation:\n            try:\n                app = config_manager._get_option('admin.application')\n                source = \"%s%s\" % (app.value.app_name, file_name_extension)\n                self.config_obj = configobj.ConfigObj(source)\n                self.delayed_parser_instantiation = False\n            except AttributeError:\n                return obj_hook()\n        if isinstance(self.config_obj, obj_hook):\n            return self.config_obj\n        return obj_hook(initializer=self.config_obj)",
    "docstring": "Return a nested dictionary representing the values in the ini file.\n        In the case of this ValueSource implementation, both parameters are\n        dummies."
  },
  {
    "code": "def day_fraction(time):\n    hour = int(time.split(\":\")[0])\n    minute = int(time.split(\":\")[1])\n    return hour/24 + minute/1440",
    "docstring": "Convert a 24-hour time to a fraction of a day.\n\n    For example, midnight corresponds to 0.0, and noon to 0.5.\n\n    :param time: Time in the form of 'HH:MM' (24-hour time)\n    :type time: string\n\n    :return: A day fraction\n    :rtype: float\n\n    :Examples:\n\n    .. code-block:: python\n\n        day_fraction(\"18:30\")"
  },
  {
    "code": "def _idx_to_bits(self, i):\n    bits = bin(i)[2:].zfill(self.nb_hyperplanes)\n    return [-1.0 if b == \"0\" else 1.0 for b in bits]",
    "docstring": "Convert an group index to its bit representation."
  },
  {
    "code": "def run(self, change):\n        if self._formats is None:\n            self.setup()\n        entry = self.entry\n        for fmt in self._formats:\n            fmt.run(change, entry)\n        self.clear()",
    "docstring": "runs the report format instances in this reporter. Will call setup\n        if it hasn't been called already"
  },
  {
    "code": "def sheets(self):\n        data = Dict()\n        for src in [src for src in self.zipfile.namelist() if 'xl/worksheets/' in src]:\n            name = os.path.splitext(os.path.basename(src))[0]\n            xml = self.xml(src)\n            data[name] = xml\n        return data",
    "docstring": "return the sheets of data."
  },
  {
    "code": "def get_coherent_next_tag(prev_label: str, cur_label: str) -> str:\n    if cur_label == \"O\":\n        return \"O\"\n    if prev_label == cur_label:\n        return f\"I-{cur_label}\"\n    else:\n        return f\"B-{cur_label}\"",
    "docstring": "Generate a coherent tag, given previous tag and current label."
  },
  {
    "code": "def values(self):\n        dtypes = [col.dtype for col in self.columns]\n        if len(set(dtypes)) > 1:\n            dtype = object\n        else:\n            dtype = None\n        return np.array(self.columns, dtype=dtype).T",
    "docstring": "Return data in `self` as a numpy array.\n\n        If all columns are the same dtype, the resulting array\n        will have this dtype. If there are >1 dtypes in columns,\n        then the resulting array will have dtype `object`."
  },
  {
    "code": "def validate(self, sources):\n        if not isinstance(sources, Root):\n            raise Exception(\"Source object expected\")\n        parameters = self.get_uri_with_missing_parameters(sources)\n        for parameter in parameters:\n            logging.getLogger().warn('Missing parameter \"%s\" in uri of method \"%s\" in versions \"%s\"' % (parameter[\"name\"], parameter[\"method\"], parameter[\"version\"]))",
    "docstring": "Validate the format of sources"
  },
  {
    "code": "def add_ref(self, ref):\n        self.refs[ref.insn_addr].append(ref)\n        self.data_addr_to_ref[ref.memory_data.addr].append(ref)",
    "docstring": "Add a reference to a memory data object.\n\n        :param CodeReference ref:   The reference.\n        :return:                    None"
  },
  {
    "code": "def dasopr(fname):\n    fname = stypes.stringToCharP(fname)\n    handle = ctypes.c_int()\n    libspice.dasopr_c(fname, ctypes.byref(handle))\n    return handle.value",
    "docstring": "Open a DAS file for reading.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html\n\n    :param fname: Name of a DAS file to be opened.\n    :type fname: str\n    :return: Handle assigned to the opened DAS file.\n    :rtype: int"
  },
  {
    "code": "def average_price(quantity_1, price_1, quantity_2, price_2):\n    return (quantity_1 * price_1 + quantity_2 * price_2) / \\\n            (quantity_1 + quantity_2)",
    "docstring": "Calculates the average price between two asset states."
  },
  {
    "code": "def lookup_controller(obj, remainder, request=None):\n    if request is None:\n        warnings.warn(\n            (\n                \"The function signature for %s.lookup_controller is changing \"\n                \"in the next version of pecan.\\nPlease update to: \"\n                \"`lookup_controller(self, obj, remainder, request)`.\" % (\n                    __name__,\n                )\n            ),\n            DeprecationWarning\n        )\n    notfound_handlers = []\n    while True:\n        try:\n            obj, remainder = find_object(obj, remainder, notfound_handlers,\n                                         request)\n            handle_security(obj)\n            return obj, remainder\n        except (exc.HTTPNotFound, exc.HTTPMethodNotAllowed,\n                PecanNotFound) as e:\n            if isinstance(e, PecanNotFound):\n                e = exc.HTTPNotFound()\n            while notfound_handlers:\n                name, obj, remainder = notfound_handlers.pop()\n                if name == '_default':\n                    return obj, remainder\n                else:\n                    result = handle_lookup_traversal(obj, remainder)\n                    if result:\n                        if (\n                            remainder == [''] and\n                            len(obj._pecan['argspec'].args) > 1\n                        ):\n                            raise e\n                        obj_, remainder_ = result\n                        return lookup_controller(obj_, remainder_, request)\n            else:\n                raise e",
    "docstring": "Traverses the requested url path and returns the appropriate controller\n    object, including default routes.\n\n    Handles common errors gracefully."
  },
  {
    "code": "def new_tag(self, name: str, category: str=None) -> models.Tag:\n        new_tag = self.Tag(name=name, category=category)\n        return new_tag",
    "docstring": "Create a new tag."
  },
  {
    "code": "def get_atoms(self, ligands=True, pseudo_group=False, inc_alt_states=False):\n        atoms = itertools.chain(\n            *(list(m.get_atoms(inc_alt_states=inc_alt_states))\n                for m in self.get_monomers(ligands=ligands,\n                                           pseudo_group=pseudo_group)))\n        return atoms",
    "docstring": "Flat list of all the `Atoms` in the `Assembly`.\n\n        Parameters\n        ----------\n        ligands : bool, optional\n            Include ligand `Atoms`.\n        pseudo_group : bool, optional\n            Include pseudo_group `Atoms`.\n        inc_alt_states : bool, optional\n            Include alternate sidechain conformations.\n\n        Returns\n        -------\n        atoms : itertools.chain\n            All the `Atoms` as a iterator."
  },
  {
    "code": "def list_security_groups_in_vpc(self, vpc_id=None):\n        log = logging.getLogger(self.cls_logger + '.list_security_groups_in_vpc')\n        if vpc_id is None and self.vpc_id is not None:\n            vpc_id = self.vpc_id\n        else:\n            msg = 'Unable to determine VPC ID to use to create the Security Group'\n            log.error(msg)\n            raise EC2UtilError(msg)\n        filters = [\n            {\n                'Name': 'vpc-id',\n                'Values': [vpc_id]\n            }\n        ]\n        log.info('Querying for a list of security groups in VPC ID: {v}'.format(v=vpc_id))\n        try:\n            security_groups = self.client.describe_security_groups(DryRun=False, Filters=filters)\n        except ClientError:\n            _, ex, trace = sys.exc_info()\n            msg = 'Unable to query AWS for a list of security groups in VPC ID: {v}\\n{e}'.format(\n                v=vpc_id, e=str(ex))\n            raise AWSAPIError, msg, trace\n        return security_groups",
    "docstring": "Lists security groups in the VPC.  If vpc_id is not provided, use self.vpc_id\n\n        :param vpc_id: (str) VPC ID to list security groups for\n        :return: (list) Security Group info\n        :raises: AWSAPIError, EC2UtilError"
  },
  {
    "code": "def get_locations(self, ip, detailed=False):\n        if isinstance(ip, str):\n            ip = [ip]\n        seek = map(self._get_pos, ip)\n        return [self._parse_location(elem, detailed=detailed) if elem > 0 else False for elem in seek]",
    "docstring": "Returns a list of dictionaries with location data or False \n        on failure. Argument `ip` must be an iterable object.\n        \n        Amount of information about IP contained in the dictionary depends\n        upon `detailed` flag state."
  },
  {
    "code": "def history_add(self, value):\n        if self._history_max_size is None or self.history_len() < self._history_max_size:\n            self._history.append(value)\n        else:\n            self._history = self._history[1:] + [value]",
    "docstring": "Add a value in the history"
  },
  {
    "code": "def _apply_transformation(inputs):\n    ts, transformation, extend_collection, clear_redo = inputs\n    new = ts.append_transformation(transformation, extend_collection,\n                                   clear_redo=clear_redo)\n    o = [ts]\n    if new:\n        o.extend(new)\n    return o",
    "docstring": "Helper method for multiprocessing of apply_transformation. Must not be\n    in the class so that it can be pickled.\n\n    Args:\n        inputs: Tuple containing the transformed structure, the transformation\n            to be applied, a boolean indicating whether to extend the\n            collection, and a boolean indicating whether to clear the redo\n\n    Returns:\n        List of output structures (the modified initial structure, plus\n        any new structures created by a one-to-many transformation)"
  },
  {
    "code": "def populate_readme(\n    version, circleci_build, appveyor_build, coveralls_build, travis_build\n):\n    with open(RELEASE_README_FILE, \"r\") as file_obj:\n        template = file_obj.read()\n    contents = template.format(\n        version=version,\n        circleci_build=circleci_build,\n        appveyor_build=appveyor_build,\n        coveralls_build=coveralls_build,\n        travis_build=travis_build,\n    )\n    with open(README_FILE, \"w\") as file_obj:\n        file_obj.write(contents)",
    "docstring": "Populates ``README.rst`` with release-specific data.\n\n    This is because ``README.rst`` is used on PyPI.\n\n    Args:\n        version (str): The current version.\n        circleci_build (Union[str, int]): The CircleCI build ID corresponding\n            to the release.\n        appveyor_build (str): The AppVeyor build ID corresponding to the\n            release.\n        coveralls_build (Union[str, int]): The Coveralls.io build ID\n            corresponding to the release.\n        travis_build (int): The Travis CI build ID corresponding to\n            the release."
  },
  {
    "code": "def addResourceFile(self, pid, resource_file, resource_filename=None, progress_callback=None):\n        url = \"{url_base}/resource/{pid}/files/\".format(url_base=self.url_base,\n                                                        pid=pid)\n        params = {}\n        close_fd = self._prepareFileForUpload(params, resource_file, resource_filename)\n        encoder = MultipartEncoder(params)\n        if progress_callback is None:\n            progress_callback = default_progress_callback\n        monitor = MultipartEncoderMonitor(encoder, progress_callback)\n        r = self._request('POST', url, data=monitor, headers={'Content-Type': monitor.content_type})\n        if close_fd:\n            fd = params['file'][1]\n            fd.close()\n        if r.status_code != 201:\n            if r.status_code == 403:\n                raise HydroShareNotAuthorized(('POST', url))\n            elif r.status_code == 404:\n                raise HydroShareNotFound((pid,))\n            else:\n                raise HydroShareHTTPException((url, 'POST', r.status_code))\n        response = r.json()\n        return response",
    "docstring": "Add a new file to an existing resource\n\n        :param pid: The HydroShare ID of the resource\n        :param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a string\n            representing path to file to be uploaded as part of the new resource\n        :param resource_filename: string representing the filename of the resource file.  Must be specified\n            if resource_file is a file-like object.  If resource_file is a string representing a valid file path,\n            and resource_filename is not specified, resource_filename will be equal to os.path.basename(resource_file).\n            is a string\n        :param progress_callback: user-defined function to provide feedback to the user about the progress\n            of the upload of resource_file.  For more information, see:\n            http://toolbelt.readthedocs.org/en/latest/uploading-data.html#monitoring-your-streaming-multipart-upload\n\n        :return: Dictionary containing 'resource_id' the ID of the resource to which the file was added, and\n                'file_name' the filename of the file added.\n\n        :raises: HydroShareNotAuthorized if user is not authorized to perform action.\n        :raises: HydroShareNotFound if the resource was not found.\n        :raises: HydroShareHTTPException if an unexpected HTTP response code is encountered."
  },
  {
    "code": "def component_doi(soup):\n    component_doi = []\n    object_id_tags = raw_parser.object_id(soup, pub_id_type = \"doi\")\n    component_list = components(soup)\n    position = 1\n    for tag in object_id_tags:\n        component_object = {}\n        component_object[\"doi\"] = doi_uri_to_doi(tag.text)\n        component_object[\"position\"] = position\n        for component in component_list:\n            if \"doi\" in component and component[\"doi\"] == component_object[\"doi\"]:\n                component_object[\"type\"] = component[\"type\"]\n        component_doi.append(component_object)\n        position = position + 1\n    return component_doi",
    "docstring": "Look for all object-id of pub-type-id = doi, these are the component DOI tags"
  },
  {
    "code": "def create_geometry(self, input_geometry, upper_depth, lower_depth):\n        self._check_seismogenic_depths(upper_depth, lower_depth)\n        if not isinstance(input_geometry, Point):\n            if not isinstance(input_geometry, np.ndarray):\n                raise ValueError('Unrecognised or unsupported geometry '\n                                 'definition')\n            self.geometry = Point(input_geometry[0], input_geometry[1])\n        else:\n            self.geometry = input_geometry",
    "docstring": "If geometry is defined as a numpy array then create instance of\n        nhlib.geo.point.Point class, otherwise if already instance of class\n        accept class\n\n        :param input_geometry:\n            Input geometry (point) as either\n            i) instance of nhlib.geo.point.Point class\n            ii) numpy.ndarray [Longitude, Latitude]\n\n        :param float upper_depth:\n            Upper seismogenic depth (km)\n\n        :param float lower_depth:\n            Lower seismogenic depth (km)"
  },
  {
    "code": "def config_babel(app):\n    \" Init application with babel. \"\n    babel.init_app(app)\n    def get_locale():\n        return request.accept_languages.best_match(app.config['BABEL_LANGUAGES'])\n    babel.localeselector(get_locale)",
    "docstring": "Init application with babel."
  },
  {
    "code": "def post_article_content(self, content, url, max_pages=25):\n        params = {\n            'doc': content,\n            'max_pages': max_pages\n        }\n        url = self._generate_url('parser', {\"url\": url})\n        return self.post(url, post_params=params)",
    "docstring": "POST content to be parsed to the Parser API.\n\n        Note: Even when POSTing content, a url must still be provided.\n\n        :param content: the content to be parsed\n        :param url: the url that represents the content\n        :param max_pages (optional): the maximum number of pages to parse\n            and combine. Default is 25."
  },
  {
    "code": "def _expand_users(device_users, common_users):\n    expected_users = deepcopy(common_users)\n    expected_users.update(device_users)\n    return expected_users",
    "docstring": "Creates a longer list of accepted users on the device."
  },
  {
    "code": "def generate(data, dimOrder, maxWindowSize, overlapPercent, transforms = []):\n\twidth = data.shape[dimOrder.index('w')]\n\theight = data.shape[dimOrder.index('h')]\n\treturn generateForSize(width, height, dimOrder, maxWindowSize, overlapPercent, transforms)",
    "docstring": "Generates a set of sliding windows for the specified dataset."
  },
  {
    "code": "def call_fan(tstat):\n    old_fan = tstat.fan\n    tstat.write({\n        'fan': not old_fan,\n    })\n    def restore():\n        tstat.write({\n            'fan': old_fan,\n        })\n    return restore",
    "docstring": "Toggles the fan"
  },
  {
    "code": "def camera_to_rays(camera):\n    half = np.radians(camera.fov / 2.0)\n    half *= (camera.resolution - 2) / camera.resolution\n    angles = util.grid_linspace(bounds=[-half, half],\n                                count=camera.resolution)\n    vectors = util.unitize(np.column_stack((\n        np.sin(angles),\n        np.ones(len(angles)))))\n    transform = np.dot(\n        camera.transform,\n        align_vectors([1, 0, 0], [-1, 0, 0]))\n    vectors = transformations.transform_points(\n        vectors,\n        transform,\n        translate=False)\n    origin = transformations.translation_from_matrix(transform)\n    origins = np.ones_like(vectors) * origin\n    return origins, vectors, angles",
    "docstring": "Convert a trimesh.scene.Camera object to ray origins\n    and direction vectors. Will return one ray per pixel,\n    as set in camera.resolution.\n\n    Parameters\n    --------------\n    camera : trimesh.scene.Camera\n      Camera with transform defined\n\n    Returns\n    --------------\n    origins : (n, 3) float\n      Ray origins in space\n    vectors : (n, 3) float\n      Ray direction unit vectors\n    angles : (n, 2) float\n      Ray spherical coordinate angles in radians"
  },
  {
    "code": "def generate_filename(self, requirement):\n        return FILENAME_PATTERN % (self.config.cache_format_revision,\n                                   requirement.name, requirement.version,\n                                   get_python_version())",
    "docstring": "Generate a distribution archive filename for a package.\n\n        :param requirement: A :class:`.Requirement` object.\n        :returns: The filename of the distribution archive (a string)\n                  including a single leading directory component to indicate\n                  the cache format revision."
  },
  {
    "code": "def _auth(url):\n    user = __salt__['config.get']('solr.user', False)\n    password = __salt__['config.get']('solr.passwd', False)\n    realm = __salt__['config.get']('solr.auth_realm', 'Solr')\n    if user and password:\n        basic = _HTTPBasicAuthHandler()\n        basic.add_password(\n            realm=realm, uri=url, user=user, passwd=password\n        )\n        digest = _HTTPDigestAuthHandler()\n        digest.add_password(\n            realm=realm, uri=url, user=user, passwd=password\n        )\n        _install_opener(\n            _build_opener(basic, digest)\n        )",
    "docstring": "Install an auth handler for urllib2"
  },
  {
    "code": "def set_edge_weight(self, edge, wt):\n        self.set_edge_properties(edge, weight=wt )\n        if not self.DIRECTED:\n            self.set_edge_properties((edge[1], edge[0]) , weight=wt )",
    "docstring": "Set the weight of an edge.\n\n        @type  edge: edge\n        @param edge: One edge.\n\n        @type  wt: number\n        @param wt: Edge weight."
  },
  {
    "code": "def parseArgsPy26():\n    from gsmtermlib.posoptparse import PosOptionParser, Option\n    parser = PosOptionParser(description='Simple script for sending SMS messages')\n    parser.add_option('-i', '--port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.')\n    parser.add_option('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate')\n    parser.add_option('-p', '--pin', metavar='PIN', default=None, help='SIM card PIN')\n    parser.add_option('-d', '--deliver',  action='store_true', help='wait for SMS delivery report')\n    parser.add_positional_argument(Option('--destination', metavar='DESTINATION', help='destination mobile number'))    \n    options, args = parser.parse_args()\n    if len(args) != 1:    \n        parser.error('Incorrect number of arguments - please specify a DESTINATION to send to, e.g. {0} 012789456'.format(sys.argv[0]))\n    else:\n        options.destination = args[0]\n        return options",
    "docstring": "Argument parser for Python 2.6"
  },
  {
    "code": "def type(self, newtype):\n        self._type = newtype\n        if self.is_multi:\n            for sibling in self.multi_rep.siblings:\n                sibling._type = newtype",
    "docstring": "If the feature is a multifeature, update all entries."
  },
  {
    "code": "def regexp_extract(str, pattern, idx):\n    r\n    sc = SparkContext._active_spark_context\n    jc = sc._jvm.functions.regexp_extract(_to_java_column(str), pattern, idx)\n    return Column(jc)",
    "docstring": "r\"\"\"Extract a specific group matched by a Java regex, from the specified string column.\n    If the regex did not match, or the specified group did not match, an empty string is returned.\n\n    >>> df = spark.createDataFrame([('100-200',)], ['str'])\n    >>> df.select(regexp_extract('str', r'(\\d+)-(\\d+)', 1).alias('d')).collect()\n    [Row(d=u'100')]\n    >>> df = spark.createDataFrame([('foo',)], ['str'])\n    >>> df.select(regexp_extract('str', r'(\\d+)', 1).alias('d')).collect()\n    [Row(d=u'')]\n    >>> df = spark.createDataFrame([('aaaac',)], ['str'])\n    >>> df.select(regexp_extract('str', '(a+)(b)?(c)', 2).alias('d')).collect()\n    [Row(d=u'')]"
  },
  {
    "code": "def read_config(file_name):\n    dirname = os.path.dirname(\n        os.path.abspath(file_name)\n    )\n    dirname = os.path.relpath(dirname)\n    def custom_str_constructor(loader, node):\n        return loader.construct_scalar(node).encode('utf-8')\n    yaml.add_constructor(u'tag:yaml.org,2002:str', custom_str_constructor)\n    config = []\n    with open(file_name) as f:\n        for item in yaml.load_all(f.read()):\n            config.append(\n                _process_config_item(item, dirname)\n            )\n    return config",
    "docstring": "Read YAML file with configuration and pointers to example data.\n\n    Args:\n        file_name (str): Name of the file, where the configuration is stored.\n\n    Returns:\n        dict: Parsed and processed data (see :func:`_process_config_item`).\n\n    Example YAML file::\n        html: simple_xml.xml\n        first:\n            data: i wan't this\n            required: true\n            notfoundmsg: Can't find variable $name.\n        second:\n            data: and this\n        ---\n        html: simple_xml2.xml\n        first:\n            data: something wanted\n            required: true\n            notfoundmsg: Can't find variable $name.\n        second:\n            data: another wanted thing"
  },
  {
    "code": "def set_data(self, index, value):\n        acces, field = self.get_item(index), self.header[index.column()]\n        self.beginResetModel()\n        self.set_data_hook(acces, field, value)\n        self.endResetModel()",
    "docstring": "Uses given data setter, and emit modelReset signal"
  },
  {
    "code": "def code(self):\n        if self._code is not None:\n            return self._code\n        elif self._defcode is not None:\n            return self._defcode\n        return 200",
    "docstring": "The HTTP response code associated with this ResponseObject.\n        If instantiated directly without overriding the code, returns\n        200 even if the default for the method is some other value.\n        Can be set or deleted; in the latter case, the default will be\n        restored."
  },
  {
    "code": "def cli(ctx):\n    level = logger.level\n    try:\n        level_to_name = logging._levelToName\n    except AttributeError:\n        level_to_name = logging._levelNames\n    level_name = level_to_name.get(level, level)\n    logger.debug('Verbosity set to {}.'.format(level_name))\n    if ctx.invoked_subcommand is None:\n        click.echo(ctx.get_help())\n        ctx.exit()\n    ctx.obj = {}",
    "docstring": "CLI for maildirs content analysis and deletion."
  },
  {
    "code": "def gen_for(self, node, target, local_iter, local_iter_decl, loop_body):\n        local_target = \"__target{0}\".format(id(node))\n        local_target_decl = self.types.builder.IteratorOfType(local_iter_decl)\n        if node.target.id in self.scope[node] and not hasattr(self, 'yields'):\n            local_type = \"auto&&\"\n        else:\n            local_type = \"\"\n        loop_body_prelude = Statement(\"{} {}= *{}\".format(local_type,\n                                                          target,\n                                                          local_target))\n        assign = self.make_assign(local_target_decl, local_target, local_iter)\n        loop = For(\"{}.begin()\".format(assign),\n                   \"{0} < {1}.end()\".format(local_target, local_iter),\n                   \"++{0}\".format(local_target),\n                   Block([loop_body_prelude, loop_body]))\n        return [self.process_omp_attachements(node, loop)]",
    "docstring": "Create For representation on iterator for Cxx generation.\n\n        Examples\n        --------\n        >> \"omp parallel for\"\n        >> for i in xrange(10):\n        >>     ... do things ...\n\n        Becomes\n\n        >> \"omp parallel for shared(__iterX)\"\n        >> for(decltype(__iterX)::iterator __targetX = __iterX.begin();\n               __targetX < __iterX.end(); ++__targetX)\n        >>         auto&& i = *__targetX;\n        >>     ... do things ...\n\n        It the case of not local variable, typing for `i` disappear and typing\n        is removed for iterator in case of yields statement in function."
  },
  {
    "code": "def submit(self, stanza):\n        body = _encode(**stanza)\n        self.service.post(self.path, body=body)\n        return self",
    "docstring": "Adds keys to the current configuration stanza as a\n        dictionary of key-value pairs.\n\n        :param stanza: A dictionary of key-value pairs for the stanza.\n        :type stanza: ``dict``\n        :return: The :class:`Stanza` object."
  },
  {
    "code": "def _output_tags(self):\n        for class_name, properties in sorted(self.resources.items()):\n            for key, value in sorted(properties.items()):\n                validator = self.override.get_validator(class_name, key)\n                if key == 'Tags' and validator is None:\n                    print(\"from troposphere import Tags\")\n                    return\n        for class_name, properties in sorted(self.properties.items()):\n            for key, value in sorted(properties.items()):\n                validator = self.override.get_validator(class_name, key)\n                if key == 'Tags' and validator is None:\n                    print(\"from troposphere import Tags\")\n                    return",
    "docstring": "Look for a Tags object to output a Tags import"
  },
  {
    "code": "def get_supported_currency_choices(api_key):\n\timport stripe\n\tstripe.api_key = api_key\n\taccount = stripe.Account.retrieve()\n\tsupported_payment_currencies = stripe.CountrySpec.retrieve(account[\"country\"])[\n\t\t\"supported_payment_currencies\"\n\t]\n\treturn [(currency, currency.upper()) for currency in supported_payment_currencies]",
    "docstring": "Pull a stripe account's supported currencies and returns a choices tuple of those supported currencies.\n\n\t:param api_key: The api key associated with the account from which to pull data.\n\t:type api_key: str"
  },
  {
    "code": "def vary_name(name: Text):\n    snake = re.match(r'^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$', name)\n    if not snake:\n        fail('The project name is not a valid snake-case Python variable name')\n    camel = [x[0].upper() + x[1:] for x in name.split('_')]\n    return {\n        'project_name_snake': name,\n        'project_name_camel': ''.join(camel),\n        'project_name_readable': ' '.join(camel),\n    }",
    "docstring": "Validates the name and creates variations"
  },
  {
    "code": "def print_math(math_expression_lst, name = \"math.html\", out='html', formatter = lambda x: x):\n    try: shutil.rmtree('viz')\n    except: pass\n    pth = get_cur_path()+print_math_template_path\n    shutil.copytree(pth, 'viz')\n    html_loc = None\n    if out == \"html\":\n        html_loc = pth+\"standalone_index.html\"\n    if out == \"notebook\":  \n        from IPython.display import display, HTML\n        html_loc = pth+\"notebook_index.html\"\n    html = open(html_loc).read()\n    html = html.replace(\"__MATH_LIST__\", json.dumps(math_expression_lst))\n    if out == \"notebook\": \n        display(HTML(html))\n    elif out == \"html\":\n        with open(name, \"w+\") as out_f:\n            out_f.write(html)",
    "docstring": "Converts LaTeX math expressions into an html layout.\n    Creates a html file in the directory where print_math is called\n    by default. Displays math to jupyter notebook if \"notebook\" argument\n    is specified.\n\n    Args:\n        math_expression_lst (list):  A list of LaTeX math (string) to be rendered by KaTeX\n        out (string): {\"html\"|\"notebook\"}: HTML by default. Specifies output medium.\n        formatter (function): function that cleans up the string for KaTeX. \n    Returns:\n        A HTML file in the directory where this function is called, or displays\n        HTML output in a notebook."
  },
  {
    "code": "def least_upper_bound(*intervals_to_join):\n        assert len(intervals_to_join) > 0, \"No intervals to join\"\n        all_same = all(x.bits == intervals_to_join[0].bits for x in intervals_to_join)\n        assert all_same, \"All intervals to join should be same\"\n        if len(intervals_to_join) == 1:\n            return intervals_to_join[0].copy()\n        if len(intervals_to_join) == 2:\n            return StridedInterval.pseudo_join(intervals_to_join[0], intervals_to_join[1])\n        sorted_intervals = sorted(intervals_to_join, key=lambda x: x.lower_bound)\n        ret = None\n        for i in xrange(len(sorted_intervals)):\n            si = reduce(lambda x, y: StridedInterval.pseudo_join(x, y, False), sorted_intervals[i:] + sorted_intervals[0:i])\n            if ret is None or ret.n_values > si.n_values:\n                ret = si\n        if any([x for x in intervals_to_join if x.uninitialized]):\n            ret.uninitialized = True\n        return ret",
    "docstring": "Pseudo least upper bound.\n        Join the given set of intervals into a big interval. The resulting strided interval is the one which in\n        all the possible joins of the presented SI, presented the least number of values.\n\n        The number of joins to compute is linear with the number of intervals to join.\n\n        Draft of proof:\n        Considering  three generic SI (a,b, and c) ordered from their lower bounds, such that\n        a.lower_bund <= b.lower_bound <= c.lower_bound, where <= is the lexicographic less or equal.\n        The only joins which have sense to compute are:\n        * a U b U c\n        * b U c U a\n        * c U a U b\n\n        All the other combinations fall in either one of these cases. For example: b U a U c does not make make sense\n        to be calculated. In fact, if one draws this union, the result is exactly either (b U c U a) or (a U b U c) or\n        (c U a U b).\n        :param intervals_to_join: Intervals to join\n        :return: Interval that contains all intervals"
  },
  {
    "code": "def get_callee_account(\n    global_state: GlobalState, callee_address: str, dynamic_loader: DynLoader\n):\n    environment = global_state.environment\n    accounts = global_state.accounts\n    try:\n        return global_state.accounts[callee_address]\n    except KeyError:\n        log.debug(\"Module with address \" + callee_address + \" not loaded.\")\n    if dynamic_loader is None:\n        raise ValueError()\n    log.debug(\"Attempting to load dependency\")\n    try:\n        code = dynamic_loader.dynld(callee_address)\n    except ValueError as error:\n        log.debug(\"Unable to execute dynamic loader because: {}\".format(str(error)))\n        raise error\n    if code is None:\n        log.debug(\"No code returned, not a contract account?\")\n        raise ValueError()\n    log.debug(\"Dependency loaded: \" + callee_address)\n    callee_account = Account(\n        callee_address, code, callee_address, dynamic_loader=dynamic_loader\n    )\n    accounts[callee_address] = callee_account\n    return callee_account",
    "docstring": "Gets the callees account from the global_state.\n\n    :param global_state: state to look in\n    :param callee_address: address of the callee\n    :param dynamic_loader: dynamic loader to use\n    :return: Account belonging to callee"
  },
  {
    "code": "def get_report(self):\n    ostr = ''\n    ostr += \"target\\tquery\\tcnt\\ttotal\\n\"\n    poss = ['-','A','C','G','T']\n    for target in poss:\n      for query in poss:\n        ostr += target+ \"\\t\"+query+\"\\t\"+str(self.matrix[target][query])+\"\\t\"+str(self.alignment_length)+\"\\n\"\n    return ostr",
    "docstring": "Another report, but not context based"
  },
  {
    "code": "def _autorestart_components(self, bundle):\n        with self.__instances_lock:\n            instances = self.__auto_restart.get(bundle)\n            if not instances:\n                return\n            for factory, name, properties in instances:\n                try:\n                    self.instantiate(factory, name, properties)\n                except Exception as ex:\n                    _logger.exception(\n                        \"Error restarting component '%s' ('%s') \"\n                        \"from bundle %s (%d): %s\",\n                        name,\n                        factory,\n                        bundle.get_symbolic_name(),\n                        bundle.get_bundle_id(),\n                        ex,\n                    )",
    "docstring": "Restart the components of the given bundle\n\n        :param bundle: A Bundle object"
  },
  {
    "code": "def get_access_token(self):\n        if self.token_info and not self.is_token_expired(self.token_info):\n            return self.token_info['access_token']\n        token_info = self._request_access_token()\n        token_info = self._add_custom_values_to_token_info(token_info)\n        self.token_info = token_info\n        return self.token_info['access_token']",
    "docstring": "If a valid access token is in memory, returns it\n        Else feches a new token and returns it"
  },
  {
    "code": "def _get_pos(self, key):\n        p = bisect(self.runtime._keys, self.hashi(key))\n        if p == len(self.runtime._keys):\n            return 0\n        else:\n            return p",
    "docstring": "Get the index of the given key in the sorted key list.\n\n        We return the position with the nearest hash based on\n        the provided key unless we reach the end of the continuum/ring\n        in which case we return the 0 (beginning) index position.\n\n        :param key: the key to hash and look for."
  },
  {
    "code": "def storage_volume_templates(self):\n        if not self.__storage_volume_templates:\n            self.__storage_volume_templates = StorageVolumeTemplates(self.__connection)\n        return self.__storage_volume_templates",
    "docstring": "Gets the StorageVolumeTemplates API client.\n\n        Returns:\n            StorageVolumeTemplates:"
  },
  {
    "code": "def rename_datastore(datastore_ref, new_datastore_name):\n    ds_name = get_managed_object_name(datastore_ref)\n    log.trace(\"Renaming datastore '%s' to '%s'\", ds_name, new_datastore_name)\n    try:\n        datastore_ref.RenameDatastore(new_datastore_name)\n    except vim.fault.NoPermission as exc:\n        log.exception(exc)\n        raise salt.exceptions.VMwareApiError(\n            'Not enough permissions. Required privilege: '\n            '{}'.format(exc.privilegeId))\n    except vim.fault.VimFault as exc:\n        log.exception(exc)\n        raise salt.exceptions.VMwareApiError(exc.msg)\n    except vmodl.RuntimeFault as exc:\n        log.exception(exc)\n        raise salt.exceptions.VMwareRuntimeError(exc.msg)",
    "docstring": "Renames a datastore\n\n    datastore_ref\n        vim.Datastore reference to the datastore object to be changed\n\n    new_datastore_name\n        New datastore name"
  },
  {
    "code": "def generic_visit(self, node):\n        assert isinstance(node, ast.expr)\n        res = self.assign(node)\n        return res, self.explanation_param(self.display(res))",
    "docstring": "Handle expressions we don't have custom code for."
  },
  {
    "code": "def get_hw_virt_ex_property(self, property_p):\n        if not isinstance(property_p, HWVirtExPropertyType):\n            raise TypeError(\"property_p can only be an instance of type HWVirtExPropertyType\")\n        value = self._call(\"getHWVirtExProperty\",\n                     in_p=[property_p])\n        return value",
    "docstring": "Returns the value of the specified hardware virtualization boolean property.\n\n        in property_p of type :class:`HWVirtExPropertyType`\n            Property type to query.\n\n        return value of type bool\n            Property value.\n\n        raises :class:`OleErrorInvalidarg`\n            Invalid property."
  },
  {
    "code": "def files(self):\n        self._check_session()\n        status, data = self._rest.get_request('files')\n        return data",
    "docstring": "Get list of files, for this session, on server."
  },
  {
    "code": "def _perform_radius_auth(self, client, packet):\n        try:\n            reply = client.SendPacket(packet)\n        except Timeout as e:\n            logging.error(\"RADIUS timeout occurred contacting %s:%s\" % (\n                client.server, client.authport))\n            return False\n        except Exception as e:\n            logging.error(\"RADIUS error: %s\" % e)\n            return False\n        if reply.code == AccessReject:\n            logging.warning(\"RADIUS access rejected for user '%s'\" % (\n                packet['User-Name']))\n            return False\n        elif reply.code != AccessAccept:\n            logging.error(\"RADIUS access error for user '%s' (code %s)\" % (\n                packet['User-Name'], reply.code))\n            return False\n        logging.info(\"RADIUS access granted for user '%s'\" % (\n            packet['User-Name']))\n        return True",
    "docstring": "Perform the actual radius authentication by passing the given packet\n        to the server which `client` is bound to.\n        Returns True or False depending on whether the user is authenticated\n        successfully."
  },
  {
    "code": "def neighbor_difference(self):\n        differences = np.zeros(self.num_neurons)\n        num_neighbors = np.zeros(self.num_neurons)\n        distance, _ = self.distance_function(self.weights, self.weights)\n        for x, y in self.neighbors():\n            differences[x] += distance[x, y]\n            num_neighbors[x] += 1\n        return differences / num_neighbors",
    "docstring": "Get the euclidean distance between a node and its neighbors."
  },
  {
    "code": "def iter_format_modules(lang):\n    if check_for_language(lang):\n        format_locations = []\n        for path in CUSTOM_FORMAT_MODULE_PATHS:\n            format_locations.append(path + '.%s')\n        format_locations.append('django.conf.locale.%s')\n        locale = to_locale(lang)\n        locales = [locale]\n        if '_' in locale:\n            locales.append(locale.split('_')[0])\n        for location in format_locations:\n            for loc in locales:\n                try:\n                    yield import_module('.formats', location % loc)\n                except ImportError:\n                    pass",
    "docstring": "Does the heavy lifting of finding format modules."
  },
  {
    "code": "def get_interface(self, interface='eth0'):\n        LOG.info(\"RPC: get_interface interfae: %s\" % interface)\n        code, message, data = agent_utils.get_interface(interface)\n        return agent_utils.make_response(code, message, data)",
    "docstring": "Interface info.\n\n        ifconfig interface"
  },
  {
    "code": "def get_currency_aggregate_by_symbol(self, symbol: str) -> CurrencyAggregate:\n        currency = self.get_by_symbol(symbol)\n        result = self.get_currency_aggregate(currency)\n        return result",
    "docstring": "Creates currency aggregate for the given currency symbol"
  },
  {
    "code": "def get_bit_width(self, resource):\n        datatype = resource.datatype\n        if \"uint\" in datatype:\n            bit_width = int(datatype.split(\"uint\")[1])\n        else:\n            raise ValueError(\"Unsupported datatype: {}\".format(datatype))\n        return bit_width",
    "docstring": "Method to return the bit width for blosc based on the Resource"
  },
  {
    "code": "def Emailer(recipients, sender=None):\n    import smtplib\n    hostname = socket.gethostname()\n    if not sender:\n        sender = 'lggr@{0}'.format(hostname)\n    smtp = smtplib.SMTP('localhost')\n    try:\n        while True:\n            logstr = (yield)\n            try:\n                smtp.sendmail(sender, recipients, logstr)\n            except smtplib.SMTPException:\n                pass\n    except GeneratorExit:\n        smtp.quit()",
    "docstring": "Sends messages as emails to the given list\n        of recipients."
  },
  {
    "code": "def next(self):\n        return self.iterator.next(task=self.task, timeout=self.timeout,\n                                                    block=self.block)",
    "docstring": "Returns a result if availble within \"timeout\" else raises a \n        ``TimeoutError`` exception. See documentation for ``NuMap.next``."
  },
  {
    "code": "async def execute(self, sql: str, parameters: Iterable[Any] = None) -> None:\n        if parameters is None:\n            parameters = []\n        await self._execute(self._cursor.execute, sql, parameters)",
    "docstring": "Execute the given query."
  },
  {
    "code": "def run(self):\n        while True:\n            try:\n                self.perform_iteration()\n            except Exception:\n                traceback.print_exc()\n                pass\n            time.sleep(ray_constants.REPORTER_UPDATE_INTERVAL_MS / 1000)",
    "docstring": "Run the reporter."
  },
  {
    "code": "def startup(api=None):\n    def startup_wrapper(startup_function):\n        apply_to_api = hug.API(api) if api else hug.api.from_object(startup_function)\n        apply_to_api.add_startup_handler(startup_function)\n        return startup_function\n    return startup_wrapper",
    "docstring": "Runs the provided function on startup, passing in an instance of the api"
  },
  {
    "code": "def register():\n    signals.article_generator_finalized.connect(link_source_files)\n    signals.page_generator_finalized.connect(link_source_files)\n    signals.page_writer_finalized.connect(write_source_files)",
    "docstring": "Calls the shots, based on signals"
  },
  {
    "code": "def standardize(self, axis=1):\n        if axis == 1:\n            return self.map(lambda x: x / std(x))\n        elif axis == 0:\n            stdval = self.std().toarray()\n            return self.map(lambda x: x / stdval)\n        else:\n            raise Exception('Axis must be 0 or 1')",
    "docstring": "Divide by standard deviation either within or across records.\n\n        Parameters\n        ----------\n        axis : int, optional, default = 0\n            Which axis to standardize along, within (1) or across (0) records"
  },
  {
    "code": "def path(self, *args: typing.List[str]) -> typing.Union[None, str]:\n        if not self._project:\n            return None\n        return environ.paths.clean(os.path.join(\n            self._project.source_directory,\n            *args\n        ))",
    "docstring": "Creates an absolute path in the project source directory from the\n        relative path components.\n\n        :param args:\n            Relative components for creating a path within the project source\n            directory\n        :return:\n            An absolute path to the specified file or directory within the\n            project source directory."
  },
  {
    "code": "def open(self):\n        self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        self.device.connect((self.host, self.port))\n        if self.device is None:\n            print \"Could not open socket for %s\" % self.host",
    "docstring": "Open TCP socket and set it as escpos device"
  },
  {
    "code": "def _dictionary(self):\n        retval = {}\n        for variant in self._override_order:\n            retval.update(self._config[variant])\n        return retval",
    "docstring": "A dictionary representing the loaded configuration."
  },
  {
    "code": "def GetDefaultContract(self):\n        try:\n            return self.GetContracts()[0]\n        except Exception as e:\n            logger.error(\"Could not find default contract: %s\" % str(e))\n            raise",
    "docstring": "Get the default contract.\n\n        Returns:\n            contract (Contract): if Successful, a contract of type neo.SmartContract.Contract, otherwise an Exception.\n\n        Raises:\n            Exception: if no default contract is found.\n\n        Note:\n            Prints a warning to the console if the default contract could not be found."
  },
  {
    "code": "def join_filter(sep, seq, pred=bool):\n    return sep.join([text_type(i) for i in seq if pred(i)])",
    "docstring": "Join with a filter."
  },
  {
    "code": "def get_attachments(self):\n        attachments = []\n        for attachment in self.context.getAttachment():\n            attachment_info = self.get_attachment_info(attachment)\n            attachments.append(attachment_info)\n        for analysis in self.context.getAnalyses(full_objects=True):\n            for attachment in analysis.getAttachment():\n                attachment_info = self.get_attachment_info(attachment)\n                attachment_info[\"analysis\"] = analysis.Title()\n                attachment_info[\"analysis_uid\"] = api.get_uid(analysis)\n                attachments.append(attachment_info)\n        return attachments",
    "docstring": "Returns a list of attachments info dictionaries\n\n        Original code taken from bika.lims.analysisrequest.view"
  },
  {
    "code": "def fit(self, X, y=None):\n        if self.normalize:\n            X = normalize(X)\n        self._check_force_weights()\n        random_state = check_random_state(self.random_state)\n        X = self._check_fit_data(X)\n        (\n            self.cluster_centers_,\n            self.labels_,\n            self.inertia_,\n            self.weights_,\n            self.concentrations_,\n            self.posterior_,\n        ) = movMF(\n            X,\n            self.n_clusters,\n            posterior_type=self.posterior_type,\n            force_weights=self.force_weights,\n            n_init=self.n_init,\n            n_jobs=self.n_jobs,\n            max_iter=self.max_iter,\n            verbose=self.verbose,\n            init=self.init,\n            random_state=random_state,\n            tol=self.tol,\n            copy_x=self.copy_x,\n        )\n        return self",
    "docstring": "Compute mixture of von Mises Fisher clustering.\n\n        Parameters\n        ----------\n        X : array-like or sparse matrix, shape=(n_samples, n_features)"
  },
  {
    "code": "def all(self, axis=None, *args, **kwargs):\n        nv.validate_all(args, kwargs)\n        values = self.sp_values\n        if len(values) != len(self) and not np.all(self.fill_value):\n            return False\n        return values.all()",
    "docstring": "Tests whether all elements evaluate True\n\n        Returns\n        -------\n        all : bool\n\n        See Also\n        --------\n        numpy.all"
  },
  {
    "code": "def _encrypt_data_key(\n        self, data_key: DataKey, algorithm: AlgorithmSuite, encryption_context: Dict[Text, Text]\n    ) -> NoReturn:\n        raise NotImplementedError(\"CountingMasterKey does not support encrypt_data_key\")",
    "docstring": "Encrypt a data key and return the ciphertext.\n\n        :param data_key: Unencrypted data key\n        :type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`\n            or :class:`aws_encryption_sdk.structures.DataKey`\n        :param algorithm: Algorithm object which directs how this Master Key will encrypt the data key\n        :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n        :param dict encryption_context: Encryption context to use in encryption\n        :raises NotImplementedError: when called"
  },
  {
    "code": "def __dict_to_pod_spec(spec):\n    spec_obj = kubernetes.client.V1PodSpec()\n    for key, value in iteritems(spec):\n        if hasattr(spec_obj, key):\n            setattr(spec_obj, key, value)\n    return spec_obj",
    "docstring": "Converts a dictionary into kubernetes V1PodSpec instance."
  },
  {
    "code": "def variable_iter(self, base):\n        base_substs = dict(('<' + t + '>', u) for (t, u) in base.items())\n        substs = []\n        vals = []\n        for with_defn in self.with_exprs:\n            substs.append('<' + with_defn[0] + '>')\n            vals.append(Host.expand_with(with_defn[1:]))\n        for val_tpl in product(*vals):\n            r = base_substs.copy()\n            r.update(dict(zip(substs, val_tpl)))\n            yield r",
    "docstring": "returns iterator over the cross product of the variables\n        for this stanza"
  },
  {
    "code": "def transform(self, vector):\n        if isinstance(vector, RDD):\n            vector = vector.map(_convert_to_vector)\n        else:\n            vector = _convert_to_vector(vector)\n        return callMLlibFunc(\"elementwiseProductVector\", self.scalingVector, vector)",
    "docstring": "Computes the Hadamard product of the vector."
  },
  {
    "code": "def add_nodes(self, nodes):\n        if not isinstance(nodes, list):\n            add_list = [nodes]\n        else:\n            add_list = nodes\n        self.node_list.extend(add_list)",
    "docstring": "Add a given node or list of nodes to self.node_list.\n\n        Args:\n            node (Node or list[Node]): the node or list of nodes to add\n                to the graph\n\n        Returns: None\n\n        Examples:\n\n        Adding one node: ::\n\n            >>> from blur.markov.node import Node\n            >>> graph = Graph()\n            >>> node_1 = Node('One')\n            >>> graph.add_nodes(node_1)\n            >>> print([node.value for node in graph.node_list])\n            ['One']\n\n        Adding multiple nodes at a time in a list: ::\n\n            >>> from blur.markov.node import Node\n            >>> graph = Graph()\n            >>> node_1 = Node('One')\n            >>> node_2 = Node('Two')\n            >>> graph.add_nodes([node_1, node_2])\n            >>> print([node.value for node in graph.node_list])\n            ['One', 'Two']"
  },
  {
    "code": "async def jsk_git(self, ctx: commands.Context, *, argument: CodeblockConverter):\n        return await ctx.invoke(self.jsk_shell, argument=Codeblock(argument.language, \"git \" + argument.content))",
    "docstring": "Shortcut for 'jsk sh git'. Invokes the system shell."
  },
  {
    "code": "def unpickle(pickle_file):\n    pickle = None\n    with open(pickle_file, \"rb\") as pickle_f:\n        pickle = dill.load(pickle_f)\n    if not pickle:\n        LOG.error(\"Could not load python object from file\")\n    return pickle",
    "docstring": "Unpickle a python object from the given path."
  },
  {
    "code": "def _get_hanging_wall_coeffs_mag(self, C, mag):\n        if mag < 5.5:\n            return 0.0\n        elif mag > 6.5:\n            return 1.0 + C[\"a2\"] * (mag - 6.5)\n        else:\n            return (mag - 5.5) * (1.0 + C[\"a2\"] * (mag - 6.5))",
    "docstring": "Returns the hanging wall magnitude term defined in equation 14"
  },
  {
    "code": "def initialize(cls) -> None:\n        if cls._initialized:\n            return\n        io_loop = ioloop.IOLoop.current()\n        cls._old_sigchld = signal.signal(\n            signal.SIGCHLD,\n            lambda sig, frame: io_loop.add_callback_from_signal(cls._cleanup),\n        )\n        cls._initialized = True",
    "docstring": "Initializes the ``SIGCHLD`` handler.\n\n        The signal handler is run on an `.IOLoop` to avoid locking issues.\n        Note that the `.IOLoop` used for signal handling need not be the\n        same one used by individual Subprocess objects (as long as the\n        ``IOLoops`` are each running in separate threads).\n\n        .. versionchanged:: 5.0\n           The ``io_loop`` argument (deprecated since version 4.1) has been\n           removed.\n\n        Availability: Unix"
  },
  {
    "code": "def get_aws_secrets_from_env():\n    keys = set()\n    for env_var in (\n        'AWS_SECRET_ACCESS_KEY', 'AWS_SECURITY_TOKEN', 'AWS_SESSION_TOKEN',\n    ):\n        if env_var in os.environ:\n            keys.add(os.environ[env_var])\n    return keys",
    "docstring": "Extract AWS secrets from environment variables."
  },
  {
    "code": "def set_widgets(self):\n        self.tblFunctions1.horizontalHeader().setSectionResizeMode(\n            QHeaderView.Stretch)\n        self.tblFunctions1.verticalHeader().setSectionResizeMode(\n            QHeaderView.Stretch)\n        self.populate_function_table_1()",
    "docstring": "Set widgets on the Impact Functions Table 1 tab."
  },
  {
    "code": "def load_stylesheet(pyside=True):\n    if pyside:\n        import qdarkstyle.pyside_style_rc\n    else:\n        import qdarkstyle.pyqt_style_rc\n    if not pyside:\n        from PyQt4.QtCore import QFile, QTextStream\n    else:\n        from PySide.QtCore import QFile, QTextStream\n    f = QFile(\":qdarkstyle/style.qss\")\n    if not f.exists():\n        _logger().error(\"Unable to load stylesheet, file not found in \"\n                        \"resources\")\n        return \"\"\n    else:\n        f.open(QFile.ReadOnly | QFile.Text)\n        ts = QTextStream(f)\n        stylesheet = ts.readAll()\n        if platform.system().lower() == 'darwin':\n            mac_fix =\n            stylesheet += mac_fix\n        return stylesheet",
    "docstring": "Loads the stylesheet. Takes care of importing the rc module.\n\n    :param pyside: True to load the pyside rc file, False to load the PyQt rc file\n\n    :return the stylesheet string"
  },
  {
    "code": "def set_image(self, image = None):\n        if image is None or type(image) is not int:\n            raise KPError(\"Need a new image number\")\n        else:\n            self.image = image\n            self.last_mod = datetime.now().replace(microsecond=0)\n            return True",
    "docstring": "This method is used to set the image number.\n\n        image must be an unsigned int."
  },
  {
    "code": "def _extend_word(self, word, length, prefix=0, end=False, flatten=False):\n        if len(word) == length:\n            if end and \"<\" not in self[word[-1]]:\n                raise GenerationError(word + \" cannot be extended\")\n            else:\n                return word\n        else:\n            exclude = {\"<\"}\n            while True:\n                choices = self.weighted_choices(word[-prefix\n                                                     if prefix > 0\n                                                     else 0:],\n                                                exclude=exclude,\n                                                flatten=flatten)\n                if not choices:\n                    raise GenerationError(word + \" cannot be extended\")\n                character = random_weighted_choice(choices)\n                word += character\n                try:\n                    word = self._extend_word(word, length, prefix=prefix,\n                                             end=end, flatten=flatten)\n                    return word\n                except GenerationError:\n                    exclude.add(character)\n                    word = word[:-1]",
    "docstring": "Extend the given word with a random suffix up to length.\n\n        :param length: the length of the extended word; >= len(word);\n        :param prefix: if greater than 0, the maximum length of the prefix to\n                       consider to choose the next character;\n        :param end: if True, the generated word ends as a word of table;\n        :param flatten: whether or not consider the table as flattened;\n        :return: a random word of length generated from table, extending word.\n        :raises GenerationError: if the generated word cannot be extended to\n                                 length."
  },
  {
    "code": "def _merge(x, y):\n    merged = {**x, **y}\n    xkeys = x.keys()\n    for key in xkeys:\n        if isinstance(x[key], dict) and key in y:\n            merged[key] = _merge(x[key], y[key])\n    return merged",
    "docstring": "Merge two nested dictionaries. Overwrite values in x with values in y."
  },
  {
    "code": "def set_environment_variable(self, key, val):\n        if self.get_environment_variable(key) in [None, val]:\n            self.__dict__['environment_variables'][key] = val\n        else:\n            raise Contradiction(\"Could not set environment variable %s\" % (key))",
    "docstring": "Sets a variable if that variable is not already set"
  },
  {
    "code": "def call(command, collect_missing=False, silent=True):\n  r\n  return (_execCommand if silent else execCommand)(shlex.split(command), collect_missing)",
    "docstring": "r\"\"\"Calls a task, as if it were called from the command line.\n\n  Args:\n    command (str): A route followed by params (as if it were entered in the shell).\n    collect_missing (bool): Collects any missing argument for the command through the shell. Defaults to False.\n\n  Returns:\n    The return value of the called command."
  },
  {
    "code": "def _sort_modules(mods):\n    def compare(x, y):\n        x = x[1]\n        y = y[1]\n        if x == y:\n            return 0\n        if y.stem == \"__init__.py\":\n            return 1\n        if x.stem == \"__init__.py\" or x < y:\n            return -1\n        return 1\n    return sorted(mods, key=cmp_to_key(compare))",
    "docstring": "Always sort `index` or `README` as first filename in list."
  },
  {
    "code": "def update(self, byte_arr):\n        if byte_arr:\n            self.value = self.calculate(byte_arr, self.value)",
    "docstring": "Read bytes and update the CRC computed."
  },
  {
    "code": "def match_patterns(codedata) :\n\tret = {}\n\tfor index1, pattern in enumerate(shaman.PatternMatcher.PATTERNS) :\n\t\tprint('Matching pattern %d \"%s\"' % (index1+1, pattern))\n\t\tmatcher = shaman.PatternMatcher(pattern)\n\t\ttmp = {}\n\t\tfor index2, (language, code) in enumerate(codedata) :\n\t\t\tif language not in shaman.SUPPORTING_LANGUAGES :\n\t\t\t\tcontinue\n\t\t\tif len(code) <= 20 or len(code) > 100000 :\n\t\t\t\tcontinue\n\t\t\tif language not in tmp :\n\t\t\t\ttmp[language] = []\n\t\t\tratio = matcher.getratio(code)\n\t\t\ttmp[language].append(ratio)\n\t\t\tprint('Matching patterns %d/%d    ' % (index2, len(codedata)), end='\\r')\n\t\tret[pattern] = {}\n\t\tfor language, data in tmp.items() :\n\t\t\tret[pattern][language] = sum(tmp[language]) / max(len(tmp[language]), 1)\n\tprint('Matching patterns completed          ')\n\treturn ret",
    "docstring": "Match patterns by shaman.PatternMatcher\n\t\tGet average ratio of pattern and language"
  },
  {
    "code": "def find_triangles(self):\n        return list(filter(lambda x: len(x) == 3, nx.find_cliques(self.model)))",
    "docstring": "Finds all the triangles present in the given model\n\n        Examples\n        --------\n        >>> from pgmpy.models import MarkovModel\n        >>> from pgmpy.factors.discrete import DiscreteFactor\n        >>> from pgmpy.inference import Mplp\n        >>> mm = MarkovModel()\n        >>> mm.add_nodes_from(['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7'])\n        >>> mm.add_edges_from([('x1', 'x3'), ('x1', 'x4'), ('x2', 'x4'),\n        ...                    ('x2', 'x5'), ('x3', 'x6'), ('x4', 'x6'),\n        ...                    ('x4', 'x7'), ('x5', 'x7')])\n        >>> phi = [DiscreteFactor(edge, [2, 2], np.random.rand(4)) for edge in mm.edges()]\n        >>> mm.add_factors(*phi)\n        >>> mplp = Mplp(mm)\n        >>> mplp.find_triangles()"
  },
  {
    "code": "def write_numeric(fmt, value, buff, byteorder='big'):\r\n    try:\r\n        buff.write(fmt[byteorder].pack(value))\r\n    except KeyError as exc:\r\n        raise ValueError('Invalid byte order') from exc",
    "docstring": "Write a numeric value to a file-like object."
  },
  {
    "code": "def fetch(self):\n        params = values.of({})\n        payload = self._version.fetch(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return EntityInstance(\n            self._version,\n            payload,\n            service_sid=self._solution['service_sid'],\n            identity=self._solution['identity'],\n        )",
    "docstring": "Fetch a EntityInstance\n\n        :returns: Fetched EntityInstance\n        :rtype: twilio.rest.authy.v1.service.entity.EntityInstance"
  },
  {
    "code": "def ft1file(self, **kwargs):\n        kwargs_copy = self.base_dict.copy()\n        kwargs_copy.update(**kwargs)\n        kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs))\n        self._replace_none(kwargs_copy)        \n        localpath = NameFactory.ft1file_format.format(**kwargs_copy)\n        if kwargs.get('fullpath', False):\n            return self.fullpath(localpath=localpath)\n        return localpath",
    "docstring": "return the name of the input ft1 file list"
  },
  {
    "code": "def get_terms(self, field=None):\n        if not field:\n            raise AttributeError(\"Please provide field to apply aggregation to!\")\n        agg = A(\"terms\", field=field, size=self.size, order={\"_count\": \"desc\"})\n        self.aggregations['terms_' + field] = agg\n        return self",
    "docstring": "Create a terms aggregation object and add it to the aggregation dict\n\n        :param field: the field present in the index that is to be aggregated\n        :returns: self, which allows the method to be chainable with the other methods"
  },
  {
    "code": "def put(self, item, block=True, timeout=None):\n        return self._queue.put(item, block, timeout)",
    "docstring": "Put item into underlying queue."
  },
  {
    "code": "def search(self, name, value):\n        partial = None\n        header_name_search_result = CocaineHeaders.STATIC_TABLE_MAPPING.get(name)\n        if header_name_search_result:\n            index = header_name_search_result[1].get(value)\n            if index is not None:\n                return index, name, value\n            partial = (header_name_search_result[0], name, None)\n        offset = len(CocaineHeaders.STATIC_TABLE)\n        for (i, (n, v)) in enumerate(self.dynamic_entries):\n            if n == name:\n                if v == value:\n                    return i + offset + 1, n, v\n                elif partial is None:\n                    partial = (i + offset + 1, n, None)\n        return partial",
    "docstring": "Searches the table for the entry specified by name\n        and value\n\n        Returns one of the following:\n            - ``None``, no match at all\n            - ``(index, name, None)`` for partial matches on name only.\n            - ``(index, name, value)`` for perfect matches."
  },
  {
    "code": "def clear_rr_ce_entries(self):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('This Primary Volume Descriptor is not yet initialized')\n        for block in self.rr_ce_blocks:\n            block.set_extent_location(-1)",
    "docstring": "A method to clear out all of the extent locations of all Rock Ridge\n        Continuation Entries that the PVD is tracking.  This can be used to\n        reset all data before assigning new data.\n\n        Parameters:\n         None.\n        Returns:\n         Nothing."
  },
  {
    "code": "def arches(self):\n        if self.method == 'image':\n            return self.params[2]\n        if self.arch:\n            return [self.arch]\n        return []",
    "docstring": "Return a list of architectures for this task.\n\n        :returns: a list of arch strings (eg [\"ppc64le\", \"x86_64\"]). The list\n                  is empty if this task has no arches associated with it."
  },
  {
    "code": "def rotation_matrix(d):\n    sin_angle = np.linalg.norm(d)\n    if sin_angle == 0:\n        return np.identity(3)\n    d /= sin_angle\n    eye = np.eye(3)\n    ddt = np.outer(d, d)\n    skew = np.array([[    0,  d[2],  -d[1]],\n                     [-d[2],     0,   d[0]],\n                     [ d[1], -d[0],     0]], dtype=np.float64)\n    M = ddt + np.sqrt(1 - sin_angle**2) * (eye - ddt) + sin_angle * skew\n    return M",
    "docstring": "Calculates a rotation matrix given a vector d. The direction of d\n    corresponds to the rotation axis. The length of d corresponds to\n    the sin of the angle of rotation.\n\n    Variant of: http://mail.scipy.org/pipermail/numpy-discussion/2009-March/040806.html"
  },
  {
    "code": "def Run(self, args):\n    try:\n      directory = vfs.VFSOpen(args.pathspec, progress_callback=self.Progress)\n    except (IOError, OSError) as e:\n      self.SetStatus(rdf_flows.GrrStatus.ReturnedStatus.IOERROR, e)\n      return\n    files = list(directory.ListFiles())\n    files.sort(key=lambda x: x.pathspec.path)\n    for response in files:\n      self.SendReply(response)",
    "docstring": "Lists a directory."
  },
  {
    "code": "def _get_cache_key(self, args, kwargs):\n        hash_input = json.dumps({'name': self.name, 'args': args, 'kwargs': kwargs}, sort_keys=True)\n        return hashlib.md5(hash_input).hexdigest()",
    "docstring": "Returns key to be used in cache"
  },
  {
    "code": "def _build_circle(self):\n        total_weight = 0\n        for node in self._nodes:\n            total_weight += self._weights.get(node, 1)\n        for node in self._nodes:\n            weight = self._weights.get(node, 1)\n            ks = math.floor((40 * len(self._nodes) * weight) / total_weight)\n            for i in xrange(0, int(ks)):\n                b_key = self._md5_digest('%s-%s-salt' % (node, i))\n                for l in xrange(0, 4):\n                    key = ((b_key[3 + l * 4] << 24)\n                           | (b_key[2 + l * 4] << 16)\n                           | (b_key[1 + l * 4] << 8)\n                           | b_key[l * 4])\n                    self._hashring[key] = node\n                    self._sorted_keys.append(key)\n        self._sorted_keys.sort()",
    "docstring": "Creates hash ring."
  },
  {
    "code": "def get_single_payload(self, query_obj):\n        payload = self.get_df_payload(query_obj)\n        df = payload.get('df')\n        status = payload.get('status')\n        if status != utils.QueryStatus.FAILED:\n            if df is not None and df.empty:\n                payload['error'] = 'No data'\n            else:\n                payload['data'] = self.get_data(df)\n        if 'df' in payload:\n            del payload['df']\n        return payload",
    "docstring": "Returns a payload of metadata and data"
  },
  {
    "code": "def make_url(self, method):\n        token = self.settings()['token']\n        return TELEGRAM_URL.format(\n            token=quote(token),\n            method=quote(method),\n        )",
    "docstring": "Generate a Telegram URL for this bot."
  },
  {
    "code": "def calculate_windows(self, **kwargs):\n        windows = find_windows(self.elements, self.coordinates, **kwargs)\n        if windows:\n            self.properties.update(\n                {\n                    'windows': {\n                        'diameters': windows[0], 'centre_of_mass': windows[1],\n                    }\n                }\n            )\n            return windows[0]\n        else:\n            self.properties.update(\n                {'windows': {'diameters': None,  'centre_of_mass': None, }}\n            )\n        return None",
    "docstring": "Return the diameters of all windows in a molecule.\n\n        This function first finds and then measures the diameters of all the\n        window in the molecule.\n\n        Returns\n        -------\n        :class:`numpy.array`\n            An array of windows' diameters.\n\n        :class:`NoneType`\n            If no windows were found."
  },
  {
    "code": "def pass_job(db: JobDB, result_queue: Queue, always_cache=False):\n    @pull\n    def pass_job_stream(job_source):\n        result_sink = result_queue.sink()\n        for message in job_source():\n            if message is EndOfQueue:\n                return\n            key, job = message\n            if always_cache or ('store' in job.hints):\n                status, retrieved_result = db.add_job_to_db(key, job)\n                if status == 'retrieved':\n                    result_sink.send(retrieved_result)\n                    continue\n                elif status == 'attached':\n                    continue\n            yield message\n    return pass_job_stream",
    "docstring": "Create a pull stream that receives jobs and passes them on to the\n    database. If the job already has a result, that result is pushed onto\n    the `result_queue`."
  },
  {
    "code": "def prerequisites(self):\n        prereqs = defaultdict(set)\n        for input in self.inputs:\n            spec = self._study.spec(input)\n            if spec.is_spec and spec.derived:\n                prereqs[spec.pipeline_getter].add(input.name)\n        return prereqs",
    "docstring": "Iterates through the inputs of the pipelinen and determines the\n        all prerequisite pipelines"
  },
  {
    "code": "def bytes2guid(s):\n    assert isinstance(s, bytes)\n    u = struct.unpack\n    v = []\n    v.extend(u(\"<IHH\", s[:8]))\n    v.extend(u(\">HQ\", s[8:10] + b\"\\x00\\x00\" + s[10:]))\n    return \"%08X-%04X-%04X-%04X-%012X\" % tuple(v)",
    "docstring": "Converts a serialized GUID to a text GUID"
  },
  {
    "code": "def load(self, mkey, mdesc, mdict=None, merge=False):\n        j = mdict if mdict else read_json(mdesc)\n        if j and isinstance(j, dict):\n            self.__meta['header'].update({mkey: mdesc})\n            if merge:\n                self.__meta = dict_merge(self.__meta, j)\n            else:\n                self.__meta['import'][mkey] = j\n            self.log = shell_notify(\n                'load %s data and %s it into meta' % (\n                    'got' if mdict else 'read',\n                    'merged' if merge else 'imported'\n                ),\n                more=dict(mkey=mkey, mdesc=mdesc, merge=merge),\n                verbose=self.__verbose\n            )\n        return j",
    "docstring": "Loads a dictionary into current meta\n\n        :param mkey:\n            Type of data to load.\n            Is be used to reference the data from the 'header' within meta\n        :param mdesc:\n            Either filename of json-file to load or further description\n            of imported data when `mdict` is used\n        :param dict mdict:\n            Directly pass data as dictionary instead of\n            loading it from a json-file.\n            Make sure to set `mkey` and `mdesc` accordingly\n        :param merge:\n            Merge received data into current meta or place it\n            under 'import' within meta\n        :returns:\n            The loaded (or directly passed) content"
  },
  {
    "code": "def DeleteConflict(self, conflict_link, options=None):\n        if options is None:\n            options = {}\n        path = base.GetPathFromLink(conflict_link)\n        conflict_id = base.GetResourceIdOrFullNameFromLink(conflict_link)\n        return self.DeleteResource(path,\n                                   'conflicts',\n                                   conflict_id,\n                                   None,\n                                   options)",
    "docstring": "Deletes a conflict.\n\n        :param str conflict_link:\n            The link to the conflict.\n        :param dict options:\n            The request options for the request.\n\n        :return:\n            The deleted Conflict.\n        :rtype:\n            dict"
  },
  {
    "code": "def process_signal(self, signum):\n        if signum == signal.SIGTERM:\n            LOGGER.info('Received SIGTERM, initiating shutdown')\n            self.stop()\n        elif signum == signal.SIGHUP:\n            LOGGER.info('Received SIGHUP')\n            if self.config.reload():\n                LOGGER.info('Configuration reloaded')\n                logging.config.dictConfig(self.config.logging)\n                self.on_configuration_reloaded()\n        elif signum == signal.SIGUSR1:\n            self.on_sigusr1()\n        elif signum == signal.SIGUSR2:\n            self.on_sigusr2()",
    "docstring": "Invoked whenever a signal is added to the stack.\n\n        :param int signum: The signal that was added"
  },
  {
    "code": "def start(self):\n        assert not self._started\n        self._listening_stream.on_recv(self._recv_callback)\n        self._started = True",
    "docstring": "Start to listen for incoming requests."
  },
  {
    "code": "def addfield(self, pkt, buf, val):\n        self.set_endianess(pkt)\n        return self.fld.addfield(pkt, buf, val)",
    "docstring": "add the field with endianness to the buffer"
  },
  {
    "code": "def split_line(self):\n        hash_or_end = self.line.find(\"\n        temp = self.line[self.region_end:hash_or_end].strip(\" |\")\n        self.coord_str = regex_paren.sub(\"\", temp)\n        if hash_or_end >= 0:\n            self.meta_str = self.line[hash_or_end:]\n        else:\n            self.meta_str = \"\"",
    "docstring": "Split line into coordinates and meta string"
  },
  {
    "code": "def save_file_json(data, export_file):\n    create_dir(os.path.dirname(export_file))\n    with open(export_file, \"w\") as file:\n        json.dump(data, file, indent=4)",
    "docstring": "Write data to a json file."
  },
  {
    "code": "def parse_metadata(cls, obj, xml):\n        for child in xml.xpath(\"ti:description\", namespaces=XPATH_NAMESPACES):\n            lg = child.get(\"{http://www.w3.org/XML/1998/namespace}lang\")\n            if lg is not None:\n                obj.set_cts_property(\"description\", child.text, lg)\n        for child in xml.xpath(\"ti:label\", namespaces=XPATH_NAMESPACES):\n            lg = child.get(\"{http://www.w3.org/XML/1998/namespace}lang\")\n            if lg is not None:\n                obj.set_cts_property(\"label\", child.text, lg)\n        obj.citation = cls.CLASS_CITATION.ingest(xml, obj.citation, \"ti:online/ti:citationMapping/ti:citation\")\n        for child in xml.xpath(\"ti:about\", namespaces=XPATH_NAMESPACES):\n            obj.set_link(RDF_NAMESPACES.CTS.term(\"about\"), child.get('urn'))\n        _parse_structured_metadata(obj, xml)",
    "docstring": "Parse a resource to feed the object\n\n        :param obj: Obj to set metadata of\n        :type obj: XmlCtsTextMetadata\n        :param xml: An xml representation object\n        :type xml: lxml.etree._Element"
  },
  {
    "code": "def create(args):\n    with _catalog(args) as cat:\n        for fname, created, obj in cat.create(args.args[0], {}):\n            args.log.info('{0} -> {1} object {2.id}'.format(\n                fname, 'new' if created else 'existing', obj))",
    "docstring": "cdstarcat create PATH\n\n    Create objects in CDSTAR specified by PATH.\n    When PATH is a file, a single object (possibly with multiple bitstreams) is created;\n    When PATH is a directory, an object will be created for each file in the directory\n    (recursing into subdirectories)."
  },
  {
    "code": "def interpolate_with(self, other_tf, t):\n        if t < 0 or t > 1:\n            raise ValueError('Must interpolate between 0 and 1')\n        interp_translation = (1.0 - t) * self.translation + t * other_tf.translation\n        interp_rotation = transformations.quaternion_slerp(self.quaternion, other_tf.quaternion, t)\n        interp_tf = RigidTransform(rotation=interp_rotation, translation=interp_translation,\n                                  from_frame = self.from_frame, to_frame = self.to_frame)\n        return interp_tf",
    "docstring": "Interpolate with another rigid transformation.\n\n        Parameters\n        ----------\n        other_tf : :obj:`RigidTransform`\n            The transform to interpolate with.\n\n        t : float\n            The interpolation step in [0,1], where 0 favors this RigidTransform.\n\n        Returns\n        -------\n        :obj:`RigidTransform`\n            The interpolated RigidTransform.\n\n        Raises\n        ------\n        ValueError\n            If t isn't in [0,1]."
  },
  {
    "code": "def norm_score(self):\n        cdf = (1.0 + math.erf(self.score / math.sqrt(2.0))) / 2.0\n        return 1 - 2*math.fabs(0.5 - cdf)",
    "docstring": "Return the normalized score.\n\n        Equals 1.0 for a z-score of 0, falling to 0.0 for extremely positive\n        or negative values."
  },
  {
    "code": "def bind(self, environ):\n        self.environ = environ\n        self.path = '/' + environ.get('PATH_INFO', '/').lstrip('/')\n        self.method = environ.get('REQUEST_METHOD', 'GET').upper()",
    "docstring": "Bind a new WSGI environment.\n\n            This is done automatically for the global `bottle.request`\n            instance on every request."
  },
  {
    "code": "def _gen_3spec(op, path, xattr=False):\n    flags = 0\n    if xattr:\n        flags |= _P.SDSPEC_F_XATTR\n    return Spec(op, path, flags)",
    "docstring": "Returns a Spec tuple suitable for passing to the underlying C extension.\n    This variant is called for operations that lack an input value.\n\n    :param str path: The path to fetch\n    :param bool xattr: Whether this is an extended attribute\n    :return: a spec suitable for passing to the underlying C extension"
  },
  {
    "code": "def as_rainbow(self, offset=35, style=None, rgb_mode=False):\n        return self._as_rainbow(\n            ('wrapper', ),\n            offset=offset,\n            style=style,\n            rgb_mode=rgb_mode,\n        )",
    "docstring": "Wrap each frame in a Colr object, using `Colr.rainbow`."
  },
  {
    "code": "def ci_macos():\n    run_command(\"brew install $PYTHON pipenv || echo \\\"Installed PipEnv\\\"\")\n    command_string = \"sudo -H $PIP install \"\n    for element in DEPENDENCIES + REQUIREMENTS + [\"-U\"]:\n        command_string += element + \" \"\n    run_command(command_string)\n    run_command(\"sudo -H $PYTHON setup.py bdist_wheel\")\n    assert check_wheel_existence()\n    exit(0)",
    "docstring": "Setup Travis-CI macOS for wheel building"
  },
  {
    "code": "def clicks(self, tag=None, fromdate=None, todate=None):\n        return self.call(\"GET\", \"/stats/outbound/clicks\", tag=tag, fromdate=fromdate, todate=todate)",
    "docstring": "Gets total counts of unique links that were clicked."
  },
  {
    "code": "def search(self, search):\n        search = search.replace('/', ' ')\n        params = {'q': search}\n        return self._get_records(params)",
    "docstring": "search Zenodo record for string `search`\n\n        :param search: string to search\n        :return: Record[] results"
  },
  {
    "code": "def get_tags_users(self, id_):\n    return _get_request(_TAGS_USERS.format(c_api=_C_API_BEGINNING,\n                                                                      api=_API_VERSION,\n                                                                      id_=id_,\n                                                                      at=self.access_token))",
    "docstring": "Get a particular user which are tagged based on the id_"
  },
  {
    "code": "def _set_cursor_position(self, value):\n        original_position = self.__cursor_position\n        self.__cursor_position = max(0, value)\n        return value != original_position",
    "docstring": "Set cursor position. Return whether it changed."
  },
  {
    "code": "def git_wrapper(path):\n    path = os.path.abspath(path)\n    if path not in _wrapper_cache:\n        if hasattr(Repo, 'commits'):\n            _wrapper_cache[path] = _GitWrapperLegacy(path)\n        else:\n            _wrapper_cache[path] = _GitWrapper(path)\n    return _wrapper_cache[path]",
    "docstring": "Get appropriate wrapper factory and cache instance for path"
  },
  {
    "code": "def install_versioning(self, conn):\n        logging.info('Creating the versioning table %s', self.version_table)\n        conn.executescript(CREATE_VERSIONING % self.version_table)\n        self._insert_script(self.read_scripts()[0], conn)",
    "docstring": "Create the version table into an already populated database\n        and insert the base script.\n\n        :param conn: a DB API 2 connection"
  },
  {
    "code": "def job(self, name):\n        for job in self.jobs():\n            if job.data.name == name:\n                return job",
    "docstring": "Method for searching specific job by it's name.\n\n        :param name: name of the job to search.\n        :return: found job or None.\n        :rtype: yagocd.resources.job.JobInstance"
  },
  {
    "code": "def decompress(self, chunk):\n        try:\n            return self._decompressobj.decompress(chunk)\n        except zlib.error:\n            if self._first_chunk:\n                self._decompressobj = zlib.decompressobj(-zlib.MAX_WBITS)\n                return self._decompressobj.decompress(chunk)\n            raise\n        finally:\n            self._first_chunk = False",
    "docstring": "Decompress the chunk of data.\n\n        :param bytes chunk: data chunk\n\n        :rtype: bytes"
  },
  {
    "code": "def get_version_history_for_file(self, filepath):\n        GIT_COMMIT_FIELDS = ['id',\n                             'author_name',\n                             'author_email',\n                             'date',\n                             'date_ISO_8601',\n                             'relative_date',\n                             'message_subject',\n                             'message_body']\n        GIT_LOG_FORMAT = ['%H', '%an', '%ae', '%aD', '%ai', '%ar', '%s', '%b']\n        GIT_LOG_FORMAT = '%x1f'.join(GIT_LOG_FORMAT) + '%x1e'\n        try:\n            log = git(self.gitdir,\n                      self.gitwd,\n                      '--no-pager',\n                      'log',\n                      '--format=%s' % GIT_LOG_FORMAT,\n                      '--follow',\n                      '--find-renames=100%',\n                      '--',\n                      filepath)\n            log = log.strip('\\n\\x1e').split(\"\\x1e\")\n            log = [row.strip().split(\"\\x1f\") for row in log]\n            log = [dict(zip(GIT_COMMIT_FIELDS, row)) for row in log]\n        except:\n            _LOG.exception('git log failed')\n            raise\n        return log",
    "docstring": "Return a dict representation of this file's commit history\n\n        This uses specially formatted git-log output for easy parsing, as described here:\n            http://blog.lost-theory.org/post/how-to-parse-git-log-output/\n        For a full list of available fields, see:\n            http://linux.die.net/man/1/git-log"
  },
  {
    "code": "def get_themes():\n    styles_dir = os.path.join(package_dir, 'styles')\n    themes = [os.path.basename(theme).replace('.less', '')\n              for theme in glob('{0}/*.less'.format(styles_dir))]\n    return themes",
    "docstring": "return list of available themes"
  },
  {
    "code": "def set_proxy_bypass(domains, network_service=\"Ethernet\"):\n    servers_str = ' '.join(domains)\n    cmd = 'networksetup -setproxybypassdomains {0} {1}'.format(network_service, servers_str,)\n    out = __salt__['cmd.run'](cmd)\n    return 'error' not in out",
    "docstring": "Sets the domains that can bypass the proxy\n\n    domains\n        An array of domains allowed to bypass the proxy\n\n    network_service\n        The network service to apply the changes to, this only necessary on\n        macOS\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' proxy.set_proxy_bypass \"['127.0.0.1', 'localhost']\""
  },
  {
    "code": "def suspend_queues(self, active_queues, sleep_time=10.0):\n        for queue in active_queues:\n            self.disable_queue(queue)\n        while self.get_active_tasks():\n            time.sleep(sleep_time)",
    "docstring": "Suspend Celery queues and wait for running tasks to complete."
  },
  {
    "code": "def find_all_segment(text: str, custom_dict: Trie = None) -> List[str]:\n    if not text or not isinstance(text, str):\n        return []\n    ww = list(_multicut(text, custom_dict=custom_dict))\n    return list(_combine(ww))",
    "docstring": "Get all possible segment variations\n\n    :param str text: input string to be tokenized\n    :return: returns list of segment variations"
  },
  {
    "code": "def create_session(self):\n        url = self.build_url(self._endpoints.get('create_session'))\n        response = self.con.post(url, data={'persistChanges': self.persist})\n        if not response:\n            raise RuntimeError('Could not create session as requested by the user.')\n        data = response.json()\n        self.session_id = data.get('id')\n        return True",
    "docstring": "Request a new session id"
  },
  {
    "code": "def get_next_action(self, request, application, label, roles):\n        if label is not None:\n            return HttpResponseBadRequest(\"<h1>Bad Request</h1>\")\n        actions = self.get_actions(request, application, roles)\n        if request.method == \"GET\":\n            context = self.context\n            context.update({\n                'application': application,\n                'actions': actions,\n                'state': self.name,\n                'roles': roles})\n            return render(\n                template_name='kgapplications/common_detail.html',\n                context=context,\n                request=request)\n        elif request.method == \"POST\":\n            for action in actions:\n                if action in request.POST:\n                    return action\n        return HttpResponseBadRequest(\"<h1>Bad Request</h1>\")",
    "docstring": "Django view method. We provide a default detail view for\n        applications."
  },
  {
    "code": "def process_pc_pathsbetween(gene_names, neighbor_limit=1,\n                            database_filter=None, block_size=None):\n    if not block_size:\n        model = pcc.graph_query('pathsbetween', gene_names,\n                                neighbor_limit=neighbor_limit,\n                                database_filter=database_filter)\n        if model is not None:\n            return process_model(model)\n    else:\n        gene_blocks = [gene_names[i:i + block_size] for i in\n                       range(0, len(gene_names), block_size)]\n        stmts = []\n        for genes1, genes2 in itertools.product(gene_blocks, repeat=2):\n            if genes1 == genes2:\n                bp = process_pc_pathsbetween(genes1,\n                                             database_filter=database_filter,\n                                             block_size=None)\n            else:\n                bp = process_pc_pathsfromto(genes1, genes2,\n                                            database_filter=database_filter)\n            stmts += bp.statements",
    "docstring": "Returns a BiopaxProcessor for a PathwayCommons paths-between query.\n\n    The paths-between query finds the paths between a set of genes. Here\n    source gene names are given in a single list and all directions of paths\n    between these genes are considered.\n\n    http://www.pathwaycommons.org/pc2/#graph\n\n    http://www.pathwaycommons.org/pc2/#graph_kind\n\n    Parameters\n    ----------\n    gene_names : list\n        A list of HGNC gene symbols to search for paths between.\n        Examples: ['BRAF', 'MAP2K1']\n    neighbor_limit : Optional[int]\n        The number of steps to limit the length of the paths between\n        the gene names being queried. Default: 1\n    database_filter : Optional[list]\n        A list of database identifiers to which the query is restricted.\n        Examples: ['reactome'], ['biogrid', 'pid', 'psp']\n        If not given, all databases are used in the query. For a full\n        list of databases see http://www.pathwaycommons.org/pc2/datasources\n    block_size : Optional[int]\n        Large paths-between queries (above ~60 genes) can error on the server\n        side. In this case, the query can be replaced by a series of\n        smaller paths-between and paths-from-to queries each of which contains\n        block_size genes.\n\n    Returns\n    -------\n    bp : BiopaxProcessor\n        A BiopaxProcessor containing the obtained BioPAX model in bp.model."
  },
  {
    "code": "def promote16(u, fn=None, *args, **kwargs):\n    r\n    dtype = np.float32 if u.dtype == np.float16 else u.dtype\n    up = np.asarray(u, dtype=dtype)\n    if fn is None:\n        return up\n    else:\n        v = fn(up, *args, **kwargs)\n        if isinstance(v, tuple):\n            vp = tuple([np.asarray(vk, dtype=u.dtype) for vk in v])\n        else:\n            vp = np.asarray(v, dtype=u.dtype)\n        return vp",
    "docstring": "r\"\"\"\n    Utility function for use with functions that do not support arrays\n    of dtype ``np.float16``. This function has two distinct modes of\n    operation. If called with only the `u` parameter specified, the\n    returned value is either `u` itself if `u` is not of dtype\n    ``np.float16``, or `u` promoted to ``np.float32`` dtype if it is. If\n    the function parameter `fn` is specified then `u` is conditionally\n    promoted as described above, passed as the first argument to\n    function `fn`, and the returned values are converted back to dtype\n    ``np.float16`` if `u` is of that dtype. Note that if parameter `fn`\n    is specified, it may not be be specified as a keyword argument if it\n    is followed by any non-keyword arguments.\n\n    Parameters\n    ----------\n    u : array_like\n      Array to be promoted to np.float32 if it is of dtype ``np.float16``\n    fn : function or None, optional (default None)\n      Function to be called with promoted `u` as first parameter and\n      \\*args and \\*\\*kwargs as additional parameters\n    *args\n      Variable length list of arguments for function `fn`\n    **kwargs\n      Keyword arguments for function `fn`\n\n    Returns\n    -------\n    up : ndarray\n      Conditionally dtype-promoted version of `u` if `fn` is None,\n      or value(s) returned by `fn`, converted to the same dtype as `u`,\n      if `fn` is a function"
  },
  {
    "code": "def _pull(self):\n        pull = self.m(\n            'pulling remote changes',\n            cmdd=dict(cmd='git pull --tags', cwd=self.local),\n            critical=False\n        )\n        if 'CONFLICT' in pull.get('out'):\n            self.m(\n                'Congratulations! You have merge conflicts in the repository!',\n                state=True,\n                more=pull\n            )\n        return pull",
    "docstring": "Helper function to pull from remote"
  },
  {
    "code": "def validate(self, path: str, strictness: str = \"speconly\") -> bool:\n\t\tvalid1 = True\n\t\twith h5py.File(path, mode=\"r\") as f:\n\t\t\tvalid1 = self.validate_spec(f)\n\t\t\tif not valid1:\n\t\t\t\tself.errors.append(\"For help, see http://linnarssonlab.org/loompy/format/\")\n\t\tvalid2 = True\n\t\tif strictness == \"conventions\":\n\t\t\twith loompy.connect(path, mode=\"r\") as ds:\n\t\t\t\tvalid2 = self.validate_conventions(ds)\n\t\t\t\tif not valid2:\n\t\t\t\t\tself.errors.append(\"For help, see http://linnarssonlab.org/loompy/conventions/\")\n\t\treturn valid1 and valid2",
    "docstring": "Validate a file for conformance to the Loom specification\n\n\t\tArgs:\n\t\t\tpath: \t\t\tFull path to the file to be validated\n\t\t\tstrictness:\t\t\"speconly\" or \"conventions\"\n\n\t\tRemarks:\n\t\t\tIn \"speconly\" mode, conformance is assessed relative to the file format specification\n\t\t\tat http://linnarssonlab.org/loompy/format/. In \"conventions\" mode, conformance is additionally\n\t\t\tassessed relative to attribute name and data type conventions given at http://linnarssonlab.org/loompy/conventions/."
  },
  {
    "code": "def do_first(self):\n        pid = os.getpid()\n        self.basename = os.path.join(self.tmpdir, 'iiif_netpbm_' + str(pid))\n        outfile = self.basename + '.pnm'\n        filetype = self.file_type(self.srcfile)\n        if (filetype == 'png'):\n            if (self.shell_call(self.pngtopnm + ' ' + self.srcfile + ' > ' + outfile)):\n                raise IIIFError(text=\"Oops... got error from pngtopnm.\")\n        elif (filetype == 'jpg'):\n            if (self.shell_call(self.jpegtopnm + ' ' + self.srcfile + ' > ' + outfile)):\n                raise IIIFError(text=\"Oops... got error from jpegtopnm.\")\n        else:\n            raise IIIFError(code='501',\n                            text='bad input file format (only know how to read png/jpeg)')\n        self.tmpfile = outfile\n        (self.width, self.height) = self.image_size(self.tmpfile)",
    "docstring": "Create PNM file from input image file."
  },
  {
    "code": "def update(self, friendly_name=values.unset,\n               assignment_callback_url=values.unset,\n               fallback_assignment_callback_url=values.unset,\n               configuration=values.unset, task_reservation_timeout=values.unset):\n        return self._proxy.update(\n            friendly_name=friendly_name,\n            assignment_callback_url=assignment_callback_url,\n            fallback_assignment_callback_url=fallback_assignment_callback_url,\n            configuration=configuration,\n            task_reservation_timeout=task_reservation_timeout,\n        )",
    "docstring": "Update the WorkflowInstance\n\n        :param unicode friendly_name: A string representing a human readable name for this Workflow.\n        :param unicode assignment_callback_url: A valid URL for the application that will process task assignment events.\n        :param unicode fallback_assignment_callback_url: If the request to the AssignmentCallbackUrl fails, the assignment callback will be made to this URL.\n        :param unicode configuration: JSON document configuring the rules for this Workflow.\n        :param unicode task_reservation_timeout: An integer value controlling how long in seconds TaskRouter will wait for a confirmation response from your application after assigning a Task to a worker.\n\n        :returns: Updated WorkflowInstance\n        :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance"
  },
  {
    "code": "def _validate_user_class(cls, user_class):\n        PraetorianError.require_condition(\n            getattr(user_class, 'lookup', None) is not None,\n            textwrap.dedent(\n),\n        )\n        PraetorianError.require_condition(\n            getattr(user_class, 'identify', None) is not None,\n            textwrap.dedent(\n),\n        )\n        return user_class",
    "docstring": "Validates the supplied user_class to make sure that it has the\n        class methods necessary to function correctly.\n\n        Requirements:\n\n        - ``lookup`` method. Accepts a string parameter, returns instance\n        - ``identify`` method. Accepts an identity parameter, returns instance"
  },
  {
    "code": "def _conv(self,v):\r\n        if isinstance(v,str):\r\n            return '\"%s\"' %v.replace(\"'\",\"''\")\r\n        elif isinstance(v,datetime.datetime):\r\n            if v.tzinfo is not None:\r\n                raise ValueError,\\\r\n                    \"datetime instances with tzinfo not supported\"\r\n            return '\"%s\"' %self.db_module.Timestamp(v.year,v.month,v.day,\r\n                v.hour,v.minute,v.second)\r\n        elif isinstance(v,datetime.date):\r\n            return '\"%s\"' %self.db_module.Date(v.year,v.month,v.day)\r\n        else:\r\n            return v",
    "docstring": "Convert Python values to MySQL values"
  },
  {
    "code": "def update_vip_request(self, vip_request, vip_request_id):\n        uri = 'api/v3/vip-request/%s/' % vip_request_id\n        data = dict()\n        data['vips'] = list()\n        data['vips'].append(vip_request)\n        return super(ApiVipRequest, self).put(uri, data)",
    "docstring": "Method to update vip request\n\n        param vip_request: vip_request object\n        param vip_request_id: vip_request id"
  },
  {
    "code": "def parse_compound_table_file(path, f):\n    context = FilePathContext(path)\n    for i, row in enumerate(csv.DictReader(f, delimiter=str('\\t'))):\n        if 'id' not in row or row['id'].strip() == '':\n            raise ParseError('Expected `id` column in table')\n        props = {key: value for key, value in iteritems(row) if value != ''}\n        if 'charge' in props:\n            props['charge'] = int(props['charge'])\n        mark = FileMark(context, i + 2, None)\n        yield CompoundEntry(props, mark)",
    "docstring": "Parse a tab-separated file containing compound IDs and properties\n\n    The compound properties are parsed according to the header which specifies\n    which property is contained in each column."
  },
  {
    "code": "def random_shift(image, wsr=0.1, hsr=0.1):\n  height, width, _ = common_layers.shape_list(image)\n  width_range, height_range = wsr*width, hsr*height\n  height_translations = tf.random_uniform((1,), -height_range, height_range)\n  width_translations = tf.random_uniform((1,), -width_range, width_range)\n  translations = tf.concat((height_translations, width_translations), axis=0)\n  return tf.contrib.image.translate(image, translations=translations)",
    "docstring": "Apply random horizontal and vertical shift to images.\n\n  This is the default data-augmentation strategy used on CIFAR in Glow.\n\n  Args:\n    image: a 3-D Tensor\n    wsr: Width shift range, as a float fraction of the width.\n    hsr: Height shift range, as a float fraction of the width.\n  Returns:\n    images: images translated by the provided wsr and hsr."
  },
  {
    "code": "def assertFileSizeEqual(self, filename, size, msg=None):\n        fsize = self._get_file_size(filename)\n        self.assertEqual(fsize, size, msg=msg)",
    "docstring": "Fail if ``filename`` does not have the given ``size`` as\n        determined by the '==' operator.\n\n        Parameters\n        ----------\n        filename : str, bytes, file-like\n        size : int, float\n        msg : str\n            If not provided, the :mod:`marbles.mixins` or\n            :mod:`unittest` standard message will be used.\n\n        Raises\n        ------\n        TypeError\n            If ``filename`` is not a str or bytes object and is not\n            file-like."
  },
  {
    "code": "def _compress_json(self, j):\n        compressed_json = copy.copy(j)\n        compressed_json.pop('users', None)\n        compressed_data = zlib.compress(\n            json.dumps(j['users']).encode('utf-8'),\n            self.zlib_compression_strength\n        )\n        b64_data = base64.b64encode(compressed_data).decode('utf-8')\n        compressed_json['blob'] = b64_data\n        return compressed_json",
    "docstring": "Compress the BLOB data portion of the usernotes.\n\n        Arguments:\n            j: the JSON in Schema v5 format (dict)\n\n        Returns a dict with the 'users' key removed and 'blob' key added"
  },
  {
    "code": "def check_values_selection_field(cr, table_name, field_name, allowed_values):\n    res = True\n    cr.execute(\"SELECT %s, count(*) FROM %s GROUP BY %s;\" %\n               (field_name, table_name, field_name))\n    for row in cr.fetchall():\n        if row[0] not in allowed_values:\n            logger.error(\n                \"Invalid value '%s' in the table '%s' \"\n                \"for the field '%s'. (%s rows).\",\n                row[0], table_name, field_name, row[1])\n            res = False\n    return res",
    "docstring": "check if the field selection 'field_name' of the table 'table_name'\n        has only the values 'allowed_values'.\n        If not return False and log an error.\n        If yes, return True.\n\n    .. versionadded:: 8.0"
  },
  {
    "code": "def build_command(chunks):\n    if not chunks:\n        raise ValueError(\n            \"No command parts: {} ({})\".format(chunks, type(chunks)))\n    if isinstance(chunks, str):\n        return chunks\n    parsed_pieces = []\n    for cmd_part in chunks:\n        if cmd_part is None:\n            continue\n        try:\n            parsed_pieces.append(cmd_part.strip(\" \"))\n        except AttributeError:\n            option, argument = cmd_part\n            if argument is None or argument == \"\":\n                continue\n            option, argument = option.strip(\" \"), str(argument).strip(\" \")\n            parsed_pieces.append(\"{} {}\".format(option, argument))\n    return \" \".join(parsed_pieces)",
    "docstring": "Create a command from various parts.\n\n    The parts provided may include a base, flags, option-bound arguments, and\n    positional arguments. Each element must be either a string or a two-tuple.\n    Raw strings are interpreted as either the command base, a pre-joined\n    pair (or multiple pairs) of option and argument, a series of positional\n    arguments, or a combination of those elements. The only modification they\n    undergo is trimming of any space characters from each end.\n\n    :param Iterable[str | (str, str | NoneType)] chunks: the collection of the\n        command components to interpret, modify, and join to create a\n        single meaningful command\n    :return str: the single meaningful command built from the given components\n    :raise ValueError: if no command parts are provided"
  },
  {
    "code": "def post_save_moderation(self, sender, comment, request, **kwargs):\n        model = comment.content_type.model_class()\n        if model not in self._registry:\n            return\n        self._registry[model].email(comment, comment.content_object, request)",
    "docstring": "Apply any necessary post-save moderation steps to new\n        comments."
  },
  {
    "code": "def listTargets(self):\n        sql = 'select * from {}'.format(self.TABLE_ITEMS)\n        cursor = self.db.execute(sql)\n        return [(iid, name, path) for iid, name, path in cursor]",
    "docstring": "Returns a list of all the items secured in the vault"
  },
  {
    "code": "def tokenize(self, config):\n        tokens = []\n        reg_ex = re.compile(self.TOKENS[0], re.M | re.I)\n        for token in re.finditer(reg_ex, config):\n            value = token.group(0)\n            if token.group(\"operator\"):\n                t_type = \"operator\"\n            elif token.group(\"literal\"):\n                t_type = \"literal\"\n            elif token.group(\"newline\"):\n                t_type = \"newline\"\n            elif token.group(\"function\"):\n                t_type = \"function\"\n            elif token.group(\"unknown\"):\n                t_type = \"unknown\"\n            else:\n                continue\n            tokens.append(\n                {\"type\": t_type, \"value\": value, \"match\": token, \"start\": token.start()}\n            )\n        self.tokens = tokens",
    "docstring": "Break the config into a series of tokens"
  },
  {
    "code": "def discovery(self, url=None):\n        if url:\n            data = self.session.get(url).content\n        elif self.discovery_url:\n            response = self.session.get(self.discovery_url)\n            if self.format == 'xml':\n                data = xml(response.text)\n            else:\n                data = response.json()\n        else:\n            data = self.get('discovery')\n        return data",
    "docstring": "Retrieve the standard discovery file that provides routing\n        information.\n\n        >>> Three().discovery()\n        {'discovery': 'data'}"
  },
  {
    "code": "def motif_from_consensus(cons, n=12):\n    width = len(cons)\n    nucs = {\"A\":0,\"C\":1,\"G\":2,\"T\":3}\n    pfm = [[0 for _ in range(4)] for _ in range(width)]\n    m = Motif()\n    for i,char in enumerate(cons):\n        for nuc in m.iupac[char.upper()]:\n            pfm[i][nucs[nuc]] = n / len(m.iupac[char.upper()])\n    m = Motif(pfm)\n    m.id = cons\n    return m",
    "docstring": "Convert consensus sequence to motif.\n\n    Converts a consensus sequences using the nucleotide IUPAC alphabet to a \n    motif. \n\n    Parameters\n    ----------\n    cons : str\n        Consensus sequence using the IUPAC alphabet.\n    n : int , optional\n        Count used to convert the sequence to a PFM.\n    \n    Returns\n    -------\n    m : Motif instance\n        Motif created from the consensus."
  },
  {
    "code": "def render_relation(self, r, **args):\n        if r is None:\n            return \".\"\n        m = self.config.relsymbolmap\n        if r in m:\n            return m[r]\n        return r",
    "docstring": "Render an object property"
  },
  {
    "code": "def purge_old(self):\n        if self.keep_max is not None:\n            keys = self.redis_conn.keys(self.get_key() + ':*')\n            keys.sort(reverse=True)\n            while len(keys) > self.keep_max:\n                key = keys.pop()\n                self.redis_conn.delete(key)",
    "docstring": "Removes keys that are beyond our keep_max limit"
  },
  {
    "code": "def msg(self, message, *args, **kwargs):\n        target = kwargs.pop('target', None)\n        raw = kwargs.pop('raw', False)\n        if not target:\n            target = self.line.sender.nick if self.line.pm else \\\n                self.line.target\n        if not raw:\n            kw = {\n                'm': self,\n                'b': chr(2),\n                'c': chr(3),\n                'u': chr(31),\n            }\n            kw.update(kwargs)\n            try:\n                message = message.format(*args, **kw)\n            except IndexError:\n                if len(args) == 1 and isinstance(args[0], list):\n                    message = message.format(*args[0], **kw)\n                else:\n                    raise\n        self.connection.msg(target, message)",
    "docstring": "Shortcut to send a message through the connection.\n\n        This function sends the input message through the connection. A target\n        can be defined, else it will send it to the channel or user from the\n        input Line, effectively responding on whatever triggered the command\n        which calls this function to be called. If raw has not been set to\n        True, formatting will be applied using the standard Python Formatting\n        Mini-Language, using the additional given args and kwargs, along with\n        some additional kwargs, such as the match object to easily access Regex\n        matches, color codes and other things.\n\n        http://docs.python.org/3.3/library/string.html#format-string-syntax"
  },
  {
    "code": "def configure(access_key=None, secret_key=None, logger=None):\n    if not logger:\n        logger = log.get_logger('s3')\n    if not all([access_key, secret_key]):\n        logger.info('')\n        access_key = input('AWS Access Key: ')\n        secret_key = input('AWS Secret Key: ')\n    _write_config(access_key, secret_key)\n    logger.info('')\n    logger.info('Completed writing S3 config file.')\n    logger.info('')",
    "docstring": "Configures s3cmd prior to first use.\n\n    If no arguments are provided, you will be prompted to enter\n    the access key and secret key interactively.\n\n    Args:\n\n        access_key (str): AWS access key\n\n        secret_key (str): AWS secret key"
  },
  {
    "code": "def _extract_asset_urls(self, asset_ids):\n        dom = get_page(self._session, OPENCOURSE_ASSET_URL,\n                       json=True,\n                       ids=quote_plus(','.join(asset_ids)))\n        return [{'id': element['id'],\n                 'url': element['url'].strip()}\n                for element in dom['elements']]",
    "docstring": "Extract asset URLs along with asset ids.\n\n        @param asset_ids: List of ids to get URLs for.\n        @type assertn: [str]\n\n        @return: List of dictionaries with asset URLs and ids.\n        @rtype: [{\n            'id': '<id>',\n            'url': '<url>'\n        }]"
  },
  {
    "code": "def getLayerName(url):\n    urlInfo = None\n    urlSplit = None\n    try:\n        urlInfo = urlparse.urlparse(url)\n        urlSplit = str(urlInfo.path).split('/')\n        name = urlSplit[len(urlSplit)-3]\n        return name\n    except:\n        return url\n    finally:\n        urlInfo = None\n        urlSplit = None\n        del urlInfo\n        del urlSplit\n        gc.collect()",
    "docstring": "Extract the layer name from a url.\n\n    Args:\n        url (str): The url to parse.\n\n    Returns:\n        str: The layer name.\n\n    Examples:\n        >>> url = \"http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12\"\n        >>> arcresthelper.common.getLayerIndex(url)\n        'test'"
  },
  {
    "code": "def get_all_tep(self):\n        teps = {}\n        for p in self.get_enabled_plugins:\n            for e, v in p[\"plugin_tep\"].items():\n                tep = teps.get(e, dict())\n                tepHF = tep.get(\"HTMLFile\", [])\n                tepHS = tep.get(\"HTMLString\", [])\n                tepHF += [s for f, s in v.items() if f == \"HTMLFile\"]\n                tepHS += [s for f, s in v.items() if f == \"HTMLString\"]\n                teps[e] = dict(HTMLFile=tepHF, HTMLString=tepHS)\n        return teps",
    "docstring": "Template extension point\n\n        :returns: dict: {tep: dict(HTMLFile=[], HTMLString=[]), tep...}"
  },
  {
    "code": "def updateMetadata(self, new):\n        if self.node_id != new.node_id:\n            raise ValueError(\"Broker metadata {!r} doesn't match node_id={}\".format(new, self.node_id))\n        self.node_id = new.node_id\n        self.host = new.host\n        self.port = new.port",
    "docstring": "Update the metadata stored for this broker.\n\n        Future connections made to the broker will use the host and port\n        defined in the new metadata. Any existing connection is not dropped,\n        however.\n\n        :param new:\n            :clas:`afkak.common.BrokerMetadata` with the same node ID as the\n            current metadata."
  },
  {
    "code": "def disable_alarm_actions(self, alarm_names):\n        params = {}\n        self.build_list_params(params, alarm_names, 'AlarmNames.member.%s')\n        return self.get_status('DisableAlarmActions', params)",
    "docstring": "Disables actions for the specified alarms.\n\n        :type alarms: list\n        :param alarms: List of alarm names."
  },
  {
    "code": "def sfs_folded(ac, n=None):\n    ac, n = _check_ac_n(ac, n)\n    mac = np.amin(ac, axis=1)\n    mac = mac.astype(int, copy=False)\n    x = n//2 + 1\n    s = np.bincount(mac, minlength=x)\n    return s",
    "docstring": "Compute the folded site frequency spectrum given reference and\n    alternate allele counts at a set of biallelic variants.\n\n    Parameters\n    ----------\n    ac : array_like, int, shape (n_variants, 2)\n        Allele counts array.\n    n : int, optional\n        The total number of chromosomes called.\n\n    Returns\n    -------\n    sfs_folded : ndarray, int, shape (n_chromosomes//2,)\n        Array where the kth element is the number of variant sites with a\n        minor allele count of k."
  },
  {
    "code": "def pack_block(self, block: BaseBlock, *args: Any, **kwargs: Any) -> BaseBlock:\n        if 'uncles' in kwargs:\n            uncles = kwargs.pop('uncles')\n            kwargs.setdefault('uncles_hash', keccak(rlp.encode(uncles)))\n        else:\n            uncles = block.uncles\n        provided_fields = set(kwargs.keys())\n        known_fields = set(BlockHeader._meta.field_names)\n        unknown_fields = provided_fields.difference(known_fields)\n        if unknown_fields:\n            raise AttributeError(\n                \"Unable to set the field(s) {0} on the `BlockHeader` class. \"\n                \"Received the following unexpected fields: {1}.\".format(\n                    \", \".join(known_fields),\n                    \", \".join(unknown_fields),\n                )\n            )\n        header = block.header.copy(**kwargs)\n        packed_block = block.copy(uncles=uncles, header=header)\n        return packed_block",
    "docstring": "Pack block for mining.\n\n        :param bytes coinbase: 20-byte public address to receive block reward\n        :param bytes uncles_hash: 32 bytes\n        :param bytes state_root: 32 bytes\n        :param bytes transaction_root: 32 bytes\n        :param bytes receipt_root: 32 bytes\n        :param int bloom:\n        :param int gas_used:\n        :param bytes extra_data: 32 bytes\n        :param bytes mix_hash: 32 bytes\n        :param bytes nonce: 8 bytes"
  },
  {
    "code": "def queuedb_findall(path, queue_id, name=None, offset=None, limit=None):\n    sql = \"SELECT * FROM queue WHERE queue_id = ? ORDER BY rowid ASC\"\n    args = (queue_id,)\n    if name:\n        sql += ' AND name = ?'\n        args += (name,)\n    if limit:\n        sql += ' LIMIT ?'\n        args += (limit,)\n    if offset:\n        sql += ' OFFSET ?'\n        args += (offset,)\n    sql += ';'\n    db = queuedb_open(path)\n    if db is None:\n        raise Exception(\"Failed to open %s\" % path)\n    cur = db.cursor()\n    rows = queuedb_query_execute(cur, sql, args)\n    count = 0\n    ret = []\n    for row in rows:\n        dat = {}\n        dat.update(row)\n        ret.append(dat)\n    db.close()\n    return ret",
    "docstring": "Get all queued entries for a queue and a name.\n    If name is None, then find all queue entries\n\n    Return the rows on success (empty list if not found)\n    Raise on error"
  },
  {
    "code": "def cleanup(self):\n        if self.data.hooks and len(self.data.hooks.cleanup) > 0:\n            env = self.data.env_list[0].copy()\n            env.update({'PIPELINE_RESULT': 'SUCCESS', 'PIPELINE_SHELL_EXIT_CODE': '0'})\n            config = ShellConfig(script=self.data.hooks.cleanup, model=self.model,\n                                 env=env, dry_run=self.options.dry_run,\n                                 debug=self.options.debug, strict=self.options.strict,\n                                 temporary_scripts_path=self.options.temporary_scripts_path)\n            cleanup_shell = Bash(config)\n            for line in cleanup_shell.process():\n                yield line",
    "docstring": "Run cleanup script of pipeline when hook is configured."
  },
  {
    "code": "def hill_climbing_stochastic(problem, iterations_limit=0, viewer=None):\n    return _local_search(problem,\n                         _random_best_expander,\n                         iterations_limit=iterations_limit,\n                         fringe_size=1,\n                         stop_when_no_better=iterations_limit==0,\n                         viewer=viewer)",
    "docstring": "Stochastic hill climbing.\n\n    If iterations_limit is specified, the algorithm will end after that\n    number of iterations. Else, it will continue until it can't find a\n    better node than the current one.\n    Requires: SearchProblem.actions, SearchProblem.result, and\n    SearchProblem.value."
  },
  {
    "code": "def init_common(app):\n    if app.config['USERPROFILES_EXTEND_SECURITY_FORMS']:\n        security_ext = app.extensions['security']\n        security_ext.confirm_register_form = confirm_register_form_factory(\n            security_ext.confirm_register_form)\n        security_ext.register_form = register_form_factory(\n            security_ext.register_form)",
    "docstring": "Post initialization."
  },
  {
    "code": "def detect_current_filename():\n    import inspect\n    filename = None\n    frame = inspect.currentframe()\n    try:\n        while frame.f_back and frame.f_globals.get('name') != '__main__':\n            frame = frame.f_back\n        filename = frame.f_globals.get('__file__')\n    finally:\n        del frame\n    return filename",
    "docstring": "Attempt to return the filename of the currently running Python process\n\n    Returns None if the filename cannot be detected."
  },
  {
    "code": "def _sd_of_runs(stats, mean, key='runs'):\n    num_runs = len(stats[key])\n    first = stats[key][0]\n    standard_deviation = {}\n    for stat_key in first:\n        if isinstance(first[stat_key], numbers.Number):\n            standard_deviation[stat_key] = math.sqrt(\n                sum((run[stat_key] - mean[stat_key])**2\n                    for run in stats[key]) / float(num_runs))\n    return standard_deviation",
    "docstring": "Obtain the standard deviation of stats.\n\n    Args:\n        stats: dict; A set of stats, structured as above.\n        mean: dict; Mean for each key in stats.\n        key: str; Optional key to determine where list of runs is found in stats"
  },
  {
    "code": "def get_roots(self):\n        id_list = []\n        for r in self._rls.get_relationships_by_genus_type_for_source(self._phantom_root_id, self._relationship_type):\n            id_list.append(r.get_destination_id())\n        return IdList(id_list)",
    "docstring": "Gets the root nodes of this hierarchy.\n\n        return: (osid.id.IdList) - the root nodes\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def use_plenary_vault_view(self):\n        self._vault_view = PLENARY\n        for session in self._get_provider_sessions():\n            try:\n                session.use_plenary_vault_view()\n            except AttributeError:\n                pass",
    "docstring": "Pass through to provider AuthorizationVaultSession.use_plenary_vault_view"
  },
  {
    "code": "def tail(self) -> 'List':\n        lambda_list = self._get_value()\n        return List(lambda_list(lambda _, tail: tail))",
    "docstring": "Return tail of List."
  },
  {
    "code": "def pprint(self, index=False, delimiter='-'):\n        lines = _build_tree_string(self, 0, index, delimiter)[0]\n        print('\\n' + '\\n'.join((line.rstrip() for line in lines)))",
    "docstring": "Pretty-print the binary tree.\n\n        :param index: If set to True (default: False), display level-order_\n            indexes using the format: ``{index}{delimiter}{value}``.\n        :type index: bool\n        :param delimiter: Delimiter character between the node index and\n            the node value (default: '-').\n        :type delimiter: str | unicode\n\n        **Example**:\n\n        .. doctest::\n\n            >>> from binarytree import Node\n            >>>\n            >>> root = Node(1)              # index: 0, value: 1\n            >>> root.left = Node(2)         # index: 1, value: 2\n            >>> root.right = Node(3)        # index: 2, value: 3\n            >>> root.left.right = Node(4)   # index: 4, value: 4\n            >>>\n            >>> root.pprint()\n            <BLANKLINE>\n              __1\n             /   \\\\\n            2     3\n             \\\\\n              4\n            <BLANKLINE>\n            >>> root.pprint(index=True)     # Format: {index}-{value}\n            <BLANKLINE>\n               _____0-1_\n              /         \\\\\n            1-2_        2-3\n                \\\\\n                4-4\n            <BLANKLINE>\n\n        .. note::\n            If you do not need level-order_ indexes in the output string, use\n            :func:`binarytree.Node.__str__` instead.\n\n        .. _level-order:\n            https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search"
  },
  {
    "code": "def emit(self, record):\n        try:\n            self._callback(self.prepare(record))\n        except Exception:\n            self.handleError(record)",
    "docstring": "Send a LogRecord to the callback function, after preparing it\n        for serialization."
  },
  {
    "code": "def inspect(self):\n        return dedent(\n        ).format(\n            dtype=self.dtype.name,\n            data=self.data,\n            adjustments=self.adjustments,\n        )",
    "docstring": "Return a string representation of the data stored in this array."
  },
  {
    "code": "def usage(self):\n        return u' '.join(u'<%s>' % pattern.usage for pattern in self.patterns)",
    "docstring": "A usage string that describes the signature."
  },
  {
    "code": "def numpy_bins_with_mask(self) -> Tuple[np.ndarray, np.ndarray]:\n        bwm = to_numpy_bins_with_mask(self.bins)\n        if not self.includes_right_edge:\n            bwm[0].append(np.inf)\n        return bwm",
    "docstring": "Bins in the numpy format, including the gaps in inconsecutive binnings.\n\n        Returns\n        -------\n        edges, mask: np.ndarray\n\n        See Also\n        --------\n        bin_utils.to_numpy_bins_with_mask"
  },
  {
    "code": "def first_sunday(self, year, month):\n        date = datetime(year, month, 1, 0)\n        days_until_sunday = 6 - date.weekday()\n        return date + timedelta(days=days_until_sunday)",
    "docstring": "Get the first sunday of a month."
  },
  {
    "code": "def vproj(a, b):\n    a = stypes.toDoubleVector(a)\n    b = stypes.toDoubleVector(b)\n    vout = stypes.emptyDoubleVector(3)\n    libspice.vproj_c(a, b, vout)\n    return stypes.cVectorToPython(vout)",
    "docstring": "Find the projection of one vector onto another vector.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vproj_c.html\n\n    :param a: The vector to be projected. \n    :type a: 3-Element Array of floats\n    :param b: The vector onto which a is to be projected. \n    :type b: 3-Element Array of floats\n    :return: The projection of a onto b.\n    :rtype: 3-Element Array of floats"
  },
  {
    "code": "def replication_details(host=None, core_name=None):\n    ret = _get_return_dict()\n    if _get_none_or_value(core_name) is None:\n        success = True\n        for name in __opts__['solr.cores']:\n            resp = _replication_request('details', host=host, core_name=name)\n            data = {name: {'data': resp['data']}}\n            ret = _update_return_dict(ret, success, data,\n                                        resp['errors'], resp['warnings'])\n    else:\n        resp = _replication_request('details', host=host, core_name=core_name)\n        if resp['success']:\n            ret = _update_return_dict(ret, resp['success'], resp['data'],\n                                        resp['errors'], resp['warnings'])\n        else:\n            return resp\n    return ret",
    "docstring": "Get the full replication details.\n\n    host : str (None)\n        The solr host to query. __opts__['host'] is default.\n    core_name : str (None)\n        The name of the solr core if using cores. Leave this blank if you are\n        not using cores or if you want to check all cores.\n\n    Return : dict<str,obj>::\n\n        {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' solr.replication_details music"
  },
  {
    "code": "def site_occupation_statistics( self ):\n        if self.time == 0.0:\n            return None\n        occupation_stats = { label : 0.0 for label in self.site_labels }\n        for site in self.sites:\n            occupation_stats[ site.label ] += site.time_occupied\n        for label in self.site_labels:\n            occupation_stats[ label ] /= self.time\n        return occupation_stats",
    "docstring": "Average site occupation for each site type\n\n        Args:\n            None\n\n        Returns:\n            (Dict(Str:Float)): Dictionary of occupation statistics, e.g.::\n\n                { 'A' : 2.5, 'B' : 25.3 }"
  },
  {
    "code": "def clear(self):\n        super(Router, self).clear()\n        for name in self.todo:\n            filename = os.path.join(self.migrate_dir, name + '.py')\n            os.remove(filename)",
    "docstring": "Remove migrations from fs."
  },
  {
    "code": "def descendents(self):\n        for c in self.children:\n            yield c\n            for d in c.descendents:\n                yield d",
    "docstring": "Iterate over all descendent terms"
  },
  {
    "code": "def generate_api_for_source(self, source_fpath: str):\n        content = self.convert_content(source_fpath)\n        if content is None:\n            return\n        dest_fpath = self.dest_fpath(source_fpath)\n        self.create_fpath_dir(dest_fpath)\n        with open(dest_fpath, 'w+') as dest_f:\n            json.dump(content, dest_f, cls=DateTimeJsonEncoder)",
    "docstring": "Generate end json api file with directory structure for concrete\n        source file."
  },
  {
    "code": "def get_context(self, name, value, attrs):\n        context = super().get_context(\n            name, value, attrs)\n        context['widget']['attrs']['dp_config'] = json_dumps(self.config)\n        return context",
    "docstring": "Return widget context dictionary."
  },
  {
    "code": "def _write_abstract_named_entity(self):\n        filename = \"%sAbstractNamedEntity.js\" % (self._class_prefix)\n        superclass_name = \"%sEntity\" % (self._class_prefix)\n        self.write(destination = self.abstract_directory,\n                    filename = filename,\n                    template_name = \"abstract_named_entity.js.tpl\",\n                    class_prefix = self._class_prefix,\n                    superclass_name = superclass_name)",
    "docstring": "This method generates AbstractNamedEntity class js file."
  },
  {
    "code": "def compress_flood_fill_regions(targets):\n    t = RegionCoreTree()\n    for (x, y), cores in iteritems(targets):\n        for p in cores:\n            t.add_core(x, y, p)\n    return sorted(t.get_regions_and_coremasks())",
    "docstring": "Generate a reduced set of flood fill parameters.\n\n    Parameters\n    ----------\n    targets : {(x, y) : set([c, ...]), ...}\n        For each used chip a set of core numbers onto which an application\n        should be loaded.  E.g., the output of\n        :py:func:`~rig.place_and_route.util.build_application_map` when indexed\n        by an application.\n\n    Yields\n    ------\n    (region, core mask)\n        Pair of integers which represent a region of a SpiNNaker machine and a\n        core mask of selected cores within that region for use in flood-filling\n        an application.  `region` and `core_mask` are both integer\n        representations of bit fields that are understood by SCAMP.\n\n        The pairs are yielded in an order suitable for direct use with SCAMP's\n        flood-fill core select (FFCS) method of loading."
  },
  {
    "code": "def clone(cls, name, vhost, directory, origin):\n        paas_info = cls.info(name)\n        if 'php' in paas_info['type'] and not vhost:\n            cls.error('PHP instances require indicating the VHOST to clone '\n                      'with --vhost <vhost>')\n        paas_access = '%s@%s' % (paas_info['user'], paas_info['git_server'])\n        remote_url = 'ssh+git://%s/%s.git' % (paas_access, vhost)\n        command = 'git clone %s %s --origin %s' \\\n                  % (remote_url, directory, origin)\n        init_git = cls.execute(command)\n        if init_git:\n            cls.echo('Use `git push %s master` to push your code to the '\n                     'instance.' % (origin))\n            cls.echo('Then `$ gandi deploy` to build and deploy your '\n                     'application.')",
    "docstring": "Clone a PaaS instance's vhost into a local git repository."
  },
  {
    "code": "def findspans(self, type,set=None):\n        if issubclass(type, AbstractAnnotationLayer):\n            layerclass = type\n        else:\n            layerclass = ANNOTATIONTYPE2LAYERCLASS[type.ANNOTATIONTYPE]\n        e = self\n        while True:\n            if not e.parent: break\n            e = e.parent\n            for layer in e.select(layerclass,set,False):\n                for e2 in layer:\n                    if isinstance(e2, AbstractSpanAnnotation):\n                        if self in e2.wrefs():\n                            yield e2",
    "docstring": "Find span annotation of the specified type that include this word"
  },
  {
    "code": "def get_vip_request_details(self, vip_request_id):\n        uri = 'api/v3/vip-request/details/%s/' % vip_request_id\n        return super(ApiVipRequest, self).get(uri)",
    "docstring": "Method to get details of vip request\n\n        param vip_request_id: vip_request id"
  },
  {
    "code": "def load_with_datetime(pairs):\n    d = {}\n    for k, v in pairs:\n        if isinstance(v, basestring):\n            try:\n                d[k] = dateutil.parser.parse(v)\n            except ValueError:\n                d[k] = v\n        else:\n            d[k] = v             \n    return d",
    "docstring": "Deserialize JSON into python datetime objects."
  },
  {
    "code": "def ReconcileShadow(self, store_type):\n    for k, v in iteritems(self.entry):\n      if v.pw_entry.store == store_type:\n        shadow_entry = self.shadow.get(k)\n        if shadow_entry is not None:\n          v.pw_entry = shadow_entry\n        else:\n          v.pw_entry.store = \"UNKNOWN\"",
    "docstring": "Verify that entries that claim to use shadow files have a shadow entry.\n\n    If the entries of the non-shadowed file indicate that a shadow file is used,\n    check that there is actually an entry for that file in shadow.\n\n    Args:\n      store_type: The type of password store that should be used (e.g.\n        /etc/shadow or /etc/gshadow)"
  },
  {
    "code": "def download_file(url, local_filename):\n    local_filename = os.path.abspath(local_filename)\n    path = os.path.dirname(local_filename)\n    if not os.path.isdir(path):\n        os.makedirs(path)\n    with tqdm(unit='B', unit_scale=True) as progress:\n        def report(chunk, chunksize, total):\n            progress.total = total\n            progress.update(chunksize)\n        return urlretrieve(url, local_filename, reporthook=report)",
    "docstring": "Simple wrapper around urlretrieve that uses tqdm to display a progress\n    bar of download progress"
  },
  {
    "code": "def _confirm_overwrite(filename):\n        message = '{}Would you like to overwrite the contents of {} (y/[n])? '.format(\n            c.Fore.MAGENTA, filename\n        )\n        response = raw_input(message)\n        response = response.lower()\n        if response in ['y', 'yes']:\n            return True\n        return False",
    "docstring": "Confirm overwrite of template files.\n\n        Make sure the user would like to continue downloading a file which will overwrite a file\n        in the current directory.\n\n        Args:\n            filename (str): The name of the file to overwrite.\n\n        Returns:\n            bool: True if the user specifies a \"yes\" response."
  },
  {
    "code": "def parse_style_rules(styles: str) -> CSSRuleList:\n    rules = CSSRuleList()\n    for m in _style_rule_re.finditer(styles):\n        rules.append(CSSStyleRule(m.group(1), parse_style_decl(m.group(2))))\n    return rules",
    "docstring": "Make CSSRuleList object from style string."
  },
  {
    "code": "def error_for(response):\n    klass = error_classes.get(response.status)\n    if klass is None:\n        if 400 <= response.status < 500:\n            klass = ClientError\n        if 500 <= response.status < 600:\n            klass = ServerError\n    return klass(response)",
    "docstring": "Return the appropriate initialized exception class for a response."
  },
  {
    "code": "def fetch_message(self, msgnum):\n        self.imap_connect()\n        status, data = self.mailbox.fetch(msgnum, \"(RFC822)\")\n        self.imap_disconnect()\n        for response_part in data:\n            if isinstance(response_part, tuple):\n                return email.message_from_string(response_part[1])",
    "docstring": "Given a message number, return the Email.Message object.\n        @Params\n        msgnum - message number to find\n        @Returns\n        Email.Message object for the given message number"
  },
  {
    "code": "def keystroke_model():\n    model = Pohmm(n_hidden_states=2,\n                  init_spread=2,\n                  emissions=['lognormal', 'lognormal'],\n                  smoothing='freq',\n                  init_method='obs',\n                  thresh=1)\n    return model",
    "docstring": "Generates a 2-state model with lognormal emissions and frequency smoothing"
  },
  {
    "code": "def get_runs():\n    data = current_app.config[\"data\"]\n    draw = parse_int_arg(\"draw\", 1)\n    start = parse_int_arg(\"start\", 0)\n    length = parse_int_arg(\"length\", -1)\n    length = length if length >= 0 else None\n    order_column = request.args.get(\"order[0][column]\")\n    order_dir = request.args.get(\"order[0][dir]\")\n    query = parse_query_filter()\n    if order_column is not None:\n        order_column = \\\n            request.args.get(\"columns[%d][name]\" % int(order_column))\n        if order_column == \"hostname\":\n            order_column = \"host.hostname\"\n    runs = data.get_run_dao().get_runs(\n        start=start, limit=length,\n        sort_by=order_column, sort_direction=order_dir, query=query)\n    records_total = runs.count()\n    records_filtered = runs.count()\n    return Response(render_template(\n        \"api/runs.js\", runs=runs,\n        draw=draw, recordsTotal=records_total,\n        recordsFiltered=records_filtered),\n        mimetype=\"application/json\")",
    "docstring": "Get all runs, sort it and return a response."
  },
  {
    "code": "def _driver_signing_reg_conversion(cls, val, **kwargs):\n        log.debug('we have %s for the driver signing value', val)\n        if val is not None:\n            _val = val.split(',')\n            if len(_val) == 2:\n                if _val[1] == '0':\n                    return 'Silently Succeed'\n                elif _val[1] == '1':\n                    return 'Warn but allow installation'\n                elif _val[1] == '2':\n                    return 'Do not allow installation'\n                elif _val[1] == 'Not Defined':\n                    return 'Not Defined'\n                else:\n                    return 'Invalid Value'\n            else:\n                return 'Not Defined'\n        else:\n            return 'Not Defined'",
    "docstring": "converts the binary value in the registry for driver signing into the\n        correct string representation"
  },
  {
    "code": "def inverse(self, vector, duration=None):\n        ann = jams.Annotation(namespace=self.namespace, duration=duration)\n        if duration is None:\n            duration = 0\n        ann.append(time=0, duration=duration, value=vector)\n        return ann",
    "docstring": "Inverse vector transformer"
  },
  {
    "code": "def get_sequence_rule_admin_session_for_bank(self, bank_id):\n        if not self.supports_sequence_rule_admin():\n            raise errors.Unimplemented()\n        return sessions.SequenceRuleAdminSession(bank_id, runtime=self._runtime)",
    "docstring": "Gets the ``OsidSession`` associated with the sequence rule administration service for the given bank.\n\n        arg:    bank_id (osid.id.Id): the ``Id`` of the ``Bank``\n        return: (osid.assessment.authoring.SequenceRuleAdminSession) - a\n                ``SequenceRuleAdminSession``\n        raise:  NotFound - no ``Bank`` found by the given ``Id``\n        raise:  NullArgument - ``bank_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_sequence_rule_admin()`` or\n                ``supports_visible_federation()`` is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_sequence_rule_admin()`` and\n        ``supports_visible_federation()`` are ``true``.*"
  },
  {
    "code": "def imageMsg2Image(img, bridge):\n    image = Image()\n    image.width = img.width\n    image.height = img.height\n    image.format = \"RGB8\"\n    image.timeStamp = img.header.stamp.secs + (img.header.stamp.nsecs *1e-9)\n    cv_image=0\n    if (img.encoding == \"32FC1\"):\n        gray_img_buff = bridge.imgmsg_to_cv2(img, \"32FC1\")\n        cv_image  = depthToRGB8(gray_img_buff)\n    else:\n        cv_image = bridge.imgmsg_to_cv2(img, \"rgb8\")\n    image.data = cv_image\n    return image",
    "docstring": "Translates from ROS Image to JderobotTypes Image. \n\n    @param img: ROS Image to translate\n    @param bridge: bridge to do translation\n\n    @type img: sensor_msgs.msg.Image\n    @type brige: CvBridge\n\n    @return a JderobotTypes.Image translated from img"
  },
  {
    "code": "def handle_err(self, exc):\n        if self.reset_rx_on_error and isinstance(exc[1], (RxSyncError, EightbTenbError)):\n            self.fifo_readout.print_readout_status()\n            self.fifo_readout.reset_rx()\n        else:\n            if not self.abort_run.is_set():\n                self.abort(msg=exc[1].__class__.__name__ + \": \" + str(exc[1]))\n            self.err_queue.put(exc)",
    "docstring": "Handling of Exceptions.\n\n        Parameters\n        ----------\n        exc : list, tuple\n            Information of the exception of the format (type, value, traceback).\n            Uses the return value of sys.exc_info()."
  },
  {
    "code": "def proxy_callback(request):\n    pgtIou = request.GET.get('pgtIou')\n    tgt = request.GET.get('pgtId')\n    if not (pgtIou and tgt):\n        logger.info('No pgtIou or tgt found in request.GET')\n        return HttpResponse('No pgtIOO', content_type=\"text/plain\")\n    try:\n        PgtIOU.objects.create(tgt=tgt, pgtIou=pgtIou, created=datetime.datetime.now())\n        request.session['pgt-TICKET'] = pgtIou\n        return HttpResponse('PGT ticket is: {ticket}'.format(ticket=pgtIou), content_type=\"text/plain\")\n    except Exception as e:\n        logger.warning('PGT storage failed. {message}'.format(\n            message=e\n        ))\n        return HttpResponse('PGT storage failed for {request}'.format(request=str(request.GET)),\n                            content_type=\"text/plain\")",
    "docstring": "Handles CAS 2.0+ XML-based proxy callback call.\n    Stores the proxy granting ticket in the database for\n    future use.\n\n    NB: Use created and set it in python in case database\n    has issues with setting up the default timestamp value"
  },
  {
    "code": "def __set_method(self, value):\n        if value not in [DELIVERY_METHOD_EMAIL, DELIVERY_METHOD_SMS,\n                         DELIVERY_METHOD_SNAILMAIL]:\n            raise ValueError(\"Invalid deliveries method '%s'\" % value)\n        self.__method = value",
    "docstring": "Sets the method to use.\n        @param value: str"
  },
  {
    "code": "def save(self):\n        storage = get_media_storage()\n        for storage_name in self.cleaned_data['selected_files']:\n            full_path = storage.path(storage_name)\n            try:\n                storage.delete(storage_name)\n                self.success_files.append(full_path)\n            except OSError:\n                self.error_files.append(full_path)",
    "docstring": "Deletes the selected files from storage"
  },
  {
    "code": "def protectbranch(self, project_id, branch):\n        request = requests.put(\n            '{0}/{1}/repository/branches/{2}/protect'.format(self.projects_url, project_id, branch),\n            headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)\n        if request.status_code == 200:\n            return True\n        else:\n            return False",
    "docstring": "Protect a branch from changes\n\n        :param project_id: project id\n        :param branch: branch id\n        :return: True if success"
  },
  {
    "code": "def __remove_category(self, id):\n        affected_query =\n        affected_ids = [res[0] for res in self.fetchall(affected_query, (id,))]\n        update = \"update activities set category_id = -1 where category_id = ?\"\n        self.execute(update, (id, ))\n        self.execute(\"delete from categories where id = ?\", (id, ))\n        self.__remove_index(affected_ids)",
    "docstring": "move all activities to unsorted and remove category"
  },
  {
    "code": "def _parse_arg(func, variables, arg_name, anno):\n    if isinstance(anno, str):\n        var = variables[anno]\n        return var, var.read_latest\n    elif (isinstance(anno, list) and len(anno) == 1 and\n          isinstance(anno[0], str)):\n        var = variables[anno[0]]\n        return var, var.read_all\n    raise StartupError(\n        'cannot parse annotation %r of parameter %r for %r' %\n        (anno, arg_name, func))",
    "docstring": "Parse an argument's annotation."
  },
  {
    "code": "def qteActiveWindow(self):\n        if len(self._qteWindowList) == 0:\n            self.qteLogger.critical('The window list is empty.')\n            return None\n        elif len(self._qteWindowList) == 1:\n            return self._qteWindowList[0]\n        else:\n            for win in self._qteWindowList:\n                if win.isActiveWindow():\n                    return win\n        return self._qteWindowList[0]",
    "docstring": "Return the currently active ``QtmacsWindow`` object.\n\n        If no Qtmacs window is currently active (for instance because\n        the user is working with another application at the moment)\n        then the method returns the first window in the window list.\n\n        The method only returns **None** if the window list is empty,\n        which is definitively a bug.\n\n        |Args|\n\n        * **None**\n\n        |Returns|\n\n        * **QtmacsWindow**: the currently active window or **None** if\n          no window is currently active.\n\n        |Raises|\n\n        * **None**"
  },
  {
    "code": "def actions(self, state):\n        'actions are index where we can make a move'\n        actions = []\n        for index, char in enumerate(state):\n            if char == '_':\n                actions.append(index)\n        return actions",
    "docstring": "actions are index where we can make a move"
  },
  {
    "code": "def get_aggregate_by_id(self, account_id: str) -> AccountAggregate:\n        account = self.get_by_id(account_id)\n        return self.get_account_aggregate(account)",
    "docstring": "Returns the aggregate for the given id"
  },
  {
    "code": "def calc_tkor_v1(self):\n    con = self.parameters.control.fastaccess\n    inp = self.sequences.inputs.fastaccess\n    flu = self.sequences.fluxes.fastaccess\n    for k in range(con.nhru):\n        flu.tkor[k] = con.kt[k] + inp.teml",
    "docstring": "Adjust the given air temperature values.\n\n    Required control parameters:\n      |NHRU|\n      |KT|\n\n    Required input sequence:\n      |TemL|\n\n    Calculated flux sequence:\n      |TKor|\n\n    Basic equation:\n      :math:`TKor = KT + TemL`\n\n    Example:\n\n        >>> from hydpy.models.lland import *\n        >>> parameterstep('1d')\n        >>> nhru(3)\n        >>> kt(-2.0, 0.0, 2.0)\n        >>> inputs.teml(1.)\n        >>> model.calc_tkor_v1()\n        >>> fluxes.tkor\n        tkor(-1.0, 1.0, 3.0)"
  },
  {
    "code": "def _EncodeString(self, string):\n    try:\n      encoded_string = string.encode(self._encoding, errors=self._errors)\n    except UnicodeEncodeError:\n      if self._errors == 'strict':\n        logging.error(\n            'Unable to properly write output due to encoding error. '\n            'Switching to error tolerant encoding which can result in '\n            'non Basic Latin (C0) characters to be replaced with \"?\" or '\n            '\"\\\\ufffd\".')\n        self._errors = 'replace'\n      encoded_string = string.encode(self._encoding, errors=self._errors)\n    return encoded_string",
    "docstring": "Encodes the string.\n\n    Args:\n      string (str): string to encode.\n\n    Returns:\n      bytes: encoded string."
  },
  {
    "code": "def log(name, data=None):\n    data = data or {}\n    data.update(core.get_default_values(data))\n    event_cls = core.find_event(name)\n    event = event_cls(name, data)\n    event.validate()\n    data = core.filter_data_values(data)\n    data = ejson.dumps(data)\n    if conf.getsetting('DEBUG'):\n        core.process(name, data)\n    else:\n        tasks.process_task.delay(name, data)",
    "docstring": "Entry point for the event lib that starts the logging process\n\n    This function uses the `name` param to find the event class that\n    will be processed to log stuff. This name must provide two\n    informations separated by a dot: the app name and the event class\n    name. Like this:\n\n        >>> name = 'deal.ActionLog'\n\n    The \"ActionLog\" is a class declared inside the 'deal.events' module\n    and this function will raise an `EventNotFoundError` error if it's\n    not possible to import the right event class.\n\n    The `data` param *must* be a dictionary, otherwise a `TypeError`\n    will be rised. All keys *must* be strings and all values *must* be\n    serializable by the `json.dumps` function. If you need to pass any\n    unsupported object, you will have to register a serializer\n    function. Consult the RFC-00003-serialize-registry for more\n    information."
  },
  {
    "code": "def write(self, text='', wrap=True):\n        if not isinstance(text, string_types):\n            raise TypeError('text must be a string')\n        text = text.encode('utf-8').decode('ascii', errors='replace')\n        self._pending_writes.append((text, wrap))\n        self.update()",
    "docstring": "Write text and scroll\n\n        Parameters\n        ----------\n        text : str\n            Text to write. ``''`` can be used for a blank line, as a newline\n            is automatically added to the end of each line.\n        wrap : str\n            If True, long messages will be wrapped to span multiple lines."
  },
  {
    "code": "def transformToNative(obj):\n        if obj.isNative:\n            return obj\n        obj.isNative = True\n        obj.value = Address(**dict(zip(ADDRESS_ORDER, splitFields(obj.value))))\n        return obj",
    "docstring": "Turn obj.value into an Address."
  },
  {
    "code": "def get_resource_admin_session_for_bin(self, bin_id, proxy):\n        if not self.supports_resource_admin():\n            raise errors.Unimplemented()\n        return sessions.ResourceAdminSession(bin_id, proxy, self._runtime)",
    "docstring": "Gets a resource administration session for the given bin.\n\n        arg:    bin_id (osid.id.Id): the ``Id`` of the bin\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.resource.ResourceAdminSession) - ``a\n                ResourceAdminSession``\n        raise:  NotFound - ``bin_id`` not found\n        raise:  NullArgument - ``bin_id`` or ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_resource_admin()`` or\n                ``supports_visible_federation()`` is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_resource_admin()`` and\n        ``supports_visible_federation()`` are ``true``.*"
  },
  {
    "code": "def _coerce_method(converter):\n    def wrapper(self):\n        if len(self) == 1:\n            return converter(self.iloc[0])\n        raise TypeError(\"cannot convert the series to \"\n                        \"{0}\".format(str(converter)))\n    wrapper.__name__ = \"__{name}__\".format(name=converter.__name__)\n    return wrapper",
    "docstring": "Install the scalar coercion methods."
  },
  {
    "code": "def print_results_from_args(args: argparse.Namespace):\n    path = args.path\n    metrics_name = args.metrics_filename\n    keys = args.keys\n    results_dict = {}\n    for root, _, files in os.walk(path):\n        if metrics_name in files:\n            full_name = os.path.join(root, metrics_name)\n            metrics = json.load(open(full_name))\n            results_dict[full_name] = metrics\n    sorted_keys = sorted(list(results_dict.keys()))\n    print(f\"model_run, {', '.join(keys)}\")\n    for name in sorted_keys:\n        results = results_dict[name]\n        keys_to_print = [str(results.get(key, \"N/A\")) for key in keys]\n        print(f\"{name}, {', '.join(keys_to_print)}\")",
    "docstring": "Prints results from an ``argparse.Namespace`` object."
  },
  {
    "code": "def get_check_digit(unchecked):\n    digits = digits_of(unchecked)\n    checksum = sum(even_digits(unchecked)) + sum([\n        sum(digits_of(2 * d)) for d in odd_digits(unchecked)])\n    return 9 * checksum % 10",
    "docstring": "returns the check digit of the card number."
  },
  {
    "code": "def _fill_text(self, text, width, indent):\n        parts = text.split('\\n\\n')\n        for i, part in enumerate(parts):\n            if part.startswith('* '):\n                subparts = part.split('\\n')\n                for j, subpart in enumerate(subparts):\n                    subparts[j] = super(WrappedTextHelpFormatter, self)._fill_text(\n                        subpart, width, indent\n                    )\n                parts[i] = '\\n'.join(subparts)\n            else:\n                parts[i] = super(WrappedTextHelpFormatter, self)._fill_text(part, width, indent)\n        return '\\n\\n'.join(parts)",
    "docstring": "Wraps text like HelpFormatter, but doesn't squash lines\n\n        This makes it easier to do lists and paragraphs."
  },
  {
    "code": "def clean():\n    shutil.rmtree('{PROJECT_NAME}.egg-info'.format(PROJECT_NAME=PROJECT_NAME), ignore_errors=True)\n    shutil.rmtree('build', ignore_errors=True)\n    shutil.rmtree('dist', ignore_errors=True)\n    shutil.rmtree('htmlcov', ignore_errors=True)\n    shutil.rmtree('__pycache__', ignore_errors=True)",
    "docstring": "remove build artifacts"
  },
  {
    "code": "def main():\n    options = _parse_args()\n    archive = download_setuptools(**_download_args(options))\n    return _install(archive, _build_install_args(options))",
    "docstring": "Install or upgrade setuptools and EasyInstall."
  },
  {
    "code": "def split_func_name_args_params_handle(tokens):\n    internal_assert(len(tokens) == 2, \"invalid function definition splitting tokens\", tokens)\n    func_name = tokens[0]\n    func_args = []\n    func_params = []\n    for arg in tokens[1]:\n        if len(arg) > 1 and arg[0] in (\"*\", \"**\"):\n            func_args.append(arg[1])\n        elif arg[0] != \"*\":\n            func_args.append(arg[0])\n        func_params.append(\"\".join(arg))\n    return [\n        func_name,\n        \", \".join(func_args),\n        \"(\" + \", \".join(func_params) + \")\",\n    ]",
    "docstring": "Process splitting a function into name, params, and args."
  },
  {
    "code": "def _get_db_names(self):\n        query =\n        conn = self._connect(self.config['dbname'])\n        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)\n        cursor.execute(query)\n        datnames = [d['datname'] for d in cursor.fetchall()]\n        conn.close()\n        if not datnames:\n            datnames = ['postgres']\n        return datnames",
    "docstring": "Try to get a list of db names"
  },
  {
    "code": "def fixed(self):\n        decision = False\n        for record in self.history:\n            if record[\"when\"] < self.options.since.date:\n                continue\n            if not decision and record[\"when\"] < self.options.until.date:\n                for change in record[\"changes\"]:\n                    if (change[\"field_name\"] == \"status\"\n                            and change[\"added\"] == \"MODIFIED\"\n                            and change[\"removed\"] != \"CLOSED\"):\n                        decision = True\n            else:\n                for change in record[\"changes\"]:\n                    if (change[\"field_name\"] == \"status\"\n                            and change[\"added\"] == \"ASSIGNED\"):\n                        decision = False\n        return decision",
    "docstring": "Moved to MODIFIED and not later moved to ASSIGNED"
  },
  {
    "code": "def setData(self, index: QModelIndex, value, role=None):\n        if not (index.isValid() and role == Qt.CheckStateRole):\n            return False\n        c_id = self.get_item(index).Id\n        self._set_id(c_id, value == Qt.Checked, index)\n        return True",
    "docstring": "Update selected_ids on click on index cell."
  },
  {
    "code": "def solve(self):\n        with log_duration(self._print, \"memcache get (resolve) took %s\"):\n            solver_dict = self._get_cached_solve()\n        if solver_dict:\n            self.from_cache = True\n            self._set_result(solver_dict)\n        else:\n            self.from_cache = False\n            solver = self._solve()\n            solver_dict = self._solver_to_dict(solver)\n            self._set_result(solver_dict)\n            with log_duration(self._print, \"memcache set (resolve) took %s\"):\n                self._set_cached_solve(solver_dict)",
    "docstring": "Perform the solve."
  },
  {
    "code": "def SVD_2_stream(uvectors, stachans, k, sampling_rate):\n    warnings.warn('Depreciated, use svd_to_stream instead.')\n    return svd_to_stream(uvectors=uvectors, stachans=stachans, k=k,\n                         sampling_rate=sampling_rate)",
    "docstring": "Depreciated. Use svd_to_stream"
  },
  {
    "code": "def sha1(self):\n        sha1 = hashlib.sha1(''.join(['%s:%s' % (k,v) for k,v in self.items()]))\n        return str(sha1.hexdigest())",
    "docstring": "Return a sha1 hash of the model items.\n\n        :rtype: str"
  },
  {
    "code": "def create_volume(size, name, profile, location_id=None, **libcloud_kwargs):\n    conn = _get_driver(profile=profile)\n    libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs)\n    if location_id is not None:\n        location = _get_by_id(conn.list_locations(), location_id)\n    else:\n        location = None\n    volume = conn.create_volume(size, name, location, snapshot=None, **libcloud_kwargs)\n    return _simple_volume(volume)",
    "docstring": "Create a storage volume\n\n    :param size: Size of volume in gigabytes (required)\n    :type size: ``int``\n\n    :param name: Name of the volume to be created\n    :type name: ``str``\n\n    :param location_id: Which data center to create a volume in. If\n                            empty, undefined behavior will be selected.\n                            (optional)\n    :type location_id: ``str``\n\n    :param profile: The profile key\n    :type  profile: ``str``\n\n    :param libcloud_kwargs: Extra arguments for the driver's list_volumes method\n    :type  libcloud_kwargs: ``dict``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion libcloud_compute.create_volume 1000 vol1 profile1"
  },
  {
    "code": "def gossip_connect_curve(self, public_key, format, *args):\n        return lib.zyre_gossip_connect_curve(self._as_parameter_, public_key, format, *args)",
    "docstring": "Set-up gossip discovery with CURVE enabled."
  },
  {
    "code": "def diabetes(display=False):\n    d = sklearn.datasets.load_diabetes()\n    df = pd.DataFrame(data=d.data, columns=d.feature_names)\n    return df, d.target",
    "docstring": "Return the diabetes data in a nice package."
  },
  {
    "code": "def locate(callback, root_frame=None, include_root=False, raw=False):\n        def get_from(maybe_callable):\n            if callable(maybe_callable):\n                return maybe_callable()\n            return maybe_callable\n        new = lambda frame: frame if raw else Frame(frame)\n        current_frame = get_from(root_frame or Frame.current_frame(raw=True))\n        current_frame = new(current_frame)\n        if not include_root:\n            current_frame = new(current_frame.f_back)\n        while current_frame:\n            found = callback(current_frame)\n            if found:\n                return current_frame\n            current_frame = new(current_frame.f_back)\n        raise Frame.NotFound('No matching frame found')",
    "docstring": "Locates a frame by criteria.\n\n        :param callback:\n            One argument function to check the frame against. The frame we are\n            curretly on, is given as that argument.\n        :param root_frame:\n            The root frame to start the search from. Can be a callback taking\n            no arguments.\n        :param include_root:\n            `True` if the search should start from the `root_frame` or the one\n            beneath it. Defaults to `False`.\n        :param raw:\n            whether to use raw frames or wrap them in our own object. Defaults to\n            `False`.\n        :raises RuntimeError:\n            When no matching frame is found.\n        :returns:\n            The first frame which responds to the `callback`."
  },
  {
    "code": "def force_disconnect_url(self, session_id, connection_id):\n        url = (\n            self.api_url + '/v2/project/' + self.api_key + '/session/' +\n            session_id + '/connection/' + connection_id\n        )\n        return url",
    "docstring": "this method returns the force disconnect url endpoint"
  },
  {
    "code": "def upload_vcl(self, service_id, version_number, name, content, main=None, comment=None):\n\t\tbody = self._formdata({\n\t\t\t\"name\": name,\n\t\t\t\"content\": content,\n\t\t\t\"comment\": comment,\n\t\t\t\"main\": main,\n\t\t}, FastlyVCL.FIELDS)\n\t\tcontent = self._fetch(\"/service/%s/version/%d/vcl\" % (service_id, version_number), method=\"POST\", body=body)\n\t\treturn FastlyVCL(self, content)",
    "docstring": "Upload a VCL for a particular service and version."
  },
  {
    "code": "def _make_options(x):\n    if isinstance(x, Mapping):\n        import warnings\n        warnings.warn(\"Support for mapping types has been deprecated and will be dropped in a future release.\", DeprecationWarning)\n        return tuple((unicode_type(k), v) for k, v in x.items())\n    xlist = tuple(x)\n    if all((isinstance(i, (list, tuple)) and len(i) == 2) for i in xlist):\n        return tuple((unicode_type(k), v) for k, v in xlist)\n    return tuple((unicode_type(i), i) for i in xlist)",
    "docstring": "Standardize the options tuple format.\n\n    The returned tuple should be in the format (('label', value), ('label', value), ...).\n\n    The input can be\n    * an iterable of (label, value) pairs\n    * an iterable of values, and labels will be generated"
  },
  {
    "code": "def composition_prediction(self, composition, to_this_composition=True):\n        preds = self.list_prediction(list(composition.keys()),\n                                     to_this_composition)\n        output = []\n        for p in preds:\n            if to_this_composition:\n                subs = {v: k for k, v in p['substitutions'].items()}\n            else:\n                subs = p['substitutions']\n            charge = 0\n            for k, v in composition.items():\n                charge += subs[k].oxi_state * v\n            if abs(charge) < 1e-8:\n                output.append(p)\n        logging.info('{} charge balanced substitutions found'\n                     .format(len(output)))\n        return output",
    "docstring": "Returns charged balanced substitutions from a starting or ending\n        composition.\n\n        Args:\n            composition:\n                starting or ending composition\n            to_this_composition:\n                If true, substitutions with this as a final composition\n                will be found. If false, substitutions with this as a\n                starting composition will be found (these are slightly\n                different)\n\n        Returns:\n            List of predictions in the form of dictionaries.\n            If to_this_composition is true, the values of the dictionary\n            will be from the list species. If false, the keys will be\n            from that list."
  },
  {
    "code": "def images(self):\n        return [\n            MediaImage(item.get('url'), item.get('height'), item.get('width'))\n            for item in self.media_metadata.get('images', [])\n        ]",
    "docstring": "Return a list of MediaImage objects for this media."
  },
  {
    "code": "def run_aggregation_by_slug(request, slug):\n    sa = get_object_or_404(Aggregation, slug=slug)\n    sa.execute_now = True\n    sa.save()\n    messages.success(request, _(\"Saved aggregation executed.\"))\n    return HttpResponseRedirect(\n        reverse(\n            'djmongo_browse_saved_aggregations_w_params',\n            args=(\n                sa.database_name,\n                sa.collection_name)))",
    "docstring": "Run Aggregation By Slug"
  },
  {
    "code": "def stats_evaluation(stats):\n    statement = stats.get('statement')\n    error = stats.get('error', 0)\n    warning = stats.get('warning', 0)\n    refactor = stats.get('refactor', 0)\n    convention = stats.get('convention', 0)\n    if not statement or statement <= 0:\n        return None\n    malus = float(5 * error + warning + refactor + convention)\n    malus_ratio = malus / statement\n    return 10.0 - (malus_ratio * 10)",
    "docstring": "Generate an evaluation for the given pylint ``stats``."
  },
  {
    "code": "def _sim_fill(r1, r2, imsize):\n    bbsize = (\n        (max(r1[\"max_x\"], r2[\"max_x\"]) - min(r1[\"min_x\"], r2[\"min_x\"]))\n        * (max(r1[\"max_y\"], r2[\"max_y\"]) - min(r1[\"min_y\"], r2[\"min_y\"]))\n    )\n    return 1.0 - (bbsize - r1[\"size\"] - r2[\"size\"]) / imsize",
    "docstring": "calculate the fill similarity over the image"
  },
  {
    "code": "def issue_link_types(self):\n        r_json = self._get_json('issueLinkType')\n        link_types = [IssueLinkType(self._options, self._session, raw_link_json) for raw_link_json in\n                      r_json['issueLinkTypes']]\n        return link_types",
    "docstring": "Get a list of issue link type Resources from the server.\n\n        :rtype: List[IssueLinkType]"
  },
  {
    "code": "def get_config(repo):\n    files = get_files(repo)\n    config = DEFAULT_CONFIG\n    if \"config.json\" in files:\n        config_file = repo.get_file_contents('/config.json', ref=\"gh-pages\")\n        try:\n            repo_config = json.loads(config_file.decoded_content.decode(\"utf-8\"))\n            config.update(repo_config)\n        except ValueError:\n            click.secho(\"WARNING: Unable to parse config file. Using defaults.\", fg=\"yellow\")\n    return config",
    "docstring": "Get the config for the repo, merged with the default config. Returns the default config if\n    no config file is found."
  },
  {
    "code": "def ones(shape, dtype=None, **kwargs):\n    data = np.ones(shape, dtype)\n    return dc.array(data, **kwargs)",
    "docstring": "Create an array of given shape and type, filled with ones.\n\n    Args:\n        shape (sequence of ints): 2D shape of the array.\n        dtype (data-type, optional): Desired data-type for the array.\n        kwargs (optional): Other arguments of the array (*coords, attrs, and name).\n\n    Returns:\n        array (decode.array): Decode array filled with ones."
  },
  {
    "code": "def update_warning_box(self):\n        self.warning_box.Clear()\n        if self.warning_text == \"\":\n            self.warning_box.AppendText(\"No Problems\")\n        else:\n            self.warning_box.AppendText(self.warning_text)",
    "docstring": "updates the warning box with whatever the warning_text variable\n        contains for this specimen"
  },
  {
    "code": "def get(self, service, params=None):\n        url = self._url_format(service)\n        if params is None:\n            params = {}\n        return self.rest_action(self._session.get, url, params=params)",
    "docstring": "Generic GET operation for retrieving data from Learning Modules API.\n\n        .. code-block:: python\n\n            gbk.get('students/{gradebookId}', params=params, gradebookId=gbid)\n\n        Args:\n            service (str): The endpoint service to use, i.e. gradebook\n            params (dict): additional parameters to add to the call\n\n        Raises:\n            requests.RequestException: Exception connection error\n            ValueError: Unable to decode response content\n\n        Returns:\n            list: the json-encoded content of the response"
  },
  {
    "code": "def get_location(conn, vm_):\n    locations = conn.list_locations()\n    vm_location = config.get_cloud_config_value('location', vm_, __opts__)\n    if not six.PY3:\n        vm_location = vm_location.encode(\n            'ascii', 'salt-cloud-force-ascii'\n        )\n    for img in locations:\n        if isinstance(img.id, six.string_types) and not six.PY3:\n            img_id = img.id.encode('ascii', 'salt-cloud-force-ascii')\n        else:\n            img_id = str(img.id)\n        if isinstance(img.name, six.string_types) and not six.PY3:\n            img_name = img.name.encode('ascii', 'salt-cloud-force-ascii')\n        else:\n            img_name = str(img.name)\n        if vm_location and vm_location in (img_id, img_name):\n            return img\n    raise SaltCloudNotFound(\n        'The specified location, \\'{0}\\', could not be found.'.format(\n            vm_location\n        )\n    )",
    "docstring": "Return the location object to use"
  },
  {
    "code": "def get_resources_to_check(client_site_url, apikey):\n    url = client_site_url + u\"deadoralive/get_resources_to_check\"\n    response = requests.get(url, headers=dict(Authorization=apikey))\n    if not response.ok:\n        raise CouldNotGetResourceIDsError(\n            u\"Couldn't get resource IDs to check: {code} {reason}\".format(\n                code=response.status_code, reason=response.reason))\n    return response.json()",
    "docstring": "Return a list of resource IDs to check for broken links.\n\n    Calls the client site's API to get a list of resource IDs.\n\n    :raises CouldNotGetResourceIDsError: if getting the resource IDs fails\n        for any reason"
  },
  {
    "code": "def parse_buffer(self, s):\n            m = self.parse_char(s)\n            if m is None:\n                return None\n            ret = [m]\n            while True:\n                m = self.parse_char(\"\")\n                if m is None:\n                    return ret\n                ret.append(m)\n            return ret",
    "docstring": "input some data bytes, possibly returning a list of new messages"
  },
  {
    "code": "def add_hyperedges(self, hyperedges, attr_dict=None, **attr):\n        attr_dict = self._combine_attribute_arguments(attr_dict, attr)\n        hyperedge_ids = []\n        for nodes in hyperedges:\n            hyperedge_id = self.add_hyperedge(nodes, attr_dict.copy())\n            hyperedge_ids.append(hyperedge_id)\n        return hyperedge_ids",
    "docstring": "Adds multiple hyperedges to the graph, along with any related\n            attributes of the hyperedges.\n            If any node of a hyperedge has not previously been added to the\n            hypergraph, it will automatically be added here.\n            Hyperedges without a \"weight\" attribute specified will be\n            assigned the default value of 1.\n\n        :param hyperedges: iterable container to references of the node sets\n        :param attr_dict: dictionary of attributes shared by all\n                    the hyperedges being added.\n        :param attr: keyword arguments of attributes of the hyperedges;\n                    attr's values will override attr_dict's values\n                    if both are provided.\n        :returns: list -- the IDs of the hyperedges added in the order\n                    specified by the hyperedges container's iterator.\n\n        See also:\n        add_hyperedge\n\n        Examples:\n        ::\n\n            >>> H = UndirectedHypergraph()\n            >>> hyperedge_list = ([\"A\", \"B\", \"C\"],\n                                  (\"A\", \"D\"),\n                                  set([\"B\", \"D\"]))\n            >>> hyperedge_ids = H.add_hyperedges(hyperedge_list)"
  },
  {
    "code": "def read_collection(self, filename):\n        with open(filename, 'rb') as fd:\n            lines = fd.read().decode('utf-8-sig').splitlines()\n        collection = list(filter(bool, [line.strip() for line in lines]))\n        return collection",
    "docstring": "Reads and returns a collection of stop words into a file."
  },
  {
    "code": "def get_network_disconnect_kwargs(self, action, network_name, container_name, kwargs=None):\n        c_kwargs = dict(\n            container=container_name,\n            net_id=network_name,\n        )\n        update_kwargs(c_kwargs, kwargs)\n        return c_kwargs",
    "docstring": "Generates keyword arguments for the Docker client to remove a container from a network.\n\n        :param action: Action configuration.\n        :type action: ActionConfig\n        :param container_name: Container name or id.\n        :type container_name: unicode | str\n        :param network_name: Network name or id.\n        :type network_name: unicode | str\n        :param kwargs: Additional keyword arguments to complement or override the configuration-based values.\n        :type kwargs: dict\n        :return: Resulting keyword arguments.\n        :rtype: dict"
  },
  {
    "code": "def _set_aws_environment(task: Task = None):\n  current_zone = os.environ.get('NCLUSTER_ZONE', '')\n  current_region = os.environ.get('AWS_DEFAULT_REGION', '')\n  def log(*args):\n    if task:\n      task.log(*args)\n    else:\n      util.log(*args)\n  if current_region and current_zone:\n    assert current_zone.startswith(\n      current_region), f'Current zone \"{current_zone}\" ($NCLUSTER_ZONE) is not ' \\\n                       f'in current region \"{current_region} ($AWS_DEFAULT_REGION)'\n    assert u.get_session().region_name == current_region\n  if current_zone and not current_region:\n    current_region = current_zone[:-1]\n    os.environ['AWS_DEFAULT_REGION'] = current_region\n  if not current_region:\n    current_region = u.get_session().region_name\n    if not current_region:\n      log(f\"No default region available, using {NCLUSTER_DEFAULT_REGION}\")\n      current_region = NCLUSTER_DEFAULT_REGION\n    os.environ['AWS_DEFAULT_REGION'] = current_region\n  log(f\"Using account {u.get_account_number()}, region {current_region}, \"\n      f\"zone {current_zone}\")",
    "docstring": "Sets up AWS environment from NCLUSTER environment variables"
  },
  {
    "code": "def reconfigure(self, service_id, workers):\n        try:\n            sc = self._services[service_id]\n        except KeyError:\n            raise ValueError(\"%s service id doesn't exists\" % service_id)\n        else:\n            _utils.check_workers(workers, minimum=(1 - sc.workers))\n            sc.workers = workers\n            self._forktimes = []",
    "docstring": "Reconfigure a service registered in ServiceManager\n\n        :param service_id: the service id\n        :type service_id: uuid.uuid4\n        :param workers: number of processes/workers for this service\n        :type workers: int\n        :raises: ValueError"
  },
  {
    "code": "def find(cls, session, resource_id, include=None):\n        url = session._build_url(cls._resource_path(), resource_id)\n        params = build_request_include(include, None)\n        process = cls._mk_one(session, include=include)\n        return session.get(url, CB.json(200, process), params=params)",
    "docstring": "Retrieve a single resource.\n\n        This should only be called from sub-classes.\n\n        Args:\n\n            session(Session): The session to find the resource in\n\n            resource_id: The ``id`` for the resource to look up\n\n        Keyword Args:\n\n            include: Resource classes to include\n\n        Returns:\n\n            Resource: An instance of a resource, or throws a\n              :class:`NotFoundError` if the resource can not be found."
  },
  {
    "code": "def create(cls, *operands, **kwargs):\n        converted_operands = []\n        for op in operands:\n            if not isinstance(op, Scalar):\n                op = ScalarValue.create(op)\n            converted_operands.append(op)\n        return super().create(*converted_operands, **kwargs)",
    "docstring": "Instantiate the product while applying simplification rules"
  },
  {
    "code": "def data_request(self, payload, timeout=TIMEOUT):\n        request_url = self.base_url + \"/data_request\"\n        return requests.get(request_url, timeout=timeout, params=payload)",
    "docstring": "Perform a data_request and return the result."
  },
  {
    "code": "def stop(self):\n        with self.lock:\n            self._message_received(ConnectionClosed(self._file, self))",
    "docstring": "Stop the communication with the shield."
  },
  {
    "code": "def _create_part(self, action, data, **kwargs):\n        if 'suppress_kevents' in kwargs:\n            data['suppress_kevents'] = kwargs.pop('suppress_kevents')\n        query_params = kwargs\n        query_params['select_action'] = action\n        response = self._request('POST', self._build_url('parts'),\n                                 params=query_params,\n                                 data=data)\n        if response.status_code != requests.codes.created:\n            raise APIError(\"Could not create part, {}: {}\".format(str(response), response.content))\n        return Part(response.json()['results'][0], client=self)",
    "docstring": "Create a part internal core function."
  },
  {
    "code": "def reset_codenames(self, dry_run=None, clear_existing=None):\n        self.created_codenames = []\n        self.updated_names = []\n        actions = [\"add\", \"change\", \"delete\", \"view\"]\n        if django.VERSION >= (2, 1):\n            actions.append(\"view\")\n        for app in django_apps.get_app_configs():\n            for model in app.get_models():\n                try:\n                    getattr(model, model._meta.simple_history_manager_attribute)\n                except AttributeError:\n                    pass\n                else:\n                    self.update_or_create(\n                        model, dry_run=dry_run, clear_existing=clear_existing\n                    )\n        if dry_run:\n            print(\"This is a dry-run. No modifications were made.\")\n        if self.created_codenames:\n            print(\"The following historical permission.codenames were be added:\")\n            pprint(self.created_codenames)\n        else:\n            print(\"No historical permission.codenames were added.\")\n        if self.updated_names:\n            print(\"The following historical permission.names were updated:\")\n            pprint(self.updated_names)\n        else:\n            print(\"No historical permission.names were updated.\")",
    "docstring": "Ensures all historical model codenames exist in Django's Permission\n        model."
  },
  {
    "code": "def send_sticker(self, sticker, **options):\n        return self.bot.api_call(\n            \"sendSticker\", chat_id=str(self.id), sticker=sticker, **options\n        )",
    "docstring": "Send a sticker to the chat.\n\n        :param sticker: Sticker to send (file or string)\n        :param options: Additional sendSticker options (see\n            https://core.telegram.org/bots/api#sendsticker)"
  },
  {
    "code": "def get_detector_incidents(self, id, **kwargs):\n        resp = self._get(\n            self._u(self._DETECTOR_ENDPOINT_SUFFIX, id, 'incidents'),\n            None,\n            **kwargs\n        )\n        resp.raise_for_status()\n        return resp.json()",
    "docstring": "Gets all incidents for a detector"
  },
  {
    "code": "def parent(self):\n        parent_id = self._json_data.get('parent_id')\n        if parent_id is None:\n            raise NotFoundError(\"Cannot find subprocess for this task '{}', \"\n                                \"as this task exist on top level.\".format(self.name))\n        return self._client.activity(pk=parent_id, scope=self.scope_id)",
    "docstring": "Retrieve the parent in which this activity is defined.\n\n        If this is a task on top level, it raises NotFounderror.\n\n        :return: a :class:`Activity2`\n        :raises NotFoundError: when it is a task in the top level of a project\n        :raises APIError: when other error occurs\n\n        Example\n        -------\n        >>> task = project.activity('Subtask')\n        >>> parent_of_task = task.parent()"
  },
  {
    "code": "def comparator_eval(comparator_params):\n    top1, top2, params1, params2, seq1, seq2, movements = comparator_params\n    xrot, yrot, zrot, xtrans, ytrans, ztrans = movements\n    obj1 = top1(*params1)\n    obj2 = top2(*params2)\n    obj2.rotate(xrot, [1, 0, 0])\n    obj2.rotate(yrot, [0, 1, 0])\n    obj2.rotate(zrot, [0, 0, 1])\n    obj2.translate([xtrans, ytrans, ztrans])\n    model = obj1 + obj2\n    model.relabel_all()\n    model.pack_new_sequences(seq1 + seq2)\n    return model.buff_interaction_energy.total_energy",
    "docstring": "Gets BUFF score for interaction between two AMPAL objects"
  },
  {
    "code": "def version(self):\n        res = self.client.service.Version()\n        return '.'.join([ustr(x) for x in res[0]])",
    "docstring": "Return version of the TR DWE."
  },
  {
    "code": "def build_gtapp(appname, dry_run, **kwargs):\n    pfiles_orig = _set_pfiles(dry_run, **kwargs)\n    gtapp = GtApp.GtApp(appname)\n    update_gtapp(gtapp, **kwargs)\n    _reset_pfiles(pfiles_orig)\n    return gtapp",
    "docstring": "Build an object that can run ScienceTools application\n\n    Parameters\n    ----------\n    appname : str\n        Name of the application (e.g., gtbin)\n\n    dry_run : bool\n        Print command but do not run it\n\n    kwargs : arguments used to invoke the application\n\n    Returns `GtApp.GtApp` object that will run the application in question"
  },
  {
    "code": "def fetch(cls, channel, start, end, bits=None, host=None, port=None,\n              verbose=False, connection=None, type=Nds2ChannelType.any()):\n        new = cls.DictClass.fetch(\n            [channel], start, end, host=host, port=port,\n            verbose=verbose, connection=connection)[channel]\n        if bits:\n            new.bits = bits\n        return new",
    "docstring": "Fetch data from NDS into a `StateVector`.\n\n        Parameters\n        ----------\n        channel : `str`, `~gwpy.detector.Channel`\n            the name of the channel to read, or a `Channel` object.\n\n        start : `~gwpy.time.LIGOTimeGPS`, `float`, `str`\n            GPS start time of required data,\n            any input parseable by `~gwpy.time.to_gps` is fine\n\n        end : `~gwpy.time.LIGOTimeGPS`, `float`, `str`\n            GPS end time of required data,\n            any input parseable by `~gwpy.time.to_gps` is fine\n\n        bits : `Bits`, `list`, optional\n            definition of bits for this `StateVector`\n\n        host : `str`, optional\n            URL of NDS server to use, defaults to observatory site host\n\n        port : `int`, optional\n            port number for NDS server query, must be given with `host`\n\n        verify : `bool`, optional, default: `True`\n            check channels exist in database before asking for data\n\n        connection : `nds2.connection`\n            open NDS connection to use\n\n        verbose : `bool`, optional\n            print verbose output about NDS progress\n\n        type : `int`, optional\n            NDS2 channel type integer\n\n        dtype : `type`, `numpy.dtype`, `str`, optional\n            identifier for desired output data type"
  },
  {
    "code": "def factorset_divide(factorset1, factorset2):\n    r\n    if not isinstance(factorset1, FactorSet) or not isinstance(factorset2, FactorSet):\n        raise TypeError(\"factorset1 and factorset2 must be FactorSet instances\")\n    return factorset1.divide(factorset2, inplace=False)",
    "docstring": "r\"\"\"\n    Base method for dividing two factor sets.\n\n    Division of two factor sets :math:`\\frac{\\vec\\phi_1}{\\vec\\phi_2}` basically translates to union of all the factors\n    present in :math:`\\vec\\phi_2` and :math:`\\frac{1}{\\phi_i}` of all the factors present in :math:`\\vec\\phi_2`.\n\n    Parameters\n    ----------\n    factorset1: FactorSet\n        The dividend\n\n    factorset2: FactorSet\n        The divisor\n\n    Returns\n    -------\n    The division of factorset1 and factorset2\n\n    Examples\n    --------\n    >>> from pgmpy.factors import FactorSet\n    >>> from pgmpy.factors.discrete import DiscreteFactor\n    >>> from pgmpy.factors import factorset_divide\n    >>> phi1 = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12))\n    >>> phi2 = DiscreteFactor(['x3', 'x4', 'x1'], [2, 2, 2], range(8))\n    >>> factor_set1 = FactorSet(phi1, phi2)\n    >>> phi3 = DiscreteFactor(['x5', 'x6', 'x7'], [2, 2, 2], range(8))\n    >>> phi4 = DiscreteFactor(['x5', 'x7', 'x8'], [2, 2, 2], range(8))\n    >>> factor_set2 = FactorSet(phi3, phi4)\n    >>> factor_set3 = factorset_divide(factor_set2, factor_set1)\n    >>> print(factor_set3)\n    set([<DiscreteFactor representing phi(x3:2, x4:2, x1:2) at 0x7f119ad78f90>,\n         <DiscreteFactor representing phi(x5:2, x6:2, x7:2) at 0x7f119ad78e50>,\n         <DiscreteFactor representing phi(x1:2, x2:3, x3:2) at 0x7f119ad78ed0>,\n         <DiscreteFactor representing phi(x5:2, x7:2, x8:2) at 0x7f119ad78e90>])"
  },
  {
    "code": "def readInput(self, directory, projectFileName, session, spatial=False, spatialReferenceID=None):\n        self.project_directory = directory\n        with tmp_chdir(directory):\n            session.add(self)\n            self.read(directory, projectFileName, session, spatial, spatialReferenceID)\n            if spatialReferenceID is None:\n                spatialReferenceID = self._automaticallyDeriveSpatialReferenceId(directory)\n            replaceParamFile = self._readReplacementFiles(directory, session, spatial, spatialReferenceID)\n            self._readXput(self.INPUT_FILES, directory, session, spatial=spatial, spatialReferenceID=spatialReferenceID, replaceParamFile=replaceParamFile)\n            self._readXputMaps(self.INPUT_MAPS, directory, session, spatial=spatial, spatialReferenceID=spatialReferenceID, replaceParamFile=replaceParamFile)\n            self._commit(session, self.COMMIT_ERROR_MESSAGE)",
    "docstring": "Read only input files for a GSSHA project into the database.\n\n        Use this method to read a project when only pre-processing tasks need to be performed.\n\n        Args:\n            directory (str): Directory containing all GSSHA model files. This method assumes that all files are located\n                in the same directory.\n            projectFileName (str): Name of the project file for the GSSHA model which will be read (e.g.: 'example.prj').\n            session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database\n            spatial (bool, optional): If True, spatially enabled objects will be read in as PostGIS spatial objects.\n                Defaults to False.\n            spatialReferenceID (int, optional): Integer id of spatial reference system for the model. If no id is\n                provided GsshaPy will attempt to automatically lookup the spatial reference ID. If this process fails,\n                default srid will be used (4326 for WGS 84)."
  },
  {
    "code": "def del_token(token):\n    token_path = os.path.join(__opts__['token_dir'], token)\n    if os.path.exists(token_path):\n        return os.remove(token_path) is None\n    return False",
    "docstring": "Delete an eauth token by name\n\n    CLI Example:\n\n    .. code-block:: shell\n\n        salt-run auth.del_token 6556760736e4077daa601baec2b67c24"
  },
  {
    "code": "def list_nodes_full(call=None):\n    response = _query('grid', 'server/list')\n    ret = {}\n    for item in response['list']:\n        name = item['name']\n        ret[name] = item\n        ret[name]['image_info'] = item['image']\n        ret[name]['image'] = item['image']['friendlyName']\n        ret[name]['size'] = item['ram']['name']\n        ret[name]['public_ips'] = [item['ip']['ip']]\n        ret[name]['private_ips'] = []\n        ret[name]['state_info'] = item['state']\n        if 'active' in item['state']['description']:\n            ret[name]['state'] = 'RUNNING'\n    return ret",
    "docstring": "List nodes, with all available information\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -F"
  },
  {
    "code": "def configure_host_cache(enabled, datastore=None, swap_size_MiB=None,\n                         service_instance=None):\n    log.debug('Validating host cache input')\n    schema = SimpleHostCacheSchema.serialize()\n    try:\n        jsonschema.validate({'enabled': enabled,\n                             'datastore_name': datastore,\n                             'swap_size_MiB': swap_size_MiB},\n                            schema)\n    except jsonschema.exceptions.ValidationError as exc:\n        raise ArgumentValueError(exc)\n    if not enabled:\n        raise ArgumentValueError('Disabling the host cache is not supported')\n    ret_dict = {'enabled': False}\n    host_ref = _get_proxy_target(service_instance)\n    hostname = __proxy__['esxi.get_details']()['esxi_host']\n    if datastore:\n        ds_refs = salt.utils.vmware.get_datastores(\n            service_instance, host_ref, datastore_names=[datastore])\n        if not ds_refs:\n            raise VMwareObjectRetrievalError(\n                'Datastore \\'{0}\\' was not found on host '\n                '\\'{1}\\''.format(datastore, hostname))\n        ds_ref = ds_refs[0]\n    salt.utils.vmware.configure_host_cache(host_ref, ds_ref, swap_size_MiB)\n    return True",
    "docstring": "Configures the host cache on the selected host.\n\n    enabled\n        Boolean flag specifying whether the host cache is enabled.\n\n    datastore\n        Name of the datastore that contains the host cache. Must be set if\n        enabled is ``true``.\n\n    swap_size_MiB\n        Swap size in Mibibytes. Needs to be set if enabled is ``true``. Must be\n        smaller than the datastore size.\n\n    service_instance\n        Service instance (vim.ServiceInstance) of the vCenter/ESXi host.\n        Default is None.\n\n    .. code-block:: bash\n\n        salt '*' vsphere.configure_host_cache enabled=False\n\n        salt '*' vsphere.configure_host_cache enabled=True datastore=ds1\n            swap_size_MiB=1024"
  },
  {
    "code": "def log_coroutine(self, cor, *args, **kwargs):\n        if self.stopping:\n            raise LoopStoppingError(\"Could not launch coroutine because loop is shutting down: %s\" % cor)\n        self.start()\n        cor = _instaniate_coroutine(cor, args, kwargs)\n        def _run_and_log():\n            task = self.loop.create_task(cor)\n            task.add_done_callback(lambda x: _log_future_exception(x, self._logger))\n        if self.inside_loop():\n            _run_and_log()\n        else:\n            self.loop.call_soon_threadsafe(_run_and_log)",
    "docstring": "Run a coroutine logging any exception raised.\n\n        This routine will not block until the coroutine is finished\n        nor will it return any result.  It will just log if any\n        exception is raised by the coroutine during operation.\n\n        It is safe to call from both inside and outside the event loop.\n\n        There is no guarantee on how soon the coroutine will be scheduled.\n\n        Args:\n            cor (coroutine): The coroutine that we wish to run in the\n                background and wait until it finishes."
  },
  {
    "code": "def abs(cls, x: 'TensorFluent') -> 'TensorFluent':\n        return cls._unary_op(x, tf.abs, tf.float32)",
    "docstring": "Returns a TensorFluent for the abs function.\n\n        Args:\n            x: The input fluent.\n\n        Returns:\n            A TensorFluent wrapping the abs function."
  },
  {
    "code": "def save_hex(hex_file, path):\n    if not hex_file:\n        raise ValueError('Cannot flash an empty .hex file.')\n    if not path.endswith('.hex'):\n        raise ValueError('The path to flash must be for a .hex file.')\n    with open(path, 'wb') as output:\n        output.write(hex_file.encode('ascii'))",
    "docstring": "Given a string representation of a hex file, this function copies it to\n    the specified path thus causing the device mounted at that point to be\n    flashed.\n\n    If the hex_file is empty it will raise a ValueError.\n\n    If the filename at the end of the path does not end in '.hex' it will raise\n    a ValueError."
  },
  {
    "code": "def partial_path_match(path1, path2, kwarg_re=r'\\{.*\\}'):\n    split_p1 = path1.split('/')\n    split_p2 = path2.split('/')\n    pat = re.compile(kwarg_re)\n    if len(split_p1) != len(split_p2):\n        return False\n    for partial_p1, partial_p2 in zip(split_p1, split_p2):\n        if pat.match(partial_p1) or pat.match(partial_p2):\n            continue\n        if not partial_p1 == partial_p2:\n            return False\n    return True",
    "docstring": "Validates if path1 and path2 matches, ignoring any kwargs in the string.\n\n    We need this to ensure we can match Swagger patterns like:\n        /foo/{id}\n    against the observed pyramid path\n        /foo/1\n\n    :param path1: path of a url\n    :type path1: string\n    :param path2: path of a url\n    :type path2: string\n    :param kwarg_re: regex pattern to identify kwargs\n    :type kwarg_re: regex string\n    :returns: boolean"
  },
  {
    "code": "def _group_by_equal_size(obj_list, tot_groups, threshold=pow(2, 32)):\n    sorted_obj_list = sorted([(obj['size'], obj) for obj in obj_list], reverse=True)\n    groups = [(random.random(), []) for _ in range(tot_groups)]\n    if tot_groups <= 1:\n        groups = _group_by_size_greedy(obj_list, tot_groups)\n        return groups\n    heapq.heapify(groups)\n    for obj in sorted_obj_list:\n        if obj[0] > threshold:\n            heapq.heappush(groups, (obj[0], [obj[1]]))\n        else:\n            size, files = heapq.heappop(groups)\n            size += obj[0]\n            files.append(obj[1])\n            heapq.heappush(groups, (size, files))\n    groups = [group[1] for group in groups]\n    return groups",
    "docstring": "Partition a list of objects evenly and by file size\n\n    Files are placed according to largest file in the smallest bucket. If the\n    file is larger than the given threshold, then it is placed in a new bucket\n    by itself.\n    :param obj_list: a list of dict-like objects with a 'size' property\n    :param tot_groups: number of partitions to split the data\n    :param threshold: the maximum size of each bucket\n    :return: a list of lists, one for each partition"
  },
  {
    "code": "def notUnique(iterable, reportMax=INF):\n    hash = {}\n    n=0\n    if reportMax < 1:\n        raise ValueError(\"`reportMax` must be >= 1 and is %r\" % reportMax)\n    for item in iterable:\n        count = hash[item] = hash.get(item, 0) + 1\n        if count > 1:\n            yield item\n            n += 1\n            if n >= reportMax:\n                return",
    "docstring": "Returns the elements in `iterable` that aren't unique; stops after it found\n    `reportMax` non-unique elements.\n\n    Examples:\n\n    >>> list(notUnique([1,1,2,2,3,3]))\n    [1, 2, 3]\n    >>> list(notUnique([1,1,2,2,3,3], 1))\n    [1]"
  },
  {
    "code": "def locate(self, path):\n        return Zconfig(lib.zconfig_locate(self._as_parameter_, path), False)",
    "docstring": "Find a config item along a path; leading slash is optional and ignored."
  },
  {
    "code": "def wait(objects, count=None, timeout=None):\n    for obj in objects:\n        if not hasattr(obj, 'add_done_callback'):\n            raise TypeError('Expecting sequence of waitable objects')\n    if count is None:\n        count = len(objects)\n    if count < 0 or count > len(objects):\n        raise ValueError('count must be between 0 and len(objects)')\n    if count == 0:\n        return [], objects\n    pending = list(objects)\n    done = []\n    try:\n        for obj in _wait(pending, timeout):\n            done.append(obj)\n            if len(done) == count:\n                break\n    except Timeout:\n        pass\n    return done, list(filter(bool, pending))",
    "docstring": "Wait for one or more waitable objects.\n\n    This method waits until *count* elements from the sequence of waitable\n    objects *objects* have become ready. If *count* is ``None`` (the default),\n    then wait for all objects to become ready.\n\n    What \"ready\" is means depends on the object type. A waitable object is a\n    objects that implements the ``add_done_callback()`` and\n    ``remove_done_callback`` methods. This currently includes:\n\n      * :class:`~gruvi.Event` - an event is ready when its internal flag is set.\n      * :class:`~gruvi.Future` - a future is ready when its result is set.\n      * :class:`~gruvi.Fiber` - a fiber is ready when has terminated.\n      * :class:`~gruvi.Process` - a process is ready when the child has exited."
  },
  {
    "code": "def boolean(flag):\n    s = flag.lower()\n    if s in ('1', 'yes', 'true'):\n        return True\n    elif s in ('0', 'no', 'false'):\n        return False\n    raise ValueError('Unknown flag %r' % s)",
    "docstring": "Convert string in boolean"
  },
  {
    "code": "def GetEntries(self, parser_mediator, top_level=None, **unused_kwargs):\n    for entry in top_level:\n      datetime_value = entry.get('date', None)\n      package_identifiers = entry.get('packageIdentifiers', [])\n      if not datetime_value or not package_identifiers:\n        continue\n      display_name = entry.get('displayName', '<UNKNOWN>')\n      display_version = entry.get('displayVersion', '<DISPLAY_VERSION>')\n      process_name = entry.get('processName', '<PROCESS_NAME>')\n      package_identifiers = ', '.join(package_identifiers)\n      event_data = plist_event.PlistTimeEventData()\n      event_data.desc = (\n          'Installation of [{0:s} {1:s}] using [{2:s}]. Packages: '\n          '{3:s}.').format(\n              display_name, display_version, process_name, package_identifiers)\n      event_data.key = ''\n      event_data.root = '/item'\n      event = time_events.PythonDatetimeEvent(\n          datetime_value, definitions.TIME_DESCRIPTION_WRITTEN)\n      parser_mediator.ProduceEventWithEventData(event, event_data)",
    "docstring": "Extracts relevant install history entries.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      top_level (dict[str, object]): plist top-level key."
  },
  {
    "code": "def start(self):\n        while True:\n            self.thread_debug(\"Interval starting\")\n            for thr in threading.enumerate():\n                self.thread_debug(\"    \" + str(thr))\n            self.feed_monitors()\n            start = time.time()\n            self.workers_queue.join()\n            end = time.time()\n            diff = self.config['interval']['test'] - (end - start)\n            if diff <= 0:\n                self.stats.procwin = -diff\n                self.thread_debug(\"Cannot keep up with tests! {} seconds late\"\n                                  .format(abs(diff)))\n            else:\n                self.thread_debug(\"waiting {} seconds...\".format(diff))\n                time.sleep(diff)",
    "docstring": "The main loop, run forever."
  },
  {
    "code": "def process_post_media_attachment(self, bulk_mode, api_media_attachment):\n        attachment = None\n        if bulk_mode:\n            attachment = self.ref_data_map[\"media\"].get(api_media_attachment[\"ID\"])\n        if not attachment:\n            attachment, created = self.get_or_create_media(api_media_attachment)\n            if attachment and not created:\n                self.update_existing_media(attachment, api_media_attachment)\n            if attachment:\n                self.ref_data_map[\"media\"][api_media_attachment[\"ID\"]] = attachment\n        return attachment",
    "docstring": "Create or update a Media attached to a post.\n\n        :param bulk_mode: If True, minimize db operations by bulk creating post objects\n        :param api_media_attachment: the API data for the Media\n        :return: the Media attachment object"
  },
  {
    "code": "def __parse_namespace(self):\n        if self.manifest.has_option('config', 'namespace'):\n            return self.manifest.get('config', 'namespace')\n        elif self.manifest.has_option('config', 'source'):\n            return NAMESPACE_REGEX.search(self.manifest.get('config', 'source')).groups()[0]\n        else:\n            logger.warn('Could not parse namespace implicitely')\n            return None",
    "docstring": "Parse the namespace from various sources"
  },
  {
    "code": "def gen_textfiles_from_filenames(\n        filenames: Iterable[str]) -> Generator[TextIO, None, None]:\n    for filename in filenames:\n        with open(filename) as f:\n            yield f",
    "docstring": "Generates file-like objects from a list of filenames.\n\n    Args:\n        filenames: iterable of filenames\n\n    Yields:\n        each file as a :class:`TextIO` object"
  },
  {
    "code": "def ystep(self):\n        amidx = self.index_addmsk()\n        Yi = self.cbpdn.AX[amidx] + self.cbpdn.U[amidx]\n        self.inner_ystep()\n        Yi[np.where(self.W.astype(np.bool))] = 0.0\n        self.cbpdn.Y[amidx] = Yi",
    "docstring": "This method is inserted into the inner cbpdn object,\n        replacing its own ystep method, thereby providing a hook for\n        applying the additional steps necessary for the AMS method."
  },
  {
    "code": "def _list_getter(self):\n        def get_child_element_list(obj):\n            return obj.findall(qn(self._nsptagname))\n        get_child_element_list.__doc__ = (\n            'A list containing each of the ``<%s>`` child elements, in the o'\n            'rder they appear.' % self._nsptagname\n        )\n        return get_child_element_list",
    "docstring": "Return a function object suitable for the \"get\" side of a list\n        property descriptor."
  },
  {
    "code": "def local(self):\n        assert self.name in CFG[\"container\"][\"images\"].value\n        tmp_dir = local.path(str(CFG[\"tmp_dir\"]))\n        target_dir = tmp_dir / self.name\n        if not target_dir.exists() or not is_valid(self, target_dir):\n            unpack(self, target_dir)\n        return target_dir",
    "docstring": "Finds the current location of a container.\n        Also unpacks the project if necessary.\n\n        Returns:\n            target: The path, where the container lies in the end."
  },
  {
    "code": "def __get_host(node, vm_):\n    if __get_ssh_interface(vm_) == 'private_ips' or vm_['external_ip'] is None:\n        ip_address = node.private_ips[0]\n        log.info('Salt node data. Private_ip: %s', ip_address)\n    else:\n        ip_address = node.public_ips[0]\n        log.info('Salt node data. Public_ip: %s', ip_address)\n    if ip_address:\n        return ip_address\n    return node.name",
    "docstring": "Return public IP, private IP, or hostname for the libcloud 'node' object"
  },
  {
    "code": "def get_gene_name(cls, entry):\n        gene_name = entry.find(\"./gene/name[@type='primary']\")\n        return gene_name.text if gene_name is not None and gene_name.text.strip() else None",
    "docstring": "get primary gene name from XML node entry\n\n        :param entry: XML node entry\n        :return: str"
  },
  {
    "code": "def _find_most_recent_backup(normal_path: Optional[str]) -> Optional[str]:\n    if normal_path is None:\n        return None\n    if os.path.exists(normal_path):\n        return normal_path\n    dirname, basename = os.path.split(normal_path)\n    root, ext = os.path.splitext(basename)\n    backups = [fi for fi in os.listdir(dirname)\n               if fi.startswith(root) and fi.endswith(ext)]\n    ts_re = re.compile(r'.*-([0-9]+)' + ext + '$')\n    def ts_compare(filename):\n        match = ts_re.match(filename)\n        if not match:\n            return -1\n        else:\n            return int(match.group(1))\n    backups_sorted = sorted(backups, key=ts_compare)\n    if not backups_sorted:\n        return None\n    return os.path.join(dirname, backups_sorted[-1])",
    "docstring": "Find the most recent old settings to migrate.\n\n    The input is the path to an unqualified settings file - e.g.\n    /mnt/usbdrive/config/robotSettings.json\n\n    This will return\n    - None if the input is None (to support chaining from dict.get())\n    - The input if it exists, or\n    - The file named normal_path-TIMESTAMP.json with the highest timestamp\n      if one can be found, or\n    - None"
  },
  {
    "code": "def get_api_version(base_url, api_version=None, timeout=10, verify=True):\n    versions = available_api_versions(base_url, timeout, verify)\n    newest_version = max([float(i) for i in versions])\n    if api_version is None:\n        api_version = newest_version\n    else:\n        if api_version not in versions:\n            api_version = newest_version\n    return api_version",
    "docstring": "Get the API version specified or resolve the latest version\n\n    :return api version\n    :rtype: float"
  },
  {
    "code": "def charm_icon_url(self, charm_id, channel=None):\n        url = '{}/{}/icon.svg'.format(self.url, _get_path(charm_id))\n        return _add_channel(url, channel)",
    "docstring": "Generate the path to the icon for charms.\n\n        @param charm_id The ID of the charm.\n        @param channel Optional channel name.\n        @return The url to the icon."
  },
  {
    "code": "def key_rule(self, regex, verifier):\n        if regex is not None:\n            regex = re.compile(regex)\n        self._additional_key_rules.append((regex, verifier))",
    "docstring": "Add a rule with a pattern that should apply to all keys.\n\n        Any key not explicitly listed in an add_required or add_optional rule\n        must match ONE OF the rules given in a call to key_rule().\n        So these rules are all OR'ed together.\n\n        In this case you should pass a raw string specifying a regex that is\n        used to determine if the rule is used to check a given key.\n\n\n        Args:\n            regex (str): The regular expression used to match the rule or None\n                if this should apply to all\n            verifier (Verifier): The verification rule"
  },
  {
    "code": "def print_coordinates(atoms, V, title=\"\"):\n    print(set_coordinates(atoms, V, title=title))\n    return",
    "docstring": "Print coordinates V with corresponding atoms to stdout in XYZ format.\n\n    Parameters\n    ----------\n    atoms : list\n        List of element types\n    V : array\n        (N,3) matrix of atomic coordinates\n    title : string (optional)\n        Title of molecule"
  },
  {
    "code": "def penalty_satisfaction(response, bqm):\n    record = response.record\n    label_dict = response.variables.index\n    if len(bqm.info['reduction']) == 0:\n        return np.array([1] * len(record.sample))\n    penalty_vector = np.prod([record.sample[:, label_dict[qi]] *\n                              record.sample[:, label_dict[qj]]\n                              == record.sample[:,\n                                 label_dict[valdict['product']]]\n                              for (qi, qj), valdict in\n                              bqm.info['reduction'].items()], axis=0)\n    return penalty_vector",
    "docstring": "Creates a penalty satisfaction list\n\n    Given a sampleSet and a bqm object, will create a binary list informing\n    whether the penalties introduced during degree reduction are satisfied for\n    each sample in sampleSet\n\n    Args:\n        response (:obj:`.SampleSet`): Samples corresponding to provided bqm\n\n        bqm (:obj:`.BinaryQuadraticModel`): a bqm object that contains\n            its reduction info.\n\n    Returns:\n        :obj:`numpy.ndarray`: a binary array of penalty satisfaction information"
  },
  {
    "code": "def get_logger(name=None):\n    logger = logging.getLogger(name)\n    if len(logger.handlers) == 0:\n        logger = add_stream_handler(logger)\n    return logger",
    "docstring": "Get a logging handle.\n\n    As with ``setup_logging``, a stream handler is added to the\n    log handle.\n\n    Arguments:\n\n        name (str): Name of the log handle. Default is ``None``."
  },
  {
    "code": "def write_alignment(self, filename, file_format, interleaved=None):\n        if file_format == 'phylip':\n            file_format = 'phylip-relaxed'\n        AlignIO.write(self._msa, filename, file_format)",
    "docstring": "Write the alignment to file using Bio.AlignIO"
  },
  {
    "code": "def diff_list(self, list1, list2):\n        for key in list1:\n            if key in list2 and list2[key] != list1[key]:\n                print key\n            elif key not in list2:\n                print key",
    "docstring": "Extracts differences between lists. For debug purposes"
  },
  {
    "code": "def astuple(self, encoding=None):\n        if not encoding:\n            return (\n                self.id, self.seqid, self.source, self.featuretype, self.start,\n                self.end, self.score, self.strand, self.frame,\n                helpers._jsonify(self.attributes),\n                helpers._jsonify(self.extra), self.calc_bin()\n            )\n        return (\n            self.id.decode(encoding), self.seqid.decode(encoding),\n            self.source.decode(encoding), self.featuretype.decode(encoding),\n            self.start, self.end, self.score.decode(encoding),\n            self.strand.decode(encoding), self.frame.decode(encoding),\n            helpers._jsonify(self.attributes).decode(encoding),\n            helpers._jsonify(self.extra).decode(encoding), self.calc_bin()\n        )",
    "docstring": "Return a tuple suitable for import into a database.\n\n        Attributes field and extra field jsonified into strings. The order of\n        fields is such that they can be supplied as arguments for the query\n        defined in :attr:`gffutils.constants._INSERT`.\n\n        If `encoding` is not None, then convert string fields to unicode using\n        the provided encoding.\n\n        Returns\n        -------\n        Tuple"
  },
  {
    "code": "def find_by_project(self, project, params={}, **options): \n        path = \"/projects/%s/sections\" % (project)\n        return self.client.get(path, params, **options)",
    "docstring": "Returns the compact records for all sections in the specified project.\n\n        Parameters\n        ----------\n        project : {Id} The project to get sections from.\n        [params] : {Object} Parameters for the request"
  },
  {
    "code": "def Parse(self, raw_data):\n    self.results = raw_data\n    for f in self.filters:\n      self.results = f.Parse(self.results)\n    return self.results",
    "docstring": "Take the results and yield results that passed through the filters.\n\n    The output of each filter is used as the input for successive filters.\n\n    Args:\n      raw_data: An iterable series of rdf values.\n\n    Returns:\n      A list of rdf values that matched all filters."
  },
  {
    "code": "def join_paths(fnames:FilePathList, path:PathOrStr='.')->Collection[Path]:\n    \"Join `path` to every file name in `fnames`.\"\n    path = Path(path)\n    return [join_path(o,path) for o in fnames]",
    "docstring": "Join `path` to every file name in `fnames`."
  },
  {
    "code": "def _determine_rotated_logfile(self):\n        rotated_filename = self._check_rotated_filename_candidates()\n        if rotated_filename and exists(rotated_filename):\n            if stat(rotated_filename).st_ino == self._offset_file_inode:\n                return rotated_filename\n            if stat(self.filename).st_ino == self._offset_file_inode:\n                if self.copytruncate:\n                    return rotated_filename\n                else:\n                    sys.stderr.write(\n                        \"[pygtail] [WARN] file size of %s shrank, and copytruncate support is \"\n                        \"disabled (expected at least %d bytes, was %d bytes).\\n\" %\n                        (self.filename, self._offset, stat(self.filename).st_size))\n        return None",
    "docstring": "We suspect the logfile has been rotated, so try to guess what the\n        rotated filename is, and return it."
  },
  {
    "code": "def _get_build_command(self, mkdocs_site_path: Path) -> str:\n        components = [self._mkdocs_config.get('mkdocs_path', 'mkdocs')]\n        components.append('build')\n        components.append(f'-d \"{self._escape_control_characters(str(mkdocs_site_path))}\"')\n        command = ' '.join(components)\n        self.logger.debug(f'Build command: {command}')\n        return command",
    "docstring": "Generate ``mkdocs build`` command to build the site.\n\n        :param mkdocs_site_path: Path to the output directory for the site"
  },
  {
    "code": "def _ReloadArtifacts(self):\n    self._artifacts = {}\n    self._LoadArtifactsFromFiles(self._sources.GetAllFiles())\n    self.ReloadDatastoreArtifacts()",
    "docstring": "Load artifacts from all sources."
  },
  {
    "code": "def run_samtools(align_bams, items, ref_file, assoc_files, region=None,\n                 out_file=None):\n    return shared_variantcall(_call_variants_samtools, \"samtools\", align_bams, ref_file,\n                              items, assoc_files, region, out_file)",
    "docstring": "Detect SNPs and indels with samtools mpileup and bcftools."
  },
  {
    "code": "def does_schema_exist(self, connection):\n        if '.' in self.table:\n            query = (\"select 1 as schema_exists \"\n                     \"from pg_namespace \"\n                     \"where nspname = lower(%s) limit 1\")\n        else:\n            return True\n        cursor = connection.cursor()\n        try:\n            schema = self.table.split('.')[0]\n            cursor.execute(query, [schema])\n            result = cursor.fetchone()\n            return bool(result)\n        finally:\n            cursor.close()",
    "docstring": "Determine whether the schema already exists."
  },
  {
    "code": "def distribute(self, f, n):\n        if self.pool is None:\n            return [f(i) for i in range(n)]\n        else:\n            return self.pool.map(f, range(n))",
    "docstring": "Distribute the computations amongst the multiprocessing pools\n\n        Parameters\n        ----------\n        f : function\n          Function to be distributed to the processors\n        n : int\n          The values in range(0,n) will be passed as arguments to the\n          function f."
  },
  {
    "code": "def restore_default(self, index):\n        spec = self.get_configspec_str(index)\n        if spec is None or isinstance(spec, Section):\n            return\n        try:\n            default = self._vld.get_default_value(spec)\n            defaultstr = self._val_to_str(default)\n            self.setData(index, defaultstr)\n        except KeyError:\n            raise ConfigError(\"Missing Default Value in spec: \\\"%s\\\"\" % spec)",
    "docstring": "Set the value of the given index row to its default\n\n        :param index:\n        :type index:\n        :returns:\n        :rtype:\n        :raises:"
  },
  {
    "code": "def get_resource_attribute(resource_attr_id, **kwargs):\n    resource_attr_qry = db.DBSession.query(ResourceAttr).filter(\n        ResourceAttr.id == resource_attr_id,\n        )\n    resource_attr = resource_attr_qry.first()\n    if resource_attr is None:\n        raise ResourceNotFoundError(\"Resource attribute %s does not exist\", resource_attr_id)\n    return resource_attr",
    "docstring": "Get a specific resource attribte, by ID\n        If type_id is Gspecified, only\n        return the resource attributes within the type."
  },
  {
    "code": "def bool_env(key, default=False):\n    try:\n        return os.environ[key].lower() in TRUE\n    except KeyError:\n        return default",
    "docstring": "Parse an environment variable as a boolean switch\n\n    `True` is returned if the variable value matches one of the following:\n\n    - ``'1'``\n    - ``'y'``\n    - ``'yes'``\n    - ``'true'``\n\n    The match is case-insensitive (so ``'Yes'`` will match as `True`)\n\n    Parameters\n    ----------\n    key : `str`\n        the name of the environment variable to find\n\n    default : `bool`\n        the default return value if the key is not found\n\n    Returns\n    -------\n    True\n        if the environment variable matches as 'yes' or similar\n    False\n        otherwise\n\n    Examples\n    --------\n    >>> import os\n    >>> from gwpy.utils.env import bool_env\n    >>> os.environ['GWPY_VALUE'] = 'yes'\n    >>> print(bool_env('GWPY_VALUE'))\n    True\n    >>> os.environ['GWPY_VALUE'] = 'something else'\n    >>> print(bool_env('GWPY_VALUE'))\n    False\n    >>> print(bool_env('GWPY_VALUE2'))\n    False"
  },
  {
    "code": "def reana_ready():\n    from reana_commons.config import REANA_READY_CONDITIONS\n    for module_name, condition_list in REANA_READY_CONDITIONS.items():\n        for condition_name in condition_list:\n            module = importlib.import_module(module_name)\n            condition_func = getattr(module, condition_name)\n            if not condition_func():\n                return False\n    return True",
    "docstring": "Check if reana can start new workflows."
  },
  {
    "code": "def pcc_pos(self, row1, row2):\n        mean1 = np.mean(row1)\n        mean2 = np.mean(row2)\n        a = 0\n        x = 0\n        y = 0\n        for n1, n2 in zip(row1, row2):\n            a += (n1 - mean1) * (n2 - mean2)\n            x += (n1 - mean1) ** 2\n            y += (n2 - mean2) ** 2\n        if a == 0:\n            return 0\n        else:\n            return a / sqrt(x * y)",
    "docstring": "Calculate the Pearson correlation coefficient of one position\n        compared to another position.\n\n        Returns\n        -------\n        score : float\n            Pearson correlation coefficient."
  },
  {
    "code": "def _rndLetterTransform(self, image):\n        w, h = image.size\n        dx = w * random.uniform(0.2, 0.7)\n        dy = h * random.uniform(0.2, 0.7)\n        x1, y1 = self.__class__._rndPointDisposition(dx, dy)\n        x2, y2 = self.__class__._rndPointDisposition(dx, dy)\n        w += abs(x1) + abs(x2)\n        h += abs(x1) + abs(x2)\n        quad = self.__class__._quadPoints((w, h), (x1, y1), (x2, y2))\n        return image.transform(image.size, Image.QUAD,\n                               data=quad, resample=self.resample)",
    "docstring": "Randomly morph a single character."
  },
  {
    "code": "def build(self, ignore=None):\n        self._prepare_workspace()\n        self.install_dependencies()\n        self.package(ignore)",
    "docstring": "Calls all necessary methods to build the Lambda Package"
  },
  {
    "code": "def parse(self, string, strict=True):\n        if isinstance(string, bytes):\n            errors = 'strict' if strict else 'replace'\n            string = string.decode(self.encoding, errors=errors)\n        if not self.raw:\n            self.raw = string\n        else:\n            self.raw += string\n        lines = unfold_lines(string).splitlines()\n        for line in lines:\n            if line:\n                if ':' not in line:\n                    if strict:\n                        raise ValueError('Field missing colon.')\n                    else:\n                        continue\n                name, value = line.split(':', 1)\n                name = name.strip()\n                value = value.strip()\n                self.add(name, value)",
    "docstring": "Parse the string or bytes.\n\n        Args:\n            strict (bool): If True, errors will not be ignored\n\n        Raises:\n            :class:`ValueError` if the record is malformed."
  },
  {
    "code": "def out_of_date(self):\n        try:\n            latest_remote_sha = self.pr_commits(self.pull_request.refresh(True))[-1].sha\n            print(\"Latest remote sha: {}\".format(latest_remote_sha))\n            try:\n                print(\"Ratelimit remaining: {}\".format(self.github.ratelimit_remaining))\n            except Exception:\n                print(\"Failed to look up ratelimit remaining\")\n            return self.last_sha != latest_remote_sha\n        except IndexError:\n            return False",
    "docstring": "Check if our local latest sha matches the remote latest sha"
  },
  {
    "code": "def guess_python_env():\n    version, major, minor = get_version_info()\n    if 'PyPy' in version:\n        return 'pypy3' if major == 3 else 'pypy'\n    return 'py{major}{minor}'.format(major=major, minor=minor)",
    "docstring": "Guess the default python env to use."
  },
  {
    "code": "def metapolicy(request, permitted, domains=None):\n    if domains is None:\n        domains = []\n    policy = policies.Policy(*domains)\n    policy.metapolicy(permitted)\n    return serve(request, policy)",
    "docstring": "Serves a cross-domain policy which can allow other policies\n    to exist on the same domain.\n\n    Note that this view, if used, must be the master policy for the\n    domain, and so must be served from the URL ``/crossdomain.xml`` on\n    the domain: setting metapolicy information in other policy files\n    is forbidden by the cross-domain policy specification.\n\n    **Required arguments:**\n\n    ``permitted``\n        A string indicating the extent to which other policies are\n        permitted. A set of constants is available in\n        ``flashpolicies.policies``, defining acceptable values for\n        this argument.\n\n    **Optional arguments:**\n\n    ``domains``\n        A list of domains from which to allow access. Each value may\n        be either a domain name (e.g., ``example.com``) or a wildcard\n        (e.g., ``*.example.com``). Due to serious potential security\n        issues, it is strongly recommended that you not use wildcard\n        domain values."
  },
  {
    "code": "def solve(expected: List[Tuple[float, float]],\n          actual: List[Tuple[float, float]]) -> np.ndarray:\n    ex = np.array([\n            list(point) + [1]\n            for point in expected\n        ]).transpose()\n    ac = np.array([\n            list(point) + [1]\n            for point in actual\n        ]).transpose()\n    transform = np.dot(ac, inv(ex))\n    return transform",
    "docstring": "Takes two lists of 3 x-y points each, and calculates the matrix\n    representing the transformation from one space to the other.\n\n    The 3x3 matrix returned by this method represents the 2-D transformation\n    matrix from the actual point to the expected point.\n\n    Example:\n        If the expected points are:\n            [ (1, 1),\n              (2, 2),\n              (1, 2) ]\n        And the actual measured points are:\n            [ (1.1, 1.1),\n              (2.1, 2.1),\n              (1.1, 2.1) ]\n        (in other words, a shift of exaxtly +0.1 in both x and y)\n\n        Then the resulting transformation matrix T should be:\n            [ 1  0  -0.1 ]\n            [ 0  1  -0.1 ]\n            [ 0  0   1   ]\n\n        Then, if we take a 3x3 matrix B representing one of the measured points\n        on the deck:\n            [ 1  0  1.1 ]\n            [ 0  1  2.1 ]\n            [ 0  0  1   ]\n\n        The B*T will yeild the \"actual\" point:\n            [ 1  0  1 ]\n            [ 0  1  2 ]\n            [ 0  0  1 ]\n\n        The return value of this function is the transformation matrix T"
  },
  {
    "code": "def scan(cls, formats=ALL_CODE_TYPES, camera=-1):\n        app = AndroidApplication.instance()\n        r = app.create_future()\n        pkg = BarcodePackage.instance()\n        pkg.setBarcodeResultListener(pkg.getId())\n        pkg.onBarcodeResult.connect(r.set_result)\n        intent = cls(app)\n        if formats:\n            intent.setDesiredBarcodeFormats(formats)\n        if camera != -1:\n            intent.setCameraId(camera)\n        intent.initiateScan()\n        return r",
    "docstring": "Shortcut only one at a time will work..."
  },
  {
    "code": "def list_voices(\n        self,\n        language_code=None,\n        retry=google.api_core.gapic_v1.method.DEFAULT,\n        timeout=google.api_core.gapic_v1.method.DEFAULT,\n        metadata=None,\n    ):\n        if \"list_voices\" not in self._inner_api_calls:\n            self._inner_api_calls[\n                \"list_voices\"\n            ] = google.api_core.gapic_v1.method.wrap_method(\n                self.transport.list_voices,\n                default_retry=self._method_configs[\"ListVoices\"].retry,\n                default_timeout=self._method_configs[\"ListVoices\"].timeout,\n                client_info=self._client_info,\n            )\n        request = cloud_tts_pb2.ListVoicesRequest(language_code=language_code)\n        return self._inner_api_calls[\"list_voices\"](\n            request, retry=retry, timeout=timeout, metadata=metadata\n        )",
    "docstring": "Returns a list of ``Voice`` supported for synthesis.\n\n        Example:\n            >>> from google.cloud import texttospeech_v1beta1\n            >>>\n            >>> client = texttospeech_v1beta1.TextToSpeechClient()\n            >>>\n            >>> response = client.list_voices()\n\n        Args:\n            language_code (str): Optional (but recommended)\n                `BCP-47 <https://www.rfc-editor.org/rfc/bcp/bcp47.txt>`__ language tag.\n                If specified, the ListVoices call will only return voices that can be\n                used to synthesize this language\\_code. E.g. when specifying \"en-NZ\",\n                you will get supported \"en-*\" voices; when specifying \"no\", you will get\n                supported \"no-*\" (Norwegian) and \"nb-*\" (Norwegian Bokmal) voices;\n                specifying \"zh\" will also get supported \"cmn-*\" voices; specifying\n                \"zh-hk\" will also get supported \"yue-\\*\" voices.\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.texttospeech_v1beta1.types.ListVoicesResponse` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def fill(text, width=70, **kwargs):\n    w = ParagraphWrapper(width=width, **kwargs)\n    return w.fill(text)",
    "docstring": "Fill multiple paragraphs of text, returning a new string.\n\n    Reformat multiple paragraphs in 'text' to fit in lines of no more\n    than 'width' columns, and return a new string containing the entire\n    wrapped text.  As with wrap(), tabs are expanded and other\n    whitespace characters converted to space.  See ParagraphWrapper class for\n    available keyword args to customize wrapping behaviour."
  },
  {
    "code": "def _ordered(generator, *args, **kwargs):\n    unordered_dict = {k: v for k, v in generator(*args, **kwargs)}\n    keys = sorted(list(dict(unordered_dict).keys()))\n    result = OrderedDict()\n    for key in keys:\n        result[key] = unordered_dict[key]\n    return result",
    "docstring": "Sort keys of unordered_dict and store in OrderedDict."
  },
  {
    "code": "def list(self):\n        mask =\n        results = self.client.call('Account', 'getReservedCapacityGroups', mask=mask)\n        return results",
    "docstring": "List Reserved Capacities"
  },
  {
    "code": "def get_version(self):\n        raw_version = run_cmd([\"podman\", \"version\"], return_output=True)\n        regex = re.compile(r\"Version:\\s*(\\d+)\\.(\\d+)\\.(\\d+)\")\n        match = regex.findall(raw_version)\n        try:\n            return match[0]\n        except IndexError:\n            logger.error(\"unable to parse version from `podman version`\")\n            return",
    "docstring": "return 3-tuple of version info or None\n\n        :return: (str, str, str)"
  },
  {
    "code": "def run():\n    print('Python ' + sys.version.replace('\\n', ''))\n    try:\n        oscrypto_tests_module_info = imp.find_module('tests', [os.path.join(build_root, 'oscrypto')])\n        oscrypto_tests = imp.load_module('oscrypto.tests', *oscrypto_tests_module_info)\n        oscrypto = oscrypto_tests.local_oscrypto()\n        print('\\noscrypto backend: %s' % oscrypto.backend())\n    except (ImportError):\n        pass\n    if run_lint:\n        print('')\n        lint_result = run_lint()\n    else:\n        lint_result = True\n    if run_coverage:\n        print('\\nRunning tests (via coverage.py)')\n        sys.stdout.flush()\n        tests_result = run_coverage(ci=True)\n    else:\n        print('\\nRunning tests')\n        sys.stdout.flush()\n        tests_result = run_tests()\n    sys.stdout.flush()\n    return lint_result and tests_result",
    "docstring": "Runs the linter and tests\n\n    :return:\n        A bool - if the linter and tests ran successfully"
  },
  {
    "code": "def action_ipset(reader, *args):\n    ip_set = set()\n    for record in reader:\n        if record.log_status in (SKIPDATA, NODATA):\n            continue\n        ip_set.add(record.srcaddr)\n        ip_set.add(record.dstaddr)\n    for ip in ip_set:\n        print(ip)",
    "docstring": "Show the set of IPs seen in Flow Log records."
  },
  {
    "code": "def get_movielens(variant=\"20m\"):\n    filename = \"movielens_%s.hdf5\" % variant\n    path = os.path.join(_download.LOCAL_CACHE_DIR, filename)\n    if not os.path.isfile(path):\n        log.info(\"Downloading dataset to '%s'\", path)\n        _download.download_file(URL_BASE + filename, path)\n    else:\n        log.info(\"Using cached dataset at '%s'\", path)\n    with h5py.File(path, 'r') as f:\n        m = f.get('movie_user_ratings')\n        plays = csr_matrix((m.get('data'), m.get('indices'), m.get('indptr')))\n        return np.array(f['movie']), plays",
    "docstring": "Gets movielens datasets\n\n    Parameters\n    ---------\n    variant : string\n        Which version of the movielens dataset to download. Should be one of '20m', '10m',\n        '1m' or '100k'.\n\n    Returns\n    -------\n    movies : ndarray\n        An array of the movie titles.\n    ratings : csr_matrix\n        A sparse matrix where the row is the movieId, the column is the userId and the value is\n        the rating."
  },
  {
    "code": "def _ilshift(self, n):\n        assert 0 < n <= self.len\n        self._append(Bits(n))\n        self._truncatestart(n)\n        return self",
    "docstring": "Shift bits by n to the left in place. Return self."
  },
  {
    "code": "def deliver(self, message):\n        config = self.config\n        success = config.success\n        failure = config.failure\n        exhaustion = config.exhaustion\n        if getattr(message, 'die', False):\n            1/0\n        if failure:\n            chance = random.randint(0,100001) / 100000.0\n            if chance < failure:\n                raise TransportFailedException(\"Mock failure.\")\n        if exhaustion:\n            chance = random.randint(0,100001) / 100000.0\n            if chance < exhaustion:\n                raise TransportExhaustedException(\"Mock exhaustion.\")\n        if success == 1.0:\n            return True\n        chance = random.randint(0,100001) / 100000.0\n        if chance <= success:\n            return True\n        return False",
    "docstring": "Concrete message delivery."
  },
  {
    "code": "def weld_vec_of_struct_to_struct_of_vec(vec_of_structs, weld_types):\n    obj_id, weld_obj = create_weld_object(vec_of_structs)\n    appenders = struct_of('appender[{e}]', weld_types)\n    types = struct_of('{e}', weld_types)\n    merges = struct_of('merge(b.${i}, e.${i})', weld_types)\n    result = struct_of('result(vecs.${i})', weld_types)\n    weld_template =\n    weld_obj.weld_code = weld_template.format(vec_of_struct=obj_id,\n                                              appenders=appenders,\n                                              types=types,\n                                              merges=merges,\n                                              result=result)\n    return weld_obj",
    "docstring": "Create a struct of vectors.\n\n    Parameters\n    ----------\n    vec_of_structs : WeldObject\n        Encoding a vector of structs.\n    weld_types : list of WeldType\n        The Weld types of the arrays in the same order.\n\n    Returns\n    -------\n    WeldObject\n        Representation of this computation."
  },
  {
    "code": "def oq_server_context_processor(request):\n    context = {}\n    context['oq_engine_server_url'] = ('//' +\n                                       request.META.get('HTTP_HOST',\n                                                        'localhost:8800'))\n    context['oq_engine_version'] = oqversion\n    context['server_name'] = settings.SERVER_NAME\n    return context",
    "docstring": "A custom context processor which allows injection of additional\n    context variables."
  },
  {
    "code": "def write_vaultlocker_conf(context, priority=100):\n    charm_vl_path = \"/var/lib/charm/{}/vaultlocker.conf\".format(\n        hookenv.service_name()\n    )\n    host.mkdir(os.path.dirname(charm_vl_path), perms=0o700)\n    templating.render(source='vaultlocker.conf.j2',\n                      target=charm_vl_path,\n                      context=context, perms=0o600),\n    alternatives.install_alternative('vaultlocker.conf',\n                                     '/etc/vaultlocker/vaultlocker.conf',\n                                     charm_vl_path, priority)",
    "docstring": "Write vaultlocker configuration to disk and install alternative\n\n    :param context: Dict of data from vault-kv relation\n    :ptype: context: dict\n    :param priority: Priority of alternative configuration\n    :ptype: priority: int"
  },
  {
    "code": "def _init_enrichment(self):\n        if self.study_n:\n            return 'e' if ((1.0 * self.study_count / self.study_n) >\n                           (1.0 * self.pop_count / self.pop_n)) else 'p'\n        return 'p'",
    "docstring": "Mark as 'enriched' or 'purified'."
  },
  {
    "code": "def tolist(self) -> List[bool]:\n        result = [False] * 64\n        for square in self:\n            result[square] = True\n        return result",
    "docstring": "Convert the set to a list of 64 bools."
  },
  {
    "code": "def get_action_arguments(self, service_name, action_name):\n        return self.services[service_name].actions[action_name].info",
    "docstring": "Returns a list of tuples with all known arguments for the given\n        service- and action-name combination. The tuples contain the\n        argument-name, direction and data_type."
  },
  {
    "code": "def changes(self):\n        output = []\n        if self.status() is self.UNMODIFIED:\n            output = [self.formatter % (' ', self.key, self.old_value)]\n        elif self.status() is self.ADDED:\n            output.append(self.formatter % ('+', self.key, self.new_value))\n        elif self.status() is self.REMOVED:\n            output.append(self.formatter % ('-', self.key, self.old_value))\n        elif self.status() is self.MODIFIED:\n            output.append(self.formatter % ('-', self.key, self.old_value))\n            output.append(self.formatter % ('+', self.key, self.new_value))\n        return output",
    "docstring": "Returns a list of changes to represent the diff between\n        old and new value.\n\n        Returns:\n            list: [string] representation of the change (if any)\n                between old and new value"
  },
  {
    "code": "def start(self, interval_s):\n    if self.running:\n      return False\n    self.stopped.clear()\n    def _execute():\n      if not self.method() and self.stop_if_false:\n        return\n      while not self.stopped.wait(interval_s):\n        if not self.method() and self.stop_if_false:\n          return\n    self.thread = threading.Thread(target=_execute)\n    self.thread.daemon = True\n    self.thread.start()\n    return True",
    "docstring": "Starts executing the method at the specified interval.\n\n    Args:\n      interval_s: The amount of time between executions of the method.\n    Returns:\n      False if the interval was already running."
  },
  {
    "code": "def _onAs( self, name ):\n        \" Memorizes an alias for an import or an imported item \"\n        if self.__lastImport.what:\n            self.__lastImport.what[ -1 ].alias = name\n        else:\n            self.__lastImport.alias = name\n        return",
    "docstring": "Memorizes an alias for an import or an imported item"
  },
  {
    "code": "def extract_largest(self, inplace=False):\n        mesh =  self.connectivity(largest=True)\n        if inplace:\n            self.overwrite(mesh)\n        else:\n            return mesh",
    "docstring": "Extract largest connected set in mesh.\n\n        Can be used to reduce residues obtained when generating an isosurface.\n        Works only if residues are not connected (share at least one point with)\n        the main component of the image.\n\n        Parameters\n        ----------\n        inplace : bool, optional\n            Updates mesh in-place while returning nothing.\n\n        Returns\n        -------\n        mesh : vtki.PolyData\n            Largest connected set in mesh"
  },
  {
    "code": "def dflt_sortby_ntgoea(ntgoea):\n        return [ntgoea.enrichment,\n                ntgoea.namespace,\n                ntgoea.p_uncorrected,\n                ntgoea.depth,\n                ntgoea.GO]",
    "docstring": "Default sorting of GOEA results stored in namedtuples."
  },
  {
    "code": "def close(self):\n        self._closed = True\n        if self.receive_task:\n            self.receive_task.cancel()\n        if self.connection:\n            self.connection.close()",
    "docstring": "Close the underlying connection."
  },
  {
    "code": "def fit_predict(self, data, labels, unkown=None):\n        self.fit(data, labels)\n        return self._predict_from_bmus(self._bmus, unkown)",
    "docstring": "\\\n        Fit and classify data efficiently.\n\n        :param data: sparse input matrix (ideal dtype is `numpy.float32`)\n        :type data: :class:`scipy.sparse.csr_matrix`\n        :param labels: the labels associated with data\n        :type labels: iterable\n        :param unkown: the label to attribute if no label is known\n        :returns: the labels guessed for data\n        :rtype: `numpy.array`"
  },
  {
    "code": "def autoidlepc(self, compute_id, platform, image, ram):\n        compute = self.get_compute(compute_id)\n        for project in list(self._projects.values()):\n            if project.name == \"AUTOIDLEPC\":\n                yield from project.delete()\n                self.remove_project(project)\n        project = yield from self.add_project(name=\"AUTOIDLEPC\")\n        node = yield from project.add_node(compute, \"AUTOIDLEPC\", str(uuid.uuid4()), node_type=\"dynamips\", platform=platform, image=image, ram=ram)\n        res = yield from node.dynamips_auto_idlepc()\n        yield from project.delete()\n        self.remove_project(project)\n        return res",
    "docstring": "Compute and IDLE PC value for an image\n\n        :param compute_id: ID of the compute where the idlepc operation need to run\n        :param platform: Platform type\n        :param image: Image to use\n        :param ram: amount of RAM to use"
  },
  {
    "code": "def beholder_ng(func):\n    @functools.wraps(func)\n    def behold(file, length, *args, **kwargs):\n        seek_cur = file.tell()\n        try:\n            return func(file, length, *args, **kwargs)\n        except Exception:\n            from pcapkit.protocols.raw import Raw\n            error = traceback.format_exc(limit=1).strip().split(os.linesep)[-1]\n            file.seek(seek_cur, os.SEEK_SET)\n            next_ = Raw(file, length, error=error)\n            return next_\n    return behold",
    "docstring": "Behold analysis procedure."
  },
  {
    "code": "def hungarian(A, B):\n    distances = cdist(A, B, 'euclidean')\n    indices_a, indices_b = linear_sum_assignment(distances)\n    return indices_b",
    "docstring": "Hungarian reordering.\n\n    Assume A and B are coordinates for atoms of SAME type only"
  },
  {
    "code": "def ensure_benchmark_data(symbol, first_date, last_date, now, trading_day,\n                          environ=None):\n    filename = get_benchmark_filename(symbol)\n    data = _load_cached_data(filename, first_date, last_date, now, 'benchmark',\n                             environ)\n    if data is not None:\n        return data\n    logger.info(\n        ('Downloading benchmark data for {symbol!r} '\n            'from {first_date} to {last_date}'),\n        symbol=symbol,\n        first_date=first_date - trading_day,\n        last_date=last_date\n    )\n    try:\n        data = get_benchmark_returns(symbol)\n        data.to_csv(get_data_filepath(filename, environ))\n    except (OSError, IOError, HTTPError):\n        logger.exception('Failed to cache the new benchmark returns')\n        raise\n    if not has_data_for_dates(data, first_date, last_date):\n        logger.warn(\n            (\"Still don't have expected benchmark data for {symbol!r} \"\n                \"from {first_date} to {last_date} after redownload!\"),\n            symbol=symbol,\n            first_date=first_date - trading_day,\n            last_date=last_date\n        )\n    return data",
    "docstring": "Ensure we have benchmark data for `symbol` from `first_date` to `last_date`\n\n    Parameters\n    ----------\n    symbol : str\n        The symbol for the benchmark to load.\n    first_date : pd.Timestamp\n        First required date for the cache.\n    last_date : pd.Timestamp\n        Last required date for the cache.\n    now : pd.Timestamp\n        The current time.  This is used to prevent repeated attempts to\n        re-download data that isn't available due to scheduling quirks or other\n        failures.\n    trading_day : pd.CustomBusinessDay\n        A trading day delta.  Used to find the day before first_date so we can\n        get the close of the day prior to first_date.\n\n    We attempt to download data unless we already have data stored at the data\n    cache for `symbol` whose first entry is before or on `first_date` and whose\n    last entry is on or after `last_date`.\n\n    If we perform a download and the cache criteria are not satisfied, we wait\n    at least one hour before attempting a redownload.  This is determined by\n    comparing the current time to the result of os.path.getmtime on the cache\n    path."
  },
  {
    "code": "def add_chars(self, chars):\n        'Add given chars to char set'\n        for c in chars:\n            if self._ignorecase:\n                self._whitelist_chars.add(c.lower())\n                self._whitelist_chars.add(c.upper())\n            else:\n                self._whitelist_chars.add(c)",
    "docstring": "Add given chars to char set"
  },
  {
    "code": "def getidfkeyswithnodes():\n    idf = IDF(StringIO(\"\"))\n    keys = idfobjectkeys(idf)\n    keysfieldnames = ((key, idf.newidfobject(key.upper()).fieldnames) \n                for key in keys)\n    keysnodefdnames = ((key,  (name for name in fdnames \n                                if (name.endswith('Node_Name')))) \n                            for key, fdnames in keysfieldnames)\n    nodekeys = [key for key, fdnames in keysnodefdnames if list(fdnames)]\n    return nodekeys",
    "docstring": "return a list of keys of idfobjects that hve 'None Name' fields"
  },
  {
    "code": "def update_lincs_proteins():\n    url = 'http://lincs.hms.harvard.edu/db/proteins/'\n    prot_data = load_lincs_csv(url)\n    prot_dict = {d['HMS LINCS ID']: d.copy() for d in prot_data}\n    assert len(prot_dict) == len(prot_data), \"We lost data.\"\n    fname = os.path.join(path, 'lincs_proteins.json')\n    with open(fname, 'w') as fh:\n        json.dump(prot_dict, fh, indent=1)",
    "docstring": "Load the csv of LINCS protein metadata into a dict.\n\n    Produces a dict keyed by HMS LINCS protein ids, with the metadata\n    contained in a dict of row values keyed by the column headers extracted\n    from the csv."
  },
  {
    "code": "def _delly_exclude_file(items, base_file, chrom):\n    base_exclude = sshared.prepare_exclude_file(items, base_file, chrom)\n    out_file = \"%s-delly%s\" % utils.splitext_plus(base_exclude)\n    with file_transaction(items[0], out_file) as tx_out_file:\n        with open(tx_out_file, \"w\") as out_handle:\n            with open(base_exclude) as in_handle:\n                for line in in_handle:\n                    parts = line.split(\"\\t\")\n                    if parts[0] == chrom:\n                        out_handle.write(line)\n                    else:\n                        out_handle.write(\"%s\\n\" % parts[0])\n    return out_file",
    "docstring": "Prepare a delly-specific exclude file eliminating chromosomes.\n    Delly wants excluded chromosomes listed as just the chromosome, with no coordinates."
  },
  {
    "code": "def _get_regions(self):\n        if self._specs_in[_REGIONS_STR] == 'all':\n            return [_get_all_objs_of_type(\n                Region, getattr(self._obj_lib, 'regions', self._obj_lib)\n            )]\n        else:\n            return [set(self._specs_in[_REGIONS_STR])]",
    "docstring": "Get the requested regions."
  },
  {
    "code": "def slanted_triangular(max_rate, num_steps, cut_frac=0.1, ratio=32, decay=1, t=0.0):\n    cut = int(num_steps * cut_frac)\n    while True:\n        t += 1\n        if t < cut:\n            p = t / cut\n        else:\n            p = 1 - ((t - cut) / (cut * (1 / cut_frac - 1)))\n        learn_rate = max_rate * (1 + p * (ratio - 1)) * (1 / ratio)\n        yield learn_rate",
    "docstring": "Yield an infinite series of values according to Howard and Ruder's\n    \"slanted triangular learning rate\" schedule."
  },
  {
    "code": "def loadDict(filename):\n    filename = os.path.expanduser(filename)\n    if not splitext(filename)[1]: filename += \".bpickle\"\n    f = None\n    try:\n        f = open(filename, \"rb\")\n        varH = cPickle.load(f)\n    finally:\n        if f: f.close()\n    return varH",
    "docstring": "Return the variables pickled pickled into `filename` with `saveVars`\n    as a dict."
  },
  {
    "code": "def movies_box_office(self, **kwargs):\n        path = self._get_path('movies_box_office')\n        response = self._GET(path, kwargs)\n        self._set_attrs_to_values(response)\n        return response",
    "docstring": "Gets the top box office earning movies from the API.\n           Sorted by most recent weekend gross ticket sales.\n\n        Args:\n          limit (optional): limits the number of movies returned, default=10\n          country (optional): localized data for selected country, default=\"us\"\n\n        Returns:\n          A dict respresentation of the JSON returned from the API."
  },
  {
    "code": "def eradicate_pgroup(self, pgroup, **kwargs):\n        eradicate = {\"eradicate\": True}\n        eradicate.update(kwargs)\n        return self._request(\"DELETE\", \"pgroup/{0}\".format(pgroup), eradicate)",
    "docstring": "Eradicate a destroyed pgroup.\n\n        :param pgroup: Name of pgroup to be eradicated.\n        :type pgroup: str\n        :param \\*\\*kwargs: See the REST API Guide on your array for the\n                           documentation on the request:\n                           **DELETE pgroup/:pgroup**\n        :type \\*\\*kwargs: optional\n\n        :returns: A dictionary mapping \"name\" to pgroup.\n        :rtype: ResponseDict\n\n        .. note::\n\n            Requires use of REST API 1.2 or later."
  },
  {
    "code": "def run(self, instream=sys.stdin):\n        sys.stdout.write(self.prompt)\n        sys.stdout.flush()\n        while True:\n            line = instream.readline()\n            try:\n                self.exec_cmd(line)\n            except Exception as e:\n                self.errfun(e)\n            sys.stdout.write(self.prompt)\n            sys.stdout.flush()",
    "docstring": "Runs the CLI, reading from sys.stdin by default"
  },
  {
    "code": "def node_to_complex_fault_geometry(node):\n    assert \"complexFaultGeometry\" in node.tag\n    intermediate_edges = []\n    for subnode in node.nodes:\n        if \"faultTopEdge\" in subnode.tag:\n            top_edge = linestring_node_to_line(subnode.nodes[0],\n                                               with_depth=True)\n        elif \"intermediateEdge\" in subnode.tag:\n            int_edge = linestring_node_to_line(subnode.nodes[0],\n                                               with_depth=True)\n            intermediate_edges.append(int_edge)\n        elif \"faultBottomEdge\" in subnode.tag:\n            bottom_edge = linestring_node_to_line(subnode.nodes[0],\n                                                  with_depth=True)\n        else:\n            pass\n    return [top_edge] + intermediate_edges + [bottom_edge]",
    "docstring": "Reads a complex fault geometry node and returns an"
  },
  {
    "code": "def format(self, record: logging.LogRecord) -> str:\n        if platform.system() != 'Linux':\n            return super().format(record)\n        record.msg = (\n            self.STYLE[record.levelname] + record.msg + self.STYLE['END'])\n        record.levelname = (\n            self.STYLE['LEVEL'] + record.levelname + self.STYLE['END'])\n        return super().format(record)",
    "docstring": "Format log records to produce colored messages.\n\n        :param record: log record\n        :return: log message"
  },
  {
    "code": "def number_of_states(dtrajs, only_used = False):\n    r\n    dtrajs = _ensure_dtraj_list(dtrajs)\n    if only_used:\n        bc = count_states(dtrajs)\n        return np.count_nonzero(bc)\n    else:\n        imax = 0\n        for dtraj in dtrajs:\n            imax = max(imax, np.max(dtraj))\n        return imax+1",
    "docstring": "r\"\"\"returns the number of states in the given trajectories.\n\n    Parameters\n    ----------\n    dtraj : array_like or list of array_like\n        Discretized trajectory or list of discretized trajectories\n    only_used = False : boolean\n        If False, will return max+1, where max is the largest index used.\n        If True, will return the number of states that occur at least once."
  },
  {
    "code": "def add_exception(self, exception, stack, remote=False):\n        self._check_ended()\n        self.add_fault_flag()\n        if hasattr(exception, '_recorded'):\n            setattr(self, 'cause', getattr(exception, '_cause_id'))\n            return\n        exceptions = []\n        exceptions.append(Throwable(exception, stack, remote))\n        self.cause['exceptions'] = exceptions\n        self.cause['working_directory'] = os.getcwd()",
    "docstring": "Add an exception to trace entities.\n\n        :param Exception exception: the catched exception.\n        :param list stack: the output from python built-in\n            `traceback.extract_stack()`.\n        :param bool remote: If False it means it's a client error\n            instead of a downstream service."
  },
  {
    "code": "def num_unused_cpus(thresh=10):\n    import psutil\n    cpu_usage = psutil.cpu_percent(percpu=True)\n    return sum([p < thresh for p in cpu_usage])",
    "docstring": "Returns the number of cpus with utilization less than `thresh` percent"
  },
  {
    "code": "def stft(func=None, **kwparams):\n  from numpy.fft import fft, ifft\n  return stft.base(transform=fft, inverse_transform=ifft)(func, **kwparams)",
    "docstring": "Short Time Fourier Transform for complex data.\n\n  Same to the default STFT strategy, but with new defaults. This is the same\n  to:\n\n  .. code-block:: python\n\n    stft.base(transform=numpy.fft.fft, inverse_transform=numpy.fft.ifft)\n\n  See ``stft.base`` docs for more."
  },
  {
    "code": "def get_share_file (filename, devel_dir=None):\n    paths = [get_share_dir()]\n    if devel_dir is not None:\n        paths.insert(0, devel_dir)\n    for path in paths:\n        fullpath = os.path.join(path, filename)\n        if os.path.isfile(fullpath):\n            return fullpath\n    msg = \"%s not found in %s; check your installation\" % (filename, paths)\n    raise ValueError(msg)",
    "docstring": "Return a filename in the share directory.\n    @param devel_dir: directory to search when developing\n    @ptype devel_dir: string\n    @param filename: filename to search for\n    @ptype filename: string\n    @return: the found filename or None\n    @rtype: string\n    @raises: ValueError if not found"
  },
  {
    "code": "def _raise_exception(self, eobj, edata=None):\n        _, _, tbobj = sys.exc_info()\n        if edata:\n            emsg = self._format_msg(eobj[\"msg\"], edata)\n            _rwtb(eobj[\"type\"], emsg, tbobj)\n        else:\n            _rwtb(eobj[\"type\"], eobj[\"msg\"], tbobj)",
    "docstring": "Raise exception by name."
  },
  {
    "code": "def set_empty_text(self):\n        self.buffer.insert_with_tags_by_name(\n            self.buffer.get_start_iter(),\n            self.empty_text, 'empty-text')",
    "docstring": "Display the empty text"
  },
  {
    "code": "def insert(self, state, token):\n        if token == EndSymbol():\n            return self[state][EndSymbol()]\n        from pydsl.check import check\n        symbol_list = [x for x in self[state] if isinstance(x, TerminalSymbol) and check(x.gd, [token])]\n        if not symbol_list:\n            return {\"action\":\"Fail\"}\n        if len(symbol_list) > 1:\n            raise Exception(\"Multiple symbols matches input\")\n        symbol = symbol_list[0]\n        return self[state][symbol]",
    "docstring": "change internal state, return action"
  },
  {
    "code": "def accumulate(self, axis: AxisIdentifier) -> HistogramBase:\n        new_one = self.copy()\n        axis_id = self._get_axis(axis)\n        new_one._frequencies = np.cumsum(new_one.frequencies, axis_id[0])\n        return new_one",
    "docstring": "Calculate cumulative frequencies along a certain axis.\n\n        Returns\n        -------\n        new_hist: Histogram of the same type & size"
  },
  {
    "code": "def version(self, bundle: str, date: dt.datetime) -> models.Version:\n        return (self.Version.query\n                            .join(models.Version.bundle)\n                            .filter(models.Bundle.name == bundle,\n                                    models.Version.created_at == date)\n                            .first())",
    "docstring": "Fetch a version from the store."
  },
  {
    "code": "def clear_all_flair(self):\n        csv = [{'user': x['user']} for x in self.get_flair_list(limit=None)]\n        if csv:\n            return self.set_flair_csv(csv)\n        else:\n            return",
    "docstring": "Remove all user flair on this subreddit.\n\n        :returns: The json response from the server when there is flair to\n            clear, otherwise returns None."
  },
  {
    "code": "def contains(self, value):\n        str_value = StringConverter.to_nullable_string(value)\n        for element in self:\n            str_element = StringConverter.to_string(element)\n            if str_value == None and str_element == None:\n                return True\n            if str_value == None or str_element == None:\n                continue\n            if str_value == str_element:\n                return True\n        return False",
    "docstring": "Checks if this array contains a value.\n        The check uses direct comparison between elements and the specified value.\n\n        :param value: a value to be checked\n\n        :return: true if this array contains the value or false otherwise."
  },
  {
    "code": "def unit_system_id(self):\n        if self._unit_system_id is None:\n            hash_data = bytearray()\n            for k, v in sorted(self.lut.items()):\n                hash_data.extend(k.encode(\"utf8\"))\n                hash_data.extend(repr(v).encode(\"utf8\"))\n            m = md5()\n            m.update(hash_data)\n            self._unit_system_id = str(m.hexdigest())\n        return self._unit_system_id",
    "docstring": "This is a unique identifier for the unit registry created\n        from a FNV hash. It is needed to register a dataset's code\n        unit system in the unit system registry."
  },
  {
    "code": "def prepare_gag_lsm(self, lsm_precip_data_var, lsm_precip_type, interpolation_type=None):\n        if self.l2g is None:\n            raise ValueError(\"LSM converter not loaded ...\")\n        for unif_precip_card in self.UNIFORM_PRECIP_CARDS:\n            self.project_manager.deleteCard(unif_precip_card, self.db_session)\n        with tmp_chdir(self.project_manager.project_directory):\n            out_gage_file = '{0}.gag'.format(self.project_manager.name)\n            self.l2g.lsm_precip_to_gssha_precip_gage(out_gage_file,\n                                                     lsm_data_var=lsm_precip_data_var,\n                                                     precip_type=lsm_precip_type)\n            self._update_simulation_end_from_lsm()\n            self.set_simulation_duration(self.simulation_end-self.simulation_start)\n            self.add_precip_file(out_gage_file, interpolation_type)\n            self.l2g.xd.close()",
    "docstring": "Prepares Gage output for GSSHA simulation\n\n        Parameters:\n            lsm_precip_data_var(list or str): String of name for precipitation variable name or list of precip variable names.  See: :func:`~gsshapy.grid.GRIDtoGSSHA.lsm_precip_to_gssha_precip_gage`.\n            lsm_precip_type(str): Type of precipitation. See: :func:`~gsshapy.grid.GRIDtoGSSHA.lsm_precip_to_gssha_precip_gage`.\n            interpolation_type(str): Type of interpolation for LSM precipitation. Can be \"INV_DISTANCE\" or \"THIESSEN\". Default is \"THIESSEN\"."
  },
  {
    "code": "def __get_supported_file_types_string(self):\n        languages = [\"All Files (*)\"]\n        for language in self.__languages_model.languages:\n            languages.append(\"{0} Files ({1})\".format(language.name,\n                                                      \" \".join(language.extensions.split(\"|\")).replace(\"\\\\\", \"*\")))\n        return \";;\".join(languages)",
    "docstring": "Returns the supported file types dialog string."
  },
  {
    "code": "def extractOne(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):\n    best_list = extractWithoutOrder(query, choices, processor, scorer, score_cutoff)\n    try:\n        return max(best_list, key=lambda i: i[1])\n    except ValueError:\n        return None",
    "docstring": "Find the single best match above a score in a list of choices.\n\n    This is a convenience method which returns the single best choice.\n    See extract() for the full arguments list.\n\n    Args:\n        query: A string to match against\n        choices: A list or dictionary of choices, suitable for use with\n            extract().\n        processor: Optional function for transforming choices before matching.\n            See extract().\n        scorer: Scoring function for extract().\n        score_cutoff: Optional argument for score threshold. If the best\n            match is found, but it is not greater than this number, then\n            return None anyway (\"not a good enough match\").  Defaults to 0.\n\n    Returns:\n        A tuple containing a single match and its score, if a match\n        was found that was above score_cutoff. Otherwise, returns None."
  },
  {
    "code": "def path_list(self, sep=os.pathsep):\n        from pathlib import Path\n        return [ Path(pathstr) for pathstr in self.split(sep) ]",
    "docstring": "Return list of Path objects."
  },
  {
    "code": "async def zrange(self, name, start, end, desc=False, withscores=False,\n                     score_cast_func=float):\n        if desc:\n            return await self.zrevrange(name, start, end, withscores,\n                                        score_cast_func)\n        pieces = ['ZRANGE', name, start, end]\n        if withscores:\n            pieces.append(b('WITHSCORES'))\n        options = {\n            'withscores': withscores,\n            'score_cast_func': score_cast_func\n        }\n        return await self.execute_command(*pieces, **options)",
    "docstring": "Return a range of values from sorted set ``name`` between\n        ``start`` and ``end`` sorted in ascending order.\n\n        ``start`` and ``end`` can be negative, indicating the end of the range.\n\n        ``desc`` a boolean indicating whether to sort the results descendingly\n\n        ``withscores`` indicates to return the scores along with the values.\n        The return type is a list of (value, score) pairs\n\n        ``score_cast_func`` a callable used to cast the score return value"
  },
  {
    "code": "def connect_edges(graph):\n    paths = []\n    for start, end in graph.array(graph.kdims):\n        start_ds = graph.nodes[:, :, start]\n        end_ds = graph.nodes[:, :, end]\n        if not len(start_ds) or not len(end_ds):\n            raise ValueError('Could not find node positions for all edges')\n        start = start_ds.array(start_ds.kdims[:2])\n        end = end_ds.array(end_ds.kdims[:2])\n        paths.append(np.array([start[0], end[0]]))\n    return paths",
    "docstring": "Given a Graph element containing abstract edges compute edge\n    segments directly connecting the source and target nodes.  This\n    operation just uses internal HoloViews operations and will be a\n    lot slower than the pandas equivalent."
  },
  {
    "code": "def delete_duplicates(seq):\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]",
    "docstring": "Remove duplicates from an iterable, preserving the order.\n\n    Args:\n        seq: Iterable of various type.\n\n    Returns:\n        list: List of unique objects."
  },
  {
    "code": "def emit_after(self, event: str) -> Callable:\n        def outer(func):\n            @wraps(func)\n            def wrapper(*args, **kwargs):\n                returned = func(*args, **kwargs)\n                self.emit(event)\n                return returned\n            return wrapper\n        return outer",
    "docstring": "Decorator that emits events after the function is completed.\n\n        :param event: Name of the event.\n        :type event: str\n\n        :return: Callable\n\n        .. note:\n            This plainly just calls functions without passing params into the\n            subscribed callables. This is great if you want to do some kind\n            of post processing without the callable requiring information\n            before doing so."
  },
  {
    "code": "def _cldf2lexstat(\n        dataset,\n        segments='segments',\n        transcription='value',\n        row='parameter_id',\n        col='language_id'):\n    D = _cldf2wld(dataset)\n    return lingpy.LexStat(D, segments=segments, transcription=transcription, row=row, col=col)",
    "docstring": "Read LexStat object from cldf dataset."
  },
  {
    "code": "def auc(y_true, y_pred, round=True):\n    y_true, y_pred = _mask_value_nan(y_true, y_pred)\n    if round:\n        y_true = y_true.round()\n    if len(y_true) == 0 or len(np.unique(y_true)) < 2:\n        return np.nan\n    return skm.roc_auc_score(y_true, y_pred)",
    "docstring": "Area under the ROC curve"
  },
  {
    "code": "def notify_systemd():\n    try:\n        import systemd.daemon\n    except ImportError:\n        if salt.utils.path.which('systemd-notify') \\\n                and systemd_notify_call('--booted'):\n            notify_socket = os.getenv('NOTIFY_SOCKET')\n            if notify_socket:\n                if notify_socket.startswith('@'):\n                    notify_socket = '\\0{0}'.format(notify_socket[1:])\n                try:\n                    sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)\n                    sock.connect(notify_socket)\n                    sock.sendall('READY=1'.encode())\n                    sock.close()\n                except socket.error:\n                    return systemd_notify_call('--ready')\n                return True\n        return False\n    if systemd.daemon.booted():\n        try:\n            return systemd.daemon.notify('READY=1')\n        except SystemError:\n            pass",
    "docstring": "Notify systemd that this process has started"
  },
  {
    "code": "def unconsumed_ranges(self):\n        res = IntervalTree()\n        prev = None\n        ranges = sorted([x for x in self.range_set], key=lambda x: x.begin)\n        for rng in ranges:\n            if prev is None:\n                prev = rng\n                continue\n            res.add(Interval(prev.end, rng.begin))\n            prev = rng\n        if len(self.range_set[self.tell()]) != 1:\n            res.add(Interval(prev.end, self.tell()))\n        return res",
    "docstring": "Return an IntervalTree of unconsumed ranges, of the format\n        (start, end] with the end value not being included"
  },
  {
    "code": "def _compute_hparam_info_from_values(self, name, values):\n    result = api_pb2.HParamInfo(name=name, type=api_pb2.DATA_TYPE_UNSET)\n    distinct_values = set(\n        _protobuf_value_to_string(v) for v in values if _protobuf_value_type(v))\n    for v in values:\n      v_type = _protobuf_value_type(v)\n      if not v_type:\n        continue\n      if result.type == api_pb2.DATA_TYPE_UNSET:\n        result.type = v_type\n      elif result.type != v_type:\n        result.type = api_pb2.DATA_TYPE_STRING\n      if result.type == api_pb2.DATA_TYPE_STRING:\n        break\n    if result.type == api_pb2.DATA_TYPE_UNSET:\n      return None\n    if (result.type == api_pb2.DATA_TYPE_STRING\n        and len(distinct_values) <= self._max_domain_discrete_len):\n      result.domain_discrete.extend(distinct_values)\n    return result",
    "docstring": "Builds an HParamInfo message from the hparam name and list of values.\n\n    Args:\n      name: string. The hparam name.\n      values: list of google.protobuf.Value messages. The list of values for the\n        hparam.\n\n    Returns:\n      An api_pb2.HParamInfo message."
  },
  {
    "code": "def do_p(self, arg):\n        try:\n            self.message(bdb.safe_repr(self._getval(arg)))\n        except Exception:\n            pass",
    "docstring": "p expression\n        Print the value of the expression."
  },
  {
    "code": "def get_default_ca_certs():\n    if not hasattr(get_default_ca_certs, '_path'):\n        for path in get_default_ca_cert_paths():\n            if os.path.exists(path):\n                get_default_ca_certs._path = path\n                break\n        else:\n            get_default_ca_certs._path = None\n    return get_default_ca_certs._path",
    "docstring": "Try to find out system path with ca certificates. This path is cached and\n    returned. If no path is found out, None is returned."
  },
  {
    "code": "def standard_lstm_lm_200(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(),\n                         root=os.path.join(get_home_dir(), 'models'), **kwargs):\n    r\n    predefined_args = {'embed_size': 200,\n                       'hidden_size': 200,\n                       'mode': 'lstm',\n                       'num_layers': 2,\n                       'tie_weights': True,\n                       'dropout': 0.2}\n    mutable_args = ['dropout']\n    assert all((k not in kwargs or k in mutable_args) for k in predefined_args), \\\n           'Cannot override predefined model settings.'\n    predefined_args.update(kwargs)\n    return _get_rnn_model(StandardRNN, 'standard_lstm_lm_200', dataset_name, vocab, pretrained,\n                          ctx, root, **predefined_args)",
    "docstring": "r\"\"\"Standard 2-layer LSTM language model with tied embedding and output weights.\n\n    Both embedding and hidden dimensions are 200.\n\n    Parameters\n    ----------\n    dataset_name : str or None, default None\n        The dataset name on which the pre-trained model is trained.\n        Options are 'wikitext-2'. If specified, then the returned vocabulary is extracted from\n        the training set of the dataset.\n        If None, then vocab is required, for specifying embedding weight size, and is directly\n        returned.\n        The pre-trained model achieves 108.25/102.26 ppl on Val and Test of wikitext-2 respectively.\n    vocab : gluonnlp.Vocab or None, default None\n        Vocabulary object to be used with the language model.\n        Required when dataset_name is not specified.\n    pretrained : bool, default False\n        Whether to load the pre-trained weights for model.\n    ctx : Context, default CPU\n        The context in which to load the pre-trained weights.\n    root : str, default '$MXNET_HOME/models'\n        Location for keeping the model parameters.\n        MXNET_HOME defaults to '~/.mxnet'.\n\n    Returns\n    -------\n    gluon.Block, gluonnlp.Vocab"
  },
  {
    "code": "def append(self, key, value=None, dir=False, ttl=None, timeout=None):\n        return self.adapter.append(key, value, dir=dir, ttl=ttl,\n                                   timeout=timeout)",
    "docstring": "Creates a new automatically increasing key in the given directory\n        key."
  },
  {
    "code": "def authnkey(self) -> dict:\n        return {k: self._pubkey[k] for k in self._pubkey if self._pubkey[k].authn}",
    "docstring": "Accessor for public keys marked as authentication keys, by identifier."
  },
  {
    "code": "def compute_eigenvalues(in_prefix, out_prefix):\n    with open(out_prefix + \".parameters\", \"w\") as o_file:\n        print >>o_file, \"genotypename:    \" + in_prefix + \".bed\"\n        print >>o_file, \"snpname:         \" + in_prefix + \".bim\"\n        print >>o_file, \"indivname:       \" + in_prefix + \".fam\"\n        print >>o_file, \"evecoutname:     \" + out_prefix + \".evec.txt\"\n        print >>o_file, \"evaloutname:     \" + out_prefix + \".eval.txt\"\n        print >>o_file, \"numoutlieriter:  0\"\n        print >>o_file, \"altnormstyle:    NO\"\n    command = [\"smartpca\", \"-p\", out_prefix + \".parameters\"]\n    runCommand(command)",
    "docstring": "Computes the Eigenvalues using smartpca from Eigensoft.\n\n    :param in_prefix: the prefix of the input files.\n    :param out_prefix: the prefix of the output files.\n\n    :type in_prefix: str\n    :type out_prefix: str\n\n    Creates a \"parameter file\" used by smartpca and runs it."
  },
  {
    "code": "def get_hooks(self):\n    if self.__hooks is None and self.hooks_class_name is not None:\n      hooks_class = util.for_name(self.hooks_class_name)\n      if not isinstance(hooks_class, type):\n        raise ValueError(\"hooks_class_name must refer to a class, got %s\" %\n                         type(hooks_class).__name__)\n      if not issubclass(hooks_class, hooks.Hooks):\n        raise ValueError(\n            \"hooks_class_name must refer to a hooks.Hooks subclass\")\n      self.__hooks = hooks_class(self)\n    return self.__hooks",
    "docstring": "Returns a hooks.Hooks class or None if no hooks class has been set."
  },
  {
    "code": "def install_module(\n    self, target=None, package_manager=None, \n    install_optional=False, production_only=False, force=False, \n    node_paths=None, frozen_lockfile=None, workunit_name=None, workunit_labels=None):\n    package_manager = package_manager or self.get_package_manager(target=target)\n    command = package_manager.install_module(\n      install_optional=install_optional,\n      force=force,\n      production_only=production_only,\n      node_paths=node_paths,\n      frozen_lockfile=frozen_lockfile\n    )\n    return self._execute_command(\n      command, workunit_name=workunit_name, workunit_labels=workunit_labels)",
    "docstring": "Installs node module using requested package_manager."
  },
  {
    "code": "def create_table(self, table_name, obj=None, **kwargs):\n        return self.client.create_table(\n            table_name, obj=obj, database=self.name, **kwargs\n        )",
    "docstring": "Dispatch to ImpalaClient.create_table. See that function's docstring\n        for more"
  },
  {
    "code": "def _set_timeouts(self, timeouts):\n        (send_timeout, recv_timeout) = (None, None)\n        try:\n            (send_timeout, recv_timeout) = timeouts\n        except TypeError:\n            raise EndpointError(\n                '`timeouts` must be a pair of numbers (2, 3) which represent '\n                'the timeout values for send and receive respectively')\n        if send_timeout is not None:\n            self.socket.set_int_option(\n                nanomsg.SOL_SOCKET, nanomsg.SNDTIMEO, send_timeout)\n        if recv_timeout is not None:\n            self.socket.set_int_option(\n                nanomsg.SOL_SOCKET, nanomsg.RCVTIMEO, recv_timeout)",
    "docstring": "Set socket timeouts for send and receive respectively"
  },
  {
    "code": "def create_roadmap_doc(dat, opFile):\n    op = format_title('Roadmap for AIKIF')\n    for h1 in dat['projects']:\n        op += format_h1(h1)\n        if dat[h1] is None:\n            op += '(No details)\\n'\n        else:\n            for h2 in dat[h1]:\n                op += '\\n' + format_h2(h2)\n                if dat[h1][h2] is None:\n                    op += '(blank text)\\n'\n                else:\n                    for txt in dat[h1][h2]:\n                        op += '  - ' + txt + '\\n'\n        op += '\\n'\n    with open(opFile, 'w') as f:\n        f.write(op)",
    "docstring": "takes a dictionary read from a yaml file and converts\n    it to the roadmap documentation"
  },
  {
    "code": "def join_struct_arrays(arrays):\n    sizes = np.array([a.itemsize for a in arrays])\n    offsets = np.r_[0, sizes.cumsum()]\n    shape = arrays[0].shape\n    joint = np.empty(shape + (offsets[-1],), dtype=np.uint8)\n    for a, size, offset in zip(arrays, sizes, offsets):\n        joint[...,offset:offset+size] = np.atleast_1d(a).view(np.uint8).reshape(shape + (size,))\n    dtype = sum((a.dtype.descr for a in arrays), [])\n    return joint.ravel().view(dtype)",
    "docstring": "Takes a list of possibly structured arrays, concatenates their\n    dtypes, and returns one big array with that dtype. Does the\n    inverse of ``separate_struct_array``.\n\n    :param list arrays: List of ``np.ndarray``s"
  },
  {
    "code": "def estimate_band_connection(prev_eigvecs, eigvecs, prev_band_order):\n    metric = np.abs(np.dot(prev_eigvecs.conjugate().T, eigvecs))\n    connection_order = []\n    for overlaps in metric:\n        maxval = 0\n        for i in reversed(range(len(metric))):\n            val = overlaps[i]\n            if i in connection_order:\n                continue\n            if val > maxval:\n                maxval = val\n                maxindex = i\n        connection_order.append(maxindex)\n    band_order = [connection_order[x] for x in prev_band_order]\n    return band_order",
    "docstring": "A function to order the phonon eigenvectors taken from phonopy"
  },
  {
    "code": "def write(self, datapoint):\n        if not isinstance(datapoint, DataPoint):\n            raise TypeError(\"First argument must be a DataPoint object\")\n        datapoint._stream_id = self.get_stream_id()\n        if self._cached_data is not None and datapoint.get_data_type() is None:\n            datapoint._data_type = self.get_data_type()\n        self._conn.post(\"/ws/DataPoint/{}\".format(self.get_stream_id()), datapoint.to_xml())",
    "docstring": "Write some raw data to a stream using the DataPoint API\n\n        This method will mutate the datapoint provided to populate it with information\n        available from the stream as it is available (but without making any new HTTP\n        requests).  For instance, we will add in information about the stream data\n        type if it is available so that proper type conversion happens.\n\n        Values already set on the datapoint will not be overridden (except for path)\n\n        :param DataPoint datapoint: The :class:`.DataPoint` that should be written to Device Cloud"
  },
  {
    "code": "def _resource(resource, pretty: bool = None, **data):\n    data = clean_data(data)\n    ctx = click.get_current_context()\n    if ctx.obj.get(\"env_prefix\"):\n        data[\"env_prefix\"] = ctx.obj[\"env_prefix\"]\n    rsp = resource(**data)\n    dump = partial(json.dumps, indent=4) if pretty else partial(json.dumps)\n    click.echo(dump(rsp))",
    "docstring": "The callback func that will be hooked to the generic resource commands"
  },
  {
    "code": "def ascolumn(x, dtype = None):\r\n    x = asarray(x, dtype)\r\n    return x if len(x.shape) >= 2 else x.reshape(len(x),1)",
    "docstring": "Convert ``x`` into a ``column``-type ``numpy.ndarray``."
  },
  {
    "code": "def get_next(self):\n        self._counter_curr += 1\n        suffix = self._separator + \"%s\" % str(self._counter_curr)\n        return self._base_name + suffix",
    "docstring": "Return next name."
  },
  {
    "code": "def insert(self, rectangle):\n        rectangle = np.asanyarray(rectangle, dtype=np.float64)\n        for child in self.child:\n            if child is not None:\n                attempt = child.insert(rectangle)\n                if attempt is not None:\n                    return attempt\n        if self.occupied:\n            return None\n        size_test = self.extents - rectangle\n        if np.any(size_test < -tol.zero):\n            return None\n        self.occupied = True\n        if np.all(size_test < tol.zero):\n            return self.bounds[0:2]\n        vertical = size_test[0] > size_test[1]\n        length = rectangle[int(not vertical)]\n        child_bounds = self.split(length, vertical)\n        self.child[0] = RectangleBin(bounds=child_bounds[0])\n        self.child[1] = RectangleBin(bounds=child_bounds[1])\n        return self.child[0].insert(rectangle)",
    "docstring": "Insert a rectangle into the bin.\n\n        Parameters\n        -------------\n        rectangle: (2,) float, size of rectangle to insert"
  },
  {
    "code": "def make_int(value, missing=-1):\n    if isinstance(value, six.string_types):\n        if not value.strip():\n            return missing\n    elif value is None:\n        return missing\n    return int(value)",
    "docstring": "Convert string value to long, '' to missing"
  },
  {
    "code": "def separator(self, *args, **kwargs):\n        levelOverride = kwargs.get('level') or self._lastlevel\n        self._log(levelOverride, '', 'separator', args, kwargs)",
    "docstring": "Prints a separator to the log. This can be used to separate blocks of log messages.\n\n        The separator will default its log level to the level of the last message printed unless\n        specified with the level= kwarg.\n\n        The length and type of the separator string is determined\n        by the current style. See ``setStyle``"
  },
  {
    "code": "def create_paired_device(self, dev_id, agent_path,\n                             capability, cb_notify_device, cb_notify_error):\n        return self._interface.CreatePairedDevice(dev_id,\n                                                  agent_path,\n                                                  capability,\n                                                  reply_handler=cb_notify_device,\n                                                  error_handler=cb_notify_error)",
    "docstring": "Creates a new object path for a remote device. This\n        method will connect to the remote device and retrieve\n        all SDP records and then initiate the pairing.\n\n        If a previously :py:meth:`create_device` was used\n        successfully, this method will only initiate the pairing.\n\n        Compared to :py:meth:`create_device` this method will\n        fail if the pairing already exists, but not if the object\n        path already has been created. This allows applications\n        to use :py:meth:`create_device` first and then, if needed,\n        use :py:meth:`create_paired_device` to initiate pairing.\n\n        The agent object path is assumed to reside within the\n        process (D-Bus connection instance) that calls this\n        method. No separate registration procedure is needed\n        for it and it gets automatically released once the\n        pairing operation is complete.\n\n        :param str dev_id: New device MAC address create\n            e.g., '11:22:33:44:55:66'\n        :param str agent_path: Path used when creating the\n            bluetooth agent e.g., '/test/agent'\n        :param str capability: Pairing agent capability\n            e.g., 'DisplayYesNo', etc\n        :param func cb_notify_device: Callback on success.  The\n            callback is called with the new device's object\n            path as an argument.\n        :param func cb_notify_error: Callback on error.  The\n            callback is called with the error reason.\n        :return:\n        :raises dbus.Exception: org.bluez.Error.InvalidArguments\n        :raises dbus.Exception: org.bluez.Error.Failed"
  },
  {
    "code": "def get_request_headers(self, *args, **kwds):\n        if self.request_headers:\n            return self._unpack_headers(self.request_headers)",
    "docstring": "A convenience method for obtaining the headers that were sent to the\n        S3 server.\n\n        The AWS S3 API depends upon setting headers. This method is provided as\n        a convenience for debugging issues with the S3 communications."
  },
  {
    "code": "def _pixel_to_tile(x: float, y: float) -> Tuple[float, float]:\n    xy = tcod.ffi.new(\"double[2]\", (x, y))\n    tcod.lib.TCOD_sys_pixel_to_tile(xy, xy + 1)\n    return xy[0], xy[1]",
    "docstring": "Convert pixel coordinates to tile coordinates."
  },
  {
    "code": "def post_slack_message(message=None, channel=None, username=None, icon_emoji=None):\n    LOG.debug('Slack Channel: %s\\nSlack Message: %s', channel, message)\n    slack = slacker.Slacker(SLACK_TOKEN)\n    try:\n        slack.chat.post_message(channel=channel, text=message, username=username, icon_emoji=icon_emoji)\n        LOG.info('Message posted to %s', channel)\n    except slacker.Error:\n        LOG.info(\"error posted message to %s\", channel)",
    "docstring": "Format the message and post to the appropriate slack channel.\n\n    Args:\n        message (str): Message to post to slack\n        channel (str): Desired channel. Must start with #"
  },
  {
    "code": "def getAllReadGroupSets(self):\n        for dataset in self.getAllDatasets():\n            iterator = self._client.search_read_group_sets(\n                dataset_id=dataset.id)\n            for readGroupSet in iterator:\n                yield readGroupSet",
    "docstring": "Returns all readgroup sets on the server."
  },
  {
    "code": "def add_field_like(self, name, like_array):\n        new_shape = list(like_array.shape)\n        new_shape[0] = len(self)\n        new_data = ma.empty(new_shape, like_array.dtype)\n        new_data.mask = True\n        self.add_field(name, new_data)",
    "docstring": "Add a new field to the Datamat with the dtype of the\n        like_array and the shape of the like_array except for the first\n        dimension which will be instead the field-length of this Datamat."
  },
  {
    "code": "def _make_ssh_forward_server(self, remote_address, local_bind_address):\n        _Handler = self._make_ssh_forward_handler_class(remote_address)\n        try:\n            if isinstance(local_bind_address, string_types):\n                forward_maker_class = self._make_unix_ssh_forward_server_class\n            else:\n                forward_maker_class = self._make_ssh_forward_server_class\n            _Server = forward_maker_class(remote_address)\n            ssh_forward_server = _Server(\n                local_bind_address,\n                _Handler,\n                logger=self.logger,\n            )\n            if ssh_forward_server:\n                ssh_forward_server.daemon_threads = self.daemon_forward_servers\n                self._server_list.append(ssh_forward_server)\n                self.tunnel_is_up[ssh_forward_server.server_address] = False\n            else:\n                self._raise(\n                    BaseSSHTunnelForwarderError,\n                    'Problem setting up ssh {0} <> {1} forwarder. You can '\n                    'suppress this exception by using the `mute_exceptions`'\n                    'argument'.format(address_to_str(local_bind_address),\n                                      address_to_str(remote_address))\n                )\n        except IOError:\n            self._raise(\n                BaseSSHTunnelForwarderError,\n                \"Couldn't open tunnel {0} <> {1} might be in use or \"\n                \"destination not reachable\".format(\n                    address_to_str(local_bind_address),\n                    address_to_str(remote_address)\n                )\n            )",
    "docstring": "Make SSH forward proxy Server class"
  },
  {
    "code": "def create(self, neighbors):\n        data = {'neighbors': neighbors}\n        return super(ApiV4Neighbor, self).post('api/v4/neighbor/', data)",
    "docstring": "Method to create neighbors\n\n        :param neighbors: List containing neighbors desired to be created on database\n        :return: None"
  },
  {
    "code": "def unescape(s, unicode_action=\"replace\"):\n    import HTMLParser\n    hp = HTMLParser.HTMLParser()\n    s = hp.unescape(s)\n    s = s.encode('ascii', unicode_action)\n    s = s.replace(\"\\n\", \"\").strip()\n    return s",
    "docstring": "Unescape HTML strings, and convert &amp; etc."
  },
  {
    "code": "def class_balancing_sample_weights(y):\n        h = np.bincount(y)\n        cls_weight = 1.0 / (h.astype(float) * len(np.nonzero(h)[0]))\n        cls_weight[np.isnan(cls_weight)] = 0.0\n        sample_weight = cls_weight[y]\n        return sample_weight",
    "docstring": "Compute sample weight given an array of sample classes. The weights\n        are assigned on a per-class basis and the per-class weights are\n        inversely proportional to their frequency.\n\n        Parameters\n        ----------\n        y: NumPy array, 1D dtype=int\n            sample classes, values must be 0 or positive\n\n        Returns\n        -------\n        NumPy array, 1D dtype=float\n            per sample weight array"
  },
  {
    "code": "def ucnstring_to_unicode(ucn_string):\n    ucn_string = ucnstring_to_python(ucn_string).decode('utf-8')\n    assert isinstance(ucn_string, text_type)\n    return ucn_string",
    "docstring": "Return ucnstring as Unicode."
  },
  {
    "code": "def start(sync_event_source, loop=None):\n    if not loop:\n        loop = asyncio.get_event_loop()\n    event_source = asyncio.Queue(loop=loop)\n    bridge = threading.Thread(target=_multiprocessing_to_asyncio,\n                              args=(sync_event_source, event_source, loop),\n                              daemon=True)\n    bridge.start()\n    app = init_app(event_source, loop=loop)\n    aiohttp.web.run_app(app,\n                        host=config['wsserver']['host'],\n                        port=config['wsserver']['port'])",
    "docstring": "Create and start the WebSocket server."
  },
  {
    "code": "def list_event_sources(self):\n        path = '/archive/{}/events/sources'.format(self._instance)\n        response = self._client.get_proto(path=path)\n        message = archive_pb2.EventSourceInfo()\n        message.ParseFromString(response.content)\n        sources = getattr(message, 'source')\n        return iter(sources)",
    "docstring": "Returns the existing event sources.\n\n        :rtype: ~collections.Iterable[str]"
  },
  {
    "code": "def _compute(self):\n        src_path = self.ctx.src_path\n        if not src_path.exists:\n            return NONE\n        if src_path.is_null:\n            return None\n        try:\n            if self.parse:\n                value = self.parse(src_path)\n            else:\n                value = self._parse(src_path)\n            return value\n        except (SourceError, ValueError), ex:\n            self.ctx.errors.invalid(str(ex))\n            return ERROR",
    "docstring": "Processes this fields `src` from `ctx.src`."
  },
  {
    "code": "async def Check(self, stream):\n        request = await stream.recv_message()\n        checks = self._checks.get(request.service)\n        if checks is None:\n            await stream.send_trailing_metadata(status=Status.NOT_FOUND)\n        elif len(checks) == 0:\n            await stream.send_message(HealthCheckResponse(\n                status=HealthCheckResponse.SERVING,\n            ))\n        else:\n            for check in checks:\n                await check.__check__()\n            await stream.send_message(HealthCheckResponse(\n                status=_status(checks),\n            ))",
    "docstring": "Implements synchronous periodic checks"
  },
  {
    "code": "def register(self, resource, event, trigger, **kwargs):\n        super(AristaTrunkDriver, self).register(resource, event,\n                                                trigger, kwargs)\n        registry.subscribe(self.subport_create,\n                           resources.SUBPORTS, events.AFTER_CREATE)\n        registry.subscribe(self.subport_delete,\n                           resources.SUBPORTS, events.AFTER_DELETE)\n        registry.subscribe(self.trunk_create,\n                           resources.TRUNK, events.AFTER_CREATE)\n        registry.subscribe(self.trunk_update,\n                           resources.TRUNK, events.AFTER_UPDATE)\n        registry.subscribe(self.trunk_delete,\n                           resources.TRUNK, events.AFTER_DELETE)\n        self.core_plugin = directory.get_plugin()\n        LOG.debug(\"Arista trunk driver initialized.\")",
    "docstring": "Called in trunk plugin's AFTER_INIT"
  },
  {
    "code": "def loaders(*specifiers):\n    for specifier in specifiers:\n        if isinstance(specifier, Locality):\n            yield from _LOADERS[specifier]\n        else:\n            yield specifier",
    "docstring": "Generates loaders in the specified order.\n\n    Arguments can be `.Locality` instances, producing the loader(s) available\n    for that locality, `str` instances (used as file path templates) or\n    `callable`s. These can be mixed:\n\n    .. code-block:: python\n\n        # define a load order using predefined user-local locations,\n        # an explicit path, a template and a user-defined function\n        load_order = loaders(Locality.user,\n                             '/etc/defaults/hard-coded.yaml',\n                             '/path/to/{name}.{extension}',\n                             my_loader)\n\n        # load configuration for name 'my-application' using the load order\n        # defined above\n        config = load_name('my-application', load_order=load_order)\n\n    :param specifiers:\n    :return: a `generator` of configuration loaders in the specified order"
  },
  {
    "code": "def dft_task(cls, mol, xc=\"b3lyp\", **kwargs):\n        t = NwTask.from_molecule(mol, theory=\"dft\", **kwargs)\n        t.theory_directives.update({\"xc\": xc,\n                                    \"mult\": t.spin_multiplicity})\n        return t",
    "docstring": "A class method for quickly creating DFT tasks with optional\n        cosmo parameter .\n\n        Args:\n            mol: Input molecule\n            xc: Exchange correlation to use.\n            \\\\*\\\\*kwargs: Any of the other kwargs supported by NwTask. Note the\n                theory is always \"dft\" for a dft task."
  },
  {
    "code": "def events(self, argv):\n        opts = cmdline(argv, FLAGS_EVENTS)\n        self.foreach(opts.args, lambda job: \n            output(job.events(**opts.kwargs)))",
    "docstring": "Retrieve events for the specified search jobs."
  },
  {
    "code": "def _prepare_conn_args(self, kwargs):\n        kwargs['connect_over_uds'] = True\n        kwargs['timeout'] = kwargs.get('timeout', 60)\n        kwargs['cookie'] = kwargs.get('cookie', 'admin')\n        if self._use_remote_connection(kwargs):\n            kwargs['transport'] = kwargs.get('transport', 'https')\n            if kwargs['transport'] == 'https':\n                kwargs['port'] = kwargs.get('port', 443)\n            else:\n                kwargs['port'] = kwargs.get('port', 80)\n            kwargs['verify'] = kwargs.get('verify', True)\n            if isinstance(kwargs['verify'], bool):\n                kwargs['verify_ssl'] = kwargs['verify']\n            else:\n                kwargs['ca_bundle'] = kwargs['verify']\n            kwargs['connect_over_uds'] = False\n        return kwargs",
    "docstring": "Set connection arguments for remote or local connection."
  },
  {
    "code": "def append(self, *nodes: Union[AbstractNode, str]) -> None:\n        node = _to_node_list(nodes)\n        self.appendChild(node)",
    "docstring": "Append new nodes after last child node."
  },
  {
    "code": "def query(number, domains, resolver=None):\n    if resolver is None:\n        resolver = dns.resolver.get_default_resolver()\n    for domain in domains:\n        if isinstance(domain, (str, unicode)):\n            domain = dns.name.from_text(domain)\n        qname = dns.e164.from_e164(number, domain)\n        try:\n            return resolver.query(qname, 'NAPTR')\n        except dns.resolver.NXDOMAIN:\n            pass\n    raise dns.resolver.NXDOMAIN",
    "docstring": "Look for NAPTR RRs for the specified number in the specified domains.\n\n    e.g. lookup('16505551212', ['e164.dnspython.org.', 'e164.arpa.'])"
  },
  {
    "code": "def match(self, package):\n        if isinstance(package, basestring):\n            from .packages import Package\n            package = Package.parse(package)\n        if self.name != package.name:\n            return False\n        if self.version_constraints and \\\n                package.version not in self.version_constraints:\n            return False\n        if self.build_options:\n            if package.build_options:\n                if self.build_options - package.build_options:\n                    return False\n                else:\n                    return True\n            else:\n                return False\n        else:\n            return True",
    "docstring": "Match ``package`` with the requirement.\n\n        :param package: Package to test with the requirement.\n        :type package: package expression string or :class:`Package`\n        :returns: ``True`` if ``package`` satisfies the requirement.\n        :rtype: bool"
  },
  {
    "code": "def lookup_object(model, object_id, slug, slug_field):\n    lookup_kwargs = {}\n    if object_id:\n        lookup_kwargs['%s__exact' % model._meta.pk.name] = object_id\n    elif slug and slug_field:\n        lookup_kwargs['%s__exact' % slug_field] = slug\n    else:\n        raise GenericViewError(\n            \"Generic view must be called with either an object_id or a\"\n            \" slug/slug_field.\")\n    try:\n        return model.objects.get(**lookup_kwargs)\n    except ObjectDoesNotExist:\n        raise Http404(\"No %s found for %s\"\n                      % (model._meta.verbose_name, lookup_kwargs))",
    "docstring": "Return the ``model`` object with the passed ``object_id``.  If\n    ``object_id`` is None, then return the object whose ``slug_field``\n    equals the passed ``slug``.  If ``slug`` and ``slug_field`` are not passed,\n    then raise Http404 exception."
  },
  {
    "code": "def get_peer_resources(self, peer_jid):\n        try:\n            d = dict(self._presences[peer_jid])\n            d.pop(None, None)\n            return d\n        except KeyError:\n            return {}",
    "docstring": "Return a dict mapping resources of the given bare `peer_jid` to the\n        presence state last received for that resource.\n\n        Unavailable presence states are not included. If the bare JID is in a\n        error state (i.e. an error presence stanza has been received), the\n        returned mapping is empty."
  },
  {
    "code": "def tryload_cache(dpath, fname, cfgstr, verbose=None):\n    try:\n        return load_cache(dpath, fname, cfgstr, verbose=verbose)\n    except IOError:\n        return None",
    "docstring": "returns None if cache cannot be loaded"
  },
  {
    "code": "def clean_community_indexes(communityID):\n    communityID = np.array(communityID)\n    cid_shape = communityID.shape\n    if len(cid_shape) > 1:\n        communityID = communityID.flatten()\n    new_communityID = np.zeros(len(communityID))\n    for i, n in enumerate(np.unique(communityID)):\n        new_communityID[communityID == n] = i\n    if len(cid_shape) > 1:\n        new_communityID = new_communityID.reshape(cid_shape)\n    return new_communityID",
    "docstring": "Takes input of community assignments. Returns reindexed community assignment by using smallest numbers possible.\n\n    Parameters\n    ----------\n\n    communityID : array-like\n        list or array of integers. Output from community detection algorithems.\n\n    Returns\n    -------\n\n    new_communityID : array\n        cleaned list going from 0 to len(np.unique(communityID))-1\n\n    Note\n    -----\n\n    Behaviour of funciton entails that the lowest community integer in communityID will recieve the lowest integer in new_communityID."
  },
  {
    "code": "def clear_key_before(self, key, namespace=None, timestamp=None):\n        block_size = self.config.block_size\n        if namespace is None:\n            namespace = self.config.namespace\n        if timestamp is not None:\n            offset, remainder = divmod(timestamp, block_size)\n            if remainder:\n                raise ValueError('timestamp must be on a block boundary')\n            if offset == 0:\n                raise ValueError('cannot delete before offset zero')\n            offset -= 1\n            self.driver.clear_key_before(key, namespace, offset, timestamp)\n        else:\n            self.driver.clear_key_before(key, namespace)",
    "docstring": "Clear all data before `timestamp` for a given key. Note that the\n        timestamp is rounded down to the nearest block boundary"
  },
  {
    "code": "def format_citations(zid, url='https://zenodo.org/', hits=10, tag_prefix='v'):\n    url = ('{url}/api/records/?'\n           'page=1&'\n           'size={hits}&'\n           'q=conceptrecid:\"{id}\"&'\n           'sort=-version&'\n           'all_versions=True'.format(id=zid, url=url, hits=hits))\n    metadata = requests.get(url).json()\n    lines = []\n    for i, hit in enumerate(metadata['hits']['hits']):\n        version = hit['metadata']['version'][len(tag_prefix):]\n        lines.append('-' * len(version))\n        lines.append(version)\n        lines.append('-' * len(version))\n        lines.append('')\n        lines.append('.. image:: {badge}\\n'\n                     '   :target: {doi}'.format(**hit['links']))\n        if i < hits - 1:\n            lines.append('')\n    return '\\n'.join(lines)",
    "docstring": "Query and format a citations page from Zenodo entries\n\n    Parameters\n    ----------\n    zid : `int`, `str`\n        the Zenodo ID of the target record\n\n    url : `str`, optional\n        the base URL of the Zenodo host, defaults to ``https://zenodo.org``\n\n    hist : `int`, optional\n        the maximum number of hits to show, default: ``10``\n\n    tag_prefix : `str`, optional\n        the prefix for git tags. This is removed to generate the section\n        headers in the output RST\n\n    Returns\n    -------\n    rst : `str`\n        an RST-formatted string of DOI badges with URLs"
  },
  {
    "code": "def needsattached(func):\n    @functools.wraps(func)\n    def wrap(self, *args, **kwargs):\n      if not self.attached:\n        raise PositionError('Not attached to any process.')\n      return func(self, *args, **kwargs)\n    return wrap",
    "docstring": "Decorator to prevent commands from being used when not attached."
  },
  {
    "code": "def print_sorted_counter(counter, tab=1):\n    for key, count in sorted(counter.items(), key=itemgetter(1), reverse=True):\n        print \"{0}{1} - {2}\".format('\\t'*tab, key, count)",
    "docstring": "print all elements of a counter in descending order"
  },
  {
    "code": "def get_instance(self, payload):\n        return CertificateInstance(self._version, payload, fleet_sid=self._solution['fleet_sid'], )",
    "docstring": "Build an instance of CertificateInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance\n        :rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateInstance"
  },
  {
    "code": "def cmd_sync(self, low):\n        kwargs = copy.deepcopy(low)\n        for ignore in ['tgt', 'fun', 'arg', 'timeout', 'tgt_type', 'kwarg']:\n            if ignore in kwargs:\n                del kwargs[ignore]\n        return self.cmd(low['tgt'],\n                        low['fun'],\n                        low.get('arg', []),\n                        low.get('timeout'),\n                        low.get('tgt_type'),\n                        low.get('kwarg'),\n                        **kwargs)",
    "docstring": "Execute a salt-ssh call synchronously.\n\n        .. versionadded:: 2015.5.0\n\n        WARNING: Eauth is **NOT** respected\n\n        .. code-block:: python\n\n            client.cmd_sync({\n                'tgt': 'silver',\n                'fun': 'test.ping',\n                'arg': (),\n                'tgt_type'='glob',\n                'kwarg'={}\n                })\n            {'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}"
  },
  {
    "code": "def attach_image(field, nested_fields, page, record_keeper=None):\n    if (field in nested_fields) and nested_fields[field]:\n        foreign_image_id = nested_fields[field][\"id\"]\n        if record_keeper:\n            try:\n                local_image_id = record_keeper.get_local_image(\n                    foreign_image_id)\n                local_image = Image.objects.get(id=local_image_id)\n                setattr(page, field, local_image)\n            except ObjectDoesNotExist:\n                raise ObjectDoesNotExist(\n                    (\"executing attach_image: local image referenced\"\n                     \"in record_keeper does not actually exist.\"),\n                    None)\n            except Exception:\n                raise\n        else:\n            raise Exception(\n                (\"Attempted to attach image without record_keeper. \"\n                 \"This functionality is not yet implemented\"))",
    "docstring": "Returns a function that attaches an image to page if it exists\n\n    Currenlty assumes that images have already been imported and info\n    has been stored in record_keeper"
  },
  {
    "code": "def singleOrPair(obj):\n    if len(list(obj.__class__.__mro__)) <= 2:\n        return 'Neither'\n    else:\n        if ancestorJr(obj) is Pair:\n            return 'Pair'\n        elif ancestor(obj) is Single:\n            return 'Single'\n        else:\n            return 'Neither'",
    "docstring": "Chech an object is single or pair or neither.\n\n    Of course,, all pairs are single, so what the function is really detecting is whether an object is only single or at the same time a pair.\n\n    Args:\n        obj (object): Literally anything.\n\n    Returns:\n        str: 'Single', or 'Pair', or 'Neither'"
  },
  {
    "code": "def version(self, context=None):\n    if self.replaces_scope and self.replaces_name:\n      if context:\n        old_opts = context.options.for_scope(self.replaces_scope)\n        if old_opts.get(self.replaces_name) and not old_opts.is_default(self.replaces_name):\n          return old_opts.get(self.replaces_name)\n      else:\n        logger.warn('Cannot resolve version of {} from deprecated option {} in scope {} without a '\n                    'context!'.format(self._get_name(), self.replaces_name, self.replaces_scope))\n    return self.get_options().version",
    "docstring": "Returns the version of the specified binary tool.\n\n    If replaces_scope and replaces_name are defined, then the caller must pass in\n    a context, otherwise no context should be passed.\n\n    # TODO: Once we're migrated, get rid of the context arg.\n\n    :API: public"
  },
  {
    "code": "def apply_single_tag_set(tag_set, selection):\n    def tags_match(server_tags):\n        for key, value in tag_set.items():\n            if key not in server_tags or server_tags[key] != value:\n                return False\n        return True\n    return selection.with_server_descriptions(\n        [s for s in selection.server_descriptions if tags_match(s.tags)])",
    "docstring": "All servers matching one tag set.\n\n    A tag set is a dict. A server matches if its tags are a superset:\n    A server tagged {'a': '1', 'b': '2'} matches the tag set {'a': '1'}.\n\n    The empty tag set {} matches any server."
  },
  {
    "code": "def load_profiles(self, overwrite=False):\n        for profile in self.minimum_needs.get_profiles(overwrite):\n            self.profile_combo.addItem(profile)\n        minimum_needs = self.minimum_needs.get_full_needs()\n        self.profile_combo.setCurrentIndex(\n            self.profile_combo.findText(minimum_needs['profile']))",
    "docstring": "Load the profiles into the dropdown list.\n\n        :param overwrite: If we overwrite existing profiles from the plugin.\n        :type overwrite: bool"
  },
  {
    "code": "def show_detailed_monitoring(name=None, instance_id=None, call=None, quiet=False):\n    if call != 'action':\n        raise SaltCloudSystemExit(\n            'The show_detailed_monitoring action must be called with -a or --action.'\n        )\n    location = get_location()\n    if six.text_type(name).startswith('i-') and (len(name) == 10 or len(name) == 19):\n        instance_id = name\n    if not name and not instance_id:\n        raise SaltCloudSystemExit(\n            'The show_detailed_monitoring action must be provided with a name or instance\\\n ID'\n        )\n    matched = _get_node(name=name, instance_id=instance_id, location=location)\n    log.log(\n        logging.DEBUG if quiet is True else logging.INFO,\n        'Detailed Monitoring is %s for %s', matched['monitoring'], name\n    )\n    return matched['monitoring']",
    "docstring": "Show the details from EC2 regarding cloudwatch detailed monitoring."
  },
  {
    "code": "def _wait_output(popen, is_slow):\n    proc = Process(popen.pid)\n    try:\n        proc.wait(settings.wait_slow_command if is_slow\n                  else settings.wait_command)\n        return True\n    except TimeoutExpired:\n        for child in proc.children(recursive=True):\n            _kill_process(child)\n        _kill_process(proc)\n        return False",
    "docstring": "Returns `True` if we can get output of the command in the\n    `settings.wait_command` time.\n\n    Command will be killed if it wasn't finished in the time.\n\n    :type popen: Popen\n    :rtype: bool"
  },
  {
    "code": "def display(self):\n        w, h = (0, 0)\n        for line in self.shell('dumpsys', 'display').splitlines():\n            m = _DISPLAY_RE.search(line, 0)\n            if not m:\n                continue\n            w = int(m.group('width'))\n            h = int(m.group('height'))\n            o = int(m.group('orientation'))\n            w, h = min(w, h), max(w, h)\n            return self.Display(w, h, o)\n        output = self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-i')\n        try:\n            data = json.loads(output)\n            (w, h, o) = (data['width'], data['height'], data['rotation']/90)\n            return self.Display(w, h, o)            \n        except ValueError:\n            pass",
    "docstring": "Return device width, height, rotation"
  },
  {
    "code": "def constructRows(self, items):\n        rows = []\n        for item in items:\n            row = dict((colname, col.extractValue(self, item))\n                       for (colname, col) in self.columns.iteritems())\n            link = self.linkToItem(item)\n            if link is not None:\n                row[u'__id__'] = link\n            rows.append(row)\n        return rows",
    "docstring": "Build row objects that are serializable using Athena for sending to the\n        client.\n\n        @param items: an iterable of objects compatible with my columns'\n        C{extractValue} methods.\n\n        @return: a list of dictionaries, where each dictionary has a string key\n        for each column name in my list of columns."
  },
  {
    "code": "def get_command_templates(command_tokens, file_tokens=[], path_tokens=[],\n    job_options=[]):\n    files = get_files(file_tokens)\n    paths = get_paths(path_tokens)\n    job_options = get_options(job_options)\n    templates = _get_command_templates(command_tokens, files, paths,\n        job_options)\n    for command_template in templates:\n        command_template._dependencies = _get_prelim_dependencies(\n            command_template, templates)\n    return templates",
    "docstring": "Given a list of tokens from the grammar, return a\n    list of commands."
  },
  {
    "code": "def _generate_default_grp_constraints(roles, network_constraints):\n    default_delay = network_constraints.get('default_delay')\n    default_rate = network_constraints.get('default_rate')\n    default_loss = network_constraints.get('default_loss', 0)\n    except_groups = network_constraints.get('except', [])\n    grps = network_constraints.get('groups', roles.keys())\n    grps = [expand_groups(g) for g in grps]\n    grps = [x for expanded_group in grps for x in expanded_group]\n    return [{'src': grp1,\n             'dst': grp2,\n             'delay': default_delay,\n             'rate': default_rate,\n             'loss': default_loss}\n            for grp1 in grps for grp2 in grps\n            if ((grp1 != grp2\n                 or _src_equals_dst_in_constraints(network_constraints, grp1))\n                and grp1 not in except_groups and grp2 not in except_groups)]",
    "docstring": "Generate default symetric grp constraints."
  },
  {
    "code": "def run(host='0.0.0.0', port=5000, reload=True, debug=True):\n    from werkzeug.serving import run_simple\n    app = bootstrap.get_app()\n    return run_simple(\n        hostname=host,\n        port=port,\n        application=app,\n        use_reloader=reload,\n        use_debugger=debug,\n    )",
    "docstring": "Run development server"
  },
  {
    "code": "def _highlight_lines(self, tokensource):\n        hls = self.hl_lines\n        for i, (t, value) in enumerate(tokensource):\n            if t != 1:\n                yield t, value\n            if i + 1 in hls:\n                if self.noclasses:\n                    style = ''\n                    if self.style.highlight_color is not None:\n                        style = (' style=\"background-color: %s\"' %\n                                 (self.style.highlight_color,))\n                    yield 1, '<span%s>%s</span>' % (style, value)\n                else:\n                    yield 1, '<span class=\"hll\">%s</span>' % value\n            else:\n                yield 1, value",
    "docstring": "Highlighted the lines specified in the `hl_lines` option by\n        post-processing the token stream coming from `_format_lines`."
  },
  {
    "code": "def smooth_angle_channels(self, channels):\n        for vertex in self.vertices:\n            for col in vertex.meta['rot_ind']:\n                if col:\n                    for k in range(1, channels.shape[0]):\n                        diff=channels[k, col]-channels[k-1, col]\n                    if abs(diff+360.)<abs(diff):\n                        channels[k:, col]=channels[k:, col]+360.\n                    elif abs(diff-360.)<abs(diff):\n                        channels[k:, col]=channels[k:, col]-360.",
    "docstring": "Remove discontinuities in angle channels so that they don't cause artifacts in algorithms that rely on the smoothness of the functions."
  },
  {
    "code": "def finalize_sv(orig_vcf, data, items):\n    paired = vcfutils.get_paired(items)\n    if paired:\n        sample_vcf = orig_vcf if paired.tumor_name == dd.get_sample_name(data) else None\n    else:\n        sample_vcf = \"%s-%s.vcf.gz\" % (utils.splitext_plus(orig_vcf)[0], dd.get_sample_name(data))\n        sample_vcf = vcfutils.select_sample(orig_vcf, dd.get_sample_name(data), sample_vcf, data[\"config\"])\n    if sample_vcf:\n        effects_vcf, _ = effects.add_to_vcf(sample_vcf, data, \"snpeff\")\n    else:\n        effects_vcf = None\n    return effects_vcf or sample_vcf",
    "docstring": "Finalize structural variants, adding effects and splitting if needed."
  },
  {
    "code": "def _container_blacklist(self):\n        if self.__container_blacklist is None:\n            self.__container_blacklist = \\\n                set(self.CLOUD_BROWSER_CONTAINER_BLACKLIST or [])\n        return self.__container_blacklist",
    "docstring": "Container blacklist."
  },
  {
    "code": "def replace_uuid_w_names(self, resp):\n        col_mapper = self.get_point_name(resp.context)[\"?point\"].to_dict()\n        resp.df.rename(columns=col_mapper, inplace=True)\n        return resp",
    "docstring": "Replace the uuid's with names.\n\n        Parameters\n        ----------\n        resp     : ???\n            ???\n\n        Returns\n        -------\n        ???\n            ???"
  },
  {
    "code": "def initialize_page(title, style, script, header=None):\n    page = markup.page(mode=\"strict_html\")\n    page._escape = False\n    page.init(title=title, css=style, script=script, header=header)\n    return page",
    "docstring": "A function that returns a markup.py page object with the required html\n    header."
  },
  {
    "code": "def vertex_fingerprints(self):\n        return self.get_vertex_fingerprints(\n            [self.get_vertex_string(i) for i in range(self.num_vertices)],\n            [self.get_edge_string(i) for i in range(self.num_edges)],\n        )",
    "docstring": "A fingerprint for each vertex\n\n           The result is invariant under permutation of the vertex indexes.\n           Vertices that are symmetrically equivalent will get the same\n           fingerprint, e.g. the hydrogens in methane would get the same\n           fingerprint."
  },
  {
    "code": "def first(sequence, message=None):\n    try:\n        return next(iter(sequence))\n    except StopIteration:\n        raise ValueError(message or ('Sequence is empty: %s' % sequence))",
    "docstring": "The first item in that sequence\n\n    If there aren't any, raise a ValueError with that message"
  },
  {
    "code": "def list_suites(suitedir=\"./testcases/suites\", cloud=False):\n        suites = []\n        suites.extend(TestSuite.get_suite_files(suitedir))\n        if cloud:\n            names = cloud.get_campaign_names()\n            if names:\n                suites.append(\"------------------------------------\")\n                suites.append(\"FROM CLOUD:\")\n                suites.extend(names)\n        if not suites:\n            return None\n        from prettytable import PrettyTable\n        table = PrettyTable([\"Testcase suites\"])\n        for suite in suites:\n            table.add_row([suite])\n        return table",
    "docstring": "Static method for listing suites from both local source and cloud.\n        Uses PrettyTable to generate the table.\n\n        :param suitedir: Local directory for suites.\n        :param cloud: cloud module\n        :return: PrettyTable object or None if no test cases were found"
  },
  {
    "code": "def from_config(cls, cp, variable_params):\n        if not cp.has_section('sampling_params'):\n            raise ValueError(\"no sampling_params section found in config file\")\n        sampling_params, replace_parameters = \\\n            read_sampling_params_from_config(cp)\n        sampling_transforms = transforms.read_transforms_from_config(\n            cp, 'sampling_transforms')\n        logging.info(\"Sampling in {} in place of {}\".format(\n            ', '.join(sampling_params), ', '.join(replace_parameters)))\n        return cls(variable_params, sampling_params,\n                   replace_parameters, sampling_transforms)",
    "docstring": "Gets sampling transforms specified in a config file.\n\n        Sampling parameters and the parameters they replace are read from the\n        ``sampling_params`` section, if it exists. Sampling transforms are\n        read from the ``sampling_transforms`` section(s), using\n        ``transforms.read_transforms_from_config``.\n\n        An ``AssertionError`` is raised if no ``sampling_params`` section\n        exists in the config file.\n\n        Parameters\n        ----------\n        cp : WorkflowConfigParser\n            Config file parser to read.\n        variable_params : list\n            List of parameter names of the original variable params.\n\n        Returns\n        -------\n        SamplingTransforms\n            A sampling transforms class."
  },
  {
    "code": "def close(self):\n        with self.lock:\n            if self.is_closed:\n                return\n            self.is_closed = True\n        log.debug(\"Closing connection (%s) to %s\", id(self), self.endpoint)\n        reactor.callFromThread(self.connector.disconnect)\n        log.debug(\"Closed socket to %s\", self.endpoint)\n        if not self.is_defunct:\n            self.error_all_requests(\n                ConnectionShutdown(\"Connection to %s was closed\" % self.endpoint))\n            self.connected_event.set()",
    "docstring": "Disconnect and error-out all requests."
  },
  {
    "code": "def open_bare_resource(self, resource_name,\n                          access_mode=constants.AccessModes.no_lock,\n                          open_timeout=constants.VI_TMO_IMMEDIATE):\n        return self.visalib.open(self.session, resource_name, access_mode, open_timeout)",
    "docstring": "Open the specified resource without wrapping into a class\n\n        :param resource_name: name or alias of the resource to open.\n        :param access_mode: access mode.\n        :type access_mode: :class:`pyvisa.constants.AccessModes`\n        :param open_timeout: time out to open.\n\n        :return: Unique logical identifier reference to a session."
  },
  {
    "code": "def do_cprofile(func):\n    def profiled_func(*args, **kwargs):\n        profile = cProfile.Profile()\n        try:\n            profile.enable()\n            result = func(*args, **kwargs)\n            profile.disable()\n            return result\n        finally:\n            profile.print_stats()\n    return profiled_func",
    "docstring": "Decorator to profile a function\n\n    It gives good numbers on various function calls but it omits a vital piece\n    of information: what is it about a function that makes it so slow?\n\n    However, it is a great start to basic profiling. Sometimes it can even\n    point you to the solution with very little fuss. I often use it as a\n    gut check to start the debugging process before I dig deeper into the\n    specific functions that are either slow are called way too often.\n\n    Pros:\n    No external dependencies and quite fast. Useful for quick high-level\n    checks.\n\n    Cons:\n    Rather limited information that usually requires deeper debugging; reports\n    are a bit unintuitive, especially for complex codebases.\n\n    See also\n    --------\n    do_profile, test_do_profile"
  },
  {
    "code": "def infile_path(self) -> Optional[PurePath]:\n        if not self.__infile_path:\n            return Path(self.__infile_path).expanduser()\n        return None",
    "docstring": "Read-only property.\n\n        :return: A ``pathlib.PurePath`` object or ``None``."
  },
  {
    "code": "def GetVersionNamespace(version):\n   ns = nsMap[version]\n   if not ns:\n      ns = serviceNsMap[version]\n   versionId = versionIdMap[version]\n   if not versionId:\n      namespace = ns\n   else:\n      namespace = '%s/%s' % (ns, versionId)\n   return namespace",
    "docstring": "Get version namespace from version"
  },
  {
    "code": "def write_text(_command, txt_file):\n    command = _command.strip()\n    with open(txt_file, 'w') as txt:\n        txt.writelines(command)",
    "docstring": "Dump SQL command to a text file."
  },
  {
    "code": "def expand_matrix_in_orthogonal_basis(\n        m: np.ndarray,\n        basis: Dict[str, np.ndarray],\n) -> value.LinearDict[str]:\n    return value.LinearDict({\n        name: (hilbert_schmidt_inner_product(b, m) /\n               hilbert_schmidt_inner_product(b, b))\n        for name, b in basis.items()\n    })",
    "docstring": "Computes coefficients of expansion of m in basis.\n\n    We require that basis be orthogonal w.r.t. the Hilbert-Schmidt inner\n    product. We do not require that basis be orthonormal. Note that Pauli\n    basis (I, X, Y, Z) is orthogonal, but not orthonormal."
  },
  {
    "code": "def fetch_single_representation(self, item_xlink_href):\n        journal_urls = {'pgen': 'http://www.plosgenetics.org/article/{0}',\n                        'pcbi': 'http://www.ploscompbiol.org/article/{0}',\n                        'ppat': 'http://www.plospathogens.org/article/{0}',\n                        'pntd': 'http://www.plosntds.org/article/{0}',\n                        'pmed': 'http://www.plosmedicine.org/article/{0}',\n                        'pbio': 'http://www.plosbiology.org/article/{0}',\n                        'pone': 'http://www.plosone.org/article/{0}',\n                        'pctr': 'http://clinicaltrials.ploshubs.org/article/{0}'}\n        subjournal_name = self.article.doi.split('.')[2]\n        base_url = journal_urls[subjournal_name]\n        resource = 'fetchSingleRepresentation.action?uri=' + item_xlink_href\n        return base_url.format(resource)",
    "docstring": "This function will render a formatted URL for accessing the PLoS' server\n        SingleRepresentation of an object."
  },
  {
    "code": "def freefn(self, item, fn, at_tail):\n        return c_void_p(lib.zlist_freefn(self._as_parameter_, item, fn, at_tail))",
    "docstring": "Set a free function for the specified list item. When the item is\ndestroyed, the free function, if any, is called on that item.\nUse this when list items are dynamically allocated, to ensure that\nyou don't have memory leaks. You can pass 'free' or NULL as a free_fn.\nReturns the item, or NULL if there is no such item."
  },
  {
    "code": "def animate(self, images, delay=.25):\n        for image in images:\n            self.set_image(image)\n            self.write_display()\n            time.sleep(delay)",
    "docstring": "Displays each of the input images in order, pausing for \"delay\"\n        seconds after each image.\n\n        Keyword arguments:\n        image -- An iterable collection of Image objects.\n        delay -- How many seconds to wait after displaying an image before\n            displaying the next one. (Default = .25)"
  },
  {
    "code": "def protract(self, x):\n        self.active = self.active.protract(x)\n        return self.active",
    "docstring": "Protract each of the `active` `Segments` by ``x`` seconds.\n\n        This method subtracts ``x`` from each segment's lower bound,\n        and adds ``x`` to the upper bound, while maintaining that each\n        `Segment` stays within the `known` bounds.\n\n        The :attr:`~DataQualityFlag.active` `SegmentList` is modified\n        in place.\n\n        Parameters\n        ----------\n        x : `float`\n            number of seconds by which to protact each `Segment`."
  },
  {
    "code": "def find(self, id):\n        for sprite in self.sprites:\n            if sprite.id == id:\n                return sprite\n        for sprite in self.sprites:\n            found = sprite.find(id)\n            if found:\n                return found",
    "docstring": "breadth-first sprite search by ID"
  },
  {
    "code": "def get_elastic_page_numbers(current_page, num_pages):\n    if num_pages <= 10:\n        return list(range(1, num_pages + 1))\n    if current_page == 1:\n        pages = [1]\n    else:\n        pages = ['first', 'previous']\n        pages.extend(_make_elastic_range(1, current_page))\n    if current_page != num_pages:\n        pages.extend(_make_elastic_range(current_page, num_pages)[1:])\n        pages.extend(['next', 'last'])\n    return pages",
    "docstring": "Alternative callable for page listing.\n\n    Produce an adaptive pagination, useful for big numbers of pages, by\n    splitting the num_pages ranges in two parts at current_page. Each part\n    will have its own S-curve."
  },
  {
    "code": "def search_function(cls, encoding):\n        if encoding == cls._codec_name:\n            return codecs.CodecInfo(\n                name=cls._codec_name,\n                encode=cls.encode,\n                decode=cls.decode,\n            )\n        return None",
    "docstring": "Search function to find 'rotunicode' codec."
  },
  {
    "code": "def setup_package():\n    import json\n    from setuptools import setup, find_packages\n    filename_setup_json = 'setup.json'\n    filename_description = 'README.md'\n    with open(filename_setup_json, 'r') as handle:\n        setup_json = json.load(handle)\n    with open(filename_description, 'r') as handle:\n        description = handle.read()\n    setup(\n        include_package_data=True,\n        packages=find_packages(),\n        setup_requires=['reentry'],\n        reentry_register=True,\n        long_description=description,\n        long_description_content_type='text/markdown',\n        **setup_json)",
    "docstring": "Setup procedure."
  },
  {
    "code": "def to_json_serializable(obj):\n    if isinstance(obj, Entity):\n        return obj.to_json_dict()\n    if isinstance(obj, dict):\n        return {k: to_json_serializable(v) for k, v in obj.items()}\n    elif isinstance(obj, (list, tuple)):\n        return [to_json_serializable(v) for v in obj]\n    elif isinstance(obj, datetime):\n        return obj.strftime('%Y-%m-%d %H:%M:%S')\n    elif isinstance(obj, date):\n        return obj.strftime('%Y-%m-%d')\n    return obj",
    "docstring": "Transforms obj into a json serializable object.\n\n    :param obj: entity or any json serializable object\n\n    :return: serializable object"
  },
  {
    "code": "def render_to_response(self, context):\n        self.setup_forms()\n        return TemplateResponse(\n            self.request, self.form_template,\n            context, current_app=self.admin_site.name)",
    "docstring": "Add django-crispy form helper and draw the template\n\n        Returns the ``TemplateResponse`` ready to be displayed"
  },
  {
    "code": "def AddAttribute(self, attribute, value=None, age=None):\n    if \"w\" not in self.mode:\n      raise IOError(\"Writing attribute %s to read only object.\" % attribute)\n    if value is None:\n      value = attribute\n      attribute = value.attribute_instance\n    if self.mode != \"w\" and attribute.lock_protected and not self.transaction:\n      raise IOError(\"Object must be locked to write attribute %s.\" % attribute)\n    self._CheckAttribute(attribute, value)\n    if attribute.versioned:\n      if attribute.creates_new_object_version:\n        self._new_version = True\n      if age:\n        value.age = age\n      else:\n        value.age = rdfvalue.RDFDatetime.Now()\n    else:\n      self._to_delete.add(attribute)\n      self.synced_attributes.pop(attribute, None)\n      self.new_attributes.pop(attribute, None)\n      value.age = 0\n    self._AddAttributeToCache(attribute, value, self.new_attributes)\n    self._dirty = True",
    "docstring": "Add an additional attribute to this object.\n\n    If value is None, attribute is expected to be already initialized with a\n    value. For example:\n\n    fd.AddAttribute(fd.Schema.CONTAINS(\"some data\"))\n\n    Args:\n       attribute: The attribute name or an RDFValue derived from the attribute.\n       value: The value the attribute will be set to.\n       age: Age (timestamp) of the attribute. If None, current time is used.\n\n    Raises:\n       IOError: If this object is read only."
  },
  {
    "code": "def listar_por_equipamento(self, id_equipamento):\n        if not is_valid_int_param(id_equipamento):\n            raise InvalidParameterError(\n                u'Equipment id is invalid or was not informed.')\n        url = 'interface/equipamento/' + str(id_equipamento) + '/'\n        code, map = self.submit(None, 'GET', url)\n        key = 'interface'\n        return get_list_map(self.response(code, map, [key]), key)",
    "docstring": "List all interfaces of an equipment.\n\n        :param id_equipamento: Equipment identifier.\n\n        :return: Dictionary with the following:\n\n        ::\n\n            {'interface':\n            [{'protegida': < protegida >,\n            'nome': < nome >,\n            'id_ligacao_front': < id_ligacao_front >,\n            'id_equipamento': < id_equipamento >,\n            'id': < id >,\n            'descricao': < descricao >,\n            'id_ligacao_back': < id_ligacao_back >}, ... other interfaces ...]}\n\n        :raise InvalidParameterError: Equipment identifier is invalid or none.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def convert_svhn(which_format, directory, output_directory,\n                 output_filename=None):\n    if which_format not in (1, 2):\n        raise ValueError(\"SVHN format needs to be either 1 or 2.\")\n    if not output_filename:\n        output_filename = 'svhn_format_{}.hdf5'.format(which_format)\n    if which_format == 1:\n        return convert_svhn_format_1(\n            directory, output_directory, output_filename)\n    else:\n        return convert_svhn_format_2(\n            directory, output_directory, output_filename)",
    "docstring": "Converts the SVHN dataset to HDF5.\n\n    Converts the SVHN dataset [SVHN] to an HDF5 dataset compatible\n    with :class:`fuel.datasets.SVHN`. The converted dataset is\n    saved as 'svhn_format_1.hdf5' or 'svhn_format_2.hdf5', depending\n    on the `which_format` argument.\n\n    .. [SVHN] Yuval Netzer, Tao Wang, Adam Coates, Alessandro Bissacco,\n       Bo Wu, Andrew Y. Ng. *Reading Digits in Natural Images with\n       Unsupervised Feature Learning*, NIPS Workshop on Deep Learning\n       and Unsupervised Feature Learning, 2011.\n\n    Parameters\n    ----------\n    which_format : int\n        Either 1 or 2. Determines which format (format 1: full numbers\n        or format 2: cropped digits) to convert.\n    directory : str\n        Directory in which input files reside.\n    output_directory : str\n        Directory in which to save the converted dataset.\n    output_filename : str, optional\n        Name of the saved dataset. Defaults to 'svhn_format_1.hdf5' or\n        'svhn_format_2.hdf5', depending on `which_format`.\n\n    Returns\n    -------\n    output_paths : tuple of str\n        Single-element tuple containing the path to the converted dataset."
  },
  {
    "code": "def get_issuer_keys(self, issuer):\n        res = []\n        for kbl in self.issuer_keys[issuer]:\n            res.extend(kbl.keys())\n        return res",
    "docstring": "Get all the keys that belong to an entity.\n\n        :param issuer: The entity ID\n        :return: A possibly empty list of keys"
  },
  {
    "code": "def update_config(self, config, timeout=-1):\n        return self._client.update(config, uri=self.URI + \"/config\", timeout=timeout)",
    "docstring": "Updates the remote server configuration and the automatic backup schedule for backup.\n\n        Args:\n            config (dict): Object to update.\n            timeout:\n                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n                in OneView, just stop waiting for its completion.\n\n        Returns:\n            dict: Backup details."
  },
  {
    "code": "def path(args):\n  from .query import Database\n  db = Database()\n  output = sys.stdout\n  if args.selftest:\n    from bob.db.utils import null\n    output = null()\n  r = db.paths(args.id, prefix=args.directory, suffix=args.extension)\n  for path in r: output.write('%s\\n' % path)\n  if not r: return 1\n  return 0",
    "docstring": "Returns a list of fully formed paths or stems given some file id"
  },
  {
    "code": "def _bse_cli_get_basis(args):\n    return api.get_basis(\n        name=args.basis,\n        elements=args.elements,\n        version=args.version,\n        fmt=args.fmt,\n        uncontract_general=args.unc_gen,\n        uncontract_spdf=args.unc_spdf,\n        uncontract_segmented=args.unc_seg,\n        make_general=args.make_gen,\n        optimize_general=args.opt_gen,\n        data_dir=args.data_dir,\n        header=not args.noheader)",
    "docstring": "Handles the get-basis subcommand"
  },
  {
    "code": "def feature_passthrough(early_feat, late_feat, filters, name, kernel_size=(1, 1)):\n    _, h_early, w_early, c_early = early_feat.get_shape().as_list()\n    _, h_late, w_late, c_late = late_feat.get_shape().as_list()\n    s_x = int(w_early / w_late)\n    s_y = int(h_early / h_late)\n    assert h_late * s_y == h_early and w_late * s_x == w_early\n    with tf.variable_scope(name) as scope:\n        early_conv = tf.layers.conv2d(early_feat, filters=filters, kernel_size=(s_x * kernel_size[0], s_y * kernel_size[1]), strides=(s_x, s_y), padding=\"same\")\n        late_conv = tf.layers.conv2d(late_feat, filters=filters, kernel_size=kernel_size, strides=(1, 1), padding=\"same\")\n        return early_conv + late_conv",
    "docstring": "A feature passthrough layer inspired by yolo9000 and the inverse tiling layer.\n\n    It can be proven, that this layer does the same as conv(concat(inverse_tile(early_feat), late_feat)).\n    This layer has no activation function.\n\n    :param early_feat: The early feature layer of shape [batch_size, h * s_x, w * s_y, _].\n    s_x and s_y are integers computed internally describing the scale between the layers.\n    :param late_feat:  The late feature layer of shape [batch_size, h, w, _].\n    :param filters: The number of convolution filters.\n    :param name: The name of the layer.\n    :param kernel_size: The size of the kernel. Default (1x1).\n    :return: The output tensor of shape [batch_size, h, w, outputs]"
  },
  {
    "code": "def handle_endtag(self, tagName):\n        inTag = self._inTag\n        try:\n            foundIt = False\n            for i in range(len(inTag)):\n                if inTag[i].tagName == tagName:\n                    foundIt = True\n                    break\n            if not foundIt:\n                sys.stderr.write('WARNING: found close tag with no matching start.\\n')\n                return\n            while inTag[-1].tagName != tagName:\n                oldTag = inTag.pop()\n                if oldTag.tagName in PREFORMATTED_TAGS:\n                    self.inPreformatted -= 1\n                self.currentIndentLevel -= 1\n            inTag.pop()\n            if tagName != INVISIBLE_ROOT_TAG:\n                self.currentIndentLevel -= 1\n            if tagName in PREFORMATTED_TAGS:\n                self.inPreformatted -= 1\n        except:\n            pass",
    "docstring": "handle_endtag - Internal for parsing"
  },
  {
    "code": "def encode_timeseries_put(self, tsobj):\n        if tsobj.columns:\n            raise NotImplementedError('columns are not used')\n        if tsobj.rows and isinstance(tsobj.rows, list):\n            req_rows = []\n            for row in tsobj.rows:\n                req_r = []\n                for cell in row:\n                    req_r.append(self.encode_to_ts_cell(cell))\n                req_rows.append(tuple(req_r))\n            req = tsputreq_a, tsobj.table.name, [], req_rows\n            mc = MSG_CODE_TS_TTB_MSG\n            rc = MSG_CODE_TS_TTB_MSG\n            return Msg(mc, encode(req), rc)\n        else:\n            raise RiakError(\"TsObject requires a list of rows\")",
    "docstring": "Returns an Erlang-TTB encoded tuple with the appropriate data and\n        metadata from a TsObject.\n\n        :param tsobj: a TsObject\n        :type tsobj: TsObject\n        :rtype: term-to-binary encoded object"
  },
  {
    "code": "def normalize_name(name, overrides=None):\n    normalized_name = name.title()\n    if overrides:\n        override_map = dict([(name.title(), name) for name in overrides])\n        return override_map.get(normalized_name, normalized_name)\n    else:\n        return normalized_name",
    "docstring": "Normalize the key name to title case.\n\n    For example, ``normalize_name('content-id')`` will become ``Content-Id``\n\n    Args:\n        name (str): The name to normalize.\n        overrides (set, sequence): A set or sequence containing keys that\n            should be cased to themselves. For example, passing\n            ``set('WARC-Type')`` will normalize any key named \"warc-type\" to\n            ``WARC-Type`` instead of the default ``Warc-Type``.\n\n    Returns:\n        str"
  },
  {
    "code": "def compute_bbox_with_margins(margin, x, y):\n    'Helper function to compute bounding box for the plot'\n    pos = np.asarray((x, y))\n    minxy, maxxy = pos.min(axis=1), pos.max(axis=1)\n    xy1 = minxy - margin*(maxxy - minxy)\n    xy2 = maxxy + margin*(maxxy - minxy)\n    return tuple(xy1), tuple(xy2)",
    "docstring": "Helper function to compute bounding box for the plot"
  },
  {
    "code": "def set_value(self, value, force=False):\n        if force:\n            self._value = value\n            return\n        if value is None:\n            self._value = value\n            return\n        if isinstance(value, six.integer_types):\n            self._value = value\n            return\n        if isinstance(value, six.string_types):\n            for v, n in self.enums.items():\n                if n == value:\n                    self._value = v\n                    return\n            raise ValueError(\"Unable to find value name in enum list\")\n        raise TypeError(\n            \"Value for '%s' must by of type String or Integer not '%s'\" % (\n                self.name,\n                type(value)\n            )\n        )",
    "docstring": "Set the value.\n\n        :param String|Integer value: The value to set. Must be in the enum list.\n        :param Boolean force: Set the value without checking it\n\n        :raises ValueError: If value name given but it isn't available\n        :raises TypeError: If value is not String or Integer"
  },
  {
    "code": "def verify(self, payload):\n        if not self.authenticator:\n            return payload\n        try:\n            self.authenticator.auth(payload)\n            return self.authenticator.unsigned(payload)\n        except AuthenticatorInvalidSignature:\n            raise\n        except Exception as exception:\n            raise AuthenticateError(str(exception))",
    "docstring": "Verify payload authenticity via the supplied authenticator"
  },
  {
    "code": "def maybe_create_placement_group(name='', max_retries=10):\n  if not name:\n    return\n  client = get_ec2_client()\n  while True:\n    try:\n      client.describe_placement_groups(GroupNames=[name])\n      print(\"Reusing placement_group group: \" + name)\n      break\n    except Exception:\n      print(\"Creating placement_group group: \" + name)\n      try:\n        _response = client.create_placement_group(GroupName=name,\n                                                  Strategy='cluster')\n      except Exception:\n        pass\n  counter = 0\n  while True:\n    try:\n      res = client.describe_placement_groups(GroupNames=[name])\n      res_entry = res['PlacementGroups'][0]\n      if res_entry['State'] == 'available':\n        assert res_entry['Strategy'] == 'cluster'\n        break\n    except Exception as e:\n      print(\"Got exception: %s\" % (e,))\n    counter += 1\n    if counter >= max_retries:\n      assert False, f'Failed to create placement_group group {name} in {max_retries} attempts'\n    time.sleep(RETRY_INTERVAL_SEC)",
    "docstring": "Creates placement_group group or reuses existing one. Crash if unable to create\n    placement_group group. If name is empty, ignores request."
  },
  {
    "code": "def delete(self, photo_id, album_id=0):\n        if isinstance(photo_id, Info):\n            photo_id = photo_id.id\n        return self._session.okc_post('photoupload', data={\n            'albumid': album_id,\n            'picid': photo_id,\n            'authcode': self._authcode,\n            'picture.delete_ajax': 1\n        })",
    "docstring": "Delete a photo from the logged in users account.\n\n        :param photo_id: The okcupid id of the photo to delete.\n        :param album_id: The album from which to delete the photo."
  },
  {
    "code": "async def certify(client: Client, certification_signed_raw: str) -> ClientResponse:\n    return await client.post(MODULE + '/certify', {'cert': certification_signed_raw}, rtype=RESPONSE_AIOHTTP)",
    "docstring": "POST certification raw document\n\n    :param client: Client to connect to the api\n    :param certification_signed_raw: Certification raw document\n    :return:"
  },
  {
    "code": "def _build_date_time_time_zone(self, date_time):\n        timezone = date_time.tzinfo.zone if date_time.tzinfo is not None else None\n        return {\n            self._cc('dateTime'): date_time.strftime('%Y-%m-%dT%H:%M:%S'),\n            self._cc('timeZone'): get_windows_tz(timezone or self.protocol.timezone)\n        }",
    "docstring": "Converts a datetime to a dateTimeTimeZone resource"
  },
  {
    "code": "def serialize_to_normalized_pretty_json(py_obj):\n    return json.dumps(py_obj, sort_keys=True, indent=2, cls=ToJsonCompatibleTypes)",
    "docstring": "Serialize a native object to normalized, pretty printed JSON.\n\n    The JSON string is normalized by sorting any dictionary keys.\n\n    Args:\n      py_obj: object\n        Any object that can be represented in JSON. Some types, such as datetimes are\n        automatically converted to strings.\n\n    Returns:\n      str: normalized, pretty printed JSON string."
  },
  {
    "code": "def from_dict(cls, d):\n        name = PartitionIdentity._name_class(**d)\n        if 'id' in d and 'revision' in d:\n            on = (ObjectNumber.parse(d['id']).rev(d['revision']))\n        elif 'vid' in d:\n            on = ObjectNumber.parse(d['vid'])\n        else:\n            raise ValueError(\"Must have id and revision, or vid\")\n        try:\n            return PartitionIdentity(name, on)\n        except TypeError as e:\n            raise TypeError(\n                \"Failed to make identity from \\n{}\\n: {}\".format(\n                    d,\n                    e.message))",
    "docstring": "Like Identity.from_dict, but will cast the class type based on the\n        format. i.e. if the format is hdf, return an HdfPartitionIdentity.\n\n        :param d:\n        :return:"
  },
  {
    "code": "def load_image(filename, timeout=120):\n    c = docker_fabric()\n    with open(expand_path(filename), 'r') as f:\n        _timeout = c._timeout\n        c._timeout = timeout\n        try:\n            c.load_image(f)\n        finally:\n            c._timeout = _timeout",
    "docstring": "Uploads an image from a local file to a Docker remote. Note that this temporarily has to extend the service timeout\n    period.\n\n    :param filename: Local file name.\n    :type filename: unicode\n    :param timeout: Timeout in seconds to set temporarily for the upload.\n    :type timeout: int"
  },
  {
    "code": "def create_app(self):\n        utils.banner(\"Creating Spinnaker App\")\n        spinnakerapp = app.SpinnakerApp(app=self.app, email=self.email, project=self.group, repo=self.repo,\n                                        pipeline_config=self.configs['pipeline'])\n        spinnakerapp.create_app()",
    "docstring": "Create the spinnaker application."
  },
  {
    "code": "def _diff_bounds(bounds, coord):\n    try:\n        return bounds[:, 1] - bounds[:, 0]\n    except IndexError:\n        diff = np.diff(bounds, axis=0)\n        return xr.DataArray(diff, dims=coord.dims, coords=coord.coords)",
    "docstring": "Get grid spacing by subtracting upper and lower bounds."
  },
  {
    "code": "def get_fba_flux(self, objective):\n        flux_result = self.solve_fba(objective)\n        fba_fluxes = {}\n        for key in self._model.reactions:\n            fba_fluxes[key] = flux_result.get_value(self._v_wt[key])\n        return fba_fluxes",
    "docstring": "Return a dictionary of all the fluxes solved by FBA.\n\n        Dictionary of fluxes is used in :meth:`.lin_moma` and :meth:`.moma`\n        to minimize changes in the flux distributions following model\n        perturbation.\n\n        Args:\n            objective: The objective reaction that is maximized.\n\n        Returns:\n            Dictionary of fluxes for each reaction in the model."
  },
  {
    "code": "def current_bed_temp(self):\n        try:\n            bedtemps = self.intervals[0]['timeseries']['tempBedC']\n            num_temps = len(bedtemps)\n            if num_temps == 0:\n                return None\n            bedtemp = bedtemps[num_temps-1][1]\n        except KeyError:\n            bedtemp = None\n        return bedtemp",
    "docstring": "Return current bed temperature for in-progress session."
  },
  {
    "code": "def length(self):\n        return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)",
    "docstring": "Array of vector lengths"
  },
  {
    "code": "def defaults(default=None):\n    def _f(func):\n        @functools.wraps(func)\n        def __f(self, *args, **kwargs):\n            try:\n                return func(self, *args, **kwargs)\n            except Exception:\n                return default\n        return __f\n    return _f",
    "docstring": "Catches any exception thrown by the wrapped function and returns `default`\n    instead.\n\n    Parameters\n    ----------\n\n    default : object\n        The default value to return if the wrapped function throws an exception"
  },
  {
    "code": "def serialise(self, element: Element) -> str:\n        return json.dumps(self.serialise_element(element))",
    "docstring": "Serialises the given element into Compact JSON.\n\n        >>> CompactJSONSerialiser().serialise(String(content='Hello'))\n        '[\"string\", null, null, \"Hello\"]'"
  },
  {
    "code": "def _enforceDataType(self, data):\n        idx = int(data)\n        if idx < 0:\n            idx += len(self._displayValues)\n        assert 0 <= idx < len(self._displayValues), \\\n            \"Index should be >= 0 and < {}. Got {}\".format(len(self._displayValues), idx)\n        return idx",
    "docstring": "Converts to int so that this CTI always stores that type.\n\n            The data be set to a negative value, e.g. use -1 to select the last item\n            by default. However, it will be converted to a positive by this method."
  },
  {
    "code": "def send(self, text):\n        if text:\n            self.send_buffer += text.replace('\\n', '\\r\\n')\n            self.send_pending = True",
    "docstring": "Send raw text to the distant end."
  },
  {
    "code": "def replace(self, key, value, expire=0, noreply=None):\n        if noreply is None:\n            noreply = self.default_noreply\n        return self._store_cmd(b'replace', {key: value}, expire, noreply)[key]",
    "docstring": "The memcached \"replace\" command.\n\n        Args:\n          key: str, see class docs for details.\n          value: str, see class docs for details.\n          expire: optional int, number of seconds until the item is expired\n                  from the cache, or zero for no expiry (the default).\n          noreply: optional bool, True to not wait for the reply (defaults to\n                   self.default_noreply).\n\n        Returns:\n          If noreply is True, always returns True. Otherwise returns True if\n          the value was stored and False if it wasn't (because the key didn't\n          already exist)."
  },
  {
    "code": "def prep_directory(self, target_dir):\n        dirname = path.dirname(target_dir)\n        if dirname:\n            dirname = path.join(settings.BUILD_DIR, dirname)\n            if not self.fs.exists(dirname):\n                logger.debug(\"Creating directory at {}{}\".format(self.fs_name, dirname))\n                self.fs.makedirs(dirname)",
    "docstring": "Prepares a new directory to store the file at the provided path, if needed."
  },
  {
    "code": "def build(self):\n        markdown_html = markdown.markdown(self.markdown_text, extensions=[\n                TocExtension(), 'fenced_code', 'markdown_checklist.extension',\n                'markdown.extensions.tables'])\n        markdown_soup = BeautifulSoup(markdown_html, 'html.parser')\n        if markdown_soup.find('code', attrs={'class': 'mermaid'}):\n            self._add_mermaid_js()\n        for dot_tag in markdown_soup.find_all('code', attrs={'class': 'dotgraph'}):\n            grap_svg = self._text_to_graphiz(dot_tag.string)\n            graph_soup = BeautifulSoup(grap_svg, 'html.parser')\n            dot_tag.parent.replaceWith(graph_soup)\n        self.main_soup.body.append(markdown_soup)\n        return self.main_soup.prettify()",
    "docstring": "convert Markdown text as html. return the html file as string"
  },
  {
    "code": "def package_locations(self, package_keyname):\n        mask = \"mask[description, keyname, locations]\"\n        package = self.get_package_by_key(package_keyname, mask='id')\n        regions = self.package_svc.getRegions(id=package['id'], mask=mask)\n        return regions",
    "docstring": "List datacenter locations for a package keyname\n\n        :param str package_keyname: The package for which to get the items.\n        :returns: List of locations a package is orderable in"
  },
  {
    "code": "def search_form(context, search_model_names=None):\n    template_vars = {\n        \"request\": context[\"request\"],\n    }\n    if not search_model_names or not settings.SEARCH_MODEL_CHOICES:\n        search_model_names = []\n    elif search_model_names == \"all\":\n        search_model_names = list(settings.SEARCH_MODEL_CHOICES)\n    else:\n        search_model_names = search_model_names.split(\" \")\n    search_model_choices = []\n    for model_name in search_model_names:\n        try:\n            model = apps.get_model(*model_name.split(\".\", 1))\n        except LookupError:\n            pass\n        else:\n            verbose_name = model._meta.verbose_name_plural.capitalize()\n            search_model_choices.append((verbose_name, model_name))\n    template_vars[\"search_model_choices\"] = sorted(search_model_choices)\n    return template_vars",
    "docstring": "Includes the search form with a list of models to use as choices\n    for filtering the search by. Models should be a string with models\n    in the format ``app_label.model_name`` separated by spaces. The\n    string ``all`` can also be used, in which case the models defined\n    by the ``SEARCH_MODEL_CHOICES`` setting will be used."
  },
  {
    "code": "def merge_elisions(elided: List[str]) -> str:\n    results = list(elided[0])\n    for line in elided:\n        for idx, car in enumerate(line):\n            if car == \" \":\n                results[idx] = \" \"\n    return \"\".join(results)",
    "docstring": "Given a list of strings with different space swapping elisions applied, merge the elisions,\n    taking the most without compounding the omissions.\n\n    :param elided:\n    :return:\n\n    >>> merge_elisions([\n    ... \"ignavae agua multum hiatus\", \"ignav   agua multum hiatus\" ,\"ignavae agua mult   hiatus\"])\n    'ignav   agua mult   hiatus'"
  },
  {
    "code": "async def save(self):\n        old_tags = list(self._orig_data['tags'])\n        new_tags = list(self.tags)\n        self._changed_data.pop('tags', None)\n        await super(BlockDevice, self).save()\n        for tag_name in new_tags:\n            if tag_name not in old_tags:\n                await self._handler.add_tag(\n                    system_id=self.node.system_id, id=self.id, tag=tag_name)\n            else:\n                old_tags.remove(tag_name)\n        for tag_name in old_tags:\n            await self._handler.remove_tag(\n                system_id=self.node.system_id, id=self.id, tag=tag_name)\n        self._orig_data['tags'] = new_tags\n        self._data['tags'] = list(new_tags)",
    "docstring": "Save this block device."
  },
  {
    "code": "def nice_size(size):\n    unit = 'B'\n    if size > 1024:\n        size /= 1024.0\n        unit = 'KB'\n        if size > 1024:\n            size /= 1024.0\n            unit = 'MB'\n            if size > 1024:\n                size /= 1024.0\n                unit = 'GB'\n    return '%s %s' % (nice_number(size, max_ndigits_after_dot=2), unit)",
    "docstring": "Nice size.\n\n    :param size: the size.\n    :type size: int\n    :return: a nicely printed size.\n    :rtype: string"
  },
  {
    "code": "def vinet_p(v, v0, k0, k0p):\n    return cal_p_vinet(v, [v0, k0, k0p],\n                       uncertainties=isuncertainties([v, v0, k0, k0p]))",
    "docstring": "calculate pressure from vinet equation\n\n    :param v: unit-cell volume in A^3\n    :param v0: unit-cell volume in A^3 at 1 bar\n    :param k0: bulk modulus at reference conditions\n    :param k0p: pressure derivative of bulk modulus at reference conditions\n    :return: pressure in GPa"
  },
  {
    "code": "def copy(self, old_name, new_name, index=None):\n        if index is None:\n            index = len(self)\n        self._copy(old_name, new_name, index)\n        return self[new_name]",
    "docstring": "Copies an old sheet with the old_name to a new sheet with new_name.\n\n        If an optional index argument is not provided then the created\n        sheet is appended at the end. Returns the new sheet."
  },
  {
    "code": "def get_build_scanner_path(self, scanner):\n        env = self.get_build_env()\n        try:\n            cwd = self.batches[0].targets[0].cwd\n        except (IndexError, AttributeError):\n            cwd = None\n        return scanner.path(env, cwd,\n                            self.get_all_targets(),\n                            self.get_all_sources())",
    "docstring": "Fetch the scanner path for this executor's targets and sources."
  },
  {
    "code": "def get_variable_grammar(self):\n        word_expr = Word(alphanums + '_' + '-')\n        word_expr2 = Word(initChars=printables, excludeChars=['{', '}', ',', ' '])\n        name_expr = Suppress('variable') + word_expr + Suppress('{')\n        state_expr = ZeroOrMore(word_expr2 + Optional(Suppress(\",\")))\n        variable_state_expr = Suppress('type') + Suppress(word_expr) + Suppress('[') + Suppress(Word(nums)) + \\\n            Suppress(']') + Suppress('{') + Group(state_expr) + Suppress('}') + Suppress(';')\n        property_expr = Suppress('property') + CharsNotIn(';') + Suppress(';')\n        return name_expr, variable_state_expr, property_expr",
    "docstring": "A method that returns variable grammar"
  },
  {
    "code": "def process_sparser_output(output_fname, output_fmt='json'):\n    if output_fmt not in ['json', 'xml']:\n        logger.error(\"Unrecognized output format '%s'.\" % output_fmt)\n        return None\n    sp = None\n    with open(output_fname, 'rt') as fh:\n        if output_fmt == 'json':\n            json_dict = json.load(fh)\n            sp = process_json_dict(json_dict)\n        else:\n            xml_str = fh.read()\n            sp = process_xml(xml_str)\n    return sp",
    "docstring": "Return a processor with Statements extracted from Sparser XML or JSON\n\n    Parameters\n    ----------\n    output_fname : str\n        The path to the Sparser output file to be processed. The file can\n        either be JSON or XML output from Sparser, with the output_fmt\n        parameter defining what format is assumed to be processed.\n    output_fmt : Optional[str]\n        The format of the Sparser output to be processed, can either be\n        'json' or 'xml'. Default: 'json'\n\n    Returns\n    -------\n    sp : SparserXMLProcessor or SparserJSONProcessor depending on what output\n    format was chosen."
  },
  {
    "code": "def init_live_reload(run):\n    from asyncio import get_event_loop\n    from ._live_reload import start_child\n    loop = get_event_loop()\n    if run:\n        loop.run_until_complete(start_child())\n    else:\n        get_event_loop().create_task(start_child())",
    "docstring": "Start the live reload task\n\n    :param run: run the task inside of this function or just create it"
  },
  {
    "code": "def check(cls, dap, network=False, yamls=True, raises=False, logger=logger):\n        dap._check_raises = raises\n        dap._problematic = False\n        dap._logger = logger\n        problems = list()\n        problems += cls.check_meta(dap)\n        problems += cls.check_no_self_dependency(dap)\n        problems += cls.check_topdir(dap)\n        problems += cls.check_files(dap)\n        if yamls:\n            problems += cls.check_yamls(dap)\n        if network:\n            problems += cls.check_name_not_on_dapi(dap)\n        for problem in problems:\n            dap._report_problem(problem.message, problem.level)\n        del dap._check_raises\n        return not dap._problematic",
    "docstring": "Checks if the dap is valid, reports problems\n\n        Parameters:\n            network -- whether to run checks that requires network connection\n            output -- where to write() problems, might be None\n            raises -- whether to raise an exception immediately after problem is detected"
  },
  {
    "code": "def update_cors_configuration(\n            self,\n            enable_cors=True,\n            allow_credentials=True,\n            origins=None,\n            overwrite_origins=False):\n        if origins is None:\n            origins = []\n        cors_config = {\n            'enable_cors': enable_cors,\n            'allow_credentials': allow_credentials,\n            'origins': origins\n        }\n        if overwrite_origins:\n            return self._write_cors_configuration(cors_config)\n        old_config = self.cors_configuration()\n        updated_config = old_config.copy()\n        updated_config['enable_cors'] = cors_config.get('enable_cors')\n        updated_config['allow_credentials'] = cors_config.get('allow_credentials')\n        if cors_config.get('origins') == [\"*\"]:\n            updated_config['origins'] = [\"*\"]\n        elif old_config.get('origins') != cors_config.get('origins'):\n            new_origins = list(\n                set(old_config.get('origins')).union(\n                    set(cors_config.get('origins')))\n            )\n            updated_config['origins'] = new_origins\n        return self._write_cors_configuration(updated_config)",
    "docstring": "Merges existing CORS configuration with updated values.\n\n        :param bool enable_cors: Enables/disables CORS.  Defaults to True.\n        :param bool allow_credentials: Allows authentication credentials.\n            Defaults to True.\n        :param list origins: List of allowed CORS origin(s).  Special cases are\n            a list containing a single \"*\" which will allow any origin and\n            an empty list which will not allow any origin.  Defaults to None.\n        :param bool overwrite_origins: Dictates whether the origins list is\n            overwritten of appended to.  Defaults to False.\n\n        :returns: CORS configuration update status in JSON format"
  },
  {
    "code": "def get_instance():\n    resources = []\n    env_resource = resource.get_from_env()\n    if env_resource is not None:\n        resources.append(env_resource)\n    if k8s_utils.is_k8s_environment():\n        resources.append(resource.Resource(\n            _K8S_CONTAINER, k8s_utils.get_k8s_metadata()))\n    if is_gce_environment():\n        resources.append(resource.Resource(\n            _GCE_INSTANCE,\n            gcp_metadata_config.GcpMetadataConfig().get_gce_metadata()))\n    elif is_aws_environment():\n        resources.append(resource.Resource(\n            _AWS_EC2_INSTANCE,\n            (aws_identity_doc_utils.AwsIdentityDocumentUtils()\n             .get_aws_metadata())))\n    if not resources:\n        return None\n    return resource.merge_resources(resources)",
    "docstring": "Get a resource based on the application environment.\n\n    Returns a `Resource` configured for the current environment, or None if the\n    environment is unknown or unsupported.\n\n    :rtype: :class:`opencensus.common.resource.Resource` or None\n    :return: A `Resource` configured for the current environment."
  },
  {
    "code": "def group_channels(self, group):\n        path = self._path(group)\n        return [\n            self.objects[p]\n            for p in self.objects\n            if p.startswith(path + '/')]",
    "docstring": "Returns a list of channel objects for the given group\n\n        :param group: Name of the group to get channels for.\n        :rtype: List of :class:`TdmsObject` objects."
  },
  {
    "code": "def tokenize(s):\n    s = re.sub(r'(?a)(\\w+)\\'s', r'\\1', s)\n    split_pattern = r'[{} ]+'.format(re.escape(STOPCHARS))\n    tokens = [token for token in re.split(split_pattern, s) if not set(token) <= set(string.punctuation)]\n    return tokens",
    "docstring": "A simple tokneizer"
  },
  {
    "code": "def ls(manager: Manager, offset: Optional[int], limit: Optional[int]):\n    q = manager.session.query(Edge)\n    if offset:\n        q = q.offset(offset)\n    if limit > 0:\n        q = q.limit(limit)\n    for e in q:\n        click.echo(e.bel)",
    "docstring": "List edges."
  },
  {
    "code": "def register_phone_view(request):\n    if request.method == \"POST\":\n        form = PhoneRegistrationForm(request.POST)\n        logger.debug(form)\n        if form.is_valid():\n            obj = form.save()\n            obj.user = request.user\n            obj.save()\n            messages.success(request, \"Successfully added phone.\")\n            return redirect(\"itemreg\")\n        else:\n            messages.error(request, \"Error adding phone.\")\n    else:\n        form = PhoneRegistrationForm()\n    return render(request, \"itemreg/register_form.html\", {\"form\": form, \"action\": \"add\", \"type\": \"phone\", \"form_route\": \"itemreg_phone\"})",
    "docstring": "Register a phone."
  },
  {
    "code": "def evaluate(self, dataset, metric='auto', missing_value_action='auto'):\n        r\n        _raise_error_evaluation_metric_is_valid(metric,\n                                          ['auto', 'rmse', 'max_error'])\n        return super(LinearRegression, self).evaluate(dataset, missing_value_action=missing_value_action,\n                                                      metric=metric)",
    "docstring": "r\"\"\"Evaluate the model by making target value predictions and comparing\n        to actual values.\n\n        Two metrics are used to evaluate linear regression models.  The first\n        is root-mean-squared error (RMSE) while the second is the absolute\n        value of the maximum error between the actual and predicted values.\n        Let :math:`y` and :math:`\\hat{y}` denote vectors of length :math:`N`\n        (number of examples) with actual and predicted values. The RMSE is\n        defined as:\n\n        .. math::\n\n            RMSE = \\sqrt{\\frac{1}{N} \\sum_{i=1}^N (\\widehat{y}_i - y_i)^2}\n\n        while the max-error is defined as\n\n        .. math::\n\n            max-error = \\max_{i=1}^N \\|\\widehat{y}_i - y_i\\|\n\n        Parameters\n        ----------\n        dataset : SFrame\n            Dataset of new observations. Must include columns with the same\n            names as the target and features used for model training. Additional\n            columns are ignored.\n\n        metric : str, optional\n            Name of the evaluation metric.  Possible values are:\n            - 'auto': Compute all metrics.\n            - 'rmse': Rooted mean squared error.\n            - 'max_error': Maximum error.\n\n        missing_value_action : str, optional\n            Action to perform when missing values are encountered. This can be\n            one of:\n\n            - 'auto': Default to 'impute'\n            - 'impute': Proceed with evaluation by filling in the missing\n              values with the mean of the training data. Missing\n              values are also imputed if an entire column of data is\n              missing during evaluation.\n            - 'error': Do not proceed with evaluation and terminate with\n              an error message.\n\n        Returns\n        -------\n        out : dict\n            Results from  model evaluation procedure.\n\n        See Also\n        ----------\n        create, predict\n\n        Examples\n        ----------\n        >>> data =  turicreate.SFrame('https://static.turi.com/datasets/regression/houses.csv')\n\n        >>> model = turicreate.linear_regression.create(data,\n                                             target='price',\n                                             features=['bath', 'bedroom', 'size'])\n        >>> results = model.evaluate(data)"
  },
  {
    "code": "def remove_custom_field_setting(self, project, params={}, **options): \n        path = \"/projects/%s/removeCustomFieldSetting\" % (project)\n        return self.client.post(path, params, **options)",
    "docstring": "Remove a custom field setting on the project.\n\n        Parameters\n        ----------\n        project : {Id} The project to associate the custom field with\n        [data] : {Object} Data for the request\n          - [custom_field] : {Id} The id of the custom field to remove from this project."
  },
  {
    "code": "def setup_app(command, conf, vars):\n    if not pylons.test.pylonsapp:\n        load_environment(conf.global_conf, conf.local_conf)",
    "docstring": "Place any commands to setup nipapwww here"
  },
  {
    "code": "def get_current_scene_node():\n    c = cmds.namespaceInfo(':', listOnlyDependencyNodes=True, absoluteName=True, dagPath=True)\n    l = cmds.ls(c, type='jb_sceneNode', absoluteName=True)\n    if not l:\n        return\n    else:\n        for n in sorted(l):\n            if not cmds.listConnections(\"%s.reftrack\" % n, d=False):\n                return n",
    "docstring": "Return the name of the jb_sceneNode, that describes the current scene or None if there is no scene node.\n\n    :returns: the full name of the node or none, if there is no scene node\n    :rtype: str | None\n    :raises: None"
  },
  {
    "code": "def _find_statistics(X, y, variogram_function,\n                     variogram_model_parameters, coordinates_type):\n    delta = np.zeros(y.shape)\n    sigma = np.zeros(y.shape)\n    for i in range(y.shape[0]):\n        if i == 0:\n            continue\n        else:\n            k, ss = _krige(X[:i, :], y[:i], X[i, :], variogram_function,\n                           variogram_model_parameters, coordinates_type)\n            if np.absolute(ss) < eps:\n                continue\n            delta[i] = y[i] - k\n            sigma[i] = np.sqrt(ss)\n    delta = delta[sigma > eps]\n    sigma = sigma[sigma > eps]\n    epsilon = delta/sigma\n    return delta, sigma, epsilon",
    "docstring": "Calculates variogram fit statistics.\n    Returns the delta, sigma, and epsilon values for the variogram fit.\n    These arrays are used for statistics calculations.\n\n    Parameters\n    ----------\n    X: ndarray\n        float array [n_samples, n_dim], the input array of coordinates\n    y: ndarray\n        float array [n_samples], the input array of measurement values\n    variogram_function: callable\n        function that will be called to evaluate variogram model\n    variogram_model_parameters: list\n        user-specified parameters for variogram model\n    coordinates_type: str\n        type of coordinates in X array, can be 'euclidean' for standard\n        rectangular coordinates or 'geographic' if the coordinates are lat/lon\n\n    Returns\n    -------\n    delta: ndarray\n        residuals between observed values and kriged estimates for those values\n    sigma: ndarray\n        mean error in kriging estimates\n    epsilon: ndarray\n        residuals normalized by their mean error"
  },
  {
    "code": "def query_decl(self, **kwargs):\n        return self.session.query(Decl).filter_by(**kwargs).all()",
    "docstring": "Query declarations."
  },
  {
    "code": "def variant(self):\n        variant = current_app.config['THEME_VARIANT']\n        if variant not in self.variants:\n            log.warning('Unkown theme variant: %s', variant)\n            return 'default'\n        else:\n            return variant",
    "docstring": "Get the current theme variant"
  },
  {
    "code": "def _get_value(obj, key):\n    if isinstance(obj, (list, tuple)):\n        for item in obj:\n            v = _find_value(key, item)\n            if v is not None:\n                return v\n        return None\n    if isinstance(obj, dict):\n        return obj.get(key)\n    if obj is not None:\n        return getattr(obj, key, None)",
    "docstring": "Get a value for 'key' from 'obj', if possible"
  },
  {
    "code": "def _arg(__decorated__, **Config):\n  r\n  if isinstance(__decorated__, tuple):\n    __decorated__[1].insert(0, Config)\n    return __decorated__\n  else:\n    return __decorated__, [Config]",
    "docstring": "r\"\"\"The worker for the arg decorator."
  },
  {
    "code": "def ListGrrBinaries(context=None):\n  items = context.SendIteratorRequest(\"ListGrrBinaries\", None)\n  return utils.MapItemsIterator(\n      lambda data: GrrBinary(data=data, context=context), items)",
    "docstring": "Lists all registered Grr binaries."
  },
  {
    "code": "def _ListTags(self):\n    all_tags = []\n    self._cursor.execute('SELECT DISTINCT tag FROM log2timeline')\n    tag_row = self._cursor.fetchone()\n    while tag_row:\n      tag_string = tag_row[0]\n      if tag_string:\n        tags = tag_string.split(',')\n        for tag in tags:\n          if tag not in all_tags:\n            all_tags.append(tag)\n      tag_row = self._cursor.fetchone()\n    return all_tags",
    "docstring": "Query database for unique tag types."
  },
  {
    "code": "def hover(self, target=None):\n        if target is None:\n            target = self._lastMatch or self\n        target_location = None\n        if isinstance(target, Pattern):\n            target_location = self.find(target).getTarget()\n        elif isinstance(target, basestring):\n            target_location = self.find(target).getTarget()\n        elif isinstance(target, Match):\n            target_location = target.getTarget()\n        elif isinstance(target, Region):\n            target_location = target.getCenter()\n        elif isinstance(target, Location):\n            target_location = target\n        else:\n            raise TypeError(\"hover expected Pattern, String, Match, Region, or Location object\")\n        Mouse.moveSpeed(target_location, Settings.MoveMouseDelay)",
    "docstring": "Moves the cursor to the target location"
  },
  {
    "code": "def wrap_resource(self, pool, resource_wrapper):\n        resource = resource_wrapper(self.resource, pool)\n        self._weakref = weakref.ref(resource)\n        return resource",
    "docstring": "Return a resource wrapped in ``resource_wrapper``.\n\n        :param pool: A pool instance.\n        :type pool: :class:`CuttlePool`\n        :param resource_wrapper: A wrapper class for the resource.\n        :type resource_wrapper: :class:`Resource`\n        :return: A wrapped resource.\n        :rtype: :class:`Resource`"
  },
  {
    "code": "def get_nodes(self, resolve_missing=False):\n        result = []\n        resolved = False\n        for node_id in self._node_ids:\n            try:\n                node = self._result.get_node(node_id)\n            except exception.DataIncomplete:\n                node = None\n            if node is not None:\n                result.append(node)\n                continue\n            if not resolve_missing:\n                raise exception.DataIncomplete(\"Resolve missing nodes is disabled\")\n            if resolved:\n                raise exception.DataIncomplete(\"Unable to resolve all nodes\")\n            query = (\"\\n\"\n                     \"[out:json];\\n\"\n                     \"way({way_id});\\n\"\n                     \"node(w);\\n\"\n                     \"out body;\\n\"\n                     )\n            query = query.format(\n                way_id=self.id\n            )\n            tmp_result = self._result.api.query(query)\n            self._result.expand(tmp_result)\n            resolved = True\n            try:\n                node = self._result.get_node(node_id)\n            except exception.DataIncomplete:\n                node = None\n            if node is None:\n                raise exception.DataIncomplete(\"Unable to resolve all nodes\")\n            result.append(node)\n        return result",
    "docstring": "Get the nodes defining the geometry of the way\n\n        :param resolve_missing: Try to resolve missing nodes.\n        :type resolve_missing: Boolean\n        :return: List of nodes\n        :rtype: List of overpy.Node\n        :raises overpy.exception.DataIncomplete: At least one referenced node is not available in the result cache.\n        :raises overpy.exception.DataIncomplete: If resolve_missing is True and at least one node can't be resolved."
  },
  {
    "code": "def return_single_convert_numpy_base(dbpath, folder_path, set_object, object_id, converter, add_args=None):\n    engine = create_engine('sqlite:////' + dbpath)\n    session_cl = sessionmaker(bind=engine)\n    session = session_cl()\n    tmp_object = session.query(set_object).get(object_id)\n    session.close()\n    if add_args is None:\n        return converter(join(folder_path, tmp_object.path))\n    else:\n        return converter(join(folder_path, tmp_object.path), add_args)",
    "docstring": "Generic function which converts an object specified by the object_id into a numpy array and returns the array,\n    the conversion is done by the 'converter' function\n\n    Parameters\n    ----------\n    dbpath : string, path to SQLite database file\n    folder_path : string, path to folder where the files are stored\n    set_object : object (either TestSet or TrainSet) which is stored in the database\n    object_id : int, id of object in database\n    converter : function, which takes the path of a data point and *args as parameters and returns a numpy array\n    add_args : optional arguments for the converter (list/dictionary/tuple/whatever). if None, the\n    converter should take only one input argument - the file path. default value: None\n\n    Returns\n    -------\n    result : ndarray"
  },
  {
    "code": "def serializable_value(self, obj):\n        value = self.__get__(obj, obj.__class__)\n        return self.property.serialize_value(value)",
    "docstring": "Produce the value as it should be serialized.\n\n        Sometimes it is desirable for the serialized value to differ from\n        the ``__get__`` in order for the ``__get__`` value to appear simpler\n        for user or developer convenience.\n\n        Args:\n            obj (HasProps) : the object to get the serialized attribute for\n\n        Returns:\n            JSON-like"
  },
  {
    "code": "def create_option_from_value(tag, value):\n    dhcp_option.parser()\n    fake_opt = dhcp_option(tag = tag)\n    for c in dhcp_option.subclasses:\n        if c.criteria(fake_opt):\n            if hasattr(c, '_parse_from_value'):\n                return c(tag = tag, value = c._parse_from_value(value))\n            else:\n                raise ValueError('Invalid DHCP option ' + str(tag) + \": \" + repr(value))\n    else:\n        fake_opt._setextra(_tobytes(value))\n        return fake_opt",
    "docstring": "Set DHCP option with human friendly value"
  },
  {
    "code": "def inspect_task(self, task):\n        url = self._url('/tasks/{0}', task)\n        return self._result(self._get(url), True)",
    "docstring": "Retrieve information about a task.\n\n        Args:\n            task (str): Task ID\n\n        Returns:\n            (dict): Information about the task.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def _remove_pre_formatting(self):\n        preformatted_wrappers = [\n            'pre',\n            'code'\n        ]\n        for wrapper in preformatted_wrappers:\n            for formatter in FORMATTERS:\n                tag = FORMATTERS[formatter]\n                character = formatter\n                regex = r'(<{w}>.*)<{t}>(.*)</{t}>(.*</{w}>)'.format(\n                    t=tag,\n                    w=wrapper\n                )\n                repl = r'\\g<1>{c}\\g<2>{c}\\g<3>'.format(c=character)\n                self.cleaned_html = re.sub(regex, repl, self.cleaned_html)",
    "docstring": "Removes formatting tags added to pre elements."
  },
  {
    "code": "def get_filename(request, date, size_x, size_y):\n        filename = '_'.join([\n            str(request.service_type.value),\n            request.layer,\n            str(request.bbox.crs),\n            str(request.bbox).replace(',', '_'),\n            '' if date is None else date.strftime(\"%Y-%m-%dT%H-%M-%S\"),\n            '{}X{}'.format(size_x, size_y)\n        ])\n        filename = OgcImageService.filename_add_custom_url_params(filename, request)\n        return OgcImageService.finalize_filename(filename, request.image_format)",
    "docstring": "Get filename location\n\n        Returns the filename's location on disk where data is or is going to be stored.\n        The files are stored in the folder specified by the user when initialising OGC-type\n        of request. The name of the file has the following structure:\n\n        {service_type}_{layer}_{crs}_{bbox}_{time}_{size_x}X{size_y}_*{custom_url_params}.{image_format}\n\n        In case of `TIFF_d32f` a `'_tiff_depth32f'` is added at the end of the filename (before format suffix)\n        to differentiate it from 16-bit float tiff.\n\n        :param request: OGC-type request with specified bounding box, cloud coverage for specific product.\n        :type request: OgcRequest or GeopediaRequest\n        :param date: acquisition date or None\n        :type date: datetime.datetime or None\n        :param size_x: horizontal image dimension\n        :type size_x: int or str\n        :param size_y: vertical image dimension\n        :type size_y: int or str\n        :return: filename for this request and date\n        :rtype: str"
  },
  {
    "code": "def _counts2radiance(self, counts, coefs, channel):\n        logger.debug('Converting counts to radiance')\n        if self._is_vis(channel):\n            slope = np.array(coefs['slope']).mean()\n            offset = np.array(coefs['offset']).mean()\n            return self._viscounts2radiance(counts=counts, slope=slope,\n                                            offset=offset)\n        return self._ircounts2radiance(counts=counts, scale=coefs['scale'],\n                                       offset=coefs['offset'])",
    "docstring": "Convert raw detector counts to radiance"
  },
  {
    "code": "def upload_entities_tsv(namespace, workspace, entities_tsv):\n    if isinstance(entities_tsv, string_types):\n        with open(entities_tsv, \"r\") as tsv:\n            entity_data = tsv.read()\n    elif isinstance(entities_tsv, io.StringIO):\n        entity_data = entities_tsv.getvalue()\n    else:\n        raise ValueError('Unsupported input type.')\n    return upload_entities(namespace, workspace, entity_data)",
    "docstring": "Upload entities from a tsv loadfile.\n\n    File-based wrapper for api.upload_entities().\n    A loadfile is a tab-separated text file with a header row\n    describing entity type and attribute names, followed by\n    rows of entities and their attribute values.\n\n        Ex:\n            entity:participant_id   age   alive\n            participant_23           25       Y\n            participant_27           35       N\n\n    Args:\n        namespace (str): project to which workspace belongs\n        workspace (str): Workspace name\n        entities_tsv (file): FireCloud loadfile, see format above"
  },
  {
    "code": "def __output_unpaired_vals(d_vals, used_ff_keys, f_f_header, sf_d, s_f_header,\n                           missing_val, out_handler, outfh, delim=\"\\t\"):\n  if missing_val is None:\n    raise MissingValueError(\"Need missing value to output \" +\n                            \" unpaired lines\")\n  for k in d_vals:\n    if k not in used_ff_keys:\n      f_f_flds = d_vals[k]\n      if s_f_header is not None:\n        s_f_flds = [dict(zip(s_f_header, [missing_val] * len(s_f_header)))]\n      else:\n        s_f_num_cols = len(sf_d[d_vals.keys()[0]][0])\n        s_f_flds = [[missing_val] * s_f_num_cols]\n      out_handler.write_output(outfh, delim, s_f_flds, f_f_flds,\n                               s_f_header, f_f_header)",
    "docstring": "Use an output handler to output keys that could not be paired.\n\n  Go over the keys in d_vals and for any that were not used (i.e. not in\n  used_ff_keys), build an output line using the values from d_vals,\n  populated the missing columns with missing_val, and output these using the\n  provided output hander."
  },
  {
    "code": "def display_completions_like_readline(event):\n    b = event.current_buffer\n    if b.completer is None:\n        return\n    complete_event = CompleteEvent(completion_requested=True)\n    completions = list(b.completer.get_completions(b.document, complete_event))\n    common_suffix = get_common_complete_suffix(b.document, completions)\n    if len(completions) == 1:\n        b.delete_before_cursor(-completions[0].start_position)\n        b.insert_text(completions[0].text)\n    elif common_suffix:\n        b.insert_text(common_suffix)\n    elif completions:\n        _display_completions_like_readline(event.cli, completions)",
    "docstring": "Key binding handler for readline-style tab completion.\n    This is meant to be as similar as possible to the way how readline displays\n    completions.\n\n    Generate the completions immediately (blocking) and display them above the\n    prompt in columns.\n\n    Usage::\n\n        # Call this handler when 'Tab' has been pressed.\n        registry.add_binding(Keys.ControlI)(display_completions_like_readline)"
  },
  {
    "code": "def close(self):\n    endpoint = self.endpoint.replace(\"/api/v1/spans\", \"\")\n    logger.debug(\"Zipkin trace may be located at this URL {}/traces/{}\".format(endpoint, self.trace_id))",
    "docstring": "End the report."
  },
  {
    "code": "def _trim_dictionary_parameters(self, dict_param):\n        keys = re.findall('(?:[^%]|^)?%\\((\\w*)\\)[a-z]', self.msgid)\n        if not keys and re.findall('(?:[^%]|^)%[a-z]', self.msgid):\n            params = self._copy_param(dict_param)\n        else:\n            params = {}\n            src = {}\n            if isinstance(self.params, dict):\n                src.update(self.params)\n            src.update(dict_param)\n            for key in keys:\n                params[key] = self._copy_param(src[key])\n        return params",
    "docstring": "Return a dict that only has matching entries in the msgid."
  },
  {
    "code": "def resumption_token(parent, pagination, **kwargs):\n    if pagination.page == 1 and not pagination.has_next:\n        return\n    token = serialize(pagination, **kwargs)\n    e_resumptionToken = SubElement(parent, etree.QName(NS_OAIPMH,\n                                                       'resumptionToken'))\n    if pagination.total:\n        expiration_date = datetime.utcnow() + timedelta(\n            seconds=current_app.config[\n                'OAISERVER_RESUMPTION_TOKEN_EXPIRE_TIME'\n            ]\n        )\n        e_resumptionToken.set('expirationDate', datetime_to_datestamp(\n            expiration_date\n        ))\n        e_resumptionToken.set('cursor', str(\n            (pagination.page - 1) * pagination.per_page\n        ))\n        e_resumptionToken.set('completeListSize', str(pagination.total))\n    if token:\n        e_resumptionToken.text = token",
    "docstring": "Attach resumption token element to a parent."
  },
  {
    "code": "def rulefiles(self, acc=None):\n        rulesdir = self.rulesdir(acc)\n        rules = [os.path.join(rulesdir, x) for x in self.get('rules', acc, [])]\n        if acc is not None:\n            rules += self.rulefiles(acc=None)\n        return rules",
    "docstring": "Return a list of rulefiles for the given account.\n\n        Returns an empty list if none specified."
  },
  {
    "code": "def get_parler_languages_from_django_cms(cms_languages=None):\n    valid_keys = ['code', 'fallbacks', 'hide_untranslated',\n                  'redirect_on_fallback']\n    if cms_languages:\n        if sys.version_info < (3, 0, 0):\n            int_types = (int, long)\n        else:\n            int_types = int\n        parler_languages = copy.deepcopy(cms_languages)\n        for site_id, site_config in cms_languages.items():\n            if site_id and (\n                    not isinstance(site_id, int_types) and\n                    site_id != 'default'\n            ):\n                del parler_languages[site_id]\n                continue\n            if site_id == 'default':\n                for key, value in site_config.items():\n                    if key not in valid_keys:\n                        del parler_languages['default'][key]\n            else:\n                for i, lang_config in enumerate(site_config):\n                    for key, value in lang_config.items():\n                        if key not in valid_keys:\n                            del parler_languages[site_id][i][key]\n        return parler_languages\n    return None",
    "docstring": "Converts django CMS' setting CMS_LANGUAGES into PARLER_LANGUAGES. Since\n    CMS_LANGUAGES is a strict superset of PARLER_LANGUAGES, we do a bit of\n    cleansing to remove irrelevant items."
  },
  {
    "code": "def mapping_of(cls):\n    def mapper(data):\n        if not isinstance(data, Mapping):\n            raise TypeError(\n                \"data must be a mapping, not %s\"\n                % type(data).__name__)\n        return {\n            key: cls(value)\n            for key, value in data.items()\n        }\n    return mapper",
    "docstring": "Expects a mapping from some key to data for `cls` instances."
  },
  {
    "code": "def usufyToGmlExport(d, fPath):\n    try:\n        oldData=nx.read_gml(fPath)\n    except UnicodeDecodeError as e:\n        print(\"UnicodeDecodeError:\\t\" + str(e))\n        print(\"Something went wrong when reading the .gml file relating to the decoding of UNICODE.\")\n        import time as time\n        fPath+=\"_\" +str(time.time())\n        print(\"To avoid losing data, the output file will be renamed to use the timestamp as:\\n\" + fPath + \"_\" + str(time.time()))\n        print()\n        oldData = nx.Graph()\n    except Exception as e:\n        oldData = nx.Graph()\n    newGraph = _generateGraphData(d, oldData)\n    nx.write_gml(newGraph,fPath)",
    "docstring": "Workaround to export data to a .gml file.\n\n    Args:\n    -----\n        d: Data to export.\n        fPath: File path for the output file."
  },
  {
    "code": "def detectTierTablet(self):\n        return self.detectIpad() \\\n            or self.detectAndroidTablet() \\\n            or self.detectBlackBerryTablet() \\\n            or self.detectFirefoxOSTablet() \\\n            or self.detectUbuntuTablet() \\\n            or self.detectWebOSTablet()",
    "docstring": "Return detection of any device in the Tablet Tier\n\n        The quick way to detect for a tier of devices.\n        This method detects for the new generation of\n        HTML 5 capable, larger screen tablets.\n        Includes iPad, Android (e.g., Xoom), BB Playbook, WebOS, etc."
  },
  {
    "code": "def __get_line_profile_data(self):\n        if self.line_profiler is None:\n            return {}\n        return self.line_profiler.file_dict[self.pyfile.path][0].line_dict",
    "docstring": "Method to procure line profiles.\n\n           @return: Line profiles if the file has been profiles else empty\n           dictionary."
  },
  {
    "code": "def _check_graph(self, graph):\n        if graph.num_vertices != self.size:\n            raise TypeError(\"The number of vertices in the graph does not \"\n                \"match the length of the atomic numbers array.\")\n        if (self.numbers != graph.numbers).any():\n            raise TypeError(\"The atomic numbers in the graph do not match the \"\n                \"atomic numbers in the molecule.\")",
    "docstring": "the atomic numbers must match"
  },
  {
    "code": "def right(self):\n        return self.source.directory[self.right_sibling_id] \\\n            if self.right_sibling_id != NOSTREAM else None",
    "docstring": "Entry is right sibling of current directory entry"
  },
  {
    "code": "def mkdir(self, path):\n        if not os.path.exists(path):\n            os.makedirs(path)",
    "docstring": "create a directory if it does not exist."
  },
  {
    "code": "def read_config(self, correlation_id, parameters):\n        value = self._read_object(correlation_id, parameters)\n        return ConfigParams.from_value(value)",
    "docstring": "Reads configuration and parameterize it with given values.\n\n        :param correlation_id: (optional) transaction id to trace execution through call chain.\n\n        :param parameters: values to parameters the configuration or null to skip parameterization.\n\n        :return: ConfigParams configuration."
  },
  {
    "code": "def tile_bbox(self, tile_indices):\n        (z, x, y) = tile_indices\n        topleft = (x * self.tilesize, (y + 1) * self.tilesize)\n        bottomright = ((x + 1) * self.tilesize, y * self.tilesize)\n        nw = self.unproject_pixels(topleft, z)\n        se = self.unproject_pixels(bottomright, z)\n        return nw + se",
    "docstring": "Returns the WGS84 bbox of the specified tile"
  },
  {
    "code": "def spacing(self):\n        libfn = utils.get_lib_fn('getSpacing%s'%self._libsuffix)\n        return libfn(self.pointer)",
    "docstring": "Get image spacing\n\n        Returns\n        -------\n        tuple"
  },
  {
    "code": "def upload_package(context):\n    if not context.dry_run and build_distributions(context):\n        upload_args = 'twine upload '\n        upload_args += ' '.join(Path('dist').files())\n        if context.pypi:\n            upload_args += ' -r %s' % context.pypi\n        upload_result = shell.dry_run(upload_args, context.dry_run)\n        if not context.dry_run and not upload_result:\n            raise Exception('Error uploading: %s' % upload_result)\n        else:\n            log.info(\n                'Successfully uploaded %s:%s', context.module_name, context.new_version\n            )\n    else:\n        log.info('Dry run, skipping package upload')",
    "docstring": "Uploads your project packages to pypi with twine."
  },
  {
    "code": "def printdir(self):\n        print \"%-46s %19s %12s\" % (\"File Name\", \"Modified    \", \"Size\")\n        for zinfo in self.filelist:\n            date = \"%d-%02d-%02d %02d:%02d:%02d\" % zinfo.date_time[:6]\n            print \"%-46s %s %12d\" % (zinfo.filename, date, zinfo.file_size)",
    "docstring": "Print a table of contents for the zip file."
  },
  {
    "code": "def _update_record(self, record_id, name, address, ttl):\n        data = json.dumps({'record': {'name': name,\n                                      'content': address,\n                                      'ttl': ttl}})\n        headers = {'Content-Type': 'application/json'}\n        request = self._session.put(self._baseurl + '/%d' % record_id,\n                                    data=data, headers=headers)\n        if not request.ok:\n            raise RuntimeError('Failed to update record: %s - %s' %\n                               (self._format_hostname(name), request.json()))\n        record = request.json()\n        if 'record' not in record or 'id' not in record['record']:\n            raise RuntimeError('Invalid record JSON format: %s - %s' %\n                               (self._format_hostname(name), request.json()))\n        return record['record']",
    "docstring": "Updates an existing record."
  },
  {
    "code": "def record(self, partition, num_bytes, num_records):\n        self.unrecorded_partitions.remove(partition)\n        self.total_bytes += num_bytes\n        self.total_records += num_records\n        if not self.unrecorded_partitions:\n            self.sensors.bytes_fetched.record(self.total_bytes)\n            self.sensors.records_fetched.record(self.total_records)",
    "docstring": "After each partition is parsed, we update the current metric totals\n        with the total bytes and number of records parsed. After all partitions\n        have reported, we write the metric."
  },
  {
    "code": "async def on_raw_317(self, message):\n        target, nickname, idle_time = message.params[:3]\n        info = {\n            'idle': int(idle_time),\n        }\n        if nickname in self._pending['whois']:\n            self._whois_info[nickname].update(info)",
    "docstring": "WHOIS idle time."
  },
  {
    "code": "def groups(self, query=None, exclude=None, maxResults=9999):\n        params = {}\n        groups = []\n        if query is not None:\n            params['query'] = query\n        if exclude is not None:\n            params['exclude'] = exclude\n        if maxResults is not None:\n            params['maxResults'] = maxResults\n        for group in self._get_json('groups/picker', params=params)['groups']:\n            groups.append(group['name'])\n        return sorted(groups)",
    "docstring": "Return a list of groups matching the specified criteria.\n\n        :param query: filter groups by name with this string\n        :type query: Optional[str]\n        :param exclude: filter out groups by name with this string\n        :type exclude: Optional[Any]\n        :param maxResults: maximum results to return. (Default: 9999)\n        :type maxResults: int\n        :rtype: List[str]"
  },
  {
    "code": "def create_todo_item(self, list_id, content, party_id=None, notify=False):\n        path = '/todos/create_item/%u' % list_id\n        req = ET.Element('request')\n        ET.SubElement(req, 'content').text = str(content)\n        if party_id is not None:\n            ET.SubElement(req, 'responsible-party').text = str(party_id)\n            ET.SubElement(req, 'notify').text = str(bool(notify)).lower()\n        return self._request(path, req)",
    "docstring": "This call lets you add an item to an existing list. The item is added\n        to the bottom of the list. If a person is responsible for the item,\n        give their id as the party_id value. If a company is responsible,\n        prefix their company id with a 'c' and use that as the party_id value.\n        If the item has a person as the responsible party, you can use the\n        notify key to indicate whether an email should be sent to that person\n        to tell them about the assignment."
  },
  {
    "code": "def _list_keys(self):\n        req = self.request(self.uri + '/keys')\n        keys = req.get().json()\n        if keys:\n            self._keys = {}\n            for key in keys:\n                self._keys[key['id']] = Key(key, self)\n        else:\n            self._keys = {}",
    "docstring": "Retrieves a list of all added Keys and populates the\n        self._keys dict with Key instances\n\n        :returns: A list of Keys instances"
  },
  {
    "code": "def _fetch_all_as_dict(self, cursor):\n        desc = cursor.description\n        return [\n            dict(zip([col[0] for col in desc], row))\n            for row in cursor.fetchall()\n        ]",
    "docstring": "Iterates over the result set and converts each row to a dictionary\n\n        :return: A list of dictionaries where each row is a dictionary\n        :rtype: list of dict"
  },
  {
    "code": "def combine(self, expert_out, multiply_by_gates=True):\n    stitched = common_layers.convert_gradient_to_tensor(\n        tf.concat(expert_out, 0))\n    if multiply_by_gates:\n      stitched *= tf.expand_dims(self._nonzero_gates, 1)\n    combined = tf.unsorted_segment_sum(stitched, self._batch_index,\n                                       tf.shape(self._gates)[0])\n    return combined",
    "docstring": "Sum together the expert output, weighted by the gates.\n\n    The slice corresponding to a particular batch element `b` is computed\n    as the sum over all experts `i` of the expert output, weighted by the\n    corresponding gate values.  If `multiply_by_gates` is set to False, the\n    gate values are ignored.\n\n    Args:\n      expert_out: a list of `num_experts` `Tensor`s, each with shape\n        `[expert_batch_size_i, <extra_output_dims>]`.\n      multiply_by_gates: a boolean\n\n    Returns:\n      a `Tensor` with shape `[batch_size, <extra_output_dims>]`."
  },
  {
    "code": "def annotate_intervals(target_file, data):\n    out_file = \"%s-gcannotated.tsv\" % utils.splitext_plus(target_file)[0]\n    if not utils.file_uptodate(out_file, target_file):\n        with file_transaction(data, out_file) as tx_out_file:\n            params = [\"-T\", \"AnnotateIntervals\", \"-R\", dd.get_ref_file(data),\n                      \"-L\", target_file,\n                      \"--interval-merging-rule\", \"OVERLAPPING_ONLY\",\n                      \"-O\", tx_out_file]\n            _run_with_memory_scaling(params, tx_out_file, data)\n    return out_file",
    "docstring": "Provide GC annotated intervals for error correction during panels and denoising.\n\n    TODO: include mappability and segmentation duplication inputs"
  },
  {
    "code": "def make_request_validator(request):\n    verb = request.values.get('verb', '', type=str)\n    resumption_token = request.values.get('resumptionToken', None)\n    schema = Verbs if resumption_token is None else ResumptionVerbs\n    return getattr(schema, verb, OAISchema)(partial=False)",
    "docstring": "Validate arguments in incomming request."
  },
  {
    "code": "def _radial_distance(shape):\n    if len(shape) != 2:\n        raise ValueError('shape must have only 2 elements')\n    position = (np.asarray(shape) - 1) / 2.\n    x = np.arange(shape[1]) - position[1]\n    y = np.arange(shape[0]) - position[0]\n    xx, yy = np.meshgrid(x, y)\n    return np.sqrt(xx**2 + yy**2)",
    "docstring": "Return an array where each value is the Euclidean distance from the\n    array center.\n\n    Parameters\n    ----------\n    shape : tuple of int\n        The size of the output array along each axis.\n\n    Returns\n    -------\n    result : `~numpy.ndarray`\n        An array containing the Euclidian radial distances from the\n        array center."
  },
  {
    "code": "async def fetch(self, limit: int = None) -> Sequence[StorageRecord]:\n        LOGGER.debug('StorageRecordSearch.fetch >>> limit: %s', limit)\n        if not self.opened:\n            LOGGER.debug('StorageRecordSearch.fetch <!< Storage record search is closed')\n            raise BadSearch('Storage record search is closed')\n        if not self._wallet.opened:\n            LOGGER.debug('StorageRecordSearch.fetch <!< Wallet %s is closed', self._wallet.name)\n            raise WalletState('Wallet {} is closed'.format(self._wallet.name))\n        records = json.loads(await non_secrets.fetch_wallet_search_next_records(\n            self._wallet.handle,\n            self.handle,\n            limit or Wallet.DEFAULT_CHUNK))['records'] or []\n        rv = [StorageRecord(typ=rec['type'], value=rec['value'], tags=rec['tags'], ident=rec['id']) for rec in records]\n        LOGGER.debug('StorageRecordSearch.fetch <<< %s', rv)\n        return rv",
    "docstring": "Fetch next batch of search results.\n\n        Raise BadSearch if search is closed, WalletState if wallet is closed.\n\n        :param limit: maximum number of records to return (default value Wallet.DEFAULT_CHUNK)\n        :return: next batch of records found"
  },
  {
    "code": "def _check_metrics(cls, schema, metrics):\n        for name, value in metrics.items():\n            metric = schema.get(name)\n            if not metric:\n                message = \"Unexpected metric '{}' returned\".format(name)\n                raise Exception(message)\n            cls._check_metric(schema, metric, name, value)",
    "docstring": "Ensure that returned metrics are properly exposed"
  },
  {
    "code": "def purge_queues(self, queues):\n        for name, vhost in queues:\n            vhost = quote(vhost, '')\n            name = quote(name, '')\n            path = Client.urls['purge_queue'] % (vhost, name)\n            self._call(path, 'DELETE')\n        return True",
    "docstring": "Purge all messages from one or more queues.\n\n        :param list queues: A list of ('qname', 'vhost') tuples.\n        :returns: True on success"
  },
  {
    "code": "def hash_data(data, hashlen=None, alphabet=None):\n    r\n    if alphabet is None:\n        alphabet = ALPHABET_27\n    if hashlen is None:\n        hashlen = HASH_LEN2\n    if isinstance(data, stringlike) and len(data) == 0:\n        text = (alphabet[0] * hashlen)\n    else:\n        hasher = hashlib.sha512()\n        _update_hasher(hasher, data)\n        text = hasher.hexdigest()\n        hashstr2 = convert_hexstr_to_bigbase(text, alphabet, bigbase=len(alphabet))\n        text = hashstr2[:hashlen]\n        return text",
    "docstring": "r\"\"\"\n    Get a unique hash depending on the state of the data.\n\n    Args:\n        data (object): any sort of loosely organized data\n        hashlen (None): (default = None)\n        alphabet (None): (default = None)\n\n    Returns:\n        str: text -  hash string\n\n    CommandLine:\n        python -m utool.util_hash hash_data\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_hash import *  # NOQA\n        >>> import utool as ut\n        >>> counter = [0]\n        >>> failed = []\n        >>> def check_hash(input_, want=None):\n        >>>     count = counter[0] = counter[0] + 1\n        >>>     got = ut.hash_data(input_)\n        >>>     print('({}) {}'.format(count, got))\n        >>>     if want is not None and not got.startswith(want):\n        >>>         failed.append((got, input_, count, want))\n        >>> check_hash('1', 'wuvrng')\n        >>> check_hash(['1'], 'dekbfpby')\n        >>> check_hash(tuple(['1']), 'dekbfpby')\n        >>> check_hash(b'12', 'marreflbv')\n        >>> check_hash([b'1', b'2'], 'nwfs')\n        >>> check_hash(['1', '2', '3'], 'arfrp')\n        >>> check_hash(['1', np.array([1,2,3]), '3'], 'uyqwcq')\n        >>> check_hash('123', 'ehkgxk')\n        >>> check_hash(zip([1, 2, 3], [4, 5, 6]), 'mjcpwa')\n        >>> import numpy as np\n        >>> rng = np.random.RandomState(0)\n        >>> check_hash(rng.rand(100000), 'bdwosuey')\n        >>> for got, input_, count, want in failed:\n        >>>     print('failed {} on {}'.format(count, input_))\n        >>>     print('got={}, want={}'.format(got, want))\n        >>> assert not failed"
  },
  {
    "code": "async def user_info(self, params=None, **kwargs):\n        params = params or {}\n        params[\n            'fields'] = 'id,email,first_name,last_name,name,link,locale,' \\\n                        'gender,location'\n        return await super(FacebookClient, self).user_info(params=params, **kwargs)",
    "docstring": "Facebook required fields-param."
  },
  {
    "code": "def load_sources(self, sources):\n        self.clear()\n        for s in sources:\n            if isinstance(s, dict):\n                s = Model.create_from_dict(s)\n            self.load_source(s, build_index=False)\n        self._build_src_index()",
    "docstring": "Delete all sources in the ROI and load the input source list."
  },
  {
    "code": "def delete_nic(self, instance_id, port_id):\n        self.client.servers.interface_detach(instance_id, port_id)\n        return True",
    "docstring": "Delete a Network Interface Controller"
  },
  {
    "code": "def issuperset(self, items):\n        return all(_compat.map(self._seen.__contains__, items))",
    "docstring": "Return whether this collection contains all items.\n\n        >>> Unique(['spam', 'eggs']).issuperset(['spam', 'spam', 'spam'])\n        True"
  },
  {
    "code": "def where_before_entry(query, ref):\n    return orm.select(\n        e for e in query\n        if e.local_date < ref.local_date or\n        (e.local_date == ref.local_date and e.id < ref.id)\n    )",
    "docstring": "Generate a where clause for prior entries\n\n    ref -- The entry of reference"
  },
  {
    "code": "def Describe(self):\n    result = [\"\\nUsername: %s\" % self.urn.Basename()]\n    labels = [l.name for l in self.GetLabels()]\n    result.append(\"Labels: %s\" % \",\".join(labels))\n    if self.Get(self.Schema.PASSWORD) is None:\n      result.append(\"Password: not set\")\n    else:\n      result.append(\"Password: set\")\n    return \"\\n\".join(result)",
    "docstring": "Return a description of this user."
  },
  {
    "code": "def _uninstall_signal_handlers(self):\n        signal.signal(signal.SIGINT, signal.SIG_DFL)\n        signal.signal(signal.SIGTERM, signal.SIG_DFL)",
    "docstring": "Restores default signal handlers."
  },
  {
    "code": "def _insert_row(self, i, index):\n        if i == len(self._index):\n            self._add_row(index)\n        else:\n            self._index.insert(i, index)\n            for c in range(len(self._columns)):\n                self._data[c].insert(i, None)",
    "docstring": "Insert a new row in the DataFrame.\n\n        :param i: index location to insert\n        :param index: index value to insert into the index list\n        :return: nothing"
  },
  {
    "code": "def _parse_subnet(self, subnet_dict):\n        if not subnet_dict:\n            return\n        alloc_pool = subnet_dict.get('allocation_pools')\n        cidr = subnet_dict.get('cidr')\n        subnet = cidr.split('/')[0]\n        start = alloc_pool[0].get('start')\n        end = alloc_pool[0].get('end')\n        gateway = subnet_dict.get('gateway_ip')\n        sec_gateway = subnet_dict.get('secondary_gw')\n        return {'subnet': subnet, 'start': start, 'end': end,\n                'gateway': gateway, 'sec_gateway': sec_gateway}",
    "docstring": "Return the subnet, start, end, gateway of a subnet."
  },
  {
    "code": "def relation_factory(relation_name):\n    role, interface = hookenv.relation_to_role_and_interface(relation_name)\n    if not (role and interface):\n        hookenv.log('Unable to determine role and interface for relation '\n                    '{}'.format(relation_name), hookenv.ERROR)\n        return None\n    return _find_relation_factory(_relation_module(role, interface))",
    "docstring": "Get the RelationFactory for the given relation name.\n\n    Looks for a RelationFactory in the first file matching:\n    ``$CHARM_DIR/hooks/relations/{interface}/{provides,requires,peer}.py``"
  },
  {
    "code": "def mapValues(self, f):\n        map_values_fn = lambda kv: (kv[0], f(kv[1]))\n        return self.map(map_values_fn, preservesPartitioning=True)",
    "docstring": "Pass each value in the key-value pair RDD through a map function\n        without changing the keys; this also retains the original RDD's\n        partitioning.\n\n        >>> x = sc.parallelize([(\"a\", [\"apple\", \"banana\", \"lemon\"]), (\"b\", [\"grapes\"])])\n        >>> def f(x): return len(x)\n        >>> x.mapValues(f).collect()\n        [('a', 3), ('b', 1)]"
  },
  {
    "code": "def get_linked_metadata(obj, name=None, context=None, site=None, language=None):\n    Metadata = _get_metadata_model(name)\n    InstanceMetadata = Metadata._meta.get_model('modelinstance')\n    ModelMetadata = Metadata._meta.get_model('model')\n    content_type = ContentType.objects.get_for_model(obj)\n    instances = []\n    if InstanceMetadata is not None:\n        try:\n            instance_md = InstanceMetadata.objects.get(_content_type=content_type, _object_id=obj.pk)\n        except InstanceMetadata.DoesNotExist:\n            instance_md = InstanceMetadata(_content_object=obj)\n        instances.append(instance_md)\n    if ModelMetadata is not None:\n        try:\n            model_md = ModelMetadata.objects.get(_content_type=content_type)\n        except ModelMetadata.DoesNotExist:\n            model_md = ModelMetadata(_content_type=content_type)\n        instances.append(model_md)    \n    return FormattedMetadata(Metadata, instances, '', site, language)",
    "docstring": "Gets metadata linked from the given object."
  },
  {
    "code": "def FilterFnTable(fn_table, symbol):\n  new_table = list()\n  for entry in fn_table:\n    if entry[0] != symbol:\n      new_table.append(entry)\n  return new_table",
    "docstring": "Remove a specific symbol from a fn_table."
  },
  {
    "code": "def map_legend_attributes(self):\n        LOGGER.debug('InaSAFE Map getMapLegendAttributes called')\n        legend_attribute_list = [\n            'legend_notes',\n            'legend_units',\n            'legend_title']\n        legend_attribute_dict = {}\n        for legend_attribute in legend_attribute_list:\n            try:\n                legend_attribute_dict[legend_attribute] = \\\n                    self._keyword_io.read_keywords(\n                        self.impact, legend_attribute)\n            except KeywordNotFoundError:\n                pass\n            except Exception:\n                pass\n        return legend_attribute_dict",
    "docstring": "Get the map legend attribute from the layer keywords if possible.\n\n        :returns: None on error, otherwise the attributes (notes and units).\n        :rtype: None, str"
  },
  {
    "code": "def write_to_path(self, path=None):\n        if path is None:\n            path = self.path\n        f = GitFile(path, 'wb')\n        try:\n            self.write_to_file(f)\n        finally:\n            f.close()",
    "docstring": "Write configuration to a file on disk."
  },
  {
    "code": "def get_languages(self):\n        languages = ['python']\n        all_options = CONF.options(self.CONF_SECTION)\n        for option in all_options:\n            if option in [l.lower() for l in LSP_LANGUAGES]:\n                languages.append(option)\n        return languages",
    "docstring": "Get the list of languages we need to start servers and create\n        clients for."
  },
  {
    "code": "def make_error_redirect(self, authorization_error=None):\n    if not self.redirect_uri:\n      return HttpResponseRedirect(self.missing_redirect_uri)\n    authorization_error = (authorization_error or\n                           AccessDenied('user denied the request'))\n    response_params = get_error_details(authorization_error)\n    if self.state is not None:\n      response_params['state'] = self.state\n    return HttpResponseRedirect(\n        update_parameters(self.redirect_uri, response_params))",
    "docstring": "Return a Django ``HttpResponseRedirect`` describing the request failure.\n\n    If the :py:meth:`validate` method raises an error, the authorization\n    endpoint should return the result of calling this method like so:\n\n      >>> auth_code_generator = (\n      >>>     AuthorizationCodeGenerator('/oauth2/missing_redirect_uri/'))\n      >>> try:\n      >>>   auth_code_generator.validate(request)\n      >>> except AuthorizationError as authorization_error:\n      >>>   return auth_code_generator.make_error_redirect(authorization_error)\n\n    If there is no known Client ``redirect_uri`` (because it is malformed, or\n    the Client is invalid, or if the supplied ``redirect_uri`` does not match\n    the regsitered value, or some other request failure) then the response will\n    redirect to the ``missing_redirect_uri`` passed to the :py:meth:`__init__`\n    method.\n\n    Also used to signify user denial; call this method without passing in the\n    optional ``authorization_error`` argument to return a generic\n    :py:class:`AccessDenied` message.\n\n      >>> if not user_accepted_request:\n      >>>   return auth_code_generator.make_error_redirect()"
  },
  {
    "code": "def get_image_uri(region_name, repo_name, repo_version=1):\n    repo = '{}:{}'.format(repo_name, repo_version)\n    return '{}/{}'.format(registry(region_name, repo_name), repo)",
    "docstring": "Return algorithm image URI for the given AWS region, repository name, and repository version"
  },
  {
    "code": "def _pick_lead_item(items):\n    paired = vcfutils.get_paired(items)\n    if paired:\n        return paired.tumor_data\n    else:\n        return list(items)[0]",
    "docstring": "Choose lead item for a set of samples.\n\n    Picks tumors for tumor/normal pairs and first sample for batch groups."
  },
  {
    "code": "def get_hierarchy_form(self, *args, **kwargs):\n        if isinstance(args[-1], list) or 'hierarchy_record_types' in kwargs:\n            return self.get_hierarchy_form_for_create(*args, **kwargs)\n        else:\n            return self.get_hierarchy_form_for_update(*args, **kwargs)",
    "docstring": "Pass through to provider HierarchyAdminSession.get_hierarchy_form_for_update"
  },
  {
    "code": "def cache_set(key, value, timeout=None, refreshed=False):\n    if timeout is None:\n        timeout = settings.CACHE_MIDDLEWARE_SECONDS\n    refresh_time = timeout + time()\n    real_timeout = timeout + settings.CACHE_SET_DELAY_SECONDS\n    packed = (value, refresh_time, refreshed)\n    return cache.set(_hashed_key(key), packed, real_timeout)",
    "docstring": "Wrapper for ``cache.set``. Stores the cache entry packed with\n    the desired cache expiry time. When the entry is retrieved from\n    cache, the packed expiry time is also checked, and if past,\n    the stale cache entry is stored again with an expiry that has\n    ``CACHE_SET_DELAY_SECONDS`` added to it. In this case the entry\n    is not returned, so that a cache miss occurs and the entry\n    should be set by the caller, but all other callers will still get\n    the stale entry, so no real cache misses ever occur."
  },
  {
    "code": "def columns_formatter(cls, colname):\n        def wrapper(func):\n            cls.columns_formatters[colname] = func\n            return func\n        return wrapper",
    "docstring": "Decorator to mark a function as columns formatter."
  },
  {
    "code": "def vector(self) -> typing.Tuple[typing.Tuple[float, float], typing.Tuple[float, float]]:\n        ...",
    "docstring": "Return the vector property in relative coordinates.\n\n        Vector will be a tuple of tuples ((y_start, x_start), (y_end, x_end))."
  },
  {
    "code": "def inject_settings(mixed: Union[str, Settings],\n                    context: MutableMapping[str, Any],\n                    fail_silently: bool = False) -> None:\n    if isinstance(mixed, str):\n        try:\n            mixed = import_module(mixed)\n        except Exception:\n            if fail_silently:\n                return\n            raise\n    for key, value in iter_settings(mixed):\n        context[key] = value",
    "docstring": "Inject settings values to given context.\n\n    :param mixed:\n        Settings can be a string (that it will be read from Python path),\n        Python module or dict-like instance.\n    :param context:\n        Context to assign settings key values. It should support dict-like item\n        assingment.\n    :param fail_silently:\n        When enabled and reading settings from Python path ignore errors if\n        given Python path couldn't be loaded."
  },
  {
    "code": "def validate_signed_elements(self, signed_elements):\n        if len(signed_elements) > 2:\n            return False\n        response_tag = '{%s}Response' % OneLogin_Saml2_Constants.NS_SAMLP\n        assertion_tag = '{%s}Assertion' % OneLogin_Saml2_Constants.NS_SAML\n        if (response_tag in signed_elements and signed_elements.count(response_tag) > 1) or \\\n           (assertion_tag in signed_elements and signed_elements.count(assertion_tag) > 1) or \\\n           (response_tag not in signed_elements and assertion_tag not in signed_elements):\n            return False\n        if response_tag in signed_elements:\n            expected_signature_nodes = OneLogin_Saml2_Utils.query(self.document, OneLogin_Saml2_Utils.RESPONSE_SIGNATURE_XPATH)\n            if len(expected_signature_nodes) != 1:\n                raise OneLogin_Saml2_ValidationError(\n                    'Unexpected number of Response signatures found. SAML Response rejected.',\n                    OneLogin_Saml2_ValidationError.WRONG_NUMBER_OF_SIGNATURES_IN_RESPONSE\n                )\n        if assertion_tag in signed_elements:\n            expected_signature_nodes = self.__query(OneLogin_Saml2_Utils.ASSERTION_SIGNATURE_XPATH)\n            if len(expected_signature_nodes) != 1:\n                raise OneLogin_Saml2_ValidationError(\n                    'Unexpected number of Assertion signatures found. SAML Response rejected.',\n                    OneLogin_Saml2_ValidationError.WRONG_NUMBER_OF_SIGNATURES_IN_ASSERTION\n                )\n        return True",
    "docstring": "Verifies that the document has the expected signed nodes.\n\n        :param signed_elements: The signed elements to be checked\n        :type signed_elements: list\n\n        :param raise_exceptions: Whether to return false on failure or raise an exception\n        :type raise_exceptions: Boolean"
  },
  {
    "code": "def print_object_attributes( thing, heading=None, file=None ):\n    if heading : print( '==', heading, '==', file=file )\n    print( '\\n'.join( object_attributes( thing ) ), file=file )",
    "docstring": "Print the attribute names in thing vertically"
  },
  {
    "code": "def execute(self, limit='default', params=None, **kwargs):\n        from ibis.client import execute\n        return execute(self, limit=limit, params=params, **kwargs)",
    "docstring": "If this expression is based on physical tables in a database backend,\n        execute it against that backend.\n\n        Parameters\n        ----------\n        limit : integer or None, default 'default'\n          Pass an integer to effect a specific row limit. limit=None means \"no\n          limit\". The default is whatever is in ibis.options.\n\n        Returns\n        -------\n        result : expression-dependent\n          Result of compiling expression and executing in backend"
  },
  {
    "code": "def call(args, stdout=PIPE, stderr=PIPE):\n    p = Popen(args, stdout=stdout, stderr=stderr)\n    out, err = p.communicate()\n    try:\n        return out.decode(sys.stdout.encoding), err.decode(sys.stdout.encoding)\n    except Exception:\n        return out, err",
    "docstring": "Calls the given arguments in a seperate process\n    and returns the contents of standard out."
  },
  {
    "code": "def computePCs(plink_path,k,bfile,ffile):\n    try:\n        output = subprocess.check_output('%s --version --noweb'%plink_path,shell=True)\n        use_plink = float(output.split(' ')[1][1:-3])>=1.9\n    except:\n        use_plink = False\n    assert bfile!=None, 'Path to bed-file is missing.'\n    assert os.path.exists(bfile+'.bed'), '%s.bed is missing.'%bfile\n    assert os.path.exists(bfile+'.bim'), '%s.bim is missing.'%bfile\n    assert os.path.exists(bfile+'.fam'), '%s.fam is missing.'%bfile\n    out_dir = os.path.split(ffile)[0]\n    if out_dir!='' and (not os.path.exists(out_dir)):\n        os.makedirs(out_dir)\n    if use_plink:\n        computePCsPlink(plink_path,k,out_dir,bfile,ffile)\n    else:\n        computePCsPython(out_dir,k,bfile,ffile)",
    "docstring": "compute the first k principal components\n\n    Input:\n    k            :   number of principal components\n    plink_path   :   plink path\n    bfile        :   binary bed file (bfile.bed, bfile.bim and bfile.fam are required)\n    ffile        :   name of output file"
  },
  {
    "code": "def rescan_file(self, filename, sha256hash, apikey):\n        url = self.base_url + \"file/rescan\"\n        params = {\n            'apikey': apikey,\n            'resource': sha256hash\n        }\n        rate_limit_clear = self.rate_limit()\n        if rate_limit_clear:\n            response = requests.post(url, params=params)\n            if response.status_code == self.HTTP_OK:\n                self.logger.info(\"sent: %s, HTTP: %d, content: %s\", os.path.basename(filename), response.status_code, response.text)\n            elif response.status_code == self.HTTP_RATE_EXCEEDED:\n                    time.sleep(20)\n            else:\n                self.logger.error(\"sent: %s, HTTP: %d\", os.path.basename(filename), response.status_code)\n            return response",
    "docstring": "just send the hash, check the date"
  },
  {
    "code": "def create_logger(log_file, name='logger', cmd=True):\n    import logging\n    logger = logging.getLogger(name)\n    logger.setLevel(logging.DEBUG)\n    formatter = logging.Formatter('%(asctime)s | %(name)s | %(levelname)s | %(message)s',\n                                  datefmt='%Y-%m-%d %H:%M:%S')\n    fh = logging.FileHandler(log_file)\n    fh.setLevel(logging.DEBUG)\n    fh.setFormatter(formatter)\n    logger.addHandler(fh)\n    if cmd:\n        ch = logging.StreamHandler()\n        ch.setLevel(logging.DEBUG)\n        ch.setFormatter(formatter)\n        logger.addHandler(ch)\n    return logger",
    "docstring": "define a logger for your program\n\n    parameters\n    ------------\n    log_file     file name of log\n    name         name of logger\n\n    example\n    ------------\n    logger = create_logger('example.log',name='logger',)\n    logger.info('This is an example!')\n    logger.warning('This is a warn!')"
  },
  {
    "code": "def greedy_max_inden_setcover(candidate_sets_dict, items, max_covers=None):\n    uncovered_set = set(items)\n    rejected_keys = set()\n    accepted_keys = set()\n    covered_items_list = []\n    while True:\n        if max_covers is not None and len(covered_items_list) >= max_covers:\n            break\n        maxkey = None\n        maxlen = -1\n        for key, candidate_items in six.iteritems(candidate_sets_dict):\n            if key in rejected_keys or key in accepted_keys:\n                continue\n            lenval = len(candidate_items)\n            if uncovered_set.issuperset(candidate_items):\n                if lenval > maxlen:\n                    maxkey = key\n                    maxlen = lenval\n            else:\n                rejected_keys.add(key)\n        if maxkey is None:\n            break\n        maxval = candidate_sets_dict[maxkey]\n        accepted_keys.add(maxkey)\n        covered_items_list.append(list(maxval))\n        uncovered_set.difference_update(maxval)\n    uncovered_items = list(uncovered_set)\n    covertup = uncovered_items, covered_items_list, accepted_keys\n    return covertup",
    "docstring": "greedy algorithm for maximum independent set cover\n\n    Covers items with sets from candidate sets. Could be made faster.\n\n    CommandLine:\n        python -m utool.util_alg --test-greedy_max_inden_setcover\n\n    Example0:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_alg import *  # NOQA\n        >>> import utool as ut\n        >>> candidate_sets_dict = {'a': [5, 3], 'b': [2, 3, 5],\n        ...                        'c': [4, 8], 'd': [7, 6, 2, 1]}\n        >>> items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n        >>> max_covers = None\n        >>> tup = greedy_max_inden_setcover(candidate_sets_dict, items, max_covers)\n        >>> (uncovered_items, covered_items_list, accepted_keys) = tup\n        >>> result = ut.repr4((uncovered_items, sorted(list(accepted_keys))), nl=False)\n        >>> print(result)\n        ([0, 9], ['a', 'c', 'd'])\n\n    Example1:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_alg import *  # NOQA\n        >>> import utool as ut\n        >>> candidate_sets_dict = {'a': [5, 3], 'b': [2, 3, 5],\n        ...                        'c': [4, 8], 'd': [7, 6, 2, 1]}\n        >>> items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n        >>> max_covers = 1\n        >>> tup = greedy_max_inden_setcover(candidate_sets_dict, items, max_covers)\n        >>> (uncovered_items, covered_items_list, accepted_keys) = tup\n        >>> result = ut.repr4((uncovered_items, sorted(list(accepted_keys))), nl=False)\n        >>> print(result)\n        ([0, 3, 4, 5, 8, 9], ['d'])"
  },
  {
    "code": "def update_state_machine_tab_label(self, state_machine_m):\n        sm_id = state_machine_m.state_machine.state_machine_id\n        if sm_id in self.tabs:\n            sm = state_machine_m.state_machine\n            if not self.tabs[sm_id]['marked_dirty'] == sm.marked_dirty or \\\n                    not self.tabs[sm_id]['file_system_path'] == sm.file_system_path or \\\n                    not self.tabs[sm_id]['root_state_name'] == sm.root_state.name:\n                label = self.view[\"notebook\"].get_tab_label(self.tabs[sm_id][\"page\"]).get_child().get_children()[0]\n                set_tab_label_texts(label, state_machine_m, unsaved_changes=sm.marked_dirty)\n                self.tabs[sm_id]['file_system_path'] = sm.file_system_path\n                self.tabs[sm_id]['marked_dirty'] = sm.marked_dirty\n                self.tabs[sm_id]['root_state_name'] = sm.root_state.name\n        else:\n            logger.warning(\"State machine '{0}' tab label can not be updated there is no tab.\".format(sm_id))",
    "docstring": "Updates tab label if needed because system path, root state name or marked_dirty flag changed\n\n        :param StateMachineModel state_machine_m: State machine model that has changed\n        :return:"
  },
  {
    "code": "def focus_down(pymux):\n    \" Move focus down. \"\n    _move_focus(pymux,\n                lambda wp: wp.xpos,\n                lambda wp: wp.ypos + wp.height + 2)",
    "docstring": "Move focus down."
  },
  {
    "code": "def widget_from_single_value(o):\n        if isinstance(o, string_types):\n            return Text(value=unicode_type(o))\n        elif isinstance(o, bool):\n            return Checkbox(value=o)\n        elif isinstance(o, Integral):\n            min, max, value = _get_min_max_value(None, None, o)\n            return IntSlider(value=o, min=min, max=max)\n        elif isinstance(o, Real):\n            min, max, value = _get_min_max_value(None, None, o)\n            return FloatSlider(value=o, min=min, max=max)\n        else:\n            return None",
    "docstring": "Make widgets from single values, which can be used as parameter defaults."
  },
  {
    "code": "def churn(self):\n\t\tcanceled = self.canceled().count()\n\t\tactive = self.active().count()\n\t\treturn decimal.Decimal(str(canceled)) / decimal.Decimal(str(active))",
    "docstring": "Return number of canceled Subscriptions divided by active Subscriptions."
  },
  {
    "code": "def get_group_for_col(self, table_name, col_name):\n        df = self.dm[table_name]\n        try:\n            group_name = df.loc[col_name, 'group']\n        except KeyError:\n            return ''\n        return group_name",
    "docstring": "Check data model to find group name for a given column header\n\n        Parameters\n        ----------\n        table_name: str\n        col_name: str\n\n        Returns\n        ---------\n        group_name: str"
  },
  {
    "code": "def _set_hyperparameters(self, parameters):\n        for name, value in parameters.iteritems():\n            try:\n                getattr(self, name)\n            except AttributeError:\n                raise ValueError(\n                    'Each parameter in parameters must be an attribute. '\n                    '{} is not.'.format(name))\n            setattr(self, name, value)",
    "docstring": "Set internal optimization parameters."
  },
  {
    "code": "def create_backend(self, \n\t\tservice_id,\n\t\tversion_number, \n\t\tname, \n\t\taddress,\n\t\tuse_ssl=False,\n\t\tport=80,\n\t\tconnect_timeout=1000,\n\t\tfirst_byte_timeout=15000,\n\t\tbetween_bytes_timeout=10000,\n\t\terror_threshold=0,\n\t\tmax_conn=20,\n\t\tweight=100,\n\t\tauto_loadbalance=False,\n\t\tshield=None,\n\t\trequest_condition=None,\n\t\thealthcheck=None,\n\t\tcomment=None):\n\t\tbody = self._formdata({\n\t\t\t\"name\": name,\n\t\t\t\"address\": address,\n\t\t\t\"use_ssl\": use_ssl,\n\t\t\t\"port\": port,\n\t\t\t\"connect_timeout\": connect_timeout,\n\t\t\t\"first_byte_timeout\": first_byte_timeout,\n\t\t\t\"between_bytes_timeout\": between_bytes_timeout,\n\t\t\t\"error_threshold\": error_threshold,\n\t\t\t\"max_conn\": max_conn,\n\t\t\t\"weight\": weight,\n\t\t\t\"auto_loadbalance\": auto_loadbalance,\n\t\t\t\"shield\": shield,\n\t\t\t\"request_condition\": request_condition,\n\t\t\t\"healthcheck\": healthcheck,\n\t\t\t\"comment\": comment,\n\t\t}, FastlyBackend.FIELDS)\n\t\tcontent = self._fetch(\"/service/%s/version/%d/backend\" % (service_id, version_number), method=\"POST\", body=body)\n\t\treturn FastlyBackend(self, content)",
    "docstring": "Create a backend for a particular service and version."
  },
  {
    "code": "def prox_soft_plus(X, step, thresh=0):\n    return prox_plus(prox_soft(X, step, thresh=thresh), step)",
    "docstring": "Soft thresholding with projection onto non-negative numbers"
  },
  {
    "code": "def exclude_chars(text, exclusion=None):\n    exclusion = [] if exclusion is None else exclusion\n    regexp = r\"|\".join([select_regexp_char(x) for x in exclusion]) or r''\n    return re.sub(regexp, '', text)",
    "docstring": "Clean text string of simbols in exclusion list."
  },
  {
    "code": "def handle_unset_command(self, line: str, position: int, tokens: ParseResults) -> ParseResults:\n        key = tokens['key']\n        self.validate_unset_command(line, position, key)\n        del self.annotations[key]\n        return tokens",
    "docstring": "Handle an ``UNSET X`` statement or raises an exception if it is not already set.\n\n        :raises: MissingAnnotationKeyWarning"
  },
  {
    "code": "def _fetch(self):\n        if 'uri' in self._meta_data:\n            error = \"There was an attempt to assign a new uri to this \"\\\n                    \"resource, the _meta_data['uri'] is %s and it should\"\\\n                    \" not be changed.\" % (self._meta_data['uri'])\n            raise URICreationCollision(error)\n        _create_uri = self._meta_data['container']._meta_data['uri']\n        session = self._meta_data['bigip']._meta_data['icr_session']\n        response = session.post(_create_uri, json={})\n        return self._produce_instance(response)",
    "docstring": "wrapped by `fetch` override that in subclasses to customize"
  },
  {
    "code": "def paint_agent_trail(self, y, x, val):\n        for j in range(1,self.cell_height-1):\n            for i in range(1,self.cell_width-1):\n                self.img.put(self.agent_color(val), (x*self.cell_width+i, y*self.cell_height+j))",
    "docstring": "paint an agent trail as ONE pixel to allow for multiple agent\n        trails to be seen in the same cell"
  },
  {
    "code": "def standardize_input_data(data):\n    if type(data) == bytes:\n        data = data.decode('utf-8')\n    if type(data) == list:\n        data = [\n            el.decode('utf-8') if type(data) == bytes else el\n            for el in data\n        ]\n    return data",
    "docstring": "Ensure utf-8 encoded strings are passed to the indico API"
  },
  {
    "code": "def is_successful(self, retry=False):\n        if not self.is_terminated(retry=retry):\n            return False\n        retry_num = options.retry_times\n        while retry_num > 0:\n            try:\n                statuses = self.get_task_statuses()\n                return all(task.status == Instance.Task.TaskStatus.SUCCESS\n                           for task in statuses.values())\n            except (errors.InternalServerError, errors.RequestTimeTooSkewed):\n                retry_num -= 1\n                if not retry or retry_num <= 0:\n                    raise",
    "docstring": "If the instance runs successfully.\n\n        :return: True if successful else False\n        :rtype: bool"
  },
  {
    "code": "def load(fp, class_=None, **kwargs):\n    return loado(json.load(fp, **kwargs), class_=class_)",
    "docstring": "Convert content in a JSON-encoded text file to a Physical Information Object or a list of such objects.\n\n    :param fp: File-like object supporting .read() method to deserialize from.\n    :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous\n    :param kwargs: Any options available to json.load().\n    :return: Single object derived from :class:`.Pio` or a list of such object."
  },
  {
    "code": "def _related_field_data(field, obj):\n    data = _basic_field_data(field, obj)\n    relation_info = {\n        Field.REL_DB_TABLE: field.rel.to._meta.db_table,\n        Field.REL_APP: field.rel.to._meta.app_label,\n        Field.REL_MODEL: field.rel.to.__name__\n    }\n    data[Field.TYPE] = FieldType.REL\n    data[Field.REL] = relation_info\n    return data",
    "docstring": "Returns relation ``field`` as a dict.\n\n    Dict contains related pk info and some meta information\n    for reconstructing objects."
  },
  {
    "code": "def make_ioc(name=None,\n                 description='Automatically generated IOC',\n                 author='IOC_api',\n                 links=None,\n                 keywords=None,\n                 iocid=None):\n        root = ioc_et.make_ioc_root(iocid)\n        root.append(ioc_et.make_metadata_node(name, description, author, links, keywords))\n        metadata_node = root.find('metadata')\n        top_level_indicator = make_indicator_node('OR')\n        parameters_node = (ioc_et.make_parameters_node())\n        root.append(ioc_et.make_criteria_node(top_level_indicator))\n        root.append(parameters_node)\n        ioc_et.set_root_lastmodified(root)\n        return root, metadata_node, top_level_indicator, parameters_node",
    "docstring": "This generates all parts of an IOC, but without any definition.\n\n        This is a helper function used by __init__.\n\n        :param name: string, Name of the ioc\n        :param description: string, description of the ioc\n        :param author: string, author name/email address\n        :param links: ist of tuples.  Each tuple should be in the form (rel, href, value).\n        :param keywords: string.  This is normally a space delimited string of values that may be used as keywords\n        :param iocid: GUID for the IOC.  This should not be specified under normal circumstances.\n        :return: a tuple containing three elementTree Element objects\n         The first element, the root, contains the entire IOC itself.\n         The second element, the top level OR indicator, allows the user to add\n          additional IndicatorItem or Indicator nodes to the IOC easily.\n         The third element, the parameters node, allows the user to quickly\n          parse the parameters."
  },
  {
    "code": "def escape_unicode_string(u):\n    def replacer(matchobj):\n        if ord(matchobj.group(1)) == 127:\n            return \"\\\\x7f\"\n        if ord(matchobj.group(1)) == 92:\n            return \"\\\\\\\\\"\n        return REPLACEMENT_TABLE[ord(matchobj.group(1))]\n    return re.sub(\"([\\\\000-\\\\037\\\\134\\\\177])\", replacer, u)",
    "docstring": "Escapes the nonprintable chars 0-31 and 127, and backslash;\n    preferably with a friendly equivalent such as '\\n' if available, but\n    otherwise with a Python-style backslashed hex escape."
  },
  {
    "code": "def escape_shell_arg(shell_arg):\n    if isinstance(shell_arg, six.text_type):\n        msg = \"ERROR: escape_shell_arg() expected string argument but \" \\\n              \"got '%s' of type '%s'.\" % (repr(shell_arg), type(shell_arg))\n        raise TypeError(msg)\n    return \"'%s'\" % shell_arg.replace(\"'\", r\"'\\''\")",
    "docstring": "Escape shell argument shell_arg by placing it within\n    single-quotes.  Any single quotes found within the shell argument\n    string will be escaped.\n\n    @param shell_arg: The shell argument to be escaped.\n    @type shell_arg: string\n    @return: The single-quote-escaped value of the shell argument.\n    @rtype: string\n    @raise TypeError: if shell_arg is not a string.\n    @see: U{http://mail.python.org/pipermail/python-list/2005-October/346957.html}"
  },
  {
    "code": "def get_customjs(self, references, plot_id=None):\n        if plot_id is None:\n            plot_id = self.plot.id or 'PLACEHOLDER_PLOT_ID'\n        self_callback = self.js_callback.format(comm_id=self.comm.id,\n                                                timeout=self.timeout,\n                                                debounce=self.debounce,\n                                                plot_id=plot_id)\n        attributes = self.attributes_js(self.attributes)\n        conditions = [\"%s\" % cond for cond in self.skip]\n        conditional = ''\n        if conditions:\n            conditional = 'if (%s) { return };\\n' % (' || '.join(conditions))\n        data = \"var data = {};\\n\"\n        code = conditional + data + attributes + self.code + self_callback\n        return CustomJS(args=references, code=code)",
    "docstring": "Creates a CustomJS callback that will send the requested\n        attributes back to python."
  },
  {
    "code": "def merge_urls_data_to(to, food={}):\n    if not to:\n        to.update(food)\n    for url, data in food.items():\n        if url not in to:\n            to[url] = data\n        else:\n            to[url] = to[url].merge_with(data)",
    "docstring": "Merge urls data"
  },
  {
    "code": "def __make_footprint(input, size, footprint):\n    \"Creates a standard footprint element ala scipy.ndimage.\"\n    if footprint is None:\n        if size is None:\n            raise RuntimeError(\"no footprint or filter size provided\")\n        sizes = _ni_support._normalize_sequence(size, input.ndim)\n        footprint = numpy.ones(sizes, dtype=bool)\n    else:\n        footprint = numpy.asarray(footprint, dtype=bool)\n    return footprint",
    "docstring": "Creates a standard footprint element ala scipy.ndimage."
  },
  {
    "code": "def next_img(self, loop=True):\n        channel = self.get_current_channel()\n        if channel is None:\n            self.show_error(\"Please create a channel.\", raisetab=True)\n            return\n        channel.next_image()\n        return True",
    "docstring": "Go to the next image in the channel."
  },
  {
    "code": "def _onWhat(self, name, line, pos, absPosition):\n        self.__lastImport.what.append(ImportWhat(name, line, pos, absPosition))",
    "docstring": "Memorizes an imported item"
  },
  {
    "code": "def make_fasta_url(\n        ensembl_release,\n        species,\n        sequence_type,\n        server=ENSEMBL_FTP_SERVER):\n    ensembl_release, species, reference_name = normalize_release_properties(\n        ensembl_release, species)\n    subdir = _species_subdir(\n        ensembl_release,\n        species=species,\n        filetype=\"fasta\",\n        server=server)\n    server_subdir = urllib_parse.urljoin(server, subdir)\n    server_sequence_subdir = join(server_subdir, sequence_type)\n    filename = make_fasta_filename(\n        ensembl_release=ensembl_release,\n        species=species,\n        sequence_type=sequence_type)\n    return join(server_sequence_subdir, filename)",
    "docstring": "Construct URL to FASTA file with cDNA transcript or protein sequences\n\n    Parameter examples:\n        ensembl_release = 75\n        species = \"Homo_sapiens\"\n        sequence_type = \"cdna\" (other option: \"pep\")"
  },
  {
    "code": "def delete_thing_shadow(self, **kwargs):\n        r\n        thing_name = self._get_required_parameter('thingName', **kwargs)\n        payload = b''\n        return self._shadow_op('delete', thing_name, payload)",
    "docstring": "r\"\"\"\n        Deletes the thing shadow for the specified thing.\n\n        :Keyword Arguments:\n            * *thingName* (``string``) --\n              [REQUIRED]\n              The name of the thing.\n\n        :returns: (``dict``) --\n        The output from the DeleteThingShadow operation\n            * *payload* (``bytes``) --\n              The state information, in JSON format."
  },
  {
    "code": "def national(self):\n        if self._national is None:\n            self._national = NationalList(\n                self._version,\n                account_sid=self._solution['account_sid'],\n                country_code=self._solution['country_code'],\n            )\n        return self._national",
    "docstring": "Access the national\n\n        :returns: twilio.rest.api.v2010.account.available_phone_number.national.NationalList\n        :rtype: twilio.rest.api.v2010.account.available_phone_number.national.NationalList"
  },
  {
    "code": "def client_getname(self, encoding=_NOTSET):\n        return self.execute(b'CLIENT', b'GETNAME', encoding=encoding)",
    "docstring": "Get the current connection name."
  },
  {
    "code": "def contributions(self, request, **kwargs):\n        if Contribution not in get_models():\n            return Response([])\n        if request.method == \"POST\":\n            serializer = ContributionSerializer(data=get_request_data(request), many=True)\n            if not serializer.is_valid():\n                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n            serializer.save()\n            return Response(serializer.data)\n        else:\n            content_pk = kwargs.get('pk', None)\n            if content_pk is None:\n                return Response([], status=status.HTTP_404_NOT_FOUND)\n            queryset = Contribution.search_objects.search().filter(\n                es_filter.Term(**{'content.id': content_pk})\n            )\n            serializer = ContributionSerializer(queryset[:queryset.count()].sort('id'), many=True)\n            return Response(serializer.data)",
    "docstring": "gets or adds contributions\n\n        :param request: a WSGI request object\n        :param kwargs: keyword arguments (optional)\n        :return: `rest_framework.response.Response`"
  },
  {
    "code": "def update(self):\n        if not self._track_changes:\n            return True\n        data = self.to_api_data(restrict_keys=self._track_changes)\n        response = self.session.patch(self.build_url(''), data=data)\n        if not response:\n            return False\n        data = response.json()\n        for field in self._track_changes:\n            setattr(self, snakecase(field), data.get(field))\n        self._track_changes.clear()\n        return True",
    "docstring": "Update this range"
  },
  {
    "code": "def _ParseRecordExtraField(self, byte_stream, file_offset):\n    extra_field_map = self._GetDataTypeMap('asl_record_extra_field')\n    try:\n      record_extra_field = self._ReadStructureFromByteStream(\n          byte_stream, file_offset, extra_field_map)\n    except (ValueError, errors.ParseError) as exception:\n      raise errors.ParseError((\n          'Unable to parse record extra field at offset: 0x{0:08x} with error: '\n          '{1!s}').format(file_offset, exception))\n    return record_extra_field",
    "docstring": "Parses a record extra field.\n\n    Args:\n      byte_stream (bytes): byte stream.\n      file_offset (int): offset of the record extra field relative to\n          the start of the file.\n\n    Returns:\n      asl_record_extra_field: record extra field.\n\n    Raises:\n      ParseError: if the record extra field cannot be parsed."
  },
  {
    "code": "def submodules(self):\n        p = lambda o: isinstance(o, Module) and self._docfilter(o)\n        return sorted(filter(p, self.doc.values()))",
    "docstring": "Returns all documented sub-modules in the module sorted\n        alphabetically as a list of `pydoc.Module`."
  },
  {
    "code": "def inet_to_str(inet):\n    try:\n        return socket.inet_ntop(socket.AF_INET, inet)\n    except ValueError:\n        return socket.inet_ntop(socket.AF_INET6, inet)",
    "docstring": "Convert inet object to a string\n\n        Args:\n            inet (inet struct): inet network address\n        Returns:\n            str: Printable/readable IP address"
  },
  {
    "code": "def install_dependencies(self):\n        if self._skip_virtualenv:\n            LOG.info('Skip Virtualenv set ... nothing to do')\n            return\n        has_reqs = _isfile(self._requirements_file) or self._requirements\n        if self._virtualenv is None and has_reqs:\n            LOG.info('Building new virtualenv and installing requirements')\n            self._build_new_virtualenv()\n            self._install_requirements()\n        elif self._virtualenv is None and not has_reqs:\n            LOG.info('No requirements found, so no virtualenv will be made')\n            self._pkg_venv = False\n        else:\n            raise Exception('Cannot determine what to do about virtualenv')",
    "docstring": "Creates a virtualenv and installs requirements"
  },
  {
    "code": "def _master_control_program(self):\n        return mcp.MasterControlProgram(self.config,\n                                        consumer=self.args.consumer,\n                                        profile=self.args.profile,\n                                        quantity=self.args.quantity)",
    "docstring": "Return an instance of the MasterControlProgram.\n\n        :rtype: rejected.mcp.MasterControlProgram"
  },
  {
    "code": "def create_switch(type, settings, pin):\n\tswitch = None\n\tif type == \"A\":\n\t\tgroup, device = settings.split(\",\")\n\t\tswitch = pi_switch.RCSwitchA(group, device)\n\telif type == \"B\":\n\t\taddr, channel = settings.split(\",\")\n\t\taddr = int(addr)\n\t\tchannel = int(channel)\n\t\tswitch = pi_switch.RCSwitchB(addr, channel)\n\telif type == \"C\":\n\t\tfamily, group, device = settings.split(\",\")\n\t\tgroup = int(group)\n\t\tdevice = int(device)\n\t\tswitch = pi_switch.RCSwitchC(family, group, device)\n\telif type == \"D\":\n\t\tgroup, device = settings.split(\",\")\n\t\tdevice = int(device)\n\t\tswitch = pi_switch.RCSwitchD(group, device)\n\telse:\n\t\tprint \"Type %s is not supported!\" % type\n\t\tsys.exit()\n\tswitch.enableTransmit(pin)\n\treturn switch",
    "docstring": "Create a switch.\n\n    Args:\n        type: (str): type of the switch [A,B,C,D]\n        settings (str): a comma separted list\n        pin (int): wiringPi pin\n\n    Returns:\n        switch"
  },
  {
    "code": "def on_import1(self, event):\n        pmag_menu_dialogs.MoveFileIntoWD(self.parent, self.parent.WD)",
    "docstring": "initialize window to import an arbitrary file into the working directory"
  },
  {
    "code": "def init_all_receivers():\n    receivers = discover()\n    init_receivers = []\n    for receiver in receivers:\n        init_receiver = DenonAVR(receiver[\"host\"])\n        init_receivers.append(init_receiver)\n    return init_receivers",
    "docstring": "Initialize all discovered Denon AVR receivers in LAN zone.\n\n    Returns a list of created Denon AVR instances.\n    By default SSDP broadcasts are sent up to 3 times with a 2 seconds timeout."
  },
  {
    "code": "def from_argparse(cls, opts):\n        return cls(opts.ethinca_pn_order, opts.filter_cutoff,\n            opts.ethinca_frequency_step, fLow=None,\n            full_ethinca=opts.calculate_ethinca_metric,\n            time_ethinca=opts.calculate_time_metric_components)",
    "docstring": "Initialize an instance of the ethincaParameters class from an\n        argparse.OptionParser instance. This assumes that\n        insert_ethinca_metric_options\n        and\n        verify_ethinca_metric_options\n        have already been called before initializing the class."
  },
  {
    "code": "def _by_columns(self, columns):\n        return columns if self.isstr(columns) else self._backtick_columns(columns)",
    "docstring": "Allow select.group and select.order accepting string and list"
  },
  {
    "code": "def _operator_norms(L):\n    L_norms = []\n    for Li in L:\n        if np.isscalar(Li):\n            L_norms.append(float(Li))\n        elif isinstance(Li, Operator):\n            L_norms.append(Li.norm(estimate=True))\n        else:\n            raise TypeError('invalid entry {!r} in `L`'.format(Li))\n    return L_norms",
    "docstring": "Get operator norms if needed.\n\n    Parameters\n    ----------\n    L : sequence of `Operator` or float\n        The operators or the norms of the operators that are used in the\n        `douglas_rachford_pd` method. For `Operator` entries, the norm\n        is computed with ``Operator.norm(estimate=True)``."
  },
  {
    "code": "def _first_word_not_cmd(self,\n                            first_word: str,\n                            command: str,\n                            args: tuple,\n                            kwargs: dict) -> None:\n        if self.service_interface.is_service(first_word):\n            self._logger.debug(' first word is a service')\n            kwargs = self.service_interface.get_metadata(first_word, kwargs)\n            self._logger.debug(' service transform kwargs: %s', kwargs)\n        elif self.author_interface.is_author(first_word):\n            self._logger.debug(' first word is an author')\n            kwargs = self.author_interface.get_metadata(first_word, kwargs)\n            self._logger.debug(' author transform kwargs: %s', kwargs)\n        if not kwargs.get('remote'):\n            kwargs['remote_command'] = command\n            command= 'REMOTE'\n            self.messaging.send_command(command, *args, **kwargs)\n            return\n        else:\n            self.messaging.send_command(command, *args, **kwargs)",
    "docstring": "check to see if this is an author or service.\n        This method does high level control handling"
  },
  {
    "code": "def run(cmd_str,cwd='.',verbose=False):\n    warnings.warn(\"run() has moved to pyemu.os_utils\",PyemuWarning)\n    pyemu.os_utils.run(cmd_str=cmd_str,cwd=cwd,verbose=verbose)",
    "docstring": "an OS agnostic function to execute command\n\n    Parameters\n    ----------\n    cmd_str : str\n        the str to execute with os.system()\n\n    cwd : str\n        the directory to execute the command in\n\n    verbose : bool\n        flag to echo to stdout complete cmd str\n\n    Note\n    ----\n    uses platform to detect OS and adds .exe or ./ as appropriate\n\n    for Windows, if os.system returns non-zero, raises exception\n\n    Example\n    -------\n    ``>>>import pyemu``\n\n    ``>>>pyemu.helpers.run(\"pestpp pest.pst\")``"
  },
  {
    "code": "def export_deleted_fields(self):\n        result = []\n        if self.__modified_data__ is not None:\n            return result\n        for index, item in enumerate(self):\n            try:\n                deleted_fields = item.export_deleted_fields()\n                result.extend(['{}.{}'.format(index, key) for key in deleted_fields])\n            except AttributeError:\n                pass\n        return result",
    "docstring": "Returns a list with any deleted fields form original data.\n        In tree models, deleted fields on children will be appended."
  },
  {
    "code": "def download(self, uri, file_path):\n        with open(file_path, 'wb') as file:\n            return self._connection.download_to_stream(file, uri)",
    "docstring": "Downloads the contents of the requested URI to a stream.\n\n        Args:\n            uri: URI\n            file_path: File path destination\n\n        Returns:\n            bool: Indicates if the file was successfully downloaded."
  },
  {
    "code": "def terminate(pid, sig, timeout):\n    os.kill(pid, sig)\n    start = time.time()\n    while True:\n        try:\n            _, status = os.waitpid(pid, os.WNOHANG)\n        except OSError as exc:\n            if exc.errno != errno.ECHILD:\n                raise\n        else:\n            if status:\n                return True\n        if not is_running(pid):\n            return True\n        if time.time()-start>=timeout:\n            return False\n        time.sleep(0.1)",
    "docstring": "Terminates process with PID `pid` and returns True if process finished\n    during `timeout`. Current user must have permission to access process\n    information."
  },
  {
    "code": "def _find_short_paths(self, paths):\n        path_parts_s = [path.split(os.path.sep) for path in paths]\n        root_node = {}\n        for parts in sorted(path_parts_s, key=len, reverse=True):\n            node = root_node\n            for part in parts:\n                node = node.setdefault(part, {})\n            node.clear()\n        short_path_s = set()\n        self._collect_leaf_paths(\n            node=root_node,\n            path_parts=(),\n            leaf_paths=short_path_s,\n        )\n        return short_path_s",
    "docstring": "Find short paths of given paths.\n\n        E.g. if both `/home` and `/home/aoik` exist, only keep `/home`.\n\n        :param paths:\n            Paths.\n\n        :return:\n            Set of short paths."
  },
  {
    "code": "def _advance_window(self):\n        x_to_remove, y_to_remove = self._x_in_window[0], self._y_in_window[0]\n        self._window_bound_lower += 1\n        self._update_values_in_window()\n        x_to_add, y_to_add = self._x_in_window[-1], self._y_in_window[-1]\n        self._remove_observation(x_to_remove, y_to_remove)\n        self._add_observation(x_to_add, y_to_add)",
    "docstring": "Update values in current window and the current window means and variances."
  },
  {
    "code": "def users_changed_handler(stream):\r\n    while True:\r\n        yield from stream.get()\r\n        users = [\r\n            {'username': username, 'uuid': uuid_str}\r\n            for username, uuid_str in ws_connections.values()\r\n        ]\r\n        packet = {\r\n            'type': 'users-changed',\r\n            'value': sorted(users, key=lambda i: i['username'])\r\n        }\r\n        logger.debug(packet)\r\n        yield from fanout_message(ws_connections.keys(), packet)",
    "docstring": "Sends connected client list of currently active users in the chatroom"
  },
  {
    "code": "def e_164(msisdn: str) -> str:\n    number = phonenumbers.parse(\"+{}\".format(msisdn.lstrip(\"+\")), None)\n    return phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164)",
    "docstring": "Returns the msisdn in E.164 international format."
  },
  {
    "code": "def write(self):\n        html = self.render()\n        if self.file_type == 'pdf':\n            self.write_pdf(html)\n        else:\n            with codecs.open(self.destination_file, 'w',\n                             encoding='utf_8') as outfile:\n                outfile.write(html)",
    "docstring": "Writes generated presentation code into the destination file."
  },
  {
    "code": "def import_data_object_to_graph(diagram_graph, process_id, process_attributes, data_object_element):\n        BpmnDiagramGraphImport.import_flow_node_to_graph(diagram_graph, process_id, process_attributes,\n                                                         data_object_element)\n        data_object_id = data_object_element.getAttribute(consts.Consts.id)\n        diagram_graph.node[data_object_id][consts.Consts.is_collection] = \\\n            data_object_element.getAttribute(consts.Consts.is_collection) \\\n                if data_object_element.hasAttribute(consts.Consts.is_collection) else \"false\"",
    "docstring": "Adds to graph the new element that represents BPMN data object.\n        Data object inherits attributes from FlowNode. In addition, an attribute 'isCollection' is added to the node.\n\n        :param diagram_graph: NetworkX graph representing a BPMN process diagram,\n        :param process_id: string object, representing an ID of process element,\n        :param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of\n            imported flow node,\n        :param data_object_element: object representing a BPMN XML 'dataObject' element."
  },
  {
    "code": "def from_string(string_data, file_format=\"xyz\"):\n        mols = pb.readstring(str(file_format), str(string_data))\n        return BabelMolAdaptor(mols.OBMol)",
    "docstring": "Uses OpenBabel to read a molecule from a string in all supported\n        formats.\n\n        Args:\n            string_data: String containing molecule data.\n            file_format: String specifying any OpenBabel supported formats.\n\n        Returns:\n            BabelMolAdaptor object"
  },
  {
    "code": "def restore_taskset(self, taskset_id):\n        try:\n            return self.get(taskset_id=taskset_id)\n        except self.model.DoesNotExist:\n            pass",
    "docstring": "Get the async result instance by taskset id."
  },
  {
    "code": "def _run_queries(self, agent_strs, stmt_types, params, persist):\n        self._query_over_statement_types(agent_strs, stmt_types, params)\n        assert len(self.__done_dict) == len(stmt_types) \\\n            or None in self.__done_dict.keys(), \\\n            \"Done dict was not initiated for all stmt_type's.\"\n        if not persist:\n            self._compile_statements()\n            return\n        while not self._all_done():\n            self._query_over_statement_types(agent_strs, stmt_types, params)\n        self._compile_statements()\n        return",
    "docstring": "Use paging to get all statements requested."
  },
  {
    "code": "def get_resourceprovider_logger(name=None, short_name=\" \", log_to_file=True):\n    global LOGGERS\n    loggername = name\n    logger = _check_existing_logger(loggername, short_name)\n    if logger is not None:\n        return logger\n    logger_config = LOGGING_CONFIG.get(name, DEFAULT_LOGGING_CONFIG)\n    logger = _get_basic_logger(loggername, log_to_file, get_base_logfilename(loggername + \".log\"))\n    cbh = logging.StreamHandler()\n    cbh.formatter = BenchFormatterWithType(COLOR_ON)\n    if VERBOSE_LEVEL > 0 and not SILENT_ON:\n        cbh.setLevel(logging.DEBUG)\n    elif SILENT_ON:\n        cbh.setLevel(logging.WARN)\n    else:\n        cbh.setLevel(getattr(logging, logger_config.get(\"level\")))\n    logger.addHandler(cbh)\n    LOGGERS[loggername] = BenchLoggerAdapter(logger, {\"source\": short_name})\n    return LOGGERS[loggername]",
    "docstring": "Get a logger for ResourceProvider and it's components, such as Allocators.\n\n    :param name: Name for logger\n    :param short_name: Shorthand name for the logger\n    :param log_to_file: Boolean, True if logger should log to a file as well.\n    :return: Logger"
  },
  {
    "code": "def get_state_vector_sampler(n_sample):\n    def sampling_by_measurement(circuit, meas):\n        val = 0.0\n        e = expect(circuit.run(returns=\"statevector\"), meas)\n        bits, probs = zip(*e.items())\n        dists = np.random.multinomial(n_sample, probs) / n_sample\n        return dict(zip(tuple(bits), dists))\n    return sampling_by_measurement",
    "docstring": "Returns a function which get the expectations by sampling the state vector"
  },
  {
    "code": "def exclude_functions(self, *funcs):\n        for f in funcs:\n            f.exclude = True\n        run_time_s = sum(0 if s.exclude else s.own_time_s for s in self.stats)\n        cProfileFuncStat.run_time_s = run_time_s",
    "docstring": "Excludes the contributions from the following functions."
  },
  {
    "code": "def doAction(self, loginMethod, actionClass):\n        loginAccount = loginMethod.account\n        return actionClass(\n            self,\n            loginMethod.localpart + u'@' + loginMethod.domain,\n            loginAccount)",
    "docstring": "Show the form for the requested action."
  },
  {
    "code": "def now(self):\n        try:\n            if self.now_id:\n                return Chart(self.now_id)\n            else:\n                log.debug('attempted to get current chart, but none was found')\n                return\n        except AttributeError:\n            log.debug('attempted to get current (\"now\") chart from a chart without a now attribute')\n            return None",
    "docstring": "fetch the chart identified by this chart's now_id attribute\n        if the now_id is either null or not present for this chart return None\n        returns the new chart instance on sucess"
  },
  {
    "code": "def _compute_nonlinear_magnitude_term(self, C, mag):\n        return self._compute_linear_magnitude_term(C, mag) +\\\n            C[\"b3\"] * ((mag - 7.0) ** 2.)",
    "docstring": "Computes the non-linear magnitude term"
  },
  {
    "code": "async def wait(self):\n        while True:\n            await self.eio.wait()\n            await self.sleep(1)\n            if not self._reconnect_task:\n                break\n            await self._reconnect_task\n            if self.eio.state != 'connected':\n                break",
    "docstring": "Wait until the connection with the server ends.\n\n        Client applications can use this function to block the main thread\n        during the life of the connection.\n\n        Note: this method is a coroutine."
  },
  {
    "code": "def _get_spec(self) -> dict:\n        if self.spec:\n            return self.spec\n        self.spec = requests.get(self.SPEC_URL.format(self.version)).json()\n        return self.spec",
    "docstring": "Fetches the OpenAPI spec from the server.\n\n        If the spec has already been fetched, the cached version is returned instead.\n\n        ArgS:\n            None\n\n        Returns:\n            OpenAPI spec data"
  },
  {
    "code": "def _get_runner(classpath, main, jvm_options, args, executor,\n               cwd, distribution,\n               create_synthetic_jar, synthetic_jar_dir):\n  executor = executor or SubprocessExecutor(distribution)\n  safe_cp = classpath\n  if create_synthetic_jar:\n    safe_cp = safe_classpath(classpath, synthetic_jar_dir)\n    logger.debug('Bundling classpath {} into {}'.format(':'.join(classpath), safe_cp))\n  return executor.runner(safe_cp, main, args=args, jvm_options=jvm_options, cwd=cwd)",
    "docstring": "Gets the java runner for execute_java and execute_java_async."
  },
  {
    "code": "def datetime_parsing(text, base_date=datetime.now()):\n    matches = []\n    found_array = []\n    for expression, function in regex:\n        for match in expression.finditer(text):\n            matches.append((match.group(), function(match, base_date), match.span()))\n    for match, value, spans in matches:\n        subn = re.subn(\n            '(?!<TAG[^>]*?>)' + match + '(?![^<]*?</TAG>)', '<TAG>' + match + '</TAG>', text\n        )\n        text = subn[0]\n        is_substituted = subn[1]\n        if is_substituted != 0:\n            found_array.append((match, value, spans))\n    return sorted(found_array, key=lambda match: match and match[2][0])",
    "docstring": "Extract datetime objects from a string of text."
  },
  {
    "code": "def warsaw_up_to_warsaw(C, parameters=None, sectors=None):\n    C_in = smeftutil.wcxf2arrays_symmetrized(C)\n    p = default_parameters.copy()\n    if parameters is not None:\n        p.update(parameters)\n    Uu = Ud = Ul = Ue = np.eye(3)\n    V = ckmutil.ckm.ckm_tree(p[\"Vus\"], p[\"Vub\"], p[\"Vcb\"], p[\"delta\"])\n    Uq = V\n    C_out = smeftutil.flavor_rotation(C_in, Uq, Uu, Ud, Ul, Ue)\n    C_out = smeftutil.arrays2wcxf_nonred(C_out)\n    warsaw = wcxf.Basis['SMEFT', 'Warsaw']\n    all_wcs = set(warsaw.all_wcs)\n    return {k: v for k, v in C_out.items() if k in all_wcs}",
    "docstring": "Translate from the 'Warsaw up' basis to the Warsaw basis.\n\n    Parameters used:\n    - `Vus`, `Vub`, `Vcb`, `gamma`: elements of the unitary CKM matrix (defined\n      as the mismatch between left-handed quark mass matrix diagonalization\n      matrices)."
  },
  {
    "code": "def GetValue(self, row, col):\n        if len(self.dataframe):\n            return str(self.dataframe.iloc[row, col])\n        return ''",
    "docstring": "Find the matching value from pandas DataFrame,\n        return it."
  },
  {
    "code": "def get_brokendate_fx_forward_rate(self, asset_manager_id,  asset_id, price_date, value_date):\n        self.logger.info('Calculate broken date FX Forward - Asset Manager: %s - Asset (currency): %s - Price Date: %s - Value Date: %s', asset_manager_id, asset_id, price_date, value_date)\n        url = '%s/brokendateforward/%s' % (self.endpoint, asset_manager_id)\n        params = {'value_date': value_date, 'asset_id':asset_id, 'price_date': price_date}\n        response = self.session.get(url=url, params = params)\n        if response.ok:\n            forward_rate = response.json()\n            self.logger.info('Retrieved broken date FX forward rate %s - %s: %s', asset_id, price_date, value_date)\n            return forward_rate\n        else:\n            self.logger.error(response.text)\n            response.raise_for_status()",
    "docstring": "This method takes calculates broken date forward FX rate based on the passed in parameters"
  },
  {
    "code": "def convert_to_feature_collection(self):\n        if self.data['type'] == 'FeatureCollection':\n            return\n        if not self.embed:\n            raise ValueError(\n                'Data is not a FeatureCollection, but it should be to apply '\n                'style or highlight. Because `embed=False` it cannot be '\n                'converted into one.\\nEither change your geojson data to a '\n                'FeatureCollection, set `embed=True` or disable styling.')\n        if 'geometry' not in self.data.keys():\n            self.data = {'type': 'Feature', 'geometry': self.data}\n        self.data = {'type': 'FeatureCollection', 'features': [self.data]}",
    "docstring": "Convert data into a FeatureCollection if it is not already."
  },
  {
    "code": "def split_array_like(df, columns=None):\n    dtypes = df.dtypes\n    if columns is None:\n        columns = df.columns\n    elif isinstance(columns, str):\n        columns = [columns]\n    for column in columns:\n        expanded = np.repeat(df.values, df[column].apply(len).values, axis=0)\n        expanded[:, df.columns.get_loc(column)] = np.concatenate(df[column].tolist())\n        df = pd.DataFrame(expanded, columns=df.columns)\n    for i, dtype in enumerate(dtypes):\n        df.iloc[:,i] = df.iloc[:,i].astype(dtype)\n    return df",
    "docstring": "Split cells with array-like values along row axis.\n\n    Column names are maintained. The index is dropped.\n\n    Parameters\n    ----------\n    df : ~pandas.DataFrame\n        Data frame ``df[columns]`` should contain :py:class:`~pytil.numpy.ArrayLike`\n        values.\n    columns : ~typing.Collection[str] or str or None\n        Columns (or column) whose values to split. Defaults to ``df.columns``.\n\n    Returns\n    -------\n    ~pandas.DataFrame\n        Data frame with array-like values in ``df[columns]`` split across rows,\n        and corresponding values in other columns repeated.\n\n    Examples\n    --------\n    >>> df = pd.DataFrame([[1,[1,2],[1]],[1,[1,2],[3,4,5]],[2,[1],[1,2]]], columns=('check', 'a', 'b'))\n    >>> df\n       check       a          b\n    0      1  [1, 2]        [1]\n    1      1  [1, 2]  [3, 4, 5]\n    2      2     [1]     [1, 2]\n    >>> split_array_like(df, ['a', 'b'])\n      check  a  b\n    0     1  1  1\n    1     1  2  1\n    2     1  1  3\n    3     1  1  4\n    4     1  1  5\n    5     1  2  3\n    6     1  2  4\n    7     1  2  5\n    8     2  1  1\n    9     2  1  2"
  },
  {
    "code": "def indexed_file(self, f):\n    filename, handle = f\n    if handle is None and filename is not None:\n      handle = open(filename)\n    if (handle is None and filename is None) or \\\n       (filename != self._indexed_filename) or \\\n       (handle != self._indexed_file_handle):\n      self.index = {}\n    if ((handle is not None or filename is not None) and\n       (self.record_iterator is None or self.record_hash_function is None)):\n      raise IndexError(\"Setting index file failed; reason: iterator \"\n                       \"(self.record_iterator) or hash function \"\n                       \"(self.record_hash_function) have to be set first\")\n    self._indexed_filename = filename\n    self._indexed_file_handle = handle",
    "docstring": "Setter for information about the file this object indexes.\n\n    :param f: a tuple of (filename, handle), either (or both) of which can be\n              None. If the handle is None, but filename is provided, then\n              handle is created from the filename. If both handle and filename\n              are None, or they don't match the previous values indexed by this\n              object, any current data in this index is cleared. If either are\n              not None, we require the iterator and the hash function for this\n              object to already be set."
  },
  {
    "code": "def run(self):\n        if self.args['add']:\n            self.action_add()\n        elif self.args['rm']:\n            self.action_rm()\n        elif self.args['show']:\n            self.action_show()\n        elif self.args['rename']:\n            self.action_rename()\n        else:\n            self.action_run_command()",
    "docstring": "Perform the specified action"
  },
  {
    "code": "def serialize(exc):\n    return {\n        'exc_type': type(exc).__name__,\n        'exc_path': get_module_path(type(exc)),\n        'exc_args': list(map(safe_for_serialization, exc.args)),\n        'value': safe_for_serialization(exc),\n    }",
    "docstring": "Serialize `self.exc` into a data dictionary representing it."
  },
  {
    "code": "def _error_catcher(self):\n        clean_exit = False\n        try:\n            try:\n                yield\n            except SocketTimeout:\n                raise ReadTimeoutError(self._pool, None, 'Read timed out.')\n            except BaseSSLError as e:\n                if 'read operation timed out' not in str(e):\n                    raise\n                raise ReadTimeoutError(self._pool, None, 'Read timed out.')\n            except (HTTPException, SocketError) as e:\n                raise ProtocolError('Connection broken: %r' % e, e)\n            clean_exit = True\n        finally:\n            if not clean_exit:\n                if self._original_response:\n                    self._original_response.close()\n                if self._connection:\n                    self._connection.close()\n            if self._original_response and self._original_response.isclosed():\n                self.release_conn()",
    "docstring": "Catch low-level python exceptions, instead re-raising urllib3\n        variants, so that low-level exceptions are not leaked in the\n        high-level api.\n\n        On exit, release the connection back to the pool."
  },
  {
    "code": "def get_level_values(self, level):\n        level = self._get_level_number(level)\n        values = self._get_level_values(level)\n        return values",
    "docstring": "Return vector of label values for requested level,\n        equal to the length of the index.\n\n        Parameters\n        ----------\n        level : int or str\n            ``level`` is either the integer position of the level in the\n            MultiIndex, or the name of the level.\n\n        Returns\n        -------\n        values : Index\n            Values is a level of this MultiIndex converted to\n            a single :class:`Index` (or subclass thereof).\n\n        Examples\n        ---------\n\n        Create a MultiIndex:\n\n        >>> mi = pd.MultiIndex.from_arrays((list('abc'), list('def')))\n        >>> mi.names = ['level_1', 'level_2']\n\n        Get level values by supplying level as either integer or name:\n\n        >>> mi.get_level_values(0)\n        Index(['a', 'b', 'c'], dtype='object', name='level_1')\n        >>> mi.get_level_values('level_2')\n        Index(['d', 'e', 'f'], dtype='object', name='level_2')"
  },
  {
    "code": "def subnet_delete(auth=None, **kwargs):\n    cloud = get_operator_cloud(auth)\n    kwargs = _clean_kwargs(**kwargs)\n    return cloud.delete_subnet(**kwargs)",
    "docstring": "Delete a subnet\n\n    name\n        Name or ID of the subnet to update\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' neutronng.subnet_delete name=subnet1\n        salt '*' neutronng.subnet_delete \\\n          name=1dcac318a83b4610b7a7f7ba01465548"
  },
  {
    "code": "def write(self, path=None):\n        if not self._path and not path:\n            raise ConfigException('no config path given')\n        if path:\n            self._path = path\n        if '~' in self._path:\n            self._path = os.path.expanduser(self._path)\n        f = open(self._path, 'w')\n        f.write(json.dumps(self._data))\n        f.close()",
    "docstring": "Write config data to disk. If this config object already has a path,\n         it will write to it. If it doesn't, one must be passed during this\n         call.\n\n        :param str path: path to config file"
  },
  {
    "code": "def _api_post(self, url, **kwargs):\n        kwargs['url'] = self.url + url\n        kwargs['auth'] = self.auth\n        headers = deepcopy(self.headers)\n        headers.update(kwargs.get('headers', {}))\n        kwargs['headers'] = headers\n        self._post(**kwargs)",
    "docstring": "A convenience wrapper for _post. Adds headers, auth and base url by\n        default"
  },
  {
    "code": "def drawQuad(page, quad, color=None, fill=None, dashes=None,\n             width=1, roundCap=False, morph=None, overlay=True):\n    img = page.newShape()\n    Q = img.drawQuad(Quad(quad))\n    img.finish(color=color, fill=fill, dashes=dashes, width=width,\n                   roundCap=roundCap, morph=morph)\n    img.commit(overlay)\n    return Q",
    "docstring": "Draw a quadrilateral."
  },
  {
    "code": "def get_hosting_devices_for_agent(self, context, host):\n        agent_ids = self._dmplugin.get_cfg_agents(context, active=None,\n                                                  filters={'host': [host]})\n        if agent_ids:\n            return [self._dmplugin.get_device_info_for_agent(context, hd_db)\n                    for hd_db in self._dmplugin.get_hosting_devices_db(\n                    context, filters={'cfg_agent_id': [agent_ids[0].id]})]\n        return []",
    "docstring": "Fetches routers that a Cisco cfg agent is managing.\n\n        This function is supposed to be called when the agent has started,\n        is ready to take on assignments and before any callbacks to fetch\n        logical resources are issued.\n\n        :param context: contains user information\n        :param host: originator of callback\n        :returns: dict of hosting devices managed by the cfg agent"
  },
  {
    "code": "def parallel_for(loop_function, parameters, nb_threads=100):\n    import multiprocessing.pool\n    from contextlib import closing\n    with closing(multiprocessing.pool.ThreadPool(nb_threads)) as pool:\n        return pool.map(loop_function, parameters)",
    "docstring": "Execute the loop body in parallel.\n\n    .. note:: Race-Conditions\n          Executing code in parallel can cause an error class called\n          \"race-condition\".\n\n    Parameters\n    ----------\n    loop_function : Python function which takes a tuple as input\n    parameters : List of tuples\n        Each element here should be executed in parallel.\n\n    Returns\n    -------\n    return_values : list of return values"
  },
  {
    "code": "def deploy(self, initial_instance_count, instance_type, accelerator_type=None, endpoint_name=None,\n               use_compiled_model=False, update_endpoint=False, **kwargs):\n        self._ensure_latest_training_job()\n        endpoint_name = endpoint_name or self.latest_training_job.name\n        self.deploy_instance_type = instance_type\n        if use_compiled_model:\n            family = '_'.join(instance_type.split('.')[:-1])\n            if family not in self._compiled_models:\n                raise ValueError(\"No compiled model for {}. \"\n                                 \"Please compile one with compile_model before deploying.\".format(family))\n            model = self._compiled_models[family]\n        else:\n            model = self.create_model(**kwargs)\n        return model.deploy(\n            instance_type=instance_type,\n            initial_instance_count=initial_instance_count,\n            accelerator_type=accelerator_type,\n            endpoint_name=endpoint_name,\n            update_endpoint=update_endpoint,\n            tags=self.tags)",
    "docstring": "Deploy the trained model to an Amazon SageMaker endpoint and return a ``sagemaker.RealTimePredictor`` object.\n\n        More information:\n        http://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-training.html\n\n        Args:\n            initial_instance_count (int): Minimum number of EC2 instances to deploy to an endpoint for prediction.\n            instance_type (str): Type of EC2 instance to deploy to an endpoint for prediction,\n                for example, 'ml.c4.xlarge'.\n            accelerator_type (str): Type of Elastic Inference accelerator to attach to an endpoint for model loading\n                and inference, for example, 'ml.eia1.medium'. If not specified, no Elastic Inference accelerator\n                will be attached to the endpoint.\n                For more information: https://docs.aws.amazon.com/sagemaker/latest/dg/ei.html\n            endpoint_name (str): Name to use for creating an Amazon SageMaker endpoint. If not specified, the name of\n                the training job is used.\n            use_compiled_model (bool): Flag to select whether to use compiled (optimized) model. Default: False.\n            update_endpoint (bool): Flag to update the model in an existing Amazon SageMaker endpoint.\n                If True, this will deploy a new EndpointConfig to an already existing endpoint and delete resources\n                corresponding to the previous EndpointConfig. Default: False\n            tags(List[dict[str, str]]): Optional. The list of tags to attach to this specific endpoint. Example:\n                    >>> tags = [{'Key': 'tagname', 'Value': 'tagvalue'}]\n                    For more information about tags, see https://boto3.amazonaws.com/v1/documentation\\\n                    /api/latest/reference/services/sagemaker.html#SageMaker.Client.add_tags\n\n            **kwargs: Passed to invocation of ``create_model()``. Implementations may customize\n                ``create_model()`` to accept ``**kwargs`` to customize model creation during deploy.\n                For more, see the implementation docs.\n\n        Returns:\n            sagemaker.predictor.RealTimePredictor: A predictor that provides a ``predict()`` method,\n                which can be used to send requests to the Amazon SageMaker endpoint and obtain inferences."
  },
  {
    "code": "def list_of_objects_from_api(url):\n    response = requests.get(url)\n    content = json.loads(response.content)\n    count = content[\"meta\"][\"total_count\"]\n    if count <= 20:\n        return content[\"items\"]\n    else:\n        items = [] + content[\"items\"]\n        num_requests = int(math.ceil(count // 20))\n        for i in range(1, num_requests + 1):\n            paginated_url = \"{}?limit=20&offset={}\".format(\n                url, str(i * 20))\n            paginated_response = requests.get(paginated_url)\n            items = items + json.loads(paginated_response.content)[\"items\"]\n    return items",
    "docstring": "API only serves 20 pages by default\n    This fetches info on all of items and return them as a list\n\n    Assumption: limit of API is not less than 20"
  },
  {
    "code": "def _set_nil(self, element, value_parser):\n        if self.value:\n            element.text = value_parser(self.value)\n        else:\n            element.attrib['nil'] = 'true'\n        return element",
    "docstring": "Method to set an attribute of the element.\n        If the value of the field is None then set the nil='true' attribute in the element\n\n        :param element: the element which needs to be modified\n        :type element: xml.etree.ElementTree.Element\n        :param value_parser: the lambda function which changes will be done to the self.value\n        :type value_parser: def\n        :return: the element with or without the specific attribute\n        :rtype: xml.etree.ElementTree.Element"
  },
  {
    "code": "def get_dataset(self, name, multi_instance=0):\n        return [elem for elem in self._data_list\n                if elem.name == name and elem.multi_id == multi_instance][0]",
    "docstring": "get a specific dataset.\n\n        example:\n        try:\n            gyro_data = ulog.get_dataset('sensor_gyro')\n        except (KeyError, IndexError, ValueError) as error:\n            print(type(error), \"(sensor_gyro):\", error)\n\n        :param name: name of the dataset\n        :param multi_instance: the multi_id, defaults to the first\n        :raises KeyError, IndexError, ValueError: if name or instance not found"
  },
  {
    "code": "def load_to_array(self, keys):\n        data = np.empty((len(self.data[keys[0]]), len(keys)))\n        for i in range(0, len(self.data[keys[0]])):\n            for j, key in enumerate(keys):\n                data[i, j] = self.data[key][i]\n        return data",
    "docstring": "This loads the data contained in the catalogue into a numpy array. The\n        method works only for float data\n\n        :param keys:\n            A list of keys to be uploaded into the array\n        :type list:"
  },
  {
    "code": "def get_codon(seq, codon_no, start_offset):\n    seq = seq.replace(\"-\",\"\")\n    codon_start_pos = int(codon_no - 1)*3 - start_offset\n    codon = seq[codon_start_pos:codon_start_pos + 3]\n    return codon",
    "docstring": "This function takes a sequece and a codon number and returns the codon\n    found in the sequence at that position"
  },
  {
    "code": "def _to_dsn(hosts):\n    p = urlparse(hosts)\n    try:\n        user_and_pw, netloc = p.netloc.split('@', maxsplit=1)\n    except ValueError:\n        netloc = p.netloc\n        user_and_pw = 'crate'\n    try:\n        host, port = netloc.split(':', maxsplit=1)\n    except ValueError:\n        host = netloc\n        port = 5432\n    dbname = p.path[1:] if p.path else 'doc'\n    dsn = f'postgres://{user_and_pw}@{host}:{port}/{dbname}'\n    if p.query:\n        dsn += '?' + '&'.join(k + '=' + v[0] for k, v in parse_qs(p.query).items())\n    return dsn",
    "docstring": "Convert a host URI into a dsn for aiopg.\n\n    >>> _to_dsn('aiopg://myhostname:4242/mydb')\n    'postgres://crate@myhostname:4242/mydb'\n\n    >>> _to_dsn('aiopg://myhostname:4242')\n    'postgres://crate@myhostname:4242/doc'\n\n    >>> _to_dsn('aiopg://hoschi:pw@myhostname:4242/doc?sslmode=require')\n    'postgres://hoschi:pw@myhostname:4242/doc?sslmode=require'\n\n    >>> _to_dsn('aiopg://myhostname')\n    'postgres://crate@myhostname:5432/doc'"
  },
  {
    "code": "def load_pyobj(name, pyobj):\n    'Return Sheet object of appropriate type for given sources in `args`.'\n    if isinstance(pyobj, list) or isinstance(pyobj, tuple):\n        if getattr(pyobj, '_fields', None):\n            return SheetNamedTuple(name, pyobj)\n        else:\n            return SheetList(name, pyobj)\n    elif isinstance(pyobj, dict):\n        return SheetDict(name, pyobj)\n    elif isinstance(pyobj, object):\n        return SheetObject(name, pyobj)\n    else:\n        error(\"cannot load '%s' as pyobj\" % type(pyobj).__name__)",
    "docstring": "Return Sheet object of appropriate type for given sources in `args`."
  },
  {
    "code": "def check_column(state, name, missing_msg=None, expand_msg=None):\n    if missing_msg is None:\n        missing_msg = \"We expected to find a column named `{{name}}` in the result of your query, but couldn't.\"\n    if expand_msg is None:\n        expand_msg = \"Have another look at your query result. \"\n    msg_kwargs = {\"name\": name}\n    has_result(state)\n    stu_res = state.student_result\n    sol_res = state.solution_result\n    if name not in sol_res:\n        raise BaseException(\"name %s not in solution column names\" % name)\n    if name not in stu_res:\n        _msg = state.build_message(missing_msg, fmt_kwargs=msg_kwargs)\n        state.do_test(_msg)\n    return state.to_child(\n        append_message={\"msg\": expand_msg, \"kwargs\": msg_kwargs},\n        student_result={name: stu_res[name]},\n        solution_result={name: sol_res[name]},\n    )",
    "docstring": "Zoom in on a particular column in the query result, by name.\n\n    After zooming in on a column, which is represented as a single-column query result,\n    you can use ``has_equal_value()`` to verify whether the column in the solution query result\n    matches the column in student query result.\n\n    Args:\n        name: name of the column to zoom in on.\n        missing_msg: if specified, this overrides the automatically generated feedback\n                     message in case the column is missing in the student query result.\n        expand_msg: if specified, this overrides the automatically generated feedback \n                    message that is prepended to feedback messages that are thrown\n                    further in the SCT chain.\n\n    :Example:\n\n        Suppose we are testing the following SELECT statements\n\n        * solution: ``SELECT artist_id as id, name FROM artists``\n        * student : ``SELECT artist_id, name       FROM artists``\n\n        We can write the following SCTs: ::\n\n            # fails, since no column named id in student result\n            Ex().check_column('id')\n\n            # passes, since a column named name is in student_result\n            Ex().check_column('name')"
  },
  {
    "code": "def style(self):\n        LOGGER.info('ANALYSIS : Styling')\n        classes = generate_classified_legend(\n            self.analysis_impacted,\n            self.exposure,\n            self.hazard,\n            self.use_rounding,\n            self.debug_mode)\n        hazard_class = hazard_class_field['key']\n        for layer in self._outputs():\n            without_geometries = [\n                QgsWkbTypes.NullGeometry,\n                QgsWkbTypes.UnknownGeometry]\n            if layer.geometryType() not in without_geometries:\n                display_not_exposed = False\n                if layer == self.impact or self.debug_mode:\n                    display_not_exposed = True\n                if layer.keywords['inasafe_fields'].get(hazard_class):\n                    hazard_class_style(layer, classes, display_not_exposed)\n        simple_polygon_without_brush(\n            self.aggregation_summary, aggregation_width, aggregation_color)\n        simple_polygon_without_brush(\n            self.analysis_impacted, analysis_width, analysis_color)\n        for layer in self._outputs():\n            layer.saveDefaultStyle()",
    "docstring": "Function to apply some styles to the layers."
  },
  {
    "code": "def _repr_mimebundle_(self, *args, **kwargs):\n        chart = self.to_chart()\n        dct = chart.to_dict()\n        return alt.renderers.get()(dct)",
    "docstring": "Return a MIME bundle for display in Jupyter frontends."
  },
  {
    "code": "def connect_database(url):\n    db = _connect_database(url)\n    db.copy = lambda: _connect_database(url)\n    return db",
    "docstring": "create database object by url\n\n    mysql:\n        mysql+type://user:passwd@host:port/database\n    sqlite:\n        # relative path\n        sqlite+type:///path/to/database.db\n        # absolute path\n        sqlite+type:////path/to/database.db\n        # memory database\n        sqlite+type://\n    mongodb:\n        mongodb+type://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]\n        more: http://docs.mongodb.org/manual/reference/connection-string/\n    sqlalchemy:\n        sqlalchemy+postgresql+type://user:passwd@host:port/database\n        sqlalchemy+mysql+mysqlconnector+type://user:passwd@host:port/database\n        more: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html\n    redis:\n        redis+taskdb://host:port/db\n    elasticsearch:\n        elasticsearch+type://host:port/?index=pyspider\n    local:\n        local+projectdb://filepath,filepath\n\n    type:\n        taskdb\n        projectdb\n        resultdb"
  },
  {
    "code": "def cli(env, identifier):\n    mgr = SoftLayer.NetworkManager(env.client)\n    subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier,\n                                   name='subnet')\n    if not (env.skip_confirmations or formatting.no_going_back(subnet_id)):\n        raise exceptions.CLIAbort('Aborted')\n    mgr.cancel_subnet(subnet_id)",
    "docstring": "Cancel a subnet."
  },
  {
    "code": "def calculate_localised_cost(self, d1, d2, neighbours, motions):\n        my_nbrs_with_motion = [n for n in neighbours[d1] if n in motions]\n        my_motion = (d1.center[0] - d2.center[0], d1.center[1] - d2.center[1])\n        if my_nbrs_with_motion == []:\n            distance = euclidean_dist(d1.center, d2.center) / self.scale\n        else:\n            distance = min([euclidean_dist(my_motion, motions[n]) for n in my_nbrs_with_motion]) / self.scale\n        area_change = 1 - min(d1.area, d2.area) / max(d1.area, d2.area)\n        return distance + self.parameters_cost_iteration[\"area_weight\"] * area_change",
    "docstring": "Calculates assignment cost between two cells taking into account the movement of cells neighbours.\n\n        :param CellFeatures d1: detection in first frame\n        :param CellFeatures d2: detection in second frame"
  },
  {
    "code": "def visit_delete(self, node):\n        return \"del %s\" % \", \".join(child.accept(self) for child in node.targets)",
    "docstring": "return an astroid.Delete node as string"
  },
  {
    "code": "def remove_image(self, image_id, force=False, noprune=False):\n        logger.info(\"removing image '%s' from filesystem\", image_id)\n        logger.debug(\"image_id = '%s'\", image_id)\n        if isinstance(image_id, ImageName):\n            image_id = image_id.to_str()\n        self.d.remove_image(image_id, force=force, noprune=noprune)",
    "docstring": "remove provided image from filesystem\n\n        :param image_id: str or ImageName\n        :param noprune: bool, keep untagged parents?\n        :param force: bool, force remove -- just trash it no matter what\n        :return: None"
  },
  {
    "code": "def _gmtime(timestamp):\n    try:\n        return time.gmtime(timestamp)\n    except OSError:\n        dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=timestamp)\n        dst = int(_isdst(dt))\n        return time.struct_time(dt.timetuple()[:8] + tuple([dst]))",
    "docstring": "Custom gmtime because yada yada."
  },
  {
    "code": "def _generate_union_properties(self, fields):\n        for field in fields:\n            if not is_void_type(field.data_type):\n                doc = self.process_doc(\n                    field.doc, self._docf) if field.doc else undocumented\n                warning_str = (\n                    ' @note Ensure the `is{}` method returns true before accessing, '\n                    'otherwise a runtime exception will be raised.')\n                doc += warning_str.format(fmt_camel_upper(field.name))\n                self.emit_wrapped_text(\n                    self.process_doc(doc, self._docf), prefix=comment_prefix)\n                self.emit(fmt_property(field=field))\n                self.emit()",
    "docstring": "Emits union instance properties from the given fields."
  },
  {
    "code": "def _read_audio_data(self, file_path):\n        try:\n            self.log(u\"Reading audio data...\")\n            audio_file = AudioFile(\n                file_path=file_path,\n                file_format=self.OUTPUT_AUDIO_FORMAT,\n                rconf=self.rconf,\n                logger=self.logger\n            )\n            audio_file.read_samples_from_file()\n            self.log([u\"Duration of '%s': %f\", file_path, audio_file.audio_length])\n            self.log(u\"Reading audio data... done\")\n            return (True, (\n                audio_file.audio_length,\n                audio_file.audio_sample_rate,\n                audio_file.audio_format,\n                audio_file.audio_samples\n            ))\n        except (AudioFileUnsupportedFormatError, OSError) as exc:\n            self.log_exc(u\"An unexpected error occurred while reading audio data\", exc, True, None)\n            return (False, None)",
    "docstring": "Read audio data from file.\n\n        :rtype: tuple (True, (duration, sample_rate, codec, data)) or (False, None) on exception"
  },
  {
    "code": "def get_instance_attribute(self, instance_id, attribute):\n        params = {'InstanceId' : instance_id}\n        if attribute:\n            params['Attribute'] = attribute\n        return self.get_object('DescribeInstanceAttribute', params,\n                               InstanceAttribute, verb='POST')",
    "docstring": "Gets an attribute from an instance.\n\n        :type instance_id: string\n        :param instance_id: The Amazon id of the instance\n\n        :type attribute: string\n        :param attribute: The attribute you need information about\n                          Valid choices are:\n\n                          * instanceType|kernel|ramdisk|userData|\n                          * disableApiTermination|\n                          * instanceInitiatedShutdownBehavior|\n                          * rootDeviceName|blockDeviceMapping\n\n        :rtype: :class:`boto.ec2.image.InstanceAttribute`\n        :return: An InstanceAttribute object representing the value of the\n                 attribute requested"
  },
  {
    "code": "def get_context_data(self, **kwargs):\n        context = super(CrossTypeAnimalList, self).get_context_data(**kwargs)\n        context['list_type'] = self.kwargs['breeding_type']\n        return context",
    "docstring": "This add in the context of list_type and returns this as whatever the crosstype was."
  },
  {
    "code": "def close_monomers(self, group, cutoff=4.0):\n        nearby_residues = []\n        for self_atom in self.atoms.values():\n            nearby_atoms = group.is_within(cutoff, self_atom)\n            for res_atom in nearby_atoms:\n                if res_atom.parent not in nearby_residues:\n                    nearby_residues.append(res_atom.parent)\n        return nearby_residues",
    "docstring": "Returns a list of Monomers from within a cut off distance of the Monomer\n\n        Parameters\n        ----------\n        group: BaseAmpal or Subclass\n            Group to be search for Monomers that are close to this Monomer.\n        cutoff: float\n            Distance cut off.\n\n        Returns\n        -------\n        nearby_residues: [Monomers]\n            List of Monomers within cut off distance."
  },
  {
    "code": "def ppca(Y, Q, iterations=100):\n    from numpy.ma import dot as madot\n    N, D = Y.shape\n    W = np.random.randn(D, Q) * 1e-3\n    Y = np.ma.masked_invalid(Y, copy=0)\n    mu = Y.mean(0)\n    Ycentered = Y - mu\n    try:\n        for _ in range(iterations):\n            exp_x = np.asarray_chkfinite(np.linalg.solve(W.T.dot(W), madot(W.T, Ycentered.T))).T\n            W = np.asarray_chkfinite(np.linalg.solve(exp_x.T.dot(exp_x), madot(exp_x.T, Ycentered))).T\n    except np.linalg.linalg.LinAlgError:\n        pass\n    return np.asarray_chkfinite(exp_x), np.asarray_chkfinite(W)",
    "docstring": "EM implementation for probabilistic pca.\n\n    :param array-like Y: Observed Data\n    :param int Q: Dimensionality for reduced array\n    :param int iterations: number of iterations for EM"
  },
  {
    "code": "def prepare_axes(axes, title, size, cmap=None):\n    if axes is None:\n        return None\n    axes.set_xlim([0, size[1]])\n    axes.set_ylim([size[0], 0])\n    axes.set_aspect('equal')\n    axes.axis('off')\n    if isinstance(cmap, str):\n        title = '{} (cmap: {})'.format(title, cmap)\n    axes.set_title(title)\n    axes_image = image.AxesImage(axes, cmap=cmap,\n                                 extent=(0, size[1], size[0], 0))\n    axes_image.set_data(np.random.random((size[0], size[1], 3)))\n    axes.add_image(axes_image)\n    return axes_image",
    "docstring": "Prepares an axes object for clean plotting.\n\n    Removes x and y axes labels and ticks, sets the aspect ratio to be\n    equal, uses the size to determine the drawing area and fills the image\n    with random colors as visual feedback.\n\n    Creates an AxesImage to be shown inside the axes object and sets the\n    needed properties.\n\n    Args:\n        axes:  The axes object to modify.\n        title: The title.\n        size:  The size of the expected image.\n        cmap:  The colormap if a custom color map is needed.\n                (Default: None)\n    Returns:\n        The AxesImage's handle."
  },
  {
    "code": "def servers(self):\n        url = \"%s/servers\" % self.root\n        return Servers(url=url,\n                       securityHandler=self._securityHandler,\n                       proxy_url=self._proxy_url,\n                       proxy_port=self._proxy_port)",
    "docstring": "gets the federated or registered servers for Portal"
  },
  {
    "code": "def pelix_bundles(self):\n        framework = self.__context.get_framework()\n        return {\n            bundle.get_bundle_id(): {\n                \"name\": bundle.get_symbolic_name(),\n                \"version\": bundle.get_version(),\n                \"state\": bundle.get_state(),\n                \"location\": bundle.get_location(),\n            }\n            for bundle in framework.get_bundles()\n        }",
    "docstring": "List of installed bundles"
  },
  {
    "code": "def _correct_qualimap_genome_results(samples):\n    for s in samples:\n        if verify_file(s.qualimap_genome_results_fpath):\n            correction_is_needed = False\n            with open(s.qualimap_genome_results_fpath, 'r') as f:\n                content = f.readlines()\n                metrics_started = False\n                for line in content:\n                    if \">> Reference\" in line:\n                        metrics_started = True\n                    if metrics_started:\n                        if line.find(',') != -1:\n                            correction_is_needed = True\n                            break\n            if correction_is_needed:\n                with open(s.qualimap_genome_results_fpath, 'w') as f:\n                    metrics_started = False\n                    for line in content:\n                        if \">> Reference\" in line:\n                            metrics_started = True\n                        if metrics_started:\n                            if line.find(',') != -1:\n                                line = line.replace(',', '')\n                        f.write(line)",
    "docstring": "fixing java.lang.Double.parseDouble error on entries like \"6,082.49\""
  },
  {
    "code": "def pair_looper(iterator):\n    left = START\n    for item in iterator:\n        if left is not START:\n            yield (left, item)\n        left = item",
    "docstring": "Loop through iterator yielding items in adjacent pairs"
  },
  {
    "code": "def top(self):\n        for child in self.children(skip_not_present=False):\n            if not isinstance(child, AddrmapNode):\n                continue\n            return child\n        raise RuntimeError",
    "docstring": "Returns the top-level addrmap node"
  },
  {
    "code": "def get_batched(portal_type=None, uid=None, endpoint=None, **kw):\n    results = get_search_results(portal_type=portal_type, uid=uid, **kw)\n    size = req.get_batch_size()\n    start = req.get_batch_start()\n    complete = req.get_complete(default=_marker)\n    if complete is _marker:\n        complete = uid and True or False\n    return get_batch(results, size, start, endpoint=endpoint,\n                     complete=complete)",
    "docstring": "Get batched results"
  },
  {
    "code": "def _load_scratch_orgs(self):\n        current_orgs = self.list_orgs()\n        if not self.project_config.orgs__scratch:\n            return\n        for config_name in self.project_config.orgs__scratch.keys():\n            if config_name in current_orgs:\n                continue\n            self.create_scratch_org(config_name, config_name)",
    "docstring": "Creates all scratch org configs for the project in the keychain if\n            a keychain org doesn't already exist"
  },
  {
    "code": "def lastId(self) -> BaseReference:\n        if self.childIds is not None:\n            if len(self.childIds) > 0:\n                return self.childIds[-1]\n            return None\n        else:\n            raise NotImplementedError",
    "docstring": "Last child's id of current TextualNode"
  },
  {
    "code": "def _create_dict_with_nested_keys_and_val(cls, keys, value):\n    if len(keys) > 1:\n      new_keys = keys[:-1]\n      new_val = {keys[-1]: value}\n      return cls._create_dict_with_nested_keys_and_val(new_keys, new_val)\n    elif len(keys) == 1:\n      return {keys[0]: value}\n    else:\n      raise ValueError('Keys must contain at least one key.')",
    "docstring": "Recursively constructs a nested dictionary with the keys pointing to the value.\n\n    For example:\n    Given the list of keys ['a', 'b', 'c', 'd'] and a primitive\n    value 'hello world', the method will produce the nested dictionary\n    {'a': {'b': {'c': {'d': 'hello world'}}}}. The number of keys in the list\n    defines the depth of the nested dict. If the list of keys is ['a'] and\n    the value is 'hello world', then the result would be {'a': 'hello world'}.\n\n    :param list of string keys: A list of keys to be nested as a dictionary.\n    :param primitive value: The value of the information being stored.\n    :return: dict of nested keys leading to the value."
  },
  {
    "code": "def convolve_stack(data, kernel, rot_kernel=False, method='scipy'):\n    r\n    if rot_kernel:\n        kernel = rotate_stack(kernel)\n    return np.array([convolve(data_i, kernel_i, method=method) for data_i,\n                    kernel_i in zip(data, kernel)])",
    "docstring": "r\"\"\"Convolve stack of data with stack of kernels\n\n    This method convolves the input data with a given kernel using FFT and\n    is the default convolution used for all routines\n\n    Parameters\n    ----------\n    data : np.ndarray\n        Input data array, normally a 2D image\n    kernel : np.ndarray\n        Input kernel array, normally a 2D kernel\n    rot_kernel : bool\n        Option to rotate kernels by 180 degrees\n    method : str {'astropy', 'scipy'}, optional\n        Convolution method (default is 'scipy')\n\n    Returns\n    -------\n    np.ndarray convolved data\n\n    Examples\n    --------\n    >>> from math.convolve import convolve\n    >>> import numpy as np\n    >>> a = np.arange(18).reshape(2, 3, 3)\n    >>> b = a + 10\n    >>> convolve_stack(a, b)\n    array([[[  534.,   525.,   534.],\n            [  453.,   444.,   453.],\n            [  534.,   525.,   534.]],\n    <BLANKLINE>\n           [[ 2721.,  2712.,  2721.],\n            [ 2640.,  2631.,  2640.],\n            [ 2721.,  2712.,  2721.]]])\n\n    >>> convolve_stack(a, b, rot_kernel=True)\n    array([[[  474.,   483.,   474.],\n        [  555.,   564.,   555.],\n        [  474.,   483.,   474.]],\n    <BLANKLINE>\n       [[ 2661.,  2670.,  2661.],\n        [ 2742.,  2751.,  2742.],\n        [ 2661.,  2670.,  2661.]]])\n\n    See Also\n    --------\n    convolve : The convolution function called by convolve_stack"
  },
  {
    "code": "def do(self):\r\n        'Do or redo the action'\r\n        self._runner = self._generator(*self.args, **self.kwargs)\r\n        rets = next(self._runner)\r\n        if isinstance(rets, tuple):\r\n            self._text = rets[0]\r\n            return rets[1:]\r\n        elif rets is None:\r\n            self._text = ''\r\n            return None\r\n        else:\r\n            self._text = rets\r\n            return None",
    "docstring": "Do or redo the action"
  },
  {
    "code": "def hessian(self, theta_x, theta_y, kwargs_lens, k=None, diff=0.00000001):\n        alpha_ra, alpha_dec = self.alpha(theta_x, theta_y, kwargs_lens)\n        alpha_ra_dx, alpha_dec_dx = self.alpha(theta_x + diff, theta_y, kwargs_lens)\n        alpha_ra_dy, alpha_dec_dy = self.alpha(theta_x, theta_y + diff, kwargs_lens)\n        dalpha_rara = (alpha_ra_dx - alpha_ra)/diff\n        dalpha_radec = (alpha_ra_dy - alpha_ra)/diff\n        dalpha_decra = (alpha_dec_dx - alpha_dec)/diff\n        dalpha_decdec = (alpha_dec_dy - alpha_dec)/diff\n        f_xx = dalpha_rara\n        f_yy = dalpha_decdec\n        f_xy = dalpha_radec\n        f_yx = dalpha_decra\n        return f_xx, f_xy, f_yx, f_yy",
    "docstring": "computes the hessian components f_xx, f_yy, f_xy from f_x and f_y with numerical differentiation\n\n        :param theta_x: x-position (preferentially arcsec)\n        :type theta_x: numpy array\n        :param theta_y: y-position (preferentially arcsec)\n        :type theta_y: numpy array\n        :param kwargs_lens: list of keyword arguments of lens model parameters matching the lens model classes\n        :param diff: numerical differential step (float)\n        :return: f_xx, f_xy, f_yx, f_yy"
  },
  {
    "code": "def retweet(self, id):\n        try:\n            self._client.retweet(id=id)\n            return True\n        except TweepError as e:\n            if e.api_code == TWITTER_PAGE_DOES_NOT_EXISTS_ERROR:\n                return False\n            raise",
    "docstring": "Retweet a tweet.\n\n        :param id: ID of the tweet in question\n        :return: True if success, False otherwise"
  },
  {
    "code": "def update_lbaas_healthmonitor(self, lbaas_healthmonitor, body=None):\n        return self.put(self.lbaas_healthmonitor_path % (lbaas_healthmonitor),\n                        body=body)",
    "docstring": "Updates a lbaas_healthmonitor."
  },
  {
    "code": "def reverse_segment(path, n1, n2):\n    q = path.copy()\n    if n2 > n1:\n        q[n1:(n2+1)] = path[n1:(n2+1)][::-1]\n        return q\n    else:\n        seg = np.hstack((path[n1:], path[:(n2+1)]))[::-1]\n        brk = len(q) - n1\n        q[n1:] = seg[:brk]\n        q[:(n2+1)] = seg[brk:]\n        return q",
    "docstring": "Reverse the nodes between n1 and n2."
  },
  {
    "code": "def update_multi_precision(self, index, weight, grad, state):\n        if self.multi_precision and weight.dtype == numpy.float16:\n            weight_master_copy = state[0]\n            original_state = state[1]\n            grad32 = grad.astype(numpy.float32)\n            self.update(index, weight_master_copy, grad32, original_state)\n            cast(weight_master_copy, dtype=weight.dtype, out=weight)\n        else:\n            self.update(index, weight, grad, state)",
    "docstring": "Updates the given parameter using the corresponding gradient and state.\n        Mixed precision version.\n\n        Parameters\n        ----------\n        index : int\n            The unique index of the parameter into the individual learning\n            rates and weight decays. Learning rates and weight decay\n            may be set via `set_lr_mult()` and `set_wd_mult()`, respectively.\n        weight : NDArray\n            The parameter to be updated.\n        grad : NDArray\n            The gradient of the objective with respect to this parameter.\n        state : any obj\n            The state returned by `create_state()`."
  },
  {
    "code": "def import_object(name: str) -> Any:\n    if name.count(\".\") == 0:\n        return __import__(name)\n    parts = name.split(\".\")\n    obj = __import__(\".\".join(parts[:-1]), fromlist=[parts[-1]])\n    try:\n        return getattr(obj, parts[-1])\n    except AttributeError:\n        raise ImportError(\"No module named %s\" % parts[-1])",
    "docstring": "Imports an object by name.\n\n    ``import_object('x')`` is equivalent to ``import x``.\n    ``import_object('x.y.z')`` is equivalent to ``from x.y import z``.\n\n    >>> import tornado.escape\n    >>> import_object('tornado.escape') is tornado.escape\n    True\n    >>> import_object('tornado.escape.utf8') is tornado.escape.utf8\n    True\n    >>> import_object('tornado') is tornado\n    True\n    >>> import_object('tornado.missing_module')\n    Traceback (most recent call last):\n        ...\n    ImportError: No module named missing_module"
  },
  {
    "code": "def _get_button_label(self):\n        dlg = wx.TextEntryDialog(self, _('Button label:'))\n        if dlg.ShowModal() == wx.ID_OK:\n            label = dlg.GetValue()\n        else:\n            label = \"\"\n        dlg.Destroy()\n        return label",
    "docstring": "Gets Button label from user and returns string"
  },
  {
    "code": "def _get_method_kwargs(self):\n        method_kwargs = {\n            'user': self.user,\n            'content_type': self.ctype,\n            'object_id': self.content_object.pk,\n        }\n        return method_kwargs",
    "docstring": "Helper method. Returns kwargs needed to filter the correct object.\n\n        Can also be used to create the correct object."
  },
  {
    "code": "def get_project_export(self, project_id):\n        try:\n            result = self._request('/getprojectexport/',\n                                   {'projectid': project_id})\n            return TildaProject(**result)\n        except NetworkError:\n            return []",
    "docstring": "Get project info for export"
  },
  {
    "code": "def streaming_client(self, tasks_regex, tasks_negate, workers_regex, workers_negate):\n        cc = CapturingClient(Queue(),\n                             re.compile(tasks_regex), tasks_negate,\n                             re.compile(workers_regex), workers_negate)\n        self.observers.append(cc)\n        yield cc.queue\n        self.observers.remove(cc)",
    "docstring": "Connects a client to the streaming capture, filtering the events that are sent\n        to it.\n\n        Args:\n            tasks_regex (str): a pattern to filter tasks to capture.\n                ex.: '^dispatch|^email' to filter names starting with that\n                      or 'dispatch.*123456' to filter that exact name and number\n                      or even '123456' to filter that exact number anywhere.\n            tasks_negate (bool): if True, finds tasks that do not match criteria\n            workers_regex (str): a pattern to filter workers to capture.\n                ex.: 'service|priority' to filter names containing that\n            workers_negate (bool): if True, finds workers that do not match criteria"
  },
  {
    "code": "def _encode_query(query):\n    if query == '':\n        return query\n    query_args = []\n    for query_kv in query.split('&'):\n        k, v = query_kv.split('=')\n        query_args.append(k + \"=\" + quote(v.encode('utf-8')))\n    return '&'.join(query_args)",
    "docstring": "Quote all values of a query string."
  },
  {
    "code": "def get_object_handle(self, obj):\n        if obj not in self._object_handles:\n            self._object_handles[obj] = self._get_object_handle(obj=obj)\n        return self._object_handles[obj]",
    "docstring": "Gets the vrep object handle."
  },
  {
    "code": "def install(self, host):\n        print(\"Installing..\")\n        if self._state[\"installed\"]:\n            return\n        if self.is_headless():\n            log.info(\"Headless host\")\n            return\n        print(\"aboutToQuit..\")\n        self.app.aboutToQuit.connect(self._on_application_quit)\n        if host == \"Maya\":\n            print(\"Maya host..\")\n            window = {\n                widget.objectName(): widget\n                for widget in self.app.topLevelWidgets()\n            }[\"MayaWindow\"]\n        else:\n            window = self.find_window()\n        print(\"event filter..\")\n        event_filter = self.EventFilter(window)\n        window.installEventFilter(event_filter)\n        for signal in SIGNALS_TO_REMOVE_EVENT_FILTER:\n            pyblish.api.register_callback(signal, self.uninstall)\n        log.info(\"Installed event filter\")\n        self.window = window\n        self._state[\"installed\"] = True\n        self._state[\"eventFilter\"] = event_filter",
    "docstring": "Setup common to all Qt-based hosts"
  },
  {
    "code": "def get_by_symbol(self, symbol: str) -> Commodity:\n        assert isinstance(symbol, str)\n        query = (\n            self.currencies_query\n                .filter(Commodity.mnemonic == symbol)\n        )\n        return query.one()",
    "docstring": "Loads currency by symbol"
  },
  {
    "code": "def poll(self, timeout=None):\n        p = select.poll()\n        p.register(self._fd, select.POLLIN | select.POLLPRI)\n        events = p.poll(int(timeout * 1000))\n        if len(events) > 0:\n            return True\n        return False",
    "docstring": "Poll for data available for reading from the serial port.\n\n        `timeout` can be positive for a timeout in seconds, 0 for a\n        non-blocking poll, or negative or None for a blocking poll. Default is\n        a blocking poll.\n\n        Args:\n            timeout (int, float, None): timeout duration in seconds.\n\n        Returns:\n            bool: ``True`` if data is available for reading from the serial port, ``False`` if not."
  },
  {
    "code": "def tokenize(code):\n    tok_regex = '|'.join('(?P<{}>{})'.format(*pair) for pair in _tokens)\n    tok_regex = re.compile(tok_regex, re.IGNORECASE|re.M)\n    line_num = 1\n    line_start = 0\n    for mo in re.finditer(tok_regex, code):\n        kind = mo.lastgroup\n        value = mo.group(kind)\n        if kind == 'NEWLINE':\n            line_start = mo.end()\n            line_num += 1\n        elif kind == 'SKIP' or value=='':\n            pass\n        else:\n            column = mo.start() - line_start\n            yield Token(kind, value, line_num, column)",
    "docstring": "Tokenize the string `code`"
  },
  {
    "code": "def lock_area(self, code, index):\n        logger.debug(\"locking area code %s index %s\" % (code, index))\n        return self.library.Srv_LockArea(self.pointer, code, index)",
    "docstring": "Locks a shared memory area."
  },
  {
    "code": "def install_reqs(venv, repo_dest):\n    with dir_path(repo_dest):\n        args = ['-r', 'requirements/compiled.txt']\n        if not verbose:\n            args.insert(0, '-q')\n        subprocess.check_call([os.path.join(venv, 'bin', 'pip'), 'install'] +\n                              args)",
    "docstring": "Installs all compiled requirements that can't be shipped in vendor."
  },
  {
    "code": "def add_prop_descriptor_to_class(self, class_name, new_class_attrs, names_with_refs, container_names, dataspecs):\n        from .bases import ContainerProperty\n        from .dataspec import DataSpec\n        name = self.name\n        if name in new_class_attrs:\n            raise RuntimeError(\"Two property generators both created %s.%s\" % (class_name, name))\n        new_class_attrs[name] = self\n        if self.has_ref:\n            names_with_refs.add(name)\n        if isinstance(self, BasicPropertyDescriptor):\n            if isinstance(self.property, ContainerProperty):\n                container_names.add(name)\n            if isinstance(self.property, DataSpec):\n                dataspecs[name] = self",
    "docstring": "``MetaHasProps`` calls this during class creation as it iterates\n        over properties to add, to update its registry of new properties.\n\n        The parameters passed in are mutable and this function is expected to\n        update them accordingly.\n\n        Args:\n            class_name (str) :\n                name of the class this descriptor is added to\n\n            new_class_attrs(dict[str, PropertyDescriptor]) :\n                mapping of attribute names to PropertyDescriptor that this\n                function will update\n\n            names_with_refs (set[str]) :\n                set of all property names for properties that also have\n                references, that this function will update\n\n            container_names (set[str]) :\n                set of all property names for properties that are\n                container props, that this function will update\n\n            dataspecs(dict[str, PropertyDescriptor]) :\n                mapping of attribute names to PropertyDescriptor for DataSpec\n                properties that this function will update\n\n        Return:\n            None"
  },
  {
    "code": "def error_router(self, original_handler, e):\n        if self._has_fr_route():\n            try:\n                return self.handle_error(e)\n            except Exception:\n                pass\n        return original_handler(e)",
    "docstring": "This function decides whether the error occured in a flask-restful\n        endpoint or not. If it happened in a flask-restful endpoint, our\n        handler will be dispatched. If it happened in an unrelated view, the\n        app's original error handler will be dispatched.\n        In the event that the error occurred in a flask-restful endpoint but\n        the local handler can't resolve the situation, the router will fall\n        back onto the original_handler as last resort.\n\n        :param original_handler: the original Flask error handler for the app\n        :type original_handler: function\n        :param e: the exception raised while handling the request\n        :type e: Exception"
  },
  {
    "code": "def crl_distribution_points(self):\n        if self._crl_distribution_points is None:\n            self._crl_distribution_points = self._get_http_crl_distribution_points(self.crl_distribution_points_value)\n        return self._crl_distribution_points",
    "docstring": "Returns complete CRL URLs - does not include delta CRLs\n\n        :return:\n            A list of zero or more DistributionPoint objects"
  },
  {
    "code": "def _init_params_default(self):\n        Yimp = self.Y.copy()\n        Inan = sp.isnan(Yimp)\n        Yimp[Inan] = Yimp[~Inan].mean()\n        if self.P==1:   C = sp.array([[Yimp.var()]])\n        else:           C = sp.cov(Yimp.T)\n        C /= float(self.n_randEffs)\n        for ti in range(self.n_randEffs):\n            self.getTraitCovarFun(ti).setCovariance(C)",
    "docstring": "Internal method for default parameter initialization"
  },
  {
    "code": "def delete_refund(self, refund_id):\n        request = self._delete('transactions/refunds/' + str(refund_id))\n        return self.responder(request)",
    "docstring": "Deletes an existing refund transaction."
  },
  {
    "code": "def check_initializers(initializers, keys):\n  if initializers is None:\n    return {}\n  _assert_is_dictlike(initializers, valid_keys=keys)\n  keys = set(keys)\n  if not set(initializers) <= keys:\n    extra_keys = set(initializers) - keys\n    raise KeyError(\n        \"Invalid initializer keys {}, initializers can only \"\n        \"be provided for {}\".format(\n            \", \".join(\"'{}'\".format(key) for key in extra_keys),\n            \", \".join(\"'{}'\".format(key) for key in keys)))\n  _check_nested_callables(initializers, \"Initializer\")\n  return dict(initializers)",
    "docstring": "Checks the given initializers.\n\n  This checks that `initializers` is a dictionary that only contains keys in\n  `keys`, and furthermore the entries in `initializers` are functions or\n  further dictionaries (the latter used, for example, in passing initializers\n  to modules inside modules) that must satisfy the same constraints.\n\n  Args:\n    initializers: Dictionary of initializers (allowing nested dictionaries) or\n      None.\n    keys: Iterable of valid keys for `initializers`.\n\n  Returns:\n    Copy of checked dictionary of initializers. If `initializers=None`, an empty\n    dictionary will be returned.\n\n  Raises:\n    KeyError: If an initializer is provided for a key not in `keys`.\n    TypeError: If a provided initializer is not a callable function, or\n      `initializers` is not a Mapping."
  },
  {
    "code": "def visit_compare(self, node, parent):\n        newnode = nodes.Compare(node.lineno, node.col_offset, parent)\n        newnode.postinit(\n            self.visit(node.left, newnode),\n            [\n                (self._cmp_op_classes[op.__class__], self.visit(expr, newnode))\n                for (op, expr) in zip(node.ops, node.comparators)\n            ],\n        )\n        return newnode",
    "docstring": "visit a Compare node by returning a fresh instance of it"
  },
  {
    "code": "def add_line(self, line):\n        if not self.is_valid_line(line):\n            logger.warn(\n                \"Invalid line for %s section: '%s'\",\n                self.section_name, line\n            )\n            return\n        self.lines.append(line)",
    "docstring": "Adds a given line string to the list of lines, validating the line\n        first."
  },
  {
    "code": "def _most_common(iterable):\n    data = Counter(iterable)\n    return max(data, key=data.__getitem__)",
    "docstring": "Returns the most common element in `iterable`."
  },
  {
    "code": "def set_default_encoder_parameters():\n    ARGTYPES = [ctypes.POINTER(CompressionParametersType)]\n    OPENJP2.opj_set_default_encoder_parameters.argtypes = ARGTYPES\n    OPENJP2.opj_set_default_encoder_parameters.restype = ctypes.c_void_p\n    cparams = CompressionParametersType()\n    OPENJP2.opj_set_default_encoder_parameters(ctypes.byref(cparams))\n    return cparams",
    "docstring": "Wraps openjp2 library function opj_set_default_encoder_parameters.\n\n    Sets encoding parameters to default values.  That means\n\n        lossless\n        1 tile\n        size of precinct : 2^15 x 2^15 (means 1 precinct)\n        size of code-block : 64 x 64\n        number of resolutions: 6\n        no SOP marker in the codestream\n        no EPH marker in the codestream\n        no sub-sampling in x or y direction\n        no mode switch activated\n        progression order: LRCP\n        no index file\n        no ROI upshifted\n        no offset of the origin of the image\n        no offset of the origin of the tiles\n        reversible DWT 5-3\n\n    The signature for this function differs from its C library counterpart, as\n    the the C function pass-by-reference parameter becomes the Python return\n    value.\n\n    Returns\n    -------\n    cparameters : CompressionParametersType\n        Compression parameters."
  },
  {
    "code": "def get_current_path(self):\n        path = self.tree_view.fileInfo(\n            self.tree_view.currentIndex()).filePath()\n        if not path:\n            path = self.tree_view.root_path\n        return path",
    "docstring": "Gets the path of the currently selected item."
  },
  {
    "code": "def iter_setup_packages(srcdir, packages):\n    for packagename in packages:\n        package_parts = packagename.split('.')\n        package_path = os.path.join(srcdir, *package_parts)\n        setup_package = os.path.relpath(\n            os.path.join(package_path, 'setup_package.py'))\n        if os.path.isfile(setup_package):\n            module = import_file(setup_package,\n                                 name=packagename + '.setup_package')\n            yield module",
    "docstring": "A generator that finds and imports all of the ``setup_package.py``\n    modules in the source packages.\n\n    Returns\n    -------\n    modgen : generator\n        A generator that yields (modname, mod), where `mod` is the module and\n        `modname` is the module name for the ``setup_package.py`` modules."
  },
  {
    "code": "async def sendmail(\n        self, sender, recipients, message, mail_options=None, rcpt_options=None\n    ):\n        if isinstance(recipients, str):\n            recipients = [recipients]\n        if mail_options is None:\n            mail_options = []\n        if rcpt_options is None:\n            rcpt_options = []\n        await self.ehlo_or_helo_if_needed()\n        if self.supports_esmtp:\n            if \"size\" in self.esmtp_extensions:\n                mail_options.append(\"size={}\".format(len(message)))\n        await self.mail(sender, mail_options)\n        errors = []\n        for recipient in recipients:\n            try:\n                await self.rcpt(recipient, rcpt_options)\n            except SMTPCommandFailedError as e:\n                errors.append(e)\n        if len(recipients) == len(errors):\n            raise SMTPNoRecipientError(errors)\n        await self.data(message)\n        return errors",
    "docstring": "Performs an entire e-mail transaction.\n\n        Example:\n\n            >>> try:\n            >>>     with SMTP() as client:\n            >>>         try:\n            >>>             r = client.sendmail(sender, recipients, message)\n            >>>         except SMTPException:\n            >>>             print(\"Error while sending message.\")\n            >>>         else:\n            >>>             print(\"Result: {}.\".format(r))\n            >>> except ConnectionError as e:\n            >>>     print(e)\n            Result: {}.\n\n        Args:\n            sender (str): E-mail address of the sender.\n            recipients (list of str or str): E-mail(s) address(es) of the\n                recipient(s).\n            message (str or bytes): Message body.\n            mail_options (list of str): ESMTP options (such as *8BITMIME*) to\n                send along the *MAIL* command.\n            rcpt_options (list of str): ESMTP options (such as *DSN*) to\n                send along all the *RCPT* commands.\n\n        Raises:\n            ConnectionResetError: If the connection with the server is\n                unexpectedely lost.\n            SMTPCommandFailedError: If the server refuses our EHLO/HELO\n                greeting.\n            SMTPCommandFailedError: If the server refuses our MAIL command.\n            SMTPCommandFailedError: If the server refuses our DATA command.\n            SMTPNoRecipientError: If the server refuses all given\n                recipients.\n\n        Returns:\n            dict: A dict containing an entry for each recipient that was\n                refused. Each entry is associated with  a (code, message)\n                2-tuple containing the error code and message, as returned by\n                the server.\n\n                When everythign runs smoothly, the returning dict is empty.\n\n        .. note:: The connection remains open after. It's your responsibility\n            to close it. A good practice is to use the asynchronous context\n            manager instead. See :meth:`SMTP.__aenter__` for further details."
  },
  {
    "code": "def runCommandReturnOutput(cmd):\n    splits = shlex.split(cmd)\n    proc = subprocess.Popen(\n        splits, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    stdout, stderr = proc.communicate()\n    if proc.returncode != 0:\n        raise subprocess.CalledProcessError(stdout, stderr)\n    return stdout, stderr",
    "docstring": "Runs a shell command and return the stdout and stderr"
  },
  {
    "code": "def _str_dtype(dtype):\n        assert dtype.byteorder != '>'\n        if dtype.kind == 'i':\n            assert dtype.itemsize == 8\n            return 'int64'\n        elif dtype.kind == 'f':\n            assert dtype.itemsize == 8\n            return 'float64'\n        elif dtype.kind == 'U':\n            return 'U%d' % (dtype.itemsize / 4)\n        else:\n            raise UnhandledDtypeException(\"Bad dtype '%s'\" % dtype)",
    "docstring": "Represent dtypes without byte order, as earlier Java tickstore code doesn't support explicit byte order."
  },
  {
    "code": "def _psed(text,\n          before,\n          after,\n          limit,\n          flags):\n    atext = text\n    if limit:\n        limit = re.compile(limit)\n        comps = text.split(limit)\n        atext = ''.join(comps[1:])\n    count = 1\n    if 'g' in flags:\n        count = 0\n        flags = flags.replace('g', '')\n    aflags = 0\n    for flag in flags:\n        aflags |= RE_FLAG_TABLE[flag]\n    before = re.compile(before, flags=aflags)\n    text = re.sub(before, after, atext, count=count)\n    return text",
    "docstring": "Does the actual work for file.psed, so that single lines can be passed in"
  },
  {
    "code": "def trigger_actions(self, subsystem):\n        for py3_module, trigger_action in self.udev_consumers[subsystem]:\n            if trigger_action in ON_TRIGGER_ACTIONS:\n                self.py3_wrapper.log(\n                    \"%s udev event, refresh consumer %s\"\n                    % (subsystem, py3_module.module_full_name)\n                )\n                py3_module.force_update()",
    "docstring": "Refresh all modules which subscribed to the given subsystem."
  },
  {
    "code": "def to_text(self, line):\n        return getattr(self, self.ENTRY_TRANSFORMERS[line.__class__])(line)",
    "docstring": "Return the textual representation of the given `line`."
  },
  {
    "code": "def fault_zone(self, zone, simulate_wire_problem=False):\n        if isinstance(zone, tuple):\n            expander_idx, channel = zone\n            zone = self._zonetracker.expander_to_zone(expander_idx, channel)\n        status = 2 if simulate_wire_problem else 1\n        self.send(\"L{0:02}{1}\\r\".format(zone, status))",
    "docstring": "Faults a zone if we are emulating a zone expander.\n\n        :param zone: zone to fault\n        :type zone: int\n        :param simulate_wire_problem: Whether or not to simulate a wire fault\n        :type simulate_wire_problem: bool"
  },
  {
    "code": "def query_certificate(self, cert_hash):\n        try:\n            cquery = self.pssl.query_cert(cert_hash)\n        except Exception:\n            self.error('Exception during processing with passiveSSL. '\n                       'This happens if the given hash is not sha1 or contains dashes/colons etc. '\n                       'Please make sure to submit a clean formatted sha1 hash.')\n        try:\n            cfetch = self.pssl.fetch_cert(cert_hash, make_datetime=False)\n        except Exception:\n            cfetch = {}\n        return {'query': cquery,\n                'cert': cfetch}",
    "docstring": "Queries Circl.lu Passive SSL for a certificate hash using PyPSSL class. Returns error if nothing is found.\n\n        :param cert_hash: hash to query for\n        :type cert_hash: str\n        :return: python dict of results\n        :rtype: dict"
  },
  {
    "code": "def finish(self):\n        os.system('setterm -cursor on')\n        if self.nl:\n            Echo(self.label).done()",
    "docstring": "Update widgets on finish"
  },
  {
    "code": "def check_token(self, token, allowed_roles, resource, method):\n        resource_conf = config.DOMAIN[resource]\n        audiences = resource_conf.get('audiences', config.JWT_AUDIENCES)\n        return self._perform_verification(token, audiences, allowed_roles)",
    "docstring": "This function is called when a token is sent throught the access_token\n        parameter or the Authorization header as specified in the oAuth 2 specification.\n\n        The provided token is validated with the JWT_SECRET defined in the Eve configuration.\n        The token issuer (iss claim) must be the one specified by JWT_ISSUER and the audience\n        (aud claim) must be one of the value(s) defined by the either the \"audiences\" resource\n        parameter or the global JWT_AUDIENCES configuration.\n\n        If JWT_ROLES_CLAIM is defined and a claim by that name is present in the token, roles\n        are checked using this claim.\n\n        If a JWT_SCOPE_CLAIM is defined and a claim by that name is present in the token, the\n        claim value is check, and if \"viewer\" is present, only GET and HEAD methods will be\n        allowed. The scope name is then added to the list of roles with the scope: prefix.\n\n        If the validation succeed, the claims are stored and accessible thru the\n        get_authen_claims() method."
  },
  {
    "code": "def extractVersion(string, default='?'):\n    return extract(VERSION_PATTERN, string, condense=True, default=default,\n                   one=True)",
    "docstring": "Extracts a three digit standard format version number"
  },
  {
    "code": "def calc_fft_with_PyCUDA(Signal):\n    print(\"starting fft\")\n    Signal = Signal.astype(_np.float32)\n    Signal_gpu = _gpuarray.to_gpu(Signal)\n    Signalfft_gpu = _gpuarray.empty(len(Signal)//2+1,_np.complex64)\n    plan = _Plan(Signal.shape,_np.float32,_np.complex64)\n    _fft(Signal_gpu, Signalfft_gpu, plan)\n    Signalfft = Signalfft_gpu.get()\n    Signalfft = _np.hstack((Signalfft,_np.conj(_np.flipud(Signalfft[1:len(Signal)//2]))))\n    print(\"fft done\")\n    return Signalfft",
    "docstring": "Calculates the FFT of the passed signal by using\n    the scikit-cuda libary which relies on PyCUDA\n\n    Parameters\n    ----------\n    Signal : ndarray\n        Signal to be transformed into Fourier space\n\n    Returns\n    -------\n    Signalfft : ndarray\n        Array containing the signal's FFT"
  },
  {
    "code": "def list_ifd(self):\n        i = self._first_ifd()\n        ifds = []\n        while i:\n            ifds.append(i)\n            i = self._next_ifd(i)\n        return ifds",
    "docstring": "Return the list of IFDs in the header."
  },
  {
    "code": "def highlight_null(self, null_color='red'):\n        self.applymap(self._highlight_null, null_color=null_color)\n        return self",
    "docstring": "Shade the background ``null_color`` for missing values.\n\n        Parameters\n        ----------\n        null_color : str\n\n        Returns\n        -------\n        self : Styler"
  },
  {
    "code": "def with_host(self, host):\n        if not isinstance(host, str):\n            raise TypeError(\"Invalid host type\")\n        if not self.is_absolute():\n            raise ValueError(\"host replacement is not allowed \" \"for relative URLs\")\n        if not host:\n            raise ValueError(\"host removing is not allowed\")\n        host = self._encode_host(host)\n        val = self._val\n        return URL(\n            self._val._replace(\n                netloc=self._make_netloc(\n                    val.username, val.password, host, val.port, encode=False\n                )\n            ),\n            encoded=True,\n        )",
    "docstring": "Return a new URL with host replaced.\n\n        Autoencode host if needed.\n\n        Changing host for relative URLs is not allowed, use .join()\n        instead."
  },
  {
    "code": "def get_all_json_from_indexq(self):\n        files = self.get_all_as_list()\n        out = []\n        for efile in files:\r\n            out.extend(self._open_file(efile))\r\n        return out",
    "docstring": "Gets all data from the todo files in indexq and returns one huge list of all data."
  },
  {
    "code": "def write_data(self, data, start_position=0):\n\t\tif len(data) > self.height():\n\t\t\traise ValueError('Data too long (too many strings)')\n\t\tfor i in range(len(data)):\n\t\t\tself.write_line(start_position + i, data[i])",
    "docstring": "Write data from the specified line\n\n\t\t:param data: string to write, each one on new line\n\t\t:param start_position: starting line\n\t\t:return:"
  },
  {
    "code": "def bind_unix_socket(file_, mode=0o600, backlog=_DEFAULT_BACKLOG):\n    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n    sock.setblocking(0)\n    try:\n        st = os.stat(file_)\n    except OSError as err:\n        if err.errno != errno.ENOENT:\n            raise\n    else:\n        if stat.S_ISSOCK(st.st_mode):\n            os.remove(file_)\n        else:\n            raise ValueError('File %s exists and is not a socket', file_)\n    sock.bind(file_)\n    os.chmod(file_, mode)\n    sock.listen(backlog)\n    return sock",
    "docstring": "Creates a listening unix socket.\n\n    If a socket with the given name already exists, it will be deleted.\n    If any other file with that name exists, an exception will be\n    raised.\n\n    Returns a socket object (not a list of socket objects like\n    `bind_sockets`)"
  },
  {
    "code": "def _edge_list_to_sframe(ls, src_column_name, dst_column_name):\n    sf = SFrame()\n    if type(ls) == list:\n        cols = reduce(set.union, (set(v.attr.keys()) for v in ls))\n        sf[src_column_name] = [e.src_vid for e in ls]\n        sf[dst_column_name] = [e.dst_vid for e in ls]\n        for c in cols:\n            sf[c] = [e.attr.get(c) for e in ls]\n    elif type(ls) == Edge:\n        sf[src_column_name] = [ls.src_vid]\n        sf[dst_column_name] = [ls.dst_vid]\n    else:\n        raise TypeError('Edges type {} is Not supported.'.format(type(ls)))\n    return sf",
    "docstring": "Convert a list of edges into an SFrame."
  },
  {
    "code": "def dict_head(d, N=5):\n    return {k: d[k] for k in list(d.keys())[:N]}",
    "docstring": "Return the head of a dictionary. It will be random!\n\n    Default is to return the first 5 key/value pairs in a dictionary.\n\n    Args:\n        d: Dictionary to get head.\n        N: Number of elements to display.\n\n    Returns:\n        dict: the first N items of the dictionary."
  },
  {
    "code": "def on_lstCategories_itemSelectionChanged(self):\n        self.clear_further_steps()\n        purpose = self.selected_purpose()\n        if not purpose:\n            return\n        self.lblDescribeCategory.setText(purpose[\"description\"])\n        self.lblIconCategory.setPixmap(QPixmap(\n            resources_path('img', 'wizard', 'keyword-category-%s.svg'\n                           % (purpose['key'] or 'notset'))))\n        self.parent.pbnNext.setEnabled(True)",
    "docstring": "Update purpose description label.\n\n        .. note:: This is an automatic Qt slot\n           executed when the purpose selection changes."
  },
  {
    "code": "def optimise_z(z, *args):\n    x, y, elements, coordinates = args\n    window_com = np.array([x, y, z])\n    return pore_diameter(elements, coordinates, com=window_com)[0]",
    "docstring": "Return pore diameter for coordinates optimisation in z direction."
  },
  {
    "code": "def simulated_quantize(x, num_bits, noise):\n  shape = x.get_shape().as_list()\n  if not (len(shape) >= 2 and shape[-1] > 1):\n    return x\n  max_abs = tf.reduce_max(tf.abs(x), -1, keepdims=True) + 1e-9\n  max_int = 2 ** (num_bits - 1) - 1\n  scale = max_abs / max_int\n  x /= scale\n  x = tf.floor(x + noise)\n  x *= scale\n  return x",
    "docstring": "Simulate quantization to num_bits bits, with externally-stored scale.\n\n  num_bits is the number of bits used to store each value.\n  noise is a float32 Tensor containing values in [0, 1).\n  Each value in noise should take different values across\n  different steps, approximating a uniform distribution over [0, 1).\n  In the case of replicated TPU training, noise should be identical\n  across replicas in order to keep the parameters identical across replicas.\n\n  The natural choice for noise would be tf.random_uniform(),\n  but this is not possible for TPU, since there is currently no way to seed\n  the different cores to produce identical values across replicas.  Instead we\n  use noise_from_step_num() (see below).\n\n  The quantization scheme is as follows:\n\n  Compute the maximum absolute value by row (call this max_abs).\n  Store this either in an auxiliary variable or in an extra column.\n\n  Divide the parameters by (max_abs / (2^(num_bits-1)-1)).  This gives a\n  float32 value in the range [-2^(num_bits-1)-1, 2^(num_bits-1)-1]\n\n  Unbiased randomized roundoff by adding noise and rounding down.\n\n  This produces a signed integer with num_bits bits which can then be stored.\n\n  Args:\n    x: a float32 Tensor\n    num_bits: an integer between 1 and 22\n    noise: a float Tensor broadcastable to the shape of x.\n\n  Returns:\n    a float32 Tensor"
  },
  {
    "code": "def clear(self):\n        self.io.seek(0)\n        self.io.truncate()\n        for item in self.monitors:\n            item[2] = 0",
    "docstring": "Removes all data from the buffer."
  },
  {
    "code": "def fill_notebook(work_notebook, script_blocks):\n    for blabel, bcontent, lineno in script_blocks:\n        if blabel == 'code':\n            add_code_cell(work_notebook, bcontent)\n        else:\n            add_markdown_cell(work_notebook, bcontent + '\\n')",
    "docstring": "Writes the Jupyter notebook cells\n\n    Parameters\n    ----------\n    script_blocks : list\n        Each list element should be a tuple of (label, content, lineno)."
  },
  {
    "code": "def validate_enum_attribute(self, attribute: str,\n                                candidates: Set[Union[str, int, float]]) -> None:\n        self.add_errors(\n            validate_enum_attribute(self.fully_qualified_name, self._spec, attribute, candidates))",
    "docstring": "Validates that the attribute value is among the candidates"
  },
  {
    "code": "def get_migrations_to_down(self, migration_id):\n        migration_id = MigrationFile.validate_id(migration_id)\n        if not migration_id:\n            return []\n        migrations = self.get_migration_files()\n        last_migration_id = self.get_last_migrated_id()\n        if migration_id in (m.id for m in self.get_unregistered_migrations()):\n            logger.error('Migration is not applied %s' % migration_id)\n            return []\n        try:\n            migration = [m for m in migrations if m.id == migration_id][0]\n        except IndexError:\n            logger.error('Migration does not exists %s' % migration_id)\n            return []\n        return list(reversed([m for m in migrations\n                              if migration.id <= m.id <= last_migration_id]))",
    "docstring": "Find migrations to rollback."
  },
  {
    "code": "def pointspace(self, **kwargs):\n        scale_array = numpy.array([\n            [prefix_factor(self.independent)**(-1)],\n            [prefix_factor(self.dependent)**(-1)]\n        ])\n        linspace = numpy.linspace(self.limits[0], self.limits[1], **kwargs)\n        return {\n          'data': self.data.array * scale_array,\n          'fit': numpy.array([linspace, self.fitted_function(linspace)]) * scale_array\n        }",
    "docstring": "Returns a dictionary with the keys `data` and `fit`.\n\n        `data` is just `scipy_data_fitting.Data.array`.\n\n        `fit` is a two row [`numpy.ndarray`][1], the first row values correspond\n        to the independent variable and are generated using [`numpy.linspace`][2].\n        The second row are the values of `scipy_data_fitting.Fit.fitted_function`\n        evaluated on the linspace.\n\n        For both `fit` and `data`, each row will be scaled by the corresponding\n        inverse prefix if given in `scipy_data_fitting.Fit.independent`\n        or `scipy_data_fitting.Fit.dependent`.\n\n        Any keyword arguments are passed to [`numpy.linspace`][2].\n\n        [1]: http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html\n        [2]: http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html"
  },
  {
    "code": "def to_frame(self, index=True, name=None):\n        from pandas import DataFrame\n        if name is not None:\n            if not is_list_like(name):\n                raise TypeError(\"'name' must be a list / sequence \"\n                                \"of column names.\")\n            if len(name) != len(self.levels):\n                raise ValueError(\"'name' should have same length as \"\n                                 \"number of levels on index.\")\n            idx_names = name\n        else:\n            idx_names = self.names\n        result = DataFrame(\n            OrderedDict([\n                ((level if lvlname is None else lvlname),\n                 self._get_level_values(level))\n                for lvlname, level in zip(idx_names, range(len(self.levels)))\n            ]),\n            copy=False\n        )\n        if index:\n            result.index = self\n        return result",
    "docstring": "Create a DataFrame with the levels of the MultiIndex as columns.\n\n        Column ordering is determined by the DataFrame constructor with data as\n        a dict.\n\n        .. versionadded:: 0.24.0\n\n        Parameters\n        ----------\n        index : boolean, default True\n            Set the index of the returned DataFrame as the original MultiIndex.\n\n        name : list / sequence of strings, optional\n            The passed names should substitute index level names.\n\n        Returns\n        -------\n        DataFrame : a DataFrame containing the original MultiIndex data.\n\n        See Also\n        --------\n        DataFrame"
  },
  {
    "code": "def getOverlayDualAnalogTransform(self, ulOverlay, eWhich):\n        fn = self.function_table.getOverlayDualAnalogTransform\n        pvCenter = HmdVector2_t()\n        pfRadius = c_float()\n        result = fn(ulOverlay, eWhich, byref(pvCenter), byref(pfRadius))\n        return result, pvCenter, pfRadius.value",
    "docstring": "Gets the analog input to Dual Analog coordinate scale for the specified overlay."
  },
  {
    "code": "def render_path(self, template_path, *context, **kwargs):\n        loader = self._make_loader()\n        template = loader.read(template_path)\n        return self._render_string(template, *context, **kwargs)",
    "docstring": "Render the template at the given path using the given context.\n\n        Read the render() docstring for more information."
  },
  {
    "code": "def OnSafeModeEntry(self, event):\n        self.main_window.main_menu.enable_file_approve(True)\n        self.main_window.grid.Refresh()\n        event.Skip()",
    "docstring": "Safe mode entry event handler"
  },
  {
    "code": "def apply_visitor(visitor, decl_inst):\n    fname = 'visit_' + \\\n        decl_inst.__class__.__name__[:-2]\n    if not hasattr(visitor, fname):\n        raise runtime_errors.visit_function_has_not_been_found_t(\n            visitor, decl_inst)\n    return getattr(visitor, fname)()",
    "docstring": "Applies a visitor on declaration instance.\n\n    :param visitor: instance\n    :type visitor: :class:`type_visitor_t` or :class:`decl_visitor_t`"
  },
  {
    "code": "def _create_dist(self,\n                   dist_tgt,\n                   dist_target_dir,\n                   setup_requires_pex,\n                   snapshot_fingerprint,\n                   is_platform_specific):\n    self._copy_sources(dist_tgt, dist_target_dir)\n    setup_py_snapshot_version_argv = self._generate_snapshot_bdist_wheel_argv(\n      snapshot_fingerprint, is_platform_specific)\n    cmd = safe_shlex_join(setup_requires_pex.cmdline(setup_py_snapshot_version_argv))\n    with self.context.new_workunit('setup.py', cmd=cmd, labels=[WorkUnitLabel.TOOL]) as workunit:\n      with pushd(dist_target_dir):\n        result = setup_requires_pex.run(args=setup_py_snapshot_version_argv,\n                                        stdout=workunit.output('stdout'),\n                                        stderr=workunit.output('stderr'))\n        if result != 0:\n          raise self.BuildLocalPythonDistributionsError(\n            \"Installation of python distribution from target {target} into directory {into_dir} \"\n            \"failed (return value of run() was: {rc!r}).\\n\"\n            \"The pex with any requirements is located at: {interpreter}.\\n\"\n            \"The host system's compiler and linker were used.\\n\"\n            \"The setup command was: {command}.\"\n            .format(target=dist_tgt,\n                    into_dir=dist_target_dir,\n                    rc=result,\n                    interpreter=setup_requires_pex.path(),\n                    command=setup_py_snapshot_version_argv))",
    "docstring": "Create a .whl file for the specified python_distribution target."
  },
  {
    "code": "def greg2julian(year, month, day, hour, minute, second):\n    year = year.astype(float)\n    month = month.astype(float)\n    day = day.astype(float)\n    timeut = hour.astype(float) + (minute.astype(float) / 60.0) + \\\n        (second / 3600.0)\n    julian_time = ((367.0 * year) -\n                   np.floor(\n                       7.0 * (year + np.floor((month + 9.0) / 12.0)) / 4.0) -\n                   np.floor(3.0 *\n                            (np.floor((year + (month - 9.0) / 7.0) / 100.0) +\n                             1.0) / 4.0) +\n                   np.floor((275.0 * month) / 9.0) +\n                   day + 1721028.5 + (timeut / 24.0))\n    return julian_time",
    "docstring": "Function to convert a date from Gregorian to Julian format\n\n    :param year:\n        Year of events (integer numpy.ndarray)\n    :param month:\n        Month of events (integer numpy.ndarray)\n    :param day:\n        Days of event (integer numpy.ndarray)\n    :param hour:\n        Hour of event (integer numpy.ndarray)\n    :param minute:\n        Minute of event (integer numpy.ndarray)\n    :param second:\n        Second of event (float numpy.ndarray)\n    :returns julian_time:\n        Julian representation of the time (as float numpy.ndarray)"
  },
  {
    "code": "def load_or_import_from_config(key, app=None, default=None):\n    app = app or current_app\n    imp = app.config.get(key)\n    return obj_or_import_string(imp, default=default)",
    "docstring": "Load or import value from config.\n\n    :returns: The loaded value."
  },
  {
    "code": "def probe(w, name=None):\n    if not isinstance(w, WireVector):\n        raise PyrtlError('Only WireVectors can be probed')\n    if name is None:\n        name = '(%s: %s)' % (probeIndexer.make_valid_string(), w.name)\n    print(\"Probe: \" + name + ' ' + get_stack(w))\n    p = Output(name=name)\n    p <<= w\n    return w",
    "docstring": "Print useful information about a WireVector when in debug mode.\n\n    :param w: WireVector from which to get info\n    :param name: optional name for probe (defaults to an autogenerated name)\n    :return: original WireVector w\n\n    Probe can be inserted into a existing design easily as it returns the\n    original wire unmodified. For example ``y <<= x[0:3] + 4`` could be turned\n    into ``y <<= probe(x)[0:3] + 4`` to give visibility into both the origin of\n    ``x`` (including the line that WireVector was originally created) and\n    the run-time values of ``x`` (which will be named and thus show up by\n    default in a trace.  Likewise ``y <<= probe(x[0:3]) + 4``,\n    ``y <<= probe(x[0:3] + 4)``, and ``probe(y) <<= x[0:3] + 4`` are all\n    valid uses of `probe`.\n\n    Note: `probe` does actually add a wire to the working block of w (which can\n    confuse various post-processing transforms such as output to verilog)."
  },
  {
    "code": "def process_selectors(self, index=0, flags=0):\n        return self.parse_selectors(self.selector_iter(self.pattern), index, flags)",
    "docstring": "Process selectors.\n\n        We do our own selectors as BeautifulSoup4 has some annoying quirks,\n        and we don't really need to do nth selectors or siblings or\n        descendants etc."
  },
  {
    "code": "def enclosure_directed(self):\n        root, enclosure = polygons.enclosure_tree(self.polygons_closed)\n        self._cache['root'] = root\n        return enclosure",
    "docstring": "Networkx DiGraph of polygon enclosure"
  },
  {
    "code": "def rename(self, **mapping):\n        params = {k: v for k, v in self.get_param_values() if k != 'name'}\n        return self.__class__(rename=mapping,\n                              source=(self._source() if self._source else None),\n                              linked=self.linked, **params)",
    "docstring": "The rename method allows stream parameters to be allocated to\n        new names to avoid clashes with other stream parameters of the\n        same name. Returns a new clone of the stream instance with the\n        specified name mapping."
  },
  {
    "code": "def start(self, local_port, remote_address, remote_port):\n        self.local_port = local_port\n        self.remote_address = remote_address\n        self.remote_port = remote_port\n        logger.debug((\"Starting ssh tunnel {0}:{1}:{2} for \"\n                      \"{3}@{4}\".format(local_port, remote_address, remote_port,\n                                       self.username, self.address)))\n        self.forward = Forward(local_port,\n                               remote_address,\n                               remote_port,\n                               self.transport)\n        self.forward.start()",
    "docstring": "Start ssh tunnel\n\n        type: local_port: int\n        param: local_port: local tunnel endpoint ip binding\n        type: remote_address: str\n        param: remote_address: Remote tunnel endpoing ip binding\n        type: remote_port: int\n        param: remote_port: Remote tunnel endpoint port binding"
  },
  {
    "code": "def rate_of_change(data, period):\n    catch_errors.check_for_period_error(data, period)\n    rocs = [((data[idx] - data[idx - (period - 1)]) /\n         data[idx - (period - 1)]) * 100 for idx in range(period - 1, len(data))]\n    rocs = fill_for_noncomputable_vals(data, rocs)\n    return rocs",
    "docstring": "Rate of Change.\n\n    Formula:\n    (Close - Close n periods ago) / (Close n periods ago) * 100"
  },
  {
    "code": "def probes_used_extract_scores(full_scores, same_probes):\n  if full_scores.shape[1] != same_probes.shape[0]: raise \"Size mismatch\"\n  import numpy as np\n  model_scores = np.ndarray((full_scores.shape[0],np.sum(same_probes)), 'float64')\n  c=0\n  for i in range(0,full_scores.shape[1]):\n    if same_probes[i]:\n      for j in range(0,full_scores.shape[0]):\n        model_scores[j,c] = full_scores[j,i]\n      c+=1\n  return model_scores",
    "docstring": "Extracts a matrix of scores for a model, given a probes_used row vector of boolean"
  },
  {
    "code": "def _readall(self, file, count):\n        data = b\"\"\n        while len(data) < count:\n            d = file.read(count - len(data))\n            if not d:\n                raise GeneralProxyError(\"Connection closed unexpectedly\")\n            data += d\n        return data",
    "docstring": "Receive EXACTLY the number of bytes requested from the file object.\n        Blocks until the required number of bytes have been received."
  },
  {
    "code": "def lockfile(lockfile_name, lock_wait_timeout=-1):\n    def decorator(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            lock = FileLock(lockfile_name)\n            try:\n                lock.acquire(lock_wait_timeout)\n            except AlreadyLocked:\n                return\n            except LockTimeout:\n                return\n            try:\n                result = func(*args, **kwargs)\n            finally:\n                lock.release()\n            return result\n        return wrapper\n    return decorator",
    "docstring": "Only runs the method if the lockfile is not acquired.\n\n    You should create a setting ``LOCKFILE_PATH`` which points to\n    ``/home/username/tmp/``.\n\n    In your management command, use it like so::\n\n        LOCKFILE = os.path.join(\n            settings.LOCKFILE_FOLDER, 'command_name')\n\n        class Command(NoArgsCommand):\n            @lockfile(LOCKFILE)\n            def handle_noargs(self, **options):\n                # your command here\n\n    :lockfile_name: A unique name for a lockfile that belongs to the wrapped\n      method.\n    :lock_wait_timeout: Seconds to wait if lockfile is acquired. If ``-1`` we\n      will not wait and just quit."
  },
  {
    "code": "def _GetOrderedEntries(data):\n  def Tag(field):\n    if isinstance(field, string_types):\n      return 0, field\n    if isinstance(field, int):\n      return 1, field\n    message = \"Unexpected field '{}' of type '{}'\".format(field, type(field))\n    raise TypeError(message)\n  for field in sorted(iterkeys(data), key=Tag):\n    yield data[field]",
    "docstring": "Gets entries of `RDFProtoStruct` in a well-defined order.\n\n  Args:\n    data: A raw data dictionary of `RDFProtoStruct`.\n\n  Yields:\n    Entries of the structured in a well-defined order."
  },
  {
    "code": "def mean_squared_error(pred:Tensor, targ:Tensor)->Rank0Tensor:\n    \"Mean squared error between `pred` and `targ`.\"\n    pred,targ = flatten_check(pred,targ)\n    return F.mse_loss(pred, targ)",
    "docstring": "Mean squared error between `pred` and `targ`."
  },
  {
    "code": "def instance_norm(x):\n  with tf.variable_scope(\"instance_norm\"):\n    epsilon = 1e-5\n    mean, var = tf.nn.moments(x, [1, 2], keep_dims=True)\n    scale = tf.get_variable(\n        \"scale\", [x.get_shape()[-1]],\n        initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.02))\n    offset = tf.get_variable(\n        \"offset\", [x.get_shape()[-1]], initializer=tf.constant_initializer(0.0))\n    out = scale * tf.div(x - mean, tf.sqrt(var + epsilon)) + offset\n    return out",
    "docstring": "Instance normalization layer."
  },
  {
    "code": "def funding_info(self, key, value):\n    return {\n        'agency': value.get('a'),\n        'grant_number': value.get('c'),\n        'project_number': value.get('f'),\n    }",
    "docstring": "Populate the ``funding_info`` key."
  },
  {
    "code": "def remove_example(self, data, cloud=None, batch=False, api_key=None, version=None, **kwargs):\n        batch = detect_batch(data)\n        data = data_preprocess(data, batch=batch)\n        url_params = {\"batch\": batch, \"api_key\": api_key, \"version\": version, 'method': 'remove_example'}\n        return self._api_handler(data, cloud=cloud, api=\"custom\", url_params=url_params, **kwargs)",
    "docstring": "This is an API made to remove a single instance of training data. This is useful in cases where a\n        single instance of content has been modified, but the remaining examples remain valid. For\n        example, if a piece of content has been retagged.\n\n        Inputs\n        data - String: The exact text you wish to remove from the given collection. If the string\n          provided does not match a known piece of text then this will fail. Again, this is required if\n          an id is not provided, and vice-versa.\n        api_key (optional) - String: Your API key, required only if the key has not been declared\n          elsewhere. This allows the API to recognize a request as yours and automatically route it\n          to the appropriate destination.\n        cloud (optional) - String: Your private cloud domain, required only if the key has not been declared\n          elsewhere. This allows the API to recognize a request as yours and automatically route it\n          to the appropriate destination."
  },
  {
    "code": "def html_encode(text):\n    text = text.replace('&', '&amp;')\n    text = text.replace('<', '&lt;')\n    text = text.replace('>', '&gt;')\n    text = text.replace('\"', '&quot;')\n    return text",
    "docstring": "Encode characters with a special meaning as HTML.\n\n    :param text: The plain text (a string).\n    :returns: The text converted to HTML (a string)."
  },
  {
    "code": "def _parse_ppm_segment(self, fptr):\n        offset = fptr.tell() - 2\n        read_buffer = fptr.read(3)\n        length, zppm = struct.unpack('>HB', read_buffer)\n        numbytes = length - 3\n        read_buffer = fptr.read(numbytes)\n        return PPMsegment(zppm, read_buffer, length, offset)",
    "docstring": "Parse the PPM segment.\n\n        Parameters\n        ----------\n        fptr : file\n            Open file object.\n\n        Returns\n        -------\n        PPMSegment\n            The current PPM segment."
  },
  {
    "code": "def count_courses(self):\n        c = 0\n        for x in self.tuning:\n            if type(x) == list:\n                c += len(x)\n            else:\n                c += 1\n        return float(c) / len(self.tuning)",
    "docstring": "Return the average number of courses per string."
  },
  {
    "code": "def get_catalog_hierarchy_design_session(self, proxy):\n        if not self.supports_catalog_hierarchy_design():\n            raise errors.Unimplemented()\n        return sessions.CatalogHierarchyDesignSession(proxy=proxy, runtime=self._runtime)",
    "docstring": "Gets the catalog hierarchy design session.\n\n        arg:    proxy (osid.proxy.Proxy): proxy\n        return: (osid.cataloging.CatalogHierarchyDesignSession) - a\n                ``CatalogHierarchyDesignSession``\n        raise:  NullArgument - ``proxy`` is null\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_catalog_hierarchy_design()``\n                is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_catalog_hierarchy_design()`` is ``true``.*"
  },
  {
    "code": "def transform(self, X):\n        return self.sess.run(self.z_mean, feed_dict={self.x: X})",
    "docstring": "Transform data by mapping it into the latent space."
  },
  {
    "code": "def get_logx(nlive, simulate=False):\n    r\n    assert nlive.min() > 0, (\n        'nlive contains zeros or negative values! nlive = ' + str(nlive))\n    if simulate:\n        logx_steps = np.log(np.random.random(nlive.shape)) / nlive\n    else:\n        logx_steps = -1 * (nlive.astype(float) ** -1)\n    return np.cumsum(logx_steps)",
    "docstring": "r\"\"\"Returns a logx vector showing the expected or simulated logx positions\n    of points.\n\n    The shrinkage factor between two points\n\n    .. math:: t_i = X_{i-1} / X_{i}\n\n    is distributed as the largest of :math:`n_i` uniform random variables\n    between 1 and 0, where :math:`n_i` is the local number of live points.\n\n    We are interested in\n\n    .. math:: \\log(t_i) = \\log X_{i-1} - \\log X_{i}\n\n    which has expected value :math:`-1/n_i`.\n\n    Parameters\n    ----------\n    nlive_array: 1d numpy array\n        Ordered local number of live points present at each point's\n        iso-likelihood contour.\n    simulate: bool, optional\n        Should log prior volumes logx be simulated from their distribution (if\n        False their expected values are used).\n\n    Returns\n    -------\n    logx: 1d numpy array\n        log X values for points."
  },
  {
    "code": "def _FlushAllRows(self, db_connection, table_name):\n    for sql in db_connection.iterdump():\n      if (sql.startswith(\"CREATE TABLE\") or\n          sql.startswith(\"BEGIN TRANSACTION\") or sql.startswith(\"COMMIT\")):\n        continue\n      yield self.archive_generator.WriteFileChunk((sql + \"\\n\").encode(\"utf-8\"))\n    with db_connection:\n      db_connection.cursor().execute(\"DELETE FROM \\\"%s\\\";\" % table_name)",
    "docstring": "Copies rows from the given db into the output file then deletes them."
  },
  {
    "code": "def refactor(self, items, write=False, doctests_only=False):\n        for dir_or_file in items:\n            if os.path.isdir(dir_or_file):\n                self.refactor_dir(dir_or_file, write, doctests_only)\n            else:\n                self.refactor_file(dir_or_file, write, doctests_only)",
    "docstring": "Refactor a list of files and directories."
  },
  {
    "code": "def reset(all=False, vms=False, switches=False):\n    ret = False\n    cmd = ['vmctl', 'reset']\n    if all:\n        cmd.append('all')\n    elif vms:\n        cmd.append('vms')\n    elif switches:\n        cmd.append('switches')\n    result = __salt__['cmd.run_all'](cmd,\n                                     output_loglevel='trace',\n                                     python_shell=False)\n    if result['retcode'] == 0:\n        ret = True\n    else:\n        raise CommandExecutionError(\n            'Problem encountered running vmctl',\n            info={'errors': [result['stderr']], 'changes': ret}\n        )\n    return ret",
    "docstring": "Reset the running state of VMM or a subsystem.\n\n    all:\n        Reset the running state.\n\n    switches:\n        Reset the configured switches.\n\n    vms:\n        Reset and terminate all VMs.\n\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' vmctl.reset all=True"
  },
  {
    "code": "def _stream_docker_logs(self):\n        thread = threading.Thread(target=self._stderr_stream_worker)\n        thread.start()\n        for line in self.docker_client.logs(self.container, stdout=True,\n                                            stderr=False, stream=True):\n            sys.stdout.write(line)\n        thread.join()",
    "docstring": "Stream stdout and stderr from the task container to this\n        process's stdout and stderr, respectively."
  },
  {
    "code": "def exists(self):\n        path = self.path\n        if '*' in path or '?' in path or '[' in path or '{' in path:\n            logger.warning(\"Using wildcards in path %s might lead to processing of an incomplete dataset; \"\n                           \"override exists() to suppress the warning.\", path)\n        return self.fs.exists(path)",
    "docstring": "Returns ``True`` if the path for this FileSystemTarget exists; ``False`` otherwise.\n\n        This method is implemented by using :py:attr:`fs`."
  },
  {
    "code": "def run_query(db, query):\n    if db in [x.keys()[0] for x in show_dbs()]:\n        conn = _connect(show_dbs(db)[db]['uri'])\n    else:\n        log.debug('No uri found in pillars - will try to use oratab')\n        conn = _connect(uri=db)\n    return conn.cursor().execute(query).fetchall()",
    "docstring": "Run SQL query and return result\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' oracle.run_query my_db \"select * from my_table\""
  },
  {
    "code": "def strictly_positive_int_or_none(val):\n    val = positive_int_or_none(val)\n    if val is None or val > 0:\n        return val\n    raise ValueError('\"{}\" must be strictly positive'.format(val))",
    "docstring": "Parse `val` into either `None` or a strictly positive integer."
  },
  {
    "code": "def _get_top_file_envs():\n    try:\n        return __context__['saltutil._top_file_envs']\n    except KeyError:\n        try:\n            st_ = salt.state.HighState(__opts__,\n                                       initial_pillar=__pillar__)\n            top = st_.get_top()\n            if top:\n                envs = list(st_.top_matches(top).keys()) or 'base'\n            else:\n                envs = 'base'\n        except SaltRenderError as exc:\n            raise CommandExecutionError(\n                'Unable to render top file(s): {0}'.format(exc)\n            )\n        __context__['saltutil._top_file_envs'] = envs\n        return envs",
    "docstring": "Get all environments from the top file"
  },
  {
    "code": "def time_reached(self, current_time, scheduled_call):\n        if current_time >= scheduled_call['ts']:\n            scheduled_call['callback'](scheduled_call['args'])\n            return True\n        else:\n            return False",
    "docstring": "Checks to see if it's time to run a scheduled call or not.\n\n        If it IS time to run a scheduled call, this function will execute the\n        method associated with that call.\n\n        Args:\n          current_time (float): Current timestamp from time.time().\n          scheduled_call (dict): A scheduled call dictionary that contains the\n            timestamp to execute the call, the method to execute, and the\n            arguments used to call the method.\n\n        Returns:\n          None\n\n        Examples:\n\n        >>> scheduled_call\n        {'callback': <function foo at 0x7f022c42cf50>,\n                 'args': {'k': 'v'},\n                 'ts': 1415066599.769509}"
  },
  {
    "code": "def determine_band_channel(kal_out):\n    band = \"\"\n    channel = \"\"\n    tgt_freq = \"\"\n    while band == \"\":\n        for line in kal_out.splitlines():\n            if \"Using \" in line and \" channel \" in line:\n                band = str(line.split()[1])\n                channel = str(line.split()[3])\n                tgt_freq = str(line.split()[4]).replace(\n                    \"(\", \"\").replace(\")\", \"\")\n        if band == \"\":\n            band = None\n    return(band, channel, tgt_freq)",
    "docstring": "Return band, channel, target frequency from kal output."
  },
  {
    "code": "def __marshal_matches(matched):\n        json_matches = []\n        for m in matched:\n            identities = [i.uuid for i in m]\n            if len(identities) == 1:\n                continue\n            json_match = {\n                'identities': identities,\n                'processed': False\n            }\n            json_matches.append(json_match)\n        return json_matches",
    "docstring": "Convert matches to JSON format.\n\n        :param matched: a list of matched identities\n\n        :returns json_matches: a list of matches in JSON format"
  },
  {
    "code": "def _extract_delta(expr, idx):\n    from qnet.algebra.core.abstract_quantum_algebra import QuantumExpression\n    from qnet.algebra.core.scalar_algebra import ScalarValue\n    sympy_factor, quantum_factor = _split_sympy_quantum_factor(expr)\n    delta, new_expr = _sympy_extract_delta(sympy_factor, idx)\n    if delta is None:\n        new_expr = expr\n    else:\n        new_expr = new_expr * quantum_factor\n    if isinstance(new_expr, ScalarValue._val_types):\n        new_expr = ScalarValue.create(new_expr)\n    assert isinstance(new_expr, QuantumExpression)\n    return delta, new_expr",
    "docstring": "Extract a \"simple\" Kronecker delta containing `idx` from `expr`.\n\n    Assuming `expr` can be written as the product of a Kronecker Delta and a\n    `new_expr`, return a tuple of the sympy.KroneckerDelta instance and\n    `new_expr`. Otherwise, return a tuple of None and the original `expr`\n    (possibly converted to a :class:`.QuantumExpression`).\n\n    On input, `expr` can be a :class:`QuantumExpression` or a\n    :class:`sympy.Basic` object. On output, `new_expr` is guaranteed to be a\n    :class:`QuantumExpression`."
  },
  {
    "code": "def run_cleanup(build_ext_cmd):\n    if not build_ext_cmd.inplace:\n        return\n    bezier_dir = os.path.join(\"src\", \"bezier\")\n    shutil.move(os.path.join(build_ext_cmd.build_lib, LIB_DIR), bezier_dir)\n    shutil.move(os.path.join(build_ext_cmd.build_lib, DLL_DIR), bezier_dir)",
    "docstring": "Cleanup after ``BuildFortranThenExt.run``.\n\n    For in-place builds, moves the built shared library into the source\n    directory."
  },
  {
    "code": "def connect(self):\n        if not (self.consumer_key and self.consumer_secret and self.access_token\n                and self.access_token_secret):\n            raise RuntimeError(\"MissingKeys\")\n        if self.client:\n            log.info(\"closing existing http session\")\n            self.client.close()\n        if self.last_response:\n            log.info(\"closing last response\")\n            self.last_response.close()\n        log.info(\"creating http session\")\n        self.client = OAuth1Session(\n            client_key=self.consumer_key,\n            client_secret=self.consumer_secret,\n            resource_owner_key=self.access_token,\n            resource_owner_secret=self.access_token_secret\n        )",
    "docstring": "Sets up the HTTP session to talk to Twitter. If one is active it is\n        closed and another one is opened."
  },
  {
    "code": "def rm_gos(self, rm_goids):\n        self.edges = self._rm_gos_edges(rm_goids, self.edges)\n        self.edges_rel = self._rm_gos_edges_rel(rm_goids, self.edges_rel)",
    "docstring": "Remove any edges that contain user-specified edges."
  },
  {
    "code": "def replace(self, old, new):\n        if old.type != new.type:\n            raise TypeError(\"new instruction has a different type\")\n        pos = self.instructions.index(old)\n        self.instructions.remove(old)\n        self.instructions.insert(pos, new)\n        for bb in self.parent.basic_blocks:\n            for instr in bb.instructions:\n                instr.replace_usage(old, new)",
    "docstring": "Replace an instruction"
  },
  {
    "code": "def get(self, obj, id, sub_object=None):\n        self.url = '{}{}/{}'.format(self.base_url, obj, id)\n        self.method = 'GET'\n        if sub_object:\n            self.url += '/' + sub_object\n        self.resp = requests.get(url=self.url, auth=self.auth,\n                                 headers=self.headers, cert=self.ca_cert)\n        if self.__process_resp__(obj):\n            return self.res\n        return False",
    "docstring": "Function get\n        Get an object by id\n\n        @param obj: object name ('hosts', 'puppetclasses'...)\n        @param id: the id of the object (name or id)\n        @return RETURN: the targeted object"
  },
  {
    "code": "def concretize_write_addr(self, addr, strategies=None):\n        if isinstance(addr, int):\n            return [ addr ]\n        elif not self.state.solver.symbolic(addr):\n            return [ self.state.solver.eval(addr) ]\n        strategies = self.write_strategies if strategies is None else strategies\n        return self._apply_concretization_strategies(addr, strategies, 'store')",
    "docstring": "Concretizes an address meant for writing.\n\n            :param addr:            An expression for the address.\n            :param strategies:      A list of concretization strategies (to override the default).\n            :returns:               A list of concrete addresses."
  },
  {
    "code": "def run(self, cmd, fn=None, globals=None, locals=None):\n        if globals is None:\n            import __main__\n            globals = __main__.__dict__\n        if locals is None:\n            locals = globals\n        self.reset()\n        if isinstance(cmd, str):\n            str_cmd = cmd\n            cmd = compile(str_cmd, fn or \"<wdb>\", \"exec\")\n            self.compile_cache[id(cmd)] = str_cmd\n        if fn:\n            from linecache import getline\n            lno = 1\n            while True:\n                line = getline(fn, lno, globals)\n                if line is None:\n                    lno = None\n                    break\n                if executable_line(line):\n                    break\n                lno += 1\n        self.start_trace()\n        if lno is not None:\n            self.breakpoints.add(LineBreakpoint(fn, lno, temporary=True))\n        try:\n            execute(cmd, globals, locals)\n        finally:\n            self.stop_trace()",
    "docstring": "Run the cmd `cmd` with trace"
  },
  {
    "code": "def add(self, filetype, **kwargs):\n        location = self.location(filetype, **kwargs)\n        source = self.url(filetype, sasdir='sas' if not self.public else '', **kwargs)\n        if 'full' not in kwargs:\n            destination = self.full(filetype, **kwargs)\n        else:\n            destination = kwargs.get('full')\n        if location and source and destination:\n            self.initial_stream.append_task(location=location, source=source, destination=destination)\n        else:\n            print(\"There is no file with filetype=%r to access in the tree module loaded\" % filetype)",
    "docstring": "Adds a filepath into the list of tasks to download"
  },
  {
    "code": "def confusion_matrix(expected: np.ndarray, predicted: np.ndarray, num_classes: int) -> np.ndarray:\n    assert np.issubclass_(expected.dtype.type, np.integer), \" Classes' indices must be integers\"\n    assert np.issubclass_(predicted.dtype.type, np.integer), \" Classes' indices must be integers\"\n    assert expected.shape == predicted.shape, \"Predicted and expected data must be the same length\"\n    assert num_classes > np.max([predicted, expected]), \\\n        \"Number of classes must be at least the number of indices in predicted/expected data\"\n    assert np.min([predicted, expected]) >= 0, \" Classes' indices must be positive integers\"\n    cm_abs = np.zeros((num_classes, num_classes), dtype=np.int32)\n    for pred, exp in zip(predicted, expected):\n        cm_abs[exp, pred] += 1\n    return cm_abs",
    "docstring": "Calculate and return confusion matrix for the predicted and expected labels\n\n    :param expected: array of expected classes (integers) with shape `[num_of_data]`\n    :param predicted: array of predicted classes (integers) with shape `[num_of_data]`\n    :param num_classes: number of classification classes\n    :return: confusion matrix (cm) with absolute values"
  },
  {
    "code": "def principal_inertia_transform(self):\n        order = np.argsort(self.principal_inertia_components)[1:][::-1]\n        vectors = self.principal_inertia_vectors[order]\n        vectors = np.vstack((vectors, np.cross(*vectors)))\n        transform = np.eye(4)\n        transform[:3, :3] = vectors\n        transform = transformations.transform_around(\n            matrix=transform,\n            point=self.centroid)\n        transform[:3, 3] -= self.centroid\n        return transform",
    "docstring": "A transform which moves the current mesh so the principal\n        inertia vectors are on the X,Y, and Z axis, and the centroid is\n        at the origin.\n\n        Returns\n        ----------\n        transform : (4, 4) float\n          Homogenous transformation matrix"
  },
  {
    "code": "def delete_field_value(self, name):\n        name = self.get_real_name(name)\n        if name and self._can_write_field(name):\n            if name in self.__modified_data__:\n                self.__modified_data__.pop(name)\n            if name in self.__original_data__ and name not in self.__deleted_fields__:\n                self.__deleted_fields__.append(name)",
    "docstring": "Mark this field to be deleted"
  },
  {
    "code": "def delete(self, identity_id, service):\n        return self.request.delete(str(identity_id) + '/limit/' + service)",
    "docstring": "Delete the limit for the given identity and service\n\n            :param identity_id: The ID of the identity to retrieve\n            :param service: The service that the token is linked to\n            :return: dict of REST API output with headers attached\n            :rtype: :class:`~datasift.request.DictResponse`\n            :raises: :class:`~datasift.exceptions.DataSiftApiException`,\n                :class:`requests.exceptions.HTTPError`"
  },
  {
    "code": "def _convert_name(self, name):\n        if re.search('^\\d+$', name):\n            if len(name) > 1 and name[0] == '0':\n                return name\n            return int(name)\n        return name",
    "docstring": "Convert ``name`` to int if it looks like an int.\n\n        Otherwise, return it as is."
  },
  {
    "code": "def update_view_state(self, view, state):\n        if view.name not in self:\n            self[view.name] = Bunch()\n        self[view.name].update(state)",
    "docstring": "Update the state of a view."
  },
  {
    "code": "def resample_dset(dset,template,prefix=None,resam='NN'):\n    if prefix==None:\n        prefix = nl.suffix(dset,'_resam')\n    nl.run(['3dresample','-master',template,'-rmode',resam,'-prefix',prefix,'-inset',dset])",
    "docstring": "Resamples ``dset`` to the grid of ``template`` using resampling mode ``resam``.\n    Default prefix is to suffix ``_resam`` at the end of ``dset``\n\n    Available resampling modes:\n        :NN:    Nearest Neighbor\n        :Li:    Linear\n        :Cu:    Cubic\n        :Bk:    Blocky"
  },
  {
    "code": "def _get_ui_content(self, cli, width, height):\n        def get_content():\n            return self.content.create_content(cli, width=width, height=height)\n        key = (cli.render_counter, width, height)\n        return self._ui_content_cache.get(key, get_content)",
    "docstring": "Create a `UIContent` instance."
  },
  {
    "code": "def nb_to_python(nb_path):\n    exporter = python.PythonExporter()\n    output, resources = exporter.from_filename(nb_path)\n    return output",
    "docstring": "convert notebook to python script"
  },
  {
    "code": "def check_recommended_files(data, vcs):\n    main_files = os.listdir(data['workingdir'])\n    if not 'setup.py' in main_files and not 'setup.cfg' in main_files:\n        return True\n    if not 'MANIFEST.in' in main_files and not 'MANIFEST' in main_files:\n        q = (\"This package is missing a MANIFEST.in file. This file is \"\n             \"recommended. \"\n             \"See http://docs.python.org/distutils/sourcedist.html\"\n             \" for more info. Sample contents:\"\n             \"\\n\"\n             \"recursive-include main_directory *\"\n             \"recursive-include docs *\"\n             \"include *\"\n             \"global-exclude *.pyc\"\n             \"\\n\"\n             \"You may want to quit and fix this.\")\n        if not vcs.is_setuptools_helper_package_installed():\n            q += \"Installing %s may help too.\\n\" % \\\n                vcs.setuptools_helper_package\n        q += \"Do you want to continue with the release?\"\n        if not ask(q, default=False):\n            return False\n        print(q)\n    return True",
    "docstring": "Do check for recommended files.\n\n    Returns True when all is fine."
  },
  {
    "code": "def type(self, name: str):\n        for f in self.body:\n            if (hasattr(f, '_ctype')\n                    and f._ctype._storage == Storages.TYPEDEF\n                    and f._name == name):\n                return f",
    "docstring": "return the first complete definition of type 'name"
  },
  {
    "code": "def nCr(n, r):\n    f = math.factorial\n    return int(f(n) / f(r) / f(n-r))",
    "docstring": "Calculates nCr.\n\n    Args:\n        n (int): total number of items.\n        r (int): items to choose\n\n    Returns:\n        nCr."
  },
  {
    "code": "def __log_overview_errors(self):\n        if self.error_file_names:\n            self._io.warning('Routines in the files below are not loaded:')\n            self._io.listing(sorted(self.error_file_names))",
    "docstring": "Show info about sources files of stored routines that were not loaded successfully."
  },
  {
    "code": "def discard(samples, chains):\n    samples = np.asarray(samples)\n    if samples.ndim != 2:\n        raise ValueError(\"expected samples to be a numpy 2D array\")\n    num_samples, num_variables = samples.shape\n    num_chains = len(chains)\n    broken = broken_chains(samples, chains)\n    unbroken_idxs, = np.where(~broken.any(axis=1))\n    chain_variables = np.fromiter((np.asarray(tuple(chain))[0] if isinstance(chain, set) else np.asarray(chain)[0]\n                                   for chain in chains),\n                                  count=num_chains, dtype=int)\n    return samples[np.ix_(unbroken_idxs, chain_variables)], unbroken_idxs",
    "docstring": "Discard broken chains.\n\n    Args:\n        samples (array_like):\n            Samples as a nS x nV array_like object where nS is the number of samples and nV is the\n            number of variables. The values should all be 0/1 or -1/+1.\n\n        chains (list[array_like]):\n            List of chains of length nC where nC is the number of chains.\n            Each chain should be an array_like collection of column indices in samples.\n\n    Returns:\n        tuple: A 2-tuple containing:\n\n            :obj:`numpy.ndarray`: An array of unembedded samples. Broken chains are discarded. The\n            array has dtype 'int8'.\n\n            :obj:`numpy.ndarray`: The indicies of the rows with unbroken chains.\n\n    Examples:\n        This example unembeds two samples that chains nodes 0 and 1 to represent a single source\n        node. The first sample has an unbroken chain, the second a broken chain.\n\n        >>> import dimod\n        >>> import numpy as np\n        ...\n        >>> chains = [(0, 1), (2,)]\n        >>> samples = np.array([[1, 1, 0], [1, 0, 0]], dtype=np.int8)\n        >>> unembedded, idx = dwave.embedding.discard(samples, chains)\n        >>> unembedded\n        array([[1, 0]], dtype=int8)\n        >>> idx\n        array([0])"
  },
  {
    "code": "def search(self, start_ts, end_ts):\n        return self._stream_search(\n            index=self.meta_index_name,\n            body={\"query\": {\"range\": {\"_ts\": {\"gte\": start_ts, \"lte\": end_ts}}}},\n        )",
    "docstring": "Query Elasticsearch for documents in a time range.\n\n        This method is used to find documents that may be in conflict during\n        a rollback event in MongoDB."
  },
  {
    "code": "def list_records_for_build_configuration(id=None, name=None, page_size=200, page_index=0, sort=\"\", q=\"\"):\n    data = list_records_for_build_configuration_raw(id, name, page_size, page_index, sort, q)\n    if data:\n        return utils.format_json_list(data)",
    "docstring": "List all BuildRecords for a given BuildConfiguration"
  },
  {
    "code": "def get_default_config(self, jid, node=None):\n        iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET)\n        iq.payload = pubsub_xso.Request(\n            pubsub_xso.Default(node=node)\n        )\n        response = yield from self.client.send(iq)\n        return response.payload.data",
    "docstring": "Request the default configuration of a node.\n\n        :param jid: Address of the PubSub service.\n        :type jid: :class:`aioxmpp.JID`\n        :param node: Name of the PubSub node to query.\n        :type node: :class:`str`\n        :raises aioxmpp.errors.XMPPError: as returned by the service\n        :return: The default configuration of subscriptions at the node.\n        :rtype: :class:`~.forms.Data`\n\n        On success, the :class:`~.forms.Data` form is returned.\n\n        If an error occurs, the corresponding :class:`~.errors.XMPPError` is\n        raised."
  },
  {
    "code": "def i18n_javascript(self, request):\n        if settings.USE_I18N:\n            from django.views.i18n import javascript_catalog\n        else:\n            from django.views.i18n import null_javascript_catalog as javascript_catalog\n        return javascript_catalog(request, packages=['media_tree'])",
    "docstring": "Displays the i18n JavaScript that the Django admin requires.\n\n        This takes into account the USE_I18N setting. If it's set to False, the\n        generated JavaScript will be leaner and faster."
  },
  {
    "code": "def worker_failed():\n    participant_id = request.args.get(\"participant_id\")\n    if not participant_id:\n        return error_response(\n            error_type=\"bad request\", error_text=\"participantId parameter is required\"\n        )\n    try:\n        _worker_failed(participant_id)\n    except KeyError:\n        return error_response(\n            error_type=\"ParticipantId not found: {}\".format(participant_id)\n        )\n    return success_response(\n        field=\"status\", data=\"success\", request_type=\"worker failed\"\n    )",
    "docstring": "Fail worker. Used by bots only for now."
  },
  {
    "code": "def collect_hosts(api, wanted_hostnames):\n  all_hosts = api.get_all_hosts(view='full')\n  all_hostnames = set([ h.hostname for h in all_hosts])\n  wanted_hostnames = set(wanted_hostnames)\n  unknown_hosts = wanted_hostnames.difference(all_hostnames)\n  if len(unknown_hosts) != 0:\n    msg = \"The following hosts are not found in Cloudera Manager. \"\\\n          \"Please check for typos:\\n%s\" % ('\\n'.join(unknown_hosts))\n    LOG.error(msg)\n    raise RuntimeError(msg)\n  return [ h for h in all_hosts if h.hostname in wanted_hostnames ]",
    "docstring": "Return a list of ApiHost objects for the set of hosts that\n  we want to change config for."
  },
  {
    "code": "def AskYesNoCancel(message, title='FontParts', default=0, informativeText=\"\"):\n    return dispatcher[\"AskYesNoCancel\"](message=message, title=title,\n                                        default=default, informativeText=informativeText)",
    "docstring": "An ask yes, no or cancel dialog, a `message` is required.\n    Optionally a `title`, `default` and `informativeText` can be provided.\n    The `default` option is to indicate which button is the default button.\n\n    ::\n\n        from fontParts.ui import AskYesNoCancel\n        print(AskYesNoCancel(\"who are you?\"))"
  },
  {
    "code": "def create_program_action(parent, text, name, icon=None, nt_name=None):\r\n    if is_text_string(icon):\r\n        icon = get_icon(icon)\r\n    if os.name == 'nt' and nt_name is not None:\r\n        name = nt_name\r\n    path = programs.find_program(name)\r\n    if path is not None:\r\n        return create_action(parent, text, icon=icon,\r\n                             triggered=lambda: programs.run_program(name))",
    "docstring": "Create action to run a program"
  },
  {
    "code": "def _populate_setup(self):\n        makedirs(os.path.dirname(self._cache_marker))\n        with codecs.open(self._cache_marker, 'w', encoding='utf-8') as fobj:\n            fobj.write(self.cache_uri)\n        self.graph.open(self.cache_uri)",
    "docstring": "Just create a local marker file since the actual database should\n        already be created on the Fuseki server."
  },
  {
    "code": "def rename(self, new_name):\r\n        old_name = self.name\r\n        self.name = new_name\r\n        pypath = self.relative_pythonpath\n        self.root_path = self.root_path[:-len(old_name)]+new_name\r\n        self.relative_pythonpath = pypath\n        self.save()",
    "docstring": "Rename project and rename its root path accordingly."
  },
  {
    "code": "def calculate_sleep_time(attempt, delay_factor=5.0, randomization_factor=.5, max_delay=120):\n    if attempt <= 0:\n        return 0\n    delay = float(2 ** (attempt - 1)) * float(delay_factor)\n    delay = delay * (randomization_factor * random.random() + 1)\n    return min(delay, max_delay)",
    "docstring": "Calculate the sleep time between retries, in seconds.\n\n    Based off of `taskcluster.utils.calculateSleepTime`, but with kwargs instead\n    of constant `delay_factor`/`randomization_factor`/`max_delay`.  The taskcluster\n    function generally slept for less than a second, which didn't always get\n    past server issues.\n\n    Args:\n        attempt (int): the retry attempt number\n        delay_factor (float, optional): a multiplier for the delay time.  Defaults to 5.\n        randomization_factor (float, optional): a randomization multiplier for the\n            delay time.  Defaults to .5.\n        max_delay (float, optional): the max delay to sleep.  Defaults to 120 (seconds).\n\n    Returns:\n        float: the time to sleep, in seconds."
  },
  {
    "code": "def TSKVolumeGetBytesPerSector(tsk_volume):\n  if hasattr(tsk_volume, 'info') and tsk_volume.info is not None:\n    block_size = getattr(tsk_volume.info, 'block_size', 512)\n  else:\n    block_size = 512\n  return block_size",
    "docstring": "Retrieves the number of bytes per sector from a TSK volume object.\n\n  Args:\n    tsk_volume (pytsk3.Volume_Info): TSK volume information.\n\n  Returns:\n    int: number of bytes per sector or 512 by default."
  },
  {
    "code": "def access_key(self):\n        credential = self.query_parameters.get(_x_amz_credential)\n        if credential is not None:\n            credential = url_unquote(credential[0])\n        else:\n            credential = self.authorization_header_parameters.get(_credential)\n            if credential is None:\n                raise AttributeError(\"Credential was not passed in the request\")\n        try:\n            key, scope = credential.split(\"/\", 1)\n        except ValueError:\n            raise AttributeError(\"Invalid request credential: %r\" % credential)\n        if scope != self.credential_scope:\n            raise AttributeError(\"Incorrect credential scope: %r (wanted %r)\" %\n                                 (scope, self.credential_scope))\n        return key",
    "docstring": "The access key id used to sign the request.\n\n        If the access key is not in the same credential scope as this request,\n        an AttributeError exception is raised."
  },
  {
    "code": "def _latex_item_to_string(item, *, escape=False, as_content=False):\n    if isinstance(item, pylatex.base_classes.LatexObject):\n        if as_content:\n            return item.dumps_as_content()\n        else:\n            return item.dumps()\n    elif not isinstance(item, str):\n        item = str(item)\n    if escape:\n        item = escape_latex(item)\n    return item",
    "docstring": "Use the render method when possible, otherwise uses str.\n\n    Args\n    ----\n    item: object\n        An object that needs to be converted to a string\n    escape: bool\n        Flag that indicates if escaping is needed\n    as_content: bool\n        Indicates whether the item should be dumped using\n        `~.LatexObject.dumps_as_content`\n\n    Returns\n    -------\n    NoEscape\n        Latex"
  },
  {
    "code": "def check_limit(self, limit):\n        if limit > 0:\n            self.limit = limit\n        else:\n            raise ValueError(\"Rule limit must be strictly > 0 ({0} given)\"\n                             .format(limit))\n        return self",
    "docstring": "Checks if the given limit is valid.\n\n        A limit must be > 0 to be considered valid.\n\n        Raises ValueError when the *limit* is not > 0."
  },
  {
    "code": "def copy_file_if_modified(src_path, dest_path):\n    if os.path.isdir(dest_path):\n        shutil.rmtree(dest_path)\n    must_copy = False\n    if not os.path.exists(dest_path):\n        must_copy = True\n    else:\n        src_stat = os.stat(src_path)\n        dest_stat = os.stat(dest_path)\n        if ((src_stat[stat.ST_SIZE] != dest_stat[stat.ST_SIZE]) or\n                (src_stat[stat.ST_MTIME] != dest_stat[stat.ST_MTIME])):\n            must_copy = True\n    if must_copy:\n        shutil.copy2(src_path, dest_path)",
    "docstring": "Only copies the file from the source path to the destination path if it doesn't exist yet or it has\n    been modified. Intended to provide something of an optimisation when a project has large trees of assets."
  },
  {
    "code": "def _extract(archive, compression, cmd, format, verbosity, outdir):\n    targetname = util.get_single_outfile(outdir, archive)\n    try:\n        with lzma.LZMAFile(archive, **_get_lzma_options(format)) as lzmafile:\n            with open(targetname, 'wb') as targetfile:\n                data = lzmafile.read(READ_SIZE_BYTES)\n                while data:\n                    targetfile.write(data)\n                    data = lzmafile.read(READ_SIZE_BYTES)\n    except Exception as err:\n        msg = \"error extracting %s to %s: %s\" % (archive, targetname, err)\n        raise util.PatoolError(msg)\n    return None",
    "docstring": "Extract an LZMA or XZ archive with the lzma Python module."
  },
  {
    "code": "def _verify_file_size(self):\n        if self._file_size > PartSize.MAXIMUM_OBJECT_SIZE:\n            self._status = TransferState.FAILED\n            raise SbgError('File size = {}b. Maximum file size is {}b'.format(\n                self._file_size, PartSize.MAXIMUM_OBJECT_SIZE)\n            )",
    "docstring": "Verifies that the file is smaller then 5TB which is the maximum\n        that is allowed for upload."
  },
  {
    "code": "def _handle_request_exception(self, e):\n        handle_func = self._exception_default_handler\n        if self.EXCEPTION_HANDLERS:\n            for excs, func_name in self.EXCEPTION_HANDLERS.items():\n                if isinstance(e, excs):\n                    handle_func = getattr(self, func_name)\n                    break\n        handle_func(e)\n        if not self._finished:\n            self.finish()",
    "docstring": "This method handle HTTPError exceptions the same as how tornado does,\n        leave other exceptions to be handled by user defined handler function\n        maped in class attribute `EXCEPTION_HANDLERS`\n\n        Common HTTP status codes:\n            200 OK\n            301 Moved Permanently\n            302 Found\n            400 Bad Request\n            401 Unauthorized\n            403 Forbidden\n            404 Not Found\n            405 Method Not Allowed\n            500 Internal Server Error\n\n        It is suggested only to use above HTTP status codes"
  },
  {
    "code": "def from_json(json):\n        return Point(\n            lat=json['lat'],\n            lon=json['lon'],\n            time=isostr_to_datetime(json['time'])\n        )",
    "docstring": "Creates Point instance from JSON representation\n\n        Args:\n            json (:obj:`dict`): Must have at least the following keys: lat (float), lon (float),\n                time (string in iso format). Example,\n                {\n                    \"lat\": 9.3470298,\n                    \"lon\": 3.79274,\n                    \"time\": \"2016-07-15T15:27:53.574110\"\n                }\n            json: map representation of Point instance\n        Returns:\n            :obj:`Point`"
  },
  {
    "code": "def main():\n    arg_parse = setup_argparse()\n    args = arg_parse.parse_args()\n    if not args.quiet:\n        print('GNS3 Topology Converter')\n    if args.debug:\n        logging_level = logging.DEBUG\n    else:\n        logging_level = logging.WARNING\n    logging.basicConfig(level=logging_level,\n                        format=LOG_MSG_FMT, datefmt=LOG_DATE_FMT)\n    logging.getLogger(__name__)\n    if args.topology == 'topology.net':\n        args.topology = os.path.join(os.getcwd(), 'topology.net')\n    topology_files = [{'file': topology_abspath(args.topology),\n                       'snapshot': False}]\n    topology_files.extend(get_snapshots(args.topology))\n    topology_name = name(args.topology, args.name)\n    for topology in topology_files:\n        do_conversion(topology, topology_name, args.output, args.debug)",
    "docstring": "Entry point for gns3-converter"
  },
  {
    "code": "def render_template(self, template_name, out_path=None):\n        return render_template(template_name, self.to_dict(), out_path=out_path)",
    "docstring": "Render a template based on this TileBus Block.\n\n        The template has access to all of the attributes of this block as a\n        dictionary (the result of calling self.to_dict()).\n\n        You can optionally render to a file by passing out_path.\n\n        Args:\n            template_name (str): The name of the template to load.  This must\n                be a file in config/templates inside this package\n            out_path (str): An optional path of where to save the output\n                file, otherwise it is just returned as a string.\n\n        Returns:\n            string: The rendered template data."
  },
  {
    "code": "def _load_vector_fit(self, fit_key, h5file):\n        vector_fit = []\n        for i in range(len(h5file[fit_key].keys())):\n            fit_data = self._read_dict(h5file[fit_key]['comp_%d'%i])\n            vector_fit.append(self._load_scalar_fit(fit_data=fit_data))\n        return vector_fit",
    "docstring": "Loads a vector of fits"
  },
  {
    "code": "def PARAMLIMITS(self, value):\n        assert set(value.keys()) == set(self.PARAMLIMITS.keys()), \"The \\\n                new parameter limits are not defined for the same set \\\n                of parameters as before.\"\n        for param in value.keys():\n            assert value[param][0] < value[param][1], \"The new \\\n                    minimum value for {0}, {1}, is equal to or \\\n                    larger than the new maximum value, {2}\"\\\n                    .format(param, value[param][0], value[param][1])\n        self._PARAMLIMITS = value.copy()",
    "docstring": "Set new `PARAMLIMITS` dictionary."
  },
  {
    "code": "def generate_configfile(cfg_file,defaults=defaults):\n    _mkdir_for_config(cfg_file=cfg_file)\n    with open(cfg_file, 'w') as f:\n        f.write('')\n    for section in defaults.keys():\n        set_option(section, cfg_file=cfg_file, **defaults[section])",
    "docstring": "Write a new nago.ini config file from the defaults.\n\n    Arguments:\n        cfg_file  -- File that is written to like /etc/nago/nago.ini\n        defaults  -- Dictionary with default values to use"
  },
  {
    "code": "def validate(self, dist):\n        for item in self.remove:\n            if not dist.has_contents_for(item):\n                raise DistutilsSetupError(\n                    \"%s wants to be able to remove %s, but the distribution\"\n                    \" doesn't contain any packages or modules under %s\"\n                    % (self.description, item, item)\n                )",
    "docstring": "Verify that feature makes sense in context of distribution\n\n        This method is called by the distribution just before it parses its\n        command line.  It checks to ensure that the 'remove' attribute, if any,\n        contains only valid package/module names that are present in the base\n        distribution when 'setup()' is called.  You may override it in a\n        subclass to perform any other required validation of the feature\n        against a target distribution."
  },
  {
    "code": "def generate_menu(self, ass, text, path=None, level=0):\n        menu = self.create_menu()\n        for index, sub in enumerate(sorted(ass[1], key=lambda y: y[0].fullname.lower())):\n            if index != 0:\n                text += \"|\"\n            text += \"- \" + sub[0].fullname\n            new_path = list(path)\n            if level == 0:\n                new_path.append(ass[0].name)\n            new_path.append(sub[0].name)\n            menu_item = self.menu_item(sub, new_path)\n            if sub[1]:\n                (sub_menu, txt) = self.generate_menu(sub, text, new_path, level=level + 1)\n                menu_item.set_submenu(sub_menu)\n            menu.append(menu_item)\n        return menu, text",
    "docstring": "Function generates menu from based on ass parameter"
  },
  {
    "code": "async def listHooks(self, *args, **kwargs):\n        return await self._makeApiCall(self.funcinfo[\"listHooks\"], *args, **kwargs)",
    "docstring": "List hooks in a given group\n\n        This endpoint will return a list of all the hook definitions within a\n        given hook group.\n\n        This method gives output: ``v1/list-hooks-response.json#``\n\n        This method is ``stable``"
  },
  {
    "code": "def update_headers(self, headers: Optional[LooseHeaders]) -> None:\n        self.headers = CIMultiDict()\n        netloc = cast(str, self.url.raw_host)\n        if helpers.is_ipv6_address(netloc):\n            netloc = '[{}]'.format(netloc)\n        if not self.url.is_default_port():\n            netloc += ':' + str(self.url.port)\n        self.headers[hdrs.HOST] = netloc\n        if headers:\n            if isinstance(headers, (dict, MultiDictProxy, MultiDict)):\n                headers = headers.items()\n            for key, value in headers:\n                if key.lower() == 'host':\n                    self.headers[key] = value\n                else:\n                    self.headers.add(key, value)",
    "docstring": "Update request headers."
  },
  {
    "code": "def nic_b(msg):\n    tc = typecode(msg)\n    if tc < 9 or tc > 18:\n        raise RuntimeError(\"%s: Not a airborne position message, expecting 8<TC<19\" % msg)\n    msgbin = common.hex2bin(msg)\n    nic_b = int(msgbin[39])\n    return nic_b",
    "docstring": "Obtain NICb, navigation integrity category supplement-b\n\n    Args:\n        msg (string): 28 bytes hexadecimal message string\n\n    Returns:\n        int: NICb number (0 or 1)"
  },
  {
    "code": "def from_json_str(cls, json_str):\n    return cls.from_json(json.loads(json_str, cls=JsonDecoder))",
    "docstring": "Convert json string representation into class instance.\n\n    Args:\n      json_str: json representation as string.\n\n    Returns:\n      New instance of the class with data loaded from json string."
  },
  {
    "code": "def symbol_top(body_output, targets, model_hparams, vocab_size):\n  del targets\n  if model_hparams.shared_embedding_and_softmax_weights:\n    scope_name = \"shared\"\n    reuse = tf.AUTO_REUSE\n  else:\n    scope_name = \"softmax\"\n    reuse = False\n  with tf.variable_scope(scope_name, reuse=reuse):\n    body_output_shape = common_layers.shape_list(body_output)\n    var = get_weights(model_hparams, vocab_size, body_output_shape[-1])\n    if (model_hparams.factored_logits and\n        model_hparams.mode == tf.estimator.ModeKeys.TRAIN):\n      body_output = tf.expand_dims(body_output, 3)\n      return common_layers.FactoredTensor(body_output, var)\n    else:\n      body_output = tf.reshape(body_output, [-1, body_output_shape[-1]])\n      logits = tf.matmul(body_output, var, transpose_b=True)\n      return tf.reshape(logits,\n                        body_output_shape[:-1] + [1, vocab_size])",
    "docstring": "Generate logits.\n\n  Args:\n    body_output: A Tensor with shape\n      [batch, p0, p1, model_hparams.hidden_size].\n    targets: Unused.\n    model_hparams: HParams, model hyperparmeters.\n    vocab_size: int, vocabulary size.\n\n  Returns:\n    logits: A Tensor with shape  [batch, p0, p1, ?, vocab_size]."
  },
  {
    "code": "def build_projection_kwargs(cls, source, mapping):\n        return cls._map_arg_names(source, cls._default_attr_mapping + mapping)",
    "docstring": "Handle mapping a dictionary of metadata to keyword arguments."
  },
  {
    "code": "def scale_up_dynos(id):\n    config = PsiturkConfig()\n    config.load_config()\n    dyno_type = config.get('Server Parameters', 'dyno_type')\n    num_dynos_web = config.get('Server Parameters', 'num_dynos_web')\n    num_dynos_worker = config.get('Server Parameters', 'num_dynos_worker')\n    log(\"Scaling up the dynos...\")\n    subprocess.call(\n        \"heroku ps:scale web=\" + str(num_dynos_web) + \":\" +\n        str(dyno_type) + \" --app \" + id, shell=True)\n    subprocess.call(\n        \"heroku ps:scale worker=\" + str(num_dynos_worker) + \":\" +\n        str(dyno_type) + \" --app \" + id, shell=True)\n    clock_on = config.getboolean('Server Parameters', 'clock_on')\n    if clock_on:\n        subprocess.call(\n            \"heroku ps:scale clock=1:\" + dyno_type + \" --app \" + id,\n            shell=True)",
    "docstring": "Scale up the Heroku dynos."
  },
  {
    "code": "def parse_domains(self, domain, params):\n        domain_id = self.get_non_aws_id(domain['DomainName'])\n        domain['name'] = domain.pop('DomainName')\n        self.domains[domain_id] = domain",
    "docstring": "Parse a single Route53Domains domain"
  },
  {
    "code": "def album(self, album_id, *, include_description=True, include_songs=True):\n\t\tresponse = self._call(\n\t\t\tmc_calls.FetchAlbum,\n\t\t\talbum_id,\n\t\t\tinclude_description=include_description,\n\t\t\tinclude_tracks=include_songs\n\t\t)\n\t\talbum_info = response.body\n\t\treturn album_info",
    "docstring": "Get information about an album.\n\n\t\tParameters:\n\t\t\talbum_id (str): An album ID. Album IDs start with a 'B'.\n\t\t\tinclude_description (bool, Optional): Include description of the album in the returned dict.\n\t\t\tinclude_songs (bool, Optional): Include songs from the album in the returned dict.\n\t\t\t\tDefault: ``True``.\n\n\t\tReturns:\n\t\t\tdict: Album information."
  },
  {
    "code": "def on_create_view(self):\n        d = self.declaration\n        changed = not d.condition\n        if changed:\n            d.condition = True\n        view = self.get_view()\n        if changed:\n            self.ready.set_result(True)\n        return view",
    "docstring": "Trigger the click"
  },
  {
    "code": "def brute_permutation(A, B):\n    rmsd_min = np.inf\n    view_min = None\n    num_atoms = A.shape[0]\n    initial_order = list(range(num_atoms))\n    for reorder_indices in generate_permutations(initial_order, num_atoms):\n        coords_ordered = B[reorder_indices]\n        rmsd_temp = kabsch_rmsd(A, coords_ordered)\n        if rmsd_temp < rmsd_min:\n            rmsd_min = rmsd_temp\n            view_min = copy.deepcopy(reorder_indices)\n    return view_min",
    "docstring": "Re-orders the input atom list and xyz coordinates using the brute force\n    method of permuting all rows of the input coordinates\n\n    Parameters\n    ----------\n    A : array\n        (N,D) matrix, where N is points and D is dimension\n    B : array\n        (N,D) matrix, where N is points and D is dimension\n\n    Returns\n    -------\n    view : array\n        (N,1) matrix, reordered view of B projected to A"
  },
  {
    "code": "def markdown_2_rst(lines):\n    out = []\n    code = False\n    for line in lines:\n        if line.strip() == \"```\":\n            code = not code\n            space = \" \" * (len(line.rstrip()) - 3)\n            if code:\n                out.append(\"\\n\\n%s.. code-block:: none\\n\\n\" % space)\n            else:\n                out.append(\"\\n\")\n        else:\n            if code and line.strip():\n                line = \"    \" + line\n            else:\n                line = line.replace(\"\\\\\", \"\\\\\\\\\")\n            out.append(line)\n    return out",
    "docstring": "Convert markdown to restructured text"
  },
  {
    "code": "def chunk_upload_file(self, name, folder_id, file_path,\n                            progress_callback=None,\n                            chunk_size=1024*1024*1):\n        try:\n            return self.__do_chunk_upload_file(name, folder_id, file_path,\n                                    progress_callback,\n                                    chunk_size)\n        except BoxError, ex:\n            if ex.status != 401:\n                raise\n            return self.__do_chunk_upload_file(name, folder_id, file_path,\n                                    progress_callback,\n                                    chunk_size)",
    "docstring": "Upload a file chunk by chunk.\n\n        The whole file is never loaded in memory.\n        Use this function for big file.\n\n        The callback(transferred, total) to let you know the upload progress.\n        Upload can be cancelled if the callback raise an Exception.\n\n        >>> def progress_callback(transferred, total):\n        ...    print 'Uploaded %i bytes of %i' % (transferred, total, )\n        ...    if user_request_cancel:\n        ...       raise MyCustomCancelException()\n\n        Args:\n            name (str): Name of the file on your Box storage.\n\n            folder_id (int): ID of the folder where to upload the file.\n\n            file_path (str): Local path of the file to upload.\n\n            progress_callback (func): Function called each time a chunk is uploaded.\n\n            chunk_size (int): Size of chunks.\n\n        Returns:\n            dict. Response from Box.\n\n        Raises:\n            BoxError: An error response is returned from Box (status_code >= 400).\n\n            BoxHttpResponseError: Response from Box is malformed.\n\n            requests.exceptions.*: Any connection related problem."
  },
  {
    "code": "def remove_first_word(ctx, text):\n    text = conversions.to_string(text, ctx).lstrip()\n    first = first_word(ctx, text)\n    return text[len(first):].lstrip() if first else ''",
    "docstring": "Removes the first word from the given text string"
  },
  {
    "code": "def from_totient(public_key, totient):\n        p_plus_q = public_key.n - totient + 1\n        p_minus_q = isqrt(p_plus_q * p_plus_q - public_key.n * 4)\n        q = (p_plus_q - p_minus_q) // 2\n        p = p_plus_q - q\n        if not p*q == public_key.n:\n            raise ValueError('given public key and totient do not match.')\n        return PaillierPrivateKey(public_key, p, q)",
    "docstring": "given the totient, one can factorize the modulus\n\n        The totient is defined as totient = (p - 1) * (q - 1),\n        and the modulus is defined as modulus = p * q\n\n        Args:\n          public_key (PaillierPublicKey): The corresponding public\n            key\n          totient (int): the totient of the modulus\n\n        Returns:\n          the :class:`PaillierPrivateKey` that corresponds to the inputs\n\n        Raises:\n          ValueError: if the given totient is not the totient of the modulus\n            of the given public key"
  },
  {
    "code": "def triple_fraction(self,query='mass_A > 0', unc=False):\n        subdf = self.stars.query(query)\n        ntriples = ((subdf['mass_B'] > 0) & (subdf['mass_C'] > 0)).sum()\n        frac = ntriples/len(subdf)\n        if unc:\n            return frac, frac/np.sqrt(ntriples)\n        else:\n            return frac",
    "docstring": "Triple fraction of stars following given query"
  },
  {
    "code": "def from_string(rxn_string):\n        rct_str, prod_str = rxn_string.split(\"->\")\n        def get_comp_amt(comp_str):\n            return {Composition(m.group(2)): float(m.group(1) or 1)\n                    for m in re.finditer(r\"([\\d\\.]*(?:[eE]-?[\\d\\.]+)?)\\s*([A-Z][\\w\\.\\(\\)]*)\",\n                                         comp_str)}\n        return BalancedReaction(get_comp_amt(rct_str), get_comp_amt(prod_str))",
    "docstring": "Generates a balanced reaction from a string. The reaction must\n        already be balanced.\n\n        Args:\n            rxn_string:\n                The reaction string. For example, \"4 Li + O2-> 2Li2O\"\n\n        Returns:\n            BalancedReaction"
  },
  {
    "code": "def _Open(self):\n    self._connection = sqlite3.connect(\n        self._path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)\n    self._cursor = self._connection.cursor()",
    "docstring": "Opens the task storage for reading."
  },
  {
    "code": "def _encode_timestamp(name, value, dummy0, dummy1):\n    return b\"\\x11\" + name + _PACK_TIMESTAMP(value.inc, value.time)",
    "docstring": "Encode bson.timestamp.Timestamp."
  },
  {
    "code": "def check_down_connections(self):\n        now = time.time()\n        for db_num, marked_down_at in self._down_connections.items():\n            if marked_down_at + self.retry_timeout <= now:\n                self.mark_connection_up(db_num)",
    "docstring": "Iterates through all connections which were previously listed as unavailable\n        and marks any that have expired their retry_timeout as being up."
  },
  {
    "code": "async def on_raw_301(self, message):\n        target, nickname, message = message.params\n        info = {\n            'away': True,\n            'away_message': message\n        }\n        if nickname in self.users:\n            self._sync_user(nickname, info)\n        if nickname in self._pending['whois']:\n            self._whois_info[nickname].update(info)",
    "docstring": "User is away."
  },
  {
    "code": "def all(self):\n        return self.pages(self.url.page, self.url.max_page)",
    "docstring": "Yield torrents in range from current page to last page"
  },
  {
    "code": "def cli(env):\n    settings = config.get_settings_from_client(env.client)\n    env.fout(config.config_table(settings))",
    "docstring": "Show current configuration."
  },
  {
    "code": "def get_dataarg(args):\n    for i, arg in enumerate(args):\n        if is_nested_config_arg(arg):\n            return i, arg\n        elif is_std_config_arg(arg):\n            return i, {\"config\": arg}\n        elif isinstance(arg, (list, tuple)) and is_nested_config_arg(arg[0]):\n            return i, arg[0]\n    raise ValueError(\"Did not find configuration or data object in arguments: %s\" % args)",
    "docstring": "Retrieve the world 'data' argument from a set of input parameters."
  },
  {
    "code": "def run_MDR(n,stack_float,labels=None):\n    x1 = stack_float.pop()\n    x2 = stack_float.pop()\n    if len(np.unique(x1))<=3 and len(np.unique(x2))<=3:\n        tmp = np.vstack((x1,x2)).transpose()\n        if labels is None:\n            return n.model.transform(tmp)[:,0]\n        else:\n            out =  n.model.fit_transform(tmp,labels)[:,0]\n            return out\n    else:\n        return np.zeros(x1.shape[0])",
    "docstring": "run utility function for MDR nodes."
  },
  {
    "code": "def query(self, expression, vm='python'):\n        condition = self.eval(expression, vm=vm)\n        return self.compress(condition)",
    "docstring": "Evaluate expression and then use it to extract rows from the table.\n\n        Parameters\n        ----------\n        expression : string\n            Expression to evaluate.\n        vm : {'numexpr', 'python'}\n            Virtual machine to use.\n\n        Returns\n        -------\n        result : structured array"
  },
  {
    "code": "def _find_guids(guid_string):\n    guids = []\n    for found_guid in re.finditer(GUID_REGEX, guid_string):\n        if found_guid.groups():\n            guids.append(found_guid.group(0).strip('{}'))\n    return sorted(list(set(guids)))",
    "docstring": "Return the set of GUIDs found in guid_string\n\n    :param str guid_string:\n        String containing zero or more GUIDs.  Each GUID may or may not be\n        enclosed in {}\n\n    Example data (this string contains two distinct GUIDs):\n\n    PARENT_SNAPSHOT_ID                      SNAPSHOT_ID\n                                            {a5b8999f-5d95-4aff-82de-e515b0101b66}\n    {a5b8999f-5d95-4aff-82de-e515b0101b66} *{a7345be5-ab66-478c-946e-a6c2caf14909}"
  },
  {
    "code": "def write_xml_document(self, document):\n        self._out.write(ET.tostring(document))\n        self._out.flush()",
    "docstring": "Writes a string representation of an\n        ``ElementTree`` object to the output stream.\n\n        :param document: An ``ElementTree`` object."
  },
  {
    "code": "def copy_reset(self):\n        self._filters = []\n        self._filter_or = False\n        self._paginate = True\n        self._paginate_count = 0\n        self._result_count = None\n        self._result_limit = 500\n        self._result_start = 0",
    "docstring": "Reset values after instance has been copied"
  },
  {
    "code": "def _or_join(self, close_group=False):\n        if not self.initialized:\n            raise ValueError(\"You must add a search term before adding an operator.\")\n        else:\n            self._operator(\"OR\", close_group=close_group)\n        return self",
    "docstring": "Combine terms with OR.\n        There must be a term added before using this method.\n\n        Arguments:\n            close_group (bool): If ``True``, will end the current group and start a new one.\n                    If ``False``, will continue current group.\n\n                    Example:\n\n                        If the current query is \"(term1\"\n                        .or(close_group=True) => \"(term1) OR(\"\n                        .or(close_group=False) => \"(term1 OR \"\n\n        Returns:\n            SearchHelper: Self"
  },
  {
    "code": "def add_hits_to_proteins(self, hmm_hit_list):\n        for org in self.organisms:\n            print \"adding SearchIO hit objects for\", org.accession\n            for hit in hmm_hit_list:\n                hit_org_id = hit.id.split(',')[0]\n                hit_prot_id = hit.id.split(',')[1]\n                if org.accession == hit_org_id:\n                    for prot in org.proteins:\n                        if prot.accession == hit_prot_id:\n                            prot.hmm_hit_list.append(hit)",
    "docstring": "Add HMMER results to Protein objects"
  },
  {
    "code": "def md5_digest(instr):\n    return salt.utils.stringutils.to_unicode(\n        hashlib.md5(salt.utils.stringutils.to_bytes(instr)).hexdigest()\n    )",
    "docstring": "Generate an md5 hash of a given string."
  },
  {
    "code": "def add_events(self, **kwargs):\n        event_q = kwargs.get('event_queue')\n        pri = kwargs.get('priority')\n        if not event_q or not pri:\n            return\n        try:\n            event_type = 'server.failure.recovery'\n            payload = {}\n            timestamp = time.ctime()\n            data = (event_type, payload)\n            event_q.put((pri, timestamp, data))\n            LOG.debug('Added failure recovery event to the queue.')\n        except Exception as exc:\n            LOG.exception('Error: %(exc)s for event %(event)s',\n                          {'exc': str(exc), 'event': event_type})\n            raise exc",
    "docstring": "Add failure event into the queue."
  },
  {
    "code": "def output(data, **kwargs):\n    if isinstance(data, Exception):\n        data = six.text_type(data)\n    if 'output_indent' in __opts__ and __opts__['output_indent'] >= 0:\n        return pprint.pformat(data, indent=__opts__['output_indent'])\n    return pprint.pformat(data)",
    "docstring": "Print out via pretty print"
  },
  {
    "code": "def _write_module_descriptor_file(handle, module_dir):\n  readme = _module_descriptor_file(module_dir)\n  readme_content = (\n      \"Module: %s\\nDownload Time: %s\\nDownloader Hostname: %s (PID:%d)\" %\n      (handle, str(datetime.datetime.today()), socket.gethostname(),\n       os.getpid()))\n  tf_utils.atomic_write_string_to_file(readme, readme_content, overwrite=True)",
    "docstring": "Writes a descriptor file about the directory containing a module.\n\n  Args:\n    handle: Module name/handle.\n    module_dir: Directory where a module was downloaded."
  },
  {
    "code": "def iter_children(self, key=None):\n        u\n        tag = None\n        if key:\n            tag = self._get_aliases().get(key)\n            if not tag:\n                raise KeyError(key)\n        for child in self._xml.iterchildren(tag=tag):\n            if len(child):\n                yield self.__class__(child)\n            else:\n                yield Literal(child)",
    "docstring": "u\"\"\"Iterates over children.\n\n        :param key: A key for filtering children by tagname."
  },
  {
    "code": "def quote_str(obj):\n    r\n    if not isinstance(obj, str):\n        return obj\n    return \"'{obj}'\".format(obj=obj) if '\"' in obj else '\"{obj}\"'.format(obj=obj)",
    "docstring": "r\"\"\"\n    Add extra quotes to a string.\n\n    If the argument is not a string it is returned unmodified.\n\n    :param obj: Object\n    :type  obj: any\n\n    :rtype: Same as argument\n\n    For example:\n\n        >>> import pmisc\n        >>> pmisc.quote_str(5)\n        5\n        >>> pmisc.quote_str('Hello!')\n        '\"Hello!\"'\n        >>> pmisc.quote_str('He said \"hello!\"')\n        '\\'He said \"hello!\"\\''"
  },
  {
    "code": "def cleanup(self):\n        self.lock.acquire()\n        logger.debug('Acquired lock in cleanup for ' + str(self))\n        self.children = [child for child in self.children if child.is_alive()]\n        self.lock.release()",
    "docstring": "Clean up finished children.\n\n        :return: None"
  },
  {
    "code": "def _determine_keys(dictionary):\n    optional = {}\n    defaults = {}\n    mandatory = {}\n    types = {}\n    for key, value in dictionary.items():\n        if isinstance(key, Optional):\n            optional[key.value] = parse_schema(value)\n            if isinstance(value, BaseSchema) and\\\n                    value.default is not UNSPECIFIED:\n                defaults[key.value] = (value.default, value.null_values)\n            continue\n        if type(key) is type:\n            types[key] = parse_schema(value)\n            continue\n        mandatory[key] = parse_schema(value)\n    return mandatory, optional, types, defaults",
    "docstring": "Determine the different kinds of keys."
  },
  {
    "code": "def _add_sentence(self, sentence, ignore_traces=True):\n        self.sentences.append(self._node_id)\n        self.add_edge(self.root, self._node_id, edge_type=dg.EdgeTypes.dominance_relation)\n        self._parse_sentencetree(sentence, ignore_traces=ignore_traces)\n        self._node_id += 1",
    "docstring": "add a sentence from the input document to the document graph.\n\n        Parameters\n        ----------\n        sentence : nltk.tree.Tree\n            a sentence represented by a Tree instance"
  },
  {
    "code": "def imagenet_preprocess_example(example, mode, resize_size=None,\n                                normalize=True):\n  resize_size = resize_size or [299, 299]\n  assert resize_size[0] == resize_size[1]\n  image = example[\"inputs\"]\n  if mode == tf.estimator.ModeKeys.TRAIN:\n    image = preprocess_for_train(image, image_size=resize_size[0],\n                                 normalize=normalize)\n  else:\n    image = preprocess_for_eval(image, image_size=resize_size[0],\n                                normalize=normalize)\n  example[\"inputs\"] = image\n  return example",
    "docstring": "Preprocessing used for Imagenet and similar problems."
  },
  {
    "code": "def delete_dimension(dimension_id,**kwargs):\n    try:\n        dimension = db.DBSession.query(Dimension).filter(Dimension.id==dimension_id).one()\n        db.DBSession.query(Unit).filter(Unit.dimension_id==dimension.id).delete()\n        db.DBSession.delete(dimension)\n        db.DBSession.flush()\n        return True\n    except NoResultFound:\n        raise ResourceNotFoundError(\"Dimension (dimension_id=%s) does not exist\"%(dimension_id))",
    "docstring": "Delete a dimension from the DB. Raises and exception if the dimension does not exist"
  },
  {
    "code": "def copy_recurse(lib_path, copy_filt_func = None, copied_libs = None):\n    if copied_libs is None:\n        copied_libs = {}\n    else:\n        copied_libs = dict(copied_libs)\n    done = False\n    while not done:\n        in_len = len(copied_libs)\n        _copy_required(lib_path, copy_filt_func, copied_libs)\n        done = len(copied_libs) == in_len\n    return copied_libs",
    "docstring": "Analyze `lib_path` for library dependencies and copy libraries\n\n    `lib_path` is a directory containing libraries.  The libraries might\n    themselves have dependencies.  This function analyzes the dependencies and\n    copies library dependencies that match the filter `copy_filt_func`. It also\n    adjusts the depending libraries to use the copy. It keeps iterating over\n    `lib_path` until all matching dependencies (of dependencies of dependencies\n    ...) have been copied.\n\n    Parameters\n    ----------\n    lib_path : str\n        Directory containing libraries\n    copy_filt_func : None or callable, optional\n        If None, copy any library that found libraries depend on.  If callable,\n        called on each depended library name; copy where\n        ``copy_filt_func(libname)`` is True, don't copy otherwise\n    copied_libs : dict\n        Dict with (key, value) pairs of (``copied_lib_path``,\n        ``dependings_dict``) where ``copied_lib_path`` is the canonical path of\n        a library that has been copied to `lib_path`, and ``dependings_dict``\n        is a dictionary with (key, value) pairs of (``depending_lib_path``,\n        ``install_name``).  ``depending_lib_path`` is the canonical path of the\n        library depending on ``copied_lib_path``, ``install_name`` is the name\n        that ``depending_lib_path`` uses to refer to ``copied_lib_path`` (in\n        its install names).\n\n    Returns\n    -------\n    copied_libs : dict\n        Input `copied_libs` dict with any extra libraries and / or dependencies\n        added."
  },
  {
    "code": "def _set_lim_and_transforms(self):\n        self.transAxes = BboxTransformTo(self.bbox)\n        self.transData = self.GingaTransform()\n        self.transData.viewer = self.viewer\n        self._xaxis_transform = self.transData\n        self._yaxis_transform = self.transData",
    "docstring": "This is called once when the plot is created to set up all the\n        transforms for the data, text and grids."
  },
  {
    "code": "def setTransducer(self, edfsignal, transducer):\n        if (edfsignal < 0 or edfsignal > self.n_channels):\n            raise ChannelDoesNotExist(edfsignal)\n        self.channels[edfsignal]['transducer'] = transducer\n        self.update_header()",
    "docstring": "Sets the transducer of signal edfsignal\n\n        :param edfsignal: int\n        :param transducer: str\n\n        Notes\n        -----\n        This function is optional for every signal and can be called only after opening a file in writemode and before the first sample write action."
  },
  {
    "code": "def sync_mounts(self, active_mounts, resources, vault_client):\n        mounts = [x for x in resources\n                  if isinstance(x, (Mount, AWS))]\n        s_resources = sorted(mounts, key=absent_sort)\n        for resource in s_resources:\n            active_mounts = self.actually_mount(vault_client,\n                                                resource,\n                                                active_mounts)\n        for resource in [x for x in resources\n                         if isinstance(x, Secret)]:\n            n_mounts = self.actually_mount(vault_client,\n                                           resource,\n                                           active_mounts)\n            if len(n_mounts) != len(active_mounts):\n                LOG.warning(\"Ad-Hoc mount with %s. Please specify\"\n                            \" explicit mountpoints.\", resource)\n            active_mounts = n_mounts\n        return active_mounts, [x for x in resources\n                               if not isinstance(x, (Mount))]",
    "docstring": "Synchronizes mount points. Removes things before\n        adding new."
  },
  {
    "code": "def simple_md2html(text, urls):\n    retval = special_links_replace(text, urls)\n    retval = re.sub(r'\\n\\n', r'</p><p>', retval)\n    retval = re.sub(r'\\n', r'<br />\\n', retval)\n    retval = re.sub(r'\"', r'&quot;', retval)\n    retval = list2html(retval)\n    return link2html(retval)",
    "docstring": "Convert a text from md to html"
  },
  {
    "code": "def result(self, input_sequence: str, config: Optional[BasicConfig] = None) -> Any:\n        sequential_labelers = [\n                sl_cls(input_sequence, config) for sl_cls in self.sequential_labeler_classes\n        ]\n        index_labels_generator = ((index, {\n                type(labeler): labeler.label(index) for labeler in sequential_labelers\n        }) for index in range(len(input_sequence)))\n        label_processor = self.label_processor_class(input_sequence, index_labels_generator, config)\n        label_processor_result = label_processor.result()\n        output_generator = self.output_generator_class(input_sequence, label_processor_result,\n                                                       config)\n        return output_generator.result()",
    "docstring": "Execute the workflow.\n\n        :param input_sequence: The input sequence."
  },
  {
    "code": "def _FindPartition(self, key):\n        hash_value = self.hash_generator.ComputeHash(key)\n        return self._LowerBoundSearch(self.partitions, hash_value)",
    "docstring": "Finds the partition from the byte array representation of the partition key."
  },
  {
    "code": "async def home_z(self, mount: top_types.Mount = None):\n        if not mount:\n            axes = [Axis.Z, Axis.A]\n        else:\n            axes = [Axis.by_mount(mount)]\n        await self.home(axes)",
    "docstring": "Home the two z-axes"
  },
  {
    "code": "def sky2pix_ellipse(self, pos, a, b, pa):\n        ra, dec = pos\n        x, y = self.sky2pix(pos)\n        x_off, y_off = self.sky2pix(translate(ra, dec, a, pa))\n        sx = np.hypot((x - x_off), (y - y_off))\n        theta = np.arctan2((y_off - y), (x_off - x))\n        x_off, y_off = self.sky2pix(translate(ra, dec, b, pa - 90))\n        sy = np.hypot((x - x_off), (y - y_off))\n        theta2 = np.arctan2((y_off - y), (x_off - x)) - np.pi / 2\n        defect = theta - theta2\n        sy *= abs(np.cos(defect))\n        return x, y, sx, sy, np.degrees(theta)",
    "docstring": "Convert an ellipse from sky to pixel coordinates.\n\n        Parameters\n        ----------\n        pos : (float, float)\n            The (ra, dec) of the ellipse center (degrees).\n        a, b, pa: float\n            The semi-major axis, semi-minor axis and position angle of the ellipse (degrees).\n\n        Returns\n        -------\n        x,y : float\n            The (x, y) pixel coordinates of the ellipse center.\n        sx, sy : float\n            The major and minor axes (FWHM) in pixels.\n        theta : float\n            The rotation angle of the ellipse (degrees).\n            theta = 0 corresponds to the ellipse being aligned with the x-axis."
  },
  {
    "code": "def withTracebackPrint(ErrorType, thrownError, _traceback):\n    file = StringIO.StringIO()\n    traceback.print_exception(ErrorType, thrownError, _traceback, file = file)\n    return _loadError(ErrorType, thrownError, file.getvalue())",
    "docstring": "returns an Exception object for the given ErrorType of the thrownError\nand the _traceback\n\ncan be used like withTracebackPrint(*sys.exc_info())"
  },
  {
    "code": "def layout_route(self, request):\n    r\n    body = self.layout_impl()\n    return http_util.Respond(request, body, 'application/json')",
    "docstring": "r\"\"\"Fetches the custom layout specified by the config file in the logdir.\n\n    If more than 1 run contains a layout, this method merges the layouts by\n    merging charts within individual categories. If 2 categories with the same\n    name are found, the charts within are merged. The merging is based on the\n    order of the runs to which the layouts are written.\n\n    The response is a JSON object mirroring properties of the Layout proto if a\n    layout for any run is found.\n\n    The response is an empty object if no layout could be found."
  },
  {
    "code": "def __init_vertical_plot(self):\n        if len(self.ax2.lines) > 0:\n            self.ax2.cla()\n        self.ax2.set_ylabel(self.datalabel, fontsize=self.fontsize)\n        self.ax2.set_xlabel(self.spectrumlabel, fontsize=self.fontsize)\n        self.ax2.set_title('vertical point profiles', fontsize=self.fontsize)\n        self.ax2.set_xlim([1, self.bands])\n        self.vline = self.ax2.axvline(self.slider.value, color='black')",
    "docstring": "set up the vertical profile plot\n\n        Returns\n        -------"
  },
  {
    "code": "def create_command_history_subscription(self, on_data=None, timeout=60):\n        return self._client.create_command_history_subscription(\n            issued_command=self, on_data=on_data, timeout=timeout)",
    "docstring": "Create a new command history subscription for this command.\n\n        :param on_data: Function that gets called with  :class:`.CommandHistory`\n                        updates.\n        :param float timeout: The amount of seconds to wait for the request\n                              to complete.\n        :return: Future that can be used to manage the background websocket\n                 subscription\n        :rtype: .CommandHistorySubscription"
  },
  {
    "code": "def _max_gain_split(self, examples):\n        gains = self._new_set_of_gain_counters()\n        for example in examples:\n            for gain in gains:\n                gain.add(example)\n        winner = max(gains, key=lambda gain: gain.get_gain())\n        if not winner.get_target_class_counts():\n            raise ValueError(\"Dataset is empty\")\n        return winner",
    "docstring": "Returns an OnlineInformationGain of the attribute with\n        max gain based on `examples`."
  },
  {
    "code": "def info(self, collector_id):\n        cid = self.collector_id\n        if collector_id:\n            cid = collector_id\n        url = '{0}/{1}'.format(self.url, cid)\n        request = requests.get(url, auth=self.auth)\n        return request.json()",
    "docstring": "Return a dict of collector.\n\n        Args:\n            collector_id (int): id of collector (optional)"
  },
  {
    "code": "def new_binary_container(self, name):\n        self._message_stack.append(BinaryContainerTemplate(name, self._current_container))",
    "docstring": "Defines a new binary container to template.\n\n        Binary container can only contain binary fields defined with `Bin`\n        keyword.\n\n        Examples:\n        | New binary container | flags |\n        | bin | 2 | foo |\n        | bin | 6 | bar |\n        | End binary container |"
  },
  {
    "code": "def fill_datetime(self):\n    if not self.filled:\n      raise SlotNotFilledError('Slot with name \"%s\", key \"%s\" not yet filled.'\n                               % (self.name, self.key))\n    return self._fill_datetime",
    "docstring": "Returns when the slot was filled.\n\n    Returns:\n      A datetime.datetime.\n\n    Raises:\n      SlotNotFilledError if the value hasn't been filled yet."
  },
  {
    "code": "def select_atoms(indices):\n    rep = current_representation()\n    rep.select({'atoms': Selection(indices, current_system().n_atoms)})\n    return rep.selection_state",
    "docstring": "Select atoms by their indices.\n\n    You can select the first 3 atoms as follows::\n\n      select_atoms([0, 1, 2])\n    \n    Return the current selection dictionary."
  },
  {
    "code": "def expand_node_successors(universe, graph, node: BaseEntity) -> None:\n    skip_predecessors = set()\n    for predecessor in universe.predecessors(node):\n        if predecessor in graph:\n            skip_predecessors.add(predecessor)\n            continue\n        graph.add_node(predecessor, **universe.nodes[predecessor])\n    graph.add_edges_from(\n        (predecessor, target, key, data)\n        for predecessor, target, key, data in universe.in_edges(node, data=True, keys=True)\n        if predecessor not in skip_predecessors\n    )\n    update_node_helper(universe, graph)\n    update_metadata(universe, graph)",
    "docstring": "Expand around the successors of the given node in the result graph.\n\n    :param pybel.BELGraph universe: The graph containing the stuff to add\n    :param pybel.BELGraph graph: The graph to add stuff to\n    :param node: A BEL node"
  },
  {
    "code": "def make_secret(form_instance, secret_fields=None):\n    warn_untested()\n    if secret_fields is None:\n        secret_fields = ['business', 'item_name']\n    data = \"\"\n    for name in secret_fields:\n        if hasattr(form_instance, 'cleaned_data'):\n            if name in form_instance.cleaned_data:\n                data += unicode(form_instance.cleaned_data[name])\n        else:\n            if name in form_instance.initial:\n                data += unicode(form_instance.initial[name])\n            elif name in form_instance.fields and form_instance.fields[name].initial is not None:\n                data += unicode(form_instance.fields[name].initial)\n    secret = get_sha1_hexdigest(settings.SECRET_KEY, data)\n    return secret",
    "docstring": "Returns a secret for use in a EWP form or an IPN verification based on a\n    selection of variables in params. Should only be used with SSL."
  },
  {
    "code": "def get_full_python_version():\n    version_part = '.'.join(str(x) for x in sys.version_info)\n    int_width = struct.calcsize('P') * 8\n    int_width_part = str(int_width) + 'bit'\n    return version_part + '.' + int_width_part",
    "docstring": "Get full Python version.\n\n    E.g.\n        - `2.7.11.final.0.32bit`\n        - `3.5.1.final.0.64bit`\n\n    :return: Full Python version."
  },
  {
    "code": "def detach_usage_plan_from_apis(plan_id, apis, region=None, key=None, keyid=None, profile=None):\n    return _update_usage_plan_apis(plan_id, apis, 'remove', region=region, key=key, keyid=keyid, profile=profile)",
    "docstring": "Detaches given usage plan from each of the apis provided in a list of apiId and stage value\n\n    .. versionadded:: 2017.7.0\n\n    apis\n        a list of dictionaries, where each dictionary contains the following:\n\n        apiId\n            a string, which is the id of the created API in AWS ApiGateway\n\n        stage\n            a string, which is the stage that the created API is deployed to.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_apigateway.detach_usage_plan_to_apis plan_id='usage plan id' apis='[{\"apiId\": \"some id 1\", \"stage\": \"some stage 1\"}]'"
  },
  {
    "code": "def save_all(polyfile):\n        nump = len(PolygonFilter.instances)\n        if nump == 0:\n            raise PolygonFilterError(\"There are not polygon filters to save.\")\n        for p in PolygonFilter.instances:\n            polyobj = p.save(polyfile, ret_fobj=True)\n        polyobj.close()",
    "docstring": "Save all polygon filters"
  },
  {
    "code": "async def send_script(self, conn_id, data):\n        self._ensure_connection(conn_id, True)\n        connection_string = self._get_property(conn_id, \"connection_string\")\n        msg = dict(connection_string=connection_string, fragment_count=1, fragment_index=0,\n                   script=base64.b64encode(data))\n        await self._send_command(OPERATIONS.SEND_SCRIPT, msg, COMMANDS.SendScriptResponse)",
    "docstring": "Send a a script to this IOTile device\n\n        Args:\n            conn_id (int): A unique identifier that will refer to this connection\n            data (bytes): the script to send to the device"
  },
  {
    "code": "def validate(self, ticket, client_ip=None, now=None, encoding='utf-8'):\n        parts = self.parse(ticket)\n        new_ticket = self.new(*(parts[1:]), client_ip=client_ip, encoding=encoding)\n        if new_ticket[:self._hash.digest_size * 2] != parts.digest:\n            raise TicketDigestError(ticket)\n        if now is None:\n            now = time.time()\n        if parts.valid_until <= now:\n            raise TicketExpired(ticket)\n        return parts",
    "docstring": "Validates the passed ticket, , raises a TicketError\n        on failure\n\n        Args:\n            ticket: String value (possibly generated by new function)\n            client_ip: Optional IPAddress of client, should be passed if the\n                ip address was passed on ticket creation.\n            now: Optional (defaults to time.time()) time to use when\n                validating ticket date\n\n        Returns:\n            Ticket a TicketInfo tuple containing the users authentication details on\n            success\n\n        Raises:\n            TicketParseError: Invalid ticket format\n            TicketDigestError: Digest is incorrect (ticket data was modified)\n            TicketExpired: Ticket has passed expiration date"
  },
  {
    "code": "def cp(src_filename, dst_filename):\n    src_dev, src_dev_filename = get_dev_and_path(src_filename)\n    dst_dev, dst_dev_filename = get_dev_and_path(dst_filename)\n    if src_dev is dst_dev:\n        return auto(copy_file, src_filename, dst_dev_filename)\n    filesize = auto(get_filesize, src_filename)\n    if dst_dev is None:\n        with open(dst_dev_filename, 'wb') as dst_file:\n            return src_dev.remote(send_file_to_host, src_dev_filename, dst_file,\n                                  filesize, xfer_func=recv_file_from_remote)\n    if src_dev is None:\n        with open(src_dev_filename, 'rb') as src_file:\n            return dst_dev.remote(recv_file_from_host, src_file, dst_dev_filename,\n                                  filesize, xfer_func=send_file_to_remote)\n    host_temp_file = tempfile.TemporaryFile()\n    if src_dev.remote(send_file_to_host, src_dev_filename, host_temp_file,\n                      filesize, xfer_func=recv_file_from_remote):\n        host_temp_file.seek(0)\n        return dst_dev.remote(recv_file_from_host, host_temp_file, dst_dev_filename,\n                              filesize, xfer_func=send_file_to_remote)\n    return False",
    "docstring": "Copies one file to another. The source file may be local or remote and\n       the destination file may be local or remote."
  },
  {
    "code": "def reset(self, indices, observations):\n    assert isinstance(indices, np.ndarray)\n    assert len(indices.shape) == 1\n    assert isinstance(observations, np.ndarray)\n    assert indices.shape[0] == observations.shape[0]\n    for index, observation in zip(indices, observations):\n      trajectory = self._trajectories[index]\n      if not trajectory.is_active:\n        trajectory.add_time_step(observation=observation)\n        continue\n      self._complete_trajectory(trajectory, index)\n      self._trajectories[index].add_time_step(observation=observation)",
    "docstring": "Resets trajectories at given indices and populates observations.\n\n    Reset can either be called right at the beginning, when there are no\n    time-steps, or to reset a currently active trajectory.\n\n    If resetting a currently active trajectory then we save it in\n    self._completed_trajectories.\n\n    Args:\n      indices: 1-D np.ndarray stating the indices to reset.\n      observations: np.ndarray of shape (indices len, obs.shape) of observations"
  },
  {
    "code": "def write_implied_format(self, path, jpeg_quality=0, jpeg_progressive=0):\n        filename = fspath(path)\n        with _LeptonicaErrorTrap():\n            lept.pixWriteImpliedFormat(\n                os.fsencode(filename), self._cdata, jpeg_quality, jpeg_progressive\n            )",
    "docstring": "Write pix to the filename, with the extension indicating format.\n\n        jpeg_quality -- quality (iff JPEG; 1 - 100, 0 for default)\n        jpeg_progressive -- (iff JPEG; 0 for baseline seq., 1 for progressive)"
  },
  {
    "code": "def get_all_load_balancers(self, load_balancer_names=None):\n        params = {}\n        if load_balancer_names:\n            self.build_list_params(params, load_balancer_names,\n                                   'LoadBalancerNames.member.%d')\n        return self.get_list('DescribeLoadBalancers', params,\n                             [('member', LoadBalancer)])",
    "docstring": "Retrieve all load balancers associated with your account.\n\n        :type load_balancer_names: list\n        :keyword load_balancer_names: An optional list of load balancer names.\n\n        :rtype: :py:class:`boto.resultset.ResultSet`\n        :return: A ResultSet containing instances of\n            :class:`boto.ec2.elb.loadbalancer.LoadBalancer`"
  },
  {
    "code": "def query_nodes(self,\n                    bel: Optional[str] = None,\n                    type: Optional[str] = None,\n                    namespace: Optional[str] = None,\n                    name: Optional[str] = None,\n                    ) -> List[Node]:\n        q = self.session.query(Node)\n        if bel:\n            q = q.filter(Node.bel.contains(bel))\n        if type:\n            q = q.filter(Node.type == type)\n        if namespace or name:\n            q = q.join(NamespaceEntry)\n            if namespace:\n                q = q.join(Namespace).filter(Namespace.keyword.contains(namespace))\n            if name:\n                q = q.filter(NamespaceEntry.name.contains(name))\n        return q",
    "docstring": "Query nodes in the database.\n\n        :param bel: BEL term that describes the biological entity. e.g. ``p(HGNC:APP)``\n        :param type: Type of the biological entity. e.g. Protein\n        :param namespace: Namespace keyword that is used in BEL. e.g. HGNC\n        :param name: Name of the biological entity. e.g. APP"
  },
  {
    "code": "def refresh(self, **kwargs):\n        if self._id_attr:\n            path = '%s/%s' % (self.manager.path, self.id)\n        else:\n            path = self.manager.path\n        server_data = self.manager.gitlab.http_get(path, **kwargs)\n        self._update_attrs(server_data)",
    "docstring": "Refresh a single object from server.\n\n        Args:\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Returns None (updates the object)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabGetError: If the server cannot perform the request"
  },
  {
    "code": "def _request_eip(interface, vm_):\n    params = {'Action': 'AllocateAddress'}\n    params['Domain'] = interface.setdefault('domain', 'vpc')\n    eips = aws.query(params,\n                     return_root=True,\n                     location=get_location(vm_),\n                     provider=get_provider(),\n                     opts=__opts__,\n                     sigver='4')\n    for eip in eips:\n        if 'allocationId' in eip:\n            return eip['allocationId']\n    return None",
    "docstring": "Request and return Elastic IP"
  },
  {
    "code": "def put(value):\n    worker = global_worker\n    worker.check_connected()\n    with profiling.profile(\"ray.put\"):\n        if worker.mode == LOCAL_MODE:\n            return value\n        object_id = ray._raylet.compute_put_id(\n            worker.current_task_id,\n            worker.task_context.put_index,\n        )\n        worker.put_object(object_id, value)\n        worker.task_context.put_index += 1\n        return object_id",
    "docstring": "Store an object in the object store.\n\n    Args:\n        value: The Python object to be stored.\n\n    Returns:\n        The object ID assigned to this value."
  },
  {
    "code": "def _get_prediction_device(self) -> int:\n        devices = {util.get_device_of(param) for param in self.parameters()}\n        if len(devices) > 1:\n            devices_string = \", \".join(str(x) for x in devices)\n            raise ConfigurationError(f\"Parameters have mismatching cuda_devices: {devices_string}\")\n        elif len(devices) == 1:\n            return devices.pop()\n        else:\n            return -1",
    "docstring": "This method checks the device of the model parameters to determine the cuda_device\n        this model should be run on for predictions.  If there are no parameters, it returns -1.\n\n        Returns\n        -------\n        The cuda device this model should run on for predictions."
  },
  {
    "code": "def store_data(self, data, encoding='utf-8'):\n        path = random_filename(self.work_path)\n        try:\n            with open(path, 'wb') as fh:\n                if isinstance(data, str):\n                    data = data.encode(encoding)\n                if data is not None:\n                    fh.write(data)\n            return self.store_file(path)\n        finally:\n            try:\n                os.unlink(path)\n            except OSError:\n                pass",
    "docstring": "Put the given content into a file, possibly encoding it as UTF-8\n        in the process."
  },
  {
    "code": "def visit_listcomp(self, node):\n        return \"[%s %s]\" % (\n            node.elt.accept(self),\n            \" \".join(n.accept(self) for n in node.generators),\n        )",
    "docstring": "return an astroid.ListComp node as string"
  },
  {
    "code": "def _ensure_reactor_running():\n    if not reactor.running:\n        signal_registrations = []\n        def signal_capture(*args, **kwargs):\n            signal_registrations.append((orig_signal, args, kwargs))\n        def set_wakeup_fd_capture(*args, **kwargs):\n            signal_registrations.append((orig_set_wakeup_fd, args, kwargs))\n        orig_signal = signal.signal\n        signal.signal = signal_capture\n        orig_set_wakeup_fd = signal.set_wakeup_fd\n        signal.set_wakeup_fd = set_wakeup_fd_capture\n        reactor_thread = threading.Thread(target=reactor.run, name=\"reactor\")\n        reactor_thread.daemon = True\n        reactor_thread.start()\n        while not reactor.running:\n            time.sleep(0.01)\n        time.sleep(0.01)\n        signal.signal = orig_signal\n        signal.set_wakeup_fd = orig_set_wakeup_fd\n        for func, args, kwargs in signal_registrations:\n            func(*args, **kwargs)",
    "docstring": "Starts the twisted reactor if it is not running already.\n    \n    The reactor is started in a new daemon-thread.\n    \n    Has to perform dirty hacks so that twisted can register\n    signals even if it is not running in the main-thread."
  },
  {
    "code": "def _sendResult(self, result):\n        try:\n            result = json.dumps(result)\n        except Exception as error:\n            result = json.dumps(self._errorInfo(command, error))\n        sys.stdout.write(result)\n        sys.stdout.write(\"\\n\")\n        sys.stdout.flush()",
    "docstring": "Send parseable json result of command."
  },
  {
    "code": "def _assert_obj_type(pub, name=\"pub\", obj_type=DBPublication):\n    if not isinstance(pub, obj_type):\n        raise InvalidType(\n            \"`%s` have to be instance of %s, not %s!\" % (\n                name,\n                obj_type.__name__,\n                pub.__class__.__name__\n            )\n        )",
    "docstring": "Make sure, that `pub` is instance of the `obj_type`.\n\n    Args:\n        pub (obj): Instance which will be checked.\n        name (str): Name of the instance. Used in exception. Default `pub`.\n        obj_type (class): Class of which the `pub` should be instance. Default\n                 :class:`.DBPublication`.\n\n    Raises:\n        InvalidType: When the `pub` is not instance of `obj_type`."
  },
  {
    "code": "def save(self, *args, **kwargs):\n        if not self.pk:\n            old_votes = Vote.objects.filter(user=self.user, node=self.node)\n            for old_vote in old_votes:\n                old_vote.delete()\n        super(Vote, self).save(*args, **kwargs)",
    "docstring": "ensure users cannot vote the same node multiple times\n        but let users change their votes"
  },
  {
    "code": "def from_session(cls, session):\n        session.error_wrapper = lambda e: NvimError(e[1])\n        channel_id, metadata = session.request(b'vim_get_api_info')\n        if IS_PYTHON3:\n            metadata = walk(decode_if_bytes, metadata)\n        types = {\n            metadata['types']['Buffer']['id']: Buffer,\n            metadata['types']['Window']['id']: Window,\n            metadata['types']['Tabpage']['id']: Tabpage,\n        }\n        return cls(session, channel_id, metadata, types)",
    "docstring": "Create a new Nvim instance for a Session instance.\n\n        This method must be called to create the first Nvim instance, since it\n        queries Nvim metadata for type information and sets a SessionHook for\n        creating specialized objects from Nvim remote handles."
  },
  {
    "code": "def authenticate(self, username, password):\n        self._username = username\n        self._password = password\n        self.disconnect()\n        self._open_connection()\n        return self.authenticated",
    "docstring": "Authenticate user on server.\n\n        :param username: Username used to be authenticated.\n        :type username: six.string_types\n        :param password: Password used to be authenticated.\n        :type password: six.string_types\n        :return: True if successful.\n        :raises: InvalidCredentials, AuthenticationNotSupported, MemcachedException\n        :rtype: bool"
  },
  {
    "code": "def order_percent(self,\n                      asset,\n                      percent,\n                      limit_price=None,\n                      stop_price=None,\n                      style=None):\n        if not self._can_order_asset(asset):\n            return None\n        amount = self._calculate_order_percent_amount(asset, percent)\n        return self.order(asset, amount,\n                          limit_price=limit_price,\n                          stop_price=stop_price,\n                          style=style)",
    "docstring": "Place an order in the specified asset corresponding to the given\n        percent of the current portfolio value.\n\n        Parameters\n        ----------\n        asset : Asset\n            The asset that this order is for.\n        percent : float\n            The percentage of the portfolio value to allocate to ``asset``.\n            This is specified as a decimal, for example: 0.50 means 50%.\n        limit_price : float, optional\n            The limit price for the order.\n        stop_price : float, optional\n            The stop price for the order.\n        style : ExecutionStyle\n            The execution style for the order.\n\n        Returns\n        -------\n        order_id : str\n            The unique identifier for this order.\n\n        Notes\n        -----\n        See :func:`zipline.api.order` for more information about\n        ``limit_price``, ``stop_price``, and ``style``\n\n        See Also\n        --------\n        :class:`zipline.finance.execution.ExecutionStyle`\n        :func:`zipline.api.order`\n        :func:`zipline.api.order_value`"
  },
  {
    "code": "def fetch(self):\n        params = values.of({})\n        payload = self._version.fetch(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return AddOnResultInstance(\n            self._version,\n            payload,\n            account_sid=self._solution['account_sid'],\n            reference_sid=self._solution['reference_sid'],\n            sid=self._solution['sid'],\n        )",
    "docstring": "Fetch a AddOnResultInstance\n\n        :returns: Fetched AddOnResultInstance\n        :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance"
  },
  {
    "code": "def DbGetAttributeAliasList(self, argin):\n        self._log.debug(\"In DbGetAttributeAliasList()\")\n        if not argin:\n            argin = \"%\"\n        else:\n            argin = replace_wildcard(argin)\n        return self.db.get_attribute_alias_list(argin)",
    "docstring": "Get attribute alias list for a specified filter\n\n        :param argin: attribute alias filter string (eg: att*)\n        :type: tango.DevString\n        :return: attribute aliases\n        :rtype: tango.DevVarStringArray"
  },
  {
    "code": "def get_axis(self, undefined=np.zeros(3)):\n        tolerance = 1e-17\n        self._normalise()\n        norm = np.linalg.norm(self.vector)\n        if norm < tolerance:\n            return undefined\n        else:\n            return self.vector / norm",
    "docstring": "Get the axis or vector about which the quaternion rotation occurs\n\n        For a null rotation (a purely real quaternion), the rotation angle will\n        always be `0`, but the rotation axis is undefined.\n        It is by default assumed to be `[0, 0, 0]`.\n\n        Params:\n            undefined: [optional] specify the axis vector that should define a null rotation.\n                This is geometrically meaningless, and could be any of an infinite set of vectors,\n                but can be specified if the default (`[0, 0, 0]`) causes undesired behaviour.\n\n        Returns:\n            A Numpy unit 3-vector describing the Quaternion object's axis of rotation.\n\n        Note:\n            This feature only makes sense when referring to a unit quaternion.\n            Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one."
  },
  {
    "code": "def spliceext(filepath, s):\n    root, ext = os.path.splitext(safepath(filepath))\n    return root + s + ext",
    "docstring": "Add s into filepath before the extension\n\n    Args:\n        filepath (str, path): file path\n        s (str): string to splice\n\n    Returns:\n        str"
  },
  {
    "code": "def create_package_node(self, team, user, package, dry_run=False):\n        contents = RootNode(dict())\n        if dry_run:\n            return contents\n        self.check_name(team, user, package)\n        assert contents is not None\n        self.create_dirs()\n        path = self.package_path(team, user, package)\n        try:\n            os.remove(path)\n        except OSError:\n            pass\n        return contents",
    "docstring": "Creates a new package and initializes its contents. See `install_package`."
  },
  {
    "code": "def p_flatten(self, obj, **kwargs):\n        if isinstance(obj, six.string_types):\n            return obj\n        result = \"\"\n        for i in obj:\n            result += self.p_flatten(i)\n        return result",
    "docstring": "Flatten a list of lists of lists... of strings into a string\n\n        This is usually used as the action for sequence expressions:\n\n        .. code-block::\n\n            my_rule <- 'a' . 'c' {p_flatten}\n\n        With the input \"abc\" and no action, this rule returns [ 'a', 'b', 'c'].\n        { p_flatten } procuces \"abc\".\n\n        >>> parser.p_flatten(['a', ['b', 'c']])\n        'abc'"
  },
  {
    "code": "def CreateJarBuilder(env):\n    try:\n        java_jar = env['BUILDERS']['JarFile']\n    except KeyError:\n        fs = SCons.Node.FS.get_default_fs()\n        jar_com = SCons.Action.Action('$JARCOM', '$JARCOMSTR')\n        java_jar = SCons.Builder.Builder(action = jar_com,\n                                         suffix = '$JARSUFFIX',\n                                         src_suffix = '$JAVACLASSSUFFIX',\n                                         src_builder = 'JavaClassFile',\n                                         source_factory = fs.Entry)\n        env['BUILDERS']['JarFile'] = java_jar\n    return java_jar",
    "docstring": "The Jar builder expects a list of class files\n    which it can package into a jar file.\n\n    The jar tool provides an interface for passing other types\n    of java files such as .java, directories or swig interfaces\n    and will build them to class files in which it can package\n    into the jar."
  },
  {
    "code": "def save_xml(self, doc, element):\n        for cond in self._targets:\n            new_element = doc.createElementNS(RTS_NS, RTS_NS_S + 'targets')\n            new_element.setAttributeNS(XSI_NS, XSI_NS_S + 'type', 'rtsExt:condition_ext')\n            cond.save_xml(doc, new_element)\n            element.appendChild(new_element)",
    "docstring": "Save this message_sending object into an xml.dom.Element object."
  },
  {
    "code": "def find_path_with_profiles(self, conversion_profiles, in_, out):\n        original_profiles = dict(self.conversion_profiles)\n        self._setup_profiles(conversion_profiles)\n        results = self.find_path(in_, out)\n        self.conversion_profiles = original_profiles\n        return results",
    "docstring": "Like find_path, except forces the conversion profiles to be the given\n        conversion profile setting. Useful for \"temporarily overriding\" the\n        global conversion profiles with your own."
  },
  {
    "code": "def credit_card_owner(self, gender: Optional[Gender] = None) -> dict:\n        owner = {\n            'credit_card': self.credit_card_number(),\n            'expiration_date': self.credit_card_expiration_date(),\n            'owner': self.__person.full_name(gender=gender).upper(),\n        }\n        return owner",
    "docstring": "Generate credit card owner.\n\n        :param gender: Gender of credit card owner.\n        :type gender: Gender's enum object.\n        :return:"
  },
  {
    "code": "def bulk_activate(workers, lbn, profile='default'):\n    ret = {}\n    if isinstance(workers, six.string_types):\n        workers = workers.split(',')\n    for worker in workers:\n        try:\n            ret[worker] = worker_activate(worker, lbn, profile)\n        except Exception:\n            ret[worker] = False\n    return ret",
    "docstring": "Activate all the given workers in the specific load balancer\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1\n        salt '*' modjk.bulk_activate node1,node2,node3 loadbalancer1 other-profile\n\n        salt '*' modjk.bulk_activate [\"node1\",\"node2\",\"node3\"] loadbalancer1\n        salt '*' modjk.bulk_activate [\"node1\",\"node2\",\"node3\"] loadbalancer1 other-profile"
  },
  {
    "code": "def send(self, request, socket, context, *args):\n        for handler, pattern in self.handlers:\n            no_channel = not pattern and not socket.channels\n            if self.name.endswith(\"subscribe\") and pattern:\n                matches = [pattern.match(args[0])]\n            else:\n                matches = [pattern.match(c) for c in socket.channels if pattern]\n            if no_channel or filter(None, matches):\n                handler(request, socket, context, *args)",
    "docstring": "When an event is sent, run all relevant handlers. Relevant\n        handlers are those without a channel pattern when the given\n        socket is not subscribed to any particular channel, or the\n        handlers with a channel pattern that matches any of the\n        channels that the given socket is subscribed to.\n\n        In the case of subscribe/unsubscribe, match the channel arg\n        being sent to the channel pattern."
  },
  {
    "code": "def commentless(data):\n    it = iter(data)\n    while True:\n        line = next(it)\n        while \":\" in line or not line.lstrip().startswith(\"..\"):\n            yield line\n            line = next(it)\n        indent = indent_size(line)\n        it = itertools.dropwhile(lambda el: indent_size(el) > indent\n                                            or not el.strip(), it)",
    "docstring": "Generator that removes from a list of strings the double dot\n    reStructuredText comments and its contents based on indentation,\n    removing trailing empty lines after each comment as well."
  },
  {
    "code": "def update_db(self, giver, receiverkarma):\n        for receiver in receiverkarma:\n            if receiver != giver:\n                urow = KarmaStatsTable(\n                    ude(giver), ude(receiver), receiverkarma[receiver])\n                self.db.session.add(urow)\n        self.db.session.commit()",
    "docstring": "Record a the giver of karma, the receiver of karma, and the karma\n        amount. Typically the count will be 1, but it can be any positive or\n        negative integer."
  },
  {
    "code": "def send_output(self, value, stdout):\n        writer = self.writer\n        if value is not None:\n            writer.write('{!r}\\n'.format(value).encode('utf8'))\n        if stdout:\n            writer.write(stdout.encode('utf8'))\n        yield from writer.drain()",
    "docstring": "Write the output or value of the expression back to user.\n\n        >>> 5\n        5\n        >>> print('cash rules everything around me')\n        cash rules everything around me"
  },
  {
    "code": "def wait_for(self, pattern, timeout=None):\n        should_continue = True\n        if self.block:\n            raise TypeError(NON_BLOCKING_ERROR_MESSAGE)\n        def stop(signum, frame):\n            nonlocal should_continue\n            if should_continue:\n                raise TimeoutError()\n        if timeout:\n            signal.signal(signal.SIGALRM, stop)\n            signal.alarm(timeout)\n        while should_continue:\n            output = self.poll_output() + self.poll_error()\n            filtered = [line for line in output if re.match(pattern, line)]\n            if filtered:\n                should_continue = False",
    "docstring": "Block until a pattern have been found in stdout and stderr\n\n        Args:\n            pattern(:class:`~re.Pattern`): The pattern to search\n            timeout(int): Maximum number of second to wait. If None, wait infinitely\n\n        Raises: \n            TimeoutError: When timeout is reach"
  },
  {
    "code": "def stacked_node_layout(self,EdgeAttribute=None,network=None,NodeAttribute=None,\\\n\t\tnodeList=None,x_position=None,y_start_position=None,verbose=None):\n\t\tnetwork=check_network(self,network,verbose=verbose)\n\t\tPARAMS=set_param(['EdgeAttribute','network','NodeAttribute','nodeList',\\\n\t\t'x_position','y_start_position'],[EdgeAttribute,network,NodeAttribute,\\\n\t\tnodeList,x_position,y_start_position])\n\t\tresponse=api(url=self.__url+\"/stacked-node-layout\", PARAMS=PARAMS, method=\"POST\", verbose=verbose)\n\t\treturn response",
    "docstring": "Execute the Stacked Node Layout on a network.\n\n\t\t:param EdgeAttribute (string, optional): The name of the edge column contai\n\t\t\tning numeric values that will be used as weights in the layout algor\n\t\t\tithm. Only columns containing numeric values are shown\n\t\t:param network (string, optional): Specifies a network by name, or by SUID\n\t\t\tif the prefix SUID: is used. The keyword CURRENT, or a blank value c\n\t\t\tan also be used to specify the current network.\n\t\t:param NodeAttribute (string, optional): The name of the node column contai\n\t\t\tning numeric values that will be used as weights in the layout algor\n\t\t\tithm. Only columns containing numeric values are shown\n\t\t:param nodeList (string, optional): Specifies a list of nodes. The keywords\n\t\t\t\tall, selected, or unselected can be used to specify nodes by their\n\t\t\tselection state. The pattern COLUMN:VALUE sets this parameter to any\n\t\t\t\trows that contain the specified column value; if the COLUMN prefix\n\t\t\tis not used, the NAME column is matched by default. A list of COLUMN\n\t\t\t:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be\n\t\t\tused to match multiple values.\n\t\t:param x_position (string, optional): X start position, in numeric value\n\t\t:param y_start_position (string, optional): Y start position, in numeric va\n\t\t\tlue"
  },
  {
    "code": "def _is_skippable(filename_full):\n    if not Settings.follow_symlinks and os.path.islink(filename_full):\n        return True\n    if os.path.basename(filename_full) == timestamp.RECORD_FILENAME:\n        return True\n    if not os.path.exists(filename_full):\n        if Settings.verbose:\n            print(filename_full, 'was not found.')\n        return True\n    return False",
    "docstring": "Handle things that are not optimizable files."
  },
  {
    "code": "def handle_comment(self, comment):\n        match = _COND_COMMENT_PATTERN.match(comment)\n        if match is not None:\n            cond = match.group(1)\n            content = match.group(2)\n            self._buffer.append(_COND_COMMENT_START_FORMAT % cond)\n            self._push_status()\n            self.feed(content)\n            self._pop_status()\n            self._buffer.append(_COND_COMMENT_END_FORMAT)\n        elif not self.remove_comments:\n            self._buffer.append(_COMMENT_FORMAT % comment)",
    "docstring": "Remove comment except IE conditional comment.\n\n        .. seealso::\n           `About conditional comments\n            <http://msdn.microsoft.com/en-us/library/ms537512.ASPX>`_"
  },
  {
    "code": "def installed(name, default=False, user=None):\n    ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}\n    if name.startswith('python-'):\n        name = re.sub(r'^python-', '', name)\n    if __opts__['test']:\n        ret['comment'] = 'python {0} is set to be installed'.format(name)\n        return ret\n    ret = _check_pyenv(ret, user)\n    if ret['result'] is False:\n        if not __salt__['pyenv.install'](user):\n            ret['comment'] = 'pyenv failed to install'\n            return ret\n        else:\n            return _check_and_install_python(ret, name, default, user=user)\n    else:\n        return _check_and_install_python(ret, name, default, user=user)",
    "docstring": "Verify that the specified python is installed with pyenv. pyenv is\n    installed if necessary.\n\n    name\n        The version of python to install\n\n    default : False\n        Whether to make this python the default.\n\n    user: None\n        The user to run pyenv as.\n\n        .. versionadded:: 0.17.0\n\n    .. versionadded:: 0.16.0"
  },
  {
    "code": "def download_from_search(query_str, folder, do_extract_text=True,\n                         max_results=None):\n    piis = get_piis(query_str)\n    for pii in piis[:max_results]:\n        if os.path.exists(os.path.join(folder, '%s.txt' % pii)):\n            continue\n        logger.info('Downloading %s' % pii)\n        xml = download_article(pii, 'pii')\n        sleep(1)\n        if do_extract_text:\n            txt = extract_text(xml)\n            if not txt:\n                continue\n            with open(os.path.join(folder, '%s.txt' % pii), 'wb') as fh:\n                fh.write(txt.encode('utf-8'))\n        else:\n            with open(os.path.join(folder, '%s.xml' % pii), 'wb') as fh:\n                fh.write(xml.encode('utf-8'))\n    return",
    "docstring": "Save raw text files based on a search for papers on ScienceDirect.\n\n    This performs a search to get PIIs, downloads the XML corresponding to\n    the PII, extracts the raw text and then saves the text into a file\n    in the designated folder.\n\n    Parameters\n    ----------\n    query_str : str\n        The query string to search with\n    folder : str\n        The local path to an existing folder in which the text files\n        will be dumped\n    do_extract_text : bool\n        Choose whether to extract text from the xml, or simply save the raw xml\n        files. Default is True, so text is extracted.\n    max_results : int or None\n        Default is None. If specified, limit the number of results to the given\n        maximum."
  },
  {
    "code": "def get_aa_letter(aa_code):\n    aa_letter = 'X'\n    for key, val in standard_amino_acids.items():\n        if val == aa_code:\n            aa_letter = key\n    return aa_letter",
    "docstring": "Get one-letter version of aa_code if possible. If not, return 'X'.\n\n    Parameters\n    ----------\n    aa_code : str\n        Three-letter amino acid code.\n\n    Returns\n    -------\n    aa_letter : str\n        One-letter aa code.\n        Default value is 'X'."
  },
  {
    "code": "def center(self, X):\n        X = X.copy()\n        inan = numpy.isnan(X)\n        if self.mu is None:\n            X_ = numpy.ma.masked_array(X, inan)\n            self.mu = X_.mean(0).base\n            self.sigma = X_.std(0).base\n        reduce(lambda y,x: setitem(x[0], x[1], x[2]), zip(X.T, inan.T, self.mu), None)\n        X = X - self.mu\n        X = X / numpy.where(self.sigma == 0, 1e-30, self.sigma)\n        return X",
    "docstring": "Center `X` in PCA space."
  },
  {
    "code": "def resolutions(self):\n        r_json = self._get_json('resolution')\n        resolutions = [Resolution(\n            self._options, self._session, raw_res_json) for raw_res_json in r_json]\n        return resolutions",
    "docstring": "Get a list of resolution Resources from the server.\n\n        :rtype: List[Resolution]"
  },
  {
    "code": "def write_info(self, w):\n        w.write_b_varchar(\"\")\n        w.write_b_varchar(self._table_type.typ_schema)\n        w.write_b_varchar(self._table_type.typ_name)",
    "docstring": "Writes TVP_TYPENAME structure\n\n        spec: https://msdn.microsoft.com/en-us/library/dd302994.aspx\n        @param w: TdsWriter\n        @return:"
  },
  {
    "code": "def display(self):\n        pygame.init()\n        self.display = pygame.display.set_mode((self.width,self.height))\n        self.display.blit(self.cloud,(0,0))\n        pygame.display.update()\n        while True:\n            for event in pygame.event.get():\n                if event.type == pygame.QUIT:\n                    pygame.quit()\n                    return",
    "docstring": "Displays the word cloud to the screen."
  },
  {
    "code": "def mode(self, target, mode_string=None, tags=None):\n        params = [target]\n        if mode_string:\n            params += mode_string\n        self.send('MODE', params=params, source=self.nick, tags=tags)",
    "docstring": "Sends new modes to or requests existing modes from the given target."
  },
  {
    "code": "def is_namespace_valid( namespace_id ):\n    if not is_b40( namespace_id ) or \"+\" in namespace_id or namespace_id.count(\".\") > 0:\n        return False\n    if len(namespace_id) == 0 or len(namespace_id) > LENGTHS['blockchain_id_namespace_id']:\n        return False\n    return True",
    "docstring": "Is a namespace ID valid?\n\n    >>> is_namespace_valid('abcd')\n    True\n    >>> is_namespace_valid('+abcd')\n    False\n    >>> is_namespace_valid('abc.def')\n    False\n    >>> is_namespace_valid('.abcd')\n    False\n    >>> is_namespace_valid('abcdabcdabcdabcdabcd')\n    False\n    >>> is_namespace_valid('abcdabcdabcdabcdabc')\n    True"
  },
  {
    "code": "def deg2fmt(ra_deg, dec_deg, format):\n    rhr, rmn, rsec = degToHms(ra_deg)\n    dsgn, ddeg, dmn, dsec = degToDms(dec_deg)\n    if format == 'hms':\n        return rhr, rmn, rsec, dsgn, ddeg, dmn, dsec\n    elif format == 'str':\n        ra_txt = '%d:%02d:%06.3f' % (rhr, rmn, rsec)\n        if dsgn < 0:\n            dsgn = '-'\n        else:\n            dsgn = '+'\n        dec_txt = '%s%d:%02d:%05.2f' % (dsgn, ddeg, dmn, dsec)\n        return ra_txt, dec_txt",
    "docstring": "Format coordinates."
  },
  {
    "code": "def register_api_doc_endpoints(config, endpoints, base_path='/api-docs'):\n    for endpoint in endpoints:\n        path = base_path.rstrip('/') + endpoint.path\n        config.add_route(endpoint.route_name, path)\n        config.add_view(\n            endpoint.view,\n            route_name=endpoint.route_name,\n            renderer=endpoint.renderer)",
    "docstring": "Create and register pyramid endpoints to service swagger api docs.\n    Routes and views will be registered on the `config` at `path`.\n\n    :param config: a pyramid configuration to register the new views and routes\n    :type  config: :class:`pyramid.config.Configurator`\n    :param endpoints: a list of endpoints to register as routes and views\n    :type  endpoints: a list of :class:`pyramid_swagger.model.PyramidEndpoint`\n    :param base_path: the base path used to register api doc endpoints.\n        Defaults to `/api-docs`.\n    :type  base_path: string"
  },
  {
    "code": "def get(self, recipe=None, plugin=None):\n        if plugin is not None:\n            if recipe is None:\n                recipes_list = {}\n                for key in self.recipes.keys():\n                    if self.recipes[key].plugin == plugin:\n                        recipes_list[key] = self.recipes[key]\n                return recipes_list\n            else:\n                if recipe in self.recipes.keys():\n                    if self.recipes[recipe].plugin == plugin:\n                        return self.recipes[recipe]\n                    else:\n                        return None\n                else:\n                    return None\n        else:\n            if recipe is None:\n                return self.recipes\n            else:\n                if recipe in self.recipes.keys():\n                    return self.recipes[recipe]\n                else:\n                    return None",
    "docstring": "Get one or more recipes.\n\n        :param recipe: Name of the recipe\n        :type recipe: str\n        :param plugin: Plugin object, under which the recipe was registered\n        :type plugin: GwBasePattern"
  },
  {
    "code": "def drawBezier(page, p1, p2, p3, p4, color=None, fill=None,\n               dashes=None, width=1, morph=None,\n               closePath=False, roundCap=False, overlay=True):\n    img = page.newShape()\n    Q = img.drawBezier(Point(p1), Point(p2), Point(p3), Point(p4))\n    img.finish(color=color, fill=fill, dashes=dashes, width=width,\n               roundCap=roundCap, morph=morph, closePath=closePath)\n    img.commit(overlay)\n    return Q",
    "docstring": "Draw a general cubic Bezier curve from p1 to p4 using control points p2 and p3."
  },
  {
    "code": "def read_git_commit_timestamp(repo_path=None):\n    repo = git.repo.base.Repo(path=repo_path, search_parent_directories=True)\n    head_commit = repo.head.commit\n    return head_commit.committed_datetime",
    "docstring": "Obtain the timestamp from the current head commit of a Git repository.\n\n    Parameters\n    ----------\n    repo_path : `str`, optional\n        Path to the Git repository. Leave as `None` to use the current working\n        directory.\n\n    Returns\n    -------\n    commit_timestamp : `datetime.datetime`\n        The datetime of the head commit."
  },
  {
    "code": "def _get_meta(self, row, col):\n        if self.meta is None:\n            logging.error(\"unable to get meta: empty section\")\n            return {}\n        if not row in self._get_row_hdrs() or\\\n            not col in self._get_col_hdrs():\n            logging.error(\"unable to get meta: cell [%s,%s] does not exist\"\n                          % (row, col))\n            return {}\n        meta_str = self.meta[col][self.irt[row]]\n        try:\n            meta = ast.literal_eval(meta_str)\n            if isinstance(meta, dict):\n                return meta\n        except (SyntaxError, ValueError), e:\n            logging.error(\"unable to parse meta string - %s: %s\"\n                          % (meta_str, e))\n        return {}",
    "docstring": "Get metadata for a particular cell"
  },
  {
    "code": "def extract_lzma(path):\n    tlfile = pathlib.Path(path)\n    with tlfile.open(\"rb\") as td:\n        data = lzma.decompress(td.read())\n    fd, tmpname = tempfile.mkstemp(prefix=\"odt_ex_\", suffix=\".tar\")\n    with open(fd, \"wb\") as fo:\n        fo.write(data)\n    return tmpname",
    "docstring": "Extract an lzma file and return the temporary file name"
  },
  {
    "code": "def in_same_box(self, a, b):\n        assert a in self.micro_indices\n        assert b in self.micro_indices\n        for part in self.partition:\n            if a in part and b in part:\n                return True\n        return False",
    "docstring": "Return ``True`` if nodes ``a`` and ``b``` are in the same box."
  },
  {
    "code": "def connect_mysql(host, port, user, password, database):\n    return pymysql.connect(\n        host=host, port=port,\n        user=user, passwd=password,\n        db=database\n    )",
    "docstring": "Connect to MySQL with retries."
  },
  {
    "code": "def as_categorical(self):\n        if len(self.shape) > 1:\n            raise ValueError(\"Can't convert a 2D array to a categorical.\")\n        with ignore_pandas_nan_categorical_warning():\n            return pd.Categorical.from_codes(\n                self.as_int_array(),\n                self.categories.copy(),\n                ordered=False,\n            )",
    "docstring": "Coerce self into a pandas categorical.\n\n        This is only defined on 1D arrays, since that's all pandas supports."
  },
  {
    "code": "def _identify_os(self, msg):\n        ret = []\n        for dev_os, data in self.compiled_prefixes.items():\n            log.debug('Matching under %s', dev_os)\n            msg_dict = self._identify_prefix(msg, data)\n            if msg_dict:\n                log.debug('Adding %s to list of matched OS', dev_os)\n                ret.append((dev_os, msg_dict))\n            else:\n                log.debug('No match found for %s', dev_os)\n        if not ret:\n            log.debug('Not matched any OS, returning original log')\n            msg_dict = {'message': msg}\n            ret.append((None, msg_dict))\n        return ret",
    "docstring": "Using the prefix of the syslog message,\n        we are able to identify the operating system and then continue parsing."
  },
  {
    "code": "def as_dict(self):\n        data = super(BaseEmail, self).as_dict()\n        data[\"Headers\"] = [{\"Name\": name, \"Value\": value} for name, value in data[\"Headers\"].items()]\n        for field in (\"To\", \"Cc\", \"Bcc\"):\n            if field in data:\n                data[field] = list_to_csv(data[field])\n        data[\"Attachments\"] = [prepare_attachments(attachment) for attachment in data[\"Attachments\"]]\n        return data",
    "docstring": "Additionally encodes headers.\n\n        :return:"
  },
  {
    "code": "def _to_linear(M, N, L, q):\n    \"Converts a qubit in chimera coordinates to its linear index.\"\n    (x, y, u, k) = q\n    return 2 * L * N * x + 2 * L * y + L * u + k",
    "docstring": "Converts a qubit in chimera coordinates to its linear index."
  },
  {
    "code": "def calculateRange(self):\n        if not self.autoRangeCti or not self.autoRangeCti.configValue:\n            return (self.rangeMinCti.data, self.rangeMaxCti.data)\n        else:\n            rangeFunction = self._rangeFunctions[self.autoRangeMethod]\n            return rangeFunction()",
    "docstring": "Calculates the range depending on the config settings."
  },
  {
    "code": "def maybe_coroutine(decide):\n    def _maybe_coroutine(f):\n        @functools.wraps(f)\n        def __maybe_coroutine(*args, **kwargs):\n            if decide(*args, **kwargs):\n                return coroutine(f)(*args, **kwargs)\n            else:\n                return no_coroutine(f)(*args, **kwargs)\n        return __maybe_coroutine\n    return _maybe_coroutine",
    "docstring": "Either be a coroutine or not.\n\n    Use as a decorator:\n    @maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))\n    def foo(maybeAPromise):\n        result = yield maybeAPromise\n        print(\"hello\")\n        return result\n\n    The function passed should be a generator yielding either only Promises or whatever\n    you feel like.\n    The decide parameter must be a function which gets called with the same parameters as\n    the function to decide whether this is a coroutine or not.\n    Using this it is possible to either make the function a coroutine or not based on a\n    parameter to the function call.\n    Let's explain the example above:\n\n    # If the maybeAPromise is an instance of Promise,\n    # we want the foo function to act as a coroutine.\n    # If the maybeAPromise is not an instance of Promise,\n    # we want the foo function to act like any other normal synchronous function.\n    @maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))\n    def foo(maybeAPromise):\n        # If isinstance(maybeAPromise, Promise), foo behaves like a coroutine,\n        # thus maybeAPromise will get resolved asynchronously and the result will be\n        # pushed back here.\n        # Otherwise, foo behaves like no_coroutine,\n        # just pushing the exact value of maybeAPromise back into the generator.\n        result = yield maybeAPromise\n        print(\"hello\")\n        return result"
  },
  {
    "code": "def reset(self):\n        if self.__row_number > self.__sample_size:\n            self.__parser.reset()\n            self.__extract_sample()\n            self.__extract_headers()\n        self.__row_number = 0",
    "docstring": "Resets the stream pointer to the beginning of the file."
  },
  {
    "code": "def choose(msg, items, attr):\n    if len(items) == 1:\n        return items[0]\n    print()\n    for index, i in enumerate(items):\n        name = attr(i) if callable(attr) else getattr(i, attr)\n        print('  %s: %s' % (index, name))\n    print()\n    while True:\n        try:\n            inp = input('%s: ' % msg)\n            if any(s in inp for s in (':', '::', '-')):\n                idx = slice(*map(lambda x: int(x.strip()) if x.strip() else None, inp.split(':')))\n                return items[idx]\n            else:\n                return items[int(inp)]\n        except (ValueError, IndexError):\n            pass",
    "docstring": "Command line helper to display a list of choices, asking the\n        user to choose one of the options."
  },
  {
    "code": "def ds_geom(ds, t_srs=None):\n    gt = ds.GetGeoTransform()\n    ds_srs = get_ds_srs(ds)\n    if t_srs is None:\n        t_srs = ds_srs\n    ns = ds.RasterXSize\n    nl = ds.RasterYSize\n    x = np.array([0, ns, ns, 0, 0], dtype=float)\n    y = np.array([0, 0, nl, nl, 0], dtype=float)\n    x -= 0.5\n    y -= 0.5\n    mx, my = pixelToMap(x, y, gt)\n    geom_wkt = 'POLYGON(({0}))'.format(', '.join(['{0} {1}'.format(*a) for a in zip(mx,my)]))\n    geom = ogr.CreateGeometryFromWkt(geom_wkt)\n    geom.AssignSpatialReference(ds_srs)\n    if not ds_srs.IsSame(t_srs):\n        geom_transform(geom, t_srs)\n    return geom",
    "docstring": "Return dataset bbox envelope as geom"
  },
  {
    "code": "def get_result(self, *, block=False, timeout=None):\n        return self.messages[-1].get_result(block=block, timeout=timeout)",
    "docstring": "Get the result of this pipeline.\n\n        Pipeline results are represented by the result of the last\n        message in the chain.\n\n        Parameters:\n          block(bool): Whether or not to block until a result is set.\n          timeout(int): The maximum amount of time, in ms, to wait for\n            a result when block is True.  Defaults to 10 seconds.\n\n        Raises:\n          ResultMissing: When block is False and the result isn't set.\n          ResultTimeout: When waiting for a result times out.\n\n        Returns:\n          object: The result."
  },
  {
    "code": "def _endReq(self, key, result=None, success=True):\n        future = self._futures.pop(key, None)\n        self._reqId2Contract.pop(key, None)\n        if future:\n            if result is None:\n                result = self._results.pop(key, [])\n            if not future.done():\n                if success:\n                    future.set_result(result)\n                else:\n                    future.set_exception(result)",
    "docstring": "Finish the future of corresponding key with the given result.\n        If no result is given then it will be popped of the general results."
  },
  {
    "code": "def reorder(args):\n    import csv\n    p = OptionParser(reorder.__doc__)\n    p.set_sep()\n    opts, args = p.parse_args(args)\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n    tabfile, order = args\n    sep = opts.sep\n    order = [int(x) - 1 for x in order.split(\",\")]\n    reader = csv.reader(must_open(tabfile), delimiter=sep)\n    writer = csv.writer(sys.stdout, delimiter=sep)\n    for row in reader:\n        newrow = [row[x] for x in order]\n        writer.writerow(newrow)",
    "docstring": "%prog reorder tabfile 1,2,4,3 > newtabfile\n\n    Reorder columns in tab-delimited files. The above syntax will print out a\n    new file with col-1,2,4,3 from the old file."
  },
  {
    "code": "def delete(self, obj):\n        obj = self.api.get_object(getattr(obj, 'id', obj))\n        obj.delete()\n        self.remove(obj.id)",
    "docstring": "Delete an object in CDSTAR and remove it from the catalog.\n\n        :param obj: An object ID or an Object instance."
  },
  {
    "code": "def call(self, callname, arguments=None):\n        action = getattr(self.api, callname, None)\n        if action is None:\n            try:\n                action = self.api.ENDPOINT_OVERRIDES.get(callname, None)\n            except AttributeError:\n                action = callname\n        if not callable(action):\n            request = self._generate_request(action, arguments)\n            if action is None:\n                return self._generate_result(\n                    callname, self.api.call(*call_args(callname, arguments)))\n            return self._generate_result(\n                callname, self.api.call(*call_args(action, arguments)))\n        request = self._generate_request(callname, arguments)\n        return self._generate_result(callname, action(request))",
    "docstring": "Executed on each scheduled iteration"
  },
  {
    "code": "def metrics(self, raw=False):\n        if raw:\n            return self._metrics.metrics.copy()\n        metrics = {}\n        for k, v in six.iteritems(self._metrics.metrics.copy()):\n            if k.group not in metrics:\n                metrics[k.group] = {}\n            if k.name not in metrics[k.group]:\n                metrics[k.group][k.name] = {}\n            metrics[k.group][k.name] = v.value()\n        return metrics",
    "docstring": "Get metrics on producer performance.\n\n        This is ported from the Java Producer, for details see:\n        https://kafka.apache.org/documentation/#producer_monitoring\n\n        Warning:\n            This is an unstable interface. It may change in future\n            releases without warning."
  },
  {
    "code": "def map_size(self, key):\n        rv = self.get(key)\n        return len(rv.value)",
    "docstring": "Get the number of items in the map.\n\n        :param str key: The document ID of the map\n        :return int: The number of items in the map\n        :raise: :cb_exc:`NotFoundError` if the document does not exist.\n\n        .. seealso:: :meth:`map_add`"
  },
  {
    "code": "def serialize(data):\n    return rapidjson.dumps(data, skipkeys=False, ensure_ascii=False,\n                           sort_keys=True)",
    "docstring": "Serialize a dict into a JSON formatted string.\n\n        This function enforces rules like the separator and order of keys.\n        This ensures that all dicts are serialized in the same way.\n\n        This is specially important for hashing data. We need to make sure that\n        everyone serializes their data in the same way so that we do not have\n        hash mismatches for the same structure due to serialization\n        differences.\n\n        Args:\n            data (dict): dict to serialize\n\n        Returns:\n            str: JSON formatted string"
  },
  {
    "code": "def trim_wav_pydub(in_path: Path, out_path: Path,\n                start_time: int, end_time: int) -> None:\n    logger.info(\n        \"Using pydub/ffmpeg to create {} from {}\".format(out_path, in_path) +\n        \" using a start_time of {} and an end_time of {}\".format(start_time,\n                                                                 end_time))\n    if out_path.is_file():\n        return\n    in_ext = in_path.suffix[1:]\n    out_ext = out_path.suffix[1:]\n    audio = AudioSegment.from_file(str(in_path), in_ext)\n    trimmed = audio[start_time:end_time]\n    trimmed.export(str(out_path), format=out_ext,\n                   parameters=[\"-ac\", \"1\", \"-ar\", \"16000\"])",
    "docstring": "Crops the wav file."
  },
  {
    "code": "def analyzer_api(url):\n    response.content_type = JSON_MIME\n    ri = get_cached_or_new(url)\n    try:\n        if ri.is_old():\n            logger.info(\"Running the analysis.\")\n            ri = get_cached_or_new(url, new=True)\n            ri.paralel_processing()\n    except (requests.exceptions.Timeout, requests.ConnectionError) as e:\n        error_msg =\n        error_msg = error_msg.format(\n            url=url,\n            timeout=REQUEST_TIMEOUT,\n            message=str(e.message)\n        )\n        logger.error(error_msg)\n        return {\n            \"status\": False,\n            \"log\": \"\",\n            \"error\": error_msg,\n        }\n    except Exception as e:\n        error_msg = str(e.message) + \"\\n\" + traceback.format_exc().strip()\n        logger.error(error_msg)\n        return {\n            \"status\": False,\n            \"log\": \"ri.get_log()\",\n            \"error\": error_msg,\n        }\n    return {\n        \"status\": True,\n        \"body\": ri.to_dict(),\n        \"log\": \"ri.get_log()\",\n    }",
    "docstring": "Analyze given `url` and return output as JSON."
  },
  {
    "code": "def shape_offset_y(self):\n        min_y = self._start_y\n        for drawing_operation in self:\n            if hasattr(drawing_operation, 'y'):\n                min_y = min(min_y, drawing_operation.y)\n        return min_y",
    "docstring": "Return y distance of shape origin from local coordinate origin.\n\n        The returned integer represents the topmost extent of the freeform\n        shape, in local coordinates. Note that the bounding box of the shape\n        need not start at the local origin."
  },
  {
    "code": "def list(self, id=None):\n        args = {'id': id}\n        self._job_chk.check(args)\n        return self._client.json('job.list', args)",
    "docstring": "List all running jobs\n\n        :param id: optional ID for the job to list"
  },
  {
    "code": "def get_text(self):\n        self._load_raw_content()\n        if self._text is None:\n            assert self._raw_content is not None\n            ret_cont = self._raw_content\n            if self.compressed:\n                ret_cont = zlib.decompress(ret_cont, zlib.MAX_WBITS+16)\n            if self.encoded:\n                ret_cont = ret_cont.decode('utf-8')\n            self._text = ret_cont\n        assert self._text is not None\n        return self._text",
    "docstring": "Get the loaded, decompressed, and decoded text of this content."
  },
  {
    "code": "def _fmtos(self):\n        plotters = self.plotters\n        if len(plotters) == 0:\n            return {}\n        p0 = plotters[0]\n        if len(plotters) == 1:\n            return p0._fmtos\n        return (getattr(p0, key) for key in set(p0).intersection(\n            *map(set, plotters[1:])))",
    "docstring": "An iterator over formatoption objects\n\n        Contains only the formatoption whose keys are in all plotters in this\n        list"
  },
  {
    "code": "def take_bug_reports(ads, test_name, begin_time, destination=None):\n    begin_time = mobly_logger.normalize_log_line_timestamp(str(begin_time))\n    def take_br(test_name, begin_time, ad, destination):\n        ad.take_bug_report(test_name, begin_time, destination=destination)\n    args = [(test_name, begin_time, ad, destination) for ad in ads]\n    utils.concurrent_exec(take_br, args)",
    "docstring": "Takes bug reports on a list of android devices.\n\n    If you want to take a bug report, call this function with a list of\n    android_device objects in on_fail. But reports will be taken on all the\n    devices in the list concurrently. Bug report takes a relative long\n    time to take, so use this cautiously.\n\n    Args:\n        ads: A list of AndroidDevice instances.\n        test_name: Name of the test method that triggered this bug report.\n        begin_time: timestamp taken when the test started, can be either\n            string or int.\n        destination: string, path to the directory where the bugreport\n            should be saved."
  },
  {
    "code": "def _dlog(self, msg, indent_increase=0):\n        self._log.debug(\"interp\", msg, indent_increase, filename=self._orig_filename, coord=self._coord)",
    "docstring": "log the message to the log"
  },
  {
    "code": "def scoped_format(txt, **objects):\n    pretty = objects.pop(\"pretty\", RecursiveAttribute.format_pretty)\n    expand = objects.pop(\"expand\", RecursiveAttribute.format_expand)\n    attr = RecursiveAttribute(objects, read_only=True)\n    formatter = scoped_formatter(**objects)\n    return formatter.format(txt, pretty=pretty, expand=expand)",
    "docstring": "Format a string with respect to a set of objects' attributes.\n\n    Example:\n\n        >>> Class Foo(object):\n        >>>     def __init__(self):\n        >>>         self.name = \"Dave\"\n        >>> print scoped_format(\"hello {foo.name}\", foo=Foo())\n        hello Dave\n\n    Args:\n        objects (dict): Dict of objects to format with. If a value is a dict,\n            its values, and any further neted dicts, will also format with dot\n            notation.\n        pretty (bool): See `ObjectStringFormatter`.\n        expand (bool): See `ObjectStringFormatter`."
  },
  {
    "code": "def _update_callsafety(self, response):\n        if self.ratelimit is not None:\n            self.callsafety['lastcalltime'] = time()\n            self.callsafety['lastlimitremaining'] = int(response.headers.get('X-Rate-Limit-Remaining', 0))",
    "docstring": "Update the callsafety data structure"
  },
  {
    "code": "def append_logs_to_result_object(result_obj, result):\n    logs = result.has_logs()\n    result_obj[\"exec\"][\"logs\"] = []\n    if logs and result.logfiles:\n        for log in logs:\n            typ = None\n            parts = log.split(os.sep)\n            if \"bench\" in parts[len(parts) - 1]:\n                typ = \"framework\"\n            if typ is not None:\n                name = parts[len(parts) - 1]\n                try:\n                    with open(log, \"r\") as file_name:\n                        data = file_name.read()\n                    dic = {\"data\": data, \"name\": name, \"from\": typ}\n                    result_obj[\"exec\"][\"logs\"].append(dic)\n                except OSError:\n                    pass\n            else:\n                continue",
    "docstring": "Append log files to cloud result object from Result.\n\n    :param result_obj: Target result object\n    :param result: Result\n    :return: Nothing, modifies result_obj in place."
  },
  {
    "code": "def load_manifests(self):\n        for path in self.plugin_paths:\n            for item in os.listdir(path):\n                item_path = os.path.join(path, item)\n                if os.path.isdir(item_path):\n                    self.load_manifest(item_path)",
    "docstring": "Loads all plugin manifests on the plugin path"
  },
  {
    "code": "def _get_YYTfactor(self, Y):\n        N, D = Y.shape\n        if (N>=D):\n            return Y.view(np.ndarray)\n        else:\n            return jitchol(tdot(Y))",
    "docstring": "find a matrix L which satisfies LLT = YYT.\n\n        Note that L may have fewer columns than Y."
  },
  {
    "code": "def setup(options):\n    sys.path.insert(0, options.gae_lib_path)\n    from dev_appserver import fix_sys_path\n    fix_sys_path()",
    "docstring": "Grabs the gae_lib_path from the options and inserts it into the first\n    index of the sys.path. Then calls GAE's fix_sys_path to get all the proper\n    GAE paths included.\n\n    :param options:"
  },
  {
    "code": "def build_attachment2():\n    attachment = Attachment()\n    attachment.content = \"BwdW\"\n    attachment.type = \"image/png\"\n    attachment.filename = \"banner.png\"\n    attachment.disposition = \"inline\"\n    attachment.content_id = \"Banner\"\n    return attachment",
    "docstring": "Build attachment mock."
  },
  {
    "code": "def update(self):\n        response = requests.get(self.update_url, timeout=timeout)\n        match = ip_pattern.search(response.content)\n        if not match:\n            raise ApiError(\"Couldn't parse the server's response\",\n                    response.content)\n        self.ip = match.group(0)",
    "docstring": "Updates remote DNS record by requesting its special endpoint URL"
  },
  {
    "code": "def fib(n):\n    assert n > 0\n    a, b = 1, 1\n    for i in range(n - 1):\n        a, b = b, a + b\n    return a",
    "docstring": "Fibonacci example function\n\n    Args:\n      n (int): integer\n\n    Returns:\n      int: n-th Fibonacci number"
  },
  {
    "code": "def _download_wrapper(self, url, *args, **kwargs):\n        try:\n            return url, self._file_downloader.download(url, *args, **kwargs)\n        except Exception as e:\n            logging.error(\"AbstractDownloader: %s\", traceback.format_exc())\n            return url, e",
    "docstring": "Actual download call. Calls the underlying file downloader,\n        catches all exceptions and returns the result."
  },
  {
    "code": "def username(self):\n        token = self.session.params.get('access_token')\n        if not token:\n            raise errors.TokenError(\n                \"session does not have a valid access_token param\")\n        data = token.split('.')[1]\n        data = data.replace('-', '+').replace('_', '/') + \"===\"\n        try:\n            return json.loads(base64.b64decode(data).decode('utf-8'))['u']\n        except (ValueError, KeyError):\n            raise errors.TokenError(\n                \"access_token does not contain username\")",
    "docstring": "The username in the service's access token\n\n        Returns\n        -------\n        str"
  },
  {
    "code": "def _freebayes_custom(in_file, ref_file, data):\n    if vcfutils.get_paired_phenotype(data):\n        return None\n    config = data[\"config\"]\n    bv_ver = programs.get_version(\"bcbio_variation\", config=config)\n    if LooseVersion(bv_ver) < LooseVersion(\"0.1.1\"):\n        return None\n    out_file = \"%s-filter%s\" % os.path.splitext(in_file)\n    if not utils.file_exists(out_file):\n        tmp_dir = utils.safe_makedir(os.path.join(os.path.dirname(in_file), \"tmp\"))\n        resources = config_utils.get_resources(\"bcbio_variation\", config)\n        jvm_opts = resources.get(\"jvm_opts\", [\"-Xms750m\", \"-Xmx2g\"])\n        java_args = [\"-Djava.io.tmpdir=%s\" % tmp_dir]\n        cmd = [\"bcbio-variation\"] + jvm_opts + java_args + \\\n              [\"variant-filter\", \"freebayes\", in_file, ref_file]\n        do.run(cmd, \"Custom FreeBayes filtering using bcbio.variation\")\n    return out_file",
    "docstring": "Custom FreeBayes filtering using bcbio.variation, tuned to human NA12878 results.\n\n    Experimental: for testing new methods."
  },
  {
    "code": "def find_next(self):\r\n        state = self.find(changed=False, forward=True, rehighlight=False,\r\n                          multiline_replace_check=False)\r\n        self.editor.setFocus()\r\n        self.search_text.add_current_text()\r\n        return state",
    "docstring": "Find next occurrence"
  },
  {
    "code": "def upload(self, file_path, timeout=-1):\n        return self._client.upload(file_path, timeout=timeout)",
    "docstring": "Upload an SPP ISO image file or a hotfix file to the appliance.\n        The API supports upload of one hotfix at a time into the system.\n        For the successful upload of a hotfix, ensure its original name and extension are not altered.\n\n        Args:\n            file_path: Full path to firmware.\n            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n                in OneView; it just stops waiting for its completion.\n\n        Returns:\n          dict: Information about the updated firmware bundle."
  },
  {
    "code": "def readBatchTupleQuotes(self, symbols, start, end):\r\n        if end is None:\r\n            end=sys.maxint\r\n        ret={}\r\n        session=self.getReadSession()()\r\n        try:\r\n            symbolChunks=splitListEqually(symbols, 100)\r\n            for chunk in symbolChunks:\r\n                rows=session.query(Quote.symbol, Quote.time, Quote.close, Quote.volume,\r\n                                     Quote.low, Quote.high).filter(and_(Quote.symbol.in_(chunk),\r\n                                                                              Quote.time >= int(start),\r\n                                                                              Quote.time < int(end)))\r\n                for row in rows:\r\n                    if row.time not in ret:\r\n                        ret[row.time]={}\r\n                    ret[row.time][row.symbol]=self.__sqlToTupleQuote(row)\r\n        finally:\r\n            self.getReadSession().remove()\r\n        return ret",
    "docstring": "read batch quotes as tuple to save memory"
  },
  {
    "code": "def update(self, old, new):\n        i = self.rank[old]\n        del self.rank[old]\n        self.heap[i] = new\n        self.rank[new] = i\n        if old < new:\n            self.down(i)\n        else:\n            self.up(i)",
    "docstring": "Replace an element in the heap"
  },
  {
    "code": "def asset_create(self, name, items, tag='', description='', atype='static'):\n        data = {\n            'name': name,\n            'description': description,\n            'type': atype,\n            'tags': tag\n        }\n        if atype == 'static':\n            data['definedIPs'] = ','.join(items)\n        if atype == 'dns':\n            data['type'] = 'dnsname'\n            data['definedDNSNames'] = ' '.join(items)\n        return self.raw_query('asset', 'add', data=data)",
    "docstring": "asset_create_static name, ips, tags, description\n        Create a new asset list with the defined information.\n\n        UN-DOCUMENTED CALL: This function is not considered stable.\n\n        :param name: asset list name (must be unique)\n        :type name: string\n        :param items: list of IP Addresses, CIDR, and Network Ranges\n        :type items: list\n        :param tag: The tag associate to the asset list\n        :type tag: string\n        :param description: The Asset List description\n        :type description: string"
  },
  {
    "code": "def listen_until_return(self, *temporary_handlers, timeout=0):\n        start = time.time()\n        while timeout == 0 or time.time() - start < timeout:\n            res = self.listen(*temporary_handlers)\n            if res is not None:\n                return res",
    "docstring": "Calls listen repeatedly until listen returns something else than None.\n        Then returns listen's result. If timeout is not zero listen_until_return\n        stops after timeout seconds and returns None."
  },
  {
    "code": "def _getsolution(self, config, section, **kwargs):\n        if section not in config:\n            raise ValueError('Section [{}] not found in [{}]'.format(section, ', '.join(config.sections())))\n        s = VSGSolution(**kwargs)\n        s.Name = config.get(section, 'name', fallback=s.Name)\n        s.FileName = os.path.normpath(config.get(section, 'filename', fallback=s.FileName))\n        s.VSVersion = config.getfloat(section, 'visual_studio_version', fallback=s.VSVersion)\n        if not s.VSVersion:\n            raise ValueError('Solution section [%s] requires a value for Visual Studio Version (visual_studio_version)' % section)\n        project_sections = config.getlist(section, 'projects', fallback=[])\n        for project_section in project_sections:\n            project = self._getproject(config, project_section, VSVersion=s.VSVersion)\n            s.Projects.append(project)\n        return s",
    "docstring": "Creates a VSG solution from a configparser instance.\n\n        :param object config: The instance of the configparser class\n        :param str section: The section name to read.\n        :param kwargs:  List of additional keyworded arguments to be passed into the VSGSolution.\n        :return: A valid VSGSolution instance if succesful; None otherwise."
  },
  {
    "code": "async def connect(self):\n        self.tls_context = None\n        if self.tls:\n            self.tls_context = self.create_tls_context()\n        (self.reader, self.writer) = await asyncio.open_connection(\n            host=self.hostname,\n            port=self.port,\n            local_addr=self.source_address,\n            ssl=self.tls_context,\n            loop=self.eventloop\n        )",
    "docstring": "Connect to target."
  },
  {
    "code": "def pkgdb(opts):\n    return LazyLoader(\n        _module_dirs(\n            opts,\n            'pkgdb',\n            base_path=os.path.join(SALT_BASE_PATH, 'spm')\n        ),\n        opts,\n        tag='pkgdb'\n    )",
    "docstring": "Return modules for SPM's package database\n\n    .. versionadded:: 2015.8.0"
  },
  {
    "code": "async def close(self, code: int = 1006, reason: str = \"Connection closed\"):\n        if self._closed:\n            return\n        self._closed = True\n        if self._scope is not None:\n            await self._scope.cancel()\n        data = self._connection.send(CloseConnection(code=code, reason=reason))\n        await self._sock.send_all(data)\n        await self._sock.close()",
    "docstring": "Closes the websocket."
  },
  {
    "code": "def create_info(name, info_type, url=None, parent=None, id=None,\n                context=ctx_default, store=False):\n    id = str(uuid4()) if id is None else id\n    pubsub = _pubsub_key(id)\n    info = {'id': id,\n            'type': info_type,\n            'pubsub': pubsub,\n            'url': url,\n            'parent': parent,\n            'context': context,\n            'name': name,\n            'status': 'Queued' if info_type == 'job' else None,\n            'date_start': None,\n            'date_end': None,\n            'date_created': str(datetime.now()),\n            'result': None}\n    if store:\n        r_client.set(id, json_encode(info))\n        if parent is not None:\n            r_client.sadd(_children_key(parent), id)\n    return info",
    "docstring": "Return a group object"
  },
  {
    "code": "def preview(pid, record, template=None, **kwargs):\n    fileobj = current_previewer.record_file_factory(\n        pid, record, request.view_args.get(\n            'filename', request.args.get('filename', type=str))\n    )\n    if not fileobj:\n        abort(404)\n    try:\n        file_previewer = fileobj['previewer']\n    except KeyError:\n        file_previewer = None\n    fileobj = PreviewFile(pid, record, fileobj)\n    for plugin in current_previewer.iter_previewers(\n            previewers=[file_previewer] if file_previewer else None):\n        if plugin.can_preview(fileobj):\n            try:\n                return plugin.preview(fileobj)\n            except Exception:\n                current_app.logger.warning(\n                    ('Preview failed for {key}, in {pid_type}:{pid_value}'\n                     .format(key=fileobj.file.key,\n                             pid_type=fileobj.pid.pid_type,\n                             pid_value=fileobj.pid.pid_value)),\n                    exc_info=True)\n    return default.preview(fileobj)",
    "docstring": "Preview file for given record.\n\n    Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration:\n\n    .. code-block:: python\n\n        RECORDS_UI_ENDPOINTS = dict(\n            recid=dict(\n                # ...\n                route='/records/<pid_value/preview/<path:filename>',\n                view_imp='invenio_previewer.views.preview',\n                record_class='invenio_records_files.api:Record',\n            )\n        )"
  },
  {
    "code": "def _explode_raster(raster, band_names=[]):\n    if not band_names:\n        band_names = raster.band_names\n    else:\n        band_names = list(IndexedSet(raster.band_names).intersection(band_names))\n    return [_Raster(image=raster.bands_data([band_name]), band_names=[band_name]) for band_name in band_names]",
    "docstring": "Splits a raster into multiband rasters."
  },
  {
    "code": "def _GetMessage(self, event_object):\n    formatter_mediator = formatters_mediator.FormatterMediator()\n    result = ''\n    try:\n      result, _ = formatters_manager.FormattersManager.GetMessageStrings(\n          formatter_mediator, event_object)\n    except KeyError as exception:\n      logging.warning(\n          'Unable to correctly assemble event with error: {0!s}'.format(\n              exception))\n    return result",
    "docstring": "Returns a properly formatted message string.\n\n    Args:\n      event_object: the event object (instance od EventObject).\n\n    Returns:\n      A formatted message string."
  },
  {
    "code": "def break_bond(self, ind1, ind2, tol=0.2):\n        sites = self._sites\n        clusters = [[sites[ind1]], [sites[ind2]]]\n        sites = [site for i, site in enumerate(sites) if i not in (ind1, ind2)]\n        def belongs_to_cluster(site, cluster):\n            for test_site in cluster:\n                if CovalentBond.is_bonded(site, test_site, tol=tol):\n                    return True\n            return False\n        while len(sites) > 0:\n            unmatched = []\n            for site in sites:\n                for cluster in clusters:\n                    if belongs_to_cluster(site, cluster):\n                        cluster.append(site)\n                        break\n                else:\n                    unmatched.append(site)\n            if len(unmatched) == len(sites):\n                raise ValueError(\"Not all sites are matched!\")\n            sites = unmatched\n        return (self.__class__.from_sites(cluster)\n                for cluster in clusters)",
    "docstring": "Returns two molecules based on breaking the bond between atoms at index\n        ind1 and ind2.\n\n        Args:\n            ind1 (int): Index of first site.\n            ind2 (int): Index of second site.\n            tol (float): Relative tolerance to test. Basically, the code\n                checks if the distance between the sites is less than (1 +\n                tol) * typical bond distances. Defaults to 0.2, i.e.,\n                20% longer.\n\n        Returns:\n            Two Molecule objects representing the two clusters formed from\n            breaking the bond."
  },
  {
    "code": "def data_transforms_mnist(args, mnist_mean=None, mnist_std=None):\n    if mnist_mean is None:\n        mnist_mean = [0.5]\n    if mnist_std is None:\n        mnist_std = [0.5]\n    train_transform = transforms.Compose(\n        [\n            transforms.RandomCrop(28, padding=4),\n            transforms.RandomHorizontalFlip(),\n            transforms.ToTensor(),\n            transforms.Normalize(mnist_mean, mnist_std),\n        ]\n    )\n    if args.cutout:\n        train_transform.transforms.append(Cutout(args.cutout_length))\n    valid_transform = transforms.Compose(\n        [transforms.ToTensor(), transforms.Normalize(mnist_mean, mnist_std)]\n    )\n    return train_transform, valid_transform",
    "docstring": "data_transforms for mnist dataset"
  },
  {
    "code": "def lf (self):\n        old_r = self.cur_r\n        self.cursor_down()\n        if old_r == self.cur_r:\n            self.scroll_up ()\n            self.erase_line()",
    "docstring": "This moves the cursor down with scrolling."
  },
  {
    "code": "def value(self, raw_value):\n        try:\n            return decimal.Decimal(raw_value)\n        except decimal.InvalidOperation:\n            raise ValueError(\n                \"Could not parse '{}' value as decimal\".format(raw_value)\n            )",
    "docstring": "Decode param as decimal value."
  },
  {
    "code": "def total_scores_in(self, leaderboard_name):\n        return sum([leader[self.SCORE_KEY] for leader in self.all_leaders_from(self.leaderboard_name)])",
    "docstring": "Sum of scores for all members in the named leaderboard.\n\n        @param leaderboard_name Name of the leaderboard.\n        @return Sum of scores for all members in the named leaderboard."
  },
  {
    "code": "def getParentElementCustomFilter(self, filterFunc):\n        parentNode = self.parentNode\n        while parentNode:\n            if filterFunc(parentNode) is True:\n                return parentNode\n            parentNode = parentNode.parentNode\n        return None",
    "docstring": "getParentElementCustomFilter - Runs through parent on up to document root, returning the\n\n                                              first tag which filterFunc(tag) returns True.\n\n                @param filterFunc <function/lambda> - A function or lambda expression that should return \"True\" if the passed node matches criteria.\n\n                @return <AdvancedTag/None> - First match, or None\n\n\n                @see getFirstElementCustomFilter for matches against children"
  },
  {
    "code": "def _GenApiConfigCallback(args, api_func=GenApiConfig):\n  service_configs = api_func(args.service,\n                             hostname=args.hostname,\n                             application_path=args.application)\n  for api_name_version, config in service_configs.iteritems():\n    _WriteFile(args.output, api_name_version + '.api', config)",
    "docstring": "Generate an api file.\n\n  Args:\n    args: An argparse.Namespace object to extract parameters from.\n    api_func: A function that generates and returns an API configuration\n      for a list of services."
  },
  {
    "code": "def match(self, route):\n        _resource = trim_resource(self.resource)\n        self.method = self.method.lower()\n        resource_match = route.resource_regex.search(_resource)\n        if resource_match is None:\n            return None\n        params = resource_match.groupdict()\n        querystring = params.pop(\"querystring\", \"\")\n        setattr(self, \"param\", params)\n        setattr(self, \"query\", parse_querystring(querystring))\n        return copy.deepcopy(self)",
    "docstring": "Match input route and return new Message instance\n        with parsed content"
  },
  {
    "code": "def ExpandRecursiveGlobs(cls, path, path_separator):\n    glob_regex = r'(.*)?{0:s}\\*\\*(\\d{{1,2}})?({0:s})?$'.format(\n        re.escape(path_separator))\n    match = re.search(glob_regex, path)\n    if not match:\n      return [path]\n    skip_first = False\n    if match.group(3):\n      skip_first = True\n    if match.group(2):\n      iterations = int(match.group(2))\n    else:\n      iterations = cls._RECURSIVE_GLOB_LIMIT\n      logger.warning((\n          'Path \"{0:s}\" contains fully recursive glob, limiting to 10 '\n          'levels').format(path))\n    return cls.AppendPathEntries(\n        match.group(1), path_separator, iterations, skip_first)",
    "docstring": "Expands recursive like globs present in an artifact path.\n\n    If a path ends in '**', with up to two optional digits such as '**10',\n    the '**' will recursively match all files and zero or more directories\n    from the specified path. The optional digits indicate the recursion depth.\n    By default recursion depth is 10 directories.\n\n    If the glob is followed by the specified path segment separator, only\n    directories and subdirectories will be matched.\n\n    Args:\n      path (str): path to be expanded.\n      path_separator (str): path segment separator.\n\n    Returns:\n      list[str]: String path expanded for each glob."
  },
  {
    "code": "def _npiter(arr):\n    for a in np.nditer(arr, flags=[\"refs_ok\"]):\n        c = a.item()\n        if c is not None:\n            yield c",
    "docstring": "Wrapper for iterating numpy array"
  },
  {
    "code": "def set_hflip(self, val):\n        self.__horizontal_flip = val\n        for image in self.images:\n            image.h_flip = val",
    "docstring": "Flip all the images in the animation list horizontally."
  },
  {
    "code": "def fader(self, value: int):\n        self._fader = int(value) if 0 < value < 1024 else 0\n        self.outport.send(mido.Message('control_change', control=0,\n                                       value=self._fader >> 7))\n        self.outport.send(mido.Message('control_change', control=32,\n                                       value=self._fader & 0x7F))",
    "docstring": "Move the fader to a new position in the range 0 to 1023."
  },
  {
    "code": "def get_merge_rules(schema=None):\n    schema = schema or get_release_schema_url(get_tags()[-1])\n    if isinstance(schema, dict):\n        deref_schema = jsonref.JsonRef.replace_refs(schema)\n    else:\n        deref_schema = _get_merge_rules_from_url_or_path(schema)\n    return dict(_get_merge_rules(deref_schema['properties']))",
    "docstring": "Returns merge rules as key-value pairs, in which the key is a JSON path as a tuple, and the value is a list of\n    merge properties whose values are `true`."
  },
  {
    "code": "def download_models(self, uniprot_acc, outdir='', force_rerun=False):\n        downloaded = []\n        subset = self.get_models(uniprot_acc)\n        for entry in subset:\n            ident = '{}_{}_{}_{}'.format(uniprot_acc, entry['template'], entry['from'], entry['to'])\n            outfile = op.join(outdir, ident + '.pdb')\n            if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):\n                response = requests.get(entry['url'])\n                if response.status_code == 404:\n                    log.error('{}: 404 returned, no model available.'.format(ident))\n                else:\n                    with open(outfile, 'w') as f:\n                        f.write(response.text)\n                    log.debug('{}: downloaded homology model'.format(ident))\n                    downloaded.append(outfile)\n            else:\n                downloaded.append(outfile)\n        return downloaded",
    "docstring": "Download all models available for a UniProt accession number.\n\n        Args:\n            uniprot_acc (str): UniProt ACC/ID\n            outdir (str): Path to output directory, uses working directory if not set\n            force_rerun (bool): Force a redownload the models if they already exist\n\n        Returns:\n            list: Paths to the downloaded models"
  },
  {
    "code": "def get_files(self, commit, paths, recursive=False):\n        filtered_file_infos = []\n        for path in paths:\n            fi = self.inspect_file(commit, path)\n            if fi.file_type == proto.FILE:\n                filtered_file_infos.append(fi)\n            else:\n                filtered_file_infos += self.list_file(commit, path, recursive=recursive)\n        filtered_paths = [fi.file.path for fi in filtered_file_infos if fi.file_type == proto.FILE]\n        return {path: b''.join(self.get_file(commit, path)) for path in filtered_paths}",
    "docstring": "Returns the contents of a list of files at a specific Commit as a\n        dictionary of file paths to data.\n\n        Params:\n        * commit: A tuple, string, or Commit object representing the commit.\n        * paths: A list of paths to retrieve.\n        * recursive: If True, will go into each directory in the list\n        recursively."
  },
  {
    "code": "def truncate_money(money: Money) -> Money:\n    amount = truncate_to(money.amount, money.currency)\n    return Money(amount, money.currency)",
    "docstring": "Truncates money amount to the number of decimals corresponding to the currency"
  },
  {
    "code": "def remove_selected(self, *args):\n        self.collapse_nested(self.selected)\n        self.remove(self.selected)",
    "docstring": "Remove the selected catalog - allow the passing of arbitrary\n        args so that buttons work. Also remove any nested catalogs."
  },
  {
    "code": "def remove_external_references(self):\n        for ex_ref_node in self.node.findall('externalReferences'):\n            self.node.remove(ex_ref_node)",
    "docstring": "Removes any external reference from the role"
  },
  {
    "code": "def add_partition(self, spec, location=None):\n        part_schema = self.partition_schema()\n        stmt = ddl.AddPartition(\n            self._qualified_name, spec, part_schema, location=location\n        )\n        return self._execute(stmt)",
    "docstring": "Add a new table partition, creating any new directories in HDFS if\n        necessary.\n\n        Partition parameters can be set in a single DDL statement, or you can\n        use alter_partition to set them after the fact.\n\n        Returns\n        -------\n        None (for now)"
  },
  {
    "code": "def write_command_line(self):\n        cmd = [\" \".join(sys.argv)]\n        try:\n            previous = self.attrs[\"cmd\"]\n            if isinstance(previous, str):\n                previous = [previous]\n            elif isinstance(previous, numpy.ndarray):\n                previous = previous.tolist()\n        except KeyError:\n            previous = []\n        self.attrs[\"cmd\"] = cmd + previous",
    "docstring": "Writes command line to attributes.\n\n        The command line is written to the file's ``attrs['cmd']``. If this\n        attribute already exists in the file (this can happen when resuming\n        from a checkpoint), ``attrs['cmd']`` will be a list storing the current\n        command line and all previous command lines."
  },
  {
    "code": "def encode_dataset(dataset, vocabulary):\n  def encode(features):\n    return {k: vocabulary.encode_tf(v) for k, v in features.items()}\n  return dataset.map(encode, num_parallel_calls=tf.data.experimental.AUTOTUNE)",
    "docstring": "Encode from strings to token ids.\n\n  Args:\n    dataset: a tf.data.Dataset with string values.\n    vocabulary: a mesh_tensorflow.transformer.Vocabulary\n  Returns:\n    a tf.data.Dataset with integer-vector values ending in EOS=1"
  },
  {
    "code": "def prune_indices(self, transforms=None):\n        if self.ndim >= 3:\n            return self._prune_3d_indices(transforms)\n        def prune_non_3d_indices(transforms):\n            row_margin = self._pruning_base(\n                hs_dims=transforms, axis=self.row_direction_axis\n            )\n            row_indices = self._margin_pruned_indices(\n                row_margin, self._inserted_dim_inds(transforms, 0), 0\n            )\n            if row_indices.ndim > 1:\n                row_indices = row_indices.all(axis=1)\n            if self.ndim == 1:\n                return [row_indices]\n            col_margin = self._pruning_base(\n                hs_dims=transforms, axis=self._col_direction_axis\n            )\n            col_indices = self._margin_pruned_indices(\n                col_margin, self._inserted_dim_inds(transforms, 1), 1\n            )\n            if col_indices.ndim > 1:\n                col_indices = col_indices.all(axis=0)\n            return [row_indices, col_indices]\n        return prune_non_3d_indices(transforms)",
    "docstring": "Return indices of pruned rows and columns as list.\n\n        The return value has one of three possible forms:\n\n        * a 1-element list of row indices (in case of 1D cube)\n        * 2-element list of row and col indices (in case of 2D cube)\n        * n-element list of tuples of 2 elements (if it's 3D cube).\n\n        For each case, the 2 elements are the ROW and COL indices of the\n        elements that need to be pruned. If it's a 3D cube, these indices are\n        calculated \"per slice\", that is NOT on the 0th dimension (as the 0th\n        dimension represents the slices)."
  },
  {
    "code": "def comment_stream(reddit_session, subreddit, limit=None, verbosity=1):\n    get_function = partial(reddit_session.get_comments,\n                           six.text_type(subreddit))\n    return _stream_generator(get_function, limit, verbosity)",
    "docstring": "Indefinitely yield new comments from the provided subreddit.\n\n    Comments are yielded from oldest to newest.\n\n    :param reddit_session: The reddit_session to make requests from. In all the\n        examples this is assigned to the variable ``r``.\n    :param subreddit: Either a subreddit object, or the name of a\n        subreddit. Use `all` to get the comment stream for all comments made to\n        reddit.\n    :param limit: The maximum number of comments to fetch in a single\n        iteration. When None, fetch all available comments (reddit limits this\n        to 1000 (or multiple of 1000 for multi-subreddits). If this number is\n        too small, comments may be missed.\n    :param verbosity: A number that controls the amount of output produced to\n        stderr. <= 0: no output; >= 1: output the total number of comments\n        processed and provide the short-term number of comments processed per\n        second; >= 2: output when additional delays are added in order to avoid\n        subsequent unexpected http errors. >= 3: output debugging information\n        regarding the comment stream. (Default: 1)"
  },
  {
    "code": "def unlock(self, key):\n        check_not_none(key, \"key can't be None\")\n        key_data = self._to_data(key)\n        return self._encode_invoke_on_key(map_unlock_codec, key_data, key=key_data, thread_id=thread_id(),\n                                          reference_id=self.reference_id_generator.get_and_increment())",
    "docstring": "Releases the lock for the specified key. It never blocks and returns immediately. If the current thread is the\n        holder of this lock, then the hold count is decremented. If the hold count is zero, then the lock is released.\n\n        :param key: (object), the key to lock."
  },
  {
    "code": "def zharkov_pel(v, temp, v0, e0, g, n, z, t_ref=300.,\n                three_r=3. * constants.R):\n    v_mol = vol_uc2mol(v, z)\n    x = v / v0\n    def f(t):\n        return three_r * n / 2. * e0 * np.power(x, g) * np.power(t, 2.) * \\\n            g / v_mol * 1.e-9\n    return f(temp) - f(t_ref)",
    "docstring": "calculate electronic contributions in pressure for the Zharkov equation\n    the equation can be found in Sokolova and Dorogokupets 2013\n\n    :param v: unit-cell volume in A^3\n    :param temp: temperature in K\n    :param v0: unit-cell volume in A^3 at 1 bar\n    :param e0: parameter in K-1 for the Zharkov equation\n    :param g: parameter for the Zharkov equation\n    :param n: number of atoms in a formula unit\n    :param z: number of formula unit in a unit cell\n    :param t_ref: reference temperature, 300 K\n    :param three_r: 3 times gas constant\n    :return: electronic contribution in GPa"
  },
  {
    "code": "def get_plugin_by_model(self, model_class):\n        self._import_plugins()\n        assert issubclass(model_class, ContentItem)\n        try:\n            name = self._name_for_model[model_class]\n        except KeyError:\n            raise PluginNotFound(\"No plugin found for model '{0}'.\".format(model_class.__name__))\n        return self.plugins[name]",
    "docstring": "Return the corresponding plugin for a given model.\n\n        You can also use the :attr:`ContentItem.plugin <fluent_contents.models.ContentItem.plugin>` property directly.\n        This is the low-level function that supports that feature."
  },
  {
    "code": "def set_logger_level(logger_name, log_level='error'):\n    logging.getLogger(logger_name).setLevel(\n        LOG_LEVELS.get(log_level.lower(), logging.ERROR)\n    )",
    "docstring": "Tweak a specific logger's logging level"
  },
  {
    "code": "def set_legend_position(self, legend_position):\n        if legend_position:\n            self.legend_position = quote(legend_position)\n        else:    \n            self.legend_position = None",
    "docstring": "Sets legend position. Default is 'r'.\n\n        b - At the bottom of the chart, legend entries in a horizontal row.\n        bv - At the bottom of the chart, legend entries in a vertical column.\n        t - At the top of the chart, legend entries in a horizontal row.\n        tv - At the top of the chart, legend entries in a vertical column.\n        r - To the right of the chart, legend entries in a vertical column.\n        l - To the left of the chart, legend entries in a vertical column."
  },
  {
    "code": "def elapsed(self):\n        if self.end is None:\n            return (self() - self.start) * self.factor\n        else:\n            return (self.end - self.start) * self.factor",
    "docstring": "Return the current elapsed time since start\n        If the `elapsed` property is called in the context manager scope,\n        the elapsed time bewteen start and property access is returned.\n        However, if it is accessed outside of the context manager scope,\n        it returns the elapsed time bewteen entering and exiting the scope.\n        The `elapsed` property can thus be accessed at different points within\n        the context manager scope, to time different parts of the block."
  },
  {
    "code": "def get(self, field):\n        if field in ('username', 'uuid', 'app_data'):\n            return self.data[field]\n        else:\n            return self.data.get('app_data', {})[field]",
    "docstring": "Returns the value of a user field.\n\n        :param str field:\n            The name of the user field.\n        :returns: str -- the value"
  },
  {
    "code": "def get_status(self):\n        if self.status is not None:\n            return self.status\n        if self.subsection == \"dmdSec\":\n            if self.older is None:\n                return \"original\"\n            else:\n                return \"updated\"\n        if self.subsection in (\"techMD\", \"rightsMD\"):\n            if self.newer is None:\n                return \"current\"\n            else:\n                return \"superseded\"\n        return None",
    "docstring": "Returns the STATUS when serializing.\n\n        Calculates based on the subsection type and if it's replacing anything.\n\n        :returns: None or the STATUS string."
  },
  {
    "code": "def dequeue(self) -> Tuple[int, TItem]:\n        if self._len == 0:\n            raise ValueError('BucketPriorityQueue is empty.')\n        while self._buckets and not self._buckets[0]:\n            self._buckets.pop(0)\n            self._offset += 1\n        item = self._buckets[0].pop(0)\n        priority = self._offset\n        self._len -= 1\n        if self._drop_set is not None:\n            self._drop_set.remove((priority, item))\n        return priority, item",
    "docstring": "Removes and returns an item from the priority queue.\n\n        Returns:\n            A tuple whose first element is the priority of the dequeued item\n            and whose second element is the dequeued item.\n\n        Raises:\n            ValueError:\n                The queue is empty."
  },
  {
    "code": "def print_num(num):\n    out('hex: 0x{0:08x}'.format(num))\n    out('dec:   {0:d}'.format(num))\n    out('oct: 0o{0:011o}'.format(num))\n    out('bin: 0b{0:032b}'.format(num))",
    "docstring": "Write a numeric result in various forms"
  },
  {
    "code": "def publish_scene_add(self, scene_id, animation_id, name, color, velocity, config):\n        self.sequence_number += 1\n        self.publisher.send_multipart(msgs.MessageBuilder.scene_add(self.sequence_number, scene_id, animation_id, name, color, velocity, config))\n        return self.sequence_number",
    "docstring": "publish added scene"
  },
  {
    "code": "def launch(self, callback_function=None):\n        self._check_registered()\n        self._socket_client.receiver_controller.launch_app(\n            self.supporting_app_id, callback_function=callback_function)",
    "docstring": "If set, launches app related to the controller."
  },
  {
    "code": "def diff(name, **kwargs):\n    ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}\n    ret['changes'] = __salt__['junos.diff'](**kwargs)\n    return ret",
    "docstring": "Gets the difference between the candidate and the current configuration.\n\n    .. code-block:: yaml\n\n            get the diff:\n              junos:\n                - diff\n                - id: 10\n\n    Parameters:\n      Optional\n        * id:\n          The rollback id value [0-49]. (default = 0)"
  },
  {
    "code": "def _names_to_bytes(names):\n    names = sorted(names)\n    names_bytes = json.dumps(names).encode('utf8')\n    return names_bytes",
    "docstring": "Reproducibly converts an iterable of strings to bytes\n\n    :param iter[str] names: An iterable of strings\n    :rtype: bytes"
  },
  {
    "code": "def set_user_password(name, passwd, **client_args):\n    if not user_exists(name, **client_args):\n        log.info('User \\'%s\\' does not exist', name)\n        return False\n    client = _client(**client_args)\n    client.set_user_password(name, passwd)\n    return True",
    "docstring": "Change password of a user.\n\n    name\n        Name of the user for whom to set the password.\n\n    passwd\n        New password of the user.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' influxdb.set_user_password <name> <password>"
  },
  {
    "code": "def create_knowledge_base(project_id, display_name):\n    import dialogflow_v2beta1 as dialogflow\n    client = dialogflow.KnowledgeBasesClient()\n    project_path = client.project_path(project_id)\n    knowledge_base = dialogflow.types.KnowledgeBase(\n        display_name=display_name)\n    response = client.create_knowledge_base(project_path, knowledge_base)\n    print('Knowledge Base created:\\n')\n    print('Display Name: {}\\n'.format(response.display_name))\n    print('Knowledge ID: {}\\n'.format(response.name))",
    "docstring": "Creates a Knowledge base.\n\n    Args:\n        project_id: The GCP project linked with the agent.\n        display_name: The display name of the Knowledge base."
  },
  {
    "code": "def get_axis_value_discrete(self, axis):\n\t\tif self.type != EventType.POINTER_AXIS:\n\t\t\traise AttributeError(_wrong_meth.format(self.type))\n\t\treturn self._libinput.libinput_event_pointer_get_axis_value_discrete(\n\t\t\tself._handle, axis)",
    "docstring": "Return the axis value in discrete steps for a given axis event.\n\n\t\tHow a value translates into a discrete step depends on the source.\n\t\tIf the source is :attr:`~libinput.constant.PointerAxisSource.WHEEL`,\n\t\tthe discrete value correspond to the number of physical mouse wheel\n\t\tclicks.\n\n\t\tIf the source is :attr:`~libinput.constant.PointerAxisSource.CONTINUOUS`\n\t\tor :attr:`~libinput.constant.PointerAxisSource.FINGER`, the discrete\n\t\tvalue is always 0.\n\n\t\tArgs:\n\t\t\taxis (~libinput.constant.PointerAxis): The axis who's value to get.\n\t\tReturns:\n\t\t\tfloat: The discrete value for the given event.\n\t\tRaises:\n\t\t\tAttributeError"
  },
  {
    "code": "def set_session(self, headers=None):\n        if headers is None:\n            headers = {\n                'User-Agent':\n                ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3)'\n                 ' AppleWebKit/537.36 (KHTML, like Gecko) '\n                 'Chrome/48.0.2564.116 Safari/537.36')\n            }\n        elif not isinstance(headers, dict):\n            raise TypeError('\"headers\" must be a dict object')\n        self.session = Session(self.proxy_pool)\n        self.session.headers.update(headers)",
    "docstring": "Init session with default or custom headers\n\n        Args:\n            headers: A dict of headers (default None, thus using the default\n                     header to init the session)"
  },
  {
    "code": "def event_return(events):\n    options = _get_options()\n    index = options['master_event_index']\n    doc_type = options['master_event_doc_type']\n    if options['index_date']:\n        index = '{0}-{1}'.format(index,\n            datetime.date.today().strftime('%Y.%m.%d'))\n    _ensure_index(index)\n    for event in events:\n        data = {\n            'tag': event.get('tag', ''),\n            'data': event.get('data', '')\n        }\n    ret = __salt__['elasticsearch.document_create'](index=index,\n                                                    doc_type=doc_type,\n                                                    id=uuid.uuid4(),\n                                                    body=salt.utils.json.dumps(data))",
    "docstring": "Return events to Elasticsearch\n\n    Requires that the `event_return` configuration be set in master config."
  },
  {
    "code": "def lemmatize(text, lowercase=True, remove_stopwords=True):\n    doc = nlp(text)\n    if lowercase and remove_stopwords:\n        lemmas = [t.lemma_.lower() for t in doc if not (t.is_stop or t.orth_.lower() in STOPWORDS)]\n    elif lowercase:\n        lemmas = [t.lemma_.lower() for t in doc]\n    elif remove_stopwords:\n        lemmas = [t.lemma_ for t in doc if not (t.is_stop or t.orth_.lower() in STOPWORDS)]\n    else:\n        lemmas = [t.lemma_ for t in doc]\n    return lemmas",
    "docstring": "Return the lemmas of the tokens in a text."
  },
  {
    "code": "def stop(self):\n        if self.original_attributes is not None:\n            termios.tcsetattr(\n                self.fd,\n                termios.TCSADRAIN,\n                self.original_attributes,\n            )",
    "docstring": "Restores the terminal attributes back to before setting raw mode.\n\n        If the raw terminal was not started, does nothing."
  },
  {
    "code": "def _compile_signature(self, iexec, call_name):\n        if iexec is not None:\n            summary = iexec.summary\n            if isinstance(iexec, Function):\n                summary = iexec.returns + \"| \" + iexec.summary\n            elif isinstance(iexec, Subroutine) and len(iexec.modifiers) > 0:\n                summary = \", \".join(iexec.modifiers) + \" | \" + iexec.summary\n            elif isinstance(iexec, Interface):\n                summary = iexec.describe()\n            else:\n                summary = iexec.summary\n            if iexec.parent is not None:\n                summary += \" | MODULE: {}\".format(iexec.module.name)\n            else:\n                summary += \" | BUILTIN\"\n            return dict(\n                params=[p.name for p in iexec.ordered_parameters],\n                index=0,\n                call_name=call_name,\n                description=summary,\n            )        \n        else:\n            return []",
    "docstring": "Compiles the signature for the specified executable and returns\n        as a dictionary."
  },
  {
    "code": "def get(self, key, bucket):\n        try:\n            return self._cache[bucket][key]\n        except (KeyError, TypeError):\n            return None",
    "docstring": "Get a cached item by key\n\n        If the cached item isn't found the return None."
  },
  {
    "code": "def rmse(params1, params2):\n    r\n    assert len(params1) == len(params2)\n    params1 = np.asarray(params1) - np.mean(params1)\n    params2 = np.asarray(params2) - np.mean(params2)\n    sqrt_n = math.sqrt(len(params1))\n    return np.linalg.norm(params1 - params2, ord=2) / sqrt_n",
    "docstring": "r\"\"\"Compute the root-mean-squared error between two models.\n\n    Parameters\n    ----------\n    params1 : array_like\n        Parameters of the first model.\n    params2 : array_like\n        Parameters of the second model.\n\n    Returns\n    -------\n    error : float\n        Root-mean-squared error."
  },
  {
    "code": "def by_readings(self, role_names=['', 'Author']):\n        if not spectator_apps.is_enabled('reading'):\n            raise ImproperlyConfigured(\"To use the CreatorManager.by_readings() method, 'spectator.reading' must by in INSTALLED_APPS.\")\n        qs = self.get_queryset()\n        qs = qs.filter(publication_roles__role_name__in=role_names) \\\n                .exclude(publications__reading__isnull=True) \\\n                .annotate(num_readings=Count('publications__reading')) \\\n                .order_by('-num_readings', 'name_sort')\n        return qs",
    "docstring": "The Creators who have been most-read, ordered by number of readings.\n\n        By default it will only include Creators whose role was left empty,\n        or is 'Author'.\n\n        Each Creator will have a `num_readings` attribute."
  },
  {
    "code": "def get_property_by_hash(self, property_hash: str) -> Optional[Property]:\n        return self.session.query(Property).filter(Property.sha512 == property_hash).one_or_none()",
    "docstring": "Get a property by its hash if it exists."
  },
  {
    "code": "def activate(self):\n        response = self._manager.activate(self.ID)\n        self._update(response[\"Bounce\"])\n        return response[\"Message\"]",
    "docstring": "Activates the bounce instance and updates it with the latest data.\n\n        :return: Activation status.\n        :rtype: `str`"
  },
  {
    "code": "def _create_date_slug(self):\n        if not self.pk:\n            d = utc_now()\n        elif self.published and self.published_on:\n            d = self.published_on\n        elif self.updated_on:\n            d = self.updated_on\n        self.date_slug = u\"{0}/{1}\".format(d.strftime(\"%Y/%m/%d\"), self.slug)",
    "docstring": "Prefixes the slug with the ``published_on`` date."
  },
  {
    "code": "def ExecuteRaw(self, position, command):\n    self.EnsureGdbPosition(position[0], None, None)\n    return gdb.execute(command, to_string=True)",
    "docstring": "Send a command string to gdb."
  },
  {
    "code": "def add_bases(cls, *bases):\n    assert inspect.isclass(cls), \"Expected class object\"\n    for mixin in bases:\n        assert inspect.isclass(mixin), \"Expected class object for bases\"\n    new_bases = (bases + cls.__bases__)\n    cls.__bases__ = new_bases",
    "docstring": "Add bases to class\n\n    >>> class Base(object): pass\n    >>> class A(Base): pass\n    >>> class B(Base): pass\n    >>> issubclass(A, B)\n    False\n    >>> add_bases(A, B)\n    >>> issubclass(A, B)\n    True"
  },
  {
    "code": "def __handle_events(self):\n        events = pygame.event.get()\n        for event in events:\n            if event.type == pygame.QUIT:\n                self.exit()",
    "docstring": "This is the place to put all event handeling."
  },
  {
    "code": "def transform_deprecated_concepts(rdf, cs):\n    deprecated_concepts = []\n    for conc in rdf.subjects(RDF.type, SKOSEXT.DeprecatedConcept):\n        rdf.add((conc, RDF.type, SKOS.Concept))\n        rdf.add((conc, OWL.deprecated, Literal(\"true\", datatype=XSD.boolean)))\n        deprecated_concepts.append(conc)\n    if len(deprecated_concepts) > 0:\n        ns = cs.replace(localname(cs), '')\n        dcs = create_concept_scheme(\n            rdf, ns, 'deprecatedconceptscheme')\n        logging.debug(\"creating deprecated concept scheme %s\", dcs)\n        for conc in deprecated_concepts:\n            rdf.add((conc, SKOS.inScheme, dcs))",
    "docstring": "Transform deprecated concepts so they are in their own concept\n    scheme."
  },
  {
    "code": "def register(self, mimetype):\n        def dec(func):\n            self._reg[mimetype] = func\n            return func\n        return dec",
    "docstring": "Register a function to handle a particular mimetype."
  },
  {
    "code": "def hook_outputs(modules:Collection[nn.Module], detach:bool=True, grad:bool=False)->Hooks:\n    \"Return `Hooks` that store activations of all `modules` in `self.stored`\"\n    return Hooks(modules, _hook_inner, detach=detach, is_forward=not grad)",
    "docstring": "Return `Hooks` that store activations of all `modules` in `self.stored`"
  },
  {
    "code": "def suspend(self):\n        vm_state = yield from self._get_vm_state()\n        if vm_state == \"running\":\n            yield from self._control_vm(\"pause\")\n            self.status = \"suspended\"\n            log.info(\"VirtualBox VM '{name}' [{id}] suspended\".format(name=self.name, id=self.id))\n        else:\n            log.warn(\"VirtualBox VM '{name}' [{id}] cannot be suspended, current state: {state}\".format(name=self.name,\n                                                                                                        id=self.id,\n                                                                                                        state=vm_state))",
    "docstring": "Suspends this VirtualBox VM."
  },
  {
    "code": "def update(self, name=None, email=None, blog=None, company=None,\n               location=None, hireable=False, bio=None):\n        user = {'name': name, 'email': email, 'blog': blog,\n                'company': company, 'location': location,\n                'hireable': hireable, 'bio': bio}\n        self._remove_none(user)\n        url = self._build_url('user')\n        json = self._json(self._patch(url, data=dumps(user)), 200)\n        if json:\n            self._update_(json)\n            return True\n        return False",
    "docstring": "If authenticated as this user, update the information with\n        the information provided in the parameters.\n\n        :param str name: e.g., 'John Smith', not login name\n        :param str email: e.g., 'john.smith@example.com'\n        :param str blog: e.g., 'http://www.example.com/jsmith/blog'\n        :param str company:\n        :param str location:\n        :param bool hireable: defaults to False\n        :param str bio: GitHub flavored markdown\n        :returns: bool"
  },
  {
    "code": "def decode_example(self, serialized_example):\n    data_fields, data_items_to_decoders = self.example_reading_spec()\n    data_fields[\"batch_prediction_key\"] = tf.FixedLenFeature([1], tf.int64, 0)\n    if data_items_to_decoders is None:\n      data_items_to_decoders = {\n          field: tf.contrib.slim.tfexample_decoder.Tensor(field)\n          for field in data_fields\n      }\n    decoder = tf.contrib.slim.tfexample_decoder.TFExampleDecoder(\n        data_fields, data_items_to_decoders)\n    decode_items = list(sorted(data_items_to_decoders))\n    decoded = decoder.decode(serialized_example, items=decode_items)\n    return dict(zip(decode_items, decoded))",
    "docstring": "Return a dict of Tensors from a serialized tensorflow.Example."
  },
  {
    "code": "def run_command(cmd, *args):\n    command = ' '.join((cmd, args))\n    p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)\n    stdout, stderr = p.communicate()\n    return p.retcode, stdout, stderr",
    "docstring": "Runs command on the system with given ``args``."
  },
  {
    "code": "def update_statistics(self, activityVectors):\n        Y = activityVectors\n        n = self.output_size\n        A = np.zeros((n, n))\n        batchSize = len(Y)\n        for y in Y:\n            active_units = np.where( y == 1 )[0]\n            for i in active_units:\n                for j in active_units:\n                    A[i,j] += 1.\n        A = A/batchSize\n        self.average_activity = self.exponential_moving_average(self.average_activity, A, self.smoothing_period)",
    "docstring": "Updates the variable that maintains exponential moving averages of \n        individual and pairwise unit activiy"
  },
  {
    "code": "def t_escaped_CARRIAGE_RETURN_CHAR(self, t):\n        r'\\x72'\n        t.lexer.pop_state()\n        t.value = unichr(0x000d)\n        return t",
    "docstring": "r'\\x72"
  },
  {
    "code": "def _split_url_string(query_string):\n        parameters = parse_qs(to_utf8(query_string), keep_blank_values=True)\n        for k, v in parameters.iteritems():\n            parameters[k] = urllib.unquote(v[0])\n        return parameters",
    "docstring": "Turns a `query_string` into a Python dictionary with unquoted values"
  },
  {
    "code": "def eeg_create_mne_events(onsets, conditions=None):\n    event_id = {}\n    if conditions is None:\n        conditions = [\"Event\"] * len(onsets)\n    if len(conditions) != len(onsets):\n        print(\"NeuroKit Warning: eeg_create_events(): conditions parameter of different length than onsets. Aborting.\")\n        return()\n    event_names = list(set(conditions))\n    event_index = list(range(len(event_names)))\n    for i in enumerate(event_names):\n        conditions = [event_index[i[0]] if x==i[1] else x for x in conditions]\n        event_id[i[1]] = event_index[i[0]]\n    events = np.array([onsets, [0]*len(onsets), conditions]).T\n    return(events, event_id)",
    "docstring": "Create MNE compatible events.\n\n    Parameters\n    ----------\n    onsets : list or array\n        Events onsets.\n    conditions : list\n        A list of equal length containing the stimuli types/conditions.\n\n\n    Returns\n    ----------\n    (events, event_id) : tuple\n        MNE-formated events and a dictionary with event's names.\n\n    Example\n    ----------\n    >>> import neurokit as nk\n    >>> events, event_id = nk.eeg_create_mne_events(events_onset, conditions)\n\n    Authors\n    ----------\n    - `Dominique Makowski <https://dominiquemakowski.github.io/>`_"
  },
  {
    "code": "def delete(self, table_id):\n        from google.api_core.exceptions import NotFound\n        if not self.exists(table_id):\n            raise NotFoundException(\"Table does not exist\")\n        table_ref = self.client.dataset(self.dataset_id).table(table_id)\n        try:\n            self.client.delete_table(table_ref)\n        except NotFound:\n            pass\n        except self.http_error as ex:\n            self.process_http_error(ex)",
    "docstring": "Delete a table in Google BigQuery\n\n        Parameters\n        ----------\n        table : str\n            Name of table to be deleted"
  },
  {
    "code": "def _list_queues():\n    queue_dir = __opts__['sqlite_queue_dir']\n    files = os.path.join(queue_dir, '*.db')\n    paths = glob.glob(files)\n    queues = [os.path.splitext(os.path.basename(item))[0] for item in paths]\n    return queues",
    "docstring": "Return a list of sqlite databases in the queue_dir"
  },
  {
    "code": "def disassemble(self, data, start_address=0):\n        return _opcodes.disassemble(self._ptr, data, start_address)",
    "docstring": "Return a list containing the virtual memory address, instruction length\n        and disassembly code for the given binary buffer."
  },
  {
    "code": "def get(self):\n        tasks = self._get_avaliable_tasks()\n        if not tasks:\n            return None\n        name, data = tasks[0]\n        self._client.kv.delete(name)\n        return data",
    "docstring": "Get a task from the queue."
  },
  {
    "code": "def open(self):\n        if self._is_open:\n            raise HIDException(\"Failed to open device: HIDDevice already open\")\n        path = self.path.encode('utf-8')\n        dev = hidapi.hid_open_path(path)\n        if dev:\n            self._is_open = True\n            self._device = dev\n        else:\n            raise HIDException(\"Failed to open device\")",
    "docstring": "Open the HID device for reading and writing."
  },
  {
    "code": "def _normalize_compare_config(self, diff):\n        ignore_strings = [\n            \"Contextual Config Diffs\",\n            \"No changes were found\",\n            \"ntp clock-period\",\n        ]\n        if self.auto_file_prompt:\n            ignore_strings.append(\"file prompt quiet\")\n        new_list = []\n        for line in diff.splitlines():\n            for ignore in ignore_strings:\n                if ignore in line:\n                    break\n            else:\n                new_list.append(line)\n        return \"\\n\".join(new_list)",
    "docstring": "Filter out strings that should not show up in the diff."
  },
  {
    "code": "def find_peakset(dataset, basecolumn=-1, method='', where=None):\n    peakset = []\n    where_i = None\n    for data in dataset:\n        base = data[basecolumn]\n        base = maidenhair.statistics.average(base)\n        if where:\n            adata = [maidenhair.statistics.average(x) for x in data]\n            where_i = np.where(where(adata))\n            base = base[where_i]\n        index = getattr(np, method, np.argmax)(base)\n        for a, axis in enumerate(data):\n            if len(peakset) <= a:\n                peakset.append([])\n            if where_i:\n                axis = axis[where_i]\n            peakset[a].append(axis[index])\n    peakset = np.array(peakset)\n    return peakset",
    "docstring": "Find peakset from the dataset\n\n    Parameters\n    -----------\n    dataset : list\n        A list of data\n    basecolumn : int\n        An index of column for finding peaks\n    method : str\n        A method name of numpy for finding peaks\n    where : function\n        A function which recieve ``data`` and return numpy indexing list\n\n    Returns\n    -------\n    list\n        A list of peaks of each axis (list)"
  },
  {
    "code": "def get_text_contents(self):\n        contents = self.get_contents()\n        if contents[:len(codecs.BOM_UTF8)] == codecs.BOM_UTF8:\n            return contents[len(codecs.BOM_UTF8):].decode('utf-8')\n        if contents[:len(codecs.BOM_UTF16_LE)] == codecs.BOM_UTF16_LE:\n            return contents[len(codecs.BOM_UTF16_LE):].decode('utf-16-le')\n        if contents[:len(codecs.BOM_UTF16_BE)] == codecs.BOM_UTF16_BE:\n            return contents[len(codecs.BOM_UTF16_BE):].decode('utf-16-be')\n        try:\n            return contents.decode('utf-8')\n        except UnicodeDecodeError as e:\n            try:\n                return contents.decode('latin-1')\n            except UnicodeDecodeError as e:\n                return contents.decode('utf-8', error='backslashreplace')",
    "docstring": "This attempts to figure out what the encoding of the text is\n        based upon the BOM bytes, and then decodes the contents so that\n        it's a valid python string."
  },
  {
    "code": "def get_xml(html, content_tag='ekb', fail_if_empty=False):\n    cont = re.findall(r'<%(tag)s(.*?)>(.*?)</%(tag)s>' % {'tag': content_tag},\n                      html, re.MULTILINE | re.DOTALL)\n    if cont:\n        events_terms = ''.join([l.strip() for l in cont[0][1].splitlines()])\n        if 'xmlns' in cont[0][0]:\n            meta = ' '.join([l.strip() for l in cont[0][0].splitlines()])\n        else:\n            meta = ''\n    else:\n        events_terms = ''\n        meta = ''\n    if fail_if_empty:\n        assert events_terms != '',\\\n            \"Got empty string for events content from html:\\n%s\" % html\n    header = ('<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><%s%s>'\n              % (content_tag, meta))\n    footer = '</%s>' % content_tag\n    return header + events_terms.replace('\\n', '') + footer",
    "docstring": "Extract the content XML from the HTML output of the TRIPS web service.\n\n    Parameters\n    ----------\n    html : str\n        The HTML output from the TRIPS web service.\n    content_tag : str\n        The xml tag used to label the content. Default is 'ekb'.\n    fail_if_empty : bool\n        If True, and if the xml content found is an empty string, raise an\n        exception. Default is False.\n\n    Returns\n    -------\n    The extraction knowledge base (e.g. EKB) XML that contains the event and\n    term extractions."
  },
  {
    "code": "def validate(self):\n        if (self.scheme is None or self.scheme != '') \\\n          and (self.host is None or self.host == ''):\n            return False\n        return True",
    "docstring": "Validates the URL object. The URL object is invalid if it does not represent an absolute URL.\n        Returns True or False based on this."
  },
  {
    "code": "def startElement(self, name, attrs):\n        self.stack.append((self.current, self.chardata))\n        self.current = {}\n        self.chardata = []",
    "docstring": "Initialize new node and store current node into stack."
  },
  {
    "code": "def get_account_history(self, account_id, **kwargs):\n        endpoint = '/accounts/{}/ledger'.format(account_id)\n        return self._send_paginated_message(endpoint, params=kwargs)",
    "docstring": "List account activity. Account activity either increases or\n        decreases your account balance.\n\n        Entry type indicates the reason for the account change.\n        * transfer:\tFunds moved to/from Coinbase to cbpro\n        * match:\tFunds moved as a result of a trade\n        * fee:\t    Fee as a result of a trade\n        * rebate:   Fee rebate as per our fee schedule\n\n        If an entry is the result of a trade (match, fee), the details\n        field will contain additional information about the trade.\n\n        Args:\n            account_id (str): Account id to get history of.\n            kwargs (dict): Additional HTTP request parameters.\n\n        Returns:\n            list: History information for the account. Example::\n                [\n                    {\n                        \"id\": \"100\",\n                        \"created_at\": \"2014-11-07T08:19:27.028459Z\",\n                        \"amount\": \"0.001\",\n                        \"balance\": \"239.669\",\n                        \"type\": \"fee\",\n                        \"details\": {\n                            \"order_id\": \"d50ec984-77a8-460a-b958-66f114b0de9b\",\n                            \"trade_id\": \"74\",\n                            \"product_id\": \"BTC-USD\"\n                        }\n                    },\n                    {\n                        ...\n                    }\n                ]"
  },
  {
    "code": "def reorient_z(structure):\n    struct = structure.copy()\n    sop = get_rot(struct)\n    struct.apply_operation(sop)\n    return struct",
    "docstring": "reorients a structure such that the z axis is concurrent with the\n    normal to the A-B plane"
  },
  {
    "code": "def compute_node_positions(self):\n        xs = []\n        ys = []\n        self.locs = dict()\n        for node in self.nodes:\n            x = self.graph.node[node][self.node_lon]\n            y = self.graph.node[node][self.node_lat]\n            xs.append(x)\n            ys.append(y)\n            self.locs[node] = (x, y)\n        self.node_coords = {\"x\": xs, \"y\": ys}",
    "docstring": "Extracts the node positions based on the specified longitude and\n        latitude keyword arguments."
  },
  {
    "code": "def list(self, argv):\n        def read(index):\n            print(index.name)\n            for key in sorted(index.content.keys()): \n                value = index.content[key]\n                print(\"    %s: %s\" % (key, value))\n        if len(argv) == 0:\n            for index in self.service.indexes:\n                count = index['totalEventCount']\n                print(\"%s (%s)\" % (index.name, count))\n        else:\n            self.foreach(argv, read)",
    "docstring": "List available indexes if no names provided, otherwise list the\n           properties of the named indexes."
  },
  {
    "code": "def invoked(self, ctx):\n        if not ctx.ansi.is_enabled:\n            print(\"You need color support to use this demo\")\n        else:\n            print(ctx.ansi.cmd('erase_display'))\n            self._demo_fg_color(ctx)\n            self._demo_bg_color(ctx)\n            self._demo_bg_indexed(ctx)\n            self._demo_rgb(ctx)\n            self._demo_style(ctx)",
    "docstring": "Method called when the command is invoked."
  },
  {
    "code": "def _regexSearchKeyValueCombo(policy_data, policy_regpath, policy_regkey):\n    if policy_data:\n        specialValueRegex = salt.utils.stringutils.to_bytes(r'(\\*\\*Del\\.|\\*\\*DelVals\\.){0,1}')\n        _thisSearch = b''.join([salt.utils.stringutils.to_bytes(r'\\['),\n                               re.escape(policy_regpath),\n                               b'\\00;',\n                               specialValueRegex,\n                               re.escape(policy_regkey),\n                               b'\\00;'])\n        match = re.search(_thisSearch, policy_data, re.IGNORECASE)\n        if match:\n            return policy_data[match.start():(policy_data.index(b']', match.end())) + 2]\n    return None",
    "docstring": "helper function to do a search of Policy data from a registry.pol file\n    for a policy_regpath and policy_regkey combo"
  },
  {
    "code": "def change_node_subscriptions(self, jid, node, subscriptions_to_set):\n        iq = aioxmpp.stanza.IQ(\n            type_=aioxmpp.structs.IQType.SET,\n            to=jid,\n            payload=pubsub_xso.OwnerRequest(\n                pubsub_xso.OwnerSubscriptions(\n                    node,\n                    subscriptions=[\n                        pubsub_xso.OwnerSubscription(\n                            jid,\n                            subscription\n                        )\n                        for jid, subscription in subscriptions_to_set\n                    ]\n                )\n            )\n        )\n        yield from self.client.send(iq)",
    "docstring": "Update the subscriptions at a node.\n\n        :param jid: Address of the PubSub service.\n        :type jid: :class:`aioxmpp.JID`\n        :param node: Name of the node to modify\n        :type node: :class:`str`\n        :param subscriptions_to_set: The subscriptions to set at the node.\n        :type subscriptions_to_set: :class:`~collections.abc.Iterable` of\n            tuples consisting of the JID to (un)subscribe and the subscription\n            level to use.\n        :raises aioxmpp.errors.XMPPError: as returned by the service\n\n        `subscriptions_to_set` must be an iterable of pairs (`jid`,\n        `subscription`), where the `jid` indicates the JID for which the\n        `subscription` is to be set."
  },
  {
    "code": "def _get_geocoding(self, key, location):\n        url = self._location_query_base % quote_plus(key)\n        if self.api_key:\n            url += \"&key=%s\" % self.api_key\n        data = self._read_from_url(url)\n        response = json.loads(data)\n        if response[\"status\"] == \"OK\":\n            formatted_address = response[\"results\"][0][\"formatted_address\"]\n            pos = formatted_address.find(\",\")\n            if pos == -1:\n                location.name = formatted_address\n                location.region = \"\"\n            else:\n                location.name = formatted_address[:pos].strip()\n                location.region = formatted_address[pos + 1 :].strip()\n            geo_location = response[\"results\"][0][\"geometry\"][\"location\"]\n            location.latitude = float(geo_location[\"lat\"])\n            location.longitude = float(geo_location[\"lng\"])\n        else:\n            raise AstralError(\"GoogleGeocoder: Unable to locate %s. Server Response=%s\" %\n                              (key, response[\"status\"]))",
    "docstring": "Lookup the Google geocoding API information for `key`"
  },
  {
    "code": "def _get_external_workers(worker):\n    worker_that_blocked_task = collections.defaultdict(set)\n    get_work_response_history = worker._get_work_response_history\n    for get_work_response in get_work_response_history:\n        if get_work_response['task_id'] is None:\n            for running_task in get_work_response['running_tasks']:\n                other_worker_id = running_task['worker']\n                other_task_id = running_task['task_id']\n                other_task = worker._scheduled_tasks.get(other_task_id)\n                if other_worker_id == worker._id or not other_task:\n                    continue\n                worker_that_blocked_task[other_worker_id].add(other_task)\n    return worker_that_blocked_task",
    "docstring": "This returns a dict with a set of tasks for all of the other workers"
  },
  {
    "code": "def process_request_thread(self, request, client_address):\n        from ..blockstackd import get_gc_thread\n        try:\n            self.finish_request(request, client_address)\n        except Exception:\n            self.handle_error(request, client_address)\n        finally:\n            self.shutdown_request(request)\n        shutdown_thread = False\n        with self._thread_guard:\n            if threading.current_thread().ident in self._threads:\n                del self._threads[threading.current_thread().ident]\n                shutdown_thread = True\n                if BLOCKSTACK_TEST:\n                    log.debug('{} active threads (removed {})'.format(len(self._threads), threading.current_thread().ident))\n        if shutdown_thread:\n            gc_thread = get_gc_thread()\n            if gc_thread:\n                gc_thread.gc_event()",
    "docstring": "Same as in BaseServer but as a thread.\n        In addition, exception handling is done here."
  },
  {
    "code": "def get_events_with_error_code(event_number, event_status, select_mask=0b1111111111111111, condition=0b0000000000000000):\n    logging.debug(\"Calculate events with certain error code\")\n    return np.unique(event_number[event_status & select_mask == condition])",
    "docstring": "Selects the events with a certain error code.\n\n    Parameters\n    ----------\n    event_number : numpy.array\n    event_status : numpy.array\n    select_mask : int\n        The mask that selects the event error code to check.\n    condition : int\n        The value the selected event error code should have.\n\n    Returns\n    -------\n    numpy.array"
  },
  {
    "code": "def submit_statsd_measurements(self):\n        for key, value in self.measurement.counters.items():\n            self.statsd.incr(key, value)\n        for key, values in self.measurement.durations.items():\n            for value in values:\n                self.statsd.add_timing(key, value)\n        for key, value in self.measurement.values.items():\n            self.statsd.set_gauge(key, value)\n        for key, value in self.measurement.tags.items():\n            if isinstance(value, bool):\n                if value:\n                    self.statsd.incr(key)\n            elif isinstance(value, str):\n                if value:\n                    self.statsd.incr('{}.{}'.format(key, value))\n            elif isinstance(value, int):\n                self.statsd.incr(key, value)\n            else:\n                LOGGER.warning('The %s value type of %s is unsupported',\n                               key, type(value))",
    "docstring": "Submit a measurement for a message to statsd as individual items."
  },
  {
    "code": "def _synchronized(meth):\n    @functools.wraps(meth)\n    def wrapper(self, *args, **kwargs):\n        with self._lock:\n            return meth(self, *args, **kwargs)\n    return wrapper",
    "docstring": "Call method while holding a lock."
  },
  {
    "code": "def create_kernel_spec(self, is_cython=False,\r\n                           is_pylab=False, is_sympy=False):\r\n        CONF.set('main', 'spyder_pythonpath',\r\n                 self.main.get_spyder_pythonpath())\r\n        return SpyderKernelSpec(is_cython=is_cython,\r\n                                is_pylab=is_pylab,\r\n                                is_sympy=is_sympy)",
    "docstring": "Create a kernel spec for our own kernels"
  },
  {
    "code": "def send_data(self, **kwargs):\n        put_url = None\n        if 'put_url' in kwargs:\n            put_url = kwargs['put_url']\n        else:\n            put_url = self.put_upload_url\n        if 'data' not in kwargs:\n            raise AttributeError(\"'data' parameter is required\")\n        if not put_url:\n            raise AttributeError(\"'put_url' cannot be None\")\n        if not isinstance(kwargs['data'], str):\n            raise TypeError(\"'data' parameter must be of type 'str'\")\n        response = GettRequest().put(put_url, kwargs['data'])\n        if response.http_status == 200:\n            return True",
    "docstring": "This method transmits data to the Gett service.\n\n        Input:\n            * ``put_url`` A PUT url to use when transmitting the data (required)\n            * ``data`` A byte stream (required)\n\n        Output:\n            * ``True``\n\n        Example::\n\n            if file.send_data(put_url=file.upload_url, data=open(\"example.txt\", \"rb\").read()):\n                print \"Your file has been uploaded.\""
  },
  {
    "code": "def pydeps(**args):\n    _args = args if args else cli.parse_args(sys.argv[1:])\n    inp = target.Target(_args['fname'])\n    log.debug(\"Target: %r\", inp)\n    if _args.get('output'):\n        _args['output'] = os.path.abspath(_args['output'])\n    else:\n        _args['output'] = os.path.join(\n            inp.calling_dir,\n            inp.modpath.replace('.', '_') + '.' + _args.get('format', 'svg')\n        )\n    with inp.chdir_work():\n        _args['fname'] = inp.fname\n        _args['isdir'] = inp.is_dir\n        if _args.get('externals'):\n            del _args['fname']\n            exts = externals(inp, **_args)\n            print(json.dumps(exts, indent=4))\n            return exts\n        else:\n            return _pydeps(inp, **_args)",
    "docstring": "Entry point for the ``pydeps`` command.\n\n       This function should do all the initial parameter and environment\n       munging before calling ``_pydeps`` (so that function has a clean\n       execution path)."
  },
  {
    "code": "def parse_objective_coefficient(entry):\n    for parameter in entry.kinetic_law_reaction_parameters:\n        pid, name, value, units = parameter\n        if (pid == 'OBJECTIVE_COEFFICIENT' or\n                name == 'OBJECTIVE_COEFFICIENT'):\n            return value\n    return None",
    "docstring": "Return objective value for reaction entry.\n\n    Detect objectives that are specified using the non-standardized\n    kinetic law parameters which are used by many pre-FBC SBML models. The\n    objective coefficient is returned for the given reaction, or None if\n    undefined.\n\n    Args:\n        entry: :class:`SBMLReactionEntry`."
  },
  {
    "code": "def collect_filepaths(self, directories):\n        plugin_filepaths = set()\n        directories = util.to_absolute_paths(directories)\n        for directory in directories:\n            filepaths = util.get_filepaths_from_dir(directory)\n            filepaths = self._filter_filepaths(filepaths)\n            plugin_filepaths.update(set(filepaths))\n        plugin_filepaths = self._remove_blacklisted(plugin_filepaths)\n        return plugin_filepaths",
    "docstring": "Collects and returns every filepath from each directory in\n        `directories` that is filtered through the `file_filters`.\n        If no `file_filters` are present, passes every file in directory\n        as a result.\n        Always returns a `set` object\n\n        `directories` can be a object or an iterable. Recommend using\n        absolute paths."
  },
  {
    "code": "def write_gif(dataset, filename, fps=10):\n    try:\n        check_dataset(dataset)\n    except ValueError as e:\n        dataset = try_fix_dataset(dataset)\n        check_dataset(dataset)\n    delay_time = 100 // int(fps)\n    def encode(d):\n        four_d = isinstance(dataset, numpy.ndarray) and len(dataset.shape) == 4\n        if four_d or not isinstance(dataset, numpy.ndarray):\n            return _make_animated_gif(d, delay_time=delay_time)\n        else:\n            return _make_gif(d)\n    with open(filename, 'wb') as outfile:\n        outfile.write(HEADER)\n        for block in encode(dataset):\n            outfile.write(block)\n        outfile.write(TRAILER)",
    "docstring": "Write a NumPy array to GIF 89a format.\n\n    Or write a list of NumPy arrays to an animation (GIF 89a format).\n\n    - Positional arguments::\n\n        :param dataset: A NumPy arrayor list of arrays with shape\n                        rgb x rows x cols and integer values in [0, 255].\n        :param filename: The output file that will contain the GIF image.\n        :param fps: The (integer) frames/second of the animation (default 10).\n        :type dataset: a NumPy array or list of NumPy arrays.\n        :return: None\n\n    - Example: a minimal array, with one red pixel, would look like this::\n\n        import numpy as np\n        one_red_pixel = np.array([[[255]], [[0]], [[0]]])\n        write_gif(one_red_pixel, 'red_pixel.gif')\n\n    ..raises:: ValueError"
  },
  {
    "code": "def iterkeys(self, key_type=None, return_all_keys=False):\r\n        if(key_type is not None):\r\n            the_key = str(key_type)\r\n            if the_key in self.__dict__:\r\n                for key in self.__dict__[the_key].keys():\r\n                    if return_all_keys:\r\n                        yield self.__dict__[the_key][key]\r\n                    else:\r\n                        yield key            \r\n        else:\r\n            for keys in self.items_dict.keys():\r\n                yield keys",
    "docstring": "Returns an iterator over the dictionary's keys.\r\n            @param key_type if specified, iterator for a dictionary of this type will be used. \r\n                   Otherwise (if not specified) tuples containing all (multiple) keys\r\n                   for this dictionary will be generated.\r\n            @param return_all_keys if set to True - tuple of keys is retuned instead of a key of this type."
  },
  {
    "code": "def _validate_allowed_settings(self, application_id, application_config, allowed_settings):\n\t\tfor setting_key in application_config.keys():\n\t\t\tif setting_key not in allowed_settings:\n\t\t\t\traise ImproperlyConfigured(\n\t\t\t\t\t\"Platform {}, app {} does not support the setting: {}.\".format(\n\t\t\t\t\t\tapplication_config[\"PLATFORM\"], application_id, setting_key\n\t\t\t\t\t)\n\t\t\t\t)",
    "docstring": "Confirm only allowed settings are present."
  },
  {
    "code": "def ifilter(self, recursive=True, matches=None, flags=FLAGS,\n                forcetype=None):\n        gen = self._indexed_ifilter(recursive, matches, flags, forcetype)\n        return (node for i, node in gen)",
    "docstring": "Iterate over nodes in our list matching certain conditions.\n\n        If *forcetype* is given, only nodes that are instances of this type (or\n        tuple of types) are yielded. Setting *recursive* to ``True`` will\n        iterate over all children and their descendants. ``RECURSE_OTHERS``\n        will only iterate over children that are not the instances of\n        *forcetype*. ``False`` will only iterate over immediate children.\n\n        ``RECURSE_OTHERS`` can be used to iterate over all un-nested templates,\n        even if they are inside of HTML tags, like so:\n\n            >>> code = mwparserfromhell.parse(\"{{foo}}<b>{{foo|{{bar}}}}</b>\")\n            >>> code.filter_templates(code.RECURSE_OTHERS)\n            [\"{{foo}}\", \"{{foo|{{bar}}}}\"]\n\n        *matches* can be used to further restrict the nodes, either as a\n        function (taking a single :class:`.Node` and returning a boolean) or a\n        regular expression (matched against the node's string representation\n        with :func:`re.search`). If *matches* is a regex, the flags passed to\n        :func:`re.search` are :const:`re.IGNORECASE`, :const:`re.DOTALL`, and\n        :const:`re.UNICODE`, but custom flags can be specified by passing\n        *flags*."
  },
  {
    "code": "def parse(binary, **params):\n    encoding = params.get('charset', 'UTF-8')\n    return json.loads(binary, encoding=encoding)",
    "docstring": "Turns a JSON structure into a python object."
  },
  {
    "code": "def client_getter():\n    def wrapper(f):\n        @wraps(f)\n        def decorated(*args, **kwargs):\n            if 'client_id' not in kwargs:\n                abort(500)\n            client = Client.query.filter_by(\n                client_id=kwargs.pop('client_id'),\n                user_id=current_user.get_id(),\n            ).first()\n            if client is None:\n                abort(404)\n            return f(client, *args, **kwargs)\n        return decorated\n    return wrapper",
    "docstring": "Decorator to retrieve Client object and check user permission."
  },
  {
    "code": "def get_preds(self, ds_type:DatasetType=DatasetType.Valid, with_loss:bool=False, n_batch:Optional[int]=None, pbar:Optional[PBar]=None,\n                  ordered:bool=False) -> List[Tensor]:\n        \"Return predictions and targets on the valid, train, or test set, depending on `ds_type`.\"\n        self.model.reset()\n        if ordered: np.random.seed(42)\n        preds = super().get_preds(ds_type=ds_type, with_loss=with_loss, n_batch=n_batch, pbar=pbar)\n        if ordered and hasattr(self.dl(ds_type), 'sampler'):\n            np.random.seed(42)\n            sampler = [i for i in self.dl(ds_type).sampler]\n            reverse_sampler = np.argsort(sampler)\n            preds = [p[reverse_sampler] for p in preds] \n        return(preds)",
    "docstring": "Return predictions and targets on the valid, train, or test set, depending on `ds_type`."
  },
  {
    "code": "def diff_dictionaries(old_dict, new_dict):\n    old_set = set(old_dict)\n    new_set = set(new_dict)\n    added_set = new_set - old_set\n    removed_set = old_set - new_set\n    common_set = old_set & new_set\n    changes = 0\n    output = []\n    for key in added_set:\n        changes += 1\n        output.append(DictValue(key, None, new_dict[key]))\n    for key in removed_set:\n        changes += 1\n        output.append(DictValue(key, old_dict[key], None))\n    for key in common_set:\n        output.append(DictValue(key, old_dict[key], new_dict[key]))\n        if str(old_dict[key]) != str(new_dict[key]):\n            changes += 1\n    output.sort(key=attrgetter(\"key\"))\n    return [changes, output]",
    "docstring": "Diffs two single dimension dictionaries\n\n    Returns the number of changes and an unordered list\n    expressing the common entries and changes.\n\n    Args:\n        old_dict(dict): old dictionary\n        new_dict(dict): new dictionary\n\n    Returns: list()\n        int: number of changed records\n        list: [DictValue]"
  },
  {
    "code": "def create_branch(self, branch_name):\n        self.create()\n        self.ensure_working_tree()\n        logger.info(\"Creating branch '%s' in %s ..\", branch_name, format_path(self.local))\n        self.context.execute(*self.get_create_branch_command(branch_name))",
    "docstring": "Create a new branch based on the working tree's revision.\n\n        :param branch_name: The name of the branch to create (a string).\n\n        This method automatically checks out the new branch, but note that the\n        new branch may not actually exist until a commit has been made on the\n        branch."
  },
  {
    "code": "def read_local_config(cfg):\n    try:\n        if os.path.exists(cfg):\n            config = import_file_object(cfg)\n            return config\n        else:\n            logger.warning(\n                '%s: local config file (%s) not found, cannot be read' %\n                (inspect.stack()[0][3], str(cfg)))\n    except IOError as e:\n        logger.warning(\n            'import_file_object: %s error opening %s' % (str(e), str(cfg))\n        )\n    return {}",
    "docstring": "Parses local config file for override values\n\n    Args:\n        :local_file (str):  filename of local config file\n\n    Returns:\n        dict object of values contained in local config file"
  },
  {
    "code": "def get_user_details(self, response):\n        email = response['email']\n        username = response.get('nickname', email).split('@', 1)[0]\n        return {'username': username,\n                'email': email,\n                'fullname': '',\n                'first_name': '',\n                'last_name': ''}",
    "docstring": "Return user details from OAuth Profile Google App Engine App"
  },
  {
    "code": "def decrypt(self,ciphertext,n=''):\n        self.ed = 'd'\n        if self.mode == MODE_XTS:\n            return self.chain.update(ciphertext,'d',n)\n        else:\n            return self.chain.update(ciphertext,'d')",
    "docstring": "Decrypt some ciphertext\n\n            ciphertext  = a string of binary data\n            n           = the 'tweak' value when the chaining mode is XTS\n\n        The decrypt function will decrypt the supplied ciphertext.\n        The behavior varies slightly depending on the chaining mode.\n\n        ECB, CBC:\n        ---------\n        When the supplied ciphertext is not a multiple of the blocksize\n          of the cipher, then the remaining ciphertext will be cached.\n        The next time the decrypt function is called with some ciphertext,\n          the new ciphertext will be concatenated to the cache and then\n          cache+ciphertext will be decrypted.\n\n        CFB, OFB, CTR:\n        --------------\n        When the chaining mode allows the cipher to act as a stream cipher,\n          the decrypt function will always decrypt all of the supplied\n          ciphertext immediately. No cache will be kept.\n\n        XTS:\n        ----\n        Because the handling of the last two blocks is linked,\n          it needs the whole block of ciphertext to be supplied at once.\n        Every decrypt function called on a XTS cipher will output\n          a decrypted block based on the current supplied ciphertext block.\n\n        CMAC:\n        -----\n        Mode not supported for decryption as this does not make sense."
  },
  {
    "code": "def _session_key(self):\n        if not hasattr(self, \"_cached_session_key\"):\n            session_id_bytes = self.get_secure_cookie(\"session_id\")\n            session_id = None\n            if session_id_bytes:\n                try:\n                    session_id = session_id_bytes.decode('utf-8')\n                except:\n                    pass\n            if not session_id:\n                session_id = oz.redis_sessions.random_hex(20)\n            session_time = oz.settings[\"session_time\"]\n            kwargs = dict(\n                name=\"session_id\",\n                value=session_id.encode('utf-8'),\n                domain=oz.settings.get(\"cookie_domain\"),\n                httponly=True,\n            )\n            if session_time:\n                kwargs[\"expires_days\"] = round(session_time/60/60/24)\n            self.set_secure_cookie(**kwargs)\n            password_salt = oz.settings[\"session_salt\"]\n            self._cached_session_key = \"session:%s:v4\" % oz.redis_sessions.password_hash(session_id, password_salt=password_salt)\n        return self._cached_session_key",
    "docstring": "Gets the redis key for a session"
  },
  {
    "code": "def graph_lasso(X, num_folds):\n    print(\"GraphLasso (sklearn)\")\n    model = GraphLassoCV(cv=num_folds)\n    model.fit(X)\n    print(\"   lam_: {}\".format(model.alpha_))\n    return model.covariance_, model.precision_, model.alpha_",
    "docstring": "Estimate inverse covariance via scikit-learn GraphLassoCV class."
  },
  {
    "code": "def read_block(self, size, from_date=None):\n        search_query = self._build_search_query(from_date)\n        hits_block = []\n        for hit in helpers.scan(self._es_conn,\n                                search_query,\n                                scroll='300m',\n                                index=self._es_index,\n                                preserve_order=True):\n            hits_block.append(hit)\n            if len(hits_block) % size == 0:\n                yield hits_block\n                hits_block = []\n        if len(hits_block) > 0:\n            yield hits_block",
    "docstring": "Read items and return them in blocks.\n\n        :param from_date: start date for incremental reading.\n        :param size: block size.\n        :return: next block of items when any available.\n        :raises ValueError: `metadata__timestamp` field not found in index\n        :raises NotFoundError: index not found in ElasticSearch"
  },
  {
    "code": "def _set_country(self, c):\n        self.location.countrycode = c.split()[0].split('=')[1].strip().upper()",
    "docstring": "callback if we used Tor's GETINFO ip-to-country"
  },
  {
    "code": "def discover_slaves(self, service_name):\n        \"Returns a list of alive slaves for service ``service_name``\"\n        for sentinel in self.sentinels:\n            try:\n                slaves = sentinel.sentinel_slaves(service_name)\n            except (ConnectionError, ResponseError, TimeoutError):\n                continue\n            slaves = self.filter_slaves(slaves)\n            if slaves:\n                return slaves\n        return []",
    "docstring": "Returns a list of alive slaves for service ``service_name``"
  },
  {
    "code": "def first_ipv6(self) -> Optional[AddressInfo]:\n        for info in self._address_infos:\n            if info.family == socket.AF_INET6:\n                return info",
    "docstring": "The first IPV6 address."
  },
  {
    "code": "def cache_model(key_params, timeout='default'):\n    def decorator_fn(fn):\n        return CacheModelDecorator().decorate(key_params, timeout, fn)\n    return decorator_fn",
    "docstring": "Caching decorator for app models in task.perform"
  },
  {
    "code": "def get_lbry_api_function_docs(url=LBRY_API_RAW_JSON_URL):\n    try:\n        docs_page = urlopen(url)\n        contents = docs_page.read().decode(\"utf-8\")\n        return loads(contents)\n    except URLError as UE:\n        print(UE)\n    except Exception as E:\n        print(E)\n    return []",
    "docstring": "Scrapes the given URL to a page in JSON format to obtain the documentation for the LBRY API\n\n    :param str url: URL to the documentation we need to obtain,\n     pybry.constants.LBRY_API_RAW_JSON_URL by default\n    :return: List of functions retrieved from the `url` given\n    :rtype: list"
  },
  {
    "code": "def username_matches_request_user(view_fn):\n    @wraps(view_fn)\n    def wrapper(request, username, *args, **kwargs):\n        User = get_user_model()\n        user = get_object_or_404(User, username=username)\n        if user != request.user:\n            return HttpResponseForbidden()\n        else:\n            return view_fn(request, user, *args, **kwargs)\n    return wrapper",
    "docstring": "Checks if the username matches the request user, and if so replaces\n    username with the actual user object.\n    Returns 404 if the username does not exist, and 403 if it doesn't match."
  },
  {
    "code": "def _handle_units_placement(changeset, units, records):\n    for service_name, service in sorted(changeset.bundle['services'].items()):\n        num_units = service.get('num_units')\n        if num_units is None:\n            continue\n        placement_directives = service.get('to', [])\n        if not isinstance(placement_directives, (list, tuple)):\n            placement_directives = [placement_directives]\n        if placement_directives and not changeset.is_legacy_bundle():\n            placement_directives += (\n                placement_directives[-1:] *\n                (num_units - len(placement_directives)))\n        placed_in_services = {}\n        for i in range(num_units):\n            unit = units['{}/{}'.format(service_name, i)]\n            record = records[unit['record']]\n            if i < len(placement_directives):\n                record = _handle_unit_placement(\n                    changeset, units, unit, record, placement_directives[i],\n                    placed_in_services)\n            changeset.send(record)",
    "docstring": "Ensure that requires and placement directives are taken into account."
  },
  {
    "code": "def join_path(self, *path):\n\t\tpath = self.directory_sep().join(path)\n\t\treturn self.normalize_path(path)",
    "docstring": "Unite entries to generate a single path\n\n\t\t:param path: path items to unite\n\n\t\t:return: str"
  },
  {
    "code": "def _current_web_port(self):\n        info = inspect_container(self._get_container_name('web'))\n        if info is None:\n            return None\n        try:\n            if not info['State']['Running']:\n                return None\n            return info['NetworkSettings']['Ports']['5000/tcp'][0]['HostPort']\n        except TypeError:\n            return None",
    "docstring": "return just the port number for the web container, or None if\n        not running"
  },
  {
    "code": "def _recv_sf(self, data):\n        self.rx_timer.cancel()\n        if self.rx_state != ISOTP_IDLE:\n            warning(\"RX state was reset because single frame was received\")\n            self.rx_state = ISOTP_IDLE\n        length = six.indexbytes(data, 0) & 0xf\n        if len(data) - 1 < length:\n            return 1\n        msg = data[1:1 + length]\n        self.rx_queue.put(msg)\n        for cb in self.rx_callbacks:\n            cb(msg)\n        self.call_release()\n        return 0",
    "docstring": "Process a received 'Single Frame' frame"
  },
  {
    "code": "def xyz_with_ports(self, arrnx3):\n        if not self.children:\n            if not arrnx3.shape[0] == 1:\n                raise ValueError(\n                    'Trying to set position of {} with more than one'\n                    'coordinate: {}'.format(\n                        self, arrnx3))\n            self.pos = np.squeeze(arrnx3)\n        else:\n            for atom, coords in zip(\n                self._particles(\n                    include_ports=True), arrnx3):\n                atom.pos = coords",
    "docstring": "Set the positions of the particles in the Compound, including the Ports.\n\n        Parameters\n        ----------\n        arrnx3 : np.ndarray, shape=(n,3), dtype=float\n            The new particle positions"
  },
  {
    "code": "def get_namespace(taskfileinfo):\n    element = taskfileinfo.task.element\n    name = element.name\n    return name + \"_1\"",
    "docstring": "Return a suitable name for a namespace for the taskfileinfo\n\n    Returns the name of the shot/asset with a \"_1\" suffix.\n    When you create the namespace the number will automatically be incremented by Maya.\n\n    :param taskfileinfo: the taskfile info for the file that needs a namespace\n    :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo`\n    :returns: a namespace suggestion\n    :rtype: str\n    :raises: None"
  },
  {
    "code": "def install_hg(path):\n    hook = op.join(path, 'hgrc')\n    if not op.isfile(hook):\n        open(hook, 'w+').close()\n    c = ConfigParser()\n    c.readfp(open(hook, 'r'))\n    if not c.has_section('hooks'):\n        c.add_section('hooks')\n    if not c.has_option('hooks', 'commit'):\n        c.set('hooks', 'commit', 'python:pylama.hooks.hg_hook')\n    if not c.has_option('hooks', 'qrefresh'):\n        c.set('hooks', 'qrefresh', 'python:pylama.hooks.hg_hook')\n    c.write(open(hook, 'w+'))",
    "docstring": "Install hook in Mercurial repository."
  },
  {
    "code": "def _build_option_description(k):\n    o = _get_registered_option(k)\n    d = _get_deprecated_option(k)\n    s = '{k} '.format(k=k)\n    if o.doc:\n        s += '\\n'.join(o.doc.strip().split('\\n'))\n    else:\n        s += 'No description available.'\n    if o:\n        s += ('\\n    [default: {default}] [currently: {current}]'\n              .format(default=o.defval, current=_get_option(k, True)))\n    if d:\n        s += '\\n    (Deprecated'\n        s += (', use `{rkey}` instead.'\n              .format(rkey=d.rkey if d.rkey else ''))\n        s += ')'\n    return s",
    "docstring": "Builds a formatted description of a registered option and prints it"
  },
  {
    "code": "def read_caffemodel(prototxt_fname, caffemodel_fname):\n    if use_caffe:\n        caffe.set_mode_cpu()\n        net = caffe.Net(prototxt_fname, caffemodel_fname, caffe.TEST)\n        layer_names = net._layer_names\n        layers = net.layers\n        return (layers, layer_names)\n    else:\n        proto = caffe_pb2.NetParameter()\n        with open(caffemodel_fname, 'rb') as f:\n            proto.ParseFromString(f.read())\n        return (get_layers(proto), None)",
    "docstring": "Return a caffe_pb2.NetParameter object that defined in a binary\n    caffemodel file"
  },
  {
    "code": "def _adjust_returns(returns, adjustment_factor):\n    if isinstance(adjustment_factor, (float, int)) and adjustment_factor == 0:\n        return returns\n    return returns - adjustment_factor",
    "docstring": "Returns the returns series adjusted by adjustment_factor. Optimizes for the\n    case of adjustment_factor being 0 by returning returns itself, not a copy!\n\n    Parameters\n    ----------\n    returns : pd.Series or np.ndarray\n    adjustment_factor : pd.Series or np.ndarray or float or int\n\n    Returns\n    -------\n    adjusted_returns : array-like"
  },
  {
    "code": "def process_all_json_files(build_dir):\n    html_files = []\n    for root, _, files in os.walk(build_dir):\n        for filename in fnmatch.filter(files, '*.fjson'):\n            if filename in ['search.fjson', 'genindex.fjson',\n                            'py-modindex.fjson']:\n                continue\n            html_files.append(os.path.join(root, filename))\n    page_list = []\n    for filename in html_files:\n        try:\n            result = process_file(filename)\n            if result:\n                page_list.append(result)\n        except:\n            pass\n    return page_list",
    "docstring": "Return a list of pages to index"
  },
  {
    "code": "def is_winding_consistent(self):\n        if self.is_empty:\n            return False\n        populate = self.is_watertight\n        return self._cache['is_winding_consistent']",
    "docstring": "Does the mesh have consistent winding or not.\n        A mesh with consistent winding has each shared edge\n        going in an opposite direction from the other in the pair.\n\n        Returns\n        --------\n        consistent : bool\n          Is winding is consistent or not"
  },
  {
    "code": "def metadata_matches(self, query={}):\n        result = len(query.keys()) > 0\n        for key in query.keys():\n            result = result and query[key] == self.metadata.get(key)\n        return result",
    "docstring": "Returns key matches to metadata\n\n        This will check every key in query for a matching key in metadata\n        returning true if every key is in metadata.  query without keys\n        return false.\n\n        Args:\n            query(object): metadata for matching\n\n        Returns:\n            bool:\n                True: when key count in query is > 0 and all keys in query in\n                    self.metadata\n                False: if key count in query is <= 0 or any key in query not\n                    found in self.metadata"
  },
  {
    "code": "def newfeed(ctx, symbol, price, market, cer, mssr, mcr, account):\n    if cer:\n        cer = Price(cer, quote=symbol, base=\"1.3.0\", bitshares_instance=ctx.bitshares)\n    print_tx(\n        ctx.bitshares.publish_price_feed(\n            symbol, Price(price, market), cer=cer, mssr=mssr, mcr=mcr, account=account\n        )\n    )",
    "docstring": "Publish a price feed!\n\n        Examples:\n\n            \\b\n            uptick newfeed USD 0.01 USD/BTS\n            uptick newfeed USD 100 BTS/USD\n\n        Core Exchange Rate (CER)\n        \\b\n        If no CER is provided, the cer will be the same as the settlement price\n        with a 5% premium (Only if the 'market' is against the core asset (e.g.\n        BTS)). The CER is always defined against the core asset (BTS). This\n        means that if the backing asset is not the core asset (BTS), then you must\n        specify your own cer as a float. The float `x` will be interpreted as\n        `x BTS/SYMBOL`."
  },
  {
    "code": "def add_surface(self, name, surface):\n        assert surface is not None\n        if hasattr(self.module, name):\n            raise ThriftCompilerError(\n                'Cannot define \"%s\". The name has already been used.' % name\n            )\n        setattr(self.module, name, surface)",
    "docstring": "Adds a top-level attribute with the given name to the module."
  },
  {
    "code": "def geoadd(self, name, *values):\n        if len(values) % 3 != 0:\n            raise DataError(\"GEOADD requires places with lon, lat and name\"\n                            \" values\")\n        return self.execute_command('GEOADD', name, *values)",
    "docstring": "Add the specified geospatial items to the specified key identified\n        by the ``name`` argument. The Geospatial items are given as ordered\n        members of the ``values`` argument, each item or place is formed by\n        the triad longitude, latitude and name."
  },
  {
    "code": "def remove(self, force=False):\n        return self.client.api.remove_plugin(self.name, force=force)",
    "docstring": "Remove the plugin from the server.\n\n            Args:\n                force (bool): Remove even if the plugin is enabled.\n                    Default: False\n\n            Raises:\n                :py:class:`docker.errors.APIError`\n                    If the server returns an error."
  },
  {
    "code": "def read_ipx(self, length):\n        if length is None:\n            length = len(self)\n        _csum = self._read_fileng(2)\n        _tlen = self._read_unpack(2)\n        _ctrl = self._read_unpack(1)\n        _type = self._read_unpack(1)\n        _dsta = self._read_ipx_address()\n        _srca = self._read_ipx_address()\n        ipx = dict(\n            chksum=_csum,\n            len=_tlen,\n            count=_ctrl,\n            type=TYPE.get(_type),\n            dst=_dsta,\n            src=_srca,\n        )\n        proto = ipx['type']\n        length = ipx['len'] - 30\n        ipx['packet'] = self._read_packet(header=30, payload=length)\n        return self._decode_next_layer(ipx, proto, length)",
    "docstring": "Read Internetwork Packet Exchange.\n\n        Structure of IPX header [RFC 1132]:\n            Octets      Bits        Name                    Description\n              0           0     ipx.cksum               Checksum\n              2          16     ipx.len                 Packet Length (header includes)\n              4          32     ipx.count               Transport Control (hop count)\n              5          40     ipx.type                Packet Type\n              6          48     ipx.dst                 Destination Address\n              18        144     ipx.src                 Source Address"
  },
  {
    "code": "def capture(self, *args, **kwargs):\n        import traceback\n        try:\n            from StringIO import StringIO\n        except ImportError:\n            from io import StringIO\n        stdout, stderr = sys.stdout, sys.stderr\n        sys.stdout = out = StringIO()\n        sys.stderr = err = StringIO()\n        result = {\n            'exception': None,\n            'stderr': None,\n            'stdout': None,\n            'return': None\n        }\n        try:\n            result['return'] = self.__call__(*args, **kwargs)\n        except Exception:\n            result['exception'] = traceback.format_exc()\n        sys.stdout, sys.stderr = stdout, stderr\n        result['stderr'] = err.getvalue()\n        result['stdout'] = out.getvalue()\n        return result",
    "docstring": "Run a task and return a dictionary with stderr, stdout and the\n        return value. Also, the traceback from the exception if there was\n        one"
  },
  {
    "code": "def poll_event(self):\n        for e in tdl.event.get():\n            self.e.type = e.type\n            if e.type == 'KEYDOWN':\n                self.e.key = e.key\n                return self.e.gettuple()",
    "docstring": "Wait for an event and return it.\n\n           Returns a tuple: (type, unicode character, key, mod, width, height,\n           mousex, mousey)."
  },
  {
    "code": "def _is_excluded(self, path, dir_only):\n        return self.npatterns and self._match_excluded(path, self.npatterns)",
    "docstring": "Check if file is excluded."
  },
  {
    "code": "def create(self, **kwargs):\n        response = self.ghost.execute_post('%s/' % self._type_name, json={\n            self._type_name: [\n                kwargs\n            ]\n        })\n        return self._model_type(response.get(self._type_name)[0])",
    "docstring": "Creates a new resource.\n\n        :param kwargs: The properties of the resource\n        :return: The created item returned by the API\n            wrapped as a `Model` object"
  },
  {
    "code": "def stop(self, timeout=5):\n        for worker in self._threads:\n            self._queue.put(_SHUTDOWNREQUEST)\n        current = threading.currentThread()\n        if timeout is not None and timeout >= 0:\n            endtime = time.time() + timeout\n        while self._threads:\n            worker = self._threads.pop()\n            if worker is not current and worker.isAlive():\n                try:\n                    if timeout is None or timeout < 0:\n                        worker.join()\n                    else:\n                        remaining_time = endtime - time.time()\n                        if remaining_time > 0:\n                            worker.join(remaining_time)\n                        if worker.isAlive():\n                            c = worker.conn\n                            if c and not c.rfile.closed:\n                                try:\n                                    c.socket.shutdown(socket.SHUT_RD)\n                                except TypeError:\n                                    c.socket.shutdown()\n                            worker.join()\n                except (\n                    AssertionError,\n                    KeyboardInterrupt,\n                ):\n                    pass",
    "docstring": "Terminate all worker threads.\n\n        Args:\n            timeout (int): time to wait for threads to stop gracefully"
  },
  {
    "code": "def type_and_times(type_: str, start: Timestamp, end: Timestamp, probability: Number = None) -> str:\n    if not type_:\n        return ''\n    if type_ == 'BECMG':\n        return f\"At {start.dt.hour or 'midnight'} zulu becoming\"\n    ret = f\"From {start.dt.hour or 'midnight'} to {end.dt.hour or 'midnight'} zulu,\"\n    if probability and probability.value:\n        ret += f\" there's a {probability.value}% chance for\"\n    if type_ == 'INTER':\n        ret += ' intermittent'\n    elif type_ == 'TEMPO':\n        ret += ' temporary'\n    return ret",
    "docstring": "Format line type and times into the beginning of a spoken line string"
  },
  {
    "code": "def pad_to_multiple(obj, factor):\n    _check_supported(obj)\n    copied = deepcopy(obj)\n    copied.pad_to_multiple(factor)\n    return copied",
    "docstring": "Return a copy of the object with its piano-roll padded with zeros at the\n    end along the time axis with the minimal length that make the length of\n    the resulting piano-roll a multiple of `factor`.\n\n    Parameters\n    ----------\n    factor : int\n        The value which the length of the resulting piano-roll will be\n        a multiple of."
  },
  {
    "code": "def list_all_requests_view(request, requestType):\n    request_type = get_object_or_404(RequestType, url_name=requestType)\n    requests = Request.objects.filter(request_type=request_type)\n    if not request_type.managers.filter(incumbent__user=request.user):\n        requests = requests.exclude(\n            ~Q(owner__user=request.user), private=True,\n            )\n    page_name = \"Archives - All {0} Requests\".format(request_type.name.title())\n    return render_to_response('list_requests.html', {\n        'page_name': page_name,\n        'requests': requests,\n        'request_type': request_type,\n        }, context_instance=RequestContext(request))",
    "docstring": "Show all the requests for a given type in list form."
  },
  {
    "code": "def umask(self, new_mask):\n        if not is_int_type(new_mask):\n            raise TypeError('an integer is required')\n        old_umask = self.filesystem.umask\n        self.filesystem.umask = new_mask\n        return old_umask",
    "docstring": "Change the current umask.\n\n        Args:\n            new_mask: (int) The new umask value.\n\n        Returns:\n            The old umask.\n\n        Raises:\n            TypeError: if new_mask is of an invalid type."
  },
  {
    "code": "def linkify_with_timeperiods(self, timeperiods, prop):\n        for i in self:\n            if not hasattr(i, prop):\n                continue\n            tpname = getattr(i, prop).strip()\n            if not tpname:\n                setattr(i, prop, '')\n                continue\n            timeperiod = timeperiods.find_by_name(tpname)\n            if timeperiod is None:\n                i.add_error(\"The %s of the %s '%s' named '%s' is unknown!\"\n                            % (prop, i.__class__.my_type, i.get_name(), tpname))\n                continue\n            setattr(i, prop, timeperiod.uuid)",
    "docstring": "Link items with timeperiods items\n\n        :param timeperiods: all timeperiods object\n        :type timeperiods: alignak.objects.timeperiod.Timeperiods\n        :param prop: property name\n        :type prop: str\n        :return: None"
  },
  {
    "code": "def total_reads_from_grabix(in_file):\n    gbi_file = _get_grabix_index(in_file)\n    if gbi_file:\n        with open(gbi_file) as in_handle:\n            next(in_handle)\n            num_lines = int(next(in_handle).strip())\n        assert num_lines % 4 == 0, \"Expected lines to be multiple of 4\"\n        return num_lines // 4\n    else:\n        return 0",
    "docstring": "Retrieve total reads in a fastq file from grabix index."
  },
  {
    "code": "def merge_layouts(layouts):\n    layout = layouts[0].clone()\n    for l in layouts[1:]:\n        layout.files.update(l.files)\n        layout.domains.update(l.domains)\n        for k, v in l.entities.items():\n            if k not in layout.entities:\n                layout.entities[k] = v\n            else:\n                layout.entities[k].files.update(v.files)\n    return layout",
    "docstring": "Utility function for merging multiple layouts.\n\n    Args:\n        layouts (list): A list of BIDSLayout instances to merge.\n    Returns:\n        A BIDSLayout containing merged files and entities.\n    Notes:\n        Layouts will be merged in the order of the elements in the list. I.e.,\n        the first Layout will be updated with all values in the 2nd Layout,\n        then the result will be updated with values from the 3rd Layout, etc.\n        This means that order matters: in the event of entity or filename\n        conflicts, later layouts will take precedence."
  },
  {
    "code": "def returner(ret):\n    serv = _get_serv(ret)\n    json_return = salt.utils.json.dumps(ret['return'])\n    del ret['return']\n    json_full_ret = salt.utils.json.dumps(ret)\n    if \"influxdb08\" in serv.__module__:\n        req = [\n            {\n                'name': 'returns',\n                'columns': ['fun', 'id', 'jid', 'return', 'full_ret'],\n                'points': [\n                    [ret['fun'], ret['id'], ret['jid'], json_return, json_full_ret]\n                ],\n            }\n        ]\n    else:\n        req = [\n            {\n                'measurement': 'returns',\n                'tags': {\n                    'fun': ret['fun'],\n                    'id': ret['id'],\n                    'jid': ret['jid']\n                },\n                'fields': {\n                    'return': json_return,\n                    'full_ret': json_full_ret\n                }\n            }\n        ]\n    try:\n        serv.write_points(req)\n    except Exception as ex:\n        log.critical('Failed to store return with InfluxDB returner: %s', ex)",
    "docstring": "Return data to a influxdb data store"
  },
  {
    "code": "def freeze_tag(name):\n    def decorator(func):\n        setattr(func, FREEZING_TAG_ATTRIBUTE, name)\n        return func\n    return decorator",
    "docstring": "This is not using decorator.py because we need to access original function\n    not the wrapper."
  },
  {
    "code": "def results(self):\n        results = self.recommendations()\n        transformed = []\n        for t in results['results']:\n            if len(t) == 2:\n                cid, fc = t\n                info = {}\n            elif len(t) == 3:\n                cid, fc, info = t\n            else:\n                bottle.abort(500, 'Invalid search result: \"%r\"' % t)\n            result = info\n            result['content_id'] = cid\n            if not self.params['omit_fc']:\n                result['fc'] = util.fc_to_json(fc)\n            transformed.append(result)\n        results['results'] = transformed\n        return results",
    "docstring": "Returns results as a JSON encodable Python value.\n\n        This calls :meth:`SearchEngine.recommendations` and converts\n        the results returned into JSON encodable values. Namely,\n        feature collections are slimmed down to only features that\n        are useful to an end-user."
  },
  {
    "code": "def get_json(jsonpath, default):\n    from os import path\n    import json\n    result = default\n    if path.isfile(jsonpath):\n        try:\n            with open(jsonpath) as f:\n                result = json.load(f, object_pairs_hook=load_with_datetime)\n        except(IOError):\n            err(\"Unable to deserialize JSON at {}\".format(jsonpath))\n            pass\n    return result",
    "docstring": "Returns the JSON serialized object at the specified path, or the default\n    if it doesn't exist or can't be deserialized."
  },
  {
    "code": "def convert(self, targetunits):\n        nunits = units.Units(targetunits)\n        self.waveunits = nunits",
    "docstring": "Set new user unit, for wavelength only.\n\n        This effectively converts the spectrum wavelength\n        to given unit. Note that actual data are always kept in\n        internal unit (Angstrom), and only converted\n        to user unit by :meth:`GetWaveSet` during actual computation.\n        User unit is stored in ``self.waveunits``.\n        Throughput is unitless and cannot be converted.\n\n        Parameters\n        ----------\n        targetunits : str\n            New unit name, as accepted by `~pysynphot.units.Units`."
  },
  {
    "code": "def list_quota_volume(name):\n    cmd = 'volume quota {0}'.format(name)\n    cmd += ' list'\n    root = _gluster_xml(cmd)\n    if not _gluster_ok(root):\n        return None\n    ret = {}\n    for limit in _iter(root, 'limit'):\n        path = limit.find('path').text\n        ret[path] = _etree_to_dict(limit)\n    return ret",
    "docstring": "List quotas of glusterfs volume\n\n    name\n        Name of the gluster volume\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' glusterfs.list_quota_volume <volume>"
  },
  {
    "code": "def chunks_str(str, n, separator=\"\\n\", fill_blanks_last=True):\n    return separator.join(chunks(str, n))",
    "docstring": "returns lines with max n characters\n\n    :Example:\n        >>> print (chunks_str('123456X', 3))\n        123\n        456\n        X"
  },
  {
    "code": "def owner(self):\n        obj = javabridge.call(self.jobject, \"getOwner\", \"()Lweka/core/CapabilitiesHandler;\")\n        if obj is None:\n            return None\n        else:\n            return JavaObject(jobject=obj)",
    "docstring": "Returns the owner of these capabilities, if any.\n\n        :return: the owner, can be None\n        :rtype: JavaObject"
  },
  {
    "code": "def make_userdir(child):\n    userdir = os.path.dirname(child)\n    if not os.path.isdir(userdir):\n        if os.name == 'nt':\n            userdir += \".\"\n        os.mkdir(userdir, 0700)",
    "docstring": "Create a child directory."
  },
  {
    "code": "def set_chat_title(\n        self,\n        chat_id: Union[int, str],\n        title: str\n    ) -> bool:\n        peer = self.resolve_peer(chat_id)\n        if isinstance(peer, types.InputPeerChat):\n            self.send(\n                functions.messages.EditChatTitle(\n                    chat_id=peer.chat_id,\n                    title=title\n                )\n            )\n        elif isinstance(peer, types.InputPeerChannel):\n            self.send(\n                functions.channels.EditTitle(\n                    channel=peer,\n                    title=title\n                )\n            )\n        else:\n            raise ValueError(\"The chat_id \\\"{}\\\" belongs to a user\".format(chat_id))\n        return True",
    "docstring": "Use this method to change the title of a chat.\n        Titles can't be changed for private chats.\n        You must be an administrator in the chat for this to work and must have the appropriate admin rights.\n\n        Note:\n            In regular groups (non-supergroups), this method will only work if the \"All Members Are Admins\"\n            setting is off.\n\n        Args:\n            chat_id (``int`` | ``str``):\n                Unique identifier (int) or username (str) of the target chat.\n\n            title (``str``):\n                New chat title, 1-255 characters.\n\n        Returns:\n            True on success.\n\n        Raises:\n            :class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.\n            ``ValueError`` if a chat_id belongs to user."
  },
  {
    "code": "def _weld_unary(array, weld_type, operation):\n    if weld_type not in {WeldFloat(), WeldDouble()}:\n        raise TypeError('Unary operation supported only on scalar f32 or f64')\n    obj_id, weld_obj = create_weld_object(array)\n    weld_template = 'map({array}, |e: {type}| {op}(e))'\n    weld_obj.weld_code = weld_template.format(array=obj_id, type=weld_type, op=operation)\n    return weld_obj",
    "docstring": "Apply operation on each element in the array.\n\n    As mentioned by Weld, the operations follow the behavior of the equivalent C functions from math.h\n\n    Parameters\n    ----------\n    array : numpy.ndarray or WeldObject\n        Data\n    weld_type : WeldType\n        Of the data\n    operation : {'exp', 'log', 'sqrt', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'sinh', 'cosh', 'tanh', 'erf'}\n        Which unary operation to apply.\n\n    Returns\n    -------\n    WeldObject\n        Representation of this computation."
  },
  {
    "code": "def report_change(self, name, value, maxdiff=1, deltat=10):\n        r = self.reports[name]\n        if time.time() < r.last_report + deltat:\n            return\n        r.last_report = time.time()\n        if math.fabs(r.value - value) < maxdiff:\n            return\n        r.value = value\n        self.say(\"%s %u\" % (name, value))",
    "docstring": "report a sensor change"
  },
  {
    "code": "def _verify_type(self, spec, path):\n        field_type = spec['type']\n        if isinstance(field_type, Schema):\n            if not set(spec.keys()).issubset(set(['type', 'required', 'nullable', 'default'])):\n                raise SchemaFormatException(\"Unsupported field spec item at {}. Items: \"+repr(spec.keys()), path)\n            return\n        elif isinstance(field_type, Array):\n            if not isinstance(field_type.contained_type, (type, Schema, Array, types.FunctionType)):\n                raise SchemaFormatException(\"Unsupported field type contained by Array at {}.\", path)\n        elif not isinstance(field_type, type) and not isinstance(field_type, types.FunctionType):\n            raise SchemaFormatException(\"Unsupported field type at {}. Type must be a type, a function, an Array or another Schema\", path)",
    "docstring": "Verify that the 'type' in the spec is valid"
  },
  {
    "code": "def merge(self, other):\n        assert self.refnames == other.refnames\n        assert self.dirs == other.dirs\n        assert self.lengths == other.lengths\n        for i in range(2):\n            if self.pos[i] is None:\n                if other.pos[i] is None:\n                   raise Error('Error merging these two links:\\n' + str(self) + '\\n' + str(other))\n                self.pos[i] = other.pos[i]\n            else:\n                if other.pos[i] is not None:\n                   raise Error('Error merging these two links:\\n' + str(self) + '\\n' + str(other))",
    "docstring": "Merge another link into this one. Expected that each link was created from each mate from a pair. We only know both distances to contig ends when we have read info from both mappings in a BAM file. All other info should be the same."
  },
  {
    "code": "def dump_np_vars(self, store_format='csv', delimiter=','):\n        ret = False\n        if self.system.files.no_output is True:\n            logger.debug('no_output is True, thus no TDS dump saved ')\n            return True\n        if self.write_lst() and self.write_np_dat(store_format=store_format, delimiter=delimiter):\n            ret = True\n        return ret",
    "docstring": "Dump the TDS simulation data to files by calling subroutines `write_lst` and\n        `write_np_dat`.\n\n        Parameters\n        -----------\n\n        store_format : str\n            dump format in `('csv', 'txt', 'hdf5')`\n\n        delimiter : str\n            delimiter for the `csv` and `txt` format\n\n        Returns\n        -------\n        bool: success flag"
  },
  {
    "code": "def _decorate_routes(self):\n        self.logger.debug(\"Decorating routes\")\n        self.app.add_url_rule('/<path:path>', 'catch', self.catch,\n                              methods=['GET', 'POST'], defaults={'path': ''})\n        self.app.add_url_rule('/', 'index', self.index,\n                              methods=['POST', 'GET'])\n        self.app.add_url_rule('/feed', 'feed', self.feed,\n                              methods=['POST'])\n        self.app.add_url_rule('/poll', 'poll', self.poll,\n                              methods=['POST'])",
    "docstring": "Decorates the routes to use within the flask app"
  },
  {
    "code": "def add_edge(self, u, v, **kwargs):\n        if u != v:\n            super(FactorGraph, self).add_edge(u, v, **kwargs)\n        else:\n            raise ValueError('Self loops are not allowed')",
    "docstring": "Add an edge between variable_node and factor_node.\n\n        Parameters\n        ----------\n        u, v: nodes\n            Nodes can be any hashable Python object.\n\n        Examples\n        --------\n        >>> from pgmpy.models import FactorGraph\n        >>> G = FactorGraph()\n        >>> G.add_nodes_from(['a', 'b', 'c'])\n        >>> phi1 = DiscreteFactor(['a', 'b'], [2, 2], np.random.rand(4))\n        >>> G.add_nodes_from([phi1, phi2])\n        >>> G.add_edge('a', phi1)"
  },
  {
    "code": "def field_subset(f, inds, rank=0):\n    f_dim_space = f.ndim - rank\n    if inds.ndim > 2:\n        raise Exception('Too many dimensions in indices array')\n    if inds.ndim == 1:\n        if f_dim_space == 1:\n            return f[inds]\n        else:\n            raise Exception('Indices array is 1d but field is not')\n    if inds.shape[1] != f_dim_space:\n        raise Exception('Indices and field dimensions do not match')\n    return f[tuple([inds[:, i] for i in range(inds.shape[1])])]",
    "docstring": "Return the value of a field at a subset of points.\n\n    Parameters\n    ----------\n    f: array, shape (a1, a2, ..., ad, r1, r2, ..., rrank)\n        Rank-r field in d dimensions\n    inds: integer array, shape (n, d)\n        Index vectors\n    rank: integer\n        The rank of the field (0: scalar field, 1: vector field and so on).\n\n    Returns\n    -------\n    f_sub: array, shape (n, rank)\n        The subset of field values."
  },
  {
    "code": "def require_login(self, view_func):\n        @wraps(view_func)\n        def decorated(*args, **kwargs):\n            if g.oidc_id_token is None:\n                return self.redirect_to_auth_server(request.url)\n            return view_func(*args, **kwargs)\n        return decorated",
    "docstring": "Use this to decorate view functions that require a user to be logged\n        in. If the user is not already logged in, they will be sent to the\n        Provider to log in, after which they will be returned.\n\n        .. versionadded:: 1.0\n           This was :func:`check` before."
  },
  {
    "code": "def left(self, speed=1):\n        self.right_motor.forward(speed)\n        self.left_motor.backward(speed)",
    "docstring": "Make the robot turn left by running the right motor forward and left\n        motor backward.\n\n        :param float speed:\n            Speed at which to drive the motors, as a value between 0 (stopped)\n            and 1 (full speed). The default is 1."
  },
  {
    "code": "def move_red_right(self):\n        self = self.flip()\n        if self.left is not NULL and self.left.left.red:\n            self = self.rotate_right().flip()\n        return self",
    "docstring": "Shuffle red to the right of a tree."
  },
  {
    "code": "def read_config(*args):\n    ret = {}\n    if _TRAFFICCTL:\n        cmd = _traffic_ctl('config', 'get')\n    else:\n        cmd = _traffic_line('-r')\n    try:\n        for arg in args:\n            log.debug('Querying: %s', arg)\n            ret[arg] = _subprocess(cmd + [arg])\n    except KeyError:\n        pass\n    return ret",
    "docstring": "Read Traffic Server configuration variable definitions.\n\n    .. versionadded:: 2016.11.0\n\n    .. code-block:: bash\n\n        salt '*' trafficserver.read_config proxy.config.http.keep_alive_post_out"
  },
  {
    "code": "def to_dict(self):\n        data = self.extract_fields()\n        for key, attr in self.attributes.iteritems():\n            if key in self.ignore:\n                continue\n            value = getattr(self.context, attr, None)\n            if value is None:\n                value = getattr(self, attr, None)\n            if callable(value):\n                value = value()\n            data[key] = api.to_json_value(self.context, key, value)\n        return data",
    "docstring": "extract the data of the content and return it as a dictionary"
  },
  {
    "code": "def calculate_job_input_hash(job_spec, workflow_json):\n    if 'workflow_workspace' in job_spec:\n        del job_spec['workflow_workspace']\n    job_md5_buffer = md5()\n    job_md5_buffer.update(json.dumps(job_spec).encode('utf-8'))\n    job_md5_buffer.update(json.dumps(workflow_json).encode('utf-8'))\n    return job_md5_buffer.hexdigest()",
    "docstring": "Calculate md5 hash of job specification and workflow json."
  },
  {
    "code": "def _define_helper(flag_name, default_value, docstring, flagtype, required):\n    option_name = flag_name if required else \"--%s\" % flag_name\n    get_context_parser().add_argument(\n        option_name, default=default_value, help=docstring, type=flagtype)",
    "docstring": "Registers 'flag_name' with 'default_value' and 'docstring'."
  },
  {
    "code": "def enable(step: 'projects.ProjectStep'):\n    restore_default_configuration()\n    stdout_interceptor = RedirectBuffer(sys.stdout)\n    sys.stdout = stdout_interceptor\n    step.report.stdout_interceptor = stdout_interceptor\n    stderr_interceptor = RedirectBuffer(sys.stderr)\n    sys.stderr = stderr_interceptor\n    step.report.stderr_interceptor = stderr_interceptor\n    stdout_interceptor.active = True\n    stderr_interceptor.active = True",
    "docstring": "Create a print equivalent function that also writes the output to the\n    project page. The write_through is enabled so that the TextIOWrapper\n    immediately writes all of its input data directly to the underlying\n    BytesIO buffer. This is needed so that we can safely access the buffer\n    data in a multi-threaded environment to display updates while the buffer\n    is being written to.\n\n    :param step:"
  },
  {
    "code": "def format_value(self, value, padding):\n        if padding:\n            return \"{:0{pad}d}\".format(value, pad=padding)\n        else:\n            return str(value)",
    "docstring": "Get padding adjusting for negative values."
  },
  {
    "code": "def patch(self, url, body=\"\", headers={}, retry=True):\n        return self.request(url=url, method=\"PATCH\", body=body, headers=headers,\n                retry=retry)",
    "docstring": "Execute an HTTP PATCH request and return a dict containing the\n        response and the response status code.\n\n        Keyword arguments:\n        url -- The path to execute the result against, not including the API\n               version or project ID, with no leading /. Required.\n        body -- A string or file object to send as the body of the request.\n                Defaults to an empty string.\n        headers -- HTTP Headers to send with the request. Can overwrite the\n                defaults. Defaults to {}.\n        retry -- Whether exponential backoff should be employed. Defaults\n                 to True."
  },
  {
    "code": "def create_key(self, title, key):\n        created = None\n        if title and key:\n            url = self._build_url('user', 'keys')\n            req = self._post(url, data={'title': title, 'key': key})\n            json = self._json(req, 201)\n            if json:\n                created = Key(json, self)\n        return created",
    "docstring": "Create a new key for the authenticated user.\n\n        :param str title: (required), key title\n        :param key: (required), actual key contents, accepts path as a string\n            or file-like object\n        :returns: :class:`Key <github3.users.Key>`"
  },
  {
    "code": "def _process_cidr_file(self, file):\n        data = {'cidr': list(), 'countries': set(), 'city_country_mapping': dict()}\n        allowed_countries = settings.IPGEOBASE_ALLOWED_COUNTRIES\n        for cidr_info in self._line_to_dict(file, field_names=settings.IPGEOBASE_CIDR_FIELDS):\n            city_id = cidr_info['city_id'] if cidr_info['city_id'] != '-' else None\n            if city_id is not None:\n                data['city_country_mapping'].update({cidr_info['city_id']: cidr_info['country_code']})\n            if allowed_countries and cidr_info['country_code'] not in allowed_countries:\n                continue\n            data['cidr'].append({'start_ip': cidr_info['start_ip'],\n                                 'end_ip': cidr_info['end_ip'],\n                                 'country_id': cidr_info['country_code'],\n                                 'city_id': city_id})\n            data['countries'].add(cidr_info['country_code'])\n        return data",
    "docstring": "Iterate over ip info and extract useful data"
  },
  {
    "code": "def increase_indent(func):\n    def wrapper(*args, **kwargs):\n        global _debug_indent\n        _debug_indent += 1\n        result = func(*args, **kwargs)\n        _debug_indent -= 1\n        return result\n    return wrapper",
    "docstring": "Decorator for makin"
  },
  {
    "code": "def listMetaContentTypes(self):\n        all_md_content_types = (\n            CT_CORE_PROPS,\n            CT_EXT_PROPS,\n            CT_CUSTOM_PROPS)\n        return [k for k in self.overrides.keys() if k in all_md_content_types]",
    "docstring": "The content types with metadata\n        @return: ['application/xxx', ...]"
  },
  {
    "code": "def _get_settings(self):\n        url = self._global_settings_url\n        payload = {}\n        res = self._send_request('GET', url, payload, 'settings')\n        if res and res.status_code in self._resp_ok:\n            return res.json()",
    "docstring": "Get global mobility domain from DCNM."
  },
  {
    "code": "def templates_match(self, path):\n        template_path = get_template_path(self.template_dir, path)\n        key = 'hardening:template:%s' % template_path\n        template_checksum = file_hash(template_path)\n        kv = unitdata.kv()\n        stored_tmplt_checksum = kv.get(key)\n        if not stored_tmplt_checksum:\n            kv.set(key, template_checksum)\n            kv.flush()\n            log('Saved template checksum for %s.' % template_path,\n                level=DEBUG)\n            return False\n        elif stored_tmplt_checksum != template_checksum:\n            kv.set(key, template_checksum)\n            kv.flush()\n            log('Updated template checksum for %s.' % template_path,\n                level=DEBUG)\n            return False\n        return True",
    "docstring": "Determines if the template files are the same.\n\n        The template file equality is determined by the hashsum of the\n        template files themselves. If there is no hashsum, then the content\n        cannot be sure to be the same so treat it as if they changed.\n        Otherwise, return whether or not the hashsums are the same.\n\n        :param path: the path to check\n        :returns: boolean"
  },
  {
    "code": "def readline(self, size=None):\n        if self._pos >= self.length:\n            return ''\n        if size:\n            amount = min(size, (self.length - self._pos))\n        else:\n            amount = self.length - self._pos\n        out = self.stream.readline(amount)\n        self._pos += len(out)\n        return out",
    "docstring": "Read a line from the stream, including the trailing\n        new line character. If `size` is set, don't read more\n        than `size` bytes, even if the result does not represent\n        a complete line.\n\n        The last line read may not include a trailing new line\n        character if one was not present in the underlying stream."
  },
  {
    "code": "def path_wo_ns(obj):\n    if isinstance(obj, pywbem.CIMInstance):\n        path = obj.path.copy()\n    elif isinstance(obj, pywbem.CIMInstanceName):\n        path = obj.copy()\n    else:\n        assert False\n    path.host = None\n    path.namespace = None\n    return path",
    "docstring": "Return path of an instance or instance path without host or namespace.\n    Creates copy of the object so the original is not changed."
  },
  {
    "code": "def field_to_markdown(field):\n    if \"title\" in field:\n        field_title = \"**{}**\".format(field[\"title\"])\n    else:\n        raise Exception(\"Es necesario un `title` para describir un campo.\")\n    field_type = \" ({})\".format(field[\"type\"]) if \"type\" in field else \"\"\n    field_desc = \": {}\".format(\n        field[\"description\"]) if \"description\" in field else \"\"\n    text_template = \"{title}{type}{description}\"\n    text = text_template.format(title=field_title, type=field_type,\n                                description=field_desc)\n    return text",
    "docstring": "Genera texto en markdown a partir de los metadatos de un `field`.\n\n    Args:\n        field (dict): Diccionario con metadatos de un `field`.\n\n    Returns:\n        str: Texto que describe un `field`."
  },
  {
    "code": "def catch_gzip_errors(f):\n    def new_f(self, *args, **kwargs):\n        try:\n            return f(self, *args, **kwargs)\n        except requests.exceptions.ContentDecodingError as e:\n            log.warning(\"caught gzip error: %s\", e)\n            self.connect()\n            return f(self, *args, **kwargs)\n    return new_f",
    "docstring": "A decorator to handle gzip encoding errors which have been known to\n    happen during hydration."
  },
  {
    "code": "def mapillary_tag_exists(self):\n        description_tag = \"Image ImageDescription\"\n        if description_tag not in self.tags:\n            return False\n        for requirement in [\"MAPSequenceUUID\", \"MAPSettingsUserKey\", \"MAPCaptureTime\", \"MAPLongitude\", \"MAPLatitude\"]:\n            if requirement not in self.tags[description_tag].values or json.loads(self.tags[description_tag].values)[requirement] in [\"\", None, \" \"]:\n                return False\n        return True",
    "docstring": "Check existence of required Mapillary tags"
  },
  {
    "code": "async def update_pin(**payload):\n    data = payload[\"data\"]\n    web_client = payload[\"web_client\"]\n    channel_id = data[\"channel_id\"]\n    user_id = data[\"user\"]\n    onboarding_tutorial = onboarding_tutorials_sent[channel_id][user_id]\n    onboarding_tutorial.pin_task_completed = True\n    message = onboarding_tutorial.get_message_payload()\n    updated_message = await web_client.chat_update(**message)\n    onboarding_tutorial.timestamp = updated_message[\"ts\"]",
    "docstring": "Update the onboarding welcome message after recieving a \"pin_added\"\n    event from Slack. Update timestamp for welcome message as well."
  },
  {
    "code": "def _get_update_fields(model, uniques, to_update):\n    fields = {\n        field.attname: field\n        for field in model._meta.fields\n    }\n    if to_update is None:\n        to_update = [\n            field.attname for field in model._meta.fields\n        ]\n    to_update = [\n        attname for attname in to_update\n        if (attname not in uniques\n            and not getattr(fields[attname], 'auto_now_add', False)\n            and not fields[attname].auto_created)\n    ]\n    return to_update",
    "docstring": "Get the fields to be updated in an upsert.\n\n    Always exclude auto_now_add, auto_created fields, and unique fields in an update"
  },
  {
    "code": "def _get_arg_spec(func):\n        args, varargs, keywords, defaults = inspect.getargspec(func)\n        if defaults is None:\n            defaults = {}\n        else:\n            defaulted_args = args[-len(defaults):]\n            defaults = {name: val for name, val in zip(defaulted_args, defaults)}\n        return args, varargs, defaults",
    "docstring": "Gets the argument spec of the given function, returning defaults as a dict of param names to values"
  },
  {
    "code": "def login(username=None, password=None, token=None, url=None,\n          two_factor_callback=None):\n    g = None\n    if (username and password) or token:\n        g = GitHubEnterprise(url) if url is not None else GitHub()\n        g.login(username, password, token, two_factor_callback)\n    return g",
    "docstring": "Construct and return an authenticated GitHub session.\n\n    This will return a GitHubEnterprise session if a url is provided.\n\n    :param str username: login name\n    :param str password: password for the login\n    :param str token: OAuth token\n    :param str url: (optional), URL of a GitHub Enterprise instance\n    :param func two_factor_callback: (optional), function you implement to\n        provide the Two Factor Authentication code to GitHub when necessary\n    :returns: :class:`GitHub <github3.github.GitHub>`"
  },
  {
    "code": "def generate_namelist_file(self, rapid_namelist_file):\n        log(\"Generating RAPID namelist file ...\",\n            \"INFO\")\n        try:\n            os.remove(rapid_namelist_file)\n        except OSError:\n            pass\n        with open(rapid_namelist_file, 'w') as new_file:\n            new_file.write('&NL_namelist\\n')\n            for attr, value in sorted(list(self.__dict__.items())):\n                if not attr.startswith('_'):\n                    if attr.startswith('BS'):\n                        new_file.write(\"{0} = .{1}.\\n\"\n                                       .format(attr, str(value).lower()))\n                    elif isinstance(value, int):\n                        new_file.write(\"%s = %s\\n\" % (attr, value))\n                    else:\n                        if value:\n                            if os.name == \"nt\":\n                                value = self._get_cygwin_path(value)\n                            new_file.write(\"%s = \\'%s\\'\\n\" % (attr, value))\n            new_file.write(\"/\\n\")",
    "docstring": "Generate rapid_namelist file.\n\n        Parameters\n        ----------\n        rapid_namelist_file: str\n            Path of namelist file to generate from\n            parameters added to the RAPID manager."
  },
  {
    "code": "def sort(self):\n        users = []\n        for _, group in itertools.groupby(sorted(self.commits),\n                                          operator.attrgetter('author_mail')):\n            if group:\n                users.append(self.merge_user_commits(group))\n        self.sorted_commits = sorted(users,\n                                     key=operator.attrgetter('line_count'),\n                                     reverse=True)\n        return self.sorted_commits",
    "docstring": "Sort by commit size, per author."
  },
  {
    "code": "def ncVarUnit(ncVar):\n    attributes = ncVarAttributes(ncVar)\n    if not attributes:\n        return ''\n    for key in ('unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'):\n        if key in attributes:\n            return attributes[key]\n    else:\n        return ''",
    "docstring": "Returns the unit of the ncVar by looking in the attributes.\n\n        It searches in the attributes for one of the following keys:\n        'unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'. If these are not found, the empty\n        string is returned."
  },
  {
    "code": "def prepare_installed_requirement(self, req, require_hashes, skip_reason):\n        assert req.satisfied_by, \"req should have been satisfied but isn't\"\n        assert skip_reason is not None, (\n            \"did not get skip reason skipped but req.satisfied_by \"\n            \"is set to %r\" % (req.satisfied_by,)\n        )\n        logger.info(\n            'Requirement %s: %s (%s)',\n            skip_reason, req, req.satisfied_by.version\n        )\n        with indent_log():\n            if require_hashes:\n                logger.debug(\n                    'Since it is already installed, we are trusting this '\n                    'package without checking its hash. To ensure a '\n                    'completely repeatable environment, install into an '\n                    'empty virtualenv.'\n                )\n            abstract_dist = Installed(req)\n        return abstract_dist",
    "docstring": "Prepare an already-installed requirement"
  },
  {
    "code": "def run_tsne(self, X=None, metric='correlation', **kwargs):\n        if(X is not None):\n            dt = man.TSNE(metric=metric, **kwargs).fit_transform(X)\n            return dt\n        else:\n            dt = man.TSNE(metric=self.distance,\n                          **kwargs).fit_transform(self.adata.obsm['X_pca'])\n            tsne2d = dt\n            self.adata.obsm['X_tsne'] = tsne2d",
    "docstring": "Wrapper for sklearn's t-SNE implementation.\n\n        See sklearn for the t-SNE documentation. All arguments are the same\n        with the exception that 'metric' is set to 'precomputed' by default,\n        implying that this function expects a distance matrix by default."
  },
  {
    "code": "def mix(self, ca, cb, xb):\n        r = (1 - xb) * ca.red + xb * cb.red\n        g = (1 - xb) * ca.green + xb * cb.green\n        b = (1 - xb) * ca.blue + xb * cb.blue\n        a = (1 - xb) * ca.alpha + xb * cb.alpha\n        return gdk.RGBA(red=r, green=g, blue=b, alpha=a)",
    "docstring": "Mix colors.\n\n        Args:\n            ca (gdk.RGBA): first color\n            cb (gdk.RGBA): second color\n            xb (float): between 0.0 and 1.0\n\n        Return:\n            gdk.RGBA: linear interpolation between ca and cb,\n                      0 or 1 return the unaltered 1st or 2nd color respectively,\n                      as in CSS."
  },
  {
    "code": "def _create_buffers(self):\n        self.buffers = {}\n        for step in self.graph.nodes():\n            num_buffers = 1\n            if isinstance(step, Reduction):\n                num_buffers = len(step.parents)\n            self.buffers[step] = Buffer(step.min_frames, step.left_context, step.right_context, num_buffers)\n        return self.buffers",
    "docstring": "Create a buffer for every step in the pipeline."
  },
  {
    "code": "def _insert_eups_version(c):\n    eups_tag = os.getenv('EUPS_TAG')\n    if eups_tag is None:\n        eups_tag = 'd_latest'\n    if eups_tag in ('d_latest', 'w_latest', 'current'):\n        git_ref = 'master'\n    elif eups_tag.startswith('d_'):\n        git_ref = 'master'\n    elif eups_tag.startswith('v'):\n        git_ref = eups_tag.lstrip('v').replace('_', '.')\n    elif eups_tag.startswith('w_'):\n        git_ref = eups_tag.replace('_', '.')\n    else:\n        git_ref = 'master'\n    c['release_eups_tag'] = eups_tag\n    c['release_git_ref'] = git_ref\n    c['version'] = eups_tag\n    c['release'] = eups_tag\n    c['scipipe_conda_ref'] = git_ref\n    c['pipelines_demo_ref'] = git_ref\n    c['newinstall_ref'] = git_ref\n    return c",
    "docstring": "Insert information about the current EUPS tag into the configuration\n    namespace.\n\n    The variables are:\n\n    ``release_eups_tag``\n        The EUPS tag (obtained from the ``EUPS_TAG`` environment variable,\n        falling back to ``d_latest`` if not available).\n    ``version``, ``release``\n        Same as ``release_eups_tag``.\n    ``release_git_ref``\n        The git ref (branch or tag) corresponding ot the EUPS tag.\n    ``scipipe_conda_ref``\n        Git ref for the https://github.com/lsst/scipipe_conda_env repo.\n    ``newinstall_ref``\n        Git ref for the https://github.com/lsst/lsst repo.\n    ``pipelines_demo_ref``\n        Git ref for the https://github.com/lsst/lsst_dm_stack_demo repo."
  },
  {
    "code": "def extend(dset, array, **attrs):\n    length = len(dset)\n    if len(array) == 0:\n        return length\n    newlength = length + len(array)\n    if array.dtype.name == 'object':\n        shape = (newlength,) + preshape(array[0])\n    else:\n        shape = (newlength,) + array.shape[1:]\n    dset.resize(shape)\n    dset[length:newlength] = array\n    for key, val in attrs.items():\n        dset.attrs[key] = val\n    return newlength",
    "docstring": "Extend an extensible dataset with an array of a compatible dtype.\n\n    :param dset: an h5py dataset\n    :param array: an array of length L\n    :returns: the total length of the dataset (i.e. initial length + L)"
  },
  {
    "code": "def body(self):\n        view = ffi.buffer(self.packet.m_body, self.packet.m_nBodySize)\n        return view[:]",
    "docstring": "The body of the packet."
  },
  {
    "code": "def get_shear_vel(self, saturated):\n        try:\n            if saturated:\n                return np.sqrt(self.g_mod / self.unit_sat_mass)\n            else:\n                return np.sqrt(self.g_mod / self.unit_dry_mass)\n        except TypeError:\n            return None",
    "docstring": "Calculate the shear wave velocity\n\n        :param saturated: bool, if true then use saturated mass\n        :return:"
  },
  {
    "code": "def ijk_to_xyz(dset,ijk):\n    i = nl.dset_info(dset)\n    orient_codes = [int(x) for x in nl.run(['@AfniOrient2RAImap',i.orient]).output.split()]\n    orient_is = [abs(x)-1 for x in orient_codes]\n    rai = []\n    for rai_i in xrange(3):\n         ijk_i = orient_is[rai_i]\n         if orient_codes[rai_i] > 0:\n             rai.append(ijk[ijk_i]*i.voxel_size[rai_i] + i.spatial_from[rai_i])\n         else:\n             rai.append(i.spatial_to[rai_i] - ijk[ijk_i]*i.voxel_size[rai_i])\n    return rai",
    "docstring": "convert the dset indices ``ijk`` to RAI coordinates ``xyz``"
  },
  {
    "code": "def getValue(self, prop, default=None):\n        f = self.props.get(prop, None)\n        if not f:\n            return default\n        if isinstance(f, Feature):\n            return f.getValue()\n        if isinstance(f, tuple):\n            if f[0]:\n                return f[0].getValue()\n            elif f[1]:\n                return f[1].getValue()\n            raise Exception(\"Getting value from a property with a constrain\")\n        return f",
    "docstring": "Return the value of feature with that name or ``default``."
  },
  {
    "code": "def supported_device(self, index=0):\n        if not util.is_natural(index) or index >= self.num_supported_devices():\n            raise ValueError('Invalid index.')\n        info = structs.JLinkDeviceInfo()\n        result = self._dll.JLINKARM_DEVICE_GetInfo(index, ctypes.byref(info))\n        return info",
    "docstring": "Gets the device at the given ``index``.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          index (int): the index of the device whose information to get\n\n        Returns:\n          A ``JLinkDeviceInfo`` describing the requested device.\n\n        Raises:\n          ValueError: if index is less than 0 or >= supported device count."
  },
  {
    "code": "def get_font_face(self):\n        return FontFace._from_pointer(\n            cairo.cairo_get_font_face(self._pointer), incref=True)",
    "docstring": "Return the current font face.\n\n        :param font_face:\n            A new :class:`FontFace` object\n            wrapping an existing cairo object."
  },
  {
    "code": "def search_continuous_sets(self, dataset_id):\n        request = protocol.SearchContinuousSetsRequest()\n        request.dataset_id = dataset_id\n        request.page_size = pb.int(self._page_size)\n        return self._run_search_request(\n            request, \"continuoussets\", protocol.SearchContinuousSetsResponse)",
    "docstring": "Returns an iterator over the ContinuousSets fulfilling the specified\n        conditions from the specified Dataset.\n\n        :param str dataset_id: The ID of the\n            :class:`ga4gh.protocol.Dataset` of interest.\n        :return: An iterator over the :class:`ga4gh.protocol.ContinuousSet`\n            objects defined by the query parameters."
  },
  {
    "code": "def to_array(self):\n        array = super(PassportElementErrorFiles, self).to_array()\n        array['source'] = u(self.source)\n        array['type'] = u(self.type)\n        array['file_hashes'] = self._as_array(self.file_hashes)\n        array['message'] = u(self.message)\n        return array",
    "docstring": "Serializes this PassportElementErrorFiles to a dictionary.\n\n        :return: dictionary representation of this object.\n        :rtype: dict"
  },
  {
    "code": "def parse_action(action, parsed):\n    if action == \"list\":\n        list_env()\n    elif action == \"new\":\n        new_env(parsed.environment)\n    elif action == \"remove\":\n        remove_env(parsed.environment)\n    elif action == \"show\":\n        show_env(parsed.environment)\n    elif action == \"start\":\n        start_env(parsed.environment, parsed.path)",
    "docstring": "Parse the action to execute."
  },
  {
    "code": "def fmt_pairs(obj, indent=4, sort_key=None):\n    lengths = [len(x[0]) for x in obj]\n    if not lengths:\n        return ''\n    longest = max(lengths)\n    obj = sorted(obj, key=sort_key)\n    formatter = '%s{: <%d} {}' % (' ' * indent, longest)\n    string = '\\n'.join([formatter.format(k, v) for k, v in obj])\n    return string",
    "docstring": "Format and sort a list of pairs, usually for printing.\n\n    If sort_key is provided, the value will be passed as the\n    'key' keyword argument of the sorted() function when\n    sorting the items. This allows for the input such as\n    [('A', 3), ('B', 5), ('Z', 1)] to be sorted by the ints\n    but formatted like so:\n\n        l = [('A', 3), ('B', 5), ('Z', 1)]\n        print(fmt_pairs(l, sort_key=lambda x: x[1]))\n\n            Z 1\n            A 3\n            B 5\n        where the default behavior would be:\n\n        print(fmt_pairs(l))\n\n            A 3\n            B 5\n            Z 1"
  },
  {
    "code": "def DualDBSystemCronJob(legacy_name=None, stateful=False):\n  def Decorator(cls):\n    if not legacy_name:\n      raise ValueError(\"legacy_name has to be provided\")\n    if stateful:\n      aff4_base_cls = StatefulSystemCronFlow\n    else:\n      aff4_base_cls = SystemCronFlow\n    if issubclass(cls, cronjobs.SystemCronJobBase):\n      raise ValueError(\"Mixin class shouldn't inherit from SystemCronJobBase\")\n    if issubclass(cls, aff4_base_cls):\n      raise ValueError(\"Mixin class shouldn't inherit from %s\" %\n                       aff4_base_cls.__name__)\n    aff4_cls = compatibility.MakeType(\n        legacy_name, (cls, LegacyCronJobAdapterMixin, aff4_base_cls), {})\n    module = sys.modules[cls.__module__]\n    setattr(module, legacy_name, aff4_cls)\n    reldb_cls = compatibility.MakeType(\n        compatibility.GetName(cls), (cls, cronjobs.SystemCronJobBase), {})\n    return reldb_cls\n  return Decorator",
    "docstring": "Decorator that creates AFF4 and RELDB cronjobs from a given mixin."
  },
  {
    "code": "def network_info():\n    def extract(host, family):\n        return socket.getaddrinfo(host, None, family)[0][4][0]\n    host = socket.gethostname()\n    response = {\n        'hostname': host,\n        'ipv4': None,\n        'ipv6': None\n    }\n    with suppress(IndexError, socket.gaierror):\n        response['ipv4'] = extract(host, socket.AF_INET)\n    with suppress(IndexError, socket.gaierror):\n        response['ipv6'] = extract(host, socket.AF_INET6)\n    return response",
    "docstring": "Returns hostname, ipv4 and ipv6."
  },
  {
    "code": "def add_hbar_widget(self, ref, x=1, y=1, length=10):\n        if ref not in self.widgets:\n            widget = widgets.HBarWidget(screen=self, ref=ref, x=x, y=y, length=length)\n            self.widgets[ref] = widget\n            return self.widgets[ref]",
    "docstring": "Add Horizontal Bar Widget"
  },
  {
    "code": "def serialize_iso(attr, **kwargs):\n        if isinstance(attr, str):\n            attr = isodate.parse_datetime(attr)\n        try:\n            if not attr.tzinfo:\n                _LOGGER.warning(\n                    \"Datetime with no tzinfo will be considered UTC.\")\n            utc = attr.utctimetuple()\n            if utc.tm_year > 9999 or utc.tm_year < 1:\n                raise OverflowError(\"Hit max or min date\")\n            microseconds = str(attr.microsecond).rjust(6,'0').rstrip('0').ljust(3, '0')\n            if microseconds:\n                microseconds = '.'+microseconds\n            date = \"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}\".format(\n                utc.tm_year, utc.tm_mon, utc.tm_mday,\n                utc.tm_hour, utc.tm_min, utc.tm_sec)\n            return date + microseconds + 'Z'\n        except (ValueError, OverflowError) as err:\n            msg = \"Unable to serialize datetime object.\"\n            raise_with_traceback(SerializationError, msg, err)\n        except AttributeError as err:\n            msg = \"ISO-8601 object must be valid Datetime object.\"\n            raise_with_traceback(TypeError, msg, err)",
    "docstring": "Serialize Datetime object into ISO-8601 formatted string.\n\n        :param Datetime attr: Object to be serialized.\n        :rtype: str\n        :raises: SerializationError if format invalid."
  },
  {
    "code": "def dec(self, key, delta=1):\n        self.set(key, (self.get(key) or 0) - delta)",
    "docstring": "Decrements the value of a key by `delta`.  If the key does\n        not yet exist it is initialized with `-delta`.\n\n        For supporting caches this is an atomic operation.\n\n        :param key: the key to increment.\n        :param delta: the delta to subtract."
  },
  {
    "code": "def dumps(obj, *args, **kwargs):\n    kwargs['default'] = object2dict\n    return json.dumps(obj, *args, **kwargs)",
    "docstring": "Serialize a object to string\n\n    Basic Usage:\n\n    >>> import simplekit.objson\n    >>> obj = {'name':'wendy'}\n    >>> print simplekit.objson.dumps(obj)\n\n\n    :param obj: a object which need to dump\n    :param args: Optional arguments that :func:`json.dumps` takes.\n    :param kwargs: Keys arguments that :py:func:`json.dumps` takes.\n    :return: string"
  },
  {
    "code": "def _datasource_cell(args, cell_body):\n  name = args['name']\n  paths = args['paths']\n  data_format = (args['format'] or 'CSV').lower()\n  compressed = args['compressed'] or False\n  record = google.datalab.utils.commands.parse_config(\n      cell_body, google.datalab.utils.commands.notebook_environment(), as_dict=False)\n  jsonschema.validate(record, BigQuerySchema.TABLE_SCHEMA_SCHEMA)\n  schema = bigquery.Schema(record['schema'])\n  datasource = bigquery.ExternalDataSource(source=paths, source_format=data_format,\n                                           compressed=compressed, schema=schema)\n  google.datalab.utils.commands.notebook_environment()[name] = datasource",
    "docstring": "Implements the BigQuery datasource cell magic for ipython notebooks.\n\n  The supported syntax is\n  %%bq datasource --name <var> --paths <url> [--format <CSV|JSON>]\n  <schema>\n\n  Args:\n    args: the optional arguments following '%%bq datasource'\n    cell_body: the datasource's schema in json/yaml"
  },
  {
    "code": "def _ParseCommon2003CachedEntry(self, value_data, cached_entry_offset):\n    data_type_map = self._GetDataTypeMap(\n        'appcompatcache_cached_entry_2003_common')\n    try:\n      cached_entry = self._ReadStructureFromByteStream(\n          value_data[cached_entry_offset:], cached_entry_offset, data_type_map)\n    except (ValueError, errors.ParseError) as exception:\n      raise errors.ParseError(\n          'Unable to parse cached entry value with error: {0!s}'.format(\n              exception))\n    if cached_entry.path_size > cached_entry.maximum_path_size:\n      raise errors.ParseError('Path size value out of bounds.')\n    path_end_of_string_size = (\n        cached_entry.maximum_path_size - cached_entry.path_size)\n    if cached_entry.path_size == 0 or path_end_of_string_size != 2:\n      raise errors.ParseError('Unsupported path size values.')\n    return cached_entry",
    "docstring": "Parses the cached entry structure common for Windows 2003, Vista and 7.\n\n    Args:\n      value_data (bytes): value data.\n      cached_entry_offset (int): offset of the first cached entry data\n          relative to the start of the value data.\n\n    Returns:\n      appcompatcache_cached_entry_2003_common: cached entry structure common\n          for Windows 2003, Windows Vista and Windows 7.\n\n    Raises:\n      ParseError: if the value data could not be parsed."
  },
  {
    "code": "def add_enclosure(self, left_char, right_char):\n        assert len(left_char) == 1, \\\n            \"Parameter left_char must be character not string\"\n        assert len(right_char) == 1, \\\n            \"Parameter right_char must be character not string\"\n        self._enclosure.add((left_char, right_char))\n        self._after_tld_chars = self._get_after_tld_chars()",
    "docstring": "Add new enclosure pair of characters. That and should be removed\n        when their presence is detected at beginning and end of found URL\n\n        :param str left_char: left character of enclosure pair - e.g. \"(\"\n        :param str right_char: right character of enclosure pair - e.g. \")\""
  },
  {
    "code": "def sas_logical_jbod_attachments(self):\n        if not self.__sas_logical_jbod_attachments:\n            self.__sas_logical_jbod_attachments = SasLogicalJbodAttachments(self.__connection)\n        return self.__sas_logical_jbod_attachments",
    "docstring": "Gets the SAS Logical JBOD Attachments client.\n\n        Returns:\n            SasLogicalJbodAttachments:"
  },
  {
    "code": "def get_cluster(\n        self,\n        project_id,\n        region,\n        cluster_name,\n        retry=google.api_core.gapic_v1.method.DEFAULT,\n        timeout=google.api_core.gapic_v1.method.DEFAULT,\n        metadata=None,\n    ):\n        if \"get_cluster\" not in self._inner_api_calls:\n            self._inner_api_calls[\n                \"get_cluster\"\n            ] = google.api_core.gapic_v1.method.wrap_method(\n                self.transport.get_cluster,\n                default_retry=self._method_configs[\"GetCluster\"].retry,\n                default_timeout=self._method_configs[\"GetCluster\"].timeout,\n                client_info=self._client_info,\n            )\n        request = clusters_pb2.GetClusterRequest(\n            project_id=project_id, region=region, cluster_name=cluster_name\n        )\n        return self._inner_api_calls[\"get_cluster\"](\n            request, retry=retry, timeout=timeout, metadata=metadata\n        )",
    "docstring": "Gets the resource representation for a cluster in a project.\n\n        Example:\n            >>> from google.cloud import dataproc_v1beta2\n            >>>\n            >>> client = dataproc_v1beta2.ClusterControllerClient()\n            >>>\n            >>> # TODO: Initialize `project_id`:\n            >>> project_id = ''\n            >>>\n            >>> # TODO: Initialize `region`:\n            >>> region = ''\n            >>>\n            >>> # TODO: Initialize `cluster_name`:\n            >>> cluster_name = ''\n            >>>\n            >>> response = client.get_cluster(project_id, region, cluster_name)\n\n        Args:\n            project_id (str): Required. The ID of the Google Cloud Platform project that the cluster\n                belongs to.\n            region (str): Required. The Cloud Dataproc region in which to handle the request.\n            cluster_name (str): Required. The cluster name.\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.dataproc_v1beta2.types.Cluster` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def create_org_smarthost(self, orgid, data):\n        return self.api_call(\n            ENDPOINTS['orgsmarthosts']['new'],\n            dict(orgid=orgid),\n            body=data)",
    "docstring": "Create an organization smarthost"
  },
  {
    "code": "def jsonify(*args, **kwargs):\n    return Response(\n        json.dumps(\n            dict(\n                *args,\n                **kwargs),\n            cls=MongoJSONEncoder),\n        mimetype='application/json')",
    "docstring": "jsonify with support for MongoDB ObjectId"
  },
  {
    "code": "def _preloop_hook(self) -> None:\n        self._stop_thread = False\n        self._alerter_thread = threading.Thread(name='alerter', target=self._alerter_thread_func)\n        self._alerter_thread.start()",
    "docstring": "Start the alerter thread"
  },
  {
    "code": "def _CompareFields(field, other_field):\n  field_attrs = _GetFieldAttributes(field)\n  other_field_attrs = _GetFieldAttributes(other_field)\n  if field_attrs != other_field_attrs:\n    return False\n  return field.__class__ == other_field.__class__",
    "docstring": "Checks if two ProtoRPC fields are \"equal\".\n\n  Compares the arguments, rather than the id of the elements (which is\n  the default __eq__ behavior) as well as the class of the fields.\n\n  Args:\n    field: A ProtoRPC message field to be compared.\n    other_field: A ProtoRPC message field to be compared.\n\n  Returns:\n    Boolean indicating whether the fields are equal."
  },
  {
    "code": "def session_hook(exception):\n    safeprint(\n        \"The resource you are trying to access requires you to \"\n        \"re-authenticate with specific identities.\"\n    )\n    params = exception.raw_json[\"authorization_parameters\"]\n    message = params.get(\"session_message\")\n    if message:\n        safeprint(\"message: {}\".format(message))\n    identities = params.get(\"session_required_identities\")\n    if identities:\n        id_str = \" \".join(identities)\n        safeprint(\n            \"Please run\\n\\n\"\n            \"    globus session update {}\\n\\n\"\n            \"to re-authenticate with the required identities\".format(id_str)\n        )\n    else:\n        safeprint(\n            'Please use \"globus session update\" to re-authenticate '\n            \"with specific identities\".format(id_str)\n        )\n    exit_with_mapped_status(exception.http_status)",
    "docstring": "Expects an exception with an authorization_paramaters field in its raw_json"
  },
  {
    "code": "def atlasdb_format_query( query, values ):\n    return \"\".join( [\"%s %s\" % (frag, \"'%s'\" % val if type(val) in [str, unicode] else val) for (frag, val) in zip(query.split(\"?\"), values + (\"\",))] )",
    "docstring": "Turn a query into a string for printing.\n    Useful for debugging."
  },
  {
    "code": "def get_unread_message_count_between(parser, token):\n    try:\n        tag_name, arg = token.contents.split(None, 1)\n    except ValueError:\n        raise template.TemplateSyntaxError(\"%s tag requires arguments\" % token.contents.split()[0])\n    m = re.search(r'(.*?) and (.*?) as (\\w+)', arg)\n    if not m:\n        raise template.TemplateSyntaxError(\"%s tag had invalid arguments\" % tag_name)\n    um_from_user, um_to_user, var_name = m.groups()\n    return MessageCount(um_from_user, var_name, um_to_user)",
    "docstring": "Returns the unread message count between two users.\n\n    Syntax::\n\n        {% get_unread_message_count_between [user] and [user] as [var_name] %}\n\n    Example usage::\n\n        {% get_unread_message_count_between funky and wunki as message_count %}"
  },
  {
    "code": "def data(self, data):\n        if self.state == STATE_SOURCE_ID:\n            self.context.audit_record.source_id = int(data)\n        elif self.state == STATE_DATETIME:\n            dt = datetime.datetime.strptime(data, \"%Y-%m-%dT%H:%M:%S\")\n            self.get_parent_element().datetimestamp = dt\n        elif self.state == STATE_REASON_FOR_CHANGE:\n            self.context.audit_record.reason_for_change = data.strip() or None\n        self.state = STATE_NONE",
    "docstring": "Called for text between tags"
  },
  {
    "code": "def _tristate_parent(self, item):\n        self.change_state(item, \"tristate\")\n        parent = self.parent(item)\n        if parent:\n            self._tristate_parent(parent)",
    "docstring": "Put the box of item in tristate and change the state of the boxes of\n        item's ancestors accordingly."
  },
  {
    "code": "def get_picture(self, login=None, **kwargs):\n        _login = kwargs.get(\n            'login',\n            login or self._login\n        )\n        _activities_url = PICTURE_URL.format(login=_login)\n        return self._request_api(url=_activities_url).content",
    "docstring": "Get a user's picture.\n\n        :param str login: Login of the user to check\n        :return: JSON"
  },
  {
    "code": "def fa2s2b(fastas):\n    s2b = {}\n    for fa in fastas:\n        for seq in parse_fasta(fa):\n            s = seq[0].split('>', 1)[1].split()[0]\n            s2b[s] = fa.rsplit('/', 1)[-1].rsplit('.', 1)[0]\n    return s2b",
    "docstring": "convert fastas to s2b dictionary"
  },
  {
    "code": "def Execute(self, http):\n        self._Execute(http)\n        for key in self.__request_response_handlers:\n            response = self.__request_response_handlers[key].response\n            callback = self.__request_response_handlers[key].handler\n            exception = None\n            if response.status_code >= 300:\n                exception = exceptions.HttpError.FromResponse(response)\n            if callback is not None:\n                callback(response, exception)\n            if self.__callback is not None:\n                self.__callback(response, exception)",
    "docstring": "Execute all the requests as a single batched HTTP request.\n\n        Args:\n          http: A httplib2.Http object to be used with the request.\n\n        Returns:\n          None\n\n        Raises:\n          BatchError if the response is the wrong format."
  },
  {
    "code": "def set_env(user, name, value=None):\n    lst = list_tab(user)\n    for env in lst['env']:\n        if name == env['name']:\n            if value != env['value']:\n                rm_env(user, name)\n                jret = set_env(user, name, value)\n                if jret == 'new':\n                    return 'updated'\n                else:\n                    return jret\n            return 'present'\n    env = {'name': name, 'value': value}\n    lst['env'].append(env)\n    comdat = _write_cron_lines(user, _render_tab(lst))\n    if comdat['retcode']:\n        return comdat['stderr']\n    return 'new'",
    "docstring": "Set up an environment variable in the crontab.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' cron.set_env root MAILTO user@example.com"
  },
  {
    "code": "def _import_object(self, path, look_for_cls_method):\n        last_nth = 2 if look_for_cls_method else 1\n        path = path.split('.')\n        module_path = '.'.join(path[:-last_nth])\n        class_name = path[-last_nth]\n        module = importlib.import_module(module_path)\n        if look_for_cls_method and path[-last_nth:][0] == path[-last_nth]:\n            class_method = path[-last_nth:][1]\n        else:\n            class_method = None\n        return getattr(module, class_name), class_name, class_method",
    "docstring": "Imports the module that contains the referenced method.\n\n        Args:\n            path: python path of class/function\n            look_for_cls_method (bool): If True, treat the last part of path as class method.\n\n        Returns:\n            Tuple. (class object, class name, method to be called)"
  },
  {
    "code": "def _get_satellite_tile(self, x_tile, y_tile, z_tile):\n        cache_file = \"mapscache/{}.{}.{}.jpg\".format(z_tile, x_tile, y_tile)\n        if cache_file not in self._tiles:\n            if not os.path.isfile(cache_file):\n                url = _IMAGE_URL.format(z_tile, x_tile, y_tile, _KEY)\n                data = requests.get(url).content\n                with open(cache_file, 'wb') as f:\n                    f.write(data)\n            self._tiles[cache_file] = [\n                x_tile, y_tile, z_tile,\n                ColourImageFile(self._screen, cache_file, height=_START_SIZE, dither=True,\n                                uni=self._screen.unicode_aware),\n                True]\n            if len(self._tiles) > _CACHE_SIZE:\n                self._tiles.popitem(False)\n            self._screen.force_update()",
    "docstring": "Load up a single satellite image tile."
  },
  {
    "code": "def _send_heartbeat_request(self):\n        if self.coordinator_unknown():\n            e = Errors.GroupCoordinatorNotAvailableError(self.coordinator_id)\n            return Future().failure(e)\n        elif not self._client.ready(self.coordinator_id, metadata_priority=False):\n            e = Errors.NodeNotReadyError(self.coordinator_id)\n            return Future().failure(e)\n        version = 0 if self.config['api_version'] < (0, 11, 0) else 1\n        request = HeartbeatRequest[version](self.group_id,\n                                            self._generation.generation_id,\n                                            self._generation.member_id)\n        log.debug(\"Heartbeat: %s[%s] %s\", request.group, request.generation_id, request.member_id)\n        future = Future()\n        _f = self._client.send(self.coordinator_id, request)\n        _f.add_callback(self._handle_heartbeat_response, future, time.time())\n        _f.add_errback(self._failed_request, self.coordinator_id,\n                       request, future)\n        return future",
    "docstring": "Send a heartbeat request"
  },
  {
    "code": "def __diff_iterable(self, level, parents_ids=frozenset({})):\n        subscriptable = self.__iterables_subscriptable(level.t1, level.t2)\n        if subscriptable:\n            child_relationship_class = SubscriptableIterableRelationship\n        else:\n            child_relationship_class = NonSubscriptableIterableRelationship\n        for i, (x, y) in enumerate(\n                zip_longest(\n                    level.t1, level.t2, fillvalue=ListItemRemovedOrAdded)):\n            if y is ListItemRemovedOrAdded:\n                change_level = level.branch_deeper(\n                    x,\n                    notpresent,\n                    child_relationship_class=child_relationship_class,\n                    child_relationship_param=i)\n                self.__report_result('iterable_item_removed', change_level)\n            elif x is ListItemRemovedOrAdded:\n                change_level = level.branch_deeper(\n                    notpresent,\n                    y,\n                    child_relationship_class=child_relationship_class,\n                    child_relationship_param=i)\n                self.__report_result('iterable_item_added', change_level)\n            else:\n                item_id = id(x)\n                if parents_ids and item_id in parents_ids:\n                    continue\n                parents_ids_added = add_to_frozen_set(parents_ids, item_id)\n                next_level = level.branch_deeper(\n                    x,\n                    y,\n                    child_relationship_class=child_relationship_class,\n                    child_relationship_param=i)\n                self.__diff(next_level, parents_ids_added)",
    "docstring": "Difference of iterables"
  },
  {
    "code": "def contentsMethod(self, contentFilter):\n        allowedroles = ['Manager', 'LabManager', 'Client', 'LabClerk']\n        pm = getToolByName(self.context, \"portal_membership\")\n        member = pm.getAuthenticatedMember()\n        roles = member.getRoles()\n        allowed = [a for a in allowedroles if a in roles]\n        return self.context.objectValues('ARReport') if allowed else []",
    "docstring": "ARReport objects associated to the current Analysis request.\n        If the user is not a Manager or LabManager or Client, no items are\n        displayed."
  },
  {
    "code": "def _analyze_indexed_fields(indexed_fields):\n  result = {}\n  for field_name in indexed_fields:\n    if not isinstance(field_name, basestring):\n      raise TypeError('Field names must be strings; got %r' % (field_name,))\n    if '.' not in field_name:\n      if field_name in result:\n        raise ValueError('Duplicate field name %s' % field_name)\n      result[field_name] = None\n    else:\n      head, tail = field_name.split('.', 1)\n      if head not in result:\n        result[head] = [tail]\n      elif result[head] is None:\n        raise ValueError('Field name %s conflicts with ancestor %s' %\n                         (field_name, head))\n      else:\n        result[head].append(tail)\n  return result",
    "docstring": "Internal helper to check a list of indexed fields.\n\n  Args:\n    indexed_fields: A list of names, possibly dotted names.\n\n  (A dotted name is a string containing names separated by dots,\n  e.g. 'foo.bar.baz'.  An undotted name is a string containing no\n  dots, e.g. 'foo'.)\n\n  Returns:\n    A dict whose keys are undotted names.  For each undotted name in\n    the argument, the dict contains that undotted name as a key with\n    None as a value.  For each dotted name in the argument, the dict\n    contains the first component as a key with a list of remainders as\n    values.\n\n  Example:\n    If the argument is ['foo.bar.baz', 'bar', 'foo.bletch'], the return\n    value is {'foo': ['bar.baz', 'bletch'], 'bar': None}.\n\n  Raises:\n    TypeError if an argument is not a string.\n    ValueError for duplicate arguments and for conflicting arguments\n      (when an undotted name also appears as the first component of\n      a dotted name)."
  },
  {
    "code": "def get_user(self, username=\"\", ext_collections=False, ext_galleries=False):\n        if not username and self.standard_grant_type == \"authorization_code\":\n            response = self._req('/user/whoami')\n            u = User()\n            u.from_dict(response)\n        else:\n            if not username:\n                raise DeviantartError(\"No username defined.\")\n            else:\n                response = self._req('/user/profile/{}'.format(username), {\n                    'ext_collections' : ext_collections,\n                    'ext_galleries' : ext_galleries\n                })\n                u = User()\n                u.from_dict(response['user'])\n        return u",
    "docstring": "Get user profile information\n\n        :param username: username to lookup profile of\n        :param ext_collections: Include collection folder info\n        :param ext_galleries: Include gallery folder info"
  },
  {
    "code": "def clearLayout(layout):\n    while layout.count():\n        child = layout.takeAt(0)\n        child.widget().deleteLater()",
    "docstring": "Removes all widgets in the layout. Useful when opening a new file, want\n    to clear everything."
  },
  {
    "code": "def get_asset(self):\n        if not bool(self._my_map['assetId']):\n            raise errors.IllegalState('asset empty')\n        mgr = self._get_provider_manager('REPOSITORY')\n        if not mgr.supports_asset_lookup():\n            raise errors.OperationFailed('Repository does not support Asset lookup')\n        lookup_session = mgr.get_asset_lookup_session(proxy=getattr(self, \"_proxy\", None))\n        lookup_session.use_federated_repository_view()\n        return lookup_session.get_asset(self.get_asset_id())",
    "docstring": "Gets the ``Asset`` corresponding to this content.\n\n        return: (osid.repository.Asset) - the asset\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def entry_breadcrumbs(entry):\n    date = entry.publication_date\n    if is_aware(date):\n        date = localtime(date)\n    return [year_crumb(date), month_crumb(date),\n            day_crumb(date), Crumb(entry.title)]",
    "docstring": "Breadcrumbs for an Entry."
  },
  {
    "code": "def get_action_meanings(self):\n        actions = sorted(self._action_meanings.keys())\n        return [self._action_meanings[action] for action in actions]",
    "docstring": "Return a list of actions meanings."
  },
  {
    "code": "def get_num_shards(num_samples: int, samples_per_shard: int, min_num_shards: int) -> int:\n    return max(int(math.ceil(num_samples / samples_per_shard)), min_num_shards)",
    "docstring": "Returns the number of shards.\n\n    :param num_samples: Number of training data samples.\n    :param samples_per_shard: Samples per shard.\n    :param min_num_shards: Minimum number of shards.\n    :return: Number of shards."
  },
  {
    "code": "def get_texts_box(texts, fs):\n    max_len = max(map(len, texts))\n    return (fs, text_len(max_len, fs))",
    "docstring": "Approximation of multiple texts bounds"
  },
  {
    "code": "def _read_response(self, may_block=False):\n        res = self._waitfor_set(yubikey_defs.RESP_PENDING_FLAG, may_block)[:7]\n        while True:\n            this = self._read()\n            flags = yubico_util.ord_byte(this[7])\n            if flags & yubikey_defs.RESP_PENDING_FLAG:\n                seq = flags & 0b00011111\n                if res and (seq == 0):\n                    break\n                res += this[:7]\n            else:\n                break\n        self._write_reset()\n        return res",
    "docstring": "Wait for a response to become available, and read it."
  },
  {
    "code": "def lookup(self, plain_src_ns):\n        if plain_src_ns in self._ex_namespace_set:\n            return None\n        if not self._regex_map and not self._plain:\n            return Namespace(\n                dest_name=plain_src_ns,\n                source_name=plain_src_ns,\n                include_fields=self._include_fields,\n                exclude_fields=self._exclude_fields,\n            )\n        try:\n            return self._plain[plain_src_ns]\n        except KeyError:\n            for regex, namespace in self._regex_map:\n                new_name = match_replace_regex(regex, plain_src_ns, namespace.dest_name)\n                if not new_name:\n                    continue\n                new_namespace = namespace.with_options(\n                    dest_name=new_name, source_name=plain_src_ns\n                )\n                self._add_plain_namespace(new_namespace)\n                return new_namespace\n        self._ex_namespace_set.add(plain_src_ns)\n        return None",
    "docstring": "Given a plain source namespace, return the corresponding Namespace\n        object, or None if it is not included."
  },
  {
    "code": "def scale_and_crop_with_ranges(\n    im, size, size_range=None, crop=False, upscale=False, zoom=None, target=None, **kwargs):\n    min_width, min_height = size\n    if min_width == 0 or min_height == 0 or not size_range:\n        return scale_and_crop(im, size, crop, upscale, zoom, target, **kwargs)\n    max_width = min_width + size_range[0]\n    max_height = min_height + size_range[1]\n    min_ar = min_width * 1.0 / max_height\n    max_ar = max_width * 1.0 / min_height\n    img_width, img_height = [float(v) for v in im.size]\n    img_ar = img_width/img_height\n    if img_ar <= min_ar:\n        size = (min_width, max_height)\n    elif img_ar >= max_ar:\n        size = (max_width, min_height)\n    else:\n        size = (max_width, max_height)\n    return scale_and_crop(im, size, crop, upscale, zoom, target, **kwargs)",
    "docstring": "An easy_thumbnails processor that accepts a `size_range` tuple, which\n    indicates that one or both dimensions can give by a number of pixels in\n    order to minimize cropping."
  },
  {
    "code": "def lines2file(lines, filename, encoding='utf-8'):\n    with codecs.open(filename, \"w\", encoding=encoding) as f:\n        for line in lines:\n            f.write(line)\n            f.write(\"\\n\")",
    "docstring": "write json stream, write lines too"
  },
  {
    "code": "def swap_dims(self, dims_dict):\n        ds = self._to_temp_dataset().swap_dims(dims_dict)\n        return self._from_temp_dataset(ds)",
    "docstring": "Returns a new DataArray with swapped dimensions.\n\n        Parameters\n        ----------\n        dims_dict : dict-like\n            Dictionary whose keys are current dimension names and whose values\n            are new names. Each value must already be a coordinate on this\n            array.\n\n        Returns\n        -------\n        renamed : Dataset\n            DataArray with swapped dimensions.\n\n        See Also\n        --------\n\n        DataArray.rename\n        Dataset.swap_dims"
  },
  {
    "code": "def keep_only_sticked_and_selected_tabs(self):\n        if not global_gui_config.get_config_value('KEEP_ONLY_STICKY_STATES_OPEN', True):\n            return\n        page_id = self.view.notebook.get_current_page()\n        if page_id == -1:\n            return\n        page = self.view.notebook.get_nth_page(page_id)\n        current_state_identifier = self.get_state_identifier_for_page(page)\n        states_to_be_closed = []\n        for state_identifier, tab_info in list(self.tabs.items()):\n            if current_state_identifier == state_identifier:\n                continue\n            if tab_info['is_sticky']:\n                continue\n            states_to_be_closed.append(state_identifier)\n        for state_identifier in states_to_be_closed:\n            self.close_page(state_identifier, delete=False)",
    "docstring": "Close all tabs, except the currently active one and all sticked ones"
  },
  {
    "code": "def createDataChannel(self, label, maxPacketLifeTime=None, maxRetransmits=None,\n                          ordered=True, protocol='', negotiated=False, id=None):\n        if maxPacketLifeTime is not None and maxRetransmits is not None:\n            raise ValueError('Cannot specify both maxPacketLifeTime and maxRetransmits')\n        if not self.__sctp:\n            self.__createSctpTransport()\n        parameters = RTCDataChannelParameters(\n            id=id,\n            label=label,\n            maxPacketLifeTime=maxPacketLifeTime,\n            maxRetransmits=maxRetransmits,\n            negotiated=negotiated,\n            ordered=ordered,\n            protocol=protocol)\n        return RTCDataChannel(self.__sctp, parameters)",
    "docstring": "Create a data channel with the given label.\n\n        :rtype: :class:`RTCDataChannel`"
  },
  {
    "code": "def create_module(sym, data_shapes, label_shapes, label_names, gpus=''):\n    if gpus == '':\n        devices = mx.cpu()\n    else:\n        devices = [mx.gpu(int(i)) for i in gpus.split(',')]\n    data_names = [data_shape[0] for data_shape in data_shapes]\n    mod = mx.mod.Module(\n        symbol=sym,\n        data_names=data_names,\n        context=devices,\n        label_names=label_names\n    )\n    mod.bind(\n        for_training=False,\n        data_shapes=data_shapes,\n        label_shapes=label_shapes\n    )\n    return mod",
    "docstring": "Creates a new MXNet module.\n\n    Parameters\n    ----------\n    sym : Symbol\n        An MXNet symbol.\n\n    input_shape: tuple\n        The shape of the input data in the form of (batch_size, channels, height, width)\n\n    files: list of strings\n        List of URLs pertaining to files that need to be downloaded in order to use the model.\n\n    data_shapes: list of tuples.\n        List of tuples where each tuple is a pair of input variable name and its shape.\n\n    label_shapes: list of (str, tuple)\n        Typically is ``data_iter.provide_label``.\n\n    label_names: list of str\n        Name of the output labels in the MXNet symbolic graph.\n\n    gpus: str\n        Comma separated string of gpu ids on which inferences are executed. E.g. 3,5,6 would refer to GPUs 3, 5 and 6.\n        If empty, we use CPU.\n\n    Returns\n    -------\n    MXNet module"
  },
  {
    "code": "def visit_slice(self, node):\n        lower = node.lower.accept(self) if node.lower else \"\"\n        upper = node.upper.accept(self) if node.upper else \"\"\n        step = node.step.accept(self) if node.step else \"\"\n        if step:\n            return \"%s:%s:%s\" % (lower, upper, step)\n        return \"%s:%s\" % (lower, upper)",
    "docstring": "return an astroid.Slice node as string"
  },
  {
    "code": "async def get_message(self, ignore_subscribe_messages=False, timeout=0):\n        response = await self.parse_response(block=False, timeout=timeout)\n        if response:\n            return self.handle_message(response, ignore_subscribe_messages)\n        return None",
    "docstring": "Get the next message if one is available, otherwise None.\n\n        If timeout is specified, the system will wait for `timeout` seconds\n        before returning. Timeout should be specified as a floating point\n        number."
  },
  {
    "code": "def revert(self, unchanged_only=False):\n        if self._reverted:\n            raise errors.ChangelistError('This changelist has been reverted')\n        change = self._change\n        if self._change == 0:\n            change = 'default'\n        cmd = ['revert', '-c', str(change)]\n        if unchanged_only:\n            cmd.append('-a')\n        files = [f.depotFile for f in self._files]\n        if files:\n            cmd += files\n            self._connection.run(cmd)\n        self._files = []\n        self._reverted = True",
    "docstring": "Revert all files in this changelist\n\n        :param unchanged_only: Only revert unchanged files\n        :type unchanged_only: bool\n        :raises: :class:`.ChangelistError`"
  },
  {
    "code": "def estimate(coll, filter={}, sample=1):\n    total = coll.estimated_document_count()\n    if not filter and sample == 1:\n        return total\n    if sample <= 1:\n        sample *= total\n    pipeline = list(builtins.filter(None, [\n        {'$sample': {'size': sample}} if sample < total else {},\n        {'$match': filter},\n        {'$count': 'matched'},\n    ]))\n    docs = next(coll.aggregate(pipeline))\n    ratio = docs['matched'] / sample\n    return int(total * ratio)",
    "docstring": "Estimate the number of documents in the collection\n    matching the filter.\n\n    Sample may be a fixed number of documents to sample\n    or a percentage of the total collection size.\n\n    >>> coll = getfixture('bulky_collection')\n    >>> estimate(coll)\n    100\n    >>> query = {\"val\": {\"$gte\": 50}}\n    >>> val = estimate(coll, filter=query)\n    >>> val > 0\n    True\n    >>> val = estimate(coll, filter=query, sample=10)\n    >>> val > 0\n    True\n    >>> val = estimate(coll, filter=query, sample=.1)\n    >>> val > 0\n    True"
  },
  {
    "code": "def variance(self, param):\n        param_number = self.model.params.index(param)\n        try:\n            return self.covariance_matrix[param_number, param_number]\n        except TypeError:\n            return None",
    "docstring": "Return the variance in a given parameter as found by the fit.\n\n        :param param: ``Parameter`` Instance.\n        :return: Variance of ``param``."
  },
  {
    "code": "def _resize(self, init=False):\n        col, row = self._selection_to_col_row(self.selection)\n        if not (self.startPos <= row <= self.startPos + self.list_maxY - 1):\n            while row > self.startPos:\n                self.startPos += 1\n            while row < self.startPos + self.list_maxY - 1:\n                self.startPos -= 1\n        if init and row > self.list_maxY:\n            new_startPos = self._num_of_rows - self.list_maxY + 1\n            if row > new_startPos:\n                if logger.isEnabledFor(logging.DEBUG):\n                    logger.debug('setting startPos at {}'.format(new_startPos))\n                self.startPos = new_startPos\n        self.refresh_selection()",
    "docstring": "if the selection at the end of the list,\n            try to scroll down"
  },
  {
    "code": "def set_hierarchy(self, hierarchy):\n        self.hierarchy = dict([(k, i) for i, j in enumerate(hierarchy) for k in j])",
    "docstring": "Sets an alternative sonority hierarchy, note that you will also need\n        to specify the vowelset with the set_vowels, in order for the module\n        to correctly identify each nucleus.\n\n        The order of the phonemes defined is by decreased consonantality\n\n        Example:\n            >>> s = Syllabifier()\n\n            >>> s.set_hierarchy([['i', 'u'], ['e'], ['a'], ['r'], ['m', 'n'], ['f']])\n\n            >>> s.set_vowels(['i', 'u', 'e', 'a'])\n\n            >>> s.syllabify('feminarum')\n            ['fe', 'mi', 'na', 'rum']"
  },
  {
    "code": "def open(self):\n        try:\n            self.graph.open(self.cache_uri, create=False)\n            self._add_namespaces(self.graph)\n            self.is_open = True\n        except Exception:\n            raise InvalidCacheException('The cache is invalid or not created')",
    "docstring": "Opens an existing cache."
  },
  {
    "code": "def execute(self, env, args):\n        task_name = args.task_name\n        clone_task = args.clone_task\n        if not env.task.create(task_name, clone_task):\n            raise errors.FocusError(u'Could not create task \"{0}\"'\n                                    .format(task_name))\n        if not args.skip_edit:\n            task_config = env.task.get_config_path(task_name)\n            if not _edit_task_config(env, task_config, confirm=True):\n                raise errors.FocusError(u'Could not open task config: {0}'\n                                        .format(task_config))",
    "docstring": "Creates a new task.\n\n            `env`\n                Runtime ``Environment`` instance.\n            `args`\n                Arguments object from arg parser."
  },
  {
    "code": "def _find_elements(self, result, elements):\n    element_mapping = {}\n    result = StringIO.StringIO(result)\n    for _, e in ET.iterparse(result, events=('end',)):\n      if not elements:\n        break\n      if e.tag in elements:\n        element_mapping[e.tag] = e.text\n        elements.remove(e.tag)\n    return element_mapping",
    "docstring": "Find interesting elements from XML.\n\n    This function tries to only look for specified elements\n    without parsing the entire XML. The specified elements is better\n    located near the beginning.\n\n    Args:\n      result: response XML.\n      elements: a set of interesting element tags.\n\n    Returns:\n      A dict from element tag to element value."
  },
  {
    "code": "def hook_alias(self, alias, model_obj=None):\n        try:\n            search_alias = self._alias_hooks[alias]\n        except KeyError:\n            raise AttributeError('Could not find search alias named {}. Is this alias defined in BUNGIESEARCH[\"ALIASES\"]?'.format(alias))\n        else:\n            if search_alias._applicable_models and \\\n                ((model_obj and model_obj not in search_alias._applicable_models) or \\\n                 not any([app_model_obj.__name__ in self._doc_type for app_model_obj in search_alias._applicable_models])):\n                    raise ValueError('Search alias {} is not applicable to model/doc_types {}.'.format(alias, model_obj if model_obj else self._doc_type))\n            return search_alias.prepare(self, model_obj).alias_for",
    "docstring": "Returns the alias function, if it exists and if it can be applied to this model."
  },
  {
    "code": "def get_spectra_id(self, fn_id, retention_time=None, scan_nr=None):\n        cursor = self.get_cursor()\n        sql = 'SELECT spectra_id FROM mzml WHERE mzmlfile_id=? '\n        values = [fn_id]\n        if retention_time is not None:\n            sql = '{0} AND retention_time=?'.format(sql)\n            values.append(retention_time)\n        if scan_nr is not None:\n            sql = '{0} AND scan_nr=?'.format(sql)\n            values.append(scan_nr)\n        cursor.execute(sql, tuple(values))\n        return cursor.fetchone()[0]",
    "docstring": "Returns spectra id for spectra filename and retention time"
  },
  {
    "code": "def coverage(self):\n        intervals = ReadIntervals(self.subjectLength)\n        for hsp in self.hsps():\n            intervals.add(hsp.subjectStart, hsp.subjectEnd)\n        return intervals.coverage()",
    "docstring": "Get the fraction of this title sequence that is matched by its reads.\n\n        @return: The C{float} fraction of the title sequence matched by its\n            reads."
  },
  {
    "code": "def manages(self, cfg_part):\n        logger.debug(\"Do I (%s/%s) manage: %s, my managed configuration(s): %s\",\n                     self.type, self.name, cfg_part, self.cfg_managed)\n        if not self.cfg_managed:\n            logger.info(\"I (%s/%s) do not manage (yet) any configuration!\", self.type, self.name)\n            return False\n        for managed_cfg in list(self.cfg_managed.values()):\n            if managed_cfg['managed_conf_id'] == cfg_part.instance_id \\\n                    and managed_cfg['push_flavor'] == cfg_part.push_flavor:\n                logger.debug(\"I do manage this configuration: %s\", cfg_part)\n                break\n        else:\n            logger.warning(\"I (%s/%s) do not manage this configuration: %s\",\n                           self.type, self.name, cfg_part)\n            return False\n        return True",
    "docstring": "Tell if the satellite is managing this configuration part\n\n        The managed configuration is formed as a dictionary indexed on the link instance_id:\n         {\n            u'SchedulerLink_1': {\n                u'hash': u'4d08630a3483e1eac7898e7a721bd5d7768c8320',\n                u'push_flavor': u'4d08630a3483e1eac7898e7a721bd5d7768c8320',\n                u'managed_conf_id': [u'Config_1']\n            }\n        }\n\n        Note that the managed configuration is a string array rather than a simple string...\n        no special for this reason, probably due to the serialization when the configuration is\n        pushed :/\n\n        :param cfg_part: configuration part as prepare by the Dispatcher\n        :type cfg_part: Conf\n        :return: True if the satellite manages this configuration\n        :rtype: bool"
  },
  {
    "code": "def Scan(self, scan_context, auto_recurse=True, scan_path_spec=None):\n    if not scan_context:\n      raise ValueError('Invalid scan context.')\n    scan_context.updated = False\n    if scan_path_spec:\n      scan_node = scan_context.GetScanNode(scan_path_spec)\n    else:\n      scan_node = scan_context.GetUnscannedScanNode()\n    if scan_node:\n      self._ScanNode(scan_context, scan_node, auto_recurse=auto_recurse)",
    "docstring": "Scans for supported formats.\n\n    Args:\n      scan_context (SourceScannerContext): source scanner context.\n      auto_recurse (Optional[bool]): True if the scan should automatically\n          recurse as far as possible.\n      scan_path_spec (Optional[PathSpec]): path specification to indicate\n          where the source scanner should continue scanning, where None\n          indicates the scanner will start with the sources.\n\n    Raises:\n      ValueError: if the scan context is invalid."
  },
  {
    "code": "def bargraph(data, max_key_width=30):\n    lines = []\n    max_length = min(max(len(key) for key in data.keys()), max_key_width)\n    max_val = max(data.values())\n    max_val_length = max(\n        len(_style_value(val))\n        for val in data.values())\n    term_width = get_terminal_size()[0]\n    max_bar_width = term_width - MARGIN - (max_length + 3 + max_val_length + 3)\n    template = u\"{key:{key_width}} [ {value:{val_width}} ] {bar}\"\n    for key, value in data.items():\n        try:\n            bar = int(math.ceil(max_bar_width * value / max_val)) * TICK\n        except ZeroDivisionError:\n            bar = ''\n        line = template.format(\n            key=key[:max_length],\n            value=_style_value(value),\n            bar=bar,\n            key_width=max_length,\n            val_width=max_val_length\n        )\n        lines.append(line)\n    return '\\n'.join(lines)",
    "docstring": "Return a bar graph as a string, given a dictionary of data."
  },
  {
    "code": "def gen500(request, baseURI, project=None):\n    return HttpResponseServerError(\n        render_to_response('plugIt/500.html', {\n            'context': {\n                'ebuio_baseUrl': baseURI,\n                'ebuio_userMode': request.session.get('plugit-standalone-usermode', 'ano'),\n            },\n            'project': project\n        }, context_instance=RequestContext(request)))",
    "docstring": "Return a 500 error"
  },
  {
    "code": "def all_hosts(self):\n        return set(imap(common.clean_node, itertools.chain(\n            self._doc.get('hosts', []),\n            self._doc.get('passives', []),\n            self._doc.get('arbiters', []))))",
    "docstring": "List of hosts, passives, and arbiters known to this server."
  },
  {
    "code": "def home_win_percentage(self):\n        try:\n            result = float(self.home_wins) / \\\n                     float(self.home_wins + self.home_losses)\n            return round(result, 3)\n        except ZeroDivisionError:\n            return 0.0",
    "docstring": "Returns a ``float`` of the percentage of games the home team has won\n        after the conclusion of the game. Percentage ranges from 0-1."
  },
  {
    "code": "def send_rally_points(self):\n        self.mav_param.mavset(self.master,'RALLY_TOTAL',self.rallyloader.rally_count(),3)\n        for i in range(self.rallyloader.rally_count()):\n            self.send_rally_point(i)",
    "docstring": "send rally points from rallyloader"
  },
  {
    "code": "def num_throats(self, labels='all', mode='union'):\n        r\n        Ts = self._get_indices(labels=labels, mode=mode, element='throat')\n        Nt = sp.shape(Ts)[0]\n        return Nt",
    "docstring": "r\"\"\"\n        Return the number of throats of the specified labels\n\n        Parameters\n        ----------\n        labels : list of strings, optional\n            The throat labels that should be included in the count.\n            If not supplied, all throats are counted.\n\n        mode : string, optional\n            Specifies how the count should be performed.  The options are:\n\n            **'or', 'union', 'any'** : (default) Throats with *one or more* of\n            the given labels are counted.\n\n            **'and', 'intersection', 'all'** : Throats with *all* of the given\n            labels are counted.\n\n            **'xor', 'exclusive_or'** : Throats with *only one* of the given\n            labels are counted.\n\n            **'nor', 'none', 'not'** : Throats with *none* of the given labels\n            are counted.\n\n            **'nand'** : Throats with *some but not all* of the given labels\n            are counted.\n\n            **'xnor'** : Throats with *more than one* of the given labels are\n            counted.\n\n        Returns\n        -------\n        Nt : int\n            Number of throats with the specified labels\n\n        See Also\n        --------\n        num_pores\n        count\n\n        Notes\n        -----\n        Technically, *'nand'* and *'xnor'* should also count throats with\n        *none* of the labels, however, to make the count more useful these are\n        not included."
  },
  {
    "code": "def pull(self, platform=None):\n        repository, _ = parse_repository_tag(self.image_name)\n        return self.collection.pull(repository, tag=self.id, platform=platform)",
    "docstring": "Pull the image digest.\n\n        Args:\n            platform (str): The platform to pull the image for.\n            Default: ``None``\n\n        Returns:\n            (:py:class:`Image`): A reference to the pulled image."
  },
  {
    "code": "def run_band_structure(self,\n                           paths,\n                           with_eigenvectors=False,\n                           with_group_velocities=False,\n                           is_band_connection=False,\n                           path_connections=None,\n                           labels=None,\n                           is_legacy_plot=False):\n        if self._dynamical_matrix is None:\n            msg = (\"Dynamical matrix has not yet built.\")\n            raise RuntimeError(msg)\n        if with_group_velocities:\n            if self._group_velocity is None:\n                self._set_group_velocity()\n            group_velocity = self._group_velocity\n        else:\n            group_velocity = None\n        self._band_structure = BandStructure(\n            paths,\n            self._dynamical_matrix,\n            with_eigenvectors=with_eigenvectors,\n            is_band_connection=is_band_connection,\n            group_velocity=group_velocity,\n            path_connections=path_connections,\n            labels=labels,\n            is_legacy_plot=is_legacy_plot,\n            factor=self._factor)",
    "docstring": "Run phonon band structure calculation.\n\n        Parameters\n        ----------\n        paths : List of array_like\n            Sets of qpoints that can be passed to phonopy.set_band_structure().\n            Numbers of qpoints can be different.\n            shape of each array_like : (qpoints, 3)\n        with_eigenvectors : bool, optional\n            Flag whether eigenvectors are calculated or not. Default is False.\n        with_group_velocities : bool, optional\n            Flag whether group velocities are calculated or not. Default is\n            False.\n        is_band_connection : bool, optional\n            Flag whether each band is connected or not. This is achieved by\n            comparing similarity of eigenvectors of neghboring poins. Sometimes\n            this fails. Default is False.\n        path_connections : List of bool, optional\n            This is only used in graphical plot of band structure and gives\n            whether each path is connected to the next path or not,\n            i.e., if False, there is a jump of q-points. Number of elements is\n            the same at that of paths. Default is None.\n        labels : List of str, optional\n            This is only used in graphical plot of band structure and gives\n            labels of end points of each path. The number of labels is equal\n            to (2 - np.array(path_connections)).sum().\n        is_legacy_plot: bool, optional\n            This makes the old style band structure plot. Default is False."
  },
  {
    "code": "def githubWebHookConsumer(self, *args, **kwargs):\n        return self._makeApiCall(self.funcinfo[\"githubWebHookConsumer\"], *args, **kwargs)",
    "docstring": "Consume GitHub WebHook\n\n        Capture a GitHub event and publish it via pulse, if it's a push,\n        release or pull request.\n\n        This method is ``experimental``"
  },
  {
    "code": "def _forgiving_issubclass(derived_class, base_class):\n    return (type(derived_class) is ClassType and \\\n            type(base_class) is ClassType and \\\n            issubclass(derived_class, base_class))",
    "docstring": "Forgiving version of ``issubclass``\n\n    Does not throw any exception when arguments are not of class type"
  },
  {
    "code": "def readTempC(self):\n        v = self._read32()\n        if v & 0x7:\n            return float('NaN')\n        if v & 0x80000000:\n            v >>= 18\n            v -= 16384\n        else:\n            v >>= 18\n        return v * 0.25",
    "docstring": "Return the thermocouple temperature value in degrees celsius."
  },
  {
    "code": "def transform_y(self, tfms:Optional[Tuple[TfmList,TfmList]]=(None,None), **kwargs):\n        \"Set `tfms` to be applied to the ys of the train and validation set.\"\n        if not tfms: tfms=(None,None)\n        self.train.transform_y(tfms[0], **kwargs)\n        self.valid.transform_y(tfms[1], **kwargs)\n        if self.test: self.test.transform_y(tfms[1], **kwargs)\n        return self",
    "docstring": "Set `tfms` to be applied to the ys of the train and validation set."
  },
  {
    "code": "def lonlat2xyz(lon, lat):\n    lat = xu.deg2rad(lat)\n    lon = xu.deg2rad(lon)\n    x = xu.cos(lat) * xu.cos(lon)\n    y = xu.cos(lat) * xu.sin(lon)\n    z = xu.sin(lat)\n    return x, y, z",
    "docstring": "Convert lon lat to cartesian."
  },
  {
    "code": "def _get_value(scikit_value, mode = 'regressor', scaling = 1.0, n_classes = 2, tree_index = 0):\n    if mode == 'regressor':\n        return scikit_value[0] * scaling\n    if n_classes == 2:\n        if len(scikit_value[0]) != 1:\n            value = scikit_value[0][1] * scaling / scikit_value[0].sum()\n        else:\n            value = scikit_value[0][0] * scaling\n        if value == 0.5:\n            value = value - 1e-7\n    else:\n        if len(scikit_value[0]) != 1:\n            value = scikit_value[0] / scikit_value[0].sum()\n        else:\n            value = {tree_index: scikit_value[0] * scaling}\n    return value",
    "docstring": "Get the right value from the scikit-tree"
  },
  {
    "code": "def re_thresh_csv(path, old_thresh, new_thresh, chan_thresh):\n    from eqcorrscan.core.match_filter import read_detections\n    warnings.warn('Legacy function, please use '\n                  'eqcorrscan.core.match_filter.Party.rethreshold.')\n    old_detections = read_detections(path)\n    old_thresh = float(old_thresh)\n    new_thresh = float(new_thresh)\n    detections = []\n    detections_in = 0\n    detections_out = 0\n    for detection in old_detections:\n        detections_in += 1\n        con1 = (new_thresh / old_thresh) * detection.threshold\n        con2 = detection.no_chans >= chan_thresh\n        requirted_thresh = (new_thresh / old_thresh) * detection.threshold\n        con3 = abs(detection.detect_val) >= requirted_thresh\n        if all([con1, con2, con3]):\n            detections_out += 1\n            detections.append(detection)\n    print('Read in %i detections' % detections_in)\n    print('Left with %i detections' % detections_out)\n    return detections",
    "docstring": "Remove detections by changing the threshold.\n\n    Can only be done to remove detection by increasing threshold,\n    threshold lowering will have no effect.\n\n    :type path: str\n    :param path: Path to the .csv detection file\n    :type old_thresh: float\n    :param old_thresh: Old threshold MAD multiplier\n    :type new_thresh: float\n    :param new_thresh: New threshold MAD multiplier\n    :type chan_thresh: int\n    :param chan_thresh: Minimum number of channels for a detection\n\n    :returns: List of detections\n    :rtype: list\n\n    .. rubric:: Example\n\n    >>> from eqcorrscan.utils.clustering import re_thresh_csv\n    >>> # Get the path to the test data\n    >>> import eqcorrscan\n    >>> import os\n    >>> TEST_PATH = os.path.dirname(eqcorrscan.__file__) + '/tests/test_data'\n    >>> det_file = os.path.join(TEST_PATH, 'expected_tutorial_detections.txt')\n    >>> detections = re_thresh_csv(path=det_file, old_thresh=8, new_thresh=10,\n    ...                            chan_thresh=3)\n    Read in 22 detections\n    Left with 17 detections\n\n    .. Note::\n        This is a legacy function, and will read detections from all versions.\n\n    .. Warning:: Only works if thresholding was done by MAD."
  },
  {
    "code": "def ReadHuntOutputPluginsStates(self, hunt_id, cursor=None):\n    columns = \", \".join(_HUNT_OUTPUT_PLUGINS_STATES_COLUMNS)\n    query = (\"SELECT {columns} FROM hunt_output_plugins_states \"\n             \"WHERE hunt_id = %s\".format(columns=columns))\n    rows_returned = cursor.execute(query, [db_utils.HuntIDToInt(hunt_id)])\n    if rows_returned > 0:\n      states = []\n      for row in cursor.fetchall():\n        states.append(self._HuntOutputPluginStateFromRow(row))\n      return states\n    query = \"SELECT hunt_id FROM hunts WHERE hunt_id = %s\"\n    rows_returned = cursor.execute(query, [db_utils.HuntIDToInt(hunt_id)])\n    if rows_returned == 0:\n      raise db.UnknownHuntError(hunt_id)\n    return []",
    "docstring": "Reads all hunt output plugins states of a given hunt."
  },
  {
    "code": "def ConsumeRange(self, start, end):\n    old = self.CurrentRange()\n    if old is None:\n      return\n    if old.start > start:\n      if old.start < end:\n        raise RuntimeError('Block end too high.')\n      return\n    if old.start < start:\n      raise RuntimeError('Block start too high.')\n    if old.end == end:\n      del self.ranges[0]\n    elif old.end > end:\n      self.ranges[0] = Range(end, old.end)\n    else:\n      raise RuntimeError('Block length exceeds range.')",
    "docstring": "Consumes an entire range, or part thereof.\n\n    If the finger has no ranges left, or the curent range start is higher\n    than the end of the consumed block, nothing happens. Otherwise,\n    the current range is adjusted for the consumed block, or removed,\n    if the entire block is consumed. For things to work, the consumed\n    range and the current finger starts must be equal, and the length\n    of the consumed range may not exceed the length of the current range.\n\n    Args:\n      start: Beginning of range to be consumed.\n      end: First offset after the consumed range (end + 1).\n\n    Raises:\n      RuntimeError: if the start position of the consumed range is\n          higher than the start of the current range in the finger, or if\n          the consumed range cuts accross block boundaries."
  },
  {
    "code": "def read_response(self):\n        response = self._read_response()\n        frame, data = nsq.unpack_response(response)\n        self.last_response = time.time()\n        if frame not in self._frame_handlers:\n            raise errors.NSQFrameError('unknown frame {}'.format(frame))\n        frame_handler = self._frame_handlers[frame]\n        processed_data = frame_handler(data)\n        return frame, processed_data",
    "docstring": "Read an individual response from nsqd.\n\n        :returns: tuple of the frame type and the processed data."
  },
  {
    "code": "def _toplevel(cls):\n        superclasses = (\n            list(set(ClosureModel.__subclasses__()) &\n                 set(cls._meta.get_parent_list()))\n        )\n        return next(iter(superclasses)) if superclasses else cls",
    "docstring": "Find the top level of the chain we're in.\n\n            For example, if we have:\n            C inheriting from B inheriting from A inheriting from ClosureModel\n            C._toplevel() will return A."
  },
  {
    "code": "def findContours(*args, **kwargs):\n    if cv2.__version__.startswith('4'):\n        contours, hierarchy = cv2.findContours(*args, **kwargs)\n    elif cv2.__version__.startswith('3'):\n        _, contours, hierarchy = cv2.findContours(*args, **kwargs)\n    else:\n        raise AssertionError(\n            'cv2 must be either version 3 or 4 to call this method')\n    return contours, hierarchy",
    "docstring": "Wraps cv2.findContours to maintain compatiblity between versions\n    3 and 4\n\n    Returns:\n        contours, hierarchy"
  },
  {
    "code": "def create_tag(self, version, params):\n        cmd = self._command.tag(version, params)\n        (code, stdout, stderr) = self._exec(cmd)\n        if code:\n            raise errors.VCSError('Can\\'t create VCS tag %s. Process exited with code %d and message: %s' % (\n                version, code, stderr or stdout))",
    "docstring": "Create VCS tag\n\n        :param version:\n        :param params:\n        :return:"
  },
  {
    "code": "def generate_keypair(keypair_file):\n    from Crypto.PublicKey import RSA\n    key = RSA.generate(2048)\n    keypair_dir = os.path.dirname(keypair_file)\n    if not os.path.exists(keypair_dir):\n        os.makedirs(keypair_dir)\n    with open(keypair_file, 'wb') as filey:\n        filey.write(key.exportKey('PEM'))\n    return key",
    "docstring": "generate_keypair is used by some of the helpers that need a keypair.\n       The function should be used if the client doesn't have the attribute \n       self.key. We generate the key and return it.\n\n       We use pycryptodome (3.7.2)       \n\n       Parameters\n       =========\n       keypair_file: fullpath to where to save keypair"
  },
  {
    "code": "def get_cache(self):\n        if self.no_cache:\n            self.pkg_list = self.list_packages()\n            return\n        if not os.path.exists(self.yolk_dir):\n            os.mkdir(self.yolk_dir)\n        if os.path.exists(self.pkg_cache_file):\n            self.pkg_list = self.query_cached_package_list()\n        else:\n            self.logger.debug(\"DEBUG: Fetching package list cache from PyPi...\")\n            self.fetch_pkg_list()",
    "docstring": "Get a package name list from disk cache or PyPI"
  },
  {
    "code": "def validate_arrangement_version(self):\n        arrangement_version = self.build_kwargs['arrangement_version']\n        if arrangement_version is None:\n            return\n        if arrangement_version <= 5:\n            self.log.warning(\"arrangement_version <= 5 is deprecated and will be removed\"\n                             \" in release 1.6.38\")",
    "docstring": "Validate if the arrangement_version is supported\n\n        This is for autorebuilds to fail early otherwise they may failed\n        on workers because of osbs-client validation checks.\n\n        Method should be called after self.adjust_build_kwargs\n\n        Shows a warning when version is deprecated\n\n        :raises ValueError: when version is not supported"
  },
  {
    "code": "def tabular(client, datasets):\n    from renku.models._tabulate import tabulate\n    click.echo(\n        tabulate(\n            datasets,\n            headers=OrderedDict((\n                ('short_id', 'id'),\n                ('name', None),\n                ('created', None),\n                ('authors_csv', 'authors'),\n            )),\n        )\n    )",
    "docstring": "Format datasets with a tabular output."
  },
  {
    "code": "def to_text(self, fn:str):\n        \"Save `self.items` to `fn` in `self.path`.\"\n        with open(self.path/fn, 'w') as f: f.writelines([f'{o}\\n' for o in self._relative_item_paths()])",
    "docstring": "Save `self.items` to `fn` in `self.path`."
  },
  {
    "code": "def label(self):\n        with self.selenium.context(self.selenium.CONTEXT_CHROME):\n            return self.root.get_attribute(\"label\")",
    "docstring": "Provide access to the notification label.\n\n        Returns:\n            str: The notification label"
  },
  {
    "code": "def putenv(key, value):\n    key = path2fsn(key)\n    value = path2fsn(value)\n    if is_win and PY2:\n        try:\n            set_windows_env_var(key, value)\n        except WindowsError:\n            raise ValueError\n    else:\n        try:\n            os.putenv(key, value)\n        except OSError:\n            raise ValueError",
    "docstring": "Like `os.putenv` but takes unicode under Windows + Python 2\n\n    Args:\n        key (pathlike): The env var to get\n        value (pathlike): The value to set\n    Raises:\n        ValueError"
  },
  {
    "code": "def app_token(vault_client, app_id, user_id):\n    resp = vault_client.auth_app_id(app_id, user_id)\n    if 'auth' in resp and 'client_token' in resp['auth']:\n        return resp['auth']['client_token']\n    else:\n        raise aomi.exceptions.AomiCredentials('invalid apptoken')",
    "docstring": "Returns a vault token based on the app and user id."
  },
  {
    "code": "def is_searchable(self):\r\n        return self.raw or (self.is_valid_country and \r\n                            (not self.state or self.is_valid_state))",
    "docstring": "A bool value that indicates whether the address is a valid address \r\n        to search by."
  },
  {
    "code": "def sigmasq_series(htilde, psd=None, low_frequency_cutoff=None,\n            high_frequency_cutoff=None):\n    htilde = make_frequency_series(htilde)\n    N = (len(htilde)-1) * 2\n    norm = 4.0 * htilde.delta_f\n    kmin, kmax = get_cutoff_indices(low_frequency_cutoff,\n                                   high_frequency_cutoff, htilde.delta_f, N)\n    sigma_vec = FrequencySeries(zeros(len(htilde), dtype=real_same_precision_as(htilde)),\n                                delta_f = htilde.delta_f, copy=False)\n    mag = htilde.squared_norm()\n    if psd is not None:\n        mag /= psd\n    sigma_vec[kmin:kmax] = mag[kmin:kmax].cumsum()\n    return sigma_vec*norm",
    "docstring": "Return a cumulative sigmasq frequency series.\n\n    Return a frequency series containing the accumulated power in the input\n    up to that frequency.\n\n    Parameters\n    ----------\n    htilde : TimeSeries or FrequencySeries\n        The input vector\n    psd : {None, FrequencySeries}, optional\n        The psd used to weight the accumulated power.\n    low_frequency_cutoff : {None, float}, optional\n        The frequency to begin accumulating power. If None, start at the beginning\n        of the vector.\n    high_frequency_cutoff : {None, float}, optional\n        The frequency to stop considering accumulated power. If None, continue\n        until the end of the input vector.\n\n    Returns\n    -------\n    Frequency Series: FrequencySeries\n        A frequency series containing the cumulative sigmasq."
  },
  {
    "code": "def load(self, config_template, config_file=None):\n        if config_file is None:\n            config_file = config_template\n        config_path = build_config_file_path(config_file)\n        template_path = os.path.join(os.path.dirname(__file__),\n                                     config_template)\n        self._copy_template_to_config(template_path, config_path)\n        return self._load_template_or_config(template_path, config_path)",
    "docstring": "Read the config file if it exists, else read the default config.\n\n        Creates the user config file if it doesn't exist using the template.\n\n        :type config_template: str\n        :param config_template: The config template file name.\n\n        :type config_file: str\n        :param config_file: (Optional) The config file name.\n            If None, the config_file name will be set to the config_template.\n\n        :rtype: :class:`configobj.ConfigObj`\n        :return: The config information for reading and writing."
  },
  {
    "code": "def delete_event_view(request, id):\n    event = get_object_or_404(Event, id=id)\n    if not request.user.has_admin_permission('events'):\n        raise exceptions.PermissionDenied\n    if request.method == \"POST\":\n        try:\n            event.delete()\n            messages.success(request, \"Successfully deleted event.\")\n        except Event.DoesNotExist:\n            pass\n        return redirect(\"events\")\n    else:\n        return render(request, \"events/delete.html\", {\"event\": event})",
    "docstring": "Delete event page. You may only delete an event if you were the creator or you are an\n    administrator. Confirmation page if not POST.\n\n    id: event id"
  },
  {
    "code": "def load(self, env=None):\n        self._load()\n        e = env or \\\n            os.environ.get(RUNNING_MODE_ENVKEY, DEFAULT_RUNNING_MODE)\n        if e in self.config:\n            return self.config[e]\n        logging.warn(\"Environment '%s' was not found.\", e)",
    "docstring": "Load a section values of given environment.\n        If nothing to specified, use environmental variable.\n        If unknown environment was specified, warn it on logger.\n\n        :param env: environment key to load in a coercive manner\n        :type env: string\n        :rtype: dict"
  },
  {
    "code": "def on_click(self, event):\n        button = event[\"button\"]\n        if button == self.button_toggle:\n            self.toggled = True\n            if self.mode == \"ip\":\n                self.mode = \"status\"\n            else:\n                self.mode = \"ip\"\n        elif button == self.button_refresh:\n            self.idle_time = 0\n        else:\n            self.py3.prevent_refresh()",
    "docstring": "Toggle between display modes 'ip' and 'status'"
  },
  {
    "code": "def categorize(func: Union[Callable, Iterable], category: str) -> None:\n    if isinstance(func, Iterable):\n        for item in func:\n            setattr(item, HELP_CATEGORY, category)\n    else:\n        setattr(func, HELP_CATEGORY, category)",
    "docstring": "Categorize a function.\n\n    The help command output will group this function under the specified category heading\n\n    :param func: function to categorize\n    :param category: category to put it in"
  },
  {
    "code": "def _sign_operation(op):\n    md5 = hashlib.md5()\n    md5.update(op.consumerId.encode('utf-8'))\n    md5.update(b'\\x00')\n    md5.update(op.operationName.encode('utf-8'))\n    if op.labels:\n        signing.add_dict_to_hash(md5, encoding.MessageToPyValue(op.labels))\n    return md5.digest()",
    "docstring": "Obtains a signature for an operation in a ReportRequest.\n\n    Args:\n       op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an\n         operation used in a `ReportRequest`\n\n    Returns:\n       string: a unique signature for that operation"
  },
  {
    "code": "def keys(self, section=None):\n        if not section and self.section:\n            section = self.section\n        config = self.config.get(section, {}) if section else self.config\n        return config.keys()",
    "docstring": "Provide dict like keys method"
  },
  {
    "code": "def add(self, interval, offset):\n        start, stop = self.get_start_stop(interval)\n        if len(self.starts) > 0:\n            if start < self.starts[-1] or offset <= self.offsets[-1][1]:\n                raise ValueError('intervals and offsets must be added in-order')\n            self.offsets[-1][1] = offset\n            self.offsets[-1][2] += 1\n        else:\n            self.starts.append(start)\n            self.stops.append(stop)\n            self.offsets.append([offset, offset, 1])",
    "docstring": "The added interval must be overlapping or beyond the last stored interval ie. added in sorted order.\n\n        :param interval: interval to add\n        :param offset: full virtual offset to add\n        :return:"
  },
  {
    "code": "def always_fail(cls, request) -> [\n            (200, 'Ok', String),\n            (406, 'Not Acceptable', Void)]:\n        task_id = uuid4().hex.upper()[:5]\n        log.info('Starting always FAILING task {}'.format(task_id))\n        for i in range(randint(0, MAX_LOOP_DURATION)):\n            yield\n        Respond(406)\n        Respond(200, 'Foobar')",
    "docstring": "Perform an always failing task."
  },
  {
    "code": "def remover(self, id_brand):\n        if not is_valid_int_param(id_brand):\n            raise InvalidParameterError(\n                u'The identifier of Brand is invalid or was not informed.')\n        url = 'brand/' + str(id_brand) + '/'\n        code, xml = self.submit(None, 'DELETE', url)\n        return self.response(code, xml)",
    "docstring": "Remove Brand from by the identifier.\n\n        :param id_brand: Identifier of the Brand. Integer value and greater than zero.\n\n        :return: None\n\n        :raise InvalidParameterError: The identifier of Brand is null and invalid.\n        :raise MarcaNaoExisteError: Brand not registered.\n        :raise MarcaError: The brand is associated with a model.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def unit(self, name: Optional[UnitName] = None, symbol=False):\n        result = self._validate_enum(item=name, enum=UnitName)\n        if symbol:\n            return result[1]\n        return result[0]",
    "docstring": "Get unit name.\n\n        :param name: Enum object UnitName.\n        :param symbol: Return only symbol\n        :return: Unit."
  },
  {
    "code": "def __read_byte_offset(decl, attrs):\n        offset = attrs.get(XML_AN_OFFSET, 0)\n        decl.byte_offset = int(offset) / 8",
    "docstring": "Using duck typing to set the offset instead of in constructor"
  },
  {
    "code": "def add_table(self, t):\n        self.push_element()\n        self._page.append(t.node)\n        self.cur_element = t",
    "docstring": "remember to call pop_element after done with table"
  },
  {
    "code": "def complex_median(complex_list):\n    median_real = numpy.median([complex_number.real\n                     for complex_number in complex_list])\n    median_imag = numpy.median([complex_number.imag\n                     for complex_number in complex_list])\n    return median_real + 1.j*median_imag",
    "docstring": "Get the median value of a list of complex numbers.\n\n    Parameters\n    ----------\n    complex_list: list\n        List of complex numbers to calculate the median.\n\n    Returns\n    -------\n    a + 1.j*b: complex number\n        The median of the real and imaginary parts."
  },
  {
    "code": "def remove_pos_arg_placeholders(alias_command):\n    split_command = shlex.split(alias_command)\n    boundary_index = len(split_command)\n    for i, subcommand in enumerate(split_command):\n        if not re.match('^[a-z]', subcommand.lower()) or i > COLLISION_CHECK_LEVEL_DEPTH:\n            boundary_index = i\n            break\n    return ' '.join(split_command[:boundary_index]).lower()",
    "docstring": "Remove positional argument placeholders from alias_command.\n\n    Args:\n        alias_command: The alias command to remove from.\n\n    Returns:\n        The alias command string without positional argument placeholder."
  },
  {
    "code": "def altshuler_grun(v, v0, gamma0, gamma_inf, beta):\n    x = v / v0\n    return gamma_inf + (gamma0 - gamma_inf) * np.power(x, beta)",
    "docstring": "calculate Gruneisen parameter for Altshuler equation\n\n    :param v: unit-cell volume in A^3\n    :param v0: unit-cell volume in A^3 at 1 bar\n    :param gamma0: Gruneisen parameter at 1 bar\n    :param gamma_inf: Gruneisen parameter at infinite pressure\n    :param beta: volume dependence of Gruneisen parameter\n    :return: Gruneisen parameter"
  },
  {
    "code": "def body_block_attribution(tag):\n    \"extract the attribution content for figures, tables, videos\"\n    attributions = []\n    if raw_parser.attrib(tag):\n        for attrib_tag in raw_parser.attrib(tag):\n            attributions.append(node_contents_str(attrib_tag))\n    if raw_parser.permissions(tag):\n        for permissions_tag in raw_parser.permissions(tag):\n            attrib_string = ''\n            attrib_string = join_sentences(attrib_string,\n                node_contents_str(raw_parser.copyright_statement(permissions_tag)), '.')\n            if raw_parser.licence_p(permissions_tag):\n                for licence_p_tag in raw_parser.licence_p(permissions_tag):\n                    attrib_string = join_sentences(attrib_string,\n                                                   node_contents_str(licence_p_tag), '.')\n            if attrib_string != '':\n                attributions.append(attrib_string)\n    return attributions",
    "docstring": "extract the attribution content for figures, tables, videos"
  },
  {
    "code": "def area(self):\n        area = abs(self.primitive.height *\n                   self.primitive.polygon.length)\n        area += self.primitive.polygon.area * 2\n        return area",
    "docstring": "The surface area of the primitive extrusion.\n\n        Calculated from polygon and height to avoid mesh creation.\n\n        Returns\n        ----------\n        area: float, surface area of 3D extrusion"
  },
  {
    "code": "def create_a10_device_instance(self, context, a10_device_instance):\n        LOG.debug(\"A10DeviceInstancePlugin.create(): a10_device_instance=%s\", a10_device_instance)\n        config = a10_config.A10Config()\n        vthunder_defaults = config.get_vthunder_config()\n        imgr = instance_manager.InstanceManager.from_config(config, context)\n        dev_instance = common_resources.remove_attributes_not_specified(\n            a10_device_instance.get(resources.RESOURCE))\n        vthunder_config = vthunder_defaults.copy()\n        vthunder_config.update(_convert(dev_instance, _API, _VTHUNDER_CONFIG))\n        instance = imgr.create_device_instance(vthunder_config, dev_instance.get(\"name\"))\n        db_record = {}\n        db_record.update(_convert(vthunder_config, _VTHUNDER_CONFIG, _DB))\n        db_record.update(_convert(dev_instance, _API, _DB))\n        db_record.update(_convert(instance, _INSTANCE, _DB))\n        db_instance = super(A10DeviceInstancePlugin, self).create_a10_device_instance(\n            context, {resources.RESOURCE: db_record})\n        return _make_api_dict(db_instance)",
    "docstring": "Attempt to create instance using neutron context"
  },
  {
    "code": "def C00_(self):\n        self._check_estimated()\n        return self._rc.cov_XX(bessel=self.bessel)",
    "docstring": "Instantaneous covariance matrix"
  },
  {
    "code": "def convertDate(self, date, prefix=\"\", weekday=False):\n        dayString = self.convertDay(\n            date, prefix=prefix, weekday=weekday)\n        timeString = self.convertTime(date)\n        return dayString + \" at \" + timeString",
    "docstring": "Convert a datetime object representing into a human-ready\n        string that can be read, spoken aloud, etc. In effect, runs\n        both convertDay and convertTime on the input, merging the results.\n\n        Args:\n            date (datetime.date): A datetime object to be converted into text.\n            prefix (str): An optional argument that prefixes the converted\n                string. For example, if prefix=\"in\", you'd receive \"in two\n                days\", rather than \"two days\", while the method would still\n                return \"tomorrow\" (rather than \"in tomorrow\").\n            weekday (bool): An optional argument that returns \"Monday, Oct. 1\"\n                if True, rather than \"Oct. 1\".\n\n        Returns:\n            A string representation of the input day and time."
  },
  {
    "code": "def find_author(self):\n        return Author(name=self.context.capture('git', 'config', 'user.name', check=False, silent=True),\n                      email=self.context.capture('git', 'config', 'user.email', check=False, silent=True))",
    "docstring": "Get the author information from the version control system."
  },
  {
    "code": "def _HasAccessToClient(self, subject, token):\n    client_id, _ = rdfvalue.RDFURN(subject).Split(2)\n    client_urn = rdf_client.ClientURN(client_id)\n    return self.CheckClientAccess(token, client_urn)",
    "docstring": "Checks if user has access to a client under given URN."
  },
  {
    "code": "def getAnalysisServicesDisplayList(self):\n        bsc = getToolByName(self, 'bika_setup_catalog')\n        items = [('', '')] + [(o.getObject().Keyword, o.Title) for o in\n                                bsc(portal_type = 'AnalysisService',\n                                    is_active = True)]\n        items.sort(lambda x, y: cmp(x[1].lower(), y[1].lower()))\n        return DisplayList(list(items))",
    "docstring": "Returns a Display List with the active Analysis Services\n            available. The value is the keyword and the title is the\n            text to be displayed."
  },
  {
    "code": "def FetchDiscoveryDoc(discovery_url, retries=5):\n    discovery_urls = _NormalizeDiscoveryUrls(discovery_url)\n    discovery_doc = None\n    last_exception = None\n    for url in discovery_urls:\n        for _ in range(retries):\n            try:\n                content = _GetURLContent(url)\n                if isinstance(content, bytes):\n                    content = content.decode('utf8')\n                discovery_doc = json.loads(content)\n                break\n            except (urllib_error.HTTPError, urllib_error.URLError) as e:\n                logging.info(\n                    'Attempting to fetch discovery doc again after \"%s\"', e)\n                last_exception = e\n    if discovery_doc is None:\n        raise CommunicationError(\n            'Could not find discovery doc at any of %s: %s' % (\n                discovery_urls, last_exception))\n    return discovery_doc",
    "docstring": "Fetch the discovery document at the given url."
  },
  {
    "code": "def int_to_rgba(cls, rgba_int):\n        if rgba_int is None:\n            return None, None, None, None\n        alpha = rgba_int % 256\n        blue = rgba_int / 256 % 256\n        green = rgba_int / 256 / 256 % 256\n        red = rgba_int / 256 / 256 / 256 % 256\n        return (red, green, blue, alpha)",
    "docstring": "Converts a color Integer into r, g, b, a tuple."
  },
  {
    "code": "def get_paginated_response(self, data):\n        return Response({\n            'next': self.get_next_link(),\n            'previous': self.get_previous_link(),\n            'count': self.page.paginator.count,\n            'num_pages': self.page.paginator.num_pages,\n            'current_page': self.page.number,\n            'start': (self.page.number - 1) * self.get_page_size(self.request),\n            'results': data\n        })",
    "docstring": "Annotate the response with pagination information."
  },
  {
    "code": "def copy(self):\n        return RigidTransform(np.copy(self.rotation), np.copy(self.translation), self.from_frame, self.to_frame)",
    "docstring": "Returns a copy of the RigidTransform.\n\n        Returns\n        -------\n        :obj:`RigidTransform`\n            A deep copy of the RigidTransform."
  },
  {
    "code": "def parse_coach_go(infile):\n    go_list = []\n    with open(infile) as go_file:\n        for line in go_file.readlines():\n            go_dict = {}\n            go_split = line.split()\n            go_dict['go_id'] = go_split[0]\n            go_dict['c_score'] = go_split[1]\n            go_dict['go_term'] = ' '.join(go_split[2:])\n            go_list.append(go_dict)\n    return go_list",
    "docstring": "Parse a GO output file from COACH and return a rank-ordered list of GO term predictions\n\n    The columns in all files are: GO terms, Confidence score, Name of GO terms. The files are:\n        \n        - GO_MF.dat - GO terms in 'molecular function'\n        - GO_BP.dat - GO terms in 'biological process'\n        - GO_CC.dat - GO terms in 'cellular component'\n\n    Args:\n        infile (str): Path to any COACH GO prediction file\n\n    Returns:\n        Pandas DataFrame: Organized dataframe of results, columns defined below\n            \n            - ``go_id``: GO term ID\n            - ``go_term``: GO term text\n            - ``c_score``: confidence score of the GO prediction"
  },
  {
    "code": "def main():\r\n    conf.init(), db.init(conf.DbPath)\r\n    inqueue = LineQueue(sys.stdin).queue\r\n    outqueue = type(\"\", (), {\"put\": lambda self, x: print(\"\\r%s\" % x, end=\" \")})()\r\n    if \"--quiet\" in sys.argv: outqueue = None\r\n    if conf.MouseEnabled:    inqueue.put(\"mouse_start\")\r\n    if conf.KeyboardEnabled: inqueue.put(\"keyboard_start\")\r\n    start(inqueue, outqueue)",
    "docstring": "Entry point for stand-alone execution."
  },
  {
    "code": "def get_simple_date(datestring):\n    simple_date = re.compile(r\"\\d{1,2}(\\.)\\d{1,2}\")\n    date = simple_date.search(datestring)\n    if date:\n        dates = date.group().split(\".\")\n        if len(dates[0]) == 1:\n            dates[0] = add_zero(dates[0])\n        if len(dates[1]) == 1:\n            dates[1] = add_zero(dates[1])\n        if date_is_valid(dates):\n            return '.'.join(dates) + '.'\n        return \"Failed\"",
    "docstring": "Transforms a datestring into shorter date 7.9.2017 > 07.09\n\n    Expects the datestring to be format 07.09.2017. If this is not the\n    case, returns string \"Failed\".\n\n    Keyword arguments:\n    datestring -- a string\n\n    Returns:\n    String -- The date in format \"dd.MM.\" or \"Failed\""
  },
  {
    "code": "def add_lb_nodes(self, lb_id, nodes):\n        log.info(\"Adding load balancer nodes %s\" % nodes)\n        resp, body = self._request(\n                'post', \n                '/loadbalancers/%s/nodes' % lb_id,\n                data={'nodes': nodes})\n        return body",
    "docstring": "Adds nodes to an existing LBaaS instance\n\n        :param string lb_id:  Balancer id\n\n        :param list nodes:  Nodes to add. {address, port, [condition]}\n\n        :rtype :class:`list`"
  },
  {
    "code": "def get_least_common_subsumer(self,from_tid,to_tid):\n        termid_from = self.terminal_for_term.get(from_tid)\n        termid_to = self.terminal_for_term.get(to_tid)\n        path_from = self.paths_for_terminal[termid_from][0]\n        path_to = self.paths_for_terminal[termid_to][0]\n        common_nodes = set(path_from) & set(path_to)\n        if len(common_nodes) == 0:\n            return None\n        else:\n            indexes = []\n            for common_node in common_nodes:\n                index1 = path_from.index(common_node)\n                index2 = path_to.index(common_node)\n                indexes.append((common_node,index1+index2))\n            indexes.sort(key=itemgetter(1))\n            shortest_common = indexes[0][0]\n            return shortest_common",
    "docstring": "Returns the deepest common subsumer among two terms\n        @type from_tid: string\n        @param from_tid: one term id\n        @type to_tid: string\n        @param to_tid: another term id\n        @rtype: string\n        @return: the term identifier of the common subsumer"
  },
  {
    "code": "def footer(self):\n        return self.footer_left(on=False), self.footer_center(on=False), \\\n               self.footer_right(on=False)",
    "docstring": "Returns the axis instance where the footer will be printed"
  },
  {
    "code": "def perform(self):\n        if self._driver.w3c:\n            self.w3c_actions.perform()\n        else:\n            for action in self._actions:\n                action()",
    "docstring": "Performs all stored actions."
  },
  {
    "code": "def start(self, service):\n        try:\n            map(self.start_class, service.depends)\n            if service.is_running():\n                return\n            if service in self.failed:\n                log.warning(\"%s previously failed to start\", service)\n                return\n            service.start()\n        except Exception:\n            log.exception(\"Unable to start service %s\", service)\n            self.failed.add(service)",
    "docstring": "Start the service, catching and logging exceptions"
  },
  {
    "code": "def get_leads(self, offset=None, limit=None, lead_list_id=None,\n                  first_name=None, last_name=None, email=None, company=None,\n                  phone_number=None, twitter=None):\n        args = locals()\n        args_params = dict((key, value) for key, value in args.items() if value\n                           is not None)\n        args_params.pop('self')\n        params = self.base_params\n        params.update(args_params)\n        endpoint = self.base_endpoint.format('leads')\n        return self._query_hunter(endpoint, params)",
    "docstring": "Gives back all the leads saved in your account.\n\n        :param offset: Number of leads to skip.\n\n        :param limit: Maximum number of leads to return.\n\n        :param lead_list_id: Id of a lead list to query leads on.\n\n        :param first_name: First name to filter on.\n\n        :param last_name: Last name to filter on.\n\n        :param email: Email to filter on.\n\n        :param company: Company to filter on.\n\n        :param phone_number: Phone number to filter on.\n\n        :param twitter: Twitter account to filter on.\n\n        :return: All leads found as a dict."
  },
  {
    "code": "def files(self):\n        ios_names = [info.name for info in self._ios_to_add.keys()]\n        return set(self.files_to_add + ios_names)",
    "docstring": "files that will be add to tar file later\n        should be tuple, list or generator that returns strings"
  },
  {
    "code": "def has_level_label(label_flags, vmin):\n    if label_flags.size == 0 or (label_flags.size == 1 and\n                                 label_flags[0] == 0 and\n                                 vmin % 1 > 0.0):\n        return False\n    else:\n        return True",
    "docstring": "Returns true if the ``label_flags`` indicate there is at least one label\n    for this level.\n\n    if the minimum view limit is not an exact integer, then the first tick\n    label won't be shown, so we must adjust for that."
  },
  {
    "code": "def add_arguments(cls, parser, sys_arg_list=None):\n        parser.add_argument('-f', '--file', dest='file', required=True,\n                            help=\"config file for routing groups \"\n                                 \"(only in configfile mode)\")\n        return [\"file\"]",
    "docstring": "Arguments for the configfile mode."
  },
  {
    "code": "def reference_fasta(self):\n        if self._db_location:\n            ref_files = glob.glob(os.path.join(self._db_location, \"*\", self._REF_FASTA))\n            if ref_files:\n                return ref_files[0]",
    "docstring": "Absolute path to the fasta file with EricScript reference data."
  },
  {
    "code": "def getWord(self, pattern, returnDiff = 0):\n        minDist = 10000\n        closest = None\n        for w in self.patterns:\n            if type(self.patterns[w]) in [int, float, int]: continue\n            if len(self.patterns[w]) == len(pattern):\n                dist = reduce(operator.add, [(a - b) ** 2 for (a,b) in zip(self.patterns[w], pattern )])\n                if dist == 0.0:\n                    if returnDiff:\n                        return w, dist\n                    else:\n                        return w\n                if dist < minDist:\n                    minDist = dist\n                    closest = w\n        if returnDiff:\n            return closest, minDist\n        else:\n            return closest",
    "docstring": "Returns the word associated with pattern.\n\n        Example: net.getWord([0, 0, 0, 1]) => \"tom\"\n\n        This method now returns the closest pattern based on distance."
  },
  {
    "code": "def is_svn_page(html):\n    return (re.search(r'<title>[^<]*Revision \\d+:', html) and\n            re.search(r'Powered by (?:<a[^>]*?>)?Subversion', html, re.I))",
    "docstring": "Returns true if the page appears to be the index page of an svn repository"
  },
  {
    "code": "def _file_path(self, dirname, filename):\n        if not os.path.exists(dirname):\n            try:\n                os.makedirs(dirname)\n            except KeyboardInterrupt as e:\n                raise e\n            except Exception:\n                pass\n        fpath = os.path.join(dirname, filename)\n        if not os.path.exists(fpath):\n            try:\n                open(fpath, \"w\").close()\n            except KeyboardInterrupt as e:\n                raise e\n            except Exception:\n                pass\n        return fpath",
    "docstring": "Builds an absolute path and creates the directory and file if they don't already exist.\n\n        @dirname  - Directory path.\n        @filename - File name.\n\n        Returns a full path of 'dirname/filename'."
  },
  {
    "code": "def to_latex(self):\n        latex = r\"[{} \" \n        for attribute, value in self:\n            if attribute in ['speaker_model', 'is_in_commonground']: continue\n            value_l = value.to_latex()\n            if value_l == \"\": continue\n            latex += \"{attribute:<15} &  {value:<20} \\\\\\\\ \\n\".format(attribute=attribute, value=value_l)\n        latex += \"]\\n\"\n        return latex",
    "docstring": "Returns a LaTeX representation of an attribute-value matrix"
  },
  {
    "code": "def as_a_dict(self):\n        index_dict = {\n            'ddoc': self._ddoc_id,\n            'name': self._name,\n            'type': self._type,\n            'def': self._def\n        }\n        if self._partitioned:\n            index_dict['partitioned'] = True\n        return index_dict",
    "docstring": "Displays the index as a dictionary.  This includes the design document\n        id, index name, index type, and index definition.\n\n        :returns: Dictionary representation of the index as a dictionary"
  },
  {
    "code": "def render_authenticateLinks(self, ctx, data):\n        if self.username is not None:\n            return ''\n        from xmantissa.signup import _getPublicSignupInfo\n        IQ = inevow.IQ(ctx.tag)\n        signupPattern = IQ.patternGenerator('signup-link')\n        signups = []\n        for (prompt, url) in _getPublicSignupInfo(self.store):\n            signups.append(signupPattern.fillSlots(\n                    'prompt', prompt).fillSlots(\n                    'url', url))\n        return ctx.tag[signups]",
    "docstring": "For unauthenticated users, add login and signup links to the given tag.\n        For authenticated users, remove the given tag from the output.\n\n        When necessary, the I{signup-link} pattern will be loaded from the tag.\n        Each copy of it will have I{prompt} and I{url} slots filled.  The list\n        of copies will be added as children of the tag."
  },
  {
    "code": "def add_automation_link(testcase):\n    automation_link = (\n        '<a href=\"{}\">Test Source</a>'.format(testcase[\"automation_script\"])\n        if testcase.get(\"automation_script\")\n        else \"\"\n    )\n    testcase[\"description\"] = \"{}<br/>{}\".format(testcase.get(\"description\") or \"\", automation_link)",
    "docstring": "Appends link to automation script to the test description."
  },
  {
    "code": "def vcf2abook():\n    from argparse import ArgumentParser, FileType\n    from sys import stdin\n    parser = ArgumentParser(description='Converter from vCard to Abook syntax.')\n    parser.add_argument('infile', nargs='?', type=FileType('r'), default=stdin,\n                        help='Input vCard file (default: stdin)')\n    parser.add_argument('outfile', nargs='?', default=expanduser('~/.abook/addressbook'),\n                        help='Output Abook file (default: ~/.abook/addressbook)')\n    args = parser.parse_args()\n    Abook.abook_file(args.infile, args.outfile)",
    "docstring": "Command line tool to convert from vCard to Abook"
  },
  {
    "code": "def get_gicon(self, icon_id: str) -> \"Gio.Icon\":\n        return Gio.ThemedIcon.new_from_names(self._icon_names[icon_id])",
    "docstring": "Lookup Gio.Icon from udiskie-internal id."
  },
  {
    "code": "def video(self):\n        if self._video is None:\n            from twilio.rest.video import Video\n            self._video = Video(self)\n        return self._video",
    "docstring": "Access the Video Twilio Domain\n\n        :returns: Video Twilio Domain\n        :rtype: twilio.rest.video.Video"
  },
  {
    "code": "def call_actions_parallel(self, service_name, actions, **kwargs):\n        return self.call_actions_parallel_future(service_name, actions, **kwargs).result()",
    "docstring": "Build and send multiple job requests to one service, each job with one action, to be executed in parallel, and\n        return once all responses have been received.\n\n        Returns a list of action responses, one for each action in the same order as provided, or raises an exception\n        if any action response is an error (unless `raise_action_errors` is passed as `False`) or if any job response\n        is an error (unless `raise_job_errors` is passed as `False`).\n\n        This method performs expansions if the Client is configured with an expansion converter.\n\n        :param service_name: The name of the service to call\n        :type service_name: union[str, unicode]\n        :param actions: A list of `ActionRequest` objects and/or dicts that can be converted to `ActionRequest` objects\n        :type actions: iterable[union[ActionRequest, dict]]\n        :param expansions: A dictionary representing the expansions to perform\n        :type expansions: dict\n        :param raise_action_errors: Whether to raise a CallActionError if any action responses contain errors (defaults\n                                    to `True`)\n        :type raise_action_errors: bool\n        :param timeout: If provided, this will override the default transport timeout values to; requests will expire\n                        after this number of seconds plus some buffer defined by the transport, and the client will not\n                        block waiting for a response for longer than this amount of time.\n        :type timeout: int\n        :param switches: A list of switch value integers\n        :type switches: list\n        :param correlation_id: The request correlation ID\n        :type correlation_id: union[str, unicode]\n        :param continue_on_error: Whether to continue executing further actions once one action has returned errors\n        :type continue_on_error: bool\n        :param context: A dictionary of extra values to include in the context header\n        :type context: dict\n        :param control_extra: A dictionary of extra values to include in the control header\n        :type control_extra: dict\n\n        :return: A generator of action responses\n        :rtype: Generator[ActionResponse]\n\n        :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge,\n                MessageReceiveError, MessageReceiveTimeout, InvalidMessage, JobError, CallActionError"
  },
  {
    "code": "def load_json_fixture(fixture_path: str) -> Dict[str, Any]:\n    with open(fixture_path) as fixture_file:\n        file_fixtures = json.load(fixture_file)\n    return file_fixtures",
    "docstring": "Loads a fixture file, caching the most recent files it loaded."
  },
  {
    "code": "def update_elements(self, line, column, charcount, docdelta=0):\n        target = self.charindex(line, column) + charcount\n        if line < self.contains_index:\n            for t in self.types:\n                if self._update_char_check(self.types[t], target, docdelta):\n                    self._element_charfix(self.types[t], charcount)\n            for m in self.members:\n                if self.members[m].start > target:\n                    self.members[m].start += charcount\n                    self.members[m].end += charcount\n            self._contains_index = None\n        else:\n            for iexec in self.executables:\n                if self._update_char_check(self.executables[iexec], target, docdelta):\n                    self._element_charfix(self.executables[iexec], charcount)",
    "docstring": "Updates all the element instances that are children of this module\n        to have new start and end charindex values based on an operation that\n        was performed on the module source code.\n\n        :arg line: the line number of the *start* of the operation.\n        :arg column: the column number of the start of the operation.\n        :arg charcount: the total character length change from the operation.\n        :arg docdelta: the character length of changes made to types/execs\n          that are children of the module whose docstrings external to their\n          definitions were changed."
  },
  {
    "code": "def set_env(self):\n        if self.cov_source is None:\n            os.environ['COV_CORE_SOURCE'] = ''\n        else:\n            os.environ['COV_CORE_SOURCE'] = UNIQUE_SEP.join(self.cov_source)\n        os.environ['COV_CORE_DATA_FILE'] = self.cov_data_file\n        os.environ['COV_CORE_CONFIG'] = self.cov_config",
    "docstring": "Put info about coverage into the env so that subprocesses can activate coverage."
  },
  {
    "code": "def get_workspace_activities(brain, limit=1):\n    mb = queryUtility(IMicroblogTool)\n    items = mb.context_values(brain.getObject(), limit=limit)\n    return [\n        {\n            'subject': item.creator,\n            'verb': 'published',\n            'object': item.text,\n            'time': {\n                'datetime': item.date.strftime('%Y-%m-%d'),\n                'title': item.date.strftime('%d %B %Y, %H:%M'),\n            }\n        } for item in items\n    ]",
    "docstring": "Return the workspace activities sorted by reverse chronological\n    order\n\n    Regarding the time value:\n     - the datetime value contains the time in international format\n       (machine readable)\n     - the title value contains the absolute date and time of the post"
  },
  {
    "code": "def _check_jp2h_child_boxes(self, boxes, parent_box_name):\n        JP2H_CHILDREN = set(['bpcc', 'cdef', 'cmap', 'ihdr', 'pclr'])\n        box_ids = set([box.box_id for box in boxes])\n        intersection = box_ids.intersection(JP2H_CHILDREN)\n        if len(intersection) > 0 and parent_box_name not in ['jp2h', 'jpch']:\n            msg = \"A {0} box can only be nested in a JP2 header box.\"\n            raise IOError(msg.format(list(intersection)[0]))\n        for box in boxes:\n            if hasattr(box, 'box'):\n                self._check_jp2h_child_boxes(box.box, box.box_id)",
    "docstring": "Certain boxes can only reside in the JP2 header."
  },
  {
    "code": "def scale(self, by):\n        self.points *= np.asarray([by])\n        self._adjust_ports()",
    "docstring": "Scale the points in the Pattern.\n\n        Parameters\n        ----------\n        by : float or np.ndarray, shape=(3,)\n            The factor to scale by. If a scalar, scale all directions isotropically.\n            If np.ndarray, scale each direction independently."
  },
  {
    "code": "def install_PMK(self):\n        self.pmk = PBKDF2HMAC(\n            algorithm=hashes.SHA1(),\n            length=32,\n            salt=self.ssid.encode(),\n            iterations=4096,\n            backend=default_backend(),\n        ).derive(self.passphrase.encode())",
    "docstring": "Compute and install the PMK"
  },
  {
    "code": "def _read(self, delta=0, wrap=False, strict=False):\n        index = self._head + delta\n        if index < 0 and (not wrap or abs(index) > len(self._text)):\n            return self.START\n        try:\n            return self._text[index]\n        except IndexError:\n            if strict:\n                self._fail_route()\n            return self.END",
    "docstring": "Read the value at a relative point in the wikicode.\n\n        The value is read from :attr:`self._head <_head>` plus the value of\n        *delta* (which can be negative). If *wrap* is ``False``, we will not\n        allow attempts to read from the end of the string if ``self._head +\n        delta`` is negative. If *strict* is ``True``, the route will be failed\n        (with :meth:`_fail_route`) if we try to read from past the end of the\n        string; otherwise, :attr:`self.END <END>` is returned. If we try to\n        read from before the start of the string, :attr:`self.START <START>` is\n        returned."
  },
  {
    "code": "def pypy_json_encode(value, pretty=False):\n    global _dealing_with_problem\n    if pretty:\n        return pretty_json(value)\n    try:\n        _buffer = UnicodeBuilder(2048)\n        _value2json(value, _buffer)\n        output = _buffer.build()\n        return output\n    except Exception as e:\n        from mo_logs import Log\n        if _dealing_with_problem:\n            Log.error(\"Serialization of JSON problems\", e)\n        else:\n            Log.warning(\"Serialization of JSON problems\", e)\n        _dealing_with_problem = True\n        try:\n            return pretty_json(value)\n        except Exception as f:\n            Log.error(\"problem serializing object\", f)\n        finally:\n            _dealing_with_problem = False",
    "docstring": "pypy DOES NOT OPTIMIZE GENERATOR CODE WELL"
  },
  {
    "code": "def keys_create(gandi, fqdn, flag):\n    key_info = gandi.dns.keys_create(fqdn, int(flag))\n    output_keys = ['uuid', 'algorithm', 'algorithm_name', 'ds', 'fingerprint',\n                   'public_key', 'flags', 'tag', 'status']\n    output_generic(gandi, key_info, output_keys, justify=15)\n    return key_info",
    "docstring": "Create key for a domain."
  },
  {
    "code": "def get_scene_suggestions(self, current):\n        l = []\n        if isinstance(current, djadapter.models.Asset):\n            l.append(current)\n        l.extend(list(current.assets.all()))\n        return l",
    "docstring": "Return a list with elements for reftracks for the current scene with this type.\n\n        For every element returned, the reftrack system will create a :class:`Reftrack` with the type\n        of this interface, if it is not already in the scene.\n\n        E.g. if you have a type that references whole scenes, you might suggest all\n        linked assets for shots, and all liked assets plus the current element itself for assets.\n        If you have a type like shader, that usually need a parent, you would return an empty list.\n        Cameras might only make sense for shots and not for assets etc.\n\n        Do not confuse this with :meth:`ReftypeInterface.get_suggestions`. It will gather suggestions\n        for children of a :class:`Reftrack`.\n\n        The standard implementation only returns an empty list!\n\n        :param reftrack: the reftrack which needs suggestions\n        :type reftrack: :class:`Reftrack`\n        :returns: list of suggestions, tuples of type and element.\n        :rtype: list\n        :raises: None"
  },
  {
    "code": "def write(self,fitsname=None,wcs=None,archive=True,overwrite=False,quiet=True):\n        self.update()\n        image = self.rootname\n        _fitsname = fitsname\n        if image.find('.fits') < 0 and _fitsname is not None:\n            self.geisname = image\n            image = self.rootname = _fitsname\n        fimg = fileutil.openImage(image, mode='update', fitsname=_fitsname)\n        _root,_iextn = fileutil.parseFilename(image)\n        _extn = fileutil.getExtn(fimg,_iextn)\n        if wcs:\n            _wcsobj = wcs\n        else:\n            _wcsobj = self\n        for key in _wcsobj.wcstrans.keys():\n            _dkey = _wcsobj.wcstrans[key]\n            if _dkey != 'pscale':\n                _extn.header[key] = _wcsobj.__dict__[_dkey]\n        fimg.close()\n        del fimg\n        if archive:\n            self.write_archive(fitsname=fitsname,overwrite=overwrite,quiet=quiet)",
    "docstring": "Write out the values of the WCS keywords to the\n        specified image.\n\n        If it is a GEIS image and 'fitsname' has been provided,\n        it will automatically make a multi-extension\n        FITS copy of the GEIS and update that file. Otherwise, it\n        throw an Exception if the user attempts to directly update\n        a GEIS image header.\n\n        If archive=True, also write out archived WCS keyword values to file.\n        If overwrite=True, replace archived WCS values in file with new values.\n\n        If a WCSObject is passed through the 'wcs' keyword, then the WCS keywords\n        of this object are copied to the header of the image to be updated. A use case\n        fo rthis is updating the WCS of a WFPC2 data quality (_c1h.fits) file\n        in order to be in sync with the science (_c0h.fits) file."
  },
  {
    "code": "def clean_inconcs(self):\n        for item in self.data:\n            if (item.inconclusive or item.get_verdict() == \"unknown\") and not item.retries_left > 0:\n                return True\n        return False",
    "docstring": "Check if there are any inconclusives or uknowns that were not subsequently retried.\n\n        :return: Boolean"
  },
  {
    "code": "def _create_Z(self,Y):\n        Z = np.ones(((self.ylen*self.lags +1),Y[0].shape[0]))\n        return self.create_design_matrix(Z, self.data, Y.shape[0], self.lags)",
    "docstring": "Creates design matrix holding the lagged variables\n\n        Parameters\n        ----------\n        Y : np.array\n            The dependent variables Y\n\n        Returns\n        ----------\n        The design matrix Z"
  },
  {
    "code": "def _callFunc(session, funcName, password, args):\n    txid = _randomString()\n    sock = session.socket\n    sock.send(bytearray('d1:q6:cookie4:txid10:%se' % txid, 'utf-8'))\n    msg = _getMessage(session, txid)\n    cookie = msg['cookie']\n    txid = _randomString()\n    tohash = (password + cookie).encode('utf-8')\n    req = {\n        'q': funcName,\n        'hash': hashlib.sha256(tohash).hexdigest(),\n        'cookie': cookie,\n        'args': args,\n        'txid': txid\n    }\n    if password:\n        req['aq'] = req['q']\n        req['q'] = 'auth'\n        reqBenc = bencode(req).encode('utf-8')\n        req['hash'] = hashlib.sha256(reqBenc).hexdigest()\n    reqBenc = bencode(req)\n    sock.send(bytearray(reqBenc, 'utf-8'))\n    return _getMessage(session, txid)",
    "docstring": "Call custom cjdns admin function"
  },
  {
    "code": "def structureOutput(fileUrl, fileName, searchFiles, format=True, space=40):\n\tif format:\n\t\tsplitUrls = fileUrl[1:].split('/')\n\t\tfileUrl = \"\"\n\t\tfor splitUrl in splitUrls:\n\t\t\tif splitUrl != \"\" and (not \".\" in splitUrl) and (splitUrl != \"pub\" and splitUrl != \"files\"):\n\t\t\t\tfileUrl += splitUrl + '/'\n\t\t\telif \".\" in splitUrl:\n\t\t\t\tarchiveName = splitUrl\n\tif searchFiles:\n\t\tfileName = archiveName\n\tpause = (space - len(fileUrl))\n\toutput = fileUrl\n\toutput += (\" \" * pause)\n\toutput += fileName\n\treturn output",
    "docstring": "Formats the output of a list of packages"
  },
  {
    "code": "def create(cls, key, crt):\n        options = {'crt': crt, 'key': key}\n        return cls.call('cert.hosted.create', options)",
    "docstring": "Add a new crt in the hosted cert store."
  },
  {
    "code": "def add_range(self, start, part_len, total_len):\n        content_range = 'bytes {0}-{1}/{2}'.format(start,\n                                                   start + part_len - 1,\n                                                   total_len)\n        self.statusline = '206 Partial Content'\n        self.replace_header('Content-Range', content_range)\n        self.replace_header('Content-Length', str(part_len))\n        self.replace_header('Accept-Ranges', 'bytes')\n        return self",
    "docstring": "Add range headers indicating that this a partial response"
  },
  {
    "code": "def get_doc_id(document_pb, expected_prefix):\n    prefix, document_id = document_pb.name.rsplit(DOCUMENT_PATH_DELIMITER, 1)\n    if prefix != expected_prefix:\n        raise ValueError(\n            \"Unexpected document name\",\n            document_pb.name,\n            \"Expected to begin with\",\n            expected_prefix,\n        )\n    return document_id",
    "docstring": "Parse a document ID from a document protobuf.\n\n    Args:\n        document_pb (google.cloud.proto.firestore.v1beta1.\\\n            document_pb2.Document): A protobuf for a document that\n            was created in a ``CreateDocument`` RPC.\n        expected_prefix (str): The expected collection prefix for the\n            fully-qualified document name.\n\n    Returns:\n        str: The document ID from the protobuf.\n\n    Raises:\n        ValueError: If the name does not begin with the prefix."
  },
  {
    "code": "def _parse_example(serialized_example):\n  data_fields = {\n      \"inputs\": tf.VarLenFeature(tf.int64),\n      \"targets\": tf.VarLenFeature(tf.int64)\n  }\n  parsed = tf.parse_single_example(serialized_example, data_fields)\n  inputs = tf.sparse_tensor_to_dense(parsed[\"inputs\"])\n  targets = tf.sparse_tensor_to_dense(parsed[\"targets\"])\n  return inputs, targets",
    "docstring": "Return inputs and targets Tensors from a serialized tf.Example."
  },
  {
    "code": "def __autoconnect_signals(self):\n        dic = {}\n        for name in dir(self):\n            method = getattr(self, name)\n            if (not isinstance(method, collections.Callable)):\n                continue\n            assert(name not in dic)\n            dic[name] = method\n        for xml in self.view.glade_xmlWidgets:\n            xml.signal_autoconnect(dic)\n        if self.view._builder is not None:\n            self.view._builder_connect_signals(dic)",
    "docstring": "This is called during view registration, to autoconnect\n        signals in glade file with methods within the controller"
  },
  {
    "code": "def _assign_zones(self):\n        for zone_id in range(1, 5):\n            zone = \\\n                RainCloudyFaucetZone(\n                    parent=self._parent,\n                    controller=self._controller,\n                    faucet=self,\n                    zone_id=zone_id)\n            if zone not in self.zones:\n                self.zones.append(zone)",
    "docstring": "Assign all RainCloudyFaucetZone managed by faucet."
  },
  {
    "code": "def remember(empowered, powerupClass, interface):\n    className = fullyQualifiedName(powerupClass)\n    powerup = _StoredByName(store=empowered.store, className=className)\n    empowered.powerUp(powerup, interface)",
    "docstring": "Adds a powerup to ``empowered`` that will instantiate ``powerupClass``\n    with the empowered's store when adapted to the given interface.\n\n    :param empowered: The Empowered (Store or Item) to be powered up.\n    :type empowered: ``axiom.item.Empowered``\n    :param powerupClass: The class that will be powered up to.\n    :type powerupClass: class\n    :param interface: The interface of the powerup.\n    :type interface: ``zope.interface.Interface``\n    :returns: ``None``"
  },
  {
    "code": "def git_ls_remote(repo_dir, remote='origin', refs=None):\n    command = ['git', 'ls-remote', pipes.quote(remote)]\n    if refs:\n        if isinstance(refs, list):\n            command.extend(refs)\n        else:\n            command.append(refs)\n    raw = execute_git_command(command, repo_dir=repo_dir).splitlines()\n    output = [l.strip() for l in raw if l.strip()\n              and not l.strip().lower().startswith('from ')]\n    return {ref: commit_hash for commit_hash, ref in\n            [l.split(None, 1) for l in output]}",
    "docstring": "Run git ls-remote.\n\n    'remote' can be a remote ref in a local repo, e.g. origin,\n    or url of a remote repository.\n\n    Return format:\n\n    .. code-block:: python\n\n        {<ref1>: <commit_hash1>,\n         <ref2>: <commit_hash2>,\n         ...,\n         <refN>: <commit_hashN>,\n        }"
  },
  {
    "code": "def _startRelay(self, client):\n        process = client.transport.connector.process\n        for _, data in process.data:\n            client.dataReceived(data)\n        process.protocol = client\n        @process._endedDeferred.addBoth\n        def stopRelay(reason):\n            relay = client.transport\n            relay.loseConnection(reason)\n            connector = relay.connector\n            connector.connectionLost(reason)\n        return client",
    "docstring": "Start relaying data between the process and the protocol.\n        This method is called when the protocol is connected."
  },
  {
    "code": "def logpdf(self, mu):\n        if self.transform is not None:\n            mu = self.transform(mu)     \n        return -np.log(float(self.sigma0)) - (0.5*(mu-self.mu0)**2)/float(self.sigma0**2)",
    "docstring": "Log PDF for Normal prior\n\n        Parameters\n        ----------\n        mu : float\n            Latent variable for which the prior is being formed over\n\n        Returns\n        ----------\n        - log(p(mu))"
  },
  {
    "code": "def wquantiles(W, x, alphas=(0.25, 0.50, 0.75)):\n    if len(x.shape) == 1:\n        return _wquantiles(W, x, alphas=alphas)\n    elif len(x.shape) == 2: \n        return np.array([_wquantiles(W, x[:, i], alphas=alphas) \n                         for i in range(x.shape[1])])",
    "docstring": "Quantiles for weighted data.\n\n    Parameters\n    ----------\n    W: (N,) ndarray\n        normalised weights (weights are >=0 and sum to one)\n    x: (N,) or (N,d) ndarray\n        data\n    alphas: list-like of size k (default: (0.25, 0.50, 0.75))\n        probabilities (between 0. and 1.) \n\n    Returns\n    -------\n    a (k,) or (d, k) ndarray containing the alpha-quantiles"
  },
  {
    "code": "def write_response(\n        self, status_code: Union[int, constants.HttpStatusCode], *,\n        headers: Optional[_HeaderType]=None\n            ) -> \"writers.HttpResponseWriter\":\n        self._writer = self.__delegate.write_response(\n            constants.HttpStatusCode(status_code),\n            headers=headers)\n        return self._writer",
    "docstring": "Write a response to the client."
  },
  {
    "code": "def hline(level, **kwargs):\n    kwargs.setdefault('colors', ['dodgerblue'])\n    kwargs.setdefault('stroke_width', 1)\n    scales = kwargs.pop('scales', {})\n    fig = kwargs.get('figure', current_figure())\n    scales['x'] = fig.scale_x\n    level = array(level)\n    if len(level.shape) == 0:\n        x = [0, 1]\n        y = [level, level]\n    else:\n        x = [0, 1]\n        y = column_stack([level, level])\n    return plot(x, y, scales=scales, preserve_domain={\n        'x': True,\n        'y': kwargs.get('preserve_domain', False)\n    }, axes=False, update_context=False, **kwargs)",
    "docstring": "Draws a horizontal line at the given level.\n\n    Parameters\n    ----------\n    level: float\n        The level at which to draw the horizontal line.\n    preserve_domain: boolean (default: False)\n        If true, the line does not affect the domain of the 'y' scale."
  },
  {
    "code": "def pool_set_autostart(name, state='on', **kwargs):\n    conn = __get_conn(**kwargs)\n    try:\n        pool = conn.storagePoolLookupByName(name)\n        return not bool(pool.setAutostart(1 if state == 'on' else 0))\n    finally:\n        conn.close()",
    "docstring": "Set the autostart flag on a libvirt storage pool so that the storage pool\n    will start with the host system on reboot.\n\n    :param name: libvirt storage pool name\n    :param state: 'on' to auto start the pool, anything else to mark the\n                  pool not to be started when the host boots\n    :param connection: libvirt connection URI, overriding defaults\n    :param username: username to connect with, overriding defaults\n    :param password: password to connect with, overriding defaults\n\n    .. versionadded:: 2019.2.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt \"*\" virt.pool_set_autostart <pool> <on | off>"
  },
  {
    "code": "def _release_command_buffer(self, command_buffer):\n        if command_buffer.closed:\n            return\n        self._cb_poll.unregister(command_buffer.host_id)\n        self.connection_pool.release(command_buffer.connection)\n        command_buffer.connection = None",
    "docstring": "This is called by the command buffer when it closes."
  },
  {
    "code": "def detect_language(lang, kernel_source):\n    if lang is None:\n        if callable(kernel_source):\n            raise TypeError(\"Please specify language when using a code generator function\")\n        kernel_string = get_kernel_string(kernel_source)\n        if \"__global__\" in kernel_string:\n            lang = \"CUDA\"\n        elif \"__kernel\" in kernel_string:\n            lang = \"OpenCL\"\n        else:\n            lang = \"C\"\n    return lang",
    "docstring": "attempt to detect language from the kernel_string if not specified"
  },
  {
    "code": "def new():\n    dir_path = os.path.dirname(os.path.realpath(__file__))\n    cookiecutter(os.path.join(dir_path, 'historical-cookiecutter/'))",
    "docstring": "Creates a new historical technology."
  },
  {
    "code": "def generate_private_key(key_type):\n    if key_type == u'rsa':\n        return rsa.generate_private_key(\n            public_exponent=65537, key_size=2048, backend=default_backend())\n    raise ValueError(key_type)",
    "docstring": "Generate a random private key using sensible parameters.\n\n    :param str key_type: The type of key to generate. One of: ``rsa``."
  },
  {
    "code": "def get_request_headers(self):\n        request_headers = self.get_proxy_request_headers(self.request)\n        if (self.add_remote_user and hasattr(self.request, 'user')\n                and self.request.user.is_active):\n            request_headers['REMOTE_USER'] = self.request.user.get_username()\n            self.log.info(\"REMOTE_USER set\")\n        return request_headers",
    "docstring": "Return request headers that will be sent to upstream.\n\n        The header REMOTE_USER is set to the current user\n        if AuthenticationMiddleware is enabled and\n        the view's add_remote_user property is True.\n\n        .. versionadded:: 0.9.8"
  },
  {
    "code": "def display_items(self) -> typing.List[Display]:\n        return [Display(display_item) for display_item in self.__document_model.display_items]",
    "docstring": "Return the list of display items.\n\n        :return: The list of :py:class:`nion.swift.Facade.Display` objects.\n\n        .. versionadded:: 1.0\n\n        Scriptable: Yes"
  },
  {
    "code": "def rename_annotations(self, sentence):\n        annotations = []\n        for token in sentence:\n            data = {CLAUSE_IDX: token[CLAUSE_IDX]}\n            if CLAUSE_ANNOT in token:\n                if 'KINDEL_PIIR' in token[CLAUSE_ANNOT]:\n                    data[CLAUSE_ANNOTATION] = CLAUSE_BOUNDARY\n                elif 'KIILU_ALGUS' in token[CLAUSE_ANNOT]:\n                    data[CLAUSE_ANNOTATION] = EMBEDDED_CLAUSE_START\n                elif 'KIILU_LOPP' in token[CLAUSE_ANNOT]:\n                    data[CLAUSE_ANNOTATION] = EMBEDDED_CLAUSE_END\n            annotations.append(data)\n        return annotations",
    "docstring": "Function that renames and restructures clause information."
  },
  {
    "code": "async def dbpoolStats(self, *args, **kwargs):\n        return await self._makeApiCall(self.funcinfo[\"dbpoolStats\"], *args, **kwargs)",
    "docstring": "Statistics on the Database client pool\n\n        This method is only for debugging the ec2-manager\n\n        This method is ``experimental``"
  },
  {
    "code": "def untokenize(words):\n    text = ' '.join(words)\n    step1 = text.replace(\"`` \", '\"').replace(\" ''\", '\"').replace('. . .', '...')\n    step2 = step1.replace(\" ( \", \" (\").replace(\" ) \", \") \")\n    step3 = re.sub(r' ([.,:;?!%]+)([ \\'\"`])', r\"\\1\\2\", step2)\n    step4 = re.sub(r' ([.,:;?!%]+)$', r\"\\1\", step3)\n    step5 = step4.replace(\" '\", \"'\").replace(\" n't\", \"n't\").replace(\n        \"can not\", \"cannot\")\n    step6 = step5.replace(\" ` \", \" '\")\n    return step6.strip()",
    "docstring": "Untokenizing a text undoes the tokenizing operation, restoring\n    punctuation and spaces to the places that people expect them to be.\n\n    Ideally, `untokenize(tokenize(text))` should be identical to `text`,\n    except for line breaks."
  },
  {
    "code": "def hash_trees(self):\n        \"hash ladderized tree topologies\"       \n        observed = {}\n        for idx, tree in enumerate(self.treelist):\n            nwk = tree.write(tree_format=9)\n            hashed = md5(nwk.encode(\"utf-8\")).hexdigest()\n            if hashed not in observed:\n                observed[hashed] = idx\n                self.treedict[idx] = 1\n            else:\n                idx = observed[hashed]\n                self.treedict[idx] += 1",
    "docstring": "hash ladderized tree topologies"
  },
  {
    "code": "def start(self):\n        self._process = threading.Thread(target=self._background_runner)\n        self._process.start()",
    "docstring": "Create a background thread for httpd and serve 'forever"
  },
  {
    "code": "def setup(self, target=None, strict=False, minify=False, line_numbers=False, keep_lines=False, no_tco=False):\n        if target is None:\n            target = \"\"\n        else:\n            target = str(target).replace(\".\", \"\")\n        if target in pseudo_targets:\n            target = pseudo_targets[target]\n        if target not in targets:\n            raise CoconutException(\n                \"unsupported target Python version \" + ascii(target),\n                extra=\"supported targets are \" + ', '.join(ascii(t) for t in specific_targets) + \", or leave blank for universal\",\n            )\n        logger.log_vars(\"Compiler args:\", locals())\n        self.target, self.strict, self.minify, self.line_numbers, self.keep_lines, self.no_tco = (\n            target, strict, minify, line_numbers, keep_lines, no_tco,\n        )",
    "docstring": "Initializes parsing parameters."
  },
  {
    "code": "def fields_to_dict(self):\n        d = {}\n        for container in FieldsContainer.class_container.values():\n            fields = getattr(self, container)\n            if fields:\n                d[container] = [field.to_dict() for field in fields]\n        return d",
    "docstring": "Transform the object to a dict and return the dict."
  },
  {
    "code": "def set_until(self, frame, lineno=None):\n        if lineno is None:\n            lineno = frame.f_lineno + 1\n        self._set_stopinfo(frame, lineno)",
    "docstring": "Stop when the current line number in frame is greater than lineno or\n        when returning from frame."
  },
  {
    "code": "def featured_games(self, region):\n        url, query = SpectatorApiV4Urls.featured_games(region=region)\n        return self._raw_request(self.featured_games.__name__, region, url, query)",
    "docstring": "Get list of featured games.\n\n        :param string region: The region to execute this request on\n\n        :returns: FeaturedGames"
  },
  {
    "code": "def snapshot_agent(self):\n        protocols = [i.get_agent_side() for i in self._protocols.values()]\n        return (self.agent, protocols, )",
    "docstring": "Gives snapshot of everything related to the agent"
  },
  {
    "code": "def get_phi_variables(self, block_addr):\n        if block_addr not in self._phi_variables_by_block:\n            return dict()\n        variables = { }\n        for phi in self._phi_variables_by_block[block_addr]:\n            variables[phi] = self._phi_variables[phi]\n        return variables",
    "docstring": "Get a dict of phi variables and their corresponding variables.\n\n        :param int block_addr:  Address of the block.\n        :return:                A dict of phi variables of an empty dict if there are no phi variables at the block.\n        :rtype:                 dict"
  },
  {
    "code": "def is_last_attempt(request):\n    environ = request.environ\n    attempt = environ.get('retry.attempt')\n    attempts = environ.get('retry.attempts')\n    if attempt is None or attempts is None:\n        return True\n    return attempt + 1 == attempts",
    "docstring": "Return ``True`` if the request is on its last attempt, meaning that\n    ``pyramid_retry`` will not be issuing any new attempts, regardless of\n    what happens when executing this request.\n\n    This will return ``True`` if ``pyramid_retry`` is inactive for the\n    request."
  },
  {
    "code": "def get_default_attribute_value(cls, object_class, property_name, attr_type=str):\n        if not cls._default_attribute_values_configuration_file_path:\n            return None\n        if not cls._config_parser:\n            cls._read_config()\n        class_name = object_class.__name__\n        if not cls._config_parser.has_section(class_name):\n            return None\n        if not cls._config_parser.has_option(class_name, property_name):\n            return None\n        if sys.version_info < (3,):\n            integer_types = (int, long,)\n        else:\n            integer_types = (int,)\n        if isinstance(attr_type, integer_types):\n            return cls._config_parser.getint(class_name, property_name)\n        elif attr_type is bool:\n            return cls._config_parser.getboolean(class_name, property_name)\n        else:\n            return cls._config_parser.get(class_name, property_name)",
    "docstring": "Gets the default value of a given property for a given object.\n\n            These properties can be set in a config INI file looking like\n\n            .. code-block:: ini\n\n                [NUEntity]\n                default_behavior = THIS\n                speed = 1000\n\n                [NUOtherEntity]\n                attribute_name = a value\n\n            This will be used when creating a :class:`bambou.NURESTObject` when no parameter or data is provided"
  },
  {
    "code": "def all(self):\n        data = {}\n        args = self.request.arguments\n        for key, value in args.items():\n            data[key] = self.get_argument(key)\n        return data",
    "docstring": "Returns all the arguments passed with the request\n\n        Sample Usage\n        ++++++++++++\n        .. code:: python\n\n            from bast import Controller\n\n            class MyController(Controller):\n                def index(self):\n                    data = self.all()\n\n        Returns a dictionary of all the request arguments"
  },
  {
    "code": "def noise():\n    from random import gauss\n    v = Vector3(gauss(0, 1), gauss(0, 1), gauss(0, 1))\n    v.normalize()\n    return v * args.noise",
    "docstring": "a noise vector"
  },
  {
    "code": "def get_schema_path(self, path):\n        if path not in self.schemas:\n            raise JSONSchemaNotFound(path)\n        return os.path.join(self.schemas[path], path)",
    "docstring": "Compute the schema's absolute path from a schema relative path.\n\n        :param path: relative path of the schema.\n        :raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema\n            was found in the specified path.\n        :returns: The absolute path."
  },
  {
    "code": "def report_metric(metric_name: str, value: int, fail_silently: bool=True):\n    if metricz is None:\n        return\n    configuration = Configuration()\n    try:\n        lizzy_domain = urlparse(configuration.lizzy_url).netloc\n        lizzy_name, _ = lizzy_domain.split('.', 1)\n    except Exception:\n        lizzy_name = 'UNKNOWN'\n    tags = {\n        'version': VERSION,\n        'lizzy': lizzy_name\n    }\n    try:\n        writer = metricz.MetricWriter(url=configuration.token_url,\n                                      directory=configuration.credentials_dir,\n                                      fail_silently=False)\n        writer.write_metric(metric_name, value, tags, timeout=10)\n    except Exception:\n        if not fail_silently:\n            raise",
    "docstring": "Tries to report a metric, ignoring all errors"
  },
  {
    "code": "def NamedPlaceholders(iterable):\n  placeholders = \", \".join(\"%({})s\".format(key) for key in sorted(iterable))\n  return \"({})\".format(placeholders)",
    "docstring": "Returns named placeholders from all elements of the given iterable.\n\n  Use this function for VALUES of MySQL INSERTs.\n\n  To account for Iterables with undefined order (dicts before Python 3.6),\n  this function sorts column names.\n\n  Examples:\n    >>> NamedPlaceholders({\"password\": \"foo\", \"name\": \"bar\"})\n    u'(%(name)s, %(password)s)'\n\n  Args:\n    iterable: The iterable of strings to be used as placeholder keys.\n\n  Returns:\n    A string containing a tuple of comma-separated, sorted, named, placeholders."
  },
  {
    "code": "def update(self, status=values.unset):\n        return self._proxy.update(status=status, )",
    "docstring": "Update the FaxInstance\n\n        :param FaxInstance.UpdateStatus status: The new status of the resource\n\n        :returns: Updated FaxInstance\n        :rtype: twilio.rest.fax.v1.fax.FaxInstance"
  },
  {
    "code": "def refreshTitles(self):\n        for index in range(self.count()):\n            widget = self.widget(index)\n            self.setTabText(index, widget.windowTitle())",
    "docstring": "Refreshes the titles for each view within this tab panel."
  },
  {
    "code": "def complete(self, msg):\n        if _debug: IOCB._debug(\"complete(%d) %r\", self.ioID, msg)\n        if self.ioController:\n            self.ioController.complete_io(self, msg)\n        else:\n            self.ioState = COMPLETED\n            self.ioResponse = msg\n            self.trigger()",
    "docstring": "Called to complete a transaction, usually when ProcessIO has\n        shipped the IOCB off to some other thread or function."
  },
  {
    "code": "def _read_apps(self):\n        apps = {}\n        for cfgfile in glob.iglob(os.path.join(self.confdir, '*.conf')):\n            name = os.path.basename(cfgfile)[0:-5]\n            try:\n                app = AppLogParser(name, cfgfile, self.args, self.logdir,\n                                   self.fields, self.name_cache, self.report)\n            except (LogRaptorOptionError, LogRaptorConfigError, LogFormatError) as err:\n                logger.error('cannot add app %r: %s', name, err)\n            else:\n                apps[name] = app\n        if not apps:\n            raise LogRaptorConfigError('no configured application in %r!' % self.confdir)\n        return apps",
    "docstring": "Read the configuration of applications returning a dictionary\n\n        :return: A dictionary with application names as keys and configuration \\\n        object as values."
  },
  {
    "code": "def hostname(hn, ft, si):\n    if not hn or not hn.fqdn:\n        hn = ft\n    if hn and hn.fqdn:\n        fqdn = hn.fqdn\n        hostname = hn.hostname if hn.hostname else fqdn.split(\".\")[0]\n        domain = hn.domain if hn.domain else \".\".join(fqdn.split(\".\")[1:])\n        return Hostname(fqdn, hostname, domain)\n    else:\n        fqdn = si.get(\"profile_name\") if si else None\n        if fqdn:\n            hostname = fqdn.split(\".\")[0]\n            domain = \".\".join(fqdn.split(\".\")[1:])\n            return Hostname(fqdn, hostname, domain)\n    raise Exception(\"Unable to get hostname.\")",
    "docstring": "Check hostname, facter and systemid to get the fqdn, hostname and domain.\n\n    Prefer hostname to facter and systemid.\n\n    Returns:\n        insights.combiners.hostname.Hostname: A named tuple with `fqdn`,\n        `hostname` and `domain` components.\n\n    Raises:\n        Exception: If no hostname can be found in any of the three parsers."
  },
  {
    "code": "def calculate_entropy(self, entropy_string):\n        total = 0\n        for char in entropy_string:\n            if char.isalpha():\n                prob = self.frequency[char.lower()]\n                total += - math.log(prob) / math.log(2)\n        logging.debug(\"Entropy score: {0}\".format(total))\n        return total",
    "docstring": "Calculates the entropy of a string based on known frequency of\n        English letters.\n\n        Args:\n            entropy_string: A str representing the string to calculate.\n\n        Returns:\n            A negative float with the total entropy of the string (higher\n            is better)."
  },
  {
    "code": "def _maybe_match_name(a, b):\n    a_has = hasattr(a, 'name')\n    b_has = hasattr(b, 'name')\n    if a_has and b_has:\n        if a.name == b.name:\n            return a.name\n        else:\n            return None\n    elif a_has:\n        return a.name\n    elif b_has:\n        return b.name\n    return None",
    "docstring": "Try to find a name to attach to the result of an operation between\n    a and b.  If only one of these has a `name` attribute, return that\n    name.  Otherwise return a consensus name if they match of None if\n    they have different names.\n\n    Parameters\n    ----------\n    a : object\n    b : object\n\n    Returns\n    -------\n    name : str or None\n\n    See Also\n    --------\n    pandas.core.common.consensus_name_attr"
  },
  {
    "code": "def _parse_os_release(*os_release_files):\n    ret = {}\n    for filename in os_release_files:\n        try:\n            with salt.utils.files.fopen(filename) as ifile:\n                regex = re.compile('^([\\\\w]+)=(?:\\'|\")?(.*?)(?:\\'|\")?$')\n                for line in ifile:\n                    match = regex.match(line.strip())\n                    if match:\n                        ret[match.group(1)] = re.sub(\n                            r'\\\\([$\"\\'\\\\`])', r'\\1', match.group(2)\n                        )\n            break\n        except (IOError, OSError):\n            pass\n    return ret",
    "docstring": "Parse os-release and return a parameter dictionary\n\n    See http://www.freedesktop.org/software/systemd/man/os-release.html\n    for specification of the file format."
  },
  {
    "code": "def parse_source_file(filename):\n    with open(filename, 'rb') as fid:\n        content = fid.read()\n    content = content.replace(b'\\r\\n', b'\\n')\n    try:\n        node = ast.parse(content)\n        return node, content.decode('utf-8')\n    except SyntaxError:\n        return None, content.decode('utf-8')",
    "docstring": "Parse source file into AST node\n\n    Parameters\n    ----------\n    filename : str\n        File path\n\n    Returns\n    -------\n    node : AST node\n    content : utf-8 encoded string"
  },
  {
    "code": "def _download_mirbase(args, version=\"CURRENT\"):\n    if not args.hairpin or not args.mirna:\n        logger.info(\"Working with version %s\" % version)\n        hairpin_fn = op.join(op.abspath(args.out), \"hairpin.fa.gz\")\n        mirna_fn = op.join(op.abspath(args.out), \"miRNA.str.gz\")\n        if not file_exists(hairpin_fn):\n            cmd_h = \"wget ftp://mirbase.org/pub/mirbase/%s/hairpin.fa.gz -O %s &&  gunzip -f !$\" % (version, hairpin_fn)\n            do.run(cmd_h, \"download hairpin\")\n        if not file_exists(mirna_fn):\n            cmd_m = \"wget ftp://mirbase.org/pub/mirbase/%s/miRNA.str.gz -O %s && gunzip -f !$\" % (version, mirna_fn)\n            do.run(cmd_m, \"download mirna\")\n    else:\n        return args.hairpin, args.mirna",
    "docstring": "Download files from mirbase"
  },
  {
    "code": "def parse_band_log(self, message):\n        if \"payload\" in message and hasattr(message[\"payload\"], \"name\"):\n            record = message[\"payload\"]\n            for k in dir(record):\n                if k.startswith(\"workflows_exc_\"):\n                    setattr(record, k[14:], getattr(record, k))\n                    delattr(record, k)\n            for k, v in self.get_status().items():\n                setattr(record, \"workflows_\" + k, v)\n            logging.getLogger(record.name).handle(record)\n        else:\n            self.log.warning(\n                \"Received broken record on log band\\n\" + \"Message: %s\\nRecord: %s\",\n                str(message),\n                str(\n                    hasattr(message.get(\"payload\"), \"__dict__\")\n                    and message[\"payload\"].__dict__\n                ),\n            )",
    "docstring": "Process incoming logging messages from the service."
  },
  {
    "code": "def _read_para_hip_signature_2(self, code, cbit, clen, *, desc, length, version):\n        _algo = self._read_unpack(2)\n        _sign = self._read_fileng(clen-2)\n        hip_signature_2 = dict(\n            type=desc,\n            critical=cbit,\n            length=clen,\n            algorithm=_HI_ALGORITHM.get(_algo, 'Unassigned'),\n            signature=_sign,\n        )\n        _plen = length - clen\n        if _plen:\n            self._read_fileng(_plen)\n        return hip_signature_2",
    "docstring": "Read HIP HIP_SIGNATURE_2 parameter.\n\n        Structure of HIP HIP_SIGNATURE_2 parameter [RFC 7401]:\n             0                   1                   2                   3\n             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |             Type              |             Length            |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |    SIG alg                    |            Signature          /\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            /                               |             Padding           |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n            Octets      Bits        Name                            Description\n              0           0     hip_signature_2.type            Parameter Type\n              1          15     hip_signature_2.critical        Critical Bit\n              2          16     hip_signature_2.length          Length of Contents\n              4          32     hip_signature_2.algorithm       SIG Algorithm\n              6          48     hip_signature_2.signature       Signature\n              ?           ?     -                               Padding"
  },
  {
    "code": "def save_script_file_for_state_and_source_path(state, state_path_full, as_copy=False):\n    from rafcon.core.states.execution_state import ExecutionState\n    if isinstance(state, ExecutionState):\n        source_script_file = os.path.join(state.script.path, state.script.filename)\n        destination_script_file = os.path.join(state_path_full, SCRIPT_FILE)\n        try:\n            write_file(destination_script_file, state.script_text)\n        except Exception:\n            logger.exception(\"Storing of script file failed: {0} -> {1}\".format(state.get_path(),\n                                                                                destination_script_file))\n            raise\n        if not source_script_file == destination_script_file and not as_copy:\n            state.script.filename = SCRIPT_FILE\n            state.script.path = state_path_full",
    "docstring": "Saves the script file for a state to the directory of the state.\n\n    The script name will be set to the SCRIPT_FILE constant.\n\n    :param state: The state of which the script file should be saved\n    :param str state_path_full: The path to the file system storage location of the state\n    :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path"
  },
  {
    "code": "def _find_start_time(hdr, s_freq):\n    start_time = hdr['stc']['creation_time']\n    for one_stamp in hdr['stamps']:\n        if one_stamp['segment_name'].decode() == hdr['erd']['filename']:\n            offset = one_stamp['start_stamp']\n            break\n    erd_time = (hdr['erd']['creation_time'] -\n                timedelta(seconds=offset / s_freq)).replace(microsecond=0)\n    stc_erd_diff = (start_time - erd_time).total_seconds()\n    if stc_erd_diff > START_TIME_TOL:\n        lg.warn('Time difference between ERD and STC is {} s so using ERD time'\n                ' at {}'.format(stc_erd_diff, erd_time))\n        start_time = erd_time\n    return start_time",
    "docstring": "Find the start time, usually in STC, but if that's not correct, use ERD\n\n    Parameters\n    ----------\n    hdr : dict\n        header with stc (and stamps) and erd\n    s_freq : int\n        sampling frequency\n\n    Returns\n    -------\n    datetime\n        either from stc or from erd\n\n    Notes\n    -----\n    Sometimes, but rather rarely, there is a mismatch between the time in the\n    stc and the time in the erd. For some reason, the time in the stc is way\n    off (by hours), which is clearly not correct.\n\n    We can try to reconstruct the actual time, but looking at the ERD time\n    (of any file apart from the first one) and compute the original time back\n    based on the offset of the number of samples in stc. For some reason, this\n    is not the same for all the ERD, but the jitter is in the order of 1-2s\n    which is acceptable for our purposes (probably, but be careful about the\n    notes)."
  },
  {
    "code": "def _Execute(self, options):\n        whitelist = dict(\n            name=options[\"name\"],\n            description=options.get(\"description\", \"<empty>\"))\n        return self._agent.client.compute.security_groups.create(**whitelist)",
    "docstring": "Handles security groups operations."
  },
  {
    "code": "def set_value(self, pymux, value):\n        try:\n            value = int(value)\n            if value < 0:\n                raise ValueError\n        except ValueError:\n            raise SetOptionError('Expecting an integer.')\n        else:\n            setattr(pymux, self.attribute_name, value)",
    "docstring": "Take a string, and return an integer. Raise SetOptionError when the\n        given text does not parse to a positive integer."
  },
  {
    "code": "def genlmsg_valid_hdr(nlh, hdrlen):\n    if not nlmsg_valid_hdr(nlh, GENL_HDRLEN):\n        return False\n    ghdr = genlmsghdr(nlmsg_data(nlh))\n    if genlmsg_len(ghdr) < NLMSG_ALIGN(hdrlen):\n        return False\n    return True",
    "docstring": "Validate Generic Netlink message headers.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L117\n\n    Verifies the integrity of the Netlink and Generic Netlink headers by enforcing the following requirements:\n    - Valid Netlink message header (`nlmsg_valid_hdr()`)\n    - Presence of a complete Generic Netlink header\n    - At least `hdrlen` bytes of payload included after the generic Netlink header.\n\n    Positional arguments:\n    nlh -- Netlink message header (nlmsghdr class instance).\n    hdrlen -- length of user header (integer).\n\n    Returns:\n    True if the headers are valid or False if not."
  },
  {
    "code": "def changed_path(self):\n        \"Find any changed path and update all changed modification times.\"\n        result = None\n        for path in self.paths_to_modification_times:\n            lastmod = self.paths_to_modification_times[path]\n            mod = os.path.getmtime(path)\n            if mod > lastmod:\n                result = \"Watch file has been modified: \" + repr(path)\n            self.paths_to_modification_times[path] = mod\n        for folder in self.folder_paths:\n            for filename in os.listdir(folder):\n                subpath = os.path.join(folder, filename)\n                if os.path.isfile(subpath) and subpath not in self.paths_to_modification_times:\n                    result = \"New file in watched folder: \" + repr(subpath)\n                    self.add(subpath)\n        if self.check_python_modules:\n            self.add_all_modules()\n        if self.check_javascript:\n            self.watch_javascript()\n        return result",
    "docstring": "Find any changed path and update all changed modification times."
  },
  {
    "code": "def save(self, expires=None):\n        if expires is None:\n            expires = self.expires\n        s = self.serialize()\n        key = self._key(self._all_keys())\n        _cache.set(key, s, expires)",
    "docstring": "Save a copy of the object into the cache."
  },
  {
    "code": "def populateFromRow(self, referenceSetRecord):\n        self._dataUrl = referenceSetRecord.dataurl\n        self._description = referenceSetRecord.description\n        self._assemblyId = referenceSetRecord.assemblyid\n        self._isDerived = bool(referenceSetRecord.isderived)\n        self._md5checksum = referenceSetRecord.md5checksum\n        species = referenceSetRecord.species\n        if species is not None and species != 'null':\n            self.setSpeciesFromJson(species)\n        self._sourceAccessions = json.loads(\n            referenceSetRecord.sourceaccessions)\n        self._sourceUri = referenceSetRecord.sourceuri",
    "docstring": "Populates this reference set from the values in the specified DB\n        row."
  },
  {
    "code": "def _rev(repo):\n    try:\n        repo_info = dict(six.iteritems(CLIENT.info(repo['repo'])))\n    except (pysvn._pysvn.ClientError, TypeError,\n            KeyError, AttributeError) as exc:\n        log.error(\n            'Error retrieving revision ID for svnfs remote %s '\n            '(cachedir: %s): %s',\n            repo['url'], repo['repo'], exc\n        )\n    else:\n        return repo_info['revision'].number\n    return None",
    "docstring": "Returns revision ID of repo"
  },
  {
    "code": "def prepare(self):\n        super(RequestHandler, self).prepare()\n        if self.request.headers.get('content-type', '').startswith(self.JSON):\n            self.request.body = escape.json_decode(self.request.body)",
    "docstring": "Prepare the incoming request, checking to see the request is sending\n        JSON content in the request body. If so, the content is decoded and\n        assigned to the json_arguments attribute."
  },
  {
    "code": "def find_config(directory_or_file, debug=False):\n    directory_or_file = os.path.realpath(directory_or_file)\n    if os.path.isfile(directory_or_file):\n        if debug:\n            print('using config file {}'.format(directory_or_file),\n                  file=sys.stderr)\n        return directory_or_file\n    directory = directory_or_file\n    while directory:\n        for filename in CONFIG_FILES:\n            candidate = os.path.join(directory, filename)\n            if os.path.exists(candidate):\n                if debug:\n                    print('using config file {}'.format(candidate),\n                          file=sys.stderr)\n                return candidate\n        parent_directory = os.path.dirname(directory)\n        if parent_directory == directory:\n            break\n        else:\n            directory = parent_directory",
    "docstring": "Return configuration filename.\n\n    If `directory_or_file` is a file, return the real-path of that file. If it\n    is a directory, find the configuration (any file name in CONFIG_FILES) in\n    that directory or its ancestors."
  },
  {
    "code": "def run(self, host, port=25, with_ssl=False):\n        try:\n            dns_rec = self._lookup(host, port)\n            self._connect(dns_rec)\n            if with_ssl:\n                self._wrap_ssl()\n            banner = self._get_banner()\n            self._check_banner(banner)\n        except Exception:\n            exc_type, exc_value, exc_tb = sys.exc_info()\n            self.results['Exception-Type'] = str(exc_type.__name__)\n            self.results['Exception-Value'] = str(exc_value)\n            self.results['Exception-Traceback'] = repr(traceback.format_exc())\n        finally:\n            self._close(with_ssl)",
    "docstring": "Executes a single health check against a remote host and port. This\n        method may only be called once per object.\n\n        :param host: The hostname or IP address of the SMTP server to check.\n        :type host: str\n        :param port: The port number of the SMTP server to check.\n        :type port: int\n        :param with_ssl: If ``True``, SSL will be initiated before attempting\n                         to get the banner message.\n        :type with_ssl: bool"
  },
  {
    "code": "def launchDashboardOverlay(self, pchAppKey):\n        fn = self.function_table.launchDashboardOverlay\n        result = fn(pchAppKey)\n        return result",
    "docstring": "Launches the dashboard overlay application if it is not already running. This call is only valid for \n        dashboard overlay applications."
  },
  {
    "code": "def _parse_use(self, string):\n        result = {}\n        for ruse in self.RE_USE.finditer(string):\n            name = ruse.group(\"name\").split(\"!\")[0].strip()\n            if name.lower() == \"mpi\":\n                continue\n            if ruse.group(\"only\"):\n                only = ruse.group(\"only\").split(\",\")\n                for method in only:\n                    key = \"{}.{}\".format(name, method.strip())\n                    self._dict_increment(result, key)\n            else:\n                self._dict_increment(result, name)\n        return result",
    "docstring": "Extracts use dependencies from the innertext of a module."
  },
  {
    "code": "def sphericalAngSep(ra0, dec0, ra1, dec1, radians=False):\n    if radians==False:\n        ra0  = np.radians(ra0)\n        dec0 = np.radians(dec0)\n        ra1  = np.radians(ra1)\n        dec1 = np.radians(dec1)\n    deltaRa= ra1-ra0\n    deltaDec= dec1-dec0\n    val = haversine(deltaDec)\n    val += np.cos(dec0) * np.cos(dec1) * haversine(deltaRa)\n    val = min(1, np.sqrt(val)) ;\n    val = 2*np.arcsin(val)\n    if radians==False:\n        val = np.degrees(val)\n    return val",
    "docstring": "Compute the spherical angular separation between two\n        points on the sky.\n\n        //Taken from http://www.movable-type.co.uk/scripts/gis-faq-5.1.html\n\n        NB: For small distances you can probably use\n        sqrt( dDec**2 + cos^2(dec)*dRa)\n        where dDec = dec1 - dec0 and\n               dRa = ra1 - ra0\n               and dec1 \\approx dec \\approx dec0"
  },
  {
    "code": "def __add_token_annotation_tier(self, tier):\n        for i, event in enumerate(tier.iter('event')):\n            anno_key = '{0}:{1}'.format(self.ns, tier.attrib['category'])\n            anno_val = event.text if event.text else ''\n            self.node[event.attrib['start']][anno_key] = anno_val",
    "docstring": "adds a tier to the document graph, in which each event annotates\n        exactly one token."
  },
  {
    "code": "def _prepare_value_nd(self, value, vshape):\n        if isinstance(value, numeric_types):\n            value_nd = full(shape=vshape, val=value, ctx=self.context, dtype=self.dtype)\n        elif isinstance(value, NDArray):\n            value_nd = value.as_in_context(self.context)\n            if value_nd.dtype != self.dtype:\n                value_nd = value_nd.astype(self.dtype)\n        else:\n            try:\n                value_nd = array(value, ctx=self.context, dtype=self.dtype)\n            except:\n                raise TypeError('NDArray does not support assignment with non-array-like'\n                                ' object %s of type %s' % (str(value), str(type(value))))\n        if value_nd.shape != vshape:\n            value_nd = value_nd.broadcast_to(vshape)\n        return value_nd",
    "docstring": "Given value and vshape, create an `NDArray` from value with the same\n        context and dtype as the current one and broadcast it to vshape."
  },
  {
    "code": "def _read_stderr(self):\r\n        f = open(self.stderr_file, 'rb')\r\n        try:\r\n            stderr_text = f.read()\r\n            if not stderr_text:\r\n                return ''\r\n            encoding = get_coding(stderr_text)\r\n            stderr_text = to_text_string(stderr_text, encoding)\r\n            return stderr_text\r\n        finally:\r\n            f.close()",
    "docstring": "Read the stderr file of the kernel."
  },
  {
    "code": "def internal_get_description(dbg, seq, thread_id, frame_id, expression):\n    try:\n        frame = dbg.find_frame(thread_id, frame_id)\n        description = pydevd_console.get_description(frame, thread_id, frame_id, expression)\n        description = pydevd_xml.make_valid_xml_value(quote(description, '/>_= \\t'))\n        description_xml = '<xml><var name=\"\" type=\"\" value=\"%s\"/></xml>' % description\n        cmd = dbg.cmd_factory.make_get_description_message(seq, description_xml)\n        dbg.writer.add_command(cmd)\n    except:\n        exc = get_exception_traceback_str()\n        cmd = dbg.cmd_factory.make_error_message(seq, \"Error in fetching description\" + exc)\n        dbg.writer.add_command(cmd)",
    "docstring": "Fetch the variable description stub from the debug console"
  },
  {
    "code": "def get_epoch_namespace_lifetime_grace_period( block_height, namespace_id ):\n    epoch_config = get_epoch_config( block_height )\n    if epoch_config['namespaces'].has_key(namespace_id):\n        return epoch_config['namespaces'][namespace_id]['NAMESPACE_LIFETIME_GRACE_PERIOD']\n    else:\n        return epoch_config['namespaces']['*']['NAMESPACE_LIFETIME_GRACE_PERIOD']",
    "docstring": "what's the namespace lifetime grace period for this epoch?"
  },
  {
    "code": "def promise(cls, fn, *args, **kwargs):\n        task = cls.task(target=fn, args=args, kwargs=kwargs)\n        task.start()\n        return task",
    "docstring": "Used to build a task based on a callable function and the arguments.\n        Kick it off and start execution of the task.\n\n        :param fn: callable\n        :param args: tuple\n        :param kwargs: dict\n        :return: SynchronousTask or AsynchronousTask"
  },
  {
    "code": "def tuple_of(*generators):\n    class TupleOfGenerators(ArbitraryInterface):\n        @classmethod\n        def arbitrary(cls):\n            return tuple([\n                arbitrary(generator) for generator in generators\n                if generator is not tuple\n            ])\n    TupleOfGenerators.__name__ = ''.join([\n        'tuple_of(', ', '.join(generator.__name__ for generator in generators),\n        ')'\n    ])\n    return TupleOfGenerators",
    "docstring": "Generates a tuple by generating values for each of the specified\n    generators.\n    This is a class factory, it makes a class which is a closure around the\n    specified generators."
  },
  {
    "code": "def make_ttv_yaml(corpora, path_to_ttv_file, ttv_ratio=DEFAULT_TTV_RATIO, deterministic=False):\n    dataset = get_dataset(corpora)\n    data_sets = make_ttv(dataset, ttv_ratio=ttv_ratio, deterministic=deterministic)\n    def get_for_ttv(key):\n        return (\n            data_sets['test'][key],\n            data_sets['train'][key],\n            data_sets['validation'][key]\n        )\n    test, train, validation = get_for_ttv('paths')\n    number_of_files_for_each_set = list(get_for_ttv('number_of_files'))\n    number_of_subjects_for_each_set = [len(x) for x in get_for_ttv('subjects')]\n    dict_for_yaml = {\n        'split': number_of_files_for_each_set,\n        'subject_split': number_of_subjects_for_each_set,\n        \"test\": test,\n        \"train\": train,\n        \"validation\": validation\n    }\n    with open(path_to_ttv_file, 'w') as f:\n        yaml.dump(dict_for_yaml, f, default_flow_style=False)",
    "docstring": "Create a test, train, validation from the corpora given and saves it as a YAML filename.\n\n        Each set will be subject independent, meaning that no one subject can have data in more than one\n        set\n\n    # Arguments;\n        corpora: a list of the paths to corpora used (these have to be formatted accoring to notes.md)\n        path_to_ttv_file: the path to where the YAML file be be saved\n        ttv_ratio: a tuple (e.g. (1,4,4) of the relative sizoe of each set)\n        deterministic: whether or not to shuffle the resources around when making the set."
  },
  {
    "code": "def verify_logout_request(cls, logout_request, ticket):\n        try:\n            session_index = cls.get_saml_slos(logout_request)\n            session_index = session_index[0].text\n            if session_index == ticket:\n                return True\n            else:\n                return False\n        except (AttributeError, IndexError):\n            return False",
    "docstring": "verifies the single logout request came from the CAS server\n        returns True if the logout_request is valid, False otherwise"
  },
  {
    "code": "def matrix(ctx, scenario_name, subcommand):\n    args = ctx.obj.get('args')\n    command_args = {\n        'subcommand': subcommand,\n    }\n    s = scenarios.Scenarios(\n        base.get_configs(args, command_args), scenario_name)\n    s.print_matrix()",
    "docstring": "List matrix of steps used to test instances."
  },
  {
    "code": "def validate(self, val):\n        if self.validation:\n            self.type.validate(val)\n            if self.custom_validator is not None:\n                self.custom_validator(val)\n        return True",
    "docstring": "Validate values according to the requirement"
  },
  {
    "code": "def request_with_retries_on_post_search(self, session, url, query, json_input, stream, headers):\n        status_code = 500\n        if '/v1/search' in url:\n            retry_count = 10\n        else:\n            retry_count = 1\n        while status_code in (500, 502, 503, 504) and retry_count > 0:\n            try:\n                retry_count -= 1\n                res = session.request(self.http_method,\n                                      url,\n                                      params=query,\n                                      json=json_input,\n                                      stream=stream,\n                                      headers=headers,\n                                      timeout=self.client.timeout_policy)\n                status_code = res.status_code\n            except SwaggerAPIException:\n                if retry_count > 0:\n                    pass\n                else:\n                    raise\n        return res",
    "docstring": "Submit a request and retry POST search requests specifically.\n\n        We don't currently retry on POST requests, and this is intended as a temporary fix until\n        the swagger is updated and changes applied to prod.  In the meantime, this function will add\n        retries specifically for POST search (and any other POST requests will not be retried)."
  },
  {
    "code": "def get_active_keys_to_keycode_list(self):\n        try:\n            _libxdo.xdo_get_active_keys_to_keycode_list\n        except AttributeError:\n            raise NotImplementedError()\n        keys = POINTER(charcodemap_t)\n        nkeys = ctypes.c_int(0)\n        _libxdo.xdo_get_active_keys_to_keycode_list(\n            self._xdo, ctypes.byref(keys), ctypes.byref(nkeys))\n        return keys.value",
    "docstring": "Get a list of active keys. Uses XQueryKeymap"
  },
  {
    "code": "def log(self, level, message):\n        if self.log_fd is not None:\n            prefix = struct.pack('ii', level, len(message))\n            os.write(self.log_fd, prefix)\n            os.write(self.log_fd, message)",
    "docstring": "Write a log message via the child process.\n\n        The child process must already exist; call :meth:`live_log_child`\n        to make sure.  If it has died in a way we don't expect then\n        this will raise :const:`signal.SIGPIPE`."
  },
  {
    "code": "def _postrun(self, result):\n        logger.debug(\n            \"{}.PostRun: {}[{}]\".format(\n                self.__class__.__name__, self.__class__.path, self.uuid\n            ),\n            extra=dict(\n                kmsg=Message(\n                    self.uuid, entrypoint=self.__class__.path,\n                    params=self.params, metadata=self.metadata\n                ).dump()\n            )\n        )\n        return self.postrun(result)",
    "docstring": "To execute after exection\n\n        :param kser.result.Result result: Execution result\n        :return: Execution result\n        :rtype: kser.result.Result"
  },
  {
    "code": "def use_db(path, mode=WorkDB.Mode.create):\n    database = WorkDB(path, mode)\n    try:\n        yield database\n    finally:\n        database.close()",
    "docstring": "Open a DB in file `path` in mode `mode` as a context manager.\n\n    On exiting the context the DB will be automatically closed.\n\n    Args:\n      path: The path to the DB file.\n      mode: The mode in which to open the DB. See the `Mode` enum for\n        details.\n\n    Raises:\n      FileNotFoundError: If `mode` is `Mode.open` and `path` does not\n        exist."
  },
  {
    "code": "def reject_entry(request, entry_id):\n    return_url = request.GET.get('next', reverse('dashboard'))\n    try:\n        entry = Entry.no_join.get(pk=entry_id)\n    except:\n        message = 'No such log entry.'\n        messages.error(request, message)\n        return redirect(return_url)\n    if entry.status == Entry.UNVERIFIED or entry.status == Entry.INVOICED:\n        msg_text = 'This entry is unverified or is already invoiced.'\n        messages.error(request, msg_text)\n        return redirect(return_url)\n    if request.POST.get('Yes'):\n        entry.status = Entry.UNVERIFIED\n        entry.save()\n        msg_text = 'The entry\\'s status was set to unverified.'\n        messages.info(request, msg_text)\n        return redirect(return_url)\n    return render(request, 'timepiece/entry/reject.html', {\n        'entry': entry,\n        'next': request.GET.get('next'),\n    })",
    "docstring": "Admins can reject an entry that has been verified or approved but not\n    invoiced to set its status to 'unverified' for the user to fix."
  },
  {
    "code": "def list_changes(self):\n        if not self.is_attached():\n            raise ItsdbError('changes are not tracked for detached tables.')\n        return [(i, self[i]) for i, row in enumerate(self._records)\n                if row is not None]",
    "docstring": "Return a list of modified records.\n\n        This is only applicable for attached tables.\n\n        Returns:\n            A list of `(row_index, record)` tuples of modified records\n        Raises:\n            :class:`delphin.exceptions.ItsdbError`: when called on a\n                detached table"
  },
  {
    "code": "def decode(addr):\n    hrpgot, data = bech32_decode(addr)\n    if hrpgot not in BECH32_VERSION_SET:\n        return (None, None)\n    decoded = convertbits(data[1:], 5, 8, False)\n    if decoded is None or len(decoded) < 2 or len(decoded) > 40:\n        return (None, None)\n    if data[0] > 16:\n        return (None, None)\n    if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32:\n        return (None, None)\n    return (data[0], decoded)",
    "docstring": "Decode a segwit address."
  },
  {
    "code": "def asQuartusTcl(self, buff: List[str], version: str, component: \"Component\",\n                     packager: \"IpPackager\", thisIf: 'Interface'):\n        name = packager.getInterfaceLogicalName(thisIf)\n        self.quartus_tcl_add_interface(buff, thisIf, packager)\n        clk = thisIf._getAssociatedClk()\n        if clk is not None:\n            self.quartus_prop(buff, name, \"associatedClock\",\n                              clk._sigInside.name, escapeStr=False)\n        rst = thisIf._getAssociatedRst()\n        if rst is not None:\n            self.quartus_prop(buff, name, \"associatedReset\",\n                              rst._sigInside.name, escapeStr=False)\n        m = self.get_quartus_map()\n        if m:\n            intfMapOrName = m\n        else:\n            intfMapOrName = thisIf.name\n        self._asQuartusTcl(buff, version, name, component,\n                           packager, thisIf, intfMapOrName)",
    "docstring": "Add interface to Quartus tcl\n\n        :param buff: line buffer for output\n        :param version: Quartus version\n        :param intfName: name of top interface\n        :param component: component object from ipcore generator\n        :param packager: instance of IpPackager which is packagin current design\n        :param allInterfaces: list of all interfaces of top unit\n        :param thisIf: interface to add into Quartus TCL"
  },
  {
    "code": "def hasnew(self,allowempty=False):\n        for e in  self.select(New,None,False, False):\n            if not allowempty and len(e) == 0: continue\n            return True\n        return False",
    "docstring": "Does the correction define new corrected annotations?"
  },
  {
    "code": "def MakeOdds(self):\n        for hypo, prob in self.Items():\n            if prob:\n                self.Set(hypo, Odds(prob))\n            else:\n                self.Remove(hypo)",
    "docstring": "Transforms from probabilities to odds.\n\n        Values with prob=0 are removed."
  },
  {
    "code": "def get_self_host(request_data):\n        if 'http_host' in request_data:\n            current_host = request_data['http_host']\n        elif 'server_name' in request_data:\n            current_host = request_data['server_name']\n        else:\n            raise Exception('No hostname defined')\n        if ':' in current_host:\n            current_host_data = current_host.split(':')\n            possible_port = current_host_data[-1]\n            try:\n                possible_port = float(possible_port)\n                current_host = current_host_data[0]\n            except ValueError:\n                current_host = ':'.join(current_host_data)\n        return current_host",
    "docstring": "Returns the current host.\n\n        :param request_data: The request as a dict\n        :type: dict\n\n        :return: The current host\n        :rtype: string"
  },
  {
    "code": "def schedCoro(self, coro):\n        import synapse.lib.provenance as s_provenance\n        if __debug__:\n            assert s_coro.iscoro(coro)\n            import synapse.lib.threads as s_threads\n            assert s_threads.iden() == self.tid\n        task = self.loop.create_task(coro)\n        if asyncio.current_task():\n            s_provenance.dupstack(task)\n        def taskDone(task):\n            self._active_tasks.remove(task)\n            try:\n                task.result()\n            except asyncio.CancelledError:\n                pass\n            except Exception:\n                logger.exception('Task scheduled through Base.schedCoro raised exception')\n        self._active_tasks.add(task)\n        task.add_done_callback(taskDone)\n        return task",
    "docstring": "Schedules a free-running coroutine to run on this base's event loop.  Kills the coroutine if Base is fini'd.\n        It does not pend on coroutine completion.\n\n        Precondition:\n            This function is *not* threadsafe and must be run on the Base's event loop\n\n        Returns:\n            asyncio.Task: An asyncio.Task object."
  },
  {
    "code": "def get_statistics_24h(self, endtime):\n        js = json.dumps(\n            {'attrs': [\"bytes\", \"num_sta\", \"time\"], 'start': int(endtime - 86400) * 1000, 'end': int(endtime - 3600) * 1000})\n        params = urllib.urlencode({'json': js})\n        return self._read(self.api_url + 'stat/report/hourly.system', params)",
    "docstring": "Return statistical data last 24h from time"
  },
  {
    "code": "def check_jobs(jobs):\n    if jobs == 0:\n        raise click.UsageError(\"Jobs must be >= 1 or == -1\")\n    elif jobs < 0:\n        import multiprocessing\n        jobs = multiprocessing.cpu_count()\n    return jobs",
    "docstring": "Validate number of jobs."
  },
  {
    "code": "def when_matches(self, path, good_value, bad_values=None, timeout=None,\n                     event_timeout=None):\n        future = self.when_matches_async(path, good_value, bad_values)\n        self.wait_all_futures(\n            future, timeout=timeout, event_timeout=event_timeout)",
    "docstring": "Resolve when an path value equals value\n\n        Args:\n            path (list): The path to wait to\n            good_value (object): the value to wait for\n            bad_values (list): values to raise an error on\n            timeout (float): time in seconds to wait for responses, wait\n                forever if None\n            event_timeout: maximum time in seconds to wait between each response\n                event, wait forever if None"
  },
  {
    "code": "def fit(self, data, parent_node=None, estimator=None):\n        if not parent_node:\n            if not self.parent_node:\n                raise ValueError(\"parent node must be specified for the model\")\n            else:\n                parent_node = self.parent_node\n        if parent_node not in data.columns:\n            raise ValueError(\"parent node: {node} is not present in the given data\".format(node=parent_node))\n        for child_node in data.columns:\n            if child_node != parent_node:\n                self.add_edge(parent_node, child_node)\n        super(NaiveBayes, self).fit(data, estimator)",
    "docstring": "Computes the CPD for each node from a given data in the form of a pandas dataframe.\n        If a variable from the data is not present in the model, it adds that node into the model.\n\n        Parameters\n        ----------\n        data : pandas DataFrame object\n            A DataFrame object with column names same as the variable names of network\n\n        parent_node: any hashable python object (optional)\n            Parent node of the model, if not specified it looks for a previously specified\n            parent node.\n\n        estimator: Estimator class\n            Any pgmpy estimator. If nothing is specified, the default ``MaximumLikelihoodEstimator``\n            would be used.\n\n        Examples\n        --------\n        >>> import numpy as np\n        >>> import pandas as pd\n        >>> from pgmpy.models import NaiveBayes\n        >>> model = NaiveBayes()\n        >>> values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 5)),\n        ...                       columns=['A', 'B', 'C', 'D', 'E'])\n        >>> model.fit(values, 'A')\n        >>> model.get_cpds()\n        [<TabularCPD representing P(D:2 | A:2) at 0x4b72870>,\n         <TabularCPD representing P(E:2 | A:2) at 0x4bb2150>,\n         <TabularCPD representing P(A:2) at 0x4bb23d0>,\n         <TabularCPD representing P(B:2 | A:2) at 0x4bb24b0>,\n         <TabularCPD representing P(C:2 | A:2) at 0x4bb2750>]\n        >>> model.edges()\n        [('A', 'D'), ('A', 'E'), ('A', 'B'), ('A', 'C')]"
  },
  {
    "code": "def create_index(self):\n        es = self._init_connection()\n        if not es.indices.exists(index=self.index):\n            es.indices.create(index=self.index, body=self.settings)",
    "docstring": "Override to provide code for creating the target index.\n\n        By default it will be created without any special settings or mappings."
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'environment_id' in _dict:\n            args['environment_id'] = _dict.get('environment_id')\n        if 'collection_id' in _dict:\n            args['collection_id'] = _dict.get('collection_id')\n        if 'queries' in _dict:\n            args['queries'] = [\n                TrainingQuery._from_dict(x) for x in (_dict.get('queries'))\n            ]\n        return cls(**args)",
    "docstring": "Initialize a TrainingDataSet object from a json dictionary."
  },
  {
    "code": "def addLabel(self, aminoAcidLabels, excludingModifications=None):\n        if excludingModifications is not None:\n            self.excludingModifictions = True\n        labelEntry = {'aminoAcidLabels': aminoAcidLabels,\n                      'excludingModifications': excludingModifications\n                      }\n        self.labels[self._labelCounter] = labelEntry\n        self._labelCounter += 1",
    "docstring": "Adds a new labelstate.\n\n        :param aminoAcidsLabels: Describes which amino acids can bear which\n            labels. Possible keys are the amino acids in one letter code and\n            'nTerm', 'cTerm'. Possible values are the modifications ids from\n            :attr:`maspy.constants.aaModMass` as strings or a list of strings.\n            An example for one expected label at the n-terminus and two expected\n                labels at each Lysine:\n                ``{'nTerm': 'u:188', 'K': ['u:188', 'u:188']}``\n        :param excludingModifications: optional, A Dectionary that describes\n            which modifications can prevent the addition of labels. Keys and\n            values have to be the modifications ids from\n            :attr:`maspy.constants.aaModMass`. The key specifies the\n            modification that prevents the label modification specified by the\n            value. For example for each modification 'u:1' that is present at an\n            amino acid or terminus of a peptide the number of expected labels at\n            this position is reduced by one: ``{'u:1':'u:188'}``"
  },
  {
    "code": "def detach_all_classes(self):\n        classes = list(self._observers.keys())\n        for cls in classes:\n            self.detach_class(cls)",
    "docstring": "Detach from all tracked classes."
  },
  {
    "code": "def classproperty(func):\n  doc = func.__doc__\n  if not isinstance(func, (classmethod, staticmethod)):\n    func = classmethod(func)\n  return ClassPropertyDescriptor(func, doc)",
    "docstring": "Use as a decorator on a method definition to make it a class-level attribute.\n\n  This decorator can be applied to a method, a classmethod, or a staticmethod. This decorator will\n  bind the first argument to the class object.\n\n  Usage:\n  >>> class Foo(object):\n  ...   @classproperty\n  ...   def name(cls):\n  ...     return cls.__name__\n  ...\n  >>> Foo.name\n  'Foo'\n\n  Setting or deleting the attribute of this name will overwrite this property.\n\n  The docstring of the classproperty `x` for a class `C` can be obtained by\n  `C.__dict__['x'].__doc__`."
  },
  {
    "code": "def sort_cards(cards, ranks=None):\n    ranks = ranks or DEFAULT_RANKS\n    if ranks.get(\"suits\"):\n        cards = sorted(\n            cards,\n            key=lambda x: ranks[\"suits\"][x.suit] if x.suit != None else 0\n        )\n    if ranks.get(\"values\"):\n        cards = sorted(\n            cards,\n            key=lambda x: ranks[\"values\"][x.value]\n        )\n    return cards",
    "docstring": "Sorts a given list of cards, either by poker ranks, or big two ranks.\n\n    :arg cards:\n        The cards to sort.\n    :arg dict ranks:\n        The rank dict to reference for sorting. If ``None``, it will\n        default to ``DEFAULT_RANKS``.\n\n    :returns:\n        The sorted cards."
  },
  {
    "code": "def from_sequence(chain, list_of_residues, sequence_type = None):\n        s = Sequence(sequence_type)\n        count = 1\n        for ResidueAA in list_of_residues:\n            s.add(Residue(chain, count, ResidueAA, sequence_type))\n            count += 1\n        return s",
    "docstring": "Takes in a chain identifier and protein sequence and returns a Sequence object of Residues, indexed from 1."
  },
  {
    "code": "def rule_variable(field_type, label=None, options=None):\n    options = options or []\n    def wrapper(func):\n        if not (type(field_type) == type and issubclass(field_type, BaseType)):\n            raise AssertionError(\"{0} is not instance of BaseType in\"\\\n                    \" rule_variable field_type\".format(field_type))\n        func.field_type = field_type\n        func.is_rule_variable = True\n        func.label = label \\\n                or fn_name_to_pretty_label(func.__name__)\n        func.options = options\n        return func\n    return wrapper",
    "docstring": "Decorator to make a function into a rule variable"
  },
  {
    "code": "def start_in_keepedalive_processes(obj, nb_process):\n    processes = []\n    readers_pipes = []\n    writers_pipes = []\n    for i in range(nb_process):\n        local_read_pipe, local_write_pipe = Pipe(duplex=False)\n        process_read_pipe, process_write_pipe = Pipe(duplex=False)\n        readers_pipes.append(local_read_pipe)\n        writers_pipes.append(process_write_pipe)\n        p = Process(target=run_keepedalive_process, args=(local_write_pipe, process_read_pipe, obj))\n        p.start()\n        processes.append(p)\n    for job in range(3):\n        print('send new job to processes:')\n        for process_number in range(nb_process):\n            writers_pipes[process_number].send(obj)\n            reader_useds = []\n        while readers_pipes:\n            for r in wait(readers_pipes):\n                try:\n                    r.recv()\n                except EOFError:\n                    pass\n                finally:\n                    reader_useds.append(r)\n                    readers_pipes.remove(r)\n        readers_pipes = reader_useds\n    for writer_pipe in writers_pipes:\n        writer_pipe.send('stop')",
    "docstring": "Start nb_process and keep them alive. Send job to them multiple times, then close thems."
  },
  {
    "code": "def ring_position(self):\n\t\tif self.type != EventType.TABLET_PAD_RING:\n\t\t\traise AttributeError(_wrong_prop.format(self.type))\n\t\treturn self._libinput.libinput_event_tablet_pad_get_ring_position(\n\t\t\tself._handle)",
    "docstring": "The current position of the ring, in degrees\n\t\tcounterclockwise from the northern-most point of the ring in\n\t\tthe tablet's current logical orientation.\n\n\t\tIf the source is\n\t\t:attr:`~libinput.constant.TabletPadRingAxisSource.FINGER`,\n\t\tlibinput sends a terminating event with a ring value of -1 when\n\t\tthe finger is lifted from the ring. A caller may use this information\n\t\tto e.g. determine if kinetic scrolling should be triggered.\n\n\t\tFor events not of type\n\t\t:attr:`~libinput.constant.EventType.TABLET_PAD_RING`, this property\n\t\traises :exc:`AttributeError`.\n\n\t\tReturns:\n\t\t\tfloat: The current value of the the axis. -1 if the finger was\n\t\t\tlifted.\n\t\tRaises:\n\t\t\tAttributeError"
  },
  {
    "code": "def init_services(service_definitions, service_context, state_db,\n                  client_authn_factory=None):\n    service = {}\n    for service_name, service_configuration in service_definitions.items():\n        try:\n            kwargs = service_configuration['kwargs']\n        except KeyError:\n            kwargs = {}\n        kwargs.update({'service_context': service_context,\n                       'state_db': state_db,\n                       'client_authn_factory': client_authn_factory})\n        if isinstance(service_configuration['class'], str):\n            _srv = util.importer(service_configuration['class'])(**kwargs)\n        else:\n            _srv = service_configuration['class'](**kwargs)\n        try:\n            service[_srv.service_name] = _srv\n        except AttributeError:\n            raise ValueError(\"Could not load '{}'\".format(service_name))\n    return service",
    "docstring": "Initiates a set of services\n\n    :param service_definitions: A dictionary cotaining service definitions\n    :param service_context: A reference to the service context, this is the same\n        for all service instances.\n    :param state_db: A reference to the state database. Shared by all the\n        services.\n    :param client_authn_factory: A list of methods the services can use to\n        authenticate the client to a service.\n    :return: A dictionary, with service name as key and the service instance as\n        value."
  },
  {
    "code": "def _capabilities_dict(envs, tags):\n    capabilities = {\n        'browserName': envs['SELENIUM_BROWSER'],\n        'acceptInsecureCerts': bool(envs.get('SELENIUM_INSECURE_CERTS', False)),\n        'video-upload-on-pass': False,\n        'sauce-advisor': False,\n        'capture-html': True,\n        'record-screenshots': True,\n        'max-duration': 600,\n        'public': 'public restricted',\n        'tags': tags,\n    }\n    if _use_remote_browser(SAUCE_ENV_VARS):\n        sauce_capabilities = {\n            'platform': envs['SELENIUM_PLATFORM'],\n            'version': envs['SELENIUM_VERSION'],\n            'username': envs['SAUCE_USER_NAME'],\n            'accessKey': envs['SAUCE_API_KEY'],\n        }\n        capabilities.update(sauce_capabilities)\n    if 'JOB_NAME' in envs:\n        jenkins_vars = {\n            'build': envs['BUILD_NUMBER'],\n            'name': envs['JOB_NAME'],\n        }\n        capabilities.update(jenkins_vars)\n    return capabilities",
    "docstring": "Convert the dictionary of environment variables to\n    a dictionary of desired capabilities to send to the\n    Remote WebDriver.\n\n    `tags` is a list of string tags to apply to the SauceLabs job."
  },
  {
    "code": "def pch_emitter(target, source, env):\n    validate_vars(env)\n    pch = None\n    obj = None\n    for t in target:\n        if SCons.Util.splitext(str(t))[1] == '.pch':\n            pch = t\n        if SCons.Util.splitext(str(t))[1] == '.obj':\n            obj = t\n    if not obj:\n        obj = SCons.Util.splitext(str(pch))[0]+'.obj'\n    target = [pch, obj]\n    return (target, source)",
    "docstring": "Adds the object file target."
  },
  {
    "code": "def get_configdir(name):\n    configdir = os.environ.get('%sCONFIGDIR' % name.upper())\n    if configdir is not None:\n        return os.path.abspath(configdir)\n    p = None\n    h = _get_home()\n    if ((sys.platform.startswith('linux') or\n         sys.platform.startswith('darwin')) and h is not None):\n        p = os.path.join(h, '.config/' + name)\n    elif h is not None:\n        p = os.path.join(h, '.' + name)\n    if not os.path.exists(p):\n        os.makedirs(p)\n    return p",
    "docstring": "Return the string representing the configuration directory.\n\n    The directory is chosen as follows:\n\n    1. If the ``name.upper() + CONFIGDIR`` environment variable is supplied,\n       choose that.\n\n    2a. On Linux, choose `$HOME/.config`.\n\n    2b. On other platforms, choose `$HOME/.matplotlib`.\n\n    3. If the chosen directory exists, use that as the\n       configuration directory.\n    4. A directory: return None.\n\n    Notes\n    -----\n    This function is taken from the matplotlib [1] module\n\n    References\n    ----------\n    [1]: http://matplotlib.org/api/"
  },
  {
    "code": "def _load_params(params, logger=logging):\n    if isinstance(params, str):\n        cur_path = os.path.dirname(os.path.realpath(__file__))\n        param_file_path = os.path.join(cur_path, params)\n        logger.info('Loading params from file %s' % param_file_path)\n        save_dict = nd_load(param_file_path)\n        arg_params = {}\n        aux_params = {}\n        for k, v in save_dict.items():\n            tp, name = k.split(':', 1)\n            if tp == 'arg':\n                arg_params[name] = v\n            if tp == 'aux':\n                aux_params[name] = v\n        return arg_params, aux_params\n    elif isinstance(params, (tuple, list)) and len(params) == 2:\n        return params[0], params[1]\n    else:\n        raise ValueError('Unsupported params provided. Must be either a path to the param file or'\n                         ' a pair of dictionaries representing arg_params and aux_params')",
    "docstring": "Given a str as a path to the .params file or a pair of params,\n    returns two dictionaries representing arg_params and aux_params."
  },
  {
    "code": "def clean(self, force=False):\n        if self.is_finalized and not force:\n            self.warn(\"Can't clean; bundle is finalized\")\n            return False\n        self.log('---- Cleaning ----')\n        self.state = self.STATES.CLEANING\n        self.dstate = self.STATES.BUILDING\n        self.commit()\n        self.clean_sources()\n        self.clean_tables()\n        self.clean_partitions()\n        self.clean_build()\n        self.clean_files()\n        self.clean_ingested()\n        self.clean_build_state()\n        self.clean_progress()\n        self.state = self.STATES.CLEANED\n        self.commit()\n        return True",
    "docstring": "Clean generated objects from the dataset, but only if there are File contents\n         to regenerate them"
  },
  {
    "code": "def call_mr_transform(data, opt='', path='./',\n                      remove_files=True):\n    r\n    if not import_astropy:\n        raise ImportError('Astropy package not found.')\n    if (not isinstance(data, np.ndarray)) or (data.ndim != 2):\n        raise ValueError('Input data must be a 2D numpy array.')\n    executable = 'mr_transform'\n    is_executable(executable)\n    unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S')\n    file_name = path + 'mr_temp_' + unique_string\n    file_fits = file_name + '.fits'\n    file_mr = file_name + '.mr'\n    fits.writeto(file_fits, data)\n    if isinstance(opt, str):\n        opt = opt.split()\n    try:\n        check_call([executable] + opt + [file_fits, file_mr])\n    except Exception:\n        warn('{} failed to run with the options provided.'.format(executable))\n        remove(file_fits)\n    else:\n        result = fits.getdata(file_mr)\n        if remove_files:\n            remove(file_fits)\n            remove(file_mr)\n        return result",
    "docstring": "r\"\"\"Call mr_transform\n\n    This method calls the iSAP module mr_transform\n\n    Parameters\n    ----------\n    data : np.ndarray\n        Input data, 2D array\n    opt : list or str, optional\n        Options to be passed to mr_transform\n    path : str, optional\n        Path for output files (default is './')\n    remove_files : bool, optional\n        Option to remove output files (default is 'True')\n\n    Returns\n    -------\n    np.ndarray results of mr_transform\n\n    Raises\n    ------\n    ValueError\n        If the input data is not a 2D numpy array\n\n    Examples\n    --------\n    >>> from modopt.signal.wavelet import *\n    >>> a = np.arange(9).reshape(3, 3).astype(float)\n    >>> call_mr_transform(a)\n    array([[[-1.5       , -1.125     , -0.75      ],\n            [-0.375     ,  0.        ,  0.375     ],\n            [ 0.75      ,  1.125     ,  1.5       ]],\n\n           [[-1.5625    , -1.171875  , -0.78125   ],\n            [-0.390625  ,  0.        ,  0.390625  ],\n            [ 0.78125   ,  1.171875  ,  1.5625    ]],\n\n           [[-0.5859375 , -0.43945312, -0.29296875],\n            [-0.14648438,  0.        ,  0.14648438],\n            [ 0.29296875,  0.43945312,  0.5859375 ]],\n\n           [[ 3.6484375 ,  3.73632812,  3.82421875],\n            [ 3.91210938,  4.        ,  4.08789062],\n            [ 4.17578125,  4.26367188,  4.3515625 ]]], dtype=float32)"
  },
  {
    "code": "def walk_recursive(f, data):\n    results = {}\n    if isinstance(data, list):\n        return [walk_recursive(f, d) for d in data]\n    elif isinstance(data, dict):\n        results = funcy.walk_keys(f, data)\n        for k, v in data.iteritems():\n            if isinstance(v, dict):\n                results[f(k)] = walk_recursive(f, v)\n            elif isinstance(v, list):\n                results[f(k)] = [walk_recursive(f, d) for d in v]\n    else:\n        return f(data)\n    return results",
    "docstring": "Recursively apply a function to all dicts in a nested dictionary\n\n    :param f: Function to apply\n    :param data: Dictionary (possibly nested) to recursively apply\n    function to\n    :return:"
  },
  {
    "code": "def set_loader(self, loader, destructor, state):\n        return lib.zcertstore_set_loader(self._as_parameter_, loader, destructor, state)",
    "docstring": "Override the default disk loader with a custom loader fn."
  },
  {
    "code": "def _raise_error_if_not_drawing_classifier_input_sframe(\n    dataset, feature, target):\n    from turicreate.toolkits._internal_utils import _raise_error_if_not_sframe\n    _raise_error_if_not_sframe(dataset)\n    if feature not in dataset.column_names():\n        raise _ToolkitError(\"Feature column '%s' does not exist\" % feature)\n    if target not in dataset.column_names():\n        raise _ToolkitError(\"Target column '%s' does not exist\" % target)\n    if (dataset[feature].dtype != _tc.Image and dataset[feature].dtype != list):\n        raise _ToolkitError(\"Feature column must contain images\" \n            + \" or stroke-based drawings encoded as lists of strokes\" \n            + \" where each stroke is a list of points and\" \n            + \" each point is stored as a dictionary\")\n    if dataset[target].dtype != int and dataset[target].dtype != str:\n        raise _ToolkitError(\"Target column contains \" + str(dataset[target].dtype)\n            + \" but it must contain strings or integers to represent\" \n            + \" labels for drawings.\")\n    if len(dataset) == 0:\n        raise _ToolkitError(\"Input Dataset is empty!\")",
    "docstring": "Performs some sanity checks on the SFrame provided as input to \n    `turicreate.drawing_classifier.create` and raises a ToolkitError\n    if something in the dataset is missing or wrong."
  },
  {
    "code": "def get_extensions(self, data=False):\n        ext_list = [key for key in\n                    self.__dict__ if type(self.__dict__[key]) is Extension]\n        for key in ext_list:\n            if data:\n                yield getattr(self, key)\n            else:\n                yield key",
    "docstring": "Yields the extensions or their names\n\n        Parameters\n        ----------\n        data : boolean, optional\n           If True, returns a generator which yields the extensions.\n           If False, returns a generator which yields the names of\n           the extensions (default)\n\n        Returns\n        -------\n        Generator for Extension or string"
  },
  {
    "code": "def linsert(self, key, pivot, value, before=False):\n        where = b'AFTER' if not before else b'BEFORE'\n        return self.execute(b'LINSERT', key, where, pivot, value)",
    "docstring": "Inserts value in the list stored at key either before or\n        after the reference value pivot."
  },
  {
    "code": "def to_placeholder(self, name=None, db_type=None):\n    if name is None:\n      placeholder = self.unnamed_placeholder\n    else:\n      placeholder = self.named_placeholder.format(name)\n    if db_type:\n      return self.typecast(placeholder, db_type)\n    else:\n      return placeholder",
    "docstring": "Returns a placeholder for the specified name, by applying the instance's format strings.\n\n    :name: if None an unamed placeholder is returned, otherwise a named placeholder is returned.\n    :db_type: if not None the placeholder is typecast."
  },
  {
    "code": "def round(self, decimals=0, *args, **kwargs):\n        nv.validate_round(args, kwargs)\n        result = com.values_from_object(self).round(decimals)\n        result = self._constructor(result, index=self.index).__finalize__(self)\n        return result",
    "docstring": "Round each value in a Series to the given number of decimals.\n\n        Parameters\n        ----------\n        decimals : int\n            Number of decimal places to round to (default: 0).\n            If decimals is negative, it specifies the number of\n            positions to the left of the decimal point.\n\n        Returns\n        -------\n        Series\n            Rounded values of the Series.\n\n        See Also\n        --------\n        numpy.around : Round values of an np.array.\n        DataFrame.round : Round values of a DataFrame.\n\n        Examples\n        --------\n        >>> s = pd.Series([0.1, 1.3, 2.7])\n        >>> s.round()\n        0    0.0\n        1    1.0\n        2    3.0\n        dtype: float64"
  },
  {
    "code": "def _update_to_s3_uri(property_key, resource_property_dict, s3_uri_value=\"s3://bucket/value\"):\n        uri_property = resource_property_dict.get(property_key, \".\")\n        if isinstance(uri_property, dict) or SamTemplateValidator.is_s3_uri(uri_property):\n            return\n        resource_property_dict[property_key] = s3_uri_value",
    "docstring": "Updates the 'property_key' in the 'resource_property_dict' to the value of 's3_uri_value'\n\n        Note: The function will mutate the resource_property_dict that is pass in\n\n        Parameters\n        ----------\n        property_key str, required\n            Key in the resource_property_dict\n        resource_property_dict dict, required\n            Property dictionary of a Resource in the template to replace\n        s3_uri_value str, optional\n            Value to update the value of the property_key to"
  },
  {
    "code": "def sudo(command, show=True, *args, **kwargs):\n    if show:\n        print_command(command)\n    with hide(\"running\"):\n        return _sudo(command, *args, **kwargs)",
    "docstring": "Runs a command as sudo on the remote server."
  },
  {
    "code": "def _get_inline_fragment(ast):\n    if not ast.selection_set:\n        return None\n    fragments = [\n        ast_node\n        for ast_node in ast.selection_set.selections\n        if isinstance(ast_node, InlineFragment)\n    ]\n    if not fragments:\n        return None\n    if len(fragments) > 1:\n        raise GraphQLCompilationError(u'Cannot compile GraphQL with more than one fragment in '\n                                      u'a given selection set.')\n    return fragments[0]",
    "docstring": "Return the inline fragment at the current AST node, or None if no fragment exists."
  },
  {
    "code": "def SetValue(self, row, col, value):\n        self.dataframe.iloc[row, col] = value",
    "docstring": "Set value in the pandas DataFrame"
  },
  {
    "code": "def total_bytes_billed(self):\n        result = self._job_statistics().get(\"totalBytesBilled\")\n        if result is not None:\n            result = int(result)\n        return result",
    "docstring": "Return total bytes billed from job statistics, if present.\n\n        See:\n        https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.totalBytesBilled\n\n        :rtype: int or None\n        :returns: total bytes processed by the job, or None if job is not\n                  yet complete."
  },
  {
    "code": "def register_provider(cls, provider):\n        def decorator(subclass):\n            cls._providers[provider] = subclass\n            subclass.name = provider\n            return subclass\n        return decorator",
    "docstring": "Register method to keep list of providers."
  },
  {
    "code": "def set_blacklisted_filepaths(self, filepaths, remove_from_stored=True):\n        filepaths = util.to_absolute_paths(filepaths)\n        self.blacklisted_filepaths = filepaths\n        if remove_from_stored:\n            self.plugin_filepaths = util.remove_from_set(self.plugin_filepaths,\n                                                         filepaths)",
    "docstring": "Sets internal blacklisted filepaths to filepaths.\n        If `remove_from_stored` is `True`, any `filepaths` in\n        `self.plugin_filepaths` will be automatically removed.\n\n        Recommend passing in absolute filepaths but method will attempt\n        to convert to absolute filepaths based on current working directory."
  },
  {
    "code": "def Reset(self):\n    self._cur_state = self.states['Start']\n    self._cur_state_name = 'Start'\n    self._result = []\n    self._ClearAllRecord()",
    "docstring": "Preserves FSM but resets starting state and current record."
  },
  {
    "code": "def addattr(self, attrname, value=None, persistent=True):\n        setattr(self, attrname, value)\n        if persistent and attrname not in self.__persistent_attributes__:\n            self.__persistent_attributes__.append(attrname)",
    "docstring": "Adds an attribute to self. If persistent is True, the attribute will\n        be made a persistent attribute. Persistent attributes are copied\n        whenever a view or copy of this array is created. Otherwise, new views\n        or copies of this will not have the attribute."
  },
  {
    "code": "def _compute_intensity(ccube, bexpcube):\n        bexp_data = np.sqrt(bexpcube.data[0:-1, 0:] * bexpcube.data[1:, 0:])\n        intensity_data = ccube.data / bexp_data\n        intensity_map = HpxMap(intensity_data, ccube.hpx)\n        return intensity_map",
    "docstring": "Compute the intensity map"
  },
  {
    "code": "def set_created_date(self, date=None):\n        if date:\n            match = re.match(DATE_REGEX, date)\n            if not match:\n                raise IOCParseError('Created date is not valid.  Must be in the form YYYY-MM-DDTHH:MM:SS')\n        ioc_et.set_root_created_date(self.root, date)\n        return True",
    "docstring": "Set the created date of a IOC to the current date.\n        User may specify the date they want to set as well.\n\n        :param date: Date value to set the created date to.  This should be in the xsdDate form.\n         This defaults to the current date if it is not provided.\n         xsdDate form: YYYY-MM-DDTHH:MM:SS\n        :return: True\n        :raises: IOCParseError if date format is not valid."
  },
  {
    "code": "def os_walk(top, *args, **kwargs):\n    if six.PY2 and salt.utils.platform.is_windows():\n        top_query = top\n    else:\n        top_query = salt.utils.stringutils.to_str(top)\n    for item in os.walk(top_query, *args, **kwargs):\n        yield salt.utils.data.decode(item, preserve_tuples=True)",
    "docstring": "This is a helper than ensures that all paths returned from os.walk are\n    unicode."
  },
  {
    "code": "def commit(self):\n        request = self.edits().commit(**self.build_params()).execute()\n        print 'Edit \"%s\" has been committed' % (request['id'])\n        self.edit_id = None",
    "docstring": "commit current edits."
  },
  {
    "code": "def simplex_projection(v, b=1):\n    r\n    v = np.asarray(v)\n    p = len(v)\n    v = (v > 0) * v\n    u = np.sort(v)[::-1]\n    sv = np.cumsum(u)\n    rho = np.where(u > (sv - b) / np.arange(1, p + 1))[0][-1]\n    theta = np.max([0, (sv[rho] - b) / (rho + 1)])\n    w = (v - theta)\n    w[w < 0] = 0\n    return w",
    "docstring": "r\"\"\"Projection vectors to the simplex domain\n\n    Implemented according to the paper: Efficient projections onto the\n    l1-ball for learning in high dimensions, John Duchi, et al. ICML 2008.\n    Implementation Time: 2011 June 17 by Bin@libin AT pmail.ntu.edu.sg\n    Optimization Problem: min_{w}\\| w - v \\|_{2}^{2}\n    s.t. sum_{i=1}^{m}=z, w_{i}\\geq 0\n\n    Input: A vector v \\in R^{m}, and a scalar z > 0 (default=1)\n    Output: Projection vector w\n\n    :Example:\n    >>> proj = simplex_projection([.4 ,.3, -.4, .5])\n    >>> proj  # doctest: +NORMALIZE_WHITESPACE\n    array([ 0.33333333, 0.23333333, 0. , 0.43333333])\n    >>> print(proj.sum())\n    1.0\n\n    Original matlab implementation: John Duchi (jduchi@cs.berkeley.edu)\n    Python-port: Copyright 2013 by Thomas Wiecki (thomas.wiecki@gmail.com)."
  },
  {
    "code": "def _aux_types(self):\n        aux_types = []\n        num_aux = self._num_aux\n        for i in range(num_aux):\n            aux_types.append(self._aux_type(i))\n        return aux_types",
    "docstring": "The data types of the aux data for the BaseSparseNDArray."
  },
  {
    "code": "def escape_newlines(s: str) -> str:\n    if not s:\n        return s\n    s = s.replace(\"\\\\\", r\"\\\\\")\n    s = s.replace(\"\\n\", r\"\\n\")\n    s = s.replace(\"\\r\", r\"\\r\")\n    return s",
    "docstring": "Escapes CR, LF, and backslashes.\n\n    Its counterpart is :func:`unescape_newlines`.\n\n    ``s.encode(\"string_escape\")`` and ``s.encode(\"unicode_escape\")`` are\n    alternatives, but they mess around with quotes, too (specifically,\n    backslash-escaping single quotes)."
  },
  {
    "code": "def uncontract_general(basis, use_copy=True):\n    if use_copy:\n        basis = copy.deepcopy(basis)\n    for k, el in basis['elements'].items():\n        if not 'electron_shells' in el:\n            continue\n        newshells = []\n        for sh in el['electron_shells']:\n            if len(sh['coefficients']) == 1 or len(sh['angular_momentum']) > 1:\n                newshells.append(sh)\n            else:\n                if len(sh['angular_momentum']) == 1:\n                    for c in sh['coefficients']:\n                        newsh = sh.copy()\n                        newsh['coefficients'] = [c]\n                        newshells.append(newsh)\n        el['electron_shells'] = newshells\n    return prune_basis(basis, False)",
    "docstring": "Removes the general contractions from a basis set\n\n    The input basis set is not modified. The returned basis\n    may have functions with coefficients of zero and may have duplicate\n    shells.\n\n    If use_copy is True, the input basis set is not modified."
  },
  {
    "code": "def Images2Rgbd(rgb, d):\n    data = Rgbd()\n    data.color=imageMsg2Image(rgb)\n    data.depth=imageMsg2Image(d)\n    data.timeStamp = rgb.header.stamp.secs + (rgb.header.stamp.nsecs *1e-9)\n    return data",
    "docstring": "Translates from ROS Images to JderobotTypes Rgbd. \n\n    @param rgb: ROS color Image to translate\n\n    @param d: ROS depth image to translate\n\n    @type rgb: ImageROS\n\n    @type d: ImageROS\n\n    @return a Rgbd translated from Images"
  },
  {
    "code": "def validate_value(self, value):\n        if self.readonly:\n            raise ValidationError(self.record, \"Cannot set readonly field '{}'\".format(self.name))\n        if value not in (None, self._unset):\n            if self.supported_types and not isinstance(value, tuple(self.supported_types)):\n                raise ValidationError(self.record, \"Field '{}' expects one of {}, got '{}' instead\".format(\n                    self.name,\n                    ', '.join([repr(t.__name__) for t in self.supported_types]),\n                    type(value).__name__)\n                )",
    "docstring": "Validate value is an acceptable type during set_python operation"
  },
  {
    "code": "def between(self, objs1: List[float], objs2: List[float], n=1):\n        from desdeo.preference.base import ReferencePoint\n        objs1_arr = np.array(objs1)\n        objs2_arr = np.array(objs2)\n        segments = n + 1\n        diff = objs2_arr - objs1_arr\n        solutions = []\n        for x in range(1, segments):\n            btwn_obj = objs1_arr + float(x) / segments * diff\n            solutions.append(\n                self._get_ach().result(ReferencePoint(self, btwn_obj), None)\n            )\n        return ResultSet(solutions)",
    "docstring": "Generate `n` solutions which attempt to trade-off `objs1` and `objs2`.\n\n        Parameters\n        ----------\n        objs1\n            First boundary point for desired objective function values\n\n        objs2\n            Second boundary point for desired objective function values\n\n        n\n            Number of solutions to generate"
  },
  {
    "code": "def process_item(self, item):\n        group, value = item['group'], item['value']\n        if group in self._groups:\n            cur_val = self._groups[group]\n            self._groups[group] = max(cur_val, value)\n        else:\n            self._src.tracking = False\n            new_max = value\n            for rec in self._src.query(criteria={'group': group},\n                                       properties=['value']):\n                new_max = max(new_max, rec['value'])\n            self._src.tracking = True\n            self._groups[group] = new_max",
    "docstring": "Calculate new maximum value for each group,\n        for \"new\" items only."
  },
  {
    "code": "def PmfProbLess(pmf1, pmf2):\n    total = 0.0\n    for v1, p1 in pmf1.Items():\n        for v2, p2 in pmf2.Items():\n            if v1 < v2:\n                total += p1 * p2\n    return total",
    "docstring": "Probability that a value from pmf1 is less than a value from pmf2.\n\n    Args:\n        pmf1: Pmf object\n        pmf2: Pmf object\n\n    Returns:\n        float probability"
  },
  {
    "code": "def _GetStatus(self, two_factor=False):\n    params = ['status']\n    if two_factor:\n      params += ['--twofactor']\n    retcode = self._RunOsLoginControl(params)\n    if retcode is None:\n      if self.oslogin_installed:\n        self.logger.warning('OS Login not installed.')\n        self.oslogin_installed = False\n      return None\n    self.oslogin_installed = True\n    if not os.path.exists(constants.OSLOGIN_NSS_CACHE):\n      return False\n    return not retcode",
    "docstring": "Check whether OS Login is installed.\n\n    Args:\n      two_factor: bool, True if two factor should be enabled.\n\n    Returns:\n      bool, True if OS Login is installed."
  },
  {
    "code": "def load_remote_settings(self, remote_bucket, remote_file):\n        if not self.session:\n            boto_session = boto3.Session()\n        else:\n            boto_session = self.session\n        s3 = boto_session.resource('s3')\n        try:\n            remote_env_object = s3.Object(remote_bucket, remote_file).get()\n        except Exception as e:\n            print('Could not load remote settings file.', e)\n            return\n        try:\n            content = remote_env_object['Body'].read()\n        except Exception as e:\n            print('Exception while reading remote settings file.', e)\n            return\n        try:\n            settings_dict = json.loads(content)\n        except (ValueError, TypeError):\n            print('Failed to parse remote settings!')\n            return\n        for key, value in settings_dict.items():\n            if self.settings.LOG_LEVEL == \"DEBUG\":\n                print('Adding {} -> {} to environment'.format(\n                    key,\n                    value\n                ))\n            try:\n                os.environ[str(key)] = value\n            except Exception:\n                if self.settings.LOG_LEVEL == \"DEBUG\":\n                    print(\"Environment variable keys must be non-unicode!\")",
    "docstring": "Attempt to read a file from s3 containing a flat json object. Adds each\n        key->value pair as environment variables. Helpful for keeping\n        sensitiZve or stage-specific configuration variables in s3 instead of\n        version control."
  },
  {
    "code": "def get_hops(self, start, end=None, forward=True):\n        if forward:\n            return list(self._iterbfs(start=start, end=end, forward=True))\n        else:\n            return list(self._iterbfs(start=start, end=end, forward=False))",
    "docstring": "Computes the hop distance to all nodes centered around a specified node.\n\n        First order neighbours are at hop 1, their neigbours are at hop 2 etc.\n        Uses :py:meth:`forw_bfs` or :py:meth:`back_bfs` depending on the value of the forward\n        parameter.  If the distance between all neighbouring nodes is 1 the hop\n        number corresponds to the shortest distance between the nodes.\n\n        :param start: the starting node\n        :param end: ending node (optional). When not specified will search the whole graph.\n        :param forward: directionality parameter (optional). If C{True} (default) it uses L{forw_bfs} otherwise L{back_bfs}.\n        :return: returns a list of tuples where each tuple contains the node and the hop.\n\n        Typical usage::\n\n            >>> print graph.get_hops(1, 8)\n            >>> [(1, 0), (2, 1), (3, 1), (4, 2), (5, 3), (7, 4), (8, 5)]\n            # node 1 is at 0 hops\n            # node 2 is at 1 hop\n            # ...\n            # node 8 is at 5 hops"
  },
  {
    "code": "def _include_exclude(file_path, include=None, exclude=None):\n    if exclude is not None and exclude:\n        for pattern in exclude:\n            if file_path.match(pattern):\n                return False\n    if include is not None and include:\n        for pattern in include:\n            if file_path.match(pattern):\n                return True\n        return False\n    return True",
    "docstring": "Check if file matches one of include filters and not in exclude filter.\n\n    :param file_path: Path to the file.\n    :param include: Tuple containing patterns to which include from result.\n    :param exclude: Tuple containing patterns to which exclude from result."
  },
  {
    "code": "def newCDataBlock(self, content, len):\n        ret = libxml2mod.xmlNewCDataBlock(self._o, content, len)\n        if ret is None:raise treeError('xmlNewCDataBlock() failed')\n        __tmp = xmlNode(_obj=ret)\n        return __tmp",
    "docstring": "Creation of a new node containing a CDATA block."
  },
  {
    "code": "def base62_encode(cls, num):\n        alphabet = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n        if num == 0:\n            return alphabet[0]\n        arr = []\n        base = len(alphabet)\n        while num:\n            rem = num % base\n            num = num // base\n            arr.append(alphabet[rem])\n        arr.reverse()\n        return ''.join(arr)",
    "docstring": "Encode a number in Base X.\n\n        `num`: The number to encode\n        `alphabet`: The alphabet to use for encoding\n        Stolen from: http://stackoverflow.com/a/1119769/1144479"
  },
  {
    "code": "def image_id_from_k8s():\n    token_path = \"/var/run/secrets/kubernetes.io/serviceaccount/token\"\n    if os.path.exists(token_path):\n        k8s_server = \"https://{}:{}/api/v1/namespaces/default/pods/{}\".format(\n            os.getenv(\"KUBERNETES_SERVICE_HOST\"), os.getenv(\n                \"KUBERNETES_PORT_443_TCP_PORT\"), os.getenv(\"HOSTNAME\")\n        )\n        try:\n            res = requests.get(k8s_server, verify=\"/var/run/secrets/kubernetes.io/serviceaccount/ca.crt\",\n                               timeout=3, headers={\"Authorization\": \"Bearer {}\".format(open(token_path).read())})\n            res.raise_for_status()\n        except requests.RequestException:\n            return None\n        try:\n            return res.json()[\"status\"][\"containerStatuses\"][0][\"imageID\"].strip(\"docker-pullable://\")\n        except (ValueError, KeyError, IndexError):\n            logger.exception(\"Error checking kubernetes for image id\")\n            return None",
    "docstring": "Pings the k8s metadata service for the image id"
  },
  {
    "code": "def nocomment(astr, com='!'):\n    alist = astr.splitlines()\n    for i in range(len(alist)):\n        element = alist[i]\n        pnt = element.find(com)\n        if pnt != -1:\n            alist[i] = element[:pnt]\n    return '\\n'.join(alist)",
    "docstring": "just like the comment in python.\n    removes any text after the phrase 'com'"
  },
  {
    "code": "def resize_bytes(fobj, old_size, new_size, offset):\n    if new_size < old_size:\n        delete_size = old_size - new_size\n        delete_at = offset + new_size\n        delete_bytes(fobj, delete_size, delete_at)\n    elif new_size > old_size:\n        insert_size = new_size - old_size\n        insert_at = offset + old_size\n        insert_bytes(fobj, insert_size, insert_at)",
    "docstring": "Resize an area in a file adding and deleting at the end of it.\n    Does nothing if no resizing is needed.\n\n    Args:\n        fobj (fileobj)\n        old_size (int): The area starting at offset\n        new_size (int): The new size of the area\n        offset (int): The start of the area\n    Raises:\n        IOError"
  },
  {
    "code": "def upload(self, response, file):\n        response = response.json()\n        if not response.get('upload_url'):\n            raise ValueError('Bad API response. No upload_url.')\n        if not response.get('upload_params'):\n            raise ValueError('Bad API response. No upload_params.')\n        kwargs = response.get('upload_params')\n        response = self._requester.request(\n            'POST',\n            use_auth=False,\n            _url=response.get('upload_url'),\n            file=file,\n            _kwargs=combine_kwargs(**kwargs)\n        )\n        response_json = json.loads(response.text.lstrip('while(1);'))\n        return ('url' in response_json, response_json)",
    "docstring": "Upload the file.\n\n        :param response: The response from the upload request.\n        :type response: dict\n        :param file: A file handler pointing to the file to upload.\n        :returns: True if the file uploaded successfully, False otherwise, \\\n            and the JSON response from the API.\n        :rtype: tuple"
  },
  {
    "code": "def sub(self, key):\n        subv = Vyper()\n        data = self.get(key)\n        if isinstance(data, dict):\n            subv._config = data\n            return subv\n        else:\n            return None",
    "docstring": "Returns new Vyper instance representing a sub tree of this instance."
  },
  {
    "code": "def _read_opt_lio(self, code, *, desc):\n        _type = self._read_opt_type(code)\n        _size = self._read_unpack(1)\n        _llen = self._read_unpack(1)\n        _line = self._read_fileng(_llen)\n        opt = dict(\n            desc=desc,\n            type=_type,\n            length=_size + 2,\n            lid_len=_llen,\n            lid=_line,\n        )\n        _plen = _size - _llen\n        if _plen:\n            self._read_fileng(_plen)\n        return opt",
    "docstring": "Read HOPOPT Line-Identification option.\n\n        Structure of HOPOPT Line-Identification option [RFC 6788]:\n             0                   1                   2                   3\n             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n                                            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n                                            |  Option Type  | Option Length |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            | LineIDLen     |     Line ID...\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n            Octets      Bits        Name                        Description\n              0           0     hopopt.lio.type             Option Type\n              0           0     hopopt.lio.type.value       Option Number\n              0           0     hopopt.lio.type.action      Action (10)\n              0           2     hopopt.lio.type.change      Change Flag (0)\n              1           8     hopopt.lio.length           Length of Option Data\n              2          16     hopopt.lio.lid_len          Line ID Length\n              3          24     hopopt.lio.lid              Line ID"
  },
  {
    "code": "def without_edge(self, edge: Edge) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]':\n        return BipartiteGraph((e2, v) for e2, v in self._edges.items() if edge != e2)",
    "docstring": "Returns a copy of this bipartite graph with the given edge removed."
  },
  {
    "code": "def setValues(self, rows, *values):\n        'Set our column value for given list of rows to `value`.'\n        for r, v in zip(rows, itertools.cycle(values)):\n            self.setValueSafe(r, v)\n        self.recalc()\n        return status('set %d cells to %d values' % (len(rows), len(values)))",
    "docstring": "Set our column value for given list of rows to `value`."
  },
  {
    "code": "def lookup_prefix(self, prefix, timestamp=timestamp_now):\n        prefix = prefix.strip().upper()\n        if self._lookuptype == \"clublogxml\" or self._lookuptype == \"countryfile\":\n            return self._check_data_for_date(prefix, timestamp, self._prefixes, self._prefixes_index)\n        elif self._lookuptype == \"redis\":\n            data_dict, index = self._get_dicts_from_redis(\"_prefix_\", \"_prefix_index_\", self._redis_prefix, prefix)\n            return self._check_data_for_date(prefix, timestamp, data_dict, index)\n        raise KeyError",
    "docstring": "Returns lookup data of a Prefix\n\n        Args:\n            prefix (string): Prefix of a Amateur Radio callsign\n            timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)\n\n        Returns:\n            dict: Dictionary containing the country specific data of the Prefix\n\n        Raises:\n            KeyError: No matching Prefix found\n            APIKeyMissingError: API Key for Clublog missing or incorrect\n\n        Example:\n           The following code shows how to obtain the information for the prefix \"DH\" from the countryfile.com\n           database (default database).\n\n           >>> from pyhamtools import LookupLib\n           >>> myLookupLib = LookupLib()\n           >>> print myLookupLib.lookup_prefix(\"DH\")\n           {\n            'adif': 230,\n            'country': u'Fed. Rep. of Germany',\n            'longitude': 10.0,\n            'cqz': 14,\n            'ituz': 28,\n            'latitude': 51.0,\n            'continent': u'EU'\n           }\n\n        Note:\n            This method is available for\n\n            - clublogxml\n            - countryfile\n            - redis"
  },
  {
    "code": "def query_target(target_chembl_id):\n    query_dict = {'query': 'target',\n                  'params': {'target_chembl_id': target_chembl_id,\n                             'limit': 1}}\n    res = send_query(query_dict)\n    target = res['targets'][0]\n    return target",
    "docstring": "Query ChEMBL API target by id\n\n    Parameters\n    ----------\n    target_chembl_id : str\n\n    Returns\n    -------\n    target : dict\n        dict parsed from json that is unique for the target"
  },
  {
    "code": "def sadd(self, key, *values):\n        if len(values) == 0:\n            raise ResponseError(\"wrong number of arguments for 'sadd' command\")\n        redis_set = self._get_set(key, 'SADD', create=True)\n        before_count = len(redis_set)\n        redis_set.update(map(self._encode, values))\n        after_count = len(redis_set)\n        return after_count - before_count",
    "docstring": "Emulate sadd."
  },
  {
    "code": "def visualize_model(X, y, estimator, path, **kwargs):\n    y = LabelEncoder().fit_transform(y)\n    model = Pipeline([\n         ('one_hot_encoder', OneHotEncoder()), \n         ('estimator', estimator)\n    ])\n    _, ax = plt.subplots()\n    visualizer = ClassificationReport(\n        model, classes=['edible', 'poisonous'], \n        cmap=\"YlGn\", size=(600, 360), ax=ax, **kwargs\n    )\n    visualizer.fit(X, y)  \n    visualizer.score(X, y)\n    visualizer.poof(outpath=path)",
    "docstring": "Test various estimators."
  },
  {
    "code": "def add(self, data_source, module, package=None):\n        super(Data, self).add(data_source, module, package)\n        if data_source not in self.layer:\n            self.layer[data_source] = {'module': module, 'package': package}\n        self.objects[data_source] = None",
    "docstring": "Add data_source to model. Tries to import module, then looks for data\n        source class definition.\n\n        :param data_source: Name of data source to add.\n        :type data_source: str\n        :param module: Module in which data source resides. Can be absolute or\n            relative. See :func:`importlib.import_module`\n        :type module: str\n        :param package: Optional, but must be used if module is relative.\n        :type package: str\n\n        .. seealso::\n            :func:`importlib.import_module`"
  },
  {
    "code": "def validate_signature(self, filename):\n        if not GPG_PRESENT:\n            return False\n        sigfilename = filename + '.sig'\n        try:\n            with open(sigfilename):\n                pass\n        except IOError:\n            return False\n        return verify(sigfilename, filename)",
    "docstring": "Returns True if a valid signature is present for filename"
  },
  {
    "code": "def get_parent_path(index=2):\n    try:\n        path = _caller_path(index)\n    except RuntimeError:\n        path = os.getcwd()\n    path = os.path.abspath(os.path.join(path, os.pardir))\n    return path",
    "docstring": "Get the caller's parent path to sys.path\n    If the caller is a CLI through stdin, the parent of the current working\n    directory is used"
  },
  {
    "code": "def _assertIndex(self, index):\n        if type(index) is not int:\n            raise TypeError('list indices must be integers')\n        if index < 0 or index >= self.nelems:\n            raise IndexError('list index out of range')",
    "docstring": "Raise TypeError or IndexError if index is not an integer or out of\n        range for the number of elements in this array, respectively."
  },
  {
    "code": "def get_pattern_additional_cycles(self, patternnumber):\n        _checkPatternNumber(patternnumber)\n        address = _calculateRegisterAddress('cycles', patternnumber)\n        return self.read_register(address)",
    "docstring": "Get the number of additional cycles for a given pattern.\n\n        Args:\n            patternnumber (integer): 0-7\n            \n        Returns:\n            The number of additional cycles (int)."
  },
  {
    "code": "def cardinal(self, to):\n        return sum(1 for _ in filter(\n            lambda d: not d.external and d.target in to, self.dependencies))",
    "docstring": "Return the number of dependencies of this module to the given node.\n\n        Args:\n            to (Package/Module): the target node.\n\n        Returns:\n            int: number of dependencies."
  },
  {
    "code": "def _restore_group(self, group_id):\n        meta = self.TaskSetModel._default_manager.restore_taskset(group_id)\n        if meta:\n            return meta.to_dict()",
    "docstring": "Get group metadata for a group by id."
  },
  {
    "code": "def get_all_hosted_routers(self, context):\n        cctxt = self.client.prepare()\n        return cctxt.call(context, 'cfg_sync_all_hosted_routers',\n                          host=self.host)",
    "docstring": "Make a remote process call to retrieve the sync data for\n           routers that have been scheduled to a hosting device.\n\n        :param context: session context"
  },
  {
    "code": "def _db(self):\n        if not hasattr(self, \"_db_client\") or getattr(self, \"_db_client\") is None:\n            self._db_client = get_db_client()\n        return self._db_client",
    "docstring": "Database client for accessing storage.\n\n           :returns: :class:`livebridge.storages.base.BaseStorage`"
  },
  {
    "code": "def _check_available(name):\n    _status = _systemctl_status(name)\n    sd_version = salt.utils.systemd.version(__context__)\n    if sd_version is not None and sd_version >= 231:\n        return 0 <= _status['retcode'] < 4\n    out = _status['stdout'].lower()\n    if 'could not be found' in out:\n        return False\n    for line in salt.utils.itertools.split(out, '\\n'):\n        match = re.match(r'\\s+loaded:\\s+(\\S+)', line)\n        if match:\n            ret = match.group(1) != 'not-found'\n            break\n    else:\n        raise CommandExecutionError(\n            'Failed to get information on unit \\'%s\\'' % name\n        )\n    return ret",
    "docstring": "Returns boolean telling whether or not the named service is available"
  },
  {
    "code": "def get_help_text(self):\n        txt = str('\\n')\n        for name, info in self.commands.items():\n            command_txt = \"\\t{0: <22} {1}\\n\".format(name, info['description'])\n            if info['attributes']:\n                command_txt = ''.join([command_txt, \"\\t Attributes:\\n\"])\n                for attrname, attrdesc in info['attributes'].items():\n                    attr_txt = \"\\t  {0: <22} {1}\\n\".format(attrname, attrdesc)\n                    command_txt = ''.join([command_txt, attr_txt])\n            if info['elements']:\n                command_txt = ''.join([command_txt, \"\\t Elements:\\n\",\n                                       self.elements_as_text(info['elements'])])\n            txt = ''.join([txt, command_txt])\n        return txt",
    "docstring": "Returns the help output in plain text format."
  },
  {
    "code": "def MetatagDistinctValuesGet(self, metatag_name, namespace = None):\r\n        ns = \"default\" if namespace is None else namespace\r\n        if self.__SenseApiCall__(\"/metatag_name/{0}/distinct_values.json\", \"GET\", parameters = {'namespace': ns}):\r\n            return True\r\n        else:\r\n            self.__error__ = \"api call unsuccessful\"\r\n            return False",
    "docstring": "Find the distinct value of a metatag name in a certain namespace\r\n            \r\n            @param metatag_name (string) - Name of the metatag for which to find the distinct values\r\n            @param namespace (stirng) - Namespace in which to find the distinct values\r\n            \r\n            @return (bool) - Boolean indicating whether MetatagDistinctValuesGet was successful"
  },
  {
    "code": "def check_platforms(platforms):\n  if len(platforms) > 0:\n    return all(platform in PLATFORM_IDS for platform in platforms)\n  return True",
    "docstring": "Checks if the platforms have a valid platform code"
  },
  {
    "code": "def encipher(self,string):\n        string = self.remove_punctuation(string)\n        ret = ''\n        for (i,c) in enumerate(string):\n            if i<len(self.key): offset = self.a2i(self.key[i])\n            else: offset = self.a2i(string[i-len(self.key)])     \n            ret += self.i2a(self.a2i(c)+offset)\n        return ret",
    "docstring": "Encipher string using Autokey cipher according to initialised key. Punctuation and whitespace\n        are removed from the input.       \n\n        Example::\n\n            ciphertext = Autokey('HELLO').encipher(plaintext)     \n\n        :param string: The string to encipher.\n        :returns: The enciphered string."
  },
  {
    "code": "def get_requested_quarter_data(self,\n                                   zero_qtr_data,\n                                   zeroth_quarter_idx,\n                                   stacked_last_per_qtr,\n                                   num_announcements,\n                                   dates):\n        zero_qtr_data_idx = zero_qtr_data.index\n        requested_qtr_idx = pd.MultiIndex.from_arrays(\n            [\n                zero_qtr_data_idx.get_level_values(0),\n                zero_qtr_data_idx.get_level_values(1),\n                self.get_shifted_qtrs(\n                    zeroth_quarter_idx.get_level_values(\n                        NORMALIZED_QUARTERS,\n                    ),\n                    num_announcements,\n                ),\n            ],\n            names=[\n                zero_qtr_data_idx.names[0],\n                zero_qtr_data_idx.names[1],\n                SHIFTED_NORMALIZED_QTRS,\n            ],\n        )\n        requested_qtr_data = stacked_last_per_qtr.loc[requested_qtr_idx]\n        requested_qtr_data = requested_qtr_data.reset_index(\n            SHIFTED_NORMALIZED_QTRS,\n        )\n        (requested_qtr_data[FISCAL_YEAR_FIELD_NAME],\n         requested_qtr_data[FISCAL_QUARTER_FIELD_NAME]) = \\\n            split_normalized_quarters(\n                requested_qtr_data[SHIFTED_NORMALIZED_QTRS]\n            )\n        return requested_qtr_data.unstack(SID_FIELD_NAME).reindex(dates)",
    "docstring": "Selects the requested data for each date.\n\n        Parameters\n        ----------\n        zero_qtr_data : pd.DataFrame\n            The 'time zero' data for each calendar date per sid.\n        zeroth_quarter_idx : pd.Index\n            An index of calendar dates, sid, and normalized quarters, for only\n            the rows that have a next or previous earnings estimate.\n        stacked_last_per_qtr : pd.DataFrame\n            The latest estimate known with the dates, normalized quarter, and\n            sid as the index.\n        num_announcements : int\n            The number of annoucements out the user requested relative to\n            each date in the calendar dates.\n        dates : pd.DatetimeIndex\n            The calendar dates for which estimates data is requested.\n\n        Returns\n        --------\n        requested_qtr_data : pd.DataFrame\n            The DataFrame with the latest values for the requested quarter\n            for all columns; `dates` are the index and columns are a MultiIndex\n            with sids at the top level and the dataset columns on the bottom."
  },
  {
    "code": "def parse_startup_message(self):\n\t\treturn parse_map(lambda args: OmapiStartupMessage(*args), parse_chain(self.parse_net32int, lambda _: self.parse_net32int()))",
    "docstring": "results in an OmapiStartupMessage\n\n\t\t>>> d = b\"\\\\0\\\\0\\\\0\\\\x64\\\\0\\\\0\\\\0\\\\x18\"\n\t\t>>> next(InBuffer(d).parse_startup_message()).validate()"
  },
  {
    "code": "def cal_frame_according_boundaries(left, right, top, bottom, parent_size, gaphas_editor=True, group=True):\n    margin = cal_margin(parent_size)\n    if group:\n        rel_pos = max(left - margin, 0), max(top - margin, 0)\n        size = (min(right - left + 2 * margin, parent_size[0] - rel_pos[0]),\n                min(bottom - top + 2 * margin, parent_size[1] - rel_pos[1]))\n    else:\n        rel_pos = left, top\n        size = right - left, bottom - top\n    return margin, rel_pos, size",
    "docstring": "Generate margin and relative position and size handed boundary parameter and parent size"
  },
  {
    "code": "def create_permissions_from_tuples(model, codename_tpls):\n    if codename_tpls:\n        model_cls = django_apps.get_model(model)\n        content_type = ContentType.objects.get_for_model(model_cls)\n        for codename_tpl in codename_tpls:\n            app_label, codename, name = get_from_codename_tuple(\n                codename_tpl, model_cls._meta.app_label\n            )\n            try:\n                Permission.objects.get(codename=codename, content_type=content_type)\n            except ObjectDoesNotExist:\n                Permission.objects.create(\n                    name=name, codename=codename, content_type=content_type\n                )\n            verify_codename_exists(f\"{app_label}.{codename}\")",
    "docstring": "Creates custom permissions on model \"model\"."
  },
  {
    "code": "async def apply_command(self, cmd):\n        if cmd:\n            if cmd.prehook:\n                await cmd.prehook(ui=self, dbm=self.dbman, cmd=cmd)\n            try:\n                if asyncio.iscoroutinefunction(cmd.apply):\n                    await cmd.apply(self)\n                else:\n                    cmd.apply(self)\n            except Exception as e:\n                self._error_handler(e)\n            else:\n                if cmd.posthook:\n                    logging.info('calling post-hook')\n                    await cmd.posthook(ui=self, dbm=self.dbman, cmd=cmd)",
    "docstring": "applies a command\n\n        This calls the pre and post hooks attached to the command,\n        as well as :meth:`cmd.apply`.\n\n        :param cmd: an applicable command\n        :type cmd: :class:`~alot.commands.Command`"
  },
  {
    "code": "def add_record(post_id, catalog_id, order=0):\n        rec = MPost2Catalog.__get_by_info(post_id, catalog_id)\n        if rec:\n            entry = TabPost2Tag.update(\n                order=order,\n                par_id=rec.tag_id[:2] + '00',\n            ).where(TabPost2Tag.uid == rec.uid)\n            entry.execute()\n        else:\n            TabPost2Tag.create(\n                uid=tools.get_uuid(),\n                par_id=catalog_id[:2] + '00',\n                post_id=post_id,\n                tag_id=catalog_id,\n                order=order,\n            )\n        MCategory.update_count(catalog_id)",
    "docstring": "Create the record of post 2 tag, and update the count in g_tag."
  },
  {
    "code": "def register_piece(self, from_address, to_address, hash, password, min_confirmations=6, sync=False, ownership=True):\n        file_hash, file_hash_metadata = hash\n        path, from_address = from_address\n        verb = Spoolverb()\n        unsigned_tx = self.simple_spool_transaction(from_address,\n                                                    [file_hash, file_hash_metadata, to_address],\n                                                    op_return=verb.piece,\n                                                    min_confirmations=min_confirmations)\n        signed_tx = self._t.sign_transaction(unsigned_tx, password)\n        txid = self._t.push(signed_tx)\n        return txid",
    "docstring": "Register a piece\n\n        Args:\n            from_address (Tuple[str]): Federation address. All register transactions\n                originate from the the Federation wallet\n            to_address (str): Address registering the edition\n            hash (Tuple[str]): Hash of the piece. (file_hash, file_hash_metadata)\n            password (str): Federation wallet password. For signing the transaction\n            edition_num (int): The number of the edition to register. User\n                edition_num=0 to register the master edition\n            min_confirmations (int): Override the number of confirmations when\n                chosing the inputs of the transaction. Defaults to 6\n            sync (bool): Perform the transaction in synchronous mode, the call to the\n                function will block until there is at least on confirmation on\n                the blockchain. Defaults to False\n            ownership (bool): Check ownsership in the blockchain before pushing the\n                transaction. Defaults to True\n\n        Returns:\n            str: transaction id"
  },
  {
    "code": "def debug(*args):\n    for i in args:\n        click.echo('D:%s' % str(i), err=True)",
    "docstring": "Send debug messages to the Maltego console."
  },
  {
    "code": "def amount(self, amount):\n        if amount is None:\n            raise ValueError(\"Invalid value for `amount`, must not be `None`\")\n        if amount < 0:\n            raise ValueError(\"Invalid value for `amount`, must be a value greater than or equal to `0`\")\n        self._amount = amount",
    "docstring": "Sets the amount of this Money.\n        The amount of money, in the smallest denomination of the currency indicated by `currency`. For example, when `currency` is `USD`, `amount` is in cents.\n\n        :param amount: The amount of this Money.\n        :type: int"
  },
  {
    "code": "def item_options(self, **kwargs):\n        actions = self._item_actions.copy()\n        if self._resource.is_singular:\n            actions['create'] = ('POST',)\n        methods = self._get_handled_methods(actions)\n        return self._set_options_headers(methods)",
    "docstring": "Handle collection OPTIONS request.\n\n        Singular route requests are handled a bit differently because\n        singular views may handle POST requests despite being registered\n        as item routes."
  },
  {
    "code": "def prepare(cls):\n        if cls._ask_openapi():\n            napp_path = Path()\n            tpl_path = SKEL_PATH / 'napp-structure/username/napp'\n            OpenAPI(napp_path, tpl_path).render_template()\n            print('Please, update your openapi.yml file.')\n            sys.exit()",
    "docstring": "Prepare NApp to be uploaded by creating openAPI skeleton."
  },
  {
    "code": "def get_diff_endpoints_from_commit_range(repo, commit_range):\n    if not commit_range:\n        raise ValueError('commit_range cannot be empty')\n    result = re_find(COMMIT_RANGE_REGEX, commit_range)\n    if not result:\n        raise ValueError(\n            'Expected diff str of the form \\'a..b\\' or \\'a...b\\' (got {})'\n            .format(commit_range))\n    a, b = result['a'], result['b']\n    a, b = repo.rev_parse(a), repo.rev_parse(b)\n    if result['thirddot']:\n        a = one_or_raise(repo.merge_base(a, b))\n    return a, b",
    "docstring": "Get endpoints of a diff given a commit range\n\n    The resulting endpoints can be diffed directly::\n\n        a, b = get_diff_endpoints_from_commit_range(repo, commit_range)\n        a.diff(b)\n\n    For details on specifying git diffs, see ``git diff --help``.\n    For details on specifying revisions, see ``git help revisions``.\n\n    Args:\n        repo (git.Repo): Repo object initialized with project root\n        commit_range (str): commit range as would be interpreted by ``git\n            diff`` command. Unfortunately only patterns of the form ``a..b``\n            and ``a...b`` are accepted. Note that the latter pattern finds the\n            merge-base of a and b and uses it as the starting point for the\n            diff.\n\n    Returns:\n        Tuple[git.Commit, git.Commit]: starting commit, ending commit (\n            inclusive)\n\n    Raises:\n        ValueError: commit_range is empty or ill-formed\n\n    See also:\n\n        <https://stackoverflow.com/q/7251477>"
  },
  {
    "code": "def authenticate(self, user, password):\n        assert user['password_hash'] == '_'.join((password, 'hash'))\n        self.logger.debug('User %s has been successfully authenticated',\n                          user['uid'])",
    "docstring": "Authenticate user."
  },
  {
    "code": "def add_arguments(self, parser):\n        subparsers = parser.add_subparsers(help='sub-command help',\n                                           dest='command')\n        add_parser = partial(_add_subparser, subparsers, parser)\n        add_parser('list', help=\"list concurrency triggers\")\n        add_parser('drop', help=\"drop  concurrency triggers\")\n        add_parser('create', help=\"create concurrency triggers\")\n        parser.add_argument('-d', '--database',\n                            action='store',\n                            dest='database',\n                            default=None,\n                            help='limit to this database')\n        parser.add_argument('-t', '--trigger',\n                            action='store',\n                            dest='trigger',\n                            default=None,\n                            help='limit to this trigger name')",
    "docstring": "Entry point for subclassed commands to add custom arguments."
  },
  {
    "code": "def toggle_concatenate(self):\n        if not (self.chunk['epoch'].isChecked() and\n                self.lock_to_staging.get_value()):\n            for i,j in zip([self.idx_chan, self.idx_cycle, self.idx_stage,\n                            self.idx_evt_type],\n                   [self.cat['chan'], self.cat['cycle'],\n                    self.cat['stage'], self.cat['evt_type']]):\n                if len(i.selectedItems()) > 1:\n                    j.setEnabled(True)\n                else:\n                    j.setEnabled(False)\n                    j.setChecked(False)\n        if not self.chunk['event'].isChecked():\n            self.cat['evt_type'].setEnabled(False)\n        if not self.cat['discontinuous'].get_value():\n            self.cat['chan'].setEnabled(False)\n            self.cat['chan'].setChecked(False)\n        self.update_nseg()",
    "docstring": "Enable and disable concatenation options."
  },
  {
    "code": "def convert_machine_list_time_val(text: str) -> datetime.datetime:\n    text = text[:14]\n    if len(text) != 14:\n        raise ValueError('Time value not 14 chars')\n    year = int(text[0:4])\n    month = int(text[4:6])\n    day = int(text[6:8])\n    hour = int(text[8:10])\n    minute = int(text[10:12])\n    second = int(text[12:14])\n    return datetime.datetime(year, month, day, hour, minute, second,\n                             tzinfo=datetime.timezone.utc)",
    "docstring": "Convert RFC 3659 time-val to datetime objects."
  },
  {
    "code": "def _zoom_rows(self, zoom):\n        self.grid.SetDefaultRowSize(self.grid.std_row_size * zoom,\n                                    resizeExistingRows=True)\n        self.grid.SetRowLabelSize(self.grid.row_label_size * zoom)\n        for row, tab in self.code_array.row_heights:\n            if tab == self.grid.current_table and \\\n               row < self.grid.code_array.shape[0]:\n                base_row_width = self.code_array.row_heights[(row, tab)]\n                if base_row_width is None:\n                    base_row_width = self.grid.GetDefaultRowSize()\n                zoomed_row_size = base_row_width * zoom\n                self.grid.SetRowSize(row, zoomed_row_size)",
    "docstring": "Zooms grid rows"
  },
  {
    "code": "def bulk_copy(self, ids):\n        schema = DeviceSchema()\n        return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)",
    "docstring": "Bulk copy a set of devices.\n\n        :param ids: Int list of device IDs.\n        :return: :class:`devices.Device <devices.Device>` list"
  },
  {
    "code": "def configure(self, options, conf):\n        self.conf = conf\n        self.when = options.browser_closer_when",
    "docstring": "Configure plugin. Plugin is enabled by default."
  },
  {
    "code": "def _make(c):\n    ann = defaultdict(list)\n    for pos in c['ann']:\n        for db in pos:\n            ann[db] += list(pos[db])\n    logger.debug(ann)\n    valid = [l for l in c['valid']]\n    ann_list = [\", \".join(list(set(ann[feature]))) for feature in ann if feature in valid]\n    return valid, ann_list",
    "docstring": "create html from template, adding figure,\n    annotation and sequences counts"
  },
  {
    "code": "def get_objects(self):\n        return rope.base.oi.soi.get_passed_objects(\n            self.pyfunction, self.index)",
    "docstring": "Returns the list of objects passed as this parameter"
  },
  {
    "code": "def edit(filename, identifier, data):\n    with open(filename, 'r') as fh:\n        bibtex = bibtexparser.load(fh)\n    bibtex.entries_dict[identifier] = data.entries[0]\n    write(filename, bibtex)",
    "docstring": "Update an entry in a BibTeX file.\n\n    :param filename: The name of the BibTeX file to edit.\n    :param identifier: The id of the entry to update, in the BibTeX file.\n    :param data: A dict associating fields and updated values. Fields present \\\n            in the BibTeX file but not in this dict will be kept as is."
  },
  {
    "code": "def pretty_print(self, indent=0):\n        s = tab = ' '*indent\n        s += '%s: ' %self.tag\n        if isinstance(self.value, basestring):\n            s += self.value\n        else:\n            s += '\\n'\n            for e in self.value:\n                s += e.pretty_print(indent+4)\n        s += '\\n'\n        return s",
    "docstring": "Print the document without tags using indentation"
  },
  {
    "code": "def basic_auth(self, username, password):\n        if not (username and password):\n            return\n        self.auth = (username, password)\n        self.headers.pop('Authorization', None)",
    "docstring": "Set the Basic Auth credentials on this Session.\n\n        :param str username: Your GitHub username\n        :param str password: Your GitHub password"
  },
  {
    "code": "def searchEnterpriseGroups(self, searchFilter=\"\", maxCount=100):\n        params = {\n            \"f\" : \"json\",\n            \"filter\" : searchFilter,\n            \"maxCount\" : maxCount\n        }\n        url = self._url + \"/groups/searchEnterpriseGroups\"\n        return self._post(url=url,\n                          param_dict=params,\n                          proxy_url=self._proxy_url,\n                          proxy_port=self._proxy_port)",
    "docstring": "This operation searches groups in the configured enterprise group\n        store. You can narrow down the search using the search filter\n        parameter.\n\n        Parameters:\n           searchFilter - text value to narrow the search down\n           maxCount - maximum number of records to return"
  },
  {
    "code": "def validation_statuses(self, area_uuid):\n        path = \"/area/{uuid}/validations\".format(uuid=area_uuid)\n        result = self._make_request('get', path)\n        return result.json()",
    "docstring": "Get count of validation statuses for all files in upload_area\n\n        :param str area_uuid: A RFC4122-compliant ID for the upload area\n        :return: a dict with key for each state and value being the count of files in that state\n        :rtype: dict\n        :raises UploadApiException: if information could not be obtained"
  },
  {
    "code": "def get_callproc_signature(self, name, param_types):\n    if isinstance(param_types[0], (list, tuple)):\n      params = [self.sql_writer.to_placeholder(*pt) for pt in param_types]\n    else:\n      params = [self.sql_writer.to_placeholder(None, pt) for pt in param_types]\n    return name + self.sql_writer.to_tuple(params)",
    "docstring": "Returns a procedure's signature from the name and list of types.\n\n    :name: the name of the procedure\n    :params: can be either strings, or 2-tuples. 2-tuples must be of the form (name, db_type).\n    :return: the procedure's signature"
  },
  {
    "code": "def diff(x, lag=1, differences=1):\n    if any(v < 1 for v in (lag, differences)):\n        raise ValueError('lag and differences must be positive (> 0) integers')\n    x = check_array(x, ensure_2d=False, dtype=np.float32)\n    fun = _diff_vector if x.ndim == 1 else _diff_matrix\n    res = x\n    for i in range(differences):\n        res = fun(res, lag)\n        if not res.shape[0]:\n            return res\n    return res",
    "docstring": "Difference an array.\n\n    A python implementation of the R ``diff`` function [1]. This computes lag\n    differences from an array given a ``lag`` and ``differencing`` term.\n\n    If ``x`` is a vector of length :math:`n`, ``lag=1`` and ``differences=1``,\n    then the computed result is equal to the successive differences\n    ``x[lag:n] - x[:n-lag]``.\n\n    Examples\n    --------\n    Where ``lag=1`` and ``differences=1``:\n\n    >>> x = c(10, 4, 2, 9, 34)\n    >>> diff(x, 1, 1)\n    array([ -6.,  -2.,   7.,  25.], dtype=float32)\n\n    Where ``lag=1`` and ``differences=2``:\n\n    >>> x = c(10, 4, 2, 9, 34)\n    >>> diff(x, 1, 2)\n    array([  4.,   9.,  18.], dtype=float32)\n\n    Where ``lag=3`` and ``differences=1``:\n\n    >>> x = c(10, 4, 2, 9, 34)\n    >>> diff(x, 3, 1)\n    array([ -1.,  30.], dtype=float32)\n\n    Where ``lag=6`` (larger than the array is) and ``differences=1``:\n\n    >>> x = c(10, 4, 2, 9, 34)\n    >>> diff(x, 6, 1)\n    array([], dtype=float32)\n\n    For a 2d array with ``lag=1`` and ``differences=1``:\n\n    >>> import numpy as np\n    >>>\n    >>> x = np.arange(1, 10).reshape((3, 3)).T\n    >>> diff(x, 1, 1)\n    array([[ 1.,  1.,  1.],\n           [ 1.,  1.,  1.]], dtype=float32)\n\n    Parameters\n    ----------\n    x : array-like, shape=(n_samples, [n_features])\n        The array to difference.\n\n    lag : int, optional (default=1)\n        An integer > 0 indicating which lag to use.\n\n    differences : int, optional (default=1)\n        An integer > 0 indicating the order of the difference.\n\n    Returns\n    -------\n    res : np.ndarray, shape=(n_samples, [n_features])\n        The result of the differenced arrays.\n\n    References\n    ----------\n    .. [1] https://stat.ethz.ch/R-manual/R-devel/library/base/html/diff.html"
  },
  {
    "code": "def parse_macro_params(token):\n    try:\n        bits = token.split_contents()\n        tag_name, macro_name, values = bits[0], bits[1], bits[2:]\n    except IndexError:\n        raise template.TemplateSyntaxError(\n            \"{0} tag requires at least one argument (macro name)\".format(\n                token.contents.split()[0]))\n    args = []\n    kwargs = {}\n    kwarg_regex = (\n        r'^([A-Za-z_][\\w_]*)=(\".*\"|{0}.*{0}|[A-Za-z_][\\w_]*)$'.format(\n            \"'\"))\n    arg_regex = r'^([A-Za-z_][\\w_]*|\".*\"|{0}.*{0}|(\\d+))$'.format(\n        \"'\")\n    for value in values:\n        kwarg_match = regex_match(\n            kwarg_regex, value)\n        if kwarg_match:\n            kwargs[kwarg_match.groups()[0]] = template.Variable(\n                kwarg_match.groups()[1])\n        else:\n            arg_match = regex_match(\n                arg_regex, value)\n            if arg_match:\n                args.append(template.Variable(arg_match.groups()[0]))\n            else:\n                raise template.TemplateSyntaxError(\n                    \"Malformed arguments to the {0} tag.\".format(\n                        tag_name))\n    return tag_name, macro_name, args, kwargs",
    "docstring": "Common parsing logic for both use_macro and macro_block"
  },
  {
    "code": "def get_local_user():\n    import getpass\n    username = None\n    try:\n        username = getpass.getuser()\n    except KeyError:\n        pass\n    except ImportError:\n        if win32:\n            import win32api\n            import win32security\n            import win32profile\n            username = win32api.GetUserName()\n    return username",
    "docstring": "Return the local executing username, or ``None`` if one can't be found.\n\n    .. versionadded:: 2.0"
  },
  {
    "code": "def visit_ImportFrom(self, node):\n        if node.level:\n            raise PythranSyntaxError(\"Relative import not supported\", node)\n        if not node.module:\n            raise PythranSyntaxError(\"import from without module\", node)\n        module = node.module\n        current_module = MODULES\n        for path in module.split('.'):\n            if path not in current_module:\n                raise PythranSyntaxError(\n                    \"Module '{0}' unknown.\".format(module),\n                    node)\n            else:\n                current_module = current_module[path]\n        for alias in node.names:\n            if alias.name == '*':\n                continue\n            elif alias.name not in current_module:\n                raise PythranSyntaxError(\n                    \"identifier '{0}' not found in module '{1}'\".format(\n                        alias.name,\n                        module),\n                    node)",
    "docstring": "Check validity of imported functions.\n\n            Check:\n                - no level specific value are provided.\n                - a module is provided\n                - module/submodule exists in MODULES\n                - imported function exists in the given module/submodule"
  },
  {
    "code": "def _gen_keys_from_multicol_key(key_multicol, n_keys):\n    keys = [('{}{:03}of{:03}')\n            .format(key_multicol, i+1, n_keys) for i in range(n_keys)]\n    return keys",
    "docstring": "Generates single-column keys from multicolumn key."
  },
  {
    "code": "def _set_categories(self, categories, fastpath=False):\n        if fastpath:\n            new_dtype = CategoricalDtype._from_fastpath(categories,\n                                                        self.ordered)\n        else:\n            new_dtype = CategoricalDtype(categories, ordered=self.ordered)\n        if (not fastpath and self.dtype.categories is not None and\n                len(new_dtype.categories) != len(self.dtype.categories)):\n            raise ValueError(\"new categories need to have the same number of \"\n                             \"items than the old categories!\")\n        self._dtype = new_dtype",
    "docstring": "Sets new categories inplace\n\n        Parameters\n        ----------\n        fastpath : bool, default False\n           Don't perform validation of the categories for uniqueness or nulls\n\n        Examples\n        --------\n        >>> c = pd.Categorical(['a', 'b'])\n        >>> c\n        [a, b]\n        Categories (2, object): [a, b]\n\n        >>> c._set_categories(pd.Index(['a', 'c']))\n        >>> c\n        [a, c]\n        Categories (2, object): [a, c]"
  },
  {
    "code": "def current_time(self) -> datetime:\n        _date = datetime.strptime(self.obj.SBRes.SBReq.StartT.get(\"date\"), \"%Y%m%d\")\n        _time = datetime.strptime(self.obj.SBRes.SBReq.StartT.get(\"time\"), \"%H:%M\")\n        return datetime.combine(_date.date(), _time.time())",
    "docstring": "Extract current time."
  },
  {
    "code": "def pdf_doc_info(instance):\n    for key, obj in instance['objects'].items():\n        if ('type' in obj and obj['type'] == 'file'):\n            try:\n                did = obj['extensions']['pdf-ext']['document_info_dict']\n            except KeyError:\n                continue\n            for elem in did:\n                if elem not in enums.PDF_DID:\n                    yield JSONError(\"The 'document_info_dict' property of \"\n                                    \"object '%s' contains a key ('%s') that is\"\n                                    \" not a valid PDF Document Information \"\n                                    \"Dictionary key.\"\n                                    % (key, elem), instance['id'],\n                                    'pdf-doc-info')",
    "docstring": "Ensure the keys of the 'document_info_dict' property of the pdf-ext\n    extension of file objects are only valid PDF Document Information\n    Dictionary Keys."
  },
  {
    "code": "def update_source(self, **kwargs):\n        callback = kwargs.pop('callback', self._callback)\n        ip_addr = ip_interface(unicode(kwargs.pop('neighbor')))\n        config = self._update_source_xml(neighbor=ip_addr,\n                                         int_type=kwargs.pop('int_type'),\n                                         int_name=kwargs.pop('int_name'),\n                                         rbridge_id=kwargs.pop('rbridge_id',\n                                                               '1'),\n                                         vrf=kwargs.pop('vrf', 'default'))\n        if kwargs.pop('get', False):\n            return callback(config, handler='get_config')\n        if kwargs.pop('delete', False):\n            config.find('.//*update-source').set('operation', 'delete')\n        return callback(config)",
    "docstring": "Set BGP update source property for a neighbor.\n\n        This method currently only supports loopback interfaces.\n\n        Args:\n            vrf (str): The VRF for this BGP process.\n            rbridge_id (str): The rbridge ID of the device on which BGP will be\n                configured in a VCS fabric.\n            neighbor (str): Address family to configure. (ipv4, ipv6)\n            int_type (str): Interface type (loopback)\n            int_name (str): Interface identifier (1, 5, 7, etc)\n            get (bool): Get config instead of editing config. (True, False)\n            callback (function): A function executed upon completion of the\n                method.  The only parameter passed to `callback` will be the\n                ``ElementTree`` `config`.\n\n        Returns:\n            Return value of `callback`.\n\n        Raises:\n            ``AttributeError``: When `neighbor` is not a valid IPv4 or IPv6\n                address.\n            ``KeyError``: When `int_type` or `int_name` are not specified.\n\n        Examples:\n            >>> import pynos.device\n            >>> switches = ['10.24.39.211', '10.24.39.230']\n            >>> for switch in switches:\n            ...     conn = (switch, '22')\n            ...     auth = ('admin', 'password')\n            ...     with pynos.device.Device(conn=conn, auth=auth) as dev:\n            ...         dev.interface.ip_address(int_type='loopback', name='6',\n            ...         rbridge_id='225', ip_addr='6.6.6.6/32')\n            ...         dev.interface.ip_address(int_type='loopback', name='6',\n            ...         ip_addr='0:0:0:0:0:ffff:606:606/128', rbridge_id='225')\n            ...         dev.bgp.local_asn(local_as='65535', rbridge_id='225')\n            ...         dev.bgp.neighbor(ip_addr='10.10.10.10',\n            ...         remote_as='65535', rbridge_id='225')\n            ...         dev.bgp.neighbor(remote_as='65535', rbridge_id='225',\n            ...         ip_addr='2001:4818:f000:1ab:cafe:beef:1000:1')\n            ...         dev.bgp.update_source(neighbor='10.10.10.10',\n            ...         rbridge_id='225', int_type='loopback', int_name='6')\n            ...         dev.bgp.update_source(get=True, neighbor='10.10.10.10',\n            ...         rbridge_id='225', int_type='loopback', int_name='6')\n            ...         dev.bgp.update_source(rbridge_id='225', int_name='6',\n            ...         neighbor='2001:4818:f000:1ab:cafe:beef:1000:1',\n            ...         int_type='loopback')\n            ...         dev.bgp.update_source(get=True, rbridge_id='225',\n            ...         neighbor='2001:4818:f000:1ab:cafe:beef:1000:1',\n            ...         int_type='loopback', int_name='6')\n            ...         dev.bgp.update_source(neighbor='10.10.10.10',\n            ...         rbridge_id='225', delete=True, int_type='loopback',\n            ...         int_name='6')\n            ...         dev.bgp.update_source(delete=True, int_type='loopback',\n            ...         rbridge_id='225', int_name='6',\n            ...         neighbor='2001:4818:f000:1ab:cafe:beef:1000:1')\n            ...         dev.bgp.neighbor(ip_addr='10.10.10.10', delete=True,\n            ...         rbridge_id='225')\n            ...         dev.bgp.neighbor(delete=True, rbridge_id='225',\n            ...         ip_addr='2001:4818:f000:1ab:cafe:beef:1000:1')\n            ...         dev.interface.ip_address(int_type='loopback', name='6',\n            ...         rbridge_id='225', ip_addr='6.6.6.6/32', delete=True)\n            ...         dev.interface.ip_address(int_type='loopback', name='6',\n            ...         ip_addr='0:0:0:0:0:ffff:606:606/128', rbridge_id='225',\n            ...         delete=True)\n            ...         output = dev.bgp.update_source(rbridge_id='225',\n            ...         int_type='loopback')\n            ...         # doctest: +IGNORE_EXCEPTION_DETAIL\n            Traceback (most recent call last):\n            NotImplementedError\n            KeyError"
  },
  {
    "code": "def set_wsgi_params(self, module=None, callable_name=None, env_strategy=None):\n        module = module or ''\n        if '/' in module:\n            self._set('wsgi-file', module, condition=module)\n        else:\n            self._set('wsgi', module, condition=module)\n        self._set('callable', callable_name)\n        self._set('wsgi-env-behaviour', env_strategy)\n        return self._section",
    "docstring": "Set wsgi related parameters.\n\n        :param str|unicode module:\n            * load .wsgi file as the Python application\n            * load a WSGI module as the application.\n\n            .. note:: The module (sans ``.py``) must be importable, ie. be in ``PYTHONPATH``.\n\n            Examples:\n                * mypackage.my_wsgi_module -- read from `application` attr of mypackage/my_wsgi_module.py\n                * mypackage.my_wsgi_module:my_app -- read from `my_app` attr of mypackage/my_wsgi_module.py\n\n        :param str|unicode callable_name: Set WSGI callable name. Default: application.\n\n        :param str|unicode env_strategy: Strategy for allocating/deallocating\n            the WSGI env, can be:\n\n            * ``cheat`` - preallocates the env dictionary on uWSGI startup and clears it\n                after each request. Default behaviour for uWSGI <= 2.0.x\n\n            * ``holy`` - creates and destroys the environ dictionary at each request.\n                Default behaviour for uWSGI >= 2.1"
  },
  {
    "code": "def _exec_cleanup(self, cursor, fd):\n        LOGGER.debug('Closing cursor and cleaning %s', fd)\n        try:\n            cursor.close()\n        except (psycopg2.Error, psycopg2.Warning) as error:\n            LOGGER.debug('Error closing the cursor: %s', error)\n        self._cleanup_fd(fd)\n        if self._cleanup_callback:\n            self._ioloop.remove_timeout(self._cleanup_callback)\n        self._cleanup_callback = self._ioloop.add_timeout(\n            self._ioloop.time() + self._pool_idle_ttl + 1,\n            self._pool_manager.clean, self.pid)",
    "docstring": "Close the cursor, remove any references to the fd in internal state\n        and remove the fd from the ioloop.\n\n        :param psycopg2.extensions.cursor cursor: The cursor to close\n        :param int fd: The connection file descriptor"
  },
  {
    "code": "def _on_connect(self, sequence, topic, message):\n        try:\n            slug = None\n            parts = topic.split('/')\n            slug = parts[-3]\n            uuid = self._extract_device_uuid(slug)\n        except Exception:\n            self._logger.exception(\"Error parsing slug from connection request (slug=%s, topic=%s)\", slug, topic)\n            return\n        if messages.ConnectCommand.matches(message):\n            key = message['key']\n            client = message['client']\n            self._loop.add_callback(self._connect_to_device, uuid, key, client)\n        else:\n            self._logger.warn(\"Unknown message received on connect topic=%s, message=%s\", topic, message)",
    "docstring": "Process a request to connect to an IOTile device\n\n        A connection message triggers an attempt to connect to a device,\n        any error checking is done by the DeviceManager that is actually\n        managing the devices.\n\n        A disconnection message is checked to make sure its key matches\n        what we except for this device and is either discarded or\n        forwarded on to the DeviceManager.\n        Args:\n            sequence (int): The sequence number of the packet received\n            topic (string): The topic this message was received on\n            message_type (string): The type of the packet received\n            message (dict): The message itself"
  },
  {
    "code": "def create_build_configuration_set_raw(**kwargs):\n    config_set = _create_build_config_set_object(**kwargs)\n    response = utils.checked_api_call(pnc_api.build_group_configs, 'create_new', body=config_set)\n    if response:\n        return response.content",
    "docstring": "Create a new BuildConfigurationSet."
  },
  {
    "code": "def _extract_methods(self):\n        service = self._service\n        all_urls = set()\n        urls_with_options = set()\n        if not service.http:\n            return\n        for rule in service.http.rules:\n            http_method, url = _detect_pattern_option(rule)\n            if not url or not http_method or not rule.selector:\n                _logger.error(u'invalid HTTP binding encountered')\n                continue\n            method_info = self._get_or_create_method_info(rule.selector)\n            if rule.body:\n                method_info.body_field_path = rule.body\n            if not self._register(http_method, url, method_info):\n                continue\n            all_urls.add(url)\n            if http_method == self._OPTIONS:\n                urls_with_options.add(url)\n        self._add_cors_options_selectors(all_urls - urls_with_options)\n        self._update_usage()\n        self._update_system_parameters()",
    "docstring": "Obtains the methods used in the service."
  },
  {
    "code": "def send(self, text, thread_ts=None):\n        self._client.rtm_send_message(self._body['channel'], text, thread_ts=thread_ts)",
    "docstring": "Send a reply using RTM API\n\n            (This function doesn't supports formatted message\n            when using a bot integration)"
  },
  {
    "code": "def valid_header_waiting(self):\n        if len(self.buffer) < 4:\n            self.logger.debug(\"Buffer does not yet contain full header\")\n            result = False\n        else:\n            result = True\n            result = result and self.buffer[0] == velbus.START_BYTE\n            if not result:\n                self.logger.warning(\"Start byte not recognized\")\n            result = result and (self.buffer[1] in velbus.PRIORITY)\n            if not result:\n                self.logger.warning(\"Priority not recognized\")\n            result = result and (self.buffer[3] & 0x0F <= 8)\n            if not result:\n                self.logger.warning(\"Message size not recognized\")\n        self.logger.debug(\"Valid Header Waiting: %s(%s)\", result, str(self.buffer))\n        return result",
    "docstring": "Check if a valid header is waiting in buffer"
  },
  {
    "code": "def transaction(self, compare, success=None, failure=None):\n        compare = [c.build_message() for c in compare]\n        success_ops = self._ops_to_requests(success)\n        failure_ops = self._ops_to_requests(failure)\n        transaction_request = etcdrpc.TxnRequest(compare=compare,\n                                                 success=success_ops,\n                                                 failure=failure_ops)\n        txn_response = self.kvstub.Txn(\n            transaction_request,\n            self.timeout,\n            credentials=self.call_credentials,\n            metadata=self.metadata\n        )\n        responses = []\n        for response in txn_response.responses:\n            response_type = response.WhichOneof('response')\n            if response_type in ['response_put', 'response_delete_range',\n                                 'response_txn']:\n                responses.append(response)\n            elif response_type == 'response_range':\n                range_kvs = []\n                for kv in response.response_range.kvs:\n                    range_kvs.append((kv.value,\n                                      KVMetadata(kv, txn_response.header)))\n                responses.append(range_kvs)\n        return txn_response.succeeded, responses",
    "docstring": "Perform a transaction.\n\n        Example usage:\n\n        .. code-block:: python\n\n            etcd.transaction(\n                compare=[\n                    etcd.transactions.value('/doot/testing') == 'doot',\n                    etcd.transactions.version('/doot/testing') > 0,\n                ],\n                success=[\n                    etcd.transactions.put('/doot/testing', 'success'),\n                ],\n                failure=[\n                    etcd.transactions.put('/doot/testing', 'failure'),\n                ]\n            )\n\n        :param compare: A list of comparisons to make\n        :param success: A list of operations to perform if all the comparisons\n                        are true\n        :param failure: A list of operations to perform if any of the\n                        comparisons are false\n        :return: A tuple of (operation status, responses)"
  },
  {
    "code": "def go_offline(self, comment=None):\n        self.make_request(\n            NodeCommandFailed,\n            method='update',\n            resource='go_offline',\n            params={'comment': comment})",
    "docstring": "Executes a Go-Offline operation on the specified node\n\n        :param str comment: optional comment to audit\n        :raises NodeCommandFailed: offline not available\n        :return: None"
  },
  {
    "code": "def _parse(reactor, directory, pemdir, *args, **kwargs):\n    def colon_join(items):\n        return ':'.join([item.replace(':', '\\\\:') for item in items])\n    sub = colon_join(list(args) + ['='.join(item) for item in kwargs.items()])\n    pem_path = FilePath(pemdir).asTextMode()\n    acme_key = load_or_create_client_key(pem_path)\n    return AutoTLSEndpoint(\n        reactor=reactor,\n        directory=directory,\n        client_creator=partial(Client.from_url, key=acme_key, alg=RS256),\n        cert_store=DirectoryStore(pem_path),\n        cert_mapping=HostDirectoryMap(pem_path),\n        sub_endpoint=serverFromString(reactor, sub))",
    "docstring": "Parse a txacme endpoint description.\n\n    :param reactor: The Twisted reactor.\n    :param directory: ``twisted.python.url.URL`` for the ACME directory to use\n        for issuing certs.\n    :param str pemdir: The path to the certificate directory to use."
  },
  {
    "code": "def send_post(config, urlpath, post_data):\n    server = config.get(\"Server\", \"url\")\n    logger.debug(\"Sending executor payload to \" + server)\n    post_data = urlencode(post_data)\n    post_data = post_data.encode(\"utf-8\", errors=\"ignore\")\n    url = server + urlpath\n    try:\n        urlopen(url, post_data)\n    except Exception as e:\n        logger.error('Error while sending data to server: ' + str(e))",
    "docstring": "Send POST data to an OpenSubmit server url path,\n    according to the configuration."
  },
  {
    "code": "def insort_event_right(self, event, lo=0, hi=None):\n    if lo < 0:\n      raise ValueError('lo must be non-negative')\n    if hi is None:\n      hi = len(self.queue)\n    while lo < hi:\n      mid = (lo + hi) // 2\n      if event[0] < self.queue[mid][0]:\n        hi = mid\n      else:\n        lo = mid + 1\n    self.queue.insert(lo, event)",
    "docstring": "Insert event in queue, and keep it sorted assuming queue is sorted.\n\n    If event is already in queue, insert it to the right of the rightmost\n    event (to keep FIFO order).\n\n    Optional args lo (default 0) and hi (default len(a)) bound the\n    slice of a to be searched.\n\n    Args:\n      event: a (time in sec since unix epoch, callback, args, kwds) tuple."
  },
  {
    "code": "def fullqualname_py2(obj):\n    if type(obj).__name__ == 'builtin_function_or_method':\n        return _fullqualname_builtin_py2(obj)\n    elif type(obj).__name__ == 'function':\n        return obj.__module__ + '.' + obj.__name__\n    elif type(obj).__name__ in ['member_descriptor', 'method_descriptor',\n                                'wrapper_descriptor']:\n        return (obj.__objclass__.__module__ + '.' +\n                obj.__objclass__.__name__ + '.' +\n                obj.__name__)\n    elif type(obj).__name__ == 'instancemethod':\n        return _fullqualname_method_py2(obj)\n    elif type(obj).__name__ == 'method-wrapper':\n        return fullqualname_py2(obj.__self__) + '.' + obj.__name__\n    elif type(obj).__name__ == 'module':\n        return obj.__name__\n    elif inspect.isclass(obj):\n        return obj.__module__ + '.' + obj.__name__\n    return obj.__class__.__module__ + '.' + obj.__class__.__name__",
    "docstring": "Fully qualified name for objects in Python 2."
  },
  {
    "code": "def run(self):\n        model = Model(self.fP, self.doc)\n        self.doc.walkabout(model)\n        return model",
    "docstring": "Parse the script file.\n\n        :rtype: :py:class:`~turberfield.dialogue.model.Model`"
  },
  {
    "code": "def int(self, *args):\n        return self.random.randint(*self._arg_defaults(args, [-sys.maxint, sys.maxint], int))",
    "docstring": "Returns a random int between -sys.maxint and sys.maxint\n            INT\n\n        %{INT} -> '1245123'\n        %{INT:10} -> '10000000'\n        %{INT:10,20} -> '19'"
  },
  {
    "code": "def _check_subnet(self, name):\n        subnets = self._vpc_connection.get_all_subnets(\n            filters={'vpcId': self._vpc_id})\n        matching_subnets = [\n            subnet\n            for subnet\n             in subnets\n             if name in [subnet.tags.get('Name'), subnet.id]\n        ]\n        if len(matching_subnets) == 0:\n            raise SubnetError(\n                \"the specified subnet %s does not exist\" % name)\n        elif len(matching_subnets) == 1:\n            return matching_subnets[0].id\n        else:\n            raise SubnetError(\n                \"the specified subnet name %s matches more than \"\n                \"one subnet\" % name)",
    "docstring": "Checks if the subnet exists.\n\n        :param str name: name of the subnet\n        :return: str - subnet id of the subnet\n        :raises: `SubnetError` if group does not exist"
  },
  {
    "code": "def get_and_subtract(self, delta):\n        return self._invoke_internal(pn_counter_add_codec, delta=-1 * delta, get_before_update=True)",
    "docstring": "Subtracts the given value from the current value and returns the previous value.\n\n        :raises NoDataMemberInClusterError: if the cluster does not contain any data members.\n        :raises UnsupportedOperationError: if the cluster version is less than 3.10.\n        :raises ConsistencyLostError: if the session guarantees have been lost.\n\n        :param delta: (int), the value to subtract.\n        :return: (int), the previous value."
  },
  {
    "code": "def prepare_content_length(self, body):\n        if body is not None:\n            length = super_len(body)\n            if length:\n                self.headers['Content-Length'] = builtin_str(length)\n        elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:\n            self.headers['Content-Length'] = '0'",
    "docstring": "Prepare Content-Length header based on request method and body"
  },
  {
    "code": "def _calculate_new_overlap(stride, traj_len, skip):\n        overlap = stride * ((traj_len - skip - 1) // stride + 1) - traj_len + skip\n        return overlap",
    "docstring": "Given two trajectories T_1 and T_2, this function calculates for the first trajectory an overlap, i.e.,\n        a skip parameter for T_2 such that the trajectory fragments T_1 and T_2 appear as one under the given stride.\n\n        Idea for deriving the formula: It is\n\n        K = ((traj_len - skip - 1) // stride + 1) = #(data points in trajectory of length (traj_len - skip)).\n\n        Therefore, the first point's position that is not contained in T_1 anymore is given by\n\n        pos = skip + s * K.\n\n        Thus the needed skip of T_2 such that the same stride parameter makes T_1 and T_2 \"look as one\" is\n\n        overlap = pos - traj_len.\n\n        :param stride: the (global) stride parameter\n        :param traj_len: length of T_1\n        :param skip: skip of T_1\n        :return: skip of T_2"
  },
  {
    "code": "def _get_elevation(self, location):\n        url = self._elevation_query_base % (location.latitude, location.longitude)\n        if self.api_key != \"\":\n            url += \"&key=%s\" % self.api_key\n        data = self._read_from_url(url)\n        response = json.loads(data)\n        if response[\"status\"] == \"OK\":\n            location.elevation = int(float(response[\"results\"][0][\"elevation\"]))\n        else:\n            location.elevation = 0",
    "docstring": "Query the elevation information with the latitude and longitude of\n        the specified `location`."
  },
  {
    "code": "def readerForFd(fd, URL, encoding, options):\n    ret = libxml2mod.xmlReaderForFd(fd, URL, encoding, options)\n    if ret is None:raise treeError('xmlReaderForFd() failed')\n    return xmlTextReader(_obj=ret)",
    "docstring": "Create an xmltextReader for an XML from a file descriptor.\n      The parsing flags @options are a combination of\n      xmlParserOption. NOTE that the file descriptor will not be\n       closed when the reader is closed or reset."
  },
  {
    "code": "def parse_pagination(headers):\n    links = {\n        link.rel: parse_qs(link.href).get(\"page\", None)\n        for link in link_header.parse(headers.get(\"Link\", \"\")).links\n    }\n    return _Navigation(\n        links.get(\"previous\", [None])[0],\n        links.get(\"next\", [None])[0],\n        links.get(\"last\", [None])[0],\n        links.get(\"current\", [None])[0],\n        links.get(\"first\", [None])[0]\n    )",
    "docstring": "Parses headers to create a pagination objects\n\n    :param headers: HTTP Headers\n    :type headers: dict\n    :return: Navigation object for pagination\n    :rtype: _Navigation"
  },
  {
    "code": "def collect_consequences(self):\n        consequences = {self.key()}\n        for relation in self.referenced_by.values():\n            consequences.update(relation.collect_consequences())\n        return consequences",
    "docstring": "Recursively collect a set of _ReferenceKeys that would\n        consequentially get dropped if this were dropped via\n        \"drop ... cascade\".\n\n        :return Set[_ReferenceKey]: All the relations that would be dropped"
  },
  {
    "code": "def _cmd_down(self):\n        revision = self._get_revision()\n        if not self._rev:\n            self._log(0, \"downgrading current revision\")\n        else:\n            self._log(0, \"downgrading to revision %s\" % revision)\n        for rev in reversed(self._revisions[int(revision) - 1:]):\n            sql_files = glob.glob(os.path.join(self._migration_path, rev, \"*.down.sql\"))\n            sql_files.sort(reverse=True)\n            self._exec(sql_files, rev)\n        self._log(0, \"done: downgraded revision to %s\" % rev)",
    "docstring": "Downgrade to a revision"
  },
  {
    "code": "def instant_articles(self, **kwargs):\n        eqs = self.search(**kwargs).sort('-last_modified', '-published')\n        return eqs.filter(InstantArticle())",
    "docstring": "QuerySet including all published content approved for instant articles.\n\n        Instant articles are configured via FeatureType. FeatureType.instant_article = True."
  },
  {
    "code": "def parse_substring(allele, pred, max_len=None):\n    result = \"\"\n    pos = 0\n    if max_len is None:\n        max_len = len(allele)\n    else:\n        max_len = min(max_len, len(allele))\n    while pos < max_len and pred(allele[pos]):\n        result += allele[pos]\n        pos += 1\n    return result, allele[pos:]",
    "docstring": "Extract substring of letters for which predicate is True"
  },
  {
    "code": "def set_cache_expiry(response):\n    if response.cache_control.max_age is None and 'CACHE_DEFAULT_TIMEOUT' in config.cache:\n        response.cache_control.max_age = config.cache['CACHE_DEFAULT_TIMEOUT']\n    return response",
    "docstring": "Set the cache control headers"
  },
  {
    "code": "def contains_any(self, other):\n        return self.value == other.value or self.value & other.value",
    "docstring": "Check if any flags are set.\n\n        (OsuMod.Hidden | OsuMod.HardRock) in flags # Check if either hidden or hardrock are enabled.\n        OsuMod.keyMod in flags # Check if any keymod is enabled."
  },
  {
    "code": "def md5_for_file(f, block_size=2 ** 20):\n    md5 = hashlib.md5()\n    try:\n        f.seek(0)\n        return md5_for_stream(f, block_size=block_size)\n    except AttributeError:\n        file_name = f\n        with open(file_name, 'rb') as f:\n            return md5_for_file(f, block_size)",
    "docstring": "Generate an MD5 has for a possibly large file by breaking it into\n    chunks."
  },
  {
    "code": "def runExperiment( self, e ):\n        space = self.parameterSpace()\n        if len(space) > 0:\n            nb = self.notebook()\n            ps = self._mixup(space)\n            try:\n                self.open()\n                view = self._client.load_balanced_view()\n                jobs = []\n                for p in ps:\n                    jobs.extend((view.apply_async((lambda p: e.set(p).run()), p)).msg_ids)\n                    time.sleep(0.01)\n                psjs = zip(ps, jobs)\n                for (p, j) in psjs:\n                    nb.addPendingResult(p, j)\n            finally:\n                nb.commit()\n                self.close()",
    "docstring": "Run the experiment across the parameter space in parallel using\n        all the engines in the cluster. This method returns immediately.\n\n        The experiments are run asynchronously, with the points in the parameter\n        space being explored randomly so that intermediate retrievals of results\n        are more representative of the overall result. Put another way, for a lot\n        of experiments the results available will converge towards a final\n        answer, so we can plot them and see the answer emerge.\n\n        :param e: the experiment"
  },
  {
    "code": "def get_project_build(account_project):\n    url = make_url(\"/projects/{account_project}\", account_project=account_project)\n    response = requests.get(url, headers=make_auth_headers())\n    return response.json()",
    "docstring": "Get the details of the latest Appveyor build."
  },
  {
    "code": "def do_local(self, host=\"localhost\", port=8000):\n        port = int(port)\n        if host == \"off\":\n            self._local_endpoint = None\n        else:\n            self._local_endpoint = (host, port)\n        self.onecmd(\"use %s\" % self.engine.region)",
    "docstring": "Connect to a local DynamoDB instance. Use 'local off' to disable.\n\n        > local\n        > local host=localhost port=8001\n        > local off"
  },
  {
    "code": "def from_vhost(cls, vhost):\n        result = Vhost().list()\n        paas_hosts = {}\n        for host in result:\n            paas_hosts[host['name']] = host['paas_id']\n        return paas_hosts.get(vhost)",
    "docstring": "Retrieve paas instance id associated to a vhost."
  },
  {
    "code": "def _get_all_timers(self, dataframe):\n        s = dataframe['custom_timers'].apply(json.loads)\n        s.index = dataframe['epoch']\n        for index, value in s.iteritems():\n            if not value:\n                continue\n            for key, value in six.iteritems(value):\n                self._timers_values[key].append((index, value))\n                self.total_timers += 1\n        del dataframe['custom_timers']\n        del s",
    "docstring": "Get all timers and set them in the _timers_values property\n\n        :param pandas.DataFrame dataframe: the main dataframe with row results"
  },
  {
    "code": "def get_config_object():\n    global _DEFAULT_CONFIG_WRAPPER\n    if _DEFAULT_CONFIG_WRAPPER is not None:\n        return _DEFAULT_CONFIG_WRAPPER\n    with _DEFAULT_CONFIG_WRAPPER_LOCK:\n        if _DEFAULT_CONFIG_WRAPPER is not None:\n            return _DEFAULT_CONFIG_WRAPPER\n        _DEFAULT_CONFIG_WRAPPER = ConfigWrapper()\n        return _DEFAULT_CONFIG_WRAPPER",
    "docstring": "Thread-safe accessor for the immutable default ConfigWrapper object"
  },
  {
    "code": "def create_cas_validate_url(cas_url, cas_route, service, ticket,\n                            renew=None):\n    return create_url(\n        cas_url,\n        cas_route,\n        ('service', service),\n        ('ticket', ticket),\n        ('renew', renew),\n    )",
    "docstring": "Create a CAS validate URL.\n\n    Keyword arguments:\n    cas_url -- The url to the CAS (ex. http://sso.pdx.edu)\n    cas_route -- The route where the CAS lives on server (ex. /cas/serviceValidate)\n    service -- (ex.  http://localhost:5000/login)\n    ticket -- (ex. 'ST-58274-x839euFek492ou832Eena7ee-cas')\n    renew -- \"true\" or \"false\"\n\n    Example usage:\n    >>> create_cas_validate_url(\n    ...     'http://sso.pdx.edu',\n    ...     '/cas/serviceValidate',\n    ...     'http://localhost:5000/login',\n    ...     'ST-58274-x839euFek492ou832Eena7ee-cas'\n    ... )\n    'http://sso.pdx.edu/cas/serviceValidate?service=http%3A%2F%2Flocalhost%3A5000%2Flogin&ticket=ST-58274-x839euFek492ou832Eena7ee-cas'"
  },
  {
    "code": "def _request_token(self, force=False):\n        if self.login_data is None:\n            raise RuntimeError(\"Don't have a token to refresh\")\n        if not force:\n            if not self._requires_refresh_token():\n                return True\n        headers = {\n            \"Accept\": \"application/json\",\n            'Authorization':\n                'Bearer ' + self.login_data['token']['accessToken']\n        }\n        url = self.api_base_url + \"account/RefreshToken\"\n        response = requests.get(url, headers=headers, timeout=10)\n        if response.status_code != 200:\n            return False\n        refresh_data = response.json()\n        if 'token' not in refresh_data:\n            return False\n        self.login_data['token']['accessToken'] = refresh_data['accessToken']\n        self.login_data['token']['issuedOn'] = refresh_data['issuedOn']\n        self.login_data['token']['expiresOn'] = refresh_data['expiresOn']\n        return True",
    "docstring": "Request a new auth token"
  },
  {
    "code": "def reraise_if_any(failures, cause_cls_finder=None):\n        if not isinstance(failures, (list, tuple)):\n            failures = list(failures)\n        if len(failures) == 1:\n            failures[0].reraise(cause_cls_finder=cause_cls_finder)\n        elif len(failures) > 1:\n            raise WrappedFailure(failures)",
    "docstring": "Re-raise exceptions if argument is not empty.\n\n        If argument is empty list/tuple/iterator, this method returns\n        None. If argument is converted into a list with a\n        single ``Failure`` object in it, that failure is reraised. Else, a\n        :class:`~.WrappedFailure` exception is raised with the failure\n        list as causes."
  },
  {
    "code": "def _clear_policy(self, lambda_name):\n        try:\n            policy_response = self.lambda_client.get_policy(\n                FunctionName=lambda_name\n            )\n            if policy_response['ResponseMetadata']['HTTPStatusCode'] == 200:\n                statement = json.loads(policy_response['Policy'])['Statement']\n                for s in statement:\n                    delete_response = self.lambda_client.remove_permission(\n                        FunctionName=lambda_name,\n                        StatementId=s['Sid']\n                    )\n                    if delete_response['ResponseMetadata']['HTTPStatusCode'] != 204:\n                        logger.error('Failed to delete an obsolete policy statement: {}'.format(policy_response))\n            else:\n                logger.debug('Failed to load Lambda function policy: {}'.format(policy_response))\n        except ClientError as e:\n            if e.args[0].find('ResourceNotFoundException') > -1:\n                logger.debug('No policy found, must be first run.')\n            else:\n                logger.error('Unexpected client error {}'.format(e.args[0]))",
    "docstring": "Remove obsolete policy statements to prevent policy from bloating over the limit after repeated updates."
  },
  {
    "code": "def session_rollback(self, session):\n        if not hasattr(session, 'meepo_unique_id'):\n            self.logger.debug(\"skipped - session_rollback\")\n            return\n        self.logger.debug(\"%s - after_rollback\" % session.meepo_unique_id)\n        signal(\"session_rollback\").send(session)\n        self._session_del(session)",
    "docstring": "Send session_rollback signal in sqlalchemy ``after_rollback``.\n\n        This marks the failure of session so the session may enter commit\n        phase."
  },
  {
    "code": "def norm(x, mu, sigma=1.0):\n    return stats.norm(loc=mu, scale=sigma).pdf(x)",
    "docstring": "Scipy norm function"
  },
  {
    "code": "def disconnect_sync(self, conn_id):\n        done = threading.Event()\n        result = {}\n        def disconnect_done(conn_id, adapter_id, status, reason):\n            result['success'] = status\n            result['failure_reason'] = reason\n            done.set()\n        self.disconnect_async(conn_id, disconnect_done)\n        done.wait()\n        return result",
    "docstring": "Synchronously disconnect from a connected device\n\n        Args:\n            conn_id (int): A unique identifier that will refer to this connection\n\n        Returns:\n            dict: A dictionary with two elements\n                'success': a bool with the result of the connection attempt\n                'failure_reason': a string with the reason for the failure if we failed"
  },
  {
    "code": "def get_byte_array(integer):\n    return int.to_bytes(\n        integer,\n        (integer.bit_length() + 8 - 1) // 8,\n        byteorder='big',\n        signed=False\n    )",
    "docstring": "Return the variable length bytes corresponding to the given int"
  },
  {
    "code": "def get_book_info(cursor, real_dict_cursor, book_id,\n                  book_version, page_id, page_version):\n    book_ident_hash = join_ident_hash(book_id, book_version)\n    page_ident_hash = join_ident_hash(page_id, page_version)\n    tree = get_tree(book_ident_hash, cursor)\n    if not tree or page_ident_hash not in flatten_tree_to_ident_hashes(tree):\n        raise httpexceptions.HTTPNotFound()\n    sql_statement =\n    real_dict_cursor.execute(sql_statement, vars=(book_ident_hash,))\n    return real_dict_cursor.fetchone()",
    "docstring": "Return information about a given book.\n\n    Return the book's title, id, shortId, authors and revised date.\n    Raise HTTPNotFound if the page is not in the book."
  },
  {
    "code": "def use_theme(theme):\n    global current\n    current = theme\n    import scene\n    if scene.current is not None:\n        scene.current.stylize()",
    "docstring": "Make the given theme current.\n\n    There are two included themes: light_theme, dark_theme."
  },
  {
    "code": "def search_certificate(self, hash):\n        c = CensysCertificates(api_id=self.__uid, api_secret=self.__api_key)\n        return c.view(hash)",
    "docstring": "Searches for a specific certificate using its hash\n\n        :param hash: certificate hash\n        :type hash: str\n        :return: dict"
  },
  {
    "code": "def _extra_compile_time_classpath(self):\n    def extra_compile_classpath_iter():\n      for conf in self._confs:\n        for jar in self.extra_compile_time_classpath_elements():\n          yield (conf, jar)\n    return list(extra_compile_classpath_iter())",
    "docstring": "Compute any extra compile-time-only classpath elements."
  },
  {
    "code": "async def _watchdog(self, timeout):\n        await asyncio.sleep(timeout, loop=self.loop)\n        _LOGGER.debug(\"Watchdog triggered!\")\n        await self.cancel_watchdog()\n        await self._watchdog_cb()",
    "docstring": "Trigger and cancel the watchdog after timeout. Call callback."
  },
  {
    "code": "def is_file(dirname):\n    if not os.path.isfile(dirname):\n        msg = \"{0} is not an existing file\".format(dirname)\n        raise argparse.ArgumentTypeError(msg)\n    else:\n        return dirname",
    "docstring": "Checks if a path is an actual file that exists"
  },
  {
    "code": "def pid(name):\n    try:\n        return int(info(name).get('PID'))\n    except (TypeError, ValueError) as exc:\n        raise CommandExecutionError(\n            'Unable to get PID for container \\'{0}\\': {1}'.format(name, exc)\n        )",
    "docstring": "Returns the PID of a container\n\n    name\n        Container name\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion nspawn.pid arch1"
  },
  {
    "code": "def get_scope_path(self, scope_separator=\"::\"):\n        if self.parent_scope is None:\n            return \"\"\n        elif isinstance(self.parent_scope, Root):\n            return \"\"\n        else:\n            parent_path = self.parent_scope.get_scope_path(scope_separator)\n            if parent_path:\n                return(\n                    parent_path\n                    + scope_separator\n                    + self.parent_scope.type_name\n                )\n            else:\n                return self.parent_scope.type_name",
    "docstring": "Generate a string that represents this component's declaration namespace\n        scope.\n\n        Parameters\n        ----------\n        scope_separator: str\n            Override the separator between namespace scopes"
  },
  {
    "code": "def modify_column_if_table_exists(self,\n                                      tablename: str,\n                                      fieldname: str,\n                                      newdef: str) -> Optional[int]:\n        if not self.table_exists(tablename):\n            return None\n        sql = \"ALTER TABLE {t} MODIFY COLUMN {field} {newdef}\".format(\n            t=tablename,\n            field=fieldname,\n            newdef=newdef\n        )\n        log.info(sql)\n        return self.db_exec_literal(sql)",
    "docstring": "Alters a column's definition without renaming it."
  },
  {
    "code": "def clean_resource_json(resource_json):\n    for a in ('parent_docname', 'parent', 'template', 'repr', 'series'):\n        if a in resource_json:\n            del resource_json[a]\n    props = resource_json['props']\n    for prop in (\n            'acquireds', 'style', 'in_nav', 'nav_title', 'weight',\n            'auto_excerpt'):\n        if prop in props:\n            del props[prop]\n    return resource_json",
    "docstring": "The catalog wants to be smaller, let's drop some stuff"
  },
  {
    "code": "def _validate_timeout(seconds: float):\n    val = int(seconds * 1000)\n    assert 60000 <= val <= 4294967294, \"Bad value: {}\".format(val)\n    return val",
    "docstring": "Creates an int from 60000 to 4294967294 that represents a\n    valid millisecond wireless LAN timeout"
  },
  {
    "code": "def union(self, other, renorm=True):\n        for d in range(1, min(self.maxdepth, other.maxdepth)+1):\n            self.add_pixels(other.pixeldict[d], d)\n        if self.maxdepth < other.maxdepth:\n            for d in range(self.maxdepth+1, other.maxdepth+1):\n                for p in other.pixeldict[d]:\n                    pp = p/4**(d-self.maxdepth)\n                    self.pixeldict[self.maxdepth].add(pp)\n        if renorm:\n            self._renorm()\n        return",
    "docstring": "Add another Region by performing union on their pixlists.\n\n        Parameters\n        ----------\n        other : :class:`AegeanTools.regions.Region`\n            The region to be combined.\n\n        renorm : bool\n            Perform renormalisation after the operation?\n            Default = True."
  },
  {
    "code": "def runGetContinuousSet(self, id_):\n        compoundId = datamodel.ContinuousSetCompoundId.parse(id_)\n        dataset = self.getDataRepository().getDataset(compoundId.dataset_id)\n        continuousSet = dataset.getContinuousSet(id_)\n        return self.runGetRequest(continuousSet)",
    "docstring": "Runs a getContinuousSet request for the specified ID."
  },
  {
    "code": "def _produce_return(self, cursor):\n        results = cursor.fetchall()\n        if self._row_formatter is not None:\n            return (self._row_formatter(r, cursor) for r in results)\n        return results",
    "docstring": "Get the rows from the cursor and apply the row formatter.\n\n        :return: sequence of rows, or a generator if a row formatter has to be\n            applied"
  },
  {
    "code": "def upload_file_boto(fname, remote_fname, mditems=None):\n    r_fname = objectstore.parse_remote(remote_fname)\n    conn = objectstore.connect(remote_fname)\n    bucket = conn.lookup(r_fname.bucket)\n    if not bucket:\n        bucket = conn.create_bucket(r_fname.bucket, location=objectstore.get_region(remote_fname))\n    key = bucket.get_key(r_fname.key, validate=False)\n    if mditems is None:\n        mditems = {}\n    if \"x-amz-server-side-encryption\" not in mditems:\n        mditems[\"x-amz-server-side-encryption\"] = \"AES256\"\n    for name, val in mditems.items():\n        key.set_metadata(name, val)\n    key.set_contents_from_filename(fname, encrypt_key=True)",
    "docstring": "Upload a file using boto instead of external tools."
  },
  {
    "code": "def create():\n    if not all(map(os.path.isdir, ARGS.directory)):\n        exit('Error: One or more of the specified directories does not exist.')\n    with sqlite3.connect(ARGS.database) as connection:\n        connection.text_factory = str\n        cursor = connection.cursor()\n        cursor.execute('DROP TABLE IF EXISTS Movies')\n        cursor.execute(\n)\n        for dir in ARGS.directory:\n            cursor.executemany('INSERT INTO Movies VALUES(?, ?, ?, ?)',\n                               local_data(dir))",
    "docstring": "Create a new database with information about the films in the specified\n       directory or directories."
  },
  {
    "code": "def _row_resized(self, row, old_height, new_height):\r\n        self.dataTable.setRowHeight(row, new_height)\r\n        self._update_layout()",
    "docstring": "Update the row height."
  },
  {
    "code": "def clean_structure(self, out_suffix='_clean', outdir=None, force_rerun=False,\n                        remove_atom_alt=True, keep_atom_alt_id='A',remove_atom_hydrogen=True,  add_atom_occ=True,\n                        remove_res_hetero=True, keep_chemicals=None, keep_res_only=None,\n                        add_chain_id_if_empty='X', keep_chains=None):\n        if not self.structure_file:\n            log.error('{}: no structure file, unable to clean'.format(self.id))\n            return None\n        clean_pdb_file = ssbio.protein.structure.utils.cleanpdb.clean_pdb(self.structure_path, out_suffix=out_suffix,\n                                                                          outdir=outdir, force_rerun=force_rerun,\n                                                                          remove_atom_alt=remove_atom_alt,\n                                                                          remove_atom_hydrogen=remove_atom_hydrogen,\n                                                                          keep_atom_alt_id=keep_atom_alt_id,\n                                                                          add_atom_occ=add_atom_occ,\n                                                                          remove_res_hetero=remove_res_hetero,\n                                                                          keep_chemicals=keep_chemicals,\n                                                                          keep_res_only=keep_res_only,\n                                                                          add_chain_id_if_empty=add_chain_id_if_empty,\n                                                                          keep_chains=keep_chains)\n        return clean_pdb_file",
    "docstring": "Clean the structure file associated with this structure, and save it as a new file. Returns the file path.\n\n        Args:\n            out_suffix (str): Suffix to append to original filename\n            outdir (str): Path to output directory\n            force_rerun (bool): If structure should be re-cleaned if a clean file exists already\n            remove_atom_alt (bool): Remove alternate positions\n            keep_atom_alt_id (str): If removing alternate positions, which alternate ID to keep\n            remove_atom_hydrogen (bool): Remove hydrogen atoms\n            add_atom_occ (bool): Add atom occupancy fields if not present\n            remove_res_hetero (bool): Remove all HETATMs\n            keep_chemicals (str, list): If removing HETATMs, keep specified chemical names\n            keep_res_only (str, list): Keep ONLY specified resnames, deletes everything else!\n            add_chain_id_if_empty (str): Add a chain ID if not present\n            keep_chains (str, list): Keep only these chains\n\n        Returns:\n            str: Path to cleaned PDB file"
  },
  {
    "code": "def fire_ret_load(self, load):\n        if load.get('retcode') and load.get('fun'):\n            if isinstance(load['fun'], list):\n                if isinstance(load['retcode'], list):\n                    multifunc_ordered = True\n                else:\n                    multifunc_ordered = False\n                for fun_index in range(0, len(load['fun'])):\n                    fun = load['fun'][fun_index]\n                    if multifunc_ordered:\n                        if (len(load['retcode']) > fun_index and\n                                load['retcode'][fun_index] and\n                                fun in SUB_EVENT):\n                            self._fire_ret_load_specific_fun(load, fun_index)\n                    else:\n                        if load['retcode'].get(fun, 0) and fun in SUB_EVENT:\n                            self._fire_ret_load_specific_fun(load, fun_index)\n            else:\n                if load['fun'] in SUB_EVENT:\n                    self._fire_ret_load_specific_fun(load)",
    "docstring": "Fire events based on information in the return load"
  },
  {
    "code": "def output_file_name(self):\n    safe_path = re.sub(r\":|/\", \"_\", self.source_urn.Path().lstrip(\"/\"))\n    return \"results_%s%s\" % (safe_path, self.output_file_extension)",
    "docstring": "Name of the file where plugin's output should be written to."
  },
  {
    "code": "def addRow(self, *row):\n        row     = [ str(item) for item in row ]\n        len_row = [ len(item) for item in row ]\n        width   = self.__width\n        len_old = len(width)\n        len_new = len(row)\n        known   = min(len_old, len_new)\n        missing = len_new - len_old\n        if missing > 0:\n            width.extend( len_row[ -missing : ] )\n        elif missing < 0:\n            len_row.extend( [0] * (-missing) )\n        self.__width = [ max( width[i], len_row[i] ) for i in compat.xrange(len(len_row)) ]\n        self.__cols.append(row)",
    "docstring": "Add a row to the table. All items are converted to strings.\n\n        @type    row: tuple\n        @keyword row: Each argument is a cell in the table."
  },
  {
    "code": "def patch():\n    from twisted.application.service import Service\n    old_startService = Service.startService\n    old_stopService = Service.stopService\n    def startService(self):\n        assert not self.running, \"%r already running\" % (self,)\n        return old_startService(self)\n    def stopService(self):\n        assert self.running, \"%r already stopped\" % (self,)\n        return old_stopService(self)\n    Service.startService = startService\n    Service.stopService = stopService",
    "docstring": "Patch startService and stopService so that they check the previous state\n    first.\n\n    (used for debugging only)"
  },
  {
    "code": "def transform_sources(self, sources, with_string=False):\n        modules = {}\n        updater = partial(\n            self.replace_source, modules=modules, prefix='string_')\n        for filename in sources:\n            updated = update_func_body(sources[filename], updater)\n            sources[filename] = EXTERN_AND_SEG + updated\n        logging.debug('modules: %s', modules)\n        return sources, self.build_funcs(modules)",
    "docstring": "Get the defintions of needed strings and functions\n        after replacement."
  },
  {
    "code": "def get_url(self, *paths, **params):\n        path_stack = self._attribute_stack[:]\n        if paths:\n            path_stack.extend(paths)\n        u = self._stack_collapser(path_stack)\n        url = self._url_template % {\n            \"domain\": self._api_url,\n            \"generated_url\" : u,\n        }\n        if self._params or params:\n            internal_params = self._params.copy()\n            internal_params.update(params)\n            url += self._generate_params(internal_params)\n        return url",
    "docstring": "Returns the URL for this request.\n\n        :param paths: Additional URL path parts to add to the request\n        :param params: Additional query parameters to add to the request"
  },
  {
    "code": "def update_contributions(sender, instance, action, model, pk_set, **kwargs):\n    if action != 'pre_add':\n        return\n    else:\n        for author in model.objects.filter(pk__in=pk_set):\n            update_content_contributions(instance, author)",
    "docstring": "Creates a contribution for each author added to an article."
  },
  {
    "code": "def _registerHandler(self, handler):\n        self._logger.addHandler(handler)\n        self._handlers.append(handler)",
    "docstring": "Registers a handler.\n\n        :param handler:  A handler object."
  },
  {
    "code": "def get_line_break_property(value, is_bytes=False):\n    obj = unidata.ascii_line_break if is_bytes else unidata.unicode_line_break\n    if value.startswith('^'):\n        negated = value[1:]\n        value = '^' + unidata.unicode_alias['linebreak'].get(negated, negated)\n    else:\n        value = unidata.unicode_alias['linebreak'].get(value, value)\n    return obj[value]",
    "docstring": "Get `LINE BREAK` property."
  },
  {
    "code": "def dump_wcxf(self, C_out, scale_out, fmt='yaml', stream=None, **kwargs):\n        wc = self.get_wcxf(C_out, scale_out)\n        return wc.dump(fmt=fmt, stream=stream, **kwargs)",
    "docstring": "Return a string representation of the Wilson coefficients `C_out`\n        in WCxf format. If `stream` is specified, export it to a file.\n        `fmt` defaults to `yaml`, but can also be `json`.\n\n        Note that the Wilson coefficients are rotated into the Warsaw basis\n        as defined in WCxf, i.e. to the basis where the down-type and charged\n        lepton mass matrices are diagonal."
  },
  {
    "code": "def get_random(self):\n        import random\n        Statement = self.get_model('statement')\n        session = self.Session()\n        count = self.count()\n        if count < 1:\n            raise self.EmptyDatabaseException()\n        random_index = random.randrange(0, count)\n        random_statement = session.query(Statement)[random_index]\n        statement = self.model_to_object(random_statement)\n        session.close()\n        return statement",
    "docstring": "Returns a random statement from the database."
  },
  {
    "code": "def get_partial_contenthandler(element):\n    from ligo.lw.ligolw import PartialLIGOLWContentHandler\n    from ligo.lw.table import Table\n    if issubclass(element, Table):\n        def _element_filter(name, attrs):\n            return element.CheckProperties(name, attrs)\n    else:\n        def _element_filter(name, _):\n            return name == element.tagName\n    return build_content_handler(PartialLIGOLWContentHandler, _element_filter)",
    "docstring": "Build a `PartialLIGOLWContentHandler` to read only this element\n\n    Parameters\n    ----------\n    element : `type`, subclass of :class:`~ligo.lw.ligolw.Element`\n        the element class to be read,\n\n    Returns\n    -------\n    contenthandler : `type`\n        a subclass of :class:`~ligo.lw.ligolw.PartialLIGOLWContentHandler`\n        to read only the given `element`"
  },
  {
    "code": "def components(accountable, project_key):\n    components = accountable.project_components(project_key)\n    headers = sorted(['id', 'name', 'self'])\n    rows = [[v for k, v in sorted(component.items()) if k in headers]\n            for component in components]\n    rows.insert(0, headers)\n    print_table(SingleTable(rows))",
    "docstring": "Returns a list of all a project's components."
  },
  {
    "code": "def getfile(data_name, path):\n    data_source = get_data_object(data_name, use_data_config=False)\n    if not data_source:\n        if 'output' in data_name:\n            floyd_logger.info(\"Note: You cannot clone the output of a running job. You need to wait for it to finish.\")\n        sys.exit()\n    url = \"{}/api/v1/resources/{}/{}?content=true\".format(floyd.floyd_host, data_source.resource_id, path)\n    fname = os.path.basename(path)\n    DataClient().download(url, filename=fname)\n    floyd_logger.info(\"Download finished\")",
    "docstring": "Download a specific file from a dataset."
  },
  {
    "code": "def find_types(self, site=None, match=r'^(?!lastfile|spectro|\\.).*'):\n        self._find_paths()\n        types = [tag for (site_, tag) in self.paths if site in (None, site_)]\n        if match is not None:\n            match = re.compile(match)\n            return list(filter(match.search, types))\n        return types",
    "docstring": "Return the list of known data types.\n\n        This is just the basename of each FFL file found in the\n        FFL directory (minus the ``.ffl`` extension)"
  },
  {
    "code": "def reset(self):\n\t\tself.gametree = self.game\n\t\tself.nodenum = 0\n\t\tself.index = 0\n\t\tself.stack = []\n\t\tself.node = self.gametree[self.index]\n\t\tself._setChildren()\n\t\tself._setFlags()",
    "docstring": "Set 'Cursor' to point to the start of the root 'GameTree', 'self.game'."
  },
  {
    "code": "def namespace(self, namespace, to=None):\n        fields = get_apphook_field_names(self.model)\n        if not fields:\n            raise ValueError(\n                ugettext(\n                    'Can\\'t find any relation to an ApphookConfig model in {0}'\n                ).format(self.model.__name__)\n            )\n        if to and to not in fields:\n            raise ValueError(\n                ugettext(\n                    'Can\\'t find relation to ApphookConfig model named '\n                    '\"{0}\" in \"{1}\"'\n                ).format(to, self.model.__name__)\n            )\n        if len(fields) > 1 and to not in fields:\n            raise ValueError(\n                ugettext(\n                    '\"{0}\" has {1} relations to an ApphookConfig model.'\n                    ' Please, specify which one to use in argument \"to\".'\n                    ' Choices are: {2}'\n                ).format(\n                    self.model.__name__, len(fields), ', '.join(fields)\n                )\n            )\n        else:\n            if not to:\n                to = fields[0]\n        lookup = '{0}__namespace'.format(to)\n        kwargs = {lookup: namespace}\n        return self.filter(**kwargs)",
    "docstring": "Filter by namespace. Try to guess which field to use in lookup.\n        Accept 'to' argument if you need to specify."
  },
  {
    "code": "def askForFolder(parent, msg = None):\n    msg = msg or 'Select folder'\n    caller = _callerName().split(\".\")\n    name = \"/\".join([LAST_PATH, caller[-1]])\n    namespace = caller[0]\n    path = pluginSetting(name, namespace)\n    folder =  QtWidgets.QFileDialog.getExistingDirectory(parent, msg, path)\n    if folder:\n        setPluginSetting(name, folder, namespace)\n    return folder",
    "docstring": "Asks for a folder, opening the corresponding dialog with the last path that was selected\n    when this same function was invoked from the calling method\n\n    :param parent: The parent window\n    :param msg: The message to use for the dialog title"
  },
  {
    "code": "def unmarshall_value(self, value):\n        value = str(value)\n        if self.escapeValues:\n            value = value.decode('hex')\n        if self.compressValues:\n            value = zlib.decompress(value)\n        value = pickle.loads(value)\n        return value",
    "docstring": "Unmarshalls a Crash object read from the database.\n\n        @type  value: str\n        @param value: Object to convert.\n\n        @rtype:  L{Crash}\n        @return: Converted object."
  },
  {
    "code": "def probe(self, axis: str, distance: float) -> Dict[str, float]:\n        return self._smoothie_driver.probe_axis(axis, distance)",
    "docstring": "Run a probe and return the new position dict"
  },
  {
    "code": "def ensure_size(\n        self,\n        size = None\n        ):\n        if size is None:\n            size = self.size_constraint\n        while sys.getsizeof(self) > size:\n            element_frequencies = collections.Counter(self)\n            infrequent_element = element_frequencies.most_common()[-1:][0][0]\n            self.remove(infrequent_element)",
    "docstring": "This function removes the least frequent elements until the size\n        constraint is met."
  },
  {
    "code": "def files(self):\n    all_files = set()\n    for label in self.filesets:\n      all_files.update(self.filesets[label])\n    return all_files",
    "docstring": "Get all files in the chroot."
  },
  {
    "code": "def encode_datetime(o):\n    r = o.isoformat()\n    if o.microsecond:\n        r = r[:23] + r[26:]\n    if r.endswith('+00:00'):\n        r = r[:-6] + 'Z'\n    return r",
    "docstring": "Encodes a Python datetime.datetime object as an ECMA-262 compliant\n    datetime string."
  },
  {
    "code": "def image(self):\n        slide_part, rId = self.part, self._element.blip_rId\n        if rId is None:\n            raise ValueError('no embedded image')\n        return slide_part.get_image(rId)",
    "docstring": "An |Image| object providing access to the properties and bytes of the\n        image in this picture shape."
  },
  {
    "code": "def estimate_bg(self, fit_offset=\"mean\", fit_profile=\"tilt\",\n                    border_px=0, from_mask=None, ret_mask=False):\n        self.set_bg(bg=None, key=\"fit\")\n        bgimage, mask = bg_estimate.estimate(data=self.image,\n                                             fit_offset=fit_offset,\n                                             fit_profile=fit_profile,\n                                             border_px=border_px,\n                                             from_mask=from_mask,\n                                             ret_mask=True)\n        attrs = {\"fit_offset\": fit_offset,\n                 \"fit_profile\": fit_profile,\n                 \"border_px\": border_px}\n        self.set_bg(bg=bgimage, key=\"fit\", attrs=attrs)\n        self[\"estimate_bg_from_mask\"] = from_mask\n        if ret_mask:\n            return mask",
    "docstring": "Estimate image background\n\n        Parameters\n        ----------\n        fit_profile: str\n            The type of background profile to fit:\n\n            - \"offset\": offset only\n            - \"poly2o\": 2D 2nd order polynomial with mixed terms\n            - \"tilt\": 2D linear tilt with offset (default)\n        fit_offset: str\n            The method for computing the profile offset\n\n            - \"fit\": offset as fitting parameter\n            - \"gauss\": center of a gaussian fit\n            - \"mean\": simple average\n            - \"mode\": mode (see `qpimage.bg_estimate.mode`)\n        border_px: float\n            Assume that a frame of `border_px` pixels around\n            the image is background.\n        from_mask: boolean np.ndarray or None\n            Use a boolean array to define the background area.\n            The mask image must have the same shape as the\n            input data.`True` elements are used for background\n            estimation.\n        ret_mask: bool\n            Return the mask image used to compute the background.\n\n        Notes\n        -----\n        If both `border_px` and `from_mask` are given, the\n        intersection of the two resulting mask images is used.\n\n        The arguments passed to this method are stored in the\n        hdf5 file `self.h5` and are used for optional integrity\n        checking using `qpimage.integrity_check.check`.\n\n        See Also\n        --------\n        qpimage.bg_estimate.estimate"
  },
  {
    "code": "def create_metadata(self, **params):\n        params = json.dumps(params)\n        return self.post(\"https://upload.twitter.com/1.1/media/metadata/create.json\", params=params)",
    "docstring": "Adds metadata to a media element, such as image descriptions for visually impaired.\n\n        Docs:\n        https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-metadata-create"
  },
  {
    "code": "def get_last_scene_time(self, refresh=False):\n        if refresh:\n            self.refresh_complex_value('LastSceneTime')\n        val = self.get_complex_value('LastSceneTime')\n        return val",
    "docstring": "Get last scene time.\n\n        Refresh data from Vera if refresh is True, otherwise use local cache.\n        Refresh is only needed if you're not using subscriptions."
  },
  {
    "code": "def _check_email_changed(cls, username, email):\n        ret = cls.exec_request('user/{}'.format(username), 'get', raise_for_status=True)\n        return ret['email'] != email",
    "docstring": "Compares email to one set on SeAT"
  },
  {
    "code": "def histogram(self, bmus=None):\n        if bmus is None:\n            assert self._bmus is not None, 'not trained'\n            bmus = self._bmus\n        arr = np.zeros((self._som.nrows, self._som.ncols))\n        for i,j in bmus:\n            arr[i,j] += 1\n        return arr",
    "docstring": "\\\n        Return a 2D histogram of bmus.\n\n        :param bmus: the best-match units indexes for underlying data.\n        :type bmus: :class:`numpy.ndarray`\n        :returns: the computed 2D histogram of bmus.\n        :rtype: :class:`numpy.ndarray`"
  },
  {
    "code": "def getReliableListeners(self):\n        for rellist in self.store.query(_ReliableListener, _ReliableListener.processor == self):\n            yield rellist.listener",
    "docstring": "Return an iterable of the listeners which have been added to\n        this batch processor."
  },
  {
    "code": "def _raw_aspera_metadata(self, bucket):\n        response = self._client.get_bucket_aspera(Bucket=bucket)\n        aspera_access_key = response['AccessKey']['Id']\n        aspera_secret_key = response['AccessKey']['Secret']\n        ats_endpoint = response['ATSEndpoint']\n        return aspera_access_key, aspera_secret_key, ats_endpoint",
    "docstring": "get the Aspera connection details on Aspera enabled buckets"
  },
  {
    "code": "def get(self, query, sort, page, size):\n        urlkwargs = {\n            'q': query,\n            'sort': sort,\n            'size': size,\n        }\n        communities = Community.filter_communities(query, sort)\n        page = communities.paginate(page, size)\n        links = default_links_pagination_factory(page, urlkwargs)\n        links_headers = map(lambda key: ('link', 'ref=\"{0}\" href=\"{1}\"'.format(\n            key, links[key])), links)\n        return self.make_response(\n            page,\n            headers=links_headers,\n            links_item_factory=default_links_item_factory,\n            page=page,\n            urlkwargs=urlkwargs,\n            links_pagination_factory=default_links_pagination_factory,\n        )",
    "docstring": "Get a list of all the communities.\n\n        .. http:get:: /communities/(string:id)\n            Returns a JSON list with all the communities.\n            **Request**:\n            .. sourcecode:: http\n                GET /communities HTTP/1.1\n                Accept: application/json\n                Content-Type: application/json\n                Host: localhost:5000\n            :reqheader Content-Type: application/json\n            **Response**:\n            .. sourcecode:: http\n                HTTP/1.0 200 OK\n                Content-Length: 334\n                Content-Type: application/json\n                [\n                    {\n                        \"id\": \"comm1\"\n                    },\n                    {\n                        \"id\": \"comm2\"\n                    }\n                ]\n            :resheader Content-Type: application/json\n            :statuscode 200: no error"
  },
  {
    "code": "def on_click(self, button, **kwargs):\n        actions = ['leftclick', 'middleclick', 'rightclick',\n                   'upscroll', 'downscroll']\n        try:\n            action = actions[button - 1]\n        except (TypeError, IndexError):\n            self.__log_button_event(button, None, None, \"Other button\")\n            action = \"otherclick\"\n        m_click = self.__multi_click\n        with m_click.lock:\n            double = m_click.check_double(button)\n            double_action = 'double%s' % action\n            if double:\n                action = double_action\n            cb = getattr(self, 'on_%s' % action, None)\n            double_handler = getattr(self, 'on_%s' % double_action, None)\n            delay_execution = (not double and double_handler)\n            if delay_execution:\n                m_click.set_timer(button, cb, **kwargs)\n            else:\n                self.__button_callback_handler(button, cb, **kwargs)",
    "docstring": "Maps a click event with its associated callback.\n\n        Currently implemented events are:\n\n        ============  ================  =========\n        Event         Callback setting  Button ID\n        ============  ================  =========\n        Left click    on_leftclick      1\n        Middle click  on_middleclick    2\n        Right click   on_rightclick     3\n        Scroll up     on_upscroll       4\n        Scroll down   on_downscroll     5\n        Others        on_otherclick     > 5\n        ============  ================  =========\n\n        The action is determined by the nature (type and value) of the callback\n        setting in the following order:\n\n        1. If null callback (``None``), no action is taken.\n        2. If it's a `python function`, call it and pass any additional\n           arguments.\n        3. If it's name of a `member method` of current module (string), call\n           it and pass any additional arguments.\n        4. If the name does not match with `member method` name execute program\n           with such name.\n\n        .. seealso:: :ref:`callbacks` for more information about\n         callback settings and examples.\n\n        :param button: The ID of button event received from i3bar.\n        :param kwargs: Further information received from i3bar like the\n         positions of the mouse where the click occured.\n        :return: Returns ``True`` if a valid callback action was executed.\n         ``False`` otherwise."
  },
  {
    "code": "def _match_registers(self, query):\n        if query in self._status_registers:\n            register = self._status_registers[query]\n            response = register.value\n            logger.debug('Found response in status register: %s',\n                         repr(response))\n            register.clear()\n            return response",
    "docstring": "Tries to match in status registers\n\n        :param query: message tuple\n        :type query: Tuple[bytes]\n        :return: response if found or None\n        :rtype: Tuple[bytes] | None"
  },
  {
    "code": "def get_perm_codename(perm, fail_silently=True):\n    try:\n        perm = perm.split('.', 1)[1]\n    except IndexError as e:\n        if not fail_silently:\n            raise e\n    return perm",
    "docstring": "Get permission codename from permission-string.\n\n    Examples\n    --------\n    >>> get_perm_codename('app_label.codename_model')\n    'codename_model'\n    >>> get_perm_codename('app_label.codename')\n    'codename'\n    >>> get_perm_codename('codename_model')\n    'codename_model'\n    >>> get_perm_codename('codename')\n    'codename'\n    >>> get_perm_codename('app_label.app_label.codename_model')\n    'app_label.codename_model'"
  },
  {
    "code": "def add_item(self, item):\n        if not(isinstance(item.name, basestring) and isinstance(item.description, basestring)):\n            raise TypeError(\"Name and description should be strings, are of type {} and {}\"\n                            .format(type(item.name), type(item.description)))\n        if not(isinstance(item.flag_type, FlagType)):\n            raise TypeError(\"Flag type should be of type FlagType, is of {}\".format(type(item.flag_type)))\n        if item.name not in self._flags:\n            if item.default is not None:\n                if item.default is not False:\n                    item.description = item.description + \" (default: %(default)s)\"\n                self._flags[item.name] = item\n            else:\n                self._flags[item.name] = item",
    "docstring": "Add single command line flag\n\n        Arguments:\n            name (:obj:`str`): Name of flag used in command line\n            flag_type (:py:class:`snap_plugin.v1.plugin.FlagType`):\n                Indication if flag should store value or is simple bool flag\n            description (:obj:`str`): Flag description used in command line\n            default (:obj:`object`, optional): Optional default value for flag\n\n        Raises:\n            TypeError: Provided wrong arguments or arguments of wrong types, method will raise TypeError"
  },
  {
    "code": "def _cache_key_select_sample_type(method, self, allow_blank=True, multiselect=False, style=None):\n    key = update_timer(), allow_blank, multiselect, style\n    return key",
    "docstring": "This function returns the key used to decide if method select_sample_type has to be recomputed"
  },
  {
    "code": "def ddns(self, domain_id, record_id, sub_domain, record_line, value):\n        record = self.info(domain_id, record_id)\n        if record.sub_domain == sub_domain and \\\n           record.record_line == record_line and \\\n           record.value == value:\n            return\n        self._api.do_post('Record.Ddns', domain_id=domain_id,\n                          record_id=record_id, sub_domain=sub_domain,\n                          record_line=record_line, value=value)",
    "docstring": "Update record's value dynamically\n\n        If the ``value`` is different from the record's current value, then\n        perform a dynamic record update. Otherwise, nothing will be done.\n\n        :param str domain_id: Domain ID\n        :param str record_id: Record ID\n        :param str sub_domain: Sub domain of domain (e.g., **www** of **www.google.com**)\n        :param str record_line: Line of the record\n        :param str value: The record's value, an IP address"
  },
  {
    "code": "def write(filename, mesh, fmt_version, write_binary=True):\n    try:\n        writer = _writers[fmt_version]\n    except KeyError:\n        try:\n            writer = _writers[fmt_version.split(\".\")[0]]\n        except KeyError:\n            raise ValueError(\n                \"Need mesh format in {} (got {})\".format(\n                    sorted(_writers.keys()), fmt_version\n                )\n            )\n    writer.write(filename, mesh, write_binary=write_binary)",
    "docstring": "Writes a Gmsh msh file."
  },
  {
    "code": "def delete_files_in_folder(fldr):\n\tfl = glob.glob(fldr + os.sep + '*.*')\n\tfor f in fl:\n\t\tdelete_file(f, True)",
    "docstring": "delete all files in folder 'fldr'"
  },
  {
    "code": "def check_syntax(string):\n    args = [\"ecpg\", \"-o\", \"-\", \"-\"]\n    with open(os.devnull, \"w\") as devnull:\n        try:\n            proc = subprocess.Popen(args, shell=False,\n                                    stdout=devnull,\n                                    stdin=subprocess.PIPE,\n                                    stderr=subprocess.PIPE,\n                                    universal_newlines=True)\n            _, err = proc.communicate(string)\n        except OSError:\n            msg = \"Unable to execute 'ecpg', you likely need to install it.'\"\n            raise OSError(msg)\n        if proc.returncode == 0:\n            return (True, \"\")\n        else:\n            return (False, parse_error(err))",
    "docstring": "Check syntax of a string of PostgreSQL-dialect SQL"
  },
  {
    "code": "def get_index_mappings(self, index):\n        fields_arr = []\n        for (key, val) in iteritems(index):\n            doc_mapping = self.get_doc_type_mappings(index[key])\n            if doc_mapping is None:\n                return None\n            fields_arr.extend(doc_mapping)\n        return fields_arr",
    "docstring": "Converts all index's doc_types to .kibana"
  },
  {
    "code": "def load(cls, path):\n        data = json.load(open(path))\n        weights = data['weights']\n        weights = np.asarray(weights, dtype=np.float64)\n        s = cls(data['map_dimensions'],\n                data['params']['lr']['orig'],\n                data['data_dimensionality'],\n                influence=data['params']['infl']['orig'],\n                lr_lambda=data['params']['lr']['factor'],\n                infl_lambda=data['params']['infl']['factor'])\n        s.weights = weights\n        s.trained = True\n        return s",
    "docstring": "Load a SOM from a JSON file saved with this package..\n\n        Parameters\n        ----------\n        path : str\n            The path to the JSON file.\n\n        Returns\n        -------\n        s : cls\n            A som of the specified class."
  },
  {
    "code": "def _http_request(url, request_timeout=None):\n    _auth(url)\n    try:\n        request_timeout = __salt__['config.option']('solr.request_timeout')\n        kwargs = {} if request_timeout is None else {'timeout': request_timeout}\n        data = salt.utils.json.load(_urlopen(url, **kwargs))\n        return _get_return_dict(True, data, [])\n    except Exception as err:\n        return _get_return_dict(False, {}, [\"{0} : {1}\".format(url, err)])",
    "docstring": "PRIVATE METHOD\n    Uses salt.utils.json.load to fetch the JSON results from the solr API.\n\n    url : str\n        a complete URL that can be passed to urllib.open\n    request_timeout : int (None)\n        The number of seconds before the timeout should fail. Leave blank/None\n        to use the default. __opts__['solr.request_timeout']\n\n    Return: dict<str,obj>::\n\n         {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}"
  },
  {
    "code": "def create_polynoms():\n    fname = pr.resource_filename('pyciss', 'data/soliton_prediction_parameters.csv')\n    res_df = pd.read_csv(fname)\n    polys = {}\n    for resorder, row in zip('65 54 43 21'.split(),\n                             range(4)):\n        p = poly1d([res_df.loc[row, 'Slope (km/yr)'], res_df.loc[row, 'Intercept (km)']])\n        polys['janus ' + ':'.join(resorder)] = p\n    return polys",
    "docstring": "Create and return poly1d objects.\n\n    Uses the parameters from Morgan to create poly1d objects for\n    calculations."
  },
  {
    "code": "def implemented_methods(cls):\n        if cls.__implemented_methods:\n            return cls.__implemented_methods\n        cls.__implemented_methods = {}\n        for method in cls.callbacks:\n            for op in getattr(method, 'swagger_ops'):\n                cls.__implemented_methods[op] = method\n        return cls.__implemented_methods",
    "docstring": "Return a mapping of implemented HTTP methods vs. their callbacks."
  },
  {
    "code": "def challenge_auth(username, password, challenge, lower, digest='sha256'):\n    def hdig(x):\n        return fdigest(x).hexdigest()\n    fdigest = get_digest(digest)\n    luser = lower(username)\n    tpass = password[:10].encode(\"ascii\")\n    hvalue = hdig(\"{0}:{1}\".format(luser, hdig(tpass)).encode(\"ascii\"))\n    bhvalue = hvalue.encode(\"ascii\")\n    bchallenge = challenge.encode(\"ascii\")\n    return hmac.HMAC(bhvalue, bchallenge, digestmod=fdigest).hexdigest()",
    "docstring": "Calculates quakenet's challenge auth hash\n\n    .. code-block:: python\n\n        >>> challenge_auth(\"mooking\", \"0000000000\",\n        ...     \"12345678901234567890123456789012\", str.lower, \"md5\")\n        '2ed1a1f1d2cd5487d2e18f27213286b9'"
  },
  {
    "code": "def add_primary_text(self, item_url, primary_text):\n        c = self.conn.cursor()\n        c.execute(\"DELETE FROM primary_texts WHERE item_url=?\",\n                      (str(item_url),))\n        self.conn.commit()\n        c.execute(\"INSERT INTO primary_texts VALUES (?, ?, ?)\",\n                  (str(item_url), primary_text, self.__now_iso_8601()))\n        self.conn.commit()\n        c.close()",
    "docstring": "Add the given primary text to the cache database, updating\n        the existing record if the primary text is already present\n\n        :type item_url: String or Item\n        :param item_url: the URL of the corresponding item, or an Item object\n        :type primary_text: String\n        :param primary_text: the item's primary text"
  },
  {
    "code": "def _copy_scratch_to_state(args: Dict[str, Any]):\n    np.copyto(_state_shard(args), _scratch_shard(args))",
    "docstring": "Copes scratch shards to state shards."
  },
  {
    "code": "def parsePositionFile(filename):\n    l=[]\n    with open( filename, \"rb\" ) as theFile:\n        reader = csv.DictReader( theFile )\n        for line in reader:\n            mytime=dateparser.parse(line['time'])\n            line['strtime']=mytime.strftime(\"%d %b %Y, %H:%M UTC\")\n            l.append(line)\n    return l",
    "docstring": "Parses Android GPS logger csv file and returns list of dictionaries"
  },
  {
    "code": "def excise(self, ngrams, replacement):\n        content = self.get_token_content()\n        ngrams.sort(key=len, reverse=True)\n        for ngram in ngrams:\n            content = content.replace(ngram, replacement)\n        return content",
    "docstring": "Returns the token content of this text with every occurrence of\n        each n-gram in `ngrams` replaced with `replacement`.\n\n        The replacing is performed on each n-gram by descending order\n        of length.\n\n        :param ngrams: n-grams to be replaced\n        :type ngrams: `list` of `str`\n        :param replacement: replacement string\n        :type replacement: `str`\n        :rtype: `str`"
  },
  {
    "code": "def pack(self):\n        sn, sa = self.number, self.attribute\n        return pack(\"<H\", (sn & 0x3ff) << 6 | (sa & 0x3f))",
    "docstring": "Pack the service code for transmission. Returns a 2 byte string."
  },
  {
    "code": "def postIncidents(self, name, message, status, visible, **kwargs):\n        kwargs['name'] = name\n        kwargs['message'] = message\n        kwargs['status'] = status\n        kwargs['visible'] = visible\n        return self.__postRequest('/incidents', kwargs)",
    "docstring": "Create a new incident.\n\n        :param name: Name of the incident\n        :param message: A message (supporting Markdown) to explain more.\n        :param status: Status of the incident.\n        :param visible: Whether the incident is publicly visible.\n        :param component_id: (optional) Component to update.\n        :param component_status: (optional) The status to update the given component with.\n        :param notify: (optional) Whether to notify subscribers.\n        :return: :class:`Response <Response>` object\n        :rtype: requests.Response"
  },
  {
    "code": "def _get_disksize_MiB(iLOIP, cred):\n    result = _parse_mibs(iLOIP, cred)\n    disksize = {}\n    for uuid in sorted(result):\n        for key in result[uuid]:\n            if key.find('PhyDrvSize') >= 0:\n                disksize[uuid] = dict()\n                for suffix in sorted(result[uuid][key]):\n                    size = result[uuid][key][suffix]\n                    disksize[uuid][key] = str(size)\n    return disksize",
    "docstring": "Reads the dictionary of parsed MIBs and gets the disk size.\n\n    :param iLOIP: IP address of the server on which SNMP discovery\n                  has to be executed.\n    :param snmp_credentials in a dictionary having following mandatory\n           keys.\n           auth_user: SNMP user\n           auth_protocol: Auth Protocol\n           auth_prot_pp: Pass phrase value for AuthProtocol.\n           priv_protocol:Privacy Protocol.\n           auth_priv_pp: Pass phrase value for Privacy Protocol.\n\n    :returns the dictionary of disk sizes of all physical drives."
  },
  {
    "code": "def process_request(self, request, client_address):\n        self.collect_children()\n        pid = os.fork()\n        if pid:\n            if self.active_children is None:\n                self.active_children = []\n            self.active_children.append(pid)\n            self.close_request(request)\n            return\n        else:\n            try:\n                self.finish_request(request, client_address)\n                self.shutdown_request(request)\n                os._exit(0)\n            except:\n                try:\n                    self.handle_error(request, client_address)\n                    self.shutdown_request(request)\n                finally:\n                    os._exit(1)",
    "docstring": "Fork a new subprocess to process the request."
  },
  {
    "code": "def getVersion():\n        print('epochs version:', str(CDFepoch.version) + '.' +\n              str(CDFepoch.release) + '.'+str(CDFepoch.increment))",
    "docstring": "Shows the code version."
  },
  {
    "code": "def guess_lexer_using_filename(file_name, text):\n    lexer, accuracy = None, None\n    try:\n        lexer = custom_pygments_guess_lexer_for_filename(file_name, text)\n    except SkipHeartbeat as ex:\n        raise SkipHeartbeat(u(ex))\n    except:\n        log.traceback(logging.DEBUG)\n    if lexer is not None:\n        try:\n            accuracy = lexer.analyse_text(text)\n        except:\n            log.traceback(logging.DEBUG)\n    return lexer, accuracy",
    "docstring": "Guess lexer for given text, limited to lexers for this file's extension.\n\n    Returns a tuple of (lexer, accuracy)."
  },
  {
    "code": "def get_sequence(self, chrom, start, end, strand=None):\n        if not self.index_dir:\n            print(\"Index dir is not defined!\")\n            sys.exit()\n        fasta_file = self.fasta_file[chrom]\n        index_file = self.index_file[chrom]\n        line_size = self.line_size[chrom]\n        total_size = self.size[chrom]\n        if start > total_size:\n            raise ValueError(\n                    \"Invalid start {0}, greater than sequence length {1} of {2}!\".format(start, total_size, chrom))\n        if start < 0:\n            raise ValueError(\"Invalid start, < 0!\")\n        if end > total_size:\n            raise ValueError(\n                    \"Invalid end {0}, greater than sequence length {1} of {2}!\".format(end, total_size, chrom))\n        index = open(index_file, \"rb\")\n        fasta = open(fasta_file)\n        seq = self._read(index, fasta, start, end, line_size)\n        index.close()\n        fasta.close()\n        if strand and strand == \"-\":\n            seq = rc(seq)\n        return seq",
    "docstring": "Retrieve a sequence"
  },
  {
    "code": "def to_json(self):\n        data = json.dumps(self)\n        out = u'{\"%s\":%s}' % (self.schema['title'], data)\n        return out",
    "docstring": "put the object to json and remove the internal stuff\n        salesking schema stores the type in the title"
  },
  {
    "code": "def inxsearch(self, r, g, b):\n        dists = (self.colormap[:, :3] - np.array([r, g, b]))\n        a = np.argmin((dists * dists).sum(1))\n        return a",
    "docstring": "Search for BGR values 0..255 and return colour index"
  },
  {
    "code": "def get(self, pid, record, **kwargs):\n        etag = str(record.revision_id)\n        self.check_etag(str(record.revision_id))\n        self.check_if_modified_since(record.updated, etag=etag)\n        return self.make_response(\n            pid, record, links_factory=self.links_factory\n        )",
    "docstring": "Get a record.\n\n        Permissions: ``read_permission_factory``\n\n        Procedure description:\n\n        #. The record is resolved reading the pid value from the url.\n\n        #. The ETag and If-Modifed-Since is checked.\n\n        #. The HTTP response is built with the help of the link factory.\n\n        :param pid: Persistent identifier for record.\n        :param record: Record object.\n        :returns: The requested record."
  },
  {
    "code": "def _has_manual_kern_feature(font):\n    return any(f for f in font.features if f.name == \"kern\" and not f.automatic)",
    "docstring": "Return true if the GSFont contains a manually written 'kern' feature."
  },
  {
    "code": "def create_or_get_keypair(self, nova, keypair_name=\"testkey\"):\n        try:\n            _keypair = nova.keypairs.get(keypair_name)\n            self.log.debug('Keypair ({}) already exists, '\n                           'using it.'.format(keypair_name))\n            return _keypair\n        except Exception:\n            self.log.debug('Keypair ({}) does not exist, '\n                           'creating it.'.format(keypair_name))\n        _keypair = nova.keypairs.create(name=keypair_name)\n        return _keypair",
    "docstring": "Create a new keypair, or return pointer if it already exists."
  },
  {
    "code": "def _open(file,mode='copyonwrite'):\n    import pyfits\n    try:\n        infits=pyfits.open(file,mode)   \n        hdu=infits\n    except (ValueError,pyfits.VerifyError,pyfits.FITS_SevereError):\n        import sys\n        hdu=_open_fix(file)\n    for f in hdu:\n        strip_pad(f)\n    return hdu",
    "docstring": "Opens a FITS format file and calls _open_fix if header doesn't\n    verify correctly."
  },
  {
    "code": "def _get_decision_trees_bulk(self, payload, valid_indices, invalid_indices, invalid_dts):\n    valid_dts = self._create_and_send_json_bulk([payload[i] for i in valid_indices],\n                                                \"{}/bulk/decision_tree\".format(self._base_url),\n                                                \"POST\")\n    if invalid_indices == []:\n      return valid_dts\n    return self._recreate_list_with_indices(valid_indices, valid_dts, invalid_indices, invalid_dts)",
    "docstring": "Tool for the function get_decision_trees_bulk.\n\n    :param list payload: contains the informations necessary for getting\n    the trees. Its form is the same than for the function.\n    get_decision_trees_bulk.\n    :param list valid_indices: list of the indices of the valid agent id.\n    :param list invalid_indices: list of the indices of the valid agent id.\n    :param list invalid_dts: list of the invalid agent id.\n\n    :return: decision trees.\n    :rtype: list of dict."
  },
  {
    "code": "def nl_socket_modify_err_cb(sk, kind, func, arg):\n    return int(nl_cb_err(sk.s_cb, kind, func, arg))",
    "docstring": "Modify the error callback handler associated with the socket.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L649\n\n    Positional arguments:\n    sk -- Netlink socket (nl_sock class instance).\n    kind -- kind of callback (integer).\n    func -- callback function.\n    arg -- argument to be passed to callback function.\n\n    Returns:\n    0 on success or a negative error code."
  },
  {
    "code": "def _get_keywords(self, location, keywords):\n        if 'xml' in keywords:\n            keywords.pop('xml')\n            self.xml = True\n        else:\n            keywords['file_type'] = 'json'\n        if 'id' in keywords:\n            if location != 'series':\n                location = location.rstrip('s')\n            key = '%s_id' % location\n            value = keywords.pop('id')\n            keywords[key] = value\n        if 'start' in keywords:\n            time = keywords.pop('start')\n            keywords['realtime_start'] = time\n        if 'end' in keywords:\n            time = keywords.pop('end')\n            keywords['realtime_end'] = time\n        if 'sort' in keywords:\n            order = keywords.pop('sort')\n            keywords['sort_order'] = order\n        keywords['api_key'] = self.api_key\n        return keywords",
    "docstring": "Format GET request's parameters from keywords."
  },
  {
    "code": "def _remove_exts(self,string):\n        if string.lower().endswith(('.png','.gif','.jpg','.bmp','.jpeg','.ppm','.datauri')):\n            format = string[string.rfind('.') +1 :len(string)]\n            if format.lower() == 'jpg':\n                    format = 'jpeg'\n            self.format = format\n            string = string[0:string.rfind('.')]\n        return string",
    "docstring": "Sets the string, to create the Robohash"
  },
  {
    "code": "def deallocate_network_ipv4(self, id_network_ipv4):\n        if not is_valid_int_param(id_network_ipv4):\n            raise InvalidParameterError(\n                u'The identifier of NetworkIPv4 is invalid or was not informed.')\n        url = 'network/ipv4/' + str(id_network_ipv4) + '/deallocate/'\n        code, xml = self.submit(None, 'DELETE', url)\n        return self.response(code, xml)",
    "docstring": "Deallocate all relationships between NetworkIPv4.\n\n        :param id_network_ipv4: ID for NetworkIPv4\n\n        :return: Nothing\n\n        :raise InvalidParameterError: Invalid ID for NetworkIPv4.\n        :raise NetworkIPv4NotFoundError: NetworkIPv4 not found.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "async def run_asgi(self):\n        try:\n            result = await self.app(self.scope, self.asgi_receive, self.asgi_send)\n        except BaseException as exc:\n            self.closed_event.set()\n            msg = \"Exception in ASGI application\\n\"\n            self.logger.error(msg, exc_info=exc)\n            if not self.handshake_started_event.is_set():\n                self.send_500_response()\n            else:\n                await self.handshake_completed_event.wait()\n            self.transport.close()\n        else:\n            self.closed_event.set()\n            if not self.handshake_started_event.is_set():\n                msg = \"ASGI callable returned without sending handshake.\"\n                self.logger.error(msg)\n                self.send_500_response()\n                self.transport.close()\n            elif result is not None:\n                msg = \"ASGI callable should return None, but returned '%s'.\"\n                self.logger.error(msg, result)\n                await self.handshake_completed_event.wait()\n                self.transport.close()",
    "docstring": "Wrapper around the ASGI callable, handling exceptions and unexpected\n        termination states."
  },
  {
    "code": "def info(gandi):\n    output_keys = ['handle', 'credit', 'prepaid']\n    account = gandi.account.all()\n    account['prepaid_info'] = gandi.contact.balance().get('prepaid', {})\n    output_account(gandi, account, output_keys)\n    return account",
    "docstring": "Display information about hosting account."
  },
  {
    "code": "def package_version(package_name: str) -> typing.Optional[str]:\n    try:\n        return pkg_resources.get_distribution(package_name).version\n    except (pkg_resources.DistributionNotFound, AttributeError):\n        return None",
    "docstring": "Returns package version as a string, or None if it couldn't be found."
  },
  {
    "code": "def multiply_encrypted_to_plaintext(public, encrypted, plaintext, output):\n    log(\"Loading public key\")\n    publickeydata = json.load(public)\n    pub = load_public_key(publickeydata)\n    log(\"Loading encrypted number\")\n    enc = load_encrypted_number(encrypted, pub)\n    log(\"Loading unencrypted number\")\n    num = float(plaintext)\n    log(\"Multiplying\")\n    enc_result = enc * num\n    serialised_result = serialise_encrypted(enc_result)\n    print(serialised_result, file=output)",
    "docstring": "Multiply encrypted num with unencrypted num.\n\n    Requires a PUBLIC key file, a number ENCRYPTED with that public key\n    also as a file, and the PLAINTEXT number to multiply.\n\n    Creates a new encrypted number."
  },
  {
    "code": "def dispatch_hook(cls, _pkt=b\"\", *args, **kargs):\n        if _pkt and len(_pkt) >= 1:\n            if orb(_pkt[0]) == 0x41:\n                return LoWPANUncompressedIPv6\n            if orb(_pkt[0]) == 0x42:\n                return LoWPAN_HC1\n            if orb(_pkt[0]) >> 3 == 0x18:\n                return LoWPANFragmentationFirst\n            elif orb(_pkt[0]) >> 3 == 0x1C:\n                return LoWPANFragmentationSubsequent\n            elif orb(_pkt[0]) >> 6 == 0x02:\n                return LoWPANMesh\n            elif orb(_pkt[0]) >> 6 == 0x01:\n                return LoWPAN_IPHC\n        return cls",
    "docstring": "Depending on the payload content, the frame type we should interpretate"
  },
  {
    "code": "def add_taxes(self, taxes):\n        _idx = len(self.taxes)\n        for idx, tax in enumerate(taxes):\n            tax_key = \"tax_\" + str(idx + _idx)\n            self.taxes[tax_key] = {\"name\": tax[0], \"amount\": tax[1]}",
    "docstring": "Appends the data to the 'taxes' key in the request object\n\n        'taxes' should be in format: [(\"tax_name\", \"tax_amount\")]\n        For example:\n        [(\"Other TAX\", 700), (\"VAT\", 5000)]"
  },
  {
    "code": "def get_items_of_media_type(self, media_type):\n        return (item for item in self.items if item.media_type == media_type)",
    "docstring": "Returns all items of specified media type.\n\n        :Args:\n          - media_type: Media type for items we are searching for\n\n        :Returns:\n          Returns found items as tuple."
  },
  {
    "code": "def discover_config_path(self, config_filename: str) -> str:\n        if config_filename and os.path.isfile(config_filename):\n            return config_filename\n        for place in _common_places:\n            config_path = os.path.join(place, config_filename)\n            if os.path.isfile(config_path):\n                return config_path\n        return",
    "docstring": "Search for config file in a number of places.\n        If there is no config file found, will return None.\n\n        :param config_filename: Config file name or custom path to filename with config.\n        :return: Path to the discovered config file or None."
  },
  {
    "code": "def set_operation_voltage_level(self):\n        mv_station_v_level_operation = float(cfg_ding0.get('mv_routing_tech_constraints',\n                                                           'mv_station_v_level_operation'))\n        self.v_level_operation = mv_station_v_level_operation * self.grid.v_level",
    "docstring": "Set operation voltage level"
  },
  {
    "code": "def readRGBA(self):\n        self.reset_bits_pending();\n        r = self.readUI8()\n        g = self.readUI8()\n        b = self.readUI8()\n        a = self.readUI8()\n        return (a << 24) | (r << 16) | (g << 8) | b",
    "docstring": "Read a RGBA color"
  },
  {
    "code": "def _combine_sets(self, sets, final_set):\n        self.cls.get_connection().sinterstore(final_set, list(sets))\n        return final_set",
    "docstring": "Given a list of set, combine them to create the final set that will be\n        used to make the final redis call."
  },
  {
    "code": "def ResourcePath(package_name, filepath):\n  if not getattr(sys, \"frozen\", None):\n    target = _GetPkgResources(package_name, filepath)\n    if target and os.access(target, os.R_OK):\n      return target\n  target = os.path.join(sys.prefix, filepath)\n  if target and os.access(target, os.R_OK):\n    return target\n  return None",
    "docstring": "Computes a path to the specified package resource.\n\n  Args:\n    package_name: A name of the package where the resource is located.\n    filepath: A path to the resource relative to the package location.\n\n  Returns:\n    A path to the resource or `None` if the resource cannot be found."
  },
  {
    "code": "def _parse_header(self, header_string):\n        header_content = header_string.strip().split('\\t')\n        if len(header_content) != self._snv_enum.HEADER_LEN.value:\n            raise MTBParserException(\n                \"Only {} header columns found, {} expected!\"\n                .format(len(header_content), self._snv_enum.HEADER_LEN.value))\n        counter = 0\n        for column in header_content:\n            for enum_type in self._snv_enum:\n                if column == enum_type.value:\n                    self._header_to_column_mapping[enum_type.name] = counter\n                    continue\n            counter+=1\n        if len(self._header_to_column_mapping) != self._snv_enum.HEADER_LEN.value:\n            debug_string = self._header_to_column_mapping.keys()\n            raise MTBParserException(\"Parsing incomplete: Not all columns have been \"\n                    \"matched to speficied column types. Identified {} columns, but expected {}. {}\"\n                    .format(len(self._header_to_column_mapping), self._snv_enum.HEADER_LEN.value, debug_string))",
    "docstring": "Parses the header and determines the column type\n        and its column index."
  },
  {
    "code": "def get_collection(self, **kwargs):\n        from pymongo import MongoClient\n        if self.host and self.port:\n            client = MongoClient(host=config.host, port=config.port)\n        else:\n            client = MongoClient()\n        db = client[self.dbname]\n        if self.user and self.password:\n            db.autenticate(self.user, password=self.password)\n        return db[self.collection]",
    "docstring": "Establish a connection with the database.\n\n        Returns MongoDb collection"
  },
  {
    "code": "def save(self, *args, **kwargs):\n        if self.gen_description:\n            self.description = strip_tags(self.description_from_content())\n        super(MetaData, self).save(*args, **kwargs)",
    "docstring": "Set the description field on save."
  },
  {
    "code": "def timezone(self, lat, lon, datetime,\n                 language=None, sensor=None):\n        parameters = dict(\n            location=\"%f,%f\" % (lat, lon),\n            timestamp=unixtimestamp(datetime),\n            language=language,\n            sensor=sensor,\n        )\n        return self._make_request(self.TIMEZONE_URL, parameters, None)",
    "docstring": "Get time offset data for given location.\n\n        :param lat: Latitude of queried point\n        :param lon: Longitude of queried point\n        :param language: The language in which to return results. For full list\n             of laguages go to Google Maps API docs\n        :param datetime: Desired time. The Time Zone API uses the timestamp to\n             determine whether or not Daylight Savings should be applied.\n             datetime should be timezone aware. If it isn't the UTC timezone\n             is assumed.\n        :type datetime: datetime.datetime\n        :param sensor: Override default client sensor parameter"
  },
  {
    "code": "def get_option(self, optionname, default=0):\n        global_options = ('verify', 'all_logs', 'log_size', 'plugin_timeout')\n        if optionname in global_options:\n            return getattr(self.commons['cmdlineopts'], optionname)\n        for name, parms in zip(self.opt_names, self.opt_parms):\n            if name == optionname:\n                val = parms['enabled']\n                if val is not None:\n                    return val\n        return default",
    "docstring": "Returns the first value that matches 'optionname' in parameters\n        passed in via the command line or set via set_option or via the\n        global_plugin_options dictionary, in that order.\n\n        optionaname may be iterable, in which case the first option that\n        matches any of the option names is returned."
  },
  {
    "code": "def get_user_id(username):\n    uid = single_line_stdout('id -u {0}'.format(username), expected_errors=(1,), shell=False)\n    return check_int(uid)",
    "docstring": "Returns the user id to a given user name. Returns ``None`` if the user does not exist.\n\n    :param username: User name.\n    :type username: unicode\n    :return: User id.\n    :rtype: int"
  },
  {
    "code": "def structural_imbalance(S, sampler=None, **sampler_args):\n    h, J = structural_imbalance_ising(S)\n    response = sampler.sample_ising(h, J, **sampler_args)\n    sample = next(iter(response))\n    colors = {v: (spin + 1) // 2 for v, spin in iteritems(sample)}\n    frustrated_edges = {}\n    for u, v, data in S.edges(data=True):\n        sign = data['sign']\n        if sign > 0 and colors[u] != colors[v]:\n            frustrated_edges[(u, v)] = data\n        elif sign < 0 and colors[u] == colors[v]:\n            frustrated_edges[(u, v)] = data\n    return frustrated_edges, colors",
    "docstring": "Returns an approximate set of frustrated edges and a bicoloring.\n\n    A signed social network graph is a graph whose signed edges\n    represent friendly/hostile interactions between nodes. A\n    signed social network is considered balanced if it can be cleanly\n    divided into two factions, where all relations within a faction are\n    friendly, and all relations between factions are hostile. The measure\n    of imbalance or frustration is the minimum number of edges that\n    violate this rule.\n\n    Parameters\n    ----------\n    S : NetworkX graph\n        A social graph on which each edge has a 'sign'\n        attribute with a numeric value.\n\n    sampler\n        A binary quadratic model sampler. A sampler is a process that\n        samples from low energy states in models defined by an Ising\n        equation or a Quadratic Unconstrainted Binary Optimization\n        Problem (QUBO). A sampler is expected to have a 'sample_qubo'\n        and 'sample_ising' method. A sampler is expected to return an\n        iterable of samples, in order of increasing energy. If no\n        sampler is provided, one must be provided using the\n        `set_default_sampler` function.\n\n    sampler_args\n        Additional keyword parameters are passed to the sampler.\n\n    Returns\n    -------\n    frustrated_edges : dict\n        A dictionary of the edges that violate the edge sign. The imbalance\n        of the network is the length of frustrated_edges.\n\n    colors: dict\n        A bicoloring of the nodes into two factions.\n\n    Raises\n    ------\n    ValueError\n        If any edge does not have a 'sign' attribute.\n\n    Examples\n    --------\n    >>> import dimod\n    >>> sampler = dimod.ExactSolver()\n    >>> S = nx.Graph()\n    >>> S.add_edge('Alice', 'Bob', sign=1)  # Alice and Bob are friendly\n    >>> S.add_edge('Alice', 'Eve', sign=-1)  # Alice and Eve are hostile\n    >>> S.add_edge('Bob', 'Eve', sign=-1)  # Bob and Eve are hostile\n    >>> frustrated_edges, colors = dnx.structural_imbalance(S, sampler)\n    >>> print(frustrated_edges)\n    {}\n    >>> print(colors)  # doctest: +SKIP\n    {'Alice': 0, 'Bob': 0, 'Eve': 1}\n    >>> S.add_edge('Ted', 'Bob', sign=1)  # Ted is friendly with all\n    >>> S.add_edge('Ted', 'Alice', sign=1)\n    >>> S.add_edge('Ted', 'Eve', sign=1)\n    >>> frustrated_edges, colors = dnx.structural_imbalance(S, sampler)\n    >>> print(frustrated_edges)\n    {('Ted', 'Eve'): {'sign': 1}}\n    >>> print(colors)  # doctest: +SKIP\n    {'Bob': 1, 'Ted': 1, 'Alice': 1, 'Eve': 0}\n\n    Notes\n    -----\n    Samplers by their nature may not return the optimal solution. This\n    function does not attempt to confirm the quality of the returned\n    sample.\n\n    References\n    ----------\n\n    `Ising model on Wikipedia <https://en.wikipedia.org/wiki/Ising_model>`_\n\n    .. [FIA] Facchetti, G., Iacono G., and Altafini C. (2011). Computing\n       global structural balance in large-scale signed social networks.\n       PNAS, 108, no. 52, 20953-20958"
  },
  {
    "code": "def consume(self, callback, bindings=None, queues=None, exchanges=None):\n        self._bindings = bindings or config.conf[\"bindings\"]\n        self._queues = queues or config.conf[\"queues\"]\n        self._exchanges = exchanges or config.conf[\"exchanges\"]\n        if inspect.isclass(callback):\n            cb_obj = callback()\n            if not callable(cb_obj):\n                raise ValueError(\n                    \"Callback must be a class that implements __call__\"\n                    \" or a function.\"\n                )\n            self._consumer_callback = cb_obj\n        elif callable(callback):\n            self._consumer_callback = callback\n        else:\n            raise ValueError(\n                \"Callback must be a class that implements __call__\" \" or a function.\"\n            )\n        self._running = True\n        self.connect()\n        self._connection.ioloop.start()",
    "docstring": "Consume messages from a message queue.\n\n        Simply define a callable to be used as the callback when messages are\n        delivered and specify the queue bindings. This call blocks. The callback\n        signature should accept a single positional argument which is an\n        instance of a :class:`Message` (or a sub-class of it).\n\n        Args:\n            callback (callable): The callable to pass the message to when one\n                arrives.\n            bindings (list of dict): A list of dictionaries describing bindings\n                for queues. Refer to the :ref:`conf-bindings` configuration\n                documentation for the format.\n            queues (dict): A dictionary of queues to ensure exist. Refer to the\n                :ref:`conf-queues` configuration documentation for the format.\n            exchanges (dict): A dictionary of exchanges to ensure exist. Refer\n                to the :ref:`conf-exchanges` configuration documentation for the\n                format.\n\n        Raises:\n            HaltConsumer: Raised when the consumer halts.\n            ValueError: If the callback isn't a callable object or a class with\n                __call__ defined."
  },
  {
    "code": "def get_invalid_txn_info(self, batch_id):\n        with self._lock:\n            return [info.copy() for info in self._invalid.get(batch_id, [])]",
    "docstring": "Fetches the id of the Transaction that failed within a particular\n        Batch, as well as any error message or other data about the failure.\n\n        Args:\n            batch_id (str): The id of the Batch containing an invalid txn\n\n        Returns:\n            list of dict: A list of dicts with three possible keys:\n                * 'id' - the header_signature of the invalid Transaction\n                * 'message' - the error message sent by the TP\n                * 'extended_data' - any additional data sent by the TP"
  },
  {
    "code": "def list_file_extensions(path: str, reportevery: int = 1) -> List[str]:\n    extensions = set()\n    count = 0\n    for root, dirs, files in os.walk(path):\n        count += 1\n        if count % reportevery == 0:\n            log.debug(\"Walking directory {}: {!r}\", count, root)\n        for file in files:\n            filename, ext = os.path.splitext(file)\n            extensions.add(ext)\n    return sorted(list(extensions))",
    "docstring": "Returns a sorted list of every file extension found in a directory\n    and its subdirectories.\n\n    Args:\n        path: path to scan\n        reportevery: report directory progress after every *n* steps\n\n    Returns:\n        sorted list of every file extension found"
  },
  {
    "code": "def message_channel(self, message):\n        self.log(None, message)\n        super(BaseBot, self).message_channel(message)",
    "docstring": "We won't receive our own messages, so log them manually."
  },
  {
    "code": "def apply_analysis_request_partition_interface(portal):\n    logger.info(\"Applying 'IAnalysisRequestPartition' marker interface ...\")\n    query = dict(portal_type=\"AnalysisRequest\", isRootAncestor=False)\n    brains = api.search(query, CATALOG_ANALYSIS_REQUEST_LISTING)\n    total = len(brains)\n    for num, brain in enumerate(brains):\n        if num % 100 == 0:\n            logger.info(\"Applying 'IAnalysisRequestPartition' interface: {}/{}\"\n                        .format(num, total))\n        ar = api.get_object(brain)\n        if IAnalysisRequestPartition.providedBy(ar):\n            continue\n        if ar.getParentAnalysisRequest():\n            alsoProvides(ar, IAnalysisRequestPartition)\n    commit_transaction(portal)",
    "docstring": "Walks trhough all AR-like partitions registered in the system and\n    applies the IAnalysisRequestPartition marker interface to them"
  },
  {
    "code": "def page(self, email=values.unset, status=values.unset, page_token=values.unset,\n             page_number=values.unset, page_size=values.unset):\n        params = values.of({\n            'Email': email,\n            'Status': status,\n            'PageToken': page_token,\n            'Page': page_number,\n            'PageSize': page_size,\n        })\n        response = self._version.page(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return AuthorizationDocumentPage(self._version, response, self._solution)",
    "docstring": "Retrieve a single page of AuthorizationDocumentInstance records from the API.\n        Request is executed immediately\n\n        :param unicode email: Email.\n        :param AuthorizationDocumentInstance.Status status: The Status of this AuthorizationDocument.\n        :param str page_token: PageToken provided by the API\n        :param int page_number: Page Number, this value is simply for client state\n        :param int page_size: Number of records to return, defaults to 50\n\n        :returns: Page of AuthorizationDocumentInstance\n        :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentPage"
  },
  {
    "code": "def get_api_connector(cls):\n        if cls._api is None:\n            cls.load_config()\n            cls.debug('initialize connection to remote server')\n            apihost = cls.get('api.host')\n            if not apihost:\n                raise MissingConfiguration()\n            apienv = cls.get('api.env')\n            if apienv and apienv in cls.apienvs:\n                apihost = cls.apienvs[apienv]\n            cls._api = XMLRPCClient(host=apihost, debug=cls.verbose)\n        return cls._api",
    "docstring": "Initialize an api connector for future use."
  },
  {
    "code": "def top_games(self, limit=10, offset=0):\n        r = self.kraken_request('GET', 'games/top',\n                                params={'limit': limit,\n                                        'offset': offset})\n        return models.Game.wrap_topgames(r)",
    "docstring": "Return the current top games\n\n        :param limit: the maximum amount of top games to query\n        :type limit: :class:`int`\n        :param offset: the offset in the top games\n        :type offset: :class:`int`\n        :returns: a list of top games\n        :rtype: :class:`list` of :class:`models.Game`\n        :raises: None"
  },
  {
    "code": "def nuclear_norm(data):\n    r\n    u, s, v = np.linalg.svd(data)\n    return np.sum(s)",
    "docstring": "r\"\"\"Nuclear norm\n\n    This method computes the nuclear (or trace) norm of the input data.\n\n    Parameters\n    ----------\n    data : np.ndarray\n        Input data array\n\n    Returns\n    -------\n    float nuclear norm value\n\n    Examples\n    --------\n    >>> from modopt.math.matrix import nuclear_norm\n    >>> a = np.arange(9).reshape(3, 3)\n    >>> nuclear_norm(a)\n    15.49193338482967\n\n    Notes\n    -----\n    Implements the following equation:\n\n    .. math::\n        \\|\\mathbf{A}\\|_* = \\sum_{i=1}^{\\min\\{m,n\\}} \\sigma_i (\\mathbf{A})"
  },
  {
    "code": "def delete(self, request, uri):\n        uri = self.decode_uri(uri)\n        uris = cio.delete(uri)\n        if uri not in uris:\n            raise Http404\n        return self.render_to_response()",
    "docstring": "Delete versioned uri and return empty text response on success."
  },
  {
    "code": "def columns(self, *args) -> List[List[Well]]:\n        col_dict = self._create_indexed_dictionary(group=2)\n        keys = sorted(col_dict, key=lambda x: int(x))\n        if not args:\n            res = [col_dict[key] for key in keys]\n        elif isinstance(args[0], int):\n            res = [col_dict[keys[idx]] for idx in args]\n        elif isinstance(args[0], str):\n            res = [col_dict[idx] for idx in args]\n        else:\n            raise TypeError\n        return res",
    "docstring": "Accessor function used to navigate through a labware by column.\n\n        With indexing one can treat it as a typical python nested list.\n        To access row A for example,\n        simply write: labware.columns()[0]\n        This will output ['A1', 'B1', 'C1', 'D1'...].\n\n        Note that this method takes args for backward-compatibility, but use\n        of args is deprecated and will be removed in future versions. Args\n        can be either strings or integers, but must all be the same type (e.g.:\n        `self.columns(1, 4, 8)` or `self.columns('1', '2')`, but\n        `self.columns('1', 4)` is invalid.\n\n        :return: A list of column lists"
  },
  {
    "code": "async def stop_pages(self):\n        await self.bot.delete_message(self.message)\n        self.paginating = False",
    "docstring": "stops the interactive pagination session"
  },
  {
    "code": "def get_revisions(page, page_num=1):\n    revisions   = page.revisions.order_by('-created_at')\n    current     = page.get_latest_revision()\n    if current:\n        revisions.exclude(id=current.id)\n    paginator = Paginator(revisions, 5)\n    try:\n        revisions = paginator.page(page_num)\n    except PageNotAnInteger:\n        revisions = paginator.page(1)\n    except EmptyPage:\n        revisions = paginator.page(paginator.num_pages)\n    return revisions",
    "docstring": "Returns paginated queryset of PageRevision instances for\n    specified Page instance.\n\n    :param page: the page instance.\n    :param page_num: the pagination page number.\n    :rtype: django.db.models.query.QuerySet."
  },
  {
    "code": "def get_min_row_num(mention):\n    span = _to_span(mention)\n    if span.sentence.is_tabular():\n        return span.sentence.cell.row_start\n    else:\n        return None",
    "docstring": "Return the lowest row number that a Mention occupies.\n\n    :param mention: The Mention to evaluate. If a candidate is given, default\n        to its first Mention.\n    :rtype: integer or None"
  },
  {
    "code": "def send_updates(self):\n        d = datetime.now()\n        if self.timeaddr:\n            self.tunnel.group_write(self.timeaddr,\n                                    time_to_knx(d))\n        if self.dateaddr:\n            self.tunnel.group_write(self.dateaddr,\n                                    date_to_knx(d))\n        if self.datetimeaddr:\n            self.tunnel.group_write(self.datetimeaddr,\n                                    datetime_to_knx(d))\n        if self.daynightaddr:\n            from pysolar.solar import get_altitude\n            alt = get_altitude(self.lat, self.long, d)\n            if alt > 0:\n                self.tunnel.group_write(self.daynightaddr, 1)\n            else:\n                self.tunnel.group_write(self.daynightaddr, 0)",
    "docstring": "Send updated to the KNX bus."
  },
  {
    "code": "def selectin(table, field, value, complement=False):\n    return select(table, field, lambda v: v in value,\n                  complement=complement)",
    "docstring": "Select rows where the given field is a member of the given value."
  },
  {
    "code": "def _RoundTowardZero(value, divider):\n  result = value // divider\n  remainder = value % divider\n  if result < 0 and remainder > 0:\n    return result + 1\n  else:\n    return result",
    "docstring": "Truncates the remainder part after division."
  },
  {
    "code": "def time_emd(emd_type, data):\n    emd = {\n        'cause': _CAUSE_EMD,\n        'effect': pyphi.subsystem.effect_emd,\n        'hamming': pyphi.utils.hamming_emd\n    }[emd_type]\n    def statement():\n        for (d1, d2) in data:\n            emd(d1, d2)\n    results = timeit.repeat(statement, number=NUMBER, repeat=REPEAT)\n    return min(results)",
    "docstring": "Time an EMD command with the given data as arguments"
  },
  {
    "code": "def clean_upload(self, query='/content/uploads/'):\n        query = query + self.uid + '/'\n        _r = self.connector.delete(query)\n        if _r.status_code == Constants.PULP_DELETE_OK:\n            juicer.utils.Log.log_info(\"Cleaned up after upload request.\")\n        else:\n            _r.raise_for_status()",
    "docstring": "pulp leaves droppings if you don't specifically tell it\n        to clean up after itself. use this to do so."
  },
  {
    "code": "def get_latlon(self, use_cached=True):\n        device_json = self.get_device_json(use_cached)\n        lat = device_json.get(\"dpMapLat\")\n        lon = device_json.get(\"dpMapLong\")\n        return (float(lat) if lat else None,\n                float(lon) if lon else None, )",
    "docstring": "Get a tuple with device latitude and longitude... these may be None"
  },
  {
    "code": "def _op(self, _, obj, app):\n        if obj.responses == None: return \n        tmp = {}\n        for k, v in six.iteritems(obj.responses):\n            if isinstance(k, six.integer_types):\n                tmp[str(k)] = v\n            else:\n                tmp[k] = v\n        obj.update_field('responses', tmp)",
    "docstring": "convert status code in Responses from int to string"
  },
  {
    "code": "def post(self, request):\n        request.session['next'] = self.get_next(request)\n        client = self.get_client()()\n        request.session[self.get_client().get_session_key()] = client\n        url = client.get_redirect_url(request=request)\n        logger.debug(\"Redirecting to %s\", url)\n        try:\n            return HttpResponseRedirect(url)\n        except OAuthError, error:\n            return self.error_to_response(request, {'error': error})\n        except socket.timeout:\n            return self.error_to_response(request, {'error': \n                _('Could not connect to service (timed out)')})",
    "docstring": "Create a client, store it in the user's session and redirect the user\n        to the API provider to authorize our app and permissions."
  },
  {
    "code": "def start(self):\n        self.log.debug('Starting the installation process')\n        self.browser.open(self.url)\n        self.system_check()",
    "docstring": "Start the installation wizard"
  },
  {
    "code": "def info(message, domain):\n        if domain in Logger._ignored_domains:\n            return\n        Logger._log(None, message, INFO, domain)",
    "docstring": "Log simple info"
  },
  {
    "code": "async def get(\n        self,\n        stream: str,\n        direction: msg.StreamDirection = msg.StreamDirection.Forward,\n        from_event: int = 0,\n        max_count: int = 100,\n        resolve_links: bool = True,\n        require_master: bool = False,\n        correlation_id: uuid.UUID = None,\n    ):\n        correlation_id = correlation_id\n        cmd = convo.ReadStreamEvents(\n            stream,\n            from_event,\n            max_count,\n            resolve_links,\n            require_master,\n            direction=direction,\n        )\n        result = await self.dispatcher.start_conversation(cmd)\n        return await result",
    "docstring": "Read a range of events from a stream.\n\n        Args:\n            stream: The name of the stream to read\n            direction (optional): Controls whether to read events forward or backward.\n              defaults to Forward.\n            from_event (optional): The first event to read.\n              defaults to the beginning of the stream when direction is forward\n              and the end of the stream if direction is backward.\n            max_count (optional): The maximum number of events to return.\n            resolve_links (optional): True if eventstore should\n                automatically resolve Link Events, otherwise False.\n            required_master (optional): True if this command must be\n                sent direct to the master node, otherwise False.\n            correlation_id (optional): A unique identifer for this command.\n\n        Examples:\n\n            Read 5 events from a stream\n\n            >>> async for event in conn.get(\"my-stream\", max_count=5):\n            >>>     print(event)\n\n\n            Read events 21 to 30\n\n            >>> async for event in conn.get(\"my-stream\", max_count=10, from_event=21):\n            >>>     print(event)\n\n            Read 10 most recent events in reverse order\n\n            >>> async for event in conn.get(\n                        \"my-stream\",\n                        max_count=10,\n                        direction=StreamDirection.Backward\n                    ):\n            >>>     print(event)"
  },
  {
    "code": "def is_link(url, processed, files):\n    if url not in processed:\n        is_file = url.endswith(BAD_TYPES)\n        if is_file:\n            files.add(url)\n            return False\n        return True\n    return False",
    "docstring": "Determine whether or not a link should be crawled\n    A url should not be crawled if it\n        - Is a file\n        - Has already been crawled\n\n    Args:\n        url: str Url to be processed\n        processed: list[str] List of urls that have already been crawled\n\n    Returns:\n        bool If `url` should be crawled"
  },
  {
    "code": "def stream_interactions(self):\n        timestamps = sorted(self.time_to_edge.keys())\n        for t in timestamps:\n            for e in self.time_to_edge[t]:\n                yield (e[0], e[1], e[2], t)",
    "docstring": "Generate a temporal ordered stream of interactions.\n\n\n        Returns\n        -------\n        nd_iter : an iterator\n            The iterator returns a 4-tuples of (node, node, op, timestamp).\n\n        Examples\n        --------\n        >>> G = dn.DynGraph()\n        >>> G.add_path([0,1,2,3], t=0)\n        >>> G.add_path([3,4,5,6], t=1)\n        >>> list(G.stream_interactions())\n        [(0, 1, '+', 0), (1, 2, '+', 0), (2, 3, '+', 0), (3, 4, '+', 1), (4, 5, '+', 1), (5, 6, '+', 1)]"
  },
  {
    "code": "def selecteq(table, field, value, complement=False):\n    return selectop(table, field, value, operator.eq, complement=complement)",
    "docstring": "Select rows where the given field equals the given value."
  },
  {
    "code": "def right_click_specimen_equalarea(self, event):\n        if event.LeftIsDown() or event.ButtonDClick():\n            return\n        elif self.specimen_EA_setting == \"Zoom\":\n            self.specimen_EA_setting = \"Pan\"\n            try:\n                self.toolbar2.pan('off')\n            except TypeError:\n                pass\n        elif self.specimen_EA_setting == \"Pan\":\n            self.specimen_EA_setting = \"Zoom\"\n            try:\n                self.toolbar2.zoom()\n            except TypeError:\n                pass",
    "docstring": "toggles between zoom and pan effects for the specimen equal area on\n        right click\n\n        Parameters\n        ----------\n        event : the wx.MouseEvent that triggered the call of this function\n\n        Alters\n        ------\n        specimen_EA_setting, toolbar2 setting"
  },
  {
    "code": "def shrink_file(in_filepath, api_key=None, out_filepath=None):\n    info = get_shrink_file_info(in_filepath, api_key, out_filepath)\n    write_shrunk_file(info)\n    return info",
    "docstring": "Shrink png file and write it back to a new file\n\n    The default file path replaces \".png\" with \".tiny.png\".\n    returns api_info (including info['ouput']['filepath'])"
  },
  {
    "code": "def listBlockOrigin(self, origin_site_name=\"\",  dataset=\"\", block_name=\"\"):\n        try:\n            return self.dbsBlock.listBlocksOrigin(origin_site_name, dataset, block_name)\n        except dbsException as de:\n            dbsExceptionHandler(de.eCode, de.message, self.logger.exception, de.serverError)\n        except Exception as ex:\n            sError = \"DBSReaderModel/listBlocks. %s\\n. Exception trace: \\n %s\" \\\n                    % (ex, traceback.format_exc())\n            dbsExceptionHandler('dbsException-server-error', dbsExceptionCode['dbsException-server-error'],\n                                self.logger.exception, sError)",
    "docstring": "API to list blocks first generated in origin_site_name.\n\n        :param origin_site_name: Origin Site Name (Optional, No wildcards)\n        :type origin_site_name: str\n        :param dataset: dataset ( No wildcards, either dataset or block name needed)\n        :type dataset: str\n        :param block_name:\n        :type block_name: str\n        :returns: List of dictionaries containing the following keys (create_by, creation_date, open_for_writing, last_modified_by, dataset, block_name, file_count, origin_site_name, last_modification_date, block_size)\n        :rtype: list of dicts"
  },
  {
    "code": "def getMonitorById(self, monitorId):\n        url = self.baseUrl\n        url += \"getMonitors?apiKey=%s&monitors=%s\" % (self.apiKey, monitorId)\n        url += \"&noJsonCallback=1&format=json\"\n        success, response = self.requestApi(url)\n        if success:\n            status = response.get('monitors').get('monitor')[0].get('status')\n            alltimeuptimeratio = response.get('monitors').get('monitor')[0].get('alltimeuptimeratio')\n            return status, alltimeuptimeratio\n        return None, None",
    "docstring": "Returns monitor status and alltimeuptimeratio for a MonitorId."
  },
  {
    "code": "def delete_trigger(self, trigger):\n        assert trigger is not None\n        assert isinstance(trigger.id, str), \"Value must be a string\"\n        status, _ = self.http_client.delete(\n            NAMED_TRIGGER_URI % trigger.id,\n            params={'appid': self.API_key},\n            headers={'Content-Type': 'application/json'})",
    "docstring": "Deletes from the Alert API the trigger record identified by the ID of the provided\n        `pyowm.alertapi30.trigger.Trigger`, along with all related alerts\n\n        :param trigger: the `pyowm.alertapi30.trigger.Trigger` object to be deleted\n        :type trigger: `pyowm.alertapi30.trigger.Trigger`\n        :returns: `None` if deletion is successful, an exception otherwise"
  },
  {
    "code": "def time(hour, minute=0, second=0, microsecond=0):\n    return Time(hour, minute, second, microsecond)",
    "docstring": "Create a new Time instance."
  },
  {
    "code": "def call_after(lag):\n  def decorator(func):\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n      wrapper.timer.cancel()\n      wrapper.timer = threading.Timer(lag, func, args=args, kwargs=kwargs)\n      wrapper.timer.start()\n    wrapper.timer = threading.Timer(0, lambda: None)\n    return wrapper\n  return decorator",
    "docstring": "Parametrized decorator for calling a function after a time ``lag`` given\n  in milliseconds. This cancels simultaneous calls."
  },
  {
    "code": "def flatten(nested, containers=(list, tuple)):\n    flat = list(nested)\n    i = 0\n    while i < len(flat):\n        while isinstance(flat[i], containers):\n            if not flat[i]:\n                flat.pop(i)\n                i -= 1\n                break\n            else:\n                flat[i:i + 1] = (flat[i])\n        i += 1\n    return flat",
    "docstring": "Flatten a nested list in-place and return it."
  },
  {
    "code": "def merge(self, cluster_ids, to=None):\n        if not _is_array_like(cluster_ids):\n            raise ValueError(\"The first argument should be a list or \"\n                             \"an array.\")\n        cluster_ids = sorted(cluster_ids)\n        if not set(cluster_ids) <= set(self.cluster_ids):\n            raise ValueError(\"Some clusters do not exist.\")\n        if to is None:\n            to = self.new_cluster_id()\n        if to < self.new_cluster_id():\n            raise ValueError(\"The new cluster numbers should be higher than \"\n                             \"{0}.\".format(self.new_cluster_id()))\n        spike_ids = _spikes_in_clusters(self.spike_clusters, cluster_ids)\n        up = self._do_merge(spike_ids, cluster_ids, to)\n        undo_state = self.emit('request_undo_state', up)\n        self._undo_stack.add((spike_ids, [to], undo_state))\n        self.emit('cluster', up)\n        return up",
    "docstring": "Merge several clusters to a new cluster.\n\n        Parameters\n        ----------\n\n        cluster_ids : array-like\n            List of clusters to merge.\n        to : integer or None\n            The id of the new cluster. By default, this is `new_cluster_id()`.\n\n        Returns\n        -------\n\n        up : UpdateInfo instance"
  },
  {
    "code": "def roughpage(request, url):\n    if settings.APPEND_SLASH and not url.endswith('/'):\n        return redirect(url + '/', permanent=True)\n    filename = url_to_filename(url)\n    template_filenames = get_backend().prepare_filenames(filename,\n                                                         request=request)\n    root = settings.ROUGHPAGES_TEMPLATE_DIR\n    template_filenames = [os.path.join(root, x) for x in template_filenames]\n    try:\n        t = loader.select_template(template_filenames)\n        return render_roughpage(request, t)\n    except TemplateDoesNotExist:\n        if settings.ROUGHPAGES_RAISE_TEMPLATE_DOES_NOT_EXISTS:\n            raise\n        raise Http404",
    "docstring": "Public interface to the rough page view."
  },
  {
    "code": "def add_columns(tree_view, df_py_dtypes, list_store):\n    tree_view.set_model(list_store)\n    for column_i, (i, dtype_i) in df_py_dtypes[['i', 'dtype']].iterrows():\n        tree_column_i = gtk.TreeViewColumn(column_i)\n        tree_column_i.set_name(column_i)\n        if dtype_i in (int, long):\n            property_name = 'text'\n            cell_renderer_i = gtk.CellRendererSpin()\n        elif dtype_i == float:\n            property_name = 'text'\n            cell_renderer_i = gtk.CellRendererSpin()\n        elif dtype_i in (bool, ):\n            property_name = 'active'\n            cell_renderer_i = gtk.CellRendererToggle()\n        elif dtype_i in (str, ):\n            property_name = 'text'\n            cell_renderer_i = gtk.CellRendererText()\n        else:\n            raise ValueError('No cell renderer for dtype: %s' % dtype_i)\n        cell_renderer_i.set_data('column_i', i)\n        cell_renderer_i.set_data('column', tree_column_i)\n        tree_column_i.pack_start(cell_renderer_i, True)\n        tree_column_i.add_attribute(cell_renderer_i, property_name, i)\n        tree_view.append_column(tree_column_i)",
    "docstring": "Add columns to a `gtk.TreeView` for the types listed in `df_py_dtypes`.\n\n    Args:\n\n        tree_view (gtk.TreeView) : Tree view to append columns to.\n        df_py_dtypes (pandas.DataFrame) : Data frame containing type\n            information for one or more columns in `list_store`.\n        list_store (gtk.ListStore) : Model data.\n\n    Returns:\n\n        None"
  },
  {
    "code": "def erase_devices():\n    server = objects.Server()\n    for controller in server.controllers:\n        drives = [x for x in controller.unassigned_physical_drives\n                  if (x.get_physical_drive_dict().get('erase_status', '')\n                      == 'OK')]\n        if drives:\n            controller.erase_devices(drives)\n    while not has_erase_completed():\n        time.sleep(300)\n    server.refresh()\n    status = {}\n    for controller in server.controllers:\n        drive_status = {x.id: x.erase_status\n                        for x in controller.unassigned_physical_drives}\n        sanitize_supported = controller.properties.get(\n            'Sanitize Erase Supported', 'False')\n        if sanitize_supported == 'False':\n            msg = (\"Drives overwritten with zeros because sanitize erase \"\n                   \"is not supported on the controller.\")\n        else:\n            msg = (\"Sanitize Erase performed on the disks attached to \"\n                   \"the controller.\")\n        drive_status.update({'Summary': msg})\n        status[controller.id] = drive_status\n    return status",
    "docstring": "Erase all the drives on this server.\n\n    This method performs sanitize erase on all the supported physical drives\n    in this server. This erase cannot be performed on logical drives.\n\n    :returns: a dictionary of controllers with drives and the erase status.\n    :raises exception.HPSSAException, if none of the drives support\n        sanitize erase."
  },
  {
    "code": "def subset_bed_by_chrom(in_file, chrom, data, out_dir=None):\n    if out_dir is None:\n        out_dir = os.path.dirname(in_file)\n    base, ext = os.path.splitext(os.path.basename(in_file))\n    out_file = os.path.join(out_dir, \"%s-%s%s\" % (base, chrom, ext))\n    if not utils.file_uptodate(out_file, in_file):\n        with file_transaction(data, out_file) as tx_out_file:\n            _rewrite_bed_with_chrom(in_file, tx_out_file, chrom)\n    return out_file",
    "docstring": "Subset a BED file to only have items from the specified chromosome."
  },
  {
    "code": "def change_password(self, previous, new_password):\n        if not self.verify_password(previous):\n            raise exceptions.Unauthorized('Incorrect password')\n        if len(new_password) < options.min_length_password:\n            msg = ('Passwords must be at least {} characters'\n                   .format(options.min_length_password))\n            raise exceptions.ValidationError(msg)\n        if len(new_password) > options.max_length_password:\n            msg = ('Passwords must be at no more than {} characters'\n                   .format(options.max_length_password))\n            raise exceptions.ValidationError(msg)\n        self.password = self.hash_password(new_password)\n        yield self._save()",
    "docstring": "Change the user's password and save to the database\n\n        :param previous: plain text previous password\n        :param new_password: plain text new password\n        :raises: ValidationError"
  },
  {
    "code": "def add_parser(subparsers, parent_parser):\n    INIT_HELP = \"Initialize DVC in the current directory.\"\n    INIT_DESCRIPTION = (\n        \"Initialize DVC in the current directory. Expects directory\\n\"\n        \"to be a Git repository unless --no-scm option is specified.\"\n    )\n    init_parser = subparsers.add_parser(\n        \"init\",\n        parents=[parent_parser],\n        description=append_doc_link(INIT_DESCRIPTION, \"init\"),\n        help=INIT_HELP,\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n    )\n    init_parser.add_argument(\n        \"--no-scm\",\n        action=\"store_true\",\n        default=False,\n        help=\"Initiate dvc in directory that is \"\n        \"not tracked by any scm tool (e.g. git).\",\n    )\n    init_parser.add_argument(\n        \"-f\",\n        \"--force\",\n        action=\"store_true\",\n        default=False,\n        help=(\n            \"Overwrite existing '.dvc' directory. \"\n            \"This operation removes local cache.\"\n        ),\n    )\n    init_parser.set_defaults(func=CmdInit)",
    "docstring": "Setup parser for `dvc init`."
  },
  {
    "code": "def _isinstance(self, model, raise_error=True):\n        rv = isinstance(model, self.__model__)\n        if not rv and raise_error:\n            raise ValueError('%s is not of type %s' % (model, self.__model__))\n        return rv",
    "docstring": "Checks if the specified model instance matches the class model.\n        By default this method will raise a `ValueError` if the model is not of\n        expected type.\n\n        Args:\n\n            model (Model) : The instance to be type checked\n\n            raise_error (bool) : Flag to specify whether to raise error on\n                type check failure\n\n        Raises:\n\n            ValueError: If `model` is not an instance of the respective Model\n                class"
  },
  {
    "code": "def get_json_log_data(data):\n    log_data = data\n    for param in LOG_HIDDEN_JSON_PARAMS:\n        if param in data['params']:\n            if log_data is data:\n                log_data = copy.deepcopy(data)\n            log_data['params'][param] = \"**********\"\n    return log_data",
    "docstring": "Returns a new `data` dictionary with hidden params\n    for log purpose."
  },
  {
    "code": "def sort_by_name(self):\n        super(JSSObjectList, self).sort(key=lambda k: k.name)",
    "docstring": "Sort list elements by name."
  },
  {
    "code": "def _reconnect_delay(self):\n        if self.RECONNECT_ON_ERROR and self.RECONNECT_DELAYED:\n            if self._reconnect_attempts >= len(self.RECONNECT_DELAYS):\n                return self.RECONNECT_DELAYS[-1]\n            else:\n                return self.RECONNECT_DELAYS[self._reconnect_attempts]\n        else:\n            return 0",
    "docstring": "Calculate reconnection delay."
  },
  {
    "code": "def write_device_config(self, device_config):\n        if not self.capabilities.have_usb_mode(device_config._mode):\n            raise yubikey_base.YubiKeyVersionError(\"USB mode: %02x not supported for %s\" % (device_config._mode, self))\n        return self._device._write_config(device_config, SLOT.DEVICE_CONFIG)",
    "docstring": "Write a DEVICE_CONFIG to the YubiKey NEO."
  },
  {
    "code": "def _configure_nve_member(self, vni, device_id, mcast_group, host_id):\n        host_nve_connections = self._get_switch_nve_info(host_id)\n        for switch_ip in host_nve_connections:\n            if cfg.CONF.ml2_cisco.vxlan_global_config:\n                nve_bindings = nxos_db.get_nve_switch_bindings(switch_ip)\n                if len(nve_bindings) == 1:\n                    LOG.debug(\"Nexus: create NVE interface\")\n                    loopback = self.get_nve_loopback(switch_ip)\n                    self.driver.enable_vxlan_feature(switch_ip,\n                        const.NVE_INT_NUM, loopback)\n            member_bindings = nxos_db.get_nve_vni_switch_bindings(vni,\n                                                                  switch_ip)\n            if len(member_bindings) == 1:\n                LOG.debug(\"Nexus: add member\")\n                self.driver.create_nve_member(switch_ip, const.NVE_INT_NUM,\n                                              vni, mcast_group)",
    "docstring": "Add \"member vni\" configuration to the NVE interface.\n\n        Called during update postcommit port event."
  },
  {
    "code": "def perform_service_validate(\n        self,\n        ticket=None,\n        service_url=None,\n        headers=None,\n        ):\n        url = self._get_service_validate_url(ticket, service_url=service_url)\n        logging.debug('[CAS] ServiceValidate URL: {}'.format(url))\n        return self._perform_cas_call(url, ticket=ticket, headers=headers)",
    "docstring": "Fetch a response from the remote CAS `serviceValidate` endpoint."
  },
  {
    "code": "def get_segment_length(\n    linestring: LineString, p: Point, q: Optional[Point] = None\n) -> float:\n    d_p = linestring.project(p)\n    if q is not None:\n        d_q = linestring.project(q)\n        d = abs(d_p - d_q)\n    else:\n        d = d_p\n    return d",
    "docstring": "Given a Shapely linestring and two Shapely points,\n    project the points onto the linestring, and return the distance\n    along the linestring between the two points.\n    If ``q is None``, then return the distance from the start of the\n    linestring to the projection of ``p``.\n    The distance is measured in the native coordinates of the linestring."
  },
  {
    "code": "def unbind(self, format, *args):\n        return lib.zsock_unbind(self._as_parameter_, format, *args)",
    "docstring": "Unbind a socket from a formatted endpoint.\nReturns 0 if OK, -1 if the endpoint was invalid or the function\nisn't supported."
  },
  {
    "code": "def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.test_info(test)\n        self._call_test_results('addSkip', test, reason)",
    "docstring": "registers a test as skipped\n\n        :param test: test to register\n        :param reason: reason why the test was skipped"
  },
  {
    "code": "def template_exists(template_name):\r\n    try:\r\n        template.loader.get_template(template_name)\r\n        return True\r\n    except template.TemplateDoesNotExist:\r\n        return False",
    "docstring": "Determine if a given template exists so that it can be loaded\r\n    if so, or a default alternative can be used if not."
  },
  {
    "code": "def select_star_cb(self, widget, res_dict):\n        keys = list(res_dict.keys())\n        if len(keys) == 0:\n            self.selected = []\n            self.replot_stars()\n        else:\n            idx = int(keys[0])\n            star = self.starlist[idx]\n            if not self._select_flag:\n                self.mark_selection(star, fromtable=True)\n        return True",
    "docstring": "This method is called when the user selects a star from the table."
  },
  {
    "code": "def _assert_equal_channels(axis):\n    for i0 in axis:\n        for i1 in axis:\n            if not all(i0 == i1):\n                raise ValueError('The channels for all the trials should have '\n                                 'the same labels, in the same order.')",
    "docstring": "check that all the trials have the same channels, in the same order.\n\n    Parameters\n    ----------\n    axis : ndarray of ndarray\n        one of the data axis\n\n    Raises\n    ------"
  },
  {
    "code": "def _wake(self):\n        try:\n            self.transmit_side.write(b(' '))\n        except OSError:\n            e = sys.exc_info()[1]\n            if e.args[0] != errno.EBADF:\n                raise",
    "docstring": "Wake the multiplexer by writing a byte. If Broker is midway through\n        teardown, the FD may already be closed, so ignore EBADF."
  },
  {
    "code": "def nearly_unique(arr, rel_tol=1e-4, verbose=0):\n    results = np.array([arr[0]])\n    for x in arr:\n        if np.abs(results - x).min() > rel_tol:\n            results = np.append(results, x)\n    return results",
    "docstring": "Heuristic method to return the uniques within some precision in a numpy array"
  },
  {
    "code": "def _ParseVSSProcessingOptions(self, options):\n    vss_only = False\n    vss_stores = None\n    self._process_vss = not getattr(options, 'no_vss', False)\n    if self._process_vss:\n      vss_only = getattr(options, 'vss_only', False)\n      vss_stores = getattr(options, 'vss_stores', None)\n    if vss_stores:\n      try:\n        self._ParseVolumeIdentifiersString(vss_stores, prefix='vss')\n      except ValueError:\n        raise errors.BadConfigOption('Unsupported VSS stores')\n    self._vss_only = vss_only\n    self._vss_stores = vss_stores",
    "docstring": "Parses the VSS processing options.\n\n    Args:\n      options (argparse.Namespace): command line arguments.\n\n    Raises:\n      BadConfigOption: if the options are invalid."
  },
  {
    "code": "def podcast_episodes_iter(self, *, device_id=None, page_size=250):\n\t\tif device_id is None:\n\t\t\tdevice_id = self.device_id\n\t\tstart_token = None\n\t\tprev_items = None\n\t\twhile True:\n\t\t\tresponse = self._call(\n\t\t\t\tmc_calls.PodcastEpisode,\n\t\t\t\tdevice_id,\n\t\t\t\tmax_results=page_size,\n\t\t\t\tstart_token=start_token\n\t\t\t)\n\t\t\titems = response.body.get('data', {}).get('items', [])\n\t\t\tif items != prev_items:\n\t\t\t\tyield items\n\t\t\t\tprev_items = items\n\t\t\telse:\n\t\t\t\tbreak\n\t\t\tstart_token = response.body.get('nextPageToken')\n\t\t\tif start_token is None:\n\t\t\t\tbreak",
    "docstring": "Get a paged iterator of podcast episode for all subscribed podcasts.\n\n\t\tParameters:\n\t\t\tdevice_id (str, Optional): A mobile device ID.\n\t\t\t\tDefault: Use ``device_id`` of the :class:`MobileClient` instance.\n\t\t\tpage_size (int, Optional): The maximum number of results per returned page.\n\t\t\t\tMax allowed is ``49995``.\n\t\t\t\tDefault: ``250``\n\n\t\tYields:\n\t\t\tlist: Podcast episode dicts."
  },
  {
    "code": "def state_entry(self, args=None, **kwargs):\n        state = self.state_blank(**kwargs)\n        if not args and state.addr.method.name == 'main' and \\\n                        state.addr.method.params[0] == 'java.lang.String[]':\n            cmd_line_args = SimSootExpr_NewArray.new_array(state, \"java.lang.String\", BVS('argc', 32))\n            cmd_line_args.add_default_value_generator(self.generate_symbolic_cmd_line_arg)\n            args = [SootArgument(cmd_line_args, \"java.lang.String[]\")]\n            state.globals['cmd_line_args'] = cmd_line_args\n        SimEngineSoot.setup_arguments(state, args)\n        return state",
    "docstring": "Create an entry state.\n\n        :param args: List of SootArgument values (optional)."
  },
  {
    "code": "def start_sikuli_process(self, port=None):\n        if port is None or int(port) == 0:\n            port = self._get_free_tcp_port()\n        self.port = port\n        start_retries = 0\n        started = False\n        while start_retries < 5:\n            try:\n                self._start_sikuli_java_process()\n            except RuntimeError as err:\n                print('error........%s' % err)\n                if self.process:\n                    self.process.terminate_process()\n                self.port = self._get_free_tcp_port()\n                start_retries += 1\n                continue\n            started = True\n            break\n        if not started:\n            raise RuntimeError('Start sikuli java process failed!')\n        self.remote = self._connect_remote_library()",
    "docstring": "This keyword is used to start sikuli java process.\n        If library is inited with mode \"OLD\", sikuli java process is started automatically.\n        If library is inited with mode \"NEW\", this keyword should be used.\n\n        :param port: port of sikuli java process, if value is None or 0, a random free port will be used\n        :return: None"
  },
  {
    "code": "def get_queryset(self):\n        query_params = self.request.query_params\n        url_params = self.kwargs\n        queryset_filters = self.get_db_filters(url_params, query_params)\n        db_filters = queryset_filters['db_filters']\n        db_excludes = queryset_filters['db_excludes']\n        queryset = Team.objects.prefetch_related(\n            'players'\n        ).all()\n        return queryset.filter(**db_filters).exclude(**db_excludes)",
    "docstring": "Optionally restricts the queryset by filtering against\n        query parameters in the URL."
  },
  {
    "code": "def on_rule(self, *args):\n        if self.rule is None:\n            return\n        self.rule.connect(self._listen_to_rule)",
    "docstring": "Make sure to update when the rule changes"
  },
  {
    "code": "def next(self):\n        if self.row < self.data.num_instances:\n            index = self.row\n            self.row += 1\n            return self.data.get_instance(index)\n        else:\n            raise StopIteration()",
    "docstring": "Returns the next row from the Instances object.\n\n        :return: the next Instance object\n        :rtype: Instance"
  },
  {
    "code": "def is_code(filename):\n    with open(filename, \"r\") as file:\n        for line in file:\n            if not is_comment(line) \\\n                    and '{' in line:\n                if '${' not in line:\n                    return True\n    return False",
    "docstring": "This function returns True, if  a line of the file contains bracket '{'."
  },
  {
    "code": "def align_and_build_tree(seqs, moltype, best_tree=False, params=None):\n    aln = align_unaligned_seqs(seqs, moltype=moltype, params=params)\n    tree = build_tree_from_alignment(aln, moltype, best_tree, params)\n    return {'Align':aln, 'Tree':tree}",
    "docstring": "Returns an alignment and a tree from Sequences object seqs.\n\n    seqs: a cogent.core.alignment.SequenceCollection object, or data that can\n    be used to build one.\n\n    moltype: cogent.core.moltype.MolType object\n\n    best_tree: if True (default:False), uses a slower but more accurate\n    algorithm to build the tree.\n\n    params: dict of parameters to pass in to the Muscle app controller.\n\n    The result will be a tuple containing a cogent.core.alignment.Alignment\n    and a cogent.core.tree.PhyloNode object (or None for the alignment\n    and/or tree if either fails)."
  },
  {
    "code": "def pause(self):\n        if self.state_machine_manager.active_state_machine_id is None:\n            logger.info(\"'Pause' is not a valid action to initiate state machine execution.\")\n            return\n        if self.state_machine_manager.get_active_state_machine() is not None:\n            self.state_machine_manager.get_active_state_machine().root_state.recursively_pause_states()\n        logger.debug(\"Pause execution ...\")\n        self.set_execution_mode(StateMachineExecutionStatus.PAUSED)",
    "docstring": "Set the execution mode to paused"
  },
  {
    "code": "def list_projects(page_size=200, page_index=0, sort=\"\", q=\"\"):\n    content = list_projects_raw(page_size=page_size, page_index=page_index, sort=sort, q=q)\n    if content:\n        return utils.format_json_list(content)",
    "docstring": "List all Projects"
  },
  {
    "code": "def parse(self, data):\n        graph = self._init_graph()\n        if len(data) != 0:\n            if \"links\" not in data[0]:\n                raise ParserError('Parse error, \"links\" key not found')\n        for node in data:\n            for link in node['links']:\n                cost = (link['txRate'] + link['rxRate']) / 2.0\n                graph.add_edge(node['name'],\n                               link['name'],\n                               weight=cost,\n                               tx_rate=link['txRate'],\n                               rx_rate=link['rxRate'])\n        return graph",
    "docstring": "Converts a BMX6 b6m JSON to a NetworkX Graph object\n        which is then returned."
  },
  {
    "code": "def pop(self, symbol):\n        last_metadata = self.find_one({'symbol': symbol}, sort=[('start_time', pymongo.DESCENDING)])\n        if last_metadata is None:\n            raise NoDataFoundException('No metadata found for symbol {}'.format(symbol))\n        self.find_one_and_delete({'symbol': symbol}, sort=[('start_time', pymongo.DESCENDING)])\n        mongo_retry(self.find_one_and_update)({'symbol': symbol}, {'$unset': {'end_time': ''}},\n                                              sort=[('start_time', pymongo.DESCENDING)])\n        return last_metadata",
    "docstring": "Delete current metadata of `symbol`\n\n        Parameters\n        ----------\n        symbol : `str`\n            symbol name to delete\n\n        Returns\n        -------\n        Deleted metadata"
  },
  {
    "code": "def parse_expmethodresponse(self, tup_tree):\n        raise CIMXMLParseError(\n            _format(\"Internal Error: Parsing support for element {0!A} is not \"\n                    \"implemented\", name(tup_tree)),\n            conn_id=self.conn_id)",
    "docstring": "This function not implemented."
  },
  {
    "code": "def bias_correct(params, data, acf=None):\n    bias = RB_bias(data, params, acf=acf)\n    i = 0\n    for p in params:\n        if 'theta' in p:\n            continue\n        if params[p].vary:\n            params[p].value -= bias[i]\n            i += 1\n    return",
    "docstring": "Calculate and apply a bias correction to the given fit parameters\n\n\n    Parameters\n    ----------\n    params : lmfit.Parameters\n        The model parameters. These will be modified.\n\n    data : 2d-array\n        The data which was used in the fitting\n\n    acf : 2d-array\n        ACF of the data. Default = None.\n\n    Returns\n    -------\n    None\n\n    See Also\n    --------\n    :func:`AegeanTools.fitting.RB_bias`"
  },
  {
    "code": "def LocalPathToCanonicalPath(path):\n  path_components = path.split(\"/\")\n  result = []\n  for component in path_components:\n    m = re.match(r\"\\\\\\\\.\\\\\", component)\n    if not m:\n      component = component.replace(\"\\\\\", \"/\")\n    result.append(component)\n  return utils.JoinPath(*result)",
    "docstring": "Converts path from the local system's convention to the canonical."
  },
  {
    "code": "def receive_pong(self, pong: Pong):\n        message_id = ('ping', pong.nonce, pong.sender)\n        async_result = self.messageids_to_asyncresults.get(message_id)\n        if async_result is not None:\n            self.log_healthcheck.debug(\n                'Pong received',\n                sender=pex(pong.sender),\n                message_id=pong.nonce,\n            )\n            async_result.set(True)\n        else:\n            self.log_healthcheck.warn(\n                'Unknown pong received',\n                message_id=message_id,\n            )",
    "docstring": "Handles a Pong message."
  },
  {
    "code": "def getProcList(self, fields=('pid', 'user', 'cmd',), threads=False,\n                    **kwargs):\n        field_list = list(fields)\n        for key in kwargs:\n            col = re.sub('(_ic)?(_regex)?$', '', key)\n            if not col in field_list:\n                field_list.append(col)\n        pinfo = self.parseProcCmd(field_list, threads)\n        if pinfo:\n            if len(kwargs) > 0:\n                pfilter = util.TableFilter()\n                pfilter.registerFilters(**kwargs)\n                stats = pfilter.applyFilters(pinfo['headers'], pinfo['stats'])\n                return {'headers': pinfo['headers'], 'stats': stats}\n            else:\n                return pinfo\n        else:\n            return None",
    "docstring": "Execute ps command with custom output format with columns columns \n        from fields, select lines using the filters defined by kwargs and return \n        result as a nested list.\n        \n        The Standard Format Specifiers from ps man page must be used for the\n        fields parameter.\n        \n        @param fields:   Fields included in the output.\n                         Default: pid, user, cmd\n        @param threads:  If True, include threads in output.\n        @param **kwargs: Keyword variables are used for filtering the results\n                         depending on the values of the columns. Each keyword \n                         must correspond to a field name with an optional \n                         suffix:\n                         field:          Field equal to value or in list of \n                                         values.\n                         field_ic:       Field equal to value or in list of \n                                         values, using case insensitive \n                                         comparison.\n                         field_regex:    Field matches regex value or matches\n                                         with any regex in list of values.\n                         field_ic_regex: Field matches regex value or matches\n                                         with any regex in list of values \n                                         using case insensitive match.                                  \n        @return:         List of headers and list of rows and columns."
  },
  {
    "code": "def wait_until_element_present(self, element, timeout=None):\n        return self._wait_until(self._expected_condition_find_element, element, timeout)",
    "docstring": "Search element and wait until it is found\n\n        :param element: PageElement or element locator as a tuple (locator_type, locator_value) to be found\n        :param timeout: max time to wait\n        :returns: the web element if it is present\n        :rtype: selenium.webdriver.remote.webelement.WebElement or appium.webdriver.webelement.WebElement\n        :raises TimeoutException: If the element is not found after the timeout"
  },
  {
    "code": "def get(cls, reactor, source='graphite', **options):\n        acls = cls.alerts[source]\n        return acls(reactor, **options)",
    "docstring": "Get Alert Class by source."
  },
  {
    "code": "def print_help(self, prog_name, subcommand):\n        parser = self.get_parser(prog_name, subcommand)\n        parser.print_help()",
    "docstring": "Prints parser's help.\n\n        :param prog_name: vcs main script name\n        :param subcommand: command name"
  },
  {
    "code": "def _checkResponseWriteData(payload, writedata):\n    _checkString(payload, minlength=4, description='payload')\n    _checkString(writedata, minlength=2, maxlength=2, description='writedata')\n    BYTERANGE_FOR_WRITEDATA = slice(2, 4)\n    receivedWritedata = payload[BYTERANGE_FOR_WRITEDATA]\n    if receivedWritedata != writedata:\n        raise ValueError('Wrong write data in the response: {0!r}, but commanded is {1!r}. The data payload is: {2!r}'.format( \\\n            receivedWritedata, writedata, payload))",
    "docstring": "Check that the write data as given in the response is correct.\n\n    The bytes 2 and 3 (zero based counting) in the payload holds the write data.\n\n    Args:\n        * payload (string): The payload\n        * writedata (string): The data to write, length should be 2 bytes.\n\n    Raises:\n        TypeError, ValueError"
  },
  {
    "code": "def combine_pyramid_and_save(g_video, orig_video, enlarge_multiple, fps, save_filename='media/output.avi'):\n    width, height = get_frame_dimensions(orig_video[0])\n    fourcc = cv2.VideoWriter_fourcc(*'MJPG')\n    print(\"Outputting to %s\" % save_filename)\n    writer = cv2.VideoWriter(save_filename, fourcc, fps, (width, height), 1)\n    for x in range(0, g_video.shape[0]):\n        img = np.ndarray(shape=g_video[x].shape, dtype='float')\n        img[:] = g_video[x]\n        for i in range(enlarge_multiple):\n            img = cv2.pyrUp(img)\n        img[:height, :width] = img[:height, :width] + orig_video[x]\n        res = cv2.convertScaleAbs(img[:height, :width])\n        writer.write(res)",
    "docstring": "Combine a gaussian video representation with the original and save to file"
  },
  {
    "code": "def read_interfaces(path: str) -> Interfaces:\n\twith open(path, encoding='utf-8') as f:\n\t\treturn json.load(f)",
    "docstring": "Reads an Interfaces JSON file at the given path and returns it as a dictionary."
  },
  {
    "code": "def validate_confusables_email(value):\n    if '@' not in value:\n        return\n    local_part, domain = value.split('@')\n    if confusables.is_dangerous(local_part) or \\\n       confusables.is_dangerous(domain):\n        raise ValidationError(CONFUSABLE_EMAIL, code='invalid')",
    "docstring": "Validator which disallows 'dangerous' email addresses likely to\n    represent homograph attacks.\n\n    An email address is 'dangerous' if either the local-part or the\n    domain, considered on their own, are mixed-script and contain one\n    or more characters appearing in the Unicode Visually Confusable\n    Characters file."
  },
  {
    "code": "def get_shots(self):\n        shots = self.response.json()['resultSets'][0]['rowSet']\n        headers = self.response.json()['resultSets'][0]['headers']\n        return pd.DataFrame(shots, columns=headers)",
    "docstring": "Returns the shot chart data as a pandas DataFrame."
  },
  {
    "code": "def write_to_cache(self, data, filename):\n        json_data = json.dumps(data, sort_keys=True, indent=2)\n        cache = open(filename, 'w')\n        cache.write(json_data)\n        cache.close()",
    "docstring": "Writes data in JSON format to a file"
  },
  {
    "code": "def _get_name_map(saltenv='base'):\n    u_name_map = {}\n    name_map = get_repo_data(saltenv).get('name_map', {})\n    if not six.PY2:\n        return name_map\n    for k in name_map:\n        u_name_map[k] = name_map[k]\n    return u_name_map",
    "docstring": "Return a reverse map of full pkg names to the names recognized by winrepo."
  },
  {
    "code": "def contribute_to_class(self, cls, name):\n        super(StateField, self).contribute_to_class(cls, name)\n        parent_property = getattr(cls, self.name, None)\n        setattr(cls, self.name, StateFieldProperty(self, parent_property))",
    "docstring": "Contribute the state to a Model.\n\n        Attaches a StateFieldProperty to wrap the attribute."
  },
  {
    "code": "def total_accessibility(in_rsa, path=True):\n    if path:\n        with open(in_rsa, 'r') as inf:\n            rsa = inf.read()\n    else:\n        rsa = in_rsa[:]\n    all_atoms, side_chains, main_chain, non_polar, polar = [\n        float(x) for x in rsa.splitlines()[-1].split()[1:]]\n    return all_atoms, side_chains, main_chain, non_polar, polar",
    "docstring": "Parses rsa file for the total surface accessibility data.\n\n    Parameters\n    ----------\n    in_rsa : str\n        Path to naccess rsa file.\n    path : bool\n        Indicates if in_rsa is a path or a string.\n\n    Returns\n    -------\n    dssp_residues : 5-tuple(float)\n        Total accessibility values for:\n        [0] all atoms\n        [1] all side-chain atoms\n        [2] all main-chain atoms\n        [3] all non-polar atoms\n        [4] all polar atoms"
  },
  {
    "code": "def submit(ctx_name, parent_id, name, url, func, *args, **kwargs):\n    if isinstance(ctx_name, Context):\n        ctx = ctx_name\n    else:\n        ctx = ctxs.get(ctx_name, ctxs[ctx_default])\n    return _submit(ctx, parent_id, name, url, func, *args, **kwargs)",
    "docstring": "Submit through a context\n\n    Parameters\n    ----------\n    ctx_name : str\n        The name of the context to submit through\n    parent_id : str\n        The ID of the group that the job is a part of.\n    name : str\n        The name of the job\n    url : str\n        The handler that can take the results (e.g., /beta_diversity/)\n    func : function\n        The function to execute. Any returns from this function will be\n        serialized and deposited into Redis using the uuid for a key. This\n        function should raise if the method fails.\n    args : tuple or None\n        Any args for ``func``\n    kwargs : dict or None\n        Any kwargs for ``func``\n\n    Returns\n    -------\n    tuple, (str, str, AsyncResult)\n        The job ID, parent ID and the IPython's AsyncResult object of the job"
  },
  {
    "code": "def get_connection_cls(cls):\n        if cls.__connection_cls is None:\n            cls.__connection_cls, _ = cls.from_settings()\n        return cls.__connection_cls",
    "docstring": "Return connection class.\n\n        :rtype: :class:`type`"
  },
  {
    "code": "def _find_relation_factory(module):\n    if not module:\n        return None\n    candidates = [o for o in (getattr(module, attr) for attr in dir(module))\n                  if (o is not RelationFactory and\n                      o is not RelationBase and\n                      isclass(o) and\n                      issubclass(o, RelationFactory))]\n    candidates = [c1 for c1 in candidates\n                  if not any(issubclass(c2, c1) for c2 in candidates\n                             if c1 is not c2)]\n    if not candidates:\n        hookenv.log('No RelationFactory found in {}'.format(module.__name__),\n                    hookenv.WARNING)\n        return None\n    if len(candidates) > 1:\n        raise RuntimeError('Too many RelationFactory found in {}'\n                           ''.format(module.__name__))\n    return candidates[0]",
    "docstring": "Attempt to find a RelationFactory subclass in the module.\n\n    Note: RelationFactory and RelationBase are ignored so they may\n    be imported to be used as base classes without fear."
  },
  {
    "code": "def DbGetPropertyHist(self, argin):\n        self._log.debug(\"In DbGetPropertyHist()\")\n        object_name = argin[0]\n        prop_name = argin[1]\n        return self.db.get_property_hist(object_name, prop_name)",
    "docstring": "Retrieve object  property history\n\n        :param argin: Str[0] = Object name\n        Str[2] = Property name\n        :type: tango.DevVarStringArray\n        :return: Str[0] = Property name\n        Str[1] = date\n        Str[2] = Property value number (array case)\n        Str[3] = Property value 1\n        Str[n] = Property value n\n        :rtype: tango.DevVarStringArray"
  },
  {
    "code": "def trace_set_format(self, fmt):\n        cmd = enums.JLinkTraceCommand.SET_FORMAT\n        data = ctypes.c_uint32(fmt)\n        res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data))\n        if (res == 1):\n            raise errors.JLinkException('Failed to set trace format.')\n        return None",
    "docstring": "Sets the format for the trace buffer to use.\n\n        Args:\n          self (JLink): the ``JLink`` instance.\n          fmt (int): format for the trace buffer; this is one of the attributes\n            of ``JLinkTraceFormat``.\n\n        Returns:\n          ``None``"
  },
  {
    "code": "def clear_errors():\n    data = []\n    data.append(0x0B)\n    data.append(BROADCAST_ID)\n    data.append(RAM_WRITE_REQ)\n    data.append(STATUS_ERROR_RAM)\n    data.append(BYTE2)\n    data.append(0x00)\n    data.append(0x00)\n    send_data(data)",
    "docstring": "Clears the errors register of all Herkulex servos\n\n    Args:\n        none"
  },
  {
    "code": "def OnGetItemText(self, item, col):\n        try:\n            column = self.columns[col]\n            value = column.get(self.sorted[item])\n        except IndexError, err:\n            return None\n        else:\n            if value is None:\n                return u''\n            if column.percentPossible and self.percentageView and self.total:\n                value = value / float(self.total) * 100.00\n            if column.format:\n                try:\n                    return column.format % (value,)\n                except Exception, err:\n                    log.warn('Column %s could not format %r value: %r',\n                        column.name, type(value), value\n                    )\n                    value = column.get(self.sorted[item] )\n                    if isinstance(value,(unicode,str)):\n                        return value\n                    return unicode(value)\n            else:\n                if isinstance(value,(unicode,str)):\n                    return value\n                return unicode(value)",
    "docstring": "Retrieve text for the item and column respectively"
  },
  {
    "code": "def _insert_html_configs(c, *, project_name, short_project_name):\n    c['templates_path'] = [\n        '_templates',\n        lsst_sphinx_bootstrap_theme.get_html_templates_path()]\n    c['html_theme'] = 'lsst_sphinx_bootstrap_theme'\n    c['html_theme_path'] = [lsst_sphinx_bootstrap_theme.get_html_theme_path()]\n    c['html_theme_options'] = {'logotext': short_project_name}\n    c['html_title'] = project_name\n    c['html_short_title'] = short_project_name\n    c['html_logo'] = None\n    c['html_favicon'] = None\n    if os.path.isdir('_static'):\n        c['html_static_path'] = ['_static']\n    else:\n        c['html_static_path'] = []\n    c['html_last_updated_fmt'] = '%b %d, %Y'\n    c['html_use_smartypants'] = True\n    c['html_domain_indices'] = False\n    c['html_use_index'] = False\n    c['html_split_index'] = False\n    c['html_show_sourcelink'] = True\n    c['html_show_sphinx'] = True\n    c['html_show_copyright'] = True\n    c['html_file_suffix'] = '.html'\n    c['html_search_language'] = 'en'\n    return c",
    "docstring": "Insert HTML theme configurations."
  },
  {
    "code": "def memory(self):\n        if self._memory is not None:\n            return self._memory\n        elif self._config is not None:\n            return self._config.defaultMemory\n        else:\n            raise AttributeError(\"Default value for 'memory' cannot be determined\")",
    "docstring": "The maximum number of bytes of memory the job will require to run."
  },
  {
    "code": "async def cli(self):\n        print('Enter commands and press enter')\n        print('Type help for help and exit to quit')\n        while True:\n            command = await _read_input(self.loop, 'pyatv> ')\n            if command.lower() == 'exit':\n                break\n            elif command == 'cli':\n                print('Command not availble here')\n                continue\n            await _handle_device_command(\n                self.args, command, self.atv, self.loop)",
    "docstring": "Enter commands in a simple CLI."
  },
  {
    "code": "def Mx(mt, x):\n    n = len(mt.Cx)\n    sum1 = 0\n    for j in range(x, n):\n        k = mt.Cx[j]\n        sum1 += k\n    return sum1",
    "docstring": "Return the Mx"
  },
  {
    "code": "def LMLgrad(self,params=None):\n        if params is not None:\n            self.setParams(params)\n        KV = self._update_cache()\n        W = KV['W']\n        LMLgrad = SP.zeros(self.covar.n_params)\n        for i in range(self.covar.n_params):\n            Kd = self.covar.Kgrad_param(i)\n            LMLgrad[i] = 0.5 * (W*Kd).sum()\n        return {'covar':LMLgrad}",
    "docstring": "evaluates the gradient of the log marginal likelihood for the given hyperparameters"
  },
  {
    "code": "def save_hdf(self,filename,path=''):\n        self.orbpop_long.save_hdf(filename,'{}/long'.format(path))\n        self.orbpop_short.save_hdf(filename,'{}/short'.format(path))",
    "docstring": "Save to .h5 file."
  },
  {
    "code": "def jtag_send(self, tms, tdi, num_bits):\n        if not util.is_natural(num_bits) or num_bits <= 0 or num_bits > 32:\n            raise ValueError('Number of bits must be >= 1 and <= 32.')\n        self._dll.JLINKARM_StoreBits(tms, tdi, num_bits)\n        return None",
    "docstring": "Sends data via JTAG.\n\n        Sends data via JTAG on the rising clock edge, TCK.  At on each rising\n        clock edge, on bit is transferred in from TDI and out to TDO.  The\n        clock uses the TMS to step through the standard JTAG state machine.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          tms (int): used to determine the state transitions for the Test\n            Access Port (TAP) controller from its current state\n          tdi (int): input data to be transferred in from TDI to TDO\n          num_bits (int): a number in the range ``[1, 32]`` inclusively\n            specifying the number of meaningful bits in the ``tms`` and\n            ``tdi`` parameters for the purpose of extracting state and data\n            information\n\n        Returns:\n          ``None``\n\n        Raises:\n          ValueError: if ``num_bits < 1`` or ``num_bits > 32``.\n\n        See Also:\n          `JTAG Technical Overview <https://www.xjtag.com/about-jtag/jtag-a-technical-overview>`_."
  },
  {
    "code": "def _setup_firefox(self, capabilities):\n        if capabilities.get(\"marionette\"):\n            gecko_driver = self.config.get('Driver', 'gecko_driver_path')\n            self.logger.debug(\"Gecko driver path given in properties: %s\", gecko_driver)\n        else:\n            gecko_driver = None\n        firefox_binary = self.config.get_optional('Firefox', 'binary')\n        firefox_options = Options()\n        if self.config.getboolean_optional('Driver', 'headless'):\n            self.logger.debug(\"Running Firefox in headless mode\")\n            firefox_options.add_argument('-headless')\n        self._add_firefox_arguments(firefox_options)\n        if firefox_binary:\n            firefox_options.binary = firefox_binary\n        log_path = os.path.join(DriverWrappersPool.output_directory, 'geckodriver.log')\n        try:\n            return webdriver.Firefox(firefox_profile=self._create_firefox_profile(), capabilities=capabilities,\n                                     executable_path=gecko_driver, firefox_options=firefox_options, log_path=log_path)\n        except TypeError:\n            return webdriver.Firefox(firefox_profile=self._create_firefox_profile(), capabilities=capabilities,\n                                     executable_path=gecko_driver, firefox_options=firefox_options)",
    "docstring": "Setup Firefox webdriver\n\n        :param capabilities: capabilities object\n        :returns: a new local Firefox driver"
  },
  {
    "code": "def _find_protocol_error(tb, proto_name):\n    tb_info = traceback.extract_tb(tb)\n    for frame in reversed(tb_info):\n        if frame.filename == proto_name:\n            return frame\n    else:\n        raise KeyError",
    "docstring": "Return the FrameInfo for the lowest frame in the traceback from the\n    protocol."
  },
  {
    "code": "async def connect(url, *, apikey=None, insecure=False):\n    url = api_url(url)\n    url = urlparse(url)\n    if url.username is not None:\n        raise ConnectError(\n            \"Cannot provide user-name explicitly in URL (%r) when connecting; \"\n            \"use login instead.\" % url.username)\n    if url.password is not None:\n        raise ConnectError(\n            \"Cannot provide password explicitly in URL (%r) when connecting; \"\n            \"use login instead.\" % url.username)\n    if apikey is None:\n        credentials = None\n    else:\n        credentials = Credentials.parse(apikey)\n    description = await fetch_api_description(url, insecure)\n    return Profile(\n        name=url.netloc, url=url.geturl(), credentials=credentials,\n        description=description)",
    "docstring": "Connect to a remote MAAS instance with `apikey`.\n\n    Returns a new :class:`Profile` which has NOT been saved. To connect AND\n    save a new profile::\n\n        profile = connect(url, apikey=apikey)\n        profile = profile.replace(name=\"mad-hatter\")\n\n        with profiles.ProfileStore.open() as config:\n            config.save(profile)\n            # Optionally, set it as the default.\n            config.default = profile.name"
  },
  {
    "code": "def write_int32(self, value, little_endian=True):\n        if little_endian:\n            endian = \"<\"\n        else:\n            endian = \">\"\n        return self.pack('%si' % endian, value)",
    "docstring": "Pack the value as a signed integer and write 4 bytes to the stream.\n\n        Args:\n            value:\n            little_endian (bool): specify the endianness. (Default) Little endian.\n\n        Returns:\n            int: the number of bytes written."
  },
  {
    "code": "def ikev2scan(ip, **kwargs):\n    return sr(IP(dst=ip) / UDP() / IKEv2(init_SPI=RandString(8),\n                                         exch_type=34) / IKEv2_payload_SA(prop=IKEv2_payload_Proposal()), **kwargs)",
    "docstring": "Send a IKEv2 SA to an IP and wait for answers."
  },
  {
    "code": "def resume(self, container_id=None, sudo=None):\n    return self._state_command(container_id, command='resume', sudo=sudo)",
    "docstring": "resume a stopped OciImage container, if it exists\n\n        Equivalent command line example:      \n           singularity oci resume <container_ID>\n           \n        Parameters\n        ==========\n        container_id: the id to stop.\n        sudo: Add sudo to the command. If the container was created by root,\n              you need sudo to interact and get its state.\n\n        Returns\n        =======\n        return_code: the return code to indicate if the container was resumed."
  },
  {
    "code": "def get_meta_graph_copy(self, tags=None):\n    meta_graph = self.get_meta_graph(tags)\n    copy = tf_v1.MetaGraphDef()\n    copy.CopyFrom(meta_graph)\n    return copy",
    "docstring": "Returns a copy of a MetaGraph with the identical set of tags."
  },
  {
    "code": "def decompress_file(filepath):\n    toks = filepath.split(\".\")\n    file_ext = toks[-1].upper()\n    from monty.io import zopen\n    if file_ext in [\"BZ2\", \"GZ\", \"Z\"]:\n        with open(\".\".join(toks[0:-1]), 'wb') as f_out, \\\n                zopen(filepath, 'rb') as f_in:\n            f_out.writelines(f_in)\n        os.remove(filepath)",
    "docstring": "Decompresses a file with the correct extension. Automatically detects\n    gz, bz2 or z extension.\n\n    Args:\n        filepath (str): Path to file.\n        compression (str): A compression mode. Valid options are \"gz\" or\n            \"bz2\". Defaults to \"gz\"."
  },
  {
    "code": "def len2dlc(length):\n    if length <= 8:\n        return length\n    for dlc, nof_bytes in enumerate(CAN_FD_DLC):\n        if nof_bytes >= length:\n            return dlc\n    return 15",
    "docstring": "Calculate the DLC from data length.\n\n    :param int length: Length in number of bytes (0-64)\n\n    :returns: DLC (0-15)\n    :rtype: int"
  },
  {
    "code": "def _traverse_report(data):\n    if 'items' not in data:\n        return {}\n    out = {}\n    for item in data['items']:\n        skip = (item['severity'] == 'NonDisplay' or\n                item['itemKey'] == 'categoryDesc' or\n                item['value'] in [None, 'Null', 'N/A', 'NULL'])\n        if skip:\n            continue\n        value = 'Ok' if item['value'] == '0.0' else item['value']\n        out[item['itemKey']] = value\n        out.update(_traverse_report(item))\n    return out",
    "docstring": "Recursively traverse vehicle health report."
  },
  {
    "code": "def temperature(self):\n        result = self.i2c_read(2)\n        value = struct.unpack('>H', result)[0]\n        if value < 32768:\n            return value / 256.0\n        else:\n            return (value - 65536) / 256.0",
    "docstring": "Get the temperature in degree celcius"
  },
  {
    "code": "async def open_wallet_search(wallet_handle: int,\n                             type_: str,\n                             query_json: str,\n                             options_json: str) -> int:\n    logger = logging.getLogger(__name__)\n    logger.debug(\"open_wallet_search: >>> wallet_handle: %r, type_: %r, query_json: %r, options_json: %r\",\n                 wallet_handle,\n                 type_,\n                 query_json,\n                 options_json)\n    if not hasattr(open_wallet_search, \"cb\"):\n        logger.debug(\"open_wallet_search: Creating callback\")\n        open_wallet_search.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_int32))\n    c_wallet_handle = c_int32(wallet_handle)\n    c_type = c_char_p(type_.encode('utf-8'))\n    c_query_json = c_char_p(query_json.encode('utf-8'))\n    c_options_json = c_char_p(options_json.encode('utf-8'))\n    search_handle = await do_call('indy_open_wallet_search',\n                                  c_wallet_handle,\n                                  c_type,\n                                  c_query_json,\n                                  c_options_json,\n                                  open_wallet_search.cb)\n    res = search_handle\n    logger.debug(\"open_wallet_search: <<< res: %r\", res)\n    return res",
    "docstring": "Search for wallet records\n\n    :param wallet_handle: wallet handler (created by open_wallet).\n    :param type_: allows to separate different record types collections\n    :param query_json: MongoDB style query to wallet record tags:\n      {\n        \"tagName\": \"tagValue\",\n        $or: {\n          \"tagName2\": { $regex: 'pattern' },\n          \"tagName3\": { $gte: '123' },\n        },\n      }\n    :param options_json: //TODO: FIXME: Think about replacing by bitmask\n      {\n        retrieveRecords: (optional, true by default) If false only \"counts\" will be calculated,\n        retrieveTotalCount: (optional, false by default) Calculate total count,\n        retrieveType: (optional, false by default) Retrieve record type,\n        retrieveValue: (optional, true by default) Retrieve record value,\n        retrieveTags: (optional, true by default) Retrieve record tags,\n      }\n    :return: search_handle: Wallet search handle that can be used later\n             to fetch records by small batches (with fetch_wallet_search_next_records)"
  },
  {
    "code": "def parse(path):\n    doc = ET.parse(path).getroot()\n    channel = doc.find(\"./channel\")\n    blog = _parse_blog(channel)\n    authors = _parse_authors(channel)\n    categories = _parse_categories(channel)\n    tags = _parse_tags(channel)\n    posts = _parse_posts(channel)\n    return {\n        \"blog\": blog,\n        \"authors\": authors,\n        \"categories\": categories,\n        \"tags\": tags,\n        \"posts\": posts,\n    }",
    "docstring": "Parses xml and returns a formatted dict.\n\n    Example:\n\n        wpparser.parse(\"./blog.wordpress.2014-09-26.xml\")\n\n    Will return:\n\n        {\n        \"blog\": {\n            \"tagline\": \"Tagline\",\n            \"site_url\": \"http://marteinn.se/blog\",\n            \"blog_url\": \"http://marteinn.se/blog\",\n            \"language\": \"en-US\",\n            \"title\": \"Marteinn / Blog\"\n        },\n        \"authors: [{\n            \"login\": \"admin\",\n            \"last_name\": None,\n            \"display_name\": \"admin\",\n            \"email\": \"martin@marteinn.se\",\n            \"first_name\": None}\n        ],\n        \"categories\": [{\n            \"parent\": None,\n            \"term_id\": \"3\",\n            \"name\": \"Action Script\",\n            \"nicename\": \"action-script\",\n            \"children\": [{\n                \"parent\": \"action-script\",\n                \"term_id\": \"20\",\n                \"name\": \"Flash related\",\n                \"nicename\": \"flash-related\",\n                \"children\": []\n            }]\n        }],\n        \"tags\": [{\"term_id\": \"36\", \"slug\": \"bash\", \"name\": \"Bash\"}],\n        \"posts\": [{\n            \"creator\": \"admin\",\n            \"excerpt\": None,\n            \"post_date_gmt\": \"2014-09-22 20:10:40\",\n            \"post_date\": \"2014-09-22 21:10:40\",\n            \"post_type\": \"post\",\n            \"menu_order\": \"0\",\n            \"guid\": \"http://marteinn.se/blog/?p=828\",\n            \"title\": \"Post Title\",\n            \"comments\": [{\n                \"date_gmt\": \"2014-09-24 23:08:31\",\n                \"parent\": \"0\",\n                \"date\": \"2014-09-25 00:08:31\",\n                \"id\": \"85929\",\n                \"user_id\": \"0\",\n                \"author\": u\"Author\",\n                \"author_email\": None,\n                \"author_ip\": \"111.111.111.111\",\n                \"approved\": \"1\",\n                \"content\": u\"Comment title\",\n                \"author_url\": \"http://example.com\",\n                \"type\": \"pingback\"\n            }],\n            \"content\": \"Text\",\n            \"post_parent\": \"0\",\n            \"post_password\": None,\n            \"status\": \"publish\",\n            \"description\": None,\n            \"tags\": [\"tag\"],\n            \"ping_status\": \"open\",\n            \"post_id\": \"828\",\n            \"link\": \"http://www.marteinn.se/blog/slug/\",\n            \"pub_date\": \"Mon, 22 Sep 2014 20:10:40 +0000\",\n            \"categories\": [\"category\"],\n            \"is_sticky\": \"0\",\n            \"post_name\": \"slug\"\n        }]\n        }"
  },
  {
    "code": "def parse_url_rules(urls_fp):\n    url_rules = []\n    for line in urls_fp:\n        re_url = line.strip()\n        if re_url:\n            url_rules.append({'str': re_url, 're': re.compile(re_url)})\n    return url_rules",
    "docstring": "URL rules from given fp"
  },
  {
    "code": "def sample_counters(mc, system_info):\n    return {\n        (x, y): mc.get_router_diagnostics(x, y) for (x, y) in system_info\n    }",
    "docstring": "Sample every router counter in the machine."
  },
  {
    "code": "def Set(self, name, initial=None):\n        return types.Set(name, self.api, initial)",
    "docstring": "The set datatype.\n\n        :param name: The name of the set.\n        :keyword initial: Initial members of the set.\n\n        See :class:`redish.types.Set`."
  },
  {
    "code": "def check_wide_data_for_blank_choices(choice_col, wide_data):\n    if wide_data[choice_col].isnull().any():\n        msg_1 = \"One or more of the values in wide_data[choice_col] is null.\"\n        msg_2 = \" Remove null values in the choice column or fill them in.\"\n        raise ValueError(msg_1 + msg_2)\n    return None",
    "docstring": "Checks `wide_data` for null values in the choice column, and raises a\n    helpful ValueError if null values are found.\n\n    Parameters\n    ----------\n    choice_col : str.\n        Denotes the column in `wide_data` that is used to record each\n        observation's choice.\n    wide_data : pandas dataframe.\n        Contains one row for each observation. Should contain `choice_col`.\n\n    Returns\n    -------\n    None."
  },
  {
    "code": "def safe_mkdir(directory, clean=False):\n  if clean:\n    safe_rmtree(directory)\n  try:\n    os.makedirs(directory)\n  except OSError as e:\n    if e.errno != errno.EEXIST:\n      raise",
    "docstring": "Safely create a directory.\n\n  Ensures a directory is present.  If it's not there, it is created.  If it\n  is, it's a no-op. If clean is True, ensures the directory is empty."
  },
  {
    "code": "def loadJSON(self, jdata):\n        self.__name = jdata['name']\n        self.__field = jdata['field']\n        self.__display = jdata.get('display') or self.__display\n        self.__flags = jdata.get('flags') or self.__flags\n        self.__defaultOrder = jdata.get('defaultOrder') or self.__defaultOrder\n        self.__default = jdata.get('default') or self.__default",
    "docstring": "Initializes the information for this class from the given JSON data blob.\n\n        :param jdata: <dict>"
  },
  {
    "code": "def define_page_breakpoint(self, dwProcessId, address,       pages = 1,\n                                                             condition = True,\n                                                                action = None):\n        process = self.system.get_process(dwProcessId)\n        bp      = PageBreakpoint(address, pages, condition, action)\n        begin   = bp.get_address()\n        end     = begin + bp.get_size()\n        address  = begin\n        pageSize = MemoryAddresses.pageSize\n        while address < end:\n            key = (dwProcessId, address)\n            if key in self.__pageBP:\n                msg = \"Already exists (PID %d) : %r\"\n                msg = msg % (dwProcessId, self.__pageBP[key])\n                raise KeyError(msg)\n            address = address + pageSize\n        address = begin\n        while address < end:\n            key = (dwProcessId, address)\n            self.__pageBP[key] = bp\n            address = address + pageSize\n        return bp",
    "docstring": "Creates a disabled page breakpoint at the given address.\n\n        @see:\n            L{has_page_breakpoint},\n            L{get_page_breakpoint},\n            L{enable_page_breakpoint},\n            L{enable_one_shot_page_breakpoint},\n            L{disable_page_breakpoint},\n            L{erase_page_breakpoint}\n\n        @type  dwProcessId: int\n        @param dwProcessId: Process global ID.\n\n        @type  address: int\n        @param address: Memory address of the first page to watch.\n\n        @type  pages: int\n        @param pages: Number of pages to watch.\n\n        @type  condition: function\n        @param condition: (Optional) Condition callback function.\n\n            The callback signature is::\n\n                def condition_callback(event):\n                    return True     # returns True or False\n\n            Where B{event} is an L{Event} object,\n            and the return value is a boolean\n            (C{True} to dispatch the event, C{False} otherwise).\n\n        @type  action: function\n        @param action: (Optional) Action callback function.\n            If specified, the event is handled by this callback instead of\n            being dispatched normally.\n\n            The callback signature is::\n\n                def action_callback(event):\n                    pass        # no return value\n\n            Where B{event} is an L{Event} object,\n            and the return value is a boolean\n            (C{True} to dispatch the event, C{False} otherwise).\n\n        @rtype:  L{PageBreakpoint}\n        @return: The page breakpoint object."
  },
  {
    "code": "def deleteRole(self, roleID):\n        url = self._url + \"/%s/delete\" % roleID\n        params = {\n            \"f\" : \"json\"\n        }\n        return self._post(url=url,\n                             param_dict=params,\n                             proxy_url=self._proxy_url,\n                             proxy_port=self._proxy_port)",
    "docstring": "deletes a role by ID"
  },
  {
    "code": "def run_latex_report(base, report_dir, section_info):\n    out_name = \"%s_recal_plots.tex\" % base\n    out = os.path.join(report_dir, out_name)\n    with open(out, \"w\") as out_handle:\n        out_tmpl = Template(out_template)\n        out_handle.write(out_tmpl.render(sections=section_info))\n    start_dir = os.getcwd()\n    try:\n        os.chdir(report_dir)\n        cl = [\"pdflatex\", out_name]\n        child = subprocess.Popen(cl)\n        child.wait()\n    finally:\n        os.chdir(start_dir)",
    "docstring": "Generate a pdf report with plots using latex."
  },
  {
    "code": "def add_path(prev: Optional[ResponsePath], key: Union[str, int]) -> ResponsePath:\n    return ResponsePath(prev, key)",
    "docstring": "Add a key to a response path.\n\n    Given a ResponsePath and a key, return a new ResponsePath containing the new key."
  },
  {
    "code": "def path_for_doc(self, doc_id):\n        full_path = self.path_for_doc_fn(self.repo, doc_id)\n        return full_path",
    "docstring": "Returns doc_dir and doc_filepath for doc_id."
  },
  {
    "code": "def snapshot_share(self, share_name, metadata=None, quota=None, timeout=None):\n        _validate_not_none('share_name', share_name)\n        request = HTTPRequest()\n        request.method = 'PUT'\n        request.host_locations = self._get_host_locations()\n        request.path = _get_path(share_name)\n        request.query = {\n            'restype': 'share',\n            'comp': 'snapshot',\n            'timeout': _int_to_str(timeout),\n        }\n        request.headers = {\n            'x-ms-share-quota': _int_to_str(quota)\n        }\n        _add_metadata_headers(metadata, request)\n        return self._perform_request(request, _parse_snapshot_share, [share_name])",
    "docstring": "Creates a snapshot of an existing share under the specified account.\n\n        :param str share_name:\n            The name of the share to create a snapshot of.\n        :param metadata:\n            A dict with name_value pairs to associate with the\n            share as metadata. Example:{'Category':'test'}\n        :type metadata: a dict of str to str:\n        :param int quota:\n            Specifies the maximum size of the share, in gigabytes. Must be\n            greater than 0, and less than or equal to 5TB (5120).\n        :param int timeout:\n            The timeout parameter is expressed in seconds.\n        :return: snapshot properties\n        :rtype: azure.storage.file.models.Share"
  },
  {
    "code": "def track_child(self, child, logical_block_size, allow_duplicate=False):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('Directory Record not yet initialized')\n        self._add_child(child, logical_block_size, allow_duplicate, False)",
    "docstring": "A method to track an existing child of this directory record.\n\n        Parameters:\n         child - The child directory record object to add.\n         logical_block_size - The size of a logical block for this volume descriptor.\n         allow_duplicate - Whether to allow duplicate names, as there are\n                           situations where duplicate children are allowed.\n        Returns:\n         Nothing."
  },
  {
    "code": "def _load_table(self, name):\n        table = self._tables.get(name, None)\n        if table is not None:\n            return table\n        if not self.engine.has_table(name):\n            raise BindingException('Table does not exist: %r' % name,\n                                   table=name)\n        table = Table(name, self.meta, autoload=True)\n        self._tables[name] = table\n        return table",
    "docstring": "Reflect a given table from the database."
  },
  {
    "code": "def symbols_to_prob(symbols):\n    myCounter = Counter(symbols)\n    N = float(len(list(symbols)))\n    for k in myCounter:\n        myCounter[k] /= N\n    return myCounter",
    "docstring": "Return a dict mapping symbols to  probability.\n\n    input:\n    -----\n        symbols:     iterable of hashable items\n                     works well if symbols is a zip of iterables"
  },
  {
    "code": "def _handle_poll(self, relpath, params):\n    request = json.loads(params.get('q')[0])\n    ret = {}\n    for poll in request:\n      _id = poll.get('id', None)\n      path = poll.get('path', None)\n      pos = poll.get('pos', 0)\n      if path:\n        abspath = os.path.normpath(os.path.join(self._root, path))\n        if os.path.isfile(abspath):\n          with open(abspath, 'rb') as infile:\n            if pos:\n              infile.seek(pos)\n            content = infile.read()\n            ret[_id] = content.decode(\"utf-8\")\n    content = json.dumps(ret).encode(\"utf-8\")\n    self._send_content(content, 'application/json')",
    "docstring": "Handle poll requests for raw file contents."
  },
  {
    "code": "def validate_quantity(self, value):\n        if not isinstance(value, pq.quantity.Quantity):\n            self._error('%s' % value, \"Must be a Python quantity.\")",
    "docstring": "Validate that the value is of the `Quantity` type."
  },
  {
    "code": "def system_update_keyspace(self, ks_def):\n    self._seqid += 1\n    d = self._reqs[self._seqid] = defer.Deferred()\n    self.send_system_update_keyspace(ks_def)\n    return d",
    "docstring": "updates properties of a keyspace. returns the new schema id.\n\n    Parameters:\n     - ks_def"
  },
  {
    "code": "def get_service_status(self, name):\n        svc = self._query_service(name)\n        if svc is not None:\n            return {'name': name,\n                    'status': self.parse_query(svc['output']),\n                    'output': svc['output']\n                    }\n        else:\n            return {'name': name,\n                    'status': 'missing',\n                    'output': ''\n                    }",
    "docstring": "Returns the status for the given service name along with the output\n        of the query command"
  },
  {
    "code": "def stat_smt_query(func: Callable):\n    stat_store = SolverStatistics()\n    def function_wrapper(*args, **kwargs):\n        if not stat_store.enabled:\n            return func(*args, **kwargs)\n        stat_store.query_count += 1\n        begin = time()\n        result = func(*args, **kwargs)\n        end = time()\n        stat_store.solver_time += end - begin\n        return result\n    return function_wrapper",
    "docstring": "Measures statistics for annotated smt query check function"
  },
  {
    "code": "def git_ls_files(*cmd_args):\n    cmd = ['git', 'ls-files']\n    cmd.extend(cmd_args)\n    return set(subprocess.check_output(cmd).splitlines())",
    "docstring": "Run ``git ls-files`` in the top-level project directory. Arguments go\n    directly to execution call.\n\n    :return: set of file names\n    :rtype: :class:`set`"
  },
  {
    "code": "def info_gain(current_impurity, true_branch, false_branch, criterion):\n    measure_impurity = gini_impurity if criterion == \"gini\" else entropy\n    p = float(len(true_branch)) / (len(true_branch) + len(false_branch))\n    return current_impurity - p * measure_impurity(true_branch) - (1 - p) * measure_impurity(false_branch)",
    "docstring": "Information Gain.\n    \n    The uncertainty of the starting node, minus the weighted impurity of\n    two child nodes."
  },
  {
    "code": "def _error(self, request, status, headers={}, prefix_template_path=False, **kwargs):\n        return self._render(\n            request = request,\n            template = str(status),\n            status = status,\n            context = {\n                'error': kwargs\n            },\n            headers = headers,\n            prefix_template_path = prefix_template_path\n        )",
    "docstring": "Convenience method to render an error response. The template is inferred from the status code.\n\n        :param request: A django.http.HttpRequest instance.\n        :param status: An integer describing the HTTP status code to respond with.\n        :param headers: A dictionary describing HTTP headers.\n        :param prefix_template_path: A boolean describing whether to prefix the template with the view's template path.\n        :param kwargs: Any additional keyword arguments to inject. These are wrapped under ``error`` for convenience.\n\n        For implementation details, see ``render``"
  },
  {
    "code": "def end_index(self):\n        paginator = self.paginator\n        if self.number == paginator.num_pages:\n            return paginator.count\n        return (self.number - 1) * paginator.per_page + paginator.first_page",
    "docstring": "Return the 1-based index of the last item on this page."
  },
  {
    "code": "def to_xarray(input):\n    from climlab.domain.field import Field\n    if isinstance(input, Field):\n        return Field_to_xarray(input)\n    elif isinstance(input, dict):\n        return state_to_xarray(input)\n    else:\n        raise TypeError('input must be Field object or dictionary of Field objects')",
    "docstring": "Convert climlab input to xarray format.\n\n    If input is a climlab.Field object, return xarray.DataArray\n\n    If input is a dictionary (e.g. process.state or process.diagnostics),\n    return xarray.Dataset object with all spatial axes,\n    including 'bounds' axes indicating cell boundaries in each spatial dimension.\n\n    Any items in the dictionary that are not instances of climlab.Field\n    are ignored."
  },
  {
    "code": "def getsourcefile(object):\n    filename = getfile(object)\n    if string.lower(filename[-4:]) in ['.pyc', '.pyo']:\n        filename = filename[:-4] + '.py'\n    for suffix, mode, kind in imp.get_suffixes():\n        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:\n            return None\n    if os.path.exists(filename):\n        return filename",
    "docstring": "Return the Python source file an object was defined in, if it exists."
  },
  {
    "code": "def facets_normal(self):\n        if len(self.facets) == 0:\n            return np.array([])\n        area_faces = self.area_faces\n        index = np.array([i[area_faces[i].argmax()]\n                          for i in self.facets])\n        normals = self.face_normals[index]\n        origins = self.vertices[self.faces[:, 0][index]]\n        self._cache['facets_origin'] = origins\n        return normals",
    "docstring": "Return the normal of each facet\n\n        Returns\n        ---------\n        normals: (len(self.facets), 3) float\n          A unit normal vector for each facet"
  },
  {
    "code": "def GetListSelect(selectList, title=\"Select\", msg=\"\"):\n    root = tkinter.Tk()\n    root.title(title)\n    label = tkinter.Label(root, text=msg)\n    label.pack()\n    listbox = tkinter.Listbox(root)\n    for i in selectList:\n        listbox.insert(tkinter.END, i)\n    listbox.pack()\n    tkinter.Button(root, text=\"OK\", fg=\"black\", command=root.quit).pack()\n    root.mainloop()\n    selected = listbox.get(listbox.curselection())\n    print(selected + \" is selected\")\n    root.destroy()\n    return (selected, selectList.index(selected))",
    "docstring": "Create list with selectList,\n    and then return seleced string and index\n\n    title: Window name\n    mag: Label of the list\n\n    return (seldctedItem, selectedindex)"
  },
  {
    "code": "def file_identifier(self):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('UDF File Entry not initialized')\n        if self.file_ident is None:\n            return b'/'\n        return self.file_ident.fi",
    "docstring": "A method to get the name of this UDF File Entry as a byte string.\n\n        Parameters:\n         None.\n        Returns:\n         The UDF File Entry as a byte string."
  },
  {
    "code": "def wait_for_tx(self, tx, max_seconds=120):\n    tx_hash = None\n    if isinstance(tx, (str, UInt256)):\n        tx_hash = str(tx)\n    elif isinstance(tx, Transaction):\n        tx_hash = tx.Hash.ToString()\n    else:\n        raise AttributeError(\"Supplied tx is type '%s', but must be Transaction or UInt256 or str\" % type(tx))\n    wait_event = Event()\n    time_start = time.time()\n    while True:\n        _tx, height = Blockchain.Default().GetTransaction(tx_hash)\n        if height > -1:\n            return True\n        wait_event.wait(3)\n        seconds_passed = time.time() - time_start\n        if seconds_passed > max_seconds:\n            raise TxNotFoundInBlockchainError(\"Transaction with hash %s not found after %s seconds\" % (tx_hash, int(seconds_passed)))",
    "docstring": "Wait for tx to show up on blockchain\n\n    Args:\n        tx (Transaction or UInt256 or str): Transaction or just the hash\n        max_seconds (float): maximum seconds to wait for tx to show up. default: 120\n\n    Returns:\n        True: if transaction was found\n\n    Raises:\n        AttributeError: if supplied tx is not Transaction or UInt256 or str\n        TxNotFoundInBlockchainError: if tx is not found in blockchain after max_seconds"
  },
  {
    "code": "def complete_object_value(\n        self,\n        return_type: GraphQLObjectType,\n        field_nodes: List[FieldNode],\n        info: GraphQLResolveInfo,\n        path: ResponsePath,\n        result: Any,\n    ) -> AwaitableOrValue[Dict[str, Any]]:\n        if return_type.is_type_of:\n            is_type_of = return_type.is_type_of(result, info)\n            if isawaitable(is_type_of):\n                async def collect_and_execute_subfields_async():\n                    if not await is_type_of:\n                        raise invalid_return_type_error(\n                            return_type, result, field_nodes\n                        )\n                    return self.collect_and_execute_subfields(\n                        return_type, field_nodes, path, result\n                    )\n                return collect_and_execute_subfields_async()\n            if not is_type_of:\n                raise invalid_return_type_error(return_type, result, field_nodes)\n        return self.collect_and_execute_subfields(\n            return_type, field_nodes, path, result\n        )",
    "docstring": "Complete an Object value by executing all sub-selections."
  },
  {
    "code": "def update(self):\n        url = self.baseurl + '/_status?format=xml'\n        response = self.s.get(url)\n        response.raise_for_status()\n        from xml.etree.ElementTree import XML\n        root = XML(response.text)\n        for serv_el in root.iter('service'):\n            serv = Monit.Service(self, serv_el)\n            self[serv.name] = serv\n            if self[serv.name].pendingaction:\n                time.sleep(1)\n                return Monit.update(self)\n            if self[serv.name].monitorState == 2:\n                time.sleep(1)\n                return Monit.update(self)",
    "docstring": "Update Monit deamon and services status."
  },
  {
    "code": "def cloud_front_origin_access_identity_exists(Id, region=None, key=None, keyid=None, profile=None):\n    authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}\n    oais = list_cloud_front_origin_access_identities(**authargs) or []\n    return bool([i['Id'] for i in oais if i['Id'] == Id])",
    "docstring": "Return True if a CloudFront origin access identity exists with the given Resource ID or False\n    otherwise.\n\n    Id\n        Resource ID of the CloudFront origin access identity.\n\n    region\n        Region to connect to.\n\n    key\n        Secret key to use.\n\n    keyid\n        Access key to use.\n\n    profile\n        Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_cloudfront.cloud_front_origin_access_identity_exists Id=E30RBTSABCDEF0"
  },
  {
    "code": "def _call(self, x, out=None):\n        if out is None:\n            out = self.range.zero()\n            for i, j, op in zip(self.ops.row, self.ops.col, self.ops.data):\n                out[i] += op(x[j])\n        else:\n            has_evaluated_row = np.zeros(len(self.range), dtype=bool)\n            for i, j, op in zip(self.ops.row, self.ops.col, self.ops.data):\n                if not has_evaluated_row[i]:\n                    op(x[j], out=out[i])\n                else:\n                    out[i] += op(x[j])\n                has_evaluated_row[i] = True\n            for i, evaluated in enumerate(has_evaluated_row):\n                if not evaluated:\n                    out[i].set_zero()\n        return out",
    "docstring": "Call the operators on the parts of ``x``."
  },
  {
    "code": "def credit(self, amount, debit_account, description, debit_memo=\"\", credit_memo=\"\", datetime=None):\n        assert amount >= 0\n        return self.post(-amount, debit_account, description, self_memo=credit_memo, other_memo=debit_memo, datetime=datetime)",
    "docstring": "Post a credit of 'amount' and a debit of -amount against this account and credit_account respectively.\n\n        note amount must be non-negative."
  },
  {
    "code": "def generate(self, labels, split_idx):\n        atom_labels = [label[0] for label in labels]\n        noise = []\n        distribution_function = distributions[self.distribution_name][\"function\"]\n        for label in atom_labels:\n            params = [self.parameters[\"{}_{}\".format(label, param)][split_idx]\n                      for param in self.distribution_parameter_names]\n            if None in params:\n                dim_noise = 0.0\n            else:\n                try:\n                    dim_noise = distribution_function(*params)\n                except ValueError:\n                    raise ValueError\n            noise.append(dim_noise)\n        return noise",
    "docstring": "Generate peak-specific noise abstract method, must be reimplemented in a subclass.\n\n        :param tuple labels: Dimension labels of a peak.\n        :param int split_idx: Index specifying which peak list split parameters to use.\n        :return: List of noise values for dimensions ordered as they appear in a peak.\n        :rtype: :py:class:`list`"
  },
  {
    "code": "def wrap_case_result(raw, expr):\n    raw_1d = np.atleast_1d(raw)\n    if np.any(pd.isnull(raw_1d)):\n        result = pd.Series(raw_1d)\n    else:\n        result = pd.Series(\n            raw_1d, dtype=constants.IBIS_TYPE_TO_PANDAS_TYPE[expr.type()]\n        )\n    if result.size == 1 and isinstance(expr, ir.ScalarExpr):\n        return result.item()\n    return result",
    "docstring": "Wrap a CASE statement result in a Series and handle returning scalars.\n\n    Parameters\n    ----------\n    raw : ndarray[T]\n        The raw results of executing the ``CASE`` expression\n    expr : ValueExpr\n        The expression from the which `raw` was computed\n\n    Returns\n    -------\n    Union[scalar, Series]"
  },
  {
    "code": "def syndic_cmd(self, data):\n        if 'tgt_type' not in data:\n            data['tgt_type'] = 'glob'\n        kwargs = {}\n        for field in ('master_id',\n                      'user',\n                      ):\n            if field in data:\n                kwargs[field] = data[field]\n        def timeout_handler(*args):\n            log.warning('Unable to forward pub data: %s', args[1])\n            return True\n        with tornado.stack_context.ExceptionStackContext(timeout_handler):\n            self.local.pub_async(data['tgt'],\n                                 data['fun'],\n                                 data['arg'],\n                                 data['tgt_type'],\n                                 data['ret'],\n                                 data['jid'],\n                                 data['to'],\n                                 io_loop=self.io_loop,\n                                 callback=lambda _: None,\n                                 **kwargs)",
    "docstring": "Take the now clear load and forward it on to the client cmd"
  },
  {
    "code": "def get_method(name):\n    name = _format_name(name)\n    try:\n        return METHODS[name]\n    except KeyError as exc:\n        exc.args = (\"no PSD method registered with name {0!r}\".format(name),)\n        raise",
    "docstring": "Return the PSD method registered with the given name."
  },
  {
    "code": "def get_app_index_dashboard(context):\n    app = context['app_list'][0]\n    model_list = []\n    app_label = None\n    app_title = app['name']\n    admin_site = get_admin_site(context=context)\n    for model, model_admin in admin_site._registry.items():\n        if app['app_label'] == model._meta.app_label:\n            split = model.__module__.find(model._meta.app_label)\n            app_label = model.__module__[0:split] + model._meta.app_label\n            for m in app['models']:\n                if m['name'] == capfirst(model._meta.verbose_name_plural):\n                    mod = '%s.%s' % (model.__module__, model.__name__)\n                    model_list.append(mod)\n    if app_label is not None and app_label in Registry.registry:\n        return Registry.registry[app_label](app_title, model_list)\n    return _get_dashboard_cls(getattr(\n        settings,\n        'ADMIN_TOOLS_APP_INDEX_DASHBOARD',\n        'admin_tools.dashboard.dashboards.DefaultAppIndexDashboard'\n    ), context)(app_title, model_list)",
    "docstring": "Returns the admin dashboard defined by the user or the default one."
  },
  {
    "code": "async def wait_for_connection_lost(self) -> bool:\n        if not self.connection_lost_waiter.done():\n            try:\n                await asyncio.wait_for(\n                    asyncio.shield(self.connection_lost_waiter),\n                    self.close_timeout,\n                    loop=self.loop,\n                )\n            except asyncio.TimeoutError:\n                pass\n        return self.connection_lost_waiter.done()",
    "docstring": "Wait until the TCP connection is closed or ``self.close_timeout`` elapses.\n\n        Return ``True`` if the connection is closed and ``False`` otherwise."
  },
  {
    "code": "def dct2(input, K=13):\n    nframes, N = input.shape\n    freqstep = numpy.pi / N\n    cosmat = dctmat(N,K,freqstep,False)\n    return numpy.dot(input, cosmat) * (2.0 / N)",
    "docstring": "Convert log-power-spectrum to MFCC using the normalized DCT-II"
  },
  {
    "code": "def list_websites(self):\n        self.connect()\n        results = self.server.list_websites(self.session_id)\n        return results",
    "docstring": "Return all websites, name is not a key"
  },
  {
    "code": "def handle_single_request(self, request_object):\n        if not isinstance(request_object, (MethodCall, Notification)):\n            raise TypeError(\"Invalid type for request_object\")\n        method_name = request_object.method_name\n        params = request_object.params\n        req_id = request_object.id\n        request_body = self.build_request_body(method_name, params, id=req_id)\n        http_request = self.build_http_request_obj(request_body)\n        try:\n            response = urllib.request.urlopen(http_request)\n        except urllib.request.HTTPError as e:\n            raise CalledServiceError(e)\n        if not req_id:\n            return\n        response_body = json.loads(response.read().decode())\n        return response_body",
    "docstring": "Handles a single request object and returns the raw response\n\n        :param request_object:"
  },
  {
    "code": "def start(host, port=5959, tag='salt/engine/logstash', proto='udp'):\n    if proto == 'tcp':\n        logstashHandler = logstash.TCPLogstashHandler\n    elif proto == 'udp':\n        logstashHandler = logstash.UDPLogstashHandler\n    logstash_logger = logging.getLogger('python-logstash-logger')\n    logstash_logger.setLevel(logging.INFO)\n    logstash_logger.addHandler(logstashHandler(host, port, version=1))\n    if __opts__.get('id').endswith('_master'):\n        event_bus = salt.utils.event.get_master_event(\n                __opts__,\n                __opts__['sock_dir'],\n                listen=True)\n    else:\n        event_bus = salt.utils.event.get_event(\n            'minion',\n            transport=__opts__['transport'],\n            opts=__opts__,\n            sock_dir=__opts__['sock_dir'],\n            listen=True)\n        log.debug('Logstash engine started')\n    while True:\n        event = event_bus.get_event()\n        if event:\n            logstash_logger.info(tag, extra=event)",
    "docstring": "Listen to salt events and forward them to logstash"
  },
  {
    "code": "def scale_calculator(multiplier, elements, rescale=None):\n    if isinstance(elements, list):\n        unique_elements = list(set(elements))\n        scales = {}\n        for x in unique_elements:\n            count = elements.count(x)\n            scales[x] = multiplier * count\n    elif isinstance(elements, dict):\n        scales = {}\n        for k,count in elements.items():\n            scales[k] = multiplier * int(count)\n    else:\n        raise ValueError('Input list of elements or dictionary of elements & counts')\n    if not rescale:\n        return scales\n    else:\n        new_scales = {}\n        for k,v in scales.items():\n            new_scales[k] = remap(v, min(scales.values()), max(scales.values()), rescale[0], rescale[1])\n        return new_scales",
    "docstring": "Get a dictionary of scales for each element in elements.\n\n    Examples:\n        >>> scale_calculator(1, [2,7,8])\n        {8: 1, 2: 1, 7: 1}\n\n        >>> scale_calculator(1, [2,2,2,3,4,5,5,6,7,8])\n        {2: 3, 3: 1, 4: 1, 5: 2, 6: 1, 7: 1, 8: 1}\n\n        >>> scale_calculator(1, [2,2,2,3,4,5,5,6,7,8], rescale=(0.5,1))\n        {2: 1.0, 3: 0.5, 4: 0.5, 5: 0.75, 6: 0.5, 7: 0.5, 8: 0.5}\n\n        >>> scale_calculator(1, {2:3, 3:1, 4:1, 5:2, 6:1, 7:1, 8:1}, rescale=(0.5,1))\n        {2: 1.0, 3: 0.5, 4: 0.5, 5: 0.75, 6: 0.5, 7: 0.5, 8: 0.5}\n\n        >>> scale_calculator(1, [(2,2,2),(3,),(4,),(5,),(5,),(6,7,8)], rescale=(0.5,1))\n        {(2, 2, 2): 0.5, (3,): 0.5, (6, 7, 8): 0.5, (4,): 0.5, (5,): 1.0}\n\n        >>> scale_calculator(1, {77:35, 80:35, 16:1}, rescale=(.99,1))\n        None\n\n    Args:\n        mutiplier (int, float): Base float to be multiplied\n        elements (list, dict): Dictionary which contains object:count\n            or list of objects that may have repeats which will be counted\n        rescale (tuple): Min and max values to rescale to\n\n    Returns:\n        dict: Scaled values of mutiplier for each element in elements"
  },
  {
    "code": "def display(table, limit=0, vrepr=None, index_header=None, caption=None,\n            tr_style=None, td_styles=None, encoding=None, truncate=None,\n            epilogue=None):\n    from IPython.core.display import display_html\n    html = _display_html(table, limit=limit, vrepr=vrepr,\n                         index_header=index_header, caption=caption,\n                         tr_style=tr_style, td_styles=td_styles,\n                         encoding=encoding, truncate=truncate,\n                         epilogue=epilogue)\n    display_html(html, raw=True)",
    "docstring": "Display a table inline within an IPython notebook."
  },
  {
    "code": "def as_translation_key(self):\n        return TranslationKey(**{\n            name: getattr(self, name)\n            for name in TranslationKey._fields})",
    "docstring": "Project Translation object or any other derived class into just a\n        TranslationKey, which has fewer fields and can be used as a\n        dictionary key."
  },
  {
    "code": "def _get_item_from_search_response(self, response, type_):\n        sections = sorted(response['sections'],\n                          key=lambda sect: sect['type'] == type_,\n                          reverse=True)\n        for section in sections:\n            hits = [hit for hit in section['hits'] if hit['type'] == type_]\n            if hits:\n                return hits[0]['result']",
    "docstring": "Returns either a Song or Artist result from search_genius_web"
  },
  {
    "code": "def output(self, context, *args, **kwargs):\n        output_fields = self.output_fields\n        output_type = self.output_type\n        if output_fields and output_type:\n            raise UnrecoverableError(\"Cannot specify both output_fields and output_type option.\")\n        if self.output_type:\n            context.set_output_type(self.output_type)\n        if self.output_fields:\n            context.set_output_fields(self.output_fields)\n        yield",
    "docstring": "Allow all readers to use eventually use output_fields XOR output_type options."
  },
  {
    "code": "def get_by_name(self, name, style_type = None):\n        for st in self.styles.values():\n            if st:\n                if st.name == name:\n                    return st\n        if style_type and not st:\n            st = self.styles.get(self.default_styles[style_type], None)            \n        return st",
    "docstring": "Find style by it's descriptive name.\n\n        :Returns:\n          Returns found style of type :class:`ooxml.doc.Style`."
  },
  {
    "code": "def synchronized(lock):\r\n    @simple_decorator\r\n    def wrap(function_target):\r\n        def new_function(*args, **kw):\r\n            lock.acquire()\r\n            try:\r\n                return function_target(*args, **kw)\r\n            finally:\r\n                lock.release()\r\n        return new_function\r\n    return wrap",
    "docstring": "Synchronization decorator.\r\n    Allos to set a mutex on any function"
  },
  {
    "code": "def id_getter(self, relation_name, strict=False):\n    def get_id(old_id):\n      return self.get_new_id(relation_name, old_id, strict)\n    return get_id",
    "docstring": "Returns a function that accepts an old_id and returns the new ID for the enclosed relation\n    name."
  },
  {
    "code": "def assign_issue(self, issue, assignee):\n        url = self._options['server'] + \\\n            '/rest/api/latest/issue/' + str(issue) + '/assignee'\n        payload = {'name': assignee}\n        r = self._session.put(\n            url, data=json.dumps(payload))\n        raise_on_error(r)\n        return True",
    "docstring": "Assign an issue to a user. None will set it to unassigned. -1 will set it to Automatic.\n\n        :param issue: the issue ID or key to assign\n        :type issue: int or str\n        :param assignee: the user to assign the issue to\n        :type assignee: str\n\n        :rtype: bool"
  },
  {
    "code": "def deprecated(fn):\n    @functools.wraps(fn)\n    def wrapper(*args, **kwargs):\n        warnings.warn(fn.__doc__.split('\\n')[0],\n                      category=DeprecationWarning, stacklevel=2)\n        return fn(*args, **kwargs)\n    return wrapper",
    "docstring": "Mark a function as deprecated and warn the user on use."
  },
  {
    "code": "def sample_size_necessary_under_cph(power, ratio_of_participants, p_exp, p_con, postulated_hazard_ratio, alpha=0.05):\n    def z(p):\n        return stats.norm.ppf(p)\n    m = (\n        1.0\n        / ratio_of_participants\n        * ((ratio_of_participants * postulated_hazard_ratio + 1.0) / (postulated_hazard_ratio - 1.0)) ** 2\n        * (z(1.0 - alpha / 2.0) + z(power)) ** 2\n    )\n    n_exp = m * ratio_of_participants / (ratio_of_participants * p_exp + p_con)\n    n_con = m / (ratio_of_participants * p_exp + p_con)\n    return int(np.ceil(n_exp)), int(np.ceil(n_con))",
    "docstring": "This computes the sample size for needed power to compare two groups under a Cox\n    Proportional Hazard model.\n\n    Parameters\n    ----------\n\n    power : float\n        power to detect the magnitude of the hazard ratio as small as that specified by postulated_hazard_ratio.\n    ratio_of_participants: ratio of participants in experimental group over control group.\n\n    p_exp : float\n        probability of failure in experimental group over period of study.\n\n    p_con : float\n        probability of failure in control group over period of study\n\n    postulated_hazard_ratio : float\n        the postulated hazard ratio\n\n    alpha : float, optional (default=0.05)\n        type I error rate\n\n\n    Returns\n    -------\n\n    n_exp : integer\n        the samples sizes need for the experiment to achieve desired power\n\n    n_con : integer\n        the samples sizes need for the control group to achieve desired power\n\n\n    Examples\n    --------\n    >>> from lifelines.statistics import sample_size_necessary_under_cph\n    >>>\n    >>> desired_power = 0.8\n    >>> ratio_of_participants = 1.\n    >>> p_exp = 0.25\n    >>> p_con = 0.35\n    >>> postulated_hazard_ratio = 0.7\n    >>> n_exp, n_con = sample_size_necessary_under_cph(desired_power, ratio_of_participants, p_exp, p_con, postulated_hazard_ratio)\n    >>> # (421, 421)\n\n    References\n    -----------\n    https://cran.r-project.org/web/packages/powerSurvEpi/powerSurvEpi.pdf\n\n    See Also\n    --------\n    power_under_cph"
  },
  {
    "code": "def _create_state_data(self, context, resp_args, relay_state):\n        if \"name_id_policy\" in resp_args and resp_args[\"name_id_policy\"] is not None:\n            resp_args[\"name_id_policy\"] = resp_args[\"name_id_policy\"].to_string().decode(\"utf-8\")\n        return {\"resp_args\": resp_args, \"relay_state\": relay_state}",
    "docstring": "Returns a dict containing the state needed in the response flow.\n\n        :type context: satosa.context.Context\n        :type resp_args: dict[str, str | saml2.samlp.NameIDPolicy]\n        :type relay_state: str\n        :rtype: dict[str, dict[str, str] | str]\n\n        :param context: The current context\n        :param resp_args: Response arguments\n        :param relay_state: Request relay state\n        :return: A state as a dict"
  },
  {
    "code": "def omitted_parcov(self):\n        if self.__omitted_parcov is None:\n            self.log(\"loading omitted_parcov\")\n            self.__load_omitted_parcov()\n            self.log(\"loading omitted_parcov\")\n        return self.__omitted_parcov",
    "docstring": "get the omitted prior parameter covariance matrix\n\n        Returns\n        -------\n        omitted_parcov : pyemu.Cov\n\n        Note\n        ----\n        returns a reference\n        \n        If ErrorVariance.__omitted_parcov is None,\n        attribute is dynamically loaded"
  },
  {
    "code": "def get_info(self):\n        field = self._current_field()\n        if field:\n            info = field.get_info()\n            info['path'] = '%s/%s' % (self.name if self.name else '<no name>', info['path'])\n        else:\n            info = super(Container, self).get_info()\n        return info",
    "docstring": "Get info regarding the current fuzzed enclosed node\n\n        :return: info dictionary"
  },
  {
    "code": "def largest_connected_submatrix(C, directed=True, lcc=None):\n    r\n    if isdense(C):\n        return sparse.connectivity.largest_connected_submatrix(csr_matrix(C), directed=directed, lcc=lcc).toarray()\n    else:\n        return sparse.connectivity.largest_connected_submatrix(C, directed=directed, lcc=lcc)",
    "docstring": "r\"\"\"Compute the count matrix on the largest connected set.\n\n    Parameters\n    ----------\n    C : scipy.sparse matrix\n        Count matrix specifying edge weights.\n    directed : bool, optional\n       Whether to compute connected components for a directed or\n       undirected graph. Default is True\n    lcc : (M,) ndarray, optional\n       The largest connected set\n\n    Returns\n    -------\n    C_cc : scipy.sparse matrix\n        Count matrix of largest completely\n        connected set of vertices (states)\n\n    See also\n    --------\n    largest_connected_set\n\n    Notes\n    -----\n    Viewing the count matrix as the adjacency matrix of a (directed)\n    graph the larest connected submatrix is the adjacency matrix of\n    the largest connected set of the corresponding graph. The largest\n    connected submatrix can be efficiently computed using Tarjan's algorithm.\n\n    References\n    ----------\n    .. [1] Tarjan, R E. 1972. Depth-first search and linear graph\n        algorithms. SIAM Journal on Computing 1 (2): 146-160.\n\n    Examples\n    --------\n\n    >>> import numpy as np\n    >>> from msmtools.estimation import largest_connected_submatrix\n\n    >>> C = np.array([[10, 1, 0], [2, 0, 3], [0, 0, 4]])\n\n    >>> C_cc_directed = largest_connected_submatrix(C)\n    >>> C_cc_directed # doctest: +ELLIPSIS\n    array([[10,  1],\n           [ 2,  0]]...)\n\n    >>> C_cc_undirected = largest_connected_submatrix(C, directed=False)\n    >>> C_cc_undirected # doctest: +ELLIPSIS\n    array([[10,  1,  0],\n           [ 2,  0,  3],\n           [ 0,  0,  4]]...)"
  },
  {
    "code": "def word_wrap_tree(parented_tree, width=0):\n    if width != 0:\n        for i, leaf_text in enumerate(parented_tree.leaves()):\n            dedented_text = textwrap.dedent(leaf_text).strip()\n            parented_tree[parented_tree.leaf_treeposition(i)] = textwrap.fill(dedented_text, width=width)\n    return parented_tree",
    "docstring": "line-wrap an NLTK ParentedTree for pretty-printing"
  },
  {
    "code": "def real_main(release_url=None,\n              tests_json_path=None,\n              upload_build_id=None,\n              upload_release_name=None):\n    coordinator = workers.get_coordinator()\n    fetch_worker.register(coordinator)\n    coordinator.start()\n    data = open(FLAGS.tests_json_path).read()\n    tests = load_tests(data)\n    item = DiffMyImages(\n        release_url,\n        tests,\n        upload_build_id,\n        upload_release_name,\n        heartbeat=workers.PrintWorkflow)\n    item.root = True\n    coordinator.input_queue.put(item)\n    coordinator.wait_one()\n    coordinator.stop()\n    coordinator.join()",
    "docstring": "Runs diff_my_images."
  },
  {
    "code": "def populateFromRow(self, continuousSetRecord):\n        self._filePath = continuousSetRecord.dataurl\n        self.setAttributesJson(continuousSetRecord.attributes)",
    "docstring": "Populates the instance variables of this ContinuousSet from the\n        specified DB row."
  },
  {
    "code": "def fill_dcnm_subnet_info(self, tenant_id, subnet, start, end, gateway,\n                              sec_gateway, direc):\n        serv_obj = self.get_service_obj(tenant_id)\n        fw_dict = serv_obj.get_fw_dict()\n        fw_id = fw_dict.get('fw_id')\n        if direc == 'in':\n            name = fw_id[0:4] + fw_const.IN_SERVICE_SUBNET + (\n                fw_id[len(fw_id) - 4:])\n        else:\n            name = fw_id[0:4] + fw_const.OUT_SERVICE_SUBNET + (\n                fw_id[len(fw_id) - 4:])\n        subnet_dict = {'enable_dhcp': False,\n                       'tenant_id': tenant_id,\n                       'name': name,\n                       'cidr': subnet + '/24',\n                       'gateway_ip': gateway,\n                       'secondary_gw': sec_gateway,\n                       'ip_version': 4}\n        subnet_dict['allocation_pools'] = [{'start': start, 'end': end}]\n        return subnet_dict",
    "docstring": "Fills the DCNM subnet parameters.\n\n        Function that fills the subnet parameters for a tenant required by\n        DCNM."
  },
  {
    "code": "def export_model(model, model_type, export_dir, model_column_fn):\n  wide_columns, deep_columns = model_column_fn()\n  if model_type == 'wide':\n    columns = wide_columns\n  elif model_type == 'deep':\n    columns = deep_columns\n  else:\n    columns = wide_columns + deep_columns\n  feature_spec = tf.feature_column.make_parse_example_spec(columns)\n  example_input_fn = (\n      tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec))\n  model.export_savedmodel(export_dir, example_input_fn,\n                          strip_default_attrs=True)",
    "docstring": "Export to SavedModel format.\n\n  Args:\n    model: Estimator object\n    model_type: string indicating model type. \"wide\", \"deep\" or \"wide_deep\"\n    export_dir: directory to export the model.\n    model_column_fn: Function to generate model feature columns."
  },
  {
    "code": "def getTmpFilename(self, tmp_dir=\"/tmp\",prefix='tmp',suffix='.fasta',\\\n           include_class_id=False,result_constructor=FilePath):\n        return super(Pplacer,self).getTmpFilename(tmp_dir=tmp_dir,\n                                    prefix=prefix,\n                                    suffix=suffix,\n                                    include_class_id=include_class_id,\n                                    result_constructor=result_constructor)",
    "docstring": "Define Tmp filename to contain .fasta suffix, since pplacer requires\n            the suffix to be .fasta"
  },
  {
    "code": "def get_device_by_id(self, device_id):\n        found_device = None\n        for device in self.get_devices():\n            if device.device_id == device_id:\n              found_device = device\n              break\n        if found_device is None:\n            logger.debug('Did not find device with {}'.format(device_id))\n        return found_device",
    "docstring": "Search the list of connected devices by ID.\n\n        device_id param is the integer ID of the device"
  },
  {
    "code": "def env(self):\n        from copy import copy\n        env = copy(self.doc.env)\n        assert env is not None, 'Got a null execution context'\n        env.update(self._envvar_env)\n        env.update(self.all_props)\n        return env",
    "docstring": "The execution context for rowprocessors and row-generating notebooks and functions."
  },
  {
    "code": "def _get(self, url, query=None):\n        if query is None:\n            query = {}\n        response = retry_request(self)(self._http_get)(url, query=query)\n        if self.raw_mode:\n            return response\n        if response.status_code != 200:\n            error = get_error(response)\n            if self.raise_errors:\n                raise error\n            return error\n        localized = query.get('locale', '') == '*'\n        return ResourceBuilder(\n            self.default_locale,\n            localized,\n            response.json(),\n            max_depth=self.max_include_resolution_depth,\n            reuse_entries=self.reuse_entries\n        ).build()",
    "docstring": "Wrapper for the HTTP Request,\n        Rate Limit Backoff is handled here,\n        Responses are Processed with ResourceBuilder."
  },
  {
    "code": "def warning (self, msg, pos=None):\n    self.log(msg, 'warning: ' + self.location(pos))",
    "docstring": "Logs a warning message pertaining to the given SeqAtom."
  },
  {
    "code": "def load(self, filename):\n        if not os.path.exists(filename):\n            raise AppConfigValueException('Could not load config file {0}'.\n                    format(filename))\n        cfl = open(filename, 'r')\n        if PY2:\n            self.readfp(cfl)\n        else:\n            self.read_file(cfl)\n        cfl.close()",
    "docstring": "Load the given config file.\n\n            @param filename: the filename including the path to load."
  },
  {
    "code": "def to_json(self, propval, extraneous=False, to_json_func=None):\n        if self.json_out:\n            return self.json_out(propval)\n        else:\n            if not to_json_func:\n                from normalize.record.json import to_json\n                to_json_func = to_json\n            return to_json_func(propval, extraneous)",
    "docstring": "This function calls the ``json_out`` function, if it was specified,\n        otherwise continues with JSON conversion of the value in the slot by\n        calling ``to_json_func`` on it."
  },
  {
    "code": "def _get_image_size(self, maxcharno, maxlineno):\n        return (self._get_char_x(maxcharno) + self.image_pad,\n                self._get_line_y(maxlineno + 0) + self.image_pad)",
    "docstring": "Get the required image size."
  },
  {
    "code": "def init_kerberos(app, service='HTTP', hostname=gethostname()):\n    global _SERVICE_NAME\n    _SERVICE_NAME = \"%s@%s\" % (service, hostname)\n    if 'KRB5_KTNAME' not in environ:\n        app.logger.warn(\"Kerberos: set KRB5_KTNAME to your keytab file\")\n    else:\n        try:\n            principal = kerberos.getServerPrincipalDetails(service, hostname)\n        except kerberos.KrbError as exc:\n            app.logger.warn(\"Kerberos: %s\" % exc.message[0])\n        else:\n            app.logger.info(\"Kerberos: server is %s\" % principal)",
    "docstring": "Configure the GSSAPI service name, and validate the presence of the\n    appropriate principal in the kerberos keytab.\n\n    :param app: a flask application\n    :type app: flask.Flask\n    :param service: GSSAPI service name\n    :type service: str\n    :param hostname: hostname the service runs under\n    :type hostname: str"
  },
  {
    "code": "def setRemoveAction(self, action):\n        if action not in ('unset', 'delete'):\n            raise orb.errors.ValidationError('The remove action must be either \"unset\" or \"delete\"')\n        else:\n            self.__removeAction = action",
    "docstring": "Sets the remove action that should be taken when a model is removed from the collection generated by\n        this reverse lookup.  Valid actions are \"unset\" or \"delete\", any other values will raise an exception.\n\n        :param action: <str>"
  },
  {
    "code": "def clear_cache(cls):\n        for key in cls._cached:\n            cls._cached[key] = None\n        cls._cached = {}",
    "docstring": "Call this before closing tk root"
  },
  {
    "code": "def set_option(self, optionname, value):\n        for name, parms in zip(self.opt_names, self.opt_parms):\n            if name == optionname:\n                defaulttype = type(parms['enabled'])\n                if defaulttype != type(value) and defaulttype != type(None):\n                    value = (defaulttype)(value)\n                parms['enabled'] = value\n                return True\n        else:\n            return False",
    "docstring": "Set the named option to value. Ensure the original type\n           of the option value is preserved."
  },
  {
    "code": "def request_syncmodule(blink, network):\n    url = \"{}/network/{}/syncmodules\".format(blink.urls.base_url, network)\n    return http_get(blink, url)",
    "docstring": "Request sync module info.\n\n    :param blink: Blink instance.\n    :param network: Sync module network id."
  },
  {
    "code": "def markdown_media_css():\n    return dict(\n        CSS_SET=posixpath.join(\n            settings.MARKDOWN_SET_PATH, settings.MARKDOWN_SET_NAME, 'style.css'\n        ),\n        CSS_SKIN=posixpath.join(\n            'django_markdown', 'skins', settings.MARKDOWN_EDITOR_SKIN,\n            'style.css'\n        )\n    )",
    "docstring": "Add css requirements to HTML.\n\n    :returns: Editor template context."
  },
  {
    "code": "def get_pages(url):\n    while True:\n        yield url\n        doc = html.parse(url).find(\"body\")\n        links = [a for a in doc.findall(\".//a\") if a.text and a.text.startswith(\"next \")]\n        if not links:\n            break\n        url = urljoin(url, links[0].get('href'))",
    "docstring": "Return the 'pages' from the starting url\n    Technically, look for the 'next 50' link, yield and download it,  repeat"
  },
  {
    "code": "def start(self):\n        logger.info(\"starting process\")\n        process = os.fork()\n        time.sleep(0.01)\n        if process != 0:\n            logger.debug('starting child watcher')\n            self.loop.reset()\n            self.child_pid = process\n            self.watcher = pyev.Child(self.child_pid, False, self.loop, self._child)\n            self.watcher.start()\n        else:\n            self.loop.reset()\n            logger.debug('running main function')\n            self.run(*self.args, **self.kwargs) \n            logger.debug('quitting')\n            sys.exit(0)",
    "docstring": "Start the process, essentially forks and calls target function."
  },
  {
    "code": "def find_deck(provider: Provider, key: str, version: int, prod: bool=True) -> Optional[Deck]:\n    pa_params = param_query(provider.network)\n    if prod:\n        p2th = pa_params.P2TH_addr\n    else:\n        p2th = pa_params.test_P2TH_addr\n    rawtx = provider.getrawtransaction(key, 1)\n    deck = deck_parser((provider, rawtx, 1, p2th))\n    return deck",
    "docstring": "Find specific deck by deck id."
  },
  {
    "code": "def generate(self, path, label):\n        for filename in os.listdir(path):\n            self[filename] = label",
    "docstring": "Creates default data from the corpus at `path`, marking all\n        works with `label`.\n\n        :param path: path to a corpus directory\n        :type path: `str`\n        :param label: label to categorise each work as\n        :type label: `str`"
  },
  {
    "code": "def get_event(self, block=True, timeout=None):\n        try:\n            return self._events.get(block, timeout)\n        except Empty:\n            return None",
    "docstring": "Get the next event from the queue.\n\n        :arg boolean block: Set to True to block if no event is available.\n        :arg seconds timeout: Timeout to wait if no event is available.\n\n        :Returns: The next event as a :class:`pygerrit.events.GerritEvent`\n            instance, or `None` if:\n             - `block` is False and there is no event available in the queue, or\n             - `block` is True and no event is available within the time\n               specified by `timeout`."
  },
  {
    "code": "def unpackage(package_):\n    return salt.utils.msgpack.loads(package_, use_list=True,\n                                    _msgpack_module=msgpack)",
    "docstring": "Unpackages a payload"
  },
  {
    "code": "def initLogging(verbosity=0, name=\"SCOOP\"):\n        global loggingConfig\n        verbose_levels = {\n            -2: \"CRITICAL\",\n            -1: \"ERROR\",\n            0: \"WARNING\",\n            1: \"INFO\",\n            2: \"DEBUG\",\n            3: \"DEBUG\",\n            4: \"NOSET\",\n        }\n        log_handlers = {\n            \"console\":\n            {\n                \"class\": \"logging.StreamHandler\",\n                \"formatter\": \"{name}Formatter\".format(name=name),\n                \"stream\": \"ext://sys.stderr\",\n            },\n        }\n        loggingConfig.update({\n            \"{name}Logger\".format(name=name):\n            {\n                \"handlers\": [\"console\"],\n                \"level\": verbose_levels[verbosity],\n            },\n        })\n        dict_log_config = {\n            \"version\": 1,\n            \"handlers\": log_handlers,\n            \"loggers\": loggingConfig,\n            \"formatters\":\n            {\n                \"{name}Formatter\".format(name=name):\n                {\n                    \"format\": \"[%(asctime)-15s] %(module)-9s \"\n                              \"%(levelname)-7s %(message)s\",\n                },\n            },\n        }\n        dictConfig(dict_log_config)\n        return logging.getLogger(\"{name}Logger\".format(name=name))",
    "docstring": "Creates a logger."
  },
  {
    "code": "def convert(obj, ids, attr_type, item_func, cdata, parent='root'):\n    LOG.info('Inside convert(). obj type is: \"%s\", obj=\"%s\"' % (type(obj).__name__, unicode_me(obj)))\n    item_name = item_func(parent)\n    if isinstance(obj, numbers.Number) or type(obj) in (str, unicode):\n        return convert_kv(item_name, obj, attr_type, cdata)\n    if hasattr(obj, 'isoformat'):\n        return convert_kv(item_name, obj.isoformat(), attr_type, cdata)\n    if type(obj) == bool:\n        return convert_bool(item_name, obj, attr_type, cdata)\n    if obj is None:\n        return convert_none(item_name, '', attr_type, cdata)\n    if isinstance(obj, dict):\n        return convert_dict(obj, ids, parent, attr_type, item_func, cdata)\n    if isinstance(obj, collections.Iterable):\n        return convert_list(obj, ids, parent, attr_type, item_func, cdata)\n    raise TypeError('Unsupported data type: %s (%s)' % (obj, type(obj).__name__))",
    "docstring": "Routes the elements of an object to the right function to convert them \n    based on their data type"
  },
  {
    "code": "def do_format(self, event_iterable):\n        for operation in self.formatter_chain:\n            partial_op = functools.partial(operation, colored=self.colored)\n            event_iterable = imap(partial_op, event_iterable)\n        return event_iterable",
    "docstring": "Formats the given CloudWatch Logs Event dictionary as necessary and returns an iterable that will\n        return the formatted string. This can be used to parse and format the events based on context\n        ie. In Lambda Function logs, a formatter may wish to color the \"ERROR\" keywords red,\n        or highlight a filter keyword separately etc.\n\n        This method takes an iterable as input and returns an iterable. It does not immediately format the event.\n        Instead, it sets up the formatter chain appropriately and returns the iterable. Actual formatting happens\n        only when the iterable is used by the caller.\n\n        Parameters\n        ----------\n        event_iterable : iterable of samcli.lib.logs.event.LogEvent\n            Iterable that returns an object containing information about each log event.\n\n        Returns\n        -------\n        iterable of string\n            Iterable that returns a formatted event as a string."
  },
  {
    "code": "def main_update(self):\n\t\ttry:\n\t\t\tos.nice(1)\n\t\texcept AttributeError as er:\n\t\t\tpass\n\t\ttime.sleep(self.refresh)\n\t\ttry:\n\t\t\twhile True:\n\t\t\t\ttimestamp=time.time()\n\t\t\t\tself.update()\n\t\t\t\tdelay=(timestamp+self.refresh)-time.time()\n\t\t\t\tif delay > 0:\n\t\t\t\t\tif delay > self.refresh:\n\t\t\t\t\t\ttime.sleep(self.refresh)\n\t\t\t\t\telse:\n\t\t\t\t\t\ttime.sleep(delay)\n\t\t\t\tself.commit()\n\t\texcept Exception as e:\n\t\t\tself.error=e\n\t\t\traise",
    "docstring": "Main function called by the updater thread.\n\t\tDirect call is unnecessary."
  },
  {
    "code": "def write_sequences_to_fasta(path, seqs):\n    from Bio import SeqIO\n    from Bio.Seq import Seq\n    from Bio.SeqRecord import SeqRecord\n    path = Path(path)\n    records = []\n    for id, seq in seqs.items():\n        record = SeqRecord(Seq(seq), id=id, description='')\n        records.append(record)\n    SeqIO.write(records, str(path), 'fasta')",
    "docstring": "Create a FASTA file listing the given sequences.\n\n    Arguments\n    =========\n    path: str or pathlib.Path\n        The name of the file to create.\n\n    seqs: dict\n        A mapping of names to sequences, which can be either protein or DNA."
  },
  {
    "code": "def _new_url_record(cls, request: Request) -> URLRecord:\n        url_record = URLRecord()\n        url_record.url = request.url_info.url\n        url_record.status = Status.in_progress\n        url_record.try_count = 0\n        url_record.level = 0\n        return url_record",
    "docstring": "Return new empty URLRecord."
  },
  {
    "code": "def write(self):\n        self._assure_writable(\"write\")\n        if not self._dirty:\n            return\n        if isinstance(self._file_or_files, (list, tuple)):\n            raise AssertionError(\"Cannot write back if there is not exactly a single file to write to, have %i files\"\n                                 % len(self._file_or_files))\n        if self._has_includes():\n            log.debug(\"Skipping write-back of configuration file as include files were merged in.\" +\n                      \"Set merge_includes=False to prevent this.\")\n            return\n        fp = self._file_or_files\n        is_file_lock = isinstance(fp, string_types + (FileType, ))\n        if is_file_lock:\n            self._lock._obtain_lock()\n        if not hasattr(fp, \"seek\"):\n            with open(self._file_or_files, \"wb\") as fp:\n                self._write(fp)\n        else:\n            fp.seek(0)\n            if hasattr(fp, 'truncate'):\n                fp.truncate()\n            self._write(fp)",
    "docstring": "Write changes to our file, if there are changes at all\n\n        :raise IOError: if this is a read-only writer instance or if we could not obtain\n            a file lock"
  },
  {
    "code": "def get_account(self, account_id, **kwargs):\n        if 'mask' not in kwargs:\n            kwargs['mask'] = 'status'\n        return self.account.getObject(id=account_id, **kwargs)",
    "docstring": "Retrieves a CDN account with the specified account ID.\n\n        :param account_id int: the numeric ID associated with the CDN account.\n        :param dict \\\\*\\\\*kwargs: additional arguments to include in the object\n                                mask."
  },
  {
    "code": "def setBreak(self,breakFlag = True):\n        if breakFlag:\n            _parseMethod = self._parse\n            def breaker(instring, loc, doActions=True, callPreParse=True):\n                import pdb\n                pdb.set_trace()\n                _parseMethod( instring, loc, doActions, callPreParse )\n            breaker._originalParseMethod = _parseMethod\n            self._parse = breaker\n        else:\n            if hasattr(self._parse,\"_originalParseMethod\"):\n                self._parse = self._parse._originalParseMethod\n        return self",
    "docstring": "Method to invoke the Python pdb debugger when this element is\n           about to be parsed. Set breakFlag to True to enable, False to\n           disable."
  },
  {
    "code": "def filter_products(self, desired_prods):\n        self.filter_prods = True\n        self.desired_prods = set(desired_prods)",
    "docstring": "When asked for a product, filter only those on this list."
  },
  {
    "code": "def _recv_nack(self, method_frame):\n        if self._nack_listener:\n            delivery_tag = method_frame.args.read_longlong()\n            multiple, requeue = method_frame.args.read_bits(2)\n            if multiple:\n                while self._last_ack_id < delivery_tag:\n                    self._last_ack_id += 1\n                    self._nack_listener(self._last_ack_id, requeue)\n            else:\n                self._last_ack_id = delivery_tag\n                self._nack_listener(self._last_ack_id, requeue)",
    "docstring": "Receive a nack from the broker."
  },
  {
    "code": "def tagged(*tags: Tags) -> Callable:\n    global GREENSIM_TAG_ATTRIBUTE\n    def hook(event: Callable):\n        def wrapper(*args, **kwargs):\n            event(*args, **kwargs)\n        setattr(wrapper, GREENSIM_TAG_ATTRIBUTE, tags)\n        return wrapper\n    return hook",
    "docstring": "Decorator for adding a label to the process.\n    These labels are applied to any child Processes produced by event"
  },
  {
    "code": "def validate_lun_path(self, host_wwpn, host_port, wwpn, lun):\n        host_wwpn_16 = format(int(host_wwpn, 16), '016x')\n        wwpn_16 = format(int(wwpn, 16), '016x')\n        lun_16 = format(int(lun, 16), '016x')\n        body = {\n            'host-world-wide-port-name': host_wwpn_16,\n            'adapter-port-uri': host_port.uri,\n            'target-world-wide-port-name': wwpn_16,\n            'logical-unit-number': lun_16,\n        }\n        self.manager.session.post(\n            self.uri + '/operations/validate-lun-path',\n            body=body)",
    "docstring": "Validate if an FCP storage volume on an actual storage subsystem is\n        reachable from this CPC, through a specified host port and using\n        a specified host WWPN.\n\n        This method performs the \"Validate LUN Path\" HMC operation.\n\n        If the volume is reachable, the method returns. If the volume is not\n        reachable (and no other errors occur), an :exc:`~zhmcclient.HTTPError`\n        is raised, and its :attr:`~zhmcclient.HTTPError.reason` property\n        indicates the reason as follows:\n\n        * 484: Target WWPN cannot be reached.\n        * 485: Target WWPN can be reached, but LUN cannot be reached.\n\n        The CPC must have the \"dpm-storage-management\" feature enabled.\n\n        Parameters:\n\n          host_wwpn (:term:`string`):\n            World wide port name (WWPN) of the host (CPC),\n            as a hexadecimal number of up to 16 characters in any lexical case.\n\n            This may be the WWPN of the physical storage port, or a WWPN of a\n            virtual HBA. In any case, it must be the kind of WWPN that is used\n            for zoning and LUN masking in the SAN.\n\n          host_port (:class:`~zhmcclient.Port`):\n            Storage port on the CPC that will be used for validating\n            reachability.\n\n          wwpn (:term:`string`):\n            World wide port name (WWPN) of the FCP storage subsystem containing\n            the storage volume,\n            as a hexadecimal number of up to 16 characters in any lexical case.\n\n          lun (:term:`string`):\n            Logical Unit Number (LUN) of the storage volume within its FCP\n            storage subsystem,\n            as a hexadecimal number of up to 16 characters in any lexical case.\n\n        Authorization requirements:\n\n        * Object-access permission to the storage group owning this storage\n          volume.\n        * Task permission to the \"Configure Storage - Storage Administrator\"\n          task.\n\n        Raises:\n\n          :exc:`~zhmcclient.HTTPError`\n          :exc:`~zhmcclient.ParseError`\n          :exc:`~zhmcclient.AuthError`\n          :exc:`~zhmcclient.ConnectionError`"
  },
  {
    "code": "def create_pgroup_snapshot(self, source, **kwargs):\n        result = self.create_pgroup_snapshots([source], **kwargs)\n        if self._rest_version >= LooseVersion(\"1.4\"):\n            headers = result.headers\n            result = ResponseDict(result[0])\n            result.headers = headers\n        return result",
    "docstring": "Create snapshot of pgroup from specified source.\n\n        :param source: Name of pgroup of which to take snapshot.\n        :type source: str\n        :param \\*\\*kwargs: See the REST API Guide on your array for the\n                           documentation on the request:\n                           **POST pgroup**\n        :type \\*\\*kwargs: optional\n\n        :returns: A dictionary describing the created snapshot.\n        :rtype: ResponseDict\n\n        .. note::\n\n            Requires use of REST API 1.2 or later."
  },
  {
    "code": "def apply_docstr(docstr_func):\n    def docstr_applier(func):\n        if isinstance(docstr_func, six.string_types):\n            olddoc = meta_util_six.get_funcdoc(func)\n            if olddoc is None:\n                olddoc = ''\n            newdoc = olddoc + docstr_func\n            meta_util_six.set_funcdoc(func, newdoc)\n            return func\n        else:\n            preserved_func = preserve_sig(func, docstr_func)\n            return preserved_func\n    return docstr_applier",
    "docstring": "Changes docstr of one functio to that of another"
  },
  {
    "code": "def confirm_dialog(self, emitter):\n        self.from_fields_to_dict()\n        return super(ProjectConfigurationDialog,self).confirm_dialog(self)",
    "docstring": "event called pressing on OK button."
  },
  {
    "code": "def view(self, template_name, kwargs=None):\n        if kwargs is None:\n            kwargs = dict()\n        self.add_('session', self.session)\n        content = self.render_template(template_name, **kwargs)\n        self.write(content)",
    "docstring": "Used to render template to view\n\n        Sample usage\n        +++++++++++++\n        .. code:: python\n\n            from bast import Controller\n\n            class MyController(Controller):\n                def index(self):\n                    self.view('index.html')"
  },
  {
    "code": "def is_parameter(self):\n        return (isinstance(self.scope, CodeFunction)\n                and self in self.scope.parameters)",
    "docstring": "Whether this is a function parameter."
  },
  {
    "code": "def get_content(self, url):\n        cache_path = self._url_to_path(url)\n        try:\n            with open(cache_path, 'rb') as f:\n                return f.read()\n        except IOError:\n            return None",
    "docstring": "Returns the content of a cached resource.\n\n        Args:\n            url: The url of the resource\n\n        Returns:\n            The content of the cached resource or None if not in the cache"
  },
  {
    "code": "def get_host_info():\n    host_info = {}\n    for k, v in host_info_gatherers.items():\n        try:\n            host_info[k] = v()\n        except IgnoreHostInfo:\n            pass\n    return host_info",
    "docstring": "Collect some information about the machine this experiment runs on.\n\n    Returns\n    -------\n    dict\n        A dictionary with information about the CPU, the OS and the\n        Python version of this machine."
  },
  {
    "code": "def get_balance(self):\n        on_date = Datum()\n        on_date.today()\n        return self.get_balance_on(on_date.value)",
    "docstring": "Current account balance"
  },
  {
    "code": "def _call(self, x, out=None):\n        if out is None:\n            return self.range.element(copy(self.constant))\n        else:\n            out.assign(self.constant)",
    "docstring": "Return the constant vector or assign it to ``out``."
  },
  {
    "code": "def _send_raw_command(ipmicmd, raw_bytes):\n    netfn, command, data = _parse_raw_bytes(raw_bytes)\n    response = ipmicmd.raw_command(netfn, command, data=data)\n    return response",
    "docstring": "Use IPMI command object to send raw ipmi command to BMC\n\n    :param ipmicmd: IPMI command object\n    :param raw_bytes: string of hexadecimal values. This is commonly used\n        for certain vendor specific commands.\n    :returns: dict -- The response from IPMI device"
  },
  {
    "code": "def ignore_exceptions(f):\n    @functools.wraps(f)\n    def wrapped(*args, **kwargs):\n        try:\n            return f(*args, **kwargs)\n        except:\n            logging.exception(\"Ignoring exception in %r\", f)\n    return wrapped",
    "docstring": "Decorator catches and ignores any exceptions raised by this function."
  },
  {
    "code": "def expand_source_paths(paths):\n    for src_path in paths:\n        if src_path.endswith(('.pyc', '.pyo')):\n            py_path = get_py_path(src_path)\n            if os.path.exists(py_path):\n                src_path = py_path\n        yield src_path",
    "docstring": "Convert pyc files into their source equivalents."
  },
  {
    "code": "def link_type(arg_type, arg_name=None, include_bt:bool=True):\n    \"Create link to documentation.\"\n    arg_name = arg_name or fn_name(arg_type)\n    if include_bt: arg_name = code_esc(arg_name)\n    if belongs_to_module(arg_type, 'torch') and ('Tensor' not in arg_name): return f'[{arg_name}]({get_pytorch_link(arg_type)})'\n    if is_fastai_class(arg_type): return f'[{arg_name}]({get_fn_link(arg_type)})'\n    return arg_name",
    "docstring": "Create link to documentation."
  },
  {
    "code": "def gather_meta(self):\n        if not os.path.exists(self.paths[\"meta\"]):\n            return \"\"\n        meta_dict = utils.yaml_load(self.paths[\"meta\"])\n        if meta_dict and \"dependencies\" in meta_dict:\n            dep_list = []\n            for dependency in meta_dict[\"dependencies\"]:\n                if type(dependency) is dict:\n                    dep_list.append(dependency[\"role\"])\n                else:\n                    dep_list.append(dependency)\n            meta_dict[\"dependencies\"] = list(set(dep_list))\n            self.dependencies = meta_dict[\"dependencies\"]\n        else:\n            self.dependencies = []\n        return utils.file_to_string(self.paths[\"meta\"])",
    "docstring": "Return the meta file."
  },
  {
    "code": "def _enable_thread_pool(func):\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        self = args[0]\n        if self.enable_thread_pool and hasattr(self, 'thread_pool'):\n            future = self.thread_pool.submit(func, *args, **kwargs)\n            is_async = kwargs.get('is_async')\n            if is_async is None or not is_async:\n                timeout = kwargs.get('timeout')\n                if timeout is None:\n                    timeout = 2\n                try:\n                    result = future.result(timeout=timeout)\n                except TimeoutError as e:\n                    self.logger.exception(e)\n                    result = None\n                return result\n            return future\n        else:\n            return func(*args, **kwargs)\n    return wrapper",
    "docstring": "Use thread pool for executing a task if self.enable_thread_pool is True.\n\n    Return an instance of future when flag is_async is True otherwise will to\n    block waiting for the result until timeout then returns the result."
  },
  {
    "code": "def update(self, friendly_name=values.unset, unique_name=values.unset):\n        return self._proxy.update(friendly_name=friendly_name, unique_name=unique_name, )",
    "docstring": "Update the FieldTypeInstance\n\n        :param unicode friendly_name: A string to describe the resource\n        :param unicode unique_name: An application-defined string that uniquely identifies the resource\n\n        :returns: Updated FieldTypeInstance\n        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance"
  },
  {
    "code": "def get_composition_metadata(self):\n        metadata = dict(self._mdata['composition'])\n        metadata.update({'existing_id_values': self._my_map['compositionId']})\n        return Metadata(**metadata)",
    "docstring": "Gets the metadata for linking this asset to a composition.\n\n        return: (osid.Metadata) - metadata for the composition\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def geodesic(crs, start, end, steps):\n    r\n    import cartopy.crs as ccrs\n    from pyproj import Geod\n    g = Geod(crs.proj4_init)\n    geodesic = np.concatenate([\n        np.array(start[::-1])[None],\n        np.array(g.npts(start[1], start[0], end[1], end[0], steps - 2)),\n        np.array(end[::-1])[None]\n    ]).transpose()\n    points = crs.transform_points(ccrs.Geodetic(), *geodesic)[:, :2]\n    return points",
    "docstring": "r\"\"\"Construct a geodesic path between two points.\n\n    This function acts as a wrapper for the geodesic construction available in `pyproj`.\n\n    Parameters\n    ----------\n    crs: `cartopy.crs`\n        Cartopy Coordinate Reference System to use for the output\n    start: (2, ) array_like\n        A latitude-longitude pair designating the start point of the geodesic (units are\n        degrees north and degrees east).\n    end: (2, ) array_like\n        A latitude-longitude pair designating the end point of the geodesic (units are degrees\n        north and degrees east).\n    steps: int, optional\n        The number of points along the geodesic between the start and the end point\n        (including the end points).\n\n    Returns\n    -------\n    `numpy.ndarray`\n        The list of x, y points in the given CRS of length `steps` along the geodesic.\n\n    See Also\n    --------\n    cross_section"
  },
  {
    "code": "def time(ctx, hours, minutes, seconds):\n    return _time(conversions.to_integer(hours, ctx), conversions.to_integer(minutes, ctx), conversions.to_integer(seconds, ctx))",
    "docstring": "Defines a time value"
  },
  {
    "code": "def unplug(self):\n        if not self.__plugged:\n            return\n        members = set([method for _, method\n                      in inspect.getmembers(self, predicate=inspect.ismethod)])\n        for message in global_callbacks:\n            global_callbacks[message] -= members\n        self.__plugged = False",
    "docstring": "Remove the actor's methods from the callback registry."
  },
  {
    "code": "def kube_pod_status_phase(self, metric, scraper_config):\n        metric_name = scraper_config['namespace'] + '.pod.status_phase'\n        status_phase_counter = Counter()\n        for sample in metric.samples:\n            tags = [\n                self._label_to_tag('namespace', sample[self.SAMPLE_LABELS], scraper_config),\n                self._label_to_tag('phase', sample[self.SAMPLE_LABELS], scraper_config),\n            ] + scraper_config['custom_tags']\n            status_phase_counter[tuple(sorted(tags))] += sample[self.SAMPLE_VALUE]\n        for tags, count in iteritems(status_phase_counter):\n            self.gauge(metric_name, count, tags=list(tags))",
    "docstring": "Phase a pod is in."
  },
  {
    "code": "def get_first_content(el_list, alt=None, strip=True):\n    if not el_list:\n        return alt\n    content = el_list[0].getContent()\n    if strip:\n        content = content.strip()\n    if not content:\n        return alt\n    return content",
    "docstring": "Return content of the first element in `el_list` or `alt`. Also return `alt`\n    if the content string of first element is blank.\n\n    Args:\n        el_list (list): List of HTMLElement objects.\n        alt (default None): Value returner when list or content is blank.\n        strip (bool, default True): Call .strip() to content.\n\n    Returns:\n        str or alt: String representation of the content of the first element \\\n                    or `alt` if not found."
  },
  {
    "code": "def change_path_prefix(self, path, old_prefix, new_prefix, app_name):\n        relative_path = os.path.relpath(path, old_prefix)\n        return os.path.join(new_prefix, app_name, relative_path)",
    "docstring": "Change path prefix and include app name."
  },
  {
    "code": "def _render_item(self, dstack, key, value = None, **settings):\n        cur_depth = len(dstack) - 1\n        treeptrn = ''\n        s = self._es_text(settings, settings[self.SETTING_TREE_FORMATING])\n        for ds in dstack:\n            treeptrn += ' ' + self.fmt_text(self.tchar(settings[self.SETTING_TREE_STYLE], cur_depth, *ds), **s) + ''\n        strptrn = \"{}\"\n        if value is not None:\n            strptrn += \": {}\"\n        s = self._es_text(settings, settings[self.SETTING_TEXT_FORMATING])\n        strptrn = self.fmt_text(strptrn.format(key, value), **s)\n        return '{} {}'.format(treeptrn, strptrn)",
    "docstring": "Format single tree line."
  },
  {
    "code": "def channel_names(self) -> tuple:\n        if \"channel_names\" not in self.attrs.keys():\n            self.attrs[\"channel_names\"] = np.array([], dtype=\"S\")\n        return tuple(s.decode() for s in self.attrs[\"channel_names\"])",
    "docstring": "Channel names."
  },
  {
    "code": "def is_topology(self, layers=None):\n        if layers is None:\n            layers = self.layers\n        layers_nodle = []\n        result = []\n        for i, layer in enumerate(layers):\n            if layer.is_delete is False:\n                layers_nodle.append(i)\n        while True:\n            flag_break = True\n            layers_toremove = []\n            for layer1 in layers_nodle:\n                flag_arrive = True\n                for layer2 in layers[layer1].input:\n                    if layer2 in layers_nodle:\n                        flag_arrive = False\n                if flag_arrive is True:\n                    for layer2 in layers[layer1].output:\n                        if layers[layer2].set_size(layer1, layers[layer1].size) is False:\n                            return False\n                    layers_toremove.append(layer1)\n                    result.append(layer1)\n                    flag_break = False\n            for layer in layers_toremove:\n                layers_nodle.remove(layer)\n            result.append('|')\n            if flag_break:\n                break\n        if layers_nodle:\n            return False\n        return result",
    "docstring": "valid the topology"
  },
  {
    "code": "def run(opts, args):\n        setup_options(opts)\n        mode = Modes.ONCE\n        if len(args) > 0 and hasattr(Modes, args[0].upper()):\n            _mode = args.pop(0).upper()\n            mode = getattr(Modes, _mode)\n        url = None\n        if len(args) > 0:\n            url = args.pop(0)\n        plugin_mgr = PluginManager.load_plugin_from_addonxml(mode, url)\n        plugin_mgr.run()",
    "docstring": "The run method for the 'run' command. Executes a plugin from the\n        command line."
  },
  {
    "code": "def add_item(self, item):\n        if not isinstance(item, JsonRpcResponse):\n            raise TypeError(\n                \"Expected JsonRpcResponse but got {} instead\".format(type(item).__name__))\n        self.items.append(item)",
    "docstring": "Adds an item to the batch."
  },
  {
    "code": "def group(__decorated__, **Config):\n  r\n  _Group = Group(__decorated__, Config)\n  if isclass(__decorated__):\n    static(__decorated__)\n  state.ActiveModuleMemberQ.insert(0, _Group)\n  return _Group.Underlying",
    "docstring": "r\"\"\"A decorator to make groups out of classes.\n\n  Config:\n    * name (str): The name of the group. Defaults to __decorated__.__name__.\n    * desc (str): The description of the group (optional).\n    * alias (str): The alias for the group (optional)."
  },
  {
    "code": "def render(self, renderer=None, **kwargs):\n        return Markup(get_renderer(current_app, renderer)(**kwargs).visit(\n            self))",
    "docstring": "Render the navigational item using a renderer.\n\n        :param renderer: An object implementing the :class:`~.Renderer`\n                         interface.\n        :return: A markupsafe string with the rendered result."
  },
  {
    "code": "def sql_get_oids(self, where=None):\n        table = self.lconfig.get('table')\n        db = self.lconfig.get('db_schema_name') or self.lconfig.get('db')\n        _oid = self.lconfig.get('_oid')\n        if is_array(_oid):\n            _oid = _oid[0]\n        sql = 'SELECT DISTINCT %s.%s FROM %s.%s' % (table, _oid, db, table)\n        if where:\n            where = [where] if isinstance(where, basestring) else list(where)\n            sql += ' WHERE %s' % ' OR '.join(where)\n        result = sorted([r[_oid] for r in self._load_sql(sql)])\n        return result",
    "docstring": "Query source database for a distinct list of oids."
  },
  {
    "code": "def update_proficiency(self, proficiency_form):\n        collection = JSONClientValidated('learning',\n                                         collection='Proficiency',\n                                         runtime=self._runtime)\n        if not isinstance(proficiency_form, ABCProficiencyForm):\n            raise errors.InvalidArgument('argument type is not an ProficiencyForm')\n        if not proficiency_form.is_for_update():\n            raise errors.InvalidArgument('the ProficiencyForm is for update only, not create')\n        try:\n            if self._forms[proficiency_form.get_id().get_identifier()] == UPDATED:\n                raise errors.IllegalState('proficiency_form already used in an update transaction')\n        except KeyError:\n            raise errors.Unsupported('proficiency_form did not originate from this session')\n        if not proficiency_form.is_valid():\n            raise errors.InvalidArgument('one or more of the form elements is invalid')\n        collection.save(proficiency_form._my_map)\n        self._forms[proficiency_form.get_id().get_identifier()] = UPDATED\n        return objects.Proficiency(\n            osid_object_map=proficiency_form._my_map,\n            runtime=self._runtime,\n            proxy=self._proxy)",
    "docstring": "Updates an existing proficiency.\n\n        arg:    proficiency_form (osid.learning.ProficiencyForm): the\n                form containing the elements to be updated\n        raise:  IllegalState - ``proficiency_form`` already used in an\n                update transaction\n        raise:  InvalidArgument - the form contains an invalid value\n        raise:  NullArgument - ``proficiency_form`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        raise:  Unsupported - ``proficiency_form`` did not originate\n                from ``get_proficiency_form_for_update()``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def make_tmp_name(name):\n    path, base = os.path.split(name)\n    tmp_base = \".tmp-%s-%s\" % (base, uuid4().hex)\n    tmp_name = os.path.join(path, tmp_base)\n    try:\n        yield tmp_name\n    finally:\n        safe_remove(tmp_name)",
    "docstring": "Generates a tmp name for a file or dir.\n\n    This is a tempname that sits in the same dir as `name`. If it exists on\n    disk at context exit time, it is deleted."
  },
  {
    "code": "def reorderbydf(df2,df1):\n    df3=pd.DataFrame()\n    for idx,row in df1.iterrows():\n        df3=df3.append(df2.loc[idx,:])\n    return df3",
    "docstring": "Reorder rows of a dataframe by other dataframe\n\n    :param df2: input dataframe\n    :param df1: template dataframe"
  },
  {
    "code": "def cctop_save_xml(jobid, outpath):\n    status = cctop_check_status(jobid=jobid)\n    if status == 'Finished':\n        result = 'http://cctop.enzim.ttk.mta.hu/php/result.php?jobId={}'.format(jobid)\n        result_text = requests.post(result)\n        with open(outpath, 'w') as f:\n            f.write(result_text.text)\n        return outpath\n    else:\n        raise ConnectionRefusedError('CCTOP job incomplete, status is \"{}\"'.format(status))",
    "docstring": "Save the CCTOP results file in XML format.\n\n    Args:\n        jobid (str): Job ID obtained when job was submitted\n        outpath (str): Path to output filename\n\n    Returns:\n        str: Path to output filename"
  },
  {
    "code": "def date_range(start=None, end=None, periods=None, freq=None, tz=None,\n               normalize=False, name=None, closed=None, **kwargs):\n    if freq is None and com._any_none(periods, start, end):\n        freq = 'D'\n    dtarr = DatetimeArray._generate_range(\n        start=start, end=end, periods=periods,\n        freq=freq, tz=tz, normalize=normalize,\n        closed=closed, **kwargs)\n    return DatetimeIndex._simple_new(\n        dtarr, tz=dtarr.tz, freq=dtarr.freq, name=name)",
    "docstring": "Return a fixed frequency DatetimeIndex.\n\n    Parameters\n    ----------\n    start : str or datetime-like, optional\n        Left bound for generating dates.\n    end : str or datetime-like, optional\n        Right bound for generating dates.\n    periods : integer, optional\n        Number of periods to generate.\n    freq : str or DateOffset, default 'D'\n        Frequency strings can have multiples, e.g. '5H'. See\n        :ref:`here <timeseries.offset_aliases>` for a list of\n        frequency aliases.\n    tz : str or tzinfo, optional\n        Time zone name for returning localized DatetimeIndex, for example\n        'Asia/Hong_Kong'. By default, the resulting DatetimeIndex is\n        timezone-naive.\n    normalize : bool, default False\n        Normalize start/end dates to midnight before generating date range.\n    name : str, default None\n        Name of the resulting DatetimeIndex.\n    closed : {None, 'left', 'right'}, optional\n        Make the interval closed with respect to the given frequency to\n        the 'left', 'right', or both sides (None, the default).\n    **kwargs\n        For compatibility. Has no effect on the result.\n\n    Returns\n    -------\n    rng : DatetimeIndex\n\n    See Also\n    --------\n    DatetimeIndex : An immutable container for datetimes.\n    timedelta_range : Return a fixed frequency TimedeltaIndex.\n    period_range : Return a fixed frequency PeriodIndex.\n    interval_range : Return a fixed frequency IntervalIndex.\n\n    Notes\n    -----\n    Of the four parameters ``start``, ``end``, ``periods``, and ``freq``,\n    exactly three must be specified. If ``freq`` is omitted, the resulting\n    ``DatetimeIndex`` will have ``periods`` linearly spaced elements between\n    ``start`` and ``end`` (closed on both sides).\n\n    To learn more about the frequency strings, please see `this link\n    <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.\n\n    Examples\n    --------\n    **Specifying the values**\n\n    The next four examples generate the same `DatetimeIndex`, but vary\n    the combination of `start`, `end` and `periods`.\n\n    Specify `start` and `end`, with the default daily frequency.\n\n    >>> pd.date_range(start='1/1/2018', end='1/08/2018')\n    DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n                   '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],\n                  dtype='datetime64[ns]', freq='D')\n\n    Specify `start` and `periods`, the number of periods (days).\n\n    >>> pd.date_range(start='1/1/2018', periods=8)\n    DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n                   '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],\n                  dtype='datetime64[ns]', freq='D')\n\n    Specify `end` and `periods`, the number of periods (days).\n\n    >>> pd.date_range(end='1/1/2018', periods=8)\n    DatetimeIndex(['2017-12-25', '2017-12-26', '2017-12-27', '2017-12-28',\n                   '2017-12-29', '2017-12-30', '2017-12-31', '2018-01-01'],\n                  dtype='datetime64[ns]', freq='D')\n\n    Specify `start`, `end`, and `periods`; the frequency is generated\n    automatically (linearly spaced).\n\n    >>> pd.date_range(start='2018-04-24', end='2018-04-27', periods=3)\n    DatetimeIndex(['2018-04-24 00:00:00', '2018-04-25 12:00:00',\n                   '2018-04-27 00:00:00'],\n                  dtype='datetime64[ns]', freq=None)\n\n    **Other Parameters**\n\n    Changed the `freq` (frequency) to ``'M'`` (month end frequency).\n\n    >>> pd.date_range(start='1/1/2018', periods=5, freq='M')\n    DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31', '2018-04-30',\n                   '2018-05-31'],\n                  dtype='datetime64[ns]', freq='M')\n\n    Multiples are allowed\n\n    >>> pd.date_range(start='1/1/2018', periods=5, freq='3M')\n    DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',\n                   '2019-01-31'],\n                  dtype='datetime64[ns]', freq='3M')\n\n    `freq` can also be specified as an Offset object.\n\n    >>> pd.date_range(start='1/1/2018', periods=5, freq=pd.offsets.MonthEnd(3))\n    DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',\n                   '2019-01-31'],\n                  dtype='datetime64[ns]', freq='3M')\n\n    Specify `tz` to set the timezone.\n\n    >>> pd.date_range(start='1/1/2018', periods=5, tz='Asia/Tokyo')\n    DatetimeIndex(['2018-01-01 00:00:00+09:00', '2018-01-02 00:00:00+09:00',\n                   '2018-01-03 00:00:00+09:00', '2018-01-04 00:00:00+09:00',\n                   '2018-01-05 00:00:00+09:00'],\n                  dtype='datetime64[ns, Asia/Tokyo]', freq='D')\n\n    `closed` controls whether to include `start` and `end` that are on the\n    boundary. The default includes boundary points on either end.\n\n    >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed=None)\n    DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04'],\n                  dtype='datetime64[ns]', freq='D')\n\n    Use ``closed='left'`` to exclude `end` if it falls on the boundary.\n\n    >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed='left')\n    DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03'],\n                  dtype='datetime64[ns]', freq='D')\n\n    Use ``closed='right'`` to exclude `start` if it falls on the boundary.\n\n    >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed='right')\n    DatetimeIndex(['2017-01-02', '2017-01-03', '2017-01-04'],\n                  dtype='datetime64[ns]', freq='D')"
  },
  {
    "code": "def schema_exists(cls, cur, schema_name):\n        cur.execute(\"SELECT EXISTS (SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}');\"\n                    .format(schema_name))\n        return cur.fetchone()[0]",
    "docstring": "Check if schema exists"
  },
  {
    "code": "def _oops_dump_state(self, ignore_remaining_data=False):\n        log_error(\"==Oops state dump\" + \"=\" * (30 - 17))\n        log_error(\"References: {0}\".format(self.references))\n        log_error(\"Stream seeking back at -16 byte (2nd line is an actual position!):\")\n        self.object_stream.seek(-16, os.SEEK_CUR)\n        position = self.object_stream.tell()\n        the_rest = self.object_stream.read()\n        if not ignore_remaining_data and len(the_rest):\n            log_error(\n                \"Warning!!!!: Stream still has {0} bytes left:\\n{1}\".format(\n                    len(the_rest), self._create_hexdump(the_rest, position)\n                )\n            )\n        log_error(\"=\" * 30)",
    "docstring": "Log a deserialization error\n\n        :param ignore_remaining_data: If True, don't log an error when\n                                      unused trailing bytes are remaining"
  },
  {
    "code": "def addSource(self, source, data):\n    self._aggregate(source, self._aggregators, data, self._result)",
    "docstring": "Adds the given source's stats."
  },
  {
    "code": "def check_signature_supported(func, warn=False):\n    function_name = func.__name__\n    sig_params = get_signature_params(func)\n    has_kwargs_param = False\n    has_kwonly_param = False\n    for keyword_name, parameter in sig_params:\n        if parameter.kind == Parameter.VAR_KEYWORD:\n            has_kwargs_param = True\n        if parameter.kind == Parameter.KEYWORD_ONLY:\n            has_kwonly_param = True\n    if has_kwargs_param:\n        message = (\"The function {} has a **kwargs argument, which is \"\n                   \"currently not supported.\".format(function_name))\n        if warn:\n            logger.warning(message)\n        else:\n            raise Exception(message)\n    if has_kwonly_param:\n        message = (\"The function {} has a keyword only argument \"\n                   \"(defined after * or *args), which is currently \"\n                   \"not supported.\".format(function_name))\n        if warn:\n            logger.warning(message)\n        else:\n            raise Exception(message)",
    "docstring": "Check if we support the signature of this function.\n\n    We currently do not allow remote functions to have **kwargs. We also do not\n    support keyword arguments in conjunction with a *args argument.\n\n    Args:\n        func: The function whose signature should be checked.\n        warn: If this is true, a warning will be printed if the signature is\n            not supported. If it is false, an exception will be raised if the\n            signature is not supported.\n\n    Raises:\n        Exception: An exception is raised if the signature is not supported."
  },
  {
    "code": "def infer_axes(self):\n        s = self.storable\n        if s is None:\n            return False\n        self.get_attrs()\n        return True",
    "docstring": "infer the axes of my storer\n              return a boolean indicating if we have a valid storer or not"
  },
  {
    "code": "def flush(self):\n        self.log.info('Flushing tables and arrays to disk...')\n        for tab in self._tables.values():\n            tab.flush()\n        self._write_ndarrays_cache_to_disk()",
    "docstring": "Flush tables and arrays to disk"
  },
  {
    "code": "def readdir(self, tid, fh):\n        ret = []\n        pt = self.PathType.get(tid)\n        try:\n            if pt is self.PathType.main:\n                ret = list(self.searches)\n            elif pt is self.PathType.subdir:\n                ret = list(self.searches[tid[0]])\n            elif pt is self.PathType.file:\n                raise FuseOSError(errno.ENOTDIR)\n            else:\n                raise FuseOSError(errno.ENOENT)\n        except KeyError:\n            raise FuseOSError(errno.ENOENT)\n        return ['.', '..'] + ret",
    "docstring": "Read directory contents. Lists visible elements of ``YTActions`` object.\n\n        Parameters\n        ----------\n        tid : str\n            Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator.\n        fh : int\n            File descriptor. Ommited in the function body.\n\n        Returns\n        -------\n        list\n            List of filenames, wich will be shown as directory content."
  },
  {
    "code": "def get_running():\n    ret = set()\n    out = __salt__['cmd.run'](\n        _systemctl_cmd('--full --no-legend --no-pager'),\n        python_shell=False,\n        ignore_retcode=True)\n    for line in salt.utils.itertools.split(out, '\\n'):\n        try:\n            comps = line.strip().split()\n            fullname = comps[0]\n            if len(comps) > 3:\n                active_state = comps[3]\n        except ValueError as exc:\n            log.error(exc)\n            continue\n        else:\n            if active_state != 'running':\n                continue\n        try:\n            unit_name, unit_type = fullname.rsplit('.', 1)\n        except ValueError:\n            continue\n        if unit_type in VALID_UNIT_TYPES:\n            ret.add(unit_name if unit_type == 'service' else fullname)\n    return sorted(ret)",
    "docstring": "Return a list of all running services, so far as systemd is concerned\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' service.get_running"
  },
  {
    "code": "def get_monomers(self, ligands=True):\n        if ligands and self.ligands:\n            monomers = self._monomers + self.ligands._monomers\n        else:\n            monomers = self._monomers\n        return iter(monomers)",
    "docstring": "Retrieves all the `Monomers` from the AMPAL object.\n\n        Parameters\n        ----------\n        ligands : bool, optional\n            If true, will include ligand `Monomers`."
  },
  {
    "code": "def _listitemify(self, item):\n        info_type = self.info_type if hasattr(self, 'info_type') else 'video'\n        if not hasattr(item, 'as_tuple'):\n            if 'info_type' not in item.keys():\n                item['info_type'] = info_type\n            item = xbmcswift2.ListItem.from_dict(**item)\n        return item",
    "docstring": "Creates an xbmcswift2.ListItem if the provided value for item is a\n        dict. If item is already a valid xbmcswift2.ListItem, the item is\n        returned unmodified."
  },
  {
    "code": "def get_role_model():\n    app_model = getattr(settings, \"ARCTIC_ROLE_MODEL\", \"arctic.Role\")\n    try:\n        return django_apps.get_model(app_model)\n    except ValueError:\n        raise ImproperlyConfigured(\n            \"ARCTIC_ROLE_MODEL must be of the \" \"form 'app_label.model_name'\"\n        )\n    except LookupError:\n        raise ImproperlyConfigured(\n            \"ARCTIC_ROLE_MODEL refers to model '%s' that has not been \"\n            \"installed\" % settings.ARCTIC_ROLE_MODEL\n        )",
    "docstring": "Returns the Role model that is active in this project."
  },
  {
    "code": "def retrieve_nodes(self):\n        self.verbose('retrieving nodes from old mysql DB...')\n        self.old_nodes = list(OldNode.objects.all())\n        self.message('retrieved %d nodes' % len(self.old_nodes))",
    "docstring": "retrieve nodes from old mysql DB"
  },
  {
    "code": "def is_serializable_type(type_):\n    if not inspect.isclass(type_):\n      return Serializable.is_serializable(type_)\n    return issubclass(type_, Serializable) or hasattr(type_, '_asdict')",
    "docstring": "Return `True` if the given type's instances conform to the Serializable protocol.\n\n    :rtype: bool"
  },
  {
    "code": "def find_maximum(self, scores, N, k_choices):\n        if not isinstance(scores, np.ndarray):\n            raise TypeError(\"Scores input is not a numpy array\")\n        index_of_maximum = int(scores.argmax())\n        maximum_combo = self.nth(combinations(\n            list(range(N)), k_choices), index_of_maximum, None)\n        return sorted(maximum_combo)",
    "docstring": "Finds the `k_choices` maximum scores from `scores`\n\n        Arguments\n        ---------\n        scores : numpy.ndarray\n        N : int\n        k_choices : int\n\n        Returns\n        -------\n        list"
  },
  {
    "code": "def reverse_dictionary(d):\n    rev_d = {}\n    [rev_d.update({v:k}) for k, v in d.items()]\n    return rev_d",
    "docstring": "Reverses the key value pairs for a given dictionary.\n\n    Parameters\n    ----------\n    d : :obj:`dict`\n        dictionary to reverse\n\n    Returns\n    -------\n    :obj:`dict`\n        dictionary with keys and values swapped"
  },
  {
    "code": "def match_ancestor_objective_id(self, objective_id=None, match=None):\n        if match:\n            self._add_match('ancestorObjectiveId', objective_id)\n        else:\n            raise errors.Unimplemented()",
    "docstring": "Sets the objective ``Id`` for this query to match objectives that have the specified objective as an ancestor.\n\n        arg:    objective_id (osid.id.Id): an objective ``Id``\n        arg:    match (boolean): ``true`` for a positive match,\n                ``false`` for a negative match\n        raise:  NullArgument - ``objective_id`` is ``null``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def add_context(self, name, indices, level=None):\n        self._validate_context((name, indices))\n        if level is None:\n            level = len(self.contexts_ranked)\n        self.contexts_ranked.insert(level, name)\n        self.contexts[name] = indices",
    "docstring": "Add a new context level to the hierarchy.\n\n        By default, new contexts are added to the lowest level of the hierarchy.\n        To insert the context elsewhere in the hierarchy, use the ``level``\n        argument. For example, ``level=0`` would insert the context at the\n        highest level of the hierarchy.\n\n        Parameters\n        ----------\n        name : str\n        indices : list\n            Token indices at which each chunk in the context begins.\n        level : int\n            Level in the hierarchy at which to insert the context. By default,\n            inserts context at the lowest level of the hierarchy"
  },
  {
    "code": "def parallel_progbar(mapper, iterable, nprocs=None, starmap=False, flatmap=False, shuffle=False,\n                     verbose=True, verbose_flatmap=None, **kwargs):\n    results = _parallel_progbar_launch(mapper, iterable, nprocs, starmap, flatmap, shuffle, verbose, verbose_flatmap, **kwargs)\n    return [x for i, x in sorted(results, key=lambda p: p[0])]",
    "docstring": "Performs a parallel mapping of the given iterable, reporting a progress bar as values get returned\n\n    :param mapper: The mapping function to apply to elements of the iterable\n    :param iterable: The iterable to map\n    :param nprocs: The number of processes (defaults to the number of cpu's)\n    :param starmap: If true, the iterable is expected to contain tuples and the mapper function gets each element of a\n        tuple as an argument\n    :param flatmap: If true, flatten out the returned values if the mapper function returns a list of objects\n    :param shuffle: If true, randomly sort the elements before processing them. This might help provide more uniform\n        runtimes if processing different objects takes different amounts of time.\n    :param verbose: Whether or not to print the progress bar\n    :param verbose_flatmap: If performing a flatmap, whether or not to report each object as it's returned\n    :param kwargs: Any other keyword arguments to pass to the progress bar (see ``progbar``)\n    :return: A list of the returned objects, in the same order as provided"
  },
  {
    "code": "def get_snmp_from_host2(self):\n        if not self.snmp2:\n            self.activity_value2 = None\n        else:\n            response = self.snmp2.get_oids(activity_oid)\n            self.activity_value2 = activity[int(response[0])]",
    "docstring": "Get SNMP values from 2nd host."
  },
  {
    "code": "def build(self, build_dir, **kwargs):\n        del kwargs\n        args = [\"cmake\", \"--build\", build_dir]\n        args.extend(self._get_build_flags())\n        return [{\"args\": args}]",
    "docstring": "This function builds the cmake build command."
  },
  {
    "code": "def get_features(self, yam):\n        mcap = [ c for c in self.capabilities\n                 if c.parameters.get(\"module\", None) == yam ][0]\n        if not mcap.parameters.get(\"features\"): return []\n        return mcap.parameters[\"features\"].split(\",\")",
    "docstring": "Return list of features declared for module `yam`."
  },
  {
    "code": "def constraint_to_si(expr):\n    satisfiable = True\n    replace_list = [ ]\n    satisfiable, replace_list = backends.vsa.constraint_to_si(expr)\n    for i in xrange(len(replace_list)):\n        ori, new = replace_list[i]\n        if not isinstance(new, Base):\n            new = BVS(new.name, new._bits, min=new._lower_bound, max=new._upper_bound, stride=new._stride, explicit_name=True)\n            replace_list[i] = (ori, new)\n    return satisfiable, replace_list",
    "docstring": "Convert a constraint to SI if possible.\n\n    :param expr:\n    :return:"
  },
  {
    "code": "def get_assessment_offered_bank_assignment_session(self, proxy):\n        if not self.supports_assessment_offered_bank_assignment():\n            raise errors.Unimplemented()\n        return sessions.AssessmentOfferedBankAssignmentSession(proxy=proxy, runtime=self._runtime)",
    "docstring": "Gets the session for assigning offered assessments to bank mappings.\n\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.assessment.AssessmentOfferedBankAssignmentSession)\n                - an ``AssessmentOfferedBankAssignmentSession``\n        raise:  NullArgument - ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented -\n                ``supports_assessment_offered_bank_assignment()`` is\n                ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_assessment_offered_bank_assignment()`` is ``true``.*"
  },
  {
    "code": "def section_branch_orders(neurites, neurite_type=NeuriteType.all):\n    return map_sections(sectionfunc.branch_order, neurites, neurite_type=neurite_type)",
    "docstring": "section branch orders in a collection of neurites"
  },
  {
    "code": "async def is_bot(self):\n        if self._bot is None:\n            self._bot = (await self.get_me()).bot\n        return self._bot",
    "docstring": "Return ``True`` if the signed-in user is a bot, ``False`` otherwise."
  },
  {
    "code": "def sub_for(expr, substitutions):\n    mapping = {k.op(): v for k, v in substitutions}\n    substitutor = Substitutor()\n    return substitutor.substitute(expr, mapping)",
    "docstring": "Substitute subexpressions in `expr` with expression to expression\n    mapping `substitutions`.\n\n    Parameters\n    ----------\n    expr : ibis.expr.types.Expr\n        An Ibis expression\n    substitutions : List[Tuple[ibis.expr.types.Expr, ibis.expr.types.Expr]]\n        A mapping from expression to expression. If any subexpression of `expr`\n        is equal to any of the keys in `substitutions`, the value for that key\n        will replace the corresponding expression in `expr`.\n\n    Returns\n    -------\n    ibis.expr.types.Expr\n        An Ibis expression"
  },
  {
    "code": "def _dispatch(self, tree):\n        \"_dispatcher function, _dispatching tree type T to method _T.\"\n        if isinstance(tree, list):\n            for t in tree:\n                self._dispatch(t)\n            return\n        meth = getattr(self, \"_\"+tree.__class__.__name__)\n        if tree.__class__.__name__ == 'NoneType' and not self._do_indent:\n            return\n        meth(tree)",
    "docstring": "_dispatcher function, _dispatching tree type T to method _T."
  },
  {
    "code": "def update_share(self, share_id, **kwargs):\n        perms = kwargs.get('perms', None)\n        password = kwargs.get('password', None)\n        public_upload = kwargs.get('public_upload', None)\n        if (isinstance(perms, int)) and (perms > self.OCS_PERMISSION_ALL):\n            perms = None\n        if not (perms or password or (public_upload is not None)):\n            return False\n        if not isinstance(share_id, int):\n            return False\n        data = {}\n        if perms:\n            data['permissions'] = perms\n        if isinstance(password, six.string_types):\n            data['password'] = password\n        if (public_upload is not None) and (isinstance(public_upload, bool)):\n            data['publicUpload'] = str(public_upload).lower()\n        res = self._make_ocs_request(\n            'PUT',\n            self.OCS_SERVICE_SHARE,\n            'shares/' + str(share_id),\n            data=data\n        )\n        if res.status_code == 200:\n            return True\n        raise HTTPResponseError(res)",
    "docstring": "Updates a given share\n\n        :param share_id: (int) Share ID\n        :param perms: (int) update permissions (see share_file_with_user() below)\n        :param password: (string) updated password for public link Share\n        :param public_upload: (boolean) enable/disable public upload for public shares\n        :returns: True if the operation succeeded, False otherwise\n        :raises: HTTPResponseError in case an HTTP error status was returned"
  },
  {
    "code": "def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):\n    num = int(num)\n    start = start * 1.\n    stop = stop * 1.\n    if num <= 0:\n        return []\n    if endpoint:\n        if num == 1:\n            return [start]\n        step = (stop-start)/float((num-1))\n        if num == 1:\n            step = nan\n        y = [start]\n        for _ in range(num-2):\n            y.append(y[-1] + step)\n        y.append(stop)\n    else:\n        step = (stop-start)/float(num)\n        if num == 1:\n            step = nan\n        y = [start]\n        for _ in range(num-1):\n            y.append(y[-1] + step)\n    if retstep:\n        return y, step\n    else:\n        return y",
    "docstring": "Port of numpy's linspace to pure python. Does not support dtype, and \n    returns lists of floats."
  },
  {
    "code": "def legislator_vote_value(self):\n        if not hasattr(self, 'legislator'):\n            msg = ('legislator_vote_value can only be called '\n                   'from a vote accessed by legislator.votes_manager.')\n            raise ValueError(msg)\n        leg_id = self.legislator.id\n        for k in ('yes', 'no', 'other'):\n            for leg in self[k + '_votes']:\n                if leg['leg_id'] == leg_id:\n                    return k",
    "docstring": "If this vote was accessed through the legislator.votes_manager,\n        return the value of this legislator's vote."
  },
  {
    "code": "def transfer(self, data):\n        settings = self.transfer_settings\n        settings.spi_tx_size = len(data)\n        self.transfer_settings = settings\n        response = ''\n        for i in range(0, len(data), 60):\n            response += self.sendCommand(commands.SPITransferCommand(data[i:i + 60])).data\n            time.sleep(0.01)\n        while len(response) < len(data):\n            response += self.sendCommand(commands.SPITransferCommand('')).data\n        return ''.join(response)",
    "docstring": "Transfers data over SPI.\n\n        Arguments:\n            data: The data to transfer.\n\n        Returns:\n            The data returned by the SPI device."
  },
  {
    "code": "def kill_cursor(self, cursor):\n        text = cursor.selectedText()\n        if text:\n            cursor.removeSelectedText()\n            self.kill(text)",
    "docstring": "Kills the text selected by the give cursor."
  },
  {
    "code": "def close_compute_projects(self, compute):\n        for project in self._projects.values():\n            if compute in project.computes:\n                yield from project.close()",
    "docstring": "Close projects running on a compute"
  },
  {
    "code": "def post_helper(form_tag=True, edit_mode=False):\n    helper = FormHelper()\n    helper.form_action = '.'\n    helper.attrs = {'data_abide': ''}\n    helper.form_tag = form_tag\n    fieldsets = [\n        Row(\n            Column(\n                'text',\n                css_class='small-12'\n            ),\n        ),\n    ]\n    if not edit_mode:\n        fieldsets.append(\n            Row(\n                Column(\n                    'threadwatch',\n                    css_class='small-12'\n                ),\n            ),\n        )\n    fieldsets = fieldsets+[\n        ButtonHolderPanel(\n            Submit('submit', _('Submit')),\n            css_class='text-right',\n        ),\n    ]\n    helper.layout = Layout(*fieldsets)\n    return helper",
    "docstring": "Post's form layout helper"
  },
  {
    "code": "def install_deny_hook(api):\n    if api == USED_API:\n        raise ValueError\n    sys.meta_path.insert(0, ImportHookDeny(api))",
    "docstring": "Install a deny import hook for Qt api.\n\n    Parameters\n    ----------\n    api : str\n        The Qt api whose import should be prevented\n\n    Example\n    -------\n    >>> install_deny_import(\"pyqt4\")\n    >>> import PyQt4\n    Traceback (most recent call last):...\n    ImportError: Import of PyQt4 is denied."
  },
  {
    "code": "def build_single_handler_applications(paths, argvs=None):\n    applications = {}\n    argvs = {} or argvs\n    for path in paths:\n        application = build_single_handler_application(path, argvs.get(path, []))\n        route = application.handlers[0].url_path()\n        if not route:\n            if '/' in applications:\n                raise RuntimeError(\"Don't know the URL path to use for %s\" % (path))\n            route = '/'\n        applications[route] = application\n    return applications",
    "docstring": "Return a dictionary mapping routes to Bokeh applications built using\n    single handlers, for specified files or directories.\n\n    This function iterates over ``paths`` and ``argvs`` and calls\n    :func:`~bokeh.command.util.build_single_handler_application` on each\n    to generate the mapping.\n\n    Args:\n        path (seq[str]) : paths to files or directories for creating Bokeh\n            applications.\n\n        argvs (dict[str, list[str]], optional) : mapping of paths to command\n            line arguments to pass to the handler for each path\n\n    Returns:\n        dict[str, Application]\n\n    Raises:\n        RuntimeError"
  },
  {
    "code": "def from_span(cls, inputs, window_length, span, **kwargs):\n        if span <= 1:\n            raise ValueError(\n                \"`span` must be a positive number. %s was passed.\" % span\n            )\n        decay_rate = (1.0 - (2.0 / (1.0 + span)))\n        assert 0.0 < decay_rate <= 1.0\n        return cls(\n            inputs=inputs,\n            window_length=window_length,\n            decay_rate=decay_rate,\n            **kwargs\n        )",
    "docstring": "Convenience constructor for passing `decay_rate` in terms of `span`.\n\n        Forwards `decay_rate` as `1 - (2.0 / (1 + span))`.  This provides the\n        behavior equivalent to passing `span` to pandas.ewma.\n\n        Examples\n        --------\n        .. code-block:: python\n\n            # Equivalent to:\n            # my_ewma = EWMA(\n            #    inputs=[EquityPricing.close],\n            #    window_length=30,\n            #    decay_rate=(1 - (2.0 / (1 + 15.0))),\n            # )\n            my_ewma = EWMA.from_span(\n                inputs=[EquityPricing.close],\n                window_length=30,\n                span=15,\n            )\n\n        Notes\n        -----\n        This classmethod is provided by both\n        :class:`ExponentialWeightedMovingAverage` and\n        :class:`ExponentialWeightedMovingStdDev`."
  },
  {
    "code": "def load(self, name=None, *args, **kwargs):\n        \"Load the instance of the object from the stash.\"\n        inst = self.stash.load(name)\n        if inst is None:\n            inst = self.instance(name, *args, **kwargs)\n        logger.debug(f'loaded (conf mng) instance: {inst}')\n        return inst",
    "docstring": "Load the instance of the object from the stash."
  },
  {
    "code": "def search(query, query_type=DEFAULT_QUERY_TYPE):\n    statement, arguments = _build_search(query)\n    if statement is None and arguments is None:\n        return QueryResults([], [], 'AND')\n    with db_connect() as db_connection:\n        with db_connection.cursor() as cursor:\n            cursor.execute(statement, arguments)\n            search_results = cursor.fetchall()\n    return QueryResults(search_results, query, query_type)",
    "docstring": "Search database using parsed query.\n\n    Executes a database search query from the given ``query``\n    (a ``Query`` object) and optionally accepts a list of search weights.\n    By default, the search results are ordered by weight.\n\n    :param query: containing terms, filters, and sorts.\n    :type query: Query\n    :returns: a sequence of records that match the query conditions\n    :rtype: QueryResults (which is a sequence of QueryRecord objects)"
  },
  {
    "code": "def get_png_data_url(blob: Optional[bytes]) -> str:\n    return BASE64_PNG_URL_PREFIX + base64.b64encode(blob).decode('ascii')",
    "docstring": "Converts a PNG blob into a local URL encapsulating the PNG."
  },
  {
    "code": "def cluster_get_keys_in_slots(self, slot, count, *, encoding):\n        return self.execute(b'CLUSTER', b'GETKEYSINSLOT', slot, count,\n                            encoding=encoding)",
    "docstring": "Return local key names in the specified hash slot."
  },
  {
    "code": "def get_recirc_content(self, published=True, count=3):\n        query = self.get_query()\n        if not query.get('included_ids'):\n            qs = Content.search_objects.search()\n            qs = qs.query(\n                TagBoost(slugs=self.tags.values_list(\"slug\", flat=True))\n            ).filter(\n                ~Ids(values=[self.id])\n            ).sort(\n                \"_score\"\n            )\n            return qs[:count]\n        query['included_ids'] = query['included_ids'][:count]\n        search = custom_search_model(Content, query, published=published, field_map={\n            \"feature_type\": \"feature_type.slug\",\n            \"tag\": \"tags.slug\",\n            \"content-type\": \"_type\"\n        })\n        return search",
    "docstring": "gets the first 3 content objects in the `included_ids`"
  },
  {
    "code": "def rescale(self, fun):\n        if self.bands != 1:\n            raise ValueError('only single band images are currently supported')\n        mat = self.matrix()\n        scaled = fun(mat)\n        self.assign(scaled, band=0)",
    "docstring": "perform raster computations with custom functions and assign them to the existing raster object in memory\n\n        Parameters\n        ----------\n        fun: function\n            the custom function to compute on the data\n\n        Examples\n        --------\n        >>> with Raster('filename') as ras:\n        >>>     ras.rescale(lambda x: 10 * x)"
  },
  {
    "code": "def data_duration(self, data):\n        lengths = []\n        for key in self._time:\n            for idx in self._time.get(key, []):\n                lengths.append(data[key].shape[idx])\n        return min(lengths)",
    "docstring": "Compute the valid data duration of a dict\n\n        Parameters\n        ----------\n        data : dict\n            As produced by pumpp.transform\n\n        Returns\n        -------\n        length : int\n            The minimum temporal extent of a dynamic observation in data"
  },
  {
    "code": "def get_3_3_tuple_list(self,obj,default=None):\n        if is_sequence3(obj):\n            return [self.get_3_3_tuple(o,default) for o in obj]\n        return [self.get_3_3_tuple(obj,default)]",
    "docstring": "Return list of 3x3-tuples."
  },
  {
    "code": "def get_block_type(self, def_id):\n        try:\n            return self._definitions[def_id]\n        except KeyError:\n            try:\n                return def_id.aside_type\n            except AttributeError:\n                raise NoSuchDefinition(repr(def_id))",
    "docstring": "Get a block_type by its definition id."
  },
  {
    "code": "def download(self, url, output_path):\n        request_failed_message = self.tr(\n            \"Can't access PetaBencana API: {source}\").format(\n            source=url)\n        downloader = FileDownloader(url, output_path)\n        result, message = downloader.download()\n        if not result:\n            display_warning_message_box(\n                self,\n                self.tr('Download error'),\n                self.tr(request_failed_message + '\\n' + message))\n        if result == QNetworkReply.OperationCanceledError:\n            display_warning_message_box(\n                self,\n                self.tr('Download error'),\n                self.tr(message))",
    "docstring": "Download file from API url and write to output path.\n\n        :param url: URL of the API.\n        :type url: str\n\n        :param output_path: Path of output file,\n        :type output_path: str"
  },
  {
    "code": "def parse_opera (url_data):\n    from ..bookmarks.opera import parse_bookmark_data\n    for url, name, lineno in parse_bookmark_data(url_data.get_content()):\n        url_data.add_url(url, line=lineno, name=name)",
    "docstring": "Parse an opera bookmark file."
  },
  {
    "code": "def assign_to_all_link_group(self, group=0x01):\n        msg = StandardSend(self._address,\n                           COMMAND_ASSIGN_TO_ALL_LINK_GROUP_0X01_NONE,\n                           cmd2=group)\n        self._send_msg(msg)",
    "docstring": "Assign a device to an All-Link Group.\n\n        The default is group 0x01."
  },
  {
    "code": "def insert(self, iterable, data=None, weight=1.0):\n        self.root.insert(iterable, index=0, data=data, weight=1.0)",
    "docstring": "Used to insert into he root node\n\n        Args\n            iterable(hashable): index or key used to identify\n            data(object): data to be paired with the key"
  },
  {
    "code": "def cli(ctx, config, debug):\n    ctx.obj['config'] = config\n    ctx.obj['engine'] = stex.SnakeTeX(config_file=config, debug=debug)",
    "docstring": "SnakTeX command line interface - write LaTeX faster through templating."
  },
  {
    "code": "def parse(cls, msg):\n        lines = msg.splitlines()\n        method, uri, version = lines[0].split()\n        headers = cls.parse_headers('\\r\\n'.join(lines[1:]))\n        return cls(version=version, uri=uri, method=method, headers=headers)",
    "docstring": "Parse message string to request object."
  },
  {
    "code": "def job_data(job_id):\n    job_dict = db.get_job(job_id)\n    if not job_dict:\n        return json.dumps({'error': 'job_id not found'}), 404, headers\n    if not is_authorized(job_dict):\n        return json.dumps({'error': 'not authorized'}), 403, headers\n    if job_dict['error']:\n        return json.dumps({'error': job_dict['error']}), 409, headers\n    content_type = job_dict['metadata'].get('mimetype')\n    return flask.Response(job_dict['data'], mimetype=content_type)",
    "docstring": "Get the raw data that the job returned. The mimetype\n    will be the value provided in the metdata for the key ``mimetype``.\n\n    **Results:**\n\n    :rtype: string\n\n    :statuscode 200: no error\n    :statuscode 403: not authorized to view the job's data\n    :statuscode 404: job id not found\n    :statuscode 409: an error occurred"
  },
  {
    "code": "def add_scanner_param(self, name, scanner_param):\n        assert name\n        assert scanner_param\n        self.scanner_params[name] = scanner_param\n        command = self.commands.get('start_scan')\n        command['elements'] = {\n            'scanner_params':\n                {k: v['name'] for k, v in self.scanner_params.items()}}",
    "docstring": "Add a scanner parameter."
  },
  {
    "code": "def build_sensors_list(self, type):\n        ret = []\n        if type == SENSOR_TEMP_UNIT and self.init_temp:\n            input_list = self.stemps\n            self.stemps = psutil.sensors_temperatures()\n        elif type == SENSOR_FAN_UNIT and self.init_fan:\n            input_list = self.sfans\n            self.sfans = psutil.sensors_fans()\n        else:\n            return ret\n        for chipname, chip in iteritems(input_list):\n            i = 1\n            for feature in chip:\n                sensors_current = {}\n                if feature.label == '':\n                    sensors_current['label'] = chipname + ' ' + str(i)\n                else:\n                    sensors_current['label'] = feature.label\n                sensors_current['value'] = int(feature.current)\n                sensors_current['unit'] = type\n                ret.append(sensors_current)\n                i += 1\n        return ret",
    "docstring": "Build the sensors list depending of the type.\n\n        type: SENSOR_TEMP_UNIT or SENSOR_FAN_UNIT\n\n        output: a list"
  },
  {
    "code": "def _find_playlist(self):\n        data = None\n        if self.id:\n            data = self.connection.get_item(\n                'find_playlist_by_id', playlist_id=self.id)\n        elif self.reference_id:\n            data = self.connection.get_item(\n                'find_playlist_by_reference_id',\n                reference_id=self.reference_id)\n        if data:\n            self._load(data)",
    "docstring": "Internal method to populate the object given the ``id`` or\n        ``reference_id`` that has been set in the constructor."
  },
  {
    "code": "def process_delta(delta):\n    kwargs = {\n        \"type\": delta[\"type\"],\n        \"date\": datetime.datetime.utcfromtimestamp(delta[\"date\"]),\n        \"object_id\": delta[\"object_data\"][\"id\"],\n    }\n    print(\" * {type} at {date} with ID {object_id}\".format(**kwargs))",
    "docstring": "This is the part of the code where you would process the information\n    from the webhook notification. Each delta is one change that happened,\n    and might require fetching message IDs, updating your database,\n    and so on.\n\n    However, because this is just an example project, we'll just print\n    out information about the notification, so you can see what\n    information is being sent."
  },
  {
    "code": "def _buildDict(self):\n        lexDict = {}\n        with io.open(self.islePath, \"r\", encoding='utf-8') as fd:\n            wordList = [line.rstrip('\\n') for line in fd]\n        for row in wordList:\n            word, pronunciation = row.split(\" \", 1)\n            word, extraInfo = word.split(\"(\", 1)\n            extraInfo = extraInfo.replace(\")\", \"\")\n            extraInfoList = [segment for segment in extraInfo.split(\",\")\n                             if (\"_\" not in segment and \"+\" not in segment and\n                                 ':' not in segment and segment != '')]\n            lexDict.setdefault(word, [])\n            lexDict[word].append((pronunciation, extraInfoList))\n        return lexDict",
    "docstring": "Builds the isle textfile into a dictionary for fast searching"
  },
  {
    "code": "def __parse_affiliations_yml(self, affiliations):\n        enrollments = []\n        for aff in affiliations:\n            name = self.__encode(aff['organization'])\n            if not name:\n                error = \"Empty organization name\"\n                msg = self.GRIMOIRELAB_INVALID_FORMAT % {'error': error}\n                raise InvalidFormatError(cause=msg)\n            elif name.lower() == 'unknown':\n                continue\n            org = Organization(name=name)\n            if org is None:\n                continue\n            if 'start' in aff:\n                start_date = self.__force_datetime(aff['start'])\n            else:\n                start_date = MIN_PERIOD_DATE\n            if 'end' in aff:\n                end_date = self.__force_datetime(aff['end'])\n            else:\n                end_date = MAX_PERIOD_DATE\n            enrollment = Enrollment(start=start_date, end=end_date,\n                                    organization=org)\n            enrollments.append(enrollment)\n        self.__validate_enrollment_periods(enrollments)\n        return enrollments",
    "docstring": "Parse identity's affiliations from a yaml dict."
  },
  {
    "code": "def convex_hull(self):\n        if self._faces is None:\n            if self._vertices is None:\n                return None\n            self.triangulate()\n        return self._convex_hull",
    "docstring": "Return an array of vertex indexes representing the convex hull.\n\n        If faces have not been computed for this mesh, the function\n        computes them.\n        If no vertices or faces are specified, the function returns None."
  },
  {
    "code": "def _init_message(self):\n        try:\n            self.message = compat.text_type(self.error)\n        except UnicodeError:\n            try:\n                self.message = str(self.error)\n            except UnicodeEncodeError:\n                self.message = self.error.args[0]\n        if not isinstance(self.message, compat.text_type):\n            self.message = compat.text_type(self.message, 'ascii', 'replace')",
    "docstring": "Find a unicode representation of self.error"
  },
  {
    "code": "def skip(self, length):\n        if length >= self.__size:\n            skip_amount = self.__size\n            rem = length - skip_amount\n            self.__segments.clear()\n            self.__offset = 0\n            self.__size = 0\n            self.position += skip_amount\n        else:\n            rem = 0\n            self.read(length, skip=True)\n        return rem",
    "docstring": "Removes ``length`` bytes and returns the number length still required to skip"
  },
  {
    "code": "def _mosaik_args_from_config(config):\n    multi_mappers = config[\"algorithm\"].get(\"multiple_mappers\", True)\n    multi_flags = [\"-m\", \"all\"] if multi_mappers else [\"-m\", \"unique\"]\n    error_flags = [\"-mm\", \"2\"]\n    num_cores = config[\"algorithm\"].get(\"num_cores\", 1)\n    core_flags = [\"-p\", str(num_cores)] if num_cores > 1 else []\n    return core_flags + multi_flags + error_flags",
    "docstring": "Configurable high level options for mosaik."
  },
  {
    "code": "def get_pub_str(self, name='master'):\n        path = os.path.join(self.opts['pki_dir'],\n                            name + '.pub')\n        if not os.path.isfile(path):\n            key = self.__get_keys()\n            if HAS_M2:\n                key.save_pub_key(path)\n            else:\n                with salt.utils.files.fopen(path, 'wb+') as wfh:\n                    wfh.write(key.publickey().exportKey('PEM'))\n        with salt.utils.files.fopen(path) as rfh:\n            return rfh.read()",
    "docstring": "Return the string representation of a public key\n        in the pki-directory"
  },
  {
    "code": "def setup_config(epab_version: str):\n    logger = logging.getLogger('EPAB')\n    logger.debug('setting up config')\n    elib_config.ELIBConfig.setup(\n        app_name='EPAB',\n        app_version=epab_version,\n        config_file_path='pyproject.toml',\n        config_sep_str='__',\n        root_path=['tool', 'epab']\n    )\n    elib_config.write_example_config('pyproject.toml.example')\n    if not pathlib.Path('pyproject.toml').exists():\n        raise FileNotFoundError('pyproject.toml')\n    elib_config.validate_config()",
    "docstring": "Set up elib_config package\n\n    :param epab_version: installed version of EPAB as as string"
  },
  {
    "code": "def start(self, container, instances=None, map_name=None, **kwargs):\n        return self.run_actions('start', container, instances=instances, map_name=map_name, **kwargs)",
    "docstring": "Starts instances for a container configuration.\n\n        :param container: Container name.\n        :type container: unicode | str\n        :param instances: Instance names to start. If not specified, will start all instances as specified in the\n         configuration (or just one default instance).\n        :param map_name: Container map name. Optional - if not provided the default map is used.\n        :type map_name: unicode | str\n        :type instances: collections.Iterable[unicode | str | NoneType]\n        :param kwargs: Additional kwargs. If multiple actions are resulting from this, they will only be applied to\n          the main container start.\n        :return: Return values of started containers.\n        :rtype: list[dockermap.map.runner.ActionOutput]"
  },
  {
    "code": "def connect_redis(redis_client, name=None, transaction=False):\n    return ConnectionManager.connect_redis(\n        redis_client=redis_client, name=name, transaction=transaction)",
    "docstring": "Connect your redis-py instance to redpipe.\n\n    Example:\n\n    .. code:: python\n\n        redpipe.connect_redis(redis.StrictRedis(), name='users')\n\n\n    Do this during your application bootstrapping.\n\n    You can also pass a redis-py-cluster instance to this method.\n\n    .. code:: python\n\n        redpipe.connect_redis(rediscluster.StrictRedisCluster(), name='users')\n\n\n    You are allowed to pass in either the strict or regular instance.\n\n    .. code:: python\n\n        redpipe.connect_redis(redis.StrictRedis(), name='a')\n        redpipe.connect_redis(redis.Redis(), name='b')\n        redpipe.connect_redis(rediscluster.StrictRedisCluster(...), name='c')\n        redpipe.connect_redis(rediscluster.RedisCluster(...), name='d')\n\n    :param redis_client:\n    :param name: nickname you want to give to your connection.\n    :param transaction:\n    :return:"
  },
  {
    "code": "def list_diff(list_a, list_b):\n    result = []\n    for item in list_b:\n        if not item in list_a:\n            result.append(item)\n    return result",
    "docstring": "Return the items from list_b that differ from list_a"
  },
  {
    "code": "def _mean_square_error(y, y_pred, w):\n    return np.average(((y_pred - y) ** 2), weights=w)",
    "docstring": "Calculate the mean square error."
  },
  {
    "code": "def valgrind(command, env={}):\n    xml_file = tempfile.NamedTemporaryFile()\n    internal.register.after_check(lambda: _check_valgrind(xml_file))\n    return run(f\"valgrind --show-leak-kinds=all --xml=yes --xml-file={xml_file.name} -- {command}\", env=env)",
    "docstring": "Run a command with valgrind.\n\n    :param command: command to be run\n    :type command: str\n    :param env: environment in which to run command\n    :type env: str\n    :raises check50.Failure: if, at the end of the check, valgrind reports any errors\n\n    This function works exactly like :func:`check50.run`, with the additional effect that ``command`` is run through\n    ``valgrind`` and ``valgrind``'s output is automatically reviewed at the end of the check for memory leaks and other\n    bugs. If ``valgrind`` reports any issues, the check is failed and student-friendly messages are printed to the log.\n\n    Example usage::\n\n        check50.c.valgrind(\"./leaky\").stdin(\"foo\").stdout(\"bar\").exit(0)\n\n    .. note::\n        It is recommended that the student's code is compiled with the `-ggdb`\n        flag so that additional information, such as the file and line number at which\n        the issue was detected can be included in the log as well."
  },
  {
    "code": "def has_prev(self):\n        if self._result_cache:\n            return self._result_cache.has_prev\n        return self.all().has_prev",
    "docstring": "Return True if there are previous values present"
  },
  {
    "code": "def add_edge(self, from_node, to_node):\n        if to_node not in self.nodes:\n            self.add_node(to_node)\n        try:\n            self.nodes[from_node][\"sons\"].append(to_node)\n        except KeyError:\n            self.nodes[from_node] = {\"dfs_loop_status\": \"\", \"sons\": [to_node]}",
    "docstring": "Add edge between two node\n        The edge is oriented\n\n        :param from_node: node where edge starts\n        :type from_node: object\n        :param to_node: node where edge ends\n        :type to_node: object\n        :return: None"
  },
  {
    "code": "def get_service(station: str) -> Service:\n    for prefix in PREFERRED:\n        if station.startswith(prefix):\n            return PREFERRED[prefix]\n    return NOAA",
    "docstring": "Returns the preferred service for a given station"
  },
  {
    "code": "def load_nddata(self, ndd, naxispath=None):\n        self.clear_metadata()\n        ahdr = self.get_header()\n        ahdr.update(ndd.meta)\n        self.setup_data(ndd.data, naxispath=naxispath)\n        if ndd.wcs is None:\n            self.wcs = wcsmod.WCS(logger=self.logger)\n            self.wcs.load_header(ahdr)\n        else:\n            wcsinfo = wcsmod.get_wcs_class('astropy')\n            self.wcs = wcsinfo.wrapper_class(logger=self.logger)\n            self.wcs.load_nddata(ndd)",
    "docstring": "Load from an astropy.nddata.NDData object."
  },
  {
    "code": "def add_external_reference_to_term(self,term_id, external_ref):\n        if self.term_layer is not None:\n            self.term_layer.add_external_reference(term_id, external_ref)",
    "docstring": "Adds an external reference to the given term identifier\n        @type term_id: string\n        @param term_id: the term identifier\n        @param external_ref: an external reference object\n        @type external_ref: L{CexternalReference}"
  },
  {
    "code": "def Group(items, key):\n  result = {}\n  for item in items:\n    result.setdefault(key(item), []).append(item)\n  return result",
    "docstring": "Groups items by given key function.\n\n  Args:\n    items: An iterable or an iterator of items.\n    key: A function which given each item will return the key.\n\n  Returns:\n    A dict with keys being each unique key and values being a list of items of\n    that key."
  },
  {
    "code": "def _resolve(self, spec):\n    if not spec.remote:\n      return spec\n    try:\n      resolved_urls = self._resolver.resolve(spec.remote)\n      if resolved_urls:\n        return CacheSpec(local=spec.local, remote='|'.join(resolved_urls))\n      return spec\n    except Resolver.ResolverError as e:\n      self._log.warn('Error while resolving from {0}: {1}'.format(spec.remote, str(e)))\n      if spec.local:\n        return CacheSpec(local=spec.local, remote=None)\n      return None",
    "docstring": "Attempt resolving cache URIs when a remote spec is provided."
  },
  {
    "code": "def images(language, word, n = 20, *args, **kwargs):\n\tfrom lltk.images import google\n\treturn google(language, word, n, *args, **kwargs)",
    "docstring": "Returns a list of URLs to suitable images for a given word."
  },
  {
    "code": "def is_transition(self):\n        return self.is_snv and is_purine(self.ref) == is_purine(self.alt)",
    "docstring": "Is this variant and pyrimidine to pyrimidine change or purine to purine change"
  },
  {
    "code": "def set_goid2color_pval(self, goid2color):\n        alpha2col = self.alpha2col\n        if self.pval_name is not None:\n            pval_name = self.pval_name\n            for goid, res in self.go2res.items():\n                pval = getattr(res, pval_name, None)\n                if pval is not None:\n                    for alpha, color in alpha2col.items():\n                        if pval <= alpha and res.study_count != 0:\n                            if goid not in goid2color:\n                                goid2color[goid] = color",
    "docstring": "Fill missing colors based on p-value of an enriched GO term."
  },
  {
    "code": "def load_configuration(linter):\n    name_checker = get_checker(linter, NameChecker)\n    name_checker.config.good_names += ('qs', 'urlpatterns', 'register', 'app_name', 'handler500')\n    linter.config.black_list += ('migrations', 'south_migrations')",
    "docstring": "Amend existing checker config."
  },
  {
    "code": "def get_pmg_structure(phonopy_structure):\n    lattice = phonopy_structure.get_cell()\n    frac_coords = phonopy_structure.get_scaled_positions()\n    symbols = phonopy_structure.get_chemical_symbols()\n    masses = phonopy_structure.get_masses()\n    mms = phonopy_structure.get_magnetic_moments()\n    mms = mms or [0] * len(symbols)\n    return Structure(lattice, symbols, frac_coords,\n                     site_properties={\"phonopy_masses\": masses,\n                                      \"magnetic_moments\": mms})",
    "docstring": "Convert a PhonopyAtoms object to pymatgen Structure object.\n\n    Args:\n        phonopy_structure (PhonopyAtoms): A phonopy structure object."
  },
  {
    "code": "def orchestration(self):\n        if self._orchestration is not None:\n            return self._orchestration\n        API_VERSIONS = {\n            '1': 'heatclient.v1.client.Client',\n        }\n        heat_client = utils.get_client_class(\n            API_NAME,\n            self._instance._api_version[API_NAME],\n            API_VERSIONS)\n        LOG.debug('Instantiating orchestration client: %s', heat_client)\n        endpoint = self._instance.get_endpoint_for_service_type(\n            'orchestration')\n        token = self._instance.auth.get_token(self._instance.session)\n        client = heat_client(\n            endpoint=endpoint,\n            auth_url=self._instance._auth_url,\n            token=token,\n            username=self._instance._username,\n            password=self._instance._password,\n            region_name=self._instance._region_name,\n            insecure=self._instance._insecure,\n            ca_file=self._instance._cli_options.os_cacert,\n        )\n        self._orchestration = client\n        return self._orchestration",
    "docstring": "Returns an orchestration service client"
  },
  {
    "code": "def _render(roster_file, **kwargs):\n    renderers = salt.loader.render(__opts__, {})\n    domain = __opts__.get('roster_domain', '')\n    try:\n        result = salt.template.compile_template(roster_file,\n                                                renderers,\n                                                __opts__['renderer'],\n                                                __opts__['renderer_blacklist'],\n                                                __opts__['renderer_whitelist'],\n                                                mask_value='passw*',\n                                                **kwargs)\n        result.setdefault('host', '{}.{}'.format(os.path.basename(roster_file), domain))\n        return result\n    except:\n        log.warning('Unable to render roster file \"%s\".', roster_file, exc_info=True)\n        return {}",
    "docstring": "Render the roster file"
  },
  {
    "code": "def to_ccw(geom):\n    if isinstance(geom, sgeom.Polygon) and not geom.exterior.is_ccw:\n        geom = sgeom.polygon.orient(geom)\n    return geom",
    "docstring": "Reorients polygon to be wound counter-clockwise."
  },
  {
    "code": "def getPhotosets(self):\n        method = 'flickr.photosets.getList'\n        data = _doget(method, user_id=self.id)\n        sets = []\n        if isinstance(data.rsp.photosets.photoset, list):\n            for photoset in data.rsp.photosets.photoset:\n                sets.append(Photoset(photoset.id, photoset.title.text,\\\n                                     Photo(photoset.primary),\\\n                                     secret=photoset.secret, \\\n                                     server=photoset.server, \\\n                                     description=photoset.description.text,\n                                     photos=photoset.photos))\n        else:\n            photoset = data.rsp.photosets.photoset\n            sets.append(Photoset(photoset.id, photoset.title.text,\\\n                                     Photo(photoset.primary),\\\n                                     secret=photoset.secret, \\\n                                     server=photoset.server, \\\n                                     description=photoset.description.text,\n                                     photos=photoset.photos))\n        return sets",
    "docstring": "Returns a list of Photosets."
  },
  {
    "code": "def create_scree_plot(in_filename, out_filename, plot_title):\n    scree_plot_args = (\"--evec\", in_filename, \"--out\", out_filename,\n                       \"--scree-plot-title\", plot_title)\n    try:\n        PlotEigenvalues.main(argString=scree_plot_args)\n    except PlotEigenvalues.ProgramError as e:\n        msg = \"PlotEigenvalues: {}\".format(e)\n        raise ProgramError(msg)",
    "docstring": "Creates a scree plot using smartpca results.\n\n    :param in_filename: the name of the input file.\n    :param out_filename: the name of the output file.\n    :param plot_title: the title of the scree plot.\n\n    :type in_filename: str\n    :type out_filename: str\n    :type plot_title: str"
  },
  {
    "code": "def unlock_swarm(self, key):\n        if isinstance(key, dict):\n            if 'UnlockKey' not in key:\n                raise errors.InvalidArgument('Invalid unlock key format')\n        else:\n            key = {'UnlockKey': key}\n        url = self._url('/swarm/unlock')\n        res = self._post_json(url, data=key)\n        self._raise_for_status(res)\n        return True",
    "docstring": "Unlock a locked swarm.\n\n            Args:\n                key (string): The unlock key as provided by\n                    :py:meth:`get_unlock_key`\n\n            Raises:\n                :py:class:`docker.errors.InvalidArgument`\n                    If the key argument is in an incompatible format\n\n                :py:class:`docker.errors.APIError`\n                    If the server returns an error.\n\n            Returns:\n                `True` if the request was successful.\n\n            Example:\n\n                >>> key = client.get_unlock_key()\n                >>> client.unlock_node(key)"
  },
  {
    "code": "def add_result(self, values):\r\n        idx = [values['host']]\r\n        for gid in self.key_gids[1:]:\r\n            idx.append(values[gid])\r\n        idx = tuple(idx)\r\n        try:\r\n            self.results[idx] += 1\r\n        except KeyError:\r\n            self.results[idx] = 1\r\n        self._last_idx = idx",
    "docstring": "Add a tuple or increment the value of an existing one\r\n        in the rule results dictionary."
  },
  {
    "code": "def parse_eprocess(self, eprocess_data):\n        Name = eprocess_data['_EPROCESS']['Cybox']['Name']\n        PID = eprocess_data['_EPROCESS']['Cybox']['PID']\n        PPID = eprocess_data['_EPROCESS']['Cybox']['Parent_PID']\n        return {'Name': Name, 'PID': PID, 'PPID': PPID}",
    "docstring": "Parse the EProcess object we get from some rekall output"
  },
  {
    "code": "def chat(self, message):\n    if message:\n      action_chat = sc_pb.ActionChat(\n          channel=sc_pb.ActionChat.Broadcast, message=message)\n      action = sc_pb.Action(action_chat=action_chat)\n      return self.act(action)",
    "docstring": "Send chat message as a broadcast."
  },
  {
    "code": "def put(src_path, dest_hdfs_path, **kwargs):\n    cp(path.abspath(src_path, local=True), dest_hdfs_path, **kwargs)",
    "docstring": "\\\n    Copy the contents of ``src_path`` to ``dest_hdfs_path``.\n\n    ``src_path`` is forced to be interpreted as an ordinary local path\n    (see :func:`~path.abspath`). The source file is opened for reading\n    and the copy is opened for writing. Additional keyword arguments,\n    if any, are handled like in :func:`open`."
  },
  {
    "code": "def select_where(self, where_col_list, where_value_list, col_name=''):\n        res = []\n        col_ids = []\n        for col_id, col in enumerate(self.header):\n            if col in where_col_list:\n                col_ids.append([col_id, col])\n        for row_num, row in enumerate(self.arr):\n            keep_this_row = True\n            for ndx, where_col in enumerate(col_ids):\n                if row[where_col[0]] != where_value_list[ndx]:\n                    keep_this_row = False\n            if keep_this_row is True:\n                if col_name == '':\n                    res.append([row_num, row])\n                else:\n                    l_dat = self.get_col_by_name(col_name)\n                    if l_dat is not None:\n                        res.append(row[l_dat])\n        return res",
    "docstring": "selects rows from the array where col_list == val_list"
  },
  {
    "code": "def save(self, path_info, checksum):\n        assert path_info[\"scheme\"] == \"local\"\n        assert checksum is not None\n        path = path_info[\"path\"]\n        assert os.path.exists(path)\n        actual_mtime, actual_size = get_mtime_and_size(path)\n        actual_inode = get_inode(path)\n        existing_record = self.get_state_record_for_inode(actual_inode)\n        if not existing_record:\n            self._insert_new_state_record(\n                path, actual_inode, actual_mtime, actual_size, checksum\n            )\n            return\n        self._update_state_for_path_changed(\n            path, actual_inode, actual_mtime, actual_size, checksum\n        )",
    "docstring": "Save checksum for the specified path info.\n\n        Args:\n            path_info (dict): path_info to save checksum for.\n            checksum (str): checksum to save."
  },
  {
    "code": "def _remove_ordered_from_queue(self, last_caught_up_3PC=None):\n        to_remove = []\n        for i, msg in enumerate(self.outBox):\n            if isinstance(msg, Ordered) and \\\n                    (not last_caught_up_3PC or\n                     compare_3PC_keys((msg.viewNo, msg.ppSeqNo), last_caught_up_3PC) >= 0):\n                to_remove.append(i)\n        self.logger.trace('{} going to remove {} Ordered messages from outbox'.format(self, len(to_remove)))\n        removed = []\n        for i in reversed(to_remove):\n            removed.insert(0, self.outBox[i])\n            del self.outBox[i]\n        return removed",
    "docstring": "Remove any Ordered that the replica might be sending to node which is\n        less than or equal to `last_caught_up_3PC` if `last_caught_up_3PC` is\n        passed else remove all ordered, needed in catchup"
  },
  {
    "code": "def callback(newstate):\n    print('callback: ', newstate)\n    if newstate == modem.STATE_RING:\n        if state == modem.STATE_IDLE:\n            att = {\"cid_time\": modem.get_cidtime,\n                   \"cid_number\": modem.get_cidnumber,\n                   \"cid_name\": modem.get_cidname}\n            print('Ringing', att)\n    elif newstate == modem.STATE_CALLERID:\n        att = {\"cid_time\": modem.get_cidtime,\n               \"cid_number\": modem.get_cidnumber,\n               \"cid_name\": modem.get_cidname}\n        print('CallerID', att)\n    elif newstate == modem.STATE_IDLE:\n        print('idle')\n    return",
    "docstring": "Callback from modem, process based on new state"
  },
  {
    "code": "def parse_venue(data):\n    return MeetupVenue(\n        id=data.get('id', None),\n        name=data.get('name', None),\n        address_1=data.get('address_1', None),\n        address_2=data.get('address_2', None),\n        address_3=data.get('address_3', None),\n        city=data.get('city', None),\n        state=data.get('state', None),\n        zip=data.get('zip', None),\n        country=data.get('country', None),\n        lat=data.get('lat', None),\n        lon=data.get('lon', None)\n    )",
    "docstring": "Parse a ``MeetupVenue`` from the given response data.\n\n    Returns\n    -------\n    A `pythonkc_meetups.types.`MeetupVenue``."
  },
  {
    "code": "def acquire_multi(self, n=1):\n        browsers = []\n        with self._lock:\n            if len(self._in_use) >= self.size:\n                raise NoBrowsersAvailable\n            while len(self._in_use) < self.size and len(browsers) < n:\n                browser = self._fresh_browser()\n                browsers.append(browser)\n                self._in_use.add(browser)\n        return browsers",
    "docstring": "Returns a list of up to `n` browsers.\n\n        Raises:\n            NoBrowsersAvailable if none available"
  },
  {
    "code": "def set_layout(wlayout, callback):\n    global display_size\n    global window_list\n    global loaded_layout\n    global pending_load\n    global vehiclename\n    if not wlayout.name in window_list and loaded_layout is not None and wlayout.name in loaded_layout:\n        callback(loaded_layout[wlayout.name])\n    window_list[wlayout.name] = ManagedWindow(wlayout, callback)\n    display_size = wlayout.dsize\n    if pending_load:\n        pending_load = False\n        load_layout(vehiclename)",
    "docstring": "set window layout"
  },
  {
    "code": "def create_destination(flowable, container, at_top_of_container=False):\n    vertical_position = 0 if at_top_of_container else container.cursor\n    ids = flowable.get_ids(container.document)\n    destination = NamedDestination(*(str(id) for id in ids))\n    container.canvas.annotate(destination, 0, vertical_position,\n                              container.width, None)\n    container.document.register_page_reference(container.page, flowable)",
    "docstring": "Create a destination anchor in the `container` to direct links to\n    `flowable` to."
  },
  {
    "code": "def _parse_status(self, output):\n        parsed = self._parse_machine_readable_output(output)\n        statuses = []\n        for target, tuples in itertools.groupby(parsed, lambda tup: tup[1]):\n            info = {kind: data for timestamp, _, kind, data in tuples}\n            status = Status(name=target, state=info.get('state'),\n                            provider=info.get('provider-name'))\n            statuses.append(status)\n        return statuses",
    "docstring": "Unit testing is so much easier when Vagrant is removed from the\n        equation."
  },
  {
    "code": "def parse(self, argv):\n        rv = {}\n        for pattern in self.patterns:\n            pattern.apply(rv, argv)\n        return rv",
    "docstring": "Parses the given `argv` and returns a dictionary mapping argument names\n        to the values found in `argv`."
  },
  {
    "code": "def update(self, key, value):\n        if not isinstance(value, dict):\n            raise BadValueError(\n                'The value {} is incorrect.'\n                ' Values should be strings'.format(value))\n        if key in self.data:\n            v = self.get(key)\n            v.update(value)\n        else:\n            v = value\n        self.set(key, v)",
    "docstring": "Update a `key` in the keystore.\n        If the key is non-existent, it's being created"
  },
  {
    "code": "def decode_osgi_props(input_props):\n    result_props = {}\n    intfs = decode_list(input_props, OBJECTCLASS)\n    result_props[OBJECTCLASS] = intfs\n    for intf in intfs:\n        package_key = ENDPOINT_PACKAGE_VERSION_ + package_name(intf)\n        intfversionstr = input_props.get(package_key, None)\n        if intfversionstr:\n            result_props[package_key] = intfversionstr\n    result_props[ENDPOINT_ID] = input_props[ENDPOINT_ID]\n    result_props[ENDPOINT_SERVICE_ID] = input_props[ENDPOINT_SERVICE_ID]\n    result_props[ENDPOINT_FRAMEWORK_UUID] = input_props[ENDPOINT_FRAMEWORK_UUID]\n    imp_configs = decode_list(input_props, SERVICE_IMPORTED_CONFIGS)\n    if imp_configs:\n        result_props[SERVICE_IMPORTED_CONFIGS] = imp_configs\n    intents = decode_list(input_props, SERVICE_INTENTS)\n    if intents:\n        result_props[SERVICE_INTENTS] = intents\n    remote_configs = decode_list(input_props, REMOTE_CONFIGS_SUPPORTED)\n    if remote_configs:\n        result_props[REMOTE_CONFIGS_SUPPORTED] = remote_configs\n    remote_intents = decode_list(input_props, REMOTE_INTENTS_SUPPORTED)\n    if remote_intents:\n        result_props[REMOTE_INTENTS_SUPPORTED] = remote_intents\n    return result_props",
    "docstring": "Decodes the OSGi properties of the given endpoint properties"
  },
  {
    "code": "def _on_process_error(self, error):\n        if self is None:\n            return\n        err = PROCESS_ERROR_STRING[error]\n        self._formatter.append_message(err + '\\r\\n', output_format=OutputFormat.ErrorMessageFormat)",
    "docstring": "Display child process error in the text edit."
  },
  {
    "code": "def make_pizzly_gtf(gtf_file, out_file, data):\n    if file_exists(out_file):\n        return out_file\n    db = gtf.get_gtf_db(gtf_file)\n    with file_transaction(data, out_file) as tx_out_file:\n        with open(tx_out_file, \"w\") as out_handle:\n            for gene in db.features_of_type(\"gene\"):\n                children = [x for x in db.children(id=gene)]\n                for child in children:\n                    if child.attributes.get(\"gene_biotype\", None):\n                        gene_biotype = child.attributes.get(\"gene_biotype\")\n                gene.attributes['gene_biotype'] = gene_biotype\n                gene.source = gene_biotype[0]\n                print(gene, file=out_handle)\n                for child in children:\n                    child.source = gene_biotype[0]\n                    child.attributes.pop(\"transcript_version\", None)\n                    print(child, file=out_handle)\n    return out_file",
    "docstring": "pizzly needs the GTF to be in gene -> transcript -> exon order for each\n    gene. it also wants the gene biotype set as the source"
  },
  {
    "code": "def get_adj_records(results, min_ratio=None, pval=0.05):\n        records = []\n        for rec in results:\n            rec.update_remaining_fldsdefprt(min_ratio=min_ratio)\n            if pval is not None and rec.p_uncorrected >= pval:\n                continue\n            if rec.is_ratio_different:\n                records.append(rec)\n        return records",
    "docstring": "Return GOEA results with some additional statistics calculated."
  },
  {
    "code": "def find_library_linux(cls):\n        dll = Library.JLINK_SDK_NAME\n        root = os.path.join('/', 'opt', 'SEGGER')\n        for (directory_name, subdirs, files) in os.walk(root):\n            fnames = []\n            x86_found = False\n            for f in files:\n                path = os.path.join(directory_name, f)\n                if os.path.isfile(path) and f.startswith(dll):\n                    fnames.append(f)\n                    if '_x86' in path:\n                        x86_found = True\n            for fname in fnames:\n                fpath = os.path.join(directory_name, fname)\n                if util.is_os_64bit():\n                    if '_x86' not in fname:\n                        yield fpath\n                elif x86_found:\n                    if '_x86' in fname:\n                        yield fpath\n                else:\n                    yield fpath",
    "docstring": "Loads the SEGGER DLL from the root directory.\n\n        On Linux, the SEGGER tools are installed under the ``/opt/SEGGER``\n        directory with versioned directories having the suffix ``_VERSION``.\n\n        Args:\n          cls (Library): the ``Library`` class\n\n        Returns:\n          The paths to the J-Link library files in the order that they are\n          found."
  },
  {
    "code": "def luns(self):\n        lun_list, smp_list = [], []\n        if self.ioclass_luns:\n            lun_list = map(lambda l: VNXLun(lun_id=l.lun_id, name=l.name,\n                                            cli=self._cli), self.ioclass_luns)\n        if self.ioclass_snapshots:\n            smp_list = map(lambda smp: VNXLun(name=smp.name, cli=self._cli),\n                           self.ioclass_snapshots)\n        return list(lun_list) + list(smp_list)",
    "docstring": "Aggregator for ioclass_luns and ioclass_snapshots."
  },
  {
    "code": "def decimate(self, fraction=0.5, N=None, boundaries=False, verbose=True):\n        poly = self.polydata(True)\n        if N:\n            Np = poly.GetNumberOfPoints()\n            fraction = float(N) / Np\n            if fraction >= 1:\n                return self\n        decimate = vtk.vtkDecimatePro()\n        decimate.SetInputData(poly)\n        decimate.SetTargetReduction(1 - fraction)\n        decimate.PreserveTopologyOff()\n        if boundaries:\n            decimate.BoundaryVertexDeletionOff()\n        else:\n            decimate.BoundaryVertexDeletionOn()\n        decimate.Update()\n        if verbose:\n            print(\"Nr. of pts, input:\", poly.GetNumberOfPoints(), end=\"\")\n            print(\" output:\", decimate.GetOutput().GetNumberOfPoints())\n        return self.updateMesh(decimate.GetOutput())",
    "docstring": "Downsample the number of vertices in a mesh.\n\n        :param float fraction: the desired target of reduction.\n        :param int N: the desired number of final points (**fraction** is recalculated based on it).\n        :param bool boundaries: (True), decide whether to leave boundaries untouched or not.\n\n        .. note:: Setting ``fraction=0.1`` leaves 10% of the original nr of vertices.\n\n        .. hint:: |skeletonize| |skeletonize.py|_"
  },
  {
    "code": "def minimum_image_dr( self, r1, r2, cutoff=None ):\n        delta_r_vector = self.minimum_image( r1, r2 )\n        return( self.dr( np.zeros( 3 ), delta_r_vector, cutoff ) )",
    "docstring": "Calculate the shortest distance between two points in the cell, \n        accounting for periodic boundary conditions.\n\n        Args:\n            r1 (np.array): fractional coordinates of point r1.\n            r2 (np.array): fractional coordinates of point r2.\n            cutoff (:obj: `float`, optional): if set, return zero if the minimum distance is greater than `cutoff`. Defaults to None.\n\n        Returns:\n            (float): The distance between r1 and r2."
  },
  {
    "code": "def use_comparative_asseessment_part_item_view(self):\n        self._object_views['asseessment_part_item'] = COMPARATIVE\n        for session in self._get_provider_sessions():\n            try:\n                session.use_comparative_asseessment_part_item_view()\n            except AttributeError:\n                pass",
    "docstring": "Pass through to provider AssessmentPartItemSession.use_comparative_asseessment_part_item_view"
  },
  {
    "code": "def new_keys(self):\n        if self._new_keys is None:\n            self._new_keys = NewKeyList(self._version, account_sid=self._solution['sid'], )\n        return self._new_keys",
    "docstring": "Access the new_keys\n\n        :returns: twilio.rest.api.v2010.account.new_key.NewKeyList\n        :rtype: twilio.rest.api.v2010.account.new_key.NewKeyList"
  },
  {
    "code": "def set_min_level_to_mail(self, level):\n        self.min_log_level_to_mail = level\n        handler_class = AlkiviEmailHandler\n        self._set_min_level(handler_class, level)",
    "docstring": "Allow to change mail level after creation"
  },
  {
    "code": "def email_type(arg):\n\tif not is_valid_email_address(arg):\n\t\traise argparse.ArgumentTypeError(\"{0} is not a valid email address\".format(repr(arg)))\n\treturn arg",
    "docstring": "An argparse type representing an email address."
  },
  {
    "code": "def prepare_schemes(self, req):\n        ret = sorted(self.__schemes__ & set(req.schemes), reverse=True)\n        if len(ret) == 0:\n            raise ValueError('No schemes available: {0}'.format(req.schemes))\n        return ret",
    "docstring": "make sure this client support schemes required by current request\n\n        :param pyswagger.io.Request req: current request object"
  },
  {
    "code": "def _clean(self):\n        if CleanupPolicy.EVERYTHING in self.cleanup:\n                self.cleanup_containers()\n                self.cleanup_volumes()\n                self.cleanup_images()\n                self._clean_tmp_dirs()\n        else:\n            if CleanupPolicy.CONTAINERS in self.cleanup:\n                self.cleanup_containers()\n            if CleanupPolicy.VOLUMES in self.cleanup:\n                self.cleanup_volumes()\n            if CleanupPolicy.IMAGES in self.cleanup:\n                self.cleanup_images()\n            if CleanupPolicy.TMP_DIRS in self.cleanup:\n                self._clean_tmp_dirs()",
    "docstring": "Method for cleaning according to object cleanup policy value\n\n        :return: None"
  },
  {
    "code": "def asdict(self):\n        timestamp_str = None\n        if self.reading_time is not None:\n            timestamp_str = self.reading_time.isoformat()\n        return {\n            'stream': self.stream,\n            'device_timestamp': self.raw_time,\n            'streamer_local_id': self.reading_id,\n            'timestamp': timestamp_str,\n            'value': self.value\n        }",
    "docstring": "Encode the data in this reading into a dictionary.\n\n        Returns:\n            dict: A dictionary containing the information from this reading."
  },
  {
    "code": "def dropdb():\n    manager.db.engine.echo = True\n    if prompt_bool(\"Are you sure you want to lose all your data\"):\n        manager.db.drop_all()\n        metadata, alembic_version = alembic_table_metadata()\n        alembic_version.drop()\n        manager.db.session.commit()",
    "docstring": "Drop database tables"
  },
  {
    "code": "def ms_pan(self, viewer, event, data_x, data_y):\n        if not self.canpan:\n            return True\n        x, y = viewer.get_last_win_xy()\n        if event.state == 'move':\n            data_x, data_y = self.get_new_pan(viewer, x, y,\n                                              ptype=self._pantype)\n            viewer.panset_xy(data_x, data_y)\n        elif event.state == 'down':\n            self.pan_set_origin(viewer, x, y, data_x, data_y)\n            self.pan_start(viewer, ptype=2)\n        else:\n            self.pan_stop(viewer)\n        return True",
    "docstring": "A 'drag' or proportional pan, where the image is panned by\n        'dragging the canvas' up or down.  The amount of the pan is\n        proportionate to the length of the drag."
  },
  {
    "code": "def _ParseCachedEntry2003(self, value_data, cached_entry_offset):\n    try:\n      cached_entry = self._ReadStructureFromByteStream(\n          value_data[cached_entry_offset:], cached_entry_offset,\n          self._cached_entry_data_type_map)\n    except (ValueError, errors.ParseError) as exception:\n      raise errors.ParseError(\n          'Unable to parse cached entry value with error: {0!s}'.format(\n              exception))\n    path_size = cached_entry.path_size\n    maximum_path_size = cached_entry.maximum_path_size\n    path_offset = cached_entry.path_offset\n    if path_offset > 0 and path_size > 0:\n      path_size += path_offset\n      maximum_path_size += path_offset\n      try:\n        path = value_data[path_offset:path_size].decode('utf-16-le')\n      except UnicodeDecodeError:\n        raise errors.ParseError('Unable to decode cached entry path to string')\n    cached_entry_object = AppCompatCacheCachedEntry()\n    cached_entry_object.cached_entry_size = (\n        self._cached_entry_data_type_map.GetByteSize())\n    cached_entry_object.file_size = getattr(cached_entry, 'file_size', None)\n    cached_entry_object.last_modification_time = (\n        cached_entry.last_modification_time)\n    cached_entry_object.path = path\n    return cached_entry_object",
    "docstring": "Parses a Windows 2003 cached entry.\n\n    Args:\n      value_data (bytes): value data.\n      cached_entry_offset (int): offset of the first cached entry data\n          relative to the start of the value data.\n\n    Returns:\n      AppCompatCacheCachedEntry: cached entry.\n\n    Raises:\n      ParseError: if the value data could not be parsed."
  },
  {
    "code": "def read_secret(path, key=None):\n    log.debug('Reading Vault secret for %s at %s', __grains__['id'], path)\n    try:\n        url = 'v1/{0}'.format(path)\n        response = __utils__['vault.make_request']('GET', url)\n        if response.status_code != 200:\n            response.raise_for_status()\n        data = response.json()['data']\n        if key is not None:\n            return data[key]\n        return data\n    except Exception as err:\n        log.error('Failed to read secret! %s: %s', type(err).__name__, err)\n        return None",
    "docstring": "Return the value of key at path in vault, or entire secret\n\n    Jinja Example:\n\n    .. code-block:: jinja\n\n        my-secret: {{ salt['vault'].read_secret('secret/my/secret', 'some-key') }}\n\n    .. code-block:: jinja\n\n        {% set supersecret = salt['vault'].read_secret('secret/my/secret') %}\n        secrets:\n            first: {{ supersecret.first }}\n            second: {{ supersecret.second }}"
  },
  {
    "code": "def parseerror(self, msg, line=None):\n        if line is None:\n            line = self.sline\n        error('parse error: ' + msg + ' on line {}'.format(line))\n        sys.exit(-2)",
    "docstring": "Emit parse error and abort assembly."
  },
  {
    "code": "def emitCurrentRecordEdited(self):\r\n        if self._changedRecord == -1:\r\n            return\r\n        if self.signalsBlocked():\r\n            return\r\n        record = self._changedRecord\r\n        self._changedRecord = -1\r\n        self.currentRecordEdited.emit(record)",
    "docstring": "Emits the current record edited signal for this combobox, provided the\r\n        signals aren't blocked and the record has changed since the last time."
  },
  {
    "code": "def transition_to_add(self):\n        assert self.state in [AQStateMachineStates.init, AQStateMachineStates.add]\n        self.state = AQStateMachineStates.add",
    "docstring": "Transition to add"
  },
  {
    "code": "def sizeof_fmt(num):\n    units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB']\n    decimals = [0, 0, 1, 2, 2, 2]\n    if num > 1:\n        exponent = min(int(log(num, 1024)), len(units) - 1)\n        quotient = float(num) / 1024 ** exponent\n        unit = units[exponent]\n        num_decimals = decimals[exponent]\n        format_string = '{0:.%sf} {1}' % (num_decimals)\n        return format_string.format(quotient, unit)\n    if num == 0:\n        return '0 bytes'\n    if num == 1:\n        return '1 byte'",
    "docstring": "Turn number of bytes into human-readable str.\n\n    Parameters\n    ----------\n    num : int\n        The number of bytes.\n\n    Returns\n    -------\n    size : str\n        The size in human-readable format."
  },
  {
    "code": "def save(self, filename, image_format=\"eps\", width=8, height=6):\n        self.get_plot(width, height).savefig(filename, format=image_format)",
    "docstring": "Save the plot to an image file.\n\n        Args:\n            filename: Filename to save to.\n            image_format: Format to save to. Defaults to eps."
  },
  {
    "code": "def random_hex(length):\n    charset = ''.join(set(string.hexdigits.lower()))\n    return random_string(length, charset)",
    "docstring": "Return a random hex string.\n\n    :param int length: The length of string to return\n    :returns: A random string\n    :rtype: str"
  },
  {
    "code": "def add_host_with_group(self, ip, mac, groupname):\n\t\tmsg = OmapiMessage.open(b\"host\")\n\t\tmsg.message.append((\"create\", struct.pack(\"!I\", 1)))\n\t\tmsg.message.append((\"exclusive\", struct.pack(\"!I\", 1)))\n\t\tmsg.obj.append((\"hardware-address\", pack_mac(mac)))\n\t\tmsg.obj.append((\"hardware-type\", struct.pack(\"!I\", 1)))\n\t\tmsg.obj.append((\"ip-address\", pack_ip(ip)))\n\t\tmsg.obj.append((\"group\", groupname))\n\t\tresponse = self.query_server(msg)\n\t\tif response.opcode != OMAPI_OP_UPDATE:\n\t\t\traise OmapiError(\"add failed\")",
    "docstring": "Adds a host with given ip and mac in a group named groupname\n\t\t@type ip: str\n\t\t@type mac: str\n\t\t@type groupname: str"
  },
  {
    "code": "def pop_scope(self, aliases, frame):\n        for name, alias in aliases.iteritems():\n            self.writeline('l_%s = %s' % (name, alias))\n        to_delete = set()\n        for name in frame.identifiers.declared_locally:\n            if name not in aliases:\n                to_delete.add('l_' + name)\n        if to_delete:\n            self.writeline(' = '.join(to_delete) + ' = missing')",
    "docstring": "Restore all aliases and delete unused variables."
  },
  {
    "code": "def to_dict(self, index=True, ordered=False):\n        result = OrderedDict() if ordered else dict()\n        if index:\n            result.update({self._index_name: self._index})\n        if ordered:\n            data_dict = [(column, self._data[i]) for i, column in enumerate(self._columns)]\n        else:\n            data_dict = {column: self._data[i] for i, column in enumerate(self._columns)}\n        result.update(data_dict)\n        return result",
    "docstring": "Returns a dict where the keys are the column names and the values are lists of the values for that column.\n\n        :param index: If True then include the index in the dict with the index_name as the key\n        :param ordered: If True then return an OrderedDict() to preserve the order of the columns in the DataFrame\n        :return: dict or OrderedDict()"
  },
  {
    "code": "def trace_region(self, region_index):\n        cmd = enums.JLinkTraceCommand.GET_REGION_PROPS_EX\n        region = structs.JLinkTraceRegion()\n        region.RegionIndex = int(region_index)\n        res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(region))\n        if (res == 1):\n            raise errors.JLinkException('Failed to get trace region.')\n        return region",
    "docstring": "Retrieves the properties of a trace region.\n\n        Args:\n          self (JLink): the ``JLink`` instance.\n          region_index (int): the trace region index.\n\n        Returns:\n          An instance of ``JLinkTraceRegion`` describing the specified region."
  },
  {
    "code": "def is_closest_date_parameter(task, param_name):\n    for name, obj in task.get_params():\n        if name == param_name:\n            return hasattr(obj, 'use_closest_date')\n    return False",
    "docstring": "Return the parameter class of param_name on task."
  },
  {
    "code": "def model_sizes(m:nn.Module, size:tuple=(64,64))->Tuple[Sizes,Tensor,Hooks]:\n    \"Pass a dummy input through the model `m` to get the various sizes of activations.\"\n    with hook_outputs(m) as hooks:\n        x = dummy_eval(m, size)\n        return [o.stored.shape for o in hooks]",
    "docstring": "Pass a dummy input through the model `m` to get the various sizes of activations."
  },
  {
    "code": "def get_resource_value(self, device_id, resource_path, fix_path=True, timeout=None):\n        return self.get_resource_value_async(device_id, resource_path, fix_path).wait(timeout)",
    "docstring": "Get a resource value for a given device and resource path by blocking thread.\n\n        Example usage:\n\n        .. code-block:: python\n\n            try:\n                v = api.get_resource_value(device_id, path)\n                print(\"Current value\", v)\n            except CloudAsyncError, e:\n                print(\"Error\", e)\n\n        :param str device_id: The name/id of the device (Required)\n        :param str resource_path: The resource path to get (Required)\n        :param fix_path: if True then the leading /, if found, will be stripped before\n            doing request to backend. This is a requirement for the API to work properly\n        :param timeout: Seconds to request value for before timeout. If not provided, the\n            program might hang indefinitely.\n        :raises: CloudAsyncError, CloudTimeoutError\n        :returns: The resource value for the requested resource path\n        :rtype: str"
  },
  {
    "code": "def automatic_density_by_vol(structure, kppvol, force_gamma=False):\n        vol = structure.lattice.reciprocal_lattice.volume\n        kppa = kppvol * vol * structure.num_sites\n        return Kpoints.automatic_density(structure, kppa,\n                                         force_gamma=force_gamma)",
    "docstring": "Returns an automatic Kpoint object based on a structure and a kpoint\n        density per inverse Angstrom^3 of reciprocal cell.\n\n        Algorithm:\n            Same as automatic_density()\n\n        Args:\n            structure (Structure): Input structure\n            kppvol (int): Grid density per Angstrom^(-3) of reciprocal cell\n            force_gamma (bool): Force a gamma centered mesh\n\n        Returns:\n            Kpoints"
  },
  {
    "code": "def _violinplot(val, shade, bw, ax, **kwargs_shade):\n    density, low_b, up_b = _fast_kde(val, bw=bw)\n    x = np.linspace(low_b, up_b, len(density))\n    x = np.concatenate([x, x[::-1]])\n    density = np.concatenate([-density, density[::-1]])\n    ax.fill_betweenx(x, density, alpha=shade, lw=0, **kwargs_shade)",
    "docstring": "Auxiliary function to plot violinplots."
  },
  {
    "code": "def assert_sympy_expressions_equal(expr1, expr2):\n    if not sympy_expressions_equal(expr1, expr2):\n        raise AssertionError(\"{0!r} != {1!r}\".format(expr1, expr2))",
    "docstring": "Raises `AssertionError` if `expr1` is not equal to `expr2`.\n\n    :param expr1: first expression\n    :param expr2: second expression\n    :return: None"
  },
  {
    "code": "def record(self):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('UDF Logical Volume Descriptor not initialized')\n        rec = struct.pack(self.FMT, b'\\x00' * 16,\n                          self.vol_desc_seqnum, self.desc_char_set,\n                          self.logical_vol_ident, 2048,\n                          self.domain_ident.record(),\n                          self.logical_volume_contents_use.record(), 6, 1,\n                          self.impl_ident.record(), self.implementation_use,\n                          self.integrity_sequence_length,\n                          self.integrity_sequence_extent,\n                          self.partition_map.record(), b'\\x00' * 66)[16:]\n        return self.desc_tag.record(rec) + rec",
    "docstring": "A method to generate the string representing this UDF Logical Volume Descriptor.\n\n        Parameters:\n         None.\n        Returns:\n         A string representing this UDF Logical Volume Descriptor."
  },
  {
    "code": "def initialize(self):\n        if not self._initialized:\n            logger.info(\"initializing %r\", self)\n            if not os.path.exists(self.path):\n                if self.mode is not None:\n                    os.makedirs(self.path, mode=self.mode)\n                else:\n                    os.makedirs(self.path)\n            self._set_mode()\n            self._add_facl_rules()\n            self._set_selinux_context()\n            self._set_ownership()\n            self._initialized = True\n            logger.info(\"initialized\")\n            return\n        logger.info(\"%r was already initialized\", self)",
    "docstring": "create the directory if needed and configure it\n\n        :return: None"
  },
  {
    "code": "def check_address(address):\n    if isinstance(address, tuple):\n        check_host(address[0])\n        check_port(address[1])\n    elif isinstance(address, string_types):\n        if os.name != 'posix':\n            raise ValueError('Platform does not support UNIX domain sockets')\n        if not (os.path.exists(address) or\n                os.access(os.path.dirname(address), os.W_OK)):\n            raise ValueError('ADDRESS not a valid socket domain socket ({0})'\n                             .format(address))\n    else:\n        raise ValueError('ADDRESS is not a tuple, string, or character buffer '\n                         '({0})'.format(type(address).__name__))",
    "docstring": "Check if the format of the address is correct\n\n    Arguments:\n        address (tuple):\n            (``str``, ``int``) representing an IP address and port,\n            respectively\n\n            .. note::\n                alternatively a local ``address`` can be a ``str`` when working\n                with UNIX domain sockets, if supported by the platform\n    Raises:\n        ValueError:\n            raised when address has an incorrect format\n\n    Example:\n        >>> check_address(('127.0.0.1', 22))"
  },
  {
    "code": "def argsort_indices(a, axis=-1):\n    a = np.asarray(a)\n    ind = list(np.ix_(*[np.arange(d) for d in a.shape]))\n    ind[axis] = a.argsort(axis)\n    return tuple(ind)",
    "docstring": "Like argsort, but returns an index suitable for sorting the\n    the original array even if that array is multidimensional"
  },
  {
    "code": "def pick_frequency_line(self, filename, frequency, cumulativefield='cumulative_frequency'):\n        if resource_exists('censusname', filename):\n            with closing(resource_stream('censusname', filename)) as b:\n                g = codecs.iterdecode(b, 'ascii')\n                return self._pick_frequency_line(g, frequency, cumulativefield)\n        else:\n            with open(filename, encoding='ascii') as g:\n                return self._pick_frequency_line(g, frequency, cumulativefield)",
    "docstring": "Given a numeric frequency, pick a line from a csv with a cumulative frequency field"
  },
  {
    "code": "def chat_delete(self, *, channel: str, ts: str, **kwargs) -> SlackResponse:\n        kwargs.update({\"channel\": channel, \"ts\": ts})\n        return self.api_call(\"chat.delete\", json=kwargs)",
    "docstring": "Deletes a message.\n\n        Args:\n            channel (str): Channel containing the message to be deleted. e.g. 'C1234567890'\n            ts (str): Timestamp of the message to be deleted. e.g. '1234567890.123456'"
  },
  {
    "code": "def match_rule_patterns(fixed_text, cur=0):\n    pattern = exact_find_in_pattern(fixed_text, cur, RULE_PATTERNS)\n    if len(pattern) > 0:\n        return {\"matched\": True, \"found\": pattern[0]['find'],\n                \"replaced\": pattern[0]['replace'], \"rules\": pattern[0]['rules']}\n    else:\n        return {\"matched\": False, \"found\": None,\n                \"replaced\": fixed_text[cur], \"rules\": None}",
    "docstring": "Matches given text at cursor position with rule patterns\n\n    Returns a dictionary of four elements:\n\n    - \"matched\" - Bool: depending on if match found\n    - \"found\" - string/None: Value of matched pattern's 'find' key or none\n    - \"replaced\": string Replaced string if match found else input string at\n    cursor\n    - \"rules\": dict/None: A dict of rules or None if no match found"
  },
  {
    "code": "def _get_all_filtered_channels(self, topics_without_signature):\n        mpe_address     = self.get_mpe_address()\n        event_signature = self.ident.w3.sha3(text=\"ChannelOpen(uint256,uint256,address,address,address,bytes32,uint256,uint256)\").hex()\n        topics = [event_signature] + topics_without_signature\n        logs = self.ident.w3.eth.getLogs({\"fromBlock\" : self.args.from_block, \"address\"   : mpe_address, \"topics\"    : topics})\n        abi           = get_contract_def(\"MultiPartyEscrow\")\n        event_abi     = abi_get_element_by_name(abi, \"ChannelOpen\")\n        channels_ids  = [get_event_data(event_abi, l)[\"args\"][\"channelId\"] for l in logs]\n        return channels_ids",
    "docstring": "get all filtered chanels from blockchain logs"
  },
  {
    "code": "def convert_mask_to_pil(mask, real=True):\n    from PIL import Image\n    header = mask._layer._psd._record.header\n    channel_ids = [ci.id for ci in mask._layer._record.channel_info]\n    if real and mask._has_real():\n        width = mask._data.real_right - mask._data.real_left\n        height = mask._data.real_bottom - mask._data.real_top\n        channel = mask._layer._channels[\n            channel_ids.index(ChannelID.REAL_USER_LAYER_MASK)\n        ]\n    else:\n        width = mask._data.right - mask._data.left\n        height = mask._data.bottom - mask._data.top\n        channel = mask._layer._channels[\n            channel_ids.index(ChannelID.USER_LAYER_MASK)\n        ]\n    data = channel.get_data(width, height, header.depth, header.version)\n    return _create_channel((width, height), data, header.depth)",
    "docstring": "Convert Mask to PIL Image."
  },
  {
    "code": "def initialize():\n        from zsl.interface.web.performers.default import create_not_found_mapping\n        from zsl.interface.web.performers.resource import create_resource_mapping\n        create_not_found_mapping()\n        create_resource_mapping()",
    "docstring": "Import in this form is necessary so that we avoid the unwanted behavior and immediate initialization of the\n        application objects. This makes the initialization procedure run in the time when it is necessary and has every\n        required resources."
  },
  {
    "code": "def roman2int(s):\n    val = 0\n    pos10 = 1000\n    beg = 0\n    for pos in range(3, -1, -1):\n        for digit in range(9,-1,-1):\n            r = roman[pos][digit]\n            if s.startswith(r, beg):\n                beg += len(r)\n                val += digit * pos10\n                break\n        pos10 //= 10\n    return val",
    "docstring": "Decode roman number\n\n    :param s: string representing a roman number between 1 and 9999\n    :returns: the decoded roman number\n    :complexity: linear (if that makes sense for constant bounded input size)"
  },
  {
    "code": "def list_accounts(self, id, max_id=None, min_id=None, since_id=None, limit=None):\n        id = self.__unpack_id(id)\n        if max_id != None:\n            max_id = self.__unpack_id(max_id)\n        if min_id != None:\n            min_id = self.__unpack_id(min_id)\n        if since_id != None:\n            since_id = self.__unpack_id(since_id)\n        params = self.__generate_params(locals(), ['id']) \n        return self.__api_request('GET', '/api/v1/lists/{0}/accounts'.format(id))",
    "docstring": "Get the accounts that are on the given list. A `limit` of 0 can\n        be specified to get all accounts without pagination.\n        \n        Returns a list of `user dicts`_."
  },
  {
    "code": "def diff_safe(cls, value):\n        if isinstance(value, Frame):\n            return {'_str': str(value), '_id': value._id}\n        elif isinstance(value, (list, tuple)):\n            return [cls.diff_safe(v) for v in value]\n        return value",
    "docstring": "Return a value that can be safely stored as a diff"
  },
  {
    "code": "def calculated_intervals(self, value):\n        if not value:\n            self._calculated_intervals = TimeIntervals()\n            return\n        if isinstance(value, TimeInterval):\n            value = TimeIntervals([value])\n        elif isinstance(value, TimeIntervals):\n            pass\n        elif isinstance(value, list):\n            value = TimeIntervals(value)\n        else:\n            raise TypeError(\"Expected list/TimeInterval/TimeIntervals, got {}\".format(type(value)))\n        for interval in value:\n            if interval.end > utcnow():\n                raise ValueError(\"Calculated intervals should not be in the future\")\n        self._calculated_intervals = value",
    "docstring": "Set the calculated intervals\n        This will be written to the stream_status collection if it's in the database channel\n\n        :param value: The calculated intervals\n        :type value: TimeIntervals, TimeInterval, list[TimeInterval]"
  },
  {
    "code": "def export_json(self, filename):\n        json_graph = self.to_json()\n        with open(filename, 'wb') as f:\n            f.write(json_graph.encode('utf-8'))",
    "docstring": "Export graph in JSON form to the given file."
  },
  {
    "code": "def get_banks_by_assessment_part(self, assessment_part_id):\n        mgr = self._get_provider_manager('ASSESSMENT', local=True)\n        lookup_session = mgr.get_bank_lookup_session(proxy=self._proxy)\n        return lookup_session.get_banks_by_ids(\n            self.get_bank_ids_by_assessment_part(assessment_part_id))",
    "docstring": "Gets the ``Banks`` mapped to an ``AssessmentPart``.\n\n        arg:    assessment_part_id (osid.id.Id): ``Id`` of an\n                ``AssessmentPart``\n        return: (osid.assessment.BankList) - list of banks\n        raise:  NotFound - ``assessment_part_id`` is not found\n        raise:  NullArgument - ``assessment_part_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def adjust_opts(in_opts, config):\n    memory_adjust = config[\"algorithm\"].get(\"memory_adjust\", {})\n    out_opts = []\n    for opt in in_opts:\n        if opt.startswith(\"-Xmx\") or (opt.startswith(\"-Xms\") and memory_adjust.get(\"direction\") == \"decrease\"):\n            arg = opt[:4]\n            opt = \"{arg}{val}\".format(arg=arg,\n                                      val=adjust_memory(opt[4:],\n                                                        memory_adjust.get(\"magnitude\", 1),\n                                                        memory_adjust.get(\"direction\"),\n                                                        maximum=memory_adjust.get(\"maximum\")))\n        out_opts.append(opt)\n    return out_opts",
    "docstring": "Establish JVM opts, adjusting memory for the context if needed.\n\n    This allows using less or more memory for highly parallel or multicore\n    supporting processes, respectively."
  },
  {
    "code": "def _handle_sigusr1(signum: int, frame: Any) -> None:\n        print('=' * 70)\n        print(''.join(traceback.format_stack()))\n        print('-' * 70)",
    "docstring": "Print stacktrace."
  },
  {
    "code": "def do_fish_complete(cli, prog_name):\n    commandline = os.environ['COMMANDLINE']\n    args = split_args(commandline)[1:]\n    if args and not commandline.endswith(' '):\n        incomplete = args[-1]\n        args = args[:-1]\n    else:\n        incomplete = ''\n    for item, help in get_choices(cli, prog_name, args, incomplete):\n        if help:\n            echo(\"%s\\t%s\" % (item, re.sub('\\s', ' ', help)))\n        else:\n            echo(item)\n    return True",
    "docstring": "Do the fish completion\n\n    Parameters\n    ----------\n    cli : click.Command\n        The main click Command of the program\n    prog_name : str\n        The program name on the command line\n\n    Returns\n    -------\n    bool\n        True if the completion was successful, False otherwise"
  },
  {
    "code": "def opath_from_ext(self, ext):\n        return os.path.join(self.workdir, self.prefix.odata + \"_\" + ext)",
    "docstring": "Returns the path of the output file with extension ext.\n        Use it when the file does not exist yet."
  },
  {
    "code": "def removeTags(dom):\n    try:\n        string_type = basestring\n    except NameError:\n        string_type = str\n    element_stack = None\n    if type(dom) in [list, tuple]:\n        element_stack = dom\n    elif isinstance(dom, HTMLElement):\n        element_stack = dom.childs if dom.isTag() else [dom]\n    elif isinstance(dom, string_type):\n        element_stack = parseString(dom).childs\n    else:\n        element_stack = dom\n    output = \"\"\n    while element_stack:\n        el = element_stack.pop(0)\n        if not (el.isTag() or el.isComment() or not el.getTagName()):\n            output += el.__str__()\n        if el.childs:\n            element_stack = el.childs + element_stack\n    return output",
    "docstring": "Remove all tags from `dom` and obtain plaintext representation.\n\n    Args:\n        dom (str, obj, array): str, HTMLElement instance or array of elements.\n\n    Returns:\n        str: Plain string without tags."
  },
  {
    "code": "def upload(ctx):\n    settings.add_cli_options(ctx.cli_options, settings.TransferAction.Upload)\n    ctx.initialize(settings.TransferAction.Upload)\n    specs = settings.create_upload_specifications(\n        ctx.cli_options, ctx.config)\n    del ctx.cli_options\n    for spec in specs:\n        blobxfer.api.Uploader(\n            ctx.general_options, ctx.credentials, spec\n        ).start()",
    "docstring": "Upload files to Azure Storage"
  },
  {
    "code": "def get_sub_dim(src_ds, scale=None, maxdim=1024):\n    ns = src_ds.RasterXSize\n    nl = src_ds.RasterYSize\n    maxdim = float(maxdim)\n    if scale is None:\n        scale_ns = ns/maxdim\n        scale_nl = nl/maxdim\n        scale = max(scale_ns, scale_nl)\n    if scale > 1:\n        ns = int(round(ns/scale))\n        nl = int(round(nl/scale))\n    return ns, nl, scale",
    "docstring": "Compute dimensions of subsampled dataset \n\n    Parameters\n    ----------\n    ds : gdal.Dataset \n        Input GDAL Datset\n    scale : int, optional\n        Scaling factor\n    maxdim : int, optional \n        Maximum dimension along either axis, in pixels\n    \n    Returns\n    -------\n    ns\n        Numper of samples in subsampled output\n    nl\n        Numper of lines in subsampled output\n    scale \n        Final scaling factor"
  },
  {
    "code": "def create_inline(project, resource, offset):\n    pyname = _get_pyname(project, resource, offset)\n    message = 'Inline refactoring should be performed on ' \\\n              'a method, local variable or parameter.'\n    if pyname is None:\n        raise rope.base.exceptions.RefactoringError(message)\n    if isinstance(pyname, pynames.ImportedName):\n        pyname = pyname._get_imported_pyname()\n    if isinstance(pyname, pynames.AssignedName):\n        return InlineVariable(project, resource, offset)\n    if isinstance(pyname, pynames.ParameterName):\n        return InlineParameter(project, resource, offset)\n    if isinstance(pyname.get_object(), pyobjects.PyFunction):\n        return InlineMethod(project, resource, offset)\n    else:\n        raise rope.base.exceptions.RefactoringError(message)",
    "docstring": "Create a refactoring object for inlining\n\n    Based on `resource` and `offset` it returns an instance of\n    `InlineMethod`, `InlineVariable` or `InlineParameter`."
  },
  {
    "code": "def cli_run():\n    options = CLI.parse_args()\n    run(options.CONFIGURATION, options.log_level, options.log_target, options.log_journal)",
    "docstring": "Run the daemon from a command line interface"
  },
  {
    "code": "def main(arguments=None):\n    if arguments is None:\n        arguments = sys.argv[1:]\n    server_parameters = get_server_parameters(arguments)\n    config = get_config(server_parameters.config_path, server_parameters.use_environment)\n    configure_log(config, server_parameters.log_level.upper())\n    validate_config(config, server_parameters)\n    importer = get_importer(config)\n    with get_context(server_parameters, config, importer) as context:\n        application = get_application(context)\n        server = run_server(application, context)\n        setup_signal_handler(server, config)\n        logging.debug('thumbor running at %s:%d' % (context.server.ip, context.server.port))\n        tornado.ioloop.IOLoop.instance().start()",
    "docstring": "Runs thumbor server with the specified arguments."
  },
  {
    "code": "def beginning_of_line(event):\n    \" Move to the start of the current line. \"\n    buff = event.current_buffer\n    buff.cursor_position += buff.document.get_start_of_line_position(after_whitespace=False)",
    "docstring": "Move to the start of the current line."
  },
  {
    "code": "async def pong(self, data: bytes = b\"\") -> None:\n        await self.ensure_open()\n        data = encode_data(data)\n        await self.write_frame(True, OP_PONG, data)",
    "docstring": "This coroutine sends a pong.\n\n        An unsolicited pong may serve as a unidirectional heartbeat.\n\n        The content may be overridden with the optional ``data`` argument\n        which must be a string (which will be encoded to UTF-8) or a\n        bytes-like object."
  },
  {
    "code": "def update(self, cur_value, mesg=None):\n        self.cur_value = cur_value\n        progress = float(self.cur_value) / self.max_value\n        num_chars = int(progress * self.max_chars)\n        num_left = self.max_chars - num_chars\n        if mesg is not None:\n            self.mesg = mesg\n        bar = self.template.format(self.progress_character * num_chars,\n                                   ' ' * num_left,\n                                   progress * 100,\n                                   self.spinner_symbols[self.spinner_index],\n                                   self.mesg)\n        sys.stdout.write(bar)\n        if self.spinner:\n            self.spinner_index = (self.spinner_index + 1) % self.n_spinner\n        sys.stdout.flush()",
    "docstring": "Update progressbar with current value of process\n\n        Parameters\n        ----------\n        cur_value : number\n            Current value of process.  Should be <= max_value (but this is not\n            enforced).  The percent of the progressbar will be computed as\n            (cur_value / max_value) * 100\n        mesg : str\n            Message to display to the right of the progressbar.  If None, the\n            last message provided will be used.  To clear the current message,\n            pass a null string, ''."
  },
  {
    "code": "def _create_row_labels(self):\n        labels = {}\n        for c in self._columns:\n            labels[c] = c\n        if self._alt_labels:\n            for k in self._alt_labels.keys():\n                labels[k] = self._alt_labels[k]\n        if self._label_suffix:\n            for k in labels.keys():\n                if k in self._nonnormal:\n                    labels[k] = \"{}, {}\".format(labels[k],\"median [Q1,Q3]\")\n                elif k in self._categorical:\n                    labels[k] = \"{}, {}\".format(labels[k],\"n (%)\")\n                else:\n                    labels[k] = \"{}, {}\".format(labels[k],\"mean (SD)\")\n        return labels",
    "docstring": "Take the original labels for rows. Rename if alternative labels are \n        provided. Append label suffix if label_suffix is True.\n\n        Returns\n        ----------\n        labels : dictionary\n            Dictionary, keys are original column name, values are final label."
  },
  {
    "code": "async def select(self, db):\n        res = True\n        async with self._cond:\n            for i in range(self.freesize):\n                res = res and (await self._pool[i].select(db))\n            else:\n                self._db = db\n        return res",
    "docstring": "Changes db index for all free connections.\n\n        All previously acquired connections will be closed when released."
  },
  {
    "code": "def matrix(fasta_path: 'path to tictax annotated fasta input',\n           scafstats_path: 'path to BBMap scaftstats file'):\n    records = SeqIO.parse(fasta_path, 'fasta')\n    df = tictax.matrix(records, scafstats_path)\n    df.to_csv(sys.stdout)",
    "docstring": "Generate taxonomic count matrix from tictax classified contigs"
  },
  {
    "code": "def randdomain(self):\n        return '.'.join(\n            rand_readable(3, 6, use=self.random, density=3)\n            for _ in range(self.random.randint(1, 2))\n        ).lower()",
    "docstring": "-> a randomized domain-like name"
  },
  {
    "code": "def allocate_ip_for_subnet(self, subnet_id, mac, port_id):\n        subnet = self.get_subnet(subnet_id)\n        ip, mask, port_id = self.a10_allocate_ip_from_dhcp_range(subnet, \"vlan\", mac, port_id)\n        return ip, mask, port_id",
    "docstring": "Allocates an IP from the specified subnet and creates a port"
  },
  {
    "code": "def transformer(self):\n        ttype = self.embedding.lower()\n        if ttype == 'mds':\n            return MDS(n_components=2, random_state=self.random_state)\n        if ttype == 'tsne':\n            return TSNE(n_components=2, random_state=self.random_state)\n        raise YellowbrickValueError(\"unknown embedding '{}'\".format(ttype))",
    "docstring": "Creates the internal transformer that maps the cluster center's high\n        dimensional space to its two dimensional space."
  },
  {
    "code": "def add_resource_types(resource_i, types):\n    if types is None:\n        return []\n    existing_type_ids = []\n    if resource_i.types:\n        for t in resource_i.types:\n            existing_type_ids.append(t.type_id)\n    new_type_ids = []\n    for templatetype in types:\n        if templatetype.id in existing_type_ids:\n            continue\n        rt_i = ResourceType()\n        rt_i.type_id     = templatetype.id\n        rt_i.ref_key     = resource_i.ref_key\n        if resource_i.ref_key == 'NODE':\n            rt_i.node_id      = resource_i.id\n        elif resource_i.ref_key == 'LINK':\n            rt_i.link_id      = resource_i.id\n        elif resource_i.ref_key == 'GROUP':\n            rt_i.group_id     = resource_i.id\n        resource_i.types.append(rt_i)\n        new_type_ids.append(templatetype.id)\n    return new_type_ids",
    "docstring": "Save a reference to the types used for this resource.\n\n    @returns a list of type_ids representing the type ids\n    on the resource."
  },
  {
    "code": "def get_descriptor_output(descriptor, key, handler=None):\n    line = 'stub'\n    lines = ''\n    while line != '':\n        try:\n            line = descriptor.readline()\n            lines += line\n        except UnicodeDecodeError:\n            error_msg = \"Error while decoding output of process {}\".format(key)\n            if handler:\n                handler.logger.error(\"{} with command {}\".format(\n                    error_msg, handler.queue[key]['command']))\n            lines += error_msg + '\\n'\n    return lines.replace('\\n', '\\n    ')",
    "docstring": "Get the descriptor output and handle incorrect UTF-8 encoding of subprocess logs.\n\n    In case an process contains valid UTF-8 lines as well as invalid lines, we want to preserve\n    the valid and remove the invalid ones.\n    To do this we need to get each line and check for an UnicodeDecodeError."
  },
  {
    "code": "def abstracts(self, key, value):\n    result = []\n    source = force_single_element(value.get('9'))\n    for a_value in force_list(value.get('a')):\n        result.append({\n            'source': source,\n            'value': a_value,\n        })\n    return result",
    "docstring": "Populate the ``abstracts`` key."
  },
  {
    "code": "def base_url(self, space_id, content_type_id, environment_id=None, **kwargs):\n        return \"spaces/{0}{1}/content_types/{2}/editor_interface\".format(\n            space_id,\n            '/environments/{0}'.format(environment_id) if environment_id is not None else '',\n            content_type_id\n        )",
    "docstring": "Returns the URI for the editor interface."
  },
  {
    "code": "def get_all(self, name, default=None):\n        if default is None:\n            default = []\n        return self._headers.get_list(name) or default",
    "docstring": "make cookie python 3 version use this instead of getheaders"
  },
  {
    "code": "def columnCount(self, parent):\n        if parent.isValid():\n            return parent.internalPointer().columnCount()\n        else:\n            return self.root.columnCount()",
    "docstring": "Returns the number of columns for the children of the given parent."
  },
  {
    "code": "def _work_path_to_rel_final_path(path, upload_path_mapping, upload_base_dir):\n    if not path or not isinstance(path, str):\n        return path\n    upload_path = None\n    if upload_path_mapping.get(path) is not None and os.path.isfile(path):\n        upload_path = upload_path_mapping[path]\n    else:\n        paths_to_check = [key for key in upload_path_mapping\n                          if path.startswith(key)]\n        if paths_to_check:\n            for work_path in paths_to_check:\n                if os.path.isdir(work_path):\n                    final_path = upload_path_mapping[work_path]\n                    upload_path = path.replace(work_path, final_path)\n                    break\n    if upload_path is not None:\n        return os.path.relpath(upload_path, upload_base_dir)\n    else:\n        return None",
    "docstring": "Check if `path` is a work-rooted path, and convert to a relative final-rooted path"
  },
  {
    "code": "def delete_all_thumbnails(path, recursive=True):\n    total = 0\n    for thumbs in all_thumbnails(path, recursive=recursive).values():\n        total += _delete_using_thumbs_list(thumbs)\n    return total",
    "docstring": "Delete all files within a path which match the thumbnails pattern.\n\n    By default, matching files from all sub-directories are also removed. To\n    only remove from the path directory, set recursive=False."
  },
  {
    "code": "def encode_csv(data_dict, column_names):\n  import csv\n  import six\n  values = [str(data_dict[x]) for x in column_names]\n  str_buff = six.StringIO()\n  writer = csv.writer(str_buff, lineterminator='')\n  writer.writerow(values)\n  return str_buff.getvalue()",
    "docstring": "Builds a csv string.\n\n  Args:\n    data_dict: dict of {column_name: 1 value}\n    column_names: list of column names\n\n  Returns:\n    A csv string version of data_dict"
  },
  {
    "code": "def e2dnde_deriv(self, x, params=None):\n        params = self.params if params is None else params\n        return np.squeeze(self.eval_e2dnde_deriv(x, params, self.scale,\n                                                 self.extra_params))",
    "docstring": "Evaluate derivative of E^2 times differential flux with\n        respect to E."
  },
  {
    "code": "def local_attr(self, name, context=None):\n        result = []\n        if name in self.locals:\n            result = self.locals[name]\n        else:\n            class_node = next(self.local_attr_ancestors(name, context), None)\n            if class_node:\n                result = class_node.locals[name]\n        result = [n for n in result if not isinstance(n, node_classes.DelAttr)]\n        if result:\n            return result\n        raise exceptions.AttributeInferenceError(\n            target=self, attribute=name, context=context\n        )",
    "docstring": "Get the list of assign nodes associated to the given name.\n\n        Assignments are looked for in both this class and in parents.\n\n        :returns: The list of assignments to the given name.\n        :rtype: list(NodeNG)\n\n        :raises AttributeInferenceError: If no attribute with this name\n            can be found in this class or parent classes."
  },
  {
    "code": "def encoded_content(self, path):\n        if path in self.__class__.asset_contents:\n            return self.__class__.asset_contents[path]\n        data = self.read_bytes(path)\n        self.__class__.asset_contents[path] = force_text(base64.b64encode(data))\n        return self.__class__.asset_contents[path]",
    "docstring": "Return the base64 encoded contents"
  },
  {
    "code": "def path_join(*args):\n    return SEP.join((x for x in args if x not in (None, ''))).strip(SEP)",
    "docstring": "Join path parts to single path."
  },
  {
    "code": "def copy(self, version=None, tx_ins=None, tx_outs=None, lock_time=None,\n             tx_joinsplits=None, joinsplit_pubkey=None, joinsplit_sig=None):\n        return SproutTx(\n            version=version if version is not None else self.version,\n            tx_ins=tx_ins if tx_ins is not None else self.tx_ins,\n            tx_outs=tx_outs if tx_outs is not None else self.tx_outs,\n            lock_time=(lock_time if lock_time is not None\n                       else self.lock_time),\n            tx_joinsplits=(tx_joinsplits if tx_joinsplits is not None\n                           else self.tx_joinsplits),\n            joinsplit_pubkey=(joinsplit_pubkey if joinsplit_pubkey is not None\n                              else self.joinsplit_pubkey),\n            joinsplit_sig=(joinsplit_sig if joinsplit_sig is not None\n                           else self.joinsplit_sig))",
    "docstring": "SproutTx, ... -> Tx\n\n        Makes a copy. Allows over-writing specific pieces."
  },
  {
    "code": "def controldata(self):\n        result = {}\n        if self._version_file_exists() and self.state != 'creating replica':\n            try:\n                env = {'LANG': 'C', 'LC_ALL': 'C', 'PATH': os.getenv('PATH')}\n                if os.getenv('SYSTEMROOT') is not None:\n                    env['SYSTEMROOT'] = os.getenv('SYSTEMROOT')\n                data = subprocess.check_output([self._pgcommand('pg_controldata'), self._data_dir], env=env)\n                if data:\n                    data = data.decode('utf-8').splitlines()\n                    result = {l.split(':')[0].replace('Current ', '', 1): l.split(':', 1)[1].strip() for l in data\n                              if l and ':' in l}\n            except subprocess.CalledProcessError:\n                logger.exception(\"Error when calling pg_controldata\")\n        return result",
    "docstring": "return the contents of pg_controldata, or non-True value if pg_controldata call failed"
  },
  {
    "code": "def segment_snrs(filters, stilde, psd, low_frequency_cutoff):\n    snrs = []\n    norms = []\n    for bank_template in filters:\n        snr, _, norm = matched_filter_core(\n                bank_template, stilde, h_norm=bank_template.sigmasq(psd),\n                psd=None, low_frequency_cutoff=low_frequency_cutoff)\n        snrs.append(snr)\n        norms.append(norm)\n    return snrs, norms",
    "docstring": "This functions calculates the snr of each bank veto template against\n    the segment\n\n    Parameters\n    ----------\n    filters: list of FrequencySeries\n        The list of bank veto templates filters.\n    stilde: FrequencySeries\n        The current segment of data.\n    psd: FrequencySeries\n    low_frequency_cutoff: float\n\n    Returns\n    -------\n    snr (list): List of snr time series.\n    norm (list): List of normalizations factors for the snr time series."
  },
  {
    "code": "def _calculate_average(self, points):\n        assert len(self.theta) == len(points), \\\n            \"points has length %i, but should have length %i\" % \\\n            (len(points), len(self.theta))\n        new_point = {'x': 0, 'y': 0, 'time': 0}\n        for key in new_point:\n            new_point[key] = self.theta[0] * points[0][key] + \\\n                self.theta[1] * points[1][key] + \\\n                self.theta[2] * points[2][key]\n        return new_point",
    "docstring": "Calculate the arithmetic mean of the points x and y coordinates\n           seperately."
  },
  {
    "code": "def fit(self, blocks, y=None):\n        self.kmeans.fit(make_weninger_features(blocks))\n        self.kmeans.cluster_centers_.sort(axis=0)\n        self.kmeans.cluster_centers_[0, :] = np.zeros(2)\n        return self",
    "docstring": "Fit a k-means clustering model using an ordered sequence of blocks."
  },
  {
    "code": "def parse_boolean(value):\n    if value is None:\n        return None\n    if isinstance(value, bool):\n        return value\n    if isinstance(value, string_types):\n        value = value.lower()\n        if value == 'false':\n            return False\n        if value == 'true':\n            return True\n    raise ValueError(\"Could not convert value to boolean: {}\".format(value))",
    "docstring": "Coerce a value to boolean.\n\n    :param value: the value, could be a string, boolean, or None\n    :return: the value as coerced to a boolean"
  },
  {
    "code": "def file_length(file_obj):\n    file_obj.seek(0, 2)\n    length = file_obj.tell()\n    file_obj.seek(0)\n    return length",
    "docstring": "Returns the length in bytes of a given file object.\n    Necessary because os.fstat only works on real files and not file-like\n    objects. This works on more types of streams, primarily StringIO."
  },
  {
    "code": "def start(self, level=\"WARN\"):\n        if self.active:\n            return\n        handler = StreamHandler()\n        handler.setFormatter(Formatter(self.LOGFMT))\n        self.addHandler(handler)\n        self.setLevel(level.upper())\n        self.active = True\n        return",
    "docstring": "Start logging with this logger.\n\n        Until the logger is started, no messages will be emitted. This applies\n        to all loggers with the same name and any child loggers.\n\n        Messages less than the given priority level will be ignored. The\n        default level is 'WARN', which conforms to the *nix convention that a\n        successful run should produce no diagnostic output. Available levels\n        and their suggested meanings:\n\n          DEBUG - output useful for developers\n          INFO - trace normal program flow, especially external interactions\n          WARN - an abnormal condition was detected that might need attention\n          ERROR - an error was detected but execution continued\n          CRITICAL - an error was detected and execution was halted"
  },
  {
    "code": "def get(self, key, default=None, type=None):\n        try:\n            value = self[key]\n            if type is not None:\n                return type(value)\n            return value\n        except (KeyError, ValueError):\n            return default",
    "docstring": "Returns the first value for a key.\n\n        If `type` is not None, the value will be converted by calling\n        `type` with the value as argument. If type() raises `ValueError`, it\n        will be treated as if the value didn't exist, and `default` will be\n        returned instead."
  },
  {
    "code": "def from_file(cls, filename):\n        with open(filename) as f:\n            molecule, origin, axes, nrep, subtitle, nuclear_charges = \\\n                read_cube_header(f)\n            data = np.zeros(tuple(nrep), float)\n            tmp = data.ravel()\n            counter = 0\n            while True:\n                line = f.readline()\n                if len(line) == 0:\n                    break\n                words = line.split()\n                for word in words:\n                    tmp[counter] = float(word)\n                    counter += 1\n        return cls(molecule, origin, axes, nrep, data, subtitle, nuclear_charges)",
    "docstring": "Create a cube object by loading data from a file.\n\n           *Arguemnts:*\n\n           filename\n                The file to load. It must contain the header with the\n                description of the grid and the molecule."
  },
  {
    "code": "def _loh_to_vcf(cur):\n    cn = int(float(cur[\"C\"]))\n    minor_cn = int(float(cur[\"M\"]))\n    if cur[\"type\"].find(\"LOH\"):\n        svtype = \"LOH\"\n    elif cn > 2:\n        svtype = \"DUP\"\n    elif cn < 1:\n        svtype = \"DEL\"\n    else:\n        svtype = None\n    if svtype:\n        info = [\"SVTYPE=%s\" % svtype, \"END=%s\" % cur[\"end\"],\n                \"SVLEN=%s\" % (int(cur[\"end\"]) - int(cur[\"start\"])),\n                \"CN=%s\" % cn, \"MajorCN=%s\" % (cn - minor_cn), \"MinorCN=%s\" % minor_cn]\n        return [cur[\"chr\"], cur[\"start\"], \".\", \"N\", \"<%s>\" % svtype, \".\", \".\",\n                \";\".join(info), \"GT\", \"0/1\"]",
    "docstring": "Convert LOH output into standardized VCF."
  },
  {
    "code": "def _parse_rule(self, rule):\n        values = rule.strip().split(self.RULE_DELIM, 4)\n        if len(values) >= 4:\n            codes = values[3].split(',')\n            for i in range(0, len(codes)):\n                try:\n                    codes[i] = int(codes[i], 0)\n                except ValueError as e:\n                    binwalk.core.common.warning(\"The specified return code '%s' for extractor '%s' is not a valid number!\" % (codes[i], values[0]))\n            values[3] = codes\n        if len(values) >= 5:\n            values[4] = (values[4].lower() == 'true')\n        return values",
    "docstring": "Parses an extraction rule.\n\n        @rule - Rule string.\n\n        Returns an array of ['<case insensitive matching string>', '<file extension>', '<command to run>', '<comma separated return codes>', <recurse into extracted directories: True|False>]."
  },
  {
    "code": "def db_for_write(self, model, **hints):\n        try:\n            if model.sf_access == READ_ONLY:\n                raise WriteNotSupportedError(\"%r is a read-only model.\" % model)\n        except AttributeError:\n            pass\n        return None",
    "docstring": "Prevent write actions on read-only tables.\n\n        Raises:\n            WriteNotSupportedError: If models.sf_access is ``read_only``."
  },
  {
    "code": "def basic_filter_languages(languages, ranges):\n    if LanguageRange.WILDCARD in ranges:\n        yield from languages\n        return\n    found = set()\n    for language_range in ranges:\n        range_str = language_range.match_str\n        for language in languages:\n            if language in found:\n                continue\n            match_str = language.match_str\n            if match_str == range_str:\n                yield language\n                found.add(language)\n                continue\n            if len(range_str) < len(match_str):\n                if     (match_str[:len(range_str)] == range_str and\n                        match_str[len(range_str)] == \"-\"):\n                    yield language\n                    found.add(language)\n                    continue",
    "docstring": "Filter languages using the string-based basic filter algorithm described in\n    RFC4647.\n\n    `languages` must be a sequence of :class:`LanguageTag` instances which are\n    to be filtered.\n\n    `ranges` must be an iterable which represent the basic language ranges to\n    filter with, in priority order. The language ranges must be given as\n    :class:`LanguageRange` objects.\n\n    Return an iterator of languages which matched any of the `ranges`. The\n    sequence produced by the iterator is in match order and duplicate-free. The\n    first range to match a language yields the language into the iterator, no\n    other range can yield that language afterwards."
  },
  {
    "code": "def _calculateCrcString(inputstring):\n    _checkString(inputstring, description='input CRC string')\n    register = 0xFFFF\n    for char in inputstring:\n        register = (register >> 8) ^ _CRC16TABLE[(register ^ ord(char)) & 0xFF]\n    return _numToTwoByteString(register, LsbFirst=True)",
    "docstring": "Calculate CRC-16 for Modbus.\n\n    Args:\n        inputstring (str): An arbitrary-length message (without the CRC).\n\n    Returns:\n        A two-byte CRC string, where the least significant byte is first."
  },
  {
    "code": "def train_agent(real_env, learner, world_model_dir, hparams, epoch):\n  initial_frame_chooser = rl_utils.make_initial_frame_chooser(\n      real_env, hparams.frame_stack_size, hparams.simulation_random_starts,\n      hparams.simulation_flip_first_random_for_beginning\n  )\n  env_fn = rl.make_simulated_env_fn_from_hparams(\n      real_env, hparams, batch_size=hparams.simulated_batch_size,\n      initial_frame_chooser=initial_frame_chooser, model_dir=world_model_dir,\n      sim_video_dir=os.path.join(\n          learner.agent_model_dir, \"sim_videos_{}\".format(epoch)\n      )\n  )\n  base_algo_str = hparams.base_algo\n  train_hparams = trainer_lib.create_hparams(hparams.base_algo_params)\n  if hparams.wm_policy_param_sharing:\n    train_hparams.optimizer_zero_grads = True\n  rl_utils.update_hparams_from_hparams(\n      train_hparams, hparams, base_algo_str + \"_\"\n  )\n  final_epoch = hparams.epochs - 1\n  is_special_epoch = (epoch + 3) == final_epoch or (epoch + 7) == final_epoch\n  is_final_epoch = epoch == final_epoch\n  env_step_multiplier = 3 if is_final_epoch else 2 if is_special_epoch else 1\n  learner.train(\n      env_fn, train_hparams, simulated=True, save_continuously=True,\n      epoch=epoch, env_step_multiplier=env_step_multiplier\n  )",
    "docstring": "Train the PPO agent in the simulated environment."
  },
  {
    "code": "def _handle_usecols(self, columns, usecols_key):\n        if self.usecols is not None:\n            if callable(self.usecols):\n                col_indices = _evaluate_usecols(self.usecols, usecols_key)\n            elif any(isinstance(u, str) for u in self.usecols):\n                if len(columns) > 1:\n                    raise ValueError(\"If using multiple headers, usecols must \"\n                                     \"be integers.\")\n                col_indices = []\n                for col in self.usecols:\n                    if isinstance(col, str):\n                        try:\n                            col_indices.append(usecols_key.index(col))\n                        except ValueError:\n                            _validate_usecols_names(self.usecols, usecols_key)\n                    else:\n                        col_indices.append(col)\n            else:\n                col_indices = self.usecols\n            columns = [[n for i, n in enumerate(column) if i in col_indices]\n                       for column in columns]\n            self._col_indices = col_indices\n        return columns",
    "docstring": "Sets self._col_indices\n\n        usecols_key is used if there are string usecols."
  },
  {
    "code": "def resolve_push_to(push_to, default_url, default_namespace):\n    protocol = 'http://' if push_to.startswith('http://') else 'https://'\n    url = push_to = REMOVE_HTTP.sub('', push_to)\n    namespace = default_namespace\n    parts = url.split('/', 1)\n    special_set = {'.', ':'}\n    char_set = set([c for c in parts[0]])\n    if len(parts) == 1:\n        if not special_set.intersection(char_set) and parts[0] != 'localhost':\n            registry_url = default_url\n            namespace = push_to\n        else:\n            registry_url = protocol + parts[0]\n    else:\n        registry_url = protocol + parts[0]\n        namespace = parts[1]\n    return registry_url, namespace",
    "docstring": "Given a push-to value, return the registry and namespace.\n\n    :param push_to: string: User supplied --push-to value.\n    :param default_url: string: Container engine's default_index value (e.g. docker.io).\n    :return: tuple: registry_url, namespace"
  },
  {
    "code": "def MessageEncoder(field_number, is_repeated, is_packed):\n  tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)\n  local_EncodeVarint = _EncodeVarint\n  assert not is_packed\n  if is_repeated:\n    def EncodeRepeatedField(write, value):\n      for element in value:\n        write(tag)\n        local_EncodeVarint(write, element.ByteSize())\n        element._InternalSerialize(write)\n    return EncodeRepeatedField\n  else:\n    def EncodeField(write, value):\n      write(tag)\n      local_EncodeVarint(write, value.ByteSize())\n      return value._InternalSerialize(write)\n    return EncodeField",
    "docstring": "Returns an encoder for a message field."
  },
  {
    "code": "def load_path(self, path):\n        containing_module, _, last_item = path.rpartition('.')\n        if last_item[0].isupper():\n            path = containing_module\n        imported_obj = importlib.import_module(path)\n        if last_item[0].isupper():\n            try:\n                imported_obj = getattr(imported_obj, last_item)\n            except AttributeError:\n                msg = 'Cannot import \"%s\". ' \\\n                    '(Hint: CamelCase is only for classes)' % last_item\n                raise ConfigurationError(msg)\n        return imported_obj",
    "docstring": "Load and return a given import path to a module or class"
  },
  {
    "code": "def get_id(self):\n        if self.type == 'NAF':\n            return self.node.get('id')\n        elif self.type == 'KAF':\n            return self.node.get('mid')",
    "docstring": "Returns the term identifier\n        @rtype: string\n        @return: the term identifier"
  },
  {
    "code": "def nunique(expr):\n    output_type = types.int64\n    if isinstance(expr, SequenceExpr):\n        return NUnique(_value_type=output_type, _inputs=[expr])\n    elif isinstance(expr, SequenceGroupBy):\n        return GroupedNUnique(_data_type=output_type, _inputs=[expr.to_column()], _grouped=expr.input)\n    elif isinstance(expr, CollectionExpr):\n        unique_input = _extract_unique_input(expr)\n        if unique_input:\n            return nunique(unique_input)\n        else:\n            return NUnique(_value_type=types.int64, _inputs=expr._project_fields)\n    elif isinstance(expr, GroupBy):\n        if expr._to_agg:\n            inputs = expr.input[expr._to_agg.names]._project_fields\n        else:\n            inputs = expr.input._project_fields\n        return GroupedNUnique(_data_type=types.int64, _inputs=inputs,\n                              _grouped=expr)",
    "docstring": "The distinct count.\n\n    :param expr:\n    :return:"
  },
  {
    "code": "def buscar_por_ip_ambiente(self, ip, id_environment):\n        if not is_valid_int_param(id_environment):\n            raise InvalidParameterError(\n                u'Environment identifier is invalid or was not informed.')\n        if not is_valid_ip(ip):\n            raise InvalidParameterError(u'IP is invalid or was not informed.')\n        url = 'ip/' + str(ip) + '/ambiente/' + str(id_environment) + '/'\n        code, xml = self.submit(None, 'GET', url)\n        return self.response(code, xml)",
    "docstring": "Get IP with an associated environment.\n\n        :param ip: IP address in the format x1.x2.x3.x4.\n        :param id_environment: Identifier of the environment. Integer value and greater than zero.\n\n        :return: Dictionary with the following structure:\n\n        ::\n\n            {'ip': {'id': < id >,\n            'id_vlan': < id_vlan >,\n            'oct4': < oct4 >,\n            'oct3': < oct3 >,\n            'oct2': < oct2 >,\n            'oct1': < oct1 >,\n            'descricao': < descricao > }}\n\n        :raise IpNaoExisteError: IP is not registered or not associated with environment.\n        :raise InvalidParameterError: The environment identifier and/or IP is/are null or invalid.\n        :raise DataBaseError: Networkapi failed to access the database."
  },
  {
    "code": "def swipe(self):\n\t\tresult = WBinArray(0, len(self))\n\t\tfor i in range(len(self)):\n\t\t\tresult[len(self) - i - 1] = self[i]\n\t\treturn result",
    "docstring": "Mirror current array value in reverse. Bits that had greater index will have lesser index, and\n\t\tvice-versa. This method doesn't change this array. It creates a new one and return it as a result.\n\n\t\t:return: WBinArray"
  },
  {
    "code": "def interpolate(self, other, t):\n        return Vertex(self.pos.lerp(other.pos, t), \n                          self.normal.lerp(other.normal, t))",
    "docstring": "Create a new vertex between this vertex and `other` by linearly\n        interpolating all properties using a parameter of `t`. Subclasses should\n        override this to interpolate additional properties."
  },
  {
    "code": "def visit_with(self, node):\n        items = \", \".join(\n            (\"%s\" % expr.accept(self)) + (vars and \" as %s\" % (vars.accept(self)) or \"\")\n            for expr, vars in node.items\n        )\n        return \"with %s:\\n%s\" % (items, self._stmt_list(node.body))",
    "docstring": "return an astroid.With node as string"
  },
  {
    "code": "def upload_module(self, local_path=None, remote_path=\"/tmp/lime.ko\"):\n        if local_path is None:\n            raise FileNotFoundFoundError(local_path)\n        self.shell.upload_file(local_path, remote_path)",
    "docstring": "Upload LiME kernel module to remote host\n\n        :type local_path: str\n        :param local_path: local path to lime kernel module\n        :type remote_path: str\n        :param remote_path: remote path to upload lime kernel module"
  },
  {
    "code": "def _check_and_uninstall_python(ret, python, user=None):\n    ret = _python_installed(ret, python, user=user)\n    if ret['result']:\n        if ret['default']:\n            __salt__['pyenv.default']('system', runas=user)\n        if __salt__['pyenv.uninstall_python'](python, runas=user):\n            ret['result'] = True\n            ret['changes'][python] = 'Uninstalled'\n            ret['comment'] = 'Successfully removed python'\n            return ret\n        else:\n            ret['result'] = False\n            ret['comment'] = 'Failed to uninstall python'\n            return ret\n    else:\n        ret['result'] = True\n        ret['comment'] = 'python {0} is already absent'.format(python)\n    return ret",
    "docstring": "Verify that python is uninstalled"
  },
  {
    "code": "def list(self, environment_vip=None):\n        uri = 'api/networkv6/?'\n        if environment_vip:\n            uri += 'environment_vip=%s' % environment_vip\n        return super(ApiNetworkIPv6, self).get(uri)",
    "docstring": "List networks redeipv6 ]\n\n        :param environment_vip: environment vip to filter\n\n        :return: IPv6 Networks"
  },
  {
    "code": "def flattenPorts(root: LNode):\n    for u in root.children:\n        u.west = _flattenPortsSide(u.west)\n        u.east = _flattenPortsSide(u.east)\n        u.north = _flattenPortsSide(u.north)\n        u.south = _flattenPortsSide(u.south)",
    "docstring": "Flatten ports to simplify layout generation\n\n    :attention: children property is destroyed, parent property stays same"
  },
  {
    "code": "def get_hkr_state(self):\n        self.update()\n        try:\n            return {\n                126.5: 'off',\n                127.0: 'on',\n                self.eco_temperature: 'eco',\n                self.comfort_temperature: 'comfort'\n            }[self.target_temperature]\n        except KeyError:\n            return 'manual'",
    "docstring": "Get the thermostate state."
  },
  {
    "code": "def exists(self, filename):\n        result = True\n        for repo in self._children:\n            if not repo.exists(filename):\n                result = False\n        return result",
    "docstring": "Report whether a file exists on all distribution points.\n\n        Determines file type by extension.\n\n        Args:\n            filename: Filename you wish to check. (No path! e.g.:\n                \"AdobeFlashPlayer-14.0.0.176.pkg\")\n\n        Returns:\n            Boolean"
  },
  {
    "code": "def do_uninstall(ctx, verbose, fake):\n    aliases = cli.list_commands(ctx)\n    aliases.extend(['graft', 'harvest', 'sprout', 'resync', 'settings', 'install', 'uninstall'])\n    for alias in aliases:\n        system_command = 'git config --global --unset-all alias.{0}'.format(alias)\n        verbose_echo(system_command, verbose, fake)\n        if not fake:\n            os.system(system_command)\n    if not fake:\n        click.echo('\\nThe following git aliases are uninstalled:\\n')\n        output_aliases(aliases)",
    "docstring": "Uninstalls legit git aliases, including deprecated legit sub-commands."
  },
  {
    "code": "def cart2dir(self,cart):\n        cart=numpy.array(cart)\n        rad=old_div(numpy.pi,180.)\n        if len(cart.shape)>1:\n            Xs,Ys,Zs=cart[:,0],cart[:,1],cart[:,2]\n        else:\n            Xs,Ys,Zs=cart[0],cart[1],cart[2]\n        Rs=numpy.sqrt(Xs**2+Ys**2+Zs**2)\n        Decs=(old_div(numpy.arctan2(Ys,Xs),rad))%360.\n        try:\n            Incs=old_div(numpy.arcsin(old_div(Zs,Rs)),rad)\n        except:\n            print('trouble in cart2dir')\n            return numpy.zeros(3)\n        return numpy.array([Decs,Incs,Rs]).transpose()",
    "docstring": "converts a direction to cartesian coordinates"
  },
  {
    "code": "def on_switch_page(self, notebook, page_pointer, page_num, user_param1=None):\n        page = notebook.get_nth_page(page_num)\n        for tab_info in list(self.tabs.values()):\n            if tab_info['page'] is page:\n                state_m = tab_info['state_m']\n                sm_id = state_m.state.get_state_machine().state_machine_id\n                selected_state_m = self.current_state_machine_m.selection.get_selected_state()\n                if selected_state_m is not state_m and sm_id in self.model.state_machine_manager.state_machines:\n                    self.model.selected_state_machine_id = sm_id\n                    self.current_state_machine_m.selection.set(state_m)\n                return",
    "docstring": "Update state selection when the active tab was changed"
  },
  {
    "code": "def draw_heading(self, writer):\n        if self.dirty == self.STATE_REFRESH:\n            writer(u''.join(\n                (self.term.home, self.term.clear,\n                 self.screen.msg_intro, '\\n',\n                 self.screen.header, '\\n',)))\n            return True",
    "docstring": "Conditionally redraw screen when ``dirty`` attribute is valued REFRESH.\n\n        When Pager attribute ``dirty`` is ``STATE_REFRESH``, cursor is moved\n        to (0,0), screen is cleared, and heading is displayed.\n\n        :param writer: callable writes to output stream, receiving unicode.\n        :returns: True if class attribute ``dirty`` is ``STATE_REFRESH``."
  },
  {
    "code": "def include(gset, elem, value=True):\n    add = getattr(gset, 'add', None)\n    if add is None: add = getattr(gset, 'append', None)\n    if add is not None: add(elem)\n    else:\n        if not hasattr(gset, '__setitem__'):\n            raise Error(\"gset is not a supported container.\")\n        gset[elem] = value\n    return elem",
    "docstring": "Do whatever it takes to make ``elem in gset`` true.\n\n        >>> L, S, D = [ ], set(), { }\n        >>> include(L, \"Lucy\"); include(S, \"Sky\"); include(D, \"Diamonds\");\n        >>> print L, S, D\n        ['Lucy'] set(['Sky']) {'Diamonds': True}\n\n    Works for sets (using ``add``), lists (using ``append``) and dicts (using\n    ``__setitem__``).\n\n    ``value``\n        if ``gset`` is a dict, does ``gset[elem] = value``.\n\n    Returns ``elem``, or raises an Error if none of these operations are supported."
  },
  {
    "code": "def _visit_handlers(handlers, visitor, prefix, suffixes):\n    results = []\n    for handler in handlers:\n        for suffix in suffixes:\n            func = getattr(handler, '{}_{}'.format(prefix, suffix).lower(), None)\n            if func:\n                results.append(visitor(suffix, func))\n    return results",
    "docstring": "Use visitor partern to collect information from handlers"
  },
  {
    "code": "def receive(self, path, diff, showProgress=True):\n        directory = os.path.dirname(path)\n        cmd = [\"btrfs\", \"receive\", \"-e\", directory]\n        if Store.skipDryRun(logger, self.dryrun)(\"Command: %s\", cmd):\n            return None\n        if not os.path.exists(directory):\n            os.makedirs(directory)\n        process = subprocess.Popen(\n            cmd,\n            stdin=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n            stdout=DEVNULL,\n        )\n        _makeNice(process)\n        return _Writer(process, process.stdin, path, diff, showProgress)",
    "docstring": "Return a context manager for stream that will store a diff."
  },
  {
    "code": "def update_models(ctx, f=False):\n    if f:\n        manage(ctx, 'create_models_from_sql --force True', env={})\n    else:\n        manage(ctx, 'create_models_from_sql', env={})",
    "docstring": "Updates local django db projects models using salic database from\n    MinC"
  },
  {
    "code": "def shutdown(self, exitcode=0):\n        logger.info(\"shutting down system stats and metadata service\")\n        self._system_stats.shutdown()\n        self._meta.shutdown()\n        if self._cloud:\n            logger.info(\"stopping streaming files and file change observer\")\n            self._stop_file_observer()\n            self._end_file_syncing(exitcode)\n        self._run.history.close()",
    "docstring": "Stops system stats, streaming handlers, and uploads files without output, used by wandb.monitor"
  },
  {
    "code": "def configuration_to_dict(handlers):\n    config_dict = defaultdict(dict)\n    for handler in handlers:\n        for option in handler.set_options:\n            value = _get_option(handler.target_obj, option)\n            config_dict[handler.section_prefix][option] = value\n    return config_dict",
    "docstring": "Returns configuration data gathered by given handlers as a dict.\n\n    :param list[ConfigHandler] handlers: Handlers list,\n        usually from parse_configuration()\n\n    :rtype: dict"
  },
  {
    "code": "def serialize(self, subject, *objects_or_combinators):\n        ec_s = rdflib.BNode()\n        if self.operator is not None:\n            if subject is not None:\n                yield subject, self.predicate, ec_s\n            yield from oc(ec_s)\n            yield from self._list.serialize(ec_s, self.operator, *objects_or_combinators)\n        else:\n            for thing in objects_or_combinators:\n                if isinstance(thing, Combinator):\n                    object = rdflib.BNode()\n                    hasType = False\n                    for t in thing(object):\n                        if t[1] == rdf.type:\n                            hasType = True\n                        yield t\n                    if not hasType:\n                        yield object, rdf.type, owl.Class\n                else:\n                    object = thing\n                yield subject, self.predicate, object",
    "docstring": "object_combinators may also be URIRefs or Literals"
  },
  {
    "code": "def plotDutyCycles(dutyCycle, filePath):\n  _,entropy = binaryEntropy(dutyCycle)\n  bins = np.linspace(0.0, 0.3, 200)\n  plt.hist(dutyCycle, bins, alpha=0.5, label='All cols')\n  plt.title(\"Histogram of duty cycles, entropy=\" + str(float(entropy)))\n  plt.xlabel(\"Duty cycle\")\n  plt.ylabel(\"Number of units\")\n  plt.savefig(filePath)\n  plt.close()",
    "docstring": "Create plot showing histogram of duty cycles\n\n  :param dutyCycle: (torch tensor) the duty cycle of each unit\n  :param filePath: (str) Full filename of image file"
  },
  {
    "code": "def resizeColumnsToContents(self, startCol=None, stopCol=None):\n        numCols = self.model().columnCount()\n        startCol = 0 if startCol is None else max(startCol, 0)\n        stopCol  = numCols if stopCol is None else min(stopCol, numCols)\n        row = 0\n        for col in range(startCol, stopCol):\n            indexWidget = self.indexWidget(self.model().index(row, col))\n            if indexWidget:\n                contentsWidth = indexWidget.sizeHint().width()\n            else:\n                contentsWidth = self.header().sectionSizeHint(col)\n            self.header().resizeSection(col, contentsWidth)",
    "docstring": "Resizes all columns to the contents"
  },
  {
    "code": "def query_term(self, term, verbose=False):\n        if term not in self:\n            sys.stderr.write(\"Term %s not found!\\n\" % term)\n            return\n        rec = self[term]\n        if verbose:\n            print(rec)\n            sys.stderr.write(\"all parents: {}\\n\".format(\n                repr(rec.get_all_parents())))\n            sys.stderr.write(\"all children: {}\\n\".format(\n                repr(rec.get_all_children())))\n        return rec",
    "docstring": "Given a GO ID, return GO object."
  },
  {
    "code": "def new(self, path, desc=None, bare=True):\n        if os.path.exists(path):\n            raise RepoError('Path already exists: %s' % path)\n        try:\n            os.mkdir(path)\n            if bare:\n                Repo.init_bare(path)\n            else:\n                Repo.init(path)\n            repo = Local(path)\n            if desc:\n                repo.setDescription(desc)\n            version = repo.addVersion()\n            version.save('Repo Initialization')\n            return repo\n        except Exception, e:\n            traceback.print_exc()\n            raise RepoError('Error creating repo')",
    "docstring": "Create a new bare repo.Local instance.\n\n        :param path: Path to new repo.\n        :param desc: Repo description.\n        :param bare: Create as bare repo.\n\n        :returns: New repo.Local instance."
  },
  {
    "code": "def use_google_symbol(fct):\n    def decorator(symbols):\n        google_symbols = []\n        if isinstance(symbols, str):\n            symbols = [symbols]\n        symbols = sorted(symbols)\n        for symbol in symbols:\n            dot_pos = symbol.find('.')\n            google_symbols.append(\n                symbol[:dot_pos] if (dot_pos > 0) else symbol)\n        data = fct(google_symbols)\n        data.columns = [s for s in symbols if s.split('.')[0] in data.columns]\n        return data\n    return decorator",
    "docstring": "Removes \".PA\" or other market indicator from yahoo symbol\n    convention to suit google convention"
  },
  {
    "code": "def get_currencies_info() -> Element:\n    response = requests.get(const.CBRF_API_URLS['info'])\n    return XML(response.text)",
    "docstring": "Get META information about currencies\n\n    url: http://www.cbr.ru/scripts/XML_val.asp\n\n    :return: :class: `Element <Element 'Valuta'>` object\n    :rtype: ElementTree.Element"
  },
  {
    "code": "def _write(self, str_buf):\n    self._filehandle.write(str_buf)\n    self._buf_size += len(str_buf)",
    "docstring": "Uses the filehandle to the file in GCS to write to it."
  },
  {
    "code": "def validate(self, value):\n        cast_callback = self.cast_callback if self.cast_callback else self.cast_type\n        try:\n            return value if isinstance(value, self.cast_type) else cast_callback(value)\n        except Exception:\n            raise NodeTypeError('Invalid value `{}` for {}.'.format(value, self.cast_type))",
    "docstring": "Base validation method. Check if type is valid, or try brute casting.\n\n        Args:\n            value (object): A value for validation.\n\n        Returns:\n            Base_type instance.\n\n        Raises:\n            SchemaError, if validation or type casting fails."
  },
  {
    "code": "def connect_entry_signals():\n    post_save.connect(\n        ping_directories_handler, sender=Entry,\n        dispatch_uid=ENTRY_PS_PING_DIRECTORIES)\n    post_save.connect(\n        ping_external_urls_handler, sender=Entry,\n        dispatch_uid=ENTRY_PS_PING_EXTERNAL_URLS)\n    post_save.connect(\n        flush_similar_cache_handler, sender=Entry,\n        dispatch_uid=ENTRY_PS_FLUSH_SIMILAR_CACHE)\n    post_delete.connect(\n        flush_similar_cache_handler, sender=Entry,\n        dispatch_uid=ENTRY_PD_FLUSH_SIMILAR_CACHE)",
    "docstring": "Connect all the signals on Entry model."
  },
  {
    "code": "def update_idxs(self):\n        \"set root idx highest, tip idxs lowest ordered as ladderized\"\n        idx = self.ttree.nnodes - 1\n        for node in self.ttree.treenode.traverse(\"levelorder\"):\n            if not node.is_leaf():\n                node.add_feature(\"idx\", idx)\n                if not node.name:\n                    node.name = str(idx)\n                idx -= 1\n        for node in self.ttree.treenode.get_leaves():\n            node.add_feature(\"idx\", idx)\n            if not node.name:\n                node.name = str(idx)\n            idx -= 1",
    "docstring": "set root idx highest, tip idxs lowest ordered as ladderized"
  },
  {
    "code": "def updateIncomeProcess(self):\n        if self.cycles == 0:\n            tax_rate = (self.IncUnemp*self.UnempPrb)/((1.0-self.UnempPrb)*self.IndL)\n            TranShkDstn     = deepcopy(approxMeanOneLognormal(self.TranShkCount,sigma=self.TranShkStd[0],tail_N=0))\n            TranShkDstn[0]  = np.insert(TranShkDstn[0]*(1.0-self.UnempPrb),0,self.UnempPrb)\n            TranShkDstn[1]  = np.insert(TranShkDstn[1]*(1.0-tax_rate)*self.IndL,0,self.IncUnemp)\n            PermShkDstn     = approxMeanOneLognormal(self.PermShkCount,sigma=self.PermShkStd[0],tail_N=0)\n            self.IncomeDstn = [combineIndepDstns(PermShkDstn,TranShkDstn)]\n            self.TranShkDstn = TranShkDstn\n            self.PermShkDstn = PermShkDstn\n            self.addToTimeVary('IncomeDstn')\n        else:\n            EstimationAgentClass.updateIncomeProcess(self)",
    "docstring": "An alternative method for constructing the income process in the infinite horizon model.\n\n        Parameters\n        ----------\n        none\n\n        Returns\n        -------\n        none"
  },
  {
    "code": "def _load_resources(self):\n        for resource in self.RESOURCES:\n            if isinstance(resource, goldman.ModelsResource):\n                route = '/%s' % resource.rtype\n            elif isinstance(resource, goldman.ModelResource):\n                route = '/%s/{rid}' % resource.rtype\n            elif isinstance(resource, goldman.RelatedResource):\n                route = '/%s/{rid}/{related}' % resource.rtype\n            else:\n                raise TypeError('unsupported resource type')\n            self.add_route(*(route, resource))",
    "docstring": "Load all the native goldman resources.\n\n        The route or API endpoint will be automatically determined\n        based on the resource object instance passed in.\n\n        INFO: Only our Model based resources are supported when\n              auto-generating API endpoints."
  },
  {
    "code": "def min_row_dist_sum_idx(dists):\n    row_sums = np.apply_along_axis(arr=dists, axis=0, func1d=np.sum)\n    return row_sums.argmin()",
    "docstring": "Find the index of the row with the minimum row distance sum \n\n    This should return the index of the row index with the least distance overall \n    to all other rows. \n\n    Args:\n        dists (np.array): must be square distance matrix\n\n    Returns:\n        int: index of row with min dist row sum"
  },
  {
    "code": "def _generate_tokens(self, text):\n    for index, tok in enumerate(tokenize.generate_tokens(io.StringIO(text).readline)):\n      tok_type, tok_str, start, end, line = tok\n      yield Token(tok_type, tok_str, start, end, line, index,\n                  self._line_numbers.line_to_offset(start[0], start[1]),\n                  self._line_numbers.line_to_offset(end[0], end[1]))",
    "docstring": "Generates tokens for the given code."
  },
  {
    "code": "def like_button_js_tag(context):\n    if FACEBOOK_APP_ID is None:\n        log.warning(\"FACEBOOK_APP_ID isn't setup correctly in your settings\")\n    if FACEBOOK_APP_ID:\n        request = context.get('request', None)\n        if request:\n            return {\"LIKE_BUTTON_IS_VALID\": True,\n                    \"facebook_app_id\": FACEBOOK_APP_ID,\n                    \"channel_base_url\": request.get_host()}\n    return {\"LIKE_BUTTON_IS_VALID\": False}",
    "docstring": "This tag will check to see if they have the FACEBOOK_LIKE_APP_ID setup\n        correctly in the django settings, if so then it will pass the data\n        along to the intercom_tag template to be displayed.\n\n        If something isn't perfect we will return False, which will then not\n        install the javascript since it isn't needed."
  },
  {
    "code": "def _subtract(summary, o):\n    found = False\n    row = [_repr(o), 1, _getsizeof(o)]\n    for r in summary:\n        if r[0] == row[0]:\n            (r[1], r[2]) = (r[1] - row[1], r[2] - row[2])\n            found = True\n    if not found:\n        summary.append([row[0], -row[1], -row[2]])\n    return summary",
    "docstring": "Remove object o from the summary by subtracting it's size."
  },
  {
    "code": "def _schedule_ad(self, delay=None, response_future=None):\n        if not self.running:\n            return\n        if delay is None:\n            delay = self.interval_secs\n        delay += random.uniform(0, self.interval_max_jitter_secs)\n        self._next_ad = self.io_loop.call_later(delay, self._ad,\n                                                response_future)",
    "docstring": "Schedules an ``ad`` request.\n\n        :param delay:\n            Time in seconds to wait before making the ``ad`` request. Defaults\n            to self.interval_secs. Regardless of value, a jitter of\n            self.interval_max_jitter_secs is applied to this.\n        :param response_future:\n            If non-None, the result of the advertise request is filled into\n            this future."
  },
  {
    "code": "def has_child_objective_banks(self, objective_bank_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.has_child_catalogs(catalog_id=objective_bank_id)\n        return self._hierarchy_session.has_children(id_=objective_bank_id)",
    "docstring": "Tests if an objective bank has any children.\n\n        arg:    objective_bank_id (osid.id.Id): the ``Id`` of an\n                objective bank\n        return: (boolean) - ``true`` if the ``objective_bank_id`` has\n                children, ``false`` otherwise\n        raise:  NotFound - ``objective_bank_id`` is not found\n        raise:  NullArgument - ``objective_bank_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def safe_mongocall(call):\n    def _safe_mongocall(*args, **kwargs):\n        for i in range(4):\n            try:\n                return call(*args, **kwargs)\n            except pymongo.errors.AutoReconnect:\n                print ('AutoReconnecting, try %d' % i)\n                time.sleep(pow(2, i))\n        return call(*args, **kwargs)\n    return _safe_mongocall",
    "docstring": "Decorator for automatic handling of AutoReconnect-exceptions."
  },
  {
    "code": "def _get_interfaces(self):\n        ios_cfg = self._get_running_config()\n        parse = HTParser(ios_cfg)\n        itfcs_raw = parse.find_lines(\"^interface GigabitEthernet\")\n        itfcs = [raw_if.strip().split(' ')[1] for raw_if in itfcs_raw]\n        LOG.debug(\"Interfaces on hosting device: %s\", itfcs)\n        return itfcs",
    "docstring": "Get a list of interfaces on this hosting device.\n\n        :return: List of the interfaces"
  },
  {
    "code": "def executable_script(src_file, gallery_conf):\n    filename_pattern = gallery_conf.get('filename_pattern')\n    execute = re.search(filename_pattern, src_file) and gallery_conf[\n        'plot_gallery']\n    return execute",
    "docstring": "Validate if script has to be run according to gallery configuration\n\n    Parameters\n    ----------\n    src_file : str\n        path to python script\n\n    gallery_conf : dict\n        Contains the configuration of Sphinx-Gallery\n\n    Returns\n    -------\n    bool\n        True if script has to be executed"
  },
  {
    "code": "def delete_taskset(self, taskset_id):\n        s = self.restore_taskset(taskset_id)\n        if s:\n            s.delete()",
    "docstring": "Delete a saved taskset result."
  },
  {
    "code": "def update_GUI_with_new_interpretation(self):\n        self.update_fit_bounds_and_statistics()\n        self.draw_interpretations()\n        self.calculate_high_levels_data()\n        self.plot_high_levels_data()",
    "docstring": "update statistics boxes and figures with a new interpretatiom when\n        selecting new temperature bound"
  },
  {
    "code": "def get_auto_allocated_topology(self, project_id, **_params):\n        return self.get(\n            self.auto_allocated_topology_path % project_id,\n            params=_params)",
    "docstring": "Fetch information about a project's auto-allocated topology."
  },
  {
    "code": "def load_mode(node):\n    obs_mode = ObservingMode()\n    obs_mode.__dict__.update(node)\n    load_mode_validator(obs_mode, node)\n    load_mode_builder(obs_mode, node)\n    load_mode_tagger(obs_mode, node)\n    return obs_mode",
    "docstring": "Load one observing mdode"
  },
  {
    "code": "def createConnection(self):\n        connection = RemoteCardConnection(self.readerobj.createConnection())\n        daemon = PyroDaemon.PyroDaemon()\n        uri = daemon.connect(connection)\n        return uri",
    "docstring": "Return a card connection thru the reader."
  },
  {
    "code": "def create_dispatcher(self):\n        before_context = max(self.args.before_context, self.args.context)\n        after_context = max(self.args.after_context, self.args.context)\n        if self.args.files_with_match is not None or self.args.count or self.args.only_matching or self.args.quiet:\n            return UnbufferedDispatcher(self._channels)\n        elif before_context == 0 and after_context == 0:\n            return UnbufferedDispatcher(self._channels)\n        elif self.args.thread:\n            return ThreadedDispatcher(self._channels, before_context, after_context)\n        else:\n            return LineBufferDispatcher(self._channels, before_context, after_context)",
    "docstring": "Return a dispatcher for configured channels."
  },
  {
    "code": "def async_call(func, *args, callback=None):\n    def do_call():\n        result = None\n        error = None\n        try:\n            result = func(*args)\n        except Exception:\n            error = traceback.format_exc()\n            logger.error(error)\n        if callback:\n            GLib.idle_add(callback, result, error)\n    thread = threading.Thread(target=do_call)\n    thread.daemon = True\n    thread.start()",
    "docstring": "Call `func` in background thread, and then call `callback` in Gtk main thread.\n\n    If error occurs in `func`, error will keep the traceback and passed to\n    `callback` as second parameter. Always check `error` is not None."
  },
  {
    "code": "def users_text(self):\n        if self._users_text is None:\n            self.chain.connection.log(\"Getting connected users text\")\n            self._users_text = self.driver.get_users_text()\n            if self._users_text:\n                self.chain.connection.log(\"Users text collected\")\n            else:\n                self.chain.connection.log(\"Users text not collected\")\n        return self._users_text",
    "docstring": "Return connected users information and collect if not available."
  },
  {
    "code": "def export_args(subparsers):\n    export_parser = subparsers.add_parser('export')\n    export_parser.add_argument('directory',\n                               help='Path where secrets will be exported into')\n    secretfile_args(export_parser)\n    vars_args(export_parser)\n    base_args(export_parser)",
    "docstring": "Add command line options for the export operation"
  },
  {
    "code": "def add_annotation(self, description, **attrs):\n        at = attributes.Attributes(attrs)\n        self.add_time_event(time_event_module.TimeEvent(datetime.utcnow(),\n                            time_event_module.Annotation(description, at)))",
    "docstring": "Add an annotation to span.\n\n        :type description: str\n        :param description: A user-supplied message describing the event.\n                        The maximum length for the description is 256 bytes.\n\n        :type attrs: kwargs\n        :param attrs: keyworded arguments e.g. failed=True, name='Caching'"
  },
  {
    "code": "def filter_keys_by_dataset_id(did, key_container):\n    keys = iter(key_container)\n    for key in DATASET_KEYS:\n        if getattr(did, key) is not None:\n            if key == \"wavelength\":\n                keys = [k for k in keys\n                        if (getattr(k, key) is not None and\n                            DatasetID.wavelength_match(getattr(k, key),\n                                                       getattr(did, key)))]\n            else:\n                keys = [k for k in keys\n                        if getattr(k, key) is not None and getattr(k, key)\n                        == getattr(did, key)]\n    return keys",
    "docstring": "Filer provided key iterable by the provided `DatasetID`.\n\n    Note: The `modifiers` attribute of `did` should be `None` to allow for\n          **any** modifier in the results.\n\n    Args:\n        did (DatasetID): Query parameters to match in the `key_container`.\n        key_container (iterable): Set, list, tuple, or dict of `DatasetID`\n                                  keys.\n\n    Returns (list): List of keys matching the provided parameters in no\n                    specific order."
  },
  {
    "code": "def _get_function_id(self):\n        if self.is_for_driver_task:\n            return ray.FunctionID.nil()\n        function_id_hash = hashlib.sha1()\n        function_id_hash.update(self.module_name.encode(\"ascii\"))\n        function_id_hash.update(self.function_name.encode(\"ascii\"))\n        function_id_hash.update(self.class_name.encode(\"ascii\"))\n        function_id_hash.update(self._function_source_hash)\n        function_id = function_id_hash.digest()\n        return ray.FunctionID(function_id)",
    "docstring": "Calculate the function id of current function descriptor.\n\n        This function id is calculated from all the fields of function\n        descriptor.\n\n        Returns:\n            ray.ObjectID to represent the function descriptor."
  },
  {
    "code": "def get_palette(samples, options, return_mask=False, kmeans_iter=40):\n    if not options.quiet:\n        print('  getting palette...')\n    bg_color = get_bg_color(samples, 6)\n    fg_mask = get_fg_mask(bg_color, samples, options)\n    centers, _ = kmeans(samples[fg_mask].astype(np.float32),\n                        options.num_colors-1,\n                        iter=kmeans_iter)\n    palette = np.vstack((bg_color, centers)).astype(np.uint8)\n    if not return_mask:\n        return palette\n    else:\n        return palette, fg_mask",
    "docstring": "Extract the palette for the set of sampled RGB values. The first\npalette entry is always the background color; the rest are determined\nfrom foreground pixels by running K-means clustering. Returns the\npalette, as well as a mask corresponding to the foreground pixels."
  },
  {
    "code": "def run(self):\n        try:\n            self._connect()\n            self._register()\n            while True:\n                try:\n                    body = self.command_queue.get(block=True, timeout=1 * SECOND)\n                except queue.Empty:\n                    body = None\n                if body is not None:\n                    result = self._send(body)\n                    if result:\n                        self.command_queue.task_done()\n                    else:\n                        self._disconnect()\n                        self._connect()\n                        self._register()\n                if self._stop_event.is_set():\n                    logger.debug(\"CoreAgentSocket thread stopping.\")\n                    break\n        except Exception:\n            logger.debug(\"CoreAgentSocket thread exception.\")\n        finally:\n            self._started_event.clear()\n            self._stop_event.clear()\n            self._stopped_event.set()\n            logger.debug(\"CoreAgentSocket thread stopped.\")",
    "docstring": "Called by the threading system"
  },
  {
    "code": "def get_permissions(self):\n        permissions = set()\n        permissions.update(self.resource_manager.get_permissions())\n        for f in self.resource_manager.filters:\n            permissions.update(f.get_permissions())\n        for a in self.resource_manager.actions:\n            permissions.update(a.get_permissions())\n        return permissions",
    "docstring": "get permissions needed by this policy"
  },
  {
    "code": "def authorized_connect_apps(self):\n        if self._authorized_connect_apps is None:\n            self._authorized_connect_apps = AuthorizedConnectAppList(\n                self._version,\n                account_sid=self._solution['sid'],\n            )\n        return self._authorized_connect_apps",
    "docstring": "Access the authorized_connect_apps\n\n        :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList\n        :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList"
  },
  {
    "code": "def check_call(self, cmd):\n        ret, _ = self._call(cmd, False)\n        if ret != 0:\n            raise RemoteCommandFailure(command=cmd, ret=ret)",
    "docstring": "Calls a command through SSH."
  },
  {
    "code": "def last_year(date_):\n    day = 28 if date_.day == 29 and date_.month == 2 else date_.day\n    return datetime.date(date_.year-1, date_.month, day)",
    "docstring": "Returns the same date 1 year ago.\n\n    Args:\n        date (datetime or datetime.date)\n    Returns:\n        (datetime or datetime.date)\n    Raises:\n        -"
  },
  {
    "code": "def get_uniquely_named_objects_by_name(object_list):\n    if not object_list:\n        return dict()\n    result = dict()\n    for obj in object_list:\n        name = obj.name.value\n        if name in result:\n            raise GraphQLCompilationError(u'Found duplicate object key: '\n                                          u'{} {}'.format(name, object_list))\n        result[name] = obj\n    return result",
    "docstring": "Return dict of name -> object pairs from a list of objects with unique names.\n\n    Args:\n        object_list: list of objects, each X of which has a unique name accessible as X.name.value\n\n    Returns:\n        dict, { X.name.value: X for x in object_list }\n        If the list is empty or None, returns an empty dict."
  },
  {
    "code": "def run(self):\n        self.exc = None\n        try:\n            self.task()\n        except BaseException:\n            self.exc = sys.exc_info()",
    "docstring": "Overwrites `threading.Thread.run`, to allow handling of exceptions thrown by threads\n        from within the main app."
  },
  {
    "code": "async def untilTrue(condition, *args, timeout=5) -> bool:\n    result = False\n    start = time.perf_counter()\n    elapsed = 0\n    while elapsed < timeout:\n        result = condition(*args)\n        if result:\n            break\n        await asyncio.sleep(.1)\n        elapsed = time.perf_counter() - start\n    return result",
    "docstring": "Keep checking the condition till it is true or a timeout is reached\n\n    :param condition: the condition to check (a function that returns bool)\n    :param args: the arguments to the condition\n    :return: True if the condition is met in the given timeout, False otherwise"
  },
  {
    "code": "def get(self, mac):\n        data = {\n            self._FORMAT_F: 'json',\n            self._SEARCH_F: mac\n        }\n        response = self.__decode_str(self.__call_api(self.__url, data), 'utf-8')\n        if len(response) > 0:\n            return self.__parse(response)\n        raise EmptyResponseException()",
    "docstring": "Get data from API as instance of ResponseModel.\n\n            Keyword arguments:\n            mac -- MAC address or OUI for searching"
  },
  {
    "code": "def show_message(self, message, duration=2500):\n        self.setText(message)\n        self.__duration = duration\n        self.__set_position()\n        if message:\n            self.__fade_in()\n        else:\n            self.__fade_out()\n        return True",
    "docstring": "Shows given message.\n\n        :param message: Message.\n        :type message: unicode\n        :param duration: Notification duration in milliseconds.\n        :type duration: int\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def insert(self, data):\n        if not data:\n            return\n        data = self._compress_by_md5(data)\n        name = self.key + str(int(data[0:2], 16) % self.block_num)\n        for h in self.hash_function:\n            local_hash = h.hash(data)\n            self.server.setbit(name, local_hash, 1)",
    "docstring": "Insert 1 into each bit by local_hash"
  },
  {
    "code": "def _getsie(self):\n        try:\n            value, newpos = self._readsie(0)\n            if value is None or newpos != self.len:\n                raise ReadError\n        except ReadError:\n            raise InterpretError(\"Bitstring is not a single interleaved exponential-Golomb code.\")\n        return value",
    "docstring": "Return data as signed interleaved exponential-Golomb code.\n\n        Raises InterpretError if bitstring is not a single exponential-Golomb code."
  },
  {
    "code": "def save(self):\n        with open(self.path, \"w\") as f:\n            self.config[\"project_templates\"] = list(filter(lambda template: template.get(\"url\"), self.config[\"project_templates\"]))\n            yaml.dump(self.config, f, default_flow_style=False)",
    "docstring": "Save settings."
  },
  {
    "code": "def get_doc(project, source_code, offset, resource=None, maxfixes=1):\n    fixer = fixsyntax.FixSyntax(project, source_code, resource, maxfixes)\n    pyname = fixer.pyname_at(offset)\n    if pyname is None:\n        return None\n    pyobject = pyname.get_object()\n    return PyDocExtractor().get_doc(pyobject)",
    "docstring": "Get the pydoc"
  },
  {
    "code": "def update_trial_stats(self, trial, result):\n        assert trial in self._live_trials\n        assert self._get_result_time(result) >= 0\n        delta = self._get_result_time(result) - \\\n            self._get_result_time(self._live_trials[trial])\n        assert delta >= 0\n        self._completed_progress += delta\n        self._live_trials[trial] = result",
    "docstring": "Update result for trial. Called after trial has finished\n        an iteration - will decrement iteration count.\n\n        TODO(rliaw): The other alternative is to keep the trials\n        in and make sure they're not set as pending later."
  },
  {
    "code": "def convert(self, value, view):\n        if isinstance(value, BASESTRING):\n            if self.pattern and not self.regex.match(value):\n                self.fail(\n                    u\"must match the pattern {0}\".format(self.pattern),\n                    view\n                )\n            return value\n        else:\n            self.fail(u'must be a string', view, True)",
    "docstring": "Check that the value is a string and matches the pattern."
  },
  {
    "code": "def download_file_insecure(url, target):\n    src = urlopen(url)\n    try:\n        data = src.read()\n    finally:\n        src.close()\n    with open(target, \"wb\") as dst:\n        dst.write(data)",
    "docstring": "Use Python to download the file, without connection authentication."
  },
  {
    "code": "def memberships_assignable(self, group, include=None):\n        return self._get(self._build_url(self.endpoint.memberships_assignable(id=group, include=include)))",
    "docstring": "Return memberships that are assignable for this group.\n\n        :param include: list of objects to sideload. `Side-loading API Docs \n            <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.\n        :param group: Group object or id"
  },
  {
    "code": "def _auth_req_callback_func(self, context, internal_request):\n        state = context.state\n        state[STATE_KEY] = {\"requester\": internal_request.requester}\n        try:\n            state_dict = context.state[consent.STATE_KEY]\n        except KeyError:\n            state_dict = context.state[consent.STATE_KEY] = {}\n        finally:\n            state_dict.update({\n                \"filter\": internal_request.attributes or [],\n                \"requester_name\": internal_request.requester_name,\n            })\n        satosa_logging(logger, logging.INFO,\n                       \"Requesting provider: {}\".format(internal_request.requester), state)\n        if self.request_micro_services:\n            return self.request_micro_services[0].process(context, internal_request)\n        return self._auth_req_finish(context, internal_request)",
    "docstring": "This function is called by a frontend module when an authorization request has been\n        processed.\n\n        :type context: satosa.context.Context\n        :type internal_request: satosa.internal.InternalData\n        :rtype: satosa.response.Response\n\n        :param context: The request context\n        :param internal_request: request processed by the frontend\n\n        :return: response"
  },
  {
    "code": "def cg(output,\n       show,\n       verbose,\n       classname,\n       methodname,\n       descriptor,\n       accessflag,\n       no_isolated,\n       apk):\n    androcg_main(verbose=verbose,\n                 APK=apk,\n                 classname=classname,\n                 methodname=methodname,\n                 descriptor=descriptor,\n                 accessflag=accessflag,\n                 no_isolated=no_isolated,\n                 show=show,\n                 output=output)",
    "docstring": "Create a call graph and export it into a graph format.\n\n    classnames are found in the type \"Lfoo/bar/bla;\".\n\n    Example:\n\n    \\b\n        $ androguard cg APK"
  },
  {
    "code": "def get_aliases(self, includename=True):\n        alias_quanta = self.get(self._KEYS.ALIAS, [])\n        aliases = [aq[QUANTITY.VALUE] for aq in alias_quanta]\n        if includename and self[self._KEYS.NAME] not in aliases:\n            aliases = [self[self._KEYS.NAME]] + aliases\n        return aliases",
    "docstring": "Retrieve the aliases of this object as a list of strings.\n\n        Arguments\n        ---------\n        includename : bool\n            Include the 'name' parameter in the list of aliases."
  },
  {
    "code": "def child_url_record(self, url: str, inline: bool=False,\n                         link_type: Optional[LinkType]=None,\n                         post_data: Optional[str]=None,\n                         level: Optional[int]=None):\n        url_record = URLRecord()\n        url_record.url = url\n        url_record.status = Status.todo\n        url_record.try_count = 0\n        url_record.level = self.url_record.level + 1 if level is None else level\n        url_record.root_url = self.url_record.root_url or self.url_record.url\n        url_record.parent_url = self.url_record.url\n        url_record.inline_level = (self.url_record.inline_level or 0) + 1 if inline else 0\n        url_record.link_type = link_type\n        url_record.post_data = post_data\n        return url_record",
    "docstring": "Return a child URLRecord.\n\n        This function is useful for testing filters before adding to table."
  },
  {
    "code": "def delete(self):\n        if not self.email_enabled:\n            raise EmailNotEnabledError(\"See settings.EMAIL_ENABLED\")\n        return requests.delete(\n            f\"{self.api_url}/{self.address}\", auth=(\"api\", self.api_key)\n        )",
    "docstring": "Returns a response after attempting to delete the list."
  },
  {
    "code": "def _start_remaining_containers(self, containers_remaining, tool_d):\n        s_containers = []\n        f_containers = []\n        for container in containers_remaining:\n            s_containers, f_containers = self._start_container(container,\n                                                               tool_d,\n                                                               s_containers,\n                                                               f_containers)\n        return (s_containers, f_containers)",
    "docstring": "Select remaining containers that didn't have priorities to start"
  },
  {
    "code": "def find_blocked_biomass_precursors(reaction, model):\n    LOGGER.debug(\"Finding blocked biomass precursors\")\n    precursors = find_biomass_precursors(model, reaction)\n    blocked_precursors = list()\n    _, ub = helpers.find_bounds(model)\n    for precursor in precursors:\n        with model:\n            dm_rxn = model.add_boundary(\n                precursor,\n                type=\"safe-demand\",\n                reaction_id=\"safe_demand\",\n                lb=0,\n                ub=ub\n            )\n            flux = helpers.run_fba(model, dm_rxn.id, direction='max')\n            if np.isnan(flux) or abs(flux) < 1E-08:\n                blocked_precursors.append(precursor)\n    return blocked_precursors",
    "docstring": "Return a list of all biomass precursors that cannot be produced.\n\n    Parameters\n    ----------\n    reaction : cobra.core.reaction.Reaction\n        The biomass reaction of the model under investigation.\n    model : cobra.Model\n        The metabolic model under investigation.\n\n    Returns\n    -------\n    list\n        Metabolite objects that are reactants of the biomass reaction excluding\n        ATP and H2O that cannot be produced by flux balance analysis."
  },
  {
    "code": "def get_vars(self):\n\t\tif self.method() != 'GET':\n\t\t\traise RuntimeError('Unable to return get vars for non-get method')\n\t\tre_search = WWebRequestProto.get_vars_re.search(self.path())\n\t\tif re_search is not None:\n\t\t\treturn urllib.parse.parse_qs(re_search.group(1), keep_blank_values=1)",
    "docstring": "Parse request path and return GET-vars\n\n\t\t:return: None or dictionary of names and tuples of values"
  },
  {
    "code": "def launch_keyword_wizard(self):\n        if self.iface.activeLayer() != self.output_layer:\n            return\n        keyword_wizard = WizardDialog(\n            self.iface.mainWindow(), self.iface, self.dock_widget)\n        keyword_wizard.set_keywords_creation_mode(self.output_layer)\n        keyword_wizard.exec_()",
    "docstring": "Launch keyword creation wizard."
  },
  {
    "code": "def gen_colors(img):\n    color_cmd = ColorThief(img).get_palette\n    for i in range(0, 10, 1):\n        raw_colors = color_cmd(color_count=8 + i)\n        if len(raw_colors) >= 8:\n            break\n        elif i == 10:\n            logging.error(\"ColorThief couldn't generate a suitable palette.\")\n            sys.exit(1)\n        else:\n            logging.warning(\"ColorThief couldn't generate a palette.\")\n            logging.warning(\"Trying a larger palette size %s\", 8 + i)\n    return [util.rgb_to_hex(color) for color in raw_colors]",
    "docstring": "Loop until 16 colors are generated."
  },
  {
    "code": "def get_func(func, aliasing, implementations):\n    try:\n        func_str = aliasing[func]\n    except KeyError:\n        if callable(func):\n            return func\n    else:\n        if func_str in implementations:\n            return func_str\n        if func_str.startswith('nan') and \\\n                func_str[3:] in funcs_no_separate_nan:\n            raise ValueError(\"%s does not have a nan-version\".format(func_str[3:]))\n        else:\n            raise NotImplementedError(\"No such function available\")\n    raise ValueError(\"func %s is neither a valid function string nor a \"\n                     \"callable object\".format(func))",
    "docstring": "Return the key of a found implementation or the func itself"
  },
  {
    "code": "def log_with_color(level):\n    def wrapper(text):\n        color = log_colors_config[level.upper()]\n        getattr(logger, level.lower())(coloring(text, color))\n    return wrapper",
    "docstring": "log with color by different level"
  },
  {
    "code": "def _metaconfigure(self, argv=None):\n        metaconfig = self._get_metaconfig_class()\n        if not metaconfig:\n            return\n        if self.__class__ is metaconfig:\n            return\n        override = {\n            'conflict_handler': 'resolve',\n            'add_help': False,\n            'prog': self._parser_kwargs.get('prog'),\n        }\n        self._metaconf = metaconfig(**override)\n        metaparser = self._metaconf.build_parser(\n            options=self._metaconf._options, permissive=False, **override)\n        self._parser_kwargs.setdefault('parents', [])\n        self._parser_kwargs['parents'].append(metaparser)\n        self._metaconf._values = self._metaconf.load_options(\n            argv=argv)\n        self._metaconf.provision(self)",
    "docstring": "Initialize metaconfig for provisioning self."
  },
  {
    "code": "def aggregate_key(self, aggregate_key):\n        aggregation = self.data_dict[aggregate_key]\n        data_dict_keys = {y for x in aggregation for y in x.keys()}\n        for key in data_dict_keys:\n            stacked = np.stack([d[key] for d in aggregation], axis=0)\n            self.data_dict[key] = np.mean(stacked, axis=0)",
    "docstring": "Aggregate values from key and put them into the top-level dictionary"
  },
  {
    "code": "def LookupNamespace(self, prefix):\n        ret = libxml2mod.xmlTextReaderLookupNamespace(self._o, prefix)\n        return ret",
    "docstring": "Resolves a namespace prefix in the scope of the current\n           element."
  },
  {
    "code": "def available_backends(self, hub=None, group=None, project=None, access_token=None, user_id=None):\n        if access_token:\n            self.req.credential.set_token(access_token)\n        if user_id:\n            self.req.credential.set_user_id(user_id)\n        if not self.check_credentials():\n            raise CredentialsError('credentials invalid')\n        else:\n            url = get_backend_url(self.config, hub, group, project)\n            ret = self.req.get(url)\n            if (ret is not None) and (isinstance(ret, dict)):\n                return []\n            return [backend for backend in ret\n                    if backend.get('status') == 'on']",
    "docstring": "Get the backends available to use in the QX Platform"
  },
  {
    "code": "def ListLanguageIdentifiers(self):\n    table_view = views.ViewsFactory.GetTableView(\n        self._views_format_type, column_names=['Identifier', 'Language'],\n        title='Language identifiers')\n    for language_id, value_list in sorted(\n        language_ids.LANGUAGE_IDENTIFIERS.items()):\n      table_view.AddRow([language_id, value_list[1]])\n    table_view.Write(self._output_writer)",
    "docstring": "Lists the language identifiers."
  },
  {
    "code": "def kill_tweens(self, obj = None):\n        if obj is not None:\n            try:\n                del self.current_tweens[obj]\n            except:\n                pass\n        else:\n            self.current_tweens = collections.defaultdict(set)",
    "docstring": "Stop tweening an object, without completing the motion or firing the\n        on_complete"
  },
  {
    "code": "def _to_numeric(val):\n    if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):\n        return val\n    return float(val)",
    "docstring": "Helper function for conversion of various data types into numeric representation."
  },
  {
    "code": "def delete_edge_by_nodes(self, node_a, node_b):\n        node = self.get_node(node_a)\n        edge_ids = []\n        for e_id in node['edges']:\n            edge = self.get_edge(e_id)\n            if edge['vertices'][1] == node_b:\n                edge_ids.append(e_id)\n        for e in edge_ids:\n            self.delete_edge_by_id(e)",
    "docstring": "Removes all the edges from node_a to node_b from the graph."
  },
  {
    "code": "def scores(self, result, add_new_line=True):\n        if result.goalsHomeTeam > result.goalsAwayTeam:\n            homeColor, awayColor = (self.colors.WIN, self.colors.LOSE)\n        elif result.goalsHomeTeam < result.goalsAwayTeam:\n            homeColor, awayColor = (self.colors.LOSE, self.colors.WIN)\n        else:\n            homeColor = awayColor = self.colors.TIE\n        click.secho('%-25s %2s' % (result.homeTeam, result.goalsHomeTeam),\n                    fg=homeColor, nl=False)\n        click.secho(\"  vs \", nl=False)\n        click.secho('%2s %s' % (result.goalsAwayTeam,\n                                result.awayTeam.rjust(25)), fg=awayColor,\n                    nl=add_new_line)",
    "docstring": "Prints out the scores in a pretty format"
  },
  {
    "code": "def _parse_state(self, config):\n        value = STATE_RE.search(config).group('value')\n        return dict(state=value)",
    "docstring": "_parse_state scans the provided configuration block and extracts\n        the vlan state value.  The config block is expected to always return\n        the vlan state config.  The return dict is inteded to be merged into\n        the response dict.\n\n        Args:\n            config (str): The vlan configuration block from the nodes\n                running configuration\n\n        Returns:\n            dict: resource dict attribute"
  },
  {
    "code": "def settle_timeout(self) -> int:\n        filter_args = get_filter_args_for_specific_event_from_channel(\n            token_network_address=self.token_network.address,\n            channel_identifier=self.channel_identifier,\n            event_name=ChannelEvent.OPENED,\n            contract_manager=self.contract_manager,\n        )\n        events = self.token_network.proxy.contract.web3.eth.getLogs(filter_args)\n        assert len(events) > 0, 'No matching ChannelOpen event found.'\n        event = decode_event(\n            self.contract_manager.get_contract_abi(CONTRACT_TOKEN_NETWORK),\n            events[-1],\n        )\n        return event['args']['settle_timeout']",
    "docstring": "Returns the channels settle_timeout."
  },
  {
    "code": "def compute_discounts(self, precision=None):\n        gross = self.compute_gross(precision)\n        return min(gross,\n                   sum([d.compute(gross, precision) for d in self.__discounts]))",
    "docstring": "Returns the total amount of discounts for this line with a specific\n        number of decimals.\n        @param precision:int number of decimal places\n        @return: Decimal"
  },
  {
    "code": "def getBigIndexFromIndices(self, indices):\n        return reduce(operator.add, [self.dimProd[i]*indices[i]\n                                     for i in range(self.ndims)], 0)",
    "docstring": "Get the big index from a given set of indices\n        @param indices\n        @return big index\n        @note no checks are performed to ensure that the returned\n        indices are valid"
  },
  {
    "code": "def clear_hidden(self, iso_path=None, rr_path=None, joliet_path=None):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInvalidInput('This object is not yet initialized; call either open() or new() to create an ISO')\n        if len([x for x in (iso_path, rr_path, joliet_path) if x is not None]) != 1:\n            raise pycdlibexception.PyCdlibInvalidInput('Must provide exactly one of iso_path, rr_path, or joliet_path')\n        if iso_path is not None:\n            rec = self._find_iso_record(utils.normpath(iso_path))\n        elif rr_path is not None:\n            rec = self._find_rr_record(utils.normpath(rr_path))\n        elif joliet_path is not None:\n            joliet_path_bytes = self._normalize_joliet_path(joliet_path)\n            rec = self._find_joliet_record(joliet_path_bytes)\n        rec.change_existence(False)",
    "docstring": "Clear the ISO9660 hidden attribute on a file or directory.  This will\n        cause the file or directory to show up when listing entries on the ISO.\n        Exactly one of iso_path, rr_path, or joliet_path must be specified.\n\n        Parameters:\n         iso_path - The path on the ISO to clear the hidden bit from.\n         rr_path - The Rock Ridge path on the ISO to clear the hidden bit from.\n         joliet_path - The Joliet path on the ISO to clear the hidden bit from.\n        Returns:\n         Nothing."
  },
  {
    "code": "def _enable_lock(func):\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        self = args[0]\n        if self.is_concurrent:\n            only_read = kwargs.get('only_read')\n            if only_read is None or only_read:\n                with self._rwlock:\n                    return func(*args, **kwargs)\n            else:\n                self._rwlock.acquire_writer()\n                try:\n                    return func(*args, **kwargs)\n                finally:\n                    self._rwlock.release()\n        else:\n            return func(*args, **kwargs)\n    return wrapper",
    "docstring": "The decorator for ensuring thread-safe when current cache instance is concurrent status."
  },
  {
    "code": "def selected_display_item(self) -> typing.Optional[DisplayItem.DisplayItem]:\n        display_item = self.focused_display_item\n        if not display_item:\n            selected_display_panel = self.selected_display_panel\n            display_item = selected_display_panel.display_item if selected_display_panel else None\n        return display_item",
    "docstring": "Return the selected display item.\n\n        The selected display is the display ite that has keyboard focus in the data panel or a display panel."
  },
  {
    "code": "def _get_column_width(self, complete_state):\n        return max(get_cwidth(c.display) for c in complete_state.current_completions) + 1",
    "docstring": "Return the width of each column."
  },
  {
    "code": "async def parse_response(response: ClientResponse, schema: dict) -> Any:\n    try:\n        data = await response.json()\n        response.close()\n        if schema is not None:\n            jsonschema.validate(data, schema)\n        return data\n    except (TypeError, json.decoder.JSONDecodeError) as e:\n        raise jsonschema.ValidationError(\"Could not parse json : {0}\".format(str(e)))",
    "docstring": "Validate and parse the BMA answer\n\n    :param response: Response of aiohttp request\n    :param schema: The expected response structure\n    :return: the json data"
  },
  {
    "code": "def template_cycles(self) -> int:\n        return sum((int(re.sub(r'\\D', '', op)) for op in self.template_tokens))",
    "docstring": "The number of cycles dedicated to template."
  },
  {
    "code": "def get_list_class(context, list):\n    return \"list_%s_%s\" % (list.model._meta.app_label, list.model._meta.model_name)",
    "docstring": "Returns the class to use for the passed in list.  We just build something up\n    from the object type for the list."
  },
  {
    "code": "def get_oa_policy(doi):\n    try:\n        request = requests.get(\"%s%s\" % (DISSEMIN_API, doi))\n        request.raise_for_status()\n        result = request.json()\n        assert result[\"status\"] == \"ok\"\n        return ([i\n                 for i in result[\"paper\"][\"publications\"]\n                 if i[\"doi\"] == doi][0])[\"policy\"]\n    except (AssertionError, ValueError,\n            KeyError, RequestException, IndexError):\n        return None",
    "docstring": "Get OA policy for a given DOI.\n\n    .. note::\n\n        Uses beta.dissem.in API.\n\n    :param doi: A canonical DOI.\n    :returns: The OpenAccess policy for the associated publications, or \\\n            ``None`` if unknown.\n\n    >>> tmp = get_oa_policy('10.1209/0295-5075/111/40005'); (tmp[\"published\"], tmp[\"preprint\"], tmp[\"postprint\"], tmp[\"romeo_id\"])\n    ('can', 'can', 'can', '1896')\n\n    >>> get_oa_policy('10.1215/9780822387268') is None\n    True"
  },
  {
    "code": "def draw_roundedrect(self, x, y, w, h, r=10):\n        context = self.context\n        context.save\n        context.move_to(x+r, y)\n        context.line_to(x+w-r, y)\n        context.curve_to(x+w, y, x+w, y, x+w, y+r)\n        context.line_to(x+w, y+h-r)\n        context.curve_to(x+w, y+h, x+w, y+h, x+w-r, y+h)\n        context.line_to(x+r, y+h)\n        context.curve_to(x, y+h, x, y+h, x, y+h-r)\n        context.line_to(x, y+r)\n        context.curve_to(x, y, x, y, x+r, y)\n        context.restore",
    "docstring": "Draws a rounded rectangle"
  },
  {
    "code": "def create(self, check, notification_plan, criteria=None,\n            disabled=False, label=None, name=None, metadata=None):\n        uri = \"/%s\" % self.uri_base\n        body = {\"check_id\": utils.get_id(check),\n                \"notification_plan_id\": utils.get_id(notification_plan),\n                }\n        if criteria:\n            body[\"criteria\"] = criteria\n        if disabled is not None:\n            body[\"disabled\"] = disabled\n        label_name = label or name\n        if label_name:\n            body[\"label\"] = label_name\n        if metadata:\n            body[\"metadata\"] = metadata\n        resp, resp_body = self.api.method_post(uri, body=body)\n        if resp.status_code == 201:\n            alarm_id = resp.headers[\"x-object-id\"]\n            return self.get(alarm_id)",
    "docstring": "Creates an alarm that binds the check on the given entity with a\n        notification plan.\n\n        Note that the 'criteria' parameter, if supplied, should be a string\n        representing the DSL for describing alerting conditions and their\n        output states. Pyrax does not do any validation of these criteria\n        statements; it is up to you as the developer to understand the language\n        and correctly form the statement. This alarm language is documented\n        online in the Cloud Monitoring section of http://docs.rackspace.com."
  },
  {
    "code": "def paginator(limit, offset, record_count, base_uri, page_nav_tpl='&limit={}&offset={}'):\n    total_pages = int(math.ceil(record_count / limit))\n    next_cond = limit + offset <= record_count\n    prev_cond = offset >= limit\n    next_page = base_uri + page_nav_tpl.format(limit, offset + limit) if next_cond else None\n    prev_page = base_uri + page_nav_tpl.format(limit, offset - limit) if prev_cond else None\n    return OrderedDict([\n        ('total_count', record_count),\n        ('total_pages', total_pages),\n        ('next_page', next_page),\n        ('prev_page', prev_page)\n    ])",
    "docstring": "Compute pagination info for collection filtering.\n\n    Args:\n        limit (int): Collection filter limit.\n        offset (int): Collection filter offset.\n        record_count (int): Collection filter total record count.\n        base_uri (str): Collection filter base uri (without limit, offset)\n        page_nav_tpl (str): Pagination template.\n\n    Returns:\n        A mapping of pagination info."
  },
  {
    "code": "def run_checks(collector):\n    artifact = collector.configuration[\"dashmat\"].artifact\n    chosen = artifact\n    if chosen in (None, \"\", NotSpecified):\n        chosen = None\n    dashmat = collector.configuration[\"dashmat\"]\n    modules = collector.configuration[\"__active_modules__\"]\n    config_root = collector.configuration[\"config_root\"]\n    module_options = collector.configuration[\"modules\"]\n    datastore = JsonDataStore(os.path.join(config_root, \"data.json\"))\n    if dashmat.redis_host:\n        datastore = RedisDataStore(redis.Redis(dashmat.redis_host))\n    scheduler = Scheduler(datastore)\n    for name, module in modules.items():\n        if chosen is None or name == chosen:\n            server = module.make_server(module_options[name].server_options)\n            scheduler.register(module, server, name)\n    scheduler.twitch(force=True)",
    "docstring": "Just run the checks for our modules"
  },
  {
    "code": "def CreateDevice(self, device_address):\n    device_name = 'dev_' + device_address.replace(':', '_').upper()\n    adapter_path = self.path\n    path = adapter_path + '/' + device_name\n    if path not in mockobject.objects:\n        raise dbus.exceptions.DBusException(\n            'Could not create device for %s.' % device_address,\n            name='org.bluez.Error.Failed')\n    adapter = mockobject.objects[self.path]\n    adapter.EmitSignal(ADAPTER_IFACE, 'DeviceCreated',\n                       'o', [dbus.ObjectPath(path, variant_level=1)])\n    return dbus.ObjectPath(path, variant_level=1)",
    "docstring": "Create a new device"
  },
  {
    "code": "async def gantry_position(\n            self,\n            mount: top_types.Mount,\n            critical_point: CriticalPoint = None) -> top_types.Point:\n        cur_pos = await self.current_position(mount, critical_point)\n        return top_types.Point(x=cur_pos[Axis.X],\n                               y=cur_pos[Axis.Y],\n                               z=cur_pos[Axis.by_mount(mount)])",
    "docstring": "Return the position of the critical point as pertains to the gantry\n\n        This ignores the plunger position and gives the Z-axis a predictable\n        name (as :py:attr:`.Point.z`).\n\n        `critical_point` specifies an override to the current critical point to\n        use (see :py:meth:`current_position`)."
  },
  {
    "code": "def _send_msg(self, header, payload):\n        if self.verbose:\n            print('->', repr(header))\n            print('..', repr(payload))\n        assert header.payload == len(payload)\n        try:\n            sent = self.socket.send(header + payload)\n        except IOError as err:\n            raise ConnError(*err.args)\n        if sent < len(header + payload):\n            raise ShortWrite(sent, len(header + payload))\n        assert sent == len(header + payload), sent",
    "docstring": "send message to server"
  },
  {
    "code": "def _GetVal(self, obj, key):\n    if \".\" in key:\n      lhs, rhs = key.split(\".\", 1)\n      obj2 = getattr(obj, lhs, None)\n      if obj2 is None:\n        return None\n      return self._GetVal(obj2, rhs)\n    else:\n      return getattr(obj, key, None)",
    "docstring": "Recurse down an attribute chain to the actual result data."
  },
  {
    "code": "def done(self):\n        logger.info('Marking %s as done', self)\n        fn = self.get_path()\n        try:\n            os.makedirs(os.path.dirname(fn))\n        except OSError:\n            pass\n        open(fn, 'w').close()",
    "docstring": "Creates temporary file to mark the task as `done`"
  },
  {
    "code": "def update_display(cb, pool, params, plane, qwertz):\n    cb.clear()\n    draw_panel(cb, pool, params, plane)\n    update_position(params)\n    draw_menu(cb, params, qwertz)\n    cb.refresh()",
    "docstring": "Draws everything.\n\n    :param cb: Cursebox instance.\n    :type cb: cursebox.Cursebox\n    :param params: Current application parameters.\n    :type params: params.Params\n    :param plane: Plane containing the current Mandelbrot values.\n    :type plane: plane.Plane\n    :return:"
  },
  {
    "code": "def url_report(self, scan_url, apikey):\n        url = self.base_url + \"url/report\"\n        params = {\"apikey\": apikey, 'resource': scan_url}\n        rate_limit_clear = self.rate_limit()\n        if rate_limit_clear:\n            response = requests.post(url, params=params, headers=self.headers)\n            if response.status_code == self.HTTP_OK:\n                json_response = response.json()\n                return json_response\n            elif response.status_code == self.HTTP_RATE_EXCEEDED:\n                time.sleep(20)\n            else:\n                self.logger.error(\"sent: %s, HTTP: %d\", scan_url, response.status_code)\n            time.sleep(self.public_api_sleep_time)",
    "docstring": "Send URLS for list of past malicous associations"
  },
  {
    "code": "def extract(json_object, args, csv_writer):\n    found = [[]]\n    for attribute in args.attributes:\n        item = attribute.getElement(json_object)\n        if len(item) == 0:\n            for row in found:\n                row.append(\"NA\")\n        else:\n            found1 = []\n            for value in item:\n                if value is None:\n                    value = \"NA\"\n                new = copy.deepcopy(found)\n                for row in new:\n                    row.append(value)\n                found1.extend(new)\n            found = found1\n    for row in found:\n        csv_writer.writerow(row)\n    return len(found)",
    "docstring": "Extract and write found attributes."
  },
  {
    "code": "def save_tabs_when_changed(func):\n    def wrapper(*args, **kwargs):\n        func(*args, **kwargs)\n        log.debug(\"mom, I've been called: %s %s\", func.__name__, func)\n        clsname = args[0].__class__.__name__\n        g = None\n        if clsname == 'Guake':\n            g = args[0]\n        elif getattr(args[0], 'get_guake', None):\n            g = args[0].get_guake()\n        elif getattr(args[0], 'get_notebook', None):\n            g = args[0].get_notebook().guake\n        elif getattr(args[0], 'guake', None):\n            g = args[0].guake\n        elif getattr(args[0], 'notebook', None):\n            g = args[0].notebook.guake\n        if g and g.settings.general.get_boolean('save-tabs-when-changed'):\n            g.save_tabs()\n    return wrapper",
    "docstring": "Decorator for save-tabs-when-changed"
  },
  {
    "code": "def hash(self, algorithm: Algorithm = None) -> str:\n        key = self._validate_enum(algorithm, Algorithm)\n        if hasattr(hashlib, key):\n            fn = getattr(hashlib, key)\n            return fn(self.uuid().encode()).hexdigest()",
    "docstring": "Generate random hash.\n\n        To change hashing algorithm, pass parameter ``algorithm``\n        with needed value of the enum object :class:`~mimesis.enums.Algorithm`\n\n        :param algorithm: Enum object :class:`~mimesis.enums.Algorithm`.\n        :return: Hash.\n        :raises NonEnumerableError: if algorithm is not supported."
  },
  {
    "code": "def flash_spi_attach(self, hspi_arg):\n        arg = struct.pack('<I', hspi_arg)\n        if not self.IS_STUB:\n            is_legacy = 0\n            arg += struct.pack('BBBB', is_legacy, 0, 0, 0)\n        self.check_command(\"configure SPI flash pins\", ESP32ROM.ESP_SPI_ATTACH, arg)",
    "docstring": "Send SPI attach command to enable the SPI flash pins\n\n        ESP8266 ROM does this when you send flash_begin, ESP32 ROM\n        has it as a SPI command."
  },
  {
    "code": "def min_date(self, symbol):\n        res = self._collection.find_one({SYMBOL: symbol}, projection={ID: 0, START: 1},\n                                        sort=[(START, pymongo.ASCENDING)])\n        if res is None:\n            raise NoDataFoundException(\"No Data found for {}\".format(symbol))\n        return utc_dt_to_local_dt(res[START])",
    "docstring": "Return the minimum datetime stored for a particular symbol\n\n        Parameters\n        ----------\n        symbol : `str`\n            symbol name for the item"
  },
  {
    "code": "def from_sequence(cls, sequence, phos_3_prime=False):\n        strand1 = NucleicAcidStrand(sequence, phos_3_prime=phos_3_prime)\n        duplex = cls(strand1)\n        return duplex",
    "docstring": "Creates a DNA duplex from a nucleotide sequence.\n\n        Parameters\n        ----------\n        sequence: str\n            Nucleotide sequence.\n        phos_3_prime: bool, optional\n            If false the 5' and the 3' phosphor will be omitted."
  },
  {
    "code": "def html(text, lazy_images=False):\n    extensions = [\n        'markdown.extensions.nl2br',\n        'markdown.extensions.sane_lists',\n        'markdown.extensions.toc',\n        'markdown.extensions.tables',\n        OEmbedExtension()\n    ]\n    if lazy_images:\n        extensions.append(LazyImageExtension())\n    return markdown.markdown(text, extensions=extensions)",
    "docstring": "To render a markdown format text into HTML.\n\n    - If you want to also build a Table of Content inside of the markdow,\n    add the tags: [TOC]\n    It will include a <ul><li>...</ul> of all <h*>\n\n    :param text:\n    :param lazy_images: bool - If true, it will activate the LazyImageExtension\n    :return:"
  },
  {
    "code": "def _set_content(self, value, oktypes):\n        if value is None:\n            value = []\n        self._content = ListContainer(*value, oktypes=oktypes, parent=self)",
    "docstring": "Similar to content.setter but when there are no existing oktypes"
  },
  {
    "code": "def p(value, bits=None, endian=None, target=None):\n    return globals()['p%d' % _get_bits(bits, target)](value, endian=endian, target=target)",
    "docstring": "Pack a signed pointer for a given target.\n\n    Args:\n        value(int): The value to pack.\n        bits(:class:`pwnypack.target.Target.Bits`): Override the default\n            word size. If ``None`` it will look at the word size of\n            ``target``.\n        endian(:class:`~pwnypack.target.Target.Endian`): Override the default\n            byte order. If ``None``, it will look at the byte order of\n            the ``target`` argument.\n        target(:class:`~pwnypack.target.Target`): Override the default byte\n            order. If ``None``, it will look at the byte order of\n            the global :data:`~pwnypack.target.target`."
  },
  {
    "code": "def open_sciobj_file_by_pid_ctx(pid, write=False):\n    abs_path = get_abs_sciobj_file_path_by_pid(pid)\n    with open_sciobj_file_by_path_ctx(abs_path, write) as sciobj_file:\n        yield sciobj_file",
    "docstring": "Open the file containing the Science Object bytes of ``pid`` in the default\n    location within the tree of the local SciObj store.\n\n    If ``write`` is True, the file is opened for writing and any missing directories are\n    created. Return the file handle and file_url with the file location in a suitable\n    form for storing in the DB.\n\n    If nothing was written to the file, it is deleted."
  },
  {
    "code": "def start_notebook(self, name, context: dict, fg=False):\n        assert context\n        assert type(context) == dict\n        assert \"context_hash\" in context\n        assert type(context[\"context_hash\"]) == int\n        http_port = self.pick_port()\n        assert http_port\n        context = context.copy()\n        context[\"http_port\"] = http_port\n        if \"websocket_url\" not in context:\n            context[\"websocket_url\"] = \"ws://localhost:{port}\".format(port=http_port)\n        if \"{port}\" in context[\"websocket_url\"]:\n            context[\"websocket_url\"] = context[\"websocket_url\"].format(port=http_port)\n        pid = self.get_pid(name)\n        assert \"terminated\" not in context\n        comm.set_context(pid, context)\n        if fg:\n            self.exec_notebook_daemon_command(name, \"fg\", port=http_port)\n        else:\n            self.exec_notebook_daemon_command(name, \"start\", port=http_port)",
    "docstring": "Start new IPython Notebook daemon.\n\n        :param name: The owner of the Notebook will be *name*. He/she gets a new Notebook content folder created where all files are placed.\n\n        :param context: Extra context information passed to the started Notebook. This must contain {context_hash:int} parameter used to identify the launch parameters for the notebook"
  },
  {
    "code": "def block_ranges(start_block, last_block, step=5):\n    if last_block is not None and start_block > last_block:\n        raise TypeError(\n            \"Incompatible start and stop arguments.\",\n            \"Start must be less than or equal to stop.\")\n    return (\n        (from_block, to_block - 1)\n        for from_block, to_block\n        in segment_count(start_block, last_block + 1, step)\n    )",
    "docstring": "Returns 2-tuple ranges describing ranges of block from start_block to last_block\n\n       Ranges do not overlap to facilitate use as ``toBlock``, ``fromBlock``\n       json-rpc arguments, which are both inclusive."
  },
  {
    "code": "def _xml_for_episode_index(self, ep_ind):\n        model_file = self.demo_file[\"data/{}\".format(ep_ind)].attrs[\"model_file\"]\n        model_path = os.path.join(self.demo_path, \"models\", model_file)\n        with open(model_path, \"r\") as model_f:\n            model_xml = model_f.read()\n        return model_xml",
    "docstring": "Helper method to retrieve the corresponding model xml string\n        for the passed episode index."
  },
  {
    "code": "def get_bucket_props(self, bucket):\n        msg_code = riak.pb.messages.MSG_CODE_GET_BUCKET_REQ\n        codec = self._get_codec(msg_code)\n        msg = codec.encode_get_bucket_props(bucket)\n        resp_code, resp = self._request(msg, codec)\n        return codec.decode_bucket_props(resp.props)",
    "docstring": "Serialize bucket property request and deserialize response"
  },
  {
    "code": "def doFindAny(self, WHAT={}, SORT=[], SKIP=None, MAX=None, LOP='AND', **params):\n\t\tself._preFind(WHAT, SORT, SKIP, MAX, LOP)\n\t\tfor key in params:\n\t\t\tself._addDBParam(key, params[key])\n\t\treturn self._doAction('-findany')",
    "docstring": "This function will perform the command -findany."
  },
  {
    "code": "def next_url(request):\n    next = request.GET.get(\"next\", request.POST.get(\"next\", \"\"))\n    host = request.get_host()\n    return next if next and is_safe_url(next, host=host) else None",
    "docstring": "Returns URL to redirect to from the ``next`` param in the request."
  },
  {
    "code": "def cli_forms(self, *args):\n        forms = []\n        missing = []\n        for key, item in schemastore.items():\n            if 'form' in item and len(item['form']) > 0:\n                forms.append(key)\n            else:\n                missing.append(key)\n        self.log('Schemata with form:', forms)\n        self.log('Missing forms:', missing)",
    "docstring": "List all available form definitions"
  },
  {
    "code": "def get_program_path():\n    src_folder = os.path.dirname(__file__)\n    program_path = os.sep.join(src_folder.split(os.sep)[:-1]) + os.sep\n    return program_path",
    "docstring": "Returns the path in which pyspread is installed"
  },
  {
    "code": "def register_measurements(self, end, rows, between, refresh_presision):\n\t\tif not self.end and len(rows) > 0:\n\t\t\tself.append_rows(rows, between, refresh_presision)\n\t\t\tself.go_inactive(end)\n\t\t\tself.save()",
    "docstring": "Register the measurements if it has measurements and close the configuration, if it hasen't got measurements clean the temporal file on disk.\n\n\t\t\tKeyword arguments:\n\t\t\tf -- open memory file\n\t\t\tend -- datetime of the moment when the configuration go inactive\n\t\t\tbetween -- time between integral_measurements in seconds\n\t\t\trefresh_presision -- time between sensor values that compose the integral_measurements"
  },
  {
    "code": "def upload_from_fileobject(f, profile=None, label=None):\n    if profile is None:\n        profile = 'default'\n    conf = get_profile_configs(profile)\n    f.seek(0)\n    if not is_image(f, types=conf['TYPES']):\n        msg = (('Format of uploaded file is not allowed. '\n                'Allowed formats is: %(formats)s.') %\n               {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))})\n        raise RuntimeError(msg)\n    return _custom_upload(f, profile, label, conf)",
    "docstring": "Saves image from f with TMP prefix and returns img_id."
  },
  {
    "code": "def load_directory(self, directory, ext=None):\n        self._say(\"Loading from directory: \" + directory)\n        if ext is None:\n            ext = ['.rive', '.rs']\n        elif type(ext) == str:\n            ext = [ext]\n        if not os.path.isdir(directory):\n            self._warn(\"Error: \" + directory + \" is not a directory.\")\n            return\n        for root, subdirs, files in os.walk(directory):\n            for file in files:\n                for extension in ext:\n                    if file.lower().endswith(extension):\n                        self.load_file(os.path.join(root, file))\n                        break",
    "docstring": "Load RiveScript documents from a directory.\n\n        :param str directory: The directory of RiveScript documents to load\n            replies from.\n        :param []str ext: List of file extensions to consider as RiveScript\n            documents. The default is ``[\".rive\", \".rs\"]``."
  },
  {
    "code": "def _resolve_device_type(self, device):\n        try:\n            from tests.unit import fakes\n            server_types = (pyrax.CloudServer, fakes.FakeServer)\n            lb_types = (CloudLoadBalancer, fakes.FakeLoadBalancer,\n                    fakes.FakeDNSDevice)\n        except ImportError:\n            server_types = (pyrax.CloudServer, )\n            lb_types = (CloudLoadBalancer, )\n        if isinstance(device, server_types):\n            device_type = \"server\"\n        elif isinstance(device, lb_types):\n            device_type = \"loadbalancer\"\n        else:\n            raise exc.InvalidDeviceType(\"The device '%s' must be a CloudServer \"\n                    \"or a CloudLoadBalancer.\" % device)\n        return device_type",
    "docstring": "Given a device, determines if it is a CloudServer, a CloudLoadBalancer,\n        or an invalid device."
  },
  {
    "code": "def find_rt_jar(javahome=None):\n    if not javahome:\n        if 'JAVA_HOME' in os.environ:\n            javahome = os.environ['JAVA_HOME']\n        elif sys.platform == 'darwin':\n            javahome = _find_osx_javahome()\n        else:\n            javahome = _get_javahome_from_java(_find_java_binary())\n    rtpath = os.path.join(javahome, 'jre', 'lib', 'rt.jar')\n    if not os.path.isfile(rtpath):\n        msg = 'Could not find rt.jar: {} is not a file'.format(rtpath)\n        raise ExtensionError(msg)\n    return rtpath",
    "docstring": "Find the path to the Java standard library jar.\n\n    The jar is expected to exist at the path 'jre/lib/rt.jar' inside a\n    standard Java installation directory. The directory is found using\n    the following procedure:\n\n    1. If the javehome argument is provided, use the value as the\n       directory.\n    2. If the JAVA_HOME environment variable is set, use the value as\n       the directory.\n    3. Find the location of the ``java`` binary in the current PATH and\n       compute the installation directory from this location.\n\n    Args:\n        javahome: A path to a Java installation directory (optional)."
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'type' in _dict:\n            args['type'] = _dict.get('type')\n        if 'text' in _dict:\n            args['text'] = _dict.get('text')\n        if 'relevance' in _dict:\n            args['relevance'] = _dict.get('relevance')\n        if 'mentions' in _dict:\n            args['mentions'] = [\n                EntityMention._from_dict(x) for x in (_dict.get('mentions'))\n            ]\n        if 'count' in _dict:\n            args['count'] = _dict.get('count')\n        if 'emotion' in _dict:\n            args['emotion'] = EmotionScores._from_dict(_dict.get('emotion'))\n        if 'sentiment' in _dict:\n            args['sentiment'] = FeatureSentimentResults._from_dict(\n                _dict.get('sentiment'))\n        if 'disambiguation' in _dict:\n            args['disambiguation'] = DisambiguationResult._from_dict(\n                _dict.get('disambiguation'))\n        return cls(**args)",
    "docstring": "Initialize a EntitiesResult object from a json dictionary."
  },
  {
    "code": "def transform_to(ext):\n    def decor(f):\n        @functools.wraps(f)\n        def wrapper(*args, **kwargs):\n            out_file = kwargs.get(\"out_file\", None)\n            if not out_file:\n                in_path = kwargs.get(\"in_file\", args[0])\n                out_dir = kwargs.get(\"out_dir\", os.path.dirname(in_path))\n                safe_mkdir(out_dir)\n                out_name = replace_suffix(os.path.basename(in_path), ext)\n                out_file = os.path.join(out_dir, out_name)\n            kwargs[\"out_file\"] = out_file\n            if not file_exists(out_file):\n                out_file = f(*args, **kwargs)\n            return out_file\n        return wrapper\n    return decor",
    "docstring": "Decorator to create an output filename from an output filename with\n    the specified extension. Changes the extension, in_file is transformed\n    to a new type.\n\n    Takes functions like this to decorate:\n    f(in_file, out_dir=None, out_file=None) or,\n    f(in_file=in_file, out_dir=None, out_file=None)\n\n    examples:\n    @transform(\".bam\")\n    f(\"the/input/path/file.sam\") ->\n        f(\"the/input/path/file.sam\", out_file=\"the/input/path/file.bam\")\n\n    @transform(\".bam\")\n    f(\"the/input/path/file.sam\", out_dir=\"results\") ->\n        f(\"the/input/path/file.sam\", out_file=\"results/file.bam\")"
  },
  {
    "code": "def _item_to_blob(iterator, item):\n    name = item.get(\"name\")\n    blob = Blob(name, bucket=iterator.bucket)\n    blob._set_properties(item)\n    return blob",
    "docstring": "Convert a JSON blob to the native object.\n\n    .. note::\n\n        This assumes that the ``bucket`` attribute has been\n        added to the iterator after being created.\n\n    :type iterator: :class:`~google.api_core.page_iterator.Iterator`\n    :param iterator: The iterator that has retrieved the item.\n\n    :type item: dict\n    :param item: An item to be converted to a blob.\n\n    :rtype: :class:`.Blob`\n    :returns: The next blob in the page."
  },
  {
    "code": "def from_geojson(geojson, srid=4326):\n        type_ = geojson[\"type\"].lower()\n        if type_ == \"geometrycollection\":\n            geometries = []\n            for geometry in geojson[\"geometries\"]:\n                geometries.append(Geometry.from_geojson(geometry, srid=None))\n            return GeometryCollection(geometries, srid)\n        elif type_ == \"point\":\n            return Point(geojson[\"coordinates\"], srid=srid)\n        elif type_ == \"linestring\":\n            return LineString(geojson[\"coordinates\"], srid=srid)\n        elif type_ == \"polygon\":\n            return Polygon(geojson[\"coordinates\"], srid=srid)\n        elif type_ == \"multipoint\":\n            geometries = _MultiGeometry._multi_from_geojson(geojson, Point)\n            return MultiPoint(geometries, srid=srid)\n        elif type_ == \"multilinestring\":\n            geometries = _MultiGeometry._multi_from_geojson(geojson, LineString)\n            return MultiLineString(geometries, srid=srid)\n        elif type_ == \"multipolygon\":\n            geometries = _MultiGeometry._multi_from_geojson(geojson, Polygon)\n            return MultiPolygon(geometries, srid=srid)",
    "docstring": "Create a Geometry from a GeoJSON. The SRID can be overridden from the\n        expected 4326."
  },
  {
    "code": "def load(cls, path_to_file):\n        import mimetypes\n        mimetypes.init()\n        mime = mimetypes.guess_type('file://%s' % path_to_file)[0]\n        img_type = ImageTypeEnum.lookup_by_mime_type(mime)\n        with open(path_to_file, 'rb') as f:\n            data = f.read()\n        return Image(data, image_type=img_type)",
    "docstring": "Loads the image data from a file on disk and tries to guess the image MIME type\n\n        :param path_to_file: path to the source file\n        :type path_to_file: str\n        :return: a `pyowm.image.Image` instance"
  },
  {
    "code": "def visit_set(self, node):\n        return \"{%s}\" % \", \".join(child.accept(self) for child in node.elts)",
    "docstring": "return an astroid.Set node as string"
  },
  {
    "code": "def _write_header(self):\n        for line in self.header.lines:\n            print(line.serialize(), file=self.stream)\n        if self.header.samples.names:\n            print(\n                \"\\t\".join(list(parser.REQUIRE_SAMPLE_HEADER) + self.header.samples.names),\n                file=self.stream,\n            )\n        else:\n            print(\"\\t\".join(parser.REQUIRE_NO_SAMPLE_HEADER), file=self.stream)",
    "docstring": "Write out the header"
  },
  {
    "code": "def notebook_to_md(notebook):\n    tmp_file = tempfile.NamedTemporaryFile(delete=False)\n    tmp_file.write(ipynb_writes(notebook).encode('utf-8'))\n    tmp_file.close()\n    pandoc(u'--from ipynb --to markdown -s --atx-headers --wrap=preserve --preserve-tabs', tmp_file.name, tmp_file.name)\n    with open(tmp_file.name, encoding='utf-8') as opened_file:\n        text = opened_file.read()\n    os.unlink(tmp_file.name)\n    return '\\n'.join(text.splitlines())",
    "docstring": "Convert a notebook to its Markdown representation, using Pandoc"
  },
  {
    "code": "def memberships(self, group, include=None):\n        return self._get(self._build_url(self.endpoint.memberships(id=group, include=include)))",
    "docstring": "Return the GroupMemberships for this group.\n\n        :param include: list of objects to sideload. `Side-loading API Docs \n            <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.\n        :param group: Group object or id"
  },
  {
    "code": "def install(self, version):\n        c = self._pyenv(\n            'install', '-s', str(version),\n            timeout=PIPENV_INSTALL_TIMEOUT,\n        )\n        return c",
    "docstring": "Install the given version with pyenv.\n\n        The version must be a ``Version`` instance representing a version\n        found in pyenv.\n\n        A ValueError is raised if the given version does not have a match in\n        pyenv. A PyenvError is raised if the pyenv command fails."
  },
  {
    "code": "def get_templates(self):\n        use = getattr(self, 'use', '')\n        if isinstance(use, list):\n            return [n.strip() for n in use if n.strip()]\n        return [n.strip() for n in use.split(',') if n.strip()]",
    "docstring": "Get list of templates this object use\n\n        :return: list of templates\n        :rtype: list"
  },
  {
    "code": "def evaluate(self, source, cards=None) -> str:\n\t\tfrom ..utils import weighted_card_choice\n\t\tif cards:\n\t\t\tself.weights = [1]\n\t\t\tcard_sets = [list(cards)]\n\t\telif not self.weightedfilters:\n\t\t\tself.weights = [1]\n\t\t\tcard_sets = [self.find_cards(source)]\n\t\telse:\n\t\t\twf = [{**x, **self.filters} for x in self.weightedfilters]\n\t\t\tcard_sets = [self.find_cards(source, **x) for x in wf]\n\t\treturn weighted_card_choice(source, self.weights, card_sets, self.count)",
    "docstring": "This picks from a single combined card pool without replacement,\n\t\tweighting each filtered set of cards against the total"
  },
  {
    "code": "def _GetAppYamlHostname(application_path, open_func=open):\n  try:\n    app_yaml_file = open_func(os.path.join(application_path or '.', 'app.yaml'))\n    config = yaml.safe_load(app_yaml_file.read())\n  except IOError:\n    return None\n  application = config.get('application')\n  if not application:\n    return None\n  if ':' in application:\n    return None\n  tilde_index = application.rfind('~')\n  if tilde_index >= 0:\n    application = application[tilde_index + 1:]\n    if not application:\n      return None\n  return '%s.appspot.com' % application",
    "docstring": "Build the hostname for this app based on the name in app.yaml.\n\n  Args:\n    application_path: A string with the path to the AppEngine application.  This\n      should be the directory containing the app.yaml file.\n    open_func: Function to call to open a file.  Used to override the default\n      open function in unit tests.\n\n  Returns:\n    A hostname, usually in the form of \"myapp.appspot.com\", based on the\n    application name in the app.yaml file.  If the file can't be found or\n    there's a problem building the name, this will return None."
  },
  {
    "code": "def bump(match):\n\tbefore, old_version, after = match.groups()\n\tmajor, minor, patch = map(int, old_version.split('.'))\n\tpatch += 1\n\tif patch == 10:\n\t\tpatch = 0\n\t\tminor += 1\n\t\tif minor == 10:\n\t\t\tminor = 0\n\t\t\tmajor += 1\n\tnew_version = '{0}.{1}.{2}'.format(major, minor, patch)\n\tprint('{0} => {1}'.format(old_version, new_version))\n\treturn before + new_version + after",
    "docstring": "Bumps the version"
  },
  {
    "code": "def sign(self, byts):\n        chosen_hash = c_hashes.SHA256()\n        hasher = c_hashes.Hash(chosen_hash, default_backend())\n        hasher.update(byts)\n        digest = hasher.finalize()\n        return self.priv.sign(digest,\n                              c_ec.ECDSA(c_utils.Prehashed(chosen_hash))\n                              )",
    "docstring": "Compute the ECC signature for the given bytestream.\n\n        Args:\n            byts (bytes): The bytes to sign.\n\n        Returns:\n            bytes: The RSA Signature bytes."
  },
  {
    "code": "def _to_chimera(M, N, L, q):\n    \"Converts a qubit's linear index to chimera coordinates.\"\n    return (q // N // L // 2, (q // L // 2) % N, (q // L) % 2, q % L)",
    "docstring": "Converts a qubit's linear index to chimera coordinates."
  },
  {
    "code": "def remove_from_s3(self, file_name, bucket_name):\n        try:\n            self.s3_client.head_bucket(Bucket=bucket_name)\n        except botocore.exceptions.ClientError as e:\n            error_code = int(e.response['Error']['Code'])\n            if error_code == 404:\n                return False\n        try:\n            self.s3_client.delete_object(Bucket=bucket_name, Key=file_name)\n            return True\n        except (botocore.exceptions.ParamValidationError, botocore.exceptions.ClientError):\n            return False",
    "docstring": "Given a file name and a bucket, remove it from S3.\n\n        There's no reason to keep the file hosted on S3 once its been made into a Lambda function, so we can delete it from S3.\n\n        Returns True on success, False on failure."
  },
  {
    "code": "def _convert_to_var(self, graph, var_res):\n        with graph.as_default():\n            var = {}\n            for key, value in var_res.items():\n                if value is not None:\n                    var[key] = tf.Variable(value, name=\"tf_%s\" % key)\n                else:\n                    var[key] = None\n        return var",
    "docstring": "Create tf.Variables from a list of numpy arrays\n\n        var_res: dictionary of numpy arrays with the key names corresponding to var"
  },
  {
    "code": "def red(cls):\n        \"Make the text foreground color red.\"\n        wAttributes = cls._get_text_attributes()\n        wAttributes &= ~win32.FOREGROUND_MASK\n        wAttributes |=  win32.FOREGROUND_RED\n        cls._set_text_attributes(wAttributes)",
    "docstring": "Make the text foreground color red."
  },
  {
    "code": "def inet_pton(address_family, ip_string):\n    global __inet_pton\n    if __inet_pton is None:\n        if hasattr(socket, 'inet_pton'):\n            __inet_pton = socket.inet_pton\n        else:\n            from ospd import win_socket\n            __inet_pton = win_socket.inet_pton\n    return __inet_pton(address_family, ip_string)",
    "docstring": "A platform independent version of inet_pton"
  },
  {
    "code": "def createPlotPanel(self):\n        self.figure = Figure()\n        self.axes = self.figure.add_subplot(111)\n        self.canvas = FigureCanvas(self,-1,self.figure)\n        self.canvas.SetSize(wx.Size(300,300))\n        self.axes.axis('off')\n        self.figure.subplots_adjust(left=0,right=1,top=1,bottom=0)\n        self.sizer = wx.BoxSizer(wx.VERTICAL)\n        self.sizer.Add(self.canvas,1,wx.EXPAND,wx.ALL)\n        self.SetSizerAndFit(self.sizer)\n        self.Fit()",
    "docstring": "Creates the figure and axes for the plotting panel."
  },
  {
    "code": "def next(self):\n        self._set_consumer_timeout_start()\n        while True:\n            try:\n                return six.next(self._get_message_iterator())\n            except StopIteration:\n                self._reset_message_iterator()\n            self._check_consumer_timeout()",
    "docstring": "Return the next available message\n\n        Blocks indefinitely unless consumer_timeout_ms > 0\n\n        Returns:\n            a single KafkaMessage from the message iterator\n\n        Raises:\n            ConsumerTimeout after consumer_timeout_ms and no message\n\n        Note:\n            This is also the method called internally during iteration"
  },
  {
    "code": "def value_right(self, other):\n    return self if isinstance(other, self.__class__) else self.value",
    "docstring": "Returns the value of the type instance calling an to use in an\n    operator method, namely when the method's instance is on the\n    right side of the expression."
  },
  {
    "code": "def _load_script(self, filename: str) -> Script:\n        with open(path.join(here, 'redis_scripts', filename), mode='rb') as f:\n            script_data = f.read()\n        rv = self._r.register_script(script_data)\n        if script_data.startswith(b'-- idempotency protected script'):\n            self._idempotency_protected_scripts.append(rv)\n        return rv",
    "docstring": "Load a Lua script.\n\n        Read the Lua script file to generate its Script object. If the script\n        starts with a magic string, add it to the list of scripts requiring an\n        idempotency token to execute."
  },
  {
    "code": "def link_markdown_cells(cells, modules):\n    \"Create documentation links for all cells in markdown with backticks.\"\n    for i, cell in enumerate(cells):\n        if cell['cell_type'] == 'markdown':\n            cell['source'] = link_docstring(modules, cell['source'])",
    "docstring": "Create documentation links for all cells in markdown with backticks."
  },
  {
    "code": "def has_field(mc, field_name):\n    try:\n        mc._meta.get_field(field_name)\n    except FieldDoesNotExist:\n        return False\n    return True",
    "docstring": "detect if a model has a given field has\n\n    :param field_name:\n    :param mc:\n    :return:"
  },
  {
    "code": "def highlight_differences(s1, s2, color):\n    ls1, ls2 = len(s1), len(s2)\n    diff_indices = [i for i, (a, b) in enumerate(zip(s1, s2)) if a != b]\n    print(s1)\n    if ls2 > ls1:\n        colorise.cprint('_' * (ls2-ls1), fg=color)\n    else:\n        print()\n    colorise.highlight(s2, indices=diff_indices, fg=color, end='')\n    if ls1 > ls2:\n        colorise.cprint('_' * (ls1-ls2), fg=color)\n    else:\n        print()",
    "docstring": "Highlight the characters in s2 that differ from those in s1."
  },
  {
    "code": "def getNonDefaultsDict(self):\n        dct = self._nodeGetNonDefaultsDict()\n        childList = []\n        for childCti in self.childItems:\n            childDct = childCti.getNonDefaultsDict()\n            if childDct:\n                childList.append(childDct)\n        if childList:\n            dct['childItems'] = childList\n        if dct:\n            dct['nodeName'] = self.nodeName\n        return dct",
    "docstring": "Recursively retrieves values as a dictionary to be used for persistence.\n            Does not save defaultData and other properties, only stores values if they differ from\n            the defaultData. If the CTI and none of its children differ from their default, a\n            completely empty dictionary is returned. This is to achieve a smaller json\n            representation.\n\n            Typically descendants should override _nodeGetNonDefaultsDict instead of this function."
  },
  {
    "code": "def make_map(declarations):\n    mapper = routes.Mapper()\n    for route, methods in ROUTE_LIST:\n        allowed_methods = []\n        for method, func in methods.items():\n            mapper.connect(route, action=func,\n                           conditions=dict(method=[method]))\n            allowed_methods.append(method)\n        allowed_methods = ', '.join(allowed_methods)\n        mapper.connect(route, action=handle_not_allowed,\n                       _methods=allowed_methods)\n    return mapper",
    "docstring": "Process route declarations to create a Route Mapper."
  },
  {
    "code": "def subscribe(self, connection, destination):\n        self.log.debug(\"Subscribing %s to %s\" % (connection, destination))\n        self._topics[destination].add(connection)",
    "docstring": "Subscribes a connection to the specified topic destination. \n\n        @param connection: The client connection to subscribe.\n        @type connection: L{coilmq.server.StompConnection}\n\n        @param destination: The topic destination (e.g. '/topic/foo')\n        @type destination: C{str}"
  },
  {
    "code": "def remove_listener(self, listener):\n        self.logger.debug('discarding listener %r', listener)\n        with self._lock:\n            self._listeners.discard(listener)",
    "docstring": "Unregister some listener; ignore if the listener was never\n        registered.\n\n        :type listener: :class:`SessionListener`"
  },
  {
    "code": "def setsebools(pairs, persist=False):\n    if not isinstance(pairs, dict):\n        return {}\n    if persist:\n        cmd = 'setsebool -P '\n    else:\n        cmd = 'setsebool '\n    for boolean, value in six.iteritems(pairs):\n        cmd = '{0} {1}={2}'.format(cmd, boolean, value)\n    return not __salt__['cmd.retcode'](cmd, python_shell=False)",
    "docstring": "Set the value of multiple booleans\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' selinux.setsebools '{virt_use_usb: on, squid_use_tproxy: off}'"
  },
  {
    "code": "def remove_infinite_values(self):\n        if util.is_shape(self.faces, (-1, 3)):\n            face_mask = np.isfinite(self.faces).all(axis=1)\n            self.update_faces(face_mask)\n        if util.is_shape(self.vertices, (-1, 3)):\n            vertex_mask = np.isfinite(self.vertices).all(axis=1)\n            self.update_vertices(vertex_mask)",
    "docstring": "Ensure that every vertex and face consists of finite numbers.\n\n        This will remove vertices or faces containing np.nan and np.inf\n\n        Alters\n        ----------\n        self.faces : masked to remove np.inf/np.nan\n        self.vertices : masked to remove np.inf/np.nan"
  },
  {
    "code": "def __execute_str(self, instr):\n        op0_val = self.read_operand(instr.operands[0])\n        self.write_operand(instr.operands[2], op0_val)\n        return None",
    "docstring": "Execute STR instruction."
  },
  {
    "code": "def slice(self, x, y, width):\n        return self._double_buffer[y][x:x + width]",
    "docstring": "Provide a slice of data from the buffer at the specified location\n\n        :param x: The X origin\n        :param y: The Y origin\n        :param width: The width of slice required\n        :return: The slice of tuples from the current double-buffer"
  },
  {
    "code": "def has_permission(cls, user):\n        if not cls.requires_login:\n            return True\n        if not user.is_authenticated:\n            return False\n        perms = cls.get_permission_required()\n        if not perms:\n            return True\n        role = user.urole.role.name\n        if role == cls.ADMIN:\n            return True\n        for permission in perms:\n            if cls.check_permission(role, permission):\n                return True\n        return False",
    "docstring": "We override this method to customize the way permissions are checked.\n        Using our roles to check permissions."
  },
  {
    "code": "def persistant_warning(request, message, extra_tags='', fail_silently=False, *args, **kwargs):\n    add_message(request, WARNING_PERSISTENT, message, extra_tags=extra_tags,\n                fail_silently=fail_silently, *args, **kwargs)",
    "docstring": "Adds a persistant message with the ``WARNING`` level."
  },
  {
    "code": "def purity(labels, true_labels):\n    purity = 0.0\n    for i in set(labels):\n        indices = (labels==i)\n        true_clusters = true_labels[indices]\n        if len(true_clusters)==0:\n            continue\n        counts = Counter(true_clusters)\n        lab, count = counts.most_common()[0]\n        purity += count\n    return float(purity)/len(labels)",
    "docstring": "Calculates the purity score for the given labels.\n\n    Args:\n        labels (array): 1D array of integers\n        true_labels (array): 1D array of integers - true labels\n\n    Returns:\n        purity score - a float bewteen 0 and 1. Closer to 1 is better."
  },
  {
    "code": "def remove_none_dict_values(obj):\n    if isinstance(obj, (list, tuple, set)):\n        return type(obj)(remove_none_dict_values(x) for x in obj)\n    elif isinstance(obj, dict):\n        return type(obj)((k, remove_none_dict_values(v))\n                         for k, v in obj.items()\n                         if v is not None)\n    else:\n        return obj",
    "docstring": "Remove None values from dict."
  },
  {
    "code": "def auth_user_oauth(self, userinfo):\n        if \"username\" in userinfo:\n            user = self.find_user(username=userinfo[\"username\"])\n        elif \"email\" in userinfo:\n            user = self.find_user(email=userinfo[\"email\"])\n        else:\n            log.error(\"User info does not have username or email {0}\".format(userinfo))\n            return None\n        if user and not user.is_active:\n            log.info(LOGMSG_WAR_SEC_LOGIN_FAILED.format(userinfo))\n            return None\n        if not user and not self.auth_user_registration:\n            return None\n        if not user:\n            user = self.add_user(\n                username=userinfo[\"username\"],\n                first_name=userinfo.get(\"first_name\", \"\"),\n                last_name=userinfo.get(\"last_name\", \"\"),\n                email=userinfo.get(\"email\", \"\"),\n                role=self.find_role(self.auth_user_registration_role),\n            )\n            if not user:\n                log.error(\"Error creating a new OAuth user %s\" % userinfo[\"username\"])\n                return None\n        self.update_user_auth_stat(user)\n        return user",
    "docstring": "OAuth user Authentication\n\n            :userinfo: dict with user information the keys have the same name\n            as User model columns."
  },
  {
    "code": "def get_view(self, columns: Sequence[str], query: str=None) -> PopulationView:\n        if 'tracked' not in columns:\n            query_with_track = query + 'and tracked == True' if query else 'tracked == True'\n            return PopulationView(self, columns, query_with_track)\n        return PopulationView(self, columns, query)",
    "docstring": "Return a configured PopulationView\n\n        Notes\n        -----\n        Client code should only need this (and only through the version exposed as\n        ``population_view`` on the builder during setup) if it uses dynamically\n        generated column names that aren't known at definition time. Otherwise\n        components should use ``uses_columns``."
  },
  {
    "code": "def resolve(self, pointer):\n        dp = DocumentPointer(pointer)\n        obj, fetcher = self.prototype(dp)\n        for token in dp.pointer:\n            obj = token.extract(obj, bypass_ref=True)\n            reference = ref(obj)\n            if reference:\n                obj = fetcher.resolve(reference)\n        return obj",
    "docstring": "Resolve from documents.\n\n        :param pointer: foo\n        :type pointer: DocumentPointer"
  },
  {
    "code": "def __getContributions(self, web):\n        contributions_raw = web.find_all('h2',\n                                         {'class': 'f4 text-normal mb-2'})\n        try:\n            contrText = contributions_raw[0].text\n            contrText = contrText.lstrip().split(\" \")[0]\n            contrText = contrText.replace(\",\", \"\")\n        except IndexError as error:\n            print(\"There was an error with the user \" + self.name)\n            print(error)\n        except AttributeError as error:\n            print(\"There was an error with the user \" + self.name)\n            print(error)\n        self.contributions = int(contrText)",
    "docstring": "Scrap the contributions from a GitHub profile.\n\n        :param web: parsed web.\n        :type web: BeautifulSoup node."
  },
  {
    "code": "def _prepare_filtering_params(domain=None, category=None, \r\n                                  sponsored_source=None, has_field=None,\r\n                                  has_fields=None, query_params_match=None, \r\n                                  query_person_match=None, **kwargs):\r\n        if query_params_match not in (None, True):\r\n            raise ValueError('query_params_match can only be `True`')\r\n        if query_person_match not in (None, True):\r\n            raise ValueError('query_person_match can only be `True`')\r\n        params = []\r\n        if domain is not None:\r\n            params.append('domain:%s' % domain)\r\n        if category is not None:\r\n            Source.validate_categories([category])\r\n            params.append('category:%s' % category)\r\n        if sponsored_source is not None:\r\n            params.append('sponsored_source:%s' % sponsored_source)\r\n        if query_params_match is not None:\r\n            params.append('query_params_match')\r\n        if query_person_match is not None:\r\n            params.append('query_person_match')\r\n        has_fields = has_fields or []\r\n        if has_field is not None:\r\n            has_fields.append(has_field)\r\n        for has_field in has_fields:\r\n            params.append('has_field:%s' % has_field.__name__)\r\n        return params",
    "docstring": "Transform the params to the API format, return a list of params."
  },
  {
    "code": "def get_open_orders(self, asset=None):\n        if asset is None:\n            return {\n                key: [order.to_api_obj() for order in orders]\n                for key, orders in iteritems(self.blotter.open_orders)\n                if orders\n            }\n        if asset in self.blotter.open_orders:\n            orders = self.blotter.open_orders[asset]\n            return [order.to_api_obj() for order in orders]\n        return []",
    "docstring": "Retrieve all of the current open orders.\n\n        Parameters\n        ----------\n        asset : Asset\n            If passed and not None, return only the open orders for the given\n            asset instead of all open orders.\n\n        Returns\n        -------\n        open_orders : dict[list[Order]] or list[Order]\n            If no asset is passed this will return a dict mapping Assets\n            to a list containing all the open orders for the asset.\n            If an asset is passed then this will return a list of the open\n            orders for this asset."
  },
  {
    "code": "def connect(self, func=None, event=None, set_method=False):\n        if func is None:\n            return partial(self.connect, set_method=set_method)\n        if event is None:\n            event = self._get_on_name(func)\n        self._callbacks[event].append(func)\n        if set_method:\n            self._create_emitter(event)\n        return func",
    "docstring": "Register a callback function to a given event.\n\n        To register a callback function to the `spam` event, where `obj` is\n        an instance of a class deriving from `EventEmitter`:\n\n        ```python\n        @obj.connect\n        def on_spam(arg1, arg2):\n            pass\n        ```\n\n        This is called when `obj.emit('spam', arg1, arg2)` is called.\n\n        Several callback functions can be registered for a given event.\n\n        The registration order is conserved and may matter in applications."
  },
  {
    "code": "def delete_label_by_id(self, content_id, label_name, callback=None):\n        params = {\"name\": label_name}\n        return self._service_delete_request(\"rest/api/content/{id}/label\".format(id=content_id),\n                                            params=params, callback=callback)",
    "docstring": "Deletes a labels to the specified content.\n\n        There is an alternative form of this delete method that is not implemented. A DELETE request to\n        /rest/api/content/{id}/label/{label} will also delete a label, but is more limited in the label name\n        that can be accepted (and has no real apparent upside).\n\n        :param content_id (string): A string containing the id of the labels content container.\n        :param label_name (string): OPTIONAL: The name of the label to be removed from the content.\n                                    Default: Empty (probably deletes all labels).\n        :param callback: OPTIONAL: The callback to execute on the resulting data, before the method returns.\n                         Default: None (no callback, raw data returned).\n        :return: Empty if successful, or the results of the callback.\n                 Will raise requests.HTTPError on bad input, potentially."
  },
  {
    "code": "def _database_exists(self):\n        con = psycopg2.connect(host=self.host, database=\"postgres\",\n            user=self.user, password=self.password, port=self.port)\n        query_check = \"select datname from pg_catalog.pg_database\"\n        query_check += \" where datname = '{0}';\".format(self.dbname)\n        c = con.cursor()\n        c.execute(query_check)\n        result = c.fetchall()\n        if len(result) > 0:\n            return True\n        return False",
    "docstring": "Check if the database exists."
  },
  {
    "code": "def transform_audio(self, y):\n        data = super(CQTPhaseDiff, self).transform_audio(y)\n        data['dphase'] = self.phase_diff(data.pop('phase'))\n        return data",
    "docstring": "Compute the CQT with unwrapped phase\n\n        Parameters\n        ----------\n        y : np.ndarray\n            The audio buffer\n\n        Returns\n        -------\n        data : dict\n            data['mag'] : np.ndarray, shape=(n_frames, n_bins)\n                CQT magnitude\n\n            data['dphase'] : np.ndarray, shape=(n_frames, n_bins)\n                Unwrapped phase differential"
  },
  {
    "code": "def parse_timespan_value(s):\n    number, unit = split_number_and_unit(s)\n    if not unit or unit == \"s\":\n        return number\n    elif unit == \"min\":\n        return number * 60\n    elif unit == \"h\":\n        return number * 60 * 60\n    elif unit == \"d\":\n        return number * 24 * 60 * 60\n    else:\n        raise ValueError('unknown unit: {} (allowed are s, min, h, and d)'.format(unit))",
    "docstring": "Parse a string that contains a time span, optionally with a unit like s.\n    @return the number of seconds encoded by the string"
  },
  {
    "code": "def write_ds9region(self, region, *args, **kwargs):\n        lines = self.to_ds9(*args,**kwargs)\n        with open(region,'w') as fo:\n            fo.write(\"\\n\".join(lines))",
    "docstring": "Create a ds9 compatible region file from the ROI.\n\n        It calls the `to_ds9` method and write the result to the region file. Only the file name is required.\n        All other parameters will be forwarded to the `to_ds9` method, see the documentation of that method\n        for all accepted parameters and options.\n        Parameters\n        ----------\n        region : str\n            name of the region file (string)"
  },
  {
    "code": "def _get_site_amplification_term(self, C, vs30):\n        return C[\"gamma\"] * np.log10(vs30 / self.CONSTS[\"Vref\"])",
    "docstring": "Returns the site amplification term for the case in which Vs30\n        is used directly"
  },
  {
    "code": "def fullversion():\n    cmd = __catalina_home() + '/bin/catalina.sh version'\n    ret = {}\n    out = __salt__['cmd.run'](cmd).splitlines()\n    for line in out:\n        if not line:\n            continue\n        if ': ' in line:\n            comps = line.split(': ')\n            ret[comps[0]] = comps[1].lstrip()\n    return ret",
    "docstring": "Return all server information from catalina.sh version\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' tomcat.fullversion"
  },
  {
    "code": "def ended(self):\n        self._end_time = time.time()\n        if setting(key='memory_profile', expected_type=bool):\n            self._end_memory = get_free_memory()",
    "docstring": "We call this method when the function is finished."
  },
  {
    "code": "def add_ability(self, phase, ability):\n        if phase not in self.abilities:\n            self.abilities[phase] = []\n        self.abilities[phase].append(ability)\n        return len(self.abilities[phase])",
    "docstring": "Add the given ability to this Card under the given phase. Returns\n        the length of the abilities for the given phase after the addition."
  },
  {
    "code": "def get_brain_by_uid(self, uid):\n        if uid == \"0\":\n            return api.get_portal()\n        if self._catalog is None:\n            uid_catalog = api.get_tool(\"uid_catalog\")\n            results = uid_catalog({\"UID\": uid})\n            if len(results) != 1:\n                raise ValueError(\"No object found for UID '{}'\".format(uid))\n            brain = results[0]\n            self._catalog = self.get_catalog_for(brain)\n        results = self.catalog({\"UID\": uid})\n        if not results:\n            raise ValueError(\"No results found for UID '{}'\".format(uid))\n        if len(results) != 1:\n            raise ValueError(\"Found more than one object for UID '{}'\"\n                             .format(uid))\n        return results[0]",
    "docstring": "Lookup brain from the right catalog"
  },
  {
    "code": "async def abort(self, *, comment: str = None):\n        params = {\n            \"system_id\": self.system_id\n        }\n        if comment:\n            params[\"comment\"] = comment\n        self._data = await self._handler.abort(**params)\n        return self",
    "docstring": "Abort the current action.\n\n        :param comment: Reason for aborting the action.\n        :param type: `str`"
  },
  {
    "code": "def parse(region_string):\n    rp = RegionParser()\n    ss = rp.parse(region_string)\n    sss1 = rp.convert_attr(ss)\n    sss2 = _check_wcs(sss1)\n    shape_list, comment_list = rp.filter_shape2(sss2)\n    return ShapeList(shape_list, comment_list=comment_list)",
    "docstring": "Parse DS9 region string into a ShapeList.\n\n    Parameters\n    ----------\n    region_string : str\n        Region string\n\n    Returns\n    -------\n    shapes : `ShapeList`\n        List of `~pyregion.Shape`"
  },
  {
    "code": "def remove_node(self, node):\n        preds = self.reverse_edges.get(node, [])\n        for pred in preds:\n            self.edges[pred].remove(node)\n        succs = self.edges.get(node, [])\n        for suc in succs:\n            self.reverse_edges[suc].remove(node)\n        exc_preds = self.reverse_catch_edges.pop(node, [])\n        for pred in exc_preds:\n            self.catch_edges[pred].remove(node)\n        exc_succs = self.catch_edges.pop(node, [])\n        for suc in exc_succs:\n            self.reverse_catch_edges[suc].remove(node)\n        self.nodes.remove(node)\n        if node in self.rpo:\n            self.rpo.remove(node)\n        del node",
    "docstring": "Remove the node from the graph, removes also all connections.\n\n        :param androguard.decompiler.dad.node.Node node: the node to remove"
  },
  {
    "code": "async def chain(*sources):\n    for source in sources:\n        async with streamcontext(source) as streamer:\n            async for item in streamer:\n                yield item",
    "docstring": "Chain asynchronous sequences together, in the order they are given.\n\n    Note: the sequences are not iterated until it is required,\n    so if the operation is interrupted, the remaining sequences\n    will be left untouched."
  },
  {
    "code": "def isfortran(env, source):\n    try:\n        fsuffixes = env['FORTRANSUFFIXES']\n    except KeyError:\n        return 0\n    if not source:\n        return 0\n    for s in source:\n        if s.sources:\n            ext = os.path.splitext(str(s.sources[0]))[1]\n            if ext in fsuffixes:\n                return 1\n    return 0",
    "docstring": "Return 1 if any of code in source has fortran files in it, 0\n    otherwise."
  },
  {
    "code": "def html_to_dom(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS):\n    if isinstance(html, unicode):\n        decoded_html = html\n        forced_encoding = encoding if encoding else default_encoding\n        html = html.encode(forced_encoding, errors)\n    else:\n        decoded_html = decode_html(html, default_encoding, encoding, errors)\n    try:\n        dom = lxml.html.fromstring(decoded_html, parser=lxml.html.HTMLParser())\n    except ValueError:\n        dom = lxml.html.fromstring(html, parser=lxml.html.HTMLParser())\n    return dom",
    "docstring": "Converts HTML to DOM."
  },
  {
    "code": "def cmd_output_remove(self, args):\n        device = args[0]\n        for i in range(len(self.mpstate.mav_outputs)):\n            conn = self.mpstate.mav_outputs[i]\n            if str(i) == device or conn.address == device:\n                print(\"Removing output %s\" % conn.address)\n                try:\n                    mp_util.child_fd_list_add(conn.port.fileno())\n                except Exception:\n                    pass\n                conn.close()\n                self.mpstate.mav_outputs.pop(i)\n                return",
    "docstring": "remove an output"
  },
  {
    "code": "def release(ctx, yes, latest):\n    m = RepoManager(ctx.obj['agile'])\n    api = m.github_repo()\n    if latest:\n        latest = api.releases.latest()\n        if latest:\n            click.echo(latest['tag_name'])\n    elif m.can_release('sandbox'):\n        branch = m.info['branch']\n        version = m.validate_version()\n        name = 'v%s' % version\n        body = ['Release %s from agiletoolkit' % name]\n        data = dict(\n            tag_name=name,\n            target_commitish=branch,\n            name=name,\n            body='\\n\\n'.join(body),\n            draft=False,\n            prerelease=False\n        )\n        if yes:\n            data = api.releases.create(data=data)\n            m.message('Successfully created a new Github release')\n        click.echo(niceJson(data))\n    else:\n        click.echo('skipped')",
    "docstring": "Create a new release in github"
  },
  {
    "code": "def validate(self, output_type, output_params):\n        return self.request.post('validate',\n                                 dict(output_type=output_type, output_params=output_params))",
    "docstring": "Check that a subscription is defined correctly.\n\n            Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushvalidate\n\n            :param output_type:   One of DataSift's supported output types, e.g. s3\n            :type output_type: str\n            :param output_params: The set of parameters required by the specified output_type for docs on all available connectors see http://dev.datasift.com/docs/push/connectors/\n            :type output_params: str\n            :returns: dict with extra response data\n            :rtype: :class:`~datasift.request.DictResponse`\n            :raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`"
  },
  {
    "code": "def add(self, config, strip_app_name=False, filter_by_app_name=False,\n            key_normalisation_func=default_key_normalisation_func):\n        config = walk_recursive(key_normalisation_func, OrderedDict(config))\n        if filter_by_app_name:\n            config = funcy.compact(funcy.select_keys(\n                lambda k: k.startswith(self._app_name), config))\n        if strip_app_name:\n            strip_app_name_regex = re.compile(\"^%s\" % self._app_name)\n            config = funcy.walk_keys(\n                lambda k: re.sub(strip_app_name_regex, '', k), config)\n        self._sources.append(config)\n        return self",
    "docstring": "Add a dict of config data. Values from later dicts will take precedence\n        over those added earlier, so the order data is added matters.\n\n        Note: Double underscores can be used to indicate dict key name\n        boundaries. i.e. if we have a dict like:\n\n        {\n            'logging': {\n                'level': INFO\n                ...\n            }\n        }\n\n        we could pass an environment variable LOGGING__LEVEL=DEBUG to override\n        the log level.\n\n        Note: Key names will be normalised by recursively applying the\n        key_normalisation_func function. By default this will:\n\n            1) Convert keys to lowercase\n            2) Replace hyphens with underscores\n            3) Strip leading underscores\n\n        This allows key names from different sources (e.g. CLI args, env vars,\n        etc.) to be able to override each other.\n\n        :param config dict: config data\n        :param strip_app_name boolean: If True, the configured app_name will\n        stripped from the start of top-level input keys if present.\n        :param filter_by_app_name boolean: If True, keys that don't begin with\n        the app name will be discarded.\n        :return:"
  },
  {
    "code": "def editor_interfaces(self):\n        return ContentTypeEditorInterfacesProxy(self._client, self.space.id, self._environment_id, self.id)",
    "docstring": "Provides access to editor interface management methods for the given content type.\n\n        API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface\n\n        :return: :class:`ContentTypeEditorInterfacesProxy <contentful_management.content_type_editor_interfaces_proxy.ContentTypeEditorInterfacesProxy>` object.\n        :rtype: contentful.content_type_editor_interfaces_proxy.ContentTypeEditorInterfacesProxy\n\n        Usage:\n\n            >>> content_type_editor_interfaces_proxy = content_type.editor_interfaces()\n            <ContentTypeEditorInterfacesProxy space_id=\"cfexampleapi\" environment_id=\"master\" content_type_id=\"cat\">"
  },
  {
    "code": "def GetEntries(self, parser_mediator, cache=None, database=None, **kwargs):\n    if database is None:\n      raise ValueError('Invalid database.')\n    for table_name, callback_method in iter(self._tables.items()):\n      if parser_mediator.abort:\n        break\n      if not callback_method:\n        continue\n      callback = getattr(self, callback_method, None)\n      if callback is None:\n        logger.warning(\n            '[{0:s}] missing callback method: {1:s} for table: {2:s}'.format(\n                self.NAME, callback_method, table_name))\n        continue\n      esedb_table = database.get_table_by_name(table_name)\n      if not esedb_table:\n        logger.warning('[{0:s}] missing table: {1:s}'.format(\n            self.NAME, table_name))\n        continue\n      callback(\n          parser_mediator, cache=cache, database=database, table=esedb_table,\n          **kwargs)",
    "docstring": "Extracts event objects from the database.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      cache (Optional[ESEDBCache]): cache.\n      database (Optional[pyesedb.file]): ESE database.\n\n    Raises:\n      ValueError: If the database attribute is not valid."
  },
  {
    "code": "def stick_perm(presenter, egg, dist_dict, strategy):\n    np.random.seed()\n    egg_pres, egg_rec, egg_features, egg_dist_funcs = parse_egg(egg)\n    regg = order_stick(presenter, egg, dist_dict, strategy)\n    regg_pres, regg_rec, regg_features, regg_dist_funcs = parse_egg(regg)\n    regg_pres = list(regg_pres)\n    egg_pres = list(egg_pres)\n    idx = [egg_pres.index(r) for r in regg_pres]\n    weights = compute_feature_weights_dict(list(regg_pres), list(regg_pres), list(regg_features), dist_dict)\n    orders = idx\n    return weights, orders",
    "docstring": "Computes weights for one reordering using stick-breaking method"
  },
  {
    "code": "def render_headers(self):\n        lines = []\n        sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location']\n        for sort_key in sort_keys:\n            if self.headers.get(sort_key, False):\n                lines.append('%s: %s' % (sort_key, self.headers[sort_key]))\n        for header_name, header_value in self.headers.items():\n            if header_name not in sort_keys:\n                if header_value:\n                    lines.append('%s: %s' % (header_name, header_value))\n        lines.append('\\r\\n')\n        return '\\r\\n'.join(lines)",
    "docstring": "Renders the headers for this request field."
  },
  {
    "code": "def bm_create_button(self, **kwargs):\n        kwargs.update(self._sanitize_locals(locals()))\n        return self._call('BMCreateButton', **kwargs)",
    "docstring": "Shortcut to the BMCreateButton method.\n\n        See the docs for details on arguments:\n        https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton\n\n        The L_BUTTONVARn fields are especially important, so make sure to\n        read those and act accordingly. See unit tests for some examples."
  },
  {
    "code": "def GenerarPDF(self, archivo=\"\", dest=\"F\"):\n        \"Generar archivo de salida en formato PDF\"\n        try:\n            self.template.render(archivo, dest=dest)\n            return True\n        except Exception, e:\n            self.Excepcion = str(e)\n            return False",
    "docstring": "Generar archivo de salida en formato PDF"
  },
  {
    "code": "def is_feeder(self, team_id=None):\n        if team_id is None:\n            return self._is_feeder\n        team_id = uuid.UUID(str(team_id))\n        if team_id not in self.teams_ids:\n            return False\n        return self.teams[team_id]['role'] == 'FEEDER'",
    "docstring": "Ensure ther resource has the role FEEDER."
  },
  {
    "code": "def iter_query(query):\n    try:\n        itr = click.open_file(query).readlines()\n    except IOError:\n        itr = [query]\n    return itr",
    "docstring": "Accept a filename, stream, or string.\n    Returns an iterator over lines of the query."
  },
  {
    "code": "def insertBefore(self, child: Node, ref_node: Node) -> Node:\n        if self.connected:\n            self._insert_before_web(child, ref_node)\n        return self._insert_before(child, ref_node)",
    "docstring": "Insert new child node before the reference child node.\n\n        If the reference node is not a child of this node, raise ValueError. If\n        this instance is connected to the node on browser, the child node is\n        also added to it."
  },
  {
    "code": "def getSigned(self, ns_uri, ns_key, default=None):\n        if self.isSigned(ns_uri, ns_key):\n            return self.message.getArg(ns_uri, ns_key, default)\n        else:\n            return default",
    "docstring": "Return the specified signed field if available,\n        otherwise return default"
  },
  {
    "code": "def get_ratings(data):\n    episodes = data['episodes']\n    ratings = {}\n    for season in episodes:\n        ratings[season] = collapse(episodes[season])\n    return co.OrderedDict(sorted(ratings.items()))",
    "docstring": "Ratings of all the episodes of all the seasons"
  },
  {
    "code": "def __updateNavButtons(self):\n        navButtons = None\n        for v in self.views:\n            if v.getId() == 'com.android.systemui:id/nav_buttons':\n                navButtons = v\n                break\n        if navButtons:\n            self.navBack = self.findViewById('com.android.systemui:id/back', navButtons)\n            self.navHome = self.findViewById('com.android.systemui:id/home', navButtons)\n            self.navRecentApps = self.findViewById('com.android.systemui:id/recent_apps', navButtons)\n        else:\n            if self.uiAutomatorHelper:\n                print >> sys.stderr, \"WARNING: nav buttons not found. Perhaps the device has hardware buttons.\"\n            self.navBack = None\n            self.navHome = None\n            self.navRecentApps = None",
    "docstring": "Updates the navigation buttons that might be on the device screen."
  },
  {
    "code": "def read_sex_problems(file_name):\n    if file_name is None:\n        return frozenset()\n    problems = None\n    with open(file_name, 'r') as input_file:\n        header_index = dict([\n            (col_name, i) for i, col_name in\n            enumerate(input_file.readline().rstrip(\"\\r\\n\").split(\"\\t\"))\n        ])\n        if \"IID\" not in header_index:\n            msg = \"{}: no column named IID\".format(file_name)\n            raise ProgramError(msg)\n        problems = frozenset([\n            i.rstrip(\"\\r\\n\").split(\"\\t\")[header_index[\"IID\"]]\n            for i in input_file.readlines()\n        ])\n    return problems",
    "docstring": "Reads the sex problem file.\n\n    :param file_name: the name of the file containing sex problems.\n\n    :type file_name: str\n\n    :returns: a :py:class:`frozenset` containing samples with sex problem.\n\n    If there is no ``file_name`` (*i.e.* is ``None``), then an empty\n    :py:class:`frozenset` is returned."
  },
  {
    "code": "def measurement_key(\n        val: Any,\n        default: Any = RaiseTypeErrorIfNotProvided):\n    getter = getattr(val, '_measurement_key_', None)\n    result = NotImplemented if getter is None else getter()\n    if result is not NotImplemented:\n        return result\n    if default is not RaiseTypeErrorIfNotProvided:\n        return default\n    if getter is None:\n        raise TypeError(\n                \"object of type '{}' has no _measurement_key_ method.\"\n                    .format(type(val)))\n    raise TypeError(\"object of type '{}' does have a _measurement_key_ method, \"\n                    \"but it returned NotImplemented.\".format(type(val)))",
    "docstring": "Get the measurement key for the given value.\n\n    Args:\n        val: The value which has the measurement key..\n        default: Determines the fallback behavior when `val` doesn't have\n            a measurement key. If `default` is not set, a TypeError is raised.\n            If default is set to a value, that value is returned if the value\n            does not have `_measurement_key_`.\n\n    Returns:\n        If `val` has a `_measurement_key_` method and its result is not\n        `NotImplemented`, that result is returned. Otherwise, if a default\n        value was specified, the default value is returned.\n\n    Raises:\n        TypeError: `val` doesn't have a _measurement_key_ method (or that method\n            returned NotImplemented) and also no default value was specified."
  },
  {
    "code": "def close(self):\n        with self.lock:\n            if self.device is not None:\n                try:\n                    self.device.close()\n                except IOError:\n                    pass\n                self.device = None",
    "docstring": "Close the contacless reader device."
  },
  {
    "code": "def get_fba_obj_flux(self, objective):\n        flux_result = self.solve_fba(objective)\n        return flux_result.get_value(self._v_wt[objective])",
    "docstring": "Return the maximum objective flux solved by FBA."
  },
  {
    "code": "def getStartingApplication(self, pchAppKeyBuffer, unAppKeyBufferLen):\n        fn = self.function_table.getStartingApplication\n        result = fn(pchAppKeyBuffer, unAppKeyBufferLen)\n        return result",
    "docstring": "Returns the app key for the application that is starting up"
  },
  {
    "code": "def get_all_for(self, key):\n        if not isinstance(key, _string_type):\n            raise TypeError(\"Key needs to be a string.\")\n        return [self[(idx, key)] for idx in _range(self.__kcount[key])]",
    "docstring": "Returns all values of the given key"
  },
  {
    "code": "def fetch(cls, client, _id, symbol):\n        url = \"https://api.robinhood.com/options/chains/\"\n        params = {\n            \"equity_instrument_ids\": _id,\n            \"state\": \"active\",\n            \"tradability\": \"tradable\"\n        }\n        data = client.get(url, params=params)\n        def filter_func(x):\n            return x[\"symbol\"] == symbol\n        results = list(filter(filter_func, data[\"results\"]))\n        return results[0]",
    "docstring": "fetch option chain for instrument"
  },
  {
    "code": "def _load_data_and_files(self):\n        if not _hasattr(self, '_data'):\n            self._data, self._files = self._parse()\n            if self._files:\n                self._full_data = self._data.copy()\n                self._full_data.update(self._files)\n            else:\n                self._full_data = self._data",
    "docstring": "Parses the request content into `self.data`."
  },
  {
    "code": "def connect(self, addr):\n        if _debug: RouterToRouterService._debug(\"connect %r\", addr)\n        conn = ConnectionState(addr)\n        self.multiplexer.connections[addr] = conn\n        conn.service = self\n        conn.pendingNPDU = []\n        request = ServiceRequest(ROUTER_TO_ROUTER_SERVICE_ID)\n        request.pduDestination = addr\n        self.service_request(request)\n        return conn",
    "docstring": "Initiate a connection request to the peer router."
  },
  {
    "code": "def freeze(self, number=None):\n        if number is None:\n            number = self.head_layers\n        for idx, child in enumerate(self.model.children()):\n            if idx < number:\n                mu.freeze_layer(child)",
    "docstring": "Freeze given number of layers in the model"
  },
  {
    "code": "def wait_for_servers(session, servers):\n    nclient = nova.Client(NOVA_VERSION, session=session,\n                          region_name=os.environ['OS_REGION_NAME'])\n    while True:\n        deployed = []\n        undeployed = []\n        for server in servers:\n            c = nclient.servers.get(server.id)\n            if c.addresses != {} and c.status == 'ACTIVE':\n                deployed.append(server)\n            if c.status == 'ERROR':\n                undeployed.append(server)\n        logger.info(\"[nova]: Polling the Deployment\")\n        logger.info(\"[nova]: %s deployed servers\" % len(deployed))\n        logger.info(\"[nova]: %s undeployed servers\" % len(undeployed))\n        if len(deployed) + len(undeployed) >= len(servers):\n            break\n        time.sleep(3)\n    return deployed, undeployed",
    "docstring": "Wait for the servers to be ready.\n\n    Note(msimonin): we don't garantee the SSH connection to be ready."
  },
  {
    "code": "def set_attribute(self, obj, attr, value):\n        if isinstance(obj, MutableMapping):\n            obj[attr] = value\n        else:\n            setattr(obj, attr, value)",
    "docstring": "Set value of attribute in given object instance.\n\n        Reason for existence of this method is the fact that 'attribute' can\n        be also a object's key if it is a dict or any other kind of mapping.\n\n        Args:\n            obj (object): object instance to modify\n            attr (str): attribute (or key) to change\n            value: value to set"
  },
  {
    "code": "def points(self):\n        if self._points is None:\n            _points = self.soma.points.tolist()\n            for n in self.neurites:\n                _points.extend(n.points.tolist())\n            self._points = np.array(_points)\n        return self._points",
    "docstring": "Return unordered array with all the points in this neuron"
  },
  {
    "code": "def macaroon_ops(self, macaroons):\n        if len(macaroons) == 0:\n            raise ValueError('no macaroons provided')\n        storage_id, ops = _decode_macaroon_id(macaroons[0].identifier_bytes)\n        root_key = self.root_keystore_for_ops(ops).get(storage_id)\n        if root_key is None:\n            raise VerificationError(\n                'macaroon key not found in storage')\n        v = Verifier()\n        conditions = []\n        def validator(condition):\n            conditions.append(condition)\n            return True\n        v.satisfy_general(validator)\n        try:\n            v.verify(macaroons[0], root_key, macaroons[1:])\n        except Exception as exc:\n            raise six.raise_from(\n                VerificationError('verification failed: {}'.format(str(exc))),\n                exc,\n            )\n        if (self.ops_store is not None\n            and len(ops) == 1\n                and ops[0].entity.startswith('multi-')):\n            ops = self.ops_store.get_ops(ops[0].entity)\n        return ops, conditions",
    "docstring": "This method makes the oven satisfy the MacaroonOpStore protocol\n        required by the Checker class.\n\n        For macaroons minted with previous bakery versions, it always\n        returns a single LoginOp operation.\n\n        :param macaroons:\n        :return:"
  },
  {
    "code": "def decode_buffer(buffer: dict) -> np.ndarray:\n    buf = np.frombuffer(buffer['data'], dtype=buffer['dtype'])\n    return buf.reshape(buffer['shape'])",
    "docstring": "Translate a DataBuffer into a numpy array.\n\n    :param buffer: Dictionary with 'data' byte array, 'dtype', and 'shape' fields\n    :return: NumPy array of decoded data"
  },
  {
    "code": "def _get_json(self, url):\n        self.log.info(u\"/GET \" + url)\n        r = requests.get(url)\n        if hasattr(r, 'from_cache'):\n            if r.from_cache:\n                self.log.info(\"(from cache)\")\n        if r.status_code != 200:\n            throw_request_err(r)\n        return r.json()",
    "docstring": "Get json from url"
  },
  {
    "code": "def margin(self, axis):\n        if self._slice.ndim < 2:\n            msg = (\n                \"Scale Means marginal cannot be calculated on 1D cubes, as\"\n                \"the scale means already get reduced to a scalar value.\"\n            )\n            raise ValueError(msg)\n        dimension_index = 1 - axis\n        margin = self._slice.margin(axis=axis)\n        if len(margin.shape) > 1:\n            index = [\n                0 if d.dimension_type == DT.MR else slice(None)\n                for d in self._slice.dimensions\n            ]\n            margin = margin[index]\n        total = np.sum(margin)\n        values = self.values[dimension_index]\n        if values is None:\n            return None\n        return np.sum(values * margin) / total",
    "docstring": "Return marginal value of the current slice scaled means.\n\n        This value is the the same what you would get from a single variable\n        (constituting a 2D cube/slice), when the \"non-missing\" filter of the\n        opposite variable would be applied. This behavior is consistent with\n        what is visible in the front-end client."
  },
  {
    "code": "def repr2(obj_, **kwargs):\n    kwargs['nl'] = kwargs.pop('nl', kwargs.pop('newlines', False))\n    val_str = _make_valstr(**kwargs)\n    return val_str(obj_)",
    "docstring": "Attempt to replace repr more configurable\n    pretty version that works the same in both 2 and 3"
  },
  {
    "code": "def _convert_token(self, token):\n        token = token.copy()\n        if \"expiresOn\" in token and \"expiresIn\" in token:\n            token[\"expiresOn\"] = token['expiresIn'] + time.time()\n        return {self._case.sub(r'\\1_\\2', k).lower(): v\n                for k, v in token.items()}",
    "docstring": "Convert token fields from camel case.\n\n        :param dict token: An authentication token.\n        :rtype: dict"
  },
  {
    "code": "def _set_new_object(self, new_obj, inherited_obj, new_class, superclass,\n                        qualifier_repo, propagated, type_str):\n        assert isinstance(new_obj, (CIMMethod, CIMProperty, CIMParameter))\n        if inherited_obj:\n            inherited_obj_qual = inherited_obj.qualifiers\n        else:\n            inherited_obj_qual = None\n        if propagated:\n            assert superclass is not None\n        new_obj.propagated = propagated\n        if propagated:\n            assert inherited_obj is not None\n            new_obj.class_origin = inherited_obj.class_origin\n        else:\n            assert inherited_obj is None\n            new_obj.class_origin = new_class.classname\n        self._resolve_qualifiers(new_obj.qualifiers,\n                                 inherited_obj_qual,\n                                 new_class,\n                                 superclass,\n                                 new_obj.name, type_str,\n                                 qualifier_repo,\n                                 propagate=propagated)",
    "docstring": "Set the object attributes for a single object and resolve the\n        qualifiers. This sets attributes for Properties, Methods, and\n        Parameters."
  },
  {
    "code": "def cli(env, identifier, crt, csr, icc, key, notes):\n    template = {'id': identifier}\n    if crt:\n        template['certificate'] = open(crt).read()\n    if key:\n        template['privateKey'] = open(key).read()\n    if csr:\n        template['certificateSigningRequest'] = open(csr).read()\n    if icc:\n        template['intermediateCertificate'] = open(icc).read()\n    if notes:\n        template['notes'] = notes\n    manager = SoftLayer.SSLManager(env.client)\n    manager.edit_certificate(template)",
    "docstring": "Edit SSL certificate."
  },
  {
    "code": "def decyear2dt(t):\n    year = int(t)\n    rem = t - year \n    base = datetime(year, 1, 1)\n    dt = base + timedelta(seconds=(base.replace(year=base.year+1) - base).total_seconds() * rem)\n    return dt",
    "docstring": "Convert decimal year to datetime"
  },
  {
    "code": "def download_attachments(self):\n        if not self._parent.has_attachments:\n            log.debug(\n                'Parent {} has no attachments, skipping out early.'.format(\n                    self._parent.__class__.__name__))\n            return False\n        if not self._parent.object_id:\n            raise RuntimeError(\n                'Attempted to download attachments of an unsaved {}'.format(\n                    self._parent.__class__.__name__))\n        url = self.build_url(self._endpoints.get('attachments').format(\n            id=self._parent.object_id))\n        response = self._parent.con.get(url)\n        if not response:\n            return False\n        attachments = response.json().get('value', [])\n        self.untrack = True\n        self.add({self._cloud_data_key: attachments})\n        self.untrack = False\n        return True",
    "docstring": "Downloads this message attachments into memory.\n        Need a call to 'attachment.save' to save them on disk.\n\n        :return: Success / Failure\n        :rtype: bool"
  },
  {
    "code": "def _mkdirs_impacket(path, share='C$', conn=None, host=None, username=None, password=None):\n    if conn is None:\n        conn = get_conn(host, username, password)\n    if conn is False:\n        return False\n    comps = path.split('/')\n    pos = 1\n    for comp in comps:\n        cwd = '\\\\'.join(comps[0:pos])\n        try:\n            conn.listPath(share, cwd)\n        except (smbSessionError, smb3SessionError):\n            log.exception('Encountered error running conn.listPath')\n            conn.createDirectory(share, cwd)\n        pos += 1",
    "docstring": "Recursively create a directory structure on an SMB share\n\n    Paths should be passed in with forward-slash delimiters, and should not\n    start with a forward-slash."
  },
  {
    "code": "def attention_bias_batch(batch_coordinates_q,\n                         batch_coordinates_k=None,\n                         condition_fn=None):\n  if batch_coordinates_k is None:\n    batch_coordinates_k = batch_coordinates_q\n  def to_float(bc):\n    bc = tf.squeeze(bc, 1)\n    bc = tf.to_float(bc)\n    return bc\n  bc_v = tf.expand_dims(to_float(batch_coordinates_q), 1)\n  bc_h = tf.expand_dims(to_float(batch_coordinates_k), 0)\n  bias_batch = bc_h - bc_v\n  bias_batch = condition_fn(bias_batch)\n  bias_batch *= -1e9\n  return bias_batch",
    "docstring": "Generate a mask to prevent the batch to attend to each others.\n\n  Args:\n    batch_coordinates_q: Int-like Tensor of shape [length_q, 1] containing the\n      coordinates of the batches\n    batch_coordinates_k: Int-like Tensor of shape [length_k, 1] containing the\n      coordinates of the batches. If None, do self-attention.\n    condition_fn: Callable defining the attention mask.\n\n  Returns:\n    Float-like Tensor of shape [length_q, length_k] containing either 0 or\n    -infinity (-1e9)."
  },
  {
    "code": "def normalize_cmd(self, command):\n        command = command.rstrip()\n        command += self.RETURN\n        return command",
    "docstring": "Normalize CLI commands to have a single trailing newline.\n\n        :param command: Command that may require line feed to be normalized\n        :type command: str"
  },
  {
    "code": "def walk_dir(dir_path, walk_after, recurse=None, archive_mtime=None):\n    if recurse is None:\n        recurse = Settings.recurse\n    result_set = set()\n    if not recurse:\n        return result_set\n    for root, _, filenames in os.walk(dir_path):\n        for filename in filenames:\n            filename_full = os.path.join(root, filename)\n            try:\n                results = walk_file(filename_full, walk_after, recurse,\n                                    archive_mtime)\n                result_set = result_set.union(results)\n            except Exception:\n                print(\"Error with file: {}\".format(filename_full))\n                raise\n    return result_set",
    "docstring": "Recursively optimize a directory."
  },
  {
    "code": "def draw_pin(text, background_color='green', font_color='white'):\n    image = Image.new('RGB', (120, 20))\n    draw = ImageDraw.Draw(image)\n    draw.rectangle([(1, 1), (118, 18)], fill=color(background_color))\n    draw.text((10, 4), text, fill=color(font_color))\n    return image",
    "docstring": "Draws and returns a pin with the specified text and color scheme"
  },
  {
    "code": "def count_values(tokens):\n    ntoks = 0\n    for tok in tokens:\n        if tok in ('=', '/', '$', '&'):\n            if ntoks > 0 and tok == '=':\n                ntoks -= 1\n            break\n        elif tok in whitespace + ',':\n            continue\n        else:\n            ntoks += 1\n    return ntoks",
    "docstring": "Identify the number of values ahead of the current token."
  },
  {
    "code": "def get_stripe_dashboard_url(self):\n\t\tif not self.stripe_dashboard_item_name or not self.id:\n\t\t\treturn \"\"\n\t\telse:\n\t\t\treturn \"{base_url}{item}/{id}\".format(\n\t\t\t\tbase_url=self._get_base_stripe_dashboard_url(),\n\t\t\t\titem=self.stripe_dashboard_item_name,\n\t\t\t\tid=self.id,\n\t\t\t)",
    "docstring": "Get the stripe dashboard url for this object."
  },
  {
    "code": "def format_page(self, page, link_resolver, output):\n        debug('Formatting page %s' % page.link.ref, 'formatting')\n        if output:\n            actual_output = os.path.join(output,\n                                         'html')\n            if not os.path.exists(actual_output):\n                os.makedirs(actual_output)\n        else:\n            actual_output = None\n        page.format(self.formatter, link_resolver, actual_output)",
    "docstring": "Called by `project.Project.format_page`, to leave full control\n        to extensions over the formatting of the pages they are\n        responsible of.\n\n        Args:\n            page: tree.Page, the page to format.\n            link_resolver: links.LinkResolver, object responsible\n                for resolving links potentially mentioned in `page`\n            output: str, path to the output directory."
  },
  {
    "code": "def get_list_dimensions(_list):\n    if isinstance(_list, list) or isinstance(_list, tuple):\n        return [len(_list)] + get_list_dimensions(_list[0])\n    return []",
    "docstring": "Takes a nested list and returns the size of each dimension followed\n    by the element type in the list"
  },
  {
    "code": "def tryOrder(self, commit: Commit):\n        canOrder, reason = self.canOrder(commit)\n        if canOrder:\n            self.logger.trace(\"{} returning request to node\".format(self))\n            self.doOrder(commit)\n        else:\n            self.logger.debug(\"{} cannot return request to node: {}\".format(self, reason))\n        return canOrder",
    "docstring": "Try to order if the Commit message is ready to be ordered."
  },
  {
    "code": "def forwards(apps, schema_editor):\n    Work = apps.get_model('spectator_events', 'Work')\n    for work in Work.objects.all():\n        if not work.slug:\n            work.slug = generate_slug(work.pk)\n            work.save()",
    "docstring": "Re-save all the Works because something earlier didn't create their slugs."
  },
  {
    "code": "def _create_scheduled_actions(conn, as_name, scheduled_actions):\n    if scheduled_actions:\n        for name, action in six.iteritems(scheduled_actions):\n            if 'start_time' in action and isinstance(action['start_time'], six.string_types):\n                action['start_time'] = datetime.datetime.strptime(\n                    action['start_time'], DATE_FORMAT\n                )\n            if 'end_time' in action and isinstance(action['end_time'], six.string_types):\n                action['end_time'] = datetime.datetime.strptime(\n                    action['end_time'], DATE_FORMAT\n                )\n            conn.create_scheduled_group_action(as_name, name,\n                desired_capacity=action.get('desired_capacity'),\n                min_size=action.get('min_size'),\n                max_size=action.get('max_size'),\n                start_time=action.get('start_time'),\n                end_time=action.get('end_time'),\n                recurrence=action.get('recurrence')\n            )",
    "docstring": "Helper function to create scheduled actions"
  },
  {
    "code": "def partition_pairs(neurites, neurite_type=NeuriteType.all):\n    return map(_bifurcationfunc.partition_pair,\n               iter_sections(neurites,\n                             iterator_type=Tree.ibifurcation_point,\n                             neurite_filter=is_type(neurite_type)))",
    "docstring": "Partition pairs at bifurcation points of a collection of neurites.\n    Partition pait is defined as the number of bifurcations at the two\n    daughters of the bifurcating section"
  },
  {
    "code": "def _multiple_field(cls):\n        klassdict = cls.__dict__\n        try:\n            return klassdict[\"_entitylist_multifield\"][0]\n        except (KeyError, IndexError, TypeError):\n            from . import fields\n            multifield_tuple = tuple(fields.find(cls, multiple=True))\n            assert len(multifield_tuple) == 1\n            multifield = multifield_tuple[0]\n            assert issubclass(multifield.type_, Entity)\n            cls._entitylist_multifield =  multifield_tuple\n            return multifield_tuple[0]",
    "docstring": "Return the \"multiple\" TypedField associated with this EntityList.\n\n        This also lazily sets the ``_entitylist_multiplefield`` value if it\n        hasn't been set yet. This is set to a tuple containing one item because\n        if we set the class attribute to the TypedField, we would effectively\n        add a TypedField descriptor to the class, which we don't want.\n\n        Raises:\n            AssertionError: If there is more than one multiple TypedField\n                or the the TypedField type_ is not a subclass of Entity."
  },
  {
    "code": "def import_from_setting(setting_name, fallback):\n    path = getattr(settings, setting_name, None)\n    if path:\n        try:\n            return import_string(path)\n        except ImportError:\n            raise ImproperlyConfigured('%s: No such path.' % path)\n    else:\n        return fallback",
    "docstring": "Return the resolution of an import path stored in a Django setting.\n\n    :arg setting_name: The name of the setting holding the import path\n    :arg fallback: An alternate object to use if the setting is empty or\n      doesn't exist\n\n    Raise ImproperlyConfigured if a path is given that can't be resolved."
  },
  {
    "code": "def get_user(self, user_id, password):\n        self.con.execute('SELECT uid, pwHash FROM archive_users WHERE userId = %s;', (user_id,))\n        results = self.con.fetchall()\n        if len(results) == 0:\n            raise ValueError(\"No such user\")\n        pw_hash = results[0]['pwHash']\n        if not passlib.hash.bcrypt.verify(password, pw_hash):\n            raise ValueError(\"Incorrect password\")\n        self.con.execute('SELECT name FROM archive_roles r INNER JOIN archive_user_roles u ON u.roleId=r.uid '\n                         'WHERE u.userId = %s;', (results[0]['uid'],))\n        role_list = [row['name'] for row in self.con.fetchall()]\n        return mp.User(user_id=user_id, roles=role_list)",
    "docstring": "Retrieve a user record\n\n        :param user_id:\n            the user ID\n        :param password:\n            password\n        :return:\n            A :class:`meteorpi_model.User` if everything is correct\n        :raises:\n            ValueError if the user is found but password is incorrect or if the user is not found."
  },
  {
    "code": "def logout(self):\n        self.client.write('exit\\r\\n')\n        self.client.read_all()\n        self.client.close()",
    "docstring": "Logout from the remote server."
  },
  {
    "code": "def tdev(data, rate=1.0, data_type=\"phase\", taus=None):\n    phase = input_to_phase(data, rate, data_type)\n    (taus, md, mde, ns) = mdev(phase, rate=rate, taus=taus)\n    td = taus * md / np.sqrt(3.0)\n    tde = td / np.sqrt(ns)\n    return taus, td, tde, ns",
    "docstring": "Time deviation.\n        Based on modified Allan variance.\n\n    .. math::\n\n        \\\\sigma^2_{TDEV}( \\\\tau ) = { \\\\tau^2 \\\\over 3 }\n        \\\\sigma^2_{MDEV}( \\\\tau )\n\n    Note that TDEV has a unit of seconds.\n\n    Parameters\n    ----------\n    data: np.array\n        Input data. Provide either phase or frequency (fractional,\n        adimensional).\n    rate: float\n        The sampling rate for data, in Hz. Defaults to 1.0\n    data_type: {'phase', 'freq'}\n        Data type, i.e. phase or frequency. Defaults to \"phase\".\n    taus: np.array\n        Array of tau values, in seconds, for which to compute statistic.\n        Optionally set taus=[\"all\"|\"octave\"|\"decade\"] for automatic\n        tau-list generation.\n\n    Returns\n    -------\n    (taus, tdev, tdev_error, ns): tuple\n          Tuple of values\n    taus: np.array\n        Tau values for which td computed\n    tdev: np.array\n        Computed time deviations (in seconds) for each tau value\n    tdev_errors: np.array\n        Time deviation errors\n    ns: np.array\n        Values of N used in mdev_phase()\n\n    Notes\n    -----\n    http://en.wikipedia.org/wiki/Time_deviation"
  },
  {
    "code": "def build_latent_variables(self):\n        lvs_to_build = []\n        lvs_to_build.append(['Noise Sigma^2', fam.Flat(transform='exp'), fam.Normal(0,3), -1.0])\n        for lag in range(self.X.shape[1]):\n            lvs_to_build.append(['l lag' + str(lag+1), fam.FLat(transform='exp'), fam.Normal(0,3), -1.0])\n        lvs_to_build.append(['tau', fam.Flat(transform='exp'), fam.Normal(0,3), -1.0])\n        return lvs_to_build",
    "docstring": "Builds latent variables for this kernel\n\n        Returns\n        ----------\n        - A list of lists (each sub-list contains latent variable information)"
  },
  {
    "code": "def import_eit_fzj(self, filename, configfile, correction_file=None,\n                       timestep=None, **kwargs):\n        df_emd, dummy1, dummy2 = eit_fzj.read_3p_data(\n            filename,\n            configfile,\n            **kwargs\n        )\n        if correction_file is not None:\n            eit_fzj_utils.apply_correction_factors(df_emd, correction_file)\n        if timestep is not None:\n            df_emd['timestep'] = timestep\n        self._add_to_container(df_emd)\n        print('Summary:')\n        self._describe_data(df_emd)",
    "docstring": "EIT data import for FZJ Medusa systems"
  },
  {
    "code": "def register(key, initializer: callable, param=None):\n    get_current_scope().container.register(key, initializer, param)",
    "docstring": "Adds resolver to global container"
  },
  {
    "code": "def uniqueTags(tagList):\n    ret = []\n    alreadyAdded = set()\n    for tag in tagList:\n        myUid = tag.getUid()\n        if myUid in alreadyAdded:\n            continue\n        ret.append(tag)\n    return TagCollection(ret)",
    "docstring": "uniqueTags - Returns the unique tags in tagList.\n        \n            @param tagList list<AdvancedTag> : A list of tag objects."
  },
  {
    "code": "def many_psds(k=2,fs=1.0, b0=1.0, N=1024):\n    psd=[]\n    for j in range(k):\n        print j\n        x = noise.white(N=2*4096,b0=b0,fs=fs)\n        f, tmp = noise.numpy_psd(x,fs)\n        if j==0:\n            psd = tmp\n        else:\n            psd = psd + tmp\n    return f, psd/k",
    "docstring": "compute average of many PSDs"
  },
  {
    "code": "def _get_file_iterator(self, file_obj):\n        file_obj.seek(0)\n        return iter(lambda: file_obj.read(self.read_bs), '')",
    "docstring": "For given `file_obj` return iterator, which will read the file in\n        `self.read_bs` chunks.\n\n        Args:\n            file_obj (file): File-like object.\n\n        Return:\n            iterator: Iterator reading the file-like object in chunks."
  },
  {
    "code": "def _get_reference(document_path, reference_map):\n    try:\n        return reference_map[document_path]\n    except KeyError:\n        msg = _BAD_DOC_TEMPLATE.format(document_path)\n        raise ValueError(msg)",
    "docstring": "Get a document reference from a dictionary.\n\n    This just wraps a simple dictionary look-up with a helpful error that is\n    specific to :meth:`~.firestore.client.Client.get_all`, the\n    **public** caller of this function.\n\n    Args:\n        document_path (str): A fully-qualified document path.\n        reference_map (Dict[str, .DocumentReference]): A mapping (produced\n            by :func:`_reference_info`) of fully-qualified document paths to\n            document references.\n\n    Returns:\n        .DocumentReference: The matching reference.\n\n    Raises:\n        ValueError: If ``document_path`` has not been encountered."
  },
  {
    "code": "def uddc(udfunc, x, dx):\n    x = ctypes.c_double(x)\n    dx = ctypes.c_double(dx)\n    isdescr = ctypes.c_int()\n    libspice.uddc_c(udfunc, x, dx, ctypes.byref(isdescr))\n    return bool(isdescr.value)",
    "docstring": "SPICE private routine intended solely for the support of SPICE\n    routines. Users should not call this routine directly due to the\n    volatile nature of this routine.\n\n    This routine calculates the derivative of 'udfunc' with respect\n    to time for 'et', then determines if the derivative has a\n    negative value.\n\n    Use the @spiceypy.utils.callbacks.SpiceUDFUNS dectorator to wrap\n    a given python function that takes one parameter (float) and\n    returns a float. For example::\n\n        @spiceypy.utils.callbacks.SpiceUDFUNS\n        def udfunc(et_in):\n            pos, new_et = spice.spkpos(\"MERCURY\", et_in, \"J2000\", \"LT+S\", \"MOON\")\n            return new_et\n\n        deriv = spice.uddf(udfunc, et, 1.0)\n\n    https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/uddc_c.html\n\n    :param udfunc: Name of the routine that computes the scalar value of interest.\n    :type udfunc: ctypes.CFunctionType\n    :param x: Independent variable of 'udfunc'.\n    :type x: float\n    :param dx: Interval from 'x' for derivative calculation.\n    :type dx: float\n    :return: Boolean indicating if the derivative is negative.\n    :rtype: bool"
  },
  {
    "code": "def initialize_block(self, block_header):\n        state_view = \\\n            BlockWrapper.state_view_for_block(\n                self._block_cache.block_store.chain_head,\n                self._state_view_factory)\n        settings_view = SettingsView(state_view)\n        self._min_wait_time = settings_view.get_setting(\n            \"sawtooth.consensus.min_wait_time\", self._min_wait_time, int)\n        self._max_wait_time = settings_view.get_setting(\n            \"sawtooth.consensus.max_wait_time\", self._max_wait_time, int)\n        self._valid_block_publishers = settings_view.get_setting(\n            \"sawtooth.consensus.valid_block_publishers\",\n            self._valid_block_publishers,\n            list)\n        block_header.consensus = b\"Devmode\"\n        self._start_time = time.time()\n        self._wait_time = random.uniform(\n            self._min_wait_time, self._max_wait_time)\n        return True",
    "docstring": "Do initialization necessary for the consensus to claim a block,\n        this may include initiating voting activates, starting proof of work\n        hash generation, or create a PoET wait timer.\n\n        Args:\n            block_header (BlockHeader): the BlockHeader to initialize.\n        Returns:\n            True"
  },
  {
    "code": "def remove_templates(self):\n        self.hosts.remove_templates()\n        self.contacts.remove_templates()\n        self.services.remove_templates()\n        self.servicedependencies.remove_templates()\n        self.hostdependencies.remove_templates()\n        self.timeperiods.remove_templates()",
    "docstring": "Clean useless elements like templates because they are not needed anymore\n\n        :return: None"
  },
  {
    "code": "def factor_rank_autocorrelation(factor_data, period=1):\n    grouper = [factor_data.index.get_level_values('date')]\n    ranks = factor_data.groupby(grouper)['factor'].rank()\n    asset_factor_rank = ranks.reset_index().pivot(index='date',\n                                                  columns='asset',\n                                                  values='factor')\n    if isinstance(period, int):\n        asset_shifted = asset_factor_rank.shift(period)\n    else:\n        shifted_idx = utils.add_custom_calendar_timedelta(\n                asset_factor_rank.index, -pd.Timedelta(period),\n                factor_data.index.levels[0].freq)\n        asset_shifted = asset_factor_rank.reindex(shifted_idx)\n        asset_shifted.index = asset_factor_rank.index\n    autocorr = asset_factor_rank.corrwith(asset_shifted, axis=1)\n    autocorr.name = period\n    return autocorr",
    "docstring": "Computes autocorrelation of mean factor ranks in specified time spans.\n    We must compare period to period factor ranks rather than factor values\n    to account for systematic shifts in the factor values of all names or names\n    within a group. This metric is useful for measuring the turnover of a\n    factor. If the value of a factor for each name changes randomly from period\n    to period, we'd expect an autocorrelation of 0.\n\n    Parameters\n    ----------\n    factor_data : pd.DataFrame - MultiIndex\n        A MultiIndex DataFrame indexed by date (level 0) and asset (level 1),\n        containing the values for a single alpha factor, forward returns for\n        each period, the factor quantile/bin that factor value belongs to, and\n        (optionally) the group the asset belongs to.\n        - See full explanation in utils.get_clean_factor_and_forward_returns\n    period: string or int, optional\n        Period over which to calculate the turnover. If it is a string it must\n        follow pandas.Timedelta constructor format (e.g. '1 days', '1D', '30m',\n        '3h', '1D1h', etc).\n    Returns\n    -------\n    autocorr : pd.Series\n        Rolling 1 period (defined by time_rule) autocorrelation of\n        factor values."
  },
  {
    "code": "def asgray(im):\n    if im.ndim == 2:\n        return im\n    elif im.ndim == 3 and im.shape[2] in (3, 4):\n        return im[..., :3].mean(axis=-1)\n    else:\n        raise ValueError('Invalid image format')",
    "docstring": "Takes an image and returns its grayscale version by averaging the color\n    channels.  if an alpha channel is present, it will simply be ignored. If a\n    grayscale image is given, the original image is returned.\n\n    Parameters\n    ----------\n    image : ndarray, ndim 2 or 3\n        RGB or grayscale image.\n\n    Returns\n    -------\n    gray_image : ndarray, ndim 2\n        Grayscale version of image."
  },
  {
    "code": "def unique(seq, idfunc=None):\n\tif idfunc is None:\n\t\tidfunc = lambda x: x\n\tpreserved_type = type(seq)\n\tseen = {}\n\tresult = []\n\tfor item in seq:\n\t\tmarker = idfunc(item)\n\t\tif marker in seen:\n\t\t\tcontinue\n\t\tseen[marker] = 1\n\t\tresult.append(item)\n\treturn preserved_type(result)",
    "docstring": "Unique a list or tuple and preserve the order\n\n\t@type idfunc: Function or None\n\t@param idfunc: If idfunc is provided it will be called during the\n\tcomparison process."
  },
  {
    "code": "def _process_json(response_body):\n    data = json.loads(response_body)\n    uwpassword = UwPassword(uwnetid=data[\"uwNetID\"],\n                            kerb_status=data[\"kerbStatus\"],\n                            interval=None,\n                            last_change=None,\n                            last_change_med=None,\n                            expires_med=None,\n                            interval_med=None,\n                            minimum_length=int(data[\"minimumLength\"]),\n                            time_stamp=parse(data[\"timeStamp\"]),)\n    if \"lastChange\" in data:\n        uwpassword.last_change = parse(data[\"lastChange\"])\n    if \"interval\" in data:\n        uwpassword.interval = timeparse(data[\"interval\"])\n    if \"lastChangeMed\" in data:\n        uwpassword.last_change_med = parse(data[\"lastChangeMed\"])\n    if \"expiresMed\" in data:\n        uwpassword.expires_med = parse(data[\"expiresMed\"])\n    if \"intervalMed\" in data:\n        uwpassword.interval_med = timeparse(data[\"intervalMed\"])\n    if \"netidStatus\" in data:\n        netid_status = []\n        for status in data[\"netidStatus\"]:\n            netid_status.append(status)\n        uwpassword.netid_status = netid_status\n    return uwpassword",
    "docstring": "Returns a UwPassword objects"
  },
  {
    "code": "def download_source_gafs(group_metadata, target_dir, exclusions=[], base_download_url=None):\n    gaf_urls = [ (data, data[\"source\"]) for data in group_metadata[\"datasets\"] if data[\"type\"] == \"gaf\" and data[\"dataset\"] not in exclusions ]\n    click.echo(\"Found {}\".format(\", \".join( [ kv[0][\"dataset\"] for kv in gaf_urls ] )))\n    downloaded_paths = []\n    for dataset_metadata, gaf_url in gaf_urls:\n        dataset = dataset_metadata[\"dataset\"]\n        path = download_a_dataset_source(group_metadata[\"id\"], dataset_metadata, target_dir, gaf_url, base_download_url=base_download_url)\n        if dataset_metadata[\"compression\"] == \"gzip\":\n            unzipped = os.path.splitext(path)[0]\n            unzip(path, unzipped)\n            path = unzipped\n        else:\n            zipup(path)\n        downloaded_paths.append((dataset_metadata, path))\n    return downloaded_paths",
    "docstring": "This looks at a group metadata dictionary and downloads each GAF source that is not in the exclusions list.\n    For each downloaded file, keep track of the path of the file. If the file is zipped, it will unzip it here.\n    This function returns a list of tuples of the dataset dictionary mapped to the downloaded source path."
  },
  {
    "code": "def enhex(d, separator=''):\n    v = binascii.hexlify(d).decode('ascii')\n    if separator:\n        return separator.join(\n            v[i:i+2]\n            for i in range(0, len(v), 2)\n        )\n    else:\n        return v",
    "docstring": "Convert bytes to their hexadecimal representation, optionally joined by a\n    given separator.\n\n    Args:\n        d(bytes): The data to convert to hexadecimal representation.\n        separator(str): The separator to insert between hexadecimal tuples.\n\n    Returns:\n        str: The hexadecimal representation of ``d``.\n\n    Examples:\n        >>> from pwny import *\n        >>> enhex(b'pwnypack')\n        '70776e797061636b'\n        >>> enhex(b'pwnypack', separator=' ')\n        '70 77 6e 79 70 61 63 6b'"
  },
  {
    "code": "def patch(\n        self,\n        id,\n        name=None,\n        description=None,\n        whitelisted_container_task_types=None,\n        whitelisted_executable_task_types=None,\n    ):\n        request_url = self._client.base_api_url + self.detail_url.format(id=id)\n        data_to_patch = {}\n        if name is not None:\n            data_to_patch[\"name\"] = name\n        if description is not None:\n            data_to_patch[\"description\"] = description\n        if whitelisted_container_task_types is not None:\n            data_to_patch[\n                \"whitelisted_container_task_types\"\n            ] = whitelisted_container_task_types\n        if whitelisted_executable_task_types is not None:\n            data_to_patch[\n                \"whitelisted_executable_task_types\"\n            ] = whitelisted_executable_task_types\n        response = self._client.session.patch(request_url, data=data_to_patch)\n        self.validate_request_success(\n            response_text=response.text,\n            request_url=request_url,\n            status_code=response.status_code,\n            expected_status_code=HTTP_200_OK,\n        )\n        return self.response_data_to_model_instance(response.json())",
    "docstring": "Partially updates a task whitelist on the saltant server.\n\n        Args:\n            id (int): The ID of the task whitelist.\n            name (str, optional): The name of the task whitelist.\n            description (str, optional): A description of the task whitelist.\n            whitelisted_container_task_types (list, optional): A list of\n                whitelisted container task type IDs.\n            whitelisted_executable_task_types (list, optional): A list\n                of whitelisted executable task type IDs.\n\n        Returns:\n            :class:`saltant.models.task_whitelist.TaskWhitelist`:\n                A task whitelist model instance representing the task\n                whitelist just updated."
  },
  {
    "code": "def validate_query_params(self, strict=True):\r\n        if not (self.api_key or default_api_key):\r\n            raise ValueError('API key is missing')\r\n        if strict and self.query_params_mode not in (None, 'and', 'or'):\r\n            raise ValueError('query_params_match should be one of \"and\"/\"or\"')\r\n        if not self.person.is_searchable:\r\n            raise ValueError('No valid name/username/phone/email in request')\r\n        if strict and self.person.unsearchable_fields:\r\n            raise ValueError('Some fields are unsearchable: %s' \r\n                             % self.person.unsearchable_fields)",
    "docstring": "Check if the request is valid and can be sent, raise ValueError if \r\n        not.\r\n        \r\n        `strict` is a boolean argument that defaults to True which means an \r\n        exception is raised on every invalid query parameter, if set to False\r\n        an exception is raised only when the search request cannot be performed\r\n        because required query params are missing."
  },
  {
    "code": "def update_account_info(self):\n        request = self._get_request()\n        return request.post(self.ACCOUNT_UPDATE_URL, {\n            'callback_url': self.account.callback_url\n        })",
    "docstring": "Update current account information\n\n        At the moment you can only update your callback_url.\n\n        Returns:\n            An Account object"
  },
  {
    "code": "def Close(self):\n    if self._connection:\n      self._cursor = None\n      self._connection.close()\n      self._connection = None\n    try:\n      os.remove(self._temp_file_path)\n    except (IOError, OSError):\n      pass\n    self._temp_file_path = ''",
    "docstring": "Closes the database file object.\n\n    Raises:\n      IOError: if the close failed.\n      OSError: if the close failed."
  },
  {
    "code": "def indent(text, num=4):\n    str_indent = ' ' * num\n    return str_indent + ('\\n' + str_indent).join(text.splitlines())",
    "docstring": "Indet the given string"
  },
  {
    "code": "def map_get(self, key, mapkey):\n        op = SD.get(mapkey)\n        sdres = self.lookup_in(key, op)\n        return self._wrap_dsop(sdres, True)",
    "docstring": "Retrieve a value from a map.\n\n        :param str key: The document ID\n        :param str mapkey: Key within the map to retrieve\n        :return: :class:`~.ValueResult`\n        :raise: :exc:`IndexError` if the mapkey does not exist\n        :raise: :cb_exc:`NotFoundError` if the document does not exist.\n\n        .. seealso:: :meth:`map_add` for an example"
  },
  {
    "code": "def functions(self):\n        return [v for v in self.globals.values()\n                if isinstance(v, values.Function)]",
    "docstring": "A list of functions declared or defined in this module."
  },
  {
    "code": "def digest(self, data=None):\n        if self.digest_finalized:\n            return self.digest_out.raw[:self.digest_size]\n        if data is not None:\n            self.update(data)\n        self.digest_out = create_string_buffer(256)\n        length = c_long(0)\n        result = libcrypto.EVP_DigestFinal_ex(self.ctx, self.digest_out,\n                                              byref(length))\n        if result != 1:\n            raise DigestError(\"Unable to finalize digest\")\n        self.digest_finalized = True\n        return self.digest_out.raw[:self.digest_size]",
    "docstring": "Finalizes digest operation and return digest value\n        Optionally hashes more data before finalizing"
  },
  {
    "code": "def shellsort(inlist):\n    n = len(inlist)\n    svec = copy.deepcopy(inlist)\n    ivec = range(n)\n    gap = n / 2\n    while gap > 0:\n        for i in range(gap, n):\n            for j in range(i - gap, -1, -gap):\n                while j >= 0 and svec[j] > svec[j + gap]:\n                    temp = svec[j]\n                    svec[j] = svec[j + gap]\n                    svec[j + gap] = temp\n                    itemp = ivec[j]\n                    ivec[j] = ivec[j + gap]\n                    ivec[j + gap] = itemp\n        gap = gap / 2\n    return svec, ivec",
    "docstring": "Shellsort algorithm.  Sorts a 1D-list.\n\nUsage:   lshellsort(inlist)\nReturns: sorted-inlist, sorting-index-vector (for original list)"
  },
  {
    "code": "def share_of_standby(df, resolution='24h', time_window=None):\n    p_sb = standby(df, resolution, time_window)\n    df = df.resample(resolution).mean()\n    p_tot = df.sum()\n    p_standby = p_sb.sum()\n    share_standby = p_standby / p_tot\n    res = share_standby.iloc[0]\n    return res",
    "docstring": "Compute the share of the standby power in the total consumption.\n\n    Parameters\n    ----------\n    df : pandas.DataFrame or pandas.Series\n        Power (typically electricity, can be anything)\n    resolution : str, default='d'\n        Resolution of the computation.  Data will be resampled to this resolution (as mean) before computation\n        of the minimum.\n        String that can be parsed by the pandas resample function, example ='h', '15min', '6h'\n    time_window : tuple with start-hour and end-hour, default=None\n        Specify the start-time and end-time for the analysis.\n        Only data within this time window will be considered.\n        Both times have to be specified as string ('01:00', '06:30') or as datetime.time() objects\n\n    Returns\n    -------\n    fraction : float between 0-1 with the share of the standby consumption"
  },
  {
    "code": "async def fetchrow(self, *, timeout=None):\n        r\n        self._check_ready()\n        if self._exhausted:\n            return None\n        recs = await self._exec(1, timeout)\n        if len(recs) < 1:\n            self._exhausted = True\n            return None\n        return recs[0]",
    "docstring": "r\"\"\"Return the next row.\n\n        :param float timeout: Optional timeout value in seconds.\n\n        :return: A :class:`Record` instance."
  },
  {
    "code": "def resolve_template(template):\n    \"Accepts a template object, path-to-template or list of paths\"\n    if isinstance(template, (list, tuple)):\n        return loader.select_template(template)\n    elif isinstance(template, basestring):\n        try:\n            return loader.get_template(template)\n        except TemplateDoesNotExist:\n            return None\n    else:\n        return template",
    "docstring": "Accepts a template object, path-to-template or list of paths"
  },
  {
    "code": "def _cbCvtReply(self, msg, returnSignature):\n        if msg is None:\n            return None\n        if returnSignature != _NO_CHECK_RETURN:\n            if not returnSignature:\n                if msg.signature:\n                    raise error.RemoteError(\n                        'Unexpected return value signature')\n            else:\n                if not msg.signature or msg.signature != returnSignature:\n                    msg = 'Expected \"%s\". Received \"%s\"' % (\n                        str(returnSignature), str(msg.signature))\n                    raise error.RemoteError(\n                        'Unexpected return value signature: %s' %\n                        (msg,))\n        if msg.body is None or len(msg.body) == 0:\n            return None\n        if len(msg.body) == 1 and not msg.signature[0] == '(':\n            return msg.body[0]\n        else:\n            return msg.body",
    "docstring": "Converts a remote method call reply message into an appropriate\n        callback\n        value."
  },
  {
    "code": "def describe(self):\n        for stage, corunners in self.get_deployers():\n            print self.name, \"STAGE \", stage\n            for d in corunners:\n                print d.__class__.__name__, \",\".join(\n                        [p[1].__name__ for p in d.phases]\n                        )",
    "docstring": "Iterates through the deployers but doesn't run anything"
  },
  {
    "code": "def recall():\n    a = TpPd(pd=0x3)\n    b = MessageType(mesType=0xb)\n    c = RecallType()\n    d = Facility()\n    packet = a / b / c / d\n    return packet",
    "docstring": "RECALL Section 9.3.18a"
  },
  {
    "code": "def mozjpeg(ext_args):\n    args = copy.copy(_MOZJPEG_ARGS)\n    if Settings.destroy_metadata:\n        args += [\"-copy\", \"none\"]\n    else:\n        args += [\"-copy\", \"all\"]\n    args += ['-outfile']\n    args += [ext_args.new_filename, ext_args.old_filename]\n    extern.run_ext(args)\n    return _JPEG_FORMAT",
    "docstring": "Create argument list for mozjpeg."
  },
  {
    "code": "def _send_loop(self):\n        while True:\n            message, response_queue = self._send_queue.get()\n            if message is self.STOP:\n                break\n            try:\n                self._response_queues.put(response_queue)\n                self._socket.send(message)\n            except Exception:\n                log.exception(\"Exception sending message %s\", message)",
    "docstring": "Service self._send_queue, sending requests to server"
  },
  {
    "code": "def correct_structure(self, atol=1e-8):\n        return np.allclose(self.structure.lattice.matrix,\n                           self.prim.lattice.matrix, atol=atol)",
    "docstring": "Determine if the structure matches the standard primitive structure.\n\n        The standard primitive will be different between seekpath and pymatgen\n        high-symmetry paths, but this is handled by the specific subclasses.\n\n        Args:\n            atol (:obj:`float`, optional): Absolute tolerance used to compare\n                the input structure with the primitive standard structure.\n\n        Returns:\n            bool: ``True`` if the structure is the same as the standard\n            primitive, otherwise ``False``."
  },
  {
    "code": "def find_nonzero_constrained_reactions(model):\n    lower_bound, upper_bound = helpers.find_bounds(model)\n    return [rxn for rxn in model.reactions if\n            0 > rxn.lower_bound > lower_bound or\n            0 < rxn.upper_bound < upper_bound]",
    "docstring": "Return list of reactions with non-zero, non-maximal bounds."
  },
  {
    "code": "def version(self):\n\t\tlines = iter(self._invoke('version').splitlines())\n\t\tversion = next(lines).strip()\n\t\treturn self._parse_version(version)",
    "docstring": "Return the underlying version"
  },
  {
    "code": "def _apply_uncertainty_to_mfd(self, mfd, value):\n        if self.uncertainty_type == 'abGRAbsolute':\n            a, b = value\n            mfd.modify('set_ab', dict(a_val=a, b_val=b))\n        elif self.uncertainty_type == 'bGRRelative':\n            mfd.modify('increment_b', dict(value=value))\n        elif self.uncertainty_type == 'maxMagGRRelative':\n            mfd.modify('increment_max_mag', dict(value=value))\n        elif self.uncertainty_type == 'maxMagGRAbsolute':\n            mfd.modify('set_max_mag', dict(value=value))\n        elif self.uncertainty_type == 'incrementalMFDAbsolute':\n            min_mag, bin_width, occur_rates = value\n            mfd.modify('set_mfd', dict(min_mag=min_mag, bin_width=bin_width,\n                                       occurrence_rates=occur_rates))",
    "docstring": "Modify ``mfd`` object with uncertainty value ``value``."
  },
  {
    "code": "def pprint(self):\n        strings = []\n        for key in sorted(self.keys()):\n            values = self[key]\n            for value in values:\n                strings.append(\"%s=%s\" % (key, value))\n        return \"\\n\".join(strings)",
    "docstring": "Print tag key=value pairs."
  },
  {
    "code": "def authorize(self, username, arguments=[],\n                  authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, priv_lvl=TAC_PLUS_PRIV_LVL_MIN,\n                  rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT):\n        with self.closing():\n            packet = self.send(\n                TACACSAuthorizationStart(username,\n                                         TAC_PLUS_AUTHEN_METH_TACACSPLUS,\n                                         priv_lvl, authen_type, arguments,\n                                         rem_addr=rem_addr, port=port),\n                TAC_PLUS_AUTHOR\n            )\n            reply = TACACSAuthorizationReply.unpacked(packet.body)\n            logger.debug('\\n'.join([\n                reply.__class__.__name__,\n                'recv header <%s>' % packet.header,\n                'recv body <%s>' % reply\n            ]))\n            reply_arguments = dict([\n                arg.split(six.b('='), 1)\n                for arg in reply.arguments or []\n                if arg.find(six.b('=')) > -1]\n            )\n            user_priv_lvl = int(reply_arguments.get(\n                six.b('priv-lvl'), TAC_PLUS_PRIV_LVL_MAX))\n            if user_priv_lvl < priv_lvl:\n                reply.status = TAC_PLUS_AUTHOR_STATUS_FAIL\n        return reply",
    "docstring": "Authorize with a TACACS+ server.\n\n        :param username:\n        :param arguments:      The authorization arguments\n        :param authen_type:    TAC_PLUS_AUTHEN_TYPE_ASCII,\n                               TAC_PLUS_AUTHEN_TYPE_PAP,\n                               TAC_PLUS_AUTHEN_TYPE_CHAP\n        :param priv_lvl:       Minimal Required priv_lvl.\n        :param rem_addr:       AAA request source, default to TAC_PLUS_VIRTUAL_REM_ADDR\n        :param port:           AAA port, default to TAC_PLUS_VIRTUAL_PORT\n        :return:               TACACSAuthenticationReply\n        :raises:               socket.timeout, socket.error"
  },
  {
    "code": "def _cast_to_type(self, value):\n        try:\n            return float(value)\n        except (ValueError, TypeError):\n            self.fail('invalid', value=value)",
    "docstring": "Convert the value to a float and raise error on failures"
  },
  {
    "code": "def filter(self, func):\n        results = OrderedDict()\n        for name, group in self:\n            if func(group):\n                results[name] = group\n        return self.__class__(results)",
    "docstring": "Filter out Groups based on filtering function.\n\n        The function should get a FeatureCollection and return True to leave in the Group and False to take it out."
  },
  {
    "code": "def tab_completion_docstring(self_or_cls):\n        elements = ['%s=Boolean' %k for k in list(Store.renderers.keys())]\n        for name, p in self_or_cls.params().items():\n            param_type = p.__class__.__name__\n            elements.append(\"%s=%s\" % (name, param_type))\n        return \"params(%s)\" % ', '.join(['holoviews=Boolean'] + elements)",
    "docstring": "Generates a docstring that can be used to enable tab-completion\n        of resources."
  },
  {
    "code": "def render(value):\n    if not value:\n        return r'^$'\n    if value[0] != beginning:\n        value = beginning + value\n    if value[-1] != end:\n        value += end\n    return value",
    "docstring": "This function finishes the url pattern creation by adding starting\n    character ^ end possibly by adding end character at the end\n\n    :param value: naive URL value\n    :return: raw string"
  },
  {
    "code": "def _handle_lrr(self, data):\n        msg = LRRMessage(data)\n        if not self._ignore_lrr_states:\n            self._lrr_system.update(msg)\n        self.on_lrr_message(message=msg)\n        return msg",
    "docstring": "Handle Long Range Radio messages.\n\n        :param data: LRR message to parse\n        :type data: string\n\n        :returns: :py:class:`~alarmdecoder.messages.LRRMessage`"
  },
  {
    "code": "def rm(ctx, cluster_id):\n    session = create_session(ctx.obj['AWS_PROFILE_NAME'])\n    client = session.client('emr')\n    try:\n        result = client.describe_cluster(ClusterId=cluster_id)\n        target_dns = result['Cluster']['MasterPublicDnsName']\n        flag = click.prompt(\n            \"Are you sure you want to terminate {0}: {1}? [y/Y]\".format(\n                cluster_id, target_dns), type=str, default='n')\n        if flag.lower() == 'y':\n            result = client.terminate_job_flows(JobFlowIds=[cluster_id])\n    except ClientError as e:\n        click.echo(e, err=True)",
    "docstring": "Terminate a EMR cluster"
  },
  {
    "code": "def check_environment_presets():\n    presets = [x for x in os.environ.copy().keys() if x.startswith('NOVA_') or\n               x.startswith('OS_')]\n    if len(presets) < 1:\n        return True\n    else:\n        click.echo(\"_\" * 80)\n        click.echo(\"*WARNING* Found existing environment variables that may \"\n                   \"cause conflicts:\")\n        for preset in presets:\n            click.echo(\"  - %s\" % preset)\n        click.echo(\"_\" * 80)\n        return False",
    "docstring": "Checks for environment variables that can cause problems with supernova"
  },
  {
    "code": "def reload(self):\n        'Generate histrow for each row and then reverse-sort by length.'\n        self.rows = []\n        self.discreteBinning()\n        for c in self.nonKeyVisibleCols:\n            c._cachedValues = collections.OrderedDict()",
    "docstring": "Generate histrow for each row and then reverse-sort by length."
  },
  {
    "code": "def BuildCloudMetadataRequests():\n  amazon_collection_map = {\n      \"/\".join((AMAZON_URL_BASE, \"instance-id\")): \"instance_id\",\n      \"/\".join((AMAZON_URL_BASE, \"ami-id\")): \"ami_id\",\n      \"/\".join((AMAZON_URL_BASE, \"hostname\")): \"hostname\",\n      \"/\".join((AMAZON_URL_BASE, \"public-hostname\")): \"public_hostname\",\n      \"/\".join((AMAZON_URL_BASE, \"instance-type\")): \"instance_type\",\n  }\n  google_collection_map = {\n      \"/\".join((GOOGLE_URL_BASE, \"instance/id\")): \"instance_id\",\n      \"/\".join((GOOGLE_URL_BASE, \"instance/zone\")): \"zone\",\n      \"/\".join((GOOGLE_URL_BASE, \"project/project-id\")): \"project_id\",\n      \"/\".join((GOOGLE_URL_BASE, \"instance/hostname\")): \"hostname\",\n      \"/\".join((GOOGLE_URL_BASE, \"instance/machine-type\")): \"machine_type\",\n  }\n  return CloudMetadataRequests(requests=_MakeArgs(amazon_collection_map,\n                                                  google_collection_map))",
    "docstring": "Build the standard set of cloud metadata to collect during interrogate."
  },
  {
    "code": "def get_interface_detail_request(last_interface_name,\n                                     last_interface_type):\n        request_interface = ET.Element(\n            'get-interface-detail',\n            xmlns=\"urn:brocade.com:mgmt:brocade-interface-ext\"\n        )\n        if last_interface_name != '':\n            last_received_int = ET.SubElement(request_interface,\n                                              \"last-rcvd-interface\")\n            last_int_type_el = ET.SubElement(last_received_int,\n                                             \"interface-type\")\n            last_int_type_el.text = last_interface_type\n            last_int_name_el = ET.SubElement(last_received_int,\n                                             \"interface-name\")\n            last_int_name_el.text = last_interface_name\n        return request_interface",
    "docstring": "Creates a new Netconf request based on the last received\n        interface name and type when the hasMore flag is true"
  },
  {
    "code": "async def _recv_loop(self):\n        while self._connected:\n            try:\n                data = await self._recv()\n            except asyncio.CancelledError:\n                break\n            except Exception as e:\n                if isinstance(e, (IOError, asyncio.IncompleteReadError)):\n                    msg = 'The server closed the connection'\n                    self._log.info(msg)\n                elif isinstance(e, InvalidChecksumError):\n                    msg = 'The server response had an invalid checksum'\n                    self._log.info(msg)\n                else:\n                    msg = 'Unexpected exception in the receive loop'\n                    self._log.exception(msg)\n                await self.disconnect()\n                if self._recv_queue.empty():\n                    self._recv_queue.put_nowait(None)\n                break\n            try:\n                await self._recv_queue.put(data)\n            except asyncio.CancelledError:\n                break",
    "docstring": "This loop is constantly putting items on the queue as they're read."
  },
  {
    "code": "def unassign_gradebook_column_from_gradebook(self, gradebook_column_id, gradebook_id):\n        mgr = self._get_provider_manager('GRADING', local=True)\n        lookup_session = mgr.get_gradebook_lookup_session(proxy=self._proxy)\n        lookup_session.get_gradebook(gradebook_id)\n        self._unassign_object_from_catalog(gradebook_column_id, gradebook_id)",
    "docstring": "Removes a ``GradebookColumn`` from a ``Gradebook``.\n\n        arg:    gradebook_column_id (osid.id.Id): the ``Id`` of the\n                ``GradebookColumn``\n        arg:    gradebook_id (osid.id.Id): the ``Id`` of the\n                ``Gradebook``\n        raise:  NotFound - ``gradebook_column_id`` or ``gradebook_id``\n                not found or ``gradebook_column_id`` not assigned to\n                ``gradebook_id``\n        raise:  NullArgument - ``gradebook_column_id`` or\n                ``gradebook_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def handle_unsubscribe_request(cls, request, message, dispatch, hash_is_valid, redirect_to):\n        if hash_is_valid:\n            Subscription.cancel(\n                dispatch.recipient_id or dispatch.address, cls.alias, dispatch.messenger\n            )\n            signal = sig_unsubscribe_success\n        else:\n            signal = sig_unsubscribe_failed\n        signal.send(cls, request=request, message=message, dispatch=dispatch)\n        return redirect(redirect_to)",
    "docstring": "Handles user subscription cancelling request.\n\n        :param Request request: Request instance\n        :param Message message: Message model instance\n        :param Dispatch dispatch: Dispatch model instance\n        :param bool hash_is_valid: Flag indicating that user supplied request signature is correct\n        :param str redirect_to: Redirection URL\n        :rtype: list"
  },
  {
    "code": "def directed_bipartition(seq, nontrivial=False):\n    bipartitions = [\n        (tuple(seq[i] for i in part0_idx), tuple(seq[j] for j in part1_idx))\n        for part0_idx, part1_idx in directed_bipartition_indices(len(seq))\n    ]\n    if nontrivial:\n        return bipartitions[1:-1]\n    return bipartitions",
    "docstring": "Return a list of directed bipartitions for a sequence.\n\n    Args:\n        seq (Iterable): The sequence to partition.\n\n    Returns:\n        list[tuple[tuple]]: A list of tuples containing each of the two\n        parts.\n\n    Example:\n        >>> directed_bipartition((1, 2, 3))  # doctest: +NORMALIZE_WHITESPACE\n        [((), (1, 2, 3)),\n         ((1,), (2, 3)),\n         ((2,), (1, 3)),\n         ((1, 2), (3,)),\n         ((3,), (1, 2)),\n         ((1, 3), (2,)),\n         ((2, 3), (1,)),\n         ((1, 2, 3), ())]"
  },
  {
    "code": "def set_current_time(self, t):\n        method = \"set_current_time\"\n        A = None\n        metadata = {method: t}\n        send_array(self.socket, A, metadata)\n        A, metadata = recv_array(\n            self.socket, poll=self.poll, poll_timeout=self.poll_timeout,\n            flags=self.zmq_flags)",
    "docstring": "Set current time of simulation"
  },
  {
    "code": "def decode(self, encoding='utf-8', errors='strict'):\n        original_class = getattr(self, 'original_class')\n        return original_class(super(ColorBytes, self).decode(encoding, errors))",
    "docstring": "Decode using the codec registered for encoding. Default encoding is 'utf-8'.\n\n        errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors\n        raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name\n        registered with codecs.register_error that is able to handle UnicodeDecodeErrors.\n\n        :param str encoding: Codec.\n        :param str errors: Error handling scheme."
  },
  {
    "code": "def get_functions_auth_string(self, target_subscription_id):\n        self._initialize_session()\n        function_auth_variables = [\n            constants.ENV_FUNCTION_TENANT_ID,\n            constants.ENV_FUNCTION_CLIENT_ID,\n            constants.ENV_FUNCTION_CLIENT_SECRET\n        ]\n        if all(k in os.environ for k in function_auth_variables):\n            auth = {\n                'credentials':\n                    {\n                        'client_id': os.environ[constants.ENV_FUNCTION_CLIENT_ID],\n                        'secret': os.environ[constants.ENV_FUNCTION_CLIENT_SECRET],\n                        'tenant': os.environ[constants.ENV_FUNCTION_TENANT_ID]\n                    },\n                'subscription': target_subscription_id\n            }\n        elif type(self.credentials) is ServicePrincipalCredentials:\n            auth = {\n                'credentials':\n                    {\n                        'client_id': os.environ[constants.ENV_CLIENT_ID],\n                        'secret': os.environ[constants.ENV_CLIENT_SECRET],\n                        'tenant': os.environ[constants.ENV_TENANT_ID]\n                    },\n                'subscription': target_subscription_id\n            }\n        else:\n            raise NotImplementedError(\n                \"Service Principal credentials are the only \"\n                \"supported auth mechanism for deploying functions.\")\n        return json.dumps(auth, indent=2)",
    "docstring": "Build auth json string for deploying\n        Azure Functions.  Look for dedicated\n        Functions environment variables or\n        fall back to normal Service Principal\n        variables."
  },
  {
    "code": "def matches(text, what):\n    return text.find(what) > -1 if is_string(what) else what.match(text)",
    "docstring": "Check if ``what`` occurs in ``text``"
  },
  {
    "code": "def ValidateKey(cls, key_path):\n    for prefix in cls.VALID_PREFIXES:\n      if key_path.startswith(prefix):\n        return\n    if key_path.startswith('HKEY_CURRENT_USER\\\\'):\n      raise errors.FormatError(\n          'HKEY_CURRENT_USER\\\\ is not supported instead use: '\n          'HKEY_USERS\\\\%%users.sid%%\\\\')\n    raise errors.FormatError(\n        'Unupported Registry key path: {0:s}'.format(key_path))",
    "docstring": "Validates this key against supported key names.\n\n    Args:\n      key_path (str): path of a Windows Registry key.\n\n    Raises:\n      FormatError: when key is not supported."
  },
  {
    "code": "def unique(iterable, key=identity):\n    seen = set()\n    for item in iterable:\n        item_key = key(item)\n        if item_key not in seen:\n            seen.add(item_key)\n            yield item",
    "docstring": "Yields all the unique values in an iterable maintaining order"
  },
  {
    "code": "def _loopreport(self):\n        while 1:\n            eventlet.sleep(0.2)\n            ac2popenlist = {}\n            for action in self.session._actions:\n                for popen in action._popenlist:\n                    if popen.poll() is None:\n                        lst = ac2popenlist.setdefault(action.activity, [])\n                        lst.append(popen)\n                if not action._popenlist and action in self._actionmayfinish:\n                    super(RetoxReporter, self).logaction_finish(action)\n                    self._actionmayfinish.remove(action)\n            self.screen.draw_next_frame(repeat=False)",
    "docstring": "Loop over the report progress"
  },
  {
    "code": "def up_capture(self, benchmark, threshold=0.0, compare_op=\"ge\"):\n        slf, bm = self.upmarket_filter(\n            benchmark=benchmark,\n            threshold=threshold,\n            compare_op=compare_op,\n            include_benchmark=True,\n        )\n        return slf.geomean() / bm.geomean()",
    "docstring": "Upside capture ratio.\n\n        Measures the performance of `self` relative to benchmark\n        conditioned on periods where `benchmark` is gt or ge to\n        `threshold`.\n\n        Upside capture ratios are calculated by taking the fund's\n        monthly return during the periods of positive benchmark\n        performance and dividing it by the benchmark return.\n        [Source: CFA Institute]\n\n        Parameters\n        ----------\n        benchmark : {pd.Series, TSeries, 1d np.ndarray}\n            The benchmark security to which `self` is compared.\n        threshold : float, default 0.\n            The threshold at which the comparison should be done.\n            `self` and `benchmark` are \"filtered\" to periods where\n            `benchmark` is gt/ge `threshold`.\n        compare_op : {'ge', 'gt'}\n            Comparison operator used to compare to `threshold`.\n            'gt' is greater-than; 'ge' is greater-than-or-equal.\n\n        Returns\n        -------\n        float\n\n        Note\n        ----\n        This metric uses geometric, not arithmetic, mean return."
  },
  {
    "code": "async def create_authenticator_async(self, connection, debug=False, loop=None, **kwargs):\n        self.loop = loop or asyncio.get_event_loop()\n        self._connection = connection\n        self._session = SessionAsync(connection, loop=self.loop, **kwargs)\n        try:\n            self._cbs_auth = c_uamqp.CBSTokenAuth(\n                self.audience,\n                self.token_type,\n                self.token,\n                int(self.expires_at),\n                self._session._session,\n                self.timeout,\n                self._connection.container_id)\n            self._cbs_auth.set_trace(debug)\n        except ValueError:\n            await self._session.destroy_async()\n            raise errors.AMQPConnectionError(\n                \"Unable to open authentication session on connection {}.\\n\"\n                \"Please confirm target hostname exists: {}\".format(\n                    connection.container_id, connection.hostname)) from None\n        return self._cbs_auth",
    "docstring": "Create the async AMQP session and the CBS channel with which\n        to negotiate the token.\n\n        :param connection: The underlying AMQP connection on which\n         to create the session.\n        :type connection: ~uamqp.async_ops.connection_async.ConnectionAsync\n        :param debug: Whether to emit network trace logging events for the\n         CBS session. Default is `False`. Logging events are set at INFO level.\n        :type debug: bool\n        :param loop: A user specified event loop.\n        :type loop: ~asycnio.AbstractEventLoop\n        :rtype: uamqp.c_uamqp.CBSTokenAuth"
  },
  {
    "code": "def contains(self, other):\n        if self.is_valid_range(other):\n            if not self:\n                return not other\n            elif not other or other.startsafter(self) and other.endsbefore(self):\n                return True\n            else:\n                return False\n        elif self.is_valid_scalar(other):\n            is_within_lower = True\n            if not self.lower_inf:\n                lower_cmp = operator.le if self.lower_inc else operator.lt\n                is_within_lower = lower_cmp(self.lower, other)\n            is_within_upper = True\n            if not self.upper_inf:\n                upper_cmp = operator.ge if self.upper_inc else operator.gt\n                is_within_upper = upper_cmp(self.upper, other)\n            return is_within_lower and is_within_upper\n        else:\n            raise TypeError(\n                \"Unsupported type to test for inclusion '{0.__class__.__name__}'\".format(\n                    other))",
    "docstring": "Return True if this contains other. Other may be either range of same\n        type or scalar of same type as the boundaries.\n\n            >>> intrange(1, 10).contains(intrange(1, 5))\n            True\n            >>> intrange(1, 10).contains(intrange(5, 10))\n            True\n            >>> intrange(1, 10).contains(intrange(5, 10, upper_inc=True))\n            False\n            >>> intrange(1, 10).contains(1)\n            True\n            >>> intrange(1, 10).contains(10)\n            False\n\n        Contains can also be called using the ``in`` operator.\n\n            >>> 1 in intrange(1, 10)\n            True\n\n        This is the same as the ``self @> other`` in PostgreSQL.\n\n        :param other: Object to be checked whether it exists within this range\n                      or not.\n        :return: ``True`` if `other` is completely within this range, otherwise\n                 ``False``.\n        :raises TypeError: If `other` is not of the correct type."
  },
  {
    "code": "def SetEnvironmentVariable(self, name, value):\n    if isinstance(value, py2to3.STRING_TYPES):\n      value = self._PathStripPrefix(value)\n    if value is not None:\n      self._environment_variables[name.upper()] = value",
    "docstring": "Sets an environment variable in the Windows path helper.\n\n    Args:\n      name (str): name of the environment variable without enclosing\n          %-characters, e.g. SystemRoot as in %SystemRoot%.\n      value (str): value of the environment variable."
  },
  {
    "code": "def _cursor(self):\n        if self._conn is None:\n            self._conn = sqlite3.connect(self.filename,\n                                         check_same_thread=False)\n        return self._conn.cursor()",
    "docstring": "Asserts that the connection is open and returns a cursor"
  },
  {
    "code": "def parse_quadrant_measurement(quad_azimuth):\n    def rotation_direction(first, second):\n        return np.cross(_azimuth2vec(first), _azimuth2vec(second))\n    quad_azimuth = quad_azimuth.strip()\n    try:\n        first_dir = quadrantletter_to_azimuth(quad_azimuth[0].upper())\n        sec_dir = quadrantletter_to_azimuth(quad_azimuth[-1].upper())\n    except KeyError:\n        raise ValueError('{} is not a valid azimuth'.format(quad_azimuth))\n    angle = float(quad_azimuth[1:-1])\n    direc = rotation_direction(first_dir, sec_dir)\n    azi = first_dir + direc * angle\n    if abs(direc) < 0.9:\n        raise ValueError('{} is not a valid azimuth'.format(quad_azimuth))\n    if azi < 0:\n        azi += 360\n    elif azi > 360:\n        azi -= 360\n    return azi",
    "docstring": "Parses a quadrant measurement of the form \"AxxB\", where A and B are cardinal\n    directions and xx is an angle measured relative to those directions.\n\n    In other words, it converts a measurement such as E30N into an azimuth of\n    60 degrees, or W10S into an azimuth of 260 degrees.\n\n    For ambiguous quadrant measurements such as \"N30S\", a ValueError is raised.\n\n    Parameters\n    -----------\n    quad_azimuth : string\n        An azimuth measurement in quadrant form.\n\n    Returns\n    -------\n    azi : float\n        An azimuth in degrees clockwise from north.\n\n    See Also\n    --------\n    parse_azimuth"
  },
  {
    "code": "def _generate_api_config_with_root(self, request):\n    actual_root = self._get_actual_root(request)\n    generator = api_config.ApiConfigGenerator()\n    api = request.body_json['api']\n    version = request.body_json['version']\n    lookup_key = (api, version)\n    service_factories = self._backend.api_name_version_map.get(lookup_key)\n    if not service_factories:\n      return None\n    service_classes = [service_factory.service_class\n                       for service_factory in service_factories]\n    config_dict = generator.get_config_dict(\n        service_classes, hostname=actual_root)\n    for config in config_dict.get('items', []):\n      lookup_key_with_root = (\n          config.get('name', ''), config.get('version', ''), actual_root)\n      self._config_manager.save_config(lookup_key_with_root, config)\n    return config_dict",
    "docstring": "Generate an API config with a specific root hostname.\n\n    This uses the backend object and the ApiConfigGenerator to create an API\n    config specific to the hostname of the incoming request. This allows for\n    flexible API configs for non-standard environments, such as localhost.\n\n    Args:\n      request: An ApiRequest, the transformed request sent to the Discovery API.\n\n    Returns:\n      A string representation of the generated API config."
  },
  {
    "code": "def _refresh(self, _):\n        from google.appengine.api import app_identity\n        try:\n            token, _ = app_identity.get_access_token(self._scopes)\n        except app_identity.Error as e:\n            raise exceptions.CredentialsError(str(e))\n        self.access_token = token",
    "docstring": "Refresh self.access_token.\n\n        Args:\n          _: (ignored) A function matching httplib2.Http.request's signature."
  },
  {
    "code": "def parse_table_properties(doc, table, prop):\n    \"Parse table properties.\"\n    if not table:\n        return\n    style = prop.find(_name('{{{w}}}tblStyle'))\n    if style is not None:\n        table.style_id = style.attrib[_name('{{{w}}}val')]\n        doc.add_style_as_used(table.style_id)",
    "docstring": "Parse table properties."
  },
  {
    "code": "def from_points(cls, point1, point2):\n        if isinstance(point1, Point) and isinstance(point2, Point):\n            displacement = point1.substract(point2)\n            return cls(displacement.x, displacement.y, displacement.z)\n        raise TypeError",
    "docstring": "Return a Vector instance from two given points."
  },
  {
    "code": "def _output_text(complete_output, categories):\n    output = \"\"\n    for result in complete_output:\n        list_result = complete_output[result]\n        if list_result:\n            list_result_sorted = sorted(list_result,\n                                        key=lambda x: list_result[x],\n                                        reverse=True)\n            output += \"\\n\\n{0}:\\n\".format(result)\n            for element in list_result_sorted:\n                output += \"\\n{0} {1}\".format(list_result[element], element)\n    output += \"\\n--\"\n    return output",
    "docstring": "Output the results obtained in text format.\n\n    :return: str, html formatted output"
  },
  {
    "code": "def _deploy(self):\n        timeout = int(os.environ.get('AMULET_SETUP_TIMEOUT', 900))\n        try:\n            self.d.setup(timeout=timeout)\n            self.d.sentry.wait(timeout=timeout)\n        except amulet.helpers.TimeoutError:\n            amulet.raise_status(\n                amulet.FAIL,\n                msg=\"Deployment timed out ({}s)\".format(timeout)\n            )\n        except Exception:\n            raise",
    "docstring": "Deploy environment and wait for all hooks to finish executing."
  },
  {
    "code": "def db_connect(cls, path):\n        con = sqlite3.connect(path, isolation_level=None, timeout=2**30)\n        con.row_factory = StateEngine.db_row_factory\n        return con",
    "docstring": "connect to our chainstate db"
  },
  {
    "code": "def add_separator(self, sub_menu='Advanced'):\n        action = QtWidgets.QAction(self)\n        action.setSeparator(True)\n        if sub_menu:\n            try:\n                mnu = self._sub_menus[sub_menu]\n            except KeyError:\n                pass\n            else:\n                mnu.addAction(action)\n        else:\n            self._actions.append(action)\n        return action",
    "docstring": "Adds a sepqrator to the editor's context menu.\n\n        :return: The sepator that has been added.\n        :rtype: QtWidgets.QAction"
  },
  {
    "code": "def load_module(self, module_name, path=None):\n        self.ensure_started()\n        if path is None:\n            path = sys.path\n        mod = self.client.call(_load_module, module_name, path)\n        mod.__isolation_context__ = self\n        return mod",
    "docstring": "Import a module into this isolation context and return a proxy for it."
  },
  {
    "code": "def updateEvent(self, event=None, home=None):\n        if not home: home=self.default_home\n        if not event:\n            listEvent = dict()\n            for cam_id in self.lastEvent:\n                listEvent[self.lastEvent[cam_id]['time']] = self.lastEvent[cam_id]\n            event = listEvent[sorted(listEvent)[0]]\n        home_data = self.homeByName(home)\n        postParams = {\n            \"access_token\" : self.getAuthToken,\n            \"home_id\" : home_data['id'],\n            \"event_id\" : event['id']\n        }\n        resp = postRequest(_GETEVENTSUNTIL_REQ, postParams)\n        eventList = resp['body']['events_list']\n        for e in eventList:\n            self.events[ e['camera_id'] ][ e['time'] ] = e\n        for camera in self.events:\n            self.lastEvent[camera]=self.events[camera][sorted(self.events[camera])[-1]]",
    "docstring": "Update the list of event with the latest ones"
  },
  {
    "code": "def do_block(parser, token):\n    name, args, kwargs = get_signature(token, contextable=True)\n    kwargs['nodelist'] = parser.parse(('end%s' % name,))\n    parser.delete_first_token()\n    return BlockNode(parser, name, *args, **kwargs)",
    "docstring": "Process several nodes inside a single block\n    Block functions take ``context``, ``nodelist`` as first arguments\n    If the second to last argument is ``as``, the rendered result is stored in the context and is named whatever the last argument is.\n\n    Syntax::\n\n        {% [block] [var args...] [name=value kwargs...] [as varname] %}\n            ... nodelist ...\n        {% end[block] %}\n\n    Examples::\n\n        {% render_block as rendered_output %}\n            {{ request.path }}/blog/{{ blog.slug }}\n        {% endrender_block %}\n\n        {% highlight_block python %}\n            import this\n        {% endhighlight_block %}"
  },
  {
    "code": "def _is_list_iter(self):\n        iter_var_type = (\n            self.context.vars.get(self.stmt.iter.id).typ\n            if isinstance(self.stmt.iter, ast.Name)\n            else None\n        )\n        if isinstance(self.stmt.iter, ast.List) or isinstance(iter_var_type, ListType):\n            return True\n        if isinstance(self.stmt.iter, ast.Attribute):\n            iter_var_type = self.context.globals.get(self.stmt.iter.attr)\n            if iter_var_type and isinstance(iter_var_type.typ, ListType):\n                return True\n        return False",
    "docstring": "Test if the current statement is a type of list, used in for loops."
  },
  {
    "code": "def data(self, data):\n        self._buffer = self._buffer + data\n        while self._data_handler():\n            pass",
    "docstring": "Use a length prefixed protocol to give the length of a pickled\n        message."
  },
  {
    "code": "def search(query, team=None):\n    if team is None:\n        team = _find_logged_in_team()\n    if team is not None:\n        session = _get_session(team)\n        response = session.get(\"%s/api/search/\" % get_registry_url(team), params=dict(q=query))\n        print(\"* Packages in team %s\" % team)\n        packages = response.json()['packages']\n        for pkg in packages:\n            print((\"%s:\" % team) + (\"%(owner)s/%(name)s\" % pkg))\n        if len(packages) == 0:\n            print(\"(No results)\")\n        print(\"* Packages in public cloud\")\n    public_session = _get_session(None)\n    response = public_session.get(\"%s/api/search/\" % get_registry_url(None), params=dict(q=query))\n    packages = response.json()['packages']\n    for pkg in packages:\n        print(\"%(owner)s/%(name)s\" % pkg)\n    if len(packages) == 0:\n        print(\"(No results)\")",
    "docstring": "Search for packages"
  },
  {
    "code": "def geometric_series(q, n):\n    q = np.asarray(q)\n    if n < 0:\n        raise ValueError('Finite geometric series is only defined for n>=0.')\n    else:\n        if q.ndim == 0:\n            if q == 1:\n                s = (n + 1) * 1.0\n                return s\n            else:\n                s = (1.0 - q ** (n + 1)) / (1.0 - q)\n                return s\n        s = np.zeros(np.shape(q), dtype=q.dtype)\n        ind = (q == 1.0)\n        s[ind] = (n + 1) * 1.0\n        not_ind = np.logical_not(ind)\n        s[not_ind] = (1.0 - q[not_ind] ** (n + 1)) / (1.0 - q[not_ind])\n        return s",
    "docstring": "Compute finite geometric series.\n\n                                \\frac{1-q^{n+1}}{1-q}   q \\neq 1\n        \\sum_{k=0}^{n} q^{k}=\n                                 n+1                     q  = 1\n\n    Parameters\n    ----------\n    q : array-like\n        The common ratio of the geometric series.\n    n : int\n        The number of terms in the finite series.\n\n    Returns\n    -------\n    s : float or ndarray\n        The value of the finite series."
  },
  {
    "code": "def alter_subprocess_kwargs_by_platform(**kwargs):\r\n    kwargs.setdefault('close_fds', os.name == 'posix')\r\n    if os.name == 'nt':\r\n        CONSOLE_CREATION_FLAGS = 0\n        CREATE_NO_WINDOW = 0x08000000\r\n        CONSOLE_CREATION_FLAGS |= CREATE_NO_WINDOW\r\n        kwargs.setdefault('creationflags', CONSOLE_CREATION_FLAGS)\r\n    return kwargs",
    "docstring": "Given a dict, populate kwargs to create a generally\r\n    useful default setup for running subprocess processes\r\n    on different platforms. For example, `close_fds` is\r\n    set on posix and creation of a new console window is\r\n    disabled on Windows.\r\n\r\n    This function will alter the given kwargs and return\r\n    the modified dict."
  },
  {
    "code": "def drop_table(self, cursor, target, options):\n        \"Drops the target table.\"\n        sql = 'DROP TABLE IF EXISTS {0}'\n        cursor.execute(sql.format(self.qualified_names[target]))",
    "docstring": "Drops the target table."
  },
  {
    "code": "def same_types(self, index1, index2):\r\n        try:\r\n            same = self.table[index1].type == self.table[index2].type != SharedData.TYPES.NO_TYPE\r\n        except Exception:\r\n            self.error()\r\n        return same",
    "docstring": "Returns True if both symbol table elements are of the same type"
  },
  {
    "code": "def read(self, entity=None, attrs=None, ignore=None, params=None):\n        if attrs is None:\n            attrs = self.update_json([])\n        if ignore is None:\n            ignore = set()\n        ignore.add('account_password')\n        return super(AuthSourceLDAP, self).read(entity, attrs, ignore, params)",
    "docstring": "Do not read the ``account_password`` attribute. Work around a bug.\n\n        For more information, see `Bugzilla #1243036\n        <https://bugzilla.redhat.com/show_bug.cgi?id=1243036>`_."
  },
  {
    "code": "def profiles():\n    paths = []\n    for pattern in PROFILES:\n        pattern = os.path.expanduser(pattern)\n        paths += glob(pattern)\n    return paths",
    "docstring": "List of all the connection profile files, ordered by preference.\n\n    :returns: list of all Koji client config files. Example:\n              ['/home/kdreyer/.koji/config.d/kojidev.conf',\n               '/etc/koji.conf.d/stg.conf',\n               '/etc/koji.conf.d/fedora.conf']"
  },
  {
    "code": "def ids2tokens(token_ids: Iterable[int],\n               vocab_inv: Dict[int, str],\n               exclude_set: Set[int]) -> Iterator[str]:\n    tokens = (vocab_inv[token] for token in token_ids)\n    return (tok for token_id, tok in zip(token_ids, tokens) if token_id not in exclude_set)",
    "docstring": "Transforms a list of token IDs into a list of words, excluding any IDs in `exclude_set`.\n\n    :param token_ids: The list of token IDs.\n    :param vocab_inv: The inverse vocabulary.\n    :param exclude_set: The list of token IDs to exclude.\n    :return: The list of words."
  },
  {
    "code": "def synchronizer_class(self):\n        if not self.synchronizer_path or self.synchronizer_path == 'None' or not self.layer:\n            return False\n        if (self._synchronizer_class is not None and self._synchronizer_class.__name__ not in self.synchronizer_path):\n            self._synchronizer = None\n            self._synchronizer_class = None\n        if not self._synchronizer_class:\n            self._synchronizer_class = import_by_path(self.synchronizer_path)\n        return self._synchronizer_class",
    "docstring": "returns synchronizer class"
  },
  {
    "code": "def _fmt(self, tag, msg):\n        msg = msg or '<unset>'\n        msg = str(msg)\n        msg = msg.strip()\n        if not msg:\n            return\n        if len(msg) > 2048:\n            msg = msg[:1024] + '...'\n        if msg.count('\\n') <= 1:\n            return '{}: {}\\n'.format(tag, msg.strip())\n        else:\n            return '{}:\\n  {}\\n'.format(tag, msg.replace('\\n', '\\n  ').strip())",
    "docstring": "Format a string for inclusion in the exception's string representation.\n\n        If msg is None, format to empty string. If msg has a single line, format to:\n        tag: msg If msg has multiple lines, format to: tag:   line 1   line 2 Msg is\n        truncated to 1024 chars."
  },
  {
    "code": "def from_pypirc(pypi_repository):\n    ret = {}\n    pypirc_locations = PYPIRC_LOCATIONS\n    for pypirc_path in pypirc_locations:\n        pypirc_path = os.path.expanduser(pypirc_path)\n        if os.path.isfile(pypirc_path):\n            parser = configparser.SafeConfigParser()\n            parser.read(pypirc_path)\n            if 'distutils' not in parser.sections():\n                continue\n            if 'index-servers' not in parser.options('distutils'):\n                continue\n            if pypi_repository not in parser.get('distutils', 'index-servers'):\n                continue\n            if pypi_repository in parser.sections():\n                for option in parser.options(pypi_repository):\n                    ret[option] = parser.get(pypi_repository, option)\n    if not ret:\n        raise ConfigError(\n            'repository does not appear to be configured in pypirc ({})'.format(pypi_repository) +\n            ', remember that it needs an entry in [distutils] and its own section'\n        )\n    return ret",
    "docstring": "Load configuration from .pypirc file, cached to only run once"
  },
  {
    "code": "def create_subvariant (self, root_targets, all_targets,\n                           build_request, sources,\n                           rproperties, usage_requirements):\n        assert is_iterable_typed(root_targets, virtual_target.VirtualTarget)\n        assert is_iterable_typed(all_targets, virtual_target.VirtualTarget)\n        assert isinstance(build_request, property_set.PropertySet)\n        assert is_iterable_typed(sources, virtual_target.VirtualTarget)\n        assert isinstance(rproperties, property_set.PropertySet)\n        assert isinstance(usage_requirements, property_set.PropertySet)\n        for e in root_targets:\n            e.root (True)\n        s = Subvariant (self, build_request, sources,\n                        rproperties, usage_requirements, all_targets)\n        for v in all_targets:\n            if not v.creating_subvariant():\n                v.creating_subvariant(s)\n        return s",
    "docstring": "Creates a new subvariant-dg instances for 'targets'\n         - 'root-targets' the virtual targets will be returned to dependents\n         - 'all-targets' all virtual\n              targets created while building this main target\n         - 'build-request' is property-set instance with\n         requested build properties"
  },
  {
    "code": "def start(cls, ev):\n        ev.stopPropagation()\n        ev.preventDefault()\n        author = cls.input_el.value.strip()\n        if not author:\n            cls.input_el.style.border = \"2px solid red\"\n            return\n        cls.hide_errors()\n        AuthorBar.show(50)\n        make_request(\n            url=join(settings.API_PATH, \"aleph/authors_by_name\"),\n            data={\"name\": author},\n            on_complete=cls.on_complete\n        )",
    "docstring": "Event handler which starts the request to REST API."
  },
  {
    "code": "def create_handler(target: str):\n    if target == 'stderr':\n        return logging.StreamHandler(sys.stderr)\n    elif target == 'stdout':\n        return logging.StreamHandler(sys.stdout)\n    else:\n        return logging.handlers.WatchedFileHandler(filename=target)",
    "docstring": "Create a handler for logging to ``target``"
  },
  {
    "code": "def main():\n    args = parser.parse_args()\n    try:\n        function = args.func\n    except AttributeError:\n        parser.print_usage()\n        parser.exit(1)\n    function(vars(args))",
    "docstring": "Parse the args and call whatever function was selected"
  },
  {
    "code": "def minimize(self, loss_fn, x, optim_state):\n    grads = self._compute_gradients(loss_fn, x, optim_state)\n    return self._apply_gradients(grads, x, optim_state)",
    "docstring": "Analogous to tf.Optimizer.minimize\n\n    :param loss_fn: tf Tensor, representing the loss to minimize\n    :param x: list of Tensor, analogous to tf.Optimizer's var_list\n    :param optim_state: A possibly nested dict, containing any optimizer state.\n\n    Returns:\n      new_x: list of Tensor, updated version of `x`\n      new_optim_state: dict, updated version of `optim_state`"
  },
  {
    "code": "def same_notebook_code(nb1, nb2):\n    if len(nb1['cells']) != len(nb2['cells']):\n        return False\n    for n in range(len(nb1['cells'])):\n        if nb1['cells'][n]['cell_type'] != nb2['cells'][n]['cell_type']:\n            return False\n        if nb1['cells'][n]['cell_type'] == 'code' and \\\n                nb1['cells'][n]['source'] != nb2['cells'][n]['source']:\n            return False\n    return True",
    "docstring": "Return true of the code cells of notebook objects `nb1` and `nb2`\n    are the same."
  },
  {
    "code": "def get_a_satellite_link(sat_type, sat_dict):\n        cls = get_alignak_class('alignak.objects.%slink.%sLink' % (sat_type, sat_type.capitalize()))\n        return cls(params=sat_dict, parsing=False)",
    "docstring": "Get a SatelliteLink object for a given satellite type and a dictionary\n\n        :param sat_type: type of satellite\n        :param sat_dict: satellite configuration data\n        :return:"
  },
  {
    "code": "def get_correlations(self, chain=0, parameters=None):\n        parameters, cov = self.get_covariance(chain=chain, parameters=parameters)\n        diag = np.sqrt(np.diag(cov))\n        divisor = diag[None, :] * diag[:, None]\n        correlations = cov / divisor\n        return parameters, correlations",
    "docstring": "Takes a chain and returns the correlation between chain parameters.\n\n        Parameters\n        ----------\n        chain : int|str, optional\n            The chain index or name. Defaults to first chain.\n        parameters : list[str], optional\n            The list of parameters to compute correlations. Defaults to all parameters\n            for the given chain.\n\n        Returns\n        -------\n            tuple\n                The first index giving a list of parameter names, the second index being the\n                2D correlation matrix."
  },
  {
    "code": "def validate(ref_intervals, ref_pitches, est_intervals, est_pitches):\n    validate_intervals(ref_intervals, est_intervals)\n    if not ref_intervals.shape[0] == ref_pitches.shape[0]:\n        raise ValueError('Reference intervals and pitches have different '\n                         'lengths.')\n    if not est_intervals.shape[0] == est_pitches.shape[0]:\n        raise ValueError('Estimated intervals and pitches have different '\n                         'lengths.')\n    if ref_pitches.size > 0 and np.min(ref_pitches) <= 0:\n        raise ValueError(\"Reference contains at least one non-positive pitch \"\n                         \"value\")\n    if est_pitches.size > 0 and np.min(est_pitches) <= 0:\n        raise ValueError(\"Estimate contains at least one non-positive pitch \"\n                         \"value\")",
    "docstring": "Checks that the input annotations to a metric look like time intervals\n    and a pitch list, and throws helpful errors if not.\n\n    Parameters\n    ----------\n    ref_intervals : np.ndarray, shape=(n,2)\n        Array of reference notes time intervals (onset and offset times)\n    ref_pitches : np.ndarray, shape=(n,)\n        Array of reference pitch values in Hertz\n    est_intervals : np.ndarray, shape=(m,2)\n        Array of estimated notes time intervals (onset and offset times)\n    est_pitches : np.ndarray, shape=(m,)\n        Array of estimated pitch values in Hertz"
  },
  {
    "code": "def sct_report_string(report):\n    ret = []\n    namespaces = {\"svrl\": \"http://purl.oclc.org/dsdl/svrl\"}\n    for index, failed_assert_el in enumerate(\n        report.findall(\"svrl:failed-assert\", namespaces=namespaces)\n    ):\n        ret.append(\n            \"{}. {}\".format(\n                index + 1,\n                failed_assert_el.find(\"svrl:text\", namespaces=namespaces).text,\n            )\n        )\n        ret.append(\"   test: {}\".format(failed_assert_el.attrib[\"test\"]))\n        ret.append(\"   location: {}\".format(failed_assert_el.attrib[\"location\"]))\n        ret.append(\"\\n\")\n    return \"\\n\".join(ret)",
    "docstring": "Return a human-readable string representation of the error report\n    returned by lxml's schematron validator."
  },
  {
    "code": "def reset_parameters(self):\n        stdv = 1.0 / math.sqrt(self.num_features)\n        self.weight.weight.data.uniform_(-stdv, stdv)\n        if self.bias is not None:\n            self.bias.data.uniform_(-stdv, stdv)\n        if self.padding_idx is not None:\n            self.weight.weight.data[self.padding_idx].fill_(0)",
    "docstring": "Reinitiate the weight parameters."
  },
  {
    "code": "def _handle_request_error(self, orig_request, error, start_response):\n    headers = [('Content-Type', 'application/json')]\n    status_code = error.status_code()\n    body = error.rest_error()\n    response_status = '%d %s' % (status_code,\n                                 httplib.responses.get(status_code,\n                                                       'Unknown Error'))\n    cors_handler = self._create_cors_handler(orig_request)\n    return util.send_wsgi_response(response_status, headers, body,\n                                   start_response, cors_handler=cors_handler)",
    "docstring": "Handle a request error, converting it to a WSGI response.\n\n    Args:\n      orig_request: An ApiRequest, the original request from the user.\n      error: A RequestError containing information about the error.\n      start_response: A function with semantics defined in PEP-333.\n\n    Returns:\n      A string containing the response body."
  },
  {
    "code": "def send(self, cmd):\n        self._bridge.send(cmd, wait=self.wait, reps=self.reps)",
    "docstring": "Send a command to the bridge.\n\n        :param cmd: List of command bytes."
  },
  {
    "code": "def modules_directory():\n    return os.path.join(os.path.dirname(os.path.abspath(__file__)), \"modules\")",
    "docstring": "Get the core modules directory."
  },
  {
    "code": "def hide(self):\n        thr_is_alive = self._spin_thread and self._spin_thread.is_alive()\n        if thr_is_alive and not self._hide_spin.is_set():\n            self._hide_spin.set()\n            sys.stdout.write(\"\\r\")\n            self._clear_line()\n            sys.stdout.flush()",
    "docstring": "Hide the spinner to allow for custom writing to the terminal."
  },
  {
    "code": "def load(self):\n        if self._modules_loaded is True:\n            return\n        self.load_modules_from_python(routes.ALL_ROUTES)\n        self.aliases.update(routes.ALL_ALIASES)\n        self._load_modules_from_entry_points('softlayer.cli')\n        self._modules_loaded = True",
    "docstring": "Loads all modules."
  },
  {
    "code": "def add_query_occurrence(self, report):\n        initial_millis = int(report['parsed']['stats']['millis'])\n        mask = report['queryMask']\n        existing_report = self._get_existing_report(mask, report)\n        if existing_report is not None:\n            self._merge_report(existing_report, report)\n        else:\n            time = None\n            if 'ts' in report['parsed']:\n                time = report['parsed']['ts']\n            self._reports.append(OrderedDict([\n                ('namespace', report['namespace']),\n                ('lastSeenDate', time),\n                ('queryMask', mask),\n                ('supported', report['queryAnalysis']['supported']),\n                ('indexStatus', report['indexStatus']),\n                ('recommendation', report['recommendation']),\n                ('stats', OrderedDict([('count', 1),\n                                       ('totalTimeMillis', initial_millis),\n                                       ('avgTimeMillis', initial_millis)]))]))",
    "docstring": "Adds a report to the report aggregation"
  },
  {
    "code": "def get_any_node(self, addr):\n        for n in self.graph.nodes():\n            if n.addr == addr:\n                return n",
    "docstring": "Get any VFG node corresponding to the basic block at @addr.\n        Note that depending on the context sensitivity level, there might be\n        multiple nodes corresponding to different contexts. This function will\n        return the first one it encounters, which might not be what you want."
  },
  {
    "code": "def resolve(self, pubID, sysID):\n        ret = libxml2mod.xmlACatalogResolve(self._o, pubID, sysID)\n        return ret",
    "docstring": "Do a complete resolution lookup of an External Identifier"
  },
  {
    "code": "def format_keyword(keyword):\n    import re\n    result = ''\n    if keyword:\n        result = re.sub(r\"\\W\", \"\", keyword)\n        result = re.sub(\"_\", \"\", result)\n    return result",
    "docstring": "Removing special character from a keyword. Analysis Services must have\n    this kind of keywords. E.g. if assay name from the Instrument is\n    'HIV-1 2.0', an AS must be created on Bika with the keyword 'HIV120'"
  },
  {
    "code": "def load_statements(fname, as_dict=False):\n    logger.info('Loading %s...' % fname)\n    with open(fname, 'rb') as fh:\n        if sys.version_info[0] < 3:\n            stmts = pickle.load(fh)\n        else:\n            stmts = pickle.load(fh, encoding='latin1')\n    if isinstance(stmts, dict):\n        if as_dict:\n            return stmts\n        st = []\n        for pmid, st_list in stmts.items():\n            st += st_list\n        stmts = st\n    logger.info('Loaded %d statements' % len(stmts))\n    return stmts",
    "docstring": "Load statements from a pickle file.\n\n    Parameters\n    ----------\n    fname : str\n        The name of the pickle file to load statements from.\n    as_dict : Optional[bool]\n        If True and the pickle file contains a dictionary of statements, it\n        is returned as a dictionary. If False, the statements are always\n        returned in a list. Default: False\n\n    Returns\n    -------\n    stmts : list\n        A list or dict of statements that were loaded."
  },
  {
    "code": "def match_var(self, tokens, item):\n        setvar, = tokens\n        if setvar != wildcard:\n            if setvar in self.names:\n                self.add_check(self.names[setvar] + \" == \" + item)\n            else:\n                self.add_def(setvar + \" = \" + item)\n                self.names[setvar] = item",
    "docstring": "Matches a variable."
  },
  {
    "code": "def metric_tensor(self) -> np.ndarray:\n        return dot(self._matrix, self._matrix.T)",
    "docstring": "The metric tensor of the lattice."
  },
  {
    "code": "def builds(self, request, pk=None):\n        builds = self.get_object().builds.prefetch_related('test_runs').order_by('-datetime')\n        page = self.paginate_queryset(builds)\n        serializer = BuildSerializer(page, many=True, context={'request': request})\n        return self.get_paginated_response(serializer.data)",
    "docstring": "List of builds for the current project."
  },
  {
    "code": "def cont_cat_split(df, max_card=20, dep_var=None)->Tuple[List,List]:\n    \"Helper function that returns column names of cont and cat variables from given df.\"\n    cont_names, cat_names = [], []\n    for label in df:\n        if label == dep_var: continue\n        if df[label].dtype == int and df[label].unique().shape[0] > max_card or df[label].dtype == float: cont_names.append(label)\n        else: cat_names.append(label)\n    return cont_names, cat_names",
    "docstring": "Helper function that returns column names of cont and cat variables from given df."
  },
  {
    "code": "def _dump_spec(spec):\n    with open(\"spec.yaml\", \"w\") as f:\n        yaml.dump(spec, f, Dumper=MyDumper, default_flow_style=False)",
    "docstring": "Dump bel specification dictionary using YAML\n\n    Formats this with an extra indentation for lists to make it easier to\n    use cold folding on the YAML version of the spec dictionary."
  },
  {
    "code": "def get_children_treepos(self, treepos):\n        children_treepos = []\n        for i, child in enumerate(self.dgtree[treepos]):\n            if isinstance(child, nltk.Tree):\n                children_treepos.append(child.treeposition())\n            elif is_leaf(child):\n                treepos_list = list(treepos)\n                treepos_list.append(i)\n                leaf_treepos = tuple(treepos_list)\n                children_treepos.append(leaf_treepos)\n        return children_treepos",
    "docstring": "Given a treeposition, return the treepositions of its children."
  },
  {
    "code": "def get_datacenters(service_instance, datacenter_names=None,\n                    get_all_datacenters=False):\n    items = [i['object'] for i in\n             get_mors_with_properties(service_instance,\n                                      vim.Datacenter,\n                                      property_list=['name'])\n             if get_all_datacenters or\n             (datacenter_names and i['name'] in datacenter_names)]\n    return items",
    "docstring": "Returns all datacenters in a vCenter.\n\n    service_instance\n        The Service Instance Object from which to obtain cluster.\n\n    datacenter_names\n        List of datacenter names to filter by. Default value is None.\n\n    get_all_datacenters\n        Flag specifying whether to retrieve all datacenters.\n        Default value is None."
  },
  {
    "code": "def filepaths_in_dir(path):\n    filepaths = []\n    for root, directories, filenames in os.walk(path):\n        for filename in filenames:\n            filepath = os.path.join(root, filename)\n            filepath = filepath.replace(path, '').lstrip('/')\n            filepaths.append(filepath)\n    return filepaths",
    "docstring": "Find all files in a directory, and return the relative paths to those files.\n\n    Args:\n        path (str): the directory path to walk\n\n    Returns:\n        list: the list of relative paths to all files inside of ``path`` or its\n            subdirectories."
  },
  {
    "code": "def parse_secured_key(secured_key,\n        key_nonce_separator='.',\n        nonce_length=4,\n        base=BASE62):\n    parts = secured_key.split(key_nonce_separator)\n    if len(parts) != 2:\n        raise ValueError('Invalid secured key format')\n    (key, nonce) = parts\n    if len(nonce) != nonce_length:\n        raise ValueError('Invalid length of the key nonce')\n    return key_to_int(key, base=base), key, nonce",
    "docstring": "Parse a given secured key and return its associated integer, the key\n    itself, and the embedded nonce.\n\n    @param secured_key a string representation of a secured key composed\n           of a key in Base62, a separator character, and a nonce.\n\n    @param key_nonce_separator: the character that is used to separate the\n           key and the nonce to form the secured key.\n\n    @param nonce_length: the number of characters to compose the nonce.\n\n    @param base: a sequence of characters that is used to encode the\n           integer value.\n\n    @return: a tuple ``(value, key, nonce)``:\n             * ``value``: the integer value of the key.\n             * ``key``: the plain-text key.\n             * ``nonce``: \"number used once\", a pseudo-random number to\n               ensure that the key cannot be reused in replay attacks.\n\n    @raise ValueError: if the format of the secured key is invalid, or if\n           the embedded nonce is of the wrong length."
  },
  {
    "code": "def handle_target(self, request, controller_args, controller_kwargs):\n        try:\n            param_args, param_kwargs = self.normalize_target_params(\n                request=request,\n                controller_args=controller_args,\n                controller_kwargs=controller_kwargs\n            )\n            ret = self.target(*param_args, **param_kwargs)\n            if not ret:\n                raise ValueError(\"{} check failed\".format(self.__class__.__name__))\n        except CallError:\n            raise\n        except Exception as e:\n            self.handle_error(e)",
    "docstring": "Internal method for this class\n\n        handles normalizing the passed in values from the decorator using\n        .normalize_target_params() and then passes them to the set .target()"
  },
  {
    "code": "def getTopRight(self):\n        return (float(self.get_x()) + float(self.get_width()), float(self.get_y()) + float(self.get_height()))",
    "docstring": "Retrieves a tuple with the x,y coordinates of the upper right point of the rect. \n        Requires the coordinates, width, height to be numbers"
  },
  {
    "code": "def _ask_for_ledger_status(self, node_name: str, ledger_id):\n        self.request_msg(LEDGER_STATUS, {f.LEDGER_ID.nm: ledger_id},\n                         [node_name, ])\n        logger.info(\"{} asking {} for ledger status of ledger {}\".format(self, node_name, ledger_id))",
    "docstring": "Ask other node for LedgerStatus"
  },
  {
    "code": "def do_logStream(self,args):\n        parser = CommandArgumentParser(\"logStream\")\n        parser.add_argument(dest='logStream',help='logStream index.');\n        args = vars(parser.parse_args(args))\n        print \"loading log stream {}\".format(args['logStream'])\n        index = int(args['logStream'])\n        logStream = self.logStreams[index]\n        print \"logStream:{}\".format(logStream)\n        self.childLoop(AwsLogStream.AwsLogStream(logStream,self))",
    "docstring": "Go to the specified log stream. logStream -h for detailed help"
  },
  {
    "code": "def _parse_tile_url(tile_url):\n        props = tile_url.rsplit('/', 7)\n        return ''.join(props[1:4]), '-'.join(props[4:7]), int(props[7])",
    "docstring": "Extracts tile name, data and AWS index from tile URL\n\n        :param tile_url: Location of tile at AWS\n        :type: tile_url: str\n        :return: Tuple in a form (tile_name, date, aws_index)\n        :rtype: (str, str, int)"
  },
  {
    "code": "def get_pelican_cls(settings):\n    cls = settings['PELICAN_CLASS']\n    if isinstance(cls, six.string_types):\n        module, cls_name = cls.rsplit('.', 1)\n        module = __import__(module)\n        cls = getattr(module, cls_name)\n    return cls",
    "docstring": "Get the Pelican class requested in settings"
  },
  {
    "code": "async def createcsrf(self, csrfarg = '_csrf'):\n        await self.sessionstart()\n        if not csrfarg in self.session.vars:\n            self.session.vars[csrfarg] = uuid.uuid4().hex",
    "docstring": "Create a anti-CSRF token in the session"
  },
  {
    "code": "def process_origin(\n        headers: Headers, origins: Optional[Sequence[Optional[Origin]]] = None\n    ) -> Optional[Origin]:\n        try:\n            origin = cast(Origin, headers.get(\"Origin\"))\n        except MultipleValuesError:\n            raise InvalidHeader(\"Origin\", \"more than one Origin header found\")\n        if origins is not None:\n            if origin not in origins:\n                raise InvalidOrigin(origin)\n        return origin",
    "docstring": "Handle the Origin HTTP request header.\n\n        Raise :exc:`~websockets.exceptions.InvalidOrigin` if the origin isn't\n        acceptable."
  },
  {
    "code": "def prepare_jochem(ctx, jochem, output, csoutput):\n    click.echo('chemdataextractor.dict.prepare_jochem')\n    for i, line in enumerate(jochem):\n        print('JC%s' % i)\n        if line.startswith('TM '):\n            if line.endswith('\t@match=ci\\n'):\n                for tokens in _make_tokens(line[3:-11]):\n                    output.write(' '.join(tokens))\n                    output.write('\\n')\n            else:\n                for tokens in _make_tokens(line[3:-1]):\n                    csoutput.write(' '.join(tokens))\n                    csoutput.write('\\n')",
    "docstring": "Process and filter jochem file to produce list of names for dictionary."
  },
  {
    "code": "def clean_whitespace(statement):\n    import re\n    statement.text = statement.text.replace('\\n', ' ').replace('\\r', ' ').replace('\\t', ' ')\n    statement.text = statement.text.strip()\n    statement.text = re.sub(' +', ' ', statement.text)\n    return statement",
    "docstring": "Remove any consecutive whitespace characters from the statement text."
  },
  {
    "code": "def process_json(json_dict):\n    ep = EidosProcessor(json_dict)\n    ep.extract_causal_relations()\n    ep.extract_correlations()\n    ep.extract_events()\n    return ep",
    "docstring": "Return an EidosProcessor by processing a Eidos JSON-LD dict.\n\n    Parameters\n    ----------\n    json_dict : dict\n        The JSON-LD dict to be processed.\n\n    Returns\n    -------\n    ep : EidosProcessor\n        A EidosProcessor containing the extracted INDRA Statements\n        in its statements attribute."
  },
  {
    "code": "def read_unicode(path, encoding, encoding_errors):\n    try:\n      f = open(path, 'rb')\n      return make_unicode(f.read(), encoding, encoding_errors)\n    finally:\n      f.close()",
    "docstring": "Return the contents of a file as a unicode string."
  },
  {
    "code": "def api_submit():\n    data = request.files.file\n    response.content_type = 'application/json'\n    if not data or not hasattr(data, 'file'):\n        return json.dumps({\"status\": \"Failed\", \"stderr\": \"Missing form params\"})\n    return json.dumps(analyse_pcap(data.file, data.filename), default=jsondate, indent=4)",
    "docstring": "Blocking POST handler for file submission.\n    Runs snort on supplied file and returns results as json text."
  },
  {
    "code": "def recalc_M(S, D_cba, Y, nr_sectors):\n    Y_diag = ioutil.diagonalize_blocks(Y.values, blocksize=nr_sectors)\n    Y_inv = np.linalg.inv(Y_diag)\n    M = D_cba.dot(Y_inv)\n    if type(D_cba) is pd.DataFrame:\n        M.columns = D_cba.columns\n        M.index = D_cba.index\n    return M",
    "docstring": "Calculate Multipliers based on footprints.\n\n    Parameters\n    ----------\n    D_cba : pandas.DataFrame or numpy array\n        Footprint per sector and country\n    Y : pandas.DataFrame or numpy array\n        Final demand: aggregated across categories or just one category, one\n        column per country. This will be diagonalized per country block.\n        The diagonolized form must be invertable for this method to work.\n    nr_sectors : int\n        Number of sectors in the MRIO\n\n    Returns\n    -------\n\n    pandas.DataFrame or numpy.array\n        Multipliers M\n        The type is determined by the type of D_cba.\n        If DataFrame index/columns as D_cba"
  },
  {
    "code": "def record(self):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('SL record not yet initialized!')\n        outlist = [b'SL', struct.pack('=BBB', self.current_length(), SU_ENTRY_VERSION, self.flags)]\n        for comp in self.symlink_components:\n            outlist.append(comp.record())\n        return b''.join(outlist)",
    "docstring": "Generate a string representing the Rock Ridge Symbolic Link record.\n\n        Parameters:\n         None.\n        Returns:\n         String containing the Rock Ridge record."
  },
  {
    "code": "def pad_array(in1):\n    padded_size = 2*np.array(in1.shape)\n    out1 = np.zeros([padded_size[0],padded_size[1]])\n    out1[padded_size[0]/4:3*padded_size[0]/4,padded_size[1]/4:3*padded_size[1]/4] = in1\n    return out1",
    "docstring": "Simple convenience function to pad arrays for linear convolution.\n\n    INPUTS:\n    in1     (no default):   Input array which is to be padded.\n\n    OUTPUTS:\n    out1                    Padded version of the input."
  },
  {
    "code": "def is_diff(self):\n        if not isinstance(self.details, dict):\n            return False\n        for key in ['additions', 'updates', 'deletions']:\n            if self.details.get(key, None):\n                return True\n        return False",
    "docstring": "Return True if there are any differences logged"
  },
  {
    "code": "def unpack_archive(*components, **kwargs) -> str:\n    path = fs.abspath(*components)\n    compression = kwargs.get(\"compression\", \"bz2\")\n    dir = kwargs.get(\"dir\", fs.dirname(path))\n    fs.cd(dir)\n    tar = tarfile.open(path, \"r:\" + compression)\n    tar.extractall()\n    tar.close()\n    fs.cdpop()\n    return dir",
    "docstring": "Unpack a compressed archive.\n\n    Arguments:\n        *components (str[]): Absolute path.\n        **kwargs (dict, optional): Set \"compression\" to compression type.\n            Default: bz2. Set \"dir\" to destination directory. Defaults to the\n            directory of the archive.\n\n    Returns:\n        str: Path to directory."
  },
  {
    "code": "def qubo_energy(sample, Q, offset=0.0):\n    for v0, v1 in Q:\n        offset += sample[v0] * sample[v1] * Q[(v0, v1)]\n    return offset",
    "docstring": "Calculate the energy for the specified sample of a QUBO model.\n\n    Energy of a sample for a binary quadratic model is defined as a sum, offset\n    by the constant energy offset associated with the model, of\n    the sample multipled by the linear bias of the variable and\n    all its interactions. For a quadratic unconstrained binary optimization (QUBO)\n    model,\n\n    .. math::\n\n        E(\\mathbf{x}) = \\sum_{u,v} Q_{u,v} x_u x_v + c\n\n    where :math:`x_v` is the sample, :math:`Q_{u,v}`\n    a matrix of biases, and :math:`c` the energy offset.\n\n    Args:\n        sample (dict[variable, spin]):\n            Sample for a binary quadratic model as a dict of form {v: bin, ...},\n            where keys are variables of the model and values are binary (either 0 or 1).\n        Q (dict[(variable, variable), coefficient]):\n            QUBO coefficients in a dict of form {(u, v): coefficient, ...}, where keys\n            are 2-tuples of variables of the model and values are biases\n            associated with the pair of variables. Tuples (u, v) represent interactions\n            and (v, v) linear biases.\n        offset (numeric, optional, default=0):\n            Constant offset to be applied to the energy. Default 0.\n\n    Returns:\n        float: The induced energy.\n\n    Notes:\n        No input checking is performed.\n\n    Examples:\n        This example calculates the energy of a sample representing two zeros for\n        a QUBO model of two variables that have positive biases of value 1 and\n        are positively coupled with an interaction of value 1.\n\n        >>> import dimod\n        >>> sample = {1: 0, 2: 0}\n        >>> Q = {(1, 1): 1, (2, 2): 1, (1, 2): 1}\n        >>> dimod.qubo_energy(sample, Q, 0.5)\n        0.5\n\n    References\n    ----------\n\n    `QUBO model on Wikipedia <https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization>`_"
  },
  {
    "code": "def getCandScoresMap(self, profile):\n        elecType = profile.getElecType()\n        if elecType != \"soc\" and elecType != \"toc\":\n            print(\"ERROR: unsupported election type\")\n            exit()\n        wmg = profile.getWmg()\n        maximinScores = dict()\n        for cand in wmg.keys():\n            maximinScores[cand] = float(\"inf\")\n        for cand1, cand2 in itertools.combinations(wmg.keys(), 2):\n            if cand2 in wmg[cand1].keys():\n                maximinScores[cand1] = min(maximinScores[cand1], wmg[cand1][cand2])\n                maximinScores[cand2] = min(maximinScores[cand2], wmg[cand2][cand1])\n        return maximinScores",
    "docstring": "Returns a dictionary that associates integer representations of each candidate with their\n        maximin score.\n\n        :ivar Profile profile: A Profile object that represents an election profile."
  },
  {
    "code": "def age(self, as_at_date=None):\n        if self.date_of_death != None or self.is_deceased == True:\n            return None\n        as_at_date = date.today() if as_at_date == None else as_at_date\n        if self.date_of_birth != None:\n            if (as_at_date.month >= self.date_of_birth.month) and (as_at_date.day >= self.date_of_birth.day):\n                return (as_at_date.year - self.date_of_birth.year)\n            else:\n                return ((as_at_date.year - self.date_of_birth.year) -1)\n        else:\n            return None",
    "docstring": "Compute the person's age"
  },
  {
    "code": "def get_query_targets(cli_ctx, apps, resource_group):\n    if isinstance(apps, list):\n        if resource_group:\n            return [get_id_from_azure_resource(cli_ctx, apps[0], resource_group)]\n        return list(map(lambda x: get_id_from_azure_resource(cli_ctx, x), apps))\n    else:\n        if resource_group:\n            return [get_id_from_azure_resource(cli_ctx, apps, resource_group)]\n        return apps",
    "docstring": "Produces a list of uniform GUIDs representing applications to query."
  },
  {
    "code": "def put_bits( self, value, count ):\n        for _ in range( count ):\n            bit = (value & 1)\n            value >>= 1\n            if self.bits_reverse:\n                if self.insert_at_msb:\n                    self.current_bits |= (bit << (self.bits_remaining-1))\n                else:\n                    self.current_bits <<= 1\n                    self.current_bits |= bit\n            else:\n                if self.insert_at_msb:\n                    self.current_bits >>= 1\n                    self.current_bits |= (bit << 7)\n                else:\n                    self.current_bits |= (bit << (8-self.bits_remaining))\n            self.bits_remaining -= 1\n            if self.bits_remaining <= 0:\n                self.output.append( self.current_bits )\n                self.current_bits = 0\n                self.bits_remaining = 8",
    "docstring": "Push bits into the target.\n\n        value\n            Integer containing bits to push, ordered from least-significant bit to\n            most-significant bit.\n\n        count\n            Number of bits to push to the target."
  },
  {
    "code": "def wait_for(self, event, predicate, result=None):\n        future = self.loop.create_future()\n        entry = EventListener(event=event, predicate=predicate, result=result, future=future)\n        self._dispatch_listeners.append(entry)\n        return future",
    "docstring": "Waits for a DISPATCH'd event that meets the predicate.\n\n        Parameters\n        -----------\n        event: :class:`str`\n            The event name in all upper case to wait for.\n        predicate\n            A function that takes a data parameter to check for event\n            properties. The data parameter is the 'd' key in the JSON message.\n        result\n            A function that takes the same data parameter and executes to send\n            the result to the future. If None, returns the data.\n\n        Returns\n        --------\n        asyncio.Future\n            A future to wait for."
  },
  {
    "code": "def merge_pdfs(pdf_names, output) -> None:\n    merger = PyPDF2.PdfFileMerger()\n    for filename in pdf_names:\n        merger.append(filename)\n    merger.write(output)\n    merger.close()",
    "docstring": "Merges all pdfs together into a single long PDF."
  },
  {
    "code": "def load_public_key(vm_):\n    public_key_filename = config.get_cloud_config_value(\n        'ssh_public_key', vm_, __opts__, search_global=False, default=None\n    )\n    if public_key_filename is not None:\n        public_key_filename = os.path.expanduser(public_key_filename)\n        if not os.path.isfile(public_key_filename):\n            raise SaltCloudConfigError(\n                'The defined ssh_public_key \\'{0}\\' does not exist'.format(\n                    public_key_filename\n                )\n            )\n        with salt.utils.files.fopen(public_key_filename, 'r') as public_key:\n            key = salt.utils.stringutils.to_unicode(public_key.read().replace('\\n', ''))\n            return key",
    "docstring": "Load the public key file if exists."
  },
  {
    "code": "def _dict_to_name_value(data):\n    if isinstance(data, dict):\n        sorted_data = sorted(data.items(), key=lambda s: s[0])\n        result = []\n        for name, value in sorted_data:\n            if isinstance(value, dict):\n                result.append({name: _dict_to_name_value(value)})\n            else:\n                result.append({name: value})\n    else:\n        result = data\n    return result",
    "docstring": "Convert a dictionary to a list of dictionaries to facilitate ordering"
  },
  {
    "code": "def print_access(access, title):\n    columns = ['id', 'hostname', 'Primary Public IP', 'Primary Private IP', 'Created']\n    table = formatting.Table(columns, title)\n    for host in access:\n        host_id = host.get('id')\n        host_fqdn = host.get('fullyQualifiedDomainName', '-')\n        host_primary = host.get('primaryIpAddress')\n        host_private = host.get('primaryBackendIpAddress')\n        host_created = host.get('provisionDate')\n        table.add_row([host_id, host_fqdn, host_primary, host_private, host_created])\n    return table",
    "docstring": "Prints out the hardware or virtual guests a user can access"
  },
  {
    "code": "def now_heating(self):\n        try:\n            if self.side == 'left':\n                heat = self.device.device_data['leftNowHeating']\n            elif self.side == 'right':\n                heat = self.device.device_data['rightNowHeating']\n            return heat\n        except TypeError:\n            return None",
    "docstring": "Return current heating state."
  },
  {
    "code": "def process_iter(proc, cmd=\"\"):\n    try:\n        for l in proc.stdout:\n            yield l\n    finally:\n        if proc.poll() is None:\n            return\n        else:\n            proc.wait()\n            if proc.returncode not in (0, None, signal.SIGPIPE, signal.SIGPIPE + 128):\n                sys.stderr.write(\"cmd was:%s\\n\" % cmd)\n                sys.stderr.write(\"return code was:%s\\n\" % proc.returncode)\n                raise ProcessException(cmd)",
    "docstring": "helper function to iterate over a process stdout\n    and report error messages when done"
  },
  {
    "code": "def files_comments_edit(\n        self, *, comment: str, file: str, id: str, **kwargs\n    ) -> SlackResponse:\n        kwargs.update({\"comment\": comment, \"file\": file, \"id\": id})\n        return self.api_call(\"files.comments.edit\", json=kwargs)",
    "docstring": "Edit an existing file comment.\n\n        Args:\n            comment (str): The body of the comment.\n                e.g. 'Everyone should take a moment to read this file.'\n            file (str): The file id. e.g. 'F1234467890'\n            id (str): The file comment id. e.g. 'Fc1234567890'"
  },
  {
    "code": "def show_files(md5):\n    if not WORKBENCH:\n        return flask.redirect('/')\n    md5_view = WORKBENCH.work_request('view', md5)\n    return flask.render_template('templates/md5_view.html', md5_view=md5_view['view'], md5=md5)",
    "docstring": "Renders template with `view` of the md5."
  },
  {
    "code": "def send_direct_message(self, text, user=None, delegate=None, screen_name=None, user_id=None, params={}):\n        params = params.copy()\n        if user is not None:\n            params['user'] = user\n        if user_id is not None:\n            params['user_id'] = user_id\n        if screen_name is not None:\n            params['screen_name'] = screen_name\n        params['text'] = text\n        parser = txml.Direct(delegate)\n        return self.__postPage('/direct_messages/new.xml', parser, params)",
    "docstring": "Send a direct message"
  },
  {
    "code": "def get_if_present(self, name, default=None):\n        if not self.processed_data:\n            raise exceptions.FormNotProcessed('The form data has not been processed yet')\n        if name in self.field_dict:\n            return self[name]\n        return default",
    "docstring": "Returns the value for a field, but if the field doesn't exist will return default instead"
  },
  {
    "code": "def remove_sshkey(host, known_hosts=None):\n    if known_hosts is None:\n        if 'HOME' in os.environ:\n            known_hosts = '{0}/.ssh/known_hosts'.format(os.environ['HOME'])\n        else:\n            try:\n                known_hosts = '{0}/.ssh/known_hosts'.format(\n                    pwd.getpwuid(os.getuid()).pwd_dir\n                )\n            except Exception:\n                pass\n    if known_hosts is not None:\n        log.debug(\n            'Removing ssh key for %s from known hosts file %s',\n            host, known_hosts\n        )\n    else:\n        log.debug('Removing ssh key for %s from known hosts file', host)\n    cmd = 'ssh-keygen -R {0}'.format(host)\n    subprocess.call(cmd, shell=True)",
    "docstring": "Remove a host from the known_hosts file"
  },
  {
    "code": "def validate_capacity(capacity):\n    if capacity not in VALID_SCALING_CONFIGURATION_CAPACITIES:\n        raise ValueError(\n            \"ScalingConfiguration capacity must be one of: {}\".format(\n                \", \".join(map(\n                    str,\n                    VALID_SCALING_CONFIGURATION_CAPACITIES\n                ))\n            )\n        )\n    return capacity",
    "docstring": "Validate ScalingConfiguration capacity for serverless DBCluster"
  },
  {
    "code": "def getdminfo(self, columnname=None):\n        dminfo = self._getdminfo()\n        if columnname is None:\n            return dminfo\n        for fld in dminfo.values():\n            if columnname in fld[\"COLUMNS\"]:\n                fldc = fld.copy()\n                del fldc['COLUMNS']\n                return fldc\n        raise KeyError(\"Column \" + columnname + \" does not exist\")",
    "docstring": "Get data manager info.\n\n        Each column in a table is stored using a data manager. A storage\n        manager is a data manager storing the physically in a file.\n        A virtual column engine is a data manager that does not store data\n        but calculates it on the fly (e.g. scaling floats to short to\n        reduce storage needs).\n\n        By default this method returns a dict telling the data managers used.\n        Each field in the dict is a dict containing:\n\n        - NAME telling the (unique) name of the data manager\n        - TYPE telling the type of data manager (e.g. TiledShapeStMan)\n        - SEQNR telling the sequence number of the data manager\n          (is ''i'' in table.f<i> for storage managers)\n        - SPEC is a dict holding the data manager specification\n        - COLUMNS is a list giving the columns stored by this data manager\n\n        When giving a column name the data manager info of that particular\n        column is returned (without the COLUMNS field).\n        It can, for instance, be used when adding a column using\n        :func:`addcols` that should use the same data manager type as an\n        existing column. However, when doing that care should be taken to\n        change the NAME because each data manager name has to be unique."
  },
  {
    "code": "def _post(self, xml_query):\n        req = urllib2.Request(url = 'http://www.rcsb.org/pdb/rest/search', data=xml_query)\n        f = urllib2.urlopen(req)\n        return f.read().strip()",
    "docstring": "POST the request."
  },
  {
    "code": "def get_header_example(cls, header):\n        if header.is_array:\n            result = cls.get_example_for_array(header.item)\n        else:\n            example_method = getattr(cls, '{}_example'.format(header.type))\n            result = example_method(header.properties, header.type_format)\n        return {header.name: result}",
    "docstring": "Get example for header object\n\n        :param Header header: Header object\n        :return: example\n        :rtype: dict"
  },
  {
    "code": "def check_command(self, op_description, op=None, data=b'', chk=0, timeout=DEFAULT_TIMEOUT):\n        val, data = self.command(op, data, chk, timeout=timeout)\n        if len(data) < self.STATUS_BYTES_LENGTH:\n            raise FatalError(\"Failed to %s. Only got %d byte status response.\" % (op_description, len(data)))\n        status_bytes = data[-self.STATUS_BYTES_LENGTH:]\n        if byte(status_bytes, 0) != 0:\n            raise FatalError.WithResult('Failed to %s' % op_description, status_bytes)\n        if len(data) > self.STATUS_BYTES_LENGTH:\n            return data[:-self.STATUS_BYTES_LENGTH]\n        else:\n            return val",
    "docstring": "Execute a command with 'command', check the result code and throw an appropriate\n        FatalError if it fails.\n\n        Returns the \"result\" of a successful command."
  },
  {
    "code": "def new(namespace, name, wdl, synopsis,\n            documentation=None, api_url=fapi.PROD_API_ROOT):\n        r = fapi.update_workflow(namespace, name, synopsis,\n                                 wdl, documentation, api_url)\n        fapi._check_response_code(r, 201)\n        d = r.json()\n        return Method(namespace, name, d[\"snapshotId\"])",
    "docstring": "Create new FireCloud method.\n\n        If the namespace + name already exists, a new snapshot is created.\n\n        Args:\n            namespace (str): Method namespace for this method\n            name (str): Method name\n            wdl (file): WDL description\n            synopsis (str): Short description of task\n            documentation (file): Extra documentation for method"
  },
  {
    "code": "def get_unread_forums_from_list(self, forums, user):\n        unread_forums = []\n        visibility_contents = ForumVisibilityContentTree.from_forums(forums)\n        forum_ids_to_visibility_nodes = visibility_contents.as_dict\n        tracks = super().get_queryset().select_related('forum').filter(\n            user=user,\n            forum__in=forums)\n        tracked_forums = []\n        for track in tracks:\n            forum_last_post_on = forum_ids_to_visibility_nodes[track.forum_id].last_post_on\n            if (forum_last_post_on and track.mark_time < forum_last_post_on) \\\n                    and track.forum not in unread_forums:\n                unread_forums.extend(track.forum.get_ancestors(include_self=True))\n            tracked_forums.append(track.forum)\n        for forum in forums:\n            if forum not in tracked_forums and forum not in unread_forums \\\n                    and forum.direct_topics_count > 0:\n                unread_forums.extend(forum.get_ancestors(include_self=True))\n        return list(set(unread_forums))",
    "docstring": "Filter a list of forums and return only those which are unread.\n\n        Given a list of forums find and returns the list of forums that are unread for the passed\n        user. If a forum is unread all of its ancestors are also unread and will be included in the\n        final list."
  },
  {
    "code": "def format_config(sensor_graph):\n    cmdfile = CommandFile(\"Config Variables\", \"1.0\")\n    for slot in sorted(sensor_graph.config_database, key=lambda x: x.encode()):\n        for conf_var, conf_def in sorted(sensor_graph.config_database[slot].items()):\n            conf_type, conf_val = conf_def\n            if conf_type == 'binary':\n                conf_val = 'hex:' + hexlify(conf_val)\n            cmdfile.add(\"set_variable\", slot, conf_var, conf_type, conf_val)\n    return cmdfile.dump()",
    "docstring": "Extract the config variables from this sensor graph in ASCII format.\n\n    Args:\n        sensor_graph (SensorGraph): the sensor graph that we want to format\n\n    Returns:\n        str: The ascii output lines concatenated as a single string"
  },
  {
    "code": "def _is_request_in_exclude_path(self, request):\n        if self._exclude_paths:\n            for path in self._exclude_paths:\n                if request.path.startswith(path):\n                    return True\n            return False\n        else:\n            return False",
    "docstring": "Check if the request path is in the `_exclude_paths` list"
  },
  {
    "code": "def addmag(self, magval):\n        if N.isscalar(magval):\n            factor = 10**(-0.4*magval)\n            return self*factor\n        else:\n            raise TypeError(\".addmag() only takes a constant scalar argument\")",
    "docstring": "Add a scalar magnitude to existing flux values.\n\n        .. math::\n\n            \\\\textnormal{flux}_{\\\\textnormal{new}} = 10^{-0.4 \\\\; \\\\textnormal{magval}} \\\\; \\\\textnormal{flux}\n\n        Parameters\n        ----------\n        magval : number\n            Magnitude value.\n\n        Returns\n        -------\n        sp : `CompositeSourceSpectrum`\n            New source spectrum with adjusted flux values.\n\n        Raises\n        ------\n        TypeError\n            Magnitude value is not a scalar number."
  },
  {
    "code": "def prep_args(arg_info):\n    filtered_args = [a for a in arg_info.args if getattr(arg_info, 'varargs', None) != a]\n    if filtered_args and (filtered_args[0] in ('self', 'cls')):\n        filtered_args = filtered_args[1:]\n    pos_args = []\n    if filtered_args:\n        for arg in filtered_args:\n            if isinstance(arg, str) and arg in arg_info.locals:\n                resolved_type = resolve_type(arg_info.locals[arg])\n                pos_args.append(resolved_type)\n            else:\n                pos_args.append(type(UnknownType()))\n    varargs = None\n    if arg_info.varargs:\n        varargs_tuple = arg_info.locals[arg_info.varargs]\n        if isinstance(varargs_tuple, tuple):\n            varargs = [resolve_type(arg) for arg in varargs_tuple[:4]]\n    return ResolvedTypes(pos_args=pos_args, varargs=varargs)",
    "docstring": "Resolve types from ArgInfo"
  },
  {
    "code": "def signed_headers(self):\n        signed_headers = self.query_parameters.get(_x_amz_signedheaders)\n        if signed_headers is not None:\n            signed_headers = url_unquote(signed_headers[0])\n        else:\n            signed_headers = self.authorization_header_parameters[\n                _signedheaders]\n        parts = signed_headers.split(\";\")\n        canonicalized = sorted([sh.lower() for sh in parts])\n        if parts != canonicalized:\n            raise AttributeError(\"SignedHeaders is not canonicalized: %r\" %\n                                 (signed_headers,))\n        return OrderedDict([(header, self.headers[header])\n                            for header in signed_headers.split(\";\")])",
    "docstring": "An ordered dictionary containing the signed header names and values."
  },
  {
    "code": "def _ReadUnionDataTypeDefinition(\n      self, definitions_registry, definition_values, definition_name,\n      is_member=False):\n    return self._ReadDataTypeDefinitionWithMembers(\n        definitions_registry, definition_values, data_types.UnionDefinition,\n        definition_name, supports_conditions=False)",
    "docstring": "Reads an union data type definition.\n\n    Args:\n      definitions_registry (DataTypeDefinitionsRegistry): data type definitions\n          registry.\n      definition_values (dict[str, object]): definition values.\n      definition_name (str): name of the definition.\n      is_member (Optional[bool]): True if the data type definition is a member\n          data type definition.\n\n    Returns:\n      UnionDefinition: union data type definition.\n\n    Raises:\n      DefinitionReaderError: if the definitions values are missing or if\n          the format is incorrect."
  },
  {
    "code": "def choose_candidate_pair(candidates):\n        highscored = sorted(candidates, key=candidates.get, reverse=True)\n        for i, h_i in enumerate(highscored):\n            for h_j in highscored[i+1:]:\n                if len(h_i) == len(h_j):\n                    yield (h_i, h_j)",
    "docstring": "Choose a pair of address candidates ensuring they have the same length and starting with the highest scored ones\n\n        :type candidates: dict[str, int]\n        :param candidates: Count how often the longest common substrings appeared in the messages\n        :return:"
  },
  {
    "code": "def _key_name(self):\n        if self._key is not None:\n            return self._key\n        return self.__class__.__name__.lower()",
    "docstring": "Return the key referring to this object\n\n        The default value is the lower case version of the class name\n\n        :rtype: str"
  },
  {
    "code": "def aloha_to_html(html_source):\n    xml = aloha_to_etree(html_source)\n    return etree.tostring(xml, pretty_print=True)",
    "docstring": "Converts HTML5 from Aloha to a more structured HTML5"
  },
  {
    "code": "def unzip_file(filename):\n    if filename.endswith('bz2'):\n        bz2file = bz2.BZ2File(filename)\n        fdn, tmpfilepath = tempfile.mkstemp()\n        with closing(os.fdopen(fdn, 'wb')) as ofpt:\n            try:\n                ofpt.write(bz2file.read())\n            except IOError:\n                import traceback\n                traceback.print_exc()\n                LOGGER.info(\"Failed to read bzipped file %s\", str(filename))\n                os.remove(tmpfilepath)\n                return None\n        return tmpfilepath\n    return None",
    "docstring": "Unzip the file if file is bzipped = ending with 'bz2"
  },
  {
    "code": "def list_vm_images_sub(access_token, subscription_id):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/providers/Microsoft.Compute/images',\n                        '?api-version=', COMP_API])\n    return do_get_next(endpoint, access_token)",
    "docstring": "List VM images in a subscription.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n\n    Returns:\n        HTTP response. JSON body of a list of VM images."
  },
  {
    "code": "def get_attribute_at(config, target_path, key, default_value=None):\n    for target in target_path:\n        config = config[target]\n    return config[key] if key in config else default_value",
    "docstring": "Return attribute value at a given path\n\n    :param config:\n    :param target_path:\n    :param key:\n    :param default_value:\n    :return:"
  },
  {
    "code": "def update_dcnm_partition_static_route(self, tenant_id, arg_dict):\n        ip_list = self.os_helper.get_subnet_nwk_excl(tenant_id,\n                                                     arg_dict.get('excl_list'))\n        srvc_node_ip = self.get_out_srvc_node_ip_addr(tenant_id)\n        ret = self.dcnm_obj.update_partition_static_route(\n            arg_dict.get('tenant_name'), fw_const.SERV_PART_NAME, ip_list,\n            vrf_prof=self.cfg.firewall.fw_service_part_vrf_profile,\n            service_node_ip=srvc_node_ip)\n        if not ret:\n            LOG.error(\"Unable to update DCNM ext profile with static \"\n                      \"route %s\", arg_dict.get('router_id'))\n            self.delete_intf_router(tenant_id, arg_dict.get('tenant_name'),\n                                    arg_dict.get('router_id'))\n            return False\n        return True",
    "docstring": "Add static route in DCNM's partition.\n\n        This gets pushed to the relevant leaf switches."
  },
  {
    "code": "def get_frame(self):\n        metric_items = list(self.db.metrics.find({'run_name': self.model_config.run_name}).sort('epoch_idx'))\n        if len(metric_items) == 0:\n            return pd.DataFrame(columns=['run_name'])\n        else:\n            return pd.DataFrame(metric_items).drop(['_id', 'model_name'], axis=1).set_index('epoch_idx')",
    "docstring": "Get a dataframe of metrics from this storage"
  },
  {
    "code": "def remove_interval_helper(self, interval, done, should_raise_error):\n        if self.center_hit(interval):\n            if not should_raise_error and interval not in self.s_center:\n                done.append(1)\n                return self\n            try:\n                self.s_center.remove(interval)\n            except:\n                self.print_structure()\n                raise KeyError(interval)\n            if self.s_center:\n                done.append(1)\n                return self\n            return self.prune()\n        else:\n            direction = self.hit_branch(interval)\n            if not self[direction]:\n                if should_raise_error:\n                    raise ValueError\n                done.append(1)\n                return self\n            self[direction] = self[direction].remove_interval_helper(interval, done, should_raise_error)\n            if not done:\n                return self.rotate()\n            return self",
    "docstring": "Returns self after removing interval and balancing.\n        If interval doesn't exist, raise ValueError.\n\n        This method may set done to [1] to tell all callers that\n        rebalancing has completed.\n\n        See Eternally Confuzzled's jsw_remove_r function (lines 1-32)\n        in his AVL tree article for reference."
  },
  {
    "code": "def get(self, document=None, plugin=None):\n        if plugin is not None:\n            if document is None:\n                documents_list = {}\n                for key in self.documents.keys():\n                    if self.documents[key].plugin == plugin:\n                        documents_list[key] = self.documents[key]\n                return documents_list\n            else:\n                if document in self.documents.keys():\n                    if self.documents[document].plugin == plugin:\n                        return self.documents[document]\n                    else:\n                        return None\n                else:\n                    return None\n        else:\n            if document is None:\n                return self.documents\n            else:\n                if document in self.documents.keys():\n                    return self.documents[document]\n                else:\n                    return None",
    "docstring": "Get one or more documents.\n\n        :param document: Name of the document\n        :type document: str\n        :param plugin: Plugin object, under which the document was registered\n        :type plugin: GwBasePattern"
  },
  {
    "code": "def get_task(self, task_id):\n        try:\n            return self.get(task_id=task_id)\n        except self.model.DoesNotExist:\n            if self._last_id == task_id:\n                self.warn_if_repeatable_read()\n            self._last_id = task_id\n            return self.model(task_id=task_id)",
    "docstring": "Get task meta for task by ``task_id``.\n\n        :keyword exception_retry_count: How many times to retry by\n            transaction rollback on exception. This could theoretically\n            happen in a race condition if another worker is trying to\n            create the same task. The default is to retry once."
  },
  {
    "code": "def create(self):\n        self.db_attrs = self.consul.create_db(\n                self.instance_name,\n                self.instance_type,\n                self.admin_username,\n                self.admin_password,\n                db_name=self.db_name,\n                storage_size_gb=self.storage_size,\n                timeout_s=self.launch_timeout_s,\n                )",
    "docstring": "Creates a new database"
  },
  {
    "code": "def show_notification(cls, channel_id, *args, **kwargs):\n        app = AndroidApplication.instance()\n        builder = Notification.Builder(app, channel_id)\n        builder.update(*args, **kwargs)\n        return builder.show()",
    "docstring": "Create and show a Notification. See `Notification.Builder.update`\n        for a list of accepted parameters."
  },
  {
    "code": "def get(dic, path, seps=PATH_SEPS, idx_reg=_JSNP_GET_ARRAY_IDX_REG):\n    items = [_jsnp_unescape(p) for p in _split_path(path, seps)]\n    if not items:\n        return (dic, '')\n    try:\n        if len(items) == 1:\n            return (dic[items[0]], '')\n        prnt = functools.reduce(operator.getitem, items[:-1], dic)\n        arr = anyconfig.utils.is_list_like(prnt) and idx_reg.match(items[-1])\n        return (prnt[int(items[-1])], '') if arr else (prnt[items[-1]], '')\n    except (TypeError, KeyError, IndexError) as exc:\n        return (None, str(exc))",
    "docstring": "getter for nested dicts.\n\n    :param dic: a dict[-like] object\n    :param path: Path expression to point object wanted\n    :param seps: Separator char candidates\n    :return: A tuple of (result_object, error_message)\n\n    >>> d = {'a': {'b': {'c': 0, 'd': [1, 2]}}, '': 3}\n    >>> assert get(d, '/') == (3, '')  # key becomes '' (empty string).\n    >>> assert get(d, \"/a/b/c\") == (0, '')\n    >>> sorted(get(d, \"a.b\")[0].items())\n    [('c', 0), ('d', [1, 2])]\n    >>> (get(d, \"a.b.d\"), get(d, \"/a/b/d/1\"))\n    (([1, 2], ''), (2, ''))\n    >>> get(d, \"a.b.key_not_exist\")  # doctest: +ELLIPSIS\n    (None, \"'...'\")\n    >>> get(d, \"/a/b/d/2\")\n    (None, 'list index out of range')\n    >>> get(d, \"/a/b/d/-\")  # doctest: +ELLIPSIS\n    (None, 'list indices must be integers...')"
  },
  {
    "code": "def section_multiplane(self,\n                           plane_origin,\n                           plane_normal,\n                           heights):\n        from .exchange.load import load_path\n        lines, transforms, faces = intersections.mesh_multiplane(\n            mesh=self,\n            plane_normal=plane_normal,\n            plane_origin=plane_origin,\n            heights=heights)\n        paths = [None] * len(lines)\n        for index, L, T in zip(range(len(lines)),\n                               lines,\n                               transforms):\n            if len(L) > 0:\n                paths[index] = load_path(\n                    L, metadata={'to_3D': T})\n        return paths",
    "docstring": "Return multiple parallel cross sections of the current\n        mesh in 2D.\n\n        Parameters\n        ---------\n        plane_normal: (3) vector for plane normal\n          Normal vector of section plane\n        plane_origin : (3,) float\n          Point on the cross section plane\n        heights : (n,) float\n          Each section is offset by height along\n          the plane normal.\n\n        Returns\n        ---------\n        paths : (n,) Path2D or None\n          2D cross sections at specified heights.\n          path.metadata['to_3D'] contains transform\n          to return 2D section back into 3D space."
  },
  {
    "code": "async def crypto_sign(wallet_handle: int,\n                      signer_vk: str,\n                      msg: bytes) -> bytes:\n    logger = logging.getLogger(__name__)\n    logger.debug(\"crypto_sign: >>> wallet_handle: %r, signer_vk: %r, msg: %r\",\n                 wallet_handle,\n                 signer_vk,\n                 msg)\n    def transform_cb(arr_ptr: POINTER(c_uint8), arr_len: c_uint32):\n        return bytes(arr_ptr[:arr_len]),\n    if not hasattr(crypto_sign, \"cb\"):\n        logger.debug(\"crypto_sign: Creating callback\")\n        crypto_sign.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, POINTER(c_uint8), c_uint32), transform_cb)\n    c_wallet_handle = c_int32(wallet_handle)\n    c_signer_vk = c_char_p(signer_vk.encode('utf-8'))\n    c_msg_len = c_uint32(len(msg))\n    signature = await do_call('indy_crypto_sign',\n                              c_wallet_handle,\n                              c_signer_vk,\n                              msg,\n                              c_msg_len,\n                              crypto_sign.cb)\n    logger.debug(\"crypto_sign: <<< res: %r\", signature)\n    return signature",
    "docstring": "Signs a message with a key.\n\n    Note to use DID keys with this function you can call indy_key_for_did to get key id (verkey) for specific DID.\n\n    :param wallet_handle: wallet handler (created by open_wallet).\n    :param signer_vk:  id (verkey) of my key. The key must be created by calling create_key or create_and_store_my_did\n    :param msg: a message to be signed\n    :return: a signature string"
  },
  {
    "code": "def reboot(search, one=True, force=False):\n    return _action('reboot', search, one, force)",
    "docstring": "Reboot one or more vms\n\n    search : string\n        filter vms, see the execution module.\n    one : boolean\n        reboot only one vm\n    force : boolean\n        force reboot, faster but no graceful shutdown\n\n    .. note::\n        If the search parameter does not contain an equal (=) symbol it will be\n        assumed it will be tried as uuid, hostname, and alias.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-run vmadm.reboot 91244bba-1146-e4ec-c07e-e825e0223aa9\n        salt-run vmadm.reboot search='alias=marije'\n        salt-run vmadm.reboot search='type=KVM' one=False"
  },
  {
    "code": "def determine_deaths(self, event: Event):\n        effective_rate = self.mortality_rate(event.index)\n        effective_probability = 1 - np.exp(-effective_rate)\n        draw = self.randomness.get_draw(event.index)\n        affected_simulants = draw < effective_probability\n        self.population_view.update(pd.Series('dead', index=event.index[affected_simulants]))",
    "docstring": "Determines who dies each time step.\n\n        Parameters\n        ----------\n        event :\n            An event object emitted by the simulation containing an index\n            representing the simulants affected by the event and timing\n            information."
  },
  {
    "code": "def get_mzmlfile_map(self):\n        cursor = self.get_cursor()\n        cursor.execute('SELECT mzmlfile_id, mzmlfilename FROM mzmlfiles')\n        return {fn: fnid for fnid, fn in cursor.fetchall()}",
    "docstring": "Returns dict of mzmlfilenames and their db ids"
  },
  {
    "code": "def porosity(im):\n    r\n    im = sp.array(im, dtype=int)\n    Vp = sp.sum(im == 1)\n    Vs = sp.sum(im == 0)\n    e = Vp/(Vs + Vp)\n    return e",
    "docstring": "r\"\"\"\n    Calculates the porosity of an image assuming 1's are void space and 0's are\n    solid phase.\n\n    All other values are ignored, so this can also return the relative\n    fraction of a phase of interest.\n\n    Parameters\n    ----------\n    im : ND-array\n        Image of the void space with 1's indicating void space (or True) and\n        0's indicating the solid phase (or False).\n\n    Returns\n    -------\n    porosity : float\n        Calculated as the sum of all 1's divided by the sum of all 1's and 0's.\n\n    See Also\n    --------\n    phase_fraction\n\n    Notes\n    -----\n    This function assumes void is represented by 1 and solid by 0, and all\n    other values are ignored.  This is useful, for example, for images of\n    cylindrical cores, where all voxels outside the core are labelled with 2.\n\n    Alternatively, images can be processed with ``find_disconnected_voxels``\n    to get an image of only blind pores.  This can then be added to the orignal\n    image such that blind pores have a value of 2, thus allowing the\n    calculation of accessible porosity, rather than overall porosity."
  },
  {
    "code": "def resize(self, lines=None, columns=None):\n        lines = lines or self.lines\n        columns = columns or self.columns\n        if lines == self.lines and columns == self.columns:\n            return\n        self.dirty.update(range(lines))\n        if lines < self.lines:\n            self.save_cursor()\n            self.cursor_position(0, 0)\n            self.delete_lines(self.lines - lines)\n            self.restore_cursor()\n        if columns < self.columns:\n            for line in self.buffer.values():\n                for x in range(columns, self.columns):\n                    line.pop(x, None)\n        self.lines, self.columns = lines, columns\n        self.set_margins()",
    "docstring": "Resize the screen to the given size.\n\n        If the requested screen size has more lines than the existing\n        screen, lines will be added at the bottom. If the requested\n        size has less lines than the existing screen lines will be\n        clipped at the top of the screen. Similarly, if the existing\n        screen has less columns than the requested screen, columns will\n        be added at the right, and if it has more -- columns will be\n        clipped at the right.\n\n        :param int lines: number of lines in the new screen.\n        :param int columns: number of columns in the new screen.\n\n        .. versionchanged:: 0.7.0\n\n           If the requested screen size is identical to the current screen\n           size, the method does nothing."
  },
  {
    "code": "def get_touch_dict(self, ind=None, out=bool):\n        if self.config is None:\n            msg = \"Config must be set in order to get touch dict !\"\n            raise Exception(msg)\n        dElt = {}\n        ind = self._check_indch(ind, out=bool)\n        for ss in self.lStruct_computeInOut:\n            kn = \"%s_%s\"%(ss.__class__.__name__, ss.Id.Name)\n            indtouch = self.select(touch=kn, out=bool)\n            if np.any(indtouch):\n                indok  = indtouch & ind\n                indout = indtouch & ~ind\n                if np.any(indok) or np.any(indout):\n                    if out == int:\n                        indok  = indok.nonzero()[0]\n                        indout = indout.nonzero()[0]\n                    dElt[kn] = {'indok':indok, 'indout':indout,\n                                'col':ss.get_color()}\n        return dElt",
    "docstring": "Get a dictionnary of Cls_Name struct with indices of Rays touching\n\n        Only includes Struct object with compute = True\n            (as returned by self.lStruct__computeInOut_computeInOut)\n        Also return the associated colors\n        If in is not None, the indices for each Struct are split between:\n            - indok : rays touching Struct and in ind\n            - indout: rays touching Struct but not in ind"
  },
  {
    "code": "def send_mail(subject, message, from_email, recipient_emails, files=None,\n              html=False, reply_to=None, bcc=None, cc=None, files_manually=None):\n    import django.core.mail\n    try:\n        logging.debug('Sending mail to: {0}'.format(', '.join(r for r in recipient_emails)))\n        logging.debug('Message: {0}'.format(message))\n        email = django.core.mail.EmailMessage(subject, message, from_email, recipient_emails,\n                                              bcc, cc=cc)\n        if html:\n            email.content_subtype = \"html\"\n        if files:\n            for file in files:\n                email.attach_file(file)\n        if files_manually:\n            for filename, content, mimetype in files_manually:\n                email.attach(filename, content, mimetype)\n        if reply_to:\n            email.extra_headers = {'Reply-To': reply_to}\n        email.send()\n    except Exception as e:\n        logging.error('Error sending message [{0}] from {1} to {2} {3}'.format(\n            subject, from_email, recipient_emails, e))",
    "docstring": "Sends email with advanced optional parameters\n\n    To attach non-file content (e.g. content not saved on disk), use\n    files_manually parameter and provide list of 3 element tuples, e.g.\n    [('design.png', img_data, 'image/png'),] which will be passed to\n    email.attach()."
  },
  {
    "code": "def run_plugins(self):\n        for obj in self.loader.objects:\n            self.output_dict[obj.output_options['name']] = None\n            self.thread_manager.add_thread(obj.main, obj.options['interval'])",
    "docstring": "Creates a thread for each plugin and lets the thread_manager handle it."
  },
  {
    "code": "def from_record(cls, record):\n        if not isinstance(record, pymarc.Record):\n            raise TypeError('record must be of type pymarc.Record')\n        record.__class__ = Record\n        return record",
    "docstring": "Factory methods to create Record from pymarc.Record object."
  },
  {
    "code": "def create_chapter_from_file(self, file_name, url=None, title=None):\n        with codecs.open(file_name, 'r', encoding='utf-8') as f:\n            content_string = f.read()\n        return self.create_chapter_from_string(content_string, url, title)",
    "docstring": "Creates a Chapter object from an html or xhtml file. Sanitizes the\n        file's content using the clean_function method, and saves\n        it as the content of the created chapter.\n\n        Args:\n            file_name (string): The file_name containing the html or xhtml\n                content of the created Chapter\n            url (Option[string]): A url to infer the title of the chapter from\n            title (Option[string]): The title of the created Chapter. By\n                default, this is None, in which case the title will try to be\n                inferred from the webpage at the url.\n\n        Returns:\n            Chapter: A chapter object whose content is the given file\n                and whose title is that provided or inferred from the url"
  },
  {
    "code": "def run(self, ket: State) -> State:\n        qubits = self.qubits\n        indices = [ket.qubits.index(q) for q in qubits]\n        tensor = bk.tensormul(self.tensor, ket.tensor, indices)\n        return State(tensor, ket.qubits, ket.memory)",
    "docstring": "Apply the action of this gate upon a state"
  },
  {
    "code": "def script_input(module_name):\n    if module_name not in registered_modules:\n        return page_not_found(module_name)\n    form = registered_modules[module_name].WebAPI()\n    return render_template('script_index.html',\n                           form=form,\n                           scripts=registered_modules,\n                           module_name=module_name)",
    "docstring": "Render a module's input page. Forms are created based on objects in\n    the module's WebAPI class."
  },
  {
    "code": "def get_resources_of_type(network_id, type_id, **kwargs):\n    nodes_with_type = db.DBSession.query(Node).join(ResourceType).filter(Node.network_id==network_id, ResourceType.type_id==type_id).all()\n    links_with_type = db.DBSession.query(Link).join(ResourceType).filter(Link.network_id==network_id, ResourceType.type_id==type_id).all()\n    groups_with_type = db.DBSession.query(ResourceGroup).join(ResourceType).filter(ResourceGroup.network_id==network_id, ResourceType.type_id==type_id).all()\n    return nodes_with_type, links_with_type, groups_with_type",
    "docstring": "Return the Nodes, Links and ResourceGroups which\n        have the type specified."
  },
  {
    "code": "def set_json(self, obj, status=HttpStatusCodes.HTTP_200):\n        obj = json.dumps(obj, sort_keys=True, default=lambda x: str(x))\n        self.set_status(status)\n        self.set_header(HttpResponseHeaders.CONTENT_TYPE, 'application/json')\n        self.set_content(obj)",
    "docstring": "Helper method to set a JSON response.\n\n        Args:\n            obj (:obj:`object`): JSON serializable object\n            status (:obj:`str`, optional): Status code of the response"
  },
  {
    "code": "def add_janitor(self, janitor):\n        if not self.owner and not self.admin:\n            raise RuntimeError(\"Not enough street creed to do this\")\n        janitor = janitor.strip().lower()\n        if not janitor:\n            raise ValueError(\"Empty strings cannot be janitors\")\n        if janitor in self.config.janitors:\n            return\n        self.config.janitors.append(janitor)\n        self.__set_config_value(\"janitors\", self.config.janitors)",
    "docstring": "Add janitor to the room"
  },
  {
    "code": "def calc_resp(password_hash, server_challenge):\n    password_hash += b'\\0' * (21 - len(password_hash))\n    res = b''\n    dobj = des.DES(password_hash[0:7])\n    res = res + dobj.encrypt(server_challenge[0:8])\n    dobj = des.DES(password_hash[7:14])\n    res = res + dobj.encrypt(server_challenge[0:8])\n    dobj = des.DES(password_hash[14:21])\n    res = res + dobj.encrypt(server_challenge[0:8])\n    return res",
    "docstring": "calc_resp generates the LM response given a 16-byte password hash and the\n        challenge from the Type-2 message.\n        @param password_hash\n            16-byte password hash\n        @param server_challenge\n            8-byte challenge from Type-2 message\n        returns\n            24-byte buffer to contain the LM response upon return"
  },
  {
    "code": "def dIbr_dV(Yf, Yt, V):\n    Vnorm = div(V, abs(V))\n    diagV = spdiag(V)\n    diagVnorm = spdiag(Vnorm)\n    dIf_dVa = Yf * 1j * diagV\n    dIf_dVm = Yf * diagVnorm\n    dIt_dVa = Yt * 1j * diagV\n    dIt_dVm = Yt * diagVnorm\n    If = Yf * V\n    It = Yt * V\n    return dIf_dVa, dIf_dVm, dIt_dVa, dIt_dVm, If, It",
    "docstring": "Computes partial derivatives of branch currents w.r.t. voltage.\n\n        Ray Zimmerman, \"dIbr_dV.m\", MATPOWER, version 4.0b1,\n        PSERC (Cornell), http://www.pserc.cornell.edu/matpower/"
  },
  {
    "code": "def namedlist(objname, fieldnames):\n    'like namedtuple but editable'\n    class NamedListTemplate(list):\n        __name__ = objname\n        _fields = fieldnames\n        def __init__(self, L=None, **kwargs):\n            if L is None:\n                L = [None]*len(fieldnames)\n            super().__init__(L)\n            for k, v in kwargs.items():\n                setattr(self, k, v)\n        @classmethod\n        def length(cls):\n            return len(cls._fields)\n    for i, attrname in enumerate(fieldnames):\n        setattr(NamedListTemplate, attrname, property(operator.itemgetter(i), itemsetter(i)))\n    return NamedListTemplate",
    "docstring": "like namedtuple but editable"
  },
  {
    "code": "def echo_verbose_results(data, no_color):\n    click.echo()\n    click.echo(\n        '\\n'.join(\n            '{}: {}'.format(key, val) for key, val in data['info'].items()\n        )\n    )\n    click.echo()\n    for test in data['tests']:\n        if test['outcome'] == 'passed':\n            fg = 'green'\n        elif test['outcome'] == 'skipped':\n            fg = 'yellow'\n        else:\n            fg = 'red'\n        name = parse_test_name(test['name'])\n        echo_style(\n            '{} {}'.format(name, test['outcome'].upper()),\n            no_color,\n            fg=fg\n        )",
    "docstring": "Print list of tests and result of each test."
  },
  {
    "code": "def log(self, level, prefix = ''):\n        logging.log(level, \"%sin interface: %s\", prefix, self.in_interface)\n        logging.log(level, \"%sout interface: %s\", prefix, self.out_interface)\n        logging.log(level, \"%ssource: %s\", prefix, self.source)\n        logging.log(level, \"%sdestination: %s\", prefix, self.destination)\n        logging.log(level, \"%smatches:\", prefix)\n        for match in self.matches:\n            match.log(level, prefix + '  ')\n        if self.jump:\n            logging.log(level, \"%sjump:\", prefix)\n            self.jump.log(level, prefix + '  ')",
    "docstring": "Writes the contents of the Rule to the logging system."
  },
  {
    "code": "def _write_standard(self, message, extra):\n        level = extra['level']\n        if self.include_extra:\n            del extra['timestamp']\n            del extra['level']\n            del extra['logger']\n            if len(extra) > 0:\n                message += \" \" + str(extra)\n        if level == 'INFO':\n            self.logger.info(message)\n        elif level == 'DEBUG':\n            self.logger.debug(message)\n        elif level == 'WARNING':\n            self.logger.warning(message)\n        elif level == 'ERROR':\n            self.logger.error(message)\n        elif level == 'CRITICAL':\n            self.logger.critical(message)\n        else:\n            self.logger.debug(message)",
    "docstring": "Writes a standard log statement\n\n        @param message: The message to write\n        @param extra: The object to pull defaults from"
  },
  {
    "code": "def get_permissions(self, namespace, explicit=False):\n        if not isinstance(namespace, Namespace):\n            namespace = Namespace(namespace)\n        keys = namespace.keys\n        p, _ = self._check(keys, self.index, explicit=explicit)\n        return p",
    "docstring": "Returns the permissions level for the specified namespace\n\n        Arguments:\n\n        namespace -- permissioning namespace (str)\n        explicit -- require explicitly set permissions to the provided namespace\n\n        Returns:\n\n        int -- permissioning flags"
  },
  {
    "code": "def linear_rref(A, b, Matrix=None, S=None):\n    if Matrix is None:\n        from sympy import Matrix\n    if S is None:\n        from sympy import S\n    mat_rows = [_map2l(S, list(row) + [v]) for row, v in zip(A, b)]\n    aug = Matrix(mat_rows)\n    raug, pivot = aug.rref()\n    nindep = len(pivot)\n    return raug[:nindep, :-1], raug[:nindep, -1]",
    "docstring": "Transform a linear system to reduced row-echelon form\n\n    Transforms both the matrix and right-hand side of a linear\n    system of equations to reduced row echelon form\n\n    Parameters\n    ----------\n    A : Matrix-like\n        Iterable of rows.\n    b : iterable\n\n    Returns\n    -------\n    A', b' - transformed versions"
  },
  {
    "code": "def array(self) -> numpy.ndarray:\n        array = numpy.full(self.shape, fillvalue, dtype=float)\n        for idx, subarray in enumerate(self.arrays.values()):\n            array[self.get_timeplaceslice(idx)] = subarray\n        return array",
    "docstring": "The aggregated data of all logged |IOSequence| objects contained\n        in one single |numpy.ndarray| object.\n\n        The documentation on |NetCDFVariableAgg.shape| explains how\n        |NetCDFVariableAgg.array| is structured.  This first example\n        confirms that, under default configuration (`timeaxis=1`),\n        the first axis corresponds to the location, while the second\n        one corresponds to time:\n\n        >>> from hydpy.core.examples import prepare_io_example_1\n        >>> nodes, elements = prepare_io_example_1()\n        >>> from hydpy.core.netcdftools import NetCDFVariableAgg\n        >>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=False, timeaxis=1)\n        >>> for element in elements:\n        ...     nkor1 = element.model.sequences.fluxes.nkor\n        ...     ncvar.log(nkor1, nkor1.average_series())\n        >>> ncvar.array\n        array([[ 12. ,  13. ,  14. ,  15. ],\n               [ 16.5,  18.5,  20.5,  22.5],\n               [ 25. ,  28. ,  31. ,  34. ]])\n\n        When using the first axis as the \"timeaxis\", the resulting\n        |NetCDFVariableAgg.array| is the transposed:\n\n        >>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=False, timeaxis=0)\n        >>> for element in elements:\n        ...     nkor1 = element.model.sequences.fluxes.nkor\n        ...     ncvar.log(nkor1, nkor1.average_series())\n        >>> ncvar.array\n        array([[ 12. ,  16.5,  25. ],\n               [ 13. ,  18.5,  28. ],\n               [ 14. ,  20.5,  31. ],\n               [ 15. ,  22.5,  34. ]])"
  },
  {
    "code": "def plotter_cls(self):\n        ret = self._plotter_cls\n        if ret is None:\n            self._logger.debug('importing %s', self.module)\n            mod = import_module(self.module)\n            plotter = self.plotter_name\n            if plotter not in vars(mod):\n                raise ImportError(\"Module %r does not have a %r plotter!\" % (\n                    mod, plotter))\n            ret = self._plotter_cls = getattr(mod, plotter)\n            _versions.update(get_versions(key=lambda s: s == self._plugin))\n        return ret",
    "docstring": "The plotter class"
  },
  {
    "code": "def format_hexadecimal_field(spec, prec, number, locale):\n    if number < 0:\n        number &= (1 << (8 * int(math.log(-number, 1 << 8) + 1))) - 1\n    format_ = u'0%d%s' % (int(prec or 0), spec)\n    return format(number, format_)",
    "docstring": "Formats a hexadeciaml field."
  },
  {
    "code": "def view_global_hcurves(token, dstore):\n    oq = dstore['oqparam']\n    nsites = len(dstore['sitecol'])\n    rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()\n    mean = getters.PmapGetter(dstore, rlzs_assoc).get_mean()\n    array = calc.convert_to_array(mean, nsites, oq.imtls)\n    res = numpy.zeros(1, array.dtype)\n    for name in array.dtype.names:\n        res[name] = array[name].mean()\n    return rst_table(res)",
    "docstring": "Display the global hazard curves for the calculation. They are\n    used for debugging purposes when comparing the results of two\n    calculations. They are the mean over the sites of the mean hazard\n    curves."
  },
  {
    "code": "def list_port_fwd(zone, permanent=True):\n    ret = []\n    cmd = '--zone={0} --list-forward-ports'.format(zone)\n    if permanent:\n        cmd += ' --permanent'\n    for i in __firewall_cmd(cmd).splitlines():\n        (src, proto, dest, addr) = i.split(':')\n        ret.append(\n            {'Source port': src.split('=')[1],\n             'Protocol': proto.split('=')[1],\n             'Destination port': dest.split('=')[1],\n             'Destination address': addr.split('=')[1]}\n        )\n    return ret",
    "docstring": "List port forwarding\n\n    .. versionadded:: 2015.8.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' firewalld.list_port_fwd public"
  },
  {
    "code": "def remove_qc_reports(portal):\n    logger.info(\"Removing Reports > Quality Control ...\")\n    ti = portal.reports.getTypeInfo()\n    actions = map(lambda action: action.id, ti._actions)\n    for index, action in enumerate(actions, start=0):\n        if action == 'qualitycontrol':\n            ti.deleteActions([index])\n            break\n    logger.info(\"Removing Reports > Quality Control [DONE]\")",
    "docstring": "Removes the action Quality Control from Reports"
  },
  {
    "code": "def iter_history(\n        self,\n        chat_id: Union[int, str],\n        limit: int = 0,\n        offset: int = 0,\n        offset_id: int = 0,\n        offset_date: int = 0,\n        reverse: bool = False\n    ) -> Generator[\"pyrogram.Message\", None, None]:\n        offset_id = offset_id or (1 if reverse else 0)\n        current = 0\n        total = limit or (1 << 31) - 1\n        limit = min(100, total)\n        while True:\n            messages = self.get_history(\n                chat_id=chat_id,\n                limit=limit,\n                offset=offset,\n                offset_id=offset_id,\n                offset_date=offset_date,\n                reverse=reverse\n            ).messages\n            if not messages:\n                return\n            offset_id = messages[-1].message_id + (1 if reverse else 0)\n            for message in messages:\n                yield message\n                current += 1\n                if current >= total:\n                    return",
    "docstring": "Use this method to iterate through a chat history sequentially.\n\n        This convenience method does the same as repeatedly calling :meth:`get_history` in a loop, thus saving you from\n        the hassle of setting up boilerplate code. It is useful for getting the whole chat history with a single call.\n\n        Args:\n            chat_id (``int`` | ``str``):\n                Unique identifier (int) or username (str) of the target chat.\n                For your personal cloud (Saved Messages) you can simply use \"me\" or \"self\".\n                For a contact that exists in your Telegram address book you can use his phone number (str).\n\n            limit (``int``, *optional*):\n                Limits the number of messages to be retrieved.\n                By default, no limit is applied and all messages are returned.\n\n            offset (``int``, *optional*):\n                Sequential number of the first message to be returned..\n                Negative values are also accepted and become useful in case you set offset_id or offset_date.\n\n            offset_id (``int``, *optional*):\n                Identifier of the first message to be returned.\n\n            offset_date (``int``, *optional*):\n                Pass a date in Unix time as offset to retrieve only older messages starting from that date.\n\n            reverse (``bool``, *optional*):\n                Pass True to retrieve the messages in reversed order (from older to most recent).\n\n        Returns:\n            A generator yielding :obj:`Message <pyrogram.Message>` objects.\n\n        Raises:\n            :class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error."
  },
  {
    "code": "def close(self):\n        if self._publish:\n            self._events.put((self._listener.publish_server_closed,\n                              (self._description.address, self._topology_id)))\n        self._monitor.close()\n        self._pool.reset()",
    "docstring": "Clear the connection pool and stop the monitor.\n\n        Reconnect with open()."
  },
  {
    "code": "def invert_delete_row2(self, key, value):\n        self.rows = filter(lambda x: x.get(key) == x.get(value), self.rows)",
    "docstring": "Invert of type two where there are two columns given"
  },
  {
    "code": "def remove(self, nodes):\n        nodes = nodes if isinstance(nodes, list) else [nodes]\n        for node in nodes:\n            k = self.id(node)\n            self.edges = list(filter(lambda e: e[0] != k and e[1] != k, self.edges))\n            del self.nodes[k]",
    "docstring": "Remove a node and its edges."
  },
  {
    "code": "def handle_error(self, exp):\n        payload = {\n            \"message\": \"Invalid or incomplete data provided.\",\n            \"errors\": exp.errors\n        }\n        self.endpoint.return_error(self.error_status, payload=payload)",
    "docstring": "Called if a Mapper returns MappingInvalid. Should handle the error\n        and return it in the appropriate format, can be overridden in order\n        to change the error format.\n\n        :param exp: MappingInvalid exception raised"
  },
  {
    "code": "def update_project(self, org_name, part_name, dci_id=UNKNOWN_DCI_ID,\n                       service_node_ip=UNKNOWN_SRVN_NODE_IP,\n                       vrf_prof=None, desc=None):\n        desc = desc or org_name\n        res = self._create_or_update_partition(org_name, part_name, desc,\n                                               dci_id=dci_id,\n                                               service_node_ip=service_node_ip,\n                                               vrf_prof=vrf_prof,\n                                               operation='PUT')\n        if res and res.status_code in self._resp_ok:\n            LOG.debug(\"Update %s partition in DCNM.\", part_name)\n        else:\n            LOG.error(\"Failed to update %(part)s partition in DCNM.\"\n                      \"Response: %(res)s\", {'part': part_name, 'res': res})\n            raise dexc.DfaClientRequestFailed(reason=res)",
    "docstring": "Update project on the DCNM.\n\n        :param org_name: name of organization.\n        :param part_name: name of partition.\n        :param dci_id: Data Center interconnect id.\n        :param desc: description of project."
  },
  {
    "code": "def is_cozy_registered():\n    req = curl_couchdb('/cozy/_design/user/_view/all')\n    users = req.json()['rows']\n    if len(users) > 0:\n        return True\n    else:\n        return False",
    "docstring": "Check if a Cozy is registered"
  },
  {
    "code": "def from_sas_token(cls, address, sas_token, eventhub=None, **kwargs):\n        address = _build_uri(address, eventhub)\n        return cls(address, sas_token=sas_token, **kwargs)",
    "docstring": "Create an EventHubClient from an existing auth token or token generator.\n\n        :param address: The Event Hub address URL\n        :type address: str\n        :param sas_token: A SAS token or function that returns a SAS token. If a function is supplied,\n         it will be used to retrieve subsequent tokens in the case of token expiry. The function should\n         take no arguments.\n        :type sas_token: str or callable\n        :param eventhub: The name of the EventHub, if not already included in the address URL.\n        :type eventhub: str\n        :param debug: Whether to output network trace logs to the logger. Default\n         is `False`.\n        :type debug: bool\n        :param http_proxy: HTTP proxy settings. This must be a dictionary with the following\n         keys: 'proxy_hostname' (str value) and 'proxy_port' (int value).\n         Additionally the following keys may also be present: 'username', 'password'.\n        :type http_proxy: dict[str, Any]\n        :param auth_timeout: The time in seconds to wait for a token to be authorized by the service.\n         The default value is 60 seconds. If set to 0, no timeout will be enforced from the client.\n        :type auth_timeout: int"
  },
  {
    "code": "def escape_string(value):\n    res = StringIO()\n    res.write('\"')\n    for c in value:\n        if c in CHAR_TO_ESCAPE:\n            res.write(f'\\\\{CHAR_TO_ESCAPE[c]}')\n        elif c.isprintable():\n            res.write(c)\n        elif ord(c) < 0x100:\n            res.write(f'\\\\x{ord(c):02x}')\n        elif ord(c) < 0x10000:\n            res.write(f'\\\\u{ord(c):04x}')\n        else:\n            res.write(f'\\\\U{ord(c):06x}')\n    res.write('\"')\n    return res.getvalue()",
    "docstring": "Converts a string to its S-expression representation, adding quotes\n    and escaping funny characters."
  },
  {
    "code": "def to_logodds_scoring_matrix( self, background=None, correction=DEFAULT_CORRECTION ):\n        alphabet_size = len( self.alphabet )\n        if background is None:\n            background = ones( alphabet_size, float32 ) / alphabet_size\n        totals = numpy.sum( self.values, 1 )[:,newaxis]\n        values = log2( maximum( self.values, correction ) ) \\\n               - log2( totals ) \\\n               - log2( maximum( background, correction ) )\n        return ScoringMatrix.create_from_other( self, values.astype( float32 ) )",
    "docstring": "Create a standard logodds scoring matrix."
  },
  {
    "code": "def get_page_full(self, page_id):\n        try:\n            result = self._request('/getpagefull/',\n                                   {'pageid': page_id})\n            return TildaPage(**result)\n        except NetworkError:\n            return []",
    "docstring": "Get full page info and full html code"
  },
  {
    "code": "def CheckHash(self, responses):\n    index = responses.request_data[\"index\"]\n    if index not in self.state.pending_files:\n      return\n    file_tracker = self.state.pending_files[index]\n    hash_response = responses.First()\n    if not responses.success or not hash_response:\n      urn = file_tracker[\"stat_entry\"].pathspec.AFF4Path(self.client_urn)\n      self.Log(\"Failed to read %s: %s\", urn, responses.status)\n      self._FileFetchFailed(index, responses.request.request.name)\n      return\n    file_tracker.setdefault(\"hash_list\", []).append(hash_response)\n    self.state.blob_hashes_pending += 1\n    if self.state.blob_hashes_pending > self.MIN_CALL_TO_FILE_STORE:\n      self.FetchFileContent()",
    "docstring": "Adds the block hash to the file tracker responsible for this vfs URN."
  },
  {
    "code": "def surface2image(surface):\n    global g_lock\n    with g_lock:\n        img_io = io.BytesIO()\n        surface.write_to_png(img_io)\n        img_io.seek(0)\n        img = PIL.Image.open(img_io)\n        img.load()\n        if \"A\" not in img.getbands():\n            return img\n        img_no_alpha = PIL.Image.new(\"RGB\", img.size, (255, 255, 255))\n        img_no_alpha.paste(img, mask=img.split()[3])\n        return img_no_alpha",
    "docstring": "Convert a cairo surface into a PIL image"
  },
  {
    "code": "def _gevent_patch():\n    try:\n        assert gevent\n        assert grequests\n    except NameError:\n        logger.warn('gevent not exist, fallback to multiprocess...')\n        return MULTITHREAD\n    else:\n        monkey.patch_all()\n        return GEVENT",
    "docstring": "Patch the modules with gevent\n\n    :return: Default is GEVENT. If it not supports gevent then return MULTITHREAD\n    :rtype: int"
  },
  {
    "code": "def get_shape_view(self, shape_obj, avoid_oob=True):\n        x1, y1, x2, y2 = [int(np.round(n)) for n in shape_obj.get_llur()]\n        if avoid_oob:\n            wd, ht = self.get_size()\n            x1, x2 = max(0, x1), min(x2, wd - 1)\n            y1, y2 = max(0, y1), min(y2, ht - 1)\n        yi = np.mgrid[y1:y2 + 1].reshape(-1, 1)\n        xi = np.mgrid[x1:x2 + 1].reshape(1, -1)\n        pts = np.asarray((xi, yi)).T\n        contains = shape_obj.contains_pts(pts)\n        view = np.s_[y1:y2 + 1, x1:x2 + 1]\n        return (view, contains)",
    "docstring": "Calculate a bounding box in the data enclosing `shape_obj` and\n        return a view that accesses it and a mask that is True only for\n        pixels enclosed in the region.\n\n        If `avoid_oob` is True (default) then the bounding box is clipped\n        to avoid coordinates outside of the actual data."
  },
  {
    "code": "def active_devices(self, active_devices):\n        if active_devices is None:\n            raise ValueError(\"Invalid value for `active_devices`, must not be `None`\")\n        if active_devices is not None and active_devices < 0:\n            raise ValueError(\"Invalid value for `active_devices`, must be a value greater than or equal to `0`\")\n        self._active_devices = active_devices",
    "docstring": "Sets the active_devices of this ReportBillingData.\n\n        :param active_devices: The active_devices of this ReportBillingData.\n        :type: int"
  },
  {
    "code": "def pop_momentum_by_name(self, name):\n        momentum = self.get_momentum_by_name(name)\n        self.remove_momentum(momentum)\n        return momentum",
    "docstring": "Removes and returns a momentum by the given name.\n\n        :param name: the momentum name.\n\n        :returns: a momentum removed.\n\n        :raises TypeError: `name` is ``None``.\n        :raises KeyError: failed to find a momentum named `name`."
  },
  {
    "code": "def get_annotation(cls, fn):\n        while fn is not None:\n            if hasattr(fn, '_schema_annotation'):\n                return fn._schema_annotation\n            fn = getattr(fn, 'im_func', fn)\n            closure = getattr(fn, '__closure__', None)\n            fn = closure[0].cell_contents if closure is not None else None\n        return None",
    "docstring": "Find the _schema_annotation attribute for the given function.\n\n        This will descend through decorators until it finds something that has\n        the attribute. If it doesn't find it anywhere, it will return None.\n\n        :param func fn: Find the attribute on this function.\n        :returns: an instance of\n            :class:`~doctor.resource.ResourceSchemaAnnotation` or\n            None."
  },
  {
    "code": "def dirsize_get(l_filesWithoutPath, **kwargs):\n        str_path    = \"\"\n        for k,v in kwargs.items():\n            if k == 'path': str_path = v\n        d_ret   = {}\n        l_size  = []\n        size    = 0\n        for f in l_filesWithoutPath:\n            str_f   = '%s/%s' % (str_path, f)\n            if not os.path.islink(str_f):\n                try:\n                    size += os.path.getsize(str_f)\n                except:\n                    pass\n        str_size    = pftree.sizeof_fmt(size)\n        return {\n            'status':           True,\n            'diskUsage_raw':    size,\n            'diskUsage_human':  str_size\n        }",
    "docstring": "Sample callback that determines a directory size."
  },
  {
    "code": "def get_hits_in_events(hits_array, events, assume_sorted=True, condition=None):\n    logging.debug(\"Calculate hits that exists in the given %d events.\" % len(events))\n    if assume_sorted:\n        events, _ = reduce_sorted_to_intersect(events, hits_array['event_number'])\n        if events.shape[0] == 0:\n            return hits_array[0:0]\n    try:\n        if assume_sorted:\n            selection = analysis_utils.in1d_events(hits_array['event_number'], events)\n        else:\n            logging.warning('Events are usually sorted. Are you sure you want this?')\n            selection = np.in1d(hits_array['event_number'], events)\n        if condition is None:\n            hits_in_events = hits_array[selection]\n        else:\n            for variable in set(re.findall(r'[a-zA-Z_]+', condition)):\n                exec(variable + ' = hits_array[\\'' + variable + '\\']')\n            hits_in_events = hits_array[ne.evaluate(condition + ' & selection')]\n    except MemoryError:\n        logging.error('There are too many hits to do in RAM operations. Consider decreasing chunk size and use the write_hits_in_events function instead.')\n        raise MemoryError\n    return hits_in_events",
    "docstring": "Selects the hits that occurred in events and optional selection criterion.\n        If a event range can be defined use the get_data_in_event_range function. It is much faster.\n\n    Parameters\n    ----------\n    hits_array : numpy.array\n    events : array\n    assume_sorted : bool\n        Is true if the events to select are sorted from low to high value. Increases speed by 35%.\n    condition : string\n        A condition that is applied to the hits in numexpr. Only if the expression evaluates to True the hit is taken.\n\n    Returns\n    -------\n    numpy.array\n        hit array with the hits in events."
  },
  {
    "code": "def _create_body(self, name, label=None, cidr=None):\n        label = label or name\n        body = {\"network\": {\n                \"label\": label,\n                \"cidr\": cidr,\n                }}\n        return body",
    "docstring": "Used to create the dict required to create a network. Accepts either\n        'label' or 'name' as the keyword parameter for the label attribute."
  },
  {
    "code": "def validate_regexp(ctx, param, value):\n    if value:\n        try:\n            value = re.compile(value)\n        except ValueError:\n            raise click.BadParameter('invalid regular expression.')\n    return value",
    "docstring": "Validate and compile regular expression."
  },
  {
    "code": "def _setup_output(self, path, force):\n        if os.path.isdir(path) or os.path.isfile(path):\n            if force:\n                logging.warn(\"Deleting previous file/directory '%s'\" % path)\n                if os.path.isfile(path):\n                    os.remove(path)\n                else:\n                    shutil.rmtree(path)\n            else:\n                raise Exception(\"Cowardly refusing to overwrite already existing path at %s\" % path)",
    "docstring": "Clear the way for an output to be placed at path"
  },
  {
    "code": "def _walk(path, follow_links=False, maximum_depth=None):\n    root_level = path.rstrip(os.path.sep).count(os.path.sep)\n    for root, dirs, files in os.walk(path, followlinks=follow_links):\n        yield root, dirs, files\n        if maximum_depth is None:\n            continue\n        if root_level + maximum_depth <= root.count(os.path.sep):\n            del dirs[:]",
    "docstring": "A modified os.walk with support for maximum traversal depth."
  },
  {
    "code": "def wrap_topgames(cls, response):\n        games = []\n        json = response.json()\n        topjsons = json['top']\n        for t in topjsons:\n            g = cls.wrap_json(json=t['game'],\n                              viewers=t['viewers'],\n                              channels=t['channels'])\n            games.append(g)\n        return games",
    "docstring": "Wrap the response from quering the top games into instances\n        and return them\n\n        :param response: The response for quering the top games\n        :type response: :class:`requests.Response`\n        :returns: the new game instances\n        :rtype: :class:`list` of :class:`Game`\n        :raises: None"
  },
  {
    "code": "def group_by_month_per_hour(self):\n        data_by_month_per_hour = OrderedDict()\n        for m in xrange(1, 13):\n            for h in xrange(0, 24):\n                data_by_month_per_hour[(m, h)] = []\n        for v, dt in zip(self.values, self.datetimes):\n            data_by_month_per_hour[(dt.month, dt.hour)].append(v)\n        return data_by_month_per_hour",
    "docstring": "Return a dictionary of this collection's values grouped by each month per hour.\n\n        Key values are tuples of 2 integers:\n        The first represents the month of the year between 1-12.\n        The first represents the hour of the day between 0-24.\n        (eg. (12, 23) for December at 11 PM)"
  },
  {
    "code": "def __safe_handler_callback(self, handler, method_name, *args, **kwargs):\n        if handler is None or method_name is None:\n            return None\n        only_boolean = kwargs.pop(\"only_boolean\", False)\n        none_as_true = kwargs.pop(\"none_as_true\", False)\n        try:\n            method = getattr(handler, method_name)\n        except AttributeError:\n            result = None\n        else:\n            try:\n                result = method(*args, **kwargs)\n            except Exception as ex:\n                result = None\n                self._logger.exception(\n                    \"Error calling handler '%s': %s\", handler, ex\n                )\n        if result is None and none_as_true:\n            result = True\n        if only_boolean:\n            return bool(result)\n        return result",
    "docstring": "Calls the given method with the given arguments in the given handler.\n        Logs exceptions, but doesn't propagate them.\n\n        Special arguments can be given in kwargs:\n\n        * 'none_as_true': If set to True and the method returned None or\n                          doesn't exist, the result is considered as True.\n                          If set to False, None result is kept as is.\n                          Default is False.\n        * 'only_boolean': If True, the result can only be True or False, else\n                          the result is the value returned by the method.\n                          Default is False.\n\n        :param handler: The handler to call\n        :param method_name: The name of the method to call\n        :param args: List of arguments for the method to call\n        :param kwargs: Dictionary of arguments for the method to call and to\n                       control the call\n        :return: The method result, or None on error"
  },
  {
    "code": "def load_rabit_checkpoint(self):\n        version = ctypes.c_int()\n        _check_call(_LIB.XGBoosterLoadRabitCheckpoint(\n            self.handle, ctypes.byref(version)))\n        return version.value",
    "docstring": "Initialize the model by load from rabit checkpoint.\n\n        Returns\n        -------\n        version: integer\n            The version number of the model."
  },
  {
    "code": "def _group_by(data, criteria):\n    if isinstance(criteria, str):\n        criteria_str = criteria\n        def criteria(x):\n            return x[criteria_str]\n    res = defaultdict(list)\n    for element in data:\n        key = criteria(element)\n        res[key].append(element)\n    return res",
    "docstring": "Group objects in data using a function or a key"
  },
  {
    "code": "def enabled(name, root=None, **kwargs):\n    if __salt__['cmd.retcode'](_systemctl_cmd('is-enabled', name, root=root),\n                               python_shell=False,\n                               ignore_retcode=True) == 0:\n        return True\n    elif '@' in name:\n        local_config_path = _root(LOCAL_CONFIG_PATH, '/')\n        cmd = ['find', local_config_path, '-name', name,\n               '-type', 'l', '-print', '-quit']\n        if bool(__salt__['cmd.run'](cmd, python_shell=False)):\n            return True\n    elif name in _get_sysv_services(root):\n        return _sysv_enabled(name, root)\n    return False",
    "docstring": "Return if the named service is enabled to start on boot\n\n    root\n        Enable/disable/mask unit files in the specified root directory\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' service.enabled <service name>"
  },
  {
    "code": "def is_list(node):\n    return (isinstance(node, Node)\n            and len(node.children) > 1\n            and isinstance(node.children[0], Leaf)\n            and isinstance(node.children[-1], Leaf)\n            and node.children[0].value == u\"[\"\n            and node.children[-1].value == u\"]\")",
    "docstring": "Does the node represent a list literal?"
  },
  {
    "code": "def list2html(lst):\n    txt = '<TABLE width=100% border=0>'\n    for l in lst:\n        txt += '<TR>\\n'\n        if type(l) is str:\n            txt+= '<TD>' + l + '</TD>\\n'\n        elif type(l) is list:\n            txt+= '<TD>'\n            for i in l:\n                txt += i + ', '\n            txt+= '</TD>'\n        else:\n            txt+= '<TD>' + str(l) + '</TD>\\n'\n        txt += '</TR>\\n'\n    txt += '</TABLE><BR>\\n'\n    return txt",
    "docstring": "convert a list to html using table formatting"
  },
  {
    "code": "def _permute_aux_specs(self):\n        calc_aux_mapping = self._NAMES_SUITE_TO_CALC.copy()\n        calc_aux_mapping[_OBJ_LIB_STR] = None\n        [calc_aux_mapping.pop(core) for core in self._CORE_SPEC_NAMES]\n        specs = self._get_aux_specs()\n        for suite_name, calc_name in calc_aux_mapping.items():\n            specs[calc_name] = specs.pop(suite_name)\n        return _permuted_dicts_of_specs(specs)",
    "docstring": "Generate all permutations of the non-core specifications."
  },
  {
    "code": "def npar(self):\n        self.control_data.npar = self.parameter_data.shape[0]\n        return self.control_data.npar",
    "docstring": "get number of parameters\n\n        Returns\n        -------\n        npar : int\n            the number of parameters"
  },
  {
    "code": "def _NTU_from_P_solver(P1, R1, NTU_min, NTU_max, function, **kwargs):\n    P1_max = _NTU_from_P_objective(NTU_max, R1, 0, function, **kwargs)\n    P1_min = _NTU_from_P_objective(NTU_min, R1, 0, function, **kwargs)\n    if P1 > P1_max:\n        raise ValueError('No solution possible gives such a high P1; maximum P1=%f at NTU1=%f' %(P1_max, NTU_max))\n    if P1 < P1_min:\n        raise ValueError('No solution possible gives such a low P1; minimum P1=%f at NTU1=%f' %(P1_min, NTU_min))\n    to_solve = lambda NTU1: _NTU_from_P_objective(NTU1, R1, P1, function, **kwargs)\n    return ridder(to_solve, NTU_min, NTU_max)",
    "docstring": "Private function to solve the P-NTU method backwards, given the\n    function to use, the upper and lower NTU bounds for consideration,\n    and the desired P1 and R1 values."
  },
  {
    "code": "def ensure_str(data: Union[str, bytes]) -> str:\n    if isinstance(data, bytes):\n        return str(data, 'utf-8')\n    return data",
    "docstring": "Convert data in str if data are bytes\n\n    :param data: Data\n    :rtype str:"
  },
  {
    "code": "def _build_prior(self, unconstrained_tensor, constrained_tensor):\n        if not misc.is_tensor(unconstrained_tensor):\n            raise GPflowError(\"Unconstrained input must be a tensor.\")\n        if not misc.is_tensor(constrained_tensor):\n            raise GPflowError(\"Constrained input must be a tensor.\")\n        prior_name = 'prior'\n        if self.prior is None:\n            return tf.constant(0.0, settings.float_type, name=prior_name)\n        log_jacobian = self.transform.log_jacobian_tensor(unconstrained_tensor)\n        logp_var = self.prior.logp(constrained_tensor)\n        return tf.squeeze(tf.add(logp_var, log_jacobian, name=prior_name))",
    "docstring": "Build a tensorflow representation of the prior density.\n        The log Jacobian is included."
  },
  {
    "code": "def create(self, enable_turn=values.unset, type=values.unset,\n               unique_name=values.unset, status_callback=values.unset,\n               status_callback_method=values.unset, max_participants=values.unset,\n               record_participants_on_connect=values.unset,\n               video_codecs=values.unset, media_region=values.unset):\n        data = values.of({\n            'EnableTurn': enable_turn,\n            'Type': type,\n            'UniqueName': unique_name,\n            'StatusCallback': status_callback,\n            'StatusCallbackMethod': status_callback_method,\n            'MaxParticipants': max_participants,\n            'RecordParticipantsOnConnect': record_participants_on_connect,\n            'VideoCodecs': serialize.map(video_codecs, lambda e: e),\n            'MediaRegion': media_region,\n        })\n        payload = self._version.create(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return RoomInstance(self._version, payload, )",
    "docstring": "Create a new RoomInstance\n\n        :param bool enable_turn: Use Twilio Network Traversal for TURN service.\n        :param RoomInstance.RoomType type: Type of room, either peer-to-peer, group-small or group.\n        :param unicode unique_name: Name of the Room.\n        :param unicode status_callback: A URL that Twilio sends asynchronous webhook requests to on every room event.\n        :param unicode status_callback_method: HTTP method Twilio should use when requesting the above URL.\n        :param unicode max_participants: Maximum number of Participants in the Room.\n        :param bool record_participants_on_connect: Start Participant recording when connected.\n        :param RoomInstance.VideoCodec video_codecs: An array of video codecs supported when publishing a Track in the Room.\n        :param unicode media_region: Region for the media server in Group Rooms.\n\n        :returns: Newly created RoomInstance\n        :rtype: twilio.rest.video.v1.room.RoomInstance"
  },
  {
    "code": "def add(self, name='', type='', agent='', scanner='', location='', language='en', *args, **kwargs):\n        part = '/library/sections?name=%s&type=%s&agent=%s&scanner=%s&language=%s&location=%s' % (\n            quote_plus(name), type, agent, quote_plus(scanner), language, quote_plus(location))\n        if kwargs:\n            part += urlencode(kwargs)\n        return self._server.query(part, method=self._server._session.post)",
    "docstring": "Simplified add for the most common options.\n\n            Parameters:\n                name (str): Name of the library\n                agent (str): Example com.plexapp.agents.imdb\n                type (str): movie, show, # check me\n                location (str): /path/to/files\n                language (str): Two letter language fx en\n                kwargs (dict): Advanced options should be passed as a dict. where the id is the key.\n\n            **Photo Preferences**\n\n                * **agent** (str): com.plexapp.agents.none\n                * **enableAutoPhotoTags** (bool): Tag photos. Default value false.\n                * **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.\n                * **includeInGlobal** (bool): Include in dashboard. Default value true.\n                * **scanner** (str): Plex Photo Scanner\n\n            **Movie Preferences**\n\n                * **agent** (str): com.plexapp.agents.none, com.plexapp.agents.imdb, com.plexapp.agents.themoviedb\n                * **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.\n                * **enableCinemaTrailers** (bool): Enable Cinema Trailers. Default value true.\n                * **includeInGlobal** (bool): Include in dashboard. Default value true.\n                * **scanner** (str): Plex Movie Scanner, Plex Video Files Scanner\n\n            **IMDB Movie Options** (com.plexapp.agents.imdb)\n\n                * **title** (bool): Localized titles. Default value false.\n                * **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.\n                * **only_trailers** (bool): Skip extras which aren't trailers. Default value false.\n                * **redband** (bool): Use red band (restricted audiences) trailers when available. Default value false.\n                * **native_subs** (bool): Include extras with subtitles in Library language. Default value false.\n                * **cast_list** (int): Cast List Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.\n                * **ratings** (int): Ratings Source, Default value 0 Possible options:\n                  0:Rotten Tomatoes, 1:IMDb, 2:The Movie Database.\n                * **summary** (int): Plot Summary Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.\n                * **country** (int): Default value 46 Possible options 0:Argentina, 1:Australia, 2:Austria,\n                  3:Belgium, 4:Belize, 5:Bolivia, 6:Brazil, 7:Canada, 8:Chile, 9:Colombia, 10:Costa Rica,\n                  11:Czech Republic, 12:Denmark, 13:Dominican Republic, 14:Ecuador, 15:El Salvador,\n                  16:France, 17:Germany, 18:Guatemala, 19:Honduras, 20:Hong Kong SAR, 21:Ireland,\n                  22:Italy, 23:Jamaica, 24:Korea, 25:Liechtenstein, 26:Luxembourg, 27:Mexico, 28:Netherlands,\n                  29:New Zealand, 30:Nicaragua, 31:Panama, 32:Paraguay, 33:Peru, 34:Portugal,\n                  35:Peoples Republic of China, 36:Puerto Rico, 37:Russia, 38:Singapore, 39:South Africa,\n                  40:Spain, 41:Sweden, 42:Switzerland, 43:Taiwan, 44:Trinidad, 45:United Kingdom,\n                  46:United States, 47:Uruguay, 48:Venezuela.\n                * **collections** (bool): Use collection info from The Movie Database. Default value false.\n                * **localart** (bool): Prefer artwork based on library language. Default value true.\n                * **adult** (bool): Include adult content. Default value false.\n                * **usage** (bool): Send anonymous usage data to Plex. Default value true.\n\n            **TheMovieDB Movie Options** (com.plexapp.agents.themoviedb)\n\n                * **collections** (bool): Use collection info from The Movie Database. Default value false.\n                * **localart** (bool): Prefer artwork based on library language. Default value true.\n                * **adult** (bool): Include adult content. Default value false.\n                * **country** (int): Country (used for release date and content rating). Default value 47 Possible\n                  options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada,\n                  9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador,\n                  16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland,\n                  23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands,\n                  30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,\n                  36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa, 41:Spain,\n                  42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States, 48:Uruguay,\n                  49:Venezuela.\n\n            **Show Preferences**\n\n                * **agent** (str): com.plexapp.agents.none, com.plexapp.agents.thetvdb, com.plexapp.agents.themoviedb\n                * **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.\n                * **episodeSort** (int): Episode order. Default -1 Possible options: 0:Oldest first, 1:Newest first.\n                * **flattenSeasons** (int): Seasons. Default value 0 Possible options: 0:Show,1:Hide.\n                * **includeInGlobal** (bool): Include in dashboard. Default value true.\n                * **scanner** (str): Plex Series Scanner\n\n            **TheTVDB Show Options** (com.plexapp.agents.thetvdb)\n\n                * **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.\n                * **native_subs** (bool): Include extras with subtitles in Library language. Default value false.\n\n            **TheMovieDB Show Options** (com.plexapp.agents.themoviedb)\n\n                * **collections** (bool): Use collection info from The Movie Database. Default value false.\n                * **localart** (bool): Prefer artwork based on library language. Default value true.\n                * **adult** (bool): Include adult content. Default value false.\n                * **country** (int): Country (used for release date and content rating). Default value 47 options\n                  0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada, 9:Chile,\n                  10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador,\n                  16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland,\n                  23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands,\n                  30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,\n                  36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa,\n                  41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States,\n                  48:Uruguay, 49:Venezuela.\n\n            **Other Video Preferences**\n\n                * **agent** (str): com.plexapp.agents.none, com.plexapp.agents.imdb, com.plexapp.agents.themoviedb\n                * **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.\n                * **enableCinemaTrailers** (bool): Enable Cinema Trailers. Default value true.\n                * **includeInGlobal** (bool): Include in dashboard. Default value true.\n                * **scanner** (str): Plex Movie Scanner, Plex Video Files Scanner\n\n            **IMDB Other Video Options** (com.plexapp.agents.imdb)\n\n                * **title** (bool): Localized titles. Default value false.\n                * **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.\n                * **only_trailers** (bool): Skip extras which aren't trailers. Default value false.\n                * **redband** (bool): Use red band (restricted audiences) trailers when available. Default value false.\n                * **native_subs** (bool): Include extras with subtitles in Library language. Default value false.\n                * **cast_list** (int): Cast List Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.\n                * **ratings** (int): Ratings Source Default value 0 Possible options:\n                  0:Rotten Tomatoes,1:IMDb,2:The Movie Database.\n                * **summary** (int): Plot Summary Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.\n                * **country** (int): Country: Default value 46 Possible options: 0:Argentina, 1:Australia, 2:Austria,\n                  3:Belgium, 4:Belize, 5:Bolivia, 6:Brazil, 7:Canada, 8:Chile, 9:Colombia, 10:Costa Rica,\n                  11:Czech Republic, 12:Denmark, 13:Dominican Republic, 14:Ecuador, 15:El Salvador, 16:France,\n                  17:Germany, 18:Guatemala, 19:Honduras, 20:Hong Kong SAR, 21:Ireland, 22:Italy, 23:Jamaica,\n                  24:Korea, 25:Liechtenstein, 26:Luxembourg, 27:Mexico, 28:Netherlands, 29:New Zealand, 30:Nicaragua,\n                  31:Panama, 32:Paraguay, 33:Peru, 34:Portugal, 35:Peoples Republic of China, 36:Puerto Rico,\n                  37:Russia, 38:Singapore, 39:South Africa, 40:Spain, 41:Sweden, 42:Switzerland, 43:Taiwan, 44:Trinidad,\n                  45:United Kingdom, 46:United States, 47:Uruguay, 48:Venezuela.\n                * **collections** (bool): Use collection info from The Movie Database. Default value false.\n                * **localart** (bool): Prefer artwork based on library language. Default value true.\n                * **adult** (bool): Include adult content. Default value false.\n                * **usage** (bool): Send anonymous usage data to Plex. Default value true.\n\n            **TheMovieDB Other Video Options** (com.plexapp.agents.themoviedb)\n\n                * **collections** (bool): Use collection info from The Movie Database. Default value false.\n                * **localart** (bool): Prefer artwork based on library language. Default value true.\n                * **adult** (bool): Include adult content. Default value false.\n                * **country** (int): Country (used for release date and content rating). Default\n                  value 47 Possible options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize,\n                  6:Bolivia, 7:Brazil, 8:Canada, 9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic,\n                  13:Denmark, 14:Dominican Republic, 15:Ecuador, 16:El Salvador, 17:France, 18:Germany,\n                  19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland, 23:Italy, 24:Jamaica,\n                  25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands, 30:New Zealand,\n                  31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,\n                  36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore,\n                  40:South Africa, 41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad,\n                  46:United Kingdom, 47:United States, 48:Uruguay, 49:Venezuela."
  },
  {
    "code": "def update(self, response_headers):\n        if \"x-ratelimit-remaining\" not in response_headers:\n            if self.remaining is not None:\n                self.remaining -= 1\n                self.used += 1\n            return\n        now = time.time()\n        prev_remaining = self.remaining\n        seconds_to_reset = int(response_headers[\"x-ratelimit-reset\"])\n        self.remaining = float(response_headers[\"x-ratelimit-remaining\"])\n        self.used = int(response_headers[\"x-ratelimit-used\"])\n        self.reset_timestamp = now + seconds_to_reset\n        if self.remaining <= 0:\n            self.next_request_timestamp = self.reset_timestamp\n            return\n        if prev_remaining is not None and prev_remaining > self.remaining:\n            estimated_clients = prev_remaining - self.remaining\n        else:\n            estimated_clients = 1.0\n        self.next_request_timestamp = min(\n            self.reset_timestamp,\n            now + (estimated_clients * seconds_to_reset / self.remaining),\n        )",
    "docstring": "Update the state of the rate limiter based on the response headers.\n\n        This method should only be called following a HTTP request to reddit.\n\n        Response headers that do not contain x-ratelimit fields will be treated\n        as a single request. This behavior is to error on the safe-side as such\n        responses should trigger exceptions that indicate invalid behavior."
  },
  {
    "code": "def _remove_none_values(dictionary):\n    return list(map(dictionary.pop,\n                    [i for i in dictionary if dictionary[i] is None]))",
    "docstring": "Remove dictionary keys whose value is None"
  },
  {
    "code": "def get_video_info_for_course_and_profiles(course_id, profiles):\n    course_id = six.text_type(course_id)\n    try:\n        encoded_videos = EncodedVideo.objects.filter(\n            profile__profile_name__in=profiles,\n            video__courses__course_id=course_id\n        ).select_related()\n    except Exception:\n        error_message = u\"Could not get encoded videos for course: {0}\".format(course_id)\n        logger.exception(error_message)\n        raise ValInternalError(error_message)\n    return_dict = {}\n    for enc_vid in encoded_videos:\n        return_dict.setdefault(enc_vid.video.edx_video_id, {}).update(\n            {\n                \"duration\": enc_vid.video.duration,\n            }\n        )\n        return_dict[enc_vid.video.edx_video_id].setdefault(\"profiles\", {}).update(\n            {enc_vid.profile.profile_name: {\n                \"url\": enc_vid.url,\n                \"file_size\": enc_vid.file_size,\n            }}\n        )\n    return return_dict",
    "docstring": "Returns a dict of edx_video_ids with a dict of requested profiles.\n\n    Args:\n        course_id (str): id of the course\n        profiles (list): list of profile_names\n    Returns:\n        (dict): Returns all the profiles attached to a specific\n        edx_video_id\n        {\n            edx_video_id: {\n                'duration': length of the video in seconds,\n                'profiles': {\n                    profile_name: {\n                        'url': url of the encoding\n                        'file_size': size of the file in bytes\n                    },\n                }\n            },\n        }\n    Example:\n        Given two videos with two profiles each in course_id 'test_course':\n        {\n            u'edx_video_id_1': {\n                u'duration: 1111,\n                u'profiles': {\n                    u'mobile': {\n                        'url': u'http: //www.example.com/meow',\n                        'file_size': 2222\n                    },\n                    u'desktop': {\n                        'url': u'http: //www.example.com/woof',\n                        'file_size': 4444\n                    }\n                }\n            },\n            u'edx_video_id_2': {\n                u'duration: 2222,\n                u'profiles': {\n                    u'mobile': {\n                        'url': u'http: //www.example.com/roar',\n                        'file_size': 6666\n                    },\n                    u'desktop': {\n                        'url': u'http: //www.example.com/bzzz',\n                        'file_size': 8888\n                    }\n                }\n            }\n        }"
  },
  {
    "code": "def safe_filename(self, part):\n        return safe_filename(\n            part,\n            os_type=self._os_type, no_control=self._no_control,\n            ascii_only=self._ascii_only, case=self._case,\n            max_length=self._max_filename_length,\n            )",
    "docstring": "Return a safe filename or file part."
  },
  {
    "code": "def count_publishingcountries(country, **kwargs):\n    url = gbif_baseurl + 'occurrence/counts/publishingCountries'\n    out = gbif_GET(url, {\"country\": country}, **kwargs)\n    return out",
    "docstring": "Lists occurrence counts for all countries that publish data about the given country\n\n    :param country: [str] A country, two letter code\n\n    :return: dict\n\n    Usage::\n\n            from pygbif import occurrences\n            occurrences.count_publishingcountries(country = \"DE\")"
  },
  {
    "code": "def from_date_time_string(cls, datetime_string, leap_year=False):\n        dt = datetime.strptime(datetime_string, '%d %b %H:%M')\n        return cls(dt.month, dt.day, dt.hour, dt.minute, leap_year)",
    "docstring": "Create Ladybug DateTime from a DateTime string.\n\n        Usage:\n\n            dt = DateTime.from_date_time_string(\"31 Dec 12:00\")"
  },
  {
    "code": "def SPI_config(self,config):\n        'Configure SPI interface parameters.'\n        self.bus.write_byte_data(self.address, 0xF0, config)\n        return self.bus.read_byte_data(self.address, 0xF0)",
    "docstring": "Configure SPI interface parameters."
  },
  {
    "code": "def _get_filename(request, item):\n        if request.keep_image_names:\n            filename = OgcImageService.finalize_filename(item['niceName'].replace(' ', '_'))\n        else:\n            filename = OgcImageService.finalize_filename(\n                '_'.join([str(GeopediaService._parse_layer(request.layer)), item['objectPath'].rsplit('/', 1)[-1]]),\n                request.image_format\n            )\n        LOGGER.debug(\"filename=%s\", filename)\n        return filename",
    "docstring": "Creates a filename"
  },
  {
    "code": "def data_from_repaircafe_org():\n    browser = webdriver.Chrome()\n    browser.get(\"https://repaircafe.org/en/?s=Contact+the+local+organisers\")\n    browser.maximize_window()\n    viewmore_button = True\n    while viewmore_button:\n        try:\n            viewmore = browser.find_element_by_id(\"viewmore_link\")\n            browser.execute_script(\"arguments[0].scrollIntoView();\", viewmore)\n            viewmore.click()\n        except:\n            viewmore_button = False\n        sleep(2)\n    page_source = BeautifulSoup(browser.page_source, \"lxml\")\n    browser.quit()\n    data = []\n    for h4 in page_source.find_all(\"h4\"):\n        for a in h4.find_all('a', href=True):\n            data.append({\"name\": a.contents[0], \"url\": a['href']})\n    return data",
    "docstring": "Gets data from repaircafe_org."
  },
  {
    "code": "def map_to_resource(self, data_element, resource=None):\n        if not IDataElement.providedBy(data_element):\n            raise ValueError('Expected data element, got %s.' % data_element)\n        if resource is None:\n            coll = \\\n                create_staging_collection(data_element.mapping.mapped_class)\n            agg = coll.get_aggregate()\n            agg.add(data_element)\n            if IMemberDataElement.providedBy(data_element):\n                ent = next(iter(agg))\n                resource = \\\n                    data_element.mapping.mapped_class.create_from_entity(ent)\n            else:\n                resource = coll\n        else:\n            resource.update(data_element)\n        return resource",
    "docstring": "Maps the given data element to a new resource or updates the given\n        resource.\n\n        :raises ValueError: If :param:`data_element` does not provide\n          :class:`everest.representers.interfaces.IDataElement`."
  },
  {
    "code": "def cmd_startstop(options):\n    statelu = {\"start\": \"stopped\", \"stop\": \"running\"}\n    options.inst_state = statelu[options.command]\n    debg.dprint(\"toggle set state: \", options.inst_state)\n    (i_info, param_str) = gather_data(options)\n    (tar_inst, tar_idx) = determine_inst(i_info, param_str, options.command)\n    response = awsc.startstop(tar_inst, options.command)\n    responselu = {\"start\": \"StartingInstances\", \"stop\": \"StoppingInstances\"}\n    filt = responselu[options.command]\n    resp = {}\n    state_term = ('CurrentState', 'PreviousState')\n    for i, j in enumerate(state_term):\n        resp[i] = response[\"{0}\".format(filt)][0][\"{0}\".format(j)]['Name']\n    print(\"Current State: {}{}{}  -  Previous State: {}{}{}\\n\".\n          format(C_STAT[resp[0]], resp[0], C_NORM,\n                 C_STAT[resp[1]], resp[1], C_NORM))",
    "docstring": "Start or Stop the specified instance.\n\n    Finds instances that match args and instance-state expected by the\n    command.  Then, the target instance is determined, the action is\n    performed on the instance, and the eturn information is displayed.\n\n    Args:\n        options (object): contains args and data from parser."
  },
  {
    "code": "def from_millis(cls, timeout_ms):\n    if hasattr(timeout_ms, 'has_expired'):\n      return timeout_ms\n    if timeout_ms is None:\n      return cls(None)\n    return cls(timeout_ms / 1000.0)",
    "docstring": "Create a new PolledTimeout if needed.\n\n    If timeout_ms is already a PolledTimeout, just return it, otherwise create a\n    new PolledTimeout with the given timeout in milliseconds.\n\n    Args:\n      timeout_ms: PolledTimeout object, or number of milliseconds to use for\n        creating a new one.\n\n    Returns:\n      A PolledTimeout object that will expire in timeout_ms milliseconds, which\n    may be timeout_ms itself, or a newly allocated PolledTimeout."
  },
  {
    "code": "def nonempty_set(C, mincount_connectivity=0):\n    if mincount_connectivity > 0:\n        C = C.copy()\n        C[np.where(C < mincount_connectivity)] = 0\n    return np.where(C.sum(axis=0) + C.sum(axis=1) > 0)[0]",
    "docstring": "Returns the set of states that have at least one incoming or outgoing count"
  },
  {
    "code": "def register_as_default(language: Language):\n    def decorator(cls: Type['CoverageExtractor']):\n        cls.register_as_default(language)\n        return cls\n    return decorator",
    "docstring": "Registers a coverage extractor class as the default coverage extractor\n    for a given language. Requires that the coverage extractor class has\n    already been registered with a given name.\n\n    .. code: python\n\n        from bugzoo.core import Language\n        from bugzoo.mgr.coverage import CoverageExtractor, register, \\\n            register_as_default\n\n        @register_as_default(Language.CPP)\n        @register('mycov')\n        class MyCoverageExtractor(CoverageExtractor):\n            ..."
  },
  {
    "code": "def load_child_sections_for_section(context, section, count=None):\n    page = section.get_main_language_page()\n    locale = context.get('locale_code')\n    qs = SectionPage.objects.child_of(page).filter(\n        language__is_main_language=True)\n    if not locale:\n        return qs[:count]\n    return get_pages(context, qs, locale)",
    "docstring": "Returns all child sections\n    If the `locale_code` in the context is not the main language, it will\n    return the translations of the live articles."
  },
  {
    "code": "def subword(w):\n    w = w.reshape(4, 8)\n    return SBOX[w[0]] + SBOX[w[1]] + SBOX[w[2]] + SBOX[w[3]]",
    "docstring": "Function used in the Key Expansion routine that takes a four-byte input word\n    and applies an S-box to each of the four bytes to produce an output word."
  },
  {
    "code": "def get_cursor_pos(window):\n    xpos_value = ctypes.c_double(0.0)\n    xpos = ctypes.pointer(xpos_value)\n    ypos_value = ctypes.c_double(0.0)\n    ypos = ctypes.pointer(ypos_value)\n    _glfw.glfwGetCursorPos(window, xpos, ypos)\n    return xpos_value.value, ypos_value.value",
    "docstring": "Retrieves the last reported cursor position, relative to the client\n    area of the window.\n\n    Wrapper for:\n        void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos);"
  },
  {
    "code": "def word_frame_pos(self, _id):\n        left = int(self.words[_id][0]/1000)\n        right = max(left+1, int(self.words[_id][1]/1000))\n        return (left, right)",
    "docstring": "Get the position of words"
  },
  {
    "code": "def iterative_overlap_assembly(\n        variant_sequences,\n        min_overlap_size=MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE):\n    if len(variant_sequences) <= 1:\n        return variant_sequences\n    n_before_collapse = len(variant_sequences)\n    variant_sequences = collapse_substrings(variant_sequences)\n    n_after_collapse = len(variant_sequences)\n    logger.info(\n        \"Collapsed %d -> %d sequences\",\n        n_before_collapse,\n        n_after_collapse)\n    merged_variant_sequences = greedy_merge(variant_sequences, min_overlap_size)\n    return list(sorted(\n        merged_variant_sequences,\n        key=lambda seq: -len(seq.reads)))",
    "docstring": "Assembles longer sequences from reads centered on a variant by\n    between merging all pairs of overlapping sequences and collapsing\n    shorter sequences onto every longer sequence which contains them.\n\n    Returns a list of variant sequences, sorted by decreasing read support."
  },
  {
    "code": "def get_attached_preparation_wait_kwargs(self, action, container_name, kwargs=None):\n        c_kwargs = dict(container=container_name)\n        client_config = action.client_config\n        c_kwargs = dict(container=container_name)\n        wait_timeout = client_config.get('wait_timeout')\n        if wait_timeout is not None:\n            c_kwargs['timeout'] = wait_timeout\n        update_kwargs(c_kwargs, kwargs)\n        return c_kwargs",
    "docstring": "Generates keyword arguments for waiting for a container when preparing a volume. The container name may be\n        the container being prepared, or the id of the container calling preparation commands.\n\n        :param action: Action configuration.\n        :type action: dockermap.map.runner.ActionConfig\n        :param container_name: Container name or id. Set ``None`` when included in kwargs for ``create_container``.\n        :type container_name: unicode | str | NoneType\n        :param kwargs: Additional keyword arguments to complement or override the configuration-based values.\n        :type kwargs: dict | NoneType\n        :return: Resulting keyword arguments.\n        :rtype: dict"
  },
  {
    "code": "def _input_optional(inp):\n        if 'default' in inp.keys():\n            return True\n        typ = inp.get('type')\n        if isinstance(typ, six.string_types):\n            return typ.endswith('?')\n        elif isinstance(typ, dict):\n            return False\n        elif isinstance(typ, list):\n            return bool(u'null' in typ)\n        else:\n            raise ValueError('Invalid input \"{}\"'.format(inp.get['id']))",
    "docstring": "Returns True if a step input parameter is optional.\n\n        Args:\n            inp (dict): a dictionary representation of an input.\n\n        Raises:\n            ValueError: The inp provided is not valid."
  },
  {
    "code": "def parse_subprotocol_item(\n    header: str, pos: int, header_name: str\n) -> Tuple[Subprotocol, int]:\n    item, pos = parse_token(header, pos, header_name)\n    return cast(Subprotocol, item), pos",
    "docstring": "Parse a subprotocol from ``header`` at the given position.\n\n    Return the subprotocol value and the new position.\n\n    Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs."
  },
  {
    "code": "def build_filter_from_kwargs(self, **kwargs):\n        query = None\n        for path_to_convert, value in kwargs.items():\n            path_parts = path_to_convert.split('__')\n            lookup_class = None\n            try:\n                lookup_class = lookups.registry[path_parts[-1]]\n                path_to_convert = '__'.join(path_parts[:-1])\n            except KeyError:\n                pass\n            path = lookup_to_path(path_to_convert)\n            if lookup_class:\n                q = QueryNode(path, lookup=lookup_class(value))\n            else:\n                q = path == value\n            if query:\n                query = query & q\n            else:\n                query = q\n        return query",
    "docstring": "Convert django-s like lookup to SQLAlchemy ones"
  },
  {
    "code": "def can_update_topics_to_announces(self, forum, user):\n        return (\n            self._perform_basic_permission_check(forum, user, 'can_edit_posts') and\n            self._perform_basic_permission_check(forum, user, 'can_post_announcements')\n        )",
    "docstring": "Given a forum, checks whether the user can change its topic types to announces."
  },
  {
    "code": "def resize(self, new_size):\n        if new_size == len(self):\n            return\n        else:\n            self._saved = LimitedSizeDict(size_limit=2**5)\n            new_arr = zeros(new_size, dtype=self.dtype)\n            if len(self) <= new_size:\n                new_arr[0:len(self)] = self\n            else:\n                new_arr[:] = self[0:new_size]\n            self._data = new_arr._data",
    "docstring": "Resize self to new_size"
  },
  {
    "code": "def getPageSizeByName(self, pageSizeName):\n\t\tpageSize = None\n\t\tlowerCaseNames = {pageSize.lower(): pageSize for pageSize in\n\t\t                  self.availablePageSizes()}\n\t\tif pageSizeName.lower() in lowerCaseNames:\n\t\t\tpageSize = getattr(QPagedPaintDevice, lowerCaseNames[pageSizeName.lower()])\n\t\treturn pageSize",
    "docstring": "Returns a validated PageSize instance corresponding to the given\n\t\tname. Returns None if the name is not a valid PageSize."
  },
  {
    "code": "def after_connect(self):\n        show_users = self.device.send(\"show users\", timeout=120)\n        result = re.search(pattern_manager.pattern(self.platform, 'connected_locally'), show_users)\n        if result:\n            self.log('Locally connected to Calvados. Exiting.')\n            self.device.send('exit')\n            return True\n        return False",
    "docstring": "Execute after connect."
  },
  {
    "code": "def write_publication(self, values):\n        con = self.connection or self._connect()\n        self._initialize(con)\n        cur = con.cursor()\n        values = (values['pub_id'],\n                  values['title'],\n                  json.dumps(values['authors']),\n                  values['journal'],\n                  values['volume'],\n                  values['number'],\n                  values['pages'],\n                  values['year'],\n                  values['publisher'],\n                  values['doi'],\n                  json.dumps(values['tags']))\n        q = self.default + ',' + ', '.join('?' * len(values))\n        cur.execute('INSERT OR IGNORE INTO publication VALUES ({})'.format(q),\n                    values)\n        pid = self.get_last_id(cur, table='publication')\n        if self.connection is None:\n            con.commit()\n            con.close()\n        return pid",
    "docstring": "Write publication info to db\n\n        Parameters\n        ----------\n        values: dict with entries\n            {'pub_id': str (short name for publication),\n            'authors': list of str ()\n            'journal': str,\n            'volume': str,\n            'number': str,\n            'pages': 'str'\n            'year': int,\n            'publisher': str,\n            'doi': str,\n            'tags': list of str}"
  },
  {
    "code": "def to_networkx(self):\n        try:\n            from networkx import DiGraph, set_node_attributes\n        except ImportError:\n            raise ImportError('You must have networkx installed to export networkx graphs')\n        result = DiGraph()\n        for row in self._raw_tree:\n            result.add_edge(row['parent'], row['child'], weight=row['lambda_val'])\n        set_node_attributes(result, dict(self._raw_tree[['child', 'child_size']]), 'size')\n        return result",
    "docstring": "Return a NetworkX DiGraph object representing the condensed tree.\n\n        Edge weights in the graph are the lamba values at which child nodes\n        'leave' the parent cluster.\n\n        Nodes have a `size` attribute attached giving the number of points\n        that are in the cluster (or 1 if it is a singleton point) at the\n        point of cluster creation (fewer points may be in the cluster at\n        larger lambda values)."
  },
  {
    "code": "def post_build(self, pkt, pay):\n        if conf.contribs['CAN']['swap-bytes']:\n            return CAN.inv_endianness(pkt) + pay\n        return pkt + pay",
    "docstring": "Implements the swap-bytes functionality when building\n\n        this is based on a copy of the Packet.self_build default method.\n        The goal is to affect only the CAN layer data and keep\n        under layers (e.g LinuxCooked) unchanged"
  },
  {
    "code": "def get_default_ref(repo):\n    assert isinstance(repo, github.Repository.Repository), type(repo)\n    default_branch = repo.default_branch\n    default_branch_ref = \"heads/{ref}\".format(ref=default_branch)\n    try:\n        head = repo.get_git_ref(default_branch_ref)\n    except github.RateLimitExceededException:\n        raise\n    except github.GithubException as e:\n        msg = \"error getting ref: {ref}\".format(ref=default_branch_ref)\n        raise CaughtRepositoryError(repo, e, msg) from None\n    return head",
    "docstring": "Return a `github.GitRef` object for the HEAD of the default branch.\n\n    Parameters\n    ----------\n    repo: github.Repository.Repository\n        repo to get default branch head ref from\n\n    Returns\n    -------\n    head : :class:`github.GitRef` instance\n\n    Raises\n    ------\n    github.RateLimitExceededException\n    codekit.pygithub.CaughtRepositoryError"
  },
  {
    "code": "def _take_values(self, item: Node) -> DictBasicType:\n        values = super()._take_values(item)\n        values['_parent'] = None\n        return values",
    "docstring": "Takes snapshot of the object and replaces _parent property value on None to avoid\n        infitinite recursion in GPflow tree traversing.\n\n        :param item: GPflow node object.\n        :return: dictionary snapshot of the node object."
  },
  {
    "code": "def list_privileges(name, **client_args):\n    client = _client(**client_args)\n    res = {}\n    for item in client.get_list_privileges(name):\n        res[item['database']] = item['privilege'].split()[0].lower()\n    return res",
    "docstring": "List privileges from a user.\n\n    name\n        Name of the user from whom privileges will be listed.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' influxdb.list_privileges <name>"
  },
  {
    "code": "def wind(direction: Number,\n         speed: Number,\n         gust: Number,\n         vardir: typing.List[Number] = None,\n         unit: str = 'kt',\n         cardinals: bool = True,\n         spoken: bool = False) -> str:\n    ret = ''\n    target = 'spoken' if spoken else 'repr'\n    if direction:\n        if direction.repr in WIND_DIR_REPR:\n            ret += WIND_DIR_REPR[direction.repr]\n        elif direction.value is None:\n            ret += direction.repr\n        else:\n            if cardinals:\n                ret += get_cardinal_direction(direction.value) + '-'\n            ret += getattr(direction, target)\n    if vardir and isinstance(vardir, list):\n        vardir = [getattr(var, target) for var in vardir]\n        ret += ' (variable {} to {})'.format(*vardir)\n    if speed and speed.value:\n        ret += f' at {speed.value}{unit}'\n    if gust and gust.value:\n        ret += f' gusting to {gust.value}{unit}'\n    return ret",
    "docstring": "Format wind elements into a readable sentence\n\n    Returns the translation string\n\n    Ex: NNE-020 (variable 010 to 040) at 14kt gusting to 20kt"
  },
  {
    "code": "def set_group_status(group_id, status, **kwargs):\n    user_id = kwargs.get('user_id')\n    try:\n        group_i = db.DBSession.query(ResourceGroup).filter(ResourceGroup.id == group_id).one()\n    except NoResultFound:\n        raise ResourceNotFoundError(\"ResourceGroup %s not found\"%(group_id))\n    group_i.network.check_write_permission(user_id)\n    group_i.status = status\n    db.DBSession.flush()\n    return group_i",
    "docstring": "Set the status of a group to 'X'"
  },
  {
    "code": "def load_config_file(self, path, profile=None):\n        config_cls = self.get_config_reader()\n        return config_cls.load_config(self, path, profile=profile)",
    "docstring": "Load the standard config file."
  },
  {
    "code": "def _is_in_try_again(self, x, y):\n        if self.won == 1:\n            x1, y1, x2, y2 = self._won_try_again\n            return x1 <= x < x2 and y1 <= y < y2\n        elif self.lost:\n            x1, y1, x2, y2 = self._lost_try_again\n            return x1 <= x < x2 and y1 <= y < y2\n        return False",
    "docstring": "Checks if the game is to be restarted."
  },
  {
    "code": "def _write(self, text, x, y, colour=Screen.COLOUR_WHITE,\n               attr=Screen.A_NORMAL, bg=Screen.COLOUR_BLACK):\n        if y >= self._height or x >= self._width:\n            return\n        if len(text) + x > self._width:\n            text = text[:self._width - x]\n        self._plain_image[y] = text.join(\n            [self._plain_image[y][:x], self._plain_image[y][x + len(text):]])\n        for i, _ in enumerate(text):\n            self._colour_map[y][x + i] = (colour, attr, bg)",
    "docstring": "Write some text to the specified location in the current image.\n\n        :param text: The text to be added.\n        :param x: The X coordinate in the image.\n        :param y: The Y coordinate in the image.\n        :param colour: The colour of the text to add.\n        :param attr: The attribute of the image.\n        :param bg: The background colour of the text to add."
  },
  {
    "code": "def is_dir(self, pathobj):\n        try:\n            stat = self.stat(pathobj)\n            return stat.is_dir\n        except OSError as exc:\n            if exc.errno != errno.ENOENT:\n                raise\n            return False",
    "docstring": "Returns True if given path is a directory"
  },
  {
    "code": "def update_fw_local_router(self, net_id, subnet_id, router_id, os_result):\n        fw_dict = self.get_fw_dict()\n        fw_dict.update({'router_id': router_id, 'router_net_id': net_id,\n                        'router_subnet_id': subnet_id})\n        self.store_dummy_router_net(net_id, subnet_id, router_id)\n        self.update_fw_local_result(os_result=os_result)",
    "docstring": "Update the FW with router attributes."
  },
  {
    "code": "def import_all(path):\n        plist = []\n        fid = 0\n        while True:\n            try:\n                p = PolygonFilter(filename=path, fileid=fid)\n                plist.append(p)\n                fid += 1\n            except IndexError:\n                break\n        return plist",
    "docstring": "Import all polygons from a .poly file.\n\n        Returns a list of the imported polygon filters"
  },
  {
    "code": "def get(self, sid):\n        return EngagementContext(self._version, flow_sid=self._solution['flow_sid'], sid=sid, )",
    "docstring": "Constructs a EngagementContext\n\n        :param sid: Engagement Sid.\n\n        :returns: twilio.rest.studio.v1.flow.engagement.EngagementContext\n        :rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext"
  },
  {
    "code": "def add_gene_ids(self, genes_list):\n        orig_num_genes = len(self.genes)\n        for g in list(set(genes_list)):\n            if not self.genes.has_id(g):\n                new_gene = GenePro(id=g, pdb_file_type=self.pdb_file_type, root_dir=self.genes_dir)\n                if self.model:\n                    self.model.genes.append(new_gene)\n                else:\n                    self.genes.append(new_gene)\n        log.info('Added {} genes to GEM-PRO project'.format(len(self.genes)-orig_num_genes))",
    "docstring": "Add gene IDs manually into the GEM-PRO project.\n\n        Args:\n            genes_list (list): List of gene IDs as strings."
  },
  {
    "code": "def sample(program: Union[circuits.Circuit, schedules.Schedule],\n           *,\n           noise: devices.NoiseModel = devices.NO_NOISE,\n           param_resolver: Optional[study.ParamResolver] = None,\n           repetitions: int = 1,\n           dtype: Type[np.number] = np.complex64) -> study.TrialResult:\n    if noise == devices.NO_NOISE and protocols.has_unitary(program):\n        return sparse_simulator.Simulator(dtype=dtype).run(\n            program=program,\n            param_resolver=param_resolver,\n            repetitions=repetitions)\n    return density_matrix_simulator.DensityMatrixSimulator(\n        dtype=dtype, noise=noise).run(program=program,\n                                      param_resolver=param_resolver,\n                                      repetitions=repetitions)",
    "docstring": "Simulates sampling from the given circuit or schedule.\n\n    Args:\n        program: The circuit or schedule to sample from.\n        noise: Noise model to use while running the simulation.\n        param_resolver: Parameters to run with the program.\n        repetitions: The number of samples to take.\n        dtype: The `numpy.dtype` used by the simulation. Typically one of\n            `numpy.complex64` or `numpy.complex128`.\n            Favors speed over precision by default, i.e. uses `numpy.complex64`."
  },
  {
    "code": "def pymmh3_hash64(key: Union[bytes, bytearray],\n                  seed: int = 0,\n                  x64arch: bool = True) -> Tuple[int, int]:\n    hash_128 = pymmh3_hash128(key, seed, x64arch)\n    unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF\n    if unsigned_val1 & 0x8000000000000000 == 0:\n        signed_val1 = unsigned_val1\n    else:\n        signed_val1 = -((unsigned_val1 ^ 0xFFFFFFFFFFFFFFFF) + 1)\n    unsigned_val2 = (hash_128 >> 64) & 0xFFFFFFFFFFFFFFFF\n    if unsigned_val2 & 0x8000000000000000 == 0:\n        signed_val2 = unsigned_val2\n    else:\n        signed_val2 = -((unsigned_val2 ^ 0xFFFFFFFFFFFFFFFF) + 1)\n    return signed_val1, signed_val2",
    "docstring": "Implements 64bit murmur3 hash, as per ``pymmh3``. Returns a tuple.\n\n    Args:\n        key: data to hash\n        seed: seed\n        x64arch: is a 64-bit architecture available?\n\n    Returns:\n        tuple: tuple of integers, ``(signed_val1, signed_val2)``"
  },
  {
    "code": "def _header_string(basis_dict):\n    tw = textwrap.TextWrapper(initial_indent='', subsequent_indent=' ' * 20)\n    header = '-' * 70 + '\\n'\n    header += ' Basis Set Exchange\\n'\n    header += ' Version ' + version() + '\\n'\n    header += ' ' + _main_url + '\\n'\n    header += '-' * 70 + '\\n'\n    header += '   Basis set: ' + basis_dict['name'] + '\\n'\n    header += tw.fill(' Description: ' + basis_dict['description']) + '\\n'\n    header += '        Role: ' + basis_dict['role'] + '\\n'\n    header += tw.fill('     Version: {}  ({})'.format(basis_dict['version'],\n                                                      basis_dict['revision_description'])) + '\\n'\n    header += '-' * 70 + '\\n'\n    return header",
    "docstring": "Creates a header with information about a basis set\n\n    Information includes description, revision, etc, but not references"
  },
  {
    "code": "def sum_stats(stats_data):\n    t_bounces = 0\n    t_complaints = 0\n    t_delivery_attempts = 0\n    t_rejects = 0\n    for dp in stats_data:\n        t_bounces += int(dp['Bounces'])\n        t_complaints += int(dp['Complaints'])\n        t_delivery_attempts += int(dp['DeliveryAttempts'])\n        t_rejects += int(dp['Rejects'])\n    return {\n        'Bounces': t_bounces,\n        'Complaints': t_complaints,\n        'DeliveryAttempts': t_delivery_attempts,\n        'Rejects': t_rejects,\n    }",
    "docstring": "Summarize the bounces, complaints, delivery attempts and rejects from a\n    list of datapoints."
  },
  {
    "code": "def handler(self):\n\t\t'Parametrized handler function'\n\t\treturn ft.partial(self.base.handler, parameter=self.parameter)\\\n\t\t\tif self.parameter else self.base.handler",
    "docstring": "Parametrized handler function"
  },
  {
    "code": "def _delete_security_groups(self):\n    group_names = self._get_all_group_names_for_cluster()\n    for group in group_names:\n      self.ec2.delete_security_group(group)",
    "docstring": "Delete the security groups for each role in the cluster, and the group for\n    the cluster."
  },
  {
    "code": "def subnet_group_exists(name, tags=None, region=None, key=None, keyid=None,\n                        profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        if not conn:\n            return {'exists': bool(conn)}\n        rds = conn.describe_db_subnet_groups(DBSubnetGroupName=name)\n        return {'exists': bool(rds)}\n    except ClientError as e:\n        if \"DBSubnetGroupNotFoundFault\" in e.message:\n            return {'exists': False}\n        else:\n            return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Check to see if an RDS subnet group exists.\n\n    CLI example::\n\n        salt myminion boto_rds.subnet_group_exists my-param-group \\\n                region=us-east-1"
  },
  {
    "code": "def visit_versions(self, func):\n        for bound in self.bounds:\n            if bound.lower is not _LowerBound.min:\n                result = func(bound.lower.version)\n                if isinstance(result, Version):\n                    bound.lower.version = result\n            if bound.upper is not _UpperBound.inf:\n                result = func(bound.upper.version)\n                if isinstance(result, Version):\n                    bound.upper.version = result",
    "docstring": "Visit each version in the range, and apply a function to each.\n\n        This is for advanced usage only.\n\n        If `func` returns a `Version`, this call will change the versions in\n        place.\n\n        It is possible to change versions in a way that is nonsensical - for\n        example setting an upper bound to a smaller version than the lower bound.\n        Use at your own risk.\n\n        Args:\n            func (callable): Takes a `Version` instance arg, and is applied to\n                every version in the range. If `func` returns a `Version`, it\n                will replace the existing version, updating this `VersionRange`\n                instance in place."
  },
  {
    "code": "def get_canonical_encoding_name(name):\n    import codecs\n    try:\n        codec = codecs.lookup(name)\n    except LookupError:\n        return name\n    else:\n        return codec.name",
    "docstring": "Given an encoding name, get the canonical name from a codec lookup.\n\n    :param str name: The name of the codec to lookup\n    :return: The canonical version of the codec name\n    :rtype: str"
  },
  {
    "code": "def dependencies(self, tkn: str) -> Set[str]:\n        return set(self.dependency_list(tkn))",
    "docstring": "Return all the items that tkn depends on as a set\n\n        :param tkn:\n        :return:"
  },
  {
    "code": "def add_audio(self,\n                  customization_id,\n                  audio_name,\n                  audio_resource,\n                  contained_content_type=None,\n                  allow_overwrite=None,\n                  content_type=None,\n                  **kwargs):\n        if customization_id is None:\n            raise ValueError('customization_id must be provided')\n        if audio_name is None:\n            raise ValueError('audio_name must be provided')\n        if audio_resource is None:\n            raise ValueError('audio_resource must be provided')\n        headers = {\n            'Contained-Content-Type': contained_content_type,\n            'Content-Type': content_type\n        }\n        if 'headers' in kwargs:\n            headers.update(kwargs.get('headers'))\n        sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'add_audio')\n        headers.update(sdk_headers)\n        params = {'allow_overwrite': allow_overwrite}\n        data = audio_resource\n        url = '/v1/acoustic_customizations/{0}/audio/{1}'.format(\n            *self._encode_path_vars(customization_id, audio_name))\n        response = self.request(\n            method='POST',\n            url=url,\n            headers=headers,\n            params=params,\n            data=data,\n            accept_json=True)\n        return response",
    "docstring": "Add an audio resource.\n\n        Adds an audio resource to a custom acoustic model. Add audio content that reflects\n        the acoustic characteristics of the audio that you plan to transcribe. You must\n        use credentials for the instance of the service that owns a model to add an audio\n        resource to it. Adding audio data does not affect the custom acoustic model until\n        you train the model for the new data by using the **Train a custom acoustic\n        model** method.\n        You can add individual audio files or an archive file that contains multiple audio\n        files. Adding multiple audio files via a single archive file is significantly more\n        efficient than adding each file individually. You can add audio resources in any\n        format that the service supports for speech recognition.\n        You can use this method to add any number of audio resources to a custom model by\n        calling the method once for each audio or archive file. But the addition of one\n        audio resource must be fully complete before you can add another. You must add a\n        minimum of 10 minutes and a maximum of 100 hours of audio that includes speech,\n        not just silence, to a custom acoustic model before you can train it. No audio\n        resource, audio- or archive-type, can be larger than 100 MB. To add an audio\n        resource that has the same name as an existing audio resource, set the\n        `allow_overwrite` parameter to `true`; otherwise, the request fails.\n        The method is asynchronous. It can take several seconds to complete depending on\n        the duration of the audio and, in the case of an archive file, the total number of\n        audio files being processed. The service returns a 201 response code if the audio\n        is valid. It then asynchronously analyzes the contents of the audio file or files\n        and automatically extracts information about the audio such as its length,\n        sampling rate, and encoding. You cannot submit requests to add additional audio\n        resources to a custom acoustic model, or to train the model, until the service's\n        analysis of all audio files for the current request completes.\n        To determine the status of the service's analysis of the audio, use the **Get an\n        audio resource** method to poll the status of the audio. The method accepts the\n        customization ID of the custom model and the name of the audio resource, and it\n        returns the status of the resource. Use a loop to check the status of the audio\n        every few seconds until it becomes `ok`.\n        **See also:** [Add audio to the custom acoustic\n        model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-create.html#addAudio).\n        ### Content types for audio-type resources\n         You can add an individual audio file in any format that the service supports for\n        speech recognition. For an audio-type resource, use the `Content-Type` parameter\n        to specify the audio format (MIME type) of the audio file, including specifying\n        the sampling rate, channels, and endianness where indicated.\n        * `audio/alaw` (Specify the sampling rate (`rate`) of the audio.)\n        * `audio/basic` (Use only with narrowband models.)\n        * `audio/flac`\n        * `audio/g729` (Use only with narrowband models.)\n        * `audio/l16` (Specify the sampling rate (`rate`) and optionally the number of\n        channels (`channels`) and endianness (`endianness`) of the audio.)\n        * `audio/mp3`\n        * `audio/mpeg`\n        * `audio/mulaw` (Specify the sampling rate (`rate`) of the audio.)\n        * `audio/ogg` (The service automatically detects the codec of the input audio.)\n        * `audio/ogg;codecs=opus`\n        * `audio/ogg;codecs=vorbis`\n        * `audio/wav` (Provide audio with a maximum of nine channels.)\n        * `audio/webm` (The service automatically detects the codec of the input audio.)\n        * `audio/webm;codecs=opus`\n        * `audio/webm;codecs=vorbis`\n        The sampling rate of an audio file must match the sampling rate of the base model\n        for the custom model: for broadband models, at least 16 kHz; for narrowband\n        models, at least 8 kHz. If the sampling rate of the audio is higher than the\n        minimum required rate, the service down-samples the audio to the appropriate rate.\n        If the sampling rate of the audio is lower than the minimum required rate, the\n        service labels the audio file as `invalid`.\n         **See also:** [Audio\n        formats](https://cloud.ibm.com/docs/services/speech-to-text/audio-formats.html).\n        ### Content types for archive-type resources\n         You can add an archive file (**.zip** or **.tar.gz** file) that contains audio\n        files in any format that the service supports for speech recognition. For an\n        archive-type resource, use the `Content-Type` parameter to specify the media type\n        of the archive file:\n        * `application/zip` for a **.zip** file\n        * `application/gzip` for a **.tar.gz** file.\n        When you add an archive-type resource, the `Contained-Content-Type` header is\n        optional depending on the format of the files that you are adding:\n        * For audio files of type `audio/alaw`, `audio/basic`, `audio/l16`, or\n        `audio/mulaw`, you must use the `Contained-Content-Type` header to specify the\n        format of the contained audio files. Include the `rate`, `channels`, and\n        `endianness` parameters where necessary. In this case, all audio files contained\n        in the archive file must have the same audio format.\n        * For audio files of all other types, you can omit the `Contained-Content-Type`\n        header. In this case, the audio files contained in the archive file can have any\n        of the formats not listed in the previous bullet. The audio files do not need to\n        have the same format.\n        Do not use the `Contained-Content-Type` header when adding an audio-type resource.\n        ### Naming restrictions for embedded audio files\n         The name of an audio file that is embedded within an archive-type resource must\n        meet the following restrictions:\n        * Include a maximum of 128 characters in the file name; this includes the file\n        extension.\n        * Do not include spaces, slashes, or backslashes in the file name.\n        * Do not use the name of an audio file that has already been added to the custom\n        model as part of an archive-type resource.\n\n        :param str customization_id: The customization ID (GUID) of the custom acoustic\n        model that is to be used for the request. You must make the request with\n        credentials for the instance of the service that owns the custom model.\n        :param str audio_name: The name of the new audio resource for the custom acoustic\n        model. Use a localized name that matches the language of the custom model and\n        reflects the contents of the resource.\n        * Include a maximum of 128 characters in the name.\n        * Do not include spaces, slashes, or backslashes in the name.\n        * Do not use the name of an audio resource that has already been added to the\n        custom model.\n        :param file audio_resource: The audio resource that is to be added to the custom\n        acoustic model, an individual audio file or an archive file.\n        :param str contained_content_type: **For an archive-type resource,** specify the\n        format of the audio files that are contained in the archive file if they are of\n        type `audio/alaw`, `audio/basic`, `audio/l16`, or `audio/mulaw`. Include the\n        `rate`, `channels`, and `endianness` parameters where necessary. In this case, all\n        audio files that are contained in the archive file must be of the indicated type.\n        For all other audio formats, you can omit the header. In this case, the audio\n        files can be of multiple types as long as they are not of the types listed in the\n        previous paragraph.\n        The parameter accepts all of the audio formats that are supported for use with\n        speech recognition. For more information, see **Content types for audio-type\n        resources** in the method description.\n        **For an audio-type resource,** omit the header.\n        :param bool allow_overwrite: If `true`, the specified audio resource overwrites an\n        existing audio resource with the same name. If `false`, the request fails if an\n        audio resource with the same name already exists. The parameter has no effect if\n        an audio resource with the same name does not already exist.\n        :param str content_type: For an audio-type resource, the format (MIME type) of the\n        audio. For more information, see **Content types for audio-type resources** in the\n        method description.\n        For an archive-type resource, the media type of the archive file. For more\n        information, see **Content types for archive-type resources** in the method\n        description.\n        :param dict headers: A `dict` containing the request headers\n        :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n        :rtype: DetailedResponse"
  },
  {
    "code": "def delegated_login(self, login, admin_zc, duration=0):\n        selector = zobjects.Account(name=login).to_selector()\n        delegate_args = {'account': selector}\n        if duration:\n            delegate_args['duration': duration]\n        resp = admin_zc.request('DelegateAuth', delegate_args)\n        lifetime = resp['lifetime']\n        authToken = resp['authToken']\n        self.login_account = login\n        self.login_with_authToken(authToken, lifetime)",
    "docstring": "Use another client to get logged in via delegated_auth mechanism by an\n        already logged in admin.\n\n        :param admin_zc: An already logged-in admin client\n        :type admin_zc: ZimbraAdminClient\n        :param login: the user login (or email) you want to log as"
  },
  {
    "code": "def re_authenticate(self, notify: bool=False) -> bool:\n        timeout = datetime.now() + \\\n            timedelta(seconds=self.reauthenticatetimeout)\n        while True:\n            if self.authenticate():\n                return True\n            if notify:\n                if not self._notifyrunning:\n                    return False\n            else:\n                if timeout and datetime.now() > timeout:\n                    return False\n            time.sleep(self.retryinterval)",
    "docstring": "Authenticate again after failure.\n           Keep trying with 10 sec interval. If called from the notify thread\n           we will not have a timeout, but will end if the notify thread has\n           been cancled.\n           Will return True if authentication was successful."
  },
  {
    "code": "def set_timeout(self, network_timeout):\n        if network_timeout == self._network_timeout:\n            return\n        self._network_timeout = network_timeout\n        self._disconnect()",
    "docstring": "Set the timeout for existing and future Clients.\n\n        Close all current connections. This will cause future operations to\n        create new Clients with the network_timeout passed through\n        socketTimeoutMS optional parameter.\n\n        Args:\n            network_timeout: The new value in milliseconds for the timeout."
  },
  {
    "code": "def convert_dict_to_params(src_dict):\n    return \"&\".join([\n        \"{}={}\".format(key, value)\n        for key, value in src_dict.items()\n    ])",
    "docstring": "convert dict to params string\n\n    Args:\n        src_dict (dict): source mapping data structure\n\n    Returns:\n        str: string params data\n\n    Examples:\n        >>> src_dict = {\n            \"a\": 1,\n            \"b\": 2\n        }\n        >>> convert_dict_to_params(src_dict)\n        >>> \"a=1&b=2\""
  },
  {
    "code": "def format_errors(self, errors, many):\n        if not errors:\n            return {}\n        if isinstance(errors, (list, tuple)):\n            return {'errors': errors}\n        formatted_errors = []\n        if many:\n            for index, errors in iteritems(errors):\n                for field_name, field_errors in iteritems(errors):\n                    formatted_errors.extend([\n                        self.format_error(field_name, message, index=index)\n                        for message in field_errors\n                    ])\n        else:\n            for field_name, field_errors in iteritems(errors):\n                formatted_errors.extend([\n                    self.format_error(field_name, message)\n                    for message in field_errors\n                ])\n        return {'errors': formatted_errors}",
    "docstring": "Format validation errors as JSON Error objects."
  },
  {
    "code": "def _package(self, task, *args, **kw):\n        return self.codec.encode([task, args, kw])",
    "docstring": "Used internally. Simply wraps the arguments up in a list and encodes \n        the list."
  },
  {
    "code": "def search(cls, args):\n        safe_shell_pat = re.escape(args['<pattern>']).replace(r'\\*', '.*')\n        pat_str = '.*{}.*'.format(safe_shell_pat)\n        pattern = re.compile(pat_str, re.IGNORECASE)\n        remote_json = NAppsManager.search(pattern)\n        remote = set()\n        for napp in remote_json:\n            username = napp.get('username', napp.get('author'))\n            remote.add(((username, napp.get('name')), napp.get('description')))\n        cls._print_napps(remote)",
    "docstring": "Search for NApps in NApps server matching a pattern."
  },
  {
    "code": "def _path_importer_cache(cls, path):\n        if path == '':\n            try:\n                path = os.getcwd()\n            except FileNotFoundError:\n                return None\n        try:\n            finder = sys.path_importer_cache[path]\n        except KeyError:\n            finder = cls._path_hooks(path)\n            sys.path_importer_cache[path] = finder\n        return finder",
    "docstring": "Get the finder for the path entry from sys.path_importer_cache.\n        If the path entry is not in the cache, find the appropriate finder\n        and cache it. If no finder is available, store None."
  },
  {
    "code": "def click_signal(target_usage, target_vendor_id):\r\n    all_devices = hid.HidDeviceFilter(vendor_id = target_vendor_id).get_devices()\r\n    if not all_devices:\r\n        print(\"Can't find target device (vendor_id = 0x%04x)!\" % target_vendor_id)\r\n    else:\r\n        for device in all_devices:\r\n            try:\r\n                device.open()\r\n                for report in device.find_output_reports():\r\n                    if target_usage in report:\r\n                        report[target_usage] = 1\n                        report.send()\r\n                        report[target_usage] = 0\r\n                        report.send()\r\n                        print(\"\\nUsage clicked!\\n\")\r\n                        return\r\n            finally:\r\n                device.close()\r\n        print(\"The target device was found, but the requested usage does not exist!\\n\")",
    "docstring": "This function will find a particular target_usage over output reports on\r\n    target_vendor_id related devices, then it will flip the signal to simulate\r\n    a 'click' event"
  },
  {
    "code": "def decode(self, value):\n        if self.encoding:\n            value = value.decode(self.encoding)\n        return self.deserialize(value)",
    "docstring": "Decode value."
  },
  {
    "code": "def fetch_partial(self, container, obj, size):\n        return self._manager.fetch_partial(container, obj, size)",
    "docstring": "Returns the first 'size' bytes of an object. If the object is smaller\n        than the specified 'size' value, the entire object is returned."
  },
  {
    "code": "def diag_sparse(A):\n    if isspmatrix(A):\n        return A.diagonal()\n    else:\n        if(np.ndim(A) != 1):\n            raise ValueError('input diagonal array expected to be 1d')\n        return csr_matrix((np.asarray(A), np.arange(len(A)),\n                           np.arange(len(A)+1)), (len(A), len(A)))",
    "docstring": "Return a diagonal.\n\n    If A is a sparse matrix (e.g. csr_matrix or csc_matrix)\n       - return the diagonal of A as an array\n\n    Otherwise\n       - return a csr_matrix with A on the diagonal\n\n    Parameters\n    ----------\n    A : sparse matrix or 1d array\n        General sparse matrix or array of diagonal entries\n\n    Returns\n    -------\n    B : array or sparse matrix\n        Diagonal sparse is returned as csr if A is dense otherwise return an\n        array of the diagonal\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from pyamg.util.utils import diag_sparse\n    >>> d = 2.0*np.ones((3,)).ravel()\n    >>> print diag_sparse(d).todense()\n    [[ 2.  0.  0.]\n     [ 0.  2.  0.]\n     [ 0.  0.  2.]]"
  },
  {
    "code": "def hashed_download(url, temp, digest):\n    def opener():\n        opener = build_opener(HTTPSHandler())\n        for handler in opener.handlers:\n            if isinstance(handler, HTTPHandler):\n                opener.handlers.remove(handler)\n        return opener\n    def read_chunks(response, chunk_size):\n        while True:\n            chunk = response.read(chunk_size)\n            if not chunk:\n                break\n            yield chunk\n    response = opener().open(url)\n    path = join(temp, urlparse(url).path.split('/')[-1])\n    actual_hash = sha256()\n    with open(path, 'wb') as file:\n        for chunk in read_chunks(response, 4096):\n            file.write(chunk)\n            actual_hash.update(chunk)\n    actual_digest = actual_hash.hexdigest()\n    if actual_digest != digest:\n        raise HashError(url, path, actual_digest, digest)\n    return path",
    "docstring": "Download ``url`` to ``temp``, make sure it has the SHA-256 ``digest``,\n    and return its path."
  },
  {
    "code": "def friendly_type_name(raw_type: typing.Type) -> str:\n    try:\n        return _TRANSLATE_TYPE[raw_type]\n    except KeyError:\n        LOGGER.error('unmanaged value type: %s', raw_type)\n        return str(raw_type)",
    "docstring": "Returns a user-friendly type name\n\n    :param raw_type: raw type (str, int, ...)\n    :return: user friendly type as string"
  },
  {
    "code": "def _define_array_view(data_type):\n    element_type = data_type.element_type\n    element_view = _resolve_view(element_type)\n    if element_view is None:\n        mixins = (_DirectArrayViewMixin,)\n        attributes = _get_mixin_attributes(mixins)\n    elif isinstance(element_type, _ATOMIC):\n        mixins = (_IndirectAtomicArrayViewMixin,)\n        attributes = _get_mixin_attributes(mixins)\n        attributes.update({\n            '_element_view': element_view,\n        })\n    else:\n        mixins = (_IndirectCompositeArrayViewMixin,)\n        attributes = _get_mixin_attributes(mixins)\n        attributes.update({\n            '_element_view': element_view,\n        })\n    name = data_type.name if data_type.name else 'ArrayView'\n    return type(name, (), attributes)",
    "docstring": "Define a new view object for a `Array` type."
  },
  {
    "code": "def get_online_symbol_data(database_id):\n    import pymysql\n    import pymysql.cursors\n    cfg = get_database_configuration()\n    mysql = cfg['mysql_online']\n    connection = pymysql.connect(host=mysql['host'],\n                                 user=mysql['user'],\n                                 passwd=mysql['passwd'],\n                                 db=mysql['db'],\n                                 cursorclass=pymysql.cursors.DictCursor)\n    cursor = connection.cursor()\n    sql = (\"SELECT `id`, `formula_in_latex`, `unicode_dec`, `font`, \"\n           \"`font_style` FROM  `wm_formula` WHERE  `id` =%i\") % database_id\n    cursor.execute(sql)\n    datasets = cursor.fetchall()\n    if len(datasets) == 1:\n        return datasets[0]\n    else:\n        return None",
    "docstring": "Get from the server."
  },
  {
    "code": "def is_app(command, *app_names, **kwargs):\n    at_least = kwargs.pop('at_least', 0)\n    if kwargs:\n        raise TypeError(\"got an unexpected keyword argument '{}'\".format(kwargs.keys()))\n    if len(command.script_parts) > at_least:\n        return command.script_parts[0] in app_names\n    return False",
    "docstring": "Returns `True` if command is call to one of passed app names."
  },
  {
    "code": "def _longest_val_in_column(self, col):\n        try:\n            return max([len(x[col]) for x in self.table if x[col]]) + 2\n        except KeyError:\n            logger.error(\"there is no column %r\", col)\n            raise",
    "docstring": "get size of longest value in specific column\n\n        :param col: str, column name\n        :return int"
  },
  {
    "code": "def fit_predict(self, features, labels):\n        self.fit(features, labels)\n        return self.predict(features)",
    "docstring": "Convenience function that fits a pipeline then predicts on the\n        provided features\n\n        Parameters\n        ----------\n        features: array-like {n_samples, n_features}\n            Feature matrix\n        labels: array-like {n_samples}\n            List of class labels for prediction\n\n        Returns\n        ----------\n        array-like: {n_samples}\n            Predicted labels for the provided features"
  },
  {
    "code": "def report_and_raise(probe_name, probe_result, failure_msg):\n    log.info('%s? %s' % (probe_name, probe_result))\n    if not probe_result:\n        raise exceptions.ProbeException(failure_msg)\n    else:\n        return True",
    "docstring": "Logs the probe result and raises on failure"
  },
  {
    "code": "def get_company_user(self, email):\n        users = self.get_company_users()\n        for user in users:\n            if user['email'] == email:\n                return user\n        msg = 'No user with email: \"{email}\" associated with this company.'\n        raise FMBaseError(msg.format(email=email))",
    "docstring": "Get company user based on email.\n\n        :param email: address of contact\n        :type email: ``str``, ``unicode``\n        :rtype: ``dict`` with contact information"
  },
  {
    "code": "def isuncertainties(arg_list):\n    for arg in arg_list:\n        if isinstance(arg, (list, tuple)) and isinstance(arg[0], uct.UFloat):\n            return True\n        elif isinstance(arg, np.ndarray) and isinstance(\n                np.atleast_1d(arg)[0], uct.UFloat):\n            return True\n        elif isinstance(arg, (float, uct.UFloat)) and \\\n                isinstance(arg, uct.UFloat):\n            return True\n    return False",
    "docstring": "check if the input list contains any elements with uncertainties class\n\n    :param arg_list: list of arguments\n    :return: True/False"
  },
  {
    "code": "def ListOutputModules(self):\n    table_view = views.ViewsFactory.GetTableView(\n        self._views_format_type, column_names=['Name', 'Description'],\n        title='Output Modules')\n    for name, output_class in output_manager.OutputManager.GetOutputClasses():\n      table_view.AddRow([name, output_class.DESCRIPTION])\n    table_view.Write(self._output_writer)\n    disabled_classes = list(\n        output_manager.OutputManager.GetDisabledOutputClasses())\n    if not disabled_classes:\n      return\n    table_view = views.ViewsFactory.GetTableView(\n        self._views_format_type, column_names=['Name', 'Description'],\n        title='Disabled Output Modules')\n    for name, output_class in disabled_classes:\n      table_view.AddRow([name, output_class.DESCRIPTION])\n    table_view.Write(self._output_writer)",
    "docstring": "Lists the output modules."
  },
  {
    "code": "def validator(func, *args, **kwargs):\n    def wrapper(func, *args, **kwargs):\n        value = func(*args, **kwargs)\n        if not value:\n            return ValidationFailure(\n                func, func_args_as_dict(func, args, kwargs)\n            )\n        return True\n    return decorator(wrapper, func)",
    "docstring": "A decorator that makes given function validator.\n\n    Whenever the given function is called and returns ``False`` value\n    this decorator returns :class:`ValidationFailure` object.\n\n    Example::\n\n        >>> @validator\n        ... def even(value):\n        ...     return not (value % 2)\n\n        >>> even(4)\n        True\n\n        >>> even(5)\n        ValidationFailure(func=even, args={'value': 5})\n\n    :param func: function to decorate\n    :param args: positional function arguments\n    :param kwargs: key value function arguments"
  },
  {
    "code": "def ensure_object_is_string(item, title):\n    assert isinstance(title, str)\n    if not isinstance(item, str):\n        msg = \"{} must be a string. {} passed instead.\"\n        raise TypeError(msg.format(title, type(item)))\n    return None",
    "docstring": "Checks that the item is a string. If not, raises ValueError."
  },
  {
    "code": "def OnCellText(self, event):\n        row, col, _ = self.grid.actions.cursor\n        self.grid.GetTable().SetValue(row, col, event.code)\n        event.Skip()",
    "docstring": "Text entry event handler"
  },
  {
    "code": "def st_ctime(self):\n        ctime = self._st_ctime_ns / 1e9\n        return ctime if self.use_float else int(ctime)",
    "docstring": "Return the creation time in seconds."
  },
  {
    "code": "def owned_by(self, owner, also_check_group=False):\n        if also_check_group:\n            return self.owner == owner and self.group == owner\n        else:\n            return self.owner == owner",
    "docstring": "Checks if the specified user or user and group own the file.\n\n        Args:\n            owner (str): the user (or group) name for which we ask about ownership\n            also_check_group (bool): if set to True, both user owner and group owner checked\n                                if set to False, only user owner checked\n\n        Returns:\n            bool: True if owner of the file is the specified owner"
  },
  {
    "code": "def db_aws_list_regions(self):\n        regions = self.db_services.list_regions()\n        if regions != []:\n            print \"Avaliable AWS regions:\"\n        for reg in regions:\n            print '\\t' + reg,\n            if reg == self.db_services.get_region():\n                print \"(currently selected)\"\n            else:\n                print ''",
    "docstring": "List AWS DB regions"
  },
  {
    "code": "def add_email_grant(self, permission, email_address, headers=None):\n        policy = self.get_acl(headers=headers)\n        policy.acl.add_email_grant(permission, email_address)\n        self.set_acl(policy, headers=headers)",
    "docstring": "Convenience method that provides a quick way to add an email grant\n        to a key. This method retrieves the current ACL, creates a new\n        grant based on the parameters passed in, adds that grant to the ACL\n        and then PUT's the new ACL back to S3.\n\n        :type permission: string\n        :param permission: The permission being granted. Should be one of:\n                           (READ, WRITE, READ_ACP, WRITE_ACP, FULL_CONTROL).\n\n        :type email_address: string\n        :param email_address: The email address associated with the AWS\n                              account your are granting the permission to.\n\n        :type recursive: boolean\n        :param recursive: A boolean value to controls whether the command\n                          will apply the grant to all keys within the bucket\n                          or not.  The default value is False.  By passing a\n                          True value, the call will iterate through all keys\n                          in the bucket and apply the same grant to each key.\n                          CAUTION: If you have a lot of keys, this could take\n                          a long time!"
  },
  {
    "code": "def search_reads(\n            self, read_group_ids, reference_id=None, start=None, end=None):\n        request = protocol.SearchReadsRequest()\n        request.read_group_ids.extend(read_group_ids)\n        request.reference_id = pb.string(reference_id)\n        request.start = pb.int(start)\n        request.end = pb.int(end)\n        request.page_size = pb.int(self._page_size)\n        return self._run_search_request(\n            request, \"reads\", protocol.SearchReadsResponse)",
    "docstring": "Returns an iterator over the Reads fulfilling the specified\n        conditions from the specified read_group_ids.\n\n        :param str read_group_ids: The IDs of the\n            :class:`ga4gh.protocol.ReadGroup` of interest.\n        :param str reference_id: The name of the\n            :class:`ga4gh.protocol.Reference` we wish to return reads\n            mapped to.\n        :param int start: The start position (0-based) of this query. If a\n            reference is specified, this defaults to 0. Genomic positions are\n            non-negative integers less than reference length. Requests spanning\n            the join of circular genomes are represented as two requests one on\n            each side of the join (position 0).\n        :param int end: The end position (0-based, exclusive) of this query.\n            If a reference is specified, this defaults to the reference's\n            length.\n        :return: An iterator over the\n            :class:`ga4gh.protocol.ReadAlignment` objects defined by\n            the query parameters.\n        :rtype: iter"
  },
  {
    "code": "def jing(rng_filepath, *xml_filepaths):\n    cmd = ['java', '-jar']\n    cmd.extend([str(JING_JAR), str(rng_filepath)])\n    for xml_filepath in xml_filepaths:\n        cmd.append(str(xml_filepath))\n    proc = subprocess.Popen(cmd,\n                            stdin=subprocess.PIPE,\n                            stdout=subprocess.PIPE,\n                            stderr=subprocess.PIPE,\n                            close_fds=True)\n    out, err = proc.communicate()\n    return _parse_jing_output(out.decode('utf-8'))",
    "docstring": "Run jing.jar using the RNG file against the given XML file."
  },
  {
    "code": "def generate_key(key_length=64):\n    if hasattr(random, 'SystemRandom'):\n        logging.info('Generating a secure random key using SystemRandom.')\n        choice = random.SystemRandom().choice\n    else:\n        msg = \"WARNING: SystemRandom not present. Generating a random \"\\\n              \"key using random.choice (NOT CRYPTOGRAPHICALLY SECURE).\"\n        logging.warning(msg)\n        choice = random.choice\n    return ''.join(map(lambda x: choice(string.digits + string.ascii_letters),\n                   range(key_length)))",
    "docstring": "Secret key generator.\n\n    The quality of randomness depends on operating system support,\n    see http://docs.python.org/library/random.html#random.SystemRandom."
  },
  {
    "code": "def _lookup_online(word):\n    URL = \"https://www.diki.pl/{word}\"\n    HEADERS = {\n        \"User-Agent\": (\n            \"Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; \"\n            \"Trident/7.0;  rv:11.0) like Gecko\"\n        )\n    }\n    logger.debug(\"Looking up online: %s\", word)\n    quoted_word = urllib.parse.quote(word)\n    req = urllib.request.Request(URL.format(word=quoted_word), headers=HEADERS)\n    with urllib.request.urlopen(req) as response:\n        html_string = response.read().decode()\n    return html.unescape(html_string)",
    "docstring": "Look up word on diki.pl.\n\n    Parameters\n    ----------\n    word : str\n        Word too look up.\n\n    Returns\n    -------\n    str\n        website HTML content."
  },
  {
    "code": "def read_from_hdx(identifier, configuration=None):\n        organization = Organization(configuration=configuration)\n        result = organization._load_from_hdx('organization', identifier)\n        if result:\n            return organization\n        return None",
    "docstring": "Reads the organization given by identifier from HDX and returns Organization object\n\n        Args:\n            identifier (str): Identifier of organization\n            configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration.\n\n        Returns:\n            Optional[Organization]: Organization object if successful read, None if not"
  },
  {
    "code": "def PYTHON_VERSION(stats, info):\n    version = sys.version.replace(' \\n', ' ').replace('\\n', ' ')\n    python = ';'.join([str(c) for c in sys.version_info] + [version])\n    info.append(('python', python))",
    "docstring": "Python interpreter version.\n\n    This is a flag you can pass to `Stats.submit()`."
  },
  {
    "code": "def get(self, key, default=miss):\n        if key not in self._dict:\n            return default\n        return self[key]",
    "docstring": "Return the value for given key if it exists."
  },
  {
    "code": "def construct(self, request_args=None, **kwargs):\n        if request_args is None:\n            request_args = {}\n        request_args, post_args = self.do_pre_construct(request_args,\n                                                        **kwargs)\n        if 'state' in self.msg_type.c_param and 'state' in kwargs:\n            if 'state' not in request_args:\n                request_args['state'] = kwargs['state']\n        _args = self.gather_request_args(**request_args)\n        request = self.msg_type(**_args)\n        return self.do_post_construct(request, **post_args)",
    "docstring": "Instantiate the request as a message class instance with\n        attribute values gathered in a pre_construct method or in the\n        gather_request_args method.\n\n        :param request_args:\n        :param kwargs: extra keyword arguments\n        :return: message class instance"
  },
  {
    "code": "def comment(self, body):\n        data = json.dumps({'body': body})\n        r = requests.post(\n            \"https://kippt.com/api/clips/%s/comments\" (self.id),\n            headers=self.kippt.header,\n            data=data\n        )\n        return (r.json())",
    "docstring": "Comment on a clip.\n\n        Parameters:\n        - body (Required)"
  },
  {
    "code": "def ismatch(a,b):\n    if a == b:\n        return True\n    else:\n        try:\n            if isinstance(a,b):\n                return True\n        except TypeError:\n            try:\n                if isinstance(b,a):\n                    return True\n            except TypeError:\n                try:\n                    if isinstance(a,type(b)):\n                        return True\n                except TypeError:\n                    try:\n                        if isinstance(b,type(a)):\n                            return True\n                    except TypeError:\n                        if str(a).lower() == str(b).lower():\n                            return True\n                        else:\n                            return False",
    "docstring": "Method to allow smart comparisons between classes, instances,\n    and string representations of units and give the right answer.\n    For internal use only."
  },
  {
    "code": "def destructuring_stmt_handle(self, original, loc, tokens):\n        internal_assert(len(tokens) == 2, \"invalid destructuring assignment tokens\", tokens)\n        matches, item = tokens\n        out = match_handle(loc, [matches, \"in\", item, None])\n        out += self.pattern_error(original, loc, match_to_var, match_check_var)\n        return out",
    "docstring": "Process match assign blocks."
  },
  {
    "code": "def _seconds_have_elapsed(token, num_seconds):\n  now = timeit.default_timer()\n  then = _log_timer_per_token.get(token, None)\n  if then is None or (now - then) >= num_seconds:\n    _log_timer_per_token[token] = now\n    return True\n  else:\n    return False",
    "docstring": "Tests if 'num_seconds' have passed since 'token' was requested.\n\n  Not strictly thread-safe - may log with the wrong frequency if called\n  concurrently from multiple threads. Accuracy depends on resolution of\n  'timeit.default_timer()'.\n\n  Always returns True on the first call for a given 'token'.\n\n  Args:\n    token: The token for which to look up the count.\n    num_seconds: The number of seconds to test for.\n\n  Returns:\n    Whether it has been >= 'num_seconds' since 'token' was last requested."
  },
  {
    "code": "def _FormatSocketUnixToken(self, token_data):\n    protocol = bsmtoken.BSM_PROTOCOLS.get(token_data.socket_family, 'UNKNOWN')\n    return {\n        'protocols': protocol,\n        'family': token_data.socket_family,\n        'path': token_data.socket_path}",
    "docstring": "Formats an Unix socket token as a dictionary of values.\n\n    Args:\n      token_data (bsm_token_data_sockunix): AUT_SOCKUNIX token data.\n\n    Returns:\n      dict[str, str]: token values."
  },
  {
    "code": "def _node_has_namespace_helper(node: BaseEntity, namespace: str) -> bool:\n        return namespace == node.get(NAMESPACE)",
    "docstring": "Check that the node has namespace information.\n\n        Might have cross references in future."
  },
  {
    "code": "def genUserCert(self, name, signas=None, outp=None, csr=None):\n        pkey, cert = self._genBasePkeyCert(name, pkey=csr)\n        cert.add_extensions([\n            crypto.X509Extension(b'nsCertType', False, b'client'),\n            crypto.X509Extension(b'keyUsage', False, b'digitalSignature'),\n            crypto.X509Extension(b'extendedKeyUsage', False, b'clientAuth'),\n            crypto.X509Extension(b'basicConstraints', False, b'CA:FALSE'),\n        ])\n        if signas is not None:\n            self.signCertAs(cert, signas)\n        else:\n            self.selfSignCert(cert, pkey)\n        crtpath = self._saveCertTo(cert, 'users', '%s.crt' % name)\n        if outp is not None:\n            outp.printf('cert saved: %s' % (crtpath,))\n        if not pkey._only_public:\n            keypath = self._savePkeyTo(pkey, 'users', '%s.key' % name)\n            if outp is not None:\n                outp.printf('key saved: %s' % (keypath,))\n        return pkey, cert",
    "docstring": "Generates a user keypair.\n\n        Args:\n            name (str): The name of the user keypair.\n            signas (str): The CA keypair to sign the new user keypair with.\n            outp (synapse.lib.output.Output): The output buffer.\n            csr (OpenSSL.crypto.PKey): The CSR public key when generating the keypair from a CSR.\n\n        Examples:\n            Generate a user cert for the user \"myuser\":\n\n                myuserkey, myusercert = cdir.genUserCert('myuser')\n\n        Returns:\n            ((OpenSSL.crypto.PKey, OpenSSL.crypto.X509)): Tuple containing the key and certificate objects."
  },
  {
    "code": "def simple_returns(prices):\n    if isinstance(prices, (pd.DataFrame, pd.Series)):\n        out = prices.pct_change().iloc[1:]\n    else:\n        out = np.diff(prices, axis=0)\n        np.divide(out, prices[:-1], out=out)\n    return out",
    "docstring": "Compute simple returns from a timeseries of prices.\n\n    Parameters\n    ----------\n    prices : pd.Series, pd.DataFrame or np.ndarray\n        Prices of assets in wide-format, with assets as columns,\n        and indexed by datetimes.\n\n    Returns\n    -------\n    returns : array-like\n        Returns of assets in wide-format, with assets as columns,\n        and index coerced to be tz-aware."
  },
  {
    "code": "def get_alpha_value(self):\n        if isinstance(self.__alpha_value, float) is False:\n            raise TypeError(\"The type of __alpha_value must be float.\")\n        return self.__alpha_value",
    "docstring": "getter\n        Learning rate."
  },
  {
    "code": "def _process_wave_param(self, pval):\n        return self._process_generic_param(\n            pval, self._internal_wave_unit, equivalencies=u.spectral())",
    "docstring": "Process individual model parameter representing wavelength."
  },
  {
    "code": "def validate_user_data(self, expected, actual, api_version=None):\n        self.log.debug('Validating user data...')\n        self.log.debug('actual: {}'.format(repr(actual)))\n        for e in expected:\n            found = False\n            for act in actual:\n                if e['name'] == act.name:\n                    a = {'enabled': act.enabled, 'name': act.name,\n                         'email': act.email, 'id': act.id}\n                    if api_version == 3:\n                        a['default_project_id'] = getattr(act,\n                                                          'default_project_id',\n                                                          'none')\n                    else:\n                        a['tenantId'] = act.tenantId\n                    found = True\n                    ret = self._validate_dict_data(e, a)\n                    if ret:\n                        return \"unexpected user data - {}\".format(ret)\n            if not found:\n                return \"user {} does not exist\".format(e['name'])\n        return ret",
    "docstring": "Validate user data.\n\n           Validate a list of actual user data vs a list of expected user\n           data."
  },
  {
    "code": "def loadcsv(filename):\n    dataframe = _pd.read_csv(filename)\n    data = {}\n    for key, value in dataframe.items():\n        data[key] = value.values\n    return data",
    "docstring": "Load data from CSV file.\n\n    Returns a single dict with column names as keys."
  },
  {
    "code": "def invitations(self):\n        url = \"%s/invitations\" % self.root\n        return Invitations(url=url,\n                           securityHandler=self._securityHandler,\n                           proxy_url=self._proxy_url,\n                           proxy_port=self._proxy_port)",
    "docstring": "returns a class to access the current user's invitations"
  },
  {
    "code": "def _force_read(\n        self,\n        element,\n        value,\n        text_prefix_before,\n        text_suffix_before,\n        text_prefix_after,\n        text_suffix_after,\n        data_of\n    ):\n        if (text_prefix_before) or (text_suffix_before):\n            text_before = text_prefix_before + value + text_suffix_before\n        else:\n            text_before = ''\n        if (text_prefix_after) or (text_suffix_after):\n            text_after = text_prefix_after + value + text_suffix_after\n        else:\n            text_after = ''\n        self._force_read_simple(element, text_before, text_after, data_of)",
    "docstring": "Force the screen reader display an information of element with prefixes\n        or suffixes.\n\n        :param element: The reference element.\n        :type element: hatemile.util.html.htmldomelement.HTMLDOMElement\n        :param value: The value to be show.\n        :type value: str\n        :param text_prefix_before: The prefix of value to show before the\n                                   element.\n        :type text_prefix_before: str\n        :param text_suffix_before: The suffix of value to show before the\n                                   element.\n        :type text_suffix_before: str\n        :param text_prefix_after: The prefix of value to show after the\n                                  element.\n        :type text_prefix_after: str\n        :param text_suffix_after: The suffix of value to show after the\n                                  element.\n        :type text_suffix_after: str\n        :param data_of: The name of attribute that links the content with\n                        element.\n        :type data_of: str"
  },
  {
    "code": "def temperature(self, what):\n        self._temperature = units.validate_quantity(what, u.K)",
    "docstring": "Set temperature."
  },
  {
    "code": "def _populate_input_for_name_id(self, config, record, context, data):\n        user_id = \"\"\n        user_id_from_attrs = config['user_id_from_attrs']\n        for attr in user_id_from_attrs:\n            if attr in record[\"attributes\"]:\n                value = record[\"attributes\"][attr]\n                if isinstance(value, list):\n                    value.sort()\n                    user_id += \"\".join(value)\n                    satosa_logging(\n                        logger,\n                        logging.DEBUG,\n                        \"Added attribute {} with values {} to input for NameID\".format(attr, value),\n                        context.state\n                        )\n                else:\n                    user_id += value\n                    satosa_logging(\n                        logger,\n                        logging.DEBUG,\n                        \"Added attribute {} with value {} to input for NameID\".format(attr, value),\n                        context.state\n                        )\n        if not user_id:\n            satosa_logging(\n                logger,\n                logging.WARNING,\n                \"Input for NameID is empty so not overriding default\",\n                context.state\n                )\n        else:\n            data.subject_id = user_id\n            satosa_logging(\n                logger,\n                logging.DEBUG,\n                \"Input for NameID is {}\".format(data.subject_id),\n                context.state\n                )",
    "docstring": "Use a record found in LDAP to populate input for\n        NameID generation."
  },
  {
    "code": "def main():\n    reporter = BugReporter()\n    print(\"JSON report:\")\n    print(reporter.as_json())\n    print()\n    print(\"Markdown report:\")\n    print(reporter.as_markdown())\n    print(\"SQL report:\")\n    print(reporter.as_sql())\n    print(\"Choose the appropriate format (if you're submitting a Github Issue \"\n          \"please chose the Markdown report) and paste it!\")",
    "docstring": "Pretty-print the bug information as JSON"
  },
  {
    "code": "def has_value(obj, name):\n  if obj is None:\n    return (False, None)\n  elif isinstance(obj, dict):\n    return (name in obj, obj.get(name))\n  elif hasattr(obj, name):\n    return (True, getattr(obj, name))\n  elif hasattr(obj, \"__getitem__\") and hasattr(obj, \"__contains__\") and name in obj:\n    return (True, obj[name])\n  else:\n    return (False, None)",
    "docstring": "A flexible method for getting values from objects by name.\n\n  returns:\n  - obj is None: (False, None)\n  - obj is dict: (name in obj, obj.get(name))\n  - obj hasattr(name): (True, getattr(obj, name))\n  - else: (False, None)\n\n  :obj: the object to pull values from\n  :name: the name to use when getting the value"
  },
  {
    "code": "def get_col_rgba(color, transparency=None, opacity=None):\n    r, g, b = color.red, color.green, color.blue\n    r /= 65535.\n    g /= 65535.\n    b /= 65535.\n    if transparency is not None or opacity is None:\n        transparency = 0 if transparency is None else transparency\n        if transparency < 0 or transparency > 1:\n            raise ValueError(\"Transparency must be between 0 and 1\")\n        alpha = 1 - transparency\n    else:\n        if opacity < 0 or opacity > 1:\n            raise ValueError(\"Opacity must be between 0 and 1\")\n        alpha = opacity\n    return r, g, b, alpha",
    "docstring": "This class converts a Gdk.Color into its r, g, b parts and adds an alpha according to needs\n\n    If both transparency and opacity is None, alpha is set to 1 => opaque\n\n    :param Gdk.Color color: Color to extract r, g and b from\n    :param float | None  transparency: Value between 0 (opaque) and 1 (transparent) or None if opacity is to be used\n    :param float | None opacity: Value between 0 (transparent) and 1 (opaque) or None if transparency is to be used\n    :return: Red, Green, Blue and Alpha value (all between 0.0 - 1.0)"
  },
  {
    "code": "def _group_cluster(self, clusters, adj_list, counts):\n        groups = []\n        for cluster in clusters:\n            groups.append(sorted(cluster, key=lambda x: counts[x],\n                                 reverse=True))\n        return groups",
    "docstring": "return groups for cluster or directional methods"
  },
  {
    "code": "def set_stage_for_epoch(self, epoch_start, name, attr='stage', save=True):\n        if self.rater is None:\n            raise IndexError('You need to have at least one rater')\n        for one_epoch in self.rater.iterfind('stages/epoch'):\n            if int(one_epoch.find('epoch_start').text) == epoch_start:\n                one_epoch.find(attr).text = name\n                if save:\n                    self.save()\n                return\n        raise KeyError('epoch starting at ' + str(epoch_start) + ' not found')",
    "docstring": "Change the stage for one specific epoch.\n\n        Parameters\n        ----------\n        epoch_start : int\n            start time of the epoch, in seconds\n        name : str\n            description of the stage or qualifier.\n        attr : str, optional\n            either 'stage' or 'quality'\n        save : bool\n            whether to save every time one epoch is scored\n\n        Raises\n        ------\n        KeyError\n            When the epoch_start is not in the list of epochs.\n        IndexError\n            When there is no rater / epochs at all\n\n        Notes\n        -----\n        In the GUI, you want to save as often as possible, even if it slows\n        down the program, but it's the safer option. But if you're converting\n        a dataset, you want to save at the end. Do not forget to save!"
  },
  {
    "code": "def w(msg, *args, **kwargs):\n    return logging.log(WARN, msg, *args, **kwargs)",
    "docstring": "log a message at warn level;"
  },
  {
    "code": "def xpointerNewRange(self, startindex, end, endindex):\n        if end is None: end__o = None\n        else: end__o = end._o\n        ret = libxml2mod.xmlXPtrNewRange(self._o, startindex, end__o, endindex)\n        if ret is None:raise treeError('xmlXPtrNewRange() failed')\n        return xpathObjectRet(ret)",
    "docstring": "Create a new xmlXPathObjectPtr of type range"
  },
  {
    "code": "def get_crime_categories(self, date=None):\n        return sorted(self._get_crime_categories(date=date).values(),\n                      key=lambda c: c.name)",
    "docstring": "Get a list of crime categories, valid for a particular date. Uses the\n        crime-categories_ API call.\n\n        .. _crime-categories:\n            https://data.police.uk/docs/method/crime-categories/\n\n        :rtype: list\n        :param date: The date of the crime categories to get.\n        :type date: str or None\n        :return: A ``list`` of crime categories which are valid at the\n                 specified date (or at the latest date, if ``None``)."
  },
  {
    "code": "def compare_filesystems(fs0, fs1, concurrent=False):\n    if concurrent:\n        future0 = concurrent_hash_filesystem(fs0)\n        future1 = concurrent_hash_filesystem(fs1)\n        files0 = future0.result()\n        files1 = future1.result()\n    else:\n        files0 = hash_filesystem(fs0)\n        files1 = hash_filesystem(fs1)\n    return file_comparison(files0, files1)",
    "docstring": "Compares the two given filesystems.\n\n    fs0 and fs1 are two mounted GuestFS instances\n    containing the two disks to be compared.\n\n    If the concurrent flag is True,\n    two processes will be used speeding up the comparison on multiple CPUs.\n\n    Returns a dictionary containing files created, removed and modified.\n\n        {'created_files': [<files in fs1 and not in fs0>],\n         'deleted_files': [<files in fs0 and not in fs1>],\n         'modified_files': [<files in both fs0 and fs1 but different>]}"
  },
  {
    "code": "def modify_model_backprop(model, backprop_modifier):\n    modified_model = _MODIFIED_MODEL_CACHE.get((model, backprop_modifier))\n    if modified_model is not None:\n        return modified_model\n    model_path = os.path.join(tempfile.gettempdir(), next(tempfile._get_candidate_names()) + '.h5')\n    try:\n        model.save(model_path)\n        modifier_fn = _BACKPROP_MODIFIERS.get(backprop_modifier)\n        if modifier_fn is None:\n            raise ValueError(\"'{}' modifier is not supported\".format(backprop_modifier))\n        modifier_fn(backprop_modifier)\n        with tf.get_default_graph().gradient_override_map({'Relu': backprop_modifier}):\n            modified_model = load_model(model_path)\n            _MODIFIED_MODEL_CACHE[(model, backprop_modifier)] = modified_model\n            return modified_model\n    finally:\n        os.remove(model_path)",
    "docstring": "Creates a copy of model by modifying all activations to use a custom op to modify the backprop behavior.\n\n    Args:\n        model:  The `keras.models.Model` instance.\n        backprop_modifier: One of `{'guided', 'rectified'}`\n\n    Returns:\n        A copy of model with modified activations for backwards pass."
  },
  {
    "code": "def _producer_wrapper(f, port, addr='tcp://127.0.0.1'):\n    try:\n        context = zmq.Context()\n        socket = context.socket(zmq.PUSH)\n        socket.connect(':'.join([addr, str(port)]))\n        f(socket)\n    finally:\n        context.destroy()",
    "docstring": "A shim that sets up a socket and starts the producer callable.\n\n    Parameters\n    ----------\n    f : callable\n        Callable that takes a single argument, a handle\n        for a ZeroMQ PUSH socket. Must be picklable.\n    port : int\n        The port on which the socket should connect.\n    addr : str, optional\n        Address to which the socket should connect. Defaults\n        to localhost ('tcp://127.0.0.1')."
  },
  {
    "code": "def backward(heads, head_grads=None, retain_graph=False, train_mode=True):\n    head_handles, hgrad_handles = _parse_head(heads, head_grads)\n    check_call(_LIB.MXAutogradBackwardEx(\n        len(head_handles),\n        head_handles,\n        hgrad_handles,\n        0,\n        ctypes.c_void_p(0),\n        ctypes.c_int(retain_graph),\n        ctypes.c_int(0),\n        ctypes.c_int(train_mode),\n        ctypes.c_void_p(0),\n        ctypes.c_void_p(0)))",
    "docstring": "Compute the gradients of heads w.r.t previously marked variables.\n\n    Parameters\n    ----------\n    heads: NDArray or list of NDArray\n        Output NDArray(s)\n    head_grads: NDArray or list of NDArray or None\n        Gradients with respect to heads.\n    train_mode: bool, optional\n        Whether to do backward for training or predicting."
  },
  {
    "code": "def register_single(key, value, param=None):\n    get_current_scope().container.register(key, lambda: value, param)",
    "docstring": "Generates resolver to return singleton value and adds it to global container"
  },
  {
    "code": "def format_warning_oneline(message, category, filename, lineno,\n                           file=None, line=None):\n    return ('{category}: {message}'\n            .format(message=message, category=category.__name__))",
    "docstring": "Format a warning for logging.\n\n    The returned value should be a single-line string, for better\n    logging style (although this is not enforced by the code).\n\n    This methods' arguments have the same meaning of the\n    like-named arguments from `warnings.formatwarning`."
  },
  {
    "code": "def create_attr_obj(self, protocol_interface, phy_interface):\n        self.intf_attr[protocol_interface] = TopoIntfAttr(\n            protocol_interface, phy_interface)\n        self.store_obj(protocol_interface, self.intf_attr[protocol_interface])",
    "docstring": "Creates the local interface attribute object and stores it."
  },
  {
    "code": "def bind(self, environment):\n        rv = object.__new__(self.__class__)\n        rv.__dict__.update(self.__dict__)\n        rv.environment = environment\n        return rv",
    "docstring": "Create a copy of this extension bound to another environment."
  },
  {
    "code": "def complete(self, nextq=None, delay=None, depends=None):\n        if nextq:\n            logger.info('Advancing %s to %s from %s',\n                self.jid, nextq, self.queue_name)\n            return self.client('complete', self.jid, self.client.worker_name,\n                self.queue_name, json.dumps(self.data), 'next', nextq,\n                'delay', delay or 0, 'depends',\n                json.dumps(depends or [])) or False\n        else:\n            logger.info('Completing %s', self.jid)\n            return self.client('complete', self.jid, self.client.worker_name,\n                self.queue_name, json.dumps(self.data)) or False",
    "docstring": "Turn this job in as complete, optionally advancing it to another\n        queue. Like ``Queue.put`` and ``move``, it accepts a delay, and\n        dependencies"
  },
  {
    "code": "def create_config(config_path=\"scriptworker.yaml\"):\n    if not os.path.exists(config_path):\n        print(\"{} doesn't exist! Exiting...\".format(config_path), file=sys.stderr)\n        sys.exit(1)\n    with open(config_path, \"r\", encoding=\"utf-8\") as fh:\n        secrets = safe_load(fh)\n    config = dict(deepcopy(DEFAULT_CONFIG))\n    if not secrets.get(\"credentials\"):\n        secrets['credentials'] = read_worker_creds()\n    config.update(secrets)\n    apply_product_config(config)\n    messages = check_config(config, config_path)\n    if messages:\n        print('\\n'.join(messages), file=sys.stderr)\n        print(\"Exiting...\", file=sys.stderr)\n        sys.exit(1)\n    credentials = get_frozen_copy(secrets['credentials'])\n    del(config['credentials'])\n    config = get_frozen_copy(config)\n    return config, credentials",
    "docstring": "Create a config from DEFAULT_CONFIG, arguments, and config file.\n\n    Then validate it and freeze it.\n\n    Args:\n        config_path (str, optional): the path to the config file.  Defaults to\n            \"scriptworker.yaml\"\n\n    Returns:\n        tuple: (config frozendict, credentials dict)\n\n    Raises:\n        SystemExit: on failure"
  },
  {
    "code": "def diff(ctx, branch):\n    diff = GitDiffReporter(branch)\n    regions = diff.changed_intervals()\n    _report_from_regions(regions, ctx.obj, file_factory=diff.old_file)",
    "docstring": "Determine which tests intersect a git diff."
  },
  {
    "code": "def _flip_feature(self, feature, parent_len):\n    copy = feature.copy()\n    if copy.strand == 0:\n        copy.strand = 1\n    else:\n        copy.strand = 0\n    copy.start = parent_len - copy.start\n    copy.stop = parent_len - copy.stop\n    copy.start, copy.stop = copy.stop, copy.start\n    return copy",
    "docstring": "Adjust a feature's location when flipping DNA.\n\n    :param feature: The feature to flip.\n    :type feature: coral.Feature\n    :param parent_len: The length of the sequence to which the feature belongs.\n    :type parent_len: int"
  },
  {
    "code": "def clear_diagram(self, diagram):\n        plot = self.subplots[diagram[1]][diagram[0]]\n        plot.cla()",
    "docstring": "Clear diagram.\n\n        Parameters\n        ----------\n        diagram : [column, row]\n            Diagram to clear."
  },
  {
    "code": "def get_analytic(user, job_id, anc_id):\n    v1_utils.verify_existence_and_get(job_id, models.JOBS)\n    analytic = v1_utils.verify_existence_and_get(anc_id, _TABLE)\n    analytic = dict(analytic)\n    if not user.is_in_team(analytic['team_id']):\n        raise dci_exc.Unauthorized()\n    return flask.jsonify({'analytic': analytic})",
    "docstring": "Get an analytic."
  },
  {
    "code": "def check_token_file(self):\n        warnings.warn('This method will be removed in future versions',\n                      DeprecationWarning)\n        return self.token_backend.check_token() if hasattr(self.token_backend, 'check_token') else None",
    "docstring": "Checks if the token file exists at the given position\n\n        :return: if file exists or not\n        :rtype: bool"
  },
  {
    "code": "def process_from_splash(self):\n        for software in self._softwares_from_splash:\n            plugin = self._plugins.get(software['name'])\n            try:\n                additional_data = {'version': software['version']}\n            except KeyError:\n                additional_data = {'type': INDICATOR_TYPE}\n            self._results.add_result(\n                Result(\n                    name=plugin.name,\n                    homepage=plugin.homepage,\n                    from_url=self.requested_url,\n                    plugin=plugin.name,\n                    **additional_data,\n                )\n            )\n            for hint in self.get_hints(plugin):\n                self._results.add_result(hint)",
    "docstring": "Add softwares found in the DOM"
  },
  {
    "code": "def send(sender_instance):\n    m = Mailin(\n        \"https://api.sendinblue.com/v2.0\",\n        sender_instance._kwargs.get(\"api_key\")\n    )\n    data = {\n        \"to\": email_list_to_email_dict(sender_instance._recipient_list),\n        \"cc\": email_list_to_email_dict(sender_instance._cc),\n        \"bcc\": email_list_to_email_dict(sender_instance._bcc),\n        \"from\": email_address_to_list(sender_instance._from_email),\n        \"subject\": sender_instance._subject,\n    }\n    if sender_instance._template.is_html:\n        data.update({\n            \"html\": sender_instance._message,\n            \"headers\": {\"Content-Type\": \"text/html; charset=utf-8\"}\n        })\n    else:\n        data.update({\"text\": sender_instance._message})\n    if \"attachments\" in sender_instance._kwargs:\n        data[\"attachment\"] = {}\n        for attachment in sender_instance._kwargs[\"attachments\"]:\n            data[\"attachment\"][attachment[0]] = base64.b64encode(attachment[1])\n    result = m.send_email(data)\n    if result[\"code\"] != \"success\":\n        raise SendInBlueError(result[\"message\"])",
    "docstring": "Send a transactional email using SendInBlue API.\n\n    Site: https://www.sendinblue.com\n    API: https://apidocs.sendinblue.com/"
  },
  {
    "code": "def cmd(send, msg, _):\n    try:\n        answer = subprocess.check_output(['wtf', msg], stderr=subprocess.STDOUT)\n        send(answer.decode().strip().replace('\\n', ' or ').replace('fuck', 'fsck'))\n    except subprocess.CalledProcessError as ex:\n        send(ex.output.decode().rstrip().splitlines()[0])",
    "docstring": "Tells you what acronyms mean.\n\n    Syntax: {command} <term>"
  },
  {
    "code": "def finite_datetimes(self, finite_start, finite_stop):\n        date_start = datetime(finite_start.year, finite_start.month, finite_start.day)\n        dates = []\n        for i in itertools.count():\n            t = date_start + timedelta(days=i)\n            if t >= finite_stop:\n                return dates\n            if t >= finite_start:\n                dates.append(t)",
    "docstring": "Simply returns the points in time that correspond to turn of day."
  },
  {
    "code": "def parse_args(options={}, *args, **kwds):\n    parser_options = ParserOptions(options)\n    parser_input = ParserInput(args, kwds)\n    parser = Parser(parser_options, parser_input)\n    parser.parse()\n    return parser.output_data",
    "docstring": "Parser of arguments.\n\n    dict options {\n        int min_items: Min of required items to fold one tuple. (default: 1)\n        int max_items: Count of items in one tuple. Last `max_items-min_items`\n            items is by default set to None. (default: 1)\n        bool allow_dict: Flag allowing dictionary as first (and only one)\n            argument or dictinary as **kwds. (default: False)\n        bool allow_list: Flag allowing list as first (and only one) argument.\n            (default: False)\n    }\n\n    Examples:\n\n    calling with min_items=1, max_items=2, allow_dict=False:\n        arg1, arg2              => ((arg1, None), (arg2, None))\n        (arg1a, arg1b), arg2    => ((arg1a, arg1b), arg2, None))\n        arg1=val1               => FAIL\n        {key1: val1}            => FAIL\n\n    calling with min_items=2, max_items=3, allow_dict=True:\n        arg1, arg2              => ((arg1, arg2, None),)\n        arg1, arg2, arg3        => ((arg1, arg2, arg3),)\n        (arg1a, arg1b, arg1c)   => ((arg1a, arg1b, arg1c),)\n        arg1=val1, arg2=val2    => ((arg1, val1, None), (arg2, val2, None))\n        {key1: val1, key2: val2} => ((key1, val1, None), (key2, val2, None))\n        (arg1a, arg1b), arg2a, arg2b => FAIL"
  },
  {
    "code": "def get_ptr(data, offset=None, ptr_type=ctypes.c_void_p):\n    ptr = ctypes.cast(ctypes.pointer(data), ctypes.c_void_p)\n    if offset:\n        ptr = ctypes.c_void_p(ptr.value + offset)\n    if ptr_type != ctypes.c_void_p:\n        ptr = ctypes.cast(ptr, ptr_type)\n    return ptr",
    "docstring": "Returns a void pointer to the data"
  },
  {
    "code": "def tex_eps_emitter(target, source, env):\n    (target, source) = tex_emitter_core(target, source, env, TexGraphics)\n    return (target, source)",
    "docstring": "An emitter for TeX and LaTeX sources when\n    executing tex or latex. It will accept .ps and .eps\n    graphics files"
  },
  {
    "code": "def send(self, request_id, payload):\n        log.debug(\"About to send %d bytes to Kafka, request %d\" % (len(payload), request_id))\n        if not self._sock:\n            self.reinit()\n        try:\n            self._sock.sendall(payload)\n        except socket.error:\n            log.exception('Unable to send payload to Kafka')\n            self._raise_connection_error()",
    "docstring": "Send a request to Kafka\n\n        Arguments::\n            request_id (int): can be any int (used only for debug logging...)\n            payload: an encoded kafka packet (see KafkaProtocol)"
  },
  {
    "code": "def src_file(self):\n        try:\n            src_uri = (curl[Gentoo._LATEST_TXT] | tail[\"-n\", \"+3\"]\n                       | cut[\"-f1\", \"-d \"])().strip()\n        except ProcessExecutionError as proc_ex:\n            src_uri = \"NOT-FOUND\"\n            LOG.error(\"Could not determine latest stage3 src uri: %s\",\n                      str(proc_ex))\n        return src_uri",
    "docstring": "Get the latest src_uri for a stage 3 tarball.\n\n        Returns (str):\n            Latest src_uri from gentoo's distfiles mirror."
  },
  {
    "code": "def to_json(self, indent=4):\n        agregate = {\n            'metas': self.metas,\n        }\n        agregate.update({k: getattr(self, k) for k in self._rule_attrs})\n        return json.dumps(agregate, indent=indent)",
    "docstring": "Serialize metas and reference attributes to a JSON string.\n\n        Keyword Arguments:\n            indent (int): Space indentation, default to ``4``.\n\n        Returns:\n            string: JSON datas."
  },
  {
    "code": "def cli_main():\n    if '--debug' in sys.argv:\n        LOG.setLevel(logging.DEBUG)\n    elif '--verbose' in sys.argv:\n        LOG.setLevel(logging.INFO)\n    args = _get_arguments()\n    try:\n        plugin, folder = get_plugin_and_folder(\n            inputzip=args.inputzip,\n            inputdir=args.inputdir,\n            inputfile=args.inputfile)\n        LOG.debug('Plugin: %s -- Folder: %s' % (plugin.name, folder))\n        run_mq2(\n            plugin, folder, lod_threshold=args.lod, session=args.session)\n    except MQ2Exception as err:\n        print(err)\n        return 1\n    return 0",
    "docstring": "Main function when running from CLI."
  },
  {
    "code": "def trigger_deleted(self, filepath):\n        if not os.path.exists(filepath):\n            self._trigger('deleted', filepath)",
    "docstring": "Triggers deleted event if the flie doesn't exist."
  },
  {
    "code": "def get_seq_number_from_id(id, id_template, prefix, **kw):\n    separator = kw.get(\"separator\", \"-\")\n    postfix = id.replace(prefix, \"\").strip(separator)\n    postfix_segments = postfix.split(separator)\n    seq_number = 0\n    possible_seq_nums = filter(lambda n: n.isalnum(), postfix_segments)\n    if possible_seq_nums:\n        seq_number = possible_seq_nums[-1]\n    seq_number = get_alpha_or_number(seq_number, id_template)\n    seq_number = to_int(seq_number)\n    return seq_number",
    "docstring": "Return the sequence number of the given ID"
  },
  {
    "code": "def delete(self, filething=None):\n        if self.tags is not None:\n            temp_blocks = [\n                b for b in self.metadata_blocks if b.code != VCFLACDict.code]\n            self._save(filething, temp_blocks, False, padding=lambda x: 0)\n            self.metadata_blocks[:] = [\n                b for b in self.metadata_blocks\n                if b.code != VCFLACDict.code or b is self.tags]\n            self.tags.clear()",
    "docstring": "Remove Vorbis comments from a file.\n\n        If no filename is given, the one most recently loaded is used."
  },
  {
    "code": "def _format_years(years):\n    def sub(x):\n        return x[1] - x[0]\n    ranges = []\n    for k, iterable in groupby(enumerate(sorted(years)), sub):\n        rng = list(iterable)\n        if len(rng) == 1:\n            s = str(rng[0][1])\n        else:\n            s = \"{}-{}\".format(rng[0][1], rng[-1][1])\n        ranges.append(s)\n    return \", \".join(ranges)",
    "docstring": "Format a list of ints into a string including ranges\n\n    Source: https://stackoverflow.com/a/9471386/1307974"
  },
  {
    "code": "def call(self, name, *args, **kwargs):\n        return self.client.call(self.name, name, *args, **kwargs)",
    "docstring": "Make a SoftLayer API call\n\n        :param service: the name of the SoftLayer API service\n        :param method: the method to call on the service\n        :param \\\\*args: same optional arguments that ``BaseClient.call`` takes\n        :param \\\\*\\\\*kwargs: same optional keyword arguments that\n                           ``BaseClient.call`` takes\n\n        :param service: the name of the SoftLayer API service\n\n        Usage:\n            >>> import SoftLayer\n            >>> client = SoftLayer.create_client_from_env()\n            >>> client['Account'].getVirtualGuests(mask=\"id\", limit=10)\n            [...]"
  },
  {
    "code": "def make_request(self, session, url, **kwargs):\n        log.debug('Making request: GET %s %s' % (url, kwargs))\n        return session.get(url, **kwargs)",
    "docstring": "Make a HTTP GET request.\n\n        :param url: The URL to get.\n        :returns: The response to the request.\n        :rtype: requests.Response"
  },
  {
    "code": "def __make_request_headers(self, teststep_dict, entry_json):\n        teststep_headers = {}\n        for header in entry_json[\"request\"].get(\"headers\", []):\n            if header[\"name\"].lower() in IGNORE_REQUEST_HEADERS:\n                continue\n            teststep_headers[header[\"name\"]] = header[\"value\"]\n        if teststep_headers:\n            teststep_dict[\"request\"][\"headers\"] = teststep_headers",
    "docstring": "parse HAR entry request headers, and make teststep headers.\n            header in IGNORE_REQUEST_HEADERS will be ignored.\n\n        Args:\n            entry_json (dict):\n                {\n                    \"request\": {\n                        \"headers\": [\n                            {\"name\": \"Host\", \"value\": \"httprunner.top\"},\n                            {\"name\": \"Content-Type\", \"value\": \"application/json\"},\n                            {\"name\": \"User-Agent\", \"value\": \"iOS/10.3\"}\n                        ],\n                    },\n                    \"response\": {}\n                }\n\n        Returns:\n            {\n                \"request\": {\n                    headers: {\"Content-Type\": \"application/json\"}\n            }"
  },
  {
    "code": "def join_cluster(host, user='rabbit', ram_node=None, runas=None):\n    cmd = [RABBITMQCTL, 'join_cluster']\n    if ram_node:\n        cmd.append('--ram')\n    cmd.append('{0}@{1}'.format(user, host))\n    if runas is None and not salt.utils.platform.is_windows():\n        runas = salt.utils.user.get_user()\n    stop_app(runas)\n    res = __salt__['cmd.run_all'](cmd, reset_system_locale=False, runas=runas, python_shell=False)\n    start_app(runas)\n    return _format_response(res, 'Join')",
    "docstring": "Join a rabbit cluster\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rabbitmq.join_cluster rabbit.example.com rabbit"
  },
  {
    "code": "def load_variable(self, var=None, start_date=None, end_date=None,\n                      time_offset=None, grid_attrs=None, **DataAttrs):\n        file_set = self._generate_file_set(var=var, start_date=start_date,\n                                           end_date=end_date, **DataAttrs)\n        ds = _load_data_from_disk(\n            file_set, self.preprocess_func, data_vars=self.data_vars,\n            coords=self.coords, start_date=start_date, end_date=end_date,\n            time_offset=time_offset, grid_attrs=grid_attrs, **DataAttrs\n        )\n        if var.def_time:\n            ds = _prep_time_data(ds)\n            start_date = times.maybe_convert_to_index_date_type(\n                ds.indexes[TIME_STR], start_date)\n            end_date = times.maybe_convert_to_index_date_type(\n                ds.indexes[TIME_STR], end_date)\n        ds = set_grid_attrs_as_coords(ds)\n        da = _sel_var(ds, var, self.upcast_float32)\n        if var.def_time:\n            da = self._maybe_apply_time_shift(da, time_offset, **DataAttrs)\n            return times.sel_time(da, start_date, end_date).load()\n        else:\n            return da.load()",
    "docstring": "Load a DataArray for requested variable and time range.\n\n        Automatically renames all grid attributes to match aospy conventions.\n\n        Parameters\n        ----------\n        var : Var\n            aospy Var object\n        start_date : datetime.datetime\n            start date for interval\n        end_date : datetime.datetime\n            end date for interval\n        time_offset : dict\n            Option to add a time offset to the time coordinate to correct for\n            incorrect metadata.\n        grid_attrs : dict (optional)\n            Overriding dictionary of grid attributes mapping aospy internal\n            names to names of grid attributes used in a particular model.\n        **DataAttrs\n            Attributes needed to identify a unique set of files to load from\n\n        Returns\n        -------\n        da : DataArray\n             DataArray for the specified variable, date range, and interval in"
  },
  {
    "code": "def InsertIntArg(self, string='', **unused_kwargs):\n    try:\n      int_value = int(string)\n    except (TypeError, ValueError):\n      raise errors.ParseError('{0:s} is not a valid integer.'.format(string))\n    return self.InsertArg(int_value)",
    "docstring": "Inserts an Integer argument."
  },
  {
    "code": "def _CreateTaskStorageWriter(self, path, task):\n    return SQLiteStorageFileWriter(\n        self._session, path,\n        storage_type=definitions.STORAGE_TYPE_TASK, task=task)",
    "docstring": "Creates a task storage writer.\n\n    Args:\n      path (str): path to the storage file.\n      task (Task): task.\n\n    Returns:\n      SQLiteStorageFileWriter: storage writer."
  },
  {
    "code": "def _containing_contigs(self, hits):\n        return {hit.ref_name for hit in hits if self._contains(hit)}",
    "docstring": "Given a list of hits, all with same query,\n           returns a set of the contigs containing that query"
  },
  {
    "code": "def selection_pos(self):\n        buff = self._vim.current.buffer\n        beg = buff.mark('<')\n        end = buff.mark('>')\n        return beg, end",
    "docstring": "Return start and end positions of the visual selection respectively."
  },
  {
    "code": "def get_value_in_base_currency(self) -> Decimal:\n        amt_orig = self.get_value()\n        sec_cur = self.get_currency()\n        cur_svc = CurrenciesAggregate(self.book)\n        base_cur = cur_svc.get_default_currency()\n        if sec_cur == base_cur:\n            return amt_orig\n        single_svc = cur_svc.get_currency_aggregate(sec_cur)\n        rate = single_svc.get_latest_rate(base_cur)\n        result = amt_orig * rate.value\n        return result",
    "docstring": "Calculates the value of security holdings in base currency"
  },
  {
    "code": "def _merge_multi_context(outputs, major_axis):\n    rets = []\n    for tensors, axis in zip(outputs, major_axis):\n        if axis >= 0:\n            if len(tensors) == 1:\n                rets.append(tensors[0])\n            else:\n                rets.append(nd.concat(*[tensor.as_in_context(tensors[0].context)\n                                        for tensor in tensors],\n                                      dim=axis))\n        else:\n            rets.append(tensors[0])\n    return rets",
    "docstring": "Merge outputs that lives on multiple context into one, so that they look\n    like living on one context."
  },
  {
    "code": "def get_last_modified_unix_sec():\n    path = request.args.get(\"path\")\n    if path and os.path.isfile(path):\n        try:\n            last_modified = os.path.getmtime(path)\n            return jsonify({\"path\": path, \"last_modified_unix_sec\": last_modified})\n        except Exception as e:\n            return client_error({\"message\": \"%s\" % e, \"path\": path})\n    else:\n        return client_error({\"message\": \"File not found: %s\" % path, \"path\": path})",
    "docstring": "Get last modified unix time for a given file"
  },
  {
    "code": "def _retrieve_download_url():\n    try:\n        with urlopen(config['nrfa']['oh_json_url'], timeout=10) as f:\n            remote_config = json.loads(f.read().decode('utf-8'))\n        if remote_config['nrfa_url'].startswith('.'):\n            remote_config['nrfa_url'] = 'file:' + pathname2url(os.path.abspath(remote_config['nrfa_url']))\n        _update_nrfa_metadata(remote_config)\n        return remote_config['nrfa_url']\n    except URLError:\n        return config['nrfa']['url']",
    "docstring": "Retrieves download location for FEH data zip file from hosted json configuration file.\n\n    :return: URL for FEH data file\n    :rtype: str"
  },
  {
    "code": "def _as_array_or_item(data):\n    data = np.asarray(data)\n    if data.ndim == 0:\n        if data.dtype.kind == 'M':\n            data = np.datetime64(data, 'ns')\n        elif data.dtype.kind == 'm':\n            data = np.timedelta64(data, 'ns')\n    return data",
    "docstring": "Return the given values as a numpy array, or as an individual item if\n    it's a 0d datetime64 or timedelta64 array.\n\n    Importantly, this function does not copy data if it is already an ndarray -\n    otherwise, it will not be possible to update Variable values in place.\n\n    This function mostly exists because 0-dimensional ndarrays with\n    dtype=datetime64 are broken :(\n    https://github.com/numpy/numpy/issues/4337\n    https://github.com/numpy/numpy/issues/7619\n\n    TODO: remove this (replace with np.asarray) once these issues are fixed"
  },
  {
    "code": "def DviPdfPsFunction(XXXDviAction, target = None, source= None, env=None):\n    try:\n        abspath = source[0].attributes.path\n    except AttributeError :\n        abspath =  ''\n    saved_env = SCons.Scanner.LaTeX.modify_env_var(env, 'TEXPICTS', abspath)\n    result = XXXDviAction(target, source, env)\n    if saved_env is _null:\n        try:\n            del env['ENV']['TEXPICTS']\n        except KeyError:\n            pass\n    else:\n        env['ENV']['TEXPICTS'] = saved_env\n    return result",
    "docstring": "A builder for DVI files that sets the TEXPICTS environment\n       variable before running dvi2ps or dvipdf."
  },
  {
    "code": "def recover(\n        data: bytes,\n        signature: Signature,\n        hasher: Callable[[bytes], bytes] = eth_sign_sha3,\n) -> Address:\n    _hash = hasher(data)\n    if signature[-1] >= 27:\n        signature = Signature(signature[:-1] + bytes([signature[-1] - 27]))\n    try:\n        sig = keys.Signature(signature_bytes=signature)\n        public_key = keys.ecdsa_recover(message_hash=_hash, signature=sig)\n    except BadSignature as e:\n        raise InvalidSignature from e\n    return public_key.to_canonical_address()",
    "docstring": "eth_recover address from data hash and signature"
  },
  {
    "code": "def _calculate_edges(self):\n        left = self.specs.left_margin\n        left += (self.specs.label_width * (self._position[1] - 1))\n        if self.specs.column_gap:\n            left += (self.specs.column_gap * (self._position[1] - 1))\n        left *= mm\n        bottom = self.specs.sheet_height - self.specs.top_margin\n        bottom -= (self.specs.label_height * self._position[0])\n        if self.specs.row_gap:\n            bottom -= (self.specs.row_gap * (self._position[0] - 1))\n        bottom *= mm\n        return float(left), float(bottom)",
    "docstring": "Calculate edges of the current label. Not intended for external use."
  },
  {
    "code": "def bounds(self):\n        google_x, google_y = self.google\n        pixel_x_west, pixel_y_north = google_x * TILE_SIZE, google_y * TILE_SIZE\n        pixel_x_east, pixel_y_south = (google_x + 1) * TILE_SIZE, (google_y + 1) * TILE_SIZE\n        point_min = Point.from_pixel(pixel_x=pixel_x_west, pixel_y=pixel_y_south, zoom=self.zoom)\n        point_max = Point.from_pixel(pixel_x=pixel_x_east, pixel_y=pixel_y_north, zoom=self.zoom)\n        return point_min, point_max",
    "docstring": "Gets the bounds of a tile represented as the most west and south point and the most east and north point"
  },
  {
    "code": "def _bind_baremetal_port(self, context, segment):\n        port = context.current\n        vif_details = {\n            portbindings.VIF_DETAILS_VLAN: str(\n                segment[driver_api.SEGMENTATION_ID])\n        }\n        context.set_binding(segment[driver_api.ID],\n                            portbindings.VIF_TYPE_OTHER,\n                            vif_details,\n                            n_const.ACTIVE)\n        LOG.debug(\"AristaDriver: bound port info- port ID %(id)s \"\n                  \"on network %(network)s\",\n                  {'id': port['id'],\n                   'network': context.network.current['id']})\n        if port.get('trunk_details'):\n            self.trunk_driver.bind_port(port)\n        return True",
    "docstring": "Bind the baremetal port to the segment"
  },
  {
    "code": "async def sqsStats(self, *args, **kwargs):\n        return await self._makeApiCall(self.funcinfo[\"sqsStats\"], *args, **kwargs)",
    "docstring": "Statistics on the sqs queues\n\n        This method is only for debugging the ec2-manager\n\n        This method is ``experimental``"
  },
  {
    "code": "def modis1kmto250m(lons1km, lats1km, cores=1):\n    if cores > 1:\n        return _multi(modis1kmto250m, lons1km, lats1km, 10, cores)\n    cols1km = np.arange(1354)\n    cols250m = np.arange(1354 * 4) / 4.0\n    along_track_order = 1\n    cross_track_order = 3\n    lines = lons1km.shape[0]\n    rows1km = np.arange(lines)\n    rows250m = (np.arange(lines * 4) - 1.5) / 4.0\n    satint = SatelliteInterpolator((lons1km, lats1km),\n                                   (rows1km, cols1km),\n                                   (rows250m, cols250m),\n                                   along_track_order,\n                                   cross_track_order,\n                                   chunk_size=40)\n    satint.fill_borders(\"y\", \"x\")\n    lons250m, lats250m = satint.interpolate()\n    return lons250m, lats250m",
    "docstring": "Getting 250m geolocation for modis from 1km tiepoints.\n\n    http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation"
  },
  {
    "code": "def list_devices():\n    output = {}\n    for device_id, device in devices.items():\n        output[device_id] = {\n            'host': device.host,\n            'state': device.state\n        }\n    return jsonify(devices=output)",
    "docstring": "List devices via HTTP GET."
  },
  {
    "code": "def _reset(self, load):\n        values = reduce(iadd, self._lists, [])\n        self._clear()\n        self._load = load\n        self._half = load >> 1\n        self._dual = load << 1\n        self._update(values)",
    "docstring": "Reset sorted list load.\n\n        The *load* specifies the load-factor of the list. The default load\n        factor of '1000' works well for lists from tens to tens of millions of\n        elements.  Good practice is to use a value that is the cube root of the\n        list size.  With billions of elements, the best load factor depends on\n        your usage.  It's best to leave the load factor at the default until\n        you start benchmarking."
  },
  {
    "code": "async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):\n        start = time.monotonic()\n        dumps = dumps_fn or self._serializer.dumps\n        ns_key = self.build_key(key, namespace=namespace)\n        await self._add(ns_key, dumps(value), ttl=self._get_ttl(ttl), _conn=_conn)\n        logger.debug(\"ADD %s %s (%.4f)s\", ns_key, True, time.monotonic() - start)\n        return True",
    "docstring": "Stores the value in the given key with ttl if specified. Raises an error if the\n        key already exists.\n\n        :param key: str\n        :param value: obj\n        :param ttl: int the expiration time in seconds. Due to memcached\n            restrictions if you want compatibility use int. In case you\n            need miliseconds, redis and memory support float ttls\n        :param dumps_fn: callable alternative to use as dumps function\n        :param namespace: str alternative namespace to use\n        :param timeout: int or float in seconds specifying maximum timeout\n            for the operations to last\n        :returns: True if key is inserted\n        :raises:\n            - ValueError if key already exists\n            - :class:`asyncio.TimeoutError` if it lasts more than self.timeout"
  },
  {
    "code": "def get_min_muO2(self, min_voltage=None, max_voltage=None):\n        data = []\n        for pair in self._select_in_voltage_range(min_voltage, max_voltage):\n            if pair.muO2_discharge is not None:\n                data.extend([d['chempot'] for d in pair.muO2_discharge])\n            if pair.muO2_charge is not None:\n                data.extend([d['chempot'] for d in pair.muO2_discharge])\n        return min(data) if len(data) > 0 else None",
    "docstring": "Minimum critical oxygen chemical potential along path.\n\n        Args:\n            min_voltage: The minimum allowable voltage for a given step\n            max_voltage: The maximum allowable voltage allowable for a given\n                step\n\n        Returns:\n            Minimum critical oxygen chemical of all compounds along the\n            insertion path (a subset of the path can be chosen by the optional\n            arguments)."
  },
  {
    "code": "def get_ssm_parameter(parameter_name):\n    try:\n        response = boto3.client('ssm').get_parameters(\n            Names=[parameter_name],\n            WithDecryption=True\n        )\n        return response.get('Parameters', None)[0].get('Value', '')\n    except Exception:\n        pass\n    return ''",
    "docstring": "Get the decrypted value of an SSM parameter\n\n    Args:\n        parameter_name - the name of the stored parameter of interest\n\n    Return:\n        Value if allowed and present else None"
  },
  {
    "code": "def _init_module_cache():\n\t\tif len(FieldTranslation._modules) < len(FieldTranslation._model_module_paths):\n\t\t\tfor module_path in FieldTranslation._model_module_paths:\n\t\t\t\tFieldTranslation._modules[module_path] = importlib.import_module(module_path)\n\t\t\treturn True\n\t\treturn False",
    "docstring": "Module caching, it helps with not having to import again and again same modules.\n\t\t@return: boolean, True if module  caching has been done, False if module caching was already done."
  },
  {
    "code": "def focus_next_sibling(self):\n        w, focuspos = self.get_focus()\n        sib = self._tree.next_sibling_position(focuspos)\n        if sib is not None:\n            self.set_focus(sib)",
    "docstring": "move focus to next sibling of currently focussed one"
  },
  {
    "code": "def set_contributor_details(self, contdetails):\n        if not isinstance(contdetails, bool):\n            raise TwitterSearchException(1008)\n        self.arguments.update({'contributor_details': 'true'\n                                                      if contdetails\n                                                      else 'false'})",
    "docstring": "Sets 'contributor_details' parameter used to enhance the \\\n        contributors element of the status response to include \\\n        the screen_name of the contributor. By default only \\\n        the user_id of the contributor is included\n\n        :param contdetails: Boolean triggering the usage of the parameter\n        :raises: TwitterSearchException"
  },
  {
    "code": "def angle_to_distance(angle, units='metric'):\n    distance = math.radians(angle) * BODY_RADIUS\n    if units in ('km', 'metric'):\n        return distance\n    elif units in ('sm', 'imperial', 'US customary'):\n        return distance / STATUTE_MILE\n    elif units in ('nm', 'nautical'):\n        return distance / NAUTICAL_MILE\n    else:\n        raise ValueError('Unknown units type %r' % units)",
    "docstring": "Convert angle in to distance along a great circle.\n\n    Args:\n        angle (float): Angle in degrees to convert to distance\n        units (str): Unit type to be used for distances\n\n    Returns:\n        float: Distance in ``units``\n\n    Raises:\n        ValueError: Unknown value for ``units``"
  },
  {
    "code": "def substitution_set(string, indexes):\n    strlen = len(string)\n    return {mutate_string(string, x) for x in indexes if valid_substitution(strlen, x)}",
    "docstring": "for a string, return a set of all possible substitutions"
  },
  {
    "code": "def _choose_width_fn(has_invisible, enable_widechars, is_multiline):\n    if has_invisible:\n        line_width_fn = _visible_width\n    elif enable_widechars:\n        line_width_fn = wcwidth.wcswidth\n    else:\n        line_width_fn = len\n    if is_multiline:\n        def width_fn(s): return _multiline_width(s, line_width_fn)\n    else:\n        width_fn = line_width_fn\n    return width_fn",
    "docstring": "Return a function to calculate visible cell width."
  },
  {
    "code": "def teardown_app_request(self, func: Callable) -> Callable:\n        self.record_once(lambda state: state.app.teardown_request(func))\n        return func",
    "docstring": "Add a teardown request function to the app.\n\n        This is designed to be used as a decorator, and has the same\n        arguments as :meth:`~quart.Quart.teardown_request`. It applies\n        to all requests to the app this blueprint is registered on. An\n        example usage,\n\n        .. code-block:: python\n\n            blueprint = Blueprint(__name__)\n            @blueprint.teardown_app_request\n            def teardown():\n                ..."
  },
  {
    "code": "def verify_in(self, first, second, msg=\"\"):\n        try:\n            self.assert_in(first, second, msg)\n        except AssertionError, e:\n            if msg:\n                m = \"%s:\\n%s\" % (msg, str(e))\n            else:\n                m = str(e)\n            self.verification_erorrs.append(m)",
    "docstring": "Soft assert for whether the first is in second\n\n        :params first: the value to check\n        :params second: the container to check in\n        :params msg: (Optional) msg explaining the difference"
  },
  {
    "code": "def template(basedir, text, vars, lookup_fatal=True, expand_lists=False):\n    try:\n        text = text.decode('utf-8')\n    except UnicodeEncodeError:\n        pass\n    text = varReplace(basedir, unicode(text), vars, lookup_fatal=lookup_fatal, expand_lists=expand_lists)\n    return text",
    "docstring": "run a text buffer through the templating engine until it no longer changes"
  },
  {
    "code": "def get_sources(zone, permanent=True):\n    cmd = '--zone={0} --list-sources'.format(zone)\n    if permanent:\n        cmd += ' --permanent'\n    return __firewall_cmd(cmd).split()",
    "docstring": "List sources bound to a zone\n\n    .. versionadded:: 2016.3.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' firewalld.get_sources zone"
  },
  {
    "code": "def setItemData(self, treeItem, column, value, role=Qt.EditRole):\n        if role == Qt.CheckStateRole:\n            if column != self.COL_VALUE:\n                return False\n            else:\n                logger.debug(\"Setting check state (col={}): {!r}\".format(column, value))\n                treeItem.checkState = value\n                return True\n        elif role == Qt.EditRole:\n            if column != self.COL_VALUE:\n                return False\n            else:\n                logger.debug(\"Set Edit value (col={}): {!r}\".format(column, value))\n                treeItem.data = value\n                return True\n        else:\n            raise ValueError(\"Unexpected edit role: {}\".format(role))",
    "docstring": "Sets the role data for the item at index to value."
  },
  {
    "code": "def fetch_routing_table(self, address):\n        new_routing_info = self.fetch_routing_info(address)\n        if new_routing_info is None:\n            return None\n        new_routing_table = RoutingTable.parse_routing_info(new_routing_info)\n        num_routers = len(new_routing_table.routers)\n        num_readers = len(new_routing_table.readers)\n        num_writers = len(new_routing_table.writers)\n        self.missing_writer = (num_writers == 0)\n        if num_routers == 0:\n            raise RoutingProtocolError(\"No routing servers returned from server %r\" % (address,))\n        if num_readers == 0:\n            raise RoutingProtocolError(\"No read servers returned from server %r\" % (address,))\n        return new_routing_table",
    "docstring": "Fetch a routing table from a given router address.\n\n        :param address: router address\n        :return: a new RoutingTable instance or None if the given router is\n                 currently unable to provide routing information\n        :raise ServiceUnavailable: if no writers are available\n        :raise ProtocolError: if the routing information received is unusable"
  },
  {
    "code": "def to_digestable(self, origin=None):\n        if not self.is_absolute():\n            if origin is None or not origin.is_absolute():\n                raise NeedAbsoluteNameOrOrigin\n            labels = list(self.labels)\n            labels.extend(list(origin.labels))\n        else:\n            labels = self.labels\n        dlabels = [\"%s%s\" % (chr(len(x)), x.lower()) for x in labels]\n        return ''.join(dlabels)",
    "docstring": "Convert name to a format suitable for digesting in hashes.\n\n        The name is canonicalized and converted to uncompressed wire format.\n\n        @param origin: If the name is relative and origin is not None, then\n        origin will be appended to it.\n        @type origin: dns.name.Name object\n        @raises NeedAbsoluteNameOrOrigin: All names in wire format are\n        absolute.  If self is a relative name, then an origin must be supplied;\n        if it is missing, then this exception is raised\n        @rtype: string"
  },
  {
    "code": "def index_natsorted(seq, key=lambda x: x, number_type=float, signed=True, exp=True):\n    from operator import itemgetter\n    item1 = itemgetter(1)\n    index_seq_pair = [[x, key(y)] for x, y in zip(range(len(seq)), seq)]\n    index_seq_pair.sort(key=lambda x: natsort_key(item1(x),\n                                                  number_type=number_type,\n                                                  signed=signed, exp=exp))\n    return [x[0] for x in index_seq_pair]",
    "docstring": "\\\n    Sorts a sequence naturally, but returns a list of sorted the\n    indeces and not the sorted list.\n\n        >>> a = ['num3', 'num5', 'num2']\n        >>> b = ['foo', 'bar', 'baz']\n        >>> index = index_natsorted(a)\n        >>> index\n        [2, 0, 1]\n        >>> # Sort both lists by the sort order of a\n        >>> [a[i] for i in index]\n        ['num2', 'num3', 'num5']\n        >>> [b[i] for i in index]\n        ['baz', 'foo', 'bar']\n        >>> c = [('a', 'num3'), ('b', 'num5'), ('c', 'num2')]\n        >>> from operator import itemgetter\n        >>> index_natsorted(c, key=itemgetter(1))\n        [2, 0, 1]"
  },
  {
    "code": "def view(self, sort=None, purge=False, done=None, undone=None, **kwargs):\n        View(self.model.modify(\n            sort=self._getPattern(sort),\n            purge=purge,\n            done=self._getDone(done, undone)\n        ), **kwargs)",
    "docstring": "Handles the 'v' command.\n\n        :sort: Sort pattern.\n        :purge: Whether to purge items marked as 'done'.\n        :done: Done pattern.\n        :undone: Not done pattern.\n        :kwargs: Additional arguments to pass to the View object."
  },
  {
    "code": "def human_bytes(n):\n    if n < 1024:\n        return '%d B' % n\n    k = n/1024\n    if k < 1024:\n        return '%d KB' % round(k)\n    m = k/1024\n    if m < 1024:\n        return '%.1f MB' % m\n    g = m/1024\n    return '%.2f GB' % g",
    "docstring": "Return the number of bytes n in more human readable form."
  },
  {
    "code": "def list(self, master=True):\n        params = {}\n        params.update(self.static_params)\n        if master:\n            params.update({\n                \"recurrenceOptions\": {\n                    \"collapseMode\": \"MASTER_ONLY\",\n                },\n                \"includeArchived\": True,\n                \"includeDeleted\": False,\n            })\n        else:\n            current_time = time.time()\n            start_time = int((current_time - (365 * 24 * 60 * 60)) * 1000)\n            end_time = int((current_time + (24 * 60 * 60)) * 1000)\n            params.update({\n                \"recurrenceOptions\": {\n                    \"collapseMode\":\"INSTANCES_ONLY\",\n                    \"recurrencesOnly\": True,\n                },\n                \"includeArchived\": False,\n                \"includeCompleted\": False,\n                \"includeDeleted\": False,\n                \"dueAfterMs\": start_time,\n                \"dueBeforeMs\": end_time,\n                \"recurrenceId\": [],\n            })\n        return self.send(\n            url=self._base_url + 'list',\n            method='POST',\n            json=params\n        )",
    "docstring": "List current reminders."
  },
  {
    "code": "def create(self, key, value):\n        data = None\n        if key is not None:\n            key = key.strip()\n            self.tcex.log.debug(u'create variable {}'.format(key))\n            parsed_key = self.parse_variable(key.strip())\n            variable_type = parsed_key['type']\n            if variable_type in self.read_data_types:\n                data = self.create_data_types[variable_type](key, value)\n            else:\n                data = self.create_raw(key, value)\n        return data",
    "docstring": "Create method of CRUD operation for working with KeyValue DB.\n\n        This method will automatically determine the variable type and\n        call the appropriate method to write the data.  If a non standard\n        type is provided the data will be written as RAW data.\n\n        Args:\n            key (string): The variable to write to the DB.\n            value (any): The data to write to the DB.\n\n        Returns:\n            (string): Result string of DB write."
  },
  {
    "code": "async def fetch_device_list(self):\n        url = '{}/users/me'.format(API_URL)\n        dlist = await self.api_get(url)\n        if dlist is None:\n            _LOGGER.error('Unable to fetch eight devices.')\n        else:\n            self._devices = dlist['user']['devices']\n            _LOGGER.debug('Devices: %s', self._devices)",
    "docstring": "Fetch list of devices."
  },
  {
    "code": "def cast_scalar(method):\n    @wraps(method)\n    def new_method(self, other):\n        if np.isscalar(other):\n            other = type(self)([other],self.domain())\n        return method(self, other)\n    return new_method",
    "docstring": "Cast scalars to constant interpolating objects"
  },
  {
    "code": "def codestr2rst(codestr, lang='python', lineno=None):\n    if lineno is not None:\n        if LooseVersion(sphinx.__version__) >= '1.3':\n            blank_lines = codestr.count('\\n', 0, -len(codestr.lstrip()))\n            lineno = '   :lineno-start: {0}\\n'.format(lineno + blank_lines)\n        else:\n            lineno = '   :linenos:\\n'\n    else:\n        lineno = ''\n    code_directive = \"\\n.. code-block:: {0}\\n{1}\\n\".format(lang, lineno)\n    indented_block = indent(codestr, ' ' * 4)\n    return code_directive + indented_block",
    "docstring": "Return reStructuredText code block from code string"
  },
  {
    "code": "def post_process(self, xout, yout, params):\n        for post_processor in self.post_processors:\n            xout, yout, params = post_processor(xout, yout, params)\n        return xout, yout, params",
    "docstring": "Transforms internal values to output, used internally."
  },
  {
    "code": "def copy_bootstrap(bootstrap_target: Path) -> None:\n    for bootstrap_file in importlib_resources.contents(bootstrap):\n        if importlib_resources.is_resource(bootstrap, bootstrap_file):\n            with importlib_resources.path(bootstrap, bootstrap_file) as f:\n                shutil.copyfile(f.absolute(), bootstrap_target / f.name)",
    "docstring": "Copy bootstrap code from shiv into the pyz.\n\n    This function is excluded from type checking due to the conditional import.\n\n    :param bootstrap_target: The temporary directory where we are staging pyz contents."
  },
  {
    "code": "def default(self, o):\n        if isinstance(o, (datetime.datetime, datetime.date, datetime.time)):\n            return o.isoformat()\n        if isinstance(o, decimal.Decimal):\n            return float(o)\n        return json.JSONEncoder.default(self, o)",
    "docstring": "Encode JSON.\n\n        :return str: A JSON encoded string"
  },
  {
    "code": "def handler_for_name(fq_name):\n  resolved_name = for_name(fq_name)\n  if isinstance(resolved_name, (type, types.ClassType)):\n    return resolved_name()\n  elif isinstance(resolved_name, types.MethodType):\n    return getattr(resolved_name.im_class(), resolved_name.__name__)\n  else:\n    return resolved_name",
    "docstring": "Resolves and instantiates handler by fully qualified name.\n\n  First resolves the name using for_name call. Then if it resolves to a class,\n  instantiates a class, if it resolves to a method - instantiates the class and\n  binds method to the instance.\n\n  Args:\n    fq_name: fully qualified name of something to find.\n\n  Returns:\n    handler instance which is ready to be called."
  },
  {
    "code": "def write(self, filename, entities, sortkey=None, columns=None):\n    if os.path.exists(filename):\n      raise IOError('File exists: %s'%filename)\n    if sortkey:\n      entities = sorted(entities, key=lambda x:x[sortkey])\n    if not columns:\n      columns = set()\n      for entity in entities:\n        columns |= set(entity.keys())\n      columns = sorted(columns)\n    with open(filename, 'wb') as f:\n      writer = unicodecsv.writer(f)\n      writer.writerow(columns)\n      for entity in entities:\n        writer.writerow([entity.get(column) for column in columns])",
    "docstring": "Write entities out to filename in csv format.\n\n    Note: this doesn't write directly into a Zip archive, because this behavior\n    is difficult to achieve with Zip archives. Use make_zip() to create a new\n    GTFS Zip archive."
  },
  {
    "code": "def updateImage(self, imgdata, xaxis=None, yaxis=None):\n        imgdata = imgdata.T\n        self.img.setImage(imgdata)\n        if xaxis is not None and yaxis is not None:\n            xscale = 1.0/(imgdata.shape[0]/xaxis[-1])\n            yscale = 1.0/(imgdata.shape[1]/yaxis[-1])\n            self.resetScale()        \n            self.img.scale(xscale, yscale)\n            self.imgScale = (xscale, yscale)\n        self.imageArray = np.fliplr(imgdata)\n        self.updateColormap()",
    "docstring": "Updates the Widget image directly.\n\n        :type imgdata: numpy.ndarray, see :meth:`pyqtgraph:pyqtgraph.ImageItem.setImage`\n        :param xaxis: x-axis values, length should match dimension 1 of imgdata\n        :param yaxis: y-axis values, length should match dimension 0 of imgdata"
  },
  {
    "code": "def __check_conflict_fronds(x, y, w, z, dfs_data):\n    if x < 0 and w < 0 and (x == y or w == z):\n        if x == w:\n            return True\n        return False\n    if b(x, dfs_data) == b(w, dfs_data) and x > w and w > y and y > z:\n        return False\n    if x < 0 or w < 0:\n        if x < 0:\n            u = abs(x)\n            t = y\n            x = w\n            y = z\n        else:\n            u = abs(w)\n            t = z\n        if b(x, dfs_data) == u and y < u and \\\n                (x, y) in __dfsify_branch_uv(u, t, dfs_data):\n            return True\n        return False\n    return False",
    "docstring": "Checks a pair of fronds to see if they conflict. Returns True if a conflict was found, False otherwise."
  },
  {
    "code": "def tracker_class(clsname):\n    stats = server.stats\n    if not stats:\n        bottle.redirect('/tracker')\n    stats.annotate()\n    return dict(stats=stats, clsname=clsname)",
    "docstring": "Get class instance details."
  },
  {
    "code": "def matches(self, properties):\n        try:\n            return self.comparator(self.value, properties[self.name])\n        except KeyError:\n            return False",
    "docstring": "Tests if the given criterion matches this LDAP criterion\n\n        :param properties: A dictionary of properties\n        :return: True if the properties matches this criterion, else False"
  },
  {
    "code": "def noinject(module_name=None, module_prefix='[???]', DEBUG=False, module=None, N=0, via=None):\n    if PRINT_INJECT_ORDER:\n        from utool._internal import meta_util_dbg\n        callername = meta_util_dbg.get_caller_name(N=N + 1, strict=False)\n        lineno = meta_util_dbg.get_caller_lineno(N=N + 1, strict=False)\n        suff = ' via %s' % (via,) if via else ''\n        fmtdict = dict(N=N, lineno=lineno, callername=callername,\n                       modname=module_name, suff=suff)\n        msg = '[util_inject] N={N} {modname} is imported by {callername} at lineno={lineno}{suff}'.format(**fmtdict)\n        if DEBUG_SLOW_IMPORT:\n            global PREV_MODNAME\n            seconds = tt.toc()\n            import_times[(PREV_MODNAME, module_name)] = seconds\n            PREV_MODNAME = module_name\n        builtins.print(msg)\n        if DEBUG_SLOW_IMPORT:\n            tt.tic()\n        if EXIT_ON_INJECT_MODNAME == module_name:\n            builtins.print('...exiting')\n            assert False, 'exit in inject requested'",
    "docstring": "Use in modules that do not have inject in them\n\n    Does not inject anything into the module. Just lets utool know that a module\n    is being imported so the import order can be debuged"
  },
  {
    "code": "def connect(self, addr):\n        if addr.find(':') == -1:\n            addr += ':5555'\n        output = self.run_cmd('connect', addr)\n        return 'unable to connect' not in output",
    "docstring": "Call adb connect\n        Return true when connect success"
  },
  {
    "code": "def install_missing(name, version=None, source=None):\n    choc_path = _find_chocolatey(__context__, __salt__)\n    if _LooseVersion(chocolatey_version()) >= _LooseVersion('0.9.8.24'):\n        log.warning('installmissing is deprecated, using install')\n        return install(name, version=version)\n    cmd = [choc_path, 'installmissing', name]\n    if version:\n        cmd.extend(['--version', version])\n    if source:\n        cmd.extend(['--source', source])\n    cmd.extend(_yes(__context__))\n    result = __salt__['cmd.run_all'](cmd, python_shell=False)\n    if result['retcode'] != 0:\n        raise CommandExecutionError(\n            'Running chocolatey failed: {0}'.format(result['stdout'])\n        )\n    return result['stdout']",
    "docstring": "Instructs Chocolatey to install a package if it doesn't already exist.\n\n    .. versionchanged:: 2014.7.0\n        If the minion has Chocolatey >= 0.9.8.24 installed, this function calls\n        :mod:`chocolatey.install <salt.modules.chocolatey.install>` instead, as\n        ``installmissing`` is deprecated as of that version and will be removed\n        in Chocolatey 1.0.\n\n    name\n        The name of the package to be installed. Only accepts a single argument.\n\n    version\n        Install a specific version of the package. Defaults to latest version\n        available.\n\n    source\n        Chocolatey repository (directory, share or remote URL feed) the package\n        comes from. Defaults to the official Chocolatey feed.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' chocolatey.install_missing <package name>\n        salt '*' chocolatey.install_missing <package name> version=<package version>"
  },
  {
    "code": "def text_to_char_array(original, alphabet):\n    r\n    return np.asarray([alphabet.label_from_string(c) for c in original])",
    "docstring": "r\"\"\"\n    Given a Python string ``original``, remove unsupported characters, map characters\n    to integers and return a numpy array representing the processed string."
  },
  {
    "code": "def is_submodule_included(src, tgt):\n    if tgt is None or not hasattr(tgt, 'i_orig_module'):\n        return True\n    if (tgt.i_orig_module.keyword == 'submodule' and\n        src.i_orig_module != tgt.i_orig_module and\n        src.i_orig_module.i_modulename == tgt.i_orig_module.i_modulename):\n        if src.i_orig_module.search_one('include',\n                                        tgt.i_orig_module.arg) is None:\n            return False\n    return True",
    "docstring": "Check that the tgt's submodule is included by src, if they belong\n    to the same module."
  },
  {
    "code": "async def close_wallet(handle: int) -> None:\n    logger = logging.getLogger(__name__)\n    logger.debug(\"close_wallet: >>> handle: %i\", handle)\n    if not hasattr(close_wallet, \"cb\"):\n        logger.debug(\"close_wallet: Creating callback\")\n        close_wallet.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))\n    c_handle = c_int32(handle)\n    await do_call('indy_close_wallet',\n                  c_handle,\n                  close_wallet.cb)\n    logger.debug(\"close_wallet: <<<\")",
    "docstring": "Closes opened wallet and frees allocated resources.\n\n    :param handle: wallet handle returned by indy_open_wallet.\n    :return: Error code"
  },
  {
    "code": "def get_resource_attributes(ref_key, ref_id, type_id=None, **kwargs):\n    user_id = kwargs.get('user_id')\n    resource_attr_qry = db.DBSession.query(ResourceAttr).filter(\n        ResourceAttr.ref_key == ref_key,\n        or_(\n            ResourceAttr.network_id==ref_id,\n            ResourceAttr.node_id==ref_id,\n            ResourceAttr.link_id==ref_id,\n            ResourceAttr.group_id==ref_id\n        ))\n    if type_id is not None:\n        attr_ids = []\n        rs = db.DBSession.query(TypeAttr).filter(TypeAttr.type_id==type_id).all()\n        for r in rs:\n            attr_ids.append(r.attr_id)\n        resource_attr_qry = resource_attr_qry.filter(ResourceAttr.attr_id.in_(attr_ids))\n    resource_attrs = resource_attr_qry.all()\n    return resource_attrs",
    "docstring": "Get all the resource attributes for a given resource.\n        If type_id is specified, only\n        return the resource attributes within the type."
  },
  {
    "code": "def _get_function_commands(module):\n    nodes = (n for n in module.body if isinstance(n, ast.FunctionDef))\n    for func in nodes:\n        docstring = ast.get_docstring(func)\n        for commands, _ in usage.parse_commands(docstring):\n            yield _EntryPoint(commands[0], next(iter(commands[1:]), None),\n                              func.name)",
    "docstring": "Yield all Command objects represented by python functions in the module.\n\n    Function commands consist of all top-level functions that contain\n    docopt-style docstrings.\n\n    Args:\n        module: An ast.Module object used to retrieve docopt-style commands.\n\n    Yields:\n        Command objects that represent entry points to append to setup.py."
  },
  {
    "code": "def process_uncaught_exception(self, e):\n        exc_file_fullpath, exc_file, exc_lineno, exc_func, exc_line = (\n            workflows.logging.get_exception_source()\n        )\n        added_information = {\n            \"workflows_exc_lineno\": exc_lineno,\n            \"workflows_exc_funcName\": exc_func,\n            \"workflows_exc_line\": exc_line,\n            \"workflows_exc_pathname\": exc_file_fullpath,\n            \"workflows_exc_filename\": exc_file,\n        }\n        for field in filter(lambda x: x.startswith(\"workflows_log_\"), dir(e)):\n            added_information[field[14:]] = getattr(e, field, None)\n        self.log.critical(\n            \"Unhandled service exception: %s\", e, exc_info=True, extra=added_information\n        )",
    "docstring": "This is called to handle otherwise uncaught exceptions from the service.\n        The service will terminate either way, but here we can do things such as\n        gathering useful environment information and logging for posterity."
  },
  {
    "code": "def isexe(*components):\n    _path = path(*components)\n    return isfile(_path) and os.access(_path, os.X_OK)",
    "docstring": "Return whether a path is an executable file.\n\n    Arguments:\n\n        path (str): Path of the file to check.\n\n    Examples:\n\n        >>> fs.isexe(\"/bin/ls\")\n        True\n\n        >>> fs.isexe(\"/home\")\n        False\n\n        >>> fs.isexe(\"/not/a/real/path\")\n        False\n\n    Returns:\n\n        bool: True if file is executable, else false."
  },
  {
    "code": "def find_following_working_day(self, day):\n        day = cleaned_date(day)\n        while day.weekday() in self.get_weekend_days():\n            day = day + timedelta(days=1)\n        return day",
    "docstring": "Looks for the following working day, if not already a working day.\n\n        **WARNING**: this function doesn't take into account the calendar\n        holidays, only the days of the week and the weekend days parameters."
  },
  {
    "code": "def transform(self, X):\n        if self.func is None:\n            return X\n        else:\n            Xt, Xc = get_ts_data_parts(X)\n            n_samples = len(Xt)\n            Xt = self.func(Xt, **self.func_kwargs)\n            if len(Xt) != n_samples:\n                raise ValueError(\"FunctionTransformer changes sample number (not supported).\")\n            if Xc is not None:\n                Xt = TS_Data(Xt, Xc)\n            return Xt",
    "docstring": "Transforms the time series data based on the provided function. Note this transformation\n        must not change the number of samples in the data.\n\n        Parameters\n        ----------\n        X : array-like, shape [n_samples, ...]\n            time series data and (optionally) contextual data\n\n        Returns\n        -------\n        Xt : array-like, shape [n_samples, ...]\n            transformed time series data"
  },
  {
    "code": "def configure(self, debug=None, quiet=None, verbosity=None, compile=None, compiler_factory=None, **kwargs):\n        if debug is not None:\n            self.arg_debug = debug\n        if quiet is not None:\n            self.arg_quiet = quiet\n        if verbosity is not None:\n            self.arg_verbosity = verbosity\n        if compile is not None:\n            self.compile = compile\n        if compiler_factory is not None:\n            self.compiler_factory = compiler_factory\n        if kwargs:\n            self.command.update(**kwargs)",
    "docstring": "configure managed args"
  },
  {
    "code": "def get_mesh_dict(self):\n        if self._mesh is None:\n            msg = (\"run_mesh has to be done.\")\n            raise RuntimeError(msg)\n        retdict = {'qpoints': self._mesh.qpoints,\n                   'weights': self._mesh.weights,\n                   'frequencies': self._mesh.frequencies,\n                   'eigenvectors': self._mesh.eigenvectors,\n                   'group_velocities': self._mesh.group_velocities}\n        return retdict",
    "docstring": "Returns calculated mesh sampling phonons\n\n        Returns\n        -------\n        dict\n            keys: qpoints, weights, frequencies, eigenvectors, and\n                  group_velocities\n\n            Each value for the corresponding key is explained as below.\n\n            qpoints: ndarray\n                q-points in reduced coordinates of reciprocal lattice\n                dtype='double'\n                shape=(ir-grid points, 3)\n            weights: ndarray\n                Geometric q-point weights. Its sum is the number of grid\n                points.\n                dtype='intc'\n                shape=(ir-grid points,)\n            frequencies: ndarray\n                Phonon frequencies at ir-grid points. Imaginary frequenies are\n                represented by negative real numbers.\n                dtype='double'\n                shape=(ir-grid points, bands)\n            eigenvectors: ndarray\n                Phonon eigenvectors at ir-grid points. See the data structure\n                at np.linalg.eigh.\n                dtype='complex'\n                shape=(ir-grid points, bands, bands)\n            group_velocities: ndarray\n                Phonon group velocities at ir-grid points.\n                dtype='double'\n                shape=(ir-grid points, bands, 3)"
  },
  {
    "code": "def inf_sup(u):\n    if np.ndim(u) == 2:\n        P = _P2\n    elif np.ndim(u) == 3:\n        P = _P3\n    else:\n        raise ValueError(\"u has an invalid number of dimensions \"\n                         \"(should be 2 or 3)\")\n    dilations = []\n    for P_i in P:\n        dilations.append(ndi.binary_dilation(u, P_i))\n    return np.array(dilations, dtype=np.int8).min(0)",
    "docstring": "IS operator."
  },
  {
    "code": "def _runargs(argstring):\n    import shlex\n    parser = cli.make_arg_parser()\n    args = parser.parse_args(shlex.split(argstring))\n    run(args)",
    "docstring": "Entrypoint for debugging"
  },
  {
    "code": "def get_token(self, url):\n        parsed_url = urlparse.urlsplit(url)\n        parsed_url = parsed_url._replace(path='/authorization/api')\n        self.url = urlparse.urlunsplit(parsed_url)\n        response = self.request(method='GET', url='/v1/token?url=' + url)\n        return response.result.text",
    "docstring": "Retrieves a temporary access token"
  },
  {
    "code": "def fetch(cls, id, api_key=None, endpoint=None, add_headers=None,\n              **kwargs):\n        if endpoint is None:\n            endpoint = cls.get_endpoint()\n        inst = cls(api_key=api_key)\n        parse_key = cls.sanitize_ep(endpoint).split(\"/\")[-1]\n        endpoint = '/'.join((endpoint, id))\n        data = cls._parse(inst.request('GET',\n                                       endpoint=endpoint,\n                                       add_headers=add_headers,\n                                       query_params=kwargs),\n                          key=parse_key)\n        inst._set(data)\n        return inst",
    "docstring": "Fetch a single entity from the API endpoint.\n\n        Used when you know the exact ID that must be queried."
  },
  {
    "code": "def has_stack(self, s):\n        for t in self.transitions:\n            if t.lhs[s].position != 0:\n                return False\n            if t.rhs[s].position != 0:\n                return False\n        return True",
    "docstring": "Tests whether store `s` is a stack, that is, it never moves from\n        position 0."
  },
  {
    "code": "def housecode_to_index(housecode):\n    match = re.search(r'^([A-P])(\\d{1,2})$', housecode.upper())\n    if match:\n        house_index = int(match.group(2))\n        if 1 <= house_index <= 16:\n            return (ord(match.group(1)) - ord('A')) * 16 + house_index - 1\n    raise ValueError(\"Invalid X10 housecode: %s\" % housecode)",
    "docstring": "Convert a X10 housecode to a zero-based index"
  },
  {
    "code": "def remove(self, w):\n        self.wpoints.remove(w)\n        self.last_change = time.time()\n        self.reindex()",
    "docstring": "remove a waypoint"
  },
  {
    "code": "def _validate_options(options, service_name, add_error):\n    if options is None:\n        return\n    if not isdict(options):\n        add_error('service {} has malformed options'.format(service_name))",
    "docstring": "Lazily validate the options, ensuring that they are a dict.\n\n    Use the given add_error callable to register validation error."
  },
  {
    "code": "def load(self, filename=None):\n        assert not self.__flag_loaded, \"File can be loaded only once\"\n        if filename is None:\n            filename = self.default_filename\n        assert filename is not None, \\\n            \"{0!s} class has no default filename\".format(self.__class__.__name__)\n        size = os.path.getsize(filename)\n        if size == 0:\n            raise RuntimeError(\"Empty file: '{0!s}'\".format(filename))\n        self._test_magic(filename)\n        self._do_load(filename)\n        self.filename = filename\n        self.__flag_loaded = True",
    "docstring": "Loads file and registers filename as attribute."
  },
  {
    "code": "def _build_tree(self):\n        if not self.nn_ready:\n            self.kdtree   = scipy.spatial.cKDTree(self.data)\n            self.nn_ready = True",
    "docstring": "Build the KDTree for the observed data"
  },
  {
    "code": "def topoff(cls, amount):\n        for user in get_user_model().objects.all():\n            cls.topoff_user(user, amount)",
    "docstring": "Ensure all users have a minimum number of invites."
  },
  {
    "code": "def with_port(self, port):\n        if port is not None and not isinstance(port, int):\n            raise TypeError(\"port should be int or None, got {}\".format(type(port)))\n        if not self.is_absolute():\n            raise ValueError(\"port replacement is not allowed \" \"for relative URLs\")\n        val = self._val\n        return URL(\n            self._val._replace(\n                netloc=self._make_netloc(\n                    val.username, val.password, val.hostname, port, encode=False\n                )\n            ),\n            encoded=True,\n        )",
    "docstring": "Return a new URL with port replaced.\n\n        Clear port to default if None is passed."
  },
  {
    "code": "def _compile_dimension_size(self, base_index, array,\n                                property, sized_elements):\n        sort_index = base_index + 2\n        sized_elements.sort(key=lambda x: x[sort_index])\n        for element_data in sized_elements:\n            start, end = element_data[base_index], element_data[sort_index]\n            end += start\n            element, size = element_data[4:6]\n            set_size = sum(array[start:end]) + (end-start-1)*self.margin\n            extra_space_needed = getattr(size, property) - set_size\n            if extra_space_needed < 0: continue\n            extra_space_each = extra_space_needed / (end-start)\n            for index in range(start, end):\n                array[index] += extra_space_each",
    "docstring": "Build one set of col widths or row heights."
  },
  {
    "code": "def create(cls, parent, child, relation_type, index=None):\n        try:\n            with db.session.begin_nested():\n                obj = cls(parent_id=parent.id,\n                          child_id=child.id,\n                          relation_type=relation_type,\n                          index=index)\n                db.session.add(obj)\n        except IntegrityError:\n            raise Exception(\"PID Relation already exists.\")\n        return obj",
    "docstring": "Create a PID relation for given parent and child."
  },
  {
    "code": "def possible_moves(self, position):\n        for move in itertools.chain(*[self.add(fn, position) for fn in self.cardinal_directions]):\n            yield move\n        for move in self.add_castle(position):\n            yield move",
    "docstring": "Generates list of possible moves\n\n        :type: position: Board\n        :rtype: list"
  },
  {
    "code": "def put_file(self, key, file):\n        if isinstance(file, str):\n            return self._put_filename(key, file)\n        else:\n            return self._put_file(key, file)",
    "docstring": "Store into key from file on disk\n\n        Stores data from a source into key. *file* can either be a string,\n        which will be interpretet as a filename, or an object with a *read()*\n        method.\n\n        If the passed object has a *fileno()* method, it may be used to speed\n        up the operation.\n\n        The file specified by *file*, if it is a filename, may be removed in\n        the process, to avoid copying if possible. If you need to make a copy,\n        pass the opened file instead.\n\n        :param key: The key under which the data is to be stored\n        :param file: A filename or an object with a read method. If a filename,\n                     may be removed\n\n        :returns: The key under which data was stored\n\n        :raises exceptions.ValueError: If the key is not valid.\n        :raises exceptions.IOError: If there was a problem moving the file in."
  },
  {
    "code": "def _compose_func(func, args_func=lambda req_info: [req_info.index]):\n    return FuncInfo(func=func, args_func=args_func)",
    "docstring": "Compose function used to compose arguments to function.\n\n    Arguments for the functions are composed from the :class:`.RequestInfo`\n    object from the ZODB."
  },
  {
    "code": "def make_spiral_texture(spirals=6.0, ccw=False, offset=0.0, resolution=1000):\n    dist = np.sqrt(np.linspace(0., 1., resolution))\n    if ccw:\n        direction = 1.\n    else:\n        direction = -1.\n    angle = dist * spirals * np.pi * 2. * direction\n    spiral_texture = (\n        (np.cos(angle) * dist / 2.) + 0.5,\n        (np.sin(angle) * dist / 2.) + 0.5\n    )\n    return spiral_texture",
    "docstring": "Makes a texture consisting of a spiral from the origin.\n\n    Args:\n        spirals (float): the number of rotations to make\n        ccw (bool): make spirals counter-clockwise (default is clockwise)\n        offset (float): if non-zero, spirals start offset by this amount\n        resolution (int): number of midpoints along the spiral\n\n    Returns:\n        A texture."
  },
  {
    "code": "def localCheckpoint(self, eager=True):\n        jdf = self._jdf.localCheckpoint(eager)\n        return DataFrame(jdf, self.sql_ctx)",
    "docstring": "Returns a locally checkpointed version of this Dataset. Checkpointing can be used to\n        truncate the logical plan of this DataFrame, which is especially useful in iterative\n        algorithms where the plan may grow exponentially. Local checkpoints are stored in the\n        executors using the caching subsystem and therefore they are not reliable.\n\n        :param eager: Whether to checkpoint this DataFrame immediately\n\n        .. note:: Experimental"
  },
  {
    "code": "def identify_modules(*args, **kwargs):\n    if len(args) == 1:\n        path_template = \"%(file)s\"\n        error_template = \"Module '%(mod)s' not found (%(error)s)\"\n    else:\n        path_template = \"%(mod)s: %(file)s\"\n        error_template = \"%(mod)s: not found (%(error)s)\"\n    for modulename in args:\n        try:\n            filepath = identify_filepath(modulename, **kwargs)\n        except ModuleNotFound:\n            exc = sys.exc_info()[1]\n            sys.stderr.write(error_template % {\n                'mod': modulename,\n                'error': str(exc),\n            })\n            sys.stderr.write('\\n')\n        else:\n            print(path_template % {\n                'mod': modulename,\n                'file': filepath\n            })",
    "docstring": "Find the disk locations of the given named modules, printing the\n    discovered paths to stdout and errors discovering paths to stderr.\n\n    Any provided keyword arguments are passed to `identify_filepath()`."
  },
  {
    "code": "def comments(self, ticket, include_inline_images=False):\n        return self._query_zendesk(self.endpoint.comments, 'comment', id=ticket, include_inline_images=repr(include_inline_images).lower())",
    "docstring": "Retrieve the comments for a ticket.\n\n        :param ticket: Ticket object or id\n        :param include_inline_images: Boolean. If `True`, inline image attachments will be\n            returned in each comments' `attachments` field alongside non-inline attachments"
  },
  {
    "code": "def get_status(self):\n        return {\n            \"host\": self.__hostid,\n            \"status\": self._service_status_announced,\n            \"statustext\": CommonService.human_readable_state.get(\n                self._service_status_announced\n            ),\n            \"service\": self._service_name,\n            \"serviceclass\": self._service_class_name,\n            \"utilization\": self._utilization.report(),\n            \"workflows\": workflows.version(),\n        }",
    "docstring": "Returns a dictionary containing all relevant status information to be\n        broadcast across the network."
  },
  {
    "code": "def move(self, bearing, distance):\n        lat = self.pkt['I105']['Lat']['val']\n        lon = self.pkt['I105']['Lon']['val']\n        (lat, lon) = mp_util.gps_newpos(lat, lon, bearing, distance)\n        self.setpos(lat, lon)",
    "docstring": "move position by bearing and distance"
  },
  {
    "code": "def parse_group_address(addr):\n    if addr is None:\n        raise KNXException(\"No address given\")\n    res = None\n    if re.match('[0-9]+$', addr):\n        res = int(addr)\n    match = re.match(\"([0-9]+)/([0-9]+)$\", addr)\n    if match:\n        main = match.group(1)\n        sub = match.group(2)\n        res = int(main) * 2048 + int(sub)\n    match = re.match(\"([0-9]+)/([0-9]+)/([0-9]+)$\", addr)\n    if match:\n        main = match.group(1)\n        middle = match.group(2)\n        sub = match.group(3)\n        res = int(main) * 256 * 8 + int(middle) * 256 + int(sub)\n    if res is None:\n        raise KNXException(\"Address {} does not match any address scheme\".\n                           format(addr))\n    return res",
    "docstring": "Parse KNX group addresses and return the address as an integer.\n\n    This allows to convert x/x/x and x/x address syntax to a numeric\n    KNX group address"
  },
  {
    "code": "def validate(self, csdl, service='facebook'):\n        return self.request.post('validate', data=dict(csdl=csdl))",
    "docstring": "Validate the given CSDL\n\n            :param csdl: The CSDL to be validated for analysis\n            :type csdl: str\n            :param service: The service for this API call (facebook, etc)\n            :type service: str\n            :return: dict of REST API output with headers attached\n            :rtype: :class:`~datasift.request.DictResponse`\n            :raises: :class:`~datasift.exceptions.DataSiftApiException`,\n                :class:`requests.exceptions.HTTPError`"
  },
  {
    "code": "def epanechnikovKernel(x,ref_x,h=1.0):\n    u          = (x-ref_x)/h\n    these      = np.abs(u) <= 1.0\n    out        = np.zeros_like(x)\n    out[these] = 0.75*(1.0-u[these]**2.0)\n    return out",
    "docstring": "The Epanechnikov kernel.\n\n    Parameters\n    ----------\n    x : np.array\n        Values at which to evaluate the kernel\n    x_ref : float\n        The reference point\n    h : float\n        Kernel bandwidth\n\n    Returns\n    -------\n    out : np.array\n        Kernel values at each value of x"
  },
  {
    "code": "def trigger_modified(self, filepath):\n        mod_time = self._get_modified_time(filepath)\n        if mod_time > self._watched_files.get(filepath, 0):\n            self._trigger('modified', filepath)\n            self._watched_files[filepath] = mod_time",
    "docstring": "Triggers modified event if the given filepath mod time is newer."
  },
  {
    "code": "def background_at_centroid(self):\n        from scipy.ndimage import map_coordinates\n        if self._background is not None:\n            if (self._is_completely_masked or\n                    np.any(~np.isfinite(self.centroid))):\n                return np.nan * self._background_unit\n            else:\n                value = map_coordinates(self._background,\n                                        [[self.ycentroid.value],\n                                         [self.xcentroid.value]], order=1,\n                                        mode='nearest')[0]\n                return value * self._background_unit\n        else:\n            return None",
    "docstring": "The value of the ``background`` at the position of the source\n        centroid.\n\n        The background value at fractional position values are\n        determined using bilinear interpolation."
  },
  {
    "code": "def update(self, key_vals=None, overwrite=True):\n        if not key_vals:\n            return\n        write_items = self._update(key_vals, overwrite)\n        self._root._root_set(self._path, write_items)\n        self._root._write(commit=True)",
    "docstring": "Locked keys will be overwritten unless overwrite=False.\n\n        Otherwise, written keys will be added to the \"locked\" list."
  },
  {
    "code": "def _locate_settings(settings=''):\n    \"Return the path to the DJANGO_SETTINGS_MODULE\"\n    import imp\n    import sys\n    sys.path.append(os.getcwd())\n    settings = settings or os.getenv('DJANGO_SETTINGS_MODULE')\n    if settings:\n        parts = settings.split('.')\n        f = imp.find_module(parts[0])[1]\n        args = [f] + parts[1:]\n        path = os.path.join(*args)\n        path = path + '.py'\n        if os.path.exists(path):\n            return path",
    "docstring": "Return the path to the DJANGO_SETTINGS_MODULE"
  },
  {
    "code": "def notify(\n        self,\n        method_name: str,\n        *args: Any,\n        trim_log_values: Optional[bool] = None,\n        validate_against_schema: Optional[bool] = None,\n        **kwargs: Any\n    ) -> Response:\n        return self.send(\n            Notification(method_name, *args, **kwargs),\n            trim_log_values=trim_log_values,\n            validate_against_schema=validate_against_schema,\n        )",
    "docstring": "Send a JSON-RPC request, without expecting a response.\n\n        Args:\n            method_name: The remote procedure's method name.\n            args: Positional arguments passed to the remote procedure.\n            kwargs: Keyword arguments passed to the remote procedure.\n            trim_log_values: Abbreviate the log entries of requests and responses.\n            validate_against_schema: Validate response against the JSON-RPC schema."
  },
  {
    "code": "def filter_yn(string, default=None):\n    if string.startswith(('Y', 'y')):\n        return True\n    elif string.startswith(('N', 'n')):\n        return False\n    elif not string and default is not None:\n        return True if default else False\n    raise InvalidInputError",
    "docstring": "Return True if yes, False if no, or the default."
  },
  {
    "code": "def scan (data, clamconf):\n    try:\n        scanner = ClamdScanner(clamconf)\n    except socket.error:\n        errmsg = _(\"Could not connect to ClamAV daemon.\")\n        return ([], [errmsg])\n    try:\n        scanner.scan(data)\n    finally:\n        scanner.close()\n    return scanner.infected, scanner.errors",
    "docstring": "Scan data for viruses.\n    @return (infection msgs, errors)\n    @rtype ([], [])"
  },
  {
    "code": "def start_child_span(operation_name, tracer=None, parent=None, tags=None):\n    tracer = tracer or opentracing.tracer\n    return tracer.start_span(\n        operation_name=operation_name,\n        child_of=parent.context if parent else None,\n        tags=tags\n    )",
    "docstring": "Start a new span as a child of parent_span. If parent_span is None,\n    start a new root span.\n\n    :param operation_name: operation name\n    :param tracer: Tracer or None (defaults to opentracing.tracer)\n    :param parent: parent Span or None\n    :param tags: optional tags\n    :return: new span"
  },
  {
    "code": "async def fire(self, name, payload=None, *,\n                   dc=None, node=None, service=None, tag=None):\n        params = {\n            \"dc\": dc,\n            \"node\": extract_pattern(node),\n            \"service\": extract_pattern(service),\n            \"tag\": extract_pattern(tag)\n        }\n        payload = encode_value(payload) if payload else None\n        response = await self._api.put(\n            \"/v1/event/fire\", name,\n            data=payload,\n            params=params,\n            headers={\"Content-Type\": \"application/octet-stream\"})\n        result = format_event(response.body)\n        return result",
    "docstring": "Fires a new event\n\n        Parameters:\n            name (str): Event name\n            payload (Payload): Opaque data\n            node (Filter): Regular expression to filter by node name\n            service (Filter): Regular expression to filter by service\n            tag (Filter): Regular expression to filter by service tags\n            dc (str): Specify datacenter that will be used.\n                      Defaults to the agent's local datacenter.\n        Returns:\n            Object: where value is event ID\n\n        The return body is like::\n\n            {\n                \"ID\": \"b54fe110-7af5-cafc-d1fb-afc8ba432b1c\",\n                \"Name\": \"deploy\",\n                \"Payload\": None,\n                \"NodeFilter\": re.compile(\"node-\\d+\"),\n                \"ServiceFilter\": \"\",\n                \"TagFilter\": \"\",\n                \"Version\": 1,\n                \"LTime\": 0\n            }\n\n        The **ID** field uniquely identifies the newly fired event."
  },
  {
    "code": "def __get_cfg_pkgs_rpm(self):\n        out, err = self._syscall('rpm', None, None, '-qa', '--configfiles',\n                                 '--queryformat', '%{name}-%{version}-%{release}\\\\n')\n        data = dict()\n        pkg_name = None\n        pkg_configs = []\n        out = salt.utils.stringutils.to_str(out)\n        for line in out.split(os.linesep):\n            line = line.strip()\n            if not line:\n                continue\n            if not line.startswith(\"/\"):\n                if pkg_name and pkg_configs:\n                    data[pkg_name] = pkg_configs\n                pkg_name = line\n                pkg_configs = []\n            else:\n                pkg_configs.append(line)\n        if pkg_name and pkg_configs:\n            data[pkg_name] = pkg_configs\n        return data",
    "docstring": "Get packages with configuration files on RPM systems."
  },
  {
    "code": "def clean_before_output(kw_matches):\n    filtered_kw_matches = {}\n    for kw_match, info in iteritems(kw_matches):\n        if not kw_match.nostandalone:\n            filtered_kw_matches[kw_match] = info\n    return filtered_kw_matches",
    "docstring": "Return a clean copy of the keywords data structure.\n\n    Stripped off the standalone and other unwanted elements."
  },
  {
    "code": "def remove_go(self, target):\n        with self.lock:\n            if not self._go:\n                try:\n                    self.job_queue.remove(target)\n                except ValueError:\n                    pass",
    "docstring": "FOR SAVING MEMORY"
  },
  {
    "code": "def get_evcodes_all(self, inc_set=None, exc_set=None):\n        codes = self._get_grps_n_codes(inc_set) if inc_set else set(self.code2nt)\n        if exc_set:\n            codes.difference_update(self._get_grps_n_codes(exc_set))\n        return codes",
    "docstring": "Get set of evidence codes given include set and exclude set"
  },
  {
    "code": "def __add_watch(self, path, mask, proc_fun, auto_add, exclude_filter):\n        path = self.__format_path(path)\n        if auto_add and not mask & IN_CREATE:\n            mask |= IN_CREATE\n        wd = self._inotify_wrapper.inotify_add_watch(self._fd, path, mask)\n        if wd < 0:\n            return wd\n        watch = Watch(wd=wd, path=path, mask=mask, proc_fun=proc_fun,\n                      auto_add=auto_add, exclude_filter=exclude_filter)\n        self._wmd[wd] = watch\n        log.debug('New %s', watch)\n        return wd",
    "docstring": "Add a watch on path, build a Watch object and insert it in the\n        watch manager dictionary. Return the wd value."
  },
  {
    "code": "def _trace_filename(self):\n        dir_stub = ''\n        if self.output_directory is not None:\n            dir_stub = self.output_directory\n        if self.each_time:\n            filename = '{0}_{1}.json'.format(\n                self.output_file_name, self.counter)\n        else:\n            filename = '{0}.json'.format(self.output_file_name)\n        return os.path.join(dir_stub, filename)",
    "docstring": "Creates trace filename."
  },
  {
    "code": "def get_nodes(code, desired_type, path=\"__main__\", mode=\"exec\", tree=None):\n    return _GetVisitor(parse(code, path, mode, tree), desired_type).result",
    "docstring": "Find all nodes of a given type\n\n\n    Arguments:\n    code -- code text\n    desired_type -- ast Node or tuple\n\n\n    Keyword Arguments:\n    path -- code path\n    mode -- execution mode (exec, eval, single)\n    tree -- current tree, if it was optimized"
  },
  {
    "code": "def unsubscribe_url(self):\n        server_relative = ('%s?s=%s' % (reverse('tidings.unsubscribe',\n                                                args=[self.pk]),\n                                        self.secret))\n        return 'https://%s%s' % (Site.objects.get_current().domain,\n                                 server_relative)",
    "docstring": "Return the absolute URL to visit to delete me."
  },
  {
    "code": "def redef(obj, key, value, **kwargs):\n    return Redef(obj, key, value=value, **kwargs)",
    "docstring": "A static constructor helper function"
  },
  {
    "code": "def _qr_factor_full(a, dtype=np.float):\n    n, m = a.shape\n    packed, pmut, rdiag, acnorm = \\\n        _manual_qr_factor_packed(a, dtype)\n    r = np.zeros((n, m))\n    for i in range(n):\n        r[i,:i] = packed[i,:i]\n        r[i,i] = rdiag[i]\n    q = np.eye(m)\n    v = np.empty(m)\n    for i in range(n):\n        v[:] = packed[i]\n        v[:i] = 0\n        hhm = np.eye(m) - 2 * np.outer(v, v) / np.dot(v, v)\n        q = np.dot(hhm, q)\n    return q, r, pmut",
    "docstring": "Compute the QR factorization of a matrix, with pivoting.\n\nParameters:\na     - An n-by-m arraylike, m >= n.\ndtype - (optional) The data type to use for computations.\n        Default is np.float.\n\nReturns:\nq    - An m-by-m orthogonal matrix (q q^T = ident)\nr    - An n-by-m upper triangular matrix\npmut - An n-element permutation vector\n\nThe returned values will satisfy the equation\n\nnp.dot(r, q) == a[:,pmut]\n\nThe outputs are computed indirectly via the function\n_qr_factor_packed. If you need to compute q and r matrices in\nproduction code, there are faster ways to do it. This function is for\ntesting _qr_factor_packed.\n\nThe permutation vector pmut is a vector of the integers 0 through\nn-1. It sorts the rows of 'a' by their norms, so that the\npmut[i]'th row of 'a' has the i'th biggest norm."
  },
  {
    "code": "def deep_merge_dict(base, priority):\n    if not isinstance(base, dict) or not isinstance(priority, dict):\n        return priority\n    result = copy.deepcopy(base)\n    for key in priority.keys():\n        if key in base:\n            result[key] = deep_merge_dict(base[key], priority[key])\n        else:\n            result[key] = priority[key]\n    return result",
    "docstring": "Recursively merges the two given dicts into a single dict.\n\n    Treating base as the the initial point of the resulting merged dict,\n    and considering the nested dictionaries as trees, they are merged os:\n    1. Every path to every leaf in priority would be represented in the result.\n    2. Subtrees of base are overwritten if a leaf is found in the\n    corresponding path in priority.\n    3. The invariant that all priority leaf nodes remain leafs is maintained.\n\n\n    Parameters\n    ----------\n    base : dict\n        The first, lower-priority, dict to merge.\n    priority : dict\n        The second, higher-priority, dict to merge.\n\n    Returns\n    -------\n    dict\n        A recursive merge of the two given dicts.\n\n    Example:\n    --------\n    >>> base = {'a': 1, 'b': 2, 'c': {'d': 4}, 'e': 5}\n    >>> priority = {'a': {'g': 7}, 'c': 3, 'e': 5, 'f': 6}\n    >>> result = deep_merge_dict(base, priority)\n    >>> print(sorted(result.items()))\n    [('a', {'g': 7}), ('b', 2), ('c', 3), ('e', 5), ('f', 6)]"
  },
  {
    "code": "def generate_css(self, output_file):\n        if self.CSS_TEMPLATE_NAME is not None:\n            template = TEMPLATE_ENV.get_template(self.CSS_TEMPLATE_NAME)\n            style = template.render(self._context())\n        if isinstance(style, six.string_types):\n            style = style.encode('utf-8')\n        output_file.write(style)",
    "docstring": "Generate an external style sheet file.\n\n        output_file must be a file handler that takes in bytes!"
  },
  {
    "code": "def get_data_size(self, sport, plan, from_day, from_month, from_year, to_day, to_month, to_year, event_id=None,\n                      event_name=None, market_types_collection=None, countries_collection=None,\n                      file_type_collection=None, session=None):\n        params = clean_locals(locals())\n        method = 'GetAdvBasketDataSize'\n        (response, elapsed_time) = self.request(method, params, session)\n        return response",
    "docstring": "Returns a dictionary of file count and combines size files.\n\n        :param sport: sport to filter data for.\n        :param plan: plan type to filter for, Basic Plan, Advanced Plan or Pro Plan.\n        :param from_day: day of month to start data from.\n        :param from_month: month to start data from.\n        :param from_year: year to start data from.\n        :param to_day: day of month to end data at.\n        :param to_month: month to end data at.\n        :param to_year: year to end data at.\n        :param event_id: id of a specific event to get data for.\n        :param event_name: name of a specific event to get data for.\n        :param market_types_collection: list of specific marketTypes to filter for.\n        :param countries_collection: list of countries to filter for.\n        :param file_type_collection: list of file types.\n        :param requests.session session: Requests session object\n\n        :rtype: dict"
  },
  {
    "code": "def Get(self):\n    args = vfs_pb2.ApiGetFileDetailsArgs(\n        client_id=self.client_id, file_path=self.path)\n    data = self._context.SendRequest(\"GetFileDetails\", args).file\n    return File(client_id=self.client_id, data=data, context=self._context)",
    "docstring": "Fetch file's data and return proper File object."
  },
  {
    "code": "def load_builtin_plugins() -> int:\n    plugin_dir = os.path.join(os.path.dirname(__file__), 'plugins')\n    return load_plugins(plugin_dir, 'nonebot.plugins')",
    "docstring": "Load built-in plugins distributed along with \"nonebot\" package."
  },
  {
    "code": "def digest(self):\n        if self._digest is None:\n            if self._buf:\n                self._add_block(self._buf)\n                self._buf = EMPTY\n            ctx = self._blake2s(0, 1, True)\n            for t in self._thread:\n                ctx.update(t.digest())\n            self._digest = ctx.digest()\n        return self._digest",
    "docstring": "Return final digest value."
  },
  {
    "code": "def has_logs(self):\n        found_files = []\n        if self.logpath is None:\n            return found_files\n        if os.path.exists(self.logpath):\n            for root, _, files in os.walk(os.path.abspath(self.logpath)):\n                for fil in files:\n                    found_files.append(os.path.join(root, fil))\n        return found_files",
    "docstring": "Check if log files are available and return file names if they exist.\n\n        :return: list"
  },
  {
    "code": "def prepare_connection():\n    elasticsearch_host = getattr(settings, 'ELASTICSEARCH_HOST', 'localhost')\n    elasticsearch_port = getattr(settings, 'ELASTICSEARCH_PORT', 9200)\n    connections.create_connection(hosts=['{}:{}'.format(elasticsearch_host, elasticsearch_port)])",
    "docstring": "Set dafault connection for ElasticSearch.\n\n    .. warning::\n\n        In case of using multiprocessing/multithreading, connection will\n        be probably initialized in the main process/thread and the same\n        connection (socket) will be used in all processes/threads. This\n        will cause some unexpected timeouts of pushes to Elasticsearch.\n        So make sure that this function is called again in each\n        process/thread to make sure that unique connection will be used."
  },
  {
    "code": "def cmdloop(self):\n        while True:\n            cmdline = input(self.prompt)\n            tokens = shlex.split(cmdline)\n            if not tokens:\n                if self.last_cmd:\n                    tokens = self.last_cmd\n                else:\n                    print('No previous command.')\n                    continue\n            if tokens[0] not in self.commands:\n                print('Invalid command')\n                continue\n            command = self.commands[tokens[0]]\n            self.last_cmd = tokens\n            try:\n                if command(self.state, tokens):\n                    break\n            except CmdExit:\n                continue\n            except Exception as e:\n                if e not in self.safe_exceptions:\n                    logger.exception('Error!')",
    "docstring": "Start CLI REPL."
  },
  {
    "code": "def search(self):\n        logger.debug(\"Grafana search... %s\", cherrypy.request.method)\n        if cherrypy.request.method == 'OPTIONS':\n            cherrypy.response.headers['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE'\n            cherrypy.response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization'\n            cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'\n            cherrypy.request.handler = None\n            return {}\n        if getattr(cherrypy.request, 'json', None):\n            logger.debug(\"Posted data: %s\", cherrypy.request.json)\n        logger.debug(\"Grafana search returns: %s\", GRAFANA_TARGETS)\n        return GRAFANA_TARGETS",
    "docstring": "Request available queries\n\n        Posted data: {u'target': u''}\n\n        Return the list of available target queries\n\n        :return: See upper comment\n        :rtype: list"
  },
  {
    "code": "def reset(self):\n        self._count = 0\n        self._exception_count = 0\n        self._stat_start_time = None\n        self._time_sum = float(0)\n        self._time_min = float('inf')\n        self._time_max = float(0)\n        self._server_time_sum = float(0)\n        self._server_time_min = float('inf')\n        self._server_time_max = float(0)\n        self._server_time_stored = False\n        self._request_len_sum = float(0)\n        self._request_len_min = float('inf')\n        self._request_len_max = float(0)\n        self._reply_len_sum = float(0)\n        self._reply_len_min = float('inf')\n        self._reply_len_max = float(0)",
    "docstring": "Reset the statistics data for this object."
  },
  {
    "code": "def set_defaults(self, default_values, recursive = False):\n        result = Parameters()\n        if recursive:\n            RecursiveObjectWriter.copy_properties(result, default_values)\n            RecursiveObjectWriter.copy_properties(result, self)\n        else:\n            ObjectWriter.set_properties(result, default_values)\n            ObjectWriter.set_properties(result, self)\n        return result",
    "docstring": "Set default values from specified Parameters and returns a new Parameters object.\n\n        :param default_values: Parameters with default parameter values.\n\n        :param recursive: (optional) true to perform deep copy, and false for shallow copy. Default: false\n\n        :return: a new Parameters object."
  },
  {
    "code": "def profile(self):\n        with self._mutex:\n            if not self._profile:\n                profile = self._obj.get_profile()\n                self._profile = utils.nvlist_to_dict(profile.properties)\n        return self._profile",
    "docstring": "The manager's profile."
  },
  {
    "code": "def solve(self):\n        result = Formula(path_actions(a_star_search(\n            ({f: self.cube[f] for f in \"LUFDRB\"}, \n             self.cube.select_type(\"edge\") & self.cube.has_colour(self.cube[\"D\"].colour)), \n            self.cross_successors, \n            self.cross_state_value, \n            self.cross_goal, \n            )))\n        self.cube(result)\n        return result",
    "docstring": "Solve the cross."
  },
  {
    "code": "def mode(keys, axis=semantics.axis_default, weights=None, return_indices=False):\n    index = as_index(keys, axis)\n    if weights is None:\n        unique, weights = count(index)\n    else:\n        unique, weights = group_by(index).sum(weights)\n    bin = np.argmax(weights)\n    _mode = unique[bin]\n    if return_indices:\n        indices = index.sorter[index.start[bin]: index.stop[bin]]\n        return _mode, indices\n    else:\n        return _mode",
    "docstring": "compute the mode, or most frequent occuring key in a set\n\n    Parameters\n    ----------\n    keys : ndarray, [n_keys, ...]\n        input array. elements of 'keys' can have arbitrary shape or dtype\n    weights : ndarray, [n_keys], optional\n        if given, the contribution of each key to the mode is weighted by the given weights\n    return_indices : bool\n        if True, return all indices such that keys[indices]==mode holds\n\n    Returns\n    -------\n    mode : ndarray, [...]\n        the most frequently occuring key in the key sequence\n    indices : ndarray, [mode_multiplicity], int, optional\n        if return_indices is True, all indices such that points[indices]==mode holds"
  },
  {
    "code": "def get_module_names(package_path, pattern=\"lazy_*.py*\"):\n  package_contents = glob(os.path.join(package_path[0], pattern))\n  relative_path_names = (os.path.split(name)[1] for name in package_contents)\n  no_ext_names = (os.path.splitext(name)[0] for name in relative_path_names)\n  return sorted(set(no_ext_names))",
    "docstring": "All names in the package directory that matches the given glob, without\n  their extension. Repeated names should appear only once."
  },
  {
    "code": "def check_extensions(extensions: Set[str], allow_multifile: bool = False):\n    check_var(extensions, var_types=set, var_name='extensions')\n    for ext in extensions:\n        check_extension(ext, allow_multifile=allow_multifile)",
    "docstring": "Utility method to check that all extensions in the provided set are valid\n\n    :param extensions:\n    :param allow_multifile:\n    :return:"
  },
  {
    "code": "def DeleteAttachment(self, attachment_link, options=None):\n        if options is None:\n            options = {}\n        path = base.GetPathFromLink(attachment_link)\n        attachment_id = base.GetResourceIdOrFullNameFromLink(attachment_link)\n        return self.DeleteResource(path,\n                                   'attachments',\n                                   attachment_id,\n                                   None,\n                                   options)",
    "docstring": "Deletes an attachment.\n\n        :param str attachment_link:\n            The link to the attachment.\n        :param dict options:\n            The request options for the request.\n\n        :return:\n            The deleted Attachment.\n        :rtype:\n            dict"
  },
  {
    "code": "def _sample_stratum(self, pmf=None, replace=True):\n        if pmf is None:\n            pmf = self.weights_\n        if not replace:\n            empty = (self._n_sampled >= self.sizes_)\n            if np.any(empty):\n                pmf = copy.copy(pmf)\n                pmf[empty] = 0\n                if np.sum(pmf) == 0:\n                    raise(RuntimeError)\n                pmf /= np.sum(pmf)\n        return np.random.choice(self.indices_, p = pmf)",
    "docstring": "Sample a stratum\n\n        Parameters\n        ----------\n        pmf : array-like, shape=(n_strata,), optional, default None\n            probability distribution to use when sampling from the strata. If\n            not given, use the stratum weights.\n\n        replace : bool, optional, default True\n            whether to sample with replacement\n\n        Returns\n        -------\n        int\n            a randomly selected stratum index"
  },
  {
    "code": "def capture_sale(self, transaction_id, capture_amount, message=None):\n        request_data = {\n            \"amount\": self.base.convert_decimal_to_hundreds(capture_amount),\n            \"currency\": self.currency,\n            \"message\": message\n        }\n        url = \"%s%s%s/capture\" % (self.api_endpoint, constants.TRANSACTION_STATUS_ENDPOINT, transaction_id)\n        username = self.base.get_username()\n        password = self.base.get_password(username=username, request_url=url)\n        response = requests.put(url, json=request_data, auth=HTTPBasicAuth(username=username, password=password))\n        if response.status_code == 404:\n            raise TransactionDoesNotExist('Wrong transaction ID!')\n        if not self.base.verify_response(response.json()):\n            raise SignatureValidationException('Server signature verification has failed')\n        response_json = response.json()\n        return response_json.get('status')",
    "docstring": "Capture existing preauth.\n\n        :param transaction_id:\n        :param capture_amount:\n        :param message:\n        :return: status code"
  },
  {
    "code": "def _disbatch_runner_async(self, chunk):\n        pub_data = self.saltclients['runner'](chunk)\n        raise tornado.gen.Return(pub_data)",
    "docstring": "Disbatch runner client_async commands"
  },
  {
    "code": "def write_intro (self):\n        self.writeln(configuration.AppInfo)\n        self.writeln(configuration.Freeware)\n        self.writeln(_(\"Get the newest version at %(url)s\") %\n                     {'url': configuration.Url})\n        self.writeln(_(\"Write comments and bugs to %(url)s\") %\n                     {'url': configuration.SupportUrl})\n        self.writeln(_(\"Support this project at %(url)s\") %\n                     {'url': configuration.DonateUrl})\n        self.check_date()\n        self.writeln()\n        self.writeln(_(\"Start checking at %s\") %\n                     strformat.strtime(self.starttime))",
    "docstring": "Log introduction text."
  },
  {
    "code": "def ellplot (mjr, mnr, pa):\n    _ellcheck (mjr, mnr, pa)\n    import omega as om\n    th = np.linspace (0, 2 * np.pi, 200)\n    x, y = ellpoint (mjr, mnr, pa, th)\n    return om.quickXY (x, y, 'mjr=%f mnr=%f pa=%f' %\n                       (mjr, mnr, pa * 180 / np.pi))",
    "docstring": "Utility for debugging."
  },
  {
    "code": "def create_writer_of_type(type_name):\n    writers = available_writers()\n    if type_name not in writers.keys():\n        raise UnknownWriterException('Unknown writer: %s' % (type_name,))\n    return writers[type_name]()",
    "docstring": "Create an instance of the writer with the given name.\n\n        Args:\n            type_name: The name of a writer.\n\n        Returns:\n            An instance of the writer with the given type."
  },
  {
    "code": "def parse(self, nodes):\n    self.last_node_type = self.initial_node_type\n    for node_number, node in enumerate(nodes):\n      try:\n        self.step(node)\n      except Exception as ex:\n        raise Exception(\"An error occurred on node {}\".format(node_number)) from ex",
    "docstring": "Given a stream of node data, try to parse the nodes according to the machine's graph."
  },
  {
    "code": "def get_custom_annotations_recursive(data_type):\n    data_types_seen = set()\n    def recurse(data_type):\n        if data_type in data_types_seen:\n            return\n        data_types_seen.add(data_type)\n        dt, _, _ = unwrap(data_type)\n        if is_struct_type(dt) or is_union_type(dt):\n            for field in dt.fields:\n                for annotation in recurse(field.data_type):\n                    yield annotation\n                for annotation in field.custom_annotations:\n                    yield annotation\n        elif is_list_type(dt):\n            for annotation in recurse(dt.data_type):\n                yield annotation\n        elif is_map_type(dt):\n            for annotation in recurse(dt.value_data_type):\n                yield annotation\n        for annotation in get_custom_annotations_for_alias(data_type):\n            yield annotation\n    return recurse(data_type)",
    "docstring": "Given a Stone data type, returns all custom annotations applied to any of\n    its memebers, as well as submembers, ..., to an arbitrary depth."
  },
  {
    "code": "def fit(self, X, y=None):\n        X = self._check_array(X)\n        solver_kwargs = self._get_solver_kwargs()\n        self._coef = algorithms._solvers[self.solver](X, y, **solver_kwargs)\n        if self.fit_intercept:\n            self.coef_ = self._coef[:-1]\n            self.intercept_ = self._coef[-1]\n        else:\n            self.coef_ = self._coef\n        return self",
    "docstring": "Fit the model on the training data\n\n        Parameters\n        ----------\n        X: array-like, shape (n_samples, n_features)\n        y : array-like, shape (n_samples,)\n\n        Returns\n        -------\n        self : objectj"
  },
  {
    "code": "def process_nxml_file(fname, output_fmt='json', outbuf=None, cleanup=True,\n                      **kwargs):\n    sp = None\n    out_fname = None\n    try:\n        out_fname = run_sparser(fname, output_fmt, outbuf, **kwargs)\n        sp = process_sparser_output(out_fname, output_fmt)\n    except Exception as e:\n        logger.error(\"Sparser failed to run on %s.\" % fname)\n        logger.exception(e)\n    finally:\n        if out_fname is not None and os.path.exists(out_fname) and cleanup:\n            os.remove(out_fname)\n    return sp",
    "docstring": "Return processor with Statements extracted by reading an NXML file.\n\n    Parameters\n    ----------\n    fname : str\n        The path to the NXML file to be read.\n    output_fmt: Optional[str]\n        The output format to obtain from Sparser, with the two options being\n        'json' and 'xml'. Default: 'json'\n    outbuf : Optional[file]\n        A file like object that the Sparser output is written to.\n    cleanup : Optional[bool]\n        If True, the output file created by Sparser is removed.\n        Default: True\n\n    Returns\n    -------\n    sp : SparserXMLProcessor or SparserJSONProcessor depending on what output\n    format was chosen."
  },
  {
    "code": "def get_tokens(condition):\n        try:\n            ast_tokens = list(ast.walk(ast.parse(condition.strip())))\n        except SyntaxError as exception:\n            Logger.get_logger(__name__).error(\"Syntax error: %s\", exception)\n            ast_tokens = []\n        return ast_tokens",
    "docstring": "Get AST tokens for Python condition.\n\n        Returns:\n            list: list of AST tokens"
  },
  {
    "code": "def checkout_dirs(self):\n        directories = [os.path.join(self.base_directory, d)\n                       for d in os.listdir(self.base_directory)]\n        return [d for d in directories if os.path.isdir(d)]",
    "docstring": "Return directories inside the base directory."
  },
  {
    "code": "def drag_and_drop(self, source_selector, destination_selector, **kwargs):\n        self.info_log(\n            \"Drag and drop: source (%s); destination (%s)\" %\n            (source_selector, destination_selector)\n        )\n        use_javascript_dnd = kwargs.get(\n            \"use_javascript_dnd\",\n            \"proxy_driver:use_javascript_dnd\"\n        )\n        source_el = self.find(source_selector)\n        destination_el = self.find(destination_selector)\n        if use_javascript_dnd:\n            try:\n                dnd_script = [\n                    \"function simulate(f,c,d,e){var b,a=null;for(b in eventMatchers)if(eventMatchers[b].test(c)){a=b;break}if(!a)return!1;document.createEvent?(b=document.createEvent(a),a=='HTMLEvents'?b.initEvent(c,!0,!0):b.initMouseEvent(c,!0,!0,document.defaultView,0,d,e,d,e,!1,!1,!1,!1,0,null),f.dispatchEvent(b)):(a=document.createEventObject(),a.detail=0,a.screenX=d,a.screenY=e,a.clientX=d,a.clientY=e,a.ctrlKey=!1,a.altKey=!1,a.shiftKey=!1,a.metaKey=!1,a.button=1,f.fireEvent('on'+c,a));return!0} var eventMatchers={HTMLEvents:/^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,MouseEvents:/^(?:click|dblclick|mouse(?:down|up|over|move|out))$/};\",\n                    \"var source = arguments[0],destination = arguments[1];\",\n                    \"simulate(source, 'mousedown', 0, 0);\",\n                    \"simulate(source, 'mousemove', destination.offsetLeft, destination.offsetTop);\",\n                    \"simulate(source, 'mouseup', destination.offsetLeft, destination.offsetTop);\"\n                ]\n                self._driver.execute_script(\n                    '\\n'.join(dnd_script),\n                    source_el._element,\n                    destination_el._element\n                )\n            except Exception as e:\n                self.error_log(u'drag_and_drop exception: %s' % str(e))\n                raise\n        else:\n            try:\n                ActionChains(self._driver).drag_and_drop(\n                    source_el,\n                    destination_el\n                ).perform()\n            except Exception as e:\n                self.error_log(u'drag_and_drop exception: %s' % str(e))\n                raise",
    "docstring": "Drag and drop\n\n        Args:\n            source_selector: (str)\n            destination_selector: (str)\n\n        Kwargs:\n            use_javascript_dnd: bool; default:\n                config proxy_driver:use_javascript_dnd"
  },
  {
    "code": "def close_filenos(preserve):\n    maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]\n    if maxfd == resource.RLIM_INFINITY:\n        maxfd = 4096\n    for fileno in range(maxfd):\n        if fileno not in preserve:\n            try:\n                os.close(fileno)\n            except OSError as err:\n                if not err.errno == errno.EBADF:\n                    raise DaemonError(\n                        'Failed to close file descriptor {0}: {1}'\n                        .format(fileno, err))",
    "docstring": "Close unprotected file descriptors\n\n    Close all open file descriptors that are not in preserve.\n\n    If ulimit -nofile is \"unlimited\", all is defined filenos <= 4096,\n    else all is <= the output of resource.getrlimit().\n\n    :param preserve: set with protected files\n    :type preserve: set\n\n    :return: None"
  },
  {
    "code": "def _create_field_mapping_action(self):\n        icon = resources_path('img', 'icons', 'show-mapping-tool.svg')\n        self.action_field_mapping = QAction(\n            QIcon(icon),\n            self.tr('InaSAFE Field Mapping Tool'),\n            self.iface.mainWindow())\n        self.action_field_mapping.setStatusTip(self.tr(\n            'Assign field mapping to layer.'))\n        self.action_field_mapping.setWhatsThis(self.tr(\n            'Use this tool to assign field mapping in layer.'))\n        self.action_field_mapping.setEnabled(False)\n        self.action_field_mapping.triggered.connect(self.show_field_mapping)\n        self.add_action(\n            self.action_field_mapping, add_to_toolbar=self.full_toolbar)",
    "docstring": "Create action for showing field mapping dialog."
  },
  {
    "code": "def OnCardRightClick(self, event):\n        item = event.GetItem()\n        if item:\n            itemdata = self.readertreepanel.cardtreectrl.GetItemPyData(item)\n            if isinstance(itemdata, smartcard.Card.Card):\n                self.selectedcard = itemdata\n                if not hasattr(self, \"connectID\"):\n                    self.connectID = wx.NewId()\n                    self.disconnectID = wx.NewId()\n                    self.Bind(wx.EVT_MENU, self.OnConnect, id=self.connectID)\n                    self.Bind(\n                        wx.EVT_MENU, self.OnDisconnect, id=self.disconnectID)\n                menu = wx.Menu()\n                if not hasattr(self.selectedcard, 'connection'):\n                    menu.Append(self.connectID, \"Connect\")\n                else:\n                    menu.Append(self.disconnectID, \"Disconnect\")\n                self.PopupMenu(menu)\n                menu.Destroy()",
    "docstring": "Called when user right-clicks a node in the card tree control."
  },
  {
    "code": "def remove_column(self, column_name, inplace=False):\n        if column_name not in self.column_names():\n            raise KeyError('Cannot find column %s' % column_name)\n        if inplace:\n            self.__is_dirty__ = True\n            try:\n                with cython_context():\n                    if self._is_vertex_frame():\n                        assert column_name != '__id', 'Cannot remove \\\"__id\\\" column'\n                        graph_proxy = self.__graph__.__proxy__.delete_vertex_field(column_name)\n                        self.__graph__.__proxy__ = graph_proxy\n                    elif self._is_edge_frame():\n                        assert column_name != '__src_id', 'Cannot remove \\\"__src_id\\\" column'\n                        assert column_name != '__dst_id', 'Cannot remove \\\"__dst_id\\\" column'\n                        graph_proxy = self.__graph__.__proxy__.delete_edge_field(column_name)\n                        self.__graph__.__proxy__ = graph_proxy\n                return self\n            except:\n                self.__is_dirty__ = False\n                raise\n        else:\n            return super(GFrame, self).remove_column(column_name, inplace=inplace)",
    "docstring": "Removes the column with the given name from the SFrame.\n\n        If inplace == False (default) this operation does not modify the\n        current SFrame, returning a new SFrame.\n\n        If inplace == True, this operation modifies the current\n        SFrame, returning self.\n\n        Parameters\n        ----------\n        column_name : string\n            The name of the column to remove.\n\n        inplace : bool, optional. Defaults to False.\n            Whether the SFrame is modified in place."
  },
  {
    "code": "def _two_qubit_accumulate_into_scratch(args: Dict[str, Any]):\n    index0, index1 = args['indices']\n    half_turns = args['half_turns']\n    scratch = _scratch_shard(args)\n    projector = _one_projector(args, index0) * _one_projector(args, index1)\n    scratch += 2 * half_turns * projector",
    "docstring": "Accumulates two qubit phase gates into the scratch shards."
  },
  {
    "code": "def inserir(self, id_brand, name):\n        model_map = dict()\n        model_map['name'] = name\n        model_map['id_brand'] = id_brand\n        code, xml = self.submit({'model': model_map}, 'POST', 'model/')\n        return self.response(code, xml)",
    "docstring": "Inserts a new Model and returns its identifier\n\n        :param id_brand: Identifier of the Brand. Integer value and greater than zero.\n        :param name: Model name. String with a minimum 3 and maximum of 100 characters\n\n        :return: Dictionary with the following structure:\n\n        ::\n\n            {'model': {'id': < id_model >}}\n\n        :raise InvalidParameterError: The identifier of Brand or name is null and invalid.\n        :raise NomeMarcaModeloDuplicadoError: There is already a registered Model with the value of name and brand.\n        :raise MarcaNaoExisteError: Brand not registered.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response"
  },
  {
    "code": "def to_array(self, variables):\n        arr = np.zeros(len(variables), np.int8)\n        dc = dict(self)\n        for i, var in enumerate(variables):\n            arr[i] = dc.get(var, arr[i])\n        return arr",
    "docstring": "Converts the clamping to a 1-D array with respect to the given variables\n\n        Parameters\n        ----------\n        variables : list[str]\n            List of variables names\n\n\n        Returns\n        -------\n        `numpy.ndarray`_\n            1-D array where position `i` correspond to the sign of the clamped variable at\n            position `i` in the given list of variables\n\n\n        .. _numpy.ndarray: http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html#numpy.ndarray"
  },
  {
    "code": "def compare(left: Union[str, pathlib.Path, _Entity],\n            right: Union[str, pathlib.Path, _Entity]) -> Comparison:\n    def normalise(param: Union[str, pathlib.Path, _Entity]) -> _Entity:\n        if isinstance(param, str):\n            param = pathlib.Path(param)\n        if isinstance(param, pathlib.Path):\n            param = _Entity.from_path(param)\n        return param\n    return Comparison.compare(normalise(left), normalise(right))",
    "docstring": "Compare two paths.\n\n    :param left: The left side or \"before\" entity.\n    :param right: The right side or \"after\" entity.\n    :return: A comparison details what has changed from the left side to the\n             right side."
  },
  {
    "code": "def check_move(self, move_type, move_x, move_y):\n        if move_type not in self.move_types:\n            raise ValueError(\"This is not a valid move!\")\n        if move_x < 0 or move_x >= self.board_width:\n            raise ValueError(\"This is not a valid X position of the move!\")\n        if move_y < 0 or move_y >= self.board_height:\n            raise ValueError(\"This is not a valid Y position of the move!\")\n        move_des = {}\n        move_des[\"move_type\"] = move_type\n        move_des[\"move_x\"] = move_x\n        move_des[\"move_y\"] = move_y\n        self.num_moves += 1\n        return move_des",
    "docstring": "Check if a move is valid.\n\n        If the move is not valid, then shut the game.\n        If the move is valid, then setup a dictionary for the game,\n        and update move counter.\n\n        TODO: maybe instead of shut the game, can end the game or turn it into\n        a valid move?\n\n        Parameters\n        ----------\n        move_type : string\n            one of four move types:\n            \"click\", \"flag\", \"unflag\", \"question\"\n        move_x : int\n            X position of the move\n        move_y : int\n            Y position of the move"
  },
  {
    "code": "def defaults(cls, *options, **kwargs):\n        if kwargs and len(kwargs) != 1 and list(kwargs.keys())[0] != 'backend':\n            raise Exception('opts.defaults only accepts \"backend\" keyword argument')\n        cls._linemagic(cls._expand_options(merge_options_to_dict(options)), backend=kwargs.get('backend'))",
    "docstring": "Set default options for a session.\n\n        Set default options for a session. whether in a Python script or\n        a Jupyter notebook.\n\n        Args:\n           *options: Option objects used to specify the defaults.\n           backend:  The plotting extension the options apply to"
  },
  {
    "code": "def ancestor_of(self, name, ancestor, visited=None):\n        if visited is None:\n            visited = set()\n        node = self._nodes.get(name)\n        if node is None or name not in self._nodes:\n            return False\n        stack = list(node.parents)\n        while stack:\n            current = stack.pop()\n            if current == ancestor:\n                return True\n            if current not in visited:\n                visited.add(current)\n                node = self._nodes.get(current)\n                if node is not None:\n                    stack.extend(node.parents)\n        return False",
    "docstring": "Check whether a node has another node as an ancestor.\n\n        name: The name of the node being checked.\n        ancestor: The name of the (possible) ancestor node.\n        visited: (optional, None) If given, a set of nodes that have\n            already been traversed. NOTE: The set will be updated with\n            any new nodes that are visited.\n\n        NOTE: If node doesn't exist, the method will return False."
  },
  {
    "code": "def has_gap_in_elf_shndx(self):\n        if not self._ptr:\n            raise BfdException(\"BFD not initialized\")\n        return _bfd.get_bfd_attribute(\n            self._ptr, BfdAttributes.HAS_GAP_IN_ELF_SHNDX)",
    "docstring": "Return the has gap in elf shndx attribute of the BFD file being\n        processed."
  },
  {
    "code": "def dependencies(project_name):\n    log = logging.getLogger('ciu')\n    log.info('Locating dependencies for {}'.format(project_name))\n    located = distlib.locators.locate(project_name, prereleases=True)\n    if not located:\n        log.warning('{0} not found'.format(project_name))\n        return None\n    return {packaging.utils.canonicalize_name(pypi.just_name(dep))\n            for dep in located.run_requires}",
    "docstring": "Get the dependencies for a project."
  },
  {
    "code": "def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs):\n        url = \"{0}{1}/{2}\".format(\n            FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH\n        )\n        args = {\"client_id\": app_id, \"redirect_uri\": canvas_url}\n        if perms:\n            args[\"scope\"] = \",\".join(perms)\n        args.update(kwargs)\n        return url + urlencode(args)",
    "docstring": "Build a URL to create an OAuth dialog."
  },
  {
    "code": "def format_platforms(cls, platforms):\n        lines = []\n        if platforms:\n            lines.append('This DAP is only supported on the following platforms:')\n            lines.extend([' * ' + platform for platform in platforms])\n        return lines",
    "docstring": "Formats supported platforms in human readable form"
  },
  {
    "code": "def influx_query_(self, q):\n        if self.influx_cli is None:\n            self.err(\n                self.influx_query_,\n                \"No database connected. Please initialize a connection\")\n            return\n        try:\n            return self.influx_cli.query(q)\n        except Exception as e:\n            self.err(e, self.influx_query_,\n                     \"Can not query database\")",
    "docstring": "Runs an Influx db query"
  },
  {
    "code": "def register_parser(parser, subparsers_action=None, categories=('other', ), add_help=True):\n    name = re.sub('^dx ', '', parser.prog)\n    if subparsers_action is None:\n        subparsers_action = subparsers\n    if isinstance(categories, basestring):\n        categories = (categories, )\n    parser_map[name] = parser\n    if add_help:\n        _help = subparsers_action._choices_actions[-1].help\n        parser_categories['all']['cmds'].append((name, _help))\n        for category in categories:\n            parser_categories[category]['cmds'].append((name, _help))",
    "docstring": "Attaches `parser` to the global ``parser_map``. If `add_help` is truthy,\n    then adds the helpstring of `parser` into the output of ``dx help...``, for\n    each category in `categories`.\n\n    :param subparsers_action: A special action object that is returned by\n    ``ArgumentParser.add_subparsers(...)``, or None.\n    :type subparsers_action: argparse._SubParsersAction, or None."
  },
  {
    "code": "def validate_driver_or_none(option, value):\n    if value is None:\n        return value\n    if not isinstance(value, DriverInfo):\n        raise TypeError(\"%s must be an instance of DriverInfo\" % (option,))\n    return value",
    "docstring": "Validate the driver keyword arg."
  },
  {
    "code": "def gpg_key(value):\n    try:\n        return crypto.get_key(value)\n    except GPGProblem as e:\n        raise ValidateError(str(e))",
    "docstring": "test if value points to a known gpg key\n    and return that key as a gpg key object."
  },
  {
    "code": "def get_data(n_samples=100):\n    X, y = make_classification(\n        n_samples=n_samples,\n        n_features=N_FEATURES,\n        n_classes=N_CLASSES,\n        random_state=0,\n    )\n    X = X.astype(np.float32)\n    return X, y",
    "docstring": "Get synthetic classification data with n_samples samples."
  },
  {
    "code": "def normalize(body_part_tup,):\n    return '\\n\\n'.join(\n        [\n            '{}\\n\\n{}'.format(\n                str(p.headers[b'Content-Disposition'], p.encoding), p.text\n            )\n            for p in sorted(\n                body_part_tup, key=lambda p: p.headers[b'Content-Disposition']\n            )\n        ]\n    )",
    "docstring": "Normalize a tuple of BodyPart objects to a string.\n\n    Normalization is done by sorting the body_parts by the Content- Disposition headers,\n    which is typically on the form, ``form-data; name=\"name_of_part``."
  },
  {
    "code": "def disable_insecure_request_warning():\n    import requests\n    from requests.packages.urllib3.exceptions import InsecureRequestWarning\n    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)",
    "docstring": "Suppress warning about untrusted SSL certificate."
  },
  {
    "code": "def capture_url_missing_namespace(self, node):\n        for arg in node.args:\n            if not(isinstance(arg, ast.Call) and isinstance(arg.func, ast.Name)):\n                continue\n            if arg.func.id != 'include':\n                continue\n            for keyword in arg.keywords:\n                if keyword.arg == 'namespace':\n                    return\n            return DJ05(\n                lineno=node.lineno,\n                col=node.col_offset,\n            )",
    "docstring": "Capture missing namespace in url include."
  },
  {
    "code": "def wrap_callback(function):\n        @wraps(function)\n        def wrapped(task):\n            task._callback_result = function(task)\n            return task._callback_result\n        return wrapped",
    "docstring": "Set the callback's result as self._callback_result."
  },
  {
    "code": "def add_standard_attention_hparams(hparams):\n  hparams.add_hparam(\"num_heads\", 8)\n  hparams.add_hparam(\"attention_key_channels\", 0)\n  hparams.add_hparam(\"attention_value_channels\", 0)\n  hparams.add_hparam(\"attention_dropout\", 0.0)\n  hparams.add_hparam(\"attention_loc_block_length\", 256)\n  hparams.add_hparam(\"attention_loc_block_width\", 128)\n  hparams.add_hparam(\"attention_red_factor\", 3)\n  hparams.add_hparam(\"attention_red_type\", \"conv\")\n  hparams.add_hparam(\"attention_red_nonlinearity\", \"none\")\n  hparams.add_hparam(\"filter_size\", 2048)\n  hparams.add_hparam(\"relu_dropout\", 0.0)\n  return hparams",
    "docstring": "Adds the hparams used by get_standardized_layers."
  },
  {
    "code": "def update_dns_ha_resource_params(resources, resource_params,\n                                  relation_id=None,\n                                  crm_ocf='ocf:maas:dns'):\n    _relation_data = {'resources': {}, 'resource_params': {}}\n    update_hacluster_dns_ha(charm_name(),\n                            _relation_data,\n                            crm_ocf)\n    resources.update(_relation_data['resources'])\n    resource_params.update(_relation_data['resource_params'])\n    relation_set(relation_id=relation_id, groups=_relation_data['groups'])",
    "docstring": "Configure DNS-HA resources based on provided configuration and\n    update resource dictionaries for the HA relation.\n\n    @param resources: Pointer to dictionary of resources.\n                      Usually instantiated in ha_joined().\n    @param resource_params: Pointer to dictionary of resource parameters.\n                            Usually instantiated in ha_joined()\n    @param relation_id: Relation ID of the ha relation\n    @param crm_ocf: Corosync Open Cluster Framework resource agent to use for\n                    DNS HA"
  },
  {
    "code": "async def create(cls, block_device: BlockDevice, size: int):\n        params = {}\n        if isinstance(block_device, BlockDevice):\n            params['system_id'] = block_device.node.system_id\n            params['device_id'] = block_device.id\n        else:\n            raise TypeError(\n                'block_device must be a BlockDevice, not %s' % (\n                    type(block_device).__name__))\n        if not size:\n            raise ValueError(\"size must be provided and greater than zero.\")\n        params['size'] = size\n        return cls._object(await cls._handler.create(**params))",
    "docstring": "Create a partition on a block device.\n\n        :param block_device: BlockDevice to create the paritition on.\n        :type block_device: `BlockDevice`\n        :param size: The size of the partition in bytes.\n        :type size: `int`"
  },
  {
    "code": "def createSomeItems(store, itemType, values, counter):\n    for i in counter:\n        itemType(store=store, **values)",
    "docstring": "Create some instances of a particular type in a store."
  },
  {
    "code": "def user_info(self, kv):\n        key, value = kv\n        self.__user_info[key] = value",
    "docstring": "Sets user_info dict entry through a tuple."
  },
  {
    "code": "def process_items(r, keys, timeout, limit=0, log_every=1000, wait=.1):\n    limit = limit or float('inf')\n    processed = 0\n    while processed < limit:\n        ret = r.blpop(keys, timeout)\n        if ret is None:\n            time.sleep(wait)\n            continue\n        source, data = ret\n        try:\n            item = json.loads(data)\n        except Exception:\n            logger.exception(\"Failed to load item:\\n%r\", pprint.pformat(data))\n            continue\n        try:\n            name = item.get('name') or item.get('title')\n            url = item.get('url') or item.get('link')\n            logger.debug(\"[%s] Processing item: %s <%s>\", source, name, url)\n        except KeyError:\n            logger.exception(\"[%s] Failed to process item:\\n%r\",\n                             source, pprint.pformat(item))\n            continue\n        processed += 1\n        if processed % log_every == 0:\n            logger.info(\"Processed %s items\", processed)",
    "docstring": "Process items from a redis queue.\n\n    Parameters\n    ----------\n    r : Redis\n        Redis connection instance.\n    keys : list\n        List of keys to read the items from.\n    timeout: int\n        Read timeout."
  },
  {
    "code": "def is_str(string):\n    if sys.version_info[:2] >= (3, 0):\n        return isinstance(string, str)\n    return isinstance(string, basestring)",
    "docstring": "Python 2 and 3 compatible string checker.\n\n    Args:\n        string (str | basestring): the string to check\n\n    Returns:\n        bool: True or False"
  },
  {
    "code": "def chunker(iterable, size=5, fill=''):\n    for index in range(0, len(iterable) // size + 1):\n        to_yield = iterable[index * size: (index + 1) * size]\n        if len(to_yield) == 0:\n            break\n        if len(to_yield) < size:\n            yield to_yield + [fill] * (size - len(to_yield))\n        else:\n            yield to_yield",
    "docstring": "Chunk the iterable.\n\n    Parameters\n    ----------\n    iterable\n        A list.\n\n    size\n        The size of the chunks.\n\n    fill\n        Fill value if the chunk is not of length 'size'.\n\n    Yields\n    -------\n    chunk\n        A chunk of length 'size'.\n\n\n    Examples\n    -------\n    >>> l = list(range(6))\n    >>> chunks = list(chunker(l, size=4, fill=''))\n    >>> chunks == [[0, 1, 2, 3], [4, 5, '', '']]\n    True"
  },
  {
    "code": "def assert_keys_have_values(self, caller, *keys):\n        for key in keys:\n            self.assert_key_has_value(key, caller)",
    "docstring": "Check that keys list are all in context and all have values.\n\n        Args:\n            *keys: Will check each of these keys in context\n            caller: string. Calling function name - just used for informational\n                    messages\n\n        Raises:\n            KeyNotInContextError: Key doesn't exist\n            KeyInContextHasNoValueError: context[key] is None\n            AssertionError: if *keys is None"
  },
  {
    "code": "def _find_gvcf_blocks(vcf_file, region, tmp_dir):\n    region_file = os.path.join(tmp_dir, \"cur_region.bed\")\n    with open(region_file, \"w\") as out_handle:\n        chrom, coords = region.split(\":\")\n        start, end = coords.split(\"-\")\n        out_handle.write(\"\\t\".join([chrom, start, end]) + \"\\n\")\n    final_file = os.path.join(tmp_dir, \"split_regions.bed\")\n    cmd = \"gvcf_regions.py {vcf_file} | bedtools intersect -a - -b {region_file} > {final_file}\"\n    do.run(cmd.format(**locals()))\n    regions = []\n    with open(final_file) as in_handle:\n        for line in in_handle:\n            chrom, start, end = line.strip().split(\"\\t\")\n            regions.append(\"%s:%s-%s\" % (chrom, start, end))\n    return regions",
    "docstring": "Retrieve gVCF blocks within our current evaluation region.\n\n    gvcfgenotyper does not support calling larger regions with individual\n    coverage blocks, so we split our big region into potentially multiple."
  },
  {
    "code": "def load_from_dict(self, conf_dict=None):\n        self.set_to_default()\n        self._update_dict(self._config, conf_dict)\n        self._update_python_paths()",
    "docstring": "Load the configuration from a dictionary.\n\n        Args:\n            conf_dict (dict): Dictionary with the configuration."
  },
  {
    "code": "def make_headers(context: TraceContext) -> Headers:\n    headers = {\n        TRACE_ID_HEADER: context.trace_id,\n        SPAN_ID_HEADER: context.span_id,\n        FLAGS_HEADER: '0',\n        SAMPLED_ID_HEADER: '1' if context.sampled else '0',\n    }\n    if context.parent_id is not None:\n        headers[PARENT_ID_HEADER] = context.parent_id\n    return headers",
    "docstring": "Creates dict with zipkin headers from supplied trace context."
  },
  {
    "code": "def validate(self):\n        validate_marked_location(self.location)\n        if not isinstance(self.optional, bool):\n            raise TypeError(u'Expected bool optional, got: {} {}'.format(\n                type(self.optional).__name__, self.optional))",
    "docstring": "Ensure that the Backtrack block is valid."
  },
  {
    "code": "def grepPDF(self, path):\n    with open(path, 'rb') as pdf_file_obj:\n      match = set()\n      text = ''\n      pdf_reader = PyPDF2.PdfFileReader(pdf_file_obj)\n      pages = pdf_reader.numPages\n      for page in range(pages):\n        page_obj = pdf_reader.getPage(page)\n        text += '\\n' + page_obj.extractText()\n      match.update(set(x.lower() for x in re.findall(\n          self._keywords, text, re.IGNORECASE)))\n    return match",
    "docstring": "Parse PDF files text content for keywords.\n\n    Args:\n      path: PDF file path.\n\n    Returns:\n      match: set of unique occurrences of every match."
  },
  {
    "code": "def rename_file(self, old_path, new_path):\n        self.log.debug(\"S3contents.GenericManager: Init rename of '%s' to '%s'\", old_path, new_path)\n        if self.file_exists(new_path) or self.dir_exists(new_path):\n            self.already_exists(new_path)\n        elif self.file_exists(old_path) or self.dir_exists(old_path):\n            self.log.debug(\"S3contents.GenericManager: Actually renaming '%s' to '%s'\", old_path,\n                           new_path)\n            self.fs.mv(old_path, new_path)\n        else:\n            self.no_such_entity(old_path)",
    "docstring": "Rename a file or directory.\n\n        NOTE: This method is unfortunately named on the base class.  It\n        actually moves a file or a directory."
  },
  {
    "code": "def prepare_env(org):\n    key_service = org.service(type='builtin:cobalt_secure_store', name='Keystore')\n    wf_service = org.service(type='builtin:workflow_service', name='Workflow', parameters='{}')\n    env = org.environment(name='default')\n    env.clean()\n    env.add_service(key_service)\n    env.add_service(wf_service)\n    env.add_policy(\n        {\"action\": \"provisionVms\",\n         \"parameter\": \"publicKeyId\",\n         \"value\": key_service.regenerate()['id']})\n    access = {\n      \"provider\": \"aws-ec2\",\n      \"usedEnvironments\": [],\n      \"ec2SecurityGroup\": \"default\",\n      \"providerCopy\": \"aws-ec2\",\n      \"name\": \"test-provider\",\n      \"jcloudsIdentity\": KEY,\n      \"jcloudsCredential\": SECRET_KEY,\n      \"jcloudsRegions\": \"us-east-1\"\n    }\n    prov = org.provider(access)\n    env.add_provider(prov)\n    return org.organizationId",
    "docstring": "Example shows how to configure environment from scratch"
  },
  {
    "code": "def process_metadata(pkg_name, metadata_lines):\n    tpip_pkg = dict(\n        PkgName=pkg_name,\n        PkgType='python package',\n        PkgMgrURL='https://pypi.org/project/%s/' % pkg_name,\n    )\n    for line in metadata_lines:\n        get_package_info_from_line(tpip_pkg, line)\n    if 'PkgAuthorEmail' in tpip_pkg:\n        tpip_pkg['PkgOriginator'] = '%s <%s>' % (\n            tpip_pkg['PkgOriginator'],\n            tpip_pkg.pop('PkgAuthorEmail')\n        )\n    explicit_license = license_cleanup(tpip_pkg.get('PkgLicense'))\n    license_candidates = tpip_pkg.pop('PkgLicenses', [])\n    if explicit_license:\n        tpip_pkg['PkgLicense'] = explicit_license\n    else:\n        tpip_pkg['PkgLicense'] = ' '.join(set(license_candidates))\n    return tpip_pkg",
    "docstring": "Create a dictionary containing the relevant fields.\n\n    The following is an example of the generated dictionary:\n\n    :Example:\n\n    {\n        'name': 'six',\n        'version': '1.11.0',\n        'repository': 'pypi.python.org/pypi/six',\n        'licence': 'MIT',\n        'classifier': 'MIT License'\n    }\n\n    :param str pkg_name: name of the package\n    :param metadata_lines: metadata resource as list of non-blank non-comment lines\n    :returns: Dictionary of each of the fields\n    :rtype: Dict[str, str]"
  },
  {
    "code": "def make_prototype_request(*args, **kwargs):\n    if args and inspect.isclass(args[0]) and issubclass(args[0], Request):\n        request_cls, arg_list = args[0], args[1:]\n        return request_cls(*arg_list, **kwargs)\n    if args and isinstance(args[0], Request):\n        if args[1:] or kwargs:\n            raise_args_err(\"can't interpret args\")\n        return args[0]\n    return Request(*args, **kwargs)",
    "docstring": "Make a prototype Request for a Matcher."
  },
  {
    "code": "def inverse(self):\n        if self.scalar == 0.0:\n            raise ZeroDivisionError('scaling operator not invertible for '\n                                    'scalar==0')\n        return ScalingOperator(self.domain, 1.0 / self.scalar)",
    "docstring": "Return the inverse operator.\n\n        Examples\n        --------\n        >>> r3 = odl.rn(3)\n        >>> vec = r3.element([1, 2, 3])\n        >>> op = ScalingOperator(r3, 2.0)\n        >>> inv = op.inverse\n        >>> inv(op(vec)) == vec\n        True\n        >>> op(inv(vec)) == vec\n        True"
  },
  {
    "code": "def check(self, user, provider, permission, **kwargs):\n        try:\n            social_user = self._get_social_user(user, provider)\n            if not social_user:\n                return False\n        except SocialUserDoesNotExist:\n            return False\n        backend = self.get_backend(social_user, provider, context=kwargs)\n        return backend.check(permission)",
    "docstring": "user - django User or UserSocialAuth instance\n            provider - name of publisher provider\n            permission - if backend maintains check permissions\n                            vk - binary mask in int format\n                            facebook - scope string"
  },
  {
    "code": "def get_param(self, name):\n        value = c_uint64(0)\n        windivert_dll.WinDivertGetParam(self._handle, name, byref(value))\n        return value.value",
    "docstring": "Get a WinDivert parameter. See pydivert.Param for the list of parameters.\n\n        The remapped function is WinDivertGetParam::\n\n            BOOL WinDivertGetParam(\n                __in HANDLE handle,\n                __in WINDIVERT_PARAM param,\n                __out UINT64 *pValue\n            );\n\n        For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_get_param\n\n        :return: The parameter value."
  },
  {
    "code": "def _get_handler_set(cls, request, fail_enum, header_proto=None):\n        added = set()\n        handlers = []\n        for controls in request.sorting:\n            control_bytes = controls.SerializeToString()\n            if control_bytes not in added:\n                added.add(control_bytes)\n                handlers.append(\n                    cls._ValueHandler(controls, fail_enum, header_proto))\n        return handlers",
    "docstring": "Goes through the list of ClientSortControls and returns a list of\n        unique _ValueHandlers. Maintains order, but drops ClientSortControls\n        that have already appeared to help prevent spamming."
  },
  {
    "code": "def open_recruitment(self, n=1):\n        logger.info(\"Multi recruitment running for {} participants\".format(n))\n        recruitments = []\n        messages = {}\n        remaining = n\n        for recruiter, count in self.recruiters(n):\n            if not count:\n                break\n            if recruiter.nickname in messages:\n                result = recruiter.recruit(count)\n                recruitments.extend(result)\n            else:\n                result = recruiter.open_recruitment(count)\n                recruitments.extend(result[\"items\"])\n                messages[recruiter.nickname] = result[\"message\"]\n            remaining -= count\n            if remaining <= 0:\n                break\n        logger.info(\n            (\n                \"Multi-recruited {} out of {} participants, \" \"using {} recruiters.\"\n            ).format(n - remaining, n, len(messages))\n        )\n        return {\"items\": recruitments, \"message\": \"\\n\".join(messages.values())}",
    "docstring": "Return initial experiment URL list."
  },
  {
    "code": "def load_tree(self):\n        timeperiod = settings.settings['synergy_start_timeperiod']\n        yearly_timeperiod = time_helper.cast_to_time_qualifier(QUALIFIER_YEARLY, timeperiod)\n        monthly_timeperiod = time_helper.cast_to_time_qualifier(QUALIFIER_MONTHLY, timeperiod)\n        daily_timeperiod = time_helper.cast_to_time_qualifier(QUALIFIER_DAILY, timeperiod)\n        hourly_timeperiod = time_helper.cast_to_time_qualifier(QUALIFIER_HOURLY, timeperiod)\n        self._build_tree_by_level(QUALIFIER_HOURLY, COLLECTION_JOB_HOURLY, since=hourly_timeperiod)\n        self._build_tree_by_level(QUALIFIER_DAILY, COLLECTION_JOB_DAILY, since=daily_timeperiod)\n        self._build_tree_by_level(QUALIFIER_MONTHLY, COLLECTION_JOB_MONTHLY, since=monthly_timeperiod)\n        self._build_tree_by_level(QUALIFIER_YEARLY, COLLECTION_JOB_YEARLY, since=yearly_timeperiod)",
    "docstring": "method iterates thru all objects older than synergy_start_timeperiod parameter in job collections\n        and loads them into this timetable"
  },
  {
    "code": "def mark_read(self):\n        raise NotImplementedError(\n            \"The Kippt API does not yet support marking notifications as read.\"\n        )\n        data = json.dumps({\"action\": \"mark_seen\"})\n        r = requests.post(\n            \"https://kippt.com/api/notifications\",\n            headers=self.kippt.header,\n            data=data\n        )\n        return (r.json())",
    "docstring": "Mark notifications as read.\n\n        CURRENT UNSUPPORTED:\n        https://github.com/kippt/api-documentation/blob/master/endpoints/notifications/POST_notifications.md"
  },
  {
    "code": "def remove_variants(self, variants):\n        chroms = set([i.chrom for i in variants])\n        for chrom in chroms:\n            if self.append_chromosome:\n                chrom = 'chr%s' % chrom\n            to_delete = [pos for pos in self.positions[chrom] if pos in variants]\n            for pos in to_delete:\n                del self.positions[chrom][pos]",
    "docstring": "Remove a list of variants from the positions we are scanning"
  },
  {
    "code": "def transliterate(table, text):\n    if table == 'sr-Latn':\n        return text.translate(SR_LATN_TABLE)\n    elif table == 'az-Latn':\n        return text.translate(AZ_LATN_TABLE)\n    else:\n        raise ValueError(\"Unknown transliteration table: {!r}\".format(table))",
    "docstring": "Transliterate text according to one of the tables above.\n\n    `table` chooses the table. It looks like a language code but comes from a\n    very restricted set:\n\n    - 'sr-Latn' means to convert Serbian, which may be in Cyrillic, into the\n      Latin alphabet.\n    - 'az-Latn' means the same for Azerbaijani Cyrillic to Latn."
  },
  {
    "code": "def vm_info(name, quiet=False):\n    data = query(quiet=True)\n    return _find_vm(name, data, quiet)",
    "docstring": "Return the information on the named VM"
  },
  {
    "code": "def getatom(self, atomends=None):\n        atomlist = ['']\n        if atomends is None:\n            atomends = self.atomends\n        while self.pos < len(self.field):\n            if self.field[self.pos] in atomends:\n                break\n            else:\n                atomlist.append(self.field[self.pos])\n            self.pos += 1\n        return EMPTYSTRING.join(atomlist)",
    "docstring": "Parse an RFC 2822 atom.\n\n        Optional atomends specifies a different set of end token delimiters\n        (the default is to use self.atomends).  This is used e.g. in\n        getphraselist() since phrase endings must not include the `.' (which\n        is legal in phrases)."
  },
  {
    "code": "def configure_visual_directories(cls, driver_info):\n        if cls.screenshots_directory is None:\n            date = datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S')\n            folder_name = '%s_%s' % (date, driver_info) if driver_info else date\n            folder_name = get_valid_filename(folder_name)\n            cls.screenshots_directory = os.path.join(cls.output_directory, 'screenshots', folder_name)\n            cls.screenshots_number = 1\n            cls.videos_directory = os.path.join(cls.output_directory, 'videos', folder_name)\n            cls.logs_directory = os.path.join(cls.output_directory, 'logs', folder_name)\n            cls.videos_number = 1\n            cls.visual_output_directory = os.path.join(cls.output_directory, 'visualtests', folder_name)\n            cls.visual_number = 1",
    "docstring": "Configure screenshots, videos and visual directories\n\n        :param driver_info: driver property value to name folders"
  },
  {
    "code": "def parse_line(self, line):\n        line = line.lstrip()\n        toks = shlex.split(line)\n        cmd = toks[0]\n        arg = line[len(cmd):]\n        return cmd, [ arg, ]",
    "docstring": "Parser for the debugging shell.\n\n        Treat everything after the first token as one literal entity. Whitespace\n        characters between the first token and the next first non-whitespace\n        character are preserved.\n\n        For example, '  foo   dicj didiw  ' is parsed as\n            ( 'foo', '   dicj didiw  ' )\n\n        Returns:\n            A tuple (cmd, args), where the args is a list that consists of one\n            and only one string containing everything after the cmd as is."
  },
  {
    "code": "def _InitializeGraph(self, os_name, artifact_list):\n    dependencies = artifact_registry.REGISTRY.SearchDependencies(\n        os_name, artifact_list)\n    artifact_names, attribute_names = dependencies\n    self._AddAttributeNodes(attribute_names)\n    self._AddArtifactNodesAndEdges(artifact_names)",
    "docstring": "Creates the nodes and directed edges of the dependency graph.\n\n    Args:\n      os_name: String specifying the OS name.\n      artifact_list: List of requested artifact names."
  },
  {
    "code": "def set_as_data(self, as_data):\r\n        self._as_data = as_data\r\n        self.asDataChanged.emit(as_data)",
    "docstring": "Set if data type conversion"
  },
  {
    "code": "def make_cookie(name, load, seed, expire=0, domain=\"\", path=\"\",\n                timestamp=\"\"):\n    cookie = SimpleCookie()\n    if not timestamp:\n        timestamp = str(int(time.mktime(time.gmtime())))\n    signature = cookie_signature(seed, load, timestamp)\n    cookie[name] = \"|\".join([load, timestamp, signature])\n    if path:\n        cookie[name][\"path\"] = path\n    if domain:\n        cookie[name][\"domain\"] = domain\n    if expire:\n        cookie[name][\"expires\"] = _expiration(expire,\n                                              \"%a, %d-%b-%Y %H:%M:%S GMT\")\n    return tuple(cookie.output().split(\": \", 1))",
    "docstring": "Create and return a cookie\n\n    :param name: Cookie name\n    :param load: Cookie load\n    :param seed: A seed for the HMAC function\n    :param expire: Number of minutes before this cookie goes stale\n    :param domain: The domain of the cookie\n    :param path: The path specification for the cookie\n    :return: A tuple to be added to headers"
  },
  {
    "code": "def plat_specific_errors(*errnames):\n    missing_attr = set([None, ])\n    unique_nums = set(getattr(errno, k, None) for k in errnames)\n    return list(unique_nums - missing_attr)",
    "docstring": "Return error numbers for all errors in errnames on this platform.\n\n    The 'errno' module contains different global constants depending on\n    the specific platform (OS). This function will return the list of\n    numeric values for a given list of potential names."
  },
  {
    "code": "def from_other(cls, item):\n        if isinstance(item, Bitmath):\n            return cls(bits=item.bits)\n        else:\n            raise ValueError(\"The provided items must be a valid bitmath class: %s\" %\n                             str(item.__class__))",
    "docstring": "Factory function to return instances of `item` converted into a new\ninstance of ``cls``. Because this is a class method, it may be called\nfrom any bitmath class object without the need to explicitly\ninstantiate the class ahead of time.\n\n*Implicit Parameter:*\n\n* ``cls`` A bitmath class, implicitly set to the class of the\n  instance object it is called on\n\n*User Supplied Parameter:*\n\n* ``item`` A :class:`bitmath.Bitmath` subclass instance\n\n*Example:*\n\n   >>> import bitmath\n   >>> kib = bitmath.KiB.from_other(bitmath.MiB(1))\n   >>> print kib\n   KiB(1024.0)"
  },
  {
    "code": "def key(\n        seq: Sequence,\n        tooth: Callable[[Sequence], str] = (\n            lambda seq: str(random.SystemRandom().choice(seq)).strip()\n        ),\n        nteeth: int = 6,\n        delimiter: str = ' ',\n) -> str:\n    return delimiter.join(tooth(seq) for _ in range(nteeth))",
    "docstring": "Concatenate strings generated by the tooth function."
  },
  {
    "code": "def load_df(self, df):\n    self.reset()\n    df_dict = {}\n    df_dict['mat'] = deepcopy(df)\n    data_formats.df_to_dat(self, df_dict, define_cat_colors=True)",
    "docstring": "Load Pandas DataFrame."
  },
  {
    "code": "def _infer_map(node, context):\n    values = {}\n    for name, value in node.items:\n        if isinstance(name, nodes.DictUnpack):\n            double_starred = helpers.safe_infer(value, context)\n            if not double_starred:\n                raise exceptions.InferenceError\n            if not isinstance(double_starred, nodes.Dict):\n                raise exceptions.InferenceError(node=node, context=context)\n            unpack_items = _infer_map(double_starred, context)\n            values = _update_with_replacement(values, unpack_items)\n        else:\n            key = helpers.safe_infer(name, context=context)\n            value = helpers.safe_infer(value, context=context)\n            if any(not elem for elem in (key, value)):\n                raise exceptions.InferenceError(node=node, context=context)\n            values = _update_with_replacement(values, {key: value})\n    return values",
    "docstring": "Infer all values based on Dict.items"
  },
  {
    "code": "def is_data_dependent(fmto, data):\n    if callable(fmto.data_dependent):\n        return fmto.data_dependent(data)\n    return fmto.data_dependent",
    "docstring": "Check whether a formatoption is data dependent\n\n    Parameters\n    ----------\n    fmto: Formatoption\n        The :class:`Formatoption` instance to check\n    data: xarray.DataArray\n        The data array to use if the :attr:`~Formatoption.data_dependent`\n        attribute is a callable\n\n    Returns\n    -------\n    bool\n        True, if the formatoption depends on the data"
  },
  {
    "code": "def get_woeid(lat, lon):\n    yql = _YQL_WOEID.format(lat, lon)\n    tmpData = _yql_query(yql)\n    if tmpData is None:\n        _LOGGER.error(\"No woid is received!\")\n        return None\n    return tmpData.get(\"place\", {}).get(\"woeid\", None)",
    "docstring": "Ask Yahoo! who is the woeid from GPS position."
  },
  {
    "code": "def mesh(**kwargs):\n    obs_params = []\n    syn_params, constraints = mesh_syn(syn=False, **kwargs)\n    obs_params += syn_params.to_list()\n    obs_params += [SelectParameter(qualifier='include_times', value=kwargs.get('include_times', []), description='append to times from the following datasets/time standards', choices=['t0@system'])]\n    obs_params += [SelectParameter(qualifier='columns', value=kwargs.get('columns', []), description='columns to expose within the mesh', choices=_mesh_columns)]\n    return ParameterSet(obs_params), constraints",
    "docstring": "Create parameters for a new mesh dataset.\n\n    Generally, this will be used as an input to the kind argument in\n    :meth:`phoebe.frontend.bundle.Bundle.add_dataset`\n\n    :parameter **kwargs: defaults for the values of any of the parameters\n    :return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly\n        created :class:`phoebe.parameters.parameters.Parameter`s"
  },
  {
    "code": "def has_ended(self):\n        assessment_offered = self.get_assessment_offered()\n        now = DateTime.utcnow()\n        if self._my_map['completionTime'] is not None:\n            return True\n        elif assessment_offered.has_deadline() and assessment_offered.has_duration():\n            if self._my_map['actualStartTime'] is None:\n                return now >= assessment_offered.get_deadline()\n            else:\n                return (now >= assessment_offered.get_deadline() and\n                        now >= self._my_map['actualStartTime'] + assessment_offered.get_duration())\n        elif assessment_offered.has_deadline():\n            return now >= assessment_offered.get_deadline()\n        elif assessment_offered.has_duration() and self._my_map['actualStartTime'] is not None:\n            return now >= self._my_map['actualStartTime'] + assessment_offered.get_duration()\n        else:\n            return False",
    "docstring": "Tests if this assessment has ended.\n\n        return: (boolean) - ``true`` if the assessment has ended,\n                ``false`` otherwise\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def add_distances(self, indices, periodic=True, indices2=None):\n        r\n        from .distances import DistanceFeature\n        atom_pairs = _parse_pairwise_input(\n            indices, indices2, self.logger, fname='add_distances()')\n        atom_pairs = self._check_indices(atom_pairs)\n        f = DistanceFeature(self.topology, atom_pairs, periodic=periodic)\n        self.__add_feature(f)",
    "docstring": "r\"\"\"\n        Adds the distances between atoms to the feature list.\n\n        Parameters\n        ----------\n        indices : can be of two types:\n\n                ndarray((n, 2), dtype=int):\n                    n x 2 array with the pairs of atoms between which the distances shall be computed\n\n                iterable of integers (either list or ndarray(n, dtype=int)):\n                    indices (not pairs of indices) of the atoms between which the distances shall be computed.\n\n        periodic : optional, boolean, default is True\n            If periodic is True and the trajectory contains unitcell information,\n            distances will be computed under the minimum image convention.\n\n        indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:\n                    Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,\n                    only the distances between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.\n\n\n        .. note::\n            When using the iterable of integers input, :py:obj:`indices` and :py:obj:`indices2`\n            will be sorted numerically and made unique before converting them to a pairlist.\n            Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added."
  },
  {
    "code": "def save_network_to_file(self, filename = \"network0.pkl\" ):\n        import cPickle, os, re\n        if filename == \"network0.pkl\":\n            while os.path.exists( os.path.join(os.getcwd(), filename )):\n                filename = re.sub('\\d(?!\\d)', lambda x: str(int(x.group(0)) + 1), filename)\n        with open( filename , 'wb') as file:\n            store_dict = {\n                \"n_inputs\"             : self.n_inputs,\n                \"layers\"               : self.layers,\n                \"n_weights\"            : self.n_weights,\n                \"weights\"              : self.weights,\n            }\n            cPickle.dump( store_dict, file, 2 )",
    "docstring": "This save method pickles the parameters of the current network into a \n        binary file for persistant storage."
  },
  {
    "code": "async def render_template_string(source: str, **context: Any) -> str:\n    await current_app.update_template_context(context)\n    template = current_app.jinja_env.from_string(source)\n    return await _render(template, context)",
    "docstring": "Render the template source with the context given.\n\n    Arguments:\n        source: The template source code.\n        context: The variables to pass to the template."
  },
  {
    "code": "def _url_base64_encode(msg):\n        msg_base64 = base64.b64encode(msg)\n        msg_base64 = msg_base64.replace('+', '-')\n        msg_base64 = msg_base64.replace('=', '_')\n        msg_base64 = msg_base64.replace('/', '~')\n        return msg_base64",
    "docstring": "Base64 encodes a string using the URL-safe characters specified by\n        Amazon."
  },
  {
    "code": "def get_source_event_declaration(self, event):\n        return next((x.source_mapping for x in self.events if x.name == event))",
    "docstring": "Return the source mapping where the event is declared\n\n        Args:\n            event (str): event name\n        Returns:\n            (dict): sourceMapping"
  },
  {
    "code": "def solve(self, value, filter_):\n        args, kwargs = filter_.get_args_and_kwargs()\n        source = self.registry[value]\n        return source.solve(value, filter_.name, args, kwargs)",
    "docstring": "Returns the value of an attribute of the value, or the result of a call to a function.\n\n        Arguments\n        ---------\n        value : ?\n            A value to solve in combination with the given filter.\n        filter_ : dataql.resource.Filter\n            An instance of ``Filter`` to solve with the given value.\n\n        Returns\n        -------\n        Depending on the source, the filter may ask for an attribute of the value, or for the\n        result of a call to a standalone function taking the value as first argument.\n        This method returns this attribute or result.\n\n        Example\n        -------\n\n        >>> from dataql.solvers.registry import Registry\n        >>> registry = Registry()\n        >>> from datetime import date\n        >>> registry.register(date, ['day', 'strftime'])\n        >>> solver = FilterSolver(registry)\n        >>> solver.solve(date(2015, 6, 1), Filter(name='day'))\n        1\n        >>> from dataql.resources import PosArg\n        >>> solver.solve(date(2015, 6, 1), Filter(name='strftime', args=[PosArg('%F')]))\n        '2015-06-01'"
  },
  {
    "code": "def _check_valid_data(self, data):\n        if data.dtype.type is not np.uint8:\n            raise ValueError(\n                'Illegal data type. Color images only support uint8 arrays')\n        if len(data.shape) != 3 or data.shape[2] != 3:\n            raise ValueError(\n                'Illegal data type. Color images only support three channels')",
    "docstring": "Checks that the given data is a uint8 array with one or three\n        channels.\n\n        Parameters\n        ----------\n        data : :obj:`numpy.ndarray`\n            The data to check.\n\n        Raises\n        ------\n        ValueError\n            If the data is invalid."
  },
  {
    "code": "def get_assignment_by_name(self, assignment_name, assignments=None):\n        if assignments is None:\n            assignments = self.get_assignments()\n        for assignment in assignments:\n            if assignment['name'] == assignment_name:\n                return assignment['assignmentId'], assignment\n        return None, None",
    "docstring": "Get assignment by name.\n\n        Get an assignment by name. It works by retrieving all assignments\n        and returning the first assignment with a matching name. If the\n        optional parameter ``assignments`` is provided, it uses this\n        collection rather than retrieving all assignments from the service.\n\n        Args:\n            assignment_name (str): name of assignment\n            assignments (list): assignments to search, default: None\n                When ``assignments`` is unspecified, all assignments\n                are retrieved from the service.\n\n        Raises:\n            requests.RequestException: Exception connection error\n            ValueError: Unable to decode response content\n\n        Returns:\n            tuple: tuple of assignment id and assignment dictionary\n\n            .. code-block:: python\n\n                (\n                    16708850,\n                    {\n                        u'assignmentId': 16708850,\n                        u'categoryId': 1293820,\n                        u'description': u'',\n                        u'dueDate': 1383541200000,\n                        u'dueDateString': u'11-04-2013',\n                        u'gradebookId': 1293808,\n                        u'graderVisible': False,\n                        u'gradingSchemeId': 16708851,\n                        u'gradingSchemeType': u'NUMERIC',\n                        u'isComposite': False,\n                        u'isHomework': False,\n                        u'maxPointsTotal': 100.0,\n                        u'name': u'midterm1',\n                        u'shortName': u'mid1',\n                        u'userDeleted': False,\n                        u'weight': 1.0\n                    }\n                )"
  },
  {
    "code": "def WriteUInt256(self, value):\n        if type(value) is UInt256:\n            value.Serialize(self)\n        else:\n            raise Exception(\"Cannot write value that is not UInt256\")",
    "docstring": "Write a UInt256 type to the stream.\n\n        Args:\n            value (UInt256):\n\n        Raises:\n            Exception: when `value` is not of neocore.UInt256 type."
  },
  {
    "code": "def get_magnitude_depth_distribution(self, magnitude_bins, depth_bins,\n                                         normalisation=False, bootstrap=None):\n        if len(self.data['depth']) == 0:\n            raise ValueError('Depths missing in catalogue')\n        if len(self.data['depthError']) == 0:\n            self.data['depthError'] = np.zeros(self.get_number_events(),\n                                               dtype=float)\n        if len(self.data['sigmaMagnitude']) == 0:\n            self.data['sigmaMagnitude'] = np.zeros(self.get_number_events(),\n                                                   dtype=float)\n        return bootstrap_histogram_2D(self.data['magnitude'],\n                                      self.data['depth'],\n                                      magnitude_bins,\n                                      depth_bins,\n                                      boundaries=[(0., None), (None, None)],\n                                      xsigma=self.data['sigmaMagnitude'],\n                                      ysigma=self.data['depthError'],\n                                      normalisation=normalisation,\n                                      number_bootstraps=bootstrap)",
    "docstring": "Returns a 2-D magnitude-depth histogram for the catalogue\n\n        :param numpy.ndarray magnitude_bins:\n             Bin edges for the magnitudes\n\n        :param numpy.ndarray depth_bins:\n            Bin edges for the depths\n\n        :param bool normalisation:\n            Choose to normalise the results such that the total contributions\n            sum to 1.0 (True) or not (False)\n\n        :param int bootstrap:\n            Number of bootstrap samples\n\n        :returns:\n            2D histogram of events in magnitude-depth bins"
  },
  {
    "code": "def stopall(self, sudo=False, quiet=True):\n    from spython.utils import run_command, check_install\n    check_install()\n    subgroup = 'instance.stop'\n    if 'version 3' in self.version():\n        subgroup = [\"instance\", \"stop\"]\n    cmd = self._init_command(subgroup)\n    cmd = cmd + ['--all']\n    output = run_command(cmd, sudo=sudo, quiet=quiet)\n    if output['return_code'] != 0:\n        message = '%s : return code %s' %(output['message'], \n                                          output['return_code'])\n        bot.error(message)\n        return output['return_code']\n    return output['return_code']",
    "docstring": "stop ALL instances. This command is only added to the command group\n       as it doesn't make sense to call from a single instance\n\n       Parameters\n       ==========\n       sudo: if the command should be done with sudo (exposes different set of\n             instances)"
  },
  {
    "code": "def _create_array(self, format, args):\n        builder = None\n        if args is None or not args[0]:\n            rest_format = self._create(format[1:], None)[1]\n            element_type = format[:len(format) - len(rest_format)]\n            builder = GLib.VariantBuilder.new(variant_type_from_string(element_type))\n        else:\n            builder = GLib.VariantBuilder.new(variant_type_from_string('a*'))\n            for i in range(len(args[0])):\n                (v, rest_format, _) = self._create(format[1:], args[0][i:])\n                builder.add_value(v)\n        if args is not None:\n            args = args[1:]\n        return (builder.end(), rest_format, args)",
    "docstring": "Handle the case where the outermost type of format is an array."
  },
  {
    "code": "def add_output(self, key, value, variable_type):\n        index = '{}-{}'.format(key, variable_type)\n        self.output_data.setdefault(index, {})\n        if value is None:\n            return\n        if variable_type in ['String', 'Binary', 'KeyValue', 'TCEntity', 'TCEnhancedEntity']:\n            self.output_data[index] = {'key': key, 'type': variable_type, 'value': value}\n        elif variable_type in [\n            'StringArray',\n            'BinaryArray',\n            'KeyValueArray',\n            'TCEntityArray',\n            'TCEnhancedEntityArray',\n        ]:\n            self.output_data[index].setdefault('key', key)\n            self.output_data[index].setdefault('type', variable_type)\n            if isinstance(value, list):\n                self.output_data[index].setdefault('value', []).extend(value)\n            else:\n                self.output_data[index].setdefault('value', []).append(value)",
    "docstring": "Dynamically add output to output_data dictionary to be written to DB later.\n\n        This method provides an alternative and more dynamic way to create output variables in an\n        App. Instead of storing the output data manually and writing all at once the data can be\n        stored inline, when it is generated and then written before the App completes.\n\n        .. code-block:: python\n            :linenos:\n            :lineno-start: 1\n\n            for color in ['blue', 'red', 'yellow']:\n                tcex.playbook.add_output('app.colors', color, 'StringArray')\n\n            tcex.playbook.write_output()  #  writes the output stored in output_data\n\n        .. code-block:: json\n            :linenos:\n            :lineno-start: 1\n\n            {\n                \"my_color-String\": {\n                    \"key\": \"my_color\",\n                    \"type\": \"String\",\n                    \"value\": \"blue\"\n                },\n                \"my_numbers-String\": {\n                    \"key\": \"my_numbers\",\n                    \"type\": \"String\",\n                    \"value\": \"seven\"\n                },\n                \"my_numbers-StringArray\": {\n                    \"key\": \"my_numbers\",\n                    \"type\": \"StringArray\",\n                    \"value\": [\"seven\", \"five\"]\n                }\n            }\n\n        Args:\n            key (string): The variable name to write to storage.\n            value (any): The value to write to storage.\n            variable_type (string): The variable type being written."
  },
  {
    "code": "def release(self, conn):\n        self._in_use.remove(conn)\n        if conn.reader.at_eof() or conn.reader.exception():\n            self._do_close(conn)\n        else:\n            self._pool.put_nowait(conn)",
    "docstring": "Releases connection back to the pool.\n\n        :param conn: ``namedtuple`` (reader, writer)"
  },
  {
    "code": "def _prepare_request_file_vs_dir(self, request: Request) -> bool:\n        if self._item_session.url_record.link_type:\n            is_file = self._item_session.url_record.link_type == LinkType.file\n        elif request.url_info.path.endswith('/'):\n            is_file = False\n        else:\n            is_file = 'unknown'\n        if is_file == 'unknown':\n            files = yield from self._fetch_parent_path(request)\n            if not files:\n                return True\n            filename = posixpath.basename(request.file_path)\n            for file_entry in files:\n                if file_entry.name == filename:\n                    _logger.debug('Found entry in parent. Type {}',\n                                  file_entry.type)\n                    is_file = file_entry.type != 'dir'\n                    break\n            else:\n                _logger.debug('Did not find entry. Assume file.')\n                return True\n            if not is_file:\n                request.url = append_slash_to_path_url(request.url_info)\n                _logger.debug('Request URL changed to {}. Path={}.',\n                              request.url, request.file_path)\n        return is_file",
    "docstring": "Check if file, modify request, and return whether is a file.\n\n        Coroutine."
  },
  {
    "code": "def confirm_email_with_link(self, link):\n        user = self.first(email_link=link)\n        if not user:\n            return False\n        elif user and user.email_confirmed:\n            return True\n        elif user and user.email_link_expired():\n            raise x.EmailLinkExpired('Link expired, generate a new one')\n        user.confirm_email()\n        db.session.add(user)\n        db.session.commit()\n        events.email_confirmed_event.send(user)\n        return user",
    "docstring": "Confirm email with link\n        A universal method to confirm email. used for both initial\n        confirmation and when email is changed."
  },
  {
    "code": "def flipped(self):\n        forward, reverse = self.value\n        return self.__class__((reverse, forward))",
    "docstring": "Return the flipped version of this direction."
  },
  {
    "code": "def _generate_rsa_key(key_length):\n    private_key = rsa.generate_private_key(public_exponent=65537, key_size=key_length, backend=default_backend())\n    key_bytes = private_key.private_bytes(\n        encoding=serialization.Encoding.DER,\n        format=serialization.PrivateFormat.PKCS8,\n        encryption_algorithm=serialization.NoEncryption(),\n    )\n    return key_bytes, EncryptionKeyType.PRIVATE, KeyEncodingType.DER",
    "docstring": "Generate a new RSA private key.\n\n    :param int key_length: Required key length in bits\n    :returns: DER-encoded private key, private key identifier, and DER encoding identifier\n    :rtype: tuple(bytes, :class:`EncryptionKeyType`, :class:`KeyEncodingType`)"
  },
  {
    "code": "def _instantiate_layers(self):\n    with self._enter_variable_scope(check_same_graph=False):\n      self._layers = [basic.Linear(self._output_sizes[i],\n                                   name=\"linear_{}\".format(i),\n                                   initializers=self._initializers,\n                                   partitioners=self._partitioners,\n                                   regularizers=self._regularizers,\n                                   use_bias=self.use_bias)\n                      for i in xrange(self._num_layers)]",
    "docstring": "Instantiates all the linear modules used in the network.\n\n    Layers are instantiated in the constructor, as opposed to the build\n    function, because MLP implements the Transposable interface, and the\n    transpose function can be called before the module is actually connected\n    to the graph and build is called.\n\n    Notice that this is safe since layers in the transposed module are\n    instantiated using a lambda returning input_size of the mlp layers, and\n    this doesn't have to return sensible values until the original module is\n    connected to the graph."
  },
  {
    "code": "def has_free_parameters(self):\n        for component in self._components.values():\n            for par in component.shape.parameters.values():\n                if par.free:\n                    return True\n        for par in self.position.parameters.values():\n            if par.free:\n                return True\n        return False",
    "docstring": "Returns True or False whether there is any parameter in this source\n\n        :return:"
  },
  {
    "code": "def a_configuration_inconsistency(ctx):\n    ctx.msg = \"This SDR's running configuration is inconsistent with persistent configuration. \" \\\n              \"No configuration commits for this SDR will be allowed until a 'clear configuration inconsistency' \" \\\n              \"command is performed.\"\n    ctx.device.chain.connection.emit_message(\"Configuration inconsistency.\", log_level=logging.ERROR)\n    ctx.finished = True\n    raise ConfigurationErrors(\"Configuration inconsistency.\")",
    "docstring": "Raise the configuration inconsistency error."
  },
  {
    "code": "def all_nodes_that_receive(service, service_configuration=None, run_only=False, deploy_to_only=False):\n    assert not (run_only and deploy_to_only)\n    if service_configuration is None:\n        service_configuration = read_services_configuration()\n    runs_on = service_configuration[service]['runs_on']\n    deployed_to = service_configuration[service].get('deployed_to')\n    if deployed_to is None:\n        deployed_to = []\n    if run_only:\n        result = runs_on\n    elif deploy_to_only:\n        result = deployed_to\n    else:\n        result = set(runs_on) | set(deployed_to)\n    return list(sorted(result))",
    "docstring": "If run_only, returns only the services that are in the runs_on list.\n    If deploy_to_only, returns only the services in the deployed_to list.\n    If neither, both are returned, duplicates stripped.\n    Results are always sorted."
  },
  {
    "code": "def Clone(self):\n        return AccountState(self.ScriptHash, self.IsFrozen, self.Votes, self.Balances)",
    "docstring": "Clone self.\n\n        Returns:\n            AccountState:"
  },
  {
    "code": "def _get_svc_list(name='*', status=None):\n    return sorted([os.path.basename(el) for el in _get_svc_path(name, status)])",
    "docstring": "Return list of services that have the specified service ``status``\n\n    name\n        a glob for service name. default is '*'\n\n    status\n        None       : all services (no filter, default choice)\n        'DISABLED' : available service that is not enabled\n        'ENABLED'  : enabled service (whether started on boot or not)"
  },
  {
    "code": "def wrongstatus(data, sb, msb, lsb):\n    status = int(data[sb-1])\n    value = bin2int(data[msb-1:lsb])\n    if not status:\n        if value != 0:\n            return True\n    return False",
    "docstring": "Check if the status bit and field bits are consistency. This Function\n    is used for checking BDS code versions."
  },
  {
    "code": "def to_fits(self, filename, wavelengths=None, **kwargs):\n        w, y = self._get_arrays(wavelengths)\n        kwargs['flux_col'] = 'Av/E(B-V)'\n        kwargs['flux_unit'] = self._internal_flux_unit\n        if 'pad_zero_ends' not in kwargs:\n            kwargs['pad_zero_ends'] = False\n        if 'trim_zero' not in kwargs:\n            kwargs['trim_zero'] = False\n        bkeys = {'tdisp1': 'G15.7', 'tdisp2': 'G15.7'}\n        if 'expr' in self.meta:\n            bkeys['expr'] = (self.meta['expr'], 'synphot expression')\n        if 'ext_header' in kwargs:\n            kwargs['ext_header'].update(bkeys)\n        else:\n            kwargs['ext_header'] = bkeys\n        specio.write_fits_spec(filename, w, y, **kwargs)",
    "docstring": "Write the reddening law to a FITS file.\n\n        :math:`R(V)` column is automatically named 'Av/E(B-V)'.\n\n        Parameters\n        ----------\n        filename : str\n            Output filename.\n\n        wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`\n            Wavelength values for sampling.\n            If not a Quantity, assumed to be in Angstrom.\n            If `None`, ``self.waveset`` is used.\n\n        kwargs : dict\n            Keywords accepted by :func:`~synphot.specio.write_fits_spec`."
  },
  {
    "code": "def __create(self, opcode):\n        tftpassert(opcode in self.classes,\n                   \"Unsupported opcode: %d\" % opcode)\n        packet = self.classes[opcode]()\n        return packet",
    "docstring": "This method returns the appropriate class object corresponding to\n        the passed opcode."
  },
  {
    "code": "def emit_children(self, node):\n        return \"\".join([self.emit_node(child) for child in node.children])",
    "docstring": "Emit all the children of a node."
  },
  {
    "code": "def process_frames(self):\n        while len(self._frame_buffer):\n            frame = self._frame_buffer.popleft()\n            if self._emergency_close_pending:\n                if (not isinstance(frame, MethodFrame) or\n                      frame.class_id != self.channel.CLASS_ID or\n                      frame.method_id not in (self.channel.CLOSE_METHOD_ID,\n                                              self.channel.CLOSE_OK_METHOD_ID)):\n                    self.logger.warn(\"Emergency channel close: dropping input \"\n                                     \"frame %.255s\", frame)\n                    continue\n            try:\n                self.dispatch(frame)\n            except ProtocolClass.FrameUnderflow:\n                return\n            except (ConnectionClosed, ChannelClosed):\n                raise\n            except Exception:\n                self.logger.exception(\n                    \"Closing on failed dispatch of frame %.255s\", frame)\n                self._emergency_close_pending = True\n                try:\n                    raise\n                finally:\n                    try:\n                        self.close(500, \"Failed to dispatch %s\" % (str(frame)))\n                    except Exception:\n                        self.logger.exception(\"Channel close failed\")\n                        pass",
    "docstring": "Process the input buffer."
  },
  {
    "code": "def launch_configuration_exists(name, region=None, key=None, keyid=None,\n                                profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    retries = 30\n    while True:\n        try:\n            lc = conn.get_all_launch_configurations(names=[name])\n            if lc:\n                return True\n            else:\n                msg = 'The launch configuration does not exist in region {0}'.format(region)\n                log.debug(msg)\n                return False\n        except boto.exception.BotoServerError as e:\n            if retries and e.code == 'Throttling':\n                log.debug('Throttled by AWS API, retrying in 5 seconds...')\n                time.sleep(5)\n                retries -= 1\n                continue\n            log.error(e)\n            return False",
    "docstring": "Check for a launch configuration's existence.\n\n    CLI example::\n\n        salt myminion boto_asg.launch_configuration_exists mylc"
  },
  {
    "code": "def parse_uci(self, uci: str) -> Move:\n        move = Move.from_uci(uci)\n        if not move:\n            return move\n        move = self._to_chess960(move)\n        move = self._from_chess960(self.chess960, move.from_square, move.to_square, move.promotion, move.drop)\n        if not self.is_legal(move):\n            raise ValueError(\"illegal uci: {!r} in {}\".format(uci, self.fen()))\n        return move",
    "docstring": "Parses the given move in UCI notation.\n\n        Supports both Chess960 and standard UCI notation.\n\n        The returned move is guaranteed to be either legal or a null move.\n\n        :raises: :exc:`ValueError` if the move is invalid or illegal in the\n            current position (but not a null move)."
  },
  {
    "code": "def sample_distinct(self, n_to_sample, **kwargs):\n        n_notsampled = np.sum(np.isnan(self.cached_labels_))\n        if n_notsampled == 0:\n            raise Exception(\"All distinct items have already been sampled.\")\n        if n_to_sample > n_notsampled:\n            warnings.warn(\"Only {} distinct item(s) have not yet been sampled.\"\n                          \" Setting n_to_sample = {}.\".format(n_notsampled, \\\n                          n_notsampled))\n            n_to_sample = n_notsampled\n        n_sampled = 0\n        while n_sampled < n_to_sample:\n            self.sample(1,**kwargs)\n            n_sampled += self._queried_oracle[self.t_ - 1]*1",
    "docstring": "Sample a sequence of items from the pool until a minimum number of\n        distinct items are queried\n\n        Parameters\n        ----------\n        n_to_sample : int\n            number of distinct items to sample. If sampling with replacement,\n            this number is not necessarily the same as the number of\n            iterations."
  },
  {
    "code": "def get_all_items_of_offer(self, offer_id):\n        return self._iterate_through_pages(\n            get_function=self.get_items_of_offer_per_page,\n            resource=OFFER_ITEMS,\n            **{'offer_id': offer_id}\n        )",
    "docstring": "Get all items of offer\n        This will iterate over all pages until it gets all elements.\n        So if the rate limit exceeded it will throw an Exception and you will get nothing\n\n        :param offer_id: the offer id\n        :return: list"
  },
  {
    "code": "def get_default_value_by_type(type_, state=None):\n        if type_ in ['byte', 'char', 'short', 'int', 'boolean']:\n            return BVS('default_value_{}'.format(type_), 32)\n        elif type_ == \"long\":\n            return BVS('default_value_{}'.format(type_), 64)\n        elif type_ == 'float':\n            return FPS('default_value_{}'.format(type_), FSORT_FLOAT)\n        elif type_ == 'double':\n            return FPS('default_value_{}'.format(type_), FSORT_DOUBLE)\n        elif state is not None:\n            if type_ == 'java.lang.String':\n                return SimSootValue_StringRef.new_string(state, StringS('default_value_{}'.format(type_), 1000))\n            if type_.endswith('[][]'):\n                raise NotImplementedError\n            elif type_.endswith('[]'):\n                array = SimSootExpr_NewArray.new_array(state, type_[:-2], BVV(2, 32))\n                return array\n            else:\n                return SimSootValue_ThisRef.new_object(state, type_, symbolic=True, init_object=False)\n        else:\n            return SootNullConstant()",
    "docstring": "Java specify defaults values for primitive and reference types. This\n        method returns the default value for a given type.\n\n        :param str type_:   Name of type.\n        :return:            Default value for this type."
  },
  {
    "code": "def _filter_from_dict(current: Dict[str, Any]) -> Dict[str, Any]:\n    filter_ = dict()\n    for k, v in current.items():\n        if isinstance(v, dict):\n            for sub, v2 in _filter_from_dict(v).items():\n                filter_[f'{k}.{sub}'] = v2\n        else:\n            filter_[k] = v\n    return filter_",
    "docstring": "Takes in a nested dictionary as a filter and returns a flattened filter dictionary"
  },
  {
    "code": "def _path_hash(path, transform, kwargs):\n    sortedargs = [\"%s:%r:%s\" % (key, value, type(value))\n                  for key, value in sorted(iteritems(kwargs))]\n    srcinfo = \"{path}:{transform}:{{{kwargs}}}\".format(path=os.path.abspath(path),\n                                                   transform=transform,\n                                                   kwargs=\",\".join(sortedargs))\n    return digest_string(srcinfo)",
    "docstring": "Generate a hash of source file path + transform + args"
  },
  {
    "code": "def _replace_variable_with_pattern(match):\n    positional = match.group(\"positional\")\n    name = match.group(\"name\")\n    template = match.group(\"template\")\n    if name is not None:\n        if not template:\n            return _SINGLE_SEGMENT_PATTERN.format(name)\n        elif template == \"**\":\n            return _MULTI_SEGMENT_PATTERN.format(name)\n        else:\n            return _generate_pattern_for_template(template)\n    elif positional == \"*\":\n        return _SINGLE_SEGMENT_PATTERN\n    elif positional == \"**\":\n        return _MULTI_SEGMENT_PATTERN\n    else:\n        raise ValueError(\"Unknown template expression {}\".format(match.group(0)))",
    "docstring": "Replace a variable match with a pattern that can be used to validate it.\n\n    Args:\n        match (re.Match): A regular expression match\n\n    Returns:\n        str: A regular expression pattern that can be used to validate the\n            variable in an expanded path.\n\n    Raises:\n        ValueError: If an unexpected template expression is encountered."
  },
  {
    "code": "def summarize(self, host):\n        return dict(\n            ok          = self.ok.get(host, 0),\n            failures    = self.failures.get(host, 0),\n            unreachable = self.dark.get(host,0),\n            changed     = self.changed.get(host, 0),\n            skipped     = self.skipped.get(host, 0)\n        )",
    "docstring": "return information about a particular host"
  },
  {
    "code": "def __update_mouse(self, milliseconds):\n        for button in self.gui_buttons:\n            was_hovering = button.is_mouse_hovering\n            button.update(milliseconds)\n            if was_hovering == False and button.is_mouse_hovering:\n                old_index = self.current_index\n                self.current_index = self.gui_buttons.index(button)\n                self.__handle_selections(old_index, self.current_index)\n            elif Ragnarok.get_world().Mouse.is_clicked(self.mouse_select_button) and button.is_mouse_hovering:\n                button.clicked_action()",
    "docstring": "Use the mouse to control selection of the buttons."
  },
  {
    "code": "def evaluate(self, genomes, config):\n        if self.mode != MODE_PRIMARY:\n            raise ModeError(\"Not in primary mode!\")\n        tasks = [(genome_id, genome, config) for genome_id, genome in genomes]\n        id2genome = {genome_id: genome for genome_id, genome in genomes}\n        tasks = chunked(tasks, self.secondary_chunksize)\n        n_tasks = len(tasks)\n        for task in tasks:\n            self.inqueue.put(task)\n        tresults = []\n        while len(tresults) < n_tasks:\n            try:\n                sr = self.outqueue.get(block=True, timeout=0.2)\n            except (queue.Empty, managers.RemoteError):\n                continue\n            tresults.append(sr)\n        results = []\n        for sr in tresults:\n            results += sr\n        for genome_id, fitness in results:\n            genome = id2genome[genome_id]\n            genome.fitness = fitness",
    "docstring": "Evaluates the genomes.\n        This method raises a ModeError if the\n        DistributedEvaluator is not in primary mode."
  },
  {
    "code": "def validate_row(self, row):\n        clean_row = {}\n        if isinstance(row, (tuple, list)):\n            assert self.header_order, \"No attribute order specified.\"\n            assert len(row) == len(self.header_order), \\\n                \"Row length does not match header length.\"\n            itr = zip(self.header_order, row)\n        else:\n            assert isinstance(row, dict)\n            itr = iteritems(row)\n        for el_name, el_value in itr:\n            if self.header_types[el_name] == ATTR_TYPE_DISCRETE:\n                clean_row[el_name] = int(el_value)\n            elif self.header_types[el_name] == ATTR_TYPE_CONTINUOUS:\n                clean_row[el_name] = float(el_value)\n            else:\n                clean_row[el_name] = el_value\n        return clean_row",
    "docstring": "Ensure each element in the row matches the schema."
  },
  {
    "code": "def sample(self, sampling_period, start=None, end=None,\n               interpolate='previous'):\n        start, end, mask = self._check_boundaries(start, end)\n        sampling_period = \\\n            self._check_regularization(start, end, sampling_period)\n        result = []\n        current_time = start\n        while current_time <= end:\n            value = self.get(current_time, interpolate=interpolate)\n            result.append((current_time, value))\n            current_time += sampling_period\n        return result",
    "docstring": "Sampling at regular time periods."
  },
  {
    "code": "def mock_chroot(self, release, cmd, **kwargs):\n        return self.mock_cmd(release, '--chroot', cmd, **kwargs)",
    "docstring": "Run a commend in the mock container for a release"
  },
  {
    "code": "def is_intent_name(name):\n    def can_handle_wrapper(handler_input):\n        return (isinstance(\n            handler_input.request_envelope.request, IntentRequest) and\n                handler_input.request_envelope.request.intent.name == name)\n    return can_handle_wrapper",
    "docstring": "A predicate function returning a boolean, when name matches the\n    name in Intent Request.\n\n    The function can be applied on a\n    :py:class:`ask_sdk_core.handler_input.HandlerInput`, to\n    check if the input is of\n    :py:class:`ask_sdk_model.intent_request.IntentRequest` type and if the\n    name of the request matches with the passed name.\n\n    :param name: Name to be matched with the Intent Request Name\n    :type name: str\n    :return: Predicate function that can be used to check name of the\n        request\n    :rtype: Callable[[HandlerInput], bool]"
  },
  {
    "code": "def mail(ui, repo, *pats, **opts):\n\tif codereview_disabled:\n\t\traise hg_util.Abort(codereview_disabled)\n\tcl, err = CommandLineCL(ui, repo, pats, opts, op=\"mail\", defaultcc=defaultcc)\n\tif err != \"\":\n\t\traise hg_util.Abort(err)\n\tcl.Upload(ui, repo, gofmt_just_warn=True)\n\tif not cl.reviewer:\n\t\tif not defaultcc:\n\t\t\traise hg_util.Abort(\"no reviewers listed in CL\")\n\t\tcl.cc = Sub(cl.cc, defaultcc)\n\t\tcl.reviewer = defaultcc\n\t\tcl.Flush(ui, repo)\n\tif cl.files == []:\n\t\t\traise hg_util.Abort(\"no changed files, not sending mail\")\n\tcl.Mail(ui, repo)",
    "docstring": "mail a change for review\n\n\tUploads a patch to the code review server and then sends mail\n\tto the reviewer and CC list asking for a review."
  },
  {
    "code": "def _make_cookie(self):\n        return struct.pack(self.COOKIE_FMT, self.COOKIE_MAGIC,\n                           os.getpid(), id(self), thread.get_ident())",
    "docstring": "Return a string encoding the ID of the process, instance and thread.\n        This disambiguates legitimate wake-ups, accidental writes to the FD,\n        and buggy internal FD sharing."
  },
  {
    "code": "def buckets_insert(self, bucket, project_id=None):\n    args = {'project': project_id if project_id else self._project_id}\n    data = {'name': bucket}\n    url = Api._ENDPOINT + (Api._BUCKET_PATH % '')\n    return datalab.utils.Http.request(url, args=args, data=data, credentials=self._credentials)",
    "docstring": "Issues a request to create a new bucket.\n\n    Args:\n      bucket: the name of the bucket.\n      project_id: the project to use when inserting the bucket.\n    Returns:\n      A parsed bucket information dictionary.\n    Raises:\n      Exception if there is an error performing the operation."
  },
  {
    "code": "def eigenvalues_(self):\n        utils.validation.check_is_fitted(self, 's_')\n        return np.square(self.s_).tolist()",
    "docstring": "The eigenvalues associated with each principal component."
  },
  {
    "code": "def parse_duration_with_start(start, duration):\n    elements = _parse_duration_string(_clean(duration))\n    year, month = _year_month_delta_from_elements(elements)\n    end = start.replace(\n        year=start.year + year,\n        month=start.month + month\n    )\n    del elements['years']\n    del elements['months']\n    end += _timedelta_from_elements(elements)\n    return start, end - start",
    "docstring": "Attepmt to parse an ISO8601 formatted duration based on a start datetime.\n\n    Accepts a ``duration`` and a start ``datetime``. ``duration`` must be\n    an ISO8601 formatted string.\n\n    Returns a ``datetime.timedelta`` object."
  },
  {
    "code": "def sort_schemas(cls, schemas_list):\n        return sorted(schemas_list,\n                      key=lambda x: (\n                          x.priority,\n                          x.compiled.key_schema.priority if x.compiled_type == const.COMPILED_TYPE.MARKER else 0\n                      ), reverse=True)",
    "docstring": "Sort the provided list of schemas according to their priority.\n\n        This also supports markers, and markers of a single type are also sorted according to the priority of the wrapped schema.\n\n        :type schemas_list: list[CompiledSchema]\n        :rtype: list[CompiledSchema]"
  },
  {
    "code": "def _socket_close(self):\n        callback = self.__callback\n        self.__callback = None\n        try:\n            if callback:\n                callback(None, InterfaceError('connection closed'))\n        finally:\n            self.__job_queue = []\n            self.__alive = False\n            self.__pool.cache(self)",
    "docstring": "cleanup after the socket is closed by the other end"
  },
  {
    "code": "def write_branch_data(self, file):\n        branch_sheet = self.book.add_sheet(\"Branches\")\n        for i, branch in enumerate(self.case.branches):\n            for j, attr in enumerate(BRANCH_ATTRS):\n                branch_sheet.write(i, j, getattr(branch, attr))",
    "docstring": "Writes branch data to an Excel spreadsheet."
  },
  {
    "code": "def _combine_msd_quan(msd, quan):\n    dim1 = msd.shape\n    n_par, _, n_chains = dim1\n    ll = []\n    for i in range(n_chains):\n        a1 = msd[:, :, i]\n        a2 = quan[:, :, i]\n        ll.append(np.column_stack([a1, a2]))\n    msdquan = np.dstack(ll)\n    return msdquan",
    "docstring": "Combine msd and quantiles in chain summary\n\n    Parameters\n    ----------\n    msd : array of shape (num_params, 2, num_chains)\n       mean and sd for chains\n    cquan : array of shape (num_params, num_quan, num_chains)\n        quantiles for chains\n\n    Returns\n    -------\n    msdquan : array of shape (num_params, 2 + num_quan, num_chains)"
  },
  {
    "code": "def SInt64(value, min_value=None, max_value=None, encoder=ENC_INT_DEFAULT, fuzzable=True, name=None, full_range=False):\n    return BitField(value, 64, signed=True, min_value=min_value, max_value=max_value, encoder=encoder, fuzzable=fuzzable, name=name, full_range=full_range)",
    "docstring": "Signed 64-bit field"
  },
  {
    "code": "def get_collection(self, collection_id):\n        sql =\n        cursor = self._execute(sql, (collection_id, collection_id))\n        sql_result = cursor.fetchone()\n        return {\n            \"collection_id\": sql_result[0],\n            \"type\": sql_result[1],\n            \"name\": sql_result[2],\n            \"path\": sql_result[3],\n            \"doc\":  sql_result[4],\n            \"version\": sql_result[5],\n            \"scope\":   sql_result[6],\n            \"namedargs\": sql_result[7],\n            \"doc_format\": sql_result[8]\n        }\n        return sql_result",
    "docstring": "Get a specific collection"
  },
  {
    "code": "def set_logger(self):\n        self.logger = logging.getLogger(self.logger_name)\n        self.logger.setLevel(self.logger_level)",
    "docstring": "Prepare the logger, using self.logger_name and self.logger_level"
  },
  {
    "code": "async def set_pairwise_metadata(wallet_handle: int,\n                                their_did: str,\n                                metadata: Optional[str]) -> None:\n    logger = logging.getLogger(__name__)\n    logger.debug(\"set_pairwise_metadata: >>> wallet_handle: %r, their_did: %r, metadata: %r\",\n                 wallet_handle,\n                 their_did,\n                 metadata)\n    if not hasattr(set_pairwise_metadata, \"cb\"):\n        logger.debug(\"set_pairwise_metadata: Creating callback\")\n        set_pairwise_metadata.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))\n    c_wallet_handle = c_int32(wallet_handle)\n    c_their_did = c_char_p(their_did.encode('utf-8'))\n    c_metadata = c_char_p(metadata.encode('utf-8')) if metadata is not None else None\n    await do_call('indy_set_pairwise_metadata',\n                  c_wallet_handle,\n                  c_their_did,\n                  c_metadata,\n                  set_pairwise_metadata.cb)\n    logger.debug(\"set_pairwise_metadata: <<<\")",
    "docstring": "Save some data in the Wallet for pairwise associated with Did.\n\n    :param wallet_handle: wallet handler (created by open_wallet).\n    :param their_did: encoded DID\n    :param metadata: some extra information for pairwise\n    :return: Error code"
  },
  {
    "code": "def gen_challenge(self, state):\n        state.decrypt(self.key)\n        chal = Challenge(state.chunks, self.prime, Random.new().read(32))\n        return chal",
    "docstring": "This function generates a challenge for given state.  It selects a\n        random number and sets that as the challenge key.  By default, v_max\n        is set to the prime, and the number of chunks to challenge is the\n        number of chunks in the file.  (this doesn't guarantee that the whole\n        file will be checked since some chunks could be selected twice and\n        some selected none.\n\n        :param state: the state to use.  it can be encrypted, as it will\n        have just been received from the server"
  },
  {
    "code": "def ReplaceInstanceDisks(r, instance, disks=None, mode=REPLACE_DISK_AUTO,\n                         remote_node=None, iallocator=None, dry_run=False):\n    if mode not in REPLACE_DISK:\n        raise GanetiApiError(\"Invalid mode %r not one of %r\" % (mode,\n                                                                REPLACE_DISK))\n    query = {\n        \"mode\": mode,\n        \"dry-run\": dry_run,\n    }\n    if disks:\n        query[\"disks\"] = \",\".join(str(idx) for idx in disks)\n    if remote_node:\n        query[\"remote_node\"] = remote_node\n    if iallocator:\n        query[\"iallocator\"] = iallocator\n    return r.request(\"post\", \"/2/instances/%s/replace-disks\" % instance,\n                     query=query)",
    "docstring": "Replaces disks on an instance.\n\n    @type instance: str\n    @param instance: instance whose disks to replace\n    @type disks: list of ints\n    @param disks: Indexes of disks to replace\n    @type mode: str\n    @param mode: replacement mode to use (defaults to replace_auto)\n    @type remote_node: str or None\n    @param remote_node: new secondary node to use (for use with\n            replace_new_secondary mode)\n    @type iallocator: str or None\n    @param iallocator: instance allocator plugin to use (for use with\n                                         replace_auto mode)\n    @type dry_run: bool\n    @param dry_run: whether to perform a dry run\n\n    @rtype: int\n    @return: job id"
  },
  {
    "code": "def show_status(self):\n    print_header('Attack work statistics')\n    self.attack_work.read_all_from_datastore()\n    self._show_status_for_work(self.attack_work)\n    self._export_work_errors(\n        self.attack_work,\n        os.path.join(self.results_dir, 'attack_errors.txt'))\n    print_header('Defense work statistics')\n    self.defense_work.read_all_from_datastore()\n    self._show_status_for_work(self.defense_work)\n    self._export_work_errors(\n        self.defense_work,\n        os.path.join(self.results_dir, 'defense_errors.txt'))",
    "docstring": "Shows current status of competition evaluation.\n\n    Also this method saves error messages generated by attacks and defenses\n    into attack_errors.txt and defense_errors.txt."
  },
  {
    "code": "def histogram1d(data, bins=None, *args, **kwargs):\n    import dask\n    if not hasattr(data, \"dask\"):\n        data = dask.array.from_array(data, chunks=int(data.shape[0] / options[\"chunk_split\"]))\n    if not kwargs.get(\"adaptive\", True):\n        raise RuntimeError(\"Only adaptive histograms supported for dask (currently).\")\n    kwargs[\"adaptive\"] = True\n    def block_hist(array):\n        return original_h1(array, bins, *args, **kwargs)\n    return _run_dask(\n        name=\"dask_adaptive1d\",\n        data=data,\n        compute=kwargs.pop(\"compute\", True),\n        method=kwargs.pop(\"dask_method\", \"threaded\"),\n        func=block_hist)",
    "docstring": "Facade function to create one-dimensional histogram using dask.\n\n    Parameters\n    ----------\n    data: dask.DaskArray or array-like\n\n    See also\n    --------\n    physt.histogram"
  },
  {
    "code": "def available_state_for_gene(self, gene: Gene, state: State) -> Tuple[State, ...]:\n        result: List[State] = []\n        active_multiplex: Tuple[Multiplex] = gene.active_multiplex(state)\n        transition: Transition = self.find_transition(gene, active_multiplex)\n        current_state: int = state[gene]\n        done = set()\n        for target_state in transition.states:\n            target_state: int = self._state_after_transition(current_state, target_state)\n            if target_state not in done:\n                done.add(target_state)\n                new_state: State = state.copy()\n                new_state[gene] = target_state\n                result.append(new_state)\n        return tuple(result)",
    "docstring": "Return the state reachable from a given state for a particular gene."
  },
  {
    "code": "def reset(self):\n    self.activeCells = np.empty(0, dtype=\"uint32\")\n    self.activeDeltaSegments = np.empty(0, dtype=\"uint32\")\n    self.activeFeatureLocationSegments = np.empty(0, dtype=\"uint32\")",
    "docstring": "Deactivate all cells."
  },
  {
    "code": "def done(self):\n        return [mm.name for mm in self.model.select().order_by(self.model.id)]",
    "docstring": "Scan migrations in database."
  },
  {
    "code": "def incrby(self, key, increment):\n        if not isinstance(increment, int):\n            raise TypeError(\"increment must be of type int\")\n        return self.execute(b'INCRBY', key, increment)",
    "docstring": "Increment the integer value of a key by the given amount.\n\n        :raises TypeError: if increment is not int"
  },
  {
    "code": "def downvote(self):\n        url = self._imgur._base_url + \"/3/gallery/{0}/vote/down\".format(self.id)\n        return self._imgur._send_request(url, needs_auth=True, method='POST')",
    "docstring": "Dislike this.\n\n        A downvote will replace a neutral vote or an upvote. Downvoting\n        something the authenticated user has already downvoted will set the\n        vote to neutral."
  },
  {
    "code": "def _step00(self, in_row, tmp_row, out_row):\n        for key, value in in_row.items():\n            in_row[key] = WhitespaceCleaner.clean(value)\n        return None, None",
    "docstring": "Prunes whitespace for all fields in the input row.\n\n        :param dict in_row: The input row.\n        :param dict tmp_row: Not used.\n        :param dict out_row: Not used."
  },
  {
    "code": "def config_program_reqs(cls, programs):\n        cls._set_program_defaults(programs)\n        do_png = cls.optipng or cls.pngout or cls.advpng\n        do_jpeg = cls.mozjpeg or cls.jpegrescan or cls.jpegtran\n        do_comics = cls.comics\n        if not do_png and not do_jpeg and not do_comics:\n            print(\"All optimizers are not available or disabled.\")\n            exit(1)",
    "docstring": "Run the program tester and determine if we can do anything."
  },
  {
    "code": "def create_masks(input_dim,\n                 hidden_dims,\n                 input_order='left-to-right',\n                 hidden_order='left-to-right'):\n  degrees = create_degrees(input_dim, hidden_dims, input_order, hidden_order)\n  masks = []\n  for input_degrees, output_degrees in zip(degrees[:-1], degrees[1:]):\n    mask = tf.cast(input_degrees[:, np.newaxis] <= output_degrees, tf.float32)\n    masks.append(mask)\n  mask = tf.cast(degrees[-1][:, np.newaxis] < degrees[0], tf.float32)\n  masks.append(mask)\n  return masks",
    "docstring": "Returns a list of binary mask matrices respecting autoregressive ordering.\n\n  Args:\n    input_dim: Number of inputs.\n    hidden_dims: list with the number of hidden units per layer. It does not\n      include the output layer; those number of units will always be set to\n      input_dim downstream. Each hidden unit size must be at least the size of\n      length (otherwise autoregressivity is not possible).\n    input_order: Order of degrees to the input units: 'random', 'left-to-right',\n      'right-to-left', or an array of an explicit order. For example,\n      'left-to-right' builds an autoregressive model\n      p(x) = p(x1) p(x2 | x1) ... p(xD | x<D).\n    hidden_order: Order of degrees to the hidden units: 'random',\n      'left-to-right'. If 'left-to-right', hidden units are allocated equally\n      (up to a remainder term) to each degree."
  },
  {
    "code": "def get_index_fields(self):\n        index_fields = self.get_meta_option('index', [])\n        if index_fields:\n            return index_fields\n        model = getattr(self.model_serializer_meta, 'model', None)\n        if model:\n            pk_name = model._meta.pk.name\n            if pk_name in self.child.get_fields():\n                return [pk_name]\n        return []",
    "docstring": "List of fields to use for index"
  },
  {
    "code": "def _split_dict(dic):\n    keys = sorted(dic.keys())\n    return keys, [dic[k] for k in keys]",
    "docstring": "Split dict into sorted keys and values\n\n    >>> _split_dict({'b': 2, 'a': 1})\n    (['a', 'b'], [1, 2])"
  },
  {
    "code": "def cd(self, *subpaths):\n        target = os.path.join(*subpaths)\n        os.chdir(target)",
    "docstring": "Change the current working directory and update all the paths in the\n        workspace.  This is useful for commands that have to be run from a\n        certain directory."
  },
  {
    "code": "def pretty_print(session, feed):\n    if feed in session.feeds:\n        print()\n        feed_info = os.path.join(session.data_dir, feed)\n        entrylinks, linkdates = parse_feed_info(feed_info)\n        print(feed)\n        print(\"-\"*len(feed))\n        print(''.join([\"    url: \", session.feeds[feed][\"url\"]]))\n        if linkdates != []:\n            print(''.join([\"    Next sync will download from: \", time.strftime(\n                \"%d %b %Y %H:%M:%S\", tuple(max(linkdates))), \".\"]))\n    else:\n        print(\"You don't have a feed called {}.\".format(feed), file=sys.stderr,\n              flush=True)",
    "docstring": "Print the dictionary entry of a feed in a nice way."
  },
  {
    "code": "def _batch_key(self, query):\n    return ''.join( ['%s%s'%(k,v) for k,v in sorted(query.items())] )",
    "docstring": "Get a unique id from a query."
  },
  {
    "code": "def bandpass(data, freqmin, freqmax, df, corners=4, zerophase=True):\n    fe = 0.5 * df\n    low = freqmin / fe\n    high = freqmax / fe\n    if high - 1.0 > -1e-6:\n        msg = (\"Selected high corner frequency ({}) of bandpass is at or \"\n               \"above Nyquist ({}). Applying a high-pass instead.\").format(\n            freqmax, fe)\n        warnings.warn(msg)\n        return highpass(data, freq=freqmin, df=df, corners=corners,\n                        zerophase=zerophase)\n    if low > 1:\n        msg = \"Selected low corner frequency is above Nyquist.\"\n        raise ValueError(msg)\n    z, p, k = iirfilter(corners, [low, high], btype='band',\n                        ftype='butter', output='zpk')\n    sos = zpk2sos(z, p, k)\n    if zerophase:\n        firstpass = sosfilt(sos, data)\n        return sosfilt(sos, firstpass[::-1])[::-1]\n    else:\n        return sosfilt(sos, data)",
    "docstring": "Butterworth-Bandpass Filter.\n\n    Filter data from ``freqmin`` to ``freqmax`` using ``corners``\n    corners.\n    The filter uses :func:`scipy.signal.iirfilter` (for design)\n    and :func:`scipy.signal.sosfilt` (for applying the filter).\n\n    :type data: numpy.ndarray\n    :param data: Data to filter.\n    :param freqmin: Pass band low corner frequency.\n    :param freqmax: Pass band high corner frequency.\n    :param df: Sampling rate in Hz.\n    :param corners: Filter corners / order.\n    :param zerophase: If True, apply filter once forwards and once backwards.\n        This results in twice the filter order but zero phase shift in\n        the resulting filtered trace.\n    :return: Filtered data."
  },
  {
    "code": "def sync_client(self):\n        if not self._sync_client:\n            self._sync_client = AlfSyncClient(\n                token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'),\n                client_id=self.config.get('OAUTH_CLIENT_ID'),\n                client_secret=self.config.get('OAUTH_CLIENT_SECRET')\n            )\n        return self._sync_client",
    "docstring": "Synchronous OAuth 2.0 Bearer client"
  },
  {
    "code": "def delete_row(self,keyValue=None,table=None,verbose=None):\n        PARAMS=set_param(['keyValue','table'],[keyValue,table])\n        response=api(url=self.__url+\"/delete row\", PARAMS=PARAMS, method=\"POST\", verbose=verbose)\n        return response",
    "docstring": "Deletes a row from a table.Requires the table name or SUID and the row key.\n\n        :param keyValue (string): Specifies the primary key of a value in the row o\n            f a table\n        :param table (string, optional): Specifies a table by table name. If the pr\n            efix SUID: is used, the table corresponding the SUID will be returne\n            d."
  },
  {
    "code": "def BuildServiceStub(self, cls):\n    def _ServiceStubInit(stub, rpc_channel):\n      stub.rpc_channel = rpc_channel\n    self.cls = cls\n    cls.__init__ = _ServiceStubInit\n    for method in self.descriptor.methods:\n      setattr(cls, method.name, self._GenerateStubMethod(method))",
    "docstring": "Constructs the stub class.\n\n    Args:\n      cls: The class that will be constructed."
  },
  {
    "code": "def create_all(self, checkfirst: bool = True) -> None:\n        self.base.metadata.create_all(bind=self.engine, checkfirst=checkfirst)",
    "docstring": "Create the PyBEL cache's database and tables.\n\n        :param checkfirst: Check if the database exists before trying to re-make it"
  },
  {
    "code": "def app_evaluation_count(app_id, value=1):\n        return TabEvaluation.select().where(\n            (TabEvaluation.post_id == app_id) & (TabEvaluation.value == value)\n        ).count()",
    "docstring": "Get the Evalution sum."
  },
  {
    "code": "def get_header(self, header_name):\n        if header_name in self.headers:\n            return self.headers[header_name]\n        return self.add_header_name(header_name)",
    "docstring": "Returns a header with that name, creates it if it does not exist."
  },
  {
    "code": "def _flush_puts(self, items, options):\n    datastore.Put(items, config=self._create_config(options))",
    "docstring": "Flush all puts to datastore."
  },
  {
    "code": "def specialize(self, start, end):\n        new_nodes = _curve_helpers.specialize_curve(self._nodes, start, end)\n        return Curve(new_nodes, self._degree, _copy=False)",
    "docstring": "Specialize the curve to a given sub-interval.\n\n        .. image:: ../../images/curve_specialize.png\n           :align: center\n\n        .. doctest:: curve-specialize\n\n           >>> nodes = np.asfortranarray([\n           ...     [0.0, 0.5, 1.0],\n           ...     [0.0, 1.0, 0.0],\n           ... ])\n           >>> curve = bezier.Curve(nodes, degree=2)\n           >>> new_curve = curve.specialize(-0.25, 0.75)\n           >>> new_curve.nodes\n           array([[-0.25 ,  0.25 ,  0.75 ],\n                  [-0.625,  0.875,  0.375]])\n\n        .. testcleanup:: curve-specialize\n\n           import make_images\n           make_images.curve_specialize(curve, new_curve)\n\n        This is generalized version of :meth:`subdivide`, and can even\n        match the output of that method:\n\n        .. testsetup:: curve-specialize2\n\n           import numpy as np\n           import bezier\n\n           nodes = np.asfortranarray([\n               [0.0, 0.5, 1.0],\n               [0.0, 1.0, 0.0],\n           ])\n           curve = bezier.Curve(nodes, degree=2)\n\n        .. doctest:: curve-specialize2\n\n           >>> left, right = curve.subdivide()\n           >>> also_left = curve.specialize(0.0, 0.5)\n           >>> np.all(also_left.nodes == left.nodes)\n           True\n           >>> also_right = curve.specialize(0.5, 1.0)\n           >>> np.all(also_right.nodes == right.nodes)\n           True\n\n        Args:\n            start (float): The start point of the interval we\n                are specializing to.\n            end (float): The end point of the interval we\n                are specializing to.\n\n        Returns:\n            Curve: The newly-specialized curve."
  },
  {
    "code": "def search_series(self, name=None, imdb_id=None, zap2it_id=None):\n        arguments = locals()\n        optional_parameters = {'name': 'name', 'imdb_id': 'imdbId', 'zap2it_id': 'zap2itId'}\n        query_string = utils.query_param_string_from_option_args(optional_parameters, arguments)\n        raw_response = requests_util.run_request('get', '%s%s?%s' % (self.API_BASE_URL, '/search/series',\n                                                                     query_string),\n                                                 headers=self.__get_header_with_auth())\n        return self.parse_raw_response(raw_response)",
    "docstring": "Searchs for a series in TheTVDB by either its name, imdb_id or zap2it_id.\n\n        :param name: the name of the series to look for\n        :param imdb_id: the IMDB id of the series to look for\n        :param zap2it_id: the zap2it id of the series to look for.\n        :return: a python dictionary with either the result of the search or an error from TheTVDB."
  },
  {
    "code": "def evaluate(self):\n        try:\n            self.condition = self.terms.prune(ConditionBinOp)\n        except AttributeError:\n            raise ValueError(\"cannot process expression [{expr}], [{slf}] \"\n                             \"is not a valid condition\".format(expr=self.expr,\n                                                               slf=self))\n        try:\n            self.filter = self.terms.prune(FilterBinOp)\n        except AttributeError:\n            raise ValueError(\"cannot process expression [{expr}], [{slf}] \"\n                             \"is not a valid filter\".format(expr=self.expr,\n                                                            slf=self))\n        return self.condition, self.filter",
    "docstring": "create and return the numexpr condition and filter"
  },
  {
    "code": "def _is_declaration(self, name, value):\n        if isinstance(value, (classmethod, staticmethod)):\n            return False\n        elif enums.get_builder_phase(value):\n            return True\n        return not name.startswith(\"_\")",
    "docstring": "Determines if a class attribute is a field value declaration.\n\n        Based on the name and value of the class attribute, return ``True`` if\n        it looks like a declaration of a default field value, ``False`` if it\n        is private (name starts with '_') or a classmethod or staticmethod."
  },
  {
    "code": "def replace_more_comments(self, limit=32, threshold=1):\n        if self._replaced_more:\n            return []\n        remaining = limit\n        more_comments = self._extract_more_comments(self.comments)\n        skipped = []\n        while more_comments:\n            item = heappop(more_comments)\n            if remaining == 0:\n                heappush(more_comments, item)\n                break\n            elif len(item.children) == 0 or 0 < item.count < threshold:\n                heappush(skipped, item)\n                continue\n            new_comments = item.comments(update=False)\n            if new_comments is not None and remaining is not None:\n                remaining -= 1\n            elif new_comments is None:\n                continue\n            for more in self._extract_more_comments(new_comments):\n                more._update_submission(self)\n                heappush(more_comments, more)\n            for comment in new_comments:\n                self._insert_comment(comment)\n        self._replaced_more = True\n        return more_comments + skipped",
    "docstring": "Update the comment tree by replacing instances of MoreComments.\n\n        :param limit: The maximum number of MoreComments objects to\n            replace. Each replacement requires 1 API request. Set to None to\n            have no limit, or to 0 to make no extra requests. Default: 32\n        :param threshold: The minimum number of children comments a\n            MoreComments object must have in order to be replaced. Default: 1\n        :returns: A list of MoreComments objects that were not replaced.\n\n        Note that after making this call, the `comments` attribute of the\n        submission will no longer contain any MoreComments objects. Items that\n        weren't replaced are still removed from the tree, and will be included\n        in the returned list."
  },
  {
    "code": "def would_move_be_promotion(self, location=None):\n        location = location or self.location\n        return (location.rank == 1 and self.color == color.black) or \\\n                (location.rank == 6 and self.color == color.white)",
    "docstring": "Finds if move from current get_location would result in promotion\n\n        :type: location: Location\n        :rtype: bool"
  },
  {
    "code": "def auto_install(self):\n        value = self.get(property_name='auto_install',\n                         environment_variable='PIP_ACCEL_AUTO_INSTALL',\n                         configuration_option='auto-install')\n        if value is not None:\n            return coerce_boolean(value)",
    "docstring": "Whether automatic installation of missing system packages is enabled.\n\n        :data:`True` if automatic installation of missing system packages is\n        enabled, :data:`False` if it is disabled, :data:`None` otherwise (in this case\n        the user will be prompted at the appropriate time).\n\n        - Environment variable: ``$PIP_ACCEL_AUTO_INSTALL`` (refer to\n          :func:`~humanfriendly.coerce_boolean()` for details on how the\n          value of the environment variable is interpreted)\n        - Configuration option: ``auto-install`` (also parsed using\n          :func:`~humanfriendly.coerce_boolean()`)\n        - Default: :data:`None`"
  },
  {
    "code": "def _le_annot_parms(self, annot, p1, p2):\n        w = annot.border[\"width\"]\n        sc = annot.colors[\"stroke\"]\n        if not sc: sc = (0,0,0)\n        scol = \" \".join(map(str, sc)) + \" RG\\n\"\n        fc = annot.colors[\"fill\"]\n        if not fc: fc = (0,0,0)\n        fcol = \" \".join(map(str, fc)) + \" rg\\n\"\n        nr = annot.rect\n        np1 = p1\n        np2 = p2\n        m = self._hor_matrix(np1, np2)\n        im = ~m\n        L = np1 * m\n        R = np2 * m\n        if 0 <= annot.opacity < 1:\n            opacity = \"/Alp0 gs\\n\"\n        else:\n            opacity = \"\"\n        return m, im, L, R, w, scol, fcol, opacity",
    "docstring": "Get common parameters for making line end symbols."
  },
  {
    "code": "def write_json_corpus(documents, fnm):\n    with codecs.open(fnm, 'wb', 'ascii') as f:\n        for document in documents:\n            f.write(json.dumps(document) + '\\n')\n    return documents",
    "docstring": "Write a lisst of Text instances as JSON corpus on disk.\n    A JSON corpus contains one document per line, encoded in JSON.\n\n    Parameters\n    ----------\n    documents: iterable of estnltk.text.Text\n        The documents of the corpus\n    fnm: str\n        The path to save the corpus."
  },
  {
    "code": "def route_election(self, election):\n        if (\n            election.election_type.slug == ElectionType.GENERAL\n            or ElectionType.GENERAL_RUNOFF\n        ):\n            self.bootstrap_general_election(election)\n        elif election.race.special:\n            self.bootstrap_special_election(election)\n        if election.race.office.is_executive:\n            self.bootstrap_executive_office(election)\n        else:\n            self.bootstrap_legislative_office(election)",
    "docstring": "Legislative or executive office?"
  },
  {
    "code": "def calc_radius(latitude, ellipsoid='WGS84'):\n    ellipsoids = {\n        'Airy (1830)': (6377.563, 6356.257),\n        'Bessel': (6377.397, 6356.079),\n        'Clarke (1880)': (6378.249145, 6356.51486955),\n        'FAI sphere': (6371, 6371),\n        'GRS-67': (6378.160, 6356.775),\n        'International': (6378.388, 6356.912),\n        'Krasovsky': (6378.245, 6356.863),\n        'NAD27': (6378.206, 6356.584),\n        'WGS66': (6378.145, 6356.758),\n        'WGS72': (6378.135, 6356.751),\n        'WGS84': (6378.137, 6356.752),\n    }\n    major, minor = ellipsoids[ellipsoid]\n    eccentricity = 1 - (minor ** 2 / major ** 2)\n    sl = math.sin(math.radians(latitude))\n    return (major * (1 - eccentricity)) / (1 - eccentricity * sl ** 2) ** 1.5",
    "docstring": "Calculate earth radius for a given latitude.\n\n    This function is most useful when dealing with datasets that are very\n    localised and require the accuracy of an ellipsoid model without the\n    complexity of code necessary to actually use one.  The results are meant to\n    be used as a :data:`BODY_RADIUS` replacement when the simple geocentric\n    value is not good enough.\n\n    The original use for ``calc_radius`` is to set a more accurate radius value\n    for use with trigpointing databases that are keyed on the OSGB36 datum, but\n    it has been expanded to cover other ellipsoids.\n\n    Args:\n        latitude (float): Latitude to calculate earth radius for\n        ellipsoid (tuple of float): Ellipsoid model to use for calculation\n\n    Returns:\n        float: Approximated Earth radius at the given latitude"
  },
  {
    "code": "def get_declared_items(self):\n        for k, v in super(AndroidListView, self).get_declared_items():\n            if k == 'layout':\n                yield k, v\n                break",
    "docstring": "Override to do it manually"
  },
  {
    "code": "def get_video_start_time(video_file):\n    if not os.path.isfile(video_file):\n        print(\"Error, video file {} does not exist\".format(video_file))\n        return None\n    video_end_time = get_video_end_time(video_file)\n    duration = get_video_duration(video_file)\n    if video_end_time == None or duration == None:\n        return None\n    else:\n        video_start_time = (\n            video_end_time - datetime.timedelta(seconds=duration))\n        return video_start_time",
    "docstring": "Get start time in seconds"
  },
  {
    "code": "def is_serving(self) -> bool:\n        try:\n            return self.server.is_serving()\n        except AttributeError:\n            return self.server.sockets is not None",
    "docstring": "Tell whether the server is accepting new connections or shutting down."
  },
  {
    "code": "def includeme(config):\n    settings = config.get_settings()\n    config.add_view_predicate('last_retry_attempt', LastAttemptPredicate)\n    config.add_view_predicate('retryable_error', RetryableErrorPredicate)\n    def register():\n        attempts = int(settings.get('retry.attempts') or 3)\n        settings['retry.attempts'] = attempts\n        activate_hook = settings.get('retry.activate_hook')\n        activate_hook = config.maybe_dotted(activate_hook)\n        policy = RetryableExecutionPolicy(\n            attempts,\n            activate_hook=activate_hook,\n        )\n        config.set_execution_policy(policy)\n    config.action(None, register, order=PHASE1_CONFIG)",
    "docstring": "Activate the ``pyramid_retry`` execution policy in your application.\n\n    This will add the :func:`pyramid_retry.RetryableErrorPolicy` with\n    ``attempts`` pulled from the ``retry.attempts`` setting.\n\n    The ``last_retry_attempt`` and ``retryable_error`` view predicates\n    are registered.\n\n    This should be included in your Pyramid application via\n    ``config.include('pyramid_retry')``."
  },
  {
    "code": "def main():\n    arguments, parser = parse_arguments()\n    store = RevisionStore()\n    sys.stdout.write(\"Iterating over %d items.\\n\" % arguments.number)\n    for i in xrange(arguments.number):\n        key = chr(65 + (i % 26))\n        value = [key * (i % 26), key * (i % 13), key * (i % 5)]\n        store.add(key, value)\n    if arguments.pause:\n        sys.stdout.write(\"Done!\")\n        sys.stdin.readline()",
    "docstring": "Run a benchmark for N items. If N is not specified, take 1,000,000 for N."
  },
  {
    "code": "def get_authorization_url(self, redirect_uri, client_id, options=None,\n                              scope=None):\n        if not options:\n            options = {}\n        if not scope:\n            scope = \"manage_accounts,collect_payments,\" \\\n                    \"view_user,preapprove_payments,\" \\\n                    \"manage_subscriptions,send_money\"\n        options['scope'] = scope\n        options['redirect_uri'] = redirect_uri\n        options['client_id'] = client_id\n        return self.browser_endpoint + '/oauth2/authorize?' + \\\n            urllib.urlencode(options)",
    "docstring": "Returns a URL to send the user to in order to get authorization.\n        After getting authorization the user will return to redirect_uri.\n        Optionally, scope can be set to limit permissions, and the options\n        dict can be loaded with any combination of state, user_name\n        or user_email.\n\n        :param str redirect_uri: The URI to redirect to after a authorization.\n        :param str client_id: The client ID issued by WePay to your app.\n        :keyword dict options: Allows for passing additional values to the\n            authorize call, aside from scope, redirect_uri, and etc.\n        :keyword str scope: A comma-separated string of permissions."
  },
  {
    "code": "def get_data_context(context_type, options, *args, **kwargs):\n    if context_type == \"SqlAlchemy\":\n        return SqlAlchemyDataContext(options, *args, **kwargs)\n    elif context_type == \"PandasCSV\":\n        return PandasCSVDataContext(options, *args, **kwargs)\n    else:\n        raise ValueError(\"Unknown data context.\")",
    "docstring": "Return a data_context object which exposes options to list datasets and get a dataset from\n    that context. This is a new API in Great Expectations 0.4, and is subject to rapid change.\n\n    :param context_type: (string) one of \"SqlAlchemy\" or \"PandasCSV\"\n    :param options: options to be passed to the data context's connect method.\n    :return: a new DataContext object"
  },
  {
    "code": "def payments(self):\n        payments = self.client.subscription_payments.on(self).list()\n        return payments",
    "docstring": "Return a list of payments for this subscription."
  },
  {
    "code": "def create_client_for_file(self, filename, is_cython=False):\r\n        self.create_new_client(filename=filename, is_cython=is_cython)\r\n        self.master_clients -= 1\r\n        client = self.get_current_client()\r\n        client.allow_rename = False\r\n        tab_text = self.disambiguate_fname(filename)\r\n        self.rename_client_tab(client, tab_text)",
    "docstring": "Create a client to execute code related to a file."
  },
  {
    "code": "def consume(self, char):\n        if self.state == \"stream\":\n            self._stream(char)\n        elif self.state == \"escape\":\n            self._escape_sequence(char)\n        elif self.state == \"escape-lb\":\n            self._escape_parameters(char)\n        elif self.state == \"mode\":\n            self._mode(char)\n        elif self.state == \"charset-g0\":\n            self._charset_g0(char)\n        elif self.state == \"charset-g1\":\n            self._charset_g1(char)",
    "docstring": "Consume a single character and advance the state as necessary."
  },
  {
    "code": "def _apply_properties(widget, properties={}):\n    with widget.hold_sync():\n        for key, value in properties.items():\n            setattr(widget, key, value)",
    "docstring": "Applies the specified properties to the widget.\n\n    `properties` is a dictionary with key value pairs corresponding\n    to the properties to be applied to the widget."
  },
  {
    "code": "def asarray(x, dtype=None):\r\n    iterable = scalarasiter(x)\r\n    if isinstance(iterable, ndarray):\r\n        return iterable\r\n    else:\r\n        if not hasattr(iterable, '__len__'):\r\n            iterable = list(iterable)\r\n        if dtype == object_type:\r\n            a = ndarray((len(iterable),), dtype=dtype)\r\n            for i,v in enumerate(iterable):\r\n                a[i] = v\r\n            return a\r\n        else:\r\n            return array(iterable, dtype=dtype)",
    "docstring": "Convert ``x`` into a ``numpy.ndarray``."
  },
  {
    "code": "def _css_rules_to_string(self, rules):\n        lines = []\n        for item in rules:\n            if isinstance(item, tuple):\n                k, v = item\n                lines.append(\"%s {%s}\" % (k, make_important(v)))\n            else:\n                for rule in item.cssRules:\n                    if isinstance(\n                        rule,\n                        (\n                            cssutils.css.csscomment.CSSComment,\n                            cssutils.css.cssunknownrule.CSSUnknownRule,\n                        ),\n                    ):\n                        continue\n                    for key in rule.style.keys():\n                        rule.style[key] = (\n                            rule.style.getPropertyValue(key, False),\n                            \"!important\",\n                        )\n                lines.append(item.cssText)\n        return \"\\n\".join(lines)",
    "docstring": "given a list of css rules returns a css string"
  },
  {
    "code": "def check_array_or_list(input):\n    if type(input) != np.ndarray:\n        if type(input) == list:\n            output = np.array(input)\n        else:\n            raise TypeError('Expecting input type as ndarray or list.')\n    else:\n        output = input\n    if output.ndim != 1:\n        raise ValueError('Input array must have 1 dimension.')\n    if np.sum(output < 0.) > 0:\n            raise ValueError(\"Input array values cannot be negative.\")\n    return output",
    "docstring": "Return 1D ndarray, if input can be converted and elements are\n    non-negative."
  },
  {
    "code": "def http(self, *args, **kwargs):\n        kwargs['api'] = self.api\n        return http(*args, **kwargs)",
    "docstring": "Starts the process of building a new HTTP route linked to this API instance"
  },
  {
    "code": "def plotGenCost(generators):\n    figure()\n    plots = []\n    for generator in generators:\n        if generator.pcost_model == PW_LINEAR:\n            x = [x for x, _ in generator.p_cost]\n            y = [y for _, y in generator.p_cost]\n        elif generator.pcost_model == POLYNOMIAL:\n            x = scipy.arange(generator.p_min, generator.p_max, 5)\n            y = scipy.polyval(scipy.array(generator.p_cost), x)\n        else:\n            raise\n        plots.append(plot(x, y))\n        xlabel(\"P (MW)\")\n        ylabel(\"Cost ($)\")\n    legend(plots, [g.name for g in generators])\n    show()",
    "docstring": "Plots the costs of the given generators."
  },
  {
    "code": "def decode(self, inputs, context, inference=False):\n        return self.decoder(inputs, context, inference)",
    "docstring": "Applies the decoder to inputs, given the context from the encoder.\n\n        :param inputs: tensor with inputs (batch, seq_len) if 'batch_first'\n            else (seq_len, batch)\n        :param context: context from the encoder\n        :param inference: if True inference mode, if False training mode"
  },
  {
    "code": "def on_for_seconds(self, steering, speed, seconds, brake=True, block=True):\n        (left_speed, right_speed) = self.get_speed_steering(steering, speed)\n        MoveTank.on_for_seconds(self, SpeedNativeUnits(left_speed), SpeedNativeUnits(right_speed), seconds, brake, block)",
    "docstring": "Rotate the motors according to the provided ``steering`` for ``seconds``."
  },
  {
    "code": "def first_order_score(y, mean, scale, shape, skewness):\n        m1 = (np.sqrt(shape)*sp.gamma((shape-1.0)/2.0))/(np.sqrt(np.pi)*sp.gamma(shape/2.0))\n        mean = mean + (skewness - (1.0/skewness))*scale*m1\n        if (y-mean)>=0:\n            return ((shape+1)/shape)*(y-mean)/(np.power(skewness*scale,2) + (np.power(y-mean,2)/shape))\n        else:\n            return ((shape+1)/shape)*(y-mean)/(np.power(scale,2) + (np.power(skewness*(y-mean),2)/shape))",
    "docstring": "GAS Skew t Update term using gradient only - native Python function\n\n        Parameters\n        ----------\n        y : float\n            datapoint for the time series\n\n        mean : float\n            location parameter for the Skew t distribution\n\n        scale : float\n            scale parameter for the Skew t distribution\n\n        shape : float\n            tail thickness parameter for the Skew t distribution\n\n        skewness : float\n            skewness parameter for the Skew t distribution\n\n        Returns\n        ----------\n        - Score of the Skew t family"
  },
  {
    "code": "def generate_content_encoding(self):\n        if self._definition['contentEncoding'] == 'base64':\n            with self.l('if isinstance({variable}, str):'):\n                with self.l('try:'):\n                    self.l('import base64')\n                    self.l('{variable} = base64.b64decode({variable})')\n                with self.l('except Exception:'):\n                    self.l('raise JsonSchemaException(\"{name} must be encoded by base64\")')\n                with self.l('if {variable} == \"\":'):\n                    self.l('raise JsonSchemaException(\"contentEncoding must be base64\")')",
    "docstring": "Means decoding value when it's encoded by base64.\n\n        .. code-block:: python\n\n            {\n                'contentEncoding': 'base64',\n            }"
  },
  {
    "code": "def delegate(attribute_name, method_names):\n    info = {\n        'attribute': attribute_name,\n        'methods': method_names\n    }\n    def decorator(cls):\n        attribute = info['attribute']\n        if attribute.startswith(\"__\"):\n            attribute = \"_\" + cls.__name__ + attribute\n        for name in info['methods']:\n            setattr(cls, name, eval(\"lambda self, *a, **kw: \"\n                                    \"self.{0}.{1}(*a, **kw)\".format(attribute, name)))\n        return cls\n    return decorator",
    "docstring": "Pass the call to the attribute called attribute_name for every method listed in method_names."
  },
  {
    "code": "def get_distribution(dist):\n    if isinstance(dist, six.string_types):\n        dist = Requirement.parse(dist)\n    if isinstance(dist, Requirement):\n        dist = get_provider(dist)\n    if not isinstance(dist, Distribution):\n        raise TypeError(\"Expected string, Requirement, or Distribution\", dist)\n    return dist",
    "docstring": "Return a current distribution object for a Requirement or string"
  },
  {
    "code": "def aggregate_series(self, *args, **kwargs) -> InfoArray:\n        mode = self.aggregation_ext\n        if mode == 'none':\n            return self.series\n        elif mode == 'mean':\n            return self.average_series(*args, **kwargs)\n        else:\n            raise RuntimeError(\n                'Unknown aggregation mode `%s` for sequence %s.'\n                % (mode, objecttools.devicephrase(self)))",
    "docstring": "Aggregates time series data based on the actual\n        |FluxSequence.aggregation_ext| attribute of |IOSequence|\n        subclasses.\n\n        We prepare some nodes and elements with the help of\n        method |prepare_io_example_1| and select a 1-dimensional\n        flux sequence of type |lland_fluxes.NKor| as an example:\n\n        >>> from hydpy.core.examples import prepare_io_example_1\n        >>> nodes, elements = prepare_io_example_1()\n        >>> seq = elements.element3.model.sequences.fluxes.nkor\n\n        If no |FluxSequence.aggregation_ext| is `none`, the\n        original time series values are returned:\n\n        >>> seq.aggregation_ext\n        'none'\n        >>> seq.aggregate_series()\n        InfoArray([[ 24.,  25.,  26.],\n                   [ 27.,  28.,  29.],\n                   [ 30.,  31.,  32.],\n                   [ 33.,  34.,  35.]])\n\n        If no |FluxSequence.aggregation_ext| is `mean`, function\n        |IOSequence.aggregate_series| is called:\n\n        >>> seq.aggregation_ext = 'mean'\n        >>> seq.aggregate_series()\n        InfoArray([ 25.,  28.,  31.,  34.])\n\n        In case the state of the sequence is invalid:\n\n        >>> seq.aggregation_ext = 'nonexistent'\n        >>> seq.aggregate_series()\n        Traceback (most recent call last):\n        ...\n        RuntimeError: Unknown aggregation mode `nonexistent` for \\\nsequence `nkor` of element `element3`.\n\n        The following technical test confirms that all potential\n        positional and keyword arguments are passed properly:\n        >>> seq.aggregation_ext = 'mean'\n\n        >>> from unittest import mock\n        >>> seq.average_series = mock.MagicMock()\n        >>> _ = seq.aggregate_series(1, x=2)\n        >>> seq.average_series.assert_called_with(1, x=2)"
  },
  {
    "code": "def transformer_tpu_1b():\n  hparams = transformer_tpu()\n  hparams.hidden_size = 2048\n  hparams.filter_size = 8192\n  hparams.num_hidden_layers = 8\n  hparams.batch_size = 1024\n  hparams.activation_dtype = \"bfloat16\"\n  hparams.weight_dtype = \"bfloat16\"\n  hparams.shared_embedding_and_softmax_weights = False\n  return hparams",
    "docstring": "Hparams for machine translation with ~1.1B parameters."
  },
  {
    "code": "def _handle_eor(self, route_family):\n        LOG.debug('Handling EOR for %s', route_family)\n        if route_family == RF_RTC_UC:\n            self._unschedule_sending_init_updates()\n            tm = self._core_service.table_manager\n            for rt_nlri in self._init_rtc_nlri_path:\n                tm.learn_path(rt_nlri)\n                self.pause(0)\n            self._init_rtc_nlri_path = None",
    "docstring": "Currently we only handle EOR for RTC address-family.\n\n        We send non-rtc initial updates if not already sent."
  },
  {
    "code": "def send_events(self, events):\n        for event in events:\n            self.queue.events.add().MergeFrom(event)\n        return None",
    "docstring": "Adds multiple events to the queued message\n\n        :returns: None - nothing has been sent to the Riemann server yet"
  },
  {
    "code": "def tx_output(network: str, value: Decimal, n: int,\n              script: ScriptSig) -> TxOut:\n    network_params = net_query(network)\n    return TxOut(network=network_params,\n                 value=int(value * network_params.to_unit),\n                 n=n, script_pubkey=script)",
    "docstring": "create TxOut object"
  },
  {
    "code": "def get_message(self):\n        if not self._message:\n            return None\n        self._populate_message_attributes(self._message)\n        return self._message",
    "docstring": "Get the underlying C message from this object.\n\n        :rtype: uamqp.c_uamqp.cMessage"
  },
  {
    "code": "def _put_many(self, items: Iterable[DtoObject], cls):\n        if cls._dto_type in self._expirations and self._expirations[cls._dto_type] == 0:\n            return\n        session = self._session\n        for item in items:\n            item = cls(**item)\n            item.updated()\n            session.merge(item)",
    "docstring": "Puts many items into the database. Updates lastUpdate column for each of them"
  },
  {
    "code": "def _get_implied_apps(self, detected_apps):\n        def __get_implied_apps(apps):\n            _implied_apps = set()\n            for app in apps:\n                try:\n                    _implied_apps.update(set(self.apps[app]['implies']))\n                except KeyError:\n                    pass\n            return _implied_apps\n        implied_apps = __get_implied_apps(detected_apps)\n        all_implied_apps = set()\n        while not all_implied_apps.issuperset(implied_apps):\n            all_implied_apps.update(implied_apps)\n            implied_apps = __get_implied_apps(all_implied_apps)\n        return all_implied_apps",
    "docstring": "Get the set of apps implied by `detected_apps`."
  },
  {
    "code": "def _locate(self, idx):\n        start = idx * self._width\n        end = (idx + 1) * self._width\n        sbyte, sbit = divmod(start, 8)\n        ebyte = BinInt(end).ceildiv(8)\n        return sbyte, sbit, ebyte",
    "docstring": "Locates an element in the internal data representation.  Returns\n        starting byte index, starting bit index in the starting byte, and\n        one past the final byte index."
  },
  {
    "code": "def shorten(string, max_length=80, trailing_chars=3):\n    assert type(string).__name__ in {'str', 'unicode'}, 'shorten needs string to be a string, not {}'.format(type(string))\n    assert type(max_length) == int, 'shorten needs max_length to be an int, not {}'.format(type(max_length))\n    assert type(trailing_chars) == int, 'shorten needs trailing_chars to be an int, not {}'.format(type(trailing_chars))\n    assert max_length > 0, 'shorten needs max_length to be positive, not {}'.format(max_length)\n    assert trailing_chars >= 0, 'shorten needs trailing_chars to be greater than or equal to 0, not {}'.format(trailing_chars)\n    return (\n        string\n    ) if len(string) <= max_length else (\n        '{before:}...{after:}'.format(\n            before=string[:max_length-(trailing_chars+3)],\n            after=string[-trailing_chars:] if trailing_chars>0 else ''\n        )\n    )",
    "docstring": "trims the 'string' argument down to 'max_length' to make previews to long string values"
  },
  {
    "code": "def set_default_by_index(self, index):\n        if index >= len(self._datasets):\n            raise DataInvalidIndex('A dataset with index {} does not exist'.format(index))\n        self._default_index = index",
    "docstring": "Set the default dataset by its index.\n\n        After changing the default dataset, all calls without explicitly specifying the\n        dataset by index or alias will be redirected to this dataset.\n\n        Args:\n            index (int): The index of the dataset that should be made the default.\n\n        Raises:\n            DataInvalidIndex: If the index does not represent a valid dataset."
  },
  {
    "code": "def update_from_stripe_data(self, stripe_coupon, exclude_fields=None, commit=True):\n        fields_to_update = self.STRIPE_FIELDS - set(exclude_fields or [])\n        update_data = {key: stripe_coupon[key] for key in fields_to_update}\n        for field in [\"created\", \"redeem_by\"]:\n            if update_data.get(field):\n                update_data[field] = timestamp_to_timezone_aware_date(update_data[field])\n        if update_data.get(\"amount_off\"):\n            update_data[\"amount_off\"] = Decimal(update_data[\"amount_off\"]) / 100\n        for key, value in six.iteritems(update_data):\n            setattr(self, key, value)\n        if commit:\n            return StripeCoupon.objects.filter(pk=self.pk).update(**update_data)",
    "docstring": "Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve.\n\n        To only update the object, set the commit param to False.\n        Returns the number of rows altered or None if commit is False."
  },
  {
    "code": "def serialize(self, private=False):\n        if not self.priv_key and not self.pub_key:\n            raise SerializationNotPossible()\n        res = self.common()\n        public_longs = list(set(self.public_members) & set(self.longs))\n        for param in public_longs:\n            item = getattr(self, param)\n            if item:\n                res[param] = item\n        if private:\n            for param in self.longs:\n                if not private and param in [\"d\", \"p\", \"q\", \"dp\", \"dq\", \"di\",\n                                             \"qi\"]:\n                    continue\n                item = getattr(self, param)\n                if item:\n                    res[param] = item\n        if self.x5c:\n            res['x5c'] = [x.decode('utf-8') for x in self.x5c]\n        return res",
    "docstring": "Given a cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or\n        RSAPublicKey instance construct the JWK representation.\n\n        :param private: Should I do the private part or not\n        :return: A JWK as a dictionary"
  },
  {
    "code": "def get_leaf_node_path_list(self, sep=os.path.sep, type_str=None):\n        return [v.get_path_str(sep, type_str) for v in self.leaf_node_gen]",
    "docstring": "Get paths for all leaf nodes for the tree rooted at this node.\n\n        Args:\n            sep: str\n                One or more characters to insert between each element in the path.\n                Defaults to \"/\" on Unix and \"\\\" on Windows.\n\n            type_str:\n                SUBJECT_NODE_TAG, TYPE_NODE_TAG or None. If set, only include\n                information from nodes of that type.\n\n        Returns:\n            list of str: The paths to the leaf nodes for the tree rooted at this node."
  },
  {
    "code": "def get_logged_in_account(token_manager=None,\n                          app_url=defaults.APP_URL):\n    return get_logged_in_account(token_manager=token_manager,\n                                 app_url=app_url)['id']",
    "docstring": "get the account details for logged in account of the auth token_manager"
  },
  {
    "code": "def Command(self, Command, Reply=u'', Block=False, Timeout=30000, Id=-1):\n        from api import Command as CommandClass\n        return CommandClass(Command, Reply, Block, Timeout, Id)",
    "docstring": "Creates an API command object.\n\n        :Parameters:\n          Command : unicode\n            Command string.\n          Reply : unicode\n            Expected reply. By default any reply is accepted (except errors which raise an\n            `SkypeError` exception).\n          Block : bool\n            If set to True, `SendCommand` method waits for a response from Skype API before\n            returning.\n          Timeout : float, int or long\n            Timeout. Used if Block == True. Timeout may be expressed in milliseconds if the type\n            is int or long or in seconds (or fractions thereof) if the type is float.\n          Id : int\n            Command Id. The default (-1) means it will be assigned automatically as soon as the\n            command is sent.\n\n        :return: A command object.\n        :rtype: `Command`\n\n        :see: `SendCommand`"
  },
  {
    "code": "def pf_to_n(L, pf, R):\n    dim = L.shape[0]\n    n = int(round(pf * np.product(L) / sphere_volume(R, dim)))\n    pf_actual = n_to_pf(L, n, R)\n    return n, pf_actual",
    "docstring": "Returns the number of non-intersecting spheres required to achieve\n    as close to a given packing fraction as possible, along with the actual\n    achieved packing fraction. for a number of non-intersecting spheres.\n\n    Parameters\n    ----------\n    L: float array, shape (d,)\n        System lengths.\n    pf: float\n        Fraction of space to be occupied by the spheres.\n    R: float\n        Sphere radius.\n\n    Returns\n    -------\n    n: integer\n        Number of spheres required to achieve a packing fraction `pf_actual`\n    pf_actual:\n        Fraction of space occupied by `n` spheres.\n        This is the closest possible fraction achievable to `pf`."
  },
  {
    "code": "def move_to(self, start, end):\n        start = numpy.array(start)\n        end = numpy.array(end)\n        if numpy.allclose(start, end):\n            raise ValueError('start and end must NOT be identical')\n        translation, angle, axis, point = find_transformations(\n            self.helix_start, self.helix_end, start, end)\n        if not numpy.isclose(angle, 0.0):\n            self.rotate(angle=angle, axis=axis, point=point, radians=False)\n        self.translate(vector=translation)\n        return",
    "docstring": "Moves the `Polynucleotide` to lie on the `start` and `end` vector.\n\n        Parameters\n        ----------\n        start : 3D Vector (tuple or list or numpy.array)\n            The coordinate of the start of the helix primitive.\n        end : 3D Vector (tuple or list or numpy.array)\n            The coordinate of the end of the helix primitive.\n\n        Raises\n        ------\n        ValueError\n            Raised if `start` and `end` are very close together."
  },
  {
    "code": "def try_to_restart_deads(self):\n        to_restart = self.to_restart[:]\n        del self.to_restart[:]\n        for instance in to_restart:\n            logger.warning(\"Trying to restart module: %s\", instance.name)\n            if self.try_instance_init(instance):\n                logger.warning(\"Restarting %s...\", instance.name)\n                instance.process = None\n                instance.start()\n            else:\n                self.to_restart.append(instance)",
    "docstring": "Try to reinit and restart dead instances\n\n        :return: None"
  },
  {
    "code": "def _eval_call(self, node):\n        try:\n            func = self.functions[node.func.id]\n        except KeyError:\n            raise NameError(node.func.id)\n        value = func(\n            *(self._eval(a) for a in node.args),\n            **dict(self._eval(k) for k in node.keywords)\n        )\n        if value is True:\n            return 1\n        elif value is False:\n            return 0\n        else:\n            return value",
    "docstring": "Evaluate a function call\n\n        :param node: Node to eval\n        :return: Result of node"
  },
  {
    "code": "def reset_ilo(self):\n        manager, reset_uri = self._get_ilo_details()\n        action = {'Action': 'Reset'}\n        status, headers, response = self._rest_post(reset_uri, None, action)\n        if(status != 200):\n            msg = self._get_extended_error(response)\n            raise exception.IloError(msg)\n        common.wait_for_ilo_after_reset(self)",
    "docstring": "Resets the iLO.\n\n        :raises: IloError, on an error from iLO.\n        :raises: IloConnectionError, if iLO is not up after reset.\n        :raises: IloCommandNotSupportedError, if the command is not supported\n                 on the server."
  },
  {
    "code": "def translate_update(blob):\n  \"converts JSON parse output to self-aware objects\"\n  return {translate_key(k):parse_serialdiff(v) for k,v in blob.items()}",
    "docstring": "converts JSON parse output to self-aware objects"
  },
  {
    "code": "def add_file_metadata(self, fname):\r\n        file_dict = {}\r\n        file_dict[\"fullfilename\"] = fname\r\n        try:\r\n            file_dict[\"name\"] = os.path.basename(fname)\r\n            file_dict[\"date\"] = self.GetDateAsString(fname)\r\n            file_dict[\"size\"] = os.path.getsize(fname)\r\n            file_dict[\"path\"] = os.path.dirname(fname)\r\n        except IOError:\r\n            print('Error getting metadata for file')\r\n        self.fl_metadata.append(file_dict)",
    "docstring": "collects the files metadata - note that this will fail\r\n        with strange errors if network connection drops out to\r\n        shared folder, but it is better to stop the program\r\n        rather than do a try except otherwise you will get an\r\n        incomplete set of files."
  },
  {
    "code": "def pull(self):\n        lock_acquired = self._pull_lock.acquire(blocking=False)\n        if not lock_acquired:\n            raise PullOrderException()\n        return self._results_generator()",
    "docstring": "Returns a generator containing the results of the next query in the pipeline"
  },
  {
    "code": "def _qteMouseClicked(self, widgetObj):\n        app = qteGetAppletFromWidget(widgetObj)\n        if app is None:\n            return\n        else:\n            self._qteActiveApplet = app\n        if not hasattr(widgetObj, '_qteAdmin'):\n            self._qteActiveApplet.qteMakeWidgetActive(widgetObj)\n        else:\n            if app._qteAdmin.isQtmacsApplet:\n                self._qteActiveApplet.qteMakeWidgetActive(None)\n            else:\n                self._qteActiveApplet.qteMakeWidgetActive(widgetObj)\n        self._qteFocusManager()",
    "docstring": "Update the Qtmacs internal focus state as the result of a mouse click.\n\n        |Args|\n\n        * ``new`` (**QWidget**): the widget that received the focus.\n\n        |Returns|\n\n        * **None**\n\n        |Raises|\n\n        * **None**"
  },
  {
    "code": "def run_cmd(command, verbose=True, shell='/bin/bash'):\n    process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT, executable=shell)\n    output = process.stdout.read().decode().strip().split('\\n')\n    if verbose:\n        return output\n    return [line for line in output if line.strip()]",
    "docstring": "internal helper function to run shell commands and get output"
  },
  {
    "code": "def set_root(self, root):\n        if root is None:\n            return\n        for plot in self.traverse(lambda x: x):\n            plot._root = root",
    "docstring": "Sets the root model on all subplots."
  },
  {
    "code": "def terms(self, facet_name, field, size=10, order=None, all_terms=False, exclude=[], regex='', regex_flags=''):\n        self[facet_name] = dict(terms=dict(field=field, size=size))\n        if order:\n            self[facet_name][terms]['order'] = order\n        if all_terms:\n            self[facet_name][terms]['all_terms'] = True\n        if exclude:\n            self[facet_name][terms]['exclude'] = exclude\n        if regex:\n            self[facet_name][terms]['regex'] = regex\n        if regex_flags:\n            self[facet_name][terms]['regex_flags'] = regex_flags\n        return self",
    "docstring": "Allow to specify field facets that return the N most frequent terms.\n\n        Ordering: Allow to control the ordering of the terms facets, to be ordered by count, term, reverse_count or reverse_term. The default is count.\n        All Terms: Allow to get all the terms in the terms facet, ones that do not match a hit, will have a count of 0. Note, this should not be used with fields that have many terms.\n        Excluding Terms: It is possible to specify a set of terms that should be excluded from the terms facet request result.\n        Regex Patterns: The terms API allows to define regex expression that will control which terms will be included in the faceted list."
  },
  {
    "code": "def delete_events(self, event_collection, params):\n        url = \"{0}/{1}/projects/{2}/events/{3}\".format(self.base_url,\n                                                       self.api_version,\n                                                       self.project_id,\n                                                       event_collection)\n        headers = utilities.headers(self.master_key)\n        response = self.fulfill(HTTPMethods.DELETE, url, params=params, headers=headers, timeout=self.post_timeout)\n        self._error_handling(response)\n        return True",
    "docstring": "Deletes events via the Keen IO API. A master key must be set first.\n\n        :param event_collection: string, the event collection from which event are being deleted"
  },
  {
    "code": "def nlmsg_find_attr(nlh, hdrlen, attrtype):\n    return nla_find(nlmsg_attrdata(nlh, hdrlen), nlmsg_attrlen(nlh, hdrlen), attrtype)",
    "docstring": "Find a specific attribute in a Netlink message.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L231\n\n    Positional arguments:\n    nlh -- Netlink message header (nlmsghdr class instance).\n    hdrlen -- length of family specific header (integer).\n    attrtype -- type of attribute to look for (integer).\n\n    Returns:\n    The first attribute which matches the specified type (nlattr class instance)."
  },
  {
    "code": "def _get_field_doc(self, field):\n        fieldspec = dict()\n        fieldspec['type'] = field.__class__.__name__\n        fieldspec['required'] = field.required\n        fieldspec['validators'] = [{validator.__class__.__name__: validator.__dict__} for validator in field.validators]\n        return fieldspec",
    "docstring": "Return documentation for a field in the representation."
  },
  {
    "code": "def routeByMonthAbbr(self, request, year, monthAbbr):\n        month = (DatePictures['Mon'].index(monthAbbr.lower()) // 4) + 1\n        return self.serveMonth(request, year, month)",
    "docstring": "Route a request with a month abbreviation to the monthly view."
  },
  {
    "code": "def normalize_mesh(mesh):\n  mesh = dict(mesh)\n  pos = mesh['position'][:,:3].copy()\n  pos -= (pos.max(0)+pos.min(0)) / 2.0\n  pos /= np.abs(pos).max()\n  mesh['position'] = pos\n  return mesh",
    "docstring": "Scale mesh to fit into -1..1 cube"
  },
  {
    "code": "def retrieve_matching_jwk(self, token):\n        response_jwks = requests.get(\n            self.OIDC_OP_JWKS_ENDPOINT,\n            verify=self.get_settings('OIDC_VERIFY_SSL', True)\n        )\n        response_jwks.raise_for_status()\n        jwks = response_jwks.json()\n        jws = JWS.from_compact(token)\n        json_header = jws.signature.protected\n        header = Header.json_loads(json_header)\n        key = None\n        for jwk in jwks['keys']:\n            if jwk['kid'] != smart_text(header.kid):\n                continue\n            if 'alg' in jwk and jwk['alg'] != smart_text(header.alg):\n                raise SuspiciousOperation('alg values do not match.')\n            key = jwk\n        if key is None:\n            raise SuspiciousOperation('Could not find a valid JWKS.')\n        return key",
    "docstring": "Get the signing key by exploring the JWKS endpoint of the OP."
  },
  {
    "code": "def save_response_content(response, filename='data.csv', destination=os.path.curdir, chunksize=32768):\n    chunksize = chunksize or 32768\n    if os.path.sep in filename:\n        full_destination_path = filename\n    else:\n        full_destination_path = os.path.join(destination, filename)\n    full_destination_path = expand_filepath(full_destination_path)\n    with open(full_destination_path, \"wb\") as f:\n        for chunk in tqdm(response.iter_content(CHUNK_SIZE)):\n            if chunk:\n                f.write(chunk)\n    return full_destination_path",
    "docstring": "For streaming response from requests, download the content one CHUNK at a time"
  },
  {
    "code": "def makeCredentials(path, email):\n    key = _generateKey()\n    cert = _makeCertificate(key, email)\n    certPath = path.child(\"client.pem\")\n    certPath.alwaysCreate = True\n    with certPath.open(\"wb\") as pemFile:\n        pemFile.write(dump_privatekey(FILETYPE_PEM, key))\n        pemFile.write(dump_certificate(FILETYPE_PEM, cert))",
    "docstring": "Make credentials for the client from given e-mail address and store\n    them in the directory at path."
  },
  {
    "code": "def use_value(self, value):\n        if self.check_value(value):\n            return value\n        return self.convert_value(value)",
    "docstring": "Converts value to field type or use original"
  },
  {
    "code": "def get_arbiter_broks(self):\n        with self.arbiter_broks_lock:\n            statsmgr.gauge('get-new-broks-count.arbiter', len(self.arbiter_broks))\n            self.external_broks.extend(self.arbiter_broks)\n            self.arbiter_broks = []",
    "docstring": "Get the broks from the arbiters,\n        but as the arbiter_broks list can be push by arbiter without Global lock,\n        we must protect this with a lock\n\n        TODO: really? check this arbiter behavior!\n\n        :return: None"
  },
  {
    "code": "def init_nautilus(method):\n    print(\"Preference elicitation options:\")\n    print(\"\\t1 - Percentages\")\n    print(\"\\t2 - Relative ranks\")\n    print(\"\\t3 - Direct\")\n    PREFCLASSES = [PercentageSpecifictation, RelativeRanking, DirectSpecification]\n    pref_sel = int(\n        _prompt_wrapper(\n            \"Reference elicitation \",\n            default=u\"%s\" % (1),\n            validator=NumberValidator([1, 3]),\n        )\n    )\n    preference_class = PREFCLASSES[pref_sel - 1]\n    print(\"Nadir: %s\" % method.problem.nadir)\n    print(\"Ideal: %s\" % method.problem.ideal)\n    if method.current_iter - method.user_iters:\n        finished_iter = method.user_iters - method.current_iter\n    else:\n        finished_iter = 0\n    new_iters = int(\n        _prompt_wrapper(\n            u\"Ni: \", default=u\"%s\" % (method.current_iter), validator=NumberValidator()\n        )\n    )\n    method.current_iter = new_iters\n    method.user_iters = finished_iter + new_iters\n    return preference_class",
    "docstring": "Initialize nautilus method\n\n    Parameters\n    ----------\n\n    method\n        Interactive method used for the process\n\n    Returns\n    -------\n\n    PreferenceInformation subclass to be initialized"
  },
  {
    "code": "def handle_memory(self, obj):\n        if obj.subject is not None:\n            with self.con as db:\n                SchemaBase.note(\n                    db,\n                    obj.subject,\n                    obj.state,\n                    obj.object,\n                    text=obj.text,\n                    html=obj.html,\n                )\n        return obj",
    "docstring": "Handle a memory event.\n\n        This function accesses the internal database. It writes a record\n        containing state information and an optional note.\n\n        :param obj: A :py:class:`~turberfield.dialogue.model.Model.Memory`\n            object.\n        :return: The supplied object."
  },
  {
    "code": "def load(path):\n    with open(path) as rfile:\n        steps = MODEL.parse(rfile.read())\n    new_steps = []\n    for step in steps:\n        new_steps += expand_includes(step, path)\n    return new_steps",
    "docstring": "Load |path| and recursively expand any includes."
  },
  {
    "code": "def is_result_edition_allowed(self, analysis_brain):\n        if not self.is_analysis_edition_allowed(analysis_brain):\n            return False\n        obj = api.get_object(analysis_brain)\n        if not obj.getDetectionLimitOperand():\n            return True\n        if obj.getDetectionLimitSelector():\n            if not obj.getAllowManualDetectionLimit():\n                return False\n        return True",
    "docstring": "Checks if the edition of the result field is allowed\n\n        :param analysis_brain: Brain that represents an analysis\n        :return: True if the user can edit the result field, otherwise False"
  },
  {
    "code": "def set_progress_brackets(self, start, end):\n        self.sep_start = start\n        self.sep_end = end",
    "docstring": "Set brackets to set around a progress bar."
  },
  {
    "code": "def extract_field(self, field):\n        if not isinstance(field, basestring):\n            err_msg = u\"Invalid extractor! => {}\\n\".format(field)\n            logger.log_error(err_msg)\n            raise exceptions.ParamsError(err_msg)\n        msg = \"extract: {}\".format(field)\n        if text_extractor_regexp_compile.match(field):\n            value = self._extract_field_with_regex(field)\n        else:\n            value = self._extract_field_with_delimiter(field)\n        if is_py2 and isinstance(value, unicode):\n            value = value.encode(\"utf-8\")\n        msg += \"\\t=> {}\".format(value)\n        logger.log_debug(msg)\n        return value",
    "docstring": "extract value from requests.Response."
  },
  {
    "code": "def invoke(self):\n        logger.debug('Running deferred function %s.', self)\n        self.module.makeLoadable()\n        function, args, kwargs = list(map(dill.loads, (self.function, self.args, self.kwargs)))\n        return function(*args, **kwargs)",
    "docstring": "Invoke the captured function with the captured arguments."
  },
  {
    "code": "def identify_denonavr_receivers():\n    devices = send_ssdp_broadcast()\n    receivers = []\n    for device in devices:\n        try:\n            receiver = evaluate_scpd_xml(device[\"URL\"])\n        except ConnectionError:\n            continue\n        if receiver:\n            receivers.append(receiver)\n    return receivers",
    "docstring": "Identify DenonAVR using SSDP and SCPD queries.\n\n    Returns a list of dictionaries which includes all discovered Denon AVR\n    devices with keys \"host\", \"modelName\", \"friendlyName\", \"presentationURL\"."
  },
  {
    "code": "def n2s(self, offset, length):\n        s = ''\n        for dummy in range(length):\n            if self.endian == 'I':\n                s += chr(offset & 0xFF)\n            else:\n                s = chr(offset & 0xFF) + s\n            offset = offset >> 8\n        return s",
    "docstring": "Convert offset to string."
  },
  {
    "code": "def unregister(self, name):\r\n        try:\r\n            name = name.name\r\n        except AttributeError:\r\n            pass\r\n        return self.pop(name,None)",
    "docstring": "Unregister function by name."
  },
  {
    "code": "def get_parent_objective_bank_ids(self, objective_bank_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.get_parent_catalog_ids(catalog_id=objective_bank_id)\n        return self._hierarchy_session.get_parents(id_=objective_bank_id)",
    "docstring": "Gets the parent ``Ids`` of the given objective bank.\n\n        arg:    objective_bank_id (osid.id.Id): the ``Id`` of an\n                objective bank\n        return: (osid.id.IdList) - the parent ``Ids`` of the objective\n                bank\n        raise:  NotFound - ``objective_bank_id`` is not found\n        raise:  NullArgument - ``objective_bank_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def remove_product_version_from_build_configuration(id=None, name=None, product_version_id=None):\n    data = remove_product_version_from_build_configuration_raw(id, name, product_version_id)\n    if data:\n        return utils.format_json_list(data)",
    "docstring": "Remove a ProductVersion from association with a BuildConfiguration"
  },
  {
    "code": "def append(self, state, symbol, action, destinationstate, production = None):\n        if action not in (None, \"Accept\", \"Shift\", \"Reduce\"):\n            raise TypeError\n        rule = {\"action\":action, \"dest\":destinationstate}\n        if action == \"Reduce\":\n            if rule is None:\n                raise TypeError(\"Expected production parameter\")\n            rule[\"rule\"] = production\n        while isinstance(symbol, TerminalSymbol) and isinstance(symbol.gd, Iterable) and len(symbol.gd) == 1 and isinstance(list(symbol.gd)[0], Grammar):\n            symbol = TerminalSymbol(list(symbol.gd)[0])\n        if not isinstance(symbol, Symbol):\n            raise TypeError(\"Expected symbol, got %s\" % symbol)\n        self[state][symbol] = rule",
    "docstring": "Appends a new rule"
  },
  {
    "code": "def get_status(video_id, _connection=None):\n        c = _connection\n        if not c:\n            c = connection.APIConnection()\n        return c.post('get_upload_status', video_id=video_id)",
    "docstring": "Get the status of a video given the ``video_id`` parameter."
  },
  {
    "code": "def compress(data,\n             mode=DEFAULT_MODE,\n             quality=lib.BROTLI_DEFAULT_QUALITY,\n             lgwin=lib.BROTLI_DEFAULT_WINDOW,\n             lgblock=0,\n             dictionary=b''):\n    compressor = Compressor(\n        mode=mode,\n        quality=quality,\n        lgwin=lgwin,\n        lgblock=lgblock,\n        dictionary=dictionary\n    )\n    compressed_data = compressor._compress(data, lib.BROTLI_OPERATION_FINISH)\n    assert lib.BrotliEncoderIsFinished(compressor._encoder) == lib.BROTLI_TRUE\n    assert (\n        lib.BrotliEncoderHasMoreOutput(compressor._encoder) == lib.BROTLI_FALSE\n    )\n    return compressed_data",
    "docstring": "Compress a string using Brotli.\n\n    .. versionchanged:: 0.5.0\n       Added ``mode``, ``quality``, `lgwin``, ``lgblock``, and ``dictionary``\n       parameters.\n\n    :param data: A bytestring containing the data to compress.\n    :type data: ``bytes``\n\n    :param mode: The encoder mode.\n    :type mode: :class:`BrotliEncoderMode` or ``int``\n\n    :param quality: Controls the compression-speed vs compression-density\n        tradeoffs. The higher the quality, the slower the compression. The\n        range of this value is 0 to 11.\n    :type quality: ``int``\n\n    :param lgwin: The base-2 logarithm of the sliding window size. The range of\n        this value is 10 to 24.\n    :type lgwin: ``int``\n\n    :param lgblock: The base-2 logarithm of the maximum input block size. The\n        range of this value is 16 to 24. If set to 0, the value will be set\n        based on ``quality``.\n    :type lgblock: ``int``\n\n    :param dictionary: A pre-set dictionary for LZ77. Please use this with\n        caution: if a dictionary is used for compression, the same dictionary\n        **must** be used for decompression!\n    :type dictionary: ``bytes``\n\n    :returns: The compressed bytestring.\n    :rtype: ``bytes``"
  },
  {
    "code": "def host_context(func):\n    \"Sets the context of the setting to the current host\"\n    @wraps(func)\n    def decorator(*args, **kwargs):\n        hosts = get_hosts_settings()\n        with settings(**hosts[env.host]):\n            return func(*args, **kwargs)\n    return decorator",
    "docstring": "Sets the context of the setting to the current host"
  },
  {
    "code": "def usages(self):\n        row, col = self.editor.cursor()\n        self.log.debug('usages: in')\n        self.call_options[self.call_id] = {\n                \"word_under_cursor\": self.editor.current_word(),\n                \"false_resp_msg\": \"Not a valid symbol under the cursor\"}\n        self.send_at_point(\"UsesOfSymbol\", row, col)",
    "docstring": "Request usages of whatever at cursor."
  },
  {
    "code": "def get(cls, bucket, key):\n        return cls.query.filter_by(\n            bucket_id=as_bucket_id(bucket),\n            key=key,\n        ).one_or_none()",
    "docstring": "Get tag object."
  },
  {
    "code": "def code(self, text, lang=None):\n        with self.paragraph(stylename='code'):\n            lines = text.splitlines()\n            for line in lines[:-1]:\n                self._code_line(line)\n                self.linebreak()\n            self._code_line(lines[-1])",
    "docstring": "Add a code block."
  },
  {
    "code": "def set_setting(key, val, env=None):\n    return settings.set(key, val, env=env)",
    "docstring": "Changes the value of the specified key in the current environment, or in\n    another environment if specified."
  },
  {
    "code": "def apply_depth_first(nodes, func, depth=0, as_dict=False, parents=None):\n    if as_dict:\n        items = OrderedDict()\n    else:\n        items = []\n    if parents is None:\n        parents = []\n    node_count = len(nodes)\n    for i, node in enumerate(nodes):\n        first = (i == 0)\n        last = (i == (node_count - 1))\n        if isinstance(node, tuple):\n            node, nodes = node\n        else:\n            nodes = []\n        item = func(node, parents, nodes, first, last, depth)\n        item_parents = parents + [node]\n        if nodes:\n            children = apply_depth_first(nodes, func,\n                                         depth=depth + 1,\n                                         as_dict=as_dict,\n                                         parents=item_parents)\n        else:\n            children = None\n        if as_dict:\n            items[node] = Node(item, children)\n        elif nodes:\n            items.append((item, children))\n        else:\n            items.append(item)\n    return items",
    "docstring": "Given a structure such as the application menu layout described above, we\n    may want to apply an operation to each entry to create a transformed\n    version of the structure.\n\n    For example, let's convert all entries in the application menu layout from\n    above to upper-case:\n\n    >>> pprint(apply_depth_first(menu_actions, lambda node, parents, nodes: node.upper()))\n    [('FILE',\n      ['LOAD', 'SAVE', ('QUIT', ['QUIT WITHOUT SAVING', 'SAVE AND QUIT'])]),\n     ('EDIT', ['COPY', 'PASTE', ('FILL', ['DOWN', 'SERIES'])])]\n\n    Here we used the `apply_depth_first` function to apply a `lambda` function\n    to each entry to compute the upper-case value corresponding to each node/key.\n\n\n    `as_dict`\n    ---------\n\n    To make traversing the structure easier, the output may be expressed as a\n    nested `OrderedDict` structure.  For instance, let's apply the upper-case\n    transformation from above, but this time with `as_dict=True`:\n\n    >>> result = apply_depth_first(menu_actions, as_dict=True, \\\n    ...                            func=lambda node, parents, nodes: node.upper())\n\n    >>> type(result)\n    <class 'collections.OrderedDict'>\n\n    Here we see that the result is an ordered dictionary.  Moreover, we can\n    look up the transformed `\"File\"` entry based on the original key/node\n    value.  Since an entry may contain children, each entry is wrapped as a\n    `namedtuple` with `item` and `children` attributes.\n\n    >>> type(result['File'])\n    <class 'nested_structures.Node'>\n    >>> result['File'].item\n    'FILE'\n    >>> type(result['File'].children)\n    <class 'collections.OrderedDict'>\n\n    If an entry has children, the `children` attribute is an `OrderedDict`.\n    Otherwise, the `children` is set to `None`.\n\n    Given the information from above, we can look up the `\"Load\"` child entry\n    of the `\"File\"` entry.\n\n    >>> result['File'].children['Load']\n    Node(item='LOAD', children=None)\n\n    Similarly, we can look up the `\"Save and quit\"` child entry of the `\"Quit\"`\n    entry.\n\n    >>> result['File'].children['Quit'].children['Save and quit']\n    Node(item='SAVE AND QUIT', children=None)\n\n    Note that this function *(i.e., `apply_depth_first`)* could be used to,\n    e.g., create a menu GUI item for each entry in the structure.  This would\n    decouple the description of the layout from the GUI framework used."
  },
  {
    "code": "def chunk_size(self, value):\n        if value is not None and value > 0 and value % self._CHUNK_SIZE_MULTIPLE != 0:\n            raise ValueError(\n                \"Chunk size must be a multiple of %d.\" % (self._CHUNK_SIZE_MULTIPLE,)\n            )\n        self._chunk_size = value",
    "docstring": "Set the blob's default chunk size.\n\n        :type value: int\n        :param value: (Optional) The current blob's chunk size, if it is set.\n\n        :raises: :class:`ValueError` if ``value`` is not ``None`` and is not a\n                 multiple of 256 KB."
  },
  {
    "code": "def main():\n    \"Send some test strings\"\n    actions =\n    SendKeys(actions, pause = .1)\n    keys = parse_keys(actions)\n    for k in keys:\n        print(k)\n        k.Run()\n        time.sleep(.1)\n    test_strings = [\n        \"\\n\"\n        \"(aa)some text\\n\",\n        \"(a)some{ }text\\n\",\n        \"(b)some{{}text\\n\",\n        \"(c)some{+}text\\n\",\n        \"(d)so%me{ab 4}text\",\n        \"(e)so%me{LEFT 4}text\",\n        \"(f)so%me{ENTER 4}text\",\n        \"(g)so%me{^aa 4}text\",\n        \"(h)some +(asdf)text\",\n        \"(i)some %^+(asdf)text\",\n        \"(j)some %^+a text+\",\n        \"(k)some %^+a tex+{&}\",\n        \"(l)some %^+a tex+(dsf)\",\n        \"\",\n        ]\n    for s in test_strings:\n        print(repr(s))\n        keys = parse_keys(s, with_newlines = True)\n        print(keys)\n        for k in keys:\n            k.Run()\n            time.sleep(.1)\n        print()",
    "docstring": "Send some test strings"
  },
  {
    "code": "def prepend(self, key, val, time=0, min_compress_len=0):\n        return self._set(\"prepend\", key, val, time, min_compress_len)",
    "docstring": "Prepend the value to the beginning of the existing key's value.\n\n        Only stores in memcache if key already exists.\n        Also see L{append}.\n\n        @return: Nonzero on success.\n        @rtype: int"
  },
  {
    "code": "def addsshkey(self, title, key):\n        data = {'title': title, 'key': key}\n        request = requests.post(\n            self.keys_url, headers=self.headers, data=data,\n            verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)\n        if request.status_code == 201:\n            return True\n        else:\n            return False",
    "docstring": "Add a new ssh key for the current user\n\n        :param title: title of the new key\n        :param key: the key itself\n        :return: true if added, false if it didn't add it (it could be because the name or key already exists)"
  },
  {
    "code": "def deploy(self, id_networkv4):\n        data = dict()\n        uri = 'api/networkv4/%s/equipments/' % id_networkv4\n        return super(ApiNetworkIPv4, self).post(uri, data=data)",
    "docstring": "Deploy network in equipments and set column 'active = 1' in tables redeipv4\n\n        :param id_networkv4: ID for NetworkIPv4\n\n        :return: Equipments configuration output"
  },
  {
    "code": "def read_local_manifest(output_path):\n    local_manifest_path = get_local_manifest_path(output_path)\n    try:\n        with open(local_manifest_path, 'r') as f:\n            manifest = dict(get_files_from_textfile(f))\n            logging.debug('Retrieving %s elements from manifest', len(manifest))\n            return manifest\n    except IOError:\n        logging.debug('No local manifest at %s', local_manifest_path)\n        return {}",
    "docstring": "Return the contents of the local manifest, as a dictionary."
  },
  {
    "code": "def delete_shell(self, pid):\n        try:\n            os.kill(pid, signal.SIGHUP)\n        except OSError:\n            pass\n        num_tries = 30\n        while num_tries > 0:\n            try:\n                if os.waitpid(pid, os.WNOHANG)[0] != 0:\n                    break\n            except OSError:\n                break\n            sleep(0.1)\n            num_tries -= 1\n        if num_tries == 0:\n            try:\n                os.kill(pid, signal.SIGKILL)\n                os.waitpid(pid, 0)\n            except OSError:\n                pass",
    "docstring": "This function will kill the shell on a tab, trying to send\n        a sigterm and if it doesn't work, a sigkill. Between these two\n        signals, we have a timeout of 3 seconds, so is recommended to\n        call this in another thread. This doesn't change any thing in\n        UI, so you can use python's start_new_thread."
  },
  {
    "code": "def avail_images(conn=None, call=None):\n    if call == 'action':\n        raise SaltCloudSystemExit(\n            'The avail_images function must be called with '\n            '-f or --function, or with the --list-images option'\n        )\n    if not conn:\n        conn = get_conn()\n    ret = {}\n    for item in conn.list_os_images():\n        ret[item.name] = object_to_dict(item)\n    for item in conn.list_vm_images():\n        ret[item.name] = object_to_dict(item)\n    return ret",
    "docstring": "List available images for Azure"
  },
  {
    "code": "def register_functions(lib, ignore_errors):\n    def register(item):\n        return register_function(lib, item, ignore_errors)\n    for f in functionList:\n        register(f)",
    "docstring": "Register function prototypes with a libclang library instance.\n\n    This must be called as part of library instantiation so Python knows how\n    to call out to the shared library."
  },
  {
    "code": "def collection_choices():\n    from invenio_collections.models import Collection\n    return [(0, _('-None-'))] + [\n        (c.id, c.name) for c in Collection.query.all()\n    ]",
    "docstring": "Return collection choices."
  },
  {
    "code": "def iterable_source(iterable, target):\n    it = iter(iterable)\n    for item in it:\n        try:\n            target.send(item)\n        except StopIteration:\n            return prepend(item, it)\n    return empty_iter()",
    "docstring": "Convert an iterable into a stream of events.\n\n    Args:\n        iterable: A series of items which will be sent to the target one by one.\n        target: The target coroutine or sink.\n\n    Returns:\n        An iterator over any remaining items."
  },
  {
    "code": "def nodes_ali(c_obj):\n    ali_nodes = []\n    try:\n        ali_nodes = c_obj.list_nodes()\n    except BaseHTTPError as e:\n        abort_err(\"\\r HTTP Error with AliCloud: {}\".format(e))\n    ali_nodes = adj_nodes_ali(ali_nodes)\n    return ali_nodes",
    "docstring": "Get node objects from AliCloud."
  },
  {
    "code": "def get_client(self, client_id):\n        self.assert_has_permission('clients.read')\n        uri = self.uri + '/oauth/clients/' + client_id\n        headers = self.get_authorization_headers()\n        response = requests.get(uri, headers=headers)\n        if response.status_code == 200:\n            return response.json()\n        else:\n            return",
    "docstring": "Returns details about a specific client by the client_id."
  },
  {
    "code": "def destroy(self):\n        super(Syndic, self).destroy()\n        if hasattr(self, 'local'):\n            del self.local\n        if hasattr(self, 'forward_events'):\n            self.forward_events.stop()",
    "docstring": "Tear down the syndic minion"
  },
  {
    "code": "def C(w, Xs):\n    n = len(Xs)\n    P = projection_matrix(w)\n    Ys = [np.dot(P, X) for X in Xs]\n    A = calc_A(Ys)\n    A_hat = calc_A_hat(A, skew_matrix(w))\n    return np.dot(A_hat, sum(np.dot(Y, Y) * Y for Y in Ys)) / np.trace(np.dot(A_hat, A))",
    "docstring": "Calculate the cylinder center given the cylinder direction and \n    a list of data points."
  },
  {
    "code": "def define_mask_borders(image2d, sought_value, nadditional=0):\n    naxis2, naxis1 = image2d.shape\n    mask2d = np.zeros((naxis2, naxis1), dtype=bool)\n    borders = []\n    for i in range(naxis2):\n        jborder_min, jborder_max = find_pix_borders(\n            image2d[i, :],\n            sought_value=sought_value\n        )\n        borders.append((jborder_min, jborder_max))\n        if (jborder_min, jborder_max) != (-1, naxis1):\n            if jborder_min != -1:\n                j1 = 0\n                j2 = jborder_min + nadditional + 1\n                mask2d[i, j1:j2] = True\n            if jborder_max != naxis1:\n                j1 = jborder_max - nadditional\n                j2 = naxis1\n                mask2d[i, j1:j2] = True\n    return mask2d, borders",
    "docstring": "Generate mask avoiding undesired values at the borders.\n\n    Set to True image borders with values equal to 'sought_value'\n\n    Parameters\n    ----------\n    image2d : numpy array\n        Initial 2D image.\n    sought_value : int, float, bool\n        Pixel value that indicates missing data in the spectrum.\n    nadditional : int\n        Number of additional pixels to be masked at each border.\n\n    Returns\n    -------\n    mask2d : numpy array\n        2D mask.\n    borders : list of tuples\n        List of tuples (jmin, jmax) with the border limits (in array\n        coordinates) found by find_pix_borders."
  },
  {
    "code": "def hz2cents(freq_hz, base_frequency=10.0):\n    freq_cent = np.zeros(freq_hz.shape[0])\n    freq_nonz_ind = np.flatnonzero(freq_hz)\n    normalized_frequency = np.abs(freq_hz[freq_nonz_ind])/base_frequency\n    freq_cent[freq_nonz_ind] = 1200*np.log2(normalized_frequency)\n    return freq_cent",
    "docstring": "Convert an array of frequency values in Hz to cents.\n    0 values are left in place.\n\n    Parameters\n    ----------\n    freq_hz : np.ndarray\n        Array of frequencies in Hz.\n    base_frequency : float\n        Base frequency for conversion.\n        (Default value = 10.0)\n\n    Returns\n    -------\n    cent : np.ndarray\n        Array of frequencies in cents, relative to base_frequency"
  },
  {
    "code": "def decompose(self):\n        self.extract()\n        if len(self.contents) == 0:\n            return\n        current = self.contents[0]\n        while current is not None:\n            next = current.next\n            if isinstance(current, Tag):\n                del current.contents[:]\n            current.parent = None\n            current.previous = None\n            current.previousSibling = None\n            current.next = None\n            current.nextSibling = None\n            current = next",
    "docstring": "Recursively destroys the contents of this tree."
  },
  {
    "code": "def requires(*params):\n    def requires(f, self, *args, **kwargs):\n        missing = filter(lambda x: kwargs.get(x) is None, params)\n        if missing:\n            msgs = \", \".join([PARAMETERS[x]['msg'] for x in missing])\n            raise ValueError(\"Missing the following parameters: %s\" % msgs)\n        return f(self, *args, **kwargs)\n    return decorator(requires)",
    "docstring": "Raise ValueError if any ``params`` are omitted from the decorated kwargs.\n\n    None values are considered omissions.\n\n    Example usage on an AWS() method:\n\n        @requires('zone', 'security_groups')\n        def my_aws_method(self, custom_args, **kwargs):\n            # We'll only get here if 'kwargs' contained non-None values for\n            # both 'zone' and 'security_groups'."
  },
  {
    "code": "def set_scope(self, value):\n        if self.default_command:\n            self.default_command += ' ' + value\n        else:\n            self.default_command += value\n        return value",
    "docstring": "narrows the scopes the commands"
  },
  {
    "code": "def _parse(self, text):\n        text = str(text).strip()\n        if not text.startswith(DELIMITER):\n            return {}, text\n        try:\n            _, fm, content = BOUNDARY.split(text, 2)\n        except ValueError:\n            return {}, text\n        metadata = yaml.load(fm, Loader=self.loader_class)\n        metadata = metadata if (isinstance(metadata, dict)) else {}\n        return metadata, content",
    "docstring": "Parse text with frontmatter, return metadata and content.\n        If frontmatter is not found, returns an empty metadata dictionary and original text content."
  },
  {
    "code": "def from_translation_key(\n            cls,\n            translation_key,\n            translations,\n            overlapping_reads,\n            ref_reads,\n            alt_reads,\n            alt_reads_supporting_protein_sequence,\n            transcripts_overlapping_variant,\n            transcripts_supporting_protein_sequence,\n            gene):\n        return cls(\n            amino_acids=translation_key.amino_acids,\n            variant_aa_interval_start=translation_key.variant_aa_interval_start,\n            variant_aa_interval_end=translation_key.variant_aa_interval_end,\n            ends_with_stop_codon=translation_key.ends_with_stop_codon,\n            frameshift=translation_key.frameshift,\n            translations=translations,\n            overlapping_reads=overlapping_reads,\n            ref_reads=ref_reads,\n            alt_reads=alt_reads,\n            alt_reads_supporting_protein_sequence=(\n                alt_reads_supporting_protein_sequence),\n            transcripts_overlapping_variant=transcripts_overlapping_variant,\n            transcripts_supporting_protein_sequence=(\n                transcripts_supporting_protein_sequence),\n            gene=gene)",
    "docstring": "Create a ProteinSequence object from a TranslationKey, along with\n        all the extra fields a ProteinSequence requires."
  },
  {
    "code": "def create_entity_type(self,\n                           parent,\n                           entity_type,\n                           language_code=None,\n                           retry=google.api_core.gapic_v1.method.DEFAULT,\n                           timeout=google.api_core.gapic_v1.method.DEFAULT,\n                           metadata=None):\n        if 'create_entity_type' not in self._inner_api_calls:\n            self._inner_api_calls[\n                'create_entity_type'] = google.api_core.gapic_v1.method.wrap_method(\n                    self.transport.create_entity_type,\n                    default_retry=self._method_configs[\n                        'CreateEntityType'].retry,\n                    default_timeout=self._method_configs['CreateEntityType']\n                    .timeout,\n                    client_info=self._client_info,\n                )\n        request = entity_type_pb2.CreateEntityTypeRequest(\n            parent=parent,\n            entity_type=entity_type,\n            language_code=language_code,\n        )\n        return self._inner_api_calls['create_entity_type'](\n            request, retry=retry, timeout=timeout, metadata=metadata)",
    "docstring": "Creates an entity type in the specified agent.\n\n        Example:\n            >>> import dialogflow_v2\n            >>>\n            >>> client = dialogflow_v2.EntityTypesClient()\n            >>>\n            >>> parent = client.project_agent_path('[PROJECT]')\n            >>>\n            >>> # TODO: Initialize ``entity_type``:\n            >>> entity_type = {}\n            >>>\n            >>> response = client.create_entity_type(parent, entity_type)\n\n        Args:\n            parent (str): Required. The agent to create a entity type for.\n                Format: ``projects/<Project ID>/agent``.\n            entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.EntityType]): Required. The entity type to create.\n                If a dict is provided, it must be of the same form as the protobuf\n                message :class:`~google.cloud.dialogflow_v2.types.EntityType`\n            language_code (str): Optional. The language of entity synonyms defined in ``entity_type``. If not\n                specified, the agent's default language is used.\n                [More than a dozen\n                languages](https://dialogflow.com/docs/reference/language) are supported.\n                Note: languages must be enabled in the agent, before they can be used.\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def parse_filename(filename):\n    _patterns = patterns.get_expressions()\n    result = {}\n    for cmatcher in _patterns:\n        match = cmatcher.match(filename)\n        if match:\n            namedgroups = match.groupdict().keys()\n            result['pattern'] = cmatcher.pattern\n            result['series_name'] = match.group('seriesname')\n            result['season_number'] = _get_season_no(match, namedgroups)\n            result['episode_numbers'] = _get_episodes(match, namedgroups)\n            break\n    else:\n        result = None\n    return result",
    "docstring": "Parse media filename for metadata.\n\n    :param str filename: the name of media file\n    :returns: dict of metadata attributes found in filename\n              or None if no matching expression.\n    :rtype: dict"
  },
  {
    "code": "def puts(s='', newline=True, stream=STDOUT):\n    max_width_ctx = _get_max_width_context()\n    if max_width_ctx:\n        cols, separator = max_width_ctx[-1]\n        s = max_width(s, cols, separator)\n    if newline:\n        s = tsplit(s, NEWLINES)\n        s = map(str, s)\n        indent = ''.join(INDENT_STRINGS)\n        s = (str('\\n' + indent)).join(s)\n    _str = ''.join((\n        ''.join(INDENT_STRINGS),\n        str(s),\n        '\\n' if newline else ''\n    ))\n    stream(_str)",
    "docstring": "Prints given string to stdout."
  },
  {
    "code": "def Find(self, node_type, item_type):\n        if node_type == OtherNodes.DirectionNode:\n            child = self.GetChild(len(self.children) - 1)\n            while child is not None and not isinstance(\n                    child.GetItem(),\n                    item_type):\n                if child.GetItem().__class__.__name__ == item_type.__name__:\n                    return True\n                child = child.GetChild(0)\n        if node_type == OtherNodes.ExpressionNode:\n            child = self.GetChild(len(self.children) - 2)\n            while child is not None and not isinstance(\n                    child.GetItem(),\n                    item_type):\n                if child.GetItem().__class__.__name__ == item_type.__name__:\n                    return True\n                child = child.GetChild(0)",
    "docstring": "method for finding specific types of notation from nodes.\n        will currently return the first one it encounters because this method's only really intended\n        for some types of notation for which the exact value doesn't really\n        matter.\n\n\n        :param node_type: the type of node to look under\n\n        :param item_type: the type of item (notation) being searched for\n\n        :return: first item_type object encountered"
  },
  {
    "code": "def get_name(self):\n        if hasattr(self, 'service_description'):\n            return self.service_description\n        if hasattr(self, 'name'):\n            return self.name\n        return 'SERVICE-DESCRIPTION-MISSING'",
    "docstring": "Accessor to service_description attribute or name if first not defined\n\n        :return: service name\n        :rtype: str"
  },
  {
    "code": "def read_time_range(cls, *args, **kwargs):\n        criteria = list(args)\n        start = kwargs.get('start_timestamp')\n        end = kwargs.get('end_timestamp')\n        if start is not None:\n            criteria.append(cls.time_order <= -start)\n        if end is not None:\n            criteria.append(cls.time_order >= -end)\n        return cls.read(*criteria)",
    "docstring": "Get all timezones set within a given time. Uses time_dsc_index\n\n        SELECT *\n        FROM <table>\n        WHERE time_order <= -<start_timestamp>\n        AND time_order >= -<end_timestamp>\n\n        :param args: SQLAlchemy filter criteria, (e.g., uid == uid, type == 1)\n        :param kwargs: start_timestamp and end_timestamp are the only kwargs, they specify the range (inclusive)\n        :return: model generator"
  },
  {
    "code": "def add_channel(channel: EFBChannel):\n    global master, slaves\n    if isinstance(channel, EFBChannel):\n        if channel.channel_type == ChannelType.Slave:\n            slaves[channel.channel_id] = channel\n        else:\n            master = channel\n    else:\n        raise TypeError(\"Channel instance is expected\")",
    "docstring": "Register the channel with the coordinator.\n\n    Args:\n        channel (EFBChannel): Channel to register"
  },
  {
    "code": "def visit_Stmt(self, node):\n        save_defs, self.defs = self.defs or list(), list()\n        self.generic_visit(node)\n        new_defs, self.defs = self.defs, save_defs\n        return new_defs + [node]",
    "docstring": "Add new variable definition before the Statement."
  },
  {
    "code": "def was_run_code(self, get_all=True):\n        if self.stored is None:\n            return \"\"\n        else:\n            if get_all:\n                self.stored = [\"\\n\".join(self.stored)]\n            return self.stored[-1]",
    "docstring": "Get all the code that was run."
  },
  {
    "code": "def analyze(self, text):\n        logger.debug('Sending %r to LUIS app %s', text, self._url)\n        r = requests.get(self._url, {'q': text})\n        logger.debug('Request sent to LUIS URL: %s', r.url)\n        logger.debug(\n            'LUIS returned status %s with text: %s', r.status_code, r.text)\n        r.raise_for_status()\n        json_response = r.json()\n        result = LuisResult._from_json(json_response)\n        logger.debug('Returning %s', result)\n        return result",
    "docstring": "Sends text to LUIS for analysis.\n\n        Returns a LuisResult."
  },
  {
    "code": "def find_by_id(self, tag, params={}, **options): \n        path = \"/tags/%s\" % (tag)\n        return self.client.get(path, params, **options)",
    "docstring": "Returns the complete tag record for a single tag.\n\n        Parameters\n        ----------\n        tag : {Id} The tag to get.\n        [params] : {Object} Parameters for the request"
  },
  {
    "code": "def create_bucket(self, bucket_name, headers=None,\n                      location=Location.DEFAULT, policy=None):\n        check_lowercase_bucketname(bucket_name)\n        if policy:\n            if headers:\n                headers[self.provider.acl_header] = policy\n            else:\n                headers = {self.provider.acl_header : policy}\n        if location == Location.DEFAULT:\n            data = ''\n        else:\n            data = '<CreateBucketConstraint><LocationConstraint>' + \\\n                    location + '</LocationConstraint></CreateBucketConstraint>'\n        response = self.make_request('PUT', bucket_name, headers=headers,\n                data=data)\n        body = response.read()\n        if response.status == 409:\n            raise self.provider.storage_create_error(\n                response.status, response.reason, body)\n        if response.status == 200:\n            return self.bucket_class(self, bucket_name)\n        else:\n            raise self.provider.storage_response_error(\n                response.status, response.reason, body)",
    "docstring": "Creates a new located bucket. By default it's in the USA. You can pass\n        Location.EU to create an European bucket.\n\n        :type bucket_name: string\n        :param bucket_name: The name of the new bucket\n        \n        :type headers: dict\n        :param headers: Additional headers to pass along with the request to AWS.\n\n        :type location: :class:`boto.s3.connection.Location`\n        :param location: The location of the new bucket\n        \n        :type policy: :class:`boto.s3.acl.CannedACLStrings`\n        :param policy: A canned ACL policy that will be applied to the\n            new key in S3."
  },
  {
    "code": "def get_snapshot(name, config_path=_DEFAULT_CONFIG_PATH, with_packages=False):\n    _validate_config(config_path)\n    sources = list()\n    cmd = ['snapshot', 'show', '-config={}'.format(config_path),\n           '-with-packages={}'.format(str(with_packages).lower()),\n           name]\n    cmd_ret = _cmd_run(cmd)\n    ret = _parse_show_output(cmd_ret=cmd_ret)\n    if ret:\n        log.debug('Found shapshot: %s', name)\n    else:\n        log.debug('Unable to find snapshot: %s', name)\n    return ret",
    "docstring": "Get detailed information about a snapshot.\n\n    :param str name: The name of the snapshot given during snapshot creation.\n    :param str config_path: The path to the configuration file for the aptly instance.\n    :param bool with_packages: Return a list of packages in the snapshot.\n\n    :return: A dictionary containing information about the snapshot.\n    :rtype: dict\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' aptly.get_snapshot name=\"test-repo\""
  },
  {
    "code": "def line(\n    xo: int, yo: int, xd: int, yd: int, py_callback: Callable[[int, int], bool]\n) -> bool:\n    for x, y in line_iter(xo, yo, xd, yd):\n        if not py_callback(x, y):\n            break\n    else:\n        return True\n    return False",
    "docstring": "Iterate over a line using a callback function.\n\n    Your callback function will take x and y parameters and return True to\n    continue iteration or False to stop iteration and return.\n\n    This function includes both the start and end points.\n\n    Args:\n        xo (int): X starting point.\n        yo (int): Y starting point.\n        xd (int): X destination point.\n        yd (int): Y destination point.\n        py_callback (Callable[[int, int], bool]):\n            A callback which takes x and y parameters and returns bool.\n\n    Returns:\n        bool: False if the callback cancels the line interation by\n              returning False or None, otherwise True.\n\n    .. deprecated:: 2.0\n       Use `line_iter` instead."
  },
  {
    "code": "def cross_validation(scheme_class, num_examples, num_folds, strict=True,\n                     **kwargs):\n    if strict and num_examples % num_folds != 0:\n        raise ValueError((\"{} examples are not divisible in {} evenly-sized \" +\n                          \"folds. To allow this, have a look at the \" +\n                          \"`strict` argument.\").format(num_examples,\n                                                       num_folds))\n    for i in xrange(num_folds):\n        begin = num_examples * i // num_folds\n        end = num_examples * (i+1) // num_folds\n        train = scheme_class(list(chain(xrange(0, begin),\n                                        xrange(end, num_examples))),\n                             **kwargs)\n        valid = scheme_class(xrange(begin, end), **kwargs)\n        if strict:\n            yield (train, valid)\n        else:\n            yield (train, valid, end - begin)",
    "docstring": "Return pairs of schemes to be used for cross-validation.\n\n    Parameters\n    ----------\n    scheme_class : subclass of :class:`IndexScheme` or :class:`BatchScheme`\n        The type of the returned schemes. The constructor is called with an\n        iterator and `**kwargs` as arguments.\n    num_examples : int\n        The number of examples in the datastream.\n    num_folds : int\n        The number of folds to return.\n    strict : bool, optional\n        If `True`, enforce that `num_examples` is divisible by `num_folds`\n        and so, that all validation sets have the same size. If `False`,\n        the size of the validation set is returned along the iteration\n        schemes. Defaults to `True`.\n\n    Yields\n    ------\n    fold : tuple\n        The generator returns `num_folds` tuples. The first two elements of\n        the tuple are the training and validation iteration schemes. If\n        `strict` is set to `False`, the tuple has a third element\n        corresponding to the size of the validation set."
  },
  {
    "code": "def GetRootKey(self):\n    root_registry_key = virtual.VirtualWinRegistryKey('')\n    for mapped_key in self._MAPPED_KEYS:\n      key_path_segments = key_paths.SplitKeyPath(mapped_key)\n      if not key_path_segments:\n        continue\n      registry_key = root_registry_key\n      for name in key_path_segments[:-1]:\n        sub_registry_key = registry_key.GetSubkeyByName(name)\n        if not sub_registry_key:\n          sub_registry_key = virtual.VirtualWinRegistryKey(name)\n          registry_key.AddSubkey(sub_registry_key)\n        registry_key = sub_registry_key\n      sub_registry_key = registry_key.GetSubkeyByName(key_path_segments[-1])\n      if (not sub_registry_key and\n          isinstance(registry_key, virtual.VirtualWinRegistryKey)):\n        sub_registry_key = virtual.VirtualWinRegistryKey(\n            key_path_segments[-1], registry=self)\n        registry_key.AddSubkey(sub_registry_key)\n    return root_registry_key",
    "docstring": "Retrieves the Windows Registry root key.\n\n    Returns:\n      WinRegistryKey: Windows Registry root key.\n\n    Raises:\n      RuntimeError: if there are multiple matching mappings and\n          the correct mapping cannot be resolved."
  },
  {
    "code": "def lookupEncoding(encoding):\n    if isinstance(encoding, binary_type):\n        try:\n            encoding = encoding.decode(\"ascii\")\n        except UnicodeDecodeError:\n            return None\n    if encoding is not None:\n        try:\n            return webencodings.lookup(encoding)\n        except AttributeError:\n            return None\n    else:\n        return None",
    "docstring": "Return the python codec name corresponding to an encoding or None if the\n    string doesn't correspond to a valid encoding."
  },
  {
    "code": "def GetNewEventId(self, event_time=None):\n    if event_time is None:\n      event_time = int(time.time() * 1e6)\n    return \"%s:%s:%s\" % (event_time, socket.gethostname(), os.getpid())",
    "docstring": "Return a unique Event ID string."
  },
  {
    "code": "def create_server(self, server_name, *args, **kwargs):\n        server = ServerConnection(name=server_name, reactor=self)\n        if args or kwargs:\n            server.set_connect_info(*args, **kwargs)\n        for verb, infos in self._event_handlers.items():\n            for info in infos:\n                server.register_event(info['direction'], verb, info['handler'],\n                                      priority=info['priority'])\n        self.servers[server_name] = server\n        return server",
    "docstring": "Create an IRC server connection slot.\n\n        The server will actually be connected to when\n        :meth:`girc.client.ServerConnection.connect` is called later.\n\n        Args:\n            server_name (str): Name of the server, to be used for functions and accessing the\n                server later through the reactor.\n\n        Returns:\n            server (girc.client.ServerConnection): A not-yet-connected server."
  },
  {
    "code": "def round(arg, digits=None):\n    op = ops.Round(arg, digits)\n    return op.to_expr()",
    "docstring": "Round values either to integer or indicated number of decimal places.\n\n    Returns\n    -------\n    rounded : type depending on digits argument\n      digits None or 0\n        decimal types: decimal\n        other numeric types: bigint\n      digits nonzero\n        decimal types: decimal\n        other numeric types: double"
  },
  {
    "code": "def publish_command_start(self, command, database_name,\n                              request_id, connection_id, op_id=None):\n        if op_id is None:\n            op_id = request_id\n        event = CommandStartedEvent(\n            command, database_name, request_id, connection_id, op_id)\n        for subscriber in self.__command_listeners:\n            try:\n                subscriber.started(event)\n            except Exception:\n                _handle_exception()",
    "docstring": "Publish a CommandStartedEvent to all command listeners.\n\n        :Parameters:\n          - `command`: The command document.\n          - `database_name`: The name of the database this command was run\n            against.\n          - `request_id`: The request id for this operation.\n          - `connection_id`: The address (host, port) of the server this\n            command was sent to.\n          - `op_id`: The (optional) operation id for this operation."
  },
  {
    "code": "def _has_x(self, kwargs):\n        return (('x' in kwargs) or (self._element_x in kwargs) or\n                (self._type == 3 and self._element_1mx in kwargs))",
    "docstring": "Returns True if x is explicitly defined in kwargs"
  },
  {
    "code": "def add_section(self, section):\n        section, _, _ = self._validate_value_types(section=section)\n        super(ConfigParser, self).add_section(section)",
    "docstring": "Create a new section in the configuration.  Extends\n        RawConfigParser.add_section by validating if the section name is\n        a string."
  },
  {
    "code": "def get_by(self, name):\n        item = self.controlled_list.get_by(name)\n        if item:\n            return TodoElementUX(parent=self, controlled_element=item)",
    "docstring": "find a todo list element by name"
  },
  {
    "code": "def save_json(obj, filename, **kwargs):\n    with open(filename, 'w', encoding='utf-8') as f:\n        json.dump(obj, f, **kwargs)",
    "docstring": "Save an object as a JSON file.\n\n    Args:\n        obj: The object to save. Must be JSON-serializable.\n        filename: Path to the output file.\n        **kwargs: Additional arguments to `json.dump`."
  },
  {
    "code": "def as_text(str_or_bytes, encoding='utf-8', errors='strict'):\n    if isinstance(str_or_bytes, text):\n        return str_or_bytes\n    return str_or_bytes.decode(encoding, errors)",
    "docstring": "Return input string as a text string.\n\n    Should work for input string that's unicode or bytes,\n    given proper encoding.\n\n    >>> print(as_text(b'foo'))\n    foo\n    >>> b'foo'.decode('utf-8') == u'foo'\n    True"
  },
  {
    "code": "def create_basic_op_node(op_name, node, kwargs):\n    name, input_nodes, _ = get_inputs(node, kwargs)\n    node = onnx.helper.make_node(\n        op_name,\n        input_nodes,\n        [name],\n        name=name\n    )\n    return [node]",
    "docstring": "Helper function to create a basic operator\n    node that doesn't contain op specific attrs"
  },
  {
    "code": "def _build_credentials(self, nexus_switches):\n        credentials = {}\n        for switch_ip, attrs in nexus_switches.items():\n            credentials[switch_ip] = (\n                attrs[const.USERNAME], attrs[const.PASSWORD],\n                attrs[const.HTTPS_VERIFY], attrs[const.HTTPS_CERT],\n                None)\n            if not attrs[const.HTTPS_VERIFY]:\n                LOG.warning(\"HTTPS Certificate verification is \"\n                            \"disabled. Your connection to Nexus \"\n                            \"Switch %(ip)s is insecure.\",\n                            {'ip': switch_ip})\n        return credentials",
    "docstring": "Build credential table for Rest API Client.\n\n        :param nexus_switches: switch config\n        :returns credentials: switch credentials list"
  },
  {
    "code": "def global_include(self, pattern):\n        if self.allfiles is None:\n            self.findall()\n        match = translate_pattern(os.path.join('**', pattern))\n        found = [f for f in self.allfiles if match.match(f)]\n        self.extend(found)\n        return bool(found)",
    "docstring": "Include all files anywhere in the current directory that match the\n        pattern. This is very inefficient on large file trees."
  },
  {
    "code": "def _aux_type(self, i):\n        aux_type = ctypes.c_int()\n        check_call(_LIB.MXNDArrayGetAuxType(self.handle, i, ctypes.byref(aux_type)))\n        return _DTYPE_MX_TO_NP[aux_type.value]",
    "docstring": "Data-type of the array's ith aux data.\n\n        Returns\n        -------\n        numpy.dtype\n            This BaseSparseNDArray's aux data type."
  },
  {
    "code": "def angle2xyz(azi, zen):\n    azi = xu.deg2rad(azi)\n    zen = xu.deg2rad(zen)\n    x = xu.sin(zen) * xu.sin(azi)\n    y = xu.sin(zen) * xu.cos(azi)\n    z = xu.cos(zen)\n    return x, y, z",
    "docstring": "Convert azimuth and zenith to cartesian."
  },
  {
    "code": "def calc_mass_from_fit_and_conv_factor(A, Damping, ConvFactor):\n    T0 = 300\n    mFromA = 2*Boltzmann*T0/(pi*A) * ConvFactor**2 * Damping\n    return mFromA",
    "docstring": "Calculates mass from the A parameter from fitting, the damping from \n    fitting in angular units and the Conversion factor calculated from \n    comparing the ratio of the z signal and first harmonic of z.\n\n    Parameters\n    ----------\n    A : float\n        A factor calculated from fitting\n    Damping : float\n        damping in radians/second calcualted from fitting\n    ConvFactor : float\n        conversion factor between volts and nms\n\n    Returns\n    -------\n    mass : float\n        mass in kgs"
  },
  {
    "code": "def progress_bar(name, maxval, prefix='Converting'):\n    widgets = ['{} {}: '.format(prefix, name), Percentage(), ' ',\n               Bar(marker='=', left='[', right=']'), ' ', ETA()]\n    bar = ProgressBar(widgets=widgets, max_value=maxval, fd=sys.stdout).start()\n    try:\n        yield bar\n    finally:\n        bar.update(maxval)\n        bar.finish()",
    "docstring": "Manages a progress bar for a conversion.\n\n    Parameters\n    ----------\n    name : str\n        Name of the file being converted.\n    maxval : int\n        Total number of steps for the conversion."
  },
  {
    "code": "def set_flowcontrol_receive(self, name, value=None, default=False,\n                                disable=False):\n        return self.set_flowcontrol(name, 'receive', value, default, disable)",
    "docstring": "Configures the interface flowcontrol receive value\n\n        Args:\n            name (string): The interface identifier.  It must be a full\n                interface name (ie Ethernet, not Et)\n\n            value (boolean): True if the interface should enable receiving\n                flow control packets, otherwise False\n\n            default (boolean): Specifies to default the interface flow\n                control receive value\n\n            disable (boolean): Specifies to disable the interface flow\n                control receive value\n\n        Returns:\n            True if the operation succeeds otherwise False is returned"
  },
  {
    "code": "def connect(self, agent='Python'):\n        headers = {'User-Agent': agent}\n        request = urlopen(Request(self.url, headers=headers))\n        try:\n            yield request\n        finally:\n            request.close()",
    "docstring": "Context manager for HTTP Connection state and ensures proper handling\n        of network sockets, sends a GET request.\n\n        Exception is raised at the yield statement.\n\n        :yield request: FileIO<Socket>"
  },
  {
    "code": "def _JsonDecodeDict(self, data):\n    rv = {}\n    for key, value in data.iteritems():\n      if isinstance(key, unicode):\n        key = self._TryStr(key)\n      if isinstance(value, unicode):\n        value = self._TryStr(value)\n      elif isinstance(value, list):\n        value = self._JsonDecodeList(value)\n      rv[key] = value\n    if '__pyringe_type_name__' in data:\n      rv = ProxyObject(rv)\n    return rv",
    "docstring": "Json object decode hook that automatically converts unicode objects."
  },
  {
    "code": "def material_advantage(self, input_color, val_scheme):\n        if self.get_king(input_color).in_check(self) and self.no_moves(input_color):\n            return -100\n        if self.get_king(-input_color).in_check(self) and self.no_moves(-input_color):\n            return 100\n        return sum([val_scheme.val(piece, input_color) for piece in self])",
    "docstring": "Finds the advantage a particular side possesses given a value scheme.\n\n        :type: input_color: Color\n        :type: val_scheme: PieceValues\n        :rtype: double"
  },
  {
    "code": "def _convert_to_array(array_like, dtype):\n        if isinstance(array_like, bytes):\n            return np.frombuffer(array_like, dtype=dtype)\n        return np.asarray(array_like, dtype=dtype)",
    "docstring": "Convert Matrix attributes which are array-like or buffer to array."
  },
  {
    "code": "def on_add_vrf_conf(self, evt):\n        vrf_conf = evt.value\n        route_family = vrf_conf.route_family\n        assert route_family in vrfs.SUPPORTED_VRF_RF\n        vrf_table = self._table_manager.create_and_link_vrf_table(vrf_conf)\n        vrf_conf.add_listener(ConfWithStats.UPDATE_STATS_LOG_ENABLED_EVT,\n                              self.on_stats_config_change)\n        vrf_conf.add_listener(ConfWithStats.UPDATE_STATS_TIME_EVT,\n                              self.on_stats_config_change)\n        vrf_conf.add_listener(VrfConf.VRF_CHG_EVT, self.on_chg_vrf_conf)\n        self._table_manager.import_all_vpn_paths_to_vrf(vrf_table)\n        self._rt_manager.update_local_rt_nlris()\n        self._signal_bus.vrf_added(vrf_conf)",
    "docstring": "Event handler for new VrfConf.\n\n        Creates a VrfTable to store routing information related to new Vrf.\n        Also arranges for related paths to be imported to this VrfTable."
  },
  {
    "code": "async def info(self) -> Optional[JobDef]:\n        info = await self.result_info()\n        if not info:\n            v = await self._redis.get(job_key_prefix + self.job_id, encoding=None)\n            if v:\n                info = unpickle_job(v)\n        if info:\n            info.score = await self._redis.zscore(queue_name, self.job_id)\n        return info",
    "docstring": "All information on a job, including its result if it's available, does not wait for the result."
  },
  {
    "code": "async def add_user(self, username, password=None, display_name=None):\n        if not display_name:\n            display_name = username\n        user_facade = client.UserManagerFacade.from_connection(\n            self.connection())\n        users = [client.AddUser(display_name=display_name,\n                                username=username,\n                                password=password)]\n        results = await user_facade.AddUser(users)\n        secret_key = results.results[0].secret_key\n        return await self.get_user(username, secret_key=secret_key)",
    "docstring": "Add a user to this controller.\n\n        :param str username: Username\n        :param str password: Password\n        :param str display_name: Display name\n        :returns: A :class:`~juju.user.User` instance"
  },
  {
    "code": "def pattern_to_regex(pattern: str) -> str:\n    if pattern and pattern[-1] == \"*\":\n        pattern = pattern[:-1]\n        end = \"\"\n    else:\n        end = \"$\"\n    for metac in META_CHARS:\n        pattern = pattern.replace(metac, \"\\\\\" + metac)\n    return \"^\" + VARS_PT.sub(regex_replacer, pattern) + end",
    "docstring": "convert url patten to regex"
  },
  {
    "code": "def draw_status(self, writer, idx):\n        if self.term.is_a_tty:\n            writer(self.term.hide_cursor())\n            style = self.screen.style\n            writer(self.term.move(self.term.height - 1))\n            if idx == self.last_page:\n                last_end = u'(END)'\n            else:\n                last_end = u'/{0}'.format(self.last_page)\n            txt = (u'Page {idx}{last_end} - '\n                   u'{q} to quit, [keys: {keyset}]'\n                   .format(idx=style.attr_minor(u'{0}'.format(idx)),\n                           last_end=style.attr_major(last_end),\n                           keyset=style.attr_major('kjfb12-='),\n                           q=style.attr_minor(u'q')))\n            writer(self.term.center(txt).rstrip())",
    "docstring": "Conditionally draw status bar when output terminal is a tty.\n\n        :param writer: callable writes to output stream, receiving unicode.\n        :param idx: current page position index.\n        :type idx: int"
  },
  {
    "code": "def _uniform_phi(M):\n        return np.random.uniform(-np.pi, np.pi, M)",
    "docstring": "Generate M random numbers in [-pi, pi)."
  },
  {
    "code": "def pagination_links(paginator_page, show_pages, url_params=None,\n                     first_page_label=None, last_page_label=None,\n                     page_url=''):\n    return {\n        'items': paginator_page,\n        'show_pages': show_pages,\n        'url_params': url_params,\n        'first_page_label': first_page_label,\n        'last_page_label': last_page_label,\n        'page_url': page_url,\n        }",
    "docstring": "Django template tag to display pagination links for a paginated\n    list of items.\n\n    Expects the following variables:\n     * the current :class:`~django.core.paginator.Page` of a\n       :class:`~django.core.paginator.Paginator` object\n     * a dictionary of the pages to be displayed, in the format\n       generated by :meth:`eulcommon.searchutil.pages_to_show`\n     * optional url params to include in pagination link (e.g., search\n       terms when paginating search results)\n     * optional first page label (only used when first page is not in\n       list of pages to be shown)\n     * optional last page label (only used when last page is not in\n       list of pages to be shown)\n     * optional url to use for page links (only needed when the url is\n       different from the current one)\n\n    Example use::\n\n      {% load search_utils %}\n\n      {% pagination_links paged_items show_pages  %}"
  },
  {
    "code": "def Matches(self, registry_key, search_depth):\n    if self._key_path_segments is None:\n      key_path_match = None\n    else:\n      key_path_match = self._CheckKeyPath(registry_key, search_depth)\n      if not key_path_match:\n        return False, key_path_match\n      if search_depth != self._number_of_key_path_segments:\n        return False, key_path_match\n    return True, key_path_match",
    "docstring": "Determines if the Windows Registry key matches the find specification.\n\n    Args:\n      registry_key (WinRegistryKey): Windows Registry key.\n      search_depth (int): number of key path segments to compare.\n\n    Returns:\n      tuple: contains:\n\n        bool: True if the Windows Registry key matches the find specification,\n            False otherwise.\n        bool: True if the key path matches, False if not or None if no key path\n            specified."
  },
  {
    "code": "def check_folders(name):\n    if os.getcwd().endswith('analyses'):\n        correct = input('You are in an analyses folder. This will create '\n                        'another analyses folder inside this one. Do '\n                        'you want to continue? (y/N)')\n        if correct != 'y':\n            return False\n    if not os.path.exists(os.path.join(os.getcwd(), 'analyses')):\n        correct = input('This is the first analysis here. Do '\n                        'you want to continue? (y/N)')\n        if correct != 'y':\n            return False\n    if os.path.exists(os.path.join(os.getcwd(), 'analyses', name)):\n        correct = input('An analysis with this name exists already. Do '\n                        'you want to continue? (y/N)')\n        if correct != 'y':\n            return False\n    return True",
    "docstring": "Only checks and asks questions. Nothing is written to disk."
  },
  {
    "code": "def render_chart_to_file(self, template_name: str, chart: Any, path: str):\n        tpl = self.env.get_template(template_name)\n        html = tpl.render(chart=self.generate_js_link(chart))\n        write_utf8_html_file(path, self._reg_replace(html))",
    "docstring": "Render a chart or page to local html files.\n\n        :param chart: A Chart or Page object\n        :param path: The destination file which the html code write to\n        :param template_name: The name of template file."
  },
  {
    "code": "def _get_sample_generator(samples):\n    if isinstance(samples, Mapping):\n        def samples_generator():\n            for ind in range(samples[list(samples.keys())[0]].shape[0]):\n                yield np.array([samples[s][ind, :] for s in sorted(samples)])\n    elif isinstance(samples, np.ndarray):\n        def samples_generator():\n            for ind in range(samples.shape[0]):\n                yield samples[ind]\n    else:\n        samples_generator = samples\n    return samples_generator",
    "docstring": "Get a sample generator from the given polymorphic input.\n\n    Args:\n        samples (ndarray, dict or generator): either an matrix of shape (d, p, n) with d problems, p parameters and\n            n samples, or a dictionary with for every parameter a matrix with shape (d, n) or, finally,\n            a generator function that yields sample arrays of shape (p, n).\n\n    Returns:\n        generator: a generator that yields a matrix of size (p, n) for every problem in the input."
  },
  {
    "code": "def linear_set_layer(layer_size,\n                     inputs,\n                     context=None,\n                     activation_fn=tf.nn.relu,\n                     dropout=0.0,\n                     name=None):\n  with tf.variable_scope(\n      name, default_name=\"linear_set_layer\", values=[inputs]):\n    outputs = conv1d(inputs, layer_size, 1, activation=None, name=\"set_conv\")\n    if context is not None:\n      if len(context.get_shape().as_list()) == 2:\n        context = tf.expand_dims(context, axis=1)\n      cont_tfm = conv1d(\n          context, layer_size, 1, activation=None, name=\"cont_conv\")\n      outputs += cont_tfm\n    if activation_fn is not None:\n      outputs = activation_fn(outputs)\n    if dropout != 0.0:\n      outputs = tf.nn.dropout(outputs, 1.0 - dropout)\n    return outputs",
    "docstring": "Basic layer type for doing funky things with sets.\n\n  Applies a linear transformation to each element in the input set.\n  If a context is supplied, it is concatenated with the inputs.\n    e.g. One can use global_pool_1d to get a representation of the set which\n    can then be used as the context for the next layer.\n\n  TODO: Add bias add (or control the biases used).\n\n  Args:\n    layer_size: Dimension to transform the input vectors to.\n    inputs: A tensor of shape [batch_size, sequence_length, input_dims]\n      containing the sequences of input vectors.\n    context: A tensor of shape [batch_size, context_dims] containing a global\n      statistic about the set.\n    activation_fn: The activation function to use.\n    dropout: Dropout probability.\n    name: name.\n\n  Returns:\n    Tensor of shape [batch_size, sequence_length, output_dims] containing the\n    sequences of transformed vectors."
  },
  {
    "code": "def _nan_minmax_object(func, fill_value, value, axis=None, **kwargs):\n    valid_count = count(value, axis=axis)\n    filled_value = fillna(value, fill_value)\n    data = getattr(np, func)(filled_value, axis=axis, **kwargs)\n    if not hasattr(data, 'dtype'):\n        data = dtypes.fill_value(value.dtype) if valid_count == 0 else data\n        return np.array(data, dtype=value.dtype)\n    return where_method(data, valid_count != 0)",
    "docstring": "In house nanmin and nanmax for object array"
  },
  {
    "code": "def encode_eternal_jwt_token(self, user, **custom_claims):\n        return self.encode_jwt_token(\n            user,\n            override_access_lifespan=VITAM_AETERNUM,\n            override_refresh_lifespan=VITAM_AETERNUM,\n            **custom_claims\n        )",
    "docstring": "This utility function encodes a jwt token that never expires\n\n        .. note:: This should be used sparingly since the token could become\n                  a security concern if it is ever lost. If you use this\n                  method, you should be sure that your application also\n                  implements a blacklist so that a given token can be blocked\n                  should it be lost or become a security concern"
  },
  {
    "code": "def combine_relevance_tables(relevance_tables):\n    def _combine(a, b):\n        a.relevant |= b.relevant\n        a.p_value = a.p_value.combine(b.p_value, min, 1)\n        return a\n    return reduce(_combine, relevance_tables)",
    "docstring": "Create a combined relevance table out of a list of relevance tables,\n    aggregating the p-values and the relevances.\n\n    :param relevance_tables: A list of relevance tables\n    :type relevance_tables: List[pd.DataFrame]\n    :return: The combined relevance table\n    :rtype: pandas.DataFrame"
  },
  {
    "code": "def build_plans(self):\n        if not self.__build_plans:\n            self.__build_plans = BuildPlans(self.__connection)\n        return self.__build_plans",
    "docstring": "Gets the Build Plans API client.\n\n        Returns:\n            BuildPlans:"
  },
  {
    "code": "def _gst_available():\n    try:\n        import gi\n    except ImportError:\n        return False\n    try:\n        gi.require_version('Gst', '1.0')\n    except (ValueError, AttributeError):\n        return False\n    try:\n        from gi.repository import Gst\n    except ImportError:\n        return False\n    return True",
    "docstring": "Determine whether Gstreamer and the Python GObject bindings are\n    installed."
  },
  {
    "code": "def query_param(self, key, value=None, default=None, as_list=False):\n        parse_result = self.query_params()\n        if value is not None:\n            if isinstance(value, (list, tuple)):\n                value = list(map(to_unicode, value))\n            else:\n                value = to_unicode(value)\n            parse_result[to_unicode(key)] = value\n            return URL._mutate(\n                self, query=unicode_urlencode(parse_result, doseq=True))\n        try:\n            result = parse_result[key]\n        except KeyError:\n            return default\n        if as_list:\n            return result\n        return result[0] if len(result) == 1 else result",
    "docstring": "Return or set a query parameter for the given key\n\n        The value can be a list.\n\n        :param string key: key to look for\n        :param string default: value to return if ``key`` isn't found\n        :param boolean as_list: whether to return the values as a list\n        :param string value: the new query parameter to use"
  },
  {
    "code": "def istring(self, in_string=''):\n        new_string = IString(in_string)\n        new_string.set_std(self.features.get('casemapping'))\n        if not self._casemap_set:\n            self._imaps.append(new_string)\n        return new_string",
    "docstring": "Return a string that uses this server's IRC casemapping.\n\n        This string's equality with other strings, ``lower()``, and ``upper()`` takes this\n        server's casemapping into account. This should be used for things such as nicks and\n        channel names, where comparing strings using the correct casemapping can be very\n        important."
  },
  {
    "code": "def copy_file(self, file_id, dest_folder_id):\n        return self.__request(\"POST\", \"/files/\" + unicode(file_id) + \"/copy\",\n                        data={ \"parent\": {\"id\": unicode(dest_folder_id)} })",
    "docstring": "Copy file to new destination\n\n        Args:\n            file_id (int): ID of the folder.\n\n            dest_folder_id (int): ID of parent folder you are copying to.\n\n        Returns:\n            dict. Response from Box.\n\n        Raises:\n            BoxError: An error response is returned from Box (status_code >= 400).\n\n            BoxError: 409 - Item with the same name already exists.\n            In this case you will need download the file and upload a new version to your destination.\n            (Box currently doesn't have a method to copy a new verison.)\n\n            BoxHttpResponseError: Response from Box is malformed.\n\n            requests.exceptions.*: Any connection related problem."
  },
  {
    "code": "def getBWTRange(self, start, end):\n        startBlockIndex = start >> self.bitPower\n        endBlockIndex = int(math.floor(float(end)/self.binSize))\n        trueStart = startBlockIndex*self.binSize\n        return self.decompressBlocks(startBlockIndex, endBlockIndex)[start-trueStart:end-trueStart]",
    "docstring": "This function masks the complexity of retrieving a chunk of the BWT from the compressed format\n        @param start - the beginning of the range to retrieve\n        @param end - the end of the range in normal python notation (bwt[end] is not part of the return)\n        @return - a range of integers representing the characters in the bwt from start to end"
  },
  {
    "code": "def _centroids(self, verts):\n        r\n        value = sp.zeros([len(verts), 3])\n        for i, i_verts in enumerate(verts):\n            value[i] = np.mean(i_verts, axis=0)\n        return value",
    "docstring": "r'''\n        Function to calculate the centroid as the mean of a set of vertices.\n        Used for pore and throat."
  },
  {
    "code": "def clean(self):\n        super().clean()\n        if (\n            (self.user is None and not self.anonymous_user) or\n            (self.user and self.anonymous_user)\n        ):\n            raise ValidationError(\n                _('A permission should target either a user or an anonymous user'),\n            )",
    "docstring": "Validates the current instance."
  },
  {
    "code": "def debug_variable_node_render(self, context):\n    try:\n        output = self.filter_expression.resolve(context)\n        output = template_localtime(output, use_tz=context.use_tz)\n        output = localize(output, use_l10n=context.use_l10n)\n        output = force_text(output)\n    except Exception as e:\n        if not hasattr(e, 'django_template_source'):\n            e.django_template_source = self.source\n        raise\n    if (context.autoescape and not isinstance(output, SafeData)) or isinstance(output, EscapeData):\n        return escape(output)\n    else:\n        return output",
    "docstring": "Like DebugVariableNode.render, but doesn't catch UnicodeDecodeError."
  },
  {
    "code": "def is_older_than(before, seconds):\n    if isinstance(before, six.string_types):\n        before = parse_strtime(before).replace(tzinfo=None)\n    else:\n        before = before.replace(tzinfo=None)\n    return utcnow() - before > datetime.timedelta(seconds=seconds)",
    "docstring": "Return True if before is older than seconds."
  },
  {
    "code": "def create_store(self):\n        if self.store_class is not None:\n            return self.store_class.load(self.client.webfinger, self)\n        raise NotImplementedError(\"You need to specify PyPump.store_class or override PyPump.create_store method.\")",
    "docstring": "Creates store object"
  },
  {
    "code": "def _add_route(self, method, path, middleware=None):\n        if middleware is not None:\n            self.add(method, path, middleware)\n            return self\n        else:\n            return lambda func: (\n                self.add(method, path, func),\n                func\n            )[1]",
    "docstring": "The implementation of adding a route"
  },
  {
    "code": "def tag_details(tag, nodenames):\n    details = {}\n    details['type'] = tag.name\n    details['ordinal'] = tag_ordinal(tag)\n    if tag_details_sibling_ordinal(tag):\n        details['sibling_ordinal'] = tag_details_sibling_ordinal(tag)\n    if tag_details_asset(tag):\n        details['asset'] = tag_details_asset(tag)\n    object_id_tag = first(raw_parser.object_id(tag, pub_id_type= \"doi\"))\n    if object_id_tag:\n        details['component_doi'] = extract_component_doi(tag, nodenames)\n    return details",
    "docstring": "Used in media and graphics to extract data from their parent tags"
  },
  {
    "code": "def crop_to_sheet(self,sheet_coord_system):\n        \"Crop the slice to the SheetCoordinateSystem's bounds.\"\n        maxrow,maxcol = sheet_coord_system.shape\n        self[0] = max(0,self[0])\n        self[1] = min(maxrow,self[1])\n        self[2] = max(0,self[2])\n        self[3] = min(maxcol,self[3])",
    "docstring": "Crop the slice to the SheetCoordinateSystem's bounds."
  },
  {
    "code": "def authenticate_redirect(self, callback_uri=None,\n                              ask_for=[\"name\", \"email\", \"language\", \"username\"]):\n        callback_uri = callback_uri or request.url\n        args = self._openid_args(callback_uri, ax_attrs=ask_for)\n        return redirect(self._OPENID_ENDPOINT +\n                        (\"&\" if \"?\" in self._OPENID_ENDPOINT else \"?\") +\n                        urllib.urlencode(args))",
    "docstring": "Performs a redirect to the authentication URL for this service.\n\n        After authentication, the service will redirect back to the given\n        callback URI.\n\n        We request the given attributes for the authenticated user by\n        default (name, email, language, and username). If you don't need\n        all those attributes for your app, you can request fewer with\n        the |ask_for| keyword argument."
  },
  {
    "code": "def initialize(self):\n        self.main_pid = os.getpid()\n        self.processes.extend(self.init_service_processes())\n        self.processes.extend(self.init_tornado_workers())",
    "docstring": "Initialize instance attributes. You can override this method in\n        the subclasses."
  },
  {
    "code": "def _make_axes_dict(self, axes):\n        if type(axes) is dict:\n            axdict = axes\n        elif type(axes) is Axis:\n            ax = axes\n            axdict = {ax.axis_type: ax}\n        elif axes is None:\n            axdict = {'empty': None}\n        else:\n            raise ValueError('axes needs to be Axis object or dictionary of Axis object')\n        return axdict",
    "docstring": "Makes an axes dictionary.\n\n        .. note::\n\n            In case the input is ``None``, the dictionary :code:`{'empty': None}`\n            is returned.\n\n        **Function-call argument** \\n\n\n        :param axes:    axes input\n        :type axes:     dict or single instance of\n                        :class:`~climlab.domain.axis.Axis` object or ``None``\n        :raises: :exc:`ValueError`  if input is not an instance of Axis class\n                                    or a dictionary of Axis objetcs\n        :returns: dictionary of input axes\n        :rtype: dict"
  },
  {
    "code": "def expand_filename_pattern(pattern, base_dir):\n    pattern = os.path.normpath(os.path.join(base_dir, pattern))\n    pattern = os.path.expandvars(os.path.expanduser(pattern))\n    fileList = glob.glob(pattern)\n    return fileList",
    "docstring": "Expand a file name pattern containing wildcards, environment variables etc.\n\n    @param pattern: The pattern string to expand.\n    @param base_dir: The directory where relative paths are based on.\n    @return: A list of file names (possibly empty)."
  },
  {
    "code": "def put(self, url_path, data):\n        request_url = \"%s%s\" % (self._url, url_path)\n        data = ElementTree.tostring(data)\n        response = self.session.put(request_url, data)\n        if response.status_code == 201 and self.verbose:\n            print \"PUT %s: Success.\" % request_url\n        elif response.status_code >= 400:\n            error_handler(JSSPutError, response)",
    "docstring": "Update an existing object on the JSS.\n\n        In general, it is better to use a higher level interface for\n        updating objects, namely, making changes to a JSSObject subclass\n        and then using its save method.\n\n        Args:\n            url_path: String API endpoint path to PUT, with ID (e.g.\n                \"/packages/id/<object ID>\")\n            data: xml.etree.ElementTree.Element with valid XML for the\n                desired obj_class.\n        Raises:\n            JSSPutError if provided url_path has a >= 400 response."
  },
  {
    "code": "def addToTimeInv(self,*params):\n        for param in params:\n            if param not in self.time_inv:\n                self.time_inv.append(param)",
    "docstring": "Adds any number of parameters to time_inv for this instance.\n\n        Parameters\n        ----------\n        params : string\n            Any number of strings naming attributes to be added to time_inv\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def trace_module(no_print=True):\n    with pexdoc.ExDocCxt() as exdoc_obj:\n        try:\n            docs.support.my_module.func(\"John\")\n            obj = docs.support.my_module.MyClass()\n            obj.value = 5\n            obj.value\n        except:\n            raise RuntimeError(\"Tracing did not complete successfully\")\n    if not no_print:\n        module_prefix = \"docs.support.my_module.\"\n        callable_names = [\"func\", \"MyClass.value\"]\n        for callable_name in callable_names:\n            callable_name = module_prefix + callable_name\n            print(\"\\nCallable: {0}\".format(callable_name))\n            print(exdoc_obj.get_sphinx_doc(callable_name, width=70))\n            print(\"\\n\")\n    return copy.copy(exdoc_obj)",
    "docstring": "Trace my_module_original exceptions."
  },
  {
    "code": "def changePermissionsRecursively(path, uid, gid):\n    os.chown(path, uid, gid)\n    for item in os.listdir(path):\n        itempath = os.path.join(path, item)\n        if os.path.isfile(itempath):\n            try:\n                os.chown(itempath, uid, gid)\n            except Exception as e:\n                pass\n            os.chmod(itempath, 600)\n        elif os.path.isdir(itempath):\n            try:\n                os.chown(itempath, uid, gid)\n            except Exception as e:\n                pass\n            os.chmod(itempath, 6600)\n            changePermissionsRecursively(itempath, uid, gid)",
    "docstring": "Function to recursively change the user id and group id.\n\n    It sets 700 permissions."
  },
  {
    "code": "def publish_avatar_set(self, avatar_set):\n        id_ = avatar_set.png_id\n        done = False\n        with (yield from self._publish_lock):\n            if (yield from self._pep.available()):\n                yield from self._pep.publish(\n                    namespaces.xep0084_data,\n                    avatar_xso.Data(avatar_set.image_bytes),\n                    id_=id_\n                )\n                yield from self._pep.publish(\n                    namespaces.xep0084_metadata,\n                    avatar_set.metadata,\n                    id_=id_\n                )\n                done = True\n            if self._synchronize_vcard:\n                my_vcard = yield from self._vcard.get_vcard()\n                my_vcard.set_photo_data(\"image/png\",\n                                        avatar_set.image_bytes)\n                self._vcard_id = avatar_set.png_id\n                yield from self._vcard.set_vcard(my_vcard)\n                self._presence_server.resend_presence()\n                done = True\n        if not done:\n            raise RuntimeError(\n                \"failed to publish avatar: no protocol available\"\n            )",
    "docstring": "Make `avatar_set` the current avatar of the jid associated with this\n        connection.\n\n        If :attr:`synchronize_vcard` is true and PEP is available the\n        vCard is only synchronized if the PEP update is successful.\n\n        This means publishing the ``image/png`` avatar data and the\n        avatar metadata set in pubsub. The `avatar_set` must be an\n        instance of :class:`AvatarSet`. If :attr:`synchronize_vcard` is\n        true the avatar is additionally published in the user vCard."
  },
  {
    "code": "def add(self, record):\n        self._field.validate_value(record)\n        self._elements[record.id] = record\n        self._sync_field()",
    "docstring": "Add a reference to the provided record"
  },
  {
    "code": "def claim_token(self, **params):\n        self._json_params.update(params)\n        success, self.user = self.Model.authenticate_by_password(\n            self._json_params)\n        if success:\n            headers = remember(self.request, self.user.username)\n            return JHTTPOk('Token claimed', headers=headers)\n        if self.user:\n            raise JHTTPUnauthorized('Wrong login or password')\n        else:\n            raise JHTTPNotFound('User not found')",
    "docstring": "Claim current token by POSTing 'login' and 'password'.\n\n        User's `Authorization` header value is returned in `WWW-Authenticate`\n        header."
  },
  {
    "code": "def _update_params(self, constants):\n        for k, v in constants.items():\n            self.params[k]['value'] *= v\n        influence = self._calculate_influence(self.params['infl']['value'])\n        return influence * self.params['lr']['value']",
    "docstring": "Update params and return new influence."
  },
  {
    "code": "def get_targets(self):\n        if not hasattr(self, \"_targets\"):\n            targets = []\n            for target_def in self.config.targets or []:\n                target = Target(target_def)\n                targets.append(target)\n            self._targets = targets\n        return self._targets",
    "docstring": "Returns the named targets that are specified in the config.\n\n        Returns:\n            list: a list of :class:`stacker.target.Target` objects"
  },
  {
    "code": "def assert_in(first, second, msg_fmt=\"{msg}\"):\n    if first not in second:\n        msg = \"{!r} not in {!r}\".format(first, second)\n        fail(msg_fmt.format(msg=msg, first=first, second=second))",
    "docstring": "Fail if first is not in collection second.\n\n    >>> assert_in(\"foo\", [4, \"foo\", {}])\n    >>> assert_in(\"bar\", [4, \"foo\", {}])\n    Traceback (most recent call last):\n        ...\n    AssertionError: 'bar' not in [4, 'foo', {}]\n\n    The following msg_fmt arguments are supported:\n    * msg - the default error message\n    * first - the element looked for\n    * second - the container looked in"
  },
  {
    "code": "def get_auth_server(domain, allow_http=False):\n    st = get_stellar_toml(domain, allow_http)\n    if not st:\n        return None\n    return st.get('AUTH_SERVER')",
    "docstring": "Retrieve the AUTH_SERVER config from a domain's stellar.toml.\n\n    :param str domain: The domain the .toml file is hosted at.\n    :param bool allow_http: Specifies whether the request should go over plain\n        HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.\n    :return str: The AUTH_SERVER url."
  },
  {
    "code": "def value(self):\n        if self.isenum():\n            if isinstance(self._value, self.enum_ref):\n                return self._value.value\n            return self._value\n        elif self.is_bitmask():\n            return self._value.bitmask\n        else:\n            return self._value",
    "docstring": "Return this type's value.\n\n        Returns:\n            object: The value of an enum, bitmask, etc."
  },
  {
    "code": "def get_insns(cls = None):\n    insns = []\n    if cls is None:\n        cls = Instruction\n    if \"_mnemonic\" in cls.__dict__.keys():\n        insns = [cls]\n    for subcls in cls.__subclasses__():\n        insns += get_insns(subcls)\n    return insns",
    "docstring": "Get all Instructions. This is based on all known subclasses of `cls`. If non is given, all Instructions are returned.\n    Only such instructions are returned that can be generated, i.e., that have a mnemonic, opcode, etc. So other\n    classes in the hierarchy are not matched.\n\n    :param cls: Base class to get list\n    :type cls: Instruction\n    :return: List of instructions"
  },
  {
    "code": "def register(self, name, content, description=None):\n        return self.__app.documents.register(name, content, self._plugin, description)",
    "docstring": "Register a new document.\n\n        :param content: Content of this document. Jinja and rst are supported.\n        :type content: str\n        :param name: Unique name of the document for documentation purposes.\n        :param description: Short description of this document"
  },
  {
    "code": "def auto_flexdock(self, binding_residues, radius, ligand_path=None, force_rerun=False):\n        log.debug('\\n{}: running DOCK6...\\n'\n                 '\\tBinding residues: {}\\n'\n                 '\\tBinding residues radius: {}\\n'\n                 '\\tLigand to dock: {}\\n'.format(self.id, binding_residues, radius, op.basename(ligand_path)))\n        self.dockprep(force_rerun=force_rerun)\n        self.protein_only_and_noH(force_rerun=force_rerun)\n        self.dms_maker(force_rerun=force_rerun)\n        self.sphgen(force_rerun=force_rerun)\n        self.binding_site_mol2(residues=binding_residues, force_rerun=force_rerun)\n        self.sphere_selector_using_residues(radius=radius, force_rerun=force_rerun)\n        self.showbox(force_rerun=force_rerun)\n        self.grid(force_rerun=force_rerun)\n        if ligand_path:\n            self.do_dock6_flexible(ligand_path=ligand_path, force_rerun=force_rerun)",
    "docstring": "Run DOCK6 on a PDB file, given its binding residues and a radius around them.\n\n        Provide a path to a ligand to dock a ligand to it. If no ligand is provided, DOCK6 preparations will be run on\n        that structure file.\n\n        Args:\n            binding_residues (str): Comma separated string of residues (eg: '144,170,199')\n            radius (int, float): Radius around binding residues to dock to\n            ligand_path (str): Path to ligand (mol2 format) to dock to protein\n            force_rerun (bool): If method should be rerun even if output files exist"
  },
  {
    "code": "def _convert_pooling_param(param):\n    param_string = \"pooling_convention='full', \"\n    if param.global_pooling:\n        param_string += \"global_pool=True, kernel=(1,1)\"\n    else:\n        param_string += \"pad=(%d,%d), kernel=(%d,%d), stride=(%d,%d)\" % (\n            param.pad, param.pad, param.kernel_size, param.kernel_size,\n            param.stride, param.stride)\n    if param.pool == 0:\n        param_string += \", pool_type='max'\"\n    elif param.pool == 1:\n        param_string += \", pool_type='avg'\"\n    else:\n        raise ValueError(\"Unknown Pooling Method!\")\n    return param_string",
    "docstring": "Convert the pooling layer parameter"
  },
  {
    "code": "def indentation(logical_line, previous_logical, indent_char,\n                indent_level, previous_indent_level):\n    r\n    c = 0 if logical_line else 3\n    tmpl = \"E11%d %s\" if logical_line else \"E11%d %s (comment)\"\n    if indent_level % 4:\n        yield 0, tmpl % (1 + c, \"indentation is not a multiple of four\")\n    indent_expect = previous_logical.endswith(':')\n    if indent_expect and indent_level <= previous_indent_level:\n        yield 0, tmpl % (2 + c, \"expected an indented block\")\n    elif not indent_expect and indent_level > previous_indent_level:\n        yield 0, tmpl % (3 + c, \"unexpected indentation\")",
    "docstring": "r\"\"\"Use 4 spaces per indentation level.\n\n    For really old code that you don't want to mess up, you can continue to\n    use 8-space tabs.\n\n    Okay: a = 1\n    Okay: if a == 0:\\n    a = 1\n    E111:   a = 1\n    E114:   # a = 1\n\n    Okay: for item in items:\\n    pass\n    E112: for item in items:\\npass\n    E115: for item in items:\\n# Hi\\n    pass\n\n    Okay: a = 1\\nb = 2\n    E113: a = 1\\n    b = 2\n    E116: a = 1\\n    # b = 2"
  },
  {
    "code": "def recycle_view(self, position):\n        d = self.declaration\n        if position < len(d.parent.items):\n            d.index = position\n            d.item = d.parent.items[position]\n        else:\n            d.index = -1\n            d.item = None",
    "docstring": "Tell the view to render the item at the given position"
  },
  {
    "code": "def set_ontime(self, ontime):\n        try:\n            ontime = float(ontime)\n        except Exception as err:\n            LOG.debug(\"SwitchPowermeter.set_ontime: Exception %s\" % (err,))\n            return False\n        self.actionNodeData(\"ON_TIME\", ontime)",
    "docstring": "Set duration th switch stays on when toggled."
  },
  {
    "code": "def unindex_model_on_delete(sender, document, **kwargs):\n    if current_app.config.get('AUTO_INDEX'):\n        unindex.delay(document)",
    "docstring": "Unindex Mongo document on post_delete"
  },
  {
    "code": "def get_themes(urls):\n    length = len(urls)\n    counter = 1\n    widgets = ['Fetching themes:', Percentage(), ' ',\n               Bar(marker='-'), ' ', ETA()]\n    pbar = ProgressBar( widgets=widgets, maxval=length ).start()\n    for i in urls.keys():\n        href = 'http://dotshare.it/dots/%s/0/raw/' % urls[i]\n        theme = urllib.urlopen(href).read()\n        f = open(THEMEDIR + i, 'w')\n        f.write(theme)\n        f.close()\n        pbar.update(counter)\n        counter += 1\n    pbar.finish()",
    "docstring": "takes in dict of names and urls, downloads and saves files"
  },
  {
    "code": "def removeProperty(self, prop: str) -> str:\n        removed_prop = self.get(prop)\n        if removed_prop is not None:\n            del self[prop]\n        return removed_prop",
    "docstring": "Remove the css property."
  },
  {
    "code": "def add_verified_read(self):\n        self.remove_perm(d1_common.const.SUBJECT_PUBLIC, 'read')\n        self.add_perm(d1_common.const.SUBJECT_VERIFIED, 'read')",
    "docstring": "Add ``read`` perm for all verified subj.\n\n        Public ``read`` is removed if present."
  },
  {
    "code": "def create_group_dampening(self, group_id, dampening):\n        data = self._serialize_object(dampening)\n        url = self._service_url(['triggers', 'groups', group_id, 'dampenings'])\n        return Dampening(self._post(url, data))",
    "docstring": "Create a new group dampening\n\n        :param group_id: Group Trigger id attached to dampening\n        :param dampening: Dampening definition to be created.\n        :type dampening: Dampening\n        :return: Group Dampening created"
  },
  {
    "code": "def _add_to(self, db, index, item, default=OOSet):\n        row = db.get(index, None)\n        if row is None:\n            row = default()\n            db[index] = row\n        row.add(item)",
    "docstring": "Add `item` to `db` under `index`. If `index` is not yet in `db`, create\n        it using `default`.\n\n        Args:\n            db (dict-obj): Dict-like object used to connect to database.\n            index (str): Index used to look in `db`.\n            item (obj): Persistent object, which may be stored in DB.\n            default (func/obj): Reference to function/object, which will be\n                used to create the object under `index`.\n                Default :class:`OOSet`."
  },
  {
    "code": "def get_event(self, name, default=_sentinel):\n        if name not in self.events:\n            if self.create_events_on_access:\n                self.add_event(name)\n            elif default is not _sentinel:\n                return default\n        return self.events[name]",
    "docstring": "Lookup an event by name.\n\n        :param str item: Event name\n        :return Event: Event instance under key"
  },
  {
    "code": "def get_angles(self) -> Tuple[List[float], List[float]]:\n        stacked_params = np.hstack((self.betas, self.gammas))\n        vqe = VQE(self.minimizer, minimizer_args=self.minimizer_args,\n                  minimizer_kwargs=self.minimizer_kwargs)\n        cost_ham = reduce(lambda x, y: x + y, self.cost_ham)\n        param_prog = self.get_parameterized_program()\n        result = vqe.vqe_run(param_prog, cost_ham, stacked_params, qc=self.qc,\n                             **self.vqe_options)\n        self.result = result\n        betas = result.x[:self.steps]\n        gammas = result.x[self.steps:]\n        return betas, gammas",
    "docstring": "Finds optimal angles with the quantum variational eigensolver method.\n\n        Stored VQE result\n\n        :returns: A tuple of the beta angles and the gamma angles for the optimal solution."
  },
  {
    "code": "def parse_format(self):\n        if (self.format is not None and\n                not re.match(r, self.format)):\n            raise IIIFRequestError(\n                parameter='format',\n                text='Bad format parameter')",
    "docstring": "Check format parameter.\n\n        All formats values listed in the specification are lowercase\n        alphanumeric value commonly used as file extensions. To leave\n        opportunity for extension here just do a limited sanity check\n        on characters and length."
  },
  {
    "code": "def _parse_expiry(response_data):\n    expires_in = response_data.get('expires_in', None)\n    if expires_in is not None:\n        return _helpers.utcnow() + datetime.timedelta(\n            seconds=expires_in)\n    else:\n        return None",
    "docstring": "Parses the expiry field from a response into a datetime.\n\n    Args:\n        response_data (Mapping): The JSON-parsed response data.\n\n    Returns:\n        Optional[datetime]: The expiration or ``None`` if no expiration was\n            specified."
  },
  {
    "code": "def api_url(self):\n        return pathjoin(Bin.path, self.name, url=self.service.url)",
    "docstring": "return the api url of self"
  },
  {
    "code": "def process_pool(self, limited_run=False):\n        from multiprocessing import cpu_count\n        from ambry.bundle.concurrent import Pool, init_library\n        if self.processes:\n            cpus = self.processes\n        else:\n            cpus = cpu_count()\n        self.logger.info('Starting MP pool with {} processors'.format(cpus))\n        return Pool(self, processes=cpus, initializer=init_library,\n                    maxtasksperchild=1,\n                    initargs=[self.database.dsn, self._account_password, limited_run])",
    "docstring": "Return a pool for multiprocess operations, sized either to the number of CPUS, or a configured value"
  },
  {
    "code": "async def stop(self):\n        for task in self.__tracks.values():\n            if task is not None:\n                task.cancel()\n        self.__tracks = {}",
    "docstring": "Stop discarding media."
  },
  {
    "code": "def storage_record2pairwise_info(storec: StorageRecord) -> PairwiseInfo:\n    return PairwiseInfo(\n        storec.id,\n        storec.value,\n        storec.tags['~my_did'],\n        storec.tags['~my_verkey'],\n        {\n            tag[tag.startswith('~'):]: storec.tags[tag] for tag in (storec.tags or {})\n        })",
    "docstring": "Given indy-sdk non_secrets implementation of pairwise storage record dict, return corresponding PairwiseInfo.\n\n    :param storec: (non-secret) storage record to convert to PairwiseInfo\n    :return: PairwiseInfo on record DIDs, verkeys, metadata"
  },
  {
    "code": "def intersection(self, other):\n        taxa1 = self.labels\n        taxa2 = other.labels\n        return taxa1 & taxa2",
    "docstring": "Returns the intersection of the taxon sets of two Trees"
  },
  {
    "code": "def _diff_disk_lists(old, new):\n    targets = []\n    prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd']\n    for disk in new:\n        target_node = disk.find('target')\n        target = target_node.get('dev')\n        prefix = [item for item in prefixes if target.startswith(item)][0]\n        new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new))\n                      if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0]\n        target_node.set('dev', new_target)\n        targets.append(new_target)\n    return _diff_lists(old, new, _disks_equal)",
    "docstring": "Compare disk definitions to extract the changes and fix target devices\n\n    :param old: list of ElementTree nodes representing the old disks\n    :param new: list of ElementTree nodes representing the new disks"
  },
  {
    "code": "def setFileSecurity(\n        self,\n        fileName,\n        securityInformation,\n        securityDescriptor,\n        lengthSecurityDescriptorBuffer,\n        dokanFileInfo,\n    ):\n        return self.operations('setFileSecurity', fileName)",
    "docstring": "Set security attributes of a file.\n\n        :param fileName: name of file to set security for\n        :type fileName: ctypes.c_wchar_p\n        :param securityInformation: new security information\n        :type securityInformation: PSECURITY_INFORMATION\n        :param securityDescriptor: newsecurity descriptor\n        :type securityDescriptor: PSECURITY_DESCRIPTOR\n        :param lengthSecurityDescriptorBuffer: length of descriptor buffer\n        :type lengthSecurityDescriptorBuffer: ctypes.c_ulong\n        :param dokanFileInfo: used by Dokan\n        :type dokanFileInfo: PDOKAN_FILE_INFO\n        :return: error code\n        :rtype: ctypes.c_int"
  },
  {
    "code": "def _validate(self, field, list_attribute):\n        if not self.scripts_added:\n            self._generate_validation_scripts()\n        self.id_generator.generate_id(field)\n        self.script_list_fields_with_validation.append_text(\n            'hatemileValidationList.'\n            + list_attribute\n            + '.push(\"'\n            + field.get_attribute('id')\n            + '\");'\n        )",
    "docstring": "Validate the field when its value change.\n\n        :param field: The field.\n        :param list_attribute: The list attribute of field with validation."
  },
  {
    "code": "def set_brightness(self, brightness):\n        if not 25 <= brightness <= 255:\n            raise ValueError(\"The brightness needs to be between 25 and 255.\")\n        payload = self.generate_payload(SET, {self.DPS_INDEX_BRIGHTNESS: brightness})\n        data = self._send_receive(payload)\n        return data",
    "docstring": "Set the brightness value of an rgb bulb.\n\n        Args:\n            brightness(int): Value for the brightness (25-255)."
  },
  {
    "code": "def _asyncio_open_serial_windows(path):\n    try:\n        yield from wait_for_named_pipe_creation(path)\n    except asyncio.TimeoutError:\n        raise NodeError('Pipe file \"{}\" is missing'.format(path))\n    return WindowsPipe(path)",
    "docstring": "Open a windows named pipe\n\n    :returns: An IO like object"
  },
  {
    "code": "def _blocked(self, args):\n        reason = args.read_shortstr()\n        if self.on_blocked:\n            return self.on_blocked(reason)",
    "docstring": "RabbitMQ Extension."
  },
  {
    "code": "def lrem(self, key, count, value):\n        if not isinstance(count, int):\n            raise TypeError(\"count argument must be int\")\n        return self.execute(b'LREM', key, count, value)",
    "docstring": "Removes the first count occurrences of elements equal to value\n        from the list stored at key.\n\n        :raises TypeError: if count is not int"
  },
  {
    "code": "def is_holiday(self, day, extra_holidays=None):\n        day = cleaned_date(day)\n        if extra_holidays:\n            extra_holidays = tuple(map(cleaned_date, extra_holidays))\n        if extra_holidays and day in extra_holidays:\n            return True\n        return day in self.holidays_set(day.year)",
    "docstring": "Return True if it's an holiday.\n        In addition to the regular holidays, you can add exceptions.\n\n        By providing ``extra_holidays``, you'll state that these dates **are**\n        holidays, even if not in the regular calendar holidays (or weekends)."
  },
  {
    "code": "def _combine_to_jointcaller(processed):\n    by_vrn_file = collections.OrderedDict()\n    for data in (x[0] for x in processed):\n        key = (tz.get_in((\"config\", \"algorithm\", \"jointcaller\"), data), data[\"vrn_file\"])\n        if key not in by_vrn_file:\n            by_vrn_file[key] = []\n        by_vrn_file[key].append(data)\n    out = []\n    for grouped_data in by_vrn_file.values():\n        cur = grouped_data[0]\n        out.append([cur])\n    return out",
    "docstring": "Add joint calling information to variants, while collapsing independent regions."
  },
  {
    "code": "def service_account_path(cls, project, service_account):\n        return google.api_core.path_template.expand(\n            \"projects/{project}/serviceAccounts/{service_account}\",\n            project=project,\n            service_account=service_account,\n        )",
    "docstring": "Return a fully-qualified service_account string."
  },
  {
    "code": "def list_group_users(self, group_id, **kwargs):\n        kwargs[\"group_id\"] = group_id\n        kwargs = self._verify_sort_options(kwargs)\n        api = self._get_api(iam.AccountAdminApi)\n        return PaginatedResponse(api.get_users_of_group, lwrap_type=User, **kwargs)",
    "docstring": "List users of a group.\n\n        :param str group_id: The group ID (Required)\n        :param int limit: The number of users to retrieve\n        :param str order: The ordering direction, ascending (asc) or descending (desc)\n        :param str after: Get API keys after/starting at given user ID\n        :returns: a list of :py:class:`User` objects.\n        :rtype: PaginatedResponse"
  },
  {
    "code": "def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:\n        return self._query(f'guilds/{guild_id}/members/{member_id}', 'GET')",
    "docstring": "Get a guild member by their id\n\n        Args:\n            guild_id: snowflake id of the guild\n            member_id: snowflake id of the member\n\n        Returns:\n            Dictionary data for the guild member.\n\n            Example:\n                {\n                    \"id\": \"41771983423143937\",\n                    \"name\": \"Discord Developers\",\n                    \"icon\": \"SEkgTU9NIElUUyBBTkRSRUkhISEhISEh\",\n                    \"splash\": null,\n                    \"owner_id\": \"80351110224678912\",\n                    \"region\": \"us-east\",\n                    \"afk_channel_id\": \"42072017402331136\",\n                    \"afk_timeout\": 300,\n                    \"embed_enabled\": true,\n                    \"embed_channel_id\": \"41771983444115456\",\n                    \"verification_level\": 1,\n                    \"roles\": [\n                        \"41771983423143936\",\n                        \"41771983423143937\",\n                        \"41771983423143938\"\n                    ],\n                    \"emojis\": [],\n                    \"features\": [\"INVITE_SPLASH\"],\n                    \"unavailable\": false\n                }"
  },
  {
    "code": "def create_partitions(self, new_partitions, **kwargs):\n        f, futmap = AdminClient._make_futures([x.topic for x in new_partitions],\n                                              None,\n                                              AdminClient._make_topics_result)\n        super(AdminClient, self).create_partitions(new_partitions, f, **kwargs)\n        return futmap",
    "docstring": "Create additional partitions for the given topics.\n\n        The future result() value is None.\n\n        :param list(NewPartitions) new_partitions: New partitions to be created.\n        :param float operation_timeout: Set broker's operation timeout in seconds,\n                  controlling how long the CreatePartitions request will block\n                  on the broker waiting for the partition creation to propagate\n                  in the cluster. A value of 0 returns immediately. Default: 0\n        :param float request_timeout: Set the overall request timeout in seconds,\n                  including broker lookup, request transmission, operation time\n                  on broker, and response. Default: `socket.timeout.ms*1000.0`\n        :param bool validate_only: Tell broker to only validate the request,\n                  without creating the partitions. Default: False\n\n        :returns: a dict of futures for each topic, keyed by the topic name.\n        :rtype: dict(<topic_name, future>)\n\n        :raises KafkaException: Operation failed locally or on broker.\n        :raises TypeException: Invalid input.\n        :raises ValueException: Invalid input."
  },
  {
    "code": "def hit(self, to_hit):\n        to_hit = list(map(lambda obj: self.idpool.id(obj), to_hit))\n        new_obj = list(filter(lambda vid: vid not in self.oracle.vmap.e2i, to_hit))\n        self.oracle.add_clause(to_hit)\n        for vid in new_obj:\n            self.oracle.add_clause([-vid], 1)",
    "docstring": "This method adds a new set to hit to the hitting set solver. This\n            is done by translating the input iterable of objects into a list of\n            Boolean variables in the MaxSAT problem formulation.\n\n            :param to_hit: a new set to hit\n            :type to_hit: iterable(obj)"
  },
  {
    "code": "def message_handler(type_, from_):\n    def decorator(f):\n        if asyncio.iscoroutinefunction(f):\n            raise TypeError(\"message_handler must not be a coroutine function\")\n        aioxmpp.service.add_handler_spec(\n            f,\n            aioxmpp.service.HandlerSpec(\n                (_apply_message_handler, (type_, from_)),\n                require_deps=(\n                    SimpleMessageDispatcher,\n                )\n            )\n        )\n        return f\n    return decorator",
    "docstring": "Register the decorated function as message handler.\n\n    :param type_: Message type to listen for\n    :type type_: :class:`~.MessageType`\n    :param from_: Sender JIDs to listen for\n    :type from_: :class:`aioxmpp.JID` or :data:`None`\n    :raise TypeError: if the decorated object is a coroutine function\n\n    .. seealso::\n\n       :meth:`~.StanzaStream.register_message_callback`\n          for more details on the `type_` and `from_` arguments\n\n    .. versionchanged:: 0.9\n\n       This is now based on\n       :class:`aioxmpp.dispatcher.SimpleMessageDispatcher`."
  },
  {
    "code": "def iter(self, obj=None):\n        'Iterate through all keys considering context of obj. If obj is None, uses the context of the top sheet.'\n        if obj is None and vd:\n            obj = vd.sheet\n        for o in self._mappings(obj):\n            for k in self.keys():\n                for o2 in self[k]:\n                    if o == o2:\n                        yield (k, o), self[k][o2]",
    "docstring": "Iterate through all keys considering context of obj. If obj is None, uses the context of the top sheet."
  },
  {
    "code": "async def jsk_hide(self, ctx: commands.Context):\n        if self.jsk.hidden:\n            return await ctx.send(\"Jishaku is already hidden.\")\n        self.jsk.hidden = True\n        await ctx.send(\"Jishaku is now hidden.\")",
    "docstring": "Hides Jishaku from the help command."
  },
  {
    "code": "def _TerminateProcessByPid(self, pid):\n    self._RaiseIfNotRegistered(pid)\n    process = self._processes_per_pid[pid]\n    self._TerminateProcess(process)\n    self._StopMonitoringProcess(process)",
    "docstring": "Terminate a process that's monitored by the engine.\n\n    Args:\n      pid (int): process identifier (PID).\n\n    Raises:\n      KeyError: if the process is not registered with and monitored by the\n          engine."
  },
  {
    "code": "def invert(self, points):\n        X = points if not points.ndim == 1 else points.reshape((points.size, 1))\n        wx, wy = self.wc\n        rn = np.sqrt((X[0,:] - wx)**2 + (X[1,:] - wy)**2)\n        phi = np.arctan2(X[1,:] - wy, X[0,:]-wx)\n        r = np.tan(rn * self.lgamma) / self.lgamma;\n        Y = np.ones(X.shape)\n        Y[0,:] = wx + r * np.cos(phi)\n        Y[1,:]= wy + r * np.sin(phi)\n        return Y",
    "docstring": "Invert the distortion\n\n        Parameters\n        ------------------\n        points : ndarray\n            Input image points\n\n        Returns\n        -----------------\n        ndarray\n            Undistorted points"
  },
  {
    "code": "def get_lower_bound(self):\n        lower_bounds = []\n        for distribution in self.distribs.values():\n            lower_bound = distribution.percent_point(distribution.mean / 10000)\n            if not pd.isnull(lower_bound):\n                lower_bounds.append(lower_bound)\n        return min(lower_bounds)",
    "docstring": "Compute the lower bound to integrate cumulative density.\n\n        Returns:\n            float: lower bound for cumulative density integral."
  },
  {
    "code": "def _extract_rows(self, rows):\n        if rows is not None:\n            rows = numpy.array(rows, ndmin=1, copy=False, dtype='i8')\n            rows = numpy.unique(rows)\n            maxrow = self._info['nrows']-1\n            if rows[0] < 0 or rows[-1] > maxrow:\n                raise ValueError(\"rows must be in [%d,%d]\" % (0, maxrow))\n        return rows",
    "docstring": "Extract an array of rows from an input scalar or sequence"
  },
  {
    "code": "def fourier_series(x, *a):\n    output = 0\n    output += a[0]/2\n    w = a[1]\n    for n in range(2, len(a), 2):\n        n_ = n/2\n        val1 = a[n]\n        val2 = a[n+1]\n        output += val1*np.sin(n_*x*w)\n        output += val2*np.cos(n_*x*w)\n    return output",
    "docstring": "Arbitrary dimensionality fourier series.\n\n    The first parameter is a_0, and the second parameter is the interval/scale\n    parameter.\n\n    The parameters are altering sin and cos paramters.\n\n    n = (len(a)-2)/2"
  },
  {
    "code": "def _rollaxis_right(A, num_rolls):\n    assert num_rolls > 0\n    rank = tf.rank(A)\n    perm = tf.concat([rank - num_rolls + tf.range(num_rolls), tf.range(rank - num_rolls)], 0)\n    return tf.transpose(A, perm)",
    "docstring": "Roll the tensor `A` forward `num_rolls` times"
  },
  {
    "code": "def purge_content(self, account_id, urls):\n        if isinstance(urls, six.string_types):\n            urls = [urls]\n        content_list = []\n        for i in range(0, len(urls), MAX_URLS_PER_PURGE):\n            content = self.account.purgeCache(urls[i:i + MAX_URLS_PER_PURGE], id=account_id)\n            content_list.extend(content)\n        return content_list",
    "docstring": "Purges one or more URLs from the CDN edge nodes.\n\n        :param int account_id: the CDN account ID from which content should\n                               be purged.\n        :param urls: a string or a list of strings representing the CDN URLs\n                     that should be purged.\n        :returns: a list of SoftLayer_Container_Network_ContentDelivery_PurgeService_Response objects\n                  which indicates if the purge for each url was SUCCESS, FAILED or INVALID_URL."
  },
  {
    "code": "def _create_default_config_file(self):\r\n        logger.info('Initialize Maya launcher, creating config file...\\n')\r\n        self.add_section(self.DEFAULTS)\r\n        self.add_section(self.PATTERNS)\r\n        self.add_section(self.ENVIRONMENTS)\r\n        self.add_section(self.EXECUTABLES)\r\n        self.set(self.DEFAULTS, 'executable', None)\r\n        self.set(self.DEFAULTS, 'environment', None)\r\n        self.set(self.PATTERNS, 'exclude', ', '.join(self.EXLUDE_PATTERNS))\r\n        self.set(self.PATTERNS, 'icon_ext', ', '.join(self.ICON_EXTENSIONS))\r\n        self.config_file.parent.mkdir(exist_ok=True)\r\n        self.config_file.touch()\r\n        with self.config_file.open('wb') as f:\r\n            self.write(f)\r\n        sys.exit('Maya launcher has successfully created config file at:\\n'\r\n                 ' \"{}\"'.format(str(self.config_file)))",
    "docstring": "If config file does not exists create and set default values."
  },
  {
    "code": "def reset_failed_attempts(ip_address=None, username=None):\n    pipe = REDIS_SERVER.pipeline()\n    unblock_ip(ip_address, pipe=pipe)\n    unblock_username(username, pipe=pipe)\n    pipe.execute()",
    "docstring": "reset the failed attempts for these ip's and usernames"
  },
  {
    "code": "def show_env(environment):\n    if not environment:\n        print(\"You need to supply an environment name\")\n        return\n    parser = read_config()\n    try:\n        commands = parser.get(environment, \"cmd\").split(\"\\n\")\n    except KeyError:\n        print(\"Unknown environment type '%s'\" % environment)\n        return\n    print(\"Environment: %s\\n\" % environment)\n    for cmd in commands:\n        print(cmd)",
    "docstring": "Show the commands for a given environment."
  },
  {
    "code": "def obtain_check_classes(self):\n        check_classes = set()\n        for path in self.paths:\n            for root, _, files in os.walk(path):\n                for fi in files:\n                    if not fi.endswith(\".py\"):\n                        continue\n                    path = os.path.join(root, fi)\n                    check_classes = check_classes.union(set(\n                        load_check_classes_from_file(path)))\n        return list(check_classes)",
    "docstring": "find children of AbstractCheck class and return them as a list"
  },
  {
    "code": "def poisson_ll(data, means):\n    if sparse.issparse(data):\n        return sparse_poisson_ll(data, means)\n    genes, cells = data.shape\n    clusters = means.shape[1]\n    ll = np.zeros((cells, clusters))\n    for i in range(clusters):\n        means_i = np.tile(means[:,i], (cells, 1))\n        means_i = means_i.transpose() + eps\n        ll[:,i] = np.sum(xlogy(data, means_i) - means_i, 0)\n    return ll",
    "docstring": "Calculates the Poisson log-likelihood.\n\n    Args:\n        data (array): 2d numpy array of genes x cells\n        means (array): 2d numpy array of genes x k\n\n    Returns:\n        cells x k array of log-likelihood for each cell/cluster pair"
  },
  {
    "code": "def get_rollout_from_id(self, rollout_id):\n    layer = self.rollout_id_map.get(rollout_id)\n    if layer:\n      return layer\n    self.logger.error('Rollout with ID \"%s\" is not in datafile.' % rollout_id)\n    return None",
    "docstring": "Get rollout for the provided ID.\n\n    Args:\n      rollout_id: ID of the rollout to be fetched.\n\n    Returns:\n      Rollout corresponding to the provided ID."
  },
  {
    "code": "def _validate_type(self, properties_spec, value):\n        if 'type' not in properties_spec.keys():\n            def_name = self.get_definition_name_from_ref(properties_spec['$ref'])\n            return self.validate_definition(def_name, value)\n        elif properties_spec['type'] == 'array':\n            if not isinstance(value, list):\n                return False\n            if ('type' in properties_spec['items'].keys() and\n                    any(not self.check_type(item, properties_spec['items']['type']) for item in value)):\n                return False\n            elif ('$ref' in properties_spec['items'].keys()):\n                def_name = self.get_definition_name_from_ref(properties_spec['items']['$ref'])\n                if any(not self.validate_definition(def_name, item) for item in value):\n                    return False\n        else:\n            if not self.check_type(value, properties_spec['type']):\n                return False\n        return True",
    "docstring": "Validate the given value with the given property spec.\n\n        Args:\n            properties_dict: specification of the property to check (From definition not route).\n            value: value to check.\n\n        Returns:\n            True if the value is valid for the given spec."
  },
  {
    "code": "def ex_call(func, args):\n    if isinstance(func, str):\n        func = ex_rvalue(func)\n    args = list(args)\n    for i in range(len(args)):\n        if not isinstance(args[i], ast.expr):\n            args[i] = ex_literal(args[i])\n    if sys.version_info[:2] < (3, 5):\n        return ast.Call(func, args, [], None, None)\n    else:\n        return ast.Call(func, args, [])",
    "docstring": "A function-call expression with only positional parameters. The\n    function may be an expression or the name of a function. Each\n    argument may be an expression or a value to be used as a literal."
  },
  {
    "code": "def clear(self):\n        if self._bit_count == 0:\n            return\n        block = self._qpart.document().begin()\n        while block.isValid():\n            if self.getBlockValue(block):\n                self.setBlockValue(block, 0)\n            block = block.next()",
    "docstring": "Convenience method to reset all the block values to 0"
  },
  {
    "code": "def wp_slope(self):\n        last_w = None\n        for i in range(1, self.wploader.count()):\n            w = self.wploader.wp(i)\n            if w.command not in [mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, mavutil.mavlink.MAV_CMD_NAV_LAND]:\n                continue\n            if last_w is not None:\n                if last_w.frame != w.frame:\n                    print(\"WARNING: frame change %u -> %u at %u\" % (last_w.frame, w.frame, i))\n                delta_alt = last_w.z - w.z\n                if delta_alt == 0:\n                    slope = \"Level\"\n                else:\n                    delta_xy = mp_util.gps_distance(w.x, w.y, last_w.x, last_w.y)\n                    slope = \"%.1f\" % (delta_xy / delta_alt)\n                print(\"WP%u: slope %s\" % (i, slope))\n            last_w = w",
    "docstring": "show slope of waypoints"
  },
  {
    "code": "def add_sponsor(self, type, name, **kwargs):\n        self['sponsors'].append(dict(type=type, name=name, **kwargs))",
    "docstring": "Associate a sponsor with this bill.\n\n        :param type: the type of sponsorship, e.g. 'primary', 'cosponsor'\n        :param name: the name of the sponsor as provided by the official source"
  },
  {
    "code": "def attr_attributes_transform(node):\n    node.locals[\"__attrs_attrs__\"] = [astroid.Unknown(parent=node)]\n    for cdefbodynode in node.body:\n        if not isinstance(cdefbodynode, astroid.Assign):\n            continue\n        if isinstance(cdefbodynode.value, astroid.Call):\n            if cdefbodynode.value.func.as_string() not in ATTRIB_NAMES:\n                continue\n        else:\n            continue\n        for target in cdefbodynode.targets:\n            rhs_node = astroid.Unknown(\n                lineno=cdefbodynode.lineno,\n                col_offset=cdefbodynode.col_offset,\n                parent=cdefbodynode,\n            )\n            node.locals[target.name] = [rhs_node]",
    "docstring": "Given that the ClassNode has an attr decorator,\n    rewrite class attributes as instance attributes"
  },
  {
    "code": "def _register_entry_point_module(self, entry_point, module):\n        records_map = self._map_entry_point_module(entry_point, module)\n        self.store_records_for_package(entry_point, list(records_map.keys()))\n        for module_name, records in records_map.items():\n            if module_name in self.records:\n                logger.info(\n                    \"module '%s' was already declared in registry '%s'; \"\n                    \"applying new records on top.\",\n                    module_name, self.registry_name,\n                )\n                logger.debug(\"overwriting keys: %s\", sorted(\n                    set(self.records[module_name].keys()) &\n                    set(records.keys())\n                ))\n                self.records[module_name].update(records)\n            else:\n                logger.debug(\n                    \"adding records for module '%s' to registry '%s'\",\n                    module_name, self.registry_name,\n                )\n                self.records[module_name] = records",
    "docstring": "Private method that registers an entry_point with a provided\n        module."
  },
  {
    "code": "def list_keyvaults_sub(access_token, subscription_id):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/providers/Microsoft.KeyVault/vaults',\n                        '?api-version=', KEYVAULT_API])\n    return do_get_next(endpoint, access_token)",
    "docstring": "Lists key vaults belonging to this subscription.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n\n    Returns:\n        HTTP response. 200 OK."
  },
  {
    "code": "def to_pillow_image(self, return_mask=False):\n        img = np.rollaxis(np.rollaxis(self.image.data, 2), 2)\n        img = Image.fromarray(img[:, :, 0]) if img.shape[2] == 1 else Image.fromarray(img)\n        if return_mask:\n            mask = np.ma.getmaskarray(self.image)\n            mask = Image.fromarray(np.rollaxis(np.rollaxis(mask, 2), 2).astype(np.uint8)[:, :, 0])\n            return img, mask\n        else:\n            return img",
    "docstring": "Return Pillow. Image, and optionally also mask."
  },
  {
    "code": "def storage(self):\n        if self.backend == 'redis':\n            return RedisBackend(self.prefix, self.secondary_indexes)\n        if self.backend == 'dynamodb':\n            return DynamoDBBackend(self.prefix, self.key, self.sort_key,\n                                   self.secondary_indexes)\n        return DictBackend(self.prefix, self.secondary_indexes)",
    "docstring": "Instantiates and returns a storage instance"
  },
  {
    "code": "def get_skill_by_name(nme, character):\n    for ndx, sk in enumerate(character[\"skills\"]):\n        if sk[\"name\"] == nme:\n            return ndx\n    return 0",
    "docstring": "returns the skill by name in a character"
  },
  {
    "code": "def add_tenant_user_role(request, project=None, user=None, role=None,\n                         group=None, domain=None):\n    manager = keystoneclient(request, admin=True).roles\n    if VERSIONS.active < 3:\n        manager.add_user_role(user, role, project)\n    else:\n        manager.grant(role, user=user, project=project,\n                      group=group, domain=domain)",
    "docstring": "Adds a role for a user on a tenant."
  },
  {
    "code": "def worker_config(queue, s3_key, period, verbose):\n    logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))\n    logging.getLogger('botocore').setLevel(logging.WARNING)\n    logging.getLogger('s3transfer').setLevel(logging.WARNING)\n    queue, region = get_queue(queue)\n    factory = SessionFactory(region)\n    session = factory()\n    client = session.client('sqs')\n    messages = MessageIterator(client, queue, timeout=20)\n    for m in messages:\n        msg = unwrap(m)\n        if 'configurationItemSummary' in msg:\n            rtype = msg['configurationItemSummary']['resourceType']\n        else:\n            rtype = msg['configurationItem']['resourceType']\n        if rtype not in RESOURCE_MAPPING.values():\n            log.info(\"skipping %s\" % rtype)\n            messages.ack(m)\n        log.info(\"message received %s\", m)",
    "docstring": "daemon queue worker for config notifications"
  },
  {
    "code": "def start(self, origin):\n        self.start_time = time.time()\n        self.pause_until = None\n        self.data.update(self._get_struct(origin, 'origin'))\n        self.data_stack.append(self.data)\n        sys.settrace(self._trace)\n        return self._trace",
    "docstring": "Start this Tracer.\n\n        Return a Python function suitable for use with sys.settrace()."
  },
  {
    "code": "def memoize(f):\n    cache = {}\n    @wraps(f)\n    def inner(arg):\n        if arg not in cache:\n            cache[arg] = f(arg)\n        return cache[arg]\n    return inner",
    "docstring": "Decorator which caches function's return value each it is called.\n    If called later with same arguments, the cached value is returned."
  },
  {
    "code": "def set_license(self, key):\n        data = {'LicenseKey': key}\n        license_service_uri = (utils.get_subresource_path_by(self,\n                               ['Oem', 'Hpe', 'Links', 'LicenseService']))\n        self._conn.post(license_service_uri, data=data)",
    "docstring": "Set the license on a redfish system\n\n        :param key: license key"
  },
  {
    "code": "def _delete_vdev_info(self, vdev):\n        vdev = vdev.lower()\n        rules_file_name = '/etc/udev/rules.d/51-qeth-0.0.%s.rules' % vdev\n        cmd = 'rm -f %s\\n' % rules_file_name\n        address = '0.0.%s' % str(vdev).zfill(4)\n        udev_file_name = '/etc/udev/rules.d/70-persistent-net.rules'\n        cmd += \"sed -i '/%s/d' %s\\n\" % (address, udev_file_name)\n        cmd += \"sed -i '/%s/d' %s\\n\" % (address,\n                                        '/boot/zipl/active_devices.txt')\n        return cmd",
    "docstring": "handle udev rules file."
  },
  {
    "code": "def partial_transform(self, traj):\n        fingerprints = np.zeros((traj.n_frames, self.n_features))\n        atom_pairs = np.zeros((len(self.solvent_indices), 2))\n        sigma = self.sigma\n        for i, solute_i in enumerate(self.solute_indices):\n            atom_pairs[:, 0] = solute_i\n            atom_pairs[:, 1] = self.solvent_indices\n            distances = md.compute_distances(traj, atom_pairs, periodic=True)\n            distances = np.exp(-distances / (2 * sigma * sigma))\n            fingerprints[:, i] = np.sum(distances, axis=1)\n        return fingerprints",
    "docstring": "Featurize an MD trajectory into a vector space via calculation\n        of solvent fingerprints\n\n        Parameters\n        ----------\n        traj : mdtraj.Trajectory\n            A molecular dynamics trajectory to featurize.\n\n        Returns\n        -------\n        features : np.ndarray, dtype=float, shape=(n_samples, n_features)\n            A featurized trajectory is a 2D array of shape\n            `(length_of_trajectory x n_features)` where each `features[i]`\n            vector is computed by applying the featurization function\n            to the `i`th snapshot of the input trajectory.\n\n        See Also\n        --------\n        transform : simultaneously featurize a collection of MD trajectories"
  },
  {
    "code": "def env_dn_dict(self, env_prefix, cert_value):\n        if not cert_value:\n            return {}\n        env = {}\n        for rdn in cert_value:\n            for attr_name, val in rdn:\n                attr_code = self.CERT_KEY_TO_LDAP_CODE.get(attr_name)\n                if attr_code:\n                    env['%s_%s' % (env_prefix, attr_code)] = val\n        return env",
    "docstring": "Return a dict of WSGI environment variables for a client cert DN.\n\n        E.g. SSL_CLIENT_S_DN_CN, SSL_CLIENT_S_DN_C, etc.\n        See SSL_CLIENT_S_DN_x509 at\n        https://httpd.apache.org/docs/2.4/mod/mod_ssl.html#envvars."
  },
  {
    "code": "def check_quirks(block_id, block_op, db_state):\n    if op_get_opcode_name(block_op['op']) in OPCODE_NAME_NAMEOPS and op_get_opcode_name(block_op['op']) not in OPCODE_NAME_STATE_PREORDER:\n        assert 'last_creation_op' in block_op, 'QUIRK BUG: missing last_creation_op in {}'.format(op_get_opcode_name(block_op['op']))\n        if block_op['last_creation_op'] == NAME_IMPORT:\n            assert isinstance(block_op['op_fee'], float), 'QUIRK BUG: op_fee is not a float when it should be'\n    return",
    "docstring": "Check that all serialization compatibility quirks have been preserved.\n    Used primarily for testing."
  },
  {
    "code": "def Record(self, obj):\n    if len(self._visit_recorder_objects) >= _MAX_VISIT_OBJECTS:\n      return False\n    obj_id = id(obj)\n    if obj_id in self._visit_recorder_objects:\n      return False\n    self._visit_recorder_objects[obj_id] = obj\n    return True",
    "docstring": "Records the object as visited.\n\n    Args:\n      obj: visited object.\n\n    Returns:\n      True if the object hasn't been previously visited or False if it has\n      already been recorded or the quota has been exhausted."
  },
  {
    "code": "def get_cache_token(self, token):\n        if self.conn is None:\n            raise CacheException('Redis is not connected')\n        token_data = self.conn.get(token)\n        token_data = json.loads(token_data) if token_data else None\n        return token_data",
    "docstring": "Get token and data from Redis"
  },
  {
    "code": "def add_validation_fun(phase, keywords, f):\n    for keyword in keywords:\n        if (phase, keyword) in _validation_map:\n            oldf = _validation_map[(phase, keyword)]\n            def newf(ctx, s):\n                oldf(ctx, s)\n                f(ctx, s)\n            _validation_map[(phase, keyword)] = newf\n        else:\n            _validation_map[(phase, keyword)] = f",
    "docstring": "Add a validation function to some phase in the framework.\n\n    Function `f` is called for each valid occurance of each keyword in\n    `keywords`.\n    Can be used by plugins to do special validation of extensions."
  },
  {
    "code": "def export_private_key(self, password=None):\n\t\tif self.__private_key is None:\n\t\t\traise ValueError('Unable to call this method. Private key must be set')\n\t\tif password is not None:\n\t\t\tif isinstance(password, str) is True:\n\t\t\t\tpassword = password.encode()\n\t\t\treturn self.__private_key.private_bytes(\n\t\t\t\tencoding=serialization.Encoding.PEM,\n\t\t\t\tformat=serialization.PrivateFormat.PKCS8,\n\t\t\t\tencryption_algorithm=serialization.BestAvailableEncryption(password)\n\t\t\t)\n\t\treturn self.__private_key.private_bytes(\n\t\t\tencoding=serialization.Encoding.PEM,\n\t\t\tformat=serialization.PrivateFormat.TraditionalOpenSSL,\n\t\t\tencryption_algorithm=serialization.NoEncryption()\n\t\t)",
    "docstring": "Export a private key in PEM-format\n\n\t\t:param password: If it is not None, then result will be encrypt with given password\n\t\t:return: bytes"
  },
  {
    "code": "def matrix(matrix, xlabel=None, ylabel=None, xticks=None, yticks=None,\n           title=None, colorbar_shrink=0.5, color_map=None, show=None,\n           save=None, ax=None):\n    if ax is None: ax = pl.gca()\n    img = ax.imshow(matrix, cmap=color_map)\n    if xlabel is not None: ax.set_xlabel(xlabel)\n    if ylabel is not None: ax.set_ylabel(ylabel)\n    if title is not None: ax.set_title(title)\n    if xticks is not None:\n        ax.set_xticks(range(len(xticks)), xticks, rotation='vertical')\n    if yticks is not None:\n        ax.set_yticks(range(len(yticks)), yticks)\n    pl.colorbar(img, shrink=colorbar_shrink, ax=ax)\n    savefig_or_show('matrix', show=show, save=save)",
    "docstring": "Plot a matrix."
  },
  {
    "code": "def grok_if_node(element, default_vars):\n    if isinstance(element.test, jinja2.nodes.Filter) and \\\n       element.test.name == 'default':\n        default_vars.append(element.test.node.name)\n    return default_vars + grok_vars(element)",
    "docstring": "Properly parses a If element"
  },
  {
    "code": "def save_or_update(self, cluster):\n        if not os.path.exists(self.storage_path):\n            os.makedirs(self.storage_path)\n        path = self._get_cluster_storage_path(cluster.name)\n        cluster.storage_file = path\n        with open(path, 'wb') as storage:\n            self.dump(cluster, storage)",
    "docstring": "Save or update the cluster to persistent state.\n\n        :param cluster: cluster to save or update\n        :type cluster: :py:class:`elasticluster.cluster.Cluster`"
  },
  {
    "code": "def add_to_document(self, parent):\n        arg = ET.SubElement(parent, \"arg\")\n        arg.set(\"name\", self.name)\n        if self.title is not None:\n            ET.SubElement(arg, \"title\").text = self.title\n        if self.description is not None:\n            ET.SubElement(arg, \"description\").text = self.description\n        if self.validation is not None:\n            ET.SubElement(arg, \"validation\").text = self.validation\n        subelements = [\n            (\"data_type\", self.data_type),\n            (\"required_on_edit\", self.required_on_edit),\n            (\"required_on_create\", self.required_on_create)\n        ]\n        for name, value in subelements:\n            ET.SubElement(arg, name).text = str(value).lower()\n        return arg",
    "docstring": "Adds an ``Argument`` object to this ElementTree document.\n\n        Adds an <arg> subelement to the parent element, typically <args>\n        and sets up its subelements with their respective text.\n\n        :param parent: An ``ET.Element`` to be the parent of a new <arg> subelement\n        :returns: An ``ET.Element`` object representing this argument."
  },
  {
    "code": "def root(self):\n        with self._mutex:\n            if self._parent:\n                return self._parent.root\n            else:\n                return self",
    "docstring": "The root node of the tree this node is in."
  },
  {
    "code": "def registration_backend(backend=None, namespace=None):\n    backend = backend or ORGS_REGISTRATION_BACKEND\n    class_module, class_name = backend.rsplit(\".\", 1)\n    mod = import_module(class_module)\n    return getattr(mod, class_name)(namespace=namespace)",
    "docstring": "Returns a specified registration backend\n\n    Args:\n        backend: dotted path to the registration backend class\n        namespace: URL namespace to use\n\n    Returns:\n        an instance of an RegistrationBackend"
  },
  {
    "code": "def RunInstaller():\n  try:\n    os.makedirs(os.path.dirname(config.CONFIG[\"Installer.logfile\"]))\n  except OSError:\n    pass\n  handler = logging.FileHandler(config.CONFIG[\"Installer.logfile\"], mode=\"wb\")\n  handler.setLevel(logging.DEBUG)\n  logging.getLogger().addHandler(handler)\n  config.CONFIG.Initialize(filename=flags.FLAGS.config, reset=True)\n  config.CONFIG.AddContext(contexts.INSTALLER_CONTEXT,\n                           \"Context applied when we run the client installer.\")\n  logging.warning(\"Starting installation procedure for GRR client.\")\n  try:\n    Installer().Init()\n  except Exception as e:\n    logging.exception(\"Installation failed: %s\", e)\n    sys.exit(-1)\n  sys.exit(0)",
    "docstring": "Run all registered installers.\n\n  Run all the current installers and then exit the process."
  },
  {
    "code": "def connection_ok():\n    try:\n        urlopen(Dataset.base_url, timeout=1)\n        return True\n    except HTTPError:\n        return True\n    except URLError:\n        return False",
    "docstring": "Check web connection.\n    Returns True if web connection is OK, False otherwise."
  },
  {
    "code": "def _get_values(self):\n        (gi, _), (ci, _), (si, _) = self._get_dims(self.hmap.last)\n        ndims = self.hmap.last.ndims\n        dims = self.hmap.last.kdims\n        dimensions = []\n        values = {}\n        for vidx, vtype in zip([gi, ci, si], self._dimensions):\n            if vidx < ndims:\n                dim = dims[vidx]\n                dimensions.append(dim)\n                vals = self.hmap.dimension_values(dim.name)\n            else:\n                dimensions.append(None)\n                vals = [None]\n            values[vtype] = list(unique_iterator(vals))\n        return values, dimensions",
    "docstring": "Get unique index value for each bar"
  },
  {
    "code": "def sendSignal(self, p, member, signature=None, body=None,\n                   path='/org/freedesktop/DBus',\n                   interface='org.freedesktop.DBus'):\n        if not isinstance(body, (list, tuple)):\n            body = [body]\n        s = message.SignalMessage(path, member, interface,\n                                  p.uniqueName, signature, body)\n        p.sendMessage(s)",
    "docstring": "Sends a signal to a specific connection\n\n        @type p: L{BusProtocol}\n        @param p: L{BusProtocol} instance to send a signal to\n\n        @type member: C{string}\n        @param member: Name of the signal to send\n\n        @type path: C{string}\n        @param path: Path of the object emitting the signal. Defaults to\n                     'org/freedesktop/DBus'\n\n        @type interface: C{string}\n        @param interface: If specified, this specifies the interface containing\n            the desired method. Defaults to 'org.freedesktop.DBus'\n\n        @type body: None or C{list}\n        @param body: If supplied, this is a list of signal arguments. The\n            contents of the list must match the signature.\n\n        @type signature: None or C{string}\n        @param signature: If specified, this specifies the DBus signature of\n            the body of the DBus Signal message. This string must be a valid\n            Signature string as defined by the DBus specification. If the body\n            argumnent is supplied, this parameter must be provided."
  },
  {
    "code": "def _pidgin_status(status, message):\n    try:\n        iface = _dbus_get_interface('im.pidgin.purple.PurpleService',\n                                    '/im/pidgin/purple/PurpleObject',\n                                    'im.pidgin.purple.PurpleInterface')\n        if iface:\n            code = PIDGIN_CODE_MAP[status]\n            saved_status = iface.PurpleSavedstatusNew('', code)\n            iface.PurpleSavedstatusSetMessage(saved_status, message)\n            iface.PurpleSavedstatusActivate(saved_status)\n    except dbus.exceptions.DBusException:\n        pass",
    "docstring": "Updates status and message for Pidgin IM application.\n\n        `status`\n            Status type.\n        `message`\n            Status message."
  },
  {
    "code": "def extract_message_info():\n    base_path = BASE_PACKAGE.replace('.', '/')\n    filename = os.path.join(base_path, 'ProtocolMessage.proto')\n    with open(filename, 'r') as file:\n        types_found = False\n        for line in file:\n            stripped = line.lstrip().rstrip()\n            if stripped == 'enum Type {':\n                types_found = True\n                continue\n            elif types_found and stripped == '}':\n                break\n            elif not types_found:\n                continue\n            constant = stripped.split(' ')[0]\n            title = constant.title().replace(\n                '_', '').replace('Hid', 'HID')\n            accessor = title[0].lower() + title[1:]\n            if not os.path.exists(os.path.join(base_path, title + '.proto')):\n                continue\n            yield MessageInfo(\n                title + '_pb2', title, accessor, constant)",
    "docstring": "Get information about all messages of interest."
  },
  {
    "code": "def check_usrmove(self, pkgs):\n        if 'filesystem' not in pkgs:\n            return os.path.islink('/bin') and os.path.islink('/sbin')\n        else:\n            filesys_version = pkgs['filesystem']['version']\n            return True if filesys_version[0] == '3' else False",
    "docstring": "Test whether the running system implements UsrMove.\n\n            If the 'filesystem' package is present, it will check that the\n            version is greater than 3. If the package is not present the\n            '/bin' and '/sbin' paths are checked and UsrMove is assumed\n            if both are symbolic links.\n\n            :param pkgs: a packages dictionary"
  },
  {
    "code": "def simultaneous_listen(self):\r\n        if self.server_con is not None:\r\n            self.server_con.s.close()\r\n            self.server_con = None\r\n        self.mappings = None\r\n        self.predictions = None\r\n        parts = self.sequential_connect()\r\n        if parts is None:\r\n            return 0\r\n        con, mappings, predictions = parts\r\n        con.blocking = 0\r\n        con.timeout = 0\r\n        con.s.settimeout(0)\r\n        self.server_con = con\r\n        self.mappings = mappings\r\n        self.predictions = predictions\r\n        msg = \"SIMULTANEOUS READY 0 0\"\r\n        ret = self.server_con.send_line(msg)\r\n        if not ret:\r\n            return 0\r\n        return 1",
    "docstring": "This function is called by passive simultaneous nodes who\r\n        wish to establish themself as such. It sets up a connection\r\n        to the Rendezvous Server to monitor for new hole punching requests."
  },
  {
    "code": "def _set_object_view(self, session):\n        for obj_name in self._object_views:\n            if self._object_views[obj_name] == PLENARY:\n                try:\n                    getattr(session, 'use_plenary_' + obj_name + '_view')()\n                except AttributeError:\n                    pass\n            else:\n                try:\n                    getattr(session, 'use_comparative_' + obj_name + '_view')()\n                except AttributeError:\n                    pass",
    "docstring": "Sets the underlying object views to match current view"
  },
  {
    "code": "def uint32_to_uint8(cls, img):\n        return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))",
    "docstring": "Cast uint32 RGB image to 4 uint8 channels."
  },
  {
    "code": "async def get_endpoint_for_did(wallet_handle: int,\n                               pool_handle: int,\n                               did: str) -> (str, Optional[str]):\n    logger = logging.getLogger(__name__)\n    logger.debug(\"get_endpoint_for_did: >>> wallet_handle: %r, pool_handle: %r, did: %r\",\n                 wallet_handle,\n                 pool_handle,\n                 did)\n    if not hasattr(get_endpoint_for_did, \"cb\"):\n        logger.debug(\"get_endpoint_for_did: Creating callback\")\n        get_endpoint_for_did.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_char_p, c_char_p))\n    c_wallet_handle = c_int32(wallet_handle)\n    c_pool_handle = c_int32(pool_handle)\n    c_did = c_char_p(did.encode('utf-8'))\n    endpoint, transport_vk = await do_call('indy_get_endpoint_for_did',\n                                           c_wallet_handle,\n                                           c_pool_handle,\n                                           c_did,\n                                           get_endpoint_for_did.cb)\n    endpoint = endpoint.decode()\n    transport_vk = transport_vk.decode() if transport_vk is not None else None\n    res = (endpoint, transport_vk)\n    logger.debug(\"get_endpoint_for_did: <<< res: %r\", res)\n    return res",
    "docstring": "Returns endpoint information for the given DID.\n\n    :param wallet_handle: Wallet handle (created by open_wallet).\n    :param pool_handle: Pool handle (created by open_pool).\n    :param did: The DID to resolve endpoint.\n    :return: (endpoint, transport_vk)"
  },
  {
    "code": "def upgrade(self, conn, skip_versions=()):\n        db_versions = self.get_db_versions(conn)\n        self.starting_version = max(db_versions)\n        to_skip = sorted(db_versions | set(skip_versions))\n        scripts = self.read_scripts(None, None, to_skip)\n        if not scripts:\n            return []\n        self.ending_version = max(s['version'] for s in scripts)\n        return self._upgrade(conn, scripts)",
    "docstring": "Upgrade the database from the current version to the maximum\n        version in the upgrade scripts.\n\n        :param conn: a DBAPI 2 connection\n        :param skip_versions: the versions to skip"
  },
  {
    "code": "def tparse(instring, lenout=_default_len_out):\n    errmsg = stypes.stringToCharP(lenout)\n    lenout = ctypes.c_int(lenout)\n    instring = stypes.stringToCharP(instring)\n    sp2000 = ctypes.c_double()\n    libspice.tparse_c(instring, lenout, ctypes.byref(sp2000), errmsg)\n    return sp2000.value, stypes.toPythonString(errmsg)",
    "docstring": "Parse a time string and return seconds past the J2000\n    epoch on a formal calendar.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tparse_c.html\n\n    :param instring: Input time string, UTC.\n    :type instring: str\n    :param lenout: Available space in output error message string.\n    :type lenout: int\n    :return: Equivalent UTC seconds past J2000, Descriptive error message.\n    :rtype: tuple"
  },
  {
    "code": "def guess_mode(self, data):\n        if data.ndim == 2:\n            return \"L\"\n        elif data.shape[-1] == 3:\n            return \"RGB\"\n        elif data.shape[-1] == 4:\n            return \"RGBA\"\n        else:\n            raise ValueError(\n                \"Un-supported shape for image conversion %s\" % list(data.shape))",
    "docstring": "Guess what type of image the np.array is representing"
  },
  {
    "code": "def create_endpoint(service_name: str, *,\n                    ipv4: OptStr = None,\n                    ipv6: OptStr = None,\n                    port: OptInt = None) -> Endpoint:\n    return Endpoint(service_name, ipv4, ipv6, port)",
    "docstring": "Factory function to create Endpoint object."
  },
  {
    "code": "def validate_card_issue_modes(issue_mode: int, cards: list) -> list:\n    supported_mask = 63\n    if not bool(issue_mode & supported_mask):\n        return []\n    for i in [1 << x for x in range(len(IssueMode))]:\n        if bool(i & issue_mode):\n            try:\n                parser_fn = cast(\n                    Callable[[list], Optional[list]],\n                    parsers[IssueMode(i).name]\n                )\n            except ValueError:\n                continue\n            parsed_cards = parser_fn(cards)\n            if not parsed_cards:\n                return []\n            cards = parsed_cards\n    return cards",
    "docstring": "validate cards against deck_issue modes"
  },
  {
    "code": "def update(self, attributes=None):\n        if attributes is None:\n            attributes = {}\n        headers = self.__class__.create_headers(attributes)\n        headers.update(self._update_headers())\n        result = self._client._put(\n            self._update_url(),\n            self.__class__.create_attributes(attributes, self),\n            headers=headers\n        )\n        self._update_from_resource(result)\n        return self",
    "docstring": "Updates the resource with attributes."
  },
  {
    "code": "def compat_py2_py3():\n    if (sys.version_info > (3, 0)):\n        def iteritems(dictionary):\n            return dictionary.items()\n        def itervalues(dictionary):\n            return dictionary.values()\n    else:\n        def iteritems(dictionary):\n            return dictionary.iteritems()\n        def itervalues(dictionary):\n            return dictionary.itervalues()\n    return iteritems, itervalues",
    "docstring": "For Python 2, 3 compatibility."
  },
  {
    "code": "def read_meminfo():\n    data = {}\n    with open(\"/proc/meminfo\", \"rb\") as meminfo_file:\n        for row in meminfo_file:\n            fields = row.split()\n            data[fields[0].decode(\"ascii\")[:-1]] = int(fields[1]) * 1024\n    return data",
    "docstring": "Returns system memory usage information.\n\n    :returns: The system memory usage.\n    :rtype: dict"
  },
  {
    "code": "def cookie_to_state(cookie_str, name, encryption_key):\n    try:\n        cookie = SimpleCookie(cookie_str)\n        state = State(cookie[name].value, encryption_key)\n    except KeyError as e:\n        msg_tmpl = 'No cookie named {name} in {data}'\n        msg = msg_tmpl.format(name=name, data=cookie_str)\n        logger.exception(msg)\n        raise SATOSAStateError(msg) from e\n    except ValueError as e:\n        msg_tmpl = 'Failed to process {name} from {data}'\n        msg = msg_tmpl.format(name=name, data=cookie_str)\n        logger.exception(msg)\n        raise SATOSAStateError(msg) from e\n    else:\n        msg_tmpl = 'Loading state from cookie {data}'\n        msg = msg_tmpl.format(data=cookie_str)\n        satosa_logging(logger, logging.DEBUG, msg, state)\n        return state",
    "docstring": "Loads a state from a cookie\n\n    :type cookie_str: str\n    :type name: str\n    :type encryption_key: str\n    :rtype: satosa.state.State\n\n    :param cookie_str: string representation of cookie/s\n    :param name: Name identifier of the cookie\n    :param encryption_key: Key to encrypt the state information\n    :return: A state"
  },
  {
    "code": "def register_archive_format(name, function, extra_args=None, description=''):\n    if extra_args is None:\n        extra_args = []\n    if not isinstance(function, collections.Callable):\n        raise TypeError('The %s object is not callable' % function)\n    if not isinstance(extra_args, (tuple, list)):\n        raise TypeError('extra_args needs to be a sequence')\n    for element in extra_args:\n        if not isinstance(element, (tuple, list)) or len(element) !=2:\n            raise TypeError('extra_args elements are : (arg_name, value)')\n    _ARCHIVE_FORMATS[name] = (function, extra_args, description)",
    "docstring": "Registers an archive format.\n\n    name is the name of the format. function is the callable that will be\n    used to create archives. If provided, extra_args is a sequence of\n    (name, value) tuples that will be passed as arguments to the callable.\n    description can be provided to describe the format, and will be returned\n    by the get_archive_formats() function."
  },
  {
    "code": "def gen_sites(path):\n    \" Seek sites by path. \"\n    for root, _, _ in walklevel(path, 2):\n        try:\n            yield Site(root)\n        except AssertionError:\n            continue",
    "docstring": "Seek sites by path."
  },
  {
    "code": "def dictionize(fields: Sequence, records: Sequence) -> Generator:\n    return (dict(zip(fields, rec)) for rec in records)",
    "docstring": "Create dictionaries mapping fields to record data."
  },
  {
    "code": "def rate(self, currency):\n        if not self._backend:\n            raise ExchangeBackendNotInstalled()\n        return self._backend.rate(currency)",
    "docstring": "Return quotation between the base and another currency"
  },
  {
    "code": "def subjects(self):\n        subj = [i[\"subject_id\"] for i in self._cache.find()]\n        return list(set(subj))",
    "docstring": "Return identifiers for all the subjects that are in the cache.\n\n        :return: list of subject identifiers"
  },
  {
    "code": "def delete_auto_scaling_group(self, name, force_delete=False):\n        if(force_delete):\n            params = {'AutoScalingGroupName': name, 'ForceDelete': 'true'}\n        else:\n            params = {'AutoScalingGroupName': name}\n        return self.get_object('DeleteAutoScalingGroup', params, Request)",
    "docstring": "Deletes the specified auto scaling group if the group has no instances\n        and no scaling activities in progress."
  },
  {
    "code": "def set_size(self, size):\n        buffer_size = self._calculate_zoom_buffer_size(size, self._zoom_level)\n        self._size = size\n        self._initialize_buffers(buffer_size)",
    "docstring": "Set the size of the map in pixels\n\n        This is an expensive operation, do only when absolutely needed.\n\n        :param size: (width, height) pixel size of camera/view of the group"
  },
  {
    "code": "def cleanup_tail(options):\n    if options.kwargs['omode'] == \"csv\":\n        options.kwargs['fd'].write(\"\\n\")\n    elif options.kwargs['omode'] == \"xml\":\n        options.kwargs['fd'].write(\"\\n</results>\\n\")\n    else:\n        options.kwargs['fd'].write(\"\\n]\\n\")",
    "docstring": "cleanup the tail of a recovery"
  },
  {
    "code": "def get_profile(session):\n    try:\n        profile = session.get(PROFILE_URL).json()\n        if 'errorCode' in profile and profile['errorCode'] == '403':\n            raise MoparError(\"not logged in\")\n        return profile\n    except JSONDecodeError:\n        raise MoparError(\"not logged in\")",
    "docstring": "Get complete profile."
  },
  {
    "code": "async def hset(self, name, key, value):\n        return await self.execute_command('HSET', name, key, value)",
    "docstring": "Set ``key`` to ``value`` within hash ``name``\n        Returns 1 if HSET created a new field, otherwise 0"
  },
  {
    "code": "def add_module_plugin_filters(self, module_plugin_filters):\n        module_plugin_filters = util.return_list(module_plugin_filters)\n        self.module_plugin_filters.extend(module_plugin_filters)",
    "docstring": "Adds `module_plugin_filters` to the internal module filters.\n        May be a single object or an iterable.\n\n        Every module filters must be a callable and take in\n        a list of plugins and their associated names."
  },
  {
    "code": "def normalize_arxiv_category(category):\n    category = _NEW_CATEGORIES.get(category.lower(), category)\n    for valid_category in valid_arxiv_categories():\n        if (category.lower() == valid_category.lower() or\n                category.lower().replace('-', '.') == valid_category.lower()):\n            return valid_category\n    return category",
    "docstring": "Normalize arXiv category to be schema compliant.\n\n    This properly capitalizes the category and replaces the dash by a dot if\n    needed. If the category is obsolete, it also gets converted it to its\n    current equivalent.\n\n    Example:\n        >>> from inspire_schemas.utils import normalize_arxiv_category\n        >>> normalize_arxiv_category('funct-an')  # doctest: +SKIP\n        u'math.FA'"
  },
  {
    "code": "def kitchen_delete(backend, kitchen):\n    click.secho('%s - Deleting kitchen %s' % (get_datetime(), kitchen), fg='green')\n    master = 'master'\n    if kitchen.lower() != master.lower():\n        check_and_print(DKCloudCommandRunner.delete_kitchen(backend.dki, kitchen))\n    else:\n        raise click.ClickException('Cannot delete the kitchen called %s' % master)",
    "docstring": "Provide the name of the kitchen to delete"
  },
  {
    "code": "def verify(self):\n        for row in range(self.nrows()):\n            result = self.verify_row(row)\n            if result != 0:\n                return result\n        return 0",
    "docstring": "Checks all parameters for invalidating conditions\n\n        :returns: str -- message if error, 0 otherwise"
  },
  {
    "code": "def default_value(self):\n        if self.name in tsdb_coded_attributes:\n            return tsdb_coded_attributes[self.name]\n        elif self.datatype == ':integer':\n            return -1\n        else:\n            return ''",
    "docstring": "Get the default value of the field."
  },
  {
    "code": "def init_chain(self):\n        if not self._hasinit:\n            self._hasinit = True\n            self._devices = []\n            self.jtag_enable()\n            while True:\n                idcode = self.rw_dr(bitcount=32, read=True,\n                                    lastbit=False)()\n                if idcode in NULL_ID_CODES: break\n                dev = self.initialize_device_from_id(self, idcode)\n                if self._debug:\n                    print(dev)\n                self._devices.append(dev)\n                if len(self._devices) >= 128:\n                    raise JTAGTooManyDevicesError(\"This is an arbitrary \"\n                        \"limit to deal with breaking infinite loops. If \"\n                        \"you have more devices, please open a bug\")\n            self.jtag_disable()\n            self._devices.reverse()",
    "docstring": "Autodetect the devices attached to the Controller, and initialize a JTAGDevice for each.\n\n        This is a required call before device specific Primitives can\n        be used."
  },
  {
    "code": "def genes_with_peak(self, peaks, transform_func=None, split=False,\n                        intersect_kwargs=None, id_attribute='ID', *args,\n                        **kwargs):\n        def _transform_func(x):\n            result = transform_func(x)\n            if isinstance(result, pybedtools.Interval):\n                result = [result]\n            for i in result:\n                if i:\n                    yield result\n        intersect_kwargs = intersect_kwargs or {}\n        if not self._cached_features:\n            self._cached_features = pybedtools\\\n                .BedTool(self.features())\\\n                .saveas()\n        if transform_func:\n            if split:\n                features = self._cached_features\\\n                    .split(_transform_func, *args, **kwargs)\n            else:\n                features = self._cached_features\\\n                    .each(transform_func, *args, **kwargs)\n        else:\n            features = self._cached_features\n        hits = list(set([i[id_attribute] for i in features.intersect(\n            peaks, **intersect_kwargs)]))\n        return self.data.index.isin(hits)",
    "docstring": "Returns a boolean index of genes that have a peak nearby.\n\n        Parameters\n        ----------\n        peaks : string or pybedtools.BedTool\n            If string, then assume it's a filename to a BED/GFF/GTF file of\n            intervals; otherwise use the pybedtools.BedTool object directly.\n\n        transform_func : callable\n            This function will be applied to each gene object returned by\n            self.features().  Additional args and kwargs are passed to\n            `transform_func`. For example, if you're looking for peaks within\n            1kb upstream of TSSs, then pybedtools.featurefuncs.TSS would be\n            a useful `transform_func`, and you could supply additional kwargs\n            of `upstream=1000` and `downstream=0`.\n\n            This function can return iterables of features, too. For example,\n            you might want to look for peaks falling within the exons of\n            a gene.  In this case, `transform_func` should return an iterable\n            of pybedtools.Interval objects.  The only requirement is that the\n            `name` field of any feature matches the index of the dataframe.\n\n        intersect_kwargs : dict\n            kwargs passed to pybedtools.BedTool.intersect.\n\n        id_attribute : str\n            The attribute in the GTF or GFF file that contains the id of the\n            gene. For meaningful results to be returned, a gene's ID be also\n            found in the index of the dataframe.\n\n            For GFF files, typically you'd use `id_attribute=\"ID\"`.  For GTF\n            files, you'd typically use `id_attribute=\"gene_id\"`."
  },
  {
    "code": "def _get_state():\n    try:\n        return pyconnman.ConnManager().get_property('State')\n    except KeyError:\n        return 'offline'\n    except dbus.DBusException as exc:\n        raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc))",
    "docstring": "Returns the state of connman"
  },
  {
    "code": "def remove_tag(self, task, params={}, **options): \n        path = \"/tasks/%s/removeTag\" % (task)\n        return self.client.post(path, params, **options)",
    "docstring": "Removes a tag from the task. Returns an empty data block.\n\n        Parameters\n        ----------\n        task : {Id} The task to remove a tag from.\n        [data] : {Object} Data for the request\n          - tag : {Id} The tag to remove from the task."
  },
  {
    "code": "def set_number(self, key, value):\n        storage = self.storage\n        if not isinstance(value, int):\n            logger.error(\"set_number: Value must be an integer\")\n            return\n        try:\n            lock.acquire()\n            storage[key] = value\n        finally:\n            self.storage._p_changed = True\n            lock.release()\n        return storage[key]",
    "docstring": "set a key's value"
  },
  {
    "code": "def on_load(target: \"EncryptableMixin\", context):\n    decrypt, plaintext = decrypt_instance(target)\n    if decrypt:\n        target.plaintext = plaintext",
    "docstring": "Intercept SQLAlchemy's instance load event."
  },
  {
    "code": "def removeCallback(cls, eventType, func, record=None):\n        callbacks = cls.callbacks()\n        callbacks.setdefault(eventType, [])\n        for i in xrange(len(callbacks[eventType])):\n            my_func, my_record, _ = callbacks[eventType][i]\n            if func == my_func and record == my_record:\n                del callbacks[eventType][i]\n                break",
    "docstring": "Removes a callback from the model's event callbacks.\n\n        :param  eventType: <str>\n        :param  func: <callable>"
  },
  {
    "code": "def describe_api_stages(restApiId, deploymentId, region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        stages = conn.get_stages(restApiId=restApiId, deploymentId=deploymentId)\n        return {'stages': [_convert_datetime_str(stage) for stage in stages['item']]}\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Get all API stages for a given apiID and deploymentID\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_apigateway.describe_api_stages restApiId deploymentId"
  },
  {
    "code": "def log_parameter_and_gradient_statistics(self,\n                                              model: Model,\n                                              batch_grad_norm: float) -> None:\n        if self._should_log_parameter_statistics:\n            for name, param in model.named_parameters():\n                self.add_train_scalar(\"parameter_mean/\" + name, param.data.mean())\n                self.add_train_scalar(\"parameter_std/\" + name, param.data.std())\n                if param.grad is not None:\n                    if param.grad.is_sparse:\n                        grad_data = param.grad.data._values()\n                    else:\n                        grad_data = param.grad.data\n                    if torch.prod(torch.tensor(grad_data.shape)).item() > 0:\n                        self.add_train_scalar(\"gradient_mean/\" + name, grad_data.mean())\n                        self.add_train_scalar(\"gradient_std/\" + name, grad_data.std())\n                    else:\n                        logger.info(\"No gradient for %s, skipping tensorboard logging.\", name)\n            if batch_grad_norm is not None:\n                self.add_train_scalar(\"gradient_norm\", batch_grad_norm)",
    "docstring": "Send the mean and std of all parameters and gradients to tensorboard, as well\n        as logging the average gradient norm."
  },
  {
    "code": "def has_isotropic_cells(self):\n        return self.is_uniform and np.allclose(self.cell_sides[:-1],\n                                               self.cell_sides[1:])",
    "docstring": "``True`` if `grid` is uniform and `cell_sides` are all equal.\n\n        Always ``True`` for 1D partitions.\n\n        Examples\n        --------\n        >>> part = uniform_partition([0, -1], [1, 1], (5, 10))\n        >>> part.has_isotropic_cells\n        True\n        >>> part = uniform_partition([0, -1], [1, 1], (5, 5))\n        >>> part.has_isotropic_cells\n        False"
  },
  {
    "code": "def _set_proxy_filter(warningstuple):\n    if len(warningstuple) > 5:\n        key = len(_proxy_map)+1\n        _proxy_map[key] = warningstuple\n        return ('always', re_matchall, ProxyWarning, re_matchall, key)\n    else:\n        return warningstuple",
    "docstring": "set up a proxy that store too long warnings in a separate map"
  },
  {
    "code": "def matches_pattern(self, other):\n        if hasattr(other, 'messageType'):\n            messageTypeIsEqual = False\n            if self.messageType is None or other.messageType is None:\n                messageTypeIsEqual = True\n            else:\n                messageTypeIsEqual = (self.messageType == other.messageType)\n            extendedIsEqual = False\n            if self.extended is None or other.extended is None:\n                extendedIsEqual = True\n            else:\n                extendedIsEqual = (self.extended == other.extended)\n            return messageTypeIsEqual and extendedIsEqual\n        return False",
    "docstring": "Test if current message match a patterns or template."
  },
  {
    "code": "def Execute(self, *params, **kw):\n        fp = self.__expandparamstodict(params, kw)\n        return self._get_subfolder('execute/', GPExecutionResult, fp)",
    "docstring": "Synchronously execute the specified GP task. Parameters are passed\n           in either in order or as keywords."
  },
  {
    "code": "def add_bond(self, name, ifaces, bond_mode=None, lacp=None):\n        assert len(ifaces) >= 2\n        options = ''\n        if bond_mode:\n            options += 'bond_mode=%(bond_mode)s' % locals()\n        if lacp:\n            options += 'lacp=%(lacp)s' % locals()\n        command_add = ovs_vsctl.VSCtlCommand(\n            'add-bond', (self.br_name, name, ifaces), options)\n        self.run_command([command_add])",
    "docstring": "Creates a bonded port.\n\n        :param name: Port name to be created\n        :param ifaces: List of interfaces containing at least 2 interfaces\n        :param bond_mode: Bonding mode (active-backup, balance-tcp\n                          or balance-slb)\n        :param lacp: LACP mode (active, passive or off)"
  },
  {
    "code": "def _build_install_args(options):\n    install_args = []\n    if options.user_install:\n        if sys.version_info < (2, 6):\n            log.warn('--user requires Python 2.6 or later')\n            raise SystemExit(1)\n        install_args.append('--user')\n    return install_args",
    "docstring": "Build the arguments to 'python setup.py install' on the setuptools package"
  },
  {
    "code": "def delete_content(self, max_chars=100):\n        def delete_content_element():\n            chars_deleted = 0\n            while len(self.get_attribute('value')) > 0 and chars_deleted < max_chars:\n                self.click()\n                self.send_keys(Keys.HOME)\n                self.send_keys(Keys.DELETE)\n                chars_deleted += 1\n        self.execute_and_handle_webelement_exceptions(delete_content_element, 'delete input contents')\n        return self",
    "docstring": "Deletes content in the input field by repeatedly typing HOME, then DELETE\n\n        @rtype:     WebElementWrapper\n        @return:    Returns itself"
  },
  {
    "code": "def async_from_options(options):\n    _type = options.pop('_type', 'furious.async.Async')\n    _type = path_to_reference(_type)\n    return _type.from_dict(options)",
    "docstring": "Deserialize an Async or Async subclass from an options dict."
  },
  {
    "code": "def chunks(iterable, size=100):\n    it = iter(iterable)\n    size -= 1\n    for head in it:\n        yield itertools.chain([head], itertools.islice(it, size))",
    "docstring": "Turns the given iterable into chunks of the specified size,\n    which is 100 by default since that's what Telegram uses the most."
  },
  {
    "code": "def write(self, p_todos):\n        todofile = codecs.open(self.path, 'w', encoding=\"utf-8\")\n        if p_todos is list:\n            for todo in p_todos:\n                todofile.write(str(todo))\n        else:\n            todofile.write(p_todos)\n        todofile.write(\"\\n\")\n        todofile.close()",
    "docstring": "Writes all the todo items to the todo.txt file.\n\n        p_todos can be a list of todo items, or a string that is just written\n        to the file."
  },
  {
    "code": "def createSuperimposedSensorySDRs(sequenceSensations, objectSensations):\n  assert len(sequenceSensations) == len(objectSensations)\n  superimposedSensations = []\n  for i, objectSensation in enumerate(objectSensations):\n    newSensation = {\n      0: (objectSensation[0][0],\n          sequenceSensations[i][0][1].union(objectSensation[0][1]))\n    }\n    superimposedSensations.append(newSensation)\n  return superimposedSensations",
    "docstring": "Given two lists of sensations, create a new list where the sensory SDRs are\n  union of the individual sensory SDRs. Keep the location SDRs from the object.\n\n  A list of sensations has the following format:\n  [\n    {\n      0: (set([1, 5, 10]), set([6, 12, 52]),  # location, feature for CC0\n    },\n    {\n      0: (set([5, 46, 50]), set([8, 10, 11]),  # location, feature for CC0\n    },\n  ]\n\n  We assume there is only one cortical column, and that the two input lists have\n  identical length."
  },
  {
    "code": "def regions():\n    return [RDSRegionInfo(name='us-east-1',\n                          endpoint='rds.us-east-1.amazonaws.com'),\n            RDSRegionInfo(name='eu-west-1',\n                          endpoint='rds.eu-west-1.amazonaws.com'),\n            RDSRegionInfo(name='us-west-1',\n                          endpoint='rds.us-west-1.amazonaws.com'),\n            RDSRegionInfo(name='us-west-2',\n                          endpoint='rds.us-west-2.amazonaws.com'),\n            RDSRegionInfo(name='sa-east-1',\n                          endpoint='rds.sa-east-1.amazonaws.com'),\n            RDSRegionInfo(name='ap-northeast-1',\n                          endpoint='rds.ap-northeast-1.amazonaws.com'),\n            RDSRegionInfo(name='ap-southeast-1',\n                          endpoint='rds.ap-southeast-1.amazonaws.com')\n            ]",
    "docstring": "Get all available regions for the RDS service.\n\n    :rtype: list\n    :return: A list of :class:`boto.rds.regioninfo.RDSRegionInfo`"
  },
  {
    "code": "def render(self, namespace):\n        return self._text.format_map(namespace.dictionary) \\\n            if self._need_format else self._text",
    "docstring": "Render template lines.\n\n        Note: we only need to parse the namespace if we used variables in\n              this part of the template."
  },
  {
    "code": "def isoformat(self):\n        text = [self.strftime('%Y-%m-%dT%H:%M:%S'), ]\n        if self.tzinfo:\n            text.append(self.tzinfo.as_timezone())\n        else:\n            text.append('+00:00')\n        return ''.join(text)",
    "docstring": "Generate an ISO 8601 formatted time stamp.\n\n        Returns:\n            str: `ISO 8601`_ formatted time stamp\n\n        .. _ISO 8601: http://www.cl.cam.ac.uk/~mgk25/iso-time.html"
  },
  {
    "code": "def delete_room(room, reason=''):\n    if room.custom_server:\n        return\n    def _delete_room(xmpp):\n        muc = xmpp.plugin['xep_0045']\n        muc.destroy(room.jid, reason=reason)\n    current_plugin.logger.info('Deleting room %s', room.jid)\n    _execute_xmpp(_delete_room)\n    delete_logs(room)",
    "docstring": "Deletes a MUC room from the XMPP server."
  },
  {
    "code": "def get_files (dirname):\n    for entry in os.listdir(dirname):\n        fullentry = os.path.join(dirname, entry)\n        if os.path.islink(fullentry):\n            continue\n        if os.path.isfile(fullentry):\n            yield entry\n        elif os.path.isdir(fullentry):\n            yield entry+\"/\"",
    "docstring": "Get iterator of entries in directory. Only allows regular files\n    and directories, no symlinks."
  },
  {
    "code": "def _getLayer(self, name, **kwargs):\n        for glyph in self.layers:\n            if glyph.layer.name == name:\n                return glyph\n        raise ValueError(\"No layer named '%s' in glyph '%s'.\"\n                         % (name, self.name))",
    "docstring": "name will be a string, but there may not be a\n        layer with a name matching the string. If not,\n        a ``ValueError`` must be raised.\n\n        Subclasses may override this method."
  },
  {
    "code": "def _checkResponseNumberOfRegisters(payload, numberOfRegisters):\n    _checkString(payload, minlength=4, description='payload')\n    _checkInt(numberOfRegisters, minvalue=1, maxvalue=0xFFFF, description='numberOfRegisters')\n    BYTERANGE_FOR_NUMBER_OF_REGISTERS = slice(2, 4)\n    bytesForNumberOfRegisters = payload[BYTERANGE_FOR_NUMBER_OF_REGISTERS]\n    receivedNumberOfWrittenReisters = _twoByteStringToNum(bytesForNumberOfRegisters)\n    if receivedNumberOfWrittenReisters != numberOfRegisters:\n        raise ValueError('Wrong number of registers to write in the response: {0}, but commanded is {1}. The data payload is: {2!r}'.format( \\\n            receivedNumberOfWrittenReisters, numberOfRegisters, payload))",
    "docstring": "Check that the number of written registers as given in the response is correct.\n\n    The bytes 2 and 3 (zero based counting) in the payload holds the value.\n\n    Args:\n        * payload (string): The payload\n        * numberOfRegisters (int): Number of registers that have been written\n\n    Raises:\n        TypeError, ValueError"
  },
  {
    "code": "def fetch(url, dest, force=False):\n    cached = True\n    if force or not os.path.exists(dest):\n        cached = False\n        r = requests.get(url, stream=True)\n        if r.status_code == 200:\n            with open(dest, 'wb') as f:\n                for chunk in r.iter_content(1024):\n                    f.write(chunk)\n    return cached, dest",
    "docstring": "Retrieve data from an url and store it into dest.\n\n    Parameters\n    ----------\n    url: str\n        Link to the remote data\n    dest: str\n        Path where the file must be stored\n    force: bool (default=False)\n        Overwrite if the file exists\n\n    Returns\n    -------\n    cached: bool\n        True if the file already exists\n    dest: str\n        The same string of the parameter"
  },
  {
    "code": "def on_connection_open(self, connection):\n        LOGGER.debug('Connection opened')\n        connection.add_on_connection_blocked_callback(\n            self.on_connection_blocked)\n        connection.add_on_connection_unblocked_callback(\n            self.on_connection_unblocked)\n        connection.add_backpressure_callback(self.on_back_pressure_detected)\n        self.channel = self._open_channel()",
    "docstring": "This method is called by pika once the connection to RabbitMQ has\n        been established.\n\n        :type connection: pika.TornadoConnection"
  },
  {
    "code": "def _call(self, x):\n        out = x.asarray().ravel()[self._indices_flat]\n        if self.variant == 'point_eval':\n            weights = 1.0\n        elif self.variant == 'integrate':\n            weights = getattr(self.domain, 'cell_volume', 1.0)\n        else:\n            raise RuntimeError('bad variant {!r}'.format(self.variant))\n        if weights != 1.0:\n            out *= weights\n        return out",
    "docstring": "Return values at indices, possibly weighted."
  },
  {
    "code": "def _next(self, **kwargs):\n        spec = self._pagination_default_spec(kwargs)\n        spec.update(kwargs)\n        query = queries.build_query(spec)\n        query = queries.where_after_entry(query, self._record)\n        for record in query.order_by(model.Entry.local_date,\n                                     model.Entry.id)[:1]:\n            return Entry(record)\n        return None",
    "docstring": "Get the next item in any particular category"
  },
  {
    "code": "async def _connect(self, hostname, port, reconnect=False, channels=[],\n                       encoding=protocol.DEFAULT_ENCODING, source_address=None):\n        if not reconnect or not self.connection:\n            self._autojoin_channels = channels\n            self.connection = connection.Connection(hostname, port, source_address=source_address,\n                                                    eventloop=self.eventloop)\n            self.encoding = encoding\n        await self.connection.connect()",
    "docstring": "Connect to IRC host."
  },
  {
    "code": "def add_patchs_to_build_without_pkg_config(self, lib_dir, include_dir):\n        additional_patches = [\n            {\n                'src': r\"pkgconfig\\('--libs-only-L'\\)\",\n                'dest': \"['{0}']\".format(lib_dir),\n            },\n            {\n                'src': r\"pkgconfig\\('--libs(-only-l)?'\\)\",\n                'dest': \"['rpm', 'rpmio']\",\n                'required': True,\n            },\n            {\n                'src': r\"pkgconfig\\('--cflags'\\)\",\n                'dest': \"['{0}']\".format(include_dir),\n                'required': True,\n            },\n        ]\n        self.patches.extend(additional_patches)",
    "docstring": "Add patches to remove pkg-config command and rpm.pc part.\n\n        Replace with given library_path: lib_dir and include_path: include_dir\n        without rpm.pc file."
  },
  {
    "code": "def _join_results(self, results, coarse, join):\n    rval = OrderedDict()\n    i_keys = set()\n    for res in results:\n      i_keys.update( res.keys() )\n    for i_key in sorted(i_keys):\n      if coarse:\n        rval[i_key] = join( [res.get(i_key) for res in results] )\n      else:\n        rval[i_key] = OrderedDict()\n        r_keys = set()\n        for res in results:\n          r_keys.update( res.get(i_key,{}).keys() )\n        for r_key in sorted(r_keys):\n          rval[i_key][r_key] = join( [res.get(i_key,{}).get(r_key) for res in results] )\n    return rval",
    "docstring": "Join a list of results. Supports both get and series."
  },
  {
    "code": "def apply_groups(cls, obj, options=None, backend=None, clone=True, **kwargs):\n        if isinstance(options, basestring):\n            from ..util.parser import OptsSpec\n            try:\n                options = OptsSpec.parse(options)\n            except SyntaxError:\n                options = OptsSpec.parse(\n                    '{clsname} {options}'.format(clsname=obj.__class__.__name__,\n                                                 options=options))\n        if kwargs:\n            options = cls._group_kwargs_to_options(obj, kwargs)\n        for backend, backend_opts in cls._grouped_backends(options, backend):\n            obj = cls._apply_groups_to_backend(obj, backend_opts, backend, clone)\n        return obj",
    "docstring": "Applies nested options definition grouped by type.\n\n        Applies options on an object or nested group of objects,\n        returning a new object with the options applied. This method\n        accepts the separate option namespaces explicitly (i.e 'plot',\n        'style' and 'norm').\n\n        If the options are to be set directly on the object a\n        simple format may be used, e.g.:\n\n            opts.apply_groups(obj, style={'cmap': 'viridis'},\n                                         plot={'show_title': False})\n\n        If the object is nested the options must be qualified using\n        a type[.group][.label] specification, e.g.:\n\n            opts.apply_groups(obj, {'Image': {'plot':  {'show_title': False},\n                                              'style': {'cmap': 'viridis}}})\n\n        If no opts are supplied all options on the object will be reset.\n\n        Args:\n            options (dict): Options specification\n                Options specification should be indexed by\n                type[.group][.label] or option type ('plot', 'style',\n                'norm').\n            backend (optional): Backend to apply options to\n                Defaults to current selected backend\n            clone (bool, optional): Whether to clone object\n                Options can be applied inplace with clone=False\n            **kwargs: Keywords of options by type\n                Applies options directly to the object by type\n                (e.g. 'plot', 'style', 'norm') specified as\n                dictionaries.\n\n        Returns:\n            Returns the object or a clone with the options applied"
  },
  {
    "code": "def flags(flags):\n        names = sorted(\n            descr for key, descr in OpCodeDebug.STREAM_CONSTANT.items() if key & flags\n        )\n        return \", \".join(names)",
    "docstring": "Returns the names of the class description flags found in the given\n        integer\n\n        :param flags: A class description flag entry\n        :return: The flags names as a single string"
  },
  {
    "code": "def log_warn(message, args):\n    get_logger(DEFAULT_LOGGER, log_creation=False).log(logging.WARNING, message, *args)",
    "docstring": "Logs a warning message using the default logger."
  },
  {
    "code": "def delete_database(client, db_name, username=None, password=None):\n    (username, password) = get_user_creds(username, password)\n    sys_db = client.db(\"_system\", username=username, password=password)\n    try:\n        return sys_db.delete_database(db_name)\n    except Exception:\n        log.warn(\"No arango database {db_name} to delete, does not exist\")",
    "docstring": "Delete Arangodb database"
  },
  {
    "code": "def addCmdClass(self, ctor, **opts):\n        item = ctor(self, **opts)\n        name = item.getCmdName()\n        self.cmds[name] = item",
    "docstring": "Add a Cmd subclass to this cli."
  },
  {
    "code": "def to_python(value, seen=None):\n  seen = seen or set()\n  if isinstance(value, framework.TupleLike):\n    if value.ident in seen:\n      raise RecursionException('to_python: infinite recursion while evaluating %r' % value)\n    new_seen = seen.union([value.ident])\n    return {k: to_python(value[k], seen=new_seen) for k in value.exportable_keys()}\n  if isinstance(value, dict):\n    return {k: to_python(value[k], seen=seen) for k in value.keys()}\n  if isinstance(value, list):\n    return [to_python(x, seen=seen) for x in value]\n  return value",
    "docstring": "Reify values to their Python equivalents.\n\n  Does recursion detection, failing when that happens."
  },
  {
    "code": "def rvs(df, gamma, n):\n        if type(n) == list:\n            u = np.random.uniform(size=n[0]*n[1])\n            result = Skewt.ppf(q=u, df=df, gamma=gamma)\n            result = np.split(result,n[0])\n            return np.array(result)\n        else:\n            u = np.random.uniform(size=n)\n            if isinstance(df, np.ndarray) or isinstance(gamma, np.ndarray):\n                return np.array([Skewt.ppf(q=np.array([u[i]]), df=df[i], gamma=gamma[i])[0] for i in range(n)])\n            else:\n                return Skewt.ppf(q=u, df=df, gamma=gamma)",
    "docstring": "Generates random variables from a Skew t distribution\n\n        Parameters\n        ----------  \n        df : float\n            degrees of freedom parameter\n\n        gamma : float\n            skewness parameter\n\n        n : int or list\n            Number of simulations to perform; if list input, produces array"
  },
  {
    "code": "async def unload_by_path(self, path):\n        p, module = findModule(path, False)\n        if module is None:\n            raise ModuleLoadException('Cannot find module: ' + repr(path))\n        return await self.unloadmodule(module)",
    "docstring": "Unload a module by full path. Dependencies are automatically unloaded if they are marked to be\n        services."
  },
  {
    "code": "def _parse_text(self, element_name, namespace=''):\n        try:\n            text = self._channel.find('.//' + namespace + element_name).text\n        except AttributeError:\n            raise Exception(\n                'Element, {0} not found in RSS feed'.format(element_name)\n            )\n        return text",
    "docstring": "Returns the text, as a string, of the specified element in the specified\n        namespace of the RSS feed.\n\n        Takes element_name and namespace as strings."
  },
  {
    "code": "def ensure_namespace(self, name):\n        if name not in self.namespaces:\n            self.namespaces[name] = ApiNamespace(name)\n        return self.namespaces[name]",
    "docstring": "Only creates a namespace if it hasn't yet been defined.\n\n        :param str name: Name of the namespace.\n\n        :return ApiNamespace:"
  },
  {
    "code": "def reorder_distance(p_atoms, q_atoms, p_coord, q_coord):\n    unique_atoms = np.unique(p_atoms)\n    view_reorder = np.zeros(q_atoms.shape, dtype=int)\n    for atom in unique_atoms:\n        p_atom_idx, = np.where(p_atoms == atom)\n        q_atom_idx, = np.where(q_atoms == atom)\n        A_coord = p_coord[p_atom_idx]\n        B_coord = q_coord[q_atom_idx]\n        A_norms = np.linalg.norm(A_coord, axis=1)\n        B_norms = np.linalg.norm(B_coord, axis=1)\n        reorder_indices_A = np.argsort(A_norms)\n        reorder_indices_B = np.argsort(B_norms)\n        translator = np.argsort(reorder_indices_A)\n        view = reorder_indices_B[translator]\n        view_reorder[p_atom_idx] = q_atom_idx[view]\n    return view_reorder",
    "docstring": "Re-orders the input atom list and xyz coordinates by atom type and then by\n    distance of each atom from the centroid.\n\n    Parameters\n    ----------\n    atoms : array\n        (N,1) matrix, where N is points holding the atoms' names\n    coord : array\n        (N,D) matrix, where N is points and D is dimension\n\n    Returns\n    -------\n    atoms_reordered : array\n        (N,1) matrix, where N is points holding the ordered atoms' names\n    coords_reordered : array\n        (N,D) matrix, where N is points and D is dimension (rows re-ordered)"
  },
  {
    "code": "def by_phone(self, phone, cc=None):\n        header, content = self._http_request(self.BASE_URL, phone=phone, cc=cc)\n        return json.loads(content)",
    "docstring": "Perform a Yelp Phone API Search based on phone number given.\n\n        Args:\n          phone    - Phone number to search by\n          cc       - ISO 3166-1 alpha-2 country code. (Optional)"
  },
  {
    "code": "def reload(self):\n        try:\n            data = self._api.get(self.href, append_base=False).json()\n            resource = File(api=self._api, **data)\n        except Exception:\n            try:\n                data = self._api.get(\n                    self._URL['get'].format(id=self.id)).json()\n                resource = File(api=self._api, **data)\n            except Exception:\n                raise SbgError('Resource can not be refreshed!')\n        self._data = resource._data\n        self._dirty = resource._dirty\n        self._old = copy.deepcopy(self._data.data)\n        try:\n            delattr(self, '_method')\n        except AttributeError:\n            pass",
    "docstring": "Refreshes the file with the data from the server."
  },
  {
    "code": "def save(self, path, group=None):\n        ext = _os.path.splitext(path)[1]\n        if ext == '.npy':\n            _numpy.save(path, self.numpy())\n        elif ext == '.txt':\n            if self.kind == 'real':\n                _numpy.savetxt(path, self.numpy())\n            elif self.kind == 'complex':\n                output = _numpy.vstack((self.numpy().real,\n                                        self.numpy().imag)).T\n                _numpy.savetxt(path, output)\n        elif ext == '.hdf':\n            key = 'data' if group is None else group\n            f = h5py.File(path)\n            f.create_dataset(key, data=self.numpy(), compression='gzip',\n                             compression_opts=9, shuffle=True)\n        else:\n            raise ValueError('Path must end with .npy, .txt, or .hdf')",
    "docstring": "Save array to a Numpy .npy, hdf, or text file. When saving a complex array as\n        text, the real and imaginary parts are saved as the first and second\n        column respectively. When using hdf format, the data is stored\n        as a single vector, along with relevant attributes.\n\n        Parameters\n        ----------\n        path: string\n            Destination file path. Must end with either .hdf, .npy or .txt.\n            \n        group: string \n            Additional name for internal storage use. Ex. hdf storage uses\n            this as the key value.\n\n        Raises\n        ------\n        ValueError\n            If path does not end in .npy or .txt."
  },
  {
    "code": "def missed_statements(self, filename):\n        el = self._get_class_element_by_filename(filename)\n        lines = el.xpath('./lines/line[@hits=0]')\n        return [int(l.attrib['number']) for l in lines]",
    "docstring": "Return a list of uncovered line numbers for each of the missed\n        statements found for the file `filename`."
  },
  {
    "code": "def identical(self, a, b):\n        return self._identical(self.convert(a), self.convert(b))",
    "docstring": "This should return whether `a` is identical to `b`. Of course, this isn't always clear. True should mean that it\n        is definitely identical. False eans that, conservatively, it might not be.\n\n        :param a: an AST\n        :param b: another AST"
  },
  {
    "code": "def _get_rev(self, fpath):\n        rev = None\n        try:\n            cmd = [\"git\", \"log\", \"-n1\", \"--pretty=format:\\\"%h\\\"\", fpath]\n            rev = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()[0]\n        except:\n            pass\n        if not rev:\n            try:\n                cmd = [\"svn\", \"info\", fpath]\n                svninfo = Popen(cmd,\n                                stdout=PIPE,\n                                stderr=PIPE).stdout.readlines()\n                for info in svninfo:\n                    tokens = info.split(\":\")\n                    if tokens[0].strip() == \"Last Changed Rev\":\n                        rev = tokens[1].strip()\n            except:\n                pass\n        return rev",
    "docstring": "Get an SCM version number. Try svn and git."
  },
  {
    "code": "def get_path(self, path, query=None):\n        return self.get(self.url_path(path), query)",
    "docstring": "Make a GET request, optionally including a query, to a relative path.\n\n        The path of the request includes a path on top of the base URL\n        assigned to the endpoint.\n\n        Parameters\n        ----------\n        path : str\n            The path to request, relative to the endpoint\n        query : DataQuery, optional\n            The query to pass when making the request\n\n        Returns\n        -------\n        resp : requests.Response\n            The server's response to the request\n\n        See Also\n        --------\n        get_query, get, url_path"
  },
  {
    "code": "def data(self, data, part=False, dataset=''):\n        links = self.parser(self.scanner(data, part), part, dataset)\n        self.storage.add_links(links)",
    "docstring": "Parse data and update links.\n\n        Parameters\n        ----------\n        data\n            Data to parse.\n        part : `bool`, optional\n            True if data is partial (default: `False`).\n        dataset : `str`, optional\n            Dataset key prefix (default: '')."
  },
  {
    "code": "def get_prebuilt_targets(build_context):\n    logger.info('Scanning for cached base images')\n    contained_deps = set()\n    required_deps = set()\n    cached_descendants = CachedDescendants(build_context.target_graph)\n    for target_name, target in build_context.targets.items():\n        if 'image_caching_behavior' not in target.props:\n            continue\n        image_name = get_image_name(target)\n        image_tag = target.props.image_tag\n        icb = ImageCachingBehavior(image_name, image_tag,\n                                   target.props.image_caching_behavior)\n        target.image_id = handle_build_cache(build_context.conf, image_name,\n                                             image_tag, icb)\n        if target.image_id:\n            image_deps = cached_descendants.get(target_name)\n            contained_deps.update(image_deps)\n            contained_deps.add(target.name)\n        else:\n            image_deps = cached_descendants.get(target_name)\n            base_image_deps = cached_descendants.get(target.props.base_image)\n            required_deps.update(image_deps - base_image_deps)\n    return contained_deps - required_deps",
    "docstring": "Return set of target names that are contained within cached base images\n\n    These targets may be considered \"pre-built\", and skipped during build."
  },
  {
    "code": "def runWizard( self ):\r\n        plugin = self.currentPlugin()\r\n        if ( plugin and plugin.runWizard(self) ):\r\n            self.accept()",
    "docstring": "Runs the current wizard."
  },
  {
    "code": "def validate_session(self, client, session):\n        if session:\n            if session._client is not client:\n                raise InvalidOperation(\n                    'Can only use session with the MongoClient that'\n                    ' started it')\n            if session._authset != self.authset:\n                raise InvalidOperation(\n                    'Cannot use session after authenticating with different'\n                    ' credentials')",
    "docstring": "Validate this session before use with client.\n\n        Raises error if this session is logged in as a different user or\n        the client is not the one that created the session."
  },
  {
    "code": "def _amplitude_bounds(counts, bkg, model):\n    if isinstance(counts, list):\n        counts = np.concatenate([t.flat for t in counts])\n        bkg = np.concatenate([t.flat for t in bkg])\n        model = np.concatenate([t.flat for t in model])\n    s_model = np.sum(model)\n    s_counts = np.sum(counts)\n    sn = bkg / model\n    imin = np.argmin(sn)\n    sn_min = sn[imin]\n    c_min = counts[imin]\n    b_min = c_min / s_model - sn_min\n    b_max = s_counts / s_model - sn_min\n    return max(b_min, 0), b_max",
    "docstring": "Compute bounds for the root of `_f_cash_root_cython`.\n\n    Parameters\n    ----------\n    counts : `~numpy.ndarray`\n        Count map.\n    bkg : `~numpy.ndarray`\n        Background map.\n    model : `~numpy.ndarray`\n        Source template (multiplied with exposure)."
  },
  {
    "code": "def backward(self):\n        if not self.filt:\n            self.forward()\n        self.smth = [self.filt[-1]]\n        log_trans = np.log(self.hmm.trans_mat)\n        ctg = np.zeros(self.hmm.dim)\n        for filt, next_ft in reversed(list(zip(self.filt[:-1], \n                                               self.logft[1:]))):\n            new_ctg = np.empty(self.hmm.dim)\n            for k in range(self.hmm.dim):\n                new_ctg[k] = rs.log_sum_exp(log_trans[k, :] + next_ft + ctg)\n            ctg = new_ctg\n            smth = rs.exp_and_normalise(np.log(filt) + ctg)\n            self.smth.append(smth)\n        self.smth.reverse()",
    "docstring": "Backward recursion. \n\n        Upon completion, the following list of length T is available: \n        * smth: marginal smoothing probabilities\n\n        Note\n        ----\n        Performs the forward step in case it has not been performed before."
  },
  {
    "code": "def returner(ret):\n    setup = _get_options(ret)\n    log.debug('highstate setup %s', setup)\n    report, failed = _generate_report(ret, setup)\n    if report:\n        _produce_output(report, failed, setup)",
    "docstring": "Check highstate return information and possibly fire off an email\n    or save a file."
  },
  {
    "code": "def _Dhcpcd(self, interfaces, logger):\n    for interface in interfaces:\n      dhcpcd = ['/sbin/dhcpcd']\n      try:\n        subprocess.check_call(dhcpcd + ['-x', interface])\n      except subprocess.CalledProcessError:\n        logger.info('Dhcpcd not yet running for interface %s.', interface)\n      try:\n        subprocess.check_call(dhcpcd + [interface])\n      except subprocess.CalledProcessError:\n        logger.warning('Could not activate interface %s.', interface)",
    "docstring": "Use dhcpcd to activate the interfaces.\n\n    Args:\n      interfaces: list of string, the output device names to enable.\n      logger: logger object, used to write to SysLog and serial port."
  },
  {
    "code": "def _decode_datetime(obj):\n    if '__datetime__' in obj:\n        obj = datetime.datetime.strptime(obj['as_str'].decode(), \"%Y%m%dT%H:%M:%S.%f\")\n    return obj",
    "docstring": "Decode a msgpack'ed datetime."
  },
  {
    "code": "def _upd_unused(self, what):\n        builder = getattr(self, '_{}_builder'.format(what))\n        updtrig = getattr(self, '_trigger_upd_unused_{}s'.format(what))\n        builder.unbind(decks=updtrig)\n        funcs = OrderedDict()\n        cards = list(self._action_builder.decks[1])\n        cards.reverse()\n        for card in cards:\n            funcs[card.ud['funcname']] = card\n        for card in self._action_builder.decks[0]:\n            if card.ud['funcname'] not in funcs:\n                funcs[card.ud['funcname']] = card.copy()\n        unused = list(funcs.values())\n        unused.reverse()\n        builder.decks[1] = unused\n        builder.bind(decks=updtrig)",
    "docstring": "Make sure to have exactly one copy of every valid function in the\n        \"unused\" pile on the right.\n\n        Doesn't read from the database.\n\n        :param what: a string, 'trigger', 'prereq', or 'action'"
  },
  {
    "code": "def include_items(items, any_all=any, ignore_case=False, normalize_values=False, **kwargs):\n\tif kwargs:\n\t\tmatch = functools.partial(\n\t\t\t_match_item, any_all=any_all, ignore_case=ignore_case, normalize_values=normalize_values, **kwargs\n\t\t)\n\t\treturn filter(match, items)\n\telse:\n\t\treturn iter(items)",
    "docstring": "Include items by matching metadata.\n\n\tNote:\n\t\tMetadata values are lowercased when ``normalized_values`` is ``True``,\n\t\tso ``ignore_case`` is automatically set to ``True``.\n\n\tParameters:\n\t\titems (list): A list of item dicts or filepaths.\n\t\tany_all (callable): A callable to determine if any or all filters must match to include items.\n\t\t\tExpected values :obj:`any` (default) or :obj:`all`.\n\t\tignore_case (bool): Perform case-insensitive matching.\n\t\t\tDefault: ``False``\n\t\tnormalize_values (bool): Normalize metadata values to remove common differences between sources.\n\t\t\tDefault: ``False``\n\t\tkwargs (list): Lists of values to match the given metadata field.\n\n\tYields:\n\t\tdict: The next item to be included.\n\n\tExample:\n\t\t>>> from google_music_utils import exclude_items\n\t\t>>> list(include_items(song_list, any_all=all, ignore_case=True, normalize_values=True, artist=['Beck'], album=['Odelay']))"
  },
  {
    "code": "def coupl_model1(self):\n        self.Coupl[0,0] = np.abs(self.Coupl[0,0])\n        self.Coupl[0,1] = -np.abs(self.Coupl[0,1])\n        self.Coupl[1,1] = np.abs(self.Coupl[1,1])",
    "docstring": "In model 1, we want enforce the following signs\n            on the couplings. Model 2 has the same couplings\n            but arbitrary signs."
  },
  {
    "code": "def a_capture_show_configuration_failed(ctx):\n    result = ctx.device.send(\"show configuration failed\")\n    ctx.device.last_command_result = result\n    index = result.find(\"SEMANTIC ERRORS\")\n    ctx.device.chain.connection.emit_message(result, log_level=logging.ERROR)\n    if index > 0:\n        raise ConfigurationSemanticErrors(result)\n    else:\n        raise ConfigurationErrors(result)",
    "docstring": "Capture the show configuration failed result."
  },
  {
    "code": "def get_logical_drives(self):\n        logical_drives = []\n        for controller in self.controllers:\n            for array in controller.raid_arrays:\n                for logical_drive in array.logical_drives:\n                    logical_drives.append(logical_drive)\n        return logical_drives",
    "docstring": "Get all the RAID logical drives in the Server.\n\n        This method returns all the RAID logical drives on the server\n        by examining all the controllers.\n\n        :returns: a list of LogicalDrive objects."
  },
  {
    "code": "def close(self, code=1000, message=''):\n        try:\n            message = self._encode_bytes(message)\n            self.send_frame(\n                struct.pack('!H%ds' % len(message), code, message),\n                opcode=self.OPCODE_CLOSE)\n        except WebSocketError:\n            logger.debug(\"Failed to write closing frame -> closing socket\")\n        finally:\n            logger.debug(\"Closed WebSocket\")\n            self._closed = True\n            self.stream = None",
    "docstring": "Close the websocket and connection, sending the specified code and\n        message.  The underlying socket object is _not_ closed, that is the\n        responsibility of the initiator."
  },
  {
    "code": "def resolve_source_mapping(\n    source_directory: str, output_directory: str, sources: Sources\n) -> Mapping[str, str]:\n    result = {\n        os.path.join(source_directory, source_file): os.path.join(\n            output_directory, output_file\n        )\n        for source_file, output_file in sources.files.items()\n    }\n    filesystem = get_filesystem()\n    for glob in sources.globs:\n        matches = filesystem.list(source_directory, glob.patterns, exclude=glob.exclude)\n        result.update(\n            {\n                os.path.join(source_directory, match): os.path.join(\n                    output_directory, match\n                )\n                for match in matches\n            }\n        )\n    return result",
    "docstring": "Returns a mapping from absolute source path to absolute output path as specified\n        by the sources object. Files are not guaranteed to exist."
  },
  {
    "code": "async def fetchone(self):\n        row = await self._cursor.fetchone()\n        if not row:\n            raise GeneratorExit\n        self._rows.append(row)",
    "docstring": "Fetch single row from the cursor."
  },
  {
    "code": "def show(self, commit):\n        author = commit.author\n        author_width = 25\n        committer = ''\n        commit_date = date_to_str(commit.committer_time, commit.committer_tz,\n                                  self.verbose)\n        if self.verbose:\n            author += \" %s\" % commit.author_mail\n            author_width = 50\n            committer = \" %s %s\" % (commit.committer, commit.committer_mail)\n        return \"    {} {:>5d} {:{}s} {}{}\".format(\n            commit.uuid[:8], commit.line_count, author, author_width,\n            commit_date, committer)",
    "docstring": "Display one commit line.\n\n        The output will be:\n            <uuid> <#lines> <author> <short-commit-date>\n\n        If verbose flag set, the output will be:\n            <uuid> <#lines> <author+email> <long-date> <committer+email>"
  },
  {
    "code": "def ising_energy(sample, h, J, offset=0.0):\n    for v in h:\n        offset += h[v] * sample[v]\n    for v0, v1 in J:\n        offset += J[(v0, v1)] * sample[v0] * sample[v1]\n    return offset",
    "docstring": "Calculate the energy for the specified sample of an Ising model.\n\n    Energy of a sample for a binary quadratic model is defined as a sum, offset\n    by the constant energy offset associated with the model, of\n    the sample multipled by the linear bias of the variable and\n    all its interactions. For an Ising model,\n\n    .. math::\n\n        E(\\mathbf{s}) = \\sum_v h_v s_v + \\sum_{u,v} J_{u,v} s_u s_v + c\n\n    where :math:`s_v` is the sample, :math:`h_v` is the linear bias, :math:`J_{u,v}`\n    the quadratic bias (interactions), and :math:`c` the energy offset.\n\n    Args:\n        sample (dict[variable, spin]):\n            Sample for a binary quadratic model as a dict of form {v: spin, ...},\n            where keys are variables of the model and values are spins (either -1 or 1).\n        h (dict[variable, bias]):\n            Linear biases as a dict of the form {v: bias, ...}, where keys are variables of\n            the model and values are biases.\n        J (dict[(variable, variable), bias]):\n           Quadratic biases as a dict of the form {(u, v): bias, ...}, where keys\n           are 2-tuples of variables of the model and values are quadratic biases\n           associated with the pair of variables (the interaction).\n        offset (numeric, optional, default=0):\n            Constant offset to be applied to the energy. Default 0.\n\n    Returns:\n        float: The induced energy.\n\n    Notes:\n        No input checking is performed.\n\n    Examples:\n        This example calculates the energy of a sample representing two down spins for\n        an Ising model of two variables that have positive biases of value 1 and\n        are positively coupled with an interaction of value 1.\n\n        >>> import dimod\n        >>> sample = {1: -1, 2: -1}\n        >>> h = {1: 1, 2: 1}\n        >>> J = {(1, 2): 1}\n        >>> dimod.ising_energy(sample, h, J, 0.5)\n        -0.5\n\n    References\n    ----------\n\n    `Ising model on Wikipedia <https://en.wikipedia.org/wiki/Ising_model>`_"
  },
  {
    "code": "def handle_subscribe(self, request):\n        ret = self._tree.handle_subscribe(request, request.path[1:])\n        self._subscription_keys[request.generate_key()] = request\n        return ret",
    "docstring": "Handle a Subscribe request from outside. Called with lock taken"
  },
  {
    "code": "async def async_set_summary(program):\n    import aiohttp\n    async with aiohttp.ClientSession() as session:\n        resp = await session.get(program.get('url'))\n        text = await resp.text()\n        summary = extract_program_summary(text)\n        program['summary'] = summary\n        return program",
    "docstring": "Set a program's summary"
  },
  {
    "code": "def list(self, **filters):\n        LOG.debug(u'Querying %s by filters=%s', self.model_class.__name__, filters)\n        query = self.__queryset__()\n        perm = build_permission_name(self.model_class, 'view')\n        LOG.debug(u\"Checking if user %s has_perm %s\" % (self.user, perm))\n        query_with_permission = filter(lambda o: self.user.has_perm(perm, obj=o), query)\n        ids = map(lambda o: o.pk, query_with_permission)\n        queryset = self.__queryset__().filter(pk__in=ids)\n        related = getattr(self, 'select_related', None)\n        if related:\n            queryset = queryset.select_related(*related)\n        return queryset",
    "docstring": "Returns a queryset filtering object by user permission. If you want,\n        you can specify filter arguments.\n\n        See https://docs.djangoproject.com/en/dev/ref/models/querysets/#filter for more details"
  },
  {
    "code": "def calc_qiga1_v1(self):\n    der = self.parameters.derived.fastaccess\n    old = self.sequences.states.fastaccess_old\n    new = self.sequences.states.fastaccess_new\n    if der.ki1 <= 0.:\n        new.qiga1 = new.qigz1\n    elif der.ki1 > 1e200:\n        new.qiga1 = old.qiga1+new.qigz1-old.qigz1\n    else:\n        d_temp = (1.-modelutils.exp(-1./der.ki1))\n        new.qiga1 = (old.qiga1 +\n                     (old.qigz1-old.qiga1)*d_temp +\n                     (new.qigz1-old.qigz1)*(1.-der.ki1*d_temp))",
    "docstring": "Perform the runoff concentration calculation for the first\n    interflow component.\n\n    The working equation is the analytical solution of the linear storage\n    equation under the assumption of constant change in inflow during\n    the simulation time step.\n\n    Required derived parameter:\n      |KI1|\n\n    Required state sequence:\n      |QIGZ1|\n\n    Calculated state sequence:\n      |QIGA1|\n\n    Basic equation:\n       :math:`QIGA1_{neu} = QIGA1_{alt} +\n       (QIGZ1_{alt}-QIGA1_{alt}) \\\\cdot (1-exp(-KI1^{-1})) +\n       (QIGZ1_{neu}-QIGZ1_{alt}) \\\\cdot (1-KI1\\\\cdot(1-exp(-KI1^{-1})))`\n\n    Examples:\n\n        A normal test case:\n\n        >>> from hydpy.models.lland import *\n        >>> parameterstep()\n        >>> derived.ki1(0.1)\n        >>> states.qigz1.old = 2.0\n        >>> states.qigz1.new = 4.0\n        >>> states.qiga1.old = 3.0\n        >>> model.calc_qiga1_v1()\n        >>> states.qiga1\n        qiga1(3.800054)\n\n        First extreme test case (zero division is circumvented):\n\n        >>> derived.ki1(0.0)\n        >>> model.calc_qiga1_v1()\n        >>> states.qiga1\n        qiga1(4.0)\n\n        Second extreme test case (numerical overflow is circumvented):\n\n        >>> derived.ki1(1e500)\n        >>> model.calc_qiga1_v1()\n        >>> states.qiga1\n        qiga1(5.0)"
  },
  {
    "code": "def Append(self, other):\n        orig_len = len(self)\n        self.Set(orig_len + len(other))\n        ipoint = orig_len\n        if hasattr(self, 'SetPointError'):\n            for point in other:\n                self.SetPoint(ipoint, point.x.value, point.y.value)\n                self.SetPointError(\n                    ipoint,\n                    point.x.error_low, point.x.error_hi,\n                    point.y.error_low, point.y.error_hi)\n                ipoint += 1\n        else:\n            for point in other:\n                self.SetPoint(ipoint, point.x.value, point.y.value)\n                ipoint += 1",
    "docstring": "Append points from another graph"
  },
  {
    "code": "def make_inverse_connectivity(conns, n_nod, ret_offsets=True):\n    from itertools import chain\n    iconn = [[] for ii in xrange( n_nod )]\n    n_els = [0] * n_nod\n    for ig, conn in enumerate( conns ):\n        for iel, row in enumerate( conn ):\n            for node in row:\n                iconn[node].extend([ig, iel])\n                n_els[node] += 1\n    n_els = nm.array(n_els, dtype=nm.int32)\n    iconn = nm.fromiter(chain(*iconn), nm.int32)\n    if ret_offsets:\n        offsets = nm.cumsum(nm.r_[0, n_els], dtype=nm.int32)\n        return offsets, iconn\n    else:\n        return n_els, iconn",
    "docstring": "For each mesh node referenced in the connectivity conns, make a list of\n    elements it belongs to."
  },
  {
    "code": "def _create_api_method(cls, name, api_method):\n    def _api_method(self, **kwargs):\n        command = api_method['name']\n        if kwargs:\n            return self._make_request(command, kwargs)\n        else:\n            kwargs = {}\n            return self._make_request(command, kwargs)\n    _api_method.__doc__ = api_method['description']\n    _api_method.__doc__ += _add_params_docstring(api_method['params'])\n    _api_method.__name__ = str(name)\n    setattr(cls, _api_method.__name__, _api_method)",
    "docstring": "Create dynamic class methods based on the Cloudmonkey precached_verbs"
  },
  {
    "code": "def actuator_on(self, service_location_id, actuator_id, duration=None):\n        return self._actuator_on_off(\n            on_off='on', service_location_id=service_location_id,\n            actuator_id=actuator_id, duration=duration)",
    "docstring": "Turn actuator on\n\n        Parameters\n        ----------\n        service_location_id : int\n        actuator_id : int\n        duration : int, optional\n            300,900,1800 or 3600 , specifying the time in seconds the actuator\n            should be turned on. Any other value results in turning on for an\n            undetermined period of time.\n\n        Returns\n        -------\n        requests.Response"
  },
  {
    "code": "def is_running(self):\n        try:\n            result = requests.get(self.proxy_url)\n        except RequestException:\n            return False\n        if 'ZAP-Header' in result.headers.get('Access-Control-Allow-Headers', []):\n            return True\n        raise ZAPError('Another process is listening on {0}'.format(self.proxy_url))",
    "docstring": "Check if ZAP is running."
  },
  {
    "code": "def get_form_kwargs(self):\n        kwargs = super().get_form_kwargs()\n        if self.request.method == 'POST':\n            data = copy(self.request.POST)\n            i = 0\n            while(data.get('%s-%s-id' % (\n                settings.FLAT_MENU_ITEMS_RELATED_NAME, i\n            ))):\n                data['%s-%s-id' % (\n                    settings.FLAT_MENU_ITEMS_RELATED_NAME, i\n                )] = None\n                i += 1\n            kwargs.update({\n                'data': data,\n                'instance': self.model()\n            })\n        return kwargs",
    "docstring": "When the form is posted, don't pass an instance to the form. It should\n        create a new one out of the posted data. We also need to nullify any\n        IDs posted for inline menu items, so that new instances of those are\n        created too."
  },
  {
    "code": "def git_lines(*args, git=maybeloggit, **kwargs):\n    'Generator of stdout lines from given git command'\n    err = io.StringIO()\n    try:\n        for line in git('--no-pager', _err=err, *args, _decode_errors='replace', _iter=True, _bg_exc=False, **kwargs):\n            yield line[:-1]\n    except sh.ErrorReturnCode as e:\n        status('exit_code=%s' % e.exit_code)\n    errlines = err.getvalue().splitlines()\n    if len(errlines) < 3:\n        for line in errlines:\n            status(line)\n    else:\n        vd().push(TextSheet('git ' + ' '.join(args), errlines))",
    "docstring": "Generator of stdout lines from given git command"
  },
  {
    "code": "def enable_logging(main):\n    @functools.wraps(main)\n    def wrapper(*args, **kwargs):\n        import argparse\n        parser = argparse.ArgumentParser()\n        parser.add_argument(\n            '--loglevel', default=\"ERROR\", type=str,\n            help=\"Set the loglevel. Possible values: CRITICAL, ERROR (default),\"\n                 \"WARNING, INFO, DEBUG\")\n        options = parser.parse_args()\n        numeric_level = getattr(logging, options.loglevel.upper(), None)\n        if not isinstance(numeric_level, int):\n            raise ValueError('Invalid log level: %s' % options.loglevel)\n        logging.basicConfig(level=numeric_level)\n        retcode = main(*args, **kwargs)\n        return retcode\n    return wrapper",
    "docstring": "This decorator is used to decorate main functions.\n    It adds the initialization of the logger and an argument parser that allows\n    one to select the loglevel.\n    Useful if we are writing simple main functions that call libraries where\n    the logging module is used\n\n    Args:\n        main:\n            main function."
  },
  {
    "code": "def is_jail(name):\n    jails = list_jails()\n    for jail in jails:\n        if jail.split()[0] == name:\n            return True\n    return False",
    "docstring": "Return True if jail exists False if not\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' poudriere.is_jail <jail name>"
  },
  {
    "code": "def show_rsa(minion_id, dns_name):\n    cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)\n    bank = 'digicert/domains'\n    data = cache.fetch(\n        bank, dns_name\n    )\n    return data['private_key']",
    "docstring": "Show a private RSA key\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-run digicert.show_rsa myminion domain.example.com"
  },
  {
    "code": "def _tc_below(self):\n        tr_below = self._tr_below\n        if tr_below is None:\n            return None\n        return tr_below.tc_at_grid_col(self._grid_col)",
    "docstring": "The tc element immediately below this one in its grid column."
  },
  {
    "code": "def delete(self, ids):\n        url = build_uri_with_ids('api/v4/as/%s/', ids)\n        return super(ApiV4As, self).delete(url)",
    "docstring": "Method to delete asns by their id's\n\n        :param ids: Identifiers of asns\n        :return: None"
  },
  {
    "code": "def as_dict(self):\n        d = {}\n        _add_value(d, 'obstory_ids', self.obstory_ids)\n        _add_string(d, 'field_name', self.field_name)\n        _add_value(d, 'lat_min', self.lat_min)\n        _add_value(d, 'lat_max', self.lat_max)\n        _add_value(d, 'long_min', self.long_min)\n        _add_value(d, 'long_max', self.long_max)\n        _add_value(d, 'time_min', self.time_min)\n        _add_value(d, 'time_max', self.time_max)\n        _add_string(d, 'item_id', self.item_id)\n        _add_value(d, 'skip', self.skip)\n        _add_value(d, 'limit', self.limit)\n        _add_boolean(d, 'exclude_imported', self.exclude_imported)\n        _add_string(d, 'exclude_export_to', self.exclude_export_to)\n        return d",
    "docstring": "Convert this ObservatoryMetadataSearch to a dict, ready for serialization to JSON for use in the API.\n\n        :return:\n            Dict representation of this ObservatoryMetadataSearch instance"
  },
  {
    "code": "def setup_project_view(self):\r\n        for i in [1, 2, 3]:\r\n            self.hideColumn(i)\r\n        self.setHeaderHidden(True)\r\n        self.filter_directories()",
    "docstring": "Setup view for projects"
  },
  {
    "code": "def token_network_leave(\n            self,\n            registry_address: PaymentNetworkID,\n            token_address: TokenAddress,\n    ) -> List[NettingChannelState]:\n        if not is_binary_address(registry_address):\n            raise InvalidAddress('registry_address must be a valid address in binary')\n        if not is_binary_address(token_address):\n            raise InvalidAddress('token_address must be a valid address in binary')\n        if token_address not in self.get_tokens_list(registry_address):\n            raise UnknownTokenAddress('token_address unknown')\n        token_network_identifier = views.get_token_network_identifier_by_token_address(\n            chain_state=views.state_from_raiden(self.raiden),\n            payment_network_id=registry_address,\n            token_address=token_address,\n        )\n        connection_manager = self.raiden.connection_manager_for_token_network(\n            token_network_identifier,\n        )\n        return connection_manager.leave(registry_address)",
    "docstring": "Close all channels and wait for settlement."
  },
  {
    "code": "def list_users(self):\n        lines = output_lines(self.exec_rabbitmqctl_list('users'))\n        return [_parse_rabbitmq_user(line) for line in lines]",
    "docstring": "Run the ``list_users`` command and return a list of tuples describing\n        the users.\n\n        :return:\n            A list of 2-element tuples. The first element is the username, the\n            second a list of tags for the user."
  },
  {
    "code": "def fetch(self, buf = None, traceno = None):\n        if buf is None:\n            buf = self.buf\n        if traceno is None:\n            traceno = self.traceno\n        try:\n            if self.kind == TraceField:\n                if traceno is None: return buf\n                return self.filehandle.getth(traceno, buf)\n            else:\n                return self.filehandle.getbin()\n        except IOError:\n            if not self.readonly:\n                return bytearray(len(self.buf))\n            else: raise",
    "docstring": "Fetch the header from disk\n\n        This object will read header when it is constructed, which means it\n        might be out-of-date if the file is updated through some other handle.\n        This method is largely meant for internal use - if you need to reload\n        disk contents, use ``reload``.\n\n        Fetch does not update any internal state (unless `buf` is ``None`` on a\n        trace header, and the read succeeds), but returns the fetched header\n        contents.\n\n        This method can be used to reposition the trace header, which is useful\n        for constructing generators.\n\n        If this is called on a writable, new file, and this header has not yet\n        been written to, it will successfully return an empty buffer that, when\n        written to, will be reflected on disk.\n\n        Parameters\n        ----------\n        buf     : bytearray\n            buffer to read into instead of ``self.buf``\n        traceno : int\n\n        Returns\n        -------\n        buf : bytearray\n\n        Notes\n        -----\n        .. versionadded:: 1.6\n\n        This method is not intended as user-oriented functionality, but might\n        be useful in high-performance code."
  },
  {
    "code": "def __load(self, path):\n        try:\n            path = os.path.abspath(path)\n            with open(path, 'rb') as df:\n                self.__data, self.__classes, self.__labels, \\\n                self.__dtype, self.__description, \\\n                self.__num_features, self.__feature_names = pickle.load(df)\n            self.__validate(self.__data, self.__classes, self.__labels)\n        except IOError as ioe:\n            raise IOError('Unable to read the dataset from file: {}', format(ioe))\n        except:\n            raise",
    "docstring": "Method to load the serialized dataset from disk."
  },
  {
    "code": "def _adjust_image_paths(self, content: str, md_file_path: Path) -> str:\n        def _sub(image):\n            image_caption = image.group('caption')\n            image_path = md_file_path.parent / Path(image.group('path'))\n            self.logger.debug(\n                f'Updating image reference; user specified path: {image.group(\"path\")}, ' +\n                f'absolute path: {image_path}, caption: {image_caption}'\n            )\n            return f'![{image_caption}]({image_path.absolute().as_posix()})'\n        return self._image_pattern.sub(_sub, content)",
    "docstring": "Locate images referenced in a Markdown string and replace their paths\n        with the absolute ones.\n\n        :param content: Markdown content\n        :param md_file_path: Path to the Markdown file containing the content\n\n        :returns: Markdown content with absolute image paths"
  },
  {
    "code": "def _process_token(cls, token):\n        assert type(token) is _TokenType or callable(token), \\\n            'token type must be simple type or callable, not %r' % (token,)\n        return token",
    "docstring": "Preprocess the token component of a token definition."
  },
  {
    "code": "def geodetic2aer(lat: float, lon: float, h: float,\n                 lat0: float, lon0: float, h0: float,\n                 ell=None, deg: bool = True) -> Tuple[float, float, float]:\n    e, n, u = geodetic2enu(lat, lon, h, lat0, lon0, h0, ell, deg=deg)\n    return enu2aer(e, n, u, deg=deg)",
    "docstring": "gives azimuth, elevation and slant range from an Observer to a Point with geodetic coordinates.\n\n\n    Parameters\n    ----------\n\n    lat : float or numpy.ndarray of float\n        target geodetic latitude\n    lon : float or numpy.ndarray of float\n        target geodetic longitude\n    h : float or numpy.ndarray of float\n        target altitude above geodetic ellipsoid (meters)\n    lat0 : float\n        Observer geodetic latitude\n    lon0 : float\n        Observer geodetic longitude\n    h0 : float\n         observer altitude above geodetic ellipsoid (meters)\n    ell : Ellipsoid, optional\n          reference ellipsoid\n    deg : bool, optional\n          degrees input/output  (False: radians in/out)\n\n    Returns\n    -------\n    az : float or numpy.ndarray of float\n         azimuth\n    el : float or numpy.ndarray of float\n         elevation\n    srange : float or numpy.ndarray of float\n         slant range [meters]"
  },
  {
    "code": "def decompress(self, value):\n        if value:\n            try:\n                pk = self.queryset.get(recurrence_rule=value).pk\n            except self.queryset.model.DoesNotExist:\n                pk = None\n            return [pk, None, value]\n        return [None, None, None]",
    "docstring": "Return the primary key value for the ``Select`` widget if the given\n        recurrence rule exists in the queryset."
  },
  {
    "code": "def Parse(self, rdf_data):\n    if self._filter:\n      return list(self._filter.Parse(rdf_data, self.expression))\n    return rdf_data",
    "docstring": "Process rdf data through the filter.\n\n    Filters sift data according to filter rules. Data that passes the filter\n    rule is kept, other data is dropped.\n\n    If no filter method is provided, the data is returned as a list.\n    Otherwise, a items that meet filter conditions are returned in a list.\n\n    Args:\n      rdf_data: Host data that has already been processed by a Parser into RDF.\n\n    Returns:\n      A list containing data items that matched the filter rules."
  },
  {
    "code": "def send_comment_email(email, package_owner, package_name, commenter):\n    link = '{CATALOG_URL}/package/{owner}/{pkg}/comments'.format(\n        CATALOG_URL=CATALOG_URL, owner=package_owner, pkg=package_name)\n    subject = \"New comment on {package_owner}/{package_name}\".format(\n        package_owner=package_owner, package_name=package_name)\n    html = render_template('comment_email.html', commenter=commenter, link=link)\n    body = render_template('comment_email.txt', commenter=commenter, link=link)\n    send_email(recipients=[email], sender=DEFAULT_SENDER, subject=subject,\n               html=html, body=body)",
    "docstring": "Send email to owner of package regarding new comment"
  },
  {
    "code": "def register_linter(linter):\n        if hasattr(linter, \"EXTS\") and hasattr(linter, \"run\"):\n            LintFactory.PLUGINS.append(linter)\n        else:\n            raise LinterException(\"Linter does not have 'run' method or EXTS variable!\")",
    "docstring": "Register a Linter class for file verification.\n\n        :param linter:\n        :return:"
  },
  {
    "code": "def unregister_file(path, pkg=None, conn=None):\n    close = False\n    if conn is None:\n        close = True\n        conn = init()\n    conn.execute('DELETE FROM files WHERE path=?', (path, ))\n    if close:\n        conn.close()",
    "docstring": "Unregister a file from the package database"
  },
  {
    "code": "def _populate(self, json):\n        from .volume import Volume\n        DerivedBase._populate(self, json)\n        devices = {}\n        for device_index, device in json['devices'].items():\n            if not device:\n                devices[device_index] = None\n                continue\n            dev = None\n            if 'disk_id' in device and device['disk_id']:\n                dev = Disk.make_instance(device['disk_id'], self._client,\n                        parent_id=self.linode_id)\n            else:\n                dev = Volume.make_instance(device['volume_id'], self._client,\n                        parent_id=self.linode_id)\n            devices[device_index] = dev\n        self._set('devices', MappedObject(**devices))",
    "docstring": "Map devices more nicely while populating."
  },
  {
    "code": "def items(self):\n        for dictreader in self._csv_dictreader_list:\n            for entry in dictreader:\n                item = self.factory()\n                item.key = self.key()\n                item.attributes = entry\n                try:\n                    item.validate()\n                except Exception as e:\n                    logger.debug(\"skipping entry due to item validation exception: %s\", str(e))\n                    continue\n                logger.debug(\"found validated item in CSV source, key: %s\", str(item.attributes[self.key()]))\n                yield item",
    "docstring": "Returns a generator of available ICachableItem in the ICachableSource"
  },
  {
    "code": "def _read_byte(self):\n        to_return = \"\"\n        if (self._mode == PROP_MODE_SERIAL):\n            to_return = self._serial.read(1)\n        elif (self._mode == PROP_MODE_TCP):\n            to_return = self._socket.recv(1)\n        elif (self._mode == PROP_MODE_FILE):\n            to_return = struct.pack(\"B\", int(self._file.readline()))\n        _LOGGER.debug(\"READ: \" + str(ord(to_return)))\n        self._logdata.append(ord(to_return))\n        if (len(self._logdata) > self._logdatalen):\n            self._logdata = self._logdata[len(self._logdata) - self._logdatalen:]\n        self._debug(PROP_LOGLEVEL_TRACE, \"READ: \" + str(ord(to_return)))\n        return to_return",
    "docstring": "Read a byte from input."
  },
  {
    "code": "def get_parent_image_koji_data(workflow):\n    koji_parent = workflow.prebuild_results.get(PLUGIN_KOJI_PARENT_KEY) or {}\n    image_metadata = {}\n    parents = {}\n    for img, build in (koji_parent.get(PARENT_IMAGES_KOJI_BUILDS) or {}).items():\n        if not build:\n            parents[str(img)] = None\n        else:\n            parents[str(img)] = {key: val for key, val in build.items() if key in ('id', 'nvr')}\n    image_metadata[PARENT_IMAGE_BUILDS_KEY] = parents\n    image_metadata[PARENT_IMAGES_KEY] = workflow.builder.parents_ordered\n    if workflow.builder.base_from_scratch:\n        return image_metadata\n    base_info = koji_parent.get(BASE_IMAGE_KOJI_BUILD) or {}\n    parent_id = base_info.get('id')\n    if parent_id is not None:\n        try:\n            parent_id = int(parent_id)\n        except ValueError:\n            logger.exception(\"invalid koji parent id %r\", parent_id)\n        else:\n            image_metadata[BASE_IMAGE_BUILD_ID_KEY] = parent_id\n    return image_metadata",
    "docstring": "Transform koji_parent plugin results into metadata dict."
  },
  {
    "code": "def _send_method(self, method_sig, args=bytes(), content=None):\n        if isinstance(args, AMQPWriter):\n            args = args.getvalue()\n        self.connection.method_writer.write_method(self.channel_id,\n            method_sig, args, content)",
    "docstring": "Send a method for our channel."
  },
  {
    "code": "def insert_before(old, new):\n    parent = old.getparent()\n    parent.insert(parent.index(old), new)",
    "docstring": "A simple way to insert a new element node before the old element node among\n    its siblings."
  },
  {
    "code": "def cleanJsbConfig(self, jsbconfig):\n        config = json.loads(jsbconfig)\n        self._cleanJsbAllClassesSection(config)\n        self._cleanJsbAppAllSection(config)\n        return json.dumps(config, indent=4)",
    "docstring": "Clean up the JSB config."
  },
  {
    "code": "def getheader(self, which, use_hash=None, polish=True):\n        header = getheader(\n            which,\n            use_hash=use_hash,\n            target=self.target,\n            no_tco=self.no_tco,\n            strict=self.strict,\n        )\n        if polish:\n            header = self.polish(header)\n        return header",
    "docstring": "Get a formatted header."
  },
  {
    "code": "def scan_file(path):\n    path = os.path.abspath(path)\n    assert os.path.exists(path), \"Unreachable file '%s'.\" % path\n    try:\n        cd = pyclamd.ClamdUnixSocket()\n        cd.ping()\n    except pyclamd.ConnectionError:\n        cd = pyclamd.ClamdNetworkSocket()\n        try:\n            cd.ping()\n        except pyclamd.ConnectionError:\n            raise ValueError(\n                \"Couldn't connect to clamd server using unix/network socket.\"\n            )\n    cd = pyclamd.ClamdUnixSocket()\n    assert cd.ping(), \"clamd server is not reachable!\"\n    result = cd.scan_file(path)\n    return result if result else {}",
    "docstring": "Scan `path` for viruses using ``clamd`` antivirus daemon.\n\n    Args:\n        path (str): Relative or absolute path of file/directory you need to\n                    scan.\n\n    Returns:\n        dict: ``{filename: (\"FOUND\", \"virus type\")}`` or blank dict.\n\n    Raises:\n        ValueError: When the server is not running.\n        AssertionError: When the internal file doesn't exists."
  },
  {
    "code": "def _incomplete_files(filenames):\n  tmp_files = [get_incomplete_path(f) for f in filenames]\n  try:\n    yield tmp_files\n    for tmp, output in zip(tmp_files, filenames):\n      tf.io.gfile.rename(tmp, output)\n  finally:\n    for tmp in tmp_files:\n      if tf.io.gfile.exists(tmp):\n        tf.io.gfile.remove(tmp)",
    "docstring": "Create temporary files for filenames and rename on exit."
  },
  {
    "code": "def make_filesystem(blk_device, fstype='ext4', timeout=10):\n    count = 0\n    e_noent = os.errno.ENOENT\n    while not os.path.exists(blk_device):\n        if count >= timeout:\n            log('Gave up waiting on block device %s' % blk_device,\n                level=ERROR)\n            raise IOError(e_noent, os.strerror(e_noent), blk_device)\n        log('Waiting for block device %s to appear' % blk_device,\n            level=DEBUG)\n        count += 1\n        time.sleep(1)\n    else:\n        log('Formatting block device %s as filesystem %s.' %\n            (blk_device, fstype), level=INFO)\n        check_call(['mkfs', '-t', fstype, blk_device])",
    "docstring": "Make a new filesystem on the specified block device."
  },
  {
    "code": "def health(self):\n        return json.dumps(dict(uptime='{:.3f}s'\n                               .format((time.time() - self._start_time))))",
    "docstring": "Health check method, returns the up-time of the device."
  },
  {
    "code": "def json(self):\n        if hasattr(self, '_json'):\n            return self._json\n        try:\n            self._json = json.loads(self.text or self.content)\n        except ValueError:\n            self._json = None\n        return self._json",
    "docstring": "Returns the json-encoded content of the response, if any."
  },
  {
    "code": "def delete_processing_block(processing_block_id):\n    scheduling_block_id = processing_block_id.split(':')[0]\n    config = get_scheduling_block(scheduling_block_id)\n    processing_blocks = config.get('processing_blocks')\n    processing_block = list(filter(\n        lambda x: x.get('id') == processing_block_id, processing_blocks))[0]\n    config['processing_blocks'].remove(processing_block)\n    DB.set('scheduling_block/{}'.format(config['id']), json.dumps(config))\n    DB.rpush('processing_block_events',\n             json.dumps(dict(type=\"deleted\", id=processing_block_id)))",
    "docstring": "Delete Processing Block with the specified ID"
  },
  {
    "code": "def _dump(obj, abspath, serializer_type,\n          dumper_func=None,\n          compress=True,\n          overwrite=False,\n          verbose=False,\n          **kwargs):\n    _check_serializer_type(serializer_type)\n    if not inspect.isfunction(dumper_func):\n        raise TypeError(\"dumper_func has to be a function take object as input \"\n                        \"and return binary!\")\n    prt_console(\"\\nDump to '%s' ...\" % abspath, verbose)\n    if os.path.exists(abspath):\n        if not overwrite:\n            prt_console(\n                \"    Stop! File exists and overwrite is not allowed\",\n                verbose,\n            )\n            return\n    st = time.clock()\n    b_or_str = dumper_func(obj, **kwargs)\n    if serializer_type is \"str\":\n        b = b_or_str.encode(\"utf-8\")\n    else:\n        b = b_or_str\n    if compress:\n        b = zlib.compress(b)\n    with atomic_write(abspath, overwrite=overwrite, mode=\"wb\") as f:\n        f.write(b)\n    elapsed = time.clock() - st\n    prt_console(\"    Complete! Elapse %.6f sec.\" % elapsed, verbose)\n    if serializer_type is \"str\":\n        return b_or_str\n    else:\n        return b",
    "docstring": "Dump object to file.\n\n    :param abspath: The file path you want dump to.\n    :type abspath: str\n\n    :param serializer_type: 'binary' or 'str'.\n    :type serializer_type: str\n\n    :param dumper_func: A dumper function that takes an object as input, return\n        binary or string.\n    :type dumper_func: callable function\n\n    :param compress: default ``False``. If True, then compress binary.\n    :type compress: bool\n\n    :param overwrite: default ``False``, If ``True``, when you dump to\n      existing file, it silently overwrite it. If ``False``, an alert\n      message is shown. Default setting ``False`` is to prevent overwrite\n      file by mistake.\n    :type overwrite: boolean\n\n    :param verbose: default True, help-message-display trigger.\n    :type verbose: boolean"
  },
  {
    "code": "def _AddStopTimeObjectUnordered(self, stoptime, schedule):\n    stop_time_class = self.GetGtfsFactory().StopTime\n    cursor = schedule._connection.cursor()\n    insert_query = \"INSERT INTO stop_times (%s) VALUES (%s);\" % (\n       ','.join(stop_time_class._SQL_FIELD_NAMES),\n       ','.join(['?'] * len(stop_time_class._SQL_FIELD_NAMES)))\n    cursor = schedule._connection.cursor()\n    cursor.execute(\n        insert_query, stoptime.GetSqlValuesTuple(self.trip_id))",
    "docstring": "Add StopTime object to this trip.\n\n    The trip isn't checked for duplicate sequence numbers so it must be\n    validated later."
  },
  {
    "code": "def from_object(self, obj: Union[str, Any]) -> None:\n        if isinstance(obj, str):\n            obj = importer.import_object_str(obj)\n        for key in dir(obj):\n            if key.isupper():\n                value = getattr(obj, key)\n                self._setattr(key, value)\n        logger.info(\"Config is loaded from object: %r\", obj)",
    "docstring": "Load values from an object."
  },
  {
    "code": "def assert_powernode(self, name:str) -> None or ValueError:\n        if name not in self.inclusions:\n            raise ValueError(\"Powernode '{}' does not exists.\".format(name))\n        if self.is_node(name):\n            raise ValueError(\"Given name '{}' is a node.\".format(name))",
    "docstring": "Do nothing if given name refers to a powernode in given graph.\n        Raise a ValueError in any other case."
  },
  {
    "code": "def directed_tripartition_indices(N):\n    result = []\n    if N <= 0:\n        return result\n    base = [0, 1, 2]\n    for key in product(base, repeat=N):\n        part = [[], [], []]\n        for i, location in enumerate(key):\n            part[location].append(i)\n        result.append(tuple(tuple(p) for p in part))\n    return result",
    "docstring": "Return indices for directed tripartitions of a sequence.\n\n    Args:\n        N (int): The length of the sequence.\n\n    Returns:\n        list[tuple]: A list of tuples containing the indices for each\n        partition.\n\n    Example:\n        >>> N = 1\n        >>> directed_tripartition_indices(N)\n        [((0,), (), ()), ((), (0,), ()), ((), (), (0,))]"
  },
  {
    "code": "def befriend(self, other_agent, force=False):\n        if force or self['openness'] > random():\n            self.env.add_edge(self, other_agent)\n            self.info('Made some friend {}'.format(other_agent))\n            return True\n        return False",
    "docstring": "Try to become friends with another agent. The chances of\n        success depend on both agents' openness."
  },
  {
    "code": "def tostring(self, encoding):\n        if self.kind == 'string':\n            if encoding is not None:\n                return self.converted\n            return '\"{converted}\"'.format(converted=self.converted)\n        elif self.kind == 'float':\n            return repr(self.converted)\n        return self.converted",
    "docstring": "quote the string if not encoded\n            else encode and return"
  },
  {
    "code": "def kitchen_create(backend, parent, kitchen):\n    click.secho('%s - Creating kitchen %s from parent kitchen %s' % (get_datetime(), kitchen, parent), fg='green')\n    master = 'master'\n    if kitchen.lower() != master.lower():\n        check_and_print(DKCloudCommandRunner.create_kitchen(backend.dki, parent, kitchen))\n    else:\n        raise click.ClickException('Cannot create a kitchen called %s' % master)",
    "docstring": "Create a new kitchen"
  },
  {
    "code": "def get(self):\n        return self.render(\n            'index.html',\n            databench_version=DATABENCH_VERSION,\n            meta_infos=self.meta_infos(),\n            **self.info\n        )",
    "docstring": "Render the List-of-Analyses overview page."
  },
  {
    "code": "def has_pending(self):\n        if self.pending:\n            return True\n        for pending in self.node2pending.values():\n            if pending:\n                return True\n        return False",
    "docstring": "Return True if there are pending test items\n\n        This indicates that collection has finished and nodes are\n        still processing test items, so this can be thought of as\n        \"the scheduler is active\"."
  },
  {
    "code": "def _generic_hook(self, name, **kwargs):\n        entries = [entry for entry in self._plugin_manager.call_hook(name, **kwargs) if entry is not None]\n        return \"\\n\".join(entries)",
    "docstring": "A generic hook that links the TemplateHelper with PluginManager"
  },
  {
    "code": "def get_attributes(aspect, id):\n    attributes = {}\n    for entry in aspect:\n        if entry['po'] == id:\n            attributes[entry['n']] = entry['v']\n    return attributes",
    "docstring": "Return the attributes pointing to a given ID in a given aspect."
  },
  {
    "code": "def hash_bytes( key, seed = 0x0, x64arch = True ):\n    hash_128 = hash128( key, seed, x64arch )\n    bytestring = ''\n    for i in xrange(0, 16, 1):\n        lsbyte = hash_128 & 0xFF\n        bytestring = bytestring + str( chr( lsbyte ) )\n        hash_128 = hash_128 >> 8\n    return bytestring",
    "docstring": "Implements 128bit murmur3 hash. Returns a byte string."
  },
  {
    "code": "def delete(self, *args, **kwargs):\n        lookup = self.with_respect_to()\n        lookup[\"_order__gte\"] = self._order\n        concrete_model = base_concrete_model(Orderable, self)\n        after = concrete_model.objects.filter(**lookup)\n        after.update(_order=models.F(\"_order\") - 1)\n        super(Orderable, self).delete(*args, **kwargs)",
    "docstring": "Update the ordering values for siblings."
  },
  {
    "code": "def remove_configurable(self, configurable_class, name):\n        configurable_class_name = configurable_class.__name__.lower()\n        logger.info(\"Removing %s: '%s'\", configurable_class_name, name)\n        registry = self.registry_for(configurable_class)\n        if name not in registry:\n            logger.warn(\n                \"Tried to remove unknown active %s: '%s'\",\n                configurable_class_name, name\n            )\n            return\n        hook = self.hook_for(configurable_class, action=\"remove\")\n        if not hook:\n            registry.pop(name)\n            return\n        def done(f):\n            try:\n                f.result()\n                registry.pop(name)\n            except Exception:\n                logger.exception(\"Error removing configurable '%s'\", name)\n        self.work_pool.submit(hook, name).add_done_callback(done)",
    "docstring": "Callback fired when a configurable instance is removed.\n\n        Looks up the existing configurable in the proper \"registry\" and\n        removes it.\n\n        If a method named \"on_<configurable classname>_remove\" is defined it\n        is called via the work pooland passed the configurable's name.\n\n        If the removed configurable is not present, a warning is given and no\n        further action is taken."
  },
  {
    "code": "def get_contact_from_id(self, contact_id):\n        contact = self.wapi_functions.getContact(contact_id)\n        if contact is None:\n            raise ContactNotFoundError(\"Contact {0} not found\".format(contact_id))\n        return Contact(contact, self)",
    "docstring": "Fetches a contact given its ID\n\n        :param contact_id: Contact ID\n        :type contact_id: str\n        :return: Contact or Error\n        :rtype: Contact"
  },
  {
    "code": "def units(self):\n        self._units, value = self.get_attr_string(self._units, 'units')\n        return value",
    "docstring": "Returns the units of the measured value for the current mode. May return\n        empty string"
  },
  {
    "code": "def scan(context, root_dir):\n    root_dir = root_dir or context.obj['root']\n    config_files = Path(root_dir).glob('*/analysis/*_config.yaml')\n    for config_file in config_files:\n        LOG.debug(\"found analysis config: %s\", config_file)\n        with config_file.open() as stream:\n            context.invoke(log_cmd, config=stream, quiet=True)\n    context.obj['store'].track_update()",
    "docstring": "Scan a directory for analyses."
  },
  {
    "code": "def WSGIMimeRender(*args, **kwargs):\n    def wrapper(*args2, **kwargs2):\n        def wrapped(f):\n            return _WSGIMimeRender(*args, **kwargs)(*args2, **kwargs2)(wsgi_wrap(f))\n        return wrapped\n    return wrapper",
    "docstring": "A wrapper for _WSGIMimeRender that wrapps the\n    inner callable with wsgi_wrap first."
  },
  {
    "code": "def focus_right(pymux):\n    \" Move focus to the right. \"\n    _move_focus(pymux,\n                lambda wp: wp.xpos + wp.width + 1,\n                lambda wp: wp.ypos)",
    "docstring": "Move focus to the right."
  },
  {
    "code": "def _get_value(self):\n        if self._aux_variable:\n            return self._aux_variable['law'](self._aux_variable['variable'].value)\n        if self._transformation is None:\n            return self._internal_value\n        else:\n            return self._transformation.backward(self._internal_value)",
    "docstring": "Return current parameter value"
  },
  {
    "code": "def _build_cmd(self, args: Union[list, tuple]) -> str:\n        cmd = [self.path]\n        cmd.extend(args)\n        return cmd",
    "docstring": "Build command."
  },
  {
    "code": "def number(items):\n    n = len(items)\n    if n == 0:\n        return items\n    places = str(int(math.log10(n) // 1 + 1))\n    format = '[{0[0]:' + str(int(places)) + 'd}] {0[1]}'\n    return map(\n        lambda x: format.format(x),\n        enumerate(items)\n    )",
    "docstring": "Maps numbering onto given values"
  },
  {
    "code": "def register(self, identified_with, identifier, user):\n        self.kv_store.set(\n            self._get_storage_key(identified_with, identifier),\n            self.serialization.dumps(user).encode(),\n        )",
    "docstring": "Register new key for given client identifier.\n\n        This is only a helper method that allows to register new\n        user objects for client identities (keys, tokens, addresses etc.).\n\n        Args:\n            identified_with (object): authentication middleware used\n                to identify the user.\n            identifier (str): user identifier.\n            user (str): user object to be stored in the backend."
  },
  {
    "code": "def run_deps(self, conf, images):\n        for dependency_name, detached in conf.dependency_images(for_running=True):\n            try:\n                self.run_container(images[dependency_name], images, detach=detached, dependency=True)\n            except Exception as error:\n                raise BadImage(\"Failed to start dependency container\", image=conf.name, dependency=dependency_name, error=error)",
    "docstring": "Start containers for all our dependencies"
  },
  {
    "code": "def get_value(self, name, parameters=None):\n        if not isinstance(parameters, dict):\n            raise TypeError(\"parameters must a dict\")\n        if name not in self._cache:\n            return None\n        hash = self._parameter_hash(parameters)\n        hashdigest = hash.hexdigest()\n        return self._cache[name].get(hashdigest, None)",
    "docstring": "Return the value of a cached variable if applicable\n\n        The value of the variable 'name' is returned, if no parameters are passed or if all parameters are identical\n        to the ones stored for the variable.\n\n        :param str name: Name of teh variable\n        :param dict parameters: Current parameters or None if parameters do not matter\n        :return: The cached value of the variable or None if the parameters differ"
  },
  {
    "code": "def textile(value):\n    try:\n        import textile\n    except ImportError:\n        warnings.warn(\"The Python textile library isn't installed.\",\n                      RuntimeWarning)\n        return value\n    return textile.textile(force_text(value))",
    "docstring": "Textile processing."
  },
  {
    "code": "def compute_position(self, layout):\n        params = self.position.setup_params(self.data)\n        data = self.position.setup_data(self.data, params)\n        data = self.position.compute_layer(data, params, layout)\n        self.data = data",
    "docstring": "Compute the position of each geometric object\n        in concert with the other objects in the panel"
  },
  {
    "code": "def get_ordered_tokens_from_vocab(vocab: Vocab) -> List[str]:\n    return [token for token, token_id in sorted(vocab.items(), key=lambda i: i[1])]",
    "docstring": "Returns the list of tokens in a vocabulary, ordered by increasing vocabulary id.\n\n    :param vocab: Input vocabulary.\n    :return: List of tokens."
  },
  {
    "code": "def dns_encode(x, check_built=False):\n    if not x or x == b\".\":\n        return b\"\\x00\"\n    if check_built and b\".\" not in x and (\n        orb(x[-1]) == 0 or (orb(x[-2]) & 0xc0) == 0xc0\n    ):\n        return x\n    x = b\"\".join(chb(len(y)) + y for y in (k[:63] for k in x.split(b\".\")))\n    if x[-1:] != b\"\\x00\":\n        x += b\"\\x00\"\n    return x",
    "docstring": "Encodes a bytes string into the DNS format\n\n    :param x: the string\n    :param check_built: detect already-built strings and ignore them\n    :returns: the encoded bytes string"
  },
  {
    "code": "def fetch(self):\n        params = values.of({})\n        payload = self._version.fetch(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return BalanceInstance(self._version, payload, account_sid=self._solution['account_sid'], )",
    "docstring": "Fetch a BalanceInstance\n\n        :returns: Fetched BalanceInstance\n        :rtype: twilio.rest.api.v2010.account.balance.BalanceInstance"
  },
  {
    "code": "def toc(self):\n        output = []\n        for key in sorted(self.catalog.keys()):\n            edition = self.catalog[key]['edition']\n            length = len(self.catalog[key]['transliteration'])\n            output.append(\n                \"Pnum: {key}, Edition: {edition}, length: {length} line(s)\".format(\n                    key=key, edition=edition, length=length))\n        return output",
    "docstring": "Returns a rich list of texts in the catalog."
  },
  {
    "code": "def fetch_all_droplets(self, tag_name=None):\n        r\n        params = {}\n        if tag_name is not None:\n            params[\"tag_name\"] = str(tag_name)\n        return map(self._droplet, self.paginate('/v2/droplets', 'droplets',\n                                                params=params))",
    "docstring": "r\"\"\"\n        Returns a generator that yields all of the droplets belonging to the\n        account\n\n        .. versionchanged:: 0.2.0\n            ``tag_name`` parameter added\n\n        :param tag_name: if non-`None`, only droplets with the given tag are\n            returned\n        :type tag_name: string or `Tag`\n        :rtype: generator of `Droplet`\\ s\n        :raises DOAPIError: if the API endpoint replies with an error"
  },
  {
    "code": "def on(self):\n        on_command = StandardSend(self._address,\n                                  COMMAND_LIGHT_ON_0X11_NONE, 0xff)\n        self._send_method(on_command,\n                          self._on_message_received)",
    "docstring": "Send ON command to device."
  },
  {
    "code": "def get_random_connection(self):\n        if self._available_connections:\n            node_name = random.choice(list(self._available_connections.keys()))\n            conn_list = self._available_connections[node_name]\n            if conn_list:\n                return conn_list.pop()\n        for node in self.nodes.random_startup_node_iter():\n            connection = self.get_connection_by_node(node)\n            if connection:\n                return connection\n        raise Exception(\"Cant reach a single startup node.\")",
    "docstring": "Open new connection to random redis server."
  },
  {
    "code": "def set_units_property(self, *, unit_ids=None, property_name, values):\n        if unit_ids is None:\n            unit_ids = self.get_unit_ids()\n        for i, unit in enumerate(unit_ids):\n            self.set_unit_property(unit_id=unit, property_name=property_name, value=values[i])",
    "docstring": "Sets unit property data for a list of units\n\n        Parameters\n        ----------\n        unit_ids: list\n            The list of unit ids for which the property will be set\n            Defaults to get_unit_ids()\n        property_name: str\n            The name of the property\n        value: list\n            The list of values to be set"
  },
  {
    "code": "def make_processors(**config):\n    global processors\n    if processors:\n        return\n    import pkg_resources\n    processors = []\n    for processor in pkg_resources.iter_entry_points('fedmsg.meta'):\n        try:\n            processors.append(processor.load()(_, **config))\n        except Exception as e:\n            log.warn(\"Failed to load %r processor.\" % processor.name)\n            log.exception(e)\n    processors.append(DefaultProcessor(_, **config))\n    if len(processors) == 3:\n        log.warn(\"No fedmsg.meta plugins found.  fedmsg.meta.msg2* crippled\")",
    "docstring": "Initialize all of the text processors.\n\n    You'll need to call this once before using any of the other functions in\n    this module.\n\n        >>> import fedmsg.config\n        >>> import fedmsg.meta\n        >>> config = fedmsg.config.load_config([], None)\n        >>> fedmsg.meta.make_processors(**config)\n        >>> text = fedmsg.meta.msg2repr(some_message_dict, **config)"
  },
  {
    "code": "def dfilter(fn, record):\n    return dict([(k, v) for k, v in record.items() if fn(v)])",
    "docstring": "filter for a directory\n\n    :param fn: A predicate function\n    :param record: a dict\n    :returns: a dict\n\n    >>> odd = lambda x: x % 2 != 0\n    >>> dfilter(odd, {'Terry': 30, 'Graham': 35, 'John': 27})\n    {'John': 27, 'Graham': 35}"
  },
  {
    "code": "def _events(self, using_url, filters=None, limit=None):\n        if not isinstance(limit, (int, NoneType)):\n            limit = None\n        if filters is None:\n            filters = []\n        if isinstance(filters, string_types):\n            filters = filters.split(',')\n        if not self.blocking:\n            self.blocking = True\n        while self.blocking:\n            params = {\n                'since': self._last_seen_id,\n                'limit': limit,\n            }\n            if filters:\n                params['events'] = ','.join(map(str, filters))\n            try:\n                data = self.get(using_url, params=params, raw_exceptions=True)\n            except (ConnectTimeout, ConnectionError) as e:\n                data = None\n            except Exception as e:\n                reraise('', e)\n            if data:\n                self._last_seen_id = data[-1]['id']\n                for event in data:\n                    self._count += 1\n                    yield event",
    "docstring": "A long-polling method that queries Syncthing for events..\n\n            Args:\n                using_url (str): REST HTTP endpoint\n                filters (List[str]): Creates an \"event group\" in Syncthing to\n                    only receive events that have been subscribed to.\n                limit (int): The number of events to query in the history\n                    to catch up to the current state.\n\n            Returns:\n                generator[dict]"
  },
  {
    "code": "def timeout(delay, handler=None):\n    delay = int(delay)\n    if handler is None:\n        def default_handler(signum, frame):\n            raise RuntimeError(\"{:d} seconds timeout expired\".format(delay))\n        handler = default_handler\n    prev_sigalrm_handler = signal.getsignal(signal.SIGALRM)\n    signal.signal(signal.SIGALRM, handler)\n    signal.alarm(delay)\n    yield\n    signal.alarm(0)\n    signal.signal(signal.SIGALRM, prev_sigalrm_handler)",
    "docstring": "Context manager to run code and deliver a SIGALRM signal after `delay` seconds.\n\n    Note that `delay` must be a whole number; otherwise it is converted to an\n    integer by Python's `int()` built-in function. For floating-point numbers,\n    that means rounding off to the nearest integer from below.\n\n    If the optional argument `handler` is supplied, it must be a callable that\n    is invoked if the alarm triggers while the code is still running. If no\n    `handler` is provided (default), then a `RuntimeError` with message\n    ``Timeout`` is raised."
  },
  {
    "code": "def result(self, timeout=None):\n        self._blocking_poll(timeout=timeout)\n        if self._exception is not None:\n            raise self._exception\n        return self._result",
    "docstring": "Get the result of the operation, blocking if necessary.\n\n        Args:\n            timeout (int):\n                How long (in seconds) to wait for the operation to complete.\n                If None, wait indefinitely.\n\n        Returns:\n            google.protobuf.Message: The Operation's result.\n\n        Raises:\n            google.api_core.GoogleAPICallError: If the operation errors or if\n                the timeout is reached before the operation completes."
  },
  {
    "code": "def _get_label_uuid(xapi, rectype, label):\n    try:\n        return getattr(xapi, rectype).get_by_name_label(label)[0]\n    except Exception:\n        return False",
    "docstring": "Internal, returns label's uuid"
  },
  {
    "code": "def get_msg_count_info(self, channel=Channel.CHANNEL_CH0):\n        msg_count_info = MsgCountInfo()\n        UcanGetMsgCountInfoEx(self._handle, channel, byref(msg_count_info))\n        return msg_count_info.sent_msg_count, msg_count_info.recv_msg_count",
    "docstring": "Reads the message counters of the specified CAN channel.\n\n        :param int channel:\n            CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).\n        :return: Tuple with number of CAN messages sent and received.\n        :rtype: tuple(int, int)"
  },
  {
    "code": "def get_licenses(service_instance, license_manager=None):\n    if not license_manager:\n        license_manager = get_license_manager(service_instance)\n    log.debug('Retrieving licenses')\n    try:\n        return license_manager.licenses\n    except vim.fault.NoPermission as exc:\n        log.exception(exc)\n        raise salt.exceptions.VMwareApiError(\n            'Not enough permissions. Required privilege: '\n            '{0}'.format(exc.privilegeId))\n    except vim.fault.VimFault as exc:\n        log.exception(exc)\n        raise salt.exceptions.VMwareApiError(exc.msg)\n    except vmodl.RuntimeFault as exc:\n        log.exception(exc)\n        raise salt.exceptions.VMwareRuntimeError(exc.msg)",
    "docstring": "Returns the licenses on a specific instance.\n\n    service_instance\n        The Service Instance Object from which to obrain the licenses.\n\n    license_manager\n        The License Manager object of the service instance. If not provided it\n        will be retrieved."
  },
  {
    "code": "def remove_user(self, user, **kwargs):\n        if isinstance(user, Entity):\n            user = user['id']\n        assert isinstance(user, six.string_types)\n        endpoint = '{0}/{1}/users/{2}'.format(\n            self.endpoint,\n            self['id'],\n            user,\n        )\n        return self.request('DELETE', endpoint=endpoint, query_params=kwargs)",
    "docstring": "Remove a user from this team."
  },
  {
    "code": "def get_keybinding(self, mode, key):\n        cmdline = None\n        bindings = self._bindings\n        if key in bindings.scalars:\n            cmdline = bindings[key]\n        if mode in bindings.sections:\n            if key in bindings[mode].scalars:\n                value = bindings[mode][key]\n                if value:\n                    cmdline = value\n                else:\n                    cmdline = None\n        if isinstance(cmdline, list):\n            cmdline = ','.join(cmdline)\n        return cmdline",
    "docstring": "look up keybinding from `MODE-maps` sections\n\n        :param mode: mode identifier\n        :type mode: str\n        :param key: urwid-style key identifier\n        :type key: str\n        :returns: a command line to be applied upon keypress\n        :rtype: str"
  },
  {
    "code": "def devices(self):\n        self.verify_integrity()\n        if session.get('u2f_device_management_authorized', False):\n            if request.method == 'GET':\n                return jsonify(self.get_devices()), 200\n            elif request.method == 'DELETE':\n                response = self.remove_device(request.json)\n                if response['status'] == 'ok':\n                    return jsonify(response), 200\n                else:\n                    return jsonify(response), 404\n        return jsonify({'status': 'failed', 'error': 'Unauthorized!'}), 401",
    "docstring": "Manages users enrolled u2f devices"
  },
  {
    "code": "def body(self):\n        if self._body is None:\n            if self._body_reader is None:\n                self._body = self.input.read(self.content_length or 0)\n            else:\n                self._body = self._body_reader(self.input)\n        return self._body",
    "docstring": "Reads and returns the entire request body.\n\n        On first access, reads `content_length` bytes from `input` and stores\n        the result on the request object. On subsequent access, returns the\n        cached value."
  },
  {
    "code": "def rm(path, service_names=None):\n    project = __load_project(path)\n    if isinstance(project, dict):\n        return project\n    else:\n        try:\n            project.remove_stopped(service_names)\n        except Exception as inst:\n            return __handle_except(inst)\n    return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)",
    "docstring": "Remove stopped containers in the docker-compose file, service_names is a python\n    list, if omitted remove all stopped containers\n\n    path\n        Path where the docker-compose file is stored on the server\n    service_names\n        If specified will remove only the specified stopped services\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion dockercompose.rm /path/where/docker-compose/stored\n        salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'"
  },
  {
    "code": "def wrap_inference_results(inference_result_proto):\n  inference_proto = inference_pb2.InferenceResult()\n  if isinstance(inference_result_proto,\n                classification_pb2.ClassificationResponse):\n    inference_proto.classification_result.CopyFrom(\n        inference_result_proto.result)\n  elif isinstance(inference_result_proto, regression_pb2.RegressionResponse):\n    inference_proto.regression_result.CopyFrom(inference_result_proto.result)\n  return inference_proto",
    "docstring": "Returns packaged inference results from the provided proto.\n\n  Args:\n    inference_result_proto: The classification or regression response proto.\n\n  Returns:\n    An InferenceResult proto with the result from the response."
  },
  {
    "code": "def store_work_results(self, results, collection, md5):\n        results['md5'] = md5\n        results['__time_stamp'] = datetime.datetime.utcnow()\n        if 'mod_time' not in results:\n            results['mod_time'] = results['__time_stamp']\n        try:\n            self.database[collection].update({'md5':md5}, self.clean_for_storage(results), True)\n        except pymongo.errors.OperationFailure:\n            print 'Could not update exising object in capped collection, punting...'\n            print 'collection: %s md5:%s' % (collection, md5)",
    "docstring": "Store the output results of the worker.\n\n        Args:\n            results: a dictionary.\n            collection: the database collection to store the results in.\n            md5: the md5 of sample data to be updated."
  },
  {
    "code": "def create_logstash(self, **kwargs):\n        logstash = predix.admin.logstash.Logging(**kwargs)\n        logstash.create()\n        logstash.add_to_manifest(self)\n        logging.info('Install Kibana-Me-Logs application by following GitHub instructions')\n        logging.info('git clone https://github.com/cloudfoundry-community/kibana-me-logs.git')\n        return logstash",
    "docstring": "Creates an instance of the Logging Service."
  },
  {
    "code": "def add_reorganize_data(self, name, input_name, output_name, mode = 'SPACE_TO_DEPTH', block_size = 2):\n        spec = self.spec\n        nn_spec = self.nn_spec\n        spec_layer = nn_spec.layers.add()\n        spec_layer.name = name\n        spec_layer.input.append(input_name)\n        spec_layer.output.append(output_name)\n        spec_layer_params = spec_layer.reorganizeData\n        if block_size < 2:\n            raise ValueError(\"Invalid block_size value %d. Must be greater than 1.\" % block_size)\n        spec_layer_params.blockSize = block_size\n        if mode == 'SPACE_TO_DEPTH':\n            spec_layer_params.mode = \\\n                        _NeuralNetwork_pb2.ReorganizeDataLayerParams.ReorganizationType.Value('SPACE_TO_DEPTH')\n        elif mode == 'DEPTH_TO_SPACE':\n            spec_layer_params.mode = \\\n                        _NeuralNetwork_pb2.ReorganizeDataLayerParams.ReorganizationType.Value('DEPTH_TO_SPACE')\n        else:\n            raise NotImplementedError(\n                'Unknown reorganization mode %s ' % mode)",
    "docstring": "Add a data reorganization layer of type \"SPACE_TO_DEPTH\" or \"DEPTH_TO_SPACE\".\n\n        Parameters\n        ----------\n        name: str\n            The name of this layer.\n\n        input_name: str\n            The input blob name of this layer.\n        output_name: str\n            The output blob name of this layer.\n\n        mode: str\n\n            - If mode == 'SPACE_TO_DEPTH': data is moved from the spatial to the channel dimension.\n              Input is spatially divided into non-overlapping blocks of size block_size X block_size\n              and data from each block is moved to the channel dimension.\n              Output CHW dimensions are: [C * block_size * block_size, H/block_size, C/block_size].\n\n            - If mode == 'DEPTH_TO_SPACE': data is moved from the channel to the spatial dimension.\n              Reverse of the operation 'SPACE_TO_DEPTH'.\n              Output CHW dimensions are: [C/(block_size * block_size), H * block_size, C * block_size].\n\n        block_size: int\n            Must be greater than 1. Must divide H and W, when mode is 'SPACE_TO_DEPTH'. (block_size * block_size)\n            must divide C when mode is 'DEPTH_TO_SPACE'.\n\n        See Also\n        --------\n        add_flatten, add_reshape"
  },
  {
    "code": "def _add_view_menu(self):\n        mainMenu = self.app.mainMenu()\n        viewMenu = AppKit.NSMenu.alloc().init()\n        viewMenu.setTitle_(localization[\"cocoa.menu.view\"])\n        viewMenuItem = AppKit.NSMenuItem.alloc().init()\n        viewMenuItem.setSubmenu_(viewMenu)\n        mainMenu.addItem_(viewMenuItem)\n        fullScreenMenuItem = viewMenu.addItemWithTitle_action_keyEquivalent_(localization[\"cocoa.menu.fullscreen\"], \"toggleFullScreen:\", \"f\")\n        fullScreenMenuItem.setKeyEquivalentModifierMask_(AppKit.NSControlKeyMask | AppKit.NSCommandKeyMask)",
    "docstring": "Create a default View menu that shows 'Enter Full Screen'."
  },
  {
    "code": "def close(self):\n        for handle in self._handles:\n            if not handle.closed:\n                handle.close()\n        del self._handles[:]\n        for transport, _ in self.connections:\n            transport.close()\n        self._all_closed.wait()",
    "docstring": "Close the listening sockets and all accepted connections."
  },
  {
    "code": "def _re_raise_as(NewExc, *args, **kw):\n    etype, val, tb = sys.exc_info()\n    raise NewExc(*args, **kw), None, tb",
    "docstring": "Raise a new exception using the preserved traceback of the last one."
  },
  {
    "code": "def start(self):\n        logging.info(\"Fixedconf watcher plugin: Started\")\n        cidr       = self.conf['fixed_cidr']\n        hosts      = self.conf['fixed_hosts'].split(\":\")\n        route_spec = {cidr : hosts}\n        try:\n            common.parse_route_spec_config(route_spec)\n            self.q_route_spec.put(route_spec)\n        except Exception as e:\n            logging.warning(\"Fixedconf watcher plugin: \"\n                            \"Invalid route spec: %s\" % str(e))",
    "docstring": "Start the config watch thread or process."
  },
  {
    "code": "def get_queues(*queue_names, **kwargs):\n    from .settings import QUEUES\n    if len(queue_names) <= 1:\n        return [get_queue(*queue_names, **kwargs)]\n    kwargs['job_class'] = get_job_class(kwargs.pop('job_class', None))\n    queue_params = QUEUES[queue_names[0]]\n    connection_params = filter_connection_params(queue_params)\n    queues = [get_queue(queue_names[0], **kwargs)]\n    for name in queue_names[1:]:\n        queue = get_queue(name, **kwargs)\n        if type(queue) is not type(queues[0]):\n            raise ValueError(\n                'Queues must have the same class.'\n                '\"{0}\" and \"{1}\" have '\n                'different classes'.format(name, queue_names[0]))\n        if connection_params != filter_connection_params(QUEUES[name]):\n            raise ValueError(\n                'Queues must have the same redis connection.'\n                '\"{0}\" and \"{1}\" have '\n                'different connections'.format(name, queue_names[0]))\n        queues.append(queue)\n    return queues",
    "docstring": "Return queue instances from specified queue names.\n    All instances must use the same Redis connection."
  },
  {
    "code": "def purge_metadata_by_name(self, name):\n    meta_dir = self._get_metadata_dir_by_name(name, self._metadata_base_dir)\n    logger.debug('purging metadata directory: {}'.format(meta_dir))\n    try:\n      rm_rf(meta_dir)\n    except OSError as e:\n      raise ProcessMetadataManager.MetadataError('failed to purge metadata directory {}: {!r}'.format(meta_dir, e))",
    "docstring": "Purge a processes metadata directory.\n\n    :raises: `ProcessManager.MetadataError` when OSError is encountered on metadata dir removal."
  },
  {
    "code": "def _validate_file_roots(file_roots):\n    if not isinstance(file_roots, dict):\n        log.warning('The file_roots parameter is not properly formatted,'\n                    ' using defaults')\n        return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}\n    return _normalize_roots(file_roots)",
    "docstring": "If the file_roots option has a key that is None then we will error out,\n    just replace it with an empty list"
  },
  {
    "code": "def validate(tool_class, model_class):\n    if not hasattr(tool_class, 'name'):\n        raise ImproperlyConfigured(\"No 'name' attribute found for tool %s.\" % (\n            tool_class.__name__\n        ))\n    if not hasattr(tool_class, 'label'):\n        raise ImproperlyConfigured(\"No 'label' attribute found for tool %s.\" % (\n            tool_class.__name__\n        ))\n    if not hasattr(tool_class, 'view'):\n        raise NotImplementedError(\"No 'view' method found for tool %s.\" % (\n            tool_class.__name__\n        ))",
    "docstring": "Does basic ObjectTool option validation."
  },
  {
    "code": "def get_structure(atoms, cls=None):\n        symbols = atoms.get_chemical_symbols()\n        positions = atoms.get_positions()\n        lattice = atoms.get_cell()\n        cls = Structure if cls is None else cls\n        return cls(lattice, symbols, positions,\n                   coords_are_cartesian=True)",
    "docstring": "Returns pymatgen structure from ASE Atoms.\n\n        Args:\n            atoms: ASE Atoms object\n            cls: The Structure class to instantiate (defaults to pymatgen structure)\n\n        Returns:\n            Equivalent pymatgen.core.structure.Structure"
  },
  {
    "code": "def cases(self, env, data):\n        for handler in self.handlers:\n            env._push()\n            data._push()\n            try:\n                result = handler(env, data)\n            finally:\n                env._pop()\n                data._pop()\n            if result is not None:\n                return result",
    "docstring": "Calls each nested handler until one of them returns nonzero result.\n\n        If any handler returns `None`, it is interpreted as \n        \"request does not match, the handler has nothing to do with it and \n        `web.cases` should try to call the next handler\"."
  },
  {
    "code": "def show_command(endpoint_id, rule_id):\n    client = get_client()\n    rule = client.get_endpoint_acl_rule(endpoint_id, rule_id)\n    formatted_print(\n        rule,\n        text_format=FORMAT_TEXT_RECORD,\n        fields=(\n            (\"Rule ID\", \"id\"),\n            (\"Permissions\", \"permissions\"),\n            (\"Shared With\", _shared_with_keyfunc),\n            (\"Path\", \"path\"),\n        ),\n    )",
    "docstring": "Executor for `globus endpoint permission show`"
  },
  {
    "code": "def PostUnregistration(method):\n    if not isinstance(method, types.FunctionType):\n        raise TypeError(\"@PostUnregistration can only be applied on functions\")\n    validate_method_arity(method, \"service_reference\")\n    _append_object_entry(\n        method,\n        constants.IPOPO_METHOD_CALLBACKS,\n        constants.IPOPO_CALLBACK_POST_UNREGISTRATION,\n    )\n    return method",
    "docstring": "The service post-unregistration callback decorator is called after a service\n    of the component has been unregistered from the framework.\n\n    The decorated method must accept the\n    :class:`~pelix.framework.ServiceReference` of the registered\n    service as argument::\n\n       @PostUnregistration\n       def callback_method(self, service_reference):\n           '''\n           service_reference: The ServiceReference of the provided service\n           '''\n           # ...\n\n    :param method: The decorated method\n    :raise TypeError: The decorated element is not a valid function"
  },
  {
    "code": "def meth_list(args):\n    r = fapi.list_repository_methods(namespace=args.namespace,\n                                     name=args.method,\n                                     snapshotId=args.snapshot_id)\n    fapi._check_response_code(r, 200)\n    methods = r.json()\n    results = []\n    for m in methods:\n        ns = m['namespace']\n        n = m['name']\n        sn_id = m['snapshotId']\n        results.append('{0}\\t{1}\\t{2}'.format(ns,n,sn_id))\n    return sorted(results, key=lambda s: s.lower())",
    "docstring": "List workflows in the methods repository"
  },
  {
    "code": "def std_blocksum(data, block_sizes, mask=None):\n    data = np.ma.asanyarray(data)\n    if mask is not None and mask is not np.ma.nomask:\n        mask = np.asanyarray(mask)\n        if data.shape != mask.shape:\n            raise ValueError('data and mask must have the same shape.')\n        data.mask |= mask\n    stds = []\n    block_sizes = np.atleast_1d(block_sizes)\n    for block_size in block_sizes:\n        mesh_values = _mesh_values(data, block_size)\n        block_sums = np.sum(mesh_values, axis=1)\n        stds.append(np.std(block_sums))\n    return np.array(stds)",
    "docstring": "Calculate the standard deviation of block-summed data values at\n    sizes of ``block_sizes``.\n\n    Values from incomplete blocks, either because of the image edges or\n    masked pixels, are not included.\n\n    Parameters\n    ----------\n    data : array-like\n        The 2D array to block sum.\n\n    block_sizes : int, array-like of int\n        An array of integer (square) block sizes.\n\n    mask : array-like (bool), optional\n        A boolean mask, with the same shape as ``data``, where a `True`\n        value indicates the corresponding element of ``data`` is masked.\n        Blocks that contain *any* masked data are excluded from\n        calculations.\n\n    Returns\n    -------\n    result : `~numpy.ndarray`\n        An array of the standard deviations of the block-summed array\n        for the input ``block_sizes``."
  },
  {
    "code": "def get_info(brain_or_object, endpoint=None, complete=False):\n    if not is_brain(brain_or_object):\n        brain_or_object = get_brain(brain_or_object)\n        if brain_or_object is None:\n            logger.warn(\"Couldn't find/fetch brain of {}\".format(brain_or_object))\n            return {}\n        complete = True\n    if is_relationship_object(brain_or_object):\n        logger.warn(\"Skipping relationship object {}\".format(repr(brain_or_object)))\n        return {}\n    info = IInfo(brain_or_object).to_dict()\n    url_info = get_url_info(brain_or_object, endpoint)\n    info.update(url_info)\n    parent = get_parent_info(brain_or_object)\n    info.update(parent)\n    if complete:\n        obj = api.get_object(brain_or_object)\n        adapter = IInfo(obj)\n        info.update(adapter.to_dict())\n        if req.get_workflow(False):\n            info.update(get_workflow_info(obj))\n    return info",
    "docstring": "Extract the data from the catalog brain or object\n\n    :param brain_or_object: A single catalog brain or content object\n    :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain\n    :param endpoint: The named URL endpoint for the root of the items\n    :type endpoint: str/unicode\n    :param complete: Flag to wake up the object and fetch all data\n    :type complete: bool\n    :returns: Data mapping for the object/catalog brain\n    :rtype: dict"
  },
  {
    "code": "def in_cache(self, zenpy_object):\n        object_type = get_object_type(zenpy_object)\n        cache_key_attr = self._cache_key_attribute(object_type)\n        return self.get(object_type, getattr(zenpy_object, cache_key_attr)) is not None",
    "docstring": "Determine whether or not this object is in the cache"
  },
  {
    "code": "def charset_to_int(s, charset):\n    output = 0\n    for char in s:\n        output = output * len(charset) + charset.index(char)\n    return output",
    "docstring": "Turn a string into a non-negative integer.\n\n    >>> charset_to_int('0', B40_CHARS)\n    0\n    >>> charset_to_int('10', B40_CHARS)\n    40\n    >>> charset_to_int('abcd', B40_CHARS)\n    658093\n    >>> charset_to_int('', B40_CHARS)\n    0\n    >>> charset_to_int('muneeb.id', B40_CHARS)\n    149190078205533\n    >>> charset_to_int('A', B40_CHARS)\n    Traceback (most recent call last):\n        ...\n    ValueError: substring not found"
  },
  {
    "code": "def index_delete(index, hosts=None, profile=None):\n    es = _get_instance(hosts, profile)\n    try:\n        result = es.indices.delete(index=index)\n        return result.get('acknowledged', False)\n    except elasticsearch.exceptions.NotFoundError:\n        return True\n    except elasticsearch.TransportError as e:\n        raise CommandExecutionError(\"Cannot delete index {0}, server returned code {1} with message {2}\".format(index, e.status_code, e.error))",
    "docstring": "Delete an index\n\n    index\n        Index name\n\n    CLI example::\n\n        salt myminion elasticsearch.index_delete testindex"
  },
  {
    "code": "def set_perspective(self, fov, aspect, near, far):\n        self.matrix = transforms.perspective(fov, aspect, near, far)",
    "docstring": "Set the perspective\n\n        Parameters\n        ----------\n        fov : float\n            Field of view.\n        aspect : float\n            Aspect ratio.\n        near : float\n            Near location.\n        far : float\n            Far location."
  },
  {
    "code": "def cummean(expr, sort=None, ascending=True, unique=False,\n            preceding=None, following=None):\n    data_type = _stats_type(expr)\n    return _cumulative_op(expr, CumMean, sort=sort, ascending=ascending,\n                          unique=unique, preceding=preceding,\n                          following=following, data_type=data_type)",
    "docstring": "Calculate cumulative mean of a sequence expression.\n\n    :param expr: expression for calculation\n    :param sort: name of the sort column\n    :param ascending: whether to sort in ascending order\n    :param unique: whether to eliminate duplicate entries\n    :param preceding: the start point of a window\n    :param following: the end point of a window\n    :return: calculated column"
  },
  {
    "code": "def save_context(context):\n    file_path = _get_context_filepath()\n    content = format_to_http_prompt(context, excluded_options=EXCLUDED_OPTIONS)\n    with io.open(file_path, 'w', encoding='utf-8') as f:\n        f.write(content)",
    "docstring": "Save a Context object to user data directory."
  },
  {
    "code": "def within(self, x, ctrs, kdtree=None):\n        if kdtree is None:\n            idxs = np.where(lalg.norm(ctrs - x, axis=1) <= self.radius)[0]\n        else:\n            idxs = kdtree.query_ball_point(x, self.radius, p=2.0, eps=0)\n        return idxs",
    "docstring": "Check which balls `x` falls within. Uses a K-D Tree to\n        perform the search if provided."
  },
  {
    "code": "def trcdep():\n    depth = ctypes.c_int()\n    libspice.trcdep_c(ctypes.byref(depth))\n    return depth.value",
    "docstring": "Return the number of modules in the traceback representation.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/trcdep_c.html\n\n    :return: The number of modules in the traceback.\n    :rtype: int"
  },
  {
    "code": "async def client_event_handler(self, client_id, event_tuple, user_data):\n        conn_string, event_name, _event = event_tuple\n        self._logger.debug(\"Ignoring event %s from device %s forwarded for client %s\",\n                           event_name, conn_string, client_id)\n        return None",
    "docstring": "Method called to actually send an event to a client.\n\n        Users of this class should override this method to actually forward\n        device events to their clients.  It is called with the client_id\n        passed to (or returned from) :meth:`setup_client` as well as the\n        user_data object that was included there.\n\n        The event tuple is a 3-tuple of:\n\n        - connection string\n        - event name\n        - event object\n\n        If you override this to be acoroutine, it will be awaited.  The\n        default implementation just logs the event.\n\n        Args:\n            client_id (str): The client_id that this event should be forwarded\n                to.\n            event_tuple (tuple): The connection_string, event_name and event_object\n                that should be forwarded.\n            user_data (object): Any user data that was passed to setup_client."
  },
  {
    "code": "def passthrough_repl(self, inputstring, **kwargs):\n        out = []\n        index = None\n        for c in append_it(inputstring, None):\n            try:\n                if index is not None:\n                    if c is not None and c in nums:\n                        index += c\n                    elif c == unwrapper and index:\n                        ref = self.get_ref(\"passthrough\", index)\n                        out.append(ref)\n                        index = None\n                    elif c != \"\\\\\" or index:\n                        out.append(\"\\\\\" + index)\n                        if c is not None:\n                            out.append(c)\n                        index = None\n                elif c is not None:\n                    if c == \"\\\\\":\n                        index = \"\"\n                    else:\n                        out.append(c)\n            except CoconutInternalException as err:\n                complain(err)\n                if index is not None:\n                    out.append(index)\n                    index = None\n                out.append(c)\n        return \"\".join(out)",
    "docstring": "Add back passthroughs."
  },
  {
    "code": "def get_shutit_pexpect_session_environment(self, environment_id):\n\t\tif not isinstance(environment_id, str):\n\t\t\tself.fail('Wrong argument type in get_shutit_pexpect_session_environment')\n\t\tfor env in shutit_global.shutit_global_object.shutit_pexpect_session_environments:\n\t\t\tif env.environment_id == environment_id:\n\t\t\t\treturn env\n\t\treturn None",
    "docstring": "Returns the first shutit_pexpect_session object related to the given\n\t\tenvironment-id"
  },
  {
    "code": "def get_time():\n    time_request = '\\x1b' + 47 * '\\0'\n    now = struct.unpack(\"!12I\", ntp_service.request(time_request, timeout=5.0).data.read())[10]\n    return time.ctime(now - EPOCH_START)",
    "docstring": "Get time from a locally running NTP server"
  },
  {
    "code": "def gen_div(src1, src2, dst):\n        assert src1.size == src2.size\n        return ReilBuilder.build(ReilMnemonic.DIV, src1, src2, dst)",
    "docstring": "Return a DIV instruction."
  },
  {
    "code": "def _clean_dirty(self, obj=None):\n        obj = obj or self\n        obj.__dict__['_dirty_attributes'].clear()\n        obj._dirty = False\n        for key, val in vars(obj).items():\n            if isinstance(val, BaseObject):\n                self._clean_dirty(val)\n            else:\n                func = getattr(val, '_clean_dirty', None)\n                if callable(func):\n                    func()",
    "docstring": "Recursively clean self and all child objects."
  },
  {
    "code": "def _check_markers(task_ids, offset=10):\n    shuffle(task_ids)\n    has_errors = False\n    for index in xrange(0, len(task_ids), offset):\n        keys = [ndb.Key(FuriousAsyncMarker, id)\n                for id in task_ids[index:index + offset]]\n        markers = ndb.get_multi(keys)\n        if not all(markers):\n            logging.debug(\"Not all Async's complete\")\n            return False, None\n        has_errors = not all((marker.success for marker in markers))\n    return True, has_errors",
    "docstring": "Returns a flag for markers being found for the task_ids. If all task ids\n    have markers True will be returned. Otherwise it will return False as soon\n    as a None result is hit."
  },
  {
    "code": "def write_meta(self, role):\n        meta_file = utils.file_to_string(self.paths[\"meta\"])\n        self.update_gen_report(role, \"meta\", meta_file)",
    "docstring": "Write out a new meta file."
  },
  {
    "code": "def prune_creds_json(creds: dict, cred_ids: set) -> str:\n    rv = deepcopy(creds)\n    for key in ('attrs', 'predicates'):\n        for attr_uuid, creds_by_uuid in rv[key].items():\n            rv[key][attr_uuid] = [cred for cred in creds_by_uuid if cred['cred_info']['referent'] in cred_ids]\n        empties = [attr_uuid for attr_uuid in rv[key] if not rv[key][attr_uuid]]\n        for attr_uuid in empties:\n            del rv[key][attr_uuid]\n    return json.dumps(rv)",
    "docstring": "Strip all creds out of the input json structure that do not match any of the input credential identifiers.\n\n    :param creds: indy-sdk creds structure\n    :param cred_ids: the set of credential identifiers of interest\n    :return: the reduced creds json"
  },
  {
    "code": "def get_page_children_dict(self, page_qs=None):\n        children_dict = defaultdict(list)\n        for page in page_qs or self.pages_for_display:\n            children_dict[page.path[:-page.steplen]].append(page)\n        return children_dict",
    "docstring": "Returns a dictionary of lists, where the keys are 'path' values for\n        pages, and the value is a list of children pages for that page."
  },
  {
    "code": "def get_queryset(self):\n        qs = VersionedQuerySet(self.model, using=self._db)\n        if hasattr(self, 'instance') and hasattr(self.instance, '_querytime'):\n            qs.querytime = self.instance._querytime\n        return qs",
    "docstring": "Returns a VersionedQuerySet capable of handling version time\n        restrictions.\n\n        :return: VersionedQuerySet"
  },
  {
    "code": "def in_session(self):\n        session = self.get_session()\n        try:\n            yield session\n            session.commit()\n        except IntegrityError:\n            session.rollback()\n            raise DuplicateError(\"Duplicate unique value detected!\")\n        except (OperationalError, DisconnectionError):\n            session.rollback()\n            self.close()\n            logger.warn(\"Database Connection Lost!\")\n            raise DatabaseConnectionError()\n        except Exception:\n            session.rollback()\n            raise\n        finally:\n            session.close()",
    "docstring": "Provide a session scope around a series of operations."
  },
  {
    "code": "def value_series(self, key, start=None, end=None, interval=None,\n                     namespace=None, cache=None):\n        return self.make_context(key=key, start=start, end=end,\n                                 interval=interval, namespace=namespace,\n                                 cache=cache).value_series()",
    "docstring": "Get a time series of gauge values"
  },
  {
    "code": "def home_page(self, tld_type: Optional[TLDType] = None) -> str:\n        resource = self.random.choice(USERNAMES)\n        domain = self.top_level_domain(\n            tld_type=tld_type,\n        )\n        return 'http://www.{}{}'.format(\n            resource, domain)",
    "docstring": "Generate a random home page.\n\n        :param tld_type: TLD type.\n        :return: Random home page.\n\n        :Example:\n            http://www.fontir.info"
  },
  {
    "code": "def imprint(self, path=None):\n        if self.version is not None:\n            with open(path or self.version_file, 'w') as h:\n                h.write(self.version + '\\n')\n        else:\n            raise ValueError('Can not write null version to file.')\n        return self",
    "docstring": "Write the determined version, if any, to ``self.version_file`` or\n           the path passed as an argument."
  },
  {
    "code": "def progressive(image_field, alt_text=''):\n    if not isinstance(image_field, ImageFieldFile):\n        raise ValueError('\"image_field\" argument must be an ImageField.')\n    for engine in engines.all():\n        if isinstance(engine, BaseEngine) and hasattr(engine, 'env'):\n            env = engine.env\n            if isinstance(env, Environment):\n                context = render_progressive_field(image_field, alt_text)\n                template = env.get_template(\n                    'progressiveimagefield/render_field.html'\n                )\n                rendered = template.render(**context)\n                return Markup(rendered)\n    return ''",
    "docstring": "Used as a Jinja2 filter, this function returns a safe HTML chunk.\n\n    Usage (in the HTML template):\n\n        {{ obj.image|progressive }}\n\n    :param django.db.models.fields.files.ImageFieldFile image_field: image\n    :param str alt_text: str\n    :return: a safe HTML template ready to be rendered"
  },
  {
    "code": "def add_vcenter(self, **kwargs):\n        config = ET.Element(\"config\")\n        vcenter = ET.SubElement(config, \"vcenter\",\n                                xmlns=\"urn:brocade.com:mgmt:brocade-vswitch\")\n        id = ET.SubElement(vcenter, \"id\")\n        id.text = kwargs.pop('id')\n        credentials = ET.SubElement(vcenter, \"credentials\")\n        url = ET.SubElement(credentials, \"url\")\n        url.text = kwargs.pop('url')\n        username = ET.SubElement(credentials, \"username\")\n        username.text = kwargs.pop('username')\n        password = ET.SubElement(credentials, \"password\")\n        password.text = kwargs.pop('password')\n        try:\n            self._callback(config)\n            return True\n        except Exception as error:\n            logging.error(error)\n            return False",
    "docstring": "Add vCenter on the switch\n\n        Args:\n            id(str) : Name of an established vCenter\n            url (bool) : vCenter URL\n            username (str): Username of the vCenter\n            password (str): Password of the vCenter\n            callback (function): A function executed upon completion of the\n                 method.\n\n        Returns:\n           Return value of `callback`.\n\n        Raises:\n            None"
  },
  {
    "code": "def _store_information(self):\n        print '<<< Generating Information Storage >>>'\n        for name, meth in inspect.getmembers(self, predicate=inspect.isroutine):\n            if not name.startswith('_'):\n                info = {'command': name, 'sig': str(funcsigs.signature(meth)), 'docstring': meth.__doc__}\n                self.store_info(info, name, type_tag='command')\n        self.store_info({'help': '<<< Workbench Server Version %s >>>' % self.version}, 'version', type_tag='help')\n        self.store_info({'help': self._help_workbench()}, 'workbench', type_tag='help')\n        self.store_info({'help': self._help_basic()}, 'basic', type_tag='help')\n        self.store_info({'help': self._help_commands()}, 'commands', type_tag='help')\n        self.store_info({'help': self._help_workers()}, 'workers', type_tag='help')",
    "docstring": "Store infomation about Workbench and its commands"
  },
  {
    "code": "def load_schema(schema_path):\n    with open(schema_path, 'r') as schema_file:\n        schema = simplejson.load(schema_file)\n    resolver = RefResolver('', '', schema.get('models', {}))\n    return build_request_to_validator_map(schema, resolver)",
    "docstring": "Prepare the api specification for request and response validation.\n\n    :returns: a mapping from :class:`RequestMatcher` to :class:`ValidatorMap`\n        for every operation in the api specification.\n    :rtype: dict"
  },
  {
    "code": "def is_int(tg_type, inc_array=False):\n    global _scalar_int_types, _array_int_types\n    if tg_type in _scalar_int_types:\n        return True\n    if not inc_array:\n        return False\n    return tg_type in _array_int_types",
    "docstring": "Tells if the given tango type is integer\n\n    :param tg_type: tango type\n    :type tg_type: :class:`tango.CmdArgType`\n    :param inc_array: (optional, default is False) determines if include array\n                      in the list of checked types\n    :type inc_array: :py:obj:`bool`\n\n    :return: True if the given tango type is integer or False otherwise\n    :rtype: :py:obj:`bool`"
  },
  {
    "code": "def get_description(cls) -> str:\n        if cls.__doc__ is None:\n            raise ValueError('No docstring found for {}'.format(cls.__name__))\n        return cls.__doc__.strip()",
    "docstring": "The description is expected to be the command class' docstring."
  },
  {
    "code": "def load(self, filename=None):\n        fields = []\n        with open(filename, 'r') as f:\n            format_data = f.read().strip()\n        lines = format_data.split('\\n')\n        self._sql_version = lines.pop(0)\n        self._num_fields = int(lines.pop(0))\n        for line in lines:\n            line = re.sub(' +', ' ', line.strip())\n            row_format = BCPFormatRow(line.split(' '))\n            fields.append(row_format)\n        self.fields = fields\n        self.filename = filename",
    "docstring": "Reads a non-XML bcp FORMAT file and parses it into fields list used for creating bulk data file"
  },
  {
    "code": "def stoptimes(self, start_date, end_date):\n        params = {\n            'start': self.format_date(start_date),\n            'end': self.format_date(end_date)\n        }\n        response = self._request(ENDPOINTS['STOPTIMES'], params)\n        return response",
    "docstring": "Return all stop times in the date range\n\n        :param start_date:\n            The starting date for the query.\n        :param end_date:\n            The end date for the query.\n        >>> import datetime\n        >>> today = datetime.date.today()\n        >>> trans.stoptimes(today - datetime.timedelta(days=1), today)"
  },
  {
    "code": "def bind(self, typevar, its_type):\n        assert type(typevar) == tg.TypeVar\n        if self.is_generic_in(typevar):\n            self.bind_to_instance(typevar, its_type)\n        else:\n            self._ns[typevar] = its_type",
    "docstring": "Binds typevar to the type its_type.\n        Binding occurs on the instance if the typevar is a TypeVar of the\n        generic type of the instance, on call level otherwise."
  },
  {
    "code": "def prepare_input_data(config):\n    if not dd.get_disambiguate(config):\n        return dd.get_input_sequence_files(config)\n    work_bam = dd.get_work_bam(config)\n    logger.info(\"Converting disambiguated reads to fastq...\")\n    fq_files = convert_bam_to_fastq(\n        work_bam, dd.get_work_dir(config), None, None, config\n    )\n    return fq_files",
    "docstring": "In case of disambiguation, we want to run fusion calling on\n    the disambiguated reads, which are in the work_bam file.\n    As EricScript accepts 2 fastq files as input, we need to convert\n    the .bam to 2 .fq files."
  },
  {
    "code": "def do_eni(self,args):\n        parser = CommandArgumentParser(\"eni\")\n        parser.add_argument(dest='eni',help='eni index or name');\n        args = vars(parser.parse_args(args))\n        print \"loading eni {}\".format(args['eni'])\n        try:\n            index = int(args['eni'])\n            eniSummary = self.wrappedStack['resourcesByTypeIndex']['AWS::EC2::NetworkInterface'][index]\n        except ValueError:\n            eniSummary = self.wrappedStack['resourcesByTypeName']['AWS::EC2::NetworkInterface'][args['eni']]\n        pprint(eniSummary)\n        self.stackResource(eniSummary.stack_name,eniSummary.logical_id)",
    "docstring": "Go to the specified eni. eni -h for detailed help."
  },
  {
    "code": "def add_tlink(self,my_tlink):\n        if self.temporalRelations_layer is None:\n            self.temporalRelations_layer = CtemporalRelations()\n            self.root.append(self.temporalRelations_layer.get_node())\n        self.temporalRelations_layer.add_tlink(my_tlink)",
    "docstring": "Adds a tlink to the temporalRelations layer\n        @type my_tlink: L{Ctlink}\n        @param my_tlink: tlink object"
  },
  {
    "code": "def worker_recover(name, workers=None, profile='default'):\n    if workers is None:\n        workers = []\n    return _bulk_state(\n        'modjk.bulk_recover', name, workers, profile\n    )",
    "docstring": "Recover all the workers in the modjk load balancer\n\n    Example:\n\n    .. code-block:: yaml\n\n        loadbalancer:\n          modjk.worker_recover:\n            - workers:\n              - app1\n              - app2"
  },
  {
    "code": "def exists(name, tags=None, region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    try:\n        rds = conn.describe_db_instances(DBInstanceIdentifier=name)\n        return {'exists': bool(rds)}\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Check to see if an RDS exists.\n\n    CLI example::\n\n        salt myminion boto_rds.exists myrds region=us-east-1"
  },
  {
    "code": "def add_arguments(self, parser):\n        parser.add_argument('app_label', nargs='*')\n        for argument in self.arguments:\n            parser.add_argument(*argument.split(' '), **self.arguments[argument])",
    "docstring": "Unpack self.arguments for parser.add_arguments."
  },
  {
    "code": "def time_stamp():\n    fmt = '%Y-%m-%dT%H:%M:%S.%f'\n    date = datetime.datetime\n    date_delta = datetime.timedelta\n    now = datetime.datetime.utcnow()\n    return fmt, date, date_delta, now",
    "docstring": "Setup time functions\n\n    :returns: ``tuple``"
  },
  {
    "code": "def transplant(new_net, net, suffix=''):\n    for p in net.params:\n        p_new = p + suffix\n        if p_new not in new_net.params:\n            print 'dropping', p\n            continue\n        for i in range(len(net.params[p])):\n            if i > (len(new_net.params[p_new]) - 1):\n                print 'dropping', p, i\n                break\n            if net.params[p][i].data.shape != new_net.params[p_new][i].data.shape:\n                print 'coercing', p, i, 'from', net.params[p][i].data.shape, 'to', new_net.params[p_new][i].data.shape\n            else:\n                print 'copying', p, ' -> ', p_new, i\n            new_net.params[p_new][i].data.flat = net.params[p][i].data.flat",
    "docstring": "Transfer weights by copying matching parameters, coercing parameters of\n    incompatible shape, and dropping unmatched parameters.\n\n    The coercion is useful to convert fully connected layers to their\n    equivalent convolutional layers, since the weights are the same and only\n    the shapes are different.  In particular, equivalent fully connected and\n    convolution layers have shapes O x I and O x I x H x W respectively for O\n    outputs channels, I input channels, H kernel height, and W kernel width.\n\n    Both  `net` to `new_net` arguments must be instantiated `caffe.Net`s."
  },
  {
    "code": "def get_filetypes_info(editor_quote=\"`\", flag_leaf=True):\n    NONE_REPL = \"\"\n    import f311\n    data = []\n    for attr in f311.classes_file(flag_leaf):\n        description = a99.get_obj_doc0(attr)\n        def_ = NONE_REPL if attr.default_filename is None else attr.default_filename\n        ee = attr.editors\n        if ee is None:\n            ee = NONE_REPL\n        else:\n            ee = \", \".join([\"{0}{1}{0}\".format(editor_quote, x, editor_quote) for x in ee])\n        data.append({\"description\": description, \"default_filename\": def_, \"classname\": attr.__name__,\n                     \"editors\": ee, \"class\": attr, \"txtbin\": \"text\" if attr.flag_txt else \"binary\"})\n    data.sort(key=lambda x: x[\"description\"])\n    return data",
    "docstring": "Reports available data types\n\n    Args:\n        editor_quote: character to enclose the name of the editor script between.\n        flag_leaf: see tabulate_filetypes_rest()\n\n    Returns:\n        list: list of FileTypeInfo"
  },
  {
    "code": "def _initialize(self, **resource_attributes):\n        super(APIResourceCollection, self)._initialize(**resource_attributes)\n        dict_list = self.data\n        self.data = []\n        for resource in dict_list:\n            self.data.append(self._expected_api_resource(**resource))",
    "docstring": "Initialize the collection.\n\n        :param resource_attributes: API resource parameters"
  },
  {
    "code": "def enclosure_groups(self):\n        if not self.__enclosure_groups:\n            self.__enclosure_groups = EnclosureGroups(self.__connection)\n        return self.__enclosure_groups",
    "docstring": "Gets the EnclosureGroups API client.\n\n        Returns:\n            EnclosureGroups:"
  },
  {
    "code": "def pix2sky(self, pixel):\n        pixbox = numpy.array([pixel, pixel])\n        skybox = self.wcs.all_pix2world(pixbox, 1)\n        return [float(skybox[0][0]), float(skybox[0][1])]",
    "docstring": "Get the sky coordinates for a given image pixel.\n\n        Parameters\n        ----------\n        pixel : (float, float)\n            Image coordinates.\n\n        Returns\n        -------\n        ra,dec : float\n            Sky coordinates (degrees)"
  },
  {
    "code": "def _format_keyword(self, keyword):\n        import re\n        result = ''\n        if keyword:\n            result = re.sub(r\"\\W\", \"\", keyword)\n            result = re.sub(r\"_\", \"\", result)\n        return result",
    "docstring": "Removing special character from a keyword. Analysis Services must have\n        this kind of keywords. E.g. if assay name from GeneXpert Instrument is\n        'Ebola RUO', an AS must be created on Bika with the keyword 'EbolaRUO'"
  },
  {
    "code": "def from_flags(flags, ednsflags):\n    value = (flags & 0x000f) | ((ednsflags >> 20) & 0xff0)\n    if value < 0 or value > 4095:\n        raise ValueError('rcode must be >= 0 and <= 4095')\n    return value",
    "docstring": "Return the rcode value encoded by flags and ednsflags.\n\n    @param flags: the DNS flags\n    @type flags: int\n    @param ednsflags: the EDNS flags\n    @type ednsflags: int\n    @raises ValueError: rcode is < 0 or > 4095\n    @rtype: int"
  },
  {
    "code": "def science_object_update(self, pid_old, path, pid_new, format_id=None):\n        self._queue_science_object_update(pid_old, path, pid_new, format_id)",
    "docstring": "Obsolete a Science Object on a Member Node with a different one."
  },
  {
    "code": "def validate_timeout_or_zero(option, value):\n    if value is None:\n        raise ConfigurationError(\"%s cannot be None\" % (option, ))\n    if value == 0 or value == \"0\":\n        return 0\n    return validate_positive_float(option, value) / 1000.0",
    "docstring": "Validates a timeout specified in milliseconds returning\n    a value in floating point seconds for the case where None is an error\n    and 0 is valid. Setting the timeout to nothing in the URI string is a\n    config error."
  },
  {
    "code": "def resample_multipitch(times, frequencies, target_times):\n    if target_times.size == 0:\n        return []\n    if times.size == 0:\n        return [np.array([])]*len(target_times)\n    n_times = len(frequencies)\n    frequency_index = np.arange(0, n_times)\n    new_frequency_index = scipy.interpolate.interp1d(\n        times, frequency_index, kind='nearest', bounds_error=False,\n        assume_sorted=True, fill_value=n_times)(target_times)\n    freq_vals = frequencies + [np.array([])]\n    frequencies_resampled = [\n        freq_vals[i] for i in new_frequency_index.astype(int)]\n    return frequencies_resampled",
    "docstring": "Resamples multipitch time series to a new timescale. Values in\n    ``target_times`` outside the range of ``times`` return no pitch estimate.\n\n    Parameters\n    ----------\n    times : np.ndarray\n        Array of time stamps\n    frequencies : list of np.ndarray\n        List of np.ndarrays of frequency values\n    target_times : np.ndarray\n        Array of target time stamps\n\n    Returns\n    -------\n    frequencies_resampled : list of numpy arrays\n        Frequency list of lists resampled to new timebase"
  },
  {
    "code": "def run_nupack(kwargs):\n    run = NUPACK(kwargs['seq'])\n    output = getattr(run, kwargs['cmd'])(**kwargs['arguments'])\n    return output",
    "docstring": "Run picklable Nupack command.\n\n    :param kwargs: keyword arguments to pass to Nupack as well as 'cmd'.\n    :returns: Variable - whatever `cmd` returns."
  },
  {
    "code": "def allState(self, *args, **kwargs):\n        return self._makeApiCall(self.funcinfo[\"allState\"], *args, **kwargs)",
    "docstring": "List out the entire internal state\n\n        This method is only for debugging the ec2-manager\n\n        This method is ``experimental``"
  },
  {
    "code": "def source_extraction(in1, tolerance, mode=\"cpu\", store_on_gpu=False,\n                      neg_comp=False):\n    if mode==\"cpu\":\n        return cpu_source_extraction(in1, tolerance, neg_comp)\n    elif mode==\"gpu\":\n        return gpu_source_extraction(in1, tolerance, store_on_gpu, neg_comp)",
    "docstring": "Convenience function for allocating work to cpu or gpu, depending on the selected mode.\n\n    INPUTS:\n    in1         (no default):   Array containing the wavelet decomposition.\n    tolerance   (no default):   Percentage of maximum coefficient at which objects are deemed significant.\n    mode        (default=\"cpu\"):Mode of operation - either \"gpu\" or \"cpu\".\n\n    OUTPUTS:\n    Array containing the significant wavelet coefficients of extracted sources."
  },
  {
    "code": "def relativize_classpath(classpath, root_dir, followlinks=True):\n  def relativize_url(url, root_dir):\n    url = os.path.realpath(url) if followlinks else url\n    root_dir = os.path.realpath(root_dir) if followlinks else root_dir\n    url_in_bundle = os.path.relpath(url, root_dir)\n    if os.path.isdir(url):\n      url_in_bundle += '/'\n    return url_in_bundle\n  return [relativize_url(url, root_dir) for url in classpath]",
    "docstring": "Convert into classpath relative to a directory.\n\n  This is eventually used by a jar file located in this directory as its manifest\n  attribute Class-Path. See\n  https://docs.oracle.com/javase/7/docs/technotes/guides/extensions/spec.html#bundled\n\n  :param list classpath: Classpath to be relativized.\n  :param string root_dir: directory to relativize urls in the classpath, does not\n    have to exist yet.\n  :param bool followlinks: whether to follow symlinks to calculate relative path.\n\n  :returns: Converted classpath of the same size as input classpath.\n  :rtype: list of strings"
  },
  {
    "code": "def condition_details_has_owner(condition_details, owner):\n    if 'subconditions' in condition_details:\n        result = condition_details_has_owner(condition_details['subconditions'], owner)\n        if result:\n            return True\n    elif isinstance(condition_details, list):\n        for subcondition in condition_details:\n            result = condition_details_has_owner(subcondition, owner)\n            if result:\n                return True\n    else:\n        if 'public_key' in condition_details \\\n                and owner == condition_details['public_key']:\n            return True\n    return False",
    "docstring": "Check if the public_key of owner is in the condition details\n    as an Ed25519Fulfillment.public_key\n\n    Args:\n        condition_details (dict): dict with condition details\n        owner (str): base58 public key of owner\n\n    Returns:\n        bool: True if the public key is found in the condition details, False otherwise"
  },
  {
    "code": "def request(community_id, record_id, accept):\n    c = Community.get(community_id)\n    assert c is not None\n    record = Record.get_record(record_id)\n    if accept:\n        c.add_record(record)\n        record.commit()\n    else:\n        InclusionRequest.create(community=c, record=record,\n                                notify=False)\n    db.session.commit()\n    RecordIndexer().index_by_id(record.id)",
    "docstring": "Request a record acceptance to a community."
  },
  {
    "code": "def _init_relationships(self, relationships_arg):\n        if relationships_arg:\n            relationships_all = self._get_all_relationships()\n            if relationships_arg is True:\n                return relationships_all\n            else:\n                return relationships_all.intersection(relationships_arg)\n        return set()",
    "docstring": "Return a set of relationships found in all subset GO Terms."
  },
  {
    "code": "def load_each(*loaders):\n    def _load_each(metadata):\n        return merge(\n            loader(metadata)\n            for loader in loaders\n        )\n    return _load_each",
    "docstring": "Loader factory that combines a series of loaders."
  },
  {
    "code": "def is_ancestor(self, commit1, commit2, patch=False):\n        result = self.hg(\"log\", \"-r\", \"first(%s::%s)\" % (commit1, commit2),\n                         \"--template\", \"exists\", patch=patch)\n        return \"exists\" in result",
    "docstring": "Returns True if commit1 is a direct ancestor of commit2, or False\n        otherwise.\n\n        This method considers a commit to be a direct ancestor of itself"
  },
  {
    "code": "def upload(self, path, engine, description=None):\n        if description is None:\n            head, tail = ntpath.split(path)\n            description = tail or ntpath.basename(head)\n        url = \"http://quickslice.{}/config/raw/\".format(self.config.host)\n        with open(path) as config_file:\n            content = config_file.read()\n        payload = {\"engine\": engine,\n                   \"description\": description,\n                   \"content\": content}\n        post_resp = requests.post(url, json=payload, cookies={\"session\": self.session})\n        if not post_resp.ok:\n            raise errors.ResourceError(\"config upload to slicing service failed\")\n        self.description = description\n        self.location = post_resp.headers[\"Location\"]",
    "docstring": "Create a new config resource in the slicing service and upload the path contents to it"
  },
  {
    "code": "def scan(self, filetypes=None):\n        self.logger.debug(\"Scanning FS content.\")\n        checksums = self.filetype_filter(self._filesystem.checksums('/'),\n                                         filetypes=filetypes)\n        self.logger.debug(\"Querying %d objects to VTotal.\", len(checksums))\n        for files in chunks(checksums, size=self.batchsize):\n            files = dict((reversed(e) for e in files))\n            response = vtquery(self._apikey, files.keys())\n            yield from self.parse_response(files, response)",
    "docstring": "Iterates over the content of the disk and queries VirusTotal\n        to determine whether it's malicious or not.\n\n        filetypes is a list containing regular expression patterns.\n        If given, only the files which type will match with one or more of\n        the given patterns will be queried against VirusTotal.\n\n        For each file which is unknown by VT or positive to any of its engines,\n        the method yields a namedtuple:\n\n        VTReport(path        -> C:\\\\Windows\\\\System32\\\\infected.dll\n                 hash        -> ab231...\n                 detections) -> dictionary engine -> detection\n\n        Files unknown by VirusTotal will contain the string 'unknown'\n        in the detection field."
  },
  {
    "code": "def json_description_metadata(description):\n    if description[:6] == 'shape=':\n        shape = tuple(int(i) for i in description[7:-1].split(','))\n        return dict(shape=shape)\n    if description[:1] == '{' and description[-1:] == '}':\n        return json.loads(description)\n    raise ValueError('invalid JSON image description', description)",
    "docstring": "Return metatata from JSON formated image description as dict.\n\n    Raise ValuError if description is of unknown format.\n\n    >>> description = '{\"shape\": [256, 256, 3], \"axes\": \"YXS\"}'\n    >>> json_description_metadata(description)  # doctest: +SKIP\n    {'shape': [256, 256, 3], 'axes': 'YXS'}\n    >>> json_description_metadata('shape=(256, 256, 3)')\n    {'shape': (256, 256, 3)}"
  },
  {
    "code": "def get_bridges(vnic_dir='/sys/devices/virtual/net'):\n    b_regex = \"%s/*/bridge\" % vnic_dir\n    return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)]",
    "docstring": "Return a list of bridges on the system."
  },
  {
    "code": "def _parse_args(cls):\n        cls.parser = argparse.ArgumentParser()\n        cls.parser.add_argument(\n            \"symbol\", help=\"Symbol for horizontal line\", nargs=\"*\")\n        cls.parser.add_argument(\n            \"--color\", \"-c\", help=\"Color of the line\", default=None, nargs=1)\n        cls.parser.add_argument(\n            \"--version\", \"-v\", action=\"version\", version=\"0.13\")\n        return cls.parser",
    "docstring": "Method to parse command line arguments"
  },
  {
    "code": "def scene_command(self, command):\n        self.logger.info(\"scene_command: Group %s Command %s\", self.group_id, command)\n        command_url = self.hub.hub_url + '/0?' + command + self.group_id + \"=I=0\"\n        return self.hub.post_direct_command(command_url)",
    "docstring": "Wrapper to send posted scene command and get response"
  },
  {
    "code": "def addResource(self, key, filePath, text):\n        url = self.root + \"/addresource\"\n        params = {\n        \"f\": \"json\",\n        \"token\" : self._securityHandler.token,\n        \"key\" : key,\n        \"text\" : text\n        }\n        files = {}\n        files['file'] = filePath\n        res = self._post(url=url,\n                         param_dict=params,\n                         files=files,\n                         securityHandler=self._securityHandler,\n                         proxy_url=self._proxy_url,\n                         proxy_port=self._proxy_port)\n        return res",
    "docstring": "The add resource operation allows the administrator to add a file\n        resource, for example, the organization's logo or custom banner.\n        The resource can be used by any member of the organization. File\n        resources use storage space from your quota and are scanned for\n        viruses.\n\n        Inputs:\n           key - The name the resource should be stored under.\n           filePath - path of file to upload\n           text - Some text to be written (for example, JSON or JavaScript)\n                  directly to the resource from a web client."
  },
  {
    "code": "def populateFromDirectory(self, vcfDirectory):\n        pattern = os.path.join(vcfDirectory, \"*.vcf.gz\")\n        dataFiles = []\n        indexFiles = []\n        for vcfFile in glob.glob(pattern):\n            dataFiles.append(vcfFile)\n            indexFiles.append(vcfFile + \".tbi\")\n        self.populateFromFile(dataFiles, indexFiles)",
    "docstring": "Populates this VariantSet by examing all the VCF files in the\n        specified directory. This is mainly used for as a convenience\n        for testing purposes."
  },
  {
    "code": "def end_profiling(profiler, filename, sorting=None):\n    profiler.disable()\n    s = six.StringIO()\n    ps = pstats.Stats(profiler, stream=s).sort_stats(sorting)\n    ps.print_stats()\n    with open(filename, \"w+\") as f:\n        _logger.info(\"[calculate_ts_features] Finished profiling of time series feature extraction\")\n        f.write(s.getvalue())",
    "docstring": "Helper function to stop the profiling process and write out the profiled\n    data into the given filename. Before this, sort the stats by the passed sorting.\n\n    :param profiler: An already started profiler (probably by start_profiling).\n    :type profiler: cProfile.Profile\n    :param filename: The name of the output file to save the profile.\n    :type filename: basestring\n    :param sorting: The sorting of the statistics passed to the sort_stats function.\n    :type sorting: basestring\n\n    :return: None\n    :rtype: None\n\n    Start and stop the profiler with:\n\n    >>> profiler = start_profiling()\n    >>> # Do something you want to profile\n    >>> end_profiling(profiler, \"out.txt\", \"cumulative\")"
  },
  {
    "code": "def init_types_collection(filter_filename=default_filter_filename):\n    global _filter_filename\n    _filter_filename = filter_filename\n    sys.setprofile(_trace_dispatch)\n    threading.setprofile(_trace_dispatch)",
    "docstring": "Setup profiler hooks to enable type collection.\n    Call this one time from the main thread.\n\n    The optional argument is a filter that maps a filename (from\n    code.co_filename) to either a normalized filename or None.\n    For the default filter see default_filter_filename()."
  },
  {
    "code": "def _cleanup_api(self):\n        resources = __salt__['boto_apigateway.describe_api_resources'](restApiId=self.restApiId,\n                                                                       **self._common_aws_args)\n        if resources.get('resources'):\n            res = resources.get('resources')[1:]\n            res.reverse()\n            for resource in res:\n                delres = __salt__['boto_apigateway.delete_api_resources'](restApiId=self.restApiId,\n                                                                          path=resource.get('path'),\n                                                                          **self._common_aws_args)\n                if not delres.get('deleted'):\n                    return delres\n        models = __salt__['boto_apigateway.describe_api_models'](restApiId=self.restApiId, **self._common_aws_args)\n        if models.get('models'):\n            for model in models.get('models'):\n                delres = __salt__['boto_apigateway.delete_api_model'](restApiId=self.restApiId,\n                                                                      modelName=model.get('name'),\n                                                                      **self._common_aws_args)\n                if not delres.get('deleted'):\n                    return delres\n        return {'deleted': True}",
    "docstring": "Helper method to clean up resources and models if we detected a change in the swagger file\n        for a stage"
  },
  {
    "code": "def add_contact_to_group(self, contact, group):\n        if isinstance(contact, basestring):\n            contact = self.get_contact(contact)\n        if isinstance(group, basestring):\n            group = self.get_group(group)\n        method, url = get_URL('contacts_add_to_group')\n        payload = {\n            'apikey': self.config.get('apikey'),\n            'logintoken': self.session.cookies.get('logintoken'),\n            'contactid': contact['contactid'],\n            'contactgroupid': group['contactgroupid']\n            }\n        res = getattr(self.session, method)(url, params=payload)\n        if res.status_code == 200:\n            return True\n        hellraiser(res)",
    "docstring": "Add contact to group\n\n        :param contact: name or contact object\n        :param group: name or group object\n        :type contact: ``str``, ``unicode``, ``dict``\n        :type group: ``str``, ``unicode``, ``dict``\n        :rtype: ``bool``"
  },
  {
    "code": "def is_expired(self, time_offset_seconds=0):\n        now = datetime.datetime.utcnow()\n        if time_offset_seconds:\n            now = now + datetime.timedelta(seconds=time_offset_seconds)\n        ts = boto.utils.parse_ts(self.expiration)\n        delta = ts - now\n        return delta.total_seconds() <= 0",
    "docstring": "Checks to see if the Session Token is expired or not.  By default\n        it will check to see if the Session Token is expired as of the\n        moment the method is called.  However, you can supply an\n        optional parameter which is the number of seconds of offset\n        into the future for the check.  For example, if you supply\n        a value of 5, this method will return a True if the Session\n        Token will be expired 5 seconds from this moment.\n\n        :type time_offset_seconds: int\n        :param time_offset_seconds: The number of seconds into the future\n            to test the Session Token for expiration."
  },
  {
    "code": "def update_not_existing_kwargs(to_update, update_from):\n    if to_update is None:\n        to_update = {}\n    to_update.update({k:v for k,v in update_from.items() if k not in to_update})\n    return to_update",
    "docstring": "This function updates the keyword aguments from update_from in\n    to_update, only if the keys are not set in to_update.\n\n    This is used for updated kwargs from the default dicts."
  },
  {
    "code": "def from_interbase_coordinates(contig, start, end=None):\n        typechecks.require_string(contig)\n        typechecks.require_integer(start)\n        if end is None:\n            end = start + 1\n        typechecks.require_integer(end)\n        contig = pyensembl.locus.normalize_chromosome(contig)\n        return Locus(contig, start, end)",
    "docstring": "Given coordinates in 0-based interbase coordinates, return a Locus\n        instance."
  },
  {
    "code": "def _update_port_locations(self, initial_coordinates):\n        particles = list(self.particles())\n        for port in self.all_ports():\n            if port.anchor:\n                idx = particles.index(port.anchor)\n                shift = particles[idx].pos - initial_coordinates[idx]\n                port.translate(shift)",
    "docstring": "Adjust port locations after particles have moved\n\n        Compares the locations of Particles between 'self' and an array of\n        reference coordinates.  Shifts Ports in accordance with how far anchors\n        have been moved.  This conserves the location of Ports with respect to\n        their anchor Particles, but does not conserve the orientation of Ports\n        with respect to the molecule as a whole.\n\n        Parameters\n        ----------\n        initial_coordinates : np.ndarray, shape=(n, 3), dtype=float\n            Reference coordinates to use for comparing how far anchor Particles\n            have shifted."
  },
  {
    "code": "def log(self, level, *args, **kwargs):\n        return self._log_kw(level, args, kwargs)",
    "docstring": "Delegate a log call to the underlying logger."
  },
  {
    "code": "def list_icmp_block(zone, permanent=True):\n    cmd = '--zone={0} --list-icmp-blocks'.format(zone)\n    if permanent:\n        cmd += ' --permanent'\n    return __firewall_cmd(cmd).split()",
    "docstring": "List ICMP blocks on a zone\n\n    .. versionadded:: 2015.8.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' firewlld.list_icmp_block zone"
  },
  {
    "code": "def position(parser, token):\n    bits = token.split_contents()\n    nodelist = parser.parse(('end' + bits[0],))\n    parser.delete_first_token()\n    return _parse_position_tag(bits, nodelist)",
    "docstring": "Render a given position for category.\n    If some position is not defined for first category, position from its parent\n    category is used unless nofallback is specified.\n\n    Syntax::\n\n        {% position POSITION_NAME for CATEGORY [nofallback] %}{% endposition %}\n        {% position POSITION_NAME for CATEGORY using BOX_TYPE [nofallback] %}{% endposition %}\n\n    Example usage::\n\n        {% position top_left for category %}{% endposition %}"
  },
  {
    "code": "def timestamps(self):\n        timestamps = set()\n        for series in self.groups.itervalues():\n            timestamps |= set(series.timestamps)\n        return sorted(list(timestamps))",
    "docstring": "Get all timestamps from all series in the group."
  },
  {
    "code": "def initialize_switch_endpoints(self):\n        self._switches = {}\n        self._port_group_info = {}\n        self._validate_config()\n        for s in cfg.CONF.ml2_arista.switch_info:\n            switch_ip, switch_user, switch_pass = s.split(\":\")\n            if switch_pass == \"''\":\n                switch_pass = ''\n            self._switches[switch_ip] = api.EAPIClient(\n                switch_ip,\n                switch_user,\n                switch_pass,\n                verify=False,\n                timeout=cfg.CONF.ml2_arista.conn_timeout)\n        self._check_dynamic_acl_support()",
    "docstring": "Initialize endpoints for switch communication"
  },
  {
    "code": "def create_vcf(isomirs, matures, gtf, vcf_file=None):\n    global STDOUT\n    isomirs['sv'] = [_get_reference_position(m) for m in isomirs[\"isomir\"]]\n    mirna = isomirs.groupby(['chrom']).sum()\n    sv = isomirs.groupby(['chrom', 'mature', 'sv'], as_index=False).sum()\n    sv[\"diff\"] = isomirs.groupby(['chrom', 'mature', 'sv'], as_index=False).size().reset_index().loc[:,0]\n    pass_pos = _get_pct(sv, mirna)\n    if vcf_file:\n        with open(vcf_file, 'w') as out_handle:\n            STDOUT = out_handle\n            pass_pos = liftover(pass_pos, matures)\n    if gtf:\n        vcf_genome_file = vcf_file.replace(\".vcf\", \"_genome.vcf\")\n        with open(vcf_genome_file, 'w') as out_handle:\n            STDOUT = out_handle\n            pass_pos = liftover_to_genome(pass_pos, gtf)",
    "docstring": "Create vcf file of changes for all samples.\n    PASS will be ones with > 3 isomiRs supporting the position\n         and > 30% of reads, otherwise LOW"
  },
  {
    "code": "def get_95_percentile_bleak(games_nr, n_back=500):\n    end_game = int(games_nr.latest_game_number)\n    start_game = end_game - n_back if end_game >= n_back else 0\n    moves = games_nr.bleakest_moves(start_game, end_game)\n    evals = np.array([m[2] for m in moves])\n    return np.percentile(evals, 5)",
    "docstring": "Gets the 95th percentile of bleakest_eval from bigtable"
  },
  {
    "code": "def pattern(self, pattern):\n        enc_pattern = _converters[type(pattern)](pattern)\n        if (enc_pattern, True) not in self._refs:\n            ch = _Sender(self, enc_pattern,\n                         is_pattern=True)\n            self._refs[(enc_pattern, True)] = ch\n        return self._refs[(enc_pattern, True)]",
    "docstring": "Create a pattern channel.\n\n        Returns ``_Sender`` object implementing\n        :class:`~aioredis.abc.AbcChannel`."
  },
  {
    "code": "def search(self, q, search_handler=None, **kwargs):\n        params = {'q': q}\n        params.update(kwargs)\n        response = self._select(params, handler=search_handler)\n        decoded = self.decoder.decode(response)\n        self.log.debug(\n            \"Found '%s' search results.\",\n            (decoded.get('response', {}) or {}).get('numFound', 0)\n        )\n        return self.results_cls(decoded)",
    "docstring": "Performs a search and returns the results.\n\n        Requires a ``q`` for a string version of the query to run.\n\n        Optionally accepts ``**kwargs`` for additional options to be passed\n        through the Solr URL.\n\n        Returns ``self.results_cls`` class object (defaults to\n        ``pysolr.Results``)\n\n        Usage::\n\n            # All docs.\n            results = solr.search('*:*')\n\n            # Search with highlighting.\n            results = solr.search('ponies', **{\n                'hl': 'true',\n                'hl.fragsize': 10,\n            })"
  },
  {
    "code": "def lastindex(*args, **kwargs):\n    _, idx = _index(*args, start=sys.maxsize, step=-1, **kwargs)\n    return idx",
    "docstring": "Search a list backwards for an exact element,\n    or element satisfying a predicate.\n\n    Usage::\n\n        lastindex(element, list_)\n        lastindex(of=element, in_=list_)\n        lastindex(where=predicate, in_=list_)\n\n    :param element, of: Element to search for (by equality comparison)\n    :param where: Predicate defining an element to search for.\n                  This should be a callable taking a single argument\n                  and returning a boolean result.\n    :param list_, in_: List to search in\n\n    :return: Index of the last matching element, or -1 if none was found\n\n    .. versionadded:: 0.0.3"
  },
  {
    "code": "def handle_stream(self, stream, address):\n        log.trace('Req client %s connected', address)\n        self.clients.append((stream, address))\n        unpacker = msgpack.Unpacker()\n        try:\n            while True:\n                wire_bytes = yield stream.read_bytes(4096, partial=True)\n                unpacker.feed(wire_bytes)\n                for framed_msg in unpacker:\n                    if six.PY3:\n                        framed_msg = salt.transport.frame.decode_embedded_strs(\n                            framed_msg\n                        )\n                    header = framed_msg['head']\n                    self.io_loop.spawn_callback(self.message_handler, stream, header, framed_msg['body'])\n        except StreamClosedError:\n            log.trace('req client disconnected %s', address)\n            self.clients.remove((stream, address))\n        except Exception as e:\n            log.trace('other master-side exception: %s', e)\n            self.clients.remove((stream, address))\n            stream.close()",
    "docstring": "Handle incoming streams and add messages to the incoming queue"
  },
  {
    "code": "def list_firewall_rules(self, retrieve_all=True, **_params):\n        return self.list('firewall_rules', self.firewall_rules_path,\n                         retrieve_all, **_params)",
    "docstring": "Fetches a list of all firewall rules for a project."
  },
  {
    "code": "def _reindex_multi(self, axes, copy, fill_value):\n        new_index, row_indexer = self.index.reindex(axes['index'])\n        new_columns, col_indexer = self.columns.reindex(axes['columns'])\n        if row_indexer is not None and col_indexer is not None:\n            indexer = row_indexer, col_indexer\n            new_values = algorithms.take_2d_multi(self.values, indexer,\n                                                  fill_value=fill_value)\n            return self._constructor(new_values, index=new_index,\n                                     columns=new_columns)\n        else:\n            return self._reindex_with_indexers({0: [new_index, row_indexer],\n                                                1: [new_columns, col_indexer]},\n                                               copy=copy,\n                                               fill_value=fill_value)",
    "docstring": "We are guaranteed non-Nones in the axes."
  },
  {
    "code": "def process_pybel_graph(graph):\n    bp = PybelProcessor(graph)\n    bp.get_statements()\n    if bp.annot_manager.failures:\n        logger.warning('missing %d annotation pairs',\n                       sum(len(v)\n                           for v in bp.annot_manager.failures.values()))\n    return bp",
    "docstring": "Return a PybelProcessor by processing a PyBEL graph.\n\n    Parameters\n    ----------\n    graph : pybel.struct.BELGraph\n        A PyBEL graph to process\n\n    Returns\n    -------\n    bp : PybelProcessor\n        A PybelProcessor object which contains INDRA Statements in\n        bp.statements."
  },
  {
    "code": "def clean_slug(self):\n        source = self.cleaned_data.get('slug', '')\n        lang_choice = self.language_code\n        if not source:\n            source = slugify(self.cleaned_data.get('title', ''))\n        qs = Post._default_manager.active_translations(lang_choice).language(lang_choice)\n        used = list(qs.values_list('translations__slug', flat=True))\n        slug = source\n        i = 1\n        while slug in used:\n            slug = '%s-%s' % (source, i)\n            i += 1\n        return slug",
    "docstring": "Generate a valid slug, in case the given one is taken"
  },
  {
    "code": "def prepare_request_params(self, _query_params, _json_params):\n        self._query_params = dictset(\n            _query_params or self.request.params.mixed())\n        self._json_params = dictset(_json_params)\n        ctype = self.request.content_type\n        if self.request.method in ['POST', 'PUT', 'PATCH']:\n            if ctype == 'application/json':\n                try:\n                    self._json_params.update(self.request.json)\n                except simplejson.JSONDecodeError:\n                    log.error(\n                        \"Expecting JSON. Received: '{}'. \"\n                        \"Request: {} {}\".format(\n                            self.request.body, self.request.method,\n                            self.request.url))\n            self._json_params = BaseView.convert_dotted(self._json_params)\n            self._query_params = BaseView.convert_dotted(self._query_params)\n        self._params = self._query_params.copy()\n        self._params.update(self._json_params)",
    "docstring": "Prepare query and update params."
  },
  {
    "code": "def open( self ):\n        if self._connection is None:\n            self._connection = sqlite3.connect(self._dbfile)",
    "docstring": "Open the database connection."
  },
  {
    "code": "def create(self):\n        self.logger.log(logging.DEBUG, 'os.mkdir %s', self.name)\n        os.mkdir(self.name)",
    "docstring": "called to create the work space"
  },
  {
    "code": "def update_by_function(self, extra_doc, index, doc_type, id, querystring_args=None,\n                           update_func=None, attempts=2):\n        if querystring_args is None:\n            querystring_args = {}\n        if update_func is None:\n            update_func = dict.update\n        for attempt in range(attempts - 1, -1, -1):\n            current_doc = self.get(index, doc_type, id, **querystring_args)\n            new_doc = update_func(current_doc, extra_doc)\n            if new_doc is None:\n                new_doc = current_doc\n            try:\n                return self.index(new_doc, index, doc_type, id,\n                                  version=current_doc._meta.version, querystring_args=querystring_args)\n            except VersionConflictEngineException:\n                if attempt <= 0:\n                    raise\n                self.refresh(index)",
    "docstring": "Update an already indexed typed JSON document.\n\n        The update happens client-side, i.e. the current document is retrieved,\n        updated locally and finally pushed to the server. This may repeat up to\n        ``attempts`` times in case of version conflicts.\n\n        :param update_func: A callable ``update_func(current_doc, extra_doc)``\n            that computes and returns the updated doc. Alternatively it may\n            update ``current_doc`` in place and return None. The default\n            ``update_func`` is ``dict.update``.\n\n        :param attempts: How many times to retry in case of version conflict."
  },
  {
    "code": "def visit_assert(self, node, parent):\n        newnode = nodes.Assert(node.lineno, node.col_offset, parent)\n        if node.msg:\n            msg = self.visit(node.msg, newnode)\n        else:\n            msg = None\n        newnode.postinit(self.visit(node.test, newnode), msg)\n        return newnode",
    "docstring": "visit a Assert node by returning a fresh instance of it"
  },
  {
    "code": "def _has_y(self, kwargs):\n        return (('y' in kwargs) or (self._element_y in kwargs) or\n                (self._type == 3 and self._element_1my in kwargs))",
    "docstring": "Returns True if y is explicitly defined in kwargs"
  },
  {
    "code": "def register(self, bucket, name_or_func, func=None):\n        assert bucket in self, 'Bucket %s is unknown' % bucket\n        if func is None and hasattr(name_or_func, '__name__'):\n            name = name_or_func.__name__\n            func = name_or_func\n        elif func:\n            name = name_or_func\n        if name in self[bucket]:\n            raise AlreadyRegistered('The function %s is already registered' % name)\n        self[bucket][name] = func",
    "docstring": "Add a function to the registry by name"
  },
  {
    "code": "def update(self, users=None, groups=None):\n        if users is not None and isinstance(users, string_types):\n            users = (users,)\n        if groups is not None and isinstance(groups, string_types):\n            groups = (groups,)\n        data = {\n            'id': self.id,\n            'categorisedActors': {\n                'atlassian-user-role-actor': users,\n                'atlassian-group-role-actor': groups}}\n        super(Role, self).update(**data)",
    "docstring": "Add the specified users or groups to this project role. One of ``users`` or ``groups`` must be specified.\n\n        :param users: a user or users to add to the role\n        :type users: string, list or tuple\n        :param groups: a group or groups to add to the role\n        :type groups: string, list or tuple"
  },
  {
    "code": "def get_dropbox_folder_location():\n    host_db_path = os.path.join(os.environ['HOME'], '.dropbox/host.db')\n    try:\n        with open(host_db_path, 'r') as f_hostdb:\n            data = f_hostdb.read().split()\n    except IOError:\n        error(\"Unable to find your Dropbox install =(\")\n    dropbox_home = base64.b64decode(data[1]).decode()\n    return dropbox_home",
    "docstring": "Try to locate the Dropbox folder.\n\n    Returns:\n        (str) Full path to the current Dropbox folder"
  },
  {
    "code": "def WaitUntilComplete(self,poll_freq=2,timeout=None):\n\t\tstart_time = time.time()\n\t\twhile len(self.requests):\n\t\t\tcur_requests = []\n\t\t\tfor request in self.requests:\n\t\t\t\tstatus = request.Status()\n\t\t\t\tif status in ('notStarted','executing','resumed','queued','running'): cur_requests.append(request)\n\t\t\t\telif status == 'succeeded': self.success_requests.append(request)\n\t\t\t\telif status in (\"failed\", \"unknown\"): self.error_requests.append(request)\n\t\t\tself.requests = cur_requests\n\t\t\tif self.requests > 0 and clc.v2.time_utils.TimeoutExpired(start_time, timeout):\n\t\t\t\traise clc.RequestTimeoutException('Timeout waiting for Requests: {0}'.format(self.requests[0].id),\n\t\t\t\t                                  self.requests[0].Status())\n\t\t\ttime.sleep(poll_freq)\n\t\treturn(len(self.error_requests))",
    "docstring": "Poll until all request objects have completed.\n\n\t\tIf status is 'notStarted' or 'executing' continue polling.\n\t\tIf status is 'succeeded' then success\n\t\tElse log as error\n\n\t\tpoll_freq option is in seconds\n\n\t\tReturns an Int the number of unsuccessful requests.  This behavior is subject to change.\n\n\t\t>>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').PowerOn().WaitUntilComplete()\n\t\t0"
  },
  {
    "code": "def label( self, node ):\n        result = []\n        if node.get('type'):\n            result.append( node['type'] )\n        if node.get('name' ):\n            result.append( node['name'] )\n        elif node.get('value') is not None:\n            result.append( unicode(node['value'])[:32])\n        if 'module' in node and not node['module'] in result:\n            result.append( ' in %s'%( node['module'] ))\n        if node.get( 'size' ):\n            result.append( '%s'%( mb( node['size'] )))\n        if node.get( 'totsize' ):\n            result.append( '(%s)'%( mb( node['totsize'] )))\n        parent_count = len( node.get('parents',()))\n        if parent_count > 1:\n            result.append( '/%s refs'%( parent_count ))\n        return \" \".join(result)",
    "docstring": "Return textual description of this node"
  },
  {
    "code": "def save_model(self, request, obj, form, change):\n        super(DisplayableAdmin, self).save_model(request, obj, form, change)\n        if settings.USE_MODELTRANSLATION:\n            lang = get_language()\n            for code in OrderedDict(settings.LANGUAGES):\n                if code != lang:\n                    try:\n                        activate(code)\n                    except:\n                        pass\n                    else:\n                        obj.save()\n            activate(lang)",
    "docstring": "Save model for every language so that field auto-population\n        is done for every each of it."
  },
  {
    "code": "def getPlugItObject(hproPk):\n    from hprojects.models import HostedProject\n    try:\n        hproject = HostedProject.objects.get(pk=hproPk)\n    except (HostedProject.DoesNotExist, ValueError):\n        try:\n            hproject = HostedProject.objects.get(plugItCustomUrlKey=hproPk)\n        except HostedProject.DoesNotExist:\n            raise Http404\n    if hproject.plugItURI == '' and not hproject.runURI:\n        raise Http404\n    plugIt = PlugIt(hproject.plugItURI)\n    if hasattr(hproject, 'plugItCustomUrlKey') and hproject.plugItCustomUrlKey:\n        baseURI = reverse('plugIt.views.main', args=(hproject.plugItCustomUrlKey, ''))\n    else:\n        baseURI = reverse('plugIt.views.main', args=(hproject.pk, ''))\n    return (plugIt, baseURI, hproject)",
    "docstring": "Return the plugit object and the baseURI to use if not in standalone mode"
  },
  {
    "code": "def merge_config_files(fnames):\n    def _load_yaml(fname):\n        with open(fname) as in_handle:\n            config = yaml.safe_load(in_handle)\n        return config\n    out = _load_yaml(fnames[0])\n    for fname in fnames[1:]:\n        cur = _load_yaml(fname)\n        for k, v in cur.items():\n            if k in out and isinstance(out[k], dict):\n                out[k].update(v)\n            else:\n                out[k] = v\n    return out",
    "docstring": "Merge configuration files, preferring definitions in latter files."
  },
  {
    "code": "def by_name(self, country, language=\"en\"):\n        with override(language):\n            for code, name in self:\n                if name.lower() == country.lower():\n                    return code\n                if code in self.OLD_NAMES:\n                    for old_name in self.OLD_NAMES[code]:\n                        if old_name.lower() == country.lower():\n                            return code\n        return \"\"",
    "docstring": "Fetch a country's ISO3166-1 two letter country code from its name.\n\n        An optional language parameter is also available.\n        Warning: This depends on the quality of the available translations.\n\n        If no match is found, returns an empty string.\n\n        ..warning:: Be cautious about relying on this returning a country code\n            (especially with any hard-coded string) since the ISO names of\n            countries may change over time."
  },
  {
    "code": "def require_login(func):\n    @wraps(func)\n    def decorated(*args, **kwargs):\n        auth = request.authorization\n        if not auth:\n            return authenticate()\n        user = session.query(User).filter(\n            User.name == auth.username\n        ).first()\n        if user and user.check(auth.password):\n            g.user = user\n            return func(*args, **kwargs)\n        else:\n            return authenticate()\n    return decorated",
    "docstring": "Function wrapper to signalize that a login is required."
  },
  {
    "code": "def object_version_choices(obj):\n    choices = BLANK_CHOICE_DASH + [(PublishAction.UNPUBLISH_CHOICE, 'Unpublish current version')]\n    if obj is not None:\n        saved_versions = Version.objects.filter(\n            content_type=ContentType.objects.get_for_model(obj),\n            object_id=obj.pk,\n        ).exclude(\n            version_number=None,\n        )\n        for version in saved_versions:\n            choices.append((version.version_number, version))\n    return choices",
    "docstring": "Return a list of form choices for versions of this object which can be published."
  },
  {
    "code": "async def nodes(self, *,\n                    dc=None, near=None, watch=None, consistency=None):\n        params = {\"dc\": dc, \"near\": near}\n        response = await self._api.get(\"/v1/catalog/nodes\",\n                                       params=params,\n                                       watch=watch,\n                                       consistency=consistency)\n        return consul(response)",
    "docstring": "Lists nodes in a given DC\n\n        Parameters:\n            dc (str): Specify datacenter that will be used.\n                      Defaults to the agent's local datacenter.\n            near (str): Sort the node list in ascending order based on the\n                        estimated round trip time from that node.\n            watch (Blocking): Do a blocking query\n            consistency (Consistency): Force consistency\n        Returns:\n            CollectionMeta: where value is a list\n\n        It returns a body like this::\n\n            [\n              {\n                \"Node\": \"baz\",\n                \"Address\": \"10.1.10.11\",\n                \"TaggedAddresses\": {\n                  \"lan\": \"10.1.10.11\",\n                  \"wan\": \"10.1.10.11\"\n                }\n              },\n              {\n                \"Node\": \"foobar\",\n                \"Address\": \"10.1.10.12\",\n                \"TaggedAddresses\": {\n                  \"lan\": \"10.1.10.11\",\n                  \"wan\": \"10.1.10.12\"\n                }\n              }\n            ]"
  },
  {
    "code": "def _iter_enum_constant_ids(eid):\n    for bitmask in _iter_bitmasks(eid):\n        for value in _iter_enum_member_values(eid, bitmask):\n            for cid, serial in _iter_serial_enum_member(eid, value, bitmask):\n                yield cid",
    "docstring": "Iterate the constant IDs of all members in the given enum"
  },
  {
    "code": "def body_content(self, election_day, body, division=None):\n        from electionnight.models import PageType\n        body_type = ContentType.objects.get_for_model(body)\n        page_type = PageType.objects.get(\n            model_type=body_type,\n            election_day=election_day,\n            body=body,\n            jurisdiction=body.jurisdiction,\n            division_level=body.jurisdiction.division.level,\n        )\n        page_type_content = self.get(\n            content_type=ContentType.objects.get_for_model(page_type),\n            object_id=page_type.pk,\n            election_day=election_day,\n        )\n        kwargs = {\n            \"content_type__pk\": body_type.pk,\n            \"object_id\": body.pk,\n            \"election_day\": election_day,\n        }\n        if division:\n            kwargs[\"division\"] = division\n        content = self.get(**kwargs)\n        return {\n            \"site\": self.site_content(election_day)[\"site\"],\n            \"page_type\": self.serialize_content_blocks(page_type_content),\n            \"page\": self.serialize_content_blocks(content),\n            \"featured\": [\n                e.meta.ap_election_id for e in content.featured.all()\n            ],\n        }",
    "docstring": "Return serialized content for a body page."
  },
  {
    "code": "def sh(self, cmd, ignore_error=False, cwd=None, shell=False, **kwargs):\n        kwargs.update({\n            'shell': shell,\n            'cwd': cwd or self.fpath,\n            'stderr': subprocess.STDOUT,\n            'stdout': subprocess.PIPE,\n            'ignore_error': ignore_error})\n        log.debug((('cmd', cmd), ('kwargs', kwargs)))\n        return sh(cmd, **kwargs)",
    "docstring": "Run a command with the current working directory set to self.fpath\n\n        Args:\n            cmd (str or tuple): cmdstring or listlike\n\n        Keyword Arguments:\n            ignore_error (bool): if False, raise an Exception if p.returncode is\n                not 0\n            cwd (str): current working dir to run cmd with\n            shell (bool): subprocess.Popen ``shell`` kwarg\n\n        Returns:\n            str: stdout output of wrapped call to ``sh`` (``subprocess.Popen``)"
  },
  {
    "code": "def run_queues(self):\n        if self.exception:\n            raise self.exception\n        listeners = self.__listeners_for_thread\n        return sum(l.process() for l in listeners) > 0",
    "docstring": "Run all queues that have data queued"
  },
  {
    "code": "def index(self):\n        self._event_error = False\n        try:\n            compilable_files = self.finder.mirror_sources(\n                self.settings.SOURCES_PATH,\n                targetdir=self.settings.TARGET_PATH,\n                excludes=self.settings.EXCLUDES\n            )\n            self.compilable_files = dict(compilable_files)\n            self.source_files = self.compilable_files.keys()\n            self.inspector.reset()\n            self.inspector.inspect(\n                *self.source_files,\n                library_paths=self.settings.LIBRARY_PATHS\n            )\n        except BoussoleBaseException as e:\n            self._event_error = True\n            self.logger.error(six.text_type(e))",
    "docstring": "Reset inspector buffers and index project sources dependencies.\n\n        This have to be executed each time an event occurs.\n\n        Note:\n            If a Boussole exception occurs during operation, it will be catched\n            and an error flag will be set to ``True`` so event operation will\n            be blocked without blocking or breaking watchdog observer."
  },
  {
    "code": "def get_news_aggregation(self):\n        news_aggregation_url = self.api_path + \"news_aggregation\" + \"/\"\n        response = self.get_response(news_aggregation_url)\n        return response",
    "docstring": "Calling News Aggregation API\n\n        Return:\n           json data"
  },
  {
    "code": "def abbrev(self,dev_suffix=\"\"):\n        return '.'.join(str(el) for el in self.release) + \\\n            (dev_suffix if self.commit_count > 0 or self.dirty else \"\")",
    "docstring": "Abbreviated string representation, optionally declaring whether it is\n        a development version."
  },
  {
    "code": "def keypair():\n    fields = [\n        ('User ID', 'user_id'),\n        ('Access Key', 'access_key'),\n        ('Secret Key', 'secret_key'),\n        ('Active?', 'is_active'),\n        ('Admin?', 'is_admin'),\n        ('Created At', 'created_at'),\n        ('Last Used', 'last_used'),\n        ('Res.Policy', 'resource_policy'),\n        ('Rate Limit', 'rate_limit'),\n        ('Concur.Limit', 'concurrency_limit'),\n        ('Concur.Used', 'concurrency_used'),\n    ]\n    with Session() as session:\n        try:\n            kp = session.KeyPair(session.config.access_key)\n            info = kp.info(fields=(item[1] for item in fields))\n        except Exception as e:\n            print_error(e)\n            sys.exit(1)\n        rows = []\n        for name, key in fields:\n            rows.append((name, info[key]))\n        print(tabulate(rows, headers=('Field', 'Value')))",
    "docstring": "Show the server-side information of the currently configured access key."
  },
  {
    "code": "async def close_interface(self, client_id, conn_string, interface):\n        conn_id = self._client_connection(client_id, conn_string)\n        await self.adapter.close_interface(conn_id, interface)\n        self._hook_close_interface(conn_string, interface, client_id)",
    "docstring": "Close a device interface on behalf of a client.\n\n        See :meth:`AbstractDeviceAdapter.close_interface`.\n\n        Args:\n            client_id (str): The client we are working for.\n            conn_string (str): A connection string that will be\n                passed to the underlying device adapter.\n            interface (str): The name of the interface to close.\n\n        Raises:\n            DeviceServerError: There is an issue with your client_id such\n                as not being connected to the device.\n            DeviceAdapterError: The adapter had an issue closing the interface."
  },
  {
    "code": "def parse(self, filepath, content):\n        try:\n            parsed = yaml.load(content)\n        except yaml.YAMLError as exc:\n            msg = \"No YAML object could be decoded from file: {}\\n{}\"\n            raise SettingsBackendError(msg.format(filepath, exc))\n        return parsed",
    "docstring": "Parse opened settings content using YAML parser.\n\n        Args:\n            filepath (str): Settings object, depends from backend\n            content (str): Settings content from opened file, depends from\n                backend.\n\n        Raises:\n            boussole.exceptions.SettingsBackendError: If parser can not decode\n                a valid YAML object.\n\n        Returns:\n            dict: Dictionnary containing parsed setting elements."
  },
  {
    "code": "def overlaps_range(self, begin, end):\n        if self.is_empty():\n            return False\n        elif begin >= end:\n            return False\n        elif self.overlaps_point(begin):\n            return True\n        return any(\n            self.overlaps_point(bound)\n            for bound in self.boundary_table\n            if begin < bound < end\n        )",
    "docstring": "Returns whether some interval in the tree overlaps the given\n        range. Returns False if given a null interval over which to\n        test.\n\n        Completes in O(r*log n) time, where r is the range length and n\n        is the table size.\n        :rtype: bool"
  },
  {
    "code": "def append_station(self, params, stationFile=''):\n        if self.new_format:\n            if stationFile:\n                st_file = stationFile\n            else:\n                st_file = self.stations_file\n            st_file, ret = self._get_playlist_abspath_from_data(st_file)\n            if ret < -1:\n                return ret\n            try:\n                with open(st_file, 'a') as cfgfile:\n                    writter = csv.writer(cfgfile)\n                    writter.writerow(params)\n                return 0\n            except:\n                return -5\n        else:\n            self.stations.append([ params[0], params[1], params[2] ])\n            self.dirty_playlist = True\n            st_file, ret = self._get_playlist_abspath_from_data(stationFile)\n            if ret < -1:\n                return ret\n            ret = self.save_playlist_file(st_file)\n            if ret < 0:\n                ret -= 4\n            return ret",
    "docstring": "Append a station to csv file\n\n        return    0: All ok\n                 -2  -  playlist not found\n                 -3  -  negative number specified\n                 -4  -  number not found\n                 -5: Error writing file\n                 -6: Error renaming file"
  },
  {
    "code": "def update_fid_list(self,filename,N):\r\n        self.filelist_count[self.filelist.index(filename)] = N\r\n        fid=self.fid_list.compress([enum[1][0] == os.path.basename(filename) for enum in enumerate(zip(*(self.filelist,self.fid_list)))])\r\n        self.__dict__.update({'fileid' :np.append(self.fileid,np.repeat(fid,N))})",
    "docstring": "update file indices attribute `altimetry.data.hydro_data.fileid`"
  },
  {
    "code": "def upsert(self, key, value, cas=0, ttl=0, format=None,\n               persist_to=0, replicate_to=0):\n        return _Base.upsert(self, key, value, cas=cas, ttl=ttl,\n                            format=format, persist_to=persist_to,\n                            replicate_to=replicate_to)",
    "docstring": "Unconditionally store the object in Couchbase.\n\n        :param key:\n            The key to set the value with. By default, the key must be\n            either a :class:`bytes` or :class:`str` object encodable as\n            UTF-8. If a custom `transcoder` class is used (see\n            :meth:`~__init__`), then the key object is passed directly\n            to the transcoder, which may serialize it how it wishes.\n        :type key: string or bytes\n\n        :param value: The value to set for the key.\n            This should be a native Python value which will be transparently\n            serialized to JSON by the library. Do not pass already-serialized\n            JSON as the value or it will be serialized again.\n\n            If you are using a different `format` setting (see `format`\n            parameter), and/or a custom transcoder then value for this\n            argument may need to conform to different criteria.\n\n        :param int cas: The _CAS_ value to use. If supplied, the value\n            will only be stored if it already exists with the supplied\n            CAS\n\n        :param int ttl: If specified, the key will expire after this\n            many seconds\n\n        :param int format: If specified, indicates the `format` to use\n            when encoding the value. If none is specified, it will use\n            the `default_format` For more info see\n            :attr:`~.default_format`\n\n        :param int persist_to:\n            Perform durability checking on this many nodes nodes for\n            persistence to disk. See :meth:`endure` for more information\n\n        :param int replicate_to: Perform durability checking on this\n            many replicas for presence in memory. See :meth:`endure` for\n            more information.\n\n        :raise: :exc:`.ArgumentError` if an argument is supplied that is\n            not applicable in this context. For example setting the CAS\n            as a string.\n        :raise: :exc`.CouchbaseNetworkError`\n        :raise: :exc:`.KeyExistsError` if the key already exists on the\n            server with a different CAS value.\n        :raise: :exc:`.ValueFormatError` if the value cannot be\n            serialized with chosen encoder, e.g. if you try to store a\n            dictionary in plain mode.\n        :return: :class:`~.Result`.\n\n        Simple set::\n\n            cb.upsert('key', 'value')\n\n        Force JSON document format for value::\n\n            cb.upsert('foo', {'bar': 'baz'}, format=couchbase.FMT_JSON)\n\n        Insert JSON from a string::\n\n            JSONstr = '{\"key1\": \"value1\", \"key2\": 123}'\n            JSONobj = json.loads(JSONstr)\n            cb.upsert(\"documentID\", JSONobj, format=couchbase.FMT_JSON)\n\n        Force UTF8 document format for value::\n\n            cb.upsert('foo', \"<xml></xml>\", format=couchbase.FMT_UTF8)\n\n        Perform optimistic locking by specifying last known CAS version::\n\n            cb.upsert('foo', 'bar', cas=8835713818674332672)\n\n        Several sets at the same time (mutli-set)::\n\n            cb.upsert_multi({'foo': 'bar', 'baz': 'value'})\n\n        .. seealso:: :meth:`upsert_multi`"
  },
  {
    "code": "def _fix_orig_vcf_refs(data):\n    variantcaller = tz.get_in((\"config\", \"algorithm\", \"variantcaller\"), data)\n    if variantcaller:\n        data[\"vrn_file_orig\"] = data[\"vrn_file\"]\n    for i, sub in enumerate(data.get(\"group_orig\", [])):\n        sub_vrn = sub.pop(\"vrn_file\", None)\n        if sub_vrn:\n            sub[\"vrn_file_orig\"] = sub_vrn\n            data[\"group_orig\"][i] = sub\n    return data",
    "docstring": "Supply references to initial variantcalls if run in addition to batching."
  },
  {
    "code": "def equivalent_relshell_type(val):\n        builtin_type = type(val)\n        if builtin_type not in Type._typemap:\n            raise NotImplementedError(\"builtin type %s is not convertible to relshell type\" %\n                                      (builtin_type))\n        relshell_type_str = Type._typemap[builtin_type]\n        return Type(relshell_type_str)",
    "docstring": "Returns `val`'s relshell compatible type.\n\n        :param val:  value to check relshell equivalent type\n        :raises:     `NotImplementedError` if val's relshell compatible type is not implemented."
  },
  {
    "code": "def _wrap_attribute(self, attr):\n        if not attr:\n            const = const_factory(attr)\n            const.parent = self\n            return const\n        return attr",
    "docstring": "Wrap the empty attributes of the Slice in a Const node."
  },
  {
    "code": "def add_poly_index(self, i, j, k):\n        self.idx_data.write(\n            struct.pack(self.idx_fmt, i) +\n            struct.pack(self.idx_fmt, j) +\n            struct.pack(self.idx_fmt, k)\n        )",
    "docstring": "Add 3 ``SCALAR`` of ``uint`` to the ``idx_data`` buffer."
  },
  {
    "code": "def tag_values(request):\n    data = defaultdict(lambda: {\"values\": {}})\n    for tag in Tag.objects.filter(lang=get_language(request)):\n        data[tag.type][\"name\"] = tag.type_name\n        data[tag.type][\"values\"][tag.value] = tag.value_name\n    return render_json(request, data, template='concepts_json.html', help_text=tag_values.__doc__)",
    "docstring": "Get tags types and values with localized names\n\n    language:\n      language of tags"
  },
  {
    "code": "def _path_is_abs(path):\n    if path is None:\n        return True\n    try:\n        return os.path.isabs(path)\n    except AttributeError:\n        return False",
    "docstring": "Return a bool telling whether or ``path`` is absolute. If ``path`` is None,\n    return ``True``. This function is designed to validate variables which\n    optionally contain a file path."
  },
  {
    "code": "def bound_bboxes(bboxes):\n    group_x0 = min(map(lambda l: l[x0], bboxes))\n    group_y0 = min(map(lambda l: l[y0], bboxes))\n    group_x1 = max(map(lambda l: l[x1], bboxes))\n    group_y1 = max(map(lambda l: l[y1], bboxes))\n    return (group_x0, group_y0, group_x1, group_y1)",
    "docstring": "Finds the minimal bbox that contains all given bboxes"
  },
  {
    "code": "def _measure(self, weighted):\n        return (\n            self._measures.means\n            if self._measures.means is not None\n            else self._measures.weighted_counts\n            if weighted\n            else self._measures.unweighted_counts\n        )",
    "docstring": "_BaseMeasure subclass representing primary measure for this cube.\n\n        If the cube response includes a means measure, the return value is\n        means. Otherwise it is counts, with the choice between weighted or\n        unweighted determined by *weighted*.\n\n        Note that weighted counts are provided on an \"as-available\" basis.\n        When *weighted* is True and the cube response is not weighted,\n        unweighted counts are returned."
  },
  {
    "code": "def set_fd_value(tag, value):\n    if tag.VR == 'OB' or tag.VR == 'UN':\n        value = struct.pack('d', value)\n    tag.value = value",
    "docstring": "Setters for data that also work with implicit transfersyntax\n\n    :param value: the value to set on the tag\n    :param tag: the tag to read"
  },
  {
    "code": "def printrdf(wflow, ctx, style):\n    rdf = gather(wflow, ctx).serialize(format=style, encoding='utf-8')\n    if not rdf:\n        return u\"\"\n    return rdf.decode('utf-8')",
    "docstring": "Serialize the CWL document into a string, ready for printing."
  },
  {
    "code": "def composite(\n    background_image,\n    foreground_image,\n    foreground_width_ratio=0.25,\n    foreground_position=(0.0, 0.0),\n):\n    if foreground_width_ratio <= 0:\n        return background_image\n    composite = background_image.copy()\n    width = int(foreground_width_ratio * background_image.shape[1])\n    foreground_resized = resize(foreground_image, width)\n    size = foreground_resized.shape\n    x = int(foreground_position[1] * (background_image.shape[1] - size[1]))\n    y = int(foreground_position[0] * (background_image.shape[0] - size[0]))\n    composite[y : y + size[0], x : x + size[1]] = foreground_resized\n    return composite",
    "docstring": "Takes two images and composites them."
  },
  {
    "code": "def _validate_instance(self, instance, errors, path_prefix=''):\n        if not isinstance(instance, dict):\n            errors[path_prefix] = \"Expected instance of dict to validate against schema.\"\n            return\n        self._apply_validations(errors, path_prefix, self._validates, instance)\n        for field, spec in self.doc_spec.iteritems():\n            path = self._append_path(path_prefix, field)\n            if field in instance:\n                self._validate_value(instance[field], spec, path, errors)\n            else:\n                if spec.get('required', False):\n                    errors[path] = \"{} is required.\".format(path)\n        if self._strict:\n            for field in instance:\n                if field not in self.doc_spec:\n                    errors[self._append_path(path_prefix, field)] = \"Unexpected document field not present in schema\"",
    "docstring": "Validates that the given instance of a document conforms to the given schema's\n        structure and validations. Any validation errors are added to the given errors\n        collection. The caller should assume the instance is considered valid if the\n        errors collection is empty when this method returns."
  },
  {
    "code": "def get_visible_elements(self, locator, params=None, timeout=None):\n        return self.get_present_elements(locator, params, timeout, True)",
    "docstring": "Get elements both present AND visible in the DOM.\n\n        If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise\n        TimeoutException should the element not be found.\n\n        :param locator: locator tuple\n        :param params: (optional) locator params\n        :param timeout: (optional) time to wait for element (default: self._explicit_wait)\n        :return: WebElement instance"
  },
  {
    "code": "def build(self, bug: Bug):\n        r = self.__api.post('bugs/{}/build'.format(bug.name))\n        if r.status_code == 204:\n            return\n        if r.status_code == 200:\n            raise Exception(\"bug already built: {}\".format(bug.name))\n        if r.status_code == 400:\n            raise Exception(\"build failure\")\n        if r.status_code == 404:\n          raise KeyError(\"no bug found with given name: {}\".format(bug.name))\n        self.__api.handle_erroneous_response(r)",
    "docstring": "Instructs the server to build the Docker image associated with a given\n        bug."
  },
  {
    "code": "def get_default(self):\n        length = len(self)\n        if length == 0:\n            return None\n        elif length == 1:\n            return self[0]\n        else:\n            return sorted(self, key=attrgetter('id'))[0]",
    "docstring": "Return the default VLAN from the set."
  },
  {
    "code": "def delete_subnet(self, subnet):\n        subnet_id = self._find_subnet_id(subnet)\n        ret = self.network_conn.delete_subnet(subnet=subnet_id)\n        return ret if ret else True",
    "docstring": "Deletes the specified subnet"
  },
  {
    "code": "def install_database(name, owner, template='template0', encoding='UTF8', locale='en_US.UTF-8'):\n    create_database(name, owner, template=template, encoding=encoding,\n                        locale=locale)",
    "docstring": "Require a PostgreSQL database.\n\n    ::\n\n        from fabtools import require\n\n        require.postgres.database('myapp', owner='dbuser')"
  },
  {
    "code": "def select_cb(self, viewer, event, data_x, data_y):\n        if not (self._cmxoff <= data_x < self._cmwd):\n            return\n        i = int(data_y / (self._cmht + self._cmsep))\n        if 0 <= i < len(self.cm_names):\n            name = self.cm_names[i]\n            msg = \"cmap => '%s'\" % (name)\n            self.logger.info(msg)\n            channel = self.fv.get_channel_info()\n            if channel is not None:\n                viewer = channel.fitsimage\n                viewer.set_color_map(name)",
    "docstring": "Called when the user clicks on the color bar viewer.\n        Calculate the index of the color bar they clicked on and\n        set that color map in the current channel viewer."
  },
  {
    "code": "def is_enable(self, plugin_name=None):\n        if not plugin_name:\n            plugin_name = self.plugin_name\n        try:\n            d = getattr(self.args, 'disable_' + plugin_name)\n        except AttributeError:\n            return True\n        else:\n            return d is False",
    "docstring": "Return true if plugin is enabled."
  },
  {
    "code": "def iter_notifications(self, all=False, participating=False, number=-1,\n                           etag=None):\n        params = None\n        if all:\n            params = {'all': all}\n        elif participating:\n            params = {'participating': participating}\n        url = self._build_url('notifications')\n        return self._iter(int(number), url, Thread, params, etag=etag)",
    "docstring": "Iterate over the user's notification.\n\n        :param bool all: (optional), iterate over all notifications\n        :param bool participating: (optional), only iterate over notifications\n            in which the user is participating\n        :param int number: (optional), how many notifications to return\n        :param str etag: (optional), ETag from a previous request to the same\n            endpoint\n        :returns: generator of\n            :class:`Thread <github3.notifications.Thread>`"
  },
  {
    "code": "def add(self, sid, token):\n        try:\n            self.dbcur.execute(SQL_SENSOR_INS, (sid, token))\n        except sqlite3.IntegrityError:\n            pass",
    "docstring": "Add new sensor to the database\n\n        Parameters\n        ----------\n        sid : str\n            SensorId\n        token : str"
  },
  {
    "code": "def data(self):\n        try:\n            data = self._data\n        except AttributeError:\n            data = self._data = json.loads(self.json)\n        return data",
    "docstring": "Returns self.json loaded as a python object."
  },
  {
    "code": "def service(self, service):\n        if service is None:\n            raise ValueError(\"Invalid value for `service`, must not be `None`\")\n        allowed_values = [\"lwm2m\", \"bootstrap\"]\n        if service not in allowed_values:\n            raise ValueError(\n                \"Invalid value for `service` ({0}), must be one of {1}\"\n                .format(service, allowed_values)\n            )\n        self._service = service",
    "docstring": "Sets the service of this TrustedCertificateInternalResp.\n        Service name where the certificate is to be used.\n\n        :param service: The service of this TrustedCertificateInternalResp.\n        :type: str"
  },
  {
    "code": "def _set_initial(self, C_in, scale_in):\n        r\n        self.C_in = C_in\n        self.scale_in = scale_in",
    "docstring": "r\"\"\"Set the initial values for parameters and Wilson coefficients at\n        the scale `scale_in`."
  },
  {
    "code": "def make_key(observer):\n        if hasattr(observer, \"__self__\"):\n            inst = observer.__self__\n            method_name = observer.__name__\n            key = (id(inst), method_name)\n        else:\n            key = id(observer)\n        return key",
    "docstring": "Construct a unique, hashable, immutable key for an observer."
  },
  {
    "code": "def i2c_config(self, read_delay_time=0):\n        task = asyncio.ensure_future(self.core.i2c_config(read_delay_time))\n        self.loop.run_until_complete(task)",
    "docstring": "This method configures Arduino i2c with an optional read delay time.\n\n        :param read_delay_time: firmata i2c delay time\n\n        :returns: No return value"
  },
  {
    "code": "def make_pdb(self, alt_states=False, inc_ligands=True):\n        if any([False if x.id else True for x in self._monomers]):\n            self.relabel_monomers()\n        if self.ligands and inc_ligands:\n            monomers = self._monomers + self.ligands._monomers\n        else:\n            monomers = self._monomers\n        pdb_str = write_pdb(monomers, self.id, alt_states=alt_states)\n        return pdb_str",
    "docstring": "Generates a PDB string for the `Polymer`.\n\n        Parameters\n        ----------\n        alt_states : bool, optional\n            Include alternate conformations for `Monomers` in PDB.\n        inc_ligands : bool, optional\n            Includes `Ligands` in PDB.\n\n        Returns\n        -------\n        pdb_str : str\n            String of the pdb for the `Polymer`. Generated using information\n            from the component `Monomers`."
  },
  {
    "code": "def make_multipart(self, content_disposition=None, content_type=None,\n                       content_location=None):\n        self.headers['Content-Disposition'] = content_disposition or 'form-data'\n        self.headers['Content-Disposition'] += '; '.join([\n            '', self._render_parts(\n                (('name', self._name), ('filename', self._filename))\n            )\n        ])\n        self.headers['Content-Type'] = content_type\n        self.headers['Content-Location'] = content_location",
    "docstring": "Makes this request field into a multipart request field.\n\n        This method overrides \"Content-Disposition\", \"Content-Type\" and\n        \"Content-Location\" headers to the request parameter.\n\n        :param content_type:\n            The 'Content-Type' of the request body.\n        :param content_location:\n            The 'Content-Location' of the request body."
  },
  {
    "code": "def LogClientError(self, client_id, log_message=None, backtrace=None):\n    self.RegisterClientError(\n        client_id, log_message=log_message, backtrace=backtrace)",
    "docstring": "Logs an error for a client."
  },
  {
    "code": "def get_format_spec(self):\n        return u\"{{:{align}{width}}}\".format(align=self.align, width=self.width)",
    "docstring": "The format specification according to the values of `align` and `width`"
  },
  {
    "code": "def clean_column_names(df: DataFrame) -> DataFrame:\n    f = df.copy()\n    f.columns = [col.strip() for col in f.columns]\n    return f",
    "docstring": "Strip the whitespace from all column names in the given DataFrame\n    and return the result."
  },
  {
    "code": "def eval(self):\n        if self.and_or == 'or':\n            return [Input(self.alias, file, self.cwd, 'and')\n                for file in self.files]\n        return ' '.join(self.files)",
    "docstring": "Evaluates the given input and returns a string containing the\n        actual filenames represented. If the input token represents multiple\n        independent files, then eval will return a list of all the input files\n        needed, otherwise it returns the filenames in a string."
  },
  {
    "code": "def send_response(self, transaction):\n        host, port = transaction.request.source\n        key_token = hash(str(host) + str(port) + str(transaction.request.token))\n        if key_token in self._relations:\n            if transaction.response.code == defines.Codes.CONTENT.number:\n                if transaction.resource is not None and transaction.resource.observable:\n                    transaction.response.observe = transaction.resource.observe_count\n                    self._relations[key_token].allowed = True\n                    self._relations[key_token].transaction = transaction\n                    self._relations[key_token].timestamp = time.time()\n                else:\n                    del self._relations[key_token]\n            elif transaction.response.code >= defines.Codes.ERROR_LOWER_BOUND:\n                del self._relations[key_token]\n        return transaction",
    "docstring": "Finalize to add the client to the list of observer.\n\n        :type transaction: Transaction\n        :param transaction: the transaction that owns the response\n        :return: the transaction unmodified"
  },
  {
    "code": "def observable_copy(value, name, instance):\n    container_class = value.__class__\n    if container_class in OBSERVABLE_REGISTRY:\n        observable_class = OBSERVABLE_REGISTRY[container_class]\n    elif container_class in OBSERVABLE_REGISTRY.values():\n        observable_class = container_class\n    else:\n        observable_class = add_properties_callbacks(\n            type(container_class)(\n                str('Observable{}'.format(container_class.__name__)),\n                (container_class,),\n                MUTATOR_CATEGORIES,\n            )\n        )\n        OBSERVABLE_REGISTRY[container_class] = observable_class\n    value = observable_class(value)\n    value._name = name\n    value._instance = instance\n    return value",
    "docstring": "Return an observable container for HasProperties notifications\n\n    This method creates a new container class to allow HasProperties\n    instances to :code:`observe_mutations`. It returns a copy of the\n    input value as this new class.\n\n    The output class behaves identically to the input value's original\n    class, except when it is used as a property on a HasProperties\n    instance. In that case, it notifies the HasProperties instance of\n    any mutations or operations."
  },
  {
    "code": "def CompareTo(self, other_hash_value):\n        if len(self.hash_value) != len(other_hash_value):\n            raise ValueError(\"Length of hashes doesn't match.\")\n        for i in xrange(0, len(self.hash_value)):\n            if(self.hash_value[len(self.hash_value) - i - 1] < other_hash_value[len(self.hash_value) - i - 1]):\n                return -1\n            elif self.hash_value[len(self.hash_value) - i - 1] > other_hash_value[len(self.hash_value) - i - 1]:\n                return 1\n        return 0",
    "docstring": "Compares the passed hash value with the hash value of this object"
  },
  {
    "code": "def aggregate(self, val1, val2):\n        assert val1 is not None\n        assert val2 is not None\n        return self._aggregator(val1, val2)",
    "docstring": "Aggregate two event values."
  },
  {
    "code": "def normalize_url(url):\n    if url.endswith('.json'):\n        url = url[:-5]\n    if url.endswith('/'):\n        url = url[:-1]\n    return url",
    "docstring": "Return url after stripping trailing .json and trailing slashes."
  },
  {
    "code": "def validate_group(images):\n        image_ids = set()\n        for image in images:\n            key = image.folder + image.name\n            if key in image_ids:\n                raise ValueError('Duplicate images in group: ' + key)\n            else:\n                image_ids.add(key)",
    "docstring": "Validates that the combination of folder and name for all images in\n        a group is unique. Raises a ValueError exception if uniqueness\n        constraint is violated.\n\n        Parameters\n        ----------\n        images : List(GroupImage)\n            List of images in group"
  },
  {
    "code": "def register_deregister(notifier, event_type, callback=None,\n                        args=None, kwargs=None, details_filter=None,\n                        weak=False):\n    if callback is None:\n        yield\n    else:\n        notifier.register(event_type, callback,\n                          args=args, kwargs=kwargs,\n                          details_filter=details_filter,\n                          weak=weak)\n        try:\n            yield\n        finally:\n            notifier.deregister(event_type, callback,\n                                details_filter=details_filter)",
    "docstring": "Context manager that registers a callback, then deregisters on exit.\n\n    NOTE(harlowja): if the callback is none, then this registers nothing, which\n                    is different from the behavior of the ``register`` method\n                    which will *not* accept none as it is not callable..."
  },
  {
    "code": "def ReadAllFlowRequestsAndResponses(self, client_id, flow_id):\n    flow_key = (client_id, flow_id)\n    try:\n      self.flows[flow_key]\n    except KeyError:\n      return []\n    request_dict = self.flow_requests.get(flow_key, {})\n    response_dict = self.flow_responses.get(flow_key, {})\n    res = []\n    for request_id in sorted(request_dict):\n      res.append((request_dict[request_id], response_dict.get(request_id, {})))\n    return res",
    "docstring": "Reads all requests and responses for a given flow from the database."
  },
  {
    "code": "def remove_log_group(self, group_name):\n        print(\"Removing log group: {}\".format(group_name))\n        try:\n            self.logs_client.delete_log_group(logGroupName=group_name)\n        except botocore.exceptions.ClientError as e:\n            print(\"Couldn't remove '{}' because of: {}\".format(group_name, e))",
    "docstring": "Filter all log groups that match the name given in log_filter."
  },
  {
    "code": "def sudo_support(fn, command):\n    if not command.script.startswith('sudo '):\n        return fn(command)\n    result = fn(command.update(script=command.script[5:]))\n    if result and isinstance(result, six.string_types):\n        return u'sudo {}'.format(result)\n    elif isinstance(result, list):\n        return [u'sudo {}'.format(x) for x in result]\n    else:\n        return result",
    "docstring": "Removes sudo before calling fn and adds it after."
  },
  {
    "code": "def permissions(self):\n        permissions_dict = {\"self\": {}, \"parent\": {}}\n        for field in self.properties._meta.get_fields():\n            split_field = field.name.split('_', 1)\n            if len(split_field) <= 0 or split_field[0] not in ['self', 'parent']:\n                continue\n            permissions_dict[split_field[0]][split_field[1]] = getattr(self.properties, field.name)\n        return permissions_dict",
    "docstring": "Dynamically generate dictionary of privacy options"
  },
  {
    "code": "def compute_resids(xy,uv,fit):\n    print('FIT coeffs: ',fit['coeffs'])\n    xn,yn = apply_fit(uv,fit['coeffs'])\n    resids = xy - np.transpose([xn,yn])\n    return resids",
    "docstring": "Compute the residuals based on fit and input arrays to the fit"
  },
  {
    "code": "def _get_initial_name(self):\n        name = None\n        addr = self.addr\n        if self._function_manager is not None:\n            if addr in self._function_manager._kb.labels:\n                name = self._function_manager._kb.labels[addr]\n        if name is None and self.project is not None:\n            project = self.project\n            if project.is_hooked(addr):\n                hooker = project.hooked_by(addr)\n                name = hooker.display_name\n            elif project.simos.is_syscall_addr(addr):\n                syscall_inst = project.simos.syscall_from_addr(addr)\n                name = syscall_inst.display_name\n        if name is None:\n            name = 'sub_%x' % addr\n        return name",
    "docstring": "Determine the most suitable name of the function.\n\n        :return:    The initial function name.\n        :rtype:     string"
  },
  {
    "code": "def ucase(inchar, lenout=None):\n    if lenout is None:\n        lenout = len(inchar) + 1\n    inchar = stypes.stringToCharP(inchar)\n    outchar = stypes.stringToCharP(\" \" * lenout)\n    lenout = ctypes.c_int(lenout)\n    libspice.ucase_c(inchar, lenout, outchar)\n    return stypes.toPythonString(outchar)",
    "docstring": "Convert the characters in a string to uppercase.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ucase_c.html\n\n    :param inchar: Input string.\n    :type inchar: str\n    :param lenout: Optional Maximum length of output string.\n    :type lenout: int\n    :return: Output string, all uppercase.\n    :rtype: str"
  },
  {
    "code": "def update_user_password(new_pwd_user_id, new_password,**kwargs):\n    try:\n        user_i = db.DBSession.query(User).filter(User.id==new_pwd_user_id).one()\n        user_i.password = bcrypt.hashpw(str(new_password).encode('utf-8'), bcrypt.gensalt())\n        return user_i\n    except NoResultFound:\n        raise ResourceNotFoundError(\"User (id=%s) not found\"%(new_pwd_user_id))",
    "docstring": "Update a user's password"
  },
  {
    "code": "def form_field(self):\n        \"Returns appropriate form field.\"\n        label = unicode(self)\n        defaults = dict(required=False, label=label, widget=self.widget)\n        defaults.update(self.extra)\n        return self.field_class(**defaults)",
    "docstring": "Returns appropriate form field."
  },
  {
    "code": "def get_commands(self, peer_jid):\n        disco = self.dependencies[aioxmpp.disco.DiscoClient]\n        response = yield from disco.query_items(\n            peer_jid,\n            node=namespaces.xep0050_commands,\n        )\n        return response.items",
    "docstring": "Return the list of commands offered by the peer.\n\n        :param peer_jid: JID of the peer to query\n        :type peer_jid: :class:`~aioxmpp.JID`\n        :rtype: :class:`list` of :class:`~.disco.xso.Item`\n        :return: List of command items\n\n        In the returned list, each :class:`~.disco.xso.Item` represents one\n        command supported by the peer. The :attr:`~.disco.xso.Item.node`\n        attribute is the identifier of the command which can be used with\n        :meth:`get_command_info` and :meth:`execute`."
  },
  {
    "code": "def execute(self, lst):\n        from . import QueryableListMixed\n        if not issubclass(lst.__class__, QueryableListBase):\n            lst = QueryableListMixed(lst)\n        filters = copy.copy(self.filters)\n        nextFilter = filters.popleft()\n        while nextFilter:\n            (filterMethod, filterArgs) = nextFilter\n            lst = self._applyFilter(lst, filterMethod, filterArgs)\n            if len(lst) == 0:\n                return lst\n            try:\n                nextFilter = filters.popleft()\n            except:\n                break\n        return lst",
    "docstring": "execute - Execute the series of filters, in order, on the provided list.\n\n            @param lst <list/ A QueryableList type> - The list to filter. If you already know the types of items within\n                the list, you can pick a QueryableList implementing class to get faster results. Otherwise, if a list type that does\n                not extend QueryableListBase is provided, QueryableListMixed will be used (Supports both object-like and dict-like items)\n\n            @return - QueryableList of results. If you provided #lst as a QueryableList type already, that same type will be returned.\n                Otherwise, a QueryableListMixed will be returned."
  },
  {
    "code": "def read_raw(self, length, *, error=None):\n        if length is None:\n            length = len(self)\n        raw = dict(\n            packet=self._read_fileng(length),\n            error=error or None,\n        )\n        return raw",
    "docstring": "Read raw packet data."
  },
  {
    "code": "def search(self, searchstring):\n        ret = {}\n        for user in self.users:\n            match = False\n            for attr in self.search_attrs:\n                if attr not in self.users[user]:\n                    pass\n                elif re.search(searchstring + '.*', self.users[user][attr]):\n                    match = True\n            if match:\n                ret[user] = self.users[user]\n        return ret",
    "docstring": "Search backend for users\n\n        :param searchstring: the search string\n        :type searchstring: string\n        :rtype: dict of dict ( {<user attr key>: {<attr>: <value>}} )"
  },
  {
    "code": "def add_scan_host_detail(self, scan_id, host='', name='', value=''):\n        self.scan_collection.add_result(scan_id, ResultType.HOST_DETAIL, host,\n                                        name, value)",
    "docstring": "Adds a host detail result to scan_id scan."
  },
  {
    "code": "def _verify(self):\n        scenario_names = [c.scenario.name for c in self._configs]\n        if self._scenario_name not in scenario_names:\n            msg = (\"Scenario '{}' not found.  \"\n                   'Exiting.').format(self._scenario_name)\n            util.sysexit_with_message(msg)",
    "docstring": "Verify the specified scenario was found and returns None.\n\n        :return: None"
  },
  {
    "code": "def _get_ssh_public_key(self):\n        key = ipa_utils.generate_public_ssh_key(self.ssh_private_key_file)\n        return '{user}:{key} {user}'.format(\n            user=self.ssh_user,\n            key=key.decode()\n        )",
    "docstring": "Generate SSH public key from private key."
  },
  {
    "code": "def column_correlations(self, X):\n        utils.validation.check_is_fitted(self, 's_')\n        if isinstance(X, np.ndarray):\n            X = pd.DataFrame(X)\n        row_pc = self.row_coordinates(X)\n        return pd.DataFrame({\n            component: {\n                feature: row_pc[component].corr(X[feature])\n                for feature in X.columns\n            }\n            for component in row_pc.columns\n        })",
    "docstring": "Returns the column correlations with each principal component."
  },
  {
    "code": "def iter_tags(self, number=-1, etag=None):\n        url = self._build_url('tags', base_url=self._api)\n        return self._iter(int(number), url, RepoTag, etag=etag)",
    "docstring": "Iterates over tags on this repository.\n\n        :param int number: (optional), return up to at most number tags.\n            Default: -1 returns all available tags.\n        :param str etag: (optional), ETag from a previous request to the same\n            endpoint\n        :returns: generator of :class:`RepoTag <github3.repos.tag.RepoTag>`\\ s"
  },
  {
    "code": "def relative_abundance(biomf, sampleIDs=None):\n    if sampleIDs is None:\n        sampleIDs = biomf.ids()\n    else:\n        try:\n            for sid in sampleIDs:\n                assert sid in biomf.ids()\n        except AssertionError:\n            raise ValueError(\n                \"\\nError while calculating relative abundances: The sampleIDs provided do\"\n                \" not match the sampleIDs in biom file. Please double check the sampleIDs\"\n                \" provided.\\n\")\n    otuIDs = biomf.ids(axis=\"observation\")\n    norm_biomf = biomf.norm(inplace=False)\n    return {sample: {otuID: norm_biomf.get_value_by_ids(otuID, sample)\n                     for otuID in otuIDs} for sample in sampleIDs}",
    "docstring": "Calculate the relative abundance of each OTUID in a Sample.\n\n    :type biomf: A BIOM file.\n    :param biomf: OTU table format.\n\n    :type sampleIDs: list\n    :param sampleIDs: A list of sample id's from BIOM format OTU table.\n\n    :rtype: dict\n    :return: Returns a keyed on SampleIDs, and the values are dictionaries keyed on\n             OTUID's and their values represent the relative abundance of that OTUID in\n             that SampleID."
  },
  {
    "code": "def member_of(self, group):\n        if isinstance(group, Group):\n            group = group.name\n        return self.groups.filter(name=group).exists()",
    "docstring": "Returns whether a user is a member of a certain group.\n\n        Args:\n            group\n                The name of a group (string) or a group object\n\n        Returns:\n            Boolean"
  },
  {
    "code": "def install(self):\n        domain_settings = DomainSettings.get()\n        with root():\n            if os.path.exists(self.SMBCONF_FILE):\n                os.remove(self.SMBCONF_FILE)\n            if domain_settings.mode == 'ad':\n                domain_settings.adminpass = make_password(15)\n                domain_settings.save()\n                run(\"samba-tool domain provision \"\n                    \"--domain='%s' \"\n                    \"--workgroup='%s' \"\n                    \"--realm='%s' \"\n                    \"--use-xattrs=yes \"\n                    \"--use-rfc2307 \"\n                    \"--server-role='domain controller' \"\n                    \"--use-ntvfs \"\n                    \"--adminpass='%s'\" %\n                    (domain_settings.domain,\n                     domain_settings.workgroup,\n                     domain_settings.realm,\n                     domain_settings.adminpass))\n                self.smbconf.write()\n                shutil.copy2(self.SMB_KRB5CONF_FILE, self.KRB5CONF_FILE)\n                run(\"echo 'nameserver 127.0.0.1' > /etc/resolv.conf\")\n                run(\"touch /etc/samba/shares.conf\")\n            elif domain_settings.mode == 'member':\n                pass",
    "docstring": "Installation procedure, it writes basic smb.conf and uses samba-tool to\n        provision the domain"
  },
  {
    "code": "def fingerprint(self):\n        if self.num_vertices == 0:\n            return np.zeros(20, np.ubyte)\n        else:\n            return sum(self.vertex_fingerprints)",
    "docstring": "A total graph fingerprint\n\n           The result is invariant under permutation of the vertex indexes. The\n           chance that two different (molecular) graphs yield the same\n           fingerprint is small but not zero. (See unit tests.)"
  },
  {
    "code": "def get_package_name_in_pipfile(self, package_name, dev=False):\n        key = \"dev-packages\" if dev else \"packages\"\n        section = self.parsed_pipfile.get(key, {})\n        package_name = pep423_name(package_name)\n        for name in section.keys():\n            if pep423_name(name) == package_name:\n                return name\n        return None",
    "docstring": "Get the equivalent package name in pipfile"
  },
  {
    "code": "def _walk_modules(modules, class_name, path, ignored_formats, args):\n    for module in _iter_modules(modules=modules,\n                                class_name=class_name,\n                                path=path,\n                                ignored_formats=ignored_formats,\n                                args=args):\n        for section in module.sections:\n            for lecture in section.lectures:\n                for resource in lecture.resources:\n                    yield module, section, lecture, resource",
    "docstring": "Helper generator that traverses modules in returns a flattened\n    iterator."
  },
  {
    "code": "def whitespace_around_keywords(logical_line):\n    r\n    for match in KEYWORD_REGEX.finditer(logical_line):\n        before, after = match.groups()\n        if '\\t' in before:\n            yield match.start(1), \"E274 tab before keyword\"\n        elif len(before) > 1:\n            yield match.start(1), \"E272 multiple spaces before keyword\"\n        if '\\t' in after:\n            yield match.start(2), \"E273 tab after keyword\"\n        elif len(after) > 1:\n            yield match.start(2), \"E271 multiple spaces after keyword\"",
    "docstring": "r\"\"\"Avoid extraneous whitespace around keywords.\n\n    Okay: True and False\n    E271: True and  False\n    E272: True  and False\n    E273: True and\\tFalse\n    E274: True\\tand False"
  },
  {
    "code": "def _fetch_options(self, merge):\n        cmd = tuple()\n        for option in FETCH_DEFAULTS:\n            value = merge.get(option, self.defaults.get(option))\n            if value:\n                cmd += (\"--%s\" % option, str(value))\n        return cmd",
    "docstring": "Get the fetch options from the given merge dict."
  },
  {
    "code": "def get_urls(self):\n        urls = super(TreeAdmin, self).get_urls()\n        if django.VERSION < (1, 10):\n            from django.views.i18n import javascript_catalog\n            jsi18n_url = url(r'^jsi18n/$', javascript_catalog, {'packages': ('treebeard',)})\n        else:\n            from django.views.i18n import JavaScriptCatalog\n            jsi18n_url = url(r'^jsi18n/$',\n                JavaScriptCatalog.as_view(packages=['treebeard']),\n                name='javascript-catalog'\n            )\n        new_urls = [\n            url('^move/$', self.admin_site.admin_view(self.move_node), ),\n            jsi18n_url,\n        ]\n        return new_urls + urls",
    "docstring": "Adds a url to move nodes to this admin"
  },
  {
    "code": "def get_marathon_task(\n        task_name,\n        inactive=False,\n        completed=False\n):\n    return get_service_task('marathon', task_name, inactive, completed)",
    "docstring": "Get a dictionary describing a named marathon task"
  },
  {
    "code": "def get_type(self, idx):\n        _type = self.get_type_ref(idx)\n        if _type == -1:\n            return \"AG:ITI: invalid type\"\n        return self.get_string(_type)",
    "docstring": "Return the resolved type name based on the index\n\n        This returns the string associated with the type.\n\n        :param int idx:\n        :return: the type name\n        :rtype: str"
  },
  {
    "code": "def _aggregate_metrics(self, session_group):\n    if (self._request.aggregation_type == api_pb2.AGGREGATION_AVG or\n        self._request.aggregation_type == api_pb2.AGGREGATION_UNSET):\n      _set_avg_session_metrics(session_group)\n    elif self._request.aggregation_type == api_pb2.AGGREGATION_MEDIAN:\n      _set_median_session_metrics(session_group,\n                                  self._request.aggregation_metric)\n    elif self._request.aggregation_type == api_pb2.AGGREGATION_MIN:\n      _set_extremum_session_metrics(session_group,\n                                    self._request.aggregation_metric,\n                                    min)\n    elif self._request.aggregation_type == api_pb2.AGGREGATION_MAX:\n      _set_extremum_session_metrics(session_group,\n                                    self._request.aggregation_metric,\n                                    max)\n    else:\n      raise error.HParamsError('Unknown aggregation_type in request: %s' %\n                               self._request.aggregation_type)",
    "docstring": "Sets the metrics of the group based on aggregation_type."
  },
  {
    "code": "def _request(self, method, body=None, raise_exc=True, headers=None, files=None):\n        headers = headers or {}\n        if body and 'Content-Type' not in headers:\n            headers.update({'Content-Type': 'application/json'})\n        response = self._core.session.request(\n            method,\n            self.uri,\n            data=body if not isinstance(body, dict) else None,\n            json=body if isinstance(body, dict) else None,\n            files=files,\n            headers=headers,\n            allow_redirects=False,\n        )\n        nav = self._create_navigator(response, raise_exc=raise_exc)\n        if raise_exc and not response:\n            raise exc.HALNavigatorError(\n                message=response.text,\n                status=response.status_code,\n                nav=nav,\n                response=response,\n            )\n        else:\n            return nav",
    "docstring": "Fetches HTTP response using the passed http method. Raises\n        HALNavigatorError if response is in the 400-500 range."
  },
  {
    "code": "def copy(self, new_grab=None):\n        obj = self.__class__()\n        obj.process_grab(new_grab if new_grab else self.grab)\n        copy_keys = ('status', 'code', 'head', 'body', 'total_time',\n                     'connect_time', 'name_lookup_time',\n                     'url', 'charset', '_unicode_body',\n                     '_grab_config')\n        for key in copy_keys:\n            setattr(obj, key, getattr(self, key))\n        obj.headers = copy(self.headers)\n        obj.cookies = copy(self.cookies)\n        return obj",
    "docstring": "Clone the Response object."
  },
  {
    "code": "def _get_broadcasts(tables):\n    tables = set(tables)\n    casts = tz.keyfilter(\n        lambda x: x[0] in tables and x[1] in tables, _BROADCASTS)\n    if tables - set(tz.concat(casts.keys())):\n        raise ValueError('Not enough links to merge all tables.')\n    return casts",
    "docstring": "Get the broadcasts associated with a set of tables.\n\n    Parameters\n    ----------\n    tables : sequence of str\n        Table names for which broadcasts have been registered.\n\n    Returns\n    -------\n    casts : dict of `Broadcast`\n        Keys are tuples of strings like (cast_name, onto_name)."
  },
  {
    "code": "def get(self, request):\n        sections = self.generate_sections()\n        if self.paginated:\n            p = Paginator(sections, 25)\n            page = request.GET.get('page')\n            try:\n                sections = p.page(page)\n            except PageNotAnInteger:\n                sections = p.page(1)\n            except EmptyPage:\n                sections = p.page(p.num_pages)\n            pageUpper = int(p.num_pages) / 2\n            try:\n                pageLower = int(page) / 2\n            except TypeError:\n                pageLower = -999\n        else:\n            pageUpper = None\n            pageLower = None\n        context = {\n            'sections': sections,\n            'page_title': self.generate_page_title(),\n            'browse_type': self.browse_type,\n            'pageUpper': pageUpper,\n            'pageLower': pageLower\n        }\n        return render(\n            request,\n            self.template_path,\n            context\n        )",
    "docstring": "View for HTTP GET method.\n\n        Returns template and context from generate_page_title and\n        generate_sections to populate template."
  },
  {
    "code": "def mouse_press_event(self, x, y, button):\n        if button == 1:\n            print(\"Left mouse button pressed @\", x, y)\n        if button == 2:\n            print(\"Right mouse button pressed @\", x, y)",
    "docstring": "Reports left and right mouse button presses + position"
  },
  {
    "code": "def add_metric_group_definition(self, definition):\n        assert isinstance(definition, FakedMetricGroupDefinition)\n        group_name = definition.name\n        if group_name in self._metric_group_defs:\n            raise ValueError(\"A metric group definition with this name \"\n                             \"already exists: {}\".format(group_name))\n        self._metric_group_defs[group_name] = definition\n        self._metric_group_def_names.append(group_name)",
    "docstring": "Add a faked metric group definition.\n\n        The definition will be used:\n\n        * For later addition of faked metrics responses.\n        * For returning the metric-group-info objects in the response of the\n          Create Metrics Context operations.\n\n        For defined metric groups, see chapter \"Metric groups\" in the\n        :term:`HMC API` book.\n\n        Parameters:\n\n          definition (:class:~zhmcclient.FakedMetricGroupDefinition`):\n            Definition of the metric group.\n\n        Raises:\n\n          ValueError: A metric group definition with this name already exists."
  },
  {
    "code": "def as_dict(self):\n        d = {\"@module\": self.__class__.__module__,\n             \"@class\": self.__class__.__name__,\n             \"structure\": self.structure.as_dict(),\n             \"frequencies\": list(self.frequencies),\n             \"densities\": list(self.densities),\n             \"pdos\": []}\n        if len(self.pdos) > 0:\n            for at in self.structure:\n                d[\"pdos\"].append(list(self.pdos[at]))\n        return d",
    "docstring": "Json-serializable dict representation of CompletePhononDos."
  },
  {
    "code": "def param_redirect(request, viewname, *args):\n    url = reverse(viewname, PARAMS_URL_CONF, args)\n    params = request.GET.urlencode().split('&')\n    if hasattr(request, 'cparam'):\n        for k, v in request.cparam.items():\n            params.append('{0}={1}'.format(k, v))\n    new_params = '&'.join(x for x in params if x != '')\n    if len(new_params) > 0:\n        return HttpResponseRedirect('{0}?{1}'.format(url, new_params))\n    return HttpResponseRedirect(url)",
    "docstring": "Redirect and keep URL parameters if any."
  },
  {
    "code": "def _close_pidfile(self):\n        if self._pid_fd is not None:\n            os.close(self._pid_fd)\n        try:\n            os.remove(self.pidfile)\n        except OSError as ex:\n            if ex.errno != errno.ENOENT:\n                raise",
    "docstring": "Closes and removes the PID file."
  },
  {
    "code": "def ToOBMag(self, wave, flux, area=None):\n        area = area if area else refs.PRIMARY_AREA\n        bin_widths = \\\n            binning.calculate_bin_widths(binning.calculate_bin_edges(wave))\n        arg = flux * bin_widths * area\n        return -1.085736 * N.log(arg)",
    "docstring": "Convert to ``obmag``.\n\n        .. math::\n\n            \\\\textnormal{obmag} = -2.5 \\\\; \\\\log(\\\\delta \\\\lambda \\\\; \\\\times \\\\; \\\\textnormal{area} \\\\; \\\\times  \\\\; \\\\textnormal{photlam})\n\n        where :math:`\\\\delta \\\\lambda` represent bin widths derived from\n        :func:`~pysynphot.binning.calculate_bin_edges` and\n        :func:`~pysynphot.binning.calculate_bin_widths`, using the input\n        wavelength values as bin centers.\n\n        Parameters\n        ----------\n        wave, flux : number or array_like\n            Wavelength and flux values to be used for conversion.\n\n        area : number or `None`\n            Telescope collecting area. If not given, default value from\n            :ref:`pysynphot-refdata` is used.\n\n        Returns\n        -------\n        result : number or array_like\n            Converted values."
  },
  {
    "code": "def serialize_to_file(\n        root_processor,\n        value,\n        xml_file_path,\n        encoding='utf-8',\n        indent=None\n):\n    serialized_value = serialize_to_string(root_processor, value, indent)\n    with open(xml_file_path, 'w', encoding=encoding) as xml_file:\n        xml_file.write(serialized_value)",
    "docstring": "Serialize the value to an XML file using the root processor.\n\n    :param root_processor: Root processor of the XML document.\n    :param value: Value to serialize.\n    :param xml_file_path: Path to the XML file to which the serialized value will be written.\n    :param encoding: Encoding of the file.\n    :param indent: If specified, then the XML will be formatted with the specified indentation."
  },
  {
    "code": "def build_pipelines_lsst_io_configs(*, project_name, copyright=None):\n    sys.setrecursionlimit(2000)\n    c = {}\n    c = _insert_common_sphinx_configs(\n        c,\n        project_name=project_name)\n    c = _insert_html_configs(\n        c,\n        project_name=project_name,\n        short_project_name=project_name)\n    c = _insert_extensions(c)\n    c = _insert_intersphinx_mapping(c)\n    c = _insert_automodapi_configs(c)\n    c = _insert_matplotlib_configs(c)\n    c = _insert_graphviz_configs(c)\n    c = _insert_eups_version(c)\n    date = datetime.datetime.now()\n    c['today'] = date.strftime('%Y-%m-%d')\n    c['copyright'] = '2015-{year} LSST contributors'.format(\n        year=date.year)\n    c['todo_include_todos'] = False\n    c['exclude_patterns'] = [\n        'README.rst',\n        '_build',\n        'releases/note-source/*.rst',\n        'releases/tickets-source/*.rst',\n        'ups',\n        '.pyvenv',\n        '.github',\n        'home',\n    ]\n    c = _insert_rst_epilog(c)\n    c = _insert_jinja_configuration(c)\n    return c",
    "docstring": "Build a `dict` of Sphinx configurations that populate the ``conf.py``\n    of the main pipelines_lsst_io Sphinx project for LSST Science Pipelines\n    documentation.\n\n    The ``conf.py`` file can ingest these configurations via::\n\n       from documenteer.sphinxconfig.stackconf import \\\n           build_pipelines_lsst_io_configs\n\n       _g = globals()\n       _g.update(build_pipelines_lsst_io_configs(\n           project_name='LSST Science Pipelines')\n\n    You can subsequently customize the Sphinx configuration by directly\n    assigning global variables, as usual in a Sphinx ``config.py``, e.g.::\n\n       copyright = '2016 Association of Universities for '\n                   'Research in Astronomy, Inc.'\n\n    Parameters\n    ----------\n    project_name : `str`\n        Name of the project\n    copyright : `str`, optional\n        Copyright statement. Do not include the 'Copyright (c)' string; it'll\n        be added automatically.\n\n    Returns\n    -------\n    c : dict\n        Dictionary of configurations that should be added to the ``conf.py``\n        global namespace via::\n\n            _g = global()\n            _g.update(c)"
  },
  {
    "code": "def wait(self, *, block=True, timeout=None):\n        cleared = not self.backend.decr(self.key, 1, 1, self.ttl)\n        if cleared:\n            self.backend.wait_notify(self.key_events, self.ttl)\n            return True\n        if block:\n            return self.backend.wait(self.key_events, timeout)\n        return False",
    "docstring": "Signal that a party has reached the barrier.\n\n        Warning:\n          Barrier blocking is currently only supported by the stub and\n          Redis backends.\n\n        Warning:\n          Re-using keys between blocking calls may lead to undefined\n          behaviour.  Make sure your barrier keys are always unique\n          (use a UUID).\n\n        Parameters:\n          block(bool): Whether or not to block while waiting for the\n            other parties.\n          timeout(int): The maximum number of milliseconds to wait for\n            the barrier to be cleared.\n\n        Returns:\n          bool: Whether or not the barrier has been reached by all parties."
  },
  {
    "code": "def get_graphql_schema_from_orientdb_schema_data(schema_data, class_to_field_type_overrides=None,\n                                                 hidden_classes=None):\n    if class_to_field_type_overrides is None:\n        class_to_field_type_overrides = dict()\n    if hidden_classes is None:\n        hidden_classes = set()\n    schema_graph = SchemaGraph(schema_data)\n    return get_graphql_schema_from_schema_graph(schema_graph, class_to_field_type_overrides,\n                                                hidden_classes)",
    "docstring": "Construct a GraphQL schema from an OrientDB schema.\n\n    Args:\n        schema_data: list of dicts describing the classes in the OrientDB schema. The following\n                     format is the way the data is structured in OrientDB 2. See\n                     the README.md file for an example of how to query this data.\n                     Each dict has the following string fields:\n                        - name: string, the name of the class.\n                        - superClasses (optional): list of strings, the name of the class's\n                                                   superclasses.\n                        - superClass (optional): string, the name of the class's superclass. May be\n                                                 used instead of superClasses if there is only one\n                                                 superClass. Used for backwards compatibility with\n                                                 OrientDB.\n                        - customFields (optional): dict, string -> string, data defined on the class\n                                                   instead of instances of the class.\n                        - abstract: bool, true if the class is abstract.\n                        - properties: list of dicts, describing the class's properties.\n                                      Each property dictionary has the following string fields:\n                                         - name: string, the name of the property.\n                                         - type: int, builtin OrientDB type ID of the property.\n                                                 See schema_properties.py for the mapping.\n                                         - linkedType (optional): int, if the property is a\n                                                                  collection of builtin OrientDB\n                                                                  objects, then it indicates their\n                                                                  type ID.\n                                         - linkedClass (optional): string, if the property is a\n                                                                   collection of class instances,\n                                                                   then it indicates the name of\n                                                                   the class. If class is an edge\n                                                                   class, and the field name is\n                                                                   either 'in' or 'out', then it\n                                                                   describes the name of an\n                                                                   endpoint of the edge.\n                                         - defaultValue: string, the textual representation of the\n                                                         default value for the property, as\n                                                         returned by OrientDB's schema\n                                                         introspection code, e.g., '{}' for\n                                                         the embedded set type. Note that if the\n                                                         property is a collection type, it must\n                                                         have a default value.\n        class_to_field_type_overrides: optional dict, class name -> {field name -> field type},\n                                       (string -> {string -> GraphQLType}). Used to override the\n                                       type of a field in the class where it's first defined and all\n                                       the class's subclasses.\n        hidden_classes: optional set of strings, classes to not include in the GraphQL schema.\n\n    Returns:\n        tuple of (GraphQL schema object, GraphQL type equivalence hints dict).\n        The tuple is of type (GraphQLSchema, {GraphQLObjectType -> GraphQLUnionType})."
  },
  {
    "code": "def has_publish_permission(self, request, obj=None):\n        if is_automatic_publishing_enabled(self.model):\n            return False\n        user_obj = request.user\n        if not user_obj.is_active:\n            return False\n        if user_obj.is_superuser:\n            return True\n        if user_obj.has_perm('%s.can_publish' % self.opts.app_label):\n            return True\n        if user_obj.has_perm('%s.can_republish' % self.opts.app_label) and \\\n                obj and getattr(obj, 'has_been_published', False):\n            return True\n        return False",
    "docstring": "Determines if the user has permissions to publish.\n\n        :param request: Django request object.\n        :param obj: The object to determine if the user has\n        permissions to publish.\n        :return: Boolean."
  },
  {
    "code": "def azureContainerSAS(self, *args, **kwargs):\n        return self._makeApiCall(self.funcinfo[\"azureContainerSAS\"], *args, **kwargs)",
    "docstring": "Get Shared-Access-Signature for Azure Container\n\n        Get a shared access signature (SAS) string for use with a specific Azure\n        Blob Storage container.\n\n        The `level` parameter can be `read-write` or `read-only` and determines\n        which type of credentials are returned.  If level is read-write, it will create the\n        container if it doesn't already exist.\n\n        This method gives output: ``v1/azure-container-response.json#``\n\n        This method is ``stable``"
  },
  {
    "code": "def css_number(self, path, default=NULL, ignore_spaces=False, smart=False,\n                   make_int=True):\n        try:\n            text = self.css_text(path, smart=smart)\n            return find_number(text, ignore_spaces=ignore_spaces,\n                               make_int=make_int)\n        except IndexError:\n            if default is NULL:\n                raise\n            else:\n                return default",
    "docstring": "Find number in normalized text of node which\n            matches the given css path."
  },
  {
    "code": "def predict(self, date, obs_code=568):\n        time = Time(date, scale='utc', precision=6)\n        jd = ctypes.c_double(time.jd)\n        self.orbfit.predict.restype = ctypes.POINTER(ctypes.c_double * 5)\n        self.orbfit.predict.argtypes = [ ctypes.c_char_p, ctypes.c_double, ctypes.c_int ]\n        predict = self.orbfit.predict(ctypes.c_char_p(self.abg.name),\n                       jd,\n                       ctypes.c_int(obs_code))\n        self.coordinate = coordinates.SkyCoord(predict.contents[0],\n                                               predict.contents[1],\n                                               unit=(units.degree, units.degree))\n        self.dra = predict.contents[2]\n        self.ddec = predict.contents[3]\n        self.pa = predict.contents[4]\n        self.date = str(time)",
    "docstring": "use the bk predict method to compute the location of the source on the given date."
  },
  {
    "code": "def average_datetimes(dt_list):\n    if sys.version_info < (3, 3):\n        import time\n        def timestamp_func(dt):\n            return time.mktime(dt.timetuple())\n    else:\n        timestamp_func = datetime.timestamp\n    total = [timestamp_func(dt) for dt in dt_list]\n    return datetime.fromtimestamp(sum(total) / len(total))",
    "docstring": "Average a series of datetime objects.\n\n    .. note::\n\n        This function assumes all datetime objects are naive and in the same\n        time zone (UTC).\n\n    Args:\n        dt_list (iterable): Datetime objects to average\n\n    Returns: Average datetime as a datetime object"
  },
  {
    "code": "def marginalize_out(node_indices, tpm):\n    return tpm.sum(tuple(node_indices), keepdims=True) / (\n        np.array(tpm.shape)[list(node_indices)].prod())",
    "docstring": "Marginalize out nodes from a TPM.\n\n    Args:\n        node_indices (list[int]): The indices of nodes to be marginalized out.\n        tpm (np.ndarray): The TPM to marginalize the node out of.\n\n    Returns:\n        np.ndarray: A TPM with the same number of dimensions, with the nodes\n        marginalized out."
  },
  {
    "code": "def _get_per_location_glob(tasks, outputs, regexes):\n    paths = [o.path for o in outputs]\n    matches = [r.search(p) for r, p in zip(regexes, paths)]\n    for m, p, t in zip(matches, paths, tasks):\n        if m is None:\n            raise NotImplementedError(\"Couldn't deduce datehour representation in output path %r of task %s\" % (p, t))\n    n_groups = len(matches[0].groups())\n    positions = [most_common((m.start(i), m.end(i)) for m in matches)[0] for i in range(1, n_groups + 1)]\n    glob = list(paths[0])\n    for start, end in positions:\n        glob = glob[:start] + ['[0-9]'] * (end - start) + glob[end:]\n    return ''.join(glob).rsplit('/', 1)[0]",
    "docstring": "Builds a glob listing existing output paths.\n\n    Esoteric reverse engineering, but worth it given that (compared to an\n    equivalent contiguousness guarantee by naive complete() checks)\n    requests to the filesystem are cut by orders of magnitude, and users\n    don't even have to retrofit existing tasks anyhow."
  },
  {
    "code": "def reader(stream):\n    string = stream.read()\n    decoder = json.JSONDecoder().raw_decode\n    index = START.match(string, 0).end()\n    while index < len(string):\n        obj, end = decoder(string, index)\n        item = Item()\n        item.primitive = obj\n        yield item\n        index = END.match(string, end).end()",
    "docstring": "Read Items from a stream containing a JSON array."
  },
  {
    "code": "def has_files(the_path):\n    the_path = Path(the_path)\n    try:\n        for _ in the_path.walkfiles():\n            return True\n        return False\n    except OSError as ex:\n        if ex.errno == errno.ENOENT:\n            return False\n        else:\n            raise",
    "docstring": "Given a path, returns whether the path has any files in it or any subfolders. Works recursively."
  },
  {
    "code": "def search_nn(self, point, dist=None):\n        return next(iter(self.search_knn(point, 1, dist)), None)",
    "docstring": "Search the nearest node of the given point\n\n        point must be an actual point, not a node. The nearest node to the\n        point is returned. If a location of an actual node is used, the Node\n        with this location will be returned (not its neighbor).\n\n        dist is a distance function, expecting two points and returning a\n        distance value. Distance values can be any comparable type.\n\n        The result is a (node, distance) tuple."
  },
  {
    "code": "def polarity_as_string(self, add_colour=True):\n        with self._mutex:\n            if self.polarity == self.PROVIDED:\n                result = 'Provided', ['reset']\n            elif self.polarity == self.REQUIRED:\n                result = 'Required', ['reset']\n            if add_colour:\n                return utils.build_attr_string(result[1], supported=add_colour) + \\\n                        result[0] + utils.build_attr_string('reset',\n                                supported=add_colour)\n            else:\n                return result[0]",
    "docstring": "Get the polarity of this interface as a string.\n\n        @param add_colour If True, ANSI colour codes will be added to the\n                          string.\n        @return A string describing the polarity of this interface."
  },
  {
    "code": "def fit_row(connection, row, unique_keys):\n    new_columns = []\n    for column_name, column_value in list(row.items()):\n        new_column = sqlalchemy.Column(column_name,\n                                       get_column_type(column_value))\n        if not column_name in list(_State.table.columns.keys()):\n            new_columns.append(new_column)\n            _State.table.append_column(new_column)\n    if _State.table_pending:\n        create_table(unique_keys)\n        return\n    for new_column in new_columns:\n        add_column(connection, new_column)",
    "docstring": "Takes a row and checks to make sure it fits in the columns of the\n    current table. If it does not fit, adds the required columns."
  },
  {
    "code": "def fetch_coords(self, query):\n        q = query.add_query_parameter(req='coord')\n        return self._parse_messages(self.get_query(q).content)",
    "docstring": "Pull down coordinate data from the endpoint."
  },
  {
    "code": "def element_should_be_disabled(self, locator, loglevel='INFO'):\r\n        if self._element_find(locator, True, True).is_enabled():\r\n            self.log_source(loglevel)\r\n            raise AssertionError(\"Element '%s' should be disabled \"\r\n                                 \"but did not\" % locator)\r\n        self._info(\"Element '%s' is disabled .\" % locator)",
    "docstring": "Verifies that element identified with locator is disabled.\r\n\r\n        Key attributes for arbitrary elements are `id` and `name`. See\r\n        `introduction` for details about locating elements."
  },
  {
    "code": "def del_functions(self, names):\n        if isinstance(names, string_types):\n            names = [names]\n        for name in names:\n            self._functionlib.pop(name)",
    "docstring": "Removes the specified function names from the function library.\n\n        Functions are removed from this instance of the array; all copies\n        and slices of this array will also have the functions removed.\n\n        Parameters\n        ----------\n        names : (list of) string(s)\n            Name or list of names of the functions to remove."
  },
  {
    "code": "def _check_pool_attr(self, attr, req_attr=None):\n        if req_attr is None:\n            req_attr = []\n        self._check_attr(attr, req_attr, _pool_attrs)\n        if attr.get('ipv4_default_prefix_length') is not None:\n            try:\n                attr['ipv4_default_prefix_length'] = \\\n                    int(attr['ipv4_default_prefix_length'])\n                if (attr['ipv4_default_prefix_length'] > 32 or\n                    attr['ipv4_default_prefix_length'] < 1):\n                    raise ValueError()\n            except ValueError:\n                raise NipapValueError('Default IPv4 prefix length must be an integer between 1 and 32.')\n        if attr.get('ipv6_default_prefix_length'):\n            try:\n                attr['ipv6_default_prefix_length'] = \\\n                    int(attr['ipv6_default_prefix_length'])\n                if (attr['ipv6_default_prefix_length'] > 128 or\n                    attr['ipv6_default_prefix_length'] < 1):\n                    raise ValueError()\n            except ValueError:\n                raise NipapValueError('Default IPv6 prefix length must be an integer between 1 and 128.')",
    "docstring": "Check pool attributes."
  },
  {
    "code": "def do_GET(self):\n        if self.path.endswith(\"http_manifest.json\"):\n            try:\n                manifest = self.generate_http_manifest()\n                self.send_response(200)\n                self.end_headers()\n                self.wfile.write(manifest)\n            except dtoolcore.DtoolCoreTypeError:\n                self.send_response(400)\n                self.end_headers()\n        else:\n            super(DtoolHTTPRequestHandler, self).do_GET()",
    "docstring": "Override inherited do_GET method.\n\n        Include logic for returning a http manifest when the URL ends with\n        \"http_manifest.json\"."
  },
  {
    "code": "def installedApp(self):\n        try:    return self._installedApp\n        except:\n            self._installedApp = runConfigs.get()\n            return self._installedApp",
    "docstring": "identify the propery application to launch, given the configuration"
  },
  {
    "code": "def iter_ensure_instance(iterable, types):\n    ensure_instance(iterable, Iterable)\n    [ ensure_instance(item, types) for item in iterable ]",
    "docstring": "Iterate over object and check each item type\n\n    >>> iter_ensure_instance([1,2,3], [str])\n    Traceback (most recent call last):\n    TypeError:\n    >>> iter_ensure_instance([1,2,3], int)\n    >>> iter_ensure_instance(1, int)\n    Traceback (most recent call last):\n    TypeError:"
  },
  {
    "code": "def is_equal(self, other):\n        other = StringCell.coerce(other)\n        empties = [None,'']\n        if self.value in empties and other.value in empties:\n            return True\n        return self.value == other.value",
    "docstring": "Whether two strings are equal"
  },
  {
    "code": "def _handle_request_noblock(self):\n        try:\n            request, client_address = self.get_request()\n        except socket.error:\n            return\n        if self.verify_request(request, client_address):\n            try:\n                self.process_request(request, client_address)\n            except:\n                self.handle_error(request, client_address)\n                self.shutdown_request(request)",
    "docstring": "Handle one request, without blocking."
  },
  {
    "code": "def __pathToTuple(self, path):\n        if not path or path.count('/') > 2:\n            raise YTFS.PathConvertError(\"Bad path given\")\n        try:\n            split = path.split('/')\n        except (AttributeError, TypeError):\n            raise TypeError(\"Path has to be string\")\n        if split[0]:\n            raise YTFS.PathConvertError(\"Path needs to start with '/'\")\n        del split[0]\n        try:\n            if not split[-1]: split.pop()\n        except IndexError:\n            raise YTFS.PathConvertError(\"Bad path given\")\n        if len(split) > 2:\n            raise YTFS.PathConvertError(\"Path is too deep. Max allowed level is 2\")\n        try:\n            d = split[0]\n        except IndexError:\n            d = None\n        try:\n            f = split[1]\n        except IndexError:\n            f = None\n        if not d and f:\n            raise YTFS.PathConvertError(\"Bad path given\")\n        return (d, f)",
    "docstring": "Convert directory or file path to its tuple identifier.\n\n        Parameters\n        ----------\n        path : str\n            Path to convert. It can look like /, /directory, /directory/ or /directory/filename.\n\n        Returns\n        -------\n        tup_id : tuple\n            Two element tuple identifier of directory/file of (`directory`, `filename`) format. If path leads to main\n            directory, then both fields of tuple will be ``None``. If path leads to a directory, then field `filename`\n            will be ``None``.\n\n        Raises\n        ------\n        YTFS.PathConvertError\n            When invalid path is given."
  },
  {
    "code": "def _get_template(querystring_key, mapping):\n    default = None\n    try:\n        template_and_keys = mapping.items()\n    except AttributeError:\n        template_and_keys = mapping\n    for template, key in template_and_keys:\n        if key is None:\n            key = PAGE_LABEL\n            default = template\n        if key == querystring_key:\n            return template\n    return default",
    "docstring": "Return the template corresponding to the given ``querystring_key``."
  },
  {
    "code": "def wait(self, timeout=None):\n        self.__stopped.wait(timeout)\n        return self.__stopped.is_set()",
    "docstring": "Waits for the client to stop its loop"
  },
  {
    "code": "def ExecuteCommandFromClient(command):\n  cmd = command.cmd\n  args = command.args\n  time_limit = command.time_limit\n  res = client_utils_common.Execute(cmd, args, time_limit)\n  (stdout, stderr, status, time_used) = res\n  stdout = stdout[:10 * 1024 * 1024]\n  stderr = stderr[:10 * 1024 * 1024]\n  yield rdf_client_action.ExecuteResponse(\n      request=command,\n      stdout=stdout,\n      stderr=stderr,\n      exit_status=status,\n      time_used=int(1e6 * time_used))",
    "docstring": "Executes one of the predefined commands.\n\n  Args:\n    command: An `ExecuteRequest` object.\n\n  Yields:\n    `rdf_client_action.ExecuteResponse` objects."
  },
  {
    "code": "def can_process_matrix(entry, matrix_tags):\n        if len(matrix_tags) == 0:\n            return True\n        count = 0\n        if 'tags' in entry:\n            for tag in matrix_tags:\n                if tag in entry['tags']:\n                    count += 1\n        return count > 0",
    "docstring": "Check given matrix tags to be in the given list of matric tags.\n\n        Args:\n            entry (dict): matrix item (in yaml).\n            matrix_tags (list): represents --matrix-tags defined by user in command line.\n        Returns:\n            bool: True when matrix entry can be processed."
  },
  {
    "code": "def main(self) -> None:\n        path = ask_path(\"where should the config be stored?\", \".snekrc\")\n        conf = configobj.ConfigObj()\n        tools = self.get_tools()\n        for tool in tools:\n            conf[tool] = getattr(self, tool)()\n        conf.filename = path\n        conf.write()\n        print(\"Written config file!\")\n        if \"pylint\" in tools:\n            print(\n                \"Please also run `pylint --generate-rcfile` to complete setup\")",
    "docstring": "The main function for generating the config file"
  },
  {
    "code": "def sort_timeplaceentries(self, timeentry, placeentry) -> Tuple[Any, Any]:\n        if self._timeaxis:\n            return placeentry, timeentry\n        return timeentry, placeentry",
    "docstring": "Return a |tuple| containing the given `timeentry` and `placeentry`\n        sorted in agreement with the currently selected `timeaxis`.\n\n        >>> from hydpy.core.netcdftools import NetCDFVariableBase\n        >>> from hydpy import make_abc_testable\n        >>> NCVar = make_abc_testable(NetCDFVariableBase)\n        >>> ncvar = NCVar('flux_nkor', isolate=True, timeaxis=1)\n        >>> ncvar.sort_timeplaceentries('time', 'place')\n        ('place', 'time')\n        >>> ncvar = NetCDFVariableDeep('test', isolate=False, timeaxis=0)\n        >>> ncvar.sort_timeplaceentries('time', 'place')\n        ('time', 'place')"
  },
  {
    "code": "def get_seconds(self):\n        parsed = self.parse_hh_mm_ss()\n        total_seconds = parsed.second\n        total_seconds += parsed.minute * 60.0\n        total_seconds += parsed.hour * 60.0 * 60.0\n        return total_seconds",
    "docstring": "Gets seconds from raw time\n\n        :return: Seconds in time"
  },
  {
    "code": "def request_password_reset(self, user, base_url):\n        user.generate_password_link()\n        db.session.add(user)\n        db.session.commit()\n        events.password_change_requested_event.send(user)\n        self.send_password_change_message(user, base_url)",
    "docstring": "Regenerate password link and send message"
  },
  {
    "code": "def tokens(self, instance):\n        if not instance.pk:\n            return \"-\"\n        totp = TOTP(instance.bin_key, instance.step, instance.t0, instance.digits)\n        tokens = []\n        for offset in range(-instance.tolerance, instance.tolerance + 1):\n            totp.drift = instance.drift + offset\n            tokens.append(totp.token())\n        return \" \".join([\"%s\" % token for token in tokens])",
    "docstring": "Just display current acceptable TOTP tokens"
  },
  {
    "code": "def seq_view_shot(self, ):\n        if not self.cur_seq:\n            return\n        i = self.seq_shot_tablev.currentIndex()\n        item = i.internalPointer()\n        if item:\n            shot = item.internal_data()\n            self.view_shot(shot)",
    "docstring": "View the shot that is selected in the table view of the sequence page\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def transformer_wikitext103_l4k_memory_v0():\n  hparams = transformer_wikitext103_l4k_v0()\n  hparams.split_targets_chunk_length = 64\n  hparams.split_targets_max_chunks = 64\n  hparams.split_targets_strided_training = True\n  hparams.add_hparam(\"memory_type\", \"transformer_xl\")\n  target_tokens_per_batch = 4096\n  hparams.batch_size = int(target_tokens_per_batch * (\n      hparams.max_length / hparams.split_targets_chunk_length))\n  hparams.pos = None\n  hparams.self_attention_type = \"dot_product_relative\"\n  hparams.max_relative_position = 2 * hparams.split_targets_chunk_length\n  hparams.add_hparam(\"unconditional\", True)\n  hparams.add_hparam(\"recurrent_memory_batch_size\", 0)\n  hparams.add_hparam(\"num_memory_items\", hparams.split_targets_chunk_length)\n  return hparams",
    "docstring": "HParams for training languagemodel_wikitext103_l4k with memory."
  },
  {
    "code": "def get_parsed_context(pipeline, context_in_string):\n    logger.debug(\"starting\")\n    if 'context_parser' in pipeline:\n        parser_module_name = pipeline['context_parser']\n        logger.debug(f\"context parser found: {parser_module_name}\")\n        parser_module = pypyr.moduleloader.get_module(parser_module_name)\n        try:\n            logger.debug(f\"running parser {parser_module_name}\")\n            result_context = parser_module.get_parsed_context(\n                context_in_string)\n            logger.debug(f\"step {parser_module_name} done\")\n            if result_context is None:\n                logger.debug(f\"{parser_module_name} returned None. Using \"\n                             \"empty context instead\")\n                return pypyr.context.Context()\n            else:\n                return pypyr.context.Context(result_context)\n        except AttributeError:\n            logger.error(f\"The parser {parser_module_name} doesn't have a \"\n                         \"get_parsed_context(context) function.\")\n            raise\n    else:\n        logger.debug(\"pipeline does not have custom context parser. Using \"\n                     \"empty context.\")\n        logger.debug(\"done\")\n        return pypyr.context.Context()",
    "docstring": "Execute get_parsed_context handler if specified.\n\n    Dynamically load the module specified by the context_parser key in pipeline\n    dict and execute the get_parsed_context function on that module.\n\n    Args:\n        pipeline: dict. Pipeline object.\n        context_in_string: string. Argument string used to initialize context.\n\n    Returns:\n        pypyr.context.Context() instance.\n\n    Raises:\n        AttributeError: parser specified on pipeline missing get_parsed_context\n                        function."
  },
  {
    "code": "def get_version(version):\n    if len(version) > 2 and version[2] is not None:\n        if isinstance(version[2], int):\n            str_version = \"%s.%s.%s\" % version[:3]\n        else:\n            str_version = \"%s.%s_%s\" % version[:3]\n    else:\n        str_version = \"%s.%s\" % version[:2]\n    return str_version",
    "docstring": "Dynamically calculate the version based on VERSION tuple."
  },
  {
    "code": "def max_brightness(self):\n        self._max_brightness, value = self.get_cached_attr_int(self._max_brightness, 'max_brightness')\n        return value",
    "docstring": "Returns the maximum allowable brightness value."
  },
  {
    "code": "def remove_root_log(self, log_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.remove_root_catalog(catalog_id=log_id)\n        return self._hierarchy_session.remove_root(id_=log_id)",
    "docstring": "Removes a root log.\n\n        arg:    log_id (osid.id.Id): the ``Id`` of a log\n        raise:  NotFound - ``log_id`` is not a root\n        raise:  NullArgument - ``log_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def generate_id(self):\n        if self.use_repeatable_ids:\n            self.repeatable_id_counter += 1\n            return 'autobaked-{}'.format(self.repeatable_id_counter)\n        else:\n            return str(uuid4())",
    "docstring": "Generate a fresh id"
  },
  {
    "code": "def validate_on_submit(self):\n        valid = FlaskWtf.validate_on_submit(self)\n        if not self._schema or not self.is_submitted():\n            return valid\n        data = dict()\n        for field in self._fields:\n            data[field] = self._fields[field].data\n        result = self.schema.process(data, context=self._force_context)\n        self.set_errors(result)\n        for field in data:\n            self._fields[field].data = data[field]\n        return valid and not bool(self.errors)",
    "docstring": "Extend validate on submit to allow validation with schema"
  },
  {
    "code": "def get_selected_tab(self):\n        selected = self.request.GET.get(self.param_name, None)\n        if selected:\n            try:\n                tab_group, tab_name = selected.split(SEPARATOR)\n            except ValueError:\n                return None\n            if tab_group == self.get_id():\n                self._selected = self.get_tab(tab_name)\n        return self._selected",
    "docstring": "Returns the tab specific by the GET request parameter.\n\n        In the event that there is no GET request parameter, the value\n        of the query parameter is invalid, or the tab is not allowed/enabled,\n        the return value of this function is None."
  },
  {
    "code": "def complement(self):\n        if self.is_empty:\n            return StridedInterval.top(self.bits)\n        if self.is_top:\n            return StridedInterval.empty(self.bits)\n        y_plus_1 = StridedInterval._modular_add(self.upper_bound, 1, self.bits)\n        x_minus_1 = StridedInterval._modular_sub(self.lower_bound, 1, self.bits)\n        dist = StridedInterval._wrapped_cardinality(y_plus_1, x_minus_1, self.bits) - 1\n        if dist < 0:\n            new_stride = 0\n        elif self._stride == 0:\n            new_stride = 1\n        else:\n            new_stride = fractions.gcd(self._stride, dist)\n        return StridedInterval(lower_bound=y_plus_1,\n                               upper_bound=x_minus_1,\n                               bits=self.bits,\n                               stride=new_stride,\n                               uninitialized=self.uninitialized)",
    "docstring": "Return the complement of the interval\n        Refer section 3.1 augmented for managing strides\n\n        :return:"
  },
  {
    "code": "def _check_current_value(gnome_kwargs, value):\n    current_value = __salt__['gnome.get'](**gnome_kwargs)\n    return six.text_type(current_value) == six.text_type(value)",
    "docstring": "Check the current value with the passed value"
  },
  {
    "code": "def get_class_doc(klass, config=default_config):\n    if config.exclude_class:\n        for ex in config.exclude_class:\n            if ex.match(klass.__name__):\n                return None\n    nested_doc = []\n    class_dict = klass.__dict__\n    for item in dir(klass):\n        if item in class_dict.keys():\n            appended = None\n            if isinstance(class_dict[item], type) and config.nested_class:\n                appended = get_class_doc(class_dict[item], config)\n            elif isinstance(class_dict[item], types.FunctionType):\n                appended = get_function_doc(class_dict[item], config)\n            if appended is not None:\n                nested_doc.append(appended)\n    return _doc_object(klass, 'class', nested_doc, config)",
    "docstring": "Return doc for a class."
  },
  {
    "code": "def main(self):\n        self._setup_task_manager()\n        self._setup_source_and_destination()\n        self.task_manager.blocking_start(waiting_func=self.waiting_func)\n        self.close()\n        self.config.logger.info('done.')",
    "docstring": "this main routine sets up the signal handlers, the source and\n        destination crashstorage systems at the  theaded task manager.  That\n        starts a flock of threads that are ready to shepherd crashes from\n        the source to the destination."
  },
  {
    "code": "def num_samples(self, sr=None):\n        native_sr = self.sampling_rate\n        num_samples = units.seconds_to_sample(self.duration, native_sr)\n        if sr is not None:\n            ratio = float(sr) / native_sr\n            num_samples = int(np.ceil(num_samples * ratio))\n        return num_samples",
    "docstring": "Return the number of samples.\n\n        Args:\n            sr (int): Calculate the number of samples with the given\n                      sampling-rate. If None use the native sampling-rate.\n\n        Returns:\n            int: Number of samples"
  },
  {
    "code": "def ratio(self, col: str, ratio_col: str=\"Ratio\"):\n        try:\n            df = self.df.copy()\n            df[ratio_col] = df[[col]].apply(\n                lambda x: 100 * x / float(x.sum()))\n            self.df = df\n        except Exception as e:\n            self.err(e, self.ratio, \"Can not calculate ratio\")",
    "docstring": "Add a column whith the percentages ratio from a column\n\n        :param col: column to calculate ratio from\n        :type col: str\n        :param ratio_col: new ratio column name, defaults to \"Ratio\"\n        :param ratio_col: str, optional\n\n        :example: ``ds2 = ds.ratio(\"Col 1\")``"
  },
  {
    "code": "def _get_attrs(self, names):\n        assert isinstance(names, str)\n        names = names.replace(\",\", \" \").split(\" \")\n        res = []\n        for n in names:\n            if n == \"\":\n                continue\n            if n not in self.__dict__:\n                raise KeyError(\"Unknown name for Container attribute: '{}'\".format(n))\n            res.append(getattr(self, n))\n        return res",
    "docstring": "Convenience function to extract multiple attributes at once\n\n        :param names:   string of names separated by comma or space\n        :return:"
  },
  {
    "code": "def dbg_repr(self, max_display=10):\n        s = repr(self) + \"\\n\"\n        if len(self.chosen_statements) > max_display:\n            s += \"%d SimRuns in program slice, displaying %d.\\n\" % (len(self.chosen_statements), max_display)\n        else:\n            s += \"%d SimRuns in program slice.\\n\" % len(self.chosen_statements)\n        if max_display is None:\n            run_addrs = sorted(self.chosen_statements.keys())\n        else:\n            run_addrs = sorted(self.chosen_statements.keys())[ : max_display]\n        for run_addr in run_addrs:\n            s += self.dbg_repr_run(run_addr) + \"\\n\"\n        return s",
    "docstring": "Debugging output of this slice.\n\n        :param max_display: The maximum number of SimRun slices to show.\n        :return:            A string representation."
  },
  {
    "code": "def exec_before_request_actions(actions, **kwargs):\n    groups = (\"before\", \"before_\" + flask.request.method.lower())\n    return execute_actions(actions, limit_groups=groups, **kwargs)",
    "docstring": "Execute actions in the \"before\" and \"before_METHOD\" groups"
  },
  {
    "code": "def get_static_properties(self):\n        return {tags.tag: tags.get('VALUE') for tags in self.bnmodel.find('STATICPROPERTIES')}",
    "docstring": "Returns a dictionary of STATICPROPERTIES\n\n        Examples\n        --------\n        >>> reader = XBNReader('xbn_test.xml')\n        >>> reader.get_static_properties()\n        {'FORMAT': 'MSR DTAS XML', 'VERSION': '0.2', 'CREATOR': 'Microsoft Research DTAS'}"
  },
  {
    "code": "def enterEvent(self, event):\n        super(XViewPanelItem, self).enterEvent(event)\n        self._hovered = True\n        self.update()",
    "docstring": "Mark the hovered state as being true.\n\n        :param      event | <QtCore.QEnterEvent>"
  },
  {
    "code": "def _get_data_volumes(vm_):\n    ret = []\n    volumes = vm_['volumes']\n    for key, value in six.iteritems(volumes):\n        if 'disk_size' not in volumes[key].keys():\n            raise SaltCloudConfigError(\n                'The volume \\'{0}\\' is missing \\'disk_size\\''.format(key)\n            )\n        if 'disk_type' not in volumes[key].keys():\n            volumes[key]['disk_type'] = 'HDD'\n        volume = Volume(\n            name=key,\n            size=volumes[key]['disk_size'],\n            disk_type=volumes[key]['disk_type'],\n            licence_type='OTHER'\n        )\n        if 'disk_availability_zone' in volumes[key].keys():\n            volume.availability_zone = volumes[key]['disk_availability_zone']\n        ret.append(volume)\n    return ret",
    "docstring": "Construct a list of optional data volumes from the cloud profile"
  },
  {
    "code": "def pop(self, key, default=None):\n        return self._dictionary.pop(key.lower(), default)",
    "docstring": "Remove the key and return the associated value or default if not\n            found\n\n            Args:\n                key (str): The key to remove\n                default (obj): The value to return if key is not present"
  },
  {
    "code": "def addPrivateCertificate(self, subjectName, existingCertificate=None):\n        if existingCertificate is None:\n            assert '@' not in subjectName, \"Don't self-sign user certs!\"\n            mainDN = DistinguishedName(commonName=subjectName)\n            mainKey = KeyPair.generate()\n            mainCertReq = mainKey.certificateRequest(mainDN)\n            mainCertData = mainKey.signCertificateRequest(\n                mainDN, mainCertReq,\n                lambda dn: True,\n                self.genSerial(subjectName)\n            )\n            mainCert = mainKey.newCertificate(mainCertData)\n        else:\n            mainCert = existingCertificate\n        self.localStore[subjectName] = mainCert",
    "docstring": "Add a PrivateCertificate object to this store for this subjectName.\n\n        If existingCertificate is None, add a new self-signed certificate."
  },
  {
    "code": "def find(self, soup):\n        for tag in soup.recursiveChildGenerator():\n            if self.match_criterion(tag):\n                yield tag",
    "docstring": "Yield tags matching the tag criterion from a soup.\n\n        There is no need to override this if you are satisfied with finding\n        tags that match match_criterion.\n\n        Args:\n            soup: A BeautifulSoup to search through.\n\n        Yields:\n            BeautifulSoup Tags that match the criterion."
  },
  {
    "code": "def _print(self, force_flush=False):\n        self._stream_flush()\n        next_perc = self._calc_percent()\n        if self.update_interval:\n            do_update = time.time() - self.last_time >= self.update_interval\n        elif force_flush:\n            do_update = True\n        else:\n            do_update = next_perc > self.last_progress\n        if do_update and self.active:\n            self.last_progress = next_perc\n            self._cache_percent_indicator(self.last_progress)\n            if self.track:\n                self._cached_output += ' Time elapsed: ' + \\\n                                       self._get_time(self._elapsed())\n                self._cache_eta()\n            if self.item_id:\n                self._cache_item_id()\n            self._stream_out('\\r%s' % self._cached_output)\n            self._stream_flush()\n            self._cached_output = ''",
    "docstring": "Prints formatted percentage and tracked time to the screen."
  },
  {
    "code": "def where(self, **kwargs):\n        clauses = copy(self.clauses)\n        for dimension, condition in kwargs.items():\n            if dimension in self.clauses:\n                raise Exception('There should be only one clause for {}'.format(dimension))\n            if dimension not in self.schema:\n                raise Exception('The dimension {} doesn\\'t exist'.format(dimension))\n            if isfunction(condition) or isinstance(condition, functools.partial):\n                clauses[dimension] = condition\n            else:\n                clauses[dimension] = functools.partial((lambda x, y: x == y), self._sanitize_dimension(str(condition)))\n        return self._copy(clauses=clauses)",
    "docstring": "Return a new Dataset refined using the given condition\n\n        :param kwargs: a map of `dimension` => `condition` to filter the elements\n            of the dataset. `condition` can either be an exact value or a\n            callable returning a boolean value. If `condition` is a value, it is\n            converted to a string, then sanitized. If `condition` is a callable, note that it will\n            be passed sanitized values -- i.e., characters outside [a-zA-Z0-9_.] are converted\n            to `_`."
  },
  {
    "code": "def send_raw_packet(self, packet: str):\n        data = packet + '\\r\\n'\n        log.debug('writing data: %s', repr(data))\n        self.transport.write(data.encode())",
    "docstring": "Encode and put packet string onto write buffer."
  },
  {
    "code": "def add_user_rating(self, item_type, item_id, item_rating):\n        raw_response = requests_util.run_request('put',\n                                                 self.API_BASE_URL + '/user/ratings/%s/%d/%d' %\n                                                 (item_type, item_id, item_rating),\n                                                 headers=self.__get_header_with_auth())\n        return self.parse_raw_response(raw_response)",
    "docstring": "Adds the rating for the item indicated for the current user.\n\n        :param item_type: One of: series, episode, banner.\n        :param item_id: The TheTVDB id of the item.\n        :param item_rating: The rating from 0 to 10.\n        :return:"
  },
  {
    "code": "def remove_empty_cols(records):\n    records = list(records)\n    seqstrs = [str(rec.seq) for rec in records]\n    clean_cols = [col\n                  for col in zip(*seqstrs)\n                  if not all(c == '-' for c in col)]\n    clean_seqs = [''.join(row)\n                  for row in zip(*clean_cols)]\n    for rec, clean_seq in zip(records, clean_seqs):\n        yield SeqRecord(Seq(clean_seq, rec.seq.alphabet), id=rec.id,\n                        name=rec.name, description=rec.description,\n                        dbxrefs=rec.dbxrefs, features=rec.features,\n                        annotations=rec.annotations,\n                        letter_annotations=rec.letter_annotations)",
    "docstring": "Remove all-gap columns from aligned SeqRecords."
  },
  {
    "code": "def collect_directories(self, directories):\n        directories = util.to_absolute_paths(directories)\n        if not self.recursive:\n            return self._remove_blacklisted(directories)\n        recursive_dirs = set()\n        for dir_ in directories:\n            walk_iter = os.walk(dir_, followlinks=True)\n            walk_iter = [w[0] for w in walk_iter]\n            walk_iter = util.to_absolute_paths(walk_iter)\n            walk_iter = self._remove_blacklisted(walk_iter)\n            recursive_dirs.update(walk_iter)\n        return recursive_dirs",
    "docstring": "Collects all the directories into a `set` object.\n\n        If `self.recursive` is set to `True` this method will iterate through\n        and return all of the directories and the subdirectories found from\n        `directories` that are not blacklisted.\n\n        if `self.recursive` is set to `False` this will return all the\n        directories that are not balcklisted.\n\n        `directories` may be either a single object or an iterable. Recommend\n        passing in absolute paths instead of relative. `collect_directories`\n        will attempt to convert `directories` to absolute paths if they are not\n        already."
  },
  {
    "code": "def area2lonlat(dataarray):\n    area = dataarray.attrs['area']\n    lons, lats = area.get_lonlats_dask()\n    lons = xr.DataArray(lons, dims=['y', 'x'],\n                        attrs={'name': \"longitude\",\n                               'standard_name': \"longitude\",\n                               'units': 'degrees_east'},\n                        name='longitude')\n    lats = xr.DataArray(lats, dims=['y', 'x'],\n                        attrs={'name': \"latitude\",\n                               'standard_name': \"latitude\",\n                               'units': 'degrees_north'},\n                        name='latitude')\n    dataarray.attrs['coordinates'] = 'longitude latitude'\n    return [dataarray, lons, lats]",
    "docstring": "Convert an area to longitudes and latitudes."
  },
  {
    "code": "def open_url(self, url, sleep_after_open=2):\n        self.zap.urlopen(url)\n        time.sleep(sleep_after_open)",
    "docstring": "Access a URL through ZAP."
  },
  {
    "code": "def map_position(pos):\n    posiction_dict = dict(zip(range(1, 17), [i for i in range(30, 62) if i % 2]))\n    return posiction_dict[pos]",
    "docstring": "Map natural position to machine code postion"
  },
  {
    "code": "def process_bind_param(self, obj, dialect):\n        value = obj or {}\n        if isinstance(obj, flask_cloudy.Object):\n            value = {}\n            for k in self.DEFAULT_KEYS:\n                value[k] = getattr(obj, k)\n        return super(self.__class__, self).process_bind_param(value, dialect)",
    "docstring": "Get a flask_cloudy.Object and save it as a dict"
  },
  {
    "code": "def get_log_id(cls, id):\n        conn = Qubole.agent()\n        r = conn.get_raw(cls.element_path(id) + \"/logs\")\n        return r.text",
    "docstring": "Fetches log for the command represented by this id\n\n        Args:\n            `id`: command id"
  },
  {
    "code": "def clean_line(str, delimiter):\n    return [x.strip() for x in str.strip().split(delimiter) if x != '']",
    "docstring": "Split string on given delimiter, remove whitespace from each field."
  },
  {
    "code": "def height(self):\n        alloc_h = self.alloc_h\n        if self.parent and isinstance(self.parent, graphics.Scene):\n            alloc_h = self.parent.height\n        min_height = (self.min_height or 0) + self.margin_top + self.margin_bottom\n        h = alloc_h if alloc_h is not None and self.fill else min_height\n        h = max(h or 0, self.get_min_size()[1])\n        return h - self.margin_top - self.margin_bottom",
    "docstring": "height in pixels"
  },
  {
    "code": "def get_entries(self, start=0, end=0, data_request=None, steam_ids=None):\n        message = MsgProto(EMsg.ClientLBSGetLBEntries)\n        message.body.app_id = self.app_id\n        message.body.leaderboard_id = self.id\n        message.body.range_start = start\n        message.body.range_end = end\n        message.body.leaderboard_data_request = self.data_request if data_request is None else data_request\n        if steam_ids:\n            message.body.steamids.extend(steam_ids)\n        resp = self._steam.send_job_and_wait(message, timeout=15)\n        if not resp:\n            raise LookupError(\"Didn't receive response within 15seconds :(\")\n        if resp.eresult != EResult.OK:\n            raise LookupError(EResult(resp.eresult))\n        if resp.HasField('leaderboard_entry_count'):\n            self.entry_count = resp.leaderboard_entry_count\n        return resp.entries",
    "docstring": "Get leaderboard entries.\n\n        :param start: start entry, not index (e.g. rank 1 is ``start=1``)\n        :type start: :class:`int`\n        :param end: end entry, not index (e.g. only one entry then ``start=1,end=1``)\n        :type end: :class:`int`\n        :param data_request: data being requested\n        :type data_request: :class:`steam.enums.common.ELeaderboardDataRequest`\n        :param steam_ids: list of steam ids when using :prop:`.ELeaderboardDataRequest.Users`\n        :type steamids: :class:`list`\n        :return: a list of entries, see ``CMsgClientLBSGetLBEntriesResponse``\n        :rtype: :class:`list`\n        :raises: :class:`LookupError` on message timeout or error"
  },
  {
    "code": "def policy(self, observations):\n        input_data = self.input_block(observations)\n        policy_base_output = self.policy_backbone(input_data)\n        policy_params = self.action_head(policy_base_output)\n        return policy_params",
    "docstring": "Calculate only action head for given state"
  },
  {
    "code": "def deleteByOrigIndex(self, index):\n        result = []\n        result_tracker = []\n        for counter, row in enumerate(self.table):\n            if self.index_track[counter] != index:\n                result.append(row)\n                result_tracker.append(self.index_track[counter])\n        self.table = result\n        self.index_track = result_tracker\n        return self",
    "docstring": "Removes a single entry from the list given the index reference.\n\n        The index, in this instance, is a reference to the *original* list\n        indexing as seen when the list was first inserted into PLOD.\n\n        An example:\n\n        >>> test = [\n        ...    {\"name\": \"Jim\",   \"age\": 18, \"income\": 93000, \"wigs\": 68       },\n        ...    {\"name\": \"Larry\", \"age\": 18,                  \"wigs\": [3, 2, 9]},\n        ...    {\"name\": \"Joe\",   \"age\": 20, \"income\": 15000, \"wigs\": [1, 2, 3]},\n        ...    {\"name\": \"Bill\",  \"age\": 19, \"income\": 29000                   },\n        ... ]\n        >>> myPLOD = PLOD(test)\n        >>> print myPLOD.sort(\"name\").returnString()\n        [\n            {age: 19, income: 29000, name: 'Bill' , wigs: None     },\n            {age: 18, income: 93000, name: 'Jim'  , wigs:        68},\n            {age: 20, income: 15000, name: 'Joe'  , wigs: [1, 2, 3]},\n            {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]}\n        ]\n        >>> print myPLOD.deleteByOrigIndex(0).returnString()\n        [\n            {age: 19, income: 29000, name: 'Bill' , wigs: None     },\n            {age: 20, income: 15000, name: 'Joe'  , wigs: [1, 2, 3]},\n            {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]}\n        ]\n\n        As you can see in the example, the list was sorted by 'name', which\n        placed 'Bill' as the first entry. Yet, when the deleteByOrigIndex was\n        passed a zero (for the first entry), it removed 'Jim' instead since\n        it was the original first entry.\n\n        :param index:\n           An integer representing the place of entry in the original list\n           of dictionaries.\n        :return:\n           self"
  },
  {
    "code": "def LDA_discriminants(x, labels):\n    try:    \n        x = np.array(x)\n    except:\n        raise ValueError('Impossible to convert x to a numpy array.')\n    eigen_values, eigen_vectors = LDA_base(x, labels)\n    return eigen_values[(-eigen_values).argsort()]",
    "docstring": "Linear Discriminant Analysis helper for determination how many columns of\n    data should be reduced.\n\n    **Args:**\n\n    * `x` : input matrix (2d array), every row represents new sample\n\n    * `labels` : list of labels (iterable), every item should be label for \\\n        sample with corresponding index\n\n    **Returns:**\n    \n    * `discriminants` : array of eigenvalues sorted in descending order"
  },
  {
    "code": "def check_signature(signature, key, data):\n    if isinstance(key, type(u'')):\n        key = key.encode()\n    digest = 'sha1=' + hmac.new(key, data, hashlib.sha1).hexdigest()\n    if isinstance(digest, type(u'')):\n        digest = digest.encode()\n    if isinstance(signature, type(u'')):\n        signature = signature.encode()\n    return werkzeug.security.safe_str_cmp(digest, signature)",
    "docstring": "Compute the HMAC signature and test against a given hash."
  },
  {
    "code": "def purge(root=os.path.join(base.data_dir(), 'models')):\n    r\n    root = os.path.expanduser(root)\n    files = os.listdir(root)\n    for f in files:\n        if f.endswith(\".params\"):\n            os.remove(os.path.join(root, f))",
    "docstring": "r\"\"\"Purge all pretrained model files in local file store.\n\n    Parameters\n    ----------\n    root : str, default '$MXNET_HOME/models'\n        Location for keeping the model parameters."
  },
  {
    "code": "def add(self, resource):\n        if isinstance(resource, collections.Iterable):\n            for r in resource:\n                self.resources.append(r)\n        else:\n            self.resources.append(resource)",
    "docstring": "Add a resource or an iterable collection of resources to this container.\n\n        Must be implemented in derived class."
  },
  {
    "code": "def _get_assignments_in(self, filterlist, symbol = \"\"):\n        if symbol != \"\":\n            lsymbol = symbol\n            for assign in self._assignments:\n                target = assign.split(\"%\")[0].lower()\n                if target == lsymbol:\n                    return True\n        else:\n            result = []\n            for assign in self._assignments:\n                target = assign.split(\"%\")[0].lower()\n                if target in filterlist:\n                    result.append(assign)\n            return result",
    "docstring": "Returns a list of code elements whose names are in the specified object.\n\n        :arg filterlist: the list of symbols to check agains the assignments.\n        :arg symbol: when specified, return true if that symbol has its value\n          changed via an assignment."
  },
  {
    "code": "def _psi_n(x, n, b):\n    return 2**(b-1) / gamma(b) * (-1)**n * \\\n    np.exp(gammaln(n+b) -\n           gammaln(n+1) +\n           np.log(2*n+b) -\n           0.5 * np.log(2*np.pi*x**3) -\n           (2*n+b)**2 / (8.*x))",
    "docstring": "Compute the n-th term in the infinite sum of\n    the Jacobi density."
  },
  {
    "code": "def get_docs_sources_from_ES(self):\n        docs = [doc for doc, _, _, get_from_ES in self.doc_to_update if get_from_ES]\n        if docs:\n            documents = self.docman.elastic.mget(body={\"docs\": docs}, realtime=True)\n            return iter(documents[\"docs\"])\n        else:\n            return iter([])",
    "docstring": "Get document sources using MGET elasticsearch API"
  },
  {
    "code": "def createPedChr24UsingPlink(options):\n    plinkCommand = [\"plink\", \"--noweb\", \"--bfile\", options.bfile, \"--chr\",\n                    \"24\", \"--recodeA\", \"--keep\",\n                    options.out + \".list_problem_sex_ids\", \"--out\",\n                    options.out + \".chr24_recodeA\"]\n    runCommand(plinkCommand)",
    "docstring": "Run plink to create a ped format.\n\n    :param options: the options.\n\n    :type options: argparse.Namespace\n\n    Uses Plink to create a ``ped`` file of markers on the chromosome ``24``. It\n    uses the ``recodeA`` options to use additive coding. It also subsets the\n    data to keep only samples with sex problems."
  },
  {
    "code": "def extract_context(tex_file, extracted_image_data):\n    if os.path.isdir(tex_file) or not os.path.exists(tex_file):\n        return []\n    lines = \"\".join(get_lines_from_file(tex_file))\n    for data in extracted_image_data:\n        context_list = []\n        indicies = [match.span()\n                    for match in re.finditer(r\"(\\\\(?:fig|ref)\\{%s\\})\" %\n                                             (re.escape(data['label']),),\n                                             lines)]\n        for startindex, endindex in indicies:\n            i = startindex - CFG_PLOTEXTRACTOR_CONTEXT_EXTRACT_LIMIT\n            if i < 0:\n                text_before = lines[:startindex]\n            else:\n                text_before = lines[i:startindex]\n            context_before = get_context(text_before, backwards=True)\n            i = endindex + CFG_PLOTEXTRACTOR_CONTEXT_EXTRACT_LIMIT\n            text_after = lines[endindex:i]\n            context_after = get_context(text_after)\n            context_list.append(\n                context_before + ' \\\\ref{' + data['label'] + '} ' +\n                context_after\n            )\n        data['contexts'] = context_list",
    "docstring": "Extract context.\n\n    Given a .tex file and a label name, this function will extract the text\n    before and after for all the references made to this label in the text.\n    The number of characters to extract before and after is configurable.\n\n    :param tex_file (list): path to .tex file\n    :param extracted_image_data ([(string, string, list), ...]):\n        a list of tuples of images matched to labels and captions from\n        this document.\n\n    :return extracted_image_data ([(string, string, list, list),\n        (string, string, list, list),...)]: the same list, but now containing\n        extracted contexts"
  },
  {
    "code": "def journal_event(events):\n    reasons = set(chain.from_iterable(e.reasons for e in events))\n    attributes = set(chain.from_iterable(e.file_attributes for e in events))\n    return JrnlEvent(events[0].file_reference_number,\n                     events[0].parent_file_reference_number,\n                     events[0].file_name,\n                     events[0].timestamp,\n                     list(reasons), list(attributes))",
    "docstring": "Group multiple events into a single one."
  },
  {
    "code": "def get_keys(self, alias_name, key_format):\n        uri = self.URI + \"/keys/\" + alias_name + \"?format=\" + key_format\n        return self._client.get(uri)",
    "docstring": "Retrieves the contents of PKCS12 file in the format specified.\n        This PKCS12 formatted file contains both the certificate as well as the key file data.\n        Valid key formats are Base64 and PKCS12.\n\n        Args:\n            alias_name: Key pair associated with the RabbitMQ\n            key_format: Valid key formats are Base64 and PKCS12.\n        Returns:\n            dict: RabbitMQ certificate"
  },
  {
    "code": "def _get_service_port(self, instance):\n        host = instance.get('host', DEFAULT_HOST)\n        port = instance.get('port', DEFAULT_PORT)\n        try:\n            socket.getaddrinfo(host, port)\n        except socket.gaierror:\n            port = DEFAULT_PORT_NUM\n        return port",
    "docstring": "Get the ntp server port"
  },
  {
    "code": "def new(cls, shapes, start_x, start_y, x_scale, y_scale):\n        return cls(\n            shapes, int(round(start_x)), int(round(start_y)),\n            x_scale, y_scale\n        )",
    "docstring": "Return a new |FreeformBuilder| object.\n\n        The initial pen location is specified (in local coordinates) by\n        (*start_x*, *start_y*)."
  },
  {
    "code": "def total_rated_level(octave_frequencies):\n    sums = 0.0\n    for band in OCTAVE_BANDS.keys():\n        if band not in octave_frequencies:\n            continue\n        if octave_frequencies[band] is None:\n            continue\n        if octave_frequencies[band] == 0:\n            continue\n        sums += pow(10.0, ((float(octave_frequencies[band]) + OCTAVE_BANDS[band][1]) / 10.0))\n    level = 10.0 * math.log10(sums)\n    return level",
    "docstring": "Calculates the A-rated total sound pressure level\n    based on octave band frequencies"
  },
  {
    "code": "def inline_callbacks(original, debug=False):\n    f = eliot_friendly_generator_function(original)\n    if debug:\n        f.debug = True\n    return inlineCallbacks(f)",
    "docstring": "Decorate a function like ``inlineCallbacks`` would but in a more\n    Eliot-friendly way.  Use it just like ``inlineCallbacks`` but where you\n    want Eliot action contexts to Do The Right Thing inside the decorated\n    function."
  },
  {
    "code": "def trainObjects(objects, exp, numRepeatsPerObject, experimentIdOffset=0):\n  objectsToLearn = objects.provideObjectsToLearn()\n  objectTraversals = {}\n  for objectId in objectsToLearn:\n    objectTraversals[objectId + experimentIdOffset] = objects.randomTraversal(\n      objectsToLearn[objectId], numRepeatsPerObject)\n  exp.learnObjects(objectTraversals)",
    "docstring": "Train the network on all the objects by randomly traversing points on\n  each object.  We offset the id of each object to avoid confusion with\n  any sequences that might have been learned."
  },
  {
    "code": "def _parse_data(self, data, charset):\n        builder = TreeBuilder(numbermode=self._numbermode)\n        if isinstance(data,basestring):\n            xml.sax.parseString(data, builder)\n        else:\n            xml.sax.parse(data, builder)\n        return builder.root[self._root_element_name()]",
    "docstring": "Parse the xml data into dictionary."
  },
  {
    "code": "def process_rgb_bytes(bytes_in, width, height, quality=DEFAULT_JPEG_QUALITY):\n    if len(bytes_in) != width * height * 3:\n        raise ValueError(\"bytes_in length is not coherent with given width and height\")\n    bytes_out_p = ffi.new(\"char**\")\n    bytes_out_p_gc = ffi.gc(bytes_out_p, lib.guetzli_free_bytes)\n    length = lib.guetzli_process_rgb_bytes(\n            bytes_in,\n            width,\n            height,\n            bytes_out_p_gc,\n            quality\n            )\n    bytes_out = ffi.cast(\"char*\", bytes_out_p_gc[0])\n    return ffi.unpack(bytes_out, length)",
    "docstring": "Generates an optimized JPEG from RGB bytes.\n\n    :param bytes bytes_in: the input image's bytes\n    :param int width: the width of the input image\n    :param int height: the height of the input image\n    :param int quality: the output JPEG quality (default 95)\n\n    :returns: Optimized JPEG bytes\n    :rtype: bytes\n\n    :raises ValueError: the given width and height is not coherent with the\n                        ``bytes_in`` length.\n\n    .. code:: python\n\n        import pyguetzli\n\n        # 2x2px RGB image\n        #                |    red    |   green   |\n        image_pixels  = b\"\\\\xFF\\\\x00\\\\x00\\\\x00\\\\xFF\\\\x00\"\n        image_pixels += b\"\\\\x00\\\\x00\\\\xFF\\\\xFF\\\\xFF\\\\xFF\"\n        #                |   blue    |   white   |\n\n        optimized_jpeg = pyguetzli.process_rgb_bytes(image_pixels, 2, 2)"
  },
  {
    "code": "def num_tasks(self, work_spec_name):\n        return self.num_finished(work_spec_name) + \\\n               self.num_failed(work_spec_name) + \\\n               self.registry.len(WORK_UNITS_ + work_spec_name)",
    "docstring": "Get the total number of work units for some work spec."
  },
  {
    "code": "def nPr(n, r):\n    f = math.factorial\n    return int(f(n) / f(n-r))",
    "docstring": "Calculates nPr.\n\n    Args:\n        n (int): total number of items.\n        r (int): items to permute\n\n    Returns:\n        nPr."
  },
  {
    "code": "def parents(self, resources):\n        if self.docname == 'index':\n            return []\n        parents = []\n        parent = resources.get(self.parent)\n        while parent is not None:\n            parents.append(parent)\n            parent = resources.get(parent.parent)\n        return parents",
    "docstring": "Split the path in name and get parents"
  },
  {
    "code": "def revoke_session():\n    form = RevokeForm(request.form)\n    if not form.validate_on_submit():\n        abort(403)\n    sid_s = form.data['sid_s']\n    if SessionActivity.query.filter_by(\n            user_id=current_user.get_id(), sid_s=sid_s).count() == 1:\n        delete_session(sid_s=sid_s)\n        db.session.commit()\n        if not SessionActivity.is_current(sid_s=sid_s):\n            flash('Session {0} successfully removed.'.format(sid_s), 'success')\n    else:\n        flash('Unable to remove the session {0}.'.format(sid_s), 'error')\n    return redirect(url_for('invenio_accounts.security'))",
    "docstring": "Revoke a session."
  },
  {
    "code": "def copytree(source_directory, destination_directory, ignore=None):\n    if os.path.isdir(source_directory):\n        if not os.path.isdir(destination_directory):\n            os.makedirs(destination_directory)\n        files = os.listdir(source_directory)\n        if ignore is not None:\n            ignored = ignore(source_directory, files)\n        else:\n            ignored = set()\n        for f in files:\n            if f not in ignored:\n                copytree(\n                    os.path.join(source_directory, f),\n                    os.path.join(destination_directory, f),\n                    ignore\n                )\n    else:\n        shutil.copyfile(source_directory, destination_directory)",
    "docstring": "Recursively copy the contents of a source directory\n    into a destination directory.\n    Both directories must exist.\n\n    This function does not copy the root directory ``source_directory``\n    into ``destination_directory``.\n\n    Since ``shutil.copytree(src, dst)`` requires ``dst`` not to exist,\n    we cannot use for our purposes.\n\n    Code adapted from http://stackoverflow.com/a/12686557\n\n    :param string source_directory: the source directory, already existing\n    :param string destination_directory: the destination directory, already existing"
  },
  {
    "code": "def clear_measurements(self):\n        keys = list(self.measurements.keys())\n        for key in keys:\n            del(self.measurements[key])\n        self.meas_counter = -1",
    "docstring": "Remove all measurements from self.measurements. Reset the\n        measurement counter. All ID are invalidated."
  },
  {
    "code": "def add_url (self, url, line=0, column=0, page=0, name=u\"\", base=None):\n        if base:\n            base_ref = urlutil.url_norm(base)[0]\n        else:\n            base_ref = None\n        url_data = get_url_from(url, self.recursion_level+1, self.aggregate,\n            parent_url=self.url, base_ref=base_ref, line=line, column=column,\n            page=page, name=name, parent_content_type=self.content_type)\n        self.aggregate.urlqueue.put(url_data)",
    "docstring": "Add new URL to queue."
  },
  {
    "code": "def check_arrays_survival(X, y, **kwargs):\n    event, time = check_y_survival(y)\n    kwargs.setdefault(\"dtype\", numpy.float64)\n    X = check_array(X, ensure_min_samples=2, **kwargs)\n    check_consistent_length(X, event, time)\n    return X, event, time",
    "docstring": "Check that all arrays have consistent first dimensions.\n\n    Parameters\n    ----------\n    X : array-like\n        Data matrix containing feature vectors.\n\n    y : structured array with two fields\n        A structured array containing the binary event indicator\n        as first field, and time of event or time of censoring as\n        second field.\n\n    kwargs : dict\n        Additional arguments passed to :func:`sklearn.utils.check_array`.\n\n    Returns\n    -------\n    X : array, shape=[n_samples, n_features]\n        Feature vectors.\n\n    event : array, shape=[n_samples,], dtype=bool\n        Binary event indicator.\n\n    time : array, shape=[n_samples,], dtype=float\n        Time of event or censoring."
  },
  {
    "code": "def get_dataset(self, dataset_ref, retry=DEFAULT_RETRY):\n        if isinstance(dataset_ref, str):\n            dataset_ref = DatasetReference.from_string(\n                dataset_ref, default_project=self.project\n            )\n        api_response = self._call_api(retry, method=\"GET\", path=dataset_ref.path)\n        return Dataset.from_api_repr(api_response)",
    "docstring": "Fetch the dataset referenced by ``dataset_ref``\n\n        Args:\n            dataset_ref (Union[ \\\n                :class:`~google.cloud.bigquery.dataset.DatasetReference`, \\\n                str, \\\n            ]):\n                A reference to the dataset to fetch from the BigQuery API.\n                If a string is passed in, this method attempts to create a\n                dataset reference from a string using\n                :func:`~google.cloud.bigquery.dataset.DatasetReference.from_string`.\n            retry (:class:`google.api_core.retry.Retry`):\n                (Optional) How to retry the RPC.\n\n        Returns:\n            google.cloud.bigquery.dataset.Dataset:\n                A ``Dataset`` instance."
  },
  {
    "code": "def _set_scripts(self, host_metadata, scripts):\n        scripts_key = 'deploy-scripts'\n        if 'ovirt-scritps' in host_metadata:\n            scripts_key = 'ovirt-scripts'\n        host_metadata[scripts_key] = scripts\n        return host_metadata",
    "docstring": "Temporary method to set the host scripts\n\n        TODO:\n            remove once the \"ovirt-scripts\" option gets deprecated\n\n        Args:\n            host_metadata(dict): host metadata to set scripts in\n\n        Returns:\n            dict: the updated metadata"
  },
  {
    "code": "def get_quotes(self):\n        mask = \"mask[order[id,items[id,package[id,keyName]]]]\"\n        quotes = self.client['Account'].getActiveQuotes(mask=mask)\n        return quotes",
    "docstring": "Retrieve a list of active quotes.\n\n        :returns: a list of SoftLayer_Billing_Order_Quote"
  },
  {
    "code": "def render_latex_text(input_text, nest_in_doc=False, preamb_extra=None,\n                      appname='utool', verbose=None):\n    import utool as ut\n    if verbose is None:\n        verbose = ut.VERBOSE\n    dpath = ut.ensure_app_resource_dir(appname, 'latex_tmp')\n    fname = 'temp_render_latex'\n    pdf_fpath = ut.compile_latex_text(\n        input_text, dpath=dpath, fname=fname, preamb_extra=preamb_extra,\n        verbose=verbose)\n    ut.startfile(pdf_fpath)\n    return pdf_fpath",
    "docstring": "compiles latex and shows the result"
  },
  {
    "code": "def sendto(self, data, addr, flags=0):\n        return self.llc.sendto(self._tco, data, addr, flags)",
    "docstring": "Send data to the socket. The socket should not be connected\n        to a remote socket, since the destination socket is specified\n        by addr. Returns a boolean value that indicates success\n        or failure. Failure to send is generally an indication that\n        the socket was closed."
  },
  {
    "code": "def get_grade_entries_for_gradebook_column_on_date(self, gradebook_column_id, from_, to):\n        grade_entry_list = []\n        for grade_entry in self.get_grade_entries_for_gradebook_column(gradebook_column_id):\n            if overlap(from_, to, grade_entry.start_date, grade_entry.end_date):\n                grade_entry_list.append(grade_entry)\n        return objects.GradeEntryList(grade_entry_list, runtime=self._runtime)",
    "docstring": "Gets a ``GradeEntryList`` for the given gradebook column and effective during the entire given date range inclusive but not confined to the date range.\n\n        arg:    gradebook_column_id (osid.id.Id): a gradebook column\n                ``Id``\n        arg:    from (osid.calendaring.DateTime): start of date range\n        arg:    to (osid.calendaring.DateTime): end of date range\n        return: (osid.grading.GradeEntryList) - the returned\n                ``GradeEntry`` list\n        raise:  InvalidArgument - ``from`` is greater than ``to``\n        raise:  NullArgument - ``gradebook_column_id, from, or to`` is\n                ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def set_jinja2_silent_none(config):\n    config.commit()\n    jinja2_env = config.get_jinja2_environment()\n    jinja2_env.finalize = _silent_none",
    "docstring": "if variable is None print '' instead of 'None'"
  },
  {
    "code": "def quadrant(xcoord, ycoord):\n    xneg = bool(xcoord < 0)\n    yneg = bool(ycoord < 0)\n    if xneg is True:\n        if yneg is False:\n            return 2\n        return 3\n    if yneg is False:\n        return 1\n    return 4",
    "docstring": "Find the quadrant a pair of coordinates are located in\n\n    :type xcoord: integer\n    :param xcoord: The x coordinate to find the quadrant for\n\n    :type ycoord: integer\n    :param ycoord: The y coordinate to find the quadrant for"
  },
  {
    "code": "def _mysql_aes_key(key):\n    final_key = bytearray(16)\n    for i, c in enumerate(key):\n        final_key[i % 16] ^= key[i] if PY3 else ord(key[i])\n    return bytes(final_key)",
    "docstring": "Format key."
  },
  {
    "code": "def Parse(self, rdf_data):\n    if not isinstance(rdf_data, (list, set)):\n      raise ProcessingError(\"Bad host data format: %s\" % type(rdf_data))\n    if self.baseline:\n      comparison = self.baseliner.Parse(rdf_data)\n    else:\n      comparison = rdf_data\n    found = self.handler.Parse(comparison)\n    results = self.hint.Render(found)\n    return self.matcher.Detect(comparison, results)",
    "docstring": "Process rdf data through filters. Test if results match expectations.\n\n    Processing of rdf data is staged by a filter handler, which manages the\n    processing of host data. The output of the filters are compared against\n    expected results.\n\n    Args:\n      rdf_data: An list containing 0 or more rdf values.\n\n    Returns:\n      An anomaly if data didn't match expectations.\n\n    Raises:\n      ProcessingError: If rdf_data is not a handled type."
  },
  {
    "code": "def auto_name_prefix(self):\n        native_system = std_platform.system()\n        native_machine = self.CPU_ALIASES.get(std_platform.machine(), std_platform.machine())\n        if native_system == self.system and native_machine == self.machine:\n            return ''\n        platform = {\n            'linux': 'linux32',\n            'android-api-16': 'android-arm',\n            'android-aarch64': 'android-arm64',\n        }.get(self.gecko_platform, self.gecko_platform)\n        return platform + '-'",
    "docstring": "Generate platform prefix for cross-platform downloads."
  },
  {
    "code": "def force_list(value, min=None, max=None):\n    if not isinstance(value, (list, tuple)):\n        value = [value]\n    return is_list(value, min, max)",
    "docstring": "Check that a value is a list, coercing strings into\n    a list with one member. Useful where users forget the\n    trailing comma that turns a single value into a list.\n\n    You can optionally specify the minimum and maximum number of members.\n    A minumum of greater than one will fail if the user only supplies a\n    string.\n\n    >>> vtor = Validator()\n    >>> vtor.check('force_list', ())\n    []\n    >>> vtor.check('force_list', [])\n    []\n    >>> vtor.check('force_list', 'hello')\n    ['hello']"
  },
  {
    "code": "def _suffix(self):\n        _output_formats={'GCG':'.msf',\n                        'GDE':'.gde',\n                        'PHYLIP':'.phy',\n                        'PIR':'.pir',\n                        'NEXUS':'.nxs'}\n        if self.Parameters['-output'].isOn():\n            return _output_formats[self.Parameters['-output'].Value]\n        else:\n            return '.aln'",
    "docstring": "Return appropriate suffix for alignment file"
  },
  {
    "code": "def critical(self, msg, *args, **kwargs) -> Task:\n        return self._make_log_task(logging.CRITICAL, msg, args, **kwargs)",
    "docstring": "Log msg with severity 'CRITICAL'.\n\n        To pass exception information, use the keyword argument exc_info with\n        a true value, e.g.\n\n        await logger.critical(\"Houston, we have a major disaster\", exc_info=1)"
  },
  {
    "code": "def read(*paths):\n    with open(os.path.join(os.path.dirname(__file__), *paths)) as fp:\n        return fp.read()",
    "docstring": "read and return txt content of file"
  },
  {
    "code": "def _load_records(self, record_type_idstrs):\n        for record_type_idstr in record_type_idstrs:\n            try:\n                self._init_record(record_type_idstr)\n            except (ImportError, KeyError):\n                pass",
    "docstring": "Loads query records"
  },
  {
    "code": "def get_sigma(x, min_limit=-np.inf, max_limit=np.inf):\n    z = np.append(x, [min_limit, max_limit])\n    sigma = np.ones(x.shape)\n    for i in range(x.size):\n        xleft = z[np.argmin([(x[i] - k) if k < x[i] else np.inf for k in z])]\n        xright = z[np.argmin([(k - x[i]) if k > x[i] else np.inf for k in z])]\n        sigma[i] = max(x[i] - xleft, xright - x[i])\n        if sigma[i] == np.inf:\n            sigma[i] = min(x[i] - xleft, xright - x[i])\n        if (sigma[i] == -np.inf):\n            sigma[i] = 1.0\n    return sigma",
    "docstring": "Compute the standard deviations around the points for a 1D GMM.\n\n    We take the distance from the nearest left and right neighbors\n    for each point, then use the max as the estimate of standard\n    deviation for the gaussian mixture around that point.\n\n    Arguments\n    ---------\n    x : 1D array\n        Set of points to create the GMM\n\n    min_limit : Optional[float], default : -inf\n        Minimum limit for the distribution\n\n    max_limit : Optional[float], default : inf\n        maximum limit for the distribution\n\n    Returns\n    -------\n    1D array\n        Array of standard deviations"
  },
  {
    "code": "def discretize(self, method, *args, **kwargs):\n        return method(self, *args, **kwargs).get_discrete_values()",
    "docstring": "Discretizes the continuous distribution into discrete\n        probability masses using various methods.\n\n        Parameters\n        ----------\n        method : A Discretizer Class from pgmpy.discretize\n\n        *args, **kwargs:\n            The parameters to be given to the Discretizer Class.\n\n        Returns\n        -------\n        An n-D array or a DiscreteFactor object according to the discretiztion\n        method used.\n\n        Examples\n        --------\n        >>> import numpy as np\n        >>> from scipy.special import beta\n        >>> from pgmpy.factors.continuous import ContinuousFactor\n        >>> from pgmpy.factors.continuous import RoundingDiscretizer\n        >>> def dirichlet_pdf(x, y):\n        ...     return (np.power(x, 1) * np.power(y, 2)) / beta(x, y)\n        >>> dirichlet_factor = ContinuousFactor(['x', 'y'], dirichlet_pdf)\n        >>> dirichlet_factor.discretize(RoundingDiscretizer, low=1, high=2, cardinality=5)\n        # TODO: finish this"
  },
  {
    "code": "def machine(self):\n        if not self._ptr:\n            raise BfdException(\"BFD not initialized\")\n        return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.FLAVOUR)",
    "docstring": "Return the flavour attribute of the BFD file being processed."
  },
  {
    "code": "def flatFieldFromFunction(self):\r\n        fitimg, mask = self._prepare()\r\n        mask = ~mask\r\n        s0, s1 = fitimg.shape\r\n        guess = (s1 * 0.7, 0, 1, s0 / 2, s1 / 2)\r\n        fn = lambda xy, f, alpha, fx, cx, cy: vignetting((xy[0] * fx, xy[1]), f, alpha,\r\n                                                         cx=cx, cy=cy)\r\n        flatfield = fit2dArrayToFn(fitimg, fn, mask=mask,\r\n                                   guess=guess, output_shape=self._orig_shape)[0]\r\n        return flatfield, self.bglevel / self._n, fitimg, mask",
    "docstring": "calculate flatField from fitting vignetting function to averaged fit-image\r\n        returns flatField, average background level, fitted image, valid indices mask"
  },
  {
    "code": "def get_personal_info(user):\n    num_phones = len(user.phones.all() or [])\n    num_emails = len(user.emails.all() or [])\n    num_websites = len(user.websites.all() or [])\n    personal_info = {}\n    for i in range(num_phones):\n        personal_info[\"phone_{}\".format(i)] = user.phones.all()[i]\n    for i in range(num_emails):\n        personal_info[\"email_{}\".format(i)] = user.emails.all()[i]\n    for i in range(num_websites):\n        personal_info[\"website_{}\".format(i)] = user.websites.all()[i]\n    num_fields = {\"phones\": num_phones, \"emails\": num_emails, \"websites\": num_websites}\n    return personal_info, num_fields",
    "docstring": "Get a user's personal info attributes to pass as an initial value to a\n    PersonalInformationForm."
  },
  {
    "code": "def _generate_edges(self, edge_prob):\n        self.E, self.parent = [], {}\n        for i in range(self.m):\n            if random() < edge_prob and i > 0:\n                p_i = choice(i)\n                self.E.append((p_i, i))\n                self.parent[i] = p_i",
    "docstring": "Generate a random tree-structured dependency graph based on a\n        specified edge probability.\n\n        Also create helper data struct mapping child -> parent."
  },
  {
    "code": "def accept(self):\n        if self._can_settle_message():\n            self._response = errors.MessageAccepted()\n            self._settler(self._response)\n            self.state = constants.MessageState.ReceivedSettled\n            return True\n        return False",
    "docstring": "Send a response disposition to the service to indicate that\n        a received message has been accepted. If the client is running in PeekLock\n        mode, the service will wait on this disposition. Otherwise it will\n        be ignored. Returns `True` is message was accepted, or `False` if the message\n        was already settled.\n\n        :rtype: bool\n        :raises: TypeError if the message is being sent rather than received."
  },
  {
    "code": "def get_heroku_connect_models():\n    from django.apps import apps\n    apps.check_models_ready()\n    from heroku_connect.db.models import HerokuConnectModel\n    return (\n        model\n        for models in apps.all_models.values()\n        for model in models.values()\n        if issubclass(model, HerokuConnectModel)\n        and not model._meta.managed\n    )",
    "docstring": "Return all registered Heroku Connect Models.\n\n    Returns:\n        (Iterator):\n            All registered models that are subclasses of `.HerokuConnectModel`.\n            Abstract models are excluded, since they are not registered."
  },
  {
    "code": "def get_token(wallet: 'Wallet', token_str: str) -> 'NEP5Token.NEP5Token':\n    if token_str.startswith('0x'):\n        token_str = token_str[2:]\n    token = None\n    for t in wallet.GetTokens().values():\n        if token_str in [t.symbol, t.ScriptHash.ToString()]:\n            token = t\n            break\n    if not isinstance(token, NEP5Token.NEP5Token):\n        raise ValueError(\"The given token argument does not represent a known NEP5 token\")\n    return token",
    "docstring": "Try to get a NEP-5 token based on the symbol or script_hash\n\n    Args:\n        wallet: wallet instance\n        token_str: symbol or script_hash (accepts script hash with or without 0x prefix)\n    Raises:\n        ValueError: if token is not found\n\n    Returns:\n        NEP5Token instance if found."
  },
  {
    "code": "def percentile(sorted_list, percent, key=lambda x: x):\n    if not sorted_list:\n        return None\n    if percent == 1:\n        return float(sorted_list[-1])\n    if percent == 0:\n        return float(sorted_list[0])\n    n = len(sorted_list)\n    i = percent * n\n    if ceil(i) == i:\n        i = int(i)\n        return (sorted_list[i-1] + sorted_list[i]) / 2\n    return float(sorted_list[ceil(i)-1])",
    "docstring": "Find the percentile of a sorted list of values.\n\n    Arguments\n    ---------\n    sorted_list : list\n        A sorted (ascending) list of values.\n    percent : float\n        A float value from 0.0 to 1.0.\n    key : function, optional\n        An optional function to compute a value from each element of N.\n\n    Returns\n    -------\n    float\n        The desired percentile of the value list.\n\n    Examples\n    --------\n    >>> sorted_list = [4,6,8,9,11]\n    >>> percentile(sorted_list, 0.4)\n    7.0\n    >>> percentile(sorted_list, 0.44)\n    8.0\n    >>> percentile(sorted_list, 0.6)\n    8.5\n    >>> percentile(sorted_list, 0.99)\n    11.0\n    >>> percentile(sorted_list, 1)\n    11.0\n    >>> percentile(sorted_list, 0)\n    4.0"
  },
  {
    "code": "def get_template(self, context, **kwargs):\n        if 'template' in kwargs['params']:\n            self.template = kwargs['params']['template']\n        return super(GoscaleTemplateInclusionTag, self).get_template(context, **kwargs)",
    "docstring": "Returns the template to be used for the current context and arguments."
  },
  {
    "code": "def rename(self, from_, to):\n        blueprint = self._create_blueprint(from_)\n        blueprint.rename(to)\n        self._build(blueprint)",
    "docstring": "Rename a table on the schema."
  },
  {
    "code": "def total_num_lines(self):\n        return sum([len(summary.measured_lines) for summary\n                    in self._diff_violations().values()])",
    "docstring": "Return the total number of lines in the diff for\n        which we have coverage info."
  },
  {
    "code": "def sense_ttb(self, target):\n        info = \"{device} does not support sense for Type B Target\"\n        raise nfc.clf.UnsupportedTargetError(info.format(device=self))",
    "docstring": "Sense for a Type B Target is not supported."
  },
  {
    "code": "def get_platform_by_name(self, name, for_target=None):\n    if not name:\n      return self.default_platform\n    if name not in self.platforms_by_name:\n      raise self.UndefinedJvmPlatform(for_target, name, self.platforms_by_name)\n    return self.platforms_by_name[name]",
    "docstring": "Finds the platform with the given name.\n\n    If the name is empty or None, returns the default platform.\n    If not platform with the given name is defined, raises an error.\n    :param str name: name of the platform.\n    :param JvmTarget for_target: optionally specified target we're looking up the platform for.\n      Only used in error message generation.\n    :return: The jvm platform object.\n    :rtype: JvmPlatformSettings"
  },
  {
    "code": "def visit_nonlocal(self, node, parent):\n        return nodes.Nonlocal(\n            node.names,\n            getattr(node, \"lineno\", None),\n            getattr(node, \"col_offset\", None),\n            parent,\n        )",
    "docstring": "visit a Nonlocal node and return a new instance of it"
  },
  {
    "code": "def profile(schemaname='sensordata', profiletype='pjs'):\n    db_log(\"Profiling \", schemaname)\n    schema = schemastore[schemaname]['schema']\n    db_log(\"Schema: \", schema, lvl=debug)\n    testclass = None\n    if profiletype == 'warmongo':\n        db_log(\"Running Warmongo benchmark\")\n        testclass = warmongo.model_factory(schema)\n    elif profiletype == 'pjs':\n        db_log(\"Running PJS benchmark\")\n        try:\n            import python_jsonschema_objects as pjs\n        except ImportError:\n            db_log(\"PJS benchmark selected but not available. Install \"\n                   \"python_jsonschema_objects (PJS)\")\n            return\n        db_log()\n        builder = pjs.ObjectBuilder(schema)\n        ns = builder.build_classes()\n        pprint(ns)\n        testclass = ns[schemaname]\n        db_log(\"ns: \", ns, lvl=warn)\n    if testclass is not None:\n        db_log(\"Instantiating elements...\")\n        for i in range(100):\n            testclass()\n    else:\n        db_log(\"No Profiletype available!\")\n    db_log(\"Profiling done\")",
    "docstring": "Profiles object model handling with a very simple benchmarking test"
  },
  {
    "code": "def _get_api_dependencies_of(name, version='', force=False):\n    m, d = _get_metadap_dap(name, version=version)\n    if not force and not _is_supported_here(d):\n        raise DapiLocalError(\n            '{0} is not supported on this platform (use --force to suppress this check).'.\n            format(name))\n    return d.get('dependencies', [])",
    "docstring": "Returns list of first level dependencies of the given dap from Dapi"
  },
  {
    "code": "def array(self) -> numpy.ndarray:\n        array = numpy.full(self.shape, fillvalue, dtype=float)\n        for idx, (descr, subarray) in enumerate(self.arrays.items()):\n            sequence = self.sequences[descr]\n            array[self.get_slices(idx, sequence.shape)] = subarray\n        return array",
    "docstring": "The series data of all logged |IOSequence| objects contained\n        in one single |numpy.ndarray|.\n\n        The documentation on |NetCDFVariableDeep.shape| explains how\n        |NetCDFVariableDeep.array| is structured.  The first example\n        confirms that, for the default configuration, the first axis\n        definces the location, while the second one defines time:\n\n        >>> from hydpy.core.examples import prepare_io_example_1\n        >>> nodes, elements = prepare_io_example_1()\n        >>> from hydpy.core.netcdftools import NetCDFVariableDeep\n        >>> ncvar = NetCDFVariableDeep('input_nied', isolate=False, timeaxis=1)\n        >>> for element in elements:\n        ...     nied1 = element.model.sequences.inputs.nied\n        ...     ncvar.log(nied1, nied1.series)\n        >>> ncvar.array\n        array([[  0.,   1.,   2.,   3.],\n               [  4.,   5.,   6.,   7.],\n               [  8.,   9.,  10.,  11.]])\n\n        For higher dimensional sequences, |NetCDFVariableDeep.array|\n        can contain missing values.  Such missing values show up for\n        some fiels of the second example element, which defines only\n        two hydrological response units instead of three:\n\n        >>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=False, timeaxis=1)\n        >>> for element in elements:\n        ...     nkor1 = element.model.sequences.fluxes.nkor\n        ...     ncvar.log(nkor1, nkor1.series)\n        >>> ncvar.array[1]\n        array([[ 16.,  17.,  nan],\n               [ 18.,  19.,  nan],\n               [ 20.,  21.,  nan],\n               [ 22.,  23.,  nan]])\n\n        When using the first axis for time (`timeaxis=0`) the same data\n        can be accessed with slightly different indexing:\n\n        >>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=False, timeaxis=0)\n        >>> for element in elements:\n        ...     nkor1 = element.model.sequences.fluxes.nkor\n        ...     ncvar.log(nkor1, nkor1.series)\n        >>> ncvar.array[:, 1]\n        array([[ 16.,  17.,  nan],\n               [ 18.,  19.,  nan],\n               [ 20.,  21.,  nan],\n               [ 22.,  23.,  nan]])"
  },
  {
    "code": "def dbmax50years(self, value=None):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type float '\n                                 'for field `dbmax50years`'.format(value))\n        self._dbmax50years = value",
    "docstring": "Corresponds to IDD Field `dbmax50years`\n        50-year return period values for maximum extreme dry-bulb temperature\n\n        Args:\n            value (float): value for IDD Field `dbmax50years`\n                Unit: C\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def _escape_string(text, _map={}):\n    if isinstance(text, str):\n        text = text.encode('ascii')\n    assert isinstance(text, (bytes, bytearray))\n    if not _map:\n        for ch in range(256):\n            if ch in _VALID_CHARS:\n                _map[ch] = chr(ch)\n            else:\n                _map[ch] = '\\\\%02x' % ch\n            if six.PY2:\n                _map[chr(ch)] = _map[ch]\n    buf = [_map[ch] for ch in text]\n    return ''.join(buf)",
    "docstring": "Escape the given bytestring for safe use as a LLVM array constant."
  },
  {
    "code": "def load_lst(self):\n        with open(self._lst_file, 'r') as fd:\n            lines = fd.readlines()\n        idx, uname, fname = list(), list(), list()\n        for line in lines:\n            values = line.split(',')\n            values = [x.strip() for x in values]\n            idx.append(int(values[0]))\n            uname.append(values[1])\n            fname.append(values[2])\n        self._idx = idx\n        self._fname = fname\n        self._uname = uname",
    "docstring": "Load the lst file into internal data structures"
  },
  {
    "code": "async def monitor_start(self, monitor):\n        cfg = self.cfg\n        if (not platform.has_multiprocessing_socket or\n                cfg.concurrency == 'thread'):\n            cfg.set('workers', 0)\n        servers = await self.binds(monitor)\n        if not servers:\n            raise ImproperlyConfigured('Could not open a socket. '\n                                       'No address to bind to')\n        addresses = []\n        for server in servers.values():\n            addresses.extend(server.addresses)\n        self.cfg.addresses = addresses",
    "docstring": "Create the socket listening to the ``bind`` address.\n\n        If the platform does not support multiprocessing sockets set the\n        number of workers to 0."
  },
  {
    "code": "def insert(self, idx, w, comment=''):\n        if idx >= self.count():\n            self.add(w, comment)\n            return\n        if idx < 0:\n            return\n        w = copy.copy(w)\n        if comment:\n            w.comment = comment\n        w.seq = idx\n        self.wpoints.insert(idx, w)\n        self.last_change = time.time()\n        self.reindex()",
    "docstring": "insert a waypoint"
  },
  {
    "code": "def validate_checksum( filename, md5sum ):\n    filename = match_filename( filename )\n    md5_hash = file_md5( filename=filename )\n    if md5_hash != md5sum:\n        raise ValueError('md5 checksums are inconsistent: {}'.format( filename ))",
    "docstring": "Compares the md5 checksum of a file with an expected value.\n    If the calculated and expected checksum values are not equal, \n    ValueError is raised.\n    If the filename `foo` is not found, will try to read a gzipped file named\n    `foo.gz`. In this case, the checksum is calculated for the unzipped file.\n\n    Args:\n        filename (str): Path for the file to be checksummed.\n        md5sum (str):  The expected hex checksum.\n\n    Returns:\n        None"
  },
  {
    "code": "def _killall(self, force=False):\n        for_termination = []\n        for n, p in iteritems(self._processes):\n            if 'returncode' not in p:\n                for_termination.append(n)\n        for n in for_termination:\n            p = self._processes[n]\n            signame = 'SIGKILL' if force else 'SIGTERM'\n            self._system_print(\"sending %s to %s (pid %s)\\n\" %\n                               (signame, n, p['pid']))\n            if force:\n                self._env.kill(p['pid'])\n            else:\n                self._env.terminate(p['pid'])",
    "docstring": "Kill all remaining processes, forcefully if requested."
  },
  {
    "code": "def CharacterData(self, data):\n        if data.strip():\n            data = data.encode()\n            if not self.data:\n                self.data = data\n            else:\n                self.data += data",
    "docstring": "Expat character data event handler"
  },
  {
    "code": "def time_to_number(self, time):\n        if not isinstance(time, datetime.time):\n            raise TypeError(time)\n        return ((time.second / 60.0 + time.minute) / 60.0 + time.hour) / 24.0",
    "docstring": "Converts a time instance to a corresponding float value."
  },
  {
    "code": "def _retry_get(self, uri):\n        for i in six.moves.range(DEFAULT_RETRY):\n            resp, body = self.api.method_get(uri)\n            if body:\n                return resp, body\n        raise exc.ServiceResponseFailure(\"The Cloud DNS service failed to \"\n                \"respond to the request.\")",
    "docstring": "Handles GET calls to the Cloud DNS API in order to retry on empty\n        body responses."
  },
  {
    "code": "def get_all_info(pdb_id):\n    out = to_dict( get_info(pdb_id) )['molDescription']['structureId']\n    out = remove_at_sign(out)\n    return out",
    "docstring": "A wrapper for get_info that cleans up the output slighly\n\n    Parameters\n    ----------\n\n    pdb_id : string\n        A 4 character string giving a pdb entry of interest\n\n    Returns\n    -------\n\n    out : dict\n        A dictionary containing all the information stored in the entry\n\n    Examples\n    --------\n\n    >>> all_info = get_all_info('4lza')\n    >>> print(all_info)\n    {'polymer': {'macroMolecule': {'@name': 'Adenine phosphoribosyltransferase', '\n    accession': {'@id': 'B0K969'}}, '@entityNr': '1', '@type': 'protein',\n    'polymerDescription': {'@description': 'Adenine phosphoribosyltransferase'},\n    'synonym': {'@name': 'APRT'}, '@length': '195', 'enzClass': {'@ec': '2.4.2.7'},\n    'chain': [{'@id': 'A'}, {'@id': 'B'}],\n    'Taxonomy': {'@name': 'Thermoanaerobacter pseudethanolicus ATCC 33223',\n    '@id': '340099'}, '@weight': '22023.9'}, 'id': '4LZA'}\n\n    >>> results = get_all_info('2F5N')\n    >>> first_polymer = results['polymer'][0]\n    >>> first_polymer['polymerDescription']\n    {'@description': \"5'-D(*AP*GP*GP*TP*AP*GP*AP*CP*CP*TP*GP*GP*AP*CP*GP*C)-3'\"}"
  },
  {
    "code": "def url(viewname, *args, **kwargs):\n    return reverse(viewname, args=args, kwargs=kwargs)",
    "docstring": "Helper for Django's ``reverse`` in templates."
  },
  {
    "code": "def get_launch_config(self, scaling_group):\n        key_map = {\n            \"OS-DCF:diskConfig\": \"disk_config\",\n            \"flavorRef\": \"flavor\",\n            \"imageRef\": \"image\",\n        }\n        uri = \"/%s/%s/launch\" % (self.uri_base, utils.get_id(scaling_group))\n        resp, resp_body = self.api.method_get(uri)\n        ret = {}\n        data = resp_body.get(\"launchConfiguration\")\n        ret[\"type\"] = data.get(\"type\")\n        args = data.get(\"args\", {})\n        ret[\"load_balancers\"] = args.get(\"loadBalancers\")\n        for key, value in args.get(\"server\", {}).items():\n            norm_key = key_map.get(key, key)\n            ret[norm_key] = value\n        return ret",
    "docstring": "Returns the launch configuration for the specified scaling group."
  },
  {
    "code": "def run(args):\n    raw_arguments = get_arguments(args[1:])\n    process_arguments(raw_arguments)\n    walk.run()\n    return True",
    "docstring": "Process command line arguments and walk inputs."
  },
  {
    "code": "def get_description(self):\n        if self._description:\n            return self._description\n        try:\n            trailerURL= \"http://trailers.apple.com%s\" % self.baseURL\n            response = urllib.request.urlopen(trailerURL)\n            Reader = codecs.getreader(\"utf-8\")\n            responseReader = Reader(response)\n            trailerHTML = responseReader.read()\n            description = re.search('<meta *name=\"Description\" *content=\"(.*?)\" *[/]*>'\n                                    ,trailerHTML)\n            if description:\n                self._description = description.group(1)\n            else:\n                self._description = \"None\"\n        except:\n            self._description = \"Error\"\n        return self._description",
    "docstring": "Returns description text as provided by the studio"
  },
  {
    "code": "def _evaluate_tempyREPR(self, child, repr_cls):\n        score = 0\n        if repr_cls.__name__ == self.__class__.__name__:\n            score += 1\n        elif repr_cls.__name__ == self.root.__class__.__name__:\n            score += 1\n        for parent_cls in _filter_classes(repr_cls.__mro__[1:], TempyPlace):\n            for scorer in (\n                method for method in dir(parent_cls) if method.startswith(\"_reprscore\")\n            ):\n                score += getattr(parent_cls, scorer, lambda *args: 0)(\n                    parent_cls, self, child\n                )\n        return score",
    "docstring": "Assign a score ito a TempyRepr class.\n        The scores depends on the current scope and position of the object in which the TempyREPR is found."
  },
  {
    "code": "def _eb_env_tags(envs, session_factory, retry):\n    client = local_session(session_factory).client('elasticbeanstalk')\n    def process_tags(eb_env):\n        try:\n            eb_env['Tags'] = retry(\n                client.list_tags_for_resource,\n                ResourceArn=eb_env['EnvironmentArn'])['ResourceTags']\n        except client.exceptions.ResourceNotFoundException:\n            return\n        return eb_env\n    return list(map(process_tags, envs))",
    "docstring": "Augment ElasticBeanstalk Environments with their tags."
  },
  {
    "code": "def _TryPrintAsAnyMessage(self, message):\n    packed_message = _BuildMessageFromTypeName(message.TypeName(),\n                                               self.descriptor_pool)\n    if packed_message:\n      packed_message.MergeFromString(message.value)\n      self.out.write('%s[%s]' % (self.indent * ' ', message.type_url))\n      self._PrintMessageFieldValue(packed_message)\n      self.out.write(' ' if self.as_one_line else '\\n')\n      return True\n    else:\n      return False",
    "docstring": "Serializes if message is a google.protobuf.Any field."
  },
  {
    "code": "def run(command, show=True, *args, **kwargs):\n    if show:\n        print_command(command)\n    with hide(\"running\"):\n        return _run(command, *args, **kwargs)",
    "docstring": "Runs a shell comand on the remote server."
  },
  {
    "code": "def push_to_server(self, data):\n        output = add_profile(self.customer.pk, data, data)\n        output['response'].raise_if_error()\n        self.profile_id = output['profile_id']\n        self.payment_profile_ids = output['payment_profile_ids']",
    "docstring": "Create customer profile for given ``customer`` on Authorize.NET"
  },
  {
    "code": "def _adjust_scrollbar(self, f):\n        hb = self.horizontalScrollBar()\n        hb.setValue(int(f * hb.value() + ((f - 1) * hb.pageStep()/2)))\n        vb = self.verticalScrollBar()\n        vb.setValue(int(f * vb.value() + ((f - 1) * vb.pageStep()/2)))",
    "docstring": "Adjust the scrollbar position to take into account the zooming of\n        the figure."
  },
  {
    "code": "def _difference(self, original_keys, updated_keys, name, item_index):\n        original_keys = set(original_keys)\n        updated_keys = set(updated_keys)\n        added_keys = updated_keys.difference(original_keys)\n        removed_keys = set()\n        if name is None:\n            removed_keys = original_keys.difference(updated_keys)\n        elif name not in updated_keys and name in original_keys:\n            removed_keys = set([name])\n        for key in removed_keys:\n            if key in item_index:\n                del(item_index[key])\n        for key in updated_keys.difference(added_keys.union(removed_keys)):\n            if item_index[key].get('_changed'):\n                item_index[key]['_changed'] = False\n                removed_keys.add(key)\n                added_keys.add(key)\n        return added_keys, removed_keys",
    "docstring": "Calculate difference between the original and updated sets of keys.\n\n        Removed items will be removed from item_index, new items should have\n        been added by the discovery process. (?help or ?sensor-list)\n\n        This method is for use in inspect_requests and inspect_sensors only.\n\n        Returns\n        -------\n\n        (added, removed)\n        added : set of str\n            Names of the keys that were added\n        removed : set of str\n            Names of the keys that were removed"
  },
  {
    "code": "def unwrap(self):\n        return [v.unwrap() if hasattr(v, 'unwrap') and not hasattr(v, 'no_unwrap') else v for v in self]",
    "docstring": "Return a deep copy of myself as a list, and unwrap any wrapper objects in me."
  },
  {
    "code": "def _dictify(field, value):\n    if value is None:\n        return None\n    elif field.type_:\n        return value.to_dict()\n    return field.dict_value(value)",
    "docstring": "Make `value` suitable for a dictionary.\n\n    * If `value` is an Entity, call to_dict() on it.\n    * If value is a timestamp, turn it into a string value.\n    * If none of the above are satisfied, return the input value"
  },
  {
    "code": "def set_metadata_cache(cache):\n    global _METADATA_CACHE\n    if _METADATA_CACHE and _METADATA_CACHE.is_open:\n        _METADATA_CACHE.close()\n    _METADATA_CACHE = cache",
    "docstring": "Sets the metadata cache object to use."
  },
  {
    "code": "def find(self, filter=None, page=1, per_page=10, fields=None, context=None):\n        if filter is None:\n            filter = []\n        rv = self.client.session.get(\n            self.path,\n            params={\n                'filter': dumps(filter or []),\n                'page': page,\n                'per_page': per_page,\n                'field': fields,\n                'context': dumps(context or self.client.context),\n            }\n        )\n        response_received.send(rv)\n        return rv",
    "docstring": "Find records that match the filter.\n\n        Pro Tip: The fields could have nested fields names if the field is\n        a relationship type. For example if you were looking up an order\n        and also want to get the shipping address country then fields would be:\n\n            `['shipment_address', 'shipment_address.country']`\n\n        but country in this case is the ID of the country which is not very\n        useful if you don't already have a map. You can fetch the country code\n        by adding `'shipment_address.country.code'` to the fields.\n\n        :param filter: A domain expression (Refer docs for domain syntax)\n        :param page: The page to fetch to get paginated results\n        :param per_page: The number of records to fetch per page\n        :param fields: A list of field names to fetch.\n        :param context: Any overrides to the context."
  },
  {
    "code": "def next(self):\n        if self.is_train:\n            data, labels = self.sample_train_batch()\n        else:\n            if self.test_count * self.batch_size < len(self.test_image_files):\n                data, labels = self.get_test_batch()\n                self.test_count += 1\n            else:\n                self.test_count = 0\n                raise StopIteration\n        return mx.io.DataBatch(data=[data], label=[labels])",
    "docstring": "Return a batch."
  },
  {
    "code": "def get_frontend_node(self):\n        if self.ssh_to:\n            if self.ssh_to in self.nodes:\n                cls = self.nodes[self.ssh_to]\n                if cls:\n                    return cls[0]\n                else:\n                    log.warning(\n                        \"preferred `ssh_to` `%s` is empty: unable to \"\n                        \"get the choosen frontend node from that class.\",\n                        self.ssh_to)\n            else:\n                raise NodeNotFound(\n                    \"Invalid ssh_to `%s`. Please check your \"\n                    \"configuration file.\" % self.ssh_to)\n        for cls in sorted(self.nodes.keys()):\n            if self.nodes[cls]:\n                return self.nodes[cls][0]\n        raise NodeNotFound(\"Unable to find a valid frontend: \"\n                           \"cluster has no nodes!\")",
    "docstring": "Returns the first node of the class specified in the\n        configuration file as `ssh_to`, or the first node of\n        the first class in alphabetic order.\n\n        :return: :py:class:`Node`\n        :raise: :py:class:`elasticluster.exceptions.NodeNotFound` if no\n                valid frontend node is found"
  },
  {
    "code": "def get_cameras_properties(self):\n        resource = \"cameras\"\n        resource_event = self.publish_and_get_event(resource)\n        if resource_event:\n            self._last_refresh = int(time.time())\n            self._camera_properties = resource_event.get('properties')",
    "docstring": "Return camera properties."
  },
  {
    "code": "def set_timeout(self, timeout):\n        try:\n            timeout = float(timeout)\n            assert timeout>=0\n            assert timeout>=self.__wait\n        except:\n            raise Exception('timeout must be a positive number bigger than wait')\n        self.__timeout  = timeout",
    "docstring": "set the timeout limit.\n\n        :Parameters:\n            #. timeout (number): The maximum delay or time allowed to successfully set the\n               lock. When timeout is exhausted before successfully setting the lock,\n               the lock ends up not acquired."
  },
  {
    "code": "def update_tabs_text(self):\r\n        try:\r\n            for index, fname in enumerate(self.filenames):\r\n                client = self.clients[index]\r\n                if fname:\r\n                    self.rename_client_tab(client,\r\n                                           self.disambiguate_fname(fname))\r\n                else:\r\n                    self.rename_client_tab(client, None)\r\n        except IndexError:\r\n            pass",
    "docstring": "Update the text from the tabs."
  },
  {
    "code": "def branches(self):\n        if self._branches is None:\n            cmd = 'git branch --contains {}'.format(self.sha1)\n            out = shell.run(\n                cmd,\n                capture=True,\n                never_pretend=True\n            ).stdout.strip()\n            self._branches = [x.strip('* \\t\\n') for x in out.splitlines()]\n        return self._branches",
    "docstring": "List of all branches this commit is a part of."
  },
  {
    "code": "def get_list(self, list_id):\n        return List(tweepy_list_to_json(self._client.get_list(list_id=list_id)))",
    "docstring": "Get info of specified list\n\n        :param list_id: list ID number\n        :return: :class:`~responsebot.models.List` object"
  },
  {
    "code": "def _inter_df_op_handler(self, func, other, **kwargs):\n        axis = kwargs.get(\"axis\", 0)\n        axis = pandas.DataFrame()._get_axis_number(axis) if axis is not None else 0\n        if isinstance(other, type(self)):\n            return self._inter_manager_operations(\n                other, \"outer\", lambda x, y: func(x, y, **kwargs)\n            )\n        else:\n            return self._scalar_operations(\n                axis, other, lambda df: func(df, other, **kwargs)\n            )",
    "docstring": "Helper method for inter-manager and scalar operations.\n\n        Args:\n            func: The function to use on the Manager/scalar.\n            other: The other Manager/scalar.\n\n        Returns:\n            New DataManager with new data and index."
  },
  {
    "code": "def setCol(self, x, l):\n        for i in xrange(0, self.__size):\n            self.setCell(x, i, l[i])",
    "docstring": "set the x-th column, starting at 0"
  },
  {
    "code": "def read_args_tool(toolkey, example_parameters, tool_add_args=None):\n    import scanpy as sc\n    p = default_tool_argparser(help(toolkey), example_parameters)\n    if tool_add_args is None:\n        p = add_args(p)\n    else:\n        p = tool_add_args(p)\n    args = vars(p.parse_args())\n    args = settings.process_args(args)\n    return args",
    "docstring": "Read args for single tool."
  },
  {
    "code": "def image_exists(self, id=None, tag=None):\n        exists = False\n        if id and self.image_by_id(id):\n            exists = True\n        elif tag and self.image_by_tag(tag):\n            exists = True\n        return exists",
    "docstring": "Check if specified image exists"
  },
  {
    "code": "def space_search(args):\n    r = fapi.list_workspaces()\n    fapi._check_response_code(r, 200)\n    workspaces = r.json()\n    extra_terms = []\n    if args.bucket:\n        workspaces = [w for w in workspaces\n                      if re.search(args.bucket, w['workspace']['bucketName'])]\n        extra_terms.append('bucket')\n    pretty_spaces = []\n    for space in workspaces:\n        ns = space['workspace']['namespace']\n        ws = space['workspace']['name']\n        pspace = ns + '/' + ws\n        pspace += '\\t' + space['workspace']['bucketName']\n        pretty_spaces.append(pspace)\n    return sorted(pretty_spaces, key=lambda s: s.lower())",
    "docstring": "Search for workspaces matching certain criteria"
  },
  {
    "code": "def _trace (frame, event, arg):\n    if event in ('call', 'c_call'):\n        _trace_line(frame, event, arg)\n    elif event in ('return', 'c_return'):\n        _trace_line(frame, event, arg)\n        print(\"  return:\", arg)\n    return _trace",
    "docstring": "Trace function calls."
  },
  {
    "code": "def match_contains(self, el, contains):\n        match = True\n        content = None\n        for contain_list in contains:\n            if content is None:\n                content = self.get_text(el, no_iframe=self.is_html)\n            found = False\n            for text in contain_list.text:\n                if text in content:\n                    found = True\n                    break\n            if not found:\n                match = False\n        return match",
    "docstring": "Match element if it contains text."
  },
  {
    "code": "def remove(self):\n        if self.parent is not None:\n            for i, child in enumerate(self.parent.children):\n                if id(child) == id(self):\n                    self.parent.remove_child(i)\n                    self.parent = None\n                    break",
    "docstring": "Remove this node from the list of children of its current parent,\n        if the current parent is not ``None``, otherwise do nothing.\n\n        .. versionadded:: 1.7.0"
  },
  {
    "code": "def hook_wnd_proc(self):\r\n        self.__local_wnd_proc_wrapped = WndProcType(self.local_wnd_proc)\r\n        self.__old_wnd_proc = SetWindowLong(self.__local_win_handle,\r\n                                        GWL_WNDPROC,\r\n                                        self.__local_wnd_proc_wrapped)",
    "docstring": "Attach to OS Window message handler"
  },
  {
    "code": "def _connected_pids(self, from_parent=True):\n        to_pid = aliased(PersistentIdentifier, name='to_pid')\n        if from_parent:\n            to_relation = PIDRelation.child_id\n            from_relation = PIDRelation.parent_id\n        else:\n            to_relation = PIDRelation.parent_id\n            from_relation = PIDRelation.child_id\n        query = PIDQuery(\n            [to_pid], db.session(), _filtered_pid_class=to_pid\n        ).join(\n            PIDRelation,\n            to_pid.id == to_relation\n        )\n        if isinstance(self.pid, PersistentIdentifier):\n            query = query.filter(from_relation == self.pid.id)\n        else:\n            from_pid = aliased(PersistentIdentifier, name='from_pid')\n            query = query.join(\n                from_pid,\n                from_pid.id == from_relation\n            ).filter(\n                from_pid.pid_value == self.pid.pid_value,\n                from_pid.pid_type == self.pid.pid_type,\n            )\n        return query",
    "docstring": "Follow a relationship to find connected PIDs.abs.\n\n        :param from_parent: search children from the current pid if True, else\n        search for its parents.\n        :type from_parent: bool"
  },
  {
    "code": "def request_uri(self):\n        uri = self.path or '/'\n        if self.query is not None:\n            uri += '?' + self.query\n        return uri",
    "docstring": "Absolute path including the query string."
  },
  {
    "code": "def update_time_range(form_data):\n    if 'since' in form_data or 'until' in form_data:\n        form_data['time_range'] = '{} : {}'.format(\n            form_data.pop('since', '') or '',\n            form_data.pop('until', '') or '',\n        )",
    "docstring": "Move since and until to time_range."
  },
  {
    "code": "def get_base_branch(cherry_pick_branch):\n    prefix, sha, base_branch = cherry_pick_branch.split(\"-\", 2)\n    if prefix != \"backport\":\n        raise ValueError(\n            'branch name is not prefixed with \"backport-\".  Is this a cherry_picker branch?'\n        )\n    if not re.match(\"[0-9a-f]{7,40}\", sha):\n        raise ValueError(f\"branch name has an invalid sha: {sha}\")\n    validate_sha(sha)\n    version_from_branch(base_branch)\n    return base_branch",
    "docstring": "return '2.7' from 'backport-sha-2.7'\n\n    raises ValueError if the specified branch name is not of a form that\n        cherry_picker would have created"
  },
  {
    "code": "def table_columns(self):\n        with self.conn.cursor() as cur:\n            cur.execute(self.TABLE_COLUMNS_QUERY % self.database)\n            for row in cur:\n                yield row",
    "docstring": "Yields column names."
  },
  {
    "code": "def conn_aws(cred, crid):\n    driver = get_driver(Provider.EC2)\n    try:\n        aws_obj = driver(cred['aws_access_key_id'],\n                         cred['aws_secret_access_key'],\n                         region=cred['aws_default_region'])\n    except SSLError as e:\n        abort_err(\"\\r SSL Error with AWS: {}\".format(e))\n    except InvalidCredsError as e:\n        abort_err(\"\\r Error with AWS Credentials: {}\".format(e))\n    return {crid: aws_obj}",
    "docstring": "Establish connection to AWS service."
  },
  {
    "code": "def _create_skt(self):\n        log.debug('Creating the auth socket')\n        if ':' in self.auth_address:\n            self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)\n        else:\n            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        try:\n            self.socket.bind((self.auth_address, self.auth_port))\n        except socket.error as msg:\n            error_string = 'Unable to bind (auth) to port {} on {}: {}'.format(self.auth_port, self.auth_address, msg)\n            log.error(error_string, exc_info=True)\n            raise BindException(error_string)",
    "docstring": "Create the authentication socket."
  },
  {
    "code": "def binary_float_to_decimal_float(number: Union[float, str]) -> float:\n    if isinstance(number, str):\n        if number[0] == '-':\n            n_sign = -1\n        else:\n            n_sign = 1\n    elif isinstance(number, float):\n        n_sign = np.sign(number)\n        number = str(number)\n    deci = 0\n    for ndx, val in enumerate(number.split('.')[-1]):\n        deci += float(val) / 2**(ndx+1)\n    deci *= n_sign\n    return deci",
    "docstring": "Convert binary floating point to decimal floating point.\n\n    :param number: Binary floating point.\n    :return: Decimal floating point representation of binary floating point."
  },
  {
    "code": "def coerce(self, value, resource):\n        return {r.name: self.registry.solve_resource(value, r) for r in resource.resources}",
    "docstring": "Get a dict with attributes from ``value``.\n\n        Arguments\n        ---------\n        value : ?\n            The value to get some resources from.\n        resource : dataql.resources.Object\n            The ``Object`` object used to obtain this value from the original one.\n\n        Returns\n        -------\n        dict\n            A dictionary containing the wanted resources for the given value.\n            Key are the ``name`` attributes of the resources, and the values are the solved values."
  },
  {
    "code": "def get_details(self, ids):\n        if isinstance(ids, list):\n            if len(ids) > 5:\n                ids = ids[:5]\n            id_param = ';'.join(ids) + '/'\n        else:\n            ids = str(ids)\n            id_param = ids + '/'\n        header, content = self._http_request(id_param)\n        resp = json.loads(content)\n        if not self._is_http_response_ok(header):\n            error = resp.get('error_message', 'Unknown Error')\n            raise HttpException(header.status, header.reason, error) \n        return resp",
    "docstring": "Locu Venue Details API Call Wrapper\n\n        Args:\n          list of ids : ids of a particular venues to get insights about. Can process up to 5 ids"
  },
  {
    "code": "def emotes(self, emotes):\n        if emotes is None:\n            self._emotes = []\n            return\n        es = []\n        for estr in emotes.split('/'):\n            es.append(Emote.from_str(estr))\n        self._emotes = es",
    "docstring": "Set the emotes\n\n        :param emotes: the key of the emotes tag\n        :type emotes: :class:`str`\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def find_default_container(builder,\n                           default_container=None,\n                           use_biocontainers=None,\n                          ):\n    if not default_container and use_biocontainers:\n        default_container = get_container_from_software_requirements(\n            use_biocontainers, builder)\n    return default_container",
    "docstring": "Default finder for default containers."
  },
  {
    "code": "def add_data_from_jsonp(self, data_src, data_name = 'json_data', series_type=\"map\", name=None, **kwargs):\n        self.jsonp_data_flag = True\n        self.jsonp_data_url = json.dumps(data_src)\n        if data_name == 'data':\n            data_name = 'json_'+ data_name\n        self.jsonp_data = data_name\n        self.add_data_set(RawJavaScriptText(data_name), series_type, name=name, **kwargs)",
    "docstring": "add data directly from a https source\n        the data_src is the https link for data using jsonp"
  },
  {
    "code": "def remove(self, observableElement):\n        if observableElement in self._observables:\n            self._observables.remove(observableElement)",
    "docstring": "remove an obsrvable element\n\n        :param str observableElement: the name of the observable element"
  },
  {
    "code": "def create_job(self, job_template_uri):\n        endpoint = self._build_url('jobs')\n        data = self._query_api('POST',\n                               endpoint,\n                               None,\n                               {'Content-Type': 'application/json'},\n                               json.dumps({'jobTemplateUri': job_template_uri}))\n        return data['results']",
    "docstring": "Creates a job"
  },
  {
    "code": "def append(self, node):\n        if node.parent == self.key and not self.elapsed_time:\n            self.children.append(node)\n        else:\n            for child in self.children:\n                if not child.elapsed_time:\n                    child.append(node)",
    "docstring": "To append a new child."
  },
  {
    "code": "def _should_trigger_abbreviation(self, buffer):\n        return any(self.__checkInput(buffer, abbr) for abbr in self.abbreviations)",
    "docstring": "Checks whether, based on the settings for the abbreviation and the given input,\n        the abbreviation should trigger.\n\n        @param buffer Input buffer to be checked (as string)"
  },
  {
    "code": "def is_option(value, *options):\n    if not isinstance(value, string_types):\n        raise VdtTypeError(value)\n    if not value in options:\n        raise VdtValueError(value)\n    return value",
    "docstring": "This check matches the value to any of a set of options.\n\n    >>> vtor = Validator()\n    >>> vtor.check('option(\"yoda\", \"jedi\")', 'yoda')\n    'yoda'\n    >>> vtor.check('option(\"yoda\", \"jedi\")', 'jed')  # doctest: +SKIP\n    Traceback (most recent call last):\n    VdtValueError: the value \"jed\" is unacceptable.\n    >>> vtor.check('option(\"yoda\", \"jedi\")', 0)  # doctest: +SKIP\n    Traceback (most recent call last):\n    VdtTypeError: the value \"0\" is of the wrong type."
  },
  {
    "code": "def _logging_callback(level, domain, message, data):\n    domain = ffi.string(domain).decode()\n    message = ffi.string(message).decode()\n    logger = LOGGER.getChild(domain)\n    if level not in LOG_LEVELS:\n        return\n    logger.log(LOG_LEVELS[level], message)",
    "docstring": "Callback that outputs libgphoto2's logging message via\n        Python's standard logging facilities.\n\n    :param level:   libgphoto2 logging level\n    :param domain:  component the message originates from\n    :param message: logging message\n    :param data:    Other data in the logging record (unused)"
  },
  {
    "code": "def zoomset_cb(self, setting, value, channel):\n        if not self.gui_up:\n            return\n        info = channel.extdata._info_info\n        if info is None:\n            return\n        scale_x, scale_y = value\n        if scale_x == scale_y:\n            text = self.fv.scale2text(scale_x)\n        else:\n            textx = self.fv.scale2text(scale_x)\n            texty = self.fv.scale2text(scale_y)\n            text = \"X: %s  Y: %s\" % (textx, texty)\n        info.winfo.zoom.set_text(text)",
    "docstring": "This callback is called when the main window is zoomed."
  },
  {
    "code": "def redirect_ext(to, params_=None, anchor_=None, permanent_=False, args=None, kwargs=None):\n    if permanent_:\n        redirect_class = HttpResponsePermanentRedirect\n    else:\n        redirect_class = HttpResponseRedirect\n    return redirect_class(resolve_url_ext(to, params_, anchor_, args, kwargs))",
    "docstring": "Advanced redirect which can includes GET-parameters and anchor."
  },
  {
    "code": "def _find_fld_pkt_val(self, pkt, val):\n        fld = self._iterate_fields_cond(pkt, val, True)\n        dflts_pkt = pkt.default_fields\n        if val == dflts_pkt[self.name] and self.name not in pkt.fields:\n            dflts_pkt[self.name] = fld.default\n            val = fld.default\n        return fld, val",
    "docstring": "Given a Packet instance `pkt` and the value `val` to be set,\nreturns the Field subclass to be used, and the updated `val` if necessary."
  },
  {
    "code": "def unregister_child(self, child):\n        self._children.remove(child)\n        child.on_closed.disconnect(self.unregister_child)",
    "docstring": "Unregister an existing child that is no longer to be owned by the\n        current instance.\n\n        :param child: The child instance."
  },
  {
    "code": "def balance(self):\r\n        while self.recNum > self.shpNum:\r\n            self.null()\r\n        while self.recNum < self.shpNum:\r\n            self.record()",
    "docstring": "Adds corresponding empty attributes or null geometry records depending\r\n        on which type of record was created to make sure all three files\r\n        are in synch."
  },
  {
    "code": "def _reset(self, **kwargs):\n        super(Tag, self)._reset(**kwargs)\n        self._api_name = self.name\n        if 'server' in self.servers:\n            self.servers = kwargs['servers']['server']\n        if self.servers and isinstance(self.servers[0], six.string_types):\n            self.servers = [Server(uuid=server, populated=False) for server in self.servers]",
    "docstring": "Reset the objects attributes.\n\n        Accepts servers as either unflattened or flattened UUID strings or Server objects."
  },
  {
    "code": "def cleanup(context):\n    for name in 'work_dir', 'artifact_dir', 'task_log_dir':\n        path = context.config[name]\n        if os.path.exists(path):\n            log.debug(\"rm({})\".format(path))\n            rm(path)\n        makedirs(path)",
    "docstring": "Clean up the work_dir and artifact_dir between task runs, then recreate.\n\n    Args:\n        context (scriptworker.context.Context): the scriptworker context."
  },
  {
    "code": "def InstallTemplatePackage():\n  virtualenv_bin = os.path.dirname(sys.executable)\n  extension = os.path.splitext(sys.executable)[1]\n  pip = \"%s/pip%s\" % (virtualenv_bin, extension)\n  major_minor_version = \".\".join(\n      pkg_resources.get_distribution(\"grr-response-core\").version.split(\".\")\n      [0:2])\n  subprocess.check_call([\n      sys.executable, pip, \"install\", \"--upgrade\", \"-f\",\n      \"https://storage.googleapis.com/releases.grr-response.com/index.html\",\n      \"grr-response-templates==%s.*\" % major_minor_version\n  ])",
    "docstring": "Call pip to install the templates."
  },
  {
    "code": "def spec(self):\n        from ambry_sources.sources import SourceSpec\n        d = self.dict\n        d['url'] = self.url\n        return SourceSpec(**d)",
    "docstring": "Return a SourceSpec to describe this source"
  },
  {
    "code": "def figure(size=(8,8), *args, **kwargs):\n        return plt.figure(figsize=size, *args, **kwargs)",
    "docstring": "Creates a figure.\n\n        Parameters\n        ----------\n        size : 2-tuple\n           size of the view window in inches\n        args : list\n           args of mayavi figure\n        kwargs : list\n           keyword args of mayavi figure\n\n        Returns\n        -------\n        pyplot figure\n            the current figure"
  },
  {
    "code": "def report_stderr(host, stderr):\n    lines = stderr.readlines()\n    if lines:\n        print(\"STDERR from {host}:\".format(host=host))\n        for line in lines:\n            print(line.rstrip(), file=sys.stderr)",
    "docstring": "Take a stderr and print it's lines to output if lines are present.\n\n    :param host: the host where the process is running\n    :type host: str\n    :param stderr: the std error of that process\n    :type stderr: paramiko.channel.Channel"
  },
  {
    "code": "def lazy_result(f):\n    @wraps(f)\n    def decorated(ctx, param, value):\n        return LocalProxy(lambda: f(ctx, param, value))\n    return decorated",
    "docstring": "Decorate function to return LazyProxy."
  },
  {
    "code": "def get_network(self, org, segid):\n        network_info = {\n            'organizationName': org,\n            'partitionName': self._part_name,\n            'segmentId': segid,\n        }\n        res = self._get_network(network_info)\n        if res and res.status_code in self._resp_ok:\n            return res.json()",
    "docstring": "Return given network from DCNM.\n\n        :param org: name of organization.\n        :param segid: segmentation id of the network."
  },
  {
    "code": "def getFixedStarList(IDs, date):\n    starList = [getFixedStar(ID, date) for ID in IDs]\n    return FixedStarList(starList)",
    "docstring": "Returns a list of fixed stars."
  },
  {
    "code": "def current_state(self):\n        field_names = set()\n        [field_names.add(f.name) for f in self._meta.local_fields]\n        [field_names.add(f.attname) for f in self._meta.local_fields]\n        return dict([(field_name, getattr(self, field_name)) for field_name in field_names])",
    "docstring": "Returns a ``field -> value`` dict of the current state of the instance."
  },
  {
    "code": "def get_random_name():\n    char_seq = []\n    name_source = random.randint(1, 2**8-1)\n    current_value = name_source\n    while current_value > 0:\n        char_offset = current_value % 26\n        current_value = current_value - random.randint(1, 26)\n        char_seq.append(chr(char_offset + ord('a')))\n    name = ''.join(char_seq)\n    assert re.match(VALID_PACKAGE_RE, name)\n    return name",
    "docstring": "Return random lowercase name"
  },
  {
    "code": "def getAllKws(self):\n        kws_ele = []\n        kws_bl = []\n        for ele in self.all_elements:\n            if ele == '_prefixstr' or ele == '_epics':\n                continue\n            elif self.getElementType(ele).lower() == u'beamline':\n                kws_bl.append(ele)\n            else:\n                kws_ele.append(ele)\n        return tuple((kws_ele, kws_bl))",
    "docstring": "extract all keywords into two categories\n\n            kws_ele: magnetic elements\n            kws_bl: beamline elements\n\n            return (kws_ele, kws_bl)"
  },
  {
    "code": "def is_delimiter(line):\n    return bool(line) and line[0] in punctuation and line[0]*len(line) == line",
    "docstring": "True if a line consists only of a single punctuation character."
  },
  {
    "code": "def get_cluster_interfaces(cluster, extra_cond=lambda nic: True):\n    nics = get_nics(cluster)\n    nics = [(nic['device'], nic['name']) for nic in nics\n            if nic['mountable']\n            and nic['interface'] == 'Ethernet'\n            and not nic['management']\n            and extra_cond(nic)]\n    nics = sorted(nics)\n    return nics",
    "docstring": "Get the network interfaces names corresponding to a criteria.\n\n    Note that the cluster is passed (not the individual node names), thus it is\n    assumed that all nodes in a cluster have the same interface names same\n    configuration. In addition to ``extra_cond``, only the mountable and\n    Ehernet interfaces are returned.\n\n    Args:\n        cluster(str): the cluster to consider\n        extra_cond(lambda): boolean lambda that takes the nic(dict) as\n            parameter"
  },
  {
    "code": "def lp10(self, subset_k, subset_p, weights={}):\n        if self._z is None:\n            self._add_minimization_vars()\n        positive = set(subset_k) - self._flipped\n        negative = set(subset_k) & self._flipped\n        v = self._v.set(positive)\n        cs = self._prob.add_linear_constraints(v >= self._epsilon)\n        self._temp_constr.extend(cs)\n        v = self._v.set(negative)\n        cs = self._prob.add_linear_constraints(v <= -self._epsilon)\n        self._temp_constr.extend(cs)\n        self._prob.set_objective(self._z.expr(\n            (rxnid, -weights.get(rxnid, 1)) for rxnid in subset_p))\n        self._solve()",
    "docstring": "Force reactions in K above epsilon while minimizing support of P.\n\n        This program forces reactions in subset K to attain flux > epsilon\n        while minimizing the sum of absolute flux values for reactions\n        in subset P (L1-regularization)."
  },
  {
    "code": "def run(self, resources):\n        if not resources['connection']._port.startswith('jlink'):\n            raise ArgumentError(\"FlashBoardStep is currently only possible through jlink\", invalid_port=args['port'])\n        hwman = resources['connection']\n        debug = hwman.hwman.debug(self._debug_string)\n        debug.flash(self._file)",
    "docstring": "Runs the flash step\n\n        Args:\n            resources (dict): A dictionary containing the required resources that\n                we needed access to in order to perform this step."
  },
  {
    "code": "def new_as_dict(self, raw=True, vars=None):\n    result = {}\n    for section in self.sections():\n        if section not in result:\n            result[section] = {}\n        for option in self.options(section):\n            value = self.get(section, option, raw=raw, vars=vars)\n            try:\n                value = cherrypy.lib.reprconf.unrepr(value)\n            except Exception:\n                x = sys.exc_info()[1]\n                msg = (\"Config error in section: %r, option: %r, \"\n                       \"value: %r. Config values must be valid Python.\" %\n                       (section, option, value))\n                raise ValueError(msg, x.__class__.__name__, x.args)\n            result[section][option] = value\n    return result",
    "docstring": "Convert an INI file to a dictionary"
  },
  {
    "code": "def run_crbox(self,spstring,form,output=\"\",wavecat=\"INDEF\",\n                  lowave=0,hiwave=30000):\n        range=hiwave-lowave\n        midwave=range/2.0\n        iraf.countrate(spectrum=spstring, magnitude=\"\",\n                       instrument=\"box(%f,%f)\"%(midwave,range),\n                       form=form,\n                       wavecat=wavecat,\n                       output=output)",
    "docstring": "Calcspec has a bug. We will use countrate instead, and force it\n        to use a box function of uniform transmission as the obsmode."
  },
  {
    "code": "def name_for_scalar_relationship(base, local_cls, referred_cls, constraint):\n    name = referred_cls.__name__.lower() + \"_ref\"\n    return name",
    "docstring": "Overriding naming schemes."
  },
  {
    "code": "def _init_alphabet_from_tokens(self, tokens):\n        self._alphabet = {c for token in tokens for c in token}\n        self._alphabet |= _ESCAPE_CHARS",
    "docstring": "Initialize alphabet from an iterable of token or subtoken strings."
  },
  {
    "code": "def set_item(self, key, value):\n        keys = list(self.keys())\n        if key in keys:\n            self.set_value(1,keys.index(key),str(value))\n        else:\n            self.set_value(0,len(self),   str(key))\n            self.set_value(1,len(self)-1, str(value))",
    "docstring": "Sets the item by key, and refills the table sorted."
  },
  {
    "code": "def list_attr(self, recursive=False):\n        if recursive:\n            raise DeprecationWarning(\"Symbol.list_attr with recursive=True has been deprecated. \"\n                                     \"Please use attr_dict instead.\")\n        size = mx_uint()\n        pairs = ctypes.POINTER(ctypes.c_char_p)()\n        f_handle = _LIB.MXSymbolListAttrShallow\n        check_call(f_handle(self.handle, ctypes.byref(size), ctypes.byref(pairs)))\n        return {py_str(pairs[i * 2]): py_str(pairs[i * 2 + 1]) for i in range(size.value)}",
    "docstring": "Gets all attributes from the symbol.\n\n        Example\n        -------\n        >>> data = mx.sym.Variable('data', attr={'mood': 'angry'})\n        >>> data.list_attr()\n        {'mood': 'angry'}\n\n        Returns\n        -------\n        ret : Dict of str to str\n            A dictionary mapping attribute keys to values."
  },
  {
    "code": "def clear( self ):\n        self.blockSignals(True)\n        self.setUpdatesEnabled(False)\n        for child in self.findChildren(XRolloutItem):\n            child.setParent(None)\n            child.deleteLater()\n        self.setUpdatesEnabled(True)\n        self.blockSignals(False)",
    "docstring": "Clears out all of the rollout items from the widget."
  },
  {
    "code": "def subscribe(self, sender=None, iface=None, signal=None, object=None, arg0=None, flags=0, signal_fired=None):\n\t\tcallback = (lambda con, sender, object, iface, signal, params: signal_fired(sender, object, iface, signal, params.unpack())) if signal_fired is not None else lambda *args: None\n\t\treturn Subscription(self.con, sender, iface, signal, object, arg0, flags, callback)",
    "docstring": "Subscribes to matching signals.\n\n\t\tSubscribes to signals on connection and invokes signal_fired callback\n\t\twhenever the signal is received.\n\n\t\tTo receive signal_fired callback, you need an event loop.\n\t\thttps://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop\n\n\t\tParameters\n\t\t----------\n\t\tsender : string, optional\n\t\t\tSender name to match on (unique or well-known name) or None to listen from all senders.\n\t\tiface : string, optional\n\t\t\tInterface name to match on or None to match on all interfaces.\n\t\tsignal : string, optional\n\t\t\tSignal name to match on or None to match on all signals.\n\t\tobject : string, optional\n\t\t\tObject path to match on or None to match on all object paths.\n\t\targ0 : string, optional\n\t\t\tContents of first string argument to match on or None to match on all kinds of arguments.\n\t\tflags : SubscriptionFlags, optional\n\t\tsignal_fired : callable, optional\n\t\t\tInvoked when there is a signal matching the requested data.\n\t\t\tParameters: sender, object, iface, signal, params\n\n\t\tReturns\n\t\t-------\n\t\tSubscription\n\t\t\tAn object you can use as a context manager to unsubscribe from the signal later.\n\n\t\tSee Also\n\t\t--------\n\t\tSee https://developer.gnome.org/gio/2.44/GDBusConnection.html#g-dbus-connection-signal-subscribe\n\t\tfor more information."
  },
  {
    "code": "def validateAllServers(self):\n        url = self._url + \"/servers/validate\"\n        params = {\"f\" : \"json\"}\n        return self._get(url=url,\n                         param_dict=params,\n                         proxy_port=self._proxy_port,\n                         proxy_url=self._proxy_ur)",
    "docstring": "This operation provides status information about a specific ArcGIS\n        Server federated with Portal for ArcGIS.\n\n        Parameters:\n           serverId - unique id of the server"
  },
  {
    "code": "def create_xref(self):\n        log.debug(\"Creating Crossreferences (XREF)\")\n        tic = time.time()\n        for c in self._get_all_classes():\n            self._create_xref(c)\n        log.info(\"End of creating cross references (XREF)\")\n        log.info(\"run time: {:0d}min {:02d}s\".format(*divmod(int(time.time() - tic), 60)))",
    "docstring": "Create Class, Method, String and Field crossreferences\n        for all classes in the Analysis.\n\n        If you are using multiple DEX files, this function must\n        be called when all DEX files are added.\n        If you call the function after every DEX file, the\n        crossreferences might be wrong!"
  },
  {
    "code": "def _get_binned_arrays(self, wavelengths, flux_unit, area=None,\n                           vegaspec=None):\n        x = self._validate_binned_wavelengths(wavelengths)\n        y = self.sample_binned(wavelengths=x, flux_unit=flux_unit, area=area,\n                               vegaspec=vegaspec)\n        if isinstance(wavelengths, u.Quantity):\n            w = x.to(wavelengths.unit, u.spectral())\n        else:\n            w = x\n        return w, y",
    "docstring": "Get binned observation in user units."
  },
  {
    "code": "def rollback(self):\n        self._tx_active = False\n        return self._channel.rpc_request(specification.Tx.Rollback())",
    "docstring": "Abandon the current transaction.\n\n            Rollback all messages published during the current transaction\n            session to the remote server.\n\n            Note that all messages published during this transaction session\n            will be lost, and will have to be published again.\n\n            A new transaction session starts as soon as the command has\n            been executed.\n\n        :return:"
  },
  {
    "code": "def has_in_url_path(url, subs):\n    scheme, netloc, path, query, fragment = urlparse.urlsplit(url)\n    return any([sub in path for sub in subs])",
    "docstring": "Test if any of `subs` strings is present in the `url` path."
  },
  {
    "code": "async def finish_pairing(self, pin):\n        self.srp.step1(pin)\n        pub_key, proof = self.srp.step2(self._atv_pub_key, self._atv_salt)\n        msg = messages.crypto_pairing({\n            tlv8.TLV_SEQ_NO: b'\\x03',\n            tlv8.TLV_PUBLIC_KEY: pub_key,\n            tlv8.TLV_PROOF: proof})\n        resp = await self.protocol.send_and_receive(\n            msg, generate_identifier=False)\n        pairing_data = _get_pairing_data(resp)\n        atv_proof = pairing_data[tlv8.TLV_PROOF]\n        log_binary(_LOGGER, 'Device', Proof=atv_proof)\n        encrypted_data = self.srp.step3()\n        msg = messages.crypto_pairing({\n            tlv8.TLV_SEQ_NO: b'\\x05',\n            tlv8.TLV_ENCRYPTED_DATA: encrypted_data})\n        resp = await self.protocol.send_and_receive(\n            msg, generate_identifier=False)\n        pairing_data = _get_pairing_data(resp)\n        encrypted_data = pairing_data[tlv8.TLV_ENCRYPTED_DATA]\n        return self.srp.step4(encrypted_data)",
    "docstring": "Finish pairing process."
  },
  {
    "code": "def extract_changesets(objects):\n    def add_changeset_info(collation, axis, item):\n        if axis not in collation:\n            collation[axis] = {}\n        first = collation[axis]\n        first[\"id\"] = axis\n        first[\"username\"] = item[\"username\"]\n        first[\"uid\"] = item[\"uid\"]\n        first[\"timestamp\"] = item[\"timestamp\"]\n        collation[axis] = first\n    changeset_collation = {}\n    for node in objects.nodes.values():\n        _collate_data(changeset_collation, node['changeset'], node['action'])\n        add_changeset_info(changeset_collation, node['changeset'], node)\n    for way in objects.ways.values():\n        _collate_data(changeset_collation, way['changeset'], way['action'])\n        add_changeset_info(changeset_collation, way['changeset'], way)\n    for relation in objects.relations.values():\n        _collate_data(changeset_collation, relation['changeset'], relation['action'])\n        add_changeset_info(changeset_collation, relation['changeset'], relation)\n    return changeset_collation",
    "docstring": "Provides information about each changeset present in an OpenStreetMap diff\n    file.\n\n    Parameters\n    ----------\n    objects : osc_decoder class\n        A class containing OpenStreetMap object dictionaries.\n\n    Returns\n    -------\n    changeset_collation : dict\n        A dictionary of dictionaries with each changeset as a separate key,\n        information about each changeset as attributes in that dictionary,\n        and the actions performed in the changeset as keys."
  },
  {
    "code": "def _verify_password(self, raw_password, hashed_password):\n        PraetorianError.require_condition(\n            self.pwd_ctx is not None,\n            \"Praetorian must be initialized before this method is available\",\n        )\n        return self.pwd_ctx.verify(raw_password, hashed_password)",
    "docstring": "Verifies that a plaintext password matches the hashed version of that\n        password using the stored passlib password context"
  },
  {
    "code": "def _format_snapshots(snapshots: List[icontract._Snapshot], prefix: Optional[str] = None) -> List[str]:\n    if not snapshots:\n        return []\n    result = []\n    if prefix is not None:\n        result.append(\":{} OLD:\".format(prefix))\n    else:\n        result.append(\":OLD:\")\n    for snapshot in snapshots:\n        text = _capture_as_text(capture=snapshot.capture)\n        result.append(\"    * :code:`.{}` = :code:`{}`\".format(snapshot.name, text))\n    return result",
    "docstring": "Format snapshots as reST.\n\n    :param snapshots: snapshots defined to capture the argument values of a function before the invocation\n    :param prefix: prefix to be prepended to ``:OLD:`` directive\n    :return: list of lines describing the snapshots"
  },
  {
    "code": "def serialize(self, data):\n        return json.dumps(self._serialize_datetime(data), ensure_ascii=False)",
    "docstring": "Return the data as serialized string.\n\n        :param dict data: The data to serialize\n        :rtype: str"
  },
  {
    "code": "def Font(name=None, source=\"sys\", italic=False, bold=False, size=20):\n    assert source in [\"sys\", \"file\"]\n    if not name:\n        return pygame.font.SysFont(pygame.font.get_default_font(), \n        size, bold=bold, italic=italic)\n    if source == \"sys\":\n        return pygame.font.SysFont(name, \n        size, bold=bold, italic=italic)\n    else:\n        f = pygame.font.Font(name, size)\n        f.set_italic(italic)\n        f.set_bold(bold)\n        return f",
    "docstring": "Unifies loading of fonts.\n\n    :param name: name of system-font or filepath, if None is passed the default\n        system-font is loaded\n\n    :type name: str\n    :param source: \"sys\" for system font, or \"file\" to load a file\n    :type source: str"
  },
  {
    "code": "def load_model(\n            self, the_metamodel, filename, is_main_model, encoding='utf-8',\n            add_to_local_models=True):\n        if not self.local_models.has_model(filename):\n            if self.all_models.has_model(filename):\n                new_model = self.all_models.filename_to_model[filename]\n            else:\n                new_model = the_metamodel.internal_model_from_file(\n                    filename, pre_ref_resolution_callback=lambda\n                    other_model: self.pre_ref_resolution_callback(other_model),\n                    is_main_model=is_main_model, encoding=encoding)\n                self.all_models.filename_to_model[filename] = new_model\n            if add_to_local_models:\n                self.local_models.filename_to_model[filename] = new_model\n        assert self.all_models.has_model(filename)\n        return self.all_models.filename_to_model[filename]",
    "docstring": "load a single model\n\n        Args:\n            the_metamodel: the metamodel used to load the model\n            filename: the model to be loaded (if not cached)\n\n        Returns:\n            the loaded/cached model"
  },
  {
    "code": "def _non_reducing_slice(slice_):\n    kinds = (ABCSeries, np.ndarray, Index, list, str)\n    if isinstance(slice_, kinds):\n        slice_ = IndexSlice[:, slice_]\n    def pred(part):\n        return ((isinstance(part, slice) or is_list_like(part))\n                and not isinstance(part, tuple))\n    if not is_list_like(slice_):\n        if not isinstance(slice_, slice):\n            slice_ = [[slice_]]\n        else:\n            slice_ = [slice_]\n    else:\n        slice_ = [part if pred(part) else [part] for part in slice_]\n    return tuple(slice_)",
    "docstring": "Ensurse that a slice doesn't reduce to a Series or Scalar.\n\n    Any user-paseed `subset` should have this called on it\n    to make sure we're always working with DataFrames."
  },
  {
    "code": "def add_type(cls, typ):\n        if not isinstance(typ, basestring):\n            raise TypeError(\"The type should be a string. But is %s\" % type(typ))\n        cls.types.append(typ)",
    "docstring": "Register a type for jb_reftrack nodes.\n\n        A type specifies how the reference should be handled. For example the type shader will connect shaders\n        with the parent when it the shaders are loaded.\n        Default types are :data:`JB_ReftrackNode.types`.\n\n        .. Note:: You have to add types before you initialize the plugin!\n\n        :param typ: a new type specifier, e.g. \\\"asset\\\"\n        :type typ: str\n        :returns: None\n        :rtype: None\n        :raises: :class:`TypeError`"
  },
  {
    "code": "async def connect(self):\n        if self.connected or self.is_connecting:\n            return\n        self._is_connecting = True\n        try:\n            logger.info(\"Connecting to RabbitMQ...\")\n            self._transport, self._protocol = await aioamqp.connect(**self._connection_parameters)\n            logger.info(\"Getting channel...\")\n            self._channel = await self._protocol.channel()\n            if self._global_qos is not None:\n                logger.info(\"Setting prefetch count on connection (%s)\", self._global_qos)\n                await self._channel.basic_qos(0, self._global_qos, 1)\n            logger.info(\"Connecting to exchange '%s (%s)'\", self._exchange_name, self._exchange_type)\n            await self._channel.exchange(self._exchange_name, self._exchange_type)\n        except (aioamqp.AmqpClosedConnection, Exception):\n            logger.error(\"Error initializing RabbitMQ connection\", exc_info=True)\n            self._is_connecting = False\n            raise exceptions.StreamConnectionError\n        self._is_connecting = False",
    "docstring": "Create new asynchronous connection to the RabbitMQ instance.\n        This will connect, declare exchange and bind itself to the configured queue.\n\n        After that, client is ready to publish or consume messages.\n\n        :return: Does not return anything."
  },
  {
    "code": "def unsnip(tag=None,start=-1):\n    import IPython\n    i = IPython.get_ipython()\n    if tag in _tagged_inputs.keys():\n        if len(_tagged_inputs[tag]) > 0:\n            i.set_next_input(_tagged_inputs[tag][start])\n    else:\n        if len(_last_inputs) > 0:\n            i.set_next_input(_last_inputs[start])",
    "docstring": "This function retrieves a tagged or untagged snippet."
  },
  {
    "code": "def is_reassignment_pending(self):\n        in_progress_plan = self.zk.get_pending_plan()\n        if in_progress_plan:\n            in_progress_partitions = in_progress_plan['partitions']\n            self.log.info(\n                'Previous re-assignment in progress for {count} partitions.'\n                ' Current partitions in re-assignment queue: {partitions}'\n                .format(\n                    count=len(in_progress_partitions),\n                    partitions=in_progress_partitions,\n                )\n            )\n            return True\n        else:\n            return False",
    "docstring": "Return True if there are reassignment tasks pending."
  },
  {
    "code": "def _enum_from_direction(direction):\n    if isinstance(direction, int):\n        return direction\n    if direction == Query.ASCENDING:\n        return enums.StructuredQuery.Direction.ASCENDING\n    elif direction == Query.DESCENDING:\n        return enums.StructuredQuery.Direction.DESCENDING\n    else:\n        msg = _BAD_DIR_STRING.format(direction, Query.ASCENDING, Query.DESCENDING)\n        raise ValueError(msg)",
    "docstring": "Convert a string representation of a direction to an enum.\n\n    Args:\n        direction (str): A direction to order by. Must be one of\n            :attr:`~.firestore.Query.ASCENDING` or\n            :attr:`~.firestore.Query.DESCENDING`.\n\n    Returns:\n        int: The enum corresponding to ``direction``.\n\n    Raises:\n        ValueError: If ``direction`` is not a valid direction."
  },
  {
    "code": "def _draw_outer_connector(context, width, height):\n        c = context\n        arrow_height = height / 2.5\n        gap = height / 6.\n        connector_height = (height - gap) / 2.\n        c.rel_move_to(-width / 2., -gap / 2.)\n        c.rel_line_to(width, 0)\n        c.rel_line_to(0, -(connector_height - arrow_height))\n        c.rel_line_to(-width / 2., -arrow_height)\n        c.rel_line_to(-width / 2., arrow_height)\n        c.close_path()",
    "docstring": "Draw the outer connector for container states\n\n        Connector for container states can be connected from the inside and the outside. Thus the connector is split\n        in two parts: A rectangle on the inside and an arrow on the outside. This method draws the outer arrow.\n\n        :param context: Cairo context\n        :param float port_size: The side length of the port"
  },
  {
    "code": "def _to_link_header(self, link):\n        try:\n            bucket, key, tag = link\n        except ValueError:\n            raise RiakError(\"Invalid link tuple %s\" % link)\n        tag = tag if tag is not None else bucket\n        url = self.object_path(bucket, key)\n        header = '<%s>; riaktag=\"%s\"' % (url, tag)\n        return header",
    "docstring": "Convert the link tuple to a link header string. Used internally."
  },
  {
    "code": "def active_brokers(self):\n        return {\n            broker for broker in six.itervalues(self.brokers)\n            if not broker.inactive and not broker.decommissioned\n        }",
    "docstring": "Set of brokers that are not inactive or decommissioned."
  },
  {
    "code": "def remove_message(self, message):\n        if message in self.__messages:\n            self.__messages.remove(message)",
    "docstring": "Remove a message from the batch"
  },
  {
    "code": "def build(self):\n        if self._category_text_iter is None:\n            raise CategoryTextIterNotSetError()\n        nlp = self.get_nlp()\n        category_document_iter = (\n            (category, self._clean_function(raw_text))\n            for category, raw_text\n            in self._category_text_iter\n        )\n        term_doc_matrix = self._build_from_category_spacy_doc_iter(\n            (\n                (category, nlp(text))\n                for (category, text)\n                in category_document_iter\n                if text.strip() != ''\n            )\n        )\n        return term_doc_matrix",
    "docstring": "Generate a TermDocMatrix from data in parameters.\n\n         Returns\n         ----------\n         term_doc_matrix : TermDocMatrix\n            The object that this factory class builds."
  },
  {
    "code": "def info(vm, info_type='all', key='uuid'):\n    ret = {}\n    if info_type not in ['all', 'block', 'blockstats', 'chardev', 'cpus', 'kvm', 'pci', 'spice', 'version', 'vnc']:\n        ret['Error'] = 'Requested info_type is not available'\n        return ret\n    if key not in ['uuid', 'alias', 'hostname']:\n        ret['Error'] = 'Key must be either uuid, alias or hostname'\n        return ret\n    vm = lookup('{0}={1}'.format(key, vm), one=True)\n    if 'Error' in vm:\n        return vm\n    cmd = 'vmadm info {uuid} {type}'.format(\n        uuid=vm,\n        type=info_type\n    )\n    res = __salt__['cmd.run_all'](cmd)\n    retcode = res['retcode']\n    if retcode != 0:\n        ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode)\n        return ret\n    return salt.utils.json.loads(res['stdout'])",
    "docstring": "Lookup info on running kvm\n\n    vm : string\n        vm to be targeted\n    info_type : string [all|block|blockstats|chardev|cpus|kvm|pci|spice|version|vnc]\n        info type to return\n    key : string [uuid|alias|hostname]\n        value type of 'vm' parameter\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' vmadm.info 186da9ab-7392-4f55-91a5-b8f1fe770543\n        salt '*' vmadm.info 186da9ab-7392-4f55-91a5-b8f1fe770543 vnc\n        salt '*' vmadm.info nacl key=alias\n        salt '*' vmadm.info nacl vnc key=alias"
  },
  {
    "code": "def require(*requirements, **kwargs):\n    none_on_failure = kwargs.get('none_on_failure', False)\n    def inner(f):\n        @functools.wraps(f)\n        def wrapper(*args, **kwargs):\n            for req in requirements:\n                if none_on_failure:\n                    if not getattr(req, 'is_available'):\n                        return None\n                else:\n                    getattr(req, 'require')()\n            return f(*args, **kwargs)\n        return wrapper\n    return inner",
    "docstring": "Decorator that can be used to require requirements.\n\n    :param requirements: List of requirements that should be verified\n    :param none_on_failure: If true, does not raise a PrerequisiteFailedError, but instead returns None"
  },
  {
    "code": "def get_config(self, view = None):\n    path = self._path() + '/config'\n    resp = self._get_resource_root().get(path,\n        params = view and dict(view=view) or None)\n    return self._parse_svc_config(resp, view)",
    "docstring": "Retrieve the service's configuration.\n\n    Retrieves both the service configuration and role type configuration\n    for each of the service's supported role types. The role type\n    configurations are returned as a dictionary, whose keys are the\n    role type name, and values are the respective configuration dictionaries.\n\n    The 'summary' view contains strings as the dictionary values. The full\n    view contains ApiConfig instances as the values.\n\n    @param view: View to materialize ('full' or 'summary')\n    @return: 2-tuple (service config dictionary, role type configurations)"
  },
  {
    "code": "def calibration_template(self):\n        temp = {}\n        temp['tone_doc'] = self.tone_calibrator.stimulus.templateDoc()\n        comp_doc = []\n        for calstim in self.bs_calibrator.get_stims():\n            comp_doc.append(calstim.stateDict())\n        temp['noise_doc'] = comp_doc\n        return temp",
    "docstring": "Gets the template documentation for the both the tone curve calibration and noise calibration\n\n        :returns: dict -- all information necessary to recreate calibration objects"
  },
  {
    "code": "def startLoading(self):\r\n        if super(XBatchItem, self).startLoading():\r\n            tree = self.treeWidget()\r\n            if not isinstance(tree, XOrbTreeWidget):\r\n                self.takeFromTree()\r\n                return\r\n            next_batch = self.batch()\r\n            tree._loadBatch(self, next_batch)",
    "docstring": "Starts loading this item for the batch."
  },
  {
    "code": "def add_grammar(self,\n                    customization_id,\n                    grammar_name,\n                    grammar_file,\n                    content_type,\n                    allow_overwrite=None,\n                    **kwargs):\n        if customization_id is None:\n            raise ValueError('customization_id must be provided')\n        if grammar_name is None:\n            raise ValueError('grammar_name must be provided')\n        if grammar_file is None:\n            raise ValueError('grammar_file must be provided')\n        if content_type is None:\n            raise ValueError('content_type must be provided')\n        headers = {'Content-Type': content_type}\n        if 'headers' in kwargs:\n            headers.update(kwargs.get('headers'))\n        sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'add_grammar')\n        headers.update(sdk_headers)\n        params = {'allow_overwrite': allow_overwrite}\n        data = grammar_file\n        url = '/v1/customizations/{0}/grammars/{1}'.format(\n            *self._encode_path_vars(customization_id, grammar_name))\n        response = self.request(\n            method='POST',\n            url=url,\n            headers=headers,\n            params=params,\n            data=data,\n            accept_json=True)\n        return response",
    "docstring": "Add a grammar.\n\n        Adds a single grammar file to a custom language model. Submit a plain text file in\n        UTF-8 format that defines the grammar. Use multiple requests to submit multiple\n        grammar files. You must use credentials for the instance of the service that owns\n        a model to add a grammar to it. Adding a grammar does not affect the custom\n        language model until you train the model for the new data by using the **Train a\n        custom language model** method.\n        The call returns an HTTP 201 response code if the grammar is valid. The service\n        then asynchronously processes the contents of the grammar and automatically\n        extracts new words that it finds. This can take a few seconds to complete\n        depending on the size and complexity of the grammar, as well as the current load\n        on the service. You cannot submit requests to add additional resources to the\n        custom model or to train the model until the service's analysis of the grammar for\n        the current request completes. Use the **Get a grammar** method to check the\n        status of the analysis.\n        The service populates the model's words resource with any word that is recognized\n        by the grammar that is not found in the model's base vocabulary. These are\n        referred to as out-of-vocabulary (OOV) words. You can use the **List custom\n        words** method to examine the words resource and use other words-related methods\n        to eliminate typos and modify how words are pronounced as needed.\n        To add a grammar that has the same name as an existing grammar, set the\n        `allow_overwrite` parameter to `true`; otherwise, the request fails. Overwriting\n        an existing grammar causes the service to process the grammar file and extract OOV\n        words anew. Before doing so, it removes any OOV words associated with the existing\n        grammar from the model's words resource unless they were also added by another\n        resource or they have been modified in some way with the **Add custom words** or\n        **Add a custom word** method.\n        The service limits the overall amount of data that you can add to a custom model\n        to a maximum of 10 million total words from all sources combined. Also, you can\n        add no more than 30 thousand OOV words to a model. This includes words that the\n        service extracts from corpora and grammars and words that you add directly.\n        **See also:**\n        * [Working with grammars](https://cloud.ibm.com/docs/services/speech-to-text/)\n        * [Add grammars to the custom language\n        model](https://cloud.ibm.com/docs/services/speech-to-text/).\n\n        :param str customization_id: The customization ID (GUID) of the custom language\n        model that is to be used for the request. You must make the request with\n        credentials for the instance of the service that owns the custom model.\n        :param str grammar_name: The name of the new grammar for the custom language\n        model. Use a localized name that matches the language of the custom model and\n        reflects the contents of the grammar.\n        * Include a maximum of 128 characters in the name.\n        * Do not include spaces, slashes, or backslashes in the name.\n        * Do not use the name of an existing grammar or corpus that is already defined for\n        the custom model.\n        * Do not use the name `user`, which is reserved by the service to denote custom\n        words that are added or modified by the user.\n        :param str grammar_file: A plain text file that contains the grammar in the format\n        specified by the `Content-Type` header. Encode the file in UTF-8 (ASCII is a\n        subset of UTF-8). Using any other encoding can lead to issues when compiling the\n        grammar or to unexpected results in decoding. The service ignores an encoding that\n        is specified in the header of the grammar.\n        :param str content_type: The format (MIME type) of the grammar file:\n        * `application/srgs` for Augmented Backus-Naur Form (ABNF), which uses a\n        plain-text representation that is similar to traditional BNF grammars.\n        * `application/srgs+xml` for XML Form, which uses XML elements to represent the\n        grammar.\n        :param bool allow_overwrite: If `true`, the specified grammar overwrites an\n        existing grammar with the same name. If `false`, the request fails if a grammar\n        with the same name already exists. The parameter has no effect if a grammar with\n        the same name does not already exist.\n        :param dict headers: A `dict` containing the request headers\n        :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n        :rtype: DetailedResponse"
  },
  {
    "code": "def get_object_detail(self, request, obj):\n        if self.display_detail_fields:\n            display_fields = self.display_detail_fields\n        else:\n            display_fields = self.display_fields\n        data = self.serialize(obj, ['id'] + list(display_fields))\n        return HttpResponse(self.json_dumps(data), content_type='application/json')",
    "docstring": "Handles get requests for the details of the given object."
  },
  {
    "code": "def addSourceLocation(self, sourceLocationUri, weight):\n        assert isinstance(weight, (float, int)), \"weight value has to be a positive or negative integer\"\n        self.topicPage[\"sourceLocations\"].append({\"uri\": sourceLocationUri, \"wgt\": weight})",
    "docstring": "add a list of relevant sources by identifying them by their geographic location\n        @param sourceLocationUri: uri of the location where the sources should be geographically located\n        @param weight: importance of the provided list of sources (typically in range 1 - 50)"
  },
  {
    "code": "def systemInformationType13():\n    a = L2PseudoLength(l2pLength=0x00)\n    b = TpPd(pd=0x6)\n    c = MessageType(mesType=0x0)\n    d = Si13RestOctets()\n    packet = a / b / c / d\n    return packet",
    "docstring": "SYSTEM INFORMATION TYPE 13 Section 9.1.43a"
  },
  {
    "code": "def save_params(step_num, model, trainer, ckpt_dir):\n    param_path = os.path.join(ckpt_dir, '%07d.params'%step_num)\n    trainer_path = os.path.join(ckpt_dir, '%07d.states'%step_num)\n    logging.info('[step %d] Saving checkpoints to %s, %s.',\n                 step_num, param_path, trainer_path)\n    model.save_parameters(param_path)\n    trainer.save_states(trainer_path)",
    "docstring": "Save the model parameter, marked by step_num."
  },
  {
    "code": "def getXML(self):\n        s = ''\n        for element in self._svgElements:\n            s += element.getXML()\n        return s",
    "docstring": "Retrieves the pysvg elements that make up the turtles path and returns them as String in an xml representation."
  },
  {
    "code": "def eccentricity(self, directed=None, weighted=None):\n    sp = self.shortest_path(directed=directed, weighted=weighted)\n    return sp.max(axis=0)",
    "docstring": "Maximum distance from each vertex to any other vertex."
  },
  {
    "code": "def _MultiStream(cls, fds):\n    missing_chunks_by_fd = {}\n    for chunk_fd_pairs in collection.Batch(\n        cls._GenerateChunkPaths(fds), cls.MULTI_STREAM_CHUNKS_READ_AHEAD):\n      chunks_map = dict(chunk_fd_pairs)\n      contents_map = {}\n      for chunk_fd in FACTORY.MultiOpen(\n          chunks_map, mode=\"r\", token=fds[0].token):\n        if isinstance(chunk_fd, AFF4Stream):\n          fd = chunks_map[chunk_fd.urn]\n          contents_map[chunk_fd.urn] = chunk_fd.read()\n      for chunk_urn, fd in chunk_fd_pairs:\n        if chunk_urn not in contents_map or not contents_map[chunk_urn]:\n          missing_chunks_by_fd.setdefault(fd, []).append(chunk_urn)\n      for chunk_urn, fd in chunk_fd_pairs:\n        if fd in missing_chunks_by_fd:\n          continue\n        yield fd, contents_map[chunk_urn], None\n    for fd, missing_chunks in iteritems(missing_chunks_by_fd):\n      e = MissingChunksError(\n          \"%d missing chunks (multi-stream).\" % len(missing_chunks),\n          missing_chunks=missing_chunks)\n      yield fd, None, e",
    "docstring": "Effectively streams data from multiple opened AFF4ImageBase objects.\n\n    Args:\n      fds: A list of opened AFF4Stream (or AFF4Stream descendants) objects.\n\n    Yields:\n      Tuples (chunk, fd, exception) where chunk is a binary blob of data and fd\n      is an object from the fds argument.\n\n      If one or more chunks are missing, exception will be a MissingChunksError\n      while chunk will be None. _MultiStream does its best to skip the file\n      entirely if one of its chunks is missing, but in case of very large files\n      it's still possible to yield a truncated file."
  },
  {
    "code": "def get_batch_header_values(self):\n        lines = self.getOriginalFile().data.splitlines()\n        reader = csv.reader(lines)\n        batch_headers = batch_data = []\n        for row in reader:\n            if not any(row):\n                continue\n            if row[0].strip().lower() == 'batch header':\n                batch_headers = [x.strip() for x in row][1:]\n                continue\n            if row[0].strip().lower() == 'batch data':\n                batch_data = [x.strip() for x in row][1:]\n                break\n        if not (batch_data or batch_headers):\n            return None\n        if not (batch_data and batch_headers):\n            self.error(\"Missing batch headers or data\")\n            return None\n        values = dict(zip(batch_headers, batch_data))\n        return values",
    "docstring": "Scrape the \"Batch Header\" values from the original input file"
  },
  {
    "code": "def get(self, robj, r=None, pr=None, timeout=None, basic_quorum=None,\n            notfound_ok=None, head_only=False):\n        raise NotImplementedError",
    "docstring": "Fetches an object."
  },
  {
    "code": "def load(path: str) -> \"Store\":\n        if _gpg.is_encrypted(path):\n            src_bytes = _gpg.decrypt(path)\n        else:\n            src_bytes = open(path, \"rb\").read()\n        src = src_bytes.decode(\"utf-8\")\n        ext = _gpg.unencrypted_ext(path)\n        assert ext not in [\n            \".yml\",\n            \".yaml\",\n        ], \"YAML support was removed in version 0.12.0\"\n        entries = _parse_entries(src)\n        return Store(path, entries)",
    "docstring": "Load password store from file."
  },
  {
    "code": "def parse_spec(self):\n        recruiters = []\n        spec = get_config().get(\"recruiters\")\n        for match in self.SPEC_RE.finditer(spec):\n            name = match.group(1)\n            count = int(match.group(2))\n            recruiters.append((name, count))\n        return recruiters",
    "docstring": "Parse the specification of how to recruit participants.\n\n        Example: recruiters = bots: 5, mturk: 1"
  },
  {
    "code": "async def read_line(stream: asyncio.StreamReader) -> bytes:\n    line = await stream.readline()\n    if len(line) > MAX_LINE:\n        raise ValueError(\"Line too long\")\n    if not line.endswith(b\"\\r\\n\"):\n        raise ValueError(\"Line without CRLF\")\n    return line[:-2]",
    "docstring": "Read a single line from ``stream``.\n\n    ``stream`` is an :class:`~asyncio.StreamReader`.\n\n    Return :class:`bytes` without CRLF."
  },
  {
    "code": "def mousePressEvent(self, event):\r\n        self.parent.raise_()\r\n        self.raise_()\r\n        if event.button() == Qt.RightButton:\r\n            pass",
    "docstring": "override Qt method"
  },
  {
    "code": "def gunzip(gzip_file, file_gunzip=None):\n    if file_gunzip is None:\n        file_gunzip = os.path.splitext(gzip_file)[0]\n        gzip_open_to(gzip_file, file_gunzip)\n        return file_gunzip",
    "docstring": "Unzip .gz file. Return filename of unzipped file."
  },
  {
    "code": "def getKendallTauScore(myResponse, otherResponse):\n    kt = 0\n    list1 = myResponse.values()\n    list2 = otherResponse.values()\n    if len(list1) <= 1:\n        return kt\n    for itr1 in range(0, len(list1) - 1):\n        for itr2 in range(itr1 + 1, len(list2)):\n            if ((list1[itr1] > list1[itr2]\n                 and list2[itr1] < list2[itr2])\n                or (list1[itr1] < list1[itr2]\n                    and list2[itr1] > list2[itr2])):\n                kt += 1\n    kt = (kt * 2) / (len(list1) * (len(list1) - 1))\n    return kt",
    "docstring": "Returns the Kendall Tau Score"
  },
  {
    "code": "def return_standard_conf():\n    result = resource_string(__name__, 'daemon/dagobahd.yml')\n    result = result % {'app_secret': os.urandom(24).encode('hex')}\n    return result",
    "docstring": "Return the sample config file."
  },
  {
    "code": "def get_response_example(self, resp_spec):\n        if 'schema' in resp_spec.keys():\n            if '$ref' in resp_spec['schema']:\n                definition_name = self.get_definition_name_from_ref(resp_spec['schema']['$ref'])\n                return self.definitions_example[definition_name]\n            elif 'items' in resp_spec['schema'] and resp_spec['schema']['type'] == 'array':\n                if '$ref' in resp_spec['schema']['items']:\n                    definition_name = self.get_definition_name_from_ref(resp_spec['schema']['items']['$ref'])\n                else:\n                    if 'type' in resp_spec['schema']['items']:\n                        definition_name = self.get_definition_name_from_ref(resp_spec['schema']['items'])\n                        return [definition_name]\n                    else:\n                        logging.warn(\"No item type in: \" + resp_spec['schema'])\n                        return ''\n                return [self.definitions_example[definition_name]]\n            elif 'type' in resp_spec['schema']:\n                return self.get_example_from_prop_spec(resp_spec['schema'])\n        else:\n            return ''",
    "docstring": "Get a response example from a response spec."
  },
  {
    "code": "async def monitor_mode(self, poll_devices=False, device=None,\n                           workdir=None):\n        print(\"Running monitor mode\")\n        await self.connect(poll_devices, device, workdir)\n        self.plm.monitor_mode()",
    "docstring": "Place the IM in monitoring mode."
  },
  {
    "code": "def getSignalParameters(fitParams, n_std=3):\r\n    signal = getSignalPeak(fitParams)\r\n    mx = signal[1] + n_std * signal[2]\r\n    mn = signal[1] - n_std * signal[2]\r\n    if mn < fitParams[0][1]:\r\n        mn = fitParams[0][1]\n    return mn, signal[1], mx",
    "docstring": "return minimum, average, maximum of the signal peak"
  },
  {
    "code": "def set_series_resistance(self, channel, value, resistor_index=None):\n        if resistor_index is None:\n            resistor_index = self.series_resistor_index(channel)\n        try:\n            if channel == 0:\n                self.calibration.R_hv[resistor_index] = value\n            else:\n                self.calibration.R_fb[resistor_index] = value\n        except:\n            pass\n        return self._set_series_resistance(channel, value)",
    "docstring": "Set the current series resistance value for the specified channel.\n\n        Parameters\n        ----------\n        channel : int\n            Analog channel index.\n        value : float\n            Series resistance value.\n        resistor_index : int, optional\n            Series resistor channel index.\n\n            If :data:`resistor_index` is not specified, the resistor-index from\n            the current context _(i.e., the result of\n            :attr:`series_resistor_index`)_ is used.\n\n            Otherwise, the series-resistor is temporarily set to the value of\n            :data:`resistor_index` to set the resistance before restoring back\n            to the original value.\n\n            See definition of :meth:`safe_series_resistor_index_read`\n            decorator.\n\n        Returns\n        -------\n        int\n            Return code from embedded call."
  },
  {
    "code": "def join(self,timeout=None):\n        if timeout is None:\n            for thread in self.__threads:\n                thread.join()\n        else:\n            deadline = _time() + timeout\n            for thread in self.__threads:\n                delay = deadline - _time()\n                if delay <= 0:\n                    return False\n                if not thread.join(delay):\n                    return False\n        return True",
    "docstring": "Join all threads in this group.\n\n        If the optional \"timeout\" argument is given, give up after that many\n        seconds.  This method returns True is the threads were successfully\n        joined, False if a timeout occurred."
  },
  {
    "code": "def get_subreddit_image(self, subreddit, id):\n        url = self._base_url + \"/3/gallery/r/{0}/{1}\".format(subreddit, id)\n        resp = self._send_request(url)\n        return Gallery_image(resp, self)",
    "docstring": "Return the Gallery_image with the id submitted to subreddit gallery\n\n        :param subreddit: The subreddit the image has been submitted to.\n        :param id: The id of the image we want."
  },
  {
    "code": "def public(self):\n        req = self.request(self.mist_client.uri+'/keys/'+self.id+\"/public\")\n        public = req.get().json()\n        return public",
    "docstring": "Return the public ssh-key\n\n        :returns: The public ssh-key as string"
  },
  {
    "code": "def main():\n  r = Random(42)\n  startSerializationTime = time.time()\n  for i in xrange(_SERIALIZATION_LOOPS):\n    builderProto = RandomProto.new_message()\n    r.write(builderProto)\n  elapsedSerializationTime = time.time() - startSerializationTime\n  builderBytes = builderProto.to_bytes()\n  startDeserializationTime = time.time()\n  deserializationCount = 0\n  while deserializationCount < _DESERIALIZATION_LOOPS:\n    readerProto = RandomProto.from_bytes(\n      builderBytes,\n      traversal_limit_in_words=_TRAVERSAL_LIMIT_IN_WORDS,\n      nesting_limit=_NESTING_LIMIT)\n    numReads = min(_DESERIALIZATION_LOOPS - deserializationCount,\n                     _MAX_DESERIALIZATION_LOOPS_PER_READER)\n    for _ in xrange(numReads):\n      r.read(readerProto)\n    deserializationCount += numReads\n  elapsedDeserializationTime = time.time() - startDeserializationTime\n  print _SERIALIZATION_LOOPS, \"Serialization loops in\", \\\n        elapsedSerializationTime, \"seconds.\"\n  print \"\\t\", elapsedSerializationTime/_SERIALIZATION_LOOPS, \"seconds per loop.\"\n  print deserializationCount, \"Deserialization loops in\", \\\n        elapsedDeserializationTime, \"seconds.\"\n  print \"\\t\", elapsedDeserializationTime/deserializationCount, \"seconds per loop.\"",
    "docstring": "Measure capnp serialization performance of Random"
  },
  {
    "code": "async def parse_get_revoc_reg_def_response(get_revoc_ref_def_response: str) -> (str, str):\n    logger = logging.getLogger(__name__)\n    logger.debug(\"parse_get_revoc_reg_def_response: >>> get_revoc_ref_def_response: %r\", get_revoc_ref_def_response)\n    if not hasattr(parse_get_revoc_reg_def_response, \"cb\"):\n        logger.debug(\"parse_get_revoc_reg_def_response: Creating callback\")\n        parse_get_revoc_reg_def_response.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_char_p, c_char_p))\n    c_get_revoc_ref_def_response = c_char_p(get_revoc_ref_def_response.encode('utf-8'))\n    (revoc_reg_def_id, revoc_reg_def_json) = await do_call('indy_parse_get_revoc_reg_def_response',\n                                                           c_get_revoc_ref_def_response,\n                                                           parse_get_revoc_reg_def_response.cb)\n    res = (revoc_reg_def_id.decode(), revoc_reg_def_json.decode())\n    logger.debug(\"parse_get_revoc_reg_def_response: <<< res: %r\", res)\n    return res",
    "docstring": "Parse a GET_REVOC_REG_DEF response to get Revocation Registry Definition in the format compatible with Anoncreds API.\n\n    :param get_revoc_ref_def_response: response of GET_REVOC_REG_DEF request.\n    :return: Revocation Registry Definition Id and Revocation Registry Definition json.\n      {\n          \"id\": string - ID of the Revocation Registry,\n          \"revocDefType\": string - Revocation Registry type (only CL_ACCUM is supported for now),\n          \"tag\": string - Unique descriptive ID of the Registry,\n          \"credDefId\": string - ID of the corresponding CredentialDefinition,\n          \"value\": Registry-specific data {\n              \"issuanceType\": string - Type of Issuance(ISSUANCE_BY_DEFAULT or ISSUANCE_ON_DEMAND),\n              \"maxCredNum\": number - Maximum number of credentials the Registry can serve.\n              \"tailsHash\": string - Hash of tails.\n              \"tailsLocation\": string - Location of tails file.\n              \"publicKeys\": <public_keys> - Registry's public key.\n          },\n          \"ver\": string - version of revocation registry definition json.\n      }"
  },
  {
    "code": "def update(self):\n        console = self.console\n        aux = self.aux\n        state = yield from self._get_container_state()\n        yield from self.reset()\n        yield from self.create()\n        self.console = console\n        self.aux = aux\n        if state == \"running\":\n            yield from self.start()",
    "docstring": "Destroy an recreate the container with the new settings"
  },
  {
    "code": "def new_method_return(self) :\n        \"creates a new DBUS.MESSAGE_TYPE_METHOD_RETURN that is a reply to this Message.\"\n        result = dbus.dbus_message_new_method_return(self._dbobj)\n        if result == None :\n            raise CallFailed(\"dbus_message_new_method_return\")\n        return \\\n            type(self)(result)",
    "docstring": "creates a new DBUS.MESSAGE_TYPE_METHOD_RETURN that is a reply to this Message."
  },
  {
    "code": "def hull_moving_average(data, period):\n    catch_errors.check_for_period_error(data, period)\n    hma = wma(\n        2 * wma(data, int(period/2)) - wma(data, period), int(np.sqrt(period))\n        )\n    return hma",
    "docstring": "Hull Moving Average.\n\n    Formula:\n    HMA = WMA(2*WMA(n/2) - WMA(n)), sqrt(n)"
  },
  {
    "code": "def get_similar_items(self, items=None, k=10, verbose=False):\n        if items is None:\n            get_all_items = True\n            items = _SArray()\n        else:\n            get_all_items = False\n        if isinstance(items, list):\n            items = _SArray(items)\n        def check_type(arg, arg_name, required_type, allowed_types):\n            if not isinstance(arg, required_type):\n                raise TypeError(\"Parameter \" + arg_name + \" must be of type(s) \"\n                                + (\", \".join(allowed_types) )\n                                + \"; Type '\" + str(type(arg)) + \"' not recognized.\")\n        check_type(items, \"items\", _SArray, [\"SArray\", \"list\"])\n        check_type(k, \"k\", int, [\"int\"])\n        return self.__proxy__.get_similar_items(items, k, verbose, get_all_items)",
    "docstring": "Get the k most similar items for each item in items.\n\n        Each type of recommender has its own model for the similarity\n        between items. For example, the item_similarity_recommender will\n        return the most similar items according to the user-chosen\n        similarity; the factorization_recommender will return the\n        nearest items based on the cosine similarity between latent item\n        factors.\n\n        Parameters\n        ----------\n        items : SArray or list; optional\n            An :class:`~turicreate.SArray` or list of item ids for which to get\n            similar items. If 'None', then return the `k` most similar items for\n            all items in the training set.\n\n        k : int, optional\n            The number of similar items for each item.\n\n        verbose : bool, optional\n            Progress printing is shown.\n\n        Returns\n        -------\n        out : SFrame\n            A SFrame with the top ranked similar items for each item. The\n            columns `item`, 'similar', 'score' and 'rank', where\n            `item` matches the item column name specified at training time.\n            The 'rank' is between 1 and `k` and 'score' gives the similarity\n            score of that item. The value of the score depends on the method\n            used for computing item similarities.\n\n        Examples\n        --------\n\n        >>> sf = turicreate.SFrame({'user_id': [\"0\", \"0\", \"0\", \"1\", \"1\", \"2\", \"2\", \"2\"],\n                                  'item_id': [\"a\", \"b\", \"c\", \"a\", \"b\", \"b\", \"c\", \"d\"]})\n        >>> m = turicreate.item_similarity_recommender.create(sf)\n        >>> nn = m.get_similar_items()"
  },
  {
    "code": "def create_disk(name, size):\n    ret = False\n    cmd = 'vmctl create {0} -s {1}'.format(name, size)\n    result = __salt__['cmd.run_all'](cmd,\n                                     output_loglevel='trace',\n                                     python_shell=False)\n    if result['retcode'] == 0:\n        ret = True\n    else:\n        raise CommandExecutionError(\n            'Problem encountered creating disk image',\n            info={'errors': [result['stderr']], 'changes': ret}\n        )\n    return ret",
    "docstring": "Create a VMM disk with the specified `name` and `size`.\n\n    size:\n        Size in megabytes, or use a specifier such as M, G, T.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' vmctl.create_disk /path/to/disk.img size=10G"
  },
  {
    "code": "def _sethex(self, hexstring):\n        hexstring = tidy_input_string(hexstring)\n        hexstring = hexstring.replace('0x', '')\n        length = len(hexstring)\n        if length % 2:\n            hexstring += '0'\n        try:\n            try:\n                data = bytearray.fromhex(hexstring)\n            except TypeError:\n                data = bytearray.fromhex(unicode(hexstring))\n        except ValueError:\n            raise CreationError(\"Invalid symbol in hex initialiser.\")\n        self._setbytes_unsafe(data, length * 4, 0)",
    "docstring": "Reset the bitstring to have the value given in hexstring."
  },
  {
    "code": "def get_encodings():\n    encodings = [__salt_system_encoding__]\n    try:\n        sys_enc = sys.getdefaultencoding()\n    except ValueError:\n        sys_enc = None\n    if sys_enc and sys_enc not in encodings:\n        encodings.append(sys_enc)\n    for enc in ['utf-8', 'latin-1']:\n        if enc not in encodings:\n            encodings.append(enc)\n    return encodings",
    "docstring": "return a list of string encodings to try"
  },
  {
    "code": "def decrement(name, tags=None):\n    def wrap(f):\n        @wraps(f)\n        def decorator(*args, **kwargs):\n            stats = client()\n            ret = f(*args, **kwargs)\n            stats.decr(name, tags=tags)\n            return ret\n        return decorator\n    return wrap",
    "docstring": "Function decorator for decrementing a statsd stat whenever\n    a function is invoked.\n\n    >>> from statsdecor.decorators import decrement\n    >>> @decrement('my.metric')\n    >>> def my_func():\n    >>>     pass"
  },
  {
    "code": "def get_credit_notes_per_page(self, per_page=1000, page=1, params=None):\n        return self._get_resource_per_page(resource=CREDIT_NOTES, per_page=per_page, page=page, params=params)",
    "docstring": "Get credit notes per page\n\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :param params: Search parameters. Default: {}\n        :return: list"
  },
  {
    "code": "def list_team_codes():\n    cleanlist = sorted(TEAM_DATA, key=lambda k: (k[\"league\"][\"name\"], k[\"code\"]))\n    leaguenames = sorted(list(set([team[\"league\"][\"name\"] for team in cleanlist])))\n    for league in leaguenames:\n        teams = [team for team in cleanlist if team[\"league\"][\"name\"] == league]\n        click.secho(league, fg=\"green\", bold=True)\n        for team in teams:\n            if team[\"code\"] != \"null\":\n                click.secho(u\"{0}: {1}\".format(team[\"code\"], team[\"name\"]), fg=\"yellow\")\n        click.secho(\"\")",
    "docstring": "List team names in alphabetical order of team ID, per league."
  },
  {
    "code": "def on_purchase_completed(self, mapping={'payload': 'payload','name':'name','status':'status','token':'token'}, convert={}, default={}):\n        def decorator(f):\n            self._intent_view_funcs['Connections.Response'] = f\n            self._intent_mappings['Connections.Response'] = mapping\n            self._intent_converts['Connections.Response'] = convert\n            self._intent_defaults['Connections.Response'] = default\n            @wraps(f)\n            def wrapper(*args, **kwargs):\n                self._flask_view_func(*args, **kwargs)\n            return f\n        return decorator",
    "docstring": "Decorator routes an Connections.Response  to the wrapped function.\n\n        Request is sent when Alexa completes the purchase flow. \n        See https://developer.amazon.com/docs/in-skill-purchase/add-isps-to-a-skill.html#handle-results \n\n\n        The wrapped view function may accept parameters from the  Request.\n        In addition to locale, requestId, timestamp, and type\n        \n\n        @ask.on_purchase_completed( mapping={'payload': 'payload','name':'name','status':'status','token':'token'})\n        def completed(payload, name, status, token):\n            logger.info(payload)\n            logger.info(name)\n            logger.info(status)\n            logger.info(token)"
  },
  {
    "code": "def related_to(self):\n        params = []\n        constraints = self.in_constraints\n        if self.is_constraint is not None:\n            constraints.append(self.is_constraint)\n        for constraint in constraints:\n            for var in constraint._vars:\n                param = var.get_parameter()\n                if param not in params and param.uniqueid != self.uniqueid:\n                    params.append(param)\n        return params",
    "docstring": "returns a list of all parameters that are either constrained by or constrain this parameter"
  },
  {
    "code": "def has_port_by_ref(self, port_ref):\n        with self._mutex:\n            if self.get_port_by_ref(self, port_ref):\n                return True\n            return False",
    "docstring": "Check if this component has a port by the given reference to a CORBA\n        PortService object."
  },
  {
    "code": "def assure_image(fnc):\n    @wraps(fnc)\n    def _wrapped(self, img, *args, **kwargs):\n        if not isinstance(img, Image):\n            img = self._manager.get(img)\n        return fnc(self, img, *args, **kwargs)\n    return _wrapped",
    "docstring": "Converts a image ID passed as the 'image' parameter to a image object."
  },
  {
    "code": "def is_valid(self, name=None, debug=False):\n        valid_tags = self.action_tree\n        invalid = False\n        for item in self.current_tree:\n            try:\n                if item in valid_tags or self.ALL_TAGS in valid_tags:\n                    valid_tags = valid_tags[item if item in valid_tags else self.ALL_TAGS]\n                else:\n                    valid_tags = None\n                    invalid = True\n                    break\n            except (KeyError, TypeError) as e:\n                invalid = True\n                break\n        if debug:\n            print name, not invalid and valid_tags is not None\n        return not invalid and valid_tags is not None",
    "docstring": "Check to see if the current xml path is to be processed."
  },
  {
    "code": "def update_status(self):\n        task = self.make_request(\n            TaskRunFailed,\n            href=self.href)\n        return Task(task)",
    "docstring": "Gets the current status of this task and returns a\n        new task object.\n\n        :raises TaskRunFailed: fail to update task status"
  },
  {
    "code": "def nmb_weights_hidden(self) -> int:\n        nmb = 0\n        for idx_layer in range(self.nmb_layers-1):\n            nmb += self.nmb_neurons[idx_layer] * self.nmb_neurons[idx_layer+1]\n        return nmb",
    "docstring": "Number of hidden weights.\n\n        >>> from hydpy import ANN\n        >>> ann = ANN(None)\n        >>> ann(nmb_inputs=2, nmb_neurons=(4, 3, 2), nmb_outputs=3)\n        >>> ann.nmb_weights_hidden\n        18"
  },
  {
    "code": "def get_sampleS(self, res, DS=None, resMode='abs',\n                    ind=None, offsetIn=0., Out='(X,Y,Z)', Ind=None):\n        if Ind is not None:\n            assert self.dgeom['Multi']\n        kwdargs = dict(DS=DS, dSMode=resMode, ind=ind, DIn=offsetIn,\n                       VIn=self.dgeom['VIn'], VType=self.Id.Type,\n                       VLim=np.ascontiguousarray(self.Lim), nVLim=self.noccur,\n                       Out=Out, margin=1.e-9,\n                       Multi=self.dgeom['Multi'], Ind=Ind)\n        args = [self.Poly, self.dgeom['P1Min'][0], self.dgeom['P1Max'][0],\n                self.dgeom['P2Min'][1], self.dgeom['P2Max'][1], res]\n        pts, dS, ind, reseff = _comp._Ves_get_sampleS(*args, **kwdargs)\n        return pts, dS, ind, reseff",
    "docstring": "Sample, with resolution res, the surface defined by DS or ind\n\n        An optionnal offset perpendicular to the surface can be used\n        (offsetIn>0 => inwards)\n\n        Parameters\n        ----------\n        res     :   float / list of 2 floats\n            Desired resolution of the surfacic sample\n                float   : same resolution for all directions of the sample\n                list    : [dl,dXPhi] where:\n                    dl      : res. along polygon contours (cross-section)\n                    dXPhi   : res. along axis (toroidal/linear direction)\n        DS      :   None / list of 3 lists of 2 floats\n            Limits of the domain in which the sample should be computed\n                None : whole surface of the object\n                list : [D1,D2,D3], where Di is a len()=2 list\n                       (increasing floats, setting limits along coordinate i)\n                    [DR,DZ,DPhi]: in toroidal geometry (self.Id.Type=='Tor')\n                    [DX,DY,DZ]  : in linear geometry (self.Id.Type=='Lin')\n        resMode  :   str\n            Flag, specifies if res is absolute or relative to element sizes\n                'abs'   :   res is an absolute distance\n                'rel'   :   if res=0.1, each polygon segment is divided in 10,\n                            as is the toroidal/linear length\n        ind     :   None / np.ndarray of int\n            If provided, DS is ignored and the sample points corresponding to\n            the provided indices are returned\n            Example (assuming obj is a Ves object)\n                > # We create a 5x5 cm2 sample of the whole surface\n                > pts, dS, ind, reseff = obj.get_sample(0.05)\n                > # Perform operations, save only the points indices (save space)\n                > ...\n                > # Retrieve the points from their indices (requires same res)\n                > pts2, dS2, ind2, reseff2 = obj.get_sample(0.05, ind=ind)\n                > np.allclose(pts,pts2)\n                True\n        offsetIn:   float\n            Offset distance from the actual surface of the object\n            Inwards if positive\n            Useful to avoid numerical errors\n        Out     :   str\n            Flag indicating the coordinate system of returned points\n            e.g. : '(X,Y,Z)' or '(R,Z,Phi)'\n        Ind     :   None / iterable of ints\n            Array of indices of the entities to be considered\n            (only when multiple entities, i.e.: self.nLim>1)\n\n        Returns\n        -------\n        pts     :   np.ndarray / list of np.ndarrays\n            Sample points coordinates, as a (3,N) array.\n            A list is returned if the object has multiple entities\n        dS      :   np.ndarray / list of np.ndarrays\n            The surface (in m^2) associated to each point\n        ind     :   np.ndarray / list of np.ndarrays\n            The index of each point\n        reseff  :   np.ndarray / list of np.ndarrays\n            Effective resolution in both directions after sample computation"
  },
  {
    "code": "def rolling_window(a, axis, window, center, fill_value):\n    pads = [(0, 0) for s in a.shape]\n    if center:\n        start = int(window / 2)\n        end = window - 1 - start\n        pads[axis] = (start, end)\n    else:\n        pads[axis] = (window - 1, 0)\n    a = np.pad(a, pads, mode='constant', constant_values=fill_value)\n    return _rolling_window(a, window, axis)",
    "docstring": "rolling window with padding."
  },
  {
    "code": "def check_dimensions(self, dataset):\n        results = []\n        required_ctx = TestCtx(BaseCheck.HIGH, 'All geophysical variables are timeseries-profile-orthogonal feature types')\n        message = '{} must be a valid profile-orthogonal feature type. It must have dimensions of (station, time, z).'\n        message += ' If it\\'s a single station, it must have dimensions (time, z). x and y dimensions must be scalar or have'\n        message += ' dimensions (station). time must be a coordinate variable with dimension (time) and z must be a'\n        message += ' coordinate variabel with dimension (z).'\n        for variable in util.get_geophysical_variables(dataset):\n            is_valid = util.is_timeseries_profile_single_station(dataset, variable)\n            is_valid = is_valid or util.is_timeseries_profile_multi_station(dataset, variable)\n            required_ctx.assert_true(\n                is_valid,\n                message.format(variable)\n            )\n        results.append(required_ctx.to_result())\n        return results",
    "docstring": "Checks that the feature types of this dataset are consistent with a timeseries-profile-orthogonal dataset.\n\n        :param netCDF4.Dataset dataset: An open netCDF dataset"
  },
  {
    "code": "def tabLayout(self):\n        self.childWindow.column += 1\n        if self.childWindow.column > Layout.BUTTONS_NUMBER:\n            self.childWindow.column = 0\n            self.childWindow.row += 1",
    "docstring": "For all tabs, specify the number of buttons in a row"
  },
  {
    "code": "def add_mongo_config_simple(app, connection_string, collection_name):\n    split_string = connection_string.split(\":\")\n    config = {\"host\": \"localhost\", \"port\": 27017, \"db\": \"sacred\"}\n    if len(split_string) > 0 and len(split_string[-1]) > 0:\n        config[\"db\"] = split_string[-1]\n    if len(split_string) > 1:\n        config[\"port\"] = int(split_string[-2])\n    if len(split_string) > 2:\n        config[\"host\"] = split_string[-3]\n    app.config[\"data\"] = PyMongoDataAccess.build_data_access(\n        config[\"host\"], config[\"port\"], config[\"db\"], collection_name)",
    "docstring": "Configure the app to use MongoDB.\n\n    :param app: Flask Application\n    :type app: Flask\n    :param connection_string: in format host:port:database or database\n            (default: sacred)\n    :type connection_string: str\n\n    :param collection_name: Name of the collection\n    :type collection_name: str"
  },
  {
    "code": "def draw(self):\n        from calysto.display import display, clear_output\n        canvas = self.render()\n        clear_output(wait=True)\n        display(canvas)",
    "docstring": "Render and draw the world and robots."
  },
  {
    "code": "def unnest_collection(collection, df_list):\n    for item in collection['link']['item']:\n        if item['class'] == 'dataset':\n            df_list.append(Dataset.read(item['href']).write('dataframe'))\n        elif item['class'] == 'collection':\n            nested_collection = request(item['href'])\n            unnest_collection(nested_collection, df_list)",
    "docstring": "Unnest collection structure extracting all its datasets and converting \\\n       them to Pandas Dataframes.\n\n          Args:\n            collection (OrderedDict): data in JSON-stat format, previously \\\n                                      deserialized to a python object by \\\n                                      json.load() or json.loads(),\n            df_list (list): list variable which will contain the converted \\\n                            datasets.\n\n          Returns:\n            Nothing."
  },
  {
    "code": "def handle_existing_user(self, provider, user, access, info):\n        \"Login user and redirect.\"\n        login(self.request, user)\n        return redirect(self.get_login_redirect(provider, user, access))",
    "docstring": "Login user and redirect."
  },
  {
    "code": "def calcChebyshev(coeffs, validDomain, freqs):\n    logger = logging.getLogger(__name__)\n    domain = (validDomain[1] - validDomain[0])[0]\n    bins = -1 + 2* n.array([ (freqs[i]-validDomain[0,i])/domain for i in range(len(freqs))])\n    ncoeffs = len(coeffs[0])/2\n    rr = n.array([n.polynomial.chebyshev.chebval(bins[i], coeffs[i,:ncoeffs]) for i in range(len(coeffs))])\n    ll = n.array([n.polynomial.chebyshev.chebval(bins[i], coeffs[i,ncoeffs:]) for i in range(len(coeffs))])\n    return rr,ll",
    "docstring": "Given a set of coefficients,\n    this method evaluates a Chebyshev approximation.\n    Used for CASA bandpass reading.\n    input coeffs and freqs are numpy arrays"
  },
  {
    "code": "def install(*pkgs, **kwargs):\n    attributes = kwargs.get('attributes', False)\n    if not pkgs:\n        return \"Plese specify a package or packages to upgrade\"\n    cmd = _quietnix()\n    cmd.append('--install')\n    if kwargs.get('attributes', False):\n        cmd.extend(_zip_flatten('--attr', pkgs))\n    else:\n        cmd.extend(pkgs)\n    out = _run(cmd)\n    installs = list(itertools.chain.from_iterable(\n        [s.split()[1:] for s in out['stderr'].splitlines()\n         if s.startswith('installing')]\n        ))\n    return [_strip_quotes(s) for s in installs]",
    "docstring": "Installs a single or multiple packages via nix\n\n    :type pkgs: list(str)\n    :param pkgs:\n        packages to update\n    :param bool attributes:\n        Pass the list of packages or single package as attribues, not package names.\n        default: False\n\n    :return: Installed packages. Example element: ``gcc-3.3.2``\n    :rtype: list(str)\n\n    .. code-block:: bash\n\n        salt '*' nix.install package [package2 ...]\n        salt '*' nix.install attributes=True attr.name [attr.name2 ...]"
  },
  {
    "code": "def toFilename(url):\n    urlp = urlparse(url)\n    path = urlp.path\n    if not path:\n        path = \"file_{}\".format(int(time.time()))\n    value = re.sub(r'[^\\w\\s\\.\\-]', '-', path).strip().lower()\n    return re.sub(r'[-\\s]+', '-', value).strip(\"-\")[-200:]",
    "docstring": "gets url and returns filename"
  },
  {
    "code": "def compute_positive_association(self, visible,\n                                     hidden_probs, hidden_states):\n        if self.visible_unit_type == 'bin':\n            positive = tf.matmul(tf.transpose(visible), hidden_states)\n        elif self.visible_unit_type == 'gauss':\n            positive = tf.matmul(tf.transpose(visible), hidden_probs)\n        else:\n            positive = None\n        return positive",
    "docstring": "Compute positive associations between visible and hidden units.\n\n        :param visible: visible units\n        :param hidden_probs: hidden units probabilities\n        :param hidden_states: hidden units states\n        :return: positive association = dot(visible.T, hidden)"
  },
  {
    "code": "def FromArchive(cls, path, actions_dict, resources_dict, temp_dir=None):\n        if not path.endswith(\".ship\"):\n            raise ArgumentError(\"Attempted to unpack a recipe archive from a file that did not end in .ship\", path=path)\n        name = os.path.basename(path)[:-5]\n        if temp_dir is None:\n            temp_dir = tempfile.mkdtemp()\n        extract_path = os.path.join(temp_dir, name)\n        archive = zipfile.ZipFile(path, \"r\")\n        archive.extractall(extract_path)\n        recipe_yaml = os.path.join(extract_path, 'recipe_script.yaml')\n        return cls.FromFile(recipe_yaml, actions_dict, resources_dict, name=name)",
    "docstring": "Create a RecipeObject from a .ship archive.\n\n        This archive should have been generated from a previous call to\n        iotile-ship -a <path to yaml file>\n\n        or via iotile-build using autobuild_shiparchive().\n\n        Args:\n            path (str): The path to the recipe file that we wish to load\n            actions_dict (dict): A dictionary of named RecipeActionObject\n                types that is used to look up all of the steps listed in\n                the recipe file.\n            resources_dict (dict): A dictionary of named RecipeResource types\n                that is used to look up all of the shared resources listed in\n                the recipe file.\n            file_format (str): The file format of the recipe file.  Currently\n                we only support yaml.\n            temp_dir (str): An optional temporary directory where this archive\n                should be unpacked. Otherwise a system wide temporary directory\n                is used."
  },
  {
    "code": "def absent(name, driver=None):\n    ret = {'name': name,\n           'changes': {},\n           'result': False,\n           'comment': ''}\n    volume = _find_volume(name)\n    if not volume:\n        ret['result'] = True\n        ret['comment'] = 'Volume \\'{0}\\' already absent'.format(name)\n        return ret\n    try:\n        ret['changes']['removed'] = __salt__['docker.remove_volume'](name)\n        ret['result'] = True\n    except Exception as exc:\n        ret['comment'] = ('Failed to remove volume \\'{0}\\': {1}'\n                          .format(name, exc))\n    return ret",
    "docstring": "Ensure that a volume is absent.\n\n    .. versionadded:: 2015.8.4\n    .. versionchanged:: 2017.7.0\n        This state was renamed from **docker.volume_absent** to **docker_volume.absent**\n\n    name\n        Name of the volume\n\n    Usage Examples:\n\n    .. code-block:: yaml\n\n        volume_foo:\n          docker_volume.absent"
  },
  {
    "code": "def hl_canvas2table_box(self, canvas, tag):\n        self.treeview.clear_selection()\n        cobj = canvas.get_object_by_tag(tag)\n        if cobj.kind != 'rectangle':\n            return\n        canvas.delete_object_by_tag(tag, redraw=False)\n        if self.maskhltag:\n            try:\n                canvas.delete_object_by_tag(self.maskhltag, redraw=True)\n            except Exception:\n                pass\n        try:\n            obj = canvas.get_object_by_tag(self.masktag)\n        except Exception:\n            return\n        if obj.kind != 'compound':\n            return\n        if len(self._maskobjs) == 0:\n            return\n        for i, mobj in enumerate(self._maskobjs):\n            mask1 = self._rgbtomask(mobj)\n            rgbimage = mobj.get_image()\n            mask2 = rgbimage.get_shape_mask(cobj)\n            if np.any(mask1 & mask2):\n                self._highlight_path(self._treepaths[i])",
    "docstring": "Highlight all masks inside user drawn box on table."
  },
  {
    "code": "def get_keyword_query(self, **kw):\n        query = dict()\n        indexes = self.catalog.get_indexes()\n        for k, v in kw.iteritems():\n            if k.lower() == \"uid\":\n                k = \"UID\"\n            if k.lower() == \"portal_type\":\n                if v:\n                    v = _.to_list(v)\n            if k not in indexes:\n                logger.warn(\"Skipping unknown keyword parameter '%s=%s'\" % (k, v))\n                continue\n            if v is None:\n                logger.warn(\"Skip None value in kw parameter '%s=%s'\" % (k, v))\n                continue\n            logger.debug(\"Adding '%s=%s' to query\" % (k, v))\n            query[k] = v\n        return query",
    "docstring": "Generates a query from the given keywords.\n        Only known indexes make it into the generated query.\n\n        :returns: Catalog query\n        :rtype: dict"
  },
  {
    "code": "def copy_data_ext(self, model, field, dest=None, idx=None, astype=None):\n        if not dest:\n            dest = field\n        assert dest not in self._states + self._algebs\n        self.__dict__[dest] = self.read_data_ext(\n            model, field, idx, astype=astype)\n        if idx is not None:\n            if len(idx) == self.n:\n                self.link_to(model, idx, self.idx)",
    "docstring": "Retrieve the field of another model and store it as a field.\n\n        :param model: name of the source model being a model name or a group name\n        :param field: name of the field to retrieve\n        :param dest: name of the destination field in ``self``\n        :param idx: idx of elements to access\n        :param astype: type cast\n\n        :type model: str\n        :type field: str\n        :type dest: str\n        :type idx: list, matrix\n        :type astype: None, list, matrix\n\n        :return: None"
  },
  {
    "code": "def to_bed(call, sample, work_dir, calls, data):\n    out_file = os.path.join(work_dir, \"%s-%s-flat.bed\" % (sample, call[\"variantcaller\"]))\n    if call.get(\"vrn_file\") and not utils.file_uptodate(out_file, call[\"vrn_file\"]):\n        with file_transaction(data, out_file) as tx_out_file:\n            convert_fn = CALLER_TO_BED.get(call[\"variantcaller\"])\n            if convert_fn:\n                vrn_file = call[\"vrn_file\"]\n                if call[\"variantcaller\"] in SUBSET_BY_SUPPORT:\n                    ecalls = [x for x in calls if x[\"variantcaller\"] in SUBSET_BY_SUPPORT[call[\"variantcaller\"]]]\n                    if len(ecalls) > 0:\n                        vrn_file = _subset_by_support(call[\"vrn_file\"], ecalls, data)\n                convert_fn(vrn_file, call[\"variantcaller\"], tx_out_file)\n    if utils.file_exists(out_file):\n        return out_file",
    "docstring": "Create a simplified BED file from caller specific input."
  },
  {
    "code": "def vlog(self, msg, *args):\n        if self.verbose:\n            self.log(msg, *args)",
    "docstring": "Logs a message to stderr only if verbose is enabled."
  },
  {
    "code": "def calc_sasa(dssp_df):\n    infodict = {'ssb_sasa': dssp_df.exposure_asa.sum(),\n                'ssb_mean_rel_exposed': dssp_df.exposure_rsa.mean(),\n                'ssb_size': len(dssp_df)}\n    return infodict",
    "docstring": "Calculation of SASA utilizing the DSSP program.\n\n    DSSP must be installed for biopython to properly call it.\n    Install using apt-get on Ubuntu\n    or from: http://swift.cmbi.ru.nl/gv/dssp/\n\n    Input: PDB or CIF structure file\n    Output: SASA (integer) of structure"
  },
  {
    "code": "def update(self, sensor, reading):\n        parents = list(self._child_to_parents[sensor])\n        for parent in parents:\n            self.recalculate(parent, (sensor,))",
    "docstring": "Update callback used by sensors to notify obervers of changes.\n\n        Parameters\n        ----------\n        sensor : :class:`katcp.Sensor` object\n            The sensor whose value has changed.\n        reading : (timestamp, status, value) tuple\n            Sensor reading as would be returned by sensor.read()"
  },
  {
    "code": "def random_id(length):\n    def char():\n        return random.choice(string.ascii_letters + string.digits)\n    return \"\".join(char() for _ in range(length))",
    "docstring": "Generates a random ID of given length"
  },
  {
    "code": "def free_cache(ctx, *elts):\n    for elt in elts:\n        if isinstance(elt, Hashable):\n            cache = __STATIC_ELEMENTS_CACHE__\n        else:\n            cache = __UNHASHABLE_ELTS_CACHE__\n            elt = id(elt)\n        if elt in cache:\n            del cache[elt]\n    if not elts:\n        __STATIC_ELEMENTS_CACHE__.clear()\n        __UNHASHABLE_ELTS_CACHE__.clear()",
    "docstring": "Free properties bound to input cached elts. If empty, free the whole\n    cache."
  },
  {
    "code": "def maybe_inspect_zip(models):\n    r\n    if not(is_zip_file(models)):\n        return models\n    if len(models) > 1:\n        return models\n    if len(models) < 1:\n        raise AssertionError('No models at all')\n    return zipfile.ZipFile(models[0]).namelist()",
    "docstring": "r'''\n    Detect if models is a list of protocolbuffer files or a ZIP file.\n    If the latter, then unzip it and return the list of protocolbuffer files\n    that were inside."
  },
  {
    "code": "def after_model_change(self, form, User, is_created):\n        if is_created and form.notification.data is True:\n            send_reset_password_instructions(User)",
    "docstring": "Send password instructions if desired."
  },
  {
    "code": "def create_relationship(manager, handle_id, other_handle_id, rel_type):\n    meta_type = get_node_meta_type(manager, handle_id)\n    if meta_type == 'Location':\n        return create_location_relationship(manager, handle_id, other_handle_id, rel_type)\n    elif meta_type == 'Logical':\n        return create_logical_relationship(manager, handle_id, other_handle_id, rel_type)\n    elif meta_type == 'Relation':\n        return create_relation_relationship(manager, handle_id, other_handle_id, rel_type)\n    elif meta_type == 'Physical':\n        return create_physical_relationship(manager, handle_id, other_handle_id, rel_type)\n    other_meta_type = get_node_meta_type(manager, other_handle_id)\n    raise exceptions.NoRelationshipPossible(handle_id, meta_type, other_handle_id, other_meta_type, rel_type)",
    "docstring": "Makes a relationship from node to other_node depending on which\n    meta_type the nodes are. Returns the relationship or raises\n    NoRelationshipPossible exception."
  },
  {
    "code": "def highlightBlock(self, string):\n        prev_data = self.currentBlock().previous().userData()\n        if prev_data is not None:\n            self._lexer._saved_state_stack = prev_data.syntax_stack\n        elif hasattr(self._lexer, '_saved_state_stack'):\n            del self._lexer._saved_state_stack\n        index = 0\n        for token, text in self._lexer.get_tokens(string):\n            length = len(text)\n            self.setFormat(index, length, self._get_format(token))\n            index += length\n        if hasattr(self._lexer, '_saved_state_stack'):\n            data = PygmentsBlockUserData(\n                syntax_stack=self._lexer._saved_state_stack)\n            self.currentBlock().setUserData(data)\n            del self._lexer._saved_state_stack",
    "docstring": "Highlight a block of text."
  },
  {
    "code": "def get_alt_lengths(self):\n        out = []\n        for i in six.moves.range(len(self.genotype)):\n            valid_alt = self.get_alt_length(individual=i)\n            if not valid_alt:\n                out.append(None)\n            else:\n                out.append(max(valid_alt)-len(self.ref))\n        return out",
    "docstring": "Returns the longest length of the variant. For deletions, return is negative,\n        SNPs return 0, and insertions are +. None return corresponds to no variant in interval\n        for specified individual"
  },
  {
    "code": "def beautify_file(self, path):\n        error = False\n        if(path == '-'):\n            data = sys.stdin.read()\n            result, error = self.beautify_string(data, '(stdin)')\n            sys.stdout.write(result)\n        else:\n            data = self.read_file(path)\n            result, error = self.beautify_string(data, path)\n            if(data != result):\n                if(self.check_only):\n                    if not error:\n                        error = (result != data)\n                else:\n                    if(self.backup):\n                        self.write_file(path+'.bak', data)\n                    self.write_file(path, result)\n        return error",
    "docstring": "Beautify bash script file."
  },
  {
    "code": "def __cloudflare_list_zones(self, *, account, **kwargs):\n        done = False\n        zones = []\n        page = 1\n        while not done:\n            kwargs['page'] = page\n            response = self.__cloudflare_request(account=account, path='/zones', args=kwargs)\n            info = response['result_info']\n            if 'total_pages' not in info or page == info['total_pages']:\n                done = True\n            else:\n                page += 1\n            zones += response['result']\n        return zones",
    "docstring": "Helper function to list all zones registered in the CloudFlare system. Returns a `list` of the zones\n\n        Args:\n            account (:obj:`CloudFlareAccount`): A CloudFlare Account object\n            **kwargs (`dict`): Extra arguments to pass to the API endpoint\n\n        Returns:\n            `list` of `dict`"
  },
  {
    "code": "def _get_vm_by_name(name, allDetails=False):\n    vms = get_resources_vms(includeConfig=allDetails)\n    if name in vms:\n        return vms[name]\n    log.info('VM with name \"%s\" could not be found.', name)\n    return False",
    "docstring": "Since Proxmox works based op id's rather than names as identifiers this\n    requires some filtering to retrieve the required information."
  },
  {
    "code": "def network_lopf(network, snapshots=None, solver_name=\"glpk\", solver_io=None,\n                 skip_pre=False, extra_functionality=None, solver_logfile=None, solver_options={},\n                 keep_files=False, formulation=\"angles\", ptdf_tolerance=0.,\n                 free_memory={},extra_postprocessing=None):\n    snapshots = _as_snapshots(network, snapshots)\n    network_lopf_build_model(network, snapshots, skip_pre=skip_pre,\n                             formulation=formulation, ptdf_tolerance=ptdf_tolerance)\n    if extra_functionality is not None:\n        extra_functionality(network,snapshots)\n    network_lopf_prepare_solver(network, solver_name=solver_name,\n                                solver_io=solver_io)\n    return network_lopf_solve(network, snapshots, formulation=formulation,\n                              solver_logfile=solver_logfile, solver_options=solver_options,\n                              keep_files=keep_files, free_memory=free_memory,\n                              extra_postprocessing=extra_postprocessing)",
    "docstring": "Linear optimal power flow for a group of snapshots.\n\n    Parameters\n    ----------\n    snapshots : list or index slice\n        A list of snapshots to optimise, must be a subset of\n        network.snapshots, defaults to network.snapshots\n    solver_name : string\n        Must be a solver name that pyomo recognises and that is\n        installed, e.g. \"glpk\", \"gurobi\"\n    solver_io : string, default None\n        Solver Input-Output option, e.g. \"python\" to use \"gurobipy\" for\n        solver_name=\"gurobi\"\n    skip_pre: bool, default False\n        Skip the preliminary steps of computing topology, calculating\n        dependent values and finding bus controls.\n    extra_functionality : callable function\n        This function must take two arguments\n        `extra_functionality(network,snapshots)` and is called after\n        the model building is complete, but before it is sent to the\n        solver. It allows the user to\n        add/change constraints and add/change the objective function.\n    solver_logfile : None|string\n        If not None, sets the logfile option of the solver.\n    solver_options : dictionary\n        A dictionary with additional options that get passed to the solver.\n        (e.g. {'threads':2} tells gurobi to use only 2 cpus)\n    keep_files : bool, default False\n        Keep the files that pyomo constructs from OPF problem\n        construction, e.g. .lp file - useful for debugging\n    formulation : string\n        Formulation of the linear power flow equations to use; must be\n        one of [\"angles\",\"cycles\",\"kirchhoff\",\"ptdf\"]\n    ptdf_tolerance : float\n        Value below which PTDF entries are ignored\n    free_memory : set, default {'pyomo'}\n        Any subset of {'pypsa', 'pyomo'}. Allows to stash `pypsa` time-series\n        data away while the solver runs (as a pickle to disk) and/or free\n        `pyomo` data after the solution has been extracted.\n    extra_postprocessing : callable function\n        This function must take three arguments\n        `extra_postprocessing(network,snapshots,duals)` and is called after\n        the model has solved and the results are extracted. It allows the user to\n        extract further information about the solution, such as additional shadow prices.\n\n    Returns\n    -------\n    None"
  },
  {
    "code": "def get_fitness(self, chromosome):\n        fitness = self.fitness_cache.get(chromosome.dna)\n        if fitness is None:\n            fitness = self.eval_fitness(chromosome)\n            self.fitness_cache[chromosome.dna] = fitness\n        return fitness",
    "docstring": "Get the fitness score for a chromosome, using the cached value if available."
  },
  {
    "code": "def run_shell(args: dict) -> int:\n    if args.get('project_directory'):\n        return run_batch(args)\n    shell = CauldronShell()\n    if in_project_directory():\n        shell.cmdqueue.append('open \"{}\"'.format(os.path.realpath(os.curdir)))\n    shell.cmdloop()\n    return 0",
    "docstring": "Run the shell sub command"
  },
  {
    "code": "def timeout(limit, handler):\n    def wrapper(f):\n        def wrapped_f(*args, **kwargs):\n            old_handler = signal.getsignal(signal.SIGALRM)\n            signal.signal(signal.SIGALRM, timeout_handler)\n            signal.alarm(limit)\n            try:\n                res = f(*args, **kwargs)\n            except Timeout:\n                handler(limit, f, args, kwargs)\n            else:\n                return res\n            finally:\n                signal.signal(signal.SIGALRM, old_handler)\n                signal.alarm(0)\n        return wrapped_f\n    return wrapper",
    "docstring": "A decorator ensuring that the decorated function tun time does not\n    exceeds the argument limit.\n\n    :args limit: the time limit\n    :type limit: int\n\n    :args handler: the handler function called when the decorated\n    function times out.\n    :type handler: callable\n\n    Example:\n    >>>def timeout_handler(limit, f, *args, **kwargs):\n    ...     print \"{func} call timed out after {lim}s.\".format(\n    ...         func=f.__name__, lim=limit)\n    ...\n    >>>@timeout(limit=5, handler=timeout_handler)\n    ... def work(foo, bar, baz=\"spam\")\n    ...     time.sleep(10)\n    >>>work(\"foo\", \"bar\", \"baz\")\n    # time passes...\n    work call timed out after 5s.\n    >>>"
  },
  {
    "code": "def find_parent_id_for_component(self, component_id):\n        cursor = self.db.cursor()\n        sql = \"SELECT parentResourceComponentId FROM ResourcesComponents WHERE resourceComponentId=%s\"\n        count = cursor.execute(sql, (component_id,))\n        if count > 0:\n            return (ArchivistsToolkitClient.RESOURCE_COMPONENT, cursor.fetchone())\n        return (\n            ArchivistsToolkitClient.RESOURCE,\n            self.find_resource_id_for_component(component_id),\n        )",
    "docstring": "Given the ID of a component, returns the parent component's ID.\n\n        :param string component_id: The ID of the component.\n        :return: A tuple containing:\n            * The type of the parent record; valid values are ArchivesSpaceClient.RESOURCE and ArchivesSpaceClient.RESOURCE_COMPONENT.\n            * The ID of the parent record.\n        :rtype tuple:"
  },
  {
    "code": "def unify_mp(b, partition_name):\n    with b.progress.start('coalesce_mp',0,message=\"MP coalesce {}\".format(partition_name)) as ps:\n        r = b.unify_partition(partition_name, None, ps)\n    return r",
    "docstring": "Unify all of the segment partitions for a parent partition, then run stats on the MPR file"
  },
  {
    "code": "def combine_ctrlpts_weights(ctrlpts, weights=None):\n    if weights is None:\n        weights = [1.0 for _ in range(len(ctrlpts))]\n    ctrlptsw = []\n    for pt, w in zip(ctrlpts, weights):\n        temp = [float(c * w) for c in pt]\n        temp.append(float(w))\n        ctrlptsw.append(temp)\n    return ctrlptsw",
    "docstring": "Multiplies control points by the weights to generate weighted control points.\n\n    This function is dimension agnostic, i.e. control points can be in any dimension but weights should be 1D.\n\n    The ``weights`` function parameter can be set to None to let the function generate a weights vector composed of\n    1.0 values. This feature can be used to convert B-Spline basis to NURBS basis.\n\n    :param ctrlpts: unweighted control points\n    :type ctrlpts: list, tuple\n    :param weights: weights vector; if set to None, a weights vector of 1.0s will be automatically generated\n    :type weights: list, tuple or None\n    :return: weighted control points\n    :rtype: list"
  },
  {
    "code": "def dump_stats(self, pattern):\n        if not isinstance(pattern, basestring):\n            raise TypeError(\"pattern can only be an instance of type basestring\")\n        self._call(\"dumpStats\",\n                     in_p=[pattern])",
    "docstring": "Dumps VM statistics.\n\n        in pattern of type str\n            The selection pattern. A bit similar to filename globbing."
  },
  {
    "code": "def up_alpha_beta(returns, factor_returns, **kwargs):\n    return up(returns, factor_returns, function=alpha_beta_aligned, **kwargs)",
    "docstring": "Computes alpha and beta for periods when the benchmark return is positive.\n\n    Parameters\n    ----------\n    see documentation for `alpha_beta`.\n\n    Returns\n    -------\n    float\n        Alpha.\n    float\n        Beta."
  },
  {
    "code": "def put(self, item, block=True, timeout=None):\n        if self.full():\n            if not block:\n                raise Full()\n            current = compat.getcurrent()\n            waketime = None if timeout is None else time.time() + timeout\n            if timeout is not None:\n                scheduler.schedule_at(waketime, current)\n            self._waiters.append((current, waketime))\n            scheduler.state.mainloop.switch()\n            if timeout is not None:\n                if not scheduler._remove_timer(waketime, current):\n                    self._waiters.remove((current, waketime))\n                    raise Full()\n        if self._waiters and not self.full():\n            scheduler.schedule(self._waiters.popleft()[0])\n        if not self._open_tasks:\n            self._jobs_done.clear()\n        self._open_tasks += 1\n        self._put(item)",
    "docstring": "put an item into the queue\n\n        .. note::\n\n            if the queue was created with a `maxsize` and it is currently\n            :meth:`full`, this method will block the calling coroutine until\n            another coroutine :meth:`get`\\ s an item.\n\n        :param item: the object to put into the queue, can be any type\n        :param block:\n            whether to block if the queue is already :meth:`full` (default\n            ``True``)\n        :type block: bool\n        :param timeout:\n            the maximum time in seconds to block waiting. with the default of\n            ``None``, it can wait indefinitely. this is unused if `block` is\n            ``False``.\n        :type timeout: int, float or None\n\n        :raises:\n            :class:`Full` if the queue is :meth:`full` and `block` is\n            ``False``, or if `timeout` expires."
  },
  {
    "code": "def _execfile(filename, globals, locals=None):\n    mode = 'rb'\n    if sys.version_info < (2, 7):\n        mode += 'U'\n    with open(filename, mode) as stream:\n        script = stream.read()\n    if locals is None:\n        locals = globals\n    code = compile(script, filename, 'exec')\n    exec(code, globals, locals)",
    "docstring": "Python 3 implementation of execfile."
  },
  {
    "code": "def get_ip_reports(self, ips):\n        api_name = 'virustotal-ip-address-reports'\n        (all_responses, ips) = self._bulk_cache_lookup(api_name, ips)\n        responses = self._request_reports(\"ip\", ips, 'ip-address/report')\n        for ip, response in zip(ips, responses):\n            if self._cache:\n                self._cache.cache_value(api_name, ip, response)\n            all_responses[ip] = response\n        return all_responses",
    "docstring": "Retrieves the most recent VT info for a set of ips.\n\n        Args:\n            ips: list of IPs.\n        Returns:\n            A dict with the IP as key and the VT report as value."
  },
  {
    "code": "def parse_mtl(mtl):\n    if hasattr(mtl, 'decode'):\n        mtl = mtl.decode('utf-8')\n    mtllib = None\n    mtllibs = []\n    for line in str.splitlines(str(mtl).strip()):\n        line_split = line.strip().split()\n        if len(line_split) <= 1:\n            continue\n        key = line_split[0]\n        if key == 'newmtl':\n            if mtllib:\n                mtllibs.append(mtllib)\n            mtllib = {'newmtl': line_split[1],\n                      'map_Kd': None,\n                      'Kd': None}\n        elif key == 'map_Kd':\n            mtllib[key] = line_split[1]\n        elif key == 'Kd':\n            mtllib[key] = [float(x) for x in line_split[1:]]\n    if mtllib:\n        mtllibs.append(mtllib)\n    return mtllibs",
    "docstring": "Parse a loaded MTL file.\n\n    Parameters\n    -------------\n    mtl : str or bytes\n      Data from an MTL file\n\n    Returns\n    ------------\n    mtllibs : list of dict\n      Each dict has keys: newmtl, map_Kd, Kd"
  },
  {
    "code": "def spam(self, tag=None, fromdate=None, todate=None):\n        return self.call(\"GET\", \"/stats/outbound/spam\", tag=tag, fromdate=fromdate, todate=todate)",
    "docstring": "Gets a total count of recipients who have marked your email as spam."
  },
  {
    "code": "def in_download_archive(track):\n    global arguments\n    if not arguments['--download-archive']:\n        return\n    archive_filename = arguments.get('--download-archive')\n    try:\n        with open(archive_filename, 'a+', encoding='utf-8') as file:\n            logger.debug('Contents of {0}:'.format(archive_filename))\n            file.seek(0)\n            track_id = '{0}'.format(track['id'])\n            for line in file:\n                logger.debug('\"'+line.strip()+'\"')\n                if line.strip() == track_id:\n                    return True\n    except IOError as ioe:\n        logger.error('Error trying to read download archive...')\n        logger.debug(ioe)\n    return False",
    "docstring": "Returns True if a track_id exists in the download archive"
  },
  {
    "code": "def select_time(da, **indexer):\n    if not indexer:\n        selected = da\n    else:\n        key, val = indexer.popitem()\n        time_att = getattr(da.time.dt, key)\n        selected = da.sel(time=time_att.isin(val)).dropna(dim='time')\n    return selected",
    "docstring": "Select entries according to a time period.\n\n    Parameters\n    ----------\n    da : xarray.DataArray\n      Input data.\n    **indexer : {dim: indexer, }, optional\n      Time attribute and values over which to subset the array. For example, use season='DJF' to select winter values,\n      month=1 to select January, or month=[6,7,8] to select summer months. If not indexer is given, all values are\n      considered.\n\n    Returns\n    -------\n    xr.DataArray\n      Selected input values."
  },
  {
    "code": "def get_image_code(self, id_code, access_token=None, user_id=None):\n        if access_token:\n            self.req.credential.set_token(access_token)\n        if user_id:\n            self.req.credential.set_user_id(user_id)\n        if not self.check_credentials():\n            raise CredentialsError('credentials invalid')\n        return self.req.get('/Codes/' + id_code + '/export/png/url')",
    "docstring": "Get the image of a code, by its id"
  },
  {
    "code": "def data_url(content, mimetype=None):\n    if isinstance(content, pathlib.Path):\n        if not mimetype:\n            mimetype = guess_type(content.name)[0]\n        with content.open('rb') as fp:\n            content = fp.read()\n    else:\n        if isinstance(content, text_type):\n            content = content.encode('utf8')\n    return \"data:{0};base64,{1}\".format(\n        mimetype or 'application/octet-stream', b64encode(content).decode())",
    "docstring": "Returns content encoded as base64 Data URI.\n\n    :param content: bytes or str or Path\n    :param mimetype: mimetype for\n    :return: str object (consisting only of ASCII, though)\n\n    .. seealso:: https://en.wikipedia.org/wiki/Data_URI_scheme"
  },
  {
    "code": "def get_composition_mdata():\n    return {\n        'children': {\n            'element_label': {\n                'text': 'children',\n                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),\n                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),\n                'formatTypeId': str(DEFAULT_FORMAT_TYPE),\n            },\n            'instructions': {\n                'text': 'accepts an osid.id.Id[] object',\n                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),\n                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),\n                'formatTypeId': str(DEFAULT_FORMAT_TYPE),\n            },\n            'required': False,\n            'read_only': False,\n            'linked': False,\n            'array': True,\n            'default_id_values': [],\n            'syntax': 'ID',\n            'id_set': [],\n        },\n    }",
    "docstring": "Return default mdata map for Composition"
  },
  {
    "code": "def run(plugin_name, *args, **kwargs):\n    plugindir = nago.settings.get_option('plugin_dir')\n    plugin = plugindir + \"/\" + plugin_name\n    if not os.path.isfile(plugin):\n        raise ValueError(\"Plugin %s not found\" % plugin)\n    command = [plugin] + list(args)\n    p = subprocess.Popen(command, stdout=subprocess.PIPE,stderr=subprocess.PIPE,)\n    stdout, stderr = p.communicate('through stdin to stdout')\n    result = {}\n    result['stdout'] = stdout\n    result['stderr'] = stderr\n    result['return_code'] = p.returncode\n    return result",
    "docstring": "Run a specific plugin"
  },
  {
    "code": "def stop(self):\n        self._running = False\n        if self._sleep_task:\n            self._sleep_task.cancel()\n            self._sleep_task = None",
    "docstring": "Stop listening."
  },
  {
    "code": "def GameTypeEnum(ctx):\n    return Enum(\n        ctx,\n        RM=0,\n        Regicide=1,\n        DM=2,\n        Scenario=3,\n        Campaign=4,\n        KingOfTheHill=5,\n        WonderRace=6,\n        DefendTheWonder=7,\n        TurboRandom=8\n    )",
    "docstring": "Game Type Enumeration."
  },
  {
    "code": "def align(self,inputwords, outputwords):\n        alignment = []\n        cursor = 0\n        for inputword in inputwords:\n            if len(outputwords) > cursor and outputwords[cursor] == inputword:\n                alignment.append(cursor)\n                cursor += 1\n            elif len(outputwords) > cursor+1 and outputwords[cursor+1] == inputword:\n                alignment.append(cursor+1)\n                cursor += 2\n            else:\n                alignment.append(None)\n                cursor += 1\n        return alignment",
    "docstring": "For each inputword, provides the index of the outputword"
  },
  {
    "code": "def inception_v3_parameters(weight_decay=0.00004, stddev=0.1,\n                            batch_norm_decay=0.9997, batch_norm_epsilon=0.001):\n  with scopes.arg_scope([ops.conv2d, ops.fc],\n                        weight_decay=weight_decay):\n    with scopes.arg_scope([ops.conv2d],\n                          stddev=stddev,\n                          activation=tf.nn.relu,\n                          batch_norm_params={\n                              'decay': batch_norm_decay,\n                              'epsilon': batch_norm_epsilon}) as arg_scope:\n      yield arg_scope",
    "docstring": "Yields the scope with the default parameters for inception_v3.\n\n  Args:\n    weight_decay: the weight decay for weights variables.\n    stddev: standard deviation of the truncated guassian weight distribution.\n    batch_norm_decay: decay for the moving average of batch_norm momentums.\n    batch_norm_epsilon: small float added to variance to avoid dividing by zero.\n\n  Yields:\n    a arg_scope with the parameters needed for inception_v3."
  },
  {
    "code": "def get_registered(option_hooks=None, event_hooks=None,\n                   command_hooks=None, root_access=None,\n                   task_active=True):\n    plugins = []\n    for _, item in _registered:\n        plugin, type_info = item\n        if task_active:\n            if type_info.get('disabled'):\n                continue\n        else:\n            if plugin.options or plugin.task_only:\n                continue\n        if not option_hooks is None:\n            if option_hooks != bool(type_info.get('option')):\n                continue\n        if not event_hooks is None:\n            if event_hooks != bool(type_info.get('event')):\n                continue\n        if not command_hooks is None:\n            if command_hooks != bool(type_info.get('command')):\n                continue\n        if not root_access is None:\n            if root_access != plugin.needs_root:\n                continue\n        plugins.append(plugin)\n    return plugins",
    "docstring": "Returns a generator of registered plugins matching filters.\n\n        `option_hooks`\n            Boolean to include or exclude plugins using option hooks.\n        `event_hooks`\n            Boolean to include or exclude task event plugins.\n        `command_hooks`\n            Boolean to include or exclude command plugins.\n        `root_access`\n            Boolean to include or exclude root plugins.\n        `task_active`\n            Set to ``False`` to not filter by task-based plugins.\n\n        Returns list of ``Plugin`` instances."
  },
  {
    "code": "def shortDescription(self):\n        cd = getattr(self,'classDescription',None)\n        if cd:\n            sd = getattr(cd,'shortDescription','')\n            d = getattr(cd,'description','')\n            return sd if sd else d\n        return ''",
    "docstring": "Overrides property from Event base class."
  },
  {
    "code": "def handler_for(obj):\n    for handler_type in handlers:\n        if isinstance(obj, handler_type):\n            return handlers[handler_type]\n    try:\n        for handler_type in handlers:\n            if issubclass(obj, handler_type):\n                return handlers[handler_type]\n    except TypeError:\n        pass",
    "docstring": "return the handler for the object type"
  },
  {
    "code": "def discard(self, element):\n        try:\n            i = int(element)\n            set.discard(self, i)\n        except ValueError:\n            pass",
    "docstring": "Remove element from the RangeSet if it is a member.\n\n        If the element is not a member, do nothing."
  },
  {
    "code": "def is_russian(self):\n        russian_chars = 0\n        for char in RUSSIAN_CHARS:\n            if char in self.name:\n                russian_chars += 1\n        return russian_chars > len(RUSSIAN_CHARS) / 2.0",
    "docstring": "Checks if file path is russian\n\n        :return: True iff document has a russian name"
  },
  {
    "code": "def sync_db():\n    with cd('/'.join([deployment_root(),'env',env.project_fullname,'project',env.project_package_name,'sitesettings'])):\n        venv = '/'.join([deployment_root(),'env',env.project_fullname,'bin','activate'])\n        sites = _get_django_sites()\n        site_ids = sites.keys()\n        site_ids.sort()\n        for site in site_ids:\n            for settings_file in _sitesettings_files():\n                site_settings = '.'.join([env.project_package_name,'sitesettings',settings_file.replace('.py','')])\n                if env.verbosity:\n                    print \" * django-admin.py syncdb --noinput --settings=%s\"% site_settings\n                output = sudo(' '.join(['source',venv,'&&',\"django-admin.py syncdb --noinput --settings=%s\"% site_settings]),\n                              user='site_%s'% site)\n                if env.verbosity:\n                    print output",
    "docstring": "Runs the django syncdb command"
  },
  {
    "code": "def _set_repo_option(repo, option):\n    if not option:\n        return\n    opt = option.split('=')\n    if len(opt) != 2:\n        return\n    if opt[0] == 'trusted':\n        repo['trusted'] = opt[1] == 'yes'\n    else:\n        repo[opt[0]] = opt[1]",
    "docstring": "Set the option to repo"
  },
  {
    "code": "def verify_axis_labels(self, expected, actual, source_name):\n        if not getattr(self, '_checked_axis_labels', False):\n            self._checked_axis_labels = defaultdict(bool)\n        if not self._checked_axis_labels[source_name]:\n            if actual is None:\n                log.warning(\"%s instance could not verify (missing) axis \"\n                            \"expected %s, got None\",\n                            self.__class__.__name__, expected)\n            else:\n                if expected != actual:\n                    raise AxisLabelsMismatchError(\"{} expected axis labels \"\n                                                  \"{}, got {} instead\".format(\n                                                      self.__class__.__name__,\n                                                      expected, actual))\n            self._checked_axis_labels[source_name] = True",
    "docstring": "Verify that axis labels for a given source are as expected.\n\n        Parameters\n        ----------\n        expected : tuple\n            A tuple of strings representing the expected axis labels.\n        actual : tuple or None\n            A tuple of strings representing the actual axis labels, or\n            `None` if they could not be determined.\n        source_name : str\n            The name of the source being checked. Used for caching the\n            results of checks so that the check is only performed once.\n\n        Notes\n        -----\n        Logs a warning in case of `actual=None`, raises an error on\n        other mismatches."
  },
  {
    "code": "def _handle_iorder(self, state):\n        if self.opts['state_auto_order']:\n            for name in state:\n                for s_dec in state[name]:\n                    if not isinstance(s_dec, six.string_types):\n                        continue\n                    if not isinstance(state[name], dict):\n                        continue\n                    if not isinstance(state[name][s_dec], list):\n                        continue\n                    found = False\n                    if s_dec.startswith('_'):\n                        continue\n                    for arg in state[name][s_dec]:\n                        if isinstance(arg, dict):\n                            if arg:\n                                if next(six.iterkeys(arg)) == 'order':\n                                    found = True\n                    if not found:\n                        if not isinstance(state[name][s_dec], list):\n                            continue\n                        state[name][s_dec].append(\n                                {'order': self.iorder}\n                                )\n                        self.iorder += 1\n        return state",
    "docstring": "Take a state and apply the iorder system"
  },
  {
    "code": "def get_statements_noprior(self):\n        stmt_lists = [v for k, v in self.stmts.items() if k != 'prior']\n        stmts = []\n        for s in stmt_lists:\n            stmts += s\n        return stmts",
    "docstring": "Return a list of all non-prior Statements in a single list.\n\n        Returns\n        -------\n        stmts : list[indra.statements.Statement]\n            A list of all the INDRA Statements in the model (excluding\n            the prior)."
  },
  {
    "code": "def create_fw_db(self, fw_id, fw_name, tenant_id):\n        fw_dict = {'fw_id': fw_id, 'name': fw_name, 'tenant_id': tenant_id}\n        self.update_fw_dict(fw_dict)",
    "docstring": "Create FW dict."
  },
  {
    "code": "def build_dictionary(self):\n        d = {}\n        for t in self.all_tags_of_type(DefinitionTag, recurse_into_sprites = False):\n            if t.characterId in d:\n                raise ValueError('illegal redefinition of character')\n            d[t.characterId] = t\n        return d",
    "docstring": "Return a dictionary of characterIds to their defining tags."
  },
  {
    "code": "def virtualchain_set_opfields( op, **fields ):\n    for f in fields.keys():\n        if f not in indexer.RESERVED_KEYS:\n            log.warning(\"Unsupported virtualchain field '%s'\" % f)\n    for f in fields.keys():\n        if f in indexer.RESERVED_KEYS:\n            op[f] = fields[f]\n    return op",
    "docstring": "Pass along virtualchain-reserved fields to a virtualchain operation.\n    This layer of indirection is meant to help with future compatibility,\n    so virtualchain implementations do not try to set operation fields\n    directly."
  },
  {
    "code": "def add(self, entity):\n        do_append = self.__check_new(entity)\n        if do_append:\n            self.__entities.append(entity)",
    "docstring": "Adds the given entity to this cache.\n\n        :param entity: Entity to add.\n        :type entity: Object implementing :class:`everest.interfaces.IEntity`.\n        :raises ValueError: If the ID of the entity to add is ``None``\n          (unless the `allow_none_id` constructor argument was set)."
  },
  {
    "code": "def access_token(self):\n        access_token = generate_token(length=self.access_token_length[1])\n        token_secret = generate_token(self.secret_length)\n        client_key = request.oauth.client_key\n        self.save_access_token(client_key, access_token,\n            request.oauth.resource_owner_key, secret=token_secret)\n        return urlencode([(u'oauth_token', access_token),\n                          (u'oauth_token_secret', token_secret)])",
    "docstring": "Create an OAuth access token for an authorized client.\n\n        Defaults to /access_token. Invoked by client applications."
  },
  {
    "code": "def _extract_centerdistance(image, mask = slice(None), voxelspacing = None):\n    image = numpy.array(image, copy=False)\n    if None == voxelspacing:\n        voxelspacing = [1.] * image.ndim\n    centers = [(x - 1) / 2. for x in image.shape]\n    indices = numpy.indices(image.shape, dtype=numpy.float)\n    for dim_indices, c, vs in zip(indices, centers, voxelspacing):\n        dim_indices -= c\n        dim_indices *= vs\n    return numpy.sqrt(numpy.sum(numpy.square(indices), 0))[mask].ravel()",
    "docstring": "Internal, single-image version of `centerdistance`."
  },
  {
    "code": "def reconfigure_log_level(self):\n        if Global.LOGGER:\n            Global.LOGGER.debug('reconfiguring logger level')\n        stream_handlers = filter(lambda x: type(x) is logging.StreamHandler,\n                                 self._logger_instance.handlers)\n        for x in stream_handlers:\n            x.level = Global.CONFIG_MANAGER.log_level\n        return self.get_logger()",
    "docstring": "Returns a new standard logger instance"
  },
  {
    "code": "def getParameter(self, name):\n        return lock_and_call(\n            lambda: Parameter(self._impl.getParameter(name)),\n            self._lock\n        )",
    "docstring": "Get the parameter with the corresponding name.\n\n        Args:\n            name: Name of the parameter to be found.\n\n        Raises:\n            TypeError: if the specified parameter does not exist."
  },
  {
    "code": "def mtr_tr_dense(sz):\n  n = 2 ** sz\n  hparams = mtf_bitransformer_base()\n  hparams.d_model = 1024\n  hparams.max_length = 256\n  hparams.batch_size = 128\n  hparams.d_ff = int(4096 * n)\n  hparams.d_kv = 128\n  hparams.encoder_num_heads = int(8 * n)\n  hparams.decoder_num_heads = int(8 * n)\n  hparams.learning_rate_decay_steps = 51400\n  hparams.layout = \"batch:batch;vocab:model;d_ff:model;heads:model\"\n  hparams.mesh_shape = \"batch:32\"\n  hparams.label_smoothing = 0.1\n  hparams.layer_prepostprocess_dropout = 0.1\n  hparams.attention_dropout = 0.1\n  hparams.relu_dropout = 0.1\n  return hparams",
    "docstring": "Series of machine translation models.\n\n  All models are trained on sequences of 256 tokens.\n\n  You can use the dataset translate_enfr_wmt32k_packed.\n  154000 steps = 3 epochs.\n\n  Args:\n    sz: an integer\n\n  Returns:\n    a hparams"
  },
  {
    "code": "def get_conversations(self):\n        cs = self.data[\"data\"]\n        res = []\n        for c in cs:\n            res.append(Conversation(c))\n        return res",
    "docstring": "Returns list of Conversation objects"
  },
  {
    "code": "def add_url_rule(self, host, rule_string, endpoint, **options):\n        rule = Rule(rule_string, host=host, endpoint=endpoint, **options)\n        self.url_map.add(rule)",
    "docstring": "Add a url rule to the app instance.\n\n        The url rule is the same with Flask apps and other Werkzeug apps.\n\n        :param host: the matched hostname. e.g. \"www.python.org\"\n        :param rule_string: the matched path pattern. e.g. \"/news/<int:id>\"\n        :param endpoint: the endpoint name as a dispatching key such as the\n                         qualified name of the object."
  },
  {
    "code": "def fit(self, X, y=None, **kwargs):\n        super(PCADecomposition, self).fit(X=X, y=y, **kwargs)\n        self.pca_transformer.fit(X)\n        self.pca_components_ = self.pca_transformer.named_steps['pca'].components_\n        return self",
    "docstring": "Fits the PCA transformer, transforms the data in X, then draws the\n        decomposition in either 2D or 3D space as a scatter plot.\n\n        Parameters\n        ----------\n        X : ndarray or DataFrame of shape n x m\n            A matrix of n instances with m features.\n\n        y : ndarray or Series of length n\n            An array or series of target or class values.\n\n        Returns\n        -------\n        self : visualizer\n            Returns self for use in Pipelines"
  },
  {
    "code": "def make_fitness(function, greater_is_better):\n    if not isinstance(greater_is_better, bool):\n        raise ValueError('greater_is_better must be bool, got %s'\n                         % type(greater_is_better))\n    if function.__code__.co_argcount != 3:\n        raise ValueError('function requires 3 arguments (y, y_pred, w),'\n                         ' got %d.' % function.__code__.co_argcount)\n    if not isinstance(function(np.array([1, 1]),\n                      np.array([2, 2]),\n                      np.array([1, 1])), numbers.Number):\n        raise ValueError('function must return a numeric.')\n    return _Fitness(function, greater_is_better)",
    "docstring": "Make a fitness measure, a metric scoring the quality of a program's fit.\n\n    This factory function creates a fitness measure object which measures the\n    quality of a program's fit and thus its likelihood to undergo genetic\n    operations into the next generation. The resulting object is able to be\n    called with NumPy vectorized arguments and return a resulting floating\n    point score quantifying the quality of the program's representation of the\n    true relationship.\n\n    Parameters\n    ----------\n    function : callable\n        A function with signature function(y, y_pred, sample_weight) that\n        returns a floating point number. Where `y` is the input target y\n        vector, `y_pred` is the predicted values from the genetic program, and\n        sample_weight is the sample_weight vector.\n\n    greater_is_better : bool\n        Whether a higher value from `function` indicates a better fit. In\n        general this would be False for metrics indicating the magnitude of\n        the error, and True for metrics indicating the quality of fit."
  },
  {
    "code": "def eval(self):\n        if self.magic:\n            return self.magic\n        if not self.filename:\n            return file_pattern.format(self.alias, self.ext)\n        return self.path",
    "docstring": "Returns a filename to be used for script output."
  },
  {
    "code": "def _receive(self):\n        preamble = self._read(1)\n        if not preamble:\n            return None\n        elif ord(preamble) != SBP_PREAMBLE:\n            if self._verbose:\n                print(\"Host Side Unhandled byte: 0x%02x\" % ord(preamble))\n            return None\n        hdr = self._readall(5)\n        msg_crc = crc16(hdr)\n        msg_type, sender, msg_len = struct.unpack(\"<HHB\", hdr)\n        data = self._readall(msg_len)\n        msg_crc = crc16(data, msg_crc)\n        crc = self._readall(2)\n        crc, = struct.unpack(\"<H\", crc)\n        if crc != msg_crc:\n            if self._verbose:\n                print(\"crc mismatch: 0x%04X 0x%04X\" % (msg_crc, crc))\n            return None\n        msg = SBP(msg_type, sender, msg_len, data, crc)\n        try:\n            msg = self._dispatch(msg)\n        except Exception as exc:\n            warnings.warn(\"SBP dispatch error: %s\" % (exc,))\n        return msg",
    "docstring": "Read and build SBP message."
  },
  {
    "code": "def list_nodes():\n    ret = {}\n    nodes = list_nodes_full()\n    for node in nodes:\n        ret[node] = {\n            'id': nodes[node]['UUID'],\n            'image': nodes[node]['Guest OS'],\n            'name': nodes[node]['Name'],\n            'state': None,\n            'private_ips': [],\n            'public_ips': [],\n        }\n        ret[node]['size'] = '{0} RAM, {1} CPU'.format(\n            nodes[node]['Memory size'],\n            nodes[node]['Number of CPUs'],\n        )\n    return ret",
    "docstring": "Return a list of registered VMs\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' vboxmanage.list_nodes"
  },
  {
    "code": "async def connect_to_endpoints(self, *endpoints: ConnectionConfig) -> None:\n        self._throw_if_already_connected(*endpoints)\n        await asyncio.gather(\n            *(self._await_connect_to_endpoint(endpoint) for endpoint in endpoints),\n            loop=self.event_loop\n        )",
    "docstring": "Connect to the given endpoints and await until all connections are established."
  },
  {
    "code": "def load_global_settings():\n    with open(settings_path, 'r') as settings_f:\n        global global_settings\n        settings_json = json.loads(settings_f.read())\n        if global_settings is None:\n            global_settings = settings_json\n            global_settings[u'package_path'] = package_dir\n        else:\n            for k, v in settings_json.items():\n                if type(v) == dict:\n                    global_settings[k].update(v)\n                else:\n                    global_settings[k] = v",
    "docstring": "Loads settings file containing paths to dependencies and other optional configuration elements."
  },
  {
    "code": "def enforce_signature(function):\n    argspec = inspect.getfullargspec(function)\n    annotations = argspec.annotations\n    argnames = argspec.args\n    unnamed_annotations = {}\n    for i, arg in enumerate(argnames):\n        if arg in annotations:\n            unnamed_annotations[i] = (annotations[arg], arg)\n    def decorated(*args, **kwargs):\n        for i, annotation in unnamed_annotations.items():\n            if i < len(args):\n                assert_right_type(args[i], annotation[0], annotation[1])\n        for argname, argval in kwargs.items():\n            if argname in annotations:\n                assert_right_type(argval, annotations[argname], argname)\n        return function(*args, **kwargs)\n    return decorated",
    "docstring": "Enforces the signature of the function by throwing TypeError's if invalid\n    arguments are provided. The return value is not checked.\n\n    You can annotate any parameter of your function with the desired type or a\n    tuple of allowed types. If you annotate the function with a value, this\n    value only will be allowed (useful especially for None). Example:\n\n    >>> @enforce_signature\n    ... def test(arg: bool, another: (int, None)):\n    ...     pass\n    ...\n    >>> test(True, 5)\n    >>> test(True, None)\n\n    Any string value for any parameter e.g. would then trigger a TypeError.\n\n    :param function: The function to check."
  },
  {
    "code": "def bulk_create_datetimes(date_start: DateTime,\n                              date_end: DateTime, **kwargs) -> List[DateTime]:\n        dt_objects = []\n        if not date_start and not date_end:\n            raise ValueError('You must pass date_start and date_end')\n        if date_end < date_start:\n            raise ValueError('date_start can not be larger than date_end')\n        while date_start <= date_end:\n            date_start += timedelta(**kwargs)\n            dt_objects.append(date_start)\n        return dt_objects",
    "docstring": "Bulk create datetime objects.\n\n        This method creates list of datetime objects from\n        ``date_start`` to ``date_end``.\n\n        You can use the following keyword arguments:\n\n        * ``days``\n        * ``hours``\n        * ``minutes``\n        * ``seconds``\n        * ``microseconds``\n\n        See datetime module documentation for more:\n        https://docs.python.org/3.7/library/datetime.html#timedelta-objects\n\n\n        :param date_start: Begin of the range.\n        :param date_end: End of the range.\n        :param kwargs: Keyword arguments for datetime.timedelta\n        :return: List of datetime objects\n        :raises: ValueError: When ``date_start``/``date_end`` not passed and\n            when ``date_start`` larger than ``date_end``."
  },
  {
    "code": "def is_time_valid(self, timestamp):\n        sec_from_morning = get_sec_from_morning(timestamp)\n        return (self.is_valid and\n                self.hstart * 3600 + self.mstart * 60 <=\n                sec_from_morning <=\n                self.hend * 3600 + self.mend * 60)",
    "docstring": "Check if time is valid for this Timerange\n\n        If sec_from_morning is not provided, get the value.\n\n        :param timestamp: time to check\n        :type timestamp: int\n        :return: True if time is valid (in interval), False otherwise\n        :rtype: bool"
  },
  {
    "code": "def set_client_params(\n            self, start_unsubscribed=None, clear_on_exit=None, unsubscribe_on_reload=None,\n            announce_interval=None):\n        self._set('start-unsubscribed', start_unsubscribed, cast=bool)\n        self._set('subscription-clear-on-shutdown', clear_on_exit, cast=bool)\n        self._set('unsubscribe-on-graceful-reload', unsubscribe_on_reload, cast=bool)\n        self._set('subscribe-freq', announce_interval)\n        return self._section",
    "docstring": "Sets subscribers related params.\n\n        :param bool start_unsubscribed: Configure subscriptions but do not send them.\n            .. note:: Useful with master FIFO.\n\n        :param bool clear_on_exit: Force clear instead of unsubscribe during shutdown.\n\n        :param bool unsubscribe_on_reload: Force unsubscribe request even during graceful reload.\n\n        :param int announce_interval: Send subscription announce at the specified interval. Default: 10 master cycles."
  },
  {
    "code": "def _post_transition(self, result, *args, **kwargs):\n        for hook in self._filter_hooks(HOOK_AFTER, HOOK_ON_ENTER):\n            hook(self.instance, result, *args, **kwargs)",
    "docstring": "Performs post-transition actions."
  },
  {
    "code": "def add_recording_behavior(self, component, runnable):\n        simulation = component.simulation\n        for rec in simulation.records:\n            rec.id = runnable.id\n            self.current_record_target.add_variable_recorder(self.current_data_output, rec)",
    "docstring": "Adds recording-related dynamics to a runnable component based on\n        the dynamics specifications in the component model.\n\n        @param component: Component model containing dynamics specifications.\n        @type component: lems.model.component.FatComponent runnable: Runnable component to which dynamics is to be added.\n        @type runnable: lems.sim.runnable.Runnable\n\n        @raise SimBuildError: Raised when a target for recording could not be\n        found."
  },
  {
    "code": "def _calc_sizes(self):\n        if self.size > 1024:\n            self.unit = \"Mb\"\n            self.size = (self.size / 1024)\n        if self.size > 1024:\n            self.unit = \"Gb\"\n            self.size = (self.size / 1024)",
    "docstring": "Package size calculation"
  },
  {
    "code": "def _get_firmware_update_service_resource(self):\n        manager, uri = self._get_ilo_details()\n        try:\n            fw_uri = manager['Oem']['Hp']['links']['UpdateService']['href']\n        except KeyError:\n            msg = (\"Firmware Update Service resource not found.\")\n            raise exception.IloCommandNotSupportedError(msg)\n        return fw_uri",
    "docstring": "Gets the firmware update service uri.\n\n        :returns: firmware update service uri\n        :raises: IloError, on an error from iLO.\n        :raises: IloConnectionError, if not able to reach iLO.\n        :raises: IloCommandNotSupportedError, for not finding the uri"
  },
  {
    "code": "def has_out_of_flow_tables(self):\n        if self.article.body is None:\n            return False\n        for table_wrap in self.article.body.findall('.//table-wrap'):\n            graphic = table_wrap.xpath('./graphic | ./alternatives/graphic')\n            table = table_wrap.xpath('./table | ./alternatives/table')\n            if graphic and table:\n                return True\n        return False",
    "docstring": "Returns True if the article has out-of-flow tables, indicates separate\n        tables document.\n\n        This method is used to indicate whether rendering this article's content\n        will result in the creation of out-of-flow HTML tables. This method has\n        a base class implementation representing a common logic; if an article\n        has a graphic(image) representation of a table then the HTML\n        representation will be placed out-of-flow if it exists, if there is no\n        graphic(image) represenation then the HTML representation will be placed\n        in-flow.\n\n        Returns\n        -------\n        bool\n            True if there are out-of-flow HTML tables, False otherwise"
  },
  {
    "code": "def change_ref(self, gm=None, r0=None, lmax=None):\n        if lmax is None:\n            lmax = self.lmax\n        clm = self.pad(lmax)\n        if gm is not None and gm != self.gm:\n            clm.coeffs *= self.gm / gm\n            clm.gm = gm\n            if self.errors is not None:\n                clm.errors *= self.gm / gm\n        if r0 is not None and r0 != self.r0:\n            for l in _np.arange(lmax+1):\n                clm.coeffs[:, l, :l+1] *= (self.r0 / r0)**l\n                if self.errors is not None:\n                    clm.errors[:, l, :l+1] *= (self.r0 / r0)**l\n            clm.r0 = r0\n        return clm",
    "docstring": "Return a new SHGravCoeffs class instance with a different reference gm\n        or r0.\n\n        Usage\n        -----\n        clm = x.change_ref([gm, r0, lmax])\n\n        Returns\n        -------\n        clm : SHGravCoeffs class instance.\n\n        Parameters\n        ----------\n        gm : float, optional, default = self.gm\n            The gravitational constant time the mass that is associated with\n            the gravitational potential coefficients.\n        r0 : float, optional, default = self.r0\n            The reference radius of the spherical harmonic coefficients.\n        lmax : int, optional, default = self.lmax\n            Maximum spherical harmonic degree to output.\n\n        Description\n        -----------\n        This method returns a new class instance of the gravitational\n        potential, but using a difference reference gm or r0. When\n        changing the reference radius r0, the spherical harmonic coefficients\n        will be upward or downward continued under the assumption that the\n        reference radius is exterior to the body."
  },
  {
    "code": "def _get_attr_value(instance, attr, default=None):\n    value = default\n    if hasattr(instance, attr):\n        value = getattr(instance, attr)\n        if callable(value):\n            value = value()\n    return value",
    "docstring": "Simple helper to get the value of an instance's attribute if it exists.\n\n    If the instance attribute is callable it will be called and the result will\n    be returned.\n\n    Optionally accepts a default value to return if the attribute is missing.\n    Defaults to `None`\n\n    >>> class Foo(object):\n    ...     bar = 'baz'\n    ...     def hi(self):\n    ...         return 'hi'\n    >>> f = Foo()\n    >>> _get_attr_value(f, 'bar')\n    'baz'\n    >>> _get_attr_value(f, 'xyz')\n\n    >>> _get_attr_value(f, 'xyz', False)\n    False\n    >>> _get_attr_value(f, 'hi')\n    'hi'"
  },
  {
    "code": "def tally(self, chain):\n        self.db._rows[chain][self.name] = self._getfunc()",
    "docstring": "Adds current value to trace"
  },
  {
    "code": "def content_type(self, content_type):\n        allowed_values = [\"application/json\", \"text/html\", \"text/plain\", \"application/x-www-form-urlencoded\", \"\"]\n        if content_type not in allowed_values:\n            raise ValueError(\n                \"Invalid value for `content_type` ({0}), must be one of {1}\"\n                .format(content_type, allowed_values)\n            )\n        self._content_type = content_type",
    "docstring": "Sets the content_type of this Notificant.\n\n        The value of the Content-Type header of the webhook POST request.  # noqa: E501\n\n        :param content_type: The content_type of this Notificant.  # noqa: E501\n        :type: str"
  },
  {
    "code": "def logfile_generator(self):\n        if not self.args['exclude']:\n            start_limits = [f.start_limit for f in self.filters\n                            if hasattr(f, 'start_limit')]\n            if start_limits:\n                for logfile in self.args['logfile']:\n                    logfile.fast_forward(max(start_limits))\n        if len(self.args['logfile']) > 1:\n            for logevent in self._merge_logfiles():\n                yield logevent\n        else:\n            for logevent in self.args['logfile'][0]:\n                if self.args['timezone'][0] != 0 and logevent.datetime:\n                    logevent._datetime = (logevent.datetime +\n                                          timedelta(hours=self\n                                                    .args['timezone'][0]))\n                yield logevent",
    "docstring": "Yield each line of the file, or the next line if several files."
  },
  {
    "code": "def get_host_datastore_system(host_ref, hostname=None):\n    if not hostname:\n        hostname = get_managed_object_name(host_ref)\n    service_instance = get_service_instance_from_managed_object(host_ref)\n    traversal_spec = vmodl.query.PropertyCollector.TraversalSpec(\n        path='configManager.datastoreSystem',\n        type=vim.HostSystem,\n        skip=False)\n    objs = get_mors_with_properties(service_instance,\n                                    vim.HostDatastoreSystem,\n                                    property_list=['datastore'],\n                                    container_ref=host_ref,\n                                    traversal_spec=traversal_spec)\n    if not objs:\n        raise salt.exceptions.VMwareObjectRetrievalError(\n            'Host\\'s \\'{0}\\' datastore system was not retrieved'\n            ''.format(hostname))\n    log.trace('[%s] Retrieved datastore system', hostname)\n    return objs[0]['object']",
    "docstring": "Returns a host's datastore system\n\n    host_ref\n        Reference to the ESXi host\n\n    hostname\n        Name of the host. This argument is optional."
  },
  {
    "code": "def find_globals_and_nonlocals(node, globs, nonlocals, code, version):\n    for n in node:\n        if isinstance(n, SyntaxTree):\n            globs, nonlocals = find_globals_and_nonlocals(n, globs, nonlocals,\n                                                          code, version)\n        elif n.kind in read_global_ops:\n            globs.add(n.pattr)\n        elif (version >= 3.0\n              and n.kind in nonglobal_ops\n              and n.pattr in code.co_freevars\n              and n.pattr != code.co_name\n              and code.co_name != '<lambda>'):\n            nonlocals.add(n.pattr)\n    return globs, nonlocals",
    "docstring": "search a node of parse tree to find variable names that need a\n    either 'global' or 'nonlocal' statements added."
  },
  {
    "code": "def ndim(self):\n        try:\n            return self.__ndim\n        except AttributeError:\n            ndim = len(self.coord_vectors)\n            self.__ndim = ndim\n            return ndim",
    "docstring": "Number of dimensions of the grid."
  },
  {
    "code": "def writelines(self, sequence):\n        iterator = iter(sequence)\n        def iterate(_=None):\n            try:\n                return self.write(next(iterator)).addCallback(iterate)\n            except StopIteration:\n                return\n        return defer.maybeDeferred(iterate)",
    "docstring": "Write a sequence of strings to the file.\n\n        Does not add separators."
  },
  {
    "code": "def get_assessments_taken_for_assessment(self, assessment_id):\n        collection = JSONClientValidated('assessment',\n                                         collection='AssessmentOffered',\n                                         runtime=self._runtime)\n        result = collection.find(\n            dict({'assessmentId': str(assessment_id)},\n                 **self._view_filter())).sort('_id', DESCENDING)\n        assessments_offered = objects.AssessmentOfferedList(\n            result,\n            runtime=self._runtime)\n        collection = JSONClientValidated('assessment',\n                                         collection='AssessmentTaken',\n                                         runtime=self._runtime)\n        ao_ids = []\n        for assessment_offered in assessments_offered:\n            ao_ids.append(str(assessment_offered.get_id()))\n        result = collection.find(\n            dict({'assessmentOfferedId': {'$in': ao_ids}},\n                 **self._view_filter())).sort('_id', DESCENDING)\n        return objects.AssessmentTakenList(result,\n                                           runtime=self._runtime,\n                                           proxy=self._proxy)",
    "docstring": "Gets an ``AssessmentTakenList`` for the given assessment.\n\n        In plenary mode, the returned list contains all known\n        assessments taken or an error results. Otherwise, the returned\n        list may contain only those assessments taken that are\n        accessible through this session.\n\n        arg:    assessment_id (osid.id.Id): ``Id`` of an ``Assessment``\n        return: (osid.assessment.AssessmentTakenList) - the returned\n                ``AssessmentTaken`` list\n        raise:  NullArgument - ``assessment_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_cached_moderated_reddits(self):\n        if self._mod_subs is None:\n            self._mod_subs = {'mod': self.reddit_session.get_subreddit('mod')}\n            for sub in self.reddit_session.get_my_moderation(limit=None):\n                self._mod_subs[six.text_type(sub).lower()] = sub\n        return self._mod_subs",
    "docstring": "Return a cached dictionary of the user's moderated reddits.\n\n        This list is used internally. Consider using the `get_my_moderation`\n        function instead."
  },
  {
    "code": "def _str_to_int(self, string):\n        string = string.lower()\n        if string.endswith(\"l\"):\n            string = string[:-1]\n        if string.lower().startswith(\"0x\"):\n            match = re.match(r'0[xX]([a-fA-F0-9]+)', string)\n            return int(match.group(1), 0x10)\n        else:\n            return int(string)",
    "docstring": "Check for the hex"
  },
  {
    "code": "def release(self, *args, **kwargs):\n        if not self.field.lockable:\n            return\n        if self.sub_lock_mode:\n            return\n        super(FieldLock, self).release(*args, **kwargs)\n        self.already_locked_by_model = self.sub_lock_mode = False",
    "docstring": "Really release the lock only if it's not a sub-lock. Then save the\n        sub-lock status and mark the model as unlocked."
  },
  {
    "code": "def unique_email_validator(form, field):\n    user_manager =  current_app.user_manager\n    if not user_manager.email_is_available(field.data):\n        raise ValidationError(_('This Email is already in use. Please try another one.'))",
    "docstring": "Username must be unique. This validator may NOT be customized."
  },
  {
    "code": "def get_value(self, column=0, row=0):\n        x = self._widget.item(row, column)\n        if x==None: return x\n        else:       return str(self._widget.item(row,column).text())",
    "docstring": "Returns a the value at column, row."
  },
  {
    "code": "def resolution(self, indicator=None):\n        self._request_entity = 'dnsResolution'\n        self._request_uri = '{}/dnsResolutions'.format(self._request_uri)\n        if indicator is not None:\n            self._request_uri = '{}/{}/dnsResolutions'.format(self._api_uri, indicator)",
    "docstring": "Update the URI to retrieve host resolutions for the provided indicator.\n\n        Args:\n            indicator (string): The indicator to retrieve resolutions."
  },
  {
    "code": "def create_api_client(api='BatchV1'):\n    k8s_config.load_incluster_config()\n    api_configuration = client.Configuration()\n    api_configuration.verify_ssl = False\n    if api == 'extensions/v1beta1':\n        api_client = client.ExtensionsV1beta1Api()\n    elif api == 'CoreV1':\n        api_client = client.CoreV1Api()\n    elif api == 'StorageV1':\n        api_client = client.StorageV1Api()\n    else:\n        api_client = client.BatchV1Api()\n    return api_client",
    "docstring": "Create Kubernetes API client using config.\n\n    :param api: String which represents which Kubernetes API to spawn. By\n        default BatchV1.\n    :returns: Kubernetes python client object for a specific API i.e. BatchV1."
  },
  {
    "code": "def insert_tree(self, items, node, headers):\n        first = items[0]\n        child = node.get_child(first)\n        if child is not None:\n            child.count += 1\n        else:\n            child = node.add_child(first)\n            if headers[first] is None:\n                headers[first] = child\n            else:\n                current = headers[first]\n                while current.link is not None:\n                    current = current.link\n                current.link = child\n        remaining_items = items[1:]\n        if len(remaining_items) > 0:\n            self.insert_tree(remaining_items, child, headers)",
    "docstring": "Recursively grow FP tree."
  },
  {
    "code": "def stop_listener(self):\n        if self.sock is not None:\n            self.sock.close()\n            self.sock = None\n        self.tracks = {}",
    "docstring": "stop listening for packets"
  },
  {
    "code": "def list_cert_bindings(site):\n    ret = dict()\n    sites = list_sites()\n    if site not in sites:\n        log.warning('Site not found: %s', site)\n        return ret\n    for binding in sites[site]['bindings']:\n        if sites[site]['bindings'][binding]['certificatehash']:\n            ret[binding] = sites[site]['bindings'][binding]\n    if not ret:\n        log.warning('No certificate bindings found for site: %s', site)\n    return ret",
    "docstring": "List certificate bindings for an IIS site.\n\n    .. versionadded:: 2016.11.0\n\n    Args:\n        site (str): The IIS site name.\n\n    Returns:\n        dict: A dictionary of the binding names and properties.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' win_iis.list_bindings site"
  },
  {
    "code": "def trips(self, val):\n        self._trips = val\n        if val is not None and not val.empty:\n            self._trips_i = self._trips.set_index(\"trip_id\")\n        else:\n            self._trips_i = None",
    "docstring": "Update ``self._trips_i`` if ``self.trips`` changes."
  },
  {
    "code": "def connected_component(self, ident):\n        ident = normalize_ident(ident)\n        done = set()\n        todo = set([ident])\n        labels = set()\n        while todo:\n            ident = todo.pop()\n            done.add(ident)\n            for label in self.directly_connected(ident):\n                if label.value != CorefValue.Positive:\n                    continue\n                ident1, ident2 = idents_from_label(\n                    label, subtopic=ident_has_subtopic(ident))\n                if ident1 not in done:\n                    todo.add(ident1)\n                if ident2 not in done:\n                    todo.add(ident2)\n                if label not in labels:\n                    labels.add(label)\n                    yield label",
    "docstring": "Return a connected component generator for ``ident``.\n\n        ``ident`` may be a ``content_id`` or a ``(content_id,\n        subtopic_id)``.\n\n        Given an ``ident``, return the corresponding connected\n        component by following all positive transitivity relationships.\n\n        For example, if ``(a, b, 1)`` is a label and ``(b, c, 1)`` is\n        a label, then ``connected_component('a')`` will return both\n        labels even though ``a`` and ``c`` are not directly connected.\n\n        (Note that even though this returns a generator, it will still\n        consume memory proportional to the number of labels in the\n        connected component.)\n\n        :param ident: content id or (content id and subtopic id)\n        :type ident: ``str`` or ``(str, str)``\n        :rtype: generator of :class:`Label`"
  },
  {
    "code": "def put(self, key, value):\n    value = self.serializedValue(value)\n    self.child_datastore.put(key, value)",
    "docstring": "Stores the object `value` named by `key`.\n    Serializes values on the way in, and stores the serialized data into the\n    ``child_datastore``.\n\n    Args:\n      key: Key naming `value`\n      value: the object to store."
  },
  {
    "code": "def __execute_kadmin(cmd):\n    ret = {}\n    auth_keytab = __opts__.get('auth_keytab', None)\n    auth_principal = __opts__.get('auth_principal', None)\n    if __salt__['file.file_exists'](auth_keytab) and auth_principal:\n        return __salt__['cmd.run_all'](\n            'kadmin -k -t {0} -p {1} -q \"{2}\"'.format(\n                auth_keytab, auth_principal, cmd\n            )\n        )\n    else:\n        log.error('Unable to find kerberos keytab/principal')\n        ret['retcode'] = 1\n        ret['comment'] = 'Missing authentication keytab/principal'\n    return ret",
    "docstring": "Execute kadmin commands"
  },
  {
    "code": "def allZero(buffer):\n    allZero = True\n    for byte in buffer:\n        if byte != \"\\x00\":\n            allZero = False\n            break\n    return allZero",
    "docstring": "Tries to determine if a buffer is empty.\n    \n    @type buffer: str\n    @param buffer: Buffer to test if it is empty.\n        \n    @rtype: bool\n    @return: C{True} if the given buffer is empty, i.e. full of zeros,\n        C{False} if it doesn't."
  },
  {
    "code": "def sY(qubit: Qubit, coefficient: complex = 1.0) -> Pauli:\n    return Pauli.sigma(qubit, 'Y', coefficient)",
    "docstring": "Return the Pauli sigma_Y operator acting on the given qubit"
  },
  {
    "code": "def unq_argument(self) -> str:\n        start = self.offset\n        self.dfa([\n            {\n                \"\": lambda: 0,\n                \";\": lambda: -1,\n                \" \": lambda: -1,\n                \"\\t\": lambda: -1,\n                \"\\r\": lambda: -1,\n                \"\\n\": lambda: -1,\n                \"{\": lambda: -1,\n                '/': lambda: 1\n            },\n            {\n                \"\": lambda: 0,\n                \"/\": self._back_break,\n                \"*\": self._back_break\n            }])\n        self._arg = self.input[start:self.offset]",
    "docstring": "Parse unquoted argument.\n\n        Raises:\n            EndOfInput: If past the end of input."
  },
  {
    "code": "def to_dict(self, delimiter=DEFAULT_DELIMITER, dict_type=collections.OrderedDict):\n        root_key = self.sections()[0]\n        return self._build_dict(\n            self._sections, delimiter=delimiter, dict_type=dict_type\n        ).get(root_key, {})",
    "docstring": "Get the dictionary representation of the current parser.\n\n        :param str delimiter: The delimiter used for nested dictionaries,\n            defaults to \":\", optional\n        :param class dict_type: The dictionary type to use for building the dictionary\n            reperesentation, defaults to collections.OrderedDict, optional\n        :return: The dictionary representation of the parser instance\n        :rtype: dict"
  },
  {
    "code": "def get_repositories_by_query(self, repository_query):\n        if self._catalog_session is not None:\n            return self._catalog_session.get_catalogs_by_query(repository_query)\n        query_terms = dict(repository_query._query_terms)\n        collection = JSONClientValidated('repository',\n                                         collection='Repository',\n                                         runtime=self._runtime)\n        result = collection.find(query_terms).sort('_id', DESCENDING)\n        return objects.RepositoryList(result, runtime=self._runtime)",
    "docstring": "Gets a list of ``Repositories`` matching the given repository query.\n\n        arg:    repository_query (osid.repository.RepositoryQuery): the\n                repository query\n        return: (osid.repository.RepositoryList) - the returned\n                ``RepositoryList``\n        raise:  NullArgument - ``repository_query`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        raise:  Unsupported - ``repository_query`` is not of this\n                service\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def add_eval(self, agent, e, fr=None):\n        self._evals[agent.name] = e\n        self._framings[agent.name] = fr",
    "docstring": "Add or change agent's evaluation of the artifact with given framing\n        information.\n\n        :param agent: Name of the agent which did the evaluation.\n        :param float e: Evaluation for the artifact.\n        :param object fr: Framing information for the evaluation."
  },
  {
    "code": "def _check_connectivity(self, err):\r\n        try:\r\n            import requests\r\n            requests.get(self.uptime_ssl)\r\n        except:\r\n            from requests import Request\r\n            request_object = Request(method='GET', url=self.uptime_ssl)\r\n            request_details = self.handle_requests(request_object)\r\n            self.printer('ERROR.')\r\n            raise ConnectionError(request_details['error'])\r\n        self.printer('ERROR.')\r\n        raise err",
    "docstring": "a method to check connectivity as source of error"
  },
  {
    "code": "def _getSyntaxBySourceFileName(self, name):\n        for regExp, xmlFileName in self._extensionToXmlFileName.items():\n            if regExp.match(name):\n                return self._getSyntaxByXmlFileName(xmlFileName)\n        else:\n            raise KeyError(\"No syntax for \" + name)",
    "docstring": "Get syntax by source name of file, which is going to be highlighted"
  },
  {
    "code": "def numericshape(self):\n        try:\n            numericshape = [self.subseqs.seqs.model.numconsts.nmb_stages]\n        except AttributeError:\n            objecttools.augment_excmessage(\n                'The `numericshape` of a sequence like `%s` depends on the '\n                'configuration of the actual integration algorithm.  '\n                'While trying to query the required configuration data '\n                '`nmb_stages` of the model associated with element `%s`'\n                % (self.name, objecttools.devicename(self)))\n        numericshape.extend(self.shape)\n        return tuple(numericshape)",
    "docstring": "Shape of the array of temporary values required for the numerical\n        solver actually being selected."
  },
  {
    "code": "def _geolocation_extract(response):\n    body = response.json()\n    if response.status_code in (200, 404):\n        return body\n    try:\n        error = body[\"error\"][\"errors\"][0][\"reason\"]\n    except KeyError:\n        error = None\n    if response.status_code == 403:\n        raise exceptions._OverQueryLimit(response.status_code, error)\n    else:\n        raise exceptions.ApiError(response.status_code, error)",
    "docstring": "Mimics the exception handling logic in ``client._get_body``, but\n    for geolocation which uses a different response format."
  },
  {
    "code": "def nominations(self, congress=CURRENT_CONGRESS):\n        \"Return votes on nominations from a given Congress\"\n        path = \"{congress}/nominations.json\".format(congress=congress)\n        return self.fetch(path)",
    "docstring": "Return votes on nominations from a given Congress"
  },
  {
    "code": "def greedy(problem, graph_search=False, viewer=None):\n    return _search(problem,\n                   BoundedPriorityQueue(),\n                   graph_search=graph_search,\n                   node_factory=SearchNodeHeuristicOrdered,\n                   graph_replace_when_better=True,\n                   viewer=viewer)",
    "docstring": "Greedy search.\n\n    If graph_search=True, will avoid exploring repeated states.\n    Requires: SearchProblem.actions, SearchProblem.result,\n    SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic."
  },
  {
    "code": "def dicom_to_nifti(dicom_input, output_file=None):\n    assert common.is_philips(dicom_input)\n    if common.is_multiframe_dicom(dicom_input):\n        _assert_explicit_vr(dicom_input)\n        logger.info('Found multiframe dicom')\n        if _is_multiframe_4d(dicom_input):\n            logger.info('Found sequence type: MULTIFRAME 4D')\n            return _multiframe_to_nifti(dicom_input, output_file)\n        if _is_multiframe_anatomical(dicom_input):\n            logger.info('Found sequence type: MULTIFRAME ANATOMICAL')\n            return _multiframe_to_nifti(dicom_input, output_file)\n    else:\n        logger.info('Found singleframe dicom')\n        grouped_dicoms = _get_grouped_dicoms(dicom_input)\n        if _is_singleframe_4d(dicom_input):\n            logger.info('Found sequence type: SINGLEFRAME 4D')\n            return _singleframe_to_nifti(grouped_dicoms, output_file)\n    logger.info('Assuming anatomical data')\n    return convert_generic.dicom_to_nifti(dicom_input, output_file)",
    "docstring": "This is the main dicom to nifti conversion fuction for philips images.\n    As input philips images are required. It will then determine the type of images and do the correct conversion\n\n    Examples: See unit test\n\n    :param output_file: file path to the output nifti\n    :param dicom_input: directory with dicom files for 1 scan"
  },
  {
    "code": "def lambda_handler(self):\n        def wrapper(event, context):\n            skill = CustomSkill(skill_configuration=self.skill_configuration)\n            request_envelope = skill.serializer.deserialize(\n                payload=json.dumps(event), obj_type=RequestEnvelope)\n            response_envelope = skill.invoke(\n                request_envelope=request_envelope, context=context)\n            return skill.serializer.serialize(response_envelope)\n        return wrapper",
    "docstring": "Create a handler function that can be used as handler in\n        AWS Lambda console.\n\n        The lambda handler provides a handler function, that acts as\n        an entry point to the AWS Lambda console. Users can set the\n        lambda_handler output to a variable and set the variable as\n        AWS Lambda Handler on the console.\n\n        :return: Handler function to tag on AWS Lambda console."
  },
  {
    "code": "def prune_by_ngram(self, ngrams):\n        self._logger.info('Pruning results by n-gram')\n        self._matches = self._matches[\n            ~self._matches[constants.NGRAM_FIELDNAME].isin(ngrams)]",
    "docstring": "Removes results rows whose n-gram is in `ngrams`.\n\n        :param ngrams: n-grams to remove\n        :type ngrams: `list` of `str`"
  },
  {
    "code": "def projector_functions(self):\n        projector_functions = OrderedDict()\n        for (mesh, values, attrib) in self._parse_all_radfuncs(\"projector_function\"):\n            state = attrib[\"state\"]\n            projector_functions[state] = RadialFunction(mesh, values)\n        return projector_functions",
    "docstring": "Dictionary with the PAW projectors indexed by state."
  },
  {
    "code": "def _prevent_default_initializer_splitting(self, item, indent_amt):\n        if unicode(item) == '=':\n            self._delete_whitespace()\n            return\n        if (not self._prev_item or not self._prev_prev_item or\n                unicode(self._prev_item) != '='):\n            return\n        self._delete_whitespace()\n        prev_prev_index = self._lines.index(self._prev_prev_item)\n        if (\n            isinstance(self._lines[prev_prev_index - 1], self._Indent) or\n            self.fits_on_current_line(item.size + 1)\n        ):\n            return\n        if isinstance(self._lines[prev_prev_index - 1], self._Space):\n            del self._lines[prev_prev_index - 1]\n        self.add_line_break_at(self._lines.index(self._prev_prev_item),\n                               indent_amt)",
    "docstring": "Prevent splitting between a default initializer.\n\n        When there is a default initializer, it's best to keep it all on\n        the same line. It's nicer and more readable, even if it goes\n        over the maximum allowable line length. This goes back along the\n        current line to determine if we have a default initializer, and,\n        if so, to remove extraneous whitespaces and add a line\n        break/indent before it if needed."
  },
  {
    "code": "def get_canonical_key_id(self, key_id):\n        shard_num = self.get_shard_num_by_key_id(key_id)\n        return self._canonical_keys[shard_num]",
    "docstring": "get_canonical_key_id is used by get_canonical_key, see the comment\n        for that method for more explanation.\n\n        Keyword arguments:\n        key_id -- the key id (e.g. '12345')\n\n        returns the canonical key id (e.g. '12')"
  },
  {
    "code": "def get_editor_cmd_from_environment():\n    result = os.getenv(ENV_VISUAL)\n    if (not result):\n        result = os.getenv(ENV_EDITOR)\n    return result",
    "docstring": "Gets and editor command from environment variables.\n\n    It first tries $VISUAL, then $EDITOR, following the same order git uses\n    when it looks up edits. If neither is available, it returns None."
  },
  {
    "code": "def delete_older(self):\n        logger.info(\n            \"Deleting all mails strictly older than the {} timestamp...\"\n            \"\".format(self.newest_timestamp))\n        candidates = [\n            mail for mail in self.pool\n            if mail.timestamp < self.newest_timestamp]\n        if len(candidates) == self.size:\n            logger.warning(\n                \"Skip deletion: all {} mails share the same timestamp.\"\n                \"\".format(self.size))\n        logger.info(\n            \"{} candidates found for deletion.\".format(len(candidates)))\n        for mail in candidates:\n            self.delete(mail)",
    "docstring": "Delete all older duplicates.\n\n        Only keeps the subset sharing the most recent timestamp."
  },
  {
    "code": "def get_object_or_404(queryset, *filter_args, **filter_kwargs):\n    try:\n        return _get_object_or_404(queryset, *filter_args, **filter_kwargs)\n    except (TypeError, ValueError, ValidationError):\n        raise Http404",
    "docstring": "Same as Django's standard shortcut, but make sure to also raise 404\n    if the filter_kwargs don't match the required types.\n\n    This function was copied from rest_framework.generics because of issue #36."
  },
  {
    "code": "def league_header(self, league):\n        league_name = \" {0} \".format(league)\n        click.secho(\"{:=^62}\".format(league_name), fg=self.colors.MISC)\n        click.echo()",
    "docstring": "Prints the league header"
  },
  {
    "code": "def find_nir_file_with_missing_depth(video_file_list, depth_file_list):\n        \"Remove all files without its own counterpart. Returns new lists of files\"\n        new_video_list = []\n        new_depth_list = []\n        for fname in video_file_list:\n            try:\n                depth_file = Kinect.depth_file_for_nir_file(fname, depth_file_list)                \n                new_video_list.append(fname)\n                new_depth_list.append(depth_file)\n            except IndexError:\n                pass\n        bad_nir = [f for f in video_file_list if f not in new_video_list]\n        bad_depth = [f for f in depth_file_list if f not in new_depth_list]\n        return (new_video_list, new_depth_list, bad_nir, bad_depth)",
    "docstring": "Remove all files without its own counterpart. Returns new lists of files"
  },
  {
    "code": "def rc4(data, key):\n    S, j, out = list(range(256)), 0, []\n    for i in range(256):\n        j = (j + S[i] + ord(key[i % len(key)])) % 256\n        S[i], S[j] = S[j], S[i]\n    i = j = 0\n    for ch in data:\n        i = (i + 1) % 256\n        j = (j + S[i]) % 256\n        S[i], S[j] = S[j], S[i]\n        out.append(chr(ord(ch) ^ S[(S[i] + S[j]) % 256]))\n    return \"\".join(out)",
    "docstring": "RC4 encryption and decryption method."
  },
  {
    "code": "def remove_link(self, rel, value=None, href=None):\n        links_node = self.metadata.find('links')\n        if links_node is None:\n            log.warning('No links node present')\n            return False\n        counter = 0\n        links = links_node.xpath('.//link[@rel=\"{}\"]'.format(rel))\n        for link in links:\n            if value and href:\n                if link.text == value and link.attrib['href'] == href:\n                    links_node.remove(link)\n                    counter += 1\n            elif value and not href:\n                if link.text == value:\n                    links_node.remove(link)\n                    counter += 1\n            elif not value and href:\n                if link.attrib['href'] == href:\n                    links_node.remove(link)\n                    counter += 1\n            else:\n                links_node.remove(link)\n                counter += 1\n        return counter",
    "docstring": "Removes link nodes based on the function arguments.\n\n        This can remove link nodes based on the following combinations of arguments:\n            link/@rel\n            link/@rel & link/text()\n            link/@rel & link/@href\n            link/@rel & link/text() & link/@href\n\n        :param rel: link/@rel value to remove.  Required.\n        :param value: link/text() value to remove. This is used in conjunction with link/@rel.\n        :param href: link/@href value to remove. This is used in conjunction with link/@rel.\n        :return: Return the number of link nodes removed, or False if no nodes are removed."
  },
  {
    "code": "def first_rec(ofile, Rec, file_type):\n    keylist = []\n    opened = False\n    while not opened:\n        try:\n            pmag_out = open(ofile, 'w')\n            opened = True\n        except IOError:\n            time.sleep(1)\n    outstring = \"tab \\t\" + file_type + \"\\n\"\n    pmag_out.write(outstring)\n    keystring = \"\"\n    for key in list(Rec.keys()):\n        keystring = keystring + '\\t' + key.strip()\n        keylist.append(key)\n    keystring = keystring + '\\n'\n    pmag_out.write(keystring[1:])\n    pmag_out.close()\n    return keylist",
    "docstring": "opens the file ofile as a magic template file with headers as the keys to Rec"
  },
  {
    "code": "def from_shapefile(cls, shapefile, *args, **kwargs):\n        reader = Reader(shapefile)\n        return cls.from_records(reader.records(), *args, **kwargs)",
    "docstring": "Loads a shapefile from disk and optionally merges\n        it with a dataset. See ``from_records`` for full\n        signature.\n\n        Parameters\n        ----------\n        records: list of cartopy.io.shapereader.Record\n           Iterator containing Records.\n        dataset: holoviews.Dataset\n           Any HoloViews Dataset type.\n        on: str or list or dict\n          A mapping between the attribute names in the records and the\n          dimensions in the dataset.\n        value: str\n          The value dimension in the dataset the values will be drawn\n          from.\n        index: str or list\n          One or more dimensions in the dataset the Shapes will be\n          indexed by.\n        drop_missing: boolean\n          Whether to drop shapes which are missing from the provides\n          dataset.\n\n        Returns\n        -------\n        shapes: Polygons or Path object\n          A Polygons or Path object containing the geometries"
  },
  {
    "code": "def positional(max_pos_args):\n  __ndb_debug__ = 'SKIP'\n  def positional_decorator(wrapped):\n    if not DEBUG:\n      return wrapped\n    __ndb_debug__ = 'SKIP'\n    @wrapping(wrapped)\n    def positional_wrapper(*args, **kwds):\n      __ndb_debug__ = 'SKIP'\n      if len(args) > max_pos_args:\n        plural_s = ''\n        if max_pos_args != 1:\n          plural_s = 's'\n        raise TypeError(\n            '%s() takes at most %d positional argument%s (%d given)' %\n            (wrapped.__name__, max_pos_args, plural_s, len(args)))\n      return wrapped(*args, **kwds)\n    return positional_wrapper\n  return positional_decorator",
    "docstring": "A decorator to declare that only the first N arguments may be positional.\n\n  Note that for methods, n includes 'self'."
  },
  {
    "code": "def user_to_request(handler):\n    @wraps(handler)\n    async def decorator(*args):\n        request = _get_request(args)\n        request[cfg.REQUEST_USER_KEY] = await get_cur_user(request)\n        return await handler(*args)\n    return decorator",
    "docstring": "Add user to request if user logged in"
  },
  {
    "code": "def duration(self):\n        if self._stop_instant is None:\n            return int((instant() - self._start_instant) * 1000)\n        if self._duration is None:\n            self._duration = int((self._stop_instant - self._start_instant) * 1000)\n        return self._duration",
    "docstring": "Returns the integer value of the interval, the value is in milliseconds.\n\n        If the interval has not had stop called yet,\n        it will report the number of milliseconds in the interval up to the current point in time."
  },
  {
    "code": "def cp_cropduster_image(self, the_image_path, del_after_upload=False, overwrite=False, invalidate=False):\n        local_file = os.path.join(settings.MEDIA_ROOT, the_image_path)\n        if os.path.exists(local_file):\n            the_image_crops_path = os.path.splitext(the_image_path)[0]\n            the_image_crops_path_full_path = os.path.join(settings.MEDIA_ROOT, the_image_crops_path)\n            self.cp(local_path=local_file,\n                    target_path=os.path.join(settings.S3_ROOT_BASE, the_image_path),\n                    del_after_upload=del_after_upload,\n                    overwrite=overwrite,\n                    invalidate=invalidate,\n                    )\n            self.cp(local_path=the_image_crops_path_full_path + \"/*\",\n                    target_path=os.path.join(settings.S3_ROOT_BASE, the_image_crops_path),\n                    del_after_upload=del_after_upload,\n                    overwrite=overwrite,\n                    invalidate=invalidate,\n                    )",
    "docstring": "Deal with saving cropduster images to S3. Cropduster is a Django library for resizing editorial images.\n        S3utils was originally written to put cropduster images on S3 bucket.\n\n        Extra Items in your Django Settings\n        -----------------------------------\n\n        MEDIA_ROOT : string\n            Django media root.\n            Currently it is ONLY used in cp_cropduster_image method.\n            NOT any other method as this library was originally made to put Django cropduster images on s3 bucket.\n\n        S3_ROOT_BASE : string\n            S3 media root base. This will be the root folder in S3.\n            Currently it is ONLY used in cp_cropduster_image method.\n            NOT any other method as this library was originally made to put Django cropduster images on s3 bucket."
  },
  {
    "code": "def get_requests_session():\n    session = requests.sessions.Session()\n    session.mount('http://', HTTPAdapter(pool_connections=25, pool_maxsize=25, pool_block=True))\n    session.mount('https://', HTTPAdapter(pool_connections=25, pool_maxsize=25, pool_block=True))\n    return session",
    "docstring": "Set connection pool maxsize and block value to avoid `connection pool full` warnings.\n\n    :return: requests session"
  },
  {
    "code": "def get_stats(self):\n        sent = ctypes.c_uint32()\n        recv = ctypes.c_uint32()\n        send_errors = ctypes.c_uint32()\n        recv_errors = ctypes.c_uint32()\n        result = self.library.Par_GetStats(self.pointer, ctypes.byref(sent),\n                                   ctypes.byref(recv),\n                                   ctypes.byref(send_errors),\n                                   ctypes.byref(recv_errors))\n        check_error(result, \"partner\")\n        return sent, recv, send_errors, recv_errors",
    "docstring": "Returns some statistics.\n\n        :returns: a tuple containing bytes send, received, send errors, recv errors"
  },
  {
    "code": "def detect_keep_boundary(start, end, namespaces):\n    result_start, result_end = False, False\n    parent_start = start.getparent()\n    parent_end = end.getparent()\n    if parent_start.tag == \"{%s}p\" % namespaces['text']:\n        result_start = len(parent_start.getchildren()) > 1\n    if parent_end.tag == \"{%s}p\" % namespaces['text']:\n        result_end = len(parent_end.getchildren()) > 1\n    return result_start, result_end",
    "docstring": "a helper to inspect a link and see if we should keep the link boundary"
  },
  {
    "code": "async def add_items(self, *items):\n    items = [item.id for item in await self.process(items)]\n    if not items:\n      return\n    await self.connector.post('Playlists/{Id}/Items'.format(Id=self.id),\n      data={'Ids': ','.join(items)}, remote=False\n    )",
    "docstring": "append items to the playlist\n\n    |coro|\n\n    Parameters\n    ----------\n    items : array_like\n      list of items to add(or their ids)\n\n    See Also\n    --------\n      remove_items :"
  },
  {
    "code": "def asarray(self, file=None, out=None, **kwargs):\n        if file is not None:\n            if isinstance(file, int):\n                return self.imread(self.files[file], **kwargs)\n            return self.imread(file, **kwargs)\n        im = self.imread(self.files[0], **kwargs)\n        shape = self.shape + im.shape\n        result = create_output(out, shape, dtype=im.dtype)\n        result = result.reshape(-1, *im.shape)\n        for index, fname in zip(self._indices, self.files):\n            index = [i-j for i, j in zip(index, self._startindex)]\n            index = numpy.ravel_multi_index(index, self.shape)\n            im = self.imread(fname, **kwargs)\n            result[index] = im\n        result.shape = shape\n        return result",
    "docstring": "Read image data from files and return as numpy array.\n\n        The kwargs parameters are passed to the imread function.\n\n        Raise IndexError or ValueError if image shapes do not match."
  },
  {
    "code": "def safe_url(url):\n    parsed = urlparse(url)\n    if parsed.password is not None:\n        pwd = ':%s@' % parsed.password\n        url = url.replace(pwd, ':*****@')\n    return url",
    "docstring": "Remove password from printed connection URLs."
  },
  {
    "code": "def _make_graphite_api_points_list(influxdb_data):\n    _data = {}\n    for key in influxdb_data.keys():\n        _data[key[0]] = [(datetime.datetime.fromtimestamp(float(d['time'])),\n                          d['value']) for d in influxdb_data.get_points(key[0])]\n    return _data",
    "docstring": "Make graphite-api data points dictionary from Influxdb ResultSet data"
  },
  {
    "code": "def tpictr(sample, lenout=_default_len_out, lenerr=_default_len_out):\n    sample = stypes.stringToCharP(sample)\n    pictur = stypes.stringToCharP(lenout)\n    errmsg = stypes.stringToCharP(lenerr)\n    lenout = ctypes.c_int(lenout)\n    lenerr = ctypes.c_int(lenerr)\n    ok = ctypes.c_int()\n    libspice.tpictr_c(sample, lenout, lenerr, pictur, ctypes.byref(ok), errmsg)\n    return stypes.toPythonString(pictur), ok.value, stypes.toPythonString(\n            errmsg)",
    "docstring": "Given a sample time string, create a time format picture\n    suitable for use by the routine timout.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tpictr_c.html\n\n    :param sample: A sample time string.\n    :type sample: str\n    :param lenout: The length for the output picture string.\n    :type lenout: int\n    :param lenerr: The length for the output error string.\n    :type lenerr: int\n    :return:\n            A format picture that describes sample,\n            Flag indicating whether sample parsed successfully,\n            Diagnostic returned if sample cannot be parsed\n    :rtype: tuple"
  },
  {
    "code": "def build_diagonals(self):\r\n    self.l2 = np.roll(self.l2, -2)\r\n    self.l1 = np.roll(self.l1, -1)\r\n    self.r1 = np.roll(self.r1, 1)\r\n    self.r2 = np.roll(self.r2, 2)\r\n    if self.coeff_matrix is not None:\r\n      pass\r\n    elif self.BC_E == 'Periodic' and self.BC_W == 'Periodic':\r\n      pass\r\n    else:\r\n      self.diags = np.vstack((self.l2,self.l1,self.c0,self.r1,self.r2))\r\n      self.offsets = np.array([-2,-1,0,1,2])\r\n    self.coeff_matrix = spdiags(self.diags, self.offsets, self.nx, self.nx, format='csr')",
    "docstring": "Builds the diagonals for the coefficient array"
  },
  {
    "code": "def process_jpeg_bytes(bytes_in, quality=DEFAULT_JPEG_QUALITY):\n    bytes_out_p = ffi.new(\"char**\")\n    bytes_out_p_gc = ffi.gc(bytes_out_p, lib.guetzli_free_bytes)\n    length = lib.guetzli_process_jpeg_bytes(\n            bytes_in,\n            len(bytes_in),\n            bytes_out_p_gc,\n            quality\n            )\n    if length == 0:\n        raise ValueError(\"Invalid JPEG: Guetzli was not able to decode the image\")\n    bytes_out = ffi.cast(\"char*\", bytes_out_p_gc[0])\n    return ffi.unpack(bytes_out, length)",
    "docstring": "Generates an optimized JPEG from JPEG-encoded bytes.\n\n    :param bytes_in: the input image's bytes\n    :param quality: the output JPEG quality (default 95)\n\n    :returns: Optimized JPEG bytes\n    :rtype: bytes\n\n    :raises ValueError: Guetzli was not able to decode the image (the image is\n                        probably corrupted or is not a JPEG)\n\n    .. code:: python\n\n        import pyguetzli\n\n        input_jpeg_bytes = open(\"./test/image.jpg\", \"rb\").read()\n        optimized_jpeg = pyguetzli.process_jpeg_bytes(input_jpeg_bytes)"
  },
  {
    "code": "def save(self, model, joining=None, touch=True):\n        if joining is None:\n            joining = {}\n        model.save({'touch': False})\n        self.attach(model.get_key(), joining, touch)\n        return model",
    "docstring": "Save a new model and attach it to the parent model.\n\n        :type model: eloquent.Model\n        :type joining: dict\n        :type touch: bool\n\n        :rtype: eloquent.Model"
  },
  {
    "code": "def load_defaults(self):\n        extract_files = [\n            self.config.settings.user.extract,\n            self.config.settings.system.extract,\n        ]\n        for extract_file in extract_files:\n            if extract_file:\n                try:\n                    self.load_from_file(extract_file)\n                except KeyboardInterrupt as e:\n                    raise e\n                except Exception as e:\n                    if binwalk.core.common.DEBUG:\n                        raise Exception(\"Extractor.load_defaults failed to load file '%s': %s\" % (extract_file, str(e)))",
    "docstring": "Loads default extraction rules from the user and system extract.conf files.\n\n        Returns None."
  },
  {
    "code": "def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs):\n    from .storage import ConsolidatedMetadataStore\n    store = normalize_store_arg(store)\n    if mode not in {'r', 'r+'}:\n        raise ValueError(\"invalid mode, expected either 'r' or 'r+'; found {!r}\"\n                         .format(mode))\n    meta_store = ConsolidatedMetadataStore(store, metadata_key=metadata_key)\n    return open(store=meta_store, chunk_store=store, mode=mode, **kwargs)",
    "docstring": "Open group using metadata previously consolidated into a single key.\n\n    This is an optimised method for opening a Zarr group, where instead of\n    traversing the group/array hierarchy by accessing the metadata keys at\n    each level, a single key contains all of the metadata for everything.\n    For remote data sources where the overhead of accessing a key is large\n    compared to the time to read data.\n\n    The group accessed must have already had its metadata consolidated into a\n    single key using the function :func:`consolidate_metadata`.\n\n    This optimised method only works in modes which do not change the\n    metadata, although the data may still be written/updated.\n\n    Parameters\n    ----------\n    store : MutableMapping or string\n        Store or path to directory in file system or name of zip file.\n    metadata_key : str\n        Key to read the consolidated metadata from. The default (.zmetadata)\n        corresponds to the default used by :func:`consolidate_metadata`.\n    mode : {'r', 'r+'}, optional\n        Persistence mode: 'r' means read only (must exist); 'r+' means\n        read/write (must exist) although only writes to data are allowed,\n        changes to metadata including creation of new arrays or group\n        are not allowed.\n    **kwargs\n        Additional parameters are passed through to :func:`zarr.creation.open_array` or\n        :func:`zarr.hierarchy.open_group`.\n\n    Returns\n    -------\n    g : :class:`zarr.hierarchy.Group`\n        Group instance, opened with the consolidated metadata.\n\n    See Also\n    --------\n    consolidate_metadata"
  },
  {
    "code": "def run(input, conf, filepath=None):\n    if conf.is_file_ignored(filepath):\n        return ()\n    if isinstance(input, (type(b''), type(u''))):\n        return _run(input, conf, filepath)\n    elif hasattr(input, 'read'):\n        content = input.read()\n        return _run(content, conf, filepath)\n    else:\n        raise TypeError('input should be a string or a stream')",
    "docstring": "Lints a YAML source.\n\n    Returns a generator of LintProblem objects.\n\n    :param input: buffer, string or stream to read from\n    :param conf: yamllint configuration object"
  },
  {
    "code": "def collapse_pair(graph, survivor: BaseEntity, victim: BaseEntity) -> None:\n    graph.add_edges_from(\n        (survivor, successor, key, data)\n        for _, successor, key, data in graph.out_edges(victim, keys=True, data=True)\n        if successor != survivor\n    )\n    graph.add_edges_from(\n        (predecessor, survivor, key, data)\n        for predecessor, _, key, data in graph.in_edges(victim, keys=True, data=True)\n        if predecessor != survivor\n    )\n    graph.remove_node(victim)",
    "docstring": "Rewire all edges from the synonymous node to the survivor node, then deletes the synonymous node.\n\n    Does not keep edges between the two nodes.\n\n    :param pybel.BELGraph graph: A BEL graph\n    :param survivor: The BEL node to collapse all edges on the synonym to\n    :param victim: The BEL node to collapse into the surviving node"
  },
  {
    "code": "def from_content(cls, content):\n        parsed_content = parse_tibiacom_content(content)\n        tables = cls._parse_tables(parsed_content)\n        char = Character()\n        if \"Could not find character\" in tables.keys():\n            return None\n        if \"Character Information\" in tables.keys():\n            char._parse_character_information(tables[\"Character Information\"])\n        else:\n            raise InvalidContent(\"content does not contain a tibia.com character information page.\")\n        char._parse_achievements(tables.get(\"Account Achievements\", []))\n        char._parse_deaths(tables.get(\"Character Deaths\", []))\n        char._parse_account_information(tables.get(\"Account Information\", []))\n        char._parse_other_characters(tables.get(\"Characters\", []))\n        return char",
    "docstring": "Creates an instance of the class from the html content of the character's page.\n\n        Parameters\n        ----------\n        content: :class:`str`\n            The HTML content of the page.\n\n        Returns\n        -------\n        :class:`Character`\n            The character contained in the page, or None if the character doesn't exist\n\n        Raises\n        ------\n        InvalidContent\n            If content is not the HTML of a character's page."
  },
  {
    "code": "def out_format(data, out='nested', opts=None, **kwargs):\n    if not opts:\n        opts = __opts__\n    return salt.output.out_format(data, out, opts=opts, **kwargs)",
    "docstring": "Return the formatted outputter string for the Python object.\n\n    data\n        The JSON serializable object.\n\n    out: ``nested``\n        The name of the output to use to transform the data. Default: ``nested``.\n\n    opts\n        Dictionary of configuration options. Default: ``__opts__``.\n\n    kwargs\n        Arguments to sent to the outputter module.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' out.out_format \"{'key': 'value'}\""
  },
  {
    "code": "def _NTU_max_for_P_solver(data, R1):\n    offset_max = data['offset'][-1]\n    for offset, p, q in zip(data['offset'], data['p'], data['q']):\n        if R1 < offset or offset == offset_max:\n            x = R1 - offset\n            return _horner(p, x)/_horner(q, x)",
    "docstring": "Private function to calculate the upper bound on the NTU1 value in the\n    P-NTU method. This value is calculated via a pade approximation obtained\n    on the result of a global minimizer which calculated the maximum P1\n    at a given R1 from ~1E-7 to approximately 100. This should suffice for \n    engineering applications. This value is needed to bound the solver."
  },
  {
    "code": "def clean_pred(self, pred, ignore_warning=False):\n        original_pred = pred\n        pred = pred.lower().strip()\n        if 'http' in pred:\n            pred = pred.split('/')[-1]\n        elif ':' in pred:\n            if pred[-1] != ':':\n                pred = pred.split(':')[-1]\n        else:\n            if not ignore_warning:\n                exit('Not a valid predicate: ' + original_pred + '. Needs to be an iri \"/\" or curie \":\".')\n        return pred",
    "docstring": "Takes the predicate and returns the suffix, lower case, stripped version"
  },
  {
    "code": "def _dirint_from_dni_ktprime(dni, kt_prime, solar_zenith, use_delta_kt_prime,\n                             temp_dew):\n    times = dni.index\n    delta_kt_prime = _delta_kt_prime_dirint(kt_prime, use_delta_kt_prime,\n                                            times)\n    w = _temp_dew_dirint(temp_dew, times)\n    dirint_coeffs = _dirint_coeffs(times, kt_prime, solar_zenith, w,\n                                   delta_kt_prime)\n    dni_dirint = dni * dirint_coeffs\n    return dni_dirint",
    "docstring": "Calculate DIRINT DNI from supplied DISC DNI and Kt'.\n\n    Supports :py:func:`gti_dirint`"
  },
  {
    "code": "def create(self, **fields):\n        entry = self.instance(**fields)\n        entry.save()\n        return entry",
    "docstring": "Create new entry."
  },
  {
    "code": "def get_list(self, ids: List[str]) -> List[Account]:\n        query = (\n            self.query\n            .filter(Account.guid.in_(ids))\n        )\n        return query.all()",
    "docstring": "Loads accounts by the ids passed as an argument"
  },
  {
    "code": "def update(self, pointvol):\n        if self.use_kdtree:\n            kdtree = spatial.KDTree(self.live_u)\n        else:\n            kdtree = None\n        if self.use_pool_update:\n            pool = self.pool\n        else:\n            pool = None\n        self.radfriends.update(self.live_u, pointvol=pointvol,\n                               rstate=self.rstate, bootstrap=self.bootstrap,\n                               pool=pool, kdtree=kdtree)\n        if self.enlarge != 1.:\n            self.radfriends.scale_to_vol(self.radfriends.vol_ball *\n                                         self.enlarge)\n        return copy.deepcopy(self.radfriends)",
    "docstring": "Update the N-sphere radii using the current set of live points."
  },
  {
    "code": "def render(self, parts=None):\n        if not parts:\n            parts = self.parts\n        fmt = []\n        data = []\n        for name, part_class in parts:\n            if issubclass(part_class, Primitive):\n                part = part_class(getattr(self, name, None))\n            else:\n                part = getattr(self, name, None)\n            part_format, part_data = part.render()\n            fmt.extend(part_format)\n            data.extend(part_data)\n        return \"\".join(fmt), data",
    "docstring": "Returns a two-element tuple with the ``struct`` format and values.\n\n        Iterates over the applicable sub-parts and calls `render()` on them,\n        accumulating the format string and values.\n\n        Optionally takes a subset of parts to render, default behavior is to\n        render all sub-parts belonging to the class."
  },
  {
    "code": "def update_attribute_value_items(self):\n        for attr in self._attribute_iterator():\n            if attr.kind != RESOURCE_ATTRIBUTE_KINDS.COLLECTION:\n                try:\n                    attr_val = self._get_proxied_attribute_value(attr)\n                except AttributeError:\n                    continue\n                else:\n                    yield (attr, attr_val)",
    "docstring": "Returns an iterator of items for an attribute value map to use for\n        an UPDATE operation.\n\n        The iterator ignores collection attributes as these are processed\n        implicitly by the traversal algorithm.\n\n        :returns: iterator yielding tuples with objects implementing\n          :class:`everest.resources.interfaces.IResourceAttribute` as the\n          first and the proxied attribute value as the second argument."
  },
  {
    "code": "def bm3_v_single(p, v0, k0, k0p, p_ref=0.0, min_strain=0.01):\n    if p <= 1.e-5:\n        return v0\n    def f_diff(v, v0, k0, k0p, p, p_ref=0.0):\n        return bm3_p(v, v0, k0, k0p, p_ref=p_ref) - p\n    v = brenth(f_diff, v0, v0 * min_strain, args=(v0, k0, k0p, p, p_ref))\n    return v",
    "docstring": "find volume at given pressure using brenth in scipy.optimize\n    this is for single p value, not vectorized\n    this cannot handle uncertainties\n\n    :param p: pressure\n    :param v0: volume at reference conditions\n    :param k0: bulk modulus at reference conditions\n    :param k0p: pressure derivative of bulk modulus at different conditions\n    :param p_ref: reference pressure (default = 0)\n    :param min_strain: minimum strain value to find solution (default = 0.01)\n    :return: volume at high pressure"
  },
  {
    "code": "def execute(self, task):\n        try:\n            return task.run()\n        except Exception:\n            if task.retries > 0:\n                task.retries -= 1\n                task.to_retrying()\n                if task.async:\n                    data = task.serialize()\n                    task.task_id = self.backend.push(\n                        self.queue_name,\n                        task.task_id,\n                        data\n                    )\n                else:\n                    return self.execute(task)\n            else:\n                raise",
    "docstring": "Given a task instance, this runs it.\n\n        This includes handling retries & re-raising exceptions.\n\n        Ex::\n\n            task = Task(async=False, retries=5)\n            task.to_call(add, 101, 35)\n            finished_task = gator.execute(task)\n\n        :param task_id: The identifier of the task to process\n        :type task_id: string\n\n        :returns: The completed ``Task`` instance"
  },
  {
    "code": "def _WorkerCommand_environment(self):\n        worker = self.workersArguments\n        c = []\n        if worker.prolog:\n            c.extend([\n                \"source\",\n                worker.prolog,\n                \"&&\",\n            ])\n        if worker.pythonPath and not self.isLocal():\n            c.extend([\n                \"env\",\n                \"PYTHONPATH={0}:$PYTHONPATH\".format(worker.pythonPath),\n            ])\n        elif worker.pythonPath and self.isLocal():\n            c.extend([\n                \"env\",\n                \"PYTHONPATH={0}:{1}\".format(\n                    worker.pythonPath,\n                    os.environ.get(\"PYTHONPATH\", \"\"),\n                ),\n            ])\n        return c",
    "docstring": "Return list of shell commands to prepare the environment for\n           bootstrap."
  },
  {
    "code": "def eval(conn, string, strip_command=True, **kwargs):\n    parser_args = {'strip_command': strip_command}\n    return _run(conn, None, string, parser_args, **kwargs)",
    "docstring": "Compiles the given template and executes it on the given\n    connection.\n    Raises an exception if the compilation fails.\n\n    if strip_command is True, the first line of each response that is\n    received after any command sent by the template is stripped. For\n    example, consider the following template::\n\n        ls -1{extract /(\\S+)/ as filenames}\n        {loop filenames as filename}\n            touch $filename\n        {end}\n\n    If strip_command is False, the response, (and hence, the `filenames'\n    variable) contains the following::\n\n        ls -1\n        myfile\n        myfile2\n        [...]\n\n    By setting strip_command to True, the first line is ommitted.\n\n    :type  conn: Exscript.protocols.Protocol\n    :param conn: The connection on which to run the template.\n    :type  string: string\n    :param string: The template to compile.\n    :type  strip_command: bool\n    :param strip_command: Whether to strip the command echo from the response.\n    :type  kwargs: dict\n    :param kwargs: Variables to define in the template.\n    :rtype:  dict\n    :return: The variables that are defined after execution of the script."
  },
  {
    "code": "def rlogistic(mu, tau, size=None):\n    u = np.random.random(size)\n    return mu + np.log(u / (1 - u)) / tau",
    "docstring": "Logistic random variates."
  },
  {
    "code": "def register(self):\n        user, created = self.Model.create_account(\n            self._json_params)\n        if not created:\n            raise JHTTPConflict('Looks like you already have an account.')\n        self.request._user = user\n        pk_field = user.pk_field()\n        headers = remember(self.request, getattr(user, pk_field))\n        return JHTTPOk('Registered', headers=headers)",
    "docstring": "Register new user by POSTing all required data."
  },
  {
    "code": "def str_to_etree(xml_str, encoding='utf-8'):\n    parser = xml.etree.ElementTree.XMLParser(encoding=encoding)\n    return xml.etree.ElementTree.fromstring(xml_str, parser=parser)",
    "docstring": "Deserialize API XML doc to an ElementTree.\n\n    Args:\n      xml_str: bytes\n        DataONE API XML doc\n\n      encoding: str\n        Decoder to use when converting the XML doc ``bytes`` to a Unicode str.\n\n    Returns:\n      ElementTree: Matching the API version of the XML doc."
  },
  {
    "code": "def segments(self):\n        segments = dict()\n        for i in xrange(len(self)):\n            image = self[i]\n            for z, contour in image.as_segments.iteritems():\n                for byte_value, contour_set in contour.iteritems():\n                    if byte_value not in segments:\n                        segments[byte_value] = dict()\n                    if z not in segments[byte_value]:\n                        segments[byte_value][z] = contour_set\n                    else:\n                        segments[byte_value][z] += contour_set                \n        return segments",
    "docstring": "A dictionary of lists of contours keyed by z-index"
  },
  {
    "code": "def genpass(pattern=r'[\\w]{32}'):\n    try:\n        return rstr.xeger(pattern)\n    except re.error as e:\n        raise ValueError(str(e))",
    "docstring": "generates a password with random chararcters"
  },
  {
    "code": "def bake(self):\n        self._yamllint_command = sh.yamllint.bake(\n            self.options,\n            self._tests,\n            _env=self.env,\n            _out=LOG.out,\n            _err=LOG.error)",
    "docstring": "Bake a `yamllint` command so it's ready to execute and returns None.\n\n        :return: None"
  },
  {
    "code": "def remove(self):\n        xmlrpc = XMLRPCConnection()\n        try:\n            xmlrpc.connection.remove_vrf(\n                {\n                    'vrf': { 'id': self.id },\n                    'auth': self._auth_opts.options\n                })\n        except xmlrpclib.Fault as xml_fault:\n            raise _fault_to_exception(xml_fault)\n        if self.id in _cache['VRF']:\n            del(_cache['VRF'][self.id])",
    "docstring": "Remove VRF.\n\n            Maps to the function :py:func:`nipap.backend.Nipap.remove_vrf` in\n            the backend. Please see the documentation for the backend function\n            for information regarding input arguments and return values."
  },
  {
    "code": "def create(cls, service=None, endpoint=None, data=None, *args, **kwargs):\n        cls.validate(data)\n        if service is None and endpoint is None:\n            raise InvalidArguments(service, endpoint)\n        if endpoint is None:\n            sid = service['id'] if isinstance(service, Entity) else service\n            endpoint = 'services/{0}/integrations'.format(sid)\n        return getattr(Entity, 'create').__func__(cls, endpoint=endpoint,\n                                                  data=data, *args, **kwargs)",
    "docstring": "Create an integration within the scope of an service.\n\n        Make sure that they should reasonably be able to query with an\n        service or endpoint that knows about an service."
  },
  {
    "code": "def data_filler_customer(self, number_of_rows, pipe):\n        try:\n            for i in range(number_of_rows):\n                pipe.hmset('customer:%s' % i, {\n                    'id': rnd_id_generator(self),\n                    'name': self.faker.first_name(),\n                    'lastname': self.faker.last_name(),\n                    'address': self.faker.address(),\n                    'country': self.faker.country(),\n                    'city': self.faker.city(),\n                    'registry_date': self.faker.date(pattern=\"%d-%m-%Y\"),\n                    'birthdate': self.faker.date(pattern=\"%d-%m-%Y\"),\n                    'email': self.faker.safe_email(),\n                    'phone_number': self.faker.phone_number(),\n                    'locale': self.faker.locale()\n                })\n            pipe.execute()\n            logger.warning('customer Commits are successful after write job!', extra=d)\n        except Exception as e:\n            logger.error(e, extra=d)",
    "docstring": "creates keys with customer data"
  },
  {
    "code": "def _get_csv_fieldnames(csv_reader):\n    fieldnames = []\n    for row in csv_reader:\n        for col in row:\n            field = (\n                col.strip()\n                .replace('\"', \"\")\n                .replace(\" \", \"\")\n                .replace(\"(\", \"\")\n                .replace(\")\", \"\")\n                .lower()\n            )\n            fieldnames.append(field)\n        if \"id\" in fieldnames:\n            break\n        else:\n            del fieldnames[:]\n    if not fieldnames:\n        return None\n    while True:\n        field = fieldnames.pop()\n        if field:\n            fieldnames.append(field)\n            break\n    suffix = 1\n    for index, field in enumerate(fieldnames):\n        if not field:\n            fieldnames[index] = \"field{}\".format(suffix)\n            suffix += 1\n    return fieldnames",
    "docstring": "Finds fieldnames in Polarion exported csv file."
  },
  {
    "code": "def information_title_header_element(feature, parent):\n    _ = feature, parent\n    header = information_title_header['string_format']\n    return header.capitalize()",
    "docstring": "Retrieve information title header string from definitions."
  },
  {
    "code": "def _create_job_details(self, key, job_config, logfile, status):\n        self.update_args(job_config)\n        job_details = JobDetails(jobname=self.full_linkname,\n                                 jobkey=key,\n                                 appname=self.appname,\n                                 logfile=logfile,\n                                 job_config=job_config,\n                                 timestamp=get_timestamp(),\n                                 file_dict=copy.deepcopy(self.files),\n                                 sub_file_dict=copy.deepcopy(self.sub_files),\n                                 status=status)\n        return job_details",
    "docstring": "Create a `JobDetails` for a single job\n\n        Parameters\n        ----------\n\n        key : str\n            Key used to identify this particular job\n\n        job_config : dict\n            Dictionary with arguements passed to this particular job\n\n        logfile : str\n            Name of the associated log file\n\n        status : int\n            Current status of the job\n\n        Returns\n        -------\n        job_details : `fermipy.jobs.JobDetails`\n            Object with the details about a particular job."
  },
  {
    "code": "def DeleteSubjects(self, subjects, sync=False):\n    for subject in subjects:\n      self.DeleteSubject(subject, sync=sync)",
    "docstring": "Delete multiple subjects at once."
  },
  {
    "code": "def _get_bandfilenames(self, **options):\n        conf = options[self.platform_name + '-viirs']\n        rootdir = conf['rootdir']\n        for section in conf:\n            if not section.startswith('section'):\n                continue\n            bandnames = conf[section]['bands']\n            for band in bandnames:\n                filename = os.path.join(rootdir, conf[section]['filename'])\n                self.bandfilenames[band] = compose(\n                    filename, {'bandname': band})",
    "docstring": "Get filename for each band"
  },
  {
    "code": "def is_auth_alive(self):\n        \"Return true if the auth is not expired, else false\"\n        model = self.model('ir.model')\n        try:\n            model.search([], None, 1, None)\n        except ClientError as err:\n            if err and err.message['code'] == 403:\n                return False\n            raise\n        except Exception:\n            raise\n        else:\n            return True",
    "docstring": "Return true if the auth is not expired, else false"
  },
  {
    "code": "def is_exchange(self, reaction_id):\n        reaction = self.get_reaction(reaction_id)\n        return (len(reaction.left) == 0) != (len(reaction.right) == 0)",
    "docstring": "Whether the given reaction is an exchange reaction."
  },
  {
    "code": "def wait(hotkey=None, suppress=False, trigger_on_release=False):\n    if hotkey:\n        lock = _Event()\n        remove = add_hotkey(hotkey, lambda: lock.set(), suppress=suppress, trigger_on_release=trigger_on_release)\n        lock.wait()\n        remove_hotkey(remove)\n    else:\n        while True:\n            _time.sleep(1e6)",
    "docstring": "Blocks the program execution until the given hotkey is pressed or,\n    if given no parameters, blocks forever."
  },
  {
    "code": "def load_personae():\n    dataset_path = _load('personae')\n    X = _load_csv(dataset_path, 'data')\n    y = X.pop('label').values\n    return Dataset(load_personae.__doc__, X, y, accuracy_score, stratify=True)",
    "docstring": "Personae Dataset.\n\n    The data of this dataset is a 2d numpy array vector containing 145 entries\n    that include texts written by Dutch users in Twitter, with some additional\n    information about the author, and the target is a 1d numpy binary integer\n    array indicating whether the author was extrovert or not."
  },
  {
    "code": "def enter_maintenance_mode(self):\n    cmd = self._cmd('enterMaintenanceMode')\n    if cmd.success:\n      self._update(get_host(self._get_resource_root(), self.hostId))\n    return cmd",
    "docstring": "Put the host in maintenance mode.\n\n    @return: Reference to the completed command.\n    @since: API v2"
  },
  {
    "code": "def absolute_path(self, path, start):\n        if posixpath.isabs(path):\n            path = posixpath.join(staticfiles_storage.location, path)\n        else:\n            path = posixpath.join(start, path)\n        return posixpath.normpath(path)",
    "docstring": "Return the absolute public path for an asset,\n        given the path of the stylesheet that contains it."
  },
  {
    "code": "def inserir(self, id_user, id_group):\n        if not is_valid_int_param(id_user):\n            raise InvalidParameterError(\n                u'The identifier of User is invalid or was not informed.')\n        if not is_valid_int_param(id_group):\n            raise InvalidParameterError(\n                u'The identifier of Group is invalid or was not informed.')\n        url = 'usergroup/user/' + \\\n            str(id_user) + '/ugroup/' + str(id_group) + '/associate/'\n        code, xml = self.submit(None, 'PUT', url)",
    "docstring": "Create a relationship between User and Group.\n\n        :param id_user: Identifier of the User. Integer value and greater than zero.\n        :param id_group: Identifier of the Group. Integer value and greater than zero.\n\n        :return: Dictionary with the following structure:\n\n        ::\n            {'user_group': {'id': < id_user_group >}}\n\n        :raise InvalidParameterError: The identifier of User or Group is null and invalid.\n        :raise GrupoUsuarioNaoExisteError: UserGroup not registered.\n        :raise UsuarioNaoExisteError: User not registered.\n        :raise UsuarioGrupoError: User already registered in the group.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def make_step_rcont (transition):\n    if not np.isfinite (transition):\n        raise ValueError ('\"transition\" argument must be finite number; got %r' % transition)\n    def step_rcont (x):\n        x = np.asarray (x)\n        x1 = np.atleast_1d (x)\n        r = (x1 >= transition).astype (x.dtype)\n        if x.ndim == 0:\n            return np.asscalar (r)\n        return r\n    step_rcont.__doc__ = ('Right-continuous step function. Returns 1 if x >= '\n                          '%g, 0 otherwise.') % (transition,)\n    return step_rcont",
    "docstring": "Return a ufunc-like step function that is right-continuous. Returns 1 if\n    x >= transition, 0 otherwise."
  },
  {
    "code": "def dependency_state(widgets, drop_defaults=True):\n    if widgets is None:\n        state = Widget.get_manager_state(drop_defaults=drop_defaults, widgets=None)['state']\n    else:\n        try:\n            widgets[0]\n        except (IndexError, TypeError):\n            widgets = [widgets]\n        state = {}\n        for widget in widgets:\n            _get_recursive_state(widget, state, drop_defaults)\n        add_resolved_links(state, drop_defaults)\n    return state",
    "docstring": "Get the state of all widgets specified, and their dependencies.\n\n    This uses a simple dependency finder, including:\n     - any widget directly referenced in the state of an included widget\n     - any widget in a list/tuple attribute in the state of an included widget\n     - any widget in a dict attribute in the state of an included widget\n     - any jslink/jsdlink between two included widgets\n    What this alogrithm does not do:\n     - Find widget references in nested list/dict structures\n     - Find widget references in other types of attributes\n\n    Note that this searches the state of the widgets for references, so if\n    a widget reference is not included in the serialized state, it won't\n    be considered as a dependency.\n\n    Parameters\n    ----------\n    widgets: single widget or list of widgets.\n       This function will return the state of every widget mentioned\n       and of all their dependencies.\n    drop_defaults: boolean\n        Whether to drop default values from the widget states.\n\n    Returns\n    -------\n    A dictionary with the state of the widgets and any widget they\n    depend on."
  },
  {
    "code": "def from_text_files(cls, path, field, train, validation, test=None, bs=64, bptt=70, **kwargs):\n        trn_ds, val_ds, test_ds = ConcatTextDataset.splits(\n            path, text_field=field, train=train, validation=validation, test=test)\n        return cls(path, field, trn_ds, val_ds, test_ds, bs, bptt, **kwargs)",
    "docstring": "Method used to instantiate a LanguageModelData object that can be used for a\n            supported nlp task.\n\n        Args:\n            path (str): the absolute path in which temporary model data will be saved\n            field (Field): torchtext field\n            train (str): file location of the training data\n            validation (str): file location of the validation data\n            test (str): file location of the testing data\n            bs (int): batch size to use\n            bptt (int): back propagation through time hyper-parameter\n            kwargs: other arguments\n\n        Returns:\n            a LanguageModelData instance, which most importantly, provides us the datasets for training,\n                validation, and testing\n\n        Note:\n            The train, validation, and test path can be pointed to any file (or folder) that contains a valid\n                text corpus."
  },
  {
    "code": "def list(self, *args, **kwargs):\n        return [\n            self.prepare_model(n)\n            for n in self.client.api.nodes(*args, **kwargs)\n        ]",
    "docstring": "List swarm nodes.\n\n        Args:\n            filters (dict): Filters to process on the nodes list. Valid\n                filters: ``id``, ``name``, ``membership`` and ``role``.\n                Default: ``None``\n\n        Returns:\n            A list of :py:class:`Node` objects.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error.\n\n        Example:\n\n            >>> client.nodes.list(filters={'role': 'manager'})"
  },
  {
    "code": "def fix_coordinate_decimal(d):\n    try:\n        for idx, n in enumerate(d[\"geo\"][\"geometry\"][\"coordinates\"]):\n            d[\"geo\"][\"geometry\"][\"coordinates\"][idx] = round(n, 5)\n    except Exception as e:\n        logger_misc.error(\"fix_coordinate_decimal: {}\".format(e))\n    return d",
    "docstring": "Coordinate decimal degrees calculated by an excel formula are often too long as a repeating decimal.\n    Round them down to 5 decimals\n\n    :param dict d: Metadata\n    :return dict d: Metadata"
  },
  {
    "code": "def _do_packet_out(self, datapath, data, in_port, actions):\n        ofproto = datapath.ofproto\n        parser = datapath.ofproto_parser\n        out = parser.OFPPacketOut(\n            datapath=datapath, buffer_id=ofproto.OFP_NO_BUFFER,\n            data=data, in_port=in_port, actions=actions)\n        datapath.send_msg(out)",
    "docstring": "send a packet."
  },
  {
    "code": "def facetrecordtrees(table, key, start='start', stop='stop'):\n    import intervaltree\n    getstart = attrgetter(start)\n    getstop = attrgetter(stop)\n    getkey = attrgetter(key)\n    trees = dict()\n    for rec in records(table):\n        k = getkey(rec)\n        if k not in trees:\n            trees[k] = intervaltree.IntervalTree()\n        trees[k].addi(getstart(rec), getstop(rec), rec)\n    return trees",
    "docstring": "Construct faceted interval trees for the given table, where each node in \n    the tree is a record."
  },
  {
    "code": "def mark_as_duplicate(self, duplicated_cid, master_cid, msg=''):\n        content_id_from = self.get_post(duplicated_cid)[\"id\"]\n        content_id_to = self.get_post(master_cid)[\"id\"]\n        params = {\n            \"cid_dupe\": content_id_from,\n            \"cid_to\": content_id_to,\n            \"msg\": msg\n        }\n        return self._rpc.content_mark_duplicate(params)",
    "docstring": "Mark the post at ``duplicated_cid`` as a duplicate of ``master_cid``\n\n        :type  duplicated_cid: int\n        :param duplicated_cid: The numeric id of the duplicated post\n        :type  master_cid: int\n        :param master_cid: The numeric id of an older post. This will be the\n            post that gets kept and ``duplicated_cid`` post will be concatinated\n            as a follow up to ``master_cid`` post.\n        :type msg: string\n        :param msg: the optional message (or reason for marking as duplicate)\n        :returns: True if it is successful. False otherwise"
  },
  {
    "code": "def is_state_machine_stopped_to_proceed(selected_sm_id=None, root_window=None):\n    if not state_machine_execution_engine.finished_or_stopped():\n        if selected_sm_id is None or selected_sm_id == state_machine_manager.active_state_machine_id:\n            message_string = \"A state machine is still running. This state machine can only be refreshed\" \\\n                             \"when not longer running.\"\n            dialog = RAFCONButtonDialog(message_string, [\"Stop execution and refresh\",\n                                                         \"Keep running and do not refresh\"],\n                                        message_type=Gtk.MessageType.QUESTION,\n                                        parent=root_window)\n            response_id = dialog.run()\n            state_machine_stopped = False\n            if response_id == 1:\n                state_machine_execution_engine.stop()\n                state_machine_stopped = True\n            elif response_id == 2:\n                logger.debug(\"State machine will stay running and no refresh will be performed!\")\n            dialog.destroy()\n            return state_machine_stopped\n    return True",
    "docstring": "Check if state machine is stopped and in case request user by dialog how to proceed\n\n     The function checks if a specific state machine or by default all state machines have stopped or finished\n     execution. If a state machine is still running the user is ask by dialog window if those should be stopped or not.\n\n    :param selected_sm_id: Specific state mine to check for\n    :param root_window: Root window for dialog window\n    :return:"
  },
  {
    "code": "def get_grade_entries_by_ids(self, grade_entry_ids):\n        collection = JSONClientValidated('grading',\n                                         collection='GradeEntry',\n                                         runtime=self._runtime)\n        object_id_list = []\n        for i in grade_entry_ids:\n            object_id_list.append(ObjectId(self._get_id(i, 'grading').get_identifier()))\n        result = collection.find(\n            dict({'_id': {'$in': object_id_list}},\n                 **self._view_filter()))\n        result = list(result)\n        sorted_result = []\n        for object_id in object_id_list:\n            for object_map in result:\n                if object_map['_id'] == object_id:\n                    sorted_result.append(object_map)\n                    break\n        return objects.GradeEntryList(sorted_result, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets a ``GradeEntryList`` corresponding to the given ``IdList``.\n\n        arg:    grade_entry_ids (osid.id.IdList): the list of ``Ids`` to\n                retrieve\n        return: (osid.grading.GradeEntryList) - the returned\n                ``GradeEntry`` list\n        raise:  NotFound - an ``Id was`` not found\n        raise:  NullArgument - ``grade_entry_ids`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def devices_in_group(self):\n        try:\n            devices = self.get_parameter('devices')\n        except AttributeError:\n            return []\n        ctor = DeviceFactory\n        return [ctor(int(x), lib=self.lib) for x in devices.split(',') if x]",
    "docstring": "Fetch list of devices in group."
  },
  {
    "code": "def login(self):\n        pg = self.getPage(\"http://www.neopets.com\")\n        form = pg.form(action=\"/login.phtml\")\n        form.update({'username': self.username, 'password': self.password})\n        pg = form.submit()\n        logging.getLogger(\"neolib.user\").info(\"Login check\", {'pg': pg})\n        return self.username in pg.content",
    "docstring": "Logs the user in, returns the result\n           \n        Returns\n           bool - Whether or not the user logged in successfully"
  },
  {
    "code": "def j0(x, context=None):\n    return _apply_function_in_current_context(\n        BigFloat,\n        mpfr.mpfr_j0,\n        (BigFloat._implicit_convert(x),),\n        context,\n    )",
    "docstring": "Return the value of the first kind Bessel function of order 0 at x."
  },
  {
    "code": "def size(self, units=\"MiB\"):\n        self.open()\n        size = lvm_pv_get_size(self.handle)\n        self.close()\n        return size_convert(size, units)",
    "docstring": "Returns the physical volume size in the given units. Default units are  MiB.\n\n        *Args:*\n\n        *       units (str):    Unit label ('MiB', 'GiB', etc...). Default is MiB."
  },
  {
    "code": "def get_assets(self, bbox, **kwargs):\n        response = self._get_assets(bbox, **kwargs)\n        assets = []\n        for asset in response['_embedded']['assets']:\n            asset_url = asset['_links']['self']\n            uid = asset_url['href'].split('/')[-1]\n            asset['uid'] = uid\n            del(asset['_links'])\n            assets.append(asset)\n        return assets",
    "docstring": "Query the assets stored in the intelligent environment for a given\n        bounding box and query.\n\n        Assets can be filtered by type of asset, event, or media available.\n\n            - device_type=['DATASIM']\n            - asset_type=['CAMERA']\n            - event_type=['PKIN']\n            - media_type=['IMAGE']\n\n        Pagination can be controlled with keyword parameters\n\n            - page=2\n            - size=100\n\n        Returns a list of assets stored in a dictionary that describe their:\n\n            - asset-id\n            - device-type\n            - device-id\n            - media-type\n            - coordinates\n            - event-type\n\n        Additionally there are some _links for additional information."
  },
  {
    "code": "def _render_list(self, items, empty='<pre>&lt;empty&gt;</pre>'):\n    if not items or len(items) == 0:\n      self._segments.append(empty)\n      return\n    self._segments.append('<ul>')\n    for o in items:\n      self._segments.append('<li>')\n      self._segments.append(str(o))\n      self._segments.append('</li>')\n    self._segments.append('</ul>')",
    "docstring": "Renders an HTML list with the specified list of strings.\n\n    Args:\n      items: the iterable collection of objects to render.\n      empty: what to render if the list is None or empty."
  },
  {
    "code": "def ReadTrigger(self, trigger_link, options=None):\n        if options is None:\n            options = {}\n        path = base.GetPathFromLink(trigger_link)\n        trigger_id = base.GetResourceIdOrFullNameFromLink(trigger_link)\n        return self.Read(path, 'triggers', trigger_id, None, options)",
    "docstring": "Reads a trigger.\n\n        :param str trigger_link:\n            The link to the trigger.\n        :param dict options:\n            The request options for the request.\n\n        :return:\n            The read Trigger.\n        :rtype:\n            dict"
  },
  {
    "code": "def url_for_token(self, token):\n        book_url = self.get_config_value(\"pages\", token)\n        book, _, url_tail = book_url.partition(':')\n        book_base = settings.HELP_TOKENS_BOOKS[book]\n        url = book_base\n        lang = getattr(settings, \"HELP_TOKENS_LANGUAGE_CODE\", None)\n        if lang is not None:\n            lang = self.get_config_value(\"locales\", lang)\n            url += \"/\" + lang\n        version = getattr(settings, \"HELP_TOKENS_VERSION\", None)\n        if version is not None:\n            url += \"/\" + version\n        url += \"/\" + url_tail\n        return url",
    "docstring": "Find the full URL for a help token."
  },
  {
    "code": "def copy_path(self):\n        path = cairo.cairo_copy_path(self._pointer)\n        result = list(_iter_path(path))\n        cairo.cairo_path_destroy(path)\n        return result",
    "docstring": "Return a copy of the current path.\n\n        :returns:\n            A list of ``(path_operation, coordinates)`` tuples\n            of a :ref:`PATH_OPERATION` string\n            and a tuple of floats coordinates\n            whose content depends on the operation type:\n\n            * :obj:`MOVE_TO <PATH_MOVE_TO>`: 1 point ``(x, y)``\n            * :obj:`LINE_TO <PATH_LINE_TO>`: 1 point ``(x, y)``\n            * :obj:`CURVE_TO <PATH_CURVE_TO>`: 3 points\n              ``(x1, y1, x2, y2, x3, y3)``\n            * :obj:`CLOSE_PATH <PATH_CLOSE_PATH>` 0 points ``()`` (empty tuple)"
  },
  {
    "code": "def UpdateFrom(self, src):\n    if not isinstance(src, PathInfo):\n      raise TypeError(\"expected `%s` but got `%s`\" % (PathInfo, type(src)))\n    if self.path_type != src.path_type:\n      raise ValueError(\n          \"src [%s] does not represent the same path type as self [%s]\" %\n          (src.path_type, self.path_type))\n    if self.components != src.components:\n      raise ValueError(\"src [%s] does not represent the same path as self [%s]\"\n                       % (src.components, self.components))\n    if src.HasField(\"stat_entry\"):\n      self.stat_entry = src.stat_entry\n    self.last_stat_entry_timestamp = max(self.last_stat_entry_timestamp,\n                                         src.last_stat_entry_timestamp)\n    self.directory = self.directory or src.directory",
    "docstring": "Merge path info records.\n\n    Merges src into self.\n    Args:\n      src: An rdfvalues.objects.PathInfo record, will be merged into self.\n\n    Raises:\n      ValueError: If src does not represent the same path."
  },
  {
    "code": "def freeze_js(html):\n    matches = js_src_pattern.finditer(html)\n    if not matches:\n        return html\n    for match in reversed(tuple(matches)):\n        file_name = match.group(1)\n        file_path = os.path.join(js_files_path, file_name)\n        with open(file_path, \"r\", encoding=\"utf-8\") as f:\n            file_content = f.read()\n        fmt = '<script type=\"text/javascript\">{}</script>'\n        js_content = fmt.format(file_content)\n        html = html[:match.start()] + js_content + html[match.end():]\n    return html",
    "docstring": "Freeze all JS assets to the rendered html itself."
  },
  {
    "code": "def build_strings(strings, prefix):\n        strings = [\n            (\n                make_c_str(prefix + str(number), value),\n                reloc_ptr(\n                    prefix + str(number), 'reloc_delta', 'char *'\n                )\n            ) for value, number in sort_values(strings)\n        ]\n        return [i[0] for i in strings], [i[1] for i in strings]",
    "docstring": "Construct string definitions according to\n        the previously maintained table."
  },
  {
    "code": "def mul(left, right):\n    from .mv_mul import MvMul\n    length = max(left, right)\n    if length == 1:\n        return Mul(left, right)\n    return MvMul(left, right)",
    "docstring": "Distribution multiplication.\n\n    Args:\n        left (Dist, numpy.ndarray) : left hand side.\n        right (Dist, numpy.ndarray) : right hand side."
  },
  {
    "code": "def check_types(func):\n    call = PythonCall(func)\n    @wraps(func)\n    def decorator(*args, **kwargs):\n        parameters = call.bind(args, kwargs)\n        for arg_name, expected_type in func.__annotations__.items():\n            if not isinstance(parameters[arg_name], expected_type):\n                raise TypeError(\"{} must be a {}\".format(\n                    arg_name, expected_type))\n        return call.apply(args, kwargs)\n    return decorator",
    "docstring": "Check if annotated function arguments are of the correct type"
  },
  {
    "code": "def _SkipGroup(buffer, pos, end):\n  while 1:\n    (tag_bytes, pos) = ReadTag(buffer, pos)\n    new_pos = SkipField(buffer, pos, end, tag_bytes)\n    if new_pos == -1:\n      return pos\n    pos = new_pos",
    "docstring": "Skip sub-group.  Returns the new position."
  },
  {
    "code": "def purge_dict(idict):\n    odict = {}\n    for key, val in idict.items():\n        if is_null(val):\n            continue\n        odict[key] = val\n    return odict",
    "docstring": "Remove null items from a dictionary"
  },
  {
    "code": "def _refresh(self):\n        new_token = self.authenticate(self._username, self._password)\n        self._token = new_token\n        logger.info('New API token received: \"{}\".'.format(new_token))\n        return self._token",
    "docstring": "Refresh the API token using the currently bound credentials.\n\n        This is simply a convenience method to be invoked automatically if authentication fails\n        during normal client use."
  },
  {
    "code": "def run():\n    _parser_options()\n    set_verbose(args[\"verbose\"])\n    if _check_global_settings():\n        _load_db()\n    else:\n        exit(-1)\n    _setup_server()\n    if args[\"rollback\"]:\n        _server_rollback()\n        okay(\"The server rollback appears to have been successful.\")\n        exit(0)\n    _server_enable()    \n    _list_repos()\n    _handle_install()\n    _do_cron()",
    "docstring": "Main script entry to handle the arguments given to the script."
  },
  {
    "code": "def search_one(self, keyword, arg=None, children=None):\n        if children is None:\n            children = self.substmts\n        for ch in children:\n            if ch.keyword == keyword and (arg is None or ch.arg == arg):\n                return ch\n        return None",
    "docstring": "Return receiver's substmt with `keyword` and optionally `arg`."
  },
  {
    "code": "def set_examples(self, examples):\n    self.store('examples', examples)\n    if len(examples) > 0:\n      self.store('are_sequence_examples',\n                 isinstance(examples[0], tf.train.SequenceExample))\n    return self",
    "docstring": "Sets the examples to be displayed in WIT.\n\n    Args:\n      examples: List of example protos.\n\n    Returns:\n      self, in order to enabled method chaining."
  },
  {
    "code": "def _get_explicit_environ_credentials():\n    explicit_file = os.environ.get(environment_vars.CREDENTIALS)\n    if explicit_file is not None:\n        credentials, project_id = _load_credentials_from_file(\n            os.environ[environment_vars.CREDENTIALS])\n        return credentials, project_id\n    else:\n        return None, None",
    "docstring": "Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment\n    variable."
  },
  {
    "code": "def load_sensor_composites(self, sensor_name):\n        config_filename = sensor_name + \".yaml\"\n        LOG.debug(\"Looking for composites config file %s\", config_filename)\n        composite_configs = config_search_paths(\n            os.path.join(\"composites\", config_filename),\n            self.ppp_config_dir, check_exists=True)\n        if not composite_configs:\n            LOG.debug(\"No composite config found called {}\".format(\n                config_filename))\n            return\n        self._load_config(composite_configs)",
    "docstring": "Load all compositor configs for the provided sensor."
  },
  {
    "code": "def get_properties(obj):\n        properties = {}\n        for property_name in dir(obj):\n            property = getattr(obj, property_name)\n            if PropertyReflector._is_property(property, property_name):\n                properties[property_name] = property\n        return properties",
    "docstring": "Get values of all properties in specified object and returns them as a map.\n\n        :param obj: an object to get properties from.\n\n        :return: a map, containing the names of the object's properties and their values."
  },
  {
    "code": "def set_mime_type(self, mime_type):\n        try:\n            self.set_lexer_from_mime_type(mime_type)\n        except ClassNotFound:\n            _logger().exception('failed to get lexer from mimetype')\n            self._lexer = TextLexer()\n            return False\n        except ImportError:\n            _logger().warning('failed to get lexer from mimetype (%s)' %\n                              mime_type)\n            self._lexer = TextLexer()\n            return False\n        else:\n            return True",
    "docstring": "Update the highlighter lexer based on a mime type.\n\n        :param mime_type: mime type of the new lexer to setup."
  },
  {
    "code": "def tag_timexes(self):\n        if not self.is_tagged(ANALYSIS):\n            self.tag_analysis()\n        if not self.is_tagged(TIMEXES):\n            if self.__timex_tagger is None:\n                self.__timex_tagger = load_default_timex_tagger()\n            self.__timex_tagger.tag_document(self, **self.__kwargs)\n        return self",
    "docstring": "Create ``timexes`` layer.\n        Depends on morphological analysis data in ``words`` layer\n        and tags it automatically, if it is not present."
  },
  {
    "code": "def set_value(self, value, block_events=False):\n        if block_events: self.block_events()\n        self._widget.setValue(value)\n        if block_events: self.unblock_events()",
    "docstring": "Sets the current value of the number box.\n\n        Setting block_events=True will temporarily block the widget from\n        sending any signals when setting the value."
  },
  {
    "code": "def delete_request(\n            self,\n            alias,\n            uri,\n            data=None,\n            json=None,\n            params=None,\n            headers=None,\n            allow_redirects=None,\n            timeout=None):\n        session = self._cache.switch(alias)\n        data = self._format_data_according_to_header(session, data, headers)\n        redir = True if allow_redirects is None else allow_redirects\n        response = self._delete_request(\n            session, uri, data, json, params, headers, redir, timeout)\n        if isinstance(data, bytes):\n            data = data.decode('utf-8')\n        logger.info('Delete Request using : alias=%s, uri=%s, data=%s, \\\n                    headers=%s, allow_redirects=%s ' % (alias, uri, data, headers, redir))\n        return response",
    "docstring": "Send a DELETE request on the session object found using the\n        given `alias`\n\n        ``alias`` that will be used to identify the Session object in the cache\n\n        ``uri`` to send the DELETE request to\n\n        ``json`` a value that will be json encoded\n               and sent as request data if data is not specified\n\n        ``headers`` a dictionary of headers to use with the request\n\n        ``allow_redirects`` Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.\n\n        ``timeout`` connection timeout"
  },
  {
    "code": "def task_transaction(channel):\n    with channel.lock:\n        if channel.poll(0):\n            task = channel.recv()\n            channel.send(Acknowledgement(os.getpid(), task.id))\n        else:\n            raise RuntimeError(\"Race condition between workers\")\n    return task",
    "docstring": "Ensures a task is fetched and acknowledged atomically."
  },
  {
    "code": "def convert(cls, value, from_unit, to_unit):\n        value_ms = value * cls.UNITS_IN_MILLISECONDS[from_unit]\n        return value_ms / cls.UNITS_IN_MILLISECONDS[to_unit]",
    "docstring": "Convert a value from one time unit to another.\n\n        :return: the numeric value converted to the desired unit\n        :rtype: float"
  },
  {
    "code": "def isinstance(instance, ifaces):\n    ifaces = _ensure_ifaces_tuple(ifaces)\n    for iface in ifaces:\n        attributes = (\n            attr\n            for attr in iface.__abstractmethods__\n            if hasattr(getattr(iface, attr), '__iattribute__')\n        )\n        for attribute in attributes:\n            if not hasattr(instance, attribute):\n                return False\n        if not issubclass(type(instance), ifaces):\n            return False\n    return True",
    "docstring": "Check if a given instance is an implementation of the interface."
  },
  {
    "code": "def get_con_id(self):\n        con_id = \"\"\n        if \"contribution\" in self.tables:\n            if \"id\" in self.tables[\"contribution\"].df.columns:\n                con_id = str(self.tables[\"contribution\"].df[\"id\"].values[0])\n        return con_id",
    "docstring": "Return contribution id if available"
  },
  {
    "code": "def convert_ids_to_tokens(self, ids):\n        tokens = []\n        for i in ids:\n            tokens.append(self.ids_to_tokens[i])\n        return tokens",
    "docstring": "Converts a sequence of ids in wordpiece tokens using the vocab."
  },
  {
    "code": "def clear_license(self):\n        if (self.get_license_metadata().is_read_only() or\n                self.get_license_metadata().is_required()):\n            raise errors.NoAccess()\n        self._my_map['license'] = dict(self._license_default)",
    "docstring": "Removes the license.\n\n        raise:  NoAccess - ``Metadata.isRequired()`` is ``true`` or\n                ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def unlistify(n, depth=1, typ=list, get=None):\n    i = 0\n    if depth is None:\n        depth = 1\n    index_desired = get or 0\n    while i < depth and isinstance(n, typ):\n        if len(n):\n            if len(n) > index_desired:\n                n = n[index_desired]\n                i += 1\n        else:\n            return n\n    return n",
    "docstring": "Return the desired element in a list ignoring the rest.\n\n    >>> unlistify([1,2,3])\n    1\n    >>> unlistify([1,[4, 5, 6],3], get=1)\n    [4, 5, 6]\n    >>> unlistify([1,[4, 5, 6],3], depth=2, get=1)\n    5\n    >>> unlistify([1,(4, 5, 6),3], depth=2, get=1)\n    (4, 5, 6)\n    >>> unlistify([1,2,(4, 5, 6)], depth=2, get=2)\n    (4, 5, 6)\n    >>> unlistify([1,2,(4, 5, 6)], depth=2, typ=(list, tuple), get=2)\n    6"
  },
  {
    "code": "def InstallNanny(self):\n    new_config = config.CONFIG.MakeNewConfig()\n    new_config.SetWriteBack(config.CONFIG[\"Config.writeback\"])\n    for option in self.nanny_options:\n      new_config.Set(option, config.CONFIG.Get(option))\n    new_config.Write()\n    args = [\n        config.CONFIG[\"Nanny.binary\"], \"--service_key\",\n        config.CONFIG[\"Client.config_key\"], \"install\"\n    ]\n    logging.debug(\"Calling %s\", (args,))\n    output = subprocess.check_output(\n        args, shell=True, stdin=subprocess.PIPE, stderr=subprocess.PIPE)\n    logging.debug(\"%s\", output)",
    "docstring": "Install the nanny program."
  },
  {
    "code": "def to_string_with_default(value, default_value):\n        result = StringConverter.to_nullable_string(value)\n        return result if result != None else default_value",
    "docstring": "Converts value into string or returns default when value is None.\n\n        :param value: the value to convert.\n\n        :param default_value: the default value.\n\n        :return: string value or default when value is null."
  },
  {
    "code": "def get(self, var, default=None):\n        try:\n            return self.__get(var)\n        except (KeyError, IndexError):\n            return default",
    "docstring": "Return a value from configuration.\n\n        Safe version which always returns a default value if the value is not\n        found."
  },
  {
    "code": "def get_mean_values(self, C, sites, rup, dists, a1100):\n        if isinstance(a1100, np.ndarray):\n            temp_vs30 = sites.vs30\n            temp_z2pt5 = sites.z2pt5\n        else:\n            temp_vs30 = 1100.0 * np.ones(len(sites.vs30))\n            temp_z2pt5 = self._select_basin_model(1100.0) *\\\n                np.ones_like(temp_vs30)\n        return (self._get_magnitude_term(C, rup.mag) +\n                self._get_geometric_attenuation_term(C, rup.mag, dists.rrup) +\n                self._get_style_of_faulting_term(C, rup) +\n                self._get_hanging_wall_term(C, rup, dists) +\n                self._get_shallow_site_response_term(C, temp_vs30, a1100) +\n                self._get_basin_response_term(C, temp_z2pt5) +\n                self._get_hypocentral_depth_term(C, rup) +\n                self._get_fault_dip_term(C, rup) +\n                self._get_anelastic_attenuation_term(C, dists.rrup))",
    "docstring": "Returns the mean values for a specific IMT"
  },
  {
    "code": "def add_column(self, column_name, column_values):\n    if isinstance(column_values, list) and isinstance(column_values[0], list):\n      raise ValueError('\"column_values\" must be a flat list, but we detected '\n                       'that its first entry is a list')\n    if isinstance(column_values, np.ndarray) and column_values.ndim != 1:\n      raise ValueError('\"column_values\" should be of rank 1, '\n                       'but is of rank %d' % column_values.ndim)\n    if len(column_values) != self.num_points:\n      raise ValueError('\"column_values\" should be of length %d, but is of '\n                       'length %d' % (self.num_points, len(column_values)))\n    if column_name in self.name_to_values:\n      raise ValueError('The column name \"%s\" is already used' % column_name)\n    self.column_names.append(column_name)\n    self.name_to_values[column_name] = column_values",
    "docstring": "Adds a named column of metadata values.\n\n    Args:\n      column_name: Name of the column.\n      column_values: 1D array/list/iterable holding the column values. Must be\n          of length `num_points`. The i-th value corresponds to the i-th point.\n\n    Raises:\n      ValueError: If `column_values` is not 1D array, or of length `num_points`,\n          or the `name` is already used."
  },
  {
    "code": "def get_sentences_list(self, sentences=1):\n        if sentences < 1:\n            raise ValueError('Param \"sentences\" must be greater than 0.')\n        sentences_list = []\n        while sentences:\n            num_rand_words = random.randint(self.MIN_WORDS, self.MAX_WORDS)\n            random_sentence = self.make_sentence(\n                random.sample(self.words, num_rand_words))\n            sentences_list.append(random_sentence)\n            sentences -= 1\n        return sentences_list",
    "docstring": "Return sentences in list.\n\n        :param int sentences: how many sentences\n        :returns: list of strings with sentence\n        :rtype: list"
  },
  {
    "code": "def lock_option(self, key, subkey):\n        key, subkey = _lower_keys(key, subkey)\n        _entry_must_exist(self.gc, key, subkey)\n        self.gc.loc[\n            (self.gc[\"k1\"] == key) &\n            (self.gc[\"k2\"] == subkey), \"locked\"] = True",
    "docstring": "Make an option unmutable.\n\n        :param str key: First identifier of the option.\n        :param str subkey: Second identifier of the option.\n\n        :raise:\n            :NotRegisteredError: If ``key`` or ``subkey`` do not define any\n                option."
  },
  {
    "code": "def resolve_nested_dict(nested_dict):\n    res = {}\n    for k, v in nested_dict.items():\n        if isinstance(v, dict):\n            for k_, v_ in resolve_nested_dict(v).items():\n                res[(k, ) + k_] = v_\n        else:\n            res[(k, )] = v\n    return res",
    "docstring": "Flattens a nested dict by joining keys into tuple of paths.\n\n    Can then be passed into `format_vars`."
  },
  {
    "code": "def _estimate_p_values(self):\n        if not self._is_fitted:\n            raise AttributeError('GAM has not been fitted. Call fit first.')\n        p_values = []\n        for term_i in range(len(self.terms)):\n            p_values.append(self._compute_p_value(term_i))\n        return p_values",
    "docstring": "estimate the p-values for all features"
  },
  {
    "code": "def scene_name(sequence_number, scene_id, name):\n        return MessageWriter().string(\"scene.name\").uint64(sequence_number).uint32(scene_id).string(name).get()",
    "docstring": "Create a scene.name message"
  },
  {
    "code": "def get_pwm_list(pwm_id_list, pseudocountProb=0.0001):\n    l = load_motif_db(HOCOMOCO_PWM)\n    l = {k.split()[0]: v for k, v in l.items()}\n    pwm_list = [PWM(_normalize_pwm(l[m]) + pseudocountProb, name=m) for m in pwm_id_list]\n    return pwm_list",
    "docstring": "Get a list of HOCOMOCO PWM's.\n\n    # Arguments\n        pwm_id_list: List of id's from the `PWM_id` column in `get_metadata()` table\n        pseudocountProb: Added pseudocount probabilities to the PWM\n\n    # Returns\n        List of `concise.utils.pwm.PWM` instances."
  },
  {
    "code": "def _customer_lifetime_value(\n    transaction_prediction_model, frequency, recency, T, monetary_value, time=12, discount_rate=0.01, freq=\"D\"\n):\n    df = pd.DataFrame(index=frequency.index)\n    df[\"clv\"] = 0\n    steps = np.arange(1, time + 1)\n    factor = {\"W\": 4.345, \"M\": 1.0, \"D\": 30, \"H\": 30 * 24}[freq]\n    for i in steps * factor:\n        expected_number_of_transactions = transaction_prediction_model.predict(\n            i, frequency, recency, T\n        ) - transaction_prediction_model.predict(i - factor, frequency, recency, T)\n        df[\"clv\"] += (monetary_value * expected_number_of_transactions) / (1 + discount_rate) ** (i / factor)\n    return df[\"clv\"]",
    "docstring": "Compute the average lifetime value for a group of one or more customers.\n\n    This method computes the average lifetime value for a group of one or more customers.\n\n    Parameters\n    ----------\n    transaction_prediction_model:\n        the model to predict future transactions\n    frequency: array_like\n        the frequency vector of customers' purchases (denoted x in literature).\n    recency: array_like\n        the recency vector of customers' purchases (denoted t_x in literature).\n    T: array_like\n        the vector of customers' age (time since first purchase)\n    monetary_value: array_like\n        the monetary value vector of customer's purchases (denoted m in literature).\n    time: int, optional\n        the lifetime expected for the user in months. Default: 12\n    discount_rate: float, optional\n        the monthly adjusted discount rate. Default: 1\n\n    Returns\n    -------\n    :obj: Series\n        series with customer ids as index and the estimated customer lifetime values as values"
  },
  {
    "code": "def _resource_prefix(self, resource=None):\n        px = 'ELASTICSEARCH'\n        if resource and config.DOMAIN[resource].get('elastic_prefix'):\n            px = config.DOMAIN[resource].get('elastic_prefix')\n        return px",
    "docstring": "Get elastic prefix for given resource.\n\n        Resource can specify ``elastic_prefix`` which behaves same like ``mongo_prefix``."
  },
  {
    "code": "def get_backspace_count(self, buffer):\n        if TriggerMode.ABBREVIATION in self.modes and self.backspace:\n            if self._should_trigger_abbreviation(buffer):\n                abbr = self._get_trigger_abbreviation(buffer)\n                stringBefore, typedAbbr, stringAfter = self._partition_input(buffer, abbr)\n                return len(abbr) + len(stringAfter)\n        if self.parent is not None:\n            return self.parent.get_backspace_count(buffer)\n        return 0",
    "docstring": "Given the input buffer, calculate how many backspaces are needed to erase the text\n        that triggered this folder."
  },
  {
    "code": "def _create_driver(self, **kwargs):\n        if self.driver is None:\n            self.driver = self.create_driver(**kwargs)\n            self.init_driver_func(self.driver)",
    "docstring": "Create webdriver, assign it to ``self.driver``, and run webdriver\n        initiation process, which is usually used for manual login."
  },
  {
    "code": "def parse(self, module):\n        self.parse_block(module.refstring, module, module, 0)\n        min_start = len(module.refstring)\n        for x in module.executables:\n            if module.executables[x].start < min_start:\n                min_start = module.executables[x].start\n        module.contains = module.refstring[min_start::]",
    "docstring": "Extracts all the subroutine and function definitions from the specified module."
  },
  {
    "code": "def _dirdiffandupdate(self, dir1, dir2):\n        self._dowork(dir1, dir2, None, self._update)",
    "docstring": "Private function which does directory diff & update"
  },
  {
    "code": "def collect_blame_info(cls, matches):\n        old_area = None\n        for filename, ranges in matches:\n            area, name = os.path.split(filename)\n            if not area:\n                area = '.'\n            if area != old_area:\n                print(\"\\n\\n%s/\\n\" % area)\n                old_area = area\n            print(\"%s \" % name, end=\"\")\n            filter = cls.build_line_range_filter(ranges)\n            command = ['git', 'blame', '--line-porcelain'] + filter + [name]\n            os.chdir(area)\n            p = subprocess.Popen(command, stdout=subprocess.PIPE,\n                                 stderr=subprocess.PIPE)\n            out, err = p.communicate()\n            if err:\n                print(\" <<<<<<<<<< Unable to collect 'git blame' info:\", err)\n            else:\n                yield out",
    "docstring": "Runs git blame on files, for the specified sets of line ranges.\n\n        If no line range tuples are provided, it will do all lines."
  },
  {
    "code": "def AddFileEntry(\n      self, path, file_entry_type=definitions.FILE_ENTRY_TYPE_FILE,\n      file_data=None, link_data=None):\n    if path in self._paths:\n      raise KeyError('File entry already set for path: {0:s}.'.format(path))\n    if file_data and file_entry_type != definitions.FILE_ENTRY_TYPE_FILE:\n      raise ValueError('File data set for non-file file entry type.')\n    if link_data and file_entry_type != definitions.FILE_ENTRY_TYPE_LINK:\n      raise ValueError('Link data set for non-link file entry type.')\n    if file_data is not None:\n      path_data = file_data\n    elif link_data is not None:\n      path_data = link_data\n    else:\n      path_data = None\n    self._paths[path] = (file_entry_type, path_data)",
    "docstring": "Adds a fake file entry.\n\n    Args:\n      path (str): path of the file entry.\n      file_entry_type (Optional[str]): type of the file entry object.\n      file_data (Optional[bytes]): data of the fake file-like object.\n      link_data (Optional[bytes]): link data of the fake file entry object.\n\n    Raises:\n      KeyError: if the path already exists.\n      ValueError: if the file data is set but the file entry type is not a file\n          or if the link data is set but the file entry type is not a link."
  },
  {
    "code": "def on_key_press(self, event):\n        key = event.key\n        if event.modifiers:\n            return\n        if self.enable_keyboard_pan and key in self._arrows:\n            self._pan_keyboard(key)\n        if key in self._pm:\n            self._zoom_keyboard(key)\n        if key == 'R':\n            self.reset()",
    "docstring": "Pan and zoom with the keyboard."
  },
  {
    "code": "def get_clonespec_for_valid_snapshot(config_spec, object_ref, reloc_spec, template, vm_):\n    moving = True\n    if QUICK_LINKED_CLONE == vm_['snapshot']['disk_move_type']:\n        reloc_spec.diskMoveType = QUICK_LINKED_CLONE\n    elif CURRENT_STATE_LINKED_CLONE == vm_['snapshot']['disk_move_type']:\n        reloc_spec.diskMoveType = CURRENT_STATE_LINKED_CLONE\n    elif COPY_ALL_DISKS_FULL_CLONE == vm_['snapshot']['disk_move_type']:\n        reloc_spec.diskMoveType = COPY_ALL_DISKS_FULL_CLONE\n    elif FLATTEN_DISK_FULL_CLONE == vm_['snapshot']['disk_move_type']:\n        reloc_spec.diskMoveType = FLATTEN_DISK_FULL_CLONE\n    else:\n        moving = False\n    if moving:\n        return build_clonespec(config_spec, object_ref, reloc_spec, template)\n    return None",
    "docstring": "return clonespec only if values are valid"
  },
  {
    "code": "def facts():\n    ret = {}\n    try:\n        ret['facts'] = __proxy__['junos.get_serialized_facts']()\n        ret['out'] = True\n    except Exception as exception:\n        ret['message'] = 'Could not display facts due to \"{0}\"'.format(\n            exception)\n        ret['out'] = False\n    return ret",
    "docstring": "Displays the facts gathered during the connection.\n    These facts are also stored in Salt grains.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'device_name' junos.facts"
  },
  {
    "code": "def view_job_info(token, dstore):\n    data = [['task', 'sent', 'received']]\n    for task in dstore['task_info']:\n        dset = dstore['task_info/' + task]\n        if 'argnames' in dset.attrs:\n            argnames = dset.attrs['argnames'].split()\n            totsent = dset.attrs['sent']\n            sent = ['%s=%s' % (a, humansize(s))\n                    for s, a in sorted(zip(totsent, argnames), reverse=True)]\n            recv = dset['received'].sum()\n            data.append((task, ' '.join(sent), humansize(recv)))\n    return rst_table(data)",
    "docstring": "Determine the amount of data transferred from the controller node\n    to the workers and back in a classical calculation."
  },
  {
    "code": "def get_parent_catalogs(self, catalog_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.get_parent_catalogs(catalog_id=catalog_id)\n        return CatalogLookupSession(\n            self._proxy,\n            self._runtime).get_catalogs_by_ids(\n                list(self.get_parent_catalog_ids(catalog_id)))",
    "docstring": "Gets the parent catalogs of the given ``id``.\n\n        arg:    catalog_id (osid.id.Id): the ``Id`` of the ``Catalog``\n                to query\n        return: (osid.cataloging.CatalogList) - the parent catalogs of\n                the ``id``\n        raise:  NotFound - a ``Catalog`` identified by ``Id is`` not\n                found\n        raise:  NullArgument - ``catalog_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _build_cookie_jar(cls, session: AppSession):\n        if not session.args.cookies:\n            return\n        if session.args.load_cookies or session.args.save_cookies:\n            session.factory.set('CookieJar', BetterMozillaCookieJar)\n            cookie_jar = session.factory.new('CookieJar')\n            if session.args.load_cookies:\n                cookie_jar.load(session.args.load_cookies, ignore_discard=True)\n        else:\n            cookie_jar = session.factory.new('CookieJar')\n        policy = session.factory.new('CookiePolicy', cookie_jar=cookie_jar)\n        cookie_jar.set_policy(policy)\n        _logger.debug(__('Loaded cookies: {0}', list(cookie_jar)))\n        cookie_jar_wrapper = session.factory.new(\n            'CookieJarWrapper',\n            cookie_jar,\n            save_filename=session.args.save_cookies,\n            keep_session_cookies=session.args.keep_session_cookies,\n        )\n        return cookie_jar_wrapper",
    "docstring": "Build the cookie jar"
  },
  {
    "code": "def ms_to_datetime(ms):\n    dt = datetime.datetime.utcfromtimestamp(ms / 1000)\n    return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)",
    "docstring": "Converts a millisecond accuracy timestamp to a datetime"
  },
  {
    "code": "def pad_char(text: str, width: int, char: str = '\\n') -> str:\r\n    dis = width - len(text)\r\n    if dis < 0:\r\n        raise ValueError\r\n    if dis > 0:\r\n        text += char * dis\r\n    return text",
    "docstring": "Pads a text until length width."
  },
  {
    "code": "def _call(self, x):\n        pointwise_norm = self.pointwise_norm(x)\n        return pointwise_norm.inner(pointwise_norm.space.one())",
    "docstring": "Return the group L1-norm of ``x``."
  },
  {
    "code": "def polygon_from_points(points):\n    polygon = []\n    for pair in points.split(\" \"):\n        x_y = pair.split(\",\")\n        polygon.append([float(x_y[0]), float(x_y[1])])\n    return polygon",
    "docstring": "Constructs a numpy-compatible polygon from a page representation."
  },
  {
    "code": "def bind_filter(self, direction, filter_name):\n        if direction not in self._dynamips_direction:\n            raise DynamipsError(\"Unknown direction {} to bind filter {}:\".format(direction, filter_name))\n        dynamips_direction = self._dynamips_direction[direction]\n        yield from self._hypervisor.send(\"nio bind_filter {name} {direction} {filter}\".format(name=self._name,\n                                                                                              direction=dynamips_direction,\n                                                                                              filter=filter_name))\n        if direction == \"in\":\n            self._input_filter = filter_name\n        elif direction == \"out\":\n            self._output_filter = filter_name\n        elif direction == \"both\":\n            self._input_filter = filter_name\n            self._output_filter = filter_name",
    "docstring": "Adds a packet filter to this NIO.\n        Filter \"freq_drop\" drops packets.\n        Filter \"capture\" captures packets.\n\n        :param direction: \"in\", \"out\" or \"both\"\n        :param filter_name: name of the filter to apply"
  },
  {
    "code": "def create_spot_datafeed_subscription(self, bucket, prefix):\n        params = {'Bucket' : bucket}\n        if prefix:\n            params['Prefix'] = prefix\n        return self.get_object('CreateSpotDatafeedSubscription',\n                               params, SpotDatafeedSubscription, verb='POST')",
    "docstring": "Create a spot instance datafeed subscription for this account.\n\n        :type bucket: str or unicode\n        :param bucket: The name of the bucket where spot instance data\n                       will be written.  The account issuing this request\n                       must have FULL_CONTROL access to the bucket\n                       specified in the request.\n\n        :type prefix: str or unicode\n        :param prefix: An optional prefix that will be pre-pended to all\n                       data files written to the bucket.\n\n        :rtype: :class:`boto.ec2.spotdatafeedsubscription.SpotDatafeedSubscription`\n        :return: The datafeed subscription object or None"
  },
  {
    "code": "def process_fields(self, fields):\n\t\tresult = []\n\t\tstrip = ''.join(self.PREFIX_MAP)\n\t\tfor field in fields:\n\t\t\tdirection = self.PREFIX_MAP['']\n\t\t\tif field[0] in self.PREFIX_MAP:\n\t\t\t\tdirection = self.PREFIX_MAP[field[0]]\n\t\t\t\tfield = field.lstrip(strip)\n\t\t\tresult.append((field, direction))\n\t\treturn result",
    "docstring": "Process a list of simple string field definitions and assign their order based on prefix."
  },
  {
    "code": "def load_dotenv(dotenv_path, verbose=False):\n    if not os.path.exists(dotenv_path):\n        if verbose:\n            warnings.warn(f\"Not loading {dotenv_path}, it doesn't exist.\")\n        return None\n    for k, v in dotenv_values(dotenv_path).items():\n        os.environ.setdefault(k, v)\n    return True",
    "docstring": "Read a .env file and load into os.environ.\n\n    :param dotenv_path:\n    :type dotenv_path: str\n    :param verbose: verbosity flag, raise warning if path does not exist\n    :return: success flag"
  },
  {
    "code": "def iv(b, **kwargs):\n    import matplotlib.pyplot as plt\n    import imview.imviewer as imview \n    b = checkma(b)\n    fig = plt.figure()\n    imview.bma_fig(fig, b, **kwargs)\n    plt.show()\n    return fig",
    "docstring": "Quick access to imview for interactive sessions"
  },
  {
    "code": "def withconfig(self, keysuffix):\n        def decorator(cls):\n            return self.loadconfig(keysuffix, cls)\n        return decorator",
    "docstring": "Load configurations with this decorator"
  },
  {
    "code": "def run(self):\n        self.files_exist()\n        self.info_file()\n        sources = self.sources\n        if len(sources) > 1 and self.sbo_sources != sources:\n            sources = self.sbo_sources\n        BuildPackage(self.script, sources, self.path, auto=True).build()\n        raise SystemExit()",
    "docstring": "Build package and fix ordelist per checksum"
  },
  {
    "code": "def return_features_numpy(self, names='all'):\n        if self._prepopulated is False:\n            raise errors.EmptyDatabase(self.dbpath)\n        else:\n            return return_features_numpy_base(self.dbpath, self._set_object, self.points_amt, names)",
    "docstring": "Returns a 2d numpy array of extracted features\n\n        Parameters\n        ----------\n        names : list of strings, a list of feature names which are to be retrieved from the database, if equal to 'all',\n        all features will be returned, default value: 'all'\n\n        Returns\n        -------\n        A numpy array of features, each row corresponds to a single datapoint. If a single feature is a 1d numpy array,\n        then it will be unrolled into the resulting array. Higher-dimensional numpy arrays are not supported."
  },
  {
    "code": "def query(self, variables, evidence=None, joint=True):\n        return self._query(variables=variables, operation='marginalize', evidence=evidence, joint=joint)",
    "docstring": "Query method using belief propagation.\n\n        Parameters\n        ----------\n        variables: list\n            list of variables for which you want to compute the probability\n\n        evidence: dict\n            a dict key, value pair as {var: state_of_var_observed}\n            None if no evidence\n\n        joint: boolean\n            If True, returns a Joint Distribution over `variables`.\n            If False, returns a dict of distributions over each of the `variables`.\n\n        Examples\n        --------\n        >>> from pgmpy.factors.discrete import TabularCPD\n        >>> from pgmpy.models import BayesianModel\n        >>> from pgmpy.inference import BeliefPropagation\n        >>> bayesian_model = BayesianModel([('A', 'J'), ('R', 'J'), ('J', 'Q'),\n        ...                                 ('J', 'L'), ('G', 'L')])\n        >>> cpd_a = TabularCPD('A', 2, [[0.2], [0.8]])\n        >>> cpd_r = TabularCPD('R', 2, [[0.4], [0.6]])\n        >>> cpd_j = TabularCPD('J', 2,\n        ...                    [[0.9, 0.6, 0.7, 0.1],\n        ...                     [0.1, 0.4, 0.3, 0.9]],\n        ...                    ['R', 'A'], [2, 2])\n        >>> cpd_q = TabularCPD('Q', 2,\n        ...                    [[0.9, 0.2],\n        ...                     [0.1, 0.8]],\n        ...                    ['J'], [2])\n        >>> cpd_l = TabularCPD('L', 2,\n        ...                    [[0.9, 0.45, 0.8, 0.1],\n        ...                     [0.1, 0.55, 0.2, 0.9]],\n        ...                    ['G', 'J'], [2, 2])\n        >>> cpd_g = TabularCPD('G', 2, [[0.6], [0.4]])\n        >>> bayesian_model.add_cpds(cpd_a, cpd_r, cpd_j, cpd_q, cpd_l, cpd_g)\n        >>> belief_propagation = BeliefPropagation(bayesian_model)\n        >>> belief_propagation.query(variables=['J', 'Q'],\n        ...                          evidence={'A': 0, 'R': 0, 'G': 0, 'L': 1})"
  },
  {
    "code": "def getReferenceByName(self, name):\n        if name not in self._referenceNameMap:\n            raise exceptions.ReferenceNameNotFoundException(name)\n        return self._referenceNameMap[name]",
    "docstring": "Returns the reference with the specified name."
  },
  {
    "code": "def add_token_to_namespace(self, token: str, namespace: str = 'tokens') -> int:\n        if not isinstance(token, str):\n            raise ValueError(\"Vocabulary tokens must be strings, or saving and loading will break.\"\n                             \"  Got %s (with type %s)\" % (repr(token), type(token)))\n        if token not in self._token_to_index[namespace]:\n            index = len(self._token_to_index[namespace])\n            self._token_to_index[namespace][token] = index\n            self._index_to_token[namespace][index] = token\n            return index\n        else:\n            return self._token_to_index[namespace][token]",
    "docstring": "Adds ``token`` to the index, if it is not already present.  Either way, we return the index of\n        the token."
  },
  {
    "code": "def get_vexrc(options, environ):\n    if options.config and not os.path.exists(options.config):\n        raise exceptions.InvalidVexrc(\"nonexistent config: {0!r}\".format(options.config))\n    filename = options.config or os.path.expanduser('~/.vexrc')\n    vexrc = config.Vexrc.from_file(filename, environ)\n    return vexrc",
    "docstring": "Get a representation of the contents of the config file.\n\n    :returns:\n        a Vexrc instance."
  },
  {
    "code": "def create_client_with_manual_poll(api_key, config_cache_class=None,\n                                   base_url=None):\n    if api_key is None:\n        raise ConfigCatClientException('API Key is required.')\n    return ConfigCatClient(api_key, 0, 0, None, 0, config_cache_class, base_url)",
    "docstring": "Create an instance of ConfigCatClient and setup Manual Poll mode with custom options\n\n    :param api_key: ConfigCat ApiKey to access your configuration.\n    :param config_cache_class: If you want to use custom caching instead of the client's default InMemoryConfigCache,\n    You can provide an implementation of ConfigCache.\n    :param base_url: You can set a base_url if you want to use a proxy server between your application and ConfigCat"
  },
  {
    "code": "def has_textonly_pdf():\n    args_tess = ['tesseract', '--print-parameters', 'pdf']\n    params = ''\n    try:\n        params = check_output(args_tess, universal_newlines=True, stderr=STDOUT)\n    except CalledProcessError as e:\n        print(\"Could not --print-parameters from tesseract\", file=sys.stderr)\n        raise MissingDependencyError from e\n    if 'textonly_pdf' in params:\n        return True\n    return False",
    "docstring": "Does Tesseract have textonly_pdf capability?\n\n    Available in v4.00.00alpha since January 2017. Best to\n    parse the parameter list"
  },
  {
    "code": "def Delete(self):\n    args = user_management_pb2.ApiDeleteGrrUserArgs(username=self.username)\n    self._context.SendRequest(\"DeleteGrrUser\", args)",
    "docstring": "Deletes the user."
  },
  {
    "code": "def cast_values_csvs(d, idx, x):\n    try:\n        d[idx].append(float(x))\n    except ValueError:\n        d[idx].append(x)\n    except KeyError as e:\n        logger_misc.warn(\"cast_values_csv: KeyError: col: {}, {}\".format(x, e))\n    return d",
    "docstring": "Attempt to cast string to float. If error, keep as a string.\n\n    :param dict d: Data\n    :param int idx: Index number\n    :param str x: Data\n    :return any:"
  },
  {
    "code": "def create(self, friendly_name, event_callback_url=values.unset,\n               events_filter=values.unset, multi_task_enabled=values.unset,\n               template=values.unset, prioritize_queue_order=values.unset):\n        data = values.of({\n            'FriendlyName': friendly_name,\n            'EventCallbackUrl': event_callback_url,\n            'EventsFilter': events_filter,\n            'MultiTaskEnabled': multi_task_enabled,\n            'Template': template,\n            'PrioritizeQueueOrder': prioritize_queue_order,\n        })\n        payload = self._version.create(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return WorkspaceInstance(self._version, payload, )",
    "docstring": "Create a new WorkspaceInstance\n\n        :param unicode friendly_name: Human readable description of this workspace\n        :param unicode event_callback_url: If provided, the Workspace will publish events to this URL.\n        :param unicode events_filter: Use this parameter to receive webhooks on EventCallbackUrl for specific events on a workspace.\n        :param bool multi_task_enabled: Multi tasking allows workers to handle multiple tasks simultaneously.\n        :param unicode template: One of the available template names.\n        :param WorkspaceInstance.QueueOrder prioritize_queue_order: Use this parameter to configure whether to prioritize LIFO or FIFO when workers are receiving Tasks from combination of LIFO and FIFO TaskQueues.\n\n        :returns: Newly created WorkspaceInstance\n        :rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceInstance"
  },
  {
    "code": "def _get_proc_username(proc):\n    try:\n        return salt.utils.data.decode(proc.username() if PSUTIL2 else proc.username)\n    except (psutil.NoSuchProcess, psutil.AccessDenied, KeyError):\n        return None",
    "docstring": "Returns the username of a Process instance.\n\n    It's backward compatible with < 2.0 versions of psutil."
  },
  {
    "code": "def _switch_partition() -> RootPartitions:\n    res = subprocess.check_output(['ot-switch-partitions'])\n    for line in res.split(b'\\n'):\n        matches = re.match(\n            b'Current boot partition: ([23]), setting to ([23])',\n            line)\n        if matches:\n            return {b'2': RootPartitions.TWO,\n                    b'3': RootPartitions.THREE}[matches.group(2)]\n    else:\n        raise RuntimeError(f'Bad output from ot-switch-partitions: {res}')",
    "docstring": "Switch the active boot partition using the switch script"
  },
  {
    "code": "def ver_cmp(ver1, ver2):\n    return cmp(\n        pkg_resources.parse_version(ver1), pkg_resources.parse_version(ver2)\n    )",
    "docstring": "Compare lago versions\n\n    Args:\n        ver1(str): version string\n        ver2(str): version string\n\n    Returns:\n        Return negative if ver1<ver2, zero if ver1==ver2, positive if\n        ver1>ver2."
  },
  {
    "code": "def get_min_instability(self, min_voltage=None, max_voltage=None):\n        data = []\n        for pair in self._select_in_voltage_range(min_voltage, max_voltage):\n            if pair.decomp_e_charge is not None:\n                data.append(pair.decomp_e_charge)\n            if pair.decomp_e_discharge is not None:\n                data.append(pair.decomp_e_discharge)\n        return min(data) if len(data) > 0 else None",
    "docstring": "The minimum instability along a path for a specific voltage range.\n\n        Args:\n            min_voltage: The minimum allowable voltage.\n            max_voltage: The maximum allowable voltage.\n\n        Returns:\n            Minimum decomposition energy of all compounds along the insertion\n            path (a subset of the path can be chosen by the optional arguments)"
  },
  {
    "code": "def hash(self):\n        return hash(\n            self._shape + (\n                self.tilewidth, self.tilelength, self.tiledepth,\n                self.bitspersample, self.fillorder, self.predictor,\n                self.extrasamples, self.photometric, self.compression,\n                self.planarconfig))",
    "docstring": "Return checksum to identify pages in same series."
  },
  {
    "code": "def _deserialize(cls, key, value, fields):\n        converter = cls._get_converter_for_field(key, None, fields)\n        return converter.deserialize(value)",
    "docstring": "Marshal incoming data into Python objects."
  },
  {
    "code": "def calc_qpout_v1(self):\n    der = self.parameters.derived.fastaccess\n    flu = self.sequences.fluxes.fastaccess\n    for idx in range(der.nmb):\n        flu.qpout[idx] = flu.qma[idx]+flu.qar[idx]",
    "docstring": "Calculate the ARMA results for the different response functions.\n\n    Required derived parameter:\n      |Nmb|\n\n    Required flux sequences:\n      |QMA|\n      |QAR|\n\n    Calculated flux sequence:\n      |QPOut|\n\n    Examples:\n\n        Initialize an arma model with three different response functions:\n\n        >>> from hydpy.models.arma import *\n        >>> parameterstep()\n        >>> derived.nmb(3)\n        >>> fluxes.qma.shape = 3\n        >>> fluxes.qar.shape = 3\n        >>> fluxes.qpout.shape = 3\n\n        Define the output values of the MA and of the AR processes\n        associated with the three response functions and apply\n        method |calc_qpout_v1|:\n\n        >>> fluxes.qar = 4.0, 5.0, 6.0\n        >>> fluxes.qma = 1.0, 2.0, 3.0\n        >>> model.calc_qpout_v1()\n        >>> fluxes.qpout\n        qpout(5.0, 7.0, 9.0)"
  },
  {
    "code": "def parse_kwargs(kwargs):\n    d = defaultdict(list)\n    for k, v in ((k.lstrip('-'), v) for k,v in (a.split('=') for a in kwargs)):\n        d[k].append(v)\n    ret = {}\n    for k, v in d.items():\n        if len(v) == 1 and type(v) is list:\n            ret[k] = v[0]\n        else:\n            ret[k] = v\n    return ret",
    "docstring": "Convert a list of kwargs into a dictionary. Duplicates of the same keyword\n    get added to an list within the dictionary.\n\n    >>> parse_kwargs(['--var1=1', '--var2=2', '--var1=3']\n    {'var1': [1, 3], 'var2': 2}"
  },
  {
    "code": "def get_script_property(value, is_bytes=False):\n    obj = unidata.ascii_scripts if is_bytes else unidata.unicode_scripts\n    if value.startswith('^'):\n        negated = value[1:]\n        value = '^' + unidata.unicode_alias['script'].get(negated, negated)\n    else:\n        value = unidata.unicode_alias['script'].get(value, value)\n    return obj[value]",
    "docstring": "Get `SC` property."
  },
  {
    "code": "def connect(self, region, **kw_params):\n        self.ec2 = boto.ec2.connect_to_region(region, **kw_params)\n        if not self.ec2:\n            raise EC2ManagerException('Unable to connect to region \"%s\"' % region)\n        self.remote_images.clear()\n        if self.images and any(('image_name' in img and 'image_id' not in img) for img in self.images.values()):\n            for img in self.images.values():\n                if 'image_name' in img and 'image_id' not in img:\n                    img['image_id'] = self.resolve_image_name(img.pop('image_name'))",
    "docstring": "Connect to a EC2.\n\n        :param region: The name of the region to connect to.\n        :type region: str\n        :param kw_params:\n        :type kw_params: dict"
  },
  {
    "code": "def get_record_types(self):\n        from ..type.objects import TypeList\n        type_list = []\n        for type_idstr in self._supported_record_type_ids:\n            type_list.append(Type(**self._record_type_data_sets[Id(type_idstr).get_identifier()]))\n        return TypeList(type_list)",
    "docstring": "Gets the record types available in this object.\n\n        A record ``Type`` explicitly indicates the specification of an\n        interface to the record. A record may or may not inherit other\n        record interfaces through interface inheritance in which case\n        support of a record type may not be explicit in the returned\n        list. Interoperability with the typed interface to this object\n        should be performed through ``hasRecordType()``.\n\n        return: (osid.type.TypeList) - the record types available\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def default(self):\n        output = ensure_unicode(self.git.log(\n            '-1',\n            '-p',\n            '--no-color',\n            '--format=%s',\n        ).stdout)\n        lines = output.splitlines()\n        return u'\\n'.join(\n            itertools.chain(\n                lines[:1],\n                itertools.islice(\n                    itertools.dropwhile(\n                        lambda x: not x.startswith('+++'),\n                        lines[1:],\n                    ),\n                    1,\n                    None,\n                ),\n            )\n        )",
    "docstring": "Return last changes in truncated unified diff format"
  },
  {
    "code": "def defaults():\n        return dict((str(k), str(v)) for k, v in cma_default_options.items())",
    "docstring": "return a dictionary with default option values and description"
  },
  {
    "code": "def add(self, entity):\n        characteristic = self.extract_traits(entity)\n        if not characteristic.traits:\n            return\n        if characteristic.is_matching:\n            self.add_match(entity, *characteristic.traits)\n        else:\n            self.add_mismatch(entity, *characteristic.traits)",
    "docstring": "Add entity to index.\n\n        :param object entity: single object to add to box's index"
  },
  {
    "code": "def zip_dict(a: Dict[str, A], b: Dict[str, B]) \\\n        -> Dict[str, Tuple[Optional[A], Optional[B]]]:\n    return {key: (a.get(key), b.get(key)) for key in a.keys() | b.keys()}",
    "docstring": "Combine the values within two dictionaries by key.\n\n    :param a: The first dictionary.\n    :param b: The second dictionary.\n    :return: A dictionary containing all keys that appear in the union of a and\n             b. Values are pairs where the first part is a's value for the key,\n             and right second part b's value."
  },
  {
    "code": "def get_commits(self, since_sha=None):\n        assert self.tempdir\n        cmd = ['git', 'log', '--first-parent', '--reverse', COMMIT_FORMAT]\n        if since_sha:\n            commits = [self.get_commit(since_sha)]\n            cmd.append('{}..HEAD'.format(since_sha))\n        else:\n            commits = []\n            cmd.append('HEAD')\n        output = cmd_output(*cmd, cwd=self.tempdir)\n        for sha, date in chunk_iter(output.splitlines(), 2):\n            commits.append(Commit(sha, int(date)))\n        return commits",
    "docstring": "Returns a list of Commit objects.\n\n        Args:\n           since_sha - (optional) A sha to search from"
  },
  {
    "code": "def set_ard_time(self, us):\n        t = int((us / 250) - 1)\n        if (t < 0):\n            t = 0\n        if (t > 0xF):\n            t = 0xF\n        _send_vendor_setup(self.handle, SET_RADIO_ARD, t, 0, ())",
    "docstring": "Set the ACK retry delay for radio communication"
  },
  {
    "code": "def _default(self, obj):\n        return obj.__dict__ if isinstance(obj, JsonObj) else json.JSONDecoder().decode(obj)",
    "docstring": "return a serialized version of obj or raise a TypeError\n\n        :param obj:\n        :return: Serialized version of obj"
  },
  {
    "code": "def request_login(blink, url, username, password, is_retry=False):\n    headers = {\n        'Host': DEFAULT_URL,\n        'Content-Type': 'application/json'\n    }\n    data = dumps({\n        'email': username,\n        'password': password,\n        'client_specifier': 'iPhone 9.2 | 2.2 | 222'\n    })\n    return http_req(blink, url=url, headers=headers, data=data,\n                    json_resp=False, reqtype='post', is_retry=is_retry)",
    "docstring": "Login request.\n\n    :param blink: Blink instance.\n    :param url: Login url.\n    :param username: Blink username.\n    :param password: Blink password.\n    :param is_retry: Is this part of a re-authorization attempt?"
  },
  {
    "code": "def get_as_float_with_default(self, index, default_value):\n        value = self[index]\n        return FloatConverter.to_float_with_default(value, default_value)",
    "docstring": "Converts array element into a float or returns default value if conversion is not possible.\n\n        :param index: an index of element to get.\n\n        :param default_value: the default value\n\n        :return: float value ot the element or default value if conversion is not supported."
  },
  {
    "code": "def _auto_commit(self):\n        if not self.auto_commit or self.auto_commit_every_n is None:\n            return\n        if self.count_since_commit >= self.auto_commit_every_n:\n            self.commit()",
    "docstring": "Check if we have to commit based on number of messages and commit"
  },
  {
    "code": "def updateData(self,exten,data):\n        _extnum=self._interpretExten(exten)\n        fimg = fileutil.openImage(self._filename, mode='update', memmap=False)\n        fimg[_extnum].data = data\n        fimg[_extnum].header = self._image[_extnum].header\n        fimg.close()",
    "docstring": "Write out updated data and header to\n            the original input file for this object."
  },
  {
    "code": "def languages_column(self, obj):\n        languages = self.get_available_languages(obj)\n        return '<span class=\"available-languages\">{0}</span>'.format(\n            \" \".join(languages)\n        )",
    "docstring": "Adds languages columns."
  },
  {
    "code": "def ip(self):\n        if not self._ip:\n            if 'ip' in self.config:\n                ip = self.config['ip']\n            else:\n                ip = self.protocol.transport.get_extra_info('sockname')[0]\n            ip = ip_address(ip)\n            if ip.version == 4:\n                self._ip = ip\n            else:\n                response = urlopen('http://ipv4.icanhazip.com/')\n                ip = response.read().strip().decode()\n                ip = ip_address(ip)\n                self._ip = ip\n        return self._ip",
    "docstring": "return bot's ip as an ``ip_address`` object"
  },
  {
    "code": "def dicomdir_info(dirpath, *args, **kwargs):\n    dr = DicomReader(dirpath=dirpath, *args, **kwargs)\n    info = dr.dicomdirectory.get_stats_of_series_in_dir()\n    return info",
    "docstring": "Get information about series in dir"
  },
  {
    "code": "def checkout(self, *args, **kwargs):\n        self._call_helper(\"Checking out\", self.real.checkout, *args, **kwargs)",
    "docstring": "This function checks out source code."
  },
  {
    "code": "def get_session_key(self, username, password_hash):\n        params = {\"username\": username, \"authToken\": md5(username + password_hash)}\n        request = _Request(self.network, \"auth.getMobileSession\", params)\n        request.sign_it()\n        doc = request.execute()\n        return _extract(doc, \"key\")",
    "docstring": "Retrieve a session key with a username and a md5 hash of the user's\n        password."
  },
  {
    "code": "def set_level(level):\n        Logger.level = level\n        for logger in Logger.loggers.values():\n            logger.setLevel(level)",
    "docstring": "Set level of logging for all loggers.\n\n        Args:\n            level (int): level of logging."
  },
  {
    "code": "def pack_value(self, val):\n        if isinstance(val, bytes):\n            val = list(iterbytes(val))\n        slen = len(val)\n        if self.pad:\n            pad = b'\\0\\0' * (slen % 2)\n        else:\n            pad = b''\n        return struct.pack('>' + 'H' * slen, *val) + pad, slen, None",
    "docstring": "Convert 8-byte string into 16-byte list"
  },
  {
    "code": "def _delete_partition(self, tenant_id, tenant_name):\n        self.dcnm_obj.delete_partition(tenant_name, fw_const.SERV_PART_NAME)",
    "docstring": "Function to delete a service partition."
  },
  {
    "code": "def _token_extensions(self):\n        token_provider = self.config['sasl_oauth_token_provider']\n        if callable(getattr(token_provider, \"extensions\", None)) and len(token_provider.extensions()) > 0:\n            msg = \"\\x01\".join([\"{}={}\".format(k, v) for k, v in token_provider.extensions().items()])\n            return \"\\x01\" + msg\n        else:\n            return \"\"",
    "docstring": "Return a string representation of the OPTIONAL key-value pairs that can be sent with an OAUTHBEARER\n        initial request."
  },
  {
    "code": "def _build_indexes(self):\n        if isinstance(self._data, list):\n            for d in self._data:\n                if not isinstance(d, dict):\n                    err = u'Cannot build index for non Dict type.'\n                    self._tcex.log.error(err)\n                    raise RuntimeError(err)\n                data_obj = DataObj(d)\n                self._master_index.setdefault(id(data_obj), data_obj)\n                for key, value in d.items():\n                    if not isinstance(value, (float, int, str)):\n                        self._tcex.log.debug(u'Can only build index String Types.')\n                        continue\n                    self._indexes.setdefault(key, {}).setdefault(value, []).append(data_obj)\n        else:\n            err = u'Only *List* data type is currently supported'\n            self._tcex.log.error(err)\n            raise RuntimeError(err)",
    "docstring": "Build indexes from data for fast filtering of data.\n\n        Building indexes of data when possible.  This is only supported when dealing with a\n        List of Dictionaries with String values."
  },
  {
    "code": "def show_grid(self, **kwargs):\n        kwargs.setdefault('grid', 'back')\n        kwargs.setdefault('location', 'outer')\n        kwargs.setdefault('ticks', 'both')\n        return self.show_bounds(**kwargs)",
    "docstring": "A wrapped implementation of ``show_bounds`` to change default\n        behaviour to use gridlines and showing the axes labels on the outer\n        edges. This is intended to be silimar to ``matplotlib``'s ``grid``\n        function."
  },
  {
    "code": "def get_model(with_pipeline=False):\n    model = NeuralNetClassifier(MLPClassifier)\n    if with_pipeline:\n        model = Pipeline([\n            ('scale', FeatureUnion([\n                ('minmax', MinMaxScaler()),\n                ('normalize', Normalizer()),\n            ])),\n            ('select', SelectKBest(k=N_FEATURES)),\n            ('net', model),\n        ])\n    return model",
    "docstring": "Get a multi-layer perceptron model.\n\n    Optionally, put it in a pipeline that scales the data."
  },
  {
    "code": "def print(self):\n        print(\n            '{dim}Identifier:{none} {cyan}{identifier}{none}\\n'\n            '{dim}Name:{none} {name}\\n'\n            '{dim}Description:{none}\\n{description}'.format(\n                dim=Style.DIM,\n                cyan=Fore.CYAN,\n                none=Style.RESET_ALL,\n                identifier=self.identifier,\n                name=self.name,\n                description=pretty_description(self.description, indent=2)\n            )\n        )\n        if hasattr(self, 'argument_list') and self.argument_list:\n            print('{dim}Arguments:{none}'.format(\n                dim=Style.DIM, none=Style.RESET_ALL))\n            for argument in self.argument_list:\n                argument.print(indent=2)",
    "docstring": "Print self."
  },
  {
    "code": "def desaturate(self, level):\n    h, s, l = self.__hsl\n    return Color((h, max(s - level, 0), l), 'hsl', self.__a, self.__wref)",
    "docstring": "Create a new instance based on this one but less saturated.\n\n    Parameters:\n      :level:\n        The amount by which the color should be desaturated to produce\n        the new one [0...1].\n\n    Returns:\n      A grapefruit.Color instance.\n\n    >>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25)\n    Color(0.625, 0.5, 0.375, 1.0)\n    >>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25).hsl\n    (30.0, 0.25, 0.5)"
  },
  {
    "code": "def from_json(cls, json_data):\n        data = json.loads(json_data)\n        result = cls(data)\n        if hasattr(result, \"_from_json\"):\n            result._from_json()\n        return result",
    "docstring": "Tries to convert a JSON representation to an object of the same\n        type as self\n\n        A class can provide a _fromJSON implementation in order to do specific\n        type checking or other custom implementation details. This method\n        will throw a ValueError for invalid JSON, a TypeError for\n        improperly constructed, but valid JSON, and any custom errors\n        that can be be propagated from class constructors.\n\n        :param json_data: The JSON string to convert\n        :type json_data: str | unicode\n\n        :raises: TypeError, ValueError, LanguageMapInitError"
  },
  {
    "code": "def _udp_transact(self, payload, handler, *args,\n                      broadcast=False, timeout=TIMEOUT):\n        if self.host in _BUFFER:\n            del _BUFFER[self.host]\n        host = self.host\n        if broadcast:\n            host = '255.255.255.255'\n        retval = None\n        for _ in range(RETRIES):\n            _SOCKET.sendto(bytearray(payload), (host, PORT))\n            start = time.time()\n            while time.time() < start + timeout:\n                data = _BUFFER.get(self.host, None)\n                if data:\n                    retval = handler(data, *args)\n                if retval:\n                    return retval",
    "docstring": "Complete a UDP transaction.\n\n        UDP is stateless and not guaranteed, so we have to\n        take some mitigation steps:\n        - Send payload multiple times.\n        - Wait for awhile to receive response.\n\n        :param payload: Payload to send.\n        :param handler: Response handler.\n        :param args: Arguments to pass to response handler.\n        :param broadcast: Send a broadcast instead.\n        :param timeout: Timeout in seconds."
  },
  {
    "code": "def match_sr(self, svc_ref, cid=None):\n        with self.__lock:\n            our_sr = self.get_reference()\n            if our_sr is None:\n                return False\n            sr_compare = our_sr == svc_ref\n            if cid is None:\n                return sr_compare\n            our_cid = self.get_export_container_id()\n            if our_cid is None:\n                return False\n            return sr_compare and our_cid == cid",
    "docstring": "Checks if this export registration matches the given service reference\n\n        :param svc_ref: A service reference\n        :param cid: A container ID\n        :return: True if the service matches this export registration"
  },
  {
    "code": "def _delete_masked_points(*arrs):\n    if any(hasattr(a, 'mask') for a in arrs):\n        keep = ~functools.reduce(np.logical_or, (np.ma.getmaskarray(a) for a in arrs))\n        return tuple(ma.asarray(a[keep]) for a in arrs)\n    else:\n        return arrs",
    "docstring": "Delete masked points from arrays.\n\n    Takes arrays and removes masked points to help with calculations and plotting.\n\n    Parameters\n    ----------\n    arrs : one or more array-like\n        source arrays\n\n    Returns\n    -------\n    arrs : one or more array-like\n        arrays with masked elements removed"
  },
  {
    "code": "def filter_ignoring_case(self, pattern):\n        return self.filter(re.compile(pattern, re.I))",
    "docstring": "Like ``filter`` but case-insensitive.\n\n        Expects a regular expression string without the surrounding ``/``\n        characters.\n\n            >>> see().filter('^my', ignore_case=True)\n                MyClass()"
  },
  {
    "code": "def update(name, maximum_version=None, required_version=None):\n    flags = [('Name', name)]\n    if maximum_version is not None:\n        flags.append(('MaximumVersion', maximum_version))\n    if required_version is not None:\n        flags.append(('RequiredVersion', required_version))\n    params = ''\n    for flag, value in flags:\n        params += '-{0} {1} '.format(flag, value)\n    cmd = 'Update-Module {0} -Force'.format(params)\n    _pshell(cmd)\n    return name in list_modules()",
    "docstring": "Update a PowerShell module to a specific version, or the newest\n\n    :param name: Name of a Powershell module\n    :type  name: ``str``\n\n    :param maximum_version: The maximum version to install, e.g. 1.23.2\n    :type  maximum_version: ``str``\n\n    :param required_version: Install a specific version\n    :type  required_version: ``str``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'win01' psget.update PowerPlan"
  },
  {
    "code": "def add_to_obj(obj, dictionary, objs=None, exceptions=None, verbose=0):\n    if exceptions is None:\n        exceptions = []\n    for item in dictionary:\n        if item in exceptions:\n            continue\n        if dictionary[item] is not None:\n            if verbose:\n                print(\"process: \", item, dictionary[item])\n            key, value = get_key_value(dictionary[item], objs, key=item)\n            if verbose:\n                print(\"assign: \", key, value)\n            try:\n                setattr(obj, key, value)\n            except AttributeError:\n                raise AttributeError(\"Can't set {0}={1} on object: {2}\".format(key, value, obj))",
    "docstring": "Cycles through a dictionary and adds the key-value pairs to an object.\n\n    :param obj:\n    :param dictionary:\n    :param exceptions:\n    :param verbose:\n    :return:"
  },
  {
    "code": "def imagetransformerpp_base_14l_8h_big_uncond_dr03_dan_p():\n  hparams = imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_l()\n  hparams.num_decoder_layers = 14\n  hparams.batch_size = 8\n  hparams.layer_prepostprocess_dropout = 0.2\n  return hparams",
    "docstring": "Gets to 2.92 in just under 4 days on 8 p100s."
  },
  {
    "code": "def make_field(self, **kwargs):\n        kwargs['required'] = False\n        kwargs['allow_null'] = True\n        return self.field_class(**kwargs)",
    "docstring": "create serializer field"
  },
  {
    "code": "def version():\n    cmd = 'lvm version'\n    out = __salt__['cmd.run'](cmd).splitlines()\n    ret = out[0].split(': ')\n    return ret[1].strip()",
    "docstring": "Return LVM version from lvm version\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' lvm.version"
  },
  {
    "code": "def get_formatted_string(self, input_string):\n        if isinstance(input_string, str):\n            try:\n                return self.get_processed_string(input_string)\n            except KeyNotInContextError as err:\n                raise KeyNotInContextError(\n                    f'Unable to format \\'{input_string}\\' because {err}'\n                ) from err\n        elif isinstance(input_string, SpecialTagDirective):\n            return input_string.get_value(self)\n        else:\n            raise TypeError(f\"can only format on strings. {input_string} is a \"\n                            f\"{type(input_string)} instead.\")",
    "docstring": "Return formatted value for input_string.\n\n        get_formatted gets a context[key] value.\n        get_formatted_string is for any arbitrary string that is not in the\n        context.\n\n        Only valid if input_string is a type string.\n        Return a string interpolated from the context dictionary.\n\n        If input_string='Piping {key1} the {key2} wild'\n        And context={'key1': 'down', 'key2': 'valleys', 'key3': 'value3'}\n\n        Then this will return string: \"Piping down the valleys wild\"\n\n        Args:\n            input_string: string to parse for substitutions.\n\n        Returns:\n            Formatted string.\n\n        Raises:\n            KeyNotInContextError: context[key] has {somekey} where somekey does\n                                  not exist in context dictionary.\n            TypeError: Attempt operation on a non-string type."
  },
  {
    "code": "def setupTable_vmtx(self):\n        if \"vmtx\" not in self.tables:\n            return\n        self.otf[\"vmtx\"] = vmtx = newTable(\"vmtx\")\n        vmtx.metrics = {}\n        for glyphName, glyph in self.allGlyphs.items():\n            height = otRound(glyph.height)\n            if height < 0:\n                raise ValueError(\n                    \"The height should not be negative: '%s'\" % (glyphName))\n            verticalOrigin = _getVerticalOrigin(self.otf, glyph)\n            bounds = self.glyphBoundingBoxes[glyphName]\n            top = bounds.yMax if bounds else 0\n            vmtx[glyphName] = (height, verticalOrigin - top)",
    "docstring": "Make the vmtx table.\n\n        **This should not be called externally.** Subclasses\n        may override or supplement this method to handle the\n        table creation in a different way if desired."
  },
  {
    "code": "def get_message(self):\n        result = ''\n        if self._data_struct is not None:\n            result = self._data_struct[KEY_MESSAGE]\n        return result",
    "docstring": "Return the message embedded in the JSON error response body,\n        or an empty string if the JSON couldn't be parsed."
  },
  {
    "code": "def list(self):\n        databases = []\n        for dbname in os.listdir(self.path):\n            databases.append(dbname)\n        return list(reversed(sorted(databases)))",
    "docstring": "List all the databases on the given path.\n\n        :return:"
  },
  {
    "code": "def WriteFromFD(self, src_fd, arcname=None, compress_type=None, st=None):\n    yield self.WriteFileHeader(\n        arcname=arcname, compress_type=compress_type, st=st)\n    while 1:\n      buf = src_fd.read(1024 * 1024)\n      if not buf:\n        break\n      yield self.WriteFileChunk(buf)\n    yield self.WriteFileFooter()",
    "docstring": "Write a zip member from a file like object.\n\n    Args:\n      src_fd: A file like object, must support seek(), tell(), read().\n      arcname: The name in the archive this should take.\n      compress_type: Compression type (zipfile.ZIP_DEFLATED, or ZIP_STORED)\n      st: An optional stat object to be used for setting headers.\n\n    Raises:\n      ArchiveAlreadyClosedError: If the zip if already closed.\n\n    Yields:\n      Chunks of binary data."
  },
  {
    "code": "def get_allowed_methods(self, callback):\n        if hasattr(callback, 'actions'):\n            return [method.upper() for method in callback.actions.keys() if method != 'head']\n        return [\n            method for method in\n            callback.cls().allowed_methods if method not in ('OPTIONS', 'HEAD')\n        ]",
    "docstring": "Return a list of the valid HTTP methods for this endpoint."
  },
  {
    "code": "def pub(self, topic, message):\n        return self.send(' '.join((constants.PUB, topic)), message)",
    "docstring": "Publish to a topic"
  },
  {
    "code": "def times(x, y):\n    def decorator(fn):\n        def wrapped(*args, **kwargs):\n            n = random.randint(x, y)\n            for z in range(1, n):\n                fn(*args, **kwargs)\n        return wrapped\n    return decorator",
    "docstring": "Do something a random amount of times\n    between x & y"
  },
  {
    "code": "def recursive_apply(inval, func):\n    if isinstance(inval, dict):\n        return {k: recursive_apply(v, func) for k, v in inval.items()}\n    elif isinstance(inval, list):\n        return [recursive_apply(v, func) for v in inval]\n    else:\n        return func(inval)",
    "docstring": "Recursively apply a function to all levels of nested iterables\n\n    :param inval: the object to run the function on\n    :param func: the function that will be run on the inval"
  },
  {
    "code": "def get_account(self, account, use_sis_id=False, **kwargs):\n        if use_sis_id:\n            account_id = account\n            uri_str = 'accounts/sis_account_id:{}'\n        else:\n            account_id = obj_or_id(account, \"account\", (Account,))\n            uri_str = 'accounts/{}'\n        response = self.__requester.request(\n            'GET',\n            uri_str.format(account_id),\n            _kwargs=combine_kwargs(**kwargs)\n        )\n        return Account(self.__requester, response.json())",
    "docstring": "Retrieve information on an individual account.\n\n        :calls: `GET /api/v1/accounts/:id \\\n        <https://canvas.instructure.com/doc/api/accounts.html#method.accounts.show>`_\n\n        :param account: The object or ID of the account to retrieve.\n        :type account: int, str or :class:`canvasapi.account.Account`\n        :param use_sis_id: Whether or not account_id is an sis ID.\n            Defaults to `False`.\n        :type use_sis_id: bool\n\n        :rtype: :class:`canvasapi.account.Account`"
  },
  {
    "code": "def validate(self):\n        validate_url = \"https://api.pushover.net/1/users/validate.json\"\n        payload = {\n            'token': self.api_token,\n            'user': self.user,\n        }\n        return requests.post(validate_url, data=payload)",
    "docstring": "Validate the user and token, returns the Requests response."
  },
  {
    "code": "async def close(self, code: int = 1000, reason: str = \"\") -> None:\n        try:\n            await asyncio.wait_for(\n                self.write_close_frame(serialize_close(code, reason)),\n                self.close_timeout,\n                loop=self.loop,\n            )\n        except asyncio.TimeoutError:\n            self.fail_connection()\n        try:\n            await asyncio.wait_for(\n                self.transfer_data_task, self.close_timeout, loop=self.loop\n            )\n        except (asyncio.TimeoutError, asyncio.CancelledError):\n            pass\n        await asyncio.shield(self.close_connection_task)",
    "docstring": "This coroutine performs the closing handshake.\n\n        It waits for the other end to complete the handshake and for the TCP\n        connection to terminate. As a consequence, there's no need to await\n        :meth:`wait_closed`; :meth:`close` already does it.\n\n        :meth:`close` is idempotent: it doesn't do anything once the\n        connection is closed.\n\n        It's safe to wrap this coroutine in :func:`~asyncio.create_task` since\n        errors during connection termination aren't particularly useful.\n\n        ``code`` must be an :class:`int` and ``reason`` a :class:`str`."
  },
  {
    "code": "def lrange(self, name, start, stop):\n        with self.pipe as pipe:\n            f = Future()\n            res = pipe.lrange(self.redis_key(name), start, stop)\n            def cb():\n                f.set([self.valueparse.decode(v) for v in res.result])\n            pipe.on_execute(cb)\n            return f",
    "docstring": "Returns a range of items.\n\n        :param name: str     the name of the redis key\n        :param start: integer representing the start index of the range\n        :param stop: integer representing the size of the list.\n        :return: Future()"
  },
  {
    "code": "def labels(data, label_column, color=None, font_name=FONT_NAME, \n           font_size=14, anchor_x='left', anchor_y='top'):\n    from geoplotlib.layers import LabelsLayer\n    _global_config.layers.append(LabelsLayer(data, label_column, color, font_name, \n           font_size, anchor_x, anchor_y))",
    "docstring": "Draw a text label for each sample\n\n    :param data: data access object\n    :param label_column: column in the data access object where the labels text is stored\n    :param color: color\n    :param font_name: font name\n    :param font_size: font size\n    :param anchor_x: anchor x\n    :param anchor_y: anchor y"
  },
  {
    "code": "def _start_primary(self):\n        self.em.start()\n        self.em.set_secondary_state(_STATE_RUNNING)\n        self._set_shared_instances()",
    "docstring": "Start as the primary"
  },
  {
    "code": "def populate_items(self, request):\n        self._items = self.get_items(request)\n        return self.items",
    "docstring": "populate and returns filtered items"
  },
  {
    "code": "def parent_tags(self):\n        tags = set()\n        for addr in self._addresses:\n            if addr.attr == 'text':\n                tags.add(addr.element.tag)\n            tags.update(el.tag for el in addr.element.iterancestors())\n        tags.discard(HTMLFragment._root_tag)\n        return frozenset(tags)",
    "docstring": "Provides tags of all parent HTML elements."
  },
  {
    "code": "def prepare(self, data):\n        result = {}\n        if not self.fields:\n            return data\n        for fieldname, lookup in self.fields.items():\n            if isinstance(lookup, SubPreparer):\n                result[fieldname] = lookup.prepare(data)\n            else:\n                result[fieldname] = self.lookup_data(lookup, data)\n        return result",
    "docstring": "Handles transforming the provided data into the fielded data that should\n        be exposed to the end user.\n\n        Uses the ``lookup_data`` method to traverse dotted paths.\n\n        Returns a dictionary of data as the response."
  },
  {
    "code": "def _spacingx(node, max_dims, xoffset, xspace):\n    x_spacing = _n_terminations(node) * xspace\n    if x_spacing > max_dims[0]:\n        max_dims[0] = x_spacing\n    return xoffset - x_spacing / 2.",
    "docstring": "Determine the spacing of the current node depending on the number\n       of the leaves of the tree"
  },
  {
    "code": "def get_networks_by_name(self, name: str) -> List[Network]:\n        return self.session.query(Network).filter(Network.name.like(name)).all()",
    "docstring": "Get all networks with the given name. Useful for getting all versions of a given network."
  },
  {
    "code": "def plot_vyx(self, colorbar=True, cb_orientation='vertical',\n                 cb_label=None, ax=None, show=True, fname=None, **kwargs):\n        if cb_label is None:\n            cb_label = self._vyx_label\n        if ax is None:\n            fig, axes = self.vyx.plot(colorbar=colorbar,\n                                      cb_orientation=cb_orientation,\n                                      cb_label=cb_label, show=False, **kwargs)\n            if show:\n                fig.show()\n            if fname is not None:\n                fig.savefig(fname)\n            return fig, axes\n        else:\n            self.vyx.plot(colorbar=colorbar, cb_orientation=cb_orientation,\n                          cb_label=cb_label, ax=ax, **kwargs)",
    "docstring": "Plot the Vyx component of the tensor.\n\n        Usage\n        -----\n        x.plot_vyx([tick_interval, xlabel, ylabel, ax, colorbar,\n                    cb_orientation, cb_label, show, fname])\n\n        Parameters\n        ----------\n        tick_interval : list or tuple, optional, default = [30, 30]\n            Intervals to use when plotting the x and y ticks. If set to None,\n            ticks will not be plotted.\n        xlabel : str, optional, default = 'longitude'\n            Label for the longitude axis.\n        ylabel : str, optional, default = 'latitude'\n            Label for the latitude axis.\n        ax : matplotlib axes object, optional, default = None\n            A single matplotlib axes object where the plot will appear.\n        colorbar : bool, optional, default = True\n            If True, plot a colorbar.\n        cb_orientation : str, optional, default = 'vertical'\n            Orientation of the colorbar: either 'vertical' or 'horizontal'.\n        cb_label : str, optional, default = '$V_{yx}$'\n            Text label for the colorbar.\n        show : bool, optional, default = True\n            If True, plot the image to the screen.\n        fname : str, optional, default = None\n            If present, and if axes is not specified, save the image to the\n            specified file.\n        kwargs : optional\n            Keyword arguements that will be sent to the SHGrid.plot()\n            and plt.imshow() methods."
  },
  {
    "code": "def _get_variable(vid, variables):\n    if isinstance(vid, six.string_types):\n        vid = get_base_id(vid)\n    else:\n        vid = _get_string_vid(vid)\n    for v in variables:\n        if vid == get_base_id(v[\"id\"]):\n            return copy.deepcopy(v)\n    raise ValueError(\"Did not find variable %s in \\n%s\" % (vid, pprint.pformat(variables)))",
    "docstring": "Retrieve an input variable from our existing pool of options."
  },
  {
    "code": "def can_handle(self, text: str) -> bool:\n        try:\n            changelogs = self.split_changelogs(text)\n            if not changelogs:\n                return False\n            for changelog in changelogs:\n                _header, _changes = self.split_changelog(changelog)\n                if not any((_header, _changes)):\n                    return False\n                header = self.parse_header(_header)\n                changes = self.parse_changes(_changes)\n                if not any((header, changes)):\n                    return False\n        except Exception:\n            return False\n        else:\n            return True",
    "docstring": "Check whether this parser can parse the text"
  },
  {
    "code": "def parse(self, s):\n        return datetime.datetime.strptime(s, self.date_format).date()",
    "docstring": "Parses a date string formatted like ``YYYY-MM-DD``."
  },
  {
    "code": "def configure_for_kerberos(self, datanode_transceiver_port=None,\n    datanode_web_port=None):\n    args = dict()\n    if datanode_transceiver_port:\n        args['datanodeTransceiverPort'] = datanode_transceiver_port\n    if datanode_web_port:\n        args['datanodeWebPort'] = datanode_web_port\n    return self._cmd('configureForKerberos', data=args, api_version=11)",
    "docstring": "Command to configure the cluster to use Kerberos for authentication.\n\n    This command will configure all relevant services on a cluster for\n    Kerberos usage.  This command will trigger a GenerateCredentials command\n    to create Kerberos keytabs for all roles in the cluster.\n\n    @param datanode_transceiver_port: The HDFS DataNode transceiver port to use.\n           This will be applied to all DataNode role configuration groups. If\n           not specified, this will default to 1004.\n    @param datanode_web_port: The HDFS DataNode web port to use.  This will be\n           applied to all DataNode role configuration groups. If not specified,\n           this will default to 1006.\n    @return: Reference to the submitted command.\n    @since: API v11"
  },
  {
    "code": "def _update_entry(entry, status, directives):\n    for directive, state in six.iteritems(directives):\n        if directive == 'delete_others':\n            status['delete_others'] = state\n            continue\n        for attr, vals in six.iteritems(state):\n            status['mentioned_attributes'].add(attr)\n            vals = _toset(vals)\n            if directive == 'default':\n                if vals and (attr not in entry or not entry[attr]):\n                    entry[attr] = vals\n            elif directive == 'add':\n                vals.update(entry.get(attr, ()))\n                if vals:\n                    entry[attr] = vals\n            elif directive == 'delete':\n                existing_vals = entry.pop(attr, OrderedSet())\n                if vals:\n                    existing_vals -= vals\n                    if existing_vals:\n                        entry[attr] = existing_vals\n            elif directive == 'replace':\n                entry.pop(attr, None)\n                if vals:\n                    entry[attr] = vals\n            else:\n                raise ValueError('unknown directive: ' + directive)",
    "docstring": "Update an entry's attributes using the provided directives\n\n    :param entry:\n        A dict mapping each attribute name to a set of its values\n    :param status:\n        A dict holding cross-invocation status (whether delete_others\n        is True or not, and the set of mentioned attributes)\n    :param directives:\n        A dict mapping directive types to directive-specific state"
  },
  {
    "code": "def _get_value(self):\n        x, y = self._point.x, self._point.y\n        self._px, self._py = self._item_point.canvas.get_matrix_i2i(self._item_point,\n                                                                    self._item_target).transform_point(x, y)\n        return self._px, self._py",
    "docstring": "Return two delegating variables. Each variable should contain\n        a value attribute with the real value."
  },
  {
    "code": "def configure_arrays(self):\n        self.science = self.hdulist['sci', 1].data\n        self.err = self.hdulist['err', 1].data\n        self.dq = self.hdulist['dq', 1].data\n        if (self.ampstring == 'ABCD'):\n            self.science = np.concatenate(\n                (self.science, self.hdulist['sci', 2].data[::-1, :]), axis=1)\n            self.err = np.concatenate(\n                (self.err, self.hdulist['err', 2].data[::-1, :]), axis=1)\n            self.dq = np.concatenate(\n                (self.dq, self.hdulist['dq', 2].data[::-1, :]), axis=1)\n        self.ingest_dark()\n        self.ingest_flash()\n        self.ingest_flatfield()",
    "docstring": "Get the SCI and ERR data."
  },
  {
    "code": "def cache_key(*args, **kwargs):\n    key = \"\"\n    for arg in args:\n        if callable(arg):\n            key += \":%s\" % repr(arg)\n        else:\n            key += \":%s\" % str(arg)\n    return key",
    "docstring": "Base method for computing the cache key with respect to the given\n    arguments."
  },
  {
    "code": "def badge(pipeline_id):\n    if not pipeline_id.startswith('./'):\n        pipeline_id = './' + pipeline_id\n    pipeline_status = status.get(pipeline_id)\n    status_color = 'lightgray'\n    if pipeline_status.pipeline_details:\n        status_text = pipeline_status.state().lower()\n        last_execution = pipeline_status.get_last_execution()\n        success = last_execution.success if last_execution else None\n        if success is True:\n            stats = last_execution.stats if last_execution else None\n            record_count = stats.get('count_of_rows')\n            if record_count is not None:\n                status_text += ' (%d records)' % record_count\n            status_color = 'brightgreen'\n        elif success is False:\n            status_color = 'red'\n    else:\n        status_text = \"not found\"\n    return _make_badge_response('pipeline', status_text, status_color)",
    "docstring": "An individual pipeline status"
  },
  {
    "code": "async def sendto(self, data, component):\n        active_pair = self._nominated.get(component)\n        if active_pair:\n            await active_pair.protocol.send_data(data, active_pair.remote_addr)\n        else:\n            raise ConnectionError('Cannot send data, not connected')",
    "docstring": "Send a datagram on the specified component.\n\n        If the connection is not established, a `ConnectionError` is raised."
  },
  {
    "code": "def _registerNode(self, nodeAddress, agentId, nodePort=5051):\n        executor = self.executors.get(nodeAddress)\n        if executor is None or executor.agentId != agentId:\n            executor = self.ExecutorInfo(nodeAddress=nodeAddress,\n                                         agentId=agentId,\n                                         nodeInfo=None,\n                                         lastSeen=time.time())\n            self.executors[nodeAddress] = executor\n        else:\n            executor.lastSeen = time.time()\n        self.agentsByID[agentId] = nodeAddress\n        return executor",
    "docstring": "Called when we get communication from an agent. Remembers the\n        information about the agent by address, and the agent address by agent\n        ID."
  },
  {
    "code": "def pair_hmm_align_unaligned_seqs(seqs, moltype=DNA_cogent, params={}):\n    seqs = LoadSeqs(data=seqs, moltype=moltype, aligned=False)\n    try:\n        s1, s2 = seqs.values()\n    except ValueError:\n        raise ValueError(\n            \"Pairwise aligning of seqs requires exactly two seqs.\")\n    try:\n        gap_open = params['gap_open']\n    except KeyError:\n        gap_open = 5\n    try:\n        gap_extend = params['gap_extend']\n    except KeyError:\n        gap_extend = 2\n    try:\n        score_matrix = params['score_matrix']\n    except KeyError:\n        score_matrix = make_dna_scoring_dict(\n            match=1, transition=-1, transversion=-1)\n    return local_pairwise(s1, s2, score_matrix, gap_open, gap_extend)",
    "docstring": "Checks parameters for pairwise alignment, returns alignment.\n\n        Code from Greg Caporaso."
  },
  {
    "code": "async def create(gc: GroupControl, name, slaves):\n    click.echo(\"Creating group %s with slaves: %s\" % (name, slaves))\n    click.echo(await gc.create(name, slaves))",
    "docstring": "Create new group"
  },
  {
    "code": "def _build_toc_node(docname, anchor=\"anchor\", text=\"test text\", bullet=False):\n    reference = nodes.reference(\n        \"\",\n        \"\",\n        internal=True,\n        refuri=docname,\n        anchorname=\"\n        *[nodes.Text(text, text)]\n    )\n    para = addnodes.compact_paragraph(\"\", \"\", reference)\n    ret_list = nodes.list_item(\"\", para)\n    return nodes.bullet_list(\"\", ret_list) if bullet else ret_list",
    "docstring": "Create the node structure that Sphinx expects for TOC Tree entries.\n\n    The ``bullet`` argument wraps it in a ``nodes.bullet_list``,\n    which is how you nest TOC Tree entries."
  },
  {
    "code": "def _hdparm(args, failhard=True):\n    cmd = 'hdparm {0}'.format(args)\n    result = __salt__['cmd.run_all'](cmd)\n    if result['retcode'] != 0:\n        msg = '{0}: {1}'.format(cmd, result['stderr'])\n        if failhard:\n            raise CommandExecutionError(msg)\n        else:\n            log.warning(msg)\n    return result['stdout']",
    "docstring": "Execute hdparm\n    Fail hard when required\n    return output when possible"
  },
  {
    "code": "def _start_loop(self):\n        loop = GObject.MainLoop()\n        bus = SystemBus()\n        manager = bus.get(\".NetworkManager\")\n        manager.onPropertiesChanged = self._vpn_signal_handler\n        loop.run()",
    "docstring": "Starts main event handler loop, run in handler thread t."
  },
  {
    "code": "def _upload_simple(self, upload_info, _=None):\n        upload_result = self._api.upload_simple(\n            upload_info.fd,\n            upload_info.name,\n            folder_key=upload_info.folder_key,\n            filedrop_key=upload_info.filedrop_key,\n            path=upload_info.path,\n            file_size=upload_info.size,\n            file_hash=upload_info.hash_info.file,\n            action_on_duplicate=upload_info.action_on_duplicate)\n        logger.debug(\"upload_result: %s\", upload_result)\n        upload_key = upload_result['doupload']['key']\n        return self._poll_upload(upload_key, 'upload/simple')",
    "docstring": "Simple upload and return quickkey\n\n        Can be used for small files smaller than UPLOAD_SIMPLE_LIMIT_BYTES\n\n        upload_info -- UploadInfo object\n        check_result -- ignored"
  },
  {
    "code": "def batch_get_assets_history(\n        self,\n        parent,\n        content_type,\n        read_time_window,\n        asset_names=None,\n        retry=google.api_core.gapic_v1.method.DEFAULT,\n        timeout=google.api_core.gapic_v1.method.DEFAULT,\n        metadata=None,\n    ):\n        if \"batch_get_assets_history\" not in self._inner_api_calls:\n            self._inner_api_calls[\n                \"batch_get_assets_history\"\n            ] = google.api_core.gapic_v1.method.wrap_method(\n                self.transport.batch_get_assets_history,\n                default_retry=self._method_configs[\"BatchGetAssetsHistory\"].retry,\n                default_timeout=self._method_configs[\"BatchGetAssetsHistory\"].timeout,\n                client_info=self._client_info,\n            )\n        request = asset_service_pb2.BatchGetAssetsHistoryRequest(\n            parent=parent,\n            content_type=content_type,\n            read_time_window=read_time_window,\n            asset_names=asset_names,\n        )\n        return self._inner_api_calls[\"batch_get_assets_history\"](\n            request, retry=retry, timeout=timeout, metadata=metadata\n        )",
    "docstring": "Batch gets the update history of assets that overlap a time window. For\n        RESOURCE content, this API outputs history with asset in both non-delete\n        or deleted status. For IAM\\_POLICY content, this API outputs history\n        when the asset and its attached IAM POLICY both exist. This can create\n        gaps in the output history. If a specified asset does not exist, this\n        API returns an INVALID\\_ARGUMENT error.\n\n        Example:\n            >>> from google.cloud import asset_v1\n            >>> from google.cloud.asset_v1 import enums\n            >>>\n            >>> client = asset_v1.AssetServiceClient()\n            >>>\n            >>> # TODO: Initialize `parent`:\n            >>> parent = ''\n            >>>\n            >>> # TODO: Initialize `content_type`:\n            >>> content_type = enums.ContentType.CONTENT_TYPE_UNSPECIFIED\n            >>>\n            >>> # TODO: Initialize `read_time_window`:\n            >>> read_time_window = {}\n            >>>\n            >>> response = client.batch_get_assets_history(parent, content_type, read_time_window)\n\n        Args:\n            parent (str): Required. The relative name of the root asset. It can only be an\n                organization number (such as \"organizations/123\"), a project ID (such as\n                \"projects/my-project-id\")\", or a project number (such as \"projects/12345\").\n            content_type (~google.cloud.asset_v1.types.ContentType): Required. The content type.\n            read_time_window (Union[dict, ~google.cloud.asset_v1.types.TimeWindow]): Optional. The time window for the asset history. Both start\\_time and\n                end\\_time are optional and if set, it must be after 2018-10-02 UTC. If\n                end\\_time is not set, it is default to current timestamp. If start\\_time\n                is not set, the snapshot of the assets at end\\_time will be returned.\n                The returned results contain all temporal assets whose time window\n                overlap with read\\_time\\_window.\n\n                If a dict is provided, it must be of the same form as the protobuf\n                message :class:`~google.cloud.asset_v1.types.TimeWindow`\n            asset_names (list[str]): A list of the full names of the assets. For example:\n                ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``.\n                See `Resource\n                Names <https://cloud.google.com/apis/design/resource_names#full_resource_name>`__\n                and `Resource Name\n                Format <https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/resource-name-format>`__\n                for more info.\n\n                The request becomes a no-op if the asset name list is empty, and the max\n                size of the asset name list is 100 in one request.\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.asset_v1.types.BatchGetAssetsHistoryResponse` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def _convert_template_option(template):\n    option = {}\n    extraction_method = template.get('extraction_method')\n    if extraction_method == 'guess':\n        option['guess'] = True\n    elif extraction_method == 'lattice':\n        option['lattice'] = True\n    elif extraction_method == 'stream':\n        option['stream'] = True\n    option['pages'] = template.get('page')\n    option['area'] = [round(template['y1'], 3), round(template['x1'], 3), round(template['y2'], 3), round(template['x2'], 3)]\n    return option",
    "docstring": "Convert Tabula app template to tabula-py option\n\n    Args:\n        template (dict): Tabula app template\n\n    Returns:\n        `obj`:dict: tabula-py option"
  },
  {
    "code": "def autobuild_onlycopy():\n    try:\n        family = utilities.get_family('module_settings.json')\n        autobuild_release(family)\n        Alias('release', os.path.join('build', 'output'))\n        Default(['release'])\n    except unit_test.IOTileException as e:\n        print(e.format())\n        Exit(1)",
    "docstring": "Autobuild a project that does not require building firmware, pcb or documentation"
  },
  {
    "code": "def get_staff(self, gradebook_id, simple=False):\n        staff_data = self.get(\n            'staff/{gradebookId}'.format(\n                gradebookId=gradebook_id or self.gradebook_id\n            ),\n            params=None,\n        )\n        if simple:\n            simple_list = []\n            unraveled_list = self.unravel_staff(staff_data)\n            for member in unraveled_list.__iter__():\n                simple_list.append({\n                    'accountEmail': member['accountEmail'],\n                    'displayName': member['displayName'],\n                    'role': member['role'],\n                })\n            return simple_list\n        return staff_data['data']",
    "docstring": "Get staff list for gradebook.\n\n        Get staff list for the gradebook specified. Optionally, return\n        a less detailed list by specifying ``simple = True``.\n\n        If simple=True, return a list of dictionaries, one dictionary\n        for each member. The dictionary contains a member's ``email``,\n        ``displayName``, and ``role``. Members with multiple roles will\n        appear in the list once for each role.\n\n        Args:\n            gradebook_id (str): unique identifier for gradebook, i.e. ``2314``\n            simple (bool): Return a staff list with less detail. Default\n                is ``False``.\n\n        Returns:\n\n            An example return value is:\n\n            .. code-block:: python\n\n                {\n                    u'data': {\n                        u'COURSE_ADMIN': [\n                            {\n                                u'accountEmail': u'benfranklin@mit.edu',\n                                u'displayName': u'Benjamin Franklin',\n                                u'editable': False,\n                                u'email': u'benfranklin@mit.edu',\n                                u'givenName': u'Benjamin',\n                                u'middleName': None,\n                                u'mitId': u'921344431',\n                                u'nickName': u'Benjamin',\n                                u'personId': 10710616,\n                                u'sortableName': u'Franklin, Benjamin',\n                                u'surname': u'Franklin',\n                                u'year': None\n                            },\n                        ],\n                        u'COURSE_PROF': [\n                            {\n                                u'accountEmail': u'dduck@mit.edu',\n                                u'displayName': u'Donald Duck',\n                                u'editable': False,\n                                u'email': u'dduck@mit.edu',\n                                u'givenName': u'Donald',\n                                u'middleName': None,\n                                u'mitId': u'916144889',\n                                u'nickName': u'Donald',\n                                u'personId': 8117160,\n                                u'sortableName': u'Duck, Donald',\n                                u'surname': u'Duck',\n                                u'year': None\n                            },\n                        ],\n                        u'COURSE_TA': [\n                            {\n                                u'accountEmail': u'hduck@mit.edu',\n                                u'displayName': u'Huey Duck',\n                                u'editable': False,\n                                u'email': u'hduck@mit.edu',\n                                u'givenName': u'Huey',\n                                u'middleName': None,\n                                u'mitId': u'920445024',\n                                u'nickName': u'Huey',\n                                u'personId': 1299059,\n                                u'sortableName': u'Duck, Huey',\n                                u'surname': u'Duck',\n                                u'year': None\n                            },\n                        ]\n                    },\n                }"
  },
  {
    "code": "def get_authors(self, entry):\n        try:\n            return format_html_join(\n                ', ', '<a href=\"{}\" target=\"blank\">{}</a>',\n                [(author.get_absolute_url(),\n                  getattr(author, author.USERNAME_FIELD))\n                 for author in entry.authors.all()])\n        except NoReverseMatch:\n            return ', '.join(\n                [conditional_escape(getattr(author, author.USERNAME_FIELD))\n                 for author in entry.authors.all()])",
    "docstring": "Return the authors in HTML."
  },
  {
    "code": "def as_text(self, max_rows=0, sep=\" | \"):\n        if not max_rows or max_rows > self.num_rows:\n            max_rows = self.num_rows\n        omitted = max(0, self.num_rows - max_rows)\n        labels = self._columns.keys()\n        fmts = self._get_column_formatters(max_rows, False)\n        rows = [[fmt(label, label=True) for fmt, label in zip(fmts, labels)]]\n        for row in itertools.islice(self.rows, max_rows):\n            rows.append([f(v, label=False) for v, f in zip(row, fmts)])\n        lines = [sep.join(row) for row in rows]\n        if omitted:\n            lines.append('... ({} rows omitted)'.format(omitted))\n        return '\\n'.join([line.rstrip() for line in lines])",
    "docstring": "Format table as text."
  },
  {
    "code": "def _estimate_centers_widths(\n            self,\n            unique_R,\n            inds,\n            X,\n            W,\n            init_centers,\n            init_widths,\n            template_centers,\n            template_widths,\n            template_centers_mean_cov,\n            template_widths_mean_var_reci):\n        init_estimate = np.hstack(\n            (init_centers.ravel(), init_widths.ravel()))\n        data_sigma = 1.0 / math.sqrt(2.0) * np.std(X)\n        final_estimate = least_squares(\n            self._residual_multivariate,\n            init_estimate,\n            args=(\n                unique_R,\n                inds,\n                X,\n                W,\n                template_centers,\n                template_widths,\n                template_centers_mean_cov,\n                template_widths_mean_var_reci,\n                data_sigma),\n            method=self.nlss_method,\n            loss=self.nlss_loss,\n            bounds=self.bounds,\n            verbose=0,\n            x_scale=self.x_scale,\n            tr_solver=self.tr_solver)\n        return final_estimate.x, final_estimate.cost",
    "docstring": "Estimate centers and widths\n\n        Parameters\n        ----------\n\n        unique_R : a list of array,\n            Each element contains unique value in one dimension of\n            coordinate matrix R.\n\n        inds : a list of array,\n            Each element contains the indices to reconstruct one\n            dimension of original cooridnate matrix from the unique\n            array.\n\n        X : 2D array, with shape [n_voxel, n_tr]\n            fMRI data from one subject.\n\n        W : 2D array, with shape [K, n_tr]\n            The weight matrix.\n\n        init_centers : 2D array, with shape [K, n_dim]\n            The initial values of centers.\n\n        init_widths : 1D array\n            The initial values of widths.\n\n        template_centers: 1D array\n            The template prior on centers\n\n        template_widths: 1D array\n            The template prior on widths\n\n        template_centers_mean_cov: 2D array, with shape [K, cov_size]\n            The template prior on centers' mean\n\n        template_widths_mean_var_reci: 1D array\n            The reciprocal of template prior on variance of widths' mean\n\n\n        Returns\n        -------\n\n        final_estimate.x: 1D array\n            The newly estimated centers and widths.\n\n        final_estimate.cost: float\n            The cost value."
  },
  {
    "code": "def _GetCachedEntryDataTypeMap(\n      self, format_type, value_data, cached_entry_offset):\n    if format_type not in self._SUPPORTED_FORMAT_TYPES:\n      raise errors.ParseError('Unsupported format type: {0:d}'.format(\n          format_type))\n    data_type_map_name = ''\n    if format_type == self._FORMAT_TYPE_XP:\n      data_type_map_name = 'appcompatcache_cached_entry_xp_32bit'\n    elif format_type in (self._FORMAT_TYPE_8, self._FORMAT_TYPE_10):\n      data_type_map_name = 'appcompatcache_cached_entry_header_8'\n    else:\n      cached_entry = self._ParseCommon2003CachedEntry(\n          value_data, cached_entry_offset)\n      if (cached_entry.path_offset_32bit == 0 and\n          cached_entry.path_offset_64bit != 0):\n        number_of_bits = '64'\n      else:\n        number_of_bits = '32'\n      if format_type == self._FORMAT_TYPE_2003:\n        data_type_map_name = (\n            'appcompatcache_cached_entry_2003_{0:s}bit'.format(number_of_bits))\n      elif format_type == self._FORMAT_TYPE_VISTA:\n        data_type_map_name = (\n            'appcompatcache_cached_entry_vista_{0:s}bit'.format(number_of_bits))\n      elif format_type == self._FORMAT_TYPE_7:\n        data_type_map_name = (\n            'appcompatcache_cached_entry_7_{0:s}bit'.format(number_of_bits))\n    return self._GetDataTypeMap(data_type_map_name)",
    "docstring": "Determines the cached entry data type map.\n\n    Args:\n      format_type (int): format type.\n      value_data (bytes): value data.\n      cached_entry_offset (int): offset of the first cached entry data\n          relative to the start of the value data.\n\n    Returns:\n      dtfabric.DataTypeMap: data type map which contains a data type definition,\n          such as a structure, that can be mapped onto binary data or None\n          if the data type map is not defined.\n\n    Raises:\n      ParseError: if the cached entry data type map cannot be determined."
  },
  {
    "code": "def _unhandled_event_default(event):\n        if isinstance(event, KeyboardEvent):\n            c = event.key_code\n            if c in (ord(\"X\"), ord(\"x\"), ord(\"Q\"), ord(\"q\")):\n                raise StopApplication(\"User terminated app\")\n            if c in (ord(\" \"), ord(\"\\n\"), ord(\"\\r\")):\n                raise NextScene()",
    "docstring": "Default unhandled event handler for handling simple scene navigation."
  },
  {
    "code": "def Find(cls, setting_matcher, port_path=None, serial=None, timeout_ms=None):\n        if port_path:\n            device_matcher = cls.PortPathMatcher(port_path)\n            usb_info = port_path\n        elif serial:\n            device_matcher = cls.SerialMatcher(serial)\n            usb_info = serial\n        else:\n            device_matcher = None\n            usb_info = 'first'\n        return cls.FindFirst(setting_matcher, device_matcher,\n                             usb_info=usb_info, timeout_ms=timeout_ms)",
    "docstring": "Gets the first device that matches according to the keyword args."
  },
  {
    "code": "def enable_vmm_statistics(self, enable):\n        if not isinstance(enable, bool):\n            raise TypeError(\"enable can only be an instance of type bool\")\n        self._call(\"enableVMMStatistics\",\n                     in_p=[enable])",
    "docstring": "Enables or disables collection of VMM RAM statistics.\n\n        in enable of type bool\n            True enables statistics collection.\n\n        raises :class:`VBoxErrorInvalidVmState`\n            Machine session is not open.\n        \n        raises :class:`VBoxErrorInvalidObjectState`\n            Session type is not direct."
  },
  {
    "code": "def get_modules(folder):\n    if is_frozen():\n        zipname = os.path.dirname(os.path.dirname(__file__))\n        parentmodule = os.path.basename(os.path.dirname(__file__))\n        with zipfile.ZipFile(zipname, 'r') as f:\n            prefix = \"%s/%s/\" % (parentmodule, folder)\n            modnames = [os.path.splitext(n[len(prefix):])[0]\n              for n in f.namelist()\n              if n.startswith(prefix) and \"__init__\" not in n]\n    else:\n        dirname = os.path.join(os.path.dirname(__file__), folder)\n        modnames = get_importable_modules(dirname)\n    for modname in modnames:\n        try:\n            name =\"..%s.%s\" % (folder, modname)\n            yield importlib.import_module(name, __name__)\n        except ImportError as msg:\n            out.error(\"could not load module %s: %s\" % (modname, msg))",
    "docstring": "Find all valid modules in the given folder which must be in\n    in the same directory as this loader.py module. A valid module\n    has a .py extension, and is importable.\n    @return: all loaded valid modules\n    @rtype: iterator of module"
  },
  {
    "code": "def handle(data_type, data, data_id=None, caller=None):\n    if not data_id:\n        data_id = data_type\n    if data_id not in _handlers:\n        _handlers[data_id] = dict(\n            [(h.handle, h) for h in handlers.instantiate_for_data_type(data_type, data_id=data_id)])\n    for handler in list(_handlers[data_id].values()):\n        try:\n            data = handler(data, caller=caller)\n        except Exception as inst:\n            vodka.log.error(\"Data handler '%s' failed with error\" % handler)\n            vodka.log.error(traceback.format_exc())\n    return data",
    "docstring": "execute all data handlers on the specified data according to data type\n\n    Args:\n        data_type (str): data type handle\n        data (dict or list): data\n\n    Kwargs:\n        data_id (str): can be used to differentiate between different data\n            sets of the same data type. If not specified will default to\n            the data type\n        caller (object): if specified, holds the object or function that\n            is trying to handle data\n\n    Returns:\n        dict or list - data after handlers have been executed on it"
  },
  {
    "code": "def pages(self):\n        pages = []\n        for har_dict in self.har_data:\n            har_parser = HarParser(har_data=har_dict)\n            if self.page_id:\n                for page in har_parser.pages:\n                    if page.page_id == self.page_id:\n                        pages.append(page)\n            else:\n                pages = pages + har_parser.pages\n        return pages",
    "docstring": "The aggregate pages of all the parser objects."
  },
  {
    "code": "def option_group_exists(name, tags=None, region=None, key=None, keyid=None,\n                        profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    try:\n        rds = conn.describe_option_groups(OptionGroupName=name)\n        return {'exists': bool(rds)}\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Check to see if an RDS option group exists.\n\n    CLI example::\n\n        salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1"
  },
  {
    "code": "def to_b58check(self, testnet=False):\n        b = self.testnet_bytes if testnet else bytes(self)\n        return base58.b58encode_check(b)",
    "docstring": "Generates a Base58Check encoding of this key.\n\n        Args:\n            testnet (bool): True if the key is to be used with\n                testnet, False otherwise.\n        Returns:\n            str: A Base58Check encoded string representing the key."
  },
  {
    "code": "def is_modified(self):\n        if self.__modified_data__ is not None:\n            return True\n        for value in self.__original_data__:\n            try:\n                if value.is_modified():\n                    return True\n            except AttributeError:\n                pass\n        return False",
    "docstring": "Returns whether list is modified or not"
  },
  {
    "code": "def to_api(in_dict, int_keys=None, date_keys=None, bool_keys=None):\n    if int_keys:\n        for in_key in int_keys:\n            if (in_key in in_dict) and (in_dict.get(in_key, None) is not None):\n                in_dict[in_key] = int(in_dict[in_key])\n    if date_keys:\n        for in_key in date_keys:\n            if (in_key in in_dict) and (in_dict.get(in_key, None) is not None):\n                _from = in_dict[in_key]\n                if isinstance(_from, basestring):\n                    dtime = parse_datetime(_from)\n                elif isinstance(_from, datetime):\n                    dtime = _from\n                in_dict[in_key] = dtime.isoformat()\n            elif (in_key in in_dict) and in_dict.get(in_key, None) is None:\n                del in_dict[in_key]\n    for k, v in in_dict.items():\n        if v is None:\n            del in_dict[k]\n    return in_dict",
    "docstring": "Extends a given object for API Production."
  },
  {
    "code": "def feature_list():\n    lib_features_c_array = ctypes.POINTER(Feature)()\n    lib_features_size = ctypes.c_size_t()\n    check_call(_LIB.MXLibInfoFeatures(ctypes.byref(lib_features_c_array), ctypes.byref(lib_features_size)))\n    features = [lib_features_c_array[i] for i in range(lib_features_size.value)]\n    return features",
    "docstring": "Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc\n\n    Returns\n    -------\n    list\n        List of :class:`.Feature` objects"
  },
  {
    "code": "def wait_for_port(self, port, timeout=10, **probe_kwargs):\n        Probe(timeout=timeout, fnc=functools.partial(self.is_port_open, port), **probe_kwargs).run()",
    "docstring": "block until specified port starts accepting connections, raises an exc ProbeTimeout\n        if timeout is reached\n\n        :param port: int, port number\n        :param timeout: int or float (seconds), time to wait for establishing the connection\n        :param probe_kwargs: arguments passed to Probe constructor\n        :return: None"
  },
  {
    "code": "def ls():\n  heading, body = cli_syncthing_adapter.ls()\n  if heading:\n    click.echo(heading)\n  if body:\n    click.echo(body.strip())",
    "docstring": "List all synchronized directories."
  },
  {
    "code": "def load_fasta_file(filename):\n    with open(filename, \"r\") as handle:\n        records = list(SeqIO.parse(handle, \"fasta\"))\n    return records",
    "docstring": "Load a FASTA file and return the sequences as a list of SeqRecords\n\n    Args:\n        filename (str): Path to the FASTA file to load\n\n    Returns:\n        list: list of all sequences in the FASTA file as Biopython SeqRecord objects"
  },
  {
    "code": "def xor(s, pad):\n    from itertools import cycle\n    s = bytearray(force_bytes(s, encoding='latin-1'))\n    pad = bytearray(force_bytes(pad, encoding='latin-1'))\n    return binary_type(bytearray(x ^ y for x, y in zip(s, cycle(pad))))",
    "docstring": "XOR a given string ``s`` with the one-time-pad ``pad``"
  },
  {
    "code": "def config_profile_list(self):\n        these_profiles = self._config_profile_list() or []\n        profile_list = [q for p in these_profiles for q in\n                        [p.get('profileName')]]\n        return profile_list",
    "docstring": "Return config profile list from DCNM."
  },
  {
    "code": "def init_selection(self):\n        si = self.shotverbrws.selected_indexes(0)\n        if si:\n            self.shot_ver_sel_changed(si[0])\n        else:\n            self.shot_ver_sel_changed(QtCore.QModelIndex())\n        ai = self.assetverbrws.selected_indexes(0)\n        if ai:\n            self.asset_ver_sel_changed(ai[0])\n        else:\n            self.asset_ver_sel_changed(QtCore.QModelIndex())",
    "docstring": "Call selection changed in the beginning, so signals get emitted once\n\n        Emit shot_taskfile_sel_changed signal and asset_taskfile_sel_changed.\n\n        :returns: None\n        :raises: None"
  },
  {
    "code": "def get_agent(self, agent_id):\n        collection = JSONClientValidated('authentication',\n                                         collection='Agent',\n                                         runtime=self._runtime)\n        result = collection.find_one(\n            dict({'_id': ObjectId(self._get_id(agent_id, 'authentication').get_identifier())},\n                 **self._view_filter()))\n        return objects.Agent(osid_object_map=result, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets the ``Agent`` specified by its ``Id``.\n\n        In plenary mode, the exact ``Id`` is found or a ``NotFound``\n        results. Otherwise, the returned ``Agent`` may have a different\n        ``Id`` than requested, such as the case where a duplicate ``Id``\n        was assigned to an ``Agent`` and retained for compatibility.\n\n        arg:    agent_id (osid.id.Id): the ``Id`` of an ``Agent``\n        return: (osid.authentication.Agent) - the returned ``Agent``\n        raise:  NotFound - no ``Agent`` found with the given ``Id``\n        raise:  NullArgument - ``agent_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def glob1(self, dir_relpath, glob):\n    if self.isignored(dir_relpath, directory=True):\n      return []\n    matched_files = self._glob1_raw(dir_relpath, glob)\n    prefix = self._relpath_no_dot(dir_relpath)\n    return self._filter_ignored(matched_files, selector=lambda p: os.path.join(prefix, p))",
    "docstring": "Returns a list of paths in path that match glob and are not ignored."
  },
  {
    "code": "def calculate_shannon_entropy(self, data):\n        if not data:\n            return 0\n        entropy = 0\n        for x in self.charset:\n            p_x = float(data.count(x)) / len(data)\n            if p_x > 0:\n                entropy += - p_x * math.log(p_x, 2)\n        return entropy",
    "docstring": "Returns the entropy of a given string.\n\n        Borrowed from: http://blog.dkbza.org/2007/05/scanning-data-for-entropy-anomalies.html.\n\n        :param data:  string. The word to analyze.\n        :returns:       float, between 0.0 and 8.0"
  },
  {
    "code": "def local_path(self, url, filename=None, decompress=False, download=False):\n        if download:\n            return self.fetch(url=url, filename=filename, decompress=decompress)\n        else:\n            filename = self.local_filename(url, filename, decompress)\n            return join(self.cache_directory_path, filename)",
    "docstring": "What will the full local path be if we download the given file?"
  },
  {
    "code": "def register_run_plugins(self, plugin_name, plugin_class):\n        if plugin_name in self.registered_plugins:\n            raise PluginException(\"Plugin {} already registered! \"\n                                  \"Duplicate plugins?\".format(plugin_name))\n        self.logger.debug(\"Registering plugin %s\", plugin_name)\n        if plugin_class.get_allocators():\n            register_func = self.plugin_types[PluginTypes.ALLOCATOR]\n            register_func(plugin_name, plugin_class)\n        self.registered_plugins.append(plugin_name)",
    "docstring": "Loads a plugin as a dictionary and attaches needed parts to correct Icetea run\n        global parts.\n\n        :param plugin_name: Name of the plugins\n        :param plugin_class: PluginBase\n        :return: Nothing"
  },
  {
    "code": "def _setup_http_session(self):\n        headers = {\"Content-type\": \"application/json\"}\n        if (self._id_token):\n            headers.update({\"authorization\": \"Bearer {}\".format(\n                self._id_token)})\n        self._session.headers.update(headers)\n        self._session.verify = False",
    "docstring": "Sets up the common HTTP session parameters used by requests."
  },
  {
    "code": "def _find_usage_networking_sgs(self):\n        logger.debug(\"Getting usage for EC2 VPC resources\")\n        sgs_per_vpc = defaultdict(int)\n        rules_per_sg = defaultdict(int)\n        for sg in self.resource_conn.security_groups.all():\n            if sg.vpc_id is not None:\n                sgs_per_vpc[sg.vpc_id] += 1\n                rules_per_sg[sg.id] = len(sg.ip_permissions)\n        for vpc_id, count in sgs_per_vpc.items():\n            self.limits['Security groups per VPC']._add_current_usage(\n                count,\n                aws_type='AWS::EC2::VPC',\n                resource_id=vpc_id,\n            )\n        for sg_id, count in rules_per_sg.items():\n            self.limits['Rules per VPC security group']._add_current_usage(\n                count,\n                aws_type='AWS::EC2::SecurityGroupRule',\n                resource_id=sg_id,\n            )",
    "docstring": "calculate usage for VPC-related things"
  },
  {
    "code": "def ulocalized_gmt0_time(self, time, context, request):\n        value = get_date(context, time)\n        if not value:\n            return \"\"\n        value = value.toZone(\"GMT+0\")\n        return self.ulocalized_time(value, context, request)",
    "docstring": "Returns the localized time in string format, but in GMT+0"
  },
  {
    "code": "def match_tagname(self, el, tag):\n        name = (util.lower(tag.name) if not self.is_xml and tag.name is not None else tag.name)\n        return not (\n            name is not None and\n            name not in (self.get_tag(el), '*')\n        )",
    "docstring": "Match tag name."
  },
  {
    "code": "async def filter_new_posts(self, source_id, post_ids):\n        new_ids = []\n        try:\n            db_client = self._db\n            posts_in_db = await db_client.get_known_posts(source_id, post_ids)\n            new_ids = [p for p in post_ids if p not in posts_in_db]\n        except Exception as exc:\n            logger.error(\"Error when filtering for new posts {} {}\".format(source_id, post_ids))\n            logger.exception(exc)\n        return new_ids",
    "docstring": "Filters ist of post_id for new ones.\n\n        :param source_id: id of the source\n        :type string:\n        :param post_ids: list of post ids\n        :type list:\n        :returns: list of unknown post ids."
  },
  {
    "code": "def begin(self, request, data):\n        request = self.get_request(\n                http_url = self.REQUEST_TOKEN_URL,\n                parameters = dict(oauth_callback = self.get_callback(request)))\n        content = self.load_request(request)\n        if not content:\n            return redirect('netauth-login')\n        request = self.get_request(token = Token.from_string(content), http_url=self.AUTHORIZE_URL)\n        return redirect(request.to_url())",
    "docstring": "Try to get Request Token from OAuth Provider and\n            redirect user to provider's site for approval."
  },
  {
    "code": "def count_open_fds():\n    pid = os.getpid()\n    procs = subprocess.check_output(\n        ['lsof', '-w', '-Ff', '-p', str(pid)])\n    nprocs = len(\n        [s for s in procs.split('\\n') if s and s[0] == 'f' and s[1:].isdigit()]\n    )\n    return nprocs",
    "docstring": "return the number of open file descriptors for current process.\n\n    .. warning: will only work on UNIX-like os-es.\n\n    http://stackoverflow.com/a/7142094"
  },
  {
    "code": "def chown(dirs, user=None, group=None):\n    if isinstance(dirs, basestring):\n        dirs = [dirs]\n    args = ' '.join(dirs)\n    if user and group:\n        return sudo('chown {}:{} {}'.format(user, group, args))\n    elif user:\n        return sudo('chown {} {}'.format(user, args))\n    elif group:\n        return sudo('chgrp {} {}'.format(group, args))\n    else:\n        return None",
    "docstring": "User sudo to set user and group ownership"
  },
  {
    "code": "def add_unique_runid(testcase, run_id=None):\n    testcase[\"description\"] = '{}<br id=\"{}\"/>'.format(\n        testcase.get(\"description\") or \"\", run_id or id(add_unique_runid)\n    )",
    "docstring": "Adds run id to the test description.\n\n    The `run_id` runs makes the descriptions unique between imports and force Polarion\n    to update every testcase every time."
  },
  {
    "code": "def __get_values(self):\n        values = []\n        if self.__remote:\n            description = self.__client.describe(self.__point)\n            if description is not None:\n                if description['type'] != 'Point':\n                    raise IOTUnknown('%s is not a Point' % self.__point)\n                values = description['meta']['values']\n        else:\n            limit = 100\n            offset = 0\n            while True:\n                new = self.__point.list(limit=limit, offset=offset)\n                values += new\n                if len(new) < limit:\n                    break\n                offset += limit\n            lang = self.__client.default_lang\n            for value in values:\n                value['comment'] = value['comment'].get(lang, None) if value['comment'] else None\n        return values",
    "docstring": "Retrieve value information either via describe or point value listing. MUST be called within lock."
  },
  {
    "code": "def emit(self, record):\n    level = record.levelno\n    if not FLAGS.is_parsed():\n      global _warn_preinit_stderr\n      if _warn_preinit_stderr:\n        sys.stderr.write(\n            'WARNING: Logging before flag parsing goes to stderr.\\n')\n        _warn_preinit_stderr = False\n      self._log_to_stderr(record)\n    elif FLAGS['logtostderr'].value:\n      self._log_to_stderr(record)\n    else:\n      super(PythonHandler, self).emit(record)\n      stderr_threshold = converter.string_to_standard(\n          FLAGS['stderrthreshold'].value)\n      if ((FLAGS['alsologtostderr'].value or level >= stderr_threshold) and\n          self.stream != sys.stderr):\n        self._log_to_stderr(record)\n    if _is_absl_fatal_record(record):\n      self.flush()\n      os.abort()",
    "docstring": "Prints a record out to some streams.\n\n    If FLAGS.logtostderr is set, it will print to sys.stderr ONLY.\n    If FLAGS.alsologtostderr is set, it will print to sys.stderr.\n    If FLAGS.logtostderr is not set, it will log to the stream\n      associated with the current thread.\n\n    Args:\n      record: logging.LogRecord, the record to emit."
  },
  {
    "code": "def apply_to(self, x, columns=False):\n        if isinstance(x, np.ndarray) and len(x.shape) == 2 and x.shape[0] == 3 and columns:\n            return x + self.t.reshape((3,1))\n        if isinstance(x, np.ndarray) and (x.shape == (3, ) or (len(x.shape) == 2 and x.shape[1] == 3)) and not columns:\n            return x + self.t\n        elif isinstance(x, Complete):\n            return Complete(x.r, x.t + self.t)\n        elif isinstance(x, Translation):\n            return Translation(x.t + self.t)\n        elif isinstance(x, Rotation):\n            return Complete(x.r, self.t)\n        elif isinstance(x, UnitCell):\n            return x\n        else:\n            raise ValueError(\"Can not apply this translation to %s\" % x)",
    "docstring": "Apply this translation to the given object\n\n           The argument can be several sorts of objects:\n\n           * ``np.array`` with shape (3, )\n           * ``np.array`` with shape (N, 3)\n           * ``np.array`` with shape (3, N), use ``columns=True``\n           * ``Translation``\n           * ``Rotation``\n           * ``Complete``\n           * ``UnitCell``\n\n           In case of arrays, the 3D vectors are translated. In case of trans-\n           formations, a new transformation is returned that consists of this\n           translation applied AFTER the given translation. In case of a unit\n           cell, the original object is returned.\n\n           This method is equivalent to ``self*x``."
  },
  {
    "code": "def configure_lease(self, lease, lease_max, mount_point=DEFAULT_MOUNT_POINT):\n        params = {\n            'lease': lease,\n            'lease_max': lease_max,\n        }\n        api_path = '/v1/{mount_point}/config/lease'.format(mount_point=mount_point)\n        return self._adapter.post(\n            url=api_path,\n            json=params,\n        )",
    "docstring": "Configure lease settings for the AWS secrets engine.\n\n        It is optional, as there are default values for lease and lease_max.\n\n        Supported methods:\n            POST: /{mount_point}/config/lease. Produces: 204 (empty body)\n\n        :param lease: Specifies the lease value provided as a string duration with time suffix. \"h\" (hour) is the\n            largest suffix.\n        :type lease: str | unicode\n        :param lease_max: Specifies the maximum lease value provided as a string duration with time suffix. \"h\" (hour)\n            is the largest suffix.\n        :type lease_max: str | unicode\n        :param mount_point: The \"path\" the method/backend was mounted on.\n        :type mount_point: str | unicode\n        :return: The response of the request.\n        :rtype: requests.Response"
  },
  {
    "code": "def format(logger,\n           show_successful=True,\n           show_errors=True,\n           show_traceback=True):\n    output = []\n    errors = logger.get_aborted_actions()\n    if show_errors and errors:\n        output += _underline('Failed actions:')\n        for log in logger.get_aborted_logs():\n            if show_traceback:\n                output.append(log.get_name() + ':')\n                output.append(log.get_error())\n            else:\n                output.append(log.get_name() + ': ' + log.get_error(False))\n        output.append('')\n    if show_successful:\n        output += _underline('Successful actions:')\n        for log in logger.get_succeeded_logs():\n            output.append(log.get_name())\n        output.append('')\n    return '\\n'.join(output).strip()",
    "docstring": "Prints a report of the actions that were logged by the given Logger.\n    The report contains a list of successful actions, as well as the full\n    error message on failed actions.\n\n    :type  logger: Logger\n    :param logger: The logger that recorded what happened in the queue.\n    :rtype:  string\n    :return: A string summarizing the status of every performed task."
  },
  {
    "code": "def _iterate_prefix(self, callsign, timestamp=timestamp_now):\n        prefix = callsign\n        if re.search('(VK|AX|VI)9[A-Z]{3}', callsign):\n            if timestamp > datetime(2006,1,1, tzinfo=UTC):\n                prefix = callsign[0:3]+callsign[4:5]\n        while len(prefix) > 0:\n            try:\n                return self._lookuplib.lookup_prefix(prefix, timestamp)\n            except KeyError:\n                prefix = prefix.replace(' ', '')[:-1]\n                continue\n        raise KeyError",
    "docstring": "truncate call until it corresponds to a Prefix in the database"
  },
  {
    "code": "def update_from_json(self, path=join('config', 'hdx_dataset_static.json')):\n        super(Dataset, self).update_from_json(path)\n        self.separate_resources()",
    "docstring": "Update dataset metadata with static metadata from JSON file\n\n        Args:\n            path (str): Path to JSON dataset metadata. Defaults to config/hdx_dataset_static.json.\n\n        Returns:\n            None"
  },
  {
    "code": "def do_history(self, line):\n        self._split_args(line, 0, 0)\n        for idx, item in enumerate(self._history):\n            d1_cli.impl.util.print_info(\"{0: 3d} {1}\".format(idx, item))",
    "docstring": "history Display a list of commands that have been entered."
  },
  {
    "code": "def compose_all(stream, Loader=Loader):\n    loader = Loader(stream)\n    try:\n        while loader.check_node():\n            yield loader.get_node()\n    finally:\n        loader.dispose()",
    "docstring": "Parse all YAML documents in a stream\n    and produce corresponding representation trees."
  },
  {
    "code": "def toPIL(self, **attribs):\n        import PIL.Image\n        bytes = self.convert(\"png\")\n        sfile = io.BytesIO(bytes)\n        pil = PIL.Image.open(sfile)\n        return pil",
    "docstring": "Convert canvas to a PIL image"
  },
  {
    "code": "def panzoom(marks):\n    return PanZoom(scales={\n            'x': sum([mark._get_dimension_scales('x', preserve_domain=True) for mark in marks], []),\n            'y': sum([mark._get_dimension_scales('y', preserve_domain=True) for mark in marks], [])\n    })",
    "docstring": "Helper function for panning and zooming over a set of marks.\n\n    Creates and returns a panzoom interaction with the 'x' and 'y' dimension\n    scales of the specified marks."
  },
  {
    "code": "def _execute_command(self, command, workunit_name=None, workunit_labels=None):\n    workunit_name = workunit_name or command.executable\n    workunit_labels = {WorkUnitLabel.TOOL} | set(workunit_labels or ())\n    with self.context.new_workunit(name=workunit_name,\n                                   labels=workunit_labels,\n                                   cmd=str(command)) as workunit:\n      returncode = self._run_node_distribution_command(command, workunit)\n      workunit.set_outcome(WorkUnit.SUCCESS if returncode == 0 else WorkUnit.FAILURE)\n      return returncode, command",
    "docstring": "Executes a node or npm command via self._run_node_distribution_command.\n\n    :param NodeDistribution.Command command: The command to run.\n    :param string workunit_name: A name for the execution's work unit; default command.executable.\n    :param list workunit_labels: Any extra :class:`pants.base.workunit.WorkUnitLabel`s to apply.\n    :returns: A tuple of (returncode, command).\n    :rtype: A tuple of (int,\n            :class:`pants.contrib.node.subsystems.node_distribution.NodeDistribution.Command`)"
  },
  {
    "code": "def build_docs(location=\"doc-source\", target=None, library=\"icetea_lib\"):\n    cmd_ar = [\"sphinx-apidoc\", \"-o\", location, library]\n    try:\n        print(\"Generating api docs.\")\n        retcode = check_call(cmd_ar)\n    except CalledProcessError as error:\n        print(\"Documentation build failed. Return code: {}\".format(error.returncode))\n        return 3\n    except OSError as error:\n        print(error)\n        print(\"Documentation build failed. Are you missing Sphinx? Please install sphinx using \"\n              \"'pip install sphinx'.\")\n        return 3\n    target = \"doc{}html\".format(os.sep) if target is None else target\n    cmd_ar = [\"sphinx-build\", \"-b\", \"html\", location, target]\n    try:\n        print(\"Building html documentation.\")\n        retcode = check_call(cmd_ar)\n    except CalledProcessError as error:\n        print(\"Documentation build failed. Return code: {}\".format(error.returncode))\n        return 3\n    except OSError as error:\n        print(error)\n        print(\"Documentation build failed. Are you missing Sphinx? Please install sphinx using \"\n              \"'pip install sphinx'.\")\n        return 3\n    print(\"Documentation built.\")\n    return 0",
    "docstring": "Build documentation for Icetea. Start by autogenerating module documentation\n    and finish by building html.\n\n    :param location: Documentation source\n    :param target: Documentation target path\n    :param library: Library location for autodoc.\n    :return: -1 if something fails. 0 if successfull."
  },
  {
    "code": "def pickle_dumps(self, protocol=None):\n        strio = StringIO()\n        pmg_pickle_dump(self, strio,\n                        protocol=self.pickle_protocol if protocol is None\n                        else protocol)\n        return strio.getvalue()",
    "docstring": "Return a string with the pickle representation.\n        `protocol` selects the pickle protocol. self.pickle_protocol is\n         used if `protocol` is None"
  },
  {
    "code": "def get(self, key, get_cas=False):\n        for server in self.servers:\n            value, cas = server.get(key)\n            if value is not None:\n                if get_cas:\n                    return value, cas\n                else:\n                    return value\n        if get_cas:\n            return None, None",
    "docstring": "Get a key from server.\n\n        :param key: Key's name\n        :type key: six.string_types\n        :param get_cas: If true, return (value, cas), where cas is the new CAS value.\n        :type get_cas: boolean\n        :return: Returns a key data from server.\n        :rtype: object"
  },
  {
    "code": "def assert_page_source_contains(self, expected_value, failure_message='Expected page source to contain: \"{}\"'):\n        assertion = lambda: expected_value in self.driver_wrapper.page_source()\n        self.webdriver_assert(assertion, unicode(failure_message).format(expected_value))",
    "docstring": "Asserts that the page source contains the string passed in expected_value"
  },
  {
    "code": "def update(self, job_id, name=NotUpdated, description=NotUpdated,\n               is_public=NotUpdated, is_protected=NotUpdated):\n        data = {}\n        self._copy_if_updated(data, name=name, description=description,\n                              is_public=is_public, is_protected=is_protected)\n        return self._patch('/jobs/%s' % job_id, data)",
    "docstring": "Update a Job."
  },
  {
    "code": "def square_root(n, epsilon=0.001):\n    guess = n / 2\n    while abs(guess * guess - n) > epsilon:\n        guess = (guess + (n / guess)) / 2\n    return guess",
    "docstring": "Return square root of n, with maximum absolute error epsilon"
  },
  {
    "code": "def safe_call(request: Request, methods: Methods, *, debug: bool) -> Response:\n    with handle_exceptions(request, debug) as handler:\n        result = call(methods.items[request.method], *request.args, **request.kwargs)\n        handler.response = SuccessResponse(result=result, id=request.id)\n    return handler.response",
    "docstring": "Call a Request, catching exceptions to ensure we always return a Response.\n\n    Args:\n        request: The Request object.\n        methods: The list of methods that can be called.\n        debug: Include more information in error responses.\n\n    Returns:\n        A Response object."
  },
  {
    "code": "def valarray(shape, value=np.NaN, typecode=None):\n    if typecode is None:\n        typecode = bool\n    out = np.ones(shape, dtype=typecode) * value\n    if not isinstance(out, np.ndarray):\n        out = np.asarray(out)\n    return out",
    "docstring": "Return an array of all value."
  },
  {
    "code": "def capitalize_unicode_name(s):\n    index = s.find('capital')\n    if index == -1: return s\n    tail = s[index:].replace('capital', '').strip()\n    tail = tail[0].upper() + tail[1:]\n    return s[:index] + tail",
    "docstring": "Turns a string such as 'capital delta' into the shortened,\n    capitalized version, in this case simply 'Delta'. Used as a\n    transform in sanitize_identifier."
  },
  {
    "code": "def get_first_lang():\n    request_lang = request.headers.get('Accept-Language').split(',')\n    if request_lang:\n        lang = locale.normalize(request_lang[0]).split('.')[0]\n    else:\n        lang = False\n    return lang",
    "docstring": "Get the first lang of Accept-Language Header."
  },
  {
    "code": "def getTypeStr(_type):\n  r\n  if isinstance(_type, CustomType):\n    return str(_type)\n  if hasattr(_type, '__name__'):\n    return _type.__name__\n  return ''",
    "docstring": "r\"\"\"Gets the string representation of the given type."
  },
  {
    "code": "def npm(usr_pwd=None, clean=False):\n\ttry: cmd('which npm')\n\texcept:\n\t\treturn\n\tprint('-[npm]----------')\n\tp = cmd(\"npm outdated -g | awk 'NR>1 {print $1}'\")\n\tif not p: return\n\tpkgs = getPackages(p)\n\tfor p in pkgs:\n\t\tcmd('{} {}'.format('npm update -g ', p), usr_pwd=usr_pwd, run=global_run)",
    "docstring": "Handle npm for Node.js"
  },
  {
    "code": "def _remote_file_size(url=None, file_name=None, pb_dir=None):\n    if file_name and pb_dir:\n        url = posixpath.join(config.db_index_url, pb_dir, file_name)\n    response = requests.head(url, headers={'Accept-Encoding': 'identity'})\n    response.raise_for_status()\n    remote_file_size = int(response.headers['content-length'])\n    return remote_file_size",
    "docstring": "Get the remote file size in bytes\n\n    Parameters\n    ----------\n    url : str, optional\n        The full url of the file. Use this option to explicitly\n        state the full url.\n    file_name : str, optional\n        The base file name. Use this argument along with pb_dir if you\n        want the full url to be constructed.\n    pb_dir : str, optional\n        The base file name. Use this argument along with file_name if\n        you want the full url to be constructed.\n\n    Returns\n    -------\n    remote_file_size : int\n        Size of the file in bytes"
  },
  {
    "code": "def _add_membership_multicast_socket(self):\n        self._membership_request = socket.inet_aton(self._multicast_group) \\\n            + socket.inet_aton(self._multicast_ip)\n        self._multicast_socket.setsockopt(\n            socket.IPPROTO_IP,\n            socket.IP_ADD_MEMBERSHIP,\n            self._membership_request\n        )",
    "docstring": "Make membership request to multicast\n\n        :rtype: None"
  },
  {
    "code": "def to_commit(obj):\n    if obj.type == 'tag':\n        obj = deref_tag(obj)\n    if obj.type != \"commit\":\n        raise ValueError(\"Cannot convert object %r to type commit\" % obj)\n    return obj",
    "docstring": "Convert the given object to a commit if possible and return it"
  },
  {
    "code": "def tokenize(self):\n        tokens = []\n        token_spec = [\n            ('mlc', r'/\\*.*?\\*/'),\n            ('slc', r'//[^\\r\\n]*?\\r?\\n'),\n            ('perl', r'<%.*?%>'),\n            ('incl', r'`include'),\n        ]\n        tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_spec)\n        for m in re.finditer(tok_regex, self.text, re.DOTALL):\n            if m.lastgroup in (\"incl\", \"perl\"):\n                tokens.append((m.lastgroup, m.start(0), m.end(0)-1))\n        return tokens",
    "docstring": "Tokenize the input text\n\n        Scans for instances of perl tags and include directives.\n        Tokenization skips line and block comments.\n\n        Returns\n        -------\n        list\n            List of tuples: (typ, start, end)\n\n            Where:\n\n            - typ is \"perl\" or \"incl\"\n            - start/end mark the first/last char offset of the token"
  },
  {
    "code": "def export_wif(self) -> str:\n        data = b''.join([b'\\x80', self.__private_key, b'\\01'])\n        checksum = Digest.hash256(data[0:34])\n        wif = base58.b58encode(b''.join([data, checksum[0:4]]))\n        return wif.decode('ascii')",
    "docstring": "This interface is used to get export ECDSA private key in the form of WIF which\n        is a way to encoding an ECDSA private key and make it easier to copy.\n\n        :return: a WIF encode private key."
  },
  {
    "code": "def effective_nsamples(self):\n        try:\n            act = numpy.array(list(self.acts.values())).max()\n        except (AttributeError, TypeError):\n            act = numpy.inf\n        if self.burn_in is None:\n            nperwalker = max(int(self.niterations // act), 1)\n        elif self.burn_in.is_burned_in:\n            nperwalker = int(\n                (self.niterations - self.burn_in.burn_in_iteration) // act)\n            nperwalker = max(nperwalker, 1)\n        else:\n            nperwalker = 0\n        return self.nwalkers * nperwalker",
    "docstring": "The effective number of samples post burn-in that the sampler has\n        acquired so far."
  },
  {
    "code": "def get(self, url, data=None):\n        response = self.http.get(url,\n                                 headers=self.headers,\n                                 params=data,\n                                 **self.requests_params)\n        return self.process(response)",
    "docstring": "Executes an HTTP GET request for the given URL.\n\n            ``data`` should be a dictionary of url parameters"
  },
  {
    "code": "def plot_sed(sed, showlnl=False, **kwargs):\n        ax = kwargs.pop('ax', plt.gca())\n        cmap = kwargs.get('cmap', 'BuGn')\n        annotate_name(sed, ax=ax)\n        SEDPlotter.plot_flux_points(sed, **kwargs)\n        if np.any(sed['ts'] > 9.):\n            if 'model_flux' in sed:\n                SEDPlotter.plot_model(sed['model_flux'],\n                                      noband=showlnl, **kwargs)\n        if showlnl:\n            SEDPlotter.plot_lnlscan(sed, **kwargs)\n        ax.set_yscale('log')\n        ax.set_xscale('log')\n        ax.set_xlabel('Energy [MeV]')\n        ax.set_ylabel('E$^{2}$dN/dE [MeV cm$^{-2}$ s$^{-1}$]')",
    "docstring": "Render a plot of a spectral energy distribution.\n\n        Parameters\n        ----------\n        showlnl : bool        \n            Overlay a map of the delta-loglikelihood values vs. flux\n            in each energy bin.\n\n        cmap : str        \n            Colormap that will be used for the delta-loglikelihood\n            map.\n\n        llhcut : float\n            Minimum delta-loglikelihood value.\n\n        ul_ts_threshold : float        \n            TS threshold that determines whether the MLE or UL\n            is plotted in each energy bin."
  },
  {
    "code": "def filter(self, chromosome, **kwargs) :\n\t\tdef appendAllele(alleles, sources, snp) :\n\t\t\tpos = snp.start\n\t\t\tif snp.alt[0] == '-' :\n\t\t\t\tpass\n\t\t\telif snp.ref[0] == '-' :\n\t\t\t\tpass\n\t\t\telse :\n\t\t\t\tsources[snpSet] = snp\n\t\t\t\talleles.append(snp.alt)\n\t\t\trefAllele = chromosome.refSequence[pos]\n\t\t\talleles.append(refAllele)\n\t\t\tsources['ref'] = refAllele\n\t\t\treturn alleles, sources\n\t\twarn = 'Warning: the default snp filter ignores indels. IGNORED %s of SNP set: %s at pos: %s of chromosome: %s'\n\t\tsources = {}\n\t\talleles = []\n\t\tfor snpSet, data in kwargs.iteritems() :\n\t\t\tif type(data) is list :\n\t\t\t\tfor snp in data :\n\t\t\t\t\talleles, sources = appendAllele(alleles, sources, snp)\n\t\t\telse :\n\t\t\t\tallels, sources = appendAllele(alleles, sources, data)\n\t\treturn SequenceSNP(alleles, sources = sources)",
    "docstring": "The default filter mixes applied all SNPs and ignores Insertions and Deletions."
  },
  {
    "code": "def threshold(image, block_size=DEFAULT_BLOCKSIZE, mask=None):\n    if mask is None:\n        mask = np.zeros(image.shape[:2], dtype=np.uint8)\n        mask[:] = 255\n    if len(image.shape) > 2 and image.shape[2] == 4:\n        image = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY)\n    res = _calc_block_mean_variance(image, mask, block_size)\n    res = image.astype(np.float32) - res.astype(np.float32) + 255\n    _, res = cv2.threshold(res, 215, 255, cv2.THRESH_BINARY)\n    return res",
    "docstring": "Applies adaptive thresholding to the given image.\n\n    Args:\n        image: BGRA image.\n        block_size: optional int block_size to use for adaptive thresholding.\n        mask: optional mask.\n    Returns:\n        Thresholded image."
  },
  {
    "code": "def revoker(self, revoker, **prefs):\n        hash_algo = prefs.pop('hash', None)\n        sig = PGPSignature.new(SignatureType.DirectlyOnKey, self.key_algorithm, hash_algo, self.fingerprint.keyid)\n        sensitive = prefs.pop('sensitive', False)\n        keyclass = RevocationKeyClass.Normal | (RevocationKeyClass.Sensitive if sensitive else 0x00)\n        sig._signature.subpackets.addnew('RevocationKey',\n                                         hashed=True,\n                                         algorithm=revoker.key_algorithm,\n                                         fingerprint=revoker.fingerprint,\n                                         keyclass=keyclass)\n        prefs['revocable'] = False\n        return self._sign(self, sig, **prefs)",
    "docstring": "Generate a signature that specifies another key as being valid for revoking this key.\n\n        :param revoker: The :py:obj:`PGPKey` to specify as a valid revocation key.\n        :type revoker: :py:obj:`PGPKey`\n        :raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked\n        :raises: :py:exc:`~pgpy.errors.PGPError` if the key is public\n        :returns: :py:obj:`PGPSignature`\n\n        In addition to the optional keyword arguments accepted by :py:meth:`PGPKey.sign`, the following optional\n        keyword arguments can be used with :py:meth:`PGPKey.revoker`.\n\n        :keyword sensitive: If ``True``, this sets the sensitive flag on the RevocationKey subpacket. Currently,\n                            this has no other effect.\n        :type sensitive: ``bool``"
  },
  {
    "code": "def _set_relationship_type(self, type_identifier, display_name=None, display_label=None, description=None, domain='Relationship'):\n        if display_name is None:\n            display_name = type_identifier\n        if display_label is None:\n            display_label = display_name\n        if description is None:\n            description = 'Relationship Type for ' + display_name\n        self._relationship_type = Type(authority='DLKIT',\n                                       namespace='relationship.Relationship',\n                                       identifier=type_identifier,\n                                       display_name=display_name,\n                                       display_label=display_label,\n                                       description=description,\n                                       domain=domain)",
    "docstring": "Sets the relationship type"
  },
  {
    "code": "def state(self, *args, **kwargs):\n        return self._makeApiCall(self.funcinfo[\"state\"], *args, **kwargs)",
    "docstring": "Get AWS State for a worker type\n\n        Return the state of a given workertype as stored by the provisioner.\n        This state is stored as three lists: 1 for running instances, 1 for\n        pending requests.  The `summary` property contains an updated summary\n        similar to that returned from `listWorkerTypeSummaries`.\n\n        This method is ``stable``"
  },
  {
    "code": "def ClaimRecords(self,\n                   limit=10000,\n                   timeout=\"30m\",\n                   start_time=None,\n                   record_filter=lambda x: False,\n                   max_filtered=1000):\n    if not self.locked:\n      raise aff4.LockError(\"Queue must be locked to claim records.\")\n    with data_store.DB.GetMutationPool() as mutation_pool:\n      return mutation_pool.QueueClaimRecords(\n          self.urn,\n          self.rdf_type,\n          limit=limit,\n          timeout=timeout,\n          start_time=start_time,\n          record_filter=record_filter,\n          max_filtered=max_filtered)",
    "docstring": "Returns and claims up to limit unclaimed records for timeout seconds.\n\n    Returns a list of records which are now \"claimed\", a claimed record will\n    generally be unavailable to be claimed until the claim times out. Note\n    however that in case of an unexpected timeout or other error a record might\n    be claimed twice at the same time. For this reason it should be considered\n    weaker than a true lock.\n\n    Args:\n      limit: The number of records to claim.\n\n      timeout: The duration of the claim.\n\n      start_time: The time to start claiming records at. Only records with a\n        timestamp after this point will be claimed.\n\n      record_filter: A filter method to determine if the record should be\n        returned. It will be called serially on each record and the record will\n        be filtered (not returned or locked) if it returns True.\n\n      max_filtered: If non-zero, limits the number of results read when\n        filtered. Specifically, if max_filtered filtered results are read\n        sequentially without any unfiltered results, we stop looking for\n        results.\n\n    Returns:\n      A list (id, record) where record is a self.rdf_type and id is a record\n      identifier which can be used to delete or release the record.\n\n    Raises:\n      LockError: If the queue is not locked."
  },
  {
    "code": "def custom_resolve(self):\n        if not callable(self.custom_resolver):\n            return\n        new_addresses = []\n        for address in self.addresses:\n            for new_address in self.custom_resolver(address):\n                new_addresses.append(new_address)\n        self.addresses = new_addresses",
    "docstring": "If a custom resolver is defined, perform custom resolution on\n        the contained addresses.\n\n        :return:"
  },
  {
    "code": "def get_resource(self, path, params=None):\n        url = '%s%s' % (path, self._param_list(params))\n        headers = {\n            'Accept': 'application/json;odata=minimalmetadata'\n        }\n        response = O365_DAO().getURL(self._url(url), headers)\n        if response.status != 200:\n            raise DataFailureException(url, response.status, response.data)\n        return json_loads(response.data)",
    "docstring": "O365 GET method. Return representation of the requested resource."
  },
  {
    "code": "def tailor(pattern_or_root, dimensions=None, distributed_dim='time',\n           read_only=False):\n    return TileManager(pattern_or_root, dimensions=dimensions,\n                       distributed_dim=distributed_dim, read_only=read_only)",
    "docstring": "Return a TileManager to wrap the root descriptor and tailor all the\n    dimensions to a specified window.\n\n    Keyword arguments:\n    root -- a NCObject descriptor.\n    pattern -- a filename string to open a NCObject descriptor.\n    dimensions -- a dictionary to configurate the dimensions limits."
  },
  {
    "code": "def unpatch(self):\n        if not self._patched:\n            return\n        for func in self._read_compilers + self._write_compilers:\n            func.execute_sql = self._original[func]\n        self.cache_backend.unpatch()\n        self._patched = False",
    "docstring": "un-applies this patch."
  },
  {
    "code": "def close(self):\n        with self._close_lock:\n            sfd = self._sfd\n            if sfd >= 0:\n                self._sfd = -1\n                self._signals = frozenset()\n                close(sfd)",
    "docstring": "Close the internal signalfd file descriptor if it isn't closed\n\n        :raises OSError:\n            If the underlying ``close(2)`` fails. The error message matches\n            those found in the manual page."
  },
  {
    "code": "def value_text(self):\n        search = self._selected.get()\n        for item in self._rbuttons:\n            if item.value == search:\n                return item.text\n        return \"\"",
    "docstring": "Sets or returns the option selected in a ButtonGroup by its text value."
  },
  {
    "code": "def save_current_figure_as(self):\n        if self.current_thumbnail is not None:\n            self.save_figure_as(self.current_thumbnail.canvas.fig,\n                                self.current_thumbnail.canvas.fmt)",
    "docstring": "Save the currently selected figure."
  },
  {
    "code": "def add_summary(self, summary, global_step=None):\n        if isinstance(summary, bytes):\n            summ = summary_pb2.Summary()\n            summ.ParseFromString(summary)\n            summary = summ\n        for value in summary.value:\n            if not value.metadata:\n                continue\n            if value.tag in self._seen_summary_tags:\n                value.ClearField(\"metadata\")\n                continue\n            self._seen_summary_tags.add(value.tag)\n        event = event_pb2.Event(summary=summary)\n        self._add_event(event, global_step)",
    "docstring": "Adds a `Summary` protocol buffer to the event file.\n        This method wraps the provided summary in an `Event` protocol buffer and adds it\n        to the event file.\n\n        Parameters\n        ----------\n          summary : A `Summary` protocol buffer\n              Optionally serialized as a string.\n          global_step: Number\n              Optional global step value to record with the summary."
  },
  {
    "code": "def _use_memcache(self, key, options=None):\n    flag = ContextOptions.use_memcache(options)\n    if flag is None:\n      flag = self._memcache_policy(key)\n    if flag is None:\n      flag = ContextOptions.use_memcache(self._conn.config)\n    if flag is None:\n      flag = True\n    return flag",
    "docstring": "Return whether to use memcache for this key.\n\n    Args:\n      key: Key instance.\n      options: ContextOptions instance, or None.\n\n    Returns:\n      True if the key should be cached in memcache, False otherwise."
  },
  {
    "code": "def translate(self, vector, inc_alt_states=True):\n        vector = numpy.array(vector)\n        for atom in self.get_atoms(inc_alt_states=inc_alt_states):\n            atom._vector += vector\n        return",
    "docstring": "Translates every atom in the AMPAL object.\n\n        Parameters\n        ----------\n        vector : 3D Vector (tuple, list, numpy.array)\n            Vector used for translation.\n        inc_alt_states : bool, optional\n            If true, will rotate atoms in all states i.e. includes\n            alternate conformations for sidechains."
  },
  {
    "code": "def _create_interval_filter(interval):\n  def filter_fn(value):\n    if (not isinstance(value, six.integer_types) and\n        not isinstance(value, float)):\n      raise error.HParamsError(\n          'Cannot use an interval filter for a value of type: %s, Value: %s' %\n          (type(value), value))\n    return interval.min_value <= value and value <= interval.max_value\n  return filter_fn",
    "docstring": "Returns a function that checkes whether a number belongs to an interval.\n\n  Args:\n    interval: A tensorboard.hparams.Interval protobuf describing the interval.\n  Returns:\n    A function taking a number (a float or an object of a type in\n    six.integer_types) that returns True if the number belongs to (the closed)\n    'interval'."
  },
  {
    "code": "def _polling_iteration(self):\n\t\tif self.__task is None:\n\t\t\tself.ready_event().set()\n\t\telif self.__task.check_events() is True:\n\t\t\tself.ready_event().set()\n\t\t\tself.registry().task_finished(self)",
    "docstring": "Poll for scheduled task stop events\n\n\t\t:return: None"
  },
  {
    "code": "def merge_entities(doc):\n    with doc.retokenize() as retokenizer:\n        for ent in doc.ents:\n            attrs = {\"tag\": ent.root.tag, \"dep\": ent.root.dep, \"ent_type\": ent.label}\n            retokenizer.merge(ent, attrs=attrs)\n    return doc",
    "docstring": "Merge entities into a single token.\n\n    doc (Doc): The Doc object.\n    RETURNS (Doc): The Doc object with merged entities.\n\n    DOCS: https://spacy.io/api/pipeline-functions#merge_entities"
  },
  {
    "code": "def job_runner(self):\n        outputs = luigi.task.flatten(self.output())\n        for output in outputs:\n            if not isinstance(output, luigi.contrib.hdfs.HdfsTarget):\n                warnings.warn(\"Job is using one or more non-HdfsTarget outputs\" +\n                              \" so it will be run in local mode\")\n                return LocalJobRunner()\n        else:\n            return DefaultHadoopJobRunner()",
    "docstring": "Get the MapReduce runner for this job.\n\n        If all outputs are HdfsTargets, the DefaultHadoopJobRunner will be used.\n        Otherwise, the LocalJobRunner which streams all data through the local machine\n        will be used (great for testing)."
  },
  {
    "code": "def _print_drift_report(self):\n        try:\n            response = self._cloud_formation.describe_stack_resources(StackName=self._stack_name)\n            rows = []\n            for resource in response.get('StackResources', []):\n                row = []\n                row.append(resource.get('LogicalResourceId', 'unknown'))\n                row.append(resource.get('PhysicalResourceId', 'unknown'))\n                row.append(resource.get('ResourceStatus', 'unknown'))\n                row.append(resource.get('DriftInformation', {}).get('StackResourceDriftStatus', 'unknown'))\n                rows.append(row)\n            print('Drift Report:')\n            print(tabulate(rows, headers=[\n                'Logical ID',\n                'Physical ID',\n                'Resource Status',\n                'Drift Info'\n            ]))\n        except Exception as wtf:\n            logging.error(wtf, exc_info=True)\n            return False\n        return True",
    "docstring": "Report the drift of the stack.\n\n        Args:\n            None\n\n        Returns:\n            Good or Bad; True or False\n\n        Note: not yet implemented"
  },
  {
    "code": "def _cli_check_format(fmt):\n    if fmt is None:\n        return None\n    fmt = fmt.lower()\n    if not fmt in api.get_formats():\n        errstr = \"Format '\" + fmt + \"' does not exist.\\n\"\n        errstr += \"For a complete list of formats, use the 'bse list-formats' command\"\n        raise RuntimeError(errstr)\n    return fmt",
    "docstring": "Checks that a basis set format exists and if not, raises a helpful exception"
  },
  {
    "code": "async def generate_waifu_insult(self, avatar):\n        if not isinstance(avatar, str):\n            raise TypeError(\"type of 'avatar' must be str.\")\n        async with aiohttp.ClientSession() as session:\n            async with session.post(\"https://api.weeb.sh/auto-image/waifu-insult\", headers=self.__headers, data={\"avatar\": avatar}) as resp:\n                if resp.status == 200:\n                    return await resp.read()\n                else:\n                    raise Exception((await resp.json())['message'])",
    "docstring": "Generate a waifu insult image.\n\n        This function is a coroutine.\n\n        Parameters:\n            avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image\n\n        Return Type: image data"
  },
  {
    "code": "def users_get(self, domain):\n        path = self._get_management_path(domain)\n        return self.http_request(path=path,\n                                 method='GET')",
    "docstring": "Retrieve a list of users from the server.\n\n        :param AuthDomain domain: The authentication domain to retrieve users from.\n        :return: :class:`~.HttpResult`. The list of users can be obtained from\n            the returned object's `value` property."
  },
  {
    "code": "def to_struct(cls, name=None):\n        if name is None:\n            name = cls.__name__\n        basic_attrs = dict([(attr_name, value)\n                            for attr_name, value in cls.get_attrs()\n                            if isinstance(value, Column)])\n        if not basic_attrs:\n            return None\n        src = 'struct {0} {{'.format(name)\n        for attr_name, value in basic_attrs.items():\n            src += '{0} {1};'.format(value.type.typename, attr_name)\n        src += '};'\n        if ROOT.gROOT.ProcessLine(src) != 0:\n            return None\n        return getattr(ROOT, name, None)",
    "docstring": "Convert the TreeModel into a compiled C struct"
  },
  {
    "code": "def GetBatchJobDownloadUrlWhenReady(client, batch_job_id,\n                                    max_poll_attempts=MAX_POLL_ATTEMPTS):\n  batch_job = GetBatchJob(client, batch_job_id)\n  if batch_job['status'] == 'CANCELED':\n    raise Exception('Batch Job with ID \"%s\" was canceled before completing.'\n                    % batch_job_id)\n  poll_attempt = 0\n  while (poll_attempt in range(max_poll_attempts) and\n         batch_job['status'] in PENDING_STATUSES):\n    sleep_interval = (30 * (2 ** poll_attempt) +\n                      (random.randint(0, 10000) / 1000))\n    print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval\n    time.sleep(sleep_interval)\n    batch_job = GetBatchJob(client, batch_job_id)\n    poll_attempt += 1\n    if 'downloadUrl' in batch_job:\n      url = batch_job['downloadUrl']['url']\n      print ('Batch Job with Id \"%s\", Status \"%s\", and DownloadUrl \"%s\" ready.'\n             % (batch_job['id'], batch_job['status'], url))\n      return url\n  print ('BatchJob with ID \"%s\" is being canceled because it was in a pending '\n         'state after polling %d times.' % (batch_job_id, max_poll_attempts))\n  CancelBatchJob(client, batch_job)",
    "docstring": "Retrieves the downloadUrl when the BatchJob is complete.\n\n  Args:\n    client: an instantiated AdWordsClient used to poll the BatchJob.\n    batch_job_id: a long identifying the BatchJob to be polled.\n    max_poll_attempts: an int defining the number of times the BatchJob will be\n      checked to determine whether it has completed.\n\n  Returns:\n    A str containing the downloadUrl of the completed BatchJob.\n\n  Raises:\n    Exception: If the BatchJob hasn't finished after the maximum poll attempts\n      have been made."
  },
  {
    "code": "def _endmsg(self, rd):\n        msg = \"\"\n        s = \"\"\n        if rd.hours > 0:\n            if rd.hours > 1:\n                s = \"s\"\n            msg += colors.bold(str(rd.hours)) + \" hour\" + s + \" \"\n        s = \"\"\n        if rd.minutes > 0:\n            if rd.minutes > 1:\n                s = \"s\"\n            msg += colors.bold(str(rd.minutes)) + \" minute\" + s + \" \"\n        milliseconds = int(rd.microseconds / 1000)\n        if milliseconds > 0:\n            msg += colors.bold(str(rd.seconds) + \".\" + str(milliseconds))\n        msg += \" seconds\"\n        return msg",
    "docstring": "Returns an end message with elapsed time"
  },
  {
    "code": "def iterator(plugins, context):\n    test = pyblish.logic.registered_test()\n    state = {\n        \"nextOrder\": None,\n        \"ordersWithError\": set()\n    }\n    for plugin in plugins:\n        state[\"nextOrder\"] = plugin.order\n        message = test(**state)\n        if message:\n            raise StopIteration(\"Stopped due to %s\" % message)\n        instances = pyblish.api.instances_by_plugin(context, plugin)\n        if plugin.__instanceEnabled__:\n            for instance in instances:\n                yield plugin, instance\n        else:\n            yield plugin, None",
    "docstring": "An iterator for plug-in and instance pairs"
  },
  {
    "code": "def expand_variable_dicts(\n    list_of_variable_dicts: 'List[Union[Dataset, OrderedDict]]',\n) -> 'List[Mapping[Any, Variable]]':\n    from .dataarray import DataArray\n    from .dataset import Dataset\n    var_dicts = []\n    for variables in list_of_variable_dicts:\n        if isinstance(variables, Dataset):\n            var_dicts.append(variables.variables)\n            continue\n        sanitized_vars = OrderedDict()\n        for name, var in variables.items():\n            if isinstance(var, DataArray):\n                coords = var._coords.copy()\n                coords.pop(name, None)\n                var_dicts.append(coords)\n            var = as_variable(var, name=name)\n            sanitized_vars[name] = var\n        var_dicts.append(sanitized_vars)\n    return var_dicts",
    "docstring": "Given a list of dicts with xarray object values, expand the values.\n\n    Parameters\n    ----------\n    list_of_variable_dicts : list of dict or Dataset objects\n        Each value for the mappings must be of the following types:\n        - an xarray.Variable\n        - a tuple `(dims, data[, attrs[, encoding]])` that can be converted in\n          an xarray.Variable\n        - or an xarray.DataArray\n\n    Returns\n    -------\n    A list of ordered dictionaries corresponding to inputs, or coordinates from\n    an input's values. The values of each ordered dictionary are all\n    xarray.Variable objects."
  },
  {
    "code": "def getFeedContent(self, feed, excludeRead=False, continuation=None, loadLimit=20, since=None, until=None):\n        return self._getFeedContent(feed.fetchUrl, excludeRead, continuation, loadLimit, since, until)",
    "docstring": "Return items for a particular feed"
  },
  {
    "code": "def _write_iodir(self, iodir=None):\n        if iodir is not None:\n            self.iodir = iodir\n        self.i2c.write_list(self.IODIR, self.iodir)",
    "docstring": "Write the specified byte value to the IODIR registor.  If no value\n        specified the current buffered value will be written."
  },
  {
    "code": "def logger_init(level):\n    levellist = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]\n    handler = logging.StreamHandler()\n    fmt = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '\n           '-35s %(lineno) -5d: %(message)s')\n    handler.setFormatter(logging.Formatter(fmt))\n    logger = logging.root\n    logger.addHandler(handler)\n    logger.setLevel(levellist[level])",
    "docstring": "Initialize the logger for this thread.\n\n    Sets the log level to ERROR (0), WARNING (1), INFO (2), or DEBUG (3),\n    depending on the argument `level`."
  },
  {
    "code": "def agent_service_deregister(consul_url=None, token=None, serviceid=None):\n    ret = {}\n    data = {}\n    if not consul_url:\n        consul_url = _get_config()\n        if not consul_url:\n            log.error('No Consul URL found.')\n            ret['message'] = 'No Consul URL found.'\n            ret['res'] = False\n            return ret\n    if not serviceid:\n        raise SaltInvocationError('Required argument \"serviceid\" is missing.')\n    function = 'agent/service/deregister/{0}'.format(serviceid)\n    res = _query(consul_url=consul_url,\n                 function=function,\n                 token=token,\n                 method='PUT',\n                 data=data)\n    if res['res']:\n        ret['res'] = True\n        ret['message'] = 'Service {0} removed from agent.'.format(serviceid)\n    else:\n        ret['res'] = False\n        ret['message'] = 'Unable to remove service {0}.'.format(serviceid)\n    return ret",
    "docstring": "Used to remove a service.\n\n    :param consul_url: The Consul server URL.\n    :param serviceid: A serviceid describing the service.\n    :return: Boolean and message indicating success or failure.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' consul.agent_service_deregister serviceid='redis'"
  },
  {
    "code": "def read_url(url):\n    logging.debug('reading {url} ...'.format(url=url))\n    token = os.environ.get(\"BOKEH_GITHUB_API_TOKEN\")\n    headers = {}\n    if token:\n        headers['Authorization'] = 'token %s' % token\n    request = Request(url, headers=headers)\n    response = urlopen(request).read()\n    return json.loads(response.decode(\"UTF-8\"))",
    "docstring": "Reads given URL as JSON and returns data as loaded python object."
  },
  {
    "code": "def apply_t0(self, hits):\n        if HAVE_NUMBA:\n            apply_t0_nb(\n                hits.time, hits.dom_id, hits.channel_id, self._lookup_tables\n            )\n        else:\n            n = len(hits)\n            cal = np.empty(n)\n            lookup = self._calib_by_dom_and_channel\n            for i in range(n):\n                calib = lookup[hits['dom_id'][i]][hits['channel_id'][i]]\n                cal[i] = calib[6]\n            hits.time += cal\n        return hits",
    "docstring": "Apply only t0s"
  },
  {
    "code": "def ping_directories_handler(sender, **kwargs):\n    entry = kwargs['instance']\n    if entry.is_visible and settings.SAVE_PING_DIRECTORIES:\n        for directory in settings.PING_DIRECTORIES:\n            DirectoryPinger(directory, [entry])",
    "docstring": "Ping directories when an entry is saved."
  },
  {
    "code": "def viable_source_types_for_generator (generator):\n    assert isinstance(generator, Generator)\n    if generator not in __viable_source_types_cache:\n        __vstg_cached_generators.append(generator)\n        __viable_source_types_cache[generator] = viable_source_types_for_generator_real (generator)\n    return __viable_source_types_cache[generator]",
    "docstring": "Caches the result of 'viable_source_types_for_generator'."
  },
  {
    "code": "def __PrintMessageCommentLines(self, message_type):\n        description = message_type.description or '%s message type.' % (\n            message_type.name)\n        width = self.__printer.CalculateWidth() - 3\n        for line in textwrap.wrap(description, width):\n            self.__printer('// %s', line)\n        PrintIndentedDescriptions(self.__printer, message_type.enum_types,\n                                  'Enums', prefix='// ')\n        PrintIndentedDescriptions(self.__printer, message_type.message_types,\n                                  'Messages', prefix='// ')\n        PrintIndentedDescriptions(self.__printer, message_type.fields,\n                                  'Fields', prefix='// ')",
    "docstring": "Print the description of this message."
  },
  {
    "code": "def script_post_save(model, os_path, contents_manager, **kwargs):\n    from nbconvert.exporters.script import ScriptExporter\n    if model['type'] != 'notebook':\n        return\n    global _script_exporter\n    if _script_exporter is None:\n        _script_exporter = ScriptExporter(parent=contents_manager)\n    log = contents_manager.log\n    base, ext = os.path.splitext(os_path)\n    script, resources = _script_exporter.from_filename(os_path)\n    script_fname = base + resources.get('output_extension', '.txt')\n    log.info(\"Saving script /%s\", to_api_path(script_fname, contents_manager.root_dir))\n    with io.open(script_fname, 'w', encoding='utf-8') as f:\n        f.write(script)",
    "docstring": "convert notebooks to Python script after save with nbconvert\n\n    replaces `ipython notebook --script`"
  },
  {
    "code": "def get_option(self, option):\n        value = getattr(self, option, None)\n        if value is not None:\n            return value\n        return getattr(settings, \"COUNTRIES_{0}\".format(option.upper()))",
    "docstring": "Get a configuration option, trying the options attribute first and\n        falling back to a Django project setting."
  },
  {
    "code": "def send_command_ack(self, device_id, action):\n        yield from self._ready_to_send.acquire()\n        acknowledgement = None\n        try:\n            self._command_ack.clear()\n            self.send_command(device_id, action)\n            log.debug('waiting for acknowledgement')\n            try:\n                yield from asyncio.wait_for(self._command_ack.wait(),\n                                            TIMEOUT.seconds, loop=self.loop)\n                log.debug('packet acknowledged')\n            except concurrent.futures._base.TimeoutError:\n                acknowledgement = {'ok': False, 'message': 'timeout'}\n                log.warning('acknowledge timeout')\n            else:\n                acknowledgement = self._last_ack.get('ok', False)\n        finally:\n            self._ready_to_send.release()\n        return acknowledgement",
    "docstring": "Send command, wait for gateway to repond with acknowledgment."
  },
  {
    "code": "def _get_sample(self, mode, encoding):\n        self._open_file(mode, encoding)\n        self._sample = self._file.read(UniversalCsvReader.sample_size)\n        self._file.close()",
    "docstring": "Get a sample from the next current input file.\n\n        :param str mode: The mode for opening the file.\n        :param str|None encoding: The encoding of the file. None for open the file in binary mode."
  },
  {
    "code": "def _get_obj_ct(self, obj):\n        if not hasattr(obj, '_wfct'):\n            if hasattr(obj, 'polymorphic_ctype'):\n                obj._wfct = obj.polymorphic_ctype\n            else:\n                obj._wfct = ContentType.objects.get_for_model(obj)\n        return obj._wfct",
    "docstring": "Look up and return object's content type and cache for reuse"
  },
  {
    "code": "def getLogger(cls, name=None):\n        return logging.getLogger(\"{0}.{1}\".format(cls.BASENAME, name) if name else cls.BASENAME)",
    "docstring": "Retrieves the Python native logger\n\n        :param name:    The name of the logger instance in the VSG namespace (VSG.<name>); a None value will use the VSG root.\n        :return:        The instacne of the Python logger object."
  },
  {
    "code": "def from_outcars_and_structures(cls, outcars, structures,\n                                    calc_ionic_from_zval=False):\n        p_elecs = []\n        p_ions = []\n        for i, o in enumerate(outcars):\n            p_elecs.append(o.p_elec)\n            if calc_ionic_from_zval:\n                p_ions.append(\n                    get_total_ionic_dipole(structures[i], o.zval_dict))\n            else:\n                p_ions.append(o.p_ion)\n        return cls(p_elecs, p_ions, structures)",
    "docstring": "Create Polarization object from list of Outcars and Structures in order\n        of nonpolar to polar.\n\n        Note, we recommend calculating the ionic dipole moment using calc_ionic\n        than using the values in Outcar (see module comments). To do this set\n        calc_ionic_from_zval = True"
  },
  {
    "code": "def exists_alias(self, alias_name, index_name=None):\n        return self._es_conn.indices.exists_alias(index=index_name, name=alias_name)",
    "docstring": "Check whether or not the given alias exists\n\n        :return: True if alias already exist"
  },
  {
    "code": "def Print(self):\n        for hypo, prob in sorted(self.Items()):\n            print(hypo, prob)",
    "docstring": "Prints the hypotheses and their probabilities."
  },
  {
    "code": "def get_image_path(image_lists, label_name, index, image_dir, category):\n  if label_name not in image_lists:\n    tf.logging.fatal('Label does not exist %s.', label_name)\n  label_lists = image_lists[label_name]\n  if category not in label_lists:\n    tf.logging.fatal('Category does not exist %s.', category)\n  category_list = label_lists[category]\n  if not category_list:\n    tf.logging.fatal('Label %s has no images in the category %s.',\n                     label_name, category)\n  mod_index = index % len(category_list)\n  base_name = category_list[mod_index]\n  sub_dir = label_lists['dir']\n  full_path = os.path.join(image_dir, sub_dir, base_name)\n  return full_path",
    "docstring": "Returns a path to an image for a label at the given index.\n\n  Args:\n    image_lists: OrderedDict of training images for each label.\n    label_name: Label string we want to get an image for.\n    index: Int offset of the image we want. This will be moduloed by the\n    available number of images for the label, so it can be arbitrarily large.\n    image_dir: Root folder string of the subfolders containing the training\n    images.\n    category: Name string of set to pull images from - training, testing, or\n    validation.\n\n  Returns:\n    File system path string to an image that meets the requested parameters."
  },
  {
    "code": "def report_onlysize(bytes_so_far, total_size, speed, eta):\n    percent = int(bytes_so_far * 100 / total_size)\n    current = approximate_size(bytes_so_far).center(10)\n    total = approximate_size(total_size).center(10)\n    sys.stdout.write('D: {0}% -{1}/{2}'.format(percent, current, total) + \"eta {0}\".format(eta))\n    sys.stdout.write(\"\\r\")\n    sys.stdout.flush()",
    "docstring": "This callback for the download function is used when console width\n    is not enough to print the bar.\n    It prints only the sizes"
  },
  {
    "code": "def log(self, timer_name, node):\n        timestamp = time.time()\n        if hasattr(self, timer_name):\n            getattr(self, timer_name).append({\n                \"node\":node,\n                \"time\":timestamp})\n        else:\n            setattr(self, timer_name, [{\"node\":node, \"time\":timestamp}])",
    "docstring": "logs a event in the timer"
  },
  {
    "code": "def __getFileObj(self, f):\r\n        if not f:\r\n            raise ShapefileException(\"No file-like object available.\")\r\n        elif hasattr(f, \"write\"):\r\n            return f\r\n        else:\r\n            pth = os.path.split(f)[0]\r\n            if pth and not os.path.exists(pth):\r\n                os.makedirs(pth)\r\n            return open(f, \"wb+\")",
    "docstring": "Safety handler to verify file-like objects"
  },
  {
    "code": "def custom_template_name(self):\n        base_path = getattr(settings, \"CUSTOM_SPECIAL_COVERAGE_PATH\", \"special_coverage/custom\")\n        if base_path is None:\n            base_path = \"\"\n        return \"{0}/{1}_custom.html\".format(\n            base_path, self.slug.replace(\"-\", \"_\")\n        ).lstrip(\"/\")",
    "docstring": "Returns the path for the custom special coverage template we want."
  },
  {
    "code": "def _update_show_toolbars_action(self):\r\n        if self.toolbars_visible:\r\n            text = _(\"Hide toolbars\")\r\n            tip = _(\"Hide toolbars\")\r\n        else:\r\n            text = _(\"Show toolbars\")\r\n            tip = _(\"Show toolbars\")\r\n        self.show_toolbars_action.setText(text)\r\n        self.show_toolbars_action.setToolTip(tip)",
    "docstring": "Update the text displayed in the menu entry."
  },
  {
    "code": "async def pulse(self):\n        get_state = GetState(pyvlx=self.pyvlx)\n        await get_state.do_api_call()\n        if not get_state.success:\n            raise PyVLXException(\"Unable to send get state.\")",
    "docstring": "Send get state request to API to keep the connection alive."
  },
  {
    "code": "def wrap(self, row: Union[Mapping[str, Any], Sequence[Any]]):\n        return (\n            self.dataclass(\n                **{\n                    ident: row[column_name]\n                    for ident, column_name in self.ids_and_column_names.items()\n                }\n            )\n            if isinstance(row, Mapping)\n            else self.dataclass(\n                **{ident: val for ident, val in zip(self.ids_and_column_names.keys(), row)}\n            )\n        )",
    "docstring": "Return row tuple for row."
  },
  {
    "code": "def get_version():\n    _globals = {}\n    _locals = {}\n    exec(\n        compile(\n            open(TOP + \"/manta/version.py\").read(), TOP + \"/manta/version.py\",\n            'exec'), _globals, _locals)\n    return _locals[\"__version__\"]",
    "docstring": "Get the python-manta version without having to import the manta package,\n    which requires deps to already be installed."
  },
  {
    "code": "def encode_hook(self, hook, msg):\n        if 'name' in hook:\n            msg.name = str_to_bytes(hook['name'])\n        else:\n            self.encode_modfun(hook, msg.modfun)\n        return msg",
    "docstring": "Encodes a commit hook dict into the protobuf message. Used in\n        bucket properties.\n\n        :param hook: the hook to encode\n        :type hook: dict\n        :param msg: the protobuf message to fill\n        :type msg: riak.pb.riak_pb2.RpbCommitHook\n        :rtype riak.pb.riak_pb2.RpbCommitHook"
  },
  {
    "code": "def _format_type_in_doc(self, namespace, data_type):\n        if is_void_type(data_type):\n            return 'None'\n        elif is_user_defined_type(data_type):\n            return ':class:`{}.{}.{}`'.format(\n                self.args.types_package, namespace.name, fmt_type(data_type))\n        else:\n            return fmt_type(data_type)",
    "docstring": "Returns a string that can be recognized by Sphinx as a type reference\n        in a docstring."
  },
  {
    "code": "def enum(cls, options, values):\n    names, real = zip(*options)\n    del names\n    def factory(i, name):\n      return cls(i, name, (len(real),), lambda a: real[a[0]], values)\n    return factory",
    "docstring": "Create an ArgumentType where you choose one of a set of known values."
  },
  {
    "code": "def inspect_filter_calculation(self):\n        try:\n            node = self.ctx.cif_filter\n            self.ctx.cif = node.outputs.cif\n        except exceptions.NotExistent:\n            self.report('aborting: CifFilterCalculation<{}> did not return the required cif output'.format(node.uuid))\n            return self.exit_codes.ERROR_CIF_FILTER_FAILED",
    "docstring": "Inspect the result of the CifFilterCalculation, verifying that it produced a CifData output node."
  },
  {
    "code": "def main():\n    logging.basicConfig()\n    logger.info(\"mmi-runner\")\n    warnings.warn(\n        \"You are using the mmi-runner script, please switch to `mmi runner`\",\n        DeprecationWarning\n    )\n    arguments = docopt.docopt(__doc__)\n    kwargs = parse_args(arguments)\n    runner = mmi.runner.Runner(\n        **kwargs\n    )\n    runner.run()",
    "docstring": "run mmi runner"
  },
  {
    "code": "def getVisibility(self):\n        try:\n            if self.map[GET_VISIBILITY_PROPERTY] == 'VISIBLE':\n                return VISIBLE\n            elif self.map[GET_VISIBILITY_PROPERTY] == 'INVISIBLE':\n                return INVISIBLE\n            elif self.map[GET_VISIBILITY_PROPERTY] == 'GONE':\n                return GONE\n            else:\n                return -2\n        except:\n            return -1",
    "docstring": "Gets the View visibility"
  },
  {
    "code": "def unbind(self, handler, argspec):\n        self.handlers[argspec.key].remove((handler, argspec))\n        if not len(self.handlers[argspec.key]):\n            del self.handlers[argspec.key]",
    "docstring": "handler will no longer be called if args match argspec\n\n        :param argspec: instance of ArgSpec - args to be matched"
  },
  {
    "code": "def listrecursive(path, ext=None):\n    filenames = set()\n    for root, dirs, files in os.walk(path):\n        if ext:\n            if ext == 'tif' or ext == 'tiff':\n                tmp = fnmatch.filter(files, '*.' + 'tiff')\n                files = tmp + fnmatch.filter(files, '*.' + 'tif')\n            else:\n                files = fnmatch.filter(files, '*.' + ext)\n        for filename in files:\n            filenames.add(os.path.join(root, filename))\n    filenames = list(filenames)\n    filenames.sort()\n    return sorted(filenames)",
    "docstring": "List files recurisvely"
  },
  {
    "code": "def get_fetcher_assets(self, dt):\n        if self._extra_source_df is None:\n            return []\n        day = normalize_date(dt)\n        if day in self._extra_source_df.index:\n            assets = self._extra_source_df.loc[day]['sid']\n        else:\n            return []\n        if isinstance(assets, pd.Series):\n            return [x for x in assets if isinstance(x, Asset)]\n        else:\n            return [assets] if isinstance(assets, Asset) else []",
    "docstring": "Returns a list of assets for the current date, as defined by the\n        fetcher data.\n\n        Returns\n        -------\n        list: a list of Asset objects."
  },
  {
    "code": "def is_job_done(job_id, conn=None):\n    result = False\n    get_done = RBJ.get_all(DONE, index=STATUS_FIELD)\n    for item in get_done.filter({ID_FIELD: job_id}).run(conn):\n        result = item\n    return result",
    "docstring": "is_job_done function checks to if Brain.Jobs Status is 'Done'\n\n    :param job_id: <str> id for the job\n    :param conn: (optional)<connection> to run on\n    :return: <dict> if job is done <false> if"
  },
  {
    "code": "def mnemonic(self, value):\n        if value not in REIL_MNEMONICS:\n            raise Exception(\"Invalid instruction mnemonic : %s\" % str(value))\n        self._mnemonic = value",
    "docstring": "Set instruction mnemonic."
  },
  {
    "code": "def pause(self):\n        self._mq.send(\"p\", True, type=1)\n        self._paused = True",
    "docstring": "Pause pulse capture"
  },
  {
    "code": "def apply_and_save(self):\n        patches = self.patches\n        content = None\n        with open(self.IN_PATH) as f_in:\n            content = f_in.read()\n        for key in self.replaced_word_dict:\n            content = content.replace(key, self.replaced_word_dict[key])\n        out_patches = []\n        for patch in patches:\n            pattern = re.compile(patch['src'], re.MULTILINE)\n            (content, subs_num) = re.subn(pattern, patch['dest'],\n                                          content)\n            if subs_num > 0:\n                patch['applied'] = True\n            out_patches.append(patch)\n        for patch in out_patches:\n            if patch.get('required') and not patch.get('applied'):\n                Log.warn('Patch not applied {0}'.format(patch['src']))\n        with open(self.OUT_PATH, 'w') as f_out:\n            f_out.write(content)\n        self.pathces = out_patches\n        content = None",
    "docstring": "Apply replaced words and patches, and save setup.py file."
  },
  {
    "code": "def sas_interconnect_types(self):\n        if not self.__sas_interconnect_types:\n            self.__sas_interconnect_types = SasInterconnectTypes(self.__connection)\n        return self.__sas_interconnect_types",
    "docstring": "Gets the SasInterconnectTypes API client.\n\n        Returns:\n            SasInterconnectTypes:"
  },
  {
    "code": "def pull_all_external(collector, **kwargs):\n    deps = set()\n    images = collector.configuration[\"images\"]\n    for layer in Builder().layered(images):\n        for image_name, image in layer:\n            for dep in image.commands.external_dependencies:\n                deps.add(dep)\n    for dep in sorted(deps):\n        kwargs[\"image\"] = dep\n        pull_arbitrary(collector, **kwargs)",
    "docstring": "Pull all the external dependencies of all the images"
  },
  {
    "code": "def shutdown(message=None, timeout=5, force_close=True, reboot=False,\n             in_seconds=False, only_on_pending_reboot=False):\n    if six.PY2:\n        message = _to_unicode(message)\n    timeout = _convert_minutes_seconds(timeout, in_seconds)\n    if only_on_pending_reboot and not get_pending_reboot():\n        return False\n    if message and not isinstance(message, six.string_types):\n        message = message.decode('utf-8')\n    try:\n        win32api.InitiateSystemShutdown('127.0.0.1', message, timeout,\n                                        force_close, reboot)\n        return True\n    except pywintypes.error as exc:\n        (number, context, message) = exc.args\n        log.error('Failed to shutdown the system')\n        log.error('nbr: %s', number)\n        log.error('ctx: %s', context)\n        log.error('msg: %s', message)\n        return False",
    "docstring": "Shutdown a running system.\n\n    Args:\n\n        message (str):\n            The message to display to the user before shutting down.\n\n        timeout (int):\n            The length of time (in seconds) that the shutdown dialog box should\n            be displayed. While this dialog box is displayed, the shutdown can\n            be aborted using the ``system.shutdown_abort`` function.\n\n            If timeout is not zero, InitiateSystemShutdown displays a dialog box\n            on the specified computer. The dialog box displays the name of the\n            user who called the function, the message specified by the lpMessage\n            parameter, and prompts the user to log off. The dialog box beeps\n            when it is created and remains on top of other windows (system\n            modal). The dialog box can be moved but not closed. A timer counts\n            down the remaining time before the shutdown occurs.\n\n            If timeout is zero, the computer shuts down immediately without\n            displaying the dialog box and cannot be stopped by\n            ``system.shutdown_abort``.\n\n            Default is 5 minutes\n\n        in_seconds (bool):\n            ``True`` will cause the ``timeout`` parameter to be in seconds.\n             ``False`` will be in minutes. Default is ``False``.\n\n            .. versionadded:: 2015.8.0\n\n        force_close (bool):\n            ``True`` will force close all open applications. ``False`` will\n            display a dialog box instructing the user to close open\n            applications. Default is ``True``.\n\n        reboot (bool):\n            ``True`` restarts the computer immediately after shutdown. ``False``\n            powers down the system. Default is ``False``.\n\n        only_on_pending_reboot (bool): If this is set to True, then the shutdown\n            will only proceed if the system reports a pending reboot. To\n            optionally shutdown in a highstate, consider using the shutdown\n            state instead of this module.\n\n        only_on_pending_reboot (bool):\n            If ``True`` the shutdown will only proceed if there is a reboot\n            pending. ``False`` will shutdown the system. Default is ``False``.\n\n    Returns:\n        bool:\n            ``True`` if successful (a shutdown or reboot will occur), otherwise\n            ``False``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' system.shutdown \"System will shutdown in 5 minutes\""
  },
  {
    "code": "def filter(self, local_name=None, name=None, ns_uri=None, node_type=None,\n            filter_fn=None, first_only=False):\n        if filter_fn is None:\n            def filter_fn(n):\n                if node_type is not None:\n                    if isinstance(node_type, int):\n                        if not n.is_type(node_type):\n                            return False\n                    elif n.__class__ != node_type:\n                        return False\n                if name is not None and n.name != name:\n                    return False\n                if local_name is not None and n.local_name != local_name:\n                    return False\n                if ns_uri is not None and n.ns_uri != ns_uri:\n                    return False\n                return True\n        nodelist = filter(filter_fn, self)\n        if first_only:\n            return nodelist[0] if nodelist else None\n        else:\n            return NodeList(nodelist)",
    "docstring": "Apply filters to the set of nodes in this list.\n\n        :param local_name: a local name used to filter the nodes.\n        :type local_name: string or None\n        :param name: a name used to filter the nodes.\n        :type name: string or None\n        :param ns_uri: a namespace URI used to filter the nodes.\n            If *None* all nodes are returned regardless of namespace.\n        :type ns_uri: string or None\n        :param node_type: a node type definition used to filter the nodes.\n        :type node_type: int node type constant, class, or None\n        :param filter_fn: an arbitrary function to filter nodes in this list.\n            This function must accept a single :class:`Node` argument and\n            return a bool indicating whether to include the node in the\n            filtered results.\n\n            .. note:: if ``filter_fn`` is provided all other filter arguments\n                are ignore.\n        :type filter_fn: function or None\n\n        :return: the type of the return value depends on the value of the\n            ``first_only`` parameter and how many nodes match the filter:\n\n            - if ``first_only=False`` return a :class:`NodeList` of filtered\n              nodes, which will be empty if there are no matching nodes.\n            - if ``first_only=True`` and at least one node matches,\n              return the first matching :class:`Node`\n            - if ``first_only=True`` and there are no matching nodes,\n              return *None*"
  },
  {
    "code": "def _modifyItemTag(self, item_id, action, tag):\n        return self.httpPost(ReaderUrl.EDIT_TAG_URL,\n                             {'i': item_id, action: tag, 'ac': 'edit-tags'})",
    "docstring": "wrapper around actual HTTP POST string for modify tags"
  },
  {
    "code": "def process(self, metric):\n        if not boto:\n            return\n        collector = str(metric.getCollectorPath())\n        metricname = str(metric.getMetricPath())\n        for rule in self.rules:\n            self.log.debug(\n                \"Comparing Collector: [%s] with (%s) \"\n                \"and Metric: [%s] with (%s)\",\n                str(rule['collector']),\n                collector,\n                str(rule['metric']),\n                metricname\n            )\n            if ((str(rule['collector']) == collector and\n                 str(rule['metric']) == metricname)):\n                if rule['collect_by_instance'] and self.instance_id:\n                    self.send_metrics_to_cloudwatch(\n                        rule,\n                        metric,\n                        {'InstanceId': self.instance_id})\n                if rule['collect_without_dimension']:\n                    self.send_metrics_to_cloudwatch(\n                        rule,\n                        metric,\n                        {})",
    "docstring": "Process a metric and send it to CloudWatch"
  },
  {
    "code": "def get_arrays_from_file(params_file, params=None):\n        try:\n            f = h5py.File(params_file, 'r')\n        except:\n            raise ValueError('File not found.')\n        if params is not None:\n            if not isinstance(params, list):\n                params = [params]\n            for p in params:\n                if p not in f.keys():\n                    raise ValueError('Parameter {} is not in {}'\n                                     .format(p, params_file))\n        else:\n            params = [str(k) for k in f.keys()]\n        params_values = {p:f[p][:] for p in params}\n        try:\n            bandwidth = f.attrs[\"bandwidth\"]\n        except KeyError:\n            bandwidth = \"scott\"\n        f.close()\n        return params_values, bandwidth",
    "docstring": "Reads the values of one or more parameters from an hdf file and\n        returns as a dictionary.\n\n        Parameters\n        ----------\n        params_file : str\n            The hdf file that contains the values of the parameters.\n        params : {None, list}\n            If provided, will just retrieve the given parameter names.\n\n        Returns\n        -------\n        dict\n            A dictionary of the parameters mapping `param_name -> array`."
  },
  {
    "code": "def get_file_listing_sha(listing_paths: Iterable) -> str:\n    return sha256(''.join(sorted(listing_paths)).encode('utf-8')).hexdigest()",
    "docstring": "Return sha256 string for group of FTP listings."
  },
  {
    "code": "def _shutdown_unlocked(self, context, lru=None, new_context=None):\n        LOG.info('%r._shutdown_unlocked(): shutting down %r', self, context)\n        context.shutdown()\n        via = self._via_by_context.get(context)\n        if via:\n            lru = self._lru_by_via.get(via)\n            if lru:\n                if context in lru:\n                    lru.remove(context)\n                if new_context:\n                    lru.append(new_context)\n        self._forget_context_unlocked(context)",
    "docstring": "Arrange for `context` to be shut down, and optionally add `new_context`\n        to the LRU list while holding the lock."
  },
  {
    "code": "def clear(self):\n        if os.path.exists(self.path):\n            os.remove(self.path)",
    "docstring": "Remove all existing done markers and the file used to store the dones."
  },
  {
    "code": "def create_appointment_group(self, appointment_group, **kwargs):\n        from canvasapi.appointment_group import AppointmentGroup\n        if (\n                isinstance(appointment_group, dict) and\n                'context_codes' in appointment_group and\n                'title' in appointment_group\n        ):\n            kwargs['appointment_group'] = appointment_group\n        elif (\n            isinstance(appointment_group, dict) and\n            'context_codes' not in appointment_group\n        ):\n            raise RequiredFieldMissing(\n                \"Dictionary with key 'context_codes' is missing.\"\n            )\n        elif isinstance(appointment_group, dict) and 'title' not in appointment_group:\n            raise RequiredFieldMissing(\"Dictionary with key 'title' is missing.\")\n        response = self.__requester.request(\n            'POST',\n            'appointment_groups',\n            _kwargs=combine_kwargs(**kwargs)\n        )\n        return AppointmentGroup(self.__requester, response.json())",
    "docstring": "Create a new Appointment Group.\n\n        :calls: `POST /api/v1/appointment_groups \\\n        <https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.create>`_\n\n        :param appointment_group: The attributes of the appointment group.\n        :type appointment_group: `dict`\n        :param title: The title of the appointment group.\n        :type title: `str`\n        :rtype: :class:`canvasapi.appointment_group.AppointmentGroup`"
  },
  {
    "code": "def claim_exp(self, data):\n        expiration = getattr(settings, 'OAUTH_ID_TOKEN_EXPIRATION', 30)\n        expires = self.now + timedelta(seconds=expiration)\n        return timegm(expires.utctimetuple())",
    "docstring": "Required expiration time."
  },
  {
    "code": "def request(self, method, params):\n        identifier = random.randint(1, 1000)\n        self._transport.write(jsonrpc_request(method, identifier, params))\n        self._buffer[identifier] = {'flag': asyncio.Event()}\n        yield from self._buffer[identifier]['flag'].wait()\n        result = self._buffer[identifier]['data']\n        del self._buffer[identifier]['data']\n        return result",
    "docstring": "Send a JSONRPC request."
  },
  {
    "code": "def update_ngram(self, ngram, count):\n        query = \"UPDATE _{0}_gram SET count = {1}\".format(len(ngram), count)\n        query += self._build_where_clause(ngram)\n        query += \";\"\n        self.execute_sql(query)",
    "docstring": "Updates a given ngram in the database. The ngram has to be in the\n        database, otherwise this method will stop with an error.\n\n        Parameters\n        ----------\n        ngram : iterable of str\n            A list, set or tuple of strings.\n        count : int\n            The count for the given n-gram."
  },
  {
    "code": "def _prepare_load_balancers(self):\n        stack = {\n                A.NAME: self[A.NAME],\n                A.VERSION: self[A.VERSION],\n                }\n        for load_balancer in self.get(R.LOAD_BALANCERS, []):\n            svars = {A.STACK: stack}\n            load_balancer[A.loadbalancer.VARS] = svars",
    "docstring": "Prepare load balancer variables"
  },
  {
    "code": "def build_message(self, stat, value):\n        return ' '.join((self.prefix + str(stat), str(value), str(round(time()))))",
    "docstring": "Build a metric in Graphite format."
  },
  {
    "code": "def get_multiplicon_seeds(self, redundant=False):\n        for node in self._multiplicon_graph.nodes():\n            if not len(self._multiplicon_graph.in_edges(node)):\n                if not self.is_redundant_multiplicon(node):\n                    yield node\n                elif redundant:\n                    yield node\n                else:\n                    continue\n            else:\n                continue",
    "docstring": "Return a generator of the IDs of multiplicons that are initial\n            seeding 'pairs' in level 2 multiplicons.\n\n            Arguments:\n\n            o redundant - if true, report redundant multiplicons"
  },
  {
    "code": "def _cls_fqn(self, cls):\n        ns = self._namespace_stack[-1]\n        if ns in ['__base__', None]:\n            return cls.__name__\n        else:\n            return ns + '.' + cls.__name__",
    "docstring": "Returns fully qualified name for the class based on current namespace\n        and the class name."
  },
  {
    "code": "def eval_constraints(self, constraints):\n        try:\n            return all(self.eval_ast(c) for c in constraints)\n        except errors.ClaripyZeroDivisionError:\n            return False",
    "docstring": "Returns whether the constraints is satisfied trivially by using the\n        last model."
  },
  {
    "code": "def random_subset_ids_by_count(self, count_per_class=1):\n        class_sizes = self.class_sizes\n        subsets = list()\n        if count_per_class < 1:\n            warnings.warn('Atleast one sample must be selected from each class')\n            return list()\n        elif count_per_class >= self.num_samples:\n            warnings.warn('All samples requested - returning a copy!')\n            return self.keys\n        for class_id, class_size in class_sizes.items():\n            this_class = self.keys_with_value(self.classes, class_id)\n            random.shuffle(this_class)\n            subset_size_this_class = max(0, min(class_size, count_per_class))\n            if subset_size_this_class < 1 or this_class is None:\n                warnings.warn('No subjects from class {} were selected.'.format(class_id))\n            else:\n                subsets_this_class = this_class[0:count_per_class]\n                subsets.extend(subsets_this_class)\n        if len(subsets) > 0:\n            return subsets\n        else:\n            warnings.warn('Zero samples were selected. Returning an empty list!')\n            return list()",
    "docstring": "Returns a random subset of sample ids of specified size by count,\n            within each class.\n\n        Parameters\n        ----------\n        count_per_class : int\n            Exact number of samples per each class.\n\n        Returns\n        -------\n        subset : list\n            Combined list of sample ids from all classes."
  },
  {
    "code": "def score(self, env=None, score_out=None):\n        messages = {}\n        self.assignment.set_args(\n            score=True,\n            score_out=score_out,\n        )\n        if env is None:\n            import __main__\n            env = __main__.__dict__\n        self.run('scoring', messages, env=env)\n        return messages['scoring']",
    "docstring": "Run the scoring protocol.\n\n        score_out -- str; a file name to write the point breakdown\n                     into.\n\n        Returns: dict; maps score tag (str) -> points (float)"
  },
  {
    "code": "def interconnect_all(self):\n        for dep in topologically_sorted(self._provides):\n            if hasattr(dep, '__injections__') and not hasattr(dep, '__injections_source__'):\n                self.inject(dep)",
    "docstring": "Propagate dependencies for provided instances"
  },
  {
    "code": "def _update_task(self, task):\n        self.task = task\n        self.task.data.update(self.task_data)\n        self.task_type = task.task_spec.__class__.__name__\n        self.spec = task.task_spec\n        self.task_name = task.get_name()\n        self.activity = getattr(self.spec, 'service_class', '')\n        self._set_lane_data()",
    "docstring": "Assigns current task step to self.task\n        then updates the task's data with self.task_data\n\n        Args:\n            task: Task object."
  },
  {
    "code": "def add_how(voevent, descriptions=None, references=None):\n    if not voevent.xpath('How'):\n        etree.SubElement(voevent, 'How')\n    if descriptions is not None:\n        for desc in _listify(descriptions):\n            etree.SubElement(voevent.How, 'Description')\n            voevent.How.Description[-1] = desc\n    if references is not None:\n        voevent.How.extend(_listify(references))",
    "docstring": "Add descriptions or references to the How section.\n\n    Args:\n        voevent(:class:`Voevent`): Root node of a VOEvent etree.\n        descriptions(str): Description string, or list of description\n            strings.\n        references(:py:class:`voeventparse.misc.Reference`): A reference element\n            (or list thereof)."
  },
  {
    "code": "def move_into(self, destination_folder):\n        headers = self.headers\n        endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id + '/move'\n        payload = '{ \"DestinationId\": \"' + destination_folder.id + '\"}'\n        r = requests.post(endpoint, headers=headers, data=payload)\n        if check_response(r):\n            return_folder = r.json()\n            return self._json_to_folder(self.account, return_folder)",
    "docstring": "Move the Folder into a different folder.\n\n        This makes the Folder provided a child folder of the destination_folder.\n\n        Raises:\n            AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token.\n\n        Args:\n            destination_folder: A :class:`Folder <pyOutlook.core.folder.Folder>` that should become the parent\n\n        Returns:\n            A new :class:`Folder <pyOutlook.core.folder.Folder>` that is now\n            inside of the destination_folder."
  },
  {
    "code": "def init_app(self, app):\n        host = app.config.get('STATS_HOSTNAME', 'localhost')\n        port = app.config.get('STATS_PORT', 8125)\n        base_key = app.config.get('STATS_BASE_KEY', app.name)\n        client = _StatsClient(\n            host=host,\n            port=port,\n            prefix=base_key,\n        )\n        app.before_request(client.flask_time_start)\n        app.after_request(client.flask_time_end)\n        if not hasattr(app, 'extensions'):\n            app.extensions = {}\n        app.extensions.setdefault('stats', {})\n        app.extensions['stats'][self] = client\n        return client",
    "docstring": "Inititialise the extension with the app object.\n\n        :param app: Your application object"
  },
  {
    "code": "def defaultSystem():\n    rsystem = platform.system()\n    if rsystem in os_canon:\n        rsystem = os_canon[rsystem][0]\n    return rsystem",
    "docstring": "Return the canonicalized system name."
  },
  {
    "code": "def __parse(self) -> object:\n        char = self.data[self.idx: self.idx + 1]\n        if char in [b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'0']:\n            str_len = int(self.__read_to(b':'))\n            return self.__read(str_len)\n        elif char == b'i':\n            self.idx += 1\n            return int(self.__read_to(b'e'))\n        elif char == b'd':\n            return self.__parse_dict()\n        elif char == b'l':\n            return self.__parse_list()\n        elif char == b'':\n            raise bencodepy.DecodingError('Unexpected End of File at index position of {0}.'.format(str(self.idx)))\n        else:\n            raise bencodepy.DecodingError(\n                'Invalid token character ({0}) at position {1}.'.format(str(char), str(self.idx)))",
    "docstring": "Selects the appropriate method to decode next bencode element and returns the result."
  },
  {
    "code": "def restore_row(self, row, schema):\n        row = list(row)\n        for index, field in enumerate(schema.fields):\n            if self.__dialect == 'postgresql':\n                if field.type in ['array', 'object']:\n                    continue\n            row[index] = field.cast_value(row[index])\n        return row",
    "docstring": "Restore row from SQL"
  },
  {
    "code": "def get_transactions(self, include_investment=False):\n        assert_pd()\n        s = StringIO(self.get_transactions_csv(\n            include_investment=include_investment))\n        s.seek(0)\n        df = pd.read_csv(s, parse_dates=['Date'])\n        df.columns = [c.lower().replace(' ', '_') for c in df.columns]\n        df.category = (df.category.str.lower()\n                       .replace('uncategorized', pd.np.nan))\n        return df",
    "docstring": "Returns the transaction data as a Pandas DataFrame."
  },
  {
    "code": "def change_nick(self, nick):\n        old_nick = self.nick\n        self.nick = IRCstr(nick)\n        for c in self.channels:\n            c.users.remove(old_nick)\n            c.users.add(self.nick)",
    "docstring": "Update this user's nick in all joined channels."
  },
  {
    "code": "def setup_ssh_tunnel(job_id, local_port, remote_port):\n    cmd = ['dx', 'ssh', '--suppress-running-check', job_id, '-o', 'StrictHostKeyChecking no']\n    cmd += ['-f', '-L', '{0}:localhost:{1}'.format(local_port, remote_port), '-N']\n    subprocess.check_call(cmd)",
    "docstring": "Setup an ssh tunnel to the given job-id.  This will establish\n    the port over the given local_port to the given remote_port\n    and then exit, keeping the tunnel in place until the job is\n    terminated."
  },
  {
    "code": "def save(self):\n        if self.rater is not None:\n            self.rater.set('modified', datetime.now().isoformat())\n        xml = parseString(tostring(self.root))\n        with open(self.xml_file, 'w') as f:\n            f.write(xml.toxml())",
    "docstring": "Save xml to file."
  },
  {
    "code": "def delete(self, monitor_id):\n        if not self._state:\n            raise InvalidState(\"State was not properly obtained from the app\")\n        monitors = self.list()\n        bit = None\n        for monitor in monitors:\n            if monitor_id != monitor['monitor_id']:\n                continue\n            bit = monitor['monitor_id']\n        if not bit:\n            raise MonitorNotFound(\"No monitor was found with that term.\")\n        url = self.ALERTS_DELETE_URL.format(requestX=self._state[3])\n        self._log.debug(\"Deleting alert using: %s\" % url)\n        payload = [None, monitor_id]\n        params = json.dumps(payload, separators=(',', ':'))\n        data = {'params': params}\n        response = self._session.post(url, data=data, headers=self.HEADERS)\n        if response.status_code != 200:\n            raise ActionError(\"Failed to delete by ID: %s\"\n                              % response.content)\n        return True",
    "docstring": "Delete a monitor by ID."
  },
  {
    "code": "def undo(self):\n        _, _, undo_state = self._undo_stack.back()\n        spike_clusters_new = self._spike_clusters_base.copy()\n        for spike_ids, cluster_ids, _ in self._undo_stack:\n            if spike_ids is not None:\n                spike_clusters_new[spike_ids] = cluster_ids\n        changed = np.nonzero(self._spike_clusters !=\n                             spike_clusters_new)[0]\n        clusters_changed = spike_clusters_new[changed]\n        up = self._do_assign(changed, clusters_changed)\n        up.history = 'undo'\n        up.undo_state = undo_state\n        self.emit('cluster', up)\n        return up",
    "docstring": "Undo the last cluster assignment operation.\n\n        Returns\n        -------\n\n        up : UpdateInfo instance of the changes done by this operation."
  },
  {
    "code": "def get_all_chats(self):\n        chats = self.wapi_functions.getAllChats()\n        if chats:\n            return [factory_chat(chat, self) for chat in chats]\n        else:\n            return []",
    "docstring": "Fetches all chats\n\n        :return: List of chats\n        :rtype: list[Chat]"
  },
  {
    "code": "def get_all_longest_col_lengths(self):\n        response = {}\n        for col in self.col_list:\n            response[col] = self._longest_val_in_column(col)\n        return response",
    "docstring": "iterate over all columns and get their longest values\n\n        :return: dict, {\"column_name\": 132}"
  },
  {
    "code": "def profile(fun, *args, **kwargs):\n    timer_name = kwargs.pop(\"prof_name\", None)\n    if not timer_name:\n        module = inspect.getmodule(fun)\n        c = [module.__name__]\n        parentclass = labtypes.get_class_that_defined_method(fun)\n        if parentclass:\n            c.append(parentclass.__name__)\n        c.append(fun.__name__)\n        timer_name = \".\".join(c)\n    start(timer_name)\n    ret = fun(*args, **kwargs)\n    stop(timer_name)\n    return ret",
    "docstring": "Profile a function."
  },
  {
    "code": "def list_of(validate_item):\n    def validate(value, should_raise=True):\n        validate_type = is_type(list)\n        if not validate_type(value, should_raise=should_raise):\n            return False\n        for item in value:\n            try:\n                validate_item(item)\n            except TypeError as e:\n                if should_raise:\n                    samtranslator.model.exceptions.prepend(e, \"list contained an invalid item\")\n                    raise\n                return False\n        return True\n    return validate",
    "docstring": "Returns a validator function that succeeds only if the input is a list, and each item in the list passes as input\n    to the provided validator validate_item.\n\n    :param callable validate_item: the validator function for items in the list\n    :returns: a function which returns True its input is an list of valid items, and raises TypeError otherwise\n    :rtype: callable"
  },
  {
    "code": "def set_of(*generators):\n    class SetOfGenerators(ArbitraryInterface):\n        @classmethod\n        def arbitrary(cls):\n            arbitrary_set = set()\n            for generator in generators:\n                arbitrary_set |= {\n                    arbitrary(generator)\n                    for _ in range(arbitrary(int) % 100)\n                }\n            return arbitrary_set\n    SetOfGenerators.__name__ = ''.join([\n        'set_of(', ', '.join(generator.__name__ for generator in generators),\n        ')'\n    ])\n    return SetOfGenerators",
    "docstring": "Generates a set consisting solely of the specified generators.\n    This is a class factory, it makes a class which is a closure around the\n    specified generators."
  },
  {
    "code": "def deepSetAttr(obj, path, val):\n    first, _, rest = path.rpartition('.')\n    return setattr(deepGetAttr(obj, first) if first else obj, rest, val)",
    "docstring": "Sets a deep attribute on an object by resolving a dot-delimited\n    path. If path does not exist an `AttributeError` will be raised`."
  },
  {
    "code": "def periodogram_auto(self, oversampling=5, nyquist_factor=3,\n                         return_periods=True):\n        N = len(self.t)\n        T = np.max(self.t) - np.min(self.t)\n        df = 1. / T / oversampling\n        f0 = df\n        Nf = int(0.5 * oversampling * nyquist_factor * N)\n        freq = f0 + df * np.arange(Nf)\n        return 1. / freq, self._score_frequency_grid(f0, df, Nf)",
    "docstring": "Compute the periodogram on an automatically-determined grid\n\n        This function uses heuristic arguments to choose a suitable frequency\n        grid for the data. Note that depending on the data window function,\n        the model may be sensitive to periodicity at higher frequencies than\n        this function returns!\n\n        The final number of frequencies will be\n        Nf = oversampling * nyquist_factor * len(t) / 2\n\n        Parameters\n        ----------\n        oversampling : float\n            the number of samples per approximate peak width\n        nyquist_factor : float\n            the highest frequency, in units of the nyquist frequency for points\n            spread uniformly through the data range.\n\n        Returns\n        -------\n        period : ndarray\n            the grid of periods\n        power : ndarray\n            the power at each frequency"
  },
  {
    "code": "def is_discrete(self):\n        return self.bounds[1] == self.bounds[0] and\\\n               self.included == (True,True)",
    "docstring": "Check whether this interval contains exactly one number\n\n        :rtype: bool"
  },
  {
    "code": "def to_df(self, method: str = 'MEMORY', **kwargs) -> 'pd.DataFrame':\n        ll = self._is_valid()\n        if ll:\n            print(ll['LOG'])\n            return None\n        else:\n            return self.sas.sasdata2dataframe(self.table, self.libref, self.dsopts, method, **kwargs)",
    "docstring": "Export this SAS Data Set to a Pandas Data Frame\n\n        :param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data\n        :param kwargs:\n        :return: Pandas data frame"
  },
  {
    "code": "def start_all_linking(self, link_type, group_id):\n        self.logger.info(\"start_all_linking for type %s group %s\",\n                         link_type, group_id)\n        self.direct_command_hub('0264' + link_type + group_id)",
    "docstring": "Begin all linking"
  },
  {
    "code": "def entity_list(args):\n    r = fapi.get_entities_with_type(args.project, args.workspace)\n    fapi._check_response_code(r, 200)\n    return [ '{0}\\t{1}'.format(e['entityType'], e['name']) for e in r.json() ]",
    "docstring": "List entities in a workspace."
  },
  {
    "code": "def all_equal(keys, axis=semantics.axis_default):\n    index = as_index(keys, axis)\n    return index.groups == 1",
    "docstring": "returns true of all keys are equal"
  },
  {
    "code": "def draw(self):\n        nodes_pos = {}\n        for node in self.graph.nodes():\n            nodes_pos[node] = (node.geom.x, node.geom.y)\n        plt.figure()\n        nx.draw_networkx(self.graph, nodes_pos, node_size=16, font_size=8)\n        plt.show()",
    "docstring": "Draw MV grid's graph using the geo data of nodes\n\n        Notes\n        -----\n        This method uses the coordinates stored in the nodes' geoms which\n        are usually conformal, not equidistant. Therefore, the plot might\n        be distorted and does not (fully) reflect the real positions or\n        distances between nodes."
  },
  {
    "code": "def convert_string(string):\n    if is_int(string):\n        return int(string)\n    elif is_float(string):\n        return float(string)\n    elif convert_bool(string)[0]:\n        return convert_bool(string)[1]\n    elif string == 'None':\n        return None\n    else:\n        return string",
    "docstring": "Convert string to int, float or bool."
  },
  {
    "code": "def toml(uncertainty):\n    text = uncertainty.text.strip()\n    if not text.startswith('['):\n        text = '[%s]' % text\n    for k, v in uncertainty.attrib.items():\n        try:\n            v = ast.literal_eval(v)\n        except ValueError:\n            v = repr(v)\n        text += '\\n%s = %s' % (k, v)\n    return text",
    "docstring": "Converts an uncertainty node into a TOML string"
  },
  {
    "code": "def start(self, children):\n        composites = []\n        for composite_dict in children:\n            if False and self.include_position:\n                key_token = composite_dict[1]\n                key_name = key_token.value.lower()\n                composites_position = self.get_position_dict(composite_dict)\n                composites_position[key_name] = self.create_position_dict(key_token, None)\n            composites.append(composite_dict)\n        if len(composites) == 1:\n            return composites[0]\n        else:\n            return composites",
    "docstring": "Parses a MapServer Mapfile\n        Parsing of partial Mapfiles or lists of composites is also possible"
  },
  {
    "code": "def from_wif(cls, wif, network=BitcoinMainNet):\n        wif = ensure_str(wif)\n        try:\n            extended_key_bytes = base58.b58decode_check(wif)\n        except ValueError as e:\n            raise ChecksumException(e)\n        network_bytes = extended_key_bytes[0]\n        if not isinstance(network_bytes, six.integer_types):\n            network_bytes = ord(network_bytes)\n        if (network_bytes != network.SECRET_KEY):\n            raise incompatible_network_exception_factory(\n                network_name=network.NAME,\n                expected_prefix=network.SECRET_KEY,\n                given_prefix=network_bytes)\n        extended_key_bytes = extended_key_bytes[1:]\n        compressed = False\n        if len(extended_key_bytes) == 33:\n            extended_key_bytes = extended_key_bytes[:-1]\n            compressed = True\n        return cls(long_or_int(hexlify(extended_key_bytes), 16), network,\n                   compressed=compressed)",
    "docstring": "Import a key in WIF format.\n\n        WIF is Wallet Import Format. It is a base58 encoded checksummed key.\n        See https://en.bitcoin.it/wiki/Wallet_import_format for a full\n        description.\n\n        This supports compressed WIFs - see this for an explanation:\n        http://bitcoin.stackexchange.com/questions/7299/when-importing-private-keys-will-compressed-or-uncompressed-format-be-used  # nopep8\n        (specifically http://bitcoin.stackexchange.com/a/7958)"
  },
  {
    "code": "def rate_limits(self):\n        if not self._rate_limits:\n            self._rate_limits = utilities.get_rate_limits(self.response)\n        return self._rate_limits",
    "docstring": "Returns a list of rate limit details."
  },
  {
    "code": "def _merge_any_two_boxes(self, box_list):\n        n = len(box_list)\n        for i in range(n):\n            for j in range(i + 1, n):\n                if self._are_nearby_parallel_boxes(box_list[i], box_list[j]):\n                    a, b = box_list[i], box_list[j]\n                    merged_points = np.vstack([a.points, b.points])\n                    merged_box = RotatedBox.from_points(merged_points, self.box_type)\n                    if merged_box.width / merged_box.height >= self.min_box_aspect:\n                        box_list.remove(a)\n                        box_list.remove(b)\n                        box_list.append(merged_box)\n                        return True\n        return False",
    "docstring": "Given a list of boxes, finds two nearby parallel ones and merges them. Returns false if none found."
  },
  {
    "code": "def write_text(filename, data, add=False):\n    write_type = 'a' if add else 'w'\n    with open(filename, write_type) as file:\n        print(data, end='', file=file)",
    "docstring": "Write image data to text file\n\n    :param filename: name of text file to write data to\n    :type filename: str\n    :param data: image data to write to text file\n    :type data: numpy array\n    :param add: whether to append to existing file or not. Default is ``False``\n    :type add: bool"
  },
  {
    "code": "def flat_list_to_polymer(atom_list, atom_group_s=4):\n    atom_labels = ['N', 'CA', 'C', 'O', 'CB']\n    atom_elements = ['N', 'C', 'C', 'O', 'C']\n    atoms_coords = [atom_list[x:x + atom_group_s]\n                    for x in range(0, len(atom_list), atom_group_s)]\n    atoms = [[Atom(x[0], x[1]) for x in zip(y, atom_elements)]\n             for y in atoms_coords]\n    if atom_group_s == 5:\n        monomers = [Residue(OrderedDict(zip(atom_labels, x)), 'ALA')\n                    for x in atoms]\n    elif atom_group_s == 4:\n        monomers = [Residue(OrderedDict(zip(atom_labels, x)), 'GLY')\n                    for x in atoms]\n    else:\n        raise ValueError(\n            'Parameter atom_group_s must be 4 or 5 so atoms can be labeled correctly.')\n    polymer = Polypeptide(monomers=monomers)\n    return polymer",
    "docstring": "Takes a flat list of atomic coordinates and converts it to a `Polymer`.\n\n    Parameters\n    ----------\n    atom_list : [Atom]\n        Flat list of coordinates.\n    atom_group_s : int, optional\n        Size of atom groups.\n\n    Returns\n    -------\n    polymer : Polypeptide\n        `Polymer` object containing atom coords converted `Monomers`.\n\n    Raises\n    ------\n    ValueError\n        Raised if `atom_group_s` != 4 or 5"
  },
  {
    "code": "def install(self, io_handler, module_name):\n        bundle = self._context.install_bundle(module_name)\n        io_handler.write_line(\"Bundle ID: {0}\", bundle.get_bundle_id())\n        return bundle.get_bundle_id()",
    "docstring": "Installs the bundle with the given module name"
  },
  {
    "code": "def get_task_progress(self, task_name):\n        params = {'instanceprogress': task_name, 'taskname': task_name}\n        resp = self._client.get(self.resource(), params=params)\n        return Instance.Task.TaskProgress.parse(self._client, resp)",
    "docstring": "Get task's current progress\n\n        :param task_name: task_name\n        :return: the task's progress\n        :rtype: :class:`odps.models.Instance.Task.TaskProgress`"
  },
  {
    "code": "def export(self, out_filename):\n        with zipfile.ZipFile(out_filename, 'w', zipfile.ZIP_DEFLATED) as arc:\n            id_list = list(self.get_thread_info())\n            for num, my_info in enumerate(id_list):\n                logging.info('Working on item %i : %s', num, my_info['number'])\n                my_thread = GitHubCommentThread(\n                    self.gh_info.owner, self.gh_info.realm, my_info['title'],\n                    self.gh_info.user, self.gh_info.token,\n                    thread_id=my_info['number'])\n                csec = my_thread.get_comment_section()\n                cdict = [item.to_dict() for item in csec.comments]\n                my_json = json.dumps(cdict)\n                arc.writestr('%i__%s' % (my_info['number'], my_info['title']),\n                             my_json)",
    "docstring": "Export desired threads as a zipfile to out_filename."
  },
  {
    "code": "def Read(f):\n  try:\n    yaml_data = yaml.load(f)\n  except yaml.YAMLError as e:\n    raise ParseError('%s' % e)\n  except IOError as e:\n    raise YAMLLoadError('%s' % e)\n  _CheckData(yaml_data)\n  try:\n    return Config(\n        yaml_data.get('blacklist', ()),\n        yaml_data.get('whitelist', ('*')))\n  except UnicodeDecodeError as e:\n    raise YAMLLoadError('%s' % e)",
    "docstring": "Reads and returns Config data from a yaml file.\n\n  Args:\n    f: Yaml file to parse.\n\n  Returns:\n    Config object as defined in this file.\n\n  Raises:\n    Error (some subclass): If there is a problem loading or parsing the file."
  },
  {
    "code": "def combine_with(self, rgbd_im):\n        new_data = self.data.copy()\n        depth_data = self.depth.data\n        other_depth_data = rgbd_im.depth.data\n        depth_zero_px = self.depth.zero_pixels()\n        depth_replace_px = np.where(\n            (other_depth_data != 0) & (\n                other_depth_data < depth_data))\n        depth_replace_px = np.c_[depth_replace_px[0], depth_replace_px[1]]\n        new_data[depth_zero_px[:, 0], depth_zero_px[:, 1],\n                 :] = rgbd_im.data[depth_zero_px[:, 0], depth_zero_px[:, 1], :]\n        new_data[depth_replace_px[:, 0], depth_replace_px[:, 1],\n                 :] = rgbd_im.data[depth_replace_px[:, 0], depth_replace_px[:, 1], :]\n        return RgbdImage(new_data, frame=self.frame)",
    "docstring": "Replaces all zeros in the source rgbd image with the values of a different rgbd image\n\n        Parameters\n        ----------\n        rgbd_im : :obj:`RgbdImage`\n            rgbd image to combine with\n\n        Returns\n        -------\n        :obj:`RgbdImage`\n            the combined rgbd image"
  },
  {
    "code": "def flush(self):\n        if self.shutdown:\n            return\n        self.flush_buffers(force=True)\n        self.queue.put(FLUSH_MARKER)\n        self.queue.join()",
    "docstring": "Ensure all logging output has been flushed."
  },
  {
    "code": "def _mpl_to_vispy(fig):\n    renderer = VispyRenderer()\n    exporter = Exporter(renderer)\n    with warnings.catch_warnings(record=True):\n        exporter.run(fig)\n    renderer._vispy_done()\n    return renderer.canvas",
    "docstring": "Convert a given matplotlib figure to vispy\n\n    This function is experimental and subject to change!\n    Requires matplotlib and mplexporter.\n\n    Parameters\n    ----------\n    fig : instance of matplotlib Figure\n        The populated figure to display.\n\n    Returns\n    -------\n    canvas : instance of Canvas\n        The resulting vispy Canvas."
  },
  {
    "code": "def _guess_record(self, rtype, name=None, content=None):\n        records = self._list_records_internal(\n            identifier=None, rtype=rtype, name=name, content=content)\n        if len(records) == 1:\n            return records[0]\n        if len(records) > 1:\n            raise Exception(\n                'Identifier was not provided and several existing '\n                'records match the request for {0}/{1}'.format(rtype, name))\n        raise Exception(\n            'Identifier was not provided and no existing records match '\n            'the request for {0}/{1}'.format(rtype, name))",
    "docstring": "Tries to find existing unique record by type, name and content"
  },
  {
    "code": "def create_for_block(\n            cls, i=None, name=None, cname=None, version=None, **kwargs):\n        if cname is None:\n            cname = name or 'values_block_{idx}'.format(idx=i)\n        if name is None:\n            name = cname\n        try:\n            if version[0] == 0 and version[1] <= 10 and version[2] == 0:\n                m = re.search(r\"values_block_(\\d+)\", name)\n                if m:\n                    name = \"values_{group}\".format(group=m.groups()[0])\n        except IndexError:\n            pass\n        return cls(name=name, cname=cname, **kwargs)",
    "docstring": "return a new datacol with the block i"
  },
  {
    "code": "def get_crash_signature(error_line):\n    search_term = None\n    match = CRASH_RE.match(error_line)\n    if match and is_helpful_search_term(match.group(1)):\n        search_term = match.group(1)\n    return search_term",
    "docstring": "Try to get a crash signature from the given error_line string."
  },
  {
    "code": "def field_value(self, value):\n        if not self.is_array:\n            return self.field_type(value)\n        if isinstance(value, (list, tuple, set)):\n            return [self.field_type(item) for item in value]\n        return self.field_type(value)",
    "docstring": "Validate against NodeType."
  },
  {
    "code": "def _get_kernel_data(self, nmr_samples, thinning, return_output):\n        kernel_data = {\n            'data': self._data,\n            'method_data': self._get_mcmc_method_kernel_data(),\n            'nmr_iterations': Scalar(nmr_samples * thinning, ctype='ulong'),\n            'iteration_offset': Scalar(self._sampling_index, ctype='ulong'),\n            'rng_state': Array(self._rng_state, 'uint', mode='rw', ensure_zero_copy=True),\n            'current_chain_position': Array(self._current_chain_position, 'mot_float_type',\n                                            mode='rw', ensure_zero_copy=True),\n            'current_log_likelihood': Array(self._current_log_likelihood, 'mot_float_type',\n                                            mode='rw', ensure_zero_copy=True),\n            'current_log_prior': Array(self._current_log_prior, 'mot_float_type',\n                                       mode='rw', ensure_zero_copy=True),\n        }\n        if return_output:\n            kernel_data.update({\n                'samples': Zeros((self._nmr_problems, self._nmr_params, nmr_samples), ctype='mot_float_type'),\n                'log_likelihoods': Zeros((self._nmr_problems, nmr_samples), ctype='mot_float_type'),\n                'log_priors': Zeros((self._nmr_problems, nmr_samples), ctype='mot_float_type'),\n            })\n        return kernel_data",
    "docstring": "Get the kernel data we will input to the MCMC sampler.\n\n        This sets the items:\n\n        * data: the pointer to the user provided data\n        * method_data: the data specific to the MCMC method\n        * nmr_iterations: the number of iterations to sample\n        * iteration_offset: the current sample index, that is, the offset to the given number of iterations\n        * rng_state: the random number generator state\n        * current_chain_position: the current position of the sampled chain\n        * current_log_likelihood: the log likelihood of the current position on the chain\n        * current_log_prior: the log prior of the current position on the chain\n\n        Additionally, if ``return_output`` is True, we add to that the arrays:\n\n        * samples: for the samples\n        * log_likelihoods: for storing the log likelihoods\n        * log_priors: for storing the priors\n\n        Args:\n            nmr_samples (int): the number of samples we will draw\n            thinning (int): the thinning factor we want to use\n            return_output (boolean): if the kernel should return output\n\n        Returns:\n            dict[str: mot.lib.utils.KernelData]: the kernel input data"
  },
  {
    "code": "def on_attribute(self, node):\n        ctx = node.ctx.__class__\n        if ctx == ast.Store:\n            msg = \"attribute for storage: shouldn't be here!\"\n            self.raise_exception(node, exc=RuntimeError, msg=msg)\n        sym = self.run(node.value)\n        if ctx == ast.Del:\n            return delattr(sym, node.attr)\n        fmt = \"cannnot access attribute '%s' for %s\"\n        if node.attr not in UNSAFE_ATTRS:\n            fmt = \"no attribute '%s' for %s\"\n            try:\n                return getattr(sym, node.attr)\n            except AttributeError:\n                pass\n        obj = self.run(node.value)\n        msg = fmt % (node.attr, obj)\n        self.raise_exception(node, exc=AttributeError, msg=msg)",
    "docstring": "Extract attribute."
  },
  {
    "code": "def _auto_commit(self, by_count=False):\n        if (self._stopping or self._shuttingdown or (not self._start_d) or\n                (self._last_processed_offset is None) or\n                (not self.consumer_group) or\n                (by_count and not self.auto_commit_every_n)):\n            return\n        if (not by_count or self._last_committed_offset is None or\n            (self._last_processed_offset - self._last_committed_offset\n             ) >= self.auto_commit_every_n):\n            if not self._commit_ds:\n                commit_d = self.commit()\n                commit_d.addErrback(self._handle_auto_commit_error)\n            else:\n                d = Deferred()\n                d.addCallback(self._retry_auto_commit, by_count)\n                self._commit_ds.append(d)",
    "docstring": "Check if we should start a new commit operation and commit"
  },
  {
    "code": "def config(config_dict: typing.Mapping) -> Config:\n    logger.debug(f\"Updating with {config_dict}\")\n    _cfg.update(config_dict)\n    return _cfg",
    "docstring": "Configures the konch shell. This function should be called in a\n    .konchrc file.\n\n    :param dict config_dict: Dict that may contain 'context', 'banner', and/or\n        'shell' (default shell class to use)."
  },
  {
    "code": "def clean_bytes(line):\n        text = line.decode('utf-8').replace('\\r', '').strip('\\n')\n        return re.sub(r'\\x1b[^m]*m', '', text).replace(\"``\", \"`\\u200b`\").strip('\\n')",
    "docstring": "Cleans a byte sequence of shell directives and decodes it."
  },
  {
    "code": "def get_index(self, filename):\r\n        index = self.fsmodel.index(filename)\r\n        if index.isValid() and index.model() is self.fsmodel:\r\n            return self.proxymodel.mapFromSource(index)",
    "docstring": "Return index associated with filename"
  },
  {
    "code": "def generate_and_merge_schemas(samples):\n    merged = generate_schema_for_sample(next(iter(samples)))\n    for sample in samples:\n        merged = merge_schema(merged, generate_schema_for_sample(sample))\n    return merged",
    "docstring": "Iterates through the given samples, generating schemas\n    and merging them, returning the resulting merged schema."
  },
  {
    "code": "def all_elements_equal(value):\n    if is_scalar(value):\n        return True\n    return np.array(value == value.flatten()[0]).all()",
    "docstring": "Checks if all elements in the given value are equal to each other.\n\n    If the input is a single value the result is trivial. If not, we compare all the values to see\n    if they are exactly the same.\n\n    Args:\n        value (ndarray or number): a numpy array or a single number.\n\n    Returns:\n        bool: true if all elements are equal to each other, false otherwise"
  },
  {
    "code": "def _parse_scale(scale_exp):\n    m = re.search(\"(\\w+?)\\{(.*?)\\}\", scale_exp)\n    if m is None:\n        raise InvalidFormat('Unable to parse the given time period.')\n    scale = m.group(1)\n    range = m.group(2)\n    if scale not in SCALES:\n        raise InvalidFormat('%s is not a valid scale.' % scale)\n    ranges = re.split(\"\\s\", range)\n    return scale, ranges",
    "docstring": "Parses a scale expression and returns the scale, and a list of ranges."
  },
  {
    "code": "def pipe_value(self, message):\n        'Send a new value into the ws pipe'\n        jmsg = json.dumps(message)\n        self.send(jmsg)",
    "docstring": "Send a new value into the ws pipe"
  },
  {
    "code": "async def get(self, cmd, daap_data=True, timeout=None, **args):\n        def _get_request():\n            return self.http.get_data(\n                self._mkurl(cmd, *args),\n                headers=_DMAP_HEADERS,\n                timeout=timeout)\n        await self._assure_logged_in()\n        return await self._do(_get_request, is_daap=daap_data)",
    "docstring": "Perform a DAAP GET command."
  },
  {
    "code": "def clear_published_date(self):\n        if (self.get_published_date_metadata().is_read_only() or\n                self.get_published_date_metadata().is_required()):\n            raise errors.NoAccess()\n        self._my_map['publishedDate'] = self._published_date_default",
    "docstring": "Removes the puiblished date.\n\n        raise:  NoAccess - ``Metadata.isRequired()`` is ``true`` or\n                ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def find_next(lines, find_str, start_index):\n    mode = None\n    if isinstance(find_str, basestring):\n        mode = 'normal'\n        message = find_str\n    elif isinstance(find_str, Invert):\n        mode = 'invert'\n        message = str(find_str)\n    else:\n        raise TypeError(\"Unsupported message type\")\n    for i in range(start_index, len(lines)):\n        if re.search(message, lines[i]):\n            return mode == 'normal', i, lines[i]\n        elif message in lines[i]:\n            return mode == 'normal', i, lines[i]\n    if mode == 'invert':\n        return True, len(lines), None\n    raise LookupError(\"Not found\")",
    "docstring": "Find the next instance of find_str from lines starting from start_index.\n\n    :param lines: Lines to look through\n    :param find_str: String or Invert to look for\n    :param start_index: Index to start from\n    :return: (boolean, index, line)"
  },
  {
    "code": "def stop_daemon(self, payload=None):\n        kill_signal = signals['9']\n        self.process_handler.kill_all(kill_signal, True)\n        self.running = False\n        return {'message': 'Pueue daemon shutting down',\n                'status': 'success'}",
    "docstring": "Kill current processes and initiate daemon shutdown.\n\n        The daemon will shut down after a last check on all killed processes."
  },
  {
    "code": "def BuildDefaultValue(self, value_cls):\n    try:\n      return value_cls()\n    except Exception as e:\n      logging.exception(e)\n      raise DefaultValueError(\n          \"Can't create default for value %s: %s\" % (value_cls.__name__, e))",
    "docstring": "Renders default value of a given class.\n\n    Args:\n      value_cls: Default value of this class will be rendered. This class has to\n        be (or to be a subclass of) a self.value_class (i.e. a class that this\n        renderer is capable of rendering).\n\n    Returns:\n      An initialized default value.\n\n    Raises:\n      DefaultValueError: if something goes wrong."
  },
  {
    "code": "def close(self):\n        from matplotlib.pyplot import close\n        for ax in self.axes[::-1]:\n            ax.set_xscale('linear')\n            ax.set_yscale('linear')\n            ax.cla()\n        close(self)",
    "docstring": "Close the plot and release its memory."
  },
  {
    "code": "def from_sds(var, *args, **kwargs):\n    var.__dict__['dtype'] = HTYPE_TO_DTYPE[var.info()[3]]\n    shape = var.info()[2]\n    var.__dict__['shape'] = shape if isinstance(shape, (tuple, list)) else tuple(shape)\n    return da.from_array(var, *args, **kwargs)",
    "docstring": "Create a dask array from a SD dataset."
  },
  {
    "code": "def close(self) -> None:\n        self._channel.close()\n        self._channel = self._stub_v1 = self._stub_v2 = None",
    "docstring": "Close the gRPC channel and free the acquired resources. Using a closed client is\n        not supported."
  },
  {
    "code": "def retract(self, idx_or_declared_fact):\n        self.facts.retract(idx_or_declared_fact)\n        if not self.running:\n            added, removed = self.get_activations()\n            self.strategy.update_agenda(self.agenda, added, removed)",
    "docstring": "Retracts a specific fact, using its index\n\n        .. note::\n            This updates the agenda"
  },
  {
    "code": "def run_in_terminal(self, func, render_cli_done=False, cooked_mode=True):\n        if render_cli_done:\n            self._return_value = True\n            self._redraw()\n            self.renderer.reset()\n        else:\n            self.renderer.erase()\n        self._return_value = None\n        if cooked_mode:\n            with self.input.cooked_mode():\n                result = func()\n        else:\n            result = func()\n        self.renderer.reset()\n        self.renderer.request_absolute_cursor_position()\n        self._redraw()\n        return result",
    "docstring": "Run function on the terminal above the prompt.\n\n        What this does is first hiding the prompt, then running this callable\n        (which can safely output to the terminal), and then again rendering the\n        prompt which causes the output of this function to scroll above the\n        prompt.\n\n        :param func: The callable to execute.\n        :param render_cli_done: When True, render the interface in the\n                'Done' state first, then execute the function. If False,\n                erase the interface first.\n        :param cooked_mode: When True (the default), switch the input to\n                cooked mode while executing the function.\n\n        :returns: the result of `func`."
  },
  {
    "code": "def create_session(self, ticket, payload=None, expires=None):\n        assert isinstance(self.session_storage_adapter, CASSessionAdapter)\n        logging.debug('[CAS] Creating session for ticket {}'.format(ticket))\n        self.session_storage_adapter.create(\n            ticket,\n            payload=payload,\n            expires=expires,\n            )",
    "docstring": "Create a session record from a service ticket."
  },
  {
    "code": "def save_model(self, filename, num_iteration=None, start_iteration=0):\n        if num_iteration is None:\n            num_iteration = self.best_iteration\n        _safe_call(_LIB.LGBM_BoosterSaveModel(\n            self.handle,\n            ctypes.c_int(start_iteration),\n            ctypes.c_int(num_iteration),\n            c_str(filename)))\n        _dump_pandas_categorical(self.pandas_categorical, filename)\n        return self",
    "docstring": "Save Booster to file.\n\n        Parameters\n        ----------\n        filename : string\n            Filename to save Booster.\n        num_iteration : int or None, optional (default=None)\n            Index of the iteration that should be saved.\n            If None, if the best iteration exists, it is saved; otherwise, all iterations are saved.\n            If <= 0, all iterations are saved.\n        start_iteration : int, optional (default=0)\n            Start index of the iteration that should be saved.\n\n        Returns\n        -------\n        self : Booster\n            Returns self."
  },
  {
    "code": "def close(self):\n        super(LockingDatabase, self).close()\n        if not self.readonly:\n            self.release_lock()",
    "docstring": "Closes the database, releasing lock."
  },
  {
    "code": "def prev(self, n=1):\n        i = abs(self.tell - n)\n        return self.get(i, n)",
    "docstring": "Get the previous n data from file.\n\n        Keyword argument:\n            n -- number of structs to be retrieved (default 1)\n                 Must be greater than 0.\n\n        Return:\n            A data in the format of obj_fmt, if n = 1. A list of\n            structs, otherwise."
  },
  {
    "code": "def plot_signal(signal, sig_len, n_sig, fs, time_units, sig_style, axes):\n    \"Plot signal channels\"\n    if len(sig_style) == 1:\n        sig_style = n_sig * sig_style\n    if time_units == 'samples':\n        t = np.linspace(0, sig_len-1, sig_len)\n    else:\n        downsample_factor = {'seconds':fs, 'minutes':fs * 60,\n                             'hours':fs * 3600}\n        t = np.linspace(0, sig_len-1, sig_len) / downsample_factor[time_units]\n    if signal.ndim == 1:\n        axes[0].plot(t, signal, sig_style[0], zorder=3)\n    else:\n        for ch in range(n_sig):\n            axes[ch].plot(t, signal[:,ch], sig_style[ch], zorder=3)",
    "docstring": "Plot signal channels"
  },
  {
    "code": "def _parse_description(self, description_text):\n        text = description_text\n        text = text.strip()\n        lines = text.split('\\n')\n        data = {}\n        for line in lines:\n            if \":\" in line:\n                idx = line.index(\":\")\n                key = line[:idx]\n                value = line[idx+1:].lstrip().rstrip()\n                data[key] = value\n            else:\n                if isinstance(value, list) is False:\n                    value = [value]\n                value.append(line.lstrip().rstrip())\n                data[key] = value\n        return data",
    "docstring": "Turn description to dictionary."
  },
  {
    "code": "def addToStore(store, identifier, name):\n    persistedFactory = store.findOrCreate(_PersistedFactory, identifier=identifier)\n    persistedFactory.name = name\n    return persistedFactory",
    "docstring": "Adds a persisted factory with given identifier and object name to\n    the given store.\n\n    This is intended to have the identifier and name partially\n    applied, so that a particular module with an exercise in it can\n    just have an ``addToStore`` function that remembers it in the\n    store.\n\n    If a persisted factory with the same identifier already exists,\n    the name will be updated."
  },
  {
    "code": "def start_tcp_server(self, ip, port, name=None, timeout=None, protocol=None, family='ipv4'):\n        self._start_server(TCPServer, ip, port, name, timeout, protocol, family)",
    "docstring": "Starts a new TCP server to given `ip` and `port`.\n\n        Server can be given a `name`, default `timeout` and a `protocol`.\n        `family` can be either ipv4 (default) or ipv6. Notice that you have to\n        use `Accept Connection` keyword for server to receive connections.\n\n        Examples:\n        | Start TCP server | 10.10.10.2 | 53 |\n        | Start TCP server | 10.10.10.2 | 53 | Server1 |\n        | Start TCP server | 10.10.10.2 | 53 | name=Server1 | protocol=GTPV2 |\n        | Start TCP server | 10.10.10.2 | 53 | timeout=5 |\n        | Start TCP server | 0:0:0:0:0:0:0:1 | 53 | family=ipv6 |"
  },
  {
    "code": "def get_arrays(self, type_img):\n        if type_img.lower() == 'lola':\n            return LolaMap(self.ppdlola, *self.window, path_pdsfile=self.path_pdsfiles).image()\n        elif type_img.lower() == 'wac':\n            return WacMap(self.ppdwac, *self.window, path_pdsfile=self.path_pdsfiles).image()\n        else:\n            raise ValueError('The img type has to be either \"Lola\" or \"Wac\"')",
    "docstring": "Return arrays the region of interest\n\n        Args:\n            type_img (str): Either lola or wac.\n\n        Returns:\n            A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the\n            longitudes, ``Y`` contains the latitude and ``Z`` the values\n            extracted for the region of interest.\n\n        Note:\n            The argument has to be either lola or wac. Note case sensitive.\n            All return arrays have the same size.\n\n            All coordinates are in degree."
  },
  {
    "code": "def get_class_from_settings_from_apps(settings_key):\n    cls_path = getattr(settings, settings_key, None)\n    if not cls_path:\n        raise NotImplementedError()\n    try:\n        app_label = cls_path.split('.')[-2]\n        model_name = cls_path.split('.')[-1]\n    except ValueError:\n        raise ImproperlyConfigured(\"{0} must be of the form \"\n                                   \"'app_label.model_name'\".format(\n                                                                settings_key))\n    app = apps.get_app_config(app_label).models_module\n    if not app:\n        raise ImproperlyConfigured(\"{0} setting refers to an app that has not \"\n                                   \"been installed\".format(settings_key))\n    return getattr(app, model_name)",
    "docstring": "Try and get a class from a settings path by lookin in installed apps."
  },
  {
    "code": "def configure_logging(verbosity):\n    root = logging.getLogger()\n    formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s',\n                                  '%y-%m-%d %H:%M:%S')\n    handler = logging.StreamHandler()\n    handler.setFormatter(formatter)\n    loglevels = [logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]\n    if verbosity >= len(loglevels):\n        verbosity = len(loglevels) - 1\n    level = loglevels[verbosity]\n    root.setLevel(level)\n    root.addHandler(handler)",
    "docstring": "Set up the global logging level.\n\n    Args:\n        verbosity (int): The logging verbosity"
  },
  {
    "code": "def parse_content(self, content, allow_no_value=False):\n        super(IniConfigFile, self).parse_content(content)\n        config = RawConfigParser(allow_no_value=allow_no_value)\n        fp = io.StringIO(u\"\\n\".join(content))\n        config.readfp(fp, filename=self.file_name)\n        self.data = config",
    "docstring": "Parses content of the config file.\n\n        In child class overload and call super to set flag\n        ``allow_no_values`` and allow keys with no value in\n        config file::\n\n            def parse_content(self, content):\n                super(YourClass, self).parse_content(content,\n                                                     allow_no_values=True)"
  },
  {
    "code": "def commuting_sets_by_indices(pauli_sums, commutation_check):\n    assert isinstance(pauli_sums, list)\n    group_inds = []\n    group_terms = []\n    for i, pauli_sum in enumerate(pauli_sums):\n        for j, term in enumerate(pauli_sum):\n            if len(group_inds) == 0:\n                group_inds.append([(i, j)])\n                group_terms.append([term])\n                continue\n            for k, group in enumerate(group_terms):\n                if commutation_check(group, term):\n                    group_inds[k] += [(i, j)]\n                    group_terms[k] += [term]\n                    break\n            else:\n                group_inds.append([(i, j)])\n                group_terms.append([term])\n    return group_inds",
    "docstring": "For a list of pauli sums, find commuting sets and keep track of which pauli sum they came from.\n\n    :param pauli_sums: A list of PauliSum\n    :param commutation_check: a function that checks if all elements of a list\n                              and a single pauli term commute.\n    :return: A list of commuting sets. Each set is a list of tuples (i, j) to find the particular\n        commuting term. i is the index of the pauli sum from whence the term came. j is the\n        index within the set."
  },
  {
    "code": "def register(self, es, append=None, modulo=None):\n        if not isinstance(es, CMAEvolutionStrategy):\n            raise TypeError(\"only class CMAEvolutionStrategy can be \" +\n                            \"registered for logging\")\n        self.es = es\n        if append is not None:\n            self.append = append\n        if modulo is not None:\n            self.modulo = modulo\n        self.registered = True\n        return self",
    "docstring": "register a `CMAEvolutionStrategy` instance for logging,\n        ``append=True`` appends to previous data logged under the same name,\n        by default previous data are overwritten."
  },
  {
    "code": "def _get_arg_tokens(cli):\n    arg = cli.input_processor.arg\n    return [\n        (Token.Prompt.Arg, '(arg: '),\n        (Token.Prompt.Arg.Text, str(arg)),\n        (Token.Prompt.Arg, ') '),\n    ]",
    "docstring": "Tokens for the arg-prompt."
  },
  {
    "code": "def remove_sites_from_neighbours( self, remove_labels ):\n        if type( remove_labels ) is str:\n            remove_labels = [ remove_labels ]\n        self.neighbours = set( n for n in self.neighbours if n.label not in remove_labels )",
    "docstring": "Removes sites from the set of neighbouring sites if these have labels in remove_labels.\n\n        Args:\n            Remove_labels (List) or (Str): List of Site labels to be removed from the cluster neighbour set.\n\n        Returns:\n            None"
  },
  {
    "code": "def get_environments():\n    envs = []\n    for root, subfolders, files in os.walk('environments'):\n        for filename in files:\n            if filename.endswith(\".json\"):\n                path = os.path.join(\n                    root[len('environments'):], filename[:-len('.json')])\n                envs.append(get_environment(path))\n    return sorted(envs, key=lambda x: x['name'])",
    "docstring": "Gets all environments found in the 'environments' directory"
  },
  {
    "code": "def update_contact_of_client(self, contact_id, contact_dict):\n        return self._create_put_request(resource=CONTACTS, billomat_id=contact_id, send_data=contact_dict)",
    "docstring": "Updates a contact\n\n        :param contact_id: the id of the contact\n        :param contact_dict: dict\n        :return: dict"
  },
  {
    "code": "def check_who_read(self, messages):\n        for m in messages:\n            readers = []\n            for p in m.thread.participation_set.all():\n                if p.date_last_check is None:\n                    pass\n                elif p.date_last_check > m.sent_at:\n                    readers.append(p.participant.id)\n            setattr(m, \"readers\", readers)\n        return messages",
    "docstring": "Check who read each message."
  },
  {
    "code": "def _wrap_rpc_behavior(handler, fn):\n    if handler is None:\n        return None\n    if handler.request_streaming and handler.response_streaming:\n        behavior_fn = handler.stream_stream\n        handler_factory = grpc.stream_stream_rpc_method_handler\n    elif handler.request_streaming and not handler.response_streaming:\n        behavior_fn = handler.stream_unary\n        handler_factory = grpc.stream_unary_rpc_method_handler\n    elif not handler.request_streaming and handler.response_streaming:\n        behavior_fn = handler.unary_stream\n        handler_factory = grpc.unary_stream_rpc_method_handler\n    else:\n        behavior_fn = handler.unary_unary\n        handler_factory = grpc.unary_unary_rpc_method_handler\n    return handler_factory(\n        fn(behavior_fn, handler.request_streaming,\n           handler.response_streaming),\n        request_deserializer=handler.request_deserializer,\n        response_serializer=handler.response_serializer\n    )",
    "docstring": "Returns a new rpc handler that wraps the given function"
  },
  {
    "code": "def close(self):\n        if self._writer is not None:\n            self.flush()\n            self._writer.close()\n            self._writer = None",
    "docstring": "Closes the record writer."
  },
  {
    "code": "def add_volume(self,colorchange=True,column=None,name='',str='{name}',**kwargs):\n\t\tif not column:\n\t\t\tcolumn=self._d['volume']\n\t\tup_color=kwargs.pop('up_color',self.theme['up_color'])\n\t\tdown_color=kwargs.pop('down_color',self.theme['down_color'])\n\t\tstudy={'kind':'volume',\n\t\t\t   'name':name,\n\t\t\t   'params':{'colorchange':colorchange,'base':'close','column':column,\n\t\t\t\t\t\t 'str':None},\n\t\t\t  'display':utils.merge_dict({'up_color':up_color,'down_color':down_color},kwargs)}\n\t\tself._add_study(study)",
    "docstring": "Add 'volume' study to QuantFigure.studies\n\n\t\tParameters:\n\t\t\tcolorchange : bool\n\t\t\t\tIf True then each volume bar will have a fill color \n\t\t\t\tdepending on if 'base' had a positive or negative\n\t\t\t\tchange compared to the previous value\n\t\t\t\tIf False then each volume bar will have a fill color \n\t\t\t\tdepending on if the volume data itself had a positive or negative\n\t\t\t\tchange compared to the previous value\n\t\t\tcolumn :string\n\t\t\t\tDefines the data column name that contains the volume data. \n\t\t\t\tDefault: 'volume'\n\t\t\tname : string\n\t\t\t\tName given to the study\n\t\t\tstr : string\n\t\t\t\tLabel factory for studies\n\t\t\t\tThe following wildcards can be used:\n\t\t\t\t\t{name} : Name of the column\n\t\t\t\t\t{study} : Name of the study\n\t\t\t\t\t{period} : Period used\n\t\t\t\tExamples:\n\t\t\t\t\t'study: {study} - period: {period}'\n\t\t\t\n\t\tkwargs : \n\t\t\tbase : string\n\t\t\t\tDefines the column which will define the\n\t\t\t\tpositive/negative changes (if colorchange=True).\n\t\t\t\tDefault = 'close'\n\t\t\tup_color : string\n\t\t\t\tColor for positive bars\n\t\t\tdown_color : string\n\t\t\t\tColor for negative bars"
  },
  {
    "code": "def create_topics(self, new_topics, timeout_ms=None, validate_only=False):\n        version = self._matching_api_version(CreateTopicsRequest)\n        timeout_ms = self._validate_timeout(timeout_ms)\n        if version == 0:\n            if validate_only:\n                raise IncompatibleBrokerVersion(\n                    \"validate_only requires CreateTopicsRequest >= v1, which is not supported by Kafka {}.\"\n                    .format(self.config['api_version']))\n            request = CreateTopicsRequest[version](\n                create_topic_requests=[self._convert_new_topic_request(new_topic) for new_topic in new_topics],\n                timeout=timeout_ms\n            )\n        elif version <= 2:\n            request = CreateTopicsRequest[version](\n                create_topic_requests=[self._convert_new_topic_request(new_topic) for new_topic in new_topics],\n                timeout=timeout_ms,\n                validate_only=validate_only\n            )\n        else:\n            raise NotImplementedError(\n                \"Support for CreateTopics v{} has not yet been added to KafkaAdminClient.\"\n                .format(version))\n        return self._send_request_to_controller(request)",
    "docstring": "Create new topics in the cluster.\n\n        :param new_topics: A list of NewTopic objects.\n        :param timeout_ms: Milliseconds to wait for new topics to be created\n            before the broker returns.\n        :param validate_only: If True, don't actually create new topics.\n            Not supported by all versions. Default: False\n        :return: Appropriate version of CreateTopicResponse class."
  },
  {
    "code": "def get_column_index(self, header):\n        try:\n            index = self._column_headers.index(header)\n            return index\n        except ValueError:\n            raise_suppressed(KeyError((\"'{}' is not a header for any \"\n                                       \"column\").format(header)))",
    "docstring": "Get index of a column from it's header.\n\n        Parameters\n        ----------\n        header: str\n            header of the column.\n\n        Raises\n        ------\n        ValueError:\n            If no column could be found corresponding to `header`."
  },
  {
    "code": "def __create_entry(self, entrytype, data, index, ttl=None):\n        if entrytype == 'HS_ADMIN':\n            op = 'creating HS_ADMIN entry'\n            msg = 'This method can not create HS_ADMIN entries.'\n            raise IllegalOperationException(operation=op, msg=msg)\n        entry = {'index':index, 'type':entrytype, 'data':data}\n        if ttl is not None:\n            entry['ttl'] = ttl\n        return entry",
    "docstring": "Create an entry of any type except HS_ADMIN.\n\n        :param entrytype: THe type of entry to create, e.g. 'URL' or\n            'checksum' or ... Note: For entries of type 'HS_ADMIN', please\n            use __create_admin_entry(). For type '10320/LOC', please use\n            'add_additional_URL()'\n        :param data: The actual value for the entry. Can be a simple string,\n            e.g. \"example\", or a dict {\"format\":\"string\", \"value\":\"example\"}.\n        :param index: The integer to be used as index.\n        :param ttl: Optional. If not set, the library's default is set. If\n            there is no default, it is not set by this library, so Handle\n            System sets it.\n        :return: The entry as a dict."
  },
  {
    "code": "def is_schema_of_common_names(schema: GraphQLSchema) -> bool:\n    query_type = schema.query_type\n    if query_type and query_type.name != \"Query\":\n        return False\n    mutation_type = schema.mutation_type\n    if mutation_type and mutation_type.name != \"Mutation\":\n        return False\n    subscription_type = schema.subscription_type\n    if subscription_type and subscription_type.name != \"Subscription\":\n        return False\n    return True",
    "docstring": "Check whether this schema uses the common naming convention.\n\n    GraphQL schema define root types for each type of operation. These types are the\n    same as any other type and can be named in any manner, however there is a common\n    naming convention:\n\n    schema {\n      query: Query\n      mutation: Mutation\n    }\n\n    When using this naming convention, the schema description can be omitted."
  },
  {
    "code": "def random_filename(path=None):\n    filename = uuid4().hex\n    if path is not None:\n        filename = os.path.join(path, filename)\n    return filename",
    "docstring": "Make a UUID-based file name which is extremely unlikely\n    to exist already."
  },
  {
    "code": "def contribute_to_class(self, cls, name):\n        self.update_rel_to(cls)\n        self.set_attributes_from_name(name)\n        self.model = cls\n        if not self.remote_field.through and not cls._meta.abstract:\n            self.remote_field.through = create_many_to_many_intermediary_model(\n                self, cls)\n        super(M2MFromVersion, self).contribute_to_class(cls, name)",
    "docstring": "Because django doesn't give us a nice way to provide\n        a through table without losing functionality. We have to\n        provide our own through table creation that uses the\n        FKToVersion field to be used for the from field."
  },
  {
    "code": "def register_trading_control(self, control):\n        if self.initialized:\n            raise RegisterTradingControlPostInit()\n        self.trading_controls.append(control)",
    "docstring": "Register a new TradingControl to be checked prior to order calls."
  },
  {
    "code": "def shape(cls, dataset):\n        if not dataset.data:\n            return (0, len(dataset.dimensions()))\n        rows, cols = 0, 0\n        ds = cls._inner_dataset_template(dataset)\n        for d in dataset.data:\n            ds.data = d\n            r, cols = ds.interface.shape(ds)\n            rows += r\n        return rows+len(dataset.data)-1, cols",
    "docstring": "Returns the shape of all subpaths, making it appear like a\n        single array of concatenated subpaths separated by NaN values."
  },
  {
    "code": "def _set_init_params(self, qrs_amp_recent, noise_amp_recent, rr_recent,\n                         last_qrs_ind):\n        self.qrs_amp_recent = qrs_amp_recent\n        self.noise_amp_recent = noise_amp_recent\n        self.qrs_thr = max(0.25*self.qrs_amp_recent\n                           + 0.75*self.noise_amp_recent,\n                           self.qrs_thr_min * self.transform_gain)\n        self.rr_recent = rr_recent\n        self.last_qrs_ind = last_qrs_ind\n        self.last_qrs_peak_num = None",
    "docstring": "Set initial online parameters"
  },
  {
    "code": "def importFile(self, srcUrl, sharedFileName=None):\n        self._assertContextManagerUsed()\n        return self._jobStore.importFile(srcUrl, sharedFileName=sharedFileName)",
    "docstring": "Imports the file at the given URL into job store.\n\n        See :func:`toil.jobStores.abstractJobStore.AbstractJobStore.importFile` for a\n        full description"
  },
  {
    "code": "def loadSessions(self, callback, bare_jid, device_ids):\n        if self.is_async:\n            self.__loadSessionsAsync(callback, bare_jid, device_ids, {})\n        else:\n            return self.__loadSessionsSync(bare_jid, device_ids)",
    "docstring": "Return a dict containing the session for each device id. By default, this method\n        calls loadSession for each device id."
  },
  {
    "code": "def bitstring_probs_to_z_moments(p):\n    zmat = np.array([[1, 1],\n                     [1, -1]])\n    return _apply_local_transforms(p, (zmat for _ in range(p.ndim)))",
    "docstring": "Convert between bitstring probabilities and joint Z moment expectations.\n\n    :param np.array p: An array that enumerates bitstring probabilities. When\n        flattened out ``p = [p_00...0, p_00...1, ...,p_11...1]``. The total number of elements must\n        therefore be a power of 2. The canonical shape has a separate axis for each qubit, such that\n        ``p[i,j,...,k]`` gives the estimated probability of bitstring ``ij...k``.\n    :return: ``z_moments``, an np.array with one length-2 axis per qubit which contains the\n        expectations of all monomials in ``{I, Z_0, Z_1, ..., Z_{n-1}}``. The expectations of each\n        monomial can be accessed via::\n\n            <Z_0^j_0 Z_1^j_1 ... Z_m^j_m> = z_moments[j_0,j_1,...,j_m]\n\n    :rtype: np.array"
  },
  {
    "code": "def _reduce_age(self, now):\n        if self.max_age:\n            keys = [\n                key for key, value in iteritems(self.data)\n                if now - value['date'] > self.max_age\n            ]\n            for key in keys:\n                del self.data[key]",
    "docstring": "Reduce size of cache by date.\n\n        :param datetime.datetime now: Current time"
  },
  {
    "code": "def files(self):\n        self._printer('\\tFiles Walk')\n        for directory in self.directory:\n            for path in os.listdir(directory):\n                full_path = os.path.join(directory, path)\n                if os.path.isfile(full_path):\n                    if not path.startswith('.'):\n                        self.filepaths.append(full_path)\n        return self._get_filepaths()",
    "docstring": "Return list of files in root directory"
  },
  {
    "code": "def grammatical_join(l, initial_joins=\", \", final_join=\" and \"):\n    return initial_joins.join(l[:-2] + [final_join.join(l[-2:])])",
    "docstring": "Display a list of items nicely, with a different string before the final\n    item. Useful for using lists in sentences.\n\n    >>> grammatical_join(['apples', 'pears', 'bananas'])\n    'apples, pears and bananas'\n\n    >>> grammatical_join(['apples', 'pears', 'bananas'], initial_joins=\";\", final_join=\"; or \")\n    'apples; pears; or bananas'\n\n    :param l: List of strings to join\n    :param initial_joins: the string to join the non-ultimate items with\n    :param final_join: the string to join the final item with\n    :return: items joined with commas except \" and \" before the final one."
  },
  {
    "code": "def get_output_content(job_id, max_size=1024, conn=None):\n    content = None\n    if RBO.index_list().contains(IDX_OUTPUT_JOB_ID).run(conn):\n        check_status = RBO.get_all(job_id, index=IDX_OUTPUT_JOB_ID).run(conn)\n    else:\n        check_status = RBO.filter({OUTPUTJOB_FIELD: {ID_FIELD: job_id}}).run(conn)\n    for status_item in check_status:\n        content = _truncate_output_content_if_required(status_item, max_size)\n    return content",
    "docstring": "returns the content buffer for a job_id if that job output exists\n\n    :param job_id: <str> id for the job\n    :param max_size: <int> truncate after [max_size] bytes\n    :param conn: (optional)<connection> to run on\n    :return: <str> or <bytes>"
  },
  {
    "code": "def ReadAllClientActionRequests(self, client_id, cursor=None):\n    query = (\"SELECT request, UNIX_TIMESTAMP(leased_until), leased_by, \"\n             \"leased_count \"\n             \"FROM client_action_requests \"\n             \"WHERE client_id = %s\")\n    cursor.execute(query, [db_utils.ClientIDToInt(client_id)])\n    ret = []\n    for req, leased_until, leased_by, leased_count in cursor.fetchall():\n      request = rdf_flows.ClientActionRequest.FromSerializedString(req)\n      if leased_until is not None:\n        request.leased_by = leased_by\n        request.leased_until = mysql_utils.TimestampToRDFDatetime(leased_until)\n      else:\n        request.leased_by = None\n        request.leased_until = None\n      request.ttl = db.Database.CLIENT_MESSAGES_TTL - leased_count\n      ret.append(request)\n    return sorted(ret, key=lambda req: (req.flow_id, req.request_id))",
    "docstring": "Reads all client messages available for a given client_id."
  },
  {
    "code": "def confirm(prompt_str, default=False):\n    if default:\n        default_str = 'y'\n        prompt = '%s [Y/n]' % prompt_str\n    else:\n        default_str = 'n'\n        prompt = '%s [y/N]' % prompt_str\n    ans = click.prompt(prompt, default=default_str, show_default=False)\n    if ans.lower() in ('y', 'yes', 'yeah', 'yup', 'yolo'):\n        return True\n    return False",
    "docstring": "Show a confirmation prompt to a command-line user.\n\n    :param string prompt_str: prompt to give to the user\n    :param bool default: Default value to True or False"
  },
  {
    "code": "def update_generators():\n    for generator in _GENERATOR_DB.keys():\n        install_templates_translations(generator)\n        add_variables_to_context(generator)\n        interlink_static_files(generator)\n        interlink_removed_content(generator)\n        interlink_translated_content(generator)",
    "docstring": "Update the context of all generators\n\n    Ads useful variables and translations into the template context\n    and interlink translations"
  },
  {
    "code": "def cluster(\n        self, cluster_id, location_id=None, serve_nodes=None, default_storage_type=None\n    ):\n        return Cluster(\n            cluster_id,\n            self,\n            location_id=location_id,\n            serve_nodes=serve_nodes,\n            default_storage_type=default_storage_type,\n        )",
    "docstring": "Factory to create a cluster associated with this instance.\n\n        For example:\n\n        .. literalinclude:: snippets.py\n            :start-after: [START bigtable_create_cluster]\n            :end-before: [END bigtable_create_cluster]\n\n        :type cluster_id: str\n        :param cluster_id: The ID of the cluster.\n\n        :type instance: :class:`~google.cloud.bigtable.instance.Instance`\n        :param instance: The instance where the cluster resides.\n\n        :type location_id: str\n        :param location_id: (Creation Only) The location where this cluster's\n                            nodes and storage reside. For best performance,\n                            clients should be located as close as possible to\n                            this cluster.\n                            For list of supported locations refer to\n                            https://cloud.google.com/bigtable/docs/locations\n\n        :type serve_nodes: int\n        :param serve_nodes: (Optional) The number of nodes in the cluster.\n\n        :type default_storage_type: int\n        :param default_storage_type: (Optional) The type of storage\n                                     Possible values are represented by the\n                                     following constants:\n                                     :data:`google.cloud.bigtable.enums.StorageType.SSD`.\n                                     :data:`google.cloud.bigtable.enums.StorageType.SHD`,\n                                     Defaults to\n                                     :data:`google.cloud.bigtable.enums.StorageType.UNSPECIFIED`.\n\n        :rtype: :class:`~google.cloud.bigtable.instance.Cluster`\n        :returns: a cluster owned by this instance."
  },
  {
    "code": "def remove_negative_entries(A):\n    r\n    A = A.tocoo()\n    data = A.data\n    row = A.row\n    col = A.col\n    pos = data > 0.0\n    datap = data[pos]\n    rowp = row[pos]\n    colp = col[pos]\n    Aplus = coo_matrix((datap, (rowp, colp)), shape=A.shape)\n    return Aplus",
    "docstring": "r\"\"\"Remove all negative entries from sparse matrix.\n\n        Aplus=max(0, A)\n\n    Parameters\n    ----------\n    A : (M, M) scipy.sparse matrix\n        Input matrix\n\n    Returns\n    -------\n    Aplus : (M, M) scipy.sparse matrix\n        Input matrix with negative entries set to zero."
  },
  {
    "code": "def get(cls, *args, **kwargs):\n        if len(args) == 1:\n            pk = args[0]\n        elif kwargs:\n            if len(kwargs) == 1 and cls._field_is_pk(list(kwargs.keys())[0]):\n                pk = list(kwargs.values())[0]\n            else:\n                result = cls.collection(**kwargs).sort(by='nosort')\n                if len(result) == 0:\n                    raise DoesNotExist(u\"No object matching filter: %s\" % kwargs)\n                elif len(result) > 1:\n                    raise ValueError(u\"More than one object matching filter: %s\" % kwargs)\n                else:\n                    try:\n                        pk = result[0]\n                    except IndexError:\n                        raise DoesNotExist(u\"No object matching filter: %s\" % kwargs)\n        else:\n            raise ValueError(\"Invalid `get` usage with args %s and kwargs %s\" % (args, kwargs))\n        return cls(pk)",
    "docstring": "Retrieve one instance from db according to given kwargs.\n\n        Optionnaly, one arg could be used to retrieve it from pk."
  },
  {
    "code": "def _create_netmap_config(self):\n        netmap_path = os.path.join(self.working_dir, \"NETMAP\")\n        try:\n            with open(netmap_path, \"w\", encoding=\"utf-8\") as f:\n                for bay in range(0, 16):\n                    for unit in range(0, 4):\n                        f.write(\"{ubridge_id}:{bay}/{unit}{iou_id:>5d}:{bay}/{unit}\\n\".format(ubridge_id=str(self.application_id + 512),\n                                                                                              bay=bay,\n                                                                                              unit=unit,\n                                                                                              iou_id=self.application_id))\n            log.info(\"IOU {name} [id={id}]: NETMAP file created\".format(name=self._name,\n                                                                        id=self._id))\n        except OSError as e:\n            raise IOUError(\"Could not create {}: {}\".format(netmap_path, e))",
    "docstring": "Creates the NETMAP file."
  },
  {
    "code": "def add_modifier(self, modifier, keywords, relative_pos,\n                     action, parameter=None):\n        if relative_pos == 0:\n            raise ValueError(\"relative_pos cannot be 0\")\n        modifier_dict = self._modifiers.get(modifier, {})\n        value = (action, parameter, relative_pos)\n        for keyword in keywords:\n            action_list = list(modifier_dict.get(keyword, []))\n            action_list.append(value)\n            modifier_dict[keyword] = tuple(action_list)\n        self._modifiers[modifier] = modifier_dict",
    "docstring": "Modify existing tasks based on presence of a keyword.\n\n        Parameters\n        ----------\n        modifier : str\n            A string value which would trigger the given Modifier.\n        keywords : iterable of str\n            sequence of strings which are keywords for some task,\n            which has to be modified.\n        relative_pos : int\n            Relative position of the task which should be modified\n            in the presence of `modifier`. It's value can never be 0. Data\n            fields should also be considered when calculating the relative\n            position.\n        action : str\n            String value representing the action which should be performed\n            on the task. Action represents calling a arbitrary function\n            to perform th emodification.\n        parameter : object\n            value required by the `action`.(Default None)"
  },
  {
    "code": "def refit(self, data, label, decay_rate=0.9, **kwargs):\n        if self.__set_objective_to_none:\n            raise LightGBMError('Cannot refit due to null objective function.')\n        predictor = self._to_predictor(copy.deepcopy(kwargs))\n        leaf_preds = predictor.predict(data, -1, pred_leaf=True)\n        nrow, ncol = leaf_preds.shape\n        train_set = Dataset(data, label, silent=True)\n        new_booster = Booster(self.params, train_set, silent=True)\n        _safe_call(_LIB.LGBM_BoosterMerge(\n            new_booster.handle,\n            predictor.handle))\n        leaf_preds = leaf_preds.reshape(-1)\n        ptr_data, type_ptr_data, _ = c_int_array(leaf_preds)\n        _safe_call(_LIB.LGBM_BoosterRefit(\n            new_booster.handle,\n            ptr_data,\n            ctypes.c_int(nrow),\n            ctypes.c_int(ncol)))\n        new_booster.network = self.network\n        new_booster.__attr = self.__attr.copy()\n        return new_booster",
    "docstring": "Refit the existing Booster by new data.\n\n        Parameters\n        ----------\n        data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse\n            Data source for refit.\n            If string, it represents the path to txt file.\n        label : list, numpy 1-D array or pandas Series / one-column DataFrame\n            Label for refit.\n        decay_rate : float, optional (default=0.9)\n            Decay rate of refit,\n            will use ``leaf_output = decay_rate * old_leaf_output + (1.0 - decay_rate) * new_leaf_output`` to refit trees.\n        **kwargs\n            Other parameters for refit.\n            These parameters will be passed to ``predict`` method.\n\n        Returns\n        -------\n        result : Booster\n            Refitted Booster."
  },
  {
    "code": "def warn(self, collection):\n        super(CodeElement, self).warn(collection)\n        if not \"implicit none\" in self.modifiers:\n            collection.append(\"WARNING: implicit none not set in {}\".format(self.name))",
    "docstring": "Checks the module for documentation and best-practice warnings."
  },
  {
    "code": "def regions(self):\n        regions = []\n        elem = self.dimensions[\"region\"].elem\n        for option_elem in elem.find_all(\"option\"):\n            region = option_elem.text.strip()\n            regions.append(region)\n        return regions",
    "docstring": "Get a list of all regions"
  },
  {
    "code": "def sets(self, keyword, value):\n        if isinstance(value, str):\n            value = KQMLString(value)\n        self.set(keyword, value)",
    "docstring": "Set the element of the list after the given keyword as string.\n\n        Parameters\n        ----------\n        keyword : str\n            The keyword parameter to find in the list.\n            Putting a colon before the keyword is optional, if no colon is\n            given, it is added automatically (e.g. \"keyword\" will be found as\n            \":keyword\" in the list).\n\n        value : str\n            The value is instantiated as KQMLString and added to the list.\n\n        Example:\n            kl = KQMLList.from_string('(FAILURE)')\n            kl.sets('reason', 'this is a custom string message, not a token')"
  },
  {
    "code": "def bet_place(\n        self,\n        betting_market_id,\n        amount_to_bet,\n        backer_multiplier,\n        back_or_lay,\n        account=None,\n        **kwargs\n    ):\n        from . import GRAPHENE_BETTING_ODDS_PRECISION\n        assert isinstance(amount_to_bet, Amount)\n        assert back_or_lay in [\"back\", \"lay\"]\n        if not account:\n            if \"default_account\" in self.config:\n                account = self.config[\"default_account\"]\n        if not account:\n            raise ValueError(\"You need to provide an account\")\n        account = Account(account)\n        bm = BettingMarket(betting_market_id)\n        op = operations.Bet_place(\n            **{\n                \"fee\": {\"amount\": 0, \"asset_id\": \"1.3.0\"},\n                \"bettor_id\": account[\"id\"],\n                \"betting_market_id\": bm[\"id\"],\n                \"amount_to_bet\": amount_to_bet.json(),\n                \"backer_multiplier\": (\n                    int(backer_multiplier * GRAPHENE_BETTING_ODDS_PRECISION)\n                ),\n                \"back_or_lay\": back_or_lay,\n                \"prefix\": self.prefix,\n            }\n        )\n        return self.finalizeOp(op, account[\"name\"], \"active\", **kwargs)",
    "docstring": "Place a bet\n\n            :param str betting_market_id: The identifier for the market to bet\n                in\n            :param peerplays.amount.Amount amount_to_bet: Amount to bet with\n            :param int backer_multiplier: Multipler for backer\n            :param str back_or_lay: \"back\" or \"lay\" the bet\n            :param str account: (optional) the account to bet (defaults\n                        to ``default_account``)"
  },
  {
    "code": "def init_properties(env='dev', app='unnecessary', **_):\n    aws_env = boto3.session.Session(profile_name=env)\n    s3client = aws_env.resource('s3')\n    generated = get_details(app=app, env=env)\n    archaius = generated.archaius()\n    archaius_file = ('{path}/application.properties').format(path=archaius['path'])\n    try:\n        s3client.Object(archaius['bucket'], archaius_file).get()\n        LOG.info('Found: %(bucket)s/%(file)s', {'bucket': archaius['bucket'], 'file': archaius_file})\n        return True\n    except boto3.exceptions.botocore.client.ClientError:\n        s3client.Object(archaius['bucket'], archaius_file).put()\n        LOG.info('Created: %(bucket)s/%(file)s', {'bucket': archaius['bucket'], 'file': archaius_file})\n        return False",
    "docstring": "Make sure _application.properties_ file exists in S3.\n\n    For Applications with Archaius support, there needs to be a file where the\n    cloud environment variable points to.\n\n    Args:\n        env (str): Deployment environment/account, i.e. dev, stage, prod.\n        app (str): GitLab Project name.\n\n    Returns:\n        True when application.properties was found.\n        False when application.properties needed to be created."
  },
  {
    "code": "def record_content_length(self):\n        untldict = py2dict(self)\n        untldict.pop('meta', None)\n        return len(str(untldict))",
    "docstring": "Calculate length of record, excluding metadata."
  },
  {
    "code": "def _sd_of_eigenvector(data, vec, measurement='poles', bidirectional=True):\n    lon, lat = _convert_measurements(data, measurement)\n    vals, vecs = cov_eig(lon, lat, bidirectional)\n    x, y, z = vecs[:, vec]\n    s, d = stereonet_math.geographic2pole(*stereonet_math.cart2sph(x, y, z))\n    return s[0], d[0]",
    "docstring": "Unifies ``fit_pole`` and ``fit_girdle``."
  },
  {
    "code": "def list_datacenters(conn=None, call=None):\n    if call != 'function':\n        raise SaltCloudSystemExit(\n            'The list_datacenters function must be called with '\n            '-f or --function.'\n        )\n    datacenters = []\n    if not conn:\n        conn = get_conn()\n    for item in conn.list_datacenters()['items']:\n        datacenter = {'id': item['id']}\n        datacenter.update(item['properties'])\n        datacenters.append({item['properties']['name']: datacenter})\n    return {'Datacenters': datacenters}",
    "docstring": "List all the data centers\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -f list_datacenters my-profitbricks-config"
  },
  {
    "code": "def _contains_policies(self, resource_properties):\n        return resource_properties is not None \\\n            and isinstance(resource_properties, dict) \\\n            and self.POLICIES_PROPERTY_NAME in resource_properties",
    "docstring": "Is there policies data in this resource?\n\n        :param dict resource_properties: Properties of the resource\n        :return: True if we can process this resource. False, otherwise"
  },
  {
    "code": "def configure(self, options, conf):\n        super(ProgressivePlugin, self).configure(options, conf)\n        if (getattr(options, 'verbosity', 0) > 1 and\n            getattr(options, 'enable_plugin_id', False)):\n            print ('Using --with-id and --verbosity=2 or higher with '\n                   'nose-progressive causes visualization errors. Remove one '\n                   'or the other to avoid a mess.')\n        if options.with_bar:\n            options.with_styling = True",
    "docstring": "Turn style-forcing on if bar-forcing is on.\n\n        It'd be messy to position the bar but still have the rest of the\n        terminal capabilities emit ''."
  },
  {
    "code": "def insertPrimaryDataset(self):\n        try :\n            body = request.body.read()\n            indata = cjson.decode(body)\n            indata = validateJSONInputNoCopy(\"primds\", indata)\n            indata.update({\"creation_date\": dbsUtils().getTime(), \"create_by\": dbsUtils().getCreateBy() })\n            self.dbsPrimaryDataset.insertPrimaryDataset(indata)\n        except cjson.DecodeError as dc:\n            dbsExceptionHandler(\"dbsException-invalid-input2\", \"Wrong format/data from insert PrimaryDataset input\",  self.logger.exception, str(dc))\n        except dbsException as de:\n            dbsExceptionHandler(de.eCode, de.message, self.logger.exception, de.message)\n        except HTTPError as he:\n            raise he\n        except Exception as ex:\n            sError = \"DBSWriterModel/insertPrimaryDataset. %s\\n Exception trace: \\n %s\" \\\n                        % (ex, traceback.format_exc())\n            dbsExceptionHandler('dbsException-server-error',  dbsExceptionCode['dbsException-server-error'], self.logger.exception, sError)",
    "docstring": "API to insert A primary dataset in DBS\n\n        :param primaryDSObj: primary dataset object\n        :type primaryDSObj: dict\n        :key primary_ds_type: TYPE (out of valid types in DBS, MC, DATA) (Required)\n        :key primary_ds_name: Name of the primary dataset (Required)"
  },
  {
    "code": "def kill(self, container, signal=None):\n        url = self._url(\"/containers/{0}/kill\", container)\n        params = {}\n        if signal is not None:\n            if not isinstance(signal, six.string_types):\n                signal = int(signal)\n            params['signal'] = signal\n        res = self._post(url, params=params)\n        self._raise_for_status(res)",
    "docstring": "Kill a container or send a signal to a container.\n\n        Args:\n            container (str): The container to kill\n            signal (str or int): The signal to send. Defaults to ``SIGKILL``\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def add_item(self, assessment_id, item_id):\n        if assessment_id.get_identifier_namespace() != 'assessment.Assessment':\n            raise errors.InvalidArgument\n        self._part_item_design_session.add_item(item_id, self._get_first_part_id(assessment_id))",
    "docstring": "Adds an existing ``Item`` to an assessment.\n\n        arg:    assessment_id (osid.id.Id): the ``Id`` of the\n                ``Assessment``\n        arg:    item_id (osid.id.Id): the ``Id`` of the ``Item``\n        raise:  NotFound - ``assessment_id`` or ``item_id`` not found\n        raise:  NullArgument - ``assessment_id`` or ``item_id`` is\n                ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _surpress_formatting_errors(fn):\n    @wraps(fn)\n    def inner(*args, **kwargs):\n        try:\n            return fn(*args, **kwargs)\n        except ValueError:\n            return \"\"\n    return inner",
    "docstring": "I know this is dangerous and the wrong way to solve the problem, but when\n    using both row and columns summaries it's easier to just swallow errors\n    so users can format their tables how they need."
  },
  {
    "code": "def NumRegressors(npix, pld_order, cross_terms=True):\n    res = 0\n    for k in range(1, pld_order + 1):\n        if cross_terms:\n            res += comb(npix + k - 1, k)\n        else:\n            res += npix\n    return int(res)",
    "docstring": "Return the number of regressors for `npix` pixels\n    and PLD order `pld_order`.\n\n    :param bool cross_terms: Include pixel cross-terms? Default :py:obj:`True`"
  },
  {
    "code": "async def set_action(self, on=None, bri=None, hue=None, sat=None, xy=None,\n                         ct=None, alert=None, effect=None, transitiontime=None,\n                         bri_inc=None, sat_inc=None, hue_inc=None, ct_inc=None,\n                         xy_inc=None, scene=None):\n        data = {\n            key: value for key, value in {\n                'on': on,\n                'bri': bri,\n                'hue': hue,\n                'sat': sat,\n                'xy': xy,\n                'ct': ct,\n                'alert': alert,\n                'effect': effect,\n                'transitiontime': transitiontime,\n                'bri_inc': bri_inc,\n                'sat_inc': sat_inc,\n                'hue_inc': hue_inc,\n                'ct_inc': ct_inc,\n                'xy_inc': xy_inc,\n                'scene': scene,\n            }.items() if value is not None\n        }\n        await self._request('put', 'groups/{}/action'.format(self.id),\n                            json=data)",
    "docstring": "Change action of a group."
  },
  {
    "code": "def _fixedpoint(D, tol=1e-7, maxiter=None):\n    N, K = D.shape\n    logp = log(D).mean(axis=0)\n    a0 = _init_a(D)\n    if maxiter is None:\n        maxiter = MAXINT\n    for i in xrange(maxiter):\n        a1 = _ipsi(psi(a0.sum()) + logp)\n        if abs(loglikelihood(D, a1)-loglikelihood(D, a0)) < tol:\n            return a1\n        a0 = a1\n    raise Exception('Failed to converge after {} iterations, values are {}.'\n                    .format(maxiter, a1))",
    "docstring": "Simple fixed point iteration method for MLE of Dirichlet distribution"
  },
  {
    "code": "def download_file(self, regex, dest_dir):\n        log = logging.getLogger(self.cls_logger + '.download_file')\n        if not isinstance(regex, basestring):\n            log.error('regex argument is not a string')\n            return None\n        if not isinstance(dest_dir, basestring):\n            log.error('dest_dir argument is not a string')\n            return None\n        if not os.path.isdir(dest_dir):\n            log.error('Directory not found on file system: %s', dest_dir)\n            return None\n        key = self.find_key(regex)\n        if key is None:\n            log.warn('Could not find a matching S3 key for: %s', regex)\n            return None\n        return self.__download_from_s3(key, dest_dir)",
    "docstring": "Downloads a file by regex from the specified S3 bucket\n\n        This method takes a regular expression as the arg, and attempts\n        to download the file to the specified dest_dir as the\n        destination directory. This method sets the downloaded filename\n        to be the same as it is on S3.\n\n        :param regex: (str) Regular expression matching the S3 key for\n            the file to be downloaded.\n        :param dest_dir: (str) Full path destination directory\n        :return: (str) Downloaded file destination if the file was\n            downloaded successfully, None otherwise."
  },
  {
    "code": "def tally(self, name, value):\n        value = value or 0\n        if 'used' not in self.usages[name]:\n            self.usages[name]['used'] = 0\n        self.usages[name]['used'] += int(value)\n        self.update_available(name)",
    "docstring": "Adds to the \"used\" metric for the given quota."
  },
  {
    "code": "def dysmetria_score(self, data_frame):\n        tap_data = data_frame[data_frame.action_type == 0]\n        ds = np.mean(np.sqrt((tap_data.x - tap_data.x_target) ** 2 + (tap_data.y - tap_data.y_target) ** 2))\n        duration = math.ceil(data_frame.td[-1])\n        return ds, duration",
    "docstring": "This method calculates accuracy of target taps in pixels\n\n            :param data_frame: the data frame\n            :type data_frame: pandas.DataFrame\n            :return ds: dysmetria score in pixels\n            :rtype ds: float"
  },
  {
    "code": "def queue_purge(self, queue, **kwargs):\n        return self.channel.queue_purge(queue=queue).message_count",
    "docstring": "Discard all messages in the queue. This will delete the messages\n        and results in an empty queue."
  },
  {
    "code": "def get_prefix_source(cls):\n        try:\n            return cls.override_prefix()\n        except AttributeError:\n            if hasattr(cls, '_prefix_source'):\n                return cls.site + cls._prefix_source\n            else:\n                return cls.site",
    "docstring": "Return the prefix source, by default derived from site."
  },
  {
    "code": "def create(self, auth, type, desc, defer=False):\n        return self._call('create', auth, [type, desc], defer)",
    "docstring": "Create something in Exosite.\n\n        Args:\n            auth: <cik>\n            type: What thing to create.\n            desc: Information about thing."
  },
  {
    "code": "def classify_elements(self,\n                          file,\n                          file_content_type=None,\n                          model=None,\n                          **kwargs):\n        if file is None:\n            raise ValueError('file must be provided')\n        headers = {}\n        if 'headers' in kwargs:\n            headers.update(kwargs.get('headers'))\n        sdk_headers = get_sdk_headers('compare-comply', 'V1',\n                                      'classify_elements')\n        headers.update(sdk_headers)\n        params = {'version': self.version, 'model': model}\n        form_data = {}\n        form_data['file'] = (None, file, file_content_type or\n                             'application/octet-stream')\n        url = '/v1/element_classification'\n        response = self.request(\n            method='POST',\n            url=url,\n            headers=headers,\n            params=params,\n            files=form_data,\n            accept_json=True)\n        return response",
    "docstring": "Classify the elements of a document.\n\n        Analyzes the structural and semantic elements of a document.\n\n        :param file file: The document to classify.\n        :param str file_content_type: The content type of file.\n        :param str model: The analysis model to be used by the service. For the **Element\n        classification** and **Compare two documents** methods, the default is\n        `contracts`. For the **Extract tables** method, the default is `tables`. These\n        defaults apply to the standalone methods as well as to the methods' use in\n        batch-processing requests.\n        :param dict headers: A `dict` containing the request headers\n        :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n        :rtype: DetailedResponse"
  },
  {
    "code": "def start(self):\n        fname = self.conf['file']\n        logging.info(\"Configfile watcher plugin: Starting to watch route spec \"\n                     \"file '%s' for changes...\" % fname)\n        route_spec = {}\n        try:\n            route_spec = read_route_spec_config(fname)\n            if route_spec:\n                self.last_route_spec_update = datetime.datetime.now()\n                self.q_route_spec.put(route_spec)\n        except ValueError as e:\n            logging.warning(\"Cannot parse route spec: %s\" % str(e))\n        abspath    = os.path.abspath(fname)\n        parent_dir = os.path.dirname(abspath)\n        handler = RouteSpecChangeEventHandler(\n                                    route_spec_fname   = fname,\n                                    route_spec_abspath = abspath,\n                                    q_route_spec       = self.q_route_spec,\n                                    plugin             = self)\n        self.observer_thread = watchdog.observers.Observer()\n        self.observer_thread.name = \"ConfMon\"\n        self.observer_thread.schedule(handler, parent_dir)\n        self.observer_thread.start()",
    "docstring": "Start the configfile change monitoring thread."
  },
  {
    "code": "def is_product_owner(self, team_id):\n        if self.is_super_admin():\n            return True\n        team_id = uuid.UUID(str(team_id))\n        return team_id in self.child_teams_ids",
    "docstring": "Ensure the user is a PRODUCT_OWNER."
  },
  {
    "code": "def gen_file_jinja(self, template_file, data, output, dest_path):\n        if not os.path.exists(dest_path):\n            os.makedirs(dest_path)\n        output = join(dest_path, output)\n        logger.debug(\"Generating: %s\" % output)\n        env = Environment()\n        env.loader = FileSystemLoader(self.TEMPLATE_DIR)\n        template = env.get_template(template_file)\n        target_text = template.render(data)\n        open(output, \"w\").write(target_text)\n        return dirname(output), output",
    "docstring": "Fills data to the project template, using jinja2."
  },
  {
    "code": "def list_targets_by_instance(self, instance_id, target_list=None):\n        if target_list is not None:\n            return [target for target in target_list\n                    if target['instance_id'] == instance_id]\n        else:\n            ports = self._target_ports_by_instance(instance_id)\n            reachable_subnets = self._get_reachable_subnets(\n                ports, fetch_router_ports=True)\n            name = self._get_server_name(instance_id)\n            targets = []\n            for p in ports:\n                for ip in p.fixed_ips:\n                    if ip['subnet_id'] not in reachable_subnets:\n                        continue\n                    if netaddr.IPAddress(ip['ip_address']).version != 4:\n                        continue\n                    targets.append(FloatingIpTarget(p, ip['ip_address'], name))\n            return targets",
    "docstring": "Returns a list of FloatingIpTarget objects of FIP association.\n\n        :param instance_id: ID of target VM instance\n        :param target_list: (optional) a list returned by list_targets().\n            If specified, looking up is done against the specified list\n            to save extra API calls to a back-end. Otherwise target list\n            is retrieved from a back-end inside the method."
  },
  {
    "code": "def db(self, entity, query_filters=\"size=10\"):\n        if self.entity_api_key == \"\":\n            return {'status': 'failure', 'response': 'No API key found in request'}\n        historic_url = self.base_url + \"api/0.1.0/historicData?\" + query_filters\n        historic_headers = {\n            \"apikey\": self.entity_api_key,\n            \"Content-Type\": \"application/json\"\n        }\n        historic_query_data = json.dumps({\n            \"query\": {\n                \"match\": {\n                    \"key\": entity\n                }\n            }\n        })\n        with self.no_ssl_verification():\n            r = requests.get(historic_url, data=historic_query_data, headers=historic_headers)\n        response = dict()\n        if \"No API key\" in str(r.content.decode(\"utf-8\")):\n            response[\"status\"] = \"failure\"\n        else:\n            r = r.content.decode(\"utf-8\")\n            response = r\n        return response",
    "docstring": "This function allows an entity to access the historic data.\n\n        Args:\n            entity        (string): Name of the device to listen to\n            query_filters (string): Elastic search response format string\n                                    example, \"pretty=true&size=10\""
  },
  {
    "code": "def imagej_shape(shape, rgb=None):\n    shape = tuple(int(i) for i in shape)\n    ndim = len(shape)\n    if 1 > ndim > 6:\n        raise ValueError('invalid ImageJ hyperstack: not 2 to 6 dimensional')\n    if rgb is None:\n        rgb = shape[-1] in (3, 4) and ndim > 2\n    if rgb and shape[-1] not in (3, 4):\n        raise ValueError('invalid ImageJ hyperstack: not a RGB image')\n    if not rgb and ndim == 6 and shape[-1] != 1:\n        raise ValueError('invalid ImageJ hyperstack: not a non-RGB image')\n    if rgb or shape[-1] == 1:\n        return (1, ) * (6 - ndim) + shape\n    return (1, ) * (5 - ndim) + shape + (1,)",
    "docstring": "Return shape normalized to 6D ImageJ hyperstack TZCYXS.\n\n    Raise ValueError if not a valid ImageJ hyperstack shape.\n\n    >>> imagej_shape((2, 3, 4, 5, 3), False)\n    (2, 3, 4, 5, 3, 1)"
  },
  {
    "code": "def write_array_empty(self, key, value):\n        arr = np.empty((1,) * value.ndim)\n        self._handle.create_array(self.group, key, arr)\n        getattr(self.group, key)._v_attrs.value_type = str(value.dtype)\n        getattr(self.group, key)._v_attrs.shape = value.shape",
    "docstring": "write a 0-len array"
  },
  {
    "code": "def pad(obj, pad_length):\n    _check_supported(obj)\n    copied = deepcopy(obj)\n    copied.pad(pad_length)\n    return copied",
    "docstring": "Return a copy of the object with piano-roll padded with zeros at the end\n    along the time axis.\n\n    Parameters\n    ----------\n    pad_length : int\n        The length to pad along the time axis with zeros."
  },
  {
    "code": "def map_block_storage(service, pool, image):\n    cmd = [\n        'rbd',\n        'map',\n        '{}/{}'.format(pool, image),\n        '--user',\n        service,\n        '--secret',\n        _keyfile_path(service),\n    ]\n    check_call(cmd)",
    "docstring": "Map a RADOS block device for local use."
  },
  {
    "code": "def walk(self):\n        intervals = sorted(self._intervals)\n        def nextFull():\n            start, stop = intervals.pop(0)\n            while intervals:\n                if intervals[0][0] <= stop:\n                    _, thisStop = intervals.pop(0)\n                    if thisStop > stop:\n                        stop = thisStop\n                else:\n                    break\n            return (start, stop)\n        if intervals:\n            if intervals[0][0] > 0:\n                yield (self.EMPTY, (0, intervals[0][0]))\n            while intervals:\n                lastFull = nextFull()\n                yield (self.FULL, lastFull)\n                if intervals:\n                    yield (self.EMPTY, (lastFull[1], intervals[0][0]))\n            if lastFull[1] < self._targetLength:\n                yield (self.EMPTY, (lastFull[1], self._targetLength))\n        else:\n            yield (self.EMPTY, (0, self._targetLength))",
    "docstring": "Get the non-overlapping read intervals that match the subject.\n\n        @return: A generator that produces (TYPE, (START, END)) tuples, where\n            where TYPE is either self.EMPTY or self.FULL and (START, STOP) is\n            the interval. The endpoint (STOP) of the interval is not considered\n            to be in the interval. I.e., the interval is really [START, STOP)."
  },
  {
    "code": "def str_from_file(path):\n    with open(path) as f:\n        s = f.read().strip()\n    return s",
    "docstring": "Return file contents as string."
  },
  {
    "code": "def xpathNsLookup(self, prefix):\n        ret = libxml2mod.xmlXPathNsLookup(self._o, prefix)\n        return ret",
    "docstring": "Search in the namespace declaration array of the context\n           for the given namespace name associated to the given prefix"
  },
  {
    "code": "def _read_para_hip_mac_2(self, code, cbit, clen, *, desc, length, version):\n        _hmac = self._read_fileng(clen)\n        hip_mac_2 = dict(\n            type=desc,\n            critical=cbit,\n            length=clen,\n            hmac=_hmac,\n        )\n        _plen = length - clen\n        if _plen:\n            self._read_fileng(_plen)\n        return hip_mac_2",
    "docstring": "Read HIP HIP_MAC_2 parameter.\n\n        Structure of HIP HIP_MAC_2 parameter [RFC 7401]:\n             0                   1                   2                   3\n             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |             Type              |             Length            |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |                                                               |\n            |                             HMAC                              |\n            /                                                               /\n            /                               +-------------------------------+\n            |                               |            Padding            |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n            Octets      Bits        Name                            Description\n              0           0     hip_mac_2.type                  Parameter Type\n              1          15     hip_mac_2.critical              Critical Bit\n              2          16     hip_mac_2.length                Length of Contents\n              4          32     hip_mac_2.hmac                  HMAC\n              ?           ?     -                               Padding"
  },
  {
    "code": "def predict(self, data, num_iteration=None,\n                raw_score=False, pred_leaf=False, pred_contrib=False,\n                data_has_header=False, is_reshape=True, **kwargs):\n        predictor = self._to_predictor(copy.deepcopy(kwargs))\n        if num_iteration is None:\n            num_iteration = self.best_iteration\n        return predictor.predict(data, num_iteration,\n                                 raw_score, pred_leaf, pred_contrib,\n                                 data_has_header, is_reshape)",
    "docstring": "Make a prediction.\n\n        Parameters\n        ----------\n        data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse\n            Data source for prediction.\n            If string, it represents the path to txt file.\n        num_iteration : int or None, optional (default=None)\n            Limit number of iterations in the prediction.\n            If None, if the best iteration exists, it is used; otherwise, all iterations are used.\n            If <= 0, all iterations are used (no limits).\n        raw_score : bool, optional (default=False)\n            Whether to predict raw scores.\n        pred_leaf : bool, optional (default=False)\n            Whether to predict leaf index.\n        pred_contrib : bool, optional (default=False)\n            Whether to predict feature contributions.\n\n            Note\n            ----\n            If you want to get more explanations for your model's predictions using SHAP values,\n            like SHAP interaction values,\n            you can install the shap package (https://github.com/slundberg/shap).\n            Note that unlike the shap package, with ``pred_contrib`` we return a matrix with an extra\n            column, where the last column is the expected value.\n\n        data_has_header : bool, optional (default=False)\n            Whether the data has header.\n            Used only if data is string.\n        is_reshape : bool, optional (default=True)\n            If True, result is reshaped to [nrow, ncol].\n        **kwargs\n            Other parameters for the prediction.\n\n        Returns\n        -------\n        result : numpy array\n            Prediction result."
  },
  {
    "code": "def remove_gateway_router(self, router):\n        router_id = self._find_router_id(router)\n        return self.network_conn.remove_gateway_router(router=router_id)",
    "docstring": "Removes an external network gateway from the specified router"
  },
  {
    "code": "def get_OID_field(fs):\n    if arcpyFound == False:\n        raise Exception(\"ArcPy is required to use this function\")\n    desc = arcpy.Describe(fs)\n    if desc.hasOID:\n        return desc.OIDFieldName\n    return None",
    "docstring": "returns a featureset's object id field"
  },
  {
    "code": "def is_object(brain_or_object):\n    if is_portal(brain_or_object):\n        return True\n    if is_at_content(brain_or_object):\n        return True\n    if is_dexterity_content(brain_or_object):\n        return True\n    if is_brain(brain_or_object):\n        return True\n    return False",
    "docstring": "Check if the passed in object is a supported portal content object\n\n    :param brain_or_object: A single catalog brain or content object\n    :type brain_or_object: Portal Object\n    :returns: True if the passed in object is a valid portal content"
  },
  {
    "code": "def _validate(self):\n        if self.region_type not in regions_attributes:\n            raise ValueError(\"'{0}' is not a valid region type in this package\"\n                             .format(self.region_type))\n        if self.coordsys not in valid_coordsys['DS9'] + valid_coordsys['CRTF']:\n            raise ValueError(\"'{0}' is not a valid coordinate reference frame \"\n                             \"in astropy\".format(self.coordsys))",
    "docstring": "Checks whether all the attributes of this object is valid."
  },
  {
    "code": "def get_current_environment(self, note=None):\n\t\tshutit_global.shutit_global_object.yield_to_draw()\n\t\tself.handle_note(note)\n\t\tres = self.get_current_shutit_pexpect_session_environment().environment_id\n\t\tself.handle_note_after(note)\n\t\treturn res",
    "docstring": "Returns the current environment id from the current\n\t\tshutit_pexpect_session"
  },
  {
    "code": "def str2int(self, num):\n        radix, alphabet = self.radix, self.alphabet\n        if radix <= 36 and alphabet[:radix].lower() == BASE85[:radix].lower():\n            return int(num, radix)\n        ret = 0\n        lalphabet = alphabet[:radix]\n        for char in num:\n            if char not in lalphabet:\n                raise ValueError(\"invalid literal for radix2int() with radix \"\n                                 \"%d: '%s'\" % (radix, num))\n            ret = ret * radix + self.cached_map[char]\n        return ret",
    "docstring": "Converts a string into an integer.\n\n        If possible, the built-in python conversion will be used for speed\n        purposes.\n\n        :param num: A string that will be converted to an integer.\n\n        :rtype: integer\n\n        :raise ValueError: when *num* is invalid"
  },
  {
    "code": "def get_all_destinations(self, server_id):\n        server = self._get_server(server_id)\n        return server.conn.EnumerateInstances(DESTINATION_CLASSNAME,\n                                              namespace=server.interop_ns)",
    "docstring": "Return all listener destinations in a WBEM server.\n\n        This function contacts the WBEM server and retrieves the listener\n        destinations by enumerating the instances of CIM class\n        \"CIM_ListenerDestinationCIMXML\" in the Interop namespace of the WBEM\n        server.\n\n        Parameters:\n\n          server_id (:term:`string`):\n            The server ID of the WBEM server, returned by\n            :meth:`~pywbem.WBEMSubscriptionManager.add_server`.\n\n        Returns:\n\n            :class:`py:list` of :class:`~pywbem.CIMInstance`: The listener\n            destination instances.\n\n        Raises:\n\n            Exceptions raised by :class:`~pywbem.WBEMConnection`."
  },
  {
    "code": "def columns(self, **kw):\n        fut = self._run_operation(self._impl.columns, **kw)\n        return fut",
    "docstring": "Creates a results set of column names in specified tables by\n        executing the ODBC SQLColumns function. Each row fetched has the\n        following columns.\n\n        :param table: the table tname\n        :param catalog: the catalog name\n        :param schema: the schmea name\n        :param column: string search pattern for column names."
  },
  {
    "code": "def stdchannel_redirected(stdchannel, dest_filename, fake=False):\n    if fake:\n        yield\n        return\n    oldstdchannel = dest_file = None\n    try:\n        oldstdchannel = os.dup(stdchannel.fileno())\n        dest_file = open(dest_filename, 'w')\n        os.dup2(dest_file.fileno(), stdchannel.fileno())\n        yield\n    finally:\n        if oldstdchannel is not None:\n            os.dup2(oldstdchannel, stdchannel.fileno())\n        if dest_file is not None:\n            dest_file.close()",
    "docstring": "A context manager to temporarily redirect stdout or stderr\n\n    e.g.:\n\n    with stdchannel_redirected(sys.stderr, os.devnull):\n        if compiler.has_function('clock_gettime', libraries=['rt']):\n            libraries.append('rt')"
  },
  {
    "code": "def needed(name, required):\n    return [\n        relative_field(r, name) if r and startswith_field(r, name) else None\n        for r in required\n    ]",
    "docstring": "RETURN SUBSET IF name IN REQUIRED"
  },
  {
    "code": "def _update_dict(self, newdict):\n        if self.bugzilla:\n            self.bugzilla.post_translation({}, newdict)\n            aliases = self.bugzilla._get_bug_aliases()\n            for newname, oldname in aliases:\n                if oldname not in newdict:\n                    continue\n                if newname not in newdict:\n                    newdict[newname] = newdict[oldname]\n                elif newdict[newname] != newdict[oldname]:\n                    log.debug(\"Update dict contained differing alias values \"\n                              \"d[%s]=%s and d[%s]=%s , dropping the value \"\n                              \"d[%s]\", newname, newdict[newname], oldname,\n                            newdict[oldname], oldname)\n                del(newdict[oldname])\n        for key in newdict.keys():\n            if key not in self._bug_fields:\n                self._bug_fields.append(key)\n        self.__dict__.update(newdict)\n        if 'id' not in self.__dict__ and 'bug_id' not in self.__dict__:\n            raise TypeError(\"Bug object needs a bug_id\")",
    "docstring": "Update internal dictionary, in a way that ensures no duplicate\n        entries are stored WRT field aliases"
  },
  {
    "code": "def nonull_dict(self):\n        return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}",
    "docstring": "Like dict, but does not hold any null values.\n\n        :return:"
  },
  {
    "code": "def code_memory_read(self, addr, num_bytes):\n        buf_size = num_bytes\n        buf = (ctypes.c_uint8 * buf_size)()\n        res = self._dll.JLINKARM_ReadCodeMem(addr, buf_size, buf)\n        if res < 0:\n            raise errors.JLinkException(res)\n        return list(buf)[:res]",
    "docstring": "Reads bytes from code memory.\n\n        Note:\n          This is similar to calling ``memory_read`` or ``memory_read8``,\n          except that this uses a cache and reads ahead.  This should be used\n          in instances where you want to read a small amount of bytes at a\n          time, and expect to always read ahead.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          addr (int): starting address from which to read\n          num_bytes (int): number of bytes to read\n\n        Returns:\n          A list of bytes read from the target.\n\n        Raises:\n          JLinkException: if memory could not be read."
  },
  {
    "code": "def handleStatus(self, version, code, message):\n        \"extends handleStatus to instantiate a local response object\"\n        proxy.ProxyClient.handleStatus(self, version, code, message)\n        self._response = client.Response(version, code, message, {}, None)",
    "docstring": "extends handleStatus to instantiate a local response object"
  },
  {
    "code": "def add_binary(self, data, address=0, overwrite=False):\n        address *= self.word_size_bytes\n        self._segments.add(_Segment(address,\n                                    address + len(data),\n                                    bytearray(data),\n                                    self.word_size_bytes),\n                           overwrite)",
    "docstring": "Add given data at given address. Set `overwrite` to ``True`` to\n        allow already added data to be overwritten."
  },
  {
    "code": "def remove_one(self):\n        self.__bulk.add_delete(self.__selector, _DELETE_ONE,\n                               collation=self.__collation)",
    "docstring": "Remove a single document matching the selector criteria."
  },
  {
    "code": "def to_json(self):\n        roots = []\n        for r in self.roots:\n            roots.append(r.to_json())\n        return {'roots': roots}",
    "docstring": "Returns the JSON representation of this graph."
  },
  {
    "code": "def save_expectations_config(\n        self,\n        filepath=None,\n        discard_failed_expectations=True,\n        discard_result_format_kwargs=True,\n        discard_include_configs_kwargs=True,\n        discard_catch_exceptions_kwargs=True,\n        suppress_warnings=False\n    ):\n        if filepath == None:\n            pass\n        expectations_config = self.get_expectations_config(\n            discard_failed_expectations,\n            discard_result_format_kwargs,\n            discard_include_configs_kwargs,\n            discard_catch_exceptions_kwargs,\n            suppress_warnings\n        )\n        expectation_config_str = json.dumps(expectations_config, indent=2)\n        open(filepath, 'w').write(expectation_config_str)",
    "docstring": "Writes ``_expectation_config`` to a JSON file.\n\n           Writes the DataAsset's expectation config to the specified JSON ``filepath``. Failing expectations \\\n           can be excluded from the JSON expectations config with ``discard_failed_expectations``. The kwarg key-value \\\n           pairs :ref:`result_format`, :ref:`include_config`, and :ref:`catch_exceptions` are optionally excluded from the JSON \\\n           expectations config.\n\n           Args:\n               filepath (string): \\\n                   The location and name to write the JSON config file to.\n               discard_failed_expectations (boolean): \\\n                   If True, excludes expectations that do not return ``success = True``. \\\n                   If False, all expectations are written to the JSON config file.\n               discard_result_format_kwargs (boolean): \\\n                   If True, the :ref:`result_format` attribute for each expectation is not written to the JSON config file. \\\n               discard_include_configs_kwargs (boolean): \\\n                   If True, the :ref:`include_config` attribute for each expectation is not written to the JSON config file.\\\n               discard_catch_exceptions_kwargs (boolean): \\\n                   If True, the :ref:`catch_exceptions` attribute for each expectation is not written to the JSON config \\\n                   file.\n               suppress_warnings (boolean): \\\n                  It True, all warnings raised by Great Expectations, as a result of dropped expectations, are \\\n                  suppressed."
  },
  {
    "code": "def create(self, publish):\n        target_url = self.client.get_url('PUBLISH', 'POST', 'create')\n        r = self.client.request('POST', target_url, json=publish._serialize())\n        return self.create_from_result(r.json())",
    "docstring": "Creates a new publish group."
  },
  {
    "code": "def to_ascii_hex(value: int, digits: int) -> str:\n    if digits < 1:\n        return ''\n    text = ''\n    for _ in range(0, digits):\n        text = chr(ord('0') + (value % 0x10)) + text\n        value //= 0x10\n    return text",
    "docstring": "Converts an int value to ASCII hex, as used by LifeSOS.\n       Unlike regular hex, it uses the first 6 characters that follow\n       numerics on the ASCII table instead of A - F."
  },
  {
    "code": "def _forward_mode(self, *args):\n        f_val, f_diff = self.f._forward_mode(*args)\n        g_val, g_diff = self.g._forward_mode(*args)\n        val = f_val + g_val\n        diff = f_diff + g_diff\n        return val, diff",
    "docstring": "Forward mode differentiation for a sum"
  },
  {
    "code": "def from_header(self, param_name, field):\n        return self.__from_source(param_name, field, lambda: request.headers, 'header')",
    "docstring": "A decorator that converts a request header into a function parameter based on the specified field.\n\n        :param str param_name: The parameter which receives the argument.\n        :param Field field: The field class or instance used to deserialize the request header to a Python object.\n        :return: A function"
  },
  {
    "code": "def get_empty_dimension(**kwargs):\n    dimension = JSONObject(Dimension())\n    dimension.id = None\n    dimension.name = ''\n    dimension.description = ''\n    dimension.project_id = None\n    dimension.units = []\n    return dimension",
    "docstring": "Returns a dimension object initialized with empty values"
  },
  {
    "code": "def scale_image(self):\n        new_width = int(self.figcanvas.fwidth *\n                        self._scalestep ** self._scalefactor)\n        new_height = int(self.figcanvas.fheight *\n                         self._scalestep ** self._scalefactor)\n        self.figcanvas.setFixedSize(new_width, new_height)",
    "docstring": "Scale the image size."
  },
  {
    "code": "def clear(self):\r\n        with self._hlock:\r\n            self.handlers.clear()\r\n        with self._mlock:\r\n            self.memoize.clear()",
    "docstring": "Discards all registered handlers and cached results"
  },
  {
    "code": "def qteGetMode(self, mode: str):\n        for item in self._qteModeList:\n            if item[0] == mode:\n                return item\n        return None",
    "docstring": "Return a tuple containing the ``mode``, its value, and\n        its associated ``QLabel`` instance.\n\n        |Args|\n\n        * ``mode`` (**str**): size and position of new window.\n\n        |Returns|\n\n        * (**str**, **object**, **QLabel**: (mode, value, label).\n\n        |Raises|\n\n        * **QtmacsArgumentError** if at least one argument has an invalid type."
  },
  {
    "code": "def _parse(read_method: Callable) -> HTTPResponse:\n        response = read_method(4096)\n        while b'HTTP/' not in response or b'\\r\\n\\r\\n' not in response:\n            response += read_method(4096)\n        fake_sock = _FakeSocket(response)\n        response = HTTPResponse(fake_sock)\n        response.begin()\n        return response",
    "docstring": "Trick to standardize the API between sockets and SSLConnection objects."
  },
  {
    "code": "def _comparator_lt(filter_value, tested_value):\n    if is_string(filter_value):\n        value_type = type(tested_value)\n        try:\n            filter_value = value_type(filter_value)\n        except (TypeError, ValueError):\n            if value_type is int:\n                try:\n                    filter_value = float(filter_value)\n                except (TypeError, ValueError):\n                    return False\n            else:\n                return False\n    try:\n        return tested_value < filter_value\n    except TypeError:\n        return False",
    "docstring": "Tests if the filter value is strictly greater than the tested value\n\n    tested_value < filter_value"
  },
  {
    "code": "def text(message: Text,\n         default: Text = \"\",\n         validate: Union[Type[Validator],\n                         Callable[[Text], bool],\n                         None] = None,\n         qmark: Text = DEFAULT_QUESTION_PREFIX,\n         style: Optional[Style] = None,\n         **kwargs: Any) -> Question:\n    merged_style = merge_styles([DEFAULT_STYLE, style])\n    validator = build_validator(validate)\n    def get_prompt_tokens():\n        return [(\"class:qmark\", qmark),\n                (\"class:question\", ' {} '.format(message))]\n    p = PromptSession(get_prompt_tokens,\n                      style=merged_style,\n                      validator=validator,\n                      **kwargs)\n    p.default_buffer.reset(Document(default))\n    return Question(p.app)",
    "docstring": "Prompt the user to enter a free text message.\n\n       This question type can be used to prompt the user for some text input.\n\n       Args:\n           message: Question text\n\n           default: Default value will be returned if the user just hits\n                    enter.\n\n           validate: Require the entered value to pass a validation. The\n                     value can not be submited until the validator accepts\n                     it (e.g. to check minimum password length).\n\n                     This can either be a function accepting the input and\n                     returning a boolean, or an class reference to a\n                     subclass of the prompt toolkit Validator class.\n\n           qmark: Question prefix displayed in front of the question.\n                  By default this is a `?`\n\n           style: A custom color and style for the question parts. You can\n                  configure colors as well as font types for different elements.\n\n       Returns:\n           Question: Question instance, ready to be prompted (using `.ask()`)."
  },
  {
    "code": "def analyze_frames(cls, workdir):\r\n        record = cls(None, workdir)\r\n        obj = {}\r\n        with open(os.path.join(workdir, 'frames', 'frames.json')) as f:\r\n            obj = json.load(f)\r\n        record.device_info = obj['device']\r\n        record.frames = obj['frames']\r\n        record.analyze_all()\r\n        record.save()",
    "docstring": "generate draft from recorded frames"
  },
  {
    "code": "def array_append(path, *values, **kwargs):\n    return _gen_4spec(LCB_SDCMD_ARRAY_ADD_LAST, path,\n                      MultiValue(*values),\n                      create_path=kwargs.pop('create_parents', False),\n                      **kwargs)",
    "docstring": "Add new values to the end of an array.\n\n    :param path: Path to the array. The path should contain the *array itself*\n        and not an element *within* the array\n    :param values: one or more values to append\n    :param create_parents: Create the array if it does not exist\n\n    .. note::\n\n        Specifying multiple values in `values` is more than just syntactical\n        sugar. It allows the server to insert the values as one single unit.\n        If you have multiple values to append to the same array, ensure they\n        are specified as multiple arguments to `array_append` rather than\n        multiple `array_append` commands to :cb_bmeth:`mutate_in`\n\n    This operation is only valid in :cb_bmeth:`mutate_in`.\n\n    .. seealso:: :func:`array_prepend`, :func:`upsert`"
  },
  {
    "code": "def stats(self, ops=(min, max, np.median, sum)):\n        names = [op.__name__ for op in ops]\n        ops = [_zero_on_type_error(op) for op in ops]\n        columns = [[op(column) for op in ops] for column in self.columns]\n        table = type(self)().with_columns(zip(self.labels, columns))\n        stats = table._unused_label('statistic')\n        table[stats] = names\n        table.move_to_start(stats)\n        return table",
    "docstring": "Compute statistics for each column and place them in a table."
  },
  {
    "code": "def get_list_by_name(self, display_name):\n        if not display_name:\n            raise ValueError('Must provide a valid list display name')\n        url = self.build_url(self._endpoints.get('get_list_by_name').format(display_name=display_name))\n        response = self.con.get(url)\n        if not response:\n            return []\n        data = response.json()\n        return self.list_constructor(parent=self, **{self._cloud_data_key: data})",
    "docstring": "Returns a sharepoint list based on the display name of the list"
  },
  {
    "code": "def get_queryset(self):\n        queryset = super(MostVotedManager, self).get_queryset()\n        sql =\n        messages = queryset.extra(\n            select={\n                'vote_count': sql,\n            }\n        )\n        return messages.order_by('-vote_count', 'received_time')",
    "docstring": "Query for the most voted messages sorting by the sum of\n        voted and after by date."
  },
  {
    "code": "def load_pretrained(self, wgts_fname:str, itos_fname:str, strict:bool=True):\n        \"Load a pretrained model and adapts it to the data vocabulary.\"\n        old_itos = pickle.load(open(itos_fname, 'rb'))\n        old_stoi = {v:k for k,v in enumerate(old_itos)}\n        wgts = torch.load(wgts_fname, map_location=lambda storage, loc: storage)\n        if 'model' in wgts: wgts = wgts['model']\n        wgts = convert_weights(wgts, old_stoi, self.data.train_ds.vocab.itos)\n        self.model.load_state_dict(wgts, strict=strict)",
    "docstring": "Load a pretrained model and adapts it to the data vocabulary."
  },
  {
    "code": "def end_task_type(self, task_type_str):\n        assert (\n            task_type_str in self._task_dict\n        ), \"Task type has not been started yet: {}\".format(task_type_str)\n        self._log_progress()\n        del self._task_dict[task_type_str]",
    "docstring": "Call when processing of all tasks of the given type is completed, typically\n        just after exiting a loop that processes many tasks of the given type.\n\n        Progress messages logged at intervals will typically not include the final entry\n        which shows that processing is 100% complete, so a final progress message is\n        logged here."
  },
  {
    "code": "def yield_once(iterator):\n    @wraps(iterator)\n    def yield_once_generator(*args, **kwargs):\n        yielded = set()\n        for item in iterator(*args, **kwargs):\n            if item not in yielded:\n                yielded.add(item)\n                yield item\n    return yield_once_generator",
    "docstring": "Decorator to make an iterator returned by a method yield each result only\n    once.\n\n    >>> @yield_once\n    ... def generate_list(foo):\n    ...     return foo\n    >>> list(generate_list([1, 2, 1]))\n    [1, 2]\n\n    :param iterator: Any method that returns an iterator\n    :return:         An method returning an iterator\n                     that yields every result only once at most."
  },
  {
    "code": "def pretrain(self, train_set, validation_set=None):\n        self.do_pretrain = True\n        def set_params_func(autoenc, autoencgraph):\n            params = autoenc.get_parameters(graph=autoencgraph)\n            self.encoding_w_.append(params['enc_w'])\n            self.encoding_b_.append(params['enc_b'])\n        return SupervisedModel.pretrain_procedure(\n            self, self.autoencoders, self.autoencoder_graphs,\n            set_params_func=set_params_func, train_set=train_set,\n            validation_set=validation_set)",
    "docstring": "Perform Unsupervised pretraining of the autoencoder."
  },
  {
    "code": "def get_chain(self, name, table=\"filter\"):\n        return [r for r in self.rules if r[\"table\"] == table and r[\"chain\"] == name]",
    "docstring": "Get the list of rules for a particular chain. Chain order is kept intact.\n\n        Args:\n            name (str): chain name, e.g. ``\n            table (str): table name, defaults to ``filter``\n\n        Returns:\n            list: rules"
  },
  {
    "code": "def stream(\n    streaming_fn,\n    status=200,\n    headers=None,\n    content_type=\"text/plain; charset=utf-8\",\n):\n    return StreamingHTTPResponse(\n        streaming_fn, headers=headers, content_type=content_type, status=status\n    )",
    "docstring": "Accepts an coroutine `streaming_fn` which can be used to\n    write chunks to a streaming response. Returns a `StreamingHTTPResponse`.\n\n    Example usage::\n\n        @app.route(\"/\")\n        async def index(request):\n            async def streaming_fn(response):\n                await response.write('foo')\n                await response.write('bar')\n\n            return stream(streaming_fn, content_type='text/plain')\n\n    :param streaming_fn: A coroutine accepts a response and\n        writes content to that response.\n    :param mime_type: Specific mime_type.\n    :param headers: Custom Headers."
  },
  {
    "code": "def save_metadata_json(self, filename: str, structure: JsonExportable) -> None:\n        if self.compress_json:\n            filename += '.json.xz'\n        else:\n            filename += '.json'\n        save_structure_to_file(structure, filename)\n        if isinstance(structure, (Post, StoryItem)):\n            self.context.log('json', end=' ', flush=True)",
    "docstring": "Saves metadata JSON file of a structure."
  },
  {
    "code": "def rgb2cmy(self, img, whitebg=False):\n        tmp = img*1.0\n        if whitebg:\n            tmp = (1.0 - (img - img.min())/(img.max() - img.min()))\n        out = tmp*0.0\n        out[:,:,0] = (tmp[:,:,1] + tmp[:,:,2])/2.0\n        out[:,:,1] = (tmp[:,:,0] + tmp[:,:,2])/2.0\n        out[:,:,2] = (tmp[:,:,0] + tmp[:,:,1])/2.0\n        return out",
    "docstring": "transforms image from RGB to CMY"
  },
  {
    "code": "def edit_tab(self, index):\r\n        self.setFocus(True)\r\n        self.tab_index = index\r\n        rect = self.main.tabRect(index)\r\n        rect.adjust(1, 1, -2, -1)\r\n        self.setFixedSize(rect.size())\r\n        self.move(self.main.mapToGlobal(rect.topLeft()))\r\n        text = self.main.tabText(index)\r\n        text = text.replace(u'&', u'')\r\n        if self.split_char:\r\n            text = text.split(self.split_char)[self.split_index]\r\n        self.setText(text)\r\n        self.selectAll()\r\n        if not self.isVisible():\r\n            self.show()",
    "docstring": "Activate the edit tab."
  },
  {
    "code": "def delete(self, database, key, callback=None):\n        token = self._get_token()\n        self._enqueue(self._PendingItem(token, BlobCommand(token=token, database=database,\n                                                           content=DeleteCommand(key=key.bytes)),\n                                        callback))",
    "docstring": "Delete an item from the given database.\n\n        :param database: The database from which to delete the value.\n        :type database: .BlobDatabaseID\n        :param key: The key to delete.\n        :type key: uuid.UUID\n        :param callback: A callback to be called on success or failure."
  },
  {
    "code": "def cartesian_product(arrays, flat=True, copy=False):\n    arrays = np.broadcast_arrays(*np.ix_(*arrays))\n    if flat:\n        return tuple(arr.flatten() if copy else arr.flat for arr in arrays)\n    return tuple(arr.copy() if copy else arr for arr in arrays)",
    "docstring": "Efficient cartesian product of a list of 1D arrays returning the\n    expanded array views for each dimensions. By default arrays are\n    flattened, which may be controlled with the flat flag. The array\n    views can be turned into regular arrays with the copy flag."
  },
  {
    "code": "def taxon_info(taxid, ncbi, outFH):\n    taxid = int(taxid)\n    tax_name = ncbi.get_taxid_translator([taxid])[taxid]\n    rank = list(ncbi.get_rank([taxid]).values())[0]\n    lineage = ncbi.get_taxid_translator(ncbi.get_lineage(taxid))\n    lineage = ['{}:{}'.format(k,v) for k,v in lineage.items()]\n    lineage = ';'.join(lineage)\n    x = [str(x) for x in [tax_name, taxid, rank, lineage]]\n    outFH.write('\\t'.join(x) + '\\n')",
    "docstring": "Write info on taxid"
  },
  {
    "code": "def undo(self):\n        if not self._wasUndo:\n            self._qteIndex = len(self._qteStack)\n        else:\n            self._qteIndex -= 1\n        self._wasUndo = True\n        if self._qteIndex <= 0:\n            return\n        undoObj = self._qteStack[self._qteIndex - 1]\n        undoObj = QtmacsUndoCommand(undoObj)\n        self._push(undoObj)\n        if (self._qteIndex - 1) == self._qteLastSavedUndoIndex:\n            self.qtesigSavedState.emit(QtmacsMessage())\n            self.saveState()",
    "docstring": "Undo the last command by adding its inverse action to the stack.\n\n        This method automatically takes care of applying the correct\n        inverse action when it is called consecutively (ie. without a\n        calling ``push`` in between).\n\n        The ``qtesigSavedState`` signal is triggered whenever enough undo\n        operations have been performed to put the document back into the\n        last saved state.\n\n        ..warning: The ``qtesigSaveState`` is triggered whenever the\n          logic of the undo operations **should** have led back to\n          that state, but since the ``UndoStack`` only stacks and\n          ``QtmacsUndoCommand`` objects it may well be the document is\n          **not** in the last saved state, eg. because not all\n          modifications were protected by undo objects, or because the\n          ``QtmacsUndoCommand`` objects have a bug. It is therefore\n          advisable to check in the calling class if the content is\n          indeed identical by comparing it with a temporarily stored\n          copy.\n\n        |Args|\n\n        * **None**\n\n        |Signals|\n\n        * ``qtesigSavedState``: the document is the last saved state.\n\n        |Returns|\n\n        * **None**\n\n        |Raises|\n\n        * **None**"
  },
  {
    "code": "def set_image_path(self, identifier, path):\n        f = open(path, 'rb')\n        self.set_image_data(identifier, f.read())\n        f.close()",
    "docstring": "Set data for an image mentioned in the template.\n\n        @param identifier: Identifier of the image; refer to the image in the\n        template by setting \"py3o.[identifier]\" as the name of that image.\n        @type identifier: string\n\n        @param path: Image path on the file system\n        @type path: string"
  },
  {
    "code": "def _get_lattice_parameters(lattice):\n    return np.array(np.sqrt(np.dot(lattice.T, lattice).diagonal()),\n                    dtype='double')",
    "docstring": "Return basis vector lengths\n\n    Parameters\n    ----------\n    lattice : array_like\n        Basis vectors given as column vectors\n        shape=(3, 3), dtype='double'\n\n    Returns\n    -------\n    ndarray, shape=(3,), dtype='double'"
  },
  {
    "code": "def descendants(self, node, relations=None, reflexive=False):\n        if reflexive:\n            decs = self.descendants(node, relations, reflexive=False)\n            decs.append(node)\n            return decs\n        g = None\n        if relations is None:\n            g = self.get_graph()\n        else:\n            g = self.get_filtered_graph(relations)\n        if node in g:\n            return list(nx.descendants(g, node))\n        else:\n            return []",
    "docstring": "Returns all descendants of specified node.\n\n        The default implementation is to use networkx, but some\n        implementations of the Ontology class may use a database or\n        service backed implementation, for large graphs.\n\n\n        Arguments\n        ---------\n        node : str\n            identifier for node in ontology\n        reflexive : bool\n            if true, return query node in graph\n        relations : list\n             relation (object property) IDs used to filter\n\n        Returns\n        -------\n        list[str]\n            descendant node IDs"
  },
  {
    "code": "def get_adjustable_form(self, element_dispatch):\n        adjustable_form = {}\n        for key in element_dispatch.keys():\n            adjustable_form[key] = element_dispatch[key]()\n        return adjustable_form",
    "docstring": "Create an adjustable form from an element dispatch table."
  },
  {
    "code": "def raw_diff(self):\n        udiff_copy = self.copy_iterator()\n        if self.__format == 'gitdiff':\n            udiff_copy = self._parse_gitdiff(udiff_copy)\n        return u''.join(udiff_copy)",
    "docstring": "Returns raw string as udiff"
  },
  {
    "code": "def get_max_levels_metadata(self):\n        metadata = dict(self._max_levels_metadata)\n        metadata.update({'existing_cardinal_values': self.my_osid_object_form._my_map['maxLevels']})\n        return Metadata(**metadata)",
    "docstring": "get the metadata for max levels"
  },
  {
    "code": "def _get_ancestors_path(self, model, levels=None):\n        if not issubclass(model, self.model):\n            raise ValueError(\n                \"%r is not a subclass of %r\" % (model, self.model))\n        ancestry = []\n        parent_link = model._meta.get_ancestor_link(self.model)\n        if levels:\n            levels -= 1\n        while parent_link is not None:\n            related = parent_link.remote_field\n            ancestry.insert(0, related.get_accessor_name())\n            if levels or levels is None:\n                parent_model = related.model\n                parent_link = parent_model._meta.get_ancestor_link(\n                    self.model)\n            else:\n                parent_link = None\n        return LOOKUP_SEP.join(ancestry)",
    "docstring": "Serves as an opposite to _get_subclasses_recurse, instead walking from\n        the Model class up the Model's ancestry and constructing the desired\n        select_related string backwards."
  },
  {
    "code": "def hx2dp(string):\n    string = stypes.stringToCharP(string)\n    lenout = ctypes.c_int(80)\n    errmsg = stypes.stringToCharP(lenout)\n    number = ctypes.c_double()\n    error = ctypes.c_int()\n    libspice.hx2dp_c(string, lenout, ctypes.byref(number), ctypes.byref(error),\n                     errmsg)\n    if not error.value:\n        return number.value\n    else:\n        return stypes.toPythonString(errmsg)",
    "docstring": "Convert a string representing a double precision number in a\n    base 16 scientific notation into its equivalent double\n    precision number.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/hx2dp_c.html\n\n    :param string: Hex form string to convert to double precision.\n    :type string: str\n    :return: Double precision value to be returned, Or Error Message.\n    :rtype: float or str"
  },
  {
    "code": "def StatFS(self, path=None):\n    if platform.system() == \"Windows\":\n      raise RuntimeError(\"os.statvfs not available on Windows\")\n    local_path = client_utils.CanonicalPathToLocalPath(path or self.path)\n    return os.statvfs(local_path)",
    "docstring": "Call os.statvfs for a given list of rdf_paths.\n\n    OS X and Linux only.\n\n    Note that a statvfs call for a network filesystem (e.g. NFS) that is\n    unavailable, e.g. due to no network, will result in the call blocking.\n\n    Args:\n      path: a Unicode string containing the path or None. If path is None the\n        value in self.path is used.\n\n    Returns:\n      posix.statvfs_result object\n    Raises:\n      RuntimeError: if called on windows"
  },
  {
    "code": "def set_state(self, state, *, index=0):\n        return self.set_values({\n            ATTR_DEVICE_STATE: int(state)\n        }, index=index)",
    "docstring": "Set state of a light."
  },
  {
    "code": "def read_file(self, url, location=None):\n        response = requests_retry_session().get(url, timeout=10.0)\n        response.raise_for_status()\n        text = response.text\n        if 'tab-width' in self.options:\n            text = text.expandtabs(self.options['tab-width'])\n        return text.splitlines(True)",
    "docstring": "Read content from the web by overriding\n        `LiteralIncludeReader.read_file`."
  },
  {
    "code": "def remove_volume(self):\n\t\tlvremove_cmd = ['sudo'] if self.lvm_command().sudo() is True else []\n\t\tlvremove_cmd.extend(['lvremove', '-f', self.volume_path()])\n\t\tsubprocess.check_output(lvremove_cmd, timeout=self.__class__.__lvm_snapshot_remove_cmd_timeout__)",
    "docstring": "Remove this volume\n\n\t\t:return: None"
  },
  {
    "code": "def _convert_simple_value_boolean_query_to_and_boolean_queries(tree, keyword):\n    def _create_operator_node(value_node):\n        base_node = value_node.op if isinstance(value_node, NotOp) else value_node\n        updated_base_node = KeywordOp(keyword, base_node) if keyword else ValueOp(base_node)\n        return NotOp(updated_base_node) if isinstance(value_node, NotOp) else updated_base_node\n    def _get_bool_op_type(bool_op):\n        return AndOp if isinstance(bool_op, And) else OrOp\n    new_tree_root = _get_bool_op_type(tree.bool_op)(None, None)\n    current_tree = new_tree_root\n    previous_tree = tree\n    while True:\n        current_tree.left = _create_operator_node(previous_tree.left)\n        if not isinstance(previous_tree.right, SimpleValueBooleanQuery):\n            current_tree.right = _create_operator_node(previous_tree.right)\n            break\n        previous_tree = previous_tree.right\n        current_tree.right = _get_bool_op_type(previous_tree.bool_op)(None, None)\n        current_tree = current_tree.right\n    return new_tree_root",
    "docstring": "Chain SimpleValueBooleanQuery values into chained AndOp queries with the given current Keyword."
  },
  {
    "code": "def get_directory_list_doc(self, configs):\n    if not isinstance(configs, (tuple, list)):\n      configs = [configs]\n    util.check_list_type(configs, dict, 'configs', allow_none=False)\n    return self.__directory_list_descriptor(configs)",
    "docstring": "JSON dict description of a protorpc.remote.Service in list format.\n\n    Args:\n      configs: Either a single dict or a list of dicts containing the service\n        configurations to list.\n\n    Returns:\n      dict, The directory list document as a JSON dict."
  },
  {
    "code": "def is_url(path):\n        try:\n            parse_result = urlparse(path)\n            return all((parse_result.scheme, parse_result.netloc, parse_result.path))\n        except ValueError:\n            return False",
    "docstring": "Test if path represents a valid URL.\n\n        :param str path: Path to file.\n        :return: True if path is valid url string, False otherwise.\n        :rtype: :py:obj:`True` or :py:obj:`False`"
  },
  {
    "code": "def save_form(self, request, form, change):\n        name = form.cleaned_data['name']\n        origin_url = form.cleaned_data['origin_url']\n        res = ClonedRepo(name=name, origin=origin_url)\n        LOG.info(\"New repo form produced %s\" % str(res))\n        form.save(commit=False)\n        return res",
    "docstring": "Here we pluck out the data to create a new cloned repo.\n\n           Form is an instance of NewRepoForm."
  },
  {
    "code": "def dumps(columns):\n    fp = BytesIO()\n    dump(columns, fp)\n    fp.seek(0)\n    return fp.read()",
    "docstring": "Serialize ``columns`` to a JSON formatted ``bytes`` object."
  },
  {
    "code": "def app(environ, start_response):\n    try:\n        if environ['REQUEST_METHOD'] == 'GET':\n            start_response('200 OK', [('content-type', 'text/html')])\n            return ['Hellow world!']\n        else:\n            start_response(\n                '405 Method Not Allowed', [('content-type', 'text/html')])\n            return ['']\n    except Exception as ex:\n        start_response(\n            '500 Internal Server Error',\n            [('content-type', 'text/html')],\n            sys.exc_info())\n        return _handle_exc(ex)",
    "docstring": "Simple WSGI application. Returns 200 OK response with 'Hellow world!' in\n    the body for GET requests. Returns 405 Method Not Allowed for all other\n    methods.\n\n    Returns 500 Internal Server Error if an exception is thrown. The response\n    body will not include the error or any information about it. The error and\n    its stack trace will be reported to FogBugz via BugzScout, though.\n\n    :param environ: WSGI environ\n    :param start_response: function that accepts status string and headers"
  },
  {
    "code": "def files_cp(self, source, dest, **kwargs):\n        args = (source, dest)\n        return self._client.request('/files/cp', args, **kwargs)",
    "docstring": "Copies files within the MFS.\n\n        Due to the nature of IPFS this will not actually involve any of the\n        file's content being copied.\n\n        .. code-block:: python\n\n            >>> c.files_ls(\"/\")\n            {'Entries': [\n                {'Size': 0, 'Hash': '', 'Name': 'Software', 'Type': 0},\n                {'Size': 0, 'Hash': '', 'Name': 'test', 'Type': 0}\n            ]}\n            >>> c.files_cp(\"/test\", \"/bla\")\n            ''\n            >>> c.files_ls(\"/\")\n            {'Entries': [\n                {'Size': 0, 'Hash': '', 'Name': 'Software', 'Type': 0},\n                {'Size': 0, 'Hash': '', 'Name': 'bla', 'Type': 0},\n                {'Size': 0, 'Hash': '', 'Name': 'test', 'Type': 0}\n            ]}\n\n        Parameters\n        ----------\n        source : str\n            Filepath within the MFS to copy from\n        dest : str\n            Destination filepath with the MFS to which the file will be\n            copied to"
  },
  {
    "code": "def part(z, s):\n    r\n    if sage_included:\n        if s == 1: return np.real(z)\n        elif s == -1: return np.imag(z)\n        elif s == 0:\n            return z\n    else:\n        if s == 1: return z.real\n        elif s == -1: return z.imag\n        elif s == 0: return z",
    "docstring": "r\"\"\"Get the real or imaginary part of a complex number."
  },
  {
    "code": "def _import_parsers():\n    global ARCGIS_NODES\n    global ARCGIS_ROOTS\n    global ArcGISParser\n    global FGDC_ROOT\n    global FgdcParser\n    global ISO_ROOTS\n    global IsoParser\n    global VALID_ROOTS\n    if ARCGIS_NODES is None or ARCGIS_ROOTS is None or ArcGISParser is None:\n        from gis_metadata.arcgis_metadata_parser import ARCGIS_NODES\n        from gis_metadata.arcgis_metadata_parser import ARCGIS_ROOTS\n        from gis_metadata.arcgis_metadata_parser import ArcGISParser\n    if FGDC_ROOT is None or FgdcParser is None:\n        from gis_metadata.fgdc_metadata_parser import FGDC_ROOT\n        from gis_metadata.fgdc_metadata_parser import FgdcParser\n    if ISO_ROOTS is None or IsoParser is None:\n        from gis_metadata.iso_metadata_parser import ISO_ROOTS\n        from gis_metadata.iso_metadata_parser import IsoParser\n    if VALID_ROOTS is None:\n        VALID_ROOTS = {FGDC_ROOT}.union(ARCGIS_ROOTS + ISO_ROOTS)",
    "docstring": "Lazy imports to prevent circular dependencies between this module and utils"
  },
  {
    "code": "def put(self, template_name):\n        self.reqparse.add_argument('template', type=str, required=True)\n        args = self.reqparse.parse_args()\n        template = db.Template.find_one(template_name=template_name)\n        if not template:\n            return self.make_response('No such template found', HTTP.NOT_FOUND)\n        changes = diff(template.template, args['template'])\n        template.template = args['template']\n        template.is_modified = True\n        db.session.add(template)\n        db.session.commit()\n        auditlog(\n            event='template.update',\n            actor=session['user'].username,\n            data={\n                'template_name': template_name,\n                'template_changes': changes\n            }\n        )\n        return self.make_response('Template {} has been updated'.format(template_name))",
    "docstring": "Update a template"
  },
  {
    "code": "def _valid_locales(locales, normalize):\n    if normalize:\n        normalizer = lambda x: locale.normalize(x.strip())\n    else:\n        normalizer = lambda x: x.strip()\n    return list(filter(can_set_locale, map(normalizer, locales)))",
    "docstring": "Return a list of normalized locales that do not throw an ``Exception``\n    when set.\n\n    Parameters\n    ----------\n    locales : str\n        A string where each locale is separated by a newline.\n    normalize : bool\n        Whether to call ``locale.normalize`` on each locale.\n\n    Returns\n    -------\n    valid_locales : list\n        A list of valid locales."
  },
  {
    "code": "def attr_sep(self, new_sep: str) -> None:\n        self._attr_sep = new_sep\n        self._filters_tree = self._generate_filters_tree()",
    "docstring": "Set the new value for the attribute separator.\n        \n        When the new value is assigned a new tree is generated."
  },
  {
    "code": "def commit(\n            self,\n            message: str,\n            files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None,\n            allow_empty: bool = False,\n    ):\n        message = str(message)\n        LOGGER.debug('message: %s', message)\n        files_to_add = self._sanitize_files_to_add(files_to_add)\n        LOGGER.debug('files to add: %s', files_to_add)\n        if not message:\n            LOGGER.error('empty commit message')\n            sys.exit(-1)\n        if os.getenv('APPVEYOR'):\n            LOGGER.info('committing on AV, adding skip_ci tag')\n            message = self.add_skip_ci_to_commit_msg(message)\n        if files_to_add is None:\n            self.stage_all()\n        else:\n            self.reset_index()\n            self.stage_subset(*files_to_add)\n        if self.index_is_empty() and not allow_empty:\n            LOGGER.error('empty commit')\n            sys.exit(-1)\n        self.repo.index.commit(message=message)",
    "docstring": "Commits changes to the repo\n\n        :param message: first line of the message\n        :type message: str\n        :param files_to_add: files to commit\n        :type files_to_add: optional list of str\n        :param allow_empty: allow dummy commit\n        :type allow_empty: bool"
  },
  {
    "code": "def clamp(color, min_v, max_v):\n    h, s, v = rgb_to_hsv(*map(down_scale, color))\n    min_v, max_v = map(down_scale, (min_v, max_v))\n    v = min(max(min_v, v), max_v)\n    return tuple(map(up_scale, hsv_to_rgb(h, s, v)))",
    "docstring": "Clamps a color such that the value is between min_v and max_v."
  },
  {
    "code": "def to_nullable_string(value):\n        if value == None:\n            return None\n        if type(value) == datetime.date:\n            return value.isoformat()\n        if type(value) == datetime.datetime:\n            if value.tzinfo == None:\n                return value.isoformat() + \"Z\"\n            else:\n                return value.isoformat()\n        if type(value) == list:\n            builder = ''\n            for element in value:\n                if len(builder) > 0:\n                    builder = builder + \",\"\n                builder = builder + element\n            return builder.__str__()\n        return str(value)",
    "docstring": "Converts value into string or returns None when value is None.\n\n        :param value: the value to convert.\n\n        :return: string value or None when value is None."
  },
  {
    "code": "def remove_duplicates(self, configs=None):\n        if configs is None:\n            c = self.configs\n        else:\n            c = configs\n        struct = c.view(c.dtype.descr * 4)\n        configs_unique = np.unique(struct).view(c.dtype).reshape(-1, 4)\n        if configs is None:\n            self.configs = configs_unique\n        else:\n            return configs_unique",
    "docstring": "remove duplicate entries from 4-point configurations. If no\n        configurations are provided, then use self.configs. Unique\n        configurations are only returned if configs is not None.\n\n        Parameters\n        ----------\n        configs: Nx4 numpy.ndarray, optional\n            remove duplicates from these configurations instead from\n            self.configs.\n\n        Returns\n        -------\n        configs_unique: Kx4 numpy.ndarray\n            unique configurations. Only returned if configs is not None"
  },
  {
    "code": "def download_saved_posts(self, max_count: int = None, fast_update: bool = False,\n                             post_filter: Optional[Callable[[Post], bool]] = None) -> None:\n        self.context.log(\"Retrieving saved posts...\")\n        count = 1\n        for post in Profile.from_username(self.context, self.context.username).get_saved_posts():\n            if max_count is not None and count > max_count:\n                break\n            if post_filter is not None and not post_filter(post):\n                self.context.log(\"<{} skipped>\".format(post), flush=True)\n                continue\n            self.context.log(\"[{:>3}] \".format(count), end=str(), flush=True)\n            count += 1\n            with self.context.error_catcher('Download saved posts'):\n                downloaded = self.download_post(post, target=':saved')\n                if fast_update and not downloaded:\n                    break",
    "docstring": "Download user's saved pictures.\n\n        :param max_count: Maximum count of pictures to download\n        :param fast_update: If true, abort when first already-downloaded picture is encountered\n        :param post_filter: function(post), which returns True if given picture should be downloaded"
  },
  {
    "code": "def look_at(self, x, y, z):\n        for camera in self.cameras:\n            camera.look_at(x, y, z)",
    "docstring": "Converges the two cameras to look at the specific point"
  },
  {
    "code": "def make_basic_table(self, file_type):\n        table_data = {sample: items['kv']\n                for sample, items\n                in self.mod_data[file_type].items()\n        }\n        table_headers = {}\n        for column_header, (description, header_options) in file_types[file_type]['kv_descriptions'].items():\n            table_headers[column_header] = {\n                    'rid': '{}_{}_bbmstheader'.format(file_type, column_header),\n                    'title': column_header,\n                    'description': description,\n            }\n            table_headers[column_header].update(header_options)\n        tconfig = {\n            'id': file_type + '_bbm_table',\n            'namespace': 'BBTools'\n        }\n        for sample in table_data:\n            for key, value in table_data[sample].items():\n                try:\n                    table_data[sample][key] = float(value)\n                except ValueError:\n                    pass\n        return table.plot(table_data, table_headers, tconfig)",
    "docstring": "Create table of key-value items in 'file_type'."
  },
  {
    "code": "def configure(project=LOGGING_PROJECT):\n    if not project:\n        sys.stderr.write('!! Error: The $LOGGING_PROJECT enviroment '\n                         'variable is required in order to set up cloud logging. '\n                         'Cloud logging is disabled.\\n')\n        return\n    try:\n        with contextlib.redirect_stderr(io.StringIO()):\n            client = glog.Client(project)\n            client.setup_logging(logging.INFO)\n    except:\n        logging.basicConfig(level=logging.INFO)\n        sys.stderr.write('!! Cloud logging disabled\\n')",
    "docstring": "Configures cloud logging\n\n    This is called for all main calls. If a $LOGGING_PROJECT is environment\n    variable configured, then STDERR and STDOUT are redirected to cloud\n    logging."
  },
  {
    "code": "def _clean_text(self, branch):\r\n        if branch.text and self.input_text_formatter:\r\n            branch.text = self.input_text_formatter(branch.text)\r\n        try:\r\n            for child in branch:\r\n                self._clean_text(child)\r\n                if branch.text and branch.text.find(child.text) >= 0:\r\n                    branch.text = branch.text.replace(child.text, '', 1)\r\n        except TypeError:\n            pass",
    "docstring": "Remove text from node if same text exists in its children.\r\n            Apply string formatter if set."
  },
  {
    "code": "def folder2db(folder_name, debug, energy_limit, skip_folders,\n              goto_reaction):\n    folder_name = folder_name.rstrip('/')\n    skip = []\n    for s in skip_folders.split(', '):\n        for sk in s.split(','):\n            skip.append(sk)\n    pub_id = _folder2db.main(folder_name, debug, energy_limit,\n                             skip, goto_reaction)\n    if pub_id:\n        print('')\n        print('')\n        print('Ready to release the data?')\n        print(\n            \"  Send it to the Catalysis-Hub server with 'cathub db2server {folder_name}/{pub_id}.db'.\".format(**locals()))\n        print(\"  Then log in at www.catalysis-hub.org/upload/ to verify and release. \")",
    "docstring": "Read folder and collect data in local sqlite3 database"
  },
  {
    "code": "def get_module_files(src_directory, blacklist, list_all=False):\n    files = []\n    for directory, dirnames, filenames in os.walk(src_directory):\n        if directory in blacklist:\n            continue\n        _handle_blacklist(blacklist, dirnames, filenames)\n        if not list_all and \"__init__.py\" not in filenames:\n            dirnames[:] = ()\n            continue\n        for filename in filenames:\n            if _is_python_file(filename):\n                src = os.path.join(directory, filename)\n                files.append(src)\n    return files",
    "docstring": "given a package directory return a list of all available python\n    module's files in the package and its subpackages\n\n    :type src_directory: str\n    :param src_directory:\n      path of the directory corresponding to the package\n\n    :type blacklist: list or tuple\n    :param blacklist: iterable\n      list of files or directories to ignore.\n\n    :type list_all: bool\n    :param list_all:\n        get files from all paths, including ones without __init__.py\n\n    :rtype: list\n    :return:\n      the list of all available python module's files in the package and\n      its subpackages"
  },
  {
    "code": "def validate_pattern(fn):\n    directory, pattern = parse_pattern(fn)\n    if directory is None:\n        print_err(\"Invalid pattern {}.\".format(fn))\n        return None, None\n    target = resolve_path(directory)\n    mode = auto(get_mode, target)\n    if not mode_exists(mode):\n        print_err(\"cannot access '{}': No such file or directory\".format(fn))\n        return None, None\n    if not mode_isdir(mode):\n        print_err(\"cannot access '{}': Not a directory\".format(fn))\n        return None, None\n    return target, pattern",
    "docstring": "On success return an absolute path and a pattern.\n    Otherwise print a message and return None, None"
  },
  {
    "code": "def _get_texture(arr, default, n_items, from_bounds):\n    if not hasattr(default, '__len__'):\n        default = [default]\n    n_cols = len(default)\n    if arr is None:\n        arr = np.tile(default, (n_items, 1))\n    assert arr.shape == (n_items, n_cols)\n    arr = arr[np.newaxis, ...].astype(np.float64)\n    assert arr.shape == (1, n_items, n_cols)\n    assert len(from_bounds) == 2\n    m, M = map(float, from_bounds)\n    assert np.all(arr >= m)\n    assert np.all(arr <= M)\n    arr = (arr - m) / (M - m)\n    assert np.all(arr >= 0)\n    assert np.all(arr <= 1.)\n    return arr",
    "docstring": "Prepare data to be uploaded as a texture.\n\n    The from_bounds must be specified."
  },
  {
    "code": "def expand_models(self, target, data):\n        if isinstance(data, dict):\n            data = data.values()\n        for chunk in data:\n            if target in chunk:\n                yield self.init_target_object(target, chunk)\n            else:\n                for key, item in chunk.items():\n                    yield self.init_single_object(key, item)",
    "docstring": "Generates all objects from given data."
  },
  {
    "code": "def int_imf_dm(m1,m2,m,imf,bywhat='bymass',integral='normal'):\n    ind_m = (m >= min(m1,m2)) & (m <= max(m1,m2))\n    if integral is 'normal':\n        int_func = sc.integrate.trapz\n    elif integral is 'cum':\n        int_func = sc.integrate.cumtrapz\n    else:\n        print(\"Error in int_imf_dm: don't know how to integrate\")\n        return 0\n    if bywhat is 'bymass':\n        return int_func(m[ind_m]*imf[ind_m],m[ind_m])\n    elif bywhat is 'bynumber':\n        return int_func(imf[ind_m],m[ind_m])\n    else:\n        print(\"Error in int_imf_dm: don't know by what to integrate\")\n        return 0",
    "docstring": "Integrate IMF between m1 and m2.\n\n    Parameters\n    ----------\n    m1 : float\n        Min mass\n    m2 : float\n        Max mass\n    m : float\n        Mass array\n    imf : float\n        IMF array\n    bywhat : string, optional\n        'bymass' integrates the mass that goes into stars of\n        that mass interval; or 'bynumber' which integrates the number\n        of stars in that mass interval.  The default is 'bymass'.\n    integrate : string, optional\n        'normal' uses sc.integrate.trapz; 'cum' returns cumulative\n        trapezoidal integral.  The default is 'normal'."
  },
  {
    "code": "def finditer_noregex(string, sub, whole_word):\n    start = 0\n    while True:\n        start = string.find(sub, start)\n        if start == -1:\n            return\n        if whole_word:\n            if start:\n                pchar = string[start - 1]\n            else:\n                pchar = ' '\n            try:\n                nchar = string[start + len(sub)]\n            except IndexError:\n                nchar = ' '\n            if nchar in DocumentWordsProvider.separators and \\\n                    pchar in DocumentWordsProvider.separators:\n                yield start\n            start += len(sub)\n        else:\n            yield start\n            start += 1",
    "docstring": "Search occurrences using str.find instead of regular expressions.\n\n    :param string: string to parse\n    :param sub: search string\n    :param whole_word: True to select whole words only"
  },
  {
    "code": "def get_aligned_collection(self, value=0, data_type=None, unit=None, mutable=None):\n        header = self._check_aligned_header(data_type, unit)\n        values = self._check_aligned_value(value)\n        if mutable is None:\n            collection = self.__class__(header, values, self.datetimes)\n        else:\n            if self._enumeration is None:\n                self._get_mutable_enumeration()\n            if mutable is False:\n                col_obj = self._enumeration['immutable'][self._collection_type]\n            else:\n                col_obj = self._enumeration['mutable'][self._collection_type]\n            collection = col_obj(header, values, self.datetimes)\n        collection._validated_a_period = self._validated_a_period\n        return collection",
    "docstring": "Return a Collection aligned with this one composed of one repeated value.\n\n        Aligned Data Collections are of the same Data Collection class, have the same\n        number of values and have matching datetimes.\n\n        Args:\n            value: A value to be repeated in the aliged collection values or\n                A list of values that has the same length as this collection.\n                Default: 0.\n            data_type: The data type of the aligned collection. Default is to\n                use the data type of this collection.\n            unit: The unit of the aligned collection. Default is to\n                use the unit of this collection or the base unit of the\n                input data_type (if it exists).\n            mutable: An optional Boolean to set whether the returned aligned\n                collection is mutable (True) or immutable (False). The default is\n                None, which will simply set the aligned collection to have the\n                same mutability as the starting collection."
  },
  {
    "code": "def _build_from(baseip):\n    from ipaddress import ip_address\n    try:\n        ip_address(baseip)\n    except ValueError:\n        if 'http' not in baseip[0:4].lower():\n            baseip = urlunsplit(['http', baseip, '', '', ''])\n        spl = urlsplit(baseip)\n        if '.xml' not in spl.path:\n            sep = '' if spl.path.endswith('/') else '/'\n            spl = spl._replace(path=spl.path+sep+'description.xml')\n        return spl.geturl()\n    else:\n        return  urlunsplit(('http', baseip, '/description.xml', '', ''))",
    "docstring": "Build URL for description.xml from ip"
  },
  {
    "code": "def unlink_user_account(self, id, provider, user_id):\n        url = self._url('{}/identities/{}/{}'.format(id, provider, user_id))\n        return self.client.delete(url)",
    "docstring": "Unlink a user account\n\n        Args:\n            id (str): The user_id of the user identity.\n\n            provider (str): The type of identity provider (e.g: facebook).\n\n            user_id (str): The unique identifier for the user for the identity.\n\n        See: https://auth0.com/docs/api/management/v2#!/Users/delete_user_identity_by_user_id"
  },
  {
    "code": "def switch(scm, to_branch, verbose, fake):\n    scm.fake = fake\n    scm.verbose = fake or verbose\n    scm.repo_check()\n    if to_branch is None:\n        scm.display_available_branches()\n        raise click.BadArgumentUsage('Please specify a branch to switch to')\n    scm.stash_log()\n    status_log(scm.checkout_branch, 'Switching to {0}.'.format(\n        crayons.yellow(to_branch)), to_branch)\n    scm.unstash_log()",
    "docstring": "Switches from one branch to another, safely stashing and restoring local changes."
  },
  {
    "code": "def perform_request(self, request_type, *args, **kwargs):\n        req = api_request(request_type, *args, **kwargs)\n        res = self.send_request(req)\n        return res",
    "docstring": "Create and send a request.\n\n        `request_type` is the request type (string). This is used to look up a\n        plugin, whose request class is instantiated and passed the remaining\n        arguments passed to this function."
  },
  {
    "code": "def worker_edit(worker, lbn, settings, profile='default'):\n    settings['cmd'] = 'update'\n    settings['mime'] = 'prop'\n    settings['w'] = lbn\n    settings['sw'] = worker\n    return _do_http(settings, profile)['worker.result.type'] == 'OK'",
    "docstring": "Edit the worker settings\n\n    Note: http://tomcat.apache.org/connectors-doc/reference/status.html\n    Data Parameters for the standard Update Action\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt '*' modjk.worker_edit node1 loadbalancer1 \"{'vwf': 500, 'vwd': 60}\"\n        salt '*' modjk.worker_edit node1 loadbalancer1 \"{'vwf': 500, 'vwd': 60}\" other-profile"
  },
  {
    "code": "def get_app_names(self):\n        app_names = set()\n        for name in self.apps:\n            app_names.add(name)\n        return app_names",
    "docstring": "Return application names.\n\n        Return the list of application names that are available in the\n        database.\n\n        Returns:\n            set of str."
  },
  {
    "code": "def split_state(self, state):\n        if self.state_separator:\n            return state.split(self.state_separator)\n        return list(state)",
    "docstring": "Split state string.\n\n        Parameters\n        ----------\n        state : `str`\n\n        Returns\n        -------\n        `list` of `str`"
  },
  {
    "code": "def _get_dis_func(self, union):\n        union_types = union.__args__\n        if NoneType in union_types:\n            union_types = tuple(\n                e for e in union_types if e is not NoneType\n            )\n        if not all(hasattr(e, \"__attrs_attrs__\") for e in union_types):\n            raise ValueError(\n                \"Only unions of attr classes supported \"\n                \"currently. Register a loads hook manually.\"\n            )\n        return create_uniq_field_dis_func(*union_types)",
    "docstring": "Fetch or try creating a disambiguation function for a union."
  },
  {
    "code": "def set_hostname(hostname=None, deploy=False):\n    if not hostname:\n        raise CommandExecutionError(\"Hostname option must not be none.\")\n    ret = {}\n    query = {'type': 'config',\n             'action': 'set',\n             'xpath': '/config/devices/entry[@name=\\'localhost.localdomain\\']/deviceconfig/system',\n             'element': '<hostname>{0}</hostname>'.format(hostname)}\n    ret.update(__proxy__['panos.call'](query))\n    if deploy is True:\n        ret.update(commit())\n    return ret",
    "docstring": "Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed.\n\n    CLI Example:\n\n    Args:\n        hostname (str): The hostname to set\n\n        deploy (bool): If true then commit the full candidate configuration, if false only set pending change.\n\n    .. code-block:: bash\n\n        salt '*' panos.set_hostname newhostname\n        salt '*' panos.set_hostname newhostname deploy=True"
  },
  {
    "code": "def resize(self, w, h):\n        self.plane_w = w\n        self.plane_h = h\n        self.plane_ratio = self.char_ratio * w / h\n        if self.crosshairs:\n            self.crosshairs_coord = ((w + 2) // 2, (h + 2) // 2)",
    "docstring": "Used when resizing the plane, resets the plane ratio factor.\n\n        :param w: New width of the visible section of the plane.\n        :param h: New height of the visible section of the plane."
  },
  {
    "code": "def _name_with_flags(self, include_restricted, title=None):\n        name = \"Special: \" if self.special else \"\"\n        name += self.name\n        if title:\n            name += \" - {}\".format(title)\n        if include_restricted and self.restricted:\n            name += \" (R)\"\n        name += \" (BB)\" if self.both_blocks else \"\"\n        name += \" (A)\" if self.administrative else \"\"\n        name += \" (S)\" if self.sticky else \"\"\n        name += \" (Deleted)\" if self.deleted else \"\"\n        return name",
    "docstring": "Generate the name with flags."
  },
  {
    "code": "def _write_multiplicons(self, filename):\n        mhead = '\\t'.join(['id', 'genome_x', 'list_x', 'parent', 'genome_y',\n                           'list_y', 'level', 'number_of_anchorpoints',\n                           'profile_length', 'begin_x', 'end_x', 'begin_y',\n                           'end_y', 'is_redundant'])\n        with open(filename, 'w') as fhandle:\n            fhandle.write(mhead + '\\n')\n            for mrow in self.multiplicons:\n                fhandle.write('\\t'.join([str(e) for e in mrow]) + '\\n')",
    "docstring": "Write multiplicons to file.\n\n            - filename, (str) location of output file"
  },
  {
    "code": "def _parse_prefix_query(self, query_str):\n        sp = smart_parsing.PrefixSmartParser()\n        query = sp.parse(query_str)\n        return query",
    "docstring": "Parse a smart search query for prefixes\n\n            This is a helper function to smart_search_prefix for easier unit\n            testing of the parser."
  },
  {
    "code": "def get_history(self):\n        if hasattr(self, '_history'):\n            return self._history\n        try:\n            self._history = APICallDayHistory.objects.get(\n                user=self.user, creation_date=now().date())\n        except APICallDayHistory.DoesNotExist:\n            self._history = APICallDayHistory(user=self.user)\n            self._history.amount_api_calls = 0\n        return self._history",
    "docstring": "Returns the history from cache or DB or a newly created one."
  },
  {
    "code": "def to_representation(self, value):\n        value = apply_subfield_projection(self, value, deep=True)\n        return super().to_representation(value)",
    "docstring": "Project outgoing native value."
  },
  {
    "code": "def find_one(self, collection, selector={}):\n        for _id, doc in self.collection_data.data.get(collection, {}).items():\n            doc.update({'_id': _id})\n            if selector == {}:\n                return doc\n            for key, value in selector.items():\n                if key in doc and doc[key] == value:\n                    return doc\n        return None",
    "docstring": "Return one item from a collection\n\n        Arguments:\n        collection - collection to search\n\n        Keyword Arguments:\n        selector - the query (default returns first item found)"
  },
  {
    "code": "def get_leading_spaces(data):\n    spaces = ''\n    m = re.match(r'^(\\s*)', data)\n    if m:\n        spaces = m.group(1)\n    return spaces",
    "docstring": "Get the leading space of a string if it is not empty\n\n    :type data: str"
  },
  {
    "code": "def check_link_and_get_info(self, target_id=0xFF):\n        for _ in range(0, 5):\n            if self._update_info(target_id):\n                if self._in_boot_cb:\n                    self._in_boot_cb.call(True, self.targets[\n                        target_id].protocol_version)\n                if self._info_cb:\n                    self._info_cb.call(self.targets[target_id])\n                return True\n        return False",
    "docstring": "Try to get a connection with the bootloader by requesting info\n        5 times. This let roughly 10 seconds to boot the copter ..."
  },
  {
    "code": "def get_urls(self):\n        urls = super(LayoutAdmin, self).get_urls()\n        my_urls = patterns(\n            '',\n            url(\n                r'^placeholder_data/(?P<id>\\d+)/$',\n                self.admin_site.admin_view(self.placeholder_data_view),\n                name='layout_placeholder_data',\n            )\n        )\n        return my_urls + urls",
    "docstring": "Add ``layout_placeholder_data`` URL."
  },
  {
    "code": "def check_for_invalid_columns(\n    problems: List, table: str, df: DataFrame\n) -> List:\n    r = cs.GTFS_REF\n    valid_columns = r.loc[r[\"table\"] == table, \"column\"].values\n    for col in df.columns:\n        if col not in valid_columns:\n            problems.append(\n                [\"warning\", f\"Unrecognized column {col}\", table, []]\n            )\n    return problems",
    "docstring": "Check for invalid columns in the given GTFS DataFrame.\n\n    Parameters\n    ----------\n    problems : list\n        A four-tuple containing\n\n        1. A problem type (string) equal to ``'error'`` or ``'warning'``;\n           ``'error'`` means the GTFS is violated;\n           ``'warning'`` means there is a problem but it is not a\n           GTFS violation\n        2. A message (string) that describes the problem\n        3. A GTFS table name, e.g. ``'routes'``, in which the problem\n           occurs\n        4. A list of rows (integers) of the table's DataFrame where the\n           problem occurs\n\n    table : string\n        Name of a GTFS table\n    df : DataFrame\n        The GTFS table corresponding to ``table``\n\n    Returns\n    -------\n    list\n        The ``problems`` list extended as follows.\n        Check whether the DataFrame contains extra columns not in the\n        GTFS and append to the problems list one warning for each extra\n        column."
  },
  {
    "code": "def ssad(patch, cols, splits):\n    sad_results = sad(patch, cols, splits, clean=False)\n    for i, sad_result in enumerate(sad_results):\n        if i == 0:\n            fulldf = sad_result[1]\n            fulldf.columns = ['spp', '0']\n        else:\n            fulldf[str(i)] = sad_result[1]['y']\n    result_list = []\n    for _, row in fulldf.iterrows():\n        row_values_array = np.array(row[1:], dtype=float)\n        result_list.append((row[0], pd.DataFrame({'y': row_values_array})))\n    return result_list",
    "docstring": "Calculates an empirical intra-specific spatial abundance distribution\n\n    Parameters\n    ----------\n    {0}\n\n    Returns\n    -------\n    {1} Result has one column giving the individuals of species in each\n    subplot.\n\n    Notes\n    -----\n    {2}\n\n    {3}\n\n    Examples\n    --------\n\n    {4}\n\n    >>> # Get the spatial abundance distribution for all species for each of\n    >>> # the cells in the ANBO plot\n    >>> all_spp_ssads = meco.empirical.ssad(pat, cols='spp_col:spp; count_col:count', splits='row:4; column:4')\n\n    >>> # Convert to dict for easy searching\n    >>> all_ssads_dict = dict(all_spp_ssads)\n\n    >>> # Look up the spatial abundance distribution for 'grass'\n    >>> all_ssads_dict['grass']\n         y\n    0    42\n    1    20\n    2    60\n    3    60\n    4    88\n    5    86\n    6    20\n    7     0\n    8   110\n    9    12\n    10  115\n    11  180\n    12  160\n    13  120\n    14   26\n    15   11\n\n    >>> # Each value in 'y' gives the abundance of grass in one of the 16 cells\n\n    See http://www.macroeco.org/tutorial_macroeco.html for additional\n    examples and explanation"
  },
  {
    "code": "def handle_update(self, options):\n        username = options[\"username\"]\n        try:\n            user = User.objects.get(username=username)\n        except User.DoesNotExist:\n            raise CommandError(\"User %s does not exist\" % username)\n        if options[\"email\"]:\n            user.email = options[\"email\"]\n        if options[\"active\"] in [True, False]:\n            user.is_active = options[\"active\"]\n        if options[\"staff\"] in [True, False]:\n            user.is_staff = options[\"staff\"]\n        if options[\"superuser\"] in [True, False]:\n            user.is_superuser = options[\"superuser\"]\n        user.save()",
    "docstring": "Update existing user"
  },
  {
    "code": "def rpc_stop(server_state):\n    rpc_srv = server_state['rpc']\n    if rpc_srv is not None:\n        log.info(\"Shutting down RPC\")\n        rpc_srv.stop_server()\n        rpc_srv.join()\n        log.info(\"RPC joined\")\n    else:\n        log.info(\"RPC already joined\")\n    server_state['rpc'] = None",
    "docstring": "Stop the global RPC server thread"
  },
  {
    "code": "def update_nanopubstore_start_dt(url: str, start_dt: str):\n    hostname = urllib.parse.urlsplit(url)[1]\n    start_dates_doc = state_mgmt.get(start_dates_doc_key)\n    if not start_dates_doc:\n        start_dates_doc = {\n            \"_key\": start_dates_doc_key,\n            \"start_dates\": [{\"nanopubstore\": hostname, \"start_dt\": start_dt}],\n        }\n        state_mgmt.insert(start_dates_doc)\n    else:\n        for idx, start_date in enumerate(start_dates_doc[\"start_dates\"]):\n            if start_date[\"nanopubstore\"] == hostname:\n                start_dates_doc[\"start_dates\"][idx][\"start_dt\"] = start_dt\n                break\n        else:\n            start_dates_doc[\"start_dates\"].append(\n                {\"nanopubstore\": hostname, \"start_dt\": start_dt}\n            )\n        state_mgmt.replace(start_dates_doc)",
    "docstring": "Add nanopubstore start_dt to belapi.state_mgmt collection\n\n    Args:\n        url: url of nanopubstore\n        start_dt: datetime of last query against nanopubstore for new ID's"
  },
  {
    "code": "def get_ordered_types(self):\n        types = self.get_types()\n        types_arr = np.array(types)\n        poss = [self.chrPos, self.startPos, self.stopPos]\n        if self.strandPos is not None:\n            poss.append(self.strandPos)\n        if self.otherPos:\n            for o in self.otherPos:\n                poss.append(o[0])\n        idx_sort = np.array(poss).argsort()\n        return types_arr[idx_sort].tolist()",
    "docstring": "Returns the ordered list of data types\n\n        :return: list of data types"
  },
  {
    "code": "def create_simulated_env(\n    output_dir, grayscale, resize_width_factor, resize_height_factor,\n    frame_stack_size, generative_model, generative_model_params,\n    random_starts=True, which_epoch_data=\"last\", **other_hparams\n):\n  a_bit_risky_defaults = {\n      \"game\": \"pong\",\n      \"real_batch_size\": 1,\n      \"rl_env_max_episode_steps\": -1,\n      \"max_num_noops\": 0\n  }\n  for key in a_bit_risky_defaults:\n    if key not in other_hparams:\n      other_hparams[key] = a_bit_risky_defaults[key]\n  hparams = hparam.HParams(\n      grayscale=grayscale,\n      resize_width_factor=resize_width_factor,\n      resize_height_factor=resize_height_factor,\n      frame_stack_size=frame_stack_size,\n      generative_model=generative_model,\n      generative_model_params=generative_model_params,\n      **other_hparams\n  )\n  return load_data_and_make_simulated_env(\n      output_dir, wm_dir=None, hparams=hparams,\n      which_epoch_data=which_epoch_data,\n      random_starts=random_starts)",
    "docstring": "Create SimulatedEnv with minimal subset of hparams."
  },
  {
    "code": "def check_signature(params):\n    if 'id' in params:\n        try:\n            id_int = int(params['id'][0])\n        except:\n            my_log_message(args, syslog.LOG_INFO, \"Non-numerical client id (%s) in request.\" % (params['id'][0]))\n            return False, None\n        key = client_ids.get(id_int)\n        if key:\n            if 'h' in params:\n                sig = params['h'][0]\n                good_sig = make_signature(params, key)\n                if sig == good_sig:\n                    return True, key\n                else:\n                    my_log_message(args, syslog.LOG_INFO, \"Bad signature from client id '%i' (%s, expected %s).\" \\\n                                       % (id_int, sig, good_sig))\n            else:\n                my_log_message(args, syslog.LOG_INFO, \"Client id (%i) but no HMAC in request.\" % (id_int))\n                return False, key\n        else:\n            my_log_message(args, syslog.LOG_INFO, \"Unknown client id '%i'\" % (id_int))\n            return False, None\n    return True, None",
    "docstring": "Verify the signature of the parameters in an OTP v2.0 verify request.\n\n    Returns ValResultBool, Key"
  },
  {
    "code": "def remove_all_connections(provider_id):\n    provider = get_provider_or_404(provider_id)\n    ctx = dict(provider=provider.name, user=current_user)\n    deleted = _datastore.delete_connections(user_id=current_user.get_id(),\n                                            provider_id=provider_id)\n    if deleted:\n        after_this_request(_commit)\n        msg = ('All connections to %s removed' % provider.name, 'info')\n        connection_removed.send(current_app._get_current_object(),\n                                user=current_user._get_current_object(),\n                                provider_id=provider_id)\n    else:\n        msg = ('Unable to remove connection to %(provider)s' % ctx, 'error')\n    do_flash(*msg)\n    return redirect(request.referrer)",
    "docstring": "Remove all connections for the authenticated user to the\n    specified provider"
  },
  {
    "code": "def convert_general(value):\n    if isinstance(value, bool):\n        return \"true\" if value else \"false\"\n    elif isinstance(value, list):\n        value = [convert_general(item) for item in value]\n        value = convert_to_imgur_list(value)\n    elif isinstance(value, Integral):\n        return str(value)\n    elif 'pyimgur' in str(type(value)):\n        return str(getattr(value, 'id', value))\n    return value",
    "docstring": "Take a python object and convert it to the format Imgur expects."
  },
  {
    "code": "def lifetimes(self):\n        r\n        return -self._lag / np.log(np.diag(self.transition_matrix))",
    "docstring": "r\"\"\" Lifetimes of states of the hidden transition matrix\n\n        Returns\n        -------\n        l : ndarray(nstates)\n            state lifetimes in units of the input trajectory time step,\n            defined by :math:`-tau / ln | p_{ii} |, i = 1,...,nstates`, where\n            :math:`p_{ii}` are the diagonal entries of the hidden transition matrix."
  },
  {
    "code": "def OnLabelSizeIntCtrl(self, event):\n        self.attrs[\"labelsize\"] = event.GetValue()\n        post_command_event(self, self.DrawChartMsg)",
    "docstring": "Label size IntCtrl event handler"
  },
  {
    "code": "def set_cols_align(self, array):\n        self._check_row_size(array)\n        self._align = array\n        return self",
    "docstring": "Set the desired columns alignment\n\n        - the elements of the array should be either \"l\", \"c\" or \"r\":\n\n            * \"l\": column flushed left\n            * \"c\": column centered\n            * \"r\": column flushed right"
  },
  {
    "code": "def set_permission(permission, value, app):\n    script =\n    app_url = 'app://' + app\n    run_marionette_script(script % (permission, app_url, app_url, value), True)",
    "docstring": "Set a permission for the specified app\n       Value should be 'deny' or 'allow'"
  },
  {
    "code": "def update_redis(project: str, environment: str, feature: str, state: str) \\\n        -> None:\n    try:\n        hosts = RedisWrapper.connection_string_parser(\n            os.environ.get('REDIS_HOSTS'))\n    except RuntimeError as ex:\n        LOG.error(ex)\n        sys.exit(1)\n    for host in hosts:\n        LOG.info(\"connecting to %s:%s\", host.host, host.port)\n        try:\n            if valid_state(state):\n                new_state = state.lower()\n                redis = RedisWrapper(\n                    host.host,\n                    host.port,\n                    project,\n                    environment\n                )\n                redis.update_flag_record(new_state, feature)\n                create_file(project, environment, feature, new_state)\n                LOG.info(\"%s was successfully updated.\", feature)\n            else:\n                raise Exception('Invalid state: {0}, -s needs \\\n                    to be either on or off.'.format(state))\n        except KeyError as ex:\n            LOG.error(\"unable to update %s. Exception: %s\",\n                      host.host,\n                      ex)\n            sys.exit(1)",
    "docstring": "Update redis state for a feature flag.\n\n    :param project: LaunchDarkly project key.\n    :param environment: LaunchDarkly environment key.\n    :param feature: LaunchDarkly feature key.\n    :param state: State for a feature flag."
  },
  {
    "code": "def wait_until_stale(self, timeout=None):\n        timeout = timeout if timeout is not None else self.driver_wrapper.timeout\n        def wait():\n            WebDriverWait(self.driver, timeout).until(EC.staleness_of(self.element))\n            return self\n        return self.execute_and_handle_webelement_exceptions(wait, 'wait for staleness')",
    "docstring": "Waits for the element to go stale in the DOM\n\n        @type timeout:          int\n        @param timeout:         override for default timeout\n\n        @rtype:                 WebElementWrapper\n        @return:                Self"
  },
  {
    "code": "def _determine_leftpad(column, point_place):\n    ndigits_left = [_find_point(x) for x in column]\n    return [max((point_place - 1) - x, 0) for x in ndigits_left]",
    "docstring": "Find how many spaces to put before a column of numbers\n       so that all the decimal points line up\n\n    This function takes a column of decimal numbers, and returns a\n    vector containing the number of spaces to place before each number\n    so that (when possible) the decimal points line up.\n\n\n    Parameters\n    ----------\n    column : list\n        Numbers that will be printed as a column\n    point_place : int\n        Number of the character column to put the decimal point"
  },
  {
    "code": "def input_file(self, _container):\n        p = local.path(_container)\n        if set_input_container(p, CFG):\n            return\n        p = find_hash(CFG[\"container\"][\"known\"].value, container)\n        if set_input_container(p, CFG):\n            return\n        raise ValueError(\"The path '{0}' does not exist.\".format(p))",
    "docstring": "Find the input path of a uchroot container."
  },
  {
    "code": "def __get_smtp(self):\n\t\tuse_tls = self.config['shutit.core.alerting.emailer.use_tls']\n\t\tif use_tls:\n\t\t\tsmtp = SMTP(self.config['shutit.core.alerting.emailer.smtp_server'], self.config['shutit.core.alerting.emailer.smtp_port'])\n\t\t\tsmtp.starttls()\n\t\telse:\n\t\t\tsmtp = SMTP_SSL(self.config['shutit.core.alerting.emailer.smtp_server'], self.config['shutit.core.alerting.emailer.smtp_port'])\n\t\treturn smtp",
    "docstring": "Return the appropraite smtplib depending on wherther we're using TLS"
  },
  {
    "code": "def doDynamicValidation(self, request: Request):\n        self.execute_hook(NodeHooks.PRE_DYNAMIC_VALIDATION, request=request)\n        ledger_id, seq_no = self.seqNoDB.get_by_payload_digest(request.payload_digest)\n        if ledger_id is not None and seq_no is not None:\n            raise SuspiciousPrePrepare('Trying to order already ordered request')\n        ledger = self.getLedger(self.ledger_id_for_request(request))\n        for txn in ledger.uncommittedTxns:\n            if get_payload_digest(txn) == request.payload_digest:\n                raise SuspiciousPrePrepare('Trying to order already ordered request')\n        operation = request.operation\n        req_handler = self.get_req_handler(txn_type=operation[TXN_TYPE])\n        req_handler.validate(request)\n        self.execute_hook(NodeHooks.POST_DYNAMIC_VALIDATION, request=request)",
    "docstring": "State based validation"
  },
  {
    "code": "def parse_http_response(http_response: HttpResponse) -> 'environ.Response':\n    try:\n        response = environ.Response.deserialize(http_response.json())\n    except Exception as error:\n        response = environ.Response().fail(\n            code='INVALID_REMOTE_RESPONSE',\n            error=error,\n            message='Invalid HTTP response from remote connection'\n        ).console(\n            whitespace=1\n        ).response\n    response.http_response = http_response\n    return response",
    "docstring": "Returns a Cauldron response object parsed from the serialized JSON data\n    specified in the http_response argument. If the response doesn't contain\n    valid Cauldron response data, an error Cauldron response object is\n    returned instead.\n\n    :param http_response:\n        The response object from an http request that contains a JSON\n        serialized Cauldron response object as its body\n    :return:\n        The Cauldron response object for the given http response"
  },
  {
    "code": "def sg_sugar_func(func):\n    r\n    @wraps(func)\n    def wrapper(tensor, **kwargs):\n        out = func(tensor, tf.sg_opt(kwargs))\n        out._sugar = tf.sg_opt(func=func, arg=tf.sg_opt(kwargs)+sg_get_context(), prev=tensor)\n        out.sg_reuse = types.MethodType(sg_reuse, out)\n        return out\n    return wrapper",
    "docstring": "r\"\"\" Decorates a function `func` so that it can be a sugar function.\n    Sugar function can be used in a chainable manner.\n\n    Args:\n        func: function to decorate\n\n    Returns:\n      A sugar function."
  },
  {
    "code": "def get_longest_table(url='https://www.openoffice.org/dev_docs/source/file_extensions.html', header=0):\n    dfs = pd.read_html(url, header=header)\n    return longest_table(dfs)",
    "docstring": "Retrieve the HTML tables from a URL and return the longest DataFrame found\n\n    >>> get_longest_table('https://en.wikipedia.org/wiki/List_of_sovereign_states').columns\n    Index(['Common and formal names', 'Membership within the UN System[a]',\n       'Sovereignty dispute[b]',\n       'Further information on status and recognition of sovereignty[d]'],\n      dtype='object')"
  },
  {
    "code": "def is_visa_electron(n):\n    n, length = str(n), len(str(n))\n    form = ['026', '508', '844', '913', '917']\n    if length == 16:\n        if n[0] == '4':\n            if ''.join(n[1:4]) in form or ''.join(n[1:6]) == '17500':\n                return True\n    return False",
    "docstring": "Checks if credit card number fits the visa electron format."
  },
  {
    "code": "def dePeriod(arr):\n    diff= arr-nu.roll(arr,1,axis=1)\n    w= diff < -6.\n    addto= nu.cumsum(w.astype(int),axis=1)\n    return arr+_TWOPI*addto",
    "docstring": "make an array of periodic angles increase linearly"
  },
  {
    "code": "def encode(self, inputs, states=None, valid_length=None):\n        return self.encoder(self.src_embed(inputs), states, valid_length)",
    "docstring": "Encode the input sequence.\n\n        Parameters\n        ----------\n        inputs : NDArray\n        states : list of NDArrays or None, default None\n        valid_length : NDArray or None, default None\n\n        Returns\n        -------\n        outputs : list\n            Outputs of the encoder."
  },
  {
    "code": "def vi_return_param(self, index):\n        if index == 0:\n            return self.mu0\n        elif index == 1:\n            return np.log(self.sigma0)",
    "docstring": "Wrapper function for selecting appropriate latent variable for variational inference\n\n        Parameters\n        ----------\n        index : int\n            0 or 1 depending on which latent variable\n\n        Returns\n        ----------\n        The appropriate indexed parameter"
  },
  {
    "code": "def setData(self, type: str, data: str) -> None:\n        type = normalize_type(type)\n        if type in self.__data:\n            del self.__data[type]\n        self.__data[type] = data",
    "docstring": "Set data of type format.\n\n        :arg str type: Data format of the data, like 'text/plain'."
  },
  {
    "code": "def finish(self):\n        self.lines.reverse()\n        self._content = '\\n'.join(self.lines)\n        self.lines = None",
    "docstring": "Creates block of content with lines\n            belonging to fragment."
  },
  {
    "code": "def _ondim(self, dimension, valuestring):\n        try:\n            self.dimensions[dimension] = int(valuestring)\n        except ValueError:\n            self.dimensions[dimension] = 1\n            self.textctrls[dimension].SetValue(str(1))\n        if self.dimensions[dimension] < 1:\n            self.dimensions[dimension] = 1\n            self.textctrls[dimension].SetValue(str(1))",
    "docstring": "Converts valuestring to int and assigns result to self.dim\n\n        If there is an error (such as an empty valuestring) or if\n        the value is < 1, the value 1 is assigned to self.dim\n\n        Parameters\n        ----------\n\n        dimension: int\n        \\tDimension that is to be updated. Must be in [1:4]\n        valuestring: string\n        \\t A string that can be converted to an int"
  },
  {
    "code": "def relative(self):\n        if not self.is_absolute():\n            raise ValueError(\"URL should be absolute\")\n        val = self._val._replace(scheme=\"\", netloc=\"\")\n        return URL(val, encoded=True)",
    "docstring": "Return a relative part of the URL.\n\n        scheme, user, password, host and port are removed."
  },
  {
    "code": "def xrb_address_to_public_key(address):\n    address = bytearray(address, 'ascii')\n    if not address.startswith(b'xrb_'):\n        raise ValueError('address does not start with xrb_: %s' % address)\n    if len(address) != 64:\n        raise ValueError('address must be 64 chars long: %s' % address)\n    address = bytes(address)\n    key_b32xrb = b'1111' + address[4:56]\n    key_bytes = b32xrb_decode(key_b32xrb)[3:]\n    checksum = address[56:]\n    if b32xrb_encode(address_checksum(key_bytes)) != checksum:\n        raise ValueError('invalid address, invalid checksum: %s' % address)\n    return key_bytes",
    "docstring": "Convert an xrb address to public key in bytes\n\n    >>> xrb_address_to_public_key('xrb_1e3i81r51e3i81r51e3i81r51e3i'\\\n                                  '81r51e3i81r51e3i81r51e3imxssakuq')\n    b'00000000000000000000000000000000'\n\n    :param address: xrb address\n    :type address: bytes\n\n    :return: public key in bytes\n    :rtype: bytes\n\n    :raises ValueError:"
  },
  {
    "code": "def check_espeak(cls):\n        try:\n            from aeneas.textfile import TextFile\n            from aeneas.textfile import TextFragment\n            from aeneas.ttswrappers.espeakttswrapper import ESPEAKTTSWrapper\n            text = u\"From fairest creatures we desire increase,\"\n            text_file = TextFile()\n            text_file.add_fragment(TextFragment(language=u\"eng\", lines=[text], filtered_lines=[text]))\n            handler, output_file_path = gf.tmp_file(suffix=u\".wav\")\n            ESPEAKTTSWrapper().synthesize_multiple(text_file, output_file_path)\n            gf.delete_file(handler, output_file_path)\n            gf.print_success(u\"espeak         OK\")\n            return False\n        except:\n            pass\n        gf.print_error(u\"espeak         ERROR\")\n        gf.print_info(u\"  Please make sure you have espeak installed correctly\")\n        gf.print_info(u\"  and that its path is in your PATH environment variable\")\n        gf.print_info(u\"  You might also want to check that the espeak-data directory\")\n        gf.print_info(u\"  is set up correctly, for example, it has the correct permissions\")\n        return True",
    "docstring": "Check whether ``espeak`` can be called.\n\n        Return ``True`` on failure and ``False`` on success.\n\n        :rtype: bool"
  },
  {
    "code": "def surrounding_nodes(self, position):\n        n_node_index, n_node_position, n_node_error = self.nearest_node(position)\n        if n_node_error == 0.0:\n            index_mod = []\n            for i in range(len(n_node_index)):\n                new_point = np.asarray(n_node_position)\n                new_point[i] += 1.e-5*np.abs(new_point[i])\n                try:\n                    self.nearest_node(tuple(new_point))\n                    index_mod.append(-1)\n                except ValueError:\n                    index_mod.append(1)\n        else:\n            index_mod = []\n            for i in range(len(n_node_index)):\n                if n_node_position[i] > position[i]:\n                    index_mod.append(-1)\n                else:\n                    index_mod.append(1)\n        return tuple(n_node_index), tuple(index_mod)",
    "docstring": "Returns nearest node indices and direction of opposite node.\n\n        :param position: Position inside the mesh to search nearest node for as (x,y,z)\n        :return: Nearest node indices and direction of opposite node."
  },
  {
    "code": "def excluded_length(self):\n        return sum([shot.length for shot in self.shots if Exclude.LENGTH in shot.flags or Exclude.TOTAL in shot.flags])",
    "docstring": "Surveyed length which does not count toward the included total"
  },
  {
    "code": "def validate(self, cmd, messages=None):\n        valid = True\n        args  = [ arg for arg in cmd.args if arg is not None ]\n        if self.nargs != len(args):\n            valid = False\n            if messages is not None:\n                msg  = 'Expected %d arguments, but received %d.'\n                messages.append(msg % (self.nargs, len(args)))\n        for defn, value in zip(self.args, cmd.args):\n            if value is None:\n                valid = False\n                if messages is not None:\n                    messages.append('Argument \"%s\" is missing.' % defn.name)\n            elif defn.validate(value, messages) is False:\n                valid = False\n        if len(cmd._unrecognized) > 0:\n            valid = False\n            if messages is not None:\n                for name in cmd.unrecognized:\n                    messages.append('Argument \"%s\" is unrecognized.' % name)\n        return valid",
    "docstring": "Returns True if the given Command is valid, False otherwise.\n        Validation error messages are appended to an optional messages\n        array."
  },
  {
    "code": "def reread(self):\n        logger.debug(\"Loading credentials from %s\",\n                     os.path.abspath(self.creds_filename))\n        creds = {}\n        try:\n            with self.open_creds() as fp:\n                creds = yaml.safe_load(fp)\n        except IOError:\n            logger.info(\"No credentials file found at %s\",\n                        os.path.abspath(self.creds_filename))\n        except:\n            logger.exception(\"Error loading credentials file\")\n        if creds != self.creds:\n            self.creds = creds\n            return True\n        return False",
    "docstring": "Read and parse credentials file.\n        If something goes wrong, log exception and continue."
  },
  {
    "code": "def _generate_feed(self, feed_data):\n        atom_feed = self._render_html('atom.xml', feed_data)\n        feed_path = os.path.join(os.getcwd(), 'public', 'atom.xml')\n        with codecs.open(feed_path, 'wb', 'utf-8') as f:\n            f.write(atom_feed)",
    "docstring": "render feed file with data"
  },
  {
    "code": "def run(self, gates, n_qubits, *args, **kwargs):\n        return self._run(gates, n_qubits, args, kwargs)",
    "docstring": "Run the backend."
  },
  {
    "code": "def ones_comp_sum16(num1: int, num2: int) -> int:\n    carry = 1 << 16\n    result = num1 + num2\n    return result if result < carry else result + 1 - carry",
    "docstring": "Calculates the 1's complement sum for 16-bit numbers.\n\n    Args:\n        num1: 16-bit number.\n        num2: 16-bit number.\n\n    Returns:\n        The calculated result."
  },
  {
    "code": "def to_struct(self, value):\n        if self.str_format:\n            return value.strftime(self.str_format)\n        return value.strftime(self.default_format)",
    "docstring": "Cast `date` object to string."
  },
  {
    "code": "def disable_component(self, component):\n        if not isinstance(component, type):\n            component = component.__class__\n        self.enabled[component] = False\n        self.components[component] = None",
    "docstring": "Force a component to be disabled.\n\n        :param component: can be a class or an instance."
  },
  {
    "code": "def _process_thread(self, client):\n    file_list = self.files\n    if not file_list:\n      return\n    print('Filefinder to collect {0:d} items'.format(len(file_list)))\n    flow_action = flows_pb2.FileFinderAction(\n        action_type=flows_pb2.FileFinderAction.DOWNLOAD)\n    flow_args = flows_pb2.FileFinderArgs(\n        paths=file_list,\n        action=flow_action,)\n    flow_id = self._launch_flow(client, 'FileFinder', flow_args)\n    self._await_flow(client, flow_id)\n    collected_flow_data = self._download_files(client, flow_id)\n    if collected_flow_data:\n      print('{0!s}: Downloaded: {1:s}'.format(flow_id, collected_flow_data))\n      fqdn = client.data.os_info.fqdn.lower()\n      self.state.output.append((fqdn, collected_flow_data))",
    "docstring": "Process a single client.\n\n    Args:\n      client: GRR client object to act on."
  },
  {
    "code": "def AddExtraShapes(extra_shapes_txt, graph):\n  print(\"Adding extra shapes from %s\" % extra_shapes_txt)\n  try:\n    tmpdir = tempfile.mkdtemp()\n    shutil.copy(extra_shapes_txt, os.path.join(tmpdir, 'shapes.txt'))\n    loader = transitfeed.ShapeLoader(tmpdir)\n    schedule = loader.Load()\n    for shape in schedule.GetShapeList():\n      print(\"Adding extra shape: %s\" % shape.shape_id)\n      graph.AddPoly(ShapeToPoly(shape))\n  finally:\n    if tmpdir:\n      shutil.rmtree(tmpdir)",
    "docstring": "Add extra shapes into our input set by parsing them out of a GTFS-formatted\n  shapes.txt file.  Useful for manually adding lines to a shape file, since it's\n  a pain to edit .shp files."
  },
  {
    "code": "def extract_zip(self, suffix, path='.'):\n        zip_fd, zip_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.zip')\n        os.close(zip_fd)\n        try:\n            _download_url(self.artifact_url(suffix), zip_fn)\n            LOG.info('.. extracting')\n            with zipfile.ZipFile(zip_fn) as zip_fp:\n                for info in zip_fp.infolist():\n                    _extract_file(zip_fp, info, path)\n        finally:\n            os.unlink(zip_fn)",
    "docstring": "Download and extract a zip artifact\n\n        @type suffix:\n        @param suffix:\n\n        @type path:\n        @param path:"
  },
  {
    "code": "def append(self, row_or_table):\n        if not row_or_table:\n            return\n        if isinstance(row_or_table, Table):\n            t = row_or_table\n            columns = list(t.select(self.labels)._columns.values())\n            n = t.num_rows\n        else:\n            if (len(list(row_or_table)) != self.num_columns):\n                raise Exception('Row should have '+ str(self.num_columns) + \" columns\")\n            columns, n = [[value] for value in row_or_table], 1\n        for i, column in enumerate(self._columns):\n            if self.num_rows:\n                self._columns[column] = np.append(self[column], columns[i])\n            else:\n                self._columns[column] = np.array(columns[i])\n        self._num_rows += n\n        return self",
    "docstring": "Append a row or all rows of a table. An appended table must have all\n        columns of self."
  },
  {
    "code": "async def capability_check(self, optional=None, required=None):\n        self._check_receive_loop()\n        await self.query(\n            \"version\", {\"optional\": optional or [], \"required\": required or []}\n        )",
    "docstring": "Perform a server capability check."
  },
  {
    "code": "def alpha(self, theta_x, theta_y, kwargs_lens, k=None):\n        beta_x, beta_y = self.ray_shooting(theta_x, theta_y, kwargs_lens)\n        alpha_x = theta_x - beta_x\n        alpha_y = theta_y - beta_y\n        return alpha_x, alpha_y",
    "docstring": "reduced deflection angle\n\n        :param theta_x: angle in x-direction\n        :param theta_y: angle in y-direction\n        :param kwargs_lens: lens model kwargs\n        :return:"
  },
  {
    "code": "def normalize_text(self, text):\n        if not self.editor.free_format:\n            text = ' ' * 6 + text[6:]\n        return text.upper()",
    "docstring": "Normalize text, when fixed format is ON, replace the first 6 chars by a space."
  },
  {
    "code": "def reverse_file(infile, outfile):\n    with open(infile, 'rb') as inf:\n        with open(outfile, 'wb') as outf:\n            reverse_fd(inf, outf)",
    "docstring": "Reverse the content of infile, write to outfile.\n    Both infile and outfile are filenames or filepaths."
  },
  {
    "code": "def get_session(self, account_id):\n        if account_id not in self.account_sessions:\n            if account_id not in self.config['accounts']:\n                raise AccountNotFound(\"account:%s is unknown\" % account_id)\n            self.account_sessions[account_id] = s = assumed_session(\n                self.config['accounts'][account_id]['role'], \"Sphere11\")\n            s._session.user_agent_name = \"Sphere11\"\n            s._session.user_agent_version = \"0.07\"\n        return self.account_sessions[account_id]",
    "docstring": "Get an active session in the target account."
  },
  {
    "code": "def add_marker_to_qtl(qtl, map_list):\n    closest = ''\n    diff = None\n    for marker in map_list:\n        if qtl[1] == marker[1]:\n            tmp_diff = float(qtl[2]) - float(marker[2])\n            if diff is None or abs(diff) > abs(tmp_diff):\n                diff = tmp_diff\n                closest = marker\n    if closest != '':\n        closest = closest[0]\n    return closest",
    "docstring": "Add the closest marker to the given QTL.\n\n    :arg qtl: a row of the QTL list.\n    :arg map_list: the genetic map containing the list of markers."
  },
  {
    "code": "def readDivPressure(fileName):\n    try:\n        df = pandas.read_csv(fileName, sep=None, engine='python')\n        pandasformat = True\n    except ValueError:\n        pandasformat = False\n    df.columns = ['site', 'divPressureValue']\n    scaleFactor = max(df[\"divPressureValue\"].abs())\n    if scaleFactor > 0:\n        df[\"divPressureValue\"] = [x / scaleFactor for x in df[\"divPressureValue\"]]\n    assert len(df['site'].tolist()) == len(set(df['site'].tolist())),\"There is at least one non-unique site in {0}\".format(fileName)\n    assert max(df[\"divPressureValue\"].abs()) <= 1, \"The scaling produced a diversifying pressure value with an absolute value greater than one.\"\n    sites = df['site'].tolist()\n    divPressure = {}\n    for r in sites:\n        divPressure[r] = df[df['site'] == r][\"divPressureValue\"].tolist()[0]\n    return divPressure",
    "docstring": "Reads in diversifying pressures from some file.\n\n    Scale diversifying pressure values so absolute value of the max value is 1,\n    unless all values are zero.\n\n    Args:\n        `fileName` (string or readable file-like object)\n            File holding diversifying pressure values. Can be\n            comma-, space-, or tab-separated file. The first column\n            is the site (consecutively numbered, sites starting\n            with one) and the second column is the diversifying pressure values.\n\n    Returns:\n        `divPressure` (dict keyed by ints)\n            `divPressure[r][v]` is the diversifying pressure value of site `r`."
  },
  {
    "code": "def _mirror_groups_from_stormpath(self):\n        APPLICATION = get_application()\n        sp_groups = [g.name for g in APPLICATION.groups]\n        missing_from_db, missing_from_sp = self._get_group_difference(sp_groups)\n        if missing_from_db:\n            groups_to_create = []\n            for g_name in missing_from_db:\n                groups_to_create.append(Group(name=g_name))\n            Group.objects.bulk_create(groups_to_create)",
    "docstring": "Helper method for saving to the local db groups\n        that are missing but are on Stormpath"
  },
  {
    "code": "def _load_greedy(self, module_name, dependencies, recursive):\n        found = module_name in self.modules\n        allmodules = list(self._pathfiles.keys())\n        i = 0\n        while not found and i < len(allmodules):\n            current = allmodules[i]\n            if not current in self._modulefiles:\n                self.parse(self._pathfiles[current], dependencies and recursive)                \n                found = module_name in self.modules\n            i += 1",
    "docstring": "Keeps loading modules in the filepaths dictionary until all have\n        been loaded or the module is found."
  },
  {
    "code": "def _message_callback(self, msg):\n        if msg.type == 'polytouch':\n            button = button_from_press(msg.note)\n            if button:\n                self.on_button(button, msg.value != 0)\n            elif msg.note == 127:\n                self.on_fader_touch(msg.value != 0)\n        elif msg.type == 'control_change' and msg.control == 0:\n            self._msb = msg.value\n        elif msg.type == 'control_change' and msg.control == 32:\n            self._fader = (self._msb << 7 | msg.value) >> 4\n            self.on_fader(self._fader)\n        elif msg.type == 'pitchwheel':\n            self.on_rotary(1 if msg.pitch < 0 else -1)\n        else:\n            print('Unhandled:', msg)",
    "docstring": "Callback function to handle incoming MIDI messages."
  },
  {
    "code": "def derivatives_factory(cls, coef, domain, kind, **kwargs):\n        basis_polynomial = cls._basis_polynomial_factory(kind)\n        return basis_polynomial(coef, domain).deriv()",
    "docstring": "Given some coefficients, return a the derivative of a certain kind of\n        orthogonal polynomial defined over a specific domain."
  },
  {
    "code": "def merge_periods(data):\n    newdata = sorted(data, key=lambda drange: drange[0])\n    end = 0\n    for period in newdata:\n        if period[0] != end and period[0] != (end - 1):\n            end = period[1]\n    dat = newdata\n    new_intervals = []\n    cur_start = None\n    cur_end = None\n    for (dt_start, dt_end) in dat:\n        if cur_end is None:\n            cur_start = dt_start\n            cur_end = dt_end\n            continue\n        else:\n            if cur_end >= dt_start:\n                cur_end = dt_end\n            else:\n                new_intervals.append((cur_start, cur_end))\n                cur_start = dt_start\n                cur_end = dt_end\n    new_intervals.append((cur_start, cur_end))\n    return new_intervals",
    "docstring": "Merge periods to have better continous periods.\n    Like 350-450, 400-600 => 350-600\n\n    :param data: list of periods\n    :type data: list\n    :return: better continous periods\n    :rtype: list"
  },
  {
    "code": "def create_header_from_telpars(telpars):\n    pars = [val.strip() for val in (';').join(telpars).split(';')\n            if val.strip() != '']\n    with warnings.catch_warnings():\n        warnings.simplefilter('ignore', fits.verify.VerifyWarning)\n        hdr = fits.Header(map(parse_hstring, pars))\n    return hdr",
    "docstring": "Create a list of fits header items from GTC telescope pars.\n\n    The GTC telescope server gives a list of string describing\n    FITS header items such as RA, DEC, etc.\n\n    Arguments\n    ---------\n    telpars : list\n        list returned by server call to getTelescopeParams"
  },
  {
    "code": "def get_client_calls_for_app(source_code):\n    parsed = parse_code(source_code)\n    parsed.parsed_ast = AppViewTransformer().visit(parsed.parsed_ast)\n    ast.fix_missing_locations(parsed.parsed_ast)\n    t = SymbolTableTypeInfer(parsed)\n    binder = t.bind_types()\n    collector = APICallCollector(binder)\n    api_calls = collector.collect_api_calls(parsed.parsed_ast)\n    return api_calls",
    "docstring": "Return client calls for a chalice app.\n\n    This is similar to ``get_client_calls`` except it will\n    automatically traverse into chalice views with the assumption\n    that they will be called."
  },
  {
    "code": "def mag_yaw(RAW_IMU, inclination, declination):\n    m = mag_rotation(RAW_IMU, inclination, declination)\n    (r, p, y) = m.to_euler()\n    y = degrees(y)\n    if y < 0:\n        y += 360\n    return y",
    "docstring": "estimate yaw from mag"
  },
  {
    "code": "def put_encryption_materials(self, cache_key, encryption_materials, plaintext_length, entry_hints=None):\n        return CryptoMaterialsCacheEntry(cache_key=cache_key, value=encryption_materials)",
    "docstring": "Does not add encryption materials to the cache since there is no cache to which to add them.\n\n        :param bytes cache_key: Identifier for entries in cache\n        :param encryption_materials: Encryption materials to add to cache\n        :type encryption_materials: aws_encryption_sdk.materials_managers.EncryptionMaterials\n        :param int plaintext_length: Length of plaintext associated with this request to the cache\n        :param entry_hints: Metadata to associate with entry (optional)\n        :type entry_hints: aws_encryption_sdk.caches.CryptoCacheEntryHints\n        :rtype: aws_encryption_sdk.caches.CryptoMaterialsCacheEntry"
  },
  {
    "code": "def find_pore_to_pore_distance(network, pores1=None, pores2=None):\n    r\n    from scipy.spatial.distance import cdist\n    p1 = sp.array(pores1, ndmin=1)\n    p2 = sp.array(pores2, ndmin=1)\n    coords = network['pore.coords']\n    return cdist(coords[p1], coords[p2])",
    "docstring": "r'''\n    Find the distance between all pores on set one to each pore in set 2\n\n    Parameters\n    ----------\n    network : OpenPNM Network Object\n        The network object containing the pore coordinates\n\n    pores1 : array_like\n        The pore indices of the first set\n\n    pores2 : array_Like\n        The pore indices of the second set.  It's OK if these indices are\n        partially or completely duplicating ``pores``.\n\n    Returns\n    -------\n    A distance matrix with ``len(pores1)`` rows and ``len(pores2)`` columns.\n    The distance between pore *i* in ``pores1`` and *j* in ``pores2`` is\n    located at *(i, j)* and *(j, i)* in the distance matrix."
  },
  {
    "code": "def _getModelData(self, modelData, parentItem=None):\n        if parentItem is None:\n            parentItem = self.rootItem\n        for item in parentItem.getChildren():\n            key = item.getItemData(0)\n            if item.childCount():\n                modelData[key] = odict()\n                self._getModelData(modelData[key], item)\n            else:\n                if isinstance(item.getItemData(2), float):\n                    modelData[key] = [item.getItemData(1), item.getItemData(2)]\n                else:\n                    modelData[key] = item.getItemData(1)",
    "docstring": "Return the data contained in the model."
  },
  {
    "code": "def association(self, group_xid):\n        association = {'groupXid': group_xid}\n        self._indicator_data.setdefault('associatedGroups', []).append(association)",
    "docstring": "Add association using xid value.\n\n        Args:\n            group_xid (str): The external id of the Group to associate."
  },
  {
    "code": "def camel_to_snake_case(string):\n    s = _1.sub(r'\\1_\\2', string)\n    return _2.sub(r'\\1_\\2', s).lower()",
    "docstring": "Converts 'string' presented in camel case to snake case.\n\n    e.g.: CamelCase => snake_case"
  },
  {
    "code": "def write(filename, groupname, items, times, features, properties=None,\n          dformat='dense', chunk_size='auto', sparsity=0.1, mode='a'):\n    sparsity = sparsity if dformat == 'sparse' else None\n    data = Data(items, times, features, properties=properties,\n                sparsity=sparsity, check=True)\n    Writer(filename, chunk_size=chunk_size).write(data, groupname, append=True)",
    "docstring": "Write h5features data in a HDF5 file.\n\n    This function is a wrapper to the Writer class. It has three purposes:\n\n    * Check parameters for errors (see details below),\n    * Create Items, Times and Features objects\n    * Send them to the Writer.\n\n    :param str filename: HDF5 file to be writted, potentially serving\n        as a container for many small files. If the file does not\n        exist, it is created. If the file is already a valid HDF5\n        file, try to append the data in it.\n\n    :param str groupname: Name of the group to write the data in, or\n        to append the data to if the group already exists in the file.\n\n    :param items: List of files from which the features where\n        extracted. Items must not contain duplicates.\n    :type items: list of str\n\n    :param times: Time value for the features array. Elements of\n        a 1D array are considered as the center of the time window\n        associated with the features. A 2D array must have 2 columns\n        corresponding to the begin and end timestamps of the features\n        time window.\n    :type times: list of  1D or 2D numpy arrays\n\n    :param features: Features should have\n        time along the lines and features along the columns\n        (accomodating row-major storage in hdf5 files).\n    :type features: list of 2D numpy arrays\n\n    :param properties: Optional. Properties associated with each\n        item. Properties describe the features associated with each\n        item in a dictionnary. It can store parameters or fields\n        recorded by the user.\n    :type properties: list of dictionnaries\n\n    :param str dformat: Optional. Which format to store the features\n        into (sparse or dense). Default is dense.\n\n    :param float chunk_size: Optional. In Mo, tuning parameter\n        corresponding to the size of a chunk in the h5file. By default\n        the chunk size is guessed automatically. Tis parameter is\n        ignored if the file already exists.\n\n    :param float sparsity: Optional. Tuning parameter corresponding to\n        the expected proportion (in [0, 1]) of non-zeros elements on\n        average in a single frame.\n\n    :param char mode: Optional. The mode for overwriting an existing\n        file, 'a' to append data to the file, 'w' to overwrite it\n\n    :raise IOError: if the filename is not valid or parameters are\n        inconsistent.\n\n    :raise NotImplementedError: if dformat == 'sparse'"
  },
  {
    "code": "def download_file(self, url, filename):\n        self.print_message(\"Downloading to file '%s' from URL '%s'\" % (filename, url))\n        try:\n            db_file = urllib2.urlopen(url)\n            with open(filename, 'wb') as output:\n                output.write(db_file.read())\n            db_file.close()\n        except Exception as e:\n            self.error(str(e))\n        self.print_message(\"File downloaded\")",
    "docstring": "Download file from url to filename."
  },
  {
    "code": "def save_hdf_metadata(filename, metadata, groupname=\"data\", mode=\"a\"):\n    with _h5py.File(filename, mode) as f:\n        for key, val in metadata.items():\n            f[groupname].attrs[key] = val",
    "docstring": "Save a dictionary of metadata to a group's attrs."
  },
  {
    "code": "def _compose(self, *args, **kwargs):\n        name = kwargs.pop('name', None)\n        if name:\n            name = c_str(name)\n        if len(args) != 0 and len(kwargs) != 0:\n            raise TypeError('compose only accept input Symbols \\\n                either as positional or keyword arguments, not both')\n        for arg in args:\n            if not isinstance(arg, SymbolBase):\n                raise TypeError('Compose expect `Symbol` as arguments')\n        for val in kwargs.values():\n            if not isinstance(val, SymbolBase):\n                raise TypeError('Compose expect `Symbol` as arguments')\n        num_args = len(args) + len(kwargs)\n        if len(kwargs) != 0:\n            keys = c_str_array(kwargs.keys())\n            args = c_handle_array(kwargs.values())\n        else:\n            keys = None\n            args = c_handle_array(kwargs.values())\n        check_call(_LIB.NNSymbolCompose(\n            self.handle, name, num_args, keys, args))",
    "docstring": "Compose symbol on inputs.\n\n        This call mutates the current symbol.\n\n        Parameters\n        ----------\n        args:\n            provide positional arguments\n\n        kwargs:\n            provide keyword arguments\n\n        Returns\n        -------\n        the resulting symbol"
  },
  {
    "code": "def create(*context, **kwargs):\n        items = context\n        context = ContextStack()\n        for item in items:\n            if item is None:\n                continue\n            if isinstance(item, ContextStack):\n                context._stack.extend(item._stack)\n            else:\n                context.push(item)\n        if kwargs:\n            context.push(kwargs)\n        return context",
    "docstring": "Build a ContextStack instance from a sequence of context-like items.\n\n        This factory-style method is more general than the ContextStack class's\n        constructor in that, unlike the constructor, the argument list\n        can itself contain ContextStack instances.\n\n        Here is an example illustrating various aspects of this method:\n\n        >>> obj1 = {'animal': 'cat', 'vegetable': 'carrot', 'mineral': 'copper'}\n        >>> obj2 = ContextStack({'vegetable': 'spinach', 'mineral': 'silver'})\n        >>>\n        >>> context = ContextStack.create(obj1, None, obj2, mineral='gold')\n        >>>\n        >>> context.get('animal')\n        'cat'\n        >>> context.get('vegetable')\n        'spinach'\n        >>> context.get('mineral')\n        'gold'\n\n        Arguments:\n\n          *context: zero or more dictionaries, ContextStack instances, or objects\n            with which to populate the initial context stack.  None\n            arguments will be skipped.  Items in the *context list are\n            added to the stack in order so that later items in the argument\n            list take precedence over earlier items.  This behavior is the\n            same as the constructor's.\n\n          **kwargs: additional key-value data to add to the context stack.\n            As these arguments appear after all items in the *context list,\n            in the case of key conflicts these values take precedence over\n            all items in the *context list.  This behavior is the same as\n            the constructor's."
  },
  {
    "code": "def ids_sharing_same_pgn(id_x, pgn_x, id_y, pgn_y):\n    for id_a, pgn_a in zip(id_x, pgn_x):\n        for id_b, pgn_b in zip(id_y, pgn_y):\n            if pgn_a == pgn_b:\n                yield (id_a, id_b)",
    "docstring": "Yield arbitration ids which has the same pgn."
  },
  {
    "code": "def get_connection(db_type, db_pth, user=None, password=None, name=None):\n    if db_type == 'sqlite':\n        print(db_pth)\n        conn = sqlite3.connect(db_pth)\n    elif db_type == 'mysql':\n        import mysql.connector\n        conn = mysql.connector.connect(user=user, password=password, database=name)\n    elif db_type == 'django_mysql':\n        from django.db import connection as conn\n    else:\n        print('unsupported database type: {}, choices are \"sqlite\", \"mysql\" or \"django_mysql\"'.format(db_type))\n    return conn",
    "docstring": "Get a connection to a SQL database. Can be used for SQLite, MySQL or Django MySQL database\n\n    Example:\n        >>> from msp2db.db import get_connection\n        >>> conn = get_connection('sqlite', 'library.db')\n\n    If using \"mysql\" mysql.connector needs to be installed.\n\n    If using \"django_mysql\" Django needs to be installed.\n\n    Args:\n        db_type (str): Type of database can either be \"sqlite\", \"mysql\" or \"django_mysql\"\n\n\n    Returns:\n       sql connection object"
  },
  {
    "code": "def create_argparser(self):\n        if self.desc:\n            if self.title:\n                fulldesc = '%s\\n\\n%s' % (self.title, self.desc)\n            else:\n                fulldesc = self.desc\n        else:\n            fulldesc = self.title\n        return self.ArgumentParser(command=self, prog=self.name,\n                                   description=fulldesc)",
    "docstring": "Factory for arg parser.  Can be overridden as long as it returns\n        an ArgParser compatible instance."
  },
  {
    "code": "def shellinput(initialtext='>> ', splitpart=' '):\n    shelluserinput = input(str(initialtext))\n    return shelluserinput if splitpart in (\n        '', None) else shelluserinput.split(splitpart)",
    "docstring": "Give the user a shell-like interface to enter commands which\n    are returned as a multi-part list containing the command\n    and each of the arguments.\n\n    :type initialtext: string\n    :param initialtext: Set the text to be displayed as the prompt.\n\n    :type splitpart: string\n    :param splitpart: The character to split when generating the list item.\n\n    :return: A string of the user's input or a list of the user's input split by the split character.\n    :rtype: string or list"
  },
  {
    "code": "def parse_value_instancewithpath(self, tup_tree):\n        self.check_node(tup_tree, 'VALUE.INSTANCEWITHPATH')\n        k = kids(tup_tree)\n        if len(k) != 2:\n            raise CIMXMLParseError(\n                _format(\"Element {0!A} has invalid number of child elements \"\n                        \"{1!A} (expecting two child elements \"\n                        \"(INSTANCEPATH, INSTANCE))\",\n                        name(tup_tree), k),\n                conn_id=self.conn_id)\n        inst_path = self.parse_instancepath(k[0])\n        instance = self.parse_instance(k[1])\n        instance.path = inst_path\n        return instance",
    "docstring": "The VALUE.INSTANCEWITHPATH is used to define a value that comprises\n        a single CIMInstance with additional information that defines the\n        absolute path to that object.\n\n          ::\n\n            <!ELEMENT VALUE.INSTANCEWITHPATH (INSTANCEPATH, INSTANCE)>"
  },
  {
    "code": "def currency_to_protocol(amount):\n    if type(amount) in [float, int]:\n        amount = \"%.8f\" % amount\n    return int(amount.replace(\".\", ''))",
    "docstring": "Convert a string of 'currency units' to 'protocol units'. For instance\n    converts 19.1 bitcoin to 1910000000 satoshis.\n\n    Input is a float, output is an integer that is 1e8 times larger.\n\n    It is hard to do this conversion because multiplying\n    floats causes rounding nubers which will mess up the transactions creation\n    process.\n\n    examples:\n\n    19.1 -> 1910000000\n    0.001 -> 100000"
  },
  {
    "code": "def ensure_float(arr):\n    if issubclass(arr.dtype.type, (np.integer, np.bool_)):\n        arr = arr.astype(float)\n    return arr",
    "docstring": "Ensure that an array object has a float dtype if possible.\n\n    Parameters\n    ----------\n    arr : array-like\n        The array whose data type we want to enforce as float.\n\n    Returns\n    -------\n    float_arr : The original array cast to the float dtype if\n                possible. Otherwise, the original array is returned."
  },
  {
    "code": "def listSites(self, block_name=\"\", site_name=\"\"):\n        try:\n            conn = self.dbi.connection()\n            if block_name:\n                result = self.blksitelist.execute(conn, block_name)\n            else:\n                result = self.sitelist.execute(conn, site_name)\n            return result\n        finally:\n            if conn:\n                conn.close()",
    "docstring": "Returns sites."
  },
  {
    "code": "def put_log_events(awsclient, log_group_name, log_stream_name, log_events,\n                   sequence_token=None):\n    client_logs = awsclient.get_client('logs')\n    request = {\n        'logGroupName': log_group_name,\n        'logStreamName': log_stream_name,\n        'logEvents': log_events\n    }\n    if sequence_token:\n        request['sequenceToken'] = sequence_token\n    response = client_logs.put_log_events(**request)\n    if 'rejectedLogEventsInfo' in response:\n        log.warn(response['rejectedLogEventsInfo'])\n    if 'nextSequenceToken' in response:\n        return response['nextSequenceToken']",
    "docstring": "Put log events for the specified log group and stream.\n\n    :param log_group_name: log group name\n    :param log_stream_name: log stream name\n    :param log_events: [{'timestamp': 123, 'message': 'string'}, ...]\n    :param sequence_token: the sequence token\n    :return: next_token"
  },
  {
    "code": "def process_batches(self):\n        for key, batch in iteritems(self._batches):\n            self._current_tups = batch\n            self._current_key = key\n            self.process_batch(key, batch)\n            if self.auto_ack:\n                for tup in batch:\n                    self.ack(tup)\n            self._current_key = None\n            self._batches[key] = []\n        self._batches = defaultdict(list)",
    "docstring": "Iterate through all batches, call process_batch on them, and ack.\n\n        Separated out for the rare instances when we want to subclass\n        BatchingBolt and customize what mechanism causes batches to be\n        processed."
  },
  {
    "code": "def get_label_names(ctx):\n    labels = [\n        label\n        for label in ctx.__dict__\n        if not label.startswith(\"_\")\n        and label\n        not in [\n            \"children\",\n            \"exception\",\n            \"invokingState\",\n            \"parentCtx\",\n            \"parser\",\n            \"start\",\n            \"stop\",\n        ]\n    ]\n    return labels",
    "docstring": "Get labels defined in an ANTLR context for a parser rule"
  },
  {
    "code": "def StaticAdd(cls, queue_urn, rdf_value, mutation_pool=None):\n    if not isinstance(rdf_value, cls.rdf_type):\n      raise ValueError(\"This collection only accepts values of type %s.\" %\n                       cls.rdf_type.__name__)\n    if mutation_pool is None:\n      raise ValueError(\"Mutation pool can't be none.\")\n    timestamp = rdfvalue.RDFDatetime.Now().AsMicrosecondsSinceEpoch()\n    if not isinstance(queue_urn, rdfvalue.RDFURN):\n      queue_urn = rdfvalue.RDFURN(queue_urn)\n    mutation_pool.QueueAddItem(queue_urn, rdf_value, timestamp)",
    "docstring": "Adds an rdf value the queue.\n\n    Adds an rdf value to a queue. Does not require that the queue be locked, or\n    even open. NOTE: The caller is responsible for ensuring that the queue\n    exists and is of the correct type.\n\n    Args:\n      queue_urn: The urn of the queue to add to.\n\n      rdf_value: The rdf value to add to the queue.\n\n      mutation_pool: A MutationPool object to write to.\n\n    Raises:\n      ValueError: rdf_value has unexpected type."
  },
  {
    "code": "def ApprovalUrnBuilder(subject, user, approval_id):\n    return aff4.ROOT_URN.Add(\"ACL\").Add(subject).Add(user).Add(approval_id)",
    "docstring": "Encode an approval URN."
  },
  {
    "code": "async def exist(self, key, param=None):\n        identity = self._gen_identity(key, param)\n        return await self.client.exists(identity)",
    "docstring": "see if specific identity exists"
  },
  {
    "code": "def get(self, sid):\n        return QueueContext(self._version, account_sid=self._solution['account_sid'], sid=sid, )",
    "docstring": "Constructs a QueueContext\n\n        :param sid: The unique string that identifies this resource\n\n        :returns: twilio.rest.api.v2010.account.queue.QueueContext\n        :rtype: twilio.rest.api.v2010.account.queue.QueueContext"
  },
  {
    "code": "def createPenWidthCti(nodeName, defaultData=1.0, zeroValueText=None):\n    return FloatCti(nodeName, defaultData=defaultData, specialValueText=zeroValueText,\n                    minValue=0.1 if zeroValueText is None else 0.0,\n                    maxValue=100, stepSize=0.1, decimals=1)",
    "docstring": "Creates a FloatCti with defaults for configuring a QPen width.\n\n        If specialValueZero is set, this string will be displayed when 0.0 is selected.\n        If specialValueZero is None, the minValue will be 0.1"
  },
  {
    "code": "def make_relative(base, obj):\n    uri = obj.get(\"location\", obj.get(\"path\"))\n    if \":\" in uri.split(\"/\")[0] and not uri.startswith(\"file://\"):\n        pass\n    else:\n        if uri.startswith(\"file://\"):\n            uri = uri_file_path(uri)\n            obj[\"location\"] = os.path.relpath(uri, base)",
    "docstring": "Relativize the location URI of a File or Directory object."
  },
  {
    "code": "def prune_feed_map(meta_graph, feed_map):\n  node_names = [x.name + \":0\" for x in meta_graph.graph_def.node]\n  keys_to_delete = []\n  for k, _ in feed_map.items():\n    if k not in node_names:\n      keys_to_delete.append(k)\n  for k in keys_to_delete:\n    del feed_map[k]",
    "docstring": "Function to prune the feedmap of nodes which no longer exist."
  },
  {
    "code": "def open_xmldoc(fobj, **kwargs):\n    from ligo.lw.ligolw import (Document, LIGOLWContentHandler)\n    from ligo.lw.lsctables import use_in\n    from ligo.lw.utils import (load_filename, load_fileobj)\n    use_in(kwargs.setdefault('contenthandler', LIGOLWContentHandler))\n    try:\n        if isinstance(fobj, string_types):\n            return load_filename(fobj, **kwargs)\n        if isinstance(fobj, FILE_LIKE):\n            return load_fileobj(fobj, **kwargs)[0]\n    except (OSError, IOError):\n        return Document()\n    except LigolwElementError as exc:\n        if LIGO_LW_COMPAT_ERROR.search(str(exc)):\n            try:\n                return open_xmldoc(fobj, ilwdchar_compat=True, **kwargs)\n            except Exception:\n                pass\n        raise",
    "docstring": "Try and open an existing LIGO_LW-format file, or create a new Document\n\n    Parameters\n    ----------\n    fobj : `str`, `file`\n        file path or open file object to read\n\n    **kwargs\n        other keyword arguments to pass to\n        :func:`~ligo.lw.utils.load_filename`, or\n        :func:`~ligo.lw.utils.load_fileobj` as appropriate\n\n    Returns\n    --------\n    xmldoc : :class:`~ligo.lw.ligolw.Document`\n        either the `Document` as parsed from an existing file, or a new, empty\n        `Document`"
  },
  {
    "code": "def set_interface(interface, name=''):\n    global interfaces\n    if not interface: raise ValueError('interface is empty')\n    if name in interfaces:\n        interfaces[name].close()\n    interfaces[name] = interface",
    "docstring": "don't want to bother with a dsn? Use this method to make an interface available"
  },
  {
    "code": "def use_mutation(module_path, operator, occurrence):\n    original_code, mutated_code = apply_mutation(module_path, operator,\n                                                 occurrence)\n    try:\n        yield original_code, mutated_code\n    finally:\n        with module_path.open(mode='wt', encoding='utf-8') as handle:\n            handle.write(original_code)\n            handle.flush()",
    "docstring": "A context manager that applies a mutation for the duration of a with-block.\n\n    This applies a mutation to a file on disk, and after the with-block it put the unmutated code\n    back in place.\n\n    Args:\n        module_path: The path to the module to mutate.\n        operator: The `Operator` instance to use.\n        occurrence: The occurrence of the operator to apply.\n\n    Yields: A `(unmutated-code, mutated-code)` tuple to the with-block. If there was\n        no mutation performed, the `mutated-code` is `None`."
  },
  {
    "code": "def getDebt(self):\n        debt = float(self['principalBalance']) + float(self['interestBalance'])\n        debt += float(self['feesBalance']) + float(self['penaltyBalance'])\n        return debt",
    "docstring": "Sums up all the balances of the account and returns them."
  },
  {
    "code": "def overlap(ival0, ival1):\n    min0, max0 = ival0\n    min1, max1 = ival1\n    return max(0, min(max0, max1) - max(min0, min1)) > 0",
    "docstring": "Determine if two interval tuples have overlap.\n\n    Args:\n        iv0 ((int,int)):    An interval tuple\n        iv1 ((int,int));    An interval tuple\n\n    Returns:\n        (bool): True if the intervals overlap, otherwise False"
  },
  {
    "code": "async def publish(self, message):\r\n        try:\r\n            self.write('data: {}\\n\\n'.format(message))\r\n            await self.flush()\r\n        except StreamClosedError:\r\n            self.finished = True",
    "docstring": "Pushes data to a listener."
  },
  {
    "code": "def removeClassBreak(self, label):\n        for v in self._classBreakInfos:\n            if v['label'] == label:\n                self._classBreakInfos.remove(v)\n                return True\n            del v\n        return False",
    "docstring": "removes a classification break value to the renderer"
  },
  {
    "code": "def load_z_meso(self,z_meso_path):\n        self.z_meso = []\n        z_meso_file_path = os.path.join(z_meso_path, self.Z_MESO_FILE_NAME)\n        if not os.path.exists(z_meso_file_path):\n            raise Exception(\"z_meso.txt file: '{}' does not exist.\".format(uwg_param_file))\n        f = open(z_meso_file_path,'r')\n        for txtline in f:\n            z_ = float(\"\".join(txtline.split()))\n            self.z_meso.append(z_)\n        f.close()",
    "docstring": "Open the z_meso.txt file and return heights as list"
  },
  {
    "code": "def log_url (self, url_data):\n        self.check_active_loggers()\n        do_print = self.do_print(url_data)\n        for log in self.loggers:\n            log.log_filter_url(url_data, do_print)",
    "docstring": "Send new url to all configured loggers."
  },
  {
    "code": "def phase_by(val: Any, phase_turns: float, qubit_index: int,\n             default: TDefault = RaiseTypeErrorIfNotProvided):\n    getter = getattr(val, '_phase_by_', None)\n    result = NotImplemented if getter is None else getter(\n        phase_turns, qubit_index)\n    if result is not NotImplemented:\n        return result\n    if default is not RaiseTypeErrorIfNotProvided:\n        return default\n    if getter is None:\n        raise TypeError(\"object of type '{}' \"\n                        \"has no _phase_by_ method.\".format(type(val)))\n    raise TypeError(\"object of type '{}' does have a _phase_by_ method, \"\n                    \"but it returned NotImplemented.\".format(type(val)))",
    "docstring": "Returns a phased version of the effect.\n\n    For example, an X gate phased by 90 degrees would be a Y gate.\n    This works by calling `val`'s _phase_by_ method and returning\n    the result.\n\n    Args:\n        val: The value to describe with a unitary matrix.\n        phase_turns: The amount to phase the gate, in fractions of a whole\n            turn.  Divide by 2pi to get radians.\n        qubit_index: The index of the target qubit the phasing applies to. For\n            operations this is the index of the qubit within the operation's\n            qubit list. For gates it's the index of the qubit within the tuple\n            of qubits taken by the gate's `on` method.\n        default: The default value to return if `val` can't be phased. If not\n            specified, an error is raised when `val` can't be phased.\n\n    Returns:\n        If `val` has a _phase_by_ method and its result is not NotImplemented,\n        that result is returned. Otherwise, the function will return the\n        default value provided or raise a TypeError if none was provided.\n\n    Raises:\n        TypeError:\n            `val` doesn't have a _phase_by_ method (or that method returned\n            NotImplemented) and no `default` was specified."
  },
  {
    "code": "def contains_is_html(cls, data):\n        for key, val in data.items():\n            if isinstance(key, str) and key.endswith(\"IsHTML\"):\n                return True\n            if isinstance(val, (OrderedDict, dict)) and cls.contains_is_html(val):\n                return True\n        return False",
    "docstring": "Detect if the problem has at least one \"xyzIsHTML\" key"
  },
  {
    "code": "def pause(self, queue_name, kw_in=None, kw_out=None, kw_all=None,\n              kw_none=None, kw_state=None, kw_bcast=None):\n        command = [\"PAUSE\", queue_name]\n        if kw_in:\n            command += [\"in\"]\n        if kw_out:\n            command += [\"out\"]\n        if kw_all:\n            command += [\"all\"]\n        if kw_none:\n            command += [\"none\"]\n        if kw_state:\n            command += [\"state\"]\n        if kw_bcast:\n            command += [\"bcast\"]\n        return self.execute_command(*command)",
    "docstring": "Pause a queue.\n\n        Unfortunately, the PAUSE keywords are mostly reserved words in Python,\n        so I've been a little creative in the function variable names. Open\n        to suggestions to change it (canardleteer)\n\n        :param queue_name: The job queue we are modifying.\n        :param kw_in: pause the queue in input.\n        :param kw_out: pause the queue in output.\n        :param kw_all: pause the queue in input and output (same as specifying\n                       both the in and out options).\n        :param kw_none: clear the paused state in input and output.\n        :param kw_state: just report the current queue state.\n        :param kw_bcast: send a PAUSE command to all the reachable nodes of\n                         the cluster to set the same queue in the other nodes\n                         to the same state."
  },
  {
    "code": "def bogoliubov_trans(p, q, theta):\n    r\n    expo = -4 * theta / np.pi\n    yield cirq.X(p)\n    yield cirq.S(p)\n    yield cirq.ISWAP(p, q)**expo\n    yield cirq.S(p) ** 1.5\n    yield cirq.X(p)",
    "docstring": "r\"\"\"The 2-mode Bogoliubov transformation is mapped to two-qubit operations.\n     We use the identity X S^\\dag X S X = Y X S^\\dag Y S X = X to transform\n     the Hamiltonian XY+YX to XX+YY type. The time evolution of the XX + YY\n     Hamiltonian can be expressed as a power of the iSWAP gate.\n\n    Args:\n        p: the first qubit\n        q: the second qubit\n        theta: The rotational angle that specifies the Bogoliubov\n        transformation, which is a function of the kinetic energy and\n        the superconducting gap."
  },
  {
    "code": "def decodeRPCErrorMsg(e):\n    found = re.search(\n        (\n            \"(10 assert_exception: Assert Exception\\n|\"\n            \"3030000 tx_missing_posting_auth)\"\n            \".*: (.*)\\n\"\n        ),\n        str(e),\n        flags=re.M,\n    )\n    if found:\n        return found.group(2).strip()\n    else:\n        return str(e)",
    "docstring": "Helper function to decode the raised Exception and give it a\n        python Exception class"
  },
  {
    "code": "def start(self):\n        if self.run is True:\n            self.job = multiprocessing.Process(target=self.indicator)\n            self.job.start()\n            return self.job",
    "docstring": "Indicate that we are performing work in a thread.\n\n        :returns: multiprocessing job object"
  },
  {
    "code": "def simulate(radius=5e-6, sphere_index=1.339, medium_index=1.333,\n             wavelength=550e-9, grid_size=(80, 80), model=\"projection\",\n             pixel_size=None, center=None):\n    if isinstance(grid_size, numbers.Integral):\n        grid_size = (grid_size, grid_size)\n    if pixel_size is None:\n        rl = radius / wavelength\n        if rl < 5:\n            fact = 4\n        elif rl >= 5 and rl <= 10:\n            fact = 4 - (rl - 5) / 5\n        else:\n            fact = 3\n        pixel_size = fact * radius / np.min(grid_size)\n    if center is None:\n        center = (np.array(grid_size) - 1) / 2\n    model = model_dict[model]\n    qpi = model(radius=radius,\n                sphere_index=sphere_index,\n                medium_index=medium_index,\n                wavelength=wavelength,\n                pixel_size=pixel_size,\n                grid_size=grid_size,\n                center=center)\n    return qpi",
    "docstring": "Simulate scattering at a sphere\n\n    Parameters\n    ----------\n    radius: float\n        Radius of the sphere [m]\n    sphere_index: float\n        Refractive index of the object\n    medium_index: float\n        Refractive index of the surrounding medium\n    wavelength: float\n        Vacuum wavelength of the imaging light [m]\n    grid_size: tuple of ints or int\n        Resulting image size in x and y [px]\n    model: str\n        Sphere model to use (see :const:`available`)\n    pixel_size: float or None\n        Pixel size [m]; if set to `None` the pixel size is\n        chosen such that the radius fits at least three to\n        four times into the grid.\n    center: tuple of floats or None\n        Center position in image coordinates [px]; if set to\n        None, the center of the image (grid_size - 1)/2 is\n        used.\n\n    Returns\n    -------\n    qpi: qpimage.QPImage\n        Quantitative phase data set"
  },
  {
    "code": "def assert_estimator_equal(left, right, exclude=None, **kwargs):\n    left_attrs = [x for x in dir(left) if x.endswith(\"_\") and not x.startswith(\"_\")]\n    right_attrs = [x for x in dir(right) if x.endswith(\"_\") and not x.startswith(\"_\")]\n    if exclude is None:\n        exclude = set()\n    elif isinstance(exclude, str):\n        exclude = {exclude}\n    else:\n        exclude = set(exclude)\n    assert (set(left_attrs) - exclude) == set(right_attrs) - exclude\n    for attr in set(left_attrs) - exclude:\n        l = getattr(left, attr)\n        r = getattr(right, attr)\n        _assert_eq(l, r, **kwargs)",
    "docstring": "Check that two Estimators are equal\n\n    Parameters\n    ----------\n    left, right : Estimators\n    exclude : str or sequence of str\n        attributes to skip in the check\n    kwargs : dict\n        Passed through to the dask `assert_eq` method."
  },
  {
    "code": "def state_cpfs(self) -> List[CPF]:\n        _, cpfs = self.cpfs\n        state_cpfs = []\n        for cpf in cpfs:\n            name = utils.rename_next_state_fluent(cpf.name)\n            if name in self.state_fluents:\n                state_cpfs.append(cpf)\n        state_cpfs = sorted(state_cpfs, key=lambda cpf: cpf.name)\n        return state_cpfs",
    "docstring": "Returns list of state-fluent CPFs."
  },
  {
    "code": "def get_rng(obj=None):\n    seed = (id(obj) + os.getpid() +\n            int(datetime.now().strftime(\"%Y%m%d%H%M%S%f\"))) % 4294967295\n    if _RNG_SEED is not None:\n        seed = _RNG_SEED\n    return np.random.RandomState(seed)",
    "docstring": "Get a good RNG seeded with time, pid and the object.\n\n    Args:\n        obj: some object to use to generate random seed.\n    Returns:\n        np.random.RandomState: the RNG."
  },
  {
    "code": "def get_cas_client(self, request, provider, renew=False):\n        service_url = utils.get_current_url(request, {\"ticket\", \"provider\"})\n        self.service_url = service_url\n        return CASFederateValidateUser(provider, service_url, renew=renew)",
    "docstring": "return a CAS client object matching provider\n\n            :param django.http.HttpRequest request: The current request object\n            :param cas_server.models.FederatedIendityProvider provider: the user identity provider\n            :return: The user CAS client object\n            :rtype: :class:`federate.CASFederateValidateUser\n                <cas_server.federate.CASFederateValidateUser>`"
  },
  {
    "code": "def offset(self, offset):\n        self.log(u\"Applying offset to all fragments...\")\n        self.log([u\"  Offset %.3f\", offset])\n        for fragment in self.fragments:\n            fragment.interval.offset(\n                offset=offset,\n                allow_negative=False,\n                min_begin_value=self.begin,\n                max_end_value=self.end\n            )\n        self.log(u\"Applying offset to all fragments... done\")",
    "docstring": "Move all the intervals in the list by the given ``offset``.\n\n        :param offset: the shift to be applied\n        :type  offset: :class:`~aeneas.exacttiming.TimeValue`\n        :raises TypeError: if ``offset`` is not an instance of ``TimeValue``"
  },
  {
    "code": "def query_source(self, source):\n        return self._get_repo_filter(Layer.objects).filter(url=source)",
    "docstring": "Query by source"
  },
  {
    "code": "def on_before_transform_template(self, template_dict):\n        template = SamTemplate(template_dict)\n        self.existing_implicit_api_resource = copy.deepcopy(template.get(self.implicit_api_logical_id))\n        template.set(self.implicit_api_logical_id, ImplicitApiResource().to_dict())\n        errors = []\n        for logicalId, function in template.iterate(SamResourceType.Function.value):\n            api_events = self._get_api_events(function)\n            condition = function.condition\n            if len(api_events) == 0:\n                continue\n            try:\n                self._process_api_events(function, api_events, template, condition)\n            except InvalidEventException as ex:\n                errors.append(InvalidResourceException(logicalId, ex.message))\n        self._maybe_add_condition_to_implicit_api(template_dict)\n        self._maybe_add_conditions_to_implicit_api_paths(template)\n        self._maybe_remove_implicit_api(template)\n        if len(errors) > 0:\n            raise InvalidDocumentException(errors)",
    "docstring": "Hook method that gets called before the SAM template is processed.\n        The template has pass the validation and is guaranteed to contain a non-empty \"Resources\" section.\n\n        :param dict template_dict: Dictionary of the SAM template\n        :return: Nothing"
  },
  {
    "code": "def app_start(name, profile, **kwargs):\n    ctx = Context(**kwargs)\n    ctx.execute_action('app:start', **{\n        'node': ctx.repo.create_secure_service('node'),\n        'name': name,\n        'profile': profile\n    })",
    "docstring": "Start an application with specified profile.\n\n    Does nothing if application is already running."
  },
  {
    "code": "def list_supported_categories():\n  categories = get_supported_categories(api)\n  category_names = [category.name for category in categories]\n  print (\"Supported account categories by name: {0}\".format(\n    COMMA_WITH_SPACE.join(map(str, category_names))))",
    "docstring": "Prints a list of supported external account category names.\n  For example, \"AWS\" is a supported external account category name."
  },
  {
    "code": "def remove_suffix(text, suffix):\n\trest, suffix, null = text.partition(suffix)\n\treturn rest",
    "docstring": "Remove the suffix from the text if it exists.\n\n\t>>> remove_suffix('name.git', '.git')\n\t'name'\n\n\t>>> remove_suffix('something special', 'sample')\n\t'something special'"
  },
  {
    "code": "def update(self, resource, timeout=-1):\n        return self._client.update(resource, timeout=timeout, default_values=self.DEFAULT_VALUES, uri=self.URI)",
    "docstring": "Updates a User.\n\n        Args:\n            resource (dict): Object to update.\n            timeout:\n                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n                in OneView, just stop waiting for its completion.\n\n        Returns:\n            dict: Updated resource."
  },
  {
    "code": "def search(self, **kwargs):\n        return super(ApiV4As, self).get(self.prepare_url(\n            'api/v4/as/', kwargs))",
    "docstring": "Method to search asns based on extends search.\n\n        :param search: Dict containing QuerySets to find asns.\n        :param include: Array containing fields to include on response.\n        :param exclude: Array containing fields to exclude on response.\n        :param fields:  Array containing fields to override default fields.\n        :param kind: Determine if result will be detailed ('detail') or basic ('basic').\n        :return: Dict containing asns"
  },
  {
    "code": "def download_log(currentfile=None):\n    if currentfile == None:\n        return\n    if not currentfile.endswith(\".err.log\"):\n        currentfile=currentfile + \".err.log\"\n    list = get_base_ev3dev_cmd() + ['download','--force']\n    list.append(currentfile)\n    env = os.environ.copy()\n    env[\"PYTHONUSERBASE\"] = THONNY_USER_BASE\n    proc = subprocess.Popen(list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,\n                            universal_newlines=True, env=env)\n    dlg = MySubprocessDialog(get_workbench(), proc, \"Downloading log of program from EV3\", autoclose=True)\n    dlg.wait_window()\n    if dlg.returncode == 0:\n        from pathlib import Path\n        home = str(Path.home())\n        open_file(currentfile,home,True)",
    "docstring": "downloads log of given .py file from EV3."
  },
  {
    "code": "def save_graph(cn_topo, filename, showintfs=False, showaddrs=False):\n    __do_draw(cn_topo, showintfs=showintfs, showaddrs=showaddrs)\n    pyp.savefig(filename)",
    "docstring": "Save the topology to an image file"
  },
  {
    "code": "def format_content_type_object(repo, content_type, uuid):\n    try:\n        storage_manager = StorageManager(repo)\n        model_class = load_model_class(repo, content_type)\n        return dict(storage_manager.get(model_class, uuid))\n    except GitCommandError:\n        raise NotFound('Object does not exist.')",
    "docstring": "Return a content object from a repository for a given content_type\n    and uuid\n\n    :param Repo repo:\n        The git repository.\n    :param str content_type:\n        The content type to list\n    :returns: dict"
  },
  {
    "code": "def enable(self, key_id, **kwargs):\n        path = '%s/%s/enable' % (self.path, key_id)\n        self.gitlab.http_post(path, **kwargs)",
    "docstring": "Enable a deploy key for a project.\n\n        Args:\n            key_id (int): The ID of the key to enable\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabProjectDeployKeyError: If the key could not be enabled"
  },
  {
    "code": "def change_name(self, username):\r\n        self.release_name()\r\n        try:\r\n            self.server.register_name(username)\r\n        except UsernameInUseException:\r\n            logging.log(', '.join(self.server.registered_names))\r\n            self.server.register_name(self.name)\r\n            raise\r\n        self.name = username",
    "docstring": "changes the username to given username, throws exception if username used"
  },
  {
    "code": "def task2ics():\n    from argparse import ArgumentParser, FileType\n    from sys import stdout\n    parser = ArgumentParser(description='Converter from Taskwarrior to iCalendar syntax.')\n    parser.add_argument('indir', nargs='?', help='Input Taskwarrior directory (default to ~/.task)', default=expanduser('~/.task'))\n    parser.add_argument('outfile', nargs='?', type=FileType('w'), default=stdout,\n                        help='Output iCalendar file (default: stdout)')\n    args = parser.parse_args()\n    task = IcsTask(args.indir)\n    args.outfile.write(task.to_vobject().serialize())",
    "docstring": "Command line tool to convert from Taskwarrior to iCalendar"
  },
  {
    "code": "def precompile_python_code(context: Context):\n    from compileall import compile_dir\n    kwargs = {}\n    if context.verbosity < 2:\n        kwargs['quiet'] = True\n    compile_dir(context.app.django_app_name, **kwargs)",
    "docstring": "Pre-compiles python modules"
  },
  {
    "code": "def layerize(begin_update=None, predict=None, *args, **kwargs):\n    if begin_update is not None:\n        return FunctionLayer(begin_update, predict=predict, *args, **kwargs)\n    def wrapper(begin_update):\n        return FunctionLayer(begin_update, *args, **kwargs)\n    return wrapper",
    "docstring": "Wrap a function into a layer"
  },
  {
    "code": "def set_as_error(self, color=Qt.red):\n        self.format.setUnderlineStyle(\n            QTextCharFormat.WaveUnderline)\n        self.format.setUnderlineColor(color)",
    "docstring": "Highlights text as a syntax error.\n\n        :param color: Underline color\n        :type color: QtGui.QColor"
  },
  {
    "code": "def _parse(cls, data, key=None):\n        parse = cls.parse if cls.parse is not None else cls.get_endpoint()\n        if callable(parse):\n            data = parse(data)\n        elif isinstance(parse, str):\n            data = data[key]\n        else:\n            raise Exception('\"parse\" should be a callable or string got, {0}'\n                            .format(parse))\n        return data",
    "docstring": "Parse a set of data to extract entity-only data.\n\n        Use classmethod `parse` if available, otherwise use the `endpoint`\n        class variable to extract data from a data blob."
  },
  {
    "code": "def set_category(self, category):\n        if isinstance(category, Category):\n            name = category.name\n        else:\n            name = category\n        self.find(\"category\").text = name",
    "docstring": "Set package category\n\n        Args:\n            category: String of an existing category's name, or a\n                Category object."
  },
  {
    "code": "def capture(returns, factor_returns, period=DAILY):\n    return (annual_return(returns, period=period) /\n            annual_return(factor_returns, period=period))",
    "docstring": "Compute capture ratio.\n\n    Parameters\n    ----------\n    returns : pd.Series or np.ndarray\n        Returns of the strategy, noncumulative.\n        - See full explanation in :func:`~empyrical.stats.cum_returns`.\n    factor_returns : pd.Series or np.ndarray\n        Noncumulative returns of the factor to which beta is\n        computed. Usually a benchmark such as the market.\n        - This is in the same style as returns.\n    period : str, optional\n        Defines the periodicity of the 'returns' data for purposes of\n        annualizing. Value ignored if `annualization` parameter is specified.\n        Defaults are::\n\n            'monthly':12\n            'weekly': 52\n            'daily': 252\n\n    Returns\n    -------\n    capture_ratio : float\n\n    Note\n    ----\n    See http://www.investopedia.com/terms/u/up-market-capture-ratio.asp for\n    details."
  },
  {
    "code": "def load_extra_data(cls, data):\n    try:\n      cls._extra_config.update(json.loads(data))\n    except ValueError as exception:\n      sys.stderr.write('Could convert to JSON. {0:s}'.format(exception))\n      exit(-1)",
    "docstring": "Loads extra JSON configuration parameters from a data buffer.\n\n    The data buffer must represent a JSON object.\n\n    Args:\n      data: str, the buffer to load the JSON data from."
  },
  {
    "code": "def _ensure_slack(self, connector: Any, retries: int,\n                      backoff: Callable[[int], float]) -> None:\n        connector = self._env_var if connector is None else connector\n        slack: SlackClient = _create_slack(connector)\n        self._slack = _SlackClientWrapper(\n            slack=slack,\n            retries=retries,\n            backoff=backoff\n        )",
    "docstring": "Ensure we have a SlackClient."
  },
  {
    "code": "def twofilter_smoothing(self, t, info, phi, loggamma, linear_cost=False,\n                            return_ess=False, modif_forward=None,\n                            modif_info=None):\n        ti = self.T - 2 - t\n        if t < 0 or t >= self.T - 1:\n            raise ValueError(\n                'two-filter smoothing: t must be in range 0,...,T-2')\n        lwinfo = info.hist.wgt[ti].lw - loggamma(info.hist.X[ti])\n        if linear_cost:\n            return self._twofilter_smoothing_ON(t, ti, info, phi, lwinfo,\n                                               return_ess,\n                                               modif_forward, modif_info)\n        else:\n            return self._twofilter_smoothing_ON2(t, ti, info, phi, lwinfo)",
    "docstring": "Two-filter smoothing.\n\n        Parameters\n        ----------\n        t: time, in range 0 <= t < T-1\n        info: SMC object \n            the information filter\n        phi: function\n            test function, a function of (X_t,X_{t+1})\n        loggamma: function\n            a function of (X_{t+1})\n        linear_cost: bool\n            if True, use the O(N) variant (basic version is O(N^2))\n\n        Returns\n        -------\n        Two-filter estimate of the smoothing expectation of phi(X_t,x_{t+1})"
  },
  {
    "code": "def _send(self, email_message):\n        pre_send.send(self.__class__, message=email_message)\n        if not email_message.recipients():\n            return False\n        from_email = sanitize_address(email_message.from_email,\n                                      email_message.encoding)\n        recipients = [sanitize_address(addr, email_message.encoding)\n                      for addr in email_message.recipients()]\n        message = email_message.message().as_bytes(linesep='\\r\\n')\n        try:\n            result = self.conn.send_raw_email(\n                Source=from_email,\n                Destinations=recipients,\n                RawMessage={\n                    'Data': message\n                }\n            )\n            message_id = result['MessageId']\n            post_send.send(\n                self.__class__,\n                message=email_message,\n                message_id=message_id\n            )\n        except ClientError:\n            if not self.fail_silently:\n                raise\n            return False\n        return True",
    "docstring": "Sends an individual message via the Amazon SES HTTP API.\n\n        Args:\n            email_message: A single Django EmailMessage object.\n        Returns:\n            True if the EmailMessage was sent successfully, otherwise False.\n        Raises:\n            ClientError: An interaction with the Amazon SES HTTP API\n                failed."
  },
  {
    "code": "def post_build_time_coverage(self):\n        from ambry.util.datestimes import expand_to_years\n        years = set()\n        if self.metadata.about.time:\n            for year in expand_to_years(self.metadata.about.time):\n                years.add(year)\n        if self.identity.btime:\n            for year in expand_to_years(self.identity.btime):\n                years.add(year)\n        for p in self.partitions:\n            years |= set(p.time_coverage)",
    "docstring": "Collect all of the time coverage for the bundle."
  },
  {
    "code": "def _get_gradient_log_pdf(self):\n        sub_vec = self.variable_assignments - self.model.mean.flatten()\n        grad = - np.dot(self.model.precision_matrix, sub_vec)\n        log_pdf = 0.5 * np.dot(sub_vec, grad)\n        return grad, log_pdf",
    "docstring": "Method that finds gradient and its log at position"
  },
  {
    "code": "def value(dtype, arg):\n    if not isinstance(arg, ir.Expr):\n        arg = ir.literal(arg)\n    if not isinstance(arg, ir.AnyValue):\n        raise com.IbisTypeError(\n            'Given argument with type {} is not a value '\n            'expression'.format(type(arg))\n        )\n    value = getattr(arg.op(), 'value', None)\n    if isinstance(dtype, type) and isinstance(arg.type(), dtype):\n        return arg\n    elif dt.castable(arg.type(), dt.dtype(dtype), value=value):\n        return arg\n    else:\n        raise com.IbisTypeError(\n            'Given argument with datatype {} is not '\n            'subtype of {} nor implicitly castable to '\n            'it'.format(arg.type(), dtype)\n        )",
    "docstring": "Validates that the given argument is a Value with a particular datatype\n\n    Parameters\n    ----------\n    dtype : DataType subclass or DataType instance\n    arg : python literal or an ibis expression\n      If a python literal is given the validator tries to coerce it to an ibis\n      literal.\n\n    Returns\n    -------\n    arg : AnyValue\n      An ibis value expression with the specified datatype"
  },
  {
    "code": "def login(session, user, password, database=None, server=None):\n    if not user:\n        user = click.prompt(\"Username\", type=str)\n    if not password:\n        password = click.prompt(\"Password\", hide_input=True, type=str)\n    try:\n        with click.progressbar(length=1, label=\"Logging in...\") as progressbar:\n            session.login(user, password, database, server)\n            progressbar.update(1)\n        if session.credentials:\n            click.echo('Logged in as: %s' % session.credentials)\n            session.load(database)\n        return session.get_api()\n    except mygeotab.AuthenticationException:\n        click.echo('Incorrect credentials. Please try again.')\n        sys.exit(0)",
    "docstring": "Logs into a MyGeotab server and stores the returned credentials.\n\n    :param session: The current Session object.\n    :param user: The username used for MyGeotab servers. Usually an email address.\n    :param password: The password associated with the username. Optional if `session_id` is provided.\n    :param database: The database or company name. Optional as this usually gets resolved upon authentication.\n    :param server: The server ie. my23.geotab.com. Optional as this usually gets resolved upon authentication."
  },
  {
    "code": "def internal_writer(self, outputs, stdout):\n        for output in outputs:\n            print(\"\\t\".join(map(self.internal_serialize, output)), file=stdout)",
    "docstring": "Writer which outputs the python repr for each item."
  },
  {
    "code": "def start_event(self):\n        if self.with_outframe_pool:\n            self.update_config()\n            for name in self.outputs:\n                self.outframe_pool[name] = ObjectPool(\n                    Frame, self.new_frame, self.config['outframe_pool_len'])\n        try:\n            self.on_start()\n        except Exception as ex:\n            self.logger.exception(ex)\n            raise StopIteration()",
    "docstring": "Called by the event loop when it is started.\n\n        Creates the output frame pools (if used) then calls\n        :py:meth:`on_start`. Creating the output frame pools now allows\n        their size to be configured before starting the component."
  },
  {
    "code": "def filter(configs, settings):\n    if isinstance(configs, pd.DataFrame):\n        configs = configs[['a', 'b', 'm', 'n']].values\n    filter_funcs = {\n        'dd': _filter_dipole_dipole,\n        'schlumberger': _filter_schlumberger,\n    }\n    keys = ['dd', 'schlumberger', ]\n    allowed_keys = settings.get('only_types', filter_funcs.keys())\n    results = {}\n    configs_filtered = configs.copy().astype(float)\n    for key in keys:\n        if key in allowed_keys:\n            configs_filtered, indices_filtered = filter_funcs[key](\n                configs_filtered,\n            )\n            if len(indices_filtered) > 0:\n                results[key] = indices_filtered\n    results['not_sorted'] = np.where(\n        ~np.all(np.isnan(configs_filtered), axis=1)\n    )[0]\n    return results",
    "docstring": "Main entry function to filtering configuration types\n\n    Parameters\n    ----------\n    configs: Nx4 array\n        array containing A-B-M-N configurations\n    settings: dict\n        'only_types': ['dd', 'other'],  # filter only for those types\n\n    Returns\n    -------\n    dict\n        results dict containing filter results (indices) for all registered\n        filter functions.  All remaining configs are stored under the keywords\n        'remaining'"
  },
  {
    "code": "def _get_json(self,\n                  path,\n                  params=None,\n                  base=JIRA_BASE_URL,\n                  ):\n        url = self._get_url(path, base)\n        r = self._session.get(url, params=params)\n        try:\n            r_json = json_loads(r)\n        except ValueError as e:\n            logging.error(\"%s\\n%s\" % (e, r.text))\n            raise e\n        return r_json",
    "docstring": "Get the json for a given path and params.\n\n        :param path: The subpath required\n        :type path: str\n        :param params: Parameters to filter the json query.\n        :type params: Optional[Dict[str, Any]]\n        :param base: The Base JIRA URL, defaults to the instance base.\n        :type base: Optional[str]\n\n        :rtype: Union[Dict[str, Any], List[Dict[str, str]]]"
  },
  {
    "code": "def add_pagination_meta(self, params, meta):\n        meta['page_size'] = params['page_size']\n        meta['page'] = params['page']\n        meta['prev'] = \"page={0}&page_size={1}\".format(\n            params['page'] - 1, params['page_size']\n        ) if meta['page'] > 0 else None\n        meta['next'] = \"page={0}&page_size={1}\".format(\n            params['page'] + 1, params['page_size']\n        ) if meta.get('has_more', True) else None",
    "docstring": "Extend default meta dictionary value with pagination hints.\n\n        Note:\n            This method handler attaches values to ``meta`` dictionary without\n            changing it's reference. This means that you should never replace\n            ``meta`` dictionary with any other dict instance but simply modify\n            its content.\n\n        Args:\n            params (dict): dictionary of decoded parameter values\n            meta (dict): dictionary of meta values attached to response"
  },
  {
    "code": "def __undo_filter_average(self, scanline):\n        ai = -self.fu\n        previous = self.prev\n        for i in range(len(scanline)):\n            x = scanline[i]\n            if ai < 0:\n                a = 0\n            else:\n                a = scanline[ai]\n            b = previous[i]\n            scanline[i] = (x + ((a + b) >> 1)) & 0xff\n            ai += 1",
    "docstring": "Undo average filter."
  },
  {
    "code": "def _compute_mean(self, C, g, mag, hypo_depth, rrup, vs30, pga_rock, imt):\n        if hypo_depth > 100:\n            hypo_depth = 100\n        delta = 0.00724 * 10 ** (0.507 * mag)\n        R = np.sqrt(rrup ** 2 + delta ** 2)\n        s_amp = self._compute_soil_amplification(C, vs30, pga_rock, imt)\n        mean = (\n            C['c1'] + C['c2'] * mag +\n            C['c3'] * hypo_depth +\n            C['c4'] * R -\n            g * np.log10(R) +\n            s_amp\n        )\n        return mean",
    "docstring": "Compute mean according to equation 1, page 1706."
  },
  {
    "code": "def connect(self):\n        future = concurrent.Future()\n        if self.connected:\n            raise exceptions.ConnectError('already connected')\n        LOGGER.debug('%s connecting', self.name)\n        self.io_loop.add_future(\n            self._client.connect(self.host, self.port),\n            lambda f: self._on_connected(f, future))\n        return future",
    "docstring": "Connect to the Redis server if necessary.\n\n        :rtype: :class:`~tornado.concurrent.Future`\n        :raises: :class:`~tredis.exceptions.ConnectError`\n                 :class:`~tredis.exceptinos.RedisError`"
  },
  {
    "code": "def post(self, request, format=None):\n        serializer_class = self.get_serializer_class()\n        serializer = serializer_class(data=request.data, instance=request.user)\n        if serializer.is_valid():\n            serializer.save()\n            return Response({'detail': _(u'Password successfully changed')})\n        return Response(serializer.errors, status=400)",
    "docstring": "validate password change operation and return result"
  },
  {
    "code": "def hildatree2dgparentedtree(self):\n        def transform(hilda_tree):\n            if isinstance(hilda_tree, basestring) or not hasattr(hilda_tree, 'label'):\n                return hilda_tree\n            assert len(hilda_tree) == 2, \"We can only handle binary trees.\"\n            match = HILDA_REL_RE.match(hilda_tree.label())\n            assert match, \"Relation '{}' does not match regex '{}'\".format(hilda_tree.label(), HILDA_REL_RE)\n            relname, left_child_nuc, right_child_nuc = match.groups()\n            hilda_tree._label = relname\n            for i, child_nuclearity in enumerate([left_child_nuc, right_child_nuc]):\n                child = hilda_tree[i]\n                hilda_tree[i] = Tree(child_nuclearity, [transform(child)])\n            return hilda_tree\n        tree = transform(self.hildafile_tree)\n        return DGParentedTree.convert(tree)",
    "docstring": "Convert the tree from HILDA's format into a conventional binary tree,\n        which can be easily converted into output formats like RS3."
  },
  {
    "code": "def config_as_dict(cfg):\n    ret = cfg.__dict__.copy()\n    del ret['rand_crop_samplers']\n    assert isinstance(cfg.rand_crop_samplers, list)\n    ret = merge_dict(ret, zip_namedtuple(cfg.rand_crop_samplers))\n    num_crop_sampler = len(cfg.rand_crop_samplers)\n    ret['num_crop_sampler'] = num_crop_sampler\n    ret['rand_crop_prob'] = 1.0 / (num_crop_sampler + 1) * num_crop_sampler\n    del ret['rand_pad']\n    ret = merge_dict(ret, cfg.rand_pad._asdict())\n    del ret['color_jitter']\n    ret = merge_dict(ret, cfg.color_jitter._asdict())\n    return ret",
    "docstring": "convert raw configuration to unified dictionary"
  },
  {
    "code": "def speed_difference(points):\n    data = [0]\n    for before, after in pairwise(points):\n        data.append(before.vel - after.vel)\n    return data",
    "docstring": "Computes the speed difference between each adjacent point\n\n    Args:\n        points (:obj:`Point`)\n    Returns:\n        :obj:`list` of int: Indexes of changepoints"
  },
  {
    "code": "def factorize_groupby_cols(self, groupby_cols):\n        factor_list = []\n        values_list = []\n        for col in groupby_cols:\n            if self.auto_cache or self.cache_valid(col):\n                if not self.cache_valid(col):\n                    self.cache_factor([col])\n                col_rootdir = self[col].rootdir\n                col_factor_rootdir = col_rootdir + '.factor'\n                col_values_rootdir = col_rootdir + '.values'\n                col_carray_factor = \\\n                    bcolz.carray(rootdir=col_factor_rootdir, mode='r')\n                col_carray_values = \\\n                    bcolz.carray(rootdir=col_values_rootdir, mode='r')\n            else:\n                col_carray_factor, values = ctable_ext.factorize(self[col])\n                col_carray_values = \\\n                    bcolz.carray(np.fromiter(values.values(), dtype=self[col].dtype))\n            factor_list.append(col_carray_factor)\n            values_list.append(col_carray_values)\n        return factor_list, values_list",
    "docstring": "factorizes all columns that are used in the groupby\n        it will use cache carrays if available\n        if not yet auto_cache is valid, it will create cache carrays"
  },
  {
    "code": "def ls(path, pattern='*'):\n    path_iter = glob(path, pattern, recursive=False)\n    return sorted(list(path_iter))",
    "docstring": "like unix ls - lists all files and dirs in path"
  },
  {
    "code": "def _assert_has_data_for_time(da, start_date, end_date):\n    if isinstance(start_date, str) and isinstance(end_date, str):\n        logging.warning(\n            'When using strings to specify start and end dates, the check '\n            'to determine if data exists for the full extent of the desired '\n            'interval is not implemented.  Therefore it is possible that '\n            'you are doing a calculation for a lesser interval than you '\n            'specified.  If you would like this check to occur, use explicit '\n            'datetime-like objects for bounds instead.')\n        return\n    if RAW_START_DATE_STR in da.coords:\n        with warnings.catch_warnings(record=True):\n            da_start = da[RAW_START_DATE_STR].values\n            da_end = da[RAW_END_DATE_STR].values\n    else:\n        times = da.time.isel(**{TIME_STR: [0, -1]})\n        da_start, da_end = times.values\n    message = ('Data does not exist for requested time range: {0} to {1};'\n               ' found data from time range: {2} to {3}.')\n    tol = datetime.timedelta(seconds=1)\n    if isinstance(da_start, np.datetime64):\n        tol = np.timedelta64(tol, 'ns')\n    range_exists = ((da_start - tol) <= start_date and\n                    (da_end + tol) >= end_date)\n    assert (range_exists), message.format(start_date, end_date,\n                                          da_start, da_end)",
    "docstring": "Check to make sure data is in Dataset for the given time range.\n\n    Parameters\n    ----------\n    da : DataArray\n         DataArray with a time variable\n    start_date : datetime-like object or str\n         start date\n    end_date : datetime-like object or str\n         end date\n\n    Raises\n    ------\n    AssertionError\n         If the time range is not within the time range of the DataArray"
  },
  {
    "code": "def write(self, output):\n        w = c_int32()\n        self.WriteAnalogF64(self.bufsize, 0, 10.0, DAQmx_Val_GroupByChannel,\n                            output, w, None);",
    "docstring": "Writes the data to be output to the device buffer, output will be looped when the data runs out\n\n        :param output: data to output\n        :type output: numpy.ndarray"
  },
  {
    "code": "def long2ip(l):\n    if MAX_IP < l or l < MIN_IP:\n        raise TypeError(\n            \"expected int between %d and %d inclusive\" % (MIN_IP, MAX_IP))\n    return '%d.%d.%d.%d' % (\n        l >> 24 & 255, l >> 16 & 255, l >> 8 & 255, l & 255)",
    "docstring": "Convert a network byte order 32-bit integer to a dotted quad ip\n    address.\n\n\n    >>> long2ip(2130706433)\n    '127.0.0.1'\n    >>> long2ip(MIN_IP)\n    '0.0.0.0'\n    >>> long2ip(MAX_IP)\n    '255.255.255.255'\n    >>> long2ip(None) #doctest: +IGNORE_EXCEPTION_DETAIL\n    Traceback (most recent call last):\n        ...\n    TypeError: unsupported operand type(s) for >>: 'NoneType' and 'int'\n    >>> long2ip(-1) #doctest: +IGNORE_EXCEPTION_DETAIL\n    Traceback (most recent call last):\n        ...\n    TypeError: expected int between 0 and 4294967295 inclusive\n    >>> long2ip(374297346592387463875) #doctest: +IGNORE_EXCEPTION_DETAIL\n    Traceback (most recent call last):\n        ...\n    TypeError: expected int between 0 and 4294967295 inclusive\n    >>> long2ip(MAX_IP + 1) #doctest: +IGNORE_EXCEPTION_DETAIL\n    Traceback (most recent call last):\n        ...\n    TypeError: expected int between 0 and 4294967295 inclusive\n\n\n    :param l: Network byte order 32-bit integer.\n    :type l: int\n    :returns: Dotted-quad ip address (eg. '127.0.0.1').\n    :raises: TypeError"
  },
  {
    "code": "def query(self, *args, **kwargs):\n        if not issubclass(kwargs.get('itercls', None), AsyncViewBase):\n            raise ArgumentError.pyexc(\"itercls must be defined \"\n                                      \"and must be derived from AsyncViewBase\")\n        return super(AsyncBucket, self).query(*args, **kwargs)",
    "docstring": "Reimplemented from base class.\n\n        This method does not add additional functionality of the\n        base class' :meth:`~couchbase.bucket.Bucket.query` method (all the\n        functionality is encapsulated in the view class anyway). However it\n        does require one additional keyword argument\n\n        :param class itercls: A class used for instantiating the view\n          object. This should be a subclass of\n          :class:`~couchbase.asynchronous.view.AsyncViewBase`."
  },
  {
    "code": "def get_code(node, coder=Coder()):\n    return cgi.escape(str(coder.code(node)), quote=True)",
    "docstring": "Return a node's code"
  },
  {
    "code": "def spin_z(particles, index):\n    mat = np.zeros((2**particles, 2**particles))\n    for i in range(2**particles):\n        ispin = btest(i, index)\n        if ispin == 1:\n            mat[i, i] = 1\n        else:\n            mat[i, i] = -1\n    return 1/2.*mat",
    "docstring": "Generates the spin_z projection operator for a system of\n        N=particles and for the selected spin index name. where index=0..N-1"
  },
  {
    "code": "def auth_list(**kwargs):\n    ctx = Context(**kwargs)\n    ctx.execute_action('auth:group:list', **{\n        'storage': ctx.repo.create_secure_service('storage'),\n    })",
    "docstring": "Shows available authorization groups."
  },
  {
    "code": "def get(self):\n        self.set_status(401)\n        self.set_header('WWW-Authenticate', 'Session')\n        ret = {'status': '401 Unauthorized',\n               'return': 'Please log in'}\n        self.write(self.serialize(ret))",
    "docstring": "All logins are done over post, this is a parked endpoint\n\n        .. http:get:: /login\n\n            :status 401: |401|\n            :status 406: |406|\n\n        **Example request:**\n\n        .. code-block:: bash\n\n            curl -i localhost:8000/login\n\n        .. code-block:: text\n\n            GET /login HTTP/1.1\n            Host: localhost:8000\n            Accept: application/json\n\n        **Example response:**\n\n        .. code-block:: text\n\n            HTTP/1.1 401 Unauthorized\n            Content-Type: application/json\n            Content-Length: 58\n\n            {\"status\": \"401 Unauthorized\", \"return\": \"Please log in\"}"
  },
  {
    "code": "def launch_shell(username, hostname, password, port=22):\n    if not username or not hostname or not password:\n        return False\n    with tempfile.NamedTemporaryFile() as tmpFile:\n        os.system(sshCmdLine.format(password, tmpFile.name, username, hostname,\n                                    port))\n    return True",
    "docstring": "Launches an ssh shell"
  },
  {
    "code": "def get_data(self, datatype, data):\n        result = {}\n        params = StopforumspamClient._set_payload(datatype, data)\n        response = self.client.get(\n            'https://api.stopforumspam.org/api',\n            params=params, proxies=self.proxies)\n        response.raise_for_status()\n        report = response.json()\n        if report['success']:\n            data = report[StopforumspamClient._type_conversion[datatype]]\n            result = self._data_conversion(data)\n        else:\n            pass\n        return result",
    "docstring": "Look for an IP address or an email address in the spammer database.\n\n        :param datatype: Which type of data is to be looked up.\n                         Allowed values are 'ip' or 'mail'.\n        :param data: The value to be looked up through the API.\n        :type datatype: str\n        :type data: str\n        :return: Data relative to the looked up artifact.\n        :rtype: dict"
  },
  {
    "code": "def delete(self):\n        r = self._client._request('DELETE', self._client._build_url('property', property_id=self.id))\n        if r.status_code != requests.codes.no_content:\n            raise APIError(\"Could not delete property: {} with id {}\".format(self.name, self.id))",
    "docstring": "Delete this property.\n\n        :return: None\n        :raises APIError: if delete was not successful"
  },
  {
    "code": "def get_version(self, dependency):\n        logger.debug(\"getting installed version for %s\", dependency)\n        stdout = helpers.logged_exec([self.pip_exe, \"show\", str(dependency)])\n        version = [line for line in stdout if line.startswith('Version:')]\n        if len(version) == 1:\n            version = version[0].strip().split()[1]\n            logger.debug(\"Installed version of %s is: %s\", dependency, version)\n            return version\n        else:\n            logger.error('Fades is having problems getting the installed version. '\n                         'Run with -v or check the logs for details')\n            return ''",
    "docstring": "Return the installed version parsing the output of 'pip show'."
  },
  {
    "code": "def format_to_json(data):\n    if sys.stdout.isatty():\n        return json.dumps(data, indent=4, separators=(',', ': '))\n    else:\n        return json.dumps(data)",
    "docstring": "Converts `data` into json\n    If stdout is a tty it performs a pretty print."
  },
  {
    "code": "def _format_options_usage(options):\n    options_usage = \"\"\n    for op in options:\n        short, long = op.get_flags()\n        if op.arg:\n            flag = \"{short} {arg} {long}={arg}\".format(\n                short=short, long=long, arg=op.arg)\n        else:\n            flag = \"{short} {long}\".format(short=short, long=long)\n        wrapped_description = textwrap.wrap(inspect.cleandoc(op.__doc__),\n                                            width=79,\n                                            initial_indent=' ' * 32,\n                                            subsequent_indent=' ' * 32)\n        wrapped_description = \"\\n\".join(wrapped_description).strip()\n        options_usage += \"  {0:28}  {1}\\n\".format(flag, wrapped_description)\n    return options_usage",
    "docstring": "Format the Options-part of the usage text.\n\n    Parameters\n    ----------\n        options : list[sacred.commandline_options.CommandLineOption]\n            A list of all supported commandline options.\n\n    Returns\n    -------\n        str\n            Text formatted as a description for the commandline options"
  },
  {
    "code": "def unique_prefixes(context):\n    res = {}\n    for m in context.modules.values():\n        if m.keyword == \"submodule\": continue\n        prf = new = m.i_prefix\n        suff = 0\n        while new in res.values():\n            suff += 1\n            new = \"%s%x\" % (prf, suff)\n        res[m] = new\n    return res",
    "docstring": "Return a dictionary with unique prefixes for modules in `context`.\n\n    Keys are 'module' statements and values are prefixes,\n    disambiguated where necessary."
  },
  {
    "code": "def prepare_image_data(extracted_image_data, output_directory,\n                       image_mapping):\n    img_list = {}\n    for image, caption, label in extracted_image_data:\n        if not image or image == 'ERROR':\n            continue\n        image_location = get_image_location(\n            image,\n            output_directory,\n            image_mapping.keys()\n        )\n        if not image_location or not os.path.exists(image_location) or \\\n                len(image_location) < 3:\n            continue\n        image_location = os.path.normpath(image_location)\n        if image_location in img_list:\n            if caption not in img_list[image_location]['captions']:\n                img_list[image_location]['captions'].append(caption)\n        else:\n            img_list[image_location] = dict(\n                url=image_location,\n                original_url=image_mapping[image_location],\n                captions=[caption],\n                label=label,\n                name=get_name_from_path(image_location, output_directory)\n            )\n    return img_list.values()",
    "docstring": "Prepare and clean image-data from duplicates and other garbage.\n\n    :param: extracted_image_data ([(string, string, list, list) ...],\n        ...])): the images and their captions + contexts, ordered\n    :param: tex_file (string): the location of the TeX (used for finding the\n        associated images; the TeX is assumed to be in the same directory\n        as the converted images)\n    :param: image_list ([string, string, ...]): a list of the converted\n        image file names\n    :return extracted_image_data ([(string, string, list, list) ...],\n        ...])) again the list of image data cleaned for output"
  },
  {
    "code": "def _total_counts(seqs, seqL, aligned=False):\n    total = Counter()\n    if isinstance(seqs, list):\n        if not aligned:\n            l = len([total.update(seqL[s].freq) for s in seqs])\n        else:\n            l = len([total.update(seqL[s].freq) for s in seqs if seqL[s].align > 0])\n    elif isinstance(seqs, dict):\n        [total.update(seqs[s].get_freq(seqL)) for s in seqs]\n        l = sum(len(seqs[s].idmembers) for s in seqs)\n    return total, l",
    "docstring": "Counts total seqs after each step"
  },
  {
    "code": "def _next_sample_index(self):\n        idx = self.active_index_\n        self.active_index_ += 1\n        if self.active_index_ >= len(self.streams_):\n            self.active_index_ = 0\n        while self.streams_[idx] is None:\n            idx = self.active_index_\n            self.active_index_ += 1\n            if self.active_index_ >= len(self.streams_):\n                self.active_index_ = 0\n        return idx",
    "docstring": "Rotates through each active sampler by incrementing the index"
  },
  {
    "code": "def array(self):\n        if self._ind < self.shape:\n            return self._values[:self._ind]\n        if not self._cached:\n            ind = int(self._ind % self.shape)\n            self._cache[:self.shape - ind] = self._values[ind:]\n            self._cache[self.shape - ind:] = self._values[:ind]\n            self._cached = True\n        return self._cache",
    "docstring": "Returns a numpy array containing the last stored values."
  },
  {
    "code": "def socket(self, blocking=True):\n        if self._socket_lock.acquire(blocking):\n            try:\n                yield self._socket\n            finally:\n                self._socket_lock.release()",
    "docstring": "Blockingly yield the socket"
  },
  {
    "code": "def run(self, format=None, reduce=False, *args, **kwargs):\n        plan = self._generate_plan()\n        if reduce:\n            plan.graph.transitive_reduction()\n        fn = FORMATTERS[format]\n        fn(sys.stdout, plan.graph)\n        sys.stdout.flush()",
    "docstring": "Generates the underlying graph and prints it."
  },
  {
    "code": "def __telnet_event_listener(self, ip, callback):\n        tn = telnetlib.Telnet(ip, 2708)\n        self._last_event = \"\"\n        self._telnet_running = True\n        while self._telnet_running:\n            try:\n                raw_string = tn.read_until(b'.\\n', 5)\n                if len(raw_string) >= 2 and raw_string[-2:] == b'.\\n':\n                    json_string = raw_string.decode('ascii')[0:-2]\n                    if json_string != self._last_event:\n                        callback(json.loads(json_string))\n                    self._last_event = json_string\n            except:\n                pass\n        tn.close()",
    "docstring": "creates a telnet connection to the lightpad"
  },
  {
    "code": "def mkdir(dir, enter):\n    if not os.path.exists(dir):\n        os.makedirs(dir)",
    "docstring": "Create directory with template for topic of the current environment"
  },
  {
    "code": "def alg2keytype(alg):\n    if not alg or alg.lower() == \"none\":\n        return \"none\"\n    elif alg.startswith(\"RS\") or alg.startswith(\"PS\"):\n        return \"RSA\"\n    elif alg.startswith(\"HS\") or alg.startswith(\"A\"):\n        return \"oct\"\n    elif alg.startswith(\"ES\") or alg.startswith(\"ECDH-ES\"):\n        return \"EC\"\n    else:\n        return None",
    "docstring": "Go from algorithm name to key type.\n\n    :param alg: The algorithm name\n    :return: The key type"
  },
  {
    "code": "def get(self):\n        if self.arch.startswith(\"i\") and self.arch.endswith(\"86\"):\n            self.arch = self.x86\n        elif self.meta.arch.startswith(\"arm\"):\n            self.arch = self.arm\n        return self.arch",
    "docstring": "Return sbo arch"
  },
  {
    "code": "def source_sum(self):\n        if self._is_completely_masked:\n            return np.nan * self._data_unit\n        else:\n            return np.sum(self.values)",
    "docstring": "The sum of the unmasked ``data`` values within the source segment.\n\n        .. math:: F = \\\\sum_{i \\\\in S} (I_i - B_i)\n\n        where :math:`F` is ``source_sum``, :math:`(I_i - B_i)` is the\n        ``data``, and :math:`S` are the unmasked pixels in the source\n        segment.\n\n        Non-finite pixel values (e.g. NaN, infs) are excluded\n        (automatically masked)."
  },
  {
    "code": "def compose(*funcs):\n\tdef compose_two(f1, f2):\n\t\treturn lambda *args, **kwargs: f1(f2(*args, **kwargs))\n\treturn functools.reduce(compose_two, funcs)",
    "docstring": "Compose any number of unary functions into a single unary function.\n\n\t>>> import textwrap\n\t>>> from six import text_type\n\t>>> stripped = text_type.strip(textwrap.dedent(compose.__doc__))\n\t>>> compose(text_type.strip, textwrap.dedent)(compose.__doc__) == stripped\n\tTrue\n\n\tCompose also allows the innermost function to take arbitrary arguments.\n\n\t>>> round_three = lambda x: round(x, ndigits=3)\n\t>>> f = compose(round_three, int.__truediv__)\n\t>>> [f(3*x, x+1) for x in range(1,10)]\n\t[1.5, 2.0, 2.25, 2.4, 2.5, 2.571, 2.625, 2.667, 2.7]"
  },
  {
    "code": "def get_crimes_area(self, points, date=None, category=None):\n        if isinstance(category, CrimeCategory):\n            category = category.id\n        method = 'crimes-street/%s' % (category or 'all-crime')\n        kwargs = {\n            'poly': encode_polygon(points),\n        }\n        crimes = []\n        if date is not None:\n            kwargs['date'] = date\n        for c in self.service.request('POST', method, **kwargs):\n            crimes.append(Crime(self, data=c))\n        return crimes",
    "docstring": "Get crimes within a custom area. Uses the crime-street_ API call.\n\n        .. _crime-street: https//data.police.uk/docs/method/crime-street/\n\n        :rtype: list\n        :param list points: A ``list`` of ``(lat, lng)`` tuples.\n        :param date: The month in which the crimes were reported in the format\n                    ``YYYY-MM`` (the latest date is used if ``None``).\n        :type date: str or None\n        :param category: The category of the crimes to filter by (either by ID\n                         or CrimeCategory object)\n        :type category: str or CrimeCategory\n        :return: A ``list`` of crimes which were reported within the specified\n                 boundary, in the given month (optionally filtered by\n                 category)."
  },
  {
    "code": "def _table_set_column(table, name, expr):\n    expr = table._ensure_expr(expr)\n    if expr._name != name:\n        expr = expr.name(name)\n    if name not in table:\n        raise KeyError('{0} is not in the table'.format(name))\n    proj_exprs = []\n    for key in table.columns:\n        if key == name:\n            proj_exprs.append(expr)\n        else:\n            proj_exprs.append(table[key])\n    return table.projection(proj_exprs)",
    "docstring": "Replace an existing column with a new expression\n\n    Parameters\n    ----------\n    name : string\n      Column name to replace\n    expr : value expression\n      New data for column\n\n    Returns\n    -------\n    set_table : TableExpr\n      New table expression"
  },
  {
    "code": "def set_location(self, uri, size, checksum, storage_class=None):\n        self.file = FileInstance()\n        self.file.set_uri(\n            uri, size, checksum, storage_class=storage_class\n        )\n        db.session.add(self.file)\n        return self",
    "docstring": "Set only URI location of for object.\n\n        Useful to link files on externally controlled storage. If a file\n        instance has already been set, this methods raises an\n        ``FileInstanceAlreadySetError`` exception.\n\n        :param uri: Full URI to object (which can be interpreted by the storage\n            interface).\n        :param size: Size of file.\n        :param checksum: Checksum of file.\n        :param storage_class: Storage class where file is stored ()"
  },
  {
    "code": "def get_smart_storage_config(self, smart_storage_config_url):\n        return (smart_storage_config.\n                HPESmartStorageConfig(self._conn, smart_storage_config_url,\n                                      redfish_version=self.redfish_version))",
    "docstring": "Returns a SmartStorageConfig Instance for each controller."
  },
  {
    "code": "def get_file(fn):\n    fn = os.path.join(os.path.dirname(__file__), 'data', fn)\n    f = open(fn, 'rb')\n    lines = [line.decode('utf-8').strip() for line in f.readlines()]\n    return lines",
    "docstring": "Returns file contents in unicode as list."
  },
  {
    "code": "def keytype_path_to(args, keytype):\n    if keytype == \"admin\":\n        return '{cluster}.client.admin.keyring'.format(\n            cluster=args.cluster)\n    if keytype == \"mon\":\n        return '{cluster}.mon.keyring'.format(\n            cluster=args.cluster)\n    return '{cluster}.bootstrap-{what}.keyring'.format(\n            cluster=args.cluster,\n            what=keytype)",
    "docstring": "Get the local filename for a keyring type"
  },
  {
    "code": "def findlast(*args, **kwargs):\n    list_, idx = _index(*args, start=sys.maxsize, step=-1, **kwargs)\n    if idx < 0:\n        raise IndexError(\"element not found\")\n    return list_[idx]",
    "docstring": "Find the last matching element in a list and return it.\n\n    Usage::\n\n        findlast(element, list_)\n        findlast(of=element, in_=list_)\n        findlast(where=predicate, in_=list_)\n\n    :param element, of: Element to search for (by equality comparison)\n    :param where: Predicate defining an element to search for.\n                  This should be a callable taking a single argument\n                  and returning a boolean result.\n    :param list_, in_: List to search in\n\n    :return: Last matching element\n    :raise IndexError: If no matching elements were found\n\n    .. versionadded:: 0.0.4"
  },
  {
    "code": "def _validate_namespaces(self, input_namespaces):\n        output_namespaces = []\n        if input_namespaces == []:\n            return output_namespaces\n        elif '*' in input_namespaces:\n            if len(input_namespaces) > 1:\n                warning = 'Warning: Multiple namespaces are '\n                warning += 'ignored when one namespace is \"*\"\\n'\n                sys.stderr.write(warning)\n            return output_namespaces\n        else:\n            for namespace in input_namespaces:\n                if not isinstance(namespace, unicode):\n                    namespace = unicode(namespace)\n                namespace_tuple = self._tuplefy_namespace(namespace)\n                if namespace_tuple is None:\n                    warning = 'Warning: Invalid namespace ' + namespace\n                    warning += ' will be ignored\\n'\n                    sys.stderr.write(warning)\n                else:\n                    if namespace_tuple not in output_namespaces:\n                        output_namespaces.append(namespace_tuple)\n                    else:\n                        warning = 'Warning: Duplicate namespace ' + namespace\n                        warning += ' will be ignored\\n'\n                        sys.stderr.write(warning)\n        return output_namespaces",
    "docstring": "Converts a list of db namespaces to a list of namespace tuples,\n            supporting basic commandline wildcards"
  },
  {
    "code": "def string(self, units: typing.Optional[str] = None) -> str:\n        if not units:\n            _units: str = self._units\n        else:\n            if not units.upper() in CustomPressure.legal_units:\n                raise UnitsError(\"unrecognized pressure unit: '\" + units + \"'\")\n            _units = units.upper()\n        val = self.value(units)\n        if _units == \"MB\":\n            return \"%.0f mb\" % val\n        if _units == \"HPA\":\n            return \"%.0f hPa\" % val\n        if _units == \"IN\":\n            return \"%.2f inches\" % val\n        if _units == \"MM\":\n            return \"%.0f mmHg\" % val\n        raise ValueError(_units)",
    "docstring": "Return a string representation of the pressure, using the given units."
  },
  {
    "code": "def set(self, field, value):\n        if field == 'uuid':\n            raise ValueError('uuid cannot be set')\n        elif field == 'key':\n            raise ValueError(\n                'key cannot be set. Use \\'reset_key\\' method')\n        else:\n            self.data[field] = value",
    "docstring": "Sets the value of an app field.\n\n        :param str field:\n            The name of the app field. Trying to set immutable fields\n            ``uuid`` or ``key`` will raise a ValueError.\n        :param value:\n            The new value of the app field.\n        :raises: ValueError"
  },
  {
    "code": "def set(self, section, option, value=''):\n        self._string_check(value)\n        super(GitConfigParser, self).set(section, option, value)",
    "docstring": "This is overridden from the RawConfigParser merely to change the\n        default value for the 'value' argument."
  },
  {
    "code": "def render_source(self, source, variables=None):\n        if variables is None:\n            variables = {}\n        template = self._engine.from_string(source)\n        return template.render(**variables)",
    "docstring": "Render a source with the passed variables."
  },
  {
    "code": "def translate(self, exc):\n        from boto.exception import StorageResponseError\n        if isinstance(exc, StorageResponseError):\n            if exc.status == 404:\n                return self.error_cls(str(exc))\n        return None",
    "docstring": "Return whether or not to do translation."
  },
  {
    "code": "def ekf1_pos(EKF1):\n  global ekf_home\n  from . import mavutil\n  self = mavutil.mavfile_global\n  if ekf_home is None:\n      if not 'GPS' in self.messages or self.messages['GPS'].Status != 3:\n          return None\n      ekf_home = self.messages['GPS']\n      (ekf_home.Lat, ekf_home.Lng) = gps_offset(ekf_home.Lat, ekf_home.Lng, -EKF1.PE, -EKF1.PN)\n  (lat,lon) = gps_offset(ekf_home.Lat, ekf_home.Lng, EKF1.PE, EKF1.PN)\n  return (lat, lon)",
    "docstring": "calculate EKF position when EKF disabled"
  },
  {
    "code": "def _tag_ebs(self, conn, role):\n        tags = {'Name': 'spilo_' + self.cluster_name, 'Role': role, 'Instance': self.instance_id}\n        volumes = conn.get_all_volumes(filters={'attachment.instance-id': self.instance_id})\n        conn.create_tags([v.id for v in volumes], tags)",
    "docstring": "set tags, carrying the cluster name, instance role and instance id for the EBS storage"
  },
  {
    "code": "def upload_mission(aFileName):\n    missionlist = readmission(aFileName)\n    print(\"\\nUpload mission from a file: %s\" % aFileName)\n    print(' Clear mission')\n    cmds = vehicle.commands\n    cmds.clear()\n    for command in missionlist:\n        cmds.add(command)\n    print(' Upload mission')\n    vehicle.commands.upload()",
    "docstring": "Upload a mission from a file."
  },
  {
    "code": "def integral(self, bandname):\n        intg = {}\n        for det in self.rsr[bandname].keys():\n            wvl = self.rsr[bandname][det]['wavelength']\n            resp = self.rsr[bandname][det]['response']\n            intg[det] = np.trapz(resp, wvl)\n        return intg",
    "docstring": "Calculate the integral of the spectral response function for each\n        detector."
  },
  {
    "code": "def _CheckPythonVersionAndDisableWarnings(self):\n    if self._checked_for_old_python_version:\n      return\n    if sys.version_info[0:3] < (2, 7, 9):\n      logger.warning(\n          'You are running a version of Python prior to 2.7.9. Your version '\n          'of Python has multiple weaknesses in its SSL implementation that '\n          'can allow an attacker to read or modify SSL encrypted data. '\n          'Please update. Further SSL warnings will be suppressed. See '\n          'https://www.python.org/dev/peps/pep-0466/ for more information.')\n      urllib3_module = urllib3\n      if not urllib3_module:\n        if hasattr(requests, 'packages'):\n          urllib3_module = getattr(requests.packages, 'urllib3')\n      if urllib3_module and hasattr(urllib3_module, 'disable_warnings'):\n        urllib3_module.disable_warnings()\n    self._checked_for_old_python_version = True",
    "docstring": "Checks python version, and disables SSL warnings.\n\n    urllib3 will warn on each HTTPS request made by older versions of Python.\n    Rather than spamming the user, we print one warning message, then disable\n    warnings in urllib3."
  },
  {
    "code": "def libvlc_media_library_media_list(p_mlib):\n    f = _Cfunctions.get('libvlc_media_library_media_list', None) or \\\n        _Cfunction('libvlc_media_library_media_list', ((1,),), class_result(MediaList),\n                    ctypes.c_void_p, MediaLibrary)\n    return f(p_mlib)",
    "docstring": "Get media library subitems.\n    @param p_mlib: media library object.\n    @return: media list subitems."
  },
  {
    "code": "def _makeTimingAbsolute(relativeDataList, startTime, endTime):\n    timingSeq = [row[0] for row in relativeDataList]\n    valueSeq = [list(row[1:]) for row in relativeDataList]\n    absTimingSeq = makeSequenceAbsolute(timingSeq, startTime, endTime)\n    absDataList = [tuple([time, ] + row) for time, row\n                   in zip(absTimingSeq, valueSeq)]\n    return absDataList",
    "docstring": "Maps values from 0 to 1 to the provided start and end time\n\n    Input is a list of tuples of the form\n    ([(time1, pitch1), (time2, pitch2),...]"
  },
  {
    "code": "def clear(self):\n        self._index = defaultdict(list)\n        self._reverse_index = defaultdict(list)\n        self._undefined_keys = {}",
    "docstring": "Clear index."
  },
  {
    "code": "def pong(self, payload):\n        if isinstance(payload, six.text_type):\n            payload = payload.encode(\"utf-8\")\n        self.send(payload, ABNF.OPCODE_PONG)",
    "docstring": "send pong data.\n\n        payload: data payload to send server."
  },
  {
    "code": "def _cleanup_tempdir(tempdir):\n    try:\n        shutil.rmtree(tempdir)\n    except OSError as err:\n        if err.errno != errno.ENOENT:\n            raise",
    "docstring": "Clean up temp directory ignoring ENOENT errors."
  },
  {
    "code": "def keys(self):\n        keys = []\n        for app_name, __ in self.items():\n            keys.append(app_name)\n        return keys",
    "docstring": "return a list of all app_names"
  },
  {
    "code": "def getNumDownloads(self, fileInfo):\n\t\tdownloads = fileInfo[fileInfo.find(\"FILE INFORMATION\"):]\n\t\tif -1 != fileInfo.find(\"not included in ranking\"):\n\t\t\treturn \"0\"\n\t\tdownloads = downloads[:downloads.find(\".<BR>\")]\n\t\tdownloads = downloads[downloads.find(\"</A> with \") + len(\"</A> with \"):]\n\t\treturn downloads",
    "docstring": "Function to get the number of times a file has been downloaded"
  },
  {
    "code": "def create_form(self, label_columns=None, inc_columns=None,\n                    description_columns=None, validators_columns=None,\n                    extra_fields=None, filter_rel_fields=None):\n        label_columns = label_columns or {}\n        inc_columns = inc_columns or []\n        description_columns = description_columns or {}\n        validators_columns = validators_columns or {}\n        extra_fields = extra_fields or {}\n        form_props = {}\n        for col_name in inc_columns:\n            if col_name in extra_fields:\n                form_props[col_name] = extra_fields.get(col_name)\n            else:\n                self._convert_col(col_name, self._get_label(col_name, label_columns),\n                                  self._get_description(col_name, description_columns),\n                                  self._get_validators(col_name, validators_columns),\n                                  filter_rel_fields, form_props)\n        return type('DynamicForm', (DynamicForm,), form_props)",
    "docstring": "Converts a model to a form given\n\n            :param label_columns:\n                A dictionary with the column's labels.\n            :param inc_columns:\n                A list with the columns to include\n            :param description_columns:\n                A dictionary with a description for cols.\n            :param validators_columns:\n                A dictionary with WTForms validators ex::\n\n                    validators={'personal_email':EmailValidator}\n\n            :param extra_fields:\n                A dictionary containing column names and a WTForm\n                Form fields to be added to the form, these fields do not\n                 exist on the model itself ex::\n\n                    extra_fields={'some_col':BooleanField('Some Col', default=False)}\n\n            :param filter_rel_fields:\n                A filter to be applied on relationships"
  },
  {
    "code": "def attach(self, stdout=True, stderr=True, stream=True, logs=False):\n        try:\n            data = parse_stream(self.client.attach(self.id, stdout, stderr, stream, logs))\n        except KeyboardInterrupt:\n            logger.warning(\n                \"service container: {0} has been interrupted. \"\n                \"The container will be stopped but will not be deleted.\".format(self.name)\n            )\n            data = None\n            self.stop()\n        return data",
    "docstring": "Keeping this simple until we need to extend later."
  },
  {
    "code": "def on_breakpoints_changed(self, removed=False):\n        if not self.ready_to_run:\n            return\n        self.mtime += 1\n        if not removed:\n            self.set_tracing_for_untraced_contexts()",
    "docstring": "When breakpoints change, we have to re-evaluate all the assumptions we've made so far."
  },
  {
    "code": "def _print_config_text(tree, indentation=0):\n    config = ''\n    for key, value in six.iteritems(tree):\n        config += '{indent}{line}\\n'.format(indent=' '*indentation, line=key)\n        if value:\n            config += _print_config_text(value, indentation=indentation+1)\n    return config",
    "docstring": "Return the config as text from a config tree."
  },
  {
    "code": "def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]:\n    jsonschema_validate(request, schema)\n    return request",
    "docstring": "Wraps jsonschema.validate, returning the same object passed in.\n\n    Args:\n        request: The deserialized-from-json request.\n        schema: The jsonschema schema to validate against.\n\n    Raises:\n        jsonschema.ValidationError"
  },
  {
    "code": "def _integrate_fixed_trajectory(self, h, T, step, relax):\n        solution = np.hstack((self.t, self.y))\n        while self.successful():\n            self.integrate(self.t + h, step, relax)\n            current_step = np.hstack((self.t, self.y))\n            solution = np.vstack((solution, current_step))\n            if (h > 0) and (self.t >= T):\n                break\n            elif (h < 0) and (self.t <= T):\n                break\n            else:\n                continue\n        return solution",
    "docstring": "Generates a solution trajectory of fixed length."
  },
  {
    "code": "def helper_add(access_token, ck_id, path, body):\n    full_path = ''.join([path, \"('\", ck_id, \"')\"])\n    full_path_encoded = urllib.parse.quote(full_path, safe='')\n    endpoint = ''.join([ams_rest_endpoint, full_path_encoded])\n    return do_ams_put(endpoint, full_path_encoded, body, access_token, \"json_only\", \"1.0;NetFx\")",
    "docstring": "Helper Function to add strings to a URL path.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        ck_id (str): A CK ID.\n        path (str): A URL Path.\n        body (str): A Body.\n\n    Returns:\n        HTTP response. JSON body."
  },
  {
    "code": "def get_singularity_version():\n    version = os.environ.get('SPYTHON_SINGULARITY_VERSION', \"\")\n    if version == \"\":\n        try:\n            version = run_command([\"singularity\", '--version'], quiet=True)\n        except:\n            return version\n        if version['return_code'] == 0:\n            if len(version['message']) > 0:\n                version = version['message'][0].strip('\\n')\n    return version",
    "docstring": "get the singularity client version. Useful in the case that functionality\n       has changed, etc. Can be \"hacked\" if needed by exporting \n       SPYTHON_SINGULARITY_VERSION, which is checked before checking on the\n       command line."
  },
  {
    "code": "def release(self, message_id, reservation_id, delay=0):\n        url = \"queues/%s/messages/%s/release\" % (self.name, message_id)\n        body = {'reservation_id': reservation_id}\n        if delay > 0:\n            body['delay'] = delay\n        body = json.dumps(body)\n        response = self.client.post(url, body=body,\n                                    headers={'Content-Type': 'application/json'})\n        return response['body']",
    "docstring": "Release locked message after specified time. If there is no message with such id on the queue.\n\n        Arguments:\n        message_id -- The ID of the message.\n        reservation_id -- Reservation Id of the message.\n        delay -- The time after which the message will be released."
  },
  {
    "code": "def unique_authors(self, limit):\n        seen = set()\n        if limit == 0:\n            limit = None\n        seen_add = seen.add\n        return [x.author for x in self.sorted_commits[:limit]\n                if not (x.author in seen or seen_add(x.author))]",
    "docstring": "Unique list of authors, but preserving order."
  },
  {
    "code": "def cross_v2(vec1, vec2):\n    return vec1.y * vec2.x - vec1.x * vec2.y",
    "docstring": "Return the crossproduct of the two vectors as a Vec2.\n    Cross product doesn't really make sense in 2D, but return the Z component\n    of the 3d result."
  },
  {
    "code": "def serverDirectories(self):\n        directs = []\n        url = self._url + \"/directories\"\n        params = {\n            \"f\" : \"json\"\n        }\n        res = self._get(url=url,\n                           param_dict=params,\n                           securityHandler=self._securityHandler,\n                           proxy_url=self._proxy_url,\n                           proxy_port=self._proxy_port)\n        for direct in res['directories']:\n            directs.append(\n                ServerDirectory(url=url + \"/%s\" % direct[\"name\"],\n                                securityHandler=self._securityHandler,\n                                proxy_url=self._proxy_url,\n                                proxy_port=self._proxy_port,\n                                initialize=True))\n        return directs",
    "docstring": "returns the server directory object in a list"
  },
  {
    "code": "def _merge_maps(m1, m2):\n    return type(m1)(chain(m1.items(), m2.items()))",
    "docstring": "merge two Mapping objects, keeping the type of the first mapping"
  },
  {
    "code": "def get(self, blocking=True):\n    if self.closed:\n      raise PoolAlreadyClosedError(\"Connection pool is already closed.\")\n    if not self.limiter.acquire(blocking=blocking):\n      return None\n    c = None\n    try:\n      c = self.idle_conns.pop()\n    except IndexError:\n      try:\n        c = self.connect_func()\n      except Exception:\n        self.limiter.release()\n        raise\n    return _ConnectionProxy(self, c)",
    "docstring": "Gets a connection.\n\n    Args:\n      blocking: Whether to block when max_size connections are already in use.\n        If false, may return None.\n\n    Returns:\n      A connection to the database.\n\n    Raises:\n      PoolAlreadyClosedError: if close() method was already called on\n      this pool."
  },
  {
    "code": "def timestamp_file():\n    config_dir = os.path.join(\n        os.path.expanduser(\"~\"), BaseGlobalConfig.config_local_dir\n    )\n    if not os.path.exists(config_dir):\n        os.mkdir(config_dir)\n    timestamp_file = os.path.join(config_dir, \"cumulus_timestamp\")\n    try:\n        with open(timestamp_file, \"r+\") as f:\n            yield f\n    except IOError:\n        with open(timestamp_file, \"w+\") as f:\n            yield f",
    "docstring": "Opens a file for tracking the time of the last version check"
  },
  {
    "code": "def crypto_core_ed25519_add(p, q):\n    ensure(isinstance(p, bytes) and isinstance(q, bytes) and\n           len(p) == crypto_core_ed25519_BYTES and\n           len(q) == crypto_core_ed25519_BYTES,\n           'Each point must be a {} long bytes sequence'.format(\n           'crypto_core_ed25519_BYTES'),\n           raising=exc.TypeError)\n    r = ffi.new(\"unsigned char[]\", crypto_core_ed25519_BYTES)\n    rc = lib.crypto_core_ed25519_add(r, p, q)\n    ensure(rc == 0,\n           'Unexpected library error',\n           raising=exc.RuntimeError)\n    return ffi.buffer(r, crypto_core_ed25519_BYTES)[:]",
    "docstring": "Add two points on the edwards25519 curve.\n\n    :param p: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence\n              representing a point on the edwards25519 curve\n    :type p: bytes\n    :param q: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence\n              representing a point on the edwards25519 curve\n    :type q: bytes\n    :return: a point on the edwards25519 curve represented as\n             a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence\n    :rtype: bytes"
  },
  {
    "code": "def run_all(self):\n        logger.debug(\"Creating batch session\")\n        session = Session()\n        for section_id in self.parser.sections():\n            self.run_job(section_id, session=session)",
    "docstring": "Run all the jobs specified in the configuration file."
  },
  {
    "code": "def is_mastercard(n):\n    n, length = str(n), len(str(n))\n    if length >= 16 and length <= 19:\n        if ''.join(n[:2]) in strings_between(51, 56):\n            return True\n    return False",
    "docstring": "Checks if credit card number fits the mastercard format."
  },
  {
    "code": "def choice(anon, obj, field, val):\n    return anon.faker.choice(field=field)",
    "docstring": "Randomly chooses one of the choices set on the field."
  },
  {
    "code": "def _param_fields(kwargs, fields):\n  if fields is None:\n    return\n  if type(fields) in [list, set, frozenset, tuple]:\n    fields = {x: True for x in fields}\n  if type(fields) == dict:\n    fields.setdefault(\"_id\", False)\n  kwargs[\"projection\"] = fields",
    "docstring": "Normalize the \"fields\" argument to most find methods"
  },
  {
    "code": "def partial_normalize(self, axis: AxisIdentifier = 0, inplace: bool = False):\n        axis = self._get_axis(axis)\n        if not inplace:\n            copy = self.copy()\n            copy.partial_normalize(axis, inplace=True)\n            return copy\n        else:\n            self._coerce_dtype(float)\n            if axis == 0:\n                divisor = self._frequencies.sum(axis=0)\n            else:\n                divisor = self._frequencies.sum(axis=1)[:, np.newaxis]\n            divisor[divisor == 0] = 1\n            self._frequencies /= divisor\n            self._errors2 /= (divisor * divisor)\n            return self",
    "docstring": "Normalize in rows or columns.\n\n        Parameters\n        ----------\n        axis: int or str\n            Along which axis to sum (numpy-sense)\n        inplace: bool\n            Update the object itself\n\n        Returns\n        -------\n        hist : Histogram2D"
  },
  {
    "code": "def is_element_visible(driver, selector, by=By.CSS_SELECTOR):\n    try:\n        element = driver.find_element(by=by, value=selector)\n        return element.is_displayed()\n    except Exception:\n        return False",
    "docstring": "Returns whether the specified element selector is visible on the page.\n    @Params\n    driver - the webdriver object (required)\n    selector - the locator that is used (required)\n    by - the method to search for the locator (Default: By.CSS_SELECTOR)\n    @Returns\n    Boolean (is element visible)"
  },
  {
    "code": "def unpickler(zone, utcoffset=None, dstoffset=None, tzname=None):\n    tz = pytz.timezone(zone)\n    if utcoffset is None:\n        return tz\n    utcoffset = memorized_timedelta(utcoffset)\n    dstoffset = memorized_timedelta(dstoffset)\n    try:\n        return tz._tzinfos[(utcoffset, dstoffset, tzname)]\n    except KeyError:\n        pass\n    for localized_tz in tz._tzinfos.values():\n        if (localized_tz._utcoffset == utcoffset\n                and localized_tz._dst == dstoffset):\n            return localized_tz\n    inf = (utcoffset, dstoffset, tzname)\n    tz._tzinfos[inf] = tz.__class__(inf, tz._tzinfos)\n    return tz._tzinfos[inf]",
    "docstring": "Factory function for unpickling pytz tzinfo instances.\n\n    This is shared for both StaticTzInfo and DstTzInfo instances, because\n    database changes could cause a zones implementation to switch between\n    these two base classes and we can't break pickles on a pytz version\n    upgrade."
  },
  {
    "code": "def create(self, url):\n        bucket, obj_key = _parse_url(url)\n        if not bucket:\n            raise InvalidURL(url,\n                             \"You must specify a bucket and (optional) path\")\n        if obj_key:\n            target = \"/\".join((bucket, obj_key))\n        else:\n            target = bucket\n        return self.call(\"CreateBucket\", bucket=target)",
    "docstring": "Create a bucket, directory, or empty file."
  },
  {
    "code": "def _normalize_properties(self, definition):\n        args = definition.get('Properties', {}).copy()\n        if 'Condition' in definition:\n            args.update({'Condition': definition['Condition']})\n        if 'UpdatePolicy' in definition:\n            args.update({'UpdatePolicy': self._create_instance(\n                UpdatePolicy, definition['UpdatePolicy'])})\n        if 'CreationPolicy' in definition:\n            args.update({'CreationPolicy': self._create_instance(\n                CreationPolicy, definition['CreationPolicy'])})\n        if 'DeletionPolicy' in definition:\n            args.update(\n                {'DeletionPolicy': self._convert_definition(\n                    definition['DeletionPolicy'])})\n        if 'Metadata' in definition:\n            args.update(\n                {'Metadata': self._convert_definition(\n                    definition['Metadata'])})\n        if 'DependsOn' in definition:\n            args.update(\n                {'DependsOn': self._convert_definition(\n                    definition['DependsOn'])})\n        return args",
    "docstring": "Inspects the definition and returns a copy of it that is updated\n        with any special property such as Condition, UpdatePolicy and the\n        like."
  },
  {
    "code": "def _checksum(self, packet):\n        xorsum = 0\n        for s in packet:\n            xorsum ^= ord(s)\n        return xorsum",
    "docstring": "calculate the XOR checksum of a packet in string format"
  },
  {
    "code": "def fullversion():\n    cmd = 'dnsmasq -v'\n    out = __salt__['cmd.run'](cmd).splitlines()\n    comps = out[0].split()\n    version_num = comps[2]\n    comps = out[1].split()\n    return {'version': version_num,\n            'compile options': comps[3:]}",
    "docstring": "Shows installed version of dnsmasq and compile options.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' dnsmasq.fullversion"
  },
  {
    "code": "def build_sort():\n    sorts = request.args.getlist('sort')\n    sorts = [sorts] if isinstance(sorts, basestring) else sorts\n    sorts = [s.split(' ') for s in sorts]\n    return [{SORTS[s]: d} for s, d in sorts if s in SORTS]",
    "docstring": "Build sort query paramter from kwargs"
  },
  {
    "code": "def on_idle(self, event):\n        self.checkReszie()\n        if self.resized:\n            self.rescaleX()\n            self.calcFontScaling()\n            self.calcHorizonPoints()\n            self.updateRPYLocations()\n            self.updateAARLocations()\n            self.adjustPitchmarkers()\n            self.adjustHeadingPointer()\n            self.adjustNorthPointer()\n            self.updateBatteryBar()\n            self.updateStateText()\n            self.updateWPText()\n            self.adjustWPPointer()\n            self.updateAltHistory()\n            self.canvas.draw()\n            self.canvas.Refresh()\n            self.resized = False\n        time.sleep(0.05)",
    "docstring": "To adjust text and positions on rescaling the window when resized."
  },
  {
    "code": "def send_exception_to_sentry(self, exc_info):\n        if not self.sentry_client:\n            LOGGER.debug('No sentry_client, aborting')\n            return\n        message = dict(self.active_message)\n        try:\n            duration = math.ceil(time.time() - self.delivery_time) * 1000\n        except TypeError:\n            duration = 0\n        kwargs = {'extra': {\n                      'consumer_name': self.consumer_name,\n                      'env': dict(os.environ),\n                      'message': message},\n                  'time_spent': duration}\n        LOGGER.debug('Sending exception to sentry: %r', kwargs)\n        self.sentry_client.captureException(exc_info, **kwargs)",
    "docstring": "Send an exception to Sentry if enabled.\n\n        :param tuple exc_info: exception information as returned from\n            :func:`sys.exc_info`"
  },
  {
    "code": "def get_version():\n    sys.modules[\"setup_helpers\"] = object()\n    sys.modules[\"setup_helpers_macos\"] = object()\n    sys.modules[\"setup_helpers_windows\"] = object()\n    filename = os.path.join(_ROOT_DIR, \"setup.py\")\n    loader = importlib.machinery.SourceFileLoader(\"setup\", filename)\n    setup_mod = loader.load_module()\n    return setup_mod.VERSION",
    "docstring": "Get the current version from ``setup.py``.\n\n    Assumes that importing ``setup.py`` will have no side-effects (i.e.\n    assumes the behavior is guarded by ``if __name__ == \"__main__\"``).\n\n    Returns:\n        str: The current version in ``setup.py``."
  },
  {
    "code": "def get_roots(self):\n    if self.__directionless:\n      sys.stderr.write(\"ERROR: can't get roots of an undirected graph\\n\")\n      sys.exit()\n    outputids = self.__nodes.keys()\n    rootset  = set(outputids) -  set(self.__child_to_parent.keys())\n    return [self.__nodes[x] for x in rootset]",
    "docstring": "get the roots of a graph.  must be a directed graph\n\n    :returns: root list of nodes\n    :rtype: Node[]"
  },
  {
    "code": "def _add_q(self, q_object):\n        self._criteria = self._criteria._combine(q_object, q_object.connector)",
    "docstring": "Add a Q-object to the current filter."
  },
  {
    "code": "def create(cls, name, datacenter, subnet=None, gateway=None,\n               background=False):\n        if not background and not cls.intty():\n            background = True\n        datacenter_id_ = int(Datacenter.usable_id(datacenter))\n        vlan_params = {\n            'name': name,\n            'datacenter_id': datacenter_id_,\n        }\n        if subnet:\n            vlan_params['subnet'] = subnet\n        if gateway:\n            vlan_params['gateway'] = gateway\n        result = cls.call('hosting.vlan.create', vlan_params)\n        if not background:\n            cls.echo('Creating your vlan.')\n            cls.display_progress(result)\n            cls.echo('Your vlan %s has been created.' % name)\n        return result",
    "docstring": "Create a new vlan."
  },
  {
    "code": "def params(self, dict):\n        self._configuration.update(dict)\n        self._measurements.update()",
    "docstring": "Set configuration variables for an OnShape part."
  },
  {
    "code": "def encode(self, obj):\n        try:\n            result = json.dumps(obj, sort_keys=True, indent=None,\n                                separators=(',', ':'), ensure_ascii=False)\n            if isinstance(result, six.text_type):\n                return result.encode(\"utf-8\")\n            else:\n                return result\n        except (UnicodeEncodeError, TypeError) as error:\n            raise exceptions.EncodingError('json', error)",
    "docstring": "Returns ``obj`` serialized as JSON formatted bytes.\n\n        Raises\n        ------\n        ~ipfsapi.exceptions.EncodingError\n\n        Parameters\n        ----------\n        obj : str | list | dict | int\n            JSON serializable Python object\n\n        Returns\n        -------\n            bytes"
  },
  {
    "code": "def streamDefByThreshold(self,\n                             stream_raster_grid,\n                             threshold,\n                             contributing_area_grid,\n                             mask_grid=None,\n                             ):\n        log(\"PROCESS: StreamDefByThreshold\")\n        self.stream_raster_grid = stream_raster_grid\n        cmd = [os.path.join(self.taudem_exe_path, 'threshold'),\n               '-ssa', contributing_area_grid,\n               '-src', self.stream_raster_grid,\n               '-thresh', str(threshold),\n               ]\n        if mask_grid:\n            cmd += ['-mask', mask_grid]\n        self._run_mpi_cmd(cmd)\n        self._add_prj_file(contributing_area_grid,\n                           self.stream_raster_grid)",
    "docstring": "Calculates the stream definition by threshold."
  },
  {
    "code": "def run(self):\n        context = zmq.Context()\n        socket = context.socket(zmq.PUB)\n        socket.setsockopt(zmq.LINGER, 100)\n        socket.bind('ipc://' + self.timer_sock)\n        count = 0\n        log.debug('ConCache-Timer started')\n        while not self.stopped.wait(1):\n            socket.send(self.serial.dumps(count))\n            count += 1\n            if count >= 60:\n                count = 0",
    "docstring": "main loop that fires the event every second"
  },
  {
    "code": "def api_post(self, action, data, binary_data_param=None):\n        binary_data_param = binary_data_param or []\n        if binary_data_param:\n            return self.api_post_multipart(action, data, binary_data_param)\n        else:\n            return self._api_request(action, data, 'POST')",
    "docstring": "Perform an HTTP POST request, using the shared-secret auth hash.\n        @param action: API action call\n        @param data: dictionary values"
  },
  {
    "code": "def remove_token(self, token_stack, token):\n        token_stack.reverse()\n        try:\n            token_stack.remove(token)\n            retval = True\n        except ValueError:\n            retval = False\n        token_stack.reverse()\n        return retval",
    "docstring": "Remove last occurance of token from stack"
  },
  {
    "code": "def select_sample(in_file, sample, out_file, config, filters=None):\n    if not utils.file_exists(out_file):\n        with file_transaction(config, out_file) as tx_out_file:\n            if len(get_samples(in_file)) == 1:\n                shutil.copy(in_file, tx_out_file)\n            else:\n                if in_file.endswith(\".gz\"):\n                    bgzip_and_index(in_file, config)\n                bcftools = config_utils.get_program(\"bcftools\", config)\n                output_type = \"z\" if out_file.endswith(\".gz\") else \"v\"\n                filter_str = \"-f %s\" % filters if filters is not None else \"\"\n                cmd = \"{bcftools} view -O {output_type} {filter_str} {in_file} -s {sample} > {tx_out_file}\"\n                do.run(cmd.format(**locals()), \"Select sample: %s\" % sample)\n    if out_file.endswith(\".gz\"):\n        bgzip_and_index(out_file, config)\n    return out_file",
    "docstring": "Select a single sample from the supplied multisample VCF file."
  },
  {
    "code": "def set_pixel(framebuf, x, y, color):\n        index = (y >> 3) * framebuf.stride + x\n        offset = y & 0x07\n        framebuf.buf[index] = (framebuf.buf[index] & ~(0x01 << offset)) | ((color != 0) << offset)",
    "docstring": "Set a given pixel to a color."
  },
  {
    "code": "def get_client(host, userid, password, port=443, auth_method='basic',\n               client_timeout=60, **kwargs):\n    return functools.partial(scci_cmd, host, userid, password,\n                             port=port, auth_method=auth_method,\n                             client_timeout=client_timeout, **kwargs)",
    "docstring": "get SCCI command partial function\n\n    This function returns SCCI command partial function\n    :param host: hostname or IP of iRMC\n    :param userid: userid for iRMC with administrator privileges\n    :param password: password for userid\n    :param port: port number of iRMC\n    :param auth_method: irmc_username\n    :param client_timeout: timeout for SCCI operations\n    :returns: scci_cmd partial function which takes a SCCI command param"
  },
  {
    "code": "def compile_file(self, filename, encoding=\"utf-8\", bare=False):\n        if isinstance(filename, _BaseString):\n            filename = [filename]\n        scripts = []\n        for f in filename:\n            with io.open(f, encoding=encoding) as fp:\n                scripts.append(fp.read())\n        return self.compile('\\n\\n'.join(scripts), bare=bare)",
    "docstring": "compile a CoffeeScript script file to a JavaScript code.\n\n        filename can be a list or tuple of filenames,\n        then contents of files are concatenated with line feeds.\n\n        if bare is True, then compile the JavaScript without the top-level\n        function safety wrapper (like the coffee command)."
  },
  {
    "code": "def meet(self, featuresets):\n        concepts = (f.concept for f in featuresets)\n        meet = self.lattice.meet(concepts)\n        return self._featuresets[meet.index]",
    "docstring": "Return the nearest featureset that implies all given ones."
  },
  {
    "code": "async def handle_request(self, request):\n        service_name = request.rel_url.query['servicename']\n        received_code = request.rel_url.query['pairingcode'].lower()\n        _LOGGER.info('Got pairing request from %s with code %s',\n                     service_name, received_code)\n        if self._verify_pin(received_code):\n            cmpg = tags.uint64_tag('cmpg', int(self._pairing_guid, 16))\n            cmnm = tags.string_tag('cmnm', self._name)\n            cmty = tags.string_tag('cmty', 'iPhone')\n            response = tags.container_tag('cmpa', cmpg + cmnm + cmty)\n            self._has_paired = True\n            return web.Response(body=response)\n        return web.Response(status=500)",
    "docstring": "Respond to request if PIN is correct."
  },
  {
    "code": "def from_file(cls, file_path: Path, w3: Web3) -> \"Package\":\n        if isinstance(file_path, Path):\n            raw_manifest = file_path.read_text()\n            validate_raw_manifest_format(raw_manifest)\n            manifest = json.loads(raw_manifest)\n        else:\n            raise TypeError(\n                \"The Package.from_file method expects a pathlib.Path instance.\"\n                f\"Got {type(file_path)} instead.\"\n            )\n        return cls(manifest, w3, file_path.as_uri())",
    "docstring": "Returns a ``Package`` instantiated by a manifest located at the provided Path.\n        ``file_path`` arg must be a ``pathlib.Path`` instance.\n        A valid ``Web3`` instance is required to instantiate a ``Package``."
  },
  {
    "code": "def _parse_path_table(self, ptr_size, extent):\n        self._seek_to_extent(extent)\n        data = self._cdfp.read(ptr_size)\n        offset = 0\n        out = []\n        extent_to_ptr = {}\n        while offset < ptr_size:\n            ptr = path_table_record.PathTableRecord()\n            len_di_byte = bytearray([data[offset]])[0]\n            read_len = path_table_record.PathTableRecord.record_length(len_di_byte)\n            ptr.parse(data[offset:offset + read_len])\n            out.append(ptr)\n            extent_to_ptr[ptr.extent_location] = ptr\n            offset += read_len\n        return out, extent_to_ptr",
    "docstring": "An internal method to parse a path table on an ISO.  For each path\n        table entry found, a Path Table Record object is created, and the\n        callback is called.\n\n        Parameters:\n         vd - The volume descriptor that these path table records correspond to.\n         extent - The extent at which this path table record starts.\n         callback - The callback to call for each path table record.\n        Returns:\n         A tuple consisting of the list of path table record entries and a\n         dictionary of the extent locations to the path table record entries."
  },
  {
    "code": "def _get_whitelist_licenses(config_path):\n    whitelist_licenses = []\n    try:\n        print('config path', config_path)\n        with open(config_path) as config:\n            whitelist_licenses = [line.rstrip() for line in config]\n    except IOError:\n        print('Warning: No {} file was found.'.format(LICENSE_CHECKER_CONFIG_NAME))\n    return whitelist_licenses",
    "docstring": "Get whitelist license names from config file.\n\n    :param config_path: str\n    :return: list"
  },
  {
    "code": "def _get_type_hints(func, args = None, res = None, infer_defaults = None):\n    if args is None or res is None:\n        args2, res2 = _get_types(func, util.is_classmethod(func),\n                util.is_method(func), unspecified_type = type(NotImplemented),\n                infer_defaults = infer_defaults)\n        if args is None:\n            args = args2\n        if res is None:\n            res = res2\n    slf = 1 if util.is_method(func) else 0\n    argNames = util.getargnames(util.getargspecs(util._actualfunc(func)))\n    result = {}\n    if not args is Any:\n        prms = get_Tuple_params(args)\n        for i in range(slf, len(argNames)):\n            if not prms[i-slf] is type(NotImplemented):\n                result[argNames[i]] = prms[i-slf]\n    result['return'] = res\n    return result",
    "docstring": "Helper for get_type_hints."
  },
  {
    "code": "def add_fs(self, name, fs, write=False, priority=0):\n        if isinstance(fs, text_type):\n            fs = open_fs(fs)\n        if not isinstance(fs, FS):\n            raise TypeError(\"fs argument should be an FS object or FS URL\")\n        self._filesystems[name] = _PrioritizedFS(\n            priority=(priority, self._sort_index), fs=fs\n        )\n        self._sort_index += 1\n        self._resort()\n        if write:\n            self.write_fs = fs\n            self._write_fs_name = name",
    "docstring": "Add a filesystem to the MultiFS.\n\n        Arguments:\n            name (str): A unique name to refer to the filesystem being\n                added.\n            fs (FS or str): The filesystem (instance or URL) to add.\n            write (bool): If this value is True, then the ``fs`` will\n                be used as the writeable FS (defaults to False).\n            priority (int): An integer that denotes the priority of the\n                filesystem being added. Filesystems will be searched in\n                descending priority order and then by the reverse order\n                they were added. So by default, the most recently added\n                filesystem will be looked at first."
  },
  {
    "code": "def add_time(self, extra_time):\n        window_start = self.parent.value('window_start') + extra_time\n        self.parent.overview.update_position(window_start)",
    "docstring": "Go to the predefined time forward."
  },
  {
    "code": "def update_workspace_acl(namespace, workspace, acl_updates, invite_users_not_found=False):\n    uri = \"{0}workspaces/{1}/{2}/acl?inviteUsersNotFound={3}\".format(fcconfig.root_url,\n                                                namespace, workspace, str(invite_users_not_found).lower())\n    headers = _fiss_agent_header({\"Content-type\":  \"application/json\"})\n    return __SESSION.patch(uri, headers=headers, data=json.dumps(acl_updates))",
    "docstring": "Update workspace access control list.\n\n    Args:\n        namespace (str): project to which workspace belongs\n        workspace (str): Workspace name\n        acl_updates (list(dict)): Acl updates as dicts with two keys:\n            \"email\" - Firecloud user email\n            \"accessLevel\" - one of \"OWNER\", \"READER\", \"WRITER\", \"NO ACCESS\"\n            Example: {\"email\":\"user1@mail.com\", \"accessLevel\":\"WRITER\"}\n        invite_users_not_found (bool): true to invite unregistered users, false to ignore\n\n    Swagger:\n        https://api.firecloud.org/#!/Workspaces/updateWorkspaceACL"
  },
  {
    "code": "def check_file(self, fs, info):\n        if self.exclude is not None and fs.match(self.exclude, info.name):\n            return False\n        return fs.match(self.filter, info.name)",
    "docstring": "Check if a filename should be included.\n\n        Override to exclude files from the walk.\n\n        Arguments:\n            fs (FS): A filesystem instance.\n            info (Info): A resource info object.\n\n        Returns:\n            bool: `True` if the file should be included."
  },
  {
    "code": "def evaluator(evaluate):\n    @functools.wraps(evaluate)\n    def inspyred_evaluator(candidates, args):\n        fitness = []\n        for candidate in candidates:\n            fitness.append(evaluate(candidate, args))\n        return fitness\n    inspyred_evaluator.single_evaluation = evaluate\n    return inspyred_evaluator",
    "docstring": "Return an inspyred evaluator function based on the given function.\n    \n    This function generator takes a function that evaluates only one\n    candidate. The generator handles the iteration over each candidate \n    to be evaluated.\n\n    The given function ``evaluate`` must have the following signature::\n    \n        fitness = evaluate(candidate, args)\n        \n    This function is most commonly used as a function decorator with\n    the following usage::\n    \n        @evaluator\n        def evaluate(candidate, args):\n            # Implementation of evaluation\n            pass\n            \n    The generated function also contains an attribute named\n    ``single_evaluation`` which holds the original evaluation function.\n    In this way, the original single-candidate function can be\n    retrieved if necessary."
  },
  {
    "code": "def _tm(self, theta, phi, psi, dx, dy, dz):\n        matrix = self.get_matrix(theta, phi, psi, dx, dy, dz)\n        coord = matrix.dot(self.coord2)\n        dist = coord - self.coord1\n        d_i2 = (dist * dist).sum(axis=0)\n        tm = -(1 / (1 + (d_i2 / self.d02)))\n        return tm",
    "docstring": "Compute the minimisation target, not normalised."
  },
  {
    "code": "def download(cls, url, filename=None):\n        return utility.download(url, cls.directory(), filename)",
    "docstring": "Download a file into the correct cache directory."
  },
  {
    "code": "def encrypt_data(self, name, plaintext, context=\"\", key_version=0, nonce=None, batch_input=None, type=\"aes256-gcm96\",\n                     convergent_encryption=\"\", mount_point=DEFAULT_MOUNT_POINT):\n        params = {\n            'plaintext': plaintext,\n            'context': context,\n            'key_version': key_version,\n            'nonce': nonce,\n            'batch_input': batch_input,\n            'type': type,\n            'convergent_encryption': convergent_encryption,\n        }\n        api_path = '/v1/{mount_point}/encrypt/{name}'.format(\n            mount_point=mount_point,\n            name=name,\n        )\n        response = self._adapter.post(\n            url=api_path,\n            json=params,\n        )\n        return response.json()",
    "docstring": "Encrypt the provided plaintext using the named key.\n\n        This path supports the create and update policy capabilities as follows: if the user has the create capability\n        for this endpoint in their policies, and the key does not exist, it will be upserted with default values\n        (whether the key requires derivation depends on whether the context parameter is empty or not). If the user only\n        has update capability and the key does not exist, an error will be returned.\n\n        Supported methods:\n            POST: /{mount_point}/encrypt/{name}. Produces: 200 application/json\n\n        :param name: Specifies the name of the encryption key to encrypt against. This is specified as part of the URL.\n        :type name: str | unicode\n        :param plaintext: Specifies base64 encoded plaintext to be encoded.\n        :type plaintext: str | unicode\n        :param context: Specifies the base64 encoded context for key derivation. This is required if key derivation is\n            enabled for this key.\n        :type context: str | unicode\n        :param key_version: Specifies the version of the key to use for encryption. If not set, uses the latest version.\n            Must be greater than or equal to the key's min_encryption_version, if set.\n        :type key_version: int\n        :param nonce: Specifies the base64 encoded nonce value. This must be provided if convergent encryption is\n            enabled for this key and the key was generated with Vault 0.6.1. Not required for keys created in 0.6.2+.\n            The value must be exactly 96 bits (12 bytes) long and the user must ensure that for any given context (and\n            thus, any given encryption key) this nonce value is never reused.\n        :type nonce: str | unicode\n        :param batch_input: Specifies a list of items to be encrypted in a single batch. When this parameter is set, if\n            the parameters 'plaintext', 'context' and 'nonce' are also set, they will be ignored. The format for the\n            input is: [dict(context=\"b64_context\", plaintext=\"b64_plaintext\"), ...]\n        :type batch_input: List[dict]\n        :param type: This parameter is required when encryption key is expected to be created. When performing an\n            upsert operation, the type of key to create.\n        :type type: str | unicode\n        :param convergent_encryption: This parameter will only be used when a key is expected to be created. Whether to\n            support convergent encryption. This is only supported when using a key with key derivation enabled and will\n            require all requests to carry both a context and 96-bit (12-byte) nonce. The given nonce will be used in\n            place of a randomly generated nonce. As a result, when the same context and nonce are supplied, the same\n            ciphertext is generated. It is very important when using this mode that you ensure that all nonces are\n            unique for a given context. Failing to do so will severely impact the ciphertext's security.\n        :type convergent_encryption: str | unicode\n        :param mount_point: The \"path\" the method/backend was mounted on.\n        :type mount_point: str | unicode\n        :return: The JSON response of the request.\n        :rtype: requests.Response"
  },
  {
    "code": "def create_response(request, body=None, status=None, headers=None):\n    if body is None:\n        return HttpResponse(None, status or HTTPStatus.NO_CONTENT, headers)\n    else:\n        body = request.response_codec.dumps(body)\n        response = HttpResponse(body, status or HTTPStatus.OK, headers)\n        response.set_content_type(request.response_codec.CONTENT_TYPE)\n        return response",
    "docstring": "Generate a HttpResponse.\n\n    :param request: Request object\n    :param body: Body of the response\n    :param status: HTTP status code\n    :param headers: Any headers."
  },
  {
    "code": "def zremrangebyscore(self, key, min_score, max_score):\n        return self._execute([b'ZREMRANGEBYSCORE', key, min_score, max_score])",
    "docstring": "Removes all elements in the sorted set stored at key with a score\n        between min and max.\n\n        Intervals are described in :meth:`~tredis.RedisClient.zrangebyscore`.\n\n        Returns the number of elements removed.\n\n        .. note::\n\n           **Time complexity**: ``O(log(N)+M)`` with ``N`` being the number of\n           elements in the sorted set and M the number of elements removed by\n           the operation.\n\n        :param key: The key of the sorted set\n        :type key: :class:`str`, :class:`bytes`\n        :param min_score: Lowest score definition\n        :type min_score: :class:`str`, :class:`bytes`\n        :param max_score: Highest score definition\n        :type max_score: :class:`str`, :class:`bytes`\n        :rtype: int\n        :raises: :exc:`~tredis.exceptions.RedisError`"
  },
  {
    "code": "def add_tag_for_component(user, c_id):\n    v1_utils.verify_existence_and_get(c_id, _TABLE)\n    values = {\n        'component_id': c_id\n    }\n    component_tagged = tags.add_tag_to_resource(values,\n                                                models.JOIN_COMPONENTS_TAGS)\n    return flask.Response(json.dumps(component_tagged), 201,\n                          content_type='application/json')",
    "docstring": "Add a tag on a specific component."
  },
  {
    "code": "def triangle_center(tri, uv=False):\n    if uv:\n        data = [t.uv for t in tri]\n        mid = [0.0, 0.0]\n    else:\n        data = tri.vertices\n        mid = [0.0, 0.0, 0.0]\n    for vert in data:\n        mid = [m + v for m, v in zip(mid, vert)]\n    mid = [float(m) / 3.0 for m in mid]\n    return tuple(mid)",
    "docstring": "Computes the center of mass of the input triangle.\n\n    :param tri: triangle object\n    :type tri: elements.Triangle\n    :param uv: if True, then finds parametric position of the center of mass\n    :type uv: bool\n    :return: center of mass of the triangle\n    :rtype: tuple"
  },
  {
    "code": "def writeinfo(self, linelist, colour = None):\n        self.checkforpilimage()\n        colour = self.defaultcolour(colour)\n        self.changecolourmode(colour)\n        self.makedraw()\n        self.loadinfofont()\n        for i, line in enumerate(linelist):\n            topspacing = 5 + (12 + 5)*i\n            self.draw.text((10, topspacing), line, fill = colour, font = self.infofont)\n        if self.verbose :\n            print \"I've written some info on the image.\"",
    "docstring": "We add a longer chunk of text on the upper left corner of the image.\n        Provide linelist, a list of strings that will be written one below the other."
  },
  {
    "code": "def __connect(self, wsURL, symbol):\n        self.logger.debug(\"Starting thread\")\n        self.ws = websocket.WebSocketApp(wsURL,\n                                         on_message=self.__on_message,\n                                         on_close=self.__on_close,\n                                         on_open=self.__on_open,\n                                         on_error=self.__on_error,\n                                         header=self.__get_auth())\n        self.wst = threading.Thread(target=lambda: self.ws.run_forever())\n        self.wst.daemon = True\n        self.wst.start()\n        self.logger.debug(\"Started thread\")\n        conn_timeout = 5\n        while not self.ws.sock or not self.ws.sock.connected and conn_timeout:\n            sleep(1)\n            conn_timeout -= 1\n        if not conn_timeout:\n            self.logger.error(\"Couldn't connect to WS! Exiting.\")\n            self.exit()\n            sys.exit(1)",
    "docstring": "Connect to the websocket in a thread."
  },
  {
    "code": "def pipes(stream, *transformers):\n    for transformer in transformers:\n        stream = stream.pipe(transformer)\n    return stream",
    "docstring": "Pipe several transformers end to end."
  },
  {
    "code": "def mongo_retry(f):\n    log_all_exceptions = 'arctic' in f.__module__ if f.__module__ else False\n    @wraps(f)\n    def f_retry(*args, **kwargs):\n        global _retry_count, _in_retry\n        top_level = not _in_retry\n        _in_retry = True\n        try:\n            while True:\n                try:\n                    return f(*args, **kwargs)\n                except (DuplicateKeyError, ServerSelectionTimeoutError) as e:\n                    _handle_error(f, e, _retry_count, **_get_host(args))\n                    raise\n                except (OperationFailure, AutoReconnect) as e:\n                    _retry_count += 1\n                    _handle_error(f, e, _retry_count, **_get_host(args))\n                except Exception as e:\n                    if log_all_exceptions:\n                        _log_exception(f.__name__, e, _retry_count, **_get_host(args))\n                    raise\n        finally:\n            if top_level:\n                _in_retry = False\n                _retry_count = 0\n    return f_retry",
    "docstring": "Catch-all decorator that handles AutoReconnect and OperationFailure\n    errors from PyMongo"
  },
  {
    "code": "def cmd_create(args):\n    if args.type == SQLITE:\n        if args.output is not None and path.exists(args.output):\n            remove(args.output)\n        storage = SqliteStorage(db=args.output, settings=args.settings)\n    else:\n        storage = JsonStorage(settings=args.settings)\n    markov = MarkovText.from_storage(storage)\n    read(args.input, markov, args.progress)\n    save(markov, args.output, args)",
    "docstring": "Create a generator.\n\n    Parameters\n    ----------\n    args : `argparse.Namespace`\n        Command arguments."
  },
  {
    "code": "def create_policy(policyName, policyDocument,\n            region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        if not isinstance(policyDocument, string_types):\n            policyDocument = salt.utils.json.dumps(policyDocument)\n        policy = conn.create_policy(policyName=policyName,\n                                    policyDocument=policyDocument)\n        if policy:\n            log.info('The newly created policy version is %s', policy['policyVersionId'])\n            return {'created': True, 'versionId': policy['policyVersionId']}\n        else:\n            log.warning('Policy was not created')\n            return {'created': False}\n    except ClientError as e:\n        return {'created': False, 'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Given a valid config, create a policy.\n\n    Returns {created: true} if the policy was created and returns\n    {created: False} if the policy was not created.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_iot.create_policy my_policy \\\\\n              '{\"Version\":\"2015-12-12\",\\\\\n              \"Statement\":[{\"Effect\":\"Allow\",\\\\\n                            \"Action\":[\"iot:Publish\"],\\\\\n                            \"Resource\":[\"arn:::::topic/foo/bar\"]}]}'"
  },
  {
    "code": "def get_bounds(pts):\n    pts_t = np.asarray(pts).T\n    return np.asarray(([np.min(_pts) for _pts in pts_t],\n                       [np.max(_pts) for _pts in pts_t]))",
    "docstring": "Return the minimum point and maximum point bounding a\n    set of points."
  },
  {
    "code": "def http_get(url, filename=None):\n    try:\n        ret = requests.get(url)\n    except requests.exceptions.SSLError as error:\n        _LOGGER.error(error)\n        return False\n    if ret.status_code != 200:\n        return False\n    if filename is None:\n        return ret.content\n    with open(filename, 'wb') as data:\n        data.write(ret.content)\n    return True",
    "docstring": "Download HTTP data."
  },
  {
    "code": "def job_started_message(self, job, queue):\n        return '[%s|%s|%s] starting' % (queue._cached_name, job.pk.get(),\n                                        job._cached_identifier)",
    "docstring": "Return the message to log just befre the execution of the job"
  },
  {
    "code": "def _deserialize(self, value, attr, data):\n        if not self.context.get('convert_dates', True) or not value:\n            return value\n        value = super(ArrowField, self)._deserialize(value, attr, data)\n        timezone = self.get_field_value('timezone')\n        target = arrow.get(value)\n        if timezone and text_type(target.to(timezone)) != text_type(target):\n            raise ValidationError(\n                \"The provided datetime is not in the \"\n                \"{} timezone.\".format(timezone)\n            )\n        return target",
    "docstring": "Deserializes a string into an Arrow object."
  },
  {
    "code": "def make_response(message, status_code, details=None):\n    response_body = dict(message=message)\n    if details:\n        response_body['details'] = details\n    response = jsonify(response_body)\n    response.status_code = status_code\n    return response",
    "docstring": "Make a jsonified response with specified message and status code."
  },
  {
    "code": "def pack(self):\n        if six.PY3:\n            return {'message': six.text_type(self), 'args': self.args}\n        return dict(message=self.__unicode__(), args=self.args)",
    "docstring": "Pack this exception into a serializable dictionary that is safe for\n        transport via msgpack"
  },
  {
    "code": "def disable_logger(self, disabled=True):\n        if disabled:\n            sys.stdout = _original_stdout\n            sys.stderr = _original_stderr\n        else:\n            sys.stdout = self.__stdout_stream\n            sys.stderr = self.__stderr_stream\n        self.logger.disabled = disabled",
    "docstring": "Disable all logging calls."
  },
  {
    "code": "def bin(x, bins, maxX=None, minX=None):\n    if maxX is None:\n        maxX = x.max()\n    if minX is None:\n        minX = x.min()\n    if not np.iterable(bins):\n        bins = np.linspace(minX, maxX+1e-5, bins+1)\n    return np.digitize(x.ravel(), bins).reshape(x.shape), bins",
    "docstring": "bin signal x using 'binsN' bin. If minX, maxX are None, they default to the full\n    range of the signal. If they are not None, everything above maxX gets assigned to\n    binsN-1 and everything below minX gets assigned to 0, this is effectively the same\n    as clipping x before passing it to 'bin'\n\n    input:\n    -----\n        x:      signal to be binned, some sort of iterable\n\n        bins:   int, number of bins\n                iterable, bin edges\n\n        maxX:   clips data above maxX\n\n        minX:   clips data below maxX\n\n    output:\n    ------\n        binnedX:    x after being binned\n\n        bins:       bins used for binning.\n                    if input 'bins' is already an iterable it just returns the\n                    same iterable\n\n    example:\n        # make 10 bins of equal length spanning from x.min() to x.max()\n        bin(x, 10)\n\n        # use predefined bins such that each bin has the same number of points (maximize\n        entropy)\n        binsN = 10\n        percentiles = list(np.arange(0, 100.1, 100/binsN))\n        bins = np.percentile(x, percentiles)\n        bin(x, bins)"
  },
  {
    "code": "def set_execution_mode(self, execution_mode, notify=True):\n        if not isinstance(execution_mode, StateMachineExecutionStatus):\n            raise TypeError(\"status must be of type StateMachineExecutionStatus\")\n        self._status.execution_mode = execution_mode\n        if notify:\n            self._status.execution_condition_variable.acquire()\n            self._status.execution_condition_variable.notify_all()\n            self._status.execution_condition_variable.release()",
    "docstring": "An observed setter for the execution mode of the state machine status. This is necessary for the\n        monitoring client to update the local state machine in the same way as the root state machine of the server.\n\n        :param execution_mode: the new execution mode of the state machine\n        :raises exceptions.TypeError: if the execution mode is of the wrong type"
  },
  {
    "code": "def print_dedicated_access(access):\n    table = formatting.Table(['id', 'Name', 'Cpus', 'Memory', 'Disk', 'Created'], 'Dedicated Access')\n    for host in access:\n        host_id = host.get('id')\n        host_fqdn = host.get('name')\n        host_cpu = host.get('cpuCount')\n        host_mem = host.get('memoryCapacity')\n        host_disk = host.get('diskCapacity')\n        host_created = host.get('createDate')\n        table.add_row([host_id, host_fqdn, host_cpu, host_mem, host_disk, host_created])\n    return table",
    "docstring": "Prints out the dedicated hosts a user can access"
  },
  {
    "code": "def get_hyperedge_id(self, tail, head):\n        frozen_tail = frozenset(tail)\n        frozen_head = frozenset(head)\n        if not self.has_hyperedge(frozen_tail, frozen_head):\n            raise ValueError(\"No such hyperedge exists.\")\n        return self._successors[frozen_tail][frozen_head]",
    "docstring": "From a tail and head set of nodes, returns the ID of the hyperedge\n        that these sets comprise.\n\n        :param tail: iterable container of references to nodes in the\n                    tail of the hyperedge to be added\n        :param head: iterable container of references to nodes in the\n                    head of the hyperedge to be added\n        :returns: str -- ID of the hyperedge that has that the specified\n                tail and head sets comprise.\n        :raises: ValueError -- No such hyperedge exists.\n\n        Examples:\n        ::\n\n            >>> H = DirectedHypergraph()\n            >>> hyperedge_list = ([\"A\"], [\"B\", \"C\"]),\n                                  ((\"A\", \"B\"), (\"C\"), {weight: 2}),\n                                  (set([\"B\"]), set([\"A\", \"C\"])))\n            >>> hyperedge_ids = H.add_hyperedges(hyperedge_list)\n            >>> x = H.get_hyperedge_id([\"A\"], [\"B\", \"C\"])"
  },
  {
    "code": "def validate_date(date, project_member_id, filename):\n    try:\n        arrow.get(date)\n    except Exception:\n        return False\n    return True",
    "docstring": "Check if date is in ISO 8601 format.\n\n    :param date: This field is the date to be checked.\n    :param project_member_id: This field is the project_member_id corresponding\n        to the date provided.\n    :param filename: This field is the filename corresponding to the date\n        provided."
  },
  {
    "code": "def unbounded(self):\n        self._check_valid()\n        return (self._problem._p.get_status() ==\n                qsoptex.SolutionStatus.UNBOUNDED)",
    "docstring": "Whether the solution is unbounded"
  },
  {
    "code": "def list_networks(kwargs=None, call=None):\n    if call != 'function':\n        raise SaltCloudSystemExit(\n            'The list_networks function must be called with '\n            '-f or --function.'\n        )\n    return {'Networks': salt.utils.vmware.list_networks(_get_si())}",
    "docstring": "List all the standard networks for this VMware environment\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -f list_networks my-vmware-config"
  },
  {
    "code": "def schedule_violations(schedule, events, slots):\n    array = converter.schedule_to_array(schedule, events, slots)\n    return array_violations(array, events, slots)",
    "docstring": "Take a schedule and return a list of violated constraints\n\n    Parameters\n    ----------\n        schedule : list or tuple\n            a schedule in schedule form\n        events : list or tuple\n            of resources.Event instances\n        slots : list or tuple\n            of resources.Slot instances\n\n    Returns\n    -------\n        Generator\n            of a list of strings indicating the nature of the violated\n            constraints"
  },
  {
    "code": "def clear(self):\n        self._level = None\n        self._fingerprint = None\n        self._transaction = None\n        self._user = None\n        self._tags = {}\n        self._contexts = {}\n        self._extras = {}\n        self.clear_breadcrumbs()\n        self._should_capture = True\n        self._span = None",
    "docstring": "Clears the entire scope."
  },
  {
    "code": "def build_command(self, config, **kwargs):\n        command = ['perl', self.script, CLI_OPTIONS['config']['option'], config]\n        for key, value in kwargs.items():\n            if value:\n                command.append(CLI_OPTIONS[key]['option'])\n                if value is True:\n                    command.append(CLI_OPTIONS[key].get('default', '1'))\n                else:\n                    command.append(value)\n        return command",
    "docstring": "Builds the command to execute MIP."
  },
  {
    "code": "def relabel_squeeze(data):\n    palette, index = np.unique(data, return_inverse=True)\n    data = index.reshape(data.shape)\n    return data",
    "docstring": "Makes relabeling of data if there are unused values."
  },
  {
    "code": "def _get_recipients(self, array):\n        for address, name in array:\n            if not name:\n                yield address\n            else:\n                yield \"\\\"%s\\\" <%s>\" % (name, address)",
    "docstring": "Returns an iterator of objects\n           in the form [\"Name <address@example.com\", ...]\n           from the array [[\"address@example.com\", \"Name\"]]"
  },
  {
    "code": "def inverse_gaussian_gradient(image, alpha=100.0, sigma=5.0):\n    gradnorm = ndi.gaussian_gradient_magnitude(image, sigma, mode='nearest')\n    return 1.0 / np.sqrt(1.0 + alpha * gradnorm)",
    "docstring": "Inverse of gradient magnitude.\n\n    Compute the magnitude of the gradients in the image and then inverts the\n    result in the range [0, 1]. Flat areas are assigned values close to 1,\n    while areas close to borders are assigned values close to 0.\n\n    This function or a similar one defined by the user should be applied over\n    the image as a preprocessing step before calling\n    `morphological_geodesic_active_contour`.\n\n    Parameters\n    ----------\n    image : (M, N) or (L, M, N) array\n        Grayscale image or volume.\n    alpha : float, optional\n        Controls the steepness of the inversion. A larger value will make the\n        transition between the flat areas and border areas steeper in the\n        resulting array.\n    sigma : float, optional\n        Standard deviation of the Gaussian filter applied over the image.\n\n    Returns\n    -------\n    gimage : (M, N) or (L, M, N) array\n        Preprocessed image (or volume) suitable for\n        `morphological_geodesic_active_contour`."
  },
  {
    "code": "def from_etree(root):\n        cite_list = []\n        citations = root.xpath('Citations/EventIVORN')\n        if citations:\n            description = root.xpath('Citations/Description')\n            if description:\n                description_text = description[0].text\n            else:\n                description_text = None\n            for entry in root.Citations.EventIVORN:\n                if entry.text:\n                    cite_list.append(\n                        Cite(ref_ivorn=entry.text,\n                             cite_type=entry.attrib['cite'],\n                             description=description_text)\n                    )\n                else:\n                    logger.info(\n                        'Ignoring empty citation in {}'.format(\n                            root.attrib['ivorn']))\n        return cite_list",
    "docstring": "Load up the citations, if present, for initializing with the Voevent."
  },
  {
    "code": "def get_downbeat_steps(self):\n        if self.downbeat is None:\n            return []\n        downbeat_steps = np.nonzero(self.downbeat)[0].tolist()\n        return downbeat_steps",
    "docstring": "Return the indices of time steps that contain downbeats.\n\n        Returns\n        -------\n        downbeat_steps : list\n            The indices of time steps that contain downbeats."
  },
  {
    "code": "def parse_blast(blast_string):\n    soup = BeautifulSoup(str(blast_string), \"html.parser\")\n    all_blasts = list()\n    all_blast_ids = list()\n    pattern = '></a>....:'\n    prog = re.compile(pattern)\n    for item in soup.find_all('pre'):\n        if len(item.find_all('a'))==1:\n            all_blasts.append(item)\n            blast_id = re.findall(pattern, str(item) )[0][-5:-1]\n            all_blast_ids.append(blast_id)\n    out = (all_blast_ids, all_blasts)\n    return out",
    "docstring": "Clean up HTML BLAST results\n\n    This function requires BeautifulSoup and the re module\n    It goes throught the complicated output returned by the BLAST\n    search and provides a list of matches, as well as the raw\n    text file showing the alignments for each of the matches.\n\n    This function works best with HTML formatted Inputs\n    ------\n\n    get_blast() uses this function internally\n\n    Parameters\n    ----------\n\n    blast_string : str\n        A complete webpage of standard BLAST results\n\n    Returns\n    -------\n\n    out : 2-tuple\n        A tuple consisting of a list of PDB matches, and a list\n        of their alignment text files (unformatted)"
  },
  {
    "code": "def get_bundle_by_id(self, bundle_id):\n        if bundle_id == 0:\n            return self\n        with self.__bundles_lock:\n            if bundle_id not in self.__bundles:\n                raise BundleException(\"Invalid bundle ID {0}\".format(bundle_id))\n            return self.__bundles[bundle_id]",
    "docstring": "Retrieves the bundle with the given ID\n\n        :param bundle_id: ID of an installed bundle\n        :return: The requested bundle\n        :raise BundleException: The ID is invalid"
  },
  {
    "code": "def resetToPreviousLoc(self):\r\n        self.rect.left = self.startDraggingX\r\n        self.rect.top = self.startDraggingY",
    "docstring": "Resets the loc of the dragger to place where dragging started.\r\n\r\n        This could be used in a test situation if the dragger was dragged to an incorrect location."
  },
  {
    "code": "def check_imts(self, imts):\n        for trt in self.values:\n            for gsim in self.values[trt]:\n                for attr in dir(gsim):\n                    coeffs = getattr(gsim, attr)\n                    if not isinstance(coeffs, CoeffsTable):\n                        continue\n                    for imt in imts:\n                        if imt.startswith('SA'):\n                            try:\n                                coeffs[from_string(imt)]\n                            except KeyError:\n                                raise ValueError(\n                                    '%s is out of the period range defined '\n                                    'for %s' % (imt, gsim))",
    "docstring": "Make sure the IMTs are recognized by all GSIMs in the logic tree"
  },
  {
    "code": "def the_one(cls):\n        if cls.THE_ONE is None:\n            cls.THE_ONE = cls(settings.HELP_TOKENS_INI_FILE)\n        return cls.THE_ONE",
    "docstring": "Get the single global HelpUrlExpert object."
  },
  {
    "code": "def _gregorian_to_ssweek(date_value):\n    \"Sundaystarting-week year, week and day for the given  Gregorian calendar date\"\n    yearStart = _ssweek_year_start(date_value.year)\n    weekNum = ((date_value - yearStart).days) // 7 + 1\n    dayOfWeek = date_value.weekday()+1\n    return (date_value.year, weekNum, dayOfWeek)",
    "docstring": "Sundaystarting-week year, week and day for the given  Gregorian calendar date"
  },
  {
    "code": "def post_authenticate(self):\n        goldman.sess.login = self\n        now = dt.now()\n        if not self.login_date:\n            self.login_date = now\n        else:\n            sec_since_updated = (now - self.login_date).seconds\n            min_since_updated = sec_since_updated / 60\n            if min_since_updated > 15:\n                self.login_date = now\n        if self.dirty:\n            store = goldman.sess.store\n            store.update(self)",
    "docstring": "Update the login_date timestamp\n\n        Initialize the thread local sess.login property with\n        the authenticated login model.\n\n        The login_date update will be debounced so writes don't\n        occur on every hit of the the API. If the login_date\n        was modified within 15 minutes then don't update it."
  },
  {
    "code": "def format_style(number: int) -> str:\n    if str(number) not in _stylenums:\n        raise InvalidStyle(number)\n    return codeformat(number)",
    "docstring": "Return an escape code for a style, by number.\n        This handles invalid style numbers."
  },
  {
    "code": "def generate_output_path(args, project_path):\n    milisec = datetime.now().microsecond\n    dirname = 'results_{}_{}'.format(time.strftime('%Y.%m.%d_%H.%M.%S', time.localtime()), str(milisec))\n    return os.path.join(project_path, 'results', dirname)",
    "docstring": "Generate default output directory"
  },
  {
    "code": "def ec_construct_private(num):\n    pub_ecpn = ec.EllipticCurvePublicNumbers(num['x'], num['y'],\n                                             NIST2SEC[as_unicode(num['crv'])]())\n    priv_ecpn = ec.EllipticCurvePrivateNumbers(num['d'], pub_ecpn)\n    return priv_ecpn.private_key(default_backend())",
    "docstring": "Given a set of values on public and private attributes build a elliptic\n    curve private key instance.\n\n    :param num: A dictionary with public and private attributes and their values\n    :return: A\n        cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey\n        instance."
  },
  {
    "code": "def _pickle_batch(self):\n        payload = pickle.dumps(self.batch)\n        header = struct.pack(\"!L\", len(payload))\n        message = header + payload\n        return message",
    "docstring": "Pickle the metrics into a form that can be understood\n        by the graphite pickle connector."
  },
  {
    "code": "def on_message(self, handler, msg):\n        if self.remote_debugging:\n            for h in self.handlers:\n                if h != handler:\n                    h.write_message(msg, True)\n        else:\n            print(msg)",
    "docstring": "In remote debugging mode this simply acts as a forwarding\n        proxy for the two clients."
  },
  {
    "code": "def update_many(cls, filter, update, upsert=False):\n        return cls.collection.update_many(filter, update, upsert).raw_result",
    "docstring": "Updates all documents that pass the filter with the update value\n        Will upsert a new document if upsert=True and no document is filtered"
  },
  {
    "code": "async def _register(self):\n        if self.registered:\n            return\n        self._registration_attempts += 1\n        self.connection.throttle = False\n        if self.password:\n            await self.rawmsg('PASS', self.password)\n        await self.set_nickname(self._attempt_nicknames.pop(0))\n        await self.rawmsg('USER', self.username, '0', '*', self.realname)",
    "docstring": "Perform IRC connection registration."
  },
  {
    "code": "def DropConnection(self, connection):\n    try:\n      connection.cursor.close()\n    except MySQLdb.Error:\n      pass\n    try:\n      connection.dbh.close()\n    except MySQLdb.Error:\n      pass",
    "docstring": "Attempt to cleanly drop the connection."
  },
  {
    "code": "def check_conditions(f, args, kwargs):\n    member_function = is_member_function(f)\n    check_preconditions(f, args, kwargs)\n    base_classes = []\n    if member_function:\n        base_classes = inspect.getmro(type(args[0]))[1:-1]\n        for clz in base_classes:\n            super_fn = getattr(clz, f.func_name, None)\n            check_preconditions(super_fn, args, kwargs)\n    return_value = f(*args, **kwargs)\n    check_postconditions(f, return_value)\n    if member_function:\n        for clz in base_classes:\n            super_fn = getattr(clz, f.func_name, None)\n            check_postconditions(super_fn, return_value)\n    return return_value",
    "docstring": "This is what runs all of the conditions attached to a method,\n    along with the conditions on the superclasses."
  },
  {
    "code": "def shutdown(self):\n        if self.lifecycle.is_live:\n            self.lifecycle.fire_lifecycle_event(LIFECYCLE_STATE_SHUTTING_DOWN)\n            self.near_cache_manager.destroy_all_near_caches()\n            self.statistics.shutdown()\n            self.partition_service.shutdown()\n            self.heartbeat.shutdown()\n            self.cluster.shutdown()\n            self.reactor.shutdown()\n            self.lifecycle.fire_lifecycle_event(LIFECYCLE_STATE_SHUTDOWN)\n            self.logger.info(\"Client shutdown.\", extra=self._logger_extras)",
    "docstring": "Shuts down this HazelcastClient."
  },
  {
    "code": "def size(self):\n        if self.children:\n            return sum( ( c.size() for c in self.children.values() ) ) + 1\n        else:\n            return 1",
    "docstring": "Size is number of nodes under the trie, including the current node"
  },
  {
    "code": "def rewrite_references_json(json_content, rewrite_json):\n    for ref in json_content:\n        if ref.get(\"id\") and ref.get(\"id\") in rewrite_json:\n            for key, value in iteritems(rewrite_json.get(ref.get(\"id\"))):\n                ref[key] = value\n    return json_content",
    "docstring": "general purpose references json rewriting by matching the id value"
  },
  {
    "code": "def correct_rytov_output(radius, sphere_index, medium_index, radius_sampling):\n    r\n    params = get_params(radius_sampling)\n    x = sphere_index / medium_index - 1\n    radius_sc = radius * (params[\"ra\"] * x**2\n                          + params[\"rb\"] * x\n                          + params[\"rc\"])\n    sphere_index_sc = sphere_index + medium_index * (params[\"na\"] * x**2\n                                                     + params[\"nb\"] * x)\n    return radius_sc, sphere_index_sc",
    "docstring": "r\"\"\"Error-correction of refractive index and radius for Rytov\n\n    This method corrects the fitting results for `radius`\n    :math:`r_\\text{Ryt}` and `sphere_index` :math:`n_\\text{Ryt}`\n    obtained using :func:`qpsphere.models.rytov` using\n    the approach described in :cite:`Mueller2018` (eqns. 3,4, and 5).\n\n    .. math::\n\n        n_\\text{Ryt-SC} &= n_\\text{Ryt} + n_\\text{med} \\cdot\n                           \\left( a_n x^2 + b_n x + c_n \\right)\n\n        r_\\text{Ryt-SC} &= r_\\text{Ryt} \\cdot\n                           \\left( a_r x^2 +b_r x + c_r \\right)\n\n        &\\text{with} x = \\frac{n_\\text{Ryt}}{n_\\text{med}} - 1\n\n    The correction factors are given in\n    :data:`qpsphere.models.mod_rytov_sc.RSC_PARAMS`.\n\n    Parameters\n    ----------\n    radius: float\n        Fitted radius of the sphere :math:`r_\\text{Ryt}` [m]\n    sphere_index: float\n        Fitted refractive index of the sphere :math:`n_\\text{Ryt}`\n    medium_index: float\n        Refractive index of the surrounding medium :math:`n_\\text{med}`\n    radius_sampling: int\n        Number of pixels used to sample the sphere radius when\n        computing the Rytov field.\n\n    Returns\n    -------\n    radius_sc: float\n        Systematically corrected radius of the sphere\n        :math:`r_\\text{Ryt-SC}` [m]\n    sphere_index_sc: float\n        Systematically corrected refractive index of the sphere\n        :math:`n_\\text{Ryt-SC}`\n\n    See Also\n    --------\n    correct_rytov_sc_input: the inverse of this method"
  },
  {
    "code": "def complete_worker(self, text, line, begidx, endidx):\n        return  [i for i in PsiturkNetworkShell.worker_commands if \\\n                 i.startswith(text)]",
    "docstring": "Tab-complete worker command."
  },
  {
    "code": "def can_add_post(self, topic, user):\n        can_add_post = self._perform_basic_permission_check(\n            topic.forum, user, 'can_reply_to_topics',\n        )\n        can_add_post &= (\n            not topic.is_locked or\n            self._perform_basic_permission_check(topic.forum, user, 'can_reply_to_locked_topics')\n        )\n        return can_add_post",
    "docstring": "Given a topic, checks whether the user can append posts to it."
  },
  {
    "code": "def CMS(data, format=\"PEM\"):\n    bio = Membio(data)\n    if format == \"PEM\":\n        ptr = libcrypto.PEM_read_bio_CMS(bio.bio, None, None, None)\n    else:\n        ptr = libcrypto.d2i_CMS_bio(bio.bio, None)\n    if ptr is None:\n        raise CMSError(\"Error parsing CMS data\")\n    typeoid = Oid(libcrypto.OBJ_obj2nid(libcrypto.CMS_get0_type(ptr)))\n    if typeoid.shortname() == \"pkcs7-signedData\":\n        return SignedData(ptr)\n    elif typeoid.shortname() == \"pkcs7-envelopedData\":\n        return EnvelopedData(ptr)\n    elif typeoid.shortname() == \"pkcs7-encryptedData\":\n        return EncryptedData(ptr)\n    else:\n        raise NotImplementedError(\"cannot handle \"+typeoid.shortname())",
    "docstring": "Factory function to create CMS objects from received messages.\n    \n    Parses CMS data and returns either SignedData or EnvelopedData\n    object. format argument can be either \"PEM\" or \"DER\".\n\n    It determines object type from the contents of received CMS\n    structure."
  },
  {
    "code": "def get_index_url(self, resource=None, **kwargs):\n        default_kwargs = self.default_kwargs_for_urls() \\\n            if resource == self.get_resource_name() else {}\n        default_kwargs.update(kwargs)\n        return self.get_full_url(\n            self.app.reverse(\n                '{}_index'.format(resource or self.get_resource_name()),\n                **default_kwargs\n            )\n        )",
    "docstring": "Builds the url of the resource's index.\n\n        :param resource: name of the resource or None\n        :param kwargs: additional keyword arguments to build the url\n        :return: url of the resource's index"
  },
  {
    "code": "def _exit(self, status_code):\n        exit_func = os._exit if threading.active_count() > 1 else sys.exit\n        exit_func(status_code)",
    "docstring": "Properly kill Python process including zombie threads."
  },
  {
    "code": "def member_profile_view(request, targetUsername):\n    if targetUsername == request.user.username and targetUsername != ANONYMOUS_USERNAME:\n        return HttpResponseRedirect(reverse('my_profile'))\n    page_name = \"{0}'s Profile\".format(targetUsername)\n    targetUser = get_object_or_404(User, username=targetUsername)\n    targetProfile = get_object_or_404(UserProfile, user=targetUser)\n    number_of_threads = Thread.objects.filter(owner=targetProfile).count()\n    number_of_messages = Message.objects.filter(owner=targetProfile).count()\n    number_of_requests = Request.objects.filter(owner=targetProfile).count()\n    rooms = Room.objects.filter(current_residents=targetProfile)\n    prev_rooms = PreviousResident.objects.filter(resident=targetProfile)\n    return render_to_response('member_profile.html', {\n        'page_name': page_name,\n        'targetUser': targetUser,\n        'targetProfile': targetProfile,\n        'number_of_threads': number_of_threads,\n        'number_of_messages': number_of_messages,\n        'number_of_requests': number_of_requests,\n        \"rooms\": rooms,\n        \"prev_rooms\": prev_rooms,\n        }, context_instance=RequestContext(request))",
    "docstring": "View a member's Profile."
  },
  {
    "code": "def activate_next(self, _previous=False):\n        current = self.get_current_value()\n        options = sorted(self.values.keys())\n        try:\n            index = options.index(current)\n        except ValueError:\n            index = 0\n        if _previous:\n            index -= 1\n        else:\n            index += 1\n        next_option = options[index % len(options)]\n        self.values[next_option]()",
    "docstring": "Activate next value."
  },
  {
    "code": "def getfile2(url, auth=None, outdir=None):\n    import requests\n    print(\"Retrieving: %s\" % url)\n    fn = os.path.split(url)[-1]\n    if outdir is not None:\n        fn = os.path.join(outdir, fn)\n    if auth is not None:\n        r = requests.get(url, stream=True, auth=auth)\n    else:\n        r = requests.get(url, stream=True)\n    chunk_size = 1000000\n    with open(fn, 'wb') as fd:\n        for chunk in r.iter_content(chunk_size):\n            fd.write(chunk)",
    "docstring": "Function to fetch files using requests\n\n    Works with https authentication"
  },
  {
    "code": "def GetCacheValueByObject(self, vfs_object):\n    for identifier, cache_value in iter(self._values.items()):\n      if not cache_value:\n        raise RuntimeError('Missing cache value.')\n      if cache_value.vfs_object == vfs_object:\n        return identifier, cache_value\n    return None, None",
    "docstring": "Retrieves the cache value for the cached object.\n\n    Args:\n      vfs_object (object): VFS object that was cached.\n\n    Returns:\n      tuple[str, ObjectsCacheValue]: identifier and cache value object or\n          (None, None) if not cached.\n\n    Raises:\n      RuntimeError: if the cache value is missing."
  },
  {
    "code": "def session_demo_danger_callback(da_children, session_state=None, **kwargs):\n    'Update output based just on state'\n    if not session_state:\n        return \"Session state not yet available\"\n    return \"Session state contains: \" + str(session_state.get('bootstrap_demo_state', \"NOTHING\")) + \" and the page render count is \" + str(session_state.get(\"ind_use\", \"NOT SET\"))",
    "docstring": "Update output based just on state"
  },
  {
    "code": "def import_participant_element(diagram_graph, participants_dictionary, participant_element):\n        participant_id = participant_element.getAttribute(consts.Consts.id)\n        name = participant_element.getAttribute(consts.Consts.name)\n        process_ref = participant_element.getAttribute(consts.Consts.process_ref)\n        if participant_element.getAttribute(consts.Consts.process_ref) == '':\n            diagram_graph.add_node(participant_id)\n            diagram_graph.node[participant_id][consts.Consts.type] = consts.Consts.participant\n            diagram_graph.node[participant_id][consts.Consts.process] = participant_id\n        participants_dictionary[participant_id] = {consts.Consts.name: name, consts.Consts.process_ref: process_ref}",
    "docstring": "Adds 'participant' element to the collaboration dictionary.\n\n        :param diagram_graph: NetworkX graph representing a BPMN process diagram,\n        :param participants_dictionary: dictionary with participant element attributes. Key is participant ID, value\n           is a dictionary of participant attributes,\n        :param participant_element: object representing a BPMN XML 'participant' element."
  },
  {
    "code": "def _build_meta(text: str, title: str) -> DocstringMeta:\n    meta = _sections[title]\n    if meta == \"returns\" and \":\" not in text.split()[0]:\n        return DocstringMeta([meta], description=text)\n    before, desc = text.split(\":\", 1)\n    if desc:\n        desc = desc[1:] if desc[0] == \" \" else desc\n        if \"\\n\" in desc:\n            first_line, rest = desc.split(\"\\n\", 1)\n            desc = first_line + \"\\n\" + inspect.cleandoc(rest)\n        desc = desc.strip(\"\\n\")\n    m = re.match(r\"(\\S+) \\((\\S+)\\)$\", before)\n    if meta == \"param\" and m:\n        arg_name, type_name = m.group(1, 2)\n        args = [meta, type_name, arg_name]\n    else:\n        args = [meta, before]\n    return DocstringMeta(args, description=desc)",
    "docstring": "Build docstring element.\n\n    :param text: docstring element text\n    :param title: title of section containing element\n    :return:"
  },
  {
    "code": "def _set_italian_leading_zeros_for_phone_number(national_number, numobj):\n    if len(national_number) > 1 and national_number[0] == U_ZERO:\n        numobj.italian_leading_zero = True\n        number_of_leading_zeros = 1\n        while (number_of_leading_zeros < len(national_number) - 1 and\n               national_number[number_of_leading_zeros] == U_ZERO):\n            number_of_leading_zeros += 1\n        if number_of_leading_zeros != 1:\n            numobj.number_of_leading_zeros = number_of_leading_zeros",
    "docstring": "A helper function to set the values related to leading zeros in a\n    PhoneNumber."
  },
  {
    "code": "def normalize_version(version):\n    if version is None:\n        return None\n    error = False\n    try:\n        version = int(version)\n        error = version < 1\n    except (ValueError, TypeError):\n        try:\n            version = consts.MICRO_VERSION_MAPPING[version.upper()]\n        except (KeyError, AttributeError):\n            error = True\n    if error or not 0 < version < 41 and version not in consts.MICRO_VERSIONS:\n        raise VersionError('Unsupported version \"{0}\". '\n                           'Supported: {1} and 1 .. 40'\n                           .format(version, ', '.join(sorted(consts.MICRO_VERSION_MAPPING.keys()))))\n    return version",
    "docstring": "\\\n    Canonicalizes the provided `version`.\n\n    If the `version` is ``None``, this function returns ``None``. Otherwise\n    this function checks if `version` is an integer or a Micro QR Code version.\n    In case the string represents a Micro QR Code version, an uppercased\n    string identifier is returned.\n\n    If the `version` does not represent a valid version identifier (aside of\n    ``None``, a VersionError is raised.\n\n    :param version: An integer, a string or ``None``.\n    :raises: VersionError: In case the version is not ``None`` and does not\n                represent a valid (Micro) QR Code version.\n    :rtype: int, str or ``None``"
  },
  {
    "code": "def get_protein_data_pgrouped(proteindata, p_acc, headerfields):\n    report = get_protein_data_base(proteindata, p_acc, headerfields)\n    return get_cov_protnumbers(proteindata, p_acc, report)",
    "docstring": "Parses protein data for a certain protein into tsv output\n    dictionary"
  },
  {
    "code": "def mutex():\n    mutex_num = [50, 50, 50, 500, 500, 500, 1000, 1000, 1000]\n    locks = [10000, 25000, 50000, 10000, 25000, 50000, 10000, 25000, 50000]\n    mutex_locks = []\n    mutex_locks.extend(locks)\n    mutex_loops = [2500, 5000, 10000, 10000, 2500, 5000, 5000, 10000, 2500]\n    test_command = 'sysbench --num-threads=250 --test=mutex '\n    test_command += '--mutex-num={0} --mutex-locks={1} --mutex-loops={2} run '\n    result = None\n    ret_val = {}\n    for num, locks, loops in zip(mutex_num, mutex_locks, mutex_loops):\n        key = 'Mutex: {0} Locks: {1} Loops: {2}'.format(num, locks, loops)\n        run_command = test_command.format(num, locks, loops)\n        result = __salt__['cmd.run'](run_command)\n        ret_val[key] = _parser(result)\n    return ret_val",
    "docstring": "Tests the implementation of mutex\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt '*' sysbench.mutex"
  },
  {
    "code": "def full_name(self):\n        if self.prefix is not None:\n            return '.'.join([self.prefix, self.member])\n        return self.member",
    "docstring": "Return full name of member"
  },
  {
    "code": "def _hide_loading_page(self):\r\n        self.infowidget.hide()\r\n        self.shellwidget.show()\r\n        self.info_page = self.blank_page\r\n        self.set_info_page()\r\n        self.shellwidget.sig_prompt_ready.disconnect(self._hide_loading_page)",
    "docstring": "Hide animation shown while the kernel is loading."
  },
  {
    "code": "def chunks(iterable, size):\n    it = iter(iterable)\n    item = list(islice(it, size))\n    while item:\n        yield item\n        item = list(islice(it, size))",
    "docstring": "Splits a very large list into evenly sized chunks.\n    Returns an iterator of lists that are no more than the size passed in."
  },
  {
    "code": "def uninit_ui(self):\n        self.lay.removeWidget(self.tool_pb)\n        self.tooltip.deleteLater()\n        self.tool_pb.deleteLater()",
    "docstring": "Delete the tooltip\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def _get_subject_alternative_names(self, ext):\n        values = []\n        for san in ext.value:\n            if isinstance(san.value, string):\n                values.append(san.value)\n            elif isinstance(san.value, x509.Name):\n                values.extend(\n                    self._name_attribute_to_string(rdn) for rdn in san.value.rdns\n                )\n        return values",
    "docstring": "Return a list of Subject Alternative Name values for the given x509\n        extension object."
  },
  {
    "code": "def _findbytes(self, bytes_, start, end, bytealigned):\n        assert self._datastore.offset == 0\n        assert bytealigned is True\n        bytepos = (start + 7) // 8\n        found = False\n        p = bytepos\n        finalpos = end // 8\n        increment = max(1024, len(bytes_) * 10)\n        buffersize = increment + len(bytes_)\n        while p < finalpos:\n            buf = bytearray(self._datastore.getbyteslice(p, min(p + buffersize, finalpos)))\n            pos = buf.find(bytes_)\n            if pos != -1:\n                found = True\n                p += pos\n                break\n            p += increment\n        if not found:\n            return ()\n        return (p * 8,)",
    "docstring": "Quicker version of find when everything's whole byte\n        and byte aligned."
  },
  {
    "code": "def _array_io(self, action, array, frames):\n        if (array.ndim not in (1, 2) or\n                array.ndim == 1 and self.channels != 1 or\n                array.ndim == 2 and array.shape[1] != self.channels):\n            raise ValueError(\"Invalid shape: {0!r}\".format(array.shape))\n        if not array.flags.c_contiguous:\n            raise ValueError(\"Data must be C-contiguous\")\n        ctype = self._check_dtype(array.dtype.name)\n        assert array.dtype.itemsize == _ffi.sizeof(ctype)\n        cdata = _ffi.cast(ctype + '*', array.__array_interface__['data'][0])\n        return self._cdata_io(action, cdata, ctype, frames)",
    "docstring": "Check array and call low-level IO function."
  },
  {
    "code": "def give_satellite_json(self):\n        daemon_properties = ['type', 'name', 'uri', 'spare', 'configuration_sent',\n                             'realm_name', 'manage_sub_realms',\n                             'active', 'reachable', 'alive', 'passive',\n                             'last_check', 'polling_interval', 'max_check_attempts']\n        (livestate, livestate_output) = self.get_livestate()\n        res = {\n            \"livestate\": livestate,\n            \"livestate_output\": livestate_output\n        }\n        for sat_prop in daemon_properties:\n            res[sat_prop] = getattr(self, sat_prop, 'not_yet_defined')\n        return res",
    "docstring": "Get the json information for a satellite.\n\n        This to provide information that will be exposed by a daemon on its HTTP interface.\n\n        :return: dictionary of information common to all the links\n        :rtype: dict"
  },
  {
    "code": "def _set_expressions(self, expressions):\n        self.expressions = {}\n        for key, item in expressions.items():\n            self.expressions[key] = {'function': item}",
    "docstring": "Extract expressions and variables from the user provided expressions."
  },
  {
    "code": "def query(cls, database, map_fun, reduce_fun,\n              language='javascript', **options):\n        return database.query(map_fun, reduce_fun=reduce_fun, language=language,\n                        wrapper=cls._wrap_row, **options)",
    "docstring": "Execute a CouchDB temporary view and map the result values back to\n        objects of this mapping.\n\n        Note that by default, any properties of the document that are not\n        included in the values of the view will be treated as if they were\n        missing from the document. If you want to load the full document for\n        every row, set the ``include_docs`` option to ``True``."
  },
  {
    "code": "def container_config_delete(name, config_key, remote_addr=None,\n                            cert=None, key=None, verify_cert=True):\n    container = container_get(\n        name, remote_addr, cert, key, verify_cert, _raw=True\n    )\n    return _delete_property_dict_item(\n        container, 'config', config_key\n    )",
    "docstring": "Delete a container config value\n\n    name :\n        Name of the container\n\n    config_key :\n        The config key to delete\n\n    remote_addr :\n        An URL to a remote Server, you also have to give cert and key if\n        you provide remote_addr and its a TCP Address!\n\n        Examples:\n            https://myserver.lan:8443\n            /var/lib/mysocket.sock\n\n    cert :\n        PEM Formatted SSL Certificate.\n\n        Examples:\n            ~/.config/lxc/client.crt\n\n    key :\n        PEM Formatted SSL Key.\n\n        Examples:\n            ~/.config/lxc/client.key\n\n    verify_cert : True\n        Wherever to verify the cert, this is by default True\n        but in the most cases you want to set it off as LXD\n        normaly uses self-signed certificates."
  },
  {
    "code": "def items(self):\n        if type(self.transaction['items']['item']) == list:\n            return self.transaction['items']['item']\n        else:\n            return [self.transaction['items']['item'],]",
    "docstring": "Lista dos items do pagamento"
  },
  {
    "code": "def entity_categories(self, entity_id):\n        attributes = self.entity_attributes(entity_id)\n        return attributes.get(ENTITY_CATEGORY, [])",
    "docstring": "Get a list of entity categories for an entity id.\n\n        :param entity_id: Entity id\n        :return: Entity categories\n\n        :type entity_id: string\n        :rtype: [string]"
  },
  {
    "code": "def log_to_api(self):\n        if self.entries:\n            try:\n                headers = {'Content-Type': 'application/json'}\n                self.session.post('/v2/logs/app', headers=headers, json=self.entries)\n            except Exception:\n                pass",
    "docstring": "Best effort API logger.\n\n        Send logs to the ThreatConnect API and do nothing if the attempt fails."
  },
  {
    "code": "def outfile_maker(inname, outext='.out', outname='', outdir='', append_to_name=''):\n    orig_dir, orig_name, orig_ext = split_folder_and_path(inname)\n    if not outname:\n        outname = orig_name\n    if not outdir:\n        outdir = orig_dir\n    if append_to_name:\n        outname += append_to_name\n    final_outfile = op.join(outdir, '{}{}'.format(outname, outext))\n    return final_outfile",
    "docstring": "Create a default name for an output file based on the inname name, unless a output name is specified.\n\n    Args:\n        inname: Path to input file\n        outext: Optional specified extension for output file (with the \".\"). Default is \".out\".\n        outfile: Optional specified name of output file.\n        outdir: Optional path to output directory.\n\n    Returns:\n        str: Path to final output destination.\n\n    Examples:\n\n        >>> outfile_maker(inname='P00001.fasta')\n        'P00001.out'\n\n        >>> outfile_maker(inname='P00001')\n        'P00001.out'\n\n        >>> outfile_maker(inname='P00001.fasta', append_to_name='_new')\n        'P00001_new.out'\n\n        >>> outfile_maker(inname='P00001.fasta', outext='.mao')\n        'P00001.mao'\n\n        >>> outfile_maker(inname='P00001.fasta', outext='.mao', append_to_name='_new')\n        'P00001_new.mao'\n\n        >>> outfile_maker(inname='P00001.fasta', outext='.new', outname='P00001_aligned')\n        'P00001_aligned.new'\n\n        >>> outfile_maker(inname='P00001.fasta', outname='P00001_aligned')\n        'P00001_aligned.out'\n\n        >>> outfile_maker(inname='P00001.fasta', outname='P00001_aligned', append_to_name='_new')\n        'P00001_aligned_new.out'\n\n        >>> outfile_maker(inname='P00001.fasta', outname='P00001_aligned', outdir='/my/dir/')\n        '/my/dir/P00001_aligned.out'\n\n        >>> outfile_maker(inname='/test/other/dir/P00001.fasta', append_to_name='_new')\n        '/test/other/dir/P00001_new.out'\n\n        >>> outfile_maker(inname='/test/other/dir/P00001.fasta', outname='P00001_aligned')\n        '/test/other/dir/P00001_aligned.out'\n\n        >>> outfile_maker(inname='/test/other/dir/P00001.fasta', outname='P00001_aligned', outdir='/my/dir/')\n        '/my/dir/P00001_aligned.out'"
  },
  {
    "code": "def generate_sample_sls_module(env_root, module_dir=None):\n    if module_dir is None:\n        module_dir = os.path.join(env_root, 'sampleapp.sls')\n    generate_sample_module(module_dir)\n    for i in ['config-dev-us-east-1.json', 'handler.py', 'package.json',\n              'serverless.yml']:\n        shutil.copyfile(\n            os.path.join(ROOT,\n                         'templates',\n                         'serverless',\n                         i),\n            os.path.join(module_dir, i),\n        )\n    LOGGER.info(\"Sample Serverless module created at %s\",\n                module_dir)",
    "docstring": "Generate skeleton Serverless sample module."
  },
  {
    "code": "def format_expose(expose):\n    if isinstance(expose, six.string_types):\n        return expose,\n    elif isinstance(expose, collections.Iterable):\n        return map(six.text_type, expose)\n    return six.text_type(expose),",
    "docstring": "Converts a port number or multiple port numbers, as used in the Dockerfile ``EXPOSE`` command, to a tuple.\n\n    :param: Port numbers, can be as integer, string, or a list/tuple of those.\n    :type expose: int | unicode | str | list | tuple\n    :return: A tuple, to be separated by spaces before inserting in a Dockerfile.\n    :rtype: tuple"
  },
  {
    "code": "def decisionviz(model,\n                X,\n                y,\n                colors=None,\n                classes=None,\n                features=None,\n                show_scatter=True,\n                step_size=0.0025,\n                markers=None,\n                pcolormesh_alpha=0.8,\n                scatter_alpha=1.0,\n                title=None,\n                **kwargs):\n    visualizer = DecisionBoundariesVisualizer(model,\n                    X,\n                    y,\n                    colors=colors,\n                    classes=classes,\n                    features=features,\n                    show_scatter=show_scatter,\n                    step_size=step_size,\n                    markers=markers,\n                    pcolormesh_alpha=pcolormesh_alpha,\n                    scatter_alpha=scatter_alpha,\n                    title=title,\n                    **kwargs)\n    visualizer.fit_draw_poof(X, y, **kwargs)\n    return visualizer.ax",
    "docstring": "DecisionBoundariesVisualizer is a bivariate data visualization algorithm\n        that plots the decision boundaries of each class.\n\n    This helper function is a quick wrapper to utilize the\n    DecisionBoundariesVisualizers for one-off analysis.\n\n    Parameters\n    ----------\n    model : the Scikit-Learn estimator, required\n        Should be an instance of a classifier, else the __init__ will\n        return an error.\n\n    x : matrix, required\n        The feature name that corresponds to a column name or index postion\n        in the matrix that will be plotted against the x-axis\n\n    y : array, required\n        The feature name that corresponds to a column name or index postion\n        in the matrix that will be plotted against the y-axis\n\n    classes : a list of class names for the legend, default: None\n        If classes is None and a y value is passed to fit then the classes\n        are selected from the target vector.\n\n    features : list of strings, default: None\n        The names of the features or columns\n\n    show_scatter : boolean, default: True\n        If boolean is True, then a scatter plot with points will be drawn\n        on top of the decision boundary graph\n\n    step_size : float percentage, default: 0.0025\n        Determines the step size for creating the numpy meshgrid that will\n        later become the foundation of the decision boundary graph. The\n        default value of 0.0025 means that the step size for constructing\n        the meshgrid will be 0.25%% of differenes of the max and min of x\n        and y for each feature.\n\n    markers : iterable of strings, default: ,od*vh+\n        Matplotlib style markers for points on the scatter plot points\n\n    pcolormesh_alpha : float, default: 0.8\n        Sets the alpha transparency for the meshgrid of model boundaries\n\n    scatter_alpha : float, default: 1.0\n        Sets the alpha transparency for the scatter plot points\n\n    title : string, default: stringified feature_one and feature_two\n        Sets the title of the visualization\n\n    kwargs : keyword arguments passed to the super class.\n\n    Returns\n    -------\n    ax : matplotlib axes\n        Returns the axes that the decision boundaries graph were drawn on."
  },
  {
    "code": "def _parse_patterns(self, pattern):\n        self.pattern = []\n        self.npatterns = None\n        npattern = []\n        for p in pattern:\n            if _wcparse.is_negative(p, self.flags):\n                npattern.append(p[1:])\n            else:\n                self.pattern.extend(\n                    [_wcparse.WcPathSplit(x, self.flags).split() for x in _wcparse.expand_braces(p, self.flags)]\n                )\n        if npattern:\n            self.npatterns = _wcparse.compile(npattern, self.flags ^ (_wcparse.NEGATE | _wcparse.REALPATH))\n        if not self.pattern and self.npatterns is not None:\n            self.pattern.append(_wcparse.WcPathSplit((b'**' if self.is_bytes else '**'), self.flags).split())",
    "docstring": "Parse patterns."
  },
  {
    "code": "def to_inches(value, units):\n    lookup = {'in': lambda x: x,\n              'cm': lambda x: x/2.54,\n              'mm': lambda x: x/(2.54*10)}\n    try:\n        return lookup[units](value)\n    except KeyError:\n        raise PlotnineError(\"Unknown units '{}'\".format(units))",
    "docstring": "Convert value to inches\n\n    Parameters\n    ----------\n    value : float\n        Value to be converted\n    units : str\n        Units of value. Must be one of\n        `['in', 'cm', 'mm']`."
  },
  {
    "code": "def fetch_entities(self):\n        query = text(\n        )\n        response = self.perform_query(query)\n        entities = {}\n        domains = set()\n        for [entity] in response:\n            domain = entity.split(\".\")[0]\n            domains.add(domain)\n            entities.setdefault(domain, []).append(entity)\n        self._domains = list(domains)\n        self._entities = entities\n        print(\"There are {} entities with data\".format(len(entities)))",
    "docstring": "Fetch entities for which we have data."
  },
  {
    "code": "def createDocument_(self, initDict = None) :\n        \"create and returns a completely empty document or one populated with initDict\"\n        if initDict is None :\n            initV = {}\n        else :\n            initV = initDict\n        return self.documentClass(self, initV)",
    "docstring": "create and returns a completely empty document or one populated with initDict"
  },
  {
    "code": "def recursive_iterator(func):\n    tee_store = {}\n    @_coconut.functools.wraps(func)\n    def recursive_iterator_func(*args, **kwargs):\n        hashable_args_kwargs = _coconut.pickle.dumps((args, kwargs), _coconut.pickle.HIGHEST_PROTOCOL)\n        try:\n            to_tee = tee_store[hashable_args_kwargs]\n        except _coconut.KeyError:\n            to_tee = func(*args, **kwargs)\n        tee_store[hashable_args_kwargs], to_return = _coconut_tee(to_tee)\n        return to_return\n    return recursive_iterator_func",
    "docstring": "Decorates a function by optimizing it for iterator recursion.\n    Requires function arguments to be pickleable."
  },
  {
    "code": "def diff_medians(array_one, array_two):\n    array_one = check_array(array_one)\n    array_two = check_array(array_two)\n    diff_medians = np.ma.median(array_one) - np.ma.median(array_two)\n    return diff_medians",
    "docstring": "Computes the difference in medians between two arrays of values.\n\n    Given arrays will be flattened (to 1D array) regardless of dimension,\n        and any non-finite/NaN values will be ignored.\n\n    Parameters\n    ----------\n    array_one, array_two : iterable\n        Two arrays of values, possibly of different length.\n\n    Returns\n    -------\n    diff_medians : float\n        scalar measuring the difference in medians, ignoring NaNs/non-finite values.\n\n    Raises\n    ------\n    ValueError\n        If one or more of the arrays are empty."
  },
  {
    "code": "def unperturbed_hamiltonian(states):\n    r\n    Ne = len(states)\n    H0 = np.zeros((Ne, Ne), complex)\n    for i in range(Ne):\n        H0[i, i] = hbar*states[i].omega\n    return H0",
    "docstring": "r\"\"\"Return the unperturbed atomic hamiltonian for given states.\n\n    We calcualte the atomic hamiltonian in the basis of the ground states of \\\n    rubidium 87 (in GHz).\n    >>> g = State(\"Rb\", 87, 5, 0, 1/Integer(2))\n    >>> magnetic_states = make_list_of_states([g], \"magnetic\")\n    >>> print(np.diag(unperturbed_hamiltonian(magnetic_states))/hbar/2/pi*1e-9)\n    [-4.2717+0.j -4.2717+0.j -4.2717+0.j  2.563 +0.j  2.563 +0.j  2.563 +0.j\n      2.563 +0.j  2.563 +0.j]"
  },
  {
    "code": "def _run_select(self):\n        return self._connection.select(\n            self.to_sql(), self.get_bindings(), not self._use_write_connection\n        )",
    "docstring": "Run the query as a \"select\" statement against the connection.\n\n        :return: The result\n        :rtype: list"
  },
  {
    "code": "def check_status_logfile(self, checker_func):\n        self.status = checker_func(self.logfile)\n        return self.status",
    "docstring": "Check on the status of this particular job using the logfile"
  },
  {
    "code": "def _del_flow_entry(self, datapath, in_port, dst, src=None):\n        del_flow = self._del_flow_func.get(datapath.ofproto.OFP_VERSION)\n        assert del_flow\n        del_flow(datapath, in_port, dst, src)",
    "docstring": "remove a flow entry."
  },
  {
    "code": "def interpolate_string(self, testString, section):\n        reObj = re.search(r\"\\$\\{.*?\\}\", testString)\n        while reObj:\n            repString = (reObj).group(0)[2:-1]\n            splitString = repString.split('|')\n            if len(splitString) == 1:\n                try:\n                    testString = testString.replace('${'+repString+'}',\\\n                                            self.get(section,splitString[0]))\n                except ConfigParser.NoOptionError:\n                    print(\"Substitution failed\")\n                    raise\n            if len(splitString) == 2:\n                try:\n                    testString = testString.replace('${'+repString+'}',\\\n                                       self.get(splitString[0],splitString[1]))\n                except ConfigParser.NoOptionError:\n                    print(\"Substitution failed\")\n                    raise\n            reObj = re.search(r\"\\$\\{.*?\\}\", testString)\n        return testString",
    "docstring": "Take a string and replace all example of ExtendedInterpolation\n        formatting within the string with the exact value.\n\n        For values like ${example} this is replaced with the value that\n        corresponds to the option called example ***in the same section***\n\n        For values like ${common|example} this is replaced with the value that\n        corresponds to the option example in the section [common]. Note that\n        in the python3 config parser this is ${common:example} but python2.7\n        interprets the : the same as a = and this breaks things\n\n        Nested interpolation is not supported here.\n\n        Parameters\n        ----------\n        testString : String\n            The string to parse and interpolate\n        section : String\n            The current section of the ConfigParser object\n\n        Returns\n        ----------\n        testString : String\n            Interpolated string"
  },
  {
    "code": "def validate_uuid(value):\n    if value and not isinstance(value, UUID):\n        try:\n            return UUID(str(value), version=4)\n        except (AttributeError, ValueError):\n            raise ValidationError('not a valid UUID')\n    return value",
    "docstring": "UUID 128-bit validator"
  },
  {
    "code": "def publish_pdb_state(self):\n        if self._pdb_obj and self._do_publish_pdb_state:\n            state = dict(namespace_view = self.get_namespace_view(),\n                         var_properties = self.get_var_properties(),\n                         step = self._pdb_step)\n            self.send_spyder_msg('pdb_state', content={'pdb_state': state})\n        self._do_publish_pdb_state = True",
    "docstring": "Publish Variable Explorer state and Pdb step through\n        send_spyder_msg."
  },
  {
    "code": "def _set_repo(self, url):\n        if url.startswith('http'):\n            try:\n                self.repo = Proxy(url)\n            except ProxyError, e:\n                log.exception('Error setting repo: %s' % url)\n                raise GritError(e)\n        else:\n            try:\n                self.repo = Local(url)\n            except NotGitRepository:\n                raise GritError('Invalid url: %s' % url)\n            except Exception, e:\n                log.exception('Error setting repo: %s' % url)\n                raise GritError(e)",
    "docstring": "sets the underlying repo object"
  },
  {
    "code": "def mouse_release_event(self, x, y, button):\n        if button == 1:\n            print(\"Left mouse button released @\", x, y)\n        if button == 2:\n            print(\"Right mouse button released @\", x, y)",
    "docstring": "Reports left and right mouse button releases + position"
  },
  {
    "code": "def create_transcript_file(video_id, language_code, file_format, resource_fs, static_dir):\n    transcript_filename = '{video_id}-{language_code}.srt'.format(\n        video_id=video_id,\n        language_code=language_code\n    )\n    transcript_data = get_video_transcript_data(video_id, language_code)\n    if transcript_data:\n        transcript_content = Transcript.convert(\n            transcript_data['content'],\n            input_format=file_format,\n            output_format=Transcript.SRT\n        )\n        create_file_in_fs(transcript_content, transcript_filename, resource_fs, static_dir)\n    return transcript_filename",
    "docstring": "Writes transcript file to file system.\n\n    Arguments:\n        video_id (str): Video id of the video transcript file is attached.\n        language_code (str): Language code of the transcript.\n        file_format (str): File format of the transcript file.\n        static_dir (str): The Directory to store transcript file.\n        resource_fs (SubFS): The file system to store transcripts."
  },
  {
    "code": "async def get(self, source_, *args, **kwargs):\n        await self.connect()\n        if isinstance(source_, peewee.Query):\n            query = source_\n            model = query.model\n        else:\n            query = source_.select()\n            model = source_\n        conditions = list(args) + [(getattr(model, k) == v)\n                                   for k, v in kwargs.items()]\n        if conditions:\n            query = query.where(*conditions)\n        try:\n            result = await self.execute(query)\n            return list(result)[0]\n        except IndexError:\n            raise model.DoesNotExist",
    "docstring": "Get the model instance.\n\n        :param source_: model or base query for lookup\n\n        Example::\n\n            async def my_async_func():\n                obj1 = await objects.get(MyModel, id=1)\n                obj2 = await objects.get(MyModel, MyModel.id==1)\n                obj3 = await objects.get(MyModel.select().where(MyModel.id==1))\n\n        All will return `MyModel` instance with `id = 1`"
  },
  {
    "code": "def to_dataframe(self, extra_edges_columns=[]):\n        return df_util.to_dataframe(\n            self.session.get(self.__url).json(),\n            edges_attr_cols=extra_edges_columns\n        )",
    "docstring": "Return this network in pandas DataFrame.\n\n        :return: Network as DataFrame.  This is equivalent to SIF."
  },
  {
    "code": "def _clauses(lexer, varname, nvars):\n    tok = next(lexer)\n    toktype = type(tok)\n    if toktype is OP_not or toktype is IntegerToken:\n        lexer.unpop_token(tok)\n        first = _clause(lexer, varname, nvars)\n        rest = _clauses(lexer, varname, nvars)\n        return (first, ) + rest\n    else:\n        lexer.unpop_token(tok)\n        return tuple()",
    "docstring": "Return a tuple of DIMACS CNF clauses."
  },
  {
    "code": "def get_nts(self, goids=None, sortby=None):\n        nts = []\n        if goids is None:\n            goids = self.go_sources\n        else:\n            chk_goids(goids, \"GoSubDag::get_nts\")\n        if goids:\n            ntobj = cx.namedtuple(\"NtGo\", \" \".join(self.prt_attr['flds']))\n            go2nt = self.get_go2nt(goids)\n            for goid, ntgo in self._get_sorted_go2nt(go2nt, sortby):\n                assert ntgo is not None, \"{GO} NOT IN go2nt\".format(GO=goid)\n                if goid == ntgo.GO:\n                    nts.append(ntgo)\n                else:\n                    fld2vals = ntgo._asdict()\n                    fld2vals['GO'] = goid\n                    nts.append(ntobj(**fld2vals))\n        return nts",
    "docstring": "Given GO IDs, get a list of namedtuples."
  },
  {
    "code": "def prevPlot(self):\n        if self.stacker.currentIndex() > 0:\n            self.stacker.setCurrentIndex(self.stacker.currentIndex()-1)",
    "docstring": "Moves the displayed plot to the previous one"
  },
  {
    "code": "def to_timedelta(value, strict=True):\n    if isinstance(value, int):\n        return timedelta(seconds=value)\n    elif isinstance(value, timedelta):\n        return value\n    elif isinstance(value, str):\n        hours, minutes, seconds = _parse(value, strict)\n    elif isinstance(value, tuple):\n        check_tuple(value, strict)\n        hours, minutes, seconds = value\n    else:\n        raise TypeError(\n            'Value %s (type %s) not supported' % (\n                value, type(value).__name__\n            )\n        )\n    return timedelta(hours=hours, minutes=minutes, seconds=seconds)",
    "docstring": "converts duration string to timedelta\n\n    strict=True (by default) raises StrictnessError if either hours,\n    minutes or seconds in duration string exceed allowed values"
  },
  {
    "code": "def calibration_stimulus(self, mode):\n        if mode == 'tone':\n            return self.tone_calibrator.stimulus\n        elif mode =='noise':\n            return self.bs_calibrator.stimulus",
    "docstring": "Gets the stimulus model for calibration\n\n        :param mode: Type of stimulus to get: tone or noise\n        :type mode: str\n        :returns: :class:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel>`"
  },
  {
    "code": "def get_file_hash(fpath, blocksize=65536, hasher=None, stride=1,\n                  hexdigest=False):\n    r\n    if hasher is None:\n        hasher = hashlib.sha1()\n    with open(fpath, 'rb') as file_:\n        buf = file_.read(blocksize)\n        while len(buf) > 0:\n            hasher.update(buf)\n            if stride > 1:\n                file_.seek(blocksize * (stride - 1), 1)\n            buf = file_.read(blocksize)\n        if hexdigest:\n            return hasher.hexdigest()\n        else:\n            return hasher.digest()",
    "docstring": "r\"\"\"\n    For better hashes use hasher=hashlib.sha256, and keep stride=1\n\n    Args:\n        fpath (str):  file path string\n        blocksize (int): 2 ** 16. Affects speed of reading file\n        hasher (None):  defaults to sha1 for fast (but insecure) hashing\n        stride (int): strides > 1 skip data to hash, useful for faster\n                      hashing, but less accurate, also makes hash dependant on\n                      blocksize.\n\n    References:\n        http://stackoverflow.com/questions/3431825/generating-a-md5-checksum-of-a-file\n        http://stackoverflow.com/questions/5001893/when-should-i-use-sha-1-and-when-should-i-use-sha-2\n\n    CommandLine:\n        python -m utool.util_hash --test-get_file_hash\n        python -m utool.util_hash --test-get_file_hash:0\n        python -m utool.util_hash --test-get_file_hash:1\n\n    Example:\n        >>> # DISABLE_DOCTEST\n        >>> from utool.util_hash import *  # NOQA\n        >>> fpath = ut.grab_test_imgpath('patsy.jpg')\n        >>> #blocksize = 65536  # 2 ** 16\n        >>> blocksize = 2 ** 16\n        >>> hasher = None\n        >>> stride = 1\n        >>> hashbytes_20 = get_file_hash(fpath, blocksize, hasher, stride)\n        >>> result = repr(hashbytes_20)\n        >>> print(result)\n        '7\\x07B\\x0eX<sRu\\xa2\\x90P\\xda\\xb2\\x84?\\x81?\\xa9\\xd9'\n\n        '\\x13\\x9b\\xf6\\x0f\\xa3QQ \\xd7\"$\\xe9m\\x05\\x9e\\x81\\xf6\\xf2v\\xe4'\n\n        '\\x16\\x00\\x80Xx\\x8c-H\\xcdP\\xf6\\x02\\x9frl\\xbf\\x99VQ\\xb5'\n\n    Example:\n        >>> # DISABLE_DOCTEST\n        >>> from utool.util_hash import *  # NOQA\n        >>> #fpath = ut.grab_file_url('http://en.wikipedia.org/wiki/List_of_comets_by_type')\n        >>> fpath = ut.unixjoin(ut.ensure_app_resource_dir('utool'), 'tmp.txt')\n        >>> ut.write_to(fpath, ut.lorium_ipsum())\n        >>> blocksize = 2 ** 3\n        >>> hasher = None\n        >>> stride = 2\n        >>> hashbytes_20 = get_file_hash(fpath, blocksize, hasher, stride)\n        >>> result = repr(hashbytes_20)\n        >>> print(result)\n        '5KP\\xcf>R\\xf6\\xffO:L\\xac\\x9c\\xd3V+\\x0e\\xf6\\xe1n'\n\n    Ignore:\n        file_ = open(fpath, 'rb')"
  },
  {
    "code": "def _http_get(self, url, query):\n        if not self.authorization_as_header:\n            query.update({'access_token': self.access_token})\n        response = None\n        self._normalize_query(query)\n        kwargs = {\n            'params': query,\n            'headers': self._request_headers()\n        }\n        if self._has_proxy():\n            kwargs['proxies'] = self._proxy_parameters()\n        response = requests.get(\n            self._url(url),\n            **kwargs\n        )\n        if response.status_code == 429:\n            raise RateLimitExceededError(response)\n        return response",
    "docstring": "Performs the HTTP GET Request."
  },
  {
    "code": "def eval_nonagg_call(self, exp):\n    \"helper for eval_callx; evaluator for CallX that consume a single value\"\n    args=self.eval(exp.args)\n    if exp.f=='coalesce':\n      a,b=args\n      return b if a is None else a\n    elif exp.f=='unnest': return self.eval(exp.args)[0]\n    elif exp.f in ('to_tsquery','to_tsvector'): return set(self.eval(exp.args.children[0]).split())\n    else: raise NotImplementedError('unk_function',exp.f)",
    "docstring": "helper for eval_callx; evaluator for CallX that consume a single value"
  },
  {
    "code": "def search(self, **kwargs):\n        return super(ApiObjectGroupPermissionGeneral, self).get(self.prepare_url('api/v3/object-group-perm-general/',\n                                                                                 kwargs))",
    "docstring": "Method to search object group permissions general based on extends search.\n\n        :param search: Dict containing QuerySets to find object group permissions general.\n        :param include: Array containing fields to include on response.\n        :param exclude: Array containing fields to exclude on response.\n        :param fields:  Array containing fields to override default fields.\n        :param kind: Determine if result will be detailed ('detail') or basic ('basic').\n        :return: Dict containing object group permissions general"
  },
  {
    "code": "def parse(self, data, extent, desc_tag):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('UDF Unallocated Space Descriptor already initialized')\n        (tag_unused, self.vol_desc_seqnum,\n         num_alloc_descriptors, end_unused) = struct.unpack_from(self.FMT, data, 0)\n        self.desc_tag = desc_tag\n        if num_alloc_descriptors != 0:\n            raise pycdlibexception.PyCdlibInvalidISO('UDF Unallocated Space Descriptor allocated descriptors is not 0')\n        self.orig_extent_loc = extent\n        self._initialized = True",
    "docstring": "Parse the passed in data into a UDF Unallocated Space Descriptor.\n\n        Parameters:\n         data - The data to parse.\n         extent - The extent that this descriptor currently lives at.\n         desc_tag - A UDFTag object that represents the Descriptor Tag.\n        Returns:\n         Nothing."
  },
  {
    "code": "def namedTempFileReader(self) -> NamedTempFileReader:\n        directory = self._directory()\n        assert isinstance(directory, Directory), (\n            \"Expected Directory, receieved %s\" % directory)\n        return NamedTempFileReader(directory, self)",
    "docstring": "Named Temporary File Reader\n\n        This provides an object compatible with NamedTemporaryFile, used for reading this\n        files contents. This will still delete after the object falls out of scope.\n\n        This solves the problem on windows where a NamedTemporaryFile can not be read\n        while it's being written to"
  },
  {
    "code": "def ismethoddescriptor(object):\n    return (hasattr(object, \"__get__\")\n            and not hasattr(object, \"__set__\")\n            and not ismethod(object)\n            and not isfunction(object)\n            and not isclass(object))",
    "docstring": "Return true if the object is a method descriptor.\n\n    But not if ismethod() or isclass() or isfunction() are true.\n\n    This is new in Python 2.2, and, for example, is true of int.__add__.\n    An object passing this test has a __get__ attribute but not a __set__\n    attribute, but beyond that the set of attributes varies.  __name__ is\n    usually sensible, and __doc__ often is.\n\n    Methods implemented via descriptors that also pass one of the other\n    tests return false from the ismethoddescriptor() test, simply because\n    the other tests promise more -- you can, e.g., count on having the\n    im_func attribute (etc) when an object passes ismethod()."
  },
  {
    "code": "def provider(func=None, *, singleton=False, injector=None):\n    def decorator(func):\n        wrapped = _wrap_provider_func(func, {'singleton': singleton})\n        if injector:\n            injector.register_provider(wrapped)\n        return wrapped\n    if func:\n        return decorator(func)\n    return decorator",
    "docstring": "Decorator to mark a function as a provider.\n\n    Args:\n        singleton (bool): The returned value should be a singleton or shared\n            instance. If False (the default) the provider function will be\n            invoked again for every time it's needed for injection.\n        injector (Injector): If provided, the function is immediately\n            registered as a provider with the injector instance.\n\n    Example:\n        @diay.provider(singleton=True)\n        def myfunc() -> MyClass:\n            return MyClass(args)"
  },
  {
    "code": "def construct_chunk(cls, chunk_type, payload, encoding='utf-8'):\n    if isinstance(payload, str):\n      payload = payload.encode(encoding)\n    elif not isinstance(payload, bytes):\n      raise TypeError('cannot encode type: {}'.format(type(payload)))\n    header = struct.pack(cls.HEADER_FMT, len(payload), chunk_type)\n    return header + payload",
    "docstring": "Construct and return a single chunk."
  },
  {
    "code": "def resend_transaction_frames(self, connection, transaction):\n        for frame in self._transaction_frames[connection][transaction]:\n            self.send(frame)",
    "docstring": "Resend the messages that were ACK'd in specified transaction.\n\n        This is called by the engine when there is an abort command.\n\n        @param connection: The client connection that aborted the transaction.\n        @type connection: L{coilmq.server.StompConnection}\n\n        @param transaction: The transaction id (which was aborted).\n        @type transaction: C{str}"
  },
  {
    "code": "def remove(self):\n        for cgroup in self.paths:\n            remove_cgroup(cgroup)\n        del self.paths\n        del self.per_subsystem",
    "docstring": "Remove all cgroups this instance represents from the system.\n        This instance is afterwards not usable anymore!"
  },
  {
    "code": "def rename(self, new_lid):\n        logger.info(\"rename(new_lid=\\\"%s\\\") [lid=%s]\", new_lid, self.__lid)\n        evt = self._client._request_entity_rename(self.__lid, new_lid)\n        self._client._wait_and_except_if_failed(evt)\n        self.__lid = new_lid\n        self._client._notify_thing_lid_change(self.__lid, new_lid)",
    "docstring": "Rename the Thing.\n\n        `ADVANCED USERS ONLY`  This can be confusing.  You are changing the local id of a Thing to `new_lid`.  If you\n        create another Thing using the \"old_lid\", the system will oblige, but it will be a completely _new_ Thing.\n\n        Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)\n        containing the error if the infrastructure detects a problem\n\n        Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)\n        if there is a communications problem between you and the infrastructure\n\n        `new_lid` (required) (string) the new local identifier of your Thing"
  },
  {
    "code": "def _FormatIPToken(self, token_data):\n    data = ''.join(['{0:02x}'.format(byte) for byte in token_data.data])\n    return {'IPv4_Header': data}",
    "docstring": "Formats an IPv4 packet header token as a dictionary of values.\n\n    Args:\n      token_data (bsm_token_data_ip): AUT_IP token data.\n\n    Returns:\n      dict[str, str]: token values."
  },
  {
    "code": "def probe_git():\n    try:\n        repo = git.Repo()\n    except git.InvalidGitRepositoryError:\n        LOGGER.warning(\n            \"We highly recommend keeping your model in a git repository.\"\n            \" It allows you to track changes and to easily collaborate with\"\n            \" others via online platforms such as https://github.com.\\n\")\n        return\n    if repo.is_dirty():\n        LOGGER.critical(\n            \"Please git commit or git stash all changes before running\"\n            \" the memote suite.\")\n        sys.exit(1)\n    return repo",
    "docstring": "Return a git repository instance if it exists."
  },
  {
    "code": "def metrics(self):\n        masterThrp, backupThrp = self.getThroughputs(self.instances.masterId)\n        r = self.instance_throughput_ratio(self.instances.masterId)\n        m = [\n            (\"{} Monitor metrics:\".format(self), None),\n            (\"Delta\", self.Delta),\n            (\"Lambda\", self.Lambda),\n            (\"Omega\", self.Omega),\n            (\"instances started\", self.instances.started),\n            (\"ordered request counts\",\n             {i: r[0] for i, r in self.numOrderedRequests.items()}),\n            (\"ordered request durations\",\n             {i: r[1] for i, r in self.numOrderedRequests.items()}),\n            (\"master request latencies\", self.masterReqLatencies),\n            (\"client avg request latencies\", {i: self.getLatency(i)\n                                              for i in self.instances.ids}),\n            (\"throughput\", {i: self.getThroughput(i)\n                            for i in self.instances.ids}),\n            (\"master throughput\", masterThrp),\n            (\"total requests\", self.totalRequests),\n            (\"avg backup throughput\", backupThrp),\n            (\"master throughput ratio\", r)]\n        return m",
    "docstring": "Calculate and return the metrics."
  },
  {
    "code": "def get_home(self):\n        if 'HOME_POSITION' in self.master.messages:\n            h = self.master.messages['HOME_POSITION']\n            return mavutil.mavlink.MAVLink_mission_item_message(self.target_system,\n                                                                self.target_component,\n                                                                0,\n                                                                0,\n                                                                mavutil.mavlink.MAV_CMD_NAV_WAYPOINT,\n                                                                0, 0, 0, 0, 0, 0,\n                                                                h.latitude*1.0e-7, h.longitude*1.0e-7, h.altitude*1.0e-3)\n        if self.wploader.count() > 0:\n            return self.wploader.wp(0)\n        return None",
    "docstring": "get home location"
  },
  {
    "code": "def filter_geometry(queryset, **filters):\n    fieldname = geo_field(queryset).name\n    query = {'%s__%s' % (fieldname, k): v for k, v in filters.items()}\n    return queryset.filter(**query)",
    "docstring": "Helper function for spatial lookups filters.\n\n    Provide spatial lookup types as keywords without underscores instead of the\n    usual \"geometryfield__lookuptype\" format."
  },
  {
    "code": "def logout(self):\n        data = self._read_uaa_cache()\n        if self.uri in data:\n            for client in data[self.uri]:\n                if client['id'] == self.client['id']:\n                    data[self.uri].remove(client)\n        with open(self._cache_path, 'w') as output:\n            output.write(json.dumps(data, sort_keys=True, indent=4))",
    "docstring": "Log currently authenticated user out, invalidating any existing tokens."
  },
  {
    "code": "def default(self):\n        if isinstance(self.__default, (str, unicode)):\n            return self.valueFromString(self.__default)\n        else:\n            return self.__default",
    "docstring": "Returns the default value for this column to return\n        when generating new instances.\n\n        :return     <variant>"
  },
  {
    "code": "def post_worker_init(worker):\n    quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'\n    sys.stdout.write(\n        \"Django version {djangover}, Gunicorn version {gunicornver}, \"\n        \"using settings {settings!r}\\n\"\n        \"Starting development server at {urls}\\n\"\n        \"Quit the server with {quit_command}.\\n\".format(\n            djangover=django.get_version(),\n            gunicornver=gunicorn.__version__,\n            settings=os.environ.get('DJANGO_SETTINGS_MODULE'),\n            urls=', '.join('http://{0}/'.format(b) for b in worker.cfg.bind),\n            quit_command=quit_command,\n        ),\n    )",
    "docstring": "Hook into Gunicorn to display message after launching.\n\n    This mimics the behaviour of Django's stock runserver command."
  },
  {
    "code": "def dag(self) -> Tuple[Dict, Dict]:\n        from pipelines import dags\n        operations = self.operations.all().prefetch_related('downstream_operations')\n        def get_downstream(op):\n            return op.downstream_operations.values_list('id', flat=True)\n        return dags.get_dag(operations, get_downstream)",
    "docstring": "Construct the DAG of this pipeline based on the its operations and their downstream."
  },
  {
    "code": "def get_supervisor(func: types.AnyFunction) -> types.Supervisor:\n    if not callable(func):\n        raise TypeError(\"func is not callable\")\n    if asyncio.iscoroutinefunction(func):\n        supervisor = _async_supervisor\n    else:\n        supervisor = _sync_supervisor\n    return functools.partial(supervisor, func)",
    "docstring": "Get the appropriate supervisor to use and pre-apply the function.\n\n    Args:\n        func: A function."
  },
  {
    "code": "def download(url, proxies=None):\n    if proxies is None:\n        proxies = [\"\"]\n    for proxy in proxies:\n        if proxy == \"\":\n            socket.socket = DEFAULT_SOCKET\n        elif proxy.startswith('socks'):\n            if proxy[5] == '4':\n                proxy_type = socks.SOCKS4\n            else:\n                proxy_type = socks.SOCKS5\n            proxy = proxy[proxy.find('://') + 3:]\n            try:\n                proxy, port = proxy.split(':')\n            except ValueError:\n                port = None\n            socks.set_default_proxy(proxy_type, proxy, port)\n            socket.socket = socks.socksocket\n        else:\n            try:\n                proxy, port = proxy.split(':')\n            except ValueError:\n                port = None\n            socks.set_default_proxy(socks.HTTP, proxy, port)\n            socket.socket = socks.socksocket\n        downloaded = _download_helper(url)\n        if downloaded is not None:\n            return downloaded\n    return (None, None)",
    "docstring": "Download a PDF or DJVU document from a url, eventually using proxies.\n\n    :params url: The URL to the PDF/DJVU document to fetch.\n    :params proxies: An optional list of proxies to use. Proxies will be \\\n            used sequentially. Proxies should be a list of proxy strings. \\\n            Do not forget to include ``\"\"`` (empty string) in the list if \\\n            you want to try direct fetching without any proxy.\n\n    :returns: A tuple of the raw content of the downloaded data and its \\\n            associated content-type. Returns ``(None, None)`` if it was \\\n            unable to download the document.\n\n    >>> download(\"http://arxiv.org/pdf/1312.4006.pdf\") # doctest: +SKIP"
  },
  {
    "code": "def selected(self, interrupt=False):\n        self.ao2.output(self.get_title(), interrupt=interrupt)",
    "docstring": "This object has been selected."
  },
  {
    "code": "def vote_poll(\n        self,\n        chat_id: Union[int, str],\n        message_id: id,\n        option: int\n    ) -> bool:\n        poll = self.get_messages(chat_id, message_id).poll\n        self.send(\n            functions.messages.SendVote(\n                peer=self.resolve_peer(chat_id),\n                msg_id=message_id,\n                options=[poll.options[option].data]\n            )\n        )\n        return True",
    "docstring": "Use this method to vote a poll.\n\n        Args:\n            chat_id (``int`` | ``str``):\n                Unique identifier (int) or username (str) of the target chat.\n                For your personal cloud (Saved Messages) you can simply use \"me\" or \"self\".\n                For a contact that exists in your Telegram address book you can use his phone number (str).\n\n            message_id (``int``):\n                Unique poll message identifier inside this chat.\n\n            option (``int``):\n                Index of the poll option you want to vote for (0 to 9).\n\n        Returns:\n            On success, True is returned.\n\n        Raises:\n            :class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error."
  },
  {
    "code": "def is_after(self, ts):\n        if self.timestamp >= int(calendar.timegm(ts.timetuple())):\n            return True\n        return False",
    "docstring": "Compare this event's timestamp to a give timestamp."
  },
  {
    "code": "def read_file(filename):\n    if os.path.isfile(filename):\n        with open(filename, 'r') as f:\n            return f.read()",
    "docstring": "return the contents of the file named filename or None if file not found"
  },
  {
    "code": "def frame_info(self):\n        if not self._logger.isEnabledFor(logging.DEBUG):\n            return ''\n        f = sys._getframe(3)\n        fname = os.path.split(f.f_code.co_filename)[1]\n        return '{}:{}'.format(fname, f.f_lineno)",
    "docstring": "Return a string identifying the current frame."
  },
  {
    "code": "def _compare_columns(self, new_columns, old_columns):\n        add_columns = {}\n        remove_columns = {}\n        rename_columns = {}\n        retype_columns = {}\n        resize_columns = {}\n        for key, value in new_columns.items():\n            if key not in old_columns.keys():\n                add_columns[key] = True\n                if value[2]:\n                    if value[2] in old_columns.keys():\n                        rename_columns[key] = value[2]\n                        del add_columns[key]\n            else:\n                if value[1] != old_columns[key][1]:\n                    retype_columns[key] = value[1]\n                if value[3] != old_columns[key][3]:\n                    resize_columns[key] = value[3]\n        remove_keys = set(old_columns.keys()) - set(new_columns.keys())\n        if remove_keys:\n            for key in list(remove_keys):\n                remove_columns[key] = True\n        return add_columns, remove_columns, rename_columns, retype_columns, resize_columns",
    "docstring": "a helper method for generating differences between column properties"
  },
  {
    "code": "def __select_builder(lxml_builder, libxml2_builder, cmdline_builder):\n    if prefer_xsltproc:\n        return cmdline_builder\n    if not has_libxml2:\n        if has_lxml:\n            return lxml_builder\n        else:\n            return cmdline_builder\n    return libxml2_builder",
    "docstring": "Selects a builder, based on which Python modules are present."
  },
  {
    "code": "def _anchor_path(self, anchor_id):\n        \"Absolute path to the data file for `anchor_id`.\"\n        file_name = '{}.yml'.format(anchor_id)\n        file_path = self._spor_dir / file_name\n        return file_path",
    "docstring": "Absolute path to the data file for `anchor_id`."
  },
  {
    "code": "def include_fields(self, *args):\n        r\n        for arg in args:\n            self._includefields.append(arg)\n        return self",
    "docstring": "r\"\"\"\n            Include fields is the fields that you want to be returned when\n            searching. These are in addition to the fields that are always\n            included below.\n\n            :param args: items passed in will be turned into a list\n            :returns: :class:`Search`\n\n            >>> bugzilla.search_for.include_fields(\"flags\")\n\n            The following fields are always included in search:\n                'version', 'id', 'summary', 'status', 'op_sys',\n                'resolution', 'product', 'component', 'platform'"
  },
  {
    "code": "def reset_config(ip, mac):\n    click.echo(\"Reset configuration of button %s...\" % ip)\n    data = {\n        'single': \"\",\n        'double': \"\",\n        'long': \"\",\n        'touch': \"\",\n    }\n    request = requests.post(\n        'http://{}/{}/{}/'.format(ip, URI, mac), data=data, timeout=TIMEOUT)\n    if request.status_code == 200:\n        click.echo(\"Reset configuration of %s\" % mac)",
    "docstring": "Reset the current configuration of a myStrom WiFi Button."
  },
  {
    "code": "def is_base_datatype(datatype, version=None):\n    if version is None:\n        version = get_default_version()\n    lib = load_library(version)\n    return lib.is_base_datatype(datatype)",
    "docstring": "Check if the given datatype is a base datatype of the specified version\n\n    :type datatype: ``str``\n    :param datatype: the datatype (e.g. ST)\n\n    :type version: ``str``\n    :param version: the HL7 version (e.g. 2.5)\n\n    :return: ``True`` if it is a base datatype, ``False`` otherwise\n\n    >>> is_base_datatype('ST')\n    True\n    >>> is_base_datatype('CE')\n    False"
  },
  {
    "code": "def _add_parameters(self, parameter_map, parameter_list):\n        for parameter in parameter_list:\n            if parameter.get('$ref'):\n                parameter = self.specification['parameters'].get(parameter.get('$ref').split('/')[-1])\n            parameter_map[parameter['name']] = parameter",
    "docstring": "Populates the given parameter map with the list of parameters provided, resolving any reference objects encountered.\n\n        Args:\n            parameter_map: mapping from parameter names to parameter objects\n            parameter_list: list of either parameter objects or reference objects"
  },
  {
    "code": "def comments(accountable):\n    comments = accountable.issue_comments()\n    headers = sorted(['author_name', 'body', 'updated'])\n    if comments:\n        rows = [[v for k, v in sorted(c.items()) if k in headers]\n                for c in comments]\n        rows.insert(0, headers)\n        print_table(SingleTable(rows))\n    else:\n        click.secho('No comments found for {}'.format(\n            accountable.issue_key\n        ), fg='red')",
    "docstring": "Lists all comments for a given issue key."
  },
  {
    "code": "def _on_split_requested(self):\n        orientation = self.sender().text()\n        widget = self.widget(self.tab_under_menu())\n        if 'horizontally' in orientation:\n            self.split_requested.emit(\n                widget, QtCore.Qt.Horizontal)\n        else:\n            self.split_requested.emit(\n                widget, QtCore.Qt.Vertical)",
    "docstring": "Emits the split requested signal with the desired orientation."
  },
  {
    "code": "def _get_ln_a_n_max(self, C, n_sites, idx, rup):\n        ln_a_n_max = C[\"lnSC1AM\"] * np.ones(n_sites)\n        for i in [2, 3, 4]:\n            if np.any(idx[i]):\n                ln_a_n_max[idx[i]] += C[\"S{:g}\".format(i)]\n        return ln_a_n_max",
    "docstring": "Defines the rock site amplification defined in equations 10a and 10b"
  },
  {
    "code": "def code_timer(reset=False):\n    global CODE_TIMER\n    if reset:\n        CODE_TIMER = CodeTimer()\n    else:\n        if CODE_TIMER is None:\n            return CodeTimer()\n        else:\n            return CODE_TIMER",
    "docstring": "Sets a global variable for tracking the timer accross multiple\n    files"
  },
  {
    "code": "def show_disk(name=None, kwargs=None, call=None):\n    if not kwargs or 'disk_name' not in kwargs:\n        log.error(\n            'Must specify disk_name.'\n        )\n        return False\n    conn = get_conn()\n    return _expand_disk(conn.ex_get_volume(kwargs['disk_name']))",
    "docstring": "Show the details of an existing disk.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -a show_disk myinstance disk_name=mydisk\n        salt-cloud -f show_disk gce disk_name=mydisk"
  },
  {
    "code": "def compose(f: Callable[[Any], Monad], g: Callable[[Any], Monad]) -> Callable[[Any], Monad]:\n    r\n    return lambda x: g(x).bind(f)",
    "docstring": "r\"\"\"Monadic compose function.\n\n    Right-to-left Kleisli composition of two monadic functions.\n\n    (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c\n    f <=< g = \\x -> g x >>= f"
  },
  {
    "code": "def tone_marks():\n    return RegexBuilder(\n        pattern_args=symbols.TONE_MARKS,\n        pattern_func=lambda x: u\"(?<={}).\".format(x)).regex",
    "docstring": "Keep tone-modifying punctuation by matching following character.\n\n    Assumes the `tone_marks` pre-processor was run for cases where there might\n    not be any space after a tone-modifying punctuation mark."
  },
  {
    "code": "def requires_lock(function):\n    def new_lock_requiring_function(self, filename, *args, **kwargs):\n        if self.owns_lock(filename):\n            return function(self, filename, *args, **kwargs)\n        else:\n            raise RequiresLockException()\n    return new_lock_requiring_function",
    "docstring": "Decorator to check if the user owns the required lock.\n    The first argument must be the filename."
  },
  {
    "code": "def close(self):\n        if self._mode == _MODE_CLOSED:\n            return\n        try:\n            if self._mode in (_MODE_READ, _MODE_READ_EOF):\n                self._decompressor = None\n                self._buffer = None\n            elif self._mode == _MODE_WRITE:\n                self._fp.write(self._compressor.flush())\n                self._compressor = None\n        finally:\n            try:\n                if self._closefp:\n                    self._fp.close()\n            finally:\n                self._fp = None\n                self._closefp = False\n                self._mode = _MODE_CLOSED",
    "docstring": "Flush and close the file.\n\n        May be called more than once without error. Once the file is\n        closed, any other operation on it will raise a ValueError."
  },
  {
    "code": "def libvlc_media_list_new(p_instance):\n    f = _Cfunctions.get('libvlc_media_list_new', None) or \\\n        _Cfunction('libvlc_media_list_new', ((1,),), class_result(MediaList),\n                    ctypes.c_void_p, Instance)\n    return f(p_instance)",
    "docstring": "Create an empty media list.\n    @param p_instance: libvlc instance.\n    @return: empty media list, or NULL on error."
  },
  {
    "code": "def r2z(r):\n    with np.errstate(invalid='ignore', divide='ignore'):\n        return 0.5 * (np.log(1 + r) - np.log(1 - r))",
    "docstring": "Function that calculates the Fisher z-transformation\n\n    Parameters\n    ----------\n    r : int or ndarray\n        Correlation value\n\n    Returns\n    ----------\n    result : int or ndarray\n        Fishers z transformed correlation value"
  },
  {
    "code": "def detect_encoding(fp, default=None):\n    init_pos = fp.tell()\n    try:\n        sample = fp.read(\n            current_app.config.get('PREVIEWER_CHARDET_BYTES', 1024))\n        result = cchardet.detect(sample)\n        threshold = current_app.config.get('PREVIEWER_CHARDET_CONFIDENCE', 0.9)\n        if result.get('confidence', 0) > threshold:\n            return result.get('encoding', default)\n        else:\n            return default\n    except Exception:\n        current_app.logger.warning('Encoding detection failed.', exc_info=True)\n        return default\n    finally:\n        fp.seek(init_pos)",
    "docstring": "Detect the cahracter encoding of a file.\n\n    :param fp: Open Python file pointer.\n    :param default: Fallback encoding to use.\n    :returns: The detected encoding.\n\n    .. note:: The file pointer is returned at its original read position."
  },
  {
    "code": "def friendships_create(self, user_id=None, screen_name=None,\n                           follow=None):\n        params = {}\n        set_str_param(params, 'user_id', user_id)\n        set_str_param(params, 'screen_name', screen_name)\n        set_bool_param(params, 'follow', follow)\n        return self._post_api('friendships/create.json', params)",
    "docstring": "Allows the authenticating users to follow the specified user.\n\n        https://dev.twitter.com/docs/api/1.1/post/friendships/create\n\n        :param str user_id:\n            The screen name of the user for whom to befriend. Required if\n            ``screen_name`` isn't given.\n        :param str screen_name:\n            The ID of the user for whom to befriend. Required if ``user_id``\n            isn't given.\n        :param bool follow:\n            Enable notifications for the target user.\n\n        :returns:\n            A dict containing the newly followed user."
  },
  {
    "code": "def remove_option(self, section, name, value=None):\n        if self._is_live():\n            raise RuntimeError('Submitted units cannot update their options')\n        removed = 0\n        for option in list(self._data['options']):\n            if option['section'] == section:\n                if option['name'] == name:\n                    if value is None or option['value'] == value:\n                        self._data['options'].remove(option)\n                        removed += 1\n        if removed > 0:\n            return True\n        return False",
    "docstring": "Remove an option from a unit\n\n        Args:\n            section (str): The section to remove from.\n            name (str): The item to remove.\n            value (str, optional): If specified, only the option matching this value will be removed\n                                   If not specified, all options with ``name`` in ``section`` will be removed\n\n        Returns:\n            True: At least one item was removed\n            False: The item requested to remove was not found"
  },
  {
    "code": "def getAtomLinesForResidueInRosettaStructure(self, resid):\n        lines = [line for line in self.lines if line[0:4] == \"ATOM\" and resid == int(line[22:27])]\n        if not lines:\n            raise Exception(\"Could not find the ATOM/HETATM line corresponding to residue '%(resid)s'.\" % vars())\n        return lines",
    "docstring": "We assume a Rosetta-generated structure where residues are uniquely identified by number."
  },
  {
    "code": "def kabsch_rmsd(P, Q, translate=False):\n    if translate:\n        Q = Q - centroid(Q)\n        P = P - centroid(P)\n    P = kabsch_rotate(P, Q)\n    return rmsd(P, Q)",
    "docstring": "Rotate matrix P unto Q using Kabsch algorithm and calculate the RMSD.\n\n    Parameters\n    ----------\n    P : array\n        (N,D) matrix, where N is points and D is dimension.\n    Q : array\n        (N,D) matrix, where N is points and D is dimension.\n    translate : bool\n        Use centroids to translate vector P and Q unto each other.\n\n    Returns\n    -------\n    rmsd : float\n        root-mean squared deviation"
  },
  {
    "code": "def hidden_cursor(self):\n        self.stream.write(self.hide_cursor)\n        try:\n            yield\n        finally:\n            self.stream.write(self.normal_cursor)",
    "docstring": "Return a context manager that hides the cursor while inside it and\n        makes it visible on leaving."
  },
  {
    "code": "def is_analyst_assignment_allowed(self):\n        if not self.allow_edit:\n            return False\n        if not self.can_manage:\n            return False\n        if self.filter_by_user:\n            return False\n        return True",
    "docstring": "Check if the analyst can be assigned"
  },
  {
    "code": "def inserted_hs_indices(self):\n        if self.dimension_type in DT.ARRAY_TYPES:\n            return []\n        return [\n            idx\n            for idx, item in enumerate(\n                self._iter_interleaved_items(self.valid_elements)\n            )\n            if item.is_insertion\n        ]",
    "docstring": "list of int index of each inserted subtotal for the dimension.\n\n        Each value represents the position of a subtotal in the interleaved\n        sequence of elements and subtotals items."
  },
  {
    "code": "def get_branching_nodes(self):\n        nodes = set()\n        for n in self.graph.nodes():\n            if self.graph.out_degree(n) >= 2:\n                nodes.add(n)\n        return nodes",
    "docstring": "Returns all nodes that has an out degree >= 2"
  },
  {
    "code": "def nodes_with_role(rolename):\n    nodes = [n['name'] for n in\n             lib.get_nodes_with_role(rolename, env.chef_environment)]\n    if not len(nodes):\n        print(\"No nodes found with role '{0}'\".format(rolename))\n        sys.exit(0)\n    return node(*nodes)",
    "docstring": "Configures a list of nodes that have the given role in their run list"
  },
  {
    "code": "def get_all_parents(self):\n        ownership = Ownership.objects.filter(child=self)\n        parents = Company.objects.filter(parent__in=ownership)\n        for parent in parents:\n            parents = parents | parent.get_all_parents()\n        return parents",
    "docstring": "Return all parents of this company."
  },
  {
    "code": "def _get_all_run_infos(self):\n    info_dir = self._settings.info_dir\n    if not os.path.isdir(info_dir):\n      return []\n    paths = [os.path.join(info_dir, x) for x in os.listdir(info_dir)]\n    return [d for d in\n            [RunInfo(os.path.join(p, 'info')).get_as_dict() for p in paths\n             if os.path.isdir(p) and not os.path.islink(p)]\n            if 'timestamp' in d]",
    "docstring": "Find the RunInfos for all runs since the last clean-all."
  },
  {
    "code": "def register_service(service):\n    frame = inspect.currentframe()\n    m_name = frame.f_back.f_globals['__name__']\n    m = sys.modules[m_name]\n    m._SERVICE_NAME = service",
    "docstring": "Register the ryu application specified by 'service' as\n    a provider of events defined in the calling module.\n\n    If an application being loaded consumes events (in the sense of\n    set_ev_cls) provided by the 'service' application, the latter\n    application will be automatically loaded.\n\n    This mechanism is used to e.g. automatically start ofp_handler if\n    there are applications consuming OFP events."
  },
  {
    "code": "def _looks_like_numpy_function(func_name, numpy_module_name, node):\n    return node.name == func_name and node.parent.name == numpy_module_name",
    "docstring": "Return True if the current node correspond to the function inside\n    the numpy module in parameters\n\n    :param node: the current node\n    :type node: FunctionDef\n    :param func_name: name of the function\n    :type func_name: str\n    :param numpy_module_name: name of the numpy module\n    :type numpy_module_name: str\n    :return: True if the current node correspond to the function looked for\n    :rtype: bool"
  },
  {
    "code": "def size_in_bytes(self, offset, timestamp, key, value, headers=None):\n        assert not headers, \"Headers not supported in v0/v1\"\n        magic = self._magic\n        return self.LOG_OVERHEAD + self.record_size(magic, key, value)",
    "docstring": "Actual size of message to add"
  },
  {
    "code": "def validate_callback(callback):\n    if not(hasattr(callback, '_validated')) or callback._validated == False:\n        assert hasattr(callback, 'on_loop_start') \\\n               or hasattr(callback, 'on_loop_end'), \\\n               'callback must have `on_loop_start` or `on_loop_end` method'\n        if hasattr(callback, 'on_loop_start'):\n            setattr(callback, 'on_loop_start',\n                    validate_callback_data(callback.on_loop_start))\n        if hasattr(callback, 'on_loop_end'):\n            setattr(callback, 'on_loop_end',\n                    validate_callback_data(callback.on_loop_end))\n        setattr(callback, '_validated', True)\n    return callback",
    "docstring": "validates a callback's on_loop_start and on_loop_end methods\n\n    Parameters\n    ----------\n    callback : Callback object\n\n    Returns\n    -------\n    validated callback"
  },
  {
    "code": "def _looks_like_resource_file(self, name):\n        if (re.search(r'__init__.(txt|robot|html|tsv)$', name)):\n            return False\n        found_keyword_table = False\n        if (name.lower().endswith(\".robot\") or\n            name.lower().endswith(\".txt\") or\n            name.lower().endswith(\".tsv\")):\n            with open(name, \"r\") as f:\n                data = f.read()\n                for match in re.finditer(r'^\\*+\\s*(Test Cases?|(?:User )?Keywords?)',\n                                         data, re.MULTILINE|re.IGNORECASE):\n                    if (re.match(r'Test Cases?', match.group(1), re.IGNORECASE)):\n                        return False\n                    if (not found_keyword_table and\n                        re.match(r'(User )?Keywords?', match.group(1), re.IGNORECASE)):\n                        found_keyword_table = True\n        return found_keyword_table",
    "docstring": "Return true if the file has a keyword table but not a testcase table"
  },
  {
    "code": "def lstltc(string, n, lenvals, array):\n    string = stypes.stringToCharP(string)\n    array = stypes.listToCharArrayPtr(array, xLen=lenvals, yLen=n)\n    n = ctypes.c_int(n)\n    lenvals = ctypes.c_int(lenvals)\n    return libspice.lstltc_c(string, n, lenvals, array)",
    "docstring": "Given a character string and an ordered array of character\n    strings, find the index of the largest array element less than\n    the given string.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstltc_c.html\n\n    :param string: Upper bound value to search against.\n    :type string: int\n    :param n: Number elements in array.\n    :type n: int\n    :param lenvals: String length.\n    :type lenvals: int\n    :param array: Array of possible lower bounds\n    :type array: list\n    :return:\n            index of the last element of array that\n            is lexically less than string.\n    :rtype: int"
  },
  {
    "code": "def _q_iteration(self, Q, Bpp_solver, Vm, Va, pq):\n        dVm = -Bpp_solver.solve(Q)\n        Vm[pq] = Vm[pq] + dVm\n        V = Vm * exp(1j * Va)\n        return V, Vm, Va",
    "docstring": "Performs a Q iteration, updates Vm."
  },
  {
    "code": "def elapsed(self, label=None, total=True):\n        t = timer()\n        if label is None:\n            label = self.dfltlbl\n            if label not in self.t0:\n                return 0.0\n        if label not in self.t0:\n            raise KeyError('Unrecognized timer key %s' % label)\n        te = 0.0\n        if self.t0[label] is not None:\n            te = t - self.t0[label]\n        if total:\n            te += self.td[label]\n        return te",
    "docstring": "Get elapsed time since timer start.\n\n        Parameters\n        ----------\n        label : string, optional (default None)\n          Specify the label of the timer for which the elapsed time is\n          required.  If it is ``None``, the default timer with label\n          specified by the ``dfltlbl`` parameter of :meth:`__init__`\n          is selected.\n        total : bool, optional (default True)\n          If ``True`` return the total elapsed time since the first\n          call of :meth:`start` for the selected timer, otherwise\n          return the elapsed time since the most recent call of\n          :meth:`start` for which there has not been a corresponding\n          call to :meth:`stop`.\n\n        Returns\n        -------\n        dlt : float\n          Elapsed time"
  },
  {
    "code": "def setup(self):\n        if not self.networks():\n            for _ in range(self.practice_repeats):\n                network = self.create_network()\n                network.role = \"practice\"\n                self.session.add(network)\n            for _ in range(self.experiment_repeats):\n                network = self.create_network()\n                network.role = \"experiment\"\n                self.session.add(network)\n            self.session.commit()",
    "docstring": "Create the networks if they don't already exist."
  },
  {
    "code": "def select_and_start_cluster(self, platform):\n        clusters = self.reactor_config.get_enabled_clusters_for_platform(platform)\n        if not clusters:\n            raise UnknownPlatformException('No clusters found for platform {}!'\n                                           .format(platform))\n        retry_contexts = {\n            cluster.name: ClusterRetryContext(self.max_cluster_fails)\n            for cluster in clusters\n        }\n        while True:\n            try:\n                possible_cluster_info = self.get_clusters(platform,\n                                                          retry_contexts,\n                                                          clusters)\n            except AllClustersFailedException as ex:\n                cluster = ClusterInfo(None, platform, None, None)\n                build_info = WorkerBuildInfo(build=None,\n                                             cluster_info=cluster,\n                                             logger=self.log)\n                build_info.monitor_exception = repr(ex)\n                self.worker_builds.append(build_info)\n                return\n            for cluster_info in possible_cluster_info:\n                ctx = retry_contexts[cluster_info.cluster.name]\n                try:\n                    self.log.info('Attempting to start build for platform %s on cluster %s',\n                                  platform, cluster_info.cluster.name)\n                    self.do_worker_build(cluster_info)\n                    return\n                except OsbsException:\n                    ctx.try_again_later(self.failure_retry_delay)",
    "docstring": "Choose a cluster and start a build on it"
  },
  {
    "code": "def get(self):\n        content = {}\n        if self.mime_type is not None:\n            content[\"type\"] = self.mime_type\n        if self.content is not None:\n            content[\"value\"] = self.content\n        return content",
    "docstring": "Get a JSON-ready representation of this HtmlContent.\n\n        :returns: This HtmlContent, ready for use in a request body.\n        :rtype: dict"
  },
  {
    "code": "def _index_entities(self):\n        all_ents = pd.DataFrame.from_records(\n            [v.entities for v in self.variables.values()])\n        constant = all_ents.apply(lambda x: x.nunique() == 1)\n        if constant.empty:\n            self.entities = {}\n        else:\n            keep = all_ents.columns[constant]\n            ents = {k: all_ents[k].dropna().iloc[0] for k in keep}\n            self.entities = {k: v for k, v in ents.items() if pd.notnull(v)}",
    "docstring": "Sets current instance's entities based on the existing index.\n\n        Note: Only entity key/value pairs common to all rows in all contained\n            Variables are returned. E.g., if a Collection contains Variables\n            extracted from runs 1, 2 and 3 from subject '01', the returned dict\n            will be {'subject': '01'}; the runs will be excluded as they vary\n            across the Collection contents."
  },
  {
    "code": "def load_glove(file):\n    model = {}\n    with open(file, encoding=\"utf8\", errors='ignore') as f:\n        for line in f:\n            line = line.split(' ')\n            word = line[0]\n            vector = np.array([float(val) for val in line[1:]])\n            model[word] = vector\n    return model",
    "docstring": "Loads GloVe vectors in numpy array.\n\n    Args:\n        file (str): a path to a glove file.\n\n    Return:\n        dict: a dict of numpy arrays."
  },
  {
    "code": "def clear(self, contours=True, components=True, anchors=True,\n              guidelines=True, image=True):\n        self._clear(contours=contours, components=components,\n                    anchors=anchors, guidelines=guidelines, image=image)",
    "docstring": "Clear the glyph.\n\n            >>> glyph.clear()\n\n        This clears:\n\n        - contours\n        - components\n        - anchors\n        - guidelines\n        - image\n\n        It's possible to turn off the clearing of portions of\n        the glyph with the listed arguments.\n\n            >>> glyph.clear(guidelines=False)"
  },
  {
    "code": "def _del_module(self, lpBaseOfDll):\n        try:\n            aModule = self.__moduleDict[lpBaseOfDll]\n            del self.__moduleDict[lpBaseOfDll]\n        except KeyError:\n            aModule = None\n            msg = \"Unknown base address %d\" % HexDump.address(lpBaseOfDll)\n            warnings.warn(msg, RuntimeWarning)\n        if aModule:\n            aModule.clear()",
    "docstring": "Private method to remove a module object from the snapshot.\n\n        @type  lpBaseOfDll: int\n        @param lpBaseOfDll: Module base address."
  },
  {
    "code": "def asDictionary(self):\n        template = {\n            \"xmin\" : self._xmin,\n            \"ymin\" : self._ymin,\n            \"xmax\" : self._xmax,\n            \"ymax\" : self._ymax,\n            \"spatialReference\" : self.spatialReference\n        }\n        if self._zmax is not None and \\\n           self._zmin is not None:\n            template['zmin'] = self._zmin\n            template['zmax'] = self._zmax\n        if self._mmin is not None and \\\n           self._mmax is not None:\n            template['mmax'] = self._mmax\n            template['mmin'] = self._mmin\n        return template",
    "docstring": "returns the envelope as a dictionary"
  },
  {
    "code": "def start_recording(self, file='mingus_dump.wav'):\n        w = wave.open(file, 'wb')\n        w.setnchannels(2)\n        w.setsampwidth(2)\n        w.setframerate(44100)\n        self.wav = w",
    "docstring": "Initialize a new wave file for recording."
  },
  {
    "code": "def paginator(context, adjacent_pages=2):\r\n    current_page = context.get('page')\r\n    paginator    = context.get('paginator')\r\n    if not paginator:\r\n        return\r\n    pages        = paginator.num_pages\r\n    current_range = range(current_page - adjacent_pages, current_page + adjacent_pages + 1)\r\n    page_numbers = [n for n in current_range if n > 0 and n <= pages]\r\n    slugtype = ''\r\n    if 'topic_slug' in context:\r\n        page_url = context[\"topic\"].get_short_url()\r\n        slugtype = 'topic'\r\n    elif 'forum_slug' in context:\r\n        page_url = '/forum/%s/' % context[\"forum_slug\"]\r\n        slugtype = 'forum'\r\n    else:\r\n        page_url = context['request'].get_full_path()\r\n    return {\r\n        \"is_paginated\": context[\"is_paginated\"],\r\n        \"page\": current_page,\r\n        \"pages\": pages,\r\n        \"page_obj\": context['page_obj'],\r\n        \"page_numbers\": page_numbers,\r\n        \"has_next\": context[\"page_obj\"].has_next(),\r\n        \"has_previous\": context[\"page_obj\"].has_previous(),\r\n        \"page_url\" : page_url,\r\n        'slugtype' : slugtype,\r\n    }",
    "docstring": "To be used in conjunction with the object_list generic view.\r\n    Adds pagination context variables for use in displaying first, adjacent and\r\n    last page links in addition to those created by the object_list generic view."
  },
  {
    "code": "def compute_We(self, Eemin=None, Eemax=None):\n        if Eemin is None and Eemax is None:\n            We = self.We\n        else:\n            if Eemax is None:\n                Eemax = self.Eemax\n            if Eemin is None:\n                Eemin = self.Eemin\n            log10gmin = np.log10(Eemin / mec2).value\n            log10gmax = np.log10(Eemax / mec2).value\n            gam = np.logspace(\n                log10gmin, log10gmax, int(self.nEed * (log10gmax - log10gmin))\n            )\n            nelec = (\n                self.particle_distribution(gam * mec2).to(1 / mec2_unit).value\n            )\n            We = trapz_loglog(gam * nelec, gam * mec2)\n        return We",
    "docstring": "Total energy in electrons between energies Eemin and Eemax\n\n        Parameters\n        ----------\n        Eemin : :class:`~astropy.units.Quantity` float, optional\n            Minimum electron energy for energy content calculation.\n\n        Eemax : :class:`~astropy.units.Quantity` float, optional\n            Maximum electron energy for energy content calculation."
  },
  {
    "code": "def getChemicalPotential(self, solution):\n        if isinstance(solution, Solution):\n            solution = solution.getSolution()\n        self.mu = self.solver.chemicalPotential(solution)\n        return self.mu",
    "docstring": "Call solver in order to calculate chemical potential."
  },
  {
    "code": "def get_bug_report():\n        platform_info = BugReporter.get_platform_info()\n        module_info = {\n            'version': hal_version.__version__,\n            'build': hal_version.__build__\n        }\n        return {\n            'platform': platform_info,\n            'pyhal': module_info\n        }",
    "docstring": "Generate information for a bug report\n\n        :return: information for bug report"
  },
  {
    "code": "def create(self, name, redirect_uri=None):\n        data = dict(name=name)\n        if redirect_uri:\n            data['redirect_uri'] = redirect_uri\n        auth_request_resource = self.resource.create(data)\n        return (auth_request_resource.attributes['metadata']['device_token'],\n                auth_request_resource.attributes['mfa_uri'])",
    "docstring": "Create a new Device object.\n\n        Devices tie Users and Applications together. For your Application to\n        access and act on behalf of a User, the User must authorize a Device\n        created by your Application.\n\n        This function will return a `device_token` which you must store and use\n        after the Device is approved in\n          `client.authenticate_device(api_token, device_token)`\n\n        The second value returned is an `mfa_uri` which is the location the User\n        must visit to approve the new device. After this function completes,\n        you should launch a new browser tab or webview with this value as the\n        location. After the User approves the Device, they will be redirected to\n        the redirect_uri you specify in this call.\n\n        Args:\n          name (str): Human-readable name for the device\n            (e.g. \"Suzanne's iPhone\")\n          redirect_uri (str, optional): A URI to which to redirect the User after\n            they approve the new Device.\n\n        Returns: A tuple of (device_token, mfa_uri)"
  },
  {
    "code": "def add_arrow(self, tipLoc, tail=None, arrow=arrow.default):\n        self._arrows.append((tipLoc, tail, arrow))",
    "docstring": "This method adds a straight arrow that points to\n        @var{TIPLOC}, which is a tuple of integers. @var{TAIL}\n        specifies the starting point of the arrow. It is either None\n        or a string consisting of the following letters: 'l', 'c',\n        'r', 't', 'm,', and 'b'.  Letters 'l', 'c', or 'r' means to\n        start the arrow from the left, center, or right of the text\n        box, respectively. Letters 't', 'm', or 'b' means to start the\n        arrow from the top, middle or bottom of the text box.  For\n        example, when @samp{tail = 'tc'} then arrow is drawn from\n        top-center point of the text box. ARROW specifies the style of\n        the arrow. <<arrow>>."
  },
  {
    "code": "def contains(self, key):\n    try:\n      self._api.objects_get(self._bucket, key)\n    except datalab.utils.RequestException as e:\n      if e.status == 404:\n        return False\n      raise e\n    except Exception as e:\n      raise e\n    return True",
    "docstring": "Checks if the specified item exists.\n\n    Args:\n      key: the key of the item to lookup.\n    Returns:\n      True if the item exists; False otherwise.\n    Raises:\n      Exception if there was an error requesting information about the item."
  },
  {
    "code": "def set_spacing(self, new_spacing):\n        if not isinstance(new_spacing, (tuple, list)):\n            raise ValueError('arg must be tuple or list')\n        if len(new_spacing) != self.dimension:\n            raise ValueError('must give a spacing value for each dimension (%i)' % self.dimension)\n        libfn = utils.get_lib_fn('setSpacing%s'%self._libsuffix)\n        libfn(self.pointer, new_spacing)",
    "docstring": "Set image spacing\n\n        Arguments\n        ---------\n        new_spacing : tuple or list\n            updated spacing for the image.\n            should have one value for each dimension\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def check_cmake_exists(cmake_command):\n    from subprocess import Popen, PIPE\n    p = Popen(\n        '{0} --version'.format(cmake_command),\n        shell=True,\n        stdin=PIPE,\n        stdout=PIPE)\n    if not ('cmake version' in p.communicate()[0].decode('UTF-8')):\n        sys.stderr.write('   This code is built using CMake\\n\\n')\n        sys.stderr.write('   CMake is not found\\n')\n        sys.stderr.write('   get CMake at http://www.cmake.org/\\n')\n        sys.stderr.write('   on many clusters CMake is installed\\n')\n        sys.stderr.write('   but you have to load it first:\\n')\n        sys.stderr.write('   $ module load cmake\\n')\n        sys.exit(1)",
    "docstring": "Check whether CMake is installed. If not, print\n    informative error message and quits."
  },
  {
    "code": "async def logs(\n        self,\n        service_id: str,\n        *,\n        details: bool = False,\n        follow: bool = False,\n        stdout: bool = False,\n        stderr: bool = False,\n        since: int = 0,\n        timestamps: bool = False,\n        is_tty: bool = False,\n        tail: str = \"all\"\n    ) -> Union[str, AsyncIterator[str]]:\n        if stdout is False and stderr is False:\n            raise TypeError(\"Need one of stdout or stderr\")\n        params = {\n            \"details\": details,\n            \"follow\": follow,\n            \"stdout\": stdout,\n            \"stderr\": stderr,\n            \"since\": since,\n            \"timestamps\": timestamps,\n            \"tail\": tail,\n        }\n        response = await self.docker._query(\n            \"services/{service_id}/logs\".format(service_id=service_id),\n            method=\"GET\",\n            params=params,\n        )\n        return await multiplexed_result(response, follow, is_tty=is_tty)",
    "docstring": "Retrieve logs of the given service\n\n        Args:\n            details: show service context and extra details provided to logs\n            follow: return the logs as a stream.\n            stdout: return logs from stdout\n            stderr: return logs from stderr\n            since: return logs since this time, as a UNIX timestamp\n            timestamps: add timestamps to every log line\n            is_tty: the service has a pseudo-TTY allocated\n            tail: only return this number of log lines\n                  from the end of the logs, specify as an integer\n                  or `all` to output all log lines."
  },
  {
    "code": "def pad_sentences(sentences, padding_word=\"</s>\"):\n    sequence_length = max(len(x) for x in sentences)\n    padded_sentences = []\n    for i, sentence in enumerate(sentences):\n        num_padding = sequence_length - len(sentence)\n        new_sentence = sentence + [padding_word] * num_padding\n        padded_sentences.append(new_sentence)\n    return padded_sentences",
    "docstring": "Pads all sentences to the same length. The length is defined by the longest sentence.\n    Returns padded sentences."
  },
  {
    "code": "def exists(self, digest):\n        return self.conn.client.blob_exists(self.container_name, digest)",
    "docstring": "Check if a blob exists\n\n        :param digest: Hex digest of the blob\n        :return: Boolean indicating existence of the blob"
  },
  {
    "code": "def _update(self, **kwargs):\n        path = self._construct_path_to_item()\n        if not kwargs:\n            return\n        return self._http.put(path, json.dumps(kwargs))",
    "docstring": "Update a resource in a remote Transifex server."
  },
  {
    "code": "def get_record_value(request, uid, keyword, default=None):\n    value = request.get(keyword)\n    if not value:\n        return default\n    if not isinstance(value, list):\n        return default\n    return value[0].get(uid, default) or default",
    "docstring": "Returns the value for the keyword and uid from the request"
  },
  {
    "code": "def abort(status_code, message=None):\n    if message is None:\n        message = STATUS_CODES.get(status_code)\n        message = message.decode(\"utf8\")\n    sanic_exception = _sanic_exceptions.get(status_code, SanicException)\n    raise sanic_exception(message=message, status_code=status_code)",
    "docstring": "Raise an exception based on SanicException. Returns the HTTP response\n    message appropriate for the given status code, unless provided.\n\n    :param status_code: The HTTP status code to return.\n    :param message: The HTTP response body. Defaults to the messages\n                    in response.py for the given status code."
  },
  {
    "code": "def _prepare_resource_chunks(self, resources, resource_delim=','):\n        return [self._prepare_resource_chunk(resources, resource_delim, pos)\n                for pos in range(0, len(resources), self._resources_per_req)]",
    "docstring": "As in some VirusTotal API methods the call can be made for multiple\n        resources at once this method prepares a list of concatenated resources\n        according to the maximum number of resources per requests.\n\n        Args:\n            resources: a list of the resources.\n            resource_delim: a string used to separate the resources.\n              Default value is a comma.\n        Returns:\n            A list of the concatenated resources."
  },
  {
    "code": "def row(self, data):\n        for column in self.column_funcs:\n            if callable(column):\n                yield column(data)\n            else:\n                yield utils.lookup(data, *column)",
    "docstring": "Return a formatted row for the given data."
  },
  {
    "code": "def add(self, uuid):\n        if uuid:\n            try:\n                x = hash64(uuid)\n            except UnicodeEncodeError:\n                x = hash64(uuid.encode('ascii', 'ignore'))\n            j = x & ((1 << self.b) - 1)\n            w = x >> self.b\n            self.M[j] = max(self.M[j], self._get_rho(w, self.bitcount_arr))",
    "docstring": "Adds a key to the HyperLogLog"
  },
  {
    "code": "def update_buttons(self):\n        current_scheme = self.current_scheme\n        names = self.get_option(\"names\")\n        try:\n            names.pop(names.index(u'Custom'))\n        except ValueError:\n            pass\n        delete_enabled = current_scheme not in names\n        self.delete_button.setEnabled(delete_enabled)\n        self.reset_button.setEnabled(not delete_enabled)",
    "docstring": "Updates the enable status of delete and reset buttons."
  },
  {
    "code": "def split_arguments(args):\n    prev = False\n    for i, value in enumerate(args[1:]):\n        if value.startswith('-'):\n            prev = True\n        elif prev:\n            prev = False\n        else:\n            return args[:i+1], args[i+1:]\n    return args, []",
    "docstring": "Split specified arguments to two list.\n\n    This is used to distinguish the options of the program and\n    execution command/arguments.\n\n    Parameters\n    ----------\n    args : list\n        Command line arguments\n\n    Returns\n    -------\n    list : options, arguments\n        options indicate the optional arguments for the program and\n        arguments indicate the execution command/arguments"
  },
  {
    "code": "def right(ctx, text, num_chars):\n    num_chars = conversions.to_integer(num_chars, ctx)\n    if num_chars < 0:\n        raise ValueError(\"Number of chars can't be negative\")\n    elif num_chars == 0:\n        return ''\n    else:\n        return conversions.to_string(text, ctx)[-num_chars:]",
    "docstring": "Returns the last characters in a text string"
  },
  {
    "code": "def get_route(self, route_id):\n        raw = self.protocol.get('/routes/{id}', id=route_id)\n        return model.Route.deserialize(raw, bind_client=self)",
    "docstring": "Gets specified route.\n\n        Will be detail-level if owned by authenticated user; otherwise summary-level.\n\n        https://strava.github.io/api/v3/routes/#retreive\n\n        :param route_id: The ID of route to fetch.\n        :type route_id: int\n\n        :rtype: :class:`stravalib.model.Route`"
  },
  {
    "code": "def merge_dicts(dict1, dict2, deep_merge=True):\n    if deep_merge:\n        if isinstance(dict1, list) and isinstance(dict2, list):\n            return dict1 + dict2\n        if not isinstance(dict1, dict) or not isinstance(dict2, dict):\n            return dict2\n        for key in dict2:\n            dict1[key] = merge_dicts(dict1[key], dict2[key]) if key in dict1 else dict2[key]\n        return dict1\n    dict3 = dict1.copy()\n    dict3.update(dict2)\n    return dict3",
    "docstring": "Merge dict2 into dict1."
  },
  {
    "code": "def delete(self):\n        self.close()\n        if self.does_file_exist():\n            os.remove(self.path)",
    "docstring": "Delete the file."
  },
  {
    "code": "def _overwrite(self, n):\n        if os.path.isfile(n[:-4]):\n            shutil.copy2(n[:-4], n[:-4] + \".old\")\n            print(\"Old file {0} saved as {1}.old\".format(\n                n[:-4].split(\"/\")[-1], n[:-4].split(\"/\")[-1]))\n        if os.path.isfile(n):\n            shutil.move(n, n[:-4])\n            print(\"New file {0} overwrite as {1}\".format(\n                n.split(\"/\")[-1], n[:-4].split(\"/\")[-1]))",
    "docstring": "Overwrite old file with new and keep file with suffix .old"
  },
  {
    "code": "def create_d1_dn_subject(common_name_str):\n    return cryptography.x509.Name(\n        [\n            cryptography.x509.NameAttribute(\n                cryptography.x509.oid.NameOID.COUNTRY_NAME, \"US\"\n            ),\n            cryptography.x509.NameAttribute(\n                cryptography.x509.oid.NameOID.STATE_OR_PROVINCE_NAME, \"California\"\n            ),\n            cryptography.x509.NameAttribute(\n                cryptography.x509.oid.NameOID.LOCALITY_NAME, \"San Francisco\"\n            ),\n            cryptography.x509.NameAttribute(\n                cryptography.x509.oid.NameOID.ORGANIZATION_NAME, \"Root CA\"\n            ),\n            cryptography.x509.NameAttribute(\n                cryptography.x509.oid.NameOID.COMMON_NAME, \"ca.ca.com\"\n            ),\n        ]\n    )",
    "docstring": "Create the DN Subject for certificate that will be used in a DataONE environment.\n\n    The DN is formatted into a DataONE subject, which is used in authentication,\n    authorization and event tracking.\n\n    Args:\n        common_name_str: str\n            DataONE uses simple DNs without physical location information, so only the\n            ``common_name_str`` (``CommonName``) needs to be specified.\n\n            For Member Node Client Side certificates or CSRs, ``common_name_str`` is the\n            ``node_id``, e.g., ``urn:node:ABCD`` for production, or\n            ``urn:node:mnTestABCD`` for the test environments.\n\n            For a local CA, something like ``localCA`` may be used.\n\n            For a locally trusted client side certificate, something like\n            ``localClient`` may be used."
  },
  {
    "code": "def events(self, *events):\n        return self.send_events(self.create_event(e) for e in events)",
    "docstring": "Sends multiple events in a single message\n\n        >>> client.events({'service': 'riemann-client', 'state': 'awesome'})\n\n         :param \\*events: event dictionaries for :py:func:`create_event`\n         :returns: The response message from Riemann"
  },
  {
    "code": "def has_path(self, path, method=None):\n        method = self._normalize_method_name(method)\n        path_dict = self.get_path(path)\n        path_dict_exists = path_dict is not None\n        if method:\n            return path_dict_exists and method in path_dict\n        return path_dict_exists",
    "docstring": "Returns True if this Swagger has the given path and optional method\n\n        :param string path: Path name\n        :param string method: HTTP method\n        :return: True, if this path/method is present in the document"
  },
  {
    "code": "def set_category(self, category):\n        pcategory = self.find(\"general/category\")\n        pcategory.clear()\n        name = ElementTree.SubElement(pcategory, \"name\")\n        if isinstance(category, Category):\n            id_ = ElementTree.SubElement(pcategory, \"id\")\n            id_.text = category.id\n            name.text = category.name\n        elif isinstance(category, basestring):\n            name.text = category",
    "docstring": "Set the policy's category.\n\n        Args:\n            category: A category object."
  },
  {
    "code": "def append_tag(self, field_number, wire_type):\n        self._stream.append_var_uint32(wire_format.pack_tag(field_number, wire_type))",
    "docstring": "Appends a tag containing field number and wire type information."
  },
  {
    "code": "def delete_operation(\n        self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT\n    ):\n        request = operations_pb2.DeleteOperationRequest(name=name)\n        self._delete_operation(request, retry=retry, timeout=timeout)",
    "docstring": "Deletes a long-running operation.\n\n        This method indicates that the client is no longer interested in the\n        operation result. It does not cancel the operation.\n\n        Example:\n            >>> from google.api_core import operations_v1\n            >>> api = operations_v1.OperationsClient()\n            >>> name = ''\n            >>> api.delete_operation(name)\n\n        Args:\n            name (str): The name of the operation resource to be deleted.\n            retry (google.api_core.retry.Retry): The retry strategy to use\n                when invoking the RPC. If unspecified, the default retry from\n                the client configuration will be used. If ``None``, then this\n                method will not retry the RPC at all.\n            timeout (float): The amount of time in seconds to wait for the RPC\n                to complete. Note that if ``retry`` is used, this timeout\n                applies to each individual attempt and the overall time it\n                takes for this method to complete may be longer. If\n                unspecified, the the default timeout in the client\n                configuration is used. If ``None``, then the RPC method will\n                not time out.\n\n        Raises:\n            google.api_core.exceptions.MethodNotImplemented: If the server\n                does not support this method. Services are not required to\n                implement this method.\n            google.api_core.exceptions.GoogleAPICallError: If an error occurred\n                while invoking the RPC, the appropriate ``GoogleAPICallError``\n                subclass will be raised."
  },
  {
    "code": "async def enable_digital_reporting(self, command):\n        pin = int(command[0])\n        await self.core.enable_digital_reporting(pin)",
    "docstring": "Enable Firmata reporting for a digital pin.\n\n        :param command: {\"method\": \"enable_digital_reporting\", \"params\": [PIN]}\n        :returns: {\"method\": \"digital_message_reply\", \"params\": [PIN, DIGITAL_DATA_VALUE]}"
  },
  {
    "code": "def rename(name):\n    from peltak.extra.gitflow import logic\n    if name is None:\n        name = click.prompt('Hotfix name')\n    logic.hotfix.rename(name)",
    "docstring": "Give the currently developed hotfix a new name."
  },
  {
    "code": "def _validate_sub(claims, subject=None):\n    if 'sub' not in claims:\n        return\n    if not isinstance(claims['sub'], string_types):\n        raise JWTClaimsError('Subject must be a string.')\n    if subject is not None:\n        if claims.get('sub') != subject:\n            raise JWTClaimsError('Invalid subject')",
    "docstring": "Validates that the 'sub' claim is valid.\n\n    The \"sub\" (subject) claim identifies the principal that is the\n    subject of the JWT.  The claims in a JWT are normally statements\n    about the subject.  The subject value MUST either be scoped to be\n    locally unique in the context of the issuer or be globally unique.\n    The processing of this claim is generally application specific.  The\n    \"sub\" value is a case-sensitive string containing a StringOrURI\n    value.  Use of this claim is OPTIONAL.\n\n    Args:\n        claims (dict): The claims dictionary to validate.\n        subject (str): The subject of the token."
  },
  {
    "code": "def get_days_off(transactions):\n    days_off = []\n    for trans in transactions:\n        date, action, _ = _parse_transaction_entry(trans)\n        if action == 'off':\n            days_off.append(date)\n    return days_off",
    "docstring": "Return the dates for any 'take day off' transactions."
  },
  {
    "code": "def rebin(self, factor):\n        if self.pilimage != None:\n            raise RuntimeError, \"Cannot rebin anymore, PIL image already exists !\"\n        if type(factor) != type(0):\n            raise RuntimeError, \"Rebin factor must be an integer !\"\n        if factor < 1:\n            return\n        origshape = np.asarray(self.numpyarray.shape)\n        neededshape = origshape - (origshape % factor)\n        if not (origshape == neededshape).all():\n            if self.verbose :\n                print \"Rebinning %ix%i : I have to crop from %s to %s\" % (factor, factor, origshape, neededshape)\n            self.crop(0, neededshape[0], 0, neededshape[1])\n        else:\n            if self.verbose :\n                print \"Rebinning %ix%i : I do not need to crop\" % (factor, factor)\n        self.numpyarray = rebin(self.numpyarray, neededshape/factor)\n        self.binfactor = int(self.binfactor * factor)",
    "docstring": "I robustly rebin your image by a given factor.\n        You simply specify a factor, and I will eventually take care of a crop to bring\n        the image to interger-multiple-of-your-factor dimensions.\n        Note that if you crop your image before, you must directly crop to compatible dimensions !\n        We update the binfactor, this allows you to draw on the image later, still using the\n        orignial pixel coordinates.\n        Here we work on the numpy array."
  },
  {
    "code": "def _exec_cmd(self, args, shell, timeout, stderr):\n        if timeout and timeout <= 0:\n            raise ValueError('Timeout is not a positive value: %s' % timeout)\n        try:\n            (ret, out, err) = utils.run_command(\n                args, shell=shell, timeout=timeout)\n        except psutil.TimeoutExpired:\n            raise AdbTimeoutError(\n                cmd=args, timeout=timeout, serial=self.serial)\n        if stderr:\n            stderr.write(err)\n        logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s',\n                      utils.cli_cmd_to_string(args), out, err, ret)\n        if ret == 0:\n            return out\n        else:\n            raise AdbError(\n                cmd=args,\n                stdout=out,\n                stderr=err,\n                ret_code=ret,\n                serial=self.serial)",
    "docstring": "Executes adb commands.\n\n        Args:\n            args: string or list of strings, program arguments.\n                See subprocess.Popen() documentation.\n            shell: bool, True to run this command through the system shell,\n                False to invoke it directly. See subprocess.Popen() docs.\n            timeout: float, the number of seconds to wait before timing out.\n                If not specified, no timeout takes effect.\n            stderr: a Byte stream, like io.BytesIO, stderr of the command will\n                be written to this object if provided.\n\n        Returns:\n            The output of the adb command run if exit code is 0.\n\n        Raises:\n            ValueError: timeout value is invalid.\n            AdbError: The adb command exit code is not 0.\n            AdbTimeoutError: The adb command timed out."
  },
  {
    "code": "def subscribers(self, date=\"\", page=1, page_size=1000, order_field=\"email\", order_direction=\"asc\", include_tracking_information=False):\n        params = {\n            \"date\": date,\n            \"page\": page,\n            \"pagesize\": page_size,\n            \"orderfield\": order_field,\n            \"orderdirection\": order_direction,\n            \"includetrackinginformation\": include_tracking_information\n        }\n        response = self._get(self.uri_for(\"active\"), params=params)\n        return json_to_py(response)",
    "docstring": "Gets the active subscribers in this segment."
  },
  {
    "code": "def dumps(obj, *args, **kwargs):\n    return json.dumps(obj, *args, cls=TypelessSONEncoder, ensure_ascii=False, **kwargs)",
    "docstring": "Typeless dump an object to json string"
  },
  {
    "code": "def add(user_id, resource_policy, admin, inactive,  rate_limit):\n    try:\n        user_id = int(user_id)\n    except ValueError:\n        pass\n    with Session() as session:\n        try:\n            data = session.KeyPair.create(\n                user_id,\n                is_active=not inactive,\n                is_admin=admin,\n                resource_policy=resource_policy,\n                rate_limit=rate_limit)\n        except Exception as e:\n            print_error(e)\n            sys.exit(1)\n        if not data['ok']:\n            print_fail('KeyPair creation has failed: {0}'.format(data['msg']))\n            sys.exit(1)\n        item = data['keypair']\n        print('Access Key: {0}'.format(item['access_key']))\n        print('Secret Key: {0}'.format(item['secret_key']))",
    "docstring": "Add a new keypair.\n\n    USER_ID: User ID of a new key pair.\n    RESOURCE_POLICY: resource policy for new key pair."
  },
  {
    "code": "def _reload_config(self, reload_original_config):\n        if reload_original_config:\n            self.original_config = self.running_config\n            self.original_config.set_name('original')\n        paths = self.running_config.get_paths()\n        self.running_config = FortiConfig('running', vdom=self.vdom)\n        for path in paths:\n            self.load_config(path, empty_candidate=True)",
    "docstring": "This command will update the running config from the live device.\n\n        Args:\n            * reload_original_config:\n                * If ``True`` the original config will be loaded with the running config before reloading the\\\n                original config.\n                * If ``False`` the original config will remain untouched."
  },
  {
    "code": "def get_relative_to_remote(self):\n        s = self.git(\"status\", \"--short\", \"-b\")[0]\n        r = re.compile(\"\\[([^\\]]+)\\]\")\n        toks = r.findall(s)\n        if toks:\n            try:\n                s2 = toks[-1]\n                adj, n = s2.split()\n                assert(adj in (\"ahead\", \"behind\"))\n                n = int(n)\n                return -n if adj == \"behind\" else n\n            except Exception as e:\n                raise ReleaseVCSError(\n                    (\"Problem parsing first line of result of 'git status \"\n                     \"--short -b' (%s):\\n%s\") % (s, str(e)))\n        else:\n            return 0",
    "docstring": "Return the number of commits we are relative to the remote. Negative\n        is behind, positive in front, zero means we are matched to remote."
  },
  {
    "code": "def _init():\n    if (hasattr(_local_context, '_initialized') and\n            _local_context._initialized == os.environ.get('REQUEST_ID_HASH')):\n        return\n    _local_context.registry = []\n    _local_context._executing_async_context = None\n    _local_context._executing_async = []\n    _local_context._initialized = os.environ.get('REQUEST_ID_HASH')\n    return _local_context",
    "docstring": "Initialize the furious context and registry.\n\n    NOTE: Do not directly run this method."
  },
  {
    "code": "def process_response(self, request, response):\n        if hasattr(request, 'COUNTRY_CODE'):\n            response.set_cookie(\n                key=constants.COUNTRY_COOKIE_NAME,\n                value=request.COUNTRY_CODE,\n                max_age=settings.LANGUAGE_COOKIE_AGE,\n                path=settings.LANGUAGE_COOKIE_PATH,\n                domain=settings.LANGUAGE_COOKIE_DOMAIN\n            )\n        return response",
    "docstring": "Shares config with the language cookie as they serve a similar purpose"
  },
  {
    "code": "def compute_qkv(query_antecedent,\n                memory_antecedent,\n                total_key_depth,\n                total_value_depth,\n                q_filter_width=1,\n                kv_filter_width=1,\n                q_padding=\"VALID\",\n                kv_padding=\"VALID\",\n                vars_3d_num_heads=0,\n                layer_collection=None):\n  if memory_antecedent is None:\n    memory_antecedent = query_antecedent\n  q = compute_attention_component(\n      query_antecedent,\n      total_key_depth,\n      q_filter_width,\n      q_padding,\n      \"q\",\n      vars_3d_num_heads=vars_3d_num_heads,\n      layer_collection=layer_collection)\n  k = compute_attention_component(\n      memory_antecedent,\n      total_key_depth,\n      kv_filter_width,\n      kv_padding,\n      \"k\",\n      vars_3d_num_heads=vars_3d_num_heads,\n      layer_collection=layer_collection)\n  v = compute_attention_component(\n      memory_antecedent,\n      total_value_depth,\n      kv_filter_width,\n      kv_padding,\n      \"v\",\n      vars_3d_num_heads=vars_3d_num_heads,\n      layer_collection=layer_collection)\n  return q, k, v",
    "docstring": "Computes query, key and value.\n\n  Args:\n    query_antecedent: a Tensor with shape [batch, length_q, channels]\n    memory_antecedent: a Tensor with shape [batch, length_m, channels]\n    total_key_depth: an integer\n    total_value_depth: an integer\n    q_filter_width: An integer specifying how wide you want the query to be.\n    kv_filter_width: An integer specifying how wide you want the keys and values\n    to be.\n    q_padding: One of \"VALID\", \"SAME\" or \"LEFT\". Default is VALID: No padding.\n    kv_padding: One of \"VALID\", \"SAME\" or \"LEFT\". Default is VALID: No padding.\n    vars_3d_num_heads: an optional (if we want to use 3d variables)\n    layer_collection: A tensorflow_kfac.LayerCollection. Only used by the\n      KFAC optimizer. Default is None.\n\n  Returns:\n    q, k, v : [batch, length, depth] tensors"
  },
  {
    "code": "def data(self):\n        content = {\n            'form_data': self.form_data,\n            'token': self.token,\n            'viz_name': self.viz_type,\n            'filter_select_enabled': self.datasource.filter_select_enabled,\n        }\n        return content",
    "docstring": "This is the data object serialized to the js layer"
  },
  {
    "code": "def log(self, time, message, level=None, attachment=None):\n        logger.debug(\"log queued\")\n        args = {\n            \"time\": time,\n            \"message\": message,\n            \"level\": level,\n            \"attachment\": attachment,\n        }\n        self.queue.put_nowait((\"log\", args))",
    "docstring": "Logs a message with attachment.\n\n        The attachment is a dict of:\n            name: name of attachment\n            data: file content\n            mime: content type for attachment"
  },
  {
    "code": "def check_in_out_dates(self):\n        if self.checkout and self.checkin:\n            if self.checkin < self.date_order:\n                raise ValidationError(_('Check-in date should be greater than \\\n                                         the current date.'))\n            if self.checkout < self.checkin:\n                raise ValidationError(_('Check-out date should be greater \\\n                                         than Check-in date.'))",
    "docstring": "When date_order is less then check-in date or\n        Checkout date should be greater than the check-in date."
  },
  {
    "code": "def get_sdb_by_id(self, sdb_id):\n        sdb_resp = get_with_retry(self.cerberus_url + '/v2/safe-deposit-box/' + sdb_id,\n                                headers=self.HEADERS)\n        throw_if_bad_response(sdb_resp)\n        return sdb_resp.json()",
    "docstring": "Return the details for the given safe deposit box id\n\n        Keyword arguments:\n        sdb_id -- this is the id of the safe deposit box, not the path."
  },
  {
    "code": "def flatten(self, df, column_name):\n        _exp_list = [[md5, x] for md5, value_list in zip(df['md5'], df[column_name]) for x in value_list]\n        return pd.DataFrame(_exp_list, columns=['md5',column_name])",
    "docstring": "Flatten a column in the dataframe that contains lists"
  },
  {
    "code": "def interact_GxG(pheno,snps1,snps2=None,K=None,covs=None):\n    if K is None:\n        K=SP.eye(N)\n    N=snps1.shape[0]\n    if snps2 is None:\n        snps2 = snps1\n    return interact_GxE(snps=snps1,pheno=pheno,env=snps2,covs=covs,K=K)",
    "docstring": "Epistasis test between two sets of SNPs\n\n    Args:\n        pheno:  [N x 1] SP.array of 1 phenotype for N individuals\n        snps1:  [N x S1] SP.array of S1 SNPs for N individuals\n        snps2:  [N x S2] SP.array of S2 SNPs for N individuals\n        K:      [N x N] SP.array of LMM-covariance/kinship koefficients (optional)\n                        If not provided, then linear regression analysis is performed\n        covs:   [N x D] SP.array of D covariates for N individuals\n\n    Returns:\n        pv:     [S2 x S1] SP.array of P values for epistasis tests beten all SNPs in\n                snps1 and snps2"
  },
  {
    "code": "def add_device_net(self, name, destname=None):\n        if not self.running:\n            return False\n        if os.path.exists(\"/sys/class/net/%s/phy80211/name\" % name):\n            with open(\"/sys/class/net/%s/phy80211/name\" % name) as fd:\n                phy = fd.read().strip()\n            if subprocess.call(['iw', 'phy', phy, 'set', 'netns',\n                                str(self.init_pid)]) != 0:\n                return False\n            if destname:\n                def rename_interface(args):\n                    old, new = args\n                    return subprocess.call(['ip', 'link', 'set',\n                                            'dev', old, 'name', new])\n                return self.attach_wait(rename_interface, (name, destname),\n                                        namespaces=(CLONE_NEWNET)) == 0\n            return True\n        if not destname:\n            destname = name\n        if not os.path.exists(\"/sys/class/net/%s/\" % name):\n            return False\n        return subprocess.call(['ip', 'link', 'set',\n                                'dev', name,\n                                'netns', str(self.init_pid),\n                                'name', destname]) == 0",
    "docstring": "Add network device to running container."
  },
  {
    "code": "def operations_happening_at_same_time_as(\n        self, scheduled_operation: ScheduledOperation\n    ) -> List[ScheduledOperation]:\n        overlaps = self.query(\n            time=scheduled_operation.time,\n            duration=scheduled_operation.duration)\n        return [e for e in overlaps if e != scheduled_operation]",
    "docstring": "Finds operations happening at the same time as the given operation.\n\n        Args:\n            scheduled_operation: The operation specifying the time to query.\n\n        Returns:\n            Scheduled operations that overlap with the given operation."
  },
  {
    "code": "def resolve_widget(self, field):\n        if hasattr(field, 'field'):\n            widget = field.field.widget\n        else:\n            widget = field.widget\n        return widget",
    "docstring": "Given a Field or BoundField, return widget instance.\n\n        Todo:\n            Raise an exception if given field object does not have a\n            widget.\n\n        Arguments:\n            field (Field or BoundField): A field instance.\n\n        Returns:\n            django.forms.widgets.Widget: Retrieved widget from given field."
  },
  {
    "code": "def jdn_to_gdate(jdn):\n    l = jdn + 68569\n    n = (4 * l) // 146097\n    l = l - (146097 * n + 3) // 4\n    i = (4000 * (l + 1)) // 1461001\n    l = l - (1461 * i) // 4 + 31\n    j = (80 * l) // 2447\n    day = l - (2447 * j) // 80\n    l = j // 11\n    month = j + 2 - (12 * l)\n    year = 100 * (n - 49) + i + l\n    return datetime.date(year, month, day)",
    "docstring": "Convert from the Julian day to the Gregorian day.\n\n    Algorithm from 'Julian and Gregorian Day Numbers' by Peter Meyer.\n    Return: day, month, year"
  },
  {
    "code": "def order(self, order):\n        given = self.given\n        surname = self.surname\n        if order in (ORDER_MAIDEN_GIVEN, ORDER_GIVEN_MAIDEN):\n            surname = self.maiden or self.surname\n        given = (\"1\" + given) if given else \"2\"\n        surname = (\"1\" + surname) if surname else \"2\"\n        if order in (ORDER_SURNAME_GIVEN, ORDER_MAIDEN_GIVEN):\n            return (surname, given)\n        elif order in (ORDER_GIVEN_SURNAME, ORDER_GIVEN_MAIDEN):\n            return (given, surname)\n        else:\n            raise ValueError(\"unexpected order: {}\".format(order))",
    "docstring": "Returns name order key.\n\n        Returns tuple with two strings that can be compared to other such\n        tuple obtained from different name. Note that if you want\n        locale-dependent ordering then you need to compare strings using\n        locale-aware method (e.g. ``locale.strxfrm``).\n\n        :param order: One of the ORDER_* constants.\n        :returns: tuple of two strings"
  },
  {
    "code": "def to_json(self):\n        return {\n            'wind_speed': self.wind_speed,\n            'wind_direction': self.wind_direction,\n            'rain': self.rain,\n            'snow_on_ground': self.snow_on_ground\n        }",
    "docstring": "Convert the Wind Condition to a dictionary."
  },
  {
    "code": "def get_patient_vcf(job, patient_dict):\n    temp = job.fileStore.readGlobalFile(patient_dict['mutation_vcf'],\n                                        os.path.join(os.getcwd(), 'temp.gz'))\n    if is_gzipfile(temp):\n        outfile = job.fileStore.writeGlobalFile(gunzip(temp))\n        job.fileStore.deleteGlobalFile(patient_dict['mutation_vcf'])\n    else:\n        outfile = patient_dict['mutation_vcf']\n    return outfile",
    "docstring": "Convenience function to get the vcf from the patient dict\n\n    :param dict patient_dict: dict of patient info\n    :return: The vcf\n    :rtype: toil.fileStore.FileID"
  },
  {
    "code": "def datetime_to_time(date, time):\n    if (255 in date) or (255 in time):\n        raise RuntimeError(\"specific date and time required\")\n    time_tuple = (\n        date[0]+1900, date[1], date[2],\n        time[0], time[1], time[2],\n        0, 0, -1,\n        )\n    return _mktime(time_tuple)",
    "docstring": "Take the date and time 4-tuples and return the time in seconds since\n    the epoch as a floating point number."
  },
  {
    "code": "def add_service_spec(self, service_spec):\n        assert service_spec is not None\n        if service_spec.name in self.service_specs:\n            raise ThriftCompilerError(\n                'Cannot define service \"%s\". That name is already taken.'\n                % service_spec.name\n            )\n        self.service_specs[service_spec.name] = service_spec",
    "docstring": "Registers the given ``ServiceSpec`` into the scope.\n\n        Raises ``ThriftCompilerError`` if the name has already been used."
  },
  {
    "code": "def process_documentline(line, nanopubs_metadata):\n    matches = re.match('SET DOCUMENT\\s+(\\w+)\\s+=\\s+\"?(.*?)\"?$', line)\n    key = matches.group(1)\n    val = matches.group(2)\n    nanopubs_metadata[key] = val\n    return nanopubs_metadata",
    "docstring": "Process SET DOCUMENT line in BEL script"
  },
  {
    "code": "def delete_role_policy(role_name, policy_name, region=None, key=None,\n                       keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile)\n    if not _policy:\n        return True\n    try:\n        conn.delete_role_policy(role_name, policy_name)\n        log.info('Successfully deleted policy %s for IAM role %s.',\n                 policy_name, role_name)\n        return True\n    except boto.exception.BotoServerError as e:\n        log.debug(e)\n        log.error('Failed to delete policy %s for IAM role %s.',\n                  policy_name, role_name)\n        return False",
    "docstring": "Delete a role policy.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_iam.delete_role_policy myirole mypolicy"
  },
  {
    "code": "def expand_uri(self, **kwargs):\n        kwargs = dict([(k, v if v != 0 else '0') for k, v in kwargs.items()])\n        return uritemplate.expand(self.link.uri, kwargs)",
    "docstring": "Returns the template uri expanded with the current arguments"
  },
  {
    "code": "def from_key(api_key, **kwargs):\n    h = Heroku(**kwargs)\n    h.authenticate(api_key)\n    return h",
    "docstring": "Returns an authenticated Heroku instance, via API Key."
  },
  {
    "code": "def addConcept(self, conceptUri, weight, label = None, conceptType = None):\n        assert isinstance(weight, (float, int)), \"weight value has to be a positive or negative integer\"\n        concept = {\"uri\": conceptUri, \"wgt\": weight}\n        if label != None: concept[\"label\"] = label\n        if conceptType != None: concept[\"type\"] = conceptType\n        self.topicPage[\"concepts\"].append(concept)",
    "docstring": "add a relevant concept to the topic page\n        @param conceptUri: uri of the concept to be added\n        @param weight: importance of the provided concept (typically in range 1 - 50)"
  },
  {
    "code": "def get_deposit_address(self, currency):\n        self._validate_currency(currency)\n        self._log('get deposit address for {}'.format(currency))\n        coin_name = self.major_currencies[currency]\n        return self._rest_client.post(\n            endpoint='/{}_deposit_address'.format(coin_name)\n        )",
    "docstring": "Return the deposit address for the given major currency.\n\n        :param currency: Major currency name in lowercase (e.g. \"btc\", \"eth\").\n        :type currency: str | unicode\n        :return: Deposit address.\n        :rtype: str | unicode"
  },
  {
    "code": "def _json_body_(cls):\n        json = []\n        for series_name, data in six.iteritems(cls._datapoints):\n            for point in data:\n                json_point = {\n                    \"measurement\": series_name,\n                    \"fields\": {},\n                    \"tags\": {},\n                    \"time\": getattr(point, \"time\")\n                }\n                for field in cls._fields:\n                    value = getattr(point, field)\n                    if value is not None:\n                        json_point['fields'][field] = value\n                for tag in cls._tags:\n                    json_point['tags'][tag] = getattr(point, tag)\n                json.append(json_point)\n        return json",
    "docstring": "Return the JSON body of given datapoints.\n\n        :return: JSON body of these datapoints."
  },
  {
    "code": "def session_commit(self, session):\n        if not hasattr(session, 'meepo_unique_id'):\n            self.logger.debug(\"skipped - session_commit\")\n            return\n        self.logger.debug(\"%s - session_commit\" % session.meepo_unique_id)\n        self._session_pub(session)\n        signal(\"session_commit\").send(session)\n        self._session_del(session)",
    "docstring": "Send session_commit signal in sqlalchemy ``before_commit``.\n\n        This marks the success of session so the session may enter commit\n        state."
  },
  {
    "code": "def register_admin(app, admin):\n    category = 'Knowledge'\n    admin.category_icon_classes[category] = \"fa fa-mortar-board\"\n    admin.add_view(\n        KnowledgeAdmin(app, KnwKB, db.session,\n                       name='Knowledge Base', category=category,\n                       endpoint=\"kb\")\n    )\n    admin.add_view(\n        KnwKBRVALAdmin(app, KnwKBRVAL, db.session,\n                       name=\"Knowledge Mappings\", category=category,\n                       endpoint=\"kbrval\")\n    )",
    "docstring": "Called on app initialization to register administration interface."
  },
  {
    "code": "def convert(self, imtls, nsites, idx=0):\n        curves = numpy.zeros(nsites, imtls.dt)\n        for imt in curves.dtype.names:\n            curves_by_imt = curves[imt]\n            for sid in self:\n                curves_by_imt[sid] = self[sid].array[imtls(imt), idx]\n        return curves",
    "docstring": "Convert a probability map into a composite array of length `nsites`\n        and dtype `imtls.dt`.\n\n        :param imtls:\n            DictArray instance\n        :param nsites:\n            the total number of sites\n        :param idx:\n            index on the z-axis (default 0)"
  },
  {
    "code": "def change_profile(self, profile_name):\n        self._server_side_completer = self._create_server_side_completer(\n            session=botocore.session.Session(profile=profile_name))",
    "docstring": "Change the profile used for server side completions."
  },
  {
    "code": "def sortBy(self, val=None):\n        if val is not None:\n            if _(val).isString():\n                return self._wrap(sorted(self.obj, key=lambda x,\n                                  *args: x.get(val)))\n            else:\n                return self._wrap(sorted(self.obj, key=val))\n        else:\n            return self._wrap(sorted(self.obj))",
    "docstring": "Sort the object's values by a criterion produced by an iterator."
  },
  {
    "code": "def compose(*funcs):\n    return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x)",
    "docstring": "compose a list of functions"
  },
  {
    "code": "def info(args):\n    \" Show information about site. \"\n    site = find_site(args.PATH)\n    print_header(\"%s -- install information\" % site.get_name())\n    LOGGER.debug(site.get_info(full=True))\n    return True",
    "docstring": "Show information about site."
  },
  {
    "code": "def register(self, intent):\n        response = self.api.post_intent(intent.serialize)\n        print(response)\n        print()\n        if response['status']['code'] == 200:\n            intent.id = response['id']\n        elif response['status']['code'] == 409:\n            intent.id = next(i.id for i in self.api.agent_intents if i.name == intent.name)\n            self.update(intent)\n        return intent",
    "docstring": "Registers a new intent and returns the Intent object with an ID"
  },
  {
    "code": "def set_cell(self, index, value):\n        if self._sort:\n            exists, i = sorted_exists(self._index, index)\n            if not exists:\n                self._insert_row(i, index)\n        else:\n            try:\n                i = self._index.index(index)\n            except ValueError:\n                i = len(self._index)\n                self._add_row(index)\n        self._data[i] = value",
    "docstring": "Sets the value of a single cell. If the index is not in the current index then a new index will be created.\n\n        :param index: index value\n        :param value: value to set\n        :return: nothing"
  },
  {
    "code": "def build(self, shutit):\n\t\tif shutit.build['delivery'] in ('docker','dockerfile'):\n\t\t\tif shutit.get_current_shutit_pexpect_session_environment().install_type == 'apt':\n\t\t\t\tshutit.add_to_bashrc('export DEBIAN_FRONTEND=noninteractive')\n\t\t\t\tif not shutit.command_available('lsb_release'):\n\t\t\t\t\tshutit.install('lsb-release')\n\t\t\t\tshutit.lsb_release()\n\t\t\telif shutit.get_current_shutit_pexpect_session_environment().install_type == 'yum':\n\t\t\t\tshutit.send('yum update -y', timeout=9999, exit_values=['0', '1'])\n\t\t\tshutit.pause_point('Anything you want to do to the target host ' + 'before the build starts?', level=2)\n\t\treturn True",
    "docstring": "Initializes target ready for build and updating package management if in container."
  },
  {
    "code": "def url(self, **kwargs):\n        url = self.fields(self._locale()).get('file', {}).get('url', '')\n        args = ['{0}={1}'.format(k, v) for k, v in kwargs.items()]\n        if args:\n            url += '?{0}'.format('&'.join(args))\n        return url",
    "docstring": "Returns a formatted URL for the asset's File\n        with serialized parameters.\n\n        Usage:\n            >>> my_asset.url()\n            \"//images.contentful.com/spaces/foobar/...\"\n            >>> my_asset.url(w=120, h=160)\n            \"//images.contentful.com/spaces/foobar/...?w=120&h=160\""
  },
  {
    "code": "def _validate_integer(name, val, min_val=0):\n    msg = \"'{name:s}' must be an integer >={min_val:d}\".format(name=name,\n                                                               min_val=min_val)\n    if val is not None:\n        if is_float(val):\n            if int(val) != val:\n                raise ValueError(msg)\n            val = int(val)\n        elif not (is_integer(val) and val >= min_val):\n            raise ValueError(msg)\n    return val",
    "docstring": "Checks whether the 'name' parameter for parsing is either\n    an integer OR float that can SAFELY be cast to an integer\n    without losing accuracy. Raises a ValueError if that is\n    not the case.\n\n    Parameters\n    ----------\n    name : string\n        Parameter name (used for error reporting)\n    val : int or float\n        The value to check\n    min_val : int\n        Minimum allowed value (val < min_val will result in a ValueError)"
  },
  {
    "code": "def multiple_sequence_alignment(seqs_fp, threads=1):\n    logger = logging.getLogger(__name__)\n    logger.info('multiple_sequence_alignment seqs file %s' % seqs_fp)\n    if threads == 0:\n        threads = -1\n    if stat(seqs_fp).st_size == 0:\n        logger.warning('msa failed. file %s has no reads' % seqs_fp)\n        return None\n    msa_fp = seqs_fp + '.msa'\n    params = ['mafft', '--quiet', '--preservecase', '--parttree', '--auto',\n              '--thread', str(threads), seqs_fp]\n    sout, serr, res = _system_call(params, stdoutfilename=msa_fp)\n    if not res == 0:\n        logger.info('msa failed for file %s (maybe only 1 read?)' % seqs_fp)\n        logger.debug('stderr : %s' % serr)\n        return None\n    return msa_fp",
    "docstring": "Perform multiple sequence alignment on FASTA file using MAFFT.\n\n    Parameters\n    ----------\n    seqs_fp: string\n        filepath to FASTA file for multiple sequence alignment\n    threads: integer, optional\n        number of threads to use. 0 to use all threads\n\n    Returns\n    -------\n    msa_fp : str\n        name of output alignment file or None if error encountered"
  },
  {
    "code": "def delete_user(name, runas=None):\n    if runas is None and not salt.utils.platform.is_windows():\n        runas = salt.utils.user.get_user()\n    res = __salt__['cmd.run_all'](\n        [RABBITMQCTL, 'delete_user', name],\n        reset_system_locale=False,\n        python_shell=False,\n        runas=runas)\n    msg = 'Deleted'\n    return _format_response(res, msg)",
    "docstring": "Deletes a user via rabbitmqctl delete_user.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rabbitmq.delete_user rabbit_user"
  },
  {
    "code": "def md5(self):\n        target = '{}{}'.format(\n            util.md5_object(bytes().join(e._bytes()\n                                         for e in self.entities)),\n            self.vertices.md5())\n        return target",
    "docstring": "An MD5 hash of the current vertices and entities.\n\n        Returns\n        ------------\n        md5: str, two appended MD5 hashes"
  },
  {
    "code": "def load_from_file(cls, file_path: str):\n        with open(file_path, \"r\") as f:\n            data = json.load(f)\n            item = cls.decode(data=data)\n        return item",
    "docstring": "Read and reconstruct the data from a JSON file."
  },
  {
    "code": "def returnPorts(self):\n        if self._gotPorts:\n            map(portpicker.return_port, self.ports)\n            self._gotPorts = False\n        self.ports = []",
    "docstring": "deallocate specific ports on the current machine"
  },
  {
    "code": "def _format_executable(lines, element, spacer=\"\"):\n    rlines = []\n    rlines.append(element.signature)\n    _format_summary(rlines, element)\n    rlines.append(\"\")\n    rlines.append(\"PARAMETERS\")\n    for p in element.ordered_parameters:\n        _format_value_element(rlines, p)\n    rlines.append(\"\")\n    _format_generic(rlines, element, [\"summary\"])\n    if len(element.types) > 0:\n        rlines.append(\"\\nEMBEDDED TYPES\")\n        for key, value in list(element.types.items()):\n            _format_type(rlines, value, \"  \")\n    if len(element.executables) > 0:\n        rlines.append(\"\\nEMBEDDED EXECUTABLES\")\n        for key, value in list(element.executables.items()):\n            _format_executable(rlines, value, \"  \")\n    lines.extend([spacer + l for l in rlines])",
    "docstring": "Performs formatting specific to a Subroutine or Function code\n    element for relevant docstrings."
  },
  {
    "code": "def run(self):\n        self.tap = Quartz.CGEventTapCreate(\n            Quartz.kCGSessionEventTap,\n            Quartz.kCGHeadInsertEventTap,\n            Quartz.kCGEventTapOptionDefault,\n            Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) |\n            Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp) |\n            Quartz.CGEventMaskBit(Quartz.kCGEventFlagsChanged),\n            self.handler,\n            None)\n        loopsource = Quartz.CFMachPortCreateRunLoopSource(None, self.tap, 0)\n        loop = Quartz.CFRunLoopGetCurrent()\n        Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode)\n        Quartz.CGEventTapEnable(self.tap, True)\n        while self.listening:\n            Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False)",
    "docstring": "Creates a listener and loops while waiting for an event. Intended to run as\n        a background thread."
  },
  {
    "code": "def get_node_instances(nodelist, instances):\n    context = _get_main_context(nodelist)\n    if TemplateAdapter is not None and isinstance(nodelist, TemplateAdapter):\n        nodelist = nodelist.template\n    return _scan_nodes(nodelist, context, instances)",
    "docstring": "Find the nodes of a given instance.\n\n    In contract to the standard ``template.nodelist.get_nodes_by_type()`` method,\n    this also looks into ``{% extends %}`` and ``{% include .. %}`` nodes\n    to find all possible nodes of the given type.\n\n    :param instances: A class Type, or tuple of types to find.\n    :param nodelist:  The Template object, or nodelist to scan.\n    :returns: A list of Node objects which inherit from the list of given `instances` to find.\n    :rtype: list"
  },
  {
    "code": "def _convert_nonstring_categoricals(self, param_dict):\n        return {name: (self.categorical_mappings_[name][val] if name in self.categorical_mappings_ else val)\n                for (name, val) in param_dict.items()}",
    "docstring": "Apply the self.categorical_mappings_ mappings where necessary."
  },
  {
    "code": "def beta_pdf(x, a, b):\n  bc = 1 / beta(a, b)\n  fc = x ** (a - 1)\n  sc = (1 - x) ** (b - 1)\n  return bc * fc * sc",
    "docstring": "Beta distirbution probability density function."
  },
  {
    "code": "def event_return(events):\n    with _get_serv(events, commit=True) as cur:\n        for event in events:\n            tag = event.get('tag', '')\n            data = event.get('data', '')\n            sql =\n            cur.execute(sql, (tag, psycopg2.extras.Json(data),\n                              __opts__['id'], time.time()))",
    "docstring": "Return event to Pg server\n\n    Requires that configuration be enabled via 'event_return'\n    option in master config."
  },
  {
    "code": "def draw(self, gdefs, theme):\n        for g in gdefs:\n            g.theme = theme\n            g._set_defaults()\n        return [g.draw() for g in gdefs]",
    "docstring": "Draw out each guide definition\n\n        Parameters\n        ----------\n        gdefs : list of guide_legend|guide_colorbar\n            guide definitions\n        theme : theme\n            Plot theme\n\n        Returns\n        -------\n        out : list of matplotlib.offsetbox.Offsetbox\n            A drawing of each legend"
  },
  {
    "code": "def get_free_port(ports=None):\n    if ports is None:\n        with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as _socket:\n            _socket.bind(('', 0))\n            _, port = _socket.getsockname()\n            return port\n    for port in ports:\n        with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as _socket:\n            try:\n                _socket.bind(('', port))\n                return port\n            except socket.error as ex:\n                if ex.errno not in (48, 98):\n                    raise\n    raise RuntimeError(\"could not find a free port\")",
    "docstring": "Get a free port.\n\n    Parameters\n    ----------\n    ports : iterable\n        ports to check (obtain a random port by default)\n\n    Returns\n    -------\n    port : int\n        a free port"
  },
  {
    "code": "def run(\n    paths,\n    output=_I_STILL_HATE_EVERYTHING,\n    recurse=core.flat,\n    sort_by=None,\n    ls=core.ls,\n    stdout=stdout,\n):\n    if output is _I_STILL_HATE_EVERYTHING:\n        output = core.columnized if stdout.isatty() else core.one_per_line\n    if sort_by is None:\n        if output == core.as_tree:\n            def sort_by(thing):\n                return (\n                    thing.parent(),\n                    thing.basename().lstrip(string.punctuation).lower(),\n                )\n        else:\n            def sort_by(thing):\n                return thing\n    def _sort_by(thing):\n        return not getattr(thing, \"_always_sorts_first\", False), sort_by(thing)\n    contents = [\n        path_and_children\n        for path in paths or (project.from_path(FilePath(\".\")),)\n        for path_and_children in recurse(path=path, ls=ls)\n    ]\n    for line in output(contents, sort_by=_sort_by):\n        stdout.write(line)\n        stdout.write(\"\\n\")",
    "docstring": "Project-oriented directory and file information lister."
  },
  {
    "code": "def _find_files(self):\n        files = []\n        for ext in self.extensions:\n            ext_files = util.find_files(self.root, \"*\" + ext)\n            log.debug(\"found {} '*{}' files in '{}'\".format(\n                len(ext_files), ext, self.root)\n            )\n            files.extend(ext_files)\n        return files",
    "docstring": "Find files recursively in the root path\n        using provided extensions.\n\n        :return: list of absolute file paths"
  },
  {
    "code": "def _function_add_return_edge(self, return_from_addr, return_to_addr, function_addr):\n        return_to_node = self._nodes.get(return_to_addr, None)\n        if return_to_node is None:\n            return_to_snippet = self._to_snippet(addr=return_to_addr, base_state=self._base_state)\n            to_outside = False\n        else:\n            return_to_snippet = self._to_snippet(cfg_node=return_to_node)\n            to_outside = return_to_node.function_address != function_addr\n        self.kb.functions._add_return_from_call(function_addr, return_from_addr, return_to_snippet,\n                                                to_outside=to_outside)",
    "docstring": "Generate CodeNodes for return_to_addr, add this node for function to\n        function manager generating new edge\n\n        :param int return_from_addr: target address\n        :param int return_to_addr: target address\n        :param int function_addr: address of function\n        :return: None"
  },
  {
    "code": "def commit(self):\n        assert self.batch is not None, \"No active batch, call start() first\"\n        logger.debug(\"Comitting batch from %d sources...\", len(self.batch))\n        by_priority = []\n        for name in self.batch.keys():\n            priority = self.priorities.get(name, self.default_priority)\n            by_priority.append((priority, name))\n        for priority, name in sorted(by_priority, key=lambda key: key[0]):\n            logger.debug(\"Processing items from '%s' (priority=%d)...\", name, priority)\n            items = self.batch[name]\n            for handlers in items.values():\n                for agg, handler in handlers:\n                    try:\n                        if agg is None:\n                            handler()\n                        else:\n                            handler(agg)\n                    except Exception as error:\n                        logger.exception(\"Error while invoking handler.\")\n        self.batch = None\n        logger.debug(\"Batch committed.\")",
    "docstring": "Commit a batch."
  },
  {
    "code": "def get_file_hash(file_path, block_size=1024, hasher=None):\n    if hasher is None:\n        hasher = hashlib.md5()\n    with open(file_path, 'rb') as f:\n        while True:\n            buffer = f.read(block_size)\n            if len(buffer) <= 0:\n                break\n            hasher.update(buffer)\n    return hasher.hexdigest()",
    "docstring": "Generate hash for given file\n\n    :param file_path: Path to file\n    :type file_path: str\n    :param block_size: Size of block to be read at once (default: 1024)\n    :type block_size: int\n    :param hasher: Use specific hasher, defaults to md5 (default: None)\n    :type hasher: _hashlib.HASH\n    :return: Hash of file\n    :rtype: str"
  },
  {
    "code": "def is_ini_file(filename, show_warnings = False):\n    try:\n        config_dict = load_config(filename, file_type = \"ini\")\n        if config_dict == {}:\n            is_ini = False\n        else:\n            is_ini = True\n    except:\n        is_ini = False\n    return(is_ini)",
    "docstring": "Check configuration file type is INI\n    Return a boolean indicating wheather the file is INI format or not"
  },
  {
    "code": "def _is_finished(self, as_of):\n        if self.is_one_off():\n            last_billing_cycle = self.get_billing_cycles()[self.total_billing_cycles - 1]\n            return last_billing_cycle.date_range.upper <= as_of\n        else:\n            return False",
    "docstring": "Have the specified number of billing cycles been completed?\n\n        If so, we should not be enacting this RecurringCost."
  },
  {
    "code": "def claim_keys(self, key_request, timeout=None):\n        content = {\"one_time_keys\": key_request}\n        if timeout:\n            content[\"timeout\"] = timeout\n        return self._send(\"POST\", \"/keys/claim\", content=content)",
    "docstring": "Claims one-time keys for use in pre-key messages.\n\n        Args:\n            key_request (dict): The keys to be claimed. Format should be\n                <user_id>: { <device_id>: <algorithm> }.\n            timeout (int): Optional. The time (in milliseconds) to wait when\n                downloading keys from remote servers."
  },
  {
    "code": "def save(self, entity):\n        assert isinstance(entity, Entity), \" entity must have an instance of Entity\"\n        return self.__collection.save(entity.as_dict())",
    "docstring": "Maps entity to dict and returns future"
  },
  {
    "code": "def get_column(column_name, node, context):\n    column = try_get_column(column_name, node, context)\n    if column is None:\n        selectable = get_node_selectable(node, context)\n        raise AssertionError(\n            u'Column \"{}\" not found in selectable \"{}\". Columns present are {}. '\n            u'Context is {}.'.format(column_name, selectable.original,\n                                     [col.name for col in selectable.c], context))\n    return column",
    "docstring": "Get a column by name from the selectable.\n\n    Args:\n        column_name: str, name of the column to retrieve.\n        node: SqlNode, the node the column is being retrieved for.\n        context: CompilationContext, compilation specific metadata.\n\n    Returns:\n        column, the SQLAlchemy column if found. Raises an AssertionError otherwise."
  },
  {
    "code": "def remove(env, securitygroup_id, rule_id):\n    mgr = SoftLayer.NetworkManager(env.client)\n    ret = mgr.remove_securitygroup_rule(securitygroup_id, rule_id)\n    if not ret:\n        raise exceptions.CLIAbort(\"Failed to remove security group rule\")\n    table = formatting.Table(REQUEST_BOOL_COLUMNS)\n    table.add_row([ret['requestId']])\n    env.fout(table)",
    "docstring": "Remove a rule from a security group."
  },
  {
    "code": "def clear(self, username, project):\n        method = 'DELETE'\n        url = ('/project/{username}/{project}/build-cache?'\n               'circle-token={token}'.format(username=username,\n                                             project=project,\n                                             token=self.client.api_token))\n        json_data = self.client.request(method, url)\n        return json_data",
    "docstring": "Clear the cache for given project."
  },
  {
    "code": "def render_pdf_file_to_image_files__ghostscript_png(pdf_file_name,\n                                                    root_output_file_path,\n                                                    res_x=150, res_y=150):\n    if not gs_executable: init_and_test_gs_executable(exit_on_fail=True)\n    command = [gs_executable, \"-dBATCH\", \"-dNOPAUSE\", \"-sDEVICE=pnggray\",\n               \"-r\"+res_x+\"x\"+res_y, \"-sOutputFile=\"+root_output_file_path+\"-%06d.png\",\n               pdf_file_name]\n    comm_output = get_external_subprocess_output(command, env=gs_environment)\n    return comm_output",
    "docstring": "Use Ghostscript to render a PDF file to .png images.  The root_output_file_path\n    is prepended to all the output files, which have numbers and extensions added.\n    Return the command output."
  },
  {
    "code": "def lspcn(body, et, abcorr):\n    body = stypes.stringToCharP(body)\n    et = ctypes.c_double(et)\n    abcorr = stypes.stringToCharP(abcorr)\n    return libspice.lspcn_c(body, et, abcorr)",
    "docstring": "Compute L_s, the planetocentric longitude of the sun, as seen\n    from a specified body.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lspcn_c.html\n\n    :param body: Name of central body.\n    :type body: str\n    :param et: Epoch in seconds past J2000 TDB.\n    :type et: float\n    :param abcorr: Aberration correction.\n    :type abcorr: str\n    :return: planetocentric longitude of the sun\n    :rtype: float"
  },
  {
    "code": "def get(self, s3_path, destination_local_path):\n        (bucket, key) = self._path_to_bucket_and_key(s3_path)\n        self.s3.meta.client.download_file(bucket, key, destination_local_path)",
    "docstring": "Get an object stored in S3 and write it to a local path."
  },
  {
    "code": "def get_new_ip(self):\n        attempts = 0\n        while True:\n            if attempts == self.new_ip_max_attempts:\n                raise TorIpError(\"Failed to obtain a new usable Tor IP\")\n            attempts += 1\n            try:\n                current_ip = self.get_current_ip()\n            except (RequestException, TorIpError):\n                self._obtain_new_ip()\n                continue\n            if not self._ip_is_usable(current_ip):\n                self._obtain_new_ip()\n                continue\n            self._manage_used_ips(current_ip)\n            break\n        return current_ip",
    "docstring": "Try to obtain new a usable TOR IP.\n\n        :returns bool\n        :raises TorIpError"
  },
  {
    "code": "def edit(community):\n    form = EditCommunityForm(formdata=request.values, obj=community)\n    deleteform = DeleteCommunityForm()\n    ctx = mycommunities_ctx()\n    ctx.update({\n        'form': form,\n        'is_new': False,\n        'community': community,\n        'deleteform': deleteform,\n    })\n    if form.validate_on_submit():\n        for field, val in form.data.items():\n            setattr(community, field, val)\n        file = request.files.get('logo', None)\n        if file:\n            if not community.save_logo(file.stream, file.filename):\n                form.logo.errors.append(_(\n                    'Cannot add this file as a logo. Supported formats: '\n                    'PNG, JPG and SVG. Max file size: 1.5 MB.'))\n        if not form.logo.errors:\n            db.session.commit()\n            flash(\"Community successfully edited.\", category='success')\n            return redirect(url_for('.edit', community_id=community.id))\n    return render_template(\n        current_app.config['COMMUNITIES_EDIT_TEMPLATE'],\n        **ctx\n    )",
    "docstring": "Create or edit a community."
  },
  {
    "code": "def getcomments(self):\n        comment_list = self.bugzilla.get_comments([self.bug_id])\n        return comment_list['bugs'][str(self.bug_id)]['comments']",
    "docstring": "Returns an array of comment dictionaries for this bug"
  },
  {
    "code": "def worklogs(self, issue):\n        r_json = self._get_json('issue/' + str(issue) + '/worklog')\n        worklogs = [Worklog(self._options, self._session, raw_worklog_json)\n                    for raw_worklog_json in r_json['worklogs']]\n        return worklogs",
    "docstring": "Get a list of worklog Resources from the server for an issue.\n\n        :param issue: ID or key of the issue to get worklogs from\n        :rtype: List[Worklog]"
  },
  {
    "code": "def delete(self, key_id=None):\n        url = self.bitbucket.url('DELETE_SSH_KEY', key_id=key_id)\n        return self.bitbucket.dispatch('DELETE', url, auth=self.bitbucket.auth)",
    "docstring": "Delete one of the ssh keys associated with your account.\n            Please use with caution as there is NO confimation and NO undo."
  },
  {
    "code": "def is_answer_valid(self, ans):\n        return ans in [str(i+1) for i in range(len(self.choices))]",
    "docstring": "Validate user's answer against available choices."
  },
  {
    "code": "def mode(self, mode):\n        _LOGGER.debug(\"Setting new mode: %s\", mode)\n        if self.mode == Mode.Boost and mode != Mode.Boost:\n            self.boost = False\n        if mode == Mode.Boost:\n            self.boost = True\n            return\n        elif mode == Mode.Away:\n            end = datetime.now() + self._away_duration\n            return self.set_away(end, self._away_temp)\n        elif mode == Mode.Closed:\n            return self.set_mode(0x40 | int(EQ3BT_OFF_TEMP * 2))\n        elif mode == Mode.Open:\n            return self.set_mode(0x40 | int(EQ3BT_ON_TEMP * 2))\n        if mode == Mode.Manual:\n            temperature = max(min(self._target_temperature, self.max_temp),\n                              self.min_temp)\n            return self.set_mode(0x40 | int(temperature * 2))\n        else:\n            return self.set_mode(0)",
    "docstring": "Set the operation mode."
  },
  {
    "code": "def corr(self):\r\n        cov = self.cov()\r\n        N = cov.shape[0]\r\n        corr = ndarray((N,N))\r\n        for r in range(N):\r\n            for c in range(r):\r\n                corr[r,c] = corr[c,r] = cov[r,c]/sqrt(cov[r,r]*cov[c,c])\r\n            corr[r,r] = 1.\r\n        return corr",
    "docstring": "The correlation matrix"
  },
  {
    "code": "def _find_git_info(self, gitdir):\n        res = {'remotes': None, 'tag': None, 'commit': None, 'dirty': None}\n        try:\n            logger.debug('opening %s as git.Repo', gitdir)\n            repo = Repo(path=gitdir, search_parent_directories=False)\n            res['commit'] = repo.head.commit.hexsha\n            res['dirty'] = repo.is_dirty(untracked_files=True)\n            res['remotes'] = {}\n            for rmt in repo.remotes:\n                urls = [u for u in rmt.urls]\n                if len(urls) > 0:\n                    res['remotes'][rmt.name] = urls[0]\n            for tag in repo.tags:\n                if tag.commit.hexsha == res['commit']:\n                    res['tag'] = tag.name\n        except Exception:\n            logger.debug('Exception getting git information', exc_info=True)\n        return res",
    "docstring": "Find information about the git repository, if this file is in a clone.\n\n        :param gitdir: path to the git repo's .git directory\n        :type gitdir: str\n        :returns: information about the git clone\n        :rtype: dict"
  },
  {
    "code": "def widget_status(self):\n        widget_status_list = []\n        for i in self.widgetlist:\n            widget_status_list += [[i.name, i.status]]\n        return widget_status_list",
    "docstring": "This method will return the status of all of the widgets in the\n        widget list"
  },
  {
    "code": "def blast_seqs(seqs,\n                 blast_constructor,\n                 blast_db=None,\n                 blast_mat_root=None,\n                 params={},\n                 add_seq_names=True,\n                 out_filename=None,\n                 WorkingDir=None,\n                 SuppressStderr=None,\n                 SuppressStdout=None,\n                 input_handler=None,\n                 HALT_EXEC=False\n                 ):\n    if blast_db:\n        params[\"-d\"] = blast_db\n    if out_filename:\n        params[\"-o\"] = out_filename\n    ih = input_handler or guess_input_handler(seqs, add_seq_names)\n    blast_app = blast_constructor(\n                   params=params,\n                   blast_mat_root=blast_mat_root,\n                   InputHandler=ih,\n                   WorkingDir=WorkingDir,\n                   SuppressStderr=SuppressStderr,\n                   SuppressStdout=SuppressStdout,\n                   HALT_EXEC=HALT_EXEC)\n    return blast_app(seqs)",
    "docstring": "Blast list of sequences.\n\n    seqs: either file name or list of sequence objects or list of strings or\n    single multiline string containing sequences.\n\n    WARNING: DECISION RULES FOR INPUT HANDLING HAVE CHANGED. Decision rules\n    for data are as follows. If it's s list, treat as lines, unless\n    add_seq_names is true (in which case treat as list of seqs). If it's a\n    string, test whether it has newlines. If it doesn't have newlines, assume\n    it's a filename. If it does have newlines, it can't be a filename, so\n    assume it's a multiline string containing sequences.\n\n    If you want to skip the detection and force a specific type of input\n    handler, use input_handler='your_favorite_handler'.\n\n    add_seq_names: boolean. if True, sequence names are inserted in the list\n        of sequences. if False, it assumes seqs is a list of lines of some\n        proper format that the program can handle"
  },
  {
    "code": "def url_to_attrs_dict(url, url_attr):\n    result = dict()\n    if isinstance(url, six.string_types):\n        url_value = url\n    else:\n        try:\n            url_value = url[\"url\"]\n        except TypeError:\n            raise BootstrapError(\n                'Function \"url_to_attrs_dict\" expects a string or a dict with key \"url\".'\n            )\n        crossorigin = url.get(\"crossorigin\", None)\n        integrity = url.get(\"integrity\", None)\n        if crossorigin:\n            result[\"crossorigin\"] = crossorigin\n        if integrity:\n            result[\"integrity\"] = integrity\n    result[url_attr] = url_value\n    return result",
    "docstring": "Sanitize url dict as used in django-bootstrap3 settings."
  },
  {
    "code": "def init_backend(self, *args, **kwargs):\n        self.model.attrs = {}\n        self.use_memory_cache = kwargs.get('use_memory_cache', True)\n        if self.use_memory_cache:\n            self.init_memory_cache()\n        self.use_disk_cache = kwargs.get('use_disk_cache', False)\n        if self.use_disk_cache:\n            self.init_disk_cache()\n        self.load_model()\n        self.model.unpicklable += ['_backend']",
    "docstring": "Initialize the backend."
  },
  {
    "code": "def draw(self, renderer):\n        dpi_cor = renderer.points_to_pixels(1.)\n        self.dpi_transform.clear()\n        self.dpi_transform.scale(dpi_cor, dpi_cor)\n        for c in self._children:\n            c.draw(renderer)\n        self.stale = False",
    "docstring": "Draw the children"
  },
  {
    "code": "def get_category_aliases_under(parent_alias=None):\n    return [ch.alias for ch in get_cache().get_children_for(parent_alias, only_with_aliases=True)]",
    "docstring": "Returns a list of category aliases under the given parent.\n\n    Could be useful to pass to `ModelWithCategory.enable_category_lists_editor`\n    in `additional_parents_aliases` parameter.\n\n    :param str|None parent_alias: Parent alias or None to categories under root\n    :rtype: list\n    :return: a list of category aliases"
  },
  {
    "code": "def unregister(self, observer):\n        self.observer_manager.observers.remove(observer)\n        observer.manager = None",
    "docstring": "Remove the observers of the observers list.\n        It will not receive any more notifications when occurs changes.\n\n        :param UpdatesObserver observer: Observer you will not receive any more notifications then\n                                         occurs changes."
  },
  {
    "code": "def _find_metadata_vars(self, ds, refresh=False):\n        if self._metadata_vars.get(ds, None) and refresh is False:\n            return self._metadata_vars[ds]\n        self._metadata_vars[ds] = []\n        for name, var in ds.variables.items():\n            if name in self._find_ancillary_vars(ds) or name in self._find_coord_vars(ds):\n                continue\n            if name in ('platform_name', 'station_name', 'instrument_name', 'station_id', 'platform_id', 'surface_altitude'):\n                self._metadata_vars[ds].append(name)\n            elif getattr(var, 'cf_role', '') != '':\n                self._metadata_vars[ds].append(name)\n            elif getattr(var, 'standard_name', None) is None and len(var.dimensions) == 0:\n                self._metadata_vars[ds].append(name)\n        return self._metadata_vars[ds]",
    "docstring": "Returns a list of netCDF variable instances for those that are likely metadata variables\n\n        :param netCDF4.Dataset ds: An open netCDF dataset\n        :param bool refresh: if refresh is set to True, the cache is\n                             invalidated.\n        :rtype: list\n        :return:   List of variable names (str) that are likely metadata\n                   variable candidates."
  },
  {
    "code": "def speak(self):\n        if self.quiet is False:\n            bot.info('[helper|%s]' %(self.name))\n            self._speak()",
    "docstring": "a function for the helper to announce him or herself, depending\n           on the level specified. If you want your client to have additional\n           announced things here, then implement the class `_speak` for your\n           client."
  },
  {
    "code": "def get_form(self, form, name):\n        kwargs = self.get_kwargs(form, name)\n        form_class = self.get_form_class(form, name)\n        composite_form = form_class(\n            data=form.data if form.is_bound else None,\n            files=form.files if form.is_bound else None,\n            **kwargs)\n        return composite_form",
    "docstring": "Get an instance of the form."
  },
  {
    "code": "def data_gen(n_ops=100):\n    while True:\n        X = np.random.uniform(size=(64, 64))\n        yield dict(X=costly_function(X, n_ops),\n                   y=np.random.randint(10, size=(1,)))",
    "docstring": "Yield data, while optionally burning compute cycles.\n\n    Parameters\n    ----------\n    n_ops : int, default=100\n        Number of operations to run between yielding data.\n\n    Returns\n    -------\n    data : dict\n        A object which looks like it might come from some\n        machine learning problem, with X as features, and y as targets."
  },
  {
    "code": "def _build_relations_config(self, yamlconfig):\n        config = {}\n        for element in yamlconfig:\n            if isinstance(element, str):\n                config[element] = {'relation_name': element, 'schemas': []}\n            elif isinstance(element, dict):\n                if 'relation_name' not in element or 'schemas' not in element:\n                    self.log.warning(\"Unknown element format for relation element %s\", element)\n                    continue\n                if not isinstance(element['schemas'], list):\n                    self.log.warning(\"Expected a list of schemas for %s\", element)\n                    continue\n                name = element['relation_name']\n                config[name] = {'relation_name': name, 'schemas': element['schemas']}\n            else:\n                self.log.warning('Unhandled relations config type: {}'.format(element))\n        return config",
    "docstring": "Builds a dictionary from relations configuration while maintaining compatibility"
  },
  {
    "code": "def next_lookup(self, symbol):\n        result = []\n        if symbol == self.initialsymbol:\n            result.append(EndSymbol())\n        for production in self.productions:\n            if symbol in production.rightside:\n                nextindex = production.rightside.index(symbol) + 1\n                while nextindex < len(production.rightside):\n                    nextsymbol = production.rightside[nextindex]\n                    firstlist = self.first_lookup(nextsymbol)\n                    cleanfirstlist = Choice([x for x in firstlist if x != NullSymbol()])\n                    result.append(cleanfirstlist)\n                    if NullSymbol() not in firstlist:\n                        break\n                else:\n                    result += self.next_lookup(production.leftside[0])\n        return result",
    "docstring": "Returns the next TerminalSymbols produced by the input symbol within this grammar definition"
  },
  {
    "code": "def update_savings_goal_data(self) -> None:\n        response = get(\n            _url(\n                \"/account/{0}/savings-goals\".format(self._account_uid),\n                self._sandbox\n            ),\n            headers=self._auth_headers\n        )\n        response.raise_for_status()\n        response = response.json()\n        response_savings_goals = response.get('savingsGoalList', {})\n        returned_uids = []\n        for goal in response_savings_goals:\n            uid = goal.get('savingsGoalUid')\n            returned_uids.append(uid)\n            if uid not in self.savings_goals:\n                self.savings_goals[uid] = SavingsGoal(\n                    self._auth_headers,\n                    self._sandbox,\n                    self._account_uid\n                )\n            self.savings_goals[uid].update(goal)\n        for uid in list(self.savings_goals):\n            if uid not in returned_uids:\n                self.savings_goals.pop(uid)",
    "docstring": "Get the latest savings goal information for the account."
  },
  {
    "code": "def saved_search(self, sid, **kw):\n        path = 'data/v1/searches/%s/results' % sid\n        params = self._params(kw)\n        return self._get(self._url(path), body_type=models.Items,\n                         params=params).get_body()",
    "docstring": "Execute a saved search by search id.\n\n        :param sid string: The id of the search\n        :returns: :py:class:`planet.api.models.Items`\n        :raises planet.api.exceptions.APIException: On API error.\n\n        :Options:\n\n        * page_size (int): Size of response pages\n        * sort (string): Sorting order in the form `field (asc|desc)`"
  },
  {
    "code": "def disable_scanners_by_group(self, group):\n        if group == 'all':\n            self.logger.debug('Disabling all scanners')\n            return self.zap.ascan.disable_all_scanners()\n        try:\n            scanner_list = self.scanner_group_map[group]\n        except KeyError:\n            raise ZAPError(\n                'Invalid group \"{0}\" provided. Valid groups are: {1}'.format(\n                    group, ', '.join(self.scanner_groups)\n                )\n            )\n        self.logger.debug('Disabling scanner group {0}'.format(group))\n        return self.disable_scanners_by_ids(scanner_list)",
    "docstring": "Disables the scanners in the group if it matches one in the scanner_group_map."
  },
  {
    "code": "def get_per_object_threshold(method, image, threshold, mask=None, labels=None,\n                             threshold_range_min = None,\n                             threshold_range_max = None,\n                             **kwargs):\n    if labels is None:\n        labels = np.ones(image.shape,int)\n        if not mask is None:\n            labels[np.logical_not(mask)] = 0 \n    label_extents = scipy.ndimage.find_objects(labels,np.max(labels))\n    local_threshold = np.ones(image.shape,image.dtype)\n    for i, extent in enumerate(label_extents, start=1):\n        label_mask = labels[extent]==i\n        if not mask is None:\n            label_mask = np.logical_and(mask[extent], label_mask)\n        values = image[extent]\n        per_object_threshold = get_global_threshold(\n            method, values, mask = label_mask, **kwargs)\n        local_threshold[extent][label_mask] = per_object_threshold\n    return local_threshold",
    "docstring": "Return a matrix giving threshold per pixel calculated per-object\n    \n    image - image to be thresholded\n    mask  - mask out \"don't care\" pixels\n    labels - a label mask indicating object boundaries\n    threshold - the global threshold"
  },
  {
    "code": "def register_model(self, model_id, properties, parameters, outputs, connector):\n        self.validate_connector(connector)\n        try:\n            return self.registry.register_model(\n                model_id,\n                properties,\n                parameters,\n                outputs,\n                connector\n            )\n        except DuplicateKeyError as ex:\n            raise ValueError(str(ex))",
    "docstring": "Register a new model with the engine. Expects connection information\n        for RabbitMQ to submit model run requests to workers.\n\n        Raises ValueError if the given model identifier is not unique.\n\n        Parameters\n        ----------\n        model_id : string\n            Unique model identifier\n        properties : Dictionary\n            Dictionary of model specific properties.\n        parameters :  list(scodata.attribute.AttributeDefinition)\n            List of attribute definitions for model run parameters\n        outputs : ModelOutputs\n            Description of model outputs\n        connector : dict\n            Connection information to communicate with model workers. Expected\n            to contain at least the connector name 'connector'.\n\n        Returns\n        -------\n        ModelHandle"
  },
  {
    "code": "def _unkown_type(self, uridecodebin, decodebin, caps):\n        streaminfo = caps.to_string()\n        if not streaminfo.startswith('audio/'):\n            return\n        self.read_exc = UnknownTypeError(streaminfo)\n        self.ready_sem.release()",
    "docstring": "The callback for decodebin's \"unknown-type\" signal."
  },
  {
    "code": "def _make_definition(self, definition):\n        if not definition:\n            return EndpointDefinition()\n        if isinstance(definition, EndpointDefinition):\n            return definition\n        elif len(definition) == 1:\n            return EndpointDefinition(\n                func=definition[0],\n            )\n        elif len(definition) == 2:\n            return EndpointDefinition(\n                func=definition[0],\n                response_schema=definition[1],\n            )\n        elif len(definition) == 3:\n            return EndpointDefinition(\n                func=definition[0],\n                request_schema=definition[1],\n                response_schema=definition[2],\n            )\n        elif len(definition) == 4:\n            return EndpointDefinition(\n                func=definition[0],\n                request_schema=definition[1],\n                response_schema=definition[2],\n                header_func=definition[3],\n            )",
    "docstring": "Generate a definition.\n\n        The input might already be a `EndpointDefinition` or it might be a tuple."
  },
  {
    "code": "def get_unused_code(self, min_confidence=0, sort_by_size=False):\n        if not 0 <= min_confidence <= 100:\n            raise ValueError('min_confidence must be between 0 and 100.')\n        def by_name(item):\n            return (item.filename.lower(), item.first_lineno)\n        def by_size(item):\n            return (item.size,) + by_name(item)\n        unused_code = (self.unused_attrs + self.unused_classes +\n                       self.unused_funcs + self.unused_imports +\n                       self.unused_props + self.unused_vars +\n                       self.unreachable_code)\n        confidently_unused = [obj for obj in unused_code\n                              if obj.confidence >= min_confidence]\n        return sorted(confidently_unused,\n                      key=by_size if sort_by_size else by_name)",
    "docstring": "Return ordered list of unused Item objects."
  },
  {
    "code": "def generate_property_deprecation_message(to_be_removed_in_version, old_name, new_name, new_attribute,\n                                          module_name='Client'):\n    message = \"Call to deprecated property '{name}'. This property will be removed in version '{version}'\".format(\n        name=old_name,\n        version=to_be_removed_in_version,\n    )\n    message += \" Please use the '{new_name}' property on the '{module_name}.{new_attribute}' attribute moving forward.\".format(\n        new_name=new_name,\n        module_name=module_name,\n        new_attribute=new_attribute,\n    )\n    return message",
    "docstring": "Generate a message to be used when warning about the use of deprecated properties.\n\n    :param to_be_removed_in_version: Version of this module the deprecated property will be removed in.\n    :type to_be_removed_in_version: str\n    :param old_name: Deprecated property name.\n    :type old_name: str\n    :param new_name: Name of the new property name to use.\n    :type new_name: str\n    :param new_attribute: The new attribute where the new property can be found.\n    :type new_attribute: str\n    :param module_name: Name of the module containing the new method to use.\n    :type module_name: str\n    :return: Full deprecation warning message for the indicated property.\n    :rtype: str"
  },
  {
    "code": "def denoise_z15():\n  hparams = xmoe2_dense_0()\n  hparams.decoder_type = \"denoising\"\n  hparams.noising_spec_train = {\"type\": \"random_zipfian\", \"prob\": 0.15}\n  hparams.noising_use_eval_during_train = 0.25\n  return hparams",
    "docstring": "Replace tokens instead of masking."
  },
  {
    "code": "def add_group_role(request, role, group, domain=None, project=None):\n    manager = keystoneclient(request, admin=True).roles\n    return manager.grant(role=role, group=group, domain=domain,\n                         project=project)",
    "docstring": "Adds a role for a group on a domain or project."
  },
  {
    "code": "def register_arguments(cls, parser):\n        if hasattr(cls, \"_dont_register_arguments\"):\n            return\n        prefix = cls.configuration_key_prefix()\n        cfgkey = cls.configuration_key\n        parser.add_argument(\"--%s-%s\" % (prefix, cfgkey),\n                            action=\"store_true\",\n                            dest=\"%s_%s\" % (prefix, cfgkey),\n                            default=False,\n                            help=\"%s: %s\" %\n                            (cls.__name__, cls.help()))\n        args = cls.init_argnames()\n        defaults = cls._init_argdefaults()\n        for arg in args[0:len(args) - len(defaults)]:\n            parser.add_argument(\"--%s-%s-%s\" % (prefix, cfgkey, arg),\n                                dest=\"%s_%s_%s\" % (prefix, cfgkey, arg),\n                                help=\"\")\n        for i, arg in enumerate(args[len(args) - len(defaults):]):\n            parser.add_argument(\"--%s-%s-%s\" % (prefix, cfgkey, arg),\n                                dest=\"%s_%s_%s\" % (prefix, cfgkey, arg),\n                                default=defaults[i],\n                                help=\"default: %(default)s\")",
    "docstring": "Register command line options.\n\n        Implement this method for normal options behavior with protection from\n        OptionConflictErrors. If you override this method and want the default\n        --$name option(s) to be registered, be sure to call super()."
  },
  {
    "code": "def get_outcome_results(self, course_id, include=None, outcome_ids=None, user_ids=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"course_id\"] = course_id\r\n        if user_ids is not None:\r\n            params[\"user_ids\"] = user_ids\r\n        if outcome_ids is not None:\r\n            params[\"outcome_ids\"] = outcome_ids\r\n        if include is not None:\r\n            params[\"include\"] = include\r\n        self.logger.debug(\"GET /api/v1/courses/{course_id}/outcome_results with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"GET\", \"/api/v1/courses/{course_id}/outcome_results\".format(**path), data=data, params=params, no_data=True)",
    "docstring": "Get outcome results.\r\n\r\n        Gets the outcome results for users and outcomes in the specified context."
  },
  {
    "code": "def read_instance(self, cls, sdmxobj, offset=None, first_only=True):\r\n        if offset:\r\n            try:\r\n                base = self._paths[offset](sdmxobj._elem)[0]\r\n            except IndexError:\r\n                return None\r\n        else:\r\n            base = sdmxobj._elem\r\n        result = self._paths[cls](base)\r\n        if result:\r\n            if first_only:\r\n                return cls(self, result[0])\r\n            else:\r\n                return [cls(self, i) for i in result]",
    "docstring": "If cls in _paths and matches,\r\n        return an instance of cls with the first XML element,\r\n        or, if first_only is False, a list of cls instances \r\n        for all elements found,\r\n        If no matches were found, return None."
  },
  {
    "code": "def search(self, pattern):\n        for node in self.nodes.values():\n            match, following = pattern.match(self, node)\n            if match:\n                return match, following\n        return [], None",
    "docstring": "Searches the graph for a sub-graph that matches the given pattern\n        and returns the first match it finds."
  },
  {
    "code": "def _imm_dir(self):\n    dir0 = set(dir(self.__class__))\n    dir0.update(self.__dict__.keys())\n    dir0.update(six.iterkeys(_imm_value_data(self)))\n    return sorted(list(dir0))",
    "docstring": "An immutable object's dir function should list not only its attributes, but also its un-cached\n    lazy values."
  },
  {
    "code": "def pack(self, out: IO):\n        out.write(self.access_flags.pack())\n        out.write(pack('>HH', self._name_index, self._descriptor_index))\n        self.attributes.pack(out)",
    "docstring": "Write the Field to the file-like object `out`.\n\n        .. note::\n\n            Advanced usage only. You will typically never need to call this\n            method as it will be called for you when saving a ClassFile.\n\n        :param out: Any file-like object providing `write()`"
  },
  {
    "code": "def value(self, value):\n        if value not in self.options:\n            if len(self.labels) == len(self.options):\n                self.options[-1] = value\n            else:\n                self.options.append(value)\n        self._value = value",
    "docstring": "Setter for value.\n\n        :param value: The value.\n        :type value: object"
  },
  {
    "code": "def auto_instantiate(*classes):\n    def decorator(f):\n        sig = signature(f)\n        @wraps(f)\n        def _(*args, **kwargs):\n            bvals = sig.bind(*args, **kwargs)\n            for varname, val in bvals.arguments.items():\n                anno = sig.parameters[varname].annotation\n                if anno in classes or (len(classes) == 0 and anno != _empty):\n                    bvals.arguments[varname] = anno(val)\n            return f(*bvals.args, **bvals.kwargs)\n        return FunctionMaker.create(\n            f, 'return _(%(signature)s)', dict(_=_, __wrapped__=f)\n        )\n    return decorator",
    "docstring": "Creates a decorator that will instantiate objects based on function\n    parameter annotations.\n\n    The decorator will check every argument passed into ``f``. If ``f`` has an\n    annotation for the specified parameter and the annotation is found in\n    ``classes``, the parameter value passed in will be used to construct a new\n    instance of the expression that is the annotation.\n\n    An example (Python 3):\n\n    .. code-block:: python\n\n        @auto_instantiate(int)\n        def foo(a: int, b: float):\n            pass\n\n    Any value passed in as ``b`` is left unchanged. Anything passed as the\n    parameter for ``a`` will be converted to :class:`int` before calling the\n    function.\n\n    Since Python 2 does not support annotations, the\n    :func:`~data.decorators.annotate` function should can be used:\n\n    .. code-block:: python\n\n        @auto_instantiate(int)\n        @annotate(a=int)\n        def foo(a, b):\n            pass\n\n\n    :param classes: Any number of classes/callables for which\n                    auto-instantiation should be performed. If empty, perform\n                    for all.\n\n    :note: When dealing with data, it is almost always more convenient to use\n           the :func:`~data.decorators.data` decorator instead."
  },
  {
    "code": "def flatten_all_but_last(a):\n  ret = tf.reshape(a, [-1, tf.shape(a)[-1]])\n  if not tf.executing_eagerly():\n    ret.set_shape([None] + a.get_shape().as_list()[-1:])\n  return ret",
    "docstring": "Flatten all dimensions of a except the last."
  },
  {
    "code": "def _apply_Create(self, change):\n        ar = _AzureRecord(self._resource_group, change.new)\n        create = self._dns_client.record_sets.create_or_update\n        create(resource_group_name=ar.resource_group,\n               zone_name=ar.zone_name,\n               relative_record_set_name=ar.relative_record_set_name,\n               record_type=ar.record_type,\n               parameters=ar.params)\n        self.log.debug('*  Success Create/Update: {}'.format(ar))",
    "docstring": "A record from change must be created.\n\n            :param change: a change object\n            :type  change: octodns.record.Change\n\n            :type return: void"
  },
  {
    "code": "def minor_extent(self) -> complex:\n        return min((self.max() - self.null, self.null - self.min()))",
    "docstring": "Minimum deviation from null."
  },
  {
    "code": "def load_configs(self, conf_file):\n        with open(conf_file) as stream:\n            lines = itertools.chain((\"[global]\",), stream)\n            self._config.read_file(lines)\n        return self._config['global']",
    "docstring": "Assumes that the config file does not have any sections, so throw it all in global"
  },
  {
    "code": "def run_command(\n        host,\n        command,\n        username=None,\n        key_path=None,\n        noisy=True\n):\n    with HostSession(host, username, key_path, noisy) as s:\n        if noisy:\n            print(\"\\n{}{} $ {}\\n\".format(shakedown.fchr('>>'), host, command))\n        s.run(command)\n    ec, output = s.get_result()\n    return ec == 0, output",
    "docstring": "Run a command via SSH, proxied through the mesos master\n\n        :param host: host or IP of the machine to execute the command on\n        :type host: str\n        :param command: the command to execute\n        :type command: str\n        :param username: SSH username\n        :type username: str\n        :param key_path: path to the SSH private key to use for SSH authentication\n        :type key_path: str\n        :return: True if successful, False otherwise\n        :rtype: bool\n        :return: Output of command\n        :rtype: string"
  },
  {
    "code": "def not_query(expression):\n    compiled_expression = compile_query(expression)\n    def _not(index, expression=compiled_expression):\n        all_keys = index.get_all_keys()\n        returned_keys = expression(index)\n        return [key for key in all_keys if key not in returned_keys]\n    return _not",
    "docstring": "Apply logical not operator to expression."
  },
  {
    "code": "def parse_multiple_json(json_file, offset=None):\n    json_info_list = []\n    if not os.path.exists(json_file):\n        return json_info_list\n    try:\n        with open(json_file, \"r\") as f:\n            if offset:\n                f.seek(offset)\n            for line in f:\n                if line[-1] != \"\\n\":\n                    break\n                json_info = json.loads(line)\n                json_info_list.append(json_info)\n                offset += len(line)\n    except BaseException as e:\n        logging.error(e.message)\n    return json_info_list, offset",
    "docstring": "Parse multiple json records from the given file.\n\n    Seek to the offset as the start point before parsing\n    if offset set. return empty list if the json file does\n    not exists or exception occurs.\n\n    Args:\n        json_file (str): File path to be parsed.\n        offset (int): Initial seek position of the file.\n\n    Returns:\n        A dict of json info.\n        New offset after parsing."
  },
  {
    "code": "def flat_map(self, func=None, name=None):\n        if func is None:\n            func = streamsx.topology.runtime._identity\n            if name is None:\n               name = 'flatten'\n        sl = _SourceLocation(_source_info(), 'flat_map')\n        _name = self.topology.graph._requested_name(name, action='flat_map', func=func)\n        stateful = self._determine_statefulness(func)\n        op = self.topology.graph.addOperator(self.topology.opnamespace+\"::FlatMap\", func, name=_name, sl=sl, stateful=stateful)\n        op.addInputPort(outputPort=self.oport)\n        streamsx.topology.schema.StreamSchema._fnop_style(self.oport.schema, op, 'pyStyle')\n        oport = op.addOutputPort(name=_name)\n        return Stream(self.topology, oport)._make_placeable()._layout('FlatMap', name=_name, orig_name=name)",
    "docstring": "Maps and flatterns each tuple from this stream into 0 or more tuples.\n\n\n        For each tuple on this stream ``func(tuple)`` is called.\n        If the result is not `None` then the the result is iterated over\n        with each value from the iterator that is not `None` will be submitted\n        to the return stream.\n\n        If the result is `None` or an empty iterable then no tuples are submitted to\n        the returned stream.\n        \n        Args:\n            func: A callable that takes a single parameter for the tuple.\n                If not supplied then a function equivalent to ``lambda tuple_ : tuple_`` is used.\n                This is suitable when each tuple on this stream is an iterable to be flattened.\n                \n            name(str): Name of the flattened stream, defaults to a generated name.\n\n        If invoking ``func`` for a tuple on the stream raises an exception\n        then its processing element will terminate. By default the processing\n        element will automatically restart though tuples may be lost.\n\n        If ``func`` is a callable object then it may suppress exceptions\n        by return a true value from its ``__exit__`` method. When an\n        exception is suppressed no tuples are submitted to the flattened\n        and mapped stream corresponding to the input tuple\n        that caused the exception.\n\n        Returns:\n            Stream: A Stream containing flattened and mapped tuples.\n        Raises:\n            TypeError: if `func` does not return an iterator nor None\n\n        .. versionchanged:: 1.11 `func` is optional."
  },
  {
    "code": "def unregister_message_handler(self, target_or_handler):\n        if isinstance(target_or_handler, str):\n            del self._message_handlers[target_or_handler]\n        else:\n            for key, val in self._message_handlers.items():\n                if val == target_or_handler:\n                    del self._message_handlers[key]",
    "docstring": "Unregister a mpv script message handler for the given script message target name.\n\n        You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is\n        registered."
  },
  {
    "code": "def getTokensEndLoc():\r\n    import inspect\r\n    fstack = inspect.stack()\r\n    try:\r\n        for f in fstack[2:]:\r\n            if f[3] == \"_parseNoCache\":\r\n                endloc = f[0].f_locals[\"loc\"]\r\n                return endloc\r\n        else:\r\n            raise ParseFatalException(\"incorrect usage of getTokensEndLoc - may only be called from within a parse action\")\r\n    finally:\r\n        del fstack",
    "docstring": "Method to be called from within a parse action to determine the end\r\n       location of the parsed tokens."
  },
  {
    "code": "def respond(self, code):\n        resp = HttpResponse(code, self.connection)\n        resp.request = self\n        if hasattr(self, 'version'):\n            resp.version = self.version\n        return resp",
    "docstring": "Starts a response.\n\n        ``code`` is an integer standing for standard HTTP status code.\n\n        This method will automatically adjust the response to adapt to request\n        parameters, such as \"Accept-Encoding\" and \"TE\"."
  },
  {
    "code": "def packagePlugin(self, dir=os.getcwd(), extraArgs=[]):\n\t\tdistDir = os.path.join(os.path.abspath(dir), 'dist')\n\t\tself.runUAT([\n\t\t\t'BuildPlugin',\n\t\t\t'-Plugin=' + self.getPluginDescriptor(dir),\n\t\t\t'-Package=' + distDir\n\t\t] + extraArgs)",
    "docstring": "Packages a build of the Unreal plugin in the specified directory, suitable for use as a prebuilt Engine module"
  },
  {
    "code": "def defaultMachine(use_rpm_default=True):\n    if use_rpm_default:\n        try:\n            rmachine = subprocess.check_output(['rpm', '--eval=%_target_cpu'], shell=False).rstrip()\n            rmachine = SCons.Util.to_str(rmachine)\n        except Exception as e:\n            return defaultMachine(False)\n    else:\n        rmachine = platform.machine()\n        if rmachine in arch_canon:\n            rmachine = arch_canon[rmachine][0]\n    return rmachine",
    "docstring": "Return the canonicalized machine name."
  },
  {
    "code": "def parse_value(cell):\n    value = cell.value\n    if isinstance(value, string_types):\n        value = value.strip()\n    if isinstance(value, (datetime)):\n        value = value.isoformat()\n    return value",
    "docstring": "Extrae el valor de una celda de Excel como texto."
  },
  {
    "code": "def _load_rules(self):\n        for ruleset in self.active_rulesets:\n            section_name = 'sweep_rules_' + ruleset.lower()\n            try:\n                ruledefs = getattr(self.config, section_name)\n            except AttributeError:\n                raise error.UserError(\"There is no [{}] section in your configuration\"\n                                      .format(section_name.upper()))\n            for ruledef, filtercond in ruledefs.items():\n                if ruledef.endswith('.filter'):\n                    rulename = ruledef.rsplit('.', 1)[0]\n                    rule = SweepRule(ruleset, rulename,\n                                     int(ruledefs.get(rulename + '.prio', '999')),\n                                     ruledefs.get(rulename + '.order', self.default_order),\n                                     parse_cond(filtercond))\n                    self.rules.append(rule)\n        self.rules.sort(key=lambda x: (x.prio, x.name))\n        return self.rules",
    "docstring": "Load rule definitions from config."
  },
  {
    "code": "def cookies(self):\n        c = Cookie.SimpleCookie(self.getheader('set-cookie'))\n        return dict((i.key, i.value) for i in c.values())",
    "docstring": "Cookies in dict"
  },
  {
    "code": "def Run(self):\n    if not data_store.AFF4Enabled():\n      return\n    try:\n      filestore = aff4.FACTORY.Create(\n          FileStore.PATH, FileStore, mode=\"rw\", token=aff4.FACTORY.root_token)\n      filestore.Close()\n      hash_filestore = aff4.FACTORY.Create(\n          HashFileStore.PATH,\n          HashFileStore,\n          mode=\"rw\",\n          token=aff4.FACTORY.root_token)\n      hash_filestore.Close()\n      nsrl_filestore = aff4.FACTORY.Create(\n          NSRLFileStore.PATH,\n          NSRLFileStore,\n          mode=\"rw\",\n          token=aff4.FACTORY.root_token)\n      nsrl_filestore.Close()\n    except access_control.UnauthorizedAccess:\n      pass",
    "docstring": "Create FileStore and HashFileStore namespaces."
  },
  {
    "code": "def enable_autocuts(self, option):\n        option = option.lower()\n        assert(option in self.autocuts_options), \\\n            ImageViewError(\"Bad autocuts option '%s': must be one of %s\" % (\n                str(self.autocuts_options)))\n        self.t_.set(autocuts=option)",
    "docstring": "Set ``autocuts`` behavior.\n\n        Parameters\n        ----------\n        option : {'on', 'override', 'once', 'off'}\n            Option for auto-cut behavior. A list of acceptable options can\n            also be obtained by :meth:`get_autocuts_options`.\n\n        Raises\n        ------\n        ginga.ImageView.ImageViewError\n            Invalid option."
  },
  {
    "code": "def readCell(self, row, col):\r\n        try:\r\n            if self.__sheet is None:\r\n                self.openSheet(super(ExcelRead, self).DEFAULT_SHEET)\r\n            return self.__sheet.cell(row, col).value\r\n        except BaseException as excp:\r\n            raise UfException(Errors.UNKNOWN_ERROR, \"Unknown Error in Excellib.readCell %s\" % excp)",
    "docstring": "read a cell"
  },
  {
    "code": "def truncate(self, table):\n        if isinstance(table, (list, set, tuple)):\n            for t in table:\n                self._truncate(t)\n        else:\n            self._truncate(table)",
    "docstring": "Empty a table by deleting all of its rows."
  },
  {
    "code": "def is_seq(obj):\n    if not hasattr(obj, '__iter__'):\n        return False\n    if isinstance(obj, basestring):\n        return False\n    return True",
    "docstring": "Returns True if object is not a string but is iterable"
  },
  {
    "code": "def _update_device_from_fs(self, device):\n        try:\n            directory_entries = listdir(device[\"mount_point\"])\n            lowercase_directory_entries = [e.lower() for e in directory_entries]\n            if self.MBED_HTM_NAME.lower() in lowercase_directory_entries:\n                self._update_device_from_htm(device)\n        except (OSError, IOError) as e:\n            logger.warning(\n                'Marking device with mount point \"%s\" as unmounted due to the '\n                \"following error: %s\",\n                device[\"mount_point\"],\n                e,\n            )\n            device[\"mount_point\"] = None",
    "docstring": "Updates the device information based on files from its 'mount_point'\n            @param device Dictionary containing device information"
  },
  {
    "code": "def add_new_devices_callback(self, callback):\n        self._new_devices_callbacks.append(callback)\n        _LOGGER.debug('Added new devices callback to %s', callback)",
    "docstring": "Register as callback for when new devices are added."
  },
  {
    "code": "def get_absolute_path(cls, roots, path):\n        for root in roots:\n            abspath = os.path.abspath(os.path.join(root, path))\n            if abspath.startswith(root) and os.path.exists(abspath):\n                return abspath\n        return 'file-not-found'",
    "docstring": "Returns the absolute location of ``path`` relative to one of\n        the ``roots``.\n\n        ``roots`` is the path configured for this `StaticFileHandler`\n        (in most cases the ``static_path`` `Application` setting)."
  },
  {
    "code": "def get_learning_objectives(self):\n        mgr = self._get_provider_manager('LEARNING')\n        lookup_session = mgr.get_objective_lookup_session(proxy=getattr(self, \"_proxy\", None))\n        lookup_session.use_federated_objective_bank_view()\n        return lookup_session.get_objectives_by_ids(self.get_learning_objective_ids())",
    "docstring": "This method also mirrors that in the Item."
  },
  {
    "code": "def init_pipette():\n    global session\n    pipette_info = set_current_mount(session.adapter, session)\n    pipette = pipette_info['pipette']\n    res = {}\n    if pipette:\n        session.current_model = pipette_info['model']\n        if not feature_flags.use_protocol_api_v2():\n            mount = pipette.mount\n            session.current_mount = mount\n        else:\n            mount = pipette.get('mount')\n            session.current_mount = mount_by_name[mount]\n        session.pipettes[mount] = pipette\n        res = {'mount': mount, 'model': pipette_info['model']}\n    log.info(\"Pipette info {}\".format(session.pipettes))\n    return res",
    "docstring": "Finds pipettes attached to the robot currently and chooses the correct one\n    to add to the session.\n\n    :return: The pipette type and mount chosen for deck calibration"
  },
  {
    "code": "def namedb_get_all_names( cur, current_block, offset=None, count=None, include_expired=False ):\n    unexpired_query = \"\"\n    unexpired_args = ()\n    if not include_expired:\n        unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )\n        unexpired_query = 'WHERE {}'.format(unexpired_query)\n    query = \"SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id \" + unexpired_query + \" ORDER BY name \"\n    args = unexpired_args\n    offset_count_query, offset_count_args = namedb_offset_count_predicate( offset=offset, count=count )\n    query += offset_count_query + \";\"\n    args += offset_count_args\n    name_rows = namedb_query_execute( cur, query, tuple(args) )\n    ret = []\n    for name_row in name_rows:\n        rec = {}\n        rec.update( name_row )\n        ret.append( rec['name'] )\n    return ret",
    "docstring": "Get a list of all names in the database, optionally\n    paginated with offset and count.  Exclude expired names.  Include revoked names."
  },
  {
    "code": "def cat(self, paths, check_crc=False):\n        if not isinstance(paths, list):\n            raise InvalidInputException(\"Paths should be a list\")\n        if not paths:\n            raise InvalidInputException(\"cat: no path given\")\n        processor = lambda path, node, check_crc=check_crc: self._handle_cat(path, node, check_crc)\n        for item in self._find_items(paths, processor, include_toplevel=True,\n                                     include_children=False, recurse=False):\n            if item:\n                yield item",
    "docstring": "Fetch all files that match the source file pattern\n        and display their content on stdout.\n\n        :param paths: Paths to display\n        :type paths: list of strings\n        :param check_crc: Check for checksum errors\n        :type check_crc: boolean\n        :returns: a generator that yields strings"
  },
  {
    "code": "def close_statement(self, connection_id, statement_id):\n        request = requests_pb2.CloseStatementRequest()\n        request.connection_id = connection_id\n        request.statement_id = statement_id\n        self._apply(request)",
    "docstring": "Closes a statement.\n\n        :param connection_id:\n            ID of the current connection.\n\n        :param statement_id:\n            ID of the statement to close."
  },
  {
    "code": "def format(self, fmt):\n        val = ''\n        for x in fmt:\n            if x == 'd':\n                val += self._driv\n            elif x == 'p':\n                val += self._path\n            elif x == 'n':\n                val += self._name\n            elif x == 'x':\n                val += self._ext\n            elif x == 'z':\n                if self._size != None: val += str(self._size)\n            elif x == 't':\n                if self._time != None: val += str(self._time)\n        return val",
    "docstring": "Returns string representing the items specified in the format string\n\n        The format string can contain:\n\n        .. code::\n\n            d - drive letter\n            p - path\n            n - name\n            x - extension\n            z - file size\n            t - file time in seconds\n\n        And, you can string them together, e.g. `dpnx` returns the fully \n        qualified name.\n\n        On platforms like Unix, where drive letter doesn't make sense, it's simply\n        ignored when used in a format string, making it easy to construct fully\n        qualified path names in an os independent manner.\n\n        Parameters\n        ----------\n            fmt : str\n                A string representing the elements you want returned.\n\n        Returns\n        -------\n            str\n                A string containing the elements of the path requested in `fmt`"
  },
  {
    "code": "def send(self, **kwargs):\n    assert len(kwargs) == 1, \"Must make a single request.\"\n    res = self.send_req(sc_pb.Request(**kwargs))\n    return getattr(res, list(kwargs.keys())[0])",
    "docstring": "Create and send a specific request, and return the response.\n\n    For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing\n\n    Args:\n      **kwargs: A single kwarg with the name and value to fill in to Request.\n\n    Returns:\n      The Response corresponding to your request."
  },
  {
    "code": "def unhumanize_class(my_classes):\n    result = []\n    interval = my_classes[-1] - my_classes[-2]\n    min_value = 0\n    for max_value in my_classes:\n        result.append((format_decimal(interval, min_value),\n                       format_decimal(interval, max_value)))\n        min_value = max_value\n    return result",
    "docstring": "Return class as interval without formatting."
  },
  {
    "code": "def restore(self):\n        if len(list(self.backup.keys())) == 0:\n            return\n        for key in self.backup.keys():\n            if key != 'WCSCDATE':\n                self.__dict__[self.wcstrans[key]] = self.orig_wcs[self.backup[key]]\n        self.update()",
    "docstring": "Reset the active WCS keywords to values stored in the\n            backup keywords."
  },
  {
    "code": "def max_repetition_level(self, path):\n        max_level = 0\n        for part in path:\n            element = self.schema_element(part)\n            if element.repetition_type == parquet_thrift.FieldRepetitionType.REQUIRED:\n                max_level += 1\n        return max_level",
    "docstring": "Get the max repetition level for the given schema path."
  },
  {
    "code": "def Validate(self, problems=default_problem_reporter):\n    found_problem = False\n    found_problem = ((not util.ValidateRequiredFieldsAreNotEmpty(\n                          self, self._REQUIRED_FIELD_NAMES, problems))\n                          or found_problem)\n    found_problem = self.ValidateAgencyUrl(problems) or found_problem\n    found_problem = self.ValidateAgencyLang(problems) or found_problem\n    found_problem = self.ValidateAgencyTimezone(problems) or found_problem\n    found_problem = self.ValidateAgencyFareUrl(problems) or found_problem\n    found_problem = self.ValidateAgencyEmail(problems) or found_problem\n    return not found_problem",
    "docstring": "Validate attribute values and this object's internal consistency.\n\n    Returns:\n      True iff all validation checks passed."
  },
  {
    "code": "def wrap_passthrough(self, text, multiline=True):\n        if not multiline:\n            text = text.lstrip()\n        if multiline:\n            out = \"\\\\\"\n        else:\n            out = \"\\\\\\\\\"\n        out += self.add_ref(\"passthrough\", text) + unwrapper\n        if not multiline:\n            out += \"\\n\"\n        return out",
    "docstring": "Wrap a passthrough."
  },
  {
    "code": "def delete_all(self):\n        def delete_action_gen():\n            scanner = scan(self.es,\n                           index=self.index_name,\n                           query={'query': {'match_all':{}}})\n            for v in scanner:\n                yield { '_op_type': 'delete',\n                        '_index': self.index_name,\n                        '_type': v['_type'],\n                        '_id': v['_id'],\n                      }\n        bulk(self.es, delete_action_gen())",
    "docstring": "Delete all books from the index"
  },
  {
    "code": "def capture(self, payment_id, amount, data={}, **kwargs):\n        url = \"{}/{}/capture\".format(self.base_url, payment_id)\n        data['amount'] = amount\n        return self.post_url(url, data, **kwargs)",
    "docstring": "Capture Payment for given Id\n\n        Args:\n            payment_id : Id for which payment object has to be retrieved\n            Amount : Amount for which the payment has to be retrieved\n\n        Returns:\n            Payment dict after getting captured"
  },
  {
    "code": "def scaledBy(self, scale):\n        scaled = deepcopy(self)\n        if type(scaled.value) in (int, float):\n            scaled.value *= scale\n        elif isinstance(scaled.value, numbers):\n            scaled.value.values = tuple(v * scale for v in scaled.value.values)\n        return scaled",
    "docstring": "Return a new Value scaled by a given number for ints and floats."
  },
  {
    "code": "def create_wallet(password, api_code, service_url, priv=None, label=None, email=None):\n        params = {'password': password, 'api_code': api_code}\n        if priv is not None:\n            params['priv'] = priv\n        if label is not None:\n            params['label'] = label\n        if email is not None:\n            params['email'] = email\n        response = util.call_api(\"api/v2/create\", params, base_url=service_url)\n        json_response = json.loads(response)\n        return CreateWalletResponse(json_response['guid'],\n                                    json_response['address'],\n                                    json_response['label'])",
    "docstring": "Create a new Blockchain.info wallet. It can be created containing a \n        pre-generated private key or will otherwise generate a new private key. \n\n        :param str password: password for the new wallet. At least 10 characters.\n        :param str api_code: API code with create wallets permission\n        :param str service_url: URL to an instance of service-my-wallet-v3 (with trailing slash)\n        :param str priv: private key to add to the wallet (optional)\n        :param str label: label for the first address in the wallet (optional)\n        :param str email: email to associate with the new wallet (optional)\n        :return: an instance of :class:`WalletResponse` class"
  },
  {
    "code": "def is_valid_size(size, chunk_size):\n        min_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MIN']\n        max_size = \\\n            chunk_size * current_app.config['FILES_REST_MULTIPART_MAX_PARTS']\n        return size > min_csize and size <= max_size",
    "docstring": "Validate max theoretical size."
  },
  {
    "code": "def is_ready(self):\n        if not self._thread:\n            return False\n        if not self._ready.is_set():\n            return False\n        return True",
    "docstring": "Is thread & ioloop ready.\n\n        :returns bool:"
  },
  {
    "code": "def gid(self):\n        if not self._gid:\n            if self.controller.config.daemon.group:\n                self._gid = grp.getgrnam(self.config.daemon.group).gr_gid\n            else:\n                self._gid = os.getgid()\n        return self._gid",
    "docstring": "Return the group id that the daemon will run with\n\n        :rtype: int"
  },
  {
    "code": "def extract_patches(images, patch_shape, samples_per_image=40, seed=0,\n                    cycle=True):\n    rs = np.random.RandomState(seed)\n    for Xi in itr.cycle(images):\n        w, h = [Xi.shape[i]-patch_shape[i] for i in range(2)]\n        assert w > 0 and h > 0\n        indices = np.asarray(list(itr.product(range(w), range(h))))\n        rs.shuffle(indices)\n        for x, y in indices[:samples_per_image]:\n            yield Xi[x:x+patch_shape[0], y:y+patch_shape[1]]",
    "docstring": "Takes a set of images and yields randomly chosen patches of specified size.\n\n    Parameters\n    ----------\n    images : iterable\n        The images have to be iterable, and each element must be a Numpy array\n        with at least two spatial 2 dimensions as the first and second axis.\n    patch_shape : tuple, length 2\n        The spatial shape of the patches that should be extracted. If the\n        images have further dimensions beyond the spatial, the patches will\n        copy these too.\n    samples_per_image : int\n        Samples to extract before moving on to the next image.\n    seed : int\n        Seed with which to select the patches.\n    cycle : bool\n        If True, then the function will produce patches indefinitely, by going\n        back to the first image when all are done. If False, the iteration will\n        stop when there are no more images.\n\n    Returns\n    -------\n    patch_generator\n        This function returns a generator that will produce patches.\n\n    Examples\n    --------\n    >>> import deepdish as dd\n    >>> import matplotlib.pylab as plt\n    >>> import itertools\n    >>> images = ag.io.load_example('mnist')\n\n    Now, let us say we want to exact patches from the these, where each patch\n    has at least some activity.\n\n    >>> gen = dd.image.extract_patches(images, (5, 5))\n    >>> gen = (x for x in gen if x.mean() > 0.1)\n    >>> patches = np.array(list(itertools.islice(gen, 25)))\n    >>> patches.shape\n    (25, 5, 5)\n    >>> dd.plot.images(patches)\n    >>> plt.show()"
  },
  {
    "code": "def mv_normal_cov_like(x, mu, C):\n    R\n    if len(np.shape(x)) > 1:\n        return np.sum([flib.cov_mvnorm(r, mu, C) for r in x])\n    else:\n        return flib.cov_mvnorm(x, mu, C)",
    "docstring": "R\"\"\"\n    Multivariate normal log-likelihood parameterized by a covariance\n    matrix.\n\n    .. math::\n        f(x \\mid \\pi, C) = \\frac{1}{(2\\pi|C|)^{1/2}} \\exp\\left\\{ -\\frac{1}{2} (x-\\mu)^{\\prime}C^{-1}(x-\\mu) \\right\\}\n\n    :Parameters:\n      - `x` : (n,k)\n      - `mu` : (k) Location parameter.\n      - `C` : (k,k) Positive definite covariance matrix.\n\n    .. seealso:: :func:`mv_normal_like`, :func:`mv_normal_chol_like`"
  },
  {
    "code": "def _ApplySudsJurkoAppenderPatch(self):\n    def PatchedAppend(self, parent, content):\n      obj = content.value\n      child = self.node(content)\n      parent.append(child)\n      for item in obj:\n        cont = suds.mx.Content(tag=item[0], value=item[1])\n        suds.mx.appender.Appender.append(self, child, cont)\n    suds.mx.appender.ObjectAppender.append = PatchedAppend",
    "docstring": "Appends a Monkey Patch to the suds.mx.appender module.\n\n    This resolves an issue where empty objects are ignored and stripped from the\n    request output. More details can be found on the suds-jurko issue tracker:\n    https://goo.gl/uyYw0C"
  },
  {
    "code": "def vote(self, direction=0):\n        url = self.reddit_session.config['vote']\n        data = {'id': self.fullname,\n                'dir': six.text_type(direction)}\n        if self.reddit_session.user:\n            urls = [urljoin(self.reddit_session.user._url, 'disliked'),\n                    urljoin(self.reddit_session.user._url, 'liked')]\n            self.reddit_session.evict(urls)\n        return self.reddit_session.request_json(url, data=data)",
    "docstring": "Vote for the given item in the direction specified.\n\n        Note: votes must be cast by humans. That is, API clients proxying a\n        human's action one-for-one are OK, but bots deciding how to vote on\n        content or amplifying a human's vote are not. See the reddit rules for\n        more details on what constitutes vote cheating.\n\n        Source for note: http://www.reddit.com/dev/api#POST_api_vote\n\n        :returns: The json response from the server."
  },
  {
    "code": "def image_to_file(self, path):\n        _LOGGER.debug(\"Writing image from %s to %s\", self.name, path)\n        response = self._cached_image\n        if response.status_code == 200:\n            with open(path, 'wb') as imgfile:\n                copyfileobj(response.raw, imgfile)\n        else:\n            _LOGGER.error(\"Cannot write image to file, response %s\",\n                          response.status_code,\n                          exc_info=True)",
    "docstring": "Write image to file.\n\n        :param path: Path to write file"
  },
  {
    "code": "def plotPixel(self, x, y, color=\"black\"):\n        p = Point(x, y)\n        p.fill(color)\n        p.draw(self)\n        p.t = lambda v: v\n        p.tx = lambda v: v\n        p.ty = lambda v: v",
    "docstring": "Doesn't use coordinant system."
  },
  {
    "code": "def cli(env, volume_id, replicant_id, immediate):\n    block_storage_manager = SoftLayer.BlockStorageManager(env.client)\n    success = block_storage_manager.failover_to_replicant(\n        volume_id,\n        replicant_id,\n        immediate\n    )\n    if success:\n        click.echo(\"Failover to replicant is now in progress.\")\n    else:\n        click.echo(\"Failover operation could not be initiated.\")",
    "docstring": "Failover a block volume to the given replicant volume."
  },
  {
    "code": "def precision_at_proportions(self):\n        return plot.precision_at_proportions(self.y_true, self.y_score,\n                                             ax=_gen_ax())",
    "docstring": "Precision at proportions plot"
  },
  {
    "code": "def encoding(self):\n        if hasattr(self, '_encoding'):\n            return self._encoding\n        if isinstance(self.content, six.text_type):\n            return 'unicode'\n        encoding = get_encoding(self.headers, self.content)\n        if not encoding and chardet is not None:\n            encoding = chardet.detect(self.content[:600])['encoding']\n        if encoding and encoding.lower() == 'gb2312':\n            encoding = 'gb18030'\n        self._encoding = encoding or 'utf-8'\n        return self._encoding",
    "docstring": "encoding of Response.content.\n\n        if Response.encoding is None, encoding will be guessed\n        by header or content or chardet if available."
  },
  {
    "code": "def update_settings(self, service_id, version_number, settings={}):\n\t\tbody = urllib.urlencode(settings)\n\t\tcontent = self._fetch(\"/service/%s/version/%d/settings\" % (service_id, version_number), method=\"PUT\", body=body)\n\t\treturn FastlySettings(self, content)",
    "docstring": "Update the settings for a particular service and version."
  },
  {
    "code": "def localize(self, location=None, latitude=None, longitude=None,\n                 **kwargs):\n        if location is None:\n            location = Location(latitude, longitude, **kwargs)\n        return LocalizedPVSystem(pvsystem=self, location=location)",
    "docstring": "Creates a LocalizedPVSystem object using this object\n        and location data. Must supply either location object or\n        latitude, longitude, and any location kwargs\n\n        Parameters\n        ----------\n        location : None or Location, default None\n        latitude : None or float, default None\n        longitude : None or float, default None\n        **kwargs : see Location\n\n        Returns\n        -------\n        localized_system : LocalizedPVSystem"
  },
  {
    "code": "def tokens(self):\n        spans = self.word_tokenizer.span_tokenize(self.text)\n        toks = [Token(\n            text=self.text[span[0]:span[1]],\n            start=span[0] + self.start,\n            end=span[1] + self.start,\n            lexicon=self.lexicon\n        ) for span in spans]\n        return toks",
    "docstring": "Return a list of token Spans for this sentence."
  },
  {
    "code": "def add_defaults(self, ctype: ContentType = None) -> \"InstanceNode\":\n        val = self.value\n        if not (isinstance(val, StructuredValue) and self.is_internal()):\n            return self\n        res = self\n        if isinstance(val, ObjectValue):\n            if val:\n                for mn in self._member_names():\n                    m = res._member(mn) if res is self else res.sibling(mn)\n                    res = m.add_defaults(ctype)\n                res = res.up()\n            return self.schema_node._add_defaults(res, ctype)\n        if not val:\n            return res\n        en = res[0]\n        while True:\n            res = en.add_defaults(ctype)\n            try:\n                en = res.next()\n            except NonexistentInstance:\n                break\n        return res.up()",
    "docstring": "Return the receiver with defaults added recursively to its value.\n\n        Args:\n            ctype: Content type of the defaults to be added. If it is\n                ``None``, the content type will be the same as receiver's."
  },
  {
    "code": "def cached(func):\n    ret = None\n    def call_or_cache(*args, **kwargs):\n        nonlocal ret\n        if ret is None:\n            ret = func(*args, **kwargs)\n        return ret\n    return call_or_cache",
    "docstring": "Memoize a function result."
  },
  {
    "code": "def buy(self, currencyPair, rate, amount, fillOrKill=None,\n            immediateOrCancel=None, postOnly=None):\n        return self._private('buy', currencyPair=currencyPair, rate=rate,\n                             amount=amount, fillOrKill=fillOrKill,\n                             immediateOrCancel=immediateOrCancel,\n                             postOnly=postOnly)",
    "docstring": "Places a limit buy order in a given market. Required POST parameters\n        are \"currencyPair\", \"rate\", and \"amount\". If successful, the method\n        will return the order number.\n        You may optionally set \"fillOrKill\", \"immediateOrCancel\", \"postOnly\"\n        to 1. A fill-or-kill order will either fill in its entirety or be\n        completely aborted. An immediate-or-cancel order can be partially or\n        completely filled, but any portion of the order that cannot be filled\n        immediately will be canceled rather than left on the order book.\n        A post-only order will only be placed if no portion of it fills\n        immediately; this guarantees you will never pay the taker fee on any\n        part of the order that fills."
  },
  {
    "code": "def convert_md_to_rst(md_path, rst_temp_path):\n    command = \"pandoc --write=rst --output=%s %s\" % (rst_temp_path, md_path)\n    print(\"converting with pandoc: %s to %s\\n-->%s\" % (md_path, rst_temp_path,\n                                                       command))\n    if os.path.exists(rst_temp_path):\n        os.remove(rst_temp_path)\n    os.system(command)\n    if not os.path.exists(rst_temp_path):\n        s = (\"Error running: %s\\n\"\n             \"  Did you install pandoc per the %s docstring?\" % (command,\n                                                                 __file__))\n        sys.exit(s)\n    return read(rst_temp_path)",
    "docstring": "Convert the contents of a file from Markdown to reStructuredText.\n\n    Returns the converted text as a Unicode string.\n\n    Arguments:\n\n      md_path: a path to a UTF-8 encoded Markdown file to convert.\n\n      rst_temp_path: a temporary path to which to write the converted contents."
  },
  {
    "code": "def from_list(cls, values):\n        self = cls()\n        for value in values:\n            self.add(value)\n        return self",
    "docstring": "Construct a tree from a list with paths."
  },
  {
    "code": "def get_all_filters(self, server_id):\n        server = self._get_server(server_id)\n        return server.conn.EnumerateInstances('CIM_IndicationFilter',\n                                              namespace=server.interop_ns)",
    "docstring": "Return all indication filters in a WBEM server.\n\n        This function contacts the WBEM server and retrieves the indication\n        filters by enumerating the instances of CIM class\n        \"CIM_IndicationFilter\" in the Interop namespace of the WBEM server.\n\n        Parameters:\n\n          server_id (:term:`string`):\n            The server ID of the WBEM server, returned by\n            :meth:`~pywbem.WBEMSubscriptionManager.add_server`.\n\n        Returns:\n\n            :class:`py:list` of :class:`~pywbem.CIMInstance`: The indication\n            filter instances.\n\n        Raises:\n\n            Exceptions raised by :class:`~pywbem.WBEMConnection`."
  },
  {
    "code": "def get_named_by_definition(cls, element_list, string_def):\n        try:\n            return next(\n                (\n                    st.value\n                    for st in element_list\n                    if st.definition == string_def\n                )\n            )\n        except Exception:\n            return None",
    "docstring": "Attempts to get an IOOS definition from a list of xml elements"
  },
  {
    "code": "def html_init(name):\n    result = \"\"\n    result += \"<html>\\n\"\n    result += \"<head>\\n\"\n    result += \"<title>\" + str(name) + \"</title>\\n\"\n    result += \"</head>\\n\"\n    result += \"<body>\\n\"\n    result += '<h1 style=\"border-bottom:1px solid ' \\\n              'black;text-align:center;\">PyCM Report</h1>'\n    return result",
    "docstring": "Return HTML report file first lines.\n\n    :param name: name of file\n    :type name : str\n    :return: html_init as str"
  },
  {
    "code": "def add_lambda_permissions(function='',\n                           statement_id='',\n                           action='lambda:InvokeFunction',\n                           principal='',\n                           source_arn='',\n                           env='',\n                           region='us-east-1'):\n    session = boto3.Session(profile_name=env, region_name=region)\n    lambda_client = session.client('lambda')\n    response_action = None\n    prefixed_sid = FOREMAST_PREFIX + statement_id\n    add_permissions_kwargs = {\n        'FunctionName': function,\n        'StatementId': prefixed_sid,\n        'Action': action,\n        'Principal': principal,\n    }\n    if source_arn:\n        add_permissions_kwargs['SourceArn'] = source_arn\n    try:\n        lambda_client.add_permission(**add_permissions_kwargs)\n        response_action = 'Add permission with Sid: {}'.format(prefixed_sid)\n    except boto3.exceptions.botocore.exceptions.ClientError as error:\n        LOG.debug('Add permission error: %s', error)\n        response_action = \"Did not add permissions\"\n    LOG.debug('Related StatementId (SID): %s', prefixed_sid)\n    LOG.info(response_action)",
    "docstring": "Add permission to Lambda for the event trigger.\n\n    Args:\n        function (str): Lambda function name\n        statement_id (str): IAM policy statement (principal) id\n        action (str): Lambda action to allow\n        principal (str): AWS principal to add permissions\n        source_arn (str): ARN of the source of the event. Only needed for S3\n        env (str): Environment/account of function\n        region (str): AWS region of function"
  },
  {
    "code": "def upload(self, filepath, service_path, remove=False):\n        local = OSFS(os.path.dirname(filepath))\n        if self.fs.hassyspath(service_path) and (\n            self.fs.getsyspath(service_path) == local.getsyspath(\n                os.path.basename(filepath))):\n            if remove:\n                os.remove(filepath)\n            return\n        if not self.fs.isdir(fs.path.dirname(service_path)):\n            self.fs.makedir(\n                fs.path.dirname(service_path),\n                recursive=True,\n                allow_recreate=True)\n        if remove:\n            fs.utils.movefile(\n                local,\n                os.path.basename(filepath),\n                self.fs,\n                service_path)\n        else:\n            fs.utils.copyfile(\n                local,\n                os.path.basename(filepath),\n                self.fs,\n                service_path)",
    "docstring": "\"Upload\" a file to a service\n\n        This copies a file from the local filesystem into the ``DataService``'s\n        filesystem. If ``remove==True``, the file is moved rather than copied.\n\n        If ``filepath`` and ``service_path`` paths are the same, ``upload``\n        deletes the file if ``remove==True`` and returns.\n\n        Parameters\n        ----------\n        filepath : str\n            Relative or absolute path to the file to be uploaded on the user's\n            filesystem\n\n        service_path: str\n            Path to the destination for the file on the ``DataService``'s\n            filesystem\n\n        remove : bool\n            If true, the file is moved rather than copied"
  },
  {
    "code": "def run(self, *args):\n        params = self.parser.parse_args(args)\n        sources = params.source\n        code = self.autocomplete(sources)\n        return code",
    "docstring": "Autocomplete profile information."
  },
  {
    "code": "def override_if_not_in_args(flag, argument, args):\n  if flag not in args:\n    args.extend([flag, argument])",
    "docstring": "Checks if flags is in args, and if not it adds the flag to args."
  },
  {
    "code": "def visit_raise(self, node, parent):\n        newnode = nodes.Raise(node.lineno, node.col_offset, parent)\n        newnode.postinit(\n            _visit_or_none(node, \"type\", self, newnode),\n            _visit_or_none(node, \"inst\", self, newnode),\n            _visit_or_none(node, \"tback\", self, newnode),\n        )\n        return newnode",
    "docstring": "visit a Raise node by returning a fresh instance of it"
  },
  {
    "code": "def _get_cache_key(self, obj):\n        if obj is not None:\n            return '{}-{}'.format(id(self), obj.pk)\n        return \"{}-None\".format(id(self))",
    "docstring": "Derive cache key for given object."
  },
  {
    "code": "def resource_update(sender, instance, created=False, **kwargs):\n    resource = instance\n    try:\n        new_configuration = CostTrackingRegister.get_configuration(resource)\n    except ResourceNotRegisteredError:\n        return\n    models.PriceEstimate.update_resource_estimate(\n        resource, new_configuration, raise_exception=not _is_in_celery_task())\n    if created:\n        _create_historical_estimates(resource, new_configuration)",
    "docstring": "Update resource consumption details and price estimate if its configuration has changed.\n        Create estimates for previous months if resource was created not in current month."
  },
  {
    "code": "def get_tags_from_job(user, job_id):\n    job = v1_utils.verify_existence_and_get(job_id, _TABLE)\n    if not user.is_in_team(job['team_id']) and not user.is_read_only_user():\n        raise dci_exc.Unauthorized()\n    JTT = models.JOIN_JOBS_TAGS\n    query = (sql.select([models.TAGS])\n             .select_from(JTT.join(models.TAGS))\n             .where(JTT.c.job_id == job_id))\n    rows = flask.g.db_conn.execute(query)\n    return flask.jsonify({'tags': rows, '_meta': {'count': rows.rowcount}})",
    "docstring": "Retrieve all tags attached to a job."
  },
  {
    "code": "def _pfp__handle_implicit_array(self, name, child):\n        existing_child = self._pfp__children_map[name]\n        if isinstance(existing_child, Array):\n            existing_child.append(child)\n            return existing_child\n        else:\n            cls = child._pfp__class if hasattr(child, \"_pfp__class\") else child.__class__\n            ary = Array(0, cls)\n            ary._pfp__offset = existing_child._pfp__offset\n            ary._pfp__parent = self\n            ary._pfp__name = name\n            ary.implicit = True\n            ary.append(existing_child)\n            ary.append(child)\n            exist_idx = -1\n            for idx,child in enumerate(self._pfp__children):\n                if child is existing_child:\n                    exist_idx = idx\n                    break\n            self._pfp__children[exist_idx] = ary\n            self._pfp__children_map[name] = ary\n            return ary",
    "docstring": "Handle inserting implicit array elements"
  },
  {
    "code": "def _extract(expr, pat, flags=0, group=0):\n    return _string_op(expr, Extract, _pat=pat, _flags=flags, _group=group)",
    "docstring": "Find group in each string in the Series using passed regular expression.\n\n    :param expr:\n    :param pat: Pattern or regular expression\n    :param flags: re module, e.g. re.IGNORECASE\n    :param group: if None as group 0\n    :return: sequence or scalar"
  },
  {
    "code": "def _getModules(self):\n        modules = {}\n        modulesPath = os.path.join(\"application\", \"module\")\n        moduleList = os.listdir(modulesPath)\n        for moduleName in moduleList:\n            modulePath = os.path.join(modulesPath, moduleName, \"module.py\")\n            if not os.path.isfile(modulePath):\n                continue\n            moduleSpec = importlib.util.spec_from_file_location(\n                moduleName,\n                modulePath\n            )\n            module = importlib.util.module_from_spec(moduleSpec)\n            moduleSpec.loader.exec_module(module)\n            moduleInstance = module.Module(self)\n            modules[moduleName] = moduleInstance\n        return modules",
    "docstring": "Import and load application modules.\n\n        :return: <dict>"
  },
  {
    "code": "def create_check(self, label=None, name=None, check_type=None,\n            disabled=False, metadata=None, details=None,\n            monitoring_zones_poll=None, timeout=None, period=None,\n            target_alias=None, target_hostname=None, target_receiver=None,\n            test_only=False, include_debug=False):\n        return self._check_manager.create_check(label=label, name=name,\n                check_type=check_type, disabled=disabled, metadata=metadata,\n                details=details, monitoring_zones_poll=monitoring_zones_poll,\n                timeout=timeout, period=period, target_alias=target_alias,\n                target_hostname=target_hostname,\n                target_receiver=target_receiver, test_only=test_only,\n                include_debug=include_debug)",
    "docstring": "Creates a check on this entity with the specified attributes. The\n        'details' parameter should be a dict with the keys as the option name,\n        and the value as the desired setting."
  },
  {
    "code": "def read(self, size=None):\n        if self.closed:\n            raise ValueError(\"I/O operation on closed file\")\n        buf = b\"\"\n        if self.buffer:\n            if size is None:\n                buf = self.buffer\n                self.buffer = b\"\"\n            else:\n                buf = self.buffer[:size]\n                self.buffer = self.buffer[size:]\n        if size is None:\n            buf += self.fileobj.read()\n        else:\n            buf += self.fileobj.read(size - len(buf))\n        self.position += len(buf)\n        return buf",
    "docstring": "Read at most size bytes from the file. If size is not\n           present or None, read all data until EOF is reached."
  },
  {
    "code": "def raise_error(self, error):\n        ex = exc.RPCError('Error calling remote procedure: %s' % error.error['message'])\n        if self.raises_errors:\n            raise ex\n        return ex",
    "docstring": "Raises the exception in the client.\n\n        Called by the client to convert the :py:class:`RPCErrorResponse` into an Exception\n        and raise or return it depending on the :py:attr:`raises_errors` attribute.\n\n        :param error: The error response received from the server.\n        :type error: :py:class:`RPCResponse`\n        :rtype: :py:exc:`~tinyrpc.exc.RPCError` when :py:attr:`raises_errors` is False.\n        :raises: :py:exc:`~tinyrpc.exc.RPCError` when :py:attr:`raises_errors` is True."
  },
  {
    "code": "def get_url_distribution(self, after=None, reports='true', limit=1000, timeout=None):\n        params = {'apikey': self.api_key, 'after': after, 'reports': reports, 'limit': limit}\n        try:\n            response = requests.get(self.base + 'url/distribution',\n                                    params=params,\n                                    proxies=self.proxies,\n                                    timeout=timeout)\n        except requests.RequestException as e:\n            return dict(error=str(e))\n        return _return_response_and_status_code(response)",
    "docstring": "Get a live feed with the lastest URLs submitted to VirusTotal.\n\n        Allows you to retrieve a live feed of URLs submitted to VirusTotal, along with their scan reports. This\n        call enables you to stay synced with VirusTotal URL submissions and replicate our dataset.\n\n        :param after: (optional) Retrieve URLs received after the given timestamp, in timestamp ascending order.\n        :param reports:  (optional) When set to \"true\" each item retrieved will include the results for each particular\n        URL scan (in exactly the same format as the URL scan retrieving API). If the parameter is not specified, each\n        item returned will only contain the scanned URL and its detection ratio.\n        :param limit: (optional) Retrieve limit file items at most (default: 1000).\n        :param timeout: The amount of time in seconds the request should wait before timing out.\n\n        :return: JSON response"
  },
  {
    "code": "def opt(self, x_init, f_fp=None, f=None, fp=None):\n        tnc_rcstrings = ['Local minimum', 'Converged', 'XConverged', 'Maximum number of f evaluations reached',\n             'Line search failed', 'Function is constant']\n        assert f_fp != None, \"TNC requires f_fp\"\n        opt_dict = {}\n        if self.xtol is not None:\n            opt_dict['xtol'] = self.xtol\n        if self.ftol is not None:\n            opt_dict['ftol'] = self.ftol\n        if self.gtol is not None:\n            opt_dict['pgtol'] = self.gtol\n        opt_result = optimize.fmin_tnc(f_fp, x_init, messages=self.messages,\n                       maxfun=self.max_f_eval, **opt_dict)\n        self.x_opt = opt_result[0]\n        self.f_opt = f_fp(self.x_opt)[0]\n        self.funct_eval = opt_result[1]\n        self.status = tnc_rcstrings[opt_result[2]]",
    "docstring": "Run the TNC optimizer"
  },
  {
    "code": "def main(jlink_serial, device):\n    buf = StringIO.StringIO()\n    jlink = pylink.JLink(log=buf.write, detailed_log=buf.write)\n    jlink.open(serial_no=jlink_serial)\n    jlink.set_tif(pylink.enums.JLinkInterfaces.SWD)\n    jlink.connect(device, verbose=True)\n    sys.stdout.write('ARM Id: %d\\n' % jlink.core_id())\n    sys.stdout.write('CPU Id: %d\\n' % jlink.core_cpu())\n    sys.stdout.write('Core Name: %s\\n' % jlink.core_name())\n    sys.stdout.write('Device Family: %d\\n' % jlink.device_family())",
    "docstring": "Prints the core's information.\n\n    Args:\n      jlink_serial (str): the J-Link serial number\n      device (str): the target CPU\n\n    Returns:\n      Always returns ``0``.\n\n    Raises:\n      JLinkException: on error"
  },
  {
    "code": "def adapt_meta(self, meta):\n        surge = meta.get('surge_confirmation')\n        href = surge.get('href')\n        surge_id = surge.get('surge_confirmation_id')\n        return href, surge_id",
    "docstring": "Convert meta from error response to href and surge_id attributes."
  },
  {
    "code": "def average(arr):\n  if len(arr) == 0:\n    sys.stderr.write(\"ERROR: no content in array to take average\\n\")\n    sys.exit()\n  if len(arr) == 1:  return arr[0]\n  return float(sum(arr))/float(len(arr))",
    "docstring": "average of the values, must have more than 0 entries.\n\n  :param arr: list of numbers\n  :type arr: number[] a number array\n  :return: average\n  :rtype: float"
  },
  {
    "code": "def _get_timethresh_heuristics(self):\n        if self.length > 1E5:\n            time_thresh = 2.5\n        elif self.length > 1E4:\n            time_thresh = 2.0\n        elif self.length > 1E3:\n            time_thresh = 1.0\n        else:\n            time_thresh = 0.5\n        return time_thresh",
    "docstring": "resonably decent hueristics for how much time to wait before\n        updating progress."
  },
  {
    "code": "def update_spec(self):\n        if self.datafile.exists:\n            with self.datafile.reader as r:\n                self.header_lines = r.info['header_rows']\n                self.comment_lines = r.info['comment_rows']\n                self.start_line = r.info['data_start_row']\n                self.end_line = r.info['data_end_row']",
    "docstring": "Update the source specification with information from the row intuiter, but only if the spec values\n        are not already set."
  },
  {
    "code": "def image_to_data(image,\n                  lang=None,\n                  config='',\n                  nice=0,\n                  output_type=Output.STRING):\n    if get_tesseract_version() < '3.05':\n        raise TSVNotSupported()\n    config = '{} {}'.format('-c tessedit_create_tsv=1', config.strip()).strip()\n    args = [image, 'tsv', lang, config, nice]\n    return {\n        Output.BYTES: lambda: run_and_get_output(*(args + [True])),\n        Output.DATAFRAME: lambda: get_pandas_output(args + [True]),\n        Output.DICT: lambda: file_to_dict(run_and_get_output(*args), '\\t', -1),\n        Output.STRING: lambda: run_and_get_output(*args),\n    }[output_type]()",
    "docstring": "Returns string containing box boundaries, confidences,\n    and other information. Requires Tesseract 3.05+"
  },
  {
    "code": "def free(self):\n        LOGGER.debug('Connection %s freeing', self.id)\n        if self.handle.isexecuting():\n            raise ConnectionBusyError(self)\n        with self._lock:\n            self.used_by = None\n        LOGGER.debug('Connection %s freed', self.id)",
    "docstring": "Remove the lock on the connection if the connection is not active\n\n        :raises: ConnectionBusyError"
  },
  {
    "code": "def addQuickElement(self, name, contents=None, attrs=None, escape=True, cdata=False):\n        if attrs is None:\n            attrs = {}\n        self.startElement(name, attrs)\n        if contents is not None:\n            self.characters(contents, escape=escape, cdata=cdata)\n        self.endElement(name)",
    "docstring": "Convenience method for adding an element with no children."
  },
  {
    "code": "def BFS(G, start):\r\n    if start not in G.vertices:\r\n        raise GraphInsertError(\"Vertex %s doesn't exist.\" % (start,))\r\n    color = {}\r\n    pred = {}\r\n    dist = {}\r\n    queue = Queue()\r\n    queue.put(start)\r\n    for vertex in G.vertices:\r\n        color[vertex] = 'white'\r\n        pred[vertex] = None\r\n        dist[vertex] = 0\r\n    while queue.qsize() > 0:\r\n        current = queue.get()\r\n        for neighbor in G.vertices[current]:\r\n            if color[neighbor] == 'white':\r\n                color[neighbor] = 'grey'\r\n                pred[neighbor] = current\r\n                dist[neighbor] = dist[current] + 1\r\n                queue.put(neighbor)\r\n        color[current] = 'black'\r\n    return pred",
    "docstring": "Algorithm for breadth-first searching the vertices of a graph."
  },
  {
    "code": "def blobs(self, repository_ids=[], reference_names=[], commit_hashes=[]):\n        if not isinstance(repository_ids, list):\n            raise Exception(\"repository_ids must be a list\")\n        if not isinstance(reference_names, list):\n            raise Exception(\"reference_names must be a list\")\n        if not isinstance(commit_hashes, list):\n            raise Exception(\"commit_hashes must be a list\")\n        return BlobsDataFrame(self.__engine.getBlobs(repository_ids,\n                                                  reference_names,\n                                                  commit_hashes),\n                              self.session,\n                              self.__implicits)",
    "docstring": "Retrieves the blobs of a list of repositories, reference names and commit hashes.\n        So the result will be a DataFrame of all the blobs in the given commits that are\n        in the given references that belong to the given repositories.\n\n        >>> blobs_df = engine.blobs(repo_ids, ref_names, hashes)\n\n        Calling this function with no arguments is the same as:\n\n        >>> engine.repositories.references.commits.tree_entries.blobs\n\n        :param repository_ids: list of repository ids to filter by (optional)\n        :type repository_ids: list of strings\n        :param reference_names: list of reference names to filter by (optional)\n        :type reference_names: list of strings\n        :param commit_hashes: list of hashes to filter by (optional)\n        :type commit_hashes: list of strings\n        :rtype: BlobsDataFrame"
  },
  {
    "code": "def update_safe(filename: str, **kw: Any) -> Generator[IO, None, None]:\n    with tempfile.NamedTemporaryFile(\n        dir=os.path.dirname(filename),\n        delete=False,\n        prefix=f\"{os.path.basename(filename)}.\",\n        **kw,\n    ) as tf:\n        if os.path.exists(filename):\n            os.chmod(tf.name, os.stat(filename).st_mode & 0o7777)\n        tf.has_changed = False\n        yield tf\n        if not os.path.exists(tf.name):\n            return\n        filename_tmp = tf.name\n    if os.path.exists(filename) and filecmp.cmp(filename, filename_tmp, shallow=False):\n        os.unlink(filename_tmp)\n    else:\n        os.rename(filename_tmp, filename)\n        tf.has_changed = True",
    "docstring": "Rewrite a file atomically.\n\n    Clients are allowed to delete the tmpfile to signal that they don't\n    want to have it updated."
  },
  {
    "code": "def whois_emails(self, emails):\n        api_name = 'opendns-whois-emails'\n        fmt_url_path = u'whois/emails/{0}'\n        return self._multi_get(api_name, fmt_url_path, emails)",
    "docstring": "Calls WHOIS Email end point\n\n        Args:\n            emails: An enumerable of string Emails\n        Returns:\n            A dict of {email: domain_result}"
  },
  {
    "code": "async def make_response(self, result: ResponseReturnValue) -> Response:\n        status_or_headers = None\n        headers = None\n        status = None\n        if isinstance(result, tuple):\n            value, status_or_headers, headers = result + (None,) * (3 - len(result))\n        else:\n            value = result\n        if value is None:\n            raise TypeError('The response value returned by the view function cannot be None')\n        if isinstance(status_or_headers, (dict, list)):\n            headers = status_or_headers\n            status = None\n        elif status_or_headers is not None:\n            status = status_or_headers\n        if not isinstance(value, Response):\n            response = self.response_class(\n                value, timeout=self.config['RESPONSE_TIMEOUT'],\n            )\n        else:\n            response = value\n        if status is not None:\n            response.status_code = status\n        if headers is not None:\n            response.headers.update(headers)\n        return response",
    "docstring": "Make a Response from the result of the route handler.\n\n        The result itself can either be:\n          - A Response object (or subclass).\n          - A tuple of a ResponseValue and a header dictionary.\n          - A tuple of a ResponseValue, status code and a header dictionary.\n\n        A ResponseValue is either a Response object (or subclass) or a str."
  },
  {
    "code": "def cache(horizon):\n    def cache_step(func):\n        @wraps(func)\n        def cached(*args):\n            try:\n                data = func.__globals__['__data']\n                assert cached.cache_t == data['time']()\n                assert hasattr(cached, 'cache_val')\n                assert cached.cache_val is not None\n            except (AssertionError, AttributeError):\n                cached.cache_val = func(*args)\n                data = func.__globals__['__data']\n                cached.cache_t = data['time']()\n            return cached.cache_val\n        return cached\n    def cache_run(func):\n        @wraps(func)\n        def cached(*args):\n            try:\n                return cached.cache_val\n            except AttributeError:\n                cached.cache_val = func(*args)\n                return cached.cache_val\n        return cached\n    if horizon == 'step':\n        return cache_step\n    elif horizon == 'run':\n        return cache_run\n    else:\n        raise (AttributeError('Bad horizon for cache decorator'))",
    "docstring": "Put a wrapper around a model function\n\n    Decorators with parameters are tricky, you have to\n    essentially create a decorator that returns a decorator,\n    which itself then returns the function wrapper.\n\n    Parameters\n    ----------\n    horizon: string\n        - 'step' means cache just until the next timestep\n        - 'run' means cache until the next initialization of the model\n\n    Returns\n    -------\n    new_func: decorated function\n        function wrapping the original function, handling caching"
  },
  {
    "code": "def FromStream(cls, stream):\n        if stream.system:\n            specifier = DataStreamSelector.MatchSystemOnly\n        else:\n            specifier = DataStreamSelector.MatchUserOnly\n        return DataStreamSelector(stream.stream_type, stream.stream_id, specifier)",
    "docstring": "Create a DataStreamSelector from a DataStream.\n\n        Args:\n            stream (DataStream): The data stream that we want to convert."
  },
  {
    "code": "def login(self, username, password=None, email=None, registry=None, reauth=False, **kwargs):\n        response = super(DockerClientWrapper, self).login(username, password, email, registry, reauth=reauth, **kwargs)\n        return response.get('Status') == 'Login Succeeded' or response.get('username') == username",
    "docstring": "Login to a Docker registry server.\n\n        :param username: User name for login.\n        :type username: unicode | str\n        :param password: Login password; may be ``None`` if blank.\n        :type password: unicode | str\n        :param email: Optional; email address for login.\n        :type email: unicode | str\n        :param registry: Optional registry URL to log in to. Uses the Docker index by default.\n        :type registry: unicode | str\n        :param reauth: Re-authenticate, even if the login has been successful before.\n        :type reauth: bool\n        :param kwargs: Additional kwargs to :meth:`docker.client.Client.login`.\n        :return: ``True`` if the login has succeeded, or if it has not been necessary as it succeeded before. ``False``\n          otherwise.\n        :rtype: bool"
  },
  {
    "code": "def type(self, s, enter=False, clear=False):\n        if clear:\n            self.clear_text()\n        self._uiauto.send_keys(s)\n        if enter:\n            self.keyevent('KEYCODE_ENTER')",
    "docstring": "Input some text, this method has been tested not very stable on some device.\n        \"Hi world\" maybe spell into \"H iworld\"\n\n        Args:\n            - s: string (text to input), better to be unicode\n            - enter(bool): input enter at last\n            - next(bool): perform editor action Next\n            - clear(bool): clear text before type\n            - ui_select_kwargs(**): tap then type\n\n        The android source code show that\n        space need to change to %s\n        insteresting thing is that if want to input %s, it is really unconvinent.\n        android source code can be found here.\n        https://android.googlesource.com/platform/frameworks/base/+/android-4.4.2_r1/cmds/input/src/com/android/commands/input/Input.java#159\n        app source see here: https://github.com/openatx/android-unicode"
  },
  {
    "code": "def delete(self, path):\n        return self.session.delete(self._request_url(path),\n                                   auth=self.auth, verify=False)",
    "docstring": "Call the Infoblox device to delete the ref\n\n        :param str ref: The reference id\n        :rtype: requests.Response"
  },
  {
    "code": "def add_child(self, node, callback):\n        if node not in self.children:\n            self.children.append(ChildNode(node, callback))",
    "docstring": "Add node and callback to the children set."
  },
  {
    "code": "def get_all_tasks(conf):\n    db = HamsterDB(conf)\n    fact_list = db.all_facts_id\n    security_days = int(conf.get_option('tasks.security_days'))\n    today = datetime.today()\n    tasks = {}\n    for fact_id in fact_list:\n        ht = HamsterTask(fact_id, conf, db)\n        if ht.end_time:\n            end_time = ht.get_object_dates()[1]\n            if today - timedelta(security_days) <= end_time:\n                rt = ht.get_remote_task()\n                tasks[rt.task_id] = rt\n    db.close_connection()\n    print 'Obtained %d tasks' % len(tasks)\n    return tasks",
    "docstring": "Returns a list with every task registred on Hamster."
  },
  {
    "code": "def Rx_matrix(theta):\n    return np.array([\n        [1, 0, 0],\n        [0, np.cos(theta), -np.sin(theta)],\n        [0, np.sin(theta), np.cos(theta)]\n    ])",
    "docstring": "Rotation matrix around the X axis"
  },
  {
    "code": "def getusers(self, userlist):\n        userobjs = [User(self, **rawuser) for rawuser in\n                    self._getusers(names=userlist).get('users', [])]\n        ret = []\n        for u in userlist:\n            for uobj in userobjs[:]:\n                if uobj.email == u:\n                    userobjs.remove(uobj)\n                    ret.append(uobj)\n                    break\n        ret += userobjs\n        return ret",
    "docstring": "Return a list of Users from .\n\n        :userlist: List of usernames to lookup\n        :returns: List of User records"
  },
  {
    "code": "def get_url(url):\n    sub = \"{0}.spotilocal.com\".format(\"\".join(choices(ascii_lowercase, k=10)))\n    return \"http://{0}:{1}{2}\".format(sub, DEFAULT_PORT, url)",
    "docstring": "Ranomdly generates a url for use in requests.\n    Generates a hostname with the port and the provided suffix url provided\n\n    :param url: A url fragment to use in the creation of the master url"
  },
  {
    "code": "def LoadData(self, data, custom_properties=None):\n    self.__data = []\n    self.AppendData(data, custom_properties)",
    "docstring": "Loads new rows to the data table, clearing existing rows.\n\n    May also set the custom_properties for the added rows. The given custom\n    properties dictionary specifies the dictionary that will be used for *all*\n    given rows.\n\n    Args:\n      data: The rows that the table will contain.\n      custom_properties: A dictionary of string to string to set as the custom\n                         properties for all rows."
  },
  {
    "code": "def gen_jcc(src, dst):\n        return ReilBuilder.build(ReilMnemonic.JCC, src, ReilEmptyOperand(), dst)",
    "docstring": "Return a JCC instruction."
  },
  {
    "code": "def get_offset_with_default(cursor=None, default_offset=0):\n    if not is_str(cursor):\n        return default_offset\n    offset = cursor_to_offset(cursor)\n    try:\n        return int(offset)\n    except:\n        return default_offset",
    "docstring": "Given an optional cursor and a default offset, returns the offset\n    to use; if the cursor contains a valid offset, that will be used,\n    otherwise it will be the default."
  },
  {
    "code": "def balance(self):\n        self.check()\n        if not sum(map(lambda x: x.amount, self.src)) == -self.amount:\n            raise XnBalanceError(\"Sum of source amounts \"\n                                 \"not equal to transaction amount\")\n        if not sum(map(lambda x: x.amount, self.dst)) == self.amount:\n            raise XnBalanceError(\"Sum of destination amounts \"\n                                 \"not equal to transaction amount\")\n        return True",
    "docstring": "Check this transaction for correctness"
  },
  {
    "code": "def get_keys_to_action(self):\n    keyword_to_key = {\n        \"UP\": ord(\"w\"),\n        \"DOWN\": ord(\"s\"),\n        \"LEFT\": ord(\"a\"),\n        \"RIGHT\": ord(\"d\"),\n        \"FIRE\": ord(\" \"),\n    }\n    keys_to_action = {}\n    for action_id, action_meaning in enumerate(self.action_meanings):\n      keys_tuple = tuple(sorted([\n          key for keyword, key in keyword_to_key.items()\n          if keyword in action_meaning]))\n      assert keys_tuple not in keys_to_action\n      keys_to_action[keys_tuple] = action_id\n    keys_to_action[(ord(\"r\"),)] = self.RETURN_DONE_ACTION\n    keys_to_action[(ord(\"c\"),)] = self.TOGGLE_WAIT_ACTION\n    keys_to_action[(ord(\"n\"),)] = self.WAIT_MODE_NOOP_ACTION\n    return keys_to_action",
    "docstring": "Get mapping from keyboard keys to actions.\n\n    Required by gym.utils.play in environment or top level wrapper.\n\n    Returns:\n      {\n        Unicode code point for keyboard key: action (formatted for step()),\n        ...\n      }"
  },
  {
    "code": "def read(self, n=4096):\n        size = self._next_packet_size(n)\n        if size <= 0:\n            return\n        else:\n            data = six.binary_type()\n            while len(data) < size:\n                nxt = self.stream.read(size - len(data))\n                if not nxt:\n                    return data\n                data = data + nxt\n            return data",
    "docstring": "Read up to `n` bytes of data from the Stream, after demuxing.\n\n        Less than `n` bytes of data may be returned depending on the available\n        payload, but the number of bytes returned will never exceed `n`.\n\n        Because demuxing involves scanning 8-byte headers, the actual amount of\n        data read from the underlying stream may be greater than `n`."
  },
  {
    "code": "def AddLabels(self, labels_names, owner=None):\n    if owner is None and not self.token:\n      raise ValueError(\"Can't set label: No owner specified and \"\n                       \"no access token available.\")\n    if isinstance(labels_names, string_types):\n      raise ValueError(\"Label list can't be string.\")\n    owner = owner or self.token.username\n    current_labels = self.Get(self.Schema.LABELS, self.Schema.LABELS())\n    for label_name in labels_names:\n      label = rdf_aff4.AFF4ObjectLabel(\n          name=label_name, owner=owner, timestamp=rdfvalue.RDFDatetime.Now())\n      current_labels.AddLabel(label)\n    self.Set(current_labels)",
    "docstring": "Add labels to the AFF4Object."
  },
  {
    "code": "def init_db(db_path):\n    logger.info(\"Creating database\")\n    with closing(connect_database(db_path)) as db:\n        with open(SCHEMA, 'r') as f:\n            db.cursor().executescript(f.read())\n        db.commit()\n    return",
    "docstring": "Build the sqlite database"
  },
  {
    "code": "def send(dest, msg, transactionid=None):\n    transheader = ''\n    if transactionid:\n        transheader = 'transaction: %s\\n' % transactionid\n    return \"SEND\\ndestination: %s\\n%s\\n%s\\x00\\n\" % (dest, transheader, msg)",
    "docstring": "STOMP send command.\n\n    dest:\n        This is the channel we wish to subscribe to\n\n    msg:\n        This is the message body to be sent.\n\n    transactionid:\n        This is an optional field and is not needed\n        by default."
  },
  {
    "code": "def ways_callback(self, data):\n        for way_id, tags, nodes in data:\n            if tags:\n                self.ways[way_id] = (tags, nodes)",
    "docstring": "Callback for all ways"
  },
  {
    "code": "def bm3_p(v, v0, k0, k0p, p_ref=0.0):\n    return cal_p_bm3(v, [v0, k0, k0p], p_ref=p_ref)",
    "docstring": "calculate pressure from 3rd order Birch-Murnathan equation\n\n    :param v: volume at different pressures\n    :param v0: volume at reference conditions\n    :param k0: bulk modulus at reference conditions\n    :param k0p: pressure derivative of bulk modulus at different conditions\n    :param p_ref: reference pressure (default = 0)\n    :return: pressure"
  },
  {
    "code": "def walk_paths(self,\n                   base: Optional[pathlib.PurePath] = pathlib.PurePath()) \\\n            -> Iterator[pathlib.PurePath]:\n        raise NotImplementedError()",
    "docstring": "Recursively traverse all paths inside this entity, including the entity\n        itself.\n\n        :param base: The base path to prepend to the entity name.\n        :return: An iterator of paths."
  },
  {
    "code": "def _recursive_matches(self, nodes, count):\n        assert self.content is not None\n        if count >= self.min:\n            yield 0, {}\n        if count < self.max:\n            for alt in self.content:\n                for c0, r0 in generate_matches(alt, nodes):\n                    for c1, r1 in self._recursive_matches(nodes[c0:], count+1):\n                        r = {}\n                        r.update(r0)\n                        r.update(r1)\n                        yield c0 + c1, r",
    "docstring": "Helper to recursively yield the matches."
  },
  {
    "code": "def recursive_copy(source, dest):\n    for root, _, files in salt.utils.path.os_walk(source):\n        path_from_source = root.replace(source, '').lstrip(os.sep)\n        target_directory = os.path.join(dest, path_from_source)\n        if not os.path.exists(target_directory):\n            os.makedirs(target_directory)\n        for name in files:\n            file_path_from_source = os.path.join(source, path_from_source, name)\n            target_path = os.path.join(target_directory, name)\n            shutil.copyfile(file_path_from_source, target_path)",
    "docstring": "Recursively copy the source directory to the destination,\n    leaving files with the source does not explicitly overwrite.\n\n    (identical to cp -r on a unix machine)"
  },
  {
    "code": "def describe(self):\r\n        lines = []\r\n        lines.append(\"Symbol = {}\".format(self.name))\r\n        if len(self.tags):\r\n            tgs = \", \".join(x.tag for x in self.tags)\r\n            lines.append(\"  tagged = {}\".format(tgs))\r\n        if len(self.aliases):\r\n            als = \", \".join(x.alias for x in self.aliases)\r\n            lines.append(\"  aliased = {}\".format(als))\r\n        if len(self.feeds):\r\n            lines.append(\"  feeds:\")\r\n            for fed in self.feeds:\r\n                lines.append(\"    {}. {}\".format(fed.fnum,\r\n                                                       fed.ftype))\r\n        return \"\\n\".join(lines)",
    "docstring": "describes a Symbol, returns a string"
  },
  {
    "code": "def apply_fixes(args, tmpdir):\n  invocation = [args.clang_apply_replacements_binary]\n  if args.format:\n    invocation.append('-format')\n  if args.style:\n    invocation.append('-style=' + args.style)\n  invocation.append(tmpdir)\n  subprocess.call(invocation)",
    "docstring": "Calls clang-apply-fixes on a given directory."
  },
  {
    "code": "def main():\n    from six import StringIO\n    import eppy.iddv7 as iddv7\n    IDF.setiddname(StringIO(iddv7.iddtxt))\n    idf1 = IDF(StringIO(''))\n    loopname = \"p_loop\"\n    sloop = ['sb0', ['sb1', 'sb2', 'sb3'], 'sb4']\n    dloop = ['db0', ['db1', 'db2', 'db3'], 'db4']\n    loopname = \"c_loop\"\n    sloop = ['sb0', ['sb1', 'sb2', 'sb3'], 'sb4']\n    dloop = ['db0', ['db1', 'db2', 'db3'], 'db4']\n    loopname = \"a_loop\"\n    sloop = ['sb0', ['sb1', 'sb2', 'sb3'], 'sb4']\n    dloop = ['zone1', 'zone2', 'zone3']\n    makeairloop(idf1, loopname, sloop, dloop)\n    idf1.savecopy(\"hh1.idf\")",
    "docstring": "the main routine"
  },
  {
    "code": "def unravel_staff(staff_data):\n        staff_list = []\n        for role, staff_members in staff_data['data'].items():\n            for member in staff_members:\n                member['role'] = role\n                staff_list.append(member)\n        return staff_list",
    "docstring": "Unravels staff role dictionary into flat list of staff\n         members with ``role`` set as an attribute.\n\n        Args:\n            staff_data(dict): Data return from py:method::get_staff\n\n        Returns:\n            list: Flat list of staff members with ``role`` set to\n                role type (i.e. course_admin, instructor, TA, etc)"
  },
  {
    "code": "def etd_ms_dict2xmlfile(filename, metadata_dict):\n    try:\n        f = open(filename, 'w')\n        f.write(generate_etd_ms_xml(metadata_dict).encode(\"utf-8\"))\n        f.close()\n    except:\n        raise MetadataGeneratorException(\n            'Failed to create an XML file. Filename: %s' % (filename)\n        )",
    "docstring": "Create an ETD MS XML file."
  },
  {
    "code": "def _get_uniparc_sequences_through_uniprot_ACs(self, mapping_pdb_id, uniprot_ACs, cache_dir):\n        m = uniprot_map('ACC', 'UPARC', uniprot_ACs, cache_dir = cache_dir)\n        UniParcIDs = []\n        for _, v in m.iteritems():\n            UniParcIDs.extend(v)\n        mapping = {mapping_pdb_id : []}\n        for UniParcID in UniParcIDs:\n            entry = UniParcEntry(UniParcID, cache_dir = cache_dir)\n            mapping[mapping_pdb_id].append(entry)\n        return mapping",
    "docstring": "Get the UniParc sequences associated with the UniProt accession number."
  },
  {
    "code": "def BLASTcheck(rid,baseURL=\"http://blast.ncbi.nlm.nih.gov\"):\n    URL=baseURL+\"/Blast.cgi?\"\n    URL=URL+\"FORMAT_OBJECT=SearchInfo&RID=\"+rid+\"&CMD=Get\"\n    response=requests.get(url = URL)\n    r=response.content.split(\"\\n\")\n    try:\n        status=[ s for s in r if \"Status=\" in s ][0].split(\"=\")[-1]\n        ThereAreHits=[ s for s in r if \"ThereAreHits=\" in s ][0].split(\"=\")[-1]\n    except:\n        status=None\n        ThereAreHits=None\n    print(rid, status, ThereAreHits)\n    sys.stdout.flush()\n    return status, ThereAreHits",
    "docstring": "Checks the status of a query.\n\n    :param rid: BLAST search request identifier. Allowed values: The Request ID (RID) returned when the search was submitted\n    :param baseURL: server url. Default=http://blast.ncbi.nlm.nih.gov\n\n    :returns status: status for the query.\n    :returns therearehist: yes or no for existing hits on a finished query."
  },
  {
    "code": "def on_source_directory_chooser_clicked(self):\n        title = self.tr('Set the source directory for script and scenario')\n        self.choose_directory(self.source_directory, title)",
    "docstring": "Autoconnect slot activated when tbSourceDir is clicked."
  },
  {
    "code": "def get_template_image(kwargs=None, call=None):\n    if call == 'action':\n        raise SaltCloudSystemExit(\n            'The get_template_image function must be called with -f or --function.'\n        )\n    if kwargs is None:\n        kwargs = {}\n    name = kwargs.get('name', None)\n    if name is None:\n        raise SaltCloudSystemExit(\n            'The get_template_image function requires a \\'name\\'.'\n        )\n    try:\n        ret = list_templates()[name]['template']['disk']['image']\n    except KeyError:\n        raise SaltCloudSystemExit(\n            'The image for template \\'{0}\\' could not be found.'.format(name)\n        )\n    return ret",
    "docstring": "Returns a template's image from the given template name.\n\n    .. versionadded:: 2018.3.0\n\n    .. code-block:: bash\n\n        salt-cloud -f get_template_image opennebula name=my-template-name"
  },
  {
    "code": "def calculate_mean(self, pars_for_mean, calculation_type):\n        if len(pars_for_mean) == 0:\n            return({})\n        elif len(pars_for_mean) == 1:\n            return ({\"dec\": float(pars_for_mean[0]['dec']), \"inc\": float(pars_for_mean[0]['inc']), \"calculation_type\": calculation_type, \"n\": 1})\n        elif calculation_type == 'Fisher':\n            mpars = pmag.dolnp(pars_for_mean, 'direction_type')\n        elif calculation_type == 'Fisher by polarity':\n            mpars = pmag.fisher_by_pol(pars_for_mean)\n            for key in list(mpars.keys()):\n                mpars[key]['n_planes'] = 0\n                mpars[key]['calculation_type'] = 'Fisher'\n        mpars['calculation_type'] = calculation_type\n        return mpars",
    "docstring": "Uses pmag.dolnp or pmag.fisher_by_pol to do a fisher mean or fisher\n        mean by polarity on the list of dictionaries in pars for mean\n\n        Parameters\n        ----------\n        pars_for_mean : list of dictionaries with all data to average\n        calculation_type : type of mean to take (options: Fisher,\n        Fisher by polarity)\n\n        Returns\n        -------\n        mpars : dictionary with information of mean or empty dictionary\n\n        TODO : put Bingham statistics back in once a method for displaying\n        them is figured out"
  },
  {
    "code": "def arrange(df, *args, **kwargs):\n    flat_args = [a for a in flatten(args)]\n    series = [df[arg] if isinstance(arg, str) else\n              df.iloc[:, arg] if isinstance(arg, int) else\n              pd.Series(arg) for arg in flat_args]\n    sorter = pd.concat(series, axis=1).reset_index(drop=True)\n    sorter = sorter.sort_values(sorter.columns.tolist(), **kwargs)\n    return df.iloc[sorter.index, :]",
    "docstring": "Calls `pandas.DataFrame.sort_values` to sort a DataFrame according to\n    criteria.\n\n    See:\n    http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html\n\n    For a list of specific keyword arguments for sort_values (which will be\n    the same in arrange).\n\n    Args:\n        *args: Symbolic, string, integer or lists of those types indicating\n            columns to sort the DataFrame by.\n\n    Kwargs:\n        **kwargs: Any keyword arguments will be passed through to the pandas\n            `DataFrame.sort_values` function."
  },
  {
    "code": "def max_cation_removal(self):\n        oxid_pot = sum(\n            [(Element(spec.symbol).max_oxidation_state - spec.oxi_state) * self.comp[spec] for spec\n             in self.comp if is_redox_active_intercalation(Element(spec.symbol))])\n        oxid_limit = oxid_pot / self.cation_charge\n        num_cation = self.comp[Specie(self.cation.symbol, self.cation_charge)]\n        return min(oxid_limit, num_cation)",
    "docstring": "Maximum number of cation A that can be removed while maintaining charge-balance.\n\n        Returns:\n            integer amount of cation. Depends on cell size (this is an 'extrinsic' function!)"
  },
  {
    "code": "def spine_to_terminal_wedge(mol):\n    for i, a in mol.atoms_iter():\n        if mol.neighbor_count(i) == 1:\n            ni, nb = list(mol.neighbors(i).items())[0]\n            if nb.order == 1 and nb.type in (1, 2) \\\n                    and ni > i != nb.is_lower_first:\n                nb.is_lower_first = not nb.is_lower_first\n                nb.type = {1: 2, 2: 1}[nb.type]",
    "docstring": "Arrange stereo wedge direction from spine to terminal atom"
  },
  {
    "code": "def copy(self, *, frame=None, form=None):\n        new_compl = {}\n        for k, v in self.complements.items():\n            new_compl[k] = v.copy() if hasattr(v, 'copy') else v\n        new_obj = self.__class__(\n            self.date, self.base.copy(), self.form,\n            self.frame, self.propagator.copy() if self.propagator is not None else None,\n            **new_compl\n        )\n        if frame and frame != self.frame:\n            new_obj.frame = frame\n        if form and form != self.form:\n            new_obj.form = form\n        return new_obj",
    "docstring": "Provide a new instance of the same point in space-time\n\n        Keyword Args:\n            frame (str or Frame): Frame to convert the new instance into\n            form (str or Form): Form to convert the new instance into\n        Return:\n            Orbit:\n\n        Override :py:meth:`numpy.ndarray.copy()` to include additional\n        fields"
  },
  {
    "code": "def _mappingGetValueSet(mapping, keys):\n    setUnion = set()\n    for k in keys:\n        setUnion = setUnion.union(mapping[k])\n    return setUnion",
    "docstring": "Return a combined set of values from the mapping.\n\n    :param mapping: dict, for each key contains a set of entries\n\n    returns a set of combined entries"
  },
  {
    "code": "def validate_token_age(callback_token):\n    try:\n        token = CallbackToken.objects.get(key=callback_token, is_active=True)\n        seconds = (timezone.now() - token.created_at).total_seconds()\n        token_expiry_time = api_settings.PASSWORDLESS_TOKEN_EXPIRE_TIME\n        if seconds <= token_expiry_time:\n            return True\n        else:\n            token.is_active = False\n            token.save()\n            return False\n    except CallbackToken.DoesNotExist:\n        return False",
    "docstring": "Returns True if a given token is within the age expiration limit."
  },
  {
    "code": "def connections(self):\n        self._check_session()\n        status, data = self._rest.get_request('connections')\n        return data",
    "docstring": "Get list of connections."
  },
  {
    "code": "def PLAY(self):\n        message = \"PLAY \" + self.session.url + \" RTSP/1.0\\r\\n\"\n        message += self.sequence\n        message += self.authentication\n        message += self.user_agent\n        message += self.session_id\n        message += '\\r\\n'\n        return message",
    "docstring": "RTSP session is ready to send data."
  },
  {
    "code": "def add_option(self, parser):\n        group = parser.add_argument_group(self.name)\n        for stat in self.stats:\n            stat.add_option(group)\n        group.add_argument(\n            \"--{0}\".format(self.option), action=\"store_true\", help=\"All above\")",
    "docstring": "Add option group and all children options."
  },
  {
    "code": "def get_scenarios(network_id,**kwargs):\n    user_id = kwargs.get('user_id')\n    try:\n        net_i = db.DBSession.query(Network).filter(Network.id == network_id).one()\n        net_i.check_read_permission(user_id=user_id)\n    except NoResultFound:\n        raise ResourceNotFoundError(\"Network %s not found\"%(network_id))\n    return net_i.scenarios",
    "docstring": "Get all the scenarios in a given network."
  },
  {
    "code": "def delete_router_by_name(self, rtr_name, tenant_id):\n        try:\n            routers = self.neutronclient.list_routers()\n            rtr_list = routers.get('routers')\n            for rtr in rtr_list:\n                if rtr_name == rtr['name']:\n                    self.neutronclient.delete_router(rtr['id'])\n        except Exception as exc:\n            LOG.error(\"Failed to get and delete router by name %(name)s, \"\n                      \"Exc %(exc)s\",\n                      {'name': rtr_name, 'exc': str(exc)})\n            return False\n        return True",
    "docstring": "Delete the openstack router and its interfaces given its name.\n\n        The interfaces should be already removed prior to calling this\n        function."
  },
  {
    "code": "def add_list_member(self, list_id, user_id):\n        return List(tweepy_list_to_json(self._client.add_list_member(list_id=list_id, user_id=user_id)))",
    "docstring": "Add a user to list\n\n        :param list_id: list ID number\n        :param user_id: user ID number\n        :return: :class:`~responsebot.models.List` object"
  },
  {
    "code": "def show_pypi_releases(self):\n        try:\n            hours = int(self.options.show_pypi_releases)\n        except ValueError:\n            self.logger.error(\"ERROR: You must supply an integer.\")\n            return 1\n        try:\n            latest_releases = self.pypi.updated_releases(hours)\n        except XMLRPCFault as err_msg:\n            self.logger.error(err_msg)\n            self.logger.error(\"ERROR: Couldn't retrieve latest releases.\")\n            return 1\n        for release in latest_releases:\n            print(\"%s %s\" % (release[0], release[1]))\n        return 0",
    "docstring": "Show PyPI releases for the last number of `hours`\n\n        @returns: 0 = success or 1 if failed to retrieve from XML-RPC server"
  },
  {
    "code": "def throw_invalid_quad_params(quad, QUADS, nparams):\n    raise InvalidICError(str(quad),\n                         \"Invalid quad code params for '%s' (expected %i, but got %i)\" %\n                         (quad, QUADS[quad][0], nparams)\n                         )",
    "docstring": "Exception raised when an invalid number of params in the\n        quad code has been emmitted."
  },
  {
    "code": "def _generate_union_class_variant_creators(self, ns, data_type):\n        for field in data_type.fields:\n            if not is_void_type(field.data_type):\n                field_name = fmt_func(field.name)\n                field_name_reserved_check = fmt_func(field.name, check_reserved=True)\n                if is_nullable_type(field.data_type):\n                    field_dt = field.data_type.data_type\n                else:\n                    field_dt = field.data_type\n                self.emit('@classmethod')\n                self.emit('def {}(cls, val):'.format(field_name_reserved_check))\n                with self.indent():\n                    self.emit('\n')\n                    self.emit(\"return cls('{}', val)\".format(field_name))\n                self.emit()",
    "docstring": "Each non-symbol, non-any variant has a corresponding class method that\n        can be used to construct a union with that variant selected."
  },
  {
    "code": "def urlsplit(url):\n    proto, rest = url.split(':', 1)\n    host = ''\n    if rest[:2] == '//':\n        host, rest = rest[2:].split('/', 1)\n        rest = '/' + rest\n    return proto, host, rest",
    "docstring": "Split an arbitrary url into protocol, host, rest\n\n    The standard urlsplit does not want to provide 'netloc' for arbitrary\n    protocols, this works around that.\n\n    :param url: The url to split into component parts"
  },
  {
    "code": "def config_field_type(field, cls):\n    return defs.ConfigField(lambda _: isinstance(_, cls),\n                            lambda: CONFIG_FIELD_TYPE_ERROR.format(field, cls.__name__))",
    "docstring": "Validate a config field against a type.\n\n    Similar functionality to :func:`validate_field_matches_type` but returns :obj:`honeycomb.defs.ConfigField`"
  },
  {
    "code": "def handleFlaskPostRequest(flaskRequest, endpoint):\n    if flaskRequest.method == \"POST\":\n        return handleHttpPost(flaskRequest, endpoint)\n    elif flaskRequest.method == \"OPTIONS\":\n        return handleHttpOptions()\n    else:\n        raise exceptions.MethodNotAllowedException()",
    "docstring": "Handles the specified flask request for one of the POST URLS\n    Invokes the specified endpoint to generate a response."
  },
  {
    "code": "def title_prefix(soup):\n    \"titlePrefix for article JSON is only articles with certain display_channel values\"\n    prefix = None\n    display_channel_match_list = ['feature article', 'insight', 'editorial']\n    for d_channel in display_channel(soup):\n        if d_channel.lower() in display_channel_match_list:\n            if raw_parser.sub_display_channel(soup):\n                prefix = node_text(first(raw_parser.sub_display_channel(soup)))\n    return prefix",
    "docstring": "titlePrefix for article JSON is only articles with certain display_channel values"
  },
  {
    "code": "def _delete_horizontal_space(text, pos):\n    while pos > 0 and text[pos - 1].isspace():\n        pos -= 1\n    end_pos = pos\n    while end_pos < len(text) and text[end_pos].isspace():\n        end_pos += 1\n    return text[:pos] + text[end_pos:], pos",
    "docstring": "Delete all spaces and tabs around pos."
  },
  {
    "code": "def error_response(self, code, content=''):\n        self.send_response(code)\n        self.send_header('Content-Type', 'text/xml')\n        self.add_compliance_header()\n        self.end_headers()\n        self.wfile.write(content)",
    "docstring": "Construct and send error response."
  },
  {
    "code": "def load_pickle(filename):\n    try:\n        if pd:\n            return pd.read_pickle(filename), None\n        else:\n            with open(filename, 'rb') as fid:\n                data = pickle.load(fid)\n            return data, None\n    except Exception as err:\n        return None, str(err)",
    "docstring": "Load a pickle file as a dictionary"
  },
  {
    "code": "def _create_table_and_update_context(node, context):\n    schema_type_name = sql_context_helpers.get_schema_type_name(node, context)\n    table = context.compiler_metadata.get_table(schema_type_name).alias()\n    context.query_path_to_selectable[node.query_path] = table\n    return table",
    "docstring": "Create an aliased table for a SqlNode.\n\n    Updates the relevant Selectable global context.\n\n    Args:\n        node: SqlNode, the current node.\n        context: CompilationContext, global compilation state and metadata.\n\n    Returns:\n        Table, the newly aliased SQLAlchemy table."
  },
  {
    "code": "def _restore_training_state(self, restore_state):\n        self.load_state_dict(restore_state[\"model\"])\n        self.optimizer.load_state_dict(restore_state[\"optimizer\"])\n        self.lr_scheduler.load_state_dict(restore_state[\"lr_scheduler\"])\n        start_iteration = restore_state[\"iteration\"] + 1\n        if self.config[\"verbose\"]:\n            print(f\"Restored checkpoint to iteration {start_iteration}.\")\n        if restore_state[\"best_model_found\"]:\n            self.checkpointer.best_model_found = True\n            self.checkpointer.best_iteration = restore_state[\"best_iteration\"]\n            self.checkpointer.best_score = restore_state[\"best_score\"]\n            if self.config[\"verbose\"]:\n                print(\n                    f\"Updated checkpointer: \"\n                    f\"best_score={self.checkpointer.best_score:.3f}, \"\n                    f\"best_iteration={self.checkpointer.best_iteration}\"\n                )\n        return start_iteration",
    "docstring": "Restores the model and optimizer states\n\n        This helper function restores the model's state to a given iteration so\n        that a user can resume training at any epoch.\n\n        Args:\n            restore_state: a state_dict dictionary"
  },
  {
    "code": "def get_and_check_project(valid_vcs_rules, source_url):\n    project_path = match_url_regex(valid_vcs_rules, source_url, match_url_path_callback)\n    if project_path is None:\n        raise ValueError(\"Unknown repo for source url {}!\".format(source_url))\n    project = project_path.split('/')[-1]\n    return project",
    "docstring": "Given vcs rules and a source_url, return the project.\n\n    The project is in the path, but is the repo name.\n    `releases/mozilla-beta` is the path; `mozilla-beta` is the project.\n\n    Args:\n        valid_vcs_rules (tuple of frozendicts): the valid vcs rules, per\n            ``match_url_regex``.\n        source_url (str): the source url to find the project for.\n\n    Raises:\n        RuntimeError: on failure to find the project.\n\n    Returns:\n        str: the project."
  },
  {
    "code": "def data_storage_shape(self):\n        if self.data_shape == -1:\n            return -1\n        else:\n            return tuple(self.data_shape[ax]\n                         for ax in np.argsort(self.data_axis_order))",
    "docstring": "Shape tuple of the data as stored in the file.\n\n        If no header is available (i.e., before it has been initialized),\n        or any of the header entries ``'nx', 'ny', 'nz'`` is missing,\n        -1 is returned, which makes reshaping a no-op.\n        Otherwise, the returned shape is a permutation of `data_shape`,\n        i.e., ``(nx, ny, nz)``, according to `data_axis_order` in the\n        following way::\n\n            data_shape[i] == data_storage_shape[data_axis_order[i]]\n\n        See Also\n        --------\n        data_shape\n        data_axis_order"
  },
  {
    "code": "def __get_response(self, uri, params=None, method=\"get\", stream=False):\n        if not hasattr(self, \"session\") or not self.session:\n            self.session = requests.Session()\n            if self.access_token:\n                self.session.headers.update(\n                    {'Authorization': 'Bearer {}'.format(self.access_token)}\n                )\n        if params:\n            params = {k: v for k, v in params.items() if v is not None}\n        kwargs = {\n            \"url\": uri,\n            \"verify\": True,\n            \"stream\": stream\n        }\n        kwargs[\"params\" if method == \"get\" else \"data\"] = params\n        return getattr(self.session, method)(**kwargs)",
    "docstring": "Creates a response object with the given params and option\n\n            Parameters\n            ----------\n            url : string\n                The full URL to request.\n            params: dict\n                A list of parameters to send with the request.  This\n                will be sent as data for methods that accept a request\n                body and will otherwise be sent as query parameters.\n            method : str\n                The HTTP method to use.\n            stream : bool\n                Whether to stream the response.\n\n            Returns a requests.Response object."
  },
  {
    "code": "def visit_continue(self, node, parent):\n        return nodes.Continue(\n            getattr(node, \"lineno\", None), getattr(node, \"col_offset\", None), parent\n        )",
    "docstring": "visit a Continue node by returning a fresh instance of it"
  },
  {
    "code": "def _cwl_workflow_template(inputs, top_level=False):\n    ready_inputs = []\n    for inp in inputs:\n        cur_inp = copy.deepcopy(inp)\n        for attr in [\"source\", \"valueFrom\", \"wf_duplicate\"]:\n            cur_inp.pop(attr, None)\n        if top_level:\n            cur_inp = workflow._flatten_nested_input(cur_inp)\n        cur_inp = _clean_record(cur_inp)\n        ready_inputs.append(cur_inp)\n    return {\"class\": \"Workflow\",\n            \"cwlVersion\": \"v1.0\",\n            \"hints\": [],\n            \"requirements\": [{\"class\": \"EnvVarRequirement\",\n                              \"envDef\": [{\"envName\": \"MPLCONFIGDIR\", \"envValue\": \".\"}]},\n                             {\"class\": \"ScatterFeatureRequirement\"},\n                             {\"class\": \"SubworkflowFeatureRequirement\"}],\n            \"inputs\": ready_inputs,\n            \"outputs\": [],\n            \"steps\": []}",
    "docstring": "Retrieve CWL inputs shared amongst different workflows."
  },
  {
    "code": "def delete(cls, name):\n        result = cls.call('hosting.rproxy.delete', cls.usable_id(name))\n        cls.echo('Deleting your webaccelerator named %s' % name)\n        cls.display_progress(result)\n        cls.echo('Webaccelerator have been deleted')\n        return result",
    "docstring": "Delete a webaccelerator"
  },
  {
    "code": "def contains(cat, key, container):\n    hash(key)\n    try:\n        loc = cat.categories.get_loc(key)\n    except KeyError:\n        return False\n    if is_scalar(loc):\n        return loc in container\n    else:\n        return any(loc_ in container for loc_ in loc)",
    "docstring": "Helper for membership check for ``key`` in ``cat``.\n\n    This is a helper method for :method:`__contains__`\n    and :class:`CategoricalIndex.__contains__`.\n\n    Returns True if ``key`` is in ``cat.categories`` and the\n    location of ``key`` in ``categories`` is in ``container``.\n\n    Parameters\n    ----------\n    cat : :class:`Categorical`or :class:`categoricalIndex`\n    key : a hashable object\n        The key to check membership for.\n    container : Container (e.g. list-like or mapping)\n        The container to check for membership in.\n\n    Returns\n    -------\n    is_in : bool\n        True if ``key`` is in ``self.categories`` and location of\n        ``key`` in ``categories`` is in ``container``, else False.\n\n    Notes\n    -----\n    This method does not check for NaN values. Do that separately\n    before calling this method."
  },
  {
    "code": "def get_client_info(self):\n        iq = aioxmpp.IQ(\n            to=self.client.local_jid.bare().replace(localpart=None),\n            type_=aioxmpp.IQType.GET,\n            payload=xso.Query()\n        )\n        reply = (yield from self.client.send(iq))\n        return reply",
    "docstring": "A query is sent to the server to obtain the client's data stored at the\n        server.\n\n        :return: :class:`~aioxmpp.ibr.Query`"
  },
  {
    "code": "def assert_pks_uniqueness(self, pks, exclude, value):\n        pks = list(set(pks))\n        if len(pks) > 1:\n            raise UniquenessError(\n                \"Multiple values indexed for unique field %s.%s: %s\" % (\n                    self.model.__name__, self.field.name, pks\n                )\n            )\n        elif len(pks) == 1 and (not exclude or pks[0] != exclude):\n            self.connection.delete(self.field.key)\n            raise UniquenessError(\n                'Value \"%s\" already indexed for unique field %s.%s (for instance %s)' % (\n                    self.normalize_value(value), self.model.__name__, self.field.name, pks[0]\n                )\n            )",
    "docstring": "Check uniqueness of pks\n\n        Parameters\n        -----------\n        pks: iterable\n            The pks to check for uniqueness. If more than one different,\n            it will raise. If only one and different than `exclude`, it will\n            raise too.\n        exclude: str\n            The pk that we accept to be the only one in `pks`. For example\n            the pk of the instance we want to check for uniqueness: we don't\n            want to raise if the value is the one already set for this instance\n        value: any\n            Only to be displayed in the error message.\n\n        Raises\n        ------\n        UniquenessError\n            - If at least two different pks\n            - If only one pk that is not the `exclude` one"
  },
  {
    "code": "def timestamps(self, use_current=True):\n        if use_current:\n            self.timestamp(\"created_at\").use_current()\n            self.timestamp(\"updated_at\").use_current()\n        else:\n            self.timestamp(\"created_at\")\n            self.timestamp(\"updated_at\")",
    "docstring": "Create creation and update timestamps to the table.\n\n        :rtype: Fluent"
  },
  {
    "code": "def prepare_amazon_algorithm_estimator(estimator, inputs, mini_batch_size=None):\n    if isinstance(inputs, list):\n        for record in inputs:\n            if isinstance(record, amazon_estimator.RecordSet) and record.channel == 'train':\n                estimator.feature_dim = record.feature_dim\n                break\n    elif isinstance(inputs, amazon_estimator.RecordSet):\n        estimator.feature_dim = inputs.feature_dim\n    else:\n        raise TypeError('Training data must be represented in RecordSet or list of RecordSets')\n    estimator.mini_batch_size = mini_batch_size",
    "docstring": "Set up amazon algorithm estimator, adding the required `feature_dim` hyperparameter from training data.\n\n    Args:\n        estimator (sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase):\n            An estimator for a built-in Amazon algorithm to get information from and update.\n        inputs: The training data.\n            * (sagemaker.amazon.amazon_estimator.RecordSet) - A collection of\n                Amazon :class:~`Record` objects serialized and stored in S3.\n                For use with an estimator for an Amazon algorithm.\n            * (list[sagemaker.amazon.amazon_estimator.RecordSet]) - A list of\n                :class:~`sagemaker.amazon.amazon_estimator.RecordSet` objects, where each instance is\n                a different channel of training data."
  },
  {
    "code": "def send_request(self, *args, **kwargs):\n        try:\n            return super(JSHost, self).send_request(*args, **kwargs)\n        except RequestsConnectionError as e:\n            if (\n                self.manager and\n                self.has_connected and\n                self.logfile and\n                'unsafe' not in kwargs\n            ):\n                raise ProcessError(\n                    '{} appears to have crashed, you can inspect the log file at {}'.format(\n                        self.get_name(),\n                        self.logfile,\n                    )\n                )\n            raise six.reraise(RequestsConnectionError, RequestsConnectionError(*e.args), sys.exc_info()[2])",
    "docstring": "Intercept connection errors which suggest that a managed host has\n        crashed and raise an exception indicating the location of the log"
  },
  {
    "code": "def _storage_list_keys(bucket, pattern):\n  data = [{'Name': item.metadata.name,\n           'Type': item.metadata.content_type,\n           'Size': item.metadata.size,\n           'Updated': item.metadata.updated_on}\n          for item in _storage_get_keys(bucket, pattern)]\n  return datalab.utils.commands.render_dictionary(data, ['Name', 'Type', 'Size', 'Updated'])",
    "docstring": "List all storage keys in a specified bucket that match a pattern."
  },
  {
    "code": "def render(self, *args, **kwargs):\n        env = {}; stdout = []\n        for dictarg in args: env.update(dictarg)\n        env.update(kwargs)\n        self.execute(stdout, env)\n        return ''.join(stdout)",
    "docstring": "Render the template using keyword arguments as local variables."
  },
  {
    "code": "def rouge_2(hypotheses, references):\n    rouge_2 = [\n        rouge_n([hyp], [ref], 2) for hyp, ref in zip(hypotheses, references)\n    ]\n    rouge_2_f, _, _ = map(np.mean, zip(*rouge_2))\n    return rouge_2_f",
    "docstring": "Calculate ROUGE-2 F1, precision, recall scores"
  },
  {
    "code": "def register_module(self, module, url_prefix):\n        module._plugin = self\n        module._url_prefix = url_prefix\n        for func in module._register_funcs:\n            func(self, url_prefix)",
    "docstring": "Registers a module with a plugin. Requires a url_prefix that\n        will then enable calls to url_for.\n\n        :param module: Should be an instance `xbmcswift2.Module`.\n        :param url_prefix: A url prefix to use for all module urls,\n                           e.g. '/mymodule'"
  },
  {
    "code": "def tabModificationStateChanged(self, tab):\n\t\tif tab == self.currentTab:\n\t\t\tchanged = tab.editBox.document().isModified()\n\t\t\tif self.autoSaveActive(tab):\n\t\t\t\tchanged = False\n\t\t\tself.actionSave.setEnabled(changed)\n\t\t\tself.setWindowModified(changed)",
    "docstring": "Perform all UI state changes that need to be done when the\n\t\tmodification state of the current tab has changed."
  },
  {
    "code": "def increment_title(title):\n    count = re.search('\\d+$', title).group(0)\n    new_title = title[:-(len(count))] + str(int(count)+1)\n    return new_title",
    "docstring": "Increments a string that ends in a number"
  },
  {
    "code": "def _remove_unused_nodes(self):\n        nodes, wf_remove_node = self.nodes, self.workflow.remove_node\n        add_visited, succ = self._visited.add, self.workflow.succ\n        for n in (set(self._wf_pred) - set(self._visited)):\n            node_type = nodes[n]['type']\n            if node_type == 'data':\n                continue\n            if node_type == 'dispatcher' and succ[n]:\n                add_visited(n)\n                i = self.index + nodes[n]['index']\n                self.sub_sol[i]._remove_unused_nodes()\n                continue\n            wf_remove_node(n)",
    "docstring": "Removes unused function and sub-dispatcher nodes."
  },
  {
    "code": "def _create_clock(self):\n        trading_o_and_c = self.trading_calendar.schedule.ix[\n            self.sim_params.sessions]\n        market_closes = trading_o_and_c['market_close']\n        minutely_emission = False\n        if self.sim_params.data_frequency == 'minute':\n            market_opens = trading_o_and_c['market_open']\n            minutely_emission = self.sim_params.emission_rate == \"minute\"\n            execution_opens = \\\n                self.trading_calendar.execution_time_from_open(market_opens)\n            execution_closes = \\\n                self.trading_calendar.execution_time_from_close(market_closes)\n        else:\n            execution_closes = \\\n                self.trading_calendar.execution_time_from_close(market_closes)\n            execution_opens = execution_closes\n        before_trading_start_minutes = days_at_time(\n            self.sim_params.sessions,\n            time(8, 45),\n            \"US/Eastern\"\n        )\n        return MinuteSimulationClock(\n            self.sim_params.sessions,\n            execution_opens,\n            execution_closes,\n            before_trading_start_minutes,\n            minute_emission=minutely_emission,\n        )",
    "docstring": "If the clock property is not set, then create one based on frequency."
  },
  {
    "code": "def _get_struct_clipactions(self):\n        obj = _make_object(\"ClipActions\")\n        clipeventflags_size = 2 if self._version <= 5 else 4\n        clipactionend_size = 2 if self._version <= 5 else 4\n        all_zero = b\"\\x00\" * clipactionend_size\n        assert unpack_ui16(self._src) == 0\n        obj.AllEventFlags = self._src.read(clipeventflags_size)\n        obj.ClipActionRecords = records = []\n        while True:\n            next_bytes = self._src.read(clipactionend_size)\n            if next_bytes == all_zero:\n                return\n            record = _make_object(\"ClipActionRecord\")\n            records.append(record)\n            record.EventFlags = next_bytes\n            record.ActionRecordSize = unpack_ui32(self._src)\n            record.TheRestTODO = self._src.read(record.ActionRecordSize)\n        return obj",
    "docstring": "Get the several CLIPACTIONRECORDs."
  },
  {
    "code": "def transform(transform_func):\n    def decorator(func):\n        @wraps(func)\n        def f(*args, **kwargs):\n            return transform_func(\n                func(*args, **kwargs)\n            )\n        return f\n    return decorator",
    "docstring": "Apply a transformation to a functions return value"
  },
  {
    "code": "def translation_generator(\n        variant_sequences,\n        reference_contexts,\n        min_transcript_prefix_length,\n        max_transcript_mismatches,\n        include_mismatches_after_variant,\n        protein_sequence_length=None):\n    for reference_context in reference_contexts:\n        for variant_sequence in variant_sequences:\n            translation = Translation.from_variant_sequence_and_reference_context(\n                variant_sequence=variant_sequence,\n                reference_context=reference_context,\n                min_transcript_prefix_length=min_transcript_prefix_length,\n                max_transcript_mismatches=max_transcript_mismatches,\n                include_mismatches_after_variant=include_mismatches_after_variant,\n                protein_sequence_length=protein_sequence_length)\n            if translation is not None:\n                yield translation",
    "docstring": "Given all detected VariantSequence objects for a particular variant\n    and all the ReferenceContext objects for that locus, translate\n    multiple protein sequences, up to the number specified by the argument\n    max_protein_sequences_per_variant.\n\n    Parameters\n    ----------\n    variant_sequences : list of VariantSequence objects\n        Variant sequences overlapping a single original variant\n\n    reference_contexts : list of ReferenceContext objects\n        Reference sequence contexts from the same variant as the variant_sequences\n\n    min_transcript_prefix_length : int\n        Minimum number of nucleotides before the variant to test whether\n        our variant sequence can use the reading frame from a reference\n        transcript.\n\n    max_transcript_mismatches : int\n        Maximum number of mismatches between coding sequence before variant\n        and reference transcript we're considering for determing the reading\n        frame.\n\n    include_mismatches_after_variant : bool\n        If true, mismatches occurring after the variant locus will also count\n        toward max_transcript_mismatches filtering.\n\n    protein_sequence_length : int, optional\n        Truncate protein to be at most this long.\n\n    Yields a sequence of Translation objects."
  },
  {
    "code": "def _second_column(self):\n        if self._A[1, 1] == 0 and self._A[2, 1] != 0:\n            self._swap_rows(1, 2)\n        if self._A[2, 1] != 0:\n            self._zero_second_column()",
    "docstring": "Right-low 2x2 matrix\n\n        Assume elements in first row and column are all zero except for A[0,0]."
  },
  {
    "code": "def get_worker_build_info(workflow, platform):\n    workspace = workflow.plugin_workspace[OrchestrateBuildPlugin.key]\n    return workspace[WORKSPACE_KEY_BUILD_INFO][platform]",
    "docstring": "Obtain worker build information for a given platform"
  },
  {
    "code": "def entropy(data):\n    if len(data) == 0:\n        return None\n    n = sum(data)\n    _op = lambda f: f * math.log(f)\n    return - sum(_op(float(i) / n) for i in data)",
    "docstring": "Compute the Shannon entropy, a measure of uncertainty."
  },
  {
    "code": "def set_value(self, instance, value, parent=None):\n        self.resolve_base(instance)\n        value = self.deserialize(value, parent)\n        instance.values[self.alias] = value\n        self._trigger_changed(instance, value)",
    "docstring": "Set prop value\n\n        :param instance:\n        :param value:\n        :param parent:\n        :return:"
  },
  {
    "code": "def resolve_identifiers(self, subject_context):\n        session = subject_context.session\n        identifiers = subject_context.resolve_identifiers(session)\n        if (not identifiers):\n            msg = (\"No identity (identifier_collection) found in the \"\n                   \"subject_context.  Looking for a remembered identity.\")\n            logger.debug(msg)\n            identifiers = self.get_remembered_identity(subject_context)\n            if identifiers:\n                msg = (\"Found remembered IdentifierCollection.  Adding to the \"\n                       \"context to be used for subject construction.\")\n                logger.debug(msg)\n                subject_context.identifiers = identifiers\n                subject_context.remembered = True\n            else:\n                msg = (\"No remembered identity found.  Returning original \"\n                       \"context.\")\n                logger.debug(msg)\n        return subject_context",
    "docstring": "ensures that a subject_context has identifiers and if it doesn't will\n        attempt to locate them using heuristics"
  },
  {
    "code": "def _specialize(self, reconfigure=False):\n        for manifest in [self.source, self.target]:\n            context_dict = {}\n            if manifest:\n                for s in manifest.formula_sections():\n                    context_dict[\"%s:root_dir\" % s] = self.directory.install_directory(s)\n                    context_dict['config:root_dir'] = self.directory.root_dir\n                    context_dict['config:node'] = system.NODE\n                manifest.add_additional_context(context_dict)\n        self._validate_manifest()\n        for feature in self.features.run_order:\n            if not reconfigure:\n                self.run_action(feature, 'resolve')\n            instance = self.features[feature]\n            if instance.target:\n                self.run_action(feature, 'prompt')",
    "docstring": "Add variables and specialize contexts"
  },
  {
    "code": "def set_var(self, vardef):\n        if not(vardef.default and self.cache['ctx'].get(vardef.name)):\n            self.cache['ctx'][vardef.name] = vardef.expression.value",
    "docstring": "Set variable to global stylesheet context."
  },
  {
    "code": "def rule_expand(component, text):\n    global rline_mpstate\n    if component[0] == '<' and component[-1] == '>':\n        return component[1:-1].split('|')\n    if component in rline_mpstate.completion_functions:\n        return rline_mpstate.completion_functions[component](text)\n    return [component]",
    "docstring": "expand one rule component"
  },
  {
    "code": "def create_environment_vip(self):\n        return EnvironmentVIP(\n            self.networkapi_url,\n            self.user,\n            self.password,\n            self.user_ldap)",
    "docstring": "Get an instance of environment_vip services facade."
  },
  {
    "code": "def check_token(self, respond):\n        if respond.status_code == 401:\n            self.credential.obtain_token(config=self.config)\n            return False\n        return True",
    "docstring": "Check is the user's token is valid"
  },
  {
    "code": "def wrap_get_channel(cls, response):\n        json = response.json()\n        c = cls.wrap_json(json)\n        return c",
    "docstring": "Wrap the response from getting a channel into an instance\n        and return it\n\n        :param response: The response from getting a channel\n        :type response: :class:`requests.Response`\n        :returns: the new channel instance\n        :rtype: :class:`list` of :class:`channel`\n        :raises: None"
  },
  {
    "code": "def _preprocess_Y(self, Y, k):\n        Y = Y.clone()\n        if Y.dim() == 1 or Y.shape[1] == 1:\n            Y = pred_to_prob(Y.long(), k=k)\n        return Y",
    "docstring": "Convert Y to prob labels if necessary"
  },
  {
    "code": "def SegmentProd(a, ids):\n    func = lambda idxs: reduce(np.multiply, a[idxs])\n    return seg_map(func, a, ids),",
    "docstring": "Segmented prod op."
  },
  {
    "code": "def get_list_database(self):\n        url = \"db\"\n        response = self.request(\n            url=url,\n            method='GET',\n            expected_response_code=200\n        )\n        return response.json()",
    "docstring": "Get the list of databases."
  },
  {
    "code": "def normalize_path(path, filetype=FILE):\n    if not path:\n        raise ValueError('\"{0}\" is not a valid path.'.format(path))\n    if not os.path.exists(path):\n        raise ValueError('\"{0}\" does not exist.'.format(path))\n    if filetype == FILE and not os.path.isfile(path):\n        raise ValueError('\"{0}\" is not a file.'.format(path))\n    elif filetype == DIR and not os.path.isdir(path):\n        raise ValueError('\"{0}\" is not a dir.'.format(path))\n    return os.path.abspath(path)",
    "docstring": "Takes a path and a filetype, verifies existence and type, and\n    returns absolute path."
  },
  {
    "code": "def remove_item_languages(self, item, languages):\n        qs = TransLanguage.objects.filter(code__in=languages)\n        remove_langs = [lang for lang in qs]\n        if not remove_langs:\n            return\n        ct_item = ContentType.objects.get_for_model(item)\n        item_lan, created = TransItemLanguage.objects.get_or_create(content_type_id=ct_item.id, object_id=item.id)\n        for lang in remove_langs:\n            item_lan.languages.remove(lang)\n        if item_lan.languages.count() == 0:\n            item_lan.delete()",
    "docstring": "delete the selected languages from the TransItemLanguage model\n\n        :param item:\n        :param languages:\n        :return:"
  },
  {
    "code": "def queueStream(self, rdds, oneAtATime=True, default=None):\n        if default and not isinstance(default, RDD):\n            default = self._sc.parallelize(default)\n        if not rdds and default:\n            rdds = [rdds]\n        if rdds and not isinstance(rdds[0], RDD):\n            rdds = [self._sc.parallelize(input) for input in rdds]\n        self._check_serializers(rdds)\n        queue = self._jvm.PythonDStream.toRDDQueue([r._jrdd for r in rdds])\n        if default:\n            default = default._reserialize(rdds[0]._jrdd_deserializer)\n            jdstream = self._jssc.queueStream(queue, oneAtATime, default._jrdd)\n        else:\n            jdstream = self._jssc.queueStream(queue, oneAtATime)\n        return DStream(jdstream, self, rdds[0]._jrdd_deserializer)",
    "docstring": "Create an input stream from a queue of RDDs or list. In each batch,\n        it will process either one or all of the RDDs returned by the queue.\n\n        .. note:: Changes to the queue after the stream is created will not be recognized.\n\n        @param rdds:       Queue of RDDs\n        @param oneAtATime: pick one rdd each time or pick all of them once.\n        @param default:    The default rdd if no more in rdds"
  },
  {
    "code": "def update():\n    assert request.method == \"POST\", \"POST request expected received {}\".format(request.method)\n    if request.method == 'POST':\n        selected_run = request.form['selected_run']\n        variable_names = utils.get_variables(selected_run).items()\n        if len(current_index) < 1:\n            for _, v_n in variable_names:\n                current_index[v_n] = 0\n        logging.info(\"Current index: {}\".format(current_index))\n        data = utils.get_variable_update_dicts(current_index, variable_names, selected_run)\n        return jsonify(data)",
    "docstring": "Called by XMLHTTPrequest function periodically to get new graph data.\n\n    Usage description:\n    This function queries the database and returns all the newly added values.\n\n    :return: JSON Object, passed on to the JS script."
  },
  {
    "code": "def after_sample(analysis_request):\n    analysis_request.setDateSampled(DateTime())\n    idxs = ['getDateSampled']\n    for analysis in analysis_request.getAnalyses(full_objects=True):\n        analysis.reindexObject(idxs=idxs)",
    "docstring": "Method triggered after \"sample\" transition for the Analysis Request\n    passed in is performed"
  },
  {
    "code": "def _data(self, received_data):\n        if self.listener.on_data(received_data) is False:\n            self.stop()\n            raise ListenerError(self.listener.connection_id, received_data)",
    "docstring": "Sends data to listener, if False is returned; socket\n        is closed.\n\n        :param received_data: Decoded data received from socket."
  },
  {
    "code": "def create(self, ogpgs):\n        data = {'ogpgs': ogpgs}\n        return super(ApiObjectGroupPermissionGeneral, self).post('api/v3/object-group-perm-general/', data)",
    "docstring": "Method to create object group permissions general\n\n        :param ogpgs: List containing vrf desired to be created on database\n        :return: None"
  },
  {
    "code": "def write(self, f):\n        if isinstance(f, str):\n            f = io.open(f, 'w', encoding='utf-8')\n        if not hasattr(f, 'read'):\n            raise AttributeError(\"Wrong type of file: {0}\".format(type(f)))\n        NS_LOGGER.info('Write to `{0}`'.format(f.name))\n        for section in self.sections.keys():\n            f.write('[{0}]\\n'.format(section))\n            for k, v in self[section].items():\n                f.write('{0:15}= {1}\\n'.format(k, v))\n            f.write('\\n')\n        f.close()",
    "docstring": "Write namespace as INI file.\n\n        :param f: File object or path to file."
  },
  {
    "code": "def radio_button(g, l, fn):\n    w = urwid.RadioButton(g, l, False, on_state_change=fn)\n    w = urwid.AttrWrap(w, 'button normal', 'button select')\n    return w",
    "docstring": "Inheriting radio button of urwid"
  },
  {
    "code": "def enqueue_command(self, command, data):\n        if command == CommandType.TrialEnd or (command == CommandType.ReportMetricData and data['type'] == 'PERIODICAL'):\n            self.assessor_command_queue.put((command, data))\n        else:\n            self.default_command_queue.put((command, data))\n        qsize = self.default_command_queue.qsize()\n        if qsize >= QUEUE_LEN_WARNING_MARK:\n            _logger.warning('default queue length: %d', qsize)\n        qsize = self.assessor_command_queue.qsize()\n        if qsize >= QUEUE_LEN_WARNING_MARK:\n            _logger.warning('assessor queue length: %d', qsize)",
    "docstring": "Enqueue command into command queues"
  },
  {
    "code": "def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None,\n                                  key=None, keyid=None, profile=None, dry_run=False):\n    if not _exactly_one((conn_id, conn_name)):\n        raise SaltInvocationError('Exactly one of conn_id or '\n                                  'conn_name must be provided.')\n    conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\n    if conn_name:\n        conn_id = _vpc_peering_conn_id_for_name(conn_name, conn)\n        if not conn_id:\n            raise SaltInvocationError(\"Couldn't resolve VPC peering connection \"\n                                      \"{0} to an ID\".format(conn_name))\n    try:\n        log.debug('Trying to delete vpc peering connection')\n        conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id)\n        return {'msg': 'VPC peering connection deleted.'}\n    except botocore.exceptions.ClientError as err:\n        e = __utils__['boto.get_error'](err)\n        log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e)\n        return {'error': e}",
    "docstring": "Delete a VPC peering connection.\n\n    .. versionadded:: 2016.11.0\n\n    conn_id\n        The connection ID to check.  Exclusive with conn_name.\n\n    conn_name\n        The connection name to check.  Exclusive with conn_id.\n\n    region\n        Region to connect to.\n\n    key\n        Secret key to be used.\n\n    keyid\n        Access key to be used.\n\n    profile\n        A dict with region, key and keyid, or a pillar key (string) that\n        contains a dict with region, key and keyid.\n\n    dry_run\n        If True, skip application and simply return projected status.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        # Create a named VPC peering connection\n        salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc\n        # Specify a region\n        salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2\n        # specify an id\n        salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3"
  },
  {
    "code": "def get_context(self,\n                    name,\n                    retry=google.api_core.gapic_v1.method.DEFAULT,\n                    timeout=google.api_core.gapic_v1.method.DEFAULT,\n                    metadata=None):\n        if 'get_context' not in self._inner_api_calls:\n            self._inner_api_calls[\n                'get_context'] = google.api_core.gapic_v1.method.wrap_method(\n                    self.transport.get_context,\n                    default_retry=self._method_configs['GetContext'].retry,\n                    default_timeout=self._method_configs['GetContext'].timeout,\n                    client_info=self._client_info,\n                )\n        request = context_pb2.GetContextRequest(name=name, )\n        return self._inner_api_calls['get_context'](\n            request, retry=retry, timeout=timeout, metadata=metadata)",
    "docstring": "Retrieves the specified context.\n\n        Example:\n            >>> import dialogflow_v2\n            >>>\n            >>> client = dialogflow_v2.ContextsClient()\n            >>>\n            >>> name = client.context_path('[PROJECT]', '[SESSION]', '[CONTEXT]')\n            >>>\n            >>> response = client.get_context(name)\n\n        Args:\n            name (str): Required. The name of the context. Format:\n                ``projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>``.\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.dialogflow_v2.types.Context` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def cells(self):\n        n = 0\n        for (order, cells) in self:\n            n += len(cells)\n        return n",
    "docstring": "The number of cells in the MOC.\n\n        This gives the total number of cells at all orders,\n        with cells from every order counted equally.\n\n        >>> m = MOC(0, (1, 2))\n        >>> m.cells\n        2"
  },
  {
    "code": "def _pull_content_revision_parent(self):\n        if self._revision_id is None:\n            query_params = {\n                \"prop\": \"extracts|revisions\",\n                \"explaintext\": \"\",\n                \"rvprop\": \"ids\",\n            }\n            query_params.update(self.__title_query_param())\n            request = self.mediawiki.wiki_request(query_params)\n            page_info = request[\"query\"][\"pages\"][self.pageid]\n            self._content = page_info[\"extract\"]\n            self._revision_id = page_info[\"revisions\"][0][\"revid\"]\n            self._parent_id = page_info[\"revisions\"][0][\"parentid\"]\n        return self._content, self._revision_id, self._parent_id",
    "docstring": "combine the pulling of these three properties"
  },
  {
    "code": "def getBottomLeft(self):\n        x1 = float(self.get_x1())\n        x2 = float(self.get_x2())\n        y1 = float(self.get_y1())\n        y2 = float(self.get_y2())\n        if x1 < x2:\n            if y1 < y2:\n                return (x1, y1)\n            else:\n                return (x1, y2)\n        else:\n            if y1 < y2:\n                return (x2, y1)\n            else:\n                return (x2, y2)",
    "docstring": "Retrieves the the bottom left coordinate of the line as tuple.\n        Coordinates must be numbers."
  },
  {
    "code": "def getExtensions(self, extname='SCI', section=None):\n        if section is None:\n            numext = 0\n            section = []\n            for hdu in self._image:\n                if 'extname' in hdu.header and hdu.header['extname'] == extname:\n                    section.append(hdu.header['extver'])\n        else:\n            if not isinstance(section,list):\n                section = [section]\n        return section",
    "docstring": "Return the list of EXTVER values for extensions with name specified\n        in extname."
  },
  {
    "code": "def simple_swap(ins: Instruction) -> Instruction:\n    try:\n        rule = ins.details['transform']['simple_swap']\n    except KeyError:\n        return ins\n    replacement_ins = opcode_table[rule['op']]\n    return Instruction(\n        replacement_ins['mnemonic'],\n        replacement_ins['op'],\n        [Operand(\n            replacement_ins['operands'][i][1],\n            r\n        ) for i, r in enumerate(rule['operands'])],\n        ins.pos\n    )",
    "docstring": "Replaces one instruction with another based on the transform rules in\n    the bytecode definitions. This can help simplify your code as it reduces\n    the overall number of instructions. For example, `aload_0` will become\n    `aload 0`.\n\n    :param ins: Instruction to potentially modify.\n    :return: Potentially modified instruction."
  },
  {
    "code": "def get_jvm_options(self):\n    ret = []\n    for opt in self.get_options().options:\n      ret.extend(safe_shlex_split(opt))\n    if (self.get_options().debug or\n        self.get_options().is_flagged('debug_port') or\n        self.get_options().is_flagged('debug_args')):\n      debug_port = self.get_options().debug_port\n      ret.extend(arg.format(debug_port=debug_port) for arg in self.get_options().debug_args)\n    return ret",
    "docstring": "Return the options to run this JVM with.\n\n    These are options to the JVM itself, such as -Dfoo=bar, -Xmx=1g, -XX:-UseParallelGC and so on.\n\n    Thus named because get_options() already exists (and returns this object's Pants options)."
  },
  {
    "code": "def find_experiment_export(app_id):\n    cwd = os.getcwd()\n    data_filename = \"{}-data.zip\".format(app_id)\n    path_to_data = os.path.join(cwd, \"data\", data_filename)\n    if os.path.exists(path_to_data):\n        try:\n            Data(path_to_data)\n        except IOError:\n            from dallinger import logger\n            logger.exception(\n                \"Error reading local data file {}, checking remote.\".format(\n                    path_to_data\n                )\n            )\n        else:\n            return path_to_data\n    path_to_data = os.path.join(tempfile.mkdtemp(), data_filename)\n    buckets = [user_s3_bucket(), dallinger_s3_bucket()]\n    for bucket in buckets:\n        try:\n            bucket.download_file(data_filename, path_to_data)\n        except botocore.exceptions.ClientError:\n            pass\n        else:\n            return path_to_data",
    "docstring": "Attempt to find a zipped export of an experiment with the ID provided\n    and return its path. Returns None if not found.\n\n    Search order:\n        1. local \"data\" subdirectory\n        2. user S3 bucket\n        3. Dallinger S3 bucket"
  },
  {
    "code": "def isidentifier(s, dotted=False):\n    if dotted:\n        return all(isidentifier(a) for a in s.split('.'))\n    if PY3:\n        return s.isidentifier()\n    else:\n        import re\n        _name_re = re.compile(r\"[a-zA-Z_][a-zA-Z0-9_]*$\")\n        return bool(_name_re.match(s))",
    "docstring": "A function equivalent to the str.isidentifier method on Py3"
  },
  {
    "code": "def minWidth(self):\n        frags = self.frags\n        nFrags = len(frags)\n        if not nFrags: return 0\n        if nFrags == 1:\n            f = frags[0]\n            fS = f.fontSize\n            fN = f.fontName\n            words = hasattr(f, 'text') and split(f.text, ' ') or f.words\n            func = lambda w, fS=fS, fN=fN: stringWidth(w, fN, fS)\n        else:\n            words = _getFragWords(frags)\n            func = lambda x: x[0]\n        return max(map(func, words))",
    "docstring": "Attempt to determine a minimum sensible width"
  },
  {
    "code": "def nested_update(d, u):\n    for k, v in list(u.items()):\n        if isinstance(v, collections.Mapping):\n            r = nested_update(d.get(k, {}), v)\n            d[k] = r\n        else:\n            d[k] = u[k]\n    return d",
    "docstring": "Merge two nested dicts.\n\n    Nested dicts are sometimes used for representing various recursive structures. When\n    updating such a structure, it may be convenient to present the updated data as a\n    corresponding recursive structure. This function will then apply the update.\n\n    Args:\n      d: dict\n        dict that will be updated in-place. May or may not contain nested dicts.\n\n      u: dict\n        dict with contents that will be merged into ``d``. May or may not contain\n        nested dicts."
  },
  {
    "code": "def scope(self, key):\n        if self.name is None:\n            return key\n        return '{:s}/{:s}'.format(self.name, key)",
    "docstring": "Apply the name scope to a key\n\n        Parameters\n        ----------\n        key : string\n\n        Returns\n        -------\n        `name/key` if `name` is not `None`;\n        otherwise, `key`."
  },
  {
    "code": "def props_to_image(regionprops, shape, prop):\n    r\n    im = sp.zeros(shape=shape)\n    for r in regionprops:\n        if prop == 'convex':\n            mask = r.convex_image\n        else:\n            mask = r.image\n        temp = mask * r[prop]\n        s = bbox_to_slices(r.bbox)\n        im[s] += temp\n    return im",
    "docstring": "r\"\"\"\n    Creates an image with each region colored according the specified ``prop``,\n    as obtained by ``regionprops_3d``.\n\n    Parameters\n    ----------\n    regionprops : list\n        This is a list of properties for each region that is computed\n        by PoreSpy's ``regionprops_3D`` or Skimage's ``regionsprops``.\n\n    shape : array_like\n        The shape of the original image for which ``regionprops`` was obtained.\n\n    prop : string\n        The region property of interest.  Can be a scalar item such as 'volume'\n        in which case the the regions will be colored by their respective\n        volumes, or can be an image-type property such as 'border' or\n        'convex_image', which will return an image composed of the sub-images.\n\n    Returns\n    -------\n    image : ND-array\n        An ND-image the same size as the original image, with each region\n        represented by the values specified in ``prop``.\n\n    See Also\n    --------\n    props_to_DataFrame\n    regionprops_3d"
  },
  {
    "code": "def href(self):\n        url = self.session.base_url + str(self.path)\n        if self.path.is_collection and not self.path.is_root:\n            return url + 's'\n        return url",
    "docstring": "Return URL of the resource\n\n        :rtype: str"
  },
  {
    "code": "def mean(self, only_valid=True) -> ErrorValue:\n        if not only_valid:\n            intensity = self.intensity\n            error = self.error\n        else:\n            intensity = self.intensity[self.mask]\n            error = self.error[self.mask]\n        return ErrorValue(intensity.mean(),\n                          (error ** 2).mean() ** 0.5)",
    "docstring": "Calculate the mean of the pixels, not counting the masked ones if only_valid is True."
  },
  {
    "code": "def Recv(self):\n    size = struct.unpack(_STRUCT_FMT, self._ReadN(_STRUCT_LEN))[0]\n    if size > MAX_SIZE:\n      raise ProtocolError(\"Expected size to be at most %d, got %d\" % (MAX_SIZE,\n                                                                      size))\n    with self._read_lock:\n      buf = self._ReadN(size)\n      self._ReadMagic()\n    res = common_pb2.Message()\n    res.ParseFromString(buf)\n    return res, len(buf)",
    "docstring": "Accept a message from Fleetspeak.\n\n    Returns:\n      A tuple (common_pb2.Message, size of the message in bytes).\n    Raises:\n      ProtocolError: If we receive unexpected data from Fleetspeak."
  },
  {
    "code": "def is_field_visible(self, field):\n        context = self.context\n        fieldname = field.getName()\n        if fieldname == \"Client\" and context.portal_type in (\"Client\", ):\n            return False\n        if fieldname == \"Batch\" and context.portal_type in (\"Batch\", ):\n            return False\n        return True",
    "docstring": "Check if the field is visible"
  },
  {
    "code": "def qteIsMiniApplet(self, obj):\n        try:\n            ret = obj._qteAdmin.isMiniApplet\n        except AttributeError:\n            ret = False\n        return ret",
    "docstring": "Test if instance ``obj`` is a mini applet.\n\n        |Args|\n\n        * ``obj`` (**object**): object to test.\n\n        |Returns|\n\n        * **bool**: whether or not ``obj`` is the mini applet.\n\n        |Raises|\n\n        * **None**"
  },
  {
    "code": "async def try_sending(self,msg,timeout_secs, max_attempts):\n        if timeout_secs is None:\n            timeout_secs = self.timeout\n        if max_attempts is None:\n            max_attempts = self.retry_count\n        attempts = 0\n        while attempts < max_attempts:\n            if msg.seq_num not in self.message: return\n            event = aio.Event()\n            self.message[msg.seq_num][1]= event\n            attempts += 1\n            if self.transport:\n                self.transport.sendto(msg.packed_message)\n            try:\n                myresult = await aio.wait_for(event.wait(),timeout_secs)\n                break\n            except Exception as inst:\n                if attempts >= max_attempts:\n                    if msg.seq_num in self.message:\n                        callb = self.message[msg.seq_num][2]\n                        if callb:\n                            callb(self, None)\n                        del(self.message[msg.seq_num])\n                    self.unregister()",
    "docstring": "Coroutine used to send message to the device when a response or ack is needed.\n\n        This coroutine will try to send up to max_attempts time the message, waiting timeout_secs\n        for an answer. If no answer is received, it will consider that the device is no longer\n        accessible and will unregister it.\n\n            :param msg: The message to send\n            :type msg: aiolifx.Message\n            :param timeout_secs: Number of seconds to wait for a response or ack\n            :type timeout_secs: int\n            :param max_attempts: .\n            :type max_attempts: int\n            :returns: a coroutine to be scheduled\n            :rtype: coroutine"
  },
  {
    "code": "def pull(self):\n        if not os.path.exists(self.repo_dir):\n            yield from self.initialize_repo()\n        else:\n            yield from self.update()",
    "docstring": "Pull selected repo from a remote git repository,\n        while preserving user changes"
  },
  {
    "code": "def clean_start_time(self):\n        start = self.cleaned_data.get('start_time')\n        if not start:\n            return start\n        active_entries = self.user.timepiece_entries.filter(\n            start_time__gte=start, end_time__isnull=True)\n        for entry in active_entries:\n            output = ('The start time is on or before the current entry: '\n                      '%s - %s starting at %s' % (entry.project, entry.activity,\n                                                  entry.start_time.strftime('%H:%M:%S')))\n            raise forms.ValidationError(output)\n        return start",
    "docstring": "Make sure that the start time doesn't come before the active entry"
  },
  {
    "code": "def render(file):\n    fp = file.open()\n    content = fp.read()\n    fp.close()\n    notebook = nbformat.reads(content.decode('utf-8'), as_version=4)\n    html_exporter = HTMLExporter()\n    html_exporter.template_file = 'basic'\n    (body, resources) = html_exporter.from_notebook_node(notebook)\n    return body, resources",
    "docstring": "Generate the result HTML."
  },
  {
    "code": "def blend(self, other, ratio=0.5):\n        keep = 1.0 - ratio\n        if not self.space == other.space:\n            raise Exception(\"Colors must belong to the same color space.\")\n        values = tuple(((u * keep) + (v * ratio)\n            for u, v in zip(self.values, other.values)))\n        return self.__class__(self.space, *values)",
    "docstring": "Blend this color with another color in the same color space.\n\n        By default, blends the colors half-and-half (ratio: 0.5).\n\n        :param Color other: The color to blend.\n        :param float ratio: How much to blend (0 -> 1).\n\n        :rtype: Color\n        :returns: A new spectra.Color"
  },
  {
    "code": "def build_wheel(source_dir, wheel_dir, config_settings=None):\n    if config_settings is None:\n        config_settings = {}\n    requires, backend = _load_pyproject(source_dir)\n    hooks = Pep517HookCaller(source_dir, backend)\n    with BuildEnvironment() as env:\n        env.pip_install(requires)\n        reqs = hooks.get_requires_for_build_wheel(config_settings)\n        env.pip_install(reqs)\n        return hooks.build_wheel(wheel_dir, config_settings)",
    "docstring": "Build a wheel from a source directory using PEP 517 hooks.\n\n    :param str source_dir: Source directory containing pyproject.toml\n    :param str wheel_dir: Target directory to create wheel in\n    :param dict config_settings: Options to pass to build backend\n\n    This is a blocking function which will run pip in a subprocess to install\n    build requirements."
  },
  {
    "code": "def generate_docs(self):\n        if self.dst.style['out'] == 'numpydoc' and self.dst.numpydoc.first_line is not None:\n            self.first_line = self.dst.numpydoc.first_line\n        self._set_desc()\n        self._set_params()\n        self._set_return()\n        self._set_raises()\n        self._set_other()\n        self._set_raw()\n        self.generated_docs = True",
    "docstring": "Generates the output docstring"
  },
  {
    "code": "def save_cPkl(fpath, data, verbose=None, n=None):\n    verbose = _rectify_verb_write(verbose)\n    if verbose:\n        print('[util_io] * save_cPkl(%r, data)' % (util_path.tail(fpath, n=n),))\n    with open(fpath, 'wb') as file_:\n        pickle.dump(data, file_, protocol=2)",
    "docstring": "Saves data to a pickled file with optional verbosity"
  },
  {
    "code": "def usable_id(cls, id):\n        try:\n            qry_id = int(id)\n        except Exception:\n            qry_id = None\n        if not qry_id:\n            msg = 'unknown identifier %s' % id\n            cls.error(msg)\n        return qry_id",
    "docstring": "Retrieve id from input which can be num or id."
  },
  {
    "code": "def raw_response(self, cursor_id=None):\n        if self.flags & 1:\n            if cursor_id is None:\n                raise ProtocolError(\"No cursor id for getMore operation\")\n            msg = \"Cursor not found, cursor id: %d\" % (cursor_id,)\n            errobj = {\"ok\": 0, \"errmsg\": msg, \"code\": 43}\n            raise CursorNotFound(msg, 43, errobj)\n        elif self.flags & 2:\n            error_object = bson.BSON(self.documents).decode()\n            error_object.setdefault(\"ok\", 0)\n            if error_object[\"$err\"].startswith(\"not master\"):\n                raise NotMasterError(error_object[\"$err\"], error_object)\n            elif error_object.get(\"code\") == 50:\n                raise ExecutionTimeout(error_object.get(\"$err\"),\n                                       error_object.get(\"code\"),\n                                       error_object)\n            raise OperationFailure(\"database error: %s\" %\n                                   error_object.get(\"$err\"),\n                                   error_object.get(\"code\"),\n                                   error_object)\n        return [self.documents]",
    "docstring": "Check the response header from the database, without decoding BSON.\n\n        Check the response for errors and unpack.\n\n        Can raise CursorNotFound, NotMasterError, ExecutionTimeout, or\n        OperationFailure.\n\n        :Parameters:\n          - `cursor_id` (optional): cursor_id we sent to get this response -\n            used for raising an informative exception when we get cursor id not\n            valid at server response."
  },
  {
    "code": "def list_feeds(self):\n        feeds = configparser.ConfigParser()\n        feeds.read(self.data_filename)\n        return feeds.sections()",
    "docstring": "Output a list of all feed names"
  },
  {
    "code": "def link_files(files: set, workspace_src_dir: str,\n               common_parent: str, conf):\n    norm_dir = normpath(workspace_src_dir)\n    base_dir = ''\n    if common_parent:\n        common_parent = normpath(common_parent)\n        base_dir = commonpath(list(files) + [common_parent])\n        if base_dir != common_parent:\n            raise ValueError('{} is not the common parent of all target '\n                             'sources and data'.format(common_parent))\n        logger.debug(\n            'Rebasing files in image relative to common parent dir {}',\n            base_dir)\n    num_linked = 0\n    for src in files:\n        abs_src = join(conf.project_root, src)\n        abs_dest = join(conf.project_root, workspace_src_dir,\n                        relpath(src, base_dir))\n        link_node(abs_src, abs_dest, conf.builders_workspace_dir in src)\n        num_linked += 1\n    return num_linked",
    "docstring": "Sync the list of files and directories in `files` to destination\n       directory specified by `workspace_src_dir`.\n\n    \"Sync\" in the sense that every file given in `files` will be\n    hard-linked under `workspace_src_dir` after this function returns, and no\n    other files will exist under `workspace_src_dir`.\n\n    For directories in `files`, hard-links of contained files are\n    created recursively.\n\n    All paths in `files`, and the `workspace_src_dir`, must be relative\n    to `conf.project_root`.\n\n    If `common_parent` is given, and it is a common parent directory of all\n    `files`, then the `commonm_parent` part is truncated from the\n    sync'ed files destination path under `workspace_src_dir`.\n\n    :raises FileNotFoundError: If `files` contains files or directories\n                               that do not exist.\n\n    :raises ValueError: If `common_parent` is given (not `None`), but is *NOT*\n                        a common parent of all `files`."
  },
  {
    "code": "def _is_flag_group(obj):\n    return (\n        isinstance(obj, h5py.Group) and\n        isinstance(obj.get(\"active\"), h5py.Dataset) and\n        isinstance(obj.get(\"known\"), h5py.Dataset)\n    )",
    "docstring": "Returns `True` if `obj` is an `h5py.Group` that looks like\n    if contains a flag"
  },
  {
    "code": "def fetch_new_id(self, ):\n        parent = self.get_parent()\n        if parent:\n            others = parent._children\n        else:\n            others = [r for r in self.get_root()._reftracks if r.get_parent() is None]\n        others = [r for r in others\n                  if r != self\n                  and r.get_typ() == self.get_typ()\n                  and r.get_element() == self.get_element()]\n        highest = -1\n        for r in others:\n            identifier = r.get_id()\n            if identifier > highest:\n                highest = identifier\n        return highest + 1",
    "docstring": "Return a new id for the given reftrack to be set on the refobject\n\n        The id can identify reftracks that share the same parent, type and element.\n\n        :returns: A new id\n        :rtype: int\n        :raises: None"
  },
  {
    "code": "def _finish_transaction_with_retry(self, command_name, explict_retry):\n        try:\n            return self._finish_transaction(command_name, explict_retry)\n        except ServerSelectionTimeoutError:\n            raise\n        except ConnectionFailure as exc:\n            try:\n                return self._finish_transaction(command_name, True)\n            except ServerSelectionTimeoutError:\n                raise exc\n        except OperationFailure as exc:\n            if exc.code not in _RETRYABLE_ERROR_CODES:\n                raise\n            try:\n                return self._finish_transaction(command_name, True)\n            except ServerSelectionTimeoutError:\n                raise exc",
    "docstring": "Run commit or abort with one retry after any retryable error.\n\n        :Parameters:\n          - `command_name`: Either \"commitTransaction\" or \"abortTransaction\".\n          - `explict_retry`: True when this is an explict commit retry attempt,\n            ie the application called session.commit_transaction() twice."
  },
  {
    "code": "def host_report_msg(hostname, module_name, result, oneline):\n    failed = utils.is_failed(result)\n    msg = ''\n    if module_name in [ 'command', 'shell', 'raw' ] and 'ansible_job_id' not in result and result.get('parsed',True) != False:\n        if not failed:\n            msg = command_generic_msg(hostname, result, oneline, 'success')\n        else:\n            msg = command_generic_msg(hostname, result, oneline, 'FAILED')\n    else:\n        if not failed:\n            msg = regular_generic_msg(hostname, result, oneline, 'success')\n        else:\n            msg = regular_generic_msg(hostname, result, oneline, 'FAILED')\n    return msg",
    "docstring": "summarize the JSON results for a particular host"
  },
  {
    "code": "def get_values (feature, properties):\n    if feature[0] != '<':\n     feature = '<' + feature + '>'\n    result = []\n    for p in properties:\n        if get_grist (p) == feature:\n            result.append (replace_grist (p, ''))\n    return result",
    "docstring": "Returns all values of the given feature specified by the given property set."
  },
  {
    "code": "def get_all_queues(self):\n        resp = self._call('getAllQueues', proto.Empty())\n        return [Queue.from_protobuf(q) for q in resp.queues]",
    "docstring": "Get information about all queues in the cluster.\n\n        Returns\n        -------\n        queues : list of Queue\n\n        Examples\n        --------\n        >>> client.get_all_queues()\n        [Queue<name='default', percent_used=0.00>,\n         Queue<name='myqueue', percent_used=5.00>,\n         Queue<name='child1', percent_used=10.00>,\n         Queue<name='child2', percent_used=0.00>]"
  },
  {
    "code": "def sort2groups(array, gpat=['_R1','_R2']):\n   groups = [REGroup(gp) for gp in gpat]\n   unmatched = []\n   for item in array:\n      matched = False\n      for m in groups:\n         if m.match(item):\n            matched = True\n            break\n      if not matched: unmatched.append(item)\n   return [sorted(m.list) for m in groups], sorted(unmatched)",
    "docstring": "Sort an array of strings to groups by patterns"
  },
  {
    "code": "def maybe_start_recording(tokens, index):\n        if _is_really_comment(tokens, index):\n            return _CommentedLineRecorder(index, tokens[index].line)\n        return None",
    "docstring": "Return a new _CommentedLineRecorder when it is time to record."
  },
  {
    "code": "def create(self, edgeList=None, excludeEdges=None, networkName=None, nodeList=None, source=None, verbose=False):\n        network=check_network(self,source, verbose=verbose)\n        PARAMS=set_param([\"edgeList\",\"excludeEdges\",\"networkName\",\"nodeList\",\"source\"], \\\n        [edgeList,excludeEdges,networkName,nodeList,network])\n        response=api(url=self.__url+\"/create\", PARAMS=PARAMS, method=\"POST\", verbose=verbose)\n        return response",
    "docstring": "Create a new network from a list of nodes and edges in an existing source network.\n        The SUID of the network and view are returned.\n\n        :param edgeList (string, optional): Specifies a list of edges. The keywords\n            all, selected, or unselected can be used to specify edges by their\n            selection state. The pattern COLUMN:VALUE sets this parameter to any\n            rows that contain the specified column value; if the COLUMN prefix is\n            not used, the NAME column is matched by default. A list of COLUMN:VALUE\n            pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be used to\n            match multiple values.\n        :param excludeEdges (string, optional): Unless this is set to true, edges\n            that connect nodes in the nodeList are implicitly included\n        :param networkName (string, optional):\n        :param nodeList (string, optional): Specifies a list of nodes. The keywords\n            all, selected, or unselected can be used to specify nodes by their\n            selection state. The pattern COLUMN:VALUE sets this parameter to any\n            rows that contain the specified column value; if the COLUMN prefix is\n            not used, the NAME column is matched by default. A list of COLUMN:VALUE\n            pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be used to\n            match multiple values.\n        :param source (string, optional): Specifies a network by name, or by SUID\n            if the prefix SUID: is used. The keyword CURRENT, or a blank value can\n            also be used to specify the current network.\n        :param verbose: print more\n\n        :returns: { netowrk, view }"
  },
  {
    "code": "def start_single(self, typ, scol):\n        self.starting_single = True\n        single = self.single = Single(typ=typ, group=self, indent=(scol - self.level))\n        self.singles.append(single)\n        return single",
    "docstring": "Start a new single"
  },
  {
    "code": "def log_value(self, name, value, step=None):\n        if isinstance(value, six.string_types):\n            raise TypeError('\"value\" should be a number, got {}'\n                            .format(type(value)))\n        value = float(value)\n        self._check_step(step)\n        tf_name = self._ensure_tf_name(name)\n        summary = self._scalar_summary(tf_name, value, step)\n        self._log_summary(tf_name, summary, value, step=step)",
    "docstring": "Log new value for given name on given step.\n\n        Args:\n            name (str): name of the variable (it will be converted to a valid\n                tensorflow summary name).\n            value (float): this is a real number to be logged as a scalar.\n            step (int): non-negative integer used for visualization: you can\n                log several different variables on one step, but should not log\n                different values of the same variable on the same step (this is\n                not checked)."
  },
  {
    "code": "def services(namespace='default', **kwargs):\n    cfg = _setup_conn(**kwargs)\n    try:\n        api_instance = kubernetes.client.CoreV1Api()\n        api_response = api_instance.list_namespaced_service(namespace)\n        return [srv['metadata']['name'] for srv in api_response.to_dict().get('items')]\n    except (ApiException, HTTPError) as exc:\n        if isinstance(exc, ApiException) and exc.status == 404:\n            return None\n        else:\n            log.exception(\n                'Exception when calling '\n                'CoreV1Api->list_namespaced_service'\n            )\n            raise CommandExecutionError(exc)\n    finally:\n        _cleanup(**cfg)",
    "docstring": "Return a list of kubernetes services defined in the namespace\n\n    CLI Examples::\n\n        salt '*' kubernetes.services\n        salt '*' kubernetes.services namespace=default"
  },
  {
    "code": "def call(self, name, request=None, **params):\n        if name not in self.resources:\n            raise exceptions.HttpError(\n                'Unknown method \\'%s\\'' % name,\n                status=status.HTTP_501_NOT_IMPLEMENTED)\n        request = request or HttpRequest()\n        resource = self.resources[name]\n        view = resource.as_view(api=self)\n        return view(request, **params)",
    "docstring": "Call resource by ``Api`` name.\n\n        :param name: The resource's name (short form)\n        :param request: django.http.Request instance\n        :param **params: Params for a resource's call\n\n        :return object: Result of resource's execution"
  },
  {
    "code": "def dtype_repr(dtype):\n    dtype = np.dtype(dtype)\n    if dtype == np.dtype(int):\n        return \"'int'\"\n    elif dtype == np.dtype(float):\n        return \"'float'\"\n    elif dtype == np.dtype(complex):\n        return \"'complex'\"\n    elif dtype.shape:\n        return \"('{}', {})\".format(dtype.base, dtype.shape)\n    else:\n        return \"'{}'\".format(dtype)",
    "docstring": "Stringify ``dtype`` for ``repr`` with default for int and float."
  },
  {
    "code": "def path_dwim(basedir, given):\n    if given.startswith(\"/\"):\n        return given\n    elif given.startswith(\"~/\"):\n        return os.path.expanduser(given)\n    else:\n        return os.path.join(basedir, given)",
    "docstring": "make relative paths work like folks expect."
  },
  {
    "code": "def get_valid_location(location):\n    if location is not None and cellular_components.get(location) is None:\n        loc = cellular_components_reverse.get(location)\n        if loc is None:\n            raise InvalidLocationError(location)\n        else:\n            return loc\n    return location",
    "docstring": "Check if the given location represents a valid cellular component."
  },
  {
    "code": "def check_for_local_repos(repo):\n    repos_dict = Repo().default_repository()\n    if repo in repos_dict:\n        repo_url = repos_dict[repo]\n        if repo_url.startswith(\"file:///\"):\n            return True",
    "docstring": "Check if repository is local"
  },
  {
    "code": "def speak(self, text):\n        if not self.is_valid_string(text):\n            raise Exception(\"%s is not ISO-8859-1 compatible.\" % (text))\n        if len(text) > 1023:\n            lines = self.word_wrap(text, width=1023)\n            for line in lines:\n                self.queue.put(\"S%s\" % (line))\n        else:\n            self.queue.put(\"S%s\" % (text))",
    "docstring": "The main function to convert text into speech."
  },
  {
    "code": "def generate_accounts(seeds):\n    return {\n        seed: {\n            'privatekey': encode_hex(sha3(seed)),\n            'address': encode_hex(privatekey_to_address(sha3(seed))),\n        }\n        for seed in seeds\n    }",
    "docstring": "Create private keys and addresses for all seeds."
  },
  {
    "code": "def check_yamls(cls, dap):\n        problems = list()\n        for yaml in dap.assistants_and_snippets:\n            path = yaml + '.yaml'\n            parsed_yaml = YamlLoader.load_yaml_by_path(dap._get_file(path, prepend=True))\n            if parsed_yaml:\n                try:\n                    yaml_checker.check(path, parsed_yaml)\n                except YamlError as e:\n                    problems.append(DapProblem(exc_as_decoded_string(e), level=logging.ERROR))\n            else:\n                problems.append(DapProblem('Empty YAML ' + path, level=logging.WARNING))\n        return problems",
    "docstring": "Check that all assistants and snippets are valid.\n\n        Return list of DapProblems."
  },
  {
    "code": "def add_json(self, json_obj, **kwargs):\n        return self.add_bytes(encoding.Json().encode(json_obj), **kwargs)",
    "docstring": "Adds a json-serializable Python dict as a json file to IPFS.\n\n        .. code-block:: python\n\n            >>> c.add_json({'one': 1, 'two': 2, 'three': 3})\n            'QmVz9g7m5u3oHiNKHj2CJX1dbG1gtismRS3g9NaPBBLbob'\n\n        Parameters\n        ----------\n        json_obj : dict\n            A json-serializable Python dictionary\n\n        Returns\n        -------\n            str : Hash of the added IPFS object"
  },
  {
    "code": "def flux_up(self, fluxUpBottom, emission=None):\n        if emission is None:\n            emission = np.zeros_like(self.absorptivity)\n        E = np.concatenate((emission, np.atleast_1d(fluxUpBottom)), axis=-1)\n        return np.squeeze(matrix_multiply(self.Tup, E[..., np.newaxis]))",
    "docstring": "Compute downwelling radiative flux at interfaces between layers.\n\n        Inputs:\n\n            * fluxDownTop: flux down at top\n            * emission: emission from atmospheric levels (N)\n              defaults to zero if not given\n\n        Returns:\n\n            * vector of downwelling radiative flux between levels (N+1)\n              element 0 is the flux down to the surface."
  },
  {
    "code": "def get_name(self, **values) -> str:\n        if not values and self.name:\n            return self.name\n        if values:\n            for ck, cvs in _sorted_items(self.compounds):\n                if ck in cvs and ck in values:\n                    continue\n                comp_values = [values.pop(cv, getattr(self, cv)) for cv in cvs]\n                if None not in comp_values:\n                    values[ck] = ''.join(rf'{v}' for v in comp_values)\n        return self._get_nice_name(**values)",
    "docstring": "Get a new name string from this object's name values.\n\n        :param values: Variable keyword arguments where the **key** should refer to a field on this object that will\n                       use the provided **value** to build the new name."
  },
  {
    "code": "def read_data_from_bin_file(fileName):\n    with open(fileName, mode='rb') as file:\n        fileContent = file.read()\n    (ChannelData, LenOf1Channel,\n     NumOfChannels, SampleTime) = read_data_from_bytes(fileContent)\n    return ChannelData, LenOf1Channel, NumOfChannels, SampleTime",
    "docstring": "Loads the binary data stored in the a binary file and extracts the \n    data for each channel that was saved, along with the sample rate and length\n    of the data array.\n\n    Parameters\n    ----------\n    fileContent : bytes \n        bytes object containing the data from a .bin file exported from\n        the saleae data logger.\n    \n    Returns\n    -------\n    ChannelData : list\n        List containing a list which contains the data from each channel\n    LenOf1Channel : int\n        The length of the data in each channel\n    NumOfChannels : int\n        The number of channels saved\n    SampleTime : float\n        The time between samples (in seconds)\n    SampleRate : float\n        The sample rate (in Hz)"
  },
  {
    "code": "def tickerId(self, contract_identifier):\n        symbol = contract_identifier\n        if isinstance(symbol, Contract):\n            symbol = self.contractString(symbol)\n        for tickerId in self.tickerIds:\n            if symbol == self.tickerIds[tickerId]:\n                return tickerId\n        else:\n            tickerId = len(self.tickerIds)\n            self.tickerIds[tickerId] = symbol\n            return tickerId",
    "docstring": "returns the tickerId for the symbol or\n        sets one if it doesn't exits"
  },
  {
    "code": "def disqus_sso_script(context):\n    settings = context[\"settings\"]\n    public_key = getattr(settings, \"COMMENTS_DISQUS_API_PUBLIC_KEY\", \"\")\n    secret_key = getattr(settings, \"COMMENTS_DISQUS_API_SECRET_KEY\", \"\")\n    user = context[\"request\"].user\n    if public_key and secret_key and user.is_authenticated():\n        context[\"public_key\"] = public_key\n        context[\"sso_data\"] = _get_disqus_sso(user, public_key, secret_key)\n    return context",
    "docstring": "Provides a generic context variable which adds single-sign-on\n    support to DISQUS if ``COMMENTS_DISQUS_API_PUBLIC_KEY`` and\n    ``COMMENTS_DISQUS_API_SECRET_KEY`` are specified."
  },
  {
    "code": "def is_bytes(string):\n    if six.PY3 and isinstance(string, (bytes, memoryview, bytearray)):\n        return True\n    elif six.PY2 and isinstance(string, (buffer, bytearray)):\n        return True\n    return False",
    "docstring": "Check if a string is a bytes instance\n\n    :param Union[str, bytes] string: A string that may be string or bytes like\n    :return: Whether the provided string is a bytes type or not\n    :rtype: bool"
  },
  {
    "code": "def __process_acl(self, load, auth_list):\n        if 'eauth' not in load:\n            return auth_list\n        fstr = '{0}.process_acl'.format(load['eauth'])\n        if fstr not in self.auth:\n            return auth_list\n        try:\n            return self.auth[fstr](auth_list, self.opts)\n        except Exception as e:\n            log.debug('Authentication module threw %s', e)\n            return auth_list",
    "docstring": "Allows eauth module to modify the access list right before it'll be applied to the request.\n        For example ldap auth module expands entries"
  },
  {
    "code": "def get_db(cls):\n        if cls._db:\n            return getattr(cls._client, cls._db)\n        return cls._client.get_default_database()",
    "docstring": "Return the database for the collection"
  },
  {
    "code": "def divide(x1, x2, output_shape=None, name=None):\n  output_shape = convert_to_shape(output_shape)\n  if not isinstance(x2, Tensor):\n    return ScalarMultiplyOperation(x1, 1.0 / x2).outputs[0]\n  with tf.name_scope(name, default_name=\"divide\"):\n    x1, x2 = binary_arguments_to_tensors(x1, x2)\n    return multiply(x1, reciprocal(x2), output_shape=output_shape)",
    "docstring": "Binary division with broadcasting.\n\n  Args:\n    x1: a Tensor\n    x2: a Tensor\n    output_shape: an optional Shape\n    name: an optional string\n  Returns:\n    a Tensor"
  },
  {
    "code": "def is_valid_data(obj):\n    if obj:\n        try:\n            tmp = json.dumps(obj, default=datetime_encoder)\n            del tmp\n        except (TypeError, UnicodeDecodeError):\n            return False\n    return True",
    "docstring": "Check if data is JSON serializable."
  },
  {
    "code": "def human_readable(self, dense_repr: Sequence[Sequence[int]]) -> List[List[str]]:\n        transcripts = []\n        for dense_r in dense_repr:\n            non_empty_phonemes = [phn_i for phn_i in dense_r if phn_i != 0]\n            transcript = self.corpus.indices_to_labels(non_empty_phonemes)\n            transcripts.append(transcript)\n        return transcripts",
    "docstring": "Returns a human readable version of a dense representation of\n        either or reference to facilitate simple manual inspection."
  },
  {
    "code": "def get_config(config, default_config):\n    if not config:\n        logging.warning('Using default config: %s', default_config)\n        config = default_config\n    try:\n        with open(config, 'r') as config_file:\n            return yaml.load(config_file)\n    except (yaml.reader.ReaderError,\n            yaml.parser.ParserError,\n            yaml.scanner.ScannerError) as e:\n        raise ConfigError('Invalid yaml file: \\n %s' % str(e))",
    "docstring": "Load configuration from file if in config, else use default"
  },
  {
    "code": "def clean_email(self):\n        if get_user_model().objects.filter(\n            Q(email__iexact=self.cleaned_data['email']) |\n            Q(email_unconfirmed__iexact=self.cleaned_data['email'])):\n            raise forms.ValidationError(_(u'This email address is already '\n                        'in use. Please supply a different email.'))\n        return self.cleaned_data['email']",
    "docstring": "Validate that the email address is unique."
  },
  {
    "code": "def totalNumberOfTiles(self, minZoom=None, maxZoom=None):\n        \"Return the total number of tiles for this instance extent\"\n        nbTiles = 0\n        minZoom = minZoom or 0\n        if maxZoom:\n            maxZoom = maxZoom + 1\n        else:\n            maxZoom = len(self.RESOLUTIONS)\n        for zoom in xrange(minZoom, maxZoom):\n            nbTiles += self.numberOfTilesAtZoom(zoom)\n        return nbTiles",
    "docstring": "Return the total number of tiles for this instance extent"
  },
  {
    "code": "def _check(peers):\n    if not isinstance(peers, list):\n        return False\n    for peer in peers:\n        if not isinstance(peer, six.string_types):\n            return False\n    if not HAS_NETADDR:\n        return True\n    ip_only_peers = []\n    for peer in peers:\n        try:\n            ip_only_peers.append(six.text_type(IPAddress(peer)))\n        except AddrFormatError:\n            if not HAS_DNSRESOLVER:\n                continue\n            dns_reply = []\n            try:\n                dns_reply = dns.resolver.query(peer)\n            except dns.resolver.NoAnswer:\n                return False\n            for dns_ip in dns_reply:\n                ip_only_peers.append(six.text_type(dns_ip))\n    peers = ip_only_peers\n    return True",
    "docstring": "Checks whether the input is a valid list of peers and transforms domain names into IP Addresses"
  },
  {
    "code": "def x_runtime(f, *args, **kwargs):\n    _t0 = now()\n    r = f(*args, **kwargs)\n    _t1 = now()\n    r.headers['X-Runtime'] = '{0}s'.format(Decimal(str(_t1 - _t0)))\n    return r",
    "docstring": "X-Runtime Flask Response Decorator."
  },
  {
    "code": "def found(self):\n        if 'ids' in self.kwargs:\n            cid = self.kwargs['query']['collection']['eq']\n            return len(self.items_by_id(self.kwargs['ids'], cid))\n        kwargs = {\n            'page': 1,\n            'limit': 0\n        }\n        kwargs.update(self.kwargs)\n        results = self.query(**kwargs)\n        return results['meta']['found']",
    "docstring": "Small query to determine total number of hits"
  },
  {
    "code": "def locate_private_alleles(*acs):\n    acs = [asarray_ndim(ac, 2) for ac in acs]\n    check_dim0_aligned(*acs)\n    acs = ensure_dim1_aligned(*acs)\n    pac = np.dstack(acs)\n    npa = np.sum(pac > 0, axis=2)\n    loc_pa = npa == 1\n    return loc_pa",
    "docstring": "Locate alleles that are found only in a single population.\n\n    Parameters\n    ----------\n    *acs : array_like, int, shape (n_variants, n_alleles)\n        Allele counts arrays from each population.\n\n    Returns\n    -------\n    loc : ndarray, bool, shape (n_variants, n_alleles)\n        Boolean array where elements are True if allele is private to a\n        single population.\n\n    Examples\n    --------\n\n    >>> import allel\n    >>> g = allel.GenotypeArray([[[0, 0], [0, 0], [1, 1], [1, 1]],\n    ...                          [[0, 1], [0, 1], [0, 1], [0, 1]],\n    ...                          [[0, 1], [0, 1], [1, 1], [1, 1]],\n    ...                          [[0, 0], [0, 0], [1, 1], [2, 2]],\n    ...                          [[0, 0], [-1, -1], [1, 1], [-1, -1]]])\n    >>> ac1 = g.count_alleles(subpop=[0, 1])\n    >>> ac2 = g.count_alleles(subpop=[2])\n    >>> ac3 = g.count_alleles(subpop=[3])\n    >>> loc_private_alleles = allel.locate_private_alleles(ac1, ac2, ac3)\n    >>> loc_private_alleles\n    array([[ True, False, False],\n           [False, False, False],\n           [ True, False, False],\n           [ True,  True,  True],\n           [ True,  True, False]])\n    >>> loc_private_variants = np.any(loc_private_alleles, axis=1)\n    >>> loc_private_variants\n    array([ True, False,  True,  True,  True])"
  },
  {
    "code": "def gradfunc(self, p):\n        self._set_stochastics(p)\n        for i in xrange(self.len):\n            self.grad[i] = self.diff(i)\n        return -1 * self.grad",
    "docstring": "The gradient-computing function that gets passed to the optimizers,\n        if needed."
  },
  {
    "code": "def function_call_with_timeout(fun_name, fun_args, secs=5):\n    from multiprocessing import Process, Queue\n    p = Process(target=fun_name, args=tuple(fun_args))\n    p.start()\n    curr_secs = 0\n    no_timeout = False\n    if secs == 0: no_timeout = True\n    else: timeout = secs\n    while p.is_alive() and not no_timeout:\n        if curr_secs > timeout:\n            print(\"Process time has exceeded timeout, terminating it.\")\n            p.terminate()\n            return False\n        time.sleep(0.1)\n        curr_secs += 0.1\n    p.join()\n    return True",
    "docstring": "Run a Python function with a timeout.  No interprocess communication or\n    return values are handled.  Setting secs to 0 gives infinite timeout."
  },
  {
    "code": "def __flush(self, async=True):\n        rh = self.rh\n        messages = list(self.messages)\n        stream_notices = list(self.stream_notices)\n        self.stream_notices = []\n        self.messages = []\n        args = (rh, messages, stream_notices)\n        if async:\n            self.hub.threadPool.execute_named(self.__inner_flush,\n                '%s __inner__flush' % self.hub.l.name, *args)\n        else:\n            self.__inner_flush(*args)\n        self.rh = None\n        self._set_timeout(int(time.time() + self.hub.timeout))",
    "docstring": "Flushes messages through current HttpRequest and closes it.\n            It assumes a current requesthandler and requires a lock\n            on self.lock"
  },
  {
    "code": "def recv_exit_status(self, command, timeout=10, get_pty=False):\n        status = None\n        self.last_command = command\n        stdin, stdout, stderr = self.cli.exec_command(command, get_pty=get_pty)\n        if stdout and stderr and stdin:\n            for _ in range(timeout):\n                if stdout.channel.exit_status_ready():\n                    status = stdout.channel.recv_exit_status()\n                    break\n                time.sleep(1)\n            self.last_stdout = stdout.read()\n            self.last_stderr = stderr.read()\n            stdin.close()\n            stdout.close()\n            stderr.close()\n        return status",
    "docstring": "Execute a command and get its return value\n\n        @param command: command to execute\n        @type command: str\n\n        @param timeout: command execution timeout\n        @type timeout: int\n\n        @param get_pty: get pty\n        @type get_pty: bool\n\n        @return: the exit code of the process or None in case of timeout\n        @rtype: int or None"
  },
  {
    "code": "def has_object_permission(self, request, view, obj):\n        if not self.object_permissions:\n            return True\n        serializer_class = view.get_serializer_class()\n        model_class = serializer_class.Meta.model\n        action_method_name = None\n        if hasattr(view, 'action'):\n            action = self._get_action(view.action)\n            action_method_name = \"has_object_{action}_permission\".format(action=action)\n            if hasattr(obj, action_method_name):\n                return getattr(obj, action_method_name)(request)\n        if request.method in permissions.SAFE_METHODS:\n            assert hasattr(obj, 'has_object_read_permission'), \\\n                self._get_error_message(model_class, 'has_object_read_permission', action_method_name)\n            return obj.has_object_read_permission(request)\n        else:\n            assert hasattr(obj, 'has_object_write_permission'), \\\n                self._get_error_message(model_class, 'has_object_write_permission', action_method_name)\n            return obj.has_object_write_permission(request)",
    "docstring": "Overrides the standard function and figures out methods to call for object permissions."
  },
  {
    "code": "def parse_if(self):\n        node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)\n        while 1:\n            node.test = self.parse_tuple(with_condexpr=False)\n            node.body = self.parse_statements(('name:elif', 'name:else',\n                                               'name:endif'))\n            node.elif_ = []\n            node.else_ = []\n            token = next(self.stream)\n            if token.test('name:elif'):\n                node = nodes.If(lineno=self.stream.current.lineno)\n                result.elif_.append(node)\n                continue\n            elif token.test('name:else'):\n                result.else_ = self.parse_statements(('name:endif',),\n                                                     drop_needle=True)\n            break\n        return result",
    "docstring": "Parse an if construct."
  },
  {
    "code": "def get_user_if_exists(strategy, details, user=None, *args, **kwargs):\n    if user:\n        return {'is_new': False}\n    try:\n        username = details.get('username')\n        return {\n            'is_new': False,\n            'user': User.objects.get(username=username)\n        }\n    except User.DoesNotExist:\n        pass\n    return {}",
    "docstring": "Return a User with the given username iff the User exists."
  },
  {
    "code": "def get_next_invalid_time_from_t(self, timestamp):\n        if not self.is_time_valid(timestamp):\n            return timestamp\n        t_day = self.get_next_invalid_day(timestamp)\n        if timestamp < t_day:\n            sec_from_morning = self.get_next_future_timerange_invalid(t_day)\n        else:\n            sec_from_morning = self.get_next_future_timerange_invalid(timestamp)\n        if t_day is not None and sec_from_morning is not None:\n            return t_day + sec_from_morning + 1\n        if t_day is not None and sec_from_morning is None:\n            return t_day\n        timestamp = get_day(timestamp) + 86400\n        t_day2 = self.get_next_invalid_day(timestamp)\n        sec_from_morning = self.get_next_future_timerange_invalid(t_day2)\n        if t_day2 is not None and sec_from_morning is not None:\n            return t_day2 + sec_from_morning + 1\n        if t_day2 is not None and sec_from_morning is None:\n            return t_day2\n        return None",
    "docstring": "Get next invalid time for time range\n\n        :param timestamp: time we compute from\n        :type timestamp: int\n        :return: timestamp of the next invalid time (LOCAL TIME)\n        :rtype: int"
  },
  {
    "code": "def stelab(pobj, vobs):\n    pobj = stypes.toDoubleVector(pobj)\n    vobs = stypes.toDoubleVector(vobs)\n    appobj = stypes.emptyDoubleVector(3)\n    libspice.stelab_c(pobj, vobs, appobj)\n    return stypes.cVectorToPython(appobj)",
    "docstring": "Correct the apparent position of an object for stellar\n    aberration.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/stelab_c.html\n\n    :param pobj: Position of an object with respect to the observer.\n    :type pobj: 3-Element Array of floats\n    :param vobs:\n                Velocity of the observer with respect\n                to the Solar System barycenter.\n    :type vobs: 3-Element Array of floats\n    :return:\n            Apparent position of the object with respect to\n            the observer, corrected for stellar aberration.\n    :rtype: 3-Element Array of floats"
  },
  {
    "code": "def configure(self, **configs):\n        configs = self._deprecate_configs(**configs)\n        self._config = {}\n        for key in self.DEFAULT_CONFIG:\n            self._config[key] = configs.pop(key, self.DEFAULT_CONFIG[key])\n        if configs:\n            raise KafkaConfigurationError('Unknown configuration key(s): ' +\n                                          str(list(configs.keys())))\n        if self._config['auto_commit_enable']:\n            if not self._config['group_id']:\n                raise KafkaConfigurationError(\n                    'KafkaConsumer configured to auto-commit '\n                    'without required consumer group (group_id)'\n                )\n        if self._config['auto_commit_enable']:\n            logger.info(\"Configuring consumer to auto-commit offsets\")\n            self._reset_auto_commit()\n        if not self._config['bootstrap_servers']:\n            raise KafkaConfigurationError(\n                'bootstrap_servers required to configure KafkaConsumer'\n            )\n        self._client = KafkaClient(\n            self._config['bootstrap_servers'],\n            client_id=self._config['client_id'],\n            timeout=(self._config['socket_timeout_ms'] / 1000.0)\n        )",
    "docstring": "Configure the consumer instance\n\n        Configuration settings can be passed to constructor,\n        otherwise defaults will be used:\n\n        Keyword Arguments:\n            bootstrap_servers (list): List of initial broker nodes the consumer\n                should contact to bootstrap initial cluster metadata.  This does\n                not have to be the full node list.  It just needs to have at\n                least one broker that will respond to a Metadata API Request.\n            client_id (str): a unique name for this client.  Defaults to\n                'kafka.consumer.kafka'.\n            group_id (str): the name of the consumer group to join,\n                Offsets are fetched / committed to this group name.\n            fetch_message_max_bytes (int, optional): Maximum bytes for each\n                topic/partition fetch request.  Defaults to 1024*1024.\n            fetch_min_bytes (int, optional): Minimum amount of data the server\n                should return for a fetch request, otherwise wait up to\n                fetch_wait_max_ms for more data to accumulate.  Defaults to 1.\n            fetch_wait_max_ms (int, optional): Maximum time for the server to\n                block waiting for fetch_min_bytes messages to accumulate.\n                Defaults to 100.\n            refresh_leader_backoff_ms (int, optional): Milliseconds to backoff\n                when refreshing metadata on errors (subject to random jitter).\n                Defaults to 200.\n            socket_timeout_ms (int, optional): TCP socket timeout in\n                milliseconds.  Defaults to 30*1000.\n            auto_offset_reset (str, optional): A policy for resetting offsets on\n                OffsetOutOfRange errors. 'smallest' will move to the oldest\n                available message, 'largest' will move to the most recent.  Any\n                ofther value will raise the exception.  Defaults to 'largest'.\n            deserializer_class (callable, optional):  Any callable that takes a\n                raw message value and returns a deserialized value.  Defaults to\n                 lambda msg: msg.\n            auto_commit_enable (bool, optional): Enabling auto-commit will cause\n                the KafkaConsumer to periodically commit offsets without an\n                explicit call to commit().  Defaults to False.\n            auto_commit_interval_ms (int, optional):  If auto_commit_enabled,\n                the milliseconds between automatic offset commits.  Defaults to\n                60 * 1000.\n            auto_commit_interval_messages (int, optional): If\n                auto_commit_enabled, a number of messages consumed between\n                automatic offset commits.  Defaults to None (disabled).\n            consumer_timeout_ms (int, optional): number of millisecond to throw\n                a timeout exception to the consumer if no message is available\n                for consumption.  Defaults to -1 (dont throw exception).\n\n        Configuration parameters are described in more detail at\n        http://kafka.apache.org/documentation.html#highlevelconsumerapi"
  },
  {
    "code": "def create_shared(self, name, ref):\n        if self._shared is not None:\n            raise RuntimeError('Can only set_shared once.')\n        self._shared = GLShared(name, ref)",
    "docstring": "For the app backends to create the GLShared object.\n\n        Parameters\n        ----------\n        name : str\n            The name.\n        ref : object\n            The reference."
  },
  {
    "code": "def compute_fw_at_frac_max_1d_simple(Y, xc, X=None, f=0.5):\n    yy = np.asarray(Y)\n    if yy.ndim != 1:\n        raise ValueError('array must be 1-d')\n    if yy.size == 0:\n        raise ValueError('array is empty')\n    if X is None:\n        xx = np.arange(yy.shape[0])\n    else:\n        xx = X\n    xpix = coor_to_pix_1d(xc - xx[0])\n    try:\n        peak = yy[xpix]\n    except IndexError:\n        raise ValueError('peak is out of array')\n    fwhm_x, _codex, _msgx = compute_fwhm_1d(xx, yy - f * peak, xc, xpix)\n    return peak, fwhm_x",
    "docstring": "Compute the full width at fraction f of the maximum"
  },
  {
    "code": "def upload(self, filename, filedata=None, filepath=None, **kwargs):\n        if filepath is None and filedata is None:\n            raise GitlabUploadError(\"No file contents or path specified\")\n        if filedata is not None and filepath is not None:\n            raise GitlabUploadError(\"File contents and file path specified\")\n        if filepath is not None:\n            with open(filepath, \"rb\") as f:\n                filedata = f.read()\n        url = ('/projects/%(id)s/uploads' % {\n            'id': self.id,\n        })\n        file_info = {\n            'file': (filename, filedata),\n        }\n        data = self.manager.gitlab.http_post(url, files=file_info)\n        return {\n            \"alt\": data['alt'],\n            \"url\": data['url'],\n            \"markdown\": data['markdown']\n        }",
    "docstring": "Upload the specified file into the project.\n\n        .. note::\n\n            Either ``filedata`` or ``filepath`` *MUST* be specified.\n\n        Args:\n            filename (str): The name of the file being uploaded\n            filedata (bytes): The raw data of the file being uploaded\n            filepath (str): The path to a local file to upload (optional)\n\n        Raises:\n            GitlabConnectionError: If the server cannot be reached\n            GitlabUploadError: If the file upload fails\n            GitlabUploadError: If ``filedata`` and ``filepath`` are not\n                specified\n            GitlabUploadError: If both ``filedata`` and ``filepath`` are\n                specified\n\n        Returns:\n            dict: A ``dict`` with the keys:\n                * ``alt`` - The alternate text for the upload\n                * ``url`` - The direct url to the uploaded file\n                * ``markdown`` - Markdown for the uploaded file"
  },
  {
    "code": "def updateColormap(self):\n        if self.imgArgs['lut'] is not None:\n            self.img.setLookupTable(self.imgArgs['lut'])\n            self.img.setLevels(self.imgArgs['levels'])",
    "docstring": "Updates the currently colormap accoring to stored settings"
  },
  {
    "code": "def _resume_ssl_session(\n            server_info: ServerConnectivityInfo,\n            ssl_version_to_use: OpenSslVersionEnum,\n            ssl_session: Optional[nassl._nassl.SSL_SESSION] = None,\n            should_enable_tls_ticket: bool = False\n    ) -> nassl._nassl.SSL_SESSION:\n        ssl_connection = server_info.get_preconfigured_ssl_connection(override_ssl_version=ssl_version_to_use)\n        if not should_enable_tls_ticket:\n            ssl_connection.ssl_client.disable_stateless_session_resumption()\n        if ssl_session:\n            ssl_connection.ssl_client.set_session(ssl_session)\n        try:\n            ssl_connection.connect()\n            new_session = ssl_connection.ssl_client.get_session()\n        finally:\n            ssl_connection.close()\n        return new_session",
    "docstring": "Connect to the server and returns the session object that was assigned for that connection.\n        If ssl_session is given, tries to resume that session."
  },
  {
    "code": "def create(self, networkipv4s):\n        data = {'networks': networkipv4s}\n        return super(ApiNetworkIPv4, self).post('api/v3/networkv4/', data)",
    "docstring": "Method to create network-ipv4's\n\n        :param networkipv4s: List containing networkipv4's desired to be created on database\n        :return: None"
  },
  {
    "code": "def remover(self, id_groupl3):\n        if not is_valid_int_param(id_groupl3):\n            raise InvalidParameterError(\n                u'The identifier of Group L3 is invalid or was not informed.')\n        url = 'groupl3/' + str(id_groupl3) + '/'\n        code, xml = self.submit(None, 'DELETE', url)\n        return self.response(code, xml)",
    "docstring": "Remove Group L3 from by the identifier.\n\n        :param id_groupl3: Identifier of the Group L3. Integer value and greater than zero.\n\n        :return: None\n\n        :raise InvalidParameterError: The identifier of Group L3 is null and invalid.\n        :raise GrupoL3NaoExisteError: Group L3 not registered.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def to_dict(self, properties=True):\n        nodes = {}\n        for node in self.nodes():\n            nd = {\n                'label': node.pred.short_form(),\n                'edges': self.edges(node.nodeid)\n            }\n            if node.lnk is not None:\n                nd['lnk'] = {'from': node.cfrom, 'to': node.cto}\n            if properties:\n                if node.cvarsort is not None:\n                    nd['type'] = node.cvarsort\n                props = node.properties\n                if props:\n                    nd['properties'] = props\n            if node.carg is not None:\n                nd['carg'] = node.carg\n            nodes[node.nodeid] = nd\n        return {'top': self.top, 'nodes': nodes}",
    "docstring": "Encode the Eds as a dictionary suitable for JSON serialization."
  },
  {
    "code": "def axis(self) -> Callable[[Any], Any]:\n        axis_func = hist_axis_func(\n            axis_type = self.axis_type\n        )\n        return axis_func",
    "docstring": "Determine the axis to return based on the hist type."
  },
  {
    "code": "def _forceInt(x,y,z,dens,b2,c2,i,glx=None,glw=None):\n    def integrand(s):\n        t= 1/s**2.-1.\n        return dens(numpy.sqrt(x**2./(1.+t)+y**2./(b2+t)+z**2./(c2+t)))\\\n            *(x/(1.+t)*(i==0)+y/(b2+t)*(i==1)+z/(c2+t)*(i==2))\\\n            /numpy.sqrt((1.+(b2-1.)*s**2.)*(1.+(c2-1.)*s**2.))\n    if glx is None:\n        return integrate.quad(integrand,0.,1.)[0]                              \n    else:\n        return numpy.sum(glw*integrand(glx))",
    "docstring": "Integral that gives the force in x,y,z"
  },
  {
    "code": "def _calculate_solar_time(self, hour, eq_of_time, is_solar_time):\n        if is_solar_time:\n            return hour\n        return (\n            (hour * 60 + eq_of_time + 4 * math.degrees(self._longitude) -\n             60 * self.time_zone) % 1440) / 60",
    "docstring": "Calculate Solar time for an hour."
  },
  {
    "code": "def fromLatex(tex, *args, **kwargs):\n        source = TexSoup(tex)\n        return TOC('[document]', source=source,\n            descendants=list(source.descendants), *args, **kwargs)",
    "docstring": "Creates abstraction using Latex\n\n        :param str tex: Latex\n        :return: TreeOfContents object"
  },
  {
    "code": "def remove_overlap(self, begin, end=None):\n        hitlist = self.at(begin) if end is None else self.overlap(begin, end)\n        for iv in hitlist:\n            self.remove(iv)",
    "docstring": "Removes all intervals overlapping the given point or range.\n\n        Completes in O((r+m)*log n) time, where:\n          * n = size of the tree\n          * m = number of matches\n          * r = size of the search range (this is 1 for a point)"
  },
  {
    "code": "def str_deps(self):\n        lines = []\n        app = lines.append\n        app(\"Dependencies of node %s:\" % str(self))\n        for i, dep in enumerate(self.deps):\n            app(\"%d) %s, status=%s\" % (i, dep.info, str(dep.status)))\n        return \"\\n\".join(lines)",
    "docstring": "Return the string representation of the dependencies of the node."
  },
  {
    "code": "async def execute(self, keys=[], args=[], client=None):\n        \"Execute the script, passing any required ``args``\"\n        if client is None:\n            client = self.registered_client\n        args = tuple(keys) + tuple(args)\n        if isinstance(client, BasePipeline):\n            client.scripts.add(self)\n        try:\n            return await client.evalsha(self.sha, len(keys), *args)\n        except NoScriptError:\n            self.sha = await client.script_load(self.script)\n            return await client.evalsha(self.sha, len(keys), *args)",
    "docstring": "Execute the script, passing any required ``args``"
  },
  {
    "code": "def pubmed_url(args=sys.argv[1:], resolve_doi=True, out=sys.stdout):\n    parser = argparse.ArgumentParser(\n        description='Get a publication URL using a PubMed ID or PubMed URL')\n    parser.add_argument('query', help='PubMed ID or PubMed URL')\n    parser.add_argument(\n        '-d', '--doi', action='store_false', help='get DOI URL')\n    parser.add_argument(\n        '-e', '--email', action='store', help='set user email', default='')\n    args = parser.parse_args(args=args)\n    lookup = PubMedLookup(args.query, args.email)\n    publication = Publication(lookup, resolve_doi=args.doi)\n    out.write(publication.url + '\\n')",
    "docstring": "Get a publication URL via the command line using a PubMed ID or PubMed URL"
  },
  {
    "code": "def geo(self):\n        out = dict(zip(['xmin', 'xres', 'rotation_x', 'ymax', 'rotation_y', 'yres'],\n                       self.raster.GetGeoTransform()))\n        out['xmax'] = out['xmin'] + out['xres'] * self.cols\n        out['ymin'] = out['ymax'] + out['yres'] * self.rows\n        return out",
    "docstring": "General image geo information.\n\n        Returns\n        -------\n        dict\n            a dictionary with keys `xmin`, `xmax`, `xres`, `rotation_x`, `ymin`, `ymax`, `yres`, `rotation_y`"
  },
  {
    "code": "def cyvcf_add_filter(rec, name):\n    if rec.FILTER:\n        filters = rec.FILTER.split(\";\")\n    else:\n        filters = []\n    if name not in filters:\n        filters.append(name)\n        rec.FILTER = filters\n    return rec",
    "docstring": "Add a FILTER value to a cyvcf2 record"
  },
  {
    "code": "def cache_hash(*a, **kw):\n    def cache_str(o):\n        if isinstance(o, (types.FunctionType, types.BuiltinFunctionType,\n                          types.MethodType, types.BuiltinMethodType,\n                          types.UnboundMethodType)):\n            return getattr(o, 'func_name', 'func')\n        if isinstance(o, dict):\n            o = [k + ':' + cache_str(v) for k, v in o.items()]\n        if isinstance(o, (list, tuple, set)):\n            o = sorted(map(cache_str, o))\n            o = '|'.join(o)\n        if isinstance(o, basestring):\n            return o\n        if hasattr(o, 'updated_at'):\n            return cache_str((repr(o), o.updated_at))\n        return repr(o)\n    hash = cache_str((a, kw)).encode('utf-8')\n    return sha1(hash).hexdigest()",
    "docstring": "Try to hash an arbitrary object for caching."
  },
  {
    "code": "def get_soql_fields(soql):\n    soql_fields = re.search('(?<=select)(?s)(.*)(?=from)', soql, re.IGNORECASE)\n    soql_fields = re.sub(' ', '', soql_fields.group())\n    soql_fields = re.sub('\\t', '', soql_fields)\n    fields = re.split(',|\\n|\\r|', soql_fields)\n    fields = [field for field in fields if field != '']\n    return fields",
    "docstring": "Gets queried columns names."
  },
  {
    "code": "def _one_hidden(self, l:int)->Tensor:\n        \"Return one hidden state.\"\n        nh = (self.n_hid if l != self.n_layers - 1 else self.emb_sz) // self.n_dir\n        return one_param(self).new(1, self.bs, nh).zero_()",
    "docstring": "Return one hidden state."
  },
  {
    "code": "def read(self):\n        found = Client.read(self)\n        if self.needs_distribute_ready():\n            self.distribute_ready()\n        return found",
    "docstring": "Read some number of messages"
  },
  {
    "code": "def visualize(\n    logdir, outdir, num_agents, num_episodes, checkpoint=None,\n    env_processes=True):\n  config = utility.load_config(logdir)\n  with tf.device('/cpu:0'):\n    batch_env = utility.define_batch_env(\n        lambda: _create_environment(config, outdir),\n        num_agents, env_processes)\n    graph = utility.define_simulation_graph(\n        batch_env, config.algorithm, config)\n    total_steps = num_episodes * config.max_length\n    loop = _define_loop(graph, total_steps)\n  saver = utility.define_saver(\n      exclude=(r'.*_temporary.*', r'global_step'))\n  sess_config = tf.ConfigProto(allow_soft_placement=True)\n  sess_config.gpu_options.allow_growth = True\n  with tf.Session(config=sess_config) as sess:\n    utility.initialize_variables(\n        sess, saver, config.logdir, checkpoint, resume=True)\n    for unused_score in loop.run(sess, saver, total_steps):\n      pass\n  batch_env.close()",
    "docstring": "Recover checkpoint and render videos from it.\n\n  Args:\n    logdir: Logging directory of the trained algorithm.\n    outdir: Directory to store rendered videos in.\n    num_agents: Number of environments to simulate in parallel.\n    num_episodes: Total number of episodes to simulate.\n    checkpoint: Checkpoint name to load; defaults to most recent.\n    env_processes: Whether to step environments in separate processes."
  },
  {
    "code": "def _load_properties(property_name, config_option, set_default=False, default=None):\n    if not property_name:\n        log.debug(\"No property specified in function, trying to load from salt configuration\")\n        try:\n            options = __salt__['config.option']('cassandra')\n        except BaseException as e:\n            log.error(\"Failed to get cassandra config options. Reason: %s\", e)\n            raise\n        loaded_property = options.get(config_option)\n        if not loaded_property:\n            if set_default:\n                log.debug('Setting default Cassandra %s to %s', config_option, default)\n                loaded_property = default\n            else:\n                log.error('No cassandra %s specified in the configuration or passed to the module.', config_option)\n                raise CommandExecutionError(\"ERROR: Cassandra {0} cannot be empty.\".format(config_option))\n        return loaded_property\n    return property_name",
    "docstring": "Load properties for the cassandra module from config or pillar.\n\n    :param property_name: The property to load.\n    :type  property_name: str or list of str\n    :param config_option: The name of the config option.\n    :type  config_option: str\n    :param set_default:   Should a default be set if not found in config.\n    :type  set_default:   bool\n    :param default:       The default value to be set.\n    :type  default:       str or int\n    :return:              The property fetched from the configuration or default.\n    :rtype:               str or list of str"
  },
  {
    "code": "def join(self, timeout=None):\n        if self.__wait_for_finishing_thread:\n            if not timeout:\n                while True:\n                    self.__wait_for_finishing_thread.join(0.5)\n                    if not self.__wait_for_finishing_thread.isAlive():\n                        break\n            else:\n                self.__wait_for_finishing_thread.join(timeout)\n            return not self.__wait_for_finishing_thread.is_alive()\n        else:\n            logger.warning(\"Cannot join as state machine was not started yet.\")\n            return False",
    "docstring": "Blocking wait for the execution to finish\n\n        :param float timeout: Maximum time to wait or None for infinitely\n        :return: True if the execution finished, False if no state machine was started or a timeout occurred\n        :rtype: bool"
  },
  {
    "code": "def _unpack_model(self, om):\n        buses = om.case.connected_buses\n        branches = om.case.online_branches\n        gens = om.case.online_generators\n        cp = om.get_cost_params()\n        return buses, branches, gens, cp",
    "docstring": "Returns data from the OPF model."
  },
  {
    "code": "def info_hash(self):\n        info = self._struct.get('info')\n        if not info:\n            return None\n        return sha1(Bencode.encode(info)).hexdigest()",
    "docstring": "Hash of torrent file info section. Also known as torrent hash."
  },
  {
    "code": "def fetchItem(self, ekey, cls=None, **kwargs):\n        if isinstance(ekey, int):\n            ekey = '/library/metadata/%s' % ekey\n        for elem in self._server.query(ekey):\n            if self._checkAttrs(elem, **kwargs):\n                return self._buildItem(elem, cls, ekey)\n        clsname = cls.__name__ if cls else 'None'\n        raise NotFound('Unable to find elem: cls=%s, attrs=%s' % (clsname, kwargs))",
    "docstring": "Load the specified key to find and build the first item with the\n            specified tag and attrs. If no tag or attrs are specified then\n            the first item in the result set is returned.\n\n            Parameters:\n                ekey (str or int): Path in Plex to fetch items from. If an int is passed\n                    in, the key will be translated to /library/metadata/<key>. This allows\n                    fetching an item only knowing its key-id.\n                cls (:class:`~plexapi.base.PlexObject`): If you know the class of the\n                    items to be fetched, passing this in will help the parser ensure\n                    it only returns those items. By default we convert the xml elements\n                    with the best guess PlexObjects based on tag and type attrs.\n                etag (str): Only fetch items with the specified tag.\n                **kwargs (dict): Optionally add attribute filters on the items to fetch. For\n                    example, passing in viewCount=0 will only return matching items. Filtering\n                    is done before the Python objects are built to help keep things speedy.\n                    Note: Because some attribute names are already used as arguments to this\n                    function, such as 'tag', you may still reference the attr tag byappending\n                    an underscore. For example, passing in _tag='foobar' will return all items\n                    where tag='foobar'. Also Note: Case very much matters when specifying kwargs\n                    -- Optionally, operators can be specified by append it\n                    to the end of the attribute name for more complex lookups. For example,\n                    passing in viewCount__gte=0 will return all items where viewCount >= 0.\n                    Available operations include:\n\n                    * __contains: Value contains specified arg.\n                    * __endswith: Value ends with specified arg.\n                    * __exact: Value matches specified arg.\n                    * __exists (bool): Value is or is not present in the attrs.\n                    * __gt: Value is greater than specified arg.\n                    * __gte: Value is greater than or equal to specified arg.\n                    * __icontains: Case insensative value contains specified arg.\n                    * __iendswith: Case insensative value ends with specified arg.\n                    * __iexact: Case insensative value matches specified arg.\n                    * __in: Value is in a specified list or tuple.\n                    * __iregex: Case insensative value matches the specified regular expression.\n                    * __istartswith: Case insensative value starts with specified arg.\n                    * __lt: Value is less than specified arg.\n                    * __lte: Value is less than or equal to specified arg.\n                    * __regex: Value matches the specified regular expression.\n                    * __startswith: Value starts with specified arg."
  },
  {
    "code": "def filesys_decode(path):\n    if isinstance(path, six.text_type):\n        return path\n    fs_enc = sys.getfilesystemencoding() or 'utf-8'\n    candidates = fs_enc, 'utf-8'\n    for enc in candidates:\n        try:\n            return path.decode(enc)\n        except UnicodeDecodeError:\n            continue",
    "docstring": "Ensure that the given path is decoded,\n    NONE when no expected encoding works"
  },
  {
    "code": "def get_events_attendees(self, event_ids):\n        query = urllib.urlencode({'key': self._api_key,\n                                  'event_id': ','.join(event_ids)})\n        url = '{0}?{1}'.format(RSVPS_URL, query)\n        data = self._http_get_json(url)\n        rsvps = data['results']\n        return [(rsvp['event']['id'], parse_member_from_rsvp(rsvp))\n                for rsvp in rsvps\n                if rsvp['response'] != \"no\"]",
    "docstring": "Get the attendees of the identified events.\n\n        Parameters\n        ----------\n        event_ids\n            List of IDs of events to get attendees for.\n\n        Returns\n        -------\n        List of tuples of (event id, ``pythonkc_meetups.types.MeetupMember``).\n\n        Exceptions\n        ----------\n        * PythonKCMeetupsBadJson\n        * PythonKCMeetupsBadResponse\n        * PythonKCMeetupsMeetupDown\n        * PythonKCMeetupsNotJson\n        * PythonKCMeetupsRateLimitExceeded"
  },
  {
    "code": "def status_message(self):\n        msg = None\n        if self.last_ddns_response in response_messages.keys():\n            return response_messages.get(self.last_ddns_response)\n        if 'good' in self.last_ddns_response:\n            ip = re.search(r'(\\d{1,3}\\.?){4}', self.last_ddns_response).group()\n            msg = \"SUCCESS: DNS hostname IP (%s) successfully updated.\" % ip\n        elif 'nochg' in self.last_ddns_response:\n            ip = re.search(r'(\\d{1,3}\\.?){4}', self.last_ddns_response).group()\n            msg = \"SUCCESS: IP address (%s) is up to date, nothing was changed. \" \\\n                  \"Additional 'nochg' updates may be considered abusive.\" % ip\n        else:\n            msg = \"ERROR: Ooops! Something went wrong !!!\"\n        return msg",
    "docstring": "Return friendly response from API based on response code."
  },
  {
    "code": "def get_objgrpwr(self, goea_results):\n        sortobj = self.get_sortobj(goea_results)\n        return GrpWr(sortobj, self.pval_fld, ver_list=self.ver_list)",
    "docstring": "Get a GrpWr object to write grouped GOEA results."
  },
  {
    "code": "def provider(cls, note, provider=None, name=False):\n        def decorator(provider):\n            if inspect.isgeneratorfunction(provider):\n                provider = cls.generator_provider.bind(\n                        provider, support_name=name)\n                return decorator(provider)\n            cls.register(note, provider)\n            return provider\n        if provider is not None:\n            decorator(provider)\n        else:\n            return decorator",
    "docstring": "Register a provider, either a Provider class or a generator.\n\n        Provider class::\n\n            from jeni import Injector as BaseInjector\n            from jeni import Provider\n\n            class Injector(BaseInjector):\n                pass\n\n            @Injector.provider('hello')\n            class HelloProvider(Provider):\n                def get(self, name=None):\n                    if name is None:\n                        name = 'world'\n                    return 'Hello, {}!'.format(name)\n\n        Simple generator::\n\n            @Injector.provider('answer')\n            def answer():\n                yield 42\n\n        If a generator supports get with a name argument::\n\n            @Injector.provider('spam', name=True)\n            def spam():\n                count_str = yield 'spam'\n                while True:\n                    count_str = yield 'spam' * int(count_str)\n\n        Registration can be a decorator or a direct method call::\n\n            Injector.provider('hello', HelloProvider)"
  },
  {
    "code": "def get_primary_mac_address():\n    log = logging.getLogger(mod_logger + '.get_primary_mac_address')\n    log.debug('Attempting to determine the MAC address for eth0...')\n    try:\n        mac_address = netifaces.ifaddresses('eth0')[netifaces.AF_LINK][0]['addr']\n    except Exception:\n        _, ex, trace = sys.exc_info()\n        msg = '{n}: Unable to determine the eth0 mac address for this system:\\n{e}'.format(\n            n=ex.__class__.__name__, e=str(ex))\n        raise AWSMetaDataError, msg, trace\n    return mac_address",
    "docstring": "Determines the MAC address to use for querying the AWS\n    meta data service for network related queries\n\n    :return: (str) MAC address for the eth0 interface\n    :raises: AWSMetaDataError"
  },
  {
    "code": "def create_filter(self, name=None, description=None,\n                      jql=None, favourite=None):\n        data = {}\n        if name is not None:\n            data['name'] = name\n        if description is not None:\n            data['description'] = description\n        if jql is not None:\n            data['jql'] = jql\n        if favourite is not None:\n            data['favourite'] = favourite\n        url = self._get_url('filter')\n        r = self._session.post(\n            url, data=json.dumps(data))\n        raw_filter_json = json_loads(r)\n        return Filter(self._options, self._session, raw=raw_filter_json)",
    "docstring": "Create a new filter and return a filter Resource for it.\n\n        :param name: name of the new filter\n        :type name: str\n        :param description: useful human readable description of the new filter\n        :type description: str\n        :param jql: query string that defines the filter\n        :type jql: str\n        :param favourite: whether to add this filter to the current user's favorites\n        :type favourite: bool\n        :rtype: Filter"
  },
  {
    "code": "def show_explorer(self):\r\n        if self.dockwidget is not None:\r\n            if self.dockwidget.isHidden():\r\n                self.dockwidget.show()\r\n            self.dockwidget.raise_()\r\n            self.dockwidget.update()",
    "docstring": "Show the explorer"
  },
  {
    "code": "def solvePerfForesight(solution_next,DiscFac,LivPrb,CRRA,Rfree,PermGroFac):\n    solver = ConsPerfForesightSolver(solution_next,DiscFac,LivPrb,CRRA,Rfree,PermGroFac)\n    solution = solver.solve()\n    return solution",
    "docstring": "Solves a single period consumption-saving problem for a consumer with perfect foresight.\n\n    Parameters\n    ----------\n    solution_next : ConsumerSolution\n        The solution to next period's one period problem.\n    DiscFac : float\n        Intertemporal discount factor for future utility.\n    LivPrb : float\n        Survival probability; likelihood of being alive at the beginning of\n        the succeeding period.\n    CRRA : float\n        Coefficient of relative risk aversion.\n    Rfree : float\n        Risk free interest factor on end-of-period assets.\n    PermGroFac : float\n        Expected permanent income growth factor at the end of this period.\n\n    Returns\n    -------\n    solution : ConsumerSolution\n            The solution to this period's problem."
  },
  {
    "code": "def A(self, ID):\n        obj = self.chart.getObject(ID).antiscia()\n        ID = 'A_%s' % (ID)\n        return self.G(ID, obj.lat, obj.lon)",
    "docstring": "Returns the Antiscia of an object."
  },
  {
    "code": "def cwd(self, newdir):\n        logger.debug('Sending FTP cwd command. New Workding Directory: {}'.format(newdir))\n        self.client.cwd(newdir)\n        self.state['current_dir'] = self.client.pwd()",
    "docstring": "Send the FTP CWD command\n\n        :param newdir: Directory to change to"
  },
  {
    "code": "def merge_contextual(self, other):\n        for k in self.keys():\n            for item in self[k]:\n                for other_item in other.get(k, []):\n                    if isinstance(other_item, six.text_type):\n                        continue\n                    for otherk in other_item.keys():\n                        if isinstance(other_item[otherk], list):\n                            if len(other_item[otherk]) > 0 and len(item[otherk]) > 0:\n                                other_nested_item = other_item[otherk][0]\n                                for othernestedk in other_nested_item.keys():\n                                    for nested_item in item[otherk]:\n                                        if not nested_item[othernestedk]:\n                                            nested_item[othernestedk] = other_nested_item[othernestedk]\n                        elif not item[otherk]:\n                            item[otherk] = other_item[otherk]\n        log.debug('Result: %s' % self.serialize())\n        return self",
    "docstring": "Merge in contextual info from a template Compound."
  },
  {
    "code": "def prj_add_dep(self, *args, **kwargs):\n        if not self.cur_prj:\n            return\n        dialog = DepAdderDialog(project=self.cur_prj)\n        dialog.exec_()\n        deps = dialog.deps\n        for dep in deps:\n            depdata = djitemdata.DepartmentItemData(dep)\n            treemodel.TreeItem(depdata, self.prj_dep_model.root)",
    "docstring": "Add more departments to the project.\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def kdf(size, password, salt,\n        opslimit=OPSLIMIT_SENSITIVE,\n        memlimit=MEMLIMIT_SENSITIVE,\n        encoder=nacl.encoding.RawEncoder):\n    return encoder.encode(\n        nacl.bindings.crypto_pwhash_alg(size, password, salt,\n                                        opslimit, memlimit,\n                                        ALG)\n    )",
    "docstring": "Derive a ``size`` bytes long key from a caller-supplied\n    ``password`` and ``salt`` pair using the argon2i\n    memory-hard construct.\n\n    the enclosing module provides the constants\n\n        - :py:const:`.OPSLIMIT_INTERACTIVE`\n        - :py:const:`.MEMLIMIT_INTERACTIVE`\n        - :py:const:`.OPSLIMIT_MODERATE`\n        - :py:const:`.MEMLIMIT_MODERATE`\n        - :py:const:`.OPSLIMIT_SENSITIVE`\n        - :py:const:`.MEMLIMIT_SENSITIVE`\n\n    as a guidance for correct settings.\n\n    :param size: derived key size, must be between\n                 :py:const:`.BYTES_MIN` and\n                 :py:const:`.BYTES_MAX`\n    :type size: int\n    :param password: password used to seed the key derivation procedure;\n                     it length must be between\n                     :py:const:`.PASSWD_MIN` and\n                     :py:const:`.PASSWD_MAX`\n    :type password: bytes\n    :param salt: **RANDOM** salt used in the key derivation procedure;\n                 its length must be exactly :py:const:`.SALTBYTES`\n    :type salt: bytes\n    :param opslimit: the time component (operation count)\n                     of the key derivation procedure's computational cost;\n                     it must be between\n                     :py:const:`.OPSLIMIT_MIN` and\n                     :py:const:`.OPSLIMIT_MAX`\n    :type opslimit: int\n    :param memlimit: the memory occupation component\n                     of the key derivation procedure's computational cost;\n                     it must be between\n                     :py:const:`.MEMLIMIT_MIN` and\n                     :py:const:`.MEMLIMIT_MAX`\n    :type memlimit: int\n    :rtype: bytes\n\n    .. versionadded:: 1.2"
  },
  {
    "code": "def login(self):\n        resp = super(CookieSession, self).request(\n            'POST',\n            self._session_url,\n            data={'name': self._username, 'password': self._password},\n        )\n        resp.raise_for_status()",
    "docstring": "Perform cookie based user login."
  },
  {
    "code": "def make_ascii(word):\n    if sys.version_info < (3, 0, 0):\n        word = unicode(word)\n    else:\n        word = str(word)\n    normalized = unicodedata.normalize('NFKD', word)\n    return normalized.encode('ascii', 'ignore').decode('utf-8')",
    "docstring": "Converts unicode-specific characters to their equivalent ascii"
  },
  {
    "code": "def getCellStr(self, x, y):\n        c = self.board.getCell(x, y)\n        if c == 0:\n            return '.' if self.__azmode else '  .'\n        elif self.__azmode:\n            az = {}\n            for i in range(1, int(math.log(self.board.goal(), 2))):\n                az[2 ** i] = chr(i + 96)\n            if c not in az:\n                return '?'\n            s = az[c]\n        elif c == 1024:\n            s = ' 1k'\n        elif c == 2048:\n            s = ' 2k'\n        else:\n            s = '%3d' % c\n        return self.__colors.get(c, Fore.RESET) + s + Style.RESET_ALL",
    "docstring": "return a string representation of the cell located at x,y."
  },
  {
    "code": "def floating_point(\n        element_name,\n        attribute=None,\n        required=True,\n        alias=None,\n        default=0.0,\n        omit_empty=False,\n        hooks=None\n):\n    value_parser = _number_parser(float)\n    return _PrimitiveValue(\n        element_name,\n        value_parser,\n        attribute,\n        required,\n        alias,\n        default,\n        omit_empty,\n        hooks\n    )",
    "docstring": "Create a processor for floating point values.\n\n    See also :func:`declxml.boolean`"
  },
  {
    "code": "def __get_switch_arr(work_sheet, row_num):\n    u_dic = []\n    for col_idx in FILTER_COLUMNS:\n        cell_val = work_sheet['{0}{1}'.format(col_idx, row_num)].value\n        if cell_val in [1, '1']:\n            u_dic.append(work_sheet['{0}1'.format(col_idx)].value.strip().split(',')[0])\n    return u_dic",
    "docstring": "if valud of the column of the row is `1`,  it will be added to the array."
  },
  {
    "code": "def get_parser(description, input_desc):\n    parser = ArgumentParser(description=description)\n    parser.add_argument(\n        dest='input_file',\n        help=input_desc\n        )\n    parser.add_argument(\n        '-r', '--readers',\n        choices=['reach', 'sparser', 'trips'],\n        help='List of readers to be used.',\n        nargs='+'\n        )\n    parser.add_argument(\n        '-n', '--num_procs',\n        dest='n_proc',\n        help='Select the number of processes to use.',\n        type=int,\n        default=1\n        )\n    parser.add_argument(\n        '-s', '--sample',\n        dest='n_samp',\n        help='Read a random sample of size N_SAMP of the inputs.',\n        type=int\n        )\n    parser.add_argument(\n        '-I', '--in_range',\n        dest='range_str',\n        help='Only read input lines in the range given as <start>:<end>.'\n        )\n    parser.add_argument(\n        '-v', '--verbose',\n        help='Include output from the readers.',\n        action='store_true'\n        )\n    parser.add_argument(\n        '-q', '--quiet',\n        help='Suppress most output. Overrides -v and -d options.',\n        action='store_true'\n        )\n    parser.add_argument(\n        '-d', '--debug',\n        help='Set the logging to debug level.',\n        action='store_true'\n        )\n    return parser",
    "docstring": "Get a parser that is generic to reading scripts.\n\n    Parameters\n    ----------\n    description : str\n        A description of the tool, usually about one line long.\n    input_desc: str\n        A string describing the nature of the input file used by the reading\n        tool.\n\n    Returns\n    -------\n    parser : argparse.ArgumentParser instance\n        An argument parser object, to which further arguments can be added."
  },
  {
    "code": "def get_sessions(self, app_path=None):\n        if app_path is not None:\n            return self._tornado.get_sessions(app_path)\n        all_sessions = []\n        for path in self._tornado.app_paths:\n            all_sessions += self._tornado.get_sessions(path)\n        return all_sessions",
    "docstring": "Gets all currently active sessions for applications.\n\n        Args:\n            app_path (str, optional) :\n                The configured application path for the application to return\n                sessions for. If None, return active sessions for all\n                applications. (default: None)\n\n        Returns:\n            list[ServerSession]"
  },
  {
    "code": "def get_remote_member(self, member=None):\n        cluster_params = self.get_standby_cluster_config()\n        if cluster_params:\n            name = member.name if member else 'remote_master:{}'.format(uuid.uuid1())\n            data = {k: v for k, v in cluster_params.items() if k in RemoteMember.allowed_keys()}\n            data['no_replication_slot'] = 'primary_slot_name' not in cluster_params\n            conn_kwargs = member.conn_kwargs() if member else \\\n                {k: cluster_params[k] for k in ('host', 'port') if k in cluster_params}\n            if conn_kwargs:\n                data['conn_kwargs'] = conn_kwargs\n            return RemoteMember(name, data)",
    "docstring": "In case of standby cluster this will tel us from which remote\n            master to stream. Config can be both patroni config or\n            cluster.config.data"
  },
  {
    "code": "def get_number_unit(number):\n    n = str(float(number))\n    mult, submult = n.split('.')\n    if float(submult) != 0:\n        unit = '0.' + (len(submult)-1)*'0' + '1'\n        return float(unit)\n    else:\n        return float(1)",
    "docstring": "get the unit of number"
  },
  {
    "code": "def _create_drawables(self, tokensource):\n        lineno = charno = maxcharno = 0\n        for ttype, value in tokensource:\n            while ttype not in self.styles:\n                ttype = ttype.parent\n            style = self.styles[ttype]\n            value = value.expandtabs(4)\n            lines = value.splitlines(True)\n            for i, line in enumerate(lines):\n                temp = line.rstrip('\\n')\n                if temp:\n                    self._draw_text(\n                        self._get_text_pos(charno, lineno),\n                        temp,\n                        font = self._get_style_font(style),\n                        fill = self._get_text_color(style)\n                    )\n                    charno += len(temp)\n                    maxcharno = max(maxcharno, charno)\n                if line.endswith('\\n'):\n                    charno = 0\n                    lineno += 1\n        self.maxcharno = maxcharno\n        self.maxlineno = lineno",
    "docstring": "Create drawables for the token content."
  },
  {
    "code": "def get_protocol_from_name(name):\n    cls = protocol_map.get(name)\n    if not cls:\n        raise ValueError('Unsupported protocol \"%s\".' % name)\n    return cls",
    "docstring": "Returns the protocol class for the protocol with the given name.\n\n    :type  name: str\n    :param name: The name of the protocol.\n    :rtype:  Protocol\n    :return: The protocol class."
  },
  {
    "code": "def _get_sqla_coltype_class_from_str(coltype: str,\n                                     dialect: Dialect) -> Type[TypeEngine]:\n    ischema_names = dialect.ischema_names\n    try:\n        return ischema_names[coltype.upper()]\n    except KeyError:\n        return ischema_names[coltype.lower()]",
    "docstring": "Returns the SQLAlchemy class corresponding to a particular SQL column\n    type in a given dialect.\n\n    Performs an upper- and lower-case search.\n    For example, the SQLite dialect uses upper case, and the\n    MySQL dialect uses lower case."
  },
  {
    "code": "def sam2fastq(line):\n    fastq = []\n    fastq.append('@%s' % line[0])\n    fastq.append(line[9])\n    fastq.append('+%s' % line[0])\n    fastq.append(line[10])\n    return fastq",
    "docstring": "print fastq from sam"
  },
  {
    "code": "def hasmethod(obj, meth):\n  if hasattr(obj, meth):\n    return callable(getattr(obj,meth))\n  return False",
    "docstring": "Checks if an object, obj, has a callable method, meth\n    \n    return True or False"
  },
  {
    "code": "def index_model(index_name, adapter):\n    model = adapter.model\n    log.info('Indexing {0} objects'.format(model.__name__))\n    qs = model.objects\n    if hasattr(model.objects, 'visible'):\n        qs = qs.visible()\n    if adapter.exclude_fields:\n        qs = qs.exclude(*adapter.exclude_fields)\n    docs = iter_qs(qs, adapter)\n    docs = iter_for_index(docs, index_name)\n    for ok, info in streaming_bulk(es.client, docs, raise_on_error=False):\n        if not ok:\n            log.error('Unable to index %s \"%s\": %s', model.__name__,\n                      info['index']['_id'], info['index']['error'])",
    "docstring": "Indel all objects given a model"
  },
  {
    "code": "def eq(self, r1, r2):\n        if not is_register(r1) or not is_register(r2):\n            return False\n        if self.regs[r1] is None or self.regs[r2] is None:\n            return False\n        return self.regs[r1] == self.regs[r2]",
    "docstring": "True if values of r1 and r2 registers are equal"
  },
  {
    "code": "def create(self, name, type, mains=None, libs=None, description=None,\n               interface=None, is_public=None, is_protected=None):\n        data = {\n            'name': name,\n            'type': type\n        }\n        self._copy_if_defined(data, description=description, mains=mains,\n                              libs=libs, interface=interface,\n                              is_public=is_public, is_protected=is_protected)\n        return self._create('/jobs', data, 'job')",
    "docstring": "Create a Job."
  },
  {
    "code": "def process_task(self):\n        if _debug: ServerSSM._debug(\"process_task\")\n        if self.state == SEGMENTED_REQUEST:\n            self.segmented_request_timeout()\n        elif self.state == AWAIT_RESPONSE:\n            self.await_response_timeout()\n        elif self.state == SEGMENTED_RESPONSE:\n            self.segmented_response_timeout()\n        elif self.state == COMPLETED:\n            pass\n        elif self.state == ABORTED:\n            pass\n        else:\n            if _debug: ServerSSM._debug(\"invalid state\")\n            raise RuntimeError(\"invalid state\")",
    "docstring": "This function is called when the client has failed to send all of the\n        segments of a segmented request, the application has taken too long to\n        complete the request, or the client failed to ack the segments of a\n        segmented response."
  },
  {
    "code": "def git_status_all_repos(cat, hard=True, origin=False, clean=True):\n    log = cat.log\n    log.debug(\"gitter.git_status_all_repos()\")\n    all_repos = cat.PATHS.get_all_repo_folders()\n    for repo_name in all_repos:\n        log.info(\"Repo in: '{}'\".format(repo_name))\n        sha_beg = get_sha(repo_name)\n        log.debug(\"Current SHA: '{}'\".format(sha_beg))\n        log.info(\"Fetching\")\n        fetch(repo_name, log=cat.log)\n        git_comm = [\"git\", \"status\"]\n        _call_command_in_repo(\n            git_comm, repo_name, cat.log, fail=True, log_flag=True)\n        sha_end = get_sha(repo_name)\n        if sha_end != sha_beg:\n            log.info(\"Updated SHA: '{}'\".format(sha_end))\n    return",
    "docstring": "Perform a 'git status' in each data repository."
  },
  {
    "code": "def setup(self, environ):\n        request = wsgi_request(environ)\n        cfg = request.cache.cfg\n        loop = request.cache._loop\n        self.store = create_store(cfg.data_store, loop=loop)\n        pubsub = self.store.pubsub(protocol=Protocol())\n        channel = '%s_webchat' % self.name\n        ensure_future(pubsub.subscribe(channel), loop=loop)\n        return WsgiHandler([Router('/', get=self.home_page),\n                            WebSocket('/message', Chat(pubsub, channel)),\n                            Router('/rpc', post=Rpc(pubsub, channel),\n                                   response_content_types=JSON_CONTENT_TYPES)],\n                           [AsyncResponseMiddleware,\n                            GZipMiddleware(min_length=20)])",
    "docstring": "Called once only to setup the WSGI application handler.\n\n        Check :ref:`lazy wsgi handler <wsgi-lazy-handler>`\n        section for further information."
  },
  {
    "code": "def _linkToParent(self, feature, parentName):\n        parentParts = self.byFeatureName.get(parentName)\n        if parentParts is None:\n            raise GFF3Exception(\n                \"Parent feature does not exist: {}\".format(parentName),\n                self.fileName)\n        for parentPart in parentParts:\n            feature.parents.add(parentPart)\n            parentPart.children.add(feature)",
    "docstring": "Link a feature with its children"
  },
  {
    "code": "def error_cutout_ma(self):\n        if self._error is None:\n            return None\n        else:\n            return np.ma.masked_array(self._error[self._slice],\n                                      mask=self._total_mask)",
    "docstring": "A 2D `~numpy.ma.MaskedArray` cutout from the input ``error``\n        image.\n\n        The mask is `True` for pixels outside of the source segment\n        (labeled region of interest), masked pixels from the ``mask``\n        input, or any non-finite ``data`` values (e.g. NaN or inf).\n\n        If ``error`` is `None`, then ``error_cutout_ma`` is also `None`."
  },
  {
    "code": "def words(self, quantity: int = 5) -> List[str]:\n        words = self._data['words'].get('normal')\n        words_list = [self.random.choice(words) for _ in range(quantity)]\n        return words_list",
    "docstring": "Generate lis of the random words.\n\n        :param quantity: Quantity of words. Default is 5.\n        :return: Word list.\n\n        :Example:\n            [science, network, god, octopus, love]"
  },
  {
    "code": "def optimize(self, sess, batch_index):\n        feed_dict = {\n            self._batch_index: batch_index,\n            self._per_device_batch_size: self._loaded_per_device_batch_size,\n            self._max_seq_len: self._loaded_max_seq_len,\n        }\n        for tower in self._towers:\n            feed_dict.update(tower.loss_graph.extra_compute_grad_feed_dict())\n        fetches = {\"train\": self._train_op}\n        for tower in self._towers:\n            fetches.update(tower.loss_graph.extra_compute_grad_fetches())\n        return sess.run(fetches, feed_dict=feed_dict)",
    "docstring": "Run a single step of SGD.\n\n        Runs a SGD step over a slice of the preloaded batch with size given by\n        self._loaded_per_device_batch_size and offset given by the batch_index\n        argument.\n\n        Updates shared model weights based on the averaged per-device\n        gradients.\n\n        Args:\n            sess: TensorFlow session.\n            batch_index: Offset into the preloaded data. This value must be\n                between `0` and `tuples_per_device`. The amount of data to\n                process is at most `max_per_device_batch_size`.\n\n        Returns:\n            The outputs of extra_ops evaluated over the batch."
  },
  {
    "code": "def rotateAroundVector(v1, w, theta_deg):\n    ct = np.cos(np.radians(theta_deg))\n    st = np.sin(np.radians(theta_deg))\n    term1 = v1*ct\n    term2 = np.cross(w, v1) * st\n    term3 = np.dot(w, v1)\n    term3 = w * term3 * (1-ct)\n    return term1 + term2 + term3",
    "docstring": "Rotate vector v1 by an angle theta around w\n\n    Taken from https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation\n    (see Section \"Rotating a vector\")\n\n    Notes:\n    Rotating the x axis 90 degrees about the y axis gives -z\n    Rotating the x axis 90 degrees about the z axis gives +y"
  },
  {
    "code": "def in_tree(self, name):\n        r\n        if self._validate_node_name(name):\n            raise RuntimeError(\"Argument `name` is not valid\")\n        return name in self._db",
    "docstring": "r\"\"\"\n        Test if a node is in the tree.\n\n        :param name: Node name to search for\n        :type  name: :ref:`NodeName`\n\n        :rtype: boolean\n\n        :raises: RuntimeError (Argument \\`name\\` is not valid)"
  },
  {
    "code": "def _get(self, locator, expected_condition, params=None, timeout=None, error_msg=\"\", driver=None, **kwargs):\n        from selenium.webdriver.support.ui import WebDriverWait\n        if not isinstance(locator, WebElement):\n            error_msg += \"\\nLocator of type <{}> with selector <{}> with params <{params}>\".format(\n                *locator, params=params)\n            locator = self.__class__.get_compliant_locator(*locator, params=params)\n        _driver = driver or self.driver\n        exp_cond = expected_condition(locator, **kwargs)\n        if timeout == 0:\n            try:\n                return exp_cond(_driver)\n            except NoSuchElementException:\n                return None\n        if timeout is None:\n            timeout = self._explicit_wait\n        error_msg += \"\\nExpected condition: {}\" \\\n                     \"\\nTimeout: {}\".format(expected_condition, timeout)\n        return WebDriverWait(_driver, timeout).until(exp_cond, error_msg)",
    "docstring": "Get elements based on locator with optional parameters.\n\n        Uses selenium.webdriver.support.expected_conditions to determine the state of the element(s).\n\n        :param locator: element identifier\n        :param expected_condition: expected condition of element (ie. visible, clickable, etc)\n        :param params: (optional) locator parameters\n        :param timeout: (optional) time to wait for element (default: self._explicit_wait)\n        :param error_msg: (optional) customized error message\n        :param driver: (optional) alternate Webdriver instance (example: parent-element)\n        :param kwargs: optional arguments to expected conditions\n        :return: WebElement instance, list of WebElements, or None"
  },
  {
    "code": "def get_schema_version_from_xml(xml):\n    if isinstance(xml, six.string_types):\n        xml = StringIO(xml)\n    try:\n        tree = ElementTree.parse(xml)\n    except ParseError:\n        return None\n    root = tree.getroot()\n    return root.attrib.get('schemaVersion', None)",
    "docstring": "Get schemaVersion attribute from OpenMalaria scenario file\n    xml - open file or content of xml document to be processed"
  },
  {
    "code": "def dataset_path(cache=None, cachefile=\"~/.io3d_cache.yaml\", get_root=False):\n    local_data_dir = local_dir\n    if cachefile is not None:\n        cache = cachef.CacheFile(cachefile)\n    if cache is not None:\n        local_data_dir = cache.get_or_save_default(\"local_dataset_dir\", local_dir)\n    if get_root:\n        local_data_dir\n    else:\n        logger.warning(\"Parameter\")\n        local_data_dir = op.join(local_data_dir, \"medical\", \"orig\")\n    return op.expanduser(local_data_dir)",
    "docstring": "Get dataset path.\n\n    :param cache: CacheFile object\n    :param cachefile: cachefile path, default '~/.io3d_cache.yaml'\n    :return: path to dataset"
  },
  {
    "code": "def get_track_by_mbid(self, mbid):\n        params = {\"mbid\": mbid}\n        doc = _Request(self, \"track.getInfo\", params).execute(True)\n        return Track(_extract(doc, \"name\", 1), _extract(doc, \"name\"), self)",
    "docstring": "Looks up a track by its MusicBrainz ID"
  },
  {
    "code": "def clear_ddata(self):\n        self._ddata = dict.fromkeys(self._get_keys_ddata())\n        self._ddata['uptodate'] = False",
    "docstring": "Clear the working copy of data\n\n        Harmless, as it preserves the reference copy and the treatment dict\n        Use only to free some memory"
  },
  {
    "code": "def toDict(self):\n        return {\n            'titleAlignments': [titleAlignment.toDict()\n                                for titleAlignment in self],\n            'subjectTitle': self.subjectTitle,\n            'subjectLength': self.subjectLength,\n        }",
    "docstring": "Get information about the title's alignments as a dictionary.\n\n        @return: A C{dict} representation of the title's aligments."
  },
  {
    "code": "def resolve_one(self, correlation_id, key):\n        connection = None\n        for item in self._items:\n            if item.key == key and item.connection != None:\n                connection = item.connection\n                break\n        return connection",
    "docstring": "Resolves a single connection parameters by its key.\n\n        :param correlation_id: (optional) transaction id to trace execution through call chain.\n\n        :param key: a key to uniquely identify the connection.\n\n        :return: a resolved connection."
  },
  {
    "code": "def _u_distance_correlation_sqr_naive(x, y, exponent=1):\n    return _distance_sqr_stats_naive_generic(\n        x, y,\n        matrix_centered=_u_distance_matrix,\n        product=u_product,\n        exponent=exponent).correlation_xy",
    "docstring": "Bias-corrected distance correlation estimator between two matrices."
  },
  {
    "code": "def make_key_hippie(obj, typed=True):\n    ftype = type if typed else lambda o: None\n    if is_hashable(obj):\n        return obj, ftype(obj)\n    if isinstance(obj, set):\n        obj = sorted(obj)\n    if isinstance(obj, (list, tuple)):\n        return tuple(make_key_hippie(e, typed) for e in obj)\n    if isinstance(obj, dict):\n        return tuple(sorted(((make_key_hippie(k, typed),\n                              make_key_hippie(v, typed))\n                             for k, v in obj.items())))\n    raise ValueError(\n        \"%r can not be hashed. Try providing a custom key function.\"\n        % obj)",
    "docstring": "Return hashable structure from non-hashable structure using hippie means\n\n    dict and set are sorted and their content subjected to same hippie means.\n\n    Note that the key identifies the current content of the structure."
  },
  {
    "code": "def read_whole_packet(self):\n        self._read_packet()\n        return readall(self, self._size - _header.size)",
    "docstring": "Reads single packet and returns bytes payload of the packet\n\n        Can only be called when transport's read pointer is at the beginning\n        of the packet."
  },
  {
    "code": "def samaccountname(self, base_dn, distinguished_name):\n        mappings = self.samaccountnames(base_dn, [distinguished_name])\n        try:\n            return mappings[distinguished_name]\n        except KeyError:\n            logging.info(\"%s - unable to retrieve object from AD by DistinguishedName\",\n                         distinguished_name)",
    "docstring": "Retrieve the sAMAccountName for a specific DistinguishedName\n\n        :param str base_dn: The base DN to search within\n        :param list distinguished_name: The base DN to search within\n        :param list attributes: Object attributes to populate, defaults to all\n\n        :return: A populated ADUser object\n        :rtype: ADUser"
  },
  {
    "code": "def datetime_match(data, dts):\n    dts = dts if islistable(dts) else [dts]\n    if any([not isinstance(i, datetime.datetime) for i in dts]):\n        error_msg = (\n            \"`time` can only be filtered by datetimes\"\n        )\n        raise TypeError(error_msg)\n    return data.isin(dts)",
    "docstring": "matching of datetimes in time columns for data filtering"
  },
  {
    "code": "def load(self):\n        private = self.is_private()\n        with open_tls_file(self.file_path, 'r', private=private) as fh:\n            if private:\n                self.x509 = crypto.load_privatekey(self.encoding, fh.read())\n            else:\n                self.x509 = crypto.load_certificate(self.encoding, fh.read())\n            return self.x509",
    "docstring": "Load from a file and return an x509 object"
  },
  {
    "code": "def all_methods(cls):\n        def name(fn):\n            return fn.__get__(cls).__name__.replace(\"_\", \"-\")\n        return sorted(name(f) for f in cls.__dict__.values()\n                      if isinstance(f, staticmethod))",
    "docstring": "Return the names of all available binning methods"
  },
  {
    "code": "def segment(self, value=None, scope=None, metric_scope=None, **selection):\n        SCOPES = {\n            'hits': 'perHit',\n            'sessions': 'perSession',\n            'users': 'perUser',\n            }\n        segments = self.meta.setdefault('segments', [])\n        if value and len(selection):\n            raise ValueError(\"Cannot specify a filter string and a filter keyword selection at the same time.\")\n        elif value:\n            value = [self.api.segments.serialize(value)]\n        elif len(selection):\n            if not scope:\n                raise ValueError(\"Scope is required. Choose from: users, sessions.\")\n            if metric_scope:\n                metric_scope = SCOPES[metric_scope]\n            value = select(self.api.columns, selection)\n            value = [[scope, 'condition', metric_scope, condition] for condition in value]\n            value = ['::'.join(filter(None, condition)) for condition in value]\n        segments.append(value)\n        self.raw['segment'] = utils.paste(segments, ',', ';')\n        return self",
    "docstring": "Return a new query, limited to a segment of all users or sessions.\n\n        Accepts segment objects, filtered segment objects and segment names:\n\n        ```python\n        query.segment(account.segments['browser'])\n        query.segment('browser')\n        query.segment(account.segments['browser'].any('Chrome', 'Firefox'))\n        ```\n\n        Segment can also accept a segment expression when you pass\n        in a `type` argument. The type argument can be either `users`\n        or `sessions`. This is pretty close to the metal.\n\n        ```python\n        # will be translated into `users::condition::perUser::ga:sessions>10`\n        query.segment('condition::perUser::ga:sessions>10', type='users')\n        ```\n\n        See the [Google Analytics dynamic segments documentation][segments]\n\n        You can also use the `any`, `all`, `followed_by` and\n        `immediately_followed_by` functions in this module to\n        chain together segments.\n\n        Everything about how segments get handled is still in flux.\n        Feel free to propose ideas for a nicer interface on\n        the [GitHub issues page][issues]\n\n        [segments]: https://developers.google.com/analytics/devguides/reporting/core/v3/segments#reference\n        [issues]: https://github.com/debrouwere/google-analytics/issues"
  },
  {
    "code": "def _validate_recurse_directive_types(current_schema_type, field_schema_type, context):\n    type_hints = context['type_equivalence_hints'].get(field_schema_type)\n    type_hints_inverse = context['type_equivalence_hints_inverse'].get(field_schema_type)\n    allowed_current_types = {field_schema_type}\n    if type_hints and isinstance(type_hints, GraphQLUnionType):\n        allowed_current_types.update(type_hints.types)\n    if type_hints_inverse and isinstance(type_hints_inverse, GraphQLUnionType):\n        allowed_current_types.update(type_hints_inverse.types)\n    current_scope_is_allowed = current_schema_type in allowed_current_types\n    is_implemented_interface = (\n        isinstance(field_schema_type, GraphQLInterfaceType) and\n        isinstance(current_schema_type, GraphQLObjectType) and\n        field_schema_type in current_schema_type.interfaces\n    )\n    if not any((current_scope_is_allowed, is_implemented_interface)):\n        raise GraphQLCompilationError(u'Edges expanded with a @recurse directive must either '\n                                      u'be of the same type as their enclosing scope, a supertype '\n                                      u'of the enclosing scope, or be of an interface type that is '\n                                      u'implemented by the type of their enclosing scope. '\n                                      u'Enclosing scope type: {}, edge type: '\n                                      u'{}'.format(current_schema_type, field_schema_type))",
    "docstring": "Perform type checks on the enclosing type and the recursed type for a recurse directive.\n\n    Args:\n        current_schema_type: GraphQLType, the schema type at the current location\n        field_schema_type: GraphQLType, the schema type at the inner scope\n        context: dict, various per-compilation data (e.g. declared tags, whether the current block\n                 is optional, etc.). May be mutated in-place in this function!"
  },
  {
    "code": "def parse_instruction(string, location, tokens):\n    mnemonic_str = tokens.get(\"mnemonic\")\n    operands = [op for op in tokens.get(\"operands\", [])]\n    instr = ArmInstruction(\n        string,\n        mnemonic_str[\"ins\"],\n        operands,\n        arch_info.architecture_mode\n    )\n    if \"cc\" in mnemonic_str:\n        instr.condition_code = cc_mapper[mnemonic_str[\"cc\"]]\n    if \"uf\" in mnemonic_str:\n        instr.update_flags = True\n    if \"ldm_stm_addr_mode\" in mnemonic_str:\n        instr.ldm_stm_addr_mode = ldm_stm_am_mapper[mnemonic_str[\"ldm_stm_addr_mode\"]]\n    return instr",
    "docstring": "Parse an ARM instruction."
  },
  {
    "code": "def slurp(path, encoding='UTF-8'):\n    with io.open(path, 'r', encoding=encoding) as f:\n        return f.read()",
    "docstring": "Reads file `path` and returns the entire contents as a unicode string\n\n    By default assumes the file is encoded as UTF-8\n\n    Parameters\n    ----------\n    path : str\n        File path to file on disk\n    encoding : str, default `UTF-8`, optional\n        Encoding of the file\n\n    Returns\n    -------\n\n    The txt read from the file as a unicode string"
  },
  {
    "code": "def sort_by_tag(self, tag):\n        return AmpalContainer(sorted(self, key=lambda x: x.tags[tag]))",
    "docstring": "Sorts the `AmpalContainer` by a tag on the component objects.\n\n        Parameters\n        ----------\n        tag : str\n            Key of tag used for sorting."
  },
  {
    "code": "def categorical__int(self, column_name, output_column_prefix):\n        return [_ColumnFunctionTransformation(\n            features = [column_name],\n            output_column_prefix = output_column_prefix,\n            transform_function = lambda col: col.astype(str),\n            transform_function_name = \"astype(str)\")]",
    "docstring": "Interprets an integer column as a categorical variable."
  },
  {
    "code": "def get_config(self, service, setting):\n        try:\n            return self.get_service(service)[setting]\n        except KeyError:\n            return getattr(self, setting + '_DEFAULT')",
    "docstring": "Access the configuration for a given service and setting. If the\n        service is not found, return a default value."
  },
  {
    "code": "def TransposeTable(table):\n  transposed = []\n  rows = len(table)\n  cols = max(len(row) for row in table)\n  for x in range(cols):\n    transposed.append([])\n    for y in range(rows):\n      if x < len(table[y]):\n        transposed[x].append(table[y][x])\n      else:\n        transposed[x].append(None)\n  return transposed",
    "docstring": "Transpose a list of lists, using None to extend all input lists to the\n  same length.\n\n  For example:\n  >>> TransposeTable(\n  [ [11,   12,   13],\n    [21,   22],\n    [31,   32,   33,   34]])\n\n  [ [11,   21,   31],\n    [12,   22,   32],\n    [13,   None, 33],\n    [None, None, 34]]"
  },
  {
    "code": "def add_zone(self, spatial_unit, container_id, name='', description='', visible=True, reuse=0, drop_behavior_type=None):\n        if not isinstance(spatial_unit, abc_mapping_primitives.SpatialUnit):\n            raise InvalidArgument('zone is not a SpatialUnit')\n        if not isinstance(reuse, int):\n            raise InvalidArgument('reuse must be an integer')\n        if reuse < 0:\n            raise InvalidArgument('reuse must be >= 0')\n        if not isinstance(name, DisplayText):\n            name = self._str_display_text(name)\n        if not isinstance(description, DisplayText):\n            description = self._str_display_text(description)\n        zone = {\n            'id': str(ObjectId()),\n            'spatialUnit': spatial_unit.get_spatial_unit_map(),\n            'containerId': container_id,\n            'names': [self._dict_display_text(name)],\n            'descriptions': [self._dict_display_text(description)],\n            'visible': visible,\n            'reuse': reuse,\n            'dropBehaviorType': str(drop_behavior_type)\n        }\n        self.my_osid_object_form._my_map['zones'].append(zone)\n        return zone",
    "docstring": "container_id is a targetId that the zone belongs to"
  },
  {
    "code": "def add(self, elem):\n        if not isinstance(elem, JWK):\n            raise TypeError('Only JWK objects are valid elements')\n        set.add(self, elem)",
    "docstring": "Adds a JWK object to the set\n\n        :param elem: the JWK object to add.\n\n        :raises TypeError: if the object is not a JWK."
  },
  {
    "code": "def extendMarkdown(self, md, md_globals):\n        md.inlinePatterns.add('del', SimpleTagPattern(DEL_RE, 'del'), '<not_strong')\n        md.inlinePatterns.add('ins', SimpleTagPattern(INS_RE, 'ins'), '<not_strong')\n        md.inlinePatterns.add('mark', SimpleTagPattern(MARK_RE, 'mark'), '<not_strong')",
    "docstring": "Modifies inline patterns."
  },
  {
    "code": "def listen(self):\n        self.listening = True\n        if self.threading:\n            from threading import Thread\n            self.listen_thread = Thread(target=self.listen_loop)\n            self.listen_thread.daemon = True\n            self.listen_thread.start()\n            self.scheduler_thread = Thread(target=self.scheduler)\n            self.scheduler_thread.daemon = True\n            self.scheduler_thread.start()\n        else:\n            self.listen_loop()",
    "docstring": "Starts the listen loop. If threading is enabled, then the loop will\n        be started in its own thread.\n\n        Args:\n          None\n\n        Returns:\n          None"
  },
  {
    "code": "def convertwaiveredfits(waiveredObject,\n                        outputFileName=None,\n                        forceFileOutput=False,\n                        convertTo='multiExtension',\n                        verbose=False):\n    if convertTo == 'multiExtension':\n        func = toMultiExtensionFits\n    else:\n        raise ValueError('Conversion type ' + convertTo + ' unknown')\n    return func(*(waiveredObject,outputFileName,forceFileOutput,verbose))",
    "docstring": "Convert the input waivered FITS object to various formats.  The\n        default conversion format is multi-extension FITS.  Generate an output\n        file in the desired format if requested.\n\n        Parameters:\n\n          waiveredObject  input object representing a waivered FITS file;\n                          either a astropy.io.fits.HDUList object, a file object, or a\n                          file specification\n\n          outputFileName  file specification for the output file\n                          Default: None - do not generate an output file\n\n          forceFileOutput force the generation of an output file when the\n                          outputFileName parameter is None; the output file\n                          specification will be the same as the input file\n                          specification with the last character of the base\n                          name replaced with the character `h` in\n                          multi-extension FITS format.\n\n                          Default: False\n\n          convertTo       target conversion type\n                          Default: 'multiExtension'\n\n          verbose         provide verbose output\n                          Default: False\n\n        Returns:\n\n          hdul            an HDUList object in the requested format.\n\n        Exceptions:\n\n           ValueError       Conversion type is unknown"
  },
  {
    "code": "def removeSessionWithKey(self, key):\n        self.store.query(\n            PersistentSession,\n            PersistentSession.sessionKey == key).deleteFromStore()",
    "docstring": "Remove a persistent session, if it exists.\n\n        @type key: L{bytes}\n        @param key: The persistent session identifier."
  },
  {
    "code": "def reset(self):\n        self._sampled = [np.repeat(False, x) for x in self.sizes_]\n        self._n_sampled = np.zeros(self.n_strata_, dtype=int)",
    "docstring": "Reset the instance to begin sampling from scratch"
  },
  {
    "code": "def _log_exception(self, exception):\n        self._io.error(str(exception).strip().split(os.linesep))",
    "docstring": "Logs an exception.\n\n        :param Exception exception: The exception.\n\n        :rtype: None"
  },
  {
    "code": "def create_stack(self, name):\n        deployment = find_exact(self.api.deployments, name=name)\n        if not deployment:\n            try:\n                self.api.client.post(\n                        '/api/deployments',\n                        data={'deployment[name]': name},\n                        )\n            except HTTPError as e:\n                log.error(\n                        'Failed to create stack %s. '\n                        'RightScale returned %d:\\n%s'\n                        % (name, e.response.status_code, e.response.content)\n                        )",
    "docstring": "Creates stack if necessary."
  },
  {
    "code": "def geom_xys(geom):\n    if geom.has_z:\n        geom = wkt.loads(geom.to_wkt())\n        assert not geom.has_z\n    if hasattr(geom, \"geoms\"):\n        geoms = geom.geoms\n    else:\n        geoms = [geom]\n    for g in geoms:\n        arr = g.array_interface_base['data']\n        for pair in zip(arr[::2], arr[1::2]):\n            yield pair",
    "docstring": "Given a shapely geometry,\n    generate a flattened series of 2D points as x,y tuples"
  },
  {
    "code": "def parse_redis_url(url):\n    redis_config = {\n        \"DB\": 0,\n        \"PASSWORD\": None,\n        \"HOST\": \"localhost\",\n        \"PORT\": 6379,\n        \"SSL\": False\n    }\n    if not url:\n        return redis_config\n    url = urlparse.urlparse(url)\n    path = url.path[1:]\n    path = path.split('?', 2)[0]\n    if path:\n        redis_config.update({\"DB\": int(path)})\n    if url.password:\n        redis_config.update({\"PASSWORD\": url.password})\n    if url.hostname:\n        redis_config.update({\"HOST\": url.hostname})\n    if url.port:\n        redis_config.update({\"PORT\": int(url.port)})\n    if url.scheme in ['https', 'rediss']:\n        redis_config.update({\"SSL\": True})\n    return redis_config",
    "docstring": "Parses a redis URL."
  },
  {
    "code": "def list_containers(self):\n        data = run_cmd([\"machinectl\", \"list\", \"--no-legend\", \"--no-pager\"],\n                       return_output=True)\n        output = []\n        reg = re.compile(r\"\\s+\")\n        for line in data.split(\"\\n\"):\n            stripped = line.strip()\n            if stripped:\n                parts = reg.split(stripped)\n                name = parts[0]\n                output.append(self.ContainerClass(None, None, name=name))\n        return output",
    "docstring": "list all available nspawn containers\n\n        :return: collection of instances of :class:`conu.backend.nspawn.container.NspawnContainer`"
  },
  {
    "code": "def site_symbols(self):\n        syms = [site.specie.symbol for site in self.structures[0]]\n        return [a[0] for a in itertools.groupby(syms)]",
    "docstring": "Sequence of symbols associated with the Xdatcar. Similar to 6th line in\n        vasp 5+ Xdatcar."
  },
  {
    "code": "def is_git_repo(repo_dir):\n    command = ['git', 'rev-parse']\n    try:\n        execute_git_command(command, repo_dir=repo_dir)\n    except exceptions.SimplGitCommandError:\n        return False\n    else:\n        return True",
    "docstring": "Return True if the directory is inside a git repo."
  },
  {
    "code": "def get_entities_query(namespace, workspace, etype, page=1,\n                       page_size=100, sort_direction=\"asc\",\n                       filter_terms=None):\n    params = {\n        \"page\" : page,\n        \"pageSize\" : page_size,\n        \"sortDirection\" : sort_direction\n    }\n    if filter_terms:\n        params['filterTerms'] = filter_terms\n    uri = \"workspaces/{0}/{1}/entityQuery/{2}\".format(namespace,workspace,etype)\n    return __get(uri, params=params)",
    "docstring": "Paginated version of get_entities_with_type.\n\n    Args:\n        namespace (str): project to which workspace belongs\n        workspace (str): Workspace name\n\n    Swagger:\n        https://api.firecloud.org/#!/Entities/entityQuery"
  },
  {
    "code": "def init_i18n (loc=None):\n    if 'LOCPATH' in os.environ:\n        locdir = os.environ['LOCPATH']\n    else:\n        locdir = os.path.join(get_install_data(), 'share', 'locale')\n    i18n.init(configdata.name.lower(), locdir, loc=loc)\n    import logging\n    logging.addLevelName(logging.CRITICAL, _('CRITICAL'))\n    logging.addLevelName(logging.ERROR, _('ERROR'))\n    logging.addLevelName(logging.WARN, _('WARN'))\n    logging.addLevelName(logging.WARNING, _('WARNING'))\n    logging.addLevelName(logging.INFO, _('INFO'))\n    logging.addLevelName(logging.DEBUG, _('DEBUG'))\n    logging.addLevelName(logging.NOTSET, _('NOTSET'))",
    "docstring": "Initialize i18n with the configured locale dir. The environment\n    variable LOCPATH can also specify a locale dir.\n\n    @return: None"
  },
  {
    "code": "def register_module_classes(yaml: ruamel.yaml.YAML, modules: Optional[Iterable[Any]] = None) -> ruamel.yaml.YAML:\n    if modules is None:\n        modules = []\n    classes_to_register = set()\n    for module in modules:\n        module_classes = [member[1] for member in inspect.getmembers(module, inspect.isclass)]\n        classes_to_register.update(module_classes)\n    return register_classes(yaml = yaml, classes = classes_to_register)",
    "docstring": "Register all classes in the given modules with the YAML object.\n\n    This is a simple helper function."
  },
  {
    "code": "def is_higher_permission(level1, level2):\n    return (is_publish_permission(level1) and\n            not is_publish_permission(level2) or\n            (is_edit_permission(level1) and\n             not is_publish_permission(level2) and\n             not is_edit_permission(level2)) or\n            (is_showon_permission(level1) and\n             is_view_permission(level2)))",
    "docstring": "Return True if the level1 is higher than level2"
  },
  {
    "code": "def iteryaml(self, *args, **kwargs):\n        from rowgenerators.rowpipe.json import VTEncoder\n        import yaml\n        if 'cls' not in kwargs:\n            kwargs['cls'] = VTEncoder\n        for s in self.iterstruct:\n            yield (yaml.safe_dump(s))",
    "docstring": "Yields the data structures from iterstruct as YAML strings"
  },
  {
    "code": "def create_parser():\n    parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter)\n    parser.add_argument('-v', '--verbose', action=\"count\", default=0, help=\"Increase logging level (goes error, warn, info, debug)\")\n    parser.add_argument('-l', '--logfile', help=\"The file where we should log all logging messages\")\n    parser.add_argument('-i', '--include', action=\"append\", default=[], help=\"Only include the specified loggers\")\n    parser.add_argument('-e', '--exclude', action=\"append\", default=[], help=\"Exclude the specified loggers, including all others\")\n    parser.add_argument('-q', '--quit', action=\"store_true\", help=\"Do not spawn a shell after executing any commands\")\n    parser.add_argument('-t', '--timeout', type=float, help=\"Do not allow this process to run for more than a specified number of seconds.\")\n    parser.add_argument('commands', nargs=argparse.REMAINDER, help=\"The command(s) to execute\")\n    return parser",
    "docstring": "Create the argument parser for iotile."
  },
  {
    "code": "def get(self, eid):\n\t\tdata = self._http_req('connections/%u' % eid)\n\t\tself.debug(0x01, data['decoded'])\n\t\treturn data['decoded']",
    "docstring": "Returns a dict with the complete record of the entity with the given eID"
  },
  {
    "code": "def read(self):\n        if path.exists(self.filepath):\n            with open(self.filepath, 'rb') as infile:\n                self.data = yaml.load(\n                    self.fernet.decrypt(infile.read()))\n        else:\n            self.data = dict()",
    "docstring": "Reads and decrypts data from the filesystem"
  },
  {
    "code": "def _find_matching_expectation(self, args, kwargs):\n        for expectation in self._expectations:\n            if expectation.satisfy_exact_match(args, kwargs):\n                return expectation\n        for expectation in self._expectations:\n            if expectation.satisfy_custom_matcher(args, kwargs):\n                return expectation\n        for expectation in self._expectations:\n            if expectation.satisfy_any_args_match():\n                return expectation",
    "docstring": "Return a matching expectation.\n\n        Returns the first expectation that matches the ones declared. Tries one with specific\n        arguments first, then falls back to an expectation that allows arbitrary arguments.\n\n        :return: The matching ``Expectation``, if one was found.\n        :rtype: Expectation, None"
  },
  {
    "code": "def profile_update(self, profile):\n        if profile.get('install_json') is None:\n            print(\n                '{}{}Missing install_json parameter for profile {}.'.format(\n                    c.Style.BRIGHT, c.Fore.YELLOW, profile.get('profile_name')\n                )\n            )\n        self.profile_update_args_v2(profile)\n        self.profile_update_args_v3(profile)\n        self.profile_update_schema(profile)",
    "docstring": "Update an existing profile with new parameters or remove deprecated parameters.\n\n        Args:\n            profile (dict): The dictionary containting the profile settings."
  },
  {
    "code": "def stop(self) -> None:\n        if self._stop and not self._posted_kork:\n            self._stop()\n            self._stop = None",
    "docstring": "Stops the analysis as soon as possible."
  },
  {
    "code": "def _build_implicit_prefetches(\n        self,\n        model,\n        prefetches,\n        requirements\n    ):\n        for source, remainder in six.iteritems(requirements):\n            if not remainder or isinstance(remainder, six.string_types):\n                continue\n            related_field = get_model_field(model, source)\n            related_model = get_related_model(related_field)\n            queryset = self._build_implicit_queryset(\n                related_model,\n                remainder\n            ) if related_model else None\n            prefetches[source] = self._create_prefetch(\n                source,\n                queryset\n            )\n        return prefetches",
    "docstring": "Build a prefetch dictionary based on internal requirements."
  },
  {
    "code": "def setup_standalone_signals(instance):\n    window = instance.get_widget('config-window')\n    window.connect('delete-event', Gtk.main_quit)\n    button = instance.get_widget('button1')\n    button.handler_block_by_func(instance.gtk_widget_destroy)\n    button.connect('clicked', Gtk.main_quit)\n    return instance",
    "docstring": "Called when prefs dialog is running in standalone mode. It\n    makes the delete event of dialog and click on close button finish\n    the application."
  },
  {
    "code": "def put_acl(Bucket,\n           ACL=None,\n           AccessControlPolicy=None,\n           GrantFullControl=None,\n           GrantRead=None,\n           GrantReadACP=None,\n           GrantWrite=None,\n           GrantWriteACP=None,\n           region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        kwargs = {}\n        if AccessControlPolicy is not None:\n            if isinstance(AccessControlPolicy, six.string_types):\n                AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)\n            kwargs['AccessControlPolicy'] = AccessControlPolicy\n        for arg in ('ACL',\n                    'GrantFullControl',\n                    'GrantRead', 'GrantReadACP',\n                    'GrantWrite', 'GrantWriteACP'):\n            if locals()[arg] is not None:\n                kwargs[arg] = str(locals()[arg])\n        conn.put_bucket_acl(Bucket=Bucket, **kwargs)\n        return {'updated': True, 'name': Bucket}\n    except ClientError as e:\n        return {'updated': False, 'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Given a valid config, update the ACL for a bucket.\n\n    Returns {updated: true} if the ACL was updated and returns\n    {updated: False} if the ACL was not updated.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\\\\n                         GrantFullControl='emailaddress=example@example.com' \\\\\n                         GrantRead='uri=\"http://acs.amazonaws.com/groups/global/AllUsers\"' \\\\\n                         GrantReadACP='emailaddress=\"exampl@example.com\",id=\"2345678909876432\"'"
  },
  {
    "code": "def do_mkdir(self, path):\n        path = path[0]\n        self.n.makeDirectory(self.current_path + path)\n        self.dirs = self.dir_complete()",
    "docstring": "create a new directory"
  },
  {
    "code": "def sg_prod(tensor, opt):\n    r\n    return tf.reduce_prod(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name)",
    "docstring": "r\"\"\"Computes the product of elements across axis of a tensor.\n\n    See `tf.reduce_prod()` in tensorflow.\n\n    Args:\n      tensor: A `Tensor` (automatically given by chain).\n      opt:\n        axis : A tuple/list of integers or an integer. The axis to reduce.\n        keep_dims: If true, retains reduced dimensions with length 1.\n        name: If provided, replace current tensor's name.\n\n    Returns:\n      A `Tensor`."
  },
  {
    "code": "def install_pyenv(name, user=None):\n    ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}\n    if __opts__['test']:\n        ret['comment'] = 'pyenv is set to be installed'\n        return ret\n    return _check_and_install_python(ret, user)",
    "docstring": "Install pyenv if not installed. Allows you to require pyenv be installed\n    prior to installing the plugins. Useful if you want to install pyenv\n    plugins via the git or file modules and need them installed before\n    installing any rubies.\n\n    Use the pyenv.root configuration option to set the path for pyenv if you\n    want a system wide install that is not in a user home dir.\n\n    user: None\n        The user to run pyenv as."
  },
  {
    "code": "def run_score(self):\n        diffs = 0\n        lines = 0\n        for file in self.files:\n            try:\n                results = self._check(file)\n            except Error as e:\n                termcolor.cprint(e.msg, \"yellow\", file=sys.stderr)\n                continue\n            diffs += results.diffs\n            lines += results.lines\n        try:\n            print(max(1 - diffs / lines, 0.0))\n        except ZeroDivisionError:\n            print(0.0)",
    "docstring": "Run checks on self.files, printing raw percentage to stdout."
  },
  {
    "code": "def not26(func):\n    @wraps(func)\n    def errfunc(*args, **kwargs):\n        raise NotImplementedError\n    if hexversion < 0x02070000:\n        return errfunc\n    else:\n        return func",
    "docstring": "Function decorator for methods not implemented in Python 2.6."
  },
  {
    "code": "def terminate(self):\n        logger.debug('client.terminate() called (state=%s)', self.strstate)\n        if self.state == ClientState.WAITING_FOR_RESULT:\n            raise ClientStateError('terimate() called while state='+self.strstate)\n        if self.state == ClientState.TERMINATING:\n            raise ClientStateError('terimate() called while state='+self.strstate)\n        elif self.state in ClientState.TerminatedSet:\n            assert not self._server_process.is_alive()\n            return\n        elif self.state == ClientState.READY:\n            self._assert_alive()\n            self.state = ClientState.TERMINATING\n            self._delegate_channel.put(FunctionCallDelegate(_raise_terminate))\n            try:\n                self._read_result(num_retries=5)\n            except ProcessTerminationError as ex:\n                pass\n            except ChannelError as ex:\n                logger.debug('client failed to read sentinel from channel after 5 retries - will terminate anyway')\n            self.state = ClientState.TERMINATED_CLEANLY",
    "docstring": "Stop the server process and change our state to TERMINATING. Only valid if state=READY."
  },
  {
    "code": "def safe_str_to_class(s):\n    lst = s.split(\".\")\n    klass = lst[-1]\n    mod_list = lst[:-1]\n    module = \".\".join(mod_list)\n    if not module:\n        module = klass\n    mod = my_import(module)\n    if hasattr(mod, klass):\n        return getattr(mod, klass)\n    else:\n        raise ImportError('')",
    "docstring": "Helper function to map string class names to module classes."
  },
  {
    "code": "def reset(self):\n        query =\n        self.backend.library.database.connection.execute(query)",
    "docstring": "Drops index table."
  },
  {
    "code": "def patch(self, request):\n        attrs = ('edx_video_id', 'status')\n        missing = [attr for attr in attrs if attr not in request.data]\n        if missing:\n            return Response(\n                status=status.HTTP_400_BAD_REQUEST,\n                data={'message': u'\"{missing}\" params must be specified.'.format(missing=' and '.join(missing))}\n            )\n        edx_video_id = request.data['edx_video_id']\n        video_status = request.data['status']\n        if video_status not in VALID_VIDEO_STATUSES:\n            return Response(\n                status=status.HTTP_400_BAD_REQUEST,\n                data={'message': u'\"{status}\" is not a valid Video status.'.format(status=video_status)}\n            )\n        try:\n            video = Video.objects.get(edx_video_id=edx_video_id)\n            video.status = video_status\n            video.save()\n            response_status = status.HTTP_200_OK\n            response_payload = {}\n        except Video.DoesNotExist:\n            response_status = status.HTTP_400_BAD_REQUEST\n            response_payload = {\n                'message': u'Video is not found for specified edx_video_id: {edx_video_id}'.format(\n                    edx_video_id=edx_video_id\n                )\n            }\n        return Response(status=response_status, data=response_payload)",
    "docstring": "Update the status of a video."
  },
  {
    "code": "def resetSession(self, username=None, password=None, verify=True) :\n        self.disconnectSession()\n        self.session = AikidoSession(username, password, verify)",
    "docstring": "resets the session"
  },
  {
    "code": "def list_all():\n    ret = []\n    if _sd_version() >= 219:\n        for line in _machinectl('list-images')['stdout'].splitlines():\n            try:\n                ret.append(line.split()[0])\n            except IndexError:\n                continue\n    else:\n        rootdir = _root()\n        try:\n            for dirname in os.listdir(rootdir):\n                if os.path.isdir(os.path.join(rootdir, dirname)):\n                    ret.append(dirname)\n        except OSError:\n            pass\n    return ret",
    "docstring": "Lists all nspawn containers\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion nspawn.list_all"
  },
  {
    "code": "def listDatawraps() :\n\tl = {\"Genomes\" : [], \"SNPs\" : []}\n\tfor f in os.listdir(os.path.join(this_dir, \"bootstrap_data/genomes\")) :\n\t\tif f.find(\".tar.gz\") > -1 :\n\t\t\tl[\"Genomes\"].append(f)\n\tfor f in os.listdir(os.path.join(this_dir, \"bootstrap_data/SNPs\")) :\n\t\tif f.find(\".tar.gz\") > -1 :\n\t\t\tl[\"SNPs\"].append(f)\n\treturn l",
    "docstring": "Lists all the datawraps pyGeno comes with"
  },
  {
    "code": "def get_nodedata(self, sort_names=False):\n        if not self.Node.n:\n            return\n        if not self.pflow.solved:\n            logger.error('Power flow not solved when getting bus data.')\n            return tuple([False] * 7)\n        idx = self.Node.idx\n        names = self.Node.name\n        V = [self.dae.y[x] for x in self.Node.v]\n        if sort_names:\n            ret = (list(x)\n                   for x in zip(*sorted(zip(idx, names, V), key=itemgetter(0))))\n        else:\n            ret = idx, names, V\n        return ret",
    "docstring": "get dc node data from solved power flow"
  },
  {
    "code": "def add_state(self, state, storage_load=False):\n        assert isinstance(state, State)\n        while state.state_id == self.state_id or state.state_id in self.states:\n            state.change_state_id()\n        if state.state_id in self._states.keys():\n            raise AttributeError(\"State id %s already exists in the container state\", state.state_id)\n        else:\n            state.parent = self\n            self._states[state.state_id] = state\n        return state.state_id",
    "docstring": "Adds a state to the container state.\n\n        :param state: the state that is going to be added\n        :param storage_load: True if the state was directly loaded from filesystem\n        :return: the state_id of the new state\n        :raises exceptions.AttributeError: if state.state_id already exist"
  },
  {
    "code": "def get_agent_settings():\n    ret = dict()\n    sorted_types = sorted(_SERVICE_TYPES.items(), key=lambda x: (-x[1], x[0]))\n    ret['services'] = list()\n    ret['contact'] = (__utils__['reg.read_value'](\n        _HKEY, _AGENT_KEY, 'sysContact'))['vdata']\n    ret['location'] = (__utils__['reg.read_value'](\n        _HKEY, _AGENT_KEY, 'sysLocation'))['vdata']\n    current_bitmask = (__utils__['reg.read_value'](\n        _HKEY, _AGENT_KEY, 'sysServices'))['vdata']\n    if current_bitmask == 0:\n        ret['services'].append(sorted_types[-1][0])\n    else:\n        for service, bitmask in sorted_types:\n            if current_bitmask is not None and current_bitmask > 0:\n                remaining_bitmask = current_bitmask - bitmask\n                if remaining_bitmask >= 0:\n                    current_bitmask = remaining_bitmask\n                    ret['services'].append(service)\n            else:\n                break\n    ret['services'] = sorted(ret['services'])\n    return ret",
    "docstring": "Determine the value of the SNMP sysContact, sysLocation, and sysServices\n    settings.\n\n    Returns:\n        dict: A dictionary of the agent settings.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' win_snmp.get_agent_settings"
  },
  {
    "code": "def namespace_lower(self, namespace):\n        return self.namespace(namespace, key_transform=lambda key: key.lower())",
    "docstring": "Return a copy with only the keys from a given namespace, lower-cased.\n\n        The keys in the returned dict will be transformed to lower case after\n        filtering, so they can be easily passed as keyword arguments to other\n        functions. This is just syntactic sugar for calling\n        :meth:`~ConfigLoader.namespace` with\n        ``key_transform=lambda key: key.lower()``.\n\n        Example::\n\n            >>> from configloader import ConfigLoader\n            >>> config = ConfigLoader(\n            ...     MY_APP_SETTING1='a',\n            ...     EXTERNAL_LIB_SETTING1='b',\n            ...     EXTERNAL_LIB_SETTING2='c',\n            ... )\n            >>> config.namespace_lower('EXTERNAL_LIB')\n            ConfigLoader({'setting1': 'b', 'setting2': 'c'})\n\n        :arg namespace: Common prefix.\n\n        :return: New config dict.\n        :rtype: :class:`ConfigLoader`"
  },
  {
    "code": "def _parse_boolean(element_text, state):\n    value = None\n    lowered_text = element_text.lower()\n    if lowered_text == 'true':\n        value = True\n    elif lowered_text == 'false':\n        value = False\n    else:\n        state.raise_error(InvalidPrimitiveValue, 'Invalid boolean value \"{}\"'.format(element_text))\n    return value",
    "docstring": "Parse the raw XML string as a boolean value."
  },
  {
    "code": "def build_submit_description(executable, output, error, user_log, query_params):\n    all_query_params = DEFAULT_QUERY_CLASSAD.copy()\n    all_query_params.update(query_params)\n    submit_description = []\n    for key, value in all_query_params.items():\n        submit_description.append('%s = %s' % (key, value))\n    submit_description.append('executable = ' + executable)\n    submit_description.append('output = ' + output)\n    submit_description.append('error = ' + error)\n    submit_description.append('log = ' + user_log)\n    submit_description.append('queue')\n    return '\\n'.join(submit_description)",
    "docstring": "Build up the contents of a condor submit description file.\n\n    >>> submit_args = dict(executable='/path/to/script', output='o', error='e', user_log='ul')\n    >>> submit_args['query_params'] = dict()\n    >>> default_description = build_submit_description(**submit_args)\n    >>> assert 'executable = /path/to/script' in default_description\n    >>> assert 'output = o' in default_description\n    >>> assert 'error = e' in default_description\n    >>> assert 'queue' in default_description\n    >>> assert 'universe = vanilla' in default_description\n    >>> assert 'universe = standard' not in default_description\n    >>> submit_args['query_params'] = dict(universe='standard')\n    >>> std_description = build_submit_description(**submit_args)\n    >>> assert 'universe = vanilla' not in std_description\n    >>> assert 'universe = standard' in std_description"
  },
  {
    "code": "def run(self, n_iter=-1, bg=False):\n        if n_iter == -1:\n            if not self.eval_at:\n                raise ValueError('Set n_iter or define evaluate_at.')\n            n_iter = self.eval_at[-1] + 1\n        self._running.set()\n        if bg:\n            self._t = threading.Thread(target=lambda: self._run(n_iter))\n            self._t.start()\n        else:\n            self._run(n_iter)",
    "docstring": "Run the experiment.\n\n            :param int n_iter: Number of run iterations, by default will run until the last evaluation step.\n            :param bool bg: whether to run in background (using a Thread)"
  },
  {
    "code": "def create_node(self, *args, **kwargs):\n        with (yield from self._iou_id_lock):\n            application_id = get_next_application_id(self.nodes)\n            node = yield from super().create_node(*args, application_id=application_id, **kwargs)\n        return node",
    "docstring": "Creates a new IOU VM.\n\n        :returns: IOUVM instance"
  },
  {
    "code": "def __eliminate_unused_constraits (self, objects):\n        result = []\n        for c in self.constraints_:\n            if c [0] in objects and c [1] in objects:\n                result.append (c)\n        return result",
    "docstring": "Eliminate constraints which mention objects not in 'objects'.\n            In graph-theory terms, this is finding subgraph induced by\n            ordered vertices."
  },
  {
    "code": "def create_queue_service(self):\n        try:\n            from azure.storage.queue.queueservice import QueueService\n            return QueueService(self.account_name, self.account_key,\n                                sas_token=self.sas_token,\n                                is_emulated=self.is_emulated)\n        except ImportError:\n            raise Exception('The package azure-storage-queue is required. '\n                            + 'Please install it using \"pip install azure-storage-queue\"')",
    "docstring": "Creates a QueueService object with the settings specified in the \n        CloudStorageAccount.\n\n        :return: A service object.\n        :rtype: :class:`~azure.storage.queue.queueservice.QueueService`"
  },
  {
    "code": "def last_written_resolver(riak_object):\n    riak_object.siblings = [max(riak_object.siblings,\n                                key=lambda x: x.last_modified), ]",
    "docstring": "A conflict-resolution function that resolves by selecting the most\n    recently-modified sibling by timestamp.\n\n    :param riak_object: an object-in-conflict that will be resolved\n    :type riak_object: :class:`RiakObject <riak.riak_object.RiakObject>`"
  },
  {
    "code": "def get_key_by_job_id(cls, mapreduce_id):\n    return db.Key.from_path(cls.kind(), str(mapreduce_id))",
    "docstring": "Retrieves the Key for a Job.\n\n    Args:\n      mapreduce_id: The job to retrieve.\n\n    Returns:\n      Datastore Key that can be used to fetch the MapreduceState."
  },
  {
    "code": "def _add_dispatcher(self, path_regex, dispatch_function):\n    self._dispatchers.append((re.compile(path_regex), dispatch_function))",
    "docstring": "Add a request path and dispatch handler.\n\n    Args:\n      path_regex: A string regex, the path to match against incoming requests.\n      dispatch_function: The function to call for these requests.  The function\n        should take (request, start_response) as arguments and\n        return the contents of the response body."
  },
  {
    "code": "def preprocess(cls, cat):\n        if isinstance(cat, str):\n            cat = intake.open_catalog(cat)\n        return cat",
    "docstring": "Function to run on each cat input"
  },
  {
    "code": "def execution_timer(self, *path):\n        start = time.time()\n        try:\n            yield\n        finally:\n            self.record_timing(max(start, time.time()) - start, *path)",
    "docstring": "Record the time it takes to perform an arbitrary code block.\n\n        :param path: elements of the metric path to record\n\n        This method returns a context manager that records the amount\n        of time spent inside of the context and submits a timing metric\n        to the specified `path` using (:meth:`record_timing`)."
  },
  {
    "code": "def inspect_swarm(self):\n        url = self._url('/swarm')\n        return self._result(self._get(url), True)",
    "docstring": "Retrieve low-level information about the current swarm.\n\n        Returns:\n            A dictionary containing data about the swarm.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def _parse_queue_list(list_output):\n    queues = dict((q.split('/')[-1], q) for q in list_output['stdout'])\n    return queues",
    "docstring": "Parse the queue to get a dict of name -> URL"
  },
  {
    "code": "def pickle_from_param(elem, name):\n\treturn pickle.loads(str(get_pyvalue(elem, u\"pickle:%s\" % name)))",
    "docstring": "Retrieve a pickled Python object from the document tree rooted at\n\telem."
  },
  {
    "code": "def field_for(self, field_id):\n        for field in self.fields:\n            if field.id == field_id:\n                return field\n        return None",
    "docstring": "Fetches the field for the given Field ID.\n\n        :param field_id: ID for Field to fetch.\n        :return: :class:`ContentTypeField <ContentTypeField>` object.\n        :rtype: contentful.ContentTypeField"
  },
  {
    "code": "def search_schema_path(self, index, **options):\n        if not self.yz_wm_schema:\n            raise RiakError(\"Yokozuna search is unsupported by this Riak node\")\n        return mkpath(self.yz_wm_schema, \"schema\", quote_plus(index),\n                      **options)",
    "docstring": "Builds a Yokozuna search Solr schema URL.\n\n        :param index: a name of a yz solr schema\n        :type index: string\n        :param options: optional list of additional arguments\n        :type index: dict\n        :rtype URL string"
  },
  {
    "code": "def _download_movielens(dest_path):\n    url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip'\n    req = requests.get(url, stream=True)\n    with open(dest_path, 'wb') as fd:\n        for chunk in req.iter_content():\n            fd.write(chunk)",
    "docstring": "Download the dataset."
  },
  {
    "code": "def DbGetDeviceAliasList(self, argin):\n        self._log.debug(\"In DbGetDeviceAliasList()\")\n        if not argin:\n            argin = \"%\"\n        else:\n            argin = replace_wildcard(argin)\n        return self.db.get_device_alias_list(argin)",
    "docstring": "Get device alias name with a specific filter\n\n        :param argin: The filter\n        :type: tango.DevString\n        :return: Device alias list\n        :rtype: tango.DevVarStringArray"
  },
  {
    "code": "def frame_size(self):\n        if self.sample_type == SampleType.S16NativeEndian:\n            return self.sample_size * self.channels\n        else:\n            raise ValueError('Unknown sample type: %d', self.sample_type)",
    "docstring": "The byte size of a single frame of this format."
  },
  {
    "code": "def load_library(self):\n        \"loads configuration options\"\n        try:\n            filename = self.environment.get_template('chartkick.json').filename\n        except TemplateNotFound:\n            return {}\n        else:\n            options = Options()\n            options.load(filename)\n            return options",
    "docstring": "loads configuration options"
  },
  {
    "code": "def rename(df, **kwargs):\n    return df.rename(columns={v: k for k, v in kwargs.items()})",
    "docstring": "Renames columns, where keyword argument values are the current names\n    of columns and keys are the new names.\n\n    Args:\n        df (:obj:`pandas.DataFrame`): DataFrame passed in via `>>` pipe.\n\n    Kwargs:\n        **kwargs: key:value pairs where keys are new names for columns and\n            values are current names of columns."
  },
  {
    "code": "def restart(uuid, **kwargs):\n    from .worker_engine import restart_worker\n    return text_type(restart_worker(uuid, **kwargs).uuid)",
    "docstring": "Restart the workflow from a given workflow engine UUID."
  },
  {
    "code": "def unload_fixture(apps, schema_editor):\n    \"Brutally deleting all entries for this model...\"\n    MyModel = apps.get_model(\"blog\", \"Post\")\n    MyModel.objects.all().delete()",
    "docstring": "Brutally deleting all entries for this model..."
  },
  {
    "code": "def _hasattr(self, fieldname):\n        special = 'history', 'raw'\n        return (fieldname in special or \n                fieldname in self._defn.fieldmap or\n                fieldname in self._defn.derivationmap)",
    "docstring": "Returns True if this packet contains fieldname, False otherwise."
  },
  {
    "code": "def list_rbac_policies(self, retrieve_all=True, **_params):\n        return self.list('rbac_policies', self.rbac_policies_path,\n                         retrieve_all, **_params)",
    "docstring": "Fetch a list of all RBAC policies for a project."
  },
  {
    "code": "def submit(self):\n        self._newflg = False\n        ret = list()\n        for buf in self._buffer.values():\n            buf = copy.deepcopy(buf)\n            if self._fdpext:\n                buf['fpout'] = f\"{self._fproot}/{buf['label']}.{self._fdpext}\"\n            else:\n                del buf['fpout']\n            buf['index'] = tuple(buf['index'])\n            ret.append(Info(buf))\n        ret += self._stream\n        return tuple(ret)",
    "docstring": "Submit traced TCP flows."
  },
  {
    "code": "def logout(request):\n    user = request.user\n    serializer = LogoutSerializer(data=request.data)\n    serializer.is_valid(raise_exception=True)\n    data = serializer.validated_data\n    if should_authenticate_session():\n        auth.logout(request)\n    if should_retrieve_token() and data['revoke_token']:\n        try:\n            user.auth_token.delete()\n        except Token.DoesNotExist:\n            raise BadRequest('Cannot remove non-existent token')\n    return get_ok_response('Logout successful')",
    "docstring": "Logs out the user. returns an error if the user is not\n    authenticated."
  },
  {
    "code": "def init(args=None, lib='standard'):\n    if args is None:\n        args = sys.argv\n    _loadlib(lib)\n    arr = (ctypes.c_char_p * len(args))()\n    arr[:] = args\n    _LIB.RabitInit(len(args), arr)",
    "docstring": "Intialize the rabit module, call this once before using anything.\n\n    Parameters\n    ----------\n    args: list of str, optional\n        The list of arguments used to initialized the rabit\n        usually you need to pass in sys.argv.\n        Defaults to sys.argv when it is None.\n    lib: {'standard', 'mock', 'mpi'}\n        Type of library we want to load"
  },
  {
    "code": "def bestDescription(self, prefLanguage=\"en\"):\n        test_preds = [rdflib.RDFS.comment, rdflib.namespace.DCTERMS.description, rdflib.namespace.DC.description,\n                      rdflib.namespace.SKOS.definition]\n        for pred in test_preds:\n            test = self.getValuesForProperty(pred)\n            if test:\n                return addQuotes(firstEnglishStringInList(test))\n        return \"\"",
    "docstring": "facility for extrating the best available description for an entity\n\n        ..This checks RFDS.label, SKOS.prefLabel and finally the qname local component"
  },
  {
    "code": "def handle_abort(self, obj):\n        async_to_sync(consumer.send_event)({\n            WorkerProtocol.COMMAND: WorkerProtocol.ABORT,\n            WorkerProtocol.DATA_ID: obj[ExecutorProtocol.DATA_ID],\n            WorkerProtocol.FINISH_COMMUNICATE_EXTRA: {\n                'executor': getattr(settings, 'FLOW_EXECUTOR', {}).get('NAME', 'resolwe.flow.executors.local'),\n            },\n        })",
    "docstring": "Handle an incoming ``Data`` abort processing request.\n\n        .. IMPORTANT::\n\n            This only makes manager's state consistent and doesn't\n            affect Data object in any way. Any changes to the Data\n            must be applied over ``handle_update`` method.\n\n        :param obj: The Channels message object. Command object format:\n\n            .. code-block:: none\n\n                {\n                    'command': 'abort',\n                    'data_id': [id of the :class:`~resolwe.flow.models.Data` object\n                               this command was triggered by],\n                }"
  },
  {
    "code": "def get_group_line(self, data):\n        idx = -1\n        for key in self.groups:\n            i = self.get_group_key_line(data, key)\n            if (i < idx and i != -1) or idx == -1:\n                idx = i\n        return idx",
    "docstring": "Get the next group-style key's line.\n\n        :param data: the data to proceed\n        :returns: the line number"
  },
  {
    "code": "def add_to_replication_queue(source_node_urn, sysmeta_pyxb):\n    replica_info_model = d1_gmn.app.models.replica_info(\n        status_str='queued', source_node_urn=source_node_urn\n    )\n    local_replica_model = d1_gmn.app.models.local_replica(\n        pid=d1_common.xml.get_req_val(sysmeta_pyxb.identifier),\n        replica_info_model=replica_info_model,\n    )\n    d1_gmn.app.models.replication_queue(\n        local_replica_model=local_replica_model, size=sysmeta_pyxb.size\n    )",
    "docstring": "Add a replication request issued by a CN to a queue that is processed\n    asynchronously.\n\n    Preconditions:\n    - sysmeta_pyxb.identifier is verified to be available for create. E.g., with\n      d1_gmn.app.views.is_valid_pid_for_create(pid).\n\n    Postconditions:\n    - The database is set up to track a new replica, with initial status, \"queued\".\n    - The PID provided in the sysmeta_pyxb is reserved for the replica."
  },
  {
    "code": "def start_circle_left(self, radius_m, velocity=VELOCITY):\n        circumference = 2 * radius_m * math.pi\n        rate = 360.0 * velocity / circumference\n        self._set_vel_setpoint(velocity, 0.0, 0.0, -rate)",
    "docstring": "Start a circular motion to the left. This function returns immediately.\n\n        :param radius_m: The radius of the circle (meters)\n        :param velocity: The velocity of the motion (meters/second)\n        :return:"
  },
  {
    "code": "def get_name_from_name_hash128( self, name ):\n        cur = self.db.cursor()\n        name = namedb_get_name_from_name_hash128( cur, name, self.lastblock )\n        return name",
    "docstring": "Get the name from a name hash"
  },
  {
    "code": "def routers_removed_from_hosting_device(self, context, router_ids,\n                                            hosting_device):\n        self._agent_notification_bulk(\n            context, 'router_removed_from_hosting_device', router_ids,\n            hosting_device, operation=None)",
    "docstring": "Notify cfg agent that routers have been removed from hosting device.\n        @param: context - information about tenant, user etc\n        @param: router-ids - list of ids\n        @param: hosting_device - device hosting the routers"
  },
  {
    "code": "def cudnnGetConvolution2dForwardOutputDim(convDesc, inputTensorDesc, wDesc):\n    n = ctypes.c_int()\n    c = ctypes.c_int()\n    h = ctypes.c_int()\n    w = ctypes.c_int()\n    status = _libcudnn.cudnnGetConvolution2dForwardOutputDim(convDesc, inputTensorDesc,\n                                                 wDesc, ctypes.byref(n),\n                                                 ctypes.byref(c), ctypes.byref(h),\n                                                 ctypes.byref(w))\n    cudnnCheckStatus(status)\n    return n.value, c.value, h.value, w.value",
    "docstring": "Return the dimensions of the output tensor given a convolution descriptor.\n\n    This function returns the dimensions of the resulting 4D tensor of a 2D\n    convolution, given the convolution descriptor, the input tensor descriptor and\n    the filter descriptor. This function can help to setup the output tensor and allocate\n    the proper amount of memory prior to launching the actual convolution.\n\n    Parameters\n    ----------\n    convDesc : cudnnConvolutionDescriptor\n        Handle to a previously created convolution descriptor.\n    inputTensorDesc: cudnnTensorDescriptor\n        Handle to a previously initialized tensor descriptor.\n    wDesc: cudnnFilterDescriptor\n        Handle to a previously initialized filter descriptor.\n\n    Returns\n    -------\n    n : int\n        Number of output images.\n    c : int\n        Number of output feature maps per image.\n    h : int\n        Height of each output feature map.\n    w : int\n        Width of each output feature map."
  },
  {
    "code": "def can_allow_multiple_input_shapes(spec):\n    try:\n        layers = _get_nn_layers(spec)\n    except:\n        raise Exception('Unable to verify that this model contains a neural network.')\n    try:\n        shaper = NeuralNetworkShaper(spec, False)\n    except:\n        raise Exception('Unable to compute shapes for this neural network.')\n    inputs = _get_input_names(spec)\n    for name in inputs:\n        shape_dict = shaper.shape(name)\n        shape = NeuralNetworkMultiArrayShapeRange(shape_dict)\n        if (shape.isFlexible()):\n            return True\n    return False",
    "docstring": "Examines a model specification and determines if it can compute results for more than one output shape.\n\n    :param spec: MLModel\n        The protobuf specification of the model.\n\n    :return: Bool\n        Returns True if the model can allow multiple input shapes, False otherwise."
  },
  {
    "code": "def map_copy(source: tcod.map.Map, dest: tcod.map.Map) -> None:\n    if source.width != dest.width or source.height != dest.height:\n        dest.__init__(\n            source.width, source.height, source._order\n        )\n    dest._Map__buffer[:] = source._Map__buffer[:]",
    "docstring": "Copy map data from `source` to `dest`.\n\n    .. deprecated:: 4.5\n        Use Python's copy module, or see :any:`tcod.map.Map` and assign between\n        array attributes manually."
  },
  {
    "code": "def maybe_download_and_extract():\n  dest_directory = \"/tmp/cifar\"\n  if not os.path.exists(dest_directory):\n    os.makedirs(dest_directory)\n  filename = DATA_URL.split('/')[-1]\n  filepath = os.path.join(dest_directory, filename)\n  if not os.path.exists(filepath):\n    def _progress(count, block_size, total_size):\n      sys.stdout.write('\\r>> Downloading %s %.1f%%' % (filename,\n          float(count * block_size) / float(total_size) * 100.0))\n      sys.stdout.flush()\n    filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)\n    print()\n    statinfo = os.stat(filepath)\n    print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')\n    tarfile.open(filepath, 'r:gz').extractall(dest_directory)",
    "docstring": "Download and extract the tarball from Alex's website."
  },
  {
    "code": "def remove(self, game_object: Hashable) -> None:\n        self.all.remove(game_object)\n        for kind in type(game_object).mro():\n            self.kinds[kind].remove(game_object)\n        for s in self.tags.values():\n            s.discard(game_object)",
    "docstring": "Remove the given object from the container.\n\n        game_object: A hashable contained by container.\n\n        Example:\n            container.remove(myObject)"
  },
  {
    "code": "def _traverse_relationship_objs(self, rel2src2dsts, goobj_child, goids_seen):\n        child_id = goobj_child.id\n        goids_seen.add(child_id)\n        for goid_altid in goobj_child.alt_ids:\n            goids_seen.add(goid_altid)\n        for reltype, recs in goobj_child.relationship.items():\n            if reltype in self.relationships:\n                for relationship_obj in recs:\n                    relationship_id = relationship_obj.id\n                    rel2src2dsts[reltype][relationship_id].add(child_id)\n                    if relationship_id not in goids_seen:\n                        self._traverse_relationship_objs(rel2src2dsts, relationship_obj, goids_seen)",
    "docstring": "Traverse from source GO up relationships."
  },
  {
    "code": "def list_styles(self):\n        known = sorted(self.defaults.known_styles)\n        if not known:\n            err_exit('No styles', 0)\n        for style in known:\n            if style == self.defaults.default_style:\n                print(style, '(default)')\n            else:\n                print(style)\n        sys.exit(0)",
    "docstring": "Print available styles and exit."
  },
  {
    "code": "def tail(ctx):\n    click.echo('tailing logs')\n    for e in ctx.tail()[-10:]:\n        ts = datetime.utcfromtimestamp(e['timestamp'] // 1000).isoformat()\n        click.echo(\"{}: {}\".format(ts, e['message']))\n    click.echo('done')",
    "docstring": "Show the last 10 lines of the log file"
  },
  {
    "code": "def remove_user(self, workspace, params={}, **options): \n        path = \"/workspaces/%s/removeUser\" % (workspace)\n        return self.client.post(path, params, **options)",
    "docstring": "The user making this call must be an admin in the workspace.\n        Returns an empty data record.\n\n        Parameters\n        ----------\n        workspace : {Id} The workspace or organization to invite the user to.\n        [data] : {Object} Data for the request\n          - user : {String} An identifier for the user. Can be one of an email address,\n          the globally unique identifier for the user, or the keyword `me`\n          to indicate the current user making the request."
  },
  {
    "code": "def _get_order_by(self, request):\n        attr = request.params.get('sort', request.params.get('order_by'))\n        if attr is None or not hasattr(self.mapped_class, attr):\n            return None\n        if request.params.get('dir', '').upper() == 'DESC':\n            return desc(getattr(self.mapped_class, attr))\n        else:\n            return asc(getattr(self.mapped_class, attr))",
    "docstring": "Return an SA order_by"
  },
  {
    "code": "def filter_data(data, filter_dict):\n    for key, match_string in filter_dict.items():\n        if key not in data:\n            logger.warning(\"{0} doesn't match a top level key\".format(key))\n            continue\n        values = data[key]\n        matcher = re.compile(match_string)\n        if isinstance(values, list):\n            values = [v for v in values if matcher.search(v)]\n        elif isinstance(values, dict):\n            values = dict((k, v) for k, v in values.items() if matcher.search(k))\n        else:\n            raise MiuraException(\"cannot filter a {0}\".format(type(values)))\n        data[key] = values",
    "docstring": "filter a data dictionary for values only matching the filter"
  },
  {
    "code": "def _make_callsites(self, stack_pointer_tracker=None):\n        rd = self.project.analyses.ReachingDefinitions(func=self.function, func_graph=self.graph, observe_all=True)\n        for key in self._blocks:\n            block = self._blocks[key]\n            csm = self.project.analyses.AILCallSiteMaker(block, reaching_definitions=rd)\n            if csm.result_block:\n                ail_block = csm.result_block\n                simp = self.project.analyses.AILBlockSimplifier(ail_block, stack_pointer_tracker=stack_pointer_tracker)\n                self._blocks[key] = simp.result_block\n        self._update_graph()",
    "docstring": "Simplify all function call statements.\n\n        :return:    None"
  },
  {
    "code": "def unbound_dimensions(streams, kdims, no_duplicates=True):\n    params = stream_parameters(streams, no_duplicates)\n    return [d for d in kdims if d not in params]",
    "docstring": "Return a list of dimensions that have not been associated with\n    any streams."
  },
  {
    "code": "def list_folder(cls, session, mailbox, folder):\n        return cls(\n            '/mailboxes/%d/folders/%s/conversations.json' % (\n                mailbox.id, folder.id,\n            ),\n            session=session,\n        )",
    "docstring": "Return conversations in a specific folder of a mailbox.\n\n        Args:\n            session (requests.sessions.Session): Authenticated session.\n            mailbox (helpscout.models.Mailbox): Mailbox that folder is in.\n            folder (helpscout.models.Folder): Folder to list.\n\n        Returns:\n            RequestPaginator(output_type=helpscout.models.Conversation):\n                Conversations iterator."
  },
  {
    "code": "def update_properties(self, properties, email_to_addresses=None,\n                          email_cc_addresses=None, email_insert=None):\n        volreq_obj = copy.deepcopy(properties)\n        volreq_obj['operation'] = 'modify'\n        volreq_obj['element-uri'] = self.uri\n        body = {\n            'storage-volumes': [volreq_obj],\n        }\n        if email_to_addresses:\n            body['email-to-addresses'] = email_to_addresses\n            if email_cc_addresses:\n                body['email-cc-addresses'] = email_cc_addresses\n            if email_insert:\n                body['email-insert'] = email_insert\n        else:\n            if email_cc_addresses:\n                raise ValueError(\"email_cc_addresses must not be specified if \"\n                                 \"there is no email_to_addresses: %r\" %\n                                 email_cc_addresses)\n            if email_insert:\n                raise ValueError(\"email_insert must not be specified if \"\n                                 \"there is no email_to_addresses: %r\" %\n                                 email_insert)\n        self.manager.session.post(\n            self.manager.storage_group.uri + '/operations/modify',\n            body=body)\n        self.properties.update(copy.deepcopy(properties))",
    "docstring": "Update writeable properties of this storage volume on the HMC, and\n        optionally send emails to storage administrators requesting\n        modification of the storage volume on the storage subsystem and of any\n        resources related to the storage volume.\n\n        This method performs the \"Modify Storage Group Properties\" operation,\n        requesting modification of the volume.\n\n        Authorization requirements:\n\n        * Object-access permission to the storage group owning this storage\n          volume.\n        * Task permission to the \"Configure Storage - System Programmer\" task.\n\n        Parameters:\n\n          properties (dict): New property values for the volume.\n            Allowable properties are the fields defined in the\n            \"storage-volume-request-info\" nested object for the \"modify\"\n            operation. That nested object is described in section \"Request body\n            contents\" for operation \"Modify Storage Group Properties\" in the\n            :term:`HMC API` book.\n\n            The properties provided in this parameter will be copied and then\n            amended with the `operation=\"modify\"` and `element-uri` properties,\n            and then used as a single array item for the `storage-volumes`\n            field in the request body of the \"Modify Storage Group Properties\"\n            operation.\n\n          email_to_addresses (:term:`iterable` of :term:`string`): Email\n            addresses of one or more storage administrator to be notified.\n            If `None` or empty, no email will be sent.\n\n          email_cc_addresses (:term:`iterable` of :term:`string`): Email\n            addresses of one or more storage administrator to be copied\n            on the notification email.\n            If `None` or empty, nobody will be copied on the email.\n            Must be `None` or empty if `email_to_addresses` is `None` or empty.\n\n          email_insert (:term:`string`): Additional text to be inserted in the\n            notification email.\n            The text can include HTML formatting tags.\n            If `None`, no additional text will be inserted.\n            Must be `None` or empty if `email_to_addresses` is `None` or empty.\n\n        Raises:\n\n          :exc:`~zhmcclient.HTTPError`\n          :exc:`~zhmcclient.ParseError`\n          :exc:`~zhmcclient.AuthError`\n          :exc:`~zhmcclient.ConnectionError`"
  },
  {
    "code": "def extractSurface(image, radius=0.5):\n    fe = vtk.vtkExtractSurface()\n    fe.SetInputData(image)\n    fe.SetRadius(radius)\n    fe.Update()\n    return Actor(fe.GetOutput())",
    "docstring": "``vtkExtractSurface`` filter. Input is a ``vtkImageData``.\n    Generate zero-crossing isosurface from truncated signed distance volume."
  },
  {
    "code": "def replay_sync(self, live=False):\n        'Replay all commands in log.'\n        self.cursorRowIndex = 0\n        CommandLog.currentReplay = self\n        with Progress(total=len(self.rows)) as prog:\n            while self.cursorRowIndex < len(self.rows):\n                if CommandLog.currentReplay is None:\n                    status('replay canceled')\n                    return\n                vd().statuses.clear()\n                try:\n                    if self.replayOne(self.cursorRow):\n                        self.cancel()\n                        return\n                except Exception as e:\n                    self.cancel()\n                    exceptionCaught(e)\n                    status('replay canceled')\n                    return\n                self.cursorRowIndex += 1\n                prog.addProgress(1)\n                sync(1 if live else 0)\n                while not self.delay():\n                    pass\n        status('replay complete')\n        CommandLog.currentReplay = None",
    "docstring": "Replay all commands in log."
  },
  {
    "code": "def _kill_process(proc):\n    try:\n        proc.kill()\n    except AccessDenied:\n        logs.debug(u'Rerun: process PID {} ({}) could not be terminated'.format(\n            proc.pid, proc.exe()))",
    "docstring": "Tries to kill the process otherwise just logs a debug message, the\n    process will be killed when thefuck terminates.\n\n    :type proc: Process"
  },
  {
    "code": "def skip_connection_distance(a, b):\n    if a[2] != b[2]:\n        return 1.0\n    len_a = abs(a[1] - a[0])\n    len_b = abs(b[1] - b[0])\n    return (abs(a[0] - b[0]) + abs(len_a - len_b)) / (max(a[0], b[0]) + max(len_a, len_b))",
    "docstring": "The distance between two skip-connections."
  },
  {
    "code": "def get_channel_comment(self, name=None, group=None, index=None):\n        gp_nr, ch_nr = self._validate_channel_selection(name, group, index)\n        grp = self.groups[gp_nr]\n        channel = grp.channels[ch_nr]\n        return extract_cncomment_xml(channel.comment)",
    "docstring": "Gets channel comment.\n\n        Channel can be specified in two ways:\n\n        * using the first positional argument *name*\n\n            * if there are multiple occurrences for this channel then the\n              *group* and *index* arguments can be used to select a specific\n              group.\n            * if there are multiple occurrences for this channel and either the\n              *group* or *index* arguments is None then a warning is issued\n\n        * using the group number (keyword argument *group*) and the channel\n          number (keyword argument *index*). Use *info* method for group and\n          channel numbers\n\n\n        If the *raster* keyword argument is not *None* the output is\n        interpolated accordingly.\n\n        Parameters\n        ----------\n        name : string\n            name of channel\n        group : int\n            0-based group index\n        index : int\n            0-based channel index\n\n        Returns\n        -------\n        comment : str\n            found channel comment"
  },
  {
    "code": "def check_driver_dependencies(driver, dependencies):\n    ret = True\n    for key, value in six.iteritems(dependencies):\n        if value is False:\n            log.warning(\n                \"Missing dependency: '%s'. The %s driver requires \"\n                \"'%s' to be installed.\", key, driver, key\n            )\n            ret = False\n    return ret",
    "docstring": "Check if the driver's dependencies are available.\n\n    .. versionadded:: 2015.8.0\n\n    driver\n        The name of the driver.\n\n    dependencies\n        The dictionary of dependencies to check."
  },
  {
    "code": "def page(self, category=values.unset, start_date=values.unset,\n             end_date=values.unset, include_subaccounts=values.unset,\n             page_token=values.unset, page_number=values.unset,\n             page_size=values.unset):\n        params = values.of({\n            'Category': category,\n            'StartDate': serialize.iso8601_date(start_date),\n            'EndDate': serialize.iso8601_date(end_date),\n            'IncludeSubaccounts': include_subaccounts,\n            'PageToken': page_token,\n            'Page': page_number,\n            'PageSize': page_size,\n        })\n        response = self._version.page(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return DailyPage(self._version, response, self._solution)",
    "docstring": "Retrieve a single page of DailyInstance records from the API.\n        Request is executed immediately\n\n        :param DailyInstance.Category category: The usage category of the UsageRecord resources to read\n        :param date start_date: Only include usage that has occurred on or after this date\n        :param date end_date: Only include usage that occurred on or before this date\n        :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts\n        :param str page_token: PageToken provided by the API\n        :param int page_number: Page Number, this value is simply for client state\n        :param int page_size: Number of records to return, defaults to 50\n\n        :returns: Page of DailyInstance\n        :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyPage"
  },
  {
    "code": "def _function_add_call_edge(self, addr, src_node, function_addr, syscall=False, stmt_idx=None, ins_addr=None):\n        try:\n            if src_node is None:\n                self.kb.functions._add_node(function_addr, addr, syscall=syscall)\n            else:\n                src_snippet = self._to_snippet(cfg_node=src_node)\n                return_to_outside = False\n                ret_snippet = None\n                self.kb.functions._add_call_to(function_addr, src_snippet, addr, ret_snippet, syscall=syscall,\n                                               stmt_idx=stmt_idx, ins_addr=ins_addr,\n                                               return_to_outside=return_to_outside,\n                                               )\n            return True\n        except (SimMemoryError, SimEngineError):\n            return False",
    "docstring": "Add a call edge to the function transition map.\n\n        :param int addr: Address that is being called (callee).\n        :param CFGNode src_node: The source CFG node (caller).\n        :param int ret_addr: Address that returns to (in case the function returns).\n        :param int function_addr: Function address..\n        :param bool syscall: If this is a call to a syscall or not.\n        :param int or str stmt_idx: Statement ID of this call.\n        :param int or None ins_addr: Instruction address of this call.\n        :return: True if the edge is added. False if any exception occurred.\n        :rtype: bool"
  },
  {
    "code": "def _max_args(self, f):\n        if f.func_defaults is None:\n            return f.func_code.co_argcount\n        return f.func_code.co_argcount + len(f.func_defaults)",
    "docstring": "Returns maximum number of arguments accepted by given function."
  },
  {
    "code": "def close(self):\n        if isinstance(self._session, requests.Session):\n            self._session.close()",
    "docstring": "Close http session."
  },
  {
    "code": "def connect_float_text(instance, prop, widget, fmt=\"{:g}\"):\n    if callable(fmt):\n        format_func = fmt\n    else:\n        def format_func(x):\n            return fmt.format(x)\n    def update_prop():\n        val = widget.text()\n        try:\n            setattr(instance, prop, float(val))\n        except ValueError:\n            setattr(instance, prop, 0)\n    def update_widget(val):\n        if val is None:\n            val = 0.\n        widget.setText(format_func(val))\n    add_callback(instance, prop, update_widget)\n    try:\n        widget.editingFinished.connect(update_prop)\n    except AttributeError:\n        pass\n    update_widget(getattr(instance, prop))",
    "docstring": "Connect a numerical callback property with a Qt widget containing text.\n\n    Parameters\n    ----------\n    instance : object\n        The class instance that the callback property is attached to\n    prop : str\n        The name of the callback property\n    widget : QtWidget\n        The Qt widget to connect. This should implement the ``setText`` and\n        ``text`` methods as well optionally the ``editingFinished`` signal.\n    fmt : str or func\n        This should be either a format string (in the ``{}`` notation), or a\n        function that takes a number and returns a string."
  },
  {
    "code": "def get_instructions(self):\n        tmp_ins = []\n        idx = 0\n        for i in self.method.get_instructions():\n            if idx >= self.start and idx < self.end:\n                tmp_ins.append(i)\n            idx += i.get_length()\n        return tmp_ins",
    "docstring": "Get all instructions from a basic block.\n\n        :rtype: Return all instructions in the current basic block"
  },
  {
    "code": "def distance_to_angle(distance, units='metric'):\n    if units in ('km', 'metric'):\n        pass\n    elif units in ('sm', 'imperial', 'US customary'):\n        distance *= STATUTE_MILE\n    elif units in ('nm', 'nautical'):\n        distance *= NAUTICAL_MILE\n    else:\n        raise ValueError('Unknown units type %r' % units)\n    return math.degrees(distance / BODY_RADIUS)",
    "docstring": "Convert a distance in to an angle along a great circle.\n\n    Args:\n        distance (float): Distance to convert to degrees\n        units (str): Unit type to be used for distances\n\n    Returns:\n        float: Angle in degrees\n\n    Raises:\n        ValueError: Unknown value for ``units``"
  },
  {
    "code": "def select_by_key(self, key):\n        self._selected_key = None\n        self._selected_item = None\n        for item in self.children.values():\n            item.attributes['selected'] = False\n        if key in self.children:\n            self.children[key].attributes['selected'] = True\n            self._selected_key = key\n            self._selected_item = self.children[key]",
    "docstring": "Selects an item by its key.\n\n        Args:\n            key (str): The unique string identifier of the item that have to be selected."
  },
  {
    "code": "def truepath_relative(path, otherpath=None):\n    if otherpath is None:\n        otherpath = os.getcwd()\n    otherpath = truepath(otherpath)\n    path_ = normpath(relpath(path, otherpath))\n    return path_",
    "docstring": "Normalizes and returns absolute path with so specs\n\n    Args:\n        path (str):  path to file or directory\n        otherpath (None): (default = None)\n\n    Returns:\n        str: path_\n\n    CommandLine:\n        python -m utool.util_path --exec-truepath_relative --show\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_path import *  # NOQA\n        >>> import utool as ut\n        >>> path = 'C:/foobar/foobiz'\n        >>> otherpath = 'C:/foobar'\n        >>> path_ = truepath_relative(path, otherpath)\n        >>> result = ('path_ = %s' % (ut.repr2(path_),))\n        >>> print(result)\n        path_ = 'foobiz'"
  },
  {
    "code": "def wrap(self, text, **kwargs):\n        pilcrow = re.compile(r'(\\n\\s*\\n)', re.MULTILINE)\n        list_prefix = re.compile(r'\\s*(?:\\w|[0-9]+)[\\.\\)]\\s+')\n        paragraphs = pilcrow.split(text)\n        wrapped_lines = []\n        for paragraph in paragraphs:\n            if paragraph.isspace():\n                wrapped_lines.append('')\n            else:\n                wrapper = textwrap.TextWrapper(**vars(self))\n                list_item = re.match(list_prefix, paragraph)\n                if list_item:\n                    wrapper.subsequent_indent += ' ' * len(list_item.group(0))\n                wrapped_lines.extend(wrapper.wrap(paragraph))\n        return wrapped_lines",
    "docstring": "Wraps each paragraph in ``text`` individually.\n\n        Parameters\n        ----------\n        text : str\n\n        Returns\n        -------\n        str\n            Single string containing the wrapped paragraphs."
  },
  {
    "code": "def Reynolds_valve(nu, Q, D1, FL, Fd, C):\n    r\n    return N4*Fd*Q/nu/(C*FL)**0.5*(FL**2*C**2/(N2*D1**4) + 1)**0.25",
    "docstring": "r'''Calculates Reynolds number of a control valve for a liquid or gas\n    flowing through it at a specified Q, for a specified D1, FL, Fd, C, and\n    with kinematic viscosity `nu` according to IEC 60534 calculations.\n\n    .. math::\n        Re_v = \\frac{N_4 F_d Q}{\\nu \\sqrt{C F_L}}\\left(\\frac{F_L^2 C^2}\n        {N_2D^4} +1\\right)^{1/4}\n\n    Parameters\n    ----------\n    nu : float\n        Kinematic viscosity, [m^2/s]\n    Q : float\n        Volumetric flow rate of the fluid [m^3/s]\n    D1 : float\n        Diameter of the pipe before the valve [m]\n    FL : float, optional\n        Liquid pressure recovery factor of a control valve without attached \n        fittings []\n    Fd : float\n        Valve style modifier [-]\n    C : float\n        Metric Kv valve flow coefficient (flow rate of water at a pressure drop  \n        of 1 bar) [m^3/hr]\n\n    Returns\n    -------\n    Rev : float\n        Valve reynolds number [-]\n\n    Examples\n    --------\n    >>> Reynolds_valve(3.26e-07, 360, 150.0, 0.9, 0.46, 165)\n    2966984.7525455453\n\n    References\n    ----------\n    .. [1] IEC 60534-2-1 / ISA-75.01.01-2007"
  },
  {
    "code": "def set_value(self, value):\n        v = 0\n        measure_unit = 'px'\n        try:\n            v = int(float(value.replace('px', '')))\n        except ValueError:\n            try:\n                v = int(float(value.replace('%', '')))\n                measure_unit = '%'\n            except ValueError:\n                pass\n        self.numInput.set_value(v)\n        self.dropMeasureUnit.set_value(measure_unit)",
    "docstring": "The value have to be in the form '10px' or '10%', so numeric value plus measure unit"
  },
  {
    "code": "def from_samples(cls, samples_like, vectors, info, vartype, variable_labels=None):\n        try:\n            samples = np.asarray(samples_like, dtype=np.int8)\n        except TypeError:\n            samples, variable_labels = _samples_dicts_to_array(samples_like, variable_labels)\n        assert samples.dtype == np.int8, 'sanity check'\n        record = data_struct_array(samples, **vectors)\n        if variable_labels is None:\n            __, num_variables = record.sample.shape\n            variable_labels = list(range(num_variables))\n        return cls(record, variable_labels, info, vartype)",
    "docstring": "Build a response from samples.\n\n        Args:\n            samples_like:\n                A collection of samples. 'samples_like' is an extension of NumPy's array_like\n                to include an iterable of sample dictionaries (as returned by\n                :meth:`.Response.samples`).\n\n            data_vectors (dict[field, :obj:`numpy.array`/list]):\n                Additional per-sample data as a dict of vectors. Each vector is the\n                same length as `samples_matrix`. The key 'energy' and it's vector is required.\n\n            info (dict):\n                Information about the response as a whole formatted as a dict.\n\n            vartype (:class:`.Vartype`/str/set):\n                Variable type for the response. Accepted input values:\n\n                * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n                * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n            variable_labels (list, optional):\n                Determines the variable labels if samples_like is not an iterable of dictionaries.\n                If samples_like is not an iterable of dictionaries and if variable_labels is not\n                provided then index labels are used.\n\n        Returns:\n            :obj:`.Response`\n\n        Examples:\n            From dicts\n\n            >>> import dimod\n            ...\n            >>> samples = [{'a': -1, 'b': +1}, {'a': -1, 'b': -1}]\n            >>> response = dimod.Response.from_samples(samples, {'energy': [-1, 0]}, {}, dimod.SPIN)\n\n            From an array\n\n            >>> import dimod\n            >>> import numpy as np\n            ...\n            >>> samples = np.ones((2, 3), dtype='int8')  # 2 samples, 3 variables\n            >>> response = dimod.Response.from_samples(samples, {'energy': [-1.0, -1.0]}, {},\n            ...                                        dimod.SPIN, variable_labels=['a', 'b', 'c'])"
  },
  {
    "code": "def to_global(s):\n  if s.startswith('GPSTime'):\n    s = 'Gps' + s[3:]\n  if '_' in s:\n    s = \"\".join([i.capitalize() for i in s.split(\"_\")])\n  return s[0].lower() + s[1:]",
    "docstring": "Format a global variable name."
  },
  {
    "code": "def follow(user, obj, send_action=True, actor_only=True, flag='', **kwargs):\n    check(obj)\n    instance, created = apps.get_model('actstream', 'follow').objects.get_or_create(\n        user=user, object_id=obj.pk, flag=flag,\n        content_type=ContentType.objects.get_for_model(obj),\n        actor_only=actor_only\n    )\n    if send_action and created:\n        if not flag:\n            action.send(user, verb=_('started following'), target=obj, **kwargs)\n        else:\n            action.send(user, verb=_('started %s' % flag), target=obj, **kwargs)\n    return instance",
    "docstring": "Creates a relationship allowing the object's activities to appear in the\n    user's stream.\n\n    Returns the created ``Follow`` instance.\n\n    If ``send_action`` is ``True`` (the default) then a\n    ``<user> started following <object>`` action signal is sent.\n    Extra keyword arguments are passed to the action.send call.\n\n    If ``actor_only`` is ``True`` (the default) then only actions where the\n    object is the actor will appear in the user's activity stream. Set to\n    ``False`` to also include actions where this object is the action_object or\n    the target.\n\n    If ``flag`` not an empty string then the relationship would marked by this flag.\n\n    Example::\n\n        follow(request.user, group, actor_only=False)\n        follow(request.user, group, actor_only=False, flag='liking')"
  },
  {
    "code": "def load(self, shapefile=None):\r\n        if shapefile:\r\n            (shapeName, ext) = os.path.splitext(shapefile)\r\n            self.shapeName = shapeName\r\n            try:\r\n                self.shp = open(\"%s.shp\" % shapeName, \"rb\")\r\n            except IOError:\r\n                raise ShapefileException(\"Unable to open %s.shp\" % shapeName)\r\n            try:\r\n                self.shx = open(\"%s.shx\" % shapeName, \"rb\")\r\n            except IOError:\r\n                raise ShapefileException(\"Unable to open %s.shx\" % shapeName)\r\n            try:\r\n                self.dbf = open(\"%s.dbf\" % shapeName, \"rb\")\r\n            except IOError:\r\n                raise ShapefileException(\"Unable to open %s.dbf\" % shapeName)\r\n        if self.shp:\r\n            self.__shpHeader()\r\n        if self.dbf:\r\n            self.__dbfHeader()",
    "docstring": "Opens a shapefile from a filename or file-like\r\n        object. Normally this method would be called by the\r\n        constructor with the file object or file name as an\r\n        argument."
  },
  {
    "code": "def calc_downsample(w, h, target=400):\n    if w > h:\n        return h / target\n    elif h >= w:\n        return w / target",
    "docstring": "Calculate downsampling value."
  },
  {
    "code": "def get_values(self, set, selected_meta):\n        warnings.warn(\"\\n\\nThis method assumes that the last level of the index is the sample_id.\\n\"\n                      \"In case of single index, the index itself should be the sample_id\")\n        sample_ids = set.index.get_level_values(-1)\n        corresponding_meta = self.meta.loc[sample_ids]\n        values = corresponding_meta[selected_meta]\n        try:\n            values = values.astype(float)\n        except ValueError:\n            print(\"the values should be numeric\")\n        return values",
    "docstring": "Retrieves the selected metadata values of the given set\n\n        :param set: cluster that contains the data\n        :param selected_meta: the values of the selected_meta\n        :return: the values of the selected meta of the cluster"
  },
  {
    "code": "def target(self):\n        task = yield self.task()\n        if not task:\n            yield defer.succeed(None)\n            defer.returnValue(None)\n        defer.returnValue(task.target)",
    "docstring": "Find the target name for this build.\n\n        :returns: deferred that when fired returns the build task's target\n                  name. If we could not determine the build task, or the task's\n                  target, return None."
  },
  {
    "code": "def async_run(self, keyword, *args, **kwargs):\n        handle = self._last_thread_handle\n        thread = self._threaded(keyword, *args, **kwargs)\n        thread.start()\n        self._thread_pool[handle] = thread\n        self._last_thread_handle += 1\n        return handle",
    "docstring": "Executes the provided Robot Framework keyword in a separate thread and immediately returns a handle to be used with async_get"
  },
  {
    "code": "def setInstrument(self, instrument, override_analyses=False):\n        analyses = [an for an in self.getAnalyses()\n                    if (not an.getInstrument() or override_analyses) and\n                    an.isInstrumentAllowed(instrument)]\n        total = 0\n        for an in analyses:\n            instr_methods = instrument.getMethods()\n            meth = instr_methods[0] if instr_methods else None\n            if meth and an.isMethodAllowed(meth):\n                if an.getMethod() not in instr_methods:\n                    an.setMethod(meth)\n            an.setInstrument(instrument)\n            total += 1\n        self.getField('Instrument').set(self, instrument)\n        return total",
    "docstring": "Sets the specified instrument to the Analysis from the\n            Worksheet. Only sets the instrument if the Analysis\n            allows it, according to its Analysis Service and Method.\n            If an analysis has already assigned an instrument, it won't\n            be overriden.\n            The Analyses that don't allow the instrument specified will\n            not be modified.\n            Returns the number of analyses affected"
  },
  {
    "code": "def get_prop_value(name, props, default=None):\n    if not props:\n        return default\n    try:\n        return props[name]\n    except KeyError:\n        return default",
    "docstring": "Returns the value of a property or the default one\n\n    :param name: Name of a property\n    :param props: Dictionary of properties\n    :param default: Default value\n    :return: The value of the property or the default one"
  },
  {
    "code": "def open_file_like(f, mode):\n    new_fd = isinstance(f, (str, pathlib.Path))\n    if new_fd:\n        f = open(f, mode)\n    try:\n        yield f\n    finally:\n        if new_fd:\n            f.close()",
    "docstring": "Wrapper for opening a file"
  },
  {
    "code": "def focusd(task):\n    if registration.get_registered(event_hooks=True, root_access=True):\n        start_cmd_srv = (os.getuid() == 0)\n    else:\n        start_cmd_srv = False\n    _run = lambda: Focusd(task).run(start_cmd_srv)\n    daemonize(get_daemon_pidfile(task), task.task_dir, _run)",
    "docstring": "Forks the current process as a daemon to run a task.\n\n        `task`\n            ``Task`` instance for the task to run."
  },
  {
    "code": "def __ordinal(self, num):\n        if 10 <= num % 100 < 20:\n            return str(num) + 'th'\n        else:\n            ord_info = {1: 'st', 2: 'nd', 3: 'rd'}.get(num % 10, 'th')\n            return '{}{}'.format(num, ord_info)",
    "docstring": "Returns the ordinal number of a given integer, as a string.\n        eg. 1 -> 1st, 2 -> 2nd, 3 -> 3rd, etc."
  },
  {
    "code": "def execute(self, query, *multiparams, **params):\n        coro = self._execute(query, *multiparams, **params)\n        return _SAConnectionContextManager(coro)",
    "docstring": "Executes a SQL query with optional parameters.\n\n        query - a SQL query string or any sqlalchemy expression.\n\n        *multiparams/**params - represent bound parameter values to be\n        used in the execution.  Typically, the format is a dictionary\n        passed to *multiparams:\n\n            await conn.execute(\n                table.insert(),\n                {\"id\":1, \"value\":\"v1\"},\n            )\n\n        ...or individual key/values interpreted by **params::\n\n            await conn.execute(\n                table.insert(), id=1, value=\"v1\"\n            )\n\n        In the case that a plain SQL string is passed, a tuple or\n        individual values in \\*multiparams may be passed::\n\n            await conn.execute(\n                \"INSERT INTO table (id, value) VALUES (%d, %s)\",\n                (1, \"v1\")\n            )\n\n            await conn.execute(\n                \"INSERT INTO table (id, value) VALUES (%s, %s)\",\n                1, \"v1\"\n            )\n\n        Returns ResultProxy instance with results of SQL query\n        execution."
  },
  {
    "code": "def disable_cors(self):\n        return self.update_cors_configuration(\n            enable_cors=False,\n            allow_credentials=False,\n            origins=[],\n            overwrite_origins=True\n        )",
    "docstring": "Switches CORS off.\n\n        :returns: CORS status in JSON format"
  },
  {
    "code": "def chart(self, x=None, y=None, chart_type=None, opts=None,\n\t\t\t  style=None, label=None, options={}, **kwargs):\n\t\ttry:\n\t\t\tself.chart_obj = self._chart(x, y, chart_type, opts, style, label,\n\t\t\t\t\t\t\t\t\t\t options=options, **kwargs)\n\t\texcept Exception as e:\n\t\t\tself.err(e, self.chart, \"Can not create chart\")",
    "docstring": "Get a chart"
  },
  {
    "code": "def _lookup_attributes(glyph_name, data):\n    attributes = (\n        data.names.get(glyph_name)\n        or data.alternative_names.get(glyph_name)\n        or data.production_names.get(glyph_name)\n        or {}\n    )\n    return attributes",
    "docstring": "Look up glyph attributes in data by glyph name, alternative name or\n    production name in order or return empty dictionary.\n\n    Look up by alternative and production names for legacy projects and\n    because of issue #232."
  },
  {
    "code": "def read_string_data(file, number_values, endianness):\n    offsets = [0]\n    for i in range(number_values):\n        offsets.append(types.Uint32.read(file, endianness))\n    strings = []\n    for i in range(number_values):\n        s = file.read(offsets[i + 1] - offsets[i])\n        strings.append(s.decode('utf-8'))\n    return strings",
    "docstring": "Read string raw data\n\n        This is stored as an array of offsets\n        followed by the contiguous string data."
  },
  {
    "code": "def loss(logits, labels):\n  labels = tf.cast(labels, tf.int64)\n  cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n      labels=labels, logits=logits, name='cross_entropy_per_example')\n  cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')\n  tf.add_to_collection('losses', cross_entropy_mean)\n  return tf.add_n(tf.get_collection('losses'), name='total_loss')",
    "docstring": "Add L2Loss to all the trainable variables.\n\n  Add summary for \"Loss\" and \"Loss/avg\".\n  Args:\n    logits: Logits from inference().\n    labels: Labels from distorted_inputs or inputs(). 1-D tensor\n            of shape [batch_size]\n\n  Returns:\n    Loss tensor of type float."
  },
  {
    "code": "def read_html_file(filename):\n    with open(os.path.join(get_static_directory(), 'html/{filename}'.format(filename=filename))) as f:\n        contents = f.read()\n    return contents",
    "docstring": "Reads the contents of an html file in the css directory\n\n    @return: Contents of the specified file"
  },
  {
    "code": "def mimetype(self, value: str) -> None:\n        if (\n                value.startswith('text/') or value == 'application/xml' or\n                (value.startswith('application/') and value.endswith('+xml'))\n        ):\n            mimetype = f\"{value}; charset={self.charset}\"\n        else:\n            mimetype = value\n        self.headers['Content-Type'] = mimetype",
    "docstring": "Set the mimetype to the value."
  },
  {
    "code": "def get_sites_in_sphere(self, pt, r):\n        neighbors = []\n        for site in self._sites:\n            dist = site.distance_from_point(pt)\n            if dist <= r:\n                neighbors.append((site, dist))\n        return neighbors",
    "docstring": "Find all sites within a sphere from a point.\n\n        Args:\n            pt (3x1 array): Cartesian coordinates of center of sphere.\n            r (float): Radius of sphere.\n\n        Returns:\n            [(site, dist) ...] since most of the time, subsequent processing\n            requires the distance."
  },
  {
    "code": "def overwrites_for(self, obj):\n        if isinstance(obj, User):\n            predicate = lambda p: p.type == 'member'\n        elif isinstance(obj, Role):\n            predicate = lambda p: p.type == 'role'\n        else:\n            predicate = lambda p: True\n        for overwrite in filter(predicate, self._overwrites):\n            if overwrite.id == obj.id:\n                allow = Permissions(overwrite.allow)\n                deny = Permissions(overwrite.deny)\n                return PermissionOverwrite.from_pair(allow, deny)\n        return PermissionOverwrite()",
    "docstring": "Returns the channel-specific overwrites for a member or a role.\n\n        Parameters\n        -----------\n        obj\n            The :class:`Role` or :class:`abc.User` denoting\n            whose overwrite to get.\n\n        Returns\n        ---------\n        :class:`PermissionOverwrite`\n            The permission overwrites for this object."
  },
  {
    "code": "def get_iso3_country_code(cls, country, use_live=True, exception=None):\n        countriesdata = cls.countriesdata(use_live=use_live)\n        countryupper = country.upper()\n        len_countryupper = len(countryupper)\n        if len_countryupper == 3:\n            if countryupper in countriesdata['countries']:\n                return countryupper\n        elif len_countryupper == 2:\n            iso3 = countriesdata['iso2iso3'].get(countryupper)\n            if iso3 is not None:\n                return iso3\n        iso3 = countriesdata['countrynames2iso3'].get(countryupper)\n        if iso3 is not None:\n            return iso3\n        for candidate in cls.expand_countryname_abbrevs(countryupper):\n            iso3 = countriesdata['countrynames2iso3'].get(candidate)\n            if iso3 is not None:\n                return iso3\n        if exception is not None:\n            raise exception\n        return None",
    "docstring": "Get ISO3 code for cls. Only exact matches or None are returned.\n\n        Args:\n            country (str): Country for which to get ISO3 code\n            use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.\n            exception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults to None.\n\n        Returns:\n            Optional[str]: ISO3 country code or None"
  },
  {
    "code": "def classify(self, classifier_id, text, **kwargs):\n        if classifier_id is None:\n            raise ValueError('classifier_id must be provided')\n        if text is None:\n            raise ValueError('text must be provided')\n        headers = {}\n        if 'headers' in kwargs:\n            headers.update(kwargs.get('headers'))\n        sdk_headers = get_sdk_headers('natural_language_classifier', 'V1',\n                                      'classify')\n        headers.update(sdk_headers)\n        data = {'text': text}\n        url = '/v1/classifiers/{0}/classify'.format(\n            *self._encode_path_vars(classifier_id))\n        response = self.request(\n            method='POST',\n            url=url,\n            headers=headers,\n            json=data,\n            accept_json=True)\n        return response",
    "docstring": "Classify a phrase.\n\n        Returns label information for the input. The status must be `Available` before you\n        can use the classifier to classify text.\n\n        :param str classifier_id: Classifier ID to use.\n        :param str text: The submitted phrase. The maximum length is 2048 characters.\n        :param dict headers: A `dict` containing the request headers\n        :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n        :rtype: DetailedResponse"
  },
  {
    "code": "def wp_status(self):\n        try:\n            print(\"Have %u of %u waypoints\" % (self.wploader.count()+len(self.wp_received), self.wploader.expected_count))\n        except Exception:\n            print(\"Have %u waypoints\" % (self.wploader.count()+len(self.wp_received)))",
    "docstring": "show status of wp download"
  },
  {
    "code": "def update(self, **kwargs):\n        super(CommonConf, self).update(**kwargs)\n        conf_changed = False\n        for conf_name, conf_value in kwargs.items():\n            rtconf.base.get_validator(conf_name)(conf_value)\n            item1 = self._settings.get(conf_name, None)\n            item2 = kwargs.get(conf_name, None)\n            if item1 != item2:\n                conf_changed = True\n        if conf_changed:\n            for conf_name, conf_value in kwargs.items():\n                self._settings[conf_name] = conf_value\n            self._notify_listeners(CommonConf.CONF_CHANGED_EVT, self)",
    "docstring": "Updates global configuration settings with given values.\n\n        First checks if given configuration values differ from current values.\n        If any of the configuration values changed, generates a change event.\n        Currently we generate change event for any configuration change.\n        Note: This method is idempotent."
  },
  {
    "code": "def confirmation(self, *args, **kwargs):\n        if not self.current_terminal:\n            raise RuntimeError(\"no active terminal\")\n        if not isinstance(self.current_terminal, Client):\n            raise RuntimeError(\"current terminal not a client\")\n        self.current_terminal.confirmation(*args, **kwargs)",
    "docstring": "Upstream packet, send to current terminal."
  },
  {
    "code": "def wsgi_app(self, environ, start_response):\n        @_LOCAL_MANAGER.middleware\n        def _wrapped_app(environ, start_response):\n            request = Request(environ)\n            setattr(_local, _CURRENT_REQUEST_KEY, request)\n            response = self._dispatch_request(request)\n            return response(environ, start_response)\n        return _wrapped_app(environ, start_response)",
    "docstring": "A basic WSGI app"
  },
  {
    "code": "def layer_from_combo(combo):\n    index = combo.currentIndex()\n    if index < 0:\n        return None\n    layer_id = combo.itemData(index, Qt.UserRole)\n    layer = QgsProject.instance().mapLayer(layer_id)\n    return layer",
    "docstring": "Get the QgsMapLayer currently selected in a combo.\n\n    Obtain QgsMapLayer id from the userrole of the QtCombo and return it as a\n    QgsMapLayer.\n\n    :returns: The currently selected map layer a combo.\n    :rtype: QgsMapLayer"
  },
  {
    "code": "def client_view(client):\n    if request.method == 'POST' and 'delete' in request.form:\n        db.session.delete(client)\n        db.session.commit()\n        return redirect(url_for('.index'))\n    form = ClientForm(request.form, obj=client)\n    if form.validate_on_submit():\n        form.populate_obj(client)\n        db.session.commit()\n    return render_template(\n        'invenio_oauth2server/settings/client_view.html',\n        client=client,\n        form=form,\n    )",
    "docstring": "Show client's detail."
  },
  {
    "code": "def _contour_helper(self, args, kwargs):\n        contour_kwargs = {}\n        contour_kwargs['measurement'] = kwargs.pop('measurement', 'poles')\n        contour_kwargs['method'] = kwargs.pop('method', 'exponential_kamb')\n        contour_kwargs['sigma'] = kwargs.pop('sigma', 3)\n        contour_kwargs['gridsize'] = kwargs.pop('gridsize', 100)\n        contour_kwargs['weights'] = kwargs.pop('weights', None)\n        lon, lat, totals = contouring.density_grid(*args, **contour_kwargs)\n        return lon, lat, totals, kwargs",
    "docstring": "Unify defaults and common functionality of ``density_contour`` and\n        ``density_contourf``."
  },
  {
    "code": "def convert_group(tokens):\n    tok = tokens.asList()\n    dic = dict(tok)\n    if not (len(dic) == len(tok)):\n        raise ParseFatalException(\"Names in group must be unique: %s\" % tokens)\n    return ConfGroup(dic)",
    "docstring": "Converts parseResult from to ConfGroup type."
  },
  {
    "code": "def prepare_value(value):\n        if isinstance(value, (list, tuple, set)):\n            return \",\".join(value)\n        if isinstance(value, bool):\n            return \"y\" if value else \"n\"\n        return str(value)",
    "docstring": "Prepare value to pylint."
  },
  {
    "code": "def get_normalized_bdew_profile(self):\n        self.df['temperature'] = self.temperature.values\n        self.df['temperature_geo'] = self.weighted_temperature(\n            how='geometric_series')\n        sf = self.get_sf_values()\n        [a, b, c, d] = self.get_sigmoid_parameters()\n        f = self.get_weekday_parameters()\n        h = (a / (1 + (b / (self.df['temperature_geo'] - 40)) ** c) + d)\n        kw = 1.0 / (sum(h * f) / 24)\n        heat_profile_normalized = (kw * h * f * sf)\n        return heat_profile_normalized",
    "docstring": "Calculation of the normalized hourly heat demand"
  },
  {
    "code": "def _create_timezone_static(tz):\n    timezone = icalendar.Timezone()\n    timezone.add('TZID', tz)\n    subcomp = icalendar.TimezoneStandard()\n    subcomp.add('TZNAME', tz)\n    subcomp.add('DTSTART', dt.datetime(1601, 1, 1))\n    subcomp.add('RDATE', dt.datetime(1601, 1, 1))\n    subcomp.add('TZOFFSETTO', tz._utcoffset)\n    subcomp.add('TZOFFSETFROM', tz._utcoffset)\n    timezone.add_component(subcomp)\n    return timezone",
    "docstring": "create an icalendar vtimezone from a pytz.tzinfo.StaticTzInfo\n\n    :param tz: the timezone\n    :type tz: pytz.tzinfo.StaticTzInfo\n    :returns: timezone information\n    :rtype: icalendar.Timezone()"
  },
  {
    "code": "def forward_moves(self, position):\n        if position.is_square_empty(self.square_in_front(self.location)):\n            if self.would_move_be_promotion():\n                for move in self.create_promotion_moves(notation_const.PROMOTE):\n                    yield move\n            else:\n                yield self.create_move(end_loc=self.square_in_front(self.location),\n                                       status=notation_const.MOVEMENT)\n            if self.on_home_row() and \\\n                    position.is_square_empty(self.two_squares_in_front(self.location)):\n                yield self.create_move(\n                    end_loc=self.square_in_front(self.square_in_front(self.location)),\n                    status=notation_const.MOVEMENT\n                )",
    "docstring": "Finds possible moves one step and two steps in front\n        of Pawn.\n\n        :type: position: Board\n        :rtype: list"
  },
  {
    "code": "def _is_whitelisted(self, email):\n        return hasattr(settings, \"SAFE_EMAIL_WHITELIST\") and \\\n            any(re.match(m, email) for m in settings.SAFE_EMAIL_WHITELIST)",
    "docstring": "Check if an email is in the whitelist. If there's no whitelist,\n        it's assumed it's not whitelisted."
  },
  {
    "code": "def generate_aliases_global(fieldfile, **kwargs):\n    from easy_thumbnails.files import generate_all_aliases\n    generate_all_aliases(fieldfile, include_global=True)",
    "docstring": "A saved_file signal handler which generates thumbnails for all field,\n    model, and app specific aliases matching the saved file's field, also\n    generating thumbnails for each project-wide alias."
  },
  {
    "code": "def copy_files(source_files, target_directory, source_directory=None):\n    try:\n        os.makedirs(target_directory)\n    except:\n        pass\n    for f in source_files:\n        source = os.path.join(source_directory, f) if source_directory else f\n        target = os.path.join(target_directory, f)\n        shutil.copy2(source, target)",
    "docstring": "Copies a list of files to the specified directory.\n    If source_directory is provided, it will be prepended to each source file."
  },
  {
    "code": "def new_temp_file(directory=None, hint=''):\n    return tempfile.NamedTemporaryFile(\n        prefix='tmp-wpull-{0}-'.format(hint), suffix='.tmp', dir=directory)",
    "docstring": "Return a new temporary file."
  },
  {
    "code": "def _get_request_token(self):\n        params = {\n            'oauth_callback': self.get_callback_url()\n        }\n        response, content = self.client().request(self.request_token_url,\n            \"POST\", body=urllib.urlencode(params))\n        content = smart_unicode(content)\n        if not response['status'] == '200':\n            raise OAuthError(_(\n                u\"Invalid status code %s while obtaining request token from %s: %s\") % (\n                    response['status'], self.request_token_url, content))\n        token = dict(urlparse.parse_qsl(content))\n        return oauth.Token(token['oauth_token'], token['oauth_token_secret'])",
    "docstring": "Fetch a request token from `self.request_token_url`."
  },
  {
    "code": "def connect(server, port, username, password):\n    print(\"-\" * 79)\n    print(\"Connecting to: {}\".format(server))\n    print(\"At port: {}\".format(port))\n    print(\"Using username: {}\".format(username))\n    print(\"Using password: {}\".format(password))\n    print(\"-\" * 79)",
    "docstring": "This function might be something coming from your ORM"
  },
  {
    "code": "def get_connection(self, fail_silently=False):\n        from protean.services.email import get_connection\n        if not self.connection:\n            self.connection = get_connection(fail_silently=fail_silently)\n        return self.connection",
    "docstring": "Retrieve connection to send email"
  },
  {
    "code": "def get_metatab_doc(nb_path):\n    from metatab.generate import CsvDataRowGenerator\n    from metatab.rowgenerators import TextRowGenerator\n    from metatab import MetatabDoc\n    with open(nb_path) as f:\n        nb = nbformat.reads(f.read(), as_version=4)\n    for cell in nb.cells:\n        source = ''.join(cell['source']).strip()\n        if source.startswith('%%metatab'):\n            return MetatabDoc(TextRowGenerator(source))",
    "docstring": "Read a notebook and extract the metatab document. Only returns the first document"
  },
  {
    "code": "def __set_value(self, value):\n        array = ((self._clean_value(value),),)\n        return self._get_target().setDataArray(array)",
    "docstring": "Sets cell value to a string or number based on the given value."
  },
  {
    "code": "def print_all_signals(self):\n        for o in dir(self):\n            obj= getattr(self, o)\n            div = False\n            for c in dir(obj):\n                cobj = getattr(obj, c)\n                if isinstance(cobj, Signal):\n                    print('def _on_{}__{}(self):'.format(o, c))\n                    div = True\n            if div: print('-'*30)",
    "docstring": "Prints out every signal available for this widget and childs."
  },
  {
    "code": "def slices(self):\n        if self.chunks is None:\n            yield tuple(slice(None, s) for s in self.shape)\n        else:\n            ceilings = tuple(-(-s // c) for s, c in zip(self.shape, self.chunks))\n            for idx in np.ndindex(ceilings):\n                out = []\n                for i, c, s in zip(idx, self.chunks, self.shape):\n                    start = i * c\n                    stop = min(start + c, s + 1)\n                    out.append(slice(start, stop, 1))\n                yield tuple(out)",
    "docstring": "Returns a generator yielding tuple of slice objects.\n\n        Order is not guaranteed."
  },
  {
    "code": "def dimensions(self):\n        return ImageDimensions(self._info.file.width, self._info.file.height)",
    "docstring": "Dimensions of the image.\n\n        :rtype: :py:class:`ImageDimensions`"
  },
  {
    "code": "def get_recipients(self, **options):\n        if options['recipients_from_setting']:\n            return settings.TIMELINE_DIGEST_EMAIL_RECIPIENTS\n        users = get_user_model()._default_manager.all()\n        if options['staff']:\n            users = users.filter(is_staff=True)\n        elif not options['all']:\n            users = users.filter(is_staff=True, is_superuser=True)\n        return users.values_list(settings.TIMELINE_USER_EMAIL_FIELD, flat=True)",
    "docstring": "Figures out the recipients"
  },
  {
    "code": "def num_orifices(FlowPlant, RatioVCOrifice, HeadLossOrifice, DiamOrifice):\n    return np.ceil(area_orifice(HeadLossOrifice, RatioVCOrifice,\n                                 FlowPlant).magnitude\n                    / area_circle(DiamOrifice).magnitude)",
    "docstring": "Return the number of orifices."
  },
  {
    "code": "def getPattern(self, word):\n        if word in self.patterns:\n            return self.patterns[word]\n        else:\n            raise ValueError('Unknown pattern in getPattern().', word)",
    "docstring": "Returns the pattern with key word.\n\n        Example: net.getPattern(\"tom\") => [0, 0, 0, 1]"
  },
  {
    "code": "def begin_transaction(\n        self,\n        database,\n        options_=None,\n        retry=google.api_core.gapic_v1.method.DEFAULT,\n        timeout=google.api_core.gapic_v1.method.DEFAULT,\n        metadata=None,\n    ):\n        if \"begin_transaction\" not in self._inner_api_calls:\n            self._inner_api_calls[\n                \"begin_transaction\"\n            ] = google.api_core.gapic_v1.method.wrap_method(\n                self.transport.begin_transaction,\n                default_retry=self._method_configs[\"BeginTransaction\"].retry,\n                default_timeout=self._method_configs[\"BeginTransaction\"].timeout,\n                client_info=self._client_info,\n            )\n        request = firestore_pb2.BeginTransactionRequest(\n            database=database, options=options_\n        )\n        if metadata is None:\n            metadata = []\n        metadata = list(metadata)\n        try:\n            routing_header = [(\"database\", database)]\n        except AttributeError:\n            pass\n        else:\n            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(\n                routing_header\n            )\n            metadata.append(routing_metadata)\n        return self._inner_api_calls[\"begin_transaction\"](\n            request, retry=retry, timeout=timeout, metadata=metadata\n        )",
    "docstring": "Starts a new transaction.\n\n        Example:\n            >>> from google.cloud import firestore_v1beta1\n            >>>\n            >>> client = firestore_v1beta1.FirestoreClient()\n            >>>\n            >>> database = client.database_root_path('[PROJECT]', '[DATABASE]')\n            >>>\n            >>> response = client.begin_transaction(database)\n\n        Args:\n            database (str): The database name. In the format:\n                ``projects/{project_id}/databases/{database_id}``.\n            options_ (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): The options for the transaction.\n                Defaults to a read-write transaction.\n\n                If a dict is provided, it must be of the same form as the protobuf\n                message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions`\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.firestore_v1beta1.types.BeginTransactionResponse` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def spike_latency(signal, threshold, fs):\n    over, = np.where(signal>threshold)\n    segments, = np.where(np.diff(over) > 1)\n    if len(over) > 1:\n        if len(segments) == 0:\n            idx = over[0] + np.argmax(signal[over[0]:over[-1]])\n            latency = float(idx)/fs\n        elif segments[0] == 0:\n            latency = float(over[0])/fs\n        else:\n            idx = over[0] + np.argmax(signal[over[0]:over[segments[0]]])\n            latency = float(idx)/fs\n    elif len(over) > 0:\n        latency = float(over[0])/fs\n    else:\n        latency = np.nan\n    return latency",
    "docstring": "Find the latency of the first spike over threshold\n\n    :param signal: Spike trace recording (vector)\n    :type signal: numpy array\n    :param threshold: Threshold value to determine spikes\n    :type threshold: float\n    :returns: float -- Time of peak of first spike, or None if no values over threshold\n\n    This is the same as the first value returned from calc_spike_times"
  },
  {
    "code": "def wrap_url(s, l):\n    parts = s.split('/')\n    if len(parts) == 1:\n        return parts[0]\n    else:\n        i = 0\n        lines = []\n        for j in range(i, len(parts) + 1):\n            tv = '/'.join(parts[i:j])\n            nv = '/'.join(parts[i:j + 1])\n            if len(nv) > l or nv == tv:\n                i = j\n                lines.append(tv)\n        return '/\\n'.join(lines)",
    "docstring": "Wrap a URL string"
  },
  {
    "code": "def limiter(arr):\n    dyn_range = 32767.0 / 32767.0\n    lim_thresh = 30000.0 / 32767.0\n    lim_range = dyn_range - lim_thresh\n    new_arr = arr.copy()\n    inds = N.where(arr > lim_thresh)[0]\n    new_arr[inds] = (new_arr[inds] - lim_thresh) / lim_range\n    new_arr[inds] = (N.arctan(new_arr[inds]) * 2.0 / N.pi) *\\\n        lim_range + lim_thresh\n    inds = N.where(arr < -lim_thresh)[0]\n    new_arr[inds] = -(new_arr[inds] + lim_thresh) / lim_range\n    new_arr[inds] = -(\n        N.arctan(new_arr[inds]) * 2.0 / N.pi * lim_range + lim_thresh)\n    return new_arr",
    "docstring": "Restrict the maximum and minimum values of arr"
  },
  {
    "code": "def get_parent_until(path):\n    dirname = osp.dirname(path)\n    try:\n        mod = osp.basename(path)\n        mod = osp.splitext(mod)[0]\n        imp.find_module(mod, [dirname])\n    except ImportError:\n        return\n    items = [mod]\n    while 1:\n        items.append(osp.basename(dirname))\n        try:\n            dirname = osp.dirname(dirname)\n            imp.find_module('__init__', [dirname + os.sep])\n        except ImportError:\n            break\n    return '.'.join(reversed(items))",
    "docstring": "Given a file path, determine the full module path.\n\n    e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields\n    'numpy.core'"
  },
  {
    "code": "def groups_invite(self, *, channel: str, user: str, **kwargs) -> SlackResponse:\n        self._validate_xoxp_token()\n        kwargs.update({\"channel\": channel, \"user\": user})\n        return self.api_call(\"groups.invite\", json=kwargs)",
    "docstring": "Invites a user to a private channel.\n\n        Args:\n            channel (str): The group id. e.g. 'G1234567890'\n            user (str): The user id. e.g. 'U1234567890'"
  },
  {
    "code": "def add_entry(self, entry):\n        self.entry_keys.setdefault(entry, [])\n        self.entries.append(entry)\n        for dist in find_distributions(entry, True):\n            self.add(dist, entry, False)",
    "docstring": "Add a path item to ``.entries``, finding any distributions on it\n\n        ``find_distributions(entry, True)`` is used to find distributions\n        corresponding to the path entry, and they are added.  `entry` is\n        always appended to ``.entries``, even if it is already present.\n        (This is because ``sys.path`` can contain the same value more than\n        once, and the ``.entries`` of the ``sys.path`` WorkingSet should always\n        equal ``sys.path``.)"
  },
  {
    "code": "def get_snapshot_by(self, volume_id_or_uri, field, value):\n        uri = self.__build_volume_snapshot_uri(volume_id_or_uri)\n        return self._client.get_by(field, value, uri=uri)",
    "docstring": "Gets all snapshots that match the filter.\n\n        The search is case-insensitive.\n\n        Args:\n            volume_id_or_uri: Can be either the volume id or the volume uri.\n            field: Field name to filter.\n            value: Value to filter.\n\n        Returns:\n            list: Snapshots"
  },
  {
    "code": "def shuffled_batches(self, batch_size):\n        if batch_size >= self.num_envs * self.num_steps:\n            yield self\n        else:\n            rollouts_in_batch = batch_size // self.num_steps\n            batch_splits = math_util.divide_ceiling(self.num_envs, rollouts_in_batch)\n            indices = list(range(self.num_envs))\n            np.random.shuffle(indices)\n            for sub_indices in np.array_split(indices, batch_splits):\n                yield Trajectories(\n                    num_steps=self.num_steps,\n                    num_envs=len(sub_indices),\n                    environment_information=None,\n                    transition_tensors={k: x[:, sub_indices] for k, x in self.transition_tensors.items()},\n                    rollout_tensors={k: x[sub_indices] for k, x in self.rollout_tensors.items()},\n                )",
    "docstring": "Generate randomized batches of data - only sample whole trajectories"
  },
  {
    "code": "def get_encoder_settings(self):\n        if self.lame_header is None:\n            return u\"\"\n        return self.lame_header.guess_settings(*self.lame_version)",
    "docstring": "Returns the guessed encoder settings"
  },
  {
    "code": "def saveShp(self, target):\r\n        if not hasattr(target, \"write\"):\r\n            target = os.path.splitext(target)[0] + '.shp'\r\n        if not self.shapeType:\r\n            self.shapeType = self._shapes[0].shapeType\r\n        self.shp = self.__getFileObj(target)\r\n        self.__shapefileHeader(self.shp, headerType='shp')\r\n        self.__shpRecords()",
    "docstring": "Save an shp file."
  },
  {
    "code": "def terminate(self):\n        for process in list(self.processes):\n            process[\"subprocess\"].send_signal(signal.SIGTERM)\n        self.stop_watch()",
    "docstring": "Terminates the processes right now with a SIGTERM"
  },
  {
    "code": "def get_maintainer(self):\n        return hdx.data.user.User.read_from_hdx(self.data['maintainer'], configuration=self.configuration)",
    "docstring": "Get the dataset's maintainer.\n\n         Returns:\n             User: Dataset's maintainer"
  },
  {
    "code": "def copy_entities(from_namespace, from_workspace, to_namespace,\n                  to_workspace, etype, enames, link_existing_entities=False):\n    uri = \"workspaces/{0}/{1}/entities/copy\".format(to_namespace, to_workspace)\n    body = {\n        \"sourceWorkspace\": {\n            \"namespace\": from_namespace,\n            \"name\": from_workspace\n        },\n        \"entityType\": etype,\n        \"entityNames\": enames\n    }\n    return __post(uri, json=body, params={'linkExistingEntities':\n                                          str(link_existing_entities).lower()})",
    "docstring": "Copy entities between workspaces\n\n    Args:\n        from_namespace (str): project (namespace) to which source workspace belongs\n        from_workspace (str): Source workspace name\n        to_namespace (str): project (namespace) to which target workspace belongs\n        to_workspace (str): Target workspace name\n        etype (str): Entity type\n        enames (list(str)): List of entity names to copy\n        link_existing_entities (boolean): Link all soft conflicts to the entities that already exist.\n\n    Swagger:\n        https://api.firecloud.org/#!/Entities/copyEntities"
  },
  {
    "code": "def _read_incoming(self):\n        fileno = self.proc.stdout.fileno()\n        while 1:\n            buf = b''\n            try:\n                buf = os.read(fileno, 1024)\n            except OSError as e:\n                self._log(e, 'read')\n            if not buf:\n                self._read_queue.put(None)\n                return\n            self._read_queue.put(buf)",
    "docstring": "Run in a thread to move output from a pipe to a queue."
  },
  {
    "code": "def guard_rollback_to_open(worksheet):\n    for analysis in worksheet.getAnalyses():\n        if api.get_review_status(analysis) in [\"assigned\"]:\n            return True\n    return False",
    "docstring": "Return whether 'rollback_to_receive' transition can be performed or not"
  },
  {
    "code": "def import_qt(glbls):\r\n    if 'QtCore' in glbls:\r\n        return\r\n    from projexui.qt import QtCore, QtGui, wrapVariant, uic\r\n    from projexui.widgets.xloggersplashscreen import XLoggerSplashScreen\r\n    glbls['QtCore'] = QtCore\r\n    glbls['QtGui'] = QtGui\r\n    glbls['wrapVariant'] = wrapVariant\r\n    glbls['uic'] = uic\r\n    glbls['XLoggerSplashScreen'] = XLoggerSplashScreen",
    "docstring": "Delayed qt loader."
  },
  {
    "code": "def cira_stretch(img, **kwargs):\n    LOG.debug(\"Applying the cira-stretch\")\n    def func(band_data):\n        log_root = np.log10(0.0223)\n        denom = (1.0 - log_root) * 0.75\n        band_data *= 0.01\n        band_data = band_data.clip(np.finfo(float).eps)\n        band_data = xu.log10(band_data)\n        band_data -= log_root\n        band_data /= denom\n        return band_data\n    return apply_enhancement(img.data, func)",
    "docstring": "Logarithmic stretch adapted to human vision.\n\n    Applicable only for visible channels."
  },
  {
    "code": "def _to_hours_mins_secs(time_taken):\n    mins, secs = divmod(time_taken, 60)\n    hours, mins = divmod(mins, 60)\n    return hours, mins, secs",
    "docstring": "Convert seconds to hours, mins, and seconds."
  },
  {
    "code": "def rtt_read(self, buffer_index, num_bytes):\n        buf = (ctypes.c_ubyte * num_bytes)()\n        bytes_read = self._dll.JLINK_RTTERMINAL_Read(buffer_index, buf, num_bytes)\n        if bytes_read < 0:\n            raise errors.JLinkRTTException(bytes_read)\n        return list(buf)[:bytes_read]",
    "docstring": "Reads data from the RTT buffer.\n\n        This method will read at most num_bytes bytes from the specified\n        RTT buffer. The data is automatically removed from the RTT buffer.\n        If there are not num_bytes bytes waiting in the RTT buffer, the\n        entire contents of the RTT buffer will be read.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          buffer_index (int): the index of the RTT buffer to read from\n          num_bytes (int): the maximum number of bytes to read\n\n        Returns:\n          A list of bytes read from RTT.\n\n        Raises:\n          JLinkRTTException if the underlying JLINK_RTTERMINAL_Read call fails."
  },
  {
    "code": "def review_metadata_csv_single_user(filedir, metadata, csv_in, n_headers):\n    try:\n        if not validate_metadata(filedir, metadata):\n            return False\n        for filename, file_metadata in metadata.items():\n            is_single_file_metadata_valid(file_metadata, None, filename)\n    except ValueError as e:\n        print_error(e)\n        return False\n    return True",
    "docstring": "Check validity of metadata for single user.\n\n    :param filedir: This field is the filepath of the directory whose csv\n        has to be made.\n    :param metadata: This field is the metadata generated from the\n        load_metadata_csv function.\n    :param csv_in: This field returns a reader object which iterates over the\n        csv.\n    :param n_headers: This field is the number of headers in the csv."
  },
  {
    "code": "def list_(runas=None):\n    rubies = []\n    output = _rvm(['list'], runas=runas)\n    if output:\n        regex = re.compile(r'^[= ]([*> ]) ([^- ]+)-([^ ]+) \\[ (.*) \\]')\n        for line in output.splitlines():\n            match = regex.match(line)\n            if match:\n                rubies.append([\n                    match.group(2), match.group(3), match.group(1) == '*'\n                ])\n    return rubies",
    "docstring": "List all rvm-installed rubies\n\n    runas\n        The user under which to run rvm. If not specified, then rvm will be run\n        as the user under which Salt is running.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rvm.list"
  },
  {
    "code": "def pore_coords(target):\n    r\n    network = target.project.network\n    Ts = network.throats(target.name)\n    conns = network['throat.conns']\n    coords = network['pore.coords']\n    return _sp.mean(coords[conns], axis=1)[Ts]",
    "docstring": "r\"\"\"\n    The average of the pore coords"
  },
  {
    "code": "def parse(filename):\n    with open(filename) as f:\n        parser = ASDLParser()\n        return parser.parse(f.read())",
    "docstring": "Parse ASDL from the given file and return a Module node describing it."
  },
  {
    "code": "def get_layer(self):\n        if self.layer:\n            return\n        try:\n            self.layer = Layer.objects.get(slug=self.kwargs['slug'])\n        except Layer.DoesNotExist:\n            raise Http404(_('Layer not found'))",
    "docstring": "retrieve layer from DB"
  },
  {
    "code": "def nextClass(self, classuri):\n        if classuri == self.classes[-1].uri:\n            return self.classes[0]\n        flag = False\n        for x in self.classes:\n            if flag == True:\n                return x\n            if x.uri == classuri:\n                flag = True\n        return None",
    "docstring": "Returns the next class in the list of classes. If it's the last one, returns the first one."
  },
  {
    "code": "def _compute_hamming_matrix(N):\n    possible_states = np.array(list(utils.all_states((N))))\n    return cdist(possible_states, possible_states, 'hamming') * N",
    "docstring": "Compute and store a Hamming matrix for |N| nodes.\n\n    Hamming matrices have the following sizes::\n\n        N   MBs\n        ==  ===\n        9   2\n        10  8\n        11  32\n        12  128\n        13  512\n\n    Given these sizes and the fact that large matrices are needed infrequently,\n    we store computed matrices using the Joblib filesystem cache instead of\n    adding computed matrices to the ``_hamming_matrices`` global and clogging\n    up memory.\n\n    This function is only called when |N| >\n    ``_NUM_PRECOMPUTED_HAMMING_MATRICES``. Don't call this function directly;\n    use |_hamming_matrix| instead."
  },
  {
    "code": "def wsp(word):\n    HEAVY = r'[ieaAoO]{1}[\\.]*(u|y)[^ieaAoO]+(\\.|$)'\n    delimiters = [i for i, char in enumerate(word) if char == '.']\n    if len(delimiters) % 2 != 0:\n        delimiters.append(len(word))\n    unstressed = []\n    for i, d in enumerate(delimiters):\n        if i % 2 == 0:\n            unstressed.extend(range(d + 1, delimiters[i + 1]))\n    heavies = re.finditer(HEAVY, word)\n    violations = sum(1 for m in heavies if m.start(0) in unstressed)\n    return violations",
    "docstring": "Return the number of unstressed heavy syllables."
  },
  {
    "code": "def add_and_matches(self, matcher, lhs, params, numq=1, flatten=None):\n        params = self._adapt_params(params)\n        qs = ['?'] * numq\n        flatten = flatten or self._default_flatten(numq)\n        expr = repeat(adapt_matcher(matcher)(lhs, *qs), len(params))\n        self.conditions.extend(expr)\n        self.params.extend(flatten(params))",
    "docstring": "Add AND conditions to match to `params`.\n\n        :type matcher: str or callable\n        :arg  matcher: if `str`, `matcher.format` is used.\n        :type     lhs: str\n        :arg      lhs: the first argument to `matcher`.\n        :type  params: list\n        :arg   params: each element should be able to feed into sqlite '?'.\n        :type    numq: int\n        :arg     numq: number of parameters for each condition.\n        :type flatten: None or callable\n        :arg  flatten: when `numq > 1`, it should return a list of\n                       length `numq * len(params)`."
  },
  {
    "code": "def readall(self):\n        if not self._open:\n            raise pycdlibexception.PyCdlibInvalidInput('I/O operation on closed file.')\n        readsize = self._length - self._offset\n        if readsize > 0:\n            data = self._fp.read(readsize)\n            self._offset += readsize\n        else:\n            data = b''\n        return data",
    "docstring": "A method to read and return the remaining bytes in the file.\n\n        Parameters:\n         None.\n        Returns:\n         The rest of the data left in the file.  If the file is at or past EOF,\n         returns an empty bytestring."
  },
  {
    "code": "def load_module(self, name):\n        if name not in sys.modules:\n            sys.modules[name] = getattr(maps, name.split('.')[2])\n        return sys.modules[name]",
    "docstring": "Load the ``pygal.maps.name`` module from the previously\n        loaded plugin"
  },
  {
    "code": "def _reserve(self, key):\n        self.assign(key, RESERVED)\n        try:\n            yield\n        finally:\n            del self._cache[key]",
    "docstring": "Reserve a component's binding temporarily.\n\n        Protects against cycles."
  },
  {
    "code": "def update_constants():\n    global MANAGER_CONTROL_CHANNEL, MANAGER_EXECUTOR_CHANNELS\n    global MANAGER_LISTENER_STATS, MANAGER_STATE_PREFIX\n    redis_prefix = getattr(settings, 'FLOW_MANAGER', {}).get('REDIS_PREFIX', '')\n    MANAGER_CONTROL_CHANNEL = '{}.control'.format(redis_prefix)\n    MANAGER_EXECUTOR_CHANNELS = ManagerChannelPair(\n        '{}.result_queue'.format(redis_prefix),\n        '{}.result_queue_response'.format(redis_prefix),\n    )\n    MANAGER_STATE_PREFIX = '{}.state'.format(redis_prefix)\n    MANAGER_LISTENER_STATS = '{}.listener_stats'.format(redis_prefix)",
    "docstring": "Recreate channel name constants with changed settings.\n\n    This kludge is mostly needed due to the way Django settings are\n    patched for testing and how modules need to be imported throughout\n    the project. On import time, settings are not patched yet, but some\n    of the code needs static values immediately. Updating functions such\n    as this one are then needed to fix dummy values."
  },
  {
    "code": "def _exprcomp(node):\n    try:\n        comp = _LITS[node.data()]\n    except KeyError:\n        comp = _LITS[node.data()] = Complement(node)\n    return comp",
    "docstring": "Return a unique Expression complement."
  },
  {
    "code": "def zero_weight_obs_names(self):\n        self.observation_data.index = self.observation_data.obsnme\n        groups = self.observation_data.groupby(\n                self.observation_data.weight.apply(lambda x: x==0.0)).groups\n        if True in groups:\n            return list(self.observation_data.loc[groups[True],\"obsnme\"])\n        else:\n            return []",
    "docstring": "get the zero-weighted observation names\n\n        Returns\n        -------\n         zero_weight_obs_names : list\n             a list of zero-weighted observation names"
  },
  {
    "code": "def focusOutEvent(self, ev):\n        Kittens.widgets.ClickableTreeWidget.focusOutEvent(self, ev)\n        wid = QApplication.focusWidget()\n        while wid:\n            if wid is self:\n                return\n            wid = wid.parent()\n        self._startOrStopEditing()",
    "docstring": "Redefine focusOut events to stop editing"
  },
  {
    "code": "def _server_rollback():\n    from os import path, remove\n    archpath = path.abspath(path.expanduser(settings.archfile))\n    if path.isfile(archpath) and not args[\"nolive\"]:\n        vms(\"Removing archive JSON file at {}.\".format(archpath))\n        remove(archpath)\n    datapath = path.abspath(path.expanduser(settings.datafile))\n    if path.isfile(datapath) and not args[\"nolive\"]:\n        vms(\"Removing script database JSON file at {}\".format(datapath))\n        remove(datapath)",
    "docstring": "Removes script database and archive files to rollback the CI server\n    installation."
  },
  {
    "code": "def get_cat_model(model):\n    try:\n        if isinstance(model, string_types):\n            model_class = apps.get_model(*model.split(\".\"))\n        elif issubclass(model, CategoryBase):\n            model_class = model\n        if model_class is None:\n            raise TypeError\n    except TypeError:\n        raise TemplateSyntaxError(\"Unknown model submitted: %s\" % model)\n    return model_class",
    "docstring": "Return a class from a string or class"
  },
  {
    "code": "def _record_last_active(self, host):\n        if host in self.hosts:\n            self.hosts = [host] + [h for h in self.hosts if h != host]\n            self._last_time_recorded_active = time.time()",
    "docstring": "Put host first in our host list, so we try it first next time\n\n        The implementation of get_active_namenode relies on this reordering."
  },
  {
    "code": "def autoinc(self):\n        if not self.get('autoinc_version'):\n            return\n        oldver = self['version']\n        newver = bump_version_tail(oldver)\n        config_path = self.filepath\n        temp_fd, temp_name = tempfile.mkstemp(\n                dir=os.path.dirname(config_path),\n                )\n        with open(config_path) as old:\n            with os.fdopen(temp_fd, 'w') as new:\n                for oldline in old:\n                    if oldline.startswith('version:'):\n                        new.write(\"version: '%s'\\n\" % newver)\n                        continue\n                    new.write(oldline)\n        log.info('Incrementing stack version %s -> %s' % (oldver, newver))\n        os.rename(temp_name, config_path)",
    "docstring": "Conditionally updates the stack version in the file associated with\n        this config.\n\n        This  handles both official releases (i.e. QA configs), and release\n        candidates.  Assumptions about version:\n\n            - Official release versions are MAJOR.minor, where MAJOR and minor\n              are both non-negative integers.  E.g.\n\n                2.9\n                2.10\n                2.11\n                3.0\n                3.1\n                3.2\n                etc...\n\n            - Release candidate versions are MAJOR.minor-rc.N, where MAJOR,\n              minor, and N are all non-negative integers.\n\n                3.5-rc.1\n                3.5-rc.2"
  },
  {
    "code": "def refresh_address_presence(self, address):\n        composite_presence = {\n            self._fetch_user_presence(uid)\n            for uid\n            in self._address_to_userids[address]\n        }\n        new_presence = UserPresence.UNKNOWN\n        for presence in UserPresence.__members__.values():\n            if presence in composite_presence:\n                new_presence = presence\n                break\n        new_address_reachability = USER_PRESENCE_TO_ADDRESS_REACHABILITY[new_presence]\n        if new_address_reachability == self._address_to_reachability.get(address):\n            return\n        log.debug(\n            'Changing address presence state',\n            current_user=self._user_id,\n            address=to_normalized_address(address),\n            prev_state=self._address_to_reachability.get(address),\n            state=new_address_reachability,\n        )\n        self._address_to_reachability[address] = new_address_reachability\n        self._address_reachability_changed_callback(address, new_address_reachability)",
    "docstring": "Update synthesized address presence state from cached user presence states.\n\n        Triggers callback (if any) in case the state has changed.\n\n        This method is only provided to cover an edge case in our use of the Matrix protocol and\n        should **not** generally be used."
  },
  {
    "code": "def db_value(self, value):\n        if isinstance(value, string_types):\n            value = arrow.get(value)\n        if isinstance(value, arrow.Arrow):\n            value = value.datetime\n        return super(ArrowDateTimeField, self).db_value(value)",
    "docstring": "Convert the Arrow instance to a datetime for saving in the db."
  },
  {
    "code": "def _count(self, method, limit, keywords):\n        limit = limit.copy()\n        has_more = True\n        count = None\n        while has_more:\n            limit.set_request_args(keywords)\n            response = self.call(method, **keywords)\n            limit.post_fetch(response)\n            count += Count.from_response(response)\n            last_evaluated_key = response.get('LastEvaluatedKey')\n            has_more = last_evaluated_key is not None and not limit.complete\n            if has_more:\n                keywords['ExclusiveStartKey'] = last_evaluated_key\n        return count",
    "docstring": "Do a scan or query and aggregate the results into a Count"
  },
  {
    "code": "def getDatastreamHistory(self, pid, dsid, format=None):\n        http_args = {}\n        if format is not None:\n            http_args['format'] = format\n        uri = 'objects/%(pid)s/datastreams/%(dsid)s/history' % \\\n            {'pid': pid, 'dsid': dsid}\n        return self.get(uri, params=http_args)",
    "docstring": "Get history information for a datastream.\n\n        :param pid: object pid\n        :param dsid: datastream id\n        :param format: format\n        :rtype: :class:`requests.models.Response`"
  },
  {
    "code": "def _on_progress(adapter, operation, conn_id, done, total):\n    conn_string = adapter._get_property(conn_id, 'connection_string')\n    if conn_string is None:\n        return\n    adapter.notify_progress(conn_string, operation, done, total)",
    "docstring": "Callback when progress is reported."
  },
  {
    "code": "def get_lower_triangle_correlation_matrix(self, sites, imt):\n        return numpy.linalg.cholesky(self._get_correlation_matrix(sites, imt))",
    "docstring": "Get lower-triangle matrix as a result of Cholesky-decomposition\n        of correlation matrix.\n\n        The resulting matrix should have zeros on values above\n        the main diagonal.\n\n        The actual implementations of :class:`BaseCorrelationModel` interface\n        might calculate the matrix considering site collection and IMT (like\n        :class:`JB2009CorrelationModel` does) or might have it pre-constructed\n        for a specific site collection and IMT, in which case they will need\n        to make sure that parameters to this function match parameters that\n        were used to pre-calculate decomposed correlation matrix.\n\n        :param sites:\n            :class:`~openquake.hazardlib.site.SiteCollection` to create\n            correlation matrix for.\n        :param imt:\n            Intensity measure type object, see :mod:`openquake.hazardlib.imt`."
  },
  {
    "code": "def get_hyperedge_degree_matrix(M):\n    degrees = M.sum(0).transpose()\n    new_degree = []\n    for degree in degrees:\n        new_degree.append(int(degree[0:]))\n    return sparse.diags([new_degree], [0])",
    "docstring": "Creates the diagonal matrix of hyperedge degrees D_e as a sparse matrix,\n    where a hyperedge degree is the cardinality of the hyperedge.\n\n    :param M: the incidence matrix of the hypergraph to find the D_e matrix on.\n    :returns: sparse.csc_matrix -- the diagonal hyperedge degree matrix as a\n            sparse matrix."
  },
  {
    "code": "def _get_weight_size(self, data, n_local_subj):\n        weight_size = np.zeros(1).astype(int)\n        local_weight_offset = np.zeros(n_local_subj).astype(int)\n        for idx, subj_data in enumerate(data):\n            if idx > 0:\n                local_weight_offset[idx] = weight_size[0]\n            weight_size[0] += self.K * subj_data.shape[1]\n        return weight_size, local_weight_offset",
    "docstring": "Calculate the size of weight for this process\n\n        Parameters\n        ----------\n\n        data : a list of 2D array, each in shape [n_voxel, n_tr]\n            The fMRI data from multi-subject.\n\n        n_local_subj : int\n            Number of subjects allocated to this process.\n\n\n        Returns\n        -------\n\n        weight_size : 1D array\n            The size of total subject weight on this process.\n\n        local_weight_offset : 1D array\n            Number of elements away from the first element\n            in the combined weight array at which to begin\n            the new, segmented array for a subject"
  },
  {
    "code": "def make_big_empty_files(self):\n        for file_url in self.file_urls:\n            local_path = file_url.get_local_path(self.dest_directory)\n            with open(local_path, \"wb\") as outfile:\n                if file_url.size > 0:\n                    outfile.seek(int(file_url.size) - 1)\n                    outfile.write(b'\\0')",
    "docstring": "Write out a empty file so the workers can seek to where they should write and write their data."
  },
  {
    "code": "def set_metrics_params(self, enable=None, store_dir=None, restore=None, no_cores=None):\n        self._set('enable-metrics', enable, cast=bool)\n        self._set('metrics-dir', self._section.replace_placeholders(store_dir))\n        self._set('metrics-dir-restore', restore, cast=bool)\n        self._set('metrics-no-cores', no_cores, cast=bool)\n        return self._section",
    "docstring": "Sets basic Metrics subsystem params.\n\n        uWSGI metrics subsystem allows you to manage \"numbers\" from your apps.\n\n        When enabled, the subsystem configures a vast amount of metrics\n        (like requests per-core, memory usage, etc) but, in addition to this,\n        you can configure your own metrics, such as the number of active users or, say,\n        hits of a particular URL, as well as the memory consumption of your app or the whole server.\n\n        * http://uwsgi.readthedocs.io/en/latest/Metrics.html\n        * SNMP Integration - http://uwsgi.readthedocs.io/en/latest/Metrics.html#snmp-integration\n\n        :param bool enable: Enables the subsystem.\n\n        :param str|unicode store_dir: Directory to store metrics.\n            The metrics subsystem can expose all of its metrics in the form\n            of text files in a directory. The content of each file is the value\n            of the metric (updated in real time).\n\n            .. note:: Placeholders can be used to build paths, e.g.: {project_runtime_dir}/metrics/\n              See ``Section.project_name`` and ``Section.runtime_dir``.\n\n        :param bool restore: Restore previous metrics from ``store_dir``.\n            When you restart a uWSGI instance, all of its metrics are reset.\n            Use the option to force the metric subsystem to read-back the values\n            from the metric directory before starting to collect values.\n\n        :param bool no_cores: Disable generation of cores-related metrics."
  },
  {
    "code": "def get_or_generate_vocab(data_dir, tmp_dir, vocab_filename, vocab_size,\n                          sources, file_byte_budget=1e6,\n                          max_subtoken_length=None):\n  vocab_generator = generate_lines_for_vocab(tmp_dir, sources, file_byte_budget)\n  return get_or_generate_vocab_inner(data_dir, vocab_filename, vocab_size,\n                                     vocab_generator, max_subtoken_length)",
    "docstring": "Generate a vocabulary from the datasets in sources."
  },
  {
    "code": "def reverse(self, name, **kwargs):\n        for p, n, _ in self.endpoints:\n            if name == n:\n                return p.format(**kwargs)",
    "docstring": "Reverse routing.\n\n        >>> from kobin import Response\n        >>> r = Router()\n        >>> def view(user_id: int) -> Response:\n        ...     return Response(f'You are {user_id}')\n        ...\n        >>> r.add('/users/{user_id}', 'GET', 'user-detail', view)\n        >>> r.reverse('user-detail', user_id=1)\n        '/users/1'"
  },
  {
    "code": "def success(self):\n        return self.ack.upper() in (self.config.ACK_SUCCESS,\n                                    self.config.ACK_SUCCESS_WITH_WARNING)",
    "docstring": "Checks for the presence of errors in the response. Returns ``True`` if\n        all is well, ``False`` otherwise.\n\n        :rtype: bool\n        :returns ``True`` if PayPal says our query was successful."
  },
  {
    "code": "def convert_result(converter):\n    def decorate(fn):\n        @inspection.wraps(fn)\n        def new_fn(*args, **kwargs):\n            return converter(fn(*args, **kwargs))\n        return new_fn\n    return decorate",
    "docstring": "Decorator that can convert the result of a function call."
  },
  {
    "code": "def is_smart(self, value):\n        self.set_bool(\"is_smart\", value)\n        if value is True:\n            if self.find(\"criteria\") is None:\n                self.criteria = ElementTree.SubElement(self, \"criteria\")",
    "docstring": "Set group is_smart property to value.\n\n        Args:\n            value: Boolean."
  },
  {
    "code": "def half_cauchy_like(x, alpha, beta):\n    R\n    x = np.atleast_1d(x)\n    if sum(x.ravel() < 0):\n        return -inf\n    return flib.cauchy(x, alpha, beta) + len(x) * np.log(2)",
    "docstring": "R\"\"\"\n    Half-Cauchy log-likelihood. Simply the absolute value of Cauchy.\n\n    .. math::\n        f(x \\mid \\alpha, \\beta) = \\frac{2}{\\pi \\beta [1 + (\\frac{x-\\alpha}{\\beta})^2]}\n\n    :Parameters:\n      - `alpha` : Location parameter.\n      - `beta` : Scale parameter (beta > 0).\n\n    .. note::\n      - x must be non-negative."
  },
  {
    "code": "def _get_subtype_tags(self):\n        assert self.is_member_of_enumerated_subtypes_tree(), \\\n            'Not a part of a subtypes tree.'\n        cur = self.parent_type\n        cur_dt = self\n        tags = []\n        while cur:\n            assert cur.has_enumerated_subtypes()\n            for subtype_field in cur.get_enumerated_subtypes():\n                if subtype_field.data_type is cur_dt:\n                    tags.append(subtype_field.name)\n                    break\n            else:\n                assert False, 'Could not find?!'\n            cur_dt = cur\n            cur = cur.parent_type\n        tags.reverse()\n        return tuple(tags)",
    "docstring": "Returns a list of type tags that refer to this type starting from the\n        base of the struct hierarchy."
  },
  {
    "code": "def get_by_details(self, name, type, clazz):\n        entry = DNSEntry(name, type, clazz)\n        return self.get(entry)",
    "docstring": "Gets an entry by details.  Will return None if there is\n        no matching entry."
  },
  {
    "code": "def _hline_bokeh_(self, col):\n        c = hv.HLine(self.df[col].mean())\n        return c",
    "docstring": "Returns an horizontal line from a column mean value"
  },
  {
    "code": "def rate_slack(self, max_rate):\n        if self.fragment_type == self.REGULAR:\n            return -self.rate_lack(max_rate)\n        elif self.fragment_type == self.NONSPEECH:\n            return self.length\n        else:\n            return TimeValue(\"0.000\")",
    "docstring": "The maximum time interval that can be stolen to this fragment\n        while keeping it respecting the given max rate.\n\n        For ``REGULAR`` fragments this value is\n        the opposite of the ``rate_lack``.\n        For ``NONSPEECH`` fragments this value is equal to\n        the length of the fragment.\n        For ``HEAD`` and ``TAIL`` fragments this value is ``0.000``,\n        meaning that they cannot be stolen.\n\n        :param max_rate: the maximum rate (characters/second)\n        :type  max_rate: :class:`~aeneas.exacttiming.Decimal`\n        :rtype: :class:`~aeneas.exacttiming.TimeValue`\n\n        .. versionadded:: 1.7.0"
  },
  {
    "code": "def timedelta_average(*values: datetime.timedelta) -> datetime.timedelta:\n    r\n    if isinstance(values[0], (list, tuple)):\n        values = values[0]\n    return sum(values, datetime.timedelta()) // len(values)",
    "docstring": "r\"\"\"Compute the arithmetic mean for timedeltas list.\n\n    :param \\*values: Timedelta instances to process."
  },
  {
    "code": "def _guess_vc_legacy(self):\n        default = r'Microsoft Visual Studio %0.1f\\VC' % self.vc_ver\n        return os.path.join(self.ProgramFilesx86, default)",
    "docstring": "Locate Visual C for versions prior to 2017"
  },
  {
    "code": "def map(self, mapper: Callable[[Any], Any]) -> 'Observable':\n        r\n        source = self\n        return Observable(lambda on_next: source.subscribe(compose(on_next, mapper)))",
    "docstring": "r\"\"\"Map a function over an observable.\n\n        Haskell: fmap f m = Cont $ \\c -> runCont m (c . f)"
  },
  {
    "code": "def extract_archive(archive, verbosity=0, outdir=None, program=None, interactive=True):\n    util.check_existing_filename(archive)\n    if verbosity >= 0:\n        util.log_info(\"Extracting %s ...\" % archive)\n    return _extract_archive(archive, verbosity=verbosity, interactive=interactive, outdir=outdir, program=program)",
    "docstring": "Extract given archive."
  },
  {
    "code": "def _arguments_repr(self):\n        document_class_repr = (\n            'dict' if self.document_class is dict\n            else repr(self.document_class))\n        uuid_rep_repr = UUID_REPRESENTATION_NAMES.get(self.uuid_representation,\n                                                      self.uuid_representation)\n        return ('document_class=%s, tz_aware=%r, uuid_representation=%s, '\n                'unicode_decode_error_handler=%r, tzinfo=%r, '\n                'type_registry=%r' %\n                (document_class_repr, self.tz_aware, uuid_rep_repr,\n                 self.unicode_decode_error_handler, self.tzinfo,\n                 self.type_registry))",
    "docstring": "Representation of the arguments used to create this object."
  },
  {
    "code": "def mapper_metro(self, _, data):\n        if 'tags' in data:\n            type_tag = 1\n            lonlat = data['coordinates']\n            payload = data['tags']\n        elif 'user_id' in data:\n            type_tag = 2\n            accept = [\n                \"twitter\\.com\",\n                \"foursquare\\.com\",\n                \"instagram\\.com\",\n                \"untappd\\.com\"\n            ]\n            expr = \"|\".join(accept)\n            if not re.findall(expr, data['source']):\n                return\n            lonlat = data['lonlat']\n            payload = None\n        metro = self.lookup.get(lonlat, METRO_DISTANCE)\n        if not metro:\n            return\n        yield metro, (type_tag, lonlat, payload)",
    "docstring": "map each osm POI and geotweets based on spatial lookup of metro area"
  },
  {
    "code": "def check_valence(self):\n        return [x for x, atom in self.atoms() if not atom.check_valence(self.environment(x))]",
    "docstring": "check valences of all atoms\n\n        :return: list of invalid atoms"
  },
  {
    "code": "def to_kwargs(triangles):\n    triangles = np.asanyarray(triangles, dtype=np.float64)\n    if not util.is_shape(triangles, (-1, 3, 3)):\n        raise ValueError('Triangles must be (n,3,3)!')\n    vertices = triangles.reshape((-1, 3))\n    faces = np.arange(len(vertices)).reshape((-1, 3))\n    kwargs = {'vertices': vertices,\n              'faces': faces}\n    return kwargs",
    "docstring": "Convert a list of triangles to the kwargs for the Trimesh\n    constructor.\n\n    Parameters\n    ---------\n    triangles : (n, 3, 3) float\n      Triangles in space\n\n    Returns\n    ---------\n    kwargs : dict\n      Keyword arguments for the trimesh.Trimesh constructor\n      Includes keys 'vertices' and 'faces'\n\n    Examples\n    ---------\n    >>> mesh = trimesh.Trimesh(**trimesh.triangles.to_kwargs(triangles))"
  },
  {
    "code": "def enable_tracing(self, thread_trace_func=None):\n        if self.frame_eval_func is not None:\n            self.frame_eval_func()\n            pydevd_tracing.SetTrace(self.dummy_trace_dispatch)\n            return\n        if thread_trace_func is None:\n            thread_trace_func = self.get_thread_local_trace_func()\n        else:\n            self._local_thread_trace_func.thread_trace_func = thread_trace_func\n        pydevd_tracing.SetTrace(thread_trace_func)",
    "docstring": "Enables tracing.\n\n        If in regular mode (tracing), will set the tracing function to the tracing\n        function for this thread -- by default it's `PyDB.trace_dispatch`, but after\n        `PyDB.enable_tracing` is called with a `thread_trace_func`, the given function will\n        be the default for the given thread."
  },
  {
    "code": "def _CreateFeedMapping(client, feed_details):\n  feed_mapping_service = client.GetService('FeedMappingService',\n                                           version='v201809')\n  operation = {\n      'operand': {\n          'criterionType': DSA_PAGE_FEED_CRITERION_TYPE,\n          'feedId': feed_details.feed_id,\n          'attributeFieldMappings': [\n              {\n                  'feedAttributeId': feed_details.url_attribute_id,\n                  'fieldId': DSA_PAGE_URLS_FIELD_ID\n              },\n              {\n                  'feedAttributeId': feed_details.label_attribute_id,\n                  'fieldId': DSA_LABEL_FIELD_ID\n              }\n          ]\n      },\n      'operator': 'ADD'\n  }\n  feed_mapping_service.mutate([operation])",
    "docstring": "Creates the feed mapping for DSA page feeds.\n\n  Args:\n    client: an AdWordsClient instance.\n    feed_details: a _DSAFeedDetails instance."
  },
  {
    "code": "def add_to_package_numpy(self, root, ndarray, node_path, target, source_path, transform, custom_meta):\n        filehash = self.save_numpy(ndarray)\n        metahash = self.save_metadata(custom_meta)\n        self._add_to_package_contents(root, node_path, [filehash], target, source_path, transform, metahash)",
    "docstring": "Save a Numpy array to the store."
  },
  {
    "code": "def _reconnect(self):\n        if self.idle or self.closed:\n            LOGGER.debug('Attempting RabbitMQ reconnect in %s seconds',\n                         self.reconnect_delay)\n            self.io_loop.call_later(self.reconnect_delay, self.connect)\n            return\n        LOGGER.warning('Reconnect called while %s', self.state_description)",
    "docstring": "Schedule the next connection attempt if the class is not currently\n        closing."
  },
  {
    "code": "def workspace_backup_add(ctx):\n    backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))\n    backup_manager.add()",
    "docstring": "Create a new backup"
  },
  {
    "code": "def _atomicModification(func):\n        def wrapper(*args, **kwargs):\n            self = args[0]\n            with self._qpart:\n                func(*args, **kwargs)\n        return wrapper",
    "docstring": "Decorator\n        Make document modification atomic"
  },
  {
    "code": "def dt_avg(self, print_output=True, output_file=\"dt_query.csv\"):\n        avg = self.dt.mean(axis=2)\n        if print_output:\n            np.savetxt(output_file, avg, delimiter=\",\")\n        return avg",
    "docstring": "Compute average document-topic matrix,\n        and print to file if print_output=True."
  },
  {
    "code": "def get_wrong_answer_ids(self):\n        id_list = []\n        for answer in self.get_wrong_answers():\n            id_list.append(answer.get_id())\n        return IdList(id_list)",
    "docstring": "provide this method to return only wrong answer ids"
  },
  {
    "code": "def parse_inline(self, text):\n        element_list = self._build_inline_element_list()\n        return inline_parser.parse(\n            text, element_list, fallback=self.inline_elements['RawText']\n        )",
    "docstring": "Parses text into inline elements.\n        RawText is not considered in parsing but created as a wrapper of holes\n        that don't match any other elements.\n\n        :param text: the text to be parsed.\n        :returns: a list of inline elements."
  },
  {
    "code": "def _serialize_rules(rules):\n    result = [(rule_name, str(rule)) for rule_name, rule in rules.items()]\n    return sorted(result, key=lambda rule: rule[0])",
    "docstring": "Serialize all the Rule object as string.\n\n    New string is used to compare the rules list."
  },
  {
    "code": "def add_selected(self, ):\n        browser = self.shot_browser if self.browser_tabw.currentIndex() == 1 else self.asset_browser\n        selelements = browser.selected_indexes(2)\n        if not selelements:\n            return\n        seltypes = browser.selected_indexes(3)\n        if not seltypes:\n            return\n        elementi = selelements[0]\n        typi = seltypes[0]\n        if not elementi.isValid() or not typi.isValid():\n            return\n        element = elementi.internalPointer().internal_data()\n        typ = typi.internalPointer().internal_data()[0]\n        reftrack.Reftrack(self.root, self.refobjinter, typ=typ, element=element)",
    "docstring": "Create a new reftrack with the selected element and type and add it to the root.\n\n        :returns: None\n        :rtype: None\n        :raises: NotImplementedError"
  },
  {
    "code": "def with_more_selectors(self, selectors):\n        if self.headers and self.headers[-1].is_selector:\n            new_selectors = extend_unique(\n                self.headers[-1].selectors,\n                selectors)\n            new_headers = self.headers[:-1] + (\n                BlockSelectorHeader(new_selectors),)\n            return RuleAncestry(new_headers)\n        else:\n            new_headers = self.headers + (BlockSelectorHeader(selectors),)\n            return RuleAncestry(new_headers)",
    "docstring": "Return a new ancestry that also matches the given selectors.  No\n        nesting is done."
  },
  {
    "code": "def ensure_on():\n    if get_status() == 'not-running':\n        if config.dbserver.multi_user:\n            sys.exit('Please start the DbServer: '\n                     'see the documentation for details')\n        subprocess.Popen([sys.executable, '-m', 'openquake.server.dbserver',\n                          '-l', 'INFO'])\n        waiting_seconds = 30\n        while get_status() == 'not-running':\n            if waiting_seconds == 0:\n                sys.exit('The DbServer cannot be started after 30 seconds. '\n                         'Please check the configuration')\n            time.sleep(1)\n            waiting_seconds -= 1",
    "docstring": "Start the DbServer if it is off"
  },
  {
    "code": "def nested_dict_to_list(path, dic, exclusion=None):\n    result = []\n    exclusion = ['__self'] if exclusion is None else exclusion\n    for key, value in dic.items():\n        if not any([exclude in key for exclude in exclusion]):\n            if isinstance(value, dict):\n                aux = path + key + \"/\"\n                result.extend(nested_dict_to_list(aux, value))\n            else:\n                if path.endswith(\"/\"):\n                    path = path[:-1]\n                result.append([path, key, value])\n    return result",
    "docstring": "Transform nested dict to list"
  },
  {
    "code": "def build_annotation_dict_any_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate:\n    if not annotations:\n        return keep_edge_permissive\n    @edge_predicate\n    def annotation_dict_any_filter(edge_data: EdgeData) -> bool:\n        return _annotation_dict_any_filter(edge_data, query=annotations)\n    return annotation_dict_any_filter",
    "docstring": "Build an edge predicate that passes for edges whose data dictionaries match the given dictionary.\n\n    If the given dictionary is empty, will always evaluate to true.\n\n    :param annotations: The annotation query dict to match"
  },
  {
    "code": "def print_file_details_as_csv(self, fname, col_headers):\r\n        line = ''\r\n        qu = '\"'\r\n        d = ','\r\n        for fld in col_headers:\r\n            if fld == \"fullfilename\":\r\n                line = line + qu + fname + qu + d\r\n            if fld == \"name\":\r\n                line = line + qu + os.path.basename(fname) + qu + d\r\n            if fld == \"date\":\r\n                line = line + qu + self.GetDateAsString(fname) + qu + d\r\n            if fld == \"size\":\r\n                line = line + qu + self.get_size_as_string(fname) + qu + d\r\n            if fld == \"path\":\r\n                try:\r\n                    line = line + qu + os.path.dirname(fname) + qu + d\r\n                except IOError:\r\n                    line = line + qu + 'ERROR_PATH' + qu + d\r\n        return line",
    "docstring": "saves as csv format"
  },
  {
    "code": "def contracts_version_expects_deposit_limits(contracts_version: Optional[str]) -> bool:\n    if contracts_version is None:\n        return True\n    if contracts_version == '0.3._':\n        return False\n    return compare(contracts_version, '0.9.0') > -1",
    "docstring": "Answers whether TokenNetworkRegistry of the contracts_vesion needs deposit limits"
  },
  {
    "code": "def _reference_rmvs(self, removes):\n        print(\"\")\n        self.msg.template(78)\n        msg_pkg = \"package\"\n        if len(removes) > 1:\n            msg_pkg = \"packages\"\n        print(\"| Total {0} {1} removed\".format(len(removes), msg_pkg))\n        self.msg.template(78)\n        for pkg in removes:\n            if not GetFromInstalled(pkg).name():\n                print(\"| Package {0} removed\".format(pkg))\n            else:\n                print(\"| Package {0} not found\".format(pkg))\n        self.msg.template(78)\n        print(\"\")",
    "docstring": "Prints all removed packages"
  },
  {
    "code": "def iter_dialogs(\n            self, limit=None, *, offset_date=None, offset_id=0,\n            offset_peer=types.InputPeerEmpty(), ignore_migrated=False\n    ):\n        return _DialogsIter(\n            self,\n            limit,\n            offset_date=offset_date,\n            offset_id=offset_id,\n            offset_peer=offset_peer,\n            ignore_migrated=ignore_migrated\n        )",
    "docstring": "Returns an iterator over the dialogs, yielding 'limit' at most.\n        Dialogs are the open \"chats\" or conversations with other people,\n        groups you have joined, or channels you are subscribed to.\n\n        Args:\n            limit (`int` | `None`):\n                How many dialogs to be retrieved as maximum. Can be set to\n                ``None`` to retrieve all dialogs. Note that this may take\n                whole minutes if you have hundreds of dialogs, as Telegram\n                will tell the library to slow down through a\n                ``FloodWaitError``.\n\n            offset_date (`datetime`, optional):\n                The offset date to be used.\n\n            offset_id (`int`, optional):\n                The message ID to be used as an offset.\n\n            offset_peer (:tl:`InputPeer`, optional):\n                The peer to be used as an offset.\n\n            ignore_migrated (`bool`, optional):\n                Whether :tl:`Chat` that have ``migrated_to`` a :tl:`Channel`\n                should be included or not. By default all the chats in your\n                dialogs are returned, but setting this to ``True`` will hide\n                them in the same way official applications do.\n\n        Yields:\n            Instances of `telethon.tl.custom.dialog.Dialog`."
  },
  {
    "code": "def get_generic_subseq_3D(protein, cutoff, prop, condition):\n        if not protein.representative_structure:\n            log.error('{}: no representative structure, cannot search for subseq'.format(protein.id))\n            return {'subseq_len': 0, 'subseq': None, 'subseq_resnums': []}\n        subseq, subseq_resnums = protein.get_seqprop_subsequence_from_structchain_property(property_key=prop,\n                                                                                           property_value=cutoff,\n                                                                                           condition=condition,\n                                                                                           use_representatives=True,\n                                                                                           return_resnums=True) or (\n                                 None, [])\n        return {'subseq_len': len(subseq_resnums), 'subseq': subseq, 'subseq_resnums': subseq_resnums}",
    "docstring": "Get a subsequence from REPSEQ based on a property stored in REPSTRUCT.REPCHAIN.letter_annotations"
  },
  {
    "code": "def visit_ListComp(self, node: ast.ListComp) -> None:\n        if node in self._recomputed_values:\n            value = self._recomputed_values[node]\n            text = self._atok.get_text(node)\n            self.reprs[text] = value\n        self.generic_visit(node=node)",
    "docstring": "Represent the list comprehension by dumping its source code."
  },
  {
    "code": "def parse_iptables_rule(line):\n    bits = line.split()\n    definition = {}\n    key = None\n    args = []\n    not_arg = False\n    def add_args():\n        arg_string = ' '.join(args)\n        if key in IPTABLES_ARGS:\n            definition_key = (\n                'not_{0}'.format(IPTABLES_ARGS[key])\n                if not_arg\n                else IPTABLES_ARGS[key]\n            )\n            definition[definition_key] = arg_string\n        else:\n            definition.setdefault('extras', []).extend((key, arg_string))\n    for bit in bits:\n        if bit == '!':\n            if key:\n                add_args()\n                args = []\n                key = None\n            not_arg = True\n        elif bit.startswith('-'):\n            if key:\n                add_args()\n                args = []\n                not_arg = False\n            key = bit\n        else:\n            args.append(bit)\n    if key:\n        add_args()\n    if 'extras' in definition:\n        definition['extras'] = set(definition['extras'])\n    return definition",
    "docstring": "Parse one iptables rule. Returns a dict where each iptables code argument\n    is mapped to a name using IPTABLES_ARGS."
  },
  {
    "code": "def renderer_doc(*args):\n    renderers_ = salt.loader.render(__opts__, [])\n    docs = {}\n    if not args:\n        for func in six.iterkeys(renderers_):\n            docs[func] = renderers_[func].__doc__\n        return _strip_rst(docs)\n    for module in args:\n        if '*' in module or '.' in module:\n            for func in fnmatch.filter(renderers_, module):\n                docs[func] = renderers_[func].__doc__\n        else:\n            moduledot = module + '.'\n            for func in six.iterkeys(renderers_):\n                if func.startswith(moduledot):\n                    docs[func] = renderers_[func].__doc__\n    return _strip_rst(docs)",
    "docstring": "Return the docstrings for all renderers. Optionally, specify a renderer or a\n    function to narrow the selection.\n\n    The strings are aggregated into a single document on the master for easy\n    reading.\n\n    Multiple renderers can be specified.\n\n    .. versionadded:: 2015.5.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' sys.renderer_doc\n        salt '*' sys.renderer_doc cheetah\n        salt '*' sys.renderer_doc jinja json\n\n    Renderer names can be specified as globs.\n\n    .. code-block:: bash\n\n        salt '*' sys.renderer_doc 'c*' 'j*'"
  },
  {
    "code": "def _create_binary_trigger(trigger):\n    ops = {\n        0: \">\",\n        1: \"<\",\n        2: \">=\",\n        3: \"<=\",\n        4: \"==\",\n        5: 'always'\n    }\n    op_codes = {y: x for x, y in ops.items()}\n    source = 0\n    if isinstance(trigger, TrueTrigger):\n        op_code = op_codes['always']\n    elif isinstance(trigger, FalseTrigger):\n        raise ArgumentError(\"Cannot express a never trigger in binary descriptor\", trigger=trigger)\n    else:\n        op_code = op_codes[trigger.comp_string]\n        if trigger.use_count:\n            source = 1\n    return (op_code << 1) | source",
    "docstring": "Create an 8-bit binary trigger from an InputTrigger, TrueTrigger, FalseTrigger."
  },
  {
    "code": "def match(self, p_todo):\n        operand1 = self.value\n        operand2 = p_todo.priority() or 'ZZ'\n        return self.compare_operands(operand1, operand2)",
    "docstring": "Performs a match on a priority in the todo.\n\n        It gets priority from p_todo and compares it with user-entered\n        expression based on the given operator (default ==). It does that however\n        in reversed order to obtain more intuitive result. Example: (>B) will\n        match todos with priority (A).\n        Items without priority are designated with corresponding operand set to\n        'ZZ', because python doesn't allow NoneType() and str() comparisons."
  },
  {
    "code": "def _validate_file_format(self, file_format):\n        if file_format not in self.valid_file_formats:\n            raise InvalidFileFormatError(\n                \"{} is not a valid file format\".format(file_format)\n            )\n        return file_format",
    "docstring": "Validates file format, raising error if invalid."
  },
  {
    "code": "def from_json(cls, data, json_schema_class=None):\n        schema = cls.json_schema if json_schema_class is None else json_schema_class()\n        return schema.load(data)",
    "docstring": "JSON deserialization method that retrieves a genome instance from its json representation\n\n        If specific json schema is provided, it is utilized, and if not, a class specific is used"
  },
  {
    "code": "def upload_content(self, synchronous=True, **kwargs):\n        kwargs = kwargs.copy()\n        kwargs.update(self._server_config.get_client_kwargs())\n        response = client.post(self.path('upload_content'), **kwargs)\n        json = _handle_response(response, self._server_config, synchronous)\n        if json['status'] != 'success':\n            raise APIResponseError(\n                'Received error when uploading file {0} to repository {1}: {2}'\n                .format(kwargs.get('files'), self.id, json)\n            )\n        return json",
    "docstring": "Upload a file or files to the current repository.\n\n        Here is an example of how to upload content::\n\n            with open('my_content.rpm') as content:\n                repo.upload_content(files={'content': content})\n\n        This method accepts the same keyword arguments as Requests. As a\n        result, the following examples can be adapted for use here:\n\n        * `POST a Multipart-Encoded File`_\n        * `POST Multiple Multipart-Encoded Files`_\n\n        :param synchronous: What should happen if the server returns an HTTP\n            202 (accepted) status code? Wait for the task to complete if\n            ``True``. Immediately return the server's response otherwise.\n        :param kwargs: Arguments to pass to requests.\n        :returns: The server's response, with all JSON decoded.\n        :raises: ``requests.exceptions.HTTPError`` If the server responds with\n            an HTTP 4XX or 5XX message.\n        :raises nailgun.entities.APIResponseError: If the response has a status\n            other than \"success\".\n\n        .. _POST a Multipart-Encoded File:\n            http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file\n        .. _POST Multiple Multipart-Encoded Files:\n            http://docs.python-requests.org/en/latest/user/advanced/#post-multiple-multipart-encoded-files"
  },
  {
    "code": "def copy(self, deep=True):\n        from copy import copy, deepcopy\n        if deep:\n            return deepcopy(self)\n        else:\n            return copy(self)",
    "docstring": "Make a copy of this object\n\n        Parameters\n        ----------\n        deep : boolean, default True\n            Make a deep copy, i.e. also copy data\n\n        Returns\n        -------\n        copy : type of caller"
  },
  {
    "code": "def _parse_file():\n    file_name = path.join(\n        path.abspath(path.dirname(path.dirname(__file__))), 'config.json'\n    )\n    logger.info('loading configuration from file: %r', file_name)\n    try:\n        data = _read_file(file_name)\n    except FileNotFoundError:\n        logger.error('no configuration available, set FLASH_CONFIG or '\n                     'provide config.json')\n        exit()\n    for service in data.get('services', []):\n        for key, val in service.items():\n            if isinstance(val, str) and re.match(r'^\\$[A-Z_]+$', val):\n                env_val = getenv(val[1:])\n                if env_val is None:\n                    logger.warning('environment variable %r not found', val[1:])\n                service[key] = env_val or val\n    return data",
    "docstring": "Parse the config from a file.\n\n    Note:\n      Assumes any value that ``\"$LOOKS_LIKE_THIS\"`` in a service\n      definition refers to an environment variable, and attempts to get\n      it accordingly."
  },
  {
    "code": "def tmp(p_queue, host=None):\n    if host is not None:\n        return _path(_c.FSQ_TMP, root=_path(host, root=hosts(p_queue)))\n    return _path(p_queue, _c.FSQ_TMP)",
    "docstring": "Construct a path to the tmp dir for a queue"
  },
  {
    "code": "def _get_request_fields_from_parent(self):\n        if not self.parent:\n            return None\n        if not getattr(self.parent, 'request_fields'):\n            return None\n        if not isinstance(self.parent.request_fields, dict):\n            return None\n        return self.parent.request_fields.get(self.field_name)",
    "docstring": "Get request fields from the parent serializer."
  },
  {
    "code": "def release_subnet(self, cidr, direc):\n        if direc == 'in':\n            self.service_in_ip.release_subnet(cidr)\n        else:\n            self.service_out_ip.release_subnet(cidr)",
    "docstring": "Routine to release a subnet from the DB."
  },
  {
    "code": "def list(self, request):\n        max_items_per_page = getattr(self, 'max_per_page',\n                                      getattr(settings, 'AJAX_MAX_PER_PAGE', 100))\n        requested_items_per_page = request.POST.get(\"items_per_page\", 20)\n        items_per_page = min(max_items_per_page, requested_items_per_page)\n        current_page = request.POST.get(\"current_page\", 1)\n        if not self.can_list(request.user):\n            raise AJAXError(403, _(\"Access to this endpoint is forbidden\"))\n        objects = self.get_queryset(request)\n        paginator = Paginator(objects, items_per_page)\n        try:\n            page = paginator.page(current_page)\n        except PageNotAnInteger:\n            page = paginator.page(1)\n        except EmptyPage:\n            page = EmptyPageResult()\n        data = [encoder.encode(record) for record in page.object_list]\n        return EnvelopedResponse(data=data, metadata={'total': paginator.count})",
    "docstring": "List objects of a model. By default will show page 1 with 20 objects on it.\n\n        **Usage**::\n\n            params = {\"items_per_page\":10,\"page\":2} //all params are optional\n            $.post(\"/ajax/{app}/{model}/list.json\"),params)"
  },
  {
    "code": "def parse_skypos(ra, dec):\n    rval = make_val_float(ra)\n    dval = make_val_float(dec)\n    if rval is None:\n        rval, dval = radec_hmstodd(ra, dec)\n    return rval, dval",
    "docstring": "Function to parse RA and Dec input values and turn them into decimal\n    degrees\n\n    Input formats could be:\n        [\"nn\",\"nn\",\"nn.nn\"]\n        \"nn nn nn.nnn\"\n        \"nn:nn:nn.nn\"\n        \"nnH nnM nn.nnS\" or \"nnD nnM nn.nnS\"\n        nn.nnnnnnnn\n        \"nn.nnnnnnn\""
  },
  {
    "code": "def mfpt(totflux, pi, qminus):\n    r\n    return dense.tpt.mfpt(totflux, pi, qminus)",
    "docstring": "r\"\"\"Mean first passage time for reaction A to B.\n\n    Parameters\n    ----------\n    totflux : float\n        The total flux between reactant and product\n    pi : (M,) ndarray\n        Stationary distribution\n    qminus : (M,) ndarray\n        Backward comittor\n\n    Returns\n    -------\n    tAB : float\n        The mean first-passage time for the A to B reaction\n\n    See also\n    --------\n    rate\n\n    Notes\n    -----\n    Equal to the inverse rate, see [1].\n\n    References\n    ----------\n    .. [1] F. Noe, Ch. Schuette, E. Vanden-Eijnden, L. Reich and\n        T. Weikl: Constructing the Full Ensemble of Folding Pathways\n        from Short Off-Equilibrium Simulations.\n        Proc. Natl. Acad. Sci. USA, 106, 19011-19016 (2009)"
  },
  {
    "code": "def is_supported():\n    on_supported_platform = False\n    if salt.utils.platform.is_sunos():\n        on_supported_platform = True\n    elif salt.utils.platform.is_freebsd() and _check_retcode('kldstat -q -m zfs'):\n        on_supported_platform = True\n    elif salt.utils.platform.is_linux() and os.path.exists('/sys/module/zfs'):\n        on_supported_platform = True\n    elif salt.utils.platform.is_linux() and salt.utils.path.which('zfs-fuse'):\n        on_supported_platform = True\n    elif salt.utils.platform.is_darwin() and \\\n         os.path.exists('/Library/Extensions/zfs.kext') and \\\n         os.path.exists('/dev/zfs'):\n        on_supported_platform = True\n    return (salt.utils.path.which('zpool') and on_supported_platform) is True",
    "docstring": "Check the system for ZFS support"
  },
  {
    "code": "def write_temp_file(self, content, filename=None, mode='w'):\n        if filename is None:\n            filename = str(uuid.uuid4())\n        fqpn = os.path.join(self.tcex.default_args.tc_temp_path, filename)\n        with open(fqpn, mode) as fh:\n            fh.write(content)\n        return fqpn",
    "docstring": "Write content to a temporary file.\n\n        Args:\n            content (bytes|str): The file content. If passing binary data the mode needs to be set\n                to 'wb'.\n            filename (str, optional): The filename to use when writing the file.\n            mode (str, optional): The file write mode which could be either 'w' or 'wb'.\n\n        Returns:\n            str: Fully qualified path name for the file."
  },
  {
    "code": "def url_view(url_pattern, name=None, priority=None):\n    def meta_wrapper(func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            return func(*args, **kwargs)\n        wrapper.urljects_view = True\n        wrapper.url = url_pattern\n        wrapper.url_name = name or func.__name__\n        wrapper.url_priority = priority\n        return wrapper\n    return meta_wrapper",
    "docstring": "Decorator for registering functional views.\n    Meta decorator syntax has to be used in order to accept arguments.\n\n    This decorator does not really do anything that magical:\n\n    This:\n    >>> from urljects import U, url_view\n    >>> @url_view(U / 'my_view')\n    ... def my_view(request)\n    ...     pass\n\n    is equivalent to this:\n    >>> def my_view(request)\n    ...     pass\n    >>> my_view.urljects_view = True\n    >>> my_view.url = U / 'my_view'\n    >>> my_view.url_name = 'my_view'\n\n    Those view are then supposed to be used with ``view_include`` which will\n    register all views that have ``urljects_view`` set to ``True``.\n\n    :param url_pattern: regex or URLPattern or anything passable to url()\n    :param name: name of the view, __name__ will be used otherwise.\n    :param priority: priority of the view, the lower the better"
  },
  {
    "code": "def _get_meaning(value_pb, is_list=False):\n    meaning = None\n    if is_list:\n        if len(value_pb.array_value.values) == 0:\n            return None\n        all_meanings = [\n            _get_meaning(sub_value_pb) for sub_value_pb in value_pb.array_value.values\n        ]\n        unique_meanings = set(all_meanings)\n        if len(unique_meanings) == 1:\n            meaning = unique_meanings.pop()\n        else:\n            meaning = all_meanings\n    elif value_pb.meaning:\n        meaning = value_pb.meaning\n    return meaning",
    "docstring": "Get the meaning from a protobuf value.\n\n    :type value_pb: :class:`.entity_pb2.Value`\n    :param value_pb: The protobuf value to be checked for an\n                     associated meaning.\n\n    :type is_list: bool\n    :param is_list: Boolean indicating if the ``value_pb`` contains\n                    a list value.\n\n    :rtype: int\n    :returns: The meaning for the ``value_pb`` if one is set, else\n              :data:`None`. For a list value, if there are disagreeing\n              means it just returns a list of meanings. If all the\n              list meanings agree, it just condenses them."
  },
  {
    "code": "def find_element(driver, elem_path, by=CSS, timeout=TIMEOUT, poll_frequency=0.5):\n    wait = WebDriverWait(driver, timeout, poll_frequency)\n    return wait.until(EC.presence_of_element_located((by, elem_path)))",
    "docstring": "Find and return an element once located\n\n    find_element locates an element on the page, waiting\n    for up to timeout seconds. The element, when located,\n    is returned. If not located, a TimeoutException is raised.\n\n    Args:\n        driver (selenium webdriver or element): A driver or element\n        elem_path (str): String used to located the element\n        by (selenium By): Selenium By reference\n        timeout (int): Selenium Wait timeout, in seconds\n        poll_frequency (float): Selenium Wait polling frequency, in seconds\n\n    Returns:\n        element: Selenium element\n\n    Raises:\n        TimeoutException: Raised when target element isn't located"
  },
  {
    "code": "def exit_statistics(hostname, start_time, count_sent, count_received, min_time, avg_time, max_time, deviation):\n    end_time = datetime.datetime.now()\n    duration = end_time - start_time\n    duration_sec = float(duration.seconds * 1000)\n    duration_ms = float(duration.microseconds / 1000)\n    duration = duration_sec + duration_ms\n    package_loss = 100 - ((float(count_received) / float(count_sent)) * 100)\n    print(f'\\b\\b--- {hostname} ping statistics ---')\n    try:\n        print(f'{count_sent} packages transmitted, {count_received} received, {package_loss}% package loss, time {duration}ms')\n    except ZeroDivisionError:\n        print(f'{count_sent} packets transmitted, {count_received} received, 100% packet loss, time {duration}ms')\n    print(\n        'rtt min/avg/max/dev = %.2f/%.2f/%.2f/%.2f ms' % (\n            min_time.seconds*1000 + float(min_time.microseconds)/1000,\n            float(avg_time) / 1000,\n            max_time.seconds*1000 + float(max_time.microseconds)/1000,\n            float(deviation)\n        )\n    )",
    "docstring": "Print ping exit statistics"
  },
  {
    "code": "def _get_subelements(self, node):\n        items = node.find('rdf:Alt', self.NS)\n        if items is not None:\n            try:\n                return items[0].text\n            except IndexError:\n                return ''\n        for xmlcontainer, container, insertfn in XMP_CONTAINERS:\n            items = node.find('rdf:{}'.format(xmlcontainer), self.NS)\n            if items is None:\n                continue\n            result = container()\n            for item in items:\n                insertfn(result, item.text)\n            return result\n        return ''",
    "docstring": "Gather the sub-elements attached to a node\n\n        Gather rdf:Bag and and rdf:Seq into set and list respectively. For\n        alternate languages values, take the first language only for\n        simplicity."
  },
  {
    "code": "def _sigma_pi_midE(self, Tp):\n        m_p = self._m_p\n        Qp = (Tp - self._Tth) / m_p\n        multip = -6e-3 + 0.237 * Qp - 0.023 * Qp ** 2\n        return self._sigma_inel(Tp) * multip",
    "docstring": "Geant 4.10.0 model for 2 GeV < Tp < 5 GeV"
  },
  {
    "code": "def ts_stats_significance(ts, ts_stat_func, null_ts_func, B=1000, permute_fast=False):\n    stats_ts = ts_stat_func(ts)\n    if permute_fast:\n        null_ts = map(np.random.permutation, np.array([ts, ] * B))\n    else:\n        null_ts = np.vstack([null_ts_func(ts) for i in np.arange(0, B)])\n    stats_null_ts = np.vstack([ts_stat_func(nts) for nts in null_ts])\n    pvals = []\n    nums = []\n    for i in np.arange(0, len(stats_ts)):\n        num_samples = np.sum((stats_null_ts[:, i] >= stats_ts[i]))\n        nums.append(num_samples)\n        pval = num_samples / float(B)\n        pvals.append(pval)\n    return stats_ts, pvals, nums",
    "docstring": "Compute  the statistical significance of a test statistic at each point\n        of the time series."
  },
  {
    "code": "def breathe_identifier(self):\n        if self.kind == \"function\":\n            return \"{name}({parameters})\".format(\n                name=self.name,\n                parameters=\", \".join(self.parameters)\n            )\n        return self.name",
    "docstring": "The unique identifier for breathe directives.\n\n        .. note::\n\n            This method is currently assumed to only be called for nodes that are\n            in :data:`exhale.utils.LEAF_LIKE_KINDS` (see also\n            :func:`exhale.graph.ExhaleRoot.generateSingleNodeRST` where it is used).\n\n        **Return**\n\n            :class:`python:str`\n                Usually, this will just be ``self.name``.  However, for functions in\n                particular the signature must be included to distinguish overloads."
  },
  {
    "code": "def table(name=None, mode='create', use_cache=True, priority='interactive',\n            allow_large_results=False):\n    output = QueryOutput()\n    output._output_type = 'table'\n    output._table_name = name\n    output._table_mode = mode\n    output._use_cache = use_cache\n    output._priority = priority\n    output._allow_large_results = allow_large_results\n    return output",
    "docstring": "Construct a query output object where the result is a table\n\n    Args:\n      name: the result table name as a string or TableName; if None (the default), then a\n          temporary table will be used.\n      table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request\n          will fail if the table exists.\n      use_cache: whether to use past query results or ignore cache. Has no effect if destination is\n          specified (default True).\n      priority:one of 'batch' or 'interactive' (default). 'interactive' jobs should be scheduled\n          to run quickly but are subject to rate limits; 'batch' jobs could be delayed by as much\n          as three hours but are not rate-limited.\n      allow_large_results: whether to allow large results; i.e. compressed data over 100MB. This is\n          slower and requires a name to be specified) (default False)."
  },
  {
    "code": "def get_version(filename):\n    with open(filename) as in_fh:\n        for line in in_fh:\n            if line.startswith('__version__'):\n                return line.split('=')[1].strip()[1:-1]\n    raise ValueError(\"Cannot extract version from %s\" % filename)",
    "docstring": "Extract the package version"
  },
  {
    "code": "def load_notebook(fullname: str):\n    shell = InteractiveShell.instance()\n    path = fullname\n    with open(path, 'r', encoding='utf-8') as f:\n        notebook = read(f, 4)\n    mod = types.ModuleType(fullname)\n    mod.__file__ = path\n    mod.__dict__['get_ipython'] = get_ipython\n    sys.modules[fullname] = mod\n    save_user_ns = shell.user_ns\n    shell.user_ns = mod.__dict__\n    try:\n        for cell in notebook.cells:\n            if cell.cell_type == 'code':\n                try:\n                    ast.parse(cell.source)\n                except SyntaxError:\n                    continue\n                try:\n                    exec(cell.source, mod.__dict__)\n                except NameError:\n                    print(cell.source)\n                    raise\n    finally:\n        shell.user_ns = save_user_ns\n    return mod",
    "docstring": "Import a notebook as a module."
  },
  {
    "code": "def display_element_selected(self, f):\n        self._display_element_selected_func = f\n        @wraps(f)\n        def wrapper(*args, **kw):\n            self._flask_view_func(*args, **kw)\n        return f",
    "docstring": "Decorator routes Alexa Display.ElementSelected request to the wrapped view function.\n\n        @ask.display_element_selected\n        def eval_element():\n            return \"\", 200\n\n        The wrapped function is registered as the display_element_selected view function\n        and renders the response for requests.\n\n        Arguments:\n            f {function} -- display_element_selected view function"
  },
  {
    "code": "def file_w_create_directories(filepath):\n    dirname = os.path.dirname(filepath)\n    if dirname and dirname != os.path.curdir and not os.path.isdir(dirname):\n        os.makedirs(dirname)\n    return open(filepath, 'w')",
    "docstring": "Recursively create some directories if needed so that the directory where\n    @filepath must be written exists, then open it in \"w\" mode and return the\n    file object."
  },
  {
    "code": "def get_start_time(self):\n        start_time = c_double()\n        self.library.get_start_time.argtypes = [POINTER(c_double)]\n        self.library.get_start_time.restype = None\n        self.library.get_start_time(byref(start_time))\n        return start_time.value",
    "docstring": "returns start time"
  },
  {
    "code": "def duration(self):\n        self._duration = self.lib.iperf_get_test_duration(self._test)\n        return self._duration",
    "docstring": "The test duration in seconds."
  },
  {
    "code": "def sync_and_deploy_gateway(collector):\n    configuration = collector.configuration\n    aws_syncr = configuration['aws_syncr']\n    find_gateway(aws_syncr, configuration)\n    artifact = aws_syncr.artifact\n    aws_syncr.artifact = \"\"\n    sync(collector)\n    aws_syncr.artifact = artifact\n    deploy_gateway(collector)",
    "docstring": "Do a sync followed by deploying the gateway"
  },
  {
    "code": "def generate_key(block_size=32):\n        random_seq = os.urandom(block_size)\n        random_key = base64.b64encode(random_seq)\n        return random_key",
    "docstring": "Generate random key for ope cipher.\n\n        Parameters\n        ----------\n        block_size : int, optional\n            Length of random bytes.\n\n        Returns\n        -------\n        random_key : str\n            A random key for encryption.\n\n        Notes:\n        ------\n        Implementation follows https://github.com/pyca/cryptography"
  },
  {
    "code": "def save_proficiency(self, proficiency_form, *args, **kwargs):\n        if proficiency_form.is_for_update():\n            return self.update_proficiency(proficiency_form, *args, **kwargs)\n        else:\n            return self.create_proficiency(proficiency_form, *args, **kwargs)",
    "docstring": "Pass through to provider ProficiencyAdminSession.update_proficiency"
  },
  {
    "code": "def sort_resources(cls, request, resources, fail_enum, header_proto=None):\n        if not request.sorting:\n            return resources\n        value_handlers = cls._get_handler_set(request, fail_enum, header_proto)\n        def sorter(resource_a, resource_b):\n            for handler in value_handlers:\n                val_a, val_b = handler.get_sort_values(resource_a, resource_b)\n                if val_a < val_b:\n                    return handler.xform_result(-1)\n                if val_a > val_b:\n                    return handler.xform_result(1)\n            return 0\n        return sorted(resources, key=cmp_to_key(sorter))",
    "docstring": "Sorts a list of resources based on a list of sort controls\n\n        Args:\n            request (object): The parsed protobuf request object\n            resources (list of objects): The resources to be sorted\n            fail_enum (int, enum): The enum status to raise with invalid keys\n            header_proto(class): Class to decode a resources header\n\n        Returns:\n            list: The sorted list of resources"
  },
  {
    "code": "def generate_token(self):\n        response = self._make_request()\n        self.auth = response\n        self.token = response['token']",
    "docstring": "Make request in API to generate a token."
  },
  {
    "code": "def on_interesting_rts_change(self, new_global_rts, removed_global_rts):\n        if new_global_rts:\n            LOG.debug(\n                'Sending route_refresh to all neighbors that'\n                ' did not negotiate RTC capability.'\n            )\n            pm = self._core_service.peer_manager\n            pm.schedule_rr_to_non_rtc_peers()\n        if removed_global_rts:\n            LOG.debug(\n                'Cleaning up global tables as some interested RTs were removed'\n            )\n            self._clean_global_uninteresting_paths()",
    "docstring": "Update global tables as interested RTs changed.\n\n        Adds `new_rts` and removes `removed_rts` rt nlris. Does not check if\n        `new_rts` or `removed_rts` are already present. Schedules refresh\n        request to peers that do not participate in RTC address-family."
  },
  {
    "code": "def circular_pores(target, pore_diameter='pore.diameter',\n                   throat_diameter='throat.diameter',\n                   throat_centroid='throat.centroid'):\n    r\n    return spherical_pores(target=target, pore_diameter=pore_diameter,\n                           throat_diameter=throat_diameter)",
    "docstring": "r\"\"\"\n    Calculate the coordinates of throat endpoints, assuming circular pores.\n    This model accounts for the overlapping lens between pores and throats.\n\n    Parameters\n    ----------\n    target : OpenPNM Object\n        The object which this model is associated with. This controls the\n        length of the calculated array, and also provides access to other\n        necessary properties.\n\n    pore_diameter : string\n        Dictionary key of the pore diameter values.\n\n    throat_diameter : string\n        Dictionary key of the throat diameter values.\n\n    throat_centroid : string, optional\n        Dictionary key of the throat centroid values. See the notes.\n\n    Returns\n    -------\n    EP : dictionary\n        Coordinates of throat endpoints stored in Dict form. Can be accessed\n        via the dict keys 'head' and 'tail'.\n\n    Notes\n    -----\n    (1) This model should only be applied to ture 2D networks.\n\n    (2) By default, this model assumes that throat centroid and pore\n    coordinates are colinear. If that's not the case, such as in extracted\n    networks, `throat_centroid` could be passed as an optional argument, and\n    the model takes care of the rest."
  },
  {
    "code": "def do_diff(self, params):\n        count = 0\n        for count, (diff, path) in enumerate(self._zk.diff(params.path_a, params.path_b), 1):\n            if diff == -1:\n                self.show_output(\"-- %s\", path)\n            elif diff == 0:\n                self.show_output(\"-+ %s\", path)\n            elif diff == 1:\n                self.show_output(\"++ %s\", path)\n        if count == 0:\n            self.show_output(\"Branches are equal.\")",
    "docstring": "\\x1b[1mNAME\\x1b[0m\n        diff - Display the differences between two paths\n\n\\x1b[1mSYNOPSIS\\x1b[0m\n        diff <src> <dst>\n\n\\x1b[1mDESCRIPTION\\x1b[0m\n        The output is interpreted as:\n          -- means the znode is missing in /new-configs\n          ++ means the znode is new in /new-configs\n          +- means the znode's content differ between /configs and /new-configs\n\n\\x1b[1mEXAMPLES\\x1b[0m\n        > diff /configs /new-configs\n        -- service-x/hosts\n        ++ service-x/hosts.json\n        +- service-x/params"
  },
  {
    "code": "def config_keys(self, sortkey = False):\n        if sortkey:\n            items = sorted(self.items())\n        else:\n            items = self.items()\n        for k,v in items:\n            if isinstance(v, ConfigTree):\n                for k2 in v.config_keys(sortkey):\n                    yield k + '.' + k2\n            else:\n                yield k",
    "docstring": "Return all configuration keys in this node, including configurations on children nodes."
  },
  {
    "code": "def validate(data):\n    text = data.get('text')\n    if not isinstance(text, _string_types) or len(text) == 0:\n        raise ValueError('text field is required and should not be empty')\n    if 'markdown' in data and not type(data['markdown']) is bool:\n        raise ValueError('markdown field should be bool')\n    if 'attachments' in data:\n        if not isinstance(data['attachments'], (list, tuple)):\n            raise ValueError('attachments field should be list or tuple')\n        for attachment in data['attachments']:\n            if 'text' not in attachment and 'title' not in attachment:\n                raise ValueError('text or title is required in attachment')\n    return True",
    "docstring": "Validates incoming data\n\n    Args:\n        data(dict): the incoming data\n\n    Returns:\n        True if the data is valid\n\n    Raises:\n        ValueError: the data is not valid"
  },
  {
    "code": "def surface_measure(self, param):\n        scalar_out = (np.shape(param) == ())\n        param = np.array(param, dtype=float, copy=False, ndmin=1)\n        if self.check_bounds and not is_inside_bounds(param, self.params):\n            raise ValueError('`param` {} not in the valid range '\n                             '{}'.format(param, self.params))\n        if scalar_out:\n            return self.radius\n        else:\n            return self.radius * np.ones(param.shape)",
    "docstring": "Return the arc length measure at ``param``.\n\n        This is a constant function evaluating to `radius` everywhere.\n\n        Parameters\n        ----------\n        param : float or `array-like`\n            Parameter value(s) at which to evaluate.\n\n        Returns\n        -------\n        measure : float or `numpy.ndarray`\n            Constant value(s) of the arc length measure at ``param``.\n            If ``param`` is a single parameter, a float is returned,\n            otherwise an array of shape ``param.shape``.\n\n        See Also\n        --------\n        surface\n        surface_deriv\n\n        Examples\n        --------\n        The method works with a single parameter, resulting in a float:\n\n        >>> part = odl.uniform_partition(-np.pi / 2, np.pi / 2, 10)\n        >>> det = CircularDetector(part, axis=[1, 0], radius=2)\n        >>> det.surface_measure(0)\n        2.0\n        >>> det.surface_measure(np.pi / 2)\n        2.0\n\n        It is also vectorized, i.e., it can be called with multiple\n        parameters at once (or an n-dimensional array of parameters):\n\n        >>> det.surface_measure([0, np.pi / 2])\n        array([ 2.,  2.])\n        >>> det.surface_measure(np.zeros((4, 5))).shape\n        (4, 5)"
  },
  {
    "code": "def upload_path(instance, filename):\n    filename = filename.replace(\" \", \"_\")\n    filename = unicodedata.normalize('NFKD', filename).lower()\n    return os.path.join(str(timezone.now().date().isoformat()), filename)",
    "docstring": "Sanitize the user-provided file name, add timestamp for uniqness."
  },
  {
    "code": "def get_session(username, password, cookie_path=COOKIE_PATH, cache=True,\n                cache_expiry=300, cache_path=CACHE_PATH, driver='phantomjs'):\n    class USPSAuth(AuthBase):\n        def __init__(self, username, password, cookie_path, driver):\n            self.username = username\n            self.password = password\n            self.cookie_path = cookie_path\n            self.driver = driver\n        def __call__(self, r):\n            return r\n    session = requests.Session()\n    if cache:\n        session = requests_cache.core.CachedSession(cache_name=cache_path,\n                                                    expire_after=cache_expiry)\n    session.auth = USPSAuth(username, password, cookie_path, driver)\n    session.headers.update({'User-Agent': USER_AGENT})\n    if os.path.exists(cookie_path):\n        _LOGGER.debug(\"cookie found at: %s\", cookie_path)\n        session.cookies = _load_cookies(cookie_path)\n    else:\n        _login(session)\n    return session",
    "docstring": "Get session, existing or new."
  },
  {
    "code": "def _identity(self, *args, **kwargs):\n        LOCAL = 'local accounts'\n        EXT = 'external accounts'\n        data = dict()\n        data[LOCAL] = self._get_local_users(disabled=kwargs.get('disabled'))\n        data[EXT] = self._get_external_accounts(data[LOCAL].keys()) or 'N/A'\n        data['local groups'] = self._get_local_groups()\n        return data",
    "docstring": "Local users and groups.\n\n        accounts\n            Can be either 'local', 'remote' or 'all' (equal to \"local,remote\").\n            Remote accounts cannot be resolved on all systems, but only\n            those, which supports 'passwd -S -a'.\n\n        disabled\n            True (or False, default) to return only disabled accounts."
  },
  {
    "code": "def bulk_create(self, *args, **kwargs):\n        ret_val = super(ManagerUtilsQuerySet, self).bulk_create(*args, **kwargs)\n        post_bulk_operation.send(sender=self.model, model=self.model)\n        return ret_val",
    "docstring": "Overrides Django's bulk_create function to emit a post_bulk_operation signal when bulk_create\n        is finished."
  },
  {
    "code": "def get_actions(self, request):\n        actions = super(CertificateMixin, self).get_actions(request)\n        actions.pop('delete_selected', '')\n        return actions",
    "docstring": "Disable the \"delete selected\" admin action.\n\n        Otherwise the action is present even though has_delete_permission is False, it just doesn't\n        work."
  },
  {
    "code": "def square_off(series, time_delta=None, transition_seconds=1):\n    if time_delta:\n        if isinstance(time_delta, (int, float)):\n            time_delta = datetime.timedelta(0, time_delta)\n        new_times = series.index + time_delta\n    else:\n        diff = np.diff(series.index)\n        time_delta = np.append(diff, [diff[-1]])\n        new_times = series.index + time_delta\n        new_times = pd.DatetimeIndex(new_times) - datetime.timedelta(0, transition_seconds)\n    return pd.concat([series, pd.Series(series.values, index=new_times)]).sort_index()",
    "docstring": "Insert samples in regularly sampled data to produce stairsteps from ramps when plotted.\n\n    New samples are 1 second (1e9 ns) before each existing samples, to facilitate plotting and sorting\n\n    >>> square_off(pd.Series(range(3), index=pd.date_range('2014-01-01', periods=3, freq='15m')),\n    ...            time_delta=5.5)  # doctest: +NORMALIZE_WHITESPACE\n    2014-01-31 00:00:00           0\n    2014-01-31 00:00:05.500000    0\n    2015-04-30 00:00:00           1\n    2015-04-30 00:00:05.500000    1\n    2016-07-31 00:00:00           2\n    2016-07-31 00:00:05.500000    2\n    dtype: int64\n    >>> square_off(pd.Series(range(2), index=pd.date_range('2014-01-01', periods=2, freq='15min')),\n    ...            transition_seconds=2.5)  # doctest: +NORMALIZE_WHITESPACE\n    2014-01-01 00:00:00           0\n    2014-01-01 00:14:57.500000    0\n    2014-01-01 00:15:00           1\n    2014-01-01 00:29:57.500000    1\n    dtype: int64"
  },
  {
    "code": "def write(text, delay=0, restore_state_after=True, exact=None):\n    if exact is None:\n        exact = _platform.system() == 'Windows'\n    state = stash_state()\n    if exact:\n        for letter in text:\n            if letter in '\\n\\b':\n                send(letter)\n            else:\n                _os_keyboard.type_unicode(letter)\n            if delay: _time.sleep(delay)\n    else:\n        for letter in text:\n            try:\n                entries = _os_keyboard.map_name(normalize_name(letter))\n                scan_code, modifiers = next(iter(entries))\n            except (KeyError, ValueError):\n                _os_keyboard.type_unicode(letter)\n                continue\n            for modifier in modifiers:\n                press(modifier)\n            _os_keyboard.press(scan_code)\n            _os_keyboard.release(scan_code)\n            for modifier in modifiers:\n                release(modifier)\n            if delay:\n                _time.sleep(delay)\n    if restore_state_after:\n        restore_modifiers(state)",
    "docstring": "Sends artificial keyboard events to the OS, simulating the typing of a given\n    text. Characters not available on the keyboard are typed as explicit unicode\n    characters using OS-specific functionality, such as alt+codepoint.\n\n    To ensure text integrity, all currently pressed keys are released before\n    the text is typed, and modifiers are restored afterwards.\n\n    - `delay` is the number of seconds to wait between keypresses, defaults to\n    no delay.\n    - `restore_state_after` can be used to restore the state of pressed keys\n    after the text is typed, i.e. presses the keys that were released at the\n    beginning. Defaults to True.\n    - `exact` forces typing all characters as explicit unicode (e.g.\n    alt+codepoint or special events). If None, uses platform-specific suggested\n    value."
  },
  {
    "code": "def shutdown(opts):\n    log.debug('dummy proxy shutdown() called...')\n    DETAILS = _load_state()\n    if 'filename' in DETAILS:\n        os.unlink(DETAILS['filename'])",
    "docstring": "For this proxy shutdown is a no-op"
  },
  {
    "code": "def _diff_interface_lists(old, new):\n    diff = _diff_lists(old, new, _nics_equal)\n    macs = [nic.find('mac').get('address') for nic in diff['unchanged']]\n    for nic in diff['new']:\n        mac = nic.find('mac')\n        if mac.get('address') in macs:\n            nic.remove(mac)\n    return diff",
    "docstring": "Compare network interface definitions to extract the changes\n\n    :param old: list of ElementTree nodes representing the old interfaces\n    :param new: list of ElementTree nodes representing the new interfaces"
  },
  {
    "code": "def _project_eigenvectors(self):\n        self._p_eigenvectors = []\n        for vecs_q in self._eigenvectors:\n            p_vecs_q = []\n            for vecs in vecs_q.T:\n                p_vecs_q.append(np.dot(vecs.reshape(-1, 3),\n                                       self._projection_direction))\n            self._p_eigenvectors.append(np.transpose(p_vecs_q))\n        self._p_eigenvectors = np.array(self._p_eigenvectors)",
    "docstring": "Eigenvectors are projected along Cartesian direction"
  },
  {
    "code": "def setMAC(self, xEUI):\n        print '%s call setMAC' % self.port\n        address64 = ''\n        try:\n            if not xEUI:\n                address64 = self.mac\n            if not isinstance(xEUI, str):\n                address64 = self.__convertLongToString(xEUI)\n                if len(address64) < 16:\n                    address64 = address64.zfill(16)\n                    print address64\n            else:\n                address64 = xEUI\n            cmd = WPANCTL_CMD + 'setprop NCP:MACAddress %s' % address64\n            if self.__sendCommand(cmd)[0] != 'Fail':\n                self.mac = address64\n                return True\n            else:\n                return False\n        except Exception, e:\n            ModuleHelper.WriteIntoDebugLogger('setMAC() Error: ' + str(e))",
    "docstring": "set the extended addresss of Thread device\n\n        Args:\n            xEUI: extended address in hex format\n\n        Returns:\n            True: successful to set the extended address\n            False: fail to set the extended address"
  },
  {
    "code": "def _to_json_type(obj, classkey=None):\n    if isinstance(obj, dict):\n        data = {}\n        for (k, v) in obj.items():\n            data[k] = _to_json_type(v, classkey)\n        return data\n    elif hasattr(obj, \"_ast\"):\n        return _to_json_type(obj._ast())\n    elif hasattr(obj, \"__iter__\"):\n        return [_to_json_type(v, classkey) for v in obj]\n    elif hasattr(obj, \"__dict__\"):\n        data = dict([\n            (key, _to_json_type(value, classkey))\n            for key, value in obj.__dict__.iteritems()\n            if not callable(value) and not key.startswith('_')\n        ])\n        if classkey is not None and hasattr(obj, \"__class__\"):\n            data[classkey] = obj.__class__.__name__\n        return data\n    else:\n        return obj",
    "docstring": "Recursively convert the object instance into a valid JSON type."
  },
  {
    "code": "def _costfcn(self, x):\n        f = self._f(x)\n        df = self._df(x)\n        d2f = self._d2f(x)\n        return f, df, d2f",
    "docstring": "Evaluates the objective function, gradient and Hessian for OPF."
  },
  {
    "code": "def label(self, input_grid):\n        marked = self.find_local_maxima(input_grid)\n        marked = np.where(marked >= 0, 1, 0)\n        markers = splabel(marked)[0]\n        return markers",
    "docstring": "Labels input grid using enhanced watershed algorithm.\n\n        Args:\n            input_grid (numpy.ndarray): Grid to be labeled.\n\n        Returns:\n            Array of labeled pixels"
  },
  {
    "code": "def check_input_files(self,\n                          return_found=True,\n                          return_missing=True):\n        all_input_files = self.files.chain_input_files + self.sub_files.chain_input_files\n        return check_files(all_input_files, self._file_stage,\n                           return_found, return_missing)",
    "docstring": "Check if input files exist.\n\n        Parameters\n        ----------\n        return_found : list\n            A list with the paths of the files that were found.\n\n        return_missing : list\n            A list with the paths of the files that were missing.\n\n        Returns\n        -------\n        found : list\n            List of the found files, if requested, otherwise `None`\n\n        missing : list\n            List of the missing files, if requested, otherwise `None`"
  },
  {
    "code": "def _post_activity(self, activity, unserialize=True):\n        feed_url = \"{proto}://{server}/api/user/{username}/feed\".format(\n            proto=self._pump.protocol,\n            server=self._pump.client.server,\n            username=self._pump.client.nickname\n        )\n        data = self._pump.request(feed_url, method=\"POST\", data=activity)\n        if not data:\n            return False\n        if \"error\" in data:\n            raise PumpException(data[\"error\"])\n        if unserialize:\n            if \"target\" in data:\n                self.unserialize(data[\"target\"])\n            else:\n                if \"author\" not in data[\"object\"]:\n                    data[\"object\"][\"author\"] = data[\"actor\"]\n                for key in [\"to\", \"cc\", \"bto\", \"bcc\"]:\n                    if key not in data[\"object\"] and key in data:\n                        data[\"object\"][key] = data[key]\n                self.unserialize(data[\"object\"])\n        return True",
    "docstring": "Posts a activity to feed"
  },
  {
    "code": "def __getAvatar(self, web):\n        try:\n            self.avatar = web.find(\"img\", {\"class\": \"avatar\"})['src'][:-10]\n        except IndexError as error:\n            print(\"There was an error with the user \" + self.name)\n            print(error)\n        except AttributeError as error:\n            print(\"There was an error with the user \" + self.name)\n            print(error)",
    "docstring": "Scrap the avatar from a GitHub profile.\n\n        :param web: parsed web.\n        :type web: BeautifulSoup node."
  },
  {
    "code": "def get_output_margin(self, status=None):\n        margin = self.get_reserved_space() + self.get_prompt(self.prompt).count('\\n') + 1\n        if special.is_timing_enabled():\n            margin += 1\n        if status:\n            margin += 1 + status.count('\\n')\n        return margin",
    "docstring": "Get the output margin (number of rows for the prompt, footer and\n        timing message."
  },
  {
    "code": "def _save(self, url, path, data):\n        worker = self._workers[url]\n        path = self._paths[url]\n        if len(data):\n            try:\n                with open(path, 'wb') as f:\n                    f.write(data)\n            except Exception:\n                logger.error((url, path))\n        worker.finished = True\n        worker.sig_download_finished.emit(url, path)\n        worker.sig_finished.emit(worker, path, None)\n        self._get_requests.pop(url)\n        self._workers.pop(url)\n        self._paths.pop(url)",
    "docstring": "Save `data` of downloaded `url` in `path`."
  },
  {
    "code": "def etree_to_string(tree):\n        buff = BytesIO()\n        tree.write(buff, xml_declaration=True, encoding='UTF-8')\n        return buff.getvalue()",
    "docstring": "Creates string from lxml.etree.ElementTree with XML declaration and UTF-8 encoding.\n\n        :param tree: the instance of ElementTree\n        :return: the string of XML."
  },
  {
    "code": "def is_newer_file(a, b):\n    if not (op.exists(a) and op.exists(b)):\n        return False\n    am = os.stat(a).st_mtime\n    bm = os.stat(b).st_mtime\n    return am > bm",
    "docstring": "Check if the file a is newer than file b"
  },
  {
    "code": "def main():\n    try:\n        device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))\n        device.on_zone_fault += handle_zone_fault\n        device.on_zone_restore += handle_zone_restore\n        with device.open(baudrate=BAUDRATE):\n            last_update = time.time()\n            while True:\n                if time.time() - last_update > WAIT_TIME:\n                    last_update = time.time()\n                    device.fault_zone(TARGET_ZONE)\n                time.sleep(1)\n    except Exception as ex:\n        print('Exception:', ex)",
    "docstring": "Example application that periodically faults a virtual zone and then\n    restores it.\n\n    This is an advanced feature that allows you to emulate a virtual zone.  When\n    the AlarmDecoder is configured to emulate a zone expander we can fault and\n    restore those zones programmatically at will. These events can also be seen by\n    others, such as home automation platforms which allows you to connect other\n    devices or services and monitor them as you would any physical zone.\n\n    For example, you could connect a ZigBee device and receiver and fault or\n    restore it's zone(s) based on the data received.\n\n    In order for this to happen you need to perform a couple configuration steps:\n\n    1. Enable zone expander emulation on your AlarmDecoder device by hitting '!'\n       in a terminal and going through the prompts.\n    2. Enable the zone expander in your panel programming."
  },
  {
    "code": "def alarm_on_segfault(self, alarm):\n        self.register_alarm(alarm)\n        for alarm in listify(alarm):\n            self._set('alarm-segfault', alarm.alias, multi=True)\n        return self._section",
    "docstring": "Raise the specified alarm when the segmentation fault handler is executed.\n\n        Sends a backtrace.\n\n        :param AlarmType|list[AlarmType] alarm: Alarm."
  },
  {
    "code": "def add_host(self, host_id=None, host='localhost', port=6379,\n                 unix_socket_path=None, db=0, password=None,\n                 ssl=False, ssl_options=None):\n        if host_id is None:\n            raise RuntimeError('Host ID is required')\n        elif not isinstance(host_id, (int, long)):\n            raise ValueError('The host ID has to be an integer')\n        host_id = int(host_id)\n        with self._lock:\n            if host_id in self.hosts:\n                raise TypeError('Two hosts share the same host id (%r)' %\n                                (host_id,))\n            self.hosts[host_id] = HostInfo(host_id=host_id, host=host,\n                                           port=port, db=db,\n                                           unix_socket_path=unix_socket_path,\n                                           password=password, ssl=ssl,\n                                           ssl_options=ssl_options)\n            self._hosts_age += 1",
    "docstring": "Adds a new host to the cluster.  This is only really useful for\n        unittests as normally hosts are added through the constructor and\n        changes after the cluster has been used for the first time are\n        unlikely to make sense."
  },
  {
    "code": "async def tile(tile_number):\n    try:\n        tile = get_tile(tile_number)\n    except TileOutOfBoundsError:\n        abort(404)\n    buf = BytesIO(tile.tobytes())\n    tile.save(buf, 'JPEG')\n    content = buf.getvalue()\n    response = await make_response(content)\n    response.headers['Content-Type'] = 'image/jpg'\n    response.headers['Accept-Ranges'] = 'bytes'\n    response.headers['Content-Length'] = str(len(content))\n    return response",
    "docstring": "Handles GET requests for a tile number.\n\n    :param int tile_number: Number of the tile between 0 and `max_tiles`^2.\n    :raises HTTPError: 404 if tile exceeds `max_tiles`^2."
  },
  {
    "code": "def check_fieldsets(*args, **kwargs):\n    if hasattr(settings, \"CONFIG_FIELDSETS\") and settings.CONFIG_FIELDSETS:\n        inconsistent_fieldnames = get_inconsistent_fieldnames()\n        if inconsistent_fieldnames:\n            return [\n                checks.Warning(\n                    _(\n                        \"CONSTANCE_CONFIG_FIELDSETS is missing \"\n                        \"field(s) that exists in CONSTANCE_CONFIG.\"\n                    ),\n                    hint=\", \".join(sorted(inconsistent_fieldnames)),\n                    obj=\"settings.CONSTANCE_CONFIG\",\n                    id=\"constance.E001\",\n                )\n            ]\n    return []",
    "docstring": "A Django system check to make sure that, if defined, CONFIG_FIELDSETS accounts for\n    every entry in settings.CONFIG."
  },
  {
    "code": "def load_fixture(self, body, attachment_bodies={}):\n        doc = json.loads(body)\n        self._documents[doc['_id']] = doc\n        self._attachments[doc['_id']] = dict()\n        for name in doc.get('_attachments', list()):\n            attachment_body = attachment_bodies.get(name, 'stub')\n            self._attachments[doc['_id']][name] = attachment_body",
    "docstring": "Loads the document into the database from json string. Fakes the\n        attachments if necessary."
  },
  {
    "code": "def operator_complexity(self):\n        return sum([level.A.nnz for level in self.levels]) /\\\n            float(self.levels[0].A.nnz)",
    "docstring": "Operator complexity of this multigrid hierarchy.\n\n        Defined as:\n            Number of nonzeros in the matrix on all levels /\n            Number of nonzeros in the matrix on the finest level"
  },
  {
    "code": "def _set_implied_name(self):\n\t\t\"Allow the name of this handler to default to the function name.\"\n\t\tif getattr(self, 'name', None) is None:\n\t\t\tself.name = self.func.__name__\n\t\tself.name = self.name.lower()",
    "docstring": "Allow the name of this handler to default to the function name."
  },
  {
    "code": "def validate_number(self, number):\n        if not isinstance(number, str):\n            raise ElksException('Recipient phone number may not be empty')\n        if number[0] == '+' and len(number) > 2 and len(number) < 16:\n            return True\n        else:\n            raise ElksException(\"Phone number must be of format +CCCXXX...\")",
    "docstring": "Checks if a number looks somewhat like a E.164 number. Not an\n        exhaustive check, as the API takes care of that"
  },
  {
    "code": "def cmServiceRequest(PriorityLevel_presence=0):\n    a = TpPd(pd=0x5)\n    b = MessageType(mesType=0x24)\n    c = CmServiceTypeAndCiphKeySeqNr()\n    e = MobileStationClassmark2()\n    f = MobileId()\n    packet = a / b / c / e / f\n    if PriorityLevel_presence is 1:\n        g = PriorityLevelHdr(ieiPL=0x8, eightBitPL=0x0)\n        packet = packet / g\n    return packet",
    "docstring": "CM SERVICE REQUEST Section 9.2.9"
  },
  {
    "code": "def secp256k1():\n        GFp = FiniteField(2 ** 256 - 2 ** 32 - 977)\n        ec = EllipticCurve(GFp, 0, 7)\n        return ECDSA(ec, ec.point(0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8), 2 ** 256 - 432420386565659656852420866394968145599)",
    "docstring": "create the secp256k1 curve"
  },
  {
    "code": "def StartElement(self, name, attributes):\n        if name == 'hierarchy':\n            pass\n        elif name == 'node':\n            attributes['uniqueId'] = 'id/no_id/%d' % self.idCount\n            bounds = re.split('[\\][,]', attributes['bounds'])\n            attributes['bounds'] = ((int(bounds[1]), int(bounds[2])), (int(bounds[4]), int(bounds[5])))\n            if DEBUG_BOUNDS:\n                print >> sys.stderr, \"bounds=\", attributes['bounds']\n            self.idCount += 1\n            child = View.factory(attributes, self.device, version=self.version, uiAutomatorHelper=self.uiAutomatorHelper)\n            self.views.append(child)\n            if not self.nodeStack:\n                self.root = child\n            else:\n                self.parent = self.nodeStack[-1]\n                self.parent.add(child)\n            self.nodeStack.append(child)",
    "docstring": "Expat start element event handler"
  },
  {
    "code": "def _transform(xsl_filename, xml, **kwargs):\n    xslt = _make_xsl(xsl_filename)\n    xml = xslt(xml, **kwargs)\n    return xml",
    "docstring": "Transforms the xml using the specifiec xsl file."
  },
  {
    "code": "def diff(candidate, running, *models):\n    if isinstance(models, tuple) and isinstance(models[0], list):\n        models = models[0]\n    first = _get_root_object(models)\n    first.load_dict(candidate)\n    second = _get_root_object(models)\n    second.load_dict(running)\n    return napalm_yang.utils.diff(first, second)",
    "docstring": "Returns the difference between two configuration entities structured\n    according to the YANG model.\n\n    .. note::\n        This function is recommended to be used mostly as a state helper.\n\n    candidate\n        First model to compare.\n\n    running\n        Second model to compare.\n\n    models\n        A list of models to be used when comparing.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' napalm_yang.diff {} {} models.openconfig_interfaces\n\n    Output Example:\n\n    .. code-block:: python\n\n        {\n            \"interfaces\": {\n                \"interface\": {\n                    \"both\": {\n                        \"Port-Channel1\": {\n                            \"config\": {\n                                \"mtu\": {\n                                    \"first\": \"0\",\n                                    \"second\": \"9000\"\n                                }\n                            }\n                        }\n                    },\n                    \"first_only\": [\n                        \"Loopback0\"\n                    ],\n                    \"second_only\": [\n                        \"Loopback1\"\n                    ]\n                }\n            }\n        }"
  },
  {
    "code": "def normalize_name(self, name):\n        name = name.lower()\n        if name in self.aliases:\n            name = self.aliases[name]\n        return name",
    "docstring": "Normalize a field or level name.\n\n        :param name: The field or level name (a string).\n        :returns: The normalized name (a string).\n\n        Transforms all strings to lowercase and resolves level name aliases\n        (refer to :func:`find_level_aliases()`) to their canonical name:\n\n        >>> from coloredlogs import NameNormalizer\n        >>> from humanfriendly import format_table\n        >>> nn = NameNormalizer()\n        >>> sample_names = ['DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'FATAL', 'CRITICAL']\n        >>> print(format_table([(n, nn.normalize_name(n)) for n in sample_names]))\n        -----------------------\n        | DEBUG    | debug    |\n        | INFO     | info     |\n        | WARN     | warning  |\n        | WARNING  | warning  |\n        | ERROR    | error    |\n        | FATAL    | critical |\n        | CRITICAL | critical |\n        -----------------------"
  },
  {
    "code": "def parse_services(config, services):\n    enabled = 0\n    for service in services:\n        check_disabled = config.getboolean(service, 'check_disabled')\n        if not check_disabled:\n            enabled += 1\n    return enabled",
    "docstring": "Parse configuration to return number of enabled service checks.\n\n    Arguments:\n        config (obj): A configparser object with the configuration of\n        anycast-healthchecker.\n        services (list): A list of section names which holds configuration\n        for each service check\n\n    Returns:\n        A number (int) of enabled service checks."
  },
  {
    "code": "def on_batch_begin(self, train, **kwargs:Any)->None:\n        \"Record learning rate and momentum at beginning of batch.\"\n        if train:\n            self.lrs.append(self.opt.lr)\n            self.moms.append(self.opt.mom)",
    "docstring": "Record learning rate and momentum at beginning of batch."
  },
  {
    "code": "def get_files(self):\n        files = {}\n        for filename in os.listdir(self.source):\n            path = os.path.join(self.source, filename)\n            files[filename] = frontmatter.load(path, \n                filename=filename, \n                slug=os.path.splitext(filename)[0])\n        return files",
    "docstring": "Read and parse files from a directory,\n        return a dictionary of path => post"
  },
  {
    "code": "def install_timers(config, context):\n    timers = []\n    if config.get('capture_timeout_warnings'):\n        timeout_threshold = config.get('timeout_warning_threshold')\n        time_remaining = context.get_remaining_time_in_millis() / 1000\n        timers.append(Timer(time_remaining * timeout_threshold, timeout_warning, (config, context)))\n        timers.append(Timer(max(time_remaining - .5, 0), timeout_error, [config]))\n    if config.get('capture_memory_warnings'):\n        timers.append(Timer(.5, memory_warning, (config, context)))\n    for t in timers:\n        t.start()\n    return timers",
    "docstring": "Create the timers as specified by the plugin configuration."
  },
  {
    "code": "def execute_sql(self, query):\n        c = self.con.cursor()\n        c.execute(query)\n        result = c.fetchall()\n        return result",
    "docstring": "Executes a given query string on an open sqlite database."
  },
  {
    "code": "def get_oncall(self, **kwargs):\n        endpoint = '/'.join((self.endpoint, self.id, 'users'))\n        return self.request('GET', endpoint=endpoint, query_params=kwargs)",
    "docstring": "Retrieve this schedule's \"on call\" users."
  },
  {
    "code": "def get_setup_requires():\n    if {'--help', '--help-commands'}.intersection(sys.argv):\n        return list()\n    reqlist = []\n    for cmd, dependencies in SETUP_REQUIRES.items():\n        if cmd in sys.argv:\n            reqlist.extend(dependencies)\n    return reqlist",
    "docstring": "Return the list of packages required for this setup.py run"
  },
  {
    "code": "def ext_pillar(minion_id,\n               pillar,\n               command):\n    try:\n        command = command.replace('%s', minion_id)\n        return deserialize(__salt__['cmd.run']('{0}'.format(command)))\n    except Exception:\n        log.critical('YAML data from %s failed to parse', command)\n        return {}",
    "docstring": "Execute a command and read the output as YAMLEX"
  },
  {
    "code": "def all(cls):\n        api = Client.instance().api\n        endpoint_list = api.endpoint.get()\n        return endpoint_list",
    "docstring": "Returns a list of all configured endpoints the server is listening on. For each endpoint,\n            the list of allowed databases is returned too if set.\n\n            The result is a JSON hash which has the endpoints as keys, and the list of\n            mapped database names as values for each endpoint.\n\n            If a list of mapped databases is empty, it means that all databases can be accessed via the endpoint.\n            If a list of mapped databases contains more than one database name, this means that any of the\n            databases might be accessed via the endpoint, and the first database in the list will be treated\n            as the default database for the endpoint. The default database will be used when an incoming request\n            does not specify a database name in the request explicitly.\n\n            *Note*: retrieving the list of all endpoints is allowed in the system database only.\n            Calling this action in any other database will make the server return an error."
  },
  {
    "code": "def jars(self, absolute=True):\n        jars = glob(os.path.join(self._jar_path, '*.jar'))\n        return jars if absolute else map(lambda j: os.path.abspath(j), jars)",
    "docstring": "List of jars in the jar path"
  },
  {
    "code": "def get_language_details(self, language):\n        for lang in self.user_data.languages:\n            if language == lang['language_string']:\n                return lang\n        return {}",
    "docstring": "Get user's status about a language."
  },
  {
    "code": "def stop(name, timeout=None, **kwargs):\n    if timeout is None:\n        try:\n            timeout = inspect_container(name)['Config']['StopTimeout']\n        except KeyError:\n            timeout = salt.utils.docker.SHUTDOWN_TIMEOUT\n    orig_state = state(name)\n    if orig_state == 'paused':\n        if kwargs.get('unpause', False):\n            unpause_result = _change_state(name, 'unpause', 'running')\n            if unpause_result['result'] is False:\n                unpause_result['comment'] = (\n                    'Failed to unpause container \\'{0}\\''.format(name)\n                )\n                return unpause_result\n        else:\n            return {'result': False,\n                    'state': {'old': orig_state, 'new': orig_state},\n                    'comment': ('Container \\'{0}\\' is paused, run with '\n                                'unpause=True to unpause before stopping'\n                                .format(name))}\n    ret = _change_state(name, 'stop', 'stopped', timeout=timeout)\n    ret['state']['old'] = orig_state\n    return ret",
    "docstring": "Stops a running container\n\n    name\n        Container name or ID\n\n    unpause : False\n        If ``True`` and the container is paused, it will be unpaused before\n        attempting to stop the container.\n\n    timeout\n        Timeout in seconds after which the container will be killed (if it has\n        not yet gracefully shut down)\n\n        .. versionchanged:: 2017.7.0\n            If this argument is not passed, then the container's configuration\n            will be checked. If the container was created using the\n            ``stop_timeout`` argument, then the configured timeout will be\n            used, otherwise the timeout will be 10 seconds.\n\n    **RETURN DATA**\n\n    A dictionary will be returned, containing the following keys:\n\n    - ``status`` - A dictionary showing the prior state of the container as\n      well as the new state\n    - ``result`` - A boolean noting whether or not the action was successful\n    - ``comment`` - Only present if the container can not be stopped\n\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt myminion docker.stop mycontainer\n        salt myminion docker.stop mycontainer unpause=True\n        salt myminion docker.stop mycontainer timeout=20"
  },
  {
    "code": "def iter_rows(self, start=None, end=None):\n        start = start or 0\n        end = end or self.nrows\n        for i in range(start, end):\n            yield self.iloc[i, :]",
    "docstring": "Iterate each of the Region rows in this region"
  },
  {
    "code": "def parse_class_id(self, sel, m, has_selector):\n        selector = m.group(0)\n        if selector.startswith('.'):\n            sel.classes.append(css_unescape(selector[1:]))\n        else:\n            sel.ids.append(css_unescape(selector[1:]))\n        has_selector = True\n        return has_selector",
    "docstring": "Parse HTML classes and ids."
  },
  {
    "code": "def _no_spelling_errors(relative_path, contents, linter_options):\n    block_regexps = linter_options.get(\"block_regexps\", None)\n    chunks, shadow = spellcheckable_and_shadow_contents(contents,\n                                                        block_regexps)\n    cache = linter_options.get(\"spellcheck_cache\", None)\n    user_words, valid_words = valid_words_dictionary_helper.create(cache)\n    technical_words = _create_technical_words_dictionary(cache,\n                                                         relative_path,\n                                                         user_words,\n                                                         shadow)\n    if linter_options.get(\"log_technical_terms_to\"):\n        linter_options[\"log_technical_terms_to\"].put(technical_words.words())\n    return [e for e in _find_spelling_errors_in_chunks(chunks,\n                                                       contents,\n                                                       valid_words,\n                                                       technical_words,\n                                                       user_words) if e]",
    "docstring": "No spelling errors in strings, comments or anything of the like."
  },
  {
    "code": "def calc_area_under_PSD(self, lowerFreq, upperFreq):\n        Freq_startAreaPSD = take_closest(self.freqs, lowerFreq)\n        index_startAreaPSD = int(_np.where(self.freqs == Freq_startAreaPSD)[0][0])\n        Freq_endAreaPSD = take_closest(self.freqs, upperFreq)\n        index_endAreaPSD = int(_np.where(self.freqs == Freq_endAreaPSD)[0][0])\n        AreaUnderPSD = sum(self.PSD[index_startAreaPSD: index_endAreaPSD])\n        return AreaUnderPSD",
    "docstring": "Sums the area under the PSD from lowerFreq to upperFreq.\n\n        Parameters\n        ----------\n        lowerFreq : float\n            The lower limit of frequency to sum from\n        upperFreq : float\n            The upper limit of frequency to sum to\n\n        Returns\n        -------\n        AreaUnderPSD : float\n            The area under the PSD from lowerFreq to upperFreq"
  },
  {
    "code": "def spectral_norm(w, dim=0, itr=1, eps=1e-12, test=False, u_init=None, fix_parameters=True):\n    assert (0 <= dim and dim < len(w.shape)\n            ), \"`dim` must be `0 <= dim and dim < len(w.shape)`.\"\n    assert 0 < itr, \"`itr` must be greater than 0.\"\n    assert 0 < eps, \"`eps` must be greater than 0.\"\n    if dim == len(w.shape) - 1:\n        w_sn = _spectral_norm_outer_most_dim(w, dim=dim, itr=itr, eps=eps, test=test,\n                                             u_init=u_init, fix_parameters=fix_parameters)\n    else:\n        w_sn = _spectral_norm(w, dim=dim, itr=itr, eps=eps, test=test,\n                              u_init=u_init, fix_parameters=fix_parameters)\n    return w_sn",
    "docstring": "Spectral Normalization.\n\n    .. math::\n\n        W_{sn} = \\\\frac{W}{\\\\sigma(W)}.\n\n    where :math:`W` is the input matrix, and the :math:`\\\\sigma(W)` is the spectral norm of :math:`W`. The spectral norm is approximately computed by the power iteration.\n\n    References:\n\n        Takeru Miyato, Toshiki Kataoka, Masanori Koyama, Yuichi Yoshida, \n        \"Spectral Normalization for Generative Adversarial Networks\", \n        International Conference on Learning Representations. 2018.\n\n    Args:\n        W (~nnabla.Variable): Input N-D array with shape. This is normally network parameter.\n        dim (`int`): Output dimension. Default is 0. If the dimension is not 0, then the specified dimension becomes the most-left dimension by transposing.\n        itr (`int`): Number of iterations. Default is 1.\n        eps (`float`): Epsilon for the normalization. Default is 1e-12.\n        test (`bool`): Use test mode. Default is False.\n\n    Returns:\n        ~nnabla.Variable: Spectrally normalized :math:`W_{sn}` with the same shape as :math:`W`.\n\n    Example:\n\n        .. code-block:: python\n\n            import nnabla as nn\n            import nnabla.parametric_functions as PF\n\n            b, c, h, w = 4, 64, 32, 32\n\n            # Spectrally normalized convolution\n            apply_w = lambda w: PF.spectral_norm(w, dim=0)\n            h = nn.Variable.from_numpy_array(np.random.randn(b, c, h, w))\n            h = PF.convolution(h, with_bias=False, apply_w=apply_w)\n\n            # Spectrally normalized affine\n            apply_w = lambda w: PF.spectral_norm(w, dim=1)\n            h = nn.Variable.from_numpy_array(np.random.randn(b, c))\n            h = PF.affine(h, with_bias=False, apply_w=apply_w)\n\n            # Spectrally normalized embed\n            apply_w = lambda w: PF.spectral_norm(w, dim=1)\n            h = nn.Variable.from_numpy_array(np.random.randn(b, c))\n            h = PF.embed(h, c, apply_w=apply_w)"
  },
  {
    "code": "def value(self):\n        if self.ready is True:\n            flag, load = self.__queue.get()\n            if flag:\n                return load\n            raise load",
    "docstring": "Read-only property containing data returned from function."
  },
  {
    "code": "def exclude(self, scheduled_operation: ScheduledOperation) -> bool:\n        try:\n            self.scheduled_operations.remove(scheduled_operation)\n            return True\n        except ValueError:\n            return False",
    "docstring": "Omits a scheduled operation from the schedule, if present.\n\n        Args:\n            scheduled_operation: The operation to try to remove.\n\n        Returns:\n            True if the operation was present and is now removed, False if it\n            was already not present."
  },
  {
    "code": "def get_page_template(self, **kwargs):\n        opts = self.object_list.model._meta\n        return '{0}/{1}{2}{3}.html'.format(\n            opts.app_label,\n            opts.object_name.lower(),\n            self.template_name_suffix,\n            self.page_template_suffix,\n        )",
    "docstring": "Return the template name used for this request.\n\n        Only called if *page_template* is not given as a kwarg of\n        *self.as_view*."
  },
  {
    "code": "def parse_keys(self, sn: \"DataNode\") -> Dict[InstanceName, ScalarValue]:\n        res = {}\n        for k in self.keys:\n            knod = sn.get_data_child(*k)\n            if knod is None:\n                raise NonexistentSchemaNode(sn.qual_name, *k)\n            kval = knod.type.parse_value(self.keys[k])\n            if kval is None:\n                raise InvalidKeyValue(self.keys[k])\n            res[knod.iname()] = kval\n        return res",
    "docstring": "Parse key dictionary in the context of a schema node.\n\n        Args:\n            sn: Schema node corresponding to a list."
  },
  {
    "code": "def run_suite(self):\n        if not self.phantomjs_runner:\n            raise JsTestException('phantomjs_runner need to be defined')\n        url = self.get_url()\n        self.phantomjs(self.phantomjs_runner, url, title=self.title)\n        self.cleanup()",
    "docstring": "Run a phantomjs test suite.\n\n         - ``phantomjs_runner`` is mandatory.\n         - Either ``url`` or ``url_name`` needs to be defined."
  },
  {
    "code": "def _configuration(self, *args, **kwargs):\n        data = dict()\n        self.db.open()\n        for pkg in self.db.get(Package):\n            configs = list()\n            for pkg_cfg in self.db.get(PackageCfgFile, eq={'pkgid': pkg.id}):\n                configs.append(pkg_cfg.path)\n            data[pkg.name] = configs\n        if not data:\n            raise InspectorQueryException(\"No inspected configuration yet available.\")\n        return data",
    "docstring": "Return configuration files."
  },
  {
    "code": "def values(self):\n        results = {}\n        results['use_calfile'] = self.ui.calfileRadio.isChecked()\n        results['calname'] = str(self.ui.calChoiceCmbbx.currentText())\n        results['frange'] = (self.ui.frangeLowSpnbx.value(), self.ui.frangeHighSpnbx.value())\n        return results",
    "docstring": "Gets the values the user input to this dialog\n\n        :returns: dict of inputs:\n        |               *'use_calfile'*: bool, -- whether to apply calibration at all\n        |               *'calname'*: str, -- the name of the calibration dataset to use\n        |               *'frange'*: (int, int), -- (min, max) of the frequency range to apply calibration to"
  },
  {
    "code": "def _fingerprint_files(self, filepaths):\n    hasher = sha1()\n    for filepath in filepaths:\n      filepath = self._assert_in_buildroot(filepath)\n      hasher.update(os.path.relpath(filepath, get_buildroot()).encode('utf-8'))\n      with open(filepath, 'rb') as f:\n        hasher.update(f.read())\n    return hasher.hexdigest()",
    "docstring": "Returns a fingerprint of the given filepaths and their contents.\n\n    This assumes the files are small enough to be read into memory."
  },
  {
    "code": "def draw_svg(self, svg_str):\n        try:\n            import rsvg\n        except ImportError:\n            self.draw_text(svg_str)\n            return\n        svg = rsvg.Handle(data=svg_str)\n        svg_width, svg_height = svg.get_dimension_data()[:2]\n        transx, transy = self._get_translation(svg_width, svg_height)\n        scale_x, scale_y = self._get_scalexy(svg_width, svg_height)\n        scale = min(scale_x, scale_y)\n        angle = float(self.code_array.cell_attributes[self.key][\"angle\"])\n        self.context.save()\n        self.context.rotate(-angle / 360 * 2 * math.pi)\n        self.context.translate(transx, transy)\n        self.context.scale(scale, scale)\n        svg.render_cairo(self.context)\n        self.context.restore()",
    "docstring": "Draws svg string to cell"
  },
  {
    "code": "def segments (self):\n    for n in xrange(len(self.vertices) - 1):\n      yield Line(self.vertices[n], self.vertices[n + 1])\n    yield Line(self.vertices[-1], self.vertices[0])",
    "docstring": "Return the Line segments that comprise this Polygon."
  },
  {
    "code": "def surface(x, y, z):\n    data = [go.Surface(x=x, y=y, z=z)]\n    return Chart(data=data)",
    "docstring": "Surface plot.\n\n    Parameters\n    ----------\n    x : array-like, optional\n    y : array-like, optional\n    z : array-like, optional\n\n    Returns\n    -------\n    Chart"
  },
  {
    "code": "def add_criterion(self, name, priority, and_or, search_type, value):\n        criterion = SearchCriteria(name, priority, and_or, search_type, value)\n        self.criteria.append(criterion)",
    "docstring": "Add a search criteria object to a smart group.\n\n        Args:\n            name: String Criteria type name (e.g. \"Application Title\")\n            priority: Int or Str number priority of criterion.\n            and_or: Str, either \"and\" or \"or\".\n            search_type: String Criteria search type. (e.g. \"is\", \"is\n                not\", \"member of\", etc). Construct a SmartGroup with the\n                criteria of interest in the web interface to determine\n                what range of values are available.\n            value: String value to search for/against."
  },
  {
    "code": "def class_factory(name, base_class, class_dict):\n    def __init__(self, tcex):\n        base_class.__init__(self, tcex)\n        for k, v in class_dict.items():\n            setattr(self, k, v)\n    newclass = type(str(name), (base_class,), {'__init__': __init__})\n    return newclass",
    "docstring": "Internal method for dynamically building Custom Indicator classes."
  },
  {
    "code": "def parse_all(self):\n        tokens = self.split_tokens\n        duration = self.duration\n        datetime = self.datetime\n        thread = self.thread\n        operation = self.operation\n        namespace = self.namespace\n        pattern = self.pattern\n        nscanned = self.nscanned\n        nscannedObjects = self.nscannedObjects\n        ntoreturn = self.ntoreturn\n        nreturned = self.nreturned\n        ninserted = self.ninserted\n        ndeleted = self.ndeleted\n        nupdated = self.nupdated\n        numYields = self.numYields\n        w = self.w\n        r = self.r",
    "docstring": "Trigger extraction of all information.\n\n        These values are usually evaluated lazily."
  },
  {
    "code": "def execution_minutes_for_session(self, session_label):\n        return self.minutes_in_range(\n            start_minute=self.execution_time_from_open(\n                self.schedule.at[session_label, 'market_open'],\n            ),\n            end_minute=self.execution_time_from_close(\n                self.schedule.at[session_label, 'market_close'],\n            ),\n        )",
    "docstring": "Given a session label, return the execution minutes for that session.\n\n        Parameters\n        ----------\n        session_label: pd.Timestamp (midnight UTC)\n            A session label whose session's minutes are desired.\n\n        Returns\n        -------\n        pd.DateTimeIndex\n            All the execution minutes for the given session."
  },
  {
    "code": "def clear_events(self, event_name):\n        self.lock.acquire()\n        try:\n            q = self.get_event_q(event_name)\n            q.queue.clear()\n        except queue.Empty:\n            return\n        finally:\n            self.lock.release()",
    "docstring": "Clear all events of a particular name.\n\n        Args:\n            event_name: Name of the events to be popped."
  },
  {
    "code": "def add_text_to_image(fname, txt, opFilename):\n    ft = ImageFont.load(\"T://user//dev//src//python//_AS_LIB//timR24.pil\")\n    print(\"Adding text \", txt, \" to \", fname, \" pixels wide to file \" , opFilename)\n    im = Image.open(fname)\n    draw = ImageDraw.Draw(im)\n    draw.text((0, 0), txt, fill=(0, 0, 0), font=ft)\n    del draw  \n    im.save(opFilename)",
    "docstring": "convert an image by adding text"
  },
  {
    "code": "def findOne(self, query=None, mode=FindOneMode.FIRST, **kwargs):\n        results = self.find(query, **kwargs)\n        if len(results) is 0:\n            return None\n        elif len(results) is 1 or mode == FindOneMode.FIRST:\n            return results[0]\n        elif mode == FindOneMode.LAST:\n            return results[-1]",
    "docstring": "Perform a find, with the same options present, but only return a maximum of one result.  If find returns\n        an empty array, then None is returned.\n\n        If there are multiple results from find, the one returned depends on the mode parameter.  If mode is\n        FindOneMode.FIRST, then the first result is returned.  If the mode is FindOneMode.LAST, then the last is\n        returned.  If the mode is FindOneMode.ERROR, then a SlickCommunicationError is raised."
  },
  {
    "code": "def get_my_hostname(self, split_hostname_on_first_period=False):\n        hostname = self.init_config.get(\"os_host\") or self.hostname\n        if split_hostname_on_first_period:\n            hostname = hostname.split('.')[0]\n        return hostname",
    "docstring": "Returns a best guess for the hostname registered with OpenStack for this host"
  },
  {
    "code": "def create_contact(self, attrs, members=None, folder_id=None, tags=None):\n        cn = {}\n        if folder_id:\n            cn['l'] = str(folder_id)\n        if tags:\n            tags = self._return_comma_list(tags)\n            cn['tn'] = tags\n        if members:\n            cn['m'] = members\n        attrs = [{'n': k, '_content': v} for k, v in attrs.items()]\n        cn['a'] = attrs\n        resp = self.request_single('CreateContact', {'cn': cn})\n        return zobjects.Contact.from_dict(resp)",
    "docstring": "Create a contact\n\n        Does not include VCARD nor group membership yet\n\n        XML example :\n        <cn l=\"7> ## ContactSpec\n            <a n=\"lastName\">MARTIN</a>\n            <a n=\"firstName\">Pierre</a>\n            <a n=\"email\">pmartin@example.com</a>\n        </cn>\n        Which would be in zimsoap : attrs = { 'lastname': 'MARTIN',\n                                        'firstname': 'Pierre',\n                                        'email': 'pmartin@example.com' }\n                                    folder_id = 7\n\n        :param folder_id: a string of the ID's folder where to create\n        contact. Default '7'\n        :param tags:     comma-separated list of tag names\n        :param attrs:   a dictionary of attributes to set ({key:value,...}). At\n        least one attr is required\n        :returns:       the created zobjects.Contact"
  },
  {
    "code": "def parse_uinput_mapping(name, mapping):\n    axes, buttons, mouse, mouse_options = {}, {}, {}, {}\n    description = \"ds4drv custom mapping ({0})\".format(name)\n    for key, attr in mapping.items():\n        key = key.upper()\n        if key.startswith(\"BTN_\") or key.startswith(\"KEY_\"):\n            buttons[key] = attr\n        elif key.startswith(\"ABS_\"):\n            axes[key] = attr\n        elif key.startswith(\"REL_\"):\n            mouse[key] = attr\n        elif key.startswith(\"MOUSE_\"):\n            mouse_options[key] = attr\n    create_mapping(name, description, axes=axes, buttons=buttons,\n                   mouse=mouse, mouse_options=mouse_options)",
    "docstring": "Parses a dict of mapping options."
  },
  {
    "code": "def check( state_engine, nameop, block_id, checked_ops ):\n    sender = nameop['sender']\n    sending_blockchain_id = None\n    found = False\n    blockchain_namerec = None\n    for blockchain_id in state_engine.get_announce_ids():\n        blockchain_namerec = state_engine.get_name( blockchain_id )\n        if blockchain_namerec is None:\n            continue\n        if str(sender) == str(blockchain_namerec['sender']):\n            found = True\n            sending_blockchain_id = blockchain_id\n            break\n    if not found:\n        log.warning(\"Announcement not sent from our whitelist of blockchain IDs\")\n        return False\n    nameop['announcer_id'] = sending_blockchain_id\n    process_announcement( blockchain_namerec, nameop, state_engine.working_dir )\n    return True",
    "docstring": "Log an announcement from the blockstack developers,\n    but first verify that it is correct.\n    Return True if the announcement came from the announce IDs whitelist\n    Return False otherwise"
  },
  {
    "code": "def asdict(self):\n        result = {}\n        for key in self._fields:\n            value = getattr(self, key)\n            if isinstance(value, list):\n                value = [i.asdict() if isinstance(i, Resource) else i for i in value]\n            if isinstance(value, Resource):\n                value = value.asdict()\n            result[key] = value\n        return result",
    "docstring": "Convert resource to dictionary"
  },
  {
    "code": "def audit_with_request(**kwargs):\n    def wrap(fn):\n        @audit(**kwargs)\n        def operation(parent_object, *args, **kw):\n            return fn(parent_object.request, *args, **kw)\n        @functools.wraps(fn)\n        def advice_with_request(the_request, *args, **kw):\n            class ParentObject:\n                request = the_request\n            return operation(ParentObject(), *args, **kw)\n        return advice_with_request\n    return wrap",
    "docstring": "use this decorator to audit an operation with a request as input variable"
  },
  {
    "code": "def _validate(claims, validate_claims, expiry_seconds):\n    if not validate_claims:\n        return\n    now = time()\n    try:\n        expiration_time = claims[CLAIM_EXPIRATION_TIME]\n    except KeyError:\n        pass\n    else:\n        _check_expiration_time(now, expiration_time)\n    try:\n        issued_at = claims[CLAIM_ISSUED_AT]\n    except KeyError:\n        pass\n    else:\n        if expiry_seconds is not None:\n            _check_expiration_time(now, issued_at + expiry_seconds)\n    try:\n        not_before = claims[CLAIM_NOT_BEFORE]\n    except KeyError:\n        pass\n    else:\n        _check_not_before(now, not_before)",
    "docstring": "Validate expiry related claims.\n\n    If validate_claims is False, do nothing.\n\n    Otherwise, validate the exp and nbf claims if they are present, and\n    validate the iat claim if expiry_seconds is provided."
  },
  {
    "code": "def build_catalog_info(self, catalog_info):\n        cat = SourceFactory.build_catalog(**catalog_info)\n        catalog_info['catalog'] = cat\n        catalog_info['catalog_table'] = cat.table\n        catalog_info['roi_model'] =\\\n            SourceFactory.make_fermipy_roi_model_from_catalogs([cat])\n        catalog_info['srcmdl_name'] =\\\n            self._name_factory.srcmdl_xml(sourcekey=catalog_info['catalog_name'])\n        return CatalogInfo(**catalog_info)",
    "docstring": "Build a CatalogInfo object"
  },
  {
    "code": "def update(cls, spec, updates, upsert=False):\n        if 'key' in spec:\n            previous = cls.get(spec['key'])\n        else:\n            previous = None\n        if previous:\n            current = cls(**previous.__dict__)\n        elif upsert:\n            current = cls(**spec)\n        else:\n            current = None\n        if current:\n            current.__dict__.update(updates)\n            current.save()\n        return current",
    "docstring": "The spec is used to search for the data to update, updates contains the\n        values to be updated, and upsert specifies whether to do an insert if\n        the original data is not found."
  },
  {
    "code": "def should_copy(column):\n    if not isinstance(column.type, Serial):\n        return True\n    if column.nullable:\n        return True\n    if not column.server_default:\n        return True\n    return False",
    "docstring": "Determine if a column should be copied."
  },
  {
    "code": "def get_db_row(db, start, size):\n    type_ = snap7.snap7types.wordlen_to_ctypes[snap7.snap7types.S7WLByte]\n    data = client.db_read(db, start, type_, size)\n    return data",
    "docstring": "Here you see and example of readying out a part of a DB\n\n    Args:\n        db (int): The db to use\n        start (int): The index of where to start in db data\n        size (int): The size of the db data to read"
  },
  {
    "code": "def spkapo(targ, et, ref, sobs, abcorr):\n    targ = ctypes.c_int(targ)\n    et = ctypes.c_double(et)\n    ref = stypes.stringToCharP(ref)\n    abcorr = stypes.stringToCharP(abcorr)\n    sobs = stypes.toDoubleVector(sobs)\n    ptarg = stypes.emptyDoubleVector(3)\n    lt = ctypes.c_double()\n    libspice.spkapo_c(targ, et, ref, sobs, abcorr, ptarg, ctypes.byref(lt))\n    return stypes.cVectorToPython(ptarg), lt.value",
    "docstring": "Return the position of a target body relative to an observer,\n    optionally corrected for light time and stellar aberration.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkapo_c.html\n\n    :param targ: Target body.\n    :type targ: int\n    :param et: Observer epoch.\n    :type et: float\n    :param ref: Inertial reference frame of observer's state.\n    :type ref: str\n    :param sobs: State of observer wrt. solar system barycenter.\n    :type sobs: 6-Element Array of floats\n    :param abcorr: Aberration correction flag.\n    :type abcorr: str\n    :return:\n            Position of target,\n            One way light time between observer and target.\n    :rtype: tuple"
  },
  {
    "code": "def on_gtk_prefer_dark_theme_toggled(self, chk):\n        self.settings.general.set_boolean('gtk-prefer-dark-theme', chk.get_active())\n        select_gtk_theme(self.settings)",
    "docstring": "Set the `gtk_prefer_dark_theme' property in dconf"
  },
  {
    "code": "def from_keys(cls, keys, loader_func, type_hint=None):\n        return cls({k: LazyLoadedValue(\n            lambda k=k: loader_func(k), type_hint=type_hint) for k in keys})",
    "docstring": "Factory method for `LazyLoadedDict`\n\n        Accepts a ``loader_func`` that is to be applied to all ``keys``.\n\n        :param keys: List of keys to create the dictionary with\n        :type keys: iterable\n        :param loader_func: Function to be applied to all keys\n        :type loader_func: function\n        :param type_hint: Expected type of lazy loaded values.\n            Used by `LazyLoadedValue`. (Default value = None)\n        :type type_hint: str\n        :returns: A properly constructed lazy loaded dictionary\n        :rtype: LazyLoadedDict"
  },
  {
    "code": "def _bits_ports_and_isrom_from_memory(mem):\n    is_rom = False\n    bits = 2**mem.addrwidth * mem.bitwidth\n    read_ports = len(mem.readport_nets)\n    try:\n        write_ports = len(mem.writeport_nets)\n    except AttributeError:\n        if not isinstance(mem, RomBlock):\n            raise PyrtlInternalError('Mem with no writeport_nets attribute'\n                                     ' but not a ROM? Thats an error')\n        write_ports = 0\n        is_rom = True\n    ports = max(read_ports, write_ports)\n    return bits, ports, is_rom",
    "docstring": "Helper to extract mem bits and ports for estimation."
  },
  {
    "code": "def _lane_detail_to_ss(fcid, ldetail):\n    return [fcid, ldetail[\"lane\"], ldetail[\"name\"], ldetail[\"genome_build\"],\n            ldetail[\"bc_index\"], ldetail[\"description\"].encode(\"ascii\", \"ignore\"), \"N\", \"\", \"\",\n            ldetail[\"project_name\"]]",
    "docstring": "Convert information about a lane into Illumina samplesheet output."
  },
  {
    "code": "def _colorize(val, color):\n    if termcolor is not None:\n        val = termcolor.colored(val, color)\n    elif colorama is not None:\n        val = TERMCOLOR2COLORAMA[color] + val + colorama.Style.RESET_ALL\n    return val",
    "docstring": "Colorize a string using termcolor or colorama.\n\n    If any of them are available."
  },
  {
    "code": "def build_from_energy_dict(cls, ebin_name, input_dict):\n        psf_types = input_dict.pop('psf_types')\n        output_list = []\n        for psf_type, val_dict in sorted(psf_types.items()):\n            fulldict = input_dict.copy()\n            fulldict.update(val_dict)\n            fulldict['evtype_name'] = psf_type\n            fulldict['ebin_name'] = ebin_name\n            component = cls(**fulldict)\n            output_list += [component]\n        return output_list",
    "docstring": "Build a list of components from a dictionary for a single energy range"
  },
  {
    "code": "def admin_link(obj):\n    if hasattr(obj, 'get_admin_link'):\n        return mark_safe(obj.get_admin_link())\n    return mark_safe(admin_link_fn(obj))",
    "docstring": "Returns a link to the admin URL of an object.\n\n    No permissions checking is involved, so use with caution to avoid exposing\n    the link to unauthorised users.\n\n    Example::\n\n        {{ foo_obj|admin_link }}\n\n    renders as::\n\n        <a href='/admin/foo/123'>Foo</a>\n\n    :param obj: A Django model instance.\n    :return: A safe string expressing an HTML link to the admin page for an\n    object."
  },
  {
    "code": "def gzip_dir(path, compresslevel=6):\n    for f in os.listdir(path):\n        full_f = os.path.join(path, f)\n        if not f.lower().endswith(\"gz\"):\n            with open(full_f, 'rb') as f_in, \\\n                GzipFile('{}.gz'.format(full_f), 'wb',\n                         compresslevel=compresslevel) as f_out:\n                shutil.copyfileobj(f_in, f_out)\n            shutil.copystat(full_f,'{}.gz'.format(full_f))\n            os.remove(full_f)",
    "docstring": "Gzips all files in a directory. Note that this is different from\n    shutil.make_archive, which creates a tar archive. The aim of this method\n    is to create gzipped files that can still be read using common Unix-style\n    commands like zless or zcat.\n\n    Args:\n        path (str): Path to directory.\n        compresslevel (int): Level of compression, 1-9. 9 is default for\n            GzipFile, 6 is default for gzip."
  },
  {
    "code": "def poly_to_pwl(self, n_points=4):\n        assert self.pcost_model == POLYNOMIAL\n        p_min = self.p_min\n        p_max = self.p_max\n        p_cost = []\n        if p_min > 0.0:\n            step = (p_max - p_min) / (n_points - 2)\n            y0 = self.total_cost(0.0)\n            p_cost.append((0.0, y0))\n            x = p_min\n            n_points -= 1\n        else:\n            step = (p_max - p_min) / (n_points - 1)\n            x = 0.0\n        for _ in range(n_points):\n            y = self.total_cost(x)\n            p_cost.append((x, y))\n            x += step\n        self.pcost_model = PW_LINEAR\n        self.p_cost = p_cost",
    "docstring": "Sets the piece-wise linear cost attribute, converting the\n        polynomial cost variable by evaluating at zero and then at n_points\n        evenly spaced points between p_min and p_max."
  },
  {
    "code": "def create_event_subscription(self, instance, on_data, timeout=60):\n        manager = WebSocketSubscriptionManager(self, resource='events')\n        subscription = WebSocketSubscriptionFuture(manager)\n        wrapped_callback = functools.partial(\n            _wrap_callback_parse_event, on_data)\n        manager.open(wrapped_callback, instance)\n        subscription.reply(timeout=timeout)\n        return subscription",
    "docstring": "Create a new subscription for receiving events of an instance.\n\n        This method returns a future, then returns immediately. Stop the\n        subscription by canceling the future.\n\n        :param str instance: A Yamcs instance name\n\n        :param on_data: Function that gets called on each :class:`.Event`.\n        :type on_data: Optional[Callable[.Event])\n\n        :param timeout: The amount of seconds to wait for the request to\n                        complete.\n        :type timeout: Optional[float]\n\n        :return: Future that can be used to manage the background websocket\n                 subscription.\n        :rtype: .WebSocketSubscriptionFuture"
  },
  {
    "code": "def get_context(self, **kwargs):\n        context = self.get_context_data(form=self.form_obj, **kwargs)\n        context.update(super(FormAdminView, self).get_context())\n        return context",
    "docstring": "Use this method to built context data for the template\n\n        Mix django wizard context data with django-xadmin context"
  },
  {
    "code": "def validate(self) :\n        if not self.mustValidate :\n            return True\n        res = {}\n        for field in self.validators.keys() :\n            try :\n                if isinstance(self.validators[field], dict) and field not in self.store :\n                    self.store[field] = DocumentStore(self.collection, validators = self.validators[field], initDct = {}, subStore=True, validateInit=self.validateInit)\n                self.validateField(field)\n            except InvalidDocument as e :\n                res.update(e.errors)\n            except (ValidationError, SchemaViolation) as e:\n                res[field] = str(e)\n        if len(res) > 0 :\n            raise InvalidDocument(res)\n        return True",
    "docstring": "Validate the whole document"
  },
  {
    "code": "def analysis(self):\n        if self._analysis is None:\n            with open(self.path, 'rb') as f:\n                self.read_analysis(f)\n        return self._analysis",
    "docstring": "Get ANALYSIS segment of the FCS file."
  },
  {
    "code": "def startLoading(self):\r\n        if self._loading:\r\n            return False\r\n        tree = self.treeWidget()\r\n        if not tree:\r\n            return\r\n        self._loading = True\r\n        self.setText(0, '')\r\n        lbl = QtGui.QLabel(self.treeWidget())\r\n        lbl.setMovie(XLoaderWidget.getMovie())\r\n        lbl.setAlignment(QtCore.Qt.AlignCenter)\r\n        tree.setItemWidget(self, 0, lbl)\r\n        try:\r\n            tree.loadStarted.emit(self)\r\n        except AttributeError:\r\n            pass\r\n        return True",
    "docstring": "Updates this item to mark the item as loading.  This will create\r\n        a QLabel with the loading ajax spinner to indicate that progress\r\n        is occurring."
  },
  {
    "code": "def get_processing_block_ids(self):\n        _processing_block_ids = []\n        pattern = '*:processing_block:*'\n        block_ids = self._db.get_ids(pattern)\n        for block_id in block_ids:\n            id_split = block_id.split(':')[-1]\n            _processing_block_ids.append(id_split)\n        return sorted(_processing_block_ids)",
    "docstring": "Get list of processing block ids using the processing block id"
  },
  {
    "code": "def _load_version(cls, state, version):\n        from ._audio_feature_extractor import _get_feature_extractor\n        from .._mxnet import _mxnet_utils\n        state['_feature_extractor'] = _get_feature_extractor(state['feature_extractor_name'])\n        num_classes = state['num_classes']\n        num_inputs = state['_feature_extractor'].output_length\n        if 'custom_layer_sizes' in state:\n            custom_layer_sizes = list(map(int, state['custom_layer_sizes']))\n        else:\n            custom_layer_sizes = [100, 100]\n        state['custom_layer_sizes'] = custom_layer_sizes\n        net = SoundClassifier._build_custom_neural_network(num_inputs, num_classes, custom_layer_sizes)\n        net_params = net.collect_params()\n        ctx = _mxnet_utils.get_mxnet_context()\n        _mxnet_utils.load_net_params_from_state(net_params, state['_custom_classifier'], ctx=ctx)\n        state['_custom_classifier'] = net\n        return SoundClassifier(state)",
    "docstring": "A function to load a previously saved SoundClassifier instance."
  },
  {
    "code": "def detach_all(self):\n        self.detach_all_classes()\n        self.objects.clear()\n        self.index.clear()\n        self._keepalive[:] = []",
    "docstring": "Detach from all tracked classes and objects.\n        Restore the original constructors and cleanse the tracking lists."
  },
  {
    "code": "def _get_action_urls(self):\n        actions = {}\n        model_name = self.model._meta.model_name\n        base_url_name = '%s_%s' % (self.model._meta.app_label, model_name)\n        model_actions_url_name = '%s_actions' % base_url_name\n        self.tools_view_name = 'admin:' + model_actions_url_name\n        for action in chain(self.change_actions, self.changelist_actions):\n            actions[action] = getattr(self, action)\n        return [\n            url(r'^(?P<pk>.+)/actions/(?P<tool>\\w+)/$',\n                self.admin_site.admin_view(\n                    ChangeActionView.as_view(\n                        model=self.model,\n                        actions=actions,\n                        back='admin:%s_change' % base_url_name,\n                        current_app=self.admin_site.name,\n                    )\n                ),\n                name=model_actions_url_name),\n            url(r'^actions/(?P<tool>\\w+)/$',\n                self.admin_site.admin_view(\n                    ChangeListActionView.as_view(\n                        model=self.model,\n                        actions=actions,\n                        back='admin:%s_changelist' % base_url_name,\n                        current_app=self.admin_site.name,\n                    )\n                ),\n                name=model_actions_url_name),\n        ]",
    "docstring": "Get the url patterns that route each action to a view."
  },
  {
    "code": "def get_config_section(self, name):\n        if self.config.has_section(name):\n            return self.config.items(name)\n        return []",
    "docstring": "Get a section of a configuration"
  },
  {
    "code": "def find_all_files(self):\n\t\tfiles = self.find_files()\n\t\tsubrepo_files = (\n\t\t\tposixpath.join(subrepo.location, filename)\n\t\t\tfor subrepo in self.subrepos()\n\t\t\tfor filename in subrepo.find_files()\n\t\t)\n\t\treturn itertools.chain(files, subrepo_files)",
    "docstring": "Find files including those in subrepositories."
  },
  {
    "code": "def one_way_portal(self, other, **stats):\n        return self.character.new_portal(\n            self, other, symmetrical=False, **stats\n        )",
    "docstring": "Connect a portal from here to another node, and return it."
  },
  {
    "code": "def _live_receivers(self, sender):\n        receivers = None\n        if self.use_caching and not self._dead_receivers:\n            receivers = self.sender_receivers_cache.get(sender)\n            if receivers is NO_RECEIVERS:\n                return []\n        if receivers is None:\n            with self.lock:\n                self._clear_dead_receivers()\n                senderkey = _make_id(sender)\n                receivers = []\n                for (receiverkey, r_senderkey), receiver in self.receivers:\n                    if r_senderkey == NONE_ID or r_senderkey == senderkey:\n                        receivers.append(receiver)\n                if self.use_caching:\n                    if not receivers:\n                        self.sender_receivers_cache[sender] = NO_RECEIVERS\n                    else:\n                        self.sender_receivers_cache[sender] = receivers\n        non_weak_receivers = []\n        for receiver in receivers:\n            if isinstance(receiver, weakref.ReferenceType):\n                receiver = receiver()\n                if receiver is not None:\n                    non_weak_receivers.append(receiver)\n            else:\n                non_weak_receivers.append(receiver)\n        return non_weak_receivers",
    "docstring": "Filter sequence of receivers to get resolved, live receivers.\n\n        This checks for weak references and resolves them, then returning only\n        live receivers."
  },
  {
    "code": "def smear(idx, factor):\n    s = [idx]\n    for i in range(factor+1):\n        a = i - factor/2\n        s += [idx + a]\n    return numpy.unique(numpy.concatenate(s))",
    "docstring": "This function will take as input an array of indexes and return every\n    unique index within the specified factor of the inputs.\n\n    E.g.: smear([5,7,100],2) = [3,4,5,6,7,8,9,98,99,100,101,102]\n\n    Parameters\n    -----------\n    idx : numpy.array of ints\n        The indexes to be smeared.\n    factor : idx\n        The factor by which to smear out the input array.\n\n    Returns\n    --------\n    new_idx : numpy.array of ints\n        The smeared array of indexes."
  },
  {
    "code": "def nla_put(msg, attrtype, datalen, data):\n    nla = nla_reserve(msg, attrtype, datalen)\n    if not nla:\n        return -NLE_NOMEM\n    if datalen <= 0:\n        return 0\n    nla_data(nla)[:datalen] = data[:datalen]\n    _LOGGER.debug('msg 0x%x: attr <0x%x> %d: Wrote %d bytes at offset +%d', id(msg), id(nla), nla.nla_type, datalen,\n                  nla.bytearray.slice.start - nlmsg_data(msg.nm_nlh).slice.start)\n    return 0",
    "docstring": "Add a unspecific attribute to Netlink message.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L497\n\n    Reserves room for an unspecific attribute and copies the provided data into the message as payload of the attribute.\n    Returns an error if there is insufficient space for the attribute.\n\n    Positional arguments:\n    msg -- Netlink message (nl_msg class instance).\n    attrtype -- attribute type (integer).\n    datalen -- length of data to be used as payload (integer).\n    data -- data to be used as attribute payload (bytearray).\n\n    Returns:\n    0 on success or a negative error code."
  },
  {
    "code": "def mod_watch(name, **kwargs):\n    ret = {'name': name,\n           'changes': {},\n           'result': False,\n           'comment': ''}\n    if kwargs['sfun'] == 'watch':\n        for p in ['sfun', '__reqs__']:\n            del kwargs[p]\n        kwargs['name'] = name\n        ret = present(**kwargs)\n    return ret",
    "docstring": "The at watcher, called to invoke the watch command.\n\n    .. note::\n        This state exists to support special handling of the ``watch``\n        :ref:`requisite <requisites>`. It should not be called directly.\n\n        Parameters for this function should be set by the state being triggered.\n\n    name\n        The name of the atjob"
  },
  {
    "code": "def estimate_frequency(self, start: int, end: int, sample_rate: float):\n        length = 2 ** int(math.log2(end - start))\n        data = self.data[start:start + length]\n        try:\n            w = np.fft.fft(data)\n            frequencies = np.fft.fftfreq(len(w))\n            idx = np.argmax(np.abs(w))\n            freq = frequencies[idx]\n            freq_in_hertz = abs(freq * sample_rate)\n        except ValueError:\n            freq_in_hertz = 100e3\n        return freq_in_hertz",
    "docstring": "Estimate the frequency of the baseband signal using FFT\n\n        :param start: Start of the area that shall be investigated\n        :param end: End of the area that shall be investigated\n        :param sample_rate: Sample rate of the signal\n        :return:"
  },
  {
    "code": "def read(self):\n\t\twith open(self.default_file) as json_file:\n\t\t\ttry:\n\t\t\t\treturn json.load(json_file)\n\t\t\texcept Exception as e:\n\t\t\t\traise 'empty file'",
    "docstring": "read default csp settings from json file"
  },
  {
    "code": "def get_development_container_name(self):\n        if self.__prefix:\n            return \"{0}:{1}-{2}-dev\".format(\n                self.__repository,\n                self.__prefix,\n                self.__branch)\n        else:\n            return \"{0}:{1}-dev\".format(\n                self.__repository,\n                self.__branch)",
    "docstring": "Returns the development container name"
  },
  {
    "code": "def changeable(self, request):\n        return self.apply_changeable(self.get_queryset(), request) if self.check_changeable(self.model, request) is not False else self.get_queryset().none()",
    "docstring": "Checks the both, check_changeable and apply_changeable, against the owned model and it's instance set"
  },
  {
    "code": "def is_digit(obj):\n    return isinstance(obj, (numbers.Integral, numbers.Complex, numbers.Real))",
    "docstring": "Check if an object is Number"
  },
  {
    "code": "def get(self, url, params={}, headers={}, auth=(), certificate_path=None):\n        certificate_path = certificate_path if certificate_path else False\n        return self.session.get(url, params=params, headers=headers, verify=certificate_path, auth=auth,\n                            timeout=self.timeout)",
    "docstring": "Returns the response payload from the request to the given URL.\n\n        Args:\n            url (str): The URL for the WEB API that the request is being made too.\n            params (dict): Dictionary containing the query string parameters.\n            headers (dict): HTTP Headers that may be needed for the request.\n            auth (tuple): User ID and password for Basic Auth\n            certificate_path (str): Path to the ssl certificate.\n\n        Returns:\n            response: (HttpResponse): Response object from requests.get api request"
  },
  {
    "code": "def softmax(w, t=1.0):\n    w = [Decimal(el) for el in w]\n    e = numpy.exp(numpy.array(w) / Decimal(t))\n    dist = e / numpy.sum(e)\n    return dist",
    "docstring": "Calculate the softmax of a list of numbers w.\n\n    Parameters\n    ----------\n    w : list of numbers\n\n    Returns\n    -------\n    a list of the same length as w of non-negative numbers\n\n    Examples\n    --------\n    >>> softmax([0.1, 0.2])\n    array([ 0.47502081,  0.52497919])\n    >>> softmax([-0.1, 0.2])\n    array([ 0.42555748,  0.57444252])\n    >>> softmax([0.9, -10])\n    array([  9.99981542e-01,   1.84578933e-05])\n    >>> softmax([0, 10])\n    array([  4.53978687e-05,   9.99954602e-01])"
  },
  {
    "code": "def create_usuario(self):\n        return Usuario(\n            self.networkapi_url,\n            self.user,\n            self.password,\n            self.user_ldap)",
    "docstring": "Get an instance of usuario services facade."
  },
  {
    "code": "def samples(self):\n        if self._samples is None:\n            self._samples = SampleList(\n                self._version,\n                assistant_sid=self._solution['assistant_sid'],\n                task_sid=self._solution['sid'],\n            )\n        return self._samples",
    "docstring": "Access the samples\n\n        :returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleList\n        :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleList"
  },
  {
    "code": "def get_missing_required_annotations(self) -> List[str]:\n        return [\n            required_annotation\n            for required_annotation in self.required_annotations\n            if required_annotation not in self.annotations\n        ]",
    "docstring": "Return missing required annotations."
  },
  {
    "code": "def service(self, name=None, pk=None, scope=None, **kwargs):\n        _services = self.services(name=name, pk=pk, scope=scope, **kwargs)\n        if len(_services) == 0:\n            raise NotFoundError(\"No service fits criteria\")\n        if len(_services) != 1:\n            raise MultipleFoundError(\"Multiple services fit criteria\")\n        return _services[0]",
    "docstring": "Retrieve single KE-chain Service.\n\n        Uses the same interface as the :func:`services` method but returns only a single pykechain\n        :class:`models.Service` instance.\n\n        :param name: (optional) name to limit the search for\n        :type name: basestring or None\n        :param pk: (optional) primary key or id (UUID) of the service to search for\n        :type pk: basestring or None\n        :param scope: (optional) id (UUID) of the scope to search in\n        :type scope: basestring or None\n        :param kwargs: (optional) additional search keyword arguments\n        :type kwargs: dict or None\n        :return: a single :class:`models.Service` object\n        :raises NotFoundError: When no `Service` object is found\n        :raises MultipleFoundError: When more than a single `Service` object is found"
  },
  {
    "code": "def options(self, parser, env=os.environ):\n        \"Add options to nosetests.\"\n        parser.add_option(\"--%s-record\" % self.name,\n                          action=\"store\",\n                          metavar=\"FILE\",\n                          dest=\"record_filename\",\n                          help=\"Record actions to this file.\")\n        parser.add_option(\"--%s-playback\" % self.name,\n                          action=\"store\",\n                          metavar=\"FILE\",\n                          dest=\"playback_filename\",\n                          help=\"Playback actions from this file.\")",
    "docstring": "Add options to nosetests."
  },
  {
    "code": "def get_loss(self, y_pred, y_true, X=None, training=False):\n        y_true = to_tensor(y_true, device=self.device)\n        return self.criterion_(y_pred, y_true)",
    "docstring": "Return the loss for this batch.\n\n        Parameters\n        ----------\n        y_pred : torch tensor\n          Predicted target values\n\n        y_true : torch tensor\n          True target values.\n\n        X : input data, compatible with skorch.dataset.Dataset\n          By default, you should be able to pass:\n\n            * numpy arrays\n            * torch tensors\n            * pandas DataFrame or Series\n            * scipy sparse CSR matrices\n            * a dictionary of the former three\n            * a list/tuple of the former three\n            * a Dataset\n\n          If this doesn't work with your data, you have to pass a\n          ``Dataset`` that can deal with the data.\n\n        training : bool (default=False)\n          Whether train mode should be used or not."
  },
  {
    "code": "def uncomplete(self):\n        args = {\n            'project_id': self.project.id,\n            'ids': [self.id]\n        }\n        owner = self.project.owner\n        _perform_command(owner, 'item_uncomplete', args)",
    "docstring": "Mark the task uncomplete.\n\n        >>> from pytodoist import todoist\n        >>> user = todoist.login('john.doe@gmail.com', 'password')\n        >>> project = user.get_project('PyTodoist')\n        >>> task = project.add_task('Install PyTodoist')\n        >>> task.uncomplete()"
  },
  {
    "code": "def assert_succeeds(exception, msg_fmt=\"{msg}\"):\n    class _AssertSucceeds(object):\n        def __enter__(self):\n            pass\n        def __exit__(self, exc_type, exc_val, exc_tb):\n            if exc_type and issubclass(exc_type, exception):\n                msg = exception.__name__ + \" was unexpectedly raised\"\n                fail(\n                    msg_fmt.format(\n                        msg=msg,\n                        exc_type=exception,\n                        exc_name=exception.__name__,\n                        exception=exc_val,\n                    )\n                )\n    return _AssertSucceeds()",
    "docstring": "Fail if a specific exception is raised within the context.\n\n    This assertion should be used for cases, where successfully running a\n    function signals a successful test, and raising the exception of a\n    certain type signals a test failure. All other raised exceptions are\n    passed on and will usually still result in a test error. This can be\n    used to signal the intent of a block.\n\n    >>> l = [\"foo\", \"bar\"]\n    >>> with assert_succeeds(ValueError):\n    ...     i = l.index(\"foo\")\n    ...\n    >>> with assert_succeeds(ValueError):\n    ...     raise ValueError()\n    ...\n    Traceback (most recent call last):\n        ...\n    AssertionError: ValueError was unexpectedly raised\n    >>> with assert_succeeds(ValueError):\n    ...     raise TypeError(\"Wrong Error\")\n    ...\n    Traceback (most recent call last):\n        ...\n    TypeError: Wrong Error\n\n    The following msg_fmt arguments are supported:\n    * msg - the default error message\n    * exc_type - exception type\n    * exc_name - exception type name\n    * exception - exception that was raised"
  },
  {
    "code": "def add_vlan_firewall(self, vlan_id, ha_enabled=False):\n        package = self.get_dedicated_package(ha_enabled)\n        product_order = {\n            'complexType': 'SoftLayer_Container_Product_Order_Network_'\n                           'Protection_Firewall_Dedicated',\n            'quantity': 1,\n            'packageId': 0,\n            'vlanId': vlan_id,\n            'prices': [{'id': package[0]['prices'][0]['id']}]\n        }\n        return self.client['Product_Order'].placeOrder(product_order)",
    "docstring": "Creates a firewall for the specified vlan.\n\n        :param int vlan_id: The ID of the vlan to create the firewall for\n        :param bool ha_enabled: If True, an HA firewall will be created\n\n        :returns: A dictionary containing the VLAN firewall order"
  },
  {
    "code": "def _detect_line_ending(self):\n        candidate_value = '\\n'\n        candidate_count = 0\n        for line_ending in UniversalCsvReader.line_endings:\n            count = self._sample.count(line_ending)\n            if count > candidate_count:\n                candidate_value = line_ending\n                candidate_count = count\n        self._formatting_parameters['line_terminator'] = candidate_value",
    "docstring": "Detects the line ending in the sample data."
  },
  {
    "code": "def ping():\n    if _worker_name() not in DETAILS:\n        init()\n    try:\n        return DETAILS[_worker_name()].conn.isalive()\n    except TerminalException as e:\n        log.error(e)\n        return False",
    "docstring": "Ping the device on the other end of the connection\n\n    .. code-block: bash\n\n        salt '*' onyx.cmd ping"
  },
  {
    "code": "def handle_cancellation(session: CommandSession):\n    def control(value):\n        if _is_cancellation(value) is True:\n            session.finish(render_expression(\n                session.bot.config.SESSION_CANCEL_EXPRESSION))\n        return value\n    return control",
    "docstring": "If the input is a string of cancellation word, finish the command session."
  },
  {
    "code": "def __get_connection(self) -> redis.Redis:\n        if self.__redis_use_socket:\n            r = redis.from_url(\n                'unix://{:s}?db={:d}'.format(\n                    self.__redis_host,\n                    self.__redis_db\n                )\n            )\n        else:\n            r = redis.from_url(\n                'redis://{:s}:{:d}/{:d}'.format(\n                    self.__redis_host,\n                    self.__redis_port,\n                    self.__redis_db\n                )\n            )\n        if BlackRed.Settings.REDIS_AUTH is not None:\n            r.execute_command('AUTH {:s}'.format(BlackRed.Settings.REDIS_AUTH))\n        return r",
    "docstring": "Get a Redis connection\n\n        :return: Redis connection instance\n        :rtype: redis.Redis"
  },
  {
    "code": "def load_brain_metadata(proxy, include_fields):\n    ret = {}\n    for index in proxy.indexes():\n        if index not in proxy:\n            continue\n        if include_fields and index not in include_fields:\n            continue\n        val = getattr(proxy, index)\n        if val != Missing.Value:\n            try:\n                json.dumps(val)\n            except:\n                continue\n            ret[index] = val\n    return ret",
    "docstring": "Load values from the catalog metadata into a list of dictionaries"
  },
  {
    "code": "def select_single_column(engine, column):\n    s = select([column])\n    return column.name, [row[0] for row in engine.execute(s)]",
    "docstring": "Select data from single column.\n\n    Example::\n\n        >>> select_single_column(engine, table_user.c.id)\n        [1, 2, 3]\n\n        >>> select_single_column(engine, table_user.c.name)\n        [\"Alice\", \"Bob\", \"Cathy\"]"
  },
  {
    "code": "def gopro_set_response_send(self, cmd_id, status, force_mavlink1=False):\n                return self.send(self.gopro_set_response_encode(cmd_id, status), force_mavlink1=force_mavlink1)",
    "docstring": "Response from a GOPRO_COMMAND set request\n\n                cmd_id                    : Command ID (uint8_t)\n                status                    : Status (uint8_t)"
  },
  {
    "code": "def truth(f):\n    @wraps(f)\n    def check(v):\n        t = f(v)\n        if not t:\n            raise ValueError\n        return v\n    return check",
    "docstring": "Convenience decorator to convert truth functions into validators.\n\n        >>> @truth\n        ... def isdir(v):\n        ...   return os.path.isdir(v)\n        >>> validate = Schema(isdir)\n        >>> validate('/')\n        '/'\n        >>> with raises(MultipleInvalid, 'not a valid value'):\n        ...   validate('/notavaliddir')"
  },
  {
    "code": "def parenthesize(self, expr, level, *args, strict=False, **kwargs):\n        needs_parenths = (\n            (precedence(expr) < level) or\n            (strict and precedence(expr) == level))\n        if needs_parenths:\n            return (\n                self._parenth_left + self.doprint(expr, *args, **kwargs) +\n                self._parenth_right)\n        else:\n            return self.doprint(expr, *args, **kwargs)",
    "docstring": "Render `expr` and wrap the result in parentheses if the precedence\n        of `expr` is below the given `level` (or at the given `level` if\n        `strict` is True. Extra `args` and `kwargs` are passed to the internal\n        `doit` renderer"
  },
  {
    "code": "def main():\n    print()\n    print(\"-~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~-\")\n    print(lorem_gotham_title().center(50))\n    print(\"-~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~-\")\n    print()\n    poem = lorem_gotham()\n    for n in range(16):\n        if n in (4, 8, 12):\n            print()\n        print(next(poem))\n    print()",
    "docstring": "I provide a command-line interface for this module"
  },
  {
    "code": "def write(self, **kwargs):\n        if 'id' in kwargs and 'data' in kwargs:\n            result = self.write_raw(kwargs['id'], kwargs['data'],\n                    bus=kwargs.get('bus', None),\n                    frame_format=kwargs.get('frame_format', None))\n        else:\n            result = self.write_translated(kwargs['name'], kwargs['value'],\n                    event=kwargs.get('event', None))\n        return result",
    "docstring": "Serialize a raw or translated write request and send it to the VI,\n        following the OpenXC message format."
  },
  {
    "code": "def autopage(self):\n        while self.items:\n            yield from self.items\n            self.items = self.fetch_next()",
    "docstring": "Iterate through results from all pages.\n\n        :return: all results\n        :rtype: generator"
  },
  {
    "code": "def evaluate_at(self, eval_at, testcases, mode=None):\n        self.eval_at = eval_at\n        self.log.eval_at = eval_at\n        if mode is None:\n            if self.context_mode is None or (self.context_mode.has_key('choose_m') and self.context_mode['choose_m']):\n                mode = 'inverse'\n            else:\n                mode = self.context_mode[\"mode\"]\n        self.evaluation = Evaluation(self.ag, self.env, testcases, mode=mode)\n        for test in testcases:\n            self.log.add('testcases', test)",
    "docstring": "Sets the evaluation interation indices.\n\n            :param list eval_at: iteration indices where an evaluation should be performed\n            :param numpy.array testcases: testcases used for evaluation"
  },
  {
    "code": "def relpath(self, path, start=None):\n        if not path:\n            raise ValueError(\"no path specified\")\n        path = make_string_path(path)\n        if start is not None:\n            start = make_string_path(start)\n        else:\n            start = self.filesystem.cwd\n        if self.filesystem.alternative_path_separator is not None:\n            path = path.replace(self.filesystem.alternative_path_separator,\n                                self._os_path.sep)\n            start = start.replace(self.filesystem.alternative_path_separator,\n                                  self._os_path.sep)\n        path = path.replace(self.filesystem.path_separator, self._os_path.sep)\n        start = start.replace(\n            self.filesystem.path_separator, self._os_path.sep)\n        path = self._os_path.relpath(path, start)\n        return path.replace(self._os_path.sep, self.filesystem.path_separator)",
    "docstring": "We mostly rely on the native implementation and adapt the\n        path separator."
  },
  {
    "code": "def _parse_mods(mods):\n    if isinstance(mods, six.string_types):\n        mods = [item.strip() for item in mods.split(',') if item.strip()]\n    return mods",
    "docstring": "Parse modules."
  },
  {
    "code": "def _handle_requests_params(self, kwargs):\n        requests_params = kwargs.pop('requests_params', {})\n        for param in requests_params:\n            if param in kwargs:\n                error_message = 'Requests Parameter %r collides with a load'\\\n                    ' parameter of the same name.' % param\n                raise RequestParamKwargCollision(error_message)\n        if self._meta_data['icontrol_version']:\n            params = requests_params.pop('params', {})\n            params.update({'ver': self._meta_data['icontrol_version']})\n            requests_params.update({'params': params})\n        return requests_params",
    "docstring": "Validate parameters that will be passed to the requests verbs.\n\n        This method validates that there is no conflict in the names of the\n        requests_params passed to the function and the other kwargs.  It also\n        ensures that the required request parameters for the object are\n        added to the request params that are passed into the verbs.  An\n        example of the latter is ensuring that a certain version of the API\n        is always called to add 'ver=11.6.0' to the url."
  },
  {
    "code": "def record(self):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('UDF Timestamp not initialized')\n        tmp = ((1 << 16) - 1) & self.tz\n        newtz = tmp & 0xff\n        newtimetype = ((tmp >> 8) & 0x0f) | (self.timetype << 4)\n        return struct.pack(self.FMT, newtz, newtimetype, self.year, self.month,\n                           self.day, self.hour, self.minute, self.second,\n                           self.centiseconds, self.hundreds_microseconds,\n                           self.microseconds)",
    "docstring": "A method to generate the string representing this UDF Timestamp.\n\n        Parameters:\n         None.\n        Returns:\n         A string representing this UDF Timestamp."
  },
  {
    "code": "def _remove_overlaps(in_file, out_dir, data):\n    out_file = os.path.join(out_dir, \"%s-nooverlaps%s\" % utils.splitext_plus(os.path.basename(in_file)))\n    if not utils.file_uptodate(out_file, in_file):\n        with file_transaction(data, out_file) as tx_out_file:\n            with open(in_file) as in_handle:\n                with open(tx_out_file, \"w\") as out_handle:\n                    prev_line = None\n                    for line in in_handle:\n                        if prev_line:\n                            pchrom, pstart, pend = prev_line.split(\"\\t\", 4)[:3]\n                            cchrom, cstart, cend = line.split(\"\\t\", 4)[:3]\n                            if pchrom == cchrom and int(pend) > int(cstart):\n                                pass\n                            else:\n                                out_handle.write(prev_line)\n                        prev_line = line\n                    out_handle.write(prev_line)\n    return out_file",
    "docstring": "Remove regions that overlap with next region, these result in issues with PureCN."
  },
  {
    "code": "def on_epoch_end(self, epoch, **kwargs:Any)->None:\n        \"Compare the value monitored to its best and maybe reduce lr.\"\n        current = self.get_monitor_value()\n        if current is None: return\n        if self.operator(current - self.min_delta, self.best): self.best,self.wait = current,0\n        else:\n            self.wait += 1\n            if self.wait > self.patience:\n                self.opt.lr *= self.factor\n                self.wait = 0\n                print(f'Epoch {epoch}: reducing lr to {self.opt.lr}')",
    "docstring": "Compare the value monitored to its best and maybe reduce lr."
  },
  {
    "code": "def parse_dsn(dsn):\n    parsed_dsn = urlparse(dsn)\n    parsed_path = parse_path(parsed_dsn.path)\n    return {\n        'scheme': parsed_dsn.scheme,\n        'sender': parsed_dsn.username,\n        'token': parsed_dsn.password,\n        'domain': parsed_dsn.hostname,\n        'port': parsed_dsn.port or 80,\n        'version': parsed_path.get('version'),\n        'project': parsed_path.get('project'),\n    }",
    "docstring": "Parse dsn string."
  },
  {
    "code": "def _key_to_address(key):\n    key_parts = key.split('.', maxsplit=_MAX_KEY_PARTS - 1)\n    key_parts.extend([''] * (_MAX_KEY_PARTS - len(key_parts)))\n    return SETTINGS_NAMESPACE + ''.join(_short_hash(x) for x in key_parts)",
    "docstring": "Creates the state address for a given setting key."
  },
  {
    "code": "def flightmode_colours():\n    from MAVProxy.modules.lib.grapher import flightmode_colours\n    mapping = {}\n    idx = 0\n    for (mode,t0,t1) in flightmodes:\n        if not mode in mapping:\n            mapping[mode] = flightmode_colours[idx]\n            idx += 1\n            if idx >= len(flightmode_colours):\n                idx = 0\n    return mapping",
    "docstring": "return mapping of flight mode to colours"
  },
  {
    "code": "def import_task(self, img, cont, img_format=None, img_name=None):\n        return self._tasks_manager.create(\"import\", img=img, cont=cont,\n                img_format=img_format, img_name=img_name)",
    "docstring": "Creates a task to import the specified image from the swift container\n        named in the 'cont' parameter. The new image will be named the same as\n        the object in the container unless you specify a value for the\n        'img_name' parameter.\n\n        By default it is assumed that the image is in 'vhd' format; if it is\n        another format, you must specify that in the 'img_format' parameter."
  },
  {
    "code": "def find_user(self, username=None, email=None):\n        if username:\n            return (\n                self.get_session.query(self.user_model)\n                .filter(func.lower(self.user_model.username) == func.lower(username))\n                .first()\n            )\n        elif email:\n            return (\n                self.get_session.query(self.user_model).filter_by(email=email).first()\n            )",
    "docstring": "Finds user by username or email"
  },
  {
    "code": "def get(self, section, option, default = None):\r\n  if self.has_section(section):\r\n   try:\r\n    return self.config[section][option].get('value', None)\r\n   except KeyError:\r\n    if default == None:\r\n     raise NoOptionError(option)\r\n    else:\r\n     return default\r\n  else:\r\n   raise NoSectionError(section)",
    "docstring": "Returns the option's value converted into it's intended type. If default is specified, return that on failure, else raise NoOptionError."
  },
  {
    "code": "def adapt_files(solver):\n    print(\"adapting {0}'s files\".format(solver))\n    root = os.path.join('solvers', solver)\n    for arch in to_extract[solver]:\n        arch = os.path.join(root, arch)\n        extract_archive(arch, solver, put_inside=True)\n    for fnames in to_move[solver]:\n        old = os.path.join(root, fnames[0])\n        new = os.path.join(root, fnames[1])\n        os.rename(old, new)\n    for f in to_remove[solver]:\n        f = os.path.join(root, f)\n        if os.path.isdir(f):\n            shutil.rmtree(f)\n        else:\n            os.remove(f)",
    "docstring": "Rename and remove files whenever necessary."
  },
  {
    "code": "def fillna(self, value=None, method=None, limit=None):\n        if ((method is None and value is None) or\n                (method is not None and value is not None)):\n            raise ValueError(\"Must specify one of 'method' or 'value'.\")\n        elif method is not None:\n            msg = \"fillna with 'method' requires high memory usage.\"\n            warnings.warn(msg, PerformanceWarning)\n            filled = interpolate_2d(np.asarray(self), method=method,\n                                    limit=limit)\n            return type(self)(filled, fill_value=self.fill_value)\n        else:\n            new_values = np.where(isna(self.sp_values), value, self.sp_values)\n            if self._null_fill_value:\n                new_dtype = SparseDtype(self.dtype.subtype, fill_value=value)\n            else:\n                new_dtype = self.dtype\n        return self._simple_new(new_values, self._sparse_index, new_dtype)",
    "docstring": "Fill missing values with `value`.\n\n        Parameters\n        ----------\n        value : scalar, optional\n        method : str, optional\n\n            .. warning::\n\n               Using 'method' will result in high memory use,\n               as all `fill_value` methods will be converted to\n               an in-memory ndarray\n\n        limit : int, optional\n\n        Returns\n        -------\n        SparseArray\n\n        Notes\n        -----\n        When `value` is specified, the result's ``fill_value`` depends on\n        ``self.fill_value``. The goal is to maintain low-memory use.\n\n        If ``self.fill_value`` is NA, the result dtype will be\n        ``SparseDtype(self.dtype, fill_value=value)``. This will preserve\n        amount of memory used before and after filling.\n\n        When ``self.fill_value`` is not NA, the result dtype will be\n        ``self.dtype``. Again, this preserves the amount of memory used."
  },
  {
    "code": "def _get_lrs(self, indices):\n        if self.lr_scheduler is not None:\n            lr = self.lr_scheduler(self.num_update)\n        else:\n            lr = self.lr\n        lrs = [lr for _ in indices]\n        for i, index in enumerate(indices):\n            if index in self.param_dict:\n                lrs[i] *= self.param_dict[index].lr_mult\n            elif index in self.lr_mult:\n                lrs[i] *= self.lr_mult[index]\n            elif index in self.idx2name:\n                lrs[i] *= self.lr_mult.get(self.idx2name[index], 1.0)\n        return lrs",
    "docstring": "Gets the learning rates given the indices of the weights.\n\n        Parameters\n        ----------\n        indices : list of int\n            Indices corresponding to weights.\n\n        Returns\n        -------\n        lrs : list of float\n            Learning rates for those indices."
  },
  {
    "code": "def huffman_encode(cls, s):\n        i = 0\n        ibl = 0\n        for c in s:\n            val, bl = cls._huffman_encode_char(c)\n            i = (i << bl) + val\n            ibl += bl\n        padlen = 8 - (ibl % 8)\n        if padlen != 8:\n            val, bl = cls._huffman_encode_char(EOS())\n            i = (i << padlen) + (val >> (bl - padlen))\n            ibl += padlen\n        ret = i, ibl\n        assert(ret[0] >= 0)\n        assert (ret[1] >= 0)\n        return ret",
    "docstring": "huffman_encode returns the bitstring and the bitlength of the\n        bitstring representing the string provided as a parameter\n\n        @param str s: the string to encode\n        @return (int, int): the bitstring of s and its bitlength\n        @raise AssertionError"
  },
  {
    "code": "def _call(self, x, out=None):\n        if out is None:\n            out = x[self.index].copy()\n        else:\n            out.assign(x[self.index])\n        return out",
    "docstring": "Project ``x`` onto the subspace."
  },
  {
    "code": "def setup_prj_page(self, ):\n        self.prj_seq_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)\n        self.prj_atype_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)\n        self.prj_dep_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)\n        self.prj_user_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)",
    "docstring": "Create and set the model on the project page\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def to_dict(self):\n        mydict = {'id': self.id, 'name': self.name,\n                  'description': self.description,\n                  'kbtype': self.kbtype}\n        if self.kbtype == 'd':\n            mydict.update((self.kbdefs.to_dict() if self.kbdefs else {}) or {})\n        return mydict",
    "docstring": "Return a dict representation of KnwKB."
  },
  {
    "code": "def delete_insight(self, project_key, insight_id):\n        projectOwner, projectId = parse_dataset_key(project_key)\n        try:\n            self._insights_api.delete_insight(projectOwner,\n                                              projectId,\n                                              insight_id)\n        except _swagger.rest.ApiException as e:\n            raise RestApiError(cause=e)",
    "docstring": "Delete an existing insight.\n\n        :params project_key: Project identifier, in the form of\n        projectOwner/projectId\n        :type project_key: str\n        :params insight_id: Insight unique id\n        :type insight_id: str\n        :raises RestApiException: If a server error occurs\n\n        Examples\n        --------\n        >>> import datadotworld as dw\n        >>> api_client = dw.api_client()\n        >>> del_insight = api_client.delete_insight(\n        ...     'username/project', 'insightid')  # doctest: +SKIP"
  },
  {
    "code": "def dump(obj, fp):\n    encoder = ArffEncoder()\n    generator = encoder.iter_encode(obj)\n    last_row = next(generator)\n    for row in generator:\n        fp.write(last_row + u'\\n')\n        last_row = row\n    fp.write(last_row)\n    return fp",
    "docstring": "Serialize an object representing the ARFF document to a given file-like\n    object.\n\n    :param obj: a dictionary.\n    :param fp: a file-like object."
  },
  {
    "code": "def power(base, exp):\n    return _ufunc_helper(\n        base,\n        exp,\n        op.broadcast_power,\n        operator.pow,\n        _internal._power_scalar,\n        _internal._rpower_scalar)",
    "docstring": "Returns result of first array elements raised to powers from second array, element-wise\n    with broadcasting.\n\n    Equivalent to ``base ** exp`` and ``mx.nd.broadcast_power(lhs, rhs)``.\n\n    .. note::\n\n       If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n       then the arrays are broadcastable to a common shape.\n\n    Parameters\n    ----------\n    base : scalar or NDArray\n         The base array\n    exp : scalar or NDArray\n         The exponent array. If ``base.shape != exp.shape``, they must be\n        broadcastable to a common shape.\n\n    Returns\n    --------\n    NDArray\n        The bases in x raised to the exponents in y.\n\n    Examples\n    --------\n    >>> x = mx.nd.ones((2,3))*2\n    >>> y = mx.nd.arange(1,3).reshape((2,1))\n    >>> z = mx.nd.arange(1,3).reshape((2,1))\n    >>> x.asnumpy()\n    array([[ 2.,  2.,  2.],\n           [ 2.,  2.,  2.]], dtype=float32)\n    >>> y.asnumpy()\n    array([[ 1.],\n           [ 2.]], dtype=float32)\n    >>> z.asnumpy()\n    array([[ 1.],\n           [ 2.]], dtype=float32)\n    >>> (x**2).asnumpy()\n    array([[ 4.,  4.,  4.],\n           [ 4.,  4.,  4.]], dtype=float32)\n    >>> (x**y).asnumpy()\n    array([[ 2.,  2.,  2.],\n           [ 4.,  4.,  4.]], dtype=float32)\n    >>> mx.nd.power(x,y).asnumpy()\n    array([[ 2.,  2.,  2.],\n           [ 4.,  4.,  4.]], dtype=float32)\n    >>> (z**y).asnumpy()\n    array([[ 1.],\n           [ 4.]], dtype=float32)"
  },
  {
    "code": "def gradient(poly):\n    return differential(poly, chaospy.poly.collection.basis(1, 1, poly.dim))",
    "docstring": "Gradient of a polynomial.\n\n    Args:\n        poly (Poly) : polynomial to take gradient of.\n\n    Returns:\n        (Poly) : The resulting gradient.\n\n    Examples:\n        >>> q0, q1, q2 = chaospy.variable(3)\n        >>> poly = 2*q0 + q1*q2\n        >>> print(chaospy.gradient(poly))\n        [2, q2, q1]"
  },
  {
    "code": "async def get_alarms():\n    async with aiohttp.ClientSession() as session:\n        ghlocalapi = Alarms(LOOP, session, IPADDRESS)\n        await ghlocalapi.get_alarms()\n        print(\"Alarms:\", ghlocalapi.alarms)",
    "docstring": "Get alarms and timers from GH."
  },
  {
    "code": "def winddir_text(pts):\n    \"Convert wind direction from 0..15 to compass point text\"\n    global _winddir_text_array\n    if pts is None:\n        return None\n    if not isinstance(pts, int):\n        pts = int(pts + 0.5) % 16\n    if not _winddir_text_array:\n        _ = pywws.localisation.translation.ugettext\n        _winddir_text_array = (\n            _(u'N'), _(u'NNE'), _(u'NE'), _(u'ENE'),\n            _(u'E'), _(u'ESE'), _(u'SE'), _(u'SSE'),\n            _(u'S'), _(u'SSW'), _(u'SW'), _(u'WSW'),\n            _(u'W'), _(u'WNW'), _(u'NW'), _(u'NNW'),\n            )\n    return _winddir_text_array[pts]",
    "docstring": "Convert wind direction from 0..15 to compass point text"
  },
  {
    "code": "def _format_metric_name(self, m_name, cfunc):\n        try:\n            aggr = CFUNC_TO_AGGR[cfunc]\n        except KeyError:\n            aggr = cfunc.lower()\n        try:\n            m_name = CACTI_TO_DD[m_name]\n            if aggr != 'avg':\n                m_name += '.{}'.format(aggr)\n            return m_name\n        except KeyError:\n            return \"cacti.{}.{}\".format(m_name.lower(), aggr)",
    "docstring": "Format a cacti metric name into a Datadog-friendly name"
  },
  {
    "code": "def fit_gaussian(x, y, yerr, p0):\n    try:\n        popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True)\n    except RuntimeError:\n        return [0],[0]\n    return popt, pcov",
    "docstring": "Fit a Gaussian to the data"
  },
  {
    "code": "def _align_bags(predicted: List[Set[str]], gold: List[Set[str]]) -> List[float]:\n    f1_scores = []\n    for gold_index, gold_item in enumerate(gold):\n        max_f1 = 0.0\n        max_index = None\n        best_alignment: Tuple[Set[str], Set[str]] = (set(), set())\n        if predicted:\n            for pred_index, pred_item in enumerate(predicted):\n                current_f1 = _compute_f1(pred_item, gold_item)\n                if current_f1 >= max_f1:\n                    best_alignment = (gold_item, pred_item)\n                    max_f1 = current_f1\n                    max_index = pred_index\n            match_flag = _match_numbers_if_present(*best_alignment)\n            gold[gold_index] = set()\n            predicted[max_index] = set()\n        else:\n            match_flag = False\n        if match_flag:\n            f1_scores.append(max_f1)\n        else:\n            f1_scores.append(0.0)\n    return f1_scores",
    "docstring": "Takes gold and predicted answer sets and first finds a greedy 1-1 alignment\n    between them and gets maximum metric values over all the answers"
  },
  {
    "code": "def _on_report(_loop, adapter, conn_id, report):\n    conn_string = None\n    if conn_id is not None:\n        conn_string = adapter._get_property(conn_id, 'connection_string')\n    if isinstance(report, BroadcastReport):\n        adapter.notify_event_nowait(conn_string, 'broadcast', report)\n    elif conn_string is not None:\n        adapter.notify_event_nowait(conn_string, 'report', report)\n    else:\n        adapter._logger.debug(\"Dropping report with unknown conn_id=%s\", conn_id)",
    "docstring": "Callback when a report is received."
  },
  {
    "code": "def calc_progress(self, completed_count, total_count):\n        self.logger.debug(\n            \"calc_progress(%s, %s)\",\n            completed_count,\n            total_count,\n        )\n        current_time = time.time()\n        time_spent = current_time - self.start_time\n        self.logger.debug(\"Progress time spent: %s\", time_spent)\n        if total_count == 0:\n            return 100, 1\n        completion_fraction = completed_count / total_count\n        if completion_fraction == 0:\n            completion_fraction = 1\n        total_time = 0\n        total_time = time_spent / completion_fraction\n        time_remaining = total_time - time_spent\n        completion_display = completion_fraction * 100\n        if completion_display == 100:\n            return 100, 1\n        return completion_display, time_remaining",
    "docstring": "Calculate the percentage progress and estimated remaining time based on\n        the current number of items completed of the total.\n\n        Returns a tuple of ``(percentage_complete, seconds_remaining)``."
  },
  {
    "code": "def createService(self, createServiceParameter,\n                      description=None,\n                      tags=\"Feature Service\",\n                      snippet=None):\n        url = \"%s/createService\" % self.location\n        val = createServiceParameter.value\n        params = {\n            \"f\" : \"json\",\n            \"outputType\" : \"featureService\",\n            \"createParameters\" : json.dumps(val),\n            \"tags\" : tags\n        }\n        if snippet is not None:\n            params['snippet'] = snippet\n        if description is not None:\n            params['description'] = description\n        res =  self._post(url=url,\n                             param_dict=params,\n                             securityHandler=self._securityHandler,\n                             proxy_port=self._proxy_port,\n                             proxy_url=self._proxy_url)\n        if 'id' in res or \\\n           'serviceItemId' in res:\n            if 'id' in res:\n                url = \"%s/items/%s\" % (self.location, res['id'])\n            else:\n                url = \"%s/items/%s\" % (self.location, res['serviceItemId'])\n            return UserItem(url=url,\n                            securityHandler=self._securityHandler,\n                            proxy_url=self._proxy_url,\n                            proxy_port=self._proxy_port)\n        return res",
    "docstring": "The Create Service operation allows users to create a hosted\n        feature service. You can use the API to create an empty hosted\n        feaure service from feature service metadata JSON.\n\n        Inputs:\n           createServiceParameter - create service object"
  },
  {
    "code": "def _get_best_prediction(self, record, train=True):\n        if not self.trees:\n            return\n        best = (+1e999999, None)\n        for tree in self.trees:\n            best = min(best, (tree.mae.mean, tree))\n        _, best_tree = best\n        prediction, tree_mae = best_tree.predict(record, train=train)\n        return prediction.mean",
    "docstring": "Gets the prediction from the tree with the lowest mean absolute error."
  },
  {
    "code": "def check_in(choices, **params):\n    for p in params:\n        if params[p] not in choices:\n            raise ValueError(\n                \"{} value {} not recognized. Choose from {}\".format(\n                    p, params[p], choices))",
    "docstring": "Checks parameters are in a list of allowed parameters\n\n    Parameters\n    ----------\n\n    choices : array-like, accepted values\n\n    params : object\n        Named arguments, parameters to be checked\n\n    Raises\n    ------\n    ValueError : unacceptable choice of parameters"
  },
  {
    "code": "def write_frames(self, frames_out):\n        self.check_for_errors()\n        self._connection.write_frames(self.channel_id, frames_out)",
    "docstring": "Write multiple pamqp frames from the current channel.\n\n        :param list frames_out: A list of pamqp frames.\n\n        :return:"
  },
  {
    "code": "def connections(self):\n        conn = lambda x: str(x).replace('connection:', '')\n        return [conn(name) for name in self.sections()]",
    "docstring": "Returns all of the loaded connections names as a list"
  },
  {
    "code": "def circuit_to_pyquil(circuit: Circuit) -> pyquil.Program:\n    prog = pyquil.Program()\n    for elem in circuit.elements:\n        if isinstance(elem, Gate) and elem.name in QUIL_GATES:\n            params = list(elem.params.values()) if elem.params else []\n            prog.gate(elem.name, params, elem.qubits)\n        elif isinstance(elem, Measure):\n            prog.measure(elem.qubit, elem.cbit)\n        else:\n            raise ValueError('Cannot convert operation to pyquil')\n    return prog",
    "docstring": "Convert a QuantumFlow circuit to a pyQuil program"
  },
  {
    "code": "def getBounds(self, tzinfo=None):\n        if self.resolution >= datetime.timedelta(days=1) \\\n        and tzinfo is not None:\n            time = self._time.replace(tzinfo=tzinfo)\n        else:\n            time = self._time\n        return (\n            min(self.fromDatetime(time), self.fromDatetime(self._time)),\n            max(self.fromDatetime(time + self.resolution),\n                self.fromDatetime(self._time + self.resolution))\n        )",
    "docstring": "Return a pair describing the bounds of self.\n\n        This returns a pair (min, max) of Time instances. It is not quite the\n        same as (self, self + self.resolution). This is because timezones are\n        insignificant for instances with a resolution greater or equal to 1\n        day.\n\n        To illustrate the problem, consider a Time instance::\n\n            T = Time.fromHumanly('today', tzinfo=anything)\n\n        This will return an equivalent instance independent of the tzinfo used.\n        The hour, minute, and second of this instance are 0, and its resolution\n        is one day.\n\n        Now say we have a sorted list of times, and we want to get all times\n        for 'today', where whoever said 'today' is in a timezone that's 5 hours\n        ahead of UTC. The start of 'today' in this timezone is UTC 05:00. The\n        example instance T above is before this, but obviously it is today.\n\n        The min and max times this returns are such that all potentially\n        matching instances are within this range. However, this range might\n        contain unmatching instances.\n\n        As an example of this, if 'today' is April first 2005, then\n        Time.fromISO8601TimeAndDate('2005-04-01T00:00:00') sorts in the same\n        place as T from above, but is not in the UTC+5 'today'.\n\n        TIME IS FUN!"
  },
  {
    "code": "def Analyze(self, hashes):\n    hash_analyses = []\n    for digest in hashes:\n      json_response = self._QueryHash(digest)\n      hash_analysis = interface.HashAnalysis(digest, json_response)\n      hash_analyses.append(hash_analysis)\n    return hash_analyses",
    "docstring": "Looks up hashes in Viper using the Viper HTTP API.\n\n    Args:\n      hashes (list[str]): hashes to look up.\n\n    Returns:\n      list[HashAnalysis]: hash analysis.\n\n    Raises:\n      RuntimeError: If no host has been set for Viper."
  },
  {
    "code": "def check_url (aggregate):\n    while True:\n        try:\n            aggregate.urlqueue.join(timeout=30)\n            break\n        except urlqueue.Timeout:\n            aggregate.remove_stopped_threads()\n            if not any(aggregate.get_check_threads()):\n                break",
    "docstring": "Helper function waiting for URL queue."
  },
  {
    "code": "def save(self, t, base=0, heap=False):\n        c, k = _keytuple(t)\n        if k and k not in _typedefs:\n            _typedefs[k] = self\n            if c and c not in _typedefs:\n                if t.__module__ in _builtin_modules:\n                    k = _kind_ignored\n                else:\n                    k = self.kind\n                _typedefs[c] = _Typedef(base=_basicsize(type(t), base=base, heap=heap),\n                                        refs=_type_refs,\n                                        both=False, kind=k, type=t)\n        elif isbuiltin(t) and t not in _typedefs:\n            _typedefs[t] = _Typedef(base=_basicsize(t, base=base),\n                                    both=False, kind=_kind_ignored, type=t)\n        else:\n            raise KeyError('asizeof typedef %r bad: %r %r' % (self, (c, k), self.both))",
    "docstring": "Save this typedef plus its class typedef."
  },
  {
    "code": "def cleanup_virtualenv(bare=True):\n    if not bare:\n        click.echo(crayons.red(\"Environment creation aborted.\"))\n    try:\n        vistir.path.rmtree(project.virtualenv_location)\n    except OSError as e:\n        click.echo(\n            \"{0} An error occurred while removing {1}!\".format(\n                crayons.red(\"Error: \", bold=True),\n                crayons.green(project.virtualenv_location),\n            ),\n            err=True,\n        )\n        click.echo(crayons.blue(e), err=True)",
    "docstring": "Removes the virtualenv directory from the system."
  },
  {
    "code": "def calendar_dates(self, val):\n        self._calendar_dates = val\n        if val is not None and not val.empty:\n            self._calendar_dates_g = self._calendar_dates.groupby(\n                [\"service_id\", \"date\"]\n            )\n        else:\n            self._calendar_dates_g = None",
    "docstring": "Update ``self._calendar_dates_g``\n        if ``self.calendar_dates`` changes."
  },
  {
    "code": "def configure_sources(update=False,\n                      sources_var='install_sources',\n                      keys_var='install_keys'):\n    sources = safe_load((config(sources_var) or '').strip()) or []\n    keys = safe_load((config(keys_var) or '').strip()) or None\n    if isinstance(sources, six.string_types):\n        sources = [sources]\n    if keys is None:\n        for source in sources:\n            add_source(source, None)\n    else:\n        if isinstance(keys, six.string_types):\n            keys = [keys]\n        if len(sources) != len(keys):\n            raise SourceConfigError(\n                'Install sources and keys lists are different lengths')\n        for source, key in zip(sources, keys):\n            add_source(source, key)\n    if update:\n        _fetch_update(fatal=True)",
    "docstring": "Configure multiple sources from charm configuration.\n\n    The lists are encoded as yaml fragments in the configuration.\n    The fragment needs to be included as a string. Sources and their\n    corresponding keys are of the types supported by add_source().\n\n    Example config:\n        install_sources: |\n          - \"ppa:foo\"\n          - \"http://example.com/repo precise main\"\n        install_keys: |\n          - null\n          - \"a1b2c3d4\"\n\n    Note that 'null' (a.k.a. None) should not be quoted."
  },
  {
    "code": "def _check_certificate(self):\n        if (self.file_name.startswith(\"jdk-\") and self.repo == \"sbo\" and\n                self.downder == \"wget\"):\n            certificate = (' --no-check-certificate --header=\"Cookie: '\n                           'oraclelicense=accept-securebackup-cookie\"')\n            self.msg.template(78)\n            print(\"| '{0}' need to go ahead downloading\".format(\n                certificate[:23].strip()))\n            self.msg.template(78)\n            print(\"\")\n            self.downder_options += certificate\n            if not self.msg.answer() in [\"y\", \"Y\"]:\n                raise SystemExit()",
    "docstring": "Check for certificates options for wget"
  },
  {
    "code": "def _filter_data(self, pattern):\n        removed = []\n        filtered = []\n        for param in self.data:\n            if not param[0].startswith(pattern):\n                filtered.append(param)\n            else:\n                removed.append(param)\n        self.data = filtered\n        return removed",
    "docstring": "Removes parameters which match the pattern from the config data"
  },
  {
    "code": "def context(self, name):\n        data = self._context(name)\n        context = data.get(\"context\")\n        if context:\n            return context\n        assert self.load_path\n        context_path = os.path.join(self.load_path, \"contexts\", \"%s.rxt\" % name)\n        context = ResolvedContext.load(context_path)\n        data[\"context\"] = context\n        data[\"loaded\"] = True\n        return context",
    "docstring": "Get a context.\n\n        Args:\n            name (str): Name to store the context under.\n\n        Returns:\n            `ResolvedContext` object."
  },
  {
    "code": "def get_following(self, auth_secret):\n        result = {pytwis_constants.ERROR_KEY: None}\n        loggedin, userid = self._is_loggedin(auth_secret)\n        if not loggedin:\n            result[pytwis_constants.ERROR_KEY] = pytwis_constants.ERROR_NOT_LOGGED_IN\n            return (False, result)\n        following_zset_key = pytwis_constants.FOLLOWING_KEY_FORMAT.format(userid)\n        following_userids = self._rc.zrange(following_zset_key, 0, -1)\n        if following_userids is None or not following_userids:\n            result[pytwis_constants.FOLLOWING_LIST_KEY] = []\n            return (True, result)\n        with self._rc.pipeline() as pipe:\n            pipe.multi()\n            for following_userid in following_userids:\n                following_userid_profile_key = \\\n                    pytwis_constants.USER_PROFILE_KEY_FORMAT.format(following_userid)\n                pipe.hget(following_userid_profile_key, pytwis_constants.USERNAME_KEY)\n            result[pytwis_constants.FOLLOWING_LIST_KEY] = pipe.execute()\n        return (True, result)",
    "docstring": "Get the following list of a logged-in user.\n\n        Parameters\n        ----------\n        auth_secret: str\n            The authentication secret of the logged-in user.\n\n        Returns\n        -------\n        bool\n            True if the following list is successfully obtained, False otherwise.\n        result\n            A dict containing the following list with the key FOLLOWING_LIST_KEY\n            if the follower list is successfully obtained, a dict containing\n            the error string with the key ERROR_KEY otherwise.\n\n        Note\n        ----\n        Possible error strings are listed as below:\n\n        -  ERROR_NOT_LOGGED_IN"
  },
  {
    "code": "def get_copy_folder_location():\n    copy_settings_path = 'Library/Application Support/Copy Agent/config.db'\n    copy_home = None\n    copy_settings = os.path.join(os.environ['HOME'], copy_settings_path)\n    if os.path.isfile(copy_settings):\n        database = sqlite3.connect(copy_settings)\n        if database:\n            cur = database.cursor()\n            query = (\"SELECT value \"\n                     \"FROM config2 \"\n                     \"WHERE option = 'csmRootPath';\")\n            cur.execute(query)\n            data = cur.fetchone()\n            copy_home = str(data[0])\n            cur.close()\n    if not copy_home:\n        error(\"Unable to find your Copy install =(\")\n    return copy_home",
    "docstring": "Try to locate the Copy folder.\n\n    Returns:\n        (str) Full path to the current Copy folder"
  },
  {
    "code": "def iq_handler(type_, payload_cls, *, with_send_reply=False):\n    if (not hasattr(payload_cls, \"TAG\") or\n            (aioxmpp.IQ.CHILD_MAP.get(payload_cls.TAG) is not\n             aioxmpp.IQ.payload.xq_descriptor) or\n            payload_cls not in aioxmpp.IQ.payload._classes):\n        raise ValueError(\n            \"{!r} is not a valid IQ payload \"\n            \"(use IQ.as_payload_class decorator)\".format(\n                payload_cls,\n            )\n        )\n    def decorator(f):\n        add_handler_spec(\n            f,\n            HandlerSpec(\n                (_apply_iq_handler, (type_, payload_cls)),\n                require_deps=(),\n            ),\n            kwargs=dict(with_send_reply=with_send_reply),\n        )\n        return f\n    return decorator",
    "docstring": "Register the decorated function or coroutine function as IQ request\n    handler.\n\n    :param type_: IQ type to listen for\n    :type type_: :class:`~.IQType`\n    :param payload_cls: Payload XSO class to listen for\n    :type payload_cls: :class:`~.XSO` subclass\n    :param with_send_reply: Whether to pass a function to send a reply\n       to the decorated callable as second argument.\n    :type with_send_reply: :class:`bool`\n\n    :raises ValueError: if `payload_cls` is not a registered IQ payload\n\n    If the decorated function is not a coroutine function, it must return an\n    awaitable instead.\n\n    .. seealso::\n\n        :meth:`~.StanzaStream.register_iq_request_handler` for more\n            details on the `type_`, `payload_cls` and\n            `with_send_reply` arguments, as well as behaviour expected\n            from the decorated function.\n\n        :meth:`aioxmpp.IQ.as_payload_class`\n            for a way to register a XSO as IQ payload\n\n    .. versionadded:: 0.11\n\n       The `with_send_reply` argument.\n\n    .. versionchanged:: 0.10\n\n        The decorator now checks if `payload_cls` is a valid, registered IQ\n        payload and raises :class:`ValueError` if not."
  },
  {
    "code": "def get_splitext_basename(path):\n    basename = foundations.common.get_first_item(os.path.splitext(os.path.basename(os.path.normpath(path))))\n    LOGGER.debug(\"> Splitext basename: '{0}'.\".format(basename))\n    return basename",
    "docstring": "Gets the basename of a path without its extension.\n\n    Usage::\n\n        >>> get_splitext_basename(\"/Users/JohnDoe/Documents/Test.txt\")\n        u'Test'\n\n    :param path: Path to extract the basename without extension.\n    :type path: unicode\n    :return: Splitext basename.\n    :rtype: unicode"
  },
  {
    "code": "def as_statements(lines: Iterator[str]) -> Iterator[str]:\n    lines = (l.strip() for l in lines if l)\n    lines = (l for l in lines if l and not l.startswith('--'))\n    parts = []\n    for line in lines:\n        parts.append(line.rstrip(';'))\n        if line.endswith(';'):\n            yield ' '.join(parts)\n            parts.clear()\n    if parts:\n        yield ' '.join(parts)",
    "docstring": "Create an iterator that transforms lines into sql statements.\n\n    Statements within the lines must end with \";\"\n    The last statement will be included even if it does not end in ';'\n\n    >>> list(as_statements(['select * from', '-- comments are filtered', 't;']))\n    ['select * from t']\n\n    >>> list(as_statements(['a;', 'b', 'c;', 'd', ' ']))\n    ['a', 'b c', 'd']"
  },
  {
    "code": "def retrieve(customer_id):\n        http_client = HttpClient()\n        response, __ = http_client.get(routes.url(routes.CUSTOMER_RESOURCE, resource_id=customer_id))\n        return resources.Customer(**response)",
    "docstring": "Retrieve a customer from its id.\n\n        :param customer_id: The customer id\n        :type customer_id: string\n\n        :return: The customer resource\n        :rtype: resources.Customer"
  },
  {
    "code": "def read(self, size):\n        raw_read = super(USBRawDevice, self).read\n        received = bytearray()\n        while not len(received) >= size:\n            resp = raw_read(self.RECV_CHUNK)\n            received.extend(resp)\n        return bytes(received)",
    "docstring": "Read raw bytes from the instrument.\n\n        :param size: amount of bytes to be sent to the instrument\n        :type size: integer\n        :return: received bytes\n        :return type: bytes"
  },
  {
    "code": "def _start_thread(self):\n        self._stopping_event = Event()\n        self._enqueueing_thread = Thread(target=self._enqueue_batches, args=(self._stopping_event,))\n        self._enqueueing_thread.start()",
    "docstring": "Start an enqueueing thread."
  },
  {
    "code": "def _createEmptyJobGraphForJob(self, jobStore, command=None, predecessorNumber=0):\n        self._config = jobStore.config\n        return jobStore.create(JobNode.fromJob(self, command=command,\n                                               predecessorNumber=predecessorNumber))",
    "docstring": "Create an empty job for the job."
  },
  {
    "code": "def docsfor(self, rel):\n        prefix, _rel = rel.split(':')\n        if prefix in self.curies:\n            doc_url = uritemplate.expand(self.curies[prefix], {'rel': _rel})\n        else:\n            doc_url = rel\n        print('opening', doc_url)\n        webbrowser.open(doc_url)",
    "docstring": "Obtains the documentation for a link relation. Opens in a webbrowser\n        window"
  },
  {
    "code": "def search_suggestion(self, query):\n\t\tresponse = self._call(\n\t\t\tmc_calls.QuerySuggestion,\n\t\t\tquery\n\t\t)\n\t\tsuggested_queries = response.body.get('suggested_queries', [])\n\t\treturn [\n\t\t\tsuggested_query['suggestion_string']\n\t\t\tfor suggested_query in suggested_queries\n\t\t]",
    "docstring": "Get search query suggestions for query.\n\n\t\tParameters:\n\t\t\tquery (str): Search text.\n\n\t\tReturns:\n\t\t\tlist: Suggested query strings."
  },
  {
    "code": "def remove(self, oid):\n        uri = self._resources[oid].uri\n        del self._resources[oid]\n        del self._hmc.all_resources[uri]",
    "docstring": "Remove a faked resource from this manager.\n\n        Parameters:\n\n          oid (string):\n            The object ID of the resource (e.g. value of the 'object-uri'\n            property)."
  },
  {
    "code": "def _handle_error(self, data, params):\n        error = data.get('error', 'API call failed')\n        mode = params.get('mode')\n        raise SabnzbdApiException(error, mode=mode)",
    "docstring": "Handle an error response from the SABnzbd API"
  },
  {
    "code": "def _setup_xauth(self):\n        handle, filename = tempfile.mkstemp(prefix='PyVirtualDisplay.',\n                                            suffix='.Xauthority')\n        self._xauth_filename = filename\n        os.close(handle)\n        self._old_xauth = {}\n        self._old_xauth['AUTHFILE'] = os.getenv('AUTHFILE')\n        self._old_xauth['XAUTHORITY'] = os.getenv('XAUTHORITY')\n        os.environ['AUTHFILE'] = os.environ['XAUTHORITY'] = filename\n        cookie = xauth.generate_mcookie()\n        xauth.call('add', self.new_display_var, '.', cookie)",
    "docstring": "Set up the Xauthority file and the XAUTHORITY environment variable."
  },
  {
    "code": "def get_qemu_info(path, backing_chain=False, fail_on_error=True):\n    cmd = ['qemu-img', 'info', '--output=json', path]\n    if backing_chain:\n        cmd.insert(-1, '--backing-chain')\n    result = run_command_with_validation(\n        cmd, fail_on_error, msg='Failed to get info for {}'.format(path)\n    )\n    return json.loads(result.out)",
    "docstring": "Get info on a given qemu disk\n\n    Args:\n        path(str): Path to the required disk\n        backing_chain(boo): if true, include also info about\n        the image predecessors.\n    Return:\n        object: if backing_chain == True then a list of dicts else a dict"
  },
  {
    "code": "def copy(self):\n        if self._global_condition is not None:\n            raise SimStateError(\"global condition was not cleared before state.copy().\")\n        c_plugins = self._copy_plugins()\n        state = SimState(project=self.project, arch=self.arch, plugins=c_plugins, options=self.options.copy(),\n                         mode=self.mode, os_name=self.os_name)\n        if self._is_java_jni_project:\n            state.ip_is_soot_addr = self.ip_is_soot_addr\n        state.uninitialized_access_handler = self.uninitialized_access_handler\n        state._special_memory_filler = self._special_memory_filler\n        state.ip_constraints = self.ip_constraints\n        return state",
    "docstring": "Returns a copy of the state."
  },
  {
    "code": "def _match_exists(self, searchable):\n        position_searchable = self.get_position_searchable()\n        for pos,val in position_searchable.iteritems():\n            if val == searchable:\n                return pos\n        return False",
    "docstring": "Make sure the searchable description doesn't already exist"
  },
  {
    "code": "def extract_objects(self, fname, type_filter=None):\n    objects = []\n    if fname in self.object_cache:\n      objects = self.object_cache[fname]\n    else:\n      with io.open(fname, 'rt', encoding='utf-8') as fh:\n        text = fh.read()\n        objects = parse_verilog(text)\n        self.object_cache[fname] = objects\n    if type_filter:\n      objects = [o for o in objects if isinstance(o, type_filter)]\n    return objects",
    "docstring": "Extract objects from a source file\n\n    Args:\n      fname(str): Name of file to read from\n      type_filter (class, optional): Object class to filter results\n    Returns:\n      List of objects extracted from the file."
  },
  {
    "code": "def get_synth_input_fn(height, width, num_channels, num_classes):\n  def input_fn(is_training, data_dir, batch_size, *args, **kwargs):\n    images = tf.zeros((batch_size, height, width, num_channels), tf.float32)\n    labels = tf.zeros((batch_size, num_classes), tf.int32)\n    return tf.data.Dataset.from_tensors((images, labels)).repeat()\n  return input_fn",
    "docstring": "Returns an input function that returns a dataset with zeroes.\n\n  This is useful in debugging input pipeline performance, as it removes all\n  elements of file reading and image preprocessing.\n\n  Args:\n    height: Integer height that will be used to create a fake image tensor.\n    width: Integer width that will be used to create a fake image tensor.\n    num_channels: Integer depth that will be used to create a fake image tensor.\n    num_classes: Number of classes that should be represented in the fake labels\n      tensor\n\n  Returns:\n    An input_fn that can be used in place of a real one to return a dataset\n    that can be used for iteration."
  },
  {
    "code": "def bootstrap(score_objs, n_boot=1000):\n    all_samples = np.random.choice(score_objs, size=(n_boot, len(score_objs)), replace=True)\n    return all_samples.sum(axis=1)",
    "docstring": "Given a set of DistributedROC or DistributedReliability objects, this function performs a\n    bootstrap resampling of the objects and returns n_boot aggregations of them.\n\n    Args:\n        score_objs: A list of DistributedROC or DistributedReliability objects. Objects must have an __add__ method\n        n_boot (int): Number of bootstrap samples\n\n    Returns:\n        An array of DistributedROC or DistributedReliability"
  },
  {
    "code": "def _get_calling_module(self):\n        for frame in inspect.stack():\n            mod = inspect.getmodule(frame[0])\n            logger.debug(f'calling module: {mod}')\n            if mod is not None:\n                mod_name = mod.__name__\n                if mod_name != __name__:\n                    return mod",
    "docstring": "Get the last module in the call stack that is not this module or ``None`` if\n        the call originated from this module."
  },
  {
    "code": "def lookup(self, req, parent, name):\n        self.reply_err(req, errno.ENOENT)",
    "docstring": "Look up a directory entry by name and get its attributes.\n\n        Valid replies:\n            reply_entry\n            reply_err"
  },
  {
    "code": "def get_comment_create_data(self):\n        user_model = get_user_model()\n        return dict(\n            content_type=ContentType.objects.get_for_model(self.target_object),\n            object_pk=force_text(self.target_object._get_pk_val()),\n            text=self.cleaned_data[\"text\"],\n            user=user_model.objects.latest('id'),\n            post_date=timezone.now(),\n            site_id=settings.SITE_ID,\n            is_public=True,\n            is_removed=False,\n        )",
    "docstring": "Returns the dict of data to be used to create a comment. Subclasses in\n        custom comment apps that override get_comment_model can override this\n        method to add extra fields onto a custom comment model."
  },
  {
    "code": "def _process_state_change_events():\n    sdp_state = SDPState()\n    service_states = get_service_state_list()\n    state_events = sdp_state.get_event_queue(subscriber=__service_name__)\n    state_is_off = sdp_state.current_state == 'off'\n    counter = 0\n    while True:\n        time.sleep(0.1)\n        if not state_is_off:\n            if counter % 1000 == 0:\n                LOG.debug('Checking published events ... %d', counter / 1000)\n                _published_events = state_events.get_published_events(\n                    process=True)\n                for _state_event in _published_events:\n                    _process_event(_state_event, sdp_state, service_states)\n            else:\n                _state_event = state_events.get()\n                if _state_event:\n                    _process_event(_state_event, sdp_state, service_states)\n                    state_is_off = sdp_state.current_state == 'off'\n            counter += 1",
    "docstring": "Process events relating to the overall state of SDP.\n\n    This function starts and event loop which continually checks for\n    and responds to SDP state change events."
  },
  {
    "code": "def get_object(self, identifier, include_inactive=False):\n        query = {'_id': identifier}\n        if not include_inactive:\n            query['active'] = True\n        cursor = self.collection.find(query)\n        if cursor.count() > 0:\n            return self.from_dict(cursor.next())\n        else:\n            return None",
    "docstring": "Retrieve object with given identifier from the database.\n\n        Parameters\n        ----------\n        identifier : string\n            Unique object identifier\n        include_inactive : Boolean\n            Flag indicating whether inactive (i.e., deleted) object should be\n            included in the search (i.e., return an object with given\n            identifier if it has been deleted or return None)\n\n        Returns\n        -------\n        (Sub-class of)ObjectHandle\n            The database object with given identifier or None if no object\n            with identifier exists."
  },
  {
    "code": "def require(self, lock, guard_func, *guard_args, **guard_kw):\n        def decorator(f):\n            @wraps(f)\n            def wrapper(*args, **kw):\n                if self.granted(lock):\n                    self.msg('Granted {}'.format(lock))\n                    return f(*args, **kw)\n                if guard_func(*guard_args, **guard_kw) and self.acquire(lock):\n                    return f(*args, **kw)\n                return None\n            return wrapper\n        return decorator",
    "docstring": "Decorate a function to be run only when a lock is acquired.\n\n        The lock is requested if the guard function returns True.\n\n        The decorated function is called if the lock has been granted."
  },
  {
    "code": "def get_resourcegroupitems(group_id, scenario_id, **kwargs):\n    rgi_qry = db.DBSession.query(ResourceGroupItem).\\\n                filter(ResourceGroupItem.scenario_id==scenario_id)\n    if group_id is not None:\n        rgi_qry = rgi_qry.filter(ResourceGroupItem.group_id==group_id)\n    rgi = rgi_qry.all()\n    return rgi",
    "docstring": "Get all the items in a group, in a scenario. If group_id is None, return\n        all items across all groups in the scenario."
  },
  {
    "code": "def publish_topology_opened(self, topology_id):\n        event = TopologyOpenedEvent(topology_id)\n        for subscriber in self.__topology_listeners:\n            try:\n                subscriber.opened(event)\n            except Exception:\n                _handle_exception()",
    "docstring": "Publish a TopologyOpenedEvent to all topology listeners.\n\n        :Parameters:\n         - `topology_id`: A unique identifier for the topology this server\n           is a part of."
  },
  {
    "code": "def uncompress_file(inputfile, filename):\n    zipfile = gzip.GzipFile(fileobj=inputfile, mode=\"rb\")\n    try:\n        outputfile = create_spooled_temporary_file(fileobj=zipfile)\n    finally:\n        zipfile.close()\n    new_basename = os.path.basename(filename).replace('.gz', '')\n    return outputfile, new_basename",
    "docstring": "Uncompress this file using gzip and change its name.\n\n    :param inputfile: File to compress\n    :type inputfile: ``file`` like object\n\n    :param filename: File's name\n    :type filename: ``str``\n\n    :returns: Tuple with file and new file's name\n    :rtype: :class:`tempfile.SpooledTemporaryFile`, ``str``"
  },
  {
    "code": "def load_api_folder(api_folder_path):\n    api_definition_mapping = {}\n    api_items_mapping = load_folder_content(api_folder_path)\n    for api_file_path, api_items in api_items_mapping.items():\n        if isinstance(api_items, list):\n            for api_item in api_items:\n                key, api_dict = api_item.popitem()\n                api_id = api_dict.get(\"id\") or api_dict.get(\"def\") or api_dict.get(\"name\")\n                if key != \"api\" or not api_id:\n                    raise exceptions.ParamsError(\n                        \"Invalid API defined in {}\".format(api_file_path))\n                if api_id in api_definition_mapping:\n                    raise exceptions.ParamsError(\n                        \"Duplicated API ({}) defined in {}\".format(api_id, api_file_path))\n                else:\n                    api_definition_mapping[api_id] = api_dict\n        elif isinstance(api_items, dict):\n            if api_file_path in api_definition_mapping:\n                raise exceptions.ParamsError(\n                    \"Duplicated API defined: {}\".format(api_file_path))\n            else:\n                api_definition_mapping[api_file_path] = api_items\n    return api_definition_mapping",
    "docstring": "load api definitions from api folder.\n\n    Args:\n        api_folder_path (str): api files folder.\n\n            api file should be in the following format:\n            [\n                {\n                    \"api\": {\n                        \"def\": \"api_login\",\n                        \"request\": {},\n                        \"validate\": []\n                    }\n                },\n                {\n                    \"api\": {\n                        \"def\": \"api_logout\",\n                        \"request\": {},\n                        \"validate\": []\n                    }\n                }\n            ]\n\n    Returns:\n        dict: api definition mapping.\n\n            {\n                \"api_login\": {\n                    \"function_meta\": {\"func_name\": \"api_login\", \"args\": [], \"kwargs\": {}}\n                    \"request\": {}\n                },\n                \"api_logout\": {\n                    \"function_meta\": {\"func_name\": \"api_logout\", \"args\": [], \"kwargs\": {}}\n                    \"request\": {}\n                }\n            }"
  },
  {
    "code": "def to_html(self, codebase):\n        body = ''\n        for section in ('params', 'options', 'exceptions'):\n            val = getattr(self, section)\n            if val:\n                body += '<h5>%s</h5>\\n<dl class = \"%s\">%s</dl>' % (\n                        printable(section), section, \n                        '\\n'.join(param.to_html() for param in val))\n        body += codebase.build_see_html(self.see, 'h5', self)\n        return ('<a name = \"%s\" />\\n<div class = \"function\">\\n' + \n                '<h4>%s</h4>\\n%s\\n%s\\n</div>\\n') % (self.name, self.name, \n                    htmlize_paragraphs(codebase.translate_links(self.doc, self)), body)",
    "docstring": "Convert this `FunctionDoc` to HTML."
  },
  {
    "code": "def get_relations_cnt(self):\n        return cx.Counter([e.relation for es in self.exts for e in es])",
    "docstring": "Get the set of all relations."
  },
  {
    "code": "def timdef(action, item, lenout, value=None):\n    action = stypes.stringToCharP(action)\n    item = stypes.stringToCharP(item)\n    lenout = ctypes.c_int(lenout)\n    if value is None:\n        value = stypes.stringToCharP(lenout)\n    else:\n        value = stypes.stringToCharP(value)\n    libspice.timdef_c(action, item, lenout, value)\n    return stypes.toPythonString(value)",
    "docstring": "Set and retrieve the defaults associated with calendar input strings.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/timdef_c.html\n\n    :param action: the kind of action to take \"SET\" or \"GET\".\n    :type action: str\n    :param item: the default item of interest.\n    :type item: str\n    :param lenout: the length of list for output.\n    :type lenout: int\n    :param value: the optional string used if action is \"SET\"\n    :type value: str\n    :return: the value associated with the default item.\n    :rtype: str"
  },
  {
    "code": "def is_obsoleted_by_pid(pid):\n    return d1_gmn.app.models.ScienceObject.objects.filter(\n        obsoleted_by__did=pid\n    ).exists()",
    "docstring": "Return True if ``pid`` is referenced in the obsoletedBy field of any object.\n\n    This will return True even if the PID is in the obsoletes field of an object that\n    does not exist on the local MN, such as replica that is in an incomplete chain."
  },
  {
    "code": "def remove_prefix(self, prefix):\n        self._req('prefix remove %s' % prefix)\n        time.sleep(1)\n        self._req('netdataregister')",
    "docstring": "Remove network prefix."
  },
  {
    "code": "def register_computer_view(request):\n    if request.method == \"POST\":\n        form = ComputerRegistrationForm(request.POST)\n        logger.debug(form)\n        if form.is_valid():\n            obj = form.save()\n            obj.user = request.user\n            obj.save()\n            messages.success(request, \"Successfully added computer.\")\n            return redirect(\"itemreg\")\n        else:\n            messages.error(request, \"Error adding computer.\")\n    else:\n        form = ComputerRegistrationForm()\n    return render(request, \"itemreg/register_form.html\", {\"form\": form, \"action\": \"add\", \"type\": \"computer\", \"form_route\": \"itemreg_computer\"})",
    "docstring": "Register a computer."
  },
  {
    "code": "def random_possible_hands(self):\n        missing = self.missing_values()\n        other_dominoes = [d for p, h in enumerate(self.hands) for d in h if p != self.turn]\n        while True:\n            shuffled_dominoes = (d for d in random.sample(other_dominoes, len(other_dominoes)))\n            hands = []\n            for player, hand in enumerate(self.hands):\n                if player != self.turn:\n                    hand = [next(shuffled_dominoes) for _ in hand]\n                hands.append(dominoes.Hand(hand))\n            if _validate_hands(hands, missing):\n                return hands",
    "docstring": "Returns random possible hands for all players, given the information\n        known by the player whose turn it is. This information includes the\n        current player's hand, the sizes of the other players' hands, and the\n        moves played by every player, including the passes.\n\n        :return: a list of possible Hand objects, corresponding to each player"
  },
  {
    "code": "def number_of_interactions(self, u=None, v=None, t=None):\n        if t is None:\n            if u is None:\n                return int(self.size())\n            elif u is not None and v is not None:\n                if v in self._succ[u]:\n                    return 1\n                else:\n                    return 0\n        else:\n            if u is None:\n                return int(self.size(t))\n            elif u is not None and v is not None:\n                if v in self._succ[u]:\n                    if self.__presence_test(u, v, t):\n                        return 1\n                    else:\n                        return 0",
    "docstring": "Return the number of interaction between two nodes at time t.\n\n        Parameters\n        ----------\n        u, v : nodes, optional (default=all interaction)\n            If u and v are specified, return the number of interaction between\n            u and v. Otherwise return the total number of all interaction.\n        t : snapshot id (default=None)\n            If None will be returned the number of edges on the flattened graph.\n\n        Returns\n        -------\n        nedges : int\n            The number of interaction in the graph.  If nodes u and v are specified\n            return the number of interaction between those nodes. If a single node is specified return None.\n\n        See Also\n        --------\n        size\n\n        Examples\n        --------\n        >>> G = dn.DynDiGraph()\n        >>> G.add_path([0,1,2,3], t=0)\n        >>> G.number_of_interactions()\n        3\n        >>> G.number_of_interactions(0,1, t=0)\n        1\n        >>> G.add_edge(3, 4, t=1)\n        >>> G.number_of_interactions()\n        4"
  },
  {
    "code": "def prepend_status(func):\n    @ft.wraps(func)\n    def wrapper(self, *args, **kwargs):\n        res = func(self, *args, **kwargs)\n        if self.status is not StepResult.UNSET:\n            res = \"[{status}]\".format(status=self.status.name) + res\n        return res\n    return wrapper",
    "docstring": "Prepends the output of `func` with the status."
  },
  {
    "code": "def get_nodes():\n    cfg_file = \"/etc/nago/nago.ini\"\n    config = ConfigParser.ConfigParser()\n    config.read(cfg_file)\n    result = {}\n    for section in config.sections():\n        if section in ['main']:\n            continue\n        token = section\n        node = Node(token)\n        for key, value in config.items(token):\n            node[key] = value\n        result[token] = node\n    return result",
    "docstring": "Returns all nodes in a list of dicts format"
  },
  {
    "code": "def get_time_remaining_estimate(self):\n        if IOPSGetTimeRemainingEstimate is not None:\n            estimate = float(IOPSGetTimeRemainingEstimate())\n            if estimate == -1.0:\n                return common.TIME_REMAINING_UNKNOWN\n            elif estimate == -2.0:\n                return common.TIME_REMAINING_UNLIMITED\n            else:\n                return estimate / 60.0\n        else:\n            warnings.warn(\"IOPSGetTimeRemainingEstimate is not preset\", RuntimeWarning)\n            blob = IOPSCopyPowerSourcesInfo()\n            type = IOPSGetProvidingPowerSourceType(blob)\n            if type == common.POWER_TYPE_AC:\n                return common.TIME_REMAINING_UNLIMITED\n            else:\n                estimate = 0.0\n                for source in IOPSCopyPowerSourcesList(blob):\n                    description = IOPSGetPowerSourceDescription(blob, source)\n                    if kIOPSIsPresentKey in description and description[kIOPSIsPresentKey] and kIOPSTimeToEmptyKey in description and description[kIOPSTimeToEmptyKey] > 0.0:\n                        estimate += float(description[kIOPSTimeToEmptyKey])\n                if estimate > 0.0:\n                    return float(estimate)\n                else:\n                    return common.TIME_REMAINING_UNKNOWN",
    "docstring": "In Mac OS X 10.7+\n        Uses IOPSGetTimeRemainingEstimate to get time remaining estimate.\n\n        In Mac OS X 10.6\n        IOPSGetTimeRemainingEstimate is not available.\n        If providing power source type is AC, returns TIME_REMAINING_UNLIMITED.\n        Otherwise looks through all power sources returned by IOPSGetProvidingPowerSourceType\n        and returns total estimate."
  },
  {
    "code": "def get_buffer( self ):\n        last_byte = self.current_bits if (self.bits_remaining < 8) else None\n        result = self.output\n        if last_byte is not None:\n            result = bytearray( result )\n            result.append( last_byte )\n        if self.bytes_reverse:\n            return bytes( reversed( result ) )\n        else:\n            return bytes( result )",
    "docstring": "Return a byte string containing the target as currently written."
  },
  {
    "code": "def _init_count_terms(self, annots):\n        gonotindag = set()\n        gocnts = self.gocnts\n        go2obj = self.go2obj\n        for terms in annots.values():\n            allterms = set()\n            for go_id in terms:\n                goobj = go2obj.get(go_id, None)\n                if goobj is not None:\n                    allterms.add(go_id)\n                    allterms |= goobj.get_all_parents()\n                else:\n                    gonotindag.add(go_id)\n            for parent in allterms:\n                gocnts[parent] += 1\n        if gonotindag:\n            print(\"{N} Assc. GO IDs not found in the GODag\\n\".format(N=len(gonotindag)))",
    "docstring": "Fills in the counts and overall aspect counts."
  },
  {
    "code": "def set(self, name, value=True):\n        \"set a feature value\"\n        setattr(self, name.lower(), value)",
    "docstring": "set a feature value"
  },
  {
    "code": "def posargs_limiter(func, *args):\n    posargs = inspect.getargspec(func)[0]\n    length = len(posargs)\n    if inspect.ismethod(func):\n        length -= 1\n    if length == 0:\n        return func()\n    return func(*args[0:length])",
    "docstring": "takes a function a positional arguments and sends only the number of\n    positional arguments the function is expecting"
  },
  {
    "code": "def ssh_known_hosts_lines(application_name, user=None):\n    known_hosts_list = []\n    with open(known_hosts(application_name, user)) as hosts:\n        for hosts_line in hosts:\n            if hosts_line.rstrip():\n                known_hosts_list.append(hosts_line.rstrip())\n    return(known_hosts_list)",
    "docstring": "Return contents of known_hosts file for given application.\n\n    :param application_name: Name of application eg nova-compute-something\n    :type application_name: str\n    :param user: The user that the ssh asserts are for.\n    :type user: str"
  },
  {
    "code": "def multi_split(text, regexes):\n    def make_regex(s):\n        return re.compile(s) if isinstance(s, basestring) else s\n    regexes = [make_regex(r) for r in regexes]\n    piece_list = [text]\n    finished_pieces = set()\n    def apply_re(regex, piece_list):\n        for piece in piece_list:\n            if piece in finished_pieces:\n                yield piece\n                continue\n            for s in full_split(piece, regex):\n                if regex.match(s):\n                    finished_pieces.add(s)\n                if s:\n                    yield s\n    for regex in regexes:\n        piece_list = list(apply_re(regex, piece_list))\n        assert ''.join(piece_list) == text\n    return piece_list",
    "docstring": "Split the text by the given regexes, in priority order.\n\n    Make sure that the regex is parenthesized so that matches are returned in\n    re.split().\n\n    Splitting on a single regex works like normal split.\n    >>> '|'.join(multi_split('one two three', [r'\\w+']))\n    'one| |two| |three'\n\n    Splitting on digits first separates the digits from their word\n    >>> '|'.join(multi_split('one234five 678', [r'\\d+', r'\\w+']))\n    'one|234|five| |678'\n\n    Splitting on words first keeps the word with digits intact.\n    >>> '|'.join(multi_split('one234five 678', [r'\\w+', r'\\d+']))\n    'one234five| |678'"
  },
  {
    "code": "def normalize(path_name, override=None):\n    identity = identify(path_name, override=override)\n    new_path_name = os.path.normpath(os.path.expanduser(path_name))\n    return new_path_name, identity",
    "docstring": "Prepares a path name to be worked with. Path name must not be empty. This\n    function will return the 'normpath'ed path and the identity of the path.\n    This function takes an optional overriding argument for the identity.\n\n    ONLY PROVIDE OVERRIDE IF:\n        1) YOU AREWORKING WITH A FOLDER THAT HAS AN EXTENSION IN THE NAME\n        2) YOU ARE MAKING A FILE WITH NO EXTENSION"
  },
  {
    "code": "def insert(self, resourcetype, source, insert_date=None):\n        caller = inspect.stack()[1][3]\n        if caller == 'transaction':\n            hhclass = 'Layer'\n            source = resourcetype\n            resourcetype = resourcetype.csw_schema\n        else:\n            hhclass = 'Service'\n            if resourcetype not in HYPERMAP_SERVICE_TYPES.keys():\n                raise RuntimeError('Unsupported Service Type')\n        return self._insert_or_update(resourcetype, source, mode='insert', hhclass=hhclass)",
    "docstring": "Insert a record into the repository"
  },
  {
    "code": "def fetch(self):\n        if self.data.type == self._manager.FOLDER_TYPE:\n            raise YagocdException(\"Can't fetch folder <{}>, only file!\".format(self._path))\n        response = self._session.get(self.data.url)\n        return response.content",
    "docstring": "Method for getting artifact's content.\n        Could only be applicable for file type.\n\n        :return: content of the artifact."
  },
  {
    "code": "def get_table(ports):\n    table = PrettyTable([\"Name\", \"Port\", \"Protocol\", \"Description\"])\n    table.align[\"Name\"] = \"l\"\n    table.align[\"Description\"] = \"l\"\n    table.padding_width = 1\n    for port in ports:\n        table.add_row(port)\n    return table",
    "docstring": "This function returns a pretty table used to display the port results.\n\n    :param ports: list of found ports\n    :return: the table to display"
  },
  {
    "code": "def login():\n    cas_token_session_key = current_app.config['CAS_TOKEN_SESSION_KEY']\n    redirect_url = create_cas_login_url(\n        current_app.config['CAS_SERVER'],\n        current_app.config['CAS_LOGIN_ROUTE'],\n        flask.url_for('.login', origin=flask.session.get('CAS_AFTER_LOGIN_SESSION_URL'), _external=True))\n    if 'ticket' in flask.request.args:\n        flask.session[cas_token_session_key] = flask.request.args['ticket']\n    if cas_token_session_key in flask.session:\n        if validate(flask.session[cas_token_session_key]):\n            if 'CAS_AFTER_LOGIN_SESSION_URL' in flask.session:\n                redirect_url = flask.session.pop('CAS_AFTER_LOGIN_SESSION_URL')\n            elif flask.request.args.get('origin'):\n                redirect_url = flask.request.args['origin']\n            else:\n                redirect_url = flask.url_for(\n                    current_app.config['CAS_AFTER_LOGIN'])\n        else:\n            del flask.session[cas_token_session_key]\n    current_app.logger.debug('Redirecting to: {0}'.format(redirect_url))\n    return flask.redirect(redirect_url)",
    "docstring": "This route has two purposes. First, it is used by the user\n    to login. Second, it is used by the CAS to respond with the\n    `ticket` after the user logs in successfully.\n\n    When the user accesses this url, they are redirected to the CAS\n    to login. If the login was successful, the CAS will respond to this\n    route with the ticket in the url. The ticket is then validated.\n    If validation was successful the logged in username is saved in\n    the user's session under the key `CAS_USERNAME_SESSION_KEY` and\n    the user's attributes are saved under the key\n    'CAS_USERNAME_ATTRIBUTE_KEY'"
  },
  {
    "code": "def change_default_radii(def_map):\n    s = current_system()\n    rep = current_representation()\n    rep.radii_state.default = [def_map[t] for t in s.type_array]\n    rep.radii_state.reset()",
    "docstring": "Change the default radii"
  },
  {
    "code": "def create_sqs_policy(self, topic_name, topic_arn, topic_subs):\n        t = self.template\n        arn_endpoints = []\n        url_endpoints = []\n        for sub in topic_subs:\n            arn_endpoints.append(sub[\"Endpoint\"])\n            split_endpoint = sub[\"Endpoint\"].split(\":\")\n            queue_url = \"https://%s.%s.amazonaws.com/%s/%s\" % (\n                split_endpoint[2],\n                split_endpoint[3],\n                split_endpoint[4],\n                split_endpoint[5],\n            )\n            url_endpoints.append(queue_url)\n        policy_doc = queue_policy(topic_arn, arn_endpoints)\n        t.add_resource(\n            sqs.QueuePolicy(\n                topic_name + \"SubPolicy\",\n                PolicyDocument=policy_doc,\n                Queues=url_endpoints,\n            )\n        )",
    "docstring": "This method creates the SQS policy needed for an SNS subscription. It\n        also takes the ARN of the SQS queue and converts it to the URL needed\n        for the subscription, as that takes a URL rather than the ARN."
  },
  {
    "code": "def get_object(self, request):\n        pattern = request.GET.get('pattern', '')\n        if len(pattern) < 3:\n            raise ObjectDoesNotExist\n        return pattern",
    "docstring": "The GET parameter 'pattern' is the object."
  },
  {
    "code": "def body(self):\n        self.connection = pika.BlockingConnection(self.connection_param)\n        self.channel = self.connection.channel()\n        print \"Monitoring file '%s'.\" % self.ftp_extended_log\n        file_iter = process_log(\n            sh.tail(\"-f\", self.ftp_extended_log, _iter=True)\n        )\n        for import_request in file_iter:\n            self.sendMessage(\n                exchange=self.output_exchange,\n                routing_key=self.output_key,\n                message=serializers.serialize(import_request),\n                UUID=str(uuid.uuid1())\n            )",
    "docstring": "This method handles AMQP connection details and reacts to FTP events by\n        sending messages to output queue."
  },
  {
    "code": "def get_function_name(s):\n    s = s.strip()\n    if s.startswith(\"__attribute__\"):\n        if \"))\" not in s:\n            raise ValueError(\"__attribute__ is present, but I cannot find double-right parenthesis in the function \"\n                             \"declaration string.\")\n        s = s[s.index(\"))\") + 2 : ].strip()\n    if '(' not in s:\n        raise ValueError(\"Cannot find any left parenthesis in the function declaration string.\")\n    func_name = s[:s.index('(')].strip()\n    for i, ch in enumerate(reversed(func_name)):\n        if ch == ' ':\n            pos = len(func_name) - 1 - i\n            break\n    else:\n        raise ValueError('Cannot find any space in the function declaration string.')\n    func_name = func_name[pos + 1 : ]\n    return func_name",
    "docstring": "Get the function name from a C-style function declaration string.\n\n    :param str s: A C-style function declaration string.\n    :return:      The function name.\n    :rtype:       str"
  },
  {
    "code": "def get_settings(config_uri, section=None, defaults=None):\n    loader = get_loader(config_uri)\n    return loader.get_settings(section, defaults)",
    "docstring": "Load the settings from a named section.\n\n    .. code-block:: python\n\n        settings = plaster.get_settings(...)\n        print(settings['foo'])\n\n    :param config_uri: Anything that can be parsed by\n        :func:`plaster.parse_uri`.\n\n    :param section: The name of the section in the config file. If this is\n        ``None`` then it is up to the loader to determine a sensible default\n        usually derived from the fragment in the ``path#name`` syntax of the\n        ``config_uri``.\n\n    :param defaults: A ``dict`` of default values used to populate the\n        settings and support variable interpolation. Any values in ``defaults``\n        may be overridden by the loader prior to returning the final\n        configuration dictionary.\n\n    :returns: A ``dict`` of settings. This should return a dictionary object\n        even if no data is available."
  },
  {
    "code": "def _ensure_ifaces_tuple(ifaces):\n    try:\n        ifaces = tuple(ifaces)\n    except TypeError:\n        ifaces = (ifaces,)\n    for iface in ifaces:\n        if not _issubclass(iface, ibc.Iface):\n            raise TypeError('Can only compare against interfaces.')\n    return ifaces",
    "docstring": "Convert to a tuple of interfaces and raise if not interfaces."
  },
  {
    "code": "def return_dict(self):\n        output_dict = {}\n        output_dict['general'] = self._iterate_through_class(self.general.__dict__)\n        output_dict['figure'] = self._iterate_through_class(self.figure.__dict__)\n        if self.total_plots > 1:\n            trans_dict = ({\n                           str(i): self._iterate_through_class(axis.__dict__) for i, axis\n                          in enumerate(self.ax)})\n            output_dict['plot_info'] = trans_dict\n        else:\n            output_dict['plot_info'] = {'0': self._iterate_through_class(self.ax.__dict__)}\n        if self.print_input:\n            print(output_dict)\n        return output_dict",
    "docstring": "Output dictionary for ``make_plot.py`` input.\n\n        Iterates through the entire MainContainer class turning its contents\n        into dictionary form. This dictionary becomes the input for ``make_plot.py``.\n\n        If `print_input` attribute is True, the entire dictionary will be printed\n        prior to returning the dicitonary.\n\n        Returns:\n            - **output_dict** (*dict*): Dicitonary for input into ``make_plot.py``."
  },
  {
    "code": "def write(self):\n        string = ''.join(self.content)\n        lines = string.splitlines(True)\n        if len(lines) == 0:\n            return\n        texts = [self.first_prefix + lines[0]]\n        for line in lines[1:]:\n            if line.strip() == '':\n                texts.append('\\n')\n            else:\n                texts.append(self.prefix + line)\n        self.base.append(''.join(texts))",
    "docstring": "Add ``self.contents`` with current ``prefix`` and ``first_prefix``\n\n        Add processed ``self.contents`` to ``self.base``.  The first line has\n        ``first_prefix`` prepended, further lines have ``prefix`` prepended.\n\n        Empty (all whitespace) lines get written as bare carriage returns, to\n        avoid ugly extra whitespace."
  },
  {
    "code": "def emptyTag(self, namespace, name, attrs, hasChildren=False):\n        yield {\"type\": \"EmptyTag\", \"name\": name,\n               \"namespace\": namespace,\n               \"data\": attrs}\n        if hasChildren:\n            yield self.error(\"Void element has children\")",
    "docstring": "Generates an EmptyTag token\n\n        :arg namespace: the namespace of the token--can be ``None``\n\n        :arg name: the name of the element\n\n        :arg attrs: the attributes of the element as a dict\n\n        :arg hasChildren: whether or not to yield a SerializationError because\n            this tag shouldn't have children\n\n        :returns: EmptyTag token"
  },
  {
    "code": "def save_profile(self, **params):\n        image = self.get_image()\n        if (image is None):\n            return\n        profile = image.get('profile', None)\n        if profile is None:\n            profile = Settings.SettingGroup()\n            image.set(profile=profile)\n        self.logger.debug(\"saving to image profile: params=%s\" % (\n            str(params)))\n        profile.set(**params)\n        return profile",
    "docstring": "Save the given parameters into profile settings.\n\n        Parameters\n        ----------\n        params : dict\n            Keywords and values to be saved."
  },
  {
    "code": "def create_standalone_context(require=None, **settings) -> 'Context':\n    backend = os.environ.get('MODERNGL_BACKEND')\n    if backend is not None:\n        settings['backend'] = backend\n    ctx = Context.__new__(Context)\n    ctx.mglo, ctx.version_code = mgl.create_standalone_context(settings)\n    ctx._screen = None\n    ctx.fbo = None\n    ctx._info = None\n    ctx.extra = None\n    if require is not None and ctx.version_code < require:\n        raise ValueError('Requested OpenGL version {}, got version {}'.format(\n            require, ctx.version_code))\n    return ctx",
    "docstring": "Create a standalone ModernGL context.\n\n        Example::\n\n            # Create a context with highest possible supported version\n            ctx = moderngl.create_context()\n\n            # Require at least OpenGL 4.3\n            ctx = moderngl.create_context(require=430)\n\n        Keyword Arguments:\n            require (int): OpenGL version code.\n\n        Returns:\n            :py:class:`Context` object"
  },
  {
    "code": "def allow_relation(self, obj1, obj2, **hints):\n        if obj1._meta.app_label != 'oldimporter' and obj2._meta.app_label != 'oldimporter':\n            return True\n        return None",
    "docstring": "Relations between objects are allowed between nodeshot2 objects only"
  },
  {
    "code": "def delete(self):\n        if 'delete' in self._URL:\n            extra = {'resource': self.__class__.__name__, 'query': {\n                'id': self.id}}\n            logger.info(\"Deleting {} resource.\".format(self), extra=extra)\n            self._api.delete(url=self._URL['delete'].format(id=self.id))\n        else:\n            raise SbgError('Resource can not be deleted!')",
    "docstring": "Deletes the resource on the server."
  },
  {
    "code": "def to_str(self):\n        dflt = super(DataportenAccount, self).to_str()\n        return '%s (%s)' % (\n            self.account.extra_data.get('name', ''),\n            dflt,\n        )",
    "docstring": "Returns string representation of a social account. Includes the name\n        of the user."
  },
  {
    "code": "def update(backend=None):\n    fileserver = salt.fileserver.Fileserver(__opts__)\n    fileserver.update(back=backend)\n    return True",
    "docstring": "Update the fileserver cache. If no backend is provided, then the cache for\n    all configured backends will be updated.\n\n    backend\n        Narrow fileserver backends to a subset of the enabled ones.\n\n        .. versionchanged:: 2015.5.0\n            If all passed backends start with a minus sign (``-``), then these\n            backends will be excluded from the enabled backends. However, if\n            there is a mix of backends with and without a minus sign (ex:\n            ``backend=-roots,git``) then the ones starting with a minus\n            sign will be disregarded.\n\n            Additionally, fileserver backends can now be passed as a\n            comma-separated list. In earlier versions, they needed to be passed\n            as a python list (ex: ``backend=\"['roots', 'git']\"``)\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-run fileserver.update\n        salt-run fileserver.update backend=roots,git"
  },
  {
    "code": "def GE(classical_reg1, classical_reg2, classical_reg3):\n    classical_reg1, classical_reg2, classical_reg3 = prepare_ternary_operands(classical_reg1,\n                                                                              classical_reg2,\n                                                                              classical_reg3)\n    return ClassicalGreaterEqual(classical_reg1, classical_reg2, classical_reg3)",
    "docstring": "Produce an GE instruction.\n\n    :param classical_reg1: Memory address to which to store the comparison result.\n    :param classical_reg2: Left comparison operand.\n    :param classical_reg3: Right comparison operand.\n    :return: A ClassicalGreaterEqual instance."
  },
  {
    "code": "def get(path_or_file, default=SENTINAL, mime=None, name=None, backend=None,\n        encoding=None, encoding_errors=None, kwargs=None,\n        _wtitle=False):\n    try:\n        text, title = _get(\n            path_or_file, default=default, mime=mime, name=name,\n            backend=backend, kwargs=kwargs, encoding=encoding,\n            encoding_errors=encoding_errors, _wtitle=_wtitle)\n        if _wtitle:\n            return (text, title)\n        else:\n            return text\n    except Exception as e:\n        if default is not SENTINAL:\n            LOGGER.exception(e)\n            return default\n        raise",
    "docstring": "Get document full text.\n\n    Accepts a path or file-like object.\n     * If given, `default` is returned instead of an error.\n     * `backend` is either a module object or a string specifying which\n       default backend to use (e.g. \"doc\"); take a look at backends\n       directory to see a list of default backends.\n     * `mime` and `name` should be passed if the information\n       is available to caller, otherwise a best guess is made.\n       If both are specified `mime` takes precedence.\n     * `encoding` and `encoding_errors` are used to handle text encoding.\n       They are taken into consideration mostly only by pure-python\n       backends which do not rely on CLI tools.\n       Default to \"utf8\" and \"strict\" respectively.\n     * `kwargs` are passed to the underlying backend."
  },
  {
    "code": "def profile_url(obj, profile_app_name, profile_model_name):\n    try:\n        content_type = ContentType.objects.get(\n            app_label=profile_app_name,\n            model=profile_model_name.lower()\n        )\n        profile = content_type.get_object_for_this_type(user=obj.user)\n        return profile.get_absolute_url()\n    except ContentType.DoesNotExist:\n        return \"\"\n    except AttributeError:\n        return \"\"",
    "docstring": "returns profile url of user"
  },
  {
    "code": "def update_bindings(self):\n        with self._lock:\n            all_valid = True\n            for handler in self.get_handlers(handlers_const.KIND_DEPENDENCY):\n                self.__safe_handler_callback(handler, \"try_binding\")\n                all_valid &= self.__safe_handler_callback(\n                    handler, \"is_valid\", only_boolean=True, none_as_true=True\n                )\n            return all_valid",
    "docstring": "Updates the bindings of the given component\n\n        :return: True if the component can be validated"
  },
  {
    "code": "def split_classes(X, y):\n    lstsclass = np.unique(y)\n    return [X[y == i, :].astype(np.float32) for i in lstsclass]",
    "docstring": "split samples in X by classes in y"
  },
  {
    "code": "def trace(function, *args, **k) :\n\tif doTrace : print (\"> \"+function.__name__, args, k)\n\tresult = function(*args, **k)\n\tif doTrace : print (\"< \"+function.__name__, args, k, \"->\", result)\n\treturn result",
    "docstring": "Decorates a function by tracing the begining and\n\tend of the function execution, if doTrace global is True"
  },
  {
    "code": "def import_authors(self, tree):\n        self.write_out(self.style.STEP('- Importing authors\\n'))\n        post_authors = set()\n        for item in tree.findall('channel/item'):\n            post_type = item.find('{%s}post_type' % WP_NS).text\n            if post_type == 'post':\n                post_authors.add(item.find(\n                    '{http://purl.org/dc/elements/1.1/}creator').text)\n        self.write_out('> %i authors found.\\n' % len(post_authors))\n        authors = {}\n        for post_author in post_authors:\n            if self.default_author:\n                authors[post_author] = self.default_author\n            else:\n                authors[post_author] = self.migrate_author(\n                    post_author.replace(' ', '-'))\n        return authors",
    "docstring": "Retrieve all the authors used in posts\n        and convert it to new or existing author and\n        return the conversion."
  },
  {
    "code": "def is_BF_hypergraph(self):\n        for hyperedge_id in self._hyperedge_attributes:\n            tail = self.get_hyperedge_tail(hyperedge_id)\n            head = self.get_hyperedge_head(hyperedge_id)\n            if len(tail) > 1 and len(head) > 1:\n                return False\n        return True",
    "docstring": "Indicates whether the hypergraph is a BF-hypergraph.\n        A BF-hypergraph consists of only B-hyperedges and F-hyperedges.\n        See \"is_B_hypergraph\" or \"is_F_hypergraph\" for more details.\n\n        :returns: bool -- True iff the hypergraph is an F-hypergraph."
  },
  {
    "code": "def _run_post_configure_callbacks(self, configure_args):\n        resulting_configuration = ImmutableDict(self.config)\n        multiple_callbacks = copy.copy(\n            self._post_configure_callbacks['multiple']\n        )\n        single_callbacks = copy.copy(self._post_configure_callbacks['single'])\n        self._post_configure_callbacks['single'] = []\n        for callback in multiple_callbacks:\n            callback(resulting_configuration, configure_args)\n        for callback in single_callbacks:\n            callback(resulting_configuration, configure_args)",
    "docstring": "Run all post configure callbacks we have stored.\n\n        Functions are passed the configuration that resulted from the call to\n        :meth:`configure` as the first argument, in an immutable form; and are\n        given the arguments passed to :meth:`configure` for the second\n        argument.\n\n        Returns from callbacks are ignored in all fashion.\n\n        Args:\n            configure_args (list[object]):\n                The full list of arguments passed to :meth:`configure`.\n\n        Returns:\n            None:\n                Does not return anything."
  },
  {
    "code": "def returns_annualized(returns, geometric=True, scale=None, expanding=False):\n    scale = _resolve_periods_in_year(scale, returns)\n    if expanding:\n        if geometric:\n            n = pd.expanding_count(returns)\n            return ((1. + returns).cumprod() ** (scale / n)) - 1.\n        else:\n            return pd.expanding_mean(returns) * scale\n    else:\n        if geometric:\n            n = returns.count()\n            return ((1. + returns).prod() ** (scale / n)) - 1.\n        else:\n            return returns.mean() * scale",
    "docstring": "return the annualized cumulative returns\n\n    Parameters\n    ----------\n    returns : DataFrame or Series\n    geometric : link the returns geometrically\n    scale: None or scalar or string (ie 12 for months in year),\n           If None, attempt to resolve from returns\n           If scalar, then use this as the annualization factor\n           If string, then pass this to periodicity function to resolve annualization factor\n    expanding: bool, default is False\n                If True, return expanding series/frames.\n                If False, return final result."
  },
  {
    "code": "def update_hash(a_hash, mv):\n    if mv.labels:\n        signing.add_dict_to_hash(a_hash, encoding.MessageToPyValue(mv.labels))\n    money_value = mv.get_assigned_value(u'moneyValue')\n    if money_value is not None:\n        a_hash.update(b'\\x00')\n        a_hash.update(money_value.currencyCode.encode('utf-8'))",
    "docstring": "Adds ``mv`` to ``a_hash``\n\n    Args:\n       a_hash (`Hash`): the secure hash, e.g created by hashlib.md5\n       mv (:class:`MetricValue`): the instance to add to the hash"
  },
  {
    "code": "def access(self, path, mode, dir_fd=None, follow_symlinks=None):\n        if follow_symlinks is not None and sys.version_info < (3, 3):\n            raise TypeError(\"access() got an unexpected \"\n                            \"keyword argument 'follow_symlinks'\")\n        path = self._path_with_dir_fd(path, self.access, dir_fd)\n        try:\n            stat_result = self.stat(path, follow_symlinks=follow_symlinks)\n        except OSError as os_error:\n            if os_error.errno == errno.ENOENT:\n                return False\n            raise\n        if is_root():\n            mode &= ~os.W_OK\n        return (mode & ((stat_result.st_mode >> 6) & 7)) == mode",
    "docstring": "Check if a file exists and has the specified permissions.\n\n        Args:\n            path: (str) Path to the file.\n            mode: (int) Permissions represented as a bitwise-OR combination of\n                os.F_OK, os.R_OK, os.W_OK, and os.X_OK.\n            dir_fd: If not `None`, the file descriptor of a directory, with\n                `path` being relative to this directory.\n                New in Python 3.3.\n            follow_symlinks: (bool) If `False` and `path` points to a symlink,\n                the link itself is queried instead of the linked object.\n                New in Python 3.3.\n\n        Returns:\n            bool, `True` if file is accessible, `False` otherwise."
  },
  {
    "code": "def get_response(self):\r\n        request = getattr(requests, self.request_method, None)\r\n        if request is None and self._request_method is None:\r\n            raise ValueError(\"A effective http request method must be set\")\r\n        if self.request_url is None:\r\n            raise ValueError(\r\n                \"Fatal error occurred, the class property \\\"request_url\\\" is\"\r\n                \"set to None, reset it with an effective url of dingtalk api.\"\r\n            )\r\n        response = request(self.request_url, **self.kwargs)\r\n        self.response = response\r\n        return response",
    "docstring": "Get the original response of requests"
  },
  {
    "code": "def find_whole_word(w):\n    return re.compile(r'\\b({0})\\b'.format(w), flags=re.IGNORECASE).search",
    "docstring": "Scan through string looking for a location where this word produces a match,\n    and return a corresponding MatchObject instance.\n    Return None if no position in the string matches the pattern;\n    note that this is different from finding a zero-length match at some point in the string."
  },
  {
    "code": "def _update_plotting_params(self, **kwargs):\n        scalars = kwargs.get('scalars', None)\n        if scalars is not None:\n            old = self.display_params['scalars']\n            self.display_params['scalars'] = scalars\n            if old != scalars:\n                self.plotter.subplot(*self.loc)\n                self.plotter.remove_actor(self._data_to_update, reset_camera=False)\n                self._need_to_update = True\n                self.valid_range = self.input_dataset.get_data_range(scalars)\n        cmap = kwargs.get('cmap', None)\n        if cmap is not None:\n            self.display_params['cmap'] = cmap",
    "docstring": "Some plotting parameters can be changed through the tool; this\n        updataes those plotting parameters."
  },
  {
    "code": "def get_extra_context(site, ctx):\n\t'Returns extra data useful to the templates.'\n\tctx['site'] = site\n\tctx['feeds'] = feeds = site.active_feeds.order_by('name')\n\tdef get_mod_chk(k):\n\t\tmod, chk = (\n\t\t\t(max(vals) if vals else None) for vals in (\n\t\t\t\tfilter(None, it.imap(op.attrgetter(k), feeds))\n\t\t\t\tfor k in ['last_modified', 'last_checked'] ) )\n\t\tchk = chk or datetime(1970, 1, 1, 0, 0, 0, 0, timezone.utc)\n\t\tctx['last_modified'], ctx['last_checked'] = mod or chk, chk\n\t\treturn ctx[k]\n\tfor k in 'last_modified', 'last_checked':\n\t\tctx[k] = lambda: get_mod_chk(k)\n\tctx['media_url'] = ctx['static_url'] =\\\n\t\t'{}feedjack/{}'.format(settings.STATIC_URL, site.template)",
    "docstring": "Returns extra data useful to the templates."
  },
  {
    "code": "def format(self, obj, **kwargs):\n        sio = StringIO()\n        self.fprint(obj, stream=sio, **kwargs)\n        return sio.getvalue()",
    "docstring": "Return the formatted representation of the object as a string."
  },
  {
    "code": "def link(self, title, path):\n        if not isinstance(path, file):\n            path = salt.utils.files.fopen(path)\n        self.__current_section.append({title: path})",
    "docstring": "Add a static file on the file system.\n\n        :param title:\n        :param path:\n        :return:"
  },
  {
    "code": "def pWMWrite(fileHandle, pWM, alphabetSize=4):\n    for i in xrange(0, alphabetSize):\n        fileHandle.write(\"%s\\n\" % ' '.join([ str(pWM[j][i]) for j in xrange(0, len(pWM)) ]))",
    "docstring": "Writes file in standard PWM format, is reverse of pWMParser"
  },
  {
    "code": "def dict_to_numpy_array(d):\n    return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()]))",
    "docstring": "Convert a dict of 1d array to a numpy recarray"
  },
  {
    "code": "def get_user(self, user_name=None):\n        params = {}\n        if user_name:\n            params['UserName'] = user_name\n        return self.get_response('GetUser', params)",
    "docstring": "Retrieve information about the specified user.\n\n        If the user_name is not specified, the user_name is determined\n        implicitly based on the AWS Access Key ID used to sign the request.\n\n        :type user_name: string\n        :param user_name: The name of the user to delete.\n                          If not specified, defaults to user making\n                          request."
  },
  {
    "code": "def _uri_to_etext(cls, uri_ref):\n        try:\n            return validate_etextno(int(os.path.basename(uri_ref.toPython())))\n        except InvalidEtextIdException:\n            return None",
    "docstring": "Converts the representation used to identify a text in the\n        meta-data RDF graph to a human-friendly integer text identifier."
  },
  {
    "code": "def _cancelScheduledUpgrade(self, justification=None) -> None:\n        if self.scheduledAction:\n            why_prefix = \": \"\n            why = justification\n            if justification is None:\n                why_prefix = \", \"\n                why = \"cancellation reason not specified\"\n            ev_data = self.scheduledAction\n            logger.info(\"Cancelling upgrade {}\"\n                        \" of node {}\"\n                        \" of package {}\"\n                        \" to version {}\"\n                        \" scheduled on {}\"\n                        \"{}{}\"\n                        .format(ev_data.upgrade_id,\n                                self.nodeName,\n                                ev_data.pkg_name,\n                                ev_data.version,\n                                ev_data.when,\n                                why_prefix,\n                                why))\n            self._unscheduleAction()\n            self._actionLog.append_cancelled(ev_data)\n            self._notifier.sendMessageUponPoolUpgradeCancel(\n                \"Upgrade of package {} on node '{}' to version {} \"\n                \"has been cancelled due to {}\"\n                .format(ev_data.pkg_name, self.nodeName,\n                        ev_data.version, why))",
    "docstring": "Cancels scheduled upgrade\n\n        :param when: time upgrade was scheduled to\n        :param version: version upgrade scheduled for"
  },
  {
    "code": "def read_chunk(stream):\n    chunk = stream.read(1)\n    while chunk in SKIP:\n        chunk = stream.read(1)\n    if chunk == \"\\\"\":\n        chunk += stream.read(1)\n        while not chunk.endswith(\"\\\"\"):\n            if chunk[-1] == ESCAPE:\n                chunk += stream.read(2)\n            else:\n                chunk += stream.read(1)\n    return chunk",
    "docstring": "Ignore whitespace outside of strings. If we hit a string, read it in\n    its entirety."
  },
  {
    "code": "def choose(self, choose_from):\n        for choice in self.elements:\n            if choice in choose_from:\n                return ImplementationChoice(choice, choose_from[choice])\n        raise LookupError(self.elements, choose_from.keys())",
    "docstring": "given a mapping of implementations\n        choose one based on the current settings\n        returns a key value pair"
  },
  {
    "code": "def get_info(self):\n        reconstructed = self.is_reconstructed()\n        site, site_type = self.get_site()\n        return reconstructed, site, site_type",
    "docstring": "Return surface reconstruction as well as primary and\n        secondary adsorption site labels"
  },
  {
    "code": "def vb_destroy_machine(name=None, timeout=10000):\n    vbox = vb_get_box()\n    log.info('Destroying machine %s', name)\n    machine = vbox.findMachine(name)\n    files = machine.unregister(2)\n    progress = machine.deleteConfig(files)\n    progress.waitForCompletion(timeout)\n    log.info('Finished destroying machine %s', name)",
    "docstring": "Attempts to get rid of a machine and all its files from the hypervisor\n    @param name:\n    @type name: str\n    @param timeout int timeout in milliseconds"
  },
  {
    "code": "def _update_font_style(self, font_style):\n        toggle_state = font_style & wx.FONTSTYLE_ITALIC == wx.FONTSTYLE_ITALIC\n        self.ToggleTool(wx.FONTFLAG_ITALIC, toggle_state)",
    "docstring": "Updates font style widget\n\n        Parameters\n        ----------\n\n        font_style: Integer\n        \\tButton down iif font_style == wx.FONTSTYLE_ITALIC"
  },
  {
    "code": "def _dump_to_pages(dump):\n  pos = 0\n  ret = []\n  start_tag = u\"<page>\\n\"\n  end_tag = u\"</page>\\n\"\n  while True:\n    start_pos = dump.find(start_tag, pos)\n    if start_pos == -1:\n      break\n    start_pos += len(start_tag)\n    end_pos = dump.find(end_tag, start_pos)\n    if end_pos == -1:\n      break\n    ret.append(dump[start_pos:end_pos])\n    pos = end_pos + len(end_tag)\n  return ret",
    "docstring": "Extract pages from an xml dump.\n\n  Args:\n    dump: a unicode string\n  Returns:\n    a list of unicode strings"
  },
  {
    "code": "def _load_from_cache_if_available(self, key):\n    if key in self._cache:\n      entity = self._cache[key]\n      if entity is None or entity._key == key:\n        raise tasklets.Return(entity)",
    "docstring": "Returns a cached Model instance given the entity key if available.\n\n    Args:\n      key: Key instance.\n\n    Returns:\n      A Model instance if the key exists in the cache."
  },
  {
    "code": "def _handle_command(self, command, env, args):\n        plugin_obj = registration.get_command_hook(command, env.task.active)\n        if plugin_obj and not env.task.active:\n            if plugin_obj.task_only or plugin_obj.options:\n                plugin_obj = None\n        if plugin_obj:\n            if plugin_obj.needs_root:\n                registration.setup_sudo_access(plugin_obj)\n            parser = self._get_plugin_parser(plugin_obj)\n            parsed_args = parser.parse_args(args)\n            plugin_obj.execute(env, parsed_args)\n            return True\n        return False",
    "docstring": "Handles calling appropriate command plugin based on the arguments\n            provided.\n\n            `command`\n                Command string.\n            `env`\n                Runtime ``Environment`` instance.\n            `args`\n                List of argument strings passed.\n\n            Returns ``False`` if nothing handled.\n\n            * Raises ``HelpBanner`` exception if mismatched command arguments."
  },
  {
    "code": "def compile_pillar(self):\n        load = {'id': self.minion_id,\n                'grains': self.grains,\n                'saltenv': self.opts['saltenv'],\n                'pillarenv': self.opts['pillarenv'],\n                'pillar_override': self.pillar_override,\n                'extra_minion_data': self.extra_minion_data,\n                'ver': '2',\n                'cmd': '_pillar'}\n        if self.ext:\n            load['ext'] = self.ext\n        try:\n            ret_pillar = yield self.channel.crypted_transfer_decode_dictentry(\n                load,\n                dictkey='pillar',\n            )\n        except Exception:\n            log.exception('Exception getting pillar:')\n            raise SaltClientError('Exception getting pillar.')\n        if not isinstance(ret_pillar, dict):\n            msg = ('Got a bad pillar from master, type {0}, expecting dict: '\n                   '{1}').format(type(ret_pillar).__name__, ret_pillar)\n            log.error(msg)\n            raise SaltClientError(msg)\n        raise tornado.gen.Return(ret_pillar)",
    "docstring": "Return a future which will contain the pillar data from the master"
  },
  {
    "code": "def show_image(kwargs, call=None):\n    if call != 'function':\n        raise SaltCloudSystemExit(\n            'The show_image action must be called with -f or --function.'\n        )\n    name = kwargs['image']\n    log.info(\"Showing image %s\", name)\n    machine = vb_get_machine(name)\n    ret = {\n        machine[\"name\"]: treat_machine_dict(machine)\n    }\n    del machine[\"name\"]\n    return ret",
    "docstring": "Show the details of an image"
  },
  {
    "code": "def _get_bundles_by_type(self, type):\n        bundles = {}\n        bundle_definitions = self.config.get(type)\n        if bundle_definitions is None:\n            return bundles\n        for bundle_name, paths in bundle_definitions.items():\n            bundle_files = []\n            for path in paths:\n                pattern = abspath = os.path.join(self.basedir, path)\n                assetdir = os.path.dirname(abspath)\n                fnames = [os.path.join(assetdir, fname)\n                          for fname in os.listdir(assetdir)]\n                expanded_fnames = fnmatch.filter(fnames, pattern)\n                bundle_files.extend(sorted(expanded_fnames))\n            bundles[bundle_name] = bundle_files\n        return bundles",
    "docstring": "Get a dictionary of bundles for requested type.\n\n        Args:\n            type: 'javascript' or 'css'"
  },
  {
    "code": "def DOM_node_to_XML(tree, xml_declaration=True):\n    result = ET.tostring(tree, encoding='utf8', method='xml').decode('utf-8')\n    if not xml_declaration:\n        result = result.split(\"<?xml version='1.0' encoding='utf8'?>\\n\")[1]\n    return result",
    "docstring": "Prints a DOM tree to its Unicode representation.\n\n    :param tree: the input DOM tree\n    :type tree: an ``xml.etree.ElementTree.Element`` object\n    :param xml_declaration: if ``True`` (default) prints a leading XML\n        declaration line\n    :type xml_declaration: bool\n    :returns: Unicode object"
  },
  {
    "code": "def get(self, key):\n        if key in self and len(self[key]) > 0:\n            return min(self[key])\n        else:\n            return 0",
    "docstring": "Return timings for `key`. Returns 0 if not present."
  },
  {
    "code": "def apply_numpy_specials(self, copy=True):\n        if copy:\n            data = self.data.astype(numpy.float64)\n        elif self.data.dtype != numpy.float64:\n            data = self.data = self.data.astype(numpy.float64)\n        else:\n            data = self.data\n        data[data == self.specials['Null']] = numpy.nan\n        data[data < self.specials['Min']] = numpy.NINF\n        data[data > self.specials['Max']] = numpy.inf\n        return data",
    "docstring": "Convert isis special pixel values to numpy special pixel values.\n\n            =======  =======\n             Isis     Numpy\n            =======  =======\n            Null     nan\n            Lrs      -inf\n            Lis      -inf\n            His      inf\n            Hrs      inf\n            =======  =======\n\n        Parameters\n        ----------\n        copy : bool [True]\n            Whether to apply the new special values to a copy of the\n            pixel data and leave the original unaffected\n\n        Returns\n        -------\n        Numpy Array\n            A numpy array with special values converted to numpy's nan, inf,\n            and -inf"
  },
  {
    "code": "def with_log(func):\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        decorator_logger = logging.getLogger('@with_log')\n        decorator_logger.debug('Entering %s() function call.', func.__name__)\n        log = kwargs.get('log', logging.getLogger(func.__name__))\n        try:\n            ret = func(log=log, *args, **kwargs)\n        finally:\n            decorator_logger.debug('Leaving %s() function call.', func.__name__)\n        return ret\n    return wrapper",
    "docstring": "Automatically adds a named logger to a function upon function call.\n\n    :param func: Function to decorate.\n\n    :return: Decorated function.\n    :rtype: function"
  },
  {
    "code": "def guess_xml_encoding(self, content):\n        r\n        matchobj = self.__regex['xml_encoding'].match(content)\n        return matchobj and matchobj.group(1).lower()",
    "docstring": "r\"\"\"Guess encoding from xml header declaration.\n\n        :param content: xml content\n        :rtype: str or None"
  },
  {
    "code": "def parse_s2bins(s2bins):\n    s2b = {}\n    b2s = {}\n    for line in s2bins:\n        line = line.strip().split()\n        s, b = line[0], line[1]\n        if 'UNK' in b:\n            continue\n        if len(line) > 2:\n            g = ' '.join(line[2:])\n        else:\n            g = 'n/a'\n        b = '%s\\t%s' % (b, g)\n        s2b[s] = b \n        if b not in b2s:\n           b2s[b] = []\n        b2s[b].append(s)\n    return s2b, b2s",
    "docstring": "parse ggKbase scaffold-to-bin mapping\n        - scaffolds-to-bins and bins-to-scaffolds"
  },
  {
    "code": "def __FinalUrlValue(self, value, field):\n        if isinstance(field, messages.BytesField) and value is not None:\n            return base64.urlsafe_b64encode(value)\n        elif isinstance(value, six.text_type):\n            return value.encode('utf8')\n        elif isinstance(value, six.binary_type):\n            return value.decode('utf8')\n        elif isinstance(value, datetime.datetime):\n            return value.isoformat()\n        return value",
    "docstring": "Encode value for the URL, using field to skip encoding for bytes."
  },
  {
    "code": "def open(self):\r\n        filename = self.dialogs.getOpenFileName(filter=\"*.%s\" % self.FTYPE)\r\n        if filename:\r\n            self.new(filename)",
    "docstring": "open a session to define in a dialog in an extra window"
  },
  {
    "code": "def facilityNetToMs():\n    a = TpPd(pd=0x3)\n    b = MessageType(mesType=0x3a)\n    c = Facility()\n    packet = a / b / c\n    return packet",
    "docstring": "FACILITY Section 9.3.9.1"
  },
  {
    "code": "def growth_volatility(eqdata, **kwargs):\n    _window = kwargs.get('window', 20)\n    _selection = kwargs.get('selection', 'Adj Close')\n    _outputcol = kwargs.get('outputcol', 'Growth Risk')\n    _growthdata = simple.growth(eqdata, selection=_selection)\n    return volatility(_growthdata, outputcol=_outputcol, window=_window)",
    "docstring": "Return the volatility of growth.\n\n    Note that, like :func:`pynance.tech.simple.growth` but in contrast to \n    :func:`volatility`, :func:`growth_volatility`\n    applies directly to a dataframe like that returned by \n    :func:`pynance.data.retrieve.get`, not necessarily to a single-column dataframe.\n\n    Parameters\n    ----------\n    eqdata : DataFrame\n        Data from which to extract growth volatility. An exception\n        will be raised if `eqdata` does not contain a column 'Adj Close'\n        or an optional name specified by the `selection` parameter.\n    window : int, optional\n        Window on which to calculate volatility. Defaults to 20.\n    selection : str, optional\n        Column of eqdata on which to calculate volatility of growth. Defaults\n        to 'Adj Close'\n    outputcol : str, optional\n        Column to use for output. Defaults to 'Growth Risk'.\n\n    Returns\n    ---------\n    out : DataFrame\n        Dataframe showing the volatility of growth over the specified `window`."
  },
  {
    "code": "def config_oauth(app):\n    \" Configure oauth support. \"\n    for name in PROVIDERS:\n        config = app.config.get('OAUTH_%s' % name.upper())\n        if not config:\n            continue\n        if not name in oauth.remote_apps:\n            remote_app = oauth.remote_app(name, **config)\n        else:\n            remote_app = oauth.remote_apps[name]\n        client_class = CLIENTS.get(name)\n        client_class(app, remote_app)",
    "docstring": "Configure oauth support."
  },
  {
    "code": "def flatten_path(path, flatten_slashes=False):\n    if not path or path == '/':\n        return '/'\n    if path[0] == '/':\n        path = path[1:]\n    parts = path.split('/')\n    new_parts = collections.deque()\n    for part in parts:\n        if part == '.' or (flatten_slashes and not part):\n            continue\n        elif part != '..':\n            new_parts.append(part)\n        elif new_parts:\n            new_parts.pop()\n    if flatten_slashes and path.endswith('/') or not len(new_parts):\n        new_parts.append('')\n    new_parts.appendleft('')\n    return '/'.join(new_parts)",
    "docstring": "Flatten an absolute URL path by removing the dot segments.\n\n    :func:`urllib.parse.urljoin` has some support for removing dot segments,\n    but it is conservative and only removes them as needed.\n\n    Arguments:\n        path (str): The URL path.\n        flatten_slashes (bool): If True, consecutive slashes are removed.\n\n    The path returned will always have a leading slash."
  },
  {
    "code": "def field_to_long(value):\n        if isinstance(value, (int, long)):\n            return long(value)\n        elif isinstance(value, basestring):\n            return bytes_to_long(from_hex(value))\n        else:\n            return None",
    "docstring": "Converts given value to long if possible, otherwise None is returned.\n\n        :param value:\n        :return:"
  },
  {
    "code": "def verify_signature(self, addr):\n        return verify(virtualchain.address_reencode(addr), self.get_plaintext_to_sign(), self.sig)",
    "docstring": "Given an address, verify whether or not it was signed by it"
  },
  {
    "code": "def fail(self, message, status=500, **kw):\n        self.request.response.setStatus(status)\n        result = {\"success\": False, \"errors\": message, \"status\": status}\n        result.update(kw)\n        return result",
    "docstring": "Set a JSON error object and a status to the response"
  },
  {
    "code": "def look_up(self, **keys: Dict[InstanceName, ScalarValue]) -> \"ArrayEntry\":\n        if not isinstance(self.schema_node, ListNode):\n            raise InstanceValueError(self.json_pointer(), \"lookup on non-list\")\n        try:\n            for i in range(len(self.value)):\n                en = self.value[i]\n                flag = True\n                for k in keys:\n                    if en[k] != keys[k]:\n                        flag = False\n                        break\n                if flag:\n                    return self._entry(i)\n            raise NonexistentInstance(self.json_pointer(), \"entry lookup failed\")\n        except KeyError:\n            raise NonexistentInstance(self.json_pointer(), \"entry lookup failed\") from None\n        except TypeError:\n            raise InstanceValueError(self.json_pointer(), \"lookup on non-list\") from None",
    "docstring": "Return the entry with matching keys.\n\n        Args:\n            keys: Keys and values specified as keyword arguments.\n\n        Raises:\n            InstanceValueError: If the receiver's value is not a YANG list.\n            NonexistentInstance: If no entry with matching keys exists."
  },
  {
    "code": "def setSignalHeaders(self, signalHeaders):\n        for edfsignal in np.arange(self.n_channels):\n            self.channels[edfsignal] = signalHeaders[edfsignal]\n        self.update_header()",
    "docstring": "Sets the parameter for all signals\n\n        Parameters\n        ----------\n        signalHeaders : array_like\n            containing dict with\n                'label' : str\n                          channel label (string, <= 16 characters, must be unique)\n                'dimension' : str\n                          physical dimension (e.g., mV) (string, <= 8 characters)\n                'sample_rate' : int\n                          sample frequency in hertz\n                'physical_max' : float\n                          maximum physical value\n                'physical_min' : float\n                         minimum physical value\n                'digital_max' : int\n                         maximum digital value (-2**15 <= x < 2**15)\n                'digital_min' : int\n                         minimum digital value (-2**15 <= x < 2**15)"
  },
  {
    "code": "def socket_close(self):\n        if self.sock != NC.INVALID_SOCKET:\n            self.sock.close()\n        self.sock = NC.INVALID_SOCKET",
    "docstring": "Close our socket."
  },
  {
    "code": "def _cosmoid_request(self, resource, cosmoid, **kwargs):\n        params = {\n            'cosmoid': cosmoid,\n        }\n        params.update(kwargs)\n        return self.make_request(resource, params)",
    "docstring": "Maps to the Generic API method for requests who's only parameter is ``cosmoid``"
  },
  {
    "code": "def iter_entries(self):\n        for idx in range(self._entry_count):\n            dir_entry_offset = self._offset + 2 + (idx*12)\n            ifd_entry = _IfdEntryFactory(self._stream_rdr, dir_entry_offset)\n            yield ifd_entry",
    "docstring": "Generate an |_IfdEntry| instance corresponding to each entry in the\n        directory."
  },
  {
    "code": "def _response_value(self, response, json=True):\n        if json:\n            contentType = response.headers.get(\"Content-Type\", \"\")\n            if not contentType.startswith((\"application/json\",\n                                           \"text/javascript\")):\n                if response.status_code == 200:\n                    raise CloudStackException(\n                        \"JSON (application/json) was expected, got {!r}\"\n                        .format(contentType),\n                        response=response)\n                raise CloudStackException(\n                    \"HTTP {0.status_code} {0.reason}\"\n                    .format(response),\n                    \"Make sure endpoint URL {!r} is correct.\"\n                    .format(self.endpoint),\n                    response=response)\n            try:\n                data = response.json()\n            except ValueError as e:\n                raise CloudStackException(\n                    \"HTTP {0.status_code} {0.reason}\"\n                    .format(response),\n                    \"{0!s}. Malformed JSON document\".format(e),\n                    response=response)\n            [key] = data.keys()\n            data = data[key]\n        else:\n            data = response.text\n        if response.status_code != 200:\n            raise CloudStackException(\n                \"HTTP {0} response from CloudStack\".format(\n                    response.status_code),\n                data,\n                response=response)\n        return data",
    "docstring": "Parses the HTTP response as a the cloudstack value.\n\n        It throws an exception if the server didn't answer with a 200."
  },
  {
    "code": "def level_names(self):\n        index = self.to_index()\n        if isinstance(index, pd.MultiIndex):\n            return index.names\n        else:\n            return None",
    "docstring": "Return MultiIndex level names or None if this IndexVariable has no\n        MultiIndex."
  },
  {
    "code": "def _get_enum(self, source, bitarray):\n        raw_value = self._get_raw(source, bitarray)\n        value_desc = source.find('item', {'value': str(raw_value)}) or self._get_rangeitem(source, raw_value)\n        return {\n            source['shortcut']: {\n                'description': source.get('description'),\n                'unit': source.get('unit', ''),\n                'value': value_desc['description'].format(value=raw_value),\n                'raw_value': raw_value,\n            }\n        }",
    "docstring": "Get enum value, based on the data in XML"
  },
  {
    "code": "def get_statements(self):\n        for k, v in self.reader_output.items():\n            for interaction in v['interactions']:\n                self._process_interaction(k, interaction, v['text'], self.pmid,\n                                          self.extra_annotations)",
    "docstring": "Process reader output to produce INDRA Statements."
  },
  {
    "code": "def _known_populations(row, pops):\n    cutoff = 0.01\n    out = set([])\n    for pop, base in [(\"esp\", \"af_esp_all\"), (\"1000g\", \"af_1kg_all\"),\n                      (\"exac\", \"af_exac_all\"), (\"anypop\", \"max_aaf_all\")]:\n        for key in [x for x in pops if x.startswith(base)]:\n            val = row[key]\n            if val and val > cutoff:\n                out.add(pop)\n    return sorted(list(out))",
    "docstring": "Find variants present in substantial frequency in population databases."
  },
  {
    "code": "def new(cls, ns_path, script, campaign_dir, runner_type='Auto',\n            overwrite=False, optimized=True, check_repo=True):\n        ns_path = os.path.abspath(ns_path)\n        campaign_dir = os.path.abspath(campaign_dir)\n        if Path(campaign_dir).exists() and not overwrite:\n            manager = CampaignManager.load(campaign_dir, ns_path,\n                                           runner_type=runner_type,\n                                           optimized=optimized,\n                                           check_repo=check_repo)\n            if manager.db.get_script() == script:\n                return manager\n            else:\n                del manager\n        runner = CampaignManager.create_runner(ns_path, script,\n                                               runner_type=runner_type,\n                                               optimized=optimized)\n        params = runner.get_available_parameters()\n        commit = \"\"\n        if check_repo:\n            from git import Repo, exc\n            commit = Repo(ns_path).head.commit.hexsha\n        db = DatabaseManager.new(script=script,\n                                 params=params,\n                                 commit=commit,\n                                 campaign_dir=campaign_dir,\n                                 overwrite=overwrite)\n        return cls(db, runner, check_repo)",
    "docstring": "Create a new campaign from an ns-3 installation and a campaign\n        directory.\n\n        This method will create a DatabaseManager, which will install a\n        database in the specified campaign_dir. If a database is already\n        available at the ns_path described in the specified campaign_dir and\n        its configuration matches config, this instance is used instead. If the\n        overwrite argument is set to True instead, the specified directory is\n        wiped and a new campaign is created in its place.\n\n        Furthermore, this method will initialize a SimulationRunner, of type\n        specified by the runner_type parameter, which will be locked on the\n        ns-3 installation at ns_path and set up to run the desired script.\n\n        Finally, note that creation of a campaign requires a git repository to\n        be initialized at the specified ns_path. This will allow SEM to save\n        the commit at which the simulations are run, enforce reproducibility\n        and avoid mixing results coming from different versions of ns-3 and its\n        libraries.\n\n        Args:\n            ns_path (str): path to the ns-3 installation to employ in this\n                campaign.\n            script (str): ns-3 script that will be executed to run simulations.\n            campaign_dir (str): path to the directory in which to save the\n                simulation campaign database.\n            runner_type (str): implementation of the SimulationRunner to use.\n                Value can be: SimulationRunner (for running sequential\n                simulations locally), ParallelRunner (for running parallel\n                simulations locally), GridRunner (for running simulations using\n                a DRMAA-compatible parallel task scheduler). Use Auto to\n                automatically pick the best runner.\n            overwrite (bool): whether to overwrite already existing\n                campaign_dir folders. This deletes the directory if and only if\n                it only contains files that were detected to be created by sem.\n            optimized (bool): whether to configure the runner to employ an\n                optimized ns-3 build."
  },
  {
    "code": "def nodeToXML(nodeObject):\n    xmlRoot = etree.Element(NODE + \"node\", nsmap=NODE_NSMAP)\n    nameNode = etree.SubElement(xmlRoot, NODE + \"name\")\n    nameNode.text = nodeObject.node_name\n    urlNode = etree.SubElement(xmlRoot, NODE + \"url\")\n    urlNode.text = nodeObject.node_url\n    pathNode = etree.SubElement(xmlRoot, NODE + \"path\")\n    pathNode.text = nodeObject.node_path\n    capNode = etree.SubElement(xmlRoot, NODE + \"capacity\")\n    capNode.text = str(nodeObject.node_capacity)\n    sizeNode = etree.SubElement(xmlRoot, NODE + \"size\")\n    sizeNode.text = str(nodeObject.node_size)\n    if nodeObject.last_checked:\n        checkedNode = etree.SubElement(xmlRoot, NODE + \"lastChecked\")\n        checkedNode.text = nodeObject.last_checked.strftime(TIME_FORMAT_STRING)\n    return xmlRoot",
    "docstring": "Take a Django node object from our CODA store and make an XML\n    representation"
  },
  {
    "code": "def visit(self, node):\n        for pattern, replace in know_pattern:\n            check = Check(node, dict())\n            if check.visit(pattern):\n                node = PlaceholderReplace(check.placeholders).visit(replace())\n                self.update = True\n        return super(PatternTransform, self).visit(node)",
    "docstring": "Try to replace if node match the given pattern or keep going."
  },
  {
    "code": "def write_badge(self, file_path, overwrite=False):\n        if file_path.endswith('/'):\n            raise Exception('File location may not be a directory.')\n        path = os.path.abspath(file_path)\n        if not path.lower().endswith('.svg'):\n            path += '.svg'\n        if not overwrite and os.path.exists(path):\n            raise Exception('File \"{}\" already exists.'.format(path))\n        with open(path, mode='w') as file_handle:\n            file_handle.write(self.badge_svg_text)",
    "docstring": "Write badge to file."
  },
  {
    "code": "def load(self, profile_args):\n        for key, value in profile_args.items():\n            self.add(key, value)",
    "docstring": "Load provided CLI Args.\n\n        Args:\n            args (dict): Dictionary of args in key/value format."
  },
  {
    "code": "def GetFeedItemIdsForCampaign(campaign_feed):\n  feed_item_ids = set()\n  try:\n    lhs_operand = campaign_feed['matchingFunction']['lhsOperand']\n  except KeyError:\n    lhs_operand = None\n  if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] ==\n      'RequestContextOperand'):\n    request_context_operand = lhs_operand[0]\n    if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and\n        campaign_feed['matchingFunction']['operator'] == 'IN'):\n      for argument in campaign_feed['matchingFunction']['rhsOperand']:\n        if argument['xsi_type'] == 'ConstantOperand':\n          feed_item_ids.add(argument['longValue'])\n  return feed_item_ids",
    "docstring": "Gets the Feed Item Ids used by a campaign through a given Campaign Feed.\n\n  Args:\n    campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from.\n\n  Returns:\n    A list of Feed Item IDs."
  },
  {
    "code": "def get_default_gwf_api():\n    for lib in APIS:\n        try:\n            import_gwf_library(lib)\n        except ImportError:\n            continue\n        else:\n            return lib\n    raise ImportError(\"no GWF API available, please install a third-party GWF \"\n                      \"library ({}) and try again\".format(', '.join(APIS)))",
    "docstring": "Return the preferred GWF library\n\n    Examples\n    --------\n    If you have |LDAStools.frameCPP|_ installed:\n\n    >>> from gwpy.timeseries.io.gwf import get_default_gwf_api\n    >>> get_default_gwf_api()\n    'framecpp'\n\n    Or, if you don't have |lalframe|_:\n\n    >>> get_default_gwf_api()\n    'lalframe'\n\n    Otherwise:\n\n    >>> get_default_gwf_api()\n    ImportError: no GWF API available, please install a third-party GWF\n    library (framecpp, lalframe) and try again"
  },
  {
    "code": "def concat_padded(base, *args):\n    ret = base\n    for n in args:\n        if is_string(n):\n            ret = \"%s_%s\" % (ret, n)\n        else:\n            ret = \"%s_%04i\"  % (ret, n + 1)\n    return ret",
    "docstring": "Concatenate string and zero-padded 4 digit number"
  },
  {
    "code": "def _pool_event_refresh_cb(conn, pool, opaque):\n    _salt_send_event(opaque, conn, {\n        'pool': {\n            'name': pool.name(),\n            'uuid': pool.UUIDString()\n        },\n        'event': opaque['event']\n    })",
    "docstring": "Storage pool refresh events handler"
  },
  {
    "code": "def getanymentions(idf, anidfobject):\n    name = anidfobject.obj[1]\n    foundobjs = []\n    keys = idfobjectkeys(idf)\n    idfkeyobjects = [idf.idfobjects[key.upper()] for key in keys]\n    for idfobjects in idfkeyobjects:\n        for idfobject in idfobjects:\n            if name.upper() in [item.upper() \n                                    for item in idfobject.obj \n                                        if isinstance(item, basestring)]:\n                foundobjs.append(idfobject)\n    return foundobjs",
    "docstring": "Find out if idjobject is mentioned an any object anywhere"
  },
  {
    "code": "def remove_external_data_field(tensor, field_key):\n    for (i, field) in enumerate(tensor.external_data):\n        if field.key == field_key:\n            del tensor.external_data[i]",
    "docstring": "Remove a field from a Tensor's external_data key-value store.\n\n    Modifies tensor object in place.\n\n    @params\n    tensor: Tensor object from which value will be removed\n    field_key: The key of the field to be removed"
  },
  {
    "code": "def encode_command(*args, buf=None):\n    if buf is None:\n        buf = bytearray()\n    buf.extend(b'*%d\\r\\n' % len(args))\n    try:\n        for arg in args:\n            barg = _converters[type(arg)](arg)\n            buf.extend(b'$%d\\r\\n%s\\r\\n' % (len(barg), barg))\n    except KeyError:\n        raise TypeError(\"Argument {!r} expected to be of bytearray, bytes,\"\n                        \" float, int, or str type\".format(arg))\n    return buf",
    "docstring": "Encodes arguments into redis bulk-strings array.\n\n    Raises TypeError if any of args not of bytearray, bytes, float, int, or str\n    type."
  },
  {
    "code": "def capabilities(self):\n        response = self.get(PATH_CAPABILITIES)\n        return _load_atom(response, MATCH_ENTRY_CONTENT).capabilities",
    "docstring": "Returns the list of system capabilities.\n\n        :return: A ``list`` of capabilities."
  },
  {
    "code": "async def start_authentication(self):\n        _, code = await self.http.post_data(\n            'pair-pin-start', headers=_AIRPLAY_HEADERS)\n        if code != 200:\n            raise DeviceAuthenticationError('pair start failed')",
    "docstring": "Start the authentication process.\n\n        This method will show the expected PIN on screen."
  },
  {
    "code": "async def get_person(self, id_):\n        data = await self._get_person_json(\n            id_,\n            OrderedDict(append_to_response='movie_credits')\n        )\n        return Person.from_json(data, self.config['data'].get('images'))",
    "docstring": "Retrieve person data by ID.\n\n        Arguments:\n          id_ (:py:class:`int`): The person's TMDb ID.\n\n        Returns:\n          :py:class:`~.Person`: The requested person."
  },
  {
    "code": "def __get_payload(self, uuid, failed):\n        try:\n            return self.publish_uuid_store[uuid]\n        except Exception as exc:\n            msg = \"Failed to load payload from publish store for UUID %s, %s: %s\"\n            if uuid in failed:\n                log.error(msg, uuid, \"discarding\", str(exc))\n                self.__discard_publish_uuid(uuid, failed)\n            else:\n                log.error(msg, uuid, \"will try agan\", str(exc))\n                failed.add(uuid)\n        return None",
    "docstring": "Retry reading a message from the publish_uuid_store once, delete on the second failure."
  },
  {
    "code": "def remove_port_profile_to_delete(self, profile_name, device_id):\n        with self.session.begin(subtransactions=True):\n            self.session.query(ucsm_model.PortProfileDelete).filter_by(\n                profile_id=profile_name, device_id=device_id).delete()",
    "docstring": "Removes port profile to be deleted from table."
  },
  {
    "code": "def work_experience(self, working_start_age: int = 22) -> int:\n        age = self._store['age']\n        if age == 0:\n            age = self.age()\n        return max(age - working_start_age, 0)",
    "docstring": "Get a work experience.\n\n        :param working_start_age: Age then person start to work.\n        :return: Depend on previous generated age."
  },
  {
    "code": "def start_pinging(self) -> None:\n        assert self.ping_interval is not None\n        if self.ping_interval > 0:\n            self.last_ping = self.last_pong = IOLoop.current().time()\n            self.ping_callback = PeriodicCallback(\n                self.periodic_ping, self.ping_interval * 1000\n            )\n            self.ping_callback.start()",
    "docstring": "Start sending periodic pings to keep the connection alive"
  },
  {
    "code": "def update_user_type(self):\n        if self.rb_tutor.isChecked():\n            self.user_type = 'tutor'\n        elif self.rb_student.isChecked():\n            self.user_type = 'student'\n        self.accept()",
    "docstring": "Return either 'tutor' or 'student' based on which radio\n        button is selected."
  },
  {
    "code": "def cli(ctx):\n    wandb.try_to_set_up_global_logging()\n    if ctx.invoked_subcommand is None:\n        click.echo(ctx.get_help())",
    "docstring": "Weights & Biases.\n\n    Run \"wandb docs\" for full documentation."
  },
  {
    "code": "def write_supercells_with_displacements(supercell, cells_with_disps, filename=\"geo.gen\"):\n    write_dftbp(filename + \"S\", supercell)\n    for ii in range(len(cells_with_disps)):\n        write_dftbp(filename + \"S-{:03d}\".format(ii+1), cells_with_disps[ii])",
    "docstring": "Writes perfect supercell and supercells with displacements\n\n    Args:\n        supercell: perfect supercell\n        cells_with_disps: supercells with displaced atoms\n        filename: root-filename"
  },
  {
    "code": "def addrs_for_hash(self, h):\n        if h not in self._hash_mapping:\n            return\n        self._mark_updated_mapping(self._hash_mapping, h)\n        to_discard = set()\n        for e in self._hash_mapping[h]:\n            try:\n                if h == hash(self[e].object): yield e\n                else: to_discard.add(e)\n            except KeyError:\n                to_discard.add(e)\n        self._hash_mapping[h] -= to_discard",
    "docstring": "Returns addresses that contain expressions that contain a variable with the hash of `h`."
  },
  {
    "code": "def Attach(self, pid):\n    if self.inferior.is_running:\n      answer = raw_input('Already attached to process ' +\n                         str(self.inferior.pid) +\n                         '. Detach? [y]/n ')\n      if answer and answer != 'y' and answer != 'yes':\n        return None\n      self.Detach()\n    for plugin in self.plugins:\n      plugin.position = None\n    self.inferior.Reinit(pid)",
    "docstring": "Attach to the process with the given pid."
  },
  {
    "code": "def handle_logout_response(self, response, sign_alg=None, digest_alg=None):\n        logger.info(\"state: %s\", self.state)\n        status = self.state[response.in_response_to]\n        logger.info(\"status: %s\", status)\n        issuer = response.issuer()\n        logger.info(\"issuer: %s\", issuer)\n        del self.state[response.in_response_to]\n        if status[\"entity_ids\"] == [issuer]:\n            self.local_logout(decode(status[\"name_id\"]))\n            return 0, \"200 Ok\", [(\"Content-type\", \"text/html\")], []\n        else:\n            status[\"entity_ids\"].remove(issuer)\n            if \"sign_alg\" in status:\n                sign_alg = status[\"sign_alg\"]\n            return self.do_logout(decode(status[\"name_id\"]),\n                                  status[\"entity_ids\"],\n                                  status[\"reason\"], status[\"not_on_or_after\"],\n                                  status[\"sign\"], sign_alg=sign_alg,\n                                  digest_alg=digest_alg)",
    "docstring": "handles a Logout response\n\n        :param response: A response.Response instance\n        :return: 4-tuple of (session_id of the last sent logout request,\n            response message, response headers and message)"
  },
  {
    "code": "def get_publish_path(self, obj):\n        return os.path.join(\n            obj.chat_type.publish_path, obj.publish_path.lstrip(\"/\")\n        )",
    "docstring": "publish_path joins the publish_paths for the chat type and the channel."
  },
  {
    "code": "def _generate_examples(self, archive, directory):\n    reg = re.compile(os.path.join(\"^%s\" % directory, \"(?P<label>neg|pos)\", \"\"))\n    for path, imdb_f in archive:\n      res = reg.match(path)\n      if not res:\n        continue\n      text = imdb_f.read().strip()\n      yield {\n          \"text\": text,\n          \"label\": res.groupdict()[\"label\"],\n      }",
    "docstring": "Generate IMDB examples."
  },
  {
    "code": "async def start(self):\n        successful = 0\n        try:\n            for adapter in self.adapters:\n                await adapter.start()\n                successful += 1\n            self._started = True\n        except:\n            for adapter in self.adapters[:successful]:\n                await adapter.stop()\n            raise",
    "docstring": "Start all adapters managed by this device adapter.\n\n        If there is an error starting one or more adapters, this method will\n        stop any adapters that we successfully started and raise an exception."
  },
  {
    "code": "def function_dependency_graph(self, func):\n        if self._function_data_dependencies is None:\n            self._build_function_dependency_graphs()\n        if func in self._function_data_dependencies:\n            return self._function_data_dependencies[func]\n        return None",
    "docstring": "Get a dependency graph for the function `func`.\n\n        :param func:    The Function object in CFG.function_manager.\n        :returns:       A networkx.DiGraph instance."
  },
  {
    "code": "def download_cart(cart_name, env):\n    cart_con = cart_db()\n    carts = cart_con[env]\n    return carts.find_one({'_id': cart_name})",
    "docstring": "accesses mongodb and return a cart spec stored there"
  },
  {
    "code": "def WebLookup(url, urlQuery=None, utf8=True):\n  goodlogging.Log.Info(\"UTIL\", \"Looking up info from URL:{0} with QUERY:{1})\".format(url, urlQuery), verbosity=goodlogging.Verbosity.MINIMAL)\n  response = requests.get(url, params=urlQuery)\n  goodlogging.Log.Info(\"UTIL\", \"Full url: {0}\".format(response.url), verbosity=goodlogging.Verbosity.MINIMAL)\n  if utf8 is True:\n    response.encoding = 'utf-8'\n  if(response.status_code == requests.codes.ok):\n    return(response.text)\n  else:\n    response.raise_for_status()",
    "docstring": "Look up webpage at given url with optional query string\n\n  Parameters\n  ----------\n    url : string\n      Web url.\n\n    urlQuery : dictionary [optional: default = None]\n      Parameter to be passed to GET method of requests module\n\n    utf8 : boolean [optional: default = True]\n      Set response encoding\n\n  Returns\n  ----------\n    string\n      GET response text"
  },
  {
    "code": "def print_locals(*args, **kwargs):\n    from utool import util_str\n    from utool import util_dbg\n    from utool import util_dict\n    locals_ = util_dbg.get_parent_frame().f_locals\n    keys = kwargs.get('keys', None if len(args) == 0 else [])\n    to_print = {}\n    for arg in args:\n        varname = util_dbg.get_varname_from_locals(arg, locals_)\n        to_print[varname] = arg\n    if keys is not None:\n        to_print.update(util_dict.dict_take(locals_, keys))\n    if not to_print:\n        to_print = locals_\n    locals_str = util_str.repr4(to_print)\n    print(locals_str)",
    "docstring": "Prints local variables in function.\n\n    If no arguments all locals are printed.\n\n    Variables can be specified directly (variable values passed in) as varargs\n    or indirectly (variable names passed in) in kwargs by using keys and a list\n    of strings."
  },
  {
    "code": "def defaulted_property(self, target, option_name):\n    if target.has_sources('.java'):\n      matching_subsystem = Java.global_instance()\n    elif target.has_sources('.scala'):\n      matching_subsystem = ScalaPlatform.global_instance()\n    else:\n      return getattr(target, option_name)\n    return matching_subsystem.get_scalar_mirrored_target_option(option_name, target)",
    "docstring": "Computes a language property setting for the given JvmTarget.\n\n    :param selector A function that takes a target or platform and returns the boolean value of the\n                    property for that target or platform, or None if that target or platform does\n                    not directly define the property.\n\n    If the target does not override the language property, returns true iff the property\n    is true for any of the matched languages for the target."
  },
  {
    "code": "def entrypoints(section):\n    return {ep.name: ep.load() for ep in pkg_resources.iter_entry_points(section)}",
    "docstring": "Returns the Entry Point for a given Entry Point section.\n\n    :param str section: The section name in the entry point collection\n    :returns:  A dictionary of (Name, Class) pairs stored in the entry point collection."
  },
  {
    "code": "def make_coord_dict(coord):\n    return dict(\n        z=int_if_exact(coord.zoom),\n        x=int_if_exact(coord.column),\n        y=int_if_exact(coord.row),\n    )",
    "docstring": "helper function to make a dict from a coordinate for logging"
  },
  {
    "code": "def set_level(self, level, realms):\n        self.level = level\n        if not self.level:\n            logger.info(\"- %s\", self.get_name())\n        else:\n            logger.info(\" %s %s\", '+' * self.level, self.get_name())\n        self.all_sub_members = []\n        self.all_sub_members_names = []\n        for child in sorted(self.realm_members):\n            child = realms.find_by_name(child)\n            if not child:\n                continue\n            self.all_sub_members.append(child.uuid)\n            self.all_sub_members_names.append(child.get_name())\n            grand_children = child.set_level(self.level + 1, realms)\n            for grand_child in grand_children:\n                if grand_child in self.all_sub_members_names:\n                    continue\n                grand_child = realms.find_by_name(grand_child)\n                if grand_child:\n                    self.all_sub_members_names.append(grand_child.get_name())\n                    self.all_sub_members.append(grand_child.uuid)\n        return self.all_sub_members_names",
    "docstring": "Set the realm level in the realms hierarchy\n\n        :return: None"
  },
  {
    "code": "def parse_env(s):\n    m = ENV_RE.search(s)\n    if m is None:\n        return {}\n    g1 = m.group(1)\n    env = dict(ENV_SPLIT_RE.findall(g1))\n    return env",
    "docstring": "Parses the environment portion of string into a dict."
  },
  {
    "code": "def minimize(self, minimize):\n        self._minimize = minimize\n        self._logger.log('debug', 'Minimize set to {}'.format(minimize))",
    "docstring": "Configures the ABC to minimize fitness function return value or\n        derived score\n\n        Args:\n            minimize (bool): if True, minimizes fitness function return value;\n                if False, minimizes derived score"
  },
  {
    "code": "def scan_for_devices(timeout: float) -> List[Tuple[str, str]]:\n        from bluepy.btle import Scanner\n        scanner = Scanner()\n        result = []\n        for device in scanner.scan(timeout):\n            result.append((device.addr, device.getValueText(9)))\n        return result",
    "docstring": "Scan for bluetooth low energy devices.\n\n        Note this must be run as root!"
  },
  {
    "code": "def node_contained_in_layer_area_validation(self):\n    if self.layer and isinstance(self.layer.area, Polygon) and not self.layer.area.contains(self.geometry):\n        raise ValidationError(_('Node must be inside layer area'))",
    "docstring": "if layer defines an area, ensure node coordinates are contained in the area"
  },
  {
    "code": "def socket_recvall(socket, length, bufsize=4096):\n    data = b\"\"\n    while len(data) < length:\n        data += socket.recv(bufsize)\n    return data",
    "docstring": "A helper method to read of bytes from a socket to a maximum length"
  },
  {
    "code": "def get_interface_by_instance_name(self, name):\n        with self._mutex:\n            for intf in self.interfaces:\n                if intf.instance_name == name:\n                    return intf\n            return None",
    "docstring": "Get an interface of this port by instance name."
  },
  {
    "code": "def saveOverlayToDicomCopy(input_dcmfilelist, output_dicom_dir, overlays,\n                           crinfo, orig_shape):\n    from . import datawriter as dwriter\n    if not os.path.exists(output_dicom_dir):\n        os.makedirs(output_dicom_dir)\n    import imtools.image_manipulation\n    for key in overlays:\n        overlays[key] = imtools.image_manipulation.uncrop(overlays[key], crinfo, orig_shape)\n    dw = dwriter.DataWriter()\n    dw.DataCopyWithOverlay(input_dcmfilelist, output_dicom_dir, overlays)",
    "docstring": "Save overlay to dicom."
  },
  {
    "code": "def timeout(self, duration=3600):\n        self.room.check_owner()\n        self.conn.make_call(\"timeoutFile\", self.fid, duration)",
    "docstring": "Timeout the uploader of this file"
  },
  {
    "code": "def remove_scene(self, scene_id):\n        if self.state.activeSceneId == scene_id:\n            err_msg = \"Requested to delete scene {sceneNum}, which is currently active. Cannot delete active scene.\".format(sceneNum=scene_id)\n            logging.info(err_msg)\n            return(False, 0, err_msg)\n        try:\n            del self.state.scenes[scene_id]\n            logging.debug(\"Deleted scene {sceneNum}\".format(sceneNum=scene_id))\n        except KeyError:\n            err_msg = \"Requested to delete scene {sceneNum}, which does not exist\".format(sceneNum=scene_id)\n            logging.info(err_msg)\n            return(False, 0, err_msg)\n        sequence_number = self.zmq_publisher.publish_scene_remove(scene_id)\n        logging.debug(\"Removed scene {sceneNum}\".format(sceneNum=scene_id))\n        return (True, sequence_number, \"OK\")",
    "docstring": "remove a scene by Scene ID"
  },
  {
    "code": "def add_dep(self, ):\n        i = self.dep_tablev.currentIndex()\n        item = i.internalPointer()\n        if item:\n            dep = item.internal_data()\n            dep.projects.add(self._project)\n            self.deps.append(dep)\n            item.set_parent(None)",
    "docstring": "Add a dep and store it in the self.deps\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def load(self, loc):\n        try:\n            w_td_c = pickle.load(open(loc, 'rb'))\n        except IOError:\n            msg = (\"Missing trontagger.pickle file.\")\n            raise MissingCorpusError(msg)\n        self.model.weights, self.tagdict, self.classes = w_td_c\n        self.model.classes = self.classes\n        return None",
    "docstring": "Load a pickled model."
  },
  {
    "code": "def fasta(self):\n        fasta_str = ''\n        max_line_length = 79\n        for p in self._molecules:\n            if hasattr(p, 'sequence'):\n                fasta_str += '>{0}:{1}|PDBID|CHAIN|SEQUENCE\\n'.format(\n                    self.id.upper(), p.id)\n                seq = p.sequence\n                split_seq = [seq[i: i + max_line_length]\n                             for i in range(0, len(seq), max_line_length)]\n                for seq_part in split_seq:\n                    fasta_str += '{0}\\n'.format(seq_part)\n        return fasta_str",
    "docstring": "Generates a FASTA string for the `Assembly`.\n\n        Notes\n        -----\n        Explanation of FASTA format: https://en.wikipedia.org/wiki/FASTA_format\n        Recommendation that all lines of text be shorter than 80\n        characters is adhered to. Format of PDBID|CHAIN|SEQUENCE is \n        consistent with files downloaded from the PDB. Uppercase \n        PDBID used for consistency with files downloaded from the PDB.\n        Useful for feeding into cdhit and then running sequence clustering.\n\n        Returns\n        -------\n        fasta_str : str\n            String of the fasta file for the `Assembly`."
  },
  {
    "code": "def resolve(self, key, keylist):\n        raise AmbiguousKeyError(\"Ambiguous key \"+ repr(key) +\n                \", could be any of \" + str(sorted(keylist)))",
    "docstring": "Hook to resolve ambiguities in selected keys"
  },
  {
    "code": "def monitor(name, callback):\r\n    global _monitor \r\n    if not exists(name):\r\n        raise ContainerNotExists(\"The container (%s) does not exist!\" % name)\r\n    if _monitor:\r\n        if _monitor.is_monitored(name):\r\n            raise Exception(\"You are already monitoring this container (%s)\" % name)\r\n    else:\r\n        _monitor = _LXCMonitor()\r\n        logging.info(\"Starting LXC Monitor\")\r\n        _monitor.start()\r\n        def kill_handler(sg, fr):\r\n            stop_monitor()\r\n        signal.signal(signal.SIGTERM, kill_handler)\r\n        signal.signal(signal.SIGINT, kill_handler)\r\n    _monitor.add_monitor(name, callback)",
    "docstring": "monitors actions on the specified container,\r\n    callback is a function to be called on"
  },
  {
    "code": "def hide(cls):\n        cls.el.style.display = \"none\"\n        cls.overlay.hide()\n        cls.bind()",
    "docstring": "Hide the log interface."
  },
  {
    "code": "def get_form(self, form_class=None):\n        form = super().get_form(form_class)\n        if not getattr(form, 'helper', None):\n            form.helper = FormHelper()\n            form.helper.form_tag = False\n        else:\n            form.helper.form_tag = False\n        return form",
    "docstring": "Get form for model"
  },
  {
    "code": "def normalize(self, address, **kwargs):\n        addresses = super(AddressType, self).normalize(address, **kwargs)\n        return addresses",
    "docstring": "Make the address more compareable."
  },
  {
    "code": "def get_ndv_b(b):\n    b_ndv = b.GetNoDataValue()\n    if b_ndv is None:\n        ns = b.XSize\n        nl = b.YSize\n        ul = float(b.ReadAsArray(0, 0, 1, 1))\n        lr = float(b.ReadAsArray(ns-1, nl-1, 1, 1))\n        if np.isnan(ul) or ul == lr:\n            b_ndv = ul\n        else:\n            b_ndv = 0\n    elif np.isnan(b_ndv):\n        b_dt = gdal.GetDataTypeName(b.DataType)\n        if 'Float' in b_dt:\n            b_ndv = np.nan\n        else:\n            b_ndv = 0\n    return b_ndv",
    "docstring": "Get NoData value for GDAL band.\n\n    If NoDataValue is not set in the band, \n    extract upper left and lower right pixel values.\n    Otherwise assume NoDataValue is 0.\n \n    Parameters\n    ----------\n    b : GDALRasterBand object \n        This is the input band.\n \n    Returns\n    -------\n    b_ndv : float \n        NoData value"
  },
  {
    "code": "def gettext(self, string, domain=None, **variables):\n        t = self.get_translations(domain)\n        return t.ugettext(string) % variables",
    "docstring": "Translate a string with the current locale."
  },
  {
    "code": "def parse(self, rrstr):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('PD record already initialized!')\n        (su_len_unused, su_entry_version_unused) = struct.unpack_from('=BB', rrstr[:4], 2)\n        self.padding = rrstr[4:]\n        self._initialized = True",
    "docstring": "Parse a Rock Ridge Platform Dependent record out of a string.\n\n        Parameters:\n         rrstr - The string to parse the record out of.\n        Returns:\n         Nothing."
  },
  {
    "code": "def listRuns(self, run_num=-1, logical_file_name=\"\",\n                 block_name=\"\", dataset=\"\"):\n        if( '%' in logical_file_name or '%' in block_name or '%' in dataset ):\n            dbsExceptionHandler('dbsException-invalid-input', \n                                \" DBSDatasetRun/listRuns. No wildcards are allowed in logical_file_name, block_name or dataset.\\n.\")\n        conn = self.dbi.connection()\n        tran = False\n        try:\n            ret = self.runlist.execute(conn, run_num, logical_file_name, block_name, dataset, tran)\n            result = []\n            rnum = []\n            for i in ret:\n                rnum.append(i['run_num'])\n            result.append({'run_num' : rnum})\n            return result\n        finally:\n            if conn:\n                conn.close()",
    "docstring": "List run known to DBS."
  },
  {
    "code": "def _where(filename, dirs=[], env=\"PATH\"):\n    if not isinstance(dirs, list):\n        dirs = [dirs]\n    if glob(filename):\n        return filename\n    paths = [os.curdir] + os.environ[env].split(os.path.pathsep) + dirs\n    for path in paths:\n        for match in glob(os.path.join(path, filename)):\n            if match:\n                return os.path.normpath(match)\n    raise IOError(\"File not found: %s\" % filename)",
    "docstring": "Find file in current dir or system path"
  },
  {
    "code": "def reduced_chi_squareds(self, p=None):\n        if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None\n        if p is None: p = self.results[0]\n        r = self.studentized_residuals(p)\n        if r is None: return\n        N = 0\n        for i in range(len(r)): N += len(r[i])\n        dof_per_point = self.degrees_of_freedom()/N\n        for n in range(len(r)):\n            r[n] = sum(r[n]**2)/(len(r[n])*dof_per_point)\n        return r",
    "docstring": "Returns the reduced chi squared for each massaged data set. \n\n        p=None means use the fit results."
  },
  {
    "code": "def cric(display=False):\n    X = pd.read_csv(cache(github_data_url + \"CRIC_time_4yearESRD_X.csv\"))\n    y = np.loadtxt(cache(github_data_url + \"CRIC_time_4yearESRD_y.csv\"))\n    if display:\n        X_display = X.copy()\n        return X_display, y\n    else:\n        return X, y",
    "docstring": "A nicely packaged version of CRIC data with progression to ESRD within 4 years as the label."
  },
  {
    "code": "def get_immediate_children_ownership(self):\n        ownership = Ownership.objects.filter(parent=self).select_related('child', 'child__country')\n        return ownership",
    "docstring": "Return all direct subsidiaries of this company AS OWNERSHIP OBJECTS.\n        Excludes subsidiaries of subsidiaries."
  },
  {
    "code": "def create_view(self, state_root_hash=None):\n        if state_root_hash is None:\n            state_root_hash = INIT_ROOT_KEY\n        merkle_db = MerkleDatabase(self._database,\n                                   merkle_root=state_root_hash)\n        return StateView(merkle_db)",
    "docstring": "Creates a StateView for the given state root hash.\n\n        Args:\n            state_root_hash (str): The state root hash of the state view\n                to return.  If None, returns the state view for the\n        Returns:\n            StateView: state view locked to the given root hash."
  },
  {
    "code": "def get_all_tags_of_reminder(self, reminder_id):\n        return self._iterate_through_pages(\n            get_function=self.get_tags_of_reminder_per_page,\n            resource=REMINDER_TAGS,\n            **{'reminder_id': reminder_id}\n        )",
    "docstring": "Get all tags of reminder\n        This will iterate over all pages until it gets all elements.\n        So if the rate limit exceeded it will throw an Exception and you will get nothing\n\n        :param reminder_id: the reminder id\n        :return: list"
  },
  {
    "code": "def _vertex_different_colors_qubo(G, x_vars):\n    Q = {}\n    for u, v in G.edges:\n        if u not in x_vars or v not in x_vars:\n            continue\n        for color in x_vars[u]:\n            if color in x_vars[v]:\n                Q[(x_vars[u][color], x_vars[v][color])] = 1.\n    return Q",
    "docstring": "For each vertex, it should not have the same color as any of its\n    neighbors. Generates the QUBO to enforce this constraint.\n\n    Notes\n    -----\n    Does not enforce each node having a single color.\n\n    Ground energy is 0, infeasible gap is 1."
  },
  {
    "code": "async def issueClaim(self, schemaId: ID, claimRequest: ClaimRequest,\n                         iA=None,\n                         i=None) -> (Claims, Dict[str, ClaimAttributeValues]):\n        schemaKey = (await self.wallet.getSchema(schemaId)).getKey()\n        attributes = self._attrRepo.getAttributes(schemaKey,\n                                                  claimRequest.userId)\n        await self._genContxt(schemaId, iA, claimRequest.userId)\n        (c1, claim) = await self._issuePrimaryClaim(schemaId, attributes,\n                                                    claimRequest.U)\n        c2 = await self._issueNonRevocationClaim(schemaId, claimRequest.Ur,\n                                                 iA,\n                                                 i) if claimRequest.Ur else None\n        signature = Claims(primaryClaim=c1, nonRevocClaim=c2)\n        return (signature, claim)",
    "docstring": "Issue a claim for the given user and schema.\n\n        :param schemaId: The schema ID (reference to claim\n        definition schema)\n        :param claimRequest: A claim request containing prover ID and\n        prover-generated values\n        :param iA: accumulator ID\n        :param i: claim's sequence number within accumulator\n        :return: The claim (both primary and non-revocation)"
  },
  {
    "code": "def log_level_from_vebosity(verbosity):\n    if verbosity == 0:\n        return logging.WARNING\n    if verbosity == 1:\n        return logging.INFO\n    return logging.DEBUG",
    "docstring": "Get the `logging` module log level from a verbosity.\n\n    :param verbosity: The number of times the `-v` option was specified.\n    :return: The corresponding log level."
  },
  {
    "code": "def set_executing(on: bool):\n    my_thread = threading.current_thread()\n    if isinstance(my_thread, threads.CauldronThread):\n        my_thread.is_executing = on",
    "docstring": "Toggle whether or not the current thread is executing a step file. This\n    will only apply when the current thread is a CauldronThread. This function\n    has no effect when run on a Main thread.\n\n    :param on:\n        Whether or not the thread should be annotated as executing a step file."
  },
  {
    "code": "def notify_observers(self, which=None, min_priority=None):\n        if self._update_on:\n            if which is None:\n                which = self\n            if min_priority is None:\n                [callble(self, which=which) for _, _, callble in self.observers]\n            else:\n                for p, _, callble in self.observers:\n                    if p <= min_priority:\n                        break\n                    callble(self, which=which)",
    "docstring": "Notifies all observers. Which is the element, which kicked off this\n        notification loop. The first argument will be self, the second `which`.\n\n        .. note::\n           \n           notifies only observers with priority p > min_priority!\n           \n        :param min_priority: only notify observers with priority > min_priority\n                             if min_priority is None, notify all observers in order"
  },
  {
    "code": "def _wait_for_function(self, function_descriptor, driver_id, timeout=10):\n        start_time = time.time()\n        warning_sent = False\n        while True:\n            with self.lock:\n                if (self._worker.actor_id.is_nil()\n                        and (function_descriptor.function_id in\n                             self._function_execution_info[driver_id])):\n                    break\n                elif not self._worker.actor_id.is_nil() and (\n                        self._worker.actor_id in self._worker.actors):\n                    break\n            if time.time() - start_time > timeout:\n                warning_message = (\"This worker was asked to execute a \"\n                                   \"function that it does not have \"\n                                   \"registered. You may have to restart \"\n                                   \"Ray.\")\n                if not warning_sent:\n                    ray.utils.push_error_to_driver(\n                        self._worker,\n                        ray_constants.WAIT_FOR_FUNCTION_PUSH_ERROR,\n                        warning_message,\n                        driver_id=driver_id)\n                warning_sent = True\n            time.sleep(0.001)",
    "docstring": "Wait until the function to be executed is present on this worker.\n\n        This method will simply loop until the import thread has imported the\n        relevant function. If we spend too long in this loop, that may indicate\n        a problem somewhere and we will push an error message to the user.\n\n        If this worker is an actor, then this will wait until the actor has\n        been defined.\n\n        Args:\n            function_descriptor : The FunctionDescriptor of the function that\n                we want to execute.\n            driver_id (str): The ID of the driver to push the error message to\n                if this times out."
  },
  {
    "code": "def calc_nfalse(d):\n    dtfactor = n.sum([1./i for i in d['dtarr']])\n    ntrials = d['readints'] * dtfactor * len(d['dmarr']) * d['npixx'] * d['npixy']\n    qfrac = 1 - (erf(d['sigma_image1']/n.sqrt(2)) + 1)/2.\n    nfalse = int(qfrac*ntrials)\n    return nfalse",
    "docstring": "Calculate the number of thermal-noise false positives per segment."
  },
  {
    "code": "def index(*args, **kwargs):\n    _, idx = _index(*args, start=0, step=1, **kwargs)\n    return idx",
    "docstring": "Search a list for an exact element, or element satisfying a predicate.\n\n    Usage::\n\n        index(element, list_)\n        index(of=element, in_=list_)\n        index(where=predicate, in_=list_)\n\n    :param element, of: Element to search for (by equality comparison)\n    :param where: Predicate defining an element to search for.\n                  This should be a callable taking a single argument\n                  and returning a boolean result.\n    :param list_, in_: List to search in\n\n    :return: Index of first matching element, or -1 if none was found\n\n    .. versionadded:: 0.0.3"
  },
  {
    "code": "def _check_warn_threshold(self, time_to, event_dict):\n        if time_to[\"total_minutes\"] <= self.warn_threshold:\n            warn_message = self.py3.safe_format(self.format_notification, event_dict)\n            self.py3.notify_user(warn_message, \"warning\", self.warn_timeout)",
    "docstring": "Checks if the time until an event starts is less than or equal to the\n        warn_threshold. If True, issue a warning with self.py3.notify_user."
  },
  {
    "code": "def recent_submissions(self):\n        for group in self.groups:\n            submission = Submission.most_recent_submission(self, group)\n            if submission:\n                yield submission",
    "docstring": "Generate a list of the most recent submissions for each user.\n\n        Only yields a submission for a user if they've made one."
  },
  {
    "code": "def makedirs_safe(fulldir):\n  try:\n    if not os.path.exists(fulldir): os.makedirs(fulldir)\n  except OSError as exc:\n    import errno\n    if exc.errno == errno.EEXIST: pass\n    else: raise",
    "docstring": "Creates a directory if it does not exists. Takes into consideration\n  concurrent access support. Works like the shell's 'mkdir -p'."
  },
  {
    "code": "def _compute_value(power, wg):\n    if power not in wg:\n        p1, p2 = power\n        if p1 == 0:\n            yy = wg[(0, -1)]\n            wg[power] = numpy.power(yy, p2 / 2).sum() / len(yy)\n        else:\n            xx = wg[(-1, 0)]\n            wg[power] = numpy.power(xx, p1 / 2).sum() / len(xx)\n    return wg[power]",
    "docstring": "Return the weight corresponding to single power."
  },
  {
    "code": "def is_template(self, filename):\n        if self.is_partial(filename):\n            return False\n        if self.is_ignored(filename):\n            return False\n        if self.is_static(filename):\n            return False\n        return True",
    "docstring": "Check if a file is a template.\n\n        A file is a considered a template if it is neither a partial nor\n        ignored.\n\n        :param filename: the name of the file to check"
  },
  {
    "code": "def name(self):\n        if not hasattr(self, 'digest_name'):\n            self.digest_name = Oid(libcrypto.EVP_MD_type(self.digest)\n                                  ).longname()\n        return self.digest_name",
    "docstring": "Returns name of the digest"
  },
  {
    "code": "def deriv(self, mu):\n        p = self._clean(mu)\n        return 1 + 2 * self.alpha * p",
    "docstring": "Derivative of the negative binomial variance function."
  },
  {
    "code": "def fit(self, inputs=None, job_name=None, include_cls_metadata=False, **kwargs):\n        if isinstance(inputs, list) or isinstance(inputs, RecordSet):\n            self.estimator._prepare_for_training(inputs, **kwargs)\n        else:\n            self.estimator._prepare_for_training(job_name)\n        self._prepare_for_training(job_name=job_name, include_cls_metadata=include_cls_metadata)\n        self.latest_tuning_job = _TuningJob.start_new(self, inputs)",
    "docstring": "Start a hyperparameter tuning job.\n\n        Args:\n            inputs: Information about the training data. Please refer to the ``fit()`` method of\n                the associated estimator, as this can take any of the following forms:\n\n                * (str) - The S3 location where training data is saved.\n                * (dict[str, str] or dict[str, sagemaker.session.s3_input]) - If using multiple channels for\n                    training data, you can specify a dict mapping channel names\n                    to strings or :func:`~sagemaker.session.s3_input` objects.\n                * (sagemaker.session.s3_input) - Channel configuration for S3 data sources that can provide\n                    additional information about the training dataset. See :func:`sagemaker.session.s3_input`\n                    for full details.\n                * (sagemaker.amazon.amazon_estimator.RecordSet) - A collection of\n                    Amazon :class:~`Record` objects serialized and stored in S3.\n                    For use with an estimator for an Amazon algorithm.\n                * (list[sagemaker.amazon.amazon_estimator.RecordSet]) - A list of\n                    :class:~`sagemaker.amazon.amazon_estimator.RecordSet` objects, where each instance is\n                    a different channel of training data.\n\n            job_name (str): Tuning job name. If not specified, the tuner generates a default job name,\n                based on the training image name and current timestamp.\n            include_cls_metadata (bool): Whether or not the hyperparameter tuning job should include\n                information about the estimator class (default: False). This information is passed\n                as a hyperparameter, so if the algorithm you are using cannot handle\n                unknown hyperparameters (e.g. an Amazon SageMaker built-in algorithm that\n                does not have a custom estimator in the Python SDK), then set\n                ``include_cls_metadata`` to ``False``.\n            **kwargs: Other arguments needed for training. Please refer to the ``fit()`` method of the associated\n                estimator to see what other arguments are needed."
  },
  {
    "code": "def delete(self):\n        if self._on_delete is not None:\n            return self._on_delete(self)\n        return self._query.delete()",
    "docstring": "Delete a record from the database."
  },
  {
    "code": "def _post(url, data, content_type, params=None):\n        try:\n            response = requests.post(url, params=params, data=data, headers={\n                'Content-Type': content_type,\n            })\n            response.raise_for_status()\n            return response.json()\n        except NameError:\n            url = '{0}?{1}'.format(url, urllib.urlencode(params))\n            req = urllib2.Request(url, data.encode(ENCODING), {\n                'Content-Type': content_type,\n            })\n            return json.loads(urllib2.urlopen(req).read().decode(ENCODING))",
    "docstring": "HTTP POST request."
  },
  {
    "code": "def _is_bhyve_hyper():\n    sysctl_cmd = 'sysctl hw.vmm.create'\n    vmm_enabled = False\n    try:\n        stdout = subprocess.Popen(sysctl_cmd,\n                                  shell=True,\n                                  stdout=subprocess.PIPE).communicate()[0]\n        vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('\"')[1]) != 0\n    except IndexError:\n        pass\n    return vmm_enabled",
    "docstring": "Returns a bool whether or not this node is a bhyve hypervisor"
  },
  {
    "code": "def repeatingfieldsnames(fields):\n    fnames = [field['field'][0] for field in fields]\n    fnames = [bunchhelpers.onlylegalchar(fname) for fname in fnames]\n    fnames = [fname for fname in fnames if bunchhelpers.intinlist(fname.split())]\n    fnames = [(bunchhelpers.replaceint(fname), None) for fname in fnames]\n    dct = dict(fnames)\n    repnames = fnames[:len(list(dct.keys()))]\n    return repnames",
    "docstring": "get the names of the repeating fields"
  },
  {
    "code": "def _create_reference_value_options(self, keys, finished_keys):\n        set_of_reference_value_option_names = set()\n        for key in keys:\n            if key in finished_keys:\n                continue\n            an_option = self.option_definitions[key]\n            if an_option.reference_value_from:\n                fully_qualified_reference_name = '.'.join((\n                    an_option.reference_value_from,\n                    an_option.name\n                ))\n                if fully_qualified_reference_name in keys:\n                    continue\n                reference_option = an_option.copy()\n                reference_option.reference_value_from = None\n                reference_option.name = fully_qualified_reference_name\n                set_of_reference_value_option_names.add(\n                    fully_qualified_reference_name\n                )\n                self.option_definitions.add_option(reference_option)\n        for a_reference_value_option_name in set_of_reference_value_option_names:\n            for x in range(a_reference_value_option_name.count('.')):\n                namespace_path = \\\n                    a_reference_value_option_name.rsplit('.', x + 1)[0]\n                self.option_definitions[namespace_path].ref_value_namespace()\n        return set_of_reference_value_option_names",
    "docstring": "this method steps through the option definitions looking for\n        alt paths.  On finding one, it creates the 'reference_value_from' links\n        within the option definitions and populates it with copied options."
  },
  {
    "code": "def gateway():\n    if settings.CAS_GATEWAY == False:\n        raise ImproperlyConfigured('CAS_GATEWAY must be set to True')\n    def wrap(func):\n        def wrapped_f(*args):\n            from cas.views import login\n            request = args[0]\n            try:\n                is_authenticated = request.user.is_authenticated()\n            except TypeError:\n                is_authenticated = request.user.is_authenticated\n            if is_authenticated:\n                pass\n            else:\n                path_with_params = request.path + '?' + urlencode(request.GET.copy())\n                if request.GET.get('ticket'):\n                    response = login(request, path_with_params, False, True)\n                    if isinstance(response, HttpResponseRedirect):\n                        return response\n                else:\n                    gatewayed = request.GET.get('gatewayed')\n                    if gatewayed == 'true':\n                        pass\n                    else:\n                        response = login(request, path_with_params, False, True)\n                        if isinstance(response, HttpResponseRedirect):\n                            return response\n            return func(*args)\n        return wrapped_f\n    return wrap",
    "docstring": "Authenticates single sign on session if ticket is available,\n    but doesn't redirect to sign in url otherwise."
  },
  {
    "code": "def complete_run(self, text, line, b, e):\n        text = line.split()[-1]\n        forth_files = glob.glob(text + '*.fs')\n        if len(forth_files) == 0:\n            return [f.split(os.path.sep)[-1] for f in glob.glob(text + '*')]\n        forth_files = [f.split(os.path.sep)[-1] for f in forth_files]\n        return forth_files",
    "docstring": "Autocomplete file names with .forth ending."
  },
  {
    "code": "def ensure_dict(param, default_value, default_key=None):\n    if not param:\n        param = default_value\n    if not isinstance(param, dict):\n        if param:\n            default_value = param\n        return {default_key: param}, default_value\n    return param, default_value",
    "docstring": "Retrieves a dict and a default value from given parameter.\n\n    if parameter is not a dict, it will be promoted as the default value.\n\n    :param param:\n    :type param:\n    :param default_value:\n    :type default_value:\n    :param default_key:\n    :type default_key:\n    :return:\n    :rtype:"
  },
  {
    "code": "def set_root(self, depth, index):\n        if depth < len(self._levels):\n            self._levels[depth].set_root(index)",
    "docstring": "Set the level\\'s root of the given depth to index\n\n        :param depth: the depth level\n        :type depth: int\n        :param index: the new root index\n        :type index: QtCore.QModelIndex\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def add_rule(name,\n             localport,\n             protocol='tcp',\n             action='allow',\n             dir='in',\n             remoteip='any'):\n    ret = {'name': name,\n           'result': True,\n           'changes': {},\n           'comment': ''}\n    if not __salt__['firewall.rule_exists'](name):\n        ret['changes'] = {'new rule': name}\n    else:\n        ret['comment'] = 'A rule with that name already exists'\n        return ret\n    if __opts__['test']:\n        ret['result'] = not ret['changes'] or None\n        ret['comment'] = ret['changes']\n        ret['changes'] = {}\n        return ret\n    try:\n        __salt__['firewall.add_rule'](\n            name, localport, protocol, action, dir, remoteip)\n    except CommandExecutionError:\n        ret['comment'] = 'Could not add rule'\n    return ret",
    "docstring": "Add a new inbound or outbound rule to the firewall policy\n\n    Args:\n\n        name (str): The name of the rule. Must be unique and cannot be \"all\".\n            Required.\n\n        localport (int): The port the rule applies to. Must be a number between\n            0 and 65535. Can be a range. Can specify multiple ports separated by\n            commas. Required.\n\n        protocol (Optional[str]): The protocol. Can be any of the following:\n\n            - A number between 0 and 255\n            - icmpv4\n            - icmpv6\n            - tcp\n            - udp\n            - any\n\n        action (Optional[str]): The action the rule performs. Can be any of the\n            following:\n\n            - allow\n            - block\n            - bypass\n\n        dir (Optional[str]): The direction. Can be ``in`` or ``out``.\n\n        remoteip (Optional [str]): The remote IP. Can be any of the following:\n\n            - any\n            - localsubnet\n            - dns\n            - dhcp\n            - wins\n            - defaultgateway\n            - Any valid IPv4 address (192.168.0.12)\n            - Any valid IPv6 address (2002:9b3b:1a31:4:208:74ff:fe39:6c43)\n            - Any valid subnet (192.168.1.0/24)\n            - Any valid range of IP addresses (192.168.0.1-192.168.0.12)\n            - A list of valid IP addresses\n\n            Can be combinations of the above separated by commas.\n\n            .. versionadded:: 2016.11.6\n\n    Example:\n\n    .. code-block:: yaml\n\n        open_smb_port:\n          win_firewall.add_rule:\n            - name: SMB (445)\n            - localport: 445\n            - protocol: tcp\n            - action: allow"
  },
  {
    "code": "def keep_session_alive(self):\n        try:\n            self.resources()\n        except xmlrpclib.Fault as fault:\n            if fault.faultCode == 5:\n                self.login()\n            else:\n                raise",
    "docstring": "If the session expired, logs back in."
  },
  {
    "code": "def make_html_page(self, valumap):\n        logger.info('Making an html report using template %r.', self.html_template)\n        fh = open(self.html_template)\n        template = fh.read()\n        fh.close()\n        parts = []\n        for sr in self.subreports:\n            report_data = [item.html for item in sr.report_data if item.html]\n            if report_data:\n                parts.append('\\n<h2>{1}</h2>\\n'.format(sr.title, sr.reptext))\n                parts.extend(report_data)\n                parts.append('\\n<hr/>')\n        valumap['subreports'] = '\\n'.join(parts)\n        html_page = Template(template).safe_substitute(valumap)\n        return TextPart(fmt='html', text=html_page, ext='html')",
    "docstring": "Builds the report as html page, using the template page from file."
  },
  {
    "code": "def _get_goroot(self, goids_all, namespace):\n        root_goid = self.consts.NAMESPACE2GO[namespace]\n        if root_goid in goids_all:\n            return root_goid\n        root_goids = set()\n        for goid in goids_all:\n            goterm = self.gosubdag.go2obj[goid]\n            if goterm.depth == 0:\n                root_goids.add(goterm.id)\n        if len(root_goids) == 1:\n            return next(iter(root_goids))\n        raise RuntimeError(\"UNEXPECTED NUMBER OF ROOTS: {R}\".format(R=root_goids))",
    "docstring": "Get the top GO for the set of goids_all."
  },
  {
    "code": "def format_exception(self):\n        import traceback\n        frames = self.get_traceback_frames()\n        tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames]\n        list = ['Traceback (most recent call last):\\n']\n        list += traceback.format_list(tb)\n        list += traceback.format_exception_only(self.exc_type, self.exc_value)\n        return list",
    "docstring": "Return the same data as from traceback.format_exception."
  },
  {
    "code": "def get_summary(self, squeeze=True, parameters=None, chains=None):\n        results = []\n        if chains is None:\n            chains = self.parent.chains\n        else:\n            if isinstance(chains, (int, str)):\n                chains = [chains]\n            chains = [self.parent.chains[i] for c in chains for i in self.parent._get_chain(c)]\n        for chain in chains:\n            res = {}\n            params_to_find = parameters if parameters is not None else chain.parameters\n            for p in params_to_find:\n                if p not in chain.parameters:\n                    continue\n                summary = self.get_parameter_summary(chain, p)\n                res[p] = summary\n            results.append(res)\n        if squeeze and len(results) == 1:\n            return results[0]\n        return results",
    "docstring": "Gets a summary of the marginalised parameter distributions.\n\n        Parameters\n        ----------\n        squeeze : bool, optional\n            Squeeze the summaries. If you only have one chain, squeeze will not return\n            a length one list, just the single summary. If this is false, you will\n            get a length one list.\n        parameters : list[str], optional\n            A list of parameters which to generate summaries for.\n        chains : list[int|str], optional\n            A list of the chains to get a summary of.\n\n        Returns\n        -------\n        list of dictionaries\n            One entry per chain, parameter bounds stored in dictionary with parameter as key"
  },
  {
    "code": "def experiments_fmri_create(self, experiment_id, filename):\n        experiment = self.experiments_get(experiment_id)\n        if experiment is None:\n            return None\n        fmri = self.funcdata.create_object(filename)\n        experiment = self.experiments.update_fmri_data(experiment_id, fmri.identifier)\n        if experiment is None:\n            shutil.rmtree(fmri.directory)\n            self.funcdata.delete_object(fmri.identifier, erase=True)\n            return None\n        else:\n            return funcdata.FMRIDataHandle(fmri, experiment_id)",
    "docstring": "Create functional data object from given file and associate the\n        object with the specified experiment.\n\n        Parameters\n        ----------\n        experiment_id : string\n            Unique experiment identifier\n        filename : File-type object\n            Functional data file\n\n        Returns\n        -------\n        FMRIDataHandle\n            Handle for created fMRI object or None if identified experiment\n            is unknown"
  },
  {
    "code": "def vividict_to_dict(vividict):\n        try:\n            from numpy import ndarray\n        except ImportError:\n            ndarray = dict\n        dictionary = {}\n        def np_to_native(np_val):\n            if isinstance(np_val, dict):\n                for key, value in np_val.items():\n                    np_val[key] = np_to_native(value)\n            elif isinstance(np_val, ndarray):\n                np_val = np_val.tolist()\n            if isinstance(np_val, (list, tuple)):\n                native_list = [np_to_native(val) for val in np_val]\n                if isinstance(np_val, tuple):\n                    return tuple(native_list)\n                return native_list\n            if not hasattr(np_val, 'dtype'):\n                return np_val\n            return np_val.item()\n        for key, value in vividict.items():\n            value = np_to_native(value)\n            if isinstance(value, Vividict):\n                value = Vividict.vividict_to_dict(value)\n            dictionary[key] = value\n        return dictionary",
    "docstring": "Helper method to create Python dicts from arbitrary Vividict objects\n\n        :param Vividict vividict: A Vividict to be converted\n        :return: A Python dict\n        :rtype: dict"
  },
  {
    "code": "def _separate_exclude_cases(name, exclude_prefix):\n        excluder = re.compile('|'.join(exclude_prefix))\n        split_entries = excluder.split(name)\n        return {'clean_name': split_entries[0],\n                'excluded_countries': split_entries[1:]}",
    "docstring": "Splits the excluded\n\n        Parameters\n        ----------\n        name : str\n            Name of the country/region to convert.\n\n        exclude_prefix : list of valid regex strings\n            List of indicators which negate the subsequent country/region.\n            These prefixes and everything following will not be converted.\n            E.g. 'Asia excluding China' becomes 'Asia' and\n            'China excluding Hong Kong' becomes 'China' prior to conversion\n\n\n        Returns\n        -------\n\n        dict with\n            'clean_name' : str\n                as name without anything following exclude_prefix\n            'excluded_countries' : list\n                list of excluded countries"
  },
  {
    "code": "def play_tour(self, name=None, interval=0):\n        if self.headless:\n            return\n        if not name:\n            name = \"default\"\n        if name not in self._tour_steps:\n            raise Exception(\"Tour {%s} does not exist!\" % name)\n        if \"Bootstrap\" in self._tour_steps[name][0]:\n            tour_helper.play_bootstrap_tour(\n                self.driver, self._tour_steps, self.browser,\n                self.message_duration, name=name, interval=interval)\n        elif \"Hopscotch\" in self._tour_steps[name][0]:\n            tour_helper.play_hopscotch_tour(\n                self.driver, self._tour_steps, self.browser,\n                self.message_duration, name=name, interval=interval)\n        elif \"IntroJS\" in self._tour_steps[name][0]:\n            tour_helper.play_introjs_tour(\n                self.driver, self._tour_steps, self.browser,\n                self.message_duration, name=name, interval=interval)\n        else:\n            tour_helper.play_shepherd_tour(\n                self.driver, self._tour_steps,\n                self.message_duration, name=name, interval=interval)",
    "docstring": "Plays a tour on the current website.\n            @Params\n            name - If creating multiple tours at the same time,\n                   use this to select the tour you wish to add steps to.\n            interval - The delay time between autoplaying tour steps.\n                       If set to 0 (default), the tour is fully manual control."
  },
  {
    "code": "def strel_octagon(radius):\n    iradius = int(radius)\n    i, j = np.mgrid[-iradius:(iradius + 1), -iradius:(iradius+1)]\n    dradius = float(iradius) * np.sqrt(2)\n    strel = (((i+j) <= dradius) & ((i+j) >= -dradius) &\n             ((i-j) <= dradius) & ((i-j) >= -dradius))\n    return strel",
    "docstring": "Create an octagonal structuring element for morphological operations\n    \n    radius - the distance from the origin to each edge of the octagon"
  },
  {
    "code": "def need_to_create_symlink(directory, checksums, filetype, symlink_path):\n    if symlink_path is None:\n        return False\n    pattern = NgdConfig.get_fileending(filetype)\n    filename, _ = get_name_and_checksum(checksums, pattern)\n    full_filename = os.path.join(directory, filename)\n    symlink_name = os.path.join(symlink_path, filename)\n    if os.path.islink(symlink_name):\n        existing_link = os.readlink(symlink_name)\n        if full_filename == existing_link:\n            return False\n    return True",
    "docstring": "Check if we need to create a symlink for an existing file."
  },
  {
    "code": "def unique_to_each(*iterables):\n    pool = [list(it) for it in iterables]\n    counts = Counter(chain.from_iterable(map(set, pool)))\n    uniques = {element for element in counts if counts[element] == 1}\n    return [list(filter(uniques.__contains__, it)) for it in pool]",
    "docstring": "Return the elements from each of the input iterables that aren't in the\n    other input iterables.\n\n    For example, suppose you have a set of packages, each with a set of\n    dependencies::\n\n        {'pkg_1': {'A', 'B'}, 'pkg_2': {'B', 'C'}, 'pkg_3': {'B', 'D'}}\n\n    If you remove one package, which dependencies can also be removed?\n\n    If ``pkg_1`` is removed, then ``A`` is no longer necessary - it is not\n    associated with ``pkg_2`` or ``pkg_3``. Similarly, ``C`` is only needed for\n    ``pkg_2``, and ``D`` is only needed for ``pkg_3``::\n\n        >>> unique_to_each({'A', 'B'}, {'B', 'C'}, {'B', 'D'})\n        [['A'], ['C'], ['D']]\n\n    If there are duplicates in one input iterable that aren't in the others\n    they will be duplicated in the output. Input order is preserved::\n\n        >>> unique_to_each(\"mississippi\", \"missouri\")\n        [['p', 'p'], ['o', 'u', 'r']]\n\n    It is assumed that the elements of each iterable are hashable."
  },
  {
    "code": "def get(self):\n        if not hasattr(self, '_instance'):\n            raise ImplementationError(\"Impossible to get the PK of an unbound field\")\n        if not hasattr(self._instance, '_pk'):\n            raise DoesNotExist(\"The current object doesn't exists anymore\")\n        if not self._instance._pk:\n            self.set(value=None)\n        return self.normalize(self._instance._pk)",
    "docstring": "We do not call the default getter as we have the value cached in the\n        instance in its _pk attribute"
  },
  {
    "code": "def remove_file_from_s3(awsclient, bucket, key):\n    client_s3 = awsclient.get_client('s3')\n    response = client_s3.delete_object(Bucket=bucket, Key=key)",
    "docstring": "Remove a file from an AWS S3 bucket.\n\n    :param awsclient:\n    :param bucket:\n    :param key:\n    :return:"
  },
  {
    "code": "def commit_events(self):\n        for event in sorted(self._event_buf):\n            self.store.record_event(event)\n            self._snapshot.process_event(event)\n        self._event_buf = []",
    "docstring": "Applies all outstanding `Event`s to the internal state"
  },
  {
    "code": "async def pause_writing(self):\n        self._restart_writer = False\n        if self._writer_task:\n            self._writer_task.remove_done_callback(self.restart_writing)\n            self._writer_task.cancel()\n            await self._writer_task\n            await asyncio.sleep(0, loop=self._loop)",
    "docstring": "Pause writing."
  },
  {
    "code": "def submit_and_verify(\n    xml_str=None, xml_file=None, xml_root=None, config=None, session=None, dry_run=None, **kwargs\n):\n    try:\n        config = config or configuration.get_config()\n        xml_root = _get_xml_root(xml_root, xml_str, xml_file)\n        submit_config = SubmitConfig(xml_root, config, **kwargs)\n        session = session or utils.get_session(submit_config.credentials, config)\n        submit_response = submit(xml_root, submit_config, session, dry_run=dry_run, **kwargs)\n    except Dump2PolarionException as err:\n        logger.error(err)\n        return None\n    valid_response = submit_response.validate_response()\n    if not valid_response or kwargs.get(\"no_verify\"):\n        return submit_response.response\n    response = verify_submit(\n        session,\n        submit_config.queue_url,\n        submit_config.log_url,\n        submit_response.job_ids,\n        timeout=kwargs.get(\"verify_timeout\"),\n        log_file=kwargs.get(\"log_file\"),\n    )\n    return response",
    "docstring": "Submits data to the Polarion Importer and checks that it was imported."
  },
  {
    "code": "def _tot_services_by_state(self, state=None, state_type=None):\n        if state is None and state_type is None:\n            return len(self.services)\n        if state_type:\n            return sum(1 for s in self.services if s.state == state and s.state_type == state_type)\n        return sum(1 for s in self.services if s.state == state)",
    "docstring": "Generic function to get the number of services in the specified state\n\n        :param state: state to filter on\n        :type state: str\n        :param state_type: state type to filter on (HARD, SOFT)\n        :type state_type: str\n        :return: number of host in state *state*\n        :rtype: int\n        TODO: Should be moved"
  },
  {
    "code": "def _MessageToJsonObject(self, message):\n    message_descriptor = message.DESCRIPTOR\n    full_name = message_descriptor.full_name\n    if _IsWrapperMessage(message_descriptor):\n      return self._WrapperMessageToJsonObject(message)\n    if full_name in _WKTJSONMETHODS:\n      return methodcaller(_WKTJSONMETHODS[full_name][0], message)(self)\n    js = {}\n    return self._RegularMessageToJsonObject(message, js)",
    "docstring": "Converts message to an object according to Proto3 JSON Specification."
  },
  {
    "code": "def _prepare_to_send_ack(self, path, ack_id):\n        'Return function that acknowledges the server'\n        return lambda *args: self._ack(path, ack_id, *args)",
    "docstring": "Return function that acknowledges the server"
  },
  {
    "code": "def addService(self, service, name=None, description=None,\n        authenticator=None, expose_request=None, preprocessor=None):\n        if isinstance(service, (int, long, float, basestring)):\n            raise TypeError(\"Service cannot be a scalar value\")\n        allowed_types = (types.ModuleType, types.FunctionType, types.DictType,\n            types.MethodType, types.InstanceType, types.ObjectType)\n        if not python.callable(service) and not isinstance(service, allowed_types):\n            raise TypeError(\"Service must be a callable, module, or an object\")\n        if name is None:\n            if isinstance(service, (type, types.ClassType)):\n                name = service.__name__\n            elif isinstance(service, types.FunctionType):\n                name = service.func_name\n            elif isinstance(service, types.ModuleType):\n                name = service.__name__\n            else:\n                name = str(service)\n        if name in self.services:\n            raise remoting.RemotingError(\"Service %s already exists\" % name)\n        self.services[name] = ServiceWrapper(service, description,\n            authenticator, expose_request, preprocessor)",
    "docstring": "Adds a service to the gateway.\n\n        @param service: The service to add to the gateway.\n        @type service: C{callable}, class instance, or a module\n        @param name: The name of the service.\n        @type name: C{str}\n        @raise pyamf.remoting.RemotingError: Service already exists.\n        @raise TypeError: C{service} cannot be a scalar value.\n        @raise TypeError: C{service} must be C{callable} or a module."
  },
  {
    "code": "def get_overall_state(self, services):\n        overall_state = 0\n        if not self.monitored:\n            overall_state = 5\n        elif self.acknowledged:\n            overall_state = 1\n        elif self.downtimed:\n            overall_state = 2\n        elif self.state_type == 'HARD':\n            if self.state == 'UNREACHABLE':\n                overall_state = 3\n            elif self.state == 'DOWN':\n                overall_state = 4\n        if overall_state <= 2:\n            for service in self.services:\n                if service in services:\n                    service = services[service]\n                    if service.overall_state_id < 5:\n                        overall_state = max(overall_state, service.overall_state_id)\n        return overall_state",
    "docstring": "Get the host overall state including the host self status\n        and the status of its services\n\n        Compute the host overall state identifier, including:\n        - the acknowledged state\n        - the downtime state\n\n        The host overall state is (prioritized):\n        - an host not monitored (5)\n        - an host down (4)\n        - an host unreachable (3)\n        - an host downtimed (2)\n        - an host acknowledged (1)\n        - an host up (0)\n\n        If the host overall state is <= 2, then the host overall state is the maximum value\n        of the host overall state and all the host services overall states.\n\n        The overall state of an host is:\n        - 0 if the host is UP and all its services are OK\n        - 1 if the host is DOWN or UNREACHABLE and acknowledged or\n            at least one of its services is acknowledged and\n            no other services are WARNING or CRITICAL\n        - 2 if the host is DOWN or UNREACHABLE and in a scheduled downtime or\n            at least one of its services is in a scheduled downtime and no\n            other services are WARNING or CRITICAL\n        - 3 if the host is UNREACHABLE or\n            at least one of its services is WARNING\n        - 4 if the host is DOWN or\n            at least one of its services is CRITICAL\n        - 5 if the host is not monitored\n\n        :param services: a list of known services\n        :type services: alignak.objects.service.Services\n\n        :return: the host overall state\n        :rtype: int"
  },
  {
    "code": "def check_cursor_location(self):\n        data_x, data_y = self.get_data_xy(self.last_win_x,\n                                          self.last_win_y)\n        if (data_x != self.last_data_x or\n            data_y != self.last_data_y):\n            self.last_data_x, self.last_data_y = data_x, data_y\n            self.logger.debug(\"cursor location changed %.4f,%.4f => %.4f,%.4f\" % (\n                self.last_data_x, self.last_data_y, data_x, data_y))\n            button = 0\n            self.make_ui_callback('cursor-changed', button, data_x, data_y)\n        return data_x, data_y",
    "docstring": "Check whether the data location of the last known position\n        of the cursor has changed.  If so, issue a callback."
  },
  {
    "code": "def traverse_depth_first_pre_order(self, callback):\n        n = len(self.suftab)\n        root = [0, 0, n - 1, \"\"]\n        def _traverse_top_down(interval):\n            callback(interval)\n            i, j = interval[1], interval[2]\n            if i != j:\n                children = self._get_child_intervals(i, j)\n                children.sort(key=lambda child: child[3])\n                for child in children:\n                    _traverse_top_down(child)\n        _traverse_top_down(root)",
    "docstring": "Visits the internal \"nodes\" of the enhanced suffix array in depth-first pre-order.\n\n        Based on Abouelhoda et al. (2004)."
  },
  {
    "code": "def get_failed_job(self, id):\n        url = self._url('{}/errors'.format(id))\n        return self.client.get(url)",
    "docstring": "Get failed job error details\n\n        Args:\n            id (str): The id of the job.\n\n        See: https://auth0.com/docs/api/management/v2#!/Jobs/get_errors"
  },
  {
    "code": "def run(self):\n        try:\n            while True:\n                message = self.connection.recv()\n                result = self.on_message(message)\n                if result:\n                    self.connection.send(result)\n        except SelenolWebSocketClosedException as ex:\n            self.on_closed(0, '')\n            raise SelenolWebSocketClosedException() from ex",
    "docstring": "Run the service in infinitive loop processing requests."
  },
  {
    "code": "def check_user(user_id, u_pass):\n        user_count = TabMember.select().where(TabMember.uid == user_id).count()\n        if user_count == 0:\n            return -1\n        the_user = TabMember.get(uid=user_id)\n        if the_user.user_pass == tools.md5(u_pass):\n            return 1\n        return 0",
    "docstring": "Checking the password by user's ID."
  },
  {
    "code": "def qual(args):\n    from jcvi.formats.sizes import Sizes\n    p = OptionParser(qual.__doc__)\n    p.add_option(\"--qv\", default=31, type=\"int\",\n                 help=\"Dummy qv score for extended bases\")\n    p.set_outfile()\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(not p.print_help())\n    fastafile, = args\n    sizes = Sizes(fastafile)\n    qvchar = str(opts.qv)\n    fw = must_open(opts.outfile, \"w\")\n    total = 0\n    for s, slen in sizes.iter_sizes():\n        print(\">\" + s, file=fw)\n        print(\" \".join([qvchar] * slen), file=fw)\n        total += 1\n    fw.close()\n    logging.debug(\"Written {0} records in `{1}`.\".format(total, opts.outfile))",
    "docstring": "%prog qual fastafile\n\n    Generate dummy .qual file based on FASTA file."
  },
  {
    "code": "def shutdown(self, message=None):\n        for name, server in self.servers.items():\n            server.quit(message)",
    "docstring": "Disconnect all servers with a message.\n\n        Args:\n            message (str): Quit message to use on each connection."
  },
  {
    "code": "def create_question_dialog(self, text, second_text):\n        dialog = self.create_message_dialog(\n            text, buttons=Gtk.ButtonsType.YES_NO, icon=Gtk.MessageType.QUESTION\n        )\n        dialog.format_secondary_text(second_text)\n        response = dialog.run()\n        dialog.destroy()\n        return response",
    "docstring": "Function creates a question dialog with title text\n        and second_text"
  },
  {
    "code": "def print_cyjs_graph(self):\n        cyjs_dict = {'edges': self._edges, 'nodes': self._nodes}\n        cyjs_str = json.dumps(cyjs_dict, indent=1, sort_keys=True)\n        return cyjs_str",
    "docstring": "Return the assembled Cytoscape JS network as a json string.\n\n        Returns\n        -------\n        cyjs_str : str\n            A json string representation of the Cytoscape JS network."
  },
  {
    "code": "def _extract_file(self, zf, info, extract_dir):\n        out_path = os.path.join(extract_dir, info.filename)\n        out_path = os.path.abspath(out_path)\n        if not out_path.startswith(extract_dir):\n            raise ValueError(\n                \"malicious zipfile, %s outside of extract_dir %s\" %\n                (info.filename, extract_dir))\n        zf.extract(info.filename, path=extract_dir)\n        perm = info.external_attr >> 16\n        os.chmod(out_path, perm)",
    "docstring": "the zipfile module does not restore file permissions\n        so we'll do it manually"
  },
  {
    "code": "def write(self, endpoints, filename):\n        with open(filename, \"w\") as filep:\n            filep.write(self.to_string(endpoints))",
    "docstring": "Writes the given endpoint descriptions to the given file\n\n        :param endpoints: A list of EndpointDescription beans\n        :param filename: Name of the file where to write the XML\n        :raise IOError: Error writing the file"
  },
  {
    "code": "def cc(self, chan, ctrl, val):\n        return fluid_synth_cc(self.synth, chan, ctrl, val)",
    "docstring": "Send control change value.\n\n        The controls that are recognized are dependent on the\n        SoundFont.  Values are always 0 to 127.  Typical controls\n        include:\n          1: vibrato\n          7: volume\n          10: pan (left to right)\n          11: expression (soft to loud)\n          64: sustain\n          91: reverb\n          93: chorus"
  },
  {
    "code": "def simple_balance(self, as_of=None, raw=False, leg_query=None, **kwargs):\n        legs = self.legs\n        if as_of:\n            legs = legs.filter(transaction__date__lte=as_of)\n        if leg_query or kwargs:\n            leg_query = leg_query or models.Q()\n            legs = legs.filter(leg_query, **kwargs)\n        return legs.sum_to_balance() * (1 if raw else self.sign) + self._zero_balance()",
    "docstring": "Get the balance for this account, ignoring all child accounts\n\n        Args:\n            as_of (Date): Only include transactions on or before this date\n            raw (bool): If true the returned balance should not have its sign\n                        adjusted for display purposes.\n            leg_query (models.Q): Django Q-expression, will be used to filter the transaction legs.\n                                  allows for more complex filtering than that provided by **kwargs.\n            kwargs (dict): Will be used to filter the transaction legs\n\n        Returns:\n            Balance"
  },
  {
    "code": "def is_pythonw(filename):\r\n    pattern = r'.*python(\\d\\.?\\d*)?w(.exe)?$'\r\n    if re.match(pattern, filename, flags=re.I) is None:\r\n        return False\r\n    else:\r\n        return True",
    "docstring": "Check that the python interpreter has 'pythonw'."
  },
  {
    "code": "def _fun_names_iter(self, functyp, val):\n        funcstore = getattr(self.engine, functyp)\n        for v in val:\n            if callable(v):\n                setattr(funcstore, v.__name__, v)\n                yield v.__name__\n            elif v not in funcstore:\n                raise KeyError(\"Function {} not present in {}\".format(\n                    v, funcstore._tab\n                ))\n            else:\n                yield v",
    "docstring": "Iterate over the names of the functions in ``val``,\n        adding them to ``funcstore`` if they are missing;\n        or if the items in ``val`` are already the names of functions\n        in ``funcstore``, iterate over those."
  },
  {
    "code": "def usage():\n    l_bracket = clr.stringc(\"[\", \"dark gray\")\n    r_bracket = clr.stringc(\"]\", \"dark gray\")\n    pipe = clr.stringc(\"|\", \"dark gray\")\n    app_name = clr.stringc(\"%prog\", \"bright blue\")\n    commands = clr.stringc(\"{0}\".format(pipe).join(c.VALID_ACTIONS), \"normal\")\n    help = clr.stringc(\"--help\", \"green\")\n    options = clr.stringc(\"options\", \"yellow\")\n    guide = \"\\n\\n\"\n    for action in c.VALID_ACTIONS:\n        guide += command_name(app_name, action,\n                              c.MESSAGES[\"help_\" + action])\n    guide = guide[:-1]\n    return \"{0} {1}{2}{3} {1}{4}{3} {1}{5}{3}\\n{6}\".format(app_name,\n                                                           l_bracket,\n                                                           commands,\n                                                           r_bracket,\n                                                           help,\n                                                           options,\n                                                           guide)",
    "docstring": "Return the usage for the help command."
  },
  {
    "code": "def _meters_per_pixel(zoom, lat=0.0, tilesize=256):\n    return (math.cos(lat * math.pi / 180.0) * 2 * math.pi * 6378137) / (\n        tilesize * 2 ** zoom\n    )",
    "docstring": "Return the pixel resolution for a given mercator tile zoom and lattitude.\n\n    Parameters\n    ----------\n    zoom: int\n        Mercator zoom level\n    lat: float, optional\n        Latitude in decimal degree (default: 0)\n    tilesize: int, optional\n        Mercator tile size (default: 256).\n\n    Returns\n    -------\n    Pixel resolution in meters"
  },
  {
    "code": "def _make_instance(cls, element_class, webelement):\n        if isinstance(webelement, FirefoxWebElement):\n            element_class = copy.deepcopy(element_class)\n            element_class.__bases__ = tuple(\n                FirefoxWebElement if base is WebElement else base\n                for base in element_class.__bases__\n            )\n        return element_class(webelement)",
    "docstring": "Firefox uses another implementation of element. This method\n        switch base of wrapped element to firefox one."
  },
  {
    "code": "def get_from_search_doc(cls, doc_id):\n        if hasattr(doc_id, 'doc_id'):\n            doc_id = doc_id.doc_id\n        return cls.from_urlsafe(doc_id)",
    "docstring": "Returns an instance of the model from a search document id.\n\n        :param doc_id: Search document id\n        :return: Instance of cls"
  },
  {
    "code": "def get_edit_scripts(pron_a, pron_b, edit_costs=(1.0, 1.0, 1.0)):\n    op_costs = {'insert': lambda x: edit_costs[0],\n                'match': lambda x, y: 0 if x == y else edit_costs[1],\n                'delete': lambda x: edit_costs[2]}\n    distance, scripts, costs, ops = edit_distance.best_transforms(pron_a, pron_b, op_costs=op_costs)\n    return [full_edit_script(script.to_primitive()) for script in scripts]",
    "docstring": "Get the edit scripts to transform between two given pronunciations.\n\n    :param pron_a: Source pronunciation as list of strings, each string corresponding to a phoneme\n    :param pron_b: Target pronunciation as list of strings, each string corresponding to a phoneme\n    :param edit_costs: Costs of insert, replace and delete respectively\n    :return: List of edit scripts.  Each edit script is represented as a list of operations,\n                where each operation is a dictionary."
  },
  {
    "code": "async def async_set_port_poe_mode(self, port_idx, mode):\n        no_existing_config = True\n        for port_override in self.port_overrides:\n            if port_idx == port_override['port_idx']:\n                port_override['poe_mode'] = mode\n                no_existing_config = False\n                break\n        if no_existing_config:\n            self.port_overrides.append({\n                'port_idx': port_idx,\n                'portconf_id': self.ports[port_idx].portconf_id,\n                'poe_mode': mode\n            })\n        url = 's/{site}/rest/device/' + self.id\n        data = {'port_overrides': self.port_overrides}\n        await self._request('put', url, json=data)",
    "docstring": "Set port poe mode.\n\n        Auto, 24v, passthrough, off.\n        Make sure to not overwrite any existing configs."
  },
  {
    "code": "def cmd_create(self, name, auto=False):\n        LOGGER.setLevel('INFO')\n        LOGGER.propagate = 0\n        router = Router(self.database,\n                        migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'],\n                        migrate_table=self.app.config['PEEWEE_MIGRATE_TABLE'])\n        if auto:\n            auto = self.models\n        router.create(name, auto=auto)",
    "docstring": "Create a new migration."
  },
  {
    "code": "def is_win64():\n    global _is_win64\n    if _is_win64 is None:\n        _is_win64 = False\n        if os.environ.get('PROCESSOR_ARCHITECTURE', 'x86') != 'x86':\n            _is_win64 = True\n        if os.environ.get('PROCESSOR_ARCHITEW6432'):\n            _is_win64 = True\n        if os.environ.get('ProgramW6432'):\n            _is_win64 = True\n    return _is_win64",
    "docstring": "Return true if running on windows 64 bits.\n\n    Works whether python itself runs in 64 bits or 32 bits."
  },
  {
    "code": "def unmapped(sam, mates):\n    for read in sam:\n        if read.startswith('@') is True:\n            continue\n        read = read.strip().split()\n        if read[2] == '*' and read[6] == '*':\n                yield read\n        elif mates is True:\n            if read[2] == '*' or read[6] == '*':\n                yield read\n            for i in read:\n                if i == 'YT:Z:UP':\n                    yield read",
    "docstring": "get unmapped reads"
  },
  {
    "code": "def _dump_additional_attributes(additional_attributes):\n    attributes_raw = io.BytesIO(additional_attributes)\n    attributes_hex = binascii.hexlify(additional_attributes)\n    if not len(additional_attributes):\n        return attributes_hex\n    len_attribute, = unpack('<I', attributes_raw.read(4))\n    if len_attribute != 8:\n        return attributes_hex\n    attr_id, = unpack('<I', attributes_raw.read(4))\n    if attr_id != APK._APK_SIG_ATTR_V2_STRIPPING_PROTECTION:\n        return attributes_hex\n    scheme_id, = unpack('<I', attributes_raw.read(4))\n    return \"stripping protection set, scheme %d\" % scheme_id",
    "docstring": "try to parse additional attributes, but ends up to hexdump if the scheme is unknown"
  },
  {
    "code": "def write_packages(self, reqs_file):\n        write_file_lines(reqs_file, ('{}\\n'.format(package) for package in self.packages))",
    "docstring": "Dump the packages in the catalog in a requirements file"
  },
  {
    "code": "def param_show(param=None):\n    ret = _run_varnishadm('param.show', [param])\n    if ret['retcode']:\n        return False\n    else:\n        result = {}\n        for line in ret['stdout'].split('\\n'):\n            m = re.search(r'^(\\w+)\\s+(.*)$', line)\n            result[m.group(1)] = m.group(2)\n            if param:\n                break\n        return result",
    "docstring": "Show params of varnish cache\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' varnish.param_show param"
  },
  {
    "code": "def check_hash(path, file_hash):\n    path = os.path.expanduser(path)\n    if not isinstance(file_hash, six.string_types):\n        raise SaltInvocationError('hash must be a string')\n    for sep in (':', '='):\n        if sep in file_hash:\n            hash_type, hash_value = file_hash.split(sep, 1)\n            break\n    else:\n        hash_value = file_hash\n        hash_len = len(file_hash)\n        hash_type = HASHES_REVMAP.get(hash_len)\n        if hash_type is None:\n            raise SaltInvocationError(\n                'Hash {0} (length: {1}) could not be matched to a supported '\n                'hash type. The supported hash types and lengths are: '\n                '{2}'.format(\n                    file_hash,\n                    hash_len,\n                    ', '.join(\n                        ['{0} ({1})'.format(HASHES_REVMAP[x], x)\n                         for x in sorted(HASHES_REVMAP)]\n                    ),\n                )\n            )\n    return get_hash(path, hash_type) == hash_value",
    "docstring": "Check if a file matches the given hash string\n\n    Returns ``True`` if the hash matches, otherwise ``False``.\n\n    path\n        Path to a file local to the minion.\n\n    hash\n        The hash to check against the file specified in the ``path`` argument.\n\n        .. versionchanged:: 2016.11.4\n\n        For this and newer versions the hash can be specified without an\n        accompanying hash type (e.g. ``e138491e9d5b97023cea823fe17bac22``),\n        but for earlier releases it is necessary to also specify the hash type\n        in the format ``<hash_type>=<hash_value>`` (e.g.\n        ``md5=e138491e9d5b97023cea823fe17bac22``).\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' file.check_hash /etc/fstab e138491e9d5b97023cea823fe17bac22\n        salt '*' file.check_hash /etc/fstab md5=e138491e9d5b97023cea823fe17bac22"
  },
  {
    "code": "def appendInnerHTML(self, html):\n        from .Parser import AdvancedHTMLParser\n        encoding = None\n        if self.ownerDocument:\n            encoding = self.ownerDocument.encoding\n        blocks = AdvancedHTMLParser.createBlocksFromHTML(html, encoding)\n        self.appendBlocks(blocks)",
    "docstring": "appendInnerHTML - Appends nodes from arbitrary HTML as if doing element.innerHTML += 'someHTML' in javascript.\n\n            @param html <str> - Some HTML\n\n            NOTE: If associated with a document ( AdvancedHTMLParser ), the html will use the encoding associated with\n                    that document.\n\n            @return - None. A browser would return innerHTML, but that's somewhat expensive on a high-level node.\n              So just call .innerHTML explicitly if you need that"
  },
  {
    "code": "def get_features(\n    dataset,\n    query=None,\n    crs=\"epsg:4326\",\n    bounds=None,\n    sortby=None,\n    pagesize=10000,\n    max_workers=5,\n):\n    param_dicts = define_request(dataset, query, crs, bounds, sortby, pagesize)\n    with ThreadPoolExecutor(max_workers=max_workers) as executor:\n        for result in executor.map(make_request, param_dicts):\n            for feature in result:\n                yield feature",
    "docstring": "Yield features from DataBC WFS"
  },
  {
    "code": "def append_form(\n            self,\n            obj: Union[Sequence[Tuple[str, str]],\n                       Mapping[str, str]],\n            headers: Optional['MultiMapping[str]']=None\n    ) -> Payload:\n        assert isinstance(obj, (Sequence, Mapping))\n        if headers is None:\n            headers = CIMultiDict()\n        if isinstance(obj, Mapping):\n            obj = list(obj.items())\n        data = urlencode(obj, doseq=True)\n        return self.append_payload(\n            StringPayload(data, headers=headers,\n                          content_type='application/x-www-form-urlencoded'))",
    "docstring": "Helper to append form urlencoded part."
  },
  {
    "code": "def lookup_bulk(self, ResponseGroup=\"Large\", **kwargs):\n        response = self.api.ItemLookup(ResponseGroup=ResponseGroup, **kwargs)\n        root = objectify.fromstring(response)\n        if not hasattr(root.Items, 'Item'):\n            return []\n        return list(\n            AmazonProduct(\n                item,\n                self.aws_associate_tag,\n                self,\n                region=self.region) for item in root.Items.Item\n        )",
    "docstring": "Lookup Amazon Products in bulk.\n\n        Returns all products matching requested ASINs, ignoring invalid\n        entries.\n\n        :return:\n            A list of  :class:`~.AmazonProduct` instances."
  },
  {
    "code": "def get_marks(self):\n        data = self.message(MessageType.GET_MARKS, '')\n        return json.loads(data)",
    "docstring": "Get a list of the names of all currently set marks.\n\n        :rtype: list"
  },
  {
    "code": "def is_equal(self, other):\n        other = self.coerce(other)\n        return len(self.get_values().symmetric_difference(other.get_values())) == 0",
    "docstring": "True iff all members are the same"
  },
  {
    "code": "def create_track_token(request):\n    from tracked_model.models import RequestInfo\n    request_pk = RequestInfo.create_or_get_from_request(request).pk\n    user_pk = None\n    if request.user.is_authenticated():\n        user_pk = request.user.pk\n    return TrackToken(request_pk=request_pk, user_pk=user_pk)",
    "docstring": "Returns ``TrackToken``.\n    ``TrackToken' contains request and user making changes.\n\n    It can be passed to ``TrackedModel.save`` instead of ``request``.\n    It is intended to be used when passing ``request`` is not possible\n    e.g. when ``TrackedModel.save`` will be called from celery task."
  },
  {
    "code": "def read_yaml(file_path, Loader=yaml.Loader, object_pairs_hook=OrderedDict):\n    class OrderedLoader(Loader):\n        pass\n    def construct_mapping(loader, node):\n        loader.flatten_mapping(node)\n        return object_pairs_hook(loader.construct_pairs(node))\n    OrderedLoader.add_constructor(\n        yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,\n        construct_mapping)\n    with open(file_path, 'r') as f:\n        return yaml.load(f, OrderedLoader)",
    "docstring": "Read YAML file and return as python dictionary"
  },
  {
    "code": "def _get_all_dependencies_of(name, deps=set(), force=False):\n    first_deps = _get_api_dependencies_of(name, force=force)\n    for dep in first_deps:\n        dep = _strip_version_from_dependency(dep)\n        if dep in deps:\n            continue\n        if dap in get_installed_daps():\n            continue\n        deps |= _get_all_dependencies_of(dep, deps)\n    return deps | set([name])",
    "docstring": "Returns list of dependencies of the given dap from Dapi recursively"
  },
  {
    "code": "def validate_url(cls, url: str) -> Optional[Match[str]]:\n        match = re.match(cls._VALID_URL, url)\n        return match",
    "docstring": "Check if the Extractor can handle the given url."
  },
  {
    "code": "def pprint_label(self):\n        \"The pretty-printed label string for the Dimension\"\n        unit = ('' if self.unit is None\n                else type(self.unit)(self.unit_format).format(unit=self.unit))\n        return bytes_to_unicode(self.label) + bytes_to_unicode(unit)",
    "docstring": "The pretty-printed label string for the Dimension"
  },
  {
    "code": "def get_all_edge_nodes(self):\n        edge_nodes = set(e for es in self.edges for e in es)\n        for edges in self.edges_rel.values():\n            rel_nodes = set(e for es in edges for e in es)\n            edge_nodes.update(rel_nodes)\n        return edge_nodes",
    "docstring": "Return a list of all GO IDs that are connected to edges."
  },
  {
    "code": "def img_url(obj, profile_app_name, profile_model_name):\n    try:\n        content_type = ContentType.objects.get(\n            app_label=profile_app_name,\n            model=profile_model_name.lower()\n        )\n    except ContentType.DoesNotExist:\n        return \"\"\n    except AttributeError:\n        return \"\"\n    Profile = content_type.model_class()\n    fields = Profile._meta.get_fields()\n    profile = content_type.model_class().objects.get(user=obj.user)\n    for field in fields:\n        if hasattr(field, \"upload_to\"):\n            return field.value_from_object(profile).url",
    "docstring": "returns url of profile image of a user"
  },
  {
    "code": "def _get_thintar_prefix(tarname):\n    tfd, tmp_tarname = tempfile.mkstemp(dir=os.path.dirname(tarname), prefix=\".thin-\",\n                                        suffix=\".\" + os.path.basename(tarname).split(\".\", 1)[-1])\n    os.close(tfd)\n    return tmp_tarname",
    "docstring": "Make sure thintar temporary name is concurrent and secure.\n\n    :param tarname: name of the chosen tarball\n    :return: prefixed tarname"
  },
  {
    "code": "def normalize_medscan_name(name):\n    suffix = ' complex'\n    for i in range(2):\n        if name.endswith(suffix):\n            name = name[:-len(suffix)]\n    return name",
    "docstring": "Removes the \"complex\" and \"complex complex\" suffixes from a medscan\n    agent name so that it better corresponds with the grounding map.\n\n    Parameters\n    ----------\n    name: str\n        The Medscan agent name\n\n    Returns\n    -------\n    norm_name: str\n        The Medscan agent name with the \"complex\" and \"complex complex\"\n        suffixes removed."
  },
  {
    "code": "def from_element(self, element, defaults={}):\n        if isinstance(defaults, SvdElement):\n            defaults = vars(defaults)\n        for key in self.props:\n            try:\n                value = element.find(key).text\n            except AttributeError:\n                default = defaults[key] if key in defaults else None\n                value = element.get(key, default)\n            if value is not None:\n                if key in self.props_to_integer:\n                    try:\n                        value = int(value)\n                    except ValueError:\n                        value = int(value, 16)\n                elif key in self.props_to_boolean:\n                    value = value.lower() in (\"yes\", \"true\", \"t\", \"1\")\n            setattr(self, key, value)",
    "docstring": "Populate object variables from SVD element"
  },
  {
    "code": "def phi_s(spin1x, spin1y, spin2x, spin2y):\n    phi1 = phi_from_spinx_spiny(spin1x, spin1y)\n    phi2 = phi_from_spinx_spiny(spin2x, spin2y)\n    return (phi1 + phi2) % (2 * numpy.pi)",
    "docstring": "Returns the sum of the in-plane perpendicular spins."
  },
  {
    "code": "def is_same_quaternion(q0, q1):\n    q0 = np.array(q0)\n    q1 = np.array(q1)\n    return np.allclose(q0, q1) or np.allclose(q0, -q1)",
    "docstring": "Return True if two quaternions are equal."
  },
  {
    "code": "def import_dashboards(self):\n        f = request.files.get('file')\n        if request.method == 'POST' and f:\n            dashboard_import_export.import_dashboards(db.session, f.stream)\n            return redirect('/dashboard/list/')\n        return self.render_template('superset/import_dashboards.html')",
    "docstring": "Overrides the dashboards using json instances from the file."
  },
  {
    "code": "def compute(self):\n        if \"Signature\" in self.params:\n            raise RuntimeError(\"Existing signature in parameters\")\n        if self.signature_version is not None:\n            version = self.signature_version\n        else:\n            version = self.params[\"SignatureVersion\"]\n        if str(version) == \"1\":\n            bytes = self.old_signing_text()\n            hash_type = \"sha1\"\n        elif str(version) == \"2\":\n            bytes = self.signing_text()\n            if self.signature_method is not None:\n                signature_method = self.signature_method\n            else:\n                signature_method = self.params[\"SignatureMethod\"]\n            hash_type = signature_method[len(\"Hmac\"):].lower()\n        else:\n            raise RuntimeError(\"Unsupported SignatureVersion: '%s'\" % version)\n        return self.creds.sign(bytes, hash_type)",
    "docstring": "Compute and return the signature according to the given data."
  },
  {
    "code": "def gen_query(self):\n        return (\n            SQL.forwards_relation(self.src, self.rel) if self.dst is None else\n            SQL.inverse_relation(self.dst, self.rel)\n            )",
    "docstring": "Generate an SQL query for the edge object."
  },
  {
    "code": "def _wait_until_connectable(self, timeout=30):\n        count = 0\n        while not utils.is_connectable(self.profile.port):\n            if self.process.poll() is not None:\n                raise WebDriverException(\n                    \"The browser appears to have exited \"\n                    \"before we could connect. If you specified a log_file in \"\n                    \"the FirefoxBinary constructor, check it for details.\")\n            if count >= timeout:\n                self.kill()\n                raise WebDriverException(\n                    \"Can't load the profile. Possible firefox version mismatch. \"\n                    \"You must use GeckoDriver instead for Firefox 48+. Profile \"\n                    \"Dir: %s If you specified a log_file in the \"\n                    \"FirefoxBinary constructor, check it for details.\"\n                    % (self.profile.path))\n            count += 1\n            time.sleep(1)\n        return True",
    "docstring": "Blocks until the extension is connectable in the firefox."
  },
  {
    "code": "def group(self, base_dn, samaccountname, attributes=(), explicit_membership_only=False):\n        groups = self.groups(base_dn, samaccountnames=[samaccountname], attributes=attributes,\n                             explicit_membership_only=explicit_membership_only)\n        try:\n            return groups[0]\n        except IndexError:\n            logging.info(\"%s - unable to retrieve object from AD by sAMAccountName\", samaccountname)",
    "docstring": "Produces a single, populated ADGroup object through the object factory.\n        Does not populate attributes for the caller instance.\n\n        sAMAccountName may not be present in group objects in modern AD schemas.\n        Searching by common name and object class (group) may be an alternative\n        approach if required in the future.\n\n        :param str base_dn: The base DN to search within\n        :param str samaccountname: The group's sAMAccountName\n        :param list attributes: Object attributes to populate, defaults to all\n\n        :return: A populated ADGroup object\n        :rtype: ADGroup"
  },
  {
    "code": "def list(self, **params):\n        _, _, loss_reasons = self.http_client.get(\"/loss_reasons\", params=params)\n        return loss_reasons",
    "docstring": "Retrieve all reasons\n\n        Returns all deal loss reasons available to the user according to the parameters provided\n\n        :calls: ``get /loss_reasons``\n        :param dict params: (optional) Search options.\n        :return: List of dictionaries that support attriubte-style access, which represent collection of LossReasons.\n        :rtype: list"
  },
  {
    "code": "def optimise_levenberg_marquardt(x, a, c, damping=0.001, tolerance=0.001):\n    x_new = x\n    x_old = x-1\n    f_old = f(x_new, a, c)\n    while np.abs(x_new - x_old).sum() > tolerance:\n        x_old = x_new\n        x_tmp = levenberg_marquardt_update(x_old, a, c, damping)\n        f_new = f(x_tmp, a, c)\n        if f_new < f_old:\n            damping = np.max(damping/10., 1e-20)\n            x_new = x_tmp\n            f_old = f_new\n        else:\n            damping *= 10.\n    return x_new",
    "docstring": "Optimise value of x using levenberg-marquardt"
  },
  {
    "code": "def _read_etc(etc_file):\n    etc_type = dtype([('offset', '<i'),\n                      ('samplestamp', '<i'),\n                      ('sample_num', '<i'),\n                      ('sample_span', '<h'),\n                      ('unknown', '<h')])\n    with etc_file.open('rb') as f:\n        f.seek(352)\n        etc = fromfile(f, dtype=etc_type)\n    return etc",
    "docstring": "Return information about table of content for each erd."
  },
  {
    "code": "async def list_keys(request: web.Request) -> web.Response:\n    return web.json_response(\n        {'public_keys': [{'key_md5': details[0], 'key': details[1]}\n                         for details in get_keys()]},\n        status=200)",
    "docstring": "List keys in the authorized_keys file.\n\n    GET /server/ssh_keys\n    -> 200 OK {\"public_keys\": [{\"key_md5\": md5 hex digest, \"key\": key string}]}\n\n    (or 403 if not from the link-local connection)"
  },
  {
    "code": "def get_polypeptide_within(self, chain_id, resnum, angstroms, only_protein=True,\n                               use_ca=False, custom_coord=None, return_resnums=False):\n        if self.structure:\n            parsed = self.structure\n        else:\n            parsed = self.parse_structure()\n        residue_list = ssbio.protein.structure.properties.residues.within(resnum=resnum, chain_id=chain_id,\n                                                                          model=parsed.first_model,\n                                                                          angstroms=angstroms, use_ca=use_ca,\n                                                                          custom_coord=custom_coord)\n        if only_protein:\n            filtered_residue_list = [x for x in residue_list if x.id[0] == ' ']\n        else:\n            filtered_residue_list = residue_list\n        residue_list_combined = Polypeptide(filtered_residue_list)\n        if return_resnums:\n            resnums = [int(x.id[1]) for x in filtered_residue_list]\n            return residue_list_combined, resnums\n        return residue_list_combined",
    "docstring": "Get a Polypeptide object of the amino acids within X angstroms of the specified chain + residue number.\n\n        Args:\n            resnum (int): Residue number of the structure\n            chain_id (str): Chain ID of the residue number\n            angstroms (float): Radius of the search sphere\n            only_protein (bool): If only protein atoms (no HETATMS) should be included in the returned sequence\n            use_ca (bool): If the alpha-carbon atom should be used for searching, default is False (last atom of residue used)\n            custom_coord (list): custom XYZ coord\n            return_resnums (bool): if list of resnums should be returned\n\n        Returns:\n            Bio.PDB.Polypeptide.Polypeptide: Biopython Polypeptide object"
  },
  {
    "code": "def find_device(self):\n        for bdaddr, name in self.scan():\n            if name == \"Wireless Controller\":\n                self.logger.info(\"Found device {0}\", bdaddr)\n                return BluetoothDS4Device.connect(bdaddr)",
    "docstring": "Scan for bluetooth devices and return a DS4 device if found."
  },
  {
    "code": "def max_fmeasure(fg_vals, bg_vals):\n    x, y = roc_values(fg_vals, bg_vals)\n    x, y = x[1:], y[1:]\n    p = y / (y + x)\n    filt = np.logical_and((p * y) > 0, (p + y) > 0)\n    p = p[filt]\n    y = y[filt]\n    f = (2 * p * y) / (p + y)\n    if len(f) > 0:\n        return np.nanmax(f)\n    else:\n        return None",
    "docstring": "Computes the maximum F-measure.\n\n    Parameters\n    ----------\n    fg_vals : array_like\n        The list of values for the positive set.\n\n    bg_vals : array_like\n        The list of values for the negative set.\n    \n    Returns\n    -------\n    f : float\n        Maximum f-measure."
  },
  {
    "code": "def keys_breadth_first(self, include_dicts=False):\n        namespaces = []\n        for key in self._key_order:\n            if isinstance(getattr(self, key), DotDict):\n                namespaces.append(key)\n                if include_dicts:\n                    yield key\n            else:\n                yield key\n        for a_namespace in namespaces:\n            for key in self[a_namespace].keys_breadth_first(include_dicts):\n                yield '%s.%s' % (a_namespace, key)",
    "docstring": "a generator that returns all the keys in a set of nested\n        DotDict instances.  The keys take the form X.Y.Z"
  },
  {
    "code": "def preview_view(self, context):\n        view_to_render = 'author_view' if hasattr(self, 'author_view') else 'student_view'\n        renderer = getattr(self, view_to_render)\n        return renderer(context)",
    "docstring": "Preview view - used by StudioContainerWithNestedXBlocksMixin to render nested xblocks in preview context.\n        Default implementation uses author_view if available, otherwise falls back to student_view\n        Child classes can override this method to control their presentation in preview context"
  },
  {
    "code": "def move(self, delta):\n        pos = self.pos\n        self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1])\n        for age in self.nodes:\n            for node in age:\n                node.move(delta)",
    "docstring": "Move the tree.\n\n        Args:\n            delta (tupel): The adjustment of the position."
  },
  {
    "code": "def get_mchirp(h5group):\n    mass1 = h5group['mass1'][:]\n    mass2 = h5group['mass2'][:]\n    return (mass1 * mass2) ** (3/5.) / (mass1 + mass2) ** (1/5.)",
    "docstring": "Calculate the chipr mass column for this PyCBC HDF5 table group"
  },
  {
    "code": "def _report_problem(self, problem, level=logging.ERROR):\n        problem = self.basename + ': ' + problem\n        if self._logger.isEnabledFor(level):\n            self._problematic = True\n        if self._check_raises:\n            raise DapInvalid(problem)\n        self._logger.log(level, problem)",
    "docstring": "Report a given problem"
  },
  {
    "code": "def exec_commands(commands: str, **parameters: Any) -> None:\n    cmdlist = commands.split(';')\n    print(f'Start to execute the commands {cmdlist} for testing purposes.')\n    for par, value in parameters.items():\n        exec(f'{par} = {value}')\n    for command in cmdlist:\n        command = command.replace('__', 'temptemptemp')\n        command = command.replace('_', ' ')\n        command = command.replace('temptemptemp', '_')\n        exec(command)",
    "docstring": "Execute the given Python commands.\n\n    Function |exec_commands| is thought for testing purposes only (see\n    the main documentation on module |hyd|).  Seperate individual commands\n    by semicolons and replaced whitespaces with underscores:\n\n    >>> from hydpy.exe.commandtools import exec_commands\n    >>> import sys\n    >>> exec_commands(\"x_=_1+1;print(x)\")\n    Start to execute the commands ['x_=_1+1', 'print(x)'] for testing purposes.\n    2\n\n    |exec_commands| interprets double underscores as a single underscores:\n\n    >>> exec_commands(\"x_=_1;print(x.____class____)\")\n    Start to execute the commands ['x_=_1', 'print(x.____class____)'] \\\nfor testing purposes.\n    <class 'int'>\n\n    |exec_commands| evaluates additional keyword arguments before it\n    executes the given commands:\n\n    >>> exec_commands(\"e=x==y;print(e)\", x=1, y=2)\n    Start to execute the commands ['e=x==y', 'print(e)'] for testing purposes.\n    False"
  },
  {
    "code": "async def listDependentTasks(self, *args, **kwargs):\n        return await self._makeApiCall(self.funcinfo[\"listDependentTasks\"], *args, **kwargs)",
    "docstring": "List Dependent Tasks\n\n        List tasks that depend on the given `taskId`.\n\n        As many tasks from different task-groups may dependent on a single tasks,\n        this end-point may return a `continuationToken`. To continue listing\n        tasks you must call `listDependentTasks` again with the\n        `continuationToken` as the query-string option `continuationToken`.\n\n        By default this end-point will try to return up to 1000 tasks in one\n        request. But it **may return less**, even if more tasks are available.\n        It may also return a `continuationToken` even though there are no more\n        results. However, you can only be sure to have seen all results if you\n        keep calling `listDependentTasks` with the last `continuationToken` until\n        you get a result without a `continuationToken`.\n\n        If you are not interested in listing all the tasks at once, you may\n        use the query-string option `limit` to return fewer.\n\n        This method gives output: ``v1/list-dependent-tasks-response.json#``\n\n        This method is ``stable``"
  },
  {
    "code": "def _init_browser(self):\n        chrome_options = webdriver.ChromeOptions()\n        chrome_options.add_argument('--disable-extensions')\n        chrome_options.add_argument('--disable-infobars')\n        chrome_options.add_argument('--ignore-certificate-errors')\n        chrome_options.add_experimental_option('prefs', {\n            'profile.managed_default_content_settings.notifications': 1\n        })\n        browser = webdriver.Chrome(chrome_options=chrome_options)\n        browser.set_page_load_timeout(10)\n        browser.implicitly_wait(1)\n        browser.maximize_window()\n        browser.get(settings.HARNESS_URL)\n        self._browser = browser\n        if not wait_until(lambda: 'Thread' in browser.title, 30):\n            self.assertIn('Thread', browser.title)",
    "docstring": "Open harness web page.\n\n        Open a quiet chrome which:\n        1. disables extensions,\n        2. ignore certificate errors and\n        3. always allow notifications."
  },
  {
    "code": "def get_instance(self, payload):\n        return YesterdayInstance(self._version, payload, account_sid=self._solution['account_sid'], )",
    "docstring": "Build an instance of YesterdayInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayInstance\n        :rtype: twilio.rest.api.v2010.account.usage.record.yesterday.YesterdayInstance"
  },
  {
    "code": "def save(self, set_cookie, **params):\n        if set(self.store.items()) ^ set(self.items()):\n            value = dict(self.items())\n            value = json.dumps(value)\n            value = self.encrypt(value)\n            if not isinstance(value, str):\n                value = value.encode(self.encoding)\n            set_cookie(self.key, value, **self.params)\n            return True\n        return False",
    "docstring": "Update cookies if the session has been changed."
  },
  {
    "code": "def schema(self):\n        if not self.__schema:\n            context = getattr(self.parent, 'context', {})\n            if isinstance(self.nested, SchemaABC):\n                self.__schema = self.nested\n                self.__schema.context.update(context)\n            else:\n                if isinstance(self.nested, type) and issubclass(self.nested, SchemaABC):\n                    schema_class = self.nested\n                elif not isinstance(self.nested, basestring):\n                    raise ValueError(\n                        'Nested fields must be passed a '\n                        'Schema, not {}.'.format(self.nested.__class__),\n                    )\n                elif self.nested == 'self':\n                    schema_class = self.parent.__class__\n                else:\n                    schema_class = class_registry.get_class(self.nested)\n                self.__schema = schema_class(\n                    many=self.many,\n                    only=self.only,\n                    exclude=self.exclude,\n                    context=context,\n                    load_only=self._nested_normalized_option('load_only'),\n                    dump_only=self._nested_normalized_option('dump_only'),\n                )\n        return self.__schema",
    "docstring": "The nested Schema object.\n\n        .. versionchanged:: 1.0.0\n            Renamed from `serializer` to `schema`"
  },
  {
    "code": "def dimNamesFromDataset(h5Dataset):\n    dimNames = []\n    for dimNr, dimScales in enumerate(h5Dataset.dims):\n        if len(dimScales) == 0:\n            dimNames.append('Dim{}'.format(dimNr))\n        elif len(dimScales) == 1:\n            dimScaleLabel, dimScaleDataset = dimScales.items()[0]\n            path = dimScaleDataset.name\n            if path:\n                dimNames.append(os.path.basename(path))\n            elif dimScaleLabel:\n                dimNames.append(dimScaleLabel)\n            else:\n                dimNames.append('Dim{}'.format(dimNr))\n        else:\n            logger.warn(\"More than one dimension scale found: {!r}\".format(dimScales))\n            dimNames.append('Dim{}'.format(dimNr))\n    return dimNames",
    "docstring": "Constructs the dimension names given a h5py dataset.\n\n        First looks in the dataset's dimension scales to see if it refers to another\n        dataset. In that case the referred dataset's name is used. If not, the label of the\n        dimension scale is used. Finally, if this is empty, the dimension is numbered."
  },
  {
    "code": "def poll_for_exceptionless_callable(callable, attempts, interval):\n    @wraps(callable)\n    def poll(*args, **kwargs):\n        for attempt in range(attempts):\n            try:\n                return callable(*args, **kwargs)\n            except Exception as ex:\n                if attempt == attempts-1:\n                    raise MaximumAttemptsReached(ex)\n                time.sleep(interval)\n                continue\n    return poll",
    "docstring": "Poll with a given callable for a specified number of times.\n\n    :param callable: callable to invoke in loop -- if no exception is raised\n                    the call is considered succeeded\n    :param attempts: number of iterations to attempt\n    :param interval: seconds to wait before next attempt"
  },
  {
    "code": "def set_color_scheme(self, color_scheme, reset=True):\r\n        try:\r\n            self.shellwidget.set_color_scheme(color_scheme, reset)\r\n        except AttributeError:\r\n            pass",
    "docstring": "Set IPython color scheme."
  },
  {
    "code": "def zoom_blur(x, severity=1):\n  c = [\n      np.arange(1, 1.11, 0.01),\n      np.arange(1, 1.16, 0.01),\n      np.arange(1, 1.21, 0.02),\n      np.arange(1, 1.26, 0.02),\n      np.arange(1, 1.31, 0.03)\n  ][severity - 1]\n  x = (np.array(x) / 255.).astype(np.float32)\n  out = np.zeros_like(x)\n  for zoom_factor in c:\n    out += clipped_zoom(x, zoom_factor)\n  x = (x + out) / (len(c) + 1)\n  x_clip = np.clip(x, 0, 1) * 255\n  return around_and_astype(x_clip)",
    "docstring": "Zoom blurring to images.\n\n  Applying zoom blurring to images by zooming the central part of the images.\n\n  Args:\n    x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].\n    severity: integer, severity of corruption.\n\n  Returns:\n    numpy array, image with uint8 pixels in [0,255]. Applied zoom blur."
  },
  {
    "code": "def integrate_storage(self, timeseries, position, **kwargs):\n        StorageControl(edisgo=self, timeseries=timeseries,\n                       position=position, **kwargs)",
    "docstring": "Integrates storage into grid.\n\n        See :class:`~.grid.network.StorageControl` for more information."
  },
  {
    "code": "def add_synchronous_cb(self, cb):\n        if self.connection.synchronous or self._synchronous:\n            wrapper = SyncWrapper(cb)\n            self._pending_events.append(wrapper)\n            while wrapper._read:\n                if self.closed:\n                    if self.close_info and \\\n                            len(self.close_info['reply_text']) > 0:\n                        raise ChannelClosed(\n                            \"channel %d is closed: %s : %s\",\n                            self.channel_id,\n                            self.close_info['reply_code'],\n                            self.close_info['reply_text'])\n                    raise ChannelClosed()\n                self.connection.read_frames()\n            return wrapper._result\n        else:\n            self._pending_events.append(cb)",
    "docstring": "Add an expectation of a callback to release a synchronous transaction."
  },
  {
    "code": "def _get_top_of_rupture_depth_term(self, C, imt, rup):\n        if rup.ztor >= 20.0:\n            return C['a15']\n        else:\n            return C['a15'] * rup.ztor / 20.0",
    "docstring": "Compute and return top of rupture depth term. See paragraph\n        'Depth-to-Top of Rupture Model', page 1042."
  },
  {
    "code": "async def server_call_async(method, server, loop: asyncio.AbstractEventLoop=asyncio.get_event_loop(), timeout=DEFAULT_TIMEOUT,\n                      verify_ssl=True, **parameters):\n    if method is None:\n        raise Exception(\"A method name must be specified\")\n    if server is None:\n        raise Exception(\"A server (eg. my3.geotab.com) must be specified\")\n    parameters = api.process_parameters(parameters)\n    return await _query(server, method, parameters, timeout=timeout, verify_ssl=verify_ssl, loop=loop)",
    "docstring": "Makes an asynchronous call to an un-authenticated method on a server.\n\n    :param method: The method name.\n    :param server: The MyGeotab server.\n    :param loop: The event loop.\n    :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes).\n    :param verify_ssl: If True, verify the SSL certificate. It's recommended not to modify this.\n    :param parameters: Additional parameters to send (for example, search=dict(id='b123') ).\n    :return: The JSON result (decoded into a dict) from the server.\n    :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server.\n    :raise TimeoutException: Raises when the request does not respond after some time."
  },
  {
    "code": "def fulltext(search, lang=Lang.English, ignore_case=True):\n        return {\n            \"$text\": {\n                \"$search\": search,\n                \"$language\": lang,\n                \"$caseSensitive\": not ignore_case,\n                \"$diacriticSensitive\": False,\n            }\n        }",
    "docstring": "Full text search.\n\n        Example::\n\n            filters = Text.fulltext(\"python pymongo_mate\")\n\n        .. note::\n\n            This field doesn't need to specify field."
  },
  {
    "code": "def encode_hooklist(self, hooklist, msg):\n        for hook in hooklist:\n            pbhook = msg.add()\n            self.encode_hook(hook, pbhook)",
    "docstring": "Encodes a list of commit hooks into their protobuf equivalent.\n        Used in bucket properties.\n\n        :param hooklist: a list of commit hooks\n        :type hooklist: list\n        :param msg: a protobuf field that is a list of commit hooks"
  },
  {
    "code": "def basic_auth_tween_factory(handler, registry):\n    def basic_auth_tween(request):\n        remote_user = get_remote_user(request)\n        if remote_user is not None:\n            request.environ['REMOTE_USER'] = remote_user[0]\n        return handler(request)\n    return basic_auth_tween",
    "docstring": "Do basic authentication, parse HTTP_AUTHORIZATION and set remote_user\n    variable to request"
  },
  {
    "code": "def path(self):\n        raw_path = wsgi_decoding_dance(\n            self.environ.get(\"PATH_INFO\") or \"\", self.charset, self.encoding_errors\n        )\n        return \"/\" + raw_path.lstrip(\"/\")",
    "docstring": "Requested path as unicode.  This works a bit like the regular path\n        info in the WSGI environment but will always include a leading slash,\n        even if the URL root is accessed."
  },
  {
    "code": "def get_role(member, cython=False):\n        if inspect.isroutine(member) or isinstance(member, numpy.ufunc):\n            return 'func'\n        elif inspect.isclass(member):\n            return 'class'\n        elif cython:\n            return 'func'\n        return 'const'",
    "docstring": "Return the reStructuredText role `func`, `class`, or `const`\n        best describing the given member.\n\n        Some examples based on the site-package |numpy|.  |numpy.clip|\n        is a function:\n\n        >>> from hydpy.core.autodoctools import Substituter\n        >>> import numpy\n        >>> Substituter.get_role(numpy.clip)\n        'func'\n\n        |numpy.ndarray| is a class:\n\n        >>> Substituter.get_role(numpy.ndarray)\n        'class'\n\n        |numpy.ndarray.clip| is a method, for which also the `function`\n        role is returned:\n\n        >>> Substituter.get_role(numpy.ndarray.clip)\n        'func'\n\n        For everything else the `constant` role is returned:\n\n        >>> Substituter.get_role(numpy.nan)\n        'const'\n\n        When analysing cython extension modules, set the option `cython`\n        flag to |True|.  |Double| is correctly identified as a class:\n\n        >>> from hydpy.cythons import pointerutils\n        >>> Substituter.get_role(pointerutils.Double, cython=True)\n        'class'\n\n        Only with the `cython` flag beeing |True|, for everything else\n        the `function` text role is returned (doesn't make sense here,\n        but the |numpy| module is not something defined in module\n        |pointerutils| anyway):\n\n        >>> Substituter.get_role(pointerutils.numpy, cython=True)\n        'func'"
  },
  {
    "code": "def to_dms(angle, style='dms'):\n    sign = 1 if angle >= 0 else -1\n    angle = abs(angle) * 3600\n    minutes, seconds = divmod(angle, 60)\n    degrees, minutes = divmod(minutes, 60)\n    if style == 'dms':\n        return tuple(sign * abs(i) for i in (int(degrees), int(minutes),\n                                             seconds))\n    elif style == 'dm':\n        return tuple(sign * abs(i) for i in (int(degrees),\n                                             (minutes + seconds / 60)))\n    else:\n        raise ValueError('Unknown style type %r' % style)",
    "docstring": "Convert decimal angle to degrees, minutes and possibly seconds.\n\n    Args:\n        angle (float): Angle to convert\n        style (str): Return fractional or whole minutes values\n\n    Returns:\n        tuple of int: Angle converted to degrees, minutes and possibly seconds\n\n    Raises:\n        ValueError: Unknown value for ``style``"
  },
  {
    "code": "def historical(self, date, base='USD'):\n        try:\n            resp = self.client.get(self.ENDPOINT_HISTORICAL %\n                                   date.strftime(\"%Y-%m-%d\"),\n                                   params={'base': base})\n            resp.raise_for_status()\n        except requests.exceptions.RequestException as e:\n            raise OpenExchangeRatesClientException(e)\n        return resp.json(parse_int=decimal.Decimal,\n                         parse_float=decimal.Decimal)",
    "docstring": "Fetches historical exchange rate data from service\n\n        :Example Data:\n            {\n                disclaimer: \"<Disclaimer data>\",\n                license: \"<License data>\",\n                timestamp: 1358150409,\n                base: \"USD\",\n                rates: {\n                    AED: 3.666311,\n                    AFN: 51.2281,\n                    ALL: 104.748751,\n                    AMD: 406.919999,\n                    ANG: 1.7831,\n                    ...\n                }\n            }"
  },
  {
    "code": "def _assembled_out_file_name(self):\n        if self.Parameters['-s'].isOn():\n            assembled_reads = self._absolute(str(self.Parameters['-s'].Value))\n        else:\n            raise ValueError(\n                \"No assembled-reads (flag -s) output path specified\")\n        return assembled_reads",
    "docstring": "Checks file name is set for assembled output.\n           Returns absolute path."
  },
  {
    "code": "def can_manage(user, semester=None, pool=None, any_pool=False):\n    if semester and user in semester.workshift_managers.all():\n        return True\n    if Manager and Manager.objects.filter(\n            incumbent__user=user, workshift_manager=True,\n    ).count() > 0:\n        return True\n    if pool and pool.managers.filter(incumbent__user=user).count() > 0:\n        return True\n    if any_pool and WorkshiftPool.objects.filter(\n            managers__incumbent__user=user,\n    ):\n        return True\n    return user.is_superuser or user.is_staff",
    "docstring": "Whether a user is allowed to manage a workshift semester. This includes the\n    current workshift managers, that semester's workshift managers, and site\n    superusers."
  },
  {
    "code": "def get_http_header(self) -> Response:\n        with wpull.util.reset_file_offset(self.block_file):\n            data = self.block_file.read(4096)\n        match = re.match(br'(.*?\\r?\\n\\r?\\n)', data)\n        if not match:\n            return\n        status_line, dummy, field_str = match.group(1).partition(b'\\n')\n        try:\n            version, code, reason = Response.parse_status_line(status_line)\n        except ValueError:\n            return\n        response = Response(status_code=code, reason=reason, version=version)\n        try:\n            response.fields.parse(field_str, strict=False)\n        except ValueError:\n            return\n        return response",
    "docstring": "Return the HTTP header.\n\n        It only attempts to read the first 4 KiB of the payload.\n\n        Returns:\n            Response, None: Returns an instance of\n            :class:`.http.request.Response` or None."
  },
  {
    "code": "def setup(self, app):\n        for other in app.plugins:\n            if not isinstance(other, SQLAlchemyPlugin):\n                continue\n            if other.keyword == self.keyword:\n                raise bottle.PluginError(\"Found another SQLAlchemy plugin with \"\\\n                                  \"conflicting settings (non-unique keyword).\")\n            elif other.name == self.name:\n                self.name += '_%s' % self.keyword\n        if self.create and not self.metadata:\n            raise bottle.PluginError('Define metadata value to create database.')",
    "docstring": "Make sure that other installed plugins don't affect the same\n            keyword argument and check if metadata is available."
  },
  {
    "code": "def _rename_duplicate_tabs(self, current, name, path):\n        for i in range(self.count()):\n            if self.widget(i)._tab_name == name and self.widget(i) != current:\n                file_path = self.widget(i).file.path\n                if file_path:\n                    parent_dir = os.path.split(os.path.abspath(\n                        os.path.join(file_path, os.pardir)))[1]\n                    new_name = os.path.join(parent_dir, name)\n                    self.setTabText(i, new_name)\n                    self.widget(i)._tab_name = new_name\n                break\n        if path:\n            parent_dir = os.path.split(os.path.abspath(\n                os.path.join(path, os.pardir)))[1]\n            return os.path.join(parent_dir, name)\n        else:\n            return name",
    "docstring": "Rename tabs whose title is the same as the name"
  },
  {
    "code": "def _parse_q2r(self, f):\n        natom, dim, epsilon, borns = self._parse_parameters(f)\n        fc_dct = {'fc': self._parse_fc(f, natom, dim),\n                  'dimension': dim,\n                  'dielectric': epsilon,\n                  'born': borns}\n        return fc_dct",
    "docstring": "Parse q2r output file\n\n        The format of q2r output is described at the mailing list below:\n        http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html\n        http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html\n        http://www.democritos.it/pipermail/pw_forum/2009-August/013613.html\n        https://www.mail-archive.com/pw_forum@pwscf.org/msg24388.html"
  },
  {
    "code": "def image_scale(xscale=1.0, yscale=1.0, axes=\"gca\"):\n    if axes == \"gca\": axes = _pylab.gca()\n    e = axes.images[0].get_extent()\n    x1 = e[0]*xscale\n    x2 = e[1]*xscale\n    y1 = e[2]*yscale\n    y2 = e[3]*yscale\n    image_set_extent([x1,x2],[y1,y2], axes)",
    "docstring": "Scales the image extent."
  },
  {
    "code": "def compute_ng_stat(gene_graph, pos_ct, alpha=.5):\n    if not len(pos_ct):\n        return 1.0, 0\n    max_pos = max(gene_graph)\n    codon_vals = np.zeros(max_pos+1)\n    for pos in pos_ct:\n        mut_count = pos_ct[pos]\n        neighbors = list(gene_graph[pos])\n        num_neighbors = len(neighbors)\n        codon_vals[neighbors] += alpha*mut_count\n        codon_vals[pos] += (1-alpha)*mut_count\n    p = codon_vals / np.sum(codon_vals)\n    graph_score = mymath.shannon_entropy(p)\n    coverage = np.count_nonzero(p)\n    return graph_score, coverage",
    "docstring": "Compute the clustering score for the gene on its neighbor graph.\n\n    Parameters\n    ----------\n    gene_graph : dict\n        Graph of spatially near codons. keys = nodes, edges = key -> value.\n    pos_ct : dict\n        missense mutation count for each codon\n    alpha : float\n        smoothing factor\n\n    Returns\n    -------\n    graph_score : float\n        score measuring the clustering of missense mutations in the graph\n    coverage : int\n        number of nodes that received non-zero weight"
  },
  {
    "code": "def mass1_from_mass2_eta(mass2, eta, force_real=True):\n    return mass_from_knownmass_eta(mass2, eta, known_is_secondary=True,\n                                   force_real=force_real)",
    "docstring": "Returns the primary mass from the secondary mass and symmetric mass\n    ratio."
  },
  {
    "code": "def build_signature_template(key_id, algorithm, headers):\n    param_map = {'keyId': key_id,\n                 'algorithm': algorithm,\n                 'signature': '%s'}\n    if headers:\n        headers = [h.lower() for h in headers]\n        param_map['headers'] = ' '.join(headers)\n    kv = map('{0[0]}=\"{0[1]}\"'.format, param_map.items())\n    kv_string = ','.join(kv)\n    sig_string = 'Signature {0}'.format(kv_string)\n    return sig_string",
    "docstring": "Build the Signature template for use with the Authorization header.\n\n    key_id is the mandatory label indicating to the server which secret to use\n    algorithm is one of the supported algorithms\n    headers is a list of http headers to be included in the signing string.\n\n    The signature must be interpolated into the template to get the final\n    Authorization header value."
  },
  {
    "code": "def bestfit_func(self, bestfit_x):\n        bestfit_x = np.array(bestfit_x)\n        if not self.done_bestfit:\n            raise KeyError(\"Do do_bestfit first\")\n        bestfit_y = 0\n        for idx, val in enumerate(self.fit_args):\n            bestfit_y += val * (bestfit_x **\n                                (self.args.get(\"degree\", 1) - idx))\n        return bestfit_y",
    "docstring": "Returns bestfit_y value\n\n        args:\n            bestfit_x: scalar, array_like\n                x value\n        return: scalar, array_like\n            bestfit y value"
  },
  {
    "code": "def remove_numbers(text_string):\n    if text_string is None or text_string == \"\":\n        return \"\"\n    elif isinstance(text_string, str):\n        return \" \".join(re.sub(r'\\b[\\d.\\/,]+', \"\", text_string).split())\n    else:\n        raise InputError(\"string not passed as argument\")",
    "docstring": "Removes any digit value discovered within text_string and returns the new string as type str.\n\n    Keyword argument:\n\n    - text_string: string instance\n\n    Exceptions raised:\n\n    - InputError: occurs should a non-string argument be passed"
  },
  {
    "code": "def get_context_and_attention_probs(values: mx.sym.Symbol,\n                                    length: mx.sym.Symbol,\n                                    logits: mx.sym.Symbol,\n                                    dtype: str) -> Tuple[mx.sym.Symbol, mx.sym.Symbol]:\n    logits = mx.sym.SequenceMask(data=logits,\n                                 axis=1,\n                                 use_sequence_length=True,\n                                 sequence_length=length,\n                                 value=-C.LARGE_VALUES[dtype])\n    probs = mx.sym.softmax(logits, axis=1, name='attention_softmax')\n    context = mx.sym.batch_dot(lhs=values, rhs=probs, transpose_a=True)\n    context = mx.sym.reshape(data=context, shape=(0, 0))\n    probs = mx.sym.reshape(data=probs, shape=(0, 0))\n    return context, probs",
    "docstring": "Returns context vector and attention probabilities\n    via a weighted sum over values.\n\n    :param values: Shape: (batch_size, seq_len, encoder_num_hidden).\n    :param length: Shape: (batch_size,).\n    :param logits: Shape: (batch_size, seq_len, 1).\n    :param dtype: data type.\n    :return: context: (batch_size, encoder_num_hidden), attention_probs: (batch_size, seq_len)."
  },
  {
    "code": "def id_to_piece(input, model_file=None, model_proto=None, name=None):\n  return _gen_sentencepiece_processor_op.sentencepiece_id_to_piece(\n      input, model_file=model_file, model_proto=model_proto, name=name)",
    "docstring": "Converts vocabulary id into piece.\n\n  Args:\n    input: An arbitrary tensor of int32.\n    model_file: The sentencepiece model file path.\n    model_proto: The sentencepiece model serialized proto.\n                 Either `model_file` or `model_proto` must be set.\n    name: The name argument that is passed to the op function.\n  Returns:\n    A tensor of string with the same shape as input."
  },
  {
    "code": "def plot_scales(self, titles=None, fig_kwargs={}, **kwargs):\n        from ..plotting import plotting_library as pl\n        if titles is None:\n            titles = [r'${}$'.format(name) for name in self.names]\n        M = len(self.bgplvms)\n        fig = pl().figure(rows=1, cols=M, **fig_kwargs)\n        for c in range(M):\n            canvas = self.bgplvms[c].kern.plot_ARD(title=titles[c], figure=fig, col=c+1, **kwargs)\n        return canvas",
    "docstring": "Plot input sensitivity for all datasets, to see which input dimensions are\n        significant for which dataset.\n\n        :param titles: titles for axes of datasets\n\n        kwargs go into plot_ARD for each kernel."
  },
  {
    "code": "def coefficients(self):\n        vector = self.get_parameter_vector(include_frozen=True)\n        pars = self.get_all_coefficients(vector)\n        if len(pars) != 6:\n            raise ValueError(\"there must be 6 coefficient blocks\")\n        if any(len(p.shape) != 1 for p in pars):\n            raise ValueError(\"coefficient blocks must be 1D\")\n        if len(pars[0]) != len(pars[1]):\n            raise ValueError(\"coefficient blocks must have the same shape\")\n        if any(len(pars[2]) != len(p) for p in pars[3:]):\n            raise ValueError(\"coefficient blocks must have the same shape\")\n        return pars",
    "docstring": "All of the coefficient arrays\n\n        This property is the concatenation of the results from\n        :func:`terms.Term.get_real_coefficients` and\n        :func:`terms.Term.get_complex_coefficients` but it will always return\n        a tuple of length 6, even if ``alpha_complex_imag`` was omitted from\n        ``get_complex_coefficients``.\n\n        Returns:\n            (array[j_real], array[j_real], array[j_complex], array[j_complex],\n            array[j_complex], array[j_complex]): ``alpha_real``, ``beta_real``,\n            ``alpha_complex_real``, ``alpha_complex_imag``,\n            ``beta_complex_real``, and ``beta_complex_imag`` as described\n            above.\n\n        Raises:\n            ValueError: For invalid dimensions for the coefficients."
  },
  {
    "code": "def like(self):\n        self.requester.post(\n            '/{endpoint}/{id}/like',\n            endpoint=self.endpoint, id=self.id\n        )\n        return self",
    "docstring": "Like the project"
  },
  {
    "code": "def _last_stack_str():\n    stack = extract_stack()\n    for s in stack[::-1]:\n        if op.join('vispy', 'gloo', 'buffer.py') not in __file__:\n            break\n    return format_list([s])[0]",
    "docstring": "Print stack trace from call that didn't originate from here"
  },
  {
    "code": "def get_single(decl_matcher, decls, recursive=True):\n        answer = matcher.find(decl_matcher, decls, recursive)\n        if len(answer) == 1:\n            return answer[0]\n        elif not answer:\n            raise runtime_errors.declaration_not_found_t(decl_matcher)\n        else:\n            raise runtime_errors.multiple_declarations_found_t(decl_matcher)",
    "docstring": "Returns a reference to declaration, that match `decl_matcher` defined\n        criteria.\n\n        If a unique declaration could not be found, an appropriate exception\n        will be raised.\n\n        :param decl_matcher: Python callable object, that takes one argument -\n            reference to a declaration\n        :param decls: the search scope, :class:declaration_t object or\n            :class:declaration_t objects list t\n        :param recursive: boolean, if True, the method will run `decl_matcher`\n            on the internal declarations too"
  },
  {
    "code": "def get_static(self, _, file_name=None):\n        content_type = {\n            'ss': 'text/css',\n            'js': 'application/javascript',\n        }.get(file_name[-2:])\n        if not content_type:\n            raise HttpError(HTTPStatus.NOT_FOUND, 42)\n        return HttpResponse(self.load_static(file_name), headers={\n            'Content-Type': content_type,\n            'Content-Encoding': 'gzip',\n            'Cache-Control': 'public, max-age=300',\n        })",
    "docstring": "Get static content for UI."
  },
  {
    "code": "def decode_str(s, free=False):\n    try:\n        if s.len == 0:\n            return u\"\"\n        return ffi.unpack(s.data, s.len).decode(\"utf-8\", \"replace\")\n    finally:\n        if free:\n            lib.semaphore_str_free(ffi.addressof(s))",
    "docstring": "Decodes a SymbolicStr"
  },
  {
    "code": "def select_from_clusters(cluster_dict, measure_vect):\n    out_dict = {}\n    for idx_key, idx_list in cluster_dict.items():\n        out_idx, out_list = select_from_cluster(\n            idx_key, idx_list, measure_vect)\n        out_dict[out_idx] = out_list\n    return out_dict",
    "docstring": "Select a single source from each cluster and make it the new cluster key\n\n    cluster_dict : dict(int:[int,])        \n       A dictionary of clusters.   Each cluster is a source index and the list of other source in the cluster.    \n\n    measure_vect : np.narray((nsrc),float)\n      vector of the measure used to select the best source in the cluster\n\n    returns dict(int:[int,...])  \n       New dictionary of clusters keyed by the best source in each cluster"
  },
  {
    "code": "def get_cluster_plan(self):\n        _log.info('Fetching current cluster-topology from Zookeeper...')\n        cluster_layout = self.get_topics(fetch_partition_state=False)\n        partitions = [\n            {\n                'topic': topic_id,\n                'partition': int(p_id),\n                'replicas': partitions_data['replicas']\n            }\n            for topic_id, topic_info in six.iteritems(cluster_layout)\n            for p_id, partitions_data in six.iteritems(topic_info['partitions'])\n        ]\n        return {\n            'version': 1,\n            'partitions': partitions\n        }",
    "docstring": "Fetch cluster plan from zookeeper."
  },
  {
    "code": "def fill_buffer(heap_data, i_chan):\n        now = datetime.datetime.utcnow()\n        time_full = now.timestamp()\n        time_count = int(time_full)\n        time_fraction = int((time_full - time_count) * (2**32 - 1))\n        diff = now - (now.replace(hour=0, minute=0, second=0, microsecond=0))\n        time_data = diff.seconds + 1e-6 * diff.microseconds\n        heap_data['visibility_timestamp_count'] = time_count\n        heap_data['visibility_timestamp_fraction'] = time_fraction\n        heap_data['correlator_output_data']['VIS'][:][:] = \\\n            time_data + i_chan * 1j",
    "docstring": "Blocking function to populate data in the heap.\n        This is run in an executor."
  },
  {
    "code": "def all_to_public(self):\n        if \"private\" not in self.modifiers:\n            def public_collection(attribute):\n                for key in self.collection(attribute):\n                    if key not in self.publics:\n                        self.publics[key.lower()] = 1\n            public_collection(\"members\")\n            public_collection(\"types\")\n            public_collection(\"executables\")",
    "docstring": "Sets all members, types and executables in this module as public as\n        long as it doesn't already have the 'private' modifier."
  },
  {
    "code": "def returns(schema):\n    validate = parse(schema).validate\n    @decorator\n    def validating(func, *args, **kwargs):\n        ret = func(*args, **kwargs)\n        validate(ret, adapt=False)\n        return ret\n    return validating",
    "docstring": "Create a decorator for validating function return value.\n\n    Example::\n        @accepts(a=int, b=int)\n        @returns(int)\n        def f(a, b):\n            return a + b\n\n    :param schema: The schema for adapting a given parameter."
  },
  {
    "code": "def load_json(json_object):\n   content = None\n   if isinstance(json_object, str) and os.path.exists(json_object):\n      with open_(json_object) as f:\n         try:\n            content = json.load(f)\n         except Exception as e:\n            debug.log(\"Warning: Content of '%s' file is not json.\"%f.name)\n   elif hasattr(json_object, 'read'):\n      try:\n         content = json.load(json_object)\n      except Exception as e:\n         debug.log(\"Warning: Content of '%s' file is not json.\"%json_object.name)\n   else:\n      debug.log(\"%s\\nWarning: Object type invalid!\"%json_object)\n   return content",
    "docstring": "Load json from file or file name"
  },
  {
    "code": "def get_signature_request(self, signature_request_id, ux_version=None):\n        request = self._get_request()\n        parameters = None\n        if ux_version is not None:\n            parameters = {\n                'ux_version': ux_version\n            }\n        return request.get(self.SIGNATURE_REQUEST_INFO_URL + signature_request_id, parameters=parameters)",
    "docstring": "Get a signature request by its ID\n\n        Args:\n\n            signature_request_id (str):     The id of the SignatureRequest to retrieve\n\n            ux_version (int):               UX version, either 1 (default) or 2.\n\n        Returns:\n            A SignatureRequest object"
  },
  {
    "code": "def find(self, groupid):\n        return self.indices[self.offset[groupid]\n                :self.offset[groupid]+ self.length[groupid]]",
    "docstring": "return all of the indices of particles of groupid"
  },
  {
    "code": "def gen_part_from_line(lines: Iterable[str],\n                       part_index: int,\n                       splitter: str = None) -> Generator[str, None, None]:\n    for line in lines:\n        parts = line.split(splitter)\n        yield parts[part_index]",
    "docstring": "Splits lines with ``splitter`` and yields a specified part by index.\n\n    Args:\n        lines: iterable of strings\n        part_index: index of part to yield\n        splitter: string to split the lines on\n\n    Yields:\n        the specified part for each line"
  },
  {
    "code": "def switchCurrentView(self, viewType):\n        if not self.count():\n            return self.addView(viewType)\n        view = self.currentView()\n        if type(view) == viewType:\n            return view\n        self.blockSignals(True)\n        self.setUpdatesEnabled(False)\n        index = self.indexOf(view)\n        if not view.close():\n            return None\n        index = self.currentIndex()\n        new_view = viewType.createInstance(self.viewWidget(), self.viewWidget())\n        self.insertTab(index, new_view, new_view.windowTitle())\n        self.blockSignals(False)\n        self.setUpdatesEnabled(True)\n        self.setCurrentIndex(index)\n        return new_view",
    "docstring": "Swaps the current tab view for the inputed action's type.\n\n        :param      action | <QAction>\n\n        :return     <XView> || None"
  },
  {
    "code": "def vgg_layer(inputs,\n              nout,\n              kernel_size=3,\n              activation=tf.nn.leaky_relu,\n              padding=\"SAME\",\n              is_training=True,\n              has_batchnorm=False,\n              scope=None):\n  with tf.variable_scope(scope):\n    net = tfl.conv2d(inputs, nout, kernel_size=kernel_size, padding=padding,\n                     activation=None, name=\"conv\")\n    if has_batchnorm:\n      net = tfl.batch_normalization(net, training=is_training, name=\"bn\")\n    net = activation(net)\n  return net",
    "docstring": "A layer of VGG network with batch norm.\n\n  Args:\n    inputs: image tensor\n    nout: number of output channels\n    kernel_size: size of the kernel\n    activation: activation function\n    padding: padding of the image\n    is_training: whether it is training mode or not\n    has_batchnorm: whether batchnorm is applied or not\n    scope: variable scope of the op\n  Returns:\n    net: output of layer"
  },
  {
    "code": "def _get_isolated(self, hostport):\n        assert hostport, \"hostport is required\"\n        if hostport not in self._peers:\n            peer = self.peer_class(\n                tchannel=self.tchannel,\n                hostport=hostport,\n            )\n            self._peers[peer.hostport] = peer\n        return self._peers[hostport]",
    "docstring": "Get a Peer for the given destination for a request.\n\n        A new Peer is added and returned if one does not already exist for the\n        given host-port. Otherwise, the existing Peer is returned.\n\n        **NOTE** new peers will not be added to the peer heap."
  },
  {
    "code": "def _process_list(self, list_line):\n        res = list_line.split(' ', 8)\n        if res[0].startswith('-'):\n            self.state['file_list'].append(res[-1])\n        if res[0].startswith('d'):\n            self.state['dir_list'].append(res[-1])",
    "docstring": "Processes a line of 'ls -l' output, and updates state accordingly.\n\n        :param list_line: Line to process"
  },
  {
    "code": "def allow_migrate(self, db, model):\n        if db == DUAS_DB_ROUTE_PREFIX:\n            return model._meta.app_label == 'duashttp'\n        elif model._meta.app_label == 'duashttp':\n            return False\n        return None",
    "docstring": "Make sure the auth app only appears in the 'duashttp'\n        database."
  },
  {
    "code": "def get_network_adapter_object_type(adapter_object):\n    if isinstance(adapter_object, vim.vm.device.VirtualVmxnet2):\n        return 'vmxnet2'\n    if isinstance(adapter_object, vim.vm.device.VirtualVmxnet3):\n        return 'vmxnet3'\n    if isinstance(adapter_object, vim.vm.device.VirtualVmxnet):\n        return 'vmxnet'\n    if isinstance(adapter_object, vim.vm.device.VirtualE1000e):\n        return 'e1000e'\n    if isinstance(adapter_object, vim.vm.device.VirtualE1000):\n        return 'e1000'\n    raise ValueError('An unknown network adapter object type.')",
    "docstring": "Returns the network adapter type.\n\n    adapter_object\n        The adapter object from which to obtain the network adapter type."
  },
  {
    "code": "def safe_join(*paths):\n    try:\n        return join(*paths)\n    except UnicodeDecodeError:\n        npaths = ()\n        for path in paths:\n            npaths += (unicoder(path),)\n        return join(*npaths)",
    "docstring": "Join paths in a Unicode-safe way"
  },
  {
    "code": "def get_process_tag(program, ccd, version='p'):\n    return \"%s_%s%s\" % (program, str(version), str(ccd).zfill(2))",
    "docstring": "make a process tag have a suffix indicating which ccd its for.\n    @param program: Name of the process that a tag is built for.\n    @param ccd: the CCD number that this process ran on.\n    @param version: The version of the exposure (s, p, o) that the process ran on.\n    @return: The string that represents the processing tag."
  },
  {
    "code": "def block_header_verify( block_data, prev_hash, block_hash ):\n    serialized_header = block_header_to_hex( block_data, prev_hash )\n    candidate_hash_bin_reversed = hashing.bin_double_sha256(binascii.unhexlify(serialized_header))\n    candidate_hash = binascii.hexlify( candidate_hash_bin_reversed[::-1] )\n    return block_hash == candidate_hash",
    "docstring": "Verify whether or not bitcoind's block header matches the hash we expect."
  },
  {
    "code": "def normalized(self):\n        return Rect(pos=(min(self.left, self.right),\n                         min(self.top, self.bottom)),\n                    size=(abs(self.width), abs(self.height)))",
    "docstring": "Return a Rect covering the same area, but with height and width\n        guaranteed to be positive."
  },
  {
    "code": "def serializer(_type):\n    def inner(func):\n        name = dr.get_name(_type)\n        if name in SERIALIZERS:\n            msg = \"%s already has a serializer registered: %s\"\n            raise Exception(msg % (name, dr.get_name(SERIALIZERS[name])))\n        SERIALIZERS[name] = func\n        return func\n    return inner",
    "docstring": "Decorator for serializers.\n\n    A serializer should accept two parameters: An object and a path which is\n    a directory on the filesystem where supplementary data can be stored. This\n    is most often useful for datasources. It should return a dictionary version\n    of the original object that contains only elements that can be serialized\n    to json."
  },
  {
    "code": "def save_load(jid, clear_load, minions=None):\n    for returner_ in __opts__[CONFIG_KEY]:\n        _mminion().returners['{0}.save_load'.format(returner_)](jid, clear_load)",
    "docstring": "Write load to all returners in multi_returner"
  },
  {
    "code": "def _compile_constant_expression(self,\n                                     expr: Expression,\n                                     scope: Dict[str, TensorFluent],\n                                     batch_size: Optional[int] = None,\n                                     noise: Optional[List[tf.Tensor]] = None) -> TensorFluent:\n        etype = expr.etype\n        args = expr.args\n        dtype = utils.python_type_to_dtype(etype[1])\n        fluent = TensorFluent.constant(args, dtype=dtype)\n        return fluent",
    "docstring": "Compile a constant expression `expr` into a TensorFluent\n        in the given `scope` with optional batch size.\n\n        Args:\n            expr (:obj:`rddl2tf.expr.Expression`): A RDDL constant expression.\n            scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope.\n            batch_size (Optional[size]): The batch size.\n\n        Returns:\n            :obj:`rddl2tf.fluent.TensorFluent`: The compiled expression as a TensorFluent."
  },
  {
    "code": "def fetchAllUsers(self):\n        data = {\"viewer\": self._uid}\n        j = self._post(\n            self.req_url.ALL_USERS, query=data, fix_request=True, as_json=True\n        )\n        if j.get(\"payload\") is None:\n            raise FBchatException(\"Missing payload while fetching users: {}\".format(j))\n        users = []\n        for data in j[\"payload\"].values():\n            if data[\"type\"] in [\"user\", \"friend\"]:\n                if data[\"id\"] in [\"0\", 0]:\n                    continue\n                users.append(User._from_all_fetch(data))\n        return users",
    "docstring": "Gets all users the client is currently chatting with\n\n        :return: :class:`models.User` objects\n        :rtype: list\n        :raises: FBchatException if request failed"
  },
  {
    "code": "def init_from_class_batches(self, class_batches, num_shards=None):\n    shards_for_submissions = {}\n    shard_idx = 0\n    for idx, (batch_id, batch_val) in enumerate(iteritems(class_batches)):\n      work_id = DEFENSE_WORK_ID_PATTERN.format(idx)\n      submission_id = batch_val['submission_id']\n      shard_id = None\n      if num_shards:\n        shard_id = shards_for_submissions.get(submission_id)\n        if shard_id is None:\n          shard_id = shard_idx % num_shards\n          shards_for_submissions[submission_id] = shard_id\n          shard_idx += 1\n      self.work[work_id] = {\n          'claimed_worker_id': None,\n          'claimed_worker_start_time': None,\n          'is_completed': False,\n          'error': None,\n          'elapsed_time': None,\n          'submission_id': submission_id,\n          'shard_id': shard_id,\n          'output_classification_batch_id': batch_id,\n      }",
    "docstring": "Initializes work pieces from classification batches.\n\n    Args:\n      class_batches: dict with classification batches, could be obtained\n        as ClassificationBatches.data\n      num_shards: number of shards to split data into,\n        if None then no sharding is done."
  },
  {
    "code": "def open(cls, filename, band_names=None, lazy_load=True, mutable=False, **kwargs):\n        if mutable:\n            geo_raster = MutableGeoRaster(filename=filename, band_names=band_names, **kwargs)\n        else:\n            geo_raster = cls(filename=filename, band_names=band_names, **kwargs)\n        if not lazy_load:\n            geo_raster._populate_from_rasterio_object(read_image=True)\n        return geo_raster",
    "docstring": "Read a georaster from a file.\n\n        :param filename: url\n        :param band_names: list of strings, or string.\n                            if None - will try to read from image, otherwise - these will be ['0', ..]\n        :param lazy_load: if True - do not load anything\n        :return: GeoRaster2"
  },
  {
    "code": "def present_weather_codes(self, value=None):\n        if value is not None:\n            try:\n                value = int(value)\n            except ValueError:\n                raise ValueError(\n                    'value {} need to be of type int '\n                    'for field `present_weather_codes`'.format(value))\n        self._present_weather_codes = value",
    "docstring": "Corresponds to IDD Field `present_weather_codes`\n\n        Args:\n            value (int): value for IDD Field `present_weather_codes`\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def to_allele_counts(self, max_allele=None, dtype='u1'):\n        if max_allele is None:\n            max_allele = self.max()\n        alleles = list(range(max_allele + 1))\n        outshape = self.shape[:-1] + (len(alleles),)\n        out = np.zeros(outshape, dtype=dtype)\n        for allele in alleles:\n            allele_match = self.values == allele\n            if self.mask is not None:\n                allele_match &= ~self.mask[..., np.newaxis]\n            np.sum(allele_match, axis=-1, out=out[..., allele])\n        if self.ndim == 2:\n            out = GenotypeAlleleCountsVector(out)\n        elif self.ndim == 3:\n            out = GenotypeAlleleCountsArray(out)\n        return out",
    "docstring": "Transform genotype calls into allele counts per call.\n\n        Parameters\n        ----------\n        max_allele : int, optional\n            Highest allele index. Provide this value to speed up computation.\n        dtype : dtype, optional\n            Output dtype.\n\n        Returns\n        -------\n        out : ndarray, uint8, shape (n_variants, n_samples, len(alleles))\n            Array of allele counts per call.\n\n        Examples\n        --------\n\n        >>> import allel\n        >>> g = allel.GenotypeArray([[[0, 0], [0, 1]],\n        ...                          [[0, 2], [1, 1]],\n        ...                          [[2, 2], [-1, -1]]])\n        >>> g.to_allele_counts()\n        <GenotypeAlleleCountsArray shape=(3, 2, 3) dtype=uint8>\n        2:0:0 1:1:0\n        1:0:1 0:2:0\n        0:0:2 0:0:0\n        >>> v = g[:, 0]\n        >>> v\n        <GenotypeVector shape=(3, 2) dtype=int64>\n        0/0 0/2 2/2\n        >>> v.to_allele_counts()\n        <GenotypeAlleleCountsVector shape=(3, 3) dtype=uint8>\n        2:0:0 1:0:1 0:0:2"
  },
  {
    "code": "def is_for_driver_task(self):\n        return all(\n            len(x) == 0\n            for x in [self.module_name, self.class_name, self.function_name])",
    "docstring": "See whether this function descriptor is for a driver or not.\n\n        Returns:\n            True if this function descriptor is for driver tasks."
  },
  {
    "code": "def disconnect(self, message=\"\"):\n        try:\n            del self.connected\n        except AttributeError:\n            return\n        try:\n            self.socket.shutdown(socket.SHUT_WR)\n            self.socket.close()\n        except socket.error:\n            pass\n        del self.socket\n        self.reactor._handle_event(\n            self,\n            Event(\"dcc_disconnect\", self.peeraddress, \"\", [message]))\n        self.reactor._remove_connection(self)",
    "docstring": "Hang up the connection and close the object.\n\n        Arguments:\n\n            message -- Quit message."
  },
  {
    "code": "def get_registered_services(self):\n        if self._state == Bundle.UNINSTALLED:\n            raise BundleException(\n                \"Can't call 'get_registered_services' on an \"\n                \"uninstalled bundle\"\n            )\n        return self.__framework._registry.get_bundle_registered_services(self)",
    "docstring": "Returns this bundle's ServiceReference list for all services it has\n        registered or an empty list\n\n        The list is valid at the time of the call to this method, however, as\n        the Framework is a very dynamic environment, services can be modified\n        or unregistered at any time.\n\n        :return: An array of ServiceReference objects\n        :raise BundleException: If the bundle has been uninstalled"
  },
  {
    "code": "def minimum_pitch(self):\n        pitch = self.pitch\n        minimal_pitch = []\n        for p in pitch:\n            minimal_pitch.append(min(p))\n        return min(minimal_pitch)",
    "docstring": "Returns the minimal pitch between two neighboring nodes of the mesh in each direction.\n\n        :return: Minimal pitch in each direction."
  },
  {
    "code": "def build_function(name, args=None, defaults=None, doc=None):\n    args, defaults = args or [], defaults or []\n    func = nodes.FunctionDef(name, doc)\n    func.args = argsnode = nodes.Arguments()\n    argsnode.args = []\n    for arg in args:\n        argsnode.args.append(nodes.Name())\n        argsnode.args[-1].name = arg\n        argsnode.args[-1].parent = argsnode\n    argsnode.defaults = []\n    for default in defaults:\n        argsnode.defaults.append(nodes.const_factory(default))\n        argsnode.defaults[-1].parent = argsnode\n    argsnode.kwarg = None\n    argsnode.vararg = None\n    argsnode.parent = func\n    if args:\n        register_arguments(func)\n    return func",
    "docstring": "create and initialize an astroid FunctionDef node"
  },
  {
    "code": "def touch(self, conn, key, exptime):\n        assert self._validate_key(key)\n        _cmd = b' '.join([b'touch', key, str(exptime).encode('utf-8')])\n        cmd = _cmd + b'\\r\\n'\n        resp = yield from self._execute_simple_command(conn, cmd)\n        if resp not in (const.TOUCHED, const.NOT_FOUND):\n            raise ClientException('Memcached touch failed', resp)\n        return resp == const.TOUCHED",
    "docstring": "The command is used to update the expiration time of\n        an existing item without fetching it.\n\n        :param key: ``bytes``, is the key to update expiration time\n        :param exptime: ``int``, is expiration time. This replaces the existing\n        expiration time.\n        :return: ``bool``, True in case of success."
  },
  {
    "code": "def fix_positions(self):\n        shift_x = 0\n        for m in self.__reactants:\n            max_x = self.__fix_positions(m, shift_x, 0)\n            shift_x = max_x + 1\n        arrow_min = shift_x\n        if self.__reagents:\n            for m in self.__reagents:\n                max_x = self.__fix_positions(m, shift_x, 1.5)\n                shift_x = max_x + 1\n        else:\n            shift_x += 3\n        arrow_max = shift_x - 1\n        for m in self.__products:\n            max_x = self.__fix_positions(m, shift_x, 0)\n            shift_x = max_x + 1\n        self._arrow = (arrow_min, arrow_max)\n        self.flush_cache()",
    "docstring": "fix coordinates of molecules in reaction"
  },
  {
    "code": "def handleFailure(self, test, err):\n        want_failure = self._handle_test_error_or_failure(test, err)\n        if not want_failure and id(test) in self._tests_that_reran:\n            self._nose_result.addFailure(test, err)\n        return want_failure or None",
    "docstring": "Baseclass override. Called when a test fails.\n\n        If the test isn't going to be rerun again, then report the failure\n        to the nose test result.\n\n        :param test:\n            The test that has raised an error\n        :type test:\n            :class:`nose.case.Test`\n        :param err:\n            Information about the test failure (from sys.exc_info())\n        :type err:\n            `tuple` of `class`, :class:`Exception`, `traceback`\n        :return:\n            True, if the test will be rerun; False, if nose should handle it.\n        :rtype:\n            `bool`"
  },
  {
    "code": "def to_dotfile(self):\n        domain = self.get_domain()\n        filename = \"%s.dot\" % (self.__class__.__name__)\n        nx.write_dot(domain, filename)\n        return filename",
    "docstring": "Writes a DOT graphviz file of the domain structure, and returns the filename"
  },
  {
    "code": "def do_zsh_complete(cli, prog_name):\n    commandline = os.environ['COMMANDLINE']\n    args = split_args(commandline)[1:]\n    if args and not commandline.endswith(' '):\n        incomplete = args[-1]\n        args = args[:-1]\n    else:\n        incomplete = ''\n    def escape(s):\n        return s.replace('\"', '\"\"').replace(\"'\", \"''\").replace('$', '\\\\$').replace('`', '\\\\`')\n    res = []\n    for item, help in get_choices(cli, prog_name, args, incomplete):\n        if help:\n            res.append(r'\"%s\"\\:\"%s\"' % (escape(item), escape(help)))\n        else:\n            res.append('\"%s\"' % escape(item))\n    if res:\n        echo(\"_arguments '*: :((%s))'\" % '\\n'.join(res))\n    else:\n        echo(\"_files\")\n    return True",
    "docstring": "Do the zsh completion\n\n    Parameters\n    ----------\n    cli : click.Command\n        The main click Command of the program\n    prog_name : str\n        The program name on the command line\n\n    Returns\n    -------\n    bool\n        True if the completion was successful, False otherwise"
  },
  {
    "code": "def main():\n    test_targets = (    \n        [ARCH_I386, MACH_I386_I386_INTEL_SYNTAX, ENDIAN_MONO, \"\\x55\\x89\\xe5\\xE8\\xB8\\xFF\\xFF\\xFF\", 0x1000],\n        [ARCH_I386, MACH_X86_64_INTEL_SYNTAX, ENDIAN_MONO, \"\\x55\\x48\\x89\\xe5\\xE8\\xA3\\xFF\\xFF\\xFF\", 0x1000],\n        [ARCH_ARM, MACH_ARM_2, ENDIAN_LITTLE, \"\\x04\\xe0\\x2d\\xe5\\xED\\xFF\\xFF\\xEB\", 0x1000],\n        [ARCH_MIPS, MACH_MIPSISA32, ENDIAN_BIG, \"\\x0C\\x10\\x00\\x97\\x00\\x00\\x00\\x00\", 0x1000],\n        [ARCH_POWERPC, MACH_PPC, ENDIAN_BIG, \"\\x94\\x21\\xFF\\xE8\\x7C\\x08\\x02\\xA6\", 0x1000],\n        )\n    for target_arch, target_mach, target_endian, binary, address in test_targets:\n        opcodes = Opcodes(target_arch, target_mach, target_endian)\n        print \"\\n[+] Architecture %s - Machine %d\" % \\\n            (opcodes.architecture_name, opcodes.machine)\n        print \"[+] Disassembly:\"\n        for vma, size, disasm in opcodes.disassemble(binary, address):\n            print \"0x%X (size=%d)\\t %s\" % (vma, size, disasm)",
    "docstring": "Test case for simple opcode disassembly."
  },
  {
    "code": "def throw_if_parsable(resp):\n    e = None\n    try:\n        e = parse_response(resp)\n    except:\n        LOG.debug(utils.stringify_expt())\n    if e is not None:\n        raise e\n    if resp.status_code == 404:\n        raise NoSuchObject('No such object.')\n    else:\n        text = resp.text if six.PY3 else resp.content\n        if text:\n            raise ODPSError(text, code=str(resp.status_code))\n        else:\n            raise ODPSError(str(resp.status_code))",
    "docstring": "Try to parse the content of the response and raise an exception\n    if neccessary."
  },
  {
    "code": "def determine_result(self, returncode, returnsignal, output, isTimeout):\n        splitout = \"\\n\".join(output)\n        if 'SMACK found no errors' in splitout:\n          return result.RESULT_TRUE_PROP\n        errmsg = re.search(r'SMACK found an error(:\\s+([^\\.]+))?\\.', splitout)\n        if errmsg:\n          errtype = errmsg.group(2)\n          if errtype:\n            if 'invalid pointer dereference' == errtype:\n              return result.RESULT_FALSE_DEREF\n            elif 'invalid memory deallocation' == errtype:\n              return result.RESULT_FALSE_FREE\n            elif 'memory leak' == errtype:\n              return result.RESULT_FALSE_MEMTRACK\n            elif 'memory cleanup' == errtype:\n              return result.RESULT_FALSE_MEMCLEANUP\n            elif 'integer overflow' == errtype:\n              return result.RESULT_FALSE_OVERFLOW\n          else:\n            return result.RESULT_FALSE_REACH\n        return result.RESULT_UNKNOWN",
    "docstring": "Returns a BenchExec result status based on the output of SMACK"
  },
  {
    "code": "def get_log_entry_ids_by_log(self, log_id):\n        id_list = []\n        for log_entry in self.get_log_entries_by_log(log_ids):\n            id_list.append(log_entry.get_id())\n        return IdList(id_list)",
    "docstring": "Gets the list of ``LogEntry``  ``Ids`` associated with a ``Log``.\n\n        arg:    log_id (osid.id.Id): ``Id`` of a ``Log``\n        return: (osid.id.IdList) - list of related logEntry ``Ids``\n        raise:  NotFound - ``log_id`` is not found\n        raise:  NullArgument - ``log_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def plot_joint_sfs_folded_scaled(*args, **kwargs):\n    imshow_kwargs = kwargs.get('imshow_kwargs', dict())\n    imshow_kwargs.setdefault('norm', None)\n    kwargs['imshow_kwargs'] = imshow_kwargs\n    ax = plot_joint_sfs_folded(*args, **kwargs)\n    ax.set_xlabel('minor allele count (population 1)')\n    ax.set_ylabel('minor allele count (population 2)')\n    return ax",
    "docstring": "Plot a scaled folded joint site frequency spectrum.\n\n    Parameters\n    ----------\n    s : array_like, int, shape (n_chromosomes_pop1/2, n_chromosomes_pop2/2)\n        Joint site frequency spectrum.\n    ax : axes, optional\n        Axes on which to draw. If not provided, a new figure will be created.\n    imshow_kwargs : dict-like\n        Additional keyword arguments, passed through to ax.imshow().\n\n    Returns\n    -------\n    ax : axes\n        The axes on which the plot was drawn."
  },
  {
    "code": "def from_two_bytes(bytes):\n    lsb, msb = bytes\n    try:\n        return msb << 7 | lsb\n    except TypeError:\n        try:\n            lsb = ord(lsb)\n        except TypeError:\n            pass\n        try:\n            msb = ord(msb)\n        except TypeError:\n            pass\n        return msb << 7 | lsb",
    "docstring": "Return an integer from two 7 bit bytes."
  },
  {
    "code": "def _get_json(value):\n    if hasattr(value, 'replace'):\n        value = value.replace('\\n', ' ')\n    try:\n        return json.loads(value)\n    except json.JSONDecodeError:\n        if hasattr(value, 'replace'):\n            value = value.replace('\"', '\\\\\"')\n        return json.loads('\"{}\"'.format(value))",
    "docstring": "Convert the given value to a JSON object."
  },
  {
    "code": "def normpath (path):\n    expanded = os.path.expanduser(os.path.expandvars(path))\n    return os.path.normcase(os.path.normpath(expanded))",
    "docstring": "Norm given system path with all available norm or expand functions\n    in os.path."
  },
  {
    "code": "def perplexity(test_data, predictions, topics, vocabulary):\n    test_data = _check_input(test_data)\n    assert isinstance(predictions, _SArray), \\\n        \"Predictions must be an SArray of vector type.\"\n    assert predictions.dtype == _array.array, \\\n        \"Predictions must be probabilities. Try using m.predict() with \" + \\\n        \"output_type='probability'.\"\n    opts = {'test_data': test_data,\n            'predictions': predictions,\n            'topics': topics,\n            'vocabulary': vocabulary}\n    response = _turicreate.extensions._text.topicmodel_get_perplexity(opts)\n    return response['perplexity']",
    "docstring": "Compute the perplexity of a set of test documents given a set\n    of predicted topics.\n\n    Let theta be the matrix of document-topic probabilities, where\n    theta_ik = p(topic k | document i). Let Phi be the matrix of term-topic\n    probabilities, where phi_jk = p(word j | topic k).\n\n    Then for each word in each document, we compute for a given word w\n    and document d\n\n    .. math::\n        p(word | \\theta[doc_id,:], \\phi[word_id,:]) =\n       \\sum_k \\theta[doc_id, k] * \\phi[word_id, k]\n\n    We compute loglikelihood to be:\n\n    .. math::\n        l(D) = \\sum_{i \\in D} \\sum_{j in D_i} count_{i,j} * log Pr(word_{i,j} | \\theta, \\phi)\n\n    and perplexity to be\n\n    .. math::\n        \\exp \\{ - l(D) / \\sum_i \\sum_j count_{i,j} \\}\n\n    Parameters\n    ----------\n    test_data : SArray of type dict or SFrame with a single column of type dict\n        Documents in bag-of-words format.\n\n    predictions : SArray\n        An SArray of vector type, where each vector contains estimates of the\n        probability that this document belongs to each of the topics.\n        This must have the same size as test_data; otherwise an exception\n        occurs. This can be the output of\n        :py:func:`~turicreate.topic_model.TopicModel.predict`, for example.\n\n    topics : SFrame\n        An SFrame containing two columns: 'vocabulary' and 'topic_probabilities'.\n        The value returned by m['topics'] is a valid input for this argument,\n        where m is a trained :py:class:`~turicreate.topic_model.TopicModel`.\n\n    vocabulary : SArray\n        An SArray of words to use. All words in test_data that are not in this\n        vocabulary will be ignored.\n\n    Notes\n    -----\n    For more details, see equations 13-16 of [PattersonTeh2013].\n\n\n    References\n    ----------\n    .. [PERP] `Wikipedia - perplexity <http://en.wikipedia.org/wiki/Perplexity>`_\n\n    .. [PattersonTeh2013] Patterson, Teh. `\"Stochastic Gradient Riemannian\n       Langevin Dynamics on the Probability Simplex\"\n       <http://www.stats.ox.ac.uk/~teh/research/compstats/PatTeh2013a.pdf>`_\n       NIPS, 2013.\n\n    Examples\n    --------\n    >>> from turicreate import topic_model\n    >>> train_data, test_data = turicreate.text_analytics.random_split(docs)\n    >>> m = topic_model.create(train_data)\n    >>> pred = m.predict(train_data)\n    >>> topics = m['topics']\n    >>> p = topic_model.perplexity(test_data, pred,\n                                   topics['topic_probabilities'],\n                                   topics['vocabulary'])\n    >>> p\n    1720.7  # lower values are better"
  },
  {
    "code": "def extend_settings(self, data_id, files, secrets):\n        process = Data.objects.get(pk=data_id).process\n        if process.requirements.get('resources', {}).get('secrets', False):\n            raise PermissionDenied(\n                \"Process which requires access to secrets cannot be run using the local executor\"\n            )\n        return super().extend_settings(data_id, files, secrets)",
    "docstring": "Prevent processes requiring access to secrets from being run."
  },
  {
    "code": "def decimal128_to_decimal(b):\n    \"decimal128 bytes to Decimal\"\n    v = decimal128_to_sign_digits_exponent(b)\n    if isinstance(v, Decimal):\n        return v\n    sign, digits, exponent = v\n    return Decimal((sign, Decimal(digits).as_tuple()[1], exponent))",
    "docstring": "decimal128 bytes to Decimal"
  },
  {
    "code": "def replace_suffixes_4(self, word):\n        length = len(word)\n        replacements = {'ational': 'ate', 'tional': 'tion', 'alize': 'al',\n                        'icate': 'ic', 'iciti': 'ic', 'ical': 'ic',\n                        'ful': '', 'ness': ''}\n        for suffix in replacements.keys():\n            if word.endswith(suffix):\n                suffix_length = len(suffix)\n                if self.r1 <= (length - suffix_length):\n                    word = word[:-suffix_length] + replacements[suffix]\n        if word.endswith('ative'):\n            if self.r1 <= (length - 5) and self.r2 <= (length - 5):\n                word = word[:-5]\n        return word",
    "docstring": "Perform replacements on even more common suffixes."
  },
  {
    "code": "def _get(self, url, params=None, headers=None):\n        url = self.clean_url(url)\n        response = requests.get(url, params=params, verify=self.verify,\n                                timeout=self.timeout, headers=headers)\n        return response",
    "docstring": "Wraps a GET request with a url check"
  },
  {
    "code": "def add(self, snapshot, distributions, component='main', storage=\"\"):\n        for dist in distributions:\n            self.publish(dist, storage=storage).add(snapshot, component)",
    "docstring": "Add mirror or repo to publish"
  },
  {
    "code": "def train_step_single(self, Xi, yi, **fit_params):\n        self.module_.train()\n        self.optimizer_.zero_grad()\n        y_pred = self.infer(Xi, **fit_params)\n        loss = self.get_loss(y_pred, yi, X=Xi, training=True)\n        loss.backward()\n        self.notify(\n            'on_grad_computed',\n            named_parameters=TeeGenerator(self.module_.named_parameters()),\n            X=Xi,\n            y=yi\n        )\n        return {\n            'loss': loss,\n            'y_pred': y_pred,\n            }",
    "docstring": "Compute y_pred, loss value, and update net's gradients.\n\n        The module is set to be in train mode (e.g. dropout is\n        applied).\n\n        Parameters\n        ----------\n        Xi : input data\n          A batch of the input data.\n\n        yi : target data\n          A batch of the target data.\n\n        **fit_params : dict\n          Additional parameters passed to the ``forward`` method of\n          the module and to the ``self.train_split`` call."
  },
  {
    "code": "def get_es(**overrides):\n    defaults = {\n        'urls': settings.ES_URLS,\n        'timeout': getattr(settings, 'ES_TIMEOUT', 5)\n        }\n    defaults.update(overrides)\n    return base_get_es(**defaults)",
    "docstring": "Return a elasticsearch Elasticsearch object using settings\n    from ``settings.py``.\n\n    :arg overrides: Allows you to override defaults to create the\n        ElasticSearch object. You can override any of the arguments\n        isted in :py:func:`elasticutils.get_es`.\n\n    For example, if you wanted to create an ElasticSearch with a\n    longer timeout to a different cluster, you'd do:\n\n    >>> from elasticutils.contrib.django import get_es\n    >>> es = get_es(urls=['http://some_other_cluster:9200'], timeout=30)"
  },
  {
    "code": "def etag(self, href):\n        if self and self._etag is None:\n            self._etag = LoadElement(href, only_etag=True)\n        return self._etag",
    "docstring": "ETag can be None if a subset of element json is using\n        this container, such as the case with Routing."
  },
  {
    "code": "def simplified_rayliegh_vel(self):\n        thicks = np.array([l.thickness for l in self])\n        depths_mid = np.array([l.depth_mid for l in self])\n        shear_vels = np.array([l.shear_vel for l in self])\n        mode_incr = depths_mid * thicks / shear_vels ** 2\n        shape = np.r_[np.cumsum(mode_incr[::-1])[::-1], 0]\n        freq_fund = np.sqrt(4 * np.sum(\n            thicks * depths_mid ** 2 / shear_vels ** 2\n        ) / np.sum(\n            thicks *\n            np.sum(np.c_[shape, np.roll(shape, -1)], axis=1)[:-1] ** 2))\n        period_fun = 2 * np.pi / freq_fund\n        rayleigh_vel = 4 * thicks.sum() / period_fun\n        return rayleigh_vel",
    "docstring": "Simplified Rayliegh velocity of the site.\n\n        This follows the simplifications proposed by Urzua et al. (2017)\n\n        Returns\n        -------\n        rayleigh_vel : float\n            Equivalent shear-wave velocity."
  },
  {
    "code": "def normalize_curves_eb(curves):\n    non_zero_curves = [(losses, poes)\n                       for losses, poes in curves if losses[-1] > 0]\n    if not non_zero_curves:\n        return curves[0][0], numpy.array([poes for _losses, poes in curves])\n    else:\n        max_losses = [losses[-1] for losses, _poes in non_zero_curves]\n        reference_curve = non_zero_curves[numpy.argmax(max_losses)]\n        loss_ratios = reference_curve[0]\n        curves_poes = [interpolate.interp1d(\n            losses, poes, bounds_error=False, fill_value=0)(loss_ratios)\n            for losses, poes in curves]\n        for cp in curves_poes:\n            if numpy.isnan(cp[0]):\n                cp[0] = 0\n    return loss_ratios, numpy.array(curves_poes)",
    "docstring": "A more sophisticated version of normalize_curves, used in the event\n    based calculator.\n\n    :param curves: a list of pairs (losses, poes)\n    :returns: first losses, all_poes"
  },
  {
    "code": "def _get(url, headers={}, params=None):\n    param_string = _foursquare_urlencode(params)\n    for i in xrange(NUM_REQUEST_RETRIES):\n        try:\n            try:\n                response = requests.get(url, headers=headers, params=param_string, verify=VERIFY_SSL)\n                return _process_response(response)\n            except requests.exceptions.RequestException as e:\n                _log_and_raise_exception('Error connecting with foursquare API', e)\n        except FoursquareException as e:\n            if e.__class__ in [InvalidAuth, ParamError, EndpointError, NotAuthorized, Deprecated]: raise\n            if ((i + 1) == NUM_REQUEST_RETRIES): raise\n        time.sleep(1)",
    "docstring": "Tries to GET data from an endpoint using retries"
  },
  {
    "code": "def get_crt_common_name(certificate_path=OLD_CERTIFICATE_PATH):\n    try:\n        certificate_file = open(certificate_path)\n        crt = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,\n                                              certificate_file.read())\n        return crt.get_subject().commonName\n    except IOError:\n        return None",
    "docstring": "Get CN from certificate"
  },
  {
    "code": "def wnelmd(point, window):\n    assert isinstance(window, stypes.SpiceCell)\n    assert window.dtype == 1\n    point = ctypes.c_double(point)\n    return bool(libspice.wnelmd_c(point, ctypes.byref(window)))",
    "docstring": "Determine whether a point is an element of a double precision\n    window.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnelmd_c.html\n\n    :param point: Input point. \n    :type point: float\n    :param window: Input window \n    :type window: spiceypy.utils.support_types.SpiceCell\n    :return: returns True if point is an element of window.\n    :rtype: bool"
  },
  {
    "code": "def func(self, p):\n        self._set_stochastics(p)\n        try:\n            return -1. * self.logp\n        except ZeroProbability:\n            return Inf",
    "docstring": "The function that gets passed to the optimizers."
  },
  {
    "code": "def open(self, bus):\n        self.fd = os.open(\"/dev/i2c-{}\".format(bus), os.O_RDWR)\n        self.funcs = self._get_funcs()",
    "docstring": "Open a given i2c bus.\n\n        :param bus: i2c bus number (e.g. 0 or 1)\n        :type bus: int"
  },
  {
    "code": "def slot_name_from_member_name(member_name):\n    def replace_char(match):\n        c = match.group(0)\n        return '_' if c in '-.' else \"u{:04d}\".format(ord(c))\n    slot_name = re.sub('[^a-z0-9_]', replace_char, member_name.lower())\n    return slot_name[0:63]",
    "docstring": "Translate member name to valid PostgreSQL slot name.\n\n    PostgreSQL replication slot names must be valid PostgreSQL names. This function maps the wider space of\n    member names to valid PostgreSQL names. Names are lowercased, dashes and periods common in hostnames\n    are replaced with underscores, other characters are encoded as their unicode codepoint. Name is truncated\n    to 64 characters. Multiple different member names may map to a single slot name."
  },
  {
    "code": "def fetch_pillar(self):\n        log.debug('Pillar cache getting external pillar with ext: %s', self.ext)\n        fresh_pillar = Pillar(self.opts,\n                              self.grains,\n                              self.minion_id,\n                              self.saltenv,\n                              ext=self.ext,\n                              functions=self.functions,\n                              pillarenv=self.pillarenv)\n        return fresh_pillar.compile_pillar()",
    "docstring": "In the event of a cache miss, we need to incur the overhead of caching\n        a new pillar."
  },
  {
    "code": "def reify_arrays(arrays, dims, copy=True):\n    arrays = ({ k : AttrDict(**a) for k, a in arrays.iteritems() }\n        if copy else arrays)\n    for n, a in arrays.iteritems():\n        a.shape = tuple(dims[v].extent_size if isinstance(v, str) else v\n            for v in a.shape)\n    return arrays",
    "docstring": "Reify arrays, given the supplied dimensions. If copy is True,\n    returns a copy of arrays else performs this inplace."
  },
  {
    "code": "def _load_feed(path: str, view: View, config: nx.DiGraph) -> Feed:\n    config_ = remove_node_attributes(config, [\"converters\", \"transformations\"])\n    feed_ = Feed(path, view={}, config=config_)\n    for filename, column_filters in view.items():\n        config_ = reroot_graph(config_, filename)\n        view_ = {filename: column_filters}\n        feed_ = Feed(feed_, view=view_, config=config_)\n    return Feed(feed_, config=config)",
    "docstring": "Multi-file feed filtering"
  },
  {
    "code": "def last_revision(self, mod: YangIdentifier) -> ModuleId:\n        revs = [mn for mn in self.modules if mn[0] == mod]\n        if not revs:\n            raise ModuleNotRegistered(mod)\n        return sorted(revs, key=lambda x: x[1])[-1]",
    "docstring": "Return the last revision of a module that's part of the data model.\n\n        Args:\n            mod: Name of a module or submodule.\n\n        Raises:\n            ModuleNotRegistered: If the module `mod` is not present in the\n                data model."
  },
  {
    "code": "def get_grp_name(self, code):\n        nt_code = self.code2nt.get(code.strip(), None)\n        if nt_code is not None:\n            return nt_code.group, nt_code.name\n        return \"\", \"\"",
    "docstring": "Return group and name for an evidence code."
  },
  {
    "code": "def _do_download(\n        self, transport, file_obj, download_url, headers, start=None, end=None\n    ):\n        if self.chunk_size is None:\n            download = Download(\n                download_url, stream=file_obj, headers=headers, start=start, end=end\n            )\n            download.consume(transport)\n        else:\n            download = ChunkedDownload(\n                download_url,\n                self.chunk_size,\n                file_obj,\n                headers=headers,\n                start=start if start else 0,\n                end=end,\n            )\n            while not download.finished:\n                download.consume_next_chunk(transport)",
    "docstring": "Perform a download without any error handling.\n\n        This is intended to be called by :meth:`download_to_file` so it can\n        be wrapped with error handling / remapping.\n\n        :type transport:\n            :class:`~google.auth.transport.requests.AuthorizedSession`\n        :param transport: The transport (with credentials) that will\n                          make authenticated requests.\n\n        :type file_obj: file\n        :param file_obj: A file handle to which to write the blob's data.\n\n        :type download_url: str\n        :param download_url: The URL where the media can be accessed.\n\n        :type headers: dict\n        :param headers: Optional headers to be sent with the request(s).\n\n        :type start: int\n        :param start: Optional, the first byte in a range to be downloaded.\n\n        :type end: int\n        :param end: Optional, The last byte in a range to be downloaded."
  },
  {
    "code": "def _add_post_data(self, request: Request):\n        if self._item_session.url_record.post_data:\n            data = wpull.string.to_bytes(self._item_session.url_record.post_data)\n        else:\n            data = wpull.string.to_bytes(\n                self._processor.fetch_params.post_data\n            )\n        request.method = 'POST'\n        request.fields['Content-Type'] = 'application/x-www-form-urlencoded'\n        request.fields['Content-Length'] = str(len(data))\n        _logger.debug('Posting with data {0}.', data)\n        if not request.body:\n            request.body = Body(io.BytesIO())\n        with wpull.util.reset_file_offset(request.body):\n            request.body.write(data)",
    "docstring": "Add data to the payload."
  },
  {
    "code": "def make_gffutils_db(gtf, db):\n    import gffutils\n    out_db = gffutils.create_db(gtf,\n                                db,\n                                keep_order=True,\n                                infer_gene_extent=False)\n    return out_db",
    "docstring": "Make database for gffutils. \n\n    Parameters\n    ----------\n    gtf : str\n        Path to Gencode gtf file.\n\n    db : str\n        Path to save database to. \n\n    Returns\n    -------\n    out_db : gffutils.FeatureDB\n        gffutils feature database."
  },
  {
    "code": "def season_game_logs(season):\n    max_year = int(datetime.now().year) - 1\n    if season > max_year or season < 1871:\n        raise ValueError('Season must be between 1871 and {}'.format(max_year))\n    file_name = 'GL{}.TXT'.format(season)\n    z = get_zip_file(gamelog_url.format(season))\n    data = pd.read_csv(z.open(file_name), header=None, sep=',', quotechar='\"')\n    data.columns = gamelog_columns\n    return data",
    "docstring": "Pull Retrosheet game logs for a given season"
  },
  {
    "code": "def dns():\n    if salt.utils.platform.is_windows() or 'proxyminion' in __opts__:\n        return {}\n    resolv = salt.utils.dns.parse_resolv()\n    for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers',\n                'sortlist'):\n        if key in resolv:\n            resolv[key] = [six.text_type(i) for i in resolv[key]]\n    return {'dns': resolv} if resolv else {}",
    "docstring": "Parse the resolver configuration file\n\n     .. versionadded:: 2016.3.0"
  },
  {
    "code": "def buckingham_input(self, structure, keywords, library=None,\n                         uc=True, valence_dict=None):\n        gin = self.keyword_line(*keywords)\n        gin += self.structure_lines(structure, symm_flg=not uc)\n        if not library:\n            gin += self.buckingham_potential(structure, valence_dict)\n        else:\n            gin += self.library_line(library)\n        return gin",
    "docstring": "Gets a GULP input for an oxide structure and buckingham potential\n        from library.\n\n        Args:\n            structure: pymatgen.core.structure.Structure\n            keywords: GULP first line keywords.\n            library (Default=None): File containing the species and potential.\n            uc (Default=True): Unit Cell Flag.\n            valence_dict: {El: valence}"
  },
  {
    "code": "def add_prioritized(self, command_obj, priority):\n\t\tif priority not in self.__priorities.keys():\n\t\t\tself.__priorities[priority] = []\n\t\tself.__priorities[priority].append(command_obj)",
    "docstring": "Add command with the specified priority\n\n\t\t:param command_obj: command to add\n\t\t:param priority: command priority\n\t\t:return: None"
  },
  {
    "code": "def get_resource_ids_by_bin(self, bin_id):\n        id_list = []\n        for resource in self.get_resources_by_bin(bin_id):\n            id_list.append(resource.get_id())\n        return IdList(id_list)",
    "docstring": "Gets the list of ``Resource``  ``Ids`` associated with a ``Bin``.\n\n        arg:    bin_id (osid.id.Id): ``Id`` of a ``Bin``\n        return: (osid.id.IdList) - list of related resource ``Ids``\n        raise:  NotFound - ``bin_id`` is not found\n        raise:  NullArgument - ``bin_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def validate_ip(s):\n    if _DOTTED_QUAD_RE.match(s):\n        quads = s.split('.')\n        for q in quads:\n            if int(q) > 255:\n                return False\n        return True\n    return False",
    "docstring": "Validate a dotted-quad ip address.\n\n    The string is considered a valid dotted-quad address if it consists of\n    one to four octets (0-255) seperated by periods (.).\n\n\n    >>> validate_ip('127.0.0.1')\n    True\n    >>> validate_ip('127.0')\n    True\n    >>> validate_ip('127.0.0.256')\n    False\n    >>> validate_ip(LOCALHOST)\n    True\n    >>> validate_ip(None) #doctest: +IGNORE_EXCEPTION_DETAIL\n    Traceback (most recent call last):\n        ...\n    TypeError: expected string or buffer\n\n\n    :param s: String to validate as a dotted-quad ip address.\n    :type s: str\n    :returns: ``True`` if a valid dotted-quad ip address, ``False`` otherwise.\n    :raises: TypeError"
  },
  {
    "code": "def build_label(self, ident, cls):\n        ident_w_label = ident + ':' + cls.__label__\n        self._ast['match'].append('({0})'.format(ident_w_label))\n        self._ast['return'] = ident\n        self._ast['result_class'] = cls\n        return ident",
    "docstring": "match nodes by a label"
  },
  {
    "code": "def thumbnails_for_file(relative_source_path, root=None, basedir=None,\n                        subdir=None, prefix=None):\n    if root is None:\n        root = settings.MEDIA_ROOT\n    if prefix is None:\n        prefix = settings.THUMBNAIL_PREFIX\n    if subdir is None:\n        subdir = settings.THUMBNAIL_SUBDIR\n    if basedir is None:\n        basedir = settings.THUMBNAIL_BASEDIR\n    source_dir, filename = os.path.split(relative_source_path)\n    thumbs_path = os.path.join(root, basedir, source_dir, subdir)\n    if not os.path.isdir(thumbs_path):\n        return []\n    files = all_thumbnails(thumbs_path, recursive=False, prefix=prefix,\n                           subdir='')\n    return files.get(filename, [])",
    "docstring": "Return a list of dictionaries, one for each thumbnail belonging to the\n    source image.\n\n    The following list explains each key of the dictionary:\n\n      `filename`  -- absolute thumbnail path\n      `x` and `y` -- the size of the thumbnail\n      `options`   -- list of options for this thumbnail\n      `quality`   -- quality setting for this thumbnail"
  },
  {
    "code": "def get_privacy_options(user):\n    privacy_options = {}\n    for ptype in user.permissions:\n        for field in user.permissions[ptype]:\n            if ptype == \"self\":\n                privacy_options[\"{}-{}\".format(field, ptype)] = user.permissions[ptype][field]\n            else:\n                privacy_options[field] = user.permissions[ptype][field]\n    return privacy_options",
    "docstring": "Get a user's privacy options to pass as an initial value to a PrivacyOptionsForm."
  },
  {
    "code": "def all_operations(self) -> Iterator[ops.Operation]:\n        return (op for moment in self for op in moment.operations)",
    "docstring": "Iterates over the operations applied by this circuit.\n\n        Operations from earlier moments will be iterated over first. Operations\n        within a moment are iterated in the order they were given to the\n        moment's constructor."
  },
  {
    "code": "def _create_vxr(self, f, recStart, recEnd, currentVDR, priorVXR, vvrOffset):\n        vxroffset = self._write_vxr(f)\n        self._use_vxrentry(f, vxroffset, recStart, recEnd, vvrOffset)\n        if (priorVXR == 0):\n            self._update_offset_value(f, currentVDR+28, 8, vxroffset)\n        else:\n            self._update_offset_value(f, priorVXR+12, 8, vxroffset)\n        self._update_offset_value(f, currentVDR+36, 8, vxroffset)\n        return vxroffset",
    "docstring": "Create a VXR AND use a VXR\n\n        Parameters:\n            f : file\n                The open CDF file\n            recStart : int\n                The start record of this block\n            recEnd : int\n                The ending record of this block\n            currentVDR : int\n                The byte location of the variables VDR\n            priorVXR : int\n                The byte location of the previous VXR\n            vvrOffset : int\n                The byte location of ther VVR\n\n        Returns:\n            vxroffset : int\n                The byte location of the created vxr"
  },
  {
    "code": "def _make_session():\n        sess = requests.Session()\n        sess.mount('http://', requests.adapters.HTTPAdapter(max_retries=False))\n        sess.mount('https://', requests.adapters.HTTPAdapter(max_retries=False))\n        return sess",
    "docstring": "Create session object.\n\n        :rtype: requests.Session"
  },
  {
    "code": "def rcategorical(p, size=None):\n    out = flib.rcat(p, np.random.random(size=size))\n    if sum(out.shape) == 1:\n        return out.squeeze()\n    else:\n        return out",
    "docstring": "Categorical random variates."
  },
  {
    "code": "def read_metadata(self, key):\n        if getattr(getattr(self.group, 'meta', None), key, None) is not None:\n            return self.parent.select(self._get_metadata_path(key))\n        return None",
    "docstring": "return the meta data array for this key"
  },
  {
    "code": "def cmd_tracker_calpress(self, args):\n        connection = self.find_connection()\n        if not connection:\n            print(\"No antenna tracker found\")\n            return\n        connection.calibrate_pressure()",
    "docstring": "calibrate barometer on tracker"
  },
  {
    "code": "def normalize(expr):\n    children = []\n    for child in expr.children:\n        branch = normalize(child)\n        if branch is None:\n            continue\n        if type(branch) is type(expr):\n            children.extend(branch.children)\n        else:\n            children.append(branch)\n    if len(children) == 0:\n        return None\n    if len(children) == 1:\n        return children[0]\n    return type(expr)(*children, start=children[0].start,\n                      end=children[-1].end)",
    "docstring": "Pass through n-ary expressions, and eliminate empty branches.\n\n    Variadic and binary expressions recursively visit all their children.\n\n    If all children are eliminated then the parent expression is also\n    eliminated:\n\n    (& [removed] [removed]) => [removed]\n\n    If only one child is left, it is promoted to replace the parent node:\n\n    (& True) => True"
  },
  {
    "code": "def resolve(self):\n        values = {}\n        for target_name in self.target_names:\n            if self.context.is_build_needed(self.parent, target_name):\n                self.context.build_task(target_name)\n            if len(self.keyword_chain) == 0:\n                values[target_name] = self.context.tasks[target_name].value\n            else:\n                values[target_name] = reduce(\n                    lambda task, name: getattr(task, name),\n                    self.keyword_chain,\n                    self.context.tasks[target_name].task)\n        return self.function(**values)",
    "docstring": "Builds all targets of this dependency and returns the result\n           of self.function on the resulting values"
  },
  {
    "code": "def start_output (self):\n        super(CSVLogger, self).start_output()\n        row = []\n        if self.has_part(\"intro\"):\n            self.write_intro()\n            self.flush()\n        else:\n            self.write(u\"\")\n        self.queue = StringIO()\n        self.writer = csv.writer(self.queue, dialect=self.dialect,\n               delimiter=self.separator, lineterminator=self.linesep,\n               quotechar=self.quotechar)\n        for s in Columns:\n            if self.has_part(s):\n                row.append(s)\n        if row:\n            self.writerow(row)",
    "docstring": "Write checking start info as csv comment."
  },
  {
    "code": "def perform_patch(cls, operations, obj, state=None):\n        if state is None:\n            state = {}\n        for operation in operations:\n            if not cls._process_patch_operation(operation, obj=obj, state=state):\n                log.info(\n                    \"%s patching has been stopped because of unknown operation %s\",\n                    obj.__class__.__name__,\n                    operation\n                )\n                raise ValidationError(\n                    \"Failed to update %s details. Operation %s could not succeed.\" % (\n                        obj.__class__.__name__,\n                        operation\n                    )\n                )\n        return True",
    "docstring": "Performs all necessary operations by calling class methods with\n        corresponding names."
  },
  {
    "code": "def serialize_to_list(self, name, datas):\n        items = datas.get('items', None)\n        splitter = datas.get('splitter', self._DEFAULT_SPLITTER)\n        if items is None:\n            msg = (\"List reference '{}' lacks of required 'items' variable \"\n                   \"or is empty\")\n            raise SerializerError(msg.format(name))\n        else:\n            items = self.value_splitter(name, 'items', items, mode=splitter)\n        return items",
    "docstring": "Serialize given datas to a list structure.\n\n        List structure is very simple and only require a variable ``--items``\n        which is a string of values separated with an empty space. Every other\n        properties are ignored.\n\n        Arguments:\n            name (string): Name only used inside possible exception message.\n            datas (dict): Datas to serialize.\n\n        Returns:\n            list: List of serialized reference datas."
  },
  {
    "code": "def get_version_from_scm(path=None):\n    if is_git(path):\n        return 'git', get_git_version(path)\n    elif is_svn(path):\n        return 'svn', get_svn_version(path)\n    return None, None",
    "docstring": "Get the current version string of this package using SCM tool.\n\n    Parameters\n    ----------\n    path : None or string, optional\n        The SCM checkout path (default is current directory)\n\n    Returns\n    -------\n    version : string\n        The version string for this package"
  },
  {
    "code": "def make_pkh_output(value, pubkey, witness=False):\n    return _make_output(\n        value=utils.i2le_padded(value, 8),\n        output_script=make_pkh_output_script(pubkey, witness))",
    "docstring": "int, bytearray -> TxOut"
  },
  {
    "code": "def list_formatter(handler, item, value):\n    return u', '.join(str(v) for v in value)",
    "docstring": "Format list."
  },
  {
    "code": "def context(self):\n    \"Internal property that returns the stylus compiler\"\n    if self._context is None:\n      with io.open(path.join(path.abspath(path.dirname(__file__)), \"compiler.js\")) as compiler_file:\n        compiler_source = compiler_file.read()\n      self._context = self.backend.compile(compiler_source)\n    return self._context",
    "docstring": "Internal property that returns the stylus compiler"
  },
  {
    "code": "def create(self, user, obj, **kwargs):\n        follow = Follow(user=user)\n        follow.target = obj\n        follow.save()\n        return follow",
    "docstring": "Create a new follow link between a user and an object\n        of a registered model type."
  },
  {
    "code": "def _nbOperations(n):\n    if n < 2:\n        return 0\n    else:\n        n0 = (n + 2) // 3\n        n02 = n0 + n // 3\n        return 3 * (n02) + n0 + _nbOperations(n02)",
    "docstring": "Exact number of atomic operations in _radixPass."
  },
  {
    "code": "def message_convert_rx(message_rx):\n    is_extended_id = bool(message_rx.flags & IS_ID_TYPE)\n    is_remote_frame = bool(message_rx.flags & IS_REMOTE_FRAME)\n    is_error_frame = bool(message_rx.flags & IS_ERROR_FRAME)\n    return Message(timestamp=message_rx.timestamp,\n                   is_remote_frame=is_remote_frame,\n                   is_extended_id=is_extended_id,\n                   is_error_frame=is_error_frame,\n                   arbitration_id=message_rx.id,\n                   dlc=message_rx.sizeData,\n                   data=message_rx.data[:message_rx.sizeData])",
    "docstring": "convert the message from the CANAL type to pythoncan type"
  },
  {
    "code": "def bit_clone( bits ):\n    new = BitSet( bits.size )\n    new.ior( bits )\n    return new",
    "docstring": "Clone a bitset"
  },
  {
    "code": "def _GetPluginData(self):\n    return_dict = {}\n    return_dict['Versions'] = [\n        ('plaso engine', plaso.__version__),\n        ('python', sys.version)]\n    hashers_information = hashers_manager.HashersManager.GetHashersInformation()\n    parsers_information = parsers_manager.ParsersManager.GetParsersInformation()\n    plugins_information = (\n        parsers_manager.ParsersManager.GetParserPluginsInformation())\n    presets_information = parsers_manager.ParsersManager.GetPresetsInformation()\n    return_dict['Hashers'] = hashers_information\n    return_dict['Parsers'] = parsers_information\n    return_dict['Parser Plugins'] = plugins_information\n    return_dict['Parser Presets'] = presets_information\n    return return_dict",
    "docstring": "Retrieves the version and various plugin information.\n\n    Returns:\n      dict[str, list[str]]: available parsers and plugins."
  },
  {
    "code": "def read_next_line(self):\n        next_line = self.file.readline()\n        if not next_line or next_line[-1:] != '\\n':\n            self.file = None\n        else:\n            next_line = next_line[:-1]\n        expanded = next_line.expandtabs()\n        edit = urwid.Edit(\"\", expanded, allow_tab=True)\n        edit.set_edit_pos(0)\n        edit.original_text = next_line\n        self.lines.append(edit)\n        return next_line",
    "docstring": "Read another line from the file."
  },
  {
    "code": "def addr_info(addr):\n    if isinstance(addr, basestring):\n        return socket.AF_UNIX\n    if not isinstance(addr, collections.Sequence):\n        raise ValueError(\"address is not a tuple\")\n    if len(addr) < 2:\n        raise ValueError(\"cannot understand address\")\n    if not (0 <= addr[1] < 65536):\n        raise ValueError(\"cannot understand port number\")\n    ipaddr = addr[0]\n    if not ipaddr:\n        if len(addr) != 2:\n            raise ValueError(\"cannot understand address\")\n        return socket.AF_INET\n    if netaddr.valid_ipv6(ipaddr):\n        if len(addr) > 4:\n            raise ValueError(\"cannot understand address\")\n        return socket.AF_INET6\n    elif netaddr.valid_ipv4(ipaddr):\n        if len(addr) != 2:\n            raise ValueError(\"cannot understand address\")\n        return socket.AF_INET\n    raise ValueError(\"cannot understand address\")",
    "docstring": "Interprets an address in standard tuple format to determine if it\n    is valid, and, if so, which socket family it is.  Returns the\n    socket family."
  },
  {
    "code": "def run_calculation(self, atoms=None, properties=['energy'],\n                            system_changes=all_changes):\n        self.calc.calculate(self, atoms, properties, system_changes)\n        self.write_input(self.atoms, properties, system_changes)\n        if self.command is None:\n            raise RuntimeError('Please configure Remote calculator!')\n        olddir = os.getcwd()\n        errorcode=0\n        try:\n            os.chdir(self.directory)\n            output = subprocess.check_output(self.command, shell=True)\n            self.jobid=output.split()[0]\n            self.submited=True\n        except subprocess.CalledProcessError as e:\n            errorcode=e.returncode\n        finally:\n            os.chdir(olddir)\n        if errorcode:\n            raise RuntimeError('%s returned an error: %d' %\n                               (self.name, errorcode))\n        self.read_results()",
    "docstring": "Internal calculation executor. We cannot use FileIOCalculator\n        directly since we need to support remote execution.\n        \n        This calculator is different from others. \n        It prepares the directory, launches the remote process and\n        raises the exception to signal that we need to come back for results\n        when the job is finished."
  },
  {
    "code": "def _get_credentials(vcap_services, service_name=None):\n    service_name = service_name or os.environ.get('STREAMING_ANALYTICS_SERVICE_NAME', None)\n    services = vcap_services['streaming-analytics']\n    creds = None\n    for service in services:\n        if service['name'] == service_name:\n            creds = service['credentials']\n            break\n    if creds is None:\n        raise ValueError(\"Streaming Analytics service \" + str(service_name) + \" was not found in VCAP_SERVICES\")\n    return creds",
    "docstring": "Retrieves the credentials of the VCAP Service of the specified `service_name`.  If\n    `service_name` is not specified, it takes the information from STREAMING_ANALYTICS_SERVICE_NAME environment\n    variable.\n\n    Args:\n        vcap_services (dict): A dict representation of the VCAP Services information.\n        service_name (str): One of the service name stored in `vcap_services`\n\n    Returns:\n        dict: A dict representation of the credentials.\n\n    Raises:\n        ValueError:  Cannot find `service_name` in `vcap_services`"
  },
  {
    "code": "def _add_arguments(self):\n        self._parser.add_argument(\n            '-v', '--version',\n            action='store_true',\n            help=\"show program's version number and exit\")\n        self._parser.add_argument(\n            '-a', '--alias',\n            nargs='?',\n            const=get_alias(),\n            help='[custom-alias-name] prints alias for current shell')\n        self._parser.add_argument(\n            '-l', '--shell-logger',\n            action='store',\n            help='log shell output to the file')\n        self._parser.add_argument(\n            '--enable-experimental-instant-mode',\n            action='store_true',\n            help='enable experimental instant mode, use on your own risk')\n        self._parser.add_argument(\n            '-h', '--help',\n            action='store_true',\n            help='show this help message and exit')\n        self._add_conflicting_arguments()\n        self._parser.add_argument(\n            '-d', '--debug',\n            action='store_true',\n            help='enable debug output')\n        self._parser.add_argument(\n            '--force-command',\n            action='store',\n            help=SUPPRESS)\n        self._parser.add_argument(\n            'command',\n            nargs='*',\n            help='command that should be fixed')",
    "docstring": "Adds arguments to parser."
  },
  {
    "code": "def pipe(self, command, timeout=None, cwd=None):\n        if not timeout:\n            timeout = self.timeout\n        if not self.was_run:\n            self.run(block=False, cwd=cwd)\n        data = self.out\n        if timeout:\n            c = Command(command, timeout)\n        else:\n            c = Command(command)\n        c.run(block=False, cwd=cwd)\n        if data:\n            c.send(data)\n        c.block()\n        return c",
    "docstring": "Runs the current command and passes its output to the next\n        given process."
  },
  {
    "code": "def safe_json_response(method):\n    def _safe_document(document):\n        assert isinstance(document, dict), 'Error: provided document is not of DICT type: {0}' \\\n            .format(document.__class__.__name__)\n        for key, value in document.items():\n            if isinstance(value, dict):\n                document[key] = {k: str(v) for k, v in value.items()}\n            elif isinstance(value, list):\n                document[key] = [str(v) for v in value]\n            else:\n                document[key] = str(document[key])\n        return document\n    @functools.wraps(method)\n    def _wrapper(self, *args, **kwargs):\n        try:\n            document = method(self, *args, **kwargs)\n            return _safe_document(document)\n        except Exception as e:\n            return self.reply_server_error(e)\n    return _wrapper",
    "docstring": "makes sure the response' document has all leaf-fields converted to string"
  },
  {
    "code": "def DEFINE_multi_enum_class(\n    name,\n    default,\n    enum_class,\n    help,\n    flag_values=_flagvalues.FLAGS,\n    module_name=None,\n    **args):\n  DEFINE_flag(\n      _flag.MultiEnumClassFlag(name, default, help, enum_class),\n      flag_values, module_name, **args)",
    "docstring": "Registers a flag whose value can be a list of enum members.\n\n  Use the flag on the command line multiple times to place multiple\n  enum values into the list.\n\n  Args:\n    name: str, the flag name.\n    default: Union[Iterable[Enum], Iterable[Text], Enum, Text, None], the\n        default value of the flag; see\n        `DEFINE_multi`; only differences are documented here. If the value is\n        a single Enum, it is treated as a single-item list of that Enum value.\n        If it is an iterable, text values within the iterable will be converted\n        to the equivalent Enum objects.\n    enum_class: class, the Enum class with all the possible values for the flag.\n        help: str, the help message.\n    flag_values: FlagValues, the FlagValues instance with which the flag will be\n      registered. This should almost never need to be overridden.\n    module_name: A string, the name of the Python module declaring this flag. If\n      not provided, it will be computed using the stack trace of this call.\n    **args: Dictionary with extra keyword args that are passed to the Flag\n      __init__."
  },
  {
    "code": "def copychildren(self, newdoc=None, idsuffix=\"\"):\n        if idsuffix is True: idsuffix = \".copy.\" + \"%08x\" % random.getrandbits(32)\n        for c in self:\n            if isinstance(c, AbstractElement):\n                yield c.copy(newdoc,idsuffix)",
    "docstring": "Generator creating a deep copy of the children of this element.\n\n        Invokes :meth:`copy` on all children, parameters are the same."
  },
  {
    "code": "def _learn(\n             permanences, rng,\n             activeCells, activeInput, growthCandidateInput,\n             sampleSize, initialPermanence, permanenceIncrement,\n             permanenceDecrement, connectedPermanence):\n    permanences.incrementNonZerosOnOuter(\n      activeCells, activeInput, permanenceIncrement)\n    permanences.incrementNonZerosOnRowsExcludingCols(\n      activeCells, activeInput, -permanenceDecrement)\n    permanences.clipRowsBelowAndAbove(\n      activeCells, 0.0, 1.0)\n    if sampleSize == -1:\n      permanences.setZerosOnOuter(\n        activeCells, activeInput, initialPermanence)\n    else:\n      existingSynapseCounts = permanences.nNonZerosPerRowOnCols(\n        activeCells, activeInput)\n      maxNewByCell = numpy.empty(len(activeCells), dtype=\"int32\")\n      numpy.subtract(sampleSize, existingSynapseCounts, out=maxNewByCell)\n      permanences.setRandomZerosOnOuter(\n        activeCells, growthCandidateInput, maxNewByCell, initialPermanence, rng)",
    "docstring": "For each active cell, reinforce active synapses, punish inactive synapses,\n    and grow new synapses to a subset of the active input bits that the cell\n    isn't already connected to.\n\n    Parameters:\n    ----------------------------\n    @param  permanences (SparseMatrix)\n            Matrix of permanences, with cells as rows and inputs as columns\n\n    @param  rng (Random)\n            Random number generator\n\n    @param  activeCells (sorted sequence)\n            Sorted list of the cells that are learning\n\n    @param  activeInput (sorted sequence)\n            Sorted list of active bits in the input\n\n    @param  growthCandidateInput (sorted sequence)\n            Sorted list of active bits in the input that the activeCells may\n            grow new synapses to\n\n    For remaining parameters, see the __init__ docstring."
  },
  {
    "code": "def MeterOffset((lat1, lon1), (lat2, lon2)):\n    \"Return offset in meters of second arg from first.\"\n    dx = EarthDistance((lat1, lon1), (lat1, lon2))\n    dy = EarthDistance((lat1, lon1), (lat2, lon1))\n    if lat1 < lat2: dy *= -1\n    if lon1 < lon2: dx *= -1\n    return (dx, dy)",
    "docstring": "Return offset in meters of second arg from first."
  },
  {
    "code": "def _get_more(self):\n        if not self.alive:\n            raise pymongo.errors.InvalidOperation(\n                \"Can't call get_more() on a MotorCursor that has been\"\n                \" exhausted or killed.\")\n        self.started = True\n        return self._refresh()",
    "docstring": "Initial query or getMore. Returns a Future."
  },
  {
    "code": "def _parse_ntthal(ntthal_output):\n    parsed_vals = re.search(_ntthal_re, ntthal_output)\n    return THERMORESULT(\n        True,\n        float(parsed_vals.group(1)),\n        float(parsed_vals.group(2)),\n        float(parsed_vals.group(3)),\n        float(parsed_vals.group(4))\n    ) if parsed_vals else NULLTHERMORESULT",
    "docstring": "Helper method that uses regex to parse ntthal output."
  },
  {
    "code": "def index(self, value, start=None, stop=None):\n        return self.__alias__.index(value, start, stop)",
    "docstring": "Return first index of value."
  },
  {
    "code": "def _process_maybe_work(self, yes_work, maybe_work, work_dir,\n                            yn_results_path, stats):\n        if maybe_work == yes_work:\n            return stats\n        self._logger.info(\n            'Processing \"maybe\" work {} against \"yes\" work {}.'.format(\n                maybe_work, yes_work))\n        for siglum in self._corpus.get_sigla(maybe_work):\n            witness = (maybe_work, siglum)\n            stats[COMMON][witness] = 0\n            stats[SHARED][witness] = 0\n            stats[UNIQUE][witness] = 100\n        works = [yes_work, maybe_work]\n        works.sort()\n        ym_results_path = os.path.join(\n            self._ym_intersects_dir, '{}_intersect_{}.csv'.format(*works))\n        stats = self._process_intersection(yes_work, maybe_work, work_dir,\n                                           ym_results_path, stats)\n        stats = self._process_diff(yes_work, maybe_work, work_dir,\n                                   ym_results_path, yn_results_path, stats)\n        return stats",
    "docstring": "Returns statistics of how `yes_work` compares with `maybe_work`.\n\n        :param yes_work: name of work for which stats are collected\n        :type yes_work: `str`\n        :param maybe_work: name of work being compared with `yes_work`\n        :type maybe_work: `str`\n        :param work_dir: directory where generated files are saved\n        :type work_dir: `str`\n        :param yn_results_path: path to results intersecting\n                                `yes_work` with \"no\" works\n        :type yn_results_path: `str`\n        :param stats: data structure to hold statistical data of the\n                      comparison\n        :type stats: `dict`\n        :rtype: `dict`"
  },
  {
    "code": "def iterfields(klass):\n    is_field = lambda x: isinstance(x, TypedField)\n    for name, field in inspect.getmembers(klass, predicate=is_field):\n        yield name, field",
    "docstring": "Iterate over the input class members and yield its TypedFields.\n\n    Args:\n        klass: A class (usually an Entity subclass).\n\n    Yields:\n        (class attribute name, TypedField instance) tuples."
  },
  {
    "code": "async def status(cls):\n        rqst = Request(cls.session, 'GET', '/manager/status')\n        rqst.set_json({\n            'status': 'running',\n        })\n        async with rqst.fetch() as resp:\n            return await resp.json()",
    "docstring": "Returns the current status of the configured API server."
  },
  {
    "code": "def insertAdjacentHTML(self, position: str, html: str) -> None:\n        df = self._parse_html(html)\n        pos = position.lower()\n        if pos == 'beforebegin':\n            self.before(df)\n        elif pos == 'afterbegin':\n            self.prepend(df)\n        elif pos == 'beforeend':\n            self.append(df)\n        elif pos == 'afterend':\n            self.after(df)\n        else:\n            raise ValueError(\n                'The value provided ({}) is not one of \"beforeBegin\", '\n                '\"afterBegin\", \"beforeEnd\", or \"afterEnd\".'.format(position)\n            )",
    "docstring": "Parse ``html`` to DOM and insert to ``position``.\n\n        ``position`` is a case-insensive string, and must be one of\n        \"beforeBegin\", \"afterBegin\", \"beforeEnd\", or \"afterEnd\"."
  },
  {
    "code": "def powerset(iterable, *, reverse=False):\n    lst = list(iterable)\n    if reverse:\n        rng = range(len(lst), -1, -1)\n    else:\n        rng = range(len(lst) + 1)\n    return chain.from_iterable(combinations(lst, r) for r in rng)",
    "docstring": "Return the powerset.\n\n    Arguments\n    ---------\n    iterable : iterable\n    reverse  : boolean\n               Indicates whether the powerset should be returned descending by\n               size\n\n    Returns\n    -------\n    A generator producing each element of the powerset."
  },
  {
    "code": "def post(self, text=None, attachments=None, source_guid=None):\n        return self.messages.create(text=text, attachments=attachments,\n                                    source_guid=source_guid)",
    "docstring": "Post a direct message to the user.\n\n        :param str text: the message content\n        :param attachments: message attachments\n        :param str source_guid: a client-side unique ID for the message\n        :return: the message sent\n        :rtype: :class:`~groupy.api.messages.DirectMessage`"
  },
  {
    "code": "def filename_for(self, subpath):\n        try:\n            filename = self.readme_for(subpath)\n            return os.path.relpath(filename, self.root_directory)\n        except ReadmeNotFoundError:\n            return None",
    "docstring": "Returns the relative filename for the specified subpath, or the\n        root filename if subpath is None.\n\n        Raises werkzeug.exceptions.NotFound if the resulting path\n        would fall out of the root directory."
  },
  {
    "code": "def photos(self, query, page=1, per_page=10):\n        url = \"/search/photos\"\n        data = self._search(url, query, page=page, per_page=per_page)\n        data[\"results\"] = PhotoModel.parse_list(data.get(\"results\"))\n        return data",
    "docstring": "Get a single page of photo results for a query.\n\n        :param query [string]: Search terms.\n        :param page [integer]: Page number to retrieve. (Optional; default: 1)\n        :param per_page [integer]: Number of items per page. (Optional; default: 10)\n        :return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [Photo]}"
  },
  {
    "code": "def needs_gcloud(self):\n        gcloud_default_path = ['google-cloud-sdk', 'bin']\n        if platform.system() != \"Windows\":\n            gcloud_default_path = os.path.join(os.path.expanduser('~'),\n                                               *gcloud_default_path)\n        else:\n            gcloud_default_path = os.path.join(os.environ['LOCALAPPDATA'],\n                                               'Google', 'Cloud SDK',\n                                               *gcloud_default_path)\n        return not os.getenv('SERVER_SOFTWARE',\n                             '').startswith('Google App Engine/') \\\n               and gcloud_default_path not in os.environ[\"PATH\"].split(os.pathsep) \\\n               and which('gcloud') is None",
    "docstring": "Returns true if gcloud is unavailable and needed for\n        authentication."
  },
  {
    "code": "def _one_iteration(self, F, Ybus, V, Vm, Va, pv, pq, pvpq):\n        J = self._build_jacobian(Ybus, V, pv, pq, pvpq)\n        dx = -1 * spsolve(J, F)\n        npv = len(pv)\n        npq = len(pq)\n        if npv > 0:\n            Va[pv] = Va[pv] + dx[range(npv)]\n        if npq > 0:\n            Va[pq] = Va[pq] + dx[range(npv, npv + npq)]\n            Vm[pq] = Vm[pq] + dx[range(npv + npq, npv + npq + npq)]\n        V = Vm * exp(1j * Va)\n        Vm = abs(V)\n        Va = angle(V)\n        return V, Vm, Va",
    "docstring": "Performs one Newton iteration."
  },
  {
    "code": "def load_rc(self, path=None, system=False):\n        if os.path.isfile(self.user_rc_path) and not system:\n            path = self.user_rc_path\n        elif os.path.isfile(self.sys_rc_path):\n            path = self.sys_rc_path\n        if not path or not os.path.isfile(path):\n            return {}\n        with open(path) as f:\n            return yaml.load(f) or {}",
    "docstring": "Load the conda configuration file.\n\n        If both user and system configuration exists, user will be used."
  },
  {
    "code": "def get_current_value(self, use_cached=False):\n        current_value = self._get_stream_metadata(use_cached).get(\"currentValue\")\n        if current_value:\n            return DataPoint.from_json(self, current_value)\n        else:\n            return None",
    "docstring": "Return the most recent DataPoint value written to a stream\n\n        The current value is the last recorded data point for this stream.\n\n        :param bool use_cached: If False, the function will always request the latest from Device Cloud.\n            If True, the device will not make a request if it already has cached data.\n        :raises devicecloud.DeviceCloudHttpException: in the case of an unexpected http error\n        :raises devicecloud.streams.NoSuchStreamException: if this stream has not yet been created\n        :return: The most recent value written to this stream (or None if nothing has been written)\n        :rtype: :class:`~DataPoint` or None"
  },
  {
    "code": "def eigenvalues_samples(self):\n        r\n        res = np.empty((self.nsamples, self.nstates), dtype=config.dtype)\n        for i in range(self.nsamples):\n            res[i, :] = self._sampled_hmms[i].eigenvalues\n        return res",
    "docstring": "r\"\"\" Samples of the eigenvalues"
  },
  {
    "code": "def handle(self, dict):\n        ex_res = self.extract(dict['url'])\n        key = \"{sid}:{dom}.{suf}:queue\".format(\n            sid=dict['spiderid'],\n            dom=ex_res.domain,\n            suf=ex_res.suffix)\n        val = ujson.dumps(dict)\n        self.redis_conn.zadd(key, val, -dict['priority'])\n        if 'expires' in dict and dict['expires'] != 0:\n            key = \"timeout:{sid}:{appid}:{crawlid}\".format(\n                            sid=dict['spiderid'],\n                            appid=dict['appid'],\n                            crawlid=dict['crawlid'])\n            self.redis_conn.set(key, dict['expires'])\n        dict['parsed'] = True\n        dict['valid'] = True\n        self.logger.info('Added crawl to Redis', extra=dict)",
    "docstring": "Processes a vaild crawl request\n\n        @param dict: a valid dictionary object"
  },
  {
    "code": "def parse(self, body):\n        self._parse_top_level(body)\n        self._parse_resource(body['data'])\n        resource = body['data']\n        if 'attributes' in resource:\n            self._parse_attributes(resource['attributes'])\n        if 'relationships' in resource:\n            self._parse_relationships(resource['relationships'])",
    "docstring": "Invoke the JSON API spec compliant parser\n\n        Order is important. Start from the request body root key\n        & work your way down so exception handling is easier to\n        follow.\n\n        :return:\n            the parsed & vetted request body"
  },
  {
    "code": "def remove_all_labels(stdout=None):\n    if not stdout:\n        stdout = sys.stdout\n    stdout.write(\"Droping constraints...\\n\")\n    drop_constraints(quiet=False, stdout=stdout)\n    stdout.write('Droping indexes...\\n')\n    drop_indexes(quiet=False, stdout=stdout)",
    "docstring": "Calls functions for dropping constraints and indexes.\n\n    :param stdout: output stream\n    :return: None"
  },
  {
    "code": "def _tab(content):\n    response = _data_frame(content).to_csv(index=False,sep='\\t')\n    return response",
    "docstring": "Helper funcation that converts text-based get response\n    to tab separated values for additional manipulation."
  },
  {
    "code": "def detect_format(filename):\n    filename = Path(filename)\n    if filename.suffix == '.csv':\n        recformat = 'csv'\n    elif filename.suffix == '.sfp':\n        recformat = 'sfp'\n    else:\n        recformat = 'unknown'\n    return recformat",
    "docstring": "Detect file format of the channels based on extension.\n\n    Parameters\n    ----------\n    filename : Path\n        name of the filename\n\n    Returns\n    -------\n    str\n        file format"
  },
  {
    "code": "def predict(self, y_prob):\n        y_pred = np.floor(y_prob[:, 1] + (1 - self.threshold_))\n        return y_pred",
    "docstring": "Calculate the prediction using the ThresholdingOptimization.\n\n        Parameters\n        ----------\n        y_prob : array-like of shape = [n_samples, 2]\n            Predicted probabilities.\n\n        Returns\n        -------\n        y_pred : array-like of shape = [n_samples]\n            Predicted class"
  },
  {
    "code": "def _getitem_with_mask(self, key, fill_value=dtypes.NA):\n        if fill_value is dtypes.NA:\n            fill_value = dtypes.get_fill_value(self.dtype)\n        dims, indexer, new_order = self._broadcast_indexes(key)\n        if self.size:\n            if isinstance(self._data, dask_array_type):\n                actual_indexer = indexing.posify_mask_indexer(indexer)\n            else:\n                actual_indexer = indexer\n            data = as_indexable(self._data)[actual_indexer]\n            chunks_hint = getattr(data, 'chunks', None)\n            mask = indexing.create_mask(indexer, self.shape, chunks_hint)\n            data = duck_array_ops.where(mask, fill_value, data)\n        else:\n            mask = indexing.create_mask(indexer, self.shape)\n            data = np.broadcast_to(fill_value, getattr(mask, 'shape', ()))\n        if new_order:\n            data = np.moveaxis(data, range(len(new_order)), new_order)\n        return self._finalize_indexing_result(dims, data)",
    "docstring": "Index this Variable with -1 remapped to fill_value."
  },
  {
    "code": "def exposed_method(name=None, private=False, is_coroutine=True, requires_handler_reference=False):\n    def wrapper(func):\n        if name:\n            method_name = name\n        else:\n            method_name = func.__name__\n        if not METHOD_NAME_REGEX.match(method_name):\n            raise ValueError(\"Invalid method name: '{}'\".format(method_name))\n        @functools.wraps(func)\n        def real_wrapper(*args, **kwargs):\n            return func(*args, **kwargs)\n        if private:\n            setattr(real_wrapper, \"_exposed_private\", True)\n        else:\n            setattr(real_wrapper, \"_exposed_public\", True)\n        if is_coroutine:\n            real_wrapper.__gemstone_is_coroutine = True\n            real_wrapper = tornado.gen.coroutine(real_wrapper)\n            setattr(real_wrapper, \"_is_coroutine\", True)\n        if requires_handler_reference:\n            setattr(real_wrapper, \"_req_h_ref\", True)\n        setattr(real_wrapper, \"_exposed_name\", method_name)\n        return real_wrapper\n    return wrapper",
    "docstring": "Marks a method as exposed via JSON RPC.\n\n    :param name: the name of the exposed method. Must contains only letters, digits, dots and underscores.\n                 If not present or is set explicitly to ``None``, this parameter will default to the name\n                 of the exposed method.\n                 If two methods with the same name are exposed, a ``ValueError`` is raised.\n    :type name: str\n    :param private: Flag that specifies if the exposed method is private.\n    :type private: bool\n    :param is_coroutine: Flag that specifies if the method is a Tornado coroutine. If True, it will be wrapped\n                         with the :py:func:`tornado.gen.coroutine` decorator.\n    :type is_coroutine: bool\n    :param requires_handler_reference: If ``True``, the handler method will receive as the first\n                                       parameter a ``handler`` argument with the Tornado\n                                       request handler for the current request. This request handler\n                                       can be further used to extract various information from the\n                                       request, such as headers, cookies, etc.\n    :type requires_handler_reference: bool\n\n    .. versionadded:: 0.9.0"
  },
  {
    "code": "def _run_cmplx(fn, image):\n    original_format = image.format\n    if image.format != 'complex' and image.format != 'dpcomplex':\n        if image.bands % 2 != 0:\n            raise Error('not an even number of bands')\n        if image.format != 'float' and image.format != 'double':\n            image = image.cast('float')\n        if image.format == 'double':\n            new_format = 'dpcomplex'\n        else:\n            new_format = 'complex'\n        image = image.copy(format=new_format, bands=image.bands / 2)\n    image = fn(image)\n    if original_format != 'complex' and original_format != 'dpcomplex':\n        if image.format == 'dpcomplex':\n            new_format = 'double'\n        else:\n            new_format = 'float'\n        image = image.copy(format=new_format, bands=image.bands * 2)\n    return image",
    "docstring": "Run a complex function on a non-complex image.\n\n    The image needs to be complex, or have an even number of bands. The input\n    can be int, the output is always float or double."
  },
  {
    "code": "def find_by_id(self, organization_export, params={}, **options): \n        path = \"/organization_exports/%s\" % (organization_export)\n        return self.client.get(path, params, **options)",
    "docstring": "Returns details of a previously-requested Organization export.\n\n        Parameters\n        ----------\n        organization_export : {Id} Globally unique identifier for the Organization export.\n        [params] : {Object} Parameters for the request"
  },
  {
    "code": "def read(cls, source, format=None, coalesce=False, **kwargs):\n        def combiner(listofseglists):\n            out = cls(seg for seglist in listofseglists for seg in seglist)\n            if coalesce:\n                return out.coalesce()\n            return out\n        return io_read_multi(combiner, cls, source, format=format, **kwargs)",
    "docstring": "Read segments from file into a `SegmentList`\n\n        Parameters\n        ----------\n        filename : `str`\n            path of file to read\n\n        format : `str`, optional\n            source format identifier. If not given, the format will be\n            detected if possible. See below for list of acceptable\n            formats.\n\n        coalesce : `bool`, optional\n            if `True` coalesce the segment list before returning,\n            otherwise return exactly as contained in file(s).\n\n        **kwargs\n            other keyword arguments depend on the format, see the online\n            documentation for details (:ref:`gwpy-segments-io`)\n\n        Returns\n        -------\n        segmentlist : `SegmentList`\n            `SegmentList` active and known segments read from file.\n\n        Notes\n        -----"
  },
  {
    "code": "def complete(self, stream):\n            assert not self.is_complete()\n            self._marker.addInputPort(outputPort=stream.oport)\n            self.stream.oport.schema = stream.oport.schema\n            self._pending_schema._set(self.stream.oport.schema)\n            stream.oport.operator._start_op = True",
    "docstring": "Complete the pending stream.\n\n            Any connections made to :py:attr:`stream` are connected to `stream` once\n            this method returns.\n\n            Args:\n                stream(Stream): Stream that completes the connection."
  },
  {
    "code": "def describe_volumes(self, *volume_ids):\n        volumeset = {}\n        for pos, volume_id in enumerate(volume_ids):\n            volumeset[\"VolumeId.%d\" % (pos + 1)] = volume_id\n        query = self.query_factory(\n            action=\"DescribeVolumes\", creds=self.creds, endpoint=self.endpoint,\n            other_params=volumeset)\n        d = query.submit()\n        return d.addCallback(self.parser.describe_volumes)",
    "docstring": "Describe available volumes."
  },
  {
    "code": "def _ip_string_from_prefix(self, prefixlen=None):\n        if not prefixlen:\n            prefixlen = self._prefixlen\n        return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))",
    "docstring": "Turn a prefix length into a dotted decimal string.\n\n        Args:\n            prefixlen: An integer, the netmask prefix length.\n\n        Returns:\n            A string, the dotted decimal netmask string."
  },
  {
    "code": "def del_object_from_parent(self):\n        if self.parent:\n            self.parent.objects.pop(self.ref)",
    "docstring": "Delete object from parent object."
  },
  {
    "code": "def clean_fail(func):\n    def func_wrapper(*args, **kwargs):\n        try:\n            return func(*args, **kwargs)\n        except botocore.exceptions.ClientError as e:\n            print(str(e), file=sys.stderr)\n            sys.exit(1)\n    return func_wrapper",
    "docstring": "A decorator to cleanly exit on a failed call to AWS.\n    catch a `botocore.exceptions.ClientError` raised from an action.\n    This sort of error is raised if you are targeting a region that\n    isn't set up (see, `credstash setup`."
  },
  {
    "code": "def _format_summary_node(self, task_class):\n        modulename = task_class.__module__\n        classname = task_class.__name__\n        nodes = []\n        nodes.append(\n            self._format_class_nodes(task_class))\n        nodes.append(\n            self._format_config_nodes(modulename, classname)\n        )\n        methods = ('run', 'runDataRef')\n        for method in methods:\n            if hasattr(task_class, method):\n                method_obj = getattr(task_class, method)\n                nodes.append(\n                    self._format_method_nodes(method_obj,\n                                              modulename,\n                                              classname))\n        return nodes",
    "docstring": "Format a section node containg a summary of a Task class's key APIs."
  },
  {
    "code": "def data_structure_builder(func):\n    @wraps(func)\n    def ds_builder_wrapper(function, *args, **kwargs):\n        try:\n            function = DSBuilder(function)\n        except NoBuilder:\n            pass\n        return func(function, *args, **kwargs)\n    return ds_builder_wrapper",
    "docstring": "Decorator to handle automatic data structure creation for pipe-utils."
  },
  {
    "code": "def _create_sot_file(self):\n        try:\n            self._delete_file(filename=\"sot_file\")\n        except Exception:\n            pass\n        commands = [\n            \"terminal dont-ask\",\n            \"checkpoint file sot_file\",\n            \"no terminal dont-ask\",\n        ]\n        self._send_command_list(commands)",
    "docstring": "Create Source of Truth file to compare."
  },
  {
    "code": "def get_doctype(self, index, name):\n        if index not in self.indices:\n            self.get_all_indices()\n        return self.indices.get(index, {}).get(name, None)",
    "docstring": "Returns a doctype given an index and a name"
  },
  {
    "code": "def WriteUInt160(self, value):\n        if type(value) is UInt160:\n            value.Serialize(self)\n        else:\n            raise Exception(\"value must be UInt160 instance \")",
    "docstring": "Write a UInt160 type to the stream.\n\n        Args:\n            value (UInt160):\n\n        Raises:\n            Exception: when `value` is not of neocore.UInt160 type."
  },
  {
    "code": "def _get_model_metadata(model_class, metadata, version=None):\n    from turicreate import __version__\n    info = {\n        'turicreate_version': __version__,\n        'type': model_class,\n    }\n    if version is not None:\n        info['version'] = str(version)\n    info.update(metadata)\n    return info",
    "docstring": "Returns user-defined metadata, making sure information all models should \n    have is also available, as a dictionary"
  },
  {
    "code": "def get_bbox_list(self, crs=None, buffer=None, reduce_bbox_sizes=None):\n        bbox_list = self.bbox_list\n        if buffer:\n            bbox_list = [bbox.buffer(buffer) for bbox in bbox_list]\n        if reduce_bbox_sizes is None:\n            reduce_bbox_sizes = self.reduce_bbox_sizes\n        if reduce_bbox_sizes:\n            bbox_list = self._reduce_sizes(bbox_list)\n        if crs:\n            return [bbox.transform(crs) for bbox in bbox_list]\n        return bbox_list",
    "docstring": "Returns a list of bounding boxes that are the result of the split\n\n        :param crs: Coordinate reference system in which the bounding boxes should be returned. If None the CRS will\n                    be the default CRS of the splitter.\n        :type crs: CRS or None\n        :param buffer: A percentage of each BBox size increase. This will cause neighbouring bounding boxes to overlap.\n        :type buffer: float or None\n        :param reduce_bbox_sizes: If `True` it will reduce the sizes of bounding boxes so that they will tightly\n            fit the given geometry in `shape_list`. This overrides the same parameter from constructor\n        :type reduce_bbox_sizes: bool\n        :return: List of bounding boxes\n        :rtype: list(BBox)"
  },
  {
    "code": "async def popHiveKey(self, path):\n        perm = ('hive:pop',) + path\n        self.user.allowed(perm)\n        return await self.cell.hive.pop(path)",
    "docstring": "Remove and return the value of a key in the cell default hive"
  },
  {
    "code": "async def start_server_in_loop(runner, hostname, port, agent):\n    await runner.setup()\n    agent.web.server = aioweb.TCPSite(runner, hostname, port)\n    await agent.web.server.start()\n    logger.info(f\"Serving on http://{hostname}:{port}/\")",
    "docstring": "Listens to http requests and sends them to the webapp.\n\n    Args:\n        runner: AppRunner to process the http requests\n        hostname: host name to listen from.\n        port: port to listen from.\n        agent: agent that owns the web app."
  },
  {
    "code": "def scatter(self, x, y, xerr=[], yerr=[], mark='o', markstyle=None):\n        self.plot(x, y, xerr=xerr, yerr=yerr, mark=mark, linestyle=None,\n                  markstyle=markstyle)",
    "docstring": "Plot a series of points.\n\n        Plot a series of points (marks) that are not connected by a\n        line. Shortcut for plot with linestyle=None.\n\n        :param x: array containing x-values.\n        :param y: array containing y-values.\n        :param xerr: array containing errors on the x-values.\n        :param yerr: array containing errors on the y-values.\n        :param mark: the symbol used to mark the data points. May be\n            any plot mark accepted by TikZ (e.g. ``*, x, +, o, square,\n            triangle``).\n        :param markstyle: the style of the plot marks (e.g. 'mark\n            size=.75pt')\n\n        Example::\n\n            >>> plot = artist.Plot()\n            >>> x = np.random.normal(size=20)\n            >>> y = np.random.normal(size=20)\n            >>> plot.scatter(x, y, mark='*')"
  },
  {
    "code": "def get_language(self):\n        if 'lang' in self.request.GET:\n            lang = self.request.GET['lang'].lower()\n            if lang in settings.LANGUAGE_URL_MAP:\n                return settings.LANGUAGE_URL_MAP[lang]\n        if self.request.META.get('HTTP_ACCEPT_LANGUAGE'):\n            best = self.get_best_language(\n                self.request.META['HTTP_ACCEPT_LANGUAGE'])\n            if best:\n                return best\n        return settings.LANGUAGE_CODE",
    "docstring": "Return a locale code we support on the site using the\n        user's Accept-Language header to determine which is best. This\n        mostly follows the RFCs but read bug 439568 for details."
  },
  {
    "code": "def by_zipcode(self,\n                   zipcode,\n                   zipcode_type=None,\n                   zero_padding=True):\n        if zero_padding:\n            zipcode = str(zipcode).zfill(5)\n        else:\n            zipcode = str(zipcode)\n        res = self.query(\n            zipcode=zipcode,\n            sort_by=None,\n            returns=1,\n            zipcode_type=zipcode_type,\n        )\n        if len(res):\n            return res[0]\n        else:\n            return self.zip_klass()",
    "docstring": "Search zipcode by exact 5 digits zipcode. No zero padding is needed.\n\n        :param zipcode: int or str, the zipcode will be automatically\n            zero padding to 5 digits.\n        :param zipcode_type: str or :class`~uszipcode.model.ZipcodeType` attribute.\n            by default, it returns any zipcode type.\n        :param zero_padding: bool, toggle on and off automatic zero padding."
  },
  {
    "code": "def keys_values(self):\n        keys_values = []\n        for value in self.keys.values():\n            if isinstance(value, list):\n                keys_values += value\n            elif isinstance(value, basestring) and not value.startswith('-'):\n                keys_values.append(value)\n            elif isinstance(value, int) and value >= 0:\n                keys_values.append(str(value))\n        return keys_values",
    "docstring": "Key values might be a list or not, always return a list."
  },
  {
    "code": "def update_pricing(kwargs=None, call=None):\n    url = 'https://cloudpricingcalculator.appspot.com/static/data/pricelist.json'\n    price_json = salt.utils.http.query(url, decode=True, decode_type='json')\n    outfile = os.path.join(\n        __opts__['cachedir'], 'gce-pricing.p'\n    )\n    with salt.utils.files.fopen(outfile, 'w') as fho:\n        salt.utils.msgpack.dump(price_json['dict'], fho)\n    return True",
    "docstring": "Download most recent pricing information from GCE and save locally\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt-cloud -f update_pricing my-gce-config\n\n    .. versionadded:: 2015.8.0"
  },
  {
    "code": "def _check_structure(self):\n        unused_variables = set()\n        unused_operators = set()\n        for variable in self.unordered_variable_iterator():\n            unused_variables.add(variable.full_name)\n        for operator in self.unordered_operator_iterator():\n            unused_operators.add(operator.full_name)\n        for operator in self.unordered_operator_iterator():\n            for variable in operator.inputs:\n                unused_variables.discard(variable.full_name)\n                unused_operators.discard(operator.full_name)\n            for variable in operator.outputs:\n                unused_variables.discard(variable.full_name)\n                unused_operators.discard(operator.full_name)\n        if len(unused_variables) > 0:\n            raise RuntimeError('Isolated variables exist: %s' % unused_variables)\n        if len(unused_operators) > 0:\n            raise RuntimeError('Isolated operators exist: %s' % unused_operators)",
    "docstring": "This function applies some rules to check if the parsed model is proper. Currently, it only checks if isolated\n        variable and isolated operator exists."
  },
  {
    "code": "def form_invalid(self, form):\n        messages.error(self.request, form.errors[NON_FIELD_ERRORS])\n        return redirect(\n            reverse(\n                'forum_conversation:topic',\n                kwargs={\n                    'forum_slug': self.object.topic.forum.slug,\n                    'forum_pk': self.object.topic.forum.pk,\n                    'slug': self.object.topic.slug,\n                    'pk': self.object.topic.pk\n                },\n            ),\n        )",
    "docstring": "Handles an invalid form."
  },
  {
    "code": "def process_md5(md5_output, pattern=r\"=\\s+(\\S+)\"):\n        match = re.search(pattern, md5_output)\n        if match:\n            return match.group(1)\n        else:\n            raise ValueError(\"Invalid output from MD5 command: {}\".format(md5_output))",
    "docstring": "Process the string to retrieve the MD5 hash\n\n        Output from Cisco IOS (ASA is similar)\n        .MD5 of flash:file_name Done!\n        verify /md5 (flash:file_name) = 410db2a7015eaa42b1fe71f1bf3d59a2"
  },
  {
    "code": "def filter_pyfqn(cls, value, relative_to=0):\n        def collect_packages(element, packages):\n            parent = element.eContainer()\n            if parent:\n                collect_packages(parent, packages)\n            packages.append(element.name)\n        packages = []\n        collect_packages(value, packages)\n        if relative_to < 0 or relative_to > len(packages):\n            raise ValueError('relative_to not in range of number of packages')\n        fqn = '.'.join(packages[relative_to:])\n        if relative_to:\n            fqn = '.' + fqn\n        return cls.module_path_map.get(fqn, fqn)",
    "docstring": "Returns Python form of fully qualified name.\n\n        Args:\n            relative_to: If greater 0, the returned path is relative to the first n directories."
  },
  {
    "code": "def get_value(self, spec, row):\n        column = spec.get('column')\n        default = spec.get('default')\n        if column is None:\n            if default is not None:\n                return self.convert_type(default, spec)\n            return\n        value = row.get(column)\n        if is_empty(value):\n            if default is not None:\n                return self.convert_type(default, spec)\n            return None\n        return self.convert_type(value, spec)",
    "docstring": "Returns the value or a dict with a 'value' entry plus extra fields."
  },
  {
    "code": "def install_new_pipeline():\n    def new_create_pipeline(context, *args, **kwargs):\n        result = old_create_pipeline(context, *args, **kwargs)\n        result.insert(1, DAAPObjectTransformer(context))\n        return result\n    old_create_pipeline = Pipeline.create_pipeline\n    Pipeline.create_pipeline = new_create_pipeline",
    "docstring": "Install above transformer into the existing pipeline creator."
  },
  {
    "code": "def update_momentum_by_name(self, name, **kwargs):\n        momentum = self.pop_momentum_by_name(name)\n        velocity, since, until = momentum[:3]\n        velocity = kwargs.get('velocity', velocity)\n        since = kwargs.get('since', since)\n        until = kwargs.get('until', until)\n        return self.add_momentum(velocity, since, until, name)",
    "docstring": "Updates a momentum by the given name.\n\n        :param name: the momentum name.\n        :param velocity: (keyword-only) a new value for `velocity`.\n        :param since: (keyword-only) a new value for `since`.\n        :param until: (keyword-only) a new value for `until`.\n\n        :returns: a momentum updated.\n\n        :raises TypeError: `name` is ``None``.\n        :raises KeyError: failed to find a momentum named `name`."
  },
  {
    "code": "def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):\n        ns = self.user_ns.copy()\n        try:\n            frame = sys._getframe(depth + 1)\n        except ValueError:\n            pass\n        else:\n            ns.update(frame.f_locals)\n        try:\n            cmd = formatter.vformat(cmd, args=[], kwargs=ns)\n        except Exception:\n            pass\n        return cmd",
    "docstring": "Expand python variables in a string.\n\n        The depth argument indicates how many frames above the caller should\n        be walked to look for the local namespace where to expand variables.\n\n        The global namespace for expansion is always the user's interactive\n        namespace."
  },
  {
    "code": "def revoke_membership(self, username):\n        url = self._build_url('memberships', username, base_url=self._api)\n        return self._boolean(self._delete(url), 204, 404)",
    "docstring": "Revoke this user's team membership.\n\n        :param str username: (required), name of the team member\n        :returns: bool"
  },
  {
    "code": "def change_group(self, name, group):\n\t\tm1 = OmapiMessage.open(b\"host\")\n\t\tm1.update_object(dict(name=name))\n\t\tr1 = self.query_server(m1)\n\t\tif r1.opcode != OMAPI_OP_UPDATE:\n\t\t\traise OmapiError(\"opening host %s failed\" % name)\n\t\tm2 = OmapiMessage.update(r1.handle)\n\t\tm2.update_object(dict(group=group))\n\t\tr2 = self.query_server(m2)\n\t\tif r2.opcode != OMAPI_OP_UPDATE:\n\t\t\traise OmapiError(\"changing group of host %s to %s failed\" % (name, group))",
    "docstring": "Change the group of a host given the name of the host.\n\t\t@type name: str\n\t\t@type group: str"
  },
  {
    "code": "def get_xml(self, fp, format=FORMAT_NATIVE):\n        r = self._client.request('GET', getattr(self, format), stream=True)\n        filename = stream.stream_response_to_file(r, path=fp)\n        return filename",
    "docstring": "Returns the XML metadata for this source, converted to the requested format.\n        Converted metadata may not contain all the same information as the native format.\n\n        :param file fp: A path, or an open file-like object which the content should be written to.\n        :param str format: desired format for the output. This should be one of the available\n            formats from :py:meth:`.get_formats`, or :py:attr:`.FORMAT_NATIVE` for the native format.\n\n        If you pass this function an open file-like object as the fp parameter, the function will\n        not close that file for you."
  },
  {
    "code": "def append_use_flags(atom, uses=None, overwrite=False):\n    if not uses:\n        uses = portage.dep.dep_getusedeps(atom)\n    if not uses:\n        return\n    atom = atom[:atom.rfind('[')]\n    append_to_package_conf('use', atom=atom, flags=uses, overwrite=overwrite)",
    "docstring": "Append a list of use flags for a given package or DEPEND atom\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' portage_config.append_use_flags \"app-admin/salt[ldap, -libvirt]\"\n        salt '*' portage_config.append_use_flags \">=app-admin/salt-0.14.1\" \"['ldap', '-libvirt']\""
  },
  {
    "code": "def _run_hooks(config, hooks, args, environ):\n    skips = _get_skips(environ)\n    cols = _compute_cols(hooks, args.verbose)\n    filenames = _all_filenames(args)\n    filenames = filter_by_include_exclude(filenames, '', config['exclude'])\n    classifier = Classifier(filenames)\n    retval = 0\n    for hook in hooks:\n        retval |= _run_single_hook(classifier, hook, args, skips, cols)\n        if retval and config['fail_fast']:\n            break\n    if retval and args.show_diff_on_failure and git.has_diff():\n        if args.all_files:\n            output.write_line(\n                'pre-commit hook(s) made changes.\\n'\n                'If you are seeing this message in CI, '\n                'reproduce locally with: `pre-commit run --all-files`.\\n'\n                'To run `pre-commit` as part of git workflow, use '\n                '`pre-commit install`.',\n            )\n        output.write_line('All changes made by hooks:')\n        subprocess.call(('git', '--no-pager', 'diff', '--no-ext-diff'))\n    return retval",
    "docstring": "Actually run the hooks."
  },
  {
    "code": "def start(self):\n        self.__stop = False\n        self._queue.start()\n        self._zk.start()",
    "docstring": "Starts the connection"
  },
  {
    "code": "def _itemsLoadedDone(self, data):\n        if data is None:\n            return\n        self.continuation   = data.get('continuation', None)\n        self.lastUpdated    = data.get('updated', None)\n        self.lastLoadLength = len(data.get('items', []))\n        self.googleReader.itemsToObjects(self, data.get('items', []))\n        self.lastLoadOk = True",
    "docstring": "Called when all items are loaded"
  },
  {
    "code": "def distance(cls, q0, q1):\n        q = Quaternion.log_map(q0, q1)\n        return q.norm",
    "docstring": "Quaternion intrinsic distance.\n\n        Find the intrinsic geodesic distance between q0 and q1.\n\n        Params:\n            q0: the first quaternion\n            q1: the second quaternion\n\n        Returns:\n           A positive amount corresponding to the length of the geodesic arc\n           connecting q0 to q1.\n\n        Note:\n           Although the q0^(-1)*q1 != q1^(-1)*q0, the length of the path joining\n           them is given by the logarithm of those product quaternions, the norm\n           of which is the same."
  },
  {
    "code": "def get_rect(self):\n        if self.handle:\n            left, top, right, bottom = win32gui.GetWindowRect(self.handle)\n            return RECT(left, top, right, bottom)\n        else:\n            desktop = win32gui.GetDesktopWindow()\n            left, top, right, bottom = win32gui.GetWindowRect(desktop)\n            return RECT(left, top, right, bottom)",
    "docstring": "Get rectangle of app or desktop resolution\n\n        Returns:\n            RECT(left, top, right, bottom)"
  },
  {
    "code": "def compose_post(apikey, resize, rotation, noexif):\n    check_rotation(rotation)\n    check_resize(resize)\n    post_data = {\n            'formatliste': ('', 'og'),\n            'userdrehung': ('', rotation),\n            'apikey': ('', apikey)\n            }\n    if resize and 'x' in resize:\n        width, height = [ x.strip() for x in resize.split('x')]\n        post_data['udefb'] = ('', width)\n        post_data['udefh'] = ('', height)\n    elif resize and '%' in resize:\n        precentage = resize.strip().strip('%')\n        post_data['udefp'] = precentage\n    if noexif:\n        post_data['noexif'] = ('', '')\n    return post_data",
    "docstring": "composes basic post requests"
  },
  {
    "code": "def purgeRDR(rh):\n    rh.printSysLog(\"Enter changeVM.purgeRDR\")\n    results = purgeReader(rh)\n    rh.updateResults(results)\n    rh.printSysLog(\"Exit changeVM.purgeRDR, rc: \" +\n        str(rh.results['overallRC']))\n    return rh.results['overallRC']",
    "docstring": "Purge the reader belonging to the virtual machine.\n\n    Input:\n       Request Handle with the following properties:\n          function    - 'CHANGEVM'\n          subfunction - 'PURGERDR'\n          userid      - userid of the virtual machine\n\n    Output:\n       Request Handle updated with the results.\n       Return code - 0: ok, non-zero: error"
  },
  {
    "code": "def gen_template_files(path):\n    \" Generate relative template pathes. \"\n    path = path.rstrip(op.sep)\n    for root, _, files in walk(path):\n        for f in filter(lambda x: not x in (TPLNAME, CFGNAME), files):\n            yield op.relpath(op.join(root, f), path)",
    "docstring": "Generate relative template pathes."
  },
  {
    "code": "def reset_term_stats(set_id, term_id, client_id, user_id, access_token):\n    found_sets = [user_set for user_set in get_user_sets(client_id, user_id)\n                  if user_set.set_id == set_id]\n    if len(found_sets) != 1:\n        raise ValueError('{} set(s) found with id {}'.format(len(found_sets), set_id))\n    found_terms = [term for term in found_sets[0].terms if term.term_id == term_id]\n    if len(found_terms) != 1:\n        raise ValueError('{} term(s) found with id {}'.format(len(found_terms), term_id))\n    term = found_terms[0]\n    if term.image.url:\n        raise NotImplementedError('\"{}\" has an image and is thus not supported'.format(term))\n    print('Deleting \"{}\"...'.format(term))\n    delete_term(set_id, term_id, access_token)\n    print('Re-creating \"{}\"...'.format(term))\n    add_term(set_id, term, access_token)\n    print('Done')",
    "docstring": "Reset the stats of a term by deleting and re-creating it."
  },
  {
    "code": "def _root(self):\n        _n = self\n        while _n.parent:\n            _n = _n.parent\n        return _n",
    "docstring": "Attribute referencing the root node of the tree.\n\n        :returns: the root node of the tree containing this instance.\n        :rtype: Node"
  },
  {
    "code": "def replace(old, new):\n    parent = old.getparent()\n    parent.replace(old, new)",
    "docstring": "A simple way to replace one element node with another."
  },
  {
    "code": "def economic_qs(K, epsilon=sqrt(finfo(float).eps)):\n    r\n    (S, Q) = eigh(K)\n    nok = abs(max(Q[0].min(), Q[0].max(), key=abs)) < epsilon\n    nok = nok and abs(max(K.min(), K.max(), key=abs)) >= epsilon\n    if nok:\n        from scipy.linalg import eigh as sp_eigh\n        (S, Q) = sp_eigh(K)\n    ok = S >= epsilon\n    nok = logical_not(ok)\n    S0 = S[ok]\n    Q0 = Q[:, ok]\n    Q1 = Q[:, nok]\n    return ((Q0, Q1), S0)",
    "docstring": "r\"\"\"Economic eigen decomposition for symmetric matrices.\n\n    A symmetric matrix ``K`` can be decomposed in\n    :math:`\\mathrm Q_0 \\mathrm S_0 \\mathrm Q_0^\\intercal + \\mathrm Q_1\\\n    \\mathrm S_1 \\mathrm Q_1^ \\intercal`, where :math:`\\mathrm S_1` is a zero\n    matrix with size determined by ``K``'s rank deficiency.\n\n    Args:\n        K (array_like): Symmetric matrix.\n        epsilon (float): Eigen value threshold. Default is\n                         ``sqrt(finfo(float).eps)``.\n\n    Returns:\n        tuple: ``((Q0, Q1), S0)``."
  },
  {
    "code": "def put_attributes(self, item_name, attributes,\n                       replace=True, expected_value=None):\n        return self.connection.put_attributes(self, item_name, attributes,\n                                              replace, expected_value)",
    "docstring": "Store attributes for a given item.\n\n        :type item_name: string\n        :param item_name: The name of the item whose attributes are being stored.\n\n        :type attribute_names: dict or dict-like object\n        :param attribute_names: The name/value pairs to store as attributes\n\n        :type expected_value: list\n        :param expected_value: If supplied, this is a list or tuple consisting\n            of a single attribute name and expected value. The list can be \n            of the form:\n\n             * ['name', 'value']\n\n            In which case the call will first verify that the attribute \n            \"name\" of this item has a value of \"value\".  If it does, the delete\n            will proceed, otherwise a ConditionalCheckFailed error will be \n            returned. The list can also be of the form:\n            \n             * ['name', True|False]\n            \n            which will simply check for the existence (True) or non-existence \n            (False) of the attribute.\n\n        :type replace: bool\n        :param replace: Whether the attribute values passed in will replace\n                        existing values or will be added as addition values.\n                        Defaults to True.\n\n        :rtype: bool\n        :return: True if successful"
  },
  {
    "code": "def map_indices(fn, iterable, indices):\n    r\n    index_set = set(indices)\n    for i, arg in enumerate(iterable):\n        if i in index_set:\n            yield fn(arg)\n        else:\n            yield arg",
    "docstring": "r\"\"\"\n    Map a function across indices of an iterable.\n\n    Notes\n    -----\n    Roughly equivalent to, though more efficient than::\n\n        lambda fn, iterable, *indices: (fn(arg) if i in indices else arg\n                                        for i, arg in enumerate(iterable))\n\n    Examples\n    --------\n\n    >>> a = [4, 6, 7, 1, 6, 8, 2]\n\n    >>> from operator import mul\n    >>> list(map_indices(partial(mul, 3), a, [0, 3, 5]))\n    [12, 6, 7, 3, 6, 24, 2]\n\n    >>> b = [9., np.array([5., 6., 2.]),\n    ...      np.array([[5., 6., 2.], [2., 3., 9.]])]\n\n    >>> list(map_indices(np.log, b, [0, 2])) # doctest: +NORMALIZE_WHITESPACE\n    [2.1972245773362196,\n     array([ 5.,  6.,  2.]),\n     array([[ 1.60943791,  1.79175947,  0.69314718],\n            [ 0.69314718,  1.09861229,  2.19722458]])]\n\n    .. todo::\n\n       Floating point precision\n\n    >>> list(map_indices(np.exp, list(map_indices(np.log, b, [0, 2])), [0, 2]))\n    ... # doctest: +NORMALIZE_WHITESPACE +SKIP\n    [9.,\n     array([5., 6., 2.]),\n     array([[ 5.,  6.,  2.],\n            [ 2.,  3.,  9.]])]"
  },
  {
    "code": "def request_update_of_all_params(self):\n        for group in self.toc.toc:\n            for name in self.toc.toc[group]:\n                complete_name = '%s.%s' % (group, name)\n                self.request_param_update(complete_name)",
    "docstring": "Request an update of all the parameters in the TOC"
  },
  {
    "code": "def get_rollup_ttl(self, use_cached=True):\n        rollup_ttl_text = self._get_stream_metadata(use_cached).get(\"rollupTtl\")\n        return int(rollup_ttl_text)",
    "docstring": "Retrieve the rollupTtl for this stream\n\n        The rollupTtl is the time to live (TTL) in seconds for the aggregate roll-ups of data points\n        stored in the stream. A roll-up expires after the configured amount of time and is\n        automatically deleted.\n\n        :param bool use_cached: If False, the function will always request the latest from Device Cloud.\n            If True, the device will not make a request if it already has cached data.\n        :raises devicecloud.DeviceCloudHttpException: in the case of an unexpected http error\n        :raises devicecloud.streams.NoSuchStreamException: if this stream has not yet been created\n        :return: The rollupTtl associated with this stream in seconds\n        :rtype: int or None"
  },
  {
    "code": "def surface_based_cape_cin(pressure, temperature, dewpoint):\n    r\n    p, t, td, profile = parcel_profile_with_lcl(pressure, temperature, dewpoint)\n    return cape_cin(p, t, td, profile)",
    "docstring": "r\"\"\"Calculate surface-based CAPE and CIN.\n\n    Calculate the convective available potential energy (CAPE) and convective inhibition (CIN)\n    of a given upper air profile for a surface-based parcel. CIN is integrated\n    between the surface and LFC, CAPE is integrated between the LFC and EL (or top of\n    sounding). Intersection points of the measured temperature profile and parcel profile are\n    linearly interpolated.\n\n    Parameters\n    ----------\n    pressure : `pint.Quantity`\n        Atmospheric pressure profile. The first entry should be the starting\n        (surface) observation.\n    temperature : `pint.Quantity`\n        Temperature profile\n    dewpoint : `pint.Quantity`\n        Dewpoint profile\n\n    Returns\n    -------\n    `pint.Quantity`\n        Surface based Convective Available Potential Energy (CAPE).\n    `pint.Quantity`\n        Surface based Convective INhibition (CIN).\n\n    See Also\n    --------\n    cape_cin, parcel_profile"
  },
  {
    "code": "def write_file(path, data):\n    with open(path, 'w') as f:\n        log.debug('setting %s contents:\\n%s', path, data)\n        f.write(data)\n    return f",
    "docstring": "Writes data to specified path."
  },
  {
    "code": "def _persist(source, path, encoder=None):\n        import posixpath\n        from dask.bytes import open_files\n        import dask\n        import pickle\n        import json\n        from intake.source.textfiles import TextFilesSource\n        encoder = {None: str, 'str': str, 'json': json.dumps,\n                   'pickle': pickle.dumps}[encoder]\n        try:\n            b = source.to_dask()\n        except NotImplementedError:\n            import dask.bag as db\n            b = db.from_sequence(source.read(), npartitions=1)\n        files = open_files(posixpath.join(path, 'part.*'), mode='wt',\n                           num=b.npartitions)\n        dwrite = dask.delayed(write_file)\n        out = [dwrite(part, f, encoder)\n               for part, f in zip(b.to_delayed(), files)]\n        dask.compute(out)\n        s = TextFilesSource(posixpath.join(path, 'part.*'))\n        return s",
    "docstring": "Save list to files using encoding\n\n        encoder : None or one of str|json|pickle\n            None is equivalent to str"
  },
  {
    "code": "def plugins(self):\n        from fluent_contents import extensions\n        if self._plugins is None:\n            return extensions.plugin_pool.get_plugins()\n        else:\n            return extensions.plugin_pool.get_plugins_by_name(*self._plugins)",
    "docstring": "Get the set of plugins that this widget should display."
  },
  {
    "code": "def leaveEvent(self, event):\n        super(ToolTipWidget, self).leaveEvent(event)\n        self.hide()",
    "docstring": "Override Qt method to hide the tooltip on leave."
  },
  {
    "code": "def flatten_pages(self, pages, level=1):\n        flattened = []\n        for page in pages:\n            if type(page) is list:\n                flattened.append(\n                             {\n                                'file': page[0],\n                                'title': page[1],\n                                'level': level,\n                             })\n            if type(page) is dict:\n                if type(list(page.values())[0]) is str:\n                    flattened.append(\n                            {\n                                'file': list(page.values())[0],\n                                'title': list(page.keys())[0],\n                                'level': level,\n                             })\n                if type(list(page.values())[0]) is list:\n                    flattened.extend(\n                            self.flatten_pages(\n                                list(page.values())[0],\n                                level + 1)\n                            )\n        return flattened",
    "docstring": "Recursively flattens pages data structure into a one-dimensional data structure"
  },
  {
    "code": "def from_dict(document):\n        type_name = document['name']\n        if type_name == ATTR_TYPE_INT:\n            return IntType()\n        elif type_name == ATTR_TYPE_FLOAT:\n            return FloatType()\n        elif type_name == ATTR_TYPE_ENUM:\n            return EnumType(document['values'])\n        elif type_name == ATTR_TYPE_DICT:\n            return DictType()\n        elif type_name == ATTR_TYPE_LIST:\n            return ListType()\n        else:\n            raise ValueError('invalid attribute type: ' + str(type_name))",
    "docstring": "Create data type definition form Json-like object represenation.\n\n        Parameters\n        ----------\n        document : dict\n            Json-like object represenation\n\n        Returns\n        -------\n        AttributeType"
  },
  {
    "code": "def handle_error(self, type_, value, tb):\n        if not issubclass(type_, pywsgi.GreenletExit):\n            self.server.loop.handle_error(self.environ, type_, value, tb)\n        if self.response_length:\n            self.close_connection = True\n        else:\n            tb_stream = traceback.format_exception(type_, value, tb)\n            del tb\n            tb_stream.append('\\n')\n            tb_stream.append(pprint.pformat(self.environ))\n            body = ''.join(tb_stream)\n            headers = pywsgi._INTERNAL_ERROR_HEADERS[:]\n            headers[2] = ('Content-Length', str(len(body)))\n            self.start_response(pywsgi._INTERNAL_ERROR_STATUS, headers)\n            self.write(body)",
    "docstring": "This method copies the code from pywsgi.WSGIHandler.handle_error,\n        change the write part to be a reflection of traceback and environ"
  },
  {
    "code": "def get_soap_client(db_alias, client_class=None):\n    if not beatbox:\n        raise InterfaceError(\"To use SOAP API, you'll need to install the Beatbox package.\")\n    if client_class is None:\n        client_class = beatbox.PythonClient\n    soap_client = client_class()\n    connection = connections[db_alias]\n    cursor = connection.cursor()\n    cursor.urls_request()\n    auth_info = connections[db_alias].sf_session.auth\n    access_token = auth_info.get_auth()['access_token']\n    assert access_token[15] == '!'\n    org_id = access_token[:15]\n    url = '/services/Soap/u/{version}/{org_id}'.format(version=salesforce.API_VERSION,\n                                                       org_id=org_id)\n    soap_client.useSession(access_token, auth_info.instance_url + url)\n    return soap_client",
    "docstring": "Create the SOAP client for the current user logged in the db_alias\n\n    The default created client is \"beatbox.PythonClient\", but an\n    alternative client is possible. (i.e. other subtype of beatbox.XMLClient)"
  },
  {
    "code": "def handleOACK(self, pkt):\n        if len(pkt.options.keys()) > 0:\n            if pkt.match_options(self.context.options):\n                log.info(\"Successful negotiation of options\")\n                self.context.options = pkt.options\n                for key in self.context.options:\n                    log.info(\"    %s = %s\" % (key, self.context.options[key]))\n            else:\n                log.error(\"Failed to negotiate options\")\n                raise TftpException(\"Failed to negotiate options\")\n        else:\n            raise TftpException(\"No options found in OACK\")",
    "docstring": "This method handles an OACK from the server, syncing any accepted\n        options."
  },
  {
    "code": "def decode_step(self, step_input, states):\n        step_output, states, step_additional_outputs =\\\n            self.decoder(self.tgt_embed(step_input), states)\n        step_output = self.tgt_proj(step_output)\n        return step_output, states, step_additional_outputs",
    "docstring": "One step decoding of the translation model.\n\n        Parameters\n        ----------\n        step_input : NDArray\n            Shape (batch_size,)\n        states : list of NDArrays\n\n        Returns\n        -------\n        step_output : NDArray\n            Shape (batch_size, C_out)\n        states : list\n        step_additional_outputs : list\n            Additional outputs of the step, e.g, the attention weights"
  },
  {
    "code": "def validate(self, uri):\n\t\tif WURIComponentVerifier.validate(self, uri) is False:\n\t\t\treturn False\n\t\ttry:\n\t\t\tWStrictURIQuery(\n\t\t\t\tWURIQuery.parse(uri.component(self.component())),\n\t\t\t\t*self.__specs,\n\t\t\t\textra_parameters=self.__extra_parameters\n\t\t\t)\n\t\texcept ValueError:\n\t\t\treturn False\n\t\treturn True",
    "docstring": "Check that an query part of an URI is compatible with this descriptor. Return True if the URI is\n\t\tcompatible.\n\n\t\t:param uri: an URI to check\n\n\t\t:return: bool"
  },
  {
    "code": "def set_qos(self, port_name, type='linux-htb', max_rate=None, queues=None):\n        queues = queues if queues else []\n        command_qos = ovs_vsctl.VSCtlCommand(\n            'set-qos',\n            [port_name, type, max_rate])\n        command_queue = ovs_vsctl.VSCtlCommand(\n            'set-queue',\n            [port_name, queues])\n        self.run_command([command_qos, command_queue])\n        if command_qos.result and command_queue.result:\n            return command_qos.result + command_queue.result\n        return None",
    "docstring": "Sets a Qos rule and creates Queues on the given port."
  },
  {
    "code": "def file_size(filename):\n    fd = os.open(filename, os.O_RDONLY)\n    try:\n        return os.lseek(fd, 0, os.SEEK_END)\n    except KeyboardInterrupt as e:\n        raise e\n    except Exception as e:\n        raise Exception(\n            \"file_size failed to obtain the size of '%s': %s\" % (filename, str(e)))\n    finally:\n        os.close(fd)",
    "docstring": "Obtains the size of a given file.\n\n    @filename - Path to the file.\n\n    Returns the size of the file."
  },
  {
    "code": "def popleft(self, block=True, timeout=None):\n        return self._pop(block, timeout, left=True)",
    "docstring": "Remove and return an item from the right side of the\n        GeventDeque. If no elements are present, raises an IndexError.\n\n        If optional args *block* is True and *timeout* is ``None``\n        (the default), block if necessary until an item is\n        available. If *timeout* is a positive number, it blocks at\n        most *timeout* seconds and raises the :class:`IndexError`\n        exception if no item was available within that time. Otherwise\n        (*block* is False), return an item if one is immediately\n        available, else raise the :class:`IndexError` exception\n        (*timeout* is ignored in that case)."
  },
  {
    "code": "def filter(self, record):\n        request = get_request()\n        if request:\n            user = getattr(request, 'user', None)\n            if user and not user.is_anonymous():\n                record.username = user.username\n            else:\n                record.username = '-'\n            meta = getattr(request, 'META', {})\n            record.remote_addr = meta.get('REMOTE_ADDR', '-')\n            record.http_user_agent = meta.get('HTTP_USER_AGENT', '-')\n            if not hasattr(record, 'request'):\n                record.request = request\n        else:\n            record.username = '-'\n            record.remote_addr = '-'\n            record.http_user_agent = '-'\n        return True",
    "docstring": "Adds user and remote_addr to the record."
  },
  {
    "code": "def random_alphanum(length=10, lower_only=False):\n    character_set = ALPHANUM_LOWER if lower_only else ALPHANUM\n    sample_size = 5\n    chars = random.sample(character_set, sample_size)\n    while len(chars) < length:\n        chars += random.sample(character_set, sample_size)\n    random.shuffle(chars)\n    return ''.join(chars[:length])",
    "docstring": "Gets a random alphanumeric value using both letters and numbers.\n\n    :param length: size of the random alphanumeric string.\n    :param lower_only: boolean indicating if only lower case letters should be\n        used.\n    :return: alphanumeric string size of length\n\n    This function uses all number except for:\n\n    * 0\n    * 1\n\n    and uses all letters except for:\n\n    * lower case \"l\" (el)\n    * lower and upper case \"o\" and \"O\" (oh)\n\n    For upper and lower cased letters...\n    ------------------------------------\n    Upper and lower cased letters and numbers can be used more than once which\n    leaves the possible combinations as follows:\n\n        8 numbers used + 49 letters used (upper and lower) = 57 total characters\n\n    Which leads us to the following equation:\n\n        57 total characters ^ length = total possible combinations\n\n    The following total possible combinations are below for a given length:\n\n        57 ^ 1 = 57\n        57 ^ 2 = 3,249\n        57 ^ 3 = 185,193\n        57 ^ 4 = 10,556,001\n        57 ^ 5 = 601,692,057\n        57 ^ 6 = 34,296,447,249\n        57 ^ 7 = 1,954,897,493,193\n        57 ^ 8 = 111,429,157,112,001\n        57 ^ 9 = 6,351,461,955,384,057\n        57 ^ 10 = 362,033,331,456,891,249\n        ...\n\n    For lower cased letters...\n    --------------------------\n    Lower cased letters and numbers can be used more than once which leaves the\n    possible combinations as follows:\n\n        8 numbers used + 24 letters used (lower only) = 32 total characters\n\n    Which leads us to the following equation:\n\n        32 total characters ^ length = total possible combinations\n\n    The following total possible combinations are below for a given length:\n\n        32 ^ 1 = 32\n        32 ^ 2 = 1,024\n        32 ^ 3 = 32,768\n        32 ^ 4 = 1,048,576\n        32 ^ 5 = 33,554,432\n        32 ^ 6 = 1,073,741,824\n        32 ^ 7 = 34,359,738,368\n        32 ^ 8 = 1,099,511,627,776\n        32 ^ 9 = 35,184,372,088,832\n        32 ^ 10 = 1,125,899,906,842,624\n        ..."
  },
  {
    "code": "async def set_reply_markup(msg: Dict, request: 'Request', stack: 'Stack') \\\n        -> None:\n    from bernard.platforms.telegram.layers import InlineKeyboard, \\\n        ReplyKeyboard, \\\n        ReplyKeyboardRemove\n    try:\n        keyboard = stack.get_layer(InlineKeyboard)\n    except KeyError:\n        pass\n    else:\n        msg['reply_markup'] = await keyboard.serialize(request)\n    try:\n        keyboard = stack.get_layer(ReplyKeyboard)\n    except KeyError:\n        pass\n    else:\n        msg['reply_markup'] = await keyboard.serialize(request)\n    try:\n        remove = stack.get_layer(ReplyKeyboardRemove)\n    except KeyError:\n        pass\n    else:\n        msg['reply_markup'] = remove.serialize()",
    "docstring": "Add the \"reply markup\" to a message from the layers\n\n    :param msg: Message dictionary\n    :param request: Current request being replied\n    :param stack: Stack to analyze"
  },
  {
    "code": "def _update_pods_metrics(self, instance, pods):\n        tags_map = defaultdict(int)\n        for pod in pods['items']:\n            pod_meta = pod.get('metadata', {})\n            pod_tags = self.kubeutil.get_pod_creator_tags(pod_meta, legacy_rep_controller_tag=True)\n            services = self.kubeutil.match_services_for_pod(pod_meta)\n            if isinstance(services, list):\n                for service in services:\n                    pod_tags.append('kube_service:%s' % service)\n            if 'namespace' in pod_meta:\n                pod_tags.append('kube_namespace:%s' % pod_meta['namespace'])\n            tags_map[frozenset(pod_tags)] += 1\n        commmon_tags = instance.get('tags', [])\n        for pod_tags, pod_count in tags_map.iteritems():\n            tags = list(pod_tags)\n            tags.extend(commmon_tags)\n            self.publish_gauge(self, NAMESPACE + '.pods.running', pod_count, tags)",
    "docstring": "Reports the number of running pods on this node, tagged by service and creator\n\n        We go though all the pods, extract tags then count them by tag list, sorted and\n        serialized in a pipe-separated string (it is an illegar character for tags)"
  },
  {
    "code": "def delete(self, password, message=\"\"):\n        data = {'user': self.user.name,\n                'passwd': password,\n                'delete_message': message,\n                'confirm': True}\n        return self.request_json(self.config['delete_redditor'], data=data)",
    "docstring": "Delete the currently authenticated redditor.\n\n        WARNING!\n\n        This action is IRREVERSIBLE. Use only if you're okay with NEVER\n        accessing this reddit account again.\n\n        :param password: password for currently authenticated account\n        :param message: optional 'reason for deletion' message.\n        :returns: json response from the server."
  },
  {
    "code": "def save_evaluations(self, evaluations_file = None):\n        iterations = np.array(range(1, self.Y.shape[0] + 1))[:, None]\n        results = np.hstack((iterations, self.Y, self.X))\n        header = ['Iteration', 'Y'] + ['var_' + str(k) for k in range(1, self.X.shape[1] + 1)]\n        data = [header] + results.tolist()\n        self._write_csv(evaluations_file, data)",
    "docstring": "Saves  evaluations at each iteration of the optimization\n\n        :param evaluations_file: name of the file in which the results are saved."
  },
  {
    "code": "async def iter_all(\n        self,\n        direction: msg.StreamDirection = msg.StreamDirection.Forward,\n        from_position: Optional[Union[msg.Position, msg._PositionSentinel]] = None,\n        batch_size: int = 100,\n        resolve_links: bool = True,\n        require_master: bool = False,\n        correlation_id: Optional[uuid.UUID] = None,\n    ):\n        correlation_id = correlation_id\n        cmd = convo.IterAllEvents(\n            msg.Position.for_direction(direction, from_position),\n            batch_size,\n            resolve_links,\n            require_master,\n            direction,\n            self.credential,\n            correlation_id,\n        )\n        result = await self.dispatcher.start_conversation(cmd)\n        iterator = await result\n        async for event in iterator:\n            yield event",
    "docstring": "Read through all the events in the database.\n\n        Args:\n            direction (optional): Controls whether to read forward or backward\n              through the events. Defaults to  StreamDirection.Forward\n            from_position (optional): The position to start reading from.\n              Defaults to photonpump.Beginning when direction is Forward,\n              photonpump.End when direction is Backward.\n            batch_size (optional): The maximum number of events to read at a time.\n            resolve_links (optional): True if eventstore should\n                automatically resolve Link Events, otherwise False.\n            required_master (optional): True if this command must be\n                sent direct to the master node, otherwise False.\n            correlation_id (optional): A unique identifer for this\n                command.\n\n        Examples:\n\n            Print every event from the database.\n\n            >>> with async.connect() as conn:\n            >>>     async for event in conn.iter_all()\n            >>>         print(event)\n\n            Print every event from the database in reverse order\n\n            >>> with async.connect() as conn:\n            >>>     async for event in conn.iter_all(direction=StreamDirection.Backward):\n            >>>         print(event)\n\n            Start reading from a known commit position\n\n            >>> with async.connect() as conn:\n            >>>     async for event in conn.iter_all(from_position=Position(12345))\n            >>>         print(event)"
  },
  {
    "code": "def main(global_config, **settings):\n    engine = engine_from_config(settings, \"sqlalchemy.\")\n    DBSession.configure(bind=engine)\n    Base.metadata.bind = engine\n    config = Configurator(settings=settings)\n    config.include(\"pyramid_jinja2\")\n    config.include(\"pyramid_debugtoolbar\")\n    config.add_route(\"home\", \"/\")\n    config.add_route(\"data\", \"/data\")\n    config.add_route(\"data_advanced\", \"/data_advanced\")\n    config.add_route(\"data_yadcf\", \"/data_yadcf\")\n    config.add_route(\"dt_110x\", \"/dt_110x\")\n    config.add_route(\"dt_110x_custom_column\", \"/dt_110x_custom_column\")\n    config.add_route(\"dt_110x_basic_column_search\",\n                     \"/dt_110x_basic_column_search\")\n    config.add_route(\"dt_110x_advanced_column_search\",\n                     \"/dt_110x_advanced_column_search\")\n    config.add_route(\"dt_110x_yadcf\", \"/dt_110x_yadcf\")\n    config.scan()\n    json_renderer = JSON()\n    json_renderer.add_adapter(date, date_adapter)\n    config.add_renderer(\"json_with_dates\", json_renderer)\n    config.add_jinja2_renderer('.html')\n    return config.make_wsgi_app()",
    "docstring": "Return a Pyramid WSGI application."
  },
  {
    "code": "async def join_voice_channel(self, guild_id, channel_id):\n        voice_ws = self.get_voice_ws(guild_id)\n        await voice_ws.voice_state(guild_id, channel_id)",
    "docstring": "Alternative way to join a voice channel if node is known."
  },
  {
    "code": "def bin_spikes(spike_times, binsz):\n    bins = np.empty((len(spike_times),), dtype=int)\n    for i, stime in enumerate(spike_times):\n        bins[i] = np.floor(np.around(stime/binsz, 5))\n    return bins",
    "docstring": "Sort spike times into bins\n\n    :param spike_times: times of spike instances\n    :type spike_times: list\n    :param binsz: length of time bin to use\n    :type binsz: float\n    :returns: list of bin indicies, one for each element in spike_times"
  },
  {
    "code": "def eager_load_relations(self, models):\n        for name, constraints in self._eager_load.items():\n            if name.find('.') == -1:\n                models = self._load_relation(models, name, constraints)\n        return models",
    "docstring": "Eager load the relationship of the models.\n\n        :param models:\n        :type models: list\n\n        :return: The models\n        :rtype: list"
  },
  {
    "code": "def decode(self, encoded):\n        if self.enforce_reversible:\n            self.enforce_reversible = False\n            if self.encode(self.decode(encoded)) != encoded:\n                raise ValueError('Decoding is not reversible for \"%s\"' % encoded)\n            self.enforce_reversible = True\n        return encoded",
    "docstring": "Decodes an object.\n\n        Args:\n            object_ (object): Encoded object.\n\n        Returns:\n            object: Object decoded."
  },
  {
    "code": "def clear_unattached_processes(self):\n        for pid in self.get_process_ids():\n            aProcess = self.get_process(pid)\n            if not aProcess.is_being_debugged():\n                self._del_process(aProcess)",
    "docstring": "Removes Process objects from the snapshot\n        referring to processes not being debugged."
  },
  {
    "code": "def get_filename(self, index):\r\n        if index:\r\n            path = self.fsmodel.filePath(self.proxymodel.mapToSource(index))\r\n            return osp.normpath(to_text_string(path))",
    "docstring": "Return filename from index"
  },
  {
    "code": "def surround_parse(self, node, pre_char, post_char):\n        self.add_text(pre_char)\n        self.subnode_parse(node)\n        self.add_text(post_char)",
    "docstring": "Parse the subnodes of a given node. Subnodes with tags in the\n        `ignore` list are ignored. Prepend `pre_char` and append `post_char` to\n        the output in self.pieces."
  },
  {
    "code": "def end_output (self, **kwargs):\n        self.write_edges()\n        self.end_graph()\n        if self.has_part(\"outro\"):\n            self.write_outro()\n        self.close_fileoutput()",
    "docstring": "Write edges and end of checking info as gml comment."
  },
  {
    "code": "def load_data(self, idx):\n        for subseqs in self:\n            if isinstance(subseqs, abctools.InputSequencesABC):\n                subseqs.load_data(idx)",
    "docstring": "Call method |InputSequences.load_data| of all handled\n        |InputSequences| objects."
  },
  {
    "code": "def convert_to_sqlite(self, destination=None, method=\"shell\", progress=False):\n        if progress: progress = tqdm.tqdm\n        else:        progress = lambda x:x\n        if destination is None: destination = self.replace_extension('sqlite')\n        destination.remove()\n        if method == 'shell':     return self.sqlite_by_shell(destination)\n        if method == 'object':    return self.sqlite_by_object(destination, progress)\n        if method == 'dataframe': return self.sqlite_by_df(destination, progress)",
    "docstring": "Who wants to use Access when you can deal with SQLite databases instead?"
  },
  {
    "code": "def has_permission(self, request, view):\n        if request.method == 'POST':\n            user = Profile.objects.only('id', 'username').get(username=view.kwargs['username'])\n            return request.user.id == user.id\n        return True",
    "docstring": "applies to social-link-list"
  },
  {
    "code": "def serialise(self, element: Element, **kwargs) -> str:\n        return json.dumps(self.serialise_dict(element), **kwargs)",
    "docstring": "Serialises the given element into JSON.\n\n        >>> JSONSerialiser().serialise(String(content='Hello'))\n        '{\"element\": \"string\", \"content\": \"Hello\"}'"
  },
  {
    "code": "def validate_replicas(self, data):\n        environment = data.get('environment')\n        if environment and environment.replicas:\n            validate_replicas(data.get('framework'), environment.replicas)",
    "docstring": "Validate distributed experiment"
  },
  {
    "code": "def drop_post(self):\n        post_index = self.version.find('.post')\n        if post_index >= 0:\n            self.version = self.version[:post_index]",
    "docstring": "Remove .postXXXX postfix from version"
  },
  {
    "code": "def Format(self, format_string, rdf):\n    result = []\n    for literal_text, field_name, _, _ in self.parse(format_string):\n      if literal_text:\n        result.append(literal_text)\n      if field_name is not None:\n        rslts = []\n        objs = self.expander(rdf, field_name)\n        for o in objs:\n          rslts.extend(self.FanOut(o))\n        result.append(\",\".join(rslts))\n    return \"\".join(result)",
    "docstring": "Apply string formatting templates to rdf data.\n\n    Uses some heuristics to coerce rdf values into a form compatible with string\n    formatter rules. Repeated items are condensed into a single comma separated\n    list. Unlike regular string.Formatter operations, we use objectfilter\n    expansion to fully acquire the target attribute in one pass, rather than\n    recursing down each element of the attribute tree.\n\n    Args:\n      format_string: A format string specification.\n      rdf: The rdf value to be formatted.\n\n    Returns:\n      A string of formatted data."
  },
  {
    "code": "def max_id_length(self):\n        if config().identifiers() == \"text\":\n            return max_id_length(len(self._todos))\n        else:\n            try:\n                return math.ceil(math.log(len(self._todos), 10))\n            except ValueError:\n                return 0",
    "docstring": "Returns the maximum length of a todo ID, used for formatting purposes."
  },
  {
    "code": "def store_magic_envelope_doc(self, payload):\n        try:\n            json_payload = json.loads(decode_if_bytes(payload))\n        except ValueError:\n            xml = unquote(decode_if_bytes(payload))\n            xml = xml.lstrip().encode(\"utf-8\")\n            logger.debug(\"diaspora.protocol.store_magic_envelope_doc: xml payload: %s\", xml)\n            self.doc = etree.fromstring(xml)\n        else:\n            logger.debug(\"diaspora.protocol.store_magic_envelope_doc: json payload: %s\", json_payload)\n            self.doc = self.get_json_payload_magic_envelope(json_payload)",
    "docstring": "Get the Magic Envelope, trying JSON first."
  },
  {
    "code": "def field_adaptors(self):\n    with exception_logging(logger, 'Exception in `field_adaptors` property'):\n      conjunction_globs = self.get_sources()\n      if conjunction_globs is None:\n        return tuple()\n      sources = conjunction_globs.non_path_globs\n      conjunction = conjunction_globs.conjunction\n      if not sources:\n        return tuple()\n      base_globs = BaseGlobs.from_sources_field(sources, self.address.spec_path)\n      path_globs = base_globs.to_path_globs(self.address.spec_path, conjunction)\n      return (SourcesField(\n        self.address,\n        'sources',\n        base_globs.filespecs,\n        base_globs,\n        path_globs,\n        self.validate_sources,\n      ),)",
    "docstring": "Returns a tuple of Fields for captured fields which need additional treatment."
  },
  {
    "code": "def encode(self, transmission):\n        data = ''\n        data += self._record_encode(transmission.header)\n        for group in transmission.groups:\n            data += self._record_encode(group.group_header)\n            for transaction in group.transactions:\n                for record in transaction:\n                    data += self._record_encode(record)\n            data += self._record_encode(group.group_trailer)\n        data += self._record_encode(transmission.trailer)\n        return data",
    "docstring": "Encodes the data, creating a CWR structure from an instance from the\n        domain model.\n\n        :param entity: the instance to encode\n        :return: a cwr string structure created from the received data"
  },
  {
    "code": "def _ParseLayerConfigJSON(self, parser_mediator, file_object):\n    file_content = file_object.read()\n    file_content = codecs.decode(file_content, self._ENCODING)\n    json_dict = json.loads(file_content)\n    if 'docker_version' not in json_dict:\n      raise errors.UnableToParseFile(\n          'not a valid Docker layer configuration file, missing '\n          '\\'docker_version\\' key.')\n    if 'created' in json_dict:\n      layer_creation_command_array = [\n          x.strip() for x in json_dict['container_config']['Cmd']]\n      layer_creation_command = ' '.join(layer_creation_command_array).replace(\n          '\\t', '')\n      event_data = DockerJSONLayerEventData()\n      event_data.command = layer_creation_command\n      event_data.layer_id = self._GetIdentifierFromPath(parser_mediator)\n      timestamp = timelib.Timestamp.FromTimeString(json_dict['created'])\n      event = time_events.TimestampEvent(\n          timestamp, definitions.TIME_DESCRIPTION_ADDED)\n      parser_mediator.ProduceEventWithEventData(event, event_data)",
    "docstring": "Extracts events from a Docker filesystem layer configuration file.\n\n    The path of each filesystem layer config file is:\n    DOCKER_DIR/graph/<layer_id>/json\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      file_object (dfvfs.FileIO): a file-like object.\n\n    Raises:\n      UnableToParseFile: when the file is not a valid layer config file."
  },
  {
    "code": "def cli_help_message(self, description):\n        config_files_listing = '\\n'.join('    {}. {!s}'.format(i, path) for i, path in enumerate(self._paths, 1))\n        text = dedent(\n).format(\n            config_file='{}.conf'.format(self._configuration_name),\n            description=description,\n            config_files_listing=config_files_listing\n        )\n        return text",
    "docstring": "Get a user friendly help message that can be dropped in a\n        `click.Command`\\ 's epilog.\n\n        Parameters\n        ----------\n        description : str\n            Description of the configuration file to include in the message.\n\n        Returns\n        -------\n        str\n            A help message that uses :py:mod:`click`\\ 's help formatting\n            constructs (e.g. ``\\b``)."
  },
  {
    "code": "def slice(self, tf_tensor, tensor_shape):\n    tensor_layout = self.tensor_layout(tensor_shape)\n    if tensor_layout.is_fully_replicated:\n      return self.LaidOutTensor([tf_tensor])\n    else:\n      slice_shape = self.slice_shape(tensor_shape)\n      slice_begins = [\n          self.slice_begin(tensor_shape, pnum) for pnum in xrange(self.size)\n      ]\n      slice_begins_tensor = tf.stack(slice_begins)\n      selected_slice_begin = tf.gather(slice_begins_tensor, self.pnum_tensor)\n      return self.LaidOutTensor(\n          [tf.slice(tf_tensor, selected_slice_begin, slice_shape)])",
    "docstring": "Slice out the corresponding part of tensor given the pnum variable."
  },
  {
    "code": "def percentage_of_reoccurring_values_to_all_values(x):\n    if not isinstance(x, pd.Series):\n        x = pd.Series(x)\n    if x.size == 0:\n        return np.nan\n    value_counts = x.value_counts()\n    reoccuring_values = value_counts[value_counts > 1].sum()\n    if np.isnan(reoccuring_values):\n        return 0\n    return reoccuring_values / x.size",
    "docstring": "Returns the ratio of unique values, that are present in the time series\n    more than once.\n\n        # of data points occurring more than once / # of all data points\n\n    This means the ratio is normalized to the number of data points in the time series,\n    in contrast to the percentage_of_reoccurring_datapoints_to_all_datapoints.\n\n    :param x: the time series to calculate the feature of\n    :type x: numpy.ndarray\n    :return: the value of this feature\n    :return type: float"
  },
  {
    "code": "def _post(self, url, data=None, json=None, params=None, headers=None):\n        url = self.clean_url(url)\n        response = requests.post(url, data=data, json=json, params=params,\n                                 headers=headers, timeout=self.timeout,\n                                 verify=self.verify)\n        return response",
    "docstring": "Wraps a POST request with a url check"
  },
  {
    "code": "def enable_cache():\n    try:\n        import requests_cache\n    except ImportError as err:\n        sys.stderr.write('Failed to enable cache: {0}\\n'.format(str(err)))\n        return\n    if not os.path.exists(CACHE_DIR):\n        os.makedirs(CACHE_DIR)\n    requests_cache.install_cache(CACHE_FILE)",
    "docstring": "Enable requests library cache."
  },
  {
    "code": "def is_cached(self):\n        from dvc.remote.local import RemoteLOCAL\n        from dvc.remote.s3 import RemoteS3\n        old = Stage.load(self.repo, self.path)\n        if old._changed_outs():\n            return False\n        for dep in self.deps:\n            dep.save()\n        old_d = old.dumpd()\n        new_d = self.dumpd()\n        old_d.pop(self.PARAM_MD5, None)\n        new_d.pop(self.PARAM_MD5, None)\n        outs = old_d.get(self.PARAM_OUTS, [])\n        for out in outs:\n            out.pop(RemoteLOCAL.PARAM_CHECKSUM, None)\n            out.pop(RemoteS3.PARAM_CHECKSUM, None)\n        if old_d != new_d:\n            return False\n        old.commit()\n        return True",
    "docstring": "Checks if this stage has been already ran and stored"
  },
  {
    "code": "def upcaseTokens(s,l,t):\n    return [ tt.upper() for tt in map(_ustr,t) ]",
    "docstring": "Helper parse action to convert tokens to upper case."
  },
  {
    "code": "def more_data(pipe_out):\n    r, _, _ = select.select([pipe_out], [], [], 0)\n    return bool(r)",
    "docstring": "Check if there is more data left on the pipe\n\n    :param pipe_out: The os pipe_out\n    :rtype: bool"
  },
  {
    "code": "def reload_texts(self, texts, ids, vocabulary=None):\n        self._check_id_length(ids)\n        self.ids = np.array(sorted(ids))\n        if vocabulary:\n            self.vectorizer.vocabulary = vocabulary\n        sorted_texts = [x for (y, x) in sorted(zip(ids, texts))]\n        self.term_mat = self.vectorizer.fit_transform(sorted_texts)\n        self._update_tfidf()",
    "docstring": "Calcula los vectores de terminos de textos y los almacena.\n\n        A diferencia de :func:`~TextClassifier.TextClassifier.store_text` esta\n        funcion borra cualquier informacion almacenada y comienza el conteo\n        desde cero. Se usa para redefinir el vocabulario sobre el que se\n        construyen los vectores.\n\n        Args:\n            texts (list): Una lista de N textos a incorporar.\n            ids (list): Una lista de N ids alfanumericos para los textos."
  },
  {
    "code": "def calc_qout_v1(self):\n    der = self.parameters.derived.fastaccess\n    flu = self.sequences.fluxes.fastaccess\n    flu.qout = 0.\n    for idx in range(der.nmb):\n        flu.qout += flu.qpout[idx]",
    "docstring": "Sum up the results of the different response functions.\n\n    Required derived parameter:\n      |Nmb|\n\n    Required flux sequences:\n      |QPOut|\n\n    Calculated flux sequence:\n      |QOut|\n\n    Examples:\n\n        Initialize an arma model with three different response functions:\n\n        >>> from hydpy.models.arma import *\n        >>> parameterstep()\n        >>> derived.nmb(3)\n        >>> fluxes.qpout.shape = 3\n\n        Define the output values of the three response functions and\n        apply method |calc_qout_v1|:\n\n        >>> fluxes.qpout = 1.0, 2.0, 3.0\n        >>> model.calc_qout_v1()\n        >>> fluxes.qout\n        qout(6.0)"
  },
  {
    "code": "def isRealmUser(self, realmname, username, environ):\n        try:\n            course = self.course_factory.get_course(realmname)\n            ok = self.user_manager.has_admin_rights_on_course(course, username=username)\n            return ok\n        except:\n            return False",
    "docstring": "Returns True if this username is valid for the realm, False otherwise."
  },
  {
    "code": "def backends_to_mutate(self, namespace, stream):\n    if namespace not in self.namespaces:\n      raise NamespaceMissing('`{}` namespace is not configured'\n                             .format(namespace))\n    return self.prefix_confs[namespace][self.get_matching_prefix(namespace,\n                                                                 stream)]",
    "docstring": "Return all the backends enabled for writing for `stream`."
  },
  {
    "code": "def check_plugins(self):\n        checkers = {}\n        for ep in pkg_resources.iter_entry_points(group='frosted.plugins'):\n            checkers.update({ep.name: ep.load()})\n        for plugin_name, plugin in checkers.items():\n            if self.filename != '(none)':\n                messages = plugin.check(self.filename)\n                for message, loc, args, kwargs in messages:\n                    self.report(message, loc, *args, **kwargs)",
    "docstring": "collect plugins from entry point 'frosted.plugins'\n\n        and run their check() method, passing the filename"
  },
  {
    "code": "def _validate_group(self, group):\n        if self._show_all_groups:\n            return\n        if group.id in self._allowed_group_ids:\n            return\n        for parent_group_id in self._allowed_subgroup_ids:\n            parent_group = self._swimlane.groups.get(id=parent_group_id)\n            parent_group_child_ids = set([g['id'] for g in parent_group._raw['groups']])\n            if group.id in parent_group_child_ids:\n                return\n        raise ValidationError(\n            self.record,\n            'Group `{}` is not a valid selection for field `{}`'.format(\n                group,\n                self.name\n            )\n        )",
    "docstring": "Validate a Group instance against allowed group IDs or subgroup of a parent group"
  },
  {
    "code": "def show_time_as_short_string(self, seconds):\n        if seconds < 60:\n            return str(seconds) + ' seconds'\n        elif seconds < 3600:\n            return str(round(seconds/60, 1)) + ' minutes'\n        elif seconds < 3600*24:\n            return str(round(seconds/(60*24), 1)) + ' hours'\n        elif seconds < 3600*24*365:\n            return str(round(seconds/(3600*24), 1)) + ' days'\n        else:\n            print('WARNING - this will take ' + str(seconds/(60*24*365)) + ' YEARS to run' )\n            return str(round(seconds/(60*24*365), 1)) + ' years'",
    "docstring": "converts seconds to a string in terms of \n        seconds -> years to show complexity of algorithm"
  },
  {
    "code": "def query_object(self, obj_uuid):\n        if not isinstance(obj_uuid, basestring):\n            raise TypeError(\"obj_uuid can only be an instance of type basestring\")\n        return_interface = self._call(\"queryObject\",\n                     in_p=[obj_uuid])\n        return_interface = Interface(return_interface)\n        return return_interface",
    "docstring": "Queries the IUnknown interface to an object in the extension pack\n        main module. This allows plug-ins and others to talk directly to an\n        extension pack.\n\n        in obj_uuid of type str\n            The object ID. What exactly this is\n\n        return return_interface of type Interface\n            The queried interface."
  },
  {
    "code": "def resample_returns(\n        returns,\n        func,\n        seed=0,\n        num_trials=100\n):\n    if type(returns) is pd.Series:\n        stats = pd.Series(index=range(num_trials))\n    elif type(returns) is pd.DataFrame:\n        stats = pd.DataFrame(\n            index=range(num_trials),\n            columns=returns.columns\n        )\n    else:\n        raise(TypeError(\"returns needs to be a Series or DataFrame!\"))\n    n = returns.shape[0]\n    for i in range(num_trials):\n        random_indices = resample(returns.index, n_samples=n, random_state=seed + i)\n        stats.loc[i] = func(returns.loc[random_indices])\n    return stats",
    "docstring": "Resample the returns and calculate any statistic on every new sample.\n\n    https://en.wikipedia.org/wiki/Resampling_(statistics)\n\n    :param returns (Series, DataFrame): Returns\n    :param func: Given the resampled returns calculate a statistic\n    :param seed: Seed for random number generator\n    :param num_trials: Number of times to resample and run the experiment\n    :return: Series of resampled statistics"
  },
  {
    "code": "def load_checkpoint(with_local=False):\n    gptr = ctypes.POINTER(ctypes.c_char)()\n    global_len = ctypes.c_ulong()\n    if with_local:\n        lptr = ctypes.POINTER(ctypes.c_char)()\n        local_len = ctypes.c_ulong()\n        version = _LIB.RabitLoadCheckPoint(\n            ctypes.byref(gptr),\n            ctypes.byref(global_len),\n            ctypes.byref(lptr),\n            ctypes.byref(local_len))\n        if version == 0:\n            return (version, None, None)\n        return (version,\n                _load_model(gptr, global_len.value),\n                _load_model(lptr, local_len.value))\n    else:\n        version = _LIB.RabitLoadCheckPoint(\n            ctypes.byref(gptr),\n            ctypes.byref(global_len),\n            None, None)\n        if version == 0:\n            return (version, None)\n        return (version,\n                _load_model(gptr, global_len.value))",
    "docstring": "Load latest check point.\n\n    Parameters\n    ----------\n    with_local: bool, optional\n        whether the checkpoint contains local model\n\n    Returns\n    -------\n    tuple : tuple\n        if with_local: return (version, gobal_model, local_model)\n        else return (version, gobal_model)\n        if returned version == 0, this means no model has been CheckPointed\n        and global_model, local_model returned will be None"
  },
  {
    "code": "def extend(self, protocol: Union[Iterable[Dict], 'Pipeline']) -> 'Pipeline':\n        for data in protocol:\n            name, args, kwargs = _get_protocol_tuple(data)\n            self.append(name, *args, **kwargs)\n        return self",
    "docstring": "Add another pipeline to the end of the current pipeline.\n\n        :param protocol: An iterable of dictionaries (or another Pipeline)\n        :return: This pipeline for fluid query building\n\n        Example:\n\n        >>> p1 = Pipeline.from_functions(['enrich_protein_and_rna_origins'])\n        >>> p2 = Pipeline.from_functions(['remove_pathologies'])\n        >>> p1.extend(p2)"
  },
  {
    "code": "def update(self, data):\n        if not isinstance(data, list): data = [data]\n        master = Handler.ALL_VERS_DATA\n        for record in data:\n            for k,v in iteritems(record):\n                try:                record[k] = int(v)\n                except ValueError:  record[k] = v\n            try: label = record[\"label\"]\n            except KeyError:\n                raise ValueError(\"Must provide a valid label argument.  Given:%s%s\"%(\\\n                    os.linesep, (\"%s  \"%(os.linesep)).join(\n                        [\"%15s:%s\"%(k,v) for k,v in iteritems(kwargs)]\n                    )))\n            try:    masterLabel = master[label]\n            except KeyError:\n                master[label] = record\n                self._updated = True\n                continue\n            for k,v in iteritems(record):\n                try:\n                    if masterLabel[k] == v:  continue\n                except KeyError:             pass\n                self._updated = True\n                try:    master[label].update(record)\n                except KeyError:             break",
    "docstring": "update known data with with newly provided data"
  },
  {
    "code": "def send(\n            self,\n            *args: str,\n            text: str=None,\n    ) -> IterationRecord:\n        if text is not None:\n            final_text = text\n        else:\n            if len(args) == 0:\n                raise BotSkeletonException((\"Please provide text either as a positional arg or \"\n                                            \"as a keyword arg (text=TEXT)\"))\n            else:\n                final_text = args[0]\n        record = IterationRecord(extra_keys=self.extra_keys)\n        for key, output in self.outputs.items():\n            if output[\"active\"]:\n                self.log.info(f\"Output {key} is active, calling send on it.\")\n                entry: Any = output[\"obj\"]\n                output_result = entry.send(text=final_text)\n                record.output_records[key] = output_result\n            else:\n                self.log.info(f\"Output {key} is inactive. Not sending.\")\n        self.history.append(record)\n        self.update_history()\n        return record",
    "docstring": "Post text-only to all outputs.\n\n        :param args: positional arguments.\n            expected: text to send as message in post.\n            keyword text argument is preferred over this.\n        :param text: text to send as message in post.\n        :returns: new record of iteration"
  },
  {
    "code": "def process_request(self, request):\n        super(SubdomainURLRoutingMiddleware, self).process_request(request)\n        subdomain = getattr(request, 'subdomain', UNSET)\n        if subdomain is not UNSET:\n            urlconf = settings.SUBDOMAIN_URLCONFS.get(subdomain)\n            if urlconf is not None:\n                logger.debug(\"Using urlconf %s for subdomain: %s\",\n                    repr(urlconf), repr(subdomain))\n                request.urlconf = urlconf",
    "docstring": "Sets the current request's ``urlconf`` attribute to the urlconf\n        associated with the subdomain, if it is listed in\n        ``settings.SUBDOMAIN_URLCONFS``."
  },
  {
    "code": "def exist(self, table: str, libref: str =\"\") -> bool:\n      code  = \"data _null_; e = exist('\"\n      if len(libref):\n         code += libref+\".\"\n      code += table+\"');\\n\"\n      code += \"v = exist('\"\n      if len(libref):\n         code += libref+\".\"\n      code += table+\"', 'VIEW');\\n if e or v then e = 1;\\n\"\n      code += \"te='TABLE_EXISTS='; put te e;run;\"\n      ll = self.submit(code, \"text\")\n      l2 = ll['LOG'].rpartition(\"TABLE_EXISTS= \")\n      l2 = l2[2].partition(\"\\n\")\n      exists = int(l2[0])\n      return bool(exists)",
    "docstring": "table  - the name of the SAS Data Set\n      libref - the libref for the Data Set, defaults to WORK, or USER if assigned\n\n      Returns True it the Data Set exists and False if it does not"
  },
  {
    "code": "def cc(self, cc_emails, global_substitutions=None, is_multiple=False, p=0):\n        if isinstance(cc_emails, list):\n            for email in cc_emails:\n                if isinstance(email, str):\n                    email = Cc(email, None)\n                if isinstance(email, tuple):\n                    email = Cc(email[0], email[1])\n                self.add_cc(email, global_substitutions, is_multiple, p)\n        else:\n            if isinstance(cc_emails, str):\n                cc_emails = Cc(cc_emails, None)\n            if isinstance(cc_emails, tuple):\n                cc_emails = To(cc_emails[0], cc_emails[1])\n            self.add_cc(cc_emails, global_substitutions, is_multiple, p)",
    "docstring": "Adds Cc objects to the Personalization object\n\n        :param cc_emails: An Cc or list of Cc objects\n        :type cc_emails: Cc, list(Cc), tuple\n        :param global_substitutions: A dict of substitutions for all recipients\n        :type global_substitutions: dict\n        :param is_multiple: Create a new personilization for each recipient\n        :type is_multiple: bool\n        :param p: p is the Personalization object or Personalization object\n                  index\n        :type p: Personalization, integer, optional"
  },
  {
    "code": "def search_variant_sets(self, dataset_id):\n        request = protocol.SearchVariantSetsRequest()\n        request.dataset_id = dataset_id\n        request.page_size = pb.int(self._page_size)\n        return self._run_search_request(\n            request, \"variantsets\", protocol.SearchVariantSetsResponse)",
    "docstring": "Returns an iterator over the VariantSets fulfilling the specified\n        conditions from the specified Dataset.\n\n        :param str dataset_id: The ID of the :class:`ga4gh.protocol.Dataset`\n            of interest.\n        :return: An iterator over the :class:`ga4gh.protocol.VariantSet`\n            objects defined by the query parameters."
  },
  {
    "code": "def get_tohu_items_name(cls):\n    assert issubclass(cls, TohuBaseGenerator)\n    try:\n        tohu_items_name = cls.__dict__['__tohu_items_name__']\n        logger.debug(f\"Using item class name '{tohu_items_name}' (derived from attribute '__tohu_items_name__')\")\n    except KeyError:\n        m = re.match('^(.*)Generator$', cls.__name__)\n        if m is not None:\n            tohu_items_name = m.group(1)\n            logger.debug(f\"Using item class name '{tohu_items_name}' (derived from custom generator name)\")\n        else:\n            msg = (\n                \"Cannot derive class name for items to be produced by custom generator. \"\n                \"Please set '__tohu_items_name__' at the top of the custom generator's \"\n                \"definition or change its name so that it ends in '...Generator'\"\n            )\n            raise ValueError(msg)\n    return tohu_items_name",
    "docstring": "Return a string which defines the name of the namedtuple class which will be used\n    to produce items for the custom generator.\n\n    By default this will be the first part of the class name (before '...Generator'),\n    for example:\n\n        FoobarGenerator -> Foobar\n        QuuxGenerator   -> Quux\n\n    However, it can be set explicitly by the user by defining `__tohu_items_name__`\n    in the class definition, for example:\n\n        class Quux(CustomGenerator):\n            __tohu_items_name__ = 'MyQuuxItem'"
  },
  {
    "code": "def terms_required(view_func):\n    @wraps(view_func, assigned=available_attrs(view_func))\n    def _wrapped_view(request, *args, **kwargs):\n        if DJANGO_VERSION <= (2, 0, 0):\n            user_authenticated = request.user.is_authenticated()\n        else:\n            user_authenticated = request.user.is_authenticated\n        if not user_authenticated or not TermsAndConditions.get_active_terms_not_agreed_to(request.user):\n            return view_func(request, *args, **kwargs)\n        current_path = request.path\n        login_url_parts = list(urlparse(ACCEPT_TERMS_PATH))\n        querystring = QueryDict(login_url_parts[4], mutable=True)\n        querystring['returnTo'] = current_path\n        login_url_parts[4] = querystring.urlencode(safe='/')\n        return HttpResponseRedirect(urlunparse(login_url_parts))\n    return _wrapped_view",
    "docstring": "This decorator checks to see if the user is logged in, and if so, if they have accepted the site terms."
  },
  {
    "code": "def get_workflow_config(runtime, code_dir, project_dir):\n    selectors_by_runtime = {\n        \"python2.7\": BasicWorkflowSelector(PYTHON_PIP_CONFIG),\n        \"python3.6\": BasicWorkflowSelector(PYTHON_PIP_CONFIG),\n        \"python3.7\": BasicWorkflowSelector(PYTHON_PIP_CONFIG),\n        \"nodejs4.3\": BasicWorkflowSelector(NODEJS_NPM_CONFIG),\n        \"nodejs6.10\": BasicWorkflowSelector(NODEJS_NPM_CONFIG),\n        \"nodejs8.10\": BasicWorkflowSelector(NODEJS_NPM_CONFIG),\n        \"ruby2.5\": BasicWorkflowSelector(RUBY_BUNDLER_CONFIG),\n        \"dotnetcore2.0\": BasicWorkflowSelector(DOTNET_CLIPACKAGE_CONFIG),\n        \"dotnetcore2.1\": BasicWorkflowSelector(DOTNET_CLIPACKAGE_CONFIG),\n        \"java8\": ManifestWorkflowSelector([\n            JAVA_GRADLE_CONFIG._replace(executable_search_paths=[code_dir, project_dir]),\n            JAVA_KOTLIN_GRADLE_CONFIG._replace(executable_search_paths=[code_dir, project_dir]),\n            JAVA_MAVEN_CONFIG\n        ]),\n    }\n    if runtime not in selectors_by_runtime:\n        raise UnsupportedRuntimeException(\"'{}' runtime is not supported\".format(runtime))\n    selector = selectors_by_runtime[runtime]\n    try:\n        config = selector.get_config(code_dir, project_dir)\n        return config\n    except ValueError as ex:\n        raise UnsupportedRuntimeException(\"Unable to find a supported build workflow for runtime '{}'. Reason: {}\"\n                                          .format(runtime, str(ex)))",
    "docstring": "Get a workflow config that corresponds to the runtime provided. This method examines contents of the project\n    and code directories to determine the most appropriate workflow for the given runtime. Currently the decision is\n    based on the presence of a supported manifest file. For runtimes that have more than one workflow, we choose a\n    workflow by examining ``code_dir`` followed by ``project_dir`` for presence of a supported manifest.\n\n    Parameters\n    ----------\n    runtime str\n        The runtime of the config\n\n    code_dir str\n        Directory where Lambda function code is present\n\n    project_dir str\n        Root of the Serverless application project.\n\n    Returns\n    -------\n    namedtuple(Capability)\n        namedtuple that represents the Builder Workflow Config"
  },
  {
    "code": "def register_service(cls, primary_key_type):\n    view_func = cls.as_view(cls.__name__.lower())\n    methods = set(cls.__model__.__methods__)\n    if 'GET' in methods:\n        current_app.add_url_rule(\n            cls.__model__.__url__ + '/', defaults={'resource_id': None},\n            view_func=view_func,\n            methods=['GET'])\n        current_app.add_url_rule(\n            '{resource}/meta'.format(resource=cls.__model__.__url__),\n            view_func=view_func,\n            methods=['GET'])\n    if 'POST' in methods:\n        current_app.add_url_rule(\n            cls.__model__.__url__ + '/', view_func=view_func, methods=['POST', ])\n    current_app.add_url_rule(\n        '{resource}/<{pk_type}:{pk}>'.format(\n            resource=cls.__model__.__url__,\n            pk='resource_id', pk_type=primary_key_type),\n        view_func=view_func,\n        methods=methods - {'POST'})\n    current_app.classes.append(cls)",
    "docstring": "Register an API service endpoint.\n\n    :param cls: The class to register\n    :param str primary_key_type: The type (as a string) of the primary_key\n                                 field"
  },
  {
    "code": "def _get_final_set(self, sets, pk, sort_options):\n        if self._lazy_collection['intersects']:\n            sets = sets[::]\n            sets.extend(self._lazy_collection['intersects'])\n            if not self._lazy_collection['sets'] and not self.stored_key:\n                sets.append(self.cls.get_field('pk').collection_key)\n        final_set, keys_to_delete_later = super(ExtendedCollectionManager,\n                                    self)._get_final_set(sets, pk, sort_options)\n        if final_set and self._sort_by_sortedset_before:\n            base_tmp_key, tmp_keys = self._prepare_sort_by_score(None, sort_options)\n            if not keys_to_delete_later:\n                keys_to_delete_later = []\n            keys_to_delete_later.append(base_tmp_key)\n            keys_to_delete_later += tmp_keys\n        return final_set, keys_to_delete_later",
    "docstring": "Add intersects fo sets and call parent's _get_final_set.\n        If we have to sort by sorted score, and we have a slice, we have to\n        convert the whole sorted set to keys now."
  },
  {
    "code": "def prefix_shared_name_attributes(meta_graph, absolute_import_scope):\n  shared_name_attr = \"shared_name\"\n  for node in meta_graph.graph_def.node:\n    shared_name_value = node.attr.get(shared_name_attr, None)\n    if shared_name_value and shared_name_value.HasField(\"s\"):\n      if shared_name_value.s:\n        node.attr[shared_name_attr].s = tf.compat.as_bytes(\n            prepend_name_scope(\n                shared_name_value.s, import_scope=absolute_import_scope))",
    "docstring": "In-place prefixes shared_name attributes of nodes."
  },
  {
    "code": "def _set_resultdir(name=None):\n    resultdir_name = name or \"enos_\" + datetime.today().isoformat()\n    resultdir_path = os.path.abspath(resultdir_name)\n    if os.path.isfile(resultdir_path):\n        raise EnosFilePathError(resultdir_path,\n                                \"Result directory cannot be created due \"\n                                \"to existing file %s\" % resultdir_path)\n    if not os.path.isdir(resultdir_path):\n        os.mkdir(resultdir_path)\n        logger.info(\"Generate results directory %s\" % resultdir_path)\n    link_path = SYMLINK_NAME\n    if os.path.lexists(link_path):\n        os.remove(link_path)\n    try:\n        os.symlink(resultdir_path, link_path)\n        logger.info(\"Symlink %s to %s\" % (resultdir_path, link_path))\n    except OSError:\n        logger.warning(\"Symlink %s to %s failed\" %\n                       (resultdir_path, link_path))\n    return resultdir_path",
    "docstring": "Set or get the directory to store experiment results.\n\n\n    Looks at the `name` and create the directory if it doesn\"t exist\n    or returns it in other cases. If the name is `None`, then the\n    function generates an unique name for the results directory.\n    Finally, it links the directory to `SYMLINK_NAME`.\n\n    Args:\n        name (str): file path to an existing directory. It could be\n            weather an absolute or a relative to the current working\n            directory.\n\n    Returns:\n        the file path of the results directory."
  },
  {
    "code": "def associate_keys(user_dict, client):\n    added_keys = user_dict['keypairs']\n    print \">>>Updating Keys-Machines association\"\n    for key in added_keys:\n        machines = added_keys[key]['machines']\n        if machines:\n            try:\n                for machine in machines:\n                    cloud_id = machine[0]\n                    machine_id = machine[1]\n                    ssh_user = machine[3]\n                    ssh_port = machine[-1]\n                    key = client.keys[key]\n                    cloud = cloud_from_id(client, cloud_id)\n                    cloud.update_machines()\n                    mach = machine_from_id(cloud, machine_id)\n                    public_ips = mach.info.get('public_ips', None)\n                    if public_ips:\n                        host = public_ips[0]\n                    else:\n                        host = \"\"\n                    key.associate_to_machine(cloud_id=cloud_id, machine_id=machine_id, host=host, ssh_port=ssh_port,\n                                             ssh_user=ssh_user)\n                    print \"associated machine %s\" % machine_id\n            except Exception as e:\n                pass\n    client.update_keys()\n    print",
    "docstring": "This whole function is black magic, had to however cause of the way we keep key-machine association"
  },
  {
    "code": "def __get_tokens(self, row):\n        row_tokenizer = RowTokenizer(row, self.config)\n        line = row_tokenizer.next()\n        while line:\n            yield line\n            line = row_tokenizer.next()",
    "docstring": "Row should be a single string"
  },
  {
    "code": "def delete_edge_by_id(self, edge_id):\n        edge = self.get_edge(edge_id)\n        from_node_id = edge['vertices'][0]\n        from_node = self.get_node(from_node_id)\n        from_node['edges'].remove(edge_id)\n        to_node_id = edge['vertices'][1]\n        to_node = self.get_node(to_node_id)\n        to_node['edges'].remove(edge_id)\n        del self.edges[edge_id]\n        self._num_edges -= 1",
    "docstring": "Removes the edge identified by \"edge_id\" from the graph."
  },
  {
    "code": "def find_by_id(self, submission_id):\n    return self._attacks.get(\n        submission_id,\n        self._defenses.get(\n            submission_id,\n            self._targeted_attacks.get(submission_id, None)))",
    "docstring": "Finds submission by ID.\n\n    Args:\n      submission_id: ID of the submission\n\n    Returns:\n      SubmissionDescriptor with information about submission or None if\n      submission is not found."
  },
  {
    "code": "def pad(attrs, inputs, proto_obj):\n    new_attrs = translation_utils._fix_attribute_names(attrs, {'pads'  : 'pad_width',\n                                                               'value' : 'constant_value'\n                                                              })\n    new_attrs['pad_width'] = translation_utils._pad_sequence_fix(new_attrs.get('pad_width'))\n    return 'pad', new_attrs, inputs",
    "docstring": "Add padding to input tensor"
  },
  {
    "code": "def match_handle(loc, tokens):\n    if len(tokens) == 4:\n        matches, match_type, item, stmts = tokens\n        cond = None\n    elif len(tokens) == 5:\n        matches, match_type, item, cond, stmts = tokens\n    else:\n        raise CoconutInternalException(\"invalid match statement tokens\", tokens)\n    if match_type == \"in\":\n        invert = False\n    elif match_type == \"not in\":\n        invert = True\n    else:\n        raise CoconutInternalException(\"invalid match type\", match_type)\n    matching = Matcher(loc, match_check_var)\n    matching.match(matches, match_to_var)\n    if cond:\n        matching.add_guard(cond)\n    return (\n        match_to_var + \" = \" + item + \"\\n\"\n        + matching.build(stmts, invert=invert)\n    )",
    "docstring": "Process match blocks."
  },
  {
    "code": "def wait_for_bump(self, buttons, timeout_ms=None):\n        start_time = time.time()\n        if self.wait_for_pressed(buttons, timeout_ms):\n            if timeout_ms is not None:\n                timeout_ms -= int((time.time() - start_time) * 1000)\n            return self.wait_for_released(buttons, timeout_ms)\n        return False",
    "docstring": "Wait for the button to be pressed down and then released.\n        Both actions must happen within timeout_ms."
  },
  {
    "code": "def namer(cls, imageUrl, pageUrl):\n        parts, year, month, stripname = pageUrl.rsplit('/', 3)\n        stripname = stripname.rsplit('.', 1)[0]\n        parts, imagename = imageUrl.rsplit('/', 1)\n        return '%s-%s-%s-%s' % (year, month, stripname, imagename)",
    "docstring": "Use page URL to construct meaningful image name."
  },
  {
    "code": "def _call(self, x):\n        return sum(fi(xi) for xi, fi in zip(x, self.functionals))",
    "docstring": "Return the separable sum evaluated in ``x``."
  },
  {
    "code": "def replace_filehandler(logname, new_file, level=None, frmt=None):\n    log = logging.getLogger(logname)\n    if level is not None:\n        level = get_level(level)\n        explicit_level = True\n    else:\n        level = logging.DEBUG\n        explicit_level = False\n    if frmt is not None:\n        frmt = logging.Formatter(frmt)\n        explicit_frmt = True\n    else:\n        frmt = logging.Formatter(STANDARD_FORMAT)\n        explicit_frmt = False\n    old_filehandler = None\n    for handler in log.handlers:\n        if type(handler) == logging.FileHandler:\n            old_filehandler = handler\n            if not explicit_level:\n                level = handler.level\n            if not explicit_frmt:\n                frmt = handler.formatter\n            break\n    new_filehandler = logging.FileHandler(new_file)\n    new_filehandler.setLevel(level)\n    new_filehandler.setFormatter(frmt)\n    log.addHandler(new_filehandler)\n    if old_filehandler is not None:\n        old_filehandler.close()\n        log.removeHandler(old_filehandler)",
    "docstring": "This utility function will remove a previous Logger FileHandler, if one\n    exists, and add a new filehandler.\n\n    Parameters:\n      logname\n          The name of the log to reconfigure, 'openaccess_epub' for example\n      new_file\n          The file location for the new FileHandler\n      level\n          Optional. Level of FileHandler logging, if not used then the new\n          FileHandler will have the same level as the old. Pass in name strings,\n          'INFO' for example\n      frmt\n          Optional string format of Formatter for the FileHandler, if not used\n          then the new FileHandler will inherit the Formatter of the old, pass\n          in format strings, '%(message)s' for example\n\n    It is best practice to use the optional level and frmt arguments to account\n    for the case where a previous FileHandler does not exist. In the case that\n    they are not used and a previous FileHandler is not found, then the level\n    will be set logging.DEBUG and the frmt will be set to\n    openaccess_epub.utils.logs.STANDARD_FORMAT as a matter of safety."
  },
  {
    "code": "def Shift(self, term):\n        new = self.Copy()\n        new.xs = [x + term for x in self.xs]\n        return new",
    "docstring": "Adds a term to the xs.\n\n        term: how much to add"
  },
  {
    "code": "def isNonNegative(matrix):\n    try:\n        if (matrix >= 0).all():\n            return True\n    except (NotImplementedError, AttributeError, TypeError):\n        try:\n            if (matrix.data >= 0).all():\n                return True\n        except AttributeError:\n            matrix = _np.array(matrix)\n            if (matrix.data >= 0).all():\n                return True\n    return False",
    "docstring": "Check that ``matrix`` is row non-negative.\n\n    Returns\n    =======\n    is_stochastic : bool\n        ``True`` if ``matrix`` is non-negative, ``False`` otherwise."
  },
  {
    "code": "def build_graph(self):\n    import tensorflow as tf\n    input_jpeg = tf.placeholder(tf.string, shape=None)\n    image = tf.image.decode_jpeg(input_jpeg, channels=self.CHANNELS)\n    image = tf.expand_dims(image, 0)\n    image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n    image = tf.image.resize_bilinear(\n        image, [self.HEIGHT, self.WIDTH], align_corners=False)\n    image = tf.subtract(image, 0.5)\n    inception_input = tf.multiply(image, 2.0)\n    with tf.contrib.slim.arg_scope(_inceptionlib.inception_v3_arg_scope()):\n      _, end_points = _inceptionlib.inception_v3(inception_input, is_training=False)\n    embedding = end_points['PreLogits']\n    return input_jpeg, embedding",
    "docstring": "Forms the core by building a wrapper around the inception graph.\n\n      Here we add the necessary input & output tensors, to decode jpegs,\n      serialize embeddings, restore from checkpoint etc.\n\n      To use other Inception models modify this file. Note that to use other\n      models beside Inception, you should make sure input_shape matches\n      their input. Resizing or other modifications may be necessary as well.\n      See tensorflow/contrib/slim/python/slim/nets/inception_v3.py for\n      details about InceptionV3.\n\n    Returns:\n      input_jpeg: A tensor containing raw image bytes as the input layer.\n      embedding: The embeddings tensor, that will be materialized later."
  },
  {
    "code": "def read_cf1_config(self):\n        target = self._cload.targets[0xFF]\n        config_page = target.flash_pages - 1\n        return self._cload.read_flash(addr=0xFF, page=config_page)",
    "docstring": "Read a flash page from the specified target"
  },
  {
    "code": "def is_directory(path, use_sudo=False):\n    result = single_line_stdout('if [[ -f {0} ]]; then echo 0; elif [[ -d {0} ]]; then echo 1; else echo -1; fi'.format(path), sudo=use_sudo, quiet=True)\n    if result == '0':\n        return False\n    elif result == '1':\n        return True\n    else:\n        return None",
    "docstring": "Check if the remote path exists and is a directory.\n\n    :param path: Remote path to check.\n    :type path: unicode\n    :param use_sudo: Use the `sudo` command.\n    :type use_sudo: bool\n    :return: `True` if the path exists and is a directory; `False` if it exists, but is a file; `None` if it does not\n      exist.\n    :rtype: bool or ``None``"
  },
  {
    "code": "def initialize_logging(self):\n        for loggername in [None] + list(logging.Logger.manager.loggerDict.keys()):\n            logger = logging.getLogger(loggername)\n            while logger.handlers:\n                logger.removeHandler(logger.handlers[0])\n        root_logger = logging.getLogger()\n        root_logger.setLevel(logging.WARN)\n        root_logger.addHandler(workflows.logging.CallbackHandler(self._log_send))\n        self.log = logging.getLogger(self._logger_name)\n        if self.start_kwargs.get(\"verbose_log\"):\n            self.log_verbosity = logging.DEBUG\n        self.log.setLevel(self.log_verbosity)\n        console = logging.StreamHandler()\n        console.setLevel(logging.CRITICAL)\n        root_logger.addHandler(console)",
    "docstring": "Reset the logging for the service process. All logged messages are\n        forwarded to the frontend. If any filtering is desired, then this must\n        take place on the service side."
  },
  {
    "code": "def safe_lshift(a, b):\n    if b > MAX_SHIFT:\n        raise RuntimeError(\"Invalid left shift, max left shift is {}\".format(MAX_SHIFT))\n    return a << b",
    "docstring": "safe version of lshift"
  },
  {
    "code": "def get_index_by_id(self, id):\n        for i in range(len(self.vertices)):\n            if self.vertices[i].id == id:\n                return i\n        raise ValueError('Reverse look up of id failed.')",
    "docstring": "Give the index associated with a given vertex id."
  },
  {
    "code": "def unproxy(possible_proxy):\n        while isinstance(possible_proxy, ThreadLocalProxy):\n            possible_proxy = ThreadLocalProxy.get_reference(possible_proxy)\n        return possible_proxy",
    "docstring": "Unwrap and return the object referenced by a proxy.\n\n        This function is very similar to :func:`get_reference`, but works for\n        both proxies and regular objects. If the specified object is a proxy,\n        its reference is extracted with ``get_reference`` and returned. If it\n        is not a proxy, it is returned as is.\n\n        If the object references by the proxy is itself a proxy, the unwrapping\n        is repeated until a regular (non-proxy) object is found.\n\n        possible_proxy:\n            object that might or might not be a proxy."
  },
  {
    "code": "def show_content(self, state_model):\n        upper_most_lib_state_m = None\n        if isinstance(state_model, LibraryStateModel):\n            uppermost_library_root_state = state_model.state.get_uppermost_library_root_state()\n            if uppermost_library_root_state is None:\n                upper_most_lib_state_m = state_model\n            else:\n                upper_lib_state = uppermost_library_root_state.parent\n                upper_most_lib_state_m = self._selected_sm_model.get_state_model_by_path(upper_lib_state.get_path())\n        if upper_most_lib_state_m:\n            return upper_most_lib_state_m.show_content()\n        else:\n            return True",
    "docstring": "Check state machine tree specific show content flag.\n\n        Is returning true if the upper most library state of a state model has a enabled show content flag or if there\n        is no library root state above this state.\n\n        :param rafcon.gui.models.abstract_state.AbstractStateModel state_model: The state model to check"
  },
  {
    "code": "def minimize_source(source):\n    source = mitogen.core.to_text(source)\n    tokens = tokenize.generate_tokens(StringIO(source).readline)\n    tokens = strip_comments(tokens)\n    tokens = strip_docstrings(tokens)\n    tokens = reindent(tokens)\n    return tokenize.untokenize(tokens)",
    "docstring": "Remove comments and docstrings from Python `source`, preserving line\n    numbers and syntax of empty blocks.\n\n    :param str source:\n        The source to minimize.\n\n    :returns str:\n        The minimized source."
  },
  {
    "code": "def optional_install():\n    print('{BOLD}Setting up Reduce (optional){END_C}'.format(**text_colours))\n    reduce = {}\n    reduce_path = get_user_path('Please provide a path to your reduce executable.', required=False)\n    reduce['path'] = str(reduce_path)\n    reduce['folder'] = str(reduce_path.parent) if reduce_path else ''\n    settings['reduce'] = reduce\n    print('{BOLD}Setting up naccess (optional){END_C}'.format(**text_colours))\n    naccess = {}\n    naccess_path = get_user_path('Please provide a path to your naccess executable.', required=False)\n    naccess['path'] = str(naccess_path)\n    settings['naccess'] = naccess\n    print('{BOLD}Setting up ProFit (optional){END_C}'.format(**text_colours))\n    profit = {}\n    profit_path = get_user_path('Please provide a path to your ProFit executable.', required=False)\n    profit['path'] = str(profit_path)\n    settings['profit'] = profit\n    return",
    "docstring": "Generates configuration settings for optional functionality of ISAMBARD."
  },
  {
    "code": "def _GenerateNonImplementedMethod(self, method):\n    return lambda inst, rpc_controller, request, callback: (\n        self._NonImplementedMethod(method.name, rpc_controller, callback))",
    "docstring": "Generates and returns a method that can be set for a service methods.\n\n    Args:\n      method: Descriptor of the service method for which a method is to be\n        generated.\n\n    Returns:\n      A method that can be added to the service class."
  },
  {
    "code": "def _find_adapter(registry, ob):\n    types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))\n    for t in types:\n        if t in registry:\n            return registry[t]",
    "docstring": "Return an adapter factory for `ob` from `registry`"
  },
  {
    "code": "def make_bin_array(bins) -> np.ndarray:\n    bins = np.asarray(bins)\n    if bins.ndim == 1:\n        return np.hstack((bins[:-1, np.newaxis], bins[1:, np.newaxis]))\n    elif bins.ndim == 2:\n        if bins.shape[1] != 2:\n            raise RuntimeError(\"Binning schema with ndim==2 must have 2 columns\")\n        return bins\n    else:\n        raise RuntimeError(\"Binning schema must have ndim==1 or ndim==2\")",
    "docstring": "Turn bin data into array understood by HistogramXX classes.\n\n    Parameters\n    ----------\n    bins: array_like\n        Array of edges or array of edge tuples\n\n    Examples\n    --------\n    >>> make_bin_array([0, 1, 2])\n    array([[0, 1],\n           [1, 2]])\n    >>> make_bin_array([[0, 1], [2, 3]])\n    array([[0, 1],\n           [2, 3]])"
  },
  {
    "code": "def thread(function):\n    @wraps(function)\n    def wrapper(*args, **kwargs):\n        future = Future()\n        launch_thread(_function_handler, function, args, kwargs, future)\n        return future\n    return wrapper",
    "docstring": "Runs the decorated function within a concurrent thread,\n    taking care of the result and error management.\n\n    Decorated functions will return a concurrent.futures.Future object\n    once called."
  },
  {
    "code": "def agent_reqs():\n    echo_info(\"Validating requirements-agent-release.txt...\")\n    agent_reqs_content = parse_agent_req_file(read_file(get_agent_release_requirements()))\n    ok_checks = 0\n    unreleased_checks = 0\n    failed_checks = 0\n    for check_name in get_valid_checks():\n        if check_name not in AGENT_V5_ONLY | NOT_CHECKS:\n            package_name = get_package_name(check_name)\n            check_version = get_version_string(check_name)\n            pinned_version = agent_reqs_content.get(package_name)\n            if package_name not in agent_reqs_content:\n                unreleased_checks += 1\n                echo_warning('{} has not yet been released'.format(check_name))\n            elif check_version != pinned_version:\n                failed_checks += 1\n                echo_failure(\"{} has version {} but is pinned to {}\".format(check_name, check_version, pinned_version))\n            else:\n                ok_checks += 1\n    if ok_checks:\n        echo_success(\"{} correctly pinned checks\".format(ok_checks))\n    if unreleased_checks:\n        echo_warning(\"{} unreleased checks\".format(unreleased_checks))\n    if failed_checks:\n        echo_failure(\"{} checks out of sync\".format(failed_checks))\n        abort()",
    "docstring": "Verify that the checks versions are in sync with the requirements-agent-release.txt file"
  },
  {
    "code": "def match_event_roll_lengths(event_roll_a, event_roll_b, length=None):\n    if length is None:\n        length = max(event_roll_b.shape[0], event_roll_a.shape[0])\n    else:\n        length = int(length)\n    if length < event_roll_a.shape[0]:\n        event_roll_a = event_roll_a[0:length, :]\n    else:\n        event_roll_a = pad_event_roll(\n            event_roll=event_roll_a,\n            length=length\n        )\n    if length < event_roll_b.shape[0]:\n        event_roll_b = event_roll_b[0:length, :]\n    else:\n        event_roll_b = pad_event_roll(\n            event_roll=event_roll_b,\n            length=length\n        )\n    return event_roll_a, event_roll_b",
    "docstring": "Fix the length of two event rolls\n\n    Parameters\n    ----------\n    event_roll_a: np.ndarray, shape=(m1,k)\n        Event roll A\n\n    event_roll_b: np.ndarray, shape=(m2,k)\n        Event roll B\n\n    length: int, optional\n        Length of the event roll, if none given, shorter event roll is padded to match longer one.\n\n    Returns\n    -------\n    event_roll_a: np.ndarray, shape=(max(m1,m2),k)\n        Padded event roll A\n\n    event_roll_b: np.ndarray, shape=(max(m1,m2),k)\n        Padded event roll B"
  },
  {
    "code": "def format_help(self):\n        if self._subparsers:\n            for action in self._subparsers._actions:\n                if isinstance(action, LazySubParsersAction):\n                    for parser_name, parser in action._name_parser_map.iteritems():\n                        action._setup_subparser(parser_name, parser)\n        return super(LazyArgumentParser, self).format_help()",
    "docstring": "Sets up all sub-parsers when help is requested."
  },
  {
    "code": "def modify_class(original_class, modifier_class, override=True):\n    modifier_methods = inspect.getmembers(modifier_class, inspect.ismethod)\n    for method_tuple in modifier_methods:\n        name = method_tuple[0]\n        method = method_tuple[1]\n        if isinstance(method, types.UnboundMethodType):\n            if hasattr(original_class, name) and not override:\n                return None\n            else:\n                setattr(original_class, name, method.im_func)",
    "docstring": "Adds class methods from modifier_class to original_class.\n    If override is True existing methods in original_class are overriden by those provided by modifier_class."
  },
  {
    "code": "def get_config(self):\n        config = super(BoltzmannGumbelQPolicy, self).get_config()\n        config['C'] = self.C\n        return config",
    "docstring": "Return configurations of BoltzmannGumbelQPolicy\n\n        # Returns\n            Dict of config"
  },
  {
    "code": "def delete_migration(connection, basename):\n    sql = \"DELETE FROM migrations_applied WHERE name = %s\"\n    with connection.cursor() as cursor:\n        cursor.execute(sql, (basename,))\n        connection.commit()\n    return True",
    "docstring": "Delete a migration in `migrations_applied` table"
  },
  {
    "code": "def validate(self, instance, value):\n        if not isinstance(value, (tuple, list, np.ndarray)):\n            self.error(instance, value)\n        if self.coerce:\n            value = self.wrapper(value)\n        valid_class = (\n            self.wrapper if isinstance(self.wrapper, type) else np.ndarray\n        )\n        if not isinstance(value, valid_class):\n            self.error(instance, value)\n        allowed_kinds = ''.join(TYPE_MAPPINGS[typ] for typ in self.dtype)\n        if value.dtype.kind not in allowed_kinds:\n            self.error(instance, value, extra='Invalid dtype.')\n        if self.shape is None:\n            return value\n        for shape in self.shape:\n            if len(shape) != value.ndim:\n                continue\n            for i, shp in enumerate(shape):\n                if shp not in ('*', value.shape[i]):\n                    break\n            else:\n                return value\n        self.error(instance, value, extra='Invalid shape.')",
    "docstring": "Determine if array is valid based on shape and dtype"
  },
  {
    "code": "def install(self, release_id):\n        release_path = os.path.join(self._releases, release_id)\n        if not self._runner.exists(release_path):\n            self._runner.run(\"mkdir -p '{0}'\".format(release_path))\n        if self._remote_name is not None:\n            destination = os.path.join(release_path, self._remote_name)\n        else:\n            destination = os.path.join(release_path, self._get_file_from_url(self._artifact_url))\n        return self._downloader(\n            self._artifact_url,\n            destination,\n            retries=self._retries,\n            retry_delay=self._retry_delay\n        )",
    "docstring": "Download and install an artifact into the remote release directory,\n        optionally with a different name the the artifact had.\n\n        If the directory for the given release ID does not exist on the remote\n        system, it will be created. The directory will be created according to\n        the standard Tunic directory structure (see :doc:`design`).\n\n        :param str release_id: Timestamp-based identifier for this deployment.\n        :return: The results of the download function being run. This return value\n            should be the result of running a command with Fabric. By default\n            this will be the result of running ``wget``."
  },
  {
    "code": "def _force(self,obj,objtype=None):\n        gen=super(Dynamic,self).__get__(obj,objtype)\n        if hasattr(gen,'_Dynamic_last'):\n            return self._produce_value(gen,force=True)\n        else:\n            return gen",
    "docstring": "Force a new value to be generated, and return it."
  },
  {
    "code": "def create_media_asset(access_token, name, options=\"0\"):\n    path = '/Assets'\n    endpoint = ''.join([ams_rest_endpoint, path])\n    body = '{\"Name\": \"' + name + '\", \"Options\": \"' + str(options) + '\"}'\n    return do_ams_post(endpoint, path, body, access_token)",
    "docstring": "Create Media Service Asset.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        name (str): Media Service Asset Name.\n        options (str): Media Service Options.\n\n    Returns:\n        HTTP response. JSON body."
  },
  {
    "code": "def _build_join(t):\n    t.source.name = t.source.parsed_name\n    t.source.alias = t.source.parsed_alias[0] if t.source.parsed_alias else ''\n    return t",
    "docstring": "Populates join token fields."
  },
  {
    "code": "def styleInheritedByChild(node, style, nodeIsChild=False):\n    if node.nodeType != Node.ELEMENT_NODE:\n        return False\n    if nodeIsChild:\n        if node.getAttribute(style) not in ['', 'inherit']:\n            return False\n        styles = _getStyle(node)\n        if (style in styles) and not (styles[style] == 'inherit'):\n            return False\n    else:\n        if not node.childNodes:\n            return False\n    if node.childNodes:\n        for child in node.childNodes:\n            if styleInheritedByChild(child, style, True):\n                return True\n    if node.nodeName in ['a', 'defs', 'glyph', 'g', 'marker', 'mask',\n                         'missing-glyph', 'pattern', 'svg', 'switch', 'symbol']:\n        return False\n    return True",
    "docstring": "Returns whether 'style' is inherited by any children of the passed-in node\n\n    If False is returned, it is guaranteed that 'style' can safely be removed\n    from the passed-in node without influencing visual output of it's children\n\n    If True is returned, the passed-in node should not have its text-based\n    attributes removed.\n\n    Warning: This method only considers presentation attributes and inline styles,\n             any style sheets are ignored!"
  },
  {
    "code": "def execute_step(self, step):\n        inputs = self.get_inputs(step.ins)\n        outputs = defaultdict(list)\n        for output in step.run(inputs):\n            for k, v in output.items():\n                outputs[k].extend(v)\n        for output in step.finalise():\n            for k, v in output.items():\n                outputs[k].extend(v)\n        self.unresolved_steps.remove(step)\n        return outputs",
    "docstring": "Execute the named step. Also control the multiplicity of input and output entities\n\n        :param step: step to prepare input for\n        :param kwargs: input to be prepared\n        :return: dict of output by entity type"
  },
  {
    "code": "def _get_file(self):\n        f = tempfile.NamedTemporaryFile(delete=False)\n        self.tmp_files.add(f.name)\n        return f",
    "docstring": "return an opened tempfile pointer that can be used\n\n        http://docs.python.org/2/library/tempfile.html"
  },
  {
    "code": "def loadJSON(self, json_string):\n        g = get_root(self).globals\n        user = json.loads(json_string)['user']\n        def setField(widget, field):\n            val = user.get(field)\n            if val is not None:\n                widget.set(val)\n        setField(self.prog_ob.obid, 'OB')\n        setField(self.target, 'target')\n        setField(self.prog_ob.progid, 'ID')\n        setField(self.pi, 'PI')\n        setField(self.observers, 'Observers')\n        setField(self.comment, 'comment')\n        setField(self.filter, 'filters')\n        setField(g.observe.rtype, 'flags')",
    "docstring": "Sets the values of the run parameters given an JSON string"
  },
  {
    "code": "def random_game(nums_actions, random_state=None):\n    N = len(nums_actions)\n    if N == 0:\n        raise ValueError('nums_actions must be non-empty')\n    random_state = check_random_state(random_state)\n    players = [\n        Player(random_state.random_sample(nums_actions[i:]+nums_actions[:i]))\n        for i in range(N)\n    ]\n    g = NormalFormGame(players)\n    return g",
    "docstring": "Return a random NormalFormGame instance where the payoffs are drawn\n    independently from the uniform distribution on [0, 1).\n\n    Parameters\n    ----------\n    nums_actions : tuple(int)\n        Tuple of the numbers of actions, one for each player.\n\n    random_state : int or np.random.RandomState, optional\n        Random seed (integer) or np.random.RandomState instance to set\n        the initial state of the random number generator for\n        reproducibility. If None, a randomly initialized RandomState is\n        used.\n\n    Returns\n    -------\n    g : NormalFormGame"
  },
  {
    "code": "def execute_ls(host_list, remote_user, remote_pass):\n    runner = spam.ansirunner.AnsibleRunner()\n    result, failed_hosts = runner.ansible_perform_operation(\n        host_list=host_list,\n        remote_user=remote_user,\n        remote_pass=remote_pass,\n        module=\"command\",\n        module_args=\"ls -1\")\n    print \"Result: \", result",
    "docstring": "Execute any adhoc command on the hosts."
  },
  {
    "code": "def sample_poly(self, poly, penalty_strength=1.0,\n                    keep_penalty_variables=False,\n                    discard_unsatisfied=False, **parameters):\n        bqm = make_quadratic(poly, penalty_strength, vartype=poly.vartype)\n        response = self.child.sample(bqm, **parameters)\n        return polymorph_response(response, poly, bqm,\n                                  penalty_strength=penalty_strength,\n                                  keep_penalty_variables=keep_penalty_variables,\n                                  discard_unsatisfied=discard_unsatisfied)",
    "docstring": "Sample from the given binary polynomial.\n\n        Takes the given binary polynomial, introduces penalties, reduces the\n        higher-order problem into a quadratic problem and sends it to its child\n        sampler.\n\n        Args:\n            poly (:obj:`.BinaryPolynomial`):\n                A binary polynomial.\n\n            penalty_strength (float, optional): Strength of the reduction constraint.\n                Insufficient strength can result in the binary quadratic model\n                not having the same minimization as the polynomial.\n\n            keep_penalty_variables (bool, optional): default is True. if False\n                will remove the variables used for penalty from the samples\n\n            discard_unsatisfied (bool, optional): default is False. If True\n                will discard samples that do not satisfy the penalty conditions.\n\n            **parameters: Parameters for the sampling method, specified by\n            the child sampler.\n\n        Returns:\n            :obj:`dimod.SampleSet`"
  },
  {
    "code": "def read(self):\n        assert os.path.isfile(self.file_path), 'No such file exists: ' + str(self.file_path)\n        with open(self.file_path, 'r') as f:\n            reader = csv_builtin.reader(f)\n            loaded_data = list(reader)\n        return juggle_types(loaded_data)",
    "docstring": "Reads CSV file and returns list of contents"
  },
  {
    "code": "def __get_bit_values(self, number, size=32):\n        res = list(self.__gen_bit_values(number))\n        res.reverse()\n        res = [0] * (size - len(res)) + res\n        return res",
    "docstring": "Get bit values as a list for a given number\n\n        >>> get_bit_values(1) == [0]*31 + [1]\n        True\n\n        >>> get_bit_values(0xDEADBEEF)\n        [1L, 1L, 0L, 1L, 1L, 1L, 1L,\n        0L, 1L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L,\n        1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L]\n\n        You may override the default word size of 32-bits to match your actual\n        application.\n        >>> get_bit_values(0x3, 2)\n        [1L, 1L]\n\n        >>> get_bit_values(0x3, 4)\n        [0L, 0L, 1L, 1L]"
  },
  {
    "code": "def delete(self):\n        if self._writeable:\n            self._write(('CRVDEL', Integer), self.idx)\n        else:\n            raise RuntimeError('Can not delete read-only curves.')",
    "docstring": "Deletes the current curve.\n\n        :raises RuntimeError: Raises when` when one tries to delete a read-only\n            curve."
  },
  {
    "code": "def data(self):\n        try:\n            request_body_size = int(self.environ.get('CONTENT_LENGTH', 0))\n        except (ValueError):\n            request_body_size = 0\n        data = self.environ['wsgi.input'].read(request_body_size)\n        return data",
    "docstring": "Returns the data sent with the request."
  },
  {
    "code": "def configure_sentry_errors(self):\n        sentry_errors_logger = logging.getLogger('sentry.errors')\n        root_logger = logging.getLogger()\n        for handler in root_logger.handlers:\n            sentry_errors_logger.addHandler(handler)",
    "docstring": "Configure sentry.errors to use the same loggers as the root handler\n        @rtype: None"
  },
  {
    "code": "def _list_function_infos(jvm):\n    jinfos = jvm.org.apache.spark.sql.api.python.PythonSQLUtils.listBuiltinFunctionInfos()\n    infos = []\n    for jinfo in jinfos:\n        name = jinfo.getName()\n        usage = jinfo.getUsage()\n        usage = usage.replace(\"_FUNC_\", name) if usage is not None else usage\n        infos.append(ExpressionInfo(\n            className=jinfo.getClassName(),\n            name=name,\n            usage=usage,\n            arguments=jinfo.getArguments().replace(\"_FUNC_\", name),\n            examples=jinfo.getExamples().replace(\"_FUNC_\", name),\n            note=jinfo.getNote(),\n            since=jinfo.getSince(),\n            deprecated=jinfo.getDeprecated()))\n    return sorted(infos, key=lambda i: i.name)",
    "docstring": "Returns a list of function information via JVM. Sorts wrapped expression infos by name\n    and returns them."
  },
  {
    "code": "def set(self, key, value):\n        self._full_config = None\n        self._override[key] = value",
    "docstring": "Set a value in the `Bison` configuration.\n\n        Args:\n            key (str): The configuration key to set a new value for.\n            value: The value to set."
  },
  {
    "code": "def construct_stable_id(\n    parent_context,\n    polymorphic_type,\n    relative_char_offset_start,\n    relative_char_offset_end,\n):\n    doc_id, _, parent_doc_char_start, _ = split_stable_id(parent_context.stable_id)\n    start = parent_doc_char_start + relative_char_offset_start\n    end = parent_doc_char_start + relative_char_offset_end\n    return f\"{doc_id}::{polymorphic_type}:{start}:{end}\"",
    "docstring": "Contruct a stable ID for a Context given its parent and its character\n    offsets relative to the parent."
  },
  {
    "code": "def get(self, sid):\n        return ChannelContext(self._version, service_sid=self._solution['service_sid'], sid=sid, )",
    "docstring": "Constructs a ChannelContext\n\n        :param sid: The sid\n\n        :returns: twilio.rest.chat.v1.service.channel.ChannelContext\n        :rtype: twilio.rest.chat.v1.service.channel.ChannelContext"
  },
  {
    "code": "def create_unsigned_transaction(cls,\n                                    *,\n                                    nonce: int,\n                                    gas_price: int,\n                                    gas: int,\n                                    to: Address,\n                                    value: int,\n                                    data: bytes) -> 'BaseUnsignedTransaction':\n        return cls.get_transaction_class().create_unsigned_transaction(\n            nonce=nonce,\n            gas_price=gas_price,\n            gas=gas,\n            to=to,\n            value=value,\n            data=data\n        )",
    "docstring": "Proxy for instantiating an unsigned transaction for this VM."
  },
  {
    "code": "def artUrl(self):\n        art = self.firstAttr('art', 'grandparentArt')\n        return self._server.url(art, includeToken=True) if art else None",
    "docstring": "Return the first first art url starting on the most specific for that item."
  },
  {
    "code": "def extendMarkdown(self, md, md_globals=None):\n        if any(\n                x not in md.treeprocessors\n                for x in self.REQUIRED_EXTENSION_INTERNAL_NAMES):\n            raise RuntimeError(\n                \"The attr_cols markdown extension depends the following\"\n                \" extensions which must preceded it in the extension\"\n                \" list: %s\" % \", \".join(self.REQUIRED_EXTENSIONS))\n        processor = AttrColTreeProcessor(md, self.conf)\n        md.treeprocessors.register(\n            processor, 'attr_cols',\n            5)",
    "docstring": "Initializes markdown extension components."
  },
  {
    "code": "def side_task(pipe, *side_jobs):\n    assert iterable(pipe), 'side_task needs the first argument to be iterable'\n    for sj in side_jobs:\n        assert callable(sj), 'all side_jobs need to be functions, not {}'.format(sj)\n    side_jobs = (lambda i:i ,) + side_jobs\n    for i in map(pipe, *side_jobs):\n        yield i[0]",
    "docstring": "allows you to run a function in a pipeline without affecting the data"
  },
  {
    "code": "def _extract_axes_for_slice(self, axes):\n        return {self._AXIS_SLICEMAP[i]: a for i, a in\n                zip(self._AXIS_ORDERS[self._AXIS_LEN - len(axes):], axes)}",
    "docstring": "Return the slice dictionary for these axes."
  },
  {
    "code": "def check_exists_repositories(repo):\n    pkg_list = \"PACKAGES.TXT\"\n    if repo == \"sbo\":\n        pkg_list = \"SLACKBUILDS.TXT\"\n    if check_for_local_repos(repo) is True:\n        pkg_list = \"PACKAGES.TXT\"\n        return \"\"\n    if not os.path.isfile(\"{0}{1}{2}\".format(\n            _meta_.lib_path, repo, \"_repo/{0}\".format(pkg_list))):\n        return repo\n    return \"\"",
    "docstring": "Checking if repositories exists by PACKAGES.TXT file"
  },
  {
    "code": "def keyframe(self, index):\n        index = int(index)\n        if index < 0:\n            index %= len(self)\n        if self._keyframe.index == index:\n            return\n        if index == 0:\n            self._keyframe = self.pages[0]\n            return\n        if self._indexed or index < len(self.pages):\n            page = self.pages[index]\n            if isinstance(page, TiffPage):\n                self._keyframe = page\n                return\n            if isinstance(page, TiffFrame):\n                self.pages[index] = page.offset\n        tiffpage = self._tiffpage\n        self._tiffpage = TiffPage\n        try:\n            self._keyframe = self._getitem(index)\n        finally:\n            self._tiffpage = tiffpage\n        self.pages[index] = self._keyframe",
    "docstring": "Set current keyframe. Load TiffPage from file if necessary."
  },
  {
    "code": "def multi_replace(instr, search_list=[], repl_list=None):\n    repl_list = [''] * len(search_list) if repl_list is None else repl_list\n    for ser, repl in zip(search_list, repl_list):\n        instr = instr.replace(ser, repl)\n    return instr",
    "docstring": "Does a string replace with a list of search and replacements\n\n    TODO: rename"
  },
  {
    "code": "def from_data(cls, data):\n        if not data.shape[1] == 3:\n            raise ValueError(\"Gyroscope data must have shape (N, 3)\")\n        instance = cls()\n        instance.data = data\n        return instance",
    "docstring": "Create gyroscope stream from data array\n\n        Parameters\n        -------------------\n        data : (N, 3) ndarray\n            Data array of angular velocities (rad/s)\n\n        Returns\n        -------------------\n        GyroStream\n            Stream object"
  },
  {
    "code": "def fetch_hg_push_log(repo_name, repo_url):\n    newrelic.agent.add_custom_parameter(\"repo_name\", repo_name)\n    process = HgPushlogProcess()\n    process.run(repo_url + '/json-pushes/?full=1&version=2', repo_name)",
    "docstring": "Run a HgPushlog etl process"
  },
  {
    "code": "def _update(self):\n        aps = []\n        for k, v in self.records.items():\n            recall, prec = self._recall_prec(v, self.counts[k])\n            ap = self._average_precision(recall, prec)\n            aps.append(ap)\n            if self.num is not None and k < (self.num - 1):\n                self.sum_metric[k] = ap\n                self.num_inst[k] = 1\n        if self.num is None:\n            self.num_inst = 1\n            self.sum_metric = np.mean(aps)\n        else:\n            self.num_inst[-1] = 1\n            self.sum_metric[-1] = np.mean(aps)",
    "docstring": "update num_inst and sum_metric"
  },
  {
    "code": "def send(self, message):\n        message = message.SerializeToString()\n        self.socket.sendall(struct.pack('!I', len(message)) + message)\n        length = struct.unpack('!I', self.socket.recv(4))[0]\n        response = riemann_client.riemann_pb2.Msg()\n        response.ParseFromString(socket_recvall(self.socket, length))\n        if not response.ok:\n            raise RiemannError(response.error)\n        return response",
    "docstring": "Sends a message to a Riemann server and returns it's response\n\n        :param message: The message to send to the Riemann server\n        :returns: The response message from Riemann\n        :raises RiemannError: if the server returns an error"
  },
  {
    "code": "def environment_failure(self, error):\n        log.exception(\n            'Failed to create environment for %s: %s',\n            self.__class__.__name__, get_error_message(error)\n        )\n        self.shutdown(error)",
    "docstring": "Log environment failure for the daemon and exit with the error code.\n\n        :param error:\n        :return:"
  },
  {
    "code": "def get_process_token():\n\ttoken = wintypes.HANDLE()\n\tres = process.OpenProcessToken(\n\t\tprocess.GetCurrentProcess(), process.TOKEN_ALL_ACCESS, token)\n\tif not res > 0:\n\t\traise RuntimeError(\"Couldn't get process token\")\n\treturn token",
    "docstring": "Get the current process token"
  },
  {
    "code": "def sociallogin_from_response(self, request, response):\n        from allauth.socialaccount.models import SocialLogin, SocialAccount\n        adapter = get_adapter(request)\n        uid = self.extract_uid(response)\n        extra_data = self.extract_extra_data(response)\n        common_fields = self.extract_common_fields(response)\n        socialaccount = SocialAccount(extra_data=extra_data,\n                                      uid=uid,\n                                      provider=self.id)\n        email_addresses = self.extract_email_addresses(response)\n        self.cleanup_email_addresses(common_fields.get('email'),\n                                     email_addresses)\n        sociallogin = SocialLogin(account=socialaccount,\n                                  email_addresses=email_addresses)\n        user = sociallogin.user = adapter.new_user(request, sociallogin)\n        user.set_unusable_password()\n        adapter.populate_user(request, sociallogin, common_fields)\n        return sociallogin",
    "docstring": "Instantiates and populates a `SocialLogin` model based on the data\n        retrieved in `response`. The method does NOT save the model to the\n        DB.\n\n        Data for `SocialLogin` will be extracted from `response` with the\n        help of the `.extract_uid()`, `.extract_extra_data()`,\n        `.extract_common_fields()`, and `.extract_email_addresses()`\n        methods.\n\n        :param request: a Django `HttpRequest` object.\n        :param response: object retrieved via the callback response of the\n            social auth provider.\n        :return: A populated instance of the `SocialLogin` model (unsaved)."
  },
  {
    "code": "def contains(self, other):\n        return (self.alt == other.alt and\n                self.prefix.endswith(other.prefix) and\n                self.suffix.startswith(other.suffix))",
    "docstring": "Is the other VariantSequence a subsequence of this one?\n\n        The two sequences must agree on the alt nucleotides, the prefix of the\n        longer must contain the prefix of the shorter, and the suffix of the\n        longer must contain the suffix of the shorter."
  },
  {
    "code": "def add_lv_load_area_group(self, lv_load_area_group):\n        if lv_load_area_group not in self.lv_load_area_groups():\n            self._lv_load_area_groups.append(lv_load_area_group)",
    "docstring": "Adds a LV load_area to _lv_load_areas if not already existing."
  },
  {
    "code": "def debug(self, request, message, extra_tags='', fail_silently=False):\n        add(self.target_name, request, constants.DEBUG, message, extra_tags=extra_tags,\n            fail_silently=fail_silently)",
    "docstring": "Add a message with the ``DEBUG`` level."
  },
  {
    "code": "def create_linked_data_element_from_resource(self, resource):\n        mp = self.__mp_reg.find_or_create_mapping(Link)\n        return mp.data_element_class.create_from_resource(resource)",
    "docstring": "Returns a new linked data element for the given resource object.\n\n        :returns: object implementing :class:`ILinkedDataElement`."
  },
  {
    "code": "def isPackage(self, dotted_name, extrapath=None):\n        candidate = self.isModule(dotted_name + '.__init__', extrapath)\n        if candidate:\n            candidate = candidate[:-len(\".__init__\")]\n        return candidate",
    "docstring": "Is ``dotted_name`` the name of a package?"
  },
  {
    "code": "def _set_alarm(self, status, home_id):\n        response = self._request(\n            MINUT_HOMES_URL + \"/{}\".format(home_id),\n            request_type='PUT',\n            json={'alarm_status': status})\n        return response.get('alarm_status', '') == status",
    "docstring": "Set alarm satus."
  },
  {
    "code": "def on_change(self, *callbacks):\n        for callback in callbacks:\n            if callback in self._callbacks: continue\n            _check_callback(callback, ('event',))\n            self._callbacks[callback] = callback",
    "docstring": "Provide callbacks to invoke if the document or any Model reachable\n        from its roots changes."
  },
  {
    "code": "def ismount(self, path):\n        path = make_string_path(path)\n        if not path:\n            return False\n        normed_path = self.filesystem.absnormpath(path)\n        sep = self.filesystem._path_separator(path)\n        if self.filesystem.is_windows_fs:\n            if self.filesystem.alternative_path_separator is not None:\n                path_seps = (\n                    sep, self.filesystem._alternative_path_separator(path)\n                )\n            else:\n                path_seps = (sep, )\n            drive, rest = self.filesystem.splitdrive(normed_path)\n            if drive and drive[:1] in path_seps:\n                return (not rest) or (rest in path_seps)\n            if rest in path_seps:\n                return True\n        for mount_point in self.filesystem.mount_points:\n            if normed_path.rstrip(sep) == mount_point.rstrip(sep):\n                return True\n        return False",
    "docstring": "Return true if the given path is a mount point.\n\n        Args:\n            path: Path to filesystem object to be checked\n\n        Returns:\n            `True` if path is a mount point added to the fake file system.\n            Under Windows also returns True for drive and UNC roots\n            (independent of their existence)."
  },
  {
    "code": "def parse_literal(x):\n    if isinstance(x, list):\n        return [parse_literal(y) for y in x]\n    elif isinstance(x, (bytes, str)):\n        try:\n            return int(x)\n        except ValueError:\n            try:\n                return float(x)\n            except ValueError:\n                return x\n    else:\n        raise TypeError('input must be a string or a list of strings')",
    "docstring": "return the smallest possible data type for a string or list of strings\n\n    Parameters\n    ----------\n    x: str or list\n        a string to be parsed\n\n    Returns\n    -------\n    int, float or str\n        the parsing result\n    \n    Examples\n    --------\n    >>> isinstance(parse_literal('1.5'), float)\n    True\n    \n    >>> isinstance(parse_literal('1'), int)\n    True\n    \n    >>> isinstance(parse_literal('foobar'), str)\n    True"
  },
  {
    "code": "def get(self, type: Type[T], query: Mapping[str, Any]) -> T:\n        LOGGER.info(\"Getting SourceHandlers for \\\"{type}\\\"\".format(type=type.__name__))\n        try:\n            handlers = self._get_types[type]\n        except KeyError:\n            try:\n                LOGGER.info(\"Building new SourceHandlers for \\\"{type}\\\"\".format(type=type.__name__))\n                handlers = self._get_handlers(type)\n            except NoConversionError:\n                handlers = None\n            self._get_types[type] = handlers\n        if handlers is None:\n            raise NoConversionError(\"No source can provide \\\"{type}\\\"\".format(type=type.__name__))\n        LOGGER.info(\"Creating new PipelineContext\")\n        context = self._new_context()\n        LOGGER.info(\"Querying SourceHandlers for \\\"{type}\\\"\".format(type=type.__name__))\n        for handler in handlers:\n            try:\n                return handler.get(query, context)\n            except NotFoundError:\n                pass\n        raise NotFoundError(\"No source returned a query result!\")",
    "docstring": "Gets a query from the data pipeline.\n\n        1) Extracts the query the sequence of data sources.\n        2) Inserts the result into the data sinks (if appropriate).\n        3) Transforms the result into the requested type if it wasn't already.\n        4) Inserts the transformed result into any data sinks.\n\n        Args:\n            query: The query being requested.\n            context: The context for the extraction (mutable).\n\n        Returns:\n            The requested object."
  },
  {
    "code": "def count_samples(ns_run, **kwargs):\n    r\n    kwargs.pop('logw', None)\n    kwargs.pop('simulate', None)\n    if kwargs:\n        raise TypeError('Unexpected **kwargs: {0}'.format(kwargs))\n    return ns_run['logl'].shape[0]",
    "docstring": "r\"\"\"Number of samples in run.\n\n    Unlike most estimators this does not require log weights, but for\n    convenience will not throw an error if they are specified.\n\n    Parameters\n    ----------\n    ns_run: dict\n        Nested sampling run dict (see the data_processing module\n        docstring for more details).\n\n    Returns\n    -------\n    int"
  },
  {
    "code": "def _get(self, key):\n        self._populate_cache()\n        if key not in self._cache:\n            raise AttributeError(\"DataField has no member {}\".format(key))\n        return self._cache[key]",
    "docstring": "Return given key from cache."
  },
  {
    "code": "def stop_monitoring(self) -> None:\n        self._context.optimisation_finished = True\n        self._on_iteration()\n        if self._print_summary:\n            self.print_summary()",
    "docstring": "The recommended way of using Monitor is opening it with the `with` statement. In this case\n        the user doesn't need to call this function explicitly. Otherwise the function should be\n        called when the optimisation is done.\n\n        The function sets the optimisation completed flag in the monitoring context and runs the\n        tasks once more. If the monitor was created with the `print_summary` option it prints the\n        tasks' timing summary."
  },
  {
    "code": "def arch(self):\n        if self.method in ('buildArch', 'createdistrepo', 'livecd'):\n            return self.params[2]\n        if self.method in ('createrepo', 'runroot'):\n            return self.params[1]\n        if self.method == 'createImage':\n            return self.params[3]\n        if self.method == 'indirectionimage':\n            return self.params[0]['arch']",
    "docstring": "Return an architecture for this task.\n\n        :returns: an arch string (eg \"noarch\", or \"ppc64le\"), or None this task\n                  has no architecture associated with it."
  },
  {
    "code": "def find_existing(self):\n        sg = self.consul.find_secgroup(self.name)\n        current = sg.rules\n        log.debug('Current rules: %s' % current)\n        log.debug('Intended rules: %s' % self.rules)\n        exp_rules = []\n        for rule in self.rules:\n            exp = (\n                    rule[A.secgroup.PROTOCOL],\n                    rule[A.secgroup.FROM],\n                    rule[A.secgroup.TO],\n                    rule[A.secgroup.SOURCE],\n                    )\n            exp_rules.append(exp)\n            if exp in current:\n                del current[exp]\n            else:\n                self.create_these_rules.append(exp)\n        self.delete_these_rules.extend(current.itervalues())\n        log.debug('Create these rules: %s' % self.create_these_rules)\n        log.debug('Delete these rules: %s' % self.delete_these_rules)",
    "docstring": "Finds existing rule in secgroup.\n\n        Populates ``self.create_these_rules`` and ``self.delete_these_rules``."
  },
  {
    "code": "def _build_callback(self, config):\n        wrapped = config['callback']\n        plugins = self.plugins + config['apply']\n        skip    = config['skip']\n        try:\n            for plugin in reversed(plugins):\n                if True in skip: break\n                if plugin in skip or type(plugin) in skip: continue\n                if getattr(plugin, 'name', True) in skip: continue\n                if hasattr(plugin, 'apply'):\n                    wrapped = plugin.apply(wrapped, config)\n                else:\n                    wrapped = plugin(wrapped)\n                if not wrapped: break\n                functools.update_wrapper(wrapped, config['callback'])\n            return wrapped\n        except RouteReset:\n            return self._build_callback(config)",
    "docstring": "Apply plugins to a route and return a new callable."
  },
  {
    "code": "def signature(self):\n        iexec, execmod = self.context.parser.tree_find(self.context.el_name, \n                                              self.context.module, \"executables\")\n        if iexec is None:\n            iexec, execmod = self.context.parser.tree_find(self.context.el_name, self.context.module,\n                                                  \"interfaces\")\n        if iexec is None:\n            return []\n        return self._signature_index(iexec)",
    "docstring": "Gets completion or call signature information for the current cursor."
  },
  {
    "code": "def long_to_bytes(N, blocksize=1):\n    bytestring = hex(N)\n    bytestring = bytestring[2:] if bytestring.startswith('0x') else bytestring\n    bytestring = bytestring[:-1] if bytestring.endswith('L') else bytestring\n    bytestring = '0' + bytestring if (len(bytestring) % 2) != 0 else bytestring\n    bytestring = binascii.unhexlify(bytestring)\n    if blocksize > 0 and len(bytestring) % blocksize != 0:\n        bytestring = '\\x00' * \\\n            (blocksize - (len(bytestring) % blocksize)) + bytestring\n    return bytestring",
    "docstring": "Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes.\n    If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes,\n    such that the return values length is a multiple of ``blocksize``."
  },
  {
    "code": "def wait_for_and_dismiss_alert(driver, timeout=settings.LARGE_TIMEOUT):\n    alert = wait_for_and_switch_to_alert(driver, timeout)\n    alert_text = alert.text\n    alert.dismiss()\n    return alert_text",
    "docstring": "Wait for and dismiss an alert. Returns the text from the alert.\n    @Params\n    driver - the webdriver object (required)\n    timeout - the time to wait for the alert in seconds"
  },
  {
    "code": "def update_reading_events(readings, event_record):\n    for i in range(event_record.start_interval - 1, event_record.end_interval):\n        readings[i] = Reading(\n            t_start=readings[i].t_start,\n            t_end=readings[i].t_end,\n            read_value=readings[i].read_value,\n            uom=readings[i].uom,\n            quality_method=event_record.quality_method,\n            event_code=event_record.reason_code,\n            event_desc=event_record.reason_description,\n            read_start=readings[i].read_start,\n            read_end=readings[i].read_end)\n    return readings",
    "docstring": "Updates readings from a 300 row to reflect any events found in a\n        subsequent 400 row"
  },
  {
    "code": "def _data(self):\n        self.wait_to_read()\n        hdl = NDArrayHandle()\n        check_call(_LIB.MXNDArrayGetDataNDArray(self.handle, ctypes.byref(hdl)))\n        return NDArray(hdl)",
    "docstring": "A deep copy NDArray of the data array associated with the BaseSparseNDArray.\n\n        This function blocks. Do not use it in performance critical code."
  },
  {
    "code": "def up(ctx, instance_id):\n    session = create_session(ctx.obj['AWS_PROFILE_NAME'])\n    ec2 = session.resource('ec2')\n    try:\n        instance = ec2.Instance(instance_id)\n        instance.start()\n    except botocore.exceptions.ClientError as e:\n        click.echo(\"Invalid instance ID {0} ({1})\".format(instance_id, e), err=True)\n        sys.exit(2)",
    "docstring": "Start EC2 instance"
  },
  {
    "code": "def validate_candidates(self):\n        async def slave_task(addr, candidates):\n            r_manager = await self.env.connect(addr)\n            return await r_manager.validate_candidates(candidates)\n        self._log(logging.DEBUG, \"Validating {} candidates\"\n                  .format(len(self.candidates)))\n        candidates = self.candidates\n        if self._single_env:\n            self._candidates = self.env.validate_candidates(candidates)\n        else:\n            mgrs = self.get_managers()\n            tasks = create_tasks(slave_task, mgrs, candidates, flatten=False)\n            rets = run(tasks)\n            valid_candidates = set(self.candidates)\n            for r in rets:\n                valid_candidates = valid_candidates.intersection(set(r))\n            self._candidates = list(valid_candidates)\n        self._log(logging.DEBUG, \"{} candidates after validation\"\n                  .format(len(self.candidates)))",
    "docstring": "Validate current candidates.\n\n        This method validates the current candidate list in all the agents\n        in the environment (or underlying slave environments) and replaces\n        the current :attr:`candidates` with the list of validated candidates.\n\n        The artifact candidates must be hashable and have a :meth:`__eq__`\n        implemented for validation to work on multi-environments and\n        distributed environments."
  },
  {
    "code": "def get_objective_search_session(self):\n        if not self.supports_objective_search():\n            raise Unimplemented()\n        try:\n            from . import sessions\n        except ImportError:\n            raise OperationFailed()\n        try:\n            session = sessions.ObjectiveSearchSession(runtime=self._runtime)\n        except AttributeError:\n            raise OperationFailed()\n        return session",
    "docstring": "Gets the OsidSession associated with the objective search\n        service.\n\n        return: (osid.learning.ObjectiveSearchSession) - an\n                ObjectiveSearchSession\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - supports_objective_search() is false\n        compliance: optional - This method must be implemented if\n                    supports_objective_search() is true."
  },
  {
    "code": "def list(self, entity=None):\n        uri = \"/%s\" % self.uri_base\n        if entity:\n            uri = \"%s?entityId=%s\" % (uri, utils.get_id(entity))\n        resp, resp_body = self._list(uri, return_raw=True)\n        return resp_body",
    "docstring": "Returns a dictionary of data, optionally filtered for a given entity."
  },
  {
    "code": "def _WaitForStartup(self, deadline):\n    start = time.time()\n    sleep = 0.05\n    def Elapsed():\n      return time.time() - start\n    while True:\n      try:\n        response, _ = self._http.request(self._host)\n        if response.status == 200:\n          logging.info('emulator responded after %f seconds', Elapsed())\n          return True\n      except (socket.error, httplib.ResponseNotReady):\n        pass\n      if Elapsed() >= deadline:\n        return False\n      else:\n        time.sleep(sleep)\n        sleep *= 2",
    "docstring": "Waits for the emulator to start.\n\n    Args:\n      deadline: deadline in seconds\n\n    Returns:\n      True if the emulator responds within the deadline, False otherwise."
  },
  {
    "code": "def main(config, host, port, logfile, debug, daemon, uid, gid, pidfile, umask, rundir):\n    _main(**locals())",
    "docstring": "Main entry point for running a socket server from the commandline.\n\n    This method will read in options from the commandline and call the L{config.init_config} method\n    to get everything setup.  Then, depending on whether deamon mode was specified or not, \n    the process may be forked (or not) and the server will be started."
  },
  {
    "code": "def getAvailableTemplates(self):\n        try:\n            adapters = getAdapters((self.context, ), IGetStickerTemplates)\n        except ComponentLookupError:\n            logger.info(\"No IGetStickerTemplates adapters found.\")\n            adapters = None\n        templates = []\n        if adapters is not None:\n            for name, adapter in adapters:\n                templates += adapter(self.request)\n        if templates:\n            return templates\n        seltemplate = self.getSelectedTemplate()\n        for temp in getStickerTemplates(filter_by_type=self.filter_by_type):\n            out = temp\n            out[\"selected\"] = temp.get(\"id\", \"\") == seltemplate\n            templates.append(out)\n        return templates",
    "docstring": "Returns an array with the templates of stickers available.\n\n        Each array item is a dictionary with the following structure:\n\n            {'id': <template_id>,\n            'title': <teamplate_title>,\n            'selected: True/False'}"
  },
  {
    "code": "def available_cpu_count() -> int:\n    try:\n        match = re.search(r'(?m)^Cpus_allowed:\\s*(.*)$',\n                          open('/proc/self/status').read())\n        if match:\n            res = bin(int(match.group(1).replace(',', ''), 16)).count('1')\n            if res > 0:\n                return res\n    except IOError:\n        LOG.debug(\"Could not get the number of allowed CPUs\")\n    try:\n        import psutil\n        return psutil.cpu_count()\n    except (ImportError, AttributeError):\n        LOG.debug(\"Could not get the number of allowed CPUs\")\n    try:\n        res = int(os.sysconf('SC_NPROCESSORS_ONLN'))\n        if res > 0:\n            return res\n    except (AttributeError, ValueError):\n        LOG.debug(\"Could not get the number of allowed CPUs\")\n    try:\n        res = open('/proc/cpuinfo').read().count('processor\\t:')\n        if res > 0:\n            return res\n    except IOError:\n        LOG.debug(\"Could not get the number of allowed CPUs\")\n    raise Exception('Can not determine number of CPUs on this system')",
    "docstring": "Get the number of available CPUs.\n\n    Number of available virtual or physical CPUs on this system, i.e.\n    user/real as output by time(1) when called with an optimally scaling\n    userspace-only program.\n\n    Returns:\n        Number of avaialable CPUs."
  },
  {
    "code": "def instruction_ROL_register(self, opcode, register):\n        a = register.value\n        r = self.ROL(a)\n        register.set(r)",
    "docstring": "Rotate accumulator left"
  },
  {
    "code": "def get_params(names):\n    params = {}\n    for name in names:\n        value = request.form.get(name) or request.files.get(name)\n        if value is not None:\n            params[name] = value\n    return params",
    "docstring": "Return a dictionary with params from request.\n\n    TODO: I think we don't use it anymore and it should be removed\n    before someone gets hurt."
  },
  {
    "code": "def parse(self, src):\n        self.cssBuilder.beginStylesheet()\n        try:\n            src = cssSpecial.cleanupCSS(src)\n            try:\n                src, stylesheet = self._parseStylesheet(src)\n            except self.ParseError as err:\n                err.setFullCSSSource(src)\n                raise\n        finally:\n            self.cssBuilder.endStylesheet()\n        return stylesheet",
    "docstring": "Parses CSS string source using the current cssBuilder.\n        Use for embedded stylesheets."
  },
  {
    "code": "def lan(self, move: Move) -> str:\n        return self._algebraic(move, long=True)",
    "docstring": "Gets the long algebraic notation of the given move in the context of\n        the current position."
  },
  {
    "code": "def unshift(self, chunk):\n        if chunk:\n            self._pos -= len(chunk)\n            self._unconsumed.append(chunk)",
    "docstring": "Pushes a chunk of data back into the internal buffer. This is useful\n        in certain situations where a stream is being consumed by code that\n        needs to \"un-consume\" some amount of data that it has optimistically\n        pulled out of the source, so that the data can be passed on to some\n        other party."
  },
  {
    "code": "def _parse():\n    if not args[\"reparse\"]:\n        settings.use_filesystem_cache = False\n    c = CodeParser()    \n    if args[\"verbose\"]:\n        c.verbose = True\n    if args[\"reparse\"]:\n        c.reparse(args[\"source\"])\n    else:\n        c.parse(args[\"source\"])\n    return c",
    "docstring": "Parses the specified Fortran source file from which the wrappers will\n    be constructed for ctypes."
  },
  {
    "code": "def predict(self, inputs: np.ndarray) -> np.ndarray:\n        return self.sess.run(self.out_var, {self.inp_var: inputs})",
    "docstring": "Run on multiple inputs"
  },
  {
    "code": "def was_modified_since(header=None, mtime=0, size=0):\n    header_mtime = modified_since(header, size)\n    if header_mtime and header_mtime <= mtime:\n        return False\n    return True",
    "docstring": "Check if an item was modified since the user last downloaded it\n\n    :param header: the value of the ``If-Modified-Since`` header.\n        If this is ``None``, simply return ``True``\n    :param mtime: the modification time of the item in question.\n    :param size: the size of the item."
  },
  {
    "code": "def _close_window(self, window):\n        if window == self.active_window:\n            self.close_active_window()\n        else:\n            original_active_window = self.active_window\n            self.close_active_window()\n            self.active_window = original_active_window",
    "docstring": "Close this window."
  },
  {
    "code": "def _find_global(self, module, func):\n        if module == __name__:\n            if func == '_unpickle_call_error' or func == 'CallError':\n                return _unpickle_call_error\n            elif func == '_unpickle_sender':\n                return self._unpickle_sender\n            elif func == '_unpickle_context':\n                return self._unpickle_context\n            elif func == 'Blob':\n                return Blob\n            elif func == 'Secret':\n                return Secret\n            elif func == 'Kwargs':\n                return Kwargs\n        elif module == '_codecs' and func == 'encode':\n            return self._unpickle_bytes\n        elif module == '__builtin__' and func == 'bytes':\n            return BytesType\n        raise StreamError('cannot unpickle %r/%r', module, func)",
    "docstring": "Return the class implementing `module_name.class_name` or raise\n        `StreamError` if the module is not whitelisted."
  },
  {
    "code": "def _index_document(self, document, force=False):\n        query = text(\n)\n        self.execute(query, **document)",
    "docstring": "Adds dataset document to the index."
  },
  {
    "code": "def save(self, path):\n        self.clip.write_videofile(path, audio_fps=self.clip.audio.fps)",
    "docstring": "Save source video to file.\n\n        Args:\n            path (str): Filename to save to.\n\n        Notes: Saves entire source video to file, not just currently selected\n            frames."
  },
  {
    "code": "def _check_authentication(self, request, request_args, request_kwargs):\n        try:\n            is_valid, status, reasons = self._verify(\n                request,\n                request_args=request_args,\n                request_kwargs=request_kwargs,\n            )\n        except Exception as e:\n            logger.debug(e.args)\n            if self.config.debug():\n                raise e\n            args = e.args if isinstance(e, SanicJWTException) else []\n            raise exceptions.Unauthorized(*args)\n        return is_valid, status, reasons",
    "docstring": "Checks a request object to determine if that request contains a valid,\n        and authenticated JWT.\n\n        It returns a tuple:\n        1. Boolean whether the request is authenticated with a valid JWT\n        2. HTTP status code\n        3. Reasons (if any) for a potential authentication failure"
  },
  {
    "code": "def recruit(self):\n        if not self.networks(full=False):\n            self.log(\"All networks full: closing recruitment\", \"-----\")\n            self.recruiter.close_recruitment()",
    "docstring": "Recruit participants to the experiment as needed.\n\n        This method runs whenever a participant successfully completes the\n        experiment (participants who fail to finish successfully are\n        automatically replaced). By default it recruits 1 participant at a time\n        until all networks are full."
  },
  {
    "code": "def sort_batch_by_length(tensor: torch.Tensor, sequence_lengths: torch.Tensor):\n    if not isinstance(tensor, torch.Tensor) or not isinstance(sequence_lengths, torch.Tensor):\n        raise ConfigurationError(\"Both the tensor and sequence lengths must be torch.Tensors.\")\n    sorted_sequence_lengths, permutation_index = sequence_lengths.sort(0, descending=True)\n    sorted_tensor = tensor.index_select(0, permutation_index)\n    index_range = torch.arange(0, len(sequence_lengths), device=sequence_lengths.device)\n    _, reverse_mapping = permutation_index.sort(0, descending=False)\n    restoration_indices = index_range.index_select(0, reverse_mapping)\n    return sorted_tensor, sorted_sequence_lengths, restoration_indices, permutation_index",
    "docstring": "Sort a batch first tensor by some specified lengths.\n\n    Parameters\n    ----------\n    tensor : torch.FloatTensor, required.\n        A batch first Pytorch tensor.\n    sequence_lengths : torch.LongTensor, required.\n        A tensor representing the lengths of some dimension of the tensor which\n        we want to sort by.\n\n    Returns\n    -------\n    sorted_tensor : torch.FloatTensor\n        The original tensor sorted along the batch dimension with respect to sequence_lengths.\n    sorted_sequence_lengths : torch.LongTensor\n        The original sequence_lengths sorted by decreasing size.\n    restoration_indices : torch.LongTensor\n        Indices into the sorted_tensor such that\n        ``sorted_tensor.index_select(0, restoration_indices) == original_tensor``\n    permutation_index : torch.LongTensor\n        The indices used to sort the tensor. This is useful if you want to sort many\n        tensors using the same ordering."
  },
  {
    "code": "def _sim_texture(r1, r2):\n    return sum([min(a, b) for a, b in zip(r1[\"hist_t\"], r2[\"hist_t\"])])",
    "docstring": "calculate the sum of histogram intersection of texture"
  },
  {
    "code": "def snappy_encode(payload, xerial_compatible=False,\n                  xerial_blocksize=32 * 1024):\n    if not has_snappy():\n        raise NotImplementedError(\"Snappy codec is not available\")\n    if xerial_compatible:\n        def _chunker():\n            for i in range(0, len(payload), xerial_blocksize):\n                yield payload[i:i+xerial_blocksize]\n        out = BytesIO()\n        out.write(_XERIAL_HEADER)\n        for chunk in _chunker():\n            block = snappy.compress(chunk)\n            out.write(struct.pack('!i', len(block)))\n            out.write(block)\n        out.seek(0)\n        return out.read()\n    else:\n        return snappy.compress(payload)",
    "docstring": "Compress the given data with the Snappy algorithm.\n\n    :param bytes payload: Data to compress.\n    :param bool xerial_compatible:\n        If set then the stream is broken into length-prefixed blocks in\n        a fashion compatible with the xerial snappy library.\n\n        The format winds up being::\n\n            +-------------+------------+--------------+------------+--------------+\n            |   Header    | Block1_len | Block1 data  | BlockN len | BlockN data  |\n            |-------------+------------+--------------+------------+--------------|\n            |  16 bytes   |  BE int32  | snappy bytes |  BE int32  | snappy bytes |\n            +-------------+------------+--------------+------------+--------------+\n\n    :param int xerial_blocksize:\n        Number of bytes per chunk to independently Snappy encode. 32k is the\n        default in the xerial library.\n\n    :returns: Compressed bytes.\n    :rtype: :class:`bytes`"
  },
  {
    "code": "def _trim_zeros_float(str_floats, na_rep='NaN'):\n    trimmed = str_floats\n    def _is_number(x):\n        return (x != na_rep and not x.endswith('inf'))\n    def _cond(values):\n        finite = [x for x in values if _is_number(x)]\n        return (len(finite) > 0 and all(x.endswith('0') for x in finite) and\n                not (any(('e' in x) or ('E' in x) for x in finite)))\n    while _cond(trimmed):\n        trimmed = [x[:-1] if _is_number(x) else x for x in trimmed]\n    return [x + \"0\" if x.endswith('.') and _is_number(x) else x\n            for x in trimmed]",
    "docstring": "Trims zeros, leaving just one before the decimal points if need be."
  },
  {
    "code": "def SendSerializedMessage(self, message):\n        try:\n            ba = Helper.ToArray(message)\n            ba2 = binascii.unhexlify(ba)\n            self.bytes_out += len(ba2)\n            self.transport.write(ba2)\n        except Exception as e:\n            logger.debug(f\"Could not send serialized message {e}\")",
    "docstring": "Send the `message` to the remote client.\n\n        Args:\n            message (neo.Network.Message):"
  },
  {
    "code": "def async_do(self, size=10):\n        if hasattr(self._session, '_async_jobs'):\n            logging.info(\"Executing asynchronous %s jobs found in queue by using %s threads...\" % (\n                len(self._session._async_jobs), size))\n            threaded_requests.map(self._session._async_jobs, size=size)",
    "docstring": "Execute all asynchronous jobs and wait for them to finish. By default it will run on 10 threads.\n\n        :param size: number of threads to run on."
  },
  {
    "code": "def designspace(self):\n        if self._designspace_is_complete:\n            return self._designspace\n        self._designspace_is_complete = True\n        list(self.masters)\n        self.to_designspace_axes()\n        self.to_designspace_sources()\n        self.to_designspace_instances()\n        self.to_designspace_family_user_data()\n        if self.bracket_layers:\n            self._apply_bracket_layers()\n        base_family = self.family_name or \"Unnamed\"\n        base_style = find_base_style(self.font.masters)\n        if base_style:\n            base_style = \"-\" + base_style\n        name = (base_family + base_style).replace(\" \", \"\") + \".designspace\"\n        self.designspace.filename = name\n        return self._designspace",
    "docstring": "Get a designspace Document instance that links the masters together\n        and holds instance data."
  },
  {
    "code": "def __assert_false(returned):\n        result = \"Pass\"\n        if isinstance(returned, str):\n            try:\n                returned = bool(returned)\n            except ValueError:\n                raise\n        try:\n            assert (returned is False), \"{0} not False\".format(returned)\n        except AssertionError as err:\n            result = \"Fail: \" + six.text_type(err)\n        return result",
    "docstring": "Test if an boolean is False"
  },
  {
    "code": "def import_module(module_fqname, superclasses=None):\n    module_name = module_fqname.rpartition(\".\")[-1]\n    module = __import__(module_fqname, globals(), locals(), [module_name])\n    modules = [class_ for cname, class_ in\n               inspect.getmembers(module, inspect.isclass)\n               if class_.__module__ == module_fqname]\n    if superclasses:\n        modules = [m for m in modules if issubclass(m, superclasses)]\n    return modules",
    "docstring": "Imports the module module_fqname and returns a list of defined classes\n    from that module. If superclasses is defined then the classes returned will\n    be subclasses of the specified superclass or superclasses. If superclasses\n    is plural it must be a tuple of classes."
  },
  {
    "code": "def cancel(self):\n        if self.done():\n            return False\n        self._client.cancel_operation(self._operation.name)\n        return True",
    "docstring": "If last Operation's value of `done` is true, returns false;\n        otherwise, issues OperationsClient.cancel_operation and returns true."
  },
  {
    "code": "def on_message(self, message):\n        if message.address != self._address:\n            return\n        if isinstance(message, velbus.ChannelNamePart1Message) or isinstance(message, velbus.ChannelNamePart1Message2):\n            self._process_channel_name_message(1, message)\n        elif isinstance(message, velbus.ChannelNamePart2Message) or isinstance(message, velbus.ChannelNamePart2Message2):\n            self._process_channel_name_message(2, message)\n        elif isinstance(message, velbus.ChannelNamePart3Message) or isinstance(message, velbus.ChannelNamePart3Message2):\n            self._process_channel_name_message(3, message)\n        elif isinstance(message, velbus.ModuleTypeMessage):\n            self._process_module_type_message(message)\n        else:\n            self._on_message(message)",
    "docstring": "Process received message"
  },
  {
    "code": "def workspace_cli(ctx, directory, mets_basename, backup):\n    ctx.obj = WorkspaceCtx(os.path.abspath(directory), mets_basename, automatic_backup=backup)",
    "docstring": "Working with workspace"
  },
  {
    "code": "def sync_in(self, force=False):\n        self.log('---- Sync In ----')\n        self.dstate = self.STATES.BUILDING\n        for path_name in self.source_fs.listdir():\n            f = self.build_source_files.instance_from_name(path_name)\n            if not f:\n                self.warn('Ignoring unknown file: {}'.format(path_name))\n                continue\n            if f and f.exists and (f.fs_is_newer or force):\n                self.log('Sync: {}'.format(f.record.path))\n                f.fs_to_record()\n                f.record_to_objects()\n        self.commit()\n        self.library.search.index_bundle(self, force=True)",
    "docstring": "Synchronize from files to records, and records to objects"
  },
  {
    "code": "def execute_replay() -> None:\n    files = glob.glob('./replay/toDo/*')\n    sorted_files = sorted(files, key=os.path.getctime)\n    if not sorted_files:\n        LOG.debug('Found %s, beginning execution.', sorted_files)\n        for command_file in sorted_files:\n            with open(command_file, 'r') as command:\n                cmd = command.read()\n                LOG.debug('executing command: %s', cmd)\n                resp = run([cmd, '-v', 'DEBUG'], shell=True, check=True)\n                LOG.debug(resp)\n                LOG.debug('moving %s to archive', command.name)\n                move_command = 'mv {0} ./replay/archive/'.format(command.name)\n                run(move_command, shell=True, check=True)\n        LOG.info('LaunchDarkly is now up to date.')\n    else:\n        LOG.warning('No files found, nothing to replay.')",
    "docstring": "Execute all commands.\n\n    For every command that is found in replay/toDo, execute each of them\n    and move the file to the replay/archive directory."
  },
  {
    "code": "def posterior_samples(self, X, size=10, full_cov=False, Y_metadata=None, likelihood=None, **predict_kwargs):\n        return self.posterior_samples_f(X, size, full_cov=full_cov, **predict_kwargs)",
    "docstring": "Samples the posterior GP at the points X, equivalent to posterior_samples_f due to the absence of a likelihood."
  },
  {
    "code": "def check_mapping(self, m):\n        if 'name' not in m:\n            self.pr_dbg(\"Missing %s\" % \"name\")\n            return False\n        for x in ['analyzed', 'indexed', 'type', 'scripted', 'count']:\n            if x not in m or m[x] == \"\":\n                self.pr_dbg(\"Missing %s\" % x)\n                self.pr_dbg(\"Full %s\" % m)\n                return False\n        if 'doc_values' not in m or m['doc_values'] == \"\":\n            if not m['name'].startswith('_'):\n                self.pr_dbg(\"Missing %s\" % \"doc_values\")\n                return False\n            m['doc_values'] = False\n        return True",
    "docstring": "Assert minimum set of fields in cache, does not validate contents"
  },
  {
    "code": "def eval(e, amplitude, e_0, alpha, e_cutoff, beta):\n        xx = e / e_0\n        return amplitude * xx ** (-alpha) * np.exp(-(e / e_cutoff) ** beta)",
    "docstring": "One dimensional power law with an exponential cutoff model function"
  },
  {
    "code": "def pop(self, k, d=_POP_DEFAULT):\n        if d is _POP_DEFAULT:\n            return self._ingredients.pop(k)\n        else:\n            return self._ingredients.pop(k, d)",
    "docstring": "Pop an ingredient off of this shelf."
  },
  {
    "code": "def get(self, r):\n        if r is None:\n            return None\n        if r.lower() == '(sp)' and self.stack:\n            return self.stack[-1]\n        if r[:1] == '(':\n            return self.mem[r[1:-1]]\n        r = r.lower()\n        if is_number(r):\n            return str(valnum(r))\n        if not is_register(r):\n            return None\n        return self.regs[r]",
    "docstring": "Returns precomputed value of the given expression"
  },
  {
    "code": "def target(self):\n        target = self.path or '/'\n        if self.query:\n            target = '{}?{}'.format(target, self.query)\n        return target",
    "docstring": "The \"target\" i.e. local part of the URL, consisting of the path and query."
  },
  {
    "code": "def query_mxrecords(self):\n        import dns.resolver\n        logging.info('Resolving DNS query...')\n        answers = dns.resolver.query(self.domain, 'MX')\n        addresses = [answer.exchange.to_text() for answer in answers]\n        logging.info(\n            '{} records found:\\n{}'.format(\n                len(addresses), '\\n  '.join(addresses)))\n        return addresses",
    "docstring": "Looks up for the MX DNS records of the recipient SMTP server"
  },
  {
    "code": "def _encode(self):\n        data = ByteBuffer()\n        if not hasattr(self, '__fields__'):\n            return data.tostring()\n        for field in self.__fields__:\n            field.encode(self, data)\n        return data.tostring()",
    "docstring": "Encode the message and return a bytestring."
  },
  {
    "code": "def eye(root=None, zodb_uri=None, port=8080):\n    if root is not None:\n        root_factory = lambda request: Node(root)\n    elif zodb_uri is not None:\n        if '://' not in zodb_uri:\n            zodb_uri = 'file://' + os.path.abspath(zodb_uri)        \n        from repoze.zodbconn.finder import PersistentApplicationFinder\n        finder = PersistentApplicationFinder(zodb_uri, appmaker=lambda root: Node(root))\n        root_factory = lambda request: finder(request.environ)\n    else:\n        raise RuntimeError(\"Must specify root object or ZODB URI.\")\n    app = Eye(root_factory)\n    if 'DEBUG' in os.environ:\n        from repoze.debug.pdbpm import PostMortemDebug\n        app = PostMortemDebug(app)\n    serve(app, host='127.0.0.1', port=port)",
    "docstring": "Serves a WSGI app to browse objects based on a root object or ZODB URI."
  },
  {
    "code": "def postprocess_citedReferences(self, entry):\n        if type(entry.citedReferences) is not list:\n            entry.citedReferences = [entry.citedReferences]",
    "docstring": "If only a single cited reference was found, ensure that\n        ``citedReferences`` is nonetheless a list."
  },
  {
    "code": "def get_status(self, device_id):\n        devices = self.get_devices()\n        if devices != False:\n            for device in devices:\n                if device['door'] == device_id:\n                    return device['status']\n        return False",
    "docstring": "List only MyQ garage door devices."
  },
  {
    "code": "def binarize(self, threshold=0):\n        if not self.is_binarized():\n            self.pianoroll = (self.pianoroll > threshold)",
    "docstring": "Binarize the pianoroll.\n\n        Parameters\n        ----------\n        threshold : int or float\n            A threshold used to binarize the pianorolls. Defaults to zero."
  },
  {
    "code": "def _parse(value, strict=True):\n    pattern = r'(?:(?P<hours>\\d+):)?(?P<minutes>\\d+):(?P<seconds>\\d+)'\n    match = re.match(pattern, value)\n    if not match:\n        raise ValueError('Invalid duration value: %s' % value)\n    hours = safe_int(match.group('hours'))\n    minutes = safe_int(match.group('minutes'))\n    seconds = safe_int(match.group('seconds'))\n    check_tuple((hours, minutes, seconds,), strict)\n    return (hours, minutes, seconds,)",
    "docstring": "Preliminary duration value parser\n\n    strict=True (by default) raises StrictnessError if either hours,\n    minutes or seconds in duration value exceed allowed values"
  },
  {
    "code": "def _set_magic_constants(self):\n        real_path = os.path.realpath(self._source_filename)\n        self._replace['__FILE__'] = \"'%s'\" % real_path\n        self._replace['__ROUTINE__'] = \"'%s'\" % self._routine_name\n        self._replace['__DIR__'] = \"'%s'\" % os.path.dirname(real_path)",
    "docstring": "Adds magic constants to replace list."
  },
  {
    "code": "def load_files(filenames,multiproc=False,**kwargs):\n    filenames = np.atleast_1d(filenames)\n    logger.debug(\"Loading %s files...\"%len(filenames))\n    kwargs = [dict(filename=f,**kwargs) for f in filenames]\n    if multiproc:\n        from multiprocessing import Pool\n        processes = multiproc if multiproc > 0 else None\n        p = Pool(processes,maxtasksperchild=1)\n        out = p.map(load_file,kwargs)\n    else:\n        out = [load_file(kw) for kw in kwargs]\n    dtype = out[0].dtype\n    for i,d in enumerate(out):\n        if d.dtype != dtype: \n            logger.warn(\"Casting input data to same type.\")\n            out[i] = d.astype(dtype,copy=False)\n    logger.debug('Concatenating arrays...')\n    return np.concatenate(out)",
    "docstring": "Load a set of FITS files with kwargs."
  },
  {
    "code": "def _should_split_cell(cls, cell_text: str) -> bool:\n        if ', ' in cell_text or '\\n' in cell_text or '/' in cell_text:\n            return True\n        return False",
    "docstring": "Checks whether the cell should be split.  We're just doing the same thing that SEMPRE did\n        here."
  },
  {
    "code": "def _input_stmt(self, stmt: Statement, sctx: SchemaContext) -> None:\n        self.get_child(\"input\")._handle_substatements(stmt, sctx)",
    "docstring": "Handle RPC or action input statement."
  },
  {
    "code": "def on_invite(self, connection, event):\n        sender = self.get_nick(event.source)\n        invited = self.get_nick(event.target)\n        channel = event.arguments[0]\n        if invited == self._nickname:\n            logging.info(\"! I am invited to %s by %s\", channel, sender)\n            connection.join(channel)\n        else:\n            logging.info(\">> %s invited %s to %s\", sender, invited, channel)",
    "docstring": "Got an invitation to a channel"
  },
  {
    "code": "def RegisterPlugin(self, report_plugin_cls):\n    name = report_plugin_cls.__name__\n    if name in self.plugins:\n      raise RuntimeError(\"Can't register two report plugins with the same \"\n                         \"name. In particular, can't register the same \"\n                         \"report plugin twice: %r\" % name)\n    self.plugins[name] = report_plugin_cls",
    "docstring": "Registers a report plugin for use in the GRR UI."
  },
  {
    "code": "def get_uninvoiced_hours(entries, billable=None):\n    statuses = ('invoiced', 'not-invoiced')\n    if billable is not None:\n        billable = (billable.lower() == u'billable')\n        entries = [e for e in entries if e.activity.billable == billable]\n    hours = sum([e.hours for e in entries if e.status not in statuses])\n    return '{0:.2f}'.format(hours)",
    "docstring": "Given an iterable of entries, return the total hours that have\n    not been invoiced. If billable is passed as 'billable' or 'nonbillable',\n    limit to the corresponding entries."
  },
  {
    "code": "def format_output(self, rendered_widgets):\n        ret = [u'<ul class=\"formfield\">']\n        for i, field in enumerate(self.fields):\n            label = self.format_label(field, i)\n            help_text = self.format_help_text(field, i)\n            ret.append(u'<li>%s %s %s</li>' % (\n                label, rendered_widgets[i], field.help_text and help_text))\n        ret.append(u'</ul>')\n        return ''.join(ret)",
    "docstring": "This output will yeild all widgets grouped in a un-ordered list"
  },
  {
    "code": "def resource_urls(request):\n    url_parsed = urlparse(settings.SEARCH_URL)\n    defaults = dict(\n        APP_NAME=__description__,\n        APP_VERSION=__version__,\n        SITE_URL=settings.SITE_URL.rstrip('/'),\n        SEARCH_TYPE=settings.SEARCH_TYPE,\n        SEARCH_URL=settings.SEARCH_URL,\n        SEARCH_IP='%s://%s:%s' % (url_parsed.scheme, url_parsed.hostname, url_parsed.port)\n    )\n    return defaults",
    "docstring": "Global values to pass to templates"
  },
  {
    "code": "def list_dvportgroups(dvs=None, portgroup_names=None, service_instance=None):\n    ret_dict = []\n    proxy_type = get_proxy_type()\n    if proxy_type == 'esxdatacenter':\n        datacenter = __salt__['esxdatacenter.get_details']()['datacenter']\n        dc_ref = _get_proxy_target(service_instance)\n    elif proxy_type == 'esxcluster':\n        datacenter = __salt__['esxcluster.get_details']()['datacenter']\n        dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)\n    if dvs:\n        dvs_refs = salt.utils.vmware.get_dvss(dc_ref, dvs_names=[dvs])\n        if not dvs_refs:\n            raise VMwareObjectRetrievalError('DVS \\'{0}\\' was not '\n                                             'retrieved'.format(dvs))\n        dvs_ref = dvs_refs[0]\n    get_all_portgroups = True if not portgroup_names else False\n    for pg_ref in salt.utils.vmware.get_dvportgroups(\n        parent_ref=dvs_ref if dvs else dc_ref,\n        portgroup_names=portgroup_names,\n        get_all_portgroups=get_all_portgroups):\n        ret_dict.append(_get_dvportgroup_dict(pg_ref))\n    return ret_dict",
    "docstring": "Returns a list of distributed virtual switch portgroups.\n    The list can be filtered by the portgroup names or by the DVS.\n\n    dvs\n        Name of the DVS containing the portgroups.\n        Default value is None.\n\n    portgroup_names\n        List of portgroup names to look for. If None, all portgroups are\n        returned.\n        Default value is None\n\n    service_instance\n        Service instance (vim.ServiceInstance) of the vCenter.\n        Default is None.\n\n    .. code-block:: bash\n\n        salt '*' vsphere.list_dvporgroups\n\n        salt '*' vsphere.list_dvportgroups dvs=dvs1\n\n        salt '*' vsphere.list_dvportgroups portgroup_names=[pg1]\n\n        salt '*' vsphere.list_dvportgroups dvs=dvs1 portgroup_names=[pg1]"
  },
  {
    "code": "def get_kwargs(self):\r\n        return {k: v for k, v in vars(self).items() if k not in self._ignored}",
    "docstring": "Return kwargs from attached attributes."
  },
  {
    "code": "def is_transaction_expired(transaction, block_number):\n    is_update_expired = (\n        isinstance(transaction, ContractSendChannelUpdateTransfer) and\n        transaction.expiration < block_number\n    )\n    if is_update_expired:\n        return True\n    is_secret_register_expired = (\n        isinstance(transaction, ContractSendSecretReveal) and\n        transaction.expiration < block_number\n    )\n    if is_secret_register_expired:\n        return True\n    return False",
    "docstring": "True if transaction cannot be mined because it has expired.\n\n    Some transactions are time dependent, e.g. the secret registration must be\n    done before the lock expiration, and the update transfer must be done\n    before the settlement window is over. If the current block is higher than\n    any of these expirations blocks, the transaction is expired and cannot be\n    successfully executed."
  },
  {
    "code": "def parse(self, file_name):\n        self.object = self.parsed_class()\n        with open(file_name, encoding='utf-8') as f:\n            self.parse_str(f.read())\n        return self.object",
    "docstring": "Parse entire file and return relevant object.\n\n        :param file_name: File path\n        :type file_name: str\n        :return: Parsed object"
  },
  {
    "code": "def referenced_vertices(self):\n        if len(self.entities) == 0:\n            return np.array([], dtype=np.int64)\n        referenced = np.concatenate([e.points for e in self.entities])\n        referenced = np.unique(referenced.astype(np.int64))\n        return referenced",
    "docstring": "Which vertices are referenced by an entity.\n\n        Returns\n        -----------\n        referenced_vertices: (n,) int, indexes of self.vertices"
  },
  {
    "code": "def drop(self, labels, dim=None):\n        if utils.is_scalar(labels):\n            labels = [labels]\n        if dim is None:\n            return self._drop_vars(labels)\n        else:\n            try:\n                index = self.indexes[dim]\n            except KeyError:\n                raise ValueError(\n                    'dimension %r does not have coordinate labels' % dim)\n            new_index = index.drop(labels)\n            return self.loc[{dim: new_index}]",
    "docstring": "Drop variables or index labels from this dataset.\n\n        Parameters\n        ----------\n        labels : scalar or list of scalars\n            Name(s) of variables or index labels to drop.\n        dim : None or str, optional\n            Dimension along which to drop index labels. By default (if\n            ``dim is None``), drops variables rather than index labels.\n\n        Returns\n        -------\n        dropped : Dataset"
  },
  {
    "code": "def _slice_bam(in_bam, region, tmp_dir, config):\n    name_file = os.path.splitext(os.path.basename(in_bam))[0]\n    out_file = os.path.join(tmp_dir, os.path.join(tmp_dir, name_file + _to_str(region) + \".bam\"))\n    sambamba = config_utils.get_program(\"sambamba\", config)\n    region = _to_sambamba(region)\n    with file_transaction(out_file) as tx_out_file:\n        cmd = (\"{sambamba} slice {in_bam} {region} -o {tx_out_file}\")\n        do.run(cmd.format(**locals()), \"Slice region\", {})\n    return out_file",
    "docstring": "Use sambamba to slice a bam region"
  },
  {
    "code": "def trace_walker(module):\n    for name, function in inspect.getmembers(module, inspect.isfunction):\n        yield None, function\n    for name, cls in inspect.getmembers(module, inspect.isclass):\n        yield cls, None\n        for name, method in inspect.getmembers(cls, inspect.ismethod):\n            yield cls, method\n        for name, function in inspect.getmembers(cls, inspect.isfunction):\n            yield cls, function\n        for name, accessor in inspect.getmembers(cls, lambda x: type(x) is property):\n            yield cls, accessor.fget\n            yield cls, accessor.fset\n            yield cls, accessor.fdel",
    "docstring": "Defines a generator used to walk into modules.\n\n    :param module: Module to walk.\n    :type module: ModuleType\n    :return: Class / Function / Method.\n    :rtype: object or object"
  },
  {
    "code": "def resource_url(path):\n    url = QtCore.QUrl.fromLocalFile(path)\n    return str(url.toString())",
    "docstring": "Get the a local filesystem url to a given resource.\n\n    .. versionadded:: 3.0\n\n    Note that in version 3.0 we removed the use of Qt Resource files in\n    favour of directly accessing on-disk resources.\n\n    :param path: Path to resource e.g. /home/timlinux/foo/bar.png\n    :type path: str\n\n    :return: A valid file url e.g. file:///home/timlinux/foo/bar.png\n    :rtype: str"
  },
  {
    "code": "def _initialize_context(self, trace_header):\n        sampled = None\n        if not global_sdk_config.sdk_enabled():\n            sampled = False\n        elif trace_header.sampled == 0:\n            sampled = False\n        elif trace_header.sampled == 1:\n            sampled = True\n        segment = FacadeSegment(\n            name='facade',\n            traceid=trace_header.root,\n            entityid=trace_header.parent,\n            sampled=sampled,\n        )\n        setattr(self._local, 'segment', segment)\n        setattr(self._local, 'entities', [])",
    "docstring": "Create a facade segment based on environment variables\n        set by AWS Lambda and initialize storage for subsegments."
  },
  {
    "code": "def lst_avg(lst):\n    salt.utils.versions.warn_until(\n        'Neon',\n        'This results of this function are currently being rounded.'\n        'Beginning in the Salt Neon release, results will no longer be '\n        'rounded and this warning will be removed.',\n        stacklevel=3\n    )\n    if not isinstance(lst, collections.Hashable):\n        return float(sum(lst)/len(lst))\n    return float(lst)",
    "docstring": "Returns the average value of a list.\n\n    .. code-block:: jinja\n\n        {% my_list = [1,2,3,4] -%}\n        {{ set my_list | avg }}\n\n    will be rendered as:\n\n    .. code-block:: yaml\n\n        2.5"
  },
  {
    "code": "def send_command(self, *args, **kwargs):\n        if len(args) >= 2:\n            expect_string = args[1]\n        else:\n            expect_string = kwargs.get(\"expect_string\")\n            if expect_string is None:\n                expect_string = r\"(OK|ERROR|Command not recognized\\.)\"\n                expect_string = self.RETURN + expect_string + self.RETURN\n                kwargs.setdefault(\"expect_string\", expect_string)\n        output = super(CiscoSSHConnection, self).send_command(*args, **kwargs)\n        return output",
    "docstring": "Send command to network device retrieve output until router_prompt or expect_string\n\n        By default this method will keep waiting to receive data until the network device prompt is\n        detected. The current network device prompt will be determined automatically.\n\n        command_string = command to execute\n        expect_string = pattern to search for uses re.search (use raw strings)\n        delay_factor = decrease the initial delay before we start looking for data\n        max_loops = number of iterations before we give up and raise an exception\n        strip_prompt = strip the trailing prompt from the output\n        strip_command = strip the leading command from the output"
  },
  {
    "code": "def author_list(self):\n        author_list = [self.submitter] + \\\n            [author for author in self.authors.all().exclude(pk=self.submitter.pk)]\n        return \",\\n\".join([author.get_full_name() for author in author_list])",
    "docstring": "The list of authors als text, for admin submission list overview."
  },
  {
    "code": "def create_ellipse(width,height,angle):\n    angle = angle / 180.0 * np.pi\n    thetas = np.linspace(0,2*np.pi,200)\n    a = width / 2.0\n    b = height / 2.0\n    x = a*np.cos(thetas)*np.cos(angle) - b*np.sin(thetas)*np.sin(angle)\n    y = a*np.cos(thetas)*np.sin(angle) + b*np.sin(thetas)*np.cos(angle)\n    z = np.zeros(thetas.shape)\n    return np.vstack((x,y,z)).T",
    "docstring": "Create parametric ellipse from 200 points."
  },
  {
    "code": "def find_by_name(self, item_name, items_list, name_list=None):\n        if not name_list:\n            names = [item.name for item in items_list if item]\n        else:\n            names = name_list\n        if item_name in names:\n            ind = names.index(item_name)\n            return items_list[ind]\n        return False",
    "docstring": "Return item from items_list with name item_name."
  },
  {
    "code": "def error(self, message, rofi_args=None, **kwargs):\n        rofi_args = rofi_args or []\n        args = ['rofi', '-e', message]\n        args.extend(self._common_args(allow_fullscreen=False, **kwargs))\n        args.extend(rofi_args)\n        self._run_blocking(args)",
    "docstring": "Show an error window.\n\n        This method blocks until the user presses a key.\n\n        Fullscreen mode is not supported for error windows, and if specified\n        will be ignored.\n\n        Parameters\n        ----------\n        message: string\n            Error message to show."
  },
  {
    "code": "def close(self):\n        with self._lock:\n            for server in self._servers.values():\n                server.close()\n            self._description = self._description.reset()\n            self._update_servers()\n            self._opened = False\n        if self._publish_tp:\n            self._events.put((self._listeners.publish_topology_closed,\n                              (self._topology_id,)))\n        if self._publish_server or self._publish_tp:\n            self.__events_executor.close()",
    "docstring": "Clear pools and terminate monitors. Topology reopens on demand."
  },
  {
    "code": "def real_time_sequencing(self, availability, oauth, event, target_calendars=()):\n        args = {\n            'oauth': oauth,\n            'event': event,\n            'target_calendars': target_calendars\n        }\n        if availability:\n            options = {}\n            options['sequence'] = self.map_availability_sequence(availability.get('sequence', None))\n            if availability.get('available_periods', None):\n                self.translate_available_periods(availability['available_periods'])\n                options['available_periods'] = availability['available_periods']\n        args['availability'] = options\n        return self.request_handler.post(endpoint='real_time_sequencing', data=args, use_api_key=True).json()",
    "docstring": "Generates an real time sequencing link to start the OAuth process with\n        an event to be automatically upserted\n\n        :param dict availability:  - A dict describing the availability details for the event:\n\n            :sequence: An Array of dics representing sequences to find availability for\n                       each sequence can contain.\n                :sequence_id - A string identifying this step in the sequence.\n                :ordinal - An Integer defining the order of this step in the sequence.\n                :participants      - A dict stating who is required for the availability\n                                 call\n                :required_duration - A dict stating the length of time the event will\n                                     last for\n                :event - A dict describing the event\n                :available_periods - A dict stating the available periods for the step\n            :available_periods - A dict stating the available periods for the sequence\n        :param dict oauth:   - A dict describing the OAuth flow required:\n            :scope             - A String representing the scopes to ask for\n                                 within the OAuth flow\n            :redirect_uri      - A String containing a url to redirect the\n                                 user to after completing the OAuth flow.\n            :scope             - A String representing additional state to\n                                 be passed within the OAuth flow.\n        :param dict event:     - A dict describing the event\n        :param list target_calendars: - An list of dics stating into which calendars\n                                        to insert the created event\n        See http://www.cronofy.com/developers/api#upsert-event for reference."
  },
  {
    "code": "def pause(msg=\"Press Enter to Continue...\"):\n    print('\\n' + Fore.YELLOW + msg + Fore.RESET, end='')\n    input()",
    "docstring": "press to continue"
  },
  {
    "code": "def atlas_init(blockstack_opts, db, recover=False, port=None):\n    if port is None:\n        port = blockstack_opts['rpc_port']\n    atlas_state = None\n    if is_atlas_enabled(blockstack_opts):\n        atlas_seed_peers = filter( lambda x: len(x) > 0, blockstack_opts['atlas_seeds'].split(\",\"))\n        atlas_blacklist = filter( lambda x: len(x) > 0, blockstack_opts['atlas_blacklist'].split(\",\"))\n        zonefile_dir = blockstack_opts['zonefiles']\n        my_hostname = blockstack_opts['atlas_hostname']\n        my_port = blockstack_opts['atlas_port']\n        initial_peer_table = atlasdb_init(blockstack_opts['atlasdb_path'], zonefile_dir, db, atlas_seed_peers, atlas_blacklist, validate=True, recover=recover)\n        atlas_peer_table_init(initial_peer_table)\n        atlas_state = atlas_node_init(my_hostname, my_port, blockstack_opts['atlasdb_path'], zonefile_dir, db.working_dir)\n    return atlas_state",
    "docstring": "Start up atlas functionality"
  },
  {
    "code": "def values(self):\n        return [self.policy.header_fetch_parse(k, v)\n                for k, v in self._headers]",
    "docstring": "Return a list of all the message's header values.\n\n        These will be sorted in the order they appeared in the original\n        message, or were added to the message, and may contain duplicates.\n        Any fields deleted and re-inserted are always appended to the header\n        list."
  },
  {
    "code": "def loadtxt_str(path:PathOrStr)->np.ndarray:\n    \"Return `ndarray` of `str` of lines of text from `path`.\"\n    with open(path, 'r') as f: lines = f.readlines()\n    return np.array([l.strip() for l in lines])",
    "docstring": "Return `ndarray` of `str` of lines of text from `path`."
  },
  {
    "code": "def open_download_stream(self, file_id):\n        gout = GridOut(self._collection, file_id)\n        gout._ensure_file()\n        return gout",
    "docstring": "Opens a Stream from which the application can read the contents of\n        the stored file specified by file_id.\n\n        For example::\n\n          my_db = MongoClient().test\n          fs = GridFSBucket(my_db)\n          # get _id of file to read.\n          file_id = fs.upload_from_stream(\"test_file\", \"data I want to store!\")\n          grid_out = fs.open_download_stream(file_id)\n          contents = grid_out.read()\n\n        Returns an instance of :class:`~gridfs.grid_file.GridOut`.\n\n        Raises :exc:`~gridfs.errors.NoFile` if no file with file_id exists.\n\n        :Parameters:\n          - `file_id`: The _id of the file to be downloaded."
  },
  {
    "code": "def from_pdb(cls, path, forcefield=None, loader=PDBFile, strict=True, **kwargs):\n        pdb = loader(path)\n        box = kwargs.pop('box', pdb.topology.getPeriodicBoxVectors())\n        positions = kwargs.pop('positions', pdb.positions)\n        velocities = kwargs.pop('velocities', getattr(pdb, 'velocities', None))\n        if strict and not forcefield:\n            from .md import FORCEFIELDS as forcefield\n            logger.info('! Forcefields for PDB not specified. Using default: %s',\n                        ', '.join(forcefield))\n        pdb.forcefield = ForceField(*list(process_forcefield(*forcefield)))\n        return cls(master=pdb.forcefield, topology=pdb.topology, positions=positions,\n                   velocities=velocities, box=box, path=path, **kwargs)",
    "docstring": "Loads topology, positions and, potentially, velocities and vectors,\n        from a PDB or PDBx file\n\n        Parameters\n        ----------\n        path : str\n            Path to PDB/PDBx file\n        forcefields : list of str\n            Paths to FFXML and/or FRCMOD forcefields. REQUIRED.\n\n        Returns\n        -------\n        pdb : SystemHandler\n            SystemHandler with topology, positions, and, potentially, velocities and\n            box vectors. Forcefields are embedded in the `master` attribute."
  },
  {
    "code": "def serve(application, host='127.0.0.1', port=8080, threads=4, **kw):\n\tserve_(application, host=host, port=int(port), threads=int(threads), **kw)",
    "docstring": "The recommended development HTTP server.\n\t\n\tNote that this server performs additional buffering and will not honour chunked encoding breaks."
  },
  {
    "code": "def check_errors(self):\n        errors = ERROR_PATTTERN.findall(self.out)\n        if errors:\n            self.log.error('! Errors occurred:')\n            self.log.error('\\n'.join(\n                [error.replace('\\r', '').strip() for error\n                 in chain(*errors) if error.strip()]\n            ))\n            self.log.error('! See \"%s.log\" for details.' % self.project_name)\n            if self.opt.exit_on_error:\n                self.log.error('! Exiting...')\n                sys.exit(1)",
    "docstring": "Check if errors occured during a latex run by\n        scanning the output."
  },
  {
    "code": "def format_name(self, name, indent_size=4):\n        name_block = ''\n        if self.short_desc is None:\n            name_block += name + '\\n'\n        else:\n            name_block += name + ': ' + self.short_desc + '\\n'\n        if self.long_desc is not None:\n            name_block += self.wrap_lines(self.long_desc, 1, indent_size=indent_size)\n            name_block += '\\n'\n        return name_block",
    "docstring": "Format the name of this verifier\n\n        The name will be formatted as:\n            <name>: <short description>\n                long description if one is given followed by \\n\n                otherwise no long description\n\n        Args:\n            name (string): A name for this validator\n            indent_size (int): The number of spaces to indent the\n                description\n        Returns:\n            string: The formatted name block with a short and or long\n                description appended."
  },
  {
    "code": "def add_package_dependency(self, package_name, version):\n        if not PEP440_VERSION_PATTERN.match(version):\n            raise ValueError('Invalid Version: \"{}\"'.format(version))\n        self.dependencies.add(PackageDependency(package_name, version))",
    "docstring": "Add a package to the list of dependencies.\n\n        :param package_name: The name of the package dependency\n        :type package_name: str\n        :param version: The (minimum) version of the package\n        :type version: str"
  },
  {
    "code": "def get_info(self, symbol, as_of=None):\n        version = self._read_metadata(symbol, as_of=as_of, read_preference=None)\n        handler = self._read_handler(version, symbol)\n        if handler and hasattr(handler, 'get_info'):\n            return handler.get_info(version)\n        return {}",
    "docstring": "Reads and returns information about the data stored for symbol\n\n        Parameters\n        ----------\n        symbol : `str`\n            symbol name for the item\n        as_of : `str` or int or `datetime.datetime`\n            Return the data as it was as_of the point in time.\n            `int` : specific version number\n            `str` : snapshot name which contains the version\n            `datetime.datetime` : the version of the data that existed as_of the requested point in time\n\n        Returns\n        -------\n        dictionary of the information (specific to the type of data)"
  },
  {
    "code": "def add(self, name, value):\n        normalized_name = normalize_name(name, self._normalize_overrides)\n        self._map[normalized_name].append(value)",
    "docstring": "Append the name-value pair to the record."
  },
  {
    "code": "def make_pattern(self, pattern, listsep=','):\n        if self is Cardinality.one:\n            return pattern\n        elif self is Cardinality.zero_or_one:\n            return self.schema % pattern\n        else:\n            return self.schema % (pattern, listsep, pattern)",
    "docstring": "Make pattern for a data type with the specified cardinality.\n\n        .. code-block:: python\n\n            yes_no_pattern = r\"yes|no\"\n            many_yes_no = Cardinality.one_or_more.make_pattern(yes_no_pattern)\n\n        :param pattern:  Regular expression for type (as string).\n        :param listsep:  List separator for multiple items (as string, optional)\n        :return: Regular expression pattern for type with cardinality."
  },
  {
    "code": "def create(cls, name, dead_interval=40, hello_interval=10,\n               hello_interval_type='normal', dead_multiplier=1,\n               mtu_mismatch_detection=True, retransmit_interval=5,\n               router_priority=1, transmit_delay=1,\n               authentication_type=None, password=None,\n               key_chain_ref=None):\n        json = {'name': name,\n                'authentication_type': authentication_type,\n                'password': password,\n                'key_chain_ref': element_resolver(key_chain_ref),\n                'dead_interval': dead_interval,\n                'dead_multiplier': dead_multiplier,\n                'hello_interval': hello_interval,\n                'hello_interval_type': hello_interval_type,\n                'mtu_mismatch_detection': mtu_mismatch_detection,\n                'retransmit_interval': retransmit_interval,\n                'router_priority': router_priority,\n                'transmit_delay': transmit_delay}\n        return ElementCreator(cls, json)",
    "docstring": "Create custom OSPF interface settings profile\n\n        :param str name: name of interface settings\n        :param int dead_interval: in seconds\n        :param str hello_interval: in seconds\n        :param str hello_interval_type: \\|normal\\|fast_hello\n        :param int dead_multipler: fast hello packet multipler\n        :param bool mtu_mismatch_detection: True|False\n        :param int retransmit_interval: in seconds\n        :param int router_priority: set priority\n        :param int transmit_delay: in seconds\n        :param str authentication_type: \\|password\\|message_digest\n        :param str password: max 8 chars (required when \n               authentication_type='password')\n        :param str,Element key_chain_ref: OSPFKeyChain (required when \n               authentication_type='message_digest')\n        :raises CreateElementFailed: create failed with reason\n        :return: instance with meta\n        :rtype: OSPFInterfaceSetting"
  },
  {
    "code": "def _setup_source_and_destination(self):\n        super(FetchTransformSaveWithSeparateNewCrashSourceApp, self) \\\n            ._setup_source_and_destination()\n        if self.config.new_crash_source.new_crash_source_class:\n            self.new_crash_source = \\\n                self.config.new_crash_source.new_crash_source_class(\n                    self.config.new_crash_source,\n                    name=self.app_instance_name,\n                    quit_check_callback=self.quit_check\n                )\n        else:\n            self.new_crash_source = self.source",
    "docstring": "use the base class to setup the source and destinations but add to\n        that setup the instantiation of the \"new_crash_source\""
  },
  {
    "code": "def unique_otuids(groups):\n    uniques = {key: set() for key in groups}\n    for i, group in enumerate(groups):\n        to_combine = groups.values()[:i]+groups.values()[i+1:]\n        combined = combine_sets(*to_combine)\n        uniques[group] = groups[group].difference(combined)\n    return uniques",
    "docstring": "Get unique OTUIDs of each category.\n\n    :type groups: Dict\n    :param groups: {Category name: OTUIDs in category}\n\n    :return type: dict\n    :return: Dict keyed on category name and unique OTUIDs as values."
  },
  {
    "code": "def _print_app(self, app, models):\n        self._print(self._app_start % app)\n        self._print_models(models)\n        self._print(self._app_end)",
    "docstring": "Print the models of app, showing them in a package."
  },
  {
    "code": "def load_json_from_file(file_path):\n    try:\n        with open(file_path) as f:\n            json_data = json.load(f)\n    except ValueError as e:\n        raise ValueError('Given file {} is not a valid JSON file: {}'.format(file_path, e))\n    else:\n        return json_data",
    "docstring": "Load schema from a JSON file"
  },
  {
    "code": "def add_graph(self, run_key, device_name, graph_def, debug=False):\n    graph_dict = (self._run_key_to_debug_graphs if debug else\n                  self._run_key_to_original_graphs)\n    if not run_key in graph_dict:\n      graph_dict[run_key] = dict()\n    graph_dict[run_key][tf.compat.as_str(device_name)] = (\n        debug_graphs_helper.DebugGraphWrapper(graph_def))",
    "docstring": "Add a GraphDef.\n\n    Args:\n      run_key: A key for the run, containing information about the feeds,\n        fetches, and targets.\n      device_name: The name of the device that the `GraphDef` is for.\n      graph_def: An instance of the `GraphDef` proto.\n      debug: Whether `graph_def` consists of the debug ops."
  },
  {
    "code": "def set_fun_prop(f, k, v):\n    if not hasattr(f, _FUN_PROPS):\n        setattr(f, _FUN_PROPS, {})\n    if not isinstance(getattr(f, _FUN_PROPS), dict):\n        raise InternalError(\"Invalid properties dictionary for %s\" % str(f))\n    getattr(f, _FUN_PROPS)[k] = v",
    "docstring": "Set the value of property `k` to be `v` in function `f`.\n\n    We define properties as annotations added to a function throughout\n    the process of defining a function for verification, e.g. the\n    argument types.  This sets function `f`'s property named `k` to be\n    value `v`.\n\n    Users should never access this function directly."
  },
  {
    "code": "def execute(self, *args, **kwargs):\n        try:\n            return self.client.execute(*args, **kwargs)\n        except requests.exceptions.HTTPError as err:\n            res = err.response\n            logger.error(\"%s response executing GraphQL.\" % res.status_code)\n            logger.error(res.text)\n            self.display_gorilla_error_if_found(res)\n            six.reraise(*sys.exc_info())",
    "docstring": "Wrapper around execute that logs in cases of failure."
  },
  {
    "code": "def do_we_have_enough_cookies(cj, class_name):\n    domain = 'class.coursera.org'\n    path = \"/\" + class_name\n    return cj.get('csrf_token', domain=domain, path=path) is not None",
    "docstring": "Check whether we have all the required cookies\n    to authenticate on class.coursera.org."
  },
  {
    "code": "def load_cml(cml_filename):\n    parser = make_parser()\n    parser.setFeature(feature_namespaces, 0)\n    dh = CMLMoleculeLoader()\n    parser.setContentHandler(dh)\n    parser.parse(cml_filename)\n    return dh.molecules",
    "docstring": "Load the molecules from a CML file\n\n       Argument:\n        | ``cml_filename``  --  The filename of a CML file.\n\n       Returns a list of molecule objects with optional molecular graph\n       attribute and extra attributes."
  },
  {
    "code": "def generate_id(self, obj):\n        object_type = type(obj).__name__.lower()\n        return '{}_{}'.format(object_type, self.get_object_id(obj))",
    "docstring": "Generate unique document id for ElasticSearch."
  },
  {
    "code": "def get(self, block=True, timeout=None):\n        return self._queue.get(block, timeout)",
    "docstring": "Get item from underlying queue."
  },
  {
    "code": "def get_cached_data(\n        step: 'projects.ProjectStep'\n) -> typing.Union[None, STEP_DATA]:\n    cache_path = step.report.results_cache_path\n    if not os.path.exists(cache_path):\n        return None\n    out = create_data(step)\n    try:\n        with open(cache_path, 'r') as f:\n            cached_data = json.load(f)\n    except Exception:\n        return None\n    file_writes = [\n        file_io.entry_from_dict(fw)\n        for fw in cached_data['file_writes']\n    ]\n    return out \\\n        ._replace(**cached_data) \\\n        ._replace(file_writes=file_writes)",
    "docstring": "Attempts to load and return the cached step data for the specified step. If\n    not cached data exists, or the cached data is corrupt, a None value is\n    returned instead.\n\n    :param step:\n        The step for which the cached data should be loaded\n\n    :return:\n        Either a step data structure containing the cached step data or None\n        if no cached data exists for the step"
  },
  {
    "code": "def check(degree, knot_vector, num_ctrlpts):\n    try:\n        if knot_vector is None or len(knot_vector) == 0:\n            raise ValueError(\"Input knot vector cannot be empty\")\n    except TypeError as e:\n        print(\"An error occurred: {}\".format(e.args[-1]))\n        raise TypeError(\"Knot vector must be a list or tuple\")\n    except Exception:\n        raise\n    if len(knot_vector) != degree + num_ctrlpts + 1:\n        return False\n    prev_knot = knot_vector[0]\n    for knot in knot_vector:\n        if prev_knot > knot:\n            return False\n        prev_knot = knot\n    return True",
    "docstring": "Checks the validity of the input knot vector.\n\n    Please refer to The NURBS Book (2nd Edition), p.50 for details.\n\n    :param degree: degree of the curve or the surface\n    :type degree: int\n    :param knot_vector: knot vector to be checked\n    :type knot_vector: list, tuple\n    :param num_ctrlpts: number of control points\n    :type num_ctrlpts: int\n    :return: True if the knot vector is valid, False otherwise\n    :rtype: bool"
  },
  {
    "code": "def _get_elements(mol, label):\n        elements = [int(mol.GetAtom(i).GetAtomicNum()) for i in label]\n        return elements",
    "docstring": "The the elements of the atoms in the specified order\n\n        Args:\n            mol: The molecule. OpenBabel OBMol object.\n            label: The atom indices. List of integers.\n\n        Returns:\n            Elements. List of integers."
  },
  {
    "code": "def kth_to_last(head, k):\n    if not (head or k > -1):\n        return False\n    p1 = head\n    p2 = head\n    for i in range(1, k+1):\n        if p1 is None:\n            raise IndexError\n        p1 = p1.next\n    while p1:\n        p1 = p1.next\n        p2 = p2.next\n    return p2",
    "docstring": "This is an optimal method using iteration.\n    We move p1 k steps ahead into the list.\n    Then we move p1 and p2 together until p1 hits the end."
  },
  {
    "code": "def get_bool(self, key: str) -> Optional[bool]:\n        v = self.get(key)\n        if v is None:\n            return None\n        if v in ['true', 'True']:\n            return True\n        if v in ['false', 'False']:\n            return False\n        raise ConfigTypeError(self.full_key(key), v, 'bool')",
    "docstring": "Returns an optional configuration value, as a bool, by its key, or None if it doesn't exist.\n        If the configuration value isn't a legal boolean, this function will throw an error.\n\n        :param str key: The requested configuration key.\n        :return: The configuration key's value, or None if one does not exist.\n        :rtype: Optional[bool]\n        :raises ConfigTypeError: The configuration value existed but couldn't be coerced to bool."
  },
  {
    "code": "def applyReferrerVouchersTemporarily(sender,**kwargs):\r\n    if not getConstant('referrals__enableReferralProgram'):\r\n        return\r\n    logger.debug('Signal fired to temporarily apply referrer vouchers.')\r\n    reg = kwargs.pop('registration')\r\n    try:\r\n        c = Customer.objects.get(user__email=reg.email)\r\n        vouchers = c.getReferralVouchers()\r\n    except ObjectDoesNotExist:\r\n        vouchers = None\r\n    if not vouchers:\r\n        logger.debug('No referral vouchers found.')\r\n        return\r\n    for v in vouchers:\r\n        TemporaryVoucherUse(voucher=v,registration=reg,amount=0).save()",
    "docstring": "Unlike voucher codes which have to be manually supplied, referrer discounts are\r\n    automatically applied here, assuming that the referral program is enabled."
  },
  {
    "code": "def folder2ver(folder):\n    ver = folder.split('EnergyPlus')[-1]\n    ver = ver[1:]\n    splitapp = ver.split('-')\n    ver = '.'.join(splitapp)\n    return ver",
    "docstring": "get the version number from the E+ install folder"
  },
  {
    "code": "def __connect(host, port, username, password, private_key):\n        ssh = paramiko.SSHClient()\n        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n        if private_key is not None and password is not None:\n            private_key = paramiko.RSAKey.from_private_key_file(private_key, password)\n        elif private_key is not None:\n            private_key = paramiko.RSAKey.from_private_key_file(private_key, password)\n        try:\n            ssh.connect(host, port, username, password, private_key)\n        except Exception as e:\n            raise e\n        return ssh",
    "docstring": "Establish remote connection\n\n        :param host: Hostname or IP address to connect to\n        :param port: Port number to use for SSH\n        :param username: Username credentials for SSH access\n        :param password: Password credentials for SSH access (or private key passphrase)\n        :param private_key: Private key to bypass clear text password\n        :return: Paramiko SSH client instance if connection was established\n        :raises Exception if connection was unsuccessful"
  },
  {
    "code": "def get_file(self, index, doc_type, id=None):\n        data = self.get(index, doc_type, id)\n        return data['_name'], base64.standard_b64decode(data['content'])",
    "docstring": "Return the filename and memory data stream"
  },
  {
    "code": "def save(self, specfiles=None, compress=True, path=None):\n        if specfiles is None:\n            specfiles = [_ for _ in viewkeys(self.info)]\n        else:\n            specfiles = aux.toList(specfiles)\n        for specfile in specfiles:\n            if specfile not in self.info:\n                warntext = 'Error while calling \"SiiContainer.save()\": \"%s\" is'\\\n                           ' not present in \"SiiContainer.info\"!'\\\n                            % (specfile, )\n                warnings.warn(warntext)\n                continue\n            else:\n                path = self.info[specfile]['path'] if path is None else path\n            with aux.PartiallySafeReplace() as msr:\n                filename = specfile + '.siic'\n                filepath = aux.joinpath(path, filename)\n                with msr.open(filepath, mode='w+b') as openfile:\n                    self._writeContainer(openfile, specfile, compress)",
    "docstring": "Writes the specified specfiles to ``siic`` files on the hard disk.\n\n        .. note::\n            If ``.save()`` is called and no ``siic`` files are present in the\n            specified path new files are generated, otherwise old files are\n            replaced.\n\n        :param specfiles: the name of an ms-run file or a list of names. If None\n            all specfiles are selected.\n        :param compress: bool, True to use zip file compression\n        :param path: filedirectory to which the ``siic`` files are written. By\n            default the parameter is set to ``None`` and the filedirectory is\n            read from ``self.info[specfile]['path']``"
  },
  {
    "code": "def _firmware_update(firmwarefile='', host='',\n                     directory=''):\n    dest = os.path.join(directory, firmwarefile[7:])\n    __salt__['cp.get_file'](firmwarefile, dest)\n    username = __pillar__['proxy']['admin_user']\n    password = __pillar__['proxy']['admin_password']\n    __salt__['dracr.update_firmware'](dest,\n                                      host=host,\n                                      admin_username=username,\n                                      admin_password=password)",
    "docstring": "Update firmware for a single host"
  },
  {
    "code": "def table(self):\n        if hasattr(self.data, 'table_on') and self.data.table_on:\n            assert_index_sane(self.data.table, len(self.song.tables))\n            return self.song.tables[self.data.table]",
    "docstring": "a ```pylsdj.Table``` referencing the instrument's table, or None\n        if the instrument doesn't have a table"
  },
  {
    "code": "def die(self):\n        if self.process:\n            _log(self.logging,\n                 'Stopping {0} server with PID: {1} running at {2}.'\n                     .format(self.__class__.__name__, self.process.pid,\n                             self.check_url))\n            self._kill()",
    "docstring": "Stops the server if it is running."
  },
  {
    "code": "def get_healthcheck(self, service_id, version_number, name):\n\t\tcontent = self._fetch(\"/service/%s/version/%d/healthcheck/%s\" % (service_id, version_number, name))\n\t\treturn FastlyHealthCheck(self, content)",
    "docstring": "Get the healthcheck for a particular service and version."
  },
  {
    "code": "def load_wikiqa():\n    dataset_path = _load('wikiqa')\n    data = _load_csv(dataset_path, 'data', set_index=True)\n    questions = _load_csv(dataset_path, 'questions', set_index=True)\n    sentences = _load_csv(dataset_path, 'sentences', set_index=True)\n    vocabulary = _load_csv(dataset_path, 'vocabulary', set_index=True)\n    entities = {\n        'data': (data, 'd3mIndex', None),\n        'questions': (questions, 'qIndex', None),\n        'sentences': (sentences, 'sIndex', None),\n        'vocabulary': (vocabulary, 'index', None)\n    }\n    relationships = [\n        ('questions', 'qIndex', 'data', 'qIndex'),\n        ('sentences', 'sIndex', 'data', 'sIndex')\n    ]\n    target = data.pop('isAnswer').values\n    return Dataset(load_wikiqa.__doc__, data, target, accuracy_score, startify=True,\n                   entities=entities, relationships=relationships)",
    "docstring": "A Challenge Dataset for Open-Domain Question Answering.\n\n    WikiQA dataset is a publicly available set of question and sentence (QS) pairs,\n    collected and annotated for research on open-domain question answering.\n\n    source: \"Microsoft\"\n    sourceURI: \"https://www.microsoft.com/en-us/research/publication/wikiqa-a-challenge-dataset-for-open-domain-question-answering/#\""
  },
  {
    "code": "def loo_compare(psisloo1, psisloo2):\n    loores = psisloo1.pointwise.join(\n        psisloo2.pointwise,\n        lsuffix = '_m1',\n        rsuffix = '_m2')\n    loores['pw_diff'] = loores.pointwise_elpd_m2 - loores.pointwise_elpd_m1\n    sum_elpd_diff = loores.apply(numpy.sum).pw_diff\n    sd_elpd_diff = loores.apply(numpy.std).pw_diff\n    elpd_diff = {\n        'diff' : sum_elpd_diff,\n        'se_diff' : math.sqrt(len(loores.pw_diff)) * sd_elpd_diff\n        }\n    return elpd_diff",
    "docstring": "Compares two models using pointwise approximate leave-one-out cross validation.\n    \n    For the method to be valid, the two models should have been fit on the same input data. \n\n    Parameters\n    -------------------\n    psisloo1 : Psisloo object for model1\n    psisloo2 : Psisloo object for model2\n\n    Returns\n    -------------------\n    Dict with two values:\n\n        diff: difference in elpd (estimated log predictive density) \n                between two models, where a positive value indicates\n                that model2 is a better fit than model1.\n\n        se_diff: estimated standard error of the difference\n                between model2 & model1."
  },
  {
    "code": "def get_user(self, username=None):\n        username = username or self.username or ''\n        url = self.url('GET_USER', username=username)\n        response = self.dispatch('GET', url)\n        try:\n            return (response[0], response[1]['user'])\n        except TypeError:\n            pass\n        return response",
    "docstring": "Returns user informations.\n            If username is not defined, tries to return own informations."
  },
  {
    "code": "def _inner_default(x1, x2):\n    order = 'F' if all(a.data.flags.f_contiguous for a in (x1, x2)) else 'C'\n    if is_real_dtype(x1.dtype):\n        if x1.size > THRESHOLD_MEDIUM:\n            return np.tensordot(x1, x2, [range(x1.ndim)] * 2)\n        else:\n            return np.dot(x1.data.ravel(order),\n                          x2.data.ravel(order))\n    else:\n        return np.vdot(x2.data.ravel(order),\n                       x1.data.ravel(order))",
    "docstring": "Default Euclidean inner product implementation."
  },
  {
    "code": "def _make_default_header(self):\n        td_max = 0\n        for idx, tr in enumerate(self._tr_nodes):\n            td_count = len(tr.contents.filter_tags(matches=ftag('td')))\n            if td_count > td_max:\n                td_max = td_count\n        self._log('creating default header (%d columns)' % td_max)\n        return [ 'column%d' % n for n in range(0,td_max) ]",
    "docstring": "Return a generic placeholder header based on the tables column count"
  },
  {
    "code": "def evaluate_feature_performance(project, force=False):\n    if not force and not project.on_pr():\n        raise SkippedValidationTest('Not on PR')\n    out = project.build()\n    X_df, y, features = out['X_df'], out['y'], out['features']\n    proposed_feature = get_proposed_feature(project)\n    accepted_features = get_accepted_features(features, proposed_feature)\n    evaluator = GFSSFAcceptanceEvaluator(X_df, y, accepted_features)\n    accepted = evaluator.judge(proposed_feature)\n    if not accepted:\n        raise FeatureRejected",
    "docstring": "Evaluate feature performance"
  },
  {
    "code": "def plot_string_match(sf,regex,field,**kwargs):\n    index,shape_records = string_match(sf,regex,field)\n    plot(shape_records,**kwargs)",
    "docstring": "Plot the geometry of a shapefile whose fields match a regular expression given\n\n    :param sf: shapefile\n    :type sf: shapefile object\n    :regex: regular expression to match\n    :type regex: string\n    :field: field number to be matched with the regex\n    :type field: integer"
  },
  {
    "code": "def load_names(self):\n        self.all_male_first_names = load_csv_data('male-first-names.csv')\n        self.all_female_first_names = load_csv_data('female-first-names.csv')\n        self.all_last_names = load_csv_data('CSV_Database_of_Last_Names.csv')",
    "docstring": "Loads a name database from package data\n\n        Uses data files sourced from\n        http://www.quietaffiliate.com/free-first-name-and-last-name-databases-csv-and-sql/"
  },
  {
    "code": "def cancel(self):\n        if (not self.cancelled) and (self._fn is not None):\n            self._cancelled = True\n            self._drop_fn()",
    "docstring": "Cancel the scheduled task."
  },
  {
    "code": "def Copy(self):\n    result = QueueManager(store=self.data_store, token=self.token)\n    result.prev_frozen_timestamps = self.prev_frozen_timestamps\n    result.frozen_timestamp = self.frozen_timestamp\n    return result",
    "docstring": "Return a copy of the queue manager.\n\n    Returns:\n    Copy of the QueueManager object.\n    NOTE: pending writes/deletions are not copied. On the other hand, if the\n    original object has a frozen timestamp, a copy will have it as well."
  },
  {
    "code": "def discard(sample, embedding):\n    unembeded = {}\n    for v, chain in iteritems(embedding):\n        vals = [sample[u] for u in chain]\n        if _all_equal(vals):\n            unembeded[v] = vals.pop()\n        else:\n            return\n    yield unembeded",
    "docstring": "Discards the sample if broken.\n\n    Args:\n        sample (dict): A sample of the form {v: val, ...} where v is\n            a variable in the target graph and val is the associated value as\n            determined by a binary quadratic model sampler.\n        embedding (dict): The mapping from the source graph to the target graph.\n            Should be of the form {v: {s, ...}, ...} where v is a node in the\n            source graph and s is a node in the target graph.\n\n    Yields:\n        dict: The unembedded sample is no chains were broken."
  },
  {
    "code": "def create_connection(self, alias='default', **kwargs):\n        kwargs.setdefault('serializer', serializer)\n        conn = self._conns[alias] = Elasticsearch(**kwargs)\n        return conn",
    "docstring": "Construct an instance of ``elasticsearch.Elasticsearch`` and register\n        it under given alias."
  },
  {
    "code": "def sql_key(self, generation, sql, params, order, result_type,\n                using='default'):\n        suffix = self.keygen.gen_key(sql, params, order, result_type)\n        using = settings.DB_CACHE_KEYS[using]\n        return '%s_%s_query_%s.%s' % (self.prefix, using, generation, suffix)",
    "docstring": "Return the specific cache key for the sql query described by the\n        pieces of the query and the generation key."
  },
  {
    "code": "def get_single_outfile (directory, archive, extension=\"\"):\n    outfile = os.path.join(directory, stripext(archive))\n    if os.path.exists(outfile + extension):\n        i = 1\n        newfile = \"%s%d\" % (outfile, i)\n        while os.path.exists(newfile + extension):\n            newfile = \"%s%d\" % (outfile, i)\n            i += 1\n        outfile = newfile\n    return outfile + extension",
    "docstring": "Get output filename if archive is in a single file format like gzip."
  },
  {
    "code": "def relation_set(relation_id=None, relation_settings=None, **kwargs):\n    try:\n        if relation_id in relation_ids('cluster'):\n            return leader_set(settings=relation_settings, **kwargs)\n        else:\n            raise NotImplementedError\n    except NotImplementedError:\n        return _relation_set(relation_id=relation_id,\n                             relation_settings=relation_settings, **kwargs)",
    "docstring": "Attempt to use leader-set if supported in the current version of Juju,\n    otherwise falls back on relation-set.\n\n    Note that we only attempt to use leader-set if the provided relation_id is\n    a peer relation id or no relation id is provided (in which case we assume\n    we are within the peer relation context)."
  },
  {
    "code": "def seek_in_frame(self, pos, *args, **kwargs):\n        super().seek(self._total_offset + pos, *args, **kwargs)",
    "docstring": "Seeks relative to the total offset of the current contextual frames."
  },
  {
    "code": "def iter_parents(self, paths='', **kwargs):\n        skip = kwargs.get(\"skip\", 1)\n        if skip == 0:\n            skip = 1\n        kwargs['skip'] = skip\n        return self.iter_items(self.repo, self, paths, **kwargs)",
    "docstring": "Iterate _all_ parents of this commit.\n\n        :param paths:\n            Optional path or list of paths limiting the Commits to those that\n            contain at least one of the paths\n        :param kwargs: All arguments allowed by git-rev-list\n        :return: Iterator yielding Commit objects which are parents of self"
  },
  {
    "code": "def set_state(self, state):\n        for k, v in state.items():\n            setattr(self, k, v)",
    "docstring": "Set the view state.\n\n        The passed object is the persisted `self.state` bunch.\n\n        May be overriden."
  },
  {
    "code": "def separators(self, reordered = True):\n        if reordered:\n            return [list(self.snrowidx[self.sncolptr[k]+self.snptr[k+1]-self.snptr[k]:self.sncolptr[k+1]]) for k in range(self.Nsn)] \n        else:\n            return [list(self.__p[self.snrowidx[self.sncolptr[k]+self.snptr[k+1]-self.snptr[k]:self.sncolptr[k+1]]]) for k in range(self.Nsn)]",
    "docstring": "Returns a list of separator sets"
  },
  {
    "code": "def get_avatar_url(self, size=2):\n        hashbytes = self.get_ps('avatar_hash')\n        if hashbytes != \"\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\":\n            ahash = hexlify(hashbytes).decode('ascii')\n        else:\n            ahash = 'fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb'\n        sizes = {\n            0: '',\n            1: '_medium',\n            2: '_full',\n        }\n        url = \"http://cdn.akamai.steamstatic.com/steamcommunity/public/images/avatars/%s/%s%s.jpg\"\n        return url % (ahash[:2], ahash, sizes[size])",
    "docstring": "Get URL to avatar picture\n\n        :param size: possible values are ``0``, ``1``, or ``2`` corresponding to small, medium, large\n        :type size: :class:`int`\n        :return: url to avatar\n        :rtype: :class:`str`"
  },
  {
    "code": "def _generate_input(options):\n    if options.input:\n        fp = open(options.input) if options.input != \"-\" else sys.stdin\n        for string in fp.readlines():\n            yield string\n    if options.strings:\n        for string in options.strings:\n            yield string",
    "docstring": "First send strings from any given file, one string per line, sends\n    any strings provided on the command line.\n\n    :param options: ArgumentParser or equivalent to provide\n        options.input and options.strings.\n    :return: string"
  },
  {
    "code": "def store(self, thing):\n        to_store = {'field1': thing.field1,\n                    'date_field': thing.date_field,\n                    }\n        to_store['stuff'] = Binary(cPickle.dumps(thing.stuff))\n        self._arctic_lib.check_quota()\n        self._collection.insert_one(to_store)",
    "docstring": "Simple persistence method"
  },
  {
    "code": "async def list(self, **params) -> Mapping:\n        response = await self.docker._query_json(\"images/json\", \"GET\", params=params)\n        return response",
    "docstring": "List of images"
  },
  {
    "code": "def list_sessions(self) -> List[Session]:\n        data = self._client.get(\"/sessions\")\n        return [Session.from_json(item) for item in data[\"sessions\"]]",
    "docstring": "List all the active sessions in Livy."
  },
  {
    "code": "def to_java_rdd(jsc, features, labels, batch_size):\n    data_sets = java_classes.ArrayList()\n    num_batches = int(len(features) / batch_size)\n    for i in range(num_batches):\n        xi = ndarray(features[:batch_size].copy())\n        yi = ndarray(labels[:batch_size].copy())\n        data_set = java_classes.DataSet(xi.array, yi.array)\n        data_sets.add(data_set)\n        features = features[batch_size:]\n        labels = labels[batch_size:]\n    return jsc.parallelize(data_sets)",
    "docstring": "Convert numpy features and labels into a JavaRDD of\n    DL4J DataSet type.\n\n    :param jsc: JavaSparkContext from pyjnius\n    :param features: numpy array with features\n    :param labels: numpy array with labels:\n    :return: JavaRDD<DataSet>"
  },
  {
    "code": "def template_delete(call=None, kwargs=None):\n    if call != 'function':\n        raise SaltCloudSystemExit(\n            'The template_delete function must be called with -f or --function.'\n        )\n    if kwargs is None:\n        kwargs = {}\n    name = kwargs.get('name', None)\n    template_id = kwargs.get('template_id', None)\n    if template_id:\n        if name:\n            log.warning(\n                'Both the \\'template_id\\' and \\'name\\' arguments were provided. '\n                '\\'template_id\\' will take precedence.'\n            )\n    elif name:\n        template_id = get_template_id(kwargs={'name': name})\n    else:\n        raise SaltCloudSystemExit(\n            'The template_delete function requires either a \\'name\\' or a \\'template_id\\' '\n            'to be provided.'\n        )\n    server, user, password = _get_xml_rpc()\n    auth = ':'.join([user, password])\n    response = server.one.template.delete(auth, int(template_id))\n    data = {\n        'action': 'template.delete',\n        'deleted': response[0],\n        'template_id': response[1],\n        'error_code': response[2],\n    }\n    return data",
    "docstring": "Deletes the given template from OpenNebula. Either a name or a template_id must\n    be supplied.\n\n    .. versionadded:: 2016.3.0\n\n    name\n        The name of the template to delete. Can be used instead of ``template_id``.\n\n    template_id\n        The ID of the template to delete. Can be used instead of ``name``.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -f template_delete opennebula name=my-template\n        salt-cloud --function template_delete opennebula template_id=5"
  },
  {
    "code": "def _node_is_match(qualified_name, package_names, fqn):\n    if len(qualified_name) == 1 and fqn[-1] == qualified_name[0]:\n        return True\n    if qualified_name[0] in package_names:\n        if is_selected_node(fqn, qualified_name):\n            return True\n    for package_name in package_names:\n        local_qualified_node_name = [package_name] + qualified_name\n        if is_selected_node(fqn, local_qualified_node_name):\n            return True\n    return False",
    "docstring": "Determine if a qualfied name matches an fqn, given the set of package\n    names in the graph.\n\n    :param List[str] qualified_name: The components of the selector or node\n        name, split on '.'.\n    :param Set[str] package_names: The set of pacakge names in the graph.\n    :param List[str] fqn: The node's fully qualified name in the graph."
  },
  {
    "code": "def create_with_secret(self, name, secret, encryption):\n        try:\n            encryption = encryption or DEFAULT_ENCRYPTION\n            enc = ENCRYPTION_MAP[encryption]\n        except KeyError:\n            raise TypeError('encryption must be one of \"cleartext\", \"md5\"'\n                            ' or \"sha512\"')\n        cmd = 'username %s secret %s %s' % (name, enc, secret)\n        return self.configure(cmd)",
    "docstring": "Creates a new user on the local node\n\n        Args:\n            name (str): The name of the user to craete\n\n            secret (str): The secret (password) to assign to this user\n\n            encryption (str): Specifies how the secret is encoded.  Valid\n                values are \"cleartext\", \"md5\", \"sha512\".  The default is\n                \"cleartext\"\n\n        Returns:\n            True if the operation was successful otherwise False"
  },
  {
    "code": "def get_knowledge_category_metadata(self):\n        metadata = dict(self._mdata['knowledge_category'])\n        metadata.update({'existing_id_values': self._my_map['knowledgeCategoryId']})\n        return Metadata(**metadata)",
    "docstring": "Gets the metadata for a knowledge category.\n\n        return: (osid.Metadata) - metadata for the knowledge category\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def instruction(self, val):\n        self._instruction = val\n        if isinstance(val, tuple):\n            if len(val) is 2:\n                self._action, self.command = val\n            else:\n                self._action, self.command, self.extra = val\n        else:\n            split = val.split(\" \", 1)\n            if split[0] == \"FROM\":\n                split = val.split(\" \", 2)\n            if len(split) == 3:\n                self._action, self.command, self.extra = split\n            else:\n                self._action, self.command = split",
    "docstring": "Set the action and command from an instruction"
  },
  {
    "code": "def set_basic(self, realm='authentication required'):\n        dict.clear(self)\n        dict.update(self, {'__auth_type__': 'basic', 'realm': realm})\n        if self.on_update:\n            self.on_update(self)",
    "docstring": "Clear the auth info and enable basic auth."
  },
  {
    "code": "def __do_filter_sub(self, scanline, result):\n        ai = 0\n        for i in range(self.fu, len(result)):\n            x = scanline[i]\n            a = scanline[ai]\n            result[i] = (x - a) & 0xff\n            ai += 1",
    "docstring": "Sub filter."
  },
  {
    "code": "def prepare_sparse_params(self, param_rowids):\n        if not self._kvstore:\n            return\n        assert(isinstance(param_rowids, dict))\n        for param_name, rowids in param_rowids.items():\n            if isinstance(rowids, (tuple, list)):\n                rowids_1d = []\n                for r in rowids:\n                    rowids_1d.append(r.reshape((-1,)).astype(np.int64))\n                rowid = mx.nd.concat(*rowids_1d, dim=0)\n            else:\n                rowid = rowids\n            param_idx = self._exec_group.param_names.index(param_name)\n            param_val = self._exec_group.param_arrays[param_idx]\n            self._kvstore.row_sparse_pull(param_name, param_val, row_ids=rowid,\n                                          priority=-param_idx)",
    "docstring": "Prepares the module for processing a data batch by pulling row_sparse\n        parameters from kvstore to all devices based on rowids.\n\n        Parameters\n        ----------\n        param_rowids : dict of str to NDArray of list of NDArrays"
  },
  {
    "code": "def set_value(self, value):\r\n        if self.__is_value_array:\r\n            if len(value) == self.__report_count:\r\n                for index, item in enumerate(value):\r\n                    self.__setitem__(index, item)\r\n            else:\r\n                raise ValueError(\"Value size should match report item size \"\\\r\n                    \"length\" )\r\n        else:\r\n            self.__value = value & ((1 << self.__bit_size) - 1)",
    "docstring": "Set usage value within report"
  },
  {
    "code": "def _scheduled_check_for_summaries(self):\n        if self._analysis_process is None:\n            return\n        timed_out = time.time() - self._analyze_start_time > self.time_limit\n        if timed_out:\n            self._handle_results('Analysis timed out but managed\\n'\n                                 ' to get lower turn results.',\n                                 'Analysis timed out with no results.')\n            return\n        try:\n            self._analysis_process.join(0.001)\n        except AssertionError:\n            pass\n        if not self._analysis_process.is_alive():\n            self._handle_results('Completed analysis.',\n                                 'Unable to find the game on screen.')\n            return\n        self._base.after(self._POLL_PERIOD_MILLISECONDS,\n                         self._scheduled_check_for_summaries)",
    "docstring": "Present the results if they have become available or timed out."
  },
  {
    "code": "def round_(values, decimals=None, width=0,\n           lfill=None, rfill=None, **kwargs):\n    if decimals is None:\n        decimals = hydpy.pub.options.reprdigits\n    with hydpy.pub.options.reprdigits(decimals):\n        if isinstance(values, abctools.IterableNonStringABC):\n            string = repr_values(values)\n        else:\n            string = repr_(values)\n        if (lfill is not None) and (rfill is not None):\n            raise ValueError(\n                'For function `round_` values are passed for both arguments '\n                '`lfill` and `rfill`.  This is not allowed.')\n        if (lfill is not None) or (rfill is not None):\n            width = max(width, len(string))\n            if lfill is not None:\n                string = string.rjust(width, lfill)\n            else:\n                string = string.ljust(width, rfill)\n        print(string, **kwargs)",
    "docstring": "Prints values with a maximum number of digits in doctests.\n\n    See the documentation on function |repr| for more details.  And\n    note thate the option keyword arguments are passed to the print function.\n\n    Usually one would apply function |round_| on a single or a vector\n    of numbers:\n\n    >>> from hydpy import round_\n    >>> round_(1./3., decimals=6)\n    0.333333\n    >>> round_((1./2., 1./3., 1./4.), decimals=4)\n    0.5, 0.3333, 0.25\n\n    Additionally, one can supply a `width` and a `rfill` argument:\n    >>> round_(1.0, width=6, rfill='0')\n    1.0000\n\n    Alternatively, one can use the `lfill` arguments, which\n    might e.g. be usefull for aligning different strings:\n\n    >>> round_('test', width=6, lfill='_')\n    __test\n\n    Using both the `lfill` and the `rfill` argument raises an error:\n\n    >>> round_(1.0, lfill='_', rfill='0')\n    Traceback (most recent call last):\n    ...\n    ValueError: For function `round_` values are passed for both \\\narguments `lfill` and `rfill`.  This is not allowed."
  },
  {
    "code": "def append(self, newconfig):\n        for attr_name in (\n            'title', 'body', 'author', 'date',\n            'strip', 'strip_id_or_class', 'strip_image_src',\n            'single_page_link', 'single_page_link_in_feed',\n            'next_page_link', 'http_header'\n        ):\n            current_set = getattr(self, attr_name)\n            for val in getattr(newconfig, attr_name):\n                current_set.add(val)\n            setattr(self, attr_name, current_set)\n        for attr_name in (\n            'parser', 'tidy', 'prune', 'autodetect_on_failure'\n        ):\n            if getattr(self, attr_name) is None:\n                if getattr(newconfig, attr_name) is None:\n                    setattr(self, attr_name, self.defaults[attr_name])\n                else:\n                    setattr(self, attr_name, getattr(newconfig, attr_name))\n        if self.parser == 'libxml':\n            self.parser = 'lxml'\n        for attr_name in ('find_string', 'replace_string', ):\n            getattr(self, attr_name).extend(getattr(newconfig, attr_name))\n        if self.find_string:\n            self.replace_patterns = zip(\n                self.find_string, self.replace_string)\n        else:\n            self.replace_patterns = None",
    "docstring": "Append another site config to current instance.\n\n        All ``newconfig`` attributes are appended one by one to ours.\n        Order matters, eg. current instance values will come first when\n        merging.\n\n        Thus, if you plan to use some sort of global site config with\n        more generic directives, append it last for specific directives\n        to be tried first.\n\n        .. note:: this method is also aliased to :meth:`merge`."
  },
  {
    "code": "def stats(self, request):\n        doc = HtmlDocument(title='Live server stats', media_path='/assets/')\n        return doc.http_response(request)",
    "docstring": "Live stats for the server.\n\n        Try sending lots of requests"
  },
  {
    "code": "def visit_tuple(self, node, parent):\n        context = self._get_context(node)\n        newnode = nodes.Tuple(\n            ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent\n        )\n        newnode.postinit([self.visit(child, newnode) for child in node.elts])\n        return newnode",
    "docstring": "visit a Tuple node by returning a fresh instance of it"
  },
  {
    "code": "def execute(self, fetchcommand, sql, params=None):\n\t\tcur = self.conn.cursor()\n\t\tif params:\n\t\t\tif not type(params).__name__ == 'tuple':\n\t\t\t\traise ValueError('the params argument needs to be a tuple')\n\t\t\t\treturn None\n\t\t\tcur.execute(sql, params)\n\t\telse:\n\t\t\tcur.execute(sql)\n\t\tself.conn.commit()\n\t\tif not fetchcommand or fetchcommand == 'none':\n\t\t\treturn\n\t\tif fetchcommand == 'last' or fetchcommand == 'lastid':\n\t\t\tlastdata = cur.fetchall()\n\t\t\tself.conn.commit()\n\t\t\treturn lastdata\n\t\tm = insertion_pattern.match(sql)\n\t\tif m:\n\t\t\tlastdata = cur.fetchone()\n\t\t\tself.conn.commit()\n\t\t\treturn lastdata\n\t\tif fetchcommand == 'fetchone' or fetchcommand == 'one':\n\t\t\treturn cur.fetchone()\n\t\telif fetchcommand == 'fetchall' or fetchcommand == 'all':\n\t\t\treturn cur.fetchall()\n\t\telse:\n\t\t\tmsg = \"expecting <fetchcommand> argument to be either 'fetchone'|'one'|'fetchall|all'\"\n\t\t\traise ValueError(msg)",
    "docstring": "where 'fetchcommand' is either 'fetchone' or 'fetchall'"
  },
  {
    "code": "def rbridge_id(self, **kwargs):\n        is_get_config = kwargs.pop('get', False)\n        if not is_get_config:\n            rbridge_id = kwargs.pop('rbridge_id')\n        else:\n            rbridge_id = ''\n        callback = kwargs.pop('callback', self._callback)\n        rid_args = dict(rbridge_id=rbridge_id)\n        rid = getattr(self._rbridge,\n                      'rbridge_id_rbridge_id')\n        config = rid(**rid_args)\n        if is_get_config:\n            return callback(config, handler='get_config')\n        return callback(config)",
    "docstring": "Configures device's rbridge ID. Setting this property will need\n        a switch reboot\n\n        Args:\n            rbridge_id (str): The rbridge ID of the device on which BGP will be\n                configured in a VCS fabric.\n            get (bool): Get config instead of editing config. (True, False)\n            callback (function): A function executed upon completion of the\n                method.  The only parameter passed to `callback` will be the\n                ``ElementTree`` `config`.\n\n        Returns:\n            Return value of `callback`.\n\n        Raises:\n            KeyError: if `rbridge_id` is not specified.\n\n        Examples:\n            >>> import pynos.device\n            >>> conn = ('10.24.39.211', '22')\n            >>> auth = ('admin', 'password')\n            >>> with pynos.device.Device(conn=conn, auth=auth) as dev:\n            ...     output = dev.system.rbridge_id(rbridge_id='225')\n            ...     output = dev.system.rbridge_id(rbridge_id='225', get=True)\n            ...     dev.system.rbridge_id() # doctest: +IGNORE_EXCEPTION_DETAIL\n            Traceback (most recent call last):\n            KeyError"
  },
  {
    "code": "def emit(self, record):\n        try:\n            msg = self.format(record)\n            if isinstance(msg,unicode):\n                if hasattr(self.stream, \"encoding\") and self.stream.encoding:\n                    self.stream.write(msg.encode(self.stream.encoding))\n                else:\n                    self.stream.write(msg.encode(encoding))\n            else:\n                self.stream.write(msg)\n            terminator = getattr(record, 'terminator', '\\n')\n            if terminator is not None:\n                self.stream.write(terminator)\n            self.flush()\n        except (KeyboardInterrupt, SystemExit):\n            raise\n        except:\n            self.handleError(record)",
    "docstring": "Emit a record. Unless record.terminator is set, a trailing\n           newline will be written to the output stream."
  },
  {
    "code": "def add_noise_to_dict_values(dictionary: Dict[A, float], noise_param: float) -> Dict[A, float]:\n    new_dict = {}\n    for key, value in dictionary.items():\n        noise_value = value * noise_param\n        noise = random.uniform(-noise_value, noise_value)\n        new_dict[key] = value + noise\n    return new_dict",
    "docstring": "Returns a new dictionary with noise added to every key in ``dictionary``.  The noise is\n    uniformly distributed within ``noise_param`` percent of the value for every value in the\n    dictionary."
  },
  {
    "code": "def _create_warm_start_tuner(self, additional_parents, warm_start_type, estimator=None):\n        all_parents = {self.latest_tuning_job.name}\n        if additional_parents:\n            all_parents = all_parents.union(additional_parents)\n        return HyperparameterTuner(estimator=estimator if estimator else self.estimator,\n                                   objective_metric_name=self.objective_metric_name,\n                                   hyperparameter_ranges=self._hyperparameter_ranges,\n                                   objective_type=self.objective_type,\n                                   max_jobs=self.max_jobs,\n                                   max_parallel_jobs=self.max_parallel_jobs,\n                                   warm_start_config=WarmStartConfig(warm_start_type=warm_start_type,\n                                                                     parents=all_parents))",
    "docstring": "Creates a new ``HyperparameterTuner`` with ``WarmStartConfig``, where type will be equal to\n        ``warm_start_type`` and``parents`` would be equal to union of ``additional_parents`` and self.\n\n        Args:\n            additional_parents (set{str}): Additional parents along with self, to be used for warm starting.\n            warm_start_type (sagemaker.tuner.WarmStartTypes): Type of warm start job.\n\n        Returns:\n            sagemaker.tuner.HyperparameterTuner: Instance with the request fields copied from self along with the\n            warm start configuration"
  },
  {
    "code": "def _find_usage_parameter_groups(self):\n        num_groups = 0\n        paginator = self.conn.get_paginator('describe_cache_parameter_groups')\n        for page in paginator.paginate():\n            for group in page['CacheParameterGroups']:\n                num_groups += 1\n        self.limits['Parameter Groups']._add_current_usage(\n            num_groups,\n            aws_type='AWS::ElastiCache::ParameterGroup'\n        )",
    "docstring": "find usage for elasticache parameter groups"
  },
  {
    "code": "def set_step(self, value, block_events=False):\n        if block_events: self.block_events()\n        self._widget.setSingleStep(value)\n        if block_events: self.unblock_events()",
    "docstring": "Sets the step of the number box.\n\n        Setting block_events=True will temporarily block the widget from\n        sending any signals when setting the value."
  },
  {
    "code": "def attach(self, payload):\n        if self._payload is None:\n            self._payload = [payload]\n        else:\n            self._payload.append(payload)",
    "docstring": "Add the given payload to the current payload.\n\n        The current payload will always be a list of objects after this method\n        is called.  If you want to set the payload to a scalar object, use\n        set_payload() instead."
  },
  {
    "code": "def set_grade_system(self, grade_system_id):\n        if self.get_grade_system_metadata().is_read_only():\n            raise errors.NoAccess()\n        if not self._is_valid_id(grade_system_id):\n            raise errors.InvalidArgument()\n        self._my_map['gradeSystemId'] = str(grade_system_id)",
    "docstring": "Sets the grading system.\n\n        arg:    grade_system_id (osid.id.Id): the grade system\n        raise:  InvalidArgument - ``grade_system_id`` is invalid\n        raise:  NoAccess - ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _get_columns(self, blueprint):\n        columns = []\n        for column in blueprint.get_added_columns():\n            sql = self.wrap(column) + ' ' + self._get_type(column)\n            columns.append(self._add_modifiers(sql, blueprint, column))\n        return columns",
    "docstring": "Get the blueprint's columns definitions.\n\n        :param blueprint: The blueprint\n        :type blueprint: Blueprint\n\n        :rtype: list"
  },
  {
    "code": "def on_delivery(self, channel, method, properties, body):\n        self.callbacks.on_delivery(\n            self.name, channel, method, properties, body)",
    "docstring": "Invoked by pika when RabbitMQ delivers a message from a queue.\n\n        :param channel: The channel the message was delivered on\n        :type channel: pika.channel.Channel\n        :param method: The AMQP method frame\n        :type method: pika.frame.Frame\n        :param properties: The AMQP message properties\n        :type properties: pika.spec.Basic.Properties\n        :param bytes body: The message body"
  },
  {
    "code": "def remove(self):\n        self.zone.alarmClock.DestroyAlarm([\n            ('ID', self._alarm_id)\n        ])\n        alarm_id = self._alarm_id\n        try:\n            del Alarm._all_alarms[alarm_id]\n        except KeyError:\n            pass\n        self._alarm_id = None",
    "docstring": "Remove the alarm from the Sonos system.\n\n        There is no need to call `save`. The Python instance is not deleted,\n        and can be saved back to Sonos again if desired."
  },
  {
    "code": "def user_can_edit_newsitem(user, NewsItem):\n    for perm in format_perms(NewsItem, ['add', 'change', 'delete']):\n        if user.has_perm(perm):\n            return True\n    return False",
    "docstring": "Check if the user has permission to edit a particular NewsItem type."
  },
  {
    "code": "def clean(self):\n        if not self.metrics:\n            self.metrics = dict(\n                (name, spec.default)\n                for name, spec in (metric_catalog.get(self.__class__, {})\n                                                 .items()))\n        return super(WithMetrics, self).clean()",
    "docstring": "Fill metrics with defaults on create"
  },
  {
    "code": "def readQuotes(self, start, end):\r\n        if self.symbol is None:\r\n            LOG.debug('Symbol is None')\r\n            return []\r\n        return self.__yf.getQuotes(self.symbol, start, end)",
    "docstring": "read quotes from Yahoo Financial"
  },
  {
    "code": "def entails(self, entailed_independencies):\n        if not isinstance(entailed_independencies, Independencies):\n            return False\n        implications = self.closure().get_assertions()\n        return all(ind in implications for ind in entailed_independencies.get_assertions())",
    "docstring": "Returns `True` if the `entailed_independencies` are implied by this `Independencies`-object, otherwise `False`.\n        Entailment is checked using the semi-graphoid axioms.\n\n        Might be very slow if more than six variables are involved.\n\n        Parameters\n        ----------\n        entailed_independencies: Independencies()-object\n\n        Examples\n        --------\n        >>> from pgmpy.independencies import Independencies\n        >>> ind1 = Independencies([['A', 'B'], ['C', 'D'], 'E'])\n        >>> ind2 = Independencies(['A', 'C', 'E'])\n        >>> ind1.entails(ind2)\n        True\n        >>> ind2.entails(ind1)\n        False"
  },
  {
    "code": "def add_nexusnve_binding(vni, switch_ip, device_id, mcast_group):\n    LOG.debug(\"add_nexusnve_binding() called\")\n    session = bc.get_writer_session()\n    binding = nexus_models_v2.NexusNVEBinding(vni=vni,\n                                              switch_ip=switch_ip,\n                                              device_id=device_id,\n                                              mcast_group=mcast_group)\n    session.add(binding)\n    session.flush()\n    return binding",
    "docstring": "Adds a nexus nve binding."
  },
  {
    "code": "def put(self, *items) -> \"AttrIndexedDict\":\n        \"Add items to the dict that will be indexed by self.attr.\"\n        for item in items:\n            self.data[getattr(item, self.attr)] = item\n        return self",
    "docstring": "Add items to the dict that will be indexed by self.attr."
  },
  {
    "code": "def send(self,\n             sender,\n             recipients,\n             cc=None,\n             bcc=None,\n             subject='',\n             body='',\n             attachments=None,\n             content='text'):\n        if not self.connected:\n            self._logger.error(('Server not connected, cannot send message, '\n                                'please connect() first and disconnect() when '\n                                'the connection is not needed any more'))\n            return False\n        try:\n            message = Message(sender,\n                              recipients,\n                              cc,\n                              bcc,\n                              subject,\n                              body,\n                              attachments,\n                              content)\n            self._smtp.sendmail(message.sender,\n                                message.recipients,\n                                message.as_string)\n            result = True\n            self._connected = False\n            self._logger.debug('Done')\n        except Exception:\n            self._logger.exception('Something went wrong!')\n            result = False\n        return result",
    "docstring": "Sends the email\n\n        :param sender: The server of the message\n        :param recipients: The recipients (To:) of the message\n        :param cc: The CC recipients of the message\n        :param bcc: The BCC recipients of the message\n        :param subject: The subject of the message\n        :param body: The body of the message\n        :param attachments: The attachments of the message\n        :param content: The type of content the message [text/html]\n\n        :return: True on success, False otherwise"
  },
  {
    "code": "def hazard_at_times(self, times, label=None):\n        label = coalesce(label, self._label)\n        return pd.Series(self._hazard(self._fitted_parameters_, times), index=_to_array(times), name=label)",
    "docstring": "Return a Pandas series of the predicted hazard at specific times.\n\n        Parameters\n        -----------\n        times: iterable or float\n          values to return the hazard at.\n        label: string, optional\n          Rename the series returned. Useful for plotting.\n\n        Returns\n        --------\n        pd.Series"
  },
  {
    "code": "def rate_overall(self):\n        elapsed = self.elapsed\n        return self.rate if not elapsed else self.numerator / self.elapsed",
    "docstring": "Returns the overall average rate based on the start time."
  },
  {
    "code": "def start_numbered_list(self):\n        self._ordered = True\n        self.start_container(List, stylename='_numbered_list')\n        self.set_next_paragraph_style('numbered-list-paragraph'\n                                      if self._item_level <= 0\n                                      else 'sublist-paragraph')",
    "docstring": "Start a numbered list."
  },
  {
    "code": "def new_instance(settings):\n    settings = set_default({}, settings)\n    if not settings[\"class\"]:\n        Log.error(\"Expecting 'class' attribute with fully qualified class name\")\n    path = settings[\"class\"].split(\".\")\n    class_name = path[-1]\n    path = \".\".join(path[:-1])\n    constructor = None\n    try:\n        temp = __import__(path, globals(), locals(), [class_name], 0)\n        constructor = object.__getattribute__(temp, class_name)\n    except Exception as e:\n        Log.error(\"Can not find class {{class}}\", {\"class\": path}, cause=e)\n    settings['class'] = None\n    try:\n        return constructor(kwargs=settings)\n    except Exception as e:\n        pass\n    try:\n        return constructor(**settings)\n    except Exception as e:\n        Log.error(\"Can not create instance of {{name}}\", name=\".\".join(path), cause=e)",
    "docstring": "MAKE A PYTHON INSTANCE\n\n    `settings` HAS ALL THE `kwargs`, PLUS `class` ATTRIBUTE TO INDICATE THE CLASS TO CREATE"
  },
  {
    "code": "def plot_eigh2(self, colorbar=True, cb_orientation='vertical',\n                   cb_label=None, ax=None, show=True, fname=None, **kwargs):\n        if cb_label is None:\n            cb_label = self._eigh2_label\n        if self.eigh2 is None:\n            self.compute_eigh()\n        if ax is None:\n            fig, axes = self.eigh2.plot(colorbar=colorbar,\n                                        cb_orientation=cb_orientation,\n                                        cb_label=cb_label, show=False,\n                                        **kwargs)\n            if show:\n                fig.show()\n            if fname is not None:\n                fig.savefig(fname)\n            return fig, axes\n        else:\n            self.eigh2.plot(colorbar=colorbar, cb_orientation=cb_orientation,\n                            cb_label=cb_label, ax=ax, **kwargs)",
    "docstring": "Plot the second eigenvalue of the horizontal tensor.\n\n        Usage\n        -----\n        x.plot_eigh2([tick_interval, xlabel, ylabel, ax, colorbar,\n                      cb_orientation, cb_label, show, fname])\n\n        Parameters\n        ----------\n        tick_interval : list or tuple, optional, default = [30, 30]\n            Intervals to use when plotting the x and y ticks. If set to None,\n            ticks will not be plotted.\n        xlabel : str, optional, default = 'longitude'\n            Label for the longitude axis.\n        ylabel : str, optional, default = 'latitude'\n            Label for the latitude axis.\n        ax : matplotlib axes object, optional, default = None\n            A single matplotlib axes object where the plot will appear.\n        colorbar : bool, optional, default = True\n            If True, plot a colorbar.\n        cb_orientation : str, optional, default = 'vertical'\n            Orientation of the colorbar: either 'vertical' or 'horizontal'.\n        cb_label : str, optional, default = '$\\lambda_{h2}$, Eotvos$^{-1}$'\n            Text label for the colorbar.\n        show : bool, optional, default = True\n            If True, plot the image to the screen.\n        fname : str, optional, default = None\n            If present, and if axes is not specified, save the image to the\n            specified file.\n        kwargs : optional\n            Keyword arguements that will be sent to the SHGrid.plot()\n            and plt.imshow() methods."
  },
  {
    "code": "def add_new_host(self, hostname, ipv4addr, comment=None):\n        host = Host(self.session, name=hostname)\n        if host.ipv4addrs:\n            host.ipv4addrs = []\n        host.add_ipv4addr(ipv4addr)\n        host.comment = comment\n        return host.save()",
    "docstring": "Add or update a host in the infoblox, overwriting any IP address\n        entries.\n\n        :param str hostname: Hostname to add/set\n        :param str ipv4addr: IP Address to add/set\n        :param str comment: The comment for the record"
  },
  {
    "code": "def find_classes(folder:Path)->FilePathList:\n    \"List of label subdirectories in imagenet-style `folder`.\"\n    classes = [d for d in folder.iterdir()\n               if d.is_dir() and not d.name.startswith('.')]\n    assert(len(classes)>0)\n    return sorted(classes, key=lambda d: d.name)",
    "docstring": "List of label subdirectories in imagenet-style `folder`."
  },
  {
    "code": "def parse_compound(s, global_compartment=None):\n    m = re.match(r'^\\|(.*)\\|$', s)\n    if m:\n        s = m.group(1)\n    m = re.match(r'^(.+)\\[(\\S+)\\]$', s)\n    if m:\n        compound_id = m.group(1)\n        compartment = m.group(2)\n    else:\n        compound_id = s\n        compartment = global_compartment\n    return Compound(compound_id, compartment=compartment)",
    "docstring": "Parse a compound specification.\n\n    If no compartment is specified in the string, the global compartment\n    will be used."
  },
  {
    "code": "def _init_topics(self):\n        _LOGGER.info('Setting up initial MQTT topic subscription')\n        init_topics = [\n            '{}/+/+/0/+/+'.format(self._in_prefix),\n            '{}/+/+/3/+/+'.format(self._in_prefix),\n        ]\n        self._handle_subscription(init_topics)\n        if not self.persistence:\n            return\n        topics = [\n            '{}/{}/{}/{}/+/+'.format(\n                self._in_prefix, str(sensor.sensor_id), str(child.id),\n                msg_type) for sensor in self.sensors.values()\n            for child in sensor.children.values()\n            for msg_type in (int(self.const.MessageType.set),\n                             int(self.const.MessageType.req))\n        ]\n        topics.extend([\n            '{}/{}/+/{}/+/+'.format(\n                self._in_prefix, str(sensor.sensor_id),\n                int(self.const.MessageType.stream))\n            for sensor in self.sensors.values()])\n        self._handle_subscription(topics)",
    "docstring": "Set up initial subscription of mysensors topics."
  },
  {
    "code": "def _stop_lock_renewer(self):\n        if self._lock_renewal_thread is None or not self._lock_renewal_thread.is_alive():\n            return\n        logger.debug(\"Signalling the lock refresher to stop\")\n        self._lock_renewal_stop.set()\n        self._lock_renewal_thread.join()\n        self._lock_renewal_thread = None\n        logger.debug(\"Lock refresher has stopped\")",
    "docstring": "Stop the lock renewer.\n\n        This signals the renewal thread and waits for its exit."
  },
  {
    "code": "def accept_dict(match, include_rejected=False, include_denied=False):\n    skey = get_key(__opts__)\n    return skey.accept(match_dict=match,\n            include_rejected=include_rejected,\n            include_denied=include_denied)",
    "docstring": "Accept keys based on a dict of keys. Returns a dictionary.\n\n    match\n        The dictionary of keys to accept.\n\n    include_rejected\n        To include rejected keys in the match along with pending keys, set this\n        to ``True``. Defaults to ``False``.\n\n        .. versionadded:: 2016.3.4\n\n    include_denied\n        To include denied keys in the match along with pending keys, set this\n        to ``True``. Defaults to ``False``.\n\n        .. versionadded:: 2016.3.4\n\n    Example to move a list of keys from the ``minions_pre`` (pending) directory\n    to the ``minions`` (accepted) directory:\n\n    .. code-block:: python\n\n        >>> wheel.cmd('key.accept_dict',\n        {\n            'minions_pre': [\n                'jerry',\n                'stuart',\n                'bob',\n            ],\n        })\n        {'minions': ['jerry', 'stuart', 'bob']}"
  },
  {
    "code": "def get_single_stack(self):\n        single = None\n        while self.single_stack:\n            single = self.single_stack.pop()\n        return single",
    "docstring": "Get the correct single stack item to use."
  },
  {
    "code": "def get_model_by_name(model_name):\n    if isinstance(model_name, six.string_types) and \\\n            len(model_name.split('.')) == 2:\n        app_name, model_name = model_name.split('.')\n        if django.VERSION[:2] < (1, 8):\n            model = models.get_model(app_name, model_name)\n        else:\n            from django.apps import apps\n            model = apps.get_model(app_name, model_name)\n    else:\n        raise ValueError(\"{0} is not a Django model\".format(model_name))\n    return model",
    "docstring": "Get model by its name.\n\n    :param str model_name: name of model.\n    :return django.db.models.Model:\n\n    Example:\n        get_concrete_model_by_name('auth.User')\n        django.contrib.auth.models.User"
  },
  {
    "code": "def send_message(self, chat_id, text, **options):\n        return self.api_call(\"sendMessage\", chat_id=chat_id, text=text, **options)",
    "docstring": "Send a text message to chat\n\n        :param int chat_id: ID of the chat to send the message to\n        :param str text: Text to send\n        :param options: Additional sendMessage options\n            (see https://core.telegram.org/bots/api#sendmessage)"
  },
  {
    "code": "def during(rrule, duration=None, timestamp=None, **kwargs):\n    result = False\n    if isinstance(rrule, string_types):\n        rrule_object = rrule_class.rrulestr(rrule)\n    else:\n        rrule_object = rrule_class(**rrule)\n    if timestamp is None:\n        timestamp = time()\n    now = datetime.fromtimestamp(timestamp)\n    duration_delta = now if duration is None else relativedelta(**duration)\n    last_date = rrule_object.before(now, inc=True)\n    if last_date is not None:\n        next_date = last_date + duration_delta\n        result = last_date <= now <= next_date\n    return result",
    "docstring": "Check if input timestamp is in rrule+duration period\n\n    :param rrule: rrule to check\n    :type rrule: str or dict\n        (freq, dtstart, interval, count, wkst, until, bymonth, byminute, etc.)\n    :param dict duration: time duration from rrule step. Ex:{'minutes': 60}\n    :param float timestamp: timestamp to check between rrule+duration. If None,\n        use now"
  },
  {
    "code": "def _validate_charset(data, charset):\n        if len(charset) > 1:\n            charset_data_length = 0\n            for symbol_charset in charset:\n                if symbol_charset not in ('A', 'B', 'C'):\n                    raise Code128.CharsetError\n                charset_data_length += 2 if symbol_charset is 'C' else 1\n            if charset_data_length != len(data):\n                raise Code128.CharsetLengthError\n        elif len(charset) == 1:\n            if charset not in ('A', 'B', 'C'):\n                raise Code128.CharsetError\n        elif charset is not None:\n            raise Code128.CharsetError",
    "docstring": "Validate that the charset is correct and throw an error if it isn't."
  },
  {
    "code": "def description(self):\n        lines = []\n        for line in self.__doc__.split('\\n')[2:]:\n            line = line.strip()\n            if line:\n                lines.append(line)\n        return ' '.join(lines)",
    "docstring": "Attribute that returns the plugin description from its docstring."
  },
  {
    "code": "def generate_pattern_list(self):\n        patterns = {}\n        items = self.frequent.keys()\n        if self.root.value is None:\n            suffix_value = []\n        else:\n            suffix_value = [self.root.value]\n            patterns[tuple(suffix_value)] = self.root.count\n        for i in range(1, len(items) + 1):\n            for subset in itertools.combinations(items, i):\n                pattern = tuple(sorted(list(subset) + suffix_value))\n                patterns[pattern] = \\\n                    min([self.frequent[x] for x in subset])\n        return patterns",
    "docstring": "Generate a list of patterns with support counts."
  },
  {
    "code": "def get_point_model(cls):\n        if is_plugin_point(cls):\n            raise Exception(_('This method is only available to plugin '\n                              'classes.'))\n        else:\n            return PluginPointModel.objects.\\\n                get(plugin__pythonpath=cls.get_pythonpath())",
    "docstring": "Returns plugin point model instance. Only used from plugin classes."
  },
  {
    "code": "def _expand_independent_outputs(fvar, full_cov, full_output_cov):\n    if full_cov and full_output_cov:\n        fvar = tf.matrix_diag(tf.transpose(fvar))\n        fvar = tf.transpose(fvar, [0, 2, 1, 3])\n    if not full_cov and full_output_cov:\n        fvar = tf.matrix_diag(fvar)\n    if full_cov and not full_output_cov:\n        pass\n    if not full_cov and not full_output_cov:\n        pass\n    return fvar",
    "docstring": "Reshapes fvar to the correct shape, specified by `full_cov` and `full_output_cov`.\n\n    :param fvar: has shape N x P (full_cov = False) or P x N x N (full_cov = True).\n    :return:\n    1. full_cov: True and full_output_cov: True\n       fvar N x P x N x P\n    2. full_cov: True and full_output_cov: False\n       fvar P x N x N\n    3. full_cov: False and full_output_cov: True\n       fvar N x P x P\n    4. full_cov: False and full_output_cov: False\n       fvar N x P"
  },
  {
    "code": "def dallinger():\n    from logging.config import fileConfig\n    fileConfig(\n        os.path.join(os.path.dirname(__file__), \"logging.ini\"),\n        disable_existing_loggers=False,\n    )",
    "docstring": "Dallinger command-line utility."
  },
  {
    "code": "def user_agent(style=None) -> _UserAgent:\n    global useragent\n    if (not useragent) and style:\n        useragent = UserAgent()\n    return useragent[style] if style else DEFAULT_USER_AGENT",
    "docstring": "Returns an apparently legit user-agent, if not requested one of a specific\n    style. Defaults to a Chrome-style User-Agent."
  },
  {
    "code": "def merge_from_obj(self, obj, lists_only=False):\n        self.clean()\n        obj.clean()\n        obj_config = obj._config\n        all_props = self.__class__.CONFIG_PROPERTIES\n        for key, value in six.iteritems(obj_config):\n            attr_config = all_props[key]\n            attr_type, default, __, merge_func = attr_config[:4]\n            if (merge_func is not False and value != default and\n                    (not lists_only or (attr_type and issubclass(attr_type, list)))):\n                self._merge_value(attr_type, merge_func, key, value)",
    "docstring": "Merges a configuration object into this one.\n\n        See :meth:`ConfigurationObject.merge` for details.\n\n        :param obj: Values to update the ConfigurationObject with.\n        :type obj: ConfigurationObject\n        :param lists_only: Ignore single-value attributes and update dictionary options.\n        :type lists_only: bool"
  },
  {
    "code": "def c2f(r, i, ctype_name):\n    ftype = c2f_dict[ctype_name]\n    return np.typeDict[ctype_name](ftype(r) + 1j * ftype(i))",
    "docstring": "Convert strings to complex number instance with specified numpy type."
  },
  {
    "code": "def describe_api_resource(restApiId, path,\n                          region=None, key=None, keyid=None, profile=None):\n    r = describe_api_resources(restApiId, region=region, key=key, keyid=keyid, profile=profile)\n    resources = r.get('resources')\n    if resources is None:\n        return r\n    for resource in resources:\n        if resource['path'] == path:\n            return {'resource': resource}\n    return {'resource': None}",
    "docstring": "Given rest api id, and an absolute resource path, returns the resource id for\n    the given path.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_apigateway.describe_api_resource myapi_id resource_path"
  },
  {
    "code": "def is_switched_on(self, refresh=False):\n        if refresh:\n            self.refresh()\n        return self.get_brightness(refresh) > 0",
    "docstring": "Get dimmer state.\n\n        Refresh data from Vera if refresh is True,\n        otherwise use local cache. Refresh is only needed if you're\n        not using subscriptions."
  },
  {
    "code": "def _normalize_joliet_path(self, joliet_path):\n        tmp_path = b''\n        if self.joliet_vd is not None:\n            if not joliet_path:\n                raise pycdlibexception.PyCdlibInvalidInput('A Joliet path must be passed for a Joliet ISO')\n            tmp_path = utils.normpath(joliet_path)\n        else:\n            if joliet_path:\n                raise pycdlibexception.PyCdlibInvalidInput('A Joliet path can only be specified for a Joliet ISO')\n        return tmp_path",
    "docstring": "An internal method to check whether this ISO does or does not require\n        a Joliet path.  If a Joliet path is required, the path is normalized\n        and returned.\n\n        Parameters:\n         joliet_path - The joliet_path to normalize (if necessary).\n        Returns:\n         The normalized joliet_path if this ISO has Joliet, None otherwise."
  },
  {
    "code": "def send_message(self, message, sign=True):\n\t\tself.check_connected()\n\t\tself.protocol.send_message(message, sign)",
    "docstring": "Sends the given message to the connection.\n\t\t@type message: OmapiMessage\n\t\t@type sign: bool\n\t\t@param sign: whether the message needs to be signed\n\t\t@raises OmapiError:\n\t\t@raises socket.error:"
  },
  {
    "code": "def lssitepackages_cmd(argv):\n    site = sitepackages_dir()\n    print(*sorted(site.iterdir()), sep=os.linesep)\n    extra_paths = site / '_virtualenv_path_extensions.pth'\n    if extra_paths.exists():\n        print('from _virtualenv_path_extensions.pth:')\n        with extra_paths.open() as extra:\n            print(''.join(extra.readlines()))",
    "docstring": "Show the content of the site-packages directory of the current virtualenv."
  },
  {
    "code": "def removeService(self, service):\n        for name, wrapper in self.services.iteritems():\n            if service in (name, wrapper.service):\n                del self.services[name]\n                return\n        raise NameError(\"Service %r not found\" % (service,))",
    "docstring": "Removes a service from the gateway.\n\n        @param service: Either the name or t of the service to remove from the\n                        gateway, or .\n        @type service: C{callable} or a class instance\n        @raise NameError: Service not found."
  },
  {
    "code": "def describe(self):\n        counts = self.value_counts(dropna=False)\n        freqs = counts / float(counts.sum())\n        from pandas.core.reshape.concat import concat\n        result = concat([counts, freqs], axis=1)\n        result.columns = ['counts', 'freqs']\n        result.index.name = 'categories'\n        return result",
    "docstring": "Describes this Categorical\n\n        Returns\n        -------\n        description: `DataFrame`\n            A dataframe with frequency and counts by category."
  },
  {
    "code": "def _format_with_same_year_and_month(format_specifier):\n    test_format_specifier = format_specifier + \"_SAME_YEAR_SAME_MONTH\"\n    test_format = get_format(test_format_specifier, use_l10n=True)\n    if test_format == test_format_specifier:\n        no_year = re.sub(YEAR_RE, '', get_format(format_specifier))\n        return re.sub(MONTH_RE, '', no_year)\n    else:\n        return test_format",
    "docstring": "Return a version of `format_specifier` that renders a date\n    assuming it has the same year and month as another date. Usually this \n    means ommitting the year and month.\n\n    This can be overridden by specifying a format that has \n    `_SAME_YEAR_SAME_MONTH` appended to the name in the project's `formats` \n    spec."
  },
  {
    "code": "def clear(self, color: Tuple[int, int, int]) -> None:\n        lib.TCOD_image_clear(self.image_c, color)",
    "docstring": "Fill this entire Image with color.\n\n        Args:\n            color (Union[Tuple[int, int, int], Sequence[int]]):\n                An (r, g, b) sequence or Color instance."
  },
  {
    "code": "def yunit(self):\n        try:\n            return self._dy.unit\n        except AttributeError:\n            try:\n                return self._y0.unit\n            except AttributeError:\n                return self._default_yunit",
    "docstring": "Unit of Y-axis index\n\n        :type: `~astropy.units.Unit`"
  },
  {
    "code": "def _load_form_data(self):\n        if \"form\" in self.__dict__:\n            return\n        _assert_not_shallow(self)\n        if self.want_form_data_parsed:\n            content_type = self.environ.get(\"CONTENT_TYPE\", \"\")\n            content_length = get_content_length(self.environ)\n            mimetype, options = parse_options_header(content_type)\n            parser = self.make_form_data_parser()\n            data = parser.parse(\n                self._get_stream_for_parsing(), mimetype, content_length, options\n            )\n        else:\n            data = (\n                self.stream,\n                self.parameter_storage_class(),\n                self.parameter_storage_class(),\n            )\n        d = self.__dict__\n        d[\"stream\"], d[\"form\"], d[\"files\"] = data",
    "docstring": "Method used internally to retrieve submitted data.  After calling\n        this sets `form` and `files` on the request object to multi dicts\n        filled with the incoming form data.  As a matter of fact the input\n        stream will be empty afterwards.  You can also call this method to\n        force the parsing of the form data.\n\n        .. versionadded:: 0.8"
  },
  {
    "code": "def get(cls, key, section=None, **kwargs):\n        section = section or cls._default_sect\n        if section not in cls._conf:\n            cls._load(section=section)\n        value = cls._conf[section].get(key)\n        if not value and section != cls._default_sect:\n            value = cls._conf[cls._default_sect].get(key) if cls._default_sect in cls._conf else None\n        if value is None:\n            if 'default' in kwargs:\n                _def_value = kwargs['default']\n                logger.warn(\"Static configuration [{}] was not found. Using the default value [{}].\".format(key, _def_value))\n                return _def_value\n            else:\n                raise InvalidConfigException(u'Not found entry: {}'.format(key))\n        try:\n            value = from_json(value)\n        except (TypeError, ValueError):\n            pass\n        return value",
    "docstring": "Retrieves a config value from dict.\n        If not found twrows an InvalidScanbooconfigException."
  },
  {
    "code": "def add_alternative (self, target_instance):\n        assert isinstance(target_instance, AbstractTarget)\n        if self.built_main_targets_:\n            raise IllegalOperation (\"add-alternative called when main targets are already created for project '%s'\" % self.full_name ())\n        self.alternatives_.append (target_instance)",
    "docstring": "Add new target alternative."
  },
  {
    "code": "def connect_sftp_with_cb(sftp_cb, *args, **kwargs):\n    with _connect_sftp(*args, **kwargs) as (ssh, sftp):\n        sftp_cb(ssh, sftp)",
    "docstring": "A \"managed\" SFTP session. When the SSH session and an additional SFTP \n    session are ready, invoke the sftp_cb callback."
  },
  {
    "code": "def _get_urls(self, version, cluster_stats):\n        pshard_stats_url = \"/_stats\"\n        health_url = \"/_cluster/health\"\n        if version >= [0, 90, 10]:\n            pending_tasks_url = \"/_cluster/pending_tasks\"\n            stats_url = \"/_nodes/stats\" if cluster_stats else \"/_nodes/_local/stats\"\n            if version < [5, 0, 0]:\n                stats_url += \"?all=true\"\n        else:\n            pending_tasks_url = None\n            stats_url = \"/_cluster/nodes/stats?all=true\" if cluster_stats else \"/_cluster/nodes/_local/stats?all=true\"\n        return health_url, stats_url, pshard_stats_url, pending_tasks_url",
    "docstring": "Compute the URLs we need to hit depending on the running ES version"
  },
  {
    "code": "def list_objects(self, prefix=None, delimiter=None):\n        return self._client.list_objects(\n            instance=self._instance, bucket_name=self.name, prefix=prefix,\n            delimiter=delimiter)",
    "docstring": "List the objects for this bucket.\n\n        :param str prefix: If specified, only objects that start with this\n                           prefix are listed.\n        :param str delimiter: If specified, return only objects whose name\n                              do not contain the delimiter after the prefix.\n                              For the other objects, the response contains\n                              (in the prefix response parameter) the name\n                              truncated after the delimiter. Duplicates are\n                              omitted."
  },
  {
    "code": "def _CheckIsLink(self, file_entry):\n    if definitions.FILE_ENTRY_TYPE_LINK not in self._file_entry_types:\n      return False\n    return file_entry.IsLink()",
    "docstring": "Checks the is_link find specification.\n\n    Args:\n      file_entry (FileEntry): file entry.\n\n    Returns:\n      bool: True if the file entry matches the find specification, False if not."
  },
  {
    "code": "def add_geo_facet(self, *args, **kwargs):\n        self.facets.append(GeoDistanceFacet(*args, **kwargs))",
    "docstring": "Add a geo factory facet"
  },
  {
    "code": "def match_any_char(self, chars, offset=0):\n        if not self.has_space(offset=offset):\n            return ''\n        current = self.string[self.pos + offset]\n        return current if current in chars else ''",
    "docstring": "Match and return the current SourceString char if its in chars."
  },
  {
    "code": "def get_transition_m(self, transition_id):\n        for transition_m in self.transitions:\n            if transition_m.transition.transition_id == transition_id:\n                return transition_m\n        return None",
    "docstring": "Searches and return the transition model with the given in the given container state model\n\n        :param transition_id: The transition id to be searched\n        :return: The model of the transition or None if it is not found"
  },
  {
    "code": "def iter_target_siblings_and_ancestors(self, target):\n    def iter_targets_in_spec_path(spec_path):\n      try:\n        siblings = SiblingAddresses(spec_path)\n        for address in self._build_graph.inject_specs_closure([siblings]):\n          yield self._build_graph.get_target(address)\n      except AddressLookupError:\n        pass\n    def iter_siblings_and_ancestors(spec_path):\n      for sibling in iter_targets_in_spec_path(spec_path):\n        yield sibling\n      parent_spec_path = os.path.dirname(spec_path)\n      if parent_spec_path != spec_path:\n        for parent in iter_siblings_and_ancestors(parent_spec_path):\n          yield parent\n    for target in iter_siblings_and_ancestors(target.address.spec_path):\n      yield target",
    "docstring": "Produces an iterator over a target's siblings and ancestor lineage.\n\n    :returns: A target iterator yielding the target and its siblings and then it ancestors from\n              nearest to furthest removed."
  },
  {
    "code": "def bytes2str(bs):\n    if isinstance(bs, type(b'')) and PY_MAJOR_VERSION > 2:\n        return bs.decode('latin1')\n    else:\n        return bs",
    "docstring": "For cross compatibility between Python 2 and Python 3 strings."
  },
  {
    "code": "def parse(self, line):\n        if not line:\n            raise KatcpSyntaxError(\"Empty message received.\")\n        type_char = line[0]\n        if type_char not in self.TYPE_SYMBOL_LOOKUP:\n            raise KatcpSyntaxError(\"Bad type character %r.\" % (type_char,))\n        mtype = self.TYPE_SYMBOL_LOOKUP[type_char]\n        parts = self.WHITESPACE_RE.split(line)\n        if not parts[-1]:\n            del parts[-1]\n        name = parts[0][1:]\n        arguments = [self._parse_arg(x) for x in parts[1:]]\n        match = self.NAME_RE.match(name)\n        if match:\n            name = match.group('name')\n            mid = match.group('id')\n        else:\n            raise KatcpSyntaxError(\"Bad message name (and possibly id) %r.\" %\n                                   (name,))\n        return Message(mtype, name, arguments, mid)",
    "docstring": "Parse a line, return a Message.\n\n        Parameters\n        ----------\n        line : str\n            The line to parse (should not contain the terminating newline\n            or carriage return).\n\n        Returns\n        -------\n        msg : Message object\n            The resulting Message."
  },
  {
    "code": "def validate_keys(dict_, expected, funcname):\n    expected = set(expected)\n    received = set(dict_)\n    missing = expected - received\n    if missing:\n        raise ValueError(\n            \"Missing keys in {}:\\n\"\n            \"Expected Keys: {}\\n\"\n            \"Received Keys: {}\".format(\n                funcname,\n                sorted(expected),\n                sorted(received),\n            )\n        )\n    unexpected = received - expected\n    if unexpected:\n        raise ValueError(\n            \"Unexpected keys in {}:\\n\"\n            \"Expected Keys: {}\\n\"\n            \"Received Keys: {}\".format(\n                funcname,\n                sorted(expected),\n                sorted(received),\n            )\n        )",
    "docstring": "Validate that a dictionary has an expected set of keys."
  },
  {
    "code": "def get_parser():\n    parser = argparse.ArgumentParser(\n        formatter_class=argparse.RawTextHelpFormatter,\n        description=__doc__,\n    )\n    parser.add_argument('--host', default='localhost')\n    parser.add_argument('--port', default=6379, type=int)\n    parser.add_argument('--db', default=0, type=int)\n    parser.add_argument('command', choices=(str('follow'), str('lock'),\n                                            str('reset'), str('status')))\n    parser.add_argument('resources', nargs='*', metavar='RESOURCE')\n    return parser",
    "docstring": "Return argument parser."
  },
  {
    "code": "def shared_dataset_ids(self):\n        shared_ids = set(self.scenes[0].keys())\n        for scene in self.scenes[1:]:\n            shared_ids &= set(scene.keys())\n        return shared_ids",
    "docstring": "Dataset IDs shared by all children."
  },
  {
    "code": "def queue_path(cls, project, location, queue):\n        return google.api_core.path_template.expand(\n            \"projects/{project}/locations/{location}/queues/{queue}\",\n            project=project,\n            location=location,\n            queue=queue,\n        )",
    "docstring": "Return a fully-qualified queue string."
  },
  {
    "code": "def finish(self):\n        \"End this session\"\n        log.debug(\"Session disconnected.\")\n        try:\n            self.sock.shutdown(socket.SHUT_RDWR)\n        except: pass\n        self.session_end()",
    "docstring": "End this session"
  },
  {
    "code": "def common_start(*args):\n    def _iter():\n        for s in zip(*args):\n            if len(set(s)) < len(args):\n                yield s[0]\n            else:\n                return\n    out = \"\".join(_iter()).strip()\n    result = [s for s in args if not s.startswith(out)]\n    result.insert(0, out)\n    return ', '.join(result)",
    "docstring": "returns the longest common substring from the beginning of sa and sb"
  },
  {
    "code": "def stash(self, payload):\n        succeeded = []\n        failed = []\n        for key in payload['keys']:\n            if self.queue.get(key) is not None:\n                if self.queue[key]['status'] == 'queued':\n                    self.queue[key]['status'] = 'stashed'\n                    succeeded.append(str(key))\n                else:\n                    failed.append(str(key))\n            else:\n                failed.append(str(key))\n        message = ''\n        if len(succeeded) > 0:\n            message += 'Stashed entries: {}.'.format(', '.join(succeeded))\n            status = 'success'\n        if len(failed) > 0:\n            message += '\\nNo queued entry for keys: {}'.format(', '.join(failed))\n            status = 'error'\n        answer = {'message': message.strip(), 'status': status}\n        return answer",
    "docstring": "Stash the specified processes."
  },
  {
    "code": "def add_child(self, tree):\n        tree.parent = self\n        self.children.append(tree)\n        return tree",
    "docstring": "Add a child to the list of this tree's children\n\n        This tree becomes the added tree's parent"
  },
  {
    "code": "def add_one(self, url: str,\n                url_properties: Optional[URLProperties]=None,\n                url_data: Optional[URLData]=None):\n        self.add_many([AddURLInfo(url, url_properties, url_data)])",
    "docstring": "Add a single URL to the table.\n\n        Args:\n            url: The URL to be added\n            url_properties: Additional values to be saved\n            url_data: Additional data to be saved"
  },
  {
    "code": "def unit_action(self, cmd, pos, shift):\n    action = sc_pb.Action()\n    if pos:\n      action_spatial = pos.action_spatial(action)\n      unit_command = action_spatial.unit_command\n      unit_command.ability_id = cmd.ability_id\n      unit_command.queue_command = shift\n      if pos.surf.surf_type & SurfType.SCREEN:\n        pos.obs_pos.assign_to(unit_command.target_screen_coord)\n      elif pos.surf.surf_type & SurfType.MINIMAP:\n        pos.obs_pos.assign_to(unit_command.target_minimap_coord)\n    else:\n      if self._feature_screen_px:\n        action.action_feature_layer.unit_command.ability_id = cmd.ability_id\n      else:\n        action.action_render.unit_command.ability_id = cmd.ability_id\n    self.clear_queued_action()\n    return action",
    "docstring": "Return a `sc_pb.Action` filled with the cmd and appropriate target."
  },
  {
    "code": "def _get_line(self, search_string, search_file, return_string=True, case_sens=True):\n        if os.path.isfile(search_file):\n            if type(search_string) == type(''): search_string = [search_string]\n            if not case_sens: search_string = [i.lower() for i in search_string]\n            with open(search_file) as fp:\n                for line in fp:\n                    query_line = line if case_sens else line.lower()\n                    if all([i in query_line for i in search_string]):\n                        return line if return_string else True\n                if return_string:\n                    raise Exception('%s not found in %s'%(' & '.join(search_string), search_file))\n                else: return False\n        else: raise Exception('%s file does not exist'%search_file)",
    "docstring": "Return the first line containing a set of strings in a file.\n\n        If return_string is False, we just return whether such a line\n        was found. If case_sens is False, the search is case\n        insensitive."
  },
  {
    "code": "def config_namespace(config_file=None, auto_find=False,\n                     verify=True, **cfg_options):\n    return ConfigNamespace(**config_dict(config_file, auto_find,\n                                         verify, **cfg_options))",
    "docstring": "Return configuration options as a Namespace.\n\n    .. code:: python\n\n        reusables.config_namespace(os.path.join(\"test\", \"data\",\n                                                \"test_config.ini\"))\n        # <Namespace: {'General': {'example': 'A regul...>\n\n\n    :param config_file: path or paths to the files location\n    :param auto_find: look for a config type file at this location or below\n    :param verify: make sure the file exists before trying to read\n    :param cfg_options: options to pass to the parser\n    :return: Namespace of the config files"
  },
  {
    "code": "def index(self, item):\n        for count, other in enumerate(self):\n            if item == other:\n                return count\n        raise ValueError('%r is not in OrderedSet' % (item,))",
    "docstring": "Find the index of `item` in the OrderedSet\n\n        Example:\n            >>> # ENABLE_DOCTEST\n            >>> import utool as ut\n            >>> self = ut.oset([1, 2, 3])\n            >>> assert self.index(1) == 0\n            >>> assert self.index(2) == 1\n            >>> assert self.index(3) == 2\n            >>> ut.assert_raises(ValueError, self.index, 4)"
  },
  {
    "code": "def del_port(self, port_name):\n        command = ovs_vsctl.VSCtlCommand('del-port', (self.br_name, port_name))\n        self.run_command([command])",
    "docstring": "Deletes a port on OVS instance.\n\n        This method is corresponding to the following ovs-vsctl command::\n\n            $ ovs-vsctl del-port <bridge> <port>"
  },
  {
    "code": "def regularrun(\n    shell,\n    prompt_template=\"default\",\n    aliases=None,\n    envvars=None,\n    extra_commands=None,\n    speed=1,\n    test_mode=False,\n    commentecho=False,\n):\n    loop_again = True\n    command_string = regulartype(prompt_template)\n    if command_string == TAB:\n        loop_again = False\n        return loop_again\n    run_command(\n        command_string,\n        shell,\n        aliases=aliases,\n        envvars=envvars,\n        extra_commands=extra_commands,\n        test_mode=test_mode,\n    )\n    return loop_again",
    "docstring": "Allow user to run their own live commands until CTRL-Z is pressed again."
  },
  {
    "code": "def list_datastore_clusters(kwargs=None, call=None):\n    if call != 'function':\n        raise SaltCloudSystemExit(\n            'The list_datastore_clusters function must be called with '\n            '-f or --function.'\n        )\n    return {'Datastore Clusters': salt.utils.vmware.list_datastore_clusters(_get_si())}",
    "docstring": "List all the datastore clusters for this VMware environment\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -f list_datastore_clusters my-vmware-config"
  },
  {
    "code": "def play_mode(self, play_mode):\n        play_mode = play_mode.upper()\n        if play_mode not in PLAY_MODES:\n            raise KeyError(\"'%s' is not a valid play mode\" % play_mode)\n        self._play_mode = play_mode",
    "docstring": "See `playmode`."
  },
  {
    "code": "def weighted_n(self):\n        if not self.is_weighted:\n            return float(self.unweighted_n)\n        return float(sum(self._cube_dict[\"result\"][\"measures\"][\"count\"][\"data\"]))",
    "docstring": "float count of returned rows adjusted for weighting."
  },
  {
    "code": "def set_coverage_placeName(self):\n        if (self.solr_response\n                and self.solr_response != 'error'\n                and self.solr_response.response != 'error'):\n            location_list = self.solr_response.get_location_list_facet().facet_list\n        else:\n            location_list = []\n        form_dict = {\n            'view_type': 'prefill',\n            'value_json': json.dumps(location_list, ensure_ascii=False),\n            'value_py': location_list,\n        }\n        return form_dict",
    "docstring": "Determine the properties for the placeName coverage field."
  },
  {
    "code": "def delete_dscp_marking_rule(self, rule, policy):\n        return self.delete(self.qos_dscp_marking_rule_path %\n                           (policy, rule))",
    "docstring": "Deletes a DSCP marking rule."
  },
  {
    "code": "def _write_pidfile(self):\n        LOGGER.debug('Writing pidfile: %s', self.pidfile_path)\n        with open(self.pidfile_path, \"w\") as handle:\n            handle.write(str(os.getpid()))",
    "docstring": "Write the pid file out with the process number in the pid file"
  },
  {
    "code": "def set_register(self, reg, data):\n        if reg < 0:\n            return\n        elif reg < len(self._register_list):\n            regName = self._register_list[reg].name\n            regBits = self._register_list[reg].bitsize\n            if regBits == 64:\n                value = conversion.hex16_to_u64be(data)\n            else:\n                value = conversion.hex8_to_u32be(data)\n            logging.debug(\"GDB: write reg %s: 0x%X\", regName, value)\n            self._context.write_core_register_raw(regName, value)",
    "docstring": "Set single register from GDB hexadecimal string.\n        reg parameter is the index of register in targetXML sent to GDB."
  },
  {
    "code": "def exists(name, path=None):\n    _exists = name in ls_(path=path)\n    if not _exists:\n        _exists = name in ls_(cache=False, path=path)\n    return _exists",
    "docstring": "Returns whether the named container exists.\n\n    path\n        path to the container parent directory (default: /var/lib/lxc)\n\n        .. versionadded:: 2015.8.0\n\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' lxc.exists name"
  },
  {
    "code": "def create_csr(cls, common_name, private_key=None, params=None):\n        params = params or []\n        params = [(key, val) for key, val in params if val]\n        subj = '/' + '/'.join(['='.join(value) for value in params])\n        cmd, private_key = cls.gen_pk(common_name, private_key)\n        if private_key.endswith('.crt') or private_key.endswith('.key'):\n            csr_file = re.sub(r'\\.(crt|key)$', '.csr', private_key)\n        else:\n            csr_file = private_key + '.csr'\n        cmd = cmd % {'csr': csr_file, 'key': private_key, 'subj': subj}\n        result = cls.execute(cmd)\n        if not result:\n            cls.echo('CSR creation failed')\n            cls.echo(cmd)\n            return\n        return csr_file",
    "docstring": "Create CSR."
  },
  {
    "code": "def createBlendedFolders():\n    create_folder(os.path.join(cwd, \"templates\"))\n    create_folder(os.path.join(cwd, \"templates\", \"assets\"))\n    create_folder(os.path.join(cwd, \"templates\", \"assets\", \"css\"))\n    create_folder(os.path.join(cwd, \"templates\", \"assets\", \"js\"))\n    create_folder(os.path.join(cwd, \"templates\", \"assets\", \"img\"))\n    create_folder(os.path.join(cwd, \"content\"))",
    "docstring": "Creates the standard folders for a Blended website"
  },
  {
    "code": "def unstruct_strat(self):\n        return (\n            UnstructureStrategy.AS_DICT\n            if self._unstructure_attrs == self.unstructure_attrs_asdict\n            else UnstructureStrategy.AS_TUPLE\n        )",
    "docstring": "The default way of unstructuring ``attrs`` classes."
  },
  {
    "code": "def IsCloud(self, request, bios_version, services):\n    if request.bios_version_regex and bios_version:\n      if re.match(request.bios_version_regex, bios_version):\n        return True\n    if request.service_name_regex and services:\n      if re.search(request.service_name_regex, services):\n        return True\n    return False",
    "docstring": "Test to see if we're on a cloud machine."
  },
  {
    "code": "def write_single_xso(x, dest):\n    gen = XMPPXMLGenerator(dest,\n                           short_empty_elements=True,\n                           sorted_attributes=True)\n    x.unparse_to_sax(gen)",
    "docstring": "Write a single XSO `x` to a binary file-like object `dest`."
  },
  {
    "code": "def repopulateWinowMenu(self, actionGroup):\n        for action in self.windowMenu.actions():\n            self.windowMenu.removeAction(action)\n        for action in actionGroup.actions():\n            self.windowMenu.addAction(action)",
    "docstring": "Clear the window menu and fills it with the actions of the actionGroup"
  },
  {
    "code": "def tofile(self, fileobj):\n\t\tfor entry in self:\n\t\t\tprint >>fileobj, str(entry)\n\t\tfileobj.close()",
    "docstring": "write a cache object to the fileobj as a lal cache file"
  },
  {
    "code": "def findElementsWithId(node, elems=None):\n    if elems is None:\n        elems = {}\n    id = node.getAttribute('id')\n    if id != '':\n        elems[id] = node\n    if node.hasChildNodes():\n        for child in node.childNodes:\n            if child.nodeType == Node.ELEMENT_NODE:\n                findElementsWithId(child, elems)\n    return elems",
    "docstring": "Returns all elements with id attributes"
  },
  {
    "code": "def describe_features(self, traj):\n        feature_descs = []\n        top = traj.topology\n        residue_indices = [[top.atom(i[0]).residue.index, top.atom(i[1]).residue.index] \\\n                           for i in self.atom_indices]\n        aind = []\n        resseqs = []\n        resnames = []\n        for ind,resid_ids in enumerate(residue_indices):\n            aind += [[i for i in self.atom_indices[ind]]]\n            resseqs += [[top.residue(ri).resSeq for ri in resid_ids]]\n            resnames += [[top.residue(ri).name for ri in resid_ids]]\n        zippy = itertools.product([\"AtomPairs\"], [\"Distance\"],\n                                  [\"Exponent {}\".format(self.exponent)],\n                                  zip(aind, resseqs, residue_indices, resnames))\n        feature_descs.extend(dict_maker(zippy))\n        return feature_descs",
    "docstring": "Return a list of dictionaries describing the atom pair features.\n\n        Parameters\n        ----------\n        traj : mdtraj.Trajectory\n            The trajectory to describe\n\n        Returns\n        -------\n        feature_descs : list of dict\n            Dictionary describing each feature with the following information\n            about the atoms participating in each dihedral\n                - resnames: unique names of residues\n                - atominds: the two atom inds\n                - resseqs: unique residue sequence ids (not necessarily\n                  0-indexed)\n                - resids: unique residue ids (0-indexed)\n                - featurizer: AtomPairsFeaturizer\n                - featuregroup: Distance.\n                - other info : Value of the exponent"
  },
  {
    "code": "def alerts(self, alert_level='High'):\n        alerts = self.zap.core.alerts()\n        alert_level_value = self.alert_levels[alert_level]\n        alerts = sorted((a for a in alerts if self.alert_levels[a['risk']] >= alert_level_value),\n                        key=lambda k: self.alert_levels[k['risk']], reverse=True)\n        return alerts",
    "docstring": "Get a filtered list of alerts at the given alert level, and sorted by alert level."
  },
  {
    "code": "def connect(dbapi_connection, connection_record):\n        try:\n            cursor = dbapi_connection.cursor()\n            try:\n                cursor.execute(\"PRAGMA foreign_keys = ON;\")\n                cursor.execute(\"PRAGMA foreign_keys;\")\n                if cursor.fetchone()[0] != 1:\n                    raise Exception()\n            finally:\n                cursor.close()\n        except Exception:\n            dbapi_connection.close()\n            raise sqlite3.Error()",
    "docstring": "Called once by SQLAlchemy for each new SQLite DB-API connection.\n\n        Here is where we issue some PRAGMA statements to configure how we're\n        going to access the SQLite database.\n\n        @param dbapi_connection:\n            A newly connected raw SQLite DB-API connection.\n\n        @param connection_record:\n            Unused by this method."
  },
  {
    "code": "def _parse_ranking(self, field, boxscore):\n        ranking = None\n        index = BOXSCORE_ELEMENT_INDEX[field]\n        teams_boxscore = boxscore(BOXSCORE_SCHEME[field])\n        if str(teams_boxscore) == '':\n            return ranking\n        team = pq(teams_boxscore[index])\n        if 'pollrank' in str(team):\n            rank_str = re.findall(r'\\(\\d+\\)', str(team))\n            if len(rank_str) == 1:\n                ranking = int(rank_str[0].replace('(', '').replace(')', ''))\n        return ranking",
    "docstring": "Parse each team's rank if applicable.\n\n        Retrieve the team's rank according to the rankings published each week.\n        The ranking for the week is only located in the scores section at\n        the top of the page and not in the actual boxscore information. The\n        rank is after the team name inside a parenthesis with a special\n        'pollrank' attribute. If this is not in the team's boxscore\n        information, the team is assumed to not have a rank and will return a\n        value of None.\n\n        Parameters\n        ----------\n        field : string\n            The name of the attribute to parse.\n        boxscore : PyQuery object\n            A PyQuery obejct containing all of the HTML data from the boxscore.\n\n        Returns\n        -------\n        int\n            An int representing the team's ranking or None if the team is not\n            ranked."
  },
  {
    "code": "def shuffle(self):\n        info = self._get_command_info(CommandInfo_pb2.ChangeShuffleMode)\n        return None if info is None else info.shuffleMode",
    "docstring": "If shuffle is enabled or not."
  },
  {
    "code": "def contains(self, token: str) -> bool:\n        self._validate_token(token)\n        return token in self",
    "docstring": "Return if the token is in the list or not."
  },
  {
    "code": "def worker(job):\n    ret = False\n    try:\n        if job.full_url is not None:\n            req = requests.get(job.full_url, stream=True)\n            ret = save_and_check(req, job.local_file, job.expected_checksum)\n            if not ret:\n                return ret\n        ret = create_symlink(job.local_file, job.symlink_path)\n    except KeyboardInterrupt:\n        logging.debug(\"Ignoring keyboard interrupt.\")\n    return ret",
    "docstring": "Run a single download job."
  },
  {
    "code": "def get_next_entry(self, method, info, request):\n        if method not in self.current_entries:\n            self.current_entries[method] = 0\n        entries_for_method = [e for e in self.entries if e.method == method]\n        if self.current_entries[method] >= len(entries_for_method):\n            self.current_entries[method] = -1\n        if not self.entries or not entries_for_method:\n            raise ValueError('I have no entries for method %s: %s'\n                             % (method, self))\n        entry = entries_for_method[self.current_entries[method]]\n        if self.current_entries[method] != -1:\n            self.current_entries[method] += 1\n        entry.info = info\n        entry.request = request\n        return entry",
    "docstring": "Cycle through available responses, but only once.\n        Any subsequent requests will receive the last response"
  },
  {
    "code": "def __precision(y_true, y_pred):\n    y_true = np.copy(y_true)\n    y_pred = np.copy(y_pred)\n    is_nan = np.isnan(y_true)\n    y_true[is_nan] = 0\n    y_pred[is_nan] = 0\n    precision = precision_score(y_true, y_pred)\n    return precision",
    "docstring": "Precision metric tolerant to unlabeled data in y_true,\n        NA values are ignored for the precision calculation"
  },
  {
    "code": "def slice(self, start, until):\n        return self._transform(transformations.slice_t(start, until))",
    "docstring": "Takes a slice of the sequence starting at start and until but not including until.\n\n        >>> seq([1, 2, 3, 4]).slice(1, 2)\n        [2]\n        >>> seq([1, 2, 3, 4]).slice(1, 3)\n        [2, 3]\n\n        :param start: starting index\n        :param until: ending index\n        :return: slice including start until but not including until"
  },
  {
    "code": "def _merge_defaults(self, data, method_params, defaults):\n        if defaults:\n            optional_args = method_params[-len(defaults):]\n            for key, value in zip(optional_args, defaults):\n                if not key in data:\n                    data[key] = value\n        return data",
    "docstring": "Helper method for adding default values to the data dictionary.\n\n        The `defaults` are the default values inspected from the method that\n        will be called. For any values that are not present in the incoming\n        data, the default value is added."
  },
  {
    "code": "def generate_catalogue_subparser(subparsers):\n    parser = subparsers.add_parser(\n        'catalogue', description=constants.CATALOGUE_DESCRIPTION,\n        epilog=constants.CATALOGUE_EPILOG,\n        formatter_class=ParagraphFormatter, help=constants.CATALOGUE_HELP)\n    utils.add_common_arguments(parser)\n    parser.set_defaults(func=generate_catalogue)\n    parser.add_argument('corpus', help=constants.DB_CORPUS_HELP,\n                        metavar='CORPUS')\n    utils.add_query_arguments(parser)\n    parser.add_argument('-l', '--label', default='',\n                        help=constants.CATALOGUE_LABEL_HELP)",
    "docstring": "Adds a sub-command parser to `subparsers` to generate and save\n    a catalogue file."
  },
  {
    "code": "def postprocess(self):\n        assert self.postscript\n        envmod.setup()\n        envmod.module('load', 'pbs')\n        cmd = 'qsub {script}'.format(script=self.postscript)\n        cmd = shlex.split(cmd)\n        rc = sp.call(cmd)\n        assert rc == 0, 'Postprocessing script submission failed.'",
    "docstring": "Submit a postprocessing script after collation"
  },
  {
    "code": "def tfrecord_iterator(filenames, gzipped=False, example_spec=None):\n  with tf.Graph().as_default():\n    dataset = tf.data.Dataset.from_tensor_slices(filenames)\n    def _load_records(filename):\n      return tf.data.TFRecordDataset(\n          filename,\n          compression_type=tf.constant(\"GZIP\") if gzipped else None,\n          buffer_size=16 * 1000 * 1000)\n    dataset = dataset.flat_map(_load_records)\n    def _parse_example(ex_ser):\n      return tf.parse_single_example(ex_ser, example_spec)\n    if example_spec:\n      dataset = dataset.map(_parse_example, num_parallel_calls=32)\n    dataset = dataset.prefetch(100)\n    record_it = dataset.make_one_shot_iterator().get_next()\n    with tf.Session() as sess:\n      while True:\n        try:\n          ex = sess.run(record_it)\n          yield ex\n        except tf.errors.OutOfRangeError:\n          break",
    "docstring": "Yields records from TFRecord files.\n\n  Args:\n    filenames: list<str>, list of TFRecord filenames to read from.\n    gzipped: bool, whether the TFRecord files are gzip-encoded.\n    example_spec: dict<str feature name, tf.VarLenFeature/tf.FixedLenFeature>,\n      if provided, will parse each record as a tensorflow.Example proto.\n\n  Yields:\n    Records (or parsed Examples, if example_spec is provided) from files."
  },
  {
    "code": "def lostitem_delete_view(request, item_id):\n    if request.method == \"POST\":\n        try:\n            a = LostItem.objects.get(id=item_id)\n            if request.POST.get(\"full_delete\", False):\n                a.delete()\n                messages.success(request, \"Successfully deleted lost item.\")\n            else:\n                a.found = True\n                a.save()\n                messages.success(request, \"Successfully marked lost item as found!\")\n        except LostItem.DoesNotExist:\n            pass\n        return redirect(\"index\")\n    else:\n        lostitem = get_object_or_404(LostItem, id=item_id)\n        return render(request, \"lostfound/lostitem_delete.html\", {\"lostitem\": lostitem})",
    "docstring": "Delete a lostitem.\n\n    id: lostitem id"
  },
  {
    "code": "def to_pixel(self, wcs, mode='all'):\n        pixel_params = self._to_pixel_params(wcs, mode=mode)\n        return CircularAperture(**pixel_params)",
    "docstring": "Convert the aperture to a `CircularAperture` object defined in\n        pixel coordinates.\n\n        Parameters\n        ----------\n        wcs : `~astropy.wcs.WCS`\n            The world coordinate system (WCS) transformation to use.\n\n        mode : {'all', 'wcs'}, optional\n            Whether to do the transformation including distortions\n            (``'all'``; default) or only including only the core WCS\n            transformation (``'wcs'``).\n\n        Returns\n        -------\n        aperture : `CircularAperture` object\n            A `CircularAperture` object."
  },
  {
    "code": "def RunValidationOutputFromOptions(feed, options):\n  if options.output.upper() == \"CONSOLE\":\n    return RunValidationOutputToConsole(feed, options)\n  else:\n    return RunValidationOutputToFilename(feed, options, options.output)",
    "docstring": "Validate feed, output results per options and return an exit code."
  },
  {
    "code": "def get_all_subscriptions_by_topic(name, region=None, key=None, keyid=None, profile=None):\n    cache_key = _subscriptions_cache_key(name)\n    try:\n        return __context__[cache_key]\n    except KeyError:\n        pass\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    ret = conn.get_all_subscriptions_by_topic(get_arn(name, region, key, keyid, profile))\n    __context__[cache_key] = ret['ListSubscriptionsByTopicResponse']['ListSubscriptionsByTopicResult']['Subscriptions']\n    return __context__[cache_key]",
    "docstring": "Get list of all subscriptions to a specific topic.\n\n    CLI example to delete a topic::\n\n        salt myminion boto_sns.get_all_subscriptions_by_topic mytopic region=us-east-1"
  },
  {
    "code": "def save_to_json(self):\r\n        requestvalues = {\r\n            'DatasetId': self.dataset,\r\n            'Name': self.name,\r\n            'Description': self.description,\r\n            'Source': self.source,\r\n            'PubDate': self.publication_date,\r\n            'AccessedOn': self.accessed_on,\r\n            'Url': self.dataset_ref,\r\n            'UploadFormatType': self.upload_format_type,\r\n            'Columns': self.columns,\r\n            'FileProperty': self.file_property.__dict__,\r\n            'FlatDSUpdateOptions': self.flat_ds_update_options,\r\n            'Public': self.public\r\n        }\r\n        return json.dumps(requestvalues)",
    "docstring": "The method saves DatasetUpload to json from object"
  },
  {
    "code": "def url_rule(blueprint_or_app, rules,\n             endpoint=None, view_func=None, **options):\n    for rule in to_list(rules):\n        blueprint_or_app.add_url_rule(rule,\n                                      endpoint=endpoint,\n                                      view_func=view_func,\n                                      **options)",
    "docstring": "Add one or more url rules to the given Flask blueprint or app.\n\n    :param blueprint_or_app: Flask blueprint or app\n    :param rules: a single rule string or a list of rules\n    :param endpoint: endpoint\n    :param view_func: view function\n    :param options: other options"
  },
  {
    "code": "def PlistValueToPlainValue(plist):\n  if isinstance(plist, dict):\n    ret_value = dict()\n    for key, value in iteritems(plist):\n      ret_value[key] = PlistValueToPlainValue(value)\n    return ret_value\n  elif isinstance(plist, list):\n    return [PlistValueToPlainValue(value) for value in plist]\n  elif isinstance(plist, datetime.datetime):\n    return (calendar.timegm(plist.utctimetuple()) * 1000000) + plist.microsecond\n  return plist",
    "docstring": "Takes the plist contents generated by binplist and returns a plain dict.\n\n  binplist uses rich types to express some of the plist types. We need to\n  convert them to types that RDFValueArray will be able to transport.\n\n  Args:\n    plist: A plist to convert.\n\n  Returns:\n    A simple python type."
  },
  {
    "code": "def _generate_relative_positions_matrix(length_q, length_k,\n                                        max_relative_position,\n                                        cache=False):\n  if not cache:\n    if length_q == length_k:\n      range_vec_q = range_vec_k = tf.range(length_q)\n    else:\n      range_vec_k = tf.range(length_k)\n      range_vec_q = range_vec_k[-length_q:]\n    distance_mat = range_vec_k[None, :] - range_vec_q[:, None]\n  else:\n    distance_mat = tf.expand_dims(tf.range(-length_k+1, 1, 1), 0)\n  distance_mat_clipped = tf.clip_by_value(distance_mat, -max_relative_position,\n                                          max_relative_position)\n  final_mat = distance_mat_clipped + max_relative_position\n  return final_mat",
    "docstring": "Generates matrix of relative positions between inputs."
  },
  {
    "code": "def convert_to_unit(self, unit):\n        self._values = self._header.data_type.to_unit(\n            self._values, unit, self._header.unit)\n        self._header._unit = unit",
    "docstring": "Convert the Data Collection to the input unit."
  },
  {
    "code": "def version_history(soup, html_flag=True):\n    \"extract the article version history details\"\n    convert = lambda xml_string: xml_to_html(html_flag, xml_string)\n    version_history = []\n    related_object_tags = raw_parser.related_object(raw_parser.article_meta(soup))\n    for tag in related_object_tags:\n        article_version = OrderedDict()\n        date_tag = first(raw_parser.date(tag))\n        if date_tag:\n            copy_attribute(date_tag.attrs, 'date-type', article_version, 'version')\n            (day, month, year) = ymd(date_tag)\n            article_version['day'] = day\n            article_version['month'] = month\n            article_version['year'] = year\n            article_version['date'] = date_struct_nn(year, month, day)\n        copy_attribute(tag.attrs, 'xlink:href', article_version, 'xlink_href')\n        set_if_value(article_version, \"comment\",\n                     convert(node_contents_str(first(raw_parser.comment(tag)))))\n        version_history.append(article_version)\n    return version_history",
    "docstring": "extract the article version history details"
  },
  {
    "code": "def cmp_public_numbers(pn1, pn2):\n    if pn1.n == pn2.n:\n        if pn1.e == pn2.e:\n            return True\n    return False",
    "docstring": "Compare 2 sets of public numbers. These is a way to compare\n    2 public RSA keys. If the sets are the same then the keys are the same.\n\n    :param pn1: The set of values belonging to the 1st key\n    :param pn2: The set of values belonging to the 2nd key\n    :return: True is the sets are the same otherwise False."
  },
  {
    "code": "def make_speaker_utters(utterances: List[Utterance]) -> Dict[str, List[Utterance]]:\n    speaker_utters = defaultdict(list)\n    for utter in utterances:\n        speaker_utters[utter.speaker].append(utter)\n    return speaker_utters",
    "docstring": "Creates a dictionary mapping from speakers to their utterances."
  },
  {
    "code": "def get_choices(field):\n\tempty_label = getattr(field.field, \"empty_label\", False)\n\tneeds_empty_value = False\n\tchoices = []\n\tif hasattr(field.field, \"_choices\"):\n\t\tchoices = field.field._choices\n\telif hasattr(field.field, \"_queryset\"):\n\t\tqueryset = field.field._queryset\n\t\tfield_name = getattr(field.field, \"to_field_name\") or \"pk\"\n\t\tchoices += ((getattr(obj, field_name), str(obj)) for obj in queryset)\n\tif choices and (choices[0][1] == BLANK_CHOICE_DASH[0][1] or choices[0][0]):\n\t\tneeds_empty_value = True\n\t\tif not choices[0][0]:\n\t\t\tdel choices[0]\n\tif empty_label == BLANK_CHOICE_DASH[0][1]:\n\t\tempty_label = None\n\tif empty_label or not field.field.required:\n\t\tif needs_empty_value:\n\t\t\tchoices.insert(0, (\"\", empty_label or BLANK_CHOICE_DASH[0][1]))\n\treturn choices",
    "docstring": "Find choices of a field, whether it has choices or has a queryset.\n\n\tArgs:\n\t\tfield (BoundField): Django form boundfield\n\n\tReturns:\n\t\tlist: List of choices"
  },
  {
    "code": "def __receiver_loop(self):\n        log.info(\"Starting receiver loop\")\n        notify_disconnected = True\n        try:\n            while self.running:\n                try:\n                    while self.running:\n                        frames = self.__read()\n                        for frame in frames:\n                            f = utils.parse_frame(frame)\n                            if f is None:\n                                continue\n                            if self.__auto_decode:\n                                f.body = decode(f.body)\n                            self.process_frame(f, frame)\n                except exception.ConnectionClosedException:\n                    if self.running:\n                        self.__recvbuf = b''\n                        self.running = False\n                        notify_disconnected = True\n                    break\n                finally:\n                    self.cleanup()\n        finally:\n            with self.__receiver_thread_exit_condition:\n                self.__receiver_thread_exited = True\n                self.__receiver_thread_exit_condition.notifyAll()\n            log.info(\"Receiver loop ended\")\n            self.notify('receiver_loop_completed')\n            if notify_disconnected:\n                self.notify('disconnected')\n            with self.__connect_wait_condition:\n                self.__connect_wait_condition.notifyAll()",
    "docstring": "Main loop listening for incoming data."
  },
  {
    "code": "def raw_encode(data):\n    content_type = 'application/data'\n    payload = data\n    if isinstance(payload, unicode):\n        content_encoding = 'utf-8'\n        payload = payload.encode(content_encoding)\n    else:\n        content_encoding = 'binary'\n    return content_type, content_encoding, payload",
    "docstring": "Special case serializer."
  },
  {
    "code": "def generate_method(method_name):\n    def call(self, *args, **kwargs):\n        if not self.threadloop.is_ready():\n            self.threadloop.start()\n        return self.threadloop.submit(\n            getattr(self.async_thrift, method_name), *args, **kwargs\n        )\n    return call",
    "docstring": "Generate a method for a given Thrift service.\n\n    Uses the provided TChannelSyncClient's threadloop in order\n    to convert RPC calls to concurrent.futures\n\n    :param method_name: Method being called.\n    :return: A method that invokes the RPC using TChannelSyncClient"
  },
  {
    "code": "def incomplete_relation_data(configs, required_interfaces):\n    complete_ctxts = configs.complete_contexts()\n    incomplete_relations = [\n        svc_type\n        for svc_type, interfaces in required_interfaces.items()\n        if not set(interfaces).intersection(complete_ctxts)]\n    return {\n        i: configs.get_incomplete_context_data(required_interfaces[i])\n        for i in incomplete_relations}",
    "docstring": "Check complete contexts against required_interfaces\n    Return dictionary of incomplete relation data.\n\n    configs is an OSConfigRenderer object with configs registered\n\n    required_interfaces is a dictionary of required general interfaces\n    with dictionary values of possible specific interfaces.\n    Example:\n    required_interfaces = {'database': ['shared-db', 'pgsql-db']}\n\n    The interface is said to be satisfied if anyone of the interfaces in the\n    list has a complete context.\n\n    Return dictionary of incomplete or missing required contexts with relation\n    status of interfaces and any missing data points. Example:\n        {'message':\n             {'amqp': {'missing_data': ['rabbitmq_password'], 'related': True},\n              'zeromq-configuration': {'related': False}},\n         'identity':\n             {'identity-service': {'related': False}},\n         'database':\n             {'pgsql-db': {'related': False},\n              'shared-db': {'related': True}}}"
  },
  {
    "code": "def extract(self, destdir, decompress='auto'):\n        for e in self.mardata.index.entries:\n            name = e.name\n            entry_path = safejoin(destdir, name)\n            entry_dir = os.path.dirname(entry_path)\n            mkdir(entry_dir)\n            with open(entry_path, 'wb') as f:\n                write_to_file(self.extract_entry(e, decompress), f)\n                os.chmod(entry_path, e.flags)",
    "docstring": "Extract the entire MAR file into a directory.\n\n        Args:\n            destdir (str): A local directory on disk into which the contents of\n                this MAR file will be extracted. Required parent directories\n                will be created as necessary.\n            decompress (obj, optional): Controls whether files are decompressed\n                when extracted. Must be one of 'auto' or None. Defaults to\n                'auto'."
  },
  {
    "code": "def remove_index(self, index):\n        query = []\n        remainder = []\n        for i in range(0, len(self.pieces), 2):\n            const = self.pieces[i]\n            if const.hash_field == index.hash_key:\n                query.append(const)\n            elif index.range_key is not None and const.range_field == index.range_key:\n                query.append(const)\n            else:\n                remainder.append(const)\n        if len(query) == 1:\n            query_constraints = query[0]\n        else:\n            query_constraints = Conjunction.and_(query)\n        if not remainder:\n            filter_constraints = None\n        elif len(remainder) == 1:\n            filter_constraints = remainder[0]\n        else:\n            filter_constraints = Conjunction.and_(remainder)\n        return (query_constraints, filter_constraints)",
    "docstring": "This one takes some explanation. When we do a query with a WHERE\n        statement, it may end up being a scan and it may end up being a query.\n        If it is a query, we need to remove the hash and range key constraints\n        from the expression and return that as the query_constraints. The\n        remaining constraints, if any, are returned as the filter_constraints."
  },
  {
    "code": "def mark_error(self, dispatch, error_log, message_cls):\n        if message_cls.send_retry_limit is not None and (dispatch.retry_count + 1) >= message_cls.send_retry_limit:\n            self.mark_failed(dispatch, error_log)\n        else:\n            dispatch.error_log = error_log\n            self._st['error'].append(dispatch)",
    "docstring": "Marks a dispatch as having error or consequently as failed\n        if send retry limit for that message type is exhausted.\n\n        Should be used within send().\n\n        :param Dispatch dispatch: a Dispatch\n        :param str error_log: error message\n        :param MessageBase message_cls: MessageBase heir"
  },
  {
    "code": "def add(repo_path, dest_path):\n    mkcfgdir()\n    try:\n        repo = getrepohandler(repo_path)\n    except NotARepo as err:\n        echo(\"ERROR: {}: {}\".format(ERR_NOT_A_REPO, err.repo_path))\n        sys.exit(1)\n    if repo.isremote:\n        localrepo, needpull = addfromremote(repo, dest_path)\n    elif dest_path:\n        raise UsageError(\"DEST_PATH is only for repos hosted online\")\n    else:\n        try:\n            repoid = repo.getrepoid()\n        except RepoHasNoCommitsError as err:\n            echo(\"ERROR: {}\".format(ERR_NO_COMMITS))\n            sys.exit(1)\n        localrepo = RepoInfo(repo, repoid, None)\n        needpull = False\n    if not localrepo:\n        return\n    with saveconfig(RepoListConfig()) as cfg:\n        cfg.add_repo(localrepo)\n    success = run_update([localrepo], pullfirst=needpull, cancleanup=True)\n    if not success:\n        sys.exit(1)",
    "docstring": "Registers a git repository with homely so that it will run its `HOMELY.py`\n    script on each invocation of `homely update`. `homely add` also immediately\n    executes a `homely update` so that the dotfiles are installed straight\n    away. If the git repository is hosted online, a local clone will be created\n    first.\n\n    REPO_PATH\n        A path to a local git repository, or the URL for a git repository\n        hosted online. If REPO_PATH is a URL, then it should be in a format\n        accepted by `git clone`. If REPO_PATH is a URL, you may also specify\n        DEST_PATH.\n    DEST_PATH\n        If REPO_PATH is a URL, then the local clone will be created at\n        DEST_PATH. If DEST_PATH is omitted then the path to the local clone\n        will be automatically derived from REPO_PATH."
  },
  {
    "code": "def _to_java_object_rdd(rdd):\n    rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer()))\n    return rdd.ctx._jvm.org.apache.spark.ml.python.MLSerDe.pythonToJava(rdd._jrdd, True)",
    "docstring": "Return an JavaRDD of Object by unpickling\n\n    It will convert each Python object into Java object by Pyrolite, whenever the\n    RDD is serialized in batch or not."
  },
  {
    "code": "def line_oriented(cls, line_oriented_options, console):\n    if type(line_oriented_options) != cls.Options:\n      raise AssertionError(\n          'Expected Options for `{}`, got: {}'.format(cls.__name__, line_oriented_options))\n    output_file = line_oriented_options.values.output_file\n    sep = line_oriented_options.values.sep.encode('utf-8').decode('unicode_escape')\n    stdout, stderr = console.stdout, console.stderr\n    if output_file:\n      stdout = open(output_file, 'w')\n    try:\n      print_stdout = lambda msg: print(msg, file=stdout, end=sep)\n      print_stderr = lambda msg: print(msg, file=stderr)\n      yield print_stdout, print_stderr\n    finally:\n      if output_file:\n        stdout.close()\n      else:\n        stdout.flush()\n      stderr.flush()",
    "docstring": "Given Goal.Options and a Console, yields functions for writing to stdout and stderr, respectively.\n\n    The passed options instance will generally be the `Goal.Options` of a `LineOriented` `Goal`."
  },
  {
    "code": "def get_type_id(context, **kw):\n    portal_type = kw.get(\"portal_type\", None)\n    if portal_type:\n        return portal_type\n    if IAnalysisRequestPartition.providedBy(context):\n        return \"AnalysisRequestPartition\"\n    elif IAnalysisRequestRetest.providedBy(context):\n        return \"AnalysisRequestRetest\"\n    elif IAnalysisRequestSecondary.providedBy(context):\n        return \"AnalysisRequestSecondary\"\n    return api.get_portal_type(context)",
    "docstring": "Returns the type id for the context passed in"
  },
  {
    "code": "def diff(self):\n        done = set(self.done)\n        return [name for name in self.todo if name not in done]",
    "docstring": "Calculate difference between fs and db."
  },
  {
    "code": "def _ssweek_of_month(date_value):\n    \"0-starting index which Sundaystarting-week in the month this date is\"\n    weekday_of_first = (date_value.replace(day=1).weekday() + 1) % 7\n    return (date_value.day + weekday_of_first - 1) // 7",
    "docstring": "0-starting index which Sundaystarting-week in the month this date is"
  },
  {
    "code": "def get_container_streaming_uri(self, container):\n        resp, resp_body = self.api.cdn_request(\"/%s\" %\n                utils.get_name(container), method=\"HEAD\")\n        return resp.headers.get(\"x-cdn-streaming-uri\")",
    "docstring": "Returns the URI for streaming content, or None if CDN is not enabled."
  },
  {
    "code": "def seektime(self, disk):\n        args = {\n            'disk': disk,\n        }\n        self._seektime_chk.check(args)\n        return self._client.json(\"disk.seektime\", args)",
    "docstring": "Gives seek latency on disk which is a very good indication to the `type` of the disk.\n        it's a very good way to verify if the underlying disk type is SSD or HDD\n\n        :param disk: disk path or name (/dev/sda, or sda)\n        :return: a dict as follows {'device': '<device-path>', 'elapsed': <seek-time in us', 'type': '<SSD or HDD>'}"
  },
  {
    "code": "def _process_marked_candidate_indexes(candidate, markers):\n    match = RE_SIGNATURE_CANDIDATE.match(markers[::-1])\n    return candidate[-match.end('candidate'):] if match else []",
    "docstring": "Run regexes against candidate's marked indexes to strip\n    signature candidate.\n\n    >>> _process_marked_candidate_indexes([9, 12, 14, 15, 17], 'clddc')\n    [15, 17]"
  },
  {
    "code": "def escape(self, text):\n        return self.__escapable.sub(self.__escape, compat.text_type(text)\n                                    ).encode('ascii')",
    "docstring": "Replace characters with their character references.\n\n        Replace characters by their named entity references.\n        Non-ASCII characters, if they do not have a named entity reference,\n        are replaced by numerical character references.\n\n        The return value is guaranteed to be ASCII."
  },
  {
    "code": "def read_contents(self, schema, name, conn):\n        sql =\n        log = get_logger()\n        cur = conn.cursor()\n        cur.execute(sql, [schema, name])\n        columns = cur.fetchall()\n        for column in columns:\n            column_dict = {'name': column[0],\n                           'type': column[1],\n                           'comment': column[2]}\n            log.debug('{} {}: {}'.format(column[0], column[1], column[2]))\n            self.contents.append(copy.deepcopy(column_dict))\n        cur.close()",
    "docstring": "Read table columns"
  },
  {
    "code": "def CheckGlobalStatic(filename, clean_lines, linenum, error):\n  line = clean_lines.elided[linenum]\n  if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):\n    line += clean_lines.elided[linenum + 1].strip()\n  match = Match(\n      r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\\b(.*)',\n      line)\n  if (match and\n      not Search(r'\\bstring\\b(\\s+const)?\\s*\\*\\s*(const\\s+)?\\w', line) and\n      not Search(r'\\boperator\\W', line) and\n      not Match(r'\\s*(<.*>)?(::[a-zA-Z0-9_]+)*\\s*\\(([^\"]|$)', match.group(3))):\n    error(filename, linenum, 'runtime/string', 4,\n          'For a static/global string constant, use a C style string instead: '\n          '\"%schar %s[]\".' %\n          (match.group(1), match.group(2)))\n  if Search(r'\\b([A-Za-z0-9_]*_)\\(\\1\\)', line):\n    error(filename, linenum, 'runtime/init', 4,\n          'You seem to be initializing a member variable with itself.')",
    "docstring": "Check for unsafe global or static objects.\n\n  Args:\n    filename: The name of the current file.\n    clean_lines: A CleansedLines instance containing the file.\n    linenum: The number of the line to check.\n    error: The function to call with any errors found."
  },
  {
    "code": "def _clear_surface(self, surface, rect=None):\n        clear_color = self._rgb_clear_color if self._clear_color is None else self._clear_color\n        surface.fill(clear_color, rect)",
    "docstring": "Clear the buffer, taking in account colorkey or alpha\n\n        :return:"
  },
  {
    "code": "def html(self, unicode=False):\n        html = lxml.html.tostring(self.element, encoding=self.encoding)\n        if unicode:\n            html = html.decode(self.encoding)\n        return html",
    "docstring": "Return HTML of element"
  },
  {
    "code": "def read_cyclic_can_msg(self, channel, count):\n        c_channel = BYTE(channel)\n        c_can_msg = (CanMsg * count)()\n        c_count = DWORD(count)\n        UcanReadCyclicCanMsg(self._handle, byref(c_channel), c_can_msg, c_count)\n        return c_can_msg[:c_count.value]",
    "docstring": "Reads back the list of CAN messages for automatically sending.\n\n        :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).\n        :param int count: The number of cyclic CAN messages to be received.\n        :return: List of received CAN messages (up to 16, see structure :class:`CanMsg`).\n        :rtype: list(CanMsg)"
  },
  {
    "code": "def protect_api(uuid=None, **kwargs):\n    bucket, version_id, key = uuid.split(':', 2)\n    g.obj = ObjectResource.get_object(bucket, key, version_id)\n    return g.obj",
    "docstring": "Retrieve object and check permissions.\n\n    Retrieve ObjectVersion of image being requested and check permission\n    using the Invenio-Files-REST permission factory."
  },
  {
    "code": "def clean(self,x):\n        return x[~np.any(np.isnan(x) | np.isinf(x),axis=1)]",
    "docstring": "remove nan and inf rows from x"
  },
  {
    "code": "def load_tab_data(self):\n        for tab in self._tabs.values():\n            if tab.load and not tab.data_loaded:\n                try:\n                    tab._data = tab.get_context_data(self.request)\n                except Exception:\n                    tab._data = False\n                    exceptions.handle(self.request)",
    "docstring": "Preload all data that for the tabs that will be displayed."
  },
  {
    "code": "def get(self, id):\n        with rconnect() as conn:\n            if id is None:\n                raise ValueError\n            if isinstance(id, uuid.UUID):\n                id = str(id)\n            if type(id) != str and type(id) != unicode:\n                raise ValueError\n            try:\n                query = self._base().get(id)\n                log.debug(query)\n                rv = query.run(conn)\n            except ReqlOpFailedError as e:\n                log.warn(e)\n                raise\n            except Exception as e:\n                log.warn(e)\n                raise\n            if rv is not None:\n                return self._model(rv)\n            return None",
    "docstring": "Get a single instance by pk id.\n\n            :param id: The UUID of the instance you want to retrieve."
  },
  {
    "code": "def _build_search_query(self, from_date):\n        sort = [{self._sort_on_field: {\"order\": \"asc\"}}]\n        filters = []\n        if self._repo:\n            filters.append({\"term\": {\"origin\": self._repo}})\n        if from_date:\n            filters.append({\"range\": {self._sort_on_field: {\"gte\": from_date}}})\n        if filters:\n            query = {\"bool\": {\"filter\": filters}}\n        else:\n            query = {\"match_all\": {}}\n        search_query = {\n            \"query\": query,\n            \"sort\": sort\n        }\n        return search_query",
    "docstring": "Build an ElasticSearch search query to retrieve items for read methods.\n\n        :param from_date: date to start retrieving items from.\n        :return: JSON query in dict format"
  },
  {
    "code": "def get_modified_items(self, target, path, last_modified_cutoff):\n        file_list = self.list_files(target, path)\n        out_dict = {}\n        for device_id, device_data in six.iteritems(file_list):\n            if isinstance(device_data, ErrorInfo):\n                out_dict[device_id] = device_data\n            else:\n                files = []\n                dirs = []\n                for cur_file in device_data.files:\n                    if cur_file.last_modified > last_modified_cutoff:\n                        files.append(cur_file)\n                for cur_dir in device_data.directories:\n                    if cur_dir.last_modified > last_modified_cutoff:\n                        dirs.append(cur_dir)\n                out_dict[device_id] = LsInfo(directories=dirs, files=files)\n        return out_dict",
    "docstring": "Get all files and directories from a path on the device modified since a given time\n\n        :param target: The device(s) to be targeted with this request\n        :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances\n        :param path: The path on the target to the directory to check for modified files.\n        :param last_modified_cutoff: The time (as Unix epoch time) to get files modified since\n        :type last_modified_cutoff: int\n        :return: A dictionary where the key is a device id and the value is either an :class:`~.ErrorInfo` if there\n            was a problem with the operation or a :class:`~.LsInfo` with the items modified since the\n            specified date"
  },
  {
    "code": "def _setup(self):\n        context_module = os.environ.get(ENVIRONMENT_CONTEXT_VARIABLE, 'context')\n        if not context_module:\n            raise ImproperlyConfigured(\n                'Requested context points to an empty variable. '\n                'You must either define the environment variable {0} '\n                'or call context.configure() before accessing the context.'\n                .format(ENVIRONMENT_CONTEXT_VARIABLE))\n        self._wrapped = Settings(context_module, default_settings=global_context)",
    "docstring": "Load the context module pointed to by the environment variable. This\n        is used the first time we need the context at all, if the user has not\n        previously configured the context manually."
  },
  {
    "code": "def _get_snpeff_cmd(cmd_name, datadir, data, out_file):\n    resources = config_utils.get_resources(\"snpeff\", data[\"config\"])\n    jvm_opts = resources.get(\"jvm_opts\", [\"-Xms750m\", \"-Xmx3g\"])\n    jvm_opts = config_utils.adjust_opts(jvm_opts, {\"algorithm\": {\"memory_adjust\":\n                                                                 {\"direction\": \"increase\",\n                                                                  \"maximum\": \"30000M\",\n                                                                  \"magnitude\": max(2, dd.get_cores(data))}}})\n    memory = \" \".join(jvm_opts)\n    snpeff = config_utils.get_program(\"snpEff\", data[\"config\"])\n    java_args = \"-Djava.io.tmpdir=%s\" % utils.safe_makedir(os.path.join(os.path.dirname(out_file), \"tmp\"))\n    export = \"unset JAVA_HOME && export PATH=%s:\\\"$PATH\\\" && \" % (utils.get_java_binpath())\n    cmd = \"{export} {snpeff} {memory} {java_args} {cmd_name} -dataDir {datadir}\"\n    return cmd.format(**locals())",
    "docstring": "Retrieve snpEff base command line."
  },
  {
    "code": "def validate(self):\n        for schema in (self.headers_schema, Message.headers_schema):\n            _log.debug(\n                'Validating message headers \"%r\" with schema \"%r\"',\n                self._headers,\n                schema,\n            )\n            jsonschema.validate(self._headers, schema)\n        for schema in (self.body_schema, Message.body_schema):\n            _log.debug(\n                'Validating message body \"%r\" with schema \"%r\"', self.body, schema\n            )\n            jsonschema.validate(self.body, schema)",
    "docstring": "Validate the headers and body with the message schema, if any.\n\n        In addition to the user-provided schema, all messages are checked against\n        the base schema which requires certain message headers and the that body\n        be a JSON object.\n\n        .. warning:: This method should not be overridden by sub-classes.\n\n        Raises:\n            jsonschema.ValidationError: If either the message headers or the message body\n                are invalid.\n            jsonschema.SchemaError: If either the message header schema or the message body\n                schema are invalid."
  },
  {
    "code": "def enable(name):\n    cmd = 'systemctl enable systemd-nspawn@{0}'.format(name)\n    if __salt__['cmd.retcode'](cmd, python_shell=False) != 0:\n        __context__['retcode'] = salt.defaults.exitcodes.EX_UNAVAILABLE\n        return False\n    return True",
    "docstring": "Set the named container to be launched at boot\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion nspawn.enable <name>"
  },
  {
    "code": "def _merge_ovls(self, ovls):\n        ret = reduce(lambda x, y: x.merge(y), ovls)\n        ret.value = self.value(ovls=ovls)\n        ret.set_props(self.props)\n        return ret",
    "docstring": "Merge ovls and also setup the value and props."
  },
  {
    "code": "def to_vobject(self, filename=None, uid=None):\n        self._update()\n        cal = iCalendar()\n        if uid:\n            self._gen_vevent(self._reminders[filename][uid], cal.add('vevent'))\n        elif filename:\n            for event in self._reminders[filename].values():\n                self._gen_vevent(event, cal.add('vevent'))\n        else:\n            for filename in self._reminders:\n                for event in self._reminders[filename].values():\n                    self._gen_vevent(event, cal.add('vevent'))\n        return cal",
    "docstring": "Return iCal object of Remind lines\n        If filename and UID are specified, the vObject only contains that event.\n        If only a filename is specified, the vObject contains all events in the file.\n        Otherwise the vObject contains all all objects of all files associated with the Remind object.\n\n        filename -- the remind file\n        uid -- the UID of the Remind line"
  },
  {
    "code": "def links(\n            self,\n            page: 'WikipediaPage',\n            **kwargs\n    ) -> PagesDict:\n        params = {\n            'action': 'query',\n            'prop': 'links',\n            'titles': page.title,\n            'pllimit': 500,\n        }\n        used_params = kwargs\n        used_params.update(params)\n        raw = self._query(\n            page,\n            used_params\n        )\n        self._common_attributes(raw['query'], page)\n        pages = raw['query']['pages']\n        for k, v in pages.items():\n            if k == '-1':\n                page._attributes['pageid'] = -1\n                return {}\n            else:\n                while 'continue' in raw:\n                    params['plcontinue'] = raw['continue']['plcontinue']\n                    raw = self._query(\n                        page,\n                        params\n                    )\n                    v['links'] += raw['query']['pages'][k]['links']\n                return self._build_links(v, page)\n        return {}",
    "docstring": "Returns links to other pages with respect to parameters\n\n        API Calls for parameters:\n\n        - https://www.mediawiki.org/w/api.php?action=help&modules=query%2Blinks\n        - https://www.mediawiki.org/wiki/API:Links\n\n        :param page: :class:`WikipediaPage`\n        :param kwargs: parameters used in API call\n        :return: links to linked pages"
  },
  {
    "code": "def set_uuid(obj, uuid=None):\n    from uuid import uuid4, UUID\n    if uuid is None:\n        uuid = uuid4()\n    elif isinstance(uuid, bytes):\n        if len(uuid) == 16:\n            uuid = UUID(bytes=uuid)\n        else:\n            uuid = UUID(hex=uuid)\n    if \"uuid\" in obj.attrs:\n        del obj.attrs[\"uuid\"]\n    obj.attrs.create(\"uuid\", str(uuid).encode('ascii'), dtype=\"|S36\")",
    "docstring": "Set the uuid attribute of an HDF5 object. Use this method to ensure correct dtype"
  },
  {
    "code": "def get_rate_from_db(currency: str) -> Decimal:\n    from .models import ConversionRate\n    try:\n        rate = ConversionRate.objects.get_rate(currency)\n    except ConversionRate.DoesNotExist:\n        raise ValueError('No conversion rate for %s' % (currency, ))\n    return rate.rate",
    "docstring": "Fetch currency conversion rate from the database"
  },
  {
    "code": "def resolve(self, from_email, resolution=None):\n        if from_email is None or not isinstance(from_email, six.string_types):\n            raise MissingFromEmail(from_email)\n        endpoint = '/'.join((self.endpoint, self.id,))\n        add_headers = {'from': from_email, }\n        data = {\n            'incident': {\n                'type': 'incident',\n                'status': 'resolved',\n            }\n        }\n        if resolution is not None:\n            data['resolution'] = resolution\n        result = self.request('PUT',\n                              endpoint=endpoint,\n                              add_headers=add_headers,\n                              data=data,)\n        return result",
    "docstring": "Resolve an incident using a valid email address."
  },
  {
    "code": "def render(self, content_state=None):\n        if content_state is None:\n            content_state = {}\n        blocks = content_state.get('blocks', [])\n        wrapper_state = WrapperState(self.block_map, blocks)\n        document = DOM.create_element()\n        entity_map = content_state.get('entityMap', {})\n        min_depth = 0\n        for block in blocks:\n            depth = block['depth']\n            elt = self.render_block(block, entity_map, wrapper_state)\n            if depth > min_depth:\n                min_depth = depth\n            if depth == 0:\n                DOM.append_child(document, elt)\n        if min_depth > 0 and wrapper_state.stack.length() != 0:\n            DOM.append_child(document, wrapper_state.stack.tail().elt)\n        return DOM.render(document)",
    "docstring": "Starts the export process on a given piece of content state."
  },
  {
    "code": "def expireat(self, key, timestamp):\n        if isinstance(timestamp, float):\n            return self.pexpireat(key, int(timestamp * 1000))\n        if not isinstance(timestamp, int):\n            raise TypeError(\"timestamp argument must be int, not {!r}\"\n                            .format(timestamp))\n        fut = self.execute(b'EXPIREAT', key, timestamp)\n        return wait_convert(fut, bool)",
    "docstring": "Set expire timestamp on a key.\n\n        if timeout is float it will be multiplied by 1000\n        coerced to int and passed to `pexpireat` method.\n\n        Otherwise raises TypeError if timestamp argument is not int."
  },
  {
    "code": "def context_chunk(self, context, j):\n        N_chunks = len(self.contexts[context])\n        start = self.contexts[context][j]\n        if j == N_chunks - 1:\n            end = len(self)\n        else:\n            end = self.contexts[context][j+1]\n        return [self[i] for i in xrange(start, end)]",
    "docstring": "Retrieve the tokens in the ``j``th chunk of context ``context``.\n\n        Parameters\n        ----------\n        context : str\n            Context name.\n        j : int\n            Index of a context chunk.\n\n        Returns\n        -------\n        chunk : list\n            List of tokens in the selected chunk."
  },
  {
    "code": "def create_widget(self, place, type, file=None, **kwargs):\n        widget_class = self.widget_types.get(type, self.widget_types['base'])\n        kwargs.update(place=place, type=type)\n        try:\n            element = widget_class(**kwargs)\n        except TypeError as e:\n            message = e.args[0] if e.args else ''\n            if (\n              'unexpected keyword argument' in message or\n              'required positional argument' in message\n              ):\n                raise WidgetParameterException(\n                    'type %s; %s; available: %r'\n                    % (type, message, widget_class._fields)\n                    )\n            raise e\n        if file and any(map(callable, element)):\n            return self._resolve_widget(file, element)\n        return element",
    "docstring": "Create a widget object based on given arguments.\n\n        If file object is provided, callable arguments will be resolved:\n        its return value will be used after calling them with file as first\n        parameter.\n\n        All extra `kwargs` parameters will be passed to widget constructor.\n\n        :param place: place hint where widget should be shown.\n        :type place: str\n        :param type: widget type name as taken from :attr:`widget_types` dict\n                     keys.\n        :type type: str\n        :param file: optional file object for widget attribute resolving\n        :type type: browsepy.files.Node or None\n        :returns: widget instance\n        :rtype: object"
  },
  {
    "code": "def has_zero_length_fragments(self, min_index=None, max_index=None):\n        min_index, max_index = self._check_min_max_indices(min_index, max_index)\n        zero = [i for i in range(min_index, max_index) if self[i].has_zero_length]\n        self.log([u\"Fragments with zero length: %s\", zero])\n        return (len(zero) > 0)",
    "docstring": "Return ``True`` if the list has at least one interval\n        with zero length withing ``min_index`` and ``max_index``.\n        If the latter are not specified, check all intervals.\n\n        :param int min_index: examine fragments with index greater than or equal to this index (i.e., included)\n        :param int max_index: examine fragments with index smaller than this index (i.e., excluded)\n        :raises ValueError: if ``min_index`` is negative or ``max_index``\n                            is bigger than the current number of fragments\n        :rtype: bool"
  },
  {
    "code": "def list_occupied_adb_ports():\n    out = AdbProxy().forward('--list')\n    clean_lines = str(out, 'utf-8').strip().split('\\n')\n    used_ports = []\n    for line in clean_lines:\n        tokens = line.split(' tcp:')\n        if len(tokens) != 3:\n            continue\n        used_ports.append(int(tokens[1]))\n    return used_ports",
    "docstring": "Lists all the host ports occupied by adb forward.\n\n    This is useful because adb will silently override the binding if an attempt\n    to bind to a port already used by adb was made, instead of throwing binding\n    error. So one should always check what ports adb is using before trying to\n    bind to a port with adb.\n\n    Returns:\n        A list of integers representing occupied host ports."
  },
  {
    "code": "def grad(self, params, epsilon=0.0001):\n        grad = []\n        for x in range(len(params)):\n            temp = np.copy(params)\n            temp[x] += epsilon\n            temp2 = np.copy(params)\n            temp2[x] -= epsilon\n            grad.append((self.__cost_function(temp)-self.__cost_function(temp2))/(2*epsilon))\n        return np.array(grad)",
    "docstring": "Used to check gradient estimation through slope approximation."
  },
  {
    "code": "def dict_from_hdf5(dict_like, h5group):\n    for name, value in h5group.attrs.items():\n        dict_like[name] = value",
    "docstring": "Load a dictionnary-like object from a h5 file group"
  },
  {
    "code": "def write(self, fptr):\n        self._validate(writing=True)\n        num_components = len(self.association)\n        fptr.write(struct.pack('>I4s', 8 + 2 + num_components * 6, b'cdef'))\n        fptr.write(struct.pack('>H', num_components))\n        for j in range(num_components):\n            fptr.write(struct.pack('>' + 'H' * 3,\n                                   self.index[j],\n                                   self.channel_type[j],\n                                   self.association[j]))",
    "docstring": "Write a channel definition box to file."
  },
  {
    "code": "def set_neighbor_out_filter(neigh_ip_address, filters):\n    core = CORE_MANAGER.get_core_service()\n    peer = core.peer_manager.get_by_addr(neigh_ip_address)\n    peer.out_filters = filters\n    return True",
    "docstring": "Sets the out_filter of a neighbor."
  },
  {
    "code": "def center(self):\n        image_center = Point(self.width / 2, self.height / 2)\n        return self.to_world(image_center)",
    "docstring": "Return footprint center in world coordinates, as GeoVector."
  },
  {
    "code": "def replaceSelectedText(self, text: str):\n        undoObj = UndoReplaceSelectedText(self, text)\n        self.qteUndoStack.push(undoObj)",
    "docstring": "Undo safe wrapper for the native ``replaceSelectedText`` method.\n\n        |Args|\n\n        * ``text`` (**str**): text to replace the current selection.\n\n        |Returns|\n\n        **None**\n\n        |Raises|\n\n        * **QtmacsArgumentError** if at least one argument has an invalid type."
  },
  {
    "code": "async def start_pairing(self):\n        self.srp.initialize()\n        msg = messages.crypto_pairing({\n            tlv8.TLV_METHOD: b'\\x00',\n            tlv8.TLV_SEQ_NO: b'\\x01'})\n        resp = await self.protocol.send_and_receive(\n            msg, generate_identifier=False)\n        pairing_data = _get_pairing_data(resp)\n        if tlv8.TLV_BACK_OFF in pairing_data:\n            time = int.from_bytes(\n                pairing_data[tlv8.TLV_BACK_OFF], byteorder='big')\n            raise Exception('back off {0}s'.format(time))\n        self._atv_salt = pairing_data[tlv8.TLV_SALT]\n        self._atv_pub_key = pairing_data[tlv8.TLV_PUBLIC_KEY]",
    "docstring": "Start pairing procedure."
  },
  {
    "code": "def package_existent(name):\n    try:\n        response = requests.get(PYPI_URL.format(name))\n        if response.ok:\n            msg = ('[error] \"{0}\" is registered already in PyPI.\\n'\n                   '\\tSpecify another package name.').format(name)\n            raise Conflict(msg)\n    except (socket.gaierror,\n            Timeout,\n            ConnectionError,\n            HTTPError) as exc:\n        raise BackendFailure(exc)",
    "docstring": "Search package.\n\n    * :class:`bootstrap_py.exceptions.Conflict` exception occurs\n      when user specified name has already existed.\n\n    * :class:`bootstrap_py.exceptions.BackendFailure` exception occurs\n      when PyPI service is down.\n\n    :param str name: package name"
  },
  {
    "code": "def callback(status, message, job, result, exception, stacktrace):\n    assert status in ['invalid', 'success', 'timeout', 'failure']\n    assert isinstance(message, Message)\n    if status == 'invalid':\n        assert job is None\n        assert result is None\n        assert exception is None\n        assert stacktrace is None\n    if status == 'success':\n        assert isinstance(job, Job)\n        assert exception is None\n        assert stacktrace is None\n    elif status == 'timeout':\n        assert isinstance(job, Job)\n        assert result is None\n        assert exception is None\n        assert stacktrace is None\n    elif status == 'failure':\n        assert isinstance(job, Job)\n        assert result is None\n        assert exception is not None\n        assert stacktrace is not None",
    "docstring": "Example callback function.\n\n    :param status: Job status. Possible values are \"invalid\" (job could not be\n        deserialized or was malformed), \"failure\" (job raised an exception),\n        \"timeout\" (job timed out), or \"success\" (job finished successfully and\n        returned a result).\n    :type status: str\n    :param message: Kafka message.\n    :type message: kq.Message\n    :param job: Job object, or None if **status** was \"invalid\".\n    :type job: kq.Job\n    :param result: Job result, or None if an exception was raised.\n    :type result: object | None\n    :param exception: Exception raised by job, or None if there was none.\n    :type exception: Exception | None\n    :param stacktrace: Exception traceback, or None if there was none.\n    :type stacktrace: str | None"
  },
  {
    "code": "def dict_pick(dictionary, allowed_keys):\n    return {key: value for key, value in viewitems(dictionary) if key in allowed_keys}",
    "docstring": "Return a dictionary only with keys found in `allowed_keys`"
  },
  {
    "code": "def build_calmjs_artifacts(dist, key, value, cmdclass=BuildCommand):\n    if value is not True:\n        return\n    build_cmd = dist.get_command_obj('build')\n    if not isinstance(build_cmd, cmdclass):\n        logger.error(\n            \"'build' command in Distribution is not an instance of \"\n            \"'%s:%s' (got %r instead)\",\n            cmdclass.__module__, cmdclass.__name__, build_cmd)\n        return\n    build_cmd.sub_commands.append((key, has_calmjs_artifact_declarations))",
    "docstring": "Trigger the artifact build process through the setuptools."
  },
  {
    "code": "def _connect_kubectl(spec):\n    return {\n        'method': 'kubectl',\n        'kwargs': {\n            'pod': spec.remote_addr(),\n            'python_path': spec.python_path(),\n            'connect_timeout': spec.ansible_ssh_timeout() or spec.timeout(),\n            'kubectl_path': spec.mitogen_kubectl_path(),\n            'kubectl_args': spec.extra_args(),\n            'remote_name': get_remote_name(spec),\n        }\n    }",
    "docstring": "Return ContextService arguments for a Kubernetes connection."
  },
  {
    "code": "def fmt_ces(c, title=None):\n    if not c:\n        return '()\\n'\n    if title is None:\n        title = 'Cause-effect structure'\n    concepts = '\\n'.join(margin(x) for x in c) + '\\n'\n    title = '{} ({} concept{})'.format(\n        title, len(c), '' if len(c) == 1 else 's')\n    return header(title, concepts, HEADER_BAR_1, HEADER_BAR_1)",
    "docstring": "Format a |CauseEffectStructure|."
  },
  {
    "code": "def _system(self, *args, **kwargs):\n        sysinfo = SysInfo(__grains__.get(\"kernel\"))\n        data = dict()\n        data['cpu'] = sysinfo._get_cpu()\n        data['disks'] = sysinfo._get_fs()\n        data['mounts'] = sysinfo._get_mounts()\n        data['memory'] = sysinfo._get_mem()\n        data['network'] = sysinfo._get_network()\n        data['os'] = sysinfo._get_os()\n        return data",
    "docstring": "This basically calls grains items and picks out only\n        necessary information in a certain structure.\n\n        :param args:\n        :param kwargs:\n        :return:"
  },
  {
    "code": "def change_password(self, password):\n        self.make_request(\n            ModificationFailed,\n            method='update',\n            resource='change_password',\n            params={'password': password})",
    "docstring": "Change user password. Change is committed immediately.\n\n        :param str password: new password\n        :return: None"
  },
  {
    "code": "def format_raw_field(key):\n    subfield = django_settings.WALDUR_CORE.get('ELASTICSEARCH', {}).get('raw_subfield', 'keyword')\n    return '%s.%s' % (camel_case_to_underscore(key), subfield)",
    "docstring": "When ElasticSearch analyzes string, it breaks it into parts.\n    In order make query for not-analyzed exact string values, we should use subfield instead.\n\n    The index template for Elasticsearch 5.0 has been changed.\n    The subfield for string multi-fields has changed from .raw to .keyword\n\n    Thus workaround for backward compatibility during migration is required.\n    See also: https://github.com/elastic/logstash/blob/v5.4.1/docs/static/breaking-changes.asciidoc"
  },
  {
    "code": "def acosh(x, context=None):\n    return _apply_function_in_current_context(\n        BigFloat,\n        mpfr.mpfr_acosh,\n        (BigFloat._implicit_convert(x),),\n        context,\n    )",
    "docstring": "Return the inverse hyperbolic cosine of x."
  },
  {
    "code": "def add_sync_callback(self, callback_cycles, callback):\n        self.sync_callbacks_cyles[callback] = 0\n        self.sync_callbacks.append([callback_cycles, callback])\n        if self.quickest_sync_callback_cycles is None or \\\n                        self.quickest_sync_callback_cycles > callback_cycles:\n            self.quickest_sync_callback_cycles = callback_cycles",
    "docstring": "Add a CPU cycle triggered callback"
  },
  {
    "code": "def log_time(method):\n    def timed(*args, **kwargs):\n        tic = time_function()\n        result = method(*args, **kwargs)\n        log.debug('%s executed in %.4f seconds.',\n                  method.__name__,\n                  time_function() - tic)\n        return result\n    timed.__name__ = method.__name__\n    timed.__doc__ = method.__doc__\n    return timed",
    "docstring": "A decorator for methods which will time the method\n    and then emit a log.debug message with the method name\n    and how long it took to execute."
  },
  {
    "code": "def paths(self):\n    paths = []\n    for tree in self.components():\n      paths += self._single_tree_paths(tree)\n    return paths",
    "docstring": "Assuming the skeleton is structured as a single tree, return a \n    list of all traversal paths across all components. For each component, \n    start from the first vertex, find the most distant vertex by \n    hops and set that as the root. Then use depth first traversal \n    to produce paths.\n\n    Returns: [ [(x,y,z), (x,y,z), ...], path_2, path_3, ... ]"
  },
  {
    "code": "def find_value_in_object(attr, obj):\n    if isinstance(obj, (collections.Iterator, list)):\n        for item in obj:\n            yield from find_value_in_object(attr, item)\n    elif isinstance(obj, collections.Mapping):\n        if attr in obj:\n            if isinstance(obj[attr], (collections.Iterator, list)):\n                for item in obj[attr]:\n                    yield item\n            else:\n                yield obj[attr]\n        for item in obj.values():\n            if item:\n                yield from find_value_in_object(attr, item)",
    "docstring": "Return values for any key coincidence with attr in obj or any other\n    nested dict."
  },
  {
    "code": "async def fetching_data(self, *_):\n        try:\n            with async_timeout.timeout(10):\n                resp = await self._websession.get(self._api_url, params=self._urlparams)\n            if resp.status != 200:\n                _LOGGER.error('%s returned %s', self._api_url, resp.status)\n                return False\n            text = await resp.text()\n        except (asyncio.TimeoutError, aiohttp.ClientError) as err:\n            _LOGGER.error('%s returned %s', self._api_url, err)\n            return False\n        try:\n            self.data = xmltodict.parse(text)['weatherdata']\n        except (ExpatError, IndexError) as err:\n            _LOGGER.error('%s returned %s', resp.url, err)\n            return False\n        return True",
    "docstring": "Get the latest data from met.no."
  },
  {
    "code": "def restart(self):\n        yield from self.manager.query(\"POST\", \"containers/{}/restart\".format(self._cid))\n        log.info(\"Docker container '{name}' [{image}] restarted\".format(\n            name=self._name, image=self._image))",
    "docstring": "Restart this Docker container."
  },
  {
    "code": "def launch(self, command_line, dependencies_description=None, env=[], remote_staging=[], job_config=None):\n        launch_params = dict(command_line=command_line, job_id=self.job_id)\n        submit_params_dict = submit_params(self.destination_params)\n        if submit_params_dict:\n            launch_params['params'] = json_dumps(submit_params_dict)\n        if dependencies_description:\n            launch_params['dependencies_description'] = json_dumps(dependencies_description.to_dict())\n        if env:\n            launch_params['env'] = json_dumps(env)\n        if remote_staging:\n            launch_params['remote_staging'] = json_dumps(remote_staging)\n        if job_config and 'touch_outputs' in job_config:\n            launch_params['submit_extras'] = json_dumps({'touch_outputs': job_config['touch_outputs']})\n        if job_config and self.setup_handler.local:\n            setup_params = _setup_params_from_job_config(job_config)\n            launch_params['setup_params'] = json_dumps(setup_params)\n        return self._raw_execute(\"submit\", launch_params)",
    "docstring": "Queue up the execution of the supplied `command_line` on the remote\n        server. Called launch for historical reasons, should be renamed to\n        enqueue or something like that.\n\n        **Parameters**\n\n        command_line : str\n            Command to execute."
  },
  {
    "code": "def matching_tokens(self, text, start=0):\n        for token_class, regexp in self._tokens:\n            match = regexp.match(text, pos=start)\n            if match:\n                yield token_class, match",
    "docstring": "Retrieve all token definitions matching the beginning of a text.\n\n        Args:\n            text (str): the text to test\n            start (int): the position where matches should be searched in the\n                string (see re.match(rx, txt, pos))\n\n        Yields:\n            (token_class, re.Match): all token class whose regexp matches the\n                text, and the related re.Match object."
  },
  {
    "code": "def calculate_boundaries(fine_states, full_magnetic_states):\n    r\n    N_magnetic = len(full_magnetic_states)\n    fq = full_magnetic_states[0].quantum_numbers[:4]\n    index_list_fine = []; start_fine = 0\n    hq = full_magnetic_states[0].quantum_numbers[:5]\n    index_list_hyperfine = []; start_hyperfine = 0\n    for i in range(N_magnetic):\n        magnetic = full_magnetic_states[i]\n        if magnetic.quantum_numbers[:4] != fq:\n            index_list_fine += [(start_fine, i)]\n            start_fine = i\n            fq = magnetic.quantum_numbers[:4]\n        if magnetic.quantum_numbers[:5] != hq:\n            index_list_hyperfine += [(start_hyperfine, i)]\n            start_hyperfine = i\n            hq = magnetic.quantum_numbers[:5]\n        if i == N_magnetic-1:\n            index_list_fine += [(start_fine, i+1)]\n            index_list_hyperfine += [(start_hyperfine, i+1)]\n    return index_list_fine, index_list_hyperfine",
    "docstring": "r\"\"\"Calculate the boundary indices within a list of magnetic states.\n\n    This function calculates the boundary indices of each fine state\n    and each hyperfine state within a list of magnetic states. The output\n    is a list of tuples (a,b) with a the starting index of a state and\n    b it's ending index.\n\n    >>> g=State(\"Rb\", 87, 5, 0, 1/Integer(2))\n    >>> full_magnetic_states=make_list_of_states([g],\"magnetic\")\n    >>> calculate_boundaries([g], full_magnetic_states)\n    ([(0, 8)], [(0, 3), (3, 8)])"
  },
  {
    "code": "def merge(metric_kind, prior, latest):\n    prior_type, _ = _detect_value(prior)\n    latest_type, _ = _detect_value(latest)\n    if prior_type != latest_type:\n        _logger.warn(u'Metric values are not compatible: %s, %s',\n                     prior, latest)\n        raise ValueError(u'Incompatible delta metric values')\n    if prior_type is None:\n        _logger.warn(u'Bad metric values, types not known for : %s, %s',\n                     prior, latest)\n        raise ValueError(u'Unsupported delta metric types')\n    if metric_kind == MetricKind.DELTA:\n        return _merge_delta_metric(prior, latest)\n    else:\n        return _merge_cumulative_or_gauge_metrics(prior, latest)",
    "docstring": "Merges `prior` and `latest`\n\n    Args:\n       metric_kind (:class:`MetricKind`): indicates the kind of metrics\n         being merged\n       prior (:class:`MetricValue`): an prior instance of the metric\n       latest (:class:`MetricValue`: the latest instance of the metric"
  },
  {
    "code": "def handle_offchain_secretreveal(\n        initiator_state: InitiatorTransferState,\n        state_change: ReceiveSecretReveal,\n        channel_state: NettingChannelState,\n        pseudo_random_generator: random.Random,\n) -> TransitionResult[InitiatorTransferState]:\n    iteration: TransitionResult[InitiatorTransferState]\n    valid_reveal = is_valid_secret_reveal(\n        state_change=state_change,\n        transfer_secrethash=initiator_state.transfer_description.secrethash,\n        secret=state_change.secret,\n    )\n    sent_by_partner = state_change.sender == channel_state.partner_state.address\n    is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED\n    if valid_reveal and is_channel_open and sent_by_partner:\n        events = events_for_unlock_lock(\n            initiator_state=initiator_state,\n            channel_state=channel_state,\n            secret=state_change.secret,\n            secrethash=state_change.secrethash,\n            pseudo_random_generator=pseudo_random_generator,\n        )\n        iteration = TransitionResult(None, events)\n    else:\n        events = list()\n        iteration = TransitionResult(initiator_state, events)\n    return iteration",
    "docstring": "Once the next hop proves it knows the secret, the initiator can unlock\n    the mediated transfer.\n\n    This will validate the secret, and if valid a new balance proof is sent to\n    the next hop with the current lock removed from the merkle tree and the\n    transferred amount updated."
  },
  {
    "code": "def update(self, group: 'SentenceGroup', flags: Flags) -> None:\n        to_append = []\n        for old, new in zip_longest(self.sentences, group.sentences):\n            if old is None:\n                old = Sentence()\n                to_append.append(old)\n            if new is None:\n                new = Sentence()\n            old.update(new, flags)\n        self.sentences.extend(to_append)",
    "docstring": "This object is considered to be a \"global\" sentence group while the\n        other one is flags-specific. All data related to the specified flags\n        will be overwritten by the content of the specified group."
  },
  {
    "code": "def splot(axes=\"gca\", smoothing=5000, degree=5, presmoothing=0, plot=True, spline_class=spline_single, interactive=True, show_derivative=1):\n    if   axes==\"gca\": axes = _pylab.gca()\n    xlabel = axes.xaxis.label.get_text()\n    ylabel = axes.yaxis.label.get_text()\n    xdata = axes.get_lines()[0].get_xdata()\n    ydata = axes.get_lines()[0].get_ydata()\n    if interactive:\n        return splinteractive(xdata, ydata, smoothing, degree, presmoothing, spline_class, xlabel, ylabel)\n    else:\n        return spline_class(xdata, ydata, smoothing, degree, presmoothing, plot, xlabel, ylabel)",
    "docstring": "gets the data from the plot and feeds it into splint\n    returns an instance of spline_single\n\n    axes=\"gca\"                  which axes to get the data from.\n    smoothing=5000              spline_single smoothing parameter\n    presmoothing=0              spline_single data presmoothing factor (nearest neighbor)\n    plot=True                   should we plot the result?\n    spline_class=spline_single  which data class to use?\n    interactive=False           should we spline fit interactively or just make a spline_single?"
  },
  {
    "code": "def check_keys_split(self, decoded):\n        bad_keys = set(decoded.keys()).difference(set(self._split_keys))\n        if bad_keys:\n            bad_keys = \", \".join(bad_keys)\n            raise ValueError(\"JSON data had unexpected key(s): {bad_keys}\"\n                             .format(bad_keys=pprint_thing(bad_keys)))",
    "docstring": "Checks that dict has only the appropriate keys for orient='split'."
  },
  {
    "code": "def _language_exclusions(stem: LanguageStemRange,\n                             exclusions: List[ShExDocParser.LanguageExclusionContext]) -> None:\n        for excl in exclusions:\n            excl_langtag = LANGTAG(excl.LANGTAG().getText()[1:])\n            stem.exclusions.append(LanguageStem(excl_langtag) if excl.STEM_MARK() else excl_langtag)",
    "docstring": "languageExclusion = '-' LANGTAG STEM_MARK?"
  },
  {
    "code": "def safe_send(self, connection, target, message, *args, **kwargs):\n        prefix = \"PRIVMSG {0} :\".format(target)\n        max_len = 510 - len(prefix)\n        for chunk in chunks(message.format(*args, **kwargs), max_len):\n            connection.send_raw(\"{0}{1}\".format(prefix, chunk))",
    "docstring": "Safely sends a message to the given target"
  },
  {
    "code": "def write_and_quit_all(editor):\n    eb = editor.window_arrangement.active_editor_buffer\n    if eb.location is None:\n        editor.show_message(_NO_FILE_NAME)\n    else:\n        eb.write()\n        quit(editor, all_=True, force=False)",
    "docstring": "Write current buffer and quit all."
  },
  {
    "code": "def getcwd(cls):\n        if not hasattr(cls._tl, \"cwd\"):\n            cls._tl.cwd = os.getcwd()\n        return cls._tl.cwd",
    "docstring": "Provide a context dependent current working directory. This method\n        will return the directory currently holding the lock."
  },
  {
    "code": "def print_event(attributes=[]):\n    def python_callback(event):\n        cls_name = event.__class__.__name__\n        attrs = ', '.join(['{attr}={val}'.format(attr=attr, val=event.__dict__[attr])\n                       for attr in attributes])\n        print('{cls_name}({attrs})'.format(cls_name=cls_name, attrs=attrs))\n    return python_callback",
    "docstring": "Function that returns a Python callback to pretty print the events."
  },
  {
    "code": "def spinn5_fpga_link(x, y, link, root_x=0, root_y=0):\n    x, y = spinn5_chip_coord(x, y, root_x, root_y)\n    return SPINN5_FPGA_LINKS.get((x, y, link))",
    "docstring": "Get the identity of the FPGA link which corresponds with the supplied\n    link.\n\n    .. note::\n        This function assumes the system is constructed from SpiNN-5 boards\n        whose FPGAs are loaded with the SpI/O 'spinnaker_fpgas' image.\n\n    Parameters\n    ----------\n    x, y : int\n        The chip whose link is of interest.\n    link : :py:class:`~rig.links.Link`\n        The link of interest.\n    root_x, root_y : int\n        The coordinates of the root chip (i.e. the chip used to boot the\n        machine), e.g. from\n        :py:attr:`rig.machine_control.MachineController.root_chip`.\n\n    Returns\n    -------\n    (fpga_num, link_num) or None\n        If not None, the link supplied passes through an FPGA link. The\n        returned tuple indicates the FPGA responsible for the sending-side of\n        the link.\n\n        `fpga_num` is the number (0, 1 or 2) of the FPGA responsible for the\n        link.\n\n        `link_num` indicates which of the sixteen SpiNNaker links (0 to 15)\n        into an FPGA is being used. Links 0-7 are typically handled by S-ATA\n        link 0 and 8-15 are handled by S-ATA link 1.\n\n        Returns None if the supplied link does not pass through an FPGA."
  },
  {
    "code": "def get_book_ids_by_comment(self, comment_id):\n        mgr = self._get_provider_manager('COMMENTING', local=True)\n        lookup_session = mgr.get_comment_lookup_session(proxy=self._proxy)\n        lookup_session.use_federated_book_view()\n        comment = lookup_session.get_comment(comment_id)\n        id_list = []\n        for idstr in comment._my_map['assignedBookIds']:\n            id_list.append(Id(idstr))\n        return IdList(id_list)",
    "docstring": "Gets the list of ``Book``  ``Ids`` mapped to a ``Comment``.\n\n        arg:    comment_id (osid.id.Id): ``Id`` of a ``Comment``\n        return: (osid.id.IdList) - list of book ``Ids``\n        raise:  NotFound - ``comment_id`` is not found\n        raise:  NullArgument - ``comment_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def read_until(self, delimiter: bytes, max_bytes: int = None) -> Awaitable[bytes]:\n        future = self._start_read()\n        self._read_delimiter = delimiter\n        self._read_max_bytes = max_bytes\n        try:\n            self._try_inline_read()\n        except UnsatisfiableReadError as e:\n            gen_log.info(\"Unsatisfiable read, closing connection: %s\" % e)\n            self.close(exc_info=e)\n            return future\n        except:\n            future.add_done_callback(lambda f: f.exception())\n            raise\n        return future",
    "docstring": "Asynchronously read until we have found the given delimiter.\n\n        The result includes all the data read including the delimiter.\n\n        If ``max_bytes`` is not None, the connection will be closed\n        if more than ``max_bytes`` bytes have been read and the delimiter\n        is not found.\n\n        .. versionchanged:: 4.0\n            Added the ``max_bytes`` argument.  The ``callback`` argument is\n            now optional and a `.Future` will be returned if it is omitted.\n\n        .. versionchanged:: 6.0\n\n           The ``callback`` argument was removed. Use the returned\n           `.Future` instead."
  },
  {
    "code": "def nd_load_and_stats(filenames, base_path=BASEPATH):\n    nds = []\n    for filename in filenames:\n        try:\n            nd_load = results.load_nd_from_pickle(filename=\n                                                  os.path.join(base_path,\n                                                               'grids',\n                                                               filename))\n            nds.append(nd_load)\n        except:\n            print(\"File {mvgd} not found. It was maybe excluded by Ding0 or \"\n                  \"just forgotten to generate by you...\".format(mvgd=filename))\n    nd = nds[0]\n    for n in nds[1:]:\n        nd.add_mv_grid_district(n._mv_grid_districts[0])\n    stats = results.calculate_mvgd_stats(nd)\n    return stats",
    "docstring": "Load multiple files from disk and generate stats\n\n    Passes the list of files assuming the ding0 data structure as default in\n    :code:`~/.ding0`.\n    Data will be concatenated and key indicators for each grid district are\n    returned in table and graphic format.\n\n    Parameters\n    ----------\n    filenames : list of str\n        Provide list of files you want to analyze\n    base_path : str\n        Root directory of Ding0 data structure, i.e. '~/.ding0' (which is\n        default).\n\n    Returns\n    -------\n    stats : pandas.DataFrame\n        Statistics of each MV grid districts"
  },
  {
    "code": "def call_ping(*args, **kwargs):\n    errors = dict()\n    for dev_id, dev_status in call_blink().items():\n        if not dev_status['result']:\n            errors[dev_id] = False\n    return errors or True",
    "docstring": "Ping the lamps by issuing a short inversion blink to all available devices.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' hue.ping"
  },
  {
    "code": "def do_chunked_gzip(infh, outfh, filename):\n    import gzip\n    gzfh = gzip.GzipFile('rawlogs', mode='wb', fileobj=outfh)\n    if infh.closed:\n        infh = open(infh.name, 'r')\n    else:\n        infh.seek(0)\n    readsize = 0\n    sys.stdout.write('Gzipping {0}: '.format(filename))\n    if os.stat(infh.name).st_size:\n        infh.seek(0)\n        progressbar = ProgressBar(sys.stdout, os.stat(infh.name).st_size, \"bytes gzipped\")\n        while True:\n            chunk = infh.read(GZIP_CHUNK_SIZE)\n            if not chunk:\n                break\n            if sys.version_info[0] >= 3:\n                gzfh.write(bytes(chunk, \"utf-8\"))\n            else:\n                gzfh.write(chunk)\n            readsize += len(chunk)\n            progressbar.redraw(readsize)\n    gzfh.close()",
    "docstring": "A memory-friendly way of compressing the data."
  },
  {
    "code": "def generate_notes(notes):\n        new_notes = []\n        for note in notes:\n            tmp_note = {}\n            for note_item in notes[note]:\n                tmp_note[note_item] = notes[note][note_item]\n            new_notes.append(tmp_note)\n        return new_notes",
    "docstring": "Generate the notes list\n\n        :param dict notes: A dict of converted notes from the old topology\n        :return: List of notes for the the topology\n        :rtype: list"
  },
  {
    "code": "def delete(self, expected_value=None, return_values=None):\n        return self.table.layer2.delete_item(self, expected_value,\n                                             return_values)",
    "docstring": "Delete the item from DynamoDB.\n\n        :type expected_value: dict\n        :param expected_value: A dictionary of name/value pairs that you expect.\n            This dictionary should have name/value pairs where the name\n            is the name of the attribute and the value is either the value\n            you are expecting or False if you expect the attribute not to\n            exist.\n            \n        :type return_values: str\n        :param return_values: Controls the return of attribute\n            name-value pairs before then were changed.  Possible\n            values are: None or 'ALL_OLD'. If 'ALL_OLD' is\n            specified and the item is overwritten, the content\n            of the old item is returned."
  },
  {
    "code": "def bulk_update_resourcedata(scenario_ids, resource_scenarios,**kwargs):\n    user_id = kwargs.get('user_id')\n    res = None\n    res = {}\n    net_ids = db.DBSession.query(Scenario.network_id).filter(Scenario.id.in_(scenario_ids)).all()\n    if len(set(net_ids)) != 1:\n        raise HydraError(\"Scenario IDS are not in the same network\")\n    for scenario_id in scenario_ids:\n        _check_can_edit_scenario(scenario_id, kwargs['user_id'])\n        scen_i = _get_scenario(scenario_id, user_id)\n        res[scenario_id] = []\n        for rs in resource_scenarios:\n            if rs.dataset is not None:\n                updated_rs = _update_resourcescenario(scen_i, rs, user_id=user_id, source=kwargs.get('app_name'))\n                res[scenario_id].append(updated_rs)\n            else:\n                _delete_resourcescenario(scenario_id, rs.resource_attr_id)\n        db.DBSession.flush()\n    return res",
    "docstring": "Update the data associated with a list of scenarios."
  },
  {
    "code": "async def export_wallet(handle: int,\n                        export_config_json: str) -> None:\n    logger = logging.getLogger(__name__)\n    logger.debug(\"export_wallet: >>> handle: %r, export_config_json: %r\",\n                 handle,\n                 export_config_json)\n    if not hasattr(export_wallet, \"cb\"):\n        logger.debug(\"export_wallet: Creating callback\")\n        export_wallet.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))\n    c_export_config_json = c_char_p(export_config_json.encode('utf-8'))\n    await do_call('indy_export_wallet',\n                  handle,\n                  c_export_config_json,\n                  export_wallet.cb)\n    logger.debug(\"export_wallet: <<<\")",
    "docstring": "Exports opened wallet to the file.\n\n    :param handle: wallet handle returned by indy_open_wallet.\n    :param export_config_json: JSON containing settings for input operation.\n       {\n          \"path\": path of the file that contains exported wallet content\n          \"key\": string, Key or passphrase used for wallet export key derivation.\n                         Look to key_derivation_method param for information about supported key derivation methods.\n          \"key_derivation_method\": optional<string> algorithm to use for export key derivation:\n                                ARGON2I_MOD - derive secured wallet export key (used by default)\n                                ARGON2I_INT - derive secured wallet export key (less secured but faster)\n                                RAW - raw wallet export key provided (skip derivation).\n                                      RAW keys can be generated with generate_wallet_key call\n       }\n    :return:"
  },
  {
    "code": "def get_initial_broks_from_satellites(self):\n        for satellites in [self.conf.brokers, self.conf.schedulers,\n                           self.conf.pollers, self.conf.reactionners, self.conf.receivers]:\n            for satellite in satellites:\n                if not satellite.reachable:\n                    continue\n                logger.debug(\"Getting initial brok from: %s\", satellite.name)\n                brok = satellite.get_initial_status_brok()\n                logger.debug(\"Satellite '%s' initial brok: %s\", satellite.name, brok)\n                self.add(brok)",
    "docstring": "Get initial broks from my internal satellite links\n\n        :return: None"
  },
  {
    "code": "def record_span(self, span):\n        if instana.singletons.agent.can_send() or \"INSTANA_TEST\" in os.environ:\n            json_span = None\n            if span.operation_name in self.registered_spans:\n                json_span = self.build_registered_span(span)\n            else:\n                json_span = self.build_sdk_span(span)\n            self.queue.put(json_span)",
    "docstring": "Convert the passed BasicSpan into an JsonSpan and\n        add it to the span queue"
  },
  {
    "code": "def revisions_diff(self, doc_id, *revisions):\n        url = '/'.join((self.database_url, '_revs_diff'))\n        data = {doc_id: list(revisions)}\n        resp = self.r_session.post(\n            url,\n            headers={'Content-Type': 'application/json'},\n            data=json.dumps(data, cls=self.client.encoder)\n        )\n        resp.raise_for_status()\n        return response_to_json_dict(resp)",
    "docstring": "Returns the differences in the current remote database for the specified\n        document id and specified list of revision values.\n\n        :param str doc_id: Document id to check for revision differences\n            against.\n        :param list revisions: List of document revisions values to check\n            against.\n\n        :returns: The revision differences in JSON format"
  },
  {
    "code": "def _get_verts_and_connect(self, paths):\n        verts = np.vstack(paths)\n        gaps = np.add.accumulate(np.array([len(x) for x in paths])) - 1\n        connect = np.ones(gaps[-1], dtype=bool)\n        connect[gaps[:-1]] = False\n        return verts, connect",
    "docstring": "retrieve vertices and connects from given paths-list"
  },
  {
    "code": "def uid_something_colon(self, node):\n        node.op_pos = [\n            NodeWithPosition(node.uid, (node.first_line, node.first_col))\n        ]\n        position = (node.body[0].first_line, node.body[0].first_col)\n        last, first = self.operators[':'].find_previous(position)\n        node.op_pos.append(NodeWithPosition(last, first))\n        return last",
    "docstring": "Creates op_pos for node from uid to colon"
  },
  {
    "code": "def _disjoint_qubits(op1: ops.Operation, op2: ops.Operation) -> bool:\n    return not set(op1.qubits) & set(op2.qubits)",
    "docstring": "Returns true only if the operations have qubits in common."
  },
  {
    "code": "def check_namespace(namespace_id):\n    if type(namespace_id) not in [str, unicode]:\n        return False\n    if not is_namespace_valid(namespace_id):\n        return False\n    return True",
    "docstring": "Verify that a namespace ID is well-formed\n\n    >>> check_namespace(123)\n    False\n    >>> check_namespace(None)\n    False\n    >>> check_namespace('')\n    False\n    >>> check_namespace('abcd')\n    True\n    >>> check_namespace('Abcd')\n    False\n    >>> check_namespace('a+bcd')\n    False\n    >>> check_namespace('.abcd')\n    False\n    >>> check_namespace('abcdabcdabcdabcdabcd')\n    False\n    >>> check_namespace('abcdabcdabcdabcdabc')\n    True"
  },
  {
    "code": "def predict_task(self, X, t=0, break_ties=\"random\", **kwargs):\n        Y_tp = self.predict_task_proba(X, t=t, **kwargs)\n        Y_tph = self._break_ties(Y_tp, break_ties)\n        return Y_tph",
    "docstring": "Predicts int labels for an input X on task t\n\n        Args:\n            X: The input for the predict_task_proba method\n            t: The task index to predict\n        Returns:\n            An n-dim tensor of int predictions for the specified task"
  },
  {
    "code": "def get_historical_minute_data(self, ticker: str):\n        start = self._start\n        stop = self._stop\n        if len(stop) > 4:\n            stop = stop[:4]\n        if len(start) > 4:\n            start = start[:4]\n        for year in range(int(start), int(stop) + 1):\n            beg_time = ('%s0101000000' % year)\n            end_time = ('%s1231235959' % year)\n            msg = \"HIT,%s,60,%s,%s,,,,1,,,s\\r\\n\" % (ticker,\n                                                    beg_time,\n                                                    end_time)\n            try:\n                data = iq.iq_query(message=msg)\n                iq.add_data_to_df(data=data)\n            except Exception as err:\n                log.error('No data returned because %s', err)\n        try:\n            self.dfdb.write_points(self._ndf, ticker)\n        except InfluxDBClientError as err:\n            log.error('Write to database failed: %s' % err)",
    "docstring": "Request historical 5 minute data from DTN."
  },
  {
    "code": "def main(argv=None):\n    try:\n        colorama.init()\n        if argv is None:\n            argv = sys.argv[1:]\n        _main(argv)\n    except RuntimeError as e:\n        print(colorama.Fore.RED + 'ERROR: ' +\n              str(e) + colorama.Style.RESET_ALL)\n        sys.exit(1)\n    else:\n        sys.exit(0)",
    "docstring": "Main entry point when the user runs the `trytravis` command."
  },
  {
    "code": "def parse_text_urls(mesg):\n    rval = []\n    loc = 0\n    for match in URLRE.finditer(mesg):\n        if loc < match.start():\n            rval.append(Chunk(mesg[loc:match.start()], None))\n        email = match.group(\"email\")\n        if email and \"mailto\" not in email:\n            mailto = \"mailto:{}\".format(email)\n        else:\n            mailto = match.group(1)\n        rval.append(Chunk(None, mailto))\n        loc = match.end()\n    if loc < len(mesg):\n        rval.append(Chunk(mesg[loc:], None))\n    return rval",
    "docstring": "Parse a block of text, splitting it into its url and non-url\n    components."
  },
  {
    "code": "def retrieve(self, *args, **kwargs):\n        lookup, key = self._lookup(*args, **kwargs)\n        return lookup[key]",
    "docstring": "Retrieve the permsission function for the provided things."
  },
  {
    "code": "def create_contour_metadata(contour_path):\n    metadata = {\n        'title': tr('Earthquake Contour'),\n        'layer_purpose': layer_purpose_earthquake_contour['key'],\n        'layer_geometry': layer_geometry_line['key'],\n        'layer_mode': layer_mode_classified['key'],\n        'inasafe_fields': {}\n    }\n    for contour_field in contour_fields:\n        metadata['inasafe_fields'][contour_field['key']] = contour_field[\n            'field_name']\n    write_iso19115_metadata(contour_path, metadata)",
    "docstring": "Create metadata file for contour layer.\n\n    :param contour_path: Path where the contour is located.\n    :type contour_path: basestring"
  },
  {
    "code": "def locate(self, point, _verify=True):\n        r\n        if _verify:\n            if self._dimension != 2:\n                raise NotImplementedError(\"Only 2D surfaces supported.\")\n            if point.shape != (self._dimension, 1):\n                point_dimensions = \" x \".join(\n                    str(dimension) for dimension in point.shape\n                )\n                msg = _LOCATE_ERROR_TEMPLATE.format(\n                    self._dimension, self._dimension, point, point_dimensions\n                )\n                raise ValueError(msg)\n        return _surface_intersection.locate_point(\n            self._nodes, self._degree, point[0, 0], point[1, 0]\n        )",
    "docstring": "r\"\"\"Find a point on the current surface.\n\n        Solves for :math:`s` and :math:`t` in :math:`B(s, t) = p`.\n\n        This method acts as a (partial) inverse to :meth:`evaluate_cartesian`.\n\n        .. warning::\n\n           A unique solution is only guaranteed if the current surface is\n           valid. This code assumes a valid surface, but doesn't check.\n\n        .. image:: ../../images/surface_locate.png\n           :align: center\n\n        .. doctest:: surface-locate\n\n           >>> nodes = np.asfortranarray([\n           ...     [0.0,  0.5 , 1.0, 0.25, 0.75, 0.0],\n           ...     [0.0, -0.25, 0.0, 0.5 , 0.75, 1.0],\n           ... ])\n           >>> surface = bezier.Surface(nodes, degree=2)\n           >>> point = np.asfortranarray([\n           ...     [0.59375],\n           ...     [0.25   ],\n           ... ])\n           >>> s, t = surface.locate(point)\n           >>> s\n           0.5\n           >>> t\n           0.25\n\n        .. testcleanup:: surface-locate\n\n           import make_images\n           make_images.surface_locate(surface, point)\n\n        Args:\n            point (numpy.ndarray): A (``D x 1``) point on the surface,\n                where :math:`D` is the dimension of the surface.\n            _verify (Optional[bool]): Indicates if extra caution should be\n                used to verify assumptions about the inputs. Can be\n                disabled to speed up execution time. Defaults to :data:`True`.\n\n        Returns:\n            Optional[Tuple[float, float]]: The :math:`s` and :math:`t`\n            values corresponding to ``point`` or :data:`None` if the point\n            is not on the surface.\n\n        Raises:\n            NotImplementedError: If the surface isn't in :math:`\\mathbf{R}^2`.\n            ValueError: If the dimension of the ``point`` doesn't match the\n                dimension of the current surface."
  },
  {
    "code": "def axis_to_data_points(ax, points_axis):\n    axis_to_data = ax.transAxes + ax.transData.inverted()\n    return axis_to_data.transform(points_axis)",
    "docstring": "Map points in axis coordinates to data coordinates.\n\n    Uses matplotlib.transform.\n\n    Parameters\n    ----------\n    ax : matplotlib.axis\n        Axis object from matplotlib.\n    points_axis : np.array\n        Points in axis coordinates."
  },
  {
    "code": "def search(self, q, **kw):\n        url = '{base_url}/search/{stream}'.format(**vars(self))\n        params = {\n            'q': q,\n        }\n        params.update(self.params)\n        params.update(kw)\n        response = self.session.get(url, params=params)\n        response.raise_for_status()\n        return response.json()",
    "docstring": "Search Gnip for given query, returning deserialized response."
  },
  {
    "code": "def coerce(self, value):\n        if isinstance(value, dict):\n            value = [value]\n        if not isiterable_notstring(value):\n            value = [value]\n        return [coerce_single_instance(self.lookup_field, v) for v in value]",
    "docstring": "Convert from whatever is given to a list of scalars for the lookup_field."
  },
  {
    "code": "def replace_u_start_day(day):\n    day = day.lstrip('-')\n    if day == 'uu' or day == '0u':\n        return '01'\n    if day == 'u0':\n        return '10'\n    return day.replace('u', '0')",
    "docstring": "Find the earliest legitimate day."
  },
  {
    "code": "def generate_modules_cache(self, modules, underlined=None,\n                               task_handle=taskhandle.NullTaskHandle()):\n        job_set = task_handle.create_jobset(\n            'Generatig autoimport cache for modules', len(modules))\n        for modname in modules:\n            job_set.started_job('Working on <%s>' % modname)\n            if modname.endswith('.*'):\n                mod = self.project.find_module(modname[:-2])\n                if mod:\n                    for sub in submodules(mod):\n                        self.update_resource(sub, underlined)\n            else:\n                self.update_module(modname, underlined)\n            job_set.finished_job()",
    "docstring": "Generate global name cache for modules listed in `modules`"
  },
  {
    "code": "def start(name, quiet=False, path=None):\n    data = _do_names(name, 'start', path=path)\n    if data and not quiet:\n        __jid_event__.fire_event(\n            {'data': data, 'outputter': 'lxc_start'}, 'progress')\n    return data",
    "docstring": "Start the named container.\n\n    path\n        path to the container parent\n        default: /var/lib/lxc (system default)\n\n        .. versionadded:: 2015.8.0\n\n    .. code-block:: bash\n\n        salt-run lxc.start name"
  },
  {
    "code": "def _set_attributes(self):\n        config = obj(self._config_dict)\n        for k, v in self._config_dict.items():\n            setattr(self, k, getattr(config, k))",
    "docstring": "Recursively transforms config dictionaries into instance attrs to make\n        for easy dot attribute access instead of dictionary access."
  },
  {
    "code": "def value(self, new_value):\n        if self.unit != units.Undefined and new_value.unit != self.unit:\n            raise AttributeError(\"%s must be in %s\" % (\n                self.__class__, self.unit))\n        self._value = new_value",
    "docstring": "Set the value of this measurement.\n\n        Raises:\n            AttributeError: if the new value isn't of the correct units."
  },
  {
    "code": "def setup_logging(namespace):\n    loglevel = {\n        0: logging.ERROR,\n        1: logging.WARNING,\n        2: logging.INFO,\n        3: logging.DEBUG,\n    }.get(namespace.verbosity, logging.DEBUG)\n    if namespace.verbosity > 1:\n        logformat = '%(levelname)s csvpandas %(lineno)s %(message)s'\n    else:\n        logformat = 'csvpandas %(message)s'\n    logging.basicConfig(stream=namespace.log, format=logformat, level=loglevel)",
    "docstring": "setup global logging"
  },
  {
    "code": "def interval(coro, interval=1, times=None, loop=None):\n    assert_corofunction(coro=coro)\n    times = int(times or 0) or float('inf')\n    @asyncio.coroutine\n    def schedule(times, *args, **kw):\n        while times > 0:\n            times -= 1\n            yield from coro(*args, **kw)\n            yield from asyncio.sleep(interval)\n    def wrapper(*args, **kw):\n        return ensure_future(schedule(times, *args, **kw), loop=loop)\n    return wrapper",
    "docstring": "Schedules the execution of a coroutine function every `x` amount of\n    seconds.\n\n    The function returns an `asyncio.Task`, which implements also an\n    `asyncio.Future` interface, allowing the user to cancel the execution\n    cycle.\n\n    This function can be used as decorator.\n\n    Arguments:\n        coro (coroutinefunction): coroutine function to defer.\n        interval (int/float): number of seconds to repeat the coroutine\n            execution.\n        times (int): optional maximum time of executions. Infinite by default.\n        loop (asyncio.BaseEventLoop, optional): loop to run.\n            Defaults to asyncio.get_event_loop().\n\n    Raises:\n        TypeError: if coro argument is not a coroutine function.\n\n    Returns:\n        future (asyncio.Task): coroutine wrapped as task future.\n            Useful for cancellation and state checking.\n\n    Usage::\n\n        # Usage as function\n        future = paco.interval(coro, 1)\n\n        # Cancel it after a while...\n        await asyncio.sleep(5)\n        future.cancel()\n\n        # Usage as decorator\n        @paco.interval(10)\n        async def metrics():\n            await send_metrics()\n\n        future = await metrics()"
  },
  {
    "code": "def MessageToDict(message,\n                  including_default_value_fields=False,\n                  preserving_proto_field_name=False):\n  printer = _Printer(including_default_value_fields,\n                     preserving_proto_field_name)\n  return printer._MessageToJsonObject(message)",
    "docstring": "Converts protobuf message to a JSON dictionary.\n\n  Args:\n    message: The protocol buffers message instance to serialize.\n    including_default_value_fields: If True, singular primitive fields,\n        repeated fields, and map fields will always be serialized.  If\n        False, only serialize non-empty fields.  Singular message fields\n        and oneof fields are not affected by this option.\n    preserving_proto_field_name: If True, use the original proto field\n        names as defined in the .proto file. If False, convert the field\n        names to lowerCamelCase.\n\n  Returns:\n    A dict representation of the JSON formatted protocol buffer message."
  },
  {
    "code": "def get_vendor(self, mac):\n        data = {\n            self._SEARCH_F: mac,\n            self._FORMAT_F: self._VERBOSE_T\n        }\n        response = self.__decode_str(self.__call_api(self.__url, data), 'utf-8')\n        return response",
    "docstring": "Get vendor company name.\n\n            Keyword arguments:\n            mac -- MAC address or OUI for searching"
  },
  {
    "code": "def _sinusoid(x, p, L, y):\n    N = int(len(p)/2)\n    n = np.linspace(0, N, N+1)\n    k = n*np.pi/L\n    func = 0\n    for n in range(0, N):\n        func += p[2*n]*np.sin(k[n]*x)+p[2*n+1]*np.cos(k[n]*x)\n    return func",
    "docstring": "Return the sinusoid cont func evaluated at input x for the continuum.\n\n    Parameters\n    ----------\n    x: float or np.array\n        data, input to function\n    p: ndarray\n        coefficients of fitting function\n    L: float\n        width of x data \n    y: float or np.array\n        output data corresponding to input x\n\n    Returns\n    -------\n    func: float\n        function evaluated for the input x"
  },
  {
    "code": "def make_function_arguments(args,\n                            kwonly,\n                            varargs,\n                            varkwargs,\n                            defaults,\n                            kw_defaults,\n                            annotations):\n    return ast.arguments(\n        args=[ast.arg(arg=a, annotation=annotations.get(a)) for a in args],\n        kwonlyargs=[\n            ast.arg(arg=a, annotation=annotations.get(a)) for a in kwonly\n        ],\n        defaults=defaults,\n        kw_defaults=list(map(kw_defaults.get, kwonly)),\n        vararg=None if varargs is None else ast.arg(\n            arg=varargs, annotation=annotations.get(varargs),\n        ),\n        kwarg=None if varkwargs is None else ast.arg(\n            arg=varkwargs, annotation=annotations.get(varkwargs)\n        ),\n    )",
    "docstring": "Make an ast.arguments from the args parsed out of a code object."
  },
  {
    "code": "def tokenize(text):\n    stem = PorterStemmer().stem\n    tokens = re.finditer('[a-z]+', text.lower())\n    for offset, match in enumerate(tokens):\n        unstemmed = match.group(0)\n        yield {\n            'stemmed':      stem(unstemmed),\n            'unstemmed':    unstemmed,\n            'offset':       offset\n        }",
    "docstring": "Yield tokens.\n\n    Args:\n        text (str): The original text.\n\n    Yields:\n        dict: The next token."
  },
  {
    "code": "def start_http_server(self, port, host='0.0.0.0', endpoint=None):\n        if self.should_start_http_server():\n            pc_start_http_server(port, host, registry=self.registry)",
    "docstring": "Start an HTTP server for exposing the metrics, if the\n        `should_start_http_server` function says we should, otherwise just return.\n        Uses the implementation from `prometheus_client` rather than a Flask app.\n\n        :param port: the HTTP port to expose the metrics endpoint on\n        :param host: the HTTP host to listen on (default: `0.0.0.0`)\n        :param endpoint: **ignored**, the HTTP server will respond on any path"
  },
  {
    "code": "def parse_csv_header(line):\n    units = {}\n    names = []\n    for var in line.split(','):\n        start = var.find('[')\n        if start < 0:\n            names.append(str(var))\n            continue\n        else:\n            names.append(str(var[:start]))\n        end = var.find(']', start)\n        unitstr = var[start + 1:end]\n        eq = unitstr.find('=')\n        if eq >= 0:\n            units[names[-1]] = unitstr[eq + 2:-1]\n    return names, units",
    "docstring": "Parse the CSV header returned by TDS."
  },
  {
    "code": "def ledger(self, start=None, end=None):\n        DEBIT_IN_DB = self._DEBIT_IN_DB()\n        flip = 1\n        if self._positive_credit():\n            flip *= -1\n        qs = self._entries_range(start=start, end=end)\n        qs = qs.order_by(\"transaction__t_stamp\", \"transaction__tid\")\n        balance = Decimal(\"0.00\")\n        if start:\n            balance = self.balance(start)\n        if not qs:\n            return []\n        def helper(balance_in):\n            balance = balance_in\n            for e in qs.all():\n                amount = e.amount * DEBIT_IN_DB\n                o_balance = balance\n                balance += flip * amount\n                yield LedgerEntry(amount, e, o_balance, balance)\n        return helper(balance)",
    "docstring": "Returns a list of entries for this account.\n\n        Ledger returns a sequence of LedgerEntry's matching the criteria\n        in chronological order. The returned sequence can be boolean-tested\n        (ie. test that nothing was returned).\n\n        If 'start' is given, only entries on or after that datetime are\n        returned.  'start' must be given with a timezone.\n\n        If 'end' is given, only entries before that datetime are\n        returned.  'end' must be given with a timezone."
  },
  {
    "code": "def find_hass_config():\n    if \"HASSIO_TOKEN\" in os.environ:\n        return \"/config\"\n    config_dir = default_hass_config_dir()\n    if os.path.isdir(config_dir):\n        return config_dir\n    raise ValueError(\n        \"Unable to automatically find the location of Home Assistant \"\n        \"config. Please pass it in.\"\n    )",
    "docstring": "Try to find HASS config."
  },
  {
    "code": "def get_nt_7z_dir ():\n    try:\n        import _winreg as winreg\n    except ImportError:\n        import winreg\n    try:\n        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r\"SOFTWARE\\7-Zip\")\n        try:\n            return winreg.QueryValueEx(key, \"Path\")[0]\n        finally:\n            winreg.CloseKey(key)\n    except WindowsError:\n        return \"\"",
    "docstring": "Return 7-Zip directory from registry, or an empty string."
  },
  {
    "code": "def get_month(datestring):\n    convert_written = re.compile(r\"jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec\", re.IGNORECASE)\n    month = convert_written.search(datestring)\n    month_number = None\n    if month:\n        month_number = strptime(month.group(), \"%b\").tm_mon\n        if month_number < 10:\n            month_number = add_zero(month_number)\n    return str(month_number)",
    "docstring": "Transforms a written month into corresponding month number.\n\n    E.g. November -> 11, or May -> 05.\n\n    Keyword arguments:\n    datestring -- a string\n\n    Returns:\n    String, or None if the transformation fails"
  },
  {
    "code": "def salt_ssh_create_dirs(self):\n        logger.debug('Creating salt-ssh dirs into: %s', self.settings_dir)\n        utils.create_dir(os.path.join(self.settings_dir, 'salt'))\n        utils.create_dir(os.path.join(self.settings_dir, 'pillar'))\n        utils.create_dir(os.path.join(self.settings_dir, 'etc', 'salt'))\n        utils.create_dir(os.path.join(self.settings_dir, 'var', 'cache', 'salt'))\n        utils.create_dir(os.path.join(self.settings_dir, 'var', 'log', 'salt'))",
    "docstring": "Creates the `salt-ssh` required directory structure"
  },
  {
    "code": "def color(string, status=True, warning=False, bold=True):\n    attr = []\n    if status:\n        attr.append('32')\n    if warning:\n        attr.append('31')\n    if bold:\n        attr.append('1')\n    return '\\x1b[%sm%s\\x1b[0m' % (';'.join(attr), string)",
    "docstring": "Change text color for the linux terminal, defaults to green.\n    Set \"warning=True\" for red."
  },
  {
    "code": "def get_url_distribution(self, params=None):\n        params = params or {}\n        all_responses = {}\n        api_name = 'virustotal-url-distribution'\n        response_chunks = self._request_reports(list(params.keys()), list(params.values()), 'url/distribution')\n        self._extract_response_chunks(all_responses, response_chunks, api_name)\n        return all_responses",
    "docstring": "Retrieves a live feed with the latest URLs submitted to VT.\n\n        Args:\n            resources: a dictionary with name and value for optional arguments\n        Returns:\n            A dict with the VT report."
  },
  {
    "code": "def membuf_tempfile(memfile):\n    memfile.seek(0, 0)\n    tmpfd, tmpname = mkstemp(suffix='.rar')\n    tmpf = os.fdopen(tmpfd, \"wb\")\n    try:\n        while True:\n            buf = memfile.read(BSIZE)\n            if not buf:\n                break\n            tmpf.write(buf)\n        tmpf.close()\n    except:\n        tmpf.close()\n        os.unlink(tmpname)\n        raise\n    return tmpname",
    "docstring": "Write in-memory file object to real file."
  },
  {
    "code": "def to_image(self, shape):\n        if len(shape) != 2:\n            raise ValueError('input shape must have 2 elements.')\n        image = np.zeros(shape)\n        if self.bbox.ixmin < 0 or self.bbox.iymin < 0:\n            return self._to_image_partial_overlap(image)\n        try:\n            image[self.bbox.slices] = self.data\n        except ValueError:\n            image = self._to_image_partial_overlap(image)\n        return image",
    "docstring": "Return an image of the mask in a 2D array of the given shape,\n        taking any edge effects into account.\n\n        Parameters\n        ----------\n        shape : tuple of int\n            The ``(ny, nx)`` shape of the output array.\n\n        Returns\n        -------\n        result : `~numpy.ndarray`\n            A 2D array of the mask."
  },
  {
    "code": "def http_reply(self):\n        data = {\n            'status': self.status,\n            'error': self.code.upper(),\n            'error_description': str(self)\n        }\n        if self.error_caught:\n            data['error_caught'] = pformat(self.error_caught)\n        if self.error_id:\n            data['error_id'] = self.error_id\n        if self.user_message:\n            data['user_message'] = self.user_message\n        r = jsonify(data)\n        r.status_code = self.status\n        if str(self.status) != \"200\":\n            log.warn(\"ERROR: caught error %s %s [%s]\" % (self.status, self.code, str(self)))\n        return r",
    "docstring": "Return a Flask reply object describing this error"
  },
  {
    "code": "def date_to_datetime(date, fraction=0.0):\n    day_seconds = (60 * 60 * 24) - 1\n    total_seconds = int(day_seconds * fraction)\n    delta = datetime.timedelta(seconds=total_seconds)\n    time = datetime.time()\n    dt = datetime.datetime.combine(date, time) + delta\n    return dt",
    "docstring": "fraction is how much through the day you are. 0=start of the day, 1=end of the day."
  },
  {
    "code": "def filebrowser(request):\n    try:\n        fb_url = reverse('fb_browse')\n    except:\n        fb_url = reverse('filebrowser:fb_browse')\n    return HttpResponse(jsmin(render_to_string('tinymce/filebrowser.js',\n                                               context={'fb_url': fb_url},\n                                               request=request)),\n                        content_type='application/javascript; charset=utf-8')",
    "docstring": "JavaScript callback function for `django-filebrowser`_\n\n    :param request: Django http request\n    :type request: django.http.request.HttpRequest\n    :return: Django http response with filebrowser JavaScript code for for TinyMCE 4\n    :rtype: django.http.HttpResponse\n\n    .. _django-filebrowser: https://github.com/sehmaschine/django-filebrowser"
  },
  {
    "code": "def _taskify(func):\n\tif not isinstance(func, _Task):\n\t\tfunc = _Task(func)\n\t\tspec = inspect.getargspec(func.func)\n\t\tif spec.args:\n\t\t\tnum_args = len(spec.args)\n\t\t\tnum_kwargs = len(spec.defaults or [])\n\t\t\tisflag = lambda x, y: '' if x.defaults[y] is False else '='\n\t\t\tfunc.args = spec.args[:(num_args - num_kwargs)]\n\t\t\tfunc.defaults = {spec.args[i - num_kwargs]: spec.defaults[i] for i in range(num_kwargs)}\n\t\t\tfunc.kwargs = [key.replace('_','-') + isflag(func, key) for key in func.defaults]\n\t\tif not func.name.startswith('_'):\n\t\t\tTASKS.append(func)\n\treturn func",
    "docstring": "Convert a function into a task."
  },
  {
    "code": "def step_prev(self):\n        window_start = around(self.parent.value('window_start') -\n                              self.parent.value('window_length') /\n                              self.parent.value('window_step'), 2)\n        if window_start < 0:\n            return\n        self.parent.overview.update_position(window_start)",
    "docstring": "Go to the previous step."
  },
  {
    "code": "def image_summary(predictions, targets, hparams):\n  del hparams\n  results = tf.cast(tf.argmax(predictions, axis=-1), tf.uint8)\n  gold = tf.cast(targets, tf.uint8)\n  summary1 = tf.summary.image(\"prediction\", results, max_outputs=2)\n  summary2 = tf.summary.image(\"data\", gold, max_outputs=2)\n  summary = tf.summary.merge([summary1, summary2])\n  return summary, tf.zeros_like(predictions)",
    "docstring": "Reshapes predictions and passes it to tensorboard.\n\n  Args:\n    predictions : The predicted image (logits).\n    targets : The ground truth.\n    hparams: model hparams.\n\n  Returns:\n    summary_proto: containing the summary images.\n    weights: A Tensor of zeros of the same shape as predictions."
  },
  {
    "code": "def _pp(dict_data):\n    for key, val in dict_data.items():\n        print('{0:<11}: {1}'.format(key, val))",
    "docstring": "Pretty print."
  },
  {
    "code": "def cs_axis_mapping(cls,\n                        part_info,\n                        axes_to_move\n                        ):\n        cs_ports = set()\n        axis_mapping = {}\n        for motor_info in cls.filter_values(part_info):\n            if motor_info.scannable in axes_to_move:\n                assert motor_info.cs_axis in cs_axis_names, \\\n                    \"Can only scan 1-1 mappings, %r is %r\" % \\\n                    (motor_info.scannable, motor_info.cs_axis)\n                cs_ports.add(motor_info.cs_port)\n                axis_mapping[motor_info.scannable] = motor_info\n        missing = list(set(axes_to_move) - set(axis_mapping))\n        assert not missing, \\\n            \"Some scannables %s are not in the CS mapping %s\" % (\n                missing, axis_mapping)\n        assert len(cs_ports) == 1, \\\n            \"Requested axes %s are in multiple CS numbers %s\" % (\n                axes_to_move, list(cs_ports))\n        cs_axis_counts = Counter([x.cs_axis for x in axis_mapping.values()])\n        overlap = [k for k, v in cs_axis_counts.items() if v > 1]\n        assert not overlap, \\\n            \"CS axis defs %s have more that one raw motor attached\" % overlap\n        return cs_ports.pop(), axis_mapping",
    "docstring": "Given the motor infos for the parts, filter those with scannable\n        names in axes_to_move, check they are all in the same CS, and return\n        the cs_port and mapping of cs_axis to MotorInfo"
  },
  {
    "code": "def _parseIsTag(self):\n        el = self._element\n        self._istag = el and el[0] == \"<\" and el[-1] == \">\"",
    "docstring": "Detect whether the element is HTML tag or not.\n\n        Result is saved to the :attr:`_istag` property."
  },
  {
    "code": "def _contiguous_slices(self):\n        k = j = None\n        for i in self._sorted():\n            if k is None:\n                k = j = i\n            if i - j > 1:\n                yield slice(k, j + 1, 1)\n                k = i\n            j = i\n        if k is not None:\n            yield slice(k, j + 1, 1)",
    "docstring": "Internal iterator over contiguous slices in RangeSet."
  },
  {
    "code": "def get_mount_points():\n    def decode_path(path):\n        return path.replace(br\"\\011\", b\"\\011\").replace(br\"\\040\", b\"\\040\").replace(br\"\\012\", b\"\\012\").replace(br\"\\134\", b\"\\134\")\n    with open(\"/proc/self/mounts\", \"rb\") as mounts:\n        for mount in mounts:\n            source, target, fstype, options, unused1, unused2 = mount.split(b\" \")\n            options = set(options.split(b\",\"))\n            yield (decode_path(source), decode_path(target), fstype, options)",
    "docstring": "Get all current mount points of the system.\n    Changes to the mount points during iteration may be reflected in the result.\n    @return a generator of (source, target, fstype, options),\n    where options is a list of bytes instances, and the others are bytes instances\n    (this avoids encoding problems with mount points with problematic characters)."
  },
  {
    "code": "def minimum_valid_values_in_any_group(df, levels=None, n=1, invalid=np.nan):\n    df = df.copy()\n    if levels is None:\n        if 'Group' in df.columns.names:\n            levels = [df.columns.names.index('Group')]\n    if invalid is np.nan:\n        dfx = ~np.isnan(df)\n    else:\n        dfx = df != invalid\n    dfc = dfx.astype(int).sum(axis=1, level=levels)\n    dfm = dfc.max(axis=1) >= n\n    mask = dfm.values\n    return df.iloc[mask, :]",
    "docstring": "Filter ``DataFrame`` by at least n valid values in at least one group.\n\n    Taking a Pandas ``DataFrame`` with a ``MultiIndex`` column index, filters rows to remove\n    rows where there are less than `n` valid values per group. Groups are defined by the `levels` parameter indexing\n    into the column index. For example, a ``MultiIndex`` with top and second level Group (A,B,C) and Replicate (1,2,3) using\n    ``levels=[0,1]`` would filter on `n` valid values per replicate. Alternatively, ``levels=[0]`` would filter on `n`\n     valid values at the Group level only, e.g. A, B or C.\n\n    By default valid values are determined by `np.nan`. However, alternatives can be supplied via `invalid`.\n\n    :param df: Pandas ``DataFrame``\n    :param levels: ``list`` of ``int`` specifying levels of column ``MultiIndex`` to group by\n    :param n: ``int`` minimum number of valid values threshold\n    :param invalid: matching invalid value\n    :return: filtered Pandas ``DataFrame``"
  },
  {
    "code": "def check(self):\r\n        return programs.is_module_installed(self.modname,\r\n                                            self.required_version,\r\n                                            self.installed_version)",
    "docstring": "Check if dependency is installed"
  },
  {
    "code": "def _call_brew(cmd, failhard=True):\n    user = __salt__['file.get_user'](_homebrew_bin())\n    runas = user if user != __opts__['user'] else None\n    cmd = '{} {}'.format(salt.utils.path.which('brew'), cmd)\n    result = __salt__['cmd.run_all'](cmd,\n                                     runas=runas,\n                                     output_loglevel='trace',\n                                     python_shell=False)\n    if failhard and result['retcode'] != 0:\n        raise CommandExecutionError('Brew command failed',\n                                    info={'result': result})\n    return result",
    "docstring": "Calls the brew command with the user account of brew"
  },
  {
    "code": "def describe(value):\n    if isinstance(value, types.ModuleType):\n        return describe_file(value)\n    elif isinstance(value, messages.Field):\n        return describe_field(value)\n    elif isinstance(value, messages.Enum):\n        return describe_enum_value(value)\n    elif isinstance(value, type):\n        if issubclass(value, messages.Message):\n            return describe_message(value)\n        elif issubclass(value, messages.Enum):\n            return describe_enum(value)\n    return None",
    "docstring": "Describe any value as a descriptor.\n\n    Helper function for describing any object with an appropriate descriptor\n    object.\n\n    Args:\n      value: Value to describe as a descriptor.\n\n    Returns:\n      Descriptor message class if object is describable as a descriptor, else\n      None."
  },
  {
    "code": "def run_total_dos(self,\n                      sigma=None,\n                      freq_min=None,\n                      freq_max=None,\n                      freq_pitch=None,\n                      use_tetrahedron_method=True):\n        if self._mesh is None:\n            msg = \"run_mesh has to be done before DOS calculation.\"\n            raise RuntimeError(msg)\n        total_dos = TotalDos(self._mesh,\n                             sigma=sigma,\n                             use_tetrahedron_method=use_tetrahedron_method)\n        total_dos.set_draw_area(freq_min, freq_max, freq_pitch)\n        total_dos.run()\n        self._total_dos = total_dos",
    "docstring": "Calculate total DOS from phonons on sampling mesh.\n\n        Parameters\n        ----------\n        sigma : float, optional\n            Smearing width for smearing method. Default is None\n        freq_min, freq_max, freq_pitch : float, optional\n            Minimum and maximum frequencies in which range DOS is computed\n            with the specified interval (freq_pitch).\n            Defaults are None and they are automatically determined.\n        use_tetrahedron_method : float, optional\n            Use tetrahedron method when this is True. When sigma is set,\n            smearing method is used."
  },
  {
    "code": "def debug(self, value):\n        self.__debug = value\n        if self.__debug:\n            for _, logger in iteritems(self.logger):\n                logger.setLevel(logging.DEBUG)\n            httplib.HTTPConnection.debuglevel = 1\n        else:\n            for _, logger in iteritems(self.logger):\n                logger.setLevel(logging.WARNING)\n            httplib.HTTPConnection.debuglevel = 0",
    "docstring": "Sets the debug status.\n\n        :param value: The debug status, True or False.\n        :type: bool"
  },
  {
    "code": "def plot_posterior_marginal(self, idx_param=0, res=100, smoothing=0,\n            range_min=None, range_max=None, label_xaxis=True,\n            other_plot_args={}, true_model=None\n        ):\n        res = plt.plot(*self.posterior_marginal(\n            idx_param, res, smoothing,\n            range_min, range_max\n        ), **other_plot_args)\n        if label_xaxis:\n            plt.xlabel('${}$'.format(self.model.modelparam_names[idx_param]))\n        if true_model is not None:\n            true_model = true_model[0, idx_param] if true_model.ndim == 2 else true_model[idx_param]\n            old_ylim = plt.ylim()\n            plt.vlines(true_model, old_ylim[0] - 0.1, old_ylim[1] + 0.1, color='k', linestyles='--')\n            plt.ylim(old_ylim)\n        return res",
    "docstring": "Plots a marginal of the requested parameter.\n\n        :param int idx_param: Index of parameter to be marginalized.\n        :param int res1: Resolution of of the axis.\n        :param float smoothing: Standard deviation of the Gaussian kernel\n            used to smooth; same units as parameter.\n        :param float range_min: Minimum range of the output axis.\n        :param float range_max: Maximum range of the output axis.\n        :param bool label_xaxis: Labels the :math:`x`-axis with the model parameter name\n            given by this updater's model.\n        :param dict other_plot_args: Keyword arguments to be passed to\n            matplotlib's ``plot`` function.\n        :param np.ndarray true_model: Plots a given model parameter vector\n            as the \"true\" model for comparison.\n\n        .. seealso::\n\n            :meth:`SMCUpdater.posterior_marginal`"
  },
  {
    "code": "def is_equal_strings_ignore_case(first, second):\r\n    if first and second:\r\n        return first.upper() == second.upper()\r\n    else:\r\n        return not (first or second)",
    "docstring": "The function compares strings ignoring case"
  },
  {
    "code": "def _init_kws(self):\n        if 'fmtgo' not in self.kws:\n            self.kws['fmtgo'] = self.grprdflt.gosubdag.prt_attr['fmt'] + \"\\n\"\n        if 'fmtgo2' not in self.kws:\n            self.kws['fmtgo2'] = self.grprdflt.gosubdag.prt_attr['fmt'] + \"\\n\"\n        if 'fmtgene' not in self.kws:\n            if 'itemid2name' not in self.kws:\n                self.kws['fmtgene'] = \"{AART} {ID}\\n\"\n            else:\n                self.kws['fmtgene'] = \"{AART} {ID} {NAME}\\n\"\n        if 'fmtgene2' not in self.kws:\n            self.kws['fmtgene2'] = self.kws['fmtgene']",
    "docstring": "Fill default values for keyword args, if necessary."
  },
  {
    "code": "def get_current_user(self):\n        from google.appengine.api import users\n        if _IS_DEVELOPMENT_SERVER:\n            return users.get_current_user()\n        else:\n            from google.appengine.api import oauth\n            try:\n                user = oauth.get_current_user()\n            except oauth.OAuthRequestError:\n                user = users.get_current_user()\n            return user",
    "docstring": "Override get_current_user for Google AppEngine\n        Checks for oauth capable request first, if this fails fall back to standard users API"
  },
  {
    "code": "def _Insert(cursor, table, values):\n  precondition.AssertIterableType(values, dict)\n  if not values:\n    return\n  column_names = list(sorted(values[0]))\n  for value_dict in values:\n    if set(column_names) != set(value_dict):\n      raise ValueError(\"Given value dictionaries must have identical keys. \"\n                       \"Expecting columns {!r}, but got value {!r}\".format(\n                           column_names, value_dict))\n  query = \"INSERT IGNORE INTO %s {cols} VALUES {vals}\" % table\n  query = query.format(\n      cols=mysql_utils.Columns(column_names),\n      vals=mysql_utils.Placeholders(num=len(column_names), values=len(values)))\n  values_list = []\n  for values_dict in values:\n    values_list.extend(values_dict[column] for column in column_names)\n  cursor.execute(query, values_list)",
    "docstring": "Inserts one or multiple rows into the given table.\n\n  Args:\n    cursor: The MySQL cursor to perform the insertion.\n    table: The table name, where rows should be inserted.\n    values: A list of dicts, associating column names to values."
  },
  {
    "code": "def option_hook(self, function):\n        sig = Signature(function)\n        if \"options\" not in sig.arguments:\n            raise KeyError(\"option_hook functions must have an argument called\"\n                           \" 'options', but got {}\".format(sig.arguments))\n        self.option_hooks.append(function)\n        return function",
    "docstring": "Decorator for adding an option hook function.\n\n        An option hook is a function that is called right before a run\n        is created. It receives (and potentially modifies) the options\n        dictionary. That is, the dictionary of commandline options used for\n        this run.\n\n        .. note::\n            The decorated function MUST have an argument called options.\n\n            The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n            but changing them has no effect. Only modification on\n            flags (entries starting with ``'--'``) are considered."
  },
  {
    "code": "def options(self, new):\n        options = self._create_options(new)\n        if self.widget.value:\n            self.widget.set_param(options=options, value=list(options.values())[:1])\n        else:\n            self.widget.options = options\n            self.widget.value = list(options.values())[:1]",
    "docstring": "Set options from list, or instance of named item\n\n        Over-writes old options"
  },
  {
    "code": "def validateAQLQuery(self, query, bindVars = None, options = None) :\n        \"returns the server answer is the query is valid. Raises an AQLQueryError if not\"\n        if bindVars is None :\n            bindVars = {}\n        if options is None :\n            options = {}\n        payload = {'query' : query, 'bindVars' : bindVars, 'options' : options}\n        r = self.connection.session.post(self.cursorsURL, data = json.dumps(payload, default=str))\n        data = r.json()\n        if r.status_code == 201 and not data[\"error\"] :\n            return data\n        else :\n            raise AQLQueryError(data[\"errorMessage\"], query, data)",
    "docstring": "returns the server answer is the query is valid. Raises an AQLQueryError if not"
  },
  {
    "code": "def extensions(self):\n        _tmp_extensions = self.mimes.encodings_map.keys() + \\\n            self.mimes.suffix_map.keys() + \\\n            self.mimes.types_map[1].keys() + \\\n            cfg['CFG_BIBDOCFILE_ADDITIONAL_KNOWN_FILE_EXTENSIONS']\n        extensions = []\n        for ext in _tmp_extensions:\n            if ext.startswith('.'):\n                extensions.append(ext)\n            else:\n                extensions.append('.' + ext)\n        extensions.sort()\n        extensions.reverse()\n        extensions = set([ext.lower() for ext in extensions])\n        extensions = '\\\\' + '$|\\\\'.join(extensions) + '$'\n        extensions = extensions.replace('+', '\\\\+')\n        return re.compile(extensions, re.I)",
    "docstring": "Generate the regular expression to match all the known extensions.\n\n        @return: the regular expression.\n        @rtype: regular expression object"
  },
  {
    "code": "def load(self, instance, xblock):\n        if djpyfs:\n            return djpyfs.get_filesystem(scope_key(instance, xblock))\n        else:\n            raise NotImplementedError(\"djpyfs not available\")",
    "docstring": "Get the filesystem for the field specified in 'instance' and the\n        xblock in 'xblock' It is locally scoped."
  },
  {
    "code": "def recipe_create(backend, kitchen, name):\n    err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)\n    if use_kitchen is None:\n        raise click.ClickException(err_str)\n    click.secho(\"%s - Creating Recipe %s for Kitchen '%s'\" % (get_datetime(), name, use_kitchen), fg='green')\n    check_and_print(DKCloudCommandRunner.recipe_create(backend.dki, use_kitchen,name))",
    "docstring": "Create a new Recipe"
  },
  {
    "code": "def writeBinaryItemContainer(filelike, binaryItemContainer, compress=True):\n    allMetadata = dict()\n    binarydatafile = io.BytesIO()\n    for index, binaryItem in enumerate(viewvalues(binaryItemContainer)):\n        metadataList = _dumpArrayDictToFile(binarydatafile, binaryItem.arrays)\n        allMetadata[index] = [binaryItem._reprJSON(), metadataList]\n    binarydatafile.seek(0)\n    zipcomp = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED\n    with zipfile.ZipFile(filelike, 'w', allowZip64=True) as containerFile:\n        containerFile.writestr('metadata',\n                               json.dumps(allMetadata, cls=MaspyJsonEncoder),\n                               zipcomp\n                               )\n        containerFile.writestr('binarydata', binarydatafile.getvalue(), zipcomp)",
    "docstring": "Serializes the binaryItems contained in binaryItemContainer and writes\n    them into a zipfile archive.\n\n    Examples of binaryItem classes are :class:`maspy.core.Ci` and\n    :class:`maspy.core.Sai`. A binaryItem class has to define the function\n    ``_reprJSON()`` which returns a JSON formated string representation of the\n    class instance. In addition it has to contain an attribute ``.arrays``, a\n    dictionary which values are ``numpy.array``, that are serialized to bytes\n    and written to the ``binarydata`` file of the zip archive. See\n    :func:`_dumpArrayDictToFile()`\n\n    The JSON formated string representation of the binaryItems, together with\n    the metadata, necessary to restore serialized numpy arrays, is written\n    to the ``metadata`` file of the archive in this form:\n    ``[[serialized binaryItem, [metadata of a numpy array, ...]], ...]``\n\n    Use the method :func:`loadBinaryItemContainer()` to restore a\n    binaryItemContainer from a zipfile.\n\n    :param filelike: path to a file (str) or a file-like object\n    :param binaryItemContainer: a dictionary containing binaryItems\n    :param compress: bool, True to use zip file compression"
  },
  {
    "code": "def describe_topic_rule(ruleName,\n             region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        rule = conn.get_topic_rule(ruleName=ruleName)\n        if rule and 'rule' in rule:\n            rule = rule['rule']\n            keys = ('ruleName', 'sql', 'description',\n                    'actions', 'ruleDisabled')\n            return {'rule': dict([(k, rule.get(k)) for k in keys])}\n        else:\n            return {'rule': None}\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Given a topic rule name describe its properties.\n\n    Returns a dictionary of interesting properties.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_iot.describe_topic_rule myrule"
  },
  {
    "code": "def create_pars_from_dict(name, pars_dict, rescale=True, update_bounds=False):\n    o = get_function_defaults(name)\n    pars_dict = pars_dict.copy()\n    for k in o.keys():\n        if not k in pars_dict:\n            continue\n        v = pars_dict[k]\n        if not isinstance(v, dict):\n            v = {'name': k, 'value': v}\n        o[k].update(v)\n        kw = dict(update_bounds=update_bounds,\n                  rescale=rescale)\n        if 'min' in v or 'max' in v:\n            kw['update_bounds'] = False\n        if 'scale' in v:\n            kw['rescale'] = False\n        o[k] = make_parameter_dict(o[k], **kw)\n    return o",
    "docstring": "Create a dictionary for the parameters of a function.\n\n    Parameters\n    ----------\n    name : str\n        Name of the function.\n\n    pars_dict : dict    \n        Existing parameter dict that will be merged with the\n        default dictionary created by this method.\n\n    rescale : bool\n        Rescale parameter values."
  },
  {
    "code": "def get_changes_since(self, change_number, app_changes=True, package_changes=False):\n        return self.send_job_and_wait(MsgProto(EMsg.ClientPICSChangesSinceRequest),\n                                      {\n                                       'since_change_number': change_number,\n                                       'send_app_info_changes': app_changes,\n                                       'send_package_info_changes': package_changes,\n                                      },\n                                      timeout=15\n                                     )",
    "docstring": "Get changes since a change number\n\n        :param change_number: change number to use as stating point\n        :type change_number: :class:`int`\n        :param app_changes: whether to inclued app changes\n        :type app_changes: :class:`bool`\n        :param package_changes: whether to inclued package changes\n        :type package_changes: :class:`bool`\n        :return: `CMsgClientPICSChangesSinceResponse <https://github.com/ValvePython/steam/blob/39627fe883feeed2206016bacd92cf0e4580ead6/protobufs/steammessages_clientserver.proto#L1171-L1191>`_\n        :rtype: proto message instance, or :class:`None` on timeout"
  },
  {
    "code": "def _dy(self):\n        min_y = max_y = self._start_y\n        for drawing_operation in self:\n            if hasattr(drawing_operation, 'y'):\n                min_y = min(min_y, drawing_operation.y)\n                max_y = max(max_y, drawing_operation.y)\n        return max_y - min_y",
    "docstring": "Return integer height of this shape's path in local units."
  },
  {
    "code": "def merge_ownership_periods(mappings):\n    return valmap(\n        lambda v: tuple(\n            OwnershipPeriod(\n                a.start,\n                b.start,\n                a.sid,\n                a.value,\n            ) for a, b in sliding_window(\n                2,\n                concatv(\n                    sorted(v),\n                    [OwnershipPeriod(\n                        pd.Timestamp.max.tz_localize('utc'),\n                        None,\n                        None,\n                        None,\n                    )],\n                ),\n            )\n        ),\n        mappings,\n    )",
    "docstring": "Given a dict of mappings where the values are lists of\n    OwnershipPeriod objects, returns a dict with the same structure with\n    new OwnershipPeriod objects adjusted so that the periods have no\n    gaps.\n\n    Orders the periods chronologically, and pushes forward the end date\n    of each period to match the start date of the following period. The\n    end date of the last period pushed forward to the max Timestamp."
  },
  {
    "code": "def _combine_attr_fast_update(self, attr, typ):\n        values = dict(getattr(self, attr, {}))\n        for base in self._class_data.bases:\n            vals = dict(getattr(base, attr, {}))\n            preserve_attr_data(vals, values)\n            values = combine(vals, values)\n        setattr(self, attr, typ(values))",
    "docstring": "Avoids having to call _update for each intermediate base.  Only\n        works for class attr of type UpdateDict."
  },
  {
    "code": "def draw_image(self, ax, image):\n        self.renderer.draw_image(imdata=utils.image_to_base64(image),\n                                 extent=image.get_extent(),\n                                 coordinates=\"data\",\n                                 style={\"alpha\": image.get_alpha(),\n                                        \"zorder\": image.get_zorder()},\n                                 mplobj=image)",
    "docstring": "Process a matplotlib image object and call renderer.draw_image"
  },
  {
    "code": "def add_styles(self, **styles):\n        for stylename in sorted(styles):\n            self._doc.styles.addElement(styles[stylename])",
    "docstring": "Add ODF styles to the current document."
  },
  {
    "code": "def mogrify(self, sql, params):\n        conn = self.engine.raw_connection()\n        cursor = conn.cursor()\n        return cursor.mogrify(sql, params)",
    "docstring": "Return the query string with parameters added"
  },
  {
    "code": "def _score_macro_average(self, n_classes):\n        all_fpr = np.unique(np.concatenate([self.fpr[i] for i in range(n_classes)]))\n        avg_tpr = np.zeros_like(all_fpr)\n        for i in range(n_classes):\n            avg_tpr += interp(all_fpr, self.fpr[i], self.tpr[i])\n        avg_tpr /= n_classes\n        self.fpr[MACRO] = all_fpr\n        self.tpr[MACRO] = avg_tpr\n        self.roc_auc[MACRO] = auc(self.fpr[MACRO], self.tpr[MACRO])",
    "docstring": "Compute the macro average scores for the ROCAUC curves."
  },
  {
    "code": "def readBuffer(self, newLength):\n        result = Buffer(self.buf, self.offset, newLength)\n        self.skip(newLength)\n        return result",
    "docstring": "Read next chunk as another buffer."
  },
  {
    "code": "def get_chart(chart_type, time_span=None, rolling_average=None, api_code=None):\n    resource = 'charts/' + chart_type + '?format=json'\n    if time_span is not None:\n        resource += '&timespan=' + time_span\n    if rolling_average is not None:\n        resource += '&rollingAverage=' + rolling_average\n    if api_code is not None:\n        resource += '&api_code=' + api_code\n    response = util.call_api(resource)\n    json_response = json.loads(response)\n    return Chart(json_response)",
    "docstring": "Get chart data of a specific chart type.\n\n    :param str chart_type: type of chart\n    :param str time_span: duration of the chart.\n    Default is 1 year for most charts, 1 week for mempool charts (optional)\n    (Example: 5weeks)\n    :param str rolling_average: duration over which the data should be averaged (optional)\n    :param str api_code: Blockchain.info API code (optional)\n    :return: an instance of :class:`Chart` class"
  },
  {
    "code": "def listflat(path, ext=None):\n    if os.path.isdir(path):\n        if ext:\n            if ext == 'tif' or ext == 'tiff':\n                files = glob.glob(os.path.join(path, '*.tif'))\n                files = files + glob.glob(os.path.join(path, '*.tiff'))\n            else:\n                files = glob.glob(os.path.join(path, '*.' + ext))\n        else:\n            files = [os.path.join(path, fname) for fname in os.listdir(path)]\n    else:\n        files = glob.glob(path)\n    files = [fpath for fpath in files if not isinstance(fpath, list) and not os.path.isdir(fpath)]\n    return sorted(files)",
    "docstring": "List files without recursion"
  },
  {
    "code": "def recover(self, requeue=False):\n        if not isinstance(requeue, bool):\n            raise AMQPInvalidArgument('requeue should be a boolean')\n        recover_frame = specification.Basic.Recover(requeue=requeue)\n        return self._channel.rpc_request(recover_frame)",
    "docstring": "Redeliver unacknowledged messages.\n\n        :param bool requeue: Re-queue the messages\n\n        :raises AMQPInvalidArgument: Invalid Parameters\n        :raises AMQPChannelError: Raises if the channel encountered an error.\n        :raises AMQPConnectionError: Raises if the connection\n                                     encountered an error.\n\n        :rtype: dict"
  },
  {
    "code": "def _needs_region_update(out_file, samples):\n    nblock_files = [x[\"regions\"][\"nblock\"] for x in samples if \"regions\" in x]\n    for nblock_file in nblock_files:\n        test_old = nblock_file.replace(\"-nblocks\", \"-analysisblocks\")\n        if os.path.exists(test_old):\n            return False\n    for noblock_file in nblock_files:\n        if not utils.file_uptodate(out_file, noblock_file):\n            return True\n    return False",
    "docstring": "Check if we need to update BED file of regions, supporting back compatibility."
  },
  {
    "code": "def status(self, **kwargs):\n        path = '/geo_nodes/%s/status' % self.get_id()\n        return self.manager.gitlab.http_get(path, **kwargs)",
    "docstring": "Get the status of the geo node.\n\n        Args:\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabGetError: If the server failed to perform the request\n\n        Returns:\n            dict: The status of the geo node"
  },
  {
    "code": "def get_build_platform():\n    from sysconfig import get_platform\n    plat = get_platform()\n    if sys.platform == \"darwin\" and not plat.startswith('macosx-'):\n        try:\n            version = _macosx_vers()\n            machine = os.uname()[4].replace(\" \", \"_\")\n            return \"macosx-%d.%d-%s\" % (\n                int(version[0]), int(version[1]),\n                _macosx_arch(machine),\n            )\n        except ValueError:\n            pass\n    return plat",
    "docstring": "Return this platform's string for platform-specific distributions\n\n    XXX Currently this is the same as ``distutils.util.get_platform()``, but it\n    needs some hacks for Linux and Mac OS X."
  },
  {
    "code": "def min(self, expr, extra_constraints=(), solver=None, model_callback=None):\n        if self._solver_required and solver is None:\n            raise BackendError(\"%s requires a solver for evaluation\" % self.__class__.__name__)\n        return self._min(self.convert(expr), extra_constraints=self.convert_list(extra_constraints), solver=solver, model_callback=model_callback)",
    "docstring": "Return the minimum value of `expr`.\n\n        :param expr: expression (an AST) to evaluate\n        :param solver: a solver object, native to the backend, to assist in\n                       the evaluation (for example, a z3.Solver)\n        :param extra_constraints: extra constraints (as ASTs) to add to the solver for this solve\n        :param model_callback:      a function that will be executed with recovered models (if any)\n        :return: the minimum possible value of expr (backend object)"
  },
  {
    "code": "def load_mldataset(filename):\n    user = []\n    item = []\n    score = []\n    with open(filename) as f:\n        for line in f:\n            tks = line.strip().split('\\t')\n            if len(tks) != 4:\n                continue\n            user.append(int(tks[0]))\n            item.append(int(tks[1]))\n            score.append(float(tks[2]))\n    user = mx.nd.array(user)\n    item = mx.nd.array(item)\n    score = mx.nd.array(score)\n    return gluon.data.ArrayDataset(user, item, score)",
    "docstring": "Not particularly fast code to parse the text file and load it into three NDArray's\n    and product an NDArrayIter"
  },
  {
    "code": "def showAddColumnDialog(self, triggered):\n        if triggered:\n            dialog = AddAttributesDialog(self)\n            dialog.accepted.connect(self.addColumn)\n            dialog.rejected.connect(self.uncheckButton)\n            dialog.show()",
    "docstring": "Display the dialog to add a column to the model.\n\n        This method is also a slot.\n\n        Args:\n            triggered (bool): If the corresponding button was\n                activated, the dialog will be created and shown."
  },
  {
    "code": "def _extend_settings(settings, configurator_config, prefix=None):\n    for key in configurator_config:\n        settings_key = '.'.join([prefix, key]) if prefix else key\n        if hasattr(configurator_config[key], 'keys') and\\\n                hasattr(configurator_config[key], '__getitem__'):\n            _extend_settings(\n                settings, configurator_config[key], prefix=settings_key\n            )\n        else:\n            settings[settings_key] = configurator_config[key]",
    "docstring": "Extend settings dictionary with content of yaml's  configurator key.\n\n    .. note::\n\n        This methods changes multilayered subkeys defined\n        within **configurator** into dotted keys in settings dictionary:\n\n        .. code-block:: yaml\n\n            configurator:\n                sqlalchemy:\n                    url: mysql://user:password@host/dbname\n\n        will result in **sqlalchemy.url**: mysql://user:password@host/dbname\n        key value in settings dictionary.\n\n    :param dict settings: settings dictionary\n    :param dict configurator_config: yml defined settings\n    :param str prefix: prefix for settings dict key"
  },
  {
    "code": "def cfg_lldp_interface(self, protocol_interface, phy_interface=None):\n        if phy_interface is None:\n            phy_interface = protocol_interface\n        self.create_attr_obj(protocol_interface, phy_interface)\n        ret = self.pub_lldp.enable_lldp(protocol_interface)\n        attr_obj = self.get_attr_obj(protocol_interface)\n        attr_obj.update_lldp_status(ret)",
    "docstring": "Cfg LLDP on interface and create object."
  },
  {
    "code": "def load_data(self, table_name, obj, database=None, **kwargs):\n        _database = self.db_name\n        self.set_database(database)\n        self.con.load_table(table_name, obj, **kwargs)\n        self.set_database(_database)",
    "docstring": "Wraps the LOAD DATA DDL statement. Loads data into an MapD table by\n        physically moving data files.\n\n        Parameters\n        ----------\n        table_name : string\n        obj: pandas.DataFrame or pyarrow.Table\n        database : string, default None (optional)"
  },
  {
    "code": "def get_induced_subhypergraph(self, nodes):\n        sub_H = self.copy()\n        sub_H.remove_nodes(sub_H.get_node_set() - set(nodes))\n        return sub_H",
    "docstring": "Gives a new hypergraph that is the subhypergraph of the current\n        hypergraph induced by the provided set of nodes. That is, the induced\n        subhypergraph's node set corresponds precisely to the nodes provided,\n        and the coressponding hyperedges in the subhypergraph are only those\n        from the original graph consist of tail and head sets that are subsets\n        of the provided nodes.\n\n        :param nodes: the set of nodes to find the induced subhypergraph of.\n        :returns: DirectedHypergraph -- the subhypergraph induced on the\n                provided nodes."
  },
  {
    "code": "def _get_args_to_parse(args, sys_argv):\n    arguments = args if args is not None else sys_argv[1:]\n    _LOG.debug(\"Parsing arguments: %s\", arguments)\n    return arguments",
    "docstring": "Return the given arguments if it is not None else sys.argv if it contains\n        something, an empty list otherwise.\n\n    Args:\n        args: argument to be parsed\n        sys_argv: arguments of the command line i.e. sys.argv"
  },
  {
    "code": "def to_list(var):\n    if var is None:\n        return []\n    if isinstance(var, str):\n        var = var.split('\\n')\n    elif not isinstance(var, list):\n        try:\n            var = list(var)\n        except TypeError:\n            raise ValueError(\"{} cannot be converted to the list.\".format(var))\n    return var",
    "docstring": "Checks if given value is a list, tries to convert, if it is not."
  },
  {
    "code": "def getattr(self, key):\n\t\tif ((key == \"classId\") and (self.__dict__.has_key(key))):\n\t\t\treturn self.__dict__[key]\n\t\tif UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId):\n\t\t\tif self.__dict__.has_key(key):\n\t\t\t\tif key in _ManagedObjectMeta[self.classId]:\n\t\t\t\t\treturn self.__dict__[key]\n\t\t\telse:\n\t\t\t\tif self.__dict__.has_key('XtraProperty'):\n\t\t\t\t\tif self.__dict__['XtraProperty'].has_key(key):\n\t\t\t\t\t\treturn self.__dict__['XtraProperty'][UcsUtils.WordU(key)]\n\t\t\t\t\telse:\n\t\t\t\t\t\traise AttributeError(key)\n\t\t\t\telse:\n\t\t\t\t\tprint \"No XtraProperty in mo:\", self.classId, \" key:\", key\n\t\telse:\n\t\t\tif self.__dict__['XtraProperty'].has_key(key):\n\t\t\t\treturn self.__dict__['XtraProperty'][UcsUtils.WordU(key)]\n\t\t\telif key == \"Dn\" or key == \"Rn\":\n\t\t\t\treturn None\n\t\t\telse:\n\t\t\t\traise AttributeError(key)",
    "docstring": "This method gets attribute value of a Managed Object."
  },
  {
    "code": "def info(name):\n    info = __salt__['user.info'](name=name)\n    ret = {'name': name,\n           'passwd': '',\n           'lstchg': '',\n           'min': '',\n           'max': '',\n           'warn': '',\n           'inact': '',\n           'expire': ''}\n    if info:\n        ret = {'name': info['name'],\n               'passwd': 'Unavailable',\n               'lstchg': info['password_changed'],\n               'min': '',\n               'max': '',\n               'warn': '',\n               'inact': '',\n               'expire': info['expiration_date']}\n    return ret",
    "docstring": "Return information for the specified user\n    This is just returns dummy data so that salt states can work.\n\n    :param str name: The name of the user account to show.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' shadow.info root"
  },
  {
    "code": "def from_response(cls, header_data, ignore_bad_cookies=False,\n                      ignore_bad_attributes=True):\n        \"Construct a Cookies object from response header data.\"\n        cookies = cls()\n        cookies.parse_response(\n            header_data,\n            ignore_bad_cookies=ignore_bad_cookies,\n            ignore_bad_attributes=ignore_bad_attributes)\n        return cookies",
    "docstring": "Construct a Cookies object from response header data."
  },
  {
    "code": "def get_current_release(self):\n        current = self._runner.run(\"readlink '{0}'\".format(self._current))\n        if current.failed:\n            return None\n        return os.path.basename(current.strip())",
    "docstring": "Get the release ID of the \"current\" deployment, None if\n        there is no current deployment.\n\n        This method performs one network operation.\n\n        :return: Get the current release ID\n        :rtype: str"
  },
  {
    "code": "def projects(self):\n        result = set()\n        for todo in self._todos:\n            projects = todo.projects()\n            result = result.union(projects)\n        return result",
    "docstring": "Returns a set of all projects in this list."
  },
  {
    "code": "def set_option(self, key, subkey, value):\n        key, subkey = _lower_keys(key, subkey)\n        _entry_must_exist(self.gc, key, subkey)\n        df = self.gc[(self.gc[\"k1\"] == key) & (self.gc[\"k2\"] == subkey)]\n        if df[\"locked\"].values[0]:\n            raise ValueError(\"{0}.{1} option is locked\".format(key, subkey))\n        ev.value_eval(value, df[\"type\"].values[0])\n        if not self.check_option(key, subkey, value):\n            info = \"{0}.{1} accepted options are: \".format(key, subkey)\n            info += \"[{}]\".format(\", \".join(df[\"values\"].values[0]))\n            raise ValueError(info)\n        self.gc.loc[\n            (self.gc[\"k1\"] == key) &\n            (self.gc[\"k2\"] == subkey), \"value\"] = value",
    "docstring": "Sets the value of an option.\n\n        :param str key: First identifier of the option.\n        :param str subkey: Second identifier of the option.\n        :param value: New value for the option (type varies).\n\n        :raise:\n            :NotRegisteredError: If ``key`` or ``subkey`` do not define any\n                option.\n            :ValueError: If the targeted obtion is locked.\n            :ValueError: If the provided value is not the expected\n                type for the option.\n            :ValueError: If the provided value is not in the expected\n                available values for the option."
  },
  {
    "code": "def create_cache(directory, compress_level=6, value_type_is_binary=False, **kwargs):\n    cache = diskcache.Cache(\n        directory,\n        disk=CompressedDisk,\n        disk_compress_level=compress_level,\n        disk_value_type_is_binary=value_type_is_binary,\n        **kwargs\n    )\n    return cache",
    "docstring": "Create a html cache. Html string will be automatically compressed.\n\n    :param directory: path for the cache directory.\n    :param compress_level: 0 ~ 9, 9 is slowest and smallest.\n    :param kwargs: other arguments.\n    :return: a `diskcache.Cache()`"
  },
  {
    "code": "def before_sleep_func_accept_retry_state(fn):\n    if not six.callable(fn):\n        return fn\n    if func_takes_retry_state(fn):\n        return fn\n    @_utils.wraps(fn)\n    def wrapped_before_sleep_func(retry_state):\n        warn_about_non_retry_state_deprecation(\n            'before_sleep', fn, stacklevel=4)\n        return fn(\n            retry_state.retry_object,\n            sleep=getattr(retry_state.next_action, 'sleep'),\n            last_result=retry_state.outcome)\n    return wrapped_before_sleep_func",
    "docstring": "Wrap \"before_sleep\" function to accept \"retry_state\"."
  },
  {
    "code": "def execute_script(self, string, args=None):\n        result = None\n        try:\n            result = self.driver_wrapper.driver.execute_script(string, args)\n            return result\n        except WebDriverException:\n            if result is not None:\n                message = 'Returned: ' + str(result)\n            else:\n                message = \"No message. Check your Javascript source: {}\".format(string)\n        raise WebDriverJavascriptException.WebDriverJavascriptException(self.driver_wrapper, message)",
    "docstring": "Execute script passed in to function\n\n        @type string:   str\n        @value string:  Script to execute\n        @type args:     dict\n        @value args:    Dictionary representing command line args\n\n        @rtype:         int\n        @rtype:         response code"
  },
  {
    "code": "def load_output_meta(self):\n        options = self.options\n        file_path = os.path.join(options.inputdir, 'output.meta.json')\n        with open(file_path) as infile:\n            return json.load(infile)",
    "docstring": "Load descriptive output meta data from a JSON file in the input directory."
  },
  {
    "code": "def getTagMapNearPosition(self, idx):\n        try:\n            return self.__ambiguousTypes[idx].tagMap\n        except KeyError:\n            raise error.PyAsn1Error('Type position out of range')",
    "docstring": "Return ASN.1 types that are allowed at or past given field position.\n\n        Some ASN.1 serialisation allow for skipping optional and defaulted fields.\n        Some constructed ASN.1 types allow reordering of the fields. When recovering\n        such objects it may be important to know which types can possibly be\n        present at any given position in the field sets.\n\n        Parameters\n        ----------\n        idx: :py:class:`int`\n            Field index\n\n        Returns\n        -------\n        : :class:`~pyasn1.type.tagmap.TagMap`\n            Map if ASN.1 types allowed at given field position\n\n        Raises\n        ------\n        : :class:`~pyasn1.error.PyAsn1Error`\n            If given position is out of fields range"
  },
  {
    "code": "def isAncestorOf(self, other):\n    if isinstance(other, Key):\n      return other._string.startswith(self._string + '/')\n    raise TypeError('%s is not of type %s' % (other, Key))",
    "docstring": "Returns whether this Key is an ancestor of `other`.\n\n        >>> john = Key('/Comedy/MontyPython/Actor:JohnCleese')\n        >>> Key('/Comedy').isAncestorOf(john)\n        True"
  },
  {
    "code": "def locationUpdatingAccept(MobileId_presence=0,\n                           FollowOnProceed_presence=0,\n                           CtsPermission_presence=0):\n    a = TpPd(pd=0x5)\n    b = MessageType(mesType=0x02)\n    c = LocalAreaId()\n    packet = a / b / c\n    if MobileId_presence is 1:\n        d = MobileIdHdr(ieiMI=0x17, eightBitMI=0x0)\n        packet = packet / d\n    if FollowOnProceed_presence is 1:\n        e = FollowOnProceed(ieiFOP=0xA1)\n        packet = packet / e\n    if CtsPermission_presence is 1:\n        f = CtsPermissionHdr(ieiCP=0xA2, eightBitCP=0x0)\n        packet = packet / f\n    return packet",
    "docstring": "LOCATION UPDATING ACCEPT Section 9.2.13"
  },
  {
    "code": "def _dict_mapping_to_pb(mapping, proto_type):\n    converted_pb = getattr(trace_pb2, proto_type)()\n    ParseDict(mapping, converted_pb)\n    return converted_pb",
    "docstring": "Convert a dict to protobuf.\n\n    Args:\n        mapping (dict): A dict that needs to be converted to protobuf.\n        proto_type (str): The type of the Protobuf.\n\n    Returns:\n        An instance of the specified protobuf."
  },
  {
    "code": "def create_color_method(color, code):\n    def func(self, content=''):\n        return self._apply_color(code, content)\n    setattr(Terminal, color, func)",
    "docstring": "Create a function for the given color\n    Done inside this function to keep the variables out of the main scope"
  },
  {
    "code": "def _regressors(self):\n        regressors = ()\n        if self.sklearn_ver[:2] >= (0, 18):\n            from sklearn.neural_network.multilayer_perceptron \\\n                import MLPRegressor\n            regressors += (MLPRegressor, )\n        return regressors",
    "docstring": "Get a set of supported regressors.\n\n        Returns\n        -------\n        regressors : {set}\n            The set of supported regressors."
  },
  {
    "code": "def LDA(x, labels, n=False):\n    if not n:\n        n = x.shape[1] - 1 \n    try:    \n        x = np.array(x)\n    except:\n        raise ValueError('Impossible to convert x to a numpy array.')\n    assert type(n) == int, \"Provided n is not an integer.\"\n    assert x.shape[1] > n, \"The requested n is bigger than \\\n        number of features in x.\"\n    eigen_values, eigen_vectors = LDA_base(x, labels)\n    eigen_order = eigen_vectors.T[(-eigen_values).argsort()]\n    return eigen_order[:n].dot(x.T).T",
    "docstring": "Linear Discriminant Analysis function.\n\n    **Args:**\n\n    * `x` : input matrix (2d array), every row represents new sample\n\n    * `labels` : list of labels (iterable), every item should be label for \\\n      sample with corresponding index\n\n    **Kwargs:**\n\n    * `n` : number of features returned (integer) - how many columns \n      should the output keep\n\n    **Returns:**\n    \n    * new_x : matrix with reduced size (number of columns are equal `n`)"
  },
  {
    "code": "def export_certificate(ctx, slot, format, certificate):\n    controller = ctx.obj['controller']\n    try:\n        cert = controller.read_certificate(slot)\n    except APDUError as e:\n        if e.sw == SW.NOT_FOUND:\n            ctx.fail('No certificate found.')\n        else:\n            logger.error('Failed to read certificate from slot %s', slot,\n                         exc_info=e)\n    certificate.write(cert.public_bytes(encoding=format))",
    "docstring": "Export a X.509 certificate.\n\n    Reads a certificate from one of the slots on the YubiKey.\n\n    \\b\n    SLOT        PIV slot to read certificate from.\n    CERTIFICATE File to write certificate to. Use '-' to use stdout."
  },
  {
    "code": "def template(cls, userdata):\n        ud = Userdata(cls.normalize(cls.create_empty(None), userdata))\n        return ud",
    "docstring": "Create a template instance used for message callbacks."
  },
  {
    "code": "def __doc_cmp(self, other):\n        if other is None:\n            return -1\n        if self.is_new and other.is_new:\n            return 0\n        if self.__docid < other.__docid:\n            return -1\n        elif self.__docid == other.__docid:\n            return 0\n        else:\n            return 1",
    "docstring": "Comparison function. Can be used to sort docs alphabetically."
  },
  {
    "code": "def _getEngineVersionDetails(self):\n\t\tversionFile = os.path.join(self.getEngineRoot(), 'Engine', 'Build', 'Build.version')\n\t\treturn json.loads(Utility.readFile(versionFile))",
    "docstring": "Parses the JSON version details for the latest installed version of UE4"
  },
  {
    "code": "def update_employee(emp_id, key=None, value=None, items=None):\n    if items is None:\n        if key is None or value is None:\n            return {'Error': 'At least one key/value pair is required'}\n        items = {key: value}\n    elif isinstance(items, six.string_types):\n        items = salt.utils.yaml.safe_load(items)\n    xml_items = ''\n    for pair in items:\n        xml_items += '<field id=\"{0}\">{1}</field>'.format(pair, items[pair])\n    xml_items = '<employee>{0}</employee>'.format(xml_items)\n    status, result = _query(\n        action='employees',\n        command=emp_id,\n        data=xml_items,\n        method='POST',\n    )\n    return show_employee(emp_id, ','.join(items.keys()))",
    "docstring": "Update one or more items for this employee. Specifying an empty value will\n    clear it for that employee.\n\n    CLI Examples:\n\n        salt myminion bamboohr.update_employee 1138 nickname Curly\n        salt myminion bamboohr.update_employee 1138 nickname ''\n        salt myminion bamboohr.update_employee 1138 items='{\"nickname\": \"Curly\"}\n        salt myminion bamboohr.update_employee 1138 items='{\"nickname\": \"\"}"
  },
  {
    "code": "def set_default_from_schema(instance, schema):\n    for name, property_ in schema.get('properties', {}).items():\n        if 'default' in property_:\n            instance.setdefault(name, property_['default'])\n        if 'properties' in property_:\n            set_default_from_schema(instance.setdefault(name, {}), property_)\n    return instance",
    "docstring": "Populate default values on an `instance` given a `schema`.\n\n    Parameters\n    ----------\n    instance : dict\n        instance to populate default values for\n    schema : dict\n        JSON schema with default values\n\n    Returns\n    -------\n    instance : dict\n        instance with populated default values"
  },
  {
    "code": "def rangify(number_list):\n    if not number_list:\n        return number_list\n    ranges = []\n    range_start = prev_num = number_list[0]\n    for num in number_list[1:]:\n        if num != (prev_num + 1):\n            ranges.append((range_start, prev_num))\n            range_start = num\n        prev_num = num\n    ranges.append((range_start, prev_num))\n    return ranges",
    "docstring": "Assumes the list is sorted."
  },
  {
    "code": "def download(self,\n                 files=None,\n                 destination=None,\n                 overwrite=False,\n                 callback=None):\n        if files is None:\n            files = self.files\n        elif not isinstance(files, list):\n            files = [files]\n        if destination is None:\n            destination = os.path.expanduser('~')\n        for f in files:\n            if not isinstance(f, dict):\n                raise FMBaseError('File must be a <dict> with file data')\n            self._download(f, destination, overwrite, callback)",
    "docstring": "Download file or files.\n\n        :param files: file or files to download\n        :param destination: destination path (defaults to users home directory)\n        :param overwrite: replace existing files?\n        :param callback: callback function that will receive total file size\n         and written bytes as arguments\n        :type files: ``list`` of ``dict`` with file data from filemail\n        :type destination: ``str`` or ``unicode``\n        :type overwrite: ``bool``\n        :type callback: ``func``"
  },
  {
    "code": "def jsonp_wrap(callback_key='callback'):\n    def decorator_fn(f):\n        @wraps(f)\n        def jsonp_output_decorator(*args, **kwargs):\n            task_data = _get_data_from_args(args)\n            data = task_data.get_data()\n            if callback_key not in data:\n                raise KeyError(\n                    'Missing required parameter \"{0}\" for task.'.format(\n                        callback_key))\n            callback = data[callback_key]\n            jsonp = f(*args, **kwargs)\n            if isinstance(JobContext.get_current_context(), WebJobContext):\n                JobContext.get_current_context().add_responder(\n                    MimeSetterWebTaskResponder('application/javascript'))\n            jsonp = \"{callback}({data})\".format(callback=callback, data=jsonp)\n            return jsonp\n        return jsonp_output_decorator\n    return decorator_fn",
    "docstring": "Format response to jsonp and add a callback to JSON data - a jsonp request"
  },
  {
    "code": "def read_motifs(infile=None, fmt=\"pwm\", as_dict=False):\n    if infile is None or isinstance(infile, six.string_types): \n        infile = pwmfile_location(infile)\n        with open(infile) as f:\n            motifs = _read_motifs_from_filehandle(f, fmt)\n    else:\n        motifs = _read_motifs_from_filehandle(infile, fmt)\n    if as_dict:\n        motifs = {m.id:m for m in motifs}\n    return motifs",
    "docstring": "Read motifs from a file or stream or file-like object.\n\n    Parameters\n    ----------\n    infile : string or file-like object, optional\n        Motif database, filename of motif file or file-like object. If infile \n        is not specified the default motifs as specified in the config file \n        will be returned.\n\n    fmt : string, optional\n        Motif format, can be 'pwm', 'transfac', 'xxmotif', 'jaspar' or 'align'.\n    \n    as_dict : boolean, optional\n        Return motifs as a dictionary with motif_id, motif pairs.\n    \n    Returns\n    -------\n    motifs : list\n        List of Motif instances. If as_dict is set to True, motifs is a \n        dictionary."
  },
  {
    "code": "def read(self, subpath=None):\n        is_binary = self.is_binary(subpath)\n        filename = self.readme_for(subpath)\n        try:\n            if is_binary:\n                return self._read_binary(filename)\n            return self._read_text(filename)\n        except (OSError, EnvironmentError) as ex:\n            if ex.errno == errno.ENOENT:\n                raise ReadmeNotFoundError(filename)\n            raise",
    "docstring": "Returns the UTF-8 content of the specified subpath.\n\n        subpath is expected to already have been normalized.\n\n        Raises ReadmeNotFoundError if a README for the specified subpath\n        does not exist.\n\n        Raises werkzeug.exceptions.NotFound if the resulting path\n        would fall out of the root directory."
  },
  {
    "code": "def restart_listener(self, topics):\n        if self.listener is not None:\n            if self.listener.running:\n                self.stop()\n        self.__init__(topics=topics)",
    "docstring": "Restart listener after configuration update."
  },
  {
    "code": "def last_component_continued(self):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('SL record not yet initialized!')\n        if not self.symlink_components:\n            raise pycdlibexception.PyCdlibInternalError('Trying to get continued on a non-existent component!')\n        return self.symlink_components[-1].is_continued()",
    "docstring": "Determines whether the previous component of this SL record is a\n        continued one or not.\n\n        Parameters:\n         None.\n        Returns:\n         True if the previous component of this SL record is continued, False otherwise."
  },
  {
    "code": "def AddSourceRestriction(self,cidr):\n\t\tself.source_restrictions.append(SourceRestriction(self,cidr))\n\t\treturn(self.Update())",
    "docstring": "Add and commit a single source IP restriction policy.\n\n\t\t>>> clc.v2.Server(\"WA1BTDIX01\").PublicIPs().public_ips[0]\n\t\t\t\t.AddSourceRestriction(cidr=\"132.200.20.1/32\").WaitUntilComplete()\n\t\t0"
  },
  {
    "code": "def get(self, key, default=None):\n    if key in self._hparam_types:\n      if default is not None:\n        param_type, is_param_list = self._hparam_types[key]\n        type_str = 'list<%s>' % param_type if is_param_list else str(param_type)\n        fail_msg = (\"Hparam '%s' of type '%s' is incompatible with \"\n                    'default=%s' % (key, type_str, default))\n        is_default_list = isinstance(default, list)\n        if is_param_list != is_default_list:\n          raise ValueError(fail_msg)\n        try:\n          if is_default_list:\n            for value in default:\n              _cast_to_type_if_compatible(key, param_type, value)\n          else:\n            _cast_to_type_if_compatible(key, param_type, default)\n        except ValueError as e:\n          raise ValueError('%s. %s' % (fail_msg, e))\n      return getattr(self, key)\n    return default",
    "docstring": "Returns the value of `key` if it exists, else `default`."
  },
  {
    "code": "def opp_two_point_field_goal_percentage(self):\n        try:\n            result = float(self.opp_two_point_field_goals) / \\\n                float(self.opp_two_point_field_goal_attempts)\n            return round(result, 3)\n        except ZeroDivisionError:\n            return 0.0",
    "docstring": "Returns a ``float`` of the number of two point field goals made divided\n        by the number of two point field goal attempts by opponents. Percentage\n        ranges from 0-1."
  },
  {
    "code": "def get_template_folder():\n    cfg = get_project_configuration()\n    if 'templates' not in cfg:\n        home = os.path.expanduser(\"~\")\n        rcfile = os.path.join(home, \".hwrtrc\")\n        cfg['templates'] = pkg_resources.resource_filename('hwrt',\n                                                           'templates/')\n        with open(rcfile, 'w') as f:\n            yaml.dump(cfg, f, default_flow_style=False)\n    return cfg['templates']",
    "docstring": "Get path to the folder where th HTML templates are."
  },
  {
    "code": "def snapshot():\n    all_objects = gc.get_objects()\n    this_frame = inspect.currentframe()\n    selected_objects = []\n    for obj in all_objects:\n        if obj is not this_frame:\n            selected_objects.append(obj)\n    graph = ObjectGraph(selected_objects)\n    del this_frame, all_objects, selected_objects, obj\n    return graph",
    "docstring": "Return the graph of all currently gc-tracked objects.\n\n    Excludes the returned :class:`~refcycle.object_graph.ObjectGraph` and\n    objects owned by it.\n\n    Note that a subsequent call to :func:`~refcycle.creators.snapshot` will\n    capture all of the objects owned by this snapshot.  The\n    :meth:`~refcycle.object_graph.ObjectGraph.owned_objects` method may be\n    helpful when excluding these objects from consideration."
  },
  {
    "code": "def resetMonitors(self):\n        Debug.error(\"*** BE AWARE: experimental - might not work ***\")\n        Debug.error(\"Re-evaluation of the monitor setup has been requested\")\n        Debug.error(\"... Current Region/Screen objects might not be valid any longer\")\n        Debug.error(\"... Use existing Region/Screen objects only if you know what you are doing!\")\n        self.__init__(self._screenId)\n        self.showMonitors()",
    "docstring": "Recalculates screen based on changed monitor setup"
  },
  {
    "code": "def parse_extension_arg(arg, arg_dict):\n    match = re.match(r'^(([^\\d\\W]\\w*)(\\.[^\\d\\W]\\w*)*)=(.*)$', arg)\n    if match is None:\n        raise ValueError(\n            \"invalid extension argument '%s', must be in key=value form\" % arg\n        )\n    name = match.group(1)\n    value = match.group(4)\n    arg_dict[name] = value",
    "docstring": "Converts argument strings in key=value or key.namespace=value form\n    to dictionary entries\n\n    Parameters\n    ----------\n    arg : str\n        The argument string to parse, which must be in key=value or\n        key.namespace=value form.\n    arg_dict : dict\n        The dictionary into which the key/value pair will be added"
  },
  {
    "code": "def end_offsets(self, partitions):\n        offsets = self._fetcher.end_offsets(\n            partitions, self.config['request_timeout_ms'])\n        return offsets",
    "docstring": "Get the last offset for the given partitions. The last offset of a\n        partition is the offset of the upcoming message, i.e. the offset of the\n        last available message + 1.\n\n        This method does not change the current consumer position of the\n        partitions.\n\n        Note:\n            This method may block indefinitely if the partition does not exist.\n\n        Arguments:\n            partitions (list): List of TopicPartition instances to fetch\n                offsets for.\n\n        Returns:\n            ``{TopicPartition: int}``: The end offsets for the given partitions.\n\n        Raises:\n            UnsupportedVersionError: If the broker does not support looking\n                up the offsets by timestamp.\n            KafkaTimeoutError: If fetch failed in request_timeout_ms"
  },
  {
    "code": "def new_fact(self):\n        fact = lib.EnvCreateFact(self._env, self._tpl)\n        if fact == ffi.NULL:\n            raise CLIPSError(self._env)\n        return new_fact(self._env, fact)",
    "docstring": "Create a new Fact from this template."
  },
  {
    "code": "def get_node_id(edge, node_type):\n    assert node_type in ('source', 'target')\n    _, node_id_str = edge.attrib[node_type].split('.')\n    return int(node_id_str)",
    "docstring": "returns the source or target node id of an edge, depending on the\n    node_type given."
  },
  {
    "code": "def get_src_names(gta):\n    o = []\n    for s in gta.roi.sources:\n        o += [s.name]\n    return sorted(o)",
    "docstring": "Build and return a list of source name\n\n    Parameters\n    ----------\n\n    gta : `fermipy.GTAnalysis`\n        The analysis object\n\n\n    Returns\n    -------\n\n    l : list\n       Names of the source"
  },
  {
    "code": "def fetch(self):\n        if self.document_url is None:\n            raise CloudantDocumentException(101)\n        resp = self.r_session.get(self.document_url)\n        resp.raise_for_status()\n        self.clear()\n        self.update(response_to_json_dict(resp, cls=self.decoder))",
    "docstring": "Retrieves the content of the current document from the remote database\n        and populates the locally cached Document object with that content.\n        A call to fetch will overwrite any dictionary content currently in\n        the locally cached Document object."
  },
  {
    "code": "def get_content_children(self, content_id, expand=None, parent_version=None, callback=None):\n        params = {}\n        if expand:\n            params[\"expand\"] = expand\n        if parent_version:\n            params[\"parentVersion\"] = parent_version\n        return self._service_get_request(\"rest/api/content/{id}/child\".format(id=content_id), params=params,\n                                         callback=callback)",
    "docstring": "Returns a map of the direct children of a piece of Content. Content can have multiple types of children -\n        for example a Page can have children that are also Pages, but it can also have Comments and Attachments.\n\n        The {@link ContentType}(s) of the children returned is specified by the \"expand\" query parameter in the request\n        - this parameter can include expands for multiple child types.\n        If no types are included in the expand parameter, the map returned will just list the child types that\n        are available to be expanded for the {@link Content} referenced by the \"content_id\" parameter.\n        :param content_id (string): A string containing the id of the content to retrieve children for.\n        :param expand (string): OPTIONAL :A comma separated list of properties to expand on the children.\n                                Default: None.\n        :param parent_version (int): OPTIONAL: An integer representing the version of the content to retrieve\n                                     children for. Default: 0 (Latest)\n\n        :param callback: OPTIONAL: The callback to execute on the resulting data, before the method returns.\n                         Default: None (no callback, raw data returned).\n        :return: The JSON data returned from the content/{id}/child endpoint, or the results of the callback.\n                 Will raise requests.HTTPError on bad input, potentially."
  },
  {
    "code": "def call(subcommand, args):\n    args['<napp>'] = parse_napps(args['<napp>'])\n    func = getattr(NAppsAPI, subcommand)\n    func(args)",
    "docstring": "Call a subcommand passing the args."
  },
  {
    "code": "def is_ancestor(self, child_key_name, ancestor_key_name):\n        if ancestor_key_name is None:\n            return True\n        one_up_parent = self.dct[child_key_name]['parent']\n        if child_key_name == ancestor_key_name:\n            return True\n        elif one_up_parent is None:\n            return False\n        else:\n            return self.is_ancestor(one_up_parent, ancestor_key_name)",
    "docstring": "Returns True if ancestor lies in the ancestry tree of child."
  },
  {
    "code": "def get_data(self, data_x, data_y):\n        image = self.get_image()\n        if image is not None:\n            return image.get_data_xy(data_x, data_y)\n        raise ImageViewNoDataError(\"No image found\")",
    "docstring": "Get the data value at the given position.\n        Indices are zero-based, as in Numpy.\n\n        Parameters\n        ----------\n        data_x, data_y : int\n            Data indices for X and Y, respectively.\n\n        Returns\n        -------\n        value\n            Data slice.\n\n        Raises\n        ------\n        ginga.ImageView.ImageViewNoDataError\n            Image not found."
  },
  {
    "code": "def update_port_statuses_cfg(self, context, port_ids, status):\n        self._l3plugin.update_router_port_statuses(context, port_ids,\n                                                   status)",
    "docstring": "Update the operational statuses of a list of router ports.\n\n        This is called by the Cisco cfg agent to update the status of a list\n        of ports.\n\n        :param context: contains user information\n        :param port_ids: list of ids of all the ports for the given status\n        :param status: PORT_STATUS_ACTIVE/PORT_STATUS_DOWN."
  },
  {
    "code": "def match(self, row):\n        if re.search(self._expression, row[self._field]):\n            return True\n        return False",
    "docstring": "Returns True if the field matches the regular expression of this simple condition. Returns False otherwise.\n\n        :param dict row: The row.\n\n        :rtype: bool"
  },
  {
    "code": "def get_client_index_from_id(self, client_id):\r\n        for index, client in enumerate(self.clients):\r\n            if id(client) == client_id:\r\n                return index",
    "docstring": "Return client index from id"
  },
  {
    "code": "def reset(self):\n        self._options = {}\n        self.save(force=True)\n        self._success = True",
    "docstring": "Resets the configuration, and overwrites the existing configuration\n        file."
  },
  {
    "code": "def humanize_duration(duration):\n    days = duration.days\n    hours = int(duration.seconds / 3600)\n    minutes = int(duration.seconds % 3600 / 60)\n    seconds = int(duration.seconds % 3600 % 60)\n    parts = []\n    if days > 0:\n        parts.append(u'%s %s' % (days, pluralize(days, _('day,days'))))\n    if hours > 0:\n        parts.append(u'%s %s' % (hours, pluralize(hours, _('hour,hours'))))\n    if minutes > 0:\n        parts.append(u'%s %s' % (minutes, pluralize(minutes, _('minute,minutes'))))\n    if seconds > 0:\n        parts.append(u'%s %s' % (seconds, pluralize(seconds, _('second,seconds'))))\n    return ', '.join(parts) if len(parts) != 0 else _('< 1 second')",
    "docstring": "Returns a humanized string representing time difference\n\n    For example: 2 days 1 hour 25 minutes 10 seconds"
  },
  {
    "code": "def conv3x3(in_channels, out_channels, stride=1):\n    return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)",
    "docstring": "3x3 convolution with padding.\n    Original code has had bias turned off, because Batch Norm would remove the bias either way"
  },
  {
    "code": "def get_session(db_url):\n        engine = create_engine(db_url, poolclass=NullPool, echo=False)\n        Session = sessionmaker(bind=engine)\n        Base.metadata.create_all(engine)\n        return Session()",
    "docstring": "Gets SQLAlchemy session given url. Your tables must inherit\n        from Base in hdx.utilities.database.\n\n        Args:\n            db_url (str): SQLAlchemy url\n\n        Returns:\n            sqlalchemy.orm.session.Session: SQLAlchemy session"
  },
  {
    "code": "def is_same_filename (filename1, filename2):\n    return os.path.realpath(filename1) == os.path.realpath(filename2)",
    "docstring": "Check if filename1 and filename2 are the same filename."
  },
  {
    "code": "def _initialize_providers(self):\n        configured_providers = active_config.DATABASES\n        provider_objects = {}\n        if not isinstance(configured_providers, dict) or configured_providers == {}:\n            raise ConfigurationError(\n                \"'DATABASES' config must be a dict and at least one \"\n                \"provider must be defined\")\n        if 'default' not in configured_providers:\n            raise ConfigurationError(\n                \"You must define a 'default' provider\")\n        for provider_name, conn_info in configured_providers.items():\n            provider_full_path = conn_info['PROVIDER']\n            provider_module, provider_class = provider_full_path.rsplit('.', maxsplit=1)\n            provider_cls = getattr(importlib.import_module(provider_module), provider_class)\n            provider_objects[provider_name] = provider_cls(conn_info)\n        return provider_objects",
    "docstring": "Read config file and initialize providers"
  },
  {
    "code": "def GameActionModeEnum(ctx):\n    return Enum(\n        ctx,\n        diplomacy=0,\n        speed=1,\n        instant_build=2,\n        quick_build=4,\n        allied_victory=5,\n        cheat=6,\n        unk0=9,\n        spy=10,\n        unk1=11,\n        farm_queue=13,\n        farm_unqueue=14,\n        default=Pass\n    )",
    "docstring": "Game Action Modes."
  },
  {
    "code": "def get_color(index):\n    if index in range(0, 8):\n        state['turtle'].goto(-WCB_WIDTH / 2, -WCB_HEIGHT / 2)\n        _make_cnc_request(\"tool.color./\" + str(index))\n        colors = [\"black\", \"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"purple\", \"brown\"]\n        state['turtle'].color(colors[index])\n        state['distance_traveled'] = 0\n    else:\n        print(\"Color indexes must be between 0 and 7, but you gave me: \" + index)",
    "docstring": "Dips the brush in paint.\n\n    Arguments:\n        index - an integer between 0 and 7, inclusive. Tells the bot which color you want."
  },
  {
    "code": "def plotGene(self):\n\t\tpl.plot(self.x, self.y, '.')\n\t\tpl.grid(True)\n\t\tpl.show()",
    "docstring": "Plot the gene"
  },
  {
    "code": "def send_packed_virtual_touch_event(xpos, ypos, phase, device_id, finger):\n    message = create(protobuf.SEND_PACKED_VIRTUAL_TOUCH_EVENT_MESSAGE)\n    event = message.inner()\n    event.data = xpos.to_bytes(2, byteorder='little')\n    event.data += ypos.to_bytes(2, byteorder='little')\n    event.data += phase.to_bytes(2, byteorder='little')\n    event.data += device_id.to_bytes(2, byteorder='little')\n    event.data += finger.to_bytes(2, byteorder='little')\n    return message",
    "docstring": "Create a new WAKE_DEVICE_MESSAGE."
  },
  {
    "code": "def purge_collection(keys):\n    \"Recursive purge of nodes with name and id\"\n    for key in keys:\n        m = re.match(r'(.*) \\((\\d+)\\)', key)\n        name = m.group(1)\n        node_id = m.group(2)\n        value = render_value_for_node(node_id)\n        print 'remove node with name:{0} and id:{1}'.format(name, node_id)\n        delete_node(node_id=node_id)\n        if isinstance(value, dict):\n            purge_collection(value.keys())",
    "docstring": "Recursive purge of nodes with name and id"
  },
  {
    "code": "def all(cls, path=''):\n        url = urljoin(cls._meta.base_url, path)\n        pq_items = cls._get_items(url=url, **cls._meta._pyquery_kwargs)\n        return [cls(item=i) for i in pq_items.items()]",
    "docstring": "Return all ocurrences of the item."
  },
  {
    "code": "def douglas_rachford_pd_stepsize(L, tau=None, sigma=None):\n    r\n    if tau is None and sigma is None:\n        L_norms = _operator_norms(L)\n        tau = 1 / sum(L_norms)\n        sigma = [2.0 / (len(L_norms) * tau * Li_norm ** 2)\n                 for Li_norm in L_norms]\n        return tau, tuple(sigma)\n    elif tau is None:\n        L_norms = _operator_norms(L)\n        tau = 2 / sum(si * Li_norm ** 2\n                      for si, Li_norm in zip(sigma, L_norms))\n        return tau, tuple(sigma)\n    elif sigma is None:\n        L_norms = _operator_norms(L)\n        tau = float(tau)\n        sigma = [2.0 / (len(L_norms) * tau * Li_norm ** 2)\n                 for Li_norm in L_norms]\n        return tau, tuple(sigma)\n    else:\n        return float(tau), tuple(sigma)",
    "docstring": "r\"\"\"Default step sizes for `douglas_rachford_pd`.\n\n    Parameters\n    ----------\n    L : sequence of `Operator` or float\n        The operators or the norms of the operators that are used in the\n        `douglas_rachford_pd` method. For `Operator` entries, the norm\n        is computed with ``Operator.norm(estimate=True)``.\n    tau : positive float, optional\n        Use this value for ``tau`` instead of computing it from the\n        operator norms, see Notes.\n    sigma : tuple of float, optional\n        The ``sigma`` step size parameters for the dual update.\n\n    Returns\n    -------\n    tau : float\n        The ``tau`` step size parameter for the primal update.\n    sigma : tuple of float\n        The ``sigma`` step size parameters for the dual update.\n\n    Notes\n    -----\n    To guarantee convergence, the parameters :math:`\\tau`, :math:`\\sigma_i`\n    and :math:`L_i` need to satisfy\n\n    .. math::\n       \\tau \\sum_{i=1}^n \\sigma_i \\|L_i\\|^2 < 4.\n\n    This function has 4 options, :math:`\\tau`/:math:`\\sigma` given or not\n    given.\n\n    - If neither :math:`\\tau` nor :math:`\\sigma` are given, they are chosen as:\n\n        .. math::\n            \\tau = \\frac{1}{\\sum_{i=1}^n \\|L_i\\|},\n            \\quad\n            \\sigma_i = \\frac{2}{n \\tau \\|L_i\\|^2}\n\n    - If only :math:`\\sigma` is given, :math:`\\tau` is set to:\n\n        .. math::\n            \\tau = \\frac{2}{\\sum_{i=1}^n \\sigma_i \\|L_i\\|^2}\n\n    - If only :math:`\\tau` is given, :math:`\\sigma` is set\n      to:\n\n        .. math::\n            \\sigma_i = \\frac{2}{n \\tau \\|L_i\\|^2}\n\n    - If both are given, they are returned as-is without further validation."
  },
  {
    "code": "def _handle_sub_action(self, input_dict, handler):\n        if not self.can_handle(input_dict):\n            return input_dict\n        key = self.intrinsic_name\n        sub_value = input_dict[key]\n        input_dict[key] = self._handle_sub_value(sub_value, handler)\n        return input_dict",
    "docstring": "Handles resolving replacements in the Sub action based on the handler that is passed as an input.\n\n        :param input_dict: Dictionary to be resolved\n        :param supported_values: One of several different objects that contain the supported values that\n            need to be changed. See each method above for specifics on these objects.\n        :param handler: handler that is specific to each implementation.\n        :return: Resolved value of the Sub dictionary"
  },
  {
    "code": "def call(cmd,\n         timeout=None,\n         signum=signal.SIGKILL,\n         keep_rc=False,\n         encoding=\"utf-8\",\n         env=os.environ):\n    if not isinstance(cmd, list):\n        cmd = [cmd]\n    p = Pipeline(*cmd, timeout=timeout, signum=signum, env=env)\n    res = p(keep_rc=keep_rc)\n    if keep_rc:\n        rc, output = res\n        output = output.decode(encoding, 'ignore')\n        return rc, output\n    return res.decode(encoding, \"ignore\")",
    "docstring": "Execute a cmd or list of commands with an optional timeout in seconds.\n\n    If `timeout` is supplied and expires, the process is killed with\n    SIGKILL (kill -9) and an exception is raised. Otherwise, the command\n    output is returned.\n\n    Parameters\n    ----------\n    cmd: str or [[str]]\n        The command(s) to execute\n    timeout: int\n        Seconds before kill is issued to the process\n    signum: int\n        The signal number to issue to the process on timeout\n    keep_rc: bool\n        Whether to return the exit code along with the output\n    encoding: str\n        unicode decoding scheme to use. Default is \"utf-8\"\n    env: dict\n        The environment in which to execute commands. Default is os.environ\n\n    Returns\n    -------\n    str\n        Content of stdout of cmd on success.\n\n    Raises\n    ------\n        CalledProcessError\n            Raised when cmd fails"
  },
  {
    "code": "def get_model(self):\n        class Model(object):\n            def __init__(self, cnn):\n                self.cnn = cnn\n        return Model(self.__cnn)",
    "docstring": "`object` of model as a function approximator,\n        which has `cnn` whose type is \n        `pydbm.cnn.pydbm.cnn.convolutional_neural_network.ConvolutionalNeuralNetwork`."
  },
  {
    "code": "def setItemPolicy(self, item, policy):\n        index = item._combobox_indices[self.ColAction].get(policy, 0)\n        self._updateItemComboBoxIndex(item, self.ColAction, index)\n        combobox = self.itemWidget(item, self.ColAction)\n        if combobox:\n            combobox.setCurrentIndex(index)",
    "docstring": "Sets the policy of the given item"
  },
  {
    "code": "def diagonalize(operator):\n    eig_values, eig_vecs = LA.eigh(operator)\n    emin = np.amin(eig_values)\n    eig_values -= emin\n    return eig_values, eig_vecs",
    "docstring": "diagonalizes single site Spin Hamiltonian"
  },
  {
    "code": "def to_iso_string(self) -> str:\n        assert isinstance(self.value, datetime)\n        return datetime.isoformat(self.value)",
    "docstring": "Returns full ISO string for the given date"
  },
  {
    "code": "def authenticate(self, code: str) -> 'Preston':\n        headers = self._get_authorization_headers()\n        data = {\n            'grant_type': 'authorization_code',\n            'code': code\n        }\n        r = self.session.post(self.TOKEN_URL, headers=headers, data=data)\n        if not r.status_code == 200:\n            raise Exception(f'Could not authenticate, got repsonse code {r.status_code}')\n        new_kwargs = dict(self._kwargs)\n        response_data = r.json()\n        new_kwargs['access_token'] = response_data['access_token']\n        new_kwargs['access_expiration'] = time.time() + float(response_data['expires_in'])\n        new_kwargs['refresh_token'] = response_data['refresh_token']\n        return Preston(**new_kwargs)",
    "docstring": "Authenticates using the code from the EVE SSO.\n\n        A new Preston object is returned; this object is not modified.\n\n        The intended usage is:\n\n            auth = preston.authenticate('some_code_here')\n\n        Args:\n            code: SSO code\n\n        Returns:\n            new Preston, authenticated"
  },
  {
    "code": "def glob_by_extensions(directory, extensions):\n    directorycheck(directory)\n    files = []\n    xt = files.extend\n    for ex in extensions:\n        xt(glob.glob('{0}/*.{1}'.format(directory, ex)))\n    return files",
    "docstring": "Returns files matched by all extensions in the extensions list"
  },
  {
    "code": "def b58enc(uid):\n    if not isinstance(uid, int):\n        raise ValueError('Invalid integer: {}'.format(uid))\n    if uid == 0:\n        return BASE58CHARS[0]\n    enc_uid = \"\"\n    while uid:\n        uid, r = divmod(uid, 58)\n        enc_uid = BASE58CHARS[r] + enc_uid\n    return enc_uid",
    "docstring": "Encodes a UID to an 11-length string, encoded using base58 url-safe alphabet"
  },
  {
    "code": "def mark(self, partition, offset):\n        max_offset = max(offset + 1, self.high_water_mark.get(partition, 0))\n        self.logger.debug(\"Setting high-water mark to: %s\",\n                          {partition: max_offset})\n        self.high_water_mark[partition] = max_offset",
    "docstring": "Set the high-water mark in the current context.\n\n        In order to know the current partition, it is helpful to initialize\n        the consumer to provide partition info via:\n\n        .. code:: python\n\n            consumer.provide_partition_info()"
  },
  {
    "code": "def error(cls, name, message, *args):\n        cls.getLogger(name).error(message, *args)",
    "docstring": "Convenience function to log a message at the ERROR level.\n\n        :param name:    The name of the logger instance in the VSG namespace (VSG.<name>)\n        :param message: A message format string.\n        :param args:    The arguments that are are merged into msg using the string formatting operator.\n        :..note:        The native logger's `kwargs` are not used in this function."
  },
  {
    "code": "def sanity_check_wirevector(self, w):\n        from .wire import WireVector\n        if not isinstance(w, WireVector):\n            raise PyrtlError(\n                'error attempting to pass an input of type \"%s\" '\n                'instead of WireVector' % type(w))",
    "docstring": "Check that w is a valid wirevector type."
  },
  {
    "code": "def columns_used(self):\n        return list(tz.unique(tz.concatv(\n            util.columns_in_filters(self.fit_filters),\n            util.columns_in_filters(self.predict_filters),\n            util.columns_in_formula(self.default_model_expr),\n            self._group.columns_used(),\n            [self.segmentation_col])))",
    "docstring": "Returns all the columns used across all models in the group\n        for filtering and in the model expression."
  },
  {
    "code": "def load_decorate(package):\n    from acorn.logging.decoration import set_decorating, decorating\n    origdecor = decorating\n    set_decorating(True)\n    import sys    \n    from importlib import import_module\n    apack = import_module(package)    \n    from acorn.logging.decoration import decorate\n    decorate(apack)\n    sys.modules[\"acorn.{}\".format(package)] = apack\n    from acorn.logging.decoration import set_decorating\n    set_decorating(origdecor)\n    return apack",
    "docstring": "Imports and decorates the package with the specified name."
  },
  {
    "code": "def _ParseTypeCheckString(type_check_string, stack_location, self_name):\n  target_frame = inspect.stack()[stack_location][0]\n  self_name = self_name or inspect.stack()[stack_location][3]\n  eval_globals = target_frame.f_globals\n  eval_locals = {self_name: Typename[self_name]}\n  try:\n    return eval(type_check_string, eval_globals, eval_locals)\n  except:\n    print \"Exception while parsing\", type_check_string\n    raise",
    "docstring": "Convert string version of a type_check into a python instance.\n\n  Type checks can be either defined directly in python code or in a string.\n  The syntax is exactly the same since we use eval to parse the string.\n\n  :param int stack_location: For eval to get the right globals() scope,\n    we require a stack_location to tell us the index in inspect.stack to\n    where the string was defined.\n  :param str self_name: Optional name of the class itself, which can be used\n    to type check for an instance of a class you are currently defining, and\n    thus would not be available in the globals namespace. If none, it will\n    be quessed from the stack."
  },
  {
    "code": "def vcas2mach(cas, h):\n    tas = vcas2tas(cas, h)\n    M   = vtas2mach(tas, h)\n    return M",
    "docstring": "CAS to Mach conversion"
  },
  {
    "code": "def info_post(node_id):\n    contents = request_parameter(parameter=\"contents\")\n    info_type = request_parameter(\n        parameter=\"info_type\", parameter_type=\"known_class\", default=models.Info\n    )\n    for x in [contents, info_type]:\n        if type(x) == Response:\n            return x\n    node = models.Node.query.get(node_id)\n    if node is None:\n        return error_response(error_type=\"/info POST, node does not exist\")\n    exp = Experiment(session)\n    try:\n        info = info_type(origin=node, contents=contents)\n        assign_properties(info)\n        exp.info_post_request(node=node, info=info)\n        session.commit()\n    except Exception:\n        return error_response(\n            error_type=\"/info POST server error\",\n            status=403,\n            participant=node.participant,\n        )\n    return success_response(info=info.__json__())",
    "docstring": "Create an info.\n\n    The node id must be specified in the url.\n\n    You must pass contents as an argument.\n    info_type is an additional optional argument.\n    If info_type is a custom subclass of Info it must be\n    added to the known_classes of the experiment class."
  },
  {
    "code": "def value(self):\n        user = self.trigger.agentml.request_log.most_recent().user\n        groups = self.trigger.agentml.request_log.most_recent().groups\n        if len(self._element):\n            message = ''.join(map(str, self.trigger.agentml.parse_tags(self._element, self.trigger)))\n        else:\n            message = self._element.text\n        default = attribute(self._element, 'default', '')\n        response = self.trigger.agentml.get_reply(user.id, message, groups)\n        return response or default",
    "docstring": "Return the value of the redirect response"
  },
  {
    "code": "def update_hash(src_file):\n    hash_file = local.path(src_file) + \".hash\"\n    new_hash = 0\n    with open(hash_file, 'w') as h_file:\n        new_hash = get_hash_of_dirs(src_file)\n        h_file.write(str(new_hash))\n    return new_hash",
    "docstring": "Update the hash for the given file.\n\n    Args:\n        src: The file name.\n        root: The path of the given file."
  },
  {
    "code": "def extract_program_summary(data):\n    from bs4 import BeautifulSoup\n    soup = BeautifulSoup(data, 'html.parser')\n    try:\n        return soup.find(\n            'div', {'class': 'episode-synopsis'}\n        ).find_all('div')[-1].text.strip()\n    except Exception:\n        _LOGGER.info('No summary found for program: %s',\n                     soup.find('a', {'class': 'prog_name'}))\n        return \"No summary\"",
    "docstring": "Extract the summary data from a program's detail page"
  },
  {
    "code": "def boolean_rows(a, b, operation=np.intersect1d):\n    a = np.asanyarray(a, dtype=np.int64)\n    b = np.asanyarray(b, dtype=np.int64)\n    av = a.view([('', a.dtype)] * a.shape[1]).ravel()\n    bv = b.view([('', b.dtype)] * b.shape[1]).ravel()\n    shared = operation(av, bv).view(a.dtype).reshape(-1, a.shape[1])\n    return shared",
    "docstring": "Find the rows in two arrays which occur in both rows.\n\n    Parameters\n    ---------\n    a: (n, d) int\n        Array with row vectors\n    b: (m, d) int\n        Array with row vectors\n    operation : function\n        Numpy boolean set operation function:\n          -np.intersect1d\n          -np.setdiff1d\n\n    Returns\n    --------\n    shared: (p, d) array containing rows in both a and b"
  },
  {
    "code": "def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0):\n    assert isinstance(P, list)\n    assert len(P) > 0\n    for p in P:\n        assert isinstance(p, tuple)\n        for i in p:\n            assert len(p) > 1\n            assert isinstance(i, float)\n    assert isinstance(n_seg, int)\n    assert n_seg >= 0\n    return [pt_on_bezier_curve(P, float(i)/n_seg) for i in range(n_seg)] + [P[-1]]",
    "docstring": "Return list N+1 points representing N line segments on bezier curve\n  defined by control points P."
  },
  {
    "code": "def get_pore_surface_parameters(surface_area):\n    PoreSurfaceParameters = DataFactory('phtools.surface')\n    d = {\n        'accessible_surface_area': surface_area.get_dict()['ASA_A^2'],\n        'target_volume': 40e3,\n        'sampling_method': 'random',\n    }\n    return PoreSurfaceParameters(dict=d)",
    "docstring": "Get input parameters for pore surface binary.\n\n    Get input parameters for pore_surface binary from zeo++ output,\n    while keeping data provenance."
  },
  {
    "code": "def get_disk_usage(path):\n    cmd = 'du -sh --block-size=1 {0}'.format(path)\n    total = getoutput(cmd).split()[0]\n    return int(total)",
    "docstring": "Returns the allocated disk space for the given path in bytes.\n\n    :param path: String representing the path as it would be given to the `du`\n      command. Best to give an absolute path here."
  },
  {
    "code": "def _filter_settings(settings, prefix):\n    ret = {}\n    for skey in settings.keys():\n        if skey.startswith(prefix):\n            key = skey[len(prefix):]\n            ret[key] = settings[skey]\n    return ret",
    "docstring": "Filter all settings to only return settings that start with a certain\n    prefix.\n\n    :param dict settings: A settings dictionary.\n    :param str prefix: A prefix."
  },
  {
    "code": "def get_screen_size(self, screen_no):\n    return GetScreenSize(display=self.display,\n                         opcode=self.display.get_extension_major(extname),\n                         window=self.id,\n                         screen=screen_no,\n                         )",
    "docstring": "Returns the size of the given screen number"
  },
  {
    "code": "def import_private_key(self, pem_text, password=None):\n\t\tif isinstance(pem_text, str) is True:\n\t\t\tpem_text = pem_text.encode()\n\t\tif password is not None and isinstance(password, str) is True:\n\t\t\tpassword = password.encode()\n\t\tself.__set_private_key(\n\t\t\tserialization.load_pem_private_key(pem_text, password=password, backend=default_backend())\n\t\t)",
    "docstring": "Import a private key from data in PEM-format\n\n\t\t:param pem_text: text with private key\n\t\t:param password: If it is not None, then result will be decrypt with the given password\n\t\t:return: None"
  },
  {
    "code": "def create_node_group(self):\n        self.create_stack(\n            self.node_group_name,\n            'amazon-eks-nodegroup.yaml',\n            capabilities=['CAPABILITY_IAM'],\n            parameters=define_parameters(\n                ClusterName=self.cluster_name,\n                ClusterControlPlaneSecurityGroup=self.security_groups,\n                Subnets=self.subnet_ids,\n                VpcId=self.vpc_ids,\n                KeyName=self.ssh_key_name,\n                NodeAutoScalingGroupMaxSize=\"1\",\n                NodeVolumeSize=\"100\",\n                NodeImageId=\"ami-0a54c984b9f908c81\",\n                NodeGroupName=f\"{self.name} OnDemand Nodes\"\n            )\n        )",
    "docstring": "Create on-demand node group on Amazon EKS."
  },
  {
    "code": "def reverse_url(self, scheme: str, path: str) -> str:\n        path = path.lstrip('/')\n        server, port = self.connection_handler.server, self.connection_handler.port\n        if self.connection_handler.path:\n            url = '{scheme}://{server}:{port}/{path}'.format(scheme=scheme,\n                                                             server=server,\n                                                             port=port,\n                                                             path=path)\n        else:\n            url = '{scheme}://{server}:{port}/'.format(scheme=scheme,\n                                                       server=server,\n                                                       port=port)\n        return url + path",
    "docstring": "Reverses the url using scheme and path given in parameter.\n\n        :param scheme: Scheme of the url\n        :param path: Path of the url\n        :return:"
  },
  {
    "code": "def daOnes(shap, dtype=numpy.float):\n    res = DistArray(shap, dtype)\n    res[:] = 1\n    return res",
    "docstring": "One constructor for numpy distributed array\n    @param shap the shape of the array\n    @param dtype the numpy data type"
  },
  {
    "code": "def get_y(self, var, coords=None):\n        coords = coords or self.ds.coords\n        coord = self.get_variable_by_axis(var, 'y', coords)\n        if coord is not None:\n            return coord\n        return coords.get(self.get_yname(var))",
    "docstring": "Get the y-coordinate of a variable\n\n        This method searches for the y-coordinate in the :attr:`ds`. It first\n        checks whether there is one dimension that holds an ``'axis'``\n        attribute with 'Y', otherwise it looks whether there is an intersection\n        between the :attr:`y` attribute and the variables dimensions, otherwise\n        it returns the coordinate corresponding to the second last dimension of\n        `var` (or the last if the dimension of var is one-dimensional)\n\n        Possible types\n        --------------\n        var: xarray.Variable\n            The variable to get the y-coordinate for\n        coords: dict\n            Coordinates to use. If None, the coordinates of the dataset in the\n            :attr:`ds` attribute are used.\n\n        Returns\n        -------\n        xarray.Coordinate or None\n            The y-coordinate or None if it could be found"
  },
  {
    "code": "def image_groups_list(self, api_url=None, offset=0, limit=-1, properties=None):\n        return sco.get_resource_listing(\n            self.get_api_references(api_url)[sco.REF_IMAGE_GROUPS_LIST],\n            offset,\n            limit,\n            properties\n        )",
    "docstring": "Get list of image group resources from a SCO-API.\n\n        Parameters\n        ----------\n        api_url : string, optional\n            Base Url of the SCO-API. Uses default API if argument not present.\n        offset : int, optional\n            Starting offset for returned list items\n        limit : int, optional\n            Limit the number of items in the result\n        properties : List(string)\n            List of additional object properties to be included for items in\n            the result\n\n        Returns\n        -------\n        List(scoserv.ResourceHandle)\n            List of resource handles (one per image group in the listing)"
  },
  {
    "code": "def _servicegroup_get_server(sg_name, s_name, s_port=None, **connection_args):\n    ret = None\n    servers = _servicegroup_get_servers(sg_name, **connection_args)\n    if servers is None:\n        return None\n    for server in servers:\n        if server.get_servername() == s_name:\n            if s_port is not None and s_port != server.get_port():\n                ret = None\n            ret = server\n    return ret",
    "docstring": "Returns a member of a service group or None"
  },
  {
    "code": "def _call_handler(self, key, insert_text):\n        if isinstance(key, tuple):\n            for k in key:\n                self._call_handler(k, insert_text)\n        else:\n            if key == Keys.BracketedPaste:\n                self._in_bracketed_paste = True\n                self._paste_buffer = ''\n            else:\n                self.feed_key_callback(KeyPress(key, insert_text))",
    "docstring": "Callback to handler."
  },
  {
    "code": "def coerce_to_list(items, preprocess=None):\n    if not isinstance(items, list):\n        items = [items]\n    if preprocess:\n        items = list(map(preprocess, items))\n    return items",
    "docstring": "Given an instance or list, coerce to list.\n\n    With optional preprocessing."
  },
  {
    "code": "def get_weights(model_hparams, vocab_size, hidden_dim=None):\n  if hidden_dim is None:\n    hidden_dim = model_hparams.hidden_size\n  num_shards = model_hparams.symbol_modality_num_shards\n  shards = []\n  for i in range(num_shards):\n    shard_size = (vocab_size // num_shards) + (\n        1 if i < vocab_size % num_shards else 0)\n    var_name = \"weights_%d\" % i\n    shards.append(\n        tf.get_variable(\n            var_name, [shard_size, hidden_dim],\n            initializer=tf.random_normal_initializer(0.0, hidden_dim**-0.5)))\n  if num_shards == 1:\n    ret = shards[0]\n  else:\n    ret = tf.concat(shards, 0)\n  if not tf.executing_eagerly():\n    ret = common_layers.convert_gradient_to_tensor(ret)\n  return ret",
    "docstring": "Create or get concatenated embedding or softmax variable.\n\n  Args:\n    model_hparams: HParams, model hyperparmeters.\n    vocab_size: int, vocabulary size.\n    hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size\n\n  Returns:\n     a list of num_shards Tensors."
  },
  {
    "code": "def broadcast_info(team_id, date=datetime.now()):\n    year = date.year\n    game_date = date.strftime('%Y-%m-%dT00:00:00')\n    data = mlbgame.data.get_broadcast_info(team_id, year)\n    schedule = json.loads(data.read().decode('utf-8'))\n    schedule = schedule['mlb_broadcast_info']['queryResults']['row']\n    return [g for g in schedule if g['game_date'] == game_date]",
    "docstring": "Returns a dictionary of broadcast information\n    for a given team during a given season"
  },
  {
    "code": "def decode_body(cls, header, f):\n        assert header.packet_type == MqttControlPacketType.pingresp\n        if header.remaining_len != 0:\n            raise DecodeError('Extra bytes at end of packet.')\n        return 0, MqttPingresp()",
    "docstring": "Generates a `MqttPingresp` packet given a\n        `MqttFixedHeader`.  This method asserts that header.packet_type\n        is `pingresp`.\n\n        Parameters\n        ----------\n        header: MqttFixedHeader\n        f: file\n            Object with a read method.\n\n        Raises\n        ------\n        DecodeError\n            When there are extra bytes at the end of the packet.\n\n        Returns\n        -------\n        int\n            Number of bytes consumed from ``f``.\n        MqttPingresp\n            Object extracted from ``f``."
  },
  {
    "code": "def start_depth_socket(self, symbol, callback, depth=None):\n        socket_name = symbol.lower() + '@depth'\n        if depth and depth != '1':\n            socket_name = '{}{}'.format(socket_name, depth)\n        return self._start_socket(socket_name, callback)",
    "docstring": "Start a websocket for symbol market depth returning either a diff or a partial book\n\n        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#partial-book-depth-streams\n\n        :param symbol: required\n        :type symbol: str\n        :param callback: callback function to handle messages\n        :type callback: function\n        :param depth: optional Number of depth entries to return, default None. If passed returns a partial book instead of a diff\n        :type depth: str\n\n        :returns: connection key string if successful, False otherwise\n\n        Partial Message Format\n\n        .. code-block:: python\n\n            {\n                \"lastUpdateId\": 160,  # Last update ID\n                \"bids\": [             # Bids to be updated\n                    [\n                        \"0.0024\",     # price level to be updated\n                        \"10\",         # quantity\n                        []            # ignore\n                    ]\n                ],\n                \"asks\": [             # Asks to be updated\n                    [\n                        \"0.0026\",     # price level to be updated\n                        \"100\",        # quantity\n                        []            # ignore\n                    ]\n                ]\n            }\n\n\n        Diff Message Format\n\n        .. code-block:: python\n\n            {\n                \"e\": \"depthUpdate\", # Event type\n                \"E\": 123456789,     # Event time\n                \"s\": \"BNBBTC\",      # Symbol\n                \"U\": 157,           # First update ID in event\n                \"u\": 160,           # Final update ID in event\n                \"b\": [              # Bids to be updated\n                    [\n                        \"0.0024\",   # price level to be updated\n                        \"10\",       # quantity\n                        []          # ignore\n                    ]\n                ],\n                \"a\": [              # Asks to be updated\n                    [\n                        \"0.0026\",   # price level to be updated\n                        \"100\",      # quantity\n                        []          # ignore\n                    ]\n                ]\n            }"
  },
  {
    "code": "def indentLine(self, block, autoIndent):\n        indent = None\n        if indent is None:\n            indent = self.tryMatchedAnchor(block, autoIndent)\n        if indent is None:\n            indent = self.tryCComment(block)\n        if indent is None and not autoIndent:\n            indent = self.tryCppComment(block)\n        if indent is None:\n            indent = self.trySwitchStatement(block)\n        if indent is None:\n            indent = self.tryAccessModifiers(block)\n        if indent is None:\n            indent = self.tryBrace(block)\n        if indent is None:\n            indent = self.tryCKeywords(block, block.text().lstrip().startswith('{'))\n        if indent is None:\n            indent = self.tryCondition(block)\n        if indent is None:\n            indent = self.tryStatement(block)\n        if indent is not None:\n            return indent\n        else:\n            dbg(\"Nothing matched\")\n            return self._prevNonEmptyBlockIndent(block)",
    "docstring": "Indent line.\n        Return filler or null."
  },
  {
    "code": "def users_list(self, *args):\n        if len(self._users) == 0:\n            self.log('No users connected')\n        else:\n            self.log(self._users, pretty=True)",
    "docstring": "Display a list of connected users"
  },
  {
    "code": "def stop(self, key):\n        self._get_limiter(key).stop()\n        self._cleanup_limiter(key)",
    "docstring": "Stop a concurrent operation.\n\n        This gets the concurrency limiter for the given key (creating it if\n        necessary) and stops a concurrent operation on it. If the concurrency\n        limiter is empty, it is deleted."
  },
  {
    "code": "def addNode(self, node):\n        LOGGER.info('Adding node {}({})'.format(node.name, node.address))\n        message = {\n            'addnode': {\n                'nodes': [{\n                    'address': node.address,\n                    'name': node.name,\n                    'node_def_id': node.id,\n                    'primary': node.primary,\n                    'drivers': node.drivers,\n                    'hint': node.hint\n                }]\n            }\n        }\n        self.send(message)",
    "docstring": "Add a node to the NodeServer\n\n        :param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required."
  },
  {
    "code": "def rowgroupmap(table, key, mapper, header=None, presorted=False,\n                buffersize=None, tempdir=None, cache=True):\n    return RowGroupMapView(table, key, mapper, header=header,\n                           presorted=presorted,\n                           buffersize=buffersize, tempdir=tempdir, cache=cache)",
    "docstring": "Group rows under the given key then apply `mapper` to yield zero or more\n    output rows for each input group of rows."
  },
  {
    "code": "def use_partial_data(self, sample_pct:float=0.01, seed:int=None)->'ItemList':\n        \"Use only a sample of `sample_pct`of the full dataset and an optional `seed`.\"\n        if seed is not None: np.random.seed(seed)\n        rand_idx = np.random.permutation(range_of(self))\n        cut = int(sample_pct * len(self))\n        return self[rand_idx[:cut]]",
    "docstring": "Use only a sample of `sample_pct`of the full dataset and an optional `seed`."
  },
  {
    "code": "def get_git_postversion(addon_dir):\n    addon_dir = os.path.realpath(addon_dir)\n    last_version = read_manifest(addon_dir).get('version', '0.0.0')\n    last_version_parsed = parse_version(last_version)\n    if not is_git_controlled(addon_dir):\n        return last_version\n    if get_git_uncommitted(addon_dir):\n        uncommitted = True\n        count = 1\n    else:\n        uncommitted = False\n        count = 0\n    last_sha = None\n    git_root = get_git_root(addon_dir)\n    for sha in git_log_iterator(addon_dir):\n        try:\n            manifest = read_manifest_from_sha(sha, addon_dir, git_root)\n        except NoManifestFound:\n            break\n        version = manifest.get('version', '0.0.0')\n        version_parsed = parse_version(version)\n        if version_parsed != last_version_parsed:\n            break\n        if last_sha is None:\n            last_sha = sha\n        else:\n            count += 1\n    if not count:\n        return last_version\n    if last_sha:\n        return last_version + \".99.dev%s\" % count\n    if uncommitted:\n        return last_version + \".dev1\"\n    return last_version",
    "docstring": "return the addon version number, with a developmental version increment\n    if there were git commits in the addon_dir after the last version change.\n\n    If the last change to the addon correspond to the version number in the\n    manifest it is used as is for the python package version. Otherwise a\n    counter is incremented for each commit and resulting version number has\n    the following form: [8|9].0.x.y.z.1devN, N being the number of git\n    commits since the version change.\n\n    Note: we use .99.devN because:\n    * pip ignores .postN  by design (https://github.com/pypa/pip/issues/2872)\n    * x.y.z.devN is anterior to x.y.z\n\n    Note: we don't put the sha1 of the commit in the version number because\n    this is not PEP 440 compliant and is therefore misinterpreted by pip."
  },
  {
    "code": "def merge_sims(oldsims, newsims, clip=None):\n    if oldsims is None:\n        result = newsims or []\n    elif newsims is None:\n        result = oldsims\n    else:\n        result = sorted(oldsims + newsims, key=lambda item: -item[1])\n    if clip is not None:\n        result = result[:clip]\n    return result",
    "docstring": "Merge two precomputed similarity lists, truncating the result to `clip` most similar items."
  },
  {
    "code": "def call_template_str(self, template):\n        high = compile_template_str(template,\n                                    self.rend,\n                                    self.opts['renderer'],\n                                    self.opts['renderer_blacklist'],\n                                    self.opts['renderer_whitelist'])\n        if not high:\n            return high\n        high, errors = self.render_template(high, '<template-str>')\n        if errors:\n            return errors\n        return self.call_high(high)",
    "docstring": "Enforce the states in a template, pass the template as a string"
  },
  {
    "code": "def apply(self, config, raise_on_unknown_key=True):\n        _recursive_merge(self._data, config, raise_on_unknown_key)",
    "docstring": "Apply additional configuration from a dictionary\n\n        This will look for dictionary items that exist in the base_config any apply their values on the current\n        configuration object"
  },
  {
    "code": "def event_list_tabs(counts, current_kind, page_number=1):\n    return {\n            'counts': counts,\n            'current_kind': current_kind,\n            'page_number': page_number,\n            'event_kinds': Event.get_kinds(),\n            'event_kinds_data': Event.get_kinds_data(),\n        }",
    "docstring": "Displays the tabs to different event_list pages.\n\n    `counts` is a dict of number of events for each kind, like:\n        {'all': 30, 'gig': 12, 'movie': 18,}\n\n    `current_kind` is the event kind that's active, if any. e.g. 'gig',\n        'movie', etc.\n\n    `page_number` is the current page of this kind of events we're on."
  },
  {
    "code": "def generate(env):\n    global PDFAction\n    if PDFAction is None:\n        PDFAction = SCons.Action.Action('$DVIPDFCOM', '$DVIPDFCOMSTR')\n    global DVIPDFAction\n    if DVIPDFAction is None:\n        DVIPDFAction = SCons.Action.Action(DviPdfFunction, strfunction = DviPdfStrFunction)\n    from . import pdf\n    pdf.generate(env)\n    bld = env['BUILDERS']['PDF']\n    bld.add_action('.dvi', DVIPDFAction)\n    bld.add_emitter('.dvi', PDFEmitter)\n    env['DVIPDF']      = 'dvipdf'\n    env['DVIPDFFLAGS'] = SCons.Util.CLVar('')\n    env['DVIPDFCOM']   = 'cd ${TARGET.dir} && $DVIPDF $DVIPDFFLAGS ${SOURCE.file} ${TARGET.file}'\n    env['PDFCOM']      = ['$DVIPDFCOM']",
    "docstring": "Add Builders and construction variables for dvipdf to an Environment."
  },
  {
    "code": "def regroup(self, group_by=None):\n        if not group_by:\n            group_by = self.group_by\n        groups = self.groups\n        self.groups = {}\n        for g in groups:\n            for item in groups[g]:\n                self.add(item, group_by)",
    "docstring": "Regroup items."
  },
  {
    "code": "def direct_horizontal_irradiance(self):\n        analysis_period = AnalysisPeriod(timestep=self.timestep,\n                                         is_leap_year=self.is_leap_year)\n        header_dhr = Header(data_type=DirectHorizontalIrradiance(),\n                            unit='W/m2',\n                            analysis_period=analysis_period,\n                            metadata=self.metadata)\n        direct_horiz = []\n        sp = Sunpath.from_location(self.location)\n        sp.is_leap_year = self.is_leap_year\n        for dt, dnr in zip(self.datetimes, self.direct_normal_irradiance):\n            sun = sp.calculate_sun_from_date_time(dt)\n            direct_horiz.append(dnr * math.sin(math.radians(sun.altitude)))\n        return HourlyContinuousCollection(header_dhr, direct_horiz)",
    "docstring": "Returns the direct irradiance on a horizontal surface at each timestep.\n\n        Note that this is different from the direct_normal_irradiance needed\n        to construct a Wea, which is NORMAL and not HORIZONTAL."
  },
  {
    "code": "def _createValueObjects(self, valueList, varList, mapTable, indexMap, contaminant, replaceParamFile):\n        def assign_values_to_table(value_list, layer_id):\n            for i, value in enumerate(value_list):\n                value = vrp(value, replaceParamFile)\n                mtValue = MTValue(variable=varList[i], value=float(value))\n                mtValue.index = mtIndex\n                mtValue.mapTable = mapTable\n                mtValue.layer_id = layer_id\n                if contaminant:\n                    mtValue.contaminant = contaminant\n        for row in valueList:\n            mtIndex = MTIndex(index=row['index'], description1=row['description1'], description2=row['description2'])\n            mtIndex.indexMap = indexMap\n            if len(np.shape(row['values'])) == 2:\n                for layer_id, values in enumerate(row['values']):\n                    assign_values_to_table(values, layer_id)\n            else:\n                assign_values_to_table(row['values'], 0)",
    "docstring": "Populate GSSHAPY MTValue and MTIndex Objects Method"
  },
  {
    "code": "def revoke_user_access( self, access_id ):\n        path = \"/api/v3/publisher/user/access/revoke\"\n        data = {\n            'api_token': self.api_token, \n            'access_id': access_id,\n        }\n        r = requests.get( self.base_url + path, data=data )\n        if r.status_code != 200:\n            raise ValueError( path + \":\" + r.reason )",
    "docstring": "Takes an access_id, probably obtained from the get_access_list structure, and revokes that access.\n            No return value, but may raise ValueError."
  },
  {
    "code": "def _write_subset_index_file(options, core_results):\n    f_path = os.path.join(options['run_dir'], '_subset_index.csv')\n    subset_strs = zip(*core_results)[0]\n    index = np.arange(len(subset_strs)) + 1\n    df = pd.DataFrame({'subsets': subset_strs}, index=index)\n    df.to_csv(f_path)",
    "docstring": "Write table giving index of subsets, giving number and subset string"
  },
  {
    "code": "def manipulate(self, stored_instance, component_instance):\n        self._logger = logging.getLogger(self._name)\n        setattr(component_instance, self._field, self._logger)",
    "docstring": "Called by iPOPO right after the instantiation of the component.\n        This is the last chance to manipulate the component before the other\n        handlers start.\n\n        :param stored_instance: The iPOPO component StoredInstance\n        :param component_instance: The component instance"
  },
  {
    "code": "def initLogging():\n    logging.basicConfig(\n        level=logging.INFO,\n        format='%(asctime)s.%(msecs)03d %(levelname)s %(name)s - %(message)s',\n        datefmt='%H:%M:%S')\n    logging.getLogger('').setLevel(logging.INFO)\n    logging.getLogger('PIL').setLevel(logging.INFO)\n    CONFIG_PATHS = [\n        os.path.curdir,\n        os.path.join(os.path.expanduser('~')),\n        '/etc',\n    ]\n    for p in CONFIG_PATHS:\n        config_file = os.path.join(p, 'ocrd_logging.py')\n        if os.path.exists(config_file):\n            logging.info(\"Loading logging configuration from '%s'\", config_file)\n            with open(config_file) as f:\n                code = compile(f.read(), config_file, 'exec')\n                exec(code, globals(), locals())",
    "docstring": "Sets logging defaults"
  },
  {
    "code": "def best_item_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False):\n    match = best_match_from_list(item,options,fuzzy,fname_match,fuzzy_fragment,guess)\n    if match:\n        return match[0]\n    return None",
    "docstring": "Returns just the best item, or ``None``"
  },
  {
    "code": "def find(self, instance_ids=None, filters=None):\n        instances = []\n        reservations = self.retry_on_ec2_error(self.ec2.get_all_instances, instance_ids=instance_ids, filters=filters)\n        for reservation in reservations:\n            instances.extend(reservation.instances)\n        return instances",
    "docstring": "Flatten list of reservations to a list of instances.\n\n        :param instance_ids: A list of instance ids to filter by\n        :type instance_ids: list\n        :param filters: A dict of Filter.N values defined in http://goo.gl/jYNej9\n        :type filters: dict\n        :return: A flattened list of filtered instances.\n        :rtype: list"
  },
  {
    "code": "def setEntry(self, entry=None):\n        busy = Purr.BusyIndicator()\n        self.entry = entry\n        self.setEntryTitle(entry.title)\n        self.setEntryComment(entry.comment.replace(\"\\n\", \"\\n\\n\").replace(\"<BR>\", \"\\n\"))\n        self.wdplv.clear()\n        self.wdplv.fillDataProducts(entry.dps)\n        self.setTimestamp(entry.timestamp)\n        self.updated = False",
    "docstring": "Populates the dialog with contents of an existing entry."
  },
  {
    "code": "def combine_types(types):\n    items = simplify_types(types)\n    if len(items) == 1:\n        return items[0]\n    else:\n        return UnionType(items)",
    "docstring": "Given some types, return a combined and simplified type.\n\n    For example, if given 'int' and 'List[int]', return Union[int, List[int]]. If given\n    'int' and 'int', return just 'int'."
  },
  {
    "code": "def update_check(self, existing, new):\n        old_state = existing.state\n        if 'NowPlayingItem' in existing.session_raw:\n            try:\n                old_theme = existing.session_raw['NowPlayingItem']['IsThemeMedia']\n            except KeyError:\n                old_theme = False\n        else:\n            old_theme = False\n        if 'NowPlayingItem' in new:\n            if new['PlayState']['IsPaused']:\n                new_state = STATE_PAUSED\n            else:\n                new_state = STATE_PLAYING\n            try:\n                new_theme = new['NowPlayingItem']['IsThemeMedia']\n            except KeyError:\n                new_theme = False\n        else:\n            new_state = STATE_IDLE\n            new_theme = False\n        if old_theme or new_theme:\n            return False\n        elif old_state == STATE_PLAYING or new_state == STATE_PLAYING:\n            return True\n        elif old_state != new_state:\n            return True\n        else:\n            return False",
    "docstring": "Check device state to see if we need to fire the callback.\n\n        True if either state is 'Playing'\n        False if both states are: 'Paused', 'Idle', or 'Off'\n        True on any state transition."
  },
  {
    "code": "def query(\n        self,\n        url: Union[str, methods],\n        data: Optional[MutableMapping] = None,\n        headers: Optional[MutableMapping] = None,\n        as_json: Optional[bool] = None,\n    ) -> dict:\n        url, body, headers = sansio.prepare_request(\n            url=url,\n            data=data,\n            headers=headers,\n            global_headers=self._headers,\n            token=self._token,\n        )\n        return self._make_query(url, body, headers)",
    "docstring": "Query the slack API\n\n        When using :class:`slack.methods` the request is made `as_json` if available\n\n        Args:\n            url: :class:`slack.methods` or url string\n            data: JSON encodable MutableMapping\n            headers: Custom headers\n            as_json: Post JSON to the slack API\n        Returns:\n            dictionary of slack API response data"
  },
  {
    "code": "def off(self):\n        for device in self:\n            if isinstance(device, (OutputDevice, CompositeOutputDevice)):\n                device.off()",
    "docstring": "Turn all the output devices off."
  },
  {
    "code": "def get_option(option_name, section_name=\"main\", default=_sentinel, cfg_file=cfg_file):\n    defaults = get_defaults()\n    if default != _sentinel:\n        my_defaults = {option_name: default}\n    else:\n        my_defaults = defaults.get('section_name', {})\n    parser = get_parser(cfg_file)\n    return parser.get(section_name, option_name, vars=my_defaults)",
    "docstring": "Returns a specific option specific in a config file\n\n    Arguments:\n        option_name  -- Name of the option (example host_name)\n        section_name -- Which section of the config (default: name)\n\n    examples:\n    >>> get_option(\"some option\", default=\"default result\")\n    'default result'"
  },
  {
    "code": "def post(node_name, key, **kwargs):\n    node = nago.core.get_node(node_name)\n    if not node:\n        raise ValueError(\"Node named %s not found\" % node_name)\n    token = node.token\n    node_data[token] = node_data[token] or {}\n    node_data[token][key] = kwargs\n    return \"thanks!\"",
    "docstring": "Give the server information about this node\n\n    Arguments:\n        node -- node_name or token for the node this data belongs to\n        key  -- identifiable key, that you use later to retrieve that piece of data\n        kwargs -- the data you need to store"
  },
  {
    "code": "def appendPoint(self, position=None, type=\"line\", smooth=False, name=None, identifier=None, point=None):\n        if point is not None:\n            if position is None:\n                position = point.position\n            type = point.type\n            smooth = point.smooth\n            if name is None:\n                name = point.name\n            if identifier is not None:\n                identifier = point.identifier\n        self.insertPoint(\n            len(self.points),\n            position=position,\n            type=type,\n            smooth=smooth,\n            name=name,\n            identifier=identifier\n        )",
    "docstring": "Append a point to the contour."
  },
  {
    "code": "def report_saved(report_stats):\n    if Settings.verbose:\n        report = ''\n        truncated_filename = truncate_cwd(report_stats.final_filename)\n        report += '{}: '.format(truncated_filename)\n        total = new_percent_saved(report_stats)\n        if total:\n            report += total\n        else:\n            report += '0%'\n        if Settings.test:\n            report += ' could be saved.'\n        if Settings.verbose > 1:\n            tools_report = ', '.join(report_stats.report_list)\n            if tools_report:\n                report += '\\n\\t' + tools_report\n        print(report)",
    "docstring": "Record the percent saved & print it."
  },
  {
    "code": "def main():\n    try:\n        device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))\n        device.on_rfx_message += handle_rfx\n        with device.open(baudrate=BAUDRATE):\n            while True:\n                time.sleep(1)\n    except Exception as ex:\n        print('Exception:', ex)",
    "docstring": "Example application that watches for an event from a specific RF device.\n\n    This feature allows you to watch for events from RF devices if you have\n    an RF receiver.  This is useful in the case of internal sensors, which\n    don't emit a FAULT if the sensor is tripped and the panel is armed STAY.\n    It also will monitor sensors that aren't configured.\n\n    NOTE: You must have an RF receiver installed and enabled in your panel\n          for RFX messages to be seen."
  },
  {
    "code": "def get_action_handler(self, controller_name, action_name):\n        try_actions = [\n            controller_name + '/' + action_name,\n            controller_name + '/not_found',\n            'index/not_found'\n        ]\n        for path in try_actions:\n            if path in self._controllers:\n                return self._controllers[path]\n        return None",
    "docstring": "Return action of controller as callable.\n\n        If requested controller isn't found - return 'not_found' action\n        of requested controller or Index controller."
  },
  {
    "code": "def get_expected_bindings(self):\n        sg_bindings = db_lib.get_baremetal_sg_bindings()\n        all_expected_bindings = collections.defaultdict(set)\n        for sg_binding, port_binding in sg_bindings:\n            sg_id = sg_binding['security_group_id']\n            try:\n                binding_profile = json.loads(port_binding.profile)\n            except ValueError:\n                binding_profile = {}\n            switchports = self._get_switchports(binding_profile)\n            for switch, intf in switchports:\n                ingress_name = self._acl_name(sg_id, n_const.INGRESS_DIRECTION)\n                egress_name = self._acl_name(sg_id, n_const.EGRESS_DIRECTION)\n                all_expected_bindings[switch].add(\n                    (intf, ingress_name, a_const.INGRESS_DIRECTION))\n                all_expected_bindings[switch].add(\n                    (intf, egress_name, a_const.EGRESS_DIRECTION))\n        return all_expected_bindings",
    "docstring": "Query the neutron DB for SG->switch interface bindings\n\n        Bindings are returned as a dict of bindings for each switch:\n        {<switch1>: set([(intf1, acl_name, direction),\n                         (intf2, acl_name, direction)]),\n         <switch2>: set([(intf1, acl_name, direction)]),\n         ...,\n        }"
  },
  {
    "code": "def buttons(self, master):\n        box = tk.Frame(master)\n        ttk.Button(\n            box,\n            text=\"Next\",\n            width=10,\n            command=self.next_day\n        ).pack(side=tk.LEFT, padx=5, pady=5)\n        ttk.Button(\n            box,\n            text=\"OK\",\n            width=10,\n            command=self.ok,\n            default=tk.ACTIVE\n        ).pack(side=tk.LEFT, padx=5, pady=5)\n        ttk.Button(\n            box,\n            text=\"Cancel\",\n            width=10,\n            command=self.cancel\n        ).pack(side=tk.LEFT, padx=5, pady=5)\n        self.bind(\"n\", self.next_day)\n        self.bind(\"<Return>\", self.ok)\n        self.bind(\"<Escape>\", self.cancel)\n        box.pack()",
    "docstring": "Add a standard button box.\n\n        Override if you do not want the standard buttons"
  },
  {
    "code": "def rm_missing_values_table(d):\n    try:\n        for k, v in d[\"columns\"].items():\n            d[\"columns\"][k] = rm_keys_from_dict(v, [\"missingValue\"])\n    except Exception:\n        pass\n    return d",
    "docstring": "Loop for each table column and remove the missingValue key & data\n\n    :param dict d: Metadata (table)\n    :return dict d: Metadata (table)"
  },
  {
    "code": "def set_name_email(configurator, question, answer):\n    name = configurator.variables['author.name']\n    configurator.variables['author.name_email'] = '\"{0}\" <{1}>'.format(\n        name, answer)\n    return answer",
    "docstring": "prepare \"Full Name\" <email@eg.com>\" string"
  },
  {
    "code": "def register_custom_actions(parser: argparse.ArgumentParser) -> None:\n    parser.register('action', None, _StoreRangeAction)\n    parser.register('action', 'store', _StoreRangeAction)\n    parser.register('action', 'append', _AppendRangeAction)",
    "docstring": "Register custom argument action types"
  },
  {
    "code": "def start_container(self, image, container_name: str, repo_path: Path):\n        command = \"bash -i\"\n        if self.inherit_image:\n            command = \"sh -i\"\n        container = self.client.containers.run(image, command=command, detach=True, tty=True, name=container_name,\n                                               working_dir=str((Path(\"/srv/data\") / self.cwd).resolve()),\n                                               auto_remove=True)\n        container.exec_run([\"mkdir\", \"-p\", \"/srv/scripts\"])\n        container.put_archive(\"/srv\", self.tar_files(repo_path))\n        container.put_archive(\"/srv/scripts\", self.tar_runner())\n        return container",
    "docstring": "Starts a container with the image and name ``container_name`` and copies the repository into the container.\n\n        :type image: docker.models.images.Image\n        :rtype: docker.models.container.Container"
  },
  {
    "code": "def request_token(self):\n        logging.debug(\"Getting request token from %s:%d\",\n                      self.server, self.port)\n        token, secret = self._token(\"/oauth/requestToken\")\n        return \"{}/oauth/authorize?oauth_token={}\".format(self.host, token), \\\n            token, secret",
    "docstring": "Returns url, request_token, request_secret"
  },
  {
    "code": "def roots(expr, types=(ops.PhysicalTable,)):\n    stack = [\n        arg.to_expr()\n        for arg in reversed(expr.op().root_tables())\n        if isinstance(arg, types)\n    ]\n    def extender(op):\n        return reversed(\n            list(\n                itertools.chain.from_iterable(\n                    arg.op().root_tables()\n                    for arg in op.flat_args()\n                    if isinstance(arg, types)\n                )\n            )\n        )\n    return _search_for_nodes(stack, extender, types)",
    "docstring": "Yield every node of a particular type on which an expression depends.\n\n    Parameters\n    ----------\n    expr : Expr\n        The expression to analyze\n    types : tuple(type), optional, default\n            (:mod:`ibis.expr.operations.PhysicalTable`,)\n        The node types to traverse\n\n    Yields\n    ------\n    table : Expr\n        Unique node types on which an expression depends\n\n    Notes\n    -----\n    If your question is: \"What nodes of type T does `expr` depend on?\", then\n    you've come to the right place. By default, we yield the physical tables\n    that an expression depends on."
  },
  {
    "code": "def get_checksum32(oqparam, hazard=False):\n    checksum = 0\n    for fname in get_input_files(oqparam, hazard):\n        checksum = _checksum(fname, checksum)\n    if hazard:\n        hazard_params = []\n        for key, val in vars(oqparam).items():\n            if key in ('rupture_mesh_spacing', 'complex_fault_mesh_spacing',\n                       'width_of_mfd_bin', 'area_source_discretization',\n                       'random_seed', 'ses_seed', 'truncation_level',\n                       'maximum_distance', 'investigation_time',\n                       'number_of_logic_tree_samples', 'imtls',\n                       'ses_per_logic_tree_path', 'minimum_magnitude',\n                       'prefilter_sources', 'sites',\n                       'pointsource_distance', 'filter_distance'):\n                hazard_params.append('%s = %s' % (key, val))\n        data = '\\n'.join(hazard_params).encode('utf8')\n        checksum = zlib.adler32(data, checksum) & 0xffffffff\n    return checksum",
    "docstring": "Build an unsigned 32 bit integer from the input files of a calculation.\n\n    :param oqparam: an OqParam instance\n    :param hazard: if True, consider only the hazard files\n    :returns: the checkume"
  },
  {
    "code": "def menu_weekly(self, building_id):\n        din = DiningV2(self.bearer, self.token)\n        response = {'result_data': {'Document': {}}}\n        days = []\n        for i in range(7):\n            date = str(datetime.date.today() + datetime.timedelta(days=i))\n            v2_response = din.menu(building_id, date)\n            if building_id in VENUE_NAMES:\n                response[\"result_data\"][\"Document\"][\"location\"] = VENUE_NAMES[building_id]\n            else:\n                response[\"result_data\"][\"Document\"][\"location\"] = v2_response[\"result_data\"][\"days\"][0][\"cafes\"][building_id][\"name\"]\n            formatted_date = datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%-m/%d/%Y')\n            days.append({\"tblDayPart\": get_meals(v2_response, building_id), \"menudate\": formatted_date})\n        response[\"result_data\"][\"Document\"][\"tblMenu\"] = days\n        return normalize_weekly(response)",
    "docstring": "Get an array of menu objects corresponding to the weekly menu for the\n        venue with building_id.\n\n        :param building_id:\n            A string representing the id of a building, e.g. \"abc\".\n\n        >>> commons_week = din.menu_weekly(\"593\")"
  },
  {
    "code": "def _get_source(link):\n    if link.startswith(\"http://\") or link.startswith(\"https://\"):\n        down = httpkie.Downloader()\n        return down.download(link)\n    if os.path.exists(link):\n        with open(link) as f:\n            return f.read()\n    raise UserWarning(\"html: '%s' is neither URL or data!\" % link)",
    "docstring": "Return source of the `link` whether it is filename or url.\n\n    Args:\n        link (str): Filename or URL.\n\n    Returns:\n        str: Content.\n\n    Raises:\n        UserWarning: When the `link` couldn't be resolved."
  },
  {
    "code": "def _ReadSequenceDataTypeDefinition(\n      self, definitions_registry, definition_values, definition_name,\n      is_member=False):\n    if is_member:\n      supported_definition_values = (\n          self._SUPPORTED_DEFINITION_VALUES_ELEMENTS_MEMBER_DATA_TYPE)\n    else:\n      supported_definition_values = (\n          self._SUPPORTED_DEFINITION_VALUES_ELEMENTS_DATA_TYPE)\n    return self._ReadElementSequenceDataTypeDefinition(\n        definitions_registry, definition_values, data_types.SequenceDefinition,\n        definition_name, supported_definition_values)",
    "docstring": "Reads a sequence data type definition.\n\n    Args:\n      definitions_registry (DataTypeDefinitionsRegistry): data type definitions\n          registry.\n      definition_values (dict[str, object]): definition values.\n      definition_name (str): name of the definition.\n      is_member (Optional[bool]): True if the data type definition is a member\n          data type definition.\n\n    Returns:\n      SequenceDefinition: sequence data type definition.\n\n    Raises:\n      DefinitionReaderError: if the definitions values are missing or if\n          the format is incorrect."
  },
  {
    "code": "def _list_element_starts_with(items, needle):\n        for item in items:\n            if item.startswith(needle):\n                return True\n        return False",
    "docstring": "True of any of the list elements starts with needle"
  },
  {
    "code": "def _create(self):\n        if not os.path.exists(settings.SALMON_WHISPER_DB_PATH):\n            os.makedirs(settings.SALMON_WHISPER_DB_PATH)\n        archives = [whisper.parseRetentionDef(retentionDef)\n                    for retentionDef in settings.ARCHIVES.split(\",\")]\n        whisper.create(self.path, archives,\n                       xFilesFactor=settings.XFILEFACTOR,\n                       aggregationMethod=settings.AGGREGATION_METHOD)",
    "docstring": "Create the Whisper file on disk"
  },
  {
    "code": "def field2type_and_format(self, field):\n        for field_class in type(field).__mro__:\n            if field_class in self.field_mapping:\n                type_, fmt = self.field_mapping[field_class]\n                break\n        else:\n            warnings.warn(\n                \"Field of type {} does not inherit from marshmallow.Field.\".format(\n                    type(field)\n                ),\n                UserWarning,\n            )\n            type_, fmt = \"string\", None\n        ret = {\"type\": type_}\n        if fmt:\n            ret[\"format\"] = fmt\n        return ret",
    "docstring": "Return the dictionary of OpenAPI type and format based on the field\n        type\n\n        :param Field field: A marshmallow field.\n        :rtype: dict"
  },
  {
    "code": "def contains_entry(self, key, value):\n        check_not_none(key, \"key can't be None\")\n        check_not_none(value, \"value can't be None\")\n        key_data = self._to_data(key)\n        value_data = self._to_data(value)\n        return self._encode_invoke_on_key(multi_map_contains_entry_codec, key_data, key=key_data,\n                                          value=value_data, thread_id=thread_id())",
    "docstring": "Returns whether the multimap contains an entry with the value.\n\n        :param key: (object), the specified key.\n        :param value: (object), the specified value.\n        :return: (bool), ``true`` if this multimap contains the key-value tuple."
  },
  {
    "code": "def cylinder_inertia(mass, radius, height, transform=None):\n    h2, r2 = height ** 2, radius ** 2\n    diagonal = np.array([((mass * h2) / 12) + ((mass * r2) / 4),\n                         ((mass * h2) / 12) + ((mass * r2) / 4),\n                         (mass * r2) / 2])\n    inertia = diagonal * np.eye(3)\n    if transform is not None:\n        inertia = transform_inertia(transform, inertia)\n    return inertia",
    "docstring": "Return the inertia tensor of a cylinder.\n\n    Parameters\n    ------------\n    mass : float\n      Mass of cylinder\n    radius : float\n      Radius of cylinder\n    height : float\n      Height of cylinder\n    transform : (4,4) float\n      Transformation of cylinder\n\n    Returns\n    ------------\n    inertia : (3,3) float\n      Inertia tensor"
  },
  {
    "code": "def blk_coverage_1d(blk, size):\n    rem = size % blk\n    maxpix = size - rem\n    return maxpix, rem",
    "docstring": "Return the part of a 1d array covered by a block.\n\n    :param blk: size of the 1d block\n    :param size: size of the 1d a image\n    :return: a tuple of size covered and remaining size\n\n    Example:\n\n        >>> blk_coverage_1d(7, 100)\n        (98, 2)"
  },
  {
    "code": "def load(self):\n        pg = self.usr.getPage(\"http://www.neopets.com/objects.phtml?type=shop&obj_type=\" + self.id)\n        self.name = pg.find(\"td\", \"contentModuleHeader\").text.strip()\n        self.inventory = MainShopInventory(self.usr, self.id)",
    "docstring": "Loads the shop name and inventory"
  },
  {
    "code": "def as_binning(obj, copy: bool = False) -> BinningBase:\n    if isinstance(obj, BinningBase):\n        if copy:\n            return obj.copy()\n        else:\n            return obj\n    else:\n        bins = make_bin_array(obj)\n        return StaticBinning(bins)",
    "docstring": "Ensure that an object is a binning\n\n    Parameters\n    ---------\n    obj : BinningBase or array_like\n        Can be a binning, numpy-like bins or full physt bins\n    copy : If true, ensure that the returned object is independent"
  },
  {
    "code": "def pprint(self):\n        items = sorted(self.items())\n        return u\"\\n\".join(u\"%s=%s\" % (k, v.pprint()) for k, v in items)",
    "docstring": "Return tag key=value pairs in a human-readable format."
  },
  {
    "code": "def add_filter(self, ftype, func):\n        if not isinstance(ftype, type):\n            raise TypeError(\"Expected type object, got %s\" % type(ftype))\n        self.castfilter = [(t, f) for (t, f) in self.castfilter if t != ftype]\n        self.castfilter.append((ftype, func))\n        self.castfilter.sort()",
    "docstring": "Register a new output filter. Whenever bottle hits a handler output\n            matching `ftype`, `func` is applyed to it."
  },
  {
    "code": "def command_max_burst_count(self, event=None):\n        try:\n            max_burst_count = self.max_burst_count_var.get()\n        except ValueError:\n            max_burst_count = self.runtime_cfg.max_burst_count\n        if max_burst_count < 1:\n            max_burst_count = self.runtime_cfg.max_burst_count\n        self.runtime_cfg.max_burst_count = max_burst_count\n        self.max_burst_count_var.set(self.runtime_cfg.max_burst_count)",
    "docstring": "max CPU burst op count - self.runtime_cfg.max_burst_count"
  },
  {
    "code": "def _separate_hdxobjects(self, hdxobjects, hdxobjects_name, id_field, hdxobjectclass):\n        new_hdxobjects = self.data.get(hdxobjects_name, list())\n        if new_hdxobjects:\n            hdxobject_names = set()\n            for hdxobject in hdxobjects:\n                hdxobject_name = hdxobject[id_field]\n                hdxobject_names.add(hdxobject_name)\n                for new_hdxobject in new_hdxobjects:\n                    if hdxobject_name == new_hdxobject[id_field]:\n                        merge_two_dictionaries(hdxobject, new_hdxobject)\n                        break\n            for new_hdxobject in new_hdxobjects:\n                if not new_hdxobject[id_field] in hdxobject_names:\n                    hdxobjects.append(hdxobjectclass(new_hdxobject, configuration=self.configuration))\n            del self.data[hdxobjects_name]",
    "docstring": "Helper function to take a list of HDX objects contained in the internal dictionary and add them to a\n        supplied list of HDX objects or update existing metadata if any objects already exist in the list. The list in\n        the internal dictionary is then deleted.\n\n        Args:\n            hdxobjects (List[T <= HDXObject]): list of HDX objects to which to add new objects or update existing ones\n            hdxobjects_name (str): Name of key in internal dictionary from which to obtain list of HDX objects\n            id_field (str): Field on which to match to determine if object already exists in list\n            hdxobjectclass (type): Type of the HDX Object to be added/updated\n\n        Returns:\n            None"
  },
  {
    "code": "def get_trial_info(current_trial):\n    if current_trial.end_time and (\"_\" in current_trial.end_time):\n        time_obj = datetime.datetime.strptime(current_trial.end_time,\n                                              \"%Y-%m-%d_%H-%M-%S\")\n        end_time = time_obj.strftime(\"%Y-%m-%d %H:%M:%S\")\n    else:\n        end_time = current_trial.end_time\n    if current_trial.metrics:\n        metrics = eval(current_trial.metrics)\n    else:\n        metrics = None\n    trial_info = {\n        \"trial_id\": current_trial.trial_id,\n        \"job_id\": current_trial.job_id,\n        \"trial_status\": current_trial.trial_status,\n        \"start_time\": current_trial.start_time,\n        \"end_time\": end_time,\n        \"params\": eval(current_trial.params.encode(\"utf-8\")),\n        \"metrics\": metrics\n    }\n    return trial_info",
    "docstring": "Get job information for current trial."
  },
  {
    "code": "def send(self, data, flags=0):\n        return self.llc.send(self._tco, data, flags)",
    "docstring": "Send data to the socket. The socket must be connected to a remote\n        socket. Returns a boolean value that indicates success or\n        failure. A false value is typically an indication that the\n        socket or connection was closed."
  },
  {
    "code": "def l2_norm(params):\n    flattened, _ = flatten(params)\n    return np.dot(flattened, flattened)",
    "docstring": "Computes l2 norm of params by flattening them into a vector."
  },
  {
    "code": "async def get_user_groups(request):\n    acl_callback = request.get(GROUPS_KEY)\n    if acl_callback is None:\n        raise RuntimeError('acl_middleware not installed')\n    user_id = await get_auth(request)\n    groups = await acl_callback(user_id)\n    if groups is None:\n        return None\n    user_groups = (Group.AuthenticatedUser, user_id) if user_id is not None else ()\n    return set(itertools.chain(groups, (Group.Everyone,), user_groups))",
    "docstring": "Returns the groups that the user in this request has access to.\n\n    This function gets the user id from the auth.get_auth function, and passes\n    it to the ACL callback function to get the groups.\n\n    Args:\n        request: aiohttp Request object\n\n    Returns:\n        If the ACL callback function returns None, this function returns None.\n        Otherwise this function returns the sequence of group permissions\n        provided by the callback, plus the Everyone group. If user_id is not\n        None, the AuthnticatedUser group and the user_id are added to the\n        groups returned by the function\n\n    Raises:\n        RuntimeError: If the ACL middleware is not installed"
  },
  {
    "code": "def loadFile(self, fileName):\n        self.fileName = fileName\n        self.file = QtCore.QFile(fileName)\n        if self.file.exists():\n            self.qteScintilla.setText(open(fileName).read())\n            self.qteScintilla.qteUndoStack.reset()\n        else:\n            msg = \"File <b>{}</b> does not exist\".format(self.qteAppletID())\n            self.qteLogger.info(msg)",
    "docstring": "Display the file ``fileName``."
  },
  {
    "code": "def move_file(\n    src_fs,\n    src_path,\n    dst_fs,\n    dst_path,\n):\n    with manage_fs(src_fs) as _src_fs:\n        with manage_fs(dst_fs, create=True) as _dst_fs:\n            if _src_fs is _dst_fs:\n                _src_fs.move(src_path, dst_path, overwrite=True)\n            else:\n                with _src_fs.lock(), _dst_fs.lock():\n                    copy_file(_src_fs, src_path, _dst_fs, dst_path)\n                    _src_fs.remove(src_path)",
    "docstring": "Move a file from one filesystem to another.\n\n    Arguments:\n        src_fs (FS or str): Source filesystem (instance or URL).\n        src_path (str): Path to a file on ``src_fs``.\n        dst_fs (FS or str); Destination filesystem (instance or URL).\n        dst_path (str): Path to a file on ``dst_fs``."
  },
  {
    "code": "def stop_experiment(args):\n    experiment_id_list = parse_ids(args)\n    if experiment_id_list:\n        experiment_config = Experiments()\n        experiment_dict = experiment_config.get_all_experiments()\n        for experiment_id in experiment_id_list:\n            print_normal('Stoping experiment %s' % experiment_id)\n            nni_config = Config(experiment_dict[experiment_id]['fileName'])\n            rest_port = nni_config.get_config('restServerPort')\n            rest_pid = nni_config.get_config('restServerPid')\n            if rest_pid:\n                kill_command(rest_pid)\n                tensorboard_pid_list = nni_config.get_config('tensorboardPidList')\n                if tensorboard_pid_list:\n                    for tensorboard_pid in tensorboard_pid_list:\n                        try:\n                            kill_command(tensorboard_pid)\n                        except Exception as exception:\n                            print_error(exception)\n                    nni_config.set_config('tensorboardPidList', [])\n            print_normal('Stop experiment success!')\n            experiment_config.update_experiment(experiment_id, 'status', 'STOPPED')\n            time_now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))\n            experiment_config.update_experiment(experiment_id, 'endTime', str(time_now))",
    "docstring": "Stop the experiment which is running"
  },
  {
    "code": "def export_process_to_csv(bpmn_diagram, directory, filename):\n        nodes = copy.deepcopy(bpmn_diagram.get_nodes())\n        start_nodes = []\n        export_elements = []\n        for node in nodes:\n            incoming_list = node[1].get(consts.Consts.incoming_flow)\n            if len(incoming_list) == 0:\n                start_nodes.append(node)\n        if len(start_nodes) != 1:\n            raise bpmn_exception.BpmnPythonError(\"Exporting to CSV format accepts only one start event\")\n        nodes_classification = utils.BpmnImportUtils.generate_nodes_clasification(bpmn_diagram)\n        start_node = start_nodes.pop()\n        BpmnDiagramGraphCsvExport.export_node(bpmn_diagram, export_elements, start_node, nodes_classification)\n        try:\n            os.makedirs(directory)\n        except OSError as exception:\n            if exception.errno != errno.EEXIST:\n                raise\n        file_object = open(directory + filename, \"w\")\n        file_object.write(\"Order,Activity,Condition,Who,Subprocess,Terminated\\n\")\n        BpmnDiagramGraphCsvExport.write_export_node_to_file(file_object, export_elements)\n        file_object.close()",
    "docstring": "Root method of CSV export functionality.\n\n        :param bpmn_diagram: an instance of BpmnDiagramGraph class,\n        :param directory: a string object, which is a path of output directory,\n        :param filename: a string object, which is a name of output file."
  },
  {
    "code": "def cover(self, pageid):\n        r = requests.get(self.api,\n                         params={'action': 'query', 'prop': 'pageimages', 'pageids': pageid, 'format': 'json'},\n                         headers=self.header)\n        jsd = r.json()\n        image = \"File:\" + jsd['query']['pages'][str(pageid)]['pageimage']\n        r = requests.get(self.api,\n                         params={'action': 'query', 'prop': 'imageinfo', 'iiprop': 'url', 'titles': image,\n                                 'format': 'json'},\n                         headers=self.header)\n        jsd = r.json()\n        return jsd['query']['pages'][list(jsd['query']['pages'].keys())[0]]['imageinfo'][0]['url']",
    "docstring": "Get a cover image given a page id.\n\n        :param str pageid: The pageid for the light novel you want a cover image for\n        :return str: the image url"
  },
  {
    "code": "def multimask_images(images: Iterable[SpatialImage],\n                     masks: Sequence[np.ndarray], image_type: type = None\n                     ) -> Iterable[Sequence[np.ndarray]]:\n    for image in images:\n        yield [mask_image(image, mask, image_type) for mask in masks]",
    "docstring": "Mask images with multiple masks.\n\n    Parameters\n    ----------\n    images:\n        Images to mask.\n    masks:\n        Masks to apply.\n    image_type:\n        Type to cast images to.\n\n    Yields\n    ------\n    Sequence[np.ndarray]\n        For each mask, a masked image."
  },
  {
    "code": "def load_results_from_table_definition(table_definition, table_definition_file, options):\n    default_columns = extract_columns_from_table_definition_file(table_definition, table_definition_file)\n    columns_relevant_for_diff = _get_columns_relevant_for_diff(default_columns)\n    results = []\n    for tag in table_definition:\n        if tag.tag == 'result':\n            columns = extract_columns_from_table_definition_file(tag, table_definition_file) or default_columns\n            run_set_id = tag.get('id')\n            for resultsFile in get_file_list_from_result_tag(tag, table_definition_file):\n                results.append(parallel.submit(\n                    load_result, resultsFile, options, run_set_id, columns, columns_relevant_for_diff))\n        elif tag.tag == 'union':\n            results.append(parallel.submit(\n                handle_union_tag, tag, table_definition_file, options, default_columns, columns_relevant_for_diff))\n    return [future.result() for future in results]",
    "docstring": "Load all results in files that are listed in the given table-definition file.\n    @return: a list of RunSetResult objects"
  },
  {
    "code": "def validate(\n    schema: GraphQLSchema,\n    document_ast: DocumentNode,\n    rules: Sequence[RuleType] = None,\n    type_info: TypeInfo = None,\n) -> List[GraphQLError]:\n    if not document_ast or not isinstance(document_ast, DocumentNode):\n        raise TypeError(\"You must provide a document node.\")\n    assert_valid_schema(schema)\n    if type_info is None:\n        type_info = TypeInfo(schema)\n    elif not isinstance(type_info, TypeInfo):\n        raise TypeError(f\"Not a TypeInfo object: {inspect(type_info)}\")\n    if rules is None:\n        rules = specified_rules\n    elif not isinstance(rules, (list, tuple)):\n        raise TypeError(\"Rules must be passed as a list/tuple.\")\n    context = ValidationContext(schema, document_ast, type_info)\n    visitors = [rule(context) for rule in rules]\n    visit(document_ast, TypeInfoVisitor(type_info, ParallelVisitor(visitors)))\n    return context.errors",
    "docstring": "Implements the \"Validation\" section of the spec.\n\n    Validation runs synchronously, returning a list of encountered errors, or an empty\n    list if no errors were encountered and the document is valid.\n\n    A list of specific validation rules may be provided. If not provided, the default\n    list of rules defined by the GraphQL specification will be used.\n\n    Each validation rule is a ValidationRule object which is a visitor object that holds\n    a ValidationContext (see the language/visitor API). Visitor methods are expected to\n    return GraphQLErrors, or lists of GraphQLErrors when invalid.\n\n    Optionally a custom TypeInfo instance may be provided. If not provided, one will be\n    created from the provided schema."
  },
  {
    "code": "def hide(self, bAsync = True):\n        if bAsync:\n            win32.ShowWindowAsync( self.get_handle(), win32.SW_HIDE )\n        else:\n            win32.ShowWindow( self.get_handle(), win32.SW_HIDE )",
    "docstring": "Make the window invisible.\n\n        @see: L{show}\n\n        @type  bAsync: bool\n        @param bAsync: Perform the request asynchronously.\n\n        @raise WindowsError: An error occured while processing this request."
  },
  {
    "code": "def intersection(line1, line2):\n    x1, y1, x2, y2 = line1\n    u1, v1, u2, v2 = line2\n    (a, b), (c, d) = (x2 - x1, u1 - u2), (y2 - y1, v1 - v2)\n    e, f = u1 - x1, v1 - y1\n    denom = float(a * d - b * c)\n    if _near(denom, 0):\n        if b == 0 or d == 0:\n            return None\n        if _near(e / b, f / d):\n            px = x1\n            py = y1\n        else:\n            return None\n    else:\n        t = (e * d - b * f) / denom\n        px = x1 + t * (x2 - x1)\n        py = y1 + t * (y2 - y1)\n    return px, py",
    "docstring": "Return the coordinates of a point of intersection given two lines.\n    Return None if the lines are parallel, but non-colli_near.\n    Return an arbitrary point of intersection if the lines are colli_near.\n\n    Parameters:\n    line1 and line2: lines given by 4 points (x0,y0,x1,y1)."
  },
  {
    "code": "def read_csv_to_html_table(csvFile, hasHeader='N'):\n    txt = '<table class=\"as-table as-table-zebra as-table-horizontal\">'\n    with open(csvFile, \"r\") as f:\n        numRows = 1\n        for row in f:\n            if hasHeader == 'Y':\n                if numRows == 1:\n                    td_begin = '<TH>'\n                    td_end = '</TH>'\n                else:\n                    td_begin = '<TD>'\n                    td_end = '</TD>'\n            else:\n                td_begin = '<TD>'\n                td_end = '</TD>'\n            cols = row.split(',')\n            numRows += 1\n            txt += \"<TR>\"\n            for col in cols:\n                txt += td_begin\n                try:\n                    colString = col\n                except Exception:\n                    colString = '<font color=red>Error decoding column data</font>'\n                txt += colString.strip('\"')\t\n                txt += td_end\n            txt += \"</TR>\\n\"\n        txt += \"</TABLE>\\n\\n\"\n    return txt",
    "docstring": "reads a CSV file and converts it to HTML"
  },
  {
    "code": "def get_preparation_data(name):\r\n    d = dict(\r\n        name=name,\r\n        sys_path=sys.path,\r\n        sys_argv=sys.argv,\r\n        log_to_stderr=_log_to_stderr,\r\n        orig_dir=process.ORIGINAL_DIR,\r\n        authkey=process.current_process().authkey,\r\n    )\r\n    if _logger is not None:\r\n        d['log_level'] = _logger.getEffectiveLevel()\r\n    if not WINEXE:\r\n        main_path = getattr(sys.modules['__main__'], '__file__', None)\r\n        if not main_path and sys.argv[0] not in ('', '-c'):\r\n            main_path = sys.argv[0]\r\n        if main_path is not None:\r\n            if (not os.path.isabs(main_path) and process.ORIGINAL_DIR\r\n                    is not None):\r\n                main_path = os.path.join(process.ORIGINAL_DIR, main_path)\r\n            if not main_path.endswith('.exe'):\r\n                d['main_path'] = os.path.normpath(main_path)\r\n    return d",
    "docstring": "Return info about parent needed by child to unpickle process object.\r\n    Monkey-patch from"
  },
  {
    "code": "def get_description(self, description_type='Abstract'):\n        if 'descriptions' in self.xml:\n            if isinstance(self.xml['descriptions']['description'], list):\n                for description in self.xml['descriptions']['description']:\n                    if description_type in description:\n                        return description[description_type]\n            elif isinstance(self.xml['descriptions']['description'], dict):\n                description = self.xml['descriptions']['description']\n                if description_type in description:\n                    return description[description_type]\n                elif len(description) == 1:\n                    return description.values()[0]\n        return None",
    "docstring": "Get DataCite description."
  },
  {
    "code": "def __sort_analyses(sentence):\n    for word in sentence:\n        if ANALYSIS not in word:\n            raise Exception( '(!) Error: no analysis found from word: '+str(word) )\n        else:\n            word[ANALYSIS] = sorted(word[ANALYSIS], \\\n                key=lambda x : \"_\".join( [x[ROOT],x[POSTAG],x[FORM],x[CLITIC]] ))\n    return sentence",
    "docstring": "Sorts analysis of all the words in the sentence. \n        This is required for consistency, because by default, analyses are \n        listed in arbitrary order;"
  },
  {
    "code": "def copy(self, name=None):\n        r\n        if name is None:\n            name = ws._gen_name()\n        proj = deepcopy(self)\n        ws[name] = proj\n        return proj",
    "docstring": "r\"\"\"\n        Creates a deep copy of the current project\n\n        A deep copy means that new, unique versions of all the objects are\n        created but with identical data and properties.\n\n        Parameters\n        ----------\n        name : string\n            The name to give to the new project.  If not supplied, a name\n            is automatically generated.\n\n        Returns\n        -------\n        A new Project object containing copies of all objects"
  },
  {
    "code": "def interval_lengths( bits ):\n    end = 0\n    while 1:\n        start = bits.next_set( end )\n        if start == bits.size: break\n        end = bits.next_clear( start )\n        yield end - start",
    "docstring": "Get the length distribution of all contiguous runs of set bits from"
  },
  {
    "code": "def remove_multi(self, kvs, quiet=None):\n        return _Base.remove_multi(self, kvs, quiet=quiet)",
    "docstring": "Remove multiple items from the cluster\n\n        :param kvs: Iterable of keys to delete from the cluster. If you wish\n            to specify a CAS for each item, then you may pass a dictionary\n            of keys mapping to cas, like `remove_multi({k1:cas1, k2:cas2}`)\n        :param quiet: Whether an exception should be raised if one or more\n            items were not found\n        :return: A :class:`~.MultiResult` containing :class:`~.OperationResult`\n            values."
  },
  {
    "code": "def clip(self, lower=None, upper=None):\n    df = self.export_df()\n    df = df.clip(lower=lower, upper=upper)\n    self.load_df(df)",
    "docstring": "Trim values at input thresholds using pandas function"
  },
  {
    "code": "def solve_mbar_for_all_states(u_kn, N_k, f_k, solver_protocol):\n    states_with_samples = np.where(N_k > 0)[0]\n    if len(states_with_samples) == 1:\n        f_k_nonzero = np.array([0.0])\n    else:\n        f_k_nonzero, all_results = solve_mbar(u_kn[states_with_samples], N_k[states_with_samples],\n                                              f_k[states_with_samples], solver_protocol=solver_protocol)\n    f_k[states_with_samples] = f_k_nonzero\n    f_k = self_consistent_update(u_kn, N_k, f_k)\n    f_k -= f_k[0]\n    return f_k",
    "docstring": "Solve for free energies of states with samples, then calculate for\n    empty states.\n\n    Parameters\n    ----------\n    u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'\n        The reduced potential energies, i.e. -log unnormalized probabilities\n    N_k : np.ndarray, shape=(n_states), dtype='int'\n        The number of samples in each state\n    f_k : np.ndarray, shape=(n_states), dtype='float'\n        The reduced free energies of each state\n    solver_protocol: tuple(dict()), optional, default=None\n        Sequence of dictionaries of steps in solver protocol for final\n        stage of refinement.\n\n    Returns\n    -------\n    f_k : np.ndarray, shape=(n_states), dtype='float'\n        The free energies of states"
  },
  {
    "code": "def get(cls, **kwargs):\n        data = cls._get(**kwargs)\n        if data is None:\n            new = cls()\n            new.from_miss(**kwargs)\n            return new\n        return cls.deserialize(data)",
    "docstring": "Get a copy of the type from the cache and reconstruct it."
  },
  {
    "code": "def set_style(network_id, ndex_cred=None, template_id=None):\n    if not template_id:\n        template_id = \"ea4ea3b7-6903-11e7-961c-0ac135e8bacf\"\n    server = 'http://public.ndexbio.org'\n    username, password = get_default_ndex_cred(ndex_cred)\n    source_network = ndex2.create_nice_cx_from_server(username=username,\n                                                      password=password,\n                                                      uuid=network_id,\n                                                      server=server)\n    source_network.apply_template(server, template_id)\n    source_network.update_to(network_id, server=server, username=username,\n                             password=password)",
    "docstring": "Set the style of the network to a given template network's style\n\n    Parameters\n    ----------\n    network_id : str\n        The UUID of the NDEx network whose style is to be changed.\n    ndex_cred : dict\n        A dictionary of NDEx credentials.\n    template_id : Optional[str]\n        The UUID of the NDEx network whose style is used on the\n        network specified in the first argument."
  },
  {
    "code": "def dependents_of_addresses(self, addresses):\n    seen = OrderedSet(addresses)\n    for address in addresses:\n      seen.update(self._dependent_address_map[address])\n      seen.update(self._implicit_dependent_address_map[address])\n    return seen",
    "docstring": "Given an iterable of addresses, yield all of those addresses dependents."
  },
  {
    "code": "def _add_intermol_molecule_type(intermol_system, parent):\n        from intermol.moleculetype import MoleculeType\n        from intermol.forces.bond import Bond as InterMolBond\n        molecule_type = MoleculeType(name=parent.name)\n        intermol_system.add_molecule_type(molecule_type)\n        for index, parent_atom in enumerate(parent.particles()):\n            parent_atom.index = index + 1\n        for atom1, atom2 in parent.bonds():\n            intermol_bond = InterMolBond(atom1.index, atom2.index)\n            molecule_type.bonds.add(intermol_bond)",
    "docstring": "Create a molecule type for the parent and add bonds."
  },
  {
    "code": "def get_package(self):\n        package_data = self._get_data()\n        package_data = package_schema.validate(package_data)\n        if \"requires_rez_version\" in package_data:\n            ver = package_data.pop(\"requires_rez_version\")\n            if _rez_Version < ver:\n                raise PackageMetadataError(\n                    \"Failed reading package definition file: rez version >= %s \"\n                    \"needed (current version is %s)\" % (ver, _rez_Version))\n        version_str = package_data.get(\"version\") or \"_NO_VERSION\"\n        repo_data = {self.name: {version_str: package_data}}\n        repo = create_memory_package_repository(repo_data)\n        family_resource = repo.get_package_family(self.name)\n        it = repo.iter_packages(family_resource)\n        package_resource = it.next()\n        package = self.package_cls(package_resource)\n        package.validate_data()\n        return package",
    "docstring": "Create the analogous package.\n\n        Returns:\n            `Package` object."
  },
  {
    "code": "def raise_right_error(response):\n    if response.status_code == 200:\n        return\n    if response.status_code == 500:\n        raise ServerError('Clef servers are down.')\n    if response.status_code == 403:\n        message = response.json().get('error')\n        error_class = MESSAGE_TO_ERROR_MAP[message]\n        if error_class == InvalidOAuthTokenError:\n            message = 'Something went wrong at Clef. Unable to retrieve user information with this token.'\n        raise error_class(message)\n    if response.status_code == 400:\n        message = response.json().get('error')\n        error_class = MESSAGE_TO_ERROR_MAP[message]\n        if error_class:\n            raise error_class(message)\n        else:\n            raise InvalidLogoutTokenError(message)\n    if response.status_code == 404:\n        raise NotFoundError('Unable to retrieve the page. Are you sure the Clef API endpoint is configured right?')\n    raise APIError",
    "docstring": "Raise appropriate error when bad response received."
  },
  {
    "code": "def resources():\n    ind_id = request.form['ind_id']\n    upload_dir = os.path.abspath(app.config['UPLOAD_DIR'])\n    req_file = request.files['file']\n    filename = secure_filename(req_file.filename)\n    file_path = os.path.join(upload_dir, filename)\n    name = request.form['name'] or filename\n    req_file.save(file_path)\n    ind_obj = app.db.individual(ind_id)\n    app.db.add_resource(name, file_path, ind_obj)\n    return redirect(request.referrer)",
    "docstring": "Upload a new resource for an individual."
  },
  {
    "code": "def generate_getter(value):\n    @property\n    @wraps(is_)\n    def getter(self):\n        return self.is_(value)\n    return getter",
    "docstring": "Generate getter for given value."
  },
  {
    "code": "def get_service_module(service_path):\n    paths = [\n        os.path.dirname(__file__),\n        os.path.realpath(os.path.join(service_path, \"..\")),\n        os.path.realpath(os.path.join(service_path)),\n        os.path.realpath(os.path.join(service_path, DEPS_DIR)),\n    ]\n    for path in paths:\n        path = os.path.realpath(path)\n        logger.debug(\"adding %s to path\", path)\n        sys.path.insert(0, path)\n    service_name = os.path.basename(service_path)\n    module = \".\".join([service_name, service_name + \"_service\"])\n    logger.debug(\"importing %s\", module)\n    return importlib.import_module(module)",
    "docstring": "Add custom paths to sys and import service module.\n\n    :param service_path: Path to service folder"
  },
  {
    "code": "def postURL(self, url, headers={}, body=None):\n        return self._load_resource(\"POST\", url, headers, body)",
    "docstring": "Request a URL using the HTTP method POST."
  },
  {
    "code": "def add_service_subnet(self, context_id, subnet_id):\n        return self.context.addServiceSubnetToNetworkTunnel(subnet_id,\n                                                            id=context_id)",
    "docstring": "Adds a service subnet to a tunnel context.\n\n        :param int context_id: The id-value representing the context instance.\n        :param int subnet_id: The id-value representing the service subnet.\n        :return bool: True if service subnet addition was successful."
  },
  {
    "code": "def setdefault (self, key, *args):\n        assert isinstance(key, basestring)\n        return dict.setdefault(self, key.lower(), *args)",
    "docstring": "Set lowercase key value and return."
  },
  {
    "code": "def with_fields(self, *fields):\n        Unihan = self.sql.base.classes.Unihan\n        query = self.sql.session.query(Unihan)\n        for field in fields:\n            query = query.filter(Column(field).isnot(None))\n        return query",
    "docstring": "Returns list of characters with information for certain fields.\n\n        Parameters\n        ----------\n        *fields : list of str\n            fields for which information should be available\n\n        Returns\n        -------\n        :class:`sqlalchemy.orm.query.Query` :\n            list of matches"
  },
  {
    "code": "def hide_tool(self, context_name, tool_name):\n        data = self._context(context_name)\n        hidden_tools = data[\"hidden_tools\"]\n        if tool_name not in hidden_tools:\n            self._validate_tool(context_name, tool_name)\n            hidden_tools.add(tool_name)\n            self._flush_tools()",
    "docstring": "Hide a tool so that it is not exposed in the suite.\n\n        Args:\n            context_name (str): Context containing the tool.\n            tool_name (str): Name of tool to hide."
  },
  {
    "code": "def lerp(vec1, vec2, time):\n        if isinstance(vec1, Vector2) \\\n                and isinstance(vec2, Vector2):\n            if time < 0:\n                time = 0\n            elif time > 1:\n                time = 1\n            x_lerp = vec1[0] + time * (vec2[0] - vec1[0])\n            y_lerp = vec1[1] + time * (vec2[1] - vec1[1])\n            return Vector2(x_lerp, y_lerp)\n        else:\n            raise TypeError(\"Objects must be of type Vector2\")",
    "docstring": "Lerp between vec1 to vec2 based on time. Time is clamped between 0 and 1."
  },
  {
    "code": "def plot(self, format='segments', bits=None, **kwargs):\n        if format == 'timeseries':\n            return super(StateVector, self).plot(**kwargs)\n        if format == 'segments':\n            from ..plot import Plot\n            kwargs.setdefault('xscale', 'auto-gps')\n            return Plot(*self.to_dqflags(bits=bits).values(),\n                        projection='segments', **kwargs)\n        raise ValueError(\"'format' argument must be one of: 'timeseries' or \"\n                         \"'segments'\")",
    "docstring": "Plot the data for this `StateVector`\n\n        Parameters\n        ----------\n        format : `str`, optional, default: ``'segments'``\n            The type of plot to make, either 'segments' to plot the\n            SegmentList for each bit, or 'timeseries' to plot the raw\n            data for this `StateVector`\n\n        bits : `list`, optional\n            A list of bit indices or bit names, defaults to\n            `~StateVector.bits`. This argument is ignored if ``format`` is\n            not ``'segments'``\n\n        **kwargs\n            Other keyword arguments to be passed to either\n            `~gwpy.plot.SegmentAxes.plot` or\n            `~gwpy.plot.Axes.plot`, depending\n            on ``format``.\n\n        Returns\n        -------\n        plot : `~gwpy.plot.Plot`\n            output plot object\n\n        See Also\n        --------\n        matplotlib.pyplot.figure\n            for documentation of keyword arguments used to create the\n            figure\n        matplotlib.figure.Figure.add_subplot\n            for documentation of keyword arguments used to create the\n            axes\n        gwpy.plot.SegmentAxes.plot_flag\n            for documentation of keyword arguments used in rendering each\n            statevector flag."
  },
  {
    "code": "def get(self):\n        if self.timer() > self.deadline:\n            self.value = None\n        return self.value",
    "docstring": "Returns existing value, or None if deadline has expired."
  },
  {
    "code": "def patch_stackless():\n    global _application_set_schedule_callback\n    _application_set_schedule_callback = stackless.set_schedule_callback(_schedule_callback)\n    def set_schedule_callback(callable):\n        global _application_set_schedule_callback\n        old = _application_set_schedule_callback\n        _application_set_schedule_callback = callable\n        return old\n    def get_schedule_callback():\n        global _application_set_schedule_callback\n        return _application_set_schedule_callback\n    set_schedule_callback.__doc__ = stackless.set_schedule_callback.__doc__\n    if hasattr(stackless, \"get_schedule_callback\"):\n        get_schedule_callback.__doc__ = stackless.get_schedule_callback.__doc__\n    stackless.set_schedule_callback = set_schedule_callback\n    stackless.get_schedule_callback = get_schedule_callback\n    if not hasattr(stackless.tasklet, \"trace_function\"):\n        __call__.__doc__ = stackless.tasklet.__call__.__doc__\n        stackless.tasklet.__call__ = __call__\n        setup.__doc__ = stackless.tasklet.setup.__doc__\n        stackless.tasklet.setup = setup\n        run.__doc__ = stackless.run.__doc__\n        stackless.run = run",
    "docstring": "This function should be called to patch the stackless module so that new tasklets are properly tracked in the\n    debugger."
  },
  {
    "code": "def __step1(self):\n        C = self.C\n        n = self.n\n        for i in range(n):\n            minval = min(self.C[i])\n            for j in range(n):\n                self.C[i][j] -= minval\n        return 2",
    "docstring": "For each row of the matrix, find the smallest element and\n        subtract it from every element in its row. Go to Step 2."
  },
  {
    "code": "def _wait_for_job(linode_id, job_id, timeout=300, quiet=True):\n    interval = 5\n    iterations = int(timeout / interval)\n    for i in range(0, iterations):\n        jobs_result = _query('linode',\n                             'job.list',\n                             args={'LinodeID': linode_id})['DATA']\n        if jobs_result[0]['JOBID'] == job_id and jobs_result[0]['HOST_SUCCESS'] == 1:\n            return True\n        time.sleep(interval)\n        log.log(\n            logging.INFO if not quiet else logging.DEBUG,\n            'Still waiting on Job %s for Linode %s.', job_id, linode_id\n        )\n    return False",
    "docstring": "Wait for a Job to return.\n\n    linode_id\n        The ID of the Linode to wait on. Required.\n\n    job_id\n        The ID of the job to wait for.\n\n    timeout\n        The amount of time to wait for a status to update.\n\n    quiet\n        Log status updates to debug logs when True. Otherwise, logs to info."
  },
  {
    "code": "def join(self):\n        self.closed = True\n        while self.expect > 0:\n            val = self.wait_change.get()\n            self.expect -= 1\n            if val is not None:\n                gevent.joinall(list(self.greenlets), timeout=30)\n                gevent.killall(list(self.greenlets), block=True, timeout=30)\n                raise val",
    "docstring": "Wait for transfer to exit, raising errors as necessary."
  },
  {
    "code": "def openDatFile(datpath):\n    pkgname, filename = datpath.split('/', 1)\n    pkgmod = s_dyndeps.getDynMod(pkgname)\n    pkgfile = os.path.abspath(pkgmod.__file__)\n    if os.path.isfile(pkgfile):\n        dirname = os.path.dirname(pkgfile)\n        datname = os.path.join(dirname, filename)\n        return open(datname, 'rb')",
    "docstring": "Open a file-like object using a pkg relative path.\n\n    Example:\n\n        fd = openDatFile('foopkg.barpkg/wootwoot.bin')"
  },
  {
    "code": "def create_custom_field(self, field_name, data_type, options=[],\n                            visible_in_preference_center=True):\n        body = {\n            \"FieldName\": field_name,\n            \"DataType\": data_type,\n            \"Options\": options,\n            \"VisibleInPreferenceCenter\": visible_in_preference_center}\n        response = self._post(self.uri_for(\"customfields\"), json.dumps(body))\n        return json_to_py(response)",
    "docstring": "Creates a new custom field for this list."
  },
  {
    "code": "def reset_current_row(self, *args, **kwargs):\n        i = self.configobj_treev.currentIndex()\n        m = self.configobj_treev.model()\n        m.restore_default(i)",
    "docstring": "Reset the selected rows value to its default value\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def parse_timedelta(deltastr):\n    matches = TIMEDELTA_REGEX.match(deltastr)\n    if not matches:\n        return None\n    components = {}\n    for name, value in matches.groupdict().items():\n        if value:\n            components[name] = int(value)\n    for period, hours in (('days', 24), ('years', 8766)):\n        if period in components:\n            components['hours'] = components.get('hours', 0) + \\\n                                  components[period] * hours\n            del components[period]\n    return int(timedelta(**components).total_seconds())",
    "docstring": "Parse a string describing a period of time."
  },
  {
    "code": "def _get_vm_by_id(vmid, allDetails=False):\n    for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)):\n        if six.text_type(vm_details['vmid']) == six.text_type(vmid):\n            return vm_details\n    log.info('VM with ID \"%s\" could not be found.', vmid)\n    return False",
    "docstring": "Retrieve a VM based on the ID."
  },
  {
    "code": "def _default_warning_handler(library_msg, _):\n    library_msg = library_msg.decode('utf-8').rstrip()\n    msg = \"OpenJPEG library warning:  {0}\".format(library_msg)\n    warnings.warn(msg, UserWarning)",
    "docstring": "Default warning handler callback."
  },
  {
    "code": "def truncate_table(self, tablename):\n        self.cursor.execute('TRUNCATE TABLE %s' %tablename)\n        self.db.commit()",
    "docstring": "Use 'TRUNCATE TABLE' to truncate the given table"
  },
  {
    "code": "def _disk(self):\n        mountpoints = [\n            p.mountpoint for p in psutil.disk_partitions()\n            if p.device.endswith(self.device)\n        ]\n        if len(mountpoints) != 1:\n            raise CommandError(\"Unknown device: {0}\".format(self.device))\n        value = int(psutil.disk_usage(mountpoints[0]).percent)\n        set_metric(\"disk-{0}\".format(self.device), value, category=self.category)\n        gauge(\"disk-{0}\".format(self.device), value)",
    "docstring": "Record Disk usage."
  },
  {
    "code": "def plot_neuron(ax, nrn,\n                neurite_type=NeuriteType.all,\n                plane='xy',\n                soma_outline=True,\n                diameter_scale=_DIAMETER_SCALE, linewidth=_LINEWIDTH,\n                color=None, alpha=_ALPHA):\n    plot_soma(ax, nrn.soma, plane=plane, soma_outline=soma_outline, linewidth=linewidth,\n              color=color, alpha=alpha)\n    for neurite in iter_neurites(nrn, filt=tree_type_checker(neurite_type)):\n        plot_tree(ax, neurite, plane=plane,\n                  diameter_scale=diameter_scale, linewidth=linewidth,\n                  color=color, alpha=alpha)\n    ax.set_title(nrn.name)\n    ax.set_xlabel(plane[0])\n    ax.set_ylabel(plane[1])",
    "docstring": "Plots a 2D figure of the neuron, that contains a soma and the neurites\n\n    Args:\n        ax(matplotlib axes): on what to plot\n        neurite_type(NeuriteType): an optional filter on the neurite type\n        nrn(neuron): neuron to be plotted\n        soma_outline(bool): should the soma be drawn as an outline\n        plane(str): Any pair of 'xyz'\n        diameter_scale(float): Scale factor multiplied with segment diameters before plotting\n        linewidth(float): all segments are plotted with this width, but only if diameter_scale=None\n        color(str or None): Color of plotted values, None corresponds to default choice\n        alpha(float): Transparency of plotted values"
  },
  {
    "code": "async def _receive(self, stream_id, pp_id, data):\n        await self._data_channel_receive(stream_id, pp_id, data)",
    "docstring": "Receive data stream -> ULP."
  },
  {
    "code": "def archive_sciobj(pid):\n    sciobj_model = d1_gmn.app.model_util.get_sci_model(pid)\n    sciobj_model.is_archived = True\n    sciobj_model.save()\n    _update_modified_timestamp(sciobj_model)",
    "docstring": "Set the status of an object to archived.\n\n    Preconditions:\n    - The object with the pid is verified to exist.\n    - The object is not a replica.\n    - The object is not archived."
  },
  {
    "code": "def count_annotation_entries(self) -> int:\n        return self.session.query(NamespaceEntry).filter(NamespaceEntry.is_annotation).count()",
    "docstring": "Count the number of annotation entries in the database."
  },
  {
    "code": "def write(self, file_path, template, context={}, preserve=False, force=False):\n        if not file_path or not template:\n            click.secho('source or target missing for document')\n            return\n        if not context:\n            context = self.context\n        error = False\n        try:\n            self._write(file_path, template, context, preserve, force)\n        except TemplateSyntaxError as exc:\n            message = '{0}:{1}: error: {2}'.format(exc.filename, exc.lineno, exc.message)\n            click.secho(message, fg='red', err=True)\n            error = True\n        except TemplateNotFound as exc:\n            message = '{0}: error: Template not found'.format(exc.name)\n            click.secho(message, fg='red', err=True)\n            error = True\n        except TemplateError as exc:\n            error = True\n        if error and Generator.strict:\n            sys.exit(1)",
    "docstring": "Using a template file name it renders a template\n           into a file given a context"
  },
  {
    "code": "def crop_coords(img, padding):\n    coords = np.nonzero(img)\n    empty_axis_exists = np.any([len(arr) == 0 for arr in coords])\n    if empty_axis_exists:\n        end_coords = img.shape\n        beg_coords = np.zeros((1, img.ndim)).astype(int).flatten()\n    else:\n        min_coords = np.array([arr.min() for arr in coords])\n        max_coords = np.array([arr.max() for arr in coords])\n        beg_coords = np.fmax(0, min_coords - padding)\n        end_coords = np.fmin(img.shape, max_coords + padding)\n    return beg_coords, end_coords",
    "docstring": "Find coordinates describing extent of non-zero portion of image, padded"
  },
  {
    "code": "def get_domain(self):\n        if hasattr(self, 'domain'):\n            return Domain(self.rest_client.make_request(self.domain), self.rest_client)",
    "docstring": "Get the Streams domain for the instance that owns this view.\n\n        Returns:\n            Domain: Streams domain for the instance owning this view."
  },
  {
    "code": "def create_router(self, context, router):\n        new_router = super(AristaL3ServicePlugin, self).create_router(\n            context,\n            router)\n        try:\n            self.driver.create_router(context, new_router)\n            return new_router\n        except Exception:\n            with excutils.save_and_reraise_exception():\n                LOG.error(_LE(\"Error creating router on Arista HW router=%s \"),\n                          new_router)\n                super(AristaL3ServicePlugin, self).delete_router(\n                    context,\n                    new_router['id']\n                )",
    "docstring": "Create a new router entry in DB, and create it Arista HW."
  },
  {
    "code": "def _assert_explicit_vr(dicom_input):\n    if settings.validate_multiframe_implicit:\n        header = dicom_input[0]\n        if header.file_meta[0x0002, 0x0010].value == '1.2.840.10008.1.2':\n            raise ConversionError('IMPLICIT_VR_ENHANCED_DICOM')",
    "docstring": "Assert that explicit vr is used"
  },
  {
    "code": "def _compute_dlt(self):\n        res = super()._compute_dlt()\n        for rec in self:\n            ltaf_to_apply = self.env['ddmrp.adjustment'].search(\n                rec._ltaf_to_apply_domain())\n            if ltaf_to_apply:\n                ltaf = 1\n                values = ltaf_to_apply.mapped('value')\n                for val in values:\n                    ltaf *= val\n                prev = rec.dlt\n                rec.dlt *= ltaf\n                _logger.debug(\n                    \"LTAF=%s applied to %s. DLT: %s -> %s\" %\n                    (ltaf, rec.name, prev, rec.dlt))\n        return res",
    "docstring": "Apply Lead Time Adj Factor if existing"
  },
  {
    "code": "def get_wsgi_filter(self, name=None, defaults=None):\n        name = self._maybe_get_default_name(name)\n        defaults = self._get_defaults(defaults)\n        return loadfilter(\n            self.pastedeploy_spec,\n            name=name,\n            relative_to=self.relative_to,\n            global_conf=defaults,\n        )",
    "docstring": "Reads the configuration soruce and finds and loads a WSGI filter\n        defined by the filter entry with the name ``name`` per the PasteDeploy\n        configuration format and loading mechanism.\n\n        :param name: The named WSGI filter to find, load and return. Defaults\n            to ``None`` which becomes ``main`` inside\n            :func:`paste.deploy.loadfilter`.\n        :param defaults: The ``global_conf`` that will be used during filter\n            instantiation.\n        :return: A callable that can filter a WSGI application."
  },
  {
    "code": "def init(self):\r\n        \"Initialize the message-digest and set all fields to zero.\"\r\n        self.length = 0L\r\n        self.input = []\r\n        self.A = 0x67452301L\r\n        self.B = 0xefcdab89L\r\n        self.C = 0x98badcfeL\r\n        self.D = 0x10325476L",
    "docstring": "Initialize the message-digest and set all fields to zero."
  },
  {
    "code": "def check_auth(self, all_credentials):\n        if all_credentials or self.authset:\n            cached = set(itervalues(all_credentials))\n            authset = self.authset.copy()\n            for credentials in authset - cached:\n                auth.logout(credentials.source, self)\n                self.authset.discard(credentials)\n            for credentials in cached - authset:\n                auth.authenticate(credentials, self)\n                self.authset.add(credentials)",
    "docstring": "Update this socket's authentication.\n\n        Log in or out to bring this socket's credentials up to date with\n        those provided. Can raise ConnectionFailure or OperationFailure.\n\n        :Parameters:\n          - `all_credentials`: dict, maps auth source to MongoCredential."
  },
  {
    "code": "def permute(x: SYM, perm: List[int]) -> SYM:\n    x_s = []\n    for i in perm:\n        x_s.append(x[i])\n    return ca.vertcat(*x_s)",
    "docstring": "Perumute a vector"
  },
  {
    "code": "def delete_role(self, name):\n    return roles.delete_role(self._get_resource_root(), self.name, name,\n        self._get_cluster_name())",
    "docstring": "Delete a role by name.\n\n    @param name: Role name\n    @return: The deleted ApiRole object"
  },
  {
    "code": "def load_lang_model(self):\n        if self.lang in self.languages:\n            if not Spacy.model_installed(self.lang):\n                download(self.lang)\n            model = spacy.load(self.lang)\n        elif self.lang in self.alpha_languages:\n            language_module = importlib.import_module(f\"spacy.lang.{self.lang}\")\n            language_method = getattr(language_module, self.alpha_languages[self.lang])\n            model = language_method()\n        self.model = model",
    "docstring": "Load spaCy language model or download if model is available and not\n        installed.\n\n        Currenty supported spaCy languages\n\n        en English (50MB)\n        de German (645MB)\n        fr French (1.33GB)\n        es Spanish (377MB)\n\n        :return:"
  },
  {
    "code": "def are_genes_in_api(my_clue_api_client, gene_symbols):\n    if len(gene_symbols) > 0:\n        query_gene_symbols = gene_symbols if type(gene_symbols) is list else list(gene_symbols)\n        query_result = my_clue_api_client.run_filter_query(resource_name,\n            {\"where\":{\"gene_symbol\":{\"inq\":query_gene_symbols}}, \"fields\":{\"gene_symbol\":True}})\n        logger.debug(\"query_result:  {}\".format(query_result))\n        r = set([x[\"gene_symbol\"] for x in query_result])\n        return r\n    else:\n        logger.warning(\"provided gene_symbols was empty, cannot run query\")\n        return set()",
    "docstring": "determine if genes are present in the API\n\n    Args:\n        my_clue_api_client:\n        gene_symbols: collection of gene symbols to query the API with\n\n    Returns: set of the found gene symbols"
  },
  {
    "code": "def attribute(func):\n    attr = abc.abstractmethod(func)\n    attr.__iattribute__ = True\n    attr = _property(attr)\n    return attr",
    "docstring": "Wrap a function as an attribute."
  },
  {
    "code": "def post(self, request, *args, **kwargs):\n        try:\n            kwargs = self.load_object(kwargs)\n        except Exception as e:\n            return self.render_te_response({\n                'title': str(e),\n            })\n        if not self.has_permission(request):\n            return self.render_te_response({\n                'title': 'No access',\n            })\n        return self.render_te_response(self.handle_dialog(*args, **kwargs))",
    "docstring": "Handle post request"
  },
  {
    "code": "def block_partition(block, i):\n    i += 1\n    new_block = BasicBlock(block.asm[i:])\n    block.mem = block.mem[:i]\n    block.asm = block.asm[:i]\n    block.update_labels()\n    new_block.update_labels()\n    new_block.goes_to = block.goes_to\n    block.goes_to = IdentitySet()\n    new_block.label_goes = block.label_goes\n    block.label_goes = []\n    new_block.next = new_block.original_next = block.original_next\n    new_block.prev = block\n    new_block.add_comes_from(block)\n    if new_block.next is not None:\n        new_block.next.prev = new_block\n        new_block.next.add_comes_from(new_block)\n        new_block.next.delete_from(block)\n    block.next = block.original_next = new_block\n    block.update_next_block()\n    block.add_goes_to(new_block)\n    return block, new_block",
    "docstring": "Returns two blocks, as a result of partitioning the given one at\n    i-th instruction."
  },
  {
    "code": "def get(self, attri):\n        isCol=False\n        isHead=False\n        if attri in self.dcols:\n            isCol=True\n        elif attri in self.hattrs:\n            isHead=True\n        else:\n            print(\"That attribute does not exist in this File\")\n            print('Returning None')\n        if isCol:\n            return self.getColData(attri)\n        elif isHead:\n            return hattrs",
    "docstring": "Method that dynamically determines the type of attribute that is\n        passed into this method. Also it then returns that attribute's\n        associated data.\n\n        Parameters\n        ----------\n        attri : string\n            The attribute we are looking for."
  },
  {
    "code": "def execute_cell_input(self, cell_input, allow_stdin=None):\n        if cell_input:\n            logger.debug('Executing cell: \"%s\"...', cell_input.splitlines()[0][:40])\n        else:\n            logger.debug('Executing empty cell')\n        return self.kc.execute(cell_input, allow_stdin=allow_stdin, stop_on_error=False)",
    "docstring": "Executes a string of python code in cell input.\n        We do not allow the kernel to make requests to the stdin\n             this is the norm for notebooks\n\n        Function returns a unique message id of the reply from\n        the kernel."
  },
  {
    "code": "def create_media_assetfile(access_token, parent_asset_id, name, is_primary=\"false\", \\\nis_encrypted=\"false\", encryption_scheme=\"None\", encryptionkey_id=\"None\"):\n    path = '/Files'\n    endpoint = ''.join([ams_rest_endpoint, path])\n    if encryption_scheme == \"StorageEncryption\":\n        body = '{ \\\n\t\t\t\"IsEncrypted\": \"' + is_encrypted + '\", \\\n\t\t\t\"EncryptionScheme\": \"' + encryption_scheme + '\", \\\n\t\t\t\"EncryptionVersion\": \"' + \"1.0\" + '\", \\\n\t\t\t\"EncryptionKeyId\": \"' + encryptionkey_id + '\", \\\n\t\t\t\"IsPrimary\": \"' + is_primary + '\", \\\n\t\t\t\"MimeType\": \"video/mp4\", \\\n\t\t\t\"Name\": \"' + name + '\", \\\n\t\t\t\"ParentAssetId\": \"' + parent_asset_id + '\" \\\n\t\t}'\n    else:\n        body = '{ \\\n\t\t\t\"IsPrimary\": \"' + is_primary + '\", \\\n\t\t\t\"MimeType\": \"video/mp4\", \\\n\t\t\t\"Name\": \"' + name + '\", \\\n\t\t\t\"ParentAssetId\": \"' + parent_asset_id + '\" \\\n\t\t}'\n    return do_ams_post(endpoint, path, body, access_token)",
    "docstring": "Create Media Service Asset File.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        parent_asset_id (str): Media Service Parent Asset ID.\n        name (str): Media Service Asset Name.\n        is_primary (str): Media Service Primary Flag.\n        is_encrypted (str): Media Service Encryption Flag.\n        encryption_scheme (str): Media Service Encryption Scheme.\n        encryptionkey_id (str): Media Service Encryption Key ID.\n\n    Returns:\n        HTTP response. JSON body."
  },
  {
    "code": "def list():\n    fields = [\n        ('Name', 'name'),\n        ('ID', 'id'),\n        ('Owner', 'is_owner'),\n        ('Permission', 'permission'),\n    ]\n    with Session() as session:\n        try:\n            resp = session.VFolder.list()\n            if not resp:\n                print('There is no virtual folders created yet.')\n                return\n            rows = (tuple(vf[key] for _, key in fields) for vf in resp)\n            hdrs = (display_name for display_name, _ in fields)\n            print(tabulate(rows, hdrs))\n        except Exception as e:\n            print_error(e)\n            sys.exit(1)",
    "docstring": "List virtual folders that belongs to the current user."
  },
  {
    "code": "def _custom_diag_normal_kl(lhs, rhs, name=None):\n  with tf.name_scope(name or 'kl_divergence'):\n    mean0 = lhs.mean()\n    mean1 = rhs.mean()\n    logstd0 = tf.log(lhs.stddev())\n    logstd1 = tf.log(rhs.stddev())\n    logstd0_2, logstd1_2 = 2 * logstd0, 2 * logstd1\n    return 0.5 * (\n        tf.reduce_sum(tf.exp(logstd0_2 - logstd1_2), -1) +\n        tf.reduce_sum((mean1 - mean0) ** 2 / tf.exp(logstd1_2), -1) +\n        tf.reduce_sum(logstd1_2, -1) - tf.reduce_sum(logstd0_2, -1) -\n        mean0.shape[-1].value)",
    "docstring": "Empirical KL divergence of two normals with diagonal covariance.\n\n  Args:\n    lhs: Diagonal Normal distribution.\n    rhs: Diagonal Normal distribution.\n    name: Name scope for the op.\n\n  Returns:\n    KL divergence from lhs to rhs."
  },
  {
    "code": "def signed_cell_areas(self):\n        assert (\n            self.node_coords.shape[1] == 2\n        ), \"Signed areas only make sense for triangles in 2D.\"\n        if self._signed_cell_areas is None:\n            p = self.node_coords[self.cells[\"nodes\"]].T\n            self._signed_cell_areas = (\n                +p[0][2] * (p[1][0] - p[1][1])\n                + p[0][0] * (p[1][1] - p[1][2])\n                + p[0][1] * (p[1][2] - p[1][0])\n            ) / 2\n        return self._signed_cell_areas",
    "docstring": "Signed area of a triangle in 2D."
  },
  {
    "code": "def _update_expander_status(self, message):\n        if message.type == ExpanderMessage.RELAY:\n            self._relay_status[(message.address, message.channel)] = message.value\n            self.on_relay_changed(message=message)\n            return self._relay_status[(message.address, message.channel)]",
    "docstring": "Uses the provided message to update the expander states.\n\n        :param message: message to use to update\n        :type message: :py:class:`~alarmdecoder.messages.ExpanderMessage`\n\n        :returns: boolean indicating the new status"
  },
  {
    "code": "def validateInt(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,\n                min=None, max=None, lessThan=None, greaterThan=None, excMsg=None):\n    return validateNum(value=value, blank=blank, strip=strip, allowlistRegexes=None,\n                       blocklistRegexes=blocklistRegexes, _numType='int', min=min, max=max,\n                       lessThan=lessThan, greaterThan=greaterThan)",
    "docstring": "Raises ValidationException if value is not a int.\n\n    Returns value, so it can be used inline in an expression:\n\n        print(2 + validateInt(your_number))\n\n    Note that since int() and ignore leading or trailing whitespace\n    when converting a string to a number, so does this validateNum().\n\n    * value (str): The value being validated as an int or float.\n    * blank (bool): If True, a blank string will be accepted. Defaults to False.\n    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.\n    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.\n    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.\n    * _numType (str): One of 'num', 'int', or 'float' for the kind of number to validate against, where 'num' means int or float.\n    * min (int, float): The (inclusive) minimum value for the value to pass validation.\n    * max (int, float): The (inclusive) maximum value for the value to pass validation.\n    * lessThan (int, float): The (exclusive) minimum value for the value to pass validation.\n    * greaterThan (int, float): The (exclusive) maximum value for the value to pass validation.\n    * excMsg (str): A custom message to use in the raised ValidationException.\n\n    If you specify min or max, you cannot also respectively specify lessThan\n    or greaterThan. Doing so will raise PySimpleValidateException.\n\n    >>> import pysimplevalidate as pysv\n    >>> pysv.validateInt('42')\n    42\n    >>> pysv.validateInt('forty two')\n    Traceback (most recent call last):\n        ...\n    pysimplevalidate.ValidationException: 'forty two' is not an integer."
  },
  {
    "code": "def currencies(self):\n        try:\n            resp = self.client.get(self.ENDPOINT_CURRENCIES)\n        except requests.exceptions.RequestException as e:\n            raise OpenExchangeRatesClientException(e)\n        return resp.json()",
    "docstring": "Fetches current currency data of the service\n\n        :Example Data:\n\n        {\n            AED: \"United Arab Emirates Dirham\",\n            AFN: \"Afghan Afghani\",\n            ALL: \"Albanian Lek\",\n            AMD: \"Armenian Dram\",\n            ANG: \"Netherlands Antillean Guilder\",\n            AOA: \"Angolan Kwanza\",\n            ARS: \"Argentine Peso\",\n            AUD: \"Australian Dollar\",\n            AWG: \"Aruban Florin\",\n            AZN: \"Azerbaijani Manat\"\n            ...\n        }"
  },
  {
    "code": "def id_request(self):\n        import inspect\n        curframe = inspect.currentframe()\n        calframe = inspect.getouterframes(curframe, 2)\n        _LOGGER.debug('caller name: %s', calframe[1][3])\n        msg = StandardSend(self.address, COMMAND_ID_REQUEST_0X10_0X00)\n        self._plm.send_msg(msg)",
    "docstring": "Request a device ID from a device."
  },
  {
    "code": "def determine(value):\n    i = -2\n    for v in base_values:\n        if value == v:\n            return (value, 0, 1, 1)\n        if value < v:\n            break\n        i += 1\n    scaled = float(value) / 2 ** i\n    if scaled >= 0.9375:\n        return (base_values[i], 0, 1, 1)\n    elif scaled >= 0.8125:\n        return (base_values[i + 1], 0, 7, 4)\n    elif scaled >= 17 / 24.0:\n        return (base_values[i + 1], 0, 3, 2)\n    elif scaled >= 31 / 48.0:\n        return (v, 1, 1, 1)\n    elif scaled >= 67 / 112.0:\n        return (base_values[i + 1], 0, 5, 4)\n    d = 3\n    for x in range(2, 5):\n        d += 2 ** x\n        if scaled == 2.0 ** x / d:\n            return (v, x, 1, 1)\n    return (base_values[i + 1], 0, 1, 1)",
    "docstring": "Analyse the value and return a tuple containing the parts it's made of.\n\n    The tuple respectively consists of the base note value, the number of\n    dots, and the ratio (see tuplet).\n\n    Examples:\n    >>> determine(8)\n    (8, 0, 1, 1)\n    >>> determine(12)\n    (8, 0, 3, 2)\n    >>> determine(14)\n    (8, 0, 7, 4)\n\n    This function recognizes all the base values, triplets, quintuplets,\n    septuplets and up to four dots. The values are matched on range."
  },
  {
    "code": "def check_apm_out(self):\n        now = time.time()\n        if now - self.last_apm_send_time < 0.02:\n            return\n        self.last_apm_send_time = now\n        if self.hil_state_msg is not None:\n            self.master.mav.send(self.hil_state_msg)",
    "docstring": "check if we should send new data to the APM"
  },
  {
    "code": "def _modulo(self, decimal_argument):\n        _times, remainder = self._context.divmod(decimal_argument, 100)\n        return remainder if remainder >= 0 else remainder + 100",
    "docstring": "The mod operator is prone to floating point errors, so use decimal.\n\n        101.1 % 100\n        >>> 1.0999999999999943\n\n        decimal_context.divmod(Decimal('100.1'), 100)\n        >>> (Decimal('1'), Decimal('0.1'))"
  },
  {
    "code": "def _stop_scan(self):\n        try:\n            response = self._send_command(6, 4, [])\n            if response.payload[0] != 0:\n                if response.payload[0] != 129:\n                    self._logger.error('Error stopping scan for devices, error=%d', response.payload[0])\n                return False, {'reason': \"Could not stop scan for ble devices\"}\n        except InternalTimeoutError:\n            return False, {'reason': \"Timeout waiting for response\"}\n        except DeviceNotConfiguredError:\n            return True, {'reason': \"Device not connected (did you disconnect the dongle?\"}\n        return True, None",
    "docstring": "Stop scanning for BLE devices"
  },
  {
    "code": "def write_message(\n        self, message: Union[str, bytes], binary: bool = False\n    ) -> \"Future[None]\":\n        return self.protocol.write_message(message, binary=binary)",
    "docstring": "Sends a message to the WebSocket server.\n\n        If the stream is closed, raises `WebSocketClosedError`.\n        Returns a `.Future` which can be used for flow control.\n\n        .. versionchanged:: 5.0\n           Exception raised on a closed stream changed from `.StreamClosedError`\n           to `WebSocketClosedError`."
  },
  {
    "code": "def get_scanner_param_default(self, param):\n        assert isinstance(param, str)\n        entry = self.scanner_params.get(param)\n        if not entry:\n            return None\n        return entry.get('default')",
    "docstring": "Returns default value of a scanner parameter."
  },
  {
    "code": "def is_all_initialized(self):\n        return frozenset(self._class_map.keys()) == \\\n            frozenset(self._instance_map.keys())",
    "docstring": "Return whether all the instances have been initialized.\n\n        Returns:\n            bool"
  },
  {
    "code": "def create_ip_arp_request(srchw, srcip, targetip):\n    ether = Ethernet()\n    ether.src = srchw\n    ether.dst = SpecialEthAddr.ETHER_BROADCAST.value\n    ether.ethertype = EtherType.ARP\n    arp = Arp()\n    arp.operation = ArpOperation.Request\n    arp.senderhwaddr = srchw\n    arp.senderprotoaddr = srcip\n    arp.targethwaddr = SpecialEthAddr.ETHER_BROADCAST.value\n    arp.targetprotoaddr = targetip\n    return ether + arp",
    "docstring": "Create and return a packet containing an Ethernet header\n    and ARP header."
  },
  {
    "code": "def symlink(source, destination, adapter=None, must_exist=True, fatal=True, logger=LOG.debug):\n    return _file_op(source, destination, _symlink, adapter, fatal, logger, must_exist=must_exist)",
    "docstring": "Symlink source <- destination\n\n    :param str|None source: Source file or folder\n    :param str|None destination: Destination file or folder\n    :param callable adapter: Optional function to call on 'source' before copy\n    :param bool must_exist: If True, verify that source does indeed exist\n    :param bool|None fatal: Abort execution on failure if True\n    :param callable|None logger: Logger to use\n    :return int: 1 if effectively done, 0 if no-op, -1 on failure"
  },
  {
    "code": "def labeller(rows=None, cols=None, multi_line=True,\n             default=label_value, **kwargs):\n    rows_labeller = as_labeller(rows, default, multi_line)\n    cols_labeller = as_labeller(cols, default, multi_line)\n    def _labeller(label_info):\n        if label_info._meta['dimension'] == 'rows':\n            margin_labeller = rows_labeller\n        else:\n            margin_labeller = cols_labeller\n        label_info = label_info.astype(str)\n        for name, value in label_info.iteritems():\n            func = as_labeller(kwargs.get(name), margin_labeller)\n            new_info = func(label_info[[name]])\n            label_info[name] = new_info[name]\n        if not multi_line:\n            label_info = collapse_label_lines(label_info)\n        return label_info\n    return _labeller",
    "docstring": "Return a labeller function\n\n    Parameters\n    ----------\n    rows : str | function | None\n        How to label the rows\n    cols : str | function | None\n        How to label the columns\n    multi_line : bool\n        Whether to place each variable on a separate line\n    default : function | str\n        Fallback labelling function. If it is a string,\n        it should be the name of one the labelling\n        functions provided by plotnine.\n    kwargs : dict\n        {variable name : function | string} pairs for\n        renaming variables. A function to rename the variable\n        or a string name.\n\n    Returns\n    -------\n    out : function\n        Function to do the labelling"
  },
  {
    "code": "def count_weights(scope=None, exclude=None, graph=None):\n  if scope:\n    scope = scope if scope.endswith('/') else scope + '/'\n  graph = graph or tf.get_default_graph()\n  vars_ = graph.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)\n  if scope:\n    vars_ = [var for var in vars_ if var.name.startswith(scope)]\n  if exclude:\n    exclude = re.compile(exclude)\n    vars_ = [var for var in vars_ if not exclude.match(var.name)]\n  shapes = [var.get_shape().as_list() for var in vars_]\n  return int(sum(np.prod(shape) for shape in shapes))",
    "docstring": "Count learnable parameters.\n\n  Args:\n    scope: Restrict the count to a variable scope.\n    exclude: Regex to match variable names to exclude.\n    graph: Operate on a graph other than the current default graph.\n\n  Returns:\n    Number of learnable parameters as integer."
  },
  {
    "code": "def make_registry(directory, output, recursive=True):\n    directory = Path(directory)\n    if recursive:\n        pattern = \"**/*\"\n    else:\n        pattern = \"*\"\n    files = sorted(\n        [\n            str(path.relative_to(directory))\n            for path in directory.glob(pattern)\n            if path.is_file()\n        ]\n    )\n    hashes = [file_hash(str(directory / fname)) for fname in files]\n    with open(output, \"w\") as outfile:\n        for fname, fhash in zip(files, hashes):\n            outfile.write(\"{} {}\\n\".format(fname.replace(\"\\\\\", \"/\"), fhash))",
    "docstring": "Make a registry of files and hashes for the given directory.\n\n    This is helpful if you have many files in your test dataset as it keeps you\n    from needing to manually update the registry.\n\n    Parameters\n    ----------\n    directory : str\n        Directory of the test data to put in the registry. All file names in the\n        registry will be relative to this directory.\n    output : str\n        Name of the output registry file.\n    recursive : bool\n        If True, will recursively look for files in subdirectories of *directory*."
  },
  {
    "code": "def view_totlosses(token, dstore):\n    oq = dstore['oqparam']\n    tot_losses = dstore['losses_by_asset']['mean'].sum(axis=0)\n    return rst_table(tot_losses.view(oq.loss_dt()), fmt='%.6E')",
    "docstring": "This is a debugging view. You can use it to check that the total\n    losses, i.e. the losses obtained by summing the average losses on\n    all assets are indeed equal to the aggregate losses. This is a\n    sanity check for the correctness of the implementation."
  },
  {
    "code": "def __send_exc_clear(self, log_if_exc_set=None):\n        if not (log_if_exc_set is None or self.__send_exc is None):\n            logger.info(log_if_exc_set)\n        self.__send_exc_time = None\n        self.__send_exc = None",
    "docstring": "Clear send exception and time. If exception was previously was set, optionally log log_if_exc_set at INFO\n        level."
  },
  {
    "code": "def save_matches(self, matches):\n        if not os.path.exists(os.path.dirname(self.location())):\n            os.makedirs(os.path.dirname(self.location()))\n        with open(self.location(), \"w+\") as f:\n            matches = [m for m in matches if not m['processed']]\n            for m in matches:\n                match_obj = json.dumps(m)\n                f.write(match_obj + \"\\n\")",
    "docstring": "Save matches of a failed execution to the log.\n\n        :param matches: a list of matches in JSON format"
  },
  {
    "code": "def output(self, chunk):\n        if chunk is not None:\n            for queue in self.output_queues:\n                queue.put(chunk)",
    "docstring": "Dispatch the given Chunk onto all the registered output queues.\n\n        If the chunk is None, it is silently ignored."
  },
  {
    "code": "async def start_transaction(connection_name: Optional[str] = None) -> BaseTransactionWrapper:\n    connection = _get_connection(connection_name)\n    transaction = connection._in_transaction()\n    await transaction.start()\n    return transaction",
    "docstring": "Function to manually control your transaction.\n\n    Returns transaction object with ``.rollback()`` and ``.commit()`` methods.\n    All db calls in same coroutine context will run into transaction\n    before ending transaction with above methods.\n\n    :param connection_name: name of connection to run with, optional if you have only\n                            one db connection"
  },
  {
    "code": "def build_pic_map(self):\n        if self.pic_to_replace:\n            part=self.docx.part\n            self.pic_map.update(self._img_filename_to_part(part))\n            for relid, rel in six.iteritems(self.docx.part.rels):\n                if rel.reltype in (REL_TYPE.HEADER,REL_TYPE.FOOTER):\n                    self.pic_map.update(self._img_filename_to_part(rel.target_part))",
    "docstring": "Searches in docx template all the xml pictures tag and store them\n        in pic_map dict"
  },
  {
    "code": "def compare_profiles(profile1, profile2):\n    length = len(profile1)\n    profile1 = np.array(list(profile1))\n    profile2 = np.array(list(profile2))\n    similarity_array = profile1 == profile2\n    matches = np.sum(similarity_array)\n    similarity_ratio = matches/length\n    return similarity_ratio",
    "docstring": "Given two profiles, determine the ratio of similarity, i.e.\n        the hamming distance between the strings.\n\n        Args:\n            profile1/2 (str): profile string\n        Returns:\n            similarity_ratio (float): the ratio of similiarity (0-1)"
  },
  {
    "code": "def dispatch_queue(self):\n        self.queue_lock.acquire()\n        q = list(self.queue)\n        self.queue = []\n        self.queue_lock.release()\n        log.debug(\"Dispatching requests: {}\".format(q))\n        for req in q:\n            req.response = self.dispatch_request(req)\n        for req in q:\n            req.signal()",
    "docstring": "Dispatch any queued requests.\n\n        Called by the debugger when it stops."
  },
  {
    "code": "def query(self, query):\n    if str(query.key) in self._items:\n      return query(self._items[str(query.key)].values())\n    else:\n      return query([])",
    "docstring": "Returns an iterable of objects matching criteria expressed in `query`\n\n    Naively applies the query operations on the objects within the namespaced\n    collection corresponding to ``query.key.path``.\n\n    Args:\n      query: Query object describing the objects to return.\n\n    Raturns:\n      iterable cursor with all objects matching criteria"
  },
  {
    "code": "def parabolic(f, x):\n    xv = 1/2. * (f[x-1] - f[x+1]) / (f[x-1] - 2 * f[x] + f[x+1]) + x\n    yv = f[x] - 1/4. * (f[x-1] - f[x+1]) * (xv - x)\n    return (xv, yv)",
    "docstring": "Interpolation. From ageobot, from somewhere else."
  },
  {
    "code": "def rank_member_if(\n            self, rank_conditional, member, score, member_data=None):\n        self.rank_member_if_in(\n            self.leaderboard_name,\n            rank_conditional,\n            member,\n            score,\n            member_data)",
    "docstring": "Rank a member in the leaderboard based on execution of the +rank_conditional+.\n\n        The +rank_conditional+ is passed the following parameters:\n          member: Member name.\n          current_score: Current score for the member in the leaderboard.\n          score: Member score.\n          member_data: Optional member data.\n          leaderboard_options: Leaderboard options, e.g. 'reverse': Value of reverse option\n\n        @param rank_conditional [function] Function which must return +True+ or +False+ that controls whether or not the member is ranked in the leaderboard.\n        @param member [String] Member name.\n        @param score [float] Member score.\n        @param member_data [String] Optional member_data."
  },
  {
    "code": "def visualise(seq, sort=lambda x: x[0]):\n    frmt = \"{:6} {:8,d} {}\"\n    if isinstance(seq, dict):\n        seq = seq.items()\n    if sort:\n        seq = sorted(seq, key=sort)\n    mx, mn = max([i[1] for i in seq]), min([i[1] for i in seq])  \n    range = mx - mn\n    for i in seq:\n        v = int((i[1] * 100) / range)\n        print (frmt.format(i[0], i[1], \"*\" * v))",
    "docstring": "visualises as seq or dictionary"
  },
  {
    "code": "def all_arguments(cls, function, arguments):\n    if isinstance(arguments, dict):\n      arguments = Arguments(**arguments)\n    elif not isinstance(arguments, Arguments):\n      arguments = Arguments(*arguments)\n    return cls(function, arguments)",
    "docstring": "Helper function for creating `FunctionCall`s with `Arguments`.\n\n    Args:\n      function: The value to store for the action function.\n      arguments: The values to store for the arguments of the action. Can either\n        be an `Arguments` object, a `dict`, or an iterable. If a `dict` or an\n        iterable is provided, the values will be unpacked into an `Arguments`\n        object.\n\n    Returns:\n      A new `FunctionCall` instance."
  },
  {
    "code": "def chain(args):\n    p = OptionParser(chain.__doc__)\n    p.add_option(\"--dist\", dest=\"dist\",\n            default=100, type=\"int\",\n            help=\"extent of flanking regions to search [default: %default]\")\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(not p.print_help())\n    blastfile, = args\n    dist = opts.dist\n    assert dist > 0\n    blast = BlastSlow(blastfile)\n    logging.debug(\"A total of {} records imported\".format(len(blast)))\n    chained_hsps = chain_HSPs(blast, xdist=dist, ydist=dist)\n    logging.debug(\"A total of {} records after chaining\".format(len(chained_hsps)))\n    for b in chained_hsps:\n        print(b)",
    "docstring": "%prog chain blastfile\n\n    Chain adjacent HSPs together to form larger HSP."
  },
  {
    "code": "def class_in_progress(stack=None):\n    if stack is None:\n        stack = inspect.stack()\n    for frame in stack:\n        statement_list = frame[4]\n        if statement_list is None:\n            continue\n        if statement_list[0].strip().startswith('class '):\n            return True\n    return False",
    "docstring": "True if currently inside a class definition, else False."
  },
  {
    "code": "def write_all_sequences_file(self, outname, outdir=None):\n        if not outdir:\n            outdir = self.sequence_dir\n            if not outdir:\n                raise ValueError('Output directory must be specified')\n        outfile = op.join(outdir, outname + '.faa')\n        SeqIO.write(self.sequences, outfile, \"fasta\")\n        log.info('{}: wrote all protein sequences to file'.format(outfile))\n        return outfile",
    "docstring": "Write all the stored sequences as a single FASTA file. By default, sets IDs to model gene IDs.\n\n        Args:\n            outname (str): Name of the output FASTA file without the extension\n            outdir (str): Path to output directory for the file, default is the sequences directory"
  },
  {
    "code": "def random(cls):\n        axis = random_unit()\n        angle = np.random.uniform(0,2*np.pi)\n        invert = bool(np.random.randint(0,2))\n        return Rotation.from_properties(angle, axis, invert)",
    "docstring": "Return a random rotation"
  },
  {
    "code": "def delete(self):\n        try:\n            result = self.get_one()\n            if 'sys_id' not in result:\n                raise NoResults()\n        except MultipleResults:\n            raise MultipleResults(\"Deletion of multiple records is not supported\")\n        except NoResults as e:\n            e.args = ('Cannot delete a non-existing record',)\n            raise\n        response = self.session.delete(self._get_table_url(sys_id=result['sys_id']))\n        return self._get_content(response)",
    "docstring": "Deletes the queried record and returns response content after response validation\n\n        :raise:\n            :NoResults: if query returned no results\n            :NotImplementedError: if query returned more than one result (currently not supported)\n        :return:\n            - Delete response content (Generally always {'Success': True})"
  },
  {
    "code": "def subtract_by_key(dict_a, dict_b):\n    difference_dict = {}\n    for key in dict_a:\n        if key not in dict_b:\n            difference_dict[key] = dict_a[key]\n    return difference_dict",
    "docstring": "given two dicts, a and b, this function returns c = a - b, where\n    a - b is defined as the key difference between a and b.\n\n    e.g.,\n    {1:None, 2:3, 3:\"yellow\", 4:True} - {2:4, 1:\"green\"} =\n        {3:\"yellow\", 4:True}"
  },
  {
    "code": "def get_datacenter_id():\n    datacenter_id = config.get_cloud_config_value(\n        'datacenter_id',\n        get_configured_provider(),\n        __opts__,\n        search_global=False\n    )\n    conn = get_conn()\n    try:\n        conn.get_datacenter(datacenter_id=datacenter_id)\n    except PBNotFoundError:\n        log.error('Failed to get datacenter: %s', datacenter_id)\n        raise\n    return datacenter_id",
    "docstring": "Return datacenter ID from provider configuration"
  },
  {
    "code": "def get(self):\n        if self.call_queue:\n            return self.apply(lambda df: df).data\n        else:\n            return self.data.copy()",
    "docstring": "Flushes the call_queue and returns the data.\n\n        Note: Since this object is a simple wrapper, just return the data.\n\n        Returns:\n            The object that was `put`."
  },
  {
    "code": "def list_by_ids(self, ids):\n        ids = utils.coerce_to_list(ids)\n        uri = \"/%s?ids=%s\" % (self.uri_base, \",\".join(ids))\n        curr_prkey = self.plural_response_key\n        self.plural_response_key = \"\"\n        ret = self._list(uri)\n        self.plural_response_key = curr_prkey\n        return ret",
    "docstring": "If you wish to retrieve a list of messages from this queue and know the\n        IDs of those messages, you can pass in a list of those IDs, and only\n        the matching messages will be returned. This avoids pulling down all\n        the messages in a queue and filtering on the client side."
  },
  {
    "code": "def init(cls, *args, **kwargs):\n        instance = cls()\n        instance._values.update(dict(*args, **kwargs))\n        return instance",
    "docstring": "Initialize the config like as you would a regular dict."
  },
  {
    "code": "def center_middle(r, window_size):\n  res = copy.copy(r)\n  mid = res.start + (len(res) / 2)\n  res.start = mid - (window_size / 2)\n  res.end = res.start + window_size\n  return res",
    "docstring": "Center a region on its middle and expand it to window_size bases.\n\n  :return: the new region."
  },
  {
    "code": "def from_specification(cls, specification, model, classical_gap, ground_energy):\n        return cls(specification.graph,\n                   specification.decision_variables,\n                   specification.feasible_configurations,\n                   specification.vartype,\n                   model,\n                   classical_gap,\n                   ground_energy,\n                   ising_linear_ranges=specification.ising_linear_ranges,\n                   ising_quadratic_ranges=specification.ising_quadratic_ranges)",
    "docstring": "Construct a PenaltyModel from a Specification.\n\n        Args:\n            specification (:class:`.Specification`): A specification that was used\n                to generate the model.\n            model (:class:`dimod.BinaryQuadraticModel`): A binary quadratic model\n                that has ground states that match the feasible_configurations.\n            classical_gap (numeric): The difference in classical energy between the ground\n                state and the first excited state. Must be positive.\n            ground_energy (numeric): The minimum energy of all possible configurations.\n\n        Returns:\n            :class:`.PenaltyModel`"
  },
  {
    "code": "def get(self):\n        io_loop = IOLoop.current()\n        new_get = Future()\n        with self._lock:\n            get, self._get = self._get, new_get\n        answer = Future()\n        def _on_node(future):\n            if future.exception():\n                return answer.set_exc_info(future.exc_info())\n            node = future.result()\n            value = node.value\n            new_hole, node.next = node.next, None\n            new_get.set_result(new_hole)\n            answer.set_result(value)\n        def _on_get(future):\n            if future.exception():\n                return answer.set_exc_info(future.exc_info())\n            hole = future.result()\n            io_loop.add_future(hole, _on_node)\n        io_loop.add_future(get, _on_get)\n        return answer",
    "docstring": "Gets the next item from the queue.\n\n        Returns a Future that resolves to the next item once it is available."
  },
  {
    "code": "def save_figure_tofile(fig, fmt, fname):\n    root, ext = osp.splitext(fname)\n    if ext == '.png' and fmt == 'image/svg+xml':\n        qimg = svg_to_image(fig)\n        qimg.save(fname)\n    else:\n        if fmt == 'image/svg+xml' and is_unicode(fig):\n            fig = fig.encode('utf-8')\n        with open(fname, 'wb') as f:\n            f.write(fig)",
    "docstring": "Save fig to fname in the format specified by fmt."
  },
  {
    "code": "def params(self):\n        if self.context.el_type in [Function, Subroutine]:\n            return self.evaluator.element.parameters",
    "docstring": "Raises an ``AttributeError``if the definition is not callable.\n        Otherwise returns a list of `ValueElement` that represents the params."
  },
  {
    "code": "def hostname_text(self):\n        if self._hostname_text is None:\n            self.chain.connection.log(\"Collecting hostname information\")\n            self._hostname_text = self.driver.get_hostname_text()\n            if self._hostname_text:\n                self.chain.connection.log(\"Hostname info collected\")\n            else:\n                self.chain.connection.log(\"Hostname info not collected\")\n        return self._hostname_text",
    "docstring": "Return hostname text and collect if not collected."
  },
  {
    "code": "def by(self, technology):\n        if technology == PluginTechnology.LV2 \\\n        or str(technology).upper() == PluginTechnology.LV2.value.upper():\n            return self.lv2_builder.all\n        else:\n            return []",
    "docstring": "Get the plugins registered in PedalPi by technology\n\n        :param PluginTechnology technology: PluginTechnology identifier"
  },
  {
    "code": "def configure_syslog(request=None, logger=None, exceptions=False):\n    syslog_host = getattr(options, 'syslog_host', None)\n    if not syslog_host:\n        return\n    sys.modules[\"logging\"].raiseExceptions = exceptions\n    handler = SysLogHandler(address=(syslog_host, options.syslog_port))\n    formatter = log_formatter(request)\n    handler.setFormatter(formatter)\n    if request:\n        handler.addFilter(RequestFilter(request))\n    if logger:\n        logger.addHandler(handler)\n    else:\n        logging.getLogger().addHandler(handler)",
    "docstring": "Configure syslog logging channel.\n    It is turned on by setting `syslog_host` in the config file.\n    The port default to 514 can be overridden by setting `syslog_port`.\n\n    :param request: tornado.httputil.HTTPServerRequest instance\n    :param exceptions: boolean - This indicates if we should raise\n        exceptions encountered in the logging system."
  },
  {
    "code": "def get_parser(self):\n        self.path = None\n        self.anony_defs = []\n        self.exhausted = False\n        return self",
    "docstring": "Returns a ParserFactory with the state reset so it can be used to\n        parse again.\n\n        :return: ParserFactory"
  },
  {
    "code": "def _prep_components(component_list: Sequence[str]) -> List[Tuple[str, Tuple[str]]]:\n    components = []\n    for c in component_list:\n        path, args_plus = c.split('(')\n        cleaned_args = _clean_args(args_plus[:-1].split(','), path)\n        components.append((path, cleaned_args))\n    return components",
    "docstring": "Transform component description strings into tuples of component paths and required arguments.\n\n    Parameters\n    ----------\n    component_list :\n        The component descriptions to transform.\n\n    Returns\n    -------\n    List of component/argument tuples."
  },
  {
    "code": "def drawstarslist(self, dictlist, r = 10, colour = None):\n        self.checkforpilimage()\n        colour = self.defaultcolour(colour)\n        self.changecolourmode(colour)\n        self.makedraw()\n        for star in dictlist:\n            self.drawcircle(star[\"x\"], star[\"y\"], r = r, colour = colour, label = star[\"name\"])\n        if self.verbose :\n            print \"I've drawn %i stars.\" % len(dictlist)",
    "docstring": "Calls drawcircle and writelable for an list of stars.\n        Provide a list of dictionnaries, where each dictionnary contains \"name\", \"x\", and \"y\"."
  },
  {
    "code": "def rmdir(remote_folder, missing_okay):\n    board_files = files.Files(_board)\n    board_files.rmdir(remote_folder, missing_okay=missing_okay)",
    "docstring": "Forcefully remove a folder and all its children from the board.\n\n    Remove the specified folder from the board's filesystem.  Must specify one\n    argument which is the path to the folder to delete.  This will delete the\n    directory and ALL of its children recursively, use with caution!\n\n    For example to delete everything under /adafruit_library from the root of a\n    board run:\n\n      ampy --port /board/serial/port rmdir adafruit_library"
  },
  {
    "code": "def reset(self):\n    self._frame_counter = 0\n    ob_real = self.real_env.reset()\n    self.sim_env.add_to_initial_stack(ob_real)\n    for _ in range(3):\n      ob_real, _, _, _ = self.real_env.step(self.name_to_action_num[\"NOOP\"])\n      self.sim_env.add_to_initial_stack(ob_real)\n    ob_sim = self.sim_env.reset()\n    assert np.all(ob_real == ob_sim)\n    self._last_step_tuples = self._pack_step_tuples((ob_real, 0, False, {}),\n                                                    (ob_sim, 0, False, {}))\n    self.set_zero_cumulative_rewards()\n    ob, _, _, _ = self._player_step_tuple(self._last_step_tuples)\n    return ob",
    "docstring": "Reset simulated and real environments."
  },
  {
    "code": "def addHendrix(self):\n        self.hendrix = HendrixService(\n            self.application,\n            threadpool=self.getThreadPool(),\n            resources=self.resources,\n            services=self.services,\n            loud=self.options['loud']\n        )\n        if self.options[\"https_only\"] is not True:\n            self.hendrix.spawn_new_server(self.options['http_port'], HendrixTCPService)",
    "docstring": "Instantiates a HendrixService with this object's threadpool.\n        It will be added as a service later."
  },
  {
    "code": "def _initial_broks(self, broker_name):\n        with self.app.conf_lock:\n            logger.info(\"A new broker just connected : %s\", broker_name)\n            return self.app.sched.fill_initial_broks(broker_name)",
    "docstring": "Get initial_broks from the scheduler\n\n        This is used by the brokers to prepare the initial status broks\n\n        This do not send broks, it only makes scheduler internal processing. Then the broker\n        must use the *_broks* API to get all the stuff\n\n        :param broker_name: broker name, used to filter broks\n        :type broker_name: str\n        :return: None"
  },
  {
    "code": "def has_attribute_type(self, attribute: str, typ: Type) -> bool:\n        if not self.has_attribute(attribute):\n            return False\n        attr_node = self.get_attribute(attribute).yaml_node\n        if typ in scalar_type_to_tag:\n            tag = scalar_type_to_tag[typ]\n            return attr_node.tag == tag\n        elif typ == list:\n            return isinstance(attr_node, yaml.SequenceNode)\n        elif typ == dict:\n            return isinstance(attr_node, yaml.MappingNode)\n        raise ValueError('Invalid argument for typ attribute')",
    "docstring": "Whether the given attribute exists and has a compatible type.\n\n        Returns true iff the attribute exists and is an instance of \\\n        the given type. Matching between types passed as typ and \\\n        yaml node types is as follows:\n\n        +---------+-------------------------------------------+\n        |   typ   |                 yaml                      |\n        +=========+===========================================+\n        |   str   |      ScalarNode containing string         |\n        +---------+-------------------------------------------+\n        |   int   |      ScalarNode containing int            |\n        +---------+-------------------------------------------+\n        |  float  |      ScalarNode containing float          |\n        +---------+-------------------------------------------+\n        |   bool  |      ScalarNode containing bool           |\n        +---------+-------------------------------------------+\n        |   None  |      ScalarNode containing null           |\n        +---------+-------------------------------------------+\n        |   list  |      SequenceNode                         |\n        +---------+-------------------------------------------+\n        |   dict  |      MappingNode                          |\n        +---------+-------------------------------------------+\n\n        Args:\n            attribute: The name of the attribute to check.\n            typ: The type to check against.\n\n        Returns:\n            True iff the attribute exists and matches the type."
  },
  {
    "code": "def quality_and_fitness_parsed(mime_type, parsed_ranges):\n    best_fitness = -1\n    best_fit_q = 0\n    (target_type, target_subtype, target_params) = \\\n        parse_media_range(mime_type)\n    for (type, subtype, params) in parsed_ranges:\n        type_match = (\n            type in (target_type, '*') or\n            target_type == '*'\n        )\n        subtype_match = (\n            subtype in (target_subtype, '*') or\n            target_subtype == '*'\n        )\n        if type_match and subtype_match:\n            fitness = type == target_type and 100 or 0\n            fitness += subtype == target_subtype and 10 or 0\n            param_matches = sum([\n                1 for (key, value) in target_params.items()\n                if key != 'q' and key in params and value == params[key]\n            ])\n            fitness += param_matches\n            fitness += float(target_params.get('q', 1))\n            if fitness > best_fitness:\n                best_fitness = fitness\n                best_fit_q = params['q']\n    return float(best_fit_q), best_fitness",
    "docstring": "Find the best match for a mime-type amongst parsed media-ranges.\n\n    Find the best match for a given mime-type against a list of media_ranges\n    that have already been parsed by parse_media_range(). Returns a tuple of\n    the fitness value and the value of the 'q' quality parameter of the best\n    match, or (-1, 0) if no match was found. Just as for quality_parsed(),\n    'parsed_ranges' must be a list of parsed media ranges.\n\n    :rtype: (float,int)"
  },
  {
    "code": "def hook(*hook_patterns):\n    def _register(action):\n        def arg_gen():\n            rel = endpoint_from_name(hookenv.relation_type())\n            if rel:\n                yield rel\n        handler = Handler.get(action)\n        handler.add_predicate(partial(_hook, hook_patterns))\n        handler.add_args(arg_gen())\n        return action\n    return _register",
    "docstring": "Register the decorated function to run when the current hook matches any of\n    the ``hook_patterns``.\n\n    This decorator is generally deprecated and should only be used when\n    absolutely necessary.\n\n    The hook patterns can use the ``{interface:...}`` and ``{A,B,...}`` syntax\n    supported by :func:`~charms.reactive.bus.any_hook`.\n\n    Note that hook decorators **cannot** be combined with :func:`when` or\n    :func:`when_not` decorators."
  },
  {
    "code": "def create(container, portal_type, *args, **kwargs):\n    from bika.lims.utils import tmpID\n    if kwargs.get(\"title\") is None:\n        kwargs[\"title\"] = \"New {}\".format(portal_type)\n    tmp_id = tmpID()\n    types_tool = get_tool(\"portal_types\")\n    fti = types_tool.getTypeInfo(portal_type)\n    if fti.product:\n        obj = _createObjectByType(portal_type, container, tmp_id)\n    else:\n        factory = getUtility(IFactory, fti.factory)\n        obj = factory(tmp_id, *args, **kwargs)\n        if hasattr(obj, '_setPortalTypeName'):\n            obj._setPortalTypeName(fti.getId())\n        notify(ObjectCreatedEvent(obj))\n        container._setObject(tmp_id, obj)\n        obj = container._getOb(obj.getId())\n    if is_at_content(obj):\n        obj.processForm()\n    obj.edit(**kwargs)\n    modified(obj)\n    return obj",
    "docstring": "Creates an object in Bika LIMS\n\n    This code uses most of the parts from the TypesTool\n    see: `Products.CMFCore.TypesTool._constructInstance`\n\n    :param container: container\n    :type container: ATContentType/DexterityContentType/CatalogBrain\n    :param portal_type: The portal type to create, e.g. \"Client\"\n    :type portal_type: string\n    :param title: The title for the new content object\n    :type title: string\n    :returns: The new created object"
  },
  {
    "code": "def read(self) -> None:\n        for folder in self.folders.values():\n            for file_ in folder.values():\n                file_.read()",
    "docstring": "Call method |NetCDFFile.read| of all handled |NetCDFFile| objects."
  },
  {
    "code": "def is_local(self):\n        local_repo = package_repository_manager.get_repository(\n            self.config.local_packages_path)\n        return (self.resource._repository.uid == local_repo.uid)",
    "docstring": "Returns True if the package is in the local package repository"
  },
  {
    "code": "def by_summoner(self, region, encrypted_summoner_id):\n        url, query = ThirdPartyCodeApiV4Urls.by_summoner(\n            region=region, encrypted_summoner_id=encrypted_summoner_id\n        )\n        return self._raw_request(self.by_summoner.__name__, region, url, query)",
    "docstring": "FOR KR SUMMONERS, A 404 WILL ALWAYS BE RETURNED.\n\n        Valid codes must be no longer than 256 characters and only use\n        valid characters: 0-9, a-z, A-Z, and -\n\n        :param string region:                   the region to execute this request on\n        :param string encrypted_summoner_id:    Summoner ID\n\n        :returns: string"
  },
  {
    "code": "def ccube(self, **kwargs):\n        kwargs_copy = self.base_dict.copy()\n        kwargs_copy.update(**kwargs)\n        kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs))\n        kwargs_copy['component'] = kwargs.get(\n            'component', self.component(**kwargs))\n        localpath = NameFactory.ccube_format.format(**kwargs_copy)\n        if kwargs.get('fullpath', False):\n            return self.fullpath(localpath=localpath)\n        return localpath",
    "docstring": "return the name of a counts cube file"
  },
  {
    "code": "def writeWorkerDebug(debugStats, queueLength, path_suffix=\"\"):\n    createDirectory(path_suffix)\n    origin_prefix = \"origin-\" if scoop.IS_ORIGIN else \"\"\n    statsFilename = os.path.join(\n        getDebugDirectory(),\n        path_suffix,\n        \"{1}worker-{0}-STATS\".format(getDebugIdentifier(), origin_prefix)\n    )\n    lengthFilename = os.path.join(\n        getDebugDirectory(),\n        path_suffix,\n        \"{1}worker-{0}-QUEUE\".format(getDebugIdentifier(), origin_prefix)\n    )\n    with open(statsFilename, 'wb') as f:\n        pickle.dump(debugStats, f)\n    with open(lengthFilename, 'wb') as f:\n        pickle.dump(queueLength, f)",
    "docstring": "Serialize the execution data using pickle and writes it into the debug\n    directory."
  },
  {
    "code": "def sample_surface_even(mesh, count):\n    from .points import remove_close\n    radius = np.sqrt(mesh.area / (2 * count))\n    samples, ids = sample_surface(mesh, count * 5)\n    result, mask = remove_close(samples, radius)\n    return result, ids[mask]",
    "docstring": "Sample the surface of a mesh, returning samples which are\n    approximately evenly spaced.\n\n\n    Parameters\n    ---------\n    mesh: Trimesh object\n    count: number of points to return\n\n    Returns\n    ---------\n    samples: (count,3) points in space on the surface of mesh\n    face_index: (count,) indices of faces for each sampled point"
  },
  {
    "code": "def get_output(self, style=OutputStyle.file):\n        return self.manager.get_output(style=style)",
    "docstring": "Returns the result of all previous calls to execute_code."
  },
  {
    "code": "def get_nagios_unit_name(relation_name='nrpe-external-master'):\n    host_context = get_nagios_hostcontext(relation_name)\n    if host_context:\n        unit = \"%s:%s\" % (host_context, local_unit())\n    else:\n        unit = local_unit()\n    return unit",
    "docstring": "Return the nagios unit name prepended with host_context if needed\n\n    :param str relation_name: Name of relation nrpe sub joined to"
  },
  {
    "code": "def _get_bq_service(credentials=None, service_url=None):\n    assert credentials, 'Must provide ServiceAccountCredentials'\n    http = credentials.authorize(Http())\n    service = build(\n        'bigquery',\n        'v2',\n        http=http,\n        discoveryServiceUrl=service_url,\n        cache_discovery=False\n    )\n    return service",
    "docstring": "Construct an authorized BigQuery service object."
  },
  {
    "code": "def filter_rows(self, filters, rows):\n        ret = []\n        for row in rows:\n            if not self.row_is_filtered(row, filters):\n                ret.append(row)\n        return ret",
    "docstring": "returns rows as filtered by filters"
  },
  {
    "code": "def register_template_directory(kb_app: kb,\n                                sphinx_app: Sphinx,\n                                sphinx_env: BuildEnvironment,\n                                docnames=List[str],\n                                ):\n    template_bridge = sphinx_app.builder.templates\n    actions = ResourceAction.get_callbacks(kb_app)\n    for action in actions:\n        f = os.path.dirname(inspect.getfile(action))\n        template_bridge.loaders.append(SphinxFileSystemLoader(f))",
    "docstring": "Add this resource's templates dir to template paths"
  },
  {
    "code": "def _load_fofn(cls, fofn):\n        filenames = {}\n        f = pyfastaq.utils.open_file_read(fofn)\n        for line in f:\n            fields = line.rstrip().split()\n            if len(fields) == 1:\n                filenames[fields[0]] = None\n            elif len(fields) == 2:\n                filenames[fields[0]] = fields[1]\n            else:\n                raise Error('Error at the following line of file ' + fofn + '. Expected at most 2 fields.\\n' + line)\n        pyfastaq.utils.close(f)\n        return filenames",
    "docstring": "Returns dictionary of filename -> short name. Value is None\n        whenever short name is not provided"
  },
  {
    "code": "def set_gamma_value(self, value):\n        if isinstance(value, float) is False:\n            raise TypeError(\"The type of __gamma_value must be float.\")\n        self.__gamma_value = value",
    "docstring": "setter\n        Gamma value."
  },
  {
    "code": "def _update_parsed_node_info(self, parsed_node, config):\n        schema_override = config.config.get('schema')\n        get_schema = self.get_schema_func()\n        parsed_node.schema = get_schema(schema_override).strip()\n        alias_override = config.config.get('alias')\n        get_alias = self.get_alias_func()\n        parsed_node.alias = get_alias(parsed_node, alias_override).strip()\n        parsed_node.database = config.config.get(\n            'database', self.default_database\n        ).strip()\n        model_tags = config.config.get('tags', [])\n        parsed_node.tags.extend(model_tags)\n        config_dict = parsed_node.get('config', {})\n        config_dict.update(config.config)\n        parsed_node.config = config_dict\n        for hook_type in dbt.hooks.ModelHookType.Both:\n            parsed_node.config[hook_type] = dbt.hooks.get_hooks(parsed_node,\n                                                                hook_type)",
    "docstring": "Given the SourceConfig used for parsing and the parsed node,\n        generate and set the true values to use, overriding the temporary parse\n        values set in _build_intermediate_parsed_node."
  },
  {
    "code": "def dims_intersect(self):\n        return set.intersection(*map(\n            set, (getattr(arr, 'dims_intersect', arr.dims) for arr in self)))",
    "docstring": "Dimensions of the arrays in this list that are used in all arrays"
  },
  {
    "code": "def cd(self, dir_p):\n        if not isinstance(dir_p, basestring):\n            raise TypeError(\"dir_p can only be an instance of type basestring\")\n        progress = self._call(\"cd\",\n                     in_p=[dir_p])\n        progress = IProgress(progress)\n        return progress",
    "docstring": "Change the current directory level.\n\n        in dir_p of type str\n            The name of the directory to go in.\n\n        return progress of type :class:`IProgress`\n            Progress object to track the operation completion."
  },
  {
    "code": "def get_moods(self):\n        mood_parent = self._get_mood_parent()\n        def process_result(result):\n            return [self.get_mood(mood, mood_parent=mood_parent) for mood in\n                    result]\n        return Command('get', [ROOT_MOODS, mood_parent],\n                       process_result=process_result)",
    "docstring": "Return moods defined on the gateway.\n\n        Returns a Command."
  },
  {
    "code": "def _stringify_predicate_value(value):\n    if isinstance(value, bool):\n        return str(value).lower()\n    elif isinstance(value, Sequence) and not isinstance(value, six.string_types):\n        return ','.join(_stringify_predicate_value(x) for x in value)\n    elif isinstance(value, datetime.datetime):\n        return value.isoformat(sep=' ')\n    elif isinstance(value, datetime.date):\n        return value.isoformat()\n    elif value is None:\n        return 'null-val'\n    else:\n        return str(value)",
    "docstring": "Convert Python objects to Space-Track compatible strings\n\n    - Booleans (``True`` -> ``'true'``)\n    - Sequences (``[25544, 34602]`` -> ``'25544,34602'``)\n    - dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)\n    - ``None`` -> ``'null-val'``"
  },
  {
    "code": "def remove_all_network_profiles(self, obj):\n        profile_name_list = self.network_profile_name_list(obj)\n        for profile_name in profile_name_list:\n            self._logger.debug(\"delete profile: %s\", profile_name)\n            str_buf = create_unicode_buffer(profile_name)\n            ret = self._wlan_delete_profile(self._handle, obj['guid'], str_buf)\n            self._logger.debug(\"delete result %d\", ret)",
    "docstring": "Remove all the AP profiles."
  },
  {
    "code": "def assert_matching_time_coord(arr1, arr2):\n    message = ('Time weights not indexed by the same time coordinate as'\n               ' computed data.  This will lead to an improperly computed'\n               ' time weighted average.  Exiting.\\n'\n               'arr1: {}\\narr2: {}')\n    if not (arr1[TIME_STR].identical(arr2[TIME_STR])):\n        raise ValueError(message.format(arr1[TIME_STR], arr2[TIME_STR]))",
    "docstring": "Check to see if two DataArrays have the same time coordinate.\n\n    Parameters\n    ----------\n    arr1 : DataArray or Dataset\n        First DataArray or Dataset\n    arr2 : DataArray or Dataset\n        Second DataArray or Dataset\n\n    Raises\n    ------\n    ValueError\n        If the time coordinates are not identical between the two Datasets"
  },
  {
    "code": "def _uninstall(cls):\n        if cls._hook:\n            sys.meta_path.remove(cls._hook)\n            cls._hook = None",
    "docstring": "uninstall the hook if installed"
  },
  {
    "code": "def _resolve_formatter(self, attr):\n        if attr in COLORS:\n            return self._resolve_color(attr)\n        elif attr in COMPOUNDABLES:\n            return self._formatting_string(self._resolve_capability(attr))\n        else:\n            formatters = split_into_formatters(attr)\n            if all(f in COMPOUNDABLES for f in formatters):\n                return self._formatting_string(\n                    u''.join(self._resolve_formatter(s) for s in formatters))\n            else:\n                return ParametrizingString(self._resolve_capability(attr))",
    "docstring": "Resolve a sugary or plain capability name, color, or compound\n        formatting function name into a callable capability.\n\n        Return a ``ParametrizingString`` or a ``FormattingString``."
  },
  {
    "code": "def template_to_base_path(template, google_songs):\n\tif template == os.getcwd() or template == '%suggested%':\n\t\tbase_path = os.getcwd()\n\telse:\n\t\ttemplate = os.path.abspath(template)\n\t\tsong_paths = [template_to_filepath(template, song) for song in google_songs]\n\t\tbase_path = os.path.dirname(os.path.commonprefix(song_paths))\n\treturn base_path",
    "docstring": "Get base output path for a list of songs for download."
  },
  {
    "code": "def _validate_jpx_box_sequence(self, boxes):\n        self._validate_label(boxes)\n        self._validate_jpx_compatibility(boxes, boxes[1].compatibility_list)\n        self._validate_singletons(boxes)\n        self._validate_top_level(boxes)",
    "docstring": "Run through series of tests for JPX box legality."
  },
  {
    "code": "def rename(self, new_name_or_name_dict=None, **names):\n        if names or utils.is_dict_like(new_name_or_name_dict):\n            name_dict = either_dict_or_kwargs(\n                new_name_or_name_dict, names, 'rename')\n            dataset = self._to_temp_dataset().rename(name_dict)\n            return self._from_temp_dataset(dataset)\n        else:\n            return self._replace(name=new_name_or_name_dict)",
    "docstring": "Returns a new DataArray with renamed coordinates or a new name.\n\n        Parameters\n        ----------\n        new_name_or_name_dict : str or dict-like, optional\n            If the argument is dict-like, it it used as a mapping from old\n            names to new names for coordinates. Otherwise, use the argument\n            as the new name for this array.\n        **names, optional\n            The keyword arguments form of a mapping from old names to\n            new names for coordinates.\n            One of new_name_or_name_dict or names must be provided.\n\n\n        Returns\n        -------\n        renamed : DataArray\n            Renamed array or array with renamed coordinates.\n\n        See Also\n        --------\n        Dataset.rename\n        DataArray.swap_dims"
  },
  {
    "code": "def get_zipped_dataset_from_predictions(predictions):\n  targets = stack_data_given_key(predictions, \"targets\")\n  outputs = stack_data_given_key(predictions, \"outputs\")\n  num_videos, num_steps = targets.shape[:2]\n  outputs = outputs[:, :num_steps]\n  targets_placeholder = tf.placeholder(targets.dtype, targets.shape)\n  outputs_placeholder = tf.placeholder(outputs.dtype, outputs.shape)\n  dataset = tf.data.Dataset.from_tensor_slices(\n      (targets_placeholder, outputs_placeholder))\n  iterator = dataset.make_initializable_iterator()\n  feed_dict = {targets_placeholder: targets,\n               outputs_placeholder: outputs}\n  return iterator, feed_dict, num_videos",
    "docstring": "Creates dataset from in-memory predictions."
  },
  {
    "code": "def set_user_passwd(self, userid, data):\n        return self.api_call(\n            ENDPOINTS['users']['password'],\n            dict(userid=userid),\n            body=data)",
    "docstring": "Set user password"
  },
  {
    "code": "def path(path_name=None, override=None, *, root=None, name=None, ext=None,\n         inject=None, relpath=None, reduce=False):\n    path_name, identity, root = _initialize(path_name, override, root, inject)\n    new_name = _process_name(path_name, identity, name, ext)\n    new_directory = _process_directory(path_name, identity, root, inject)\n    full_path = os.path.normpath(os.path.join(new_directory, new_name))\n    if APPEND_SEP_TO_DIRS and not new_name and full_path[-1] != os.sep:\n        full_path += os.sep\n    final_path = _format_path(full_path, root, relpath, reduce)\n    return final_path",
    "docstring": "Path manipulation black magic"
  },
  {
    "code": "def _margtimephase_loglr(self, mf_snr, opt_snr):\n        return special.logsumexp(numpy.log(special.i0(mf_snr)),\n                                 b=self._deltat) - 0.5*opt_snr",
    "docstring": "Returns the log likelihood ratio marginalized over time and phase."
  },
  {
    "code": "def get_currentDim(self):\r\n        selfDim = self._dimensions.copy()\r\n        if not isinstance(selfDim,dimStr):\r\n            if selfDim.has_key('_ndims') : nself = selfDim.pop('_ndims')\r\n            else : \r\n                self.warning(1, 'self._dimensions does not have the _ndims key')\r\n                nself = len(selfDim)\r\n        else : nself = selfDim['_ndims']\r\n        curDim = [[key for key in selfDim.keys()],[selfDim[key] for key in selfDim.keys()]]\r\n        return curDim, nself",
    "docstring": "returns the current dimensions of the object"
  },
  {
    "code": "def _prepare_menu(self, node, flat=None):\n        if flat is None:\n            flat = self.flat\n        ItemGroup = MenuSection if flat else SubMenu\n        return [\n            ItemGroup(branch.label, self._collapse_device(branch, flat))\n            for branch in node.branches\n            if branch.methods or branch.branches\n        ]",
    "docstring": "Prepare the menu hierarchy from the given device tree.\n\n        :param Device node: root node of device hierarchy\n        :returns: menu hierarchy as list"
  },
  {
    "code": "def get(self):\n        self.lock.acquire()\n        try:\n            c = self.conn.popleft()\n            yield c\n        except self.exc_classes:\n            gevent.spawn_later(1, self._addOne)\n            raise\n        except:\n            self.conn.append(c)\n            self.lock.release()\n            raise\n        else:\n            self.conn.append(c)\n            self.lock.release()",
    "docstring": "Get a connection from the pool, to make and receive traffic.\n\n        If the connection fails for any reason (socket.error), it is dropped\n        and a new one is scheduled. Please use @retry as a way to automatically\n        retry whatever operation you were performing."
  },
  {
    "code": "def plot(self):\n        msg = \"'%s.plot': ADW 2018-05-05\"%self.__class__.__name__\n        DeprecationWarning(msg)\n        import ugali.utils.plotting\n        mask = hp.UNSEEN * np.ones(hp.nside2npix(self.nside))\n        mask[self.roi.pixels] = self.mask_roi_sparse\n        mask[mask == 0.] = hp.UNSEEN\n        ugali.utils.plotting.zoomedHealpixMap('Completeness Depth',\n                                              mask,\n                                              self.roi.lon, self.roi.lat,\n                                              self.roi.config.params['coords']['roi_radius'])",
    "docstring": "Plot the magnitude depth."
  },
  {
    "code": "def get_requirements(self, arguments, max_retries=None, use_wheels=False):\n        arguments = self.decorate_arguments(arguments)\n        with DownloadLogFilter():\n            with SetupRequiresPatch(self.config, self.eggs_links):\n                self.create_build_directory()\n                if any(match_option(a, '-U', '--upgrade') for a in arguments):\n                    logger.info(\"Checking index(es) for new version (-U or --upgrade was given) ..\")\n                else:\n                    try:\n                        return self.unpack_source_dists(arguments, use_wheels=use_wheels)\n                    except DistributionNotFound:\n                        logger.info(\"We don't have all distribution archives yet!\")\n                if max_retries is None:\n                    max_retries = self.config.max_retries\n                for i in range(max_retries):\n                    try:\n                        return self.download_source_dists(arguments, use_wheels=use_wheels)\n                    except Exception as e:\n                        if i + 1 < max_retries:\n                            logger.warning(\"pip raised exception while downloading distributions: %s\", e)\n                        else:\n                            raise\n                    logger.info(\"Retrying after pip failed (%i/%i) ..\", i + 1, max_retries)",
    "docstring": "Use pip to download and unpack the requested source distribution archives.\n\n        :param arguments: The command line arguments to ``pip install ...`` (a\n                          list of strings).\n        :param max_retries: The maximum number of times that pip will be asked\n                            to download distribution archives (this helps to\n                            deal with intermittent failures). If this is\n                            :data:`None` then :attr:`~.Config.max_retries` is\n                            used.\n        :param use_wheels: Whether pip and pip-accel are allowed to use wheels_\n                           (:data:`False` by default for backwards compatibility\n                           with callers that use pip-accel as a Python API).\n\n        .. warning:: Requirements which are already installed are not included\n                     in the result. If this breaks your use case consider using\n                     pip's ``--ignore-installed`` option."
  },
  {
    "code": "def buildcommit(self):\n        if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None):\n            return self.dutinformation.get(0).build.commit_id\n        return None",
    "docstring": "get build commit id.\n\n        :return: build commit id or None if not found"
  },
  {
    "code": "def action_update(self):\n        order = []\n        form = self.request.form\n        attachments = form.get(\"attachments\", [])\n        for attachment in attachments:\n            values = dict(attachment)\n            uid = values.pop(\"UID\")\n            obj = api.get_object_by_uid(uid)\n            if values.pop(\"delete\", False):\n                self.delete_attachment(obj)\n                continue\n            order.append(uid)\n            obj.update(**values)\n            obj.reindexObject()\n        self.set_attachments_order(order)\n        return self.request.response.redirect(self.context.absolute_url())",
    "docstring": "Form action enpoint to update the attachments"
  },
  {
    "code": "def close(self):\n        close_command = StandardSend(self._address,\n                                     COMMAND_LIGHT_OFF_0X13_0X00)\n        self._send_method(close_command, self._close_message_received)",
    "docstring": "Send CLOSE command to device."
  },
  {
    "code": "def _try_join_cancelled_thread(thread):\n    thread.join(10)\n    if thread.is_alive():\n        logging.warning(\"Thread %s did not terminate within grace period after cancellation\",\n                        thread.name)",
    "docstring": "Join a thread, but if the thread doesn't terminate for some time, ignore it\n    instead of waiting infinitely."
  },
  {
    "code": "def sni2route(self, sni: SchemaNodeId, sctx: SchemaContext) -> SchemaRoute:\n        nlist = sni.split(\"/\")\n        res = []\n        for qn in (nlist[1:] if sni[0] == \"/\" else nlist):\n            res.append(self.translate_node_id(qn, sctx))\n        return res",
    "docstring": "Translate schema node identifier to a schema route.\n\n        Args:\n            sni: Schema node identifier (absolute or relative).\n            sctx: Schema context.\n\n        Raises:\n            ModuleNotRegistered: If `mid` is not registered in the data model.\n            UnknownPrefix: If a prefix specified in `sni` is not declared."
  },
  {
    "code": "def dispatch_to_index_op(op, left, right, index_class):\n    left_idx = index_class(left)\n    if getattr(left_idx, 'freq', None) is not None:\n        left_idx = left_idx._shallow_copy(freq=None)\n    try:\n        result = op(left_idx, right)\n    except NullFrequencyError:\n        raise TypeError('incompatible type for a datetime/timedelta '\n                        'operation [{name}]'.format(name=op.__name__))\n    return result",
    "docstring": "Wrap Series left in the given index_class to delegate the operation op\n    to the index implementation.  DatetimeIndex and TimedeltaIndex perform\n    type checking, timezone handling, overflow checks, etc.\n\n    Parameters\n    ----------\n    op : binary operator (operator.add, operator.sub, ...)\n    left : Series\n    right : object\n    index_class : DatetimeIndex or TimedeltaIndex\n\n    Returns\n    -------\n    result : object, usually DatetimeIndex, TimedeltaIndex, or Series"
  },
  {
    "code": "def add_ref(self, reftype, data):\n        ref = (reftype, data)\n        try:\n            index = self.refs.index(ref)\n        except ValueError:\n            self.refs.append(ref)\n            index = len(self.refs) - 1\n        return str(index)",
    "docstring": "Add a reference and returns the identifier."
  },
  {
    "code": "def _csv_temp(self, cursor, fieldnames):\n        temp_fd, temp_path = tempfile.mkstemp(text=True)\n        with open(temp_fd, 'w', encoding='utf-8', newline='') as results_fh:\n            self._csv(cursor, fieldnames, results_fh)\n        return temp_path",
    "docstring": "Writes the rows of `cursor` in CSV format to a temporary file and\n        returns the path to that file.\n\n        :param cursor: database cursor containing data to be output\n        :type cursor: `sqlite3.Cursor`\n        :param fieldnames: row headings\n        :type fieldnames: `list`\n        :rtype: `str`"
  },
  {
    "code": "def enable(states):\n    ret = {\n        'res': True,\n        'msg': ''\n    }\n    states = salt.utils.args.split_input(states)\n    log.debug('states %s', states)\n    msg = []\n    _disabled = __salt__['grains.get']('state_runs_disabled')\n    if not isinstance(_disabled, list):\n        _disabled = []\n    _changed = False\n    for _state in states:\n        log.debug('_state %s', _state)\n        if _state not in _disabled:\n            msg.append('Info: {0} state already enabled.'.format(_state))\n        else:\n            msg.append('Info: {0} state enabled.'.format(_state))\n            _disabled.remove(_state)\n            _changed = True\n    if _changed:\n        __salt__['grains.setval']('state_runs_disabled', _disabled)\n    ret['msg'] = '\\n'.join(msg)\n    __salt__['saltutil.refresh_modules']()\n    return ret",
    "docstring": "Enable state function or sls run\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' state.enable highstate\n\n        salt '*' state.enable test.succeed_without_changes\n\n    .. note::\n        To enable a state file from running provide the same name that would\n        be passed in a state.sls call.\n\n        salt '*' state.disable bind.config"
  },
  {
    "code": "def validate(self, attrs):\n        user = authenticate(**self.user_credentials(attrs))\n        if user:\n            if user.is_active:\n                self.instance = user\n            else:\n                raise serializers.ValidationError(_(\"This account is currently inactive.\"))\n        else:\n            error = _(\"Invalid login credentials.\")\n            raise serializers.ValidationError(error)\n        return attrs",
    "docstring": "checks if login credentials are correct"
  },
  {
    "code": "def from_lines(lines: Iterable[str], **kwargs) -> BELGraph:\n    graph = BELGraph()\n    parse_lines(graph=graph, lines=lines, **kwargs)\n    return graph",
    "docstring": "Load a BEL graph from an iterable over the lines of a BEL script.\n\n    :param lines: An iterable of strings (the lines in a BEL script)\n\n    The remaining keyword arguments are passed to :func:`pybel.io.line_utils.parse_lines`."
  },
  {
    "code": "def migrateFileFields(portal):\n    portal_types = [\n        \"Attachment\",\n        \"ARImport\",\n        \"Instrument\",\n        \"InstrumentCertification\",\n        \"Method\",\n        \"Multifile\",\n        \"Report\",\n        \"ARReport\",\n        \"SamplePoint\"]\n    for portal_type in portal_types:\n        migrate_to_blob(\n            portal,\n            portal_type=portal_type,\n            remove_old_value=True)",
    "docstring": "This function walks over all attachment types and migrates their FileField\n    fields."
  },
  {
    "code": "def get_channelstate_filter(\n        chain_state: ChainState,\n        payment_network_id: PaymentNetworkID,\n        token_address: TokenAddress,\n        filter_fn: Callable,\n) -> List[NettingChannelState]:\n    token_network = get_token_network_by_token_address(\n        chain_state,\n        payment_network_id,\n        token_address,\n    )\n    result: List[NettingChannelState] = []\n    if not token_network:\n        return result\n    for channel_state in token_network.channelidentifiers_to_channels.values():\n        if filter_fn(channel_state):\n            result.append(channel_state)\n    return result",
    "docstring": "Return the state of channels that match the condition in `filter_fn`"
  },
  {
    "code": "def remove(self):\n        \"Remove the hook from the model.\"\n        if not self.removed:\n            self.hook.remove()\n            self.removed=True",
    "docstring": "Remove the hook from the model."
  },
  {
    "code": "def add(self, data, name=None):\n        if name is None:\n            n = len(self.data)\n            while \"Series %d\"%n in self.data:\n                n += 1\n            name = \"Series %d\"%n\n        self.data[name] = data\n        return name",
    "docstring": "Appends a new column of data to the data source.\n\n        Args:\n            data (seq) : new data to add\n            name (str, optional) : column name to use.\n                If not supplied, generate a name of the form \"Series ####\"\n\n        Returns:\n            str:  the column name used"
  },
  {
    "code": "def sync_time(self):\n        now = time.localtime(time.time())\n        self.remote(set_time, (now.tm_year, now.tm_mon, now.tm_mday, now.tm_wday + 1,\n                               now.tm_hour, now.tm_min, now.tm_sec, 0))\n        return now",
    "docstring": "Sets the time on the pyboard to match the time on the host."
  },
  {
    "code": "def optimal_part_info(length, part_size):\n    if length == -1:\n        length = MAX_MULTIPART_OBJECT_SIZE\n    if length > MAX_MULTIPART_OBJECT_SIZE:\n        raise InvalidArgumentError('Input content size is bigger '\n                                   ' than allowed maximum of 5TiB.')\n    if part_size != MIN_PART_SIZE:\n        part_size_float = float(part_size)\n    else:\n        part_size_float = math.ceil(length/MAX_MULTIPART_COUNT)\n        part_size_float = (math.ceil(part_size_float/part_size)\n                        * part_size)\n    total_parts_count = int(math.ceil(length/part_size_float))\n    part_size = int(part_size_float)\n    last_part_size = length - int(total_parts_count-1)*part_size\n    return total_parts_count, part_size, last_part_size",
    "docstring": "Calculate optimal part size for multipart uploads.\n\n    :param length: Input length to calculate part size of.\n    :return: Optimal part size."
  },
  {
    "code": "def parse_image_spec(spec):\n    match = re.match(r'(.+)\\s+\\\"(.*)\\\"\\s*$', spec)\n    if match:\n        spec, title = match.group(1, 2)\n    else:\n        title = None\n    match = re.match(r'([^\\{]*)(\\{(.*)\\})\\s*$', spec)\n    if match:\n        spec = match.group(1)\n        args = parse_arglist(match.group(3))\n    else:\n        args = {}\n    return spec, args, (title and html.unescape(title))",
    "docstring": "Parses out a Publ-Markdown image spec into a tuple of path, args, title"
  },
  {
    "code": "def _get_extended(scene, resp):\n    root = ElementTree.fromstring(resp.text)\n    items = root.findall(\"eemetadata:metadataFields/eemetadata:metadataField\", NAMESPACES)\n    scene['extended'] = {item.attrib.get('name').strip(): xsi.get(item[0]) for item in items}\n    return scene",
    "docstring": "Parse metadata returned from the metadataUrl of a USGS scene.\n\n    :param scene:\n        Dictionary representation of a USGS scene\n    :param resp:\n        Response object from requests/grequests"
  },
  {
    "code": "def list(self, filter_args=None):\n        res = list()\n        for oid in self._resources:\n            resource = self._resources[oid]\n            if self._matches_filters(resource, filter_args):\n                res.append(resource)\n        return res",
    "docstring": "List the faked resources of this manager.\n\n        Parameters:\n\n          filter_args (dict):\n            Filter arguments. `None` causes no filtering to happen. See\n            :meth:`~zhmcclient.BaseManager.list()` for details.\n\n        Returns:\n          list of FakedBaseResource: The faked resource objects of this\n            manager."
  },
  {
    "code": "def get_all_tags_of_confirmation(self, confirmation_id):\n        return self._iterate_through_pages(\n            get_function=self.get_tags_of_confirmation_per_page,\n            resource=CONFIRMATION_TAGS,\n            **{'confirmation_id': confirmation_id}\n        )",
    "docstring": "Get all tags of confirmation\n        This will iterate over all pages until it gets all elements.\n        So if the rate limit exceeded it will throw an Exception and you will get nothing\n\n        :param confirmation_id: the confirmation id\n        :return: list"
  },
  {
    "code": "def map(**kwargs):\n    d = {}\n    e = lower_dict(environ.copy())\n    for k, v in kwargs.items():\n        d[k] = e.get(v.lower())\n    return d",
    "docstring": "Returns a dictionary of the given keyword arguments mapped to their\n    values from the environment, with input keys lower cased."
  },
  {
    "code": "def get(self, sid):\n        return IpAccessControlListMappingContext(\n            self._version,\n            account_sid=self._solution['account_sid'],\n            domain_sid=self._solution['domain_sid'],\n            sid=sid,\n        )",
    "docstring": "Constructs a IpAccessControlListMappingContext\n\n        :param sid: A 34 character string that uniquely identifies the resource to fetch.\n\n        :returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingContext\n        :rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingContext"
  },
  {
    "code": "def set_system_id(self, system_id):\n        yield from self._hypervisor.send('{platform} set_system_id \"{name}\" {system_id}'.format(platform=self._platform,\n                                                                                                name=self._name,\n                                                                                                system_id=system_id))\n        log.info('Router \"{name}\" [{id}]: system ID updated from {old_id} to {new_id}'.format(name=self._name,\n                                                                                              id=self._id,\n                                                                                              old_id=self._system_id,\n                                                                                              new_id=system_id))\n        self._system_id = system_id",
    "docstring": "Sets the system ID.\n\n        :param system_id: a system ID (also called board processor ID)"
  },
  {
    "code": "def tarbell_update(command, args):\n    with ensure_settings(command, args) as settings, ensure_project(command, args) as site:\n        puts(\"Updating to latest blueprint\\n\")\n        git = sh.git.bake(_cwd=site.base.base_dir)\n        puts(colored.yellow(\"Stashing local changes\"))\n        puts(git.stash())\n        puts(colored.yellow(\"Pull latest changes\"))\n        puts(git.pull())\n        if git.stash.list():\n            puts(git.stash.pop())",
    "docstring": "Update the current tarbell project."
  },
  {
    "code": "def shift(self, shifts=None, fill_value=dtypes.NA, **shifts_kwargs):\n        variable = self.variable.shift(\n            shifts=shifts, fill_value=fill_value, **shifts_kwargs)\n        return self._replace(variable=variable)",
    "docstring": "Shift this array by an offset along one or more dimensions.\n\n        Only the data is moved; coordinates stay in place. Values shifted from\n        beyond array bounds are replaced by NaN. This is consistent with the\n        behavior of ``shift`` in pandas.\n\n        Parameters\n        ----------\n        shifts : Mapping with the form of {dim: offset}\n            Integer offset to shift along each of the given dimensions.\n            Positive offsets shift to the right; negative offsets shift to the\n            left.\n        fill_value: scalar, optional\n            Value to use for newly missing values\n        **shifts_kwargs:\n            The keyword arguments form of ``shifts``.\n            One of shifts or shifts_kwarg must be provided.\n\n        Returns\n        -------\n        shifted : DataArray\n            DataArray with the same coordinates and attributes but shifted\n            data.\n\n        See also\n        --------\n        roll\n\n        Examples\n        --------\n\n        >>> arr = xr.DataArray([5, 6, 7], dims='x')\n        >>> arr.shift(x=1)\n        <xarray.DataArray (x: 3)>\n        array([ nan,   5.,   6.])\n        Coordinates:\n          * x        (x) int64 0 1 2"
  },
  {
    "code": "def parse(self, rrstr):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('TF record already initialized!')\n        (su_len, su_entry_version_unused, self.time_flags,) = struct.unpack_from('=BBB', rrstr[:5], 2)\n        if su_len < 5:\n            raise pycdlibexception.PyCdlibInvalidISO('Not enough bytes in the TF record')\n        tflen = 7\n        if self.time_flags & (1 << 7):\n            tflen = 17\n        offset = 5\n        for index, fieldname in enumerate(self.FIELDNAMES):\n            if self.time_flags & (1 << index):\n                if tflen == 7:\n                    setattr(self, fieldname, dates.DirectoryRecordDate())\n                elif tflen == 17:\n                    setattr(self, fieldname, dates.VolumeDescriptorDate())\n                getattr(self, fieldname).parse(rrstr[offset:offset + tflen])\n                offset += tflen\n        self._initialized = True",
    "docstring": "Parse a Rock Ridge Time Stamp record out of a string.\n\n        Parameters:\n         rrstr - The string to parse the record out of.\n        Returns:\n         Nothing."
  },
  {
    "code": "def end_experience_collection_timer(self):\n        if self.time_start_experience_collection:\n            curr_delta = time() - self.time_start_experience_collection\n            if self.delta_last_experience_collection is None:\n                self.delta_last_experience_collection = curr_delta\n            else:\n                self.delta_last_experience_collection += curr_delta\n        self.time_start_experience_collection = None",
    "docstring": "Inform Metrics class that experience collection is done."
  },
  {
    "code": "def icon(self):\n        if isinstance(self._icon, str):\n            if QtGui.QIcon.hasThemeIcon(self._icon):\n                return QtGui.QIcon.fromTheme(self._icon)\n            else:\n                return QtGui.QIcon(self._icon)\n        elif isinstance(self._icon, tuple):\n            return QtGui.QIcon.fromTheme(self._icon[0],\n                                         QtGui.QIcon(self._icon[1]))\n        elif isinstance(self._icon, QtGui.QIcon):\n            return self._icon\n        return QtGui.QIcon()",
    "docstring": "Gets the icon file name. Read-only."
  },
  {
    "code": "def deserialize(data):\n    key = data.get('exc_path')\n    if key in registry:\n        exc_args = data.get('exc_args', ())\n        return registry[key](*exc_args)\n    exc_type = data.get('exc_type')\n    value = data.get('value')\n    return RemoteError(exc_type=exc_type, value=value)",
    "docstring": "Deserialize `data` to an exception instance.\n\n    If the `exc_path` value matches an exception registered as\n    ``deserializable``, return an instance of that exception type.\n    Otherwise, return a `RemoteError` instance describing the exception\n    that occurred."
  },
  {
    "code": "def _get_running_config(self, split=True):\n        conn = self._get_connection()\n        config = conn.get_config(source=\"running\")\n        if config:\n            root = ET.fromstring(config._raw)\n            running_config = root[0][0]\n            if split is True:\n                rgx = re.compile(\"\\r*\\n+\")\n                ioscfg = rgx.split(running_config.text)\n            else:\n                ioscfg = running_config.text\n            return ioscfg",
    "docstring": "Get the IOS XE device's current running config.\n\n        :return: Current IOS running config as multiline string"
  },
  {
    "code": "def _get_long_description(self):\n        if self.description is None:\n            return None\n        lines = [x for x in self.description.split('\\n')]\n        if len(lines) == 1:\n            return None\n        elif len(lines) >= 3 and lines[1] == '':\n            return '\\n'.join(lines[2:])\n        return self.description",
    "docstring": "Return the subsequent lines of a multiline description\n\n        Returns:\n            string: The long description, otherwise None"
  },
  {
    "code": "def _default_key_normalizer(key_class, request_context):\n    context = request_context.copy()\n    context['scheme'] = context['scheme'].lower()\n    context['host'] = context['host'].lower()\n    for key in ('headers', '_proxy_headers', '_socks_options'):\n        if key in context and context[key] is not None:\n            context[key] = frozenset(context[key].items())\n    socket_opts = context.get('socket_options')\n    if socket_opts is not None:\n        context['socket_options'] = tuple(socket_opts)\n    for key in list(context.keys()):\n        context['key_' + key] = context.pop(key)\n    for field in key_class._fields:\n        if field not in context:\n            context[field] = None\n    return key_class(**context)",
    "docstring": "Create a pool key out of a request context dictionary.\n\n    According to RFC 3986, both the scheme and host are case-insensitive.\n    Therefore, this function normalizes both before constructing the pool\n    key for an HTTPS request. If you wish to change this behaviour, provide\n    alternate callables to ``key_fn_by_scheme``.\n\n    :param key_class:\n        The class to use when constructing the key. This should be a namedtuple\n        with the ``scheme`` and ``host`` keys at a minimum.\n    :type  key_class: namedtuple\n    :param request_context:\n        A dictionary-like object that contain the context for a request.\n    :type  request_context: dict\n\n    :return: A namedtuple that can be used as a connection pool key.\n    :rtype:  PoolKey"
  },
  {
    "code": "def load_module(prefix, epoch, data_names, data_shapes):\n    sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch)\n    pred_fc = sym.get_internals()['pred_fc_output']\n    sym = mx.sym.softmax(data=pred_fc)\n    mod = mx.mod.Module(symbol=sym, context=mx.cpu(), data_names=data_names, label_names=None)\n    mod.bind(for_training=False, data_shapes=data_shapes)\n    mod.set_params(arg_params, aux_params, allow_missing=False)\n    return mod",
    "docstring": "Loads the model from checkpoint specified by prefix and epoch, binds it\n    to an executor, and sets its parameters and returns a mx.mod.Module"
  },
  {
    "code": "def check(self, spec, data):\n        path_eval = self.path_eval\n        for keypath, specvalue in spec.items():\n            if keypath.startswith('$'):\n                optext = keypath\n                checkable = data\n                args = (optext, specvalue, checkable)\n                generator = self.dispatch_operator(*args)\n            else:\n                try:\n                    checkable = path_eval(data, keypath)\n                except self.InvalidPath:\n                    return False\n                generator = self.dispatch_literal(specvalue, checkable)\n            for result in generator:\n                if not result:\n                    return False\n        return True",
    "docstring": "Given a mongo-style spec and some data or python object,\n        check whether the object complies with the spec. Fails eagerly."
  },
  {
    "code": "def bounds(self):\n        the_bounds = [np.inf, -np.inf, np.inf, -np.inf, np.inf, -np.inf]\n        def _update_bounds(bounds):\n            def update_axis(ax):\n                if bounds[ax*2] < the_bounds[ax*2]:\n                    the_bounds[ax*2] = bounds[ax*2]\n                if bounds[ax*2+1] > the_bounds[ax*2+1]:\n                    the_bounds[ax*2+1] = bounds[ax*2+1]\n            for ax in range(3):\n                update_axis(ax)\n            return\n        for actor in self._actors.values():\n            if isinstance(actor, vtk.vtkCubeAxesActor):\n                continue\n            if ( hasattr(actor, 'GetBounds') and actor.GetBounds() is not None\n                 and id(actor) != id(self.bounding_box_actor)):\n                _update_bounds(actor.GetBounds())\n        return the_bounds",
    "docstring": "Bounds of all actors present in the rendering window"
  },
  {
    "code": "def _bounds_from_array(arr, dim_name, bounds_name):\n    spacing = arr.diff(dim_name).values\n    lower = xr.DataArray(np.empty_like(arr), dims=arr.dims,\n                         coords=arr.coords)\n    lower.values[:-1] = arr.values[:-1] - 0.5*spacing\n    lower.values[-1] = arr.values[-1] - 0.5*spacing[-1]\n    upper = xr.DataArray(np.empty_like(arr), dims=arr.dims,\n                         coords=arr.coords)\n    upper.values[:-1] = arr.values[:-1] + 0.5*spacing\n    upper.values[-1] = arr.values[-1] + 0.5*spacing[-1]\n    bounds = xr.concat([lower, upper], dim='bounds')\n    return bounds.T",
    "docstring": "Get the bounds of an array given its center values.\n\n    E.g. if lat-lon grid center lat/lon values are known, but not the\n    bounds of each grid box.  The algorithm assumes that the bounds\n    are simply halfway between each pair of center values."
  },
  {
    "code": "def cluster_application(self, application_id):\n        path = '/ws/v1/cluster/apps/{appid}'.format(appid=application_id)\n        return self.request(path)",
    "docstring": "An application resource contains information about a particular\n        application that was submitted to a cluster.\n\n        :param str application_id: The application id\n        :returns: API response object with JSON data\n        :rtype: :py:class:`yarn_api_client.base.Response`"
  },
  {
    "code": "def filter(self, info, releases):\n        for version in list(releases.keys()):\n            if any(pattern.match(version) for pattern in self.patterns):\n                del releases[version]",
    "docstring": "Remove all release versions that match any of the specificed patterns."
  },
  {
    "code": "def _compute_std(self, C, stddevs, idx):\n        for stddev in stddevs:\n            stddev[idx] += C['sigma']",
    "docstring": "Compute total standard deviation, see tables 3 and 4, pages 227 and\n        228."
  },
  {
    "code": "def _read_pretrained_embeddings_file(file_uri: str,\n                                     embedding_dim: int,\n                                     vocab: Vocabulary,\n                                     namespace: str = \"tokens\") -> torch.FloatTensor:\n    file_ext = get_file_extension(file_uri)\n    if file_ext in ['.h5', '.hdf5']:\n        return _read_embeddings_from_hdf5(file_uri,\n                                          embedding_dim,\n                                          vocab, namespace)\n    return _read_embeddings_from_text_file(file_uri,\n                                           embedding_dim,\n                                           vocab, namespace)",
    "docstring": "Returns and embedding matrix for the given vocabulary using the pretrained embeddings\n    contained in the given file. Embeddings for tokens not found in the pretrained embedding file\n    are randomly initialized using a normal distribution with mean and standard deviation equal to\n    those of the pretrained embeddings.\n\n    We support two file formats:\n\n        * text format - utf-8 encoded text file with space separated fields: [word] [dim 1] [dim 2] ...\n          The text file can eventually be compressed, and even resides in an archive with multiple files.\n          If the file resides in an archive with other files, then ``embeddings_filename`` must\n          be a URI \"(archive_uri)#file_path_inside_the_archive\"\n\n        * hdf5 format - hdf5 file containing an embedding matrix in the form of a torch.Tensor.\n\n    If the filename ends with '.hdf5' or '.h5' then we load from hdf5, otherwise we assume\n    text format.\n\n    Parameters\n    ----------\n    file_uri : str, required.\n        It can be:\n\n        * a file system path or a URL of an eventually compressed text file or a zip/tar archive\n          containing a single file.\n\n        * URI of the type ``(archive_path_or_url)#file_path_inside_archive`` if the text file\n          is contained in a multi-file archive.\n\n    vocab : Vocabulary, required.\n        A Vocabulary object.\n    namespace : str, (optional, default=tokens)\n        The namespace of the vocabulary to find pretrained embeddings for.\n    trainable : bool, (optional, default=True)\n        Whether or not the embedding parameters should be optimized.\n\n    Returns\n    -------\n    A weight matrix with embeddings initialized from the read file.  The matrix has shape\n    ``(vocab.get_vocab_size(namespace), embedding_dim)``, where the indices of words appearing in\n    the pretrained embedding file are initialized to the pretrained embedding value."
  },
  {
    "code": "def update_models(new_obj, current_table, tables, relations):\n    _update_check_inputs(current_table, tables, relations)\n    _check_no_current_table(new_obj, current_table)\n    if isinstance(new_obj, Table):\n        tables_names = [t.name for t in tables]\n        _check_not_creating_duplicates(new_obj.name, tables_names, 'table', DuplicateTableException)\n        return new_obj, tables + [new_obj], relations\n    if isinstance(new_obj, Relation):\n        tables_names = [t.name for t in tables]\n        _check_colname_in_lst(new_obj.right_col, tables_names)\n        _check_colname_in_lst(new_obj.left_col, tables_names)\n        return current_table, tables, relations + [new_obj]\n    if isinstance(new_obj, Column):\n        columns_names = [c.name for c in current_table.columns]\n        _check_not_creating_duplicates(new_obj.name, columns_names, 'column', DuplicateColumnException)\n        current_table.columns.append(new_obj)\n        return current_table, tables, relations\n    msg = \"new_obj cannot be of type {}\"\n    raise ValueError(msg.format(new_obj.__class__.__name__))",
    "docstring": "Update the state of the parsing."
  },
  {
    "code": "def compress(self):\n        for ast_token in self.ast_tokens:\n            if type(ast_token) in self.dispatcher:\n                self.dispatcher[type(ast_token)](ast_token)\n            else:\n                self.dispatcher['default'](ast_token)",
    "docstring": "Main function of compression."
  },
  {
    "code": "def vm_result_update(self, payload):\n        port_id = payload.get('port_id')\n        result = payload.get('result')\n        if port_id and result:\n            params = dict(columns=dict(result=result))\n            self.update_vm_db(port_id, **params)",
    "docstring": "Update the result field in VM database.\n\n        This request comes from an agent that needs to update the result\n        in VM database to success or failure to reflect the operation's result\n        in the agent."
  },
  {
    "code": "def asxc(cls, obj):\n        if isinstance(obj, cls): return obj\n        if is_string(obj): return cls.from_name(obj)\n        raise TypeError(\"Don't know how to convert <%s:%s> to Xcfunc\" % (type(obj), str(obj)))",
    "docstring": "Convert object into Xcfunc."
  },
  {
    "code": "def xml_records(filename):\n    with Evtx(filename) as evtx:\n        for xml, record in evtx_file_xml_view(evtx.get_file_header()):\n            try:\n                yield to_lxml(xml), None\n            except etree.XMLSyntaxError as e:\n                yield xml, e",
    "docstring": "If the second return value is not None, then it is an\n      Exception encountered during parsing.  The first return value\n      will be the XML string.\n\n    @type filename str\n    @rtype: generator of (etree.Element or str), (None or Exception)"
  },
  {
    "code": "def quit(self):\n        self.script.LOG.warn(\"Abort due to user choice!\")\n        sys.exit(self.QUIT_RC)",
    "docstring": "Exit the program due to user's choices."
  },
  {
    "code": "def add_transition_list (self, list_input_symbols, state, action=None, next_state=None):\n        if next_state is None:\n            next_state = state\n        for input_symbol in list_input_symbols:\n            self.add_transition (input_symbol, state, action, next_state)",
    "docstring": "This adds the same transition for a list of input symbols.\n        You can pass a list or a string. Note that it is handy to use\n        string.digits, string.whitespace, string.letters, etc. to add\n        transitions that match character classes.\n\n        The action may be set to None in which case the process() method will\n        ignore the action and only set the next_state. The next_state may be\n        set to None in which case the current state will be unchanged."
  },
  {
    "code": "def get_compositions(self):\n        collection = JSONClientValidated('repository',\n                                         collection='Composition',\n                                         runtime=self._runtime)\n        result = collection.find(self._view_filter()).sort('_id', DESCENDING)\n        return objects.CompositionList(result, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets all ``Compositions``.\n\n        return: (osid.repository.CompositionList) - a list of\n                ``Compositions``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def rainDelay(self, dev_id, duration):\n        path = 'device/rain_delay'\n        payload = {'id': dev_id, 'duration': duration}\n        return self.rachio.put(path, payload)",
    "docstring": "Rain delay device."
  },
  {
    "code": "def parse_impl(self):\n        parser = XMLParser(encoding=str('UTF-8'))\n        element_iter = ET.iterparse(self.handle, events=(\"start\", \"end\"), parser=parser)\n        for pos, element in element_iter:\n            tag, class_attr = _tag_and_class_attr(element)\n            if tag == \"h1\" and pos == \"end\":\n                if not self.user:\n                    self.user = element.text.strip()\n            elif tag == \"div\" and \"thread\" in class_attr and pos == \"start\":\n                participants = self.parse_participants(element)\n                thread = self.parse_thread(participants, element_iter, True)\n                self.save_thread(thread)",
    "docstring": "Parses the HTML content as a stream. This is far less memory\n        intensive than loading the entire HTML file into memory, like\n        BeautifulSoup does."
  },
  {
    "code": "def items(self):\n        for word in self._dictionary.keys():\n            yield word, self._dictionary[word]",
    "docstring": "Iterator over the words in the dictionary\n\n            Yields:\n                str: The next word in the dictionary\n                int: The number of instances in the dictionary\n            Note:\n                This is the same as `dict.items()`"
  },
  {
    "code": "def set_interactive_policy(*, locals=None, banner=None, serve=None,\n                           prompt_control=None):\n    policy = InteractiveEventLoopPolicy(\n        locals=locals,\n        banner=banner,\n        serve=serve,\n        prompt_control=prompt_control)\n    asyncio.set_event_loop_policy(policy)",
    "docstring": "Use an interactive event loop by default."
  },
  {
    "code": "def get_inner_fts(elt)->List[str]:\n    \"List the inner functions of a class.\"\n    fts = []\n    for ft_name in elt.__dict__.keys():\n        if ft_name.startswith('_'): continue\n        ft = getattr(elt, ft_name)\n        if inspect.isfunction(ft): fts.append(f'{elt.__name__}.{ft_name}')\n        if inspect.ismethod(ft): fts.append(f'{elt.__name__}.{ft_name}')\n        if inspect.isclass(ft): fts += [f'{elt.__name__}.{n}' for n in get_inner_fts(ft)]\n    return fts",
    "docstring": "List the inner functions of a class."
  },
  {
    "code": "def _split_diff(merge_result, context_lines=3):\n    collect = []\n    for item in _visible_in_diff(merge_result, context_lines=context_lines):\n        if item is None:\n            if collect:\n                yield collect\n            collect = []\n        else:\n            collect.append(item)",
    "docstring": "Split diffs and context lines into groups based on None sentinel"
  },
  {
    "code": "def chk_qualifiers(self):\n        if self.name == 'id2gos':\n            return\n        for ntd in self.associations:\n            qual = ntd.Qualifier\n            assert isinstance(qual, set), '{NAME}: QUALIFIER MUST BE A LIST: {NT}'.format(\n                NAME=self.name, NT=ntd)\n            assert qual != set(['']), ntd\n            assert qual != set(['-']), ntd\n            assert 'always' not in qual, 'SPEC SAID IT WOULD BE THERE'",
    "docstring": "Check format of qualifier"
  },
  {
    "code": "def infer_enum(node, context=None):\n    enum_meta = extract_node(\n    )\n    class_node = infer_func_form(node, enum_meta, context=context, enum=True)[0]\n    return iter([class_node.instantiate_class()])",
    "docstring": "Specific inference function for enum Call node."
  },
  {
    "code": "def _post(self, q, payload='', params=''):\n        if (q[-1] == '/'): q = q[:-1]\n        headers = {'Content-Type': 'application/json'}\n        r = requests.post('{url}{q}?api_key={key}{params}'.format(url=self.url, q=q, key=self.api_key, params=params),\n                        headers=headers, data=payload)\n        ret = DotDict(r.json())\n        if (not r.ok or ('error' in ret and ret.error == True)):\n            raise Exception(r.url, r.reason, r.status_code, r.json())\n        return DotDict(r.json())",
    "docstring": "Generic POST wrapper including the api_key"
  },
  {
    "code": "def string_to_decimal(value, strict=True):\n    if is_undefined(value):\n        if strict:\n            raise ValueError('The value cannot be null')\n        return None\n    try:\n        return float(value)\n    except ValueError:\n        raise ValueError(\n            'The specified string \"%s\" does not represent an integer' % value)",
    "docstring": "Return a decimal corresponding to the string representation of a\n    number.\n\n    @param value: a string representation of an decimal number.\n\n    @param strict:  indicate whether the specified string MUST be of a\n        valid decimal number representation.\n\n    @return: the decimal value represented by the string.\n\n    @raise ValueError: if the string doesn't represent a valid decimal,\n        while the argument ``strict`` equals ``True``."
  },
  {
    "code": "def phase_progeny_by_transmission(g):\n    g = GenotypeArray(g, dtype='i1', copy=True)\n    check_ploidy(g.ploidy, 2)\n    check_min_samples(g.n_samples, 3)\n    is_phased = _opt_phase_progeny_by_transmission(g.values)\n    g.is_phased = np.asarray(is_phased).view(bool)\n    return g",
    "docstring": "Phase progeny genotypes from a trio or cross using Mendelian\n    transmission.\n\n    Parameters\n    ----------\n    g : array_like, int, shape (n_variants, n_samples, 2)\n        Genotype array, with parents as first two columns and progeny as\n        remaining columns.\n\n    Returns\n    -------\n    g : ndarray, int8, shape (n_variants, n_samples, 2)\n        Genotype array with progeny phased where possible.\n\n    Examples\n    --------\n    >>> import allel\n    >>> g = allel.GenotypeArray([\n    ...     [[0, 0], [0, 0], [0, 0]],\n    ...     [[1, 1], [1, 1], [1, 1]],\n    ...     [[0, 0], [1, 1], [0, 1]],\n    ...     [[1, 1], [0, 0], [0, 1]],\n    ...     [[0, 0], [0, 1], [0, 0]],\n    ...     [[0, 0], [0, 1], [0, 1]],\n    ...     [[0, 1], [0, 0], [0, 1]],\n    ...     [[0, 1], [0, 1], [0, 1]],\n    ...     [[0, 1], [1, 2], [0, 1]],\n    ...     [[1, 2], [0, 1], [1, 2]],\n    ...     [[0, 1], [2, 3], [0, 2]],\n    ...     [[2, 3], [0, 1], [1, 3]],\n    ...     [[0, 0], [0, 0], [-1, -1]],\n    ...     [[0, 0], [0, 0], [1, 1]],\n    ... ], dtype='i1')\n    >>> g = allel.phase_progeny_by_transmission(g)\n    >>> print(g.to_str(row_threshold=None))\n    0/0 0/0 0|0\n    1/1 1/1 1|1\n    0/0 1/1 0|1\n    1/1 0/0 1|0\n    0/0 0/1 0|0\n    0/0 0/1 0|1\n    0/1 0/0 1|0\n    0/1 0/1 0/1\n    0/1 1/2 0|1\n    1/2 0/1 2|1\n    0/1 2/3 0|2\n    2/3 0/1 3|1\n    0/0 0/0 ./.\n    0/0 0/0 1/1\n    >>> g.is_phased\n    array([[False, False,  True],\n           [False, False,  True],\n           [False, False,  True],\n           [False, False,  True],\n           [False, False,  True],\n           [False, False,  True],\n           [False, False,  True],\n           [False, False, False],\n           [False, False,  True],\n           [False, False,  True],\n           [False, False,  True],\n           [False, False,  True],\n           [False, False, False],\n           [False, False, False]])"
  },
  {
    "code": "def addReferenceSet(self, referenceSet):\n        id_ = referenceSet.getId()\n        self._referenceSetIdMap[id_] = referenceSet\n        self._referenceSetNameMap[referenceSet.getLocalId()] = referenceSet\n        self._referenceSetIds.append(id_)",
    "docstring": "Adds the specified reference set to this data repository."
  },
  {
    "code": "def add_subscription(self, channel, callback_function):\n        if channel not in CHANNELS:\n            CHANNELS.append(channel)\n            SUBSCRIPTIONS[channel] = [callback_function]\n        else:\n            SUBSCRIPTIONS[channel].append(callback_function)\n        if self._subscribed:\n            _LOGGER.info(\"New channel added after main subscribe call.\")\n            self._pubnub.subscribe().channels(channel).execute()",
    "docstring": "Add a channel to subscribe to and a callback function to\n        run when the channel receives an update.\n        If channel already exists, create a new \"subscription\"\n        and append another callback function.\n\n        Args:\n            channel (str): The channel to add a subscription too.\n            callback_function (func): The function to run on an\n                update to the passed in channel."
  },
  {
    "code": "def _debug_mode_responses(self, request, response):\n        if django.conf.settings.DEBUG_GMN:\n            if 'pretty' in request.GET:\n                response['Content-Type'] = d1_common.const.CONTENT_TYPE_TEXT\n            if (\n                'HTTP_VENDOR_PROFILE_SQL' in request.META\n                or django.conf.settings.DEBUG_PROFILE_SQL\n            ):\n                response_list = []\n                for query in django.db.connection.queries:\n                    response_list.append('{}\\n{}'.format(query['time'], query['sql']))\n                return django.http.HttpResponse(\n                    '\\n\\n'.join(response_list), d1_common.const.CONTENT_TYPE_TEXT\n                )\n        return response",
    "docstring": "Extra functionality available in debug mode.\n\n        - If pretty printed output was requested, force the content type to text. This\n          causes the browser to not try to format the output in any way.\n        - If SQL profiling is turned on, return a page with SQL query timing\n          information instead of the actual response."
  },
  {
    "code": "def _start_monitoring(self):\n        before = self._file_timestamp_info(self.path)\n        while True:\n            gevent.sleep(1)\n            after = self._file_timestamp_info(self.path)\n            added = [fname for fname in after.keys() if fname not in before.keys()]\n            removed = [fname for fname in before.keys() if fname not in after.keys()]\n            modified = []\n            for fname in before.keys():\n                if fname not in removed:\n                    if os.path.getmtime(fname) != before.get(fname):\n                        modified.append(fname)\n            if added: \n                self.on_create(added)\n            if removed: \n                self.on_delete(removed)\n            if modified: \n                self.on_modify(modified)\n            before = after",
    "docstring": "Internal method that monitors the directory for changes"
  },
  {
    "code": "def save_csv(self, filename, write_header_separately=True):\n        txt = ''\n        with open(filename, \"w\") as f:\n            if write_header_separately:\n                f.write(','.join([c for c in self.header]) + '\\n')\n            for row in self.arr:\n                txt = ','.join([self.force_to_string(col) for col in row])\n                f.write(txt + '\\n')\n            f.write('\\n')",
    "docstring": "save the default array as a CSV file"
  },
  {
    "code": "def registered(self, socket_client):\n        self._socket_client = socket_client\n        if self.target_platform:\n            self._message_func = self._socket_client.send_platform_message\n        else:\n            self._message_func = self._socket_client.send_app_message",
    "docstring": "Called when a controller is registered."
  },
  {
    "code": "def multi_select(self, elements_to_select):\n        first_element = elements_to_select.pop()\n        self.click(first_element)\n        for index, element in enumerate(elements_to_select, start=1):\n            self.multi_click(element)",
    "docstring": "Multi-select any number of elements.\n\n        :param elements_to_select: list of WebElement instances\n        :return: None"
  },
  {
    "code": "def sign_message(self, key, message, verbose=False):\n        secret_exponent = key.secret_exponent()\n        if not secret_exponent:\n            raise ValueError(\"Private key is required to sign a message\")\n        addr = key.address()\n        msg_hash = self.hash_for_signing(message)\n        is_compressed = key.is_compressed()\n        sig = self.signature_for_message_hash(secret_exponent, msg_hash, is_compressed)\n        if not verbose or message is None:\n            return sig\n        return self.signature_template.format(\n            msg=message, sig=sig, addr=addr,\n            net_name=self._network_name.upper())",
    "docstring": "Return a signature, encoded in Base64, which can be verified by anyone using the\n        public key."
  },
  {
    "code": "def custom_property_prefix_lax(instance):\n    for prop_name in instance.keys():\n        if (instance['type'] in enums.PROPERTIES and\n                prop_name not in enums.PROPERTIES[instance['type']] and\n                prop_name not in enums.RESERVED_PROPERTIES and\n                not CUSTOM_PROPERTY_LAX_PREFIX_RE.match(prop_name)):\n            yield JSONError(\"Custom property '%s' should have a type that \"\n                            \"starts with 'x_' in order to be compatible with \"\n                            \"future versions of the STIX 2 specification.\" %\n                            prop_name, instance['id'],\n                            'custom-prefix-lax')",
    "docstring": "Ensure custom properties follow lenient naming style conventions\n    for forward-compatibility.\n\n    Does not check property names in custom objects."
  },
  {
    "code": "def add_data_attribute(self, data_attr):\n        if data_attr.header.attr_type_id is not AttrTypes.DATA:\n            raise DataStreamError(\"Invalid attribute. A Datastream deals only with DATA attributes\")\n        if data_attr.header.attr_name != self.name:\n            raise DataStreamError(f\"Data from a different stream '{data_attr.header.attr_name}' cannot be add to this stream\")\n        if data_attr.header.non_resident:\n            nonr_header = data_attr.header\n            if self._data_runs is None:\n                self._data_runs = []\n            if nonr_header.end_vcn > self.cluster_count:\n                self.cluster_count = nonr_header.end_vcn\n            if not nonr_header.start_vcn:\n                self.size = nonr_header.curr_sstream\n                self.alloc_size = nonr_header.alloc_sstream\n            self._data_runs.append((nonr_header.start_vcn, nonr_header.data_runs))\n            self._data_runs_sorted = False\n        else:\n            self.size = self.alloc_size = data_attr.header.content_len\n            self._pending_processing = None\n            self._content = data_attr.content.content",
    "docstring": "Interprets a DATA attribute and add it to the datastream."
  },
  {
    "code": "def resolve(tex):\n    soup = TexSoup(tex)\n    for subimport in soup.find_all('subimport'):\n        path = subimport.args[0] + subimport.args[1]\n        subimport.replace_with(*resolve(open(path)).contents)\n    for _import in soup.find_all('import'):\n        _import.replace_with(*resolve(open(_import.args[0])).contents)\n    for include in soup.find_all('include'):\n        include.replace_with(*resolve(open(include.args[0])).contents)\n    return soup",
    "docstring": "Resolve all imports and update the parse tree.\n\n    Reads from a tex file and once finished, writes to a tex file."
  },
  {
    "code": "def authorization_code_pkce(self, client_id, code_verifier, code,\n                                redirect_uri, grant_type='authorization_code'):\n        return self.post(\n            'https://{}/oauth/token'.format(self.domain),\n            data={\n                'client_id': client_id,\n                'code_verifier': code_verifier,\n                'code': code,\n                'grant_type': grant_type,\n                'redirect_uri': redirect_uri,\n            },\n            headers={'Content-Type': 'application/json'}\n        )",
    "docstring": "Authorization code pkce grant\n\n        This is the OAuth 2.0 grant that mobile apps utilize in order to access an API.\n        Use this endpoint to exchange an Authorization Code for a Token.\n\n        Args:\n            grant_type (str): Denotes the flow you're using. For authorization code pkce\n            use authorization_code\n\n            client_id (str): your application's client Id\n\n            code_verifier (str): Cryptographically random key that was used to generate\n            the code_challenge passed to /authorize.\n\n            code (str): The Authorization Code received from the /authorize Calls\n\n            redirect_uri (str, optional): This is required only if it was set at\n            the GET /authorize endpoint. The values must match\n\n        Returns:\n            access_token, id_token"
  },
  {
    "code": "def _getReader(self, filename, scoreClass):\n        if filename.endswith('.json') or filename.endswith('.json.bz2'):\n            return JSONRecordsReader(filename, scoreClass)\n        else:\n            raise ValueError(\n                'Unknown DIAMOND record file suffix for file %r.' % filename)",
    "docstring": "Obtain a JSON record reader for DIAMOND records.\n\n        @param filename: The C{str} file name holding the JSON.\n        @param scoreClass: A class to hold and compare scores (see scores.py)."
  },
  {
    "code": "def analysis_error(sender, exception, message):\n    LOGGER.exception(message)\n    message = get_error_message(exception, context=message)\n    send_error_message(sender, message)",
    "docstring": "A helper to spawn an error and halt processing.\n\n    An exception will be logged, busy status removed and a message\n    displayed.\n\n    .. versionadded:: 3.3\n\n    :param sender: The sender.\n    :type sender: object\n\n    :param message: an ErrorMessage to display\n    :type message: ErrorMessage, Message\n\n    :param exception: An exception that was raised\n    :type exception: Exception"
  },
  {
    "code": "def read_index(group, version='1.1'):\n    if version == '0.1':\n        return np.int64(group['index'][...])\n    elif version == '1.0':\n        return group['file_index'][...]\n    else:\n        return group['index'][...]",
    "docstring": "Return the index stored in a h5features group.\n\n    :param h5py.Group group: The group to read the index from.\n    :param str version: The h5features version of the `group`.\n    :return: a 1D numpy array of features indices."
  },
  {
    "code": "def parse_mark_duplicate_metrics(fn):\n    with open(fn) as f:\n        lines = [x.strip().split('\\t') for x in f.readlines()]\n    metrics = pd.Series(lines[7], lines[6])\n    m = pd.to_numeric(metrics[metrics.index[1:]])\n    metrics[m.index] = m.values\n    vals = np.array(lines[11:-1])\n    hist = pd.Series(vals[:, 1], index=[int(float(x)) for x in vals[:, 0]])\n    hist = pd.to_numeric(hist)\n    return metrics, hist",
    "docstring": "Parse the output from Picard's MarkDuplicates and return as pandas\n    Series.\n\n    Parameters\n    ----------\n    filename : str of filename or file handle\n        Filename of the Picard output you want to parse.\n\n    Returns\n    -------\n    metrics : pandas.Series\n        Duplicate metrics.\n\n    hist : pandas.Series\n        Duplicate histogram."
  },
  {
    "code": "def get(remote_path,\n        local_path='',\n        recursive=False,\n        preserve_times=False,\n        **kwargs):\n    scp_client = _prepare_connection(**kwargs)\n    get_kwargs = {\n        'recursive': recursive,\n        'preserve_times': preserve_times\n    }\n    if local_path:\n        get_kwargs['local_path'] = local_path\n    return scp_client.get(remote_path, **get_kwargs)",
    "docstring": "Transfer files and directories from remote host to the localhost of the\n    Minion.\n\n    remote_path\n        Path to retrieve from remote host. Since this is evaluated by scp on the\n        remote host, shell wildcards and environment variables may be used.\n\n    recursive: ``False``\n        Transfer files and directories recursively.\n\n    preserve_times: ``False``\n        Preserve ``mtime`` and ``atime`` of transferred files and directories.\n\n    hostname\n        The hostname of the remote device.\n\n    port: ``22``\n        The port of the remote device.\n\n    username\n        The username required for SSH authentication on the device.\n\n    password\n        Used for password authentication. It is also used for private key\n        decryption if ``passphrase`` is not given.\n\n    passphrase\n        Used for decrypting private keys.\n\n    pkey\n        An optional private key to use for authentication.\n\n    key_filename\n        The filename, or list of filenames, of optional private key(s) and/or\n        certificates to try for authentication.\n\n    timeout\n        An optional timeout (in seconds) for the TCP connect.\n\n    socket_timeout: ``10``\n        The channel socket timeout in seconds.\n\n    buff_size: ``16384``\n        The size of the SCP send buffer.\n\n    allow_agent: ``True``\n        Set to ``False`` to disable connecting to the SSH agent.\n\n    look_for_keys: ``True``\n        Set to ``False`` to disable searching for discoverable private key\n        files in ``~/.ssh/``\n\n    banner_timeout\n        An optional timeout (in seconds) to wait for the SSH banner to be\n        presented.\n\n    auth_timeout\n        An optional timeout (in seconds) to wait for an authentication\n        response.\n\n    auto_add_policy: ``False``\n        Automatically add the host to the ``known_hosts``.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' scp.get /var/tmp/file /tmp/file hostname=10.10.10.1 auto_add_policy=True"
  },
  {
    "code": "def bleu_score(logits, labels):\n  predictions = tf.to_int32(tf.argmax(logits, axis=-1))\n  bleu = tf.py_func(compute_bleu, (labels, predictions), tf.float32)\n  return bleu, tf.constant(1.0)",
    "docstring": "Approximate BLEU score computation between labels and predictions.\n\n  An approximate BLEU scoring method since we do not glue word pieces or\n  decode the ids and tokenize the output. By default, we use ngram order of 4\n  and use brevity penalty. Also, this does not have beam search.\n\n  Args:\n    logits: Tensor of size [batch_size, length_logits, vocab_size]\n    labels: Tensor of size [batch-size, length_labels]\n\n  Returns:\n    bleu: int, approx bleu score"
  },
  {
    "code": "def list_lbaas_members(self, lbaas_pool, retrieve_all=True, **_params):\n        return self.list('members', self.lbaas_members_path % lbaas_pool,\n                         retrieve_all, **_params)",
    "docstring": "Fetches a list of all lbaas_members for a project."
  },
  {
    "code": "def list_objects(self, instance, bucket_name, prefix=None, delimiter=None):\n        url = '/buckets/{}/{}'.format(instance, bucket_name)\n        params = {}\n        if prefix is not None:\n            params['prefix'] = prefix\n        if delimiter is not None:\n            params['delimiter'] = delimiter\n        response = self._client.get_proto(path=url, params=params)\n        message = rest_pb2.ListObjectsResponse()\n        message.ParseFromString(response.content)\n        return ObjectListing(message, instance, bucket_name, self)",
    "docstring": "List the objects for a bucket.\n\n        :param str instance: A Yamcs instance name.\n        :param str bucket_name: The name of the bucket.\n        :param str prefix: If specified, only objects that start with this\n                           prefix are listed.\n        :param str delimiter: If specified, return only objects whose name\n                              do not contain the delimiter after the prefix.\n                              For the other objects, the response contains\n                              (in the prefix response parameter) the name\n                              truncated after the delimiter. Duplicates are\n                              omitted."
  },
  {
    "code": "def get_affected_box(self, src):\n        mag = src.get_min_max_mag()[1]\n        maxdist = self(src.tectonic_region_type, mag)\n        bbox = get_bounding_box(src, maxdist)\n        return (fix_lon(bbox[0]), bbox[1], fix_lon(bbox[2]), bbox[3])",
    "docstring": "Get the enlarged bounding box of a source.\n\n        :param src: a source object\n        :returns: a bounding box (min_lon, min_lat, max_lon, max_lat)"
  },
  {
    "code": "def info(*messages):\n    sys.stderr.write(\"%s.%s: \" % get_caller_info())\n    sys.stderr.write(' '.join(map(str, messages)))\n    sys.stderr.write('\\n')",
    "docstring": "Prints the current GloTK module and a `message`.\n    Taken from biolite"
  },
  {
    "code": "def send_request(req_cat, con, req_str, kwargs):\n        try:\n                kwargs = parse.urlencode(kwargs)\n        except:\n                kwargs = urllib.urlencode(kwargs)\n        try:\n            con.request(req_cat, req_str, kwargs)\n        except httplib.CannotSendRequest:\n            con = create()\n            con.request(req_cat, req_str, kwargs)\n        try:\n            res = con.getresponse().read()\n        except (IOError, httplib.BadStatusLine):\n            con = create()\n            con.request(req_cat, req_str, kwargs) \n            res = con.getresponse().read()  \n        t = type(res)\n        if type(res) == t:\n                res = bytes.decode(res)\n        return json.loads(res)",
    "docstring": "Sends request to facebook graph\n\tReturns the facebook-json response converted to python object"
  },
  {
    "code": "def move_to_limit(self, position):\n        cmd = 'MOVE', [Float, Integer]\n        self._write(cmd, position, 1)",
    "docstring": "Move to limit switch and define it as position.\n\n        :param position: The new position of the limit switch."
  },
  {
    "code": "def write_data(self, write_finished_cb):\n        self._write_finished_cb = write_finished_cb\n        data = bytearray()\n        for poly4D in self.poly4Ds:\n            data += struct.pack('<ffffffff', *poly4D.x.values)\n            data += struct.pack('<ffffffff', *poly4D.y.values)\n            data += struct.pack('<ffffffff', *poly4D.z.values)\n            data += struct.pack('<ffffffff', *poly4D.yaw.values)\n            data += struct.pack('<f', poly4D.duration)\n        self.mem_handler.write(self, 0x00, data, flush_queue=True)",
    "docstring": "Write trajectory data to the Crazyflie"
  },
  {
    "code": "def _document_path(self):\n        if self._document_path_internal is None:\n            if self._client is None:\n                raise ValueError(\"A document reference requires a `client`.\")\n            self._document_path_internal = _get_document_path(self._client, self._path)\n        return self._document_path_internal",
    "docstring": "Create and cache the full path for this document.\n\n        Of the form:\n\n            ``projects/{project_id}/databases/{database_id}/...\n                  documents/{document_path}``\n\n        Returns:\n            str: The full document path.\n\n        Raises:\n            ValueError: If the current document reference has no ``client``."
  },
  {
    "code": "def getChecks(self, **parameters):\n        for key in parameters:\n            if key not in ['limit', 'offset', 'tags']:\n                sys.stderr.write('%s not a valid argument for getChecks()\\n'\n                                 % key)\n        response = self.request('GET', 'checks', parameters)\n        return [PingdomCheck(self, x) for x in response.json()['checks']]",
    "docstring": "Pulls all checks from pingdom\n\n        Optional Parameters:\n\n            * limit -- Limits the number of returned probes to the\n                specified quantity.\n                    Type: Integer (max 25000)\n                    Default: 25000\n\n            * offset -- Offset for listing (requires limit.)\n                    Type: Integer\n                    Default: 0\n\n            * tags -- Filter listing by tag/s\n                    Type: String\n                    Default: None"
  },
  {
    "code": "def get_size(self, chrom=None):\n        if len(self.size) == 0:\n            raise LookupError(\"no chromosomes in index, is the index correct?\")\n        if chrom:\n            if chrom in self.size:\n                return self.size[chrom]\n            else: \n                raise KeyError(\"chromosome {} not in index\".format(chrom))\n        total = 0\n        for size in self.size.values():\n            total += size\n        return total",
    "docstring": "Return the sizes of all sequences in the index, or the size of chrom if specified\n        as an optional argument"
  },
  {
    "code": "def _drop_no_label_results(self, results, fh):\n        results.seek(0)\n        results = Results(results, self._tokenizer)\n        results.remove_label(self._no_label)\n        results.csv(fh)",
    "docstring": "Writes `results` to `fh` minus those results associated with the\n        'no' label.\n\n        :param results: results to be manipulated\n        :type results: file-like object\n        :param fh: output destination\n        :type fh: file-like object"
  },
  {
    "code": "def constant_outfile_iterator(outfiles, infiles, arggroups):\n    assert len(infiles) == 1\n    assert len(arggroups) == 1\n    return ((outfile, infiles[0], arggroups[0]) for outfile in outfiles)",
    "docstring": "Iterate over all output files."
  },
  {
    "code": "def _add_model(self, model_list_or_dict, core_element, model_class, model_key=None, load_meta_data=True):\n        found_model = self._get_future_expected_model(core_element)\n        if found_model:\n            found_model.parent = self\n        if model_class is IncomeModel:\n            self.income = found_model if found_model else IncomeModel(core_element, self)\n            return\n        if model_key is None:\n            model_list_or_dict.append(found_model if found_model else model_class(core_element, self))\n        else:\n            model_list_or_dict[model_key] = found_model if found_model else model_class(core_element, self,\n                                                                                        load_meta_data=load_meta_data)",
    "docstring": "Adds one model for a given core element.\n\n        The method will add a model for a given core object and checks if there is a corresponding model object in the\n        future expected model list. The method does not check if an object with corresponding model has already been\n        inserted.\n\n        :param model_list_or_dict:  could be a list or dictionary of one model type\n        :param core_element: the core element to a model for, can be state or state element\n        :param model_class: model-class of the elements that should be insert\n        :param model_key: if model_list_or_dict is a dictionary the key is the id of the respective element\n                          (e.g. 'state_id')\n        :param load_meta_data: specific argument for loading meta data\n        :return:"
  },
  {
    "code": "def _add_numeric_methods_unary(cls):\n        def _make_evaluate_unary(op, opstr):\n            def _evaluate_numeric_unary(self):\n                self._validate_for_numeric_unaryop(op, opstr)\n                attrs = self._get_attributes_dict()\n                attrs = self._maybe_update_attributes(attrs)\n                return Index(op(self.values), **attrs)\n            _evaluate_numeric_unary.__name__ = opstr\n            return _evaluate_numeric_unary\n        cls.__neg__ = _make_evaluate_unary(operator.neg, '__neg__')\n        cls.__pos__ = _make_evaluate_unary(operator.pos, '__pos__')\n        cls.__abs__ = _make_evaluate_unary(np.abs, '__abs__')\n        cls.__inv__ = _make_evaluate_unary(lambda x: -x, '__inv__')",
    "docstring": "Add in numeric unary methods."
  },
  {
    "code": "def clean():\n        screenshot_dir = settings.SELENIUM_SCREENSHOT_DIR\n        if screenshot_dir and os.path.isdir(screenshot_dir):\n            rmtree(screenshot_dir, ignore_errors=True)",
    "docstring": "Clear out any old screenshots"
  },
  {
    "code": "def getXmlText (parent, tag):\n    elem = parent.getElementsByTagName(tag)[0]\n    rc = []\n    for node in elem.childNodes:\n        if node.nodeType == node.TEXT_NODE:\n            rc.append(node.data)\n    return ''.join(rc)",
    "docstring": "Return XML content of given tag in parent element."
  },
  {
    "code": "def ext_pillar(minion_id,\n               pillar,\n               *args,\n               **kwargs):\n    return MySQLExtPillar().fetch(minion_id, pillar, *args, **kwargs)",
    "docstring": "Execute queries against MySQL, merge and return as a dict"
  },
  {
    "code": "def obj_name(self, obj: Union[str, Element]) -> str:\n        if isinstance(obj, str):\n            obj = self.obj_for(obj)\n        if isinstance(obj, SlotDefinition):\n            return underscore(self.aliased_slot_name(obj))\n        else:\n            return camelcase(obj if isinstance(obj, str) else obj.name)",
    "docstring": "Return the formatted name used for the supplied definition"
  },
  {
    "code": "def deactivate(profile='default'):\n    with jconfig(profile) as config:\n        deact = True;\n        if not getattr(config.NotebookApp.contents_manager_class, 'startswith',lambda x:False)('jupyterdrive'):\n            deact=False\n        if 'gdrive' not in getattr(config.NotebookApp.tornado_settings,'get', lambda _,__:'')('contents_js_source',''):\n            deact=False\n        if deact:\n            del config['NotebookApp']['tornado_settings']['contents_js_source']\n            del config['NotebookApp']['contents_manager_class']",
    "docstring": "should be a matter of just unsetting the above keys"
  },
  {
    "code": "def git_hash(blob):\n    head = str(\"blob \" + str(len(blob)) + \"\\0\").encode(\"utf-8\")\n    return sha1(head + blob).hexdigest()",
    "docstring": "Return git-hash compatible SHA-1 hexdigits for a blob of data."
  },
  {
    "code": "def handle_data(self, data):\n        if self.current_parent_element['tag'] == '':\n            self.cleaned_html += '<p>'\n            self.current_parent_element['tag'] = 'p'\n        self.cleaned_html += data",
    "docstring": "Called by HTMLParser.feed when text is found."
  },
  {
    "code": "def age(self, minimum: int = 16, maximum: int = 66) -> int:\n        age = self.random.randint(minimum, maximum)\n        self._store['age'] = age\n        return age",
    "docstring": "Get a random integer value.\n\n        :param maximum: Maximum value of age.\n        :param minimum: Minimum value of age.\n        :return: Random integer.\n\n        :Example:\n            23."
  },
  {
    "code": "def read_wait_cell(self):\n        table_state = self.bt_table.read_row(\n            TABLE_STATE,\n            filter_=bigtable_row_filters.ColumnRangeFilter(\n                METADATA, WAIT_CELL, WAIT_CELL))\n        if table_state is None:\n            utils.dbg('No waiting for new games needed; '\n                      'wait_for_game_number column not in table_state')\n            return None\n        value = table_state.cell_value(METADATA, WAIT_CELL)\n        if not value:\n            utils.dbg('No waiting for new games needed; '\n                      'no value in wait_for_game_number cell '\n                      'in table_state')\n            return None\n        return cbt_intvalue(value)",
    "docstring": "Read the value of the cell holding the 'wait' value,\n\n        Returns the int value of whatever it has, or None if the cell doesn't\n        exist."
  },
  {
    "code": "def initialize(config):\n\t\"Initialize the bot with a dictionary of config items\"\n\tconfig = init_config(config)\n\t_setup_logging()\n\t_load_library_extensions()\n\tif not Handler._registry:\n\t\traise RuntimeError(\"No handlers registered\")\n\tclass_ = _load_bot_class()\n\tconfig.setdefault('log_channels', [])\n\tconfig.setdefault('other_channels', [])\n\tchannels = config.log_channels + config.other_channels\n\tlog.info('Running with config')\n\tlog.info(pprint.pformat(config))\n\thost = config.get('server_host', 'localhost')\n\tport = config.get('server_port', 6667)\n\treturn class_(\n\t\thost,\n\t\tport,\n\t\tconfig.bot_nickname,\n\t\tchannels=channels,\n\t\tpassword=config.get('password'),\n\t)",
    "docstring": "Initialize the bot with a dictionary of config items"
  },
  {
    "code": "def assert_is_not(first, second, msg_fmt=\"{msg}\"):\n    if first is second:\n        msg = \"both arguments refer to {!r}\".format(first)\n        fail(msg_fmt.format(msg=msg, first=first, second=second))",
    "docstring": "Fail if first and second refer to the same object.\n\n    >>> list1 = [5, \"foo\"]\n    >>> list2 = [5, \"foo\"]\n    >>> assert_is_not(list1, list2)\n    >>> assert_is_not(list1, list1)\n    Traceback (most recent call last):\n        ...\n    AssertionError: both arguments refer to [5, 'foo']\n\n    The following msg_fmt arguments are supported:\n    * msg - the default error message\n    * first - the first argument\n    * second - the second argument"
  },
  {
    "code": "def set_attribute(self, app, key, value):\n        path = 'setattribute/' + parse.quote(app, '') + '/' + parse.quote(\n            self._encode_string(key), '')\n        res = self._make_ocs_request(\n            'POST',\n            self.OCS_SERVICE_PRIVATEDATA,\n            path,\n            data={'value': self._encode_string(value)}\n        )\n        if res.status_code == 200:\n            tree = ET.fromstring(res.content)\n            self._check_ocs_status(tree)\n            return True\n        raise HTTPResponseError(res)",
    "docstring": "Sets an application attribute\n\n        :param app: application id\n        :param key: key of the attribute to set\n        :param value: value to set\n        :returns: True if the operation succeeded, False otherwise\n        :raises: HTTPResponseError in case an HTTP error status was returned"
  },
  {
    "code": "def token_auth(self, token):\n        if not token:\n            return\n        self.headers.update({\n            'Authorization': 'token {0}'.format(token)\n            })\n        self.auth = None",
    "docstring": "Use an application token for authentication.\n\n        :param str token: Application token retrieved from GitHub's\n            /authorizations endpoint"
  },
  {
    "code": "def run(toolkit_name, options, verbose=True, show_progress=False):\n    unity = glconnect.get_unity()\n    if (not verbose):\n        glconnect.get_server().set_log_progress(False)\n    (success, message, params) = unity.run_toolkit(toolkit_name, options)\n    if (len(message) > 0):\n        logging.getLogger(__name__).error(\"Toolkit error: \" + message)\n    glconnect.get_server().set_log_progress(True)\n    if success:\n        return params\n    else:\n        raise ToolkitError(str(message))",
    "docstring": "Internal function to execute toolkit on the turicreate server.\n\n    Parameters\n    ----------\n    toolkit_name : string\n        The name of the toolkit.\n\n    options : dict\n        A map containing the required input for the toolkit function,\n        for example: {'graph': g, 'reset_prob': 0.15}.\n\n    verbose : bool\n        If true, enable progress log from server.\n\n    show_progress : bool\n        If true, display progress plot.\n\n    Returns\n    -------\n    out : dict\n        The toolkit specific model parameters.\n\n    Raises\n    ------\n    RuntimeError\n        Raises RuntimeError if the server fail executing the toolkit."
  },
  {
    "code": "def build_tensor_serving_input_receiver_fn(shape, dtype=tf.float32,\n                                           batch_size=1):\n  def serving_input_receiver_fn():\n    features = tf.placeholder(\n        dtype=dtype, shape=[batch_size] + shape, name='input_tensor')\n    return tf.estimator.export.TensorServingInputReceiver(\n        features=features, receiver_tensors=features)\n  return serving_input_receiver_fn",
    "docstring": "Returns a input_receiver_fn that can be used during serving.\n\n  This expects examples to come through as float tensors, and simply\n  wraps them as TensorServingInputReceivers.\n\n  Arguably, this should live in tf.estimator.export. Testing here first.\n\n  Args:\n    shape: list representing target size of a single example.\n    dtype: the expected datatype for the input example\n    batch_size: number of input tensors that will be passed for prediction\n\n  Returns:\n    A function that itself returns a TensorServingInputReceiver."
  },
  {
    "code": "def minmax_candidates(self):\n        from numpy.polynomial import Polynomial as P\n        p = P.fromroots(self.roots)\n        return p.deriv(1).roots()",
    "docstring": "Get points where derivative is zero.\n\n        Useful for computing the extrema of the polynomial over an interval if\n        the polynomial has real roots. In this case, the maximum is attained\n        for one of the interval endpoints or a point from the result of this\n        function that is contained in the interval."
  },
  {
    "code": "def strip_path_prefix(ipath, prefix):\n    if prefix is None:\n        return ipath\n    return ipath[len(prefix):] if ipath.startswith(prefix) else ipath",
    "docstring": "Strip prefix from path.\n\n    Args:\n        ipath: input path\n        prefix: the prefix to remove, if it is found in :ipath:\n\n    Examples:\n        >>> strip_path_prefix(\"/foo/bar\", \"/bar\")\n        '/foo/bar'\n        >>> strip_path_prefix(\"/foo/bar\", \"/\")\n        'foo/bar'\n        >>> strip_path_prefix(\"/foo/bar\", \"/foo\")\n        '/bar'\n        >>> strip_path_prefix(\"/foo/bar\", \"None\")\n        '/foo/bar'"
  },
  {
    "code": "def from_uci(cls, uci: str) -> \"Move\":\n        if uci == \"0000\":\n            return cls.null()\n        elif len(uci) == 4 and \"@\" == uci[1]:\n            drop = PIECE_SYMBOLS.index(uci[0].lower())\n            square = SQUARE_NAMES.index(uci[2:])\n            return cls(square, square, drop=drop)\n        elif len(uci) == 4:\n            return cls(SQUARE_NAMES.index(uci[0:2]), SQUARE_NAMES.index(uci[2:4]))\n        elif len(uci) == 5:\n            promotion = PIECE_SYMBOLS.index(uci[4])\n            return cls(SQUARE_NAMES.index(uci[0:2]), SQUARE_NAMES.index(uci[2:4]), promotion=promotion)\n        else:\n            raise ValueError(\"expected uci string to be of length 4 or 5: {!r}\".format(uci))",
    "docstring": "Parses an UCI string.\n\n        :raises: :exc:`ValueError` if the UCI string is invalid."
  },
  {
    "code": "def deunicode(item):\n    if item is None:\n        return None\n    if isinstance(item, str):\n        return item\n    if isinstance(item, six.text_type):\n        return item.encode('utf-8')\n    if isinstance(item, dict):\n        return {\n            deunicode(key): deunicode(value)\n            for (key, value) in item.items()\n        }\n    if isinstance(item, list):\n        return [deunicode(x) for x in item]\n    raise TypeError('Unhandled item type: {!r}'.format(item))",
    "docstring": "Convert unicode objects to str"
  },
  {
    "code": "def badRequestMethod(self, environ, start_response):\n        response = \"400 Bad Request\\n\\nTo access this PyAMF gateway you \" \\\n            \"must use POST requests (%s received)\" % environ['REQUEST_METHOD']\n        start_response('400 Bad Request', [\n            ('Content-Type', 'text/plain'),\n            ('Content-Length', str(len(response))),\n            ('Server', gateway.SERVER_NAME),\n        ])\n        return [response]",
    "docstring": "Return HTTP 400 Bad Request."
  },
  {
    "code": "def complete_event(self, event_id: str):\n        event_ids = DB.get_list(self._processed_key)\n        if event_id not in event_ids:\n            raise KeyError('Unable to complete event. Event {} has not been '\n                           'processed (ie. it is not in the processed '\n                           'list).'.format(event_id))\n        DB.remove_from_list(self._processed_key, event_id, pipeline=True)\n        key = _keys.completed_events(self._object_type, self._subscriber)\n        DB.append_to_list(key, event_id, pipeline=True)\n        DB.execute()",
    "docstring": "Complete the specified event."
  },
  {
    "code": "def check_archive_format (format, compression):\n    if format not in ArchiveFormats:\n        raise util.PatoolError(\"unknown archive format `%s'\" % format)\n    if compression is not None and compression not in ArchiveCompressions:\n        raise util.PatoolError(\"unkonwn archive compression `%s'\" % compression)",
    "docstring": "Make sure format and compression is known."
  },
  {
    "code": "def get_full_alias(self, query):\n        if query in self.alias_table.sections():\n            return query\n        return next((section for section in self.alias_table.sections() if section.split()[0] == query), '')",
    "docstring": "Get the full alias given a search query.\n\n        Args:\n            query: The query this function performs searching on.\n\n        Returns:\n            The full alias (with the placeholders, if any)."
  },
  {
    "code": "def _create_handler(self, config):\n        if config is None:\n            raise ValueError('No handler config to create handler from.')\n        if 'name' not in config:\n            raise ValueError('Handler name is required.')\n        handler_name = config['name']\n        module_name = handler_name.rsplit('.', 1)[0]\n        class_name = handler_name.rsplit('.', 1)[-1]\n        module = import_module(module_name)\n        handler_class = getattr(module, class_name)\n        instance = handler_class(**config)\n        return instance",
    "docstring": "Creates a handler from its config.\n\n        Params:\n            config:      handler config\n        Returns:\n            handler instance"
  },
  {
    "code": "def print_variable(obj, **kwargs):\n    variable_print_length = kwargs.get(\"variable_print_length\", 1000)\n    s = str(obj)\n    if len(s) < 300:\n        return \"Printing the object:\\n\" + str(obj)\n    else:\n        return \"Printing the object:\\n\" + str(obj)[:variable_print_length] + ' ...'",
    "docstring": "Print the variable out. Limit the string length to, by default, 300 characters."
  },
  {
    "code": "def assertTimeZoneIsNotNone(self, dt, msg=None):\n        if not isinstance(dt, datetime):\n            raise TypeError('First argument is not a datetime object')\n        self.assertIsNotNone(dt.tzinfo, msg=msg)",
    "docstring": "Fail unless ``dt`` has a non-null ``tzinfo`` attribute.\n\n        Parameters\n        ----------\n        dt : datetime\n        msg : str\n            If not provided, the :mod:`marbles.mixins` or\n            :mod:`unittest` standard message will be used.\n\n        Raises\n        ------\n        TypeError\n            If ``dt`` is not a datetime object."
  },
  {
    "code": "def minimize_core(self):\n        if self.minz and len(self.core) > 1:\n            self.core = sorted(self.core, key=lambda l: self.wght[l])\n            self.oracle.conf_budget(1000)\n            i = 0\n            while i < len(self.core):\n                to_test = self.core[:i] + self.core[(i + 1):]\n                if self.oracle.solve_limited(assumptions=to_test) == False:\n                    self.core = to_test\n                else:\n                    i += 1",
    "docstring": "Reduce a previously extracted core and compute an\n            over-approximation of an MUS. This is done using the\n            simple deletion-based MUS extraction algorithm.\n\n            The idea is to try to deactivate soft clauses of the\n            unsatisfiable core one by one while checking if the\n            remaining soft clauses together with the hard part of the\n            formula are unsatisfiable. Clauses that are necessary for\n            preserving unsatisfiability comprise an MUS of the input\n            formula (it is contained in the given unsatisfiable core)\n            and are reported as a result of the procedure.\n\n            During this core minimization procedure, all SAT calls are\n            dropped after obtaining 1000 conflicts."
  },
  {
    "code": "def parse_class(val):\n    module, class_name = val.rsplit('.', 1)\n    module = importlib.import_module(module)\n    try:\n        return getattr(module, class_name)\n    except AttributeError:\n        raise ValueError('\"%s\" is not a valid member of %s' % (\n            class_name, qualname(module))\n        )",
    "docstring": "Parse a string, imports the module and returns the class.\n\n    >>> parse_class('hashlib.md5')\n    <built-in function openssl_md5>"
  },
  {
    "code": "def get_abbreviation_of(self, name):\n        for language in self.user_data.languages:\n            if language['language_string'] == name:\n                return language['language']\n        return None",
    "docstring": "Get abbreviation of a language."
  },
  {
    "code": "def _apply_args_to_func(global_args, func):\n    global_args = vars(global_args)\n    local_args = dict()\n    for argument in inspect.getargspec(func).args:\n        local_args[argument] = global_args[argument]\n    return func(**local_args)",
    "docstring": "Unpacks the argparse Namespace object and applies its\n    contents as normal arguments to the function func"
  },
  {
    "code": "def _exec(self, query, **kwargs):\n        variables = {'entity': self.username,\n                     'project': self.project, 'name': self.name}\n        variables.update(kwargs)\n        return self.client.execute(query, variable_values=variables)",
    "docstring": "Execute a query against the cloud backend"
  },
  {
    "code": "def _open_file_obj(f, mode=\"r\"):\n    if isinstance(f, six.string_types):\n        if f.startswith((\"http://\", \"https://\")):\n            file_obj = _urlopen(f)\n            yield file_obj\n            file_obj.close()\n        else:\n            with open(f, mode) as file_obj:\n                yield file_obj\n    else:\n        yield f",
    "docstring": "A context manager that provides access to a file.\n\n    :param f: the file to be opened\n    :type f: a file-like object or path to file\n    :param mode: how to open the file\n    :type mode: string"
  },
  {
    "code": "def format_auto_patching_settings(result):\n    from collections import OrderedDict\n    order_dict = OrderedDict()\n    if result.enable is not None:\n        order_dict['enable'] = result.enable\n    if result.day_of_week is not None:\n        order_dict['dayOfWeek'] = result.day_of_week\n    if result.maintenance_window_starting_hour is not None:\n        order_dict['maintenanceWindowStartingHour'] = result.maintenance_window_starting_hour\n    if result.maintenance_window_duration is not None:\n        order_dict['maintenanceWindowDuration'] = result.maintenance_window_duration\n    return order_dict",
    "docstring": "Formats the AutoPatchingSettings object removing arguments that are empty"
  },
  {
    "code": "def split_join_classification(element, classification_labels, nodes_classification):\n        classification_join = \"Join\"\n        classification_split = \"Split\"\n        if len(element[1][consts.Consts.incoming_flow]) >= 2:\n            classification_labels.append(classification_join)\n        if len(element[1][consts.Consts.outgoing_flow]) >= 2:\n            classification_labels.append(classification_split)\n        nodes_classification[element[0]] = classification_labels",
    "docstring": "Add the \"Split\", \"Join\" classification, if the element qualifies for.\n\n        :param element: an element from BPMN diagram,\n        :param classification_labels: list of labels attached to the element,\n        :param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels."
  },
  {
    "code": "def TP0(dv, u):\n    return np.linalg.norm(np.array(dv)) + np.linalg.norm(np.array(u))",
    "docstring": "Demo problem 0 for horsetail matching, takes two input vectors of any size\n    and returns a single output"
  },
  {
    "code": "def convert(value, source_unit, target_unit, fmt=False):\n    orig_target_unit = target_unit\n    source_unit = functions.value_for_key(INFORMATION_UNITS, source_unit)\n    target_unit = functions.value_for_key(INFORMATION_UNITS, target_unit)\n    q = ureg.Quantity(value, source_unit)\n    q = q.to(ureg.parse_expression(target_unit))\n    value = functions.format_value(q.magnitude) if fmt else q.magnitude\n    return value, orig_target_unit",
    "docstring": "Converts value from source_unit to target_unit.\n\n    Returns a tuple containing the converted value and target_unit.\n    Having fmt set to True causes the value to be formatted to 1 decimal digit\n    if it's a decimal or be formatted as integer if it's an integer.\n\n    E.g:\n\n    >>> convert(2, 'hr', 'min')\n    (120.0, 'min')\n    >>> convert(2, 'hr', 'min', fmt=True)\n    (120, 'min')\n    >>> convert(30, 'min', 'hr', fmt=True)\n    (0.5, 'hr')"
  },
  {
    "code": "def generic_service_exception(*args):\n        exception_tuple = LambdaErrorResponses.ServiceException\n        return BaseLocalService.service_response(\n            LambdaErrorResponses._construct_error_response_body(LambdaErrorResponses.SERVICE_ERROR, \"ServiceException\"),\n            LambdaErrorResponses._construct_headers(exception_tuple[0]),\n            exception_tuple[1]\n        )",
    "docstring": "Creates a Lambda Service Generic ServiceException Response\n\n        Parameters\n        ----------\n        args list\n            List of arguments Flask passes to the method\n\n        Returns\n        -------\n        Flask.Response\n            A response object representing the GenericServiceException Error"
  },
  {
    "code": "def save_method_args(method):\n\targs_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')\n\t@functools.wraps(method)\n\tdef wrapper(self, *args, **kwargs):\n\t\tattr_name = '_saved_' + method.__name__\n\t\tattr = args_and_kwargs(args, kwargs)\n\t\tsetattr(self, attr_name, attr)\n\t\treturn method(self, *args, **kwargs)\n\treturn wrapper",
    "docstring": "Wrap a method such that when it is called, the args and kwargs are\n\tsaved on the method.\n\n\t>>> class MyClass:\n\t...     @save_method_args\n\t...     def method(self, a, b):\n\t...         print(a, b)\n\t>>> my_ob = MyClass()\n\t>>> my_ob.method(1, 2)\n\t1 2\n\t>>> my_ob._saved_method.args\n\t(1, 2)\n\t>>> my_ob._saved_method.kwargs\n\t{}\n\t>>> my_ob.method(a=3, b='foo')\n\t3 foo\n\t>>> my_ob._saved_method.args\n\t()\n\t>>> my_ob._saved_method.kwargs == dict(a=3, b='foo')\n\tTrue\n\n\tThe arguments are stored on the instance, allowing for\n\tdifferent instance to save different args.\n\n\t>>> your_ob = MyClass()\n\t>>> your_ob.method({str('x'): 3}, b=[4])\n\t{'x': 3} [4]\n\t>>> your_ob._saved_method.args\n\t({'x': 3},)\n\t>>> my_ob._saved_method.args\n\t()"
  },
  {
    "code": "def on_core_metadata_event(self, event):\n    core_metadata = json.loads(event.log_message.message)\n    input_names = ','.join(core_metadata['input_names'])\n    output_names = ','.join(core_metadata['output_names'])\n    target_nodes = ','.join(core_metadata['target_nodes'])\n    self._run_key = RunKey(input_names, output_names, target_nodes)\n    if not self._graph_defs:\n      self._graph_defs_arrive_first = False\n    else:\n      for device_name in self._graph_defs:\n        self._add_graph_def(device_name, self._graph_defs[device_name])\n    self._outgoing_channel.put(_comm_metadata(self._run_key, event.wall_time))\n    logger.info('on_core_metadata_event() waiting for client ack (meta)...')\n    self._incoming_channel.get()\n    logger.info('on_core_metadata_event() client ack received (meta).')",
    "docstring": "Implementation of the core metadata-carrying Event proto callback.\n\n    Args:\n      event: An Event proto that contains core metadata about the debugged\n        Session::Run() in its log_message.message field, as a JSON string.\n        See the doc string of debug_data.DebugDumpDir.core_metadata for details."
  },
  {
    "code": "def get_event_action(cls) -> Optional[str]:\n        if not cls.actor:\n            return None\n        return event_context.get_event_action(cls.event_type)",
    "docstring": "Return the second part of the event_type\n\n        e.g.\n\n        >>> Event.event_type = 'experiment.deleted'\n        >>> Event.get_event_action() == 'deleted'"
  },
  {
    "code": "def is_collection(obj):\n    col = getattr(obj, '__getitem__', False)\n    val = False if (not col) else True\n    if isinstance(obj, basestring):\n        val = False\n    return val",
    "docstring": "Tests if an object is a collection."
  },
  {
    "code": "def update_docs(self, t, module):\n        key = \"{}.{}\".format(module.name, t.name)\n        if key in module.predocs:\n            t.docstring = self.docparser.to_doc(module.predocs[key][0], t.name)\n            t.docstart, t.docend = (module.predocs[key][1], module.predocs[key][2])",
    "docstring": "Updates the documentation for the specified type using the module predocs."
  },
  {
    "code": "def generate_tuple_batches(qs, batch_len=1):\n    num_items, batch = 0, []\n    for item in qs:\n        if num_items >= batch_len:\n            yield tuple(batch)\n            num_items = 0\n            batch = []\n        num_items += 1\n        batch += [item]\n    if num_items:\n        yield tuple(batch)",
    "docstring": "Iterate through a queryset in batches of length `batch_len`\n\n    >>> [batch for batch in generate_tuple_batches(range(7), 3)]\n    [(0, 1, 2), (3, 4, 5), (6,)]"
  },
  {
    "code": "def zscore(bars, window=20, stds=1, col='close'):\n    std = numpy_rolling_std(bars[col], window)\n    mean = numpy_rolling_mean(bars[col], window)\n    return (bars[col] - mean) / (std * stds)",
    "docstring": "get zscore of price"
  },
  {
    "code": "def WhereIs(self, prog, path=None, pathext=None, reject=[]):\n        if path is None:\n            try:\n                path = self['ENV']['PATH']\n            except KeyError:\n                pass\n        elif SCons.Util.is_String(path):\n            path = self.subst(path)\n        if pathext is None:\n            try:\n                pathext = self['ENV']['PATHEXT']\n            except KeyError:\n                pass\n        elif SCons.Util.is_String(pathext):\n            pathext = self.subst(pathext)\n        prog = SCons.Util.CLVar(self.subst(prog))\n        path = SCons.Util.WhereIs(prog[0], path, pathext, reject)\n        if path: return path\n        return None",
    "docstring": "Find prog in the path."
  },
  {
    "code": "def getAnalyst(self):\n        analyst = self.getField(\"Analyst\").get(self)\n        if not analyst:\n            analyst = self.getSubmittedBy()\n        return analyst or \"\"",
    "docstring": "Returns the stored Analyst or the user who submitted the result"
  },
  {
    "code": "def get_conversion(scale, limits):\n    fb = float(scale) / float(limits['b'][1] - limits['b'][0])\n    fl = float(scale) / float(limits['l'][1] - limits['l'][0])\n    fr = float(scale) / float(limits['r'][1] - limits['r'][0])\n    conversion = {\"b\": lambda x: (x - limits['b'][0]) * fb,\n                  \"l\": lambda x: (x - limits['l'][0]) * fl,\n                  \"r\": lambda x: (x - limits['r'][0]) * fr}\n    return conversion",
    "docstring": "Get the conversion equations for each axis.\n\n    limits: dict of min and max values for the axes in the order blr."
  },
  {
    "code": "def set_zap_authenticator(self, zap_authenticator):\n        result = self._zap_authenticator\n        if result:\n            self.unregister_child(result)\n        self._zap_authenticator = zap_authenticator\n        if self.zap_client:\n            self.zap_client.close()\n        if self._zap_authenticator:\n            self.register_child(zap_authenticator)\n            self.zap_client = ZAPClient(context=self)\n            self.register_child(self.zap_client)\n        else:\n            self.zap_client = None\n        return result",
    "docstring": "Setup a ZAP authenticator.\n\n        :param zap_authenticator: A ZAP authenticator instance to use. The\n            context takes ownership of the specified instance. It will close it\n            automatically when it stops. If `None` is specified, any previously\n            owner instance is disowned and returned. It becomes the caller's\n            responsibility to close it.\n        :returns: The previous ZAP authenticator instance."
  },
  {
    "code": "def get_nonce(self):\n        nonce = getattr(self, '_nonce', 0)\n        if nonce:\n            nonce += 1\n        self._nonce = max(int(time.time()), nonce)\n        return self._nonce",
    "docstring": "Get a unique nonce for the bitstamp API.\n\n        This integer must always be increasing, so use the current unix time.\n        Every time this variable is requested, it automatically increments to\n        allow for more than one API request per second.\n\n        This isn't a thread-safe function however, so you should only rely on a\n        single thread if you have a high level of concurrent API requests in\n        your application."
  },
  {
    "code": "def request(self, msg, use_mid=None):\n        mid = self._get_mid_and_update_msg(msg, use_mid)\n        self.send_request(msg)\n        return mid",
    "docstring": "Send a request message, with automatic message ID assignment.\n\n        Parameters\n        ----------\n        msg : katcp.Message request message\n        use_mid : bool or None, default=None\n\n        Returns\n        -------\n        mid : string or None\n            The message id, or None if no msg id is used\n\n        If use_mid is None and the server supports msg ids, or if use_mid is\n        True a message ID will automatically be assigned msg.mid is None.\n\n        if msg.mid has a value, and the server supports msg ids, that value\n        will be used. If the server does not support msg ids, KatcpVersionError\n        will be raised."
  },
  {
    "code": "def listify(args):\n    if args:\n        if isinstance(args, list):\n            return args\n        elif isinstance(args, (set, tuple, GeneratorType,\n                               range, past.builtins.xrange)):\n            return list(args)\n        return [args]\n    return []",
    "docstring": "Return args as a list.\n\n    If already a list - return as is.\n\n    >>> listify([1, 2, 3])\n    [1, 2, 3]\n\n    If a set - return as a list.\n\n    >>> listify(set([1, 2, 3]))\n    [1, 2, 3]\n\n    If a tuple - return as a list.\n\n    >>> listify(tuple([1, 2, 3]))\n    [1, 2, 3]\n\n    If a generator (also range / xrange) - return as a list.\n\n    >>> listify(x + 1 for x in range(3))\n    [1, 2, 3]\n    >>> from past.builtins import xrange\n    >>> from builtins import range\n    >>> listify(xrange(1, 4))\n    [1, 2, 3]\n    >>> listify(range(1, 4))\n    [1, 2, 3]\n\n    If a single instance of something that isn't any of the above - put as a\n    single element of the returned list.\n\n    >>> listify(1)\n    [1]\n\n    If \"empty\" (None or False or '' or anything else that evaluates to False),\n    return an empty list ([]).\n\n    >>> listify(None)\n    []\n    >>> listify(False)\n    []\n    >>> listify('')\n    []\n    >>> listify(0)\n    []\n    >>> listify([])\n    []"
  },
  {
    "code": "def sort_func(variant=VARIANT1, case_sensitive=False):\n    return lambda x: normalize(\n        x, variant=variant, case_sensitive=case_sensitive)",
    "docstring": "A function generator that can be used for sorting.\n\n    All keywords are passed to `normalize()` and generate keywords that\n    can be passed to `sorted()`::\n\n      >>> key = sort_func()\n      >>> print(sorted([\"fur\", \"far\"], key=key))\n      [u'far', u'fur']\n\n    Please note, that `sort_func` returns a function."
  },
  {
    "code": "def cylinder(target, throat_diameter='throat.diameter',\n             throat_length='throat.length'):\n    r\n    D = target[throat_diameter]\n    L = target[throat_length]\n    value = _sp.pi*D*L\n    return value",
    "docstring": "r\"\"\"\n    Calculate surface area for a cylindrical throat\n\n    Parameters\n    ----------\n    target : OpenPNM Object\n        The object which this model is associated with. This controls the\n        length of the calculated array, and also provides access to other\n        necessary properties.\n\n    throat_diameter : string\n        Dictionary key to the throat diameter array.  Default is\n        'throat.diameter'.\n\n    throat_length : string\n        Dictionary key to the throat length array.  Default is 'throat.length'."
  },
  {
    "code": "def delete(customer, card):\n        if isinstance(customer, resources.Customer):\n            customer = customer.id\n        if isinstance(card, resources.Card):\n            card = card.id\n        http_client = HttpClient()\n        http_client.delete(routes.url(routes.CARD_RESOURCE, resource_id=card, customer_id=customer))",
    "docstring": "Delete a card from its id.\n\n        :param customer: The customer id or object\n        :type customer: string|Customer\n        :param card: The card id or object\n        :type card: string|Card"
  },
  {
    "code": "def get(issue_id, issue_type_id):\n        return db.Issue.find_one(\n            Issue.issue_id == issue_id,\n            Issue.issue_type_id == issue_type_id\n        )",
    "docstring": "Return issue by ID\n\n        Args:\n            issue_id (str): Unique Issue identifier\n            issue_type_id (str): Type of issue to get\n\n        Returns:\n            :obj:`Issue`: Returns Issue object if found, else None"
  },
  {
    "code": "def _is_allowed(input):\n    gnupg_options = _get_all_gnupg_options()\n    allowed = _get_options_group(\"allowed\")\n    try:\n        assert allowed.issubset(gnupg_options)\n    except AssertionError:\n        raise UsageError(\"'allowed' isn't a subset of known options, diff: %s\"\n                         % allowed.difference(gnupg_options))\n    if not isinstance(input, str):\n        input = ' '.join([x for x in input])\n    if isinstance(input, str):\n        if input.find('_') > 0:\n            if not input.startswith('--'):\n                hyphenated = _hyphenate(input, add_prefix=True)\n            else:\n                hyphenated = _hyphenate(input)\n        else:\n            hyphenated = input\n            try:\n                assert hyphenated in allowed\n            except AssertionError as ae:\n                dropped = _fix_unsafe(hyphenated)\n                log.warn(\"_is_allowed(): Dropping option '%s'...\" % dropped)\n                raise ProtectedOption(\"Option '%s' not supported.\" % dropped)\n            else:\n                return input\n    return None",
    "docstring": "Check that an option or argument given to GPG is in the set of allowed\n    options, the latter being a strict subset of the set of all options known\n    to GPG.\n\n    :param str input: An input meant to be parsed as an option or flag to the\n                      GnuPG process. Should be formatted the same as an option\n                      or flag to the commandline gpg, i.e. \"--encrypt-files\".\n\n    :ivar frozenset gnupg_options: All known GPG options and flags.\n\n    :ivar frozenset allowed: All allowed GPG options and flags, e.g. all GPG\n                             options and flags which we are willing to\n                             acknowledge and parse. If we want to support a\n                             new option, it will need to have its own parsing\n                             class and its name will need to be added to this\n                             set.\n\n    :raises: :exc:`UsageError` if **input** is not a subset of the hard-coded\n             set of all GnuPG options in :func:`_get_all_gnupg_options`.\n\n             :exc:`ProtectedOption` if **input** is not in the set of allowed\n             options.\n\n    :rtype: str\n    :return: The original **input** parameter, unmodified and unsanitized, if\n             no errors occur."
  },
  {
    "code": "def _PrintAnalysisStatusHeader(self, processing_status):\n    self._output_writer.Write(\n        'Storage file\\t\\t: {0:s}\\n'.format(self._storage_file_path))\n    self._PrintProcessingTime(processing_status)\n    if processing_status and processing_status.events_status:\n      self._PrintEventsStatus(processing_status.events_status)\n    self._output_writer.Write('\\n')",
    "docstring": "Prints the analysis status header.\n\n    Args:\n      processing_status (ProcessingStatus): processing status."
  },
  {
    "code": "def resolve_dst(self, dst_dir, src):\n        if os.path.isabs(src):\n            return os.path.join(dst_dir, os.path.basename(src))\n        return os.path.join(dst_dir, src)",
    "docstring": "finds the destination based on source\n        if source is an absolute path, and there's no pattern, it copies the file to base dst_dir"
  },
  {
    "code": "def get_headers_global():\n        headers = dict()\n        headers[\"applications_path_txt\"] = 'Applications_Path'\n        headers[\"channel_index_txt\"] = 'Channel_Index'\n        headers[\"channel_number_txt\"] = 'Channel_Number'\n        headers[\"channel_type_txt\"] = 'Channel_Type'\n        headers[\"comments_txt\"] = 'Comments'\n        headers[\"creator_txt\"] = 'Creator'\n        headers[\"daq_index_txt\"] = 'DAQ_Index'\n        headers[\"item_id_txt\"] = 'Item_ID'\n        headers[\"log_aux_data_flag_txt\"] = 'Log_Aux_Data_Flag'\n        headers[\"log_chanstat_data_flag_txt\"] = 'Log_ChanStat_Data_Flag'\n        headers[\"log_event_data_flag_txt\"] = 'Log_Event_Data_Flag'\n        headers[\"log_smart_battery_data_flag_txt\"] = 'Log_Smart_Battery_Data_Flag'\n        headers[\"mapped_aux_conc_cnumber_txt\"] = 'Mapped_Aux_Conc_CNumber'\n        headers[\"mapped_aux_di_cnumber_txt\"] = 'Mapped_Aux_DI_CNumber'\n        headers[\"mapped_aux_do_cnumber_txt\"] = 'Mapped_Aux_DO_CNumber'\n        headers[\"mapped_aux_flow_rate_cnumber_txt\"] = 'Mapped_Aux_Flow_Rate_CNumber'\n        headers[\"mapped_aux_ph_number_txt\"] = 'Mapped_Aux_PH_Number'\n        headers[\"mapped_aux_pressure_number_txt\"] = 'Mapped_Aux_Pressure_Number'\n        headers[\"mapped_aux_temperature_number_txt\"] = 'Mapped_Aux_Temperature_Number'\n        headers[\"mapped_aux_voltage_number_txt\"] = 'Mapped_Aux_Voltage_Number'\n        headers[\"schedule_file_name_txt\"] = 'Schedule_File_Name'\n        headers[\"start_datetime_txt\"] = 'Start_DateTime'\n        headers[\"test_id_txt\"] = 'Test_ID'\n        headers[\"test_name_txt\"] = 'Test_Name'\n        return headers",
    "docstring": "Defines the so-called global column headings for Arbin .res-files"
  },
  {
    "code": "def table(self, datatype=None, **kwargs):\n        if config.future_deprecations:\n            self.param.warning(\"The table method is deprecated and should no \"\n                               \"longer be used. If using a HoloMap use \"\n                               \"HoloMap.collapse() instead to return a Dataset.\")\n        from .data.interface import Interface\n        from ..element.tabular import Table\n        new_data = [(key, value.table(datatype=datatype, **kwargs))\n                    for key, value in self.data.items()]\n        tables = self.clone(new_data)\n        return Interface.concatenate(tables, new_type=Table)",
    "docstring": "Deprecated method to convert an MultiDimensionalMapping of\n        Elements to a Table."
  },
  {
    "code": "def copy_fields(layer, fields_to_copy):\n    for field in fields_to_copy:\n        index = layer.fields().lookupField(field)\n        if index != -1:\n            layer.startEditing()\n            source_field = layer.fields().at(index)\n            new_field = QgsField(source_field)\n            new_field.setName(fields_to_copy[field])\n            layer.addAttribute(new_field)\n            new_index = layer.fields().lookupField(fields_to_copy[field])\n            for feature in layer.getFeatures():\n                attributes = feature.attributes()\n                source_value = attributes[index]\n                layer.changeAttributeValue(\n                    feature.id(), new_index, source_value)\n            layer.commitChanges()\n            layer.updateFields()",
    "docstring": "Copy fields inside an attribute table.\n\n    :param layer: The vector layer.\n    :type layer: QgsVectorLayer\n\n    :param fields_to_copy: Dictionary of fields to copy.\n    :type fields_to_copy: dict"
  },
  {
    "code": "def selectfalse(table, field, complement=False):\n    return select(table, field, lambda v: not bool(v),\n                  complement=complement)",
    "docstring": "Select rows where the given field evaluates `False`."
  },
  {
    "code": "def row_csv_limiter(rows, limits=None):\n    limits = [None, None] if limits is None else limits\n    if len(exclude_empty_values(limits)) == 2:\n        upper_limit = limits[0]\n        lower_limit = limits[1]\n    elif len(exclude_empty_values(limits)) == 1:\n        upper_limit = limits[0]\n        lower_limit = row_iter_limiter(rows, 1, -1, 1)\n    else:\n        upper_limit = row_iter_limiter(rows, 0, 1, 0)\n        lower_limit = row_iter_limiter(rows, 1, -1, 1)\n    return rows[upper_limit: lower_limit]",
    "docstring": "Limit row passing a value or detect limits making the best effort."
  },
  {
    "code": "def visit_FunctionBody(self, node):\n        for child in node.children:\n            return_value = self.visit(child)\n            if isinstance(child, ReturnStatement):\n                return return_value\n            if isinstance(child, (IfStatement, WhileStatement)):\n                if return_value is not None:\n                    return return_value\n        return NoneType()",
    "docstring": "Visitor for `FunctionBody` AST node."
  },
  {
    "code": "def abort_expired_batches(self, request_timeout_ms, cluster):\n        expired_batches = []\n        to_remove = []\n        count = 0\n        for tp in list(self._batches.keys()):\n            assert tp in self._tp_locks, 'TopicPartition not in locks dict'\n            if tp in self.muted:\n                continue\n            with self._tp_locks[tp]:\n                dq = self._batches[tp]\n                for batch in dq:\n                    is_full = bool(bool(batch != dq[-1]) or batch.records.is_full())\n                    if batch.maybe_expire(request_timeout_ms,\n                                          self.config['retry_backoff_ms'],\n                                          self.config['linger_ms'],\n                                          is_full):\n                        expired_batches.append(batch)\n                        to_remove.append(batch)\n                        count += 1\n                        self.deallocate(batch)\n                    else:\n                        break\n                if to_remove:\n                    for batch in to_remove:\n                        dq.remove(batch)\n                    to_remove = []\n        if expired_batches:\n            log.warning(\"Expired %d batches in accumulator\", count)\n        return expired_batches",
    "docstring": "Abort the batches that have been sitting in RecordAccumulator for\n        more than the configured request_timeout due to metadata being\n        unavailable.\n\n        Arguments:\n            request_timeout_ms (int): milliseconds to timeout\n            cluster (ClusterMetadata): current metadata for kafka cluster\n\n        Returns:\n            list of ProducerBatch that were expired"
  },
  {
    "code": "def _find_datastream(self, name):\n        for stream in self.data_streams:\n            if stream.name == name:\n                return stream\n        return None",
    "docstring": "Find and return if a datastream exists, by name."
  },
  {
    "code": "def restore(source, offset):\n    backup_location = os.path.join(\n        os.path.dirname(os.path.abspath(source)), source + '.bytes_backup')\n    click.echo('Reading backup from: {location}'.format(location=backup_location))\n    if not os.path.isfile(backup_location):\n        click.echo('No backup found for: {source}'.format(source=source))\n        return\n    with open(backup_location, 'r+b') as b:\n        data = b.read()\n    click.echo('Restoring {c} bytes from offset {o}'.format(c=len(data), o=offset))\n    with open(source, 'r+b') as f:\n        f.seek(offset)\n        f.write(data)\n        f.flush()\n    click.echo('Changes written')",
    "docstring": "Restore a smudged file from .bytes_backup"
  },
  {
    "code": "def downcaseTokens(s,l,t):\n    return [ tt.lower() for tt in map(_ustr,t) ]",
    "docstring": "Helper parse action to convert tokens to lower case."
  },
  {
    "code": "def int_to_words(int_val, num_words=4, word_size=32):\n        max_int = 2 ** (word_size*num_words) - 1\n        max_word_size = 2 ** word_size - 1\n        if not 0 <= int_val <= max_int:\n            raise AttributeError('integer %r is out of bounds!' % hex(int_val))\n        words = []\n        for _ in range(num_words):\n            word = int_val & max_word_size\n            words.append(int(word))\n            int_val >>= word_size\n        words.reverse()\n        return words",
    "docstring": "Convert a int value to bytes.\n\n        :param int_val: an arbitrary length Python integer to be split up.\n            Network byte order is assumed. Raises an IndexError if width of\n            integer (in bits) exceeds word_size * num_words.\n\n        :param num_words: number of words expected in return value tuple.\n\n        :param word_size: size/width of individual words (in bits).\n\n        :return: a list of fixed width words based on provided parameters."
  },
  {
    "code": "def create(self):\n        self.server_attrs = self.consul.create_server(\n                \"%s-%s\" % (self.stack.name, self.name),\n                self.disk_image_id,\n                self.instance_type,\n                self.ssh_key_name,\n                tags=self.tags,\n                availability_zone=self.availability_zone,\n                timeout_s=self.launch_timeout_s,\n                security_groups=self.security_groups,\n                **self.provider_extras\n                )\n        log.debug('Post launch delay: %d s' % self.post_launch_delay_s)\n        time.sleep(self.post_launch_delay_s)",
    "docstring": "Launches a new server instance."
  },
  {
    "code": "def event_details(event_id=None, lang=\"en\"):\n    if event_id:\n        cache_name = \"event_details.%s.%s.json\" % (event_id, lang)\n        params = {\"event_id\": event_id, \"lang\": lang}\n    else:\n        cache_name = \"event_details.%s.json\" % lang\n        params = {\"lang\": lang}\n    data = get_cached(\"event_details.json\", cache_name, params=params)\n    events = data[\"events\"]\n    return events.get(event_id) if event_id else events",
    "docstring": "This resource returns static details about available events.\n\n    :param event_id: Only list this event.\n    :param lang: Show localized texts in the specified language.\n\n    The response is a dictionary where the key is the event id, and the value\n    is a dictionary containing the following properties:\n\n    name (string)\n        The name of the event.\n\n    level (int)\n        The event level.\n\n    map_id (int)\n        The map where the event takes place.\n\n    flags (list)\n        A list of additional flags. Possible flags are:\n\n        ``group_event``\n            For group events\n\n        ``map_wide``\n            For map-wide events.\n\n    location (object)\n        The location of the event.\n\n        type (string)\n            The type of the event location, can be ``sphere``, ``cylinder`` or\n            ``poly``.\n\n        center (list)\n            X, Y, Z coordinates of the event location.\n\n        radius (number) (type ``sphere`` and ``cylinder``)\n            Radius of the event location.\n\n        z_range (list) (type ``poly``)\n            List of Minimum and Maximum Z coordinate.\n\n        points (list) (type ``poly``)\n            List of Points (X, Y) denoting the event location perimeter.\n\n    If a event_id is given, only the values for that event are returned."
  },
  {
    "code": "def compile_excludes(self):\n        self.compiled_exclude_files = []\n        for pattern in self.exclude_files:\n            try:\n                self.compiled_exclude_files.append(re.compile(pattern))\n            except re.error as e:\n                raise ValueError(\n                    \"Bad python regex in exclude '%s': %s\" % (pattern, str(e)))",
    "docstring": "Compile a set of regexps for files to be exlcuded from scans."
  },
  {
    "code": "def retrieve_manual_indices(self):\n        if self.parent_changed:\n            pass\n        else:\n            pbool = map_indices_child2root(\n                child=self.rtdc_ds,\n                child_indices=np.where(~self.manual)[0]).tolist()\n            pold = self._man_root_ids\n            pall = sorted(list(set(pbool + pold)))\n            pvis_c = map_indices_root2child(child=self.rtdc_ds,\n                                            root_indices=pall).tolist()\n            pvis_p = map_indices_child2root(child=self.rtdc_ds,\n                                            child_indices=pvis_c).tolist()\n            phid = list(set(pall) - set(pvis_p))\n            all_idx = list(set(pbool + phid))\n            self._man_root_ids = sorted(all_idx)\n        return self._man_root_ids",
    "docstring": "Read from self.manual\n\n        Read from the boolean array `self.manual`, index all\n        occurences of `False` and find the corresponding indices\n        in the root hierarchy parent, return those and store them\n        in `self._man_root_ids` as well.\n\n        Notes\n        -----\n        This method also retrieves hidden indices, i.e. events\n        that are not part of the current hierarchy child but\n        which have been manually excluded before and are now\n        hidden because a hierarchy parent filtered it out.\n\n        If `self.parent_changed` is `True`, i.e. the parent applied\n        a filter and the child did not yet hear about this, then\n        nothing is computed and `self._man_root_ids` as-is.  This\n        is important, because the size of the current filter would\n        not match the size of the filtered events of the parent and\n        thus index-mapping would not work."
  },
  {
    "code": "def promote_owner(self, stream_id, user_id):\n        req_hook = 'pod/v1/room/' + stream_id + '/membership/promoteOwner'\n        req_args = '{ \"id\": %s }' % user_id\n        status_code, response = self.__rest__.POST_query(req_hook, req_args)\n        self.logger.debug('%s: %s' % (status_code, response))\n        return status_code, response",
    "docstring": "promote user to owner in stream"
  },
  {
    "code": "def get_version():\n    if isinstance(VERSION[-1], str):\n        return '.'.join(map(str, VERSION[:-1])) + VERSION[-1]\n    return '.'.join(map(str, VERSION))",
    "docstring": "Returns a string representation of the current SDK version."
  },
  {
    "code": "def nrows_expected(self):\n        return np.prod([i.cvalues.shape[0] for i in self.index_axes])",
    "docstring": "based on our axes, compute the expected nrows"
  },
  {
    "code": "def address_inline(request, prefix=\"\", country_code=None, template_name=\"postal/form.html\"):\n    country_prefix = \"country\"\n    prefix = request.POST.get('prefix', prefix)\n    if prefix:\n        country_prefix = prefix + '-country'\n    country_code = request.POST.get(country_prefix, country_code)\n    form_class = form_factory(country_code=country_code)\n    if request.method == \"POST\":\n        data = {}\n        for (key, val) in request.POST.items():\n            if val is not None and len(val) > 0:\n                data[key] = val\n        data.update({country_prefix: country_code})\n        form = form_class(prefix=prefix, initial=data)\n    else:\n        form = form_class(prefix=prefix)\n    return render_to_string(template_name, RequestContext(request, {\n        \"form\": form,\n        \"prefix\": prefix,\n    }))",
    "docstring": "Displays postal address with localized fields"
  },
  {
    "code": "def generate_static_matching(app,\n                             directory_serve_app=DirectoryApp):\n    static_dir = os.path.join(os.path.dirname(app.__file__),\n                              'static')\n    try:\n        static_app = directory_serve_app(static_dir, index_page='')\n    except OSError:\n        return None\n    static_pattern = '/static/{app.__name__}/*path'.format(app=app)\n    static_name = '{app.__name__}:static'.format(app=app)\n    return Matching(static_pattern, static_app, static_name)",
    "docstring": "Creating a matching for WSGI application to serve static files\n    for passed app.\n\n    Static files will be collected from directory named 'static'\n    under passed application::\n\n        ./blog/static/\n\n    This example is with an application named `blog`.\n    URLs for static files in static directory will begin with\n    /static/app_name/. so in blog app case, if the directory has\n    css/main.css file, the file will be published like this::\n\n         yoursite.com/static/blog/css/main.css\n\n    And you can get this URL by reversing form matching object::\n\n        matching.reverse('blog:static', path=['css', 'main.css'])"
  },
  {
    "code": "def _summarize_coefficients(top_coefs, bottom_coefs):\n    def get_row_name(row):\n        if row['index'] is None:\n            return row['name']\n        else:\n            return \"%s[%s]\" % (row['name'], row['index'])\n    if len(top_coefs) == 0:\n        top_coefs_list = [('No Positive Coefficients', _precomputed_field('') )]\n    else:\n        top_coefs_list = [ (get_row_name(row),\n                            _precomputed_field(row['value'])) \\\n                            for row in top_coefs ]\n    if len(bottom_coefs) == 0:\n        bottom_coefs_list = [('No Negative Coefficients', _precomputed_field(''))]\n    else:\n        bottom_coefs_list = [ (get_row_name(row),\n                            _precomputed_field(row['value'])) \\\n                            for row in bottom_coefs ]\n    return ([top_coefs_list, bottom_coefs_list], \\\n                    [ 'Highest Positive Coefficients', 'Lowest Negative Coefficients'] )",
    "docstring": "Return a tuple of sections and section titles.\n    Sections are pretty print of model coefficients\n\n    Parameters\n    ----------\n    top_coefs : SFrame of top k coefficients\n\n    bottom_coefs : SFrame of bottom k coefficients\n\n    Returns\n    -------\n    (sections, section_titles) : tuple\n            sections : list\n                summary sections for top/bottom k coefficients\n            section_titles : list\n                summary section titles"
  },
  {
    "code": "def GetNextNode(self, modes, innode):\n        nodes = N.where(self.innodes == innode)\n        if nodes[0].size == 0:\n            return -1\n        defaultindex = N.where(self.keywords[nodes] == 'default')\n        if len(defaultindex[0]) != 0:\n            outnode = self.outnodes[nodes[0][defaultindex[0]]]\n        for mode in modes:\n            result = self.keywords[nodes].count(mode)\n            if result != 0:\n                index = N.where(self.keywords[nodes]==mode)\n                outnode = self.outnodes[nodes[0][index[0]]]\n        return outnode",
    "docstring": "GetNextNode returns the outnode that matches an element from\n        the modes list, starting at the given innode.\n        This method isnt actually used, its just a helper method for\n        debugging purposes."
  },
  {
    "code": "def get_as_nullable_type(self, key, value_type):\n        value = self.get(key)\n        return TypeConverter.to_nullable_type(value_type, value)",
    "docstring": "Converts map element into a value defined by specied typecode.\n        If conversion is not possible it returns None.\n\n        :param key: an index of element to get.\n\n        :param value_type: the TypeCode that defined the type of the result\n\n        :return: element value defined by the typecode or None if conversion is not supported."
  },
  {
    "code": "def get_feature_names(self):\n        feature_names = []\n        for name, trans, weight in self._iter():\n            if not hasattr(trans, 'get_feature_names'):\n                raise AttributeError(\"Transformer %s (type %s) does not \"\n                                     \"provide get_feature_names.\"\n                                     % (str(name), type(trans).__name__))\n            feature_names.extend([name + \"__\" + f for f in\n                                  trans.get_feature_names()])\n        return feature_names",
    "docstring": "Get feature names from all transformers.\n\n        Returns\n        -------\n        feature_names : list of strings\n            Names of the features produced by transform."
  },
  {
    "code": "def invert(m):\n    m = stypes.toDoubleMatrix(m)\n    mout = stypes.emptyDoubleMatrix()\n    libspice.invert_c(m, mout)\n    return stypes.cMatrixToNumpy(mout)",
    "docstring": "Generate the inverse of a 3x3 matrix.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/invert_c.html\n\n    :param m: Matrix to be inverted.\n    :type m: 3x3-Element Array of floats\n    :return: Inverted matrix (m1)^-1\n    :rtype: 3x3-Element Array of floats"
  },
  {
    "code": "async def get_codec(self):\n        act = self.service.action(\"X_GetCodec\")\n        res = await act.async_call()\n        return res",
    "docstring": "Get codec settings."
  },
  {
    "code": "def variable(\n            self,\n            name=None,\n            function=None,\n            decl_type=None,\n            header_dir=None,\n            header_file=None,\n            recursive=None):\n        return (\n            self._find_single(\n                self._impl_matchers[\n                    scopedef_t.variable],\n                name=name,\n                function=function,\n                decl_type=decl_type,\n                header_dir=header_dir,\n                header_file=header_file,\n                recursive=recursive)\n        )",
    "docstring": "returns reference to variable declaration, that is matched defined\n        criteria"
  },
  {
    "code": "def get_encoder(self, content_type):\n        if content_type in self._encoders:\n            return self._encoders[content_type]\n        else:\n            return self._client.get_encoder(content_type)",
    "docstring": "Get the encoding function for the provided content type for\n        this bucket.\n\n        :param content_type: the requested media type\n        :type content_type: str\n        :param content_type: Content type requested"
  },
  {
    "code": "def create(cls, video, language_code, file_format, content, provider):\n        video_transcript = cls(video=video, language_code=language_code, file_format=file_format, provider=provider)\n        with closing(content) as transcript_content:\n            try:\n                file_name = '{uuid}.{ext}'.format(uuid=uuid4().hex, ext=video_transcript.file_format)\n                video_transcript.transcript.save(file_name, transcript_content)\n                video_transcript.save()\n            except Exception:\n                logger.exception(\n                    '[VAL] Transcript save failed to storage for video_id \"%s\" language code \"%s\"',\n                    video.edx_video_id,\n                    language_code\n                )\n                raise\n        return video_transcript",
    "docstring": "Create a Video Transcript.\n\n        Arguments:\n            video(Video): Video data model object\n            language_code(unicode): A language code.\n            file_format(unicode): Transcript file format.\n            content(InMemoryUploadedFile): Transcript content.\n            provider(unicode): Transcript provider."
  },
  {
    "code": "def fetchAllUsersFromThreads(self, threads):\n        users = []\n        users_to_fetch = []\n        for thread in threads:\n            if thread.type == ThreadType.USER:\n                if thread.uid not in [user.uid for user in users]:\n                    users.append(thread)\n            elif thread.type == ThreadType.GROUP:\n                for user_id in thread.participants:\n                    if (\n                        user_id not in [user.uid for user in users]\n                        and user_id not in users_to_fetch\n                    ):\n                        users_to_fetch.append(user_id)\n        for user_id, user in self.fetchUserInfo(*users_to_fetch).items():\n            users.append(user)\n        return users",
    "docstring": "Get all users involved in threads.\n\n        :param threads: models.Thread: List of threads to check for users\n        :return: :class:`models.User` objects\n        :rtype: list\n        :raises: FBchatException if request failed"
  },
  {
    "code": "def _finalize(self, chain=-1):\n        chain = range(self.chains)[chain]\n        for name in self.trace_names[chain]:\n            self._traces[name]._finalize(chain)\n        self.commit()",
    "docstring": "Finalize the chain for all tallyable objects."
  },
  {
    "code": "def pymongo_class_wrapper(f, pymongo_class):\n    @functools.wraps(f)\n    @coroutine\n    def _wrapper(self, *args, **kwargs):\n        result = yield f(self, *args, **kwargs)\n        if result.__class__ == pymongo_class:\n            raise gen.Return(self.wrap(result))\n        else:\n            raise gen.Return(result)\n    return _wrapper",
    "docstring": "Executes the coroutine f and wraps its result in a Motor class.\n\n    See WrapAsync."
  },
  {
    "code": "def add_tileset(self, tileset):\n        assert (isinstance(tileset, TiledTileset))\n        self.tilesets.append(tileset)",
    "docstring": "Add a tileset to the map\n\n        :param tileset: TiledTileset"
  },
  {
    "code": "def get(self):\n        self.loaded = True\n        if not hasattr(self.manager, \"get\"):\n            return\n        if not self.get_details:\n            return\n        new = self.manager.get(self)\n        if new:\n            self._add_details(new._info)",
    "docstring": "Gets the details for the object."
  },
  {
    "code": "def export_vtkjs(self, filename, compress_arrays=False):\n        if not hasattr(self, 'ren_win'):\n            raise RuntimeError('Export must be called before showing/closing the scene.')\n        if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename):\n            filename = os.path.join(vtki.FIGURE_PATH, filename)\n        return export_plotter_vtkjs(self, filename, compress_arrays=compress_arrays)",
    "docstring": "Export the current rendering scene as a VTKjs scene for\n        rendering in a web browser"
  },
  {
    "code": "def _register_with_pkg_resources(cls):\n        try:\n            import pkg_resources\n            pkg_resources.__name__\n        except ImportError:\n            return\n        pkg_resources.register_loader_type(cls, pkg_resources.DefaultProvider)",
    "docstring": "Ensure package resources can be loaded from this loader. May be called\n        multiple times, as the operation is idempotent."
  },
  {
    "code": "def get_validated_options(options, warn=True):\n    validated_options = {}\n    for opt, value in iteritems(options):\n        lower = opt.lower()\n        try:\n            validator = URI_VALIDATORS.get(lower, raise_config_error)\n            value = validator(opt, value)\n        except (ValueError, ConfigurationError) as exc:\n            if warn:\n                warnings.warn(str(exc))\n            else:\n                raise\n        else:\n            validated_options[lower] = value\n    return validated_options",
    "docstring": "Validate each entry in options and raise a warning if it is not valid.\n    Returns a copy of options with invalid entries removed"
  },
  {
    "code": "def im_open(self, *, user: str, **kwargs) -> SlackResponse:\n        kwargs.update({\"user\": user})\n        return self.api_call(\"im.open\", json=kwargs)",
    "docstring": "Opens a direct message channel.\n\n        Args:\n            user (str): The user id to open a DM with. e.g. 'W1234567890'"
  },
  {
    "code": "def _l2ycbcr(self, mode):\n        self._check_modes((\"L\", \"LA\"))\n        luma = self.channels[0]\n        zeros = np.ma.zeros(luma.shape)\n        zeros.mask = luma.mask\n        self.channels = [luma, zeros, zeros] + self.channels[1:]\n        if self.fill_value is not None:\n            self.fill_value = [self.fill_value[0], 0, 0] + self.fill_value[1:]\n        self.mode = mode",
    "docstring": "Convert from L to YCbCr."
  },
  {
    "code": "def plot_total(self, colorbar=True, cb_orientation='vertical',\n                   cb_label='$|B|$, nT', ax=None, show=True, fname=None,\n                   **kwargs):\n        if ax is None:\n            fig, axes = self.total.plot(\n                colorbar=colorbar, cb_orientation=cb_orientation,\n                cb_label=cb_label, show=False, **kwargs)\n            if show:\n                fig.show()\n            if fname is not None:\n                fig.savefig(fname)\n            return fig, axes\n        else:\n            self.total.plot(\n                colorbar=colorbar, cb_orientation=cb_orientation,\n                cb_label=cb_label, ax=ax, **kwargs)",
    "docstring": "Plot the total magnetic intensity.\n\n        Usage\n        -----\n        x.plot_total([tick_interval, xlabel, ylabel, ax, colorbar,\n                      cb_orientation, cb_label, show, fname, **kwargs])\n\n        Parameters\n        ----------\n        tick_interval : list or tuple, optional, default = [30, 30]\n            Intervals to use when plotting the x and y ticks. If set to None,\n            ticks will not be plotted.\n        xlabel : str, optional, default = 'longitude'\n            Label for the longitude axis.\n        ylabel : str, optional, default = 'latitude'\n            Label for the latitude axis.\n        ax : matplotlib axes object, optional, default = None\n            A single matplotlib axes object where the plot will appear.\n        colorbar : bool, optional, default = True\n            If True, plot a colorbar.\n        cb_orientation : str, optional, default = 'vertical'\n            Orientation of the colorbar: either 'vertical' or 'horizontal'.\n        cb_label : str, optional, default = '$|B|$, nT'\n            Text label for the colorbar.\n        show : bool, optional, default = True\n            If True, plot the image to the screen.\n        fname : str, optional, default = None\n            If present, and if axes is not specified, save the image to the\n            specified file.\n        kwargs : optional\n            Keyword arguements that will be sent to the SHGrid.plot()\n            and plt.imshow() methods."
  },
  {
    "code": "def get_start_state(self, set_final_outcome=False):\n        if self.get_path() in state_machine_execution_engine.start_state_paths:\n            for state_id, state in self.states.items():\n                if state.get_path() in state_machine_execution_engine.start_state_paths:\n                    state_machine_execution_engine.start_state_paths.remove(self.get_path())\n                    self._start_state_modified = True\n                    return state\n        if self.start_state_id is None:\n            return None\n        if self.start_state_id == self.state_id:\n            if set_final_outcome:\n                for transition_id in self.transitions:\n                    if self.transitions[transition_id].from_state is None:\n                        to_outcome_id = self.transitions[transition_id].to_outcome\n                        self.final_outcome = self.outcomes[to_outcome_id]\n                        break\n            return self\n        return self.states[self.start_state_id]",
    "docstring": "Get the start state of the container state\n\n        :param set_final_outcome: if the final_outcome of the state should be set if the income directly connects to\n                                    an outcome\n        :return: the start state"
  },
  {
    "code": "def dict_print(self, output_file=\"dict.csv\"):\n        with codecs.open(output_file, \"w\", encoding='utf-8') as f:\n                for (v, k) in self.token_key.items():\n                    f.write(\"%s,%d\\n\" % (v, k))",
    "docstring": "Print mapping from tokens to numeric indices."
  },
  {
    "code": "def parent_widget(self):\n        parent = self.parent()\n        if parent is not None and isinstance(parent, QtGraphicsItem):\n            return parent.widget",
    "docstring": "Reimplemented to only return GraphicsItems"
  },
  {
    "code": "def BitmathType(bmstring):\n    try:\n        argvalue = bitmath.parse_string(bmstring)\n    except ValueError:\n        raise argparse.ArgumentTypeError(\"'%s' can not be parsed into a valid bitmath object\" %\n                                         bmstring)\n    else:\n        return argvalue",
    "docstring": "An 'argument type' for integrations with the argparse module.\n\nFor more information, see\nhttps://docs.python.org/2/library/argparse.html#type Of particular\ninterest to us is this bit:\n\n   ``type=`` can take any callable that takes a single string\n   argument and returns the converted value\n\nI.e., ``type`` can be a function (such as this function) or a class\nwhich implements the ``__call__`` method.\n\nExample usage of the bitmath.BitmathType argparser type:\n\n   >>> import bitmath\n   >>> import argparse\n   >>> parser = argparse.ArgumentParser()\n   >>> parser.add_argument(\"--file-size\", type=bitmath.BitmathType)\n   >>> parser.parse_args(\"--file-size 1337MiB\".split())\n   Namespace(file_size=MiB(1337.0))\n\nInvalid usage includes any input that the bitmath.parse_string\nfunction already rejects. Additionally, **UNQUOTED** arguments with\nspaces in them are rejected (shlex.split used in the following\nexamples to conserve single quotes in the parse_args call):\n\n   >>> parser = argparse.ArgumentParser()\n   >>> parser.add_argument(\"--file-size\", type=bitmath.BitmathType)\n   >>> import shlex\n\n   >>> # The following is ACCEPTABLE USAGE:\n   ...\n   >>> parser.parse_args(shlex.split(\"--file-size '1337 MiB'\"))\n   Namespace(file_size=MiB(1337.0))\n\n   >>> # The following is INCORRECT USAGE because the string \"1337 MiB\" is not quoted!\n   ...\n   >>> parser.parse_args(shlex.split(\"--file-size 1337 MiB\"))\n   error: argument --file-size: 1337 can not be parsed into a valid bitmath object"
  },
  {
    "code": "def config(self, function):\n        self.configurations.append(ConfigScope(function))\n        return self.configurations[-1]",
    "docstring": "Decorator to add a function to the configuration of the Experiment.\n\n        The decorated function is turned into a\n        :class:`~sacred.config_scope.ConfigScope` and added to the\n        Ingredient/Experiment.\n\n        When the experiment is run, this function will also be executed and\n        all json-serializable local variables inside it will end up as entries\n        in the configuration of the experiment."
  },
  {
    "code": "def concatenate(self, catalogue):\n        atts = getattr(self, 'data')\n        attn = getattr(catalogue, 'data')\n        data = _merge_data(atts, attn)\n        if data is not None:\n            setattr(self, 'data', data)\n            for attrib in vars(self):\n                atts = getattr(self, attrib)\n                attn = getattr(catalogue, attrib)\n                if attrib is 'end_year':\n                    setattr(self, attrib, max(atts, attn))\n                elif attrib is 'start_year':\n                    setattr(self, attrib, min(atts, attn))\n                elif attrib is 'data':\n                    pass\n                elif attrib is 'number_earthquakes':\n                    setattr(self, attrib, atts + attn)\n                elif attrib is 'processes':\n                    if atts != attn:\n                        raise ValueError('The catalogues cannot be merged' +\n                                         ' since the they have' +\n                                         ' a different processing history')\n                else:\n                    raise ValueError('unknown attribute: %s' % attrib)\n        self.sort_catalogue_chronologically()",
    "docstring": "This method attaches one catalogue to the current one\n\n        :parameter catalogue:\n            An instance of :class:`htmk.seismicity.catalogue.Catalogue`"
  },
  {
    "code": "def is_standalone(self):\n        return (not self.args.client and\n                not self.args.browser and\n                not self.args.server and\n                not self.args.webserver)",
    "docstring": "Return True if Glances is running in standalone mode."
  },
  {
    "code": "def chemical_formula(self):\n        counts = {}\n        for number in self.numbers:\n            counts[number] = counts.get(number, 0)+1\n        items = []\n        for number, count in sorted(counts.items(), reverse=True):\n            if count == 1:\n                items.append(periodic[number].symbol)\n            else:\n                items.append(\"%s%i\" % (periodic[number].symbol, count))\n        return \"\".join(items)",
    "docstring": "the chemical formula of the molecule"
  },
  {
    "code": "def detect(checksum_revisions, radius=defaults.RADIUS):\n    revert_detector = Detector(radius)\n    for checksum, revision in checksum_revisions:\n        revert = revert_detector.process(checksum, revision)\n        if revert is not None:\n            yield revert",
    "docstring": "Detects reverts that occur in a sequence of revisions.  Note that,\n    `revision` data meta will simply be returned in the case of a revert.\n\n    This function serves as a convenience wrapper around calls to\n    :class:`mwreverts.Detector`'s :func:`~mwreverts.Detector.process`\n    method.\n\n    :Parameters:\n        checksum_revisions : `iterable` ( (checksum, revision) )\n            an iterable over tuples of checksum and revision meta data\n        radius : int\n            a positive integer indicating the maximum revision distance that a\n            revert can span.\n\n    :Return:\n        a iterator over :class:`mwreverts.Revert`\n\n    :Example:\n        >>> import mwreverts\n        >>>\n        >>> checksum_revisions = [\n        ...     (\"aaa\", {'rev_id': 1}),\n        ...     (\"bbb\", {'rev_id': 2}),\n        ...     (\"aaa\", {'rev_id': 3}),\n        ...     (\"ccc\", {'rev_id': 4})\n        ... ]\n        >>>\n        >>> list(mwreverts.detect(checksum_revisions))\n        [Revert(reverting={'rev_id': 3},\n                reverteds=[{'rev_id': 2}],\n                reverted_to={'rev_id': 1})]"
  },
  {
    "code": "def interactive_merge_conflict_handler(self, exception):\n        if connected_to_terminal(sys.stdin):\n            logger.info(compact(\n))\n            while True:\n                if prompt_for_confirmation(\"Ignore merge error because you've resolved all conflicts?\"):\n                    if self.merge_conflicts:\n                        logger.warning(\"I'm still seeing merge conflicts, please double check! (%s)\",\n                                       concatenate(self.merge_conflicts))\n                    else:\n                        return True\n                else:\n                    break\n        return False",
    "docstring": "Give the operator a chance to interactively resolve merge conflicts.\n\n        :param exception: An :exc:`~executor.ExternalCommandFailed` object.\n        :returns: :data:`True` if the operator has interactively resolved any\n                  merge conflicts (and as such the merge error doesn't need to\n                  be propagated), :data:`False` otherwise.\n\n        This method checks whether :data:`sys.stdin` is connected to a terminal\n        to decide whether interaction with an operator is possible. If it is\n        then an interactive terminal prompt is used to ask the operator to\n        resolve the merge conflict(s). If the operator confirms the prompt, the\n        merge error is swallowed instead of propagated. When :data:`sys.stdin`\n        is not connected to a terminal or the operator denies the prompt the\n        merge error is propagated."
  },
  {
    "code": "def delete_intent(project_id, intent_id):\n    import dialogflow_v2 as dialogflow\n    intents_client = dialogflow.IntentsClient()\n    intent_path = intents_client.intent_path(project_id, intent_id)\n    intents_client.delete_intent(intent_path)",
    "docstring": "Delete intent with the given intent type and intent value."
  },
  {
    "code": "def check_alive_instances(self):\n        for instance in self.instances:\n            if instance in self.to_restart:\n                continue\n            if instance.is_external and instance.process and not instance.process.is_alive():\n                logger.error(\"The external module %s died unexpectedly!\", instance.name)\n                logger.info(\"Setting the module %s to restart\", instance.name)\n                instance.clear_queues(self.daemon.sync_manager)\n                self.set_to_restart(instance)\n                continue\n            if self.daemon.max_queue_size == 0:\n                continue\n            queue_size = 0\n            try:\n                queue_size = instance.to_q.qsize()\n            except Exception:\n                pass\n            if queue_size > self.daemon.max_queue_size:\n                logger.error(\"The module %s has a too important queue size (%s > %s max)!\",\n                             instance.name, queue_size, self.daemon.max_queue_size)\n                logger.info(\"Setting the module %s to restart\", instance.name)\n                instance.clear_queues(self.daemon.sync_manager)\n                self.set_to_restart(instance)",
    "docstring": "Check alive instances.\n        If not, log error and try to restart it\n\n        :return: None"
  },
  {
    "code": "def page(self, order=values.unset, from_=values.unset, bounds=values.unset,\n             page_token=values.unset, page_number=values.unset,\n             page_size=values.unset):\n        params = values.of({\n            'Order': order,\n            'From': from_,\n            'Bounds': bounds,\n            'PageToken': page_token,\n            'Page': page_number,\n            'PageSize': page_size,\n        })\n        response = self._version.page(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return SyncListItemPage(self._version, response, self._solution)",
    "docstring": "Retrieve a single page of SyncListItemInstance records from the API.\n        Request is executed immediately\n\n        :param SyncListItemInstance.QueryResultOrder order: The order\n        :param unicode from_: The from\n        :param SyncListItemInstance.QueryFromBoundType bounds: The bounds\n        :param str page_token: PageToken provided by the API\n        :param int page_number: Page Number, this value is simply for client state\n        :param int page_size: Number of records to return, defaults to 50\n\n        :returns: Page of SyncListItemInstance\n        :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemPage"
  },
  {
    "code": "def geom_iter(self, g_nums):\n        from .utils import pack_tups\n        vals = pack_tups(g_nums)\n        for val in vals:\n            yield self.geom_single(val[0])",
    "docstring": "Iterator over a subset of geometries.\n\n        The indices of the geometries to be returned are indicated by an\n        iterable of |int|\\\\ s passed as `g_nums`.\n\n        As with :meth:`geom_single`, each geometry is returned as a\n        length-3N |npfloat_| with each atom's x/y/z coordinates\n        grouped together::\n\n            [A1x, A1y, A1z, A2x, A2y, A2z, ...]\n\n        In order to use NumPy `slicing or advanced indexing\n        <http://docs.scipy.org/doc/numpy-1.10.0/reference/\n        arrays.indexing.html>`__, :data:`geoms` must first be\n        explicitly converted to |nparray|, e.g.::\n\n            >>> x = opan.xyz.OpanXYZ(path='...')\n            >>> np.array(x.geoms)[[2,6,9]]\n\n        Parameters\n        ----------\n        g_nums\n            length-R iterable of |int| --\n            Indices of the desired geometries\n\n        Yields\n        ------\n        geom\n            length-3N |npfloat_| --\n            Vectors of the atomic coordinates for each geometry\n            indicated in `g_nums`\n\n        Raises\n        ------\n        ~exceptions.IndexError\n            If an item in `g_nums` is invalid (out of range)"
  },
  {
    "code": "def add_package(package_name, package_path='templates', encoding='utf-8'):\n    if not _has_jinja:\n        raise RuntimeError(_except_text)\n    _jload.add_loader(PackageLoader(package_name, package_path, encoding))",
    "docstring": "Adds the given package to the template search routine"
  },
  {
    "code": "def _return_response_and_status_code(response, json_results=True):\n    if response.status_code == requests.codes.ok:\n        return dict(results=response.json() if json_results else response.content, response_code=response.status_code)\n    elif response.status_code == 400:\n        return dict(\n                error='package sent is either malformed or not within the past 24 hours.',\n                response_code=response.status_code)\n    elif response.status_code == 204:\n        return dict(\n            error='You exceeded the public API request rate limit (4 requests of any nature per minute)',\n            response_code=response.status_code)\n    elif response.status_code == 403:\n        return dict(\n            error='You tried to perform calls to functions for which you require a Private API key.',\n            response_code=response.status_code)\n    elif response.status_code == 404:\n        return dict(error='File not found.', response_code=response.status_code)\n    else:\n        return dict(response_code=response.status_code)",
    "docstring": "Output the requests response content or content as json and status code\n\n    :rtype : dict\n    :param response: requests response object\n    :param json_results: Should return JSON or raw content\n    :return: dict containing the response content and/or the status code with error string."
  },
  {
    "code": "def delete(self):\n        self.__class__.objects.filter(pk=self.pk).delete()",
    "docstring": "Removes a node and all it's descendants."
  },
  {
    "code": "def program_rtr_default_gw(self, tenant_id, rout_id, gw):\n        args = ['route', 'add', 'default', 'gw', gw]\n        ret = self.program_rtr(args, rout_id)\n        if not ret:\n            LOG.error(\"Program router returned error for %s\", rout_id)\n            return False\n        return True",
    "docstring": "Program the default gateway of a router."
  },
  {
    "code": "def parent(self):\n        \"Get this object's parent\"\n        if self._parent:\n            return self._parent\n        elif getattr(self, '__parent_type__', None):\n            return self._get_subfolder('..' if self._url[2].endswith('/')\n                                            else '.', self.__parent_type__)\n        else:\n            raise AttributeError(\"%r has no parent attribute\" % type(self))",
    "docstring": "Get this object's parent"
  },
  {
    "code": "def execute(self, eopatch):\r\n        feature_type, feature_name = next(self.feature(eopatch))\r\n        eopatch[feature_type][feature_name] = self.process(eopatch[feature_type][feature_name])\r\n        return eopatch",
    "docstring": "Execute method takes EOPatch and changes the specified feature"
  },
  {
    "code": "def factory(token, alg=''):\n    _jw = JWS(alg=alg)\n    if _jw.is_jws(token):\n        return _jw\n    else:\n        return None",
    "docstring": "Instantiate an JWS instance if the token is a signed JWT.\n\n    :param token: The token that might be a signed JWT\n    :param alg: The expected signature algorithm\n    :return: A JWS instance if the token was a signed JWT, otherwise None"
  },
  {
    "code": "def items(self) -> Tuple[Tuple[str, \"Package\"], ...]:\n        item_dict = {\n            name: self.build_dependencies.get(name) for name in self.build_dependencies\n        }\n        return tuple(item_dict.items())",
    "docstring": "Return an iterable containing package name and\n        corresponding `Package` instance that are available."
  },
  {
    "code": "def _update_images(self):\n        wd_images = self.data['claims'].get('P18')\n        if wd_images:\n            if not isinstance(wd_images, list):\n                wd_images = [wd_images]\n            if 'image' not in self.data:\n                self.data['image'] = []\n            for img_file in wd_images:\n                self.data['image'].append({'file': img_file,\n                                           'kind': 'wikidata-image'})",
    "docstring": "add images from Wikidata"
  },
  {
    "code": "def plot_vzz(self, colorbar=True, cb_orientation='vertical',\n                 cb_label=None, ax=None, show=True, fname=None, **kwargs):\n        if cb_label is None:\n            cb_label = self._vzz_label\n        if ax is None:\n            fig, axes = self.vzz.plot(colorbar=colorbar,\n                                      cb_orientation=cb_orientation,\n                                      cb_label=cb_label, show=False, **kwargs)\n            if show:\n                fig.show()\n            if fname is not None:\n                fig.savefig(fname)\n            return fig, axes\n        else:\n            self.vzz.plot(colorbar=colorbar, cb_orientation=cb_orientation,\n                          cb_label=cb_label, ax=ax, **kwargs)",
    "docstring": "Plot the Vzz component of the tensor.\n\n        Usage\n        -----\n        x.plot_vzz([tick_interval, xlabel, ylabel, ax, colorbar,\n                    cb_orientation, cb_label, show, fname])\n\n        Parameters\n        ----------\n        tick_interval : list or tuple, optional, default = [30, 30]\n            Intervals to use when plotting the x and y ticks. If set to None,\n            ticks will not be plotted.\n        xlabel : str, optional, default = 'longitude'\n            Label for the longitude axis.\n        ylabel : str, optional, default = 'latitude'\n            Label for the latitude axis.\n        ax : matplotlib axes object, optional, default = None\n            A single matplotlib axes object where the plot will appear.\n        colorbar : bool, optional, default = True\n            If True, plot a colorbar.\n        cb_orientation : str, optional, default = 'vertical'\n            Orientation of the colorbar: either 'vertical' or 'horizontal'.\n        cb_label : str, optional, default = '$V_{zz}$'\n            Text label for the colorbar.\n        show : bool, optional, default = True\n            If True, plot the image to the screen.\n        fname : str, optional, default = None\n            If present, and if axes is not specified, save the image to the\n            specified file.\n        kwargs : optional\n            Keyword arguements that will be sent to the SHGrid.plot()\n            and plt.imshow() methods."
  },
  {
    "code": "def run(self, node):\n        n = super(Transformation, self).run(node)\n        if self.update:\n            ast.fix_missing_locations(n)\n            self.passmanager._cache.clear()\n        return n",
    "docstring": "Apply transformation and dependencies and fix new node location."
  },
  {
    "code": "def _remove_boundaries(self, interval):\n        begin = interval.begin\n        end = interval.end\n        if self.boundary_table[begin] == 1:\n            del self.boundary_table[begin]\n        else:\n            self.boundary_table[begin] -= 1\n        if self.boundary_table[end] == 1:\n            del self.boundary_table[end]\n        else:\n            self.boundary_table[end] -= 1",
    "docstring": "Removes the boundaries of the interval from the boundary table."
  },
  {
    "code": "def query(self, model_cls):\n        self._filters_cmd = list()\n        self.query_filters = list()\n        self._order_by_cmd = None\n        self._offset = 0\n        self._limit = 0\n        self.query_class = model_cls._name\n        return self",
    "docstring": "SQLAlchemy query like method"
  },
  {
    "code": "def _equivalent_node_iterator_helper(self, node: BaseEntity, visited: Set[BaseEntity]) -> BaseEntity:\n        for v in self[node]:\n            if v in visited:\n                continue\n            if self._has_no_equivalent_edge(node, v):\n                continue\n            visited.add(v)\n            yield v\n            yield from self._equivalent_node_iterator_helper(v, visited)",
    "docstring": "Iterate over nodes and their data that are equal to the given node, starting with the original."
  },
  {
    "code": "def get_vbox_version(config_kmk):\n    \"Return the vbox config major, minor, build\"\n    with open(config_kmk, 'rb') as f:\n        config = f.read()\n    major = b\"6\"\n    minor = b\"0\"\n    build = b\"4\"\n    return b\".\".join([major, minor, build])",
    "docstring": "Return the vbox config major, minor, build"
  },
  {
    "code": "def slice_on_length(self, data_len, *addSlices):\n        if len(self.ordered_ranges) + len(addSlices) == 0:\n            return slice(None,None,None)\n        ranges = self.ordered_ranges\n        if len(addSlices) > 0:\n            ranges = ranges + DimensionRange(*addSlices).ordered_ranges\n        return self._combine_lists_of_ranges_on_length(data_len, *ranges)",
    "docstring": "Returns a slice representing the dimension range\n        restrictions applied to a list of length data_len.\n\n        If addSlices contains additional slice requirements,\n        they are processed in the order they are given."
  },
  {
    "code": "def filename(self, value):\n        warnings.warn(\n            \"The 'filename' attribute will be removed in future versions.  \"\n            \"Use 'source' instead.\",\n            DeprecationWarning, stacklevel=2\n        )\n        self.source = value",
    "docstring": "Deprecated, user `source'."
  },
  {
    "code": "def _on_context_disconnect(self, context):\n        self._lock.acquire()\n        try:\n            LOG.info('%r: Forgetting %r due to stream disconnect', self, context)\n            self._forget_context_unlocked(context)\n        finally:\n            self._lock.release()",
    "docstring": "Respond to Context disconnect event by deleting any record of the no\n        longer reachable context.  This method runs in the Broker thread and\n        must not to block."
  },
  {
    "code": "def get_etags_and_matchers(self, request):\n        self.evaluate_preconditions(request)\n        return super(APIETAGProcessor, self).get_etags_and_matchers(request)",
    "docstring": "Get the etags from the header and perform a validation against the required preconditions."
  },
  {
    "code": "def catalog(self):\n        if self._catalog is None:\n            logger.debug(\"SuperModel::catalog: *Fetch catalog*\")\n            self._catalog = self.get_catalog_for(self.brain)\n        return self._catalog",
    "docstring": "Primary registered catalog for the wrapped portal type"
  },
  {
    "code": "def connect_controller(self, vid, pid, serial):\n        self.lib.tdConnectTellStickController(vid, pid, serial)",
    "docstring": "Connect a controller."
  },
  {
    "code": "def get_collections(db, collection=None, prefix=None, suffix=None):\n    if collection is not None:\n        return [collection, ]\n    collections = db.collection_names(include_system_collections=False)\n    if prefix is not None:\n        collections = [c for c in collections if c.startswith(prefix)]\n    if suffix is not None:\n        collections = [c for c in collections if c.endswith(suffix)]\n    return sorted(collections)",
    "docstring": "Returns a sorted list of collection names found in ``db``.\n\n    Arguments:\n\n        db (Database): A pymongo Database object. Can be obtained\n            with ``get_db``.\n\n        collection (str): Name of a collection. If the collection is\n            present in the MongoDB database, a single-element list will\n            be returned with the collecion name. If not, an empty list\n            will be returned. This option is primarly included to allow\n            for quick checking to see if a collection name is present.\n            Default is None, which results in this option being ignored.\n\n        prefix (str): If supplied, only collections that begin with\n            ``prefix`` will be returned.\n\n        suffix (str): If supplied, only collections that end with\n            ``suffix`` will be returned.\n\n    Returns:\n\n        list: A sorted list of collection names."
  },
  {
    "code": "def _check_changetype(self, dn, changetype, attr_value):\n        if dn is None:\n            self._error('Read changetype: before getting valid dn: line.')\n        if changetype is not None:\n            self._error('Two lines starting with changetype: in one record.')\n        if attr_value not in CHANGE_TYPES:\n            self._error('changetype value %s is invalid.' % attr_value)",
    "docstring": "Check changetype attribute for issues."
  },
  {
    "code": "def get_copies_count(self):\n        setup = api.get_setup()\n        default_num = setup.getDefaultNumberOfCopies()\n        request_num = self.request.form.get(\"copies_count\")\n        return to_int(request_num, default_num)",
    "docstring": "Return the copies_count number request parameter\n\n        :returns: the number of copies for each sticker as stated\n        in the request\n        :rtype: int"
  },
  {
    "code": "def _offset_for(self, param):\n        if param.has_parent():\n            p = param._parent_._get_original(param)\n            if p in self.parameters:\n                return reduce(lambda a,b: a + b.size, self.parameters[:p._parent_index_], 0)\n            return self._offset_for(param._parent_) + param._parent_._offset_for(param)\n        return 0",
    "docstring": "Return the offset of the param inside this parameterized object.\n        This does not need to account for shaped parameters, as it\n        basically just sums up the parameter sizes which come before param."
  },
  {
    "code": "def StartTiming(self, profile_name):\n    if profile_name not in self._profile_measurements:\n      self._profile_measurements[profile_name] = CPUTimeMeasurement()\n    self._profile_measurements[profile_name].SampleStart()",
    "docstring": "Starts timing CPU time.\n\n    Args:\n      profile_name (str): name of the profile to sample."
  },
  {
    "code": "def wrap_exception(func: Callable) -> Callable:\n    try:\n        from pygatt.backends.bgapi.exceptions import BGAPIError\n        from pygatt.exceptions import NotConnectedError\n    except ImportError:\n        return func\n    def _func_wrapper(*args, **kwargs):\n        try:\n            return func(*args, **kwargs)\n        except BGAPIError as exception:\n            raise BluetoothBackendException() from exception\n        except NotConnectedError as exception:\n            raise BluetoothBackendException() from exception\n    return _func_wrapper",
    "docstring": "Decorator to wrap pygatt exceptions into BluetoothBackendException."
  },
  {
    "code": "def hashable_identity(obj):\n    if hasattr(obj, '__func__'):\n        return (id(obj.__func__), id(obj.__self__))\n    elif hasattr(obj, 'im_func'):\n        return (id(obj.im_func), id(obj.im_self))\n    elif isinstance(obj, (basestring, unicode)):\n        return obj\n    else:\n        return id(obj)",
    "docstring": "Generate a hashable ID that is stable for methods etc\n\n    Approach borrowed from blinker. Why it matters: see e.g.\n    http://stackoverflow.com/questions/13348031/python-bound-and-unbound-method-object"
  },
  {
    "code": "def clean_up_datetime(obj_map):\n    clean_map = {}\n    for key, value in obj_map.items():\n        if isinstance(value, datetime.datetime):\n            clean_map[key] = {\n                'year': value.year,\n                'month': value.month,\n                'day': value.day,\n                'hour': value.hour,\n                'minute': value.minute,\n                'second': value.second,\n                'microsecond': value.microsecond,\n                'tzinfo': value.tzinfo\n            }\n        elif isinstance(value, dict):\n            clean_map[key] = clean_up_datetime(value)\n        elif isinstance(value, list):\n            if key not in clean_map:\n                clean_map[key] = []\n            if len(value) > 0:\n                for index, list_value in enumerate(value):\n                    if isinstance(list_value, dict):\n                        clean_map[key].append(clean_up_datetime(list_value))\n                    else:\n                        clean_map[key].append(list_value)\n            else:\n                clean_map[key] = value\n        else:\n            clean_map[key] = value\n    return clean_map",
    "docstring": "convert datetime objects to dictionaries for storage"
  },
  {
    "code": "def get_quantmap(features, acc_col, quantfields):\n    qmap = {}\n    for feature in features:\n        feat_acc = feature.pop(acc_col)\n        qmap[feat_acc] = {qf: feature[qf] for qf in quantfields}\n    return qmap",
    "docstring": "Runs through proteins that are in a quanted protein table, extracts\n    and maps their information based on the quantfields list input.\n    Map is a dict with protein_accessions as keys."
  },
  {
    "code": "def replace(self, src):\n        \"Given some source html substitute and annotated as applicable\"\n        for html in self.substitutions.keys():\n            if src == html:\n                annotation = self.annotation % self.substitutions[src][1]\n                return annotation + self.substitutions[src][0]\n        return src",
    "docstring": "Given some source html substitute and annotated as applicable"
  },
  {
    "code": "def main():\n    global DEFAULT_SERVER_PORT, DEFAULT_SERVER_LISTEN_ADDRESS, DEFAULT_LOGGING_LEVEL\n    if 'ANYBADGE_PORT' in environ:\n        DEFAULT_SERVER_PORT = environ['ANYBADGE_PORT']\n    if 'ANYBADGE_LISTEN_ADDRESS' in environ:\n        DEFAULT_SERVER_LISTEN_ADDRESS = environ['ANYBADGE_LISTEN_ADDRESS']\n    if 'ANYBADGE_LOG_LEVEL' in environ:\n        DEFAULT_LOGGING_LEVEL = logging.getLevelName(environ['ANYBADGE_LOG_LEVEL'])\n    args = parse_args()\n    logging_level = DEFAULT_LOGGING_LEVEL\n    if args.debug:\n        logging_level = logging.DEBUG\n    logging.basicConfig(format='%(asctime)-15s %(levelname)s:%(filename)s(%(lineno)d):%(funcName)s: %(message)s',\n                        level=logging_level)\n    logger.info('Starting up anybadge server.')\n    run(listen_address=args.listen_address, port=args.port)",
    "docstring": "Run server."
  },
  {
    "code": "def run(addr, *commands, **kwargs):\n    results = []\n    handler = VarnishHandler(addr, **kwargs)\n    for cmd in commands:\n        if isinstance(cmd, tuple) and len(cmd)>1:\n            results.extend([getattr(handler, c[0].replace('.','_'))(*c[1:]) for c in cmd])\n        else:\n            results.append(getattr(handler, cmd.replace('.','_'))(*commands[1:]))\n            break\n    handler.close()\n    return results",
    "docstring": "Non-threaded batch command runner returning output results"
  },
  {
    "code": "def short_repr(item, max_length=15):\n    item = repr(item)\n    if len(item) > max_length:\n        item = '{}...{}'.format(item[:max_length - 3], item[-1])\n    return item",
    "docstring": "Short representation of item if it is too long"
  },
  {
    "code": "def train_by_stream(self, stream: StreamWrapper) -> None:\n        self._run_epoch(stream=stream, train=True)",
    "docstring": "Train the model with the given stream.\n\n        :param stream: stream to train with"
  },
  {
    "code": "def dict_to_vtk(data, path='./dictvtk', voxel_size=1, origin=(0, 0, 0)):\n    r\n    vs = voxel_size\n    for entry in data:\n        if data[entry].dtype == bool:\n            data[entry] = data[entry].astype(np.int8)\n        if data[entry].flags['C_CONTIGUOUS']:\n            data[entry] = np.ascontiguousarray(data[entry])\n    imageToVTK(path, cellData=data, spacing=(vs, vs, vs), origin=origin)",
    "docstring": "r\"\"\"\n    Accepts multiple images as a dictionary and compiles them into a vtk file\n\n    Parameters\n    ----------\n    data : dict\n        A dictionary of *key: value* pairs, where the *key* is the name of the\n        scalar property stored in each voxel of the array stored in the\n        corresponding *value*.\n    path : string\n        Path to output file\n    voxel_size : int\n        The side length of the voxels (voxels  are cubic)\n    origin : float\n        data origin (according to selected voxel size)\n\n    Notes\n    -----\n    Outputs a vtk, vtp or vti file that can opened in ParaView"
  },
  {
    "code": "def get_boot_device(self):\n        operation = 'get_boot_device'\n        try:\n            boot_device = self.sp_manager.get_boot_device()\n            return boot_device\n        except UcsException as ex:\n            print(_(\"Cisco client exception: %(msg)s.\"), {'msg': ex})\n            raise exception.UcsOperationError(operation=operation, error=ex)",
    "docstring": "Get the current boot device for the node.\n\n            Provides the current boot device of the node. Be aware that not\n            all drivers support this.\n\n            :raises: InvalidParameterValue if any connection parameters are\n                incorrect.\n            :raises: MissingParameterValue if a required parameter is missing\n            :returns: a dictionary containing:\n\n            :boot_device: the boot device, one of\n            :mod:`ironic.common.boot_devices` or None if it is unknown.\n            :persistent: Whether the boot device will persist to all\n                future boots or not, None if it is unknown."
  },
  {
    "code": "def doLog(self, level, where, format, *args, **kwargs):\n        if _canShortcutLogging(self.logCategory, level):\n            return {}\n        args = self.logFunction(*args)\n        return doLog(level, self.logObjectName(), self.logCategory,\n            format, args, where=where, **kwargs)",
    "docstring": "Log a message at the given level, with the possibility of going\n        higher up in the stack.\n\n        @param level: log level\n        @type  level: int\n        @param where: how many frames to go back from the last log frame;\n                      or a function (to log for a future call)\n        @type  where: int (negative), or function\n\n        @param kwargs: a dict of pre-calculated values from a previous\n                       doLog call\n\n        @return: a dict of calculated variables, to be reused in a\n                 call to doLog that should show the same location\n        @rtype:  dict"
  },
  {
    "code": "def sort_func(self, key):\n        if key == self._KEYS.TIME:\n            return 'aaa'\n        if key == self._KEYS.DATA:\n            return 'zzy'\n        if key == self._KEYS.SOURCE:\n            return 'zzz'\n        return key",
    "docstring": "Logic for sorting keys in a `Spectrum` relative to one another."
  },
  {
    "code": "def find_all(self, kw: YangIdentifier,\n                 pref: YangIdentifier = None) -> List[\"Statement\"]:\n        return [c for c in self.substatements\n                if c.keyword == kw and c.prefix == pref]",
    "docstring": "Return the list all substatements with the given keyword and prefix.\n\n        Args:\n            kw: Statement keyword (local part for extensions).\n            pref: Keyword prefix (``None`` for built-in statements)."
  },
  {
    "code": "def _load(self, filename=None):\n        if not filename:\n            filename = self.filename\n        wb_ = open_workbook(filename)\n        self.rsr = {}\n        sheet_names = []\n        for sheet in wb_.sheets():\n            if sheet.name in ['Title', ]:\n                continue\n            ch_name = AHI_BAND_NAMES.get(\n                sheet.name.strip(), sheet.name.strip())\n            sheet_names.append(sheet.name.strip())\n            self.rsr[ch_name] = {'wavelength': None,\n                                 'response': None}\n            wvl = np.array(\n                sheet.col_values(0, start_rowx=5, end_rowx=5453))\n            resp = np.array(\n                sheet.col_values(2, start_rowx=5, end_rowx=5453))\n            self.rsr[ch_name]['wavelength'] = wvl\n            self.rsr[ch_name]['response'] = resp",
    "docstring": "Load the Himawari AHI RSR data for the band requested"
  },
  {
    "code": "def query_list_pager(con, idx, kind='2'):\n        all_list = MPost.query_under_condition(con, kind=kind)\n        return all_list[(idx - 1) * CMS_CFG['list_num']: idx * CMS_CFG['list_num']]",
    "docstring": "Get records of certain pager."
  },
  {
    "code": "def keys(self, prefix=None, limit=None, offset=None, namespace=None):\n        return self.make_context(prefix=prefix, limit=limit, offset=offset,\n                                 namespace=namespace).keys()",
    "docstring": "Get gauge keys"
  },
  {
    "code": "def count(self, low, high=None):\n        if high is None:\n            high = low\n        return self.database.zcount(self.key, low, high)",
    "docstring": "Return the number of items between the given bounds."
  },
  {
    "code": "def write_record(self, warc_record):\n        warc_record.write_to(self.fileobj)\n        if isinstance(self.fileobj, gzip2.GzipFile):\n            self.fileobj.close_member()",
    "docstring": "Adds a warc record to this WARC file."
  },
  {
    "code": "def add_compliance_header(self):\n        if (self.manipulator.compliance_uri is not None):\n            self.headers['Link'] = '<' + \\\n                self.manipulator.compliance_uri + '>;rel=\"profile\"'",
    "docstring": "Add IIIF Compliance level header to response."
  },
  {
    "code": "def normalize_likes(sql):\n    sql = sql.replace('%', '')\n    sql = re.sub(r\"LIKE '[^\\']+'\", 'LIKE X', sql)\n    matches = re.finditer(r'(or|and) [^\\s]+ LIKE X', sql, flags=re.IGNORECASE)\n    matches = [match.group(0) for match in matches] if matches else None\n    if matches:\n        for match in set(matches):\n            sql = re.sub(r'(\\s?' + re.escape(match) + ')+', ' ' + match + ' ...', sql)\n    return sql",
    "docstring": "Normalize and wrap LIKE statements\n\n    :type sql str\n    :rtype: str"
  },
  {
    "code": "def dict2bibtex(data):\n    bibtex = '@' + data['ENTRYTYPE'] + '{' + data['ID'] + \",\\n\"\n    for field in [i for i in sorted(data) if i not in ['ENTRYTYPE', 'ID']]:\n        bibtex += \"\\t\" + field + \"={\" + data[field] + \"},\\n\"\n    bibtex += \"}\\n\\n\"\n    return bibtex",
    "docstring": "Convert a single BibTeX entry dict to a BibTeX string.\n\n    :param data: A dict representing BibTeX entry, as the ones from \\\n            ``bibtexparser.BibDatabase.entries`` output.\n    :return: A formatted BibTeX string."
  },
  {
    "code": "def path_for_import(name):\n    return os.path.dirname(os.path.abspath(import_module(name).__file__))",
    "docstring": "Returns the directory path for the given package or module."
  },
  {
    "code": "def getkey(stype, site_id=None, key=None):\n\t'Returns the cache key depending on its type.'\n\tbase = '{0}.feedjack'.format(settings.CACHE_MIDDLEWARE_KEY_PREFIX)\n\tif stype == T_HOST: return '{0}.hostcache'.format(base)\n\telif stype == T_ITEM: return '{0}.{1}.item.{2}'.format(base, site_id, str2md5(key))\n\telif stype == T_META: return '{0}.{1}.meta'.format(base, site_id)\n\telif stype == T_INTERVAL: return '{0}.interval.{1}'.format(base, str2md5(key))",
    "docstring": "Returns the cache key depending on its type."
  },
  {
    "code": "def linkify_s_by_sg(self, servicegroups):\n        for serv in self:\n            new_servicegroups = []\n            if hasattr(serv, 'servicegroups') and serv.servicegroups != '':\n                for sg_name in serv.servicegroups:\n                    sg_name = sg_name.strip()\n                    servicegroup = servicegroups.find_by_name(sg_name)\n                    if servicegroup is not None:\n                        new_servicegroups.append(servicegroup.uuid)\n                    else:\n                        err = \"Error: the servicegroup '%s' of the service '%s' is unknown\" %\\\n                              (sg_name, serv.get_dbg_name())\n                        serv.add_error(err)\n            serv.servicegroups = new_servicegroups",
    "docstring": "Link services with servicegroups\n\n        :param servicegroups: Servicegroups\n        :type servicegroups: alignak.objects.servicegroup.Servicegroups\n        :return: None"
  },
  {
    "code": "def partial(cls, prefix, source):\n        match = prefix + \".\"\n        matches = cls([(key[len(match):], source[key]) for key in source if key.startswith(match)])\n        if not matches:\n            raise ValueError()\n        return matches",
    "docstring": "Strip a prefix from the keys of another dictionary, returning a Bunch containing only valid key, value pairs."
  },
  {
    "code": "def remove_security_group(self, name):\n        for group in self.security_groups:\n            if group.isc_name == name:\n                group.delete()",
    "docstring": "Remove a security group from container"
  },
  {
    "code": "def contrast(self, color, step):\n        hls = colorsys.rgb_to_hls(*self.rgb(color))\n        if self.is_light(color):\n            return colorsys.hls_to_rgb(hls[0], hls[1] - step, hls[2])\n        else:\n            return colorsys.hls_to_rgb(hls[0], hls[1] + step, hls[2])",
    "docstring": "if color is dark, will return a lighter one, otherwise darker"
  },
  {
    "code": "def close(self):\n        if hasattr(self, \"thread\"):\n            self.thread._exit = True\n            self.thread.join(1000)\n        if self._conn is not None:\n            self._conn.close()",
    "docstring": "Close the current connection and terminate the agent\n        Should be called manually"
  },
  {
    "code": "def _validate_condition_keys(self, field, value, error):\n        if 'field' in value:\n            operators = self.nonscalar_conditions + self.scalar_conditions\n            matches = sum(1 for k in operators if k in value)\n            if matches == 0:\n                error(field, 'Must contain one of {}'.format(operators))\n                return False\n            elif matches > 1:\n                error(\n                    field,\n                    'Must contain no more than one of {}'.format(operators)\n                )\n                return False\n            return True\n        elif 'and' in value:\n            for condition in value['and']:\n                self._validate_condition_keys(field, condition, error)\n        elif 'or' in value:\n            for condition in value['or']:\n                self._validate_condition_keys(field, condition, error)\n        else:\n            error(field, \"Must contain field + operator keys, 'and', or 'or'.\")\n            return False",
    "docstring": "Validates that all of the keys in one of the sets of keys are defined\n        as keys of ``value``."
  },
  {
    "code": "def html(self, text=TEXT):\n        self.logger.debug(\"Generating the HTML report{}...\"\n                          .format([\"\", \" (text only)\"][text]))\n        html = []\n        for piece in self._pieces:\n            if isinstance(piece, string_types):\n                html.append(markdown2.markdown(piece, extras=[\"tables\"]))\n            elif isinstance(piece, Element):\n                html.append(piece.html())\n        return \"\\n\\n\".join(html)",
    "docstring": "Generate an HTML file from the report data."
  },
  {
    "code": "def unregister_peer(self, connection_id):\n        public_key = self.peer_to_public_key(connection_id)\n        if public_key:\n            self._consensus_notifier.notify_peer_disconnected(public_key)\n        with self._lock:\n            if connection_id in self._peers:\n                del self._peers[connection_id]\n                LOGGER.debug(\"Removed connection_id %s, \"\n                             \"connected identities are now %s\",\n                             connection_id, self._peers)\n                self._topology.set_connection_status(connection_id,\n                                                     PeerStatus.TEMP)\n            else:\n                LOGGER.warning(\"Connection unregister failed as connection \"\n                               \"was not registered: %s\",\n                               connection_id)",
    "docstring": "Removes a connection_id from the registry.\n\n        Args:\n            connection_id (str): A unique identifier which identifies an\n                connection on the network server socket."
  },
  {
    "code": "def add_site(self, site_name, location_name=None, er_data=None, pmag_data=None):\n        if location_name:\n            location = self.find_by_name(location_name, self.locations)\n            if not location:\n                location = self.add_location(location_name)\n        else:\n            location = None\n        new_site = Site(site_name, location, self.data_model, er_data, pmag_data)\n        self.sites.append(new_site)\n        if location:\n            location.sites.append(new_site)\n        return new_site",
    "docstring": "Create a Site object and add it to self.sites.\n        If a location name is provided, add the site to location.sites as well."
  },
  {
    "code": "def add_header(self, entry):\n        info = entry.split('\\t')\n        self.n_individuals = len(info)-9\n        for i,v in enumerate(info[9:]):\n            self.individuals[v] = i\n        return self.n_individuals > 0",
    "docstring": "Parses the VCF Header field and returns the number of samples in the VCF file"
  },
  {
    "code": "def update_cursor_position(self, line, index):\n        value = 'Line {}, Col {}'.format(line + 1, index + 1)\n        self.set_value(value)",
    "docstring": "Update cursor position."
  },
  {
    "code": "def reciprocal(self):\n        try:\n            return self.character.portal[self.dest][self.orig]\n        except KeyError:\n            raise KeyError(\"This portal has no reciprocal\")",
    "docstring": "If there's another Portal connecting the same origin and\n        destination that I do, but going the opposite way, return\n        it. Else raise KeyError."
  },
  {
    "code": "def load_zipfile(self, path):\n        zin = zipfile.ZipFile(path)\n        for zinfo in zin.infolist():\n            name = zinfo.filename\n            if name.endswith(\"/\"):\n                self.mkdir(name)\n            else:\n                content = zin.read(name)\n                self.touch(name, content)",
    "docstring": "import contents of a zipfile"
  },
  {
    "code": "def stop(self, accountID, **kwargs):\n        return self.create(\n            accountID,\n            order=StopOrderRequest(**kwargs)\n        )",
    "docstring": "Shortcut to create a Stop Order in an Account\n\n        Args:\n            accountID : The ID of the Account\n            kwargs : The arguments to create a StopOrderRequest\n\n        Returns:\n            v20.response.Response containing the results from submitting\n            the request"
  },
  {
    "code": "def _count_classified_pixels(self):\n        class_values = self.class_dictionary.values()\n        classification_count = np.array([[[np.count_nonzero(prediction[np.nonzero(mask)] == class_val)\n                                           for prediction, mask in zip(self.classification_masks, masktype)]\n                                          for masktype in self.truth_masks]\n                                         for class_val in class_values])\n        classification_count = np.moveaxis(classification_count, 0, -1)\n        classification_count = np.moveaxis(classification_count, 0, -2)\n        if self.pixel_classification_counts is None:\n            self.pixel_classification_counts = np.copy(classification_count)\n        else:\n            self.pixel_classification_counts = np.concatenate((self.pixel_classification_counts, classification_count))",
    "docstring": "Count the pixels belonging to each classified class."
  },
  {
    "code": "def set(self, fmt, offset, value):\n        bfo = BitFieldOperation(self.database, self.key)\n        return bfo.set(fmt, offset, value)",
    "docstring": "Set the value of a given bitfield.\n\n        :param fmt: format-string for the bitfield being read, e.g. u8 for an\n            unsigned 8-bit integer.\n        :param int offset: offset (in number of bits).\n        :param int value: value to set at the given position.\n        :returns: a :py:class:`BitFieldOperation` instance."
  },
  {
    "code": "def _query(self, sql, *params):\n        cursor = None\n        try:\n            cursor = self._cursor()\n            cursor.execute(sql, params)\n            return cursor\n        except psycopg2.Error as e:\n            if cursor and cursor.connection.closed == 0:\n                if isinstance(e, psycopg2.OperationalError):\n                    self.close_connection()\n                else:\n                    raise e\n            if self.state == 'restarting':\n                raise RetryFailedError('cluster is being restarted')\n            raise PostgresConnectionException('connection problems')",
    "docstring": "We are always using the same cursor, therefore this method is not thread-safe!!!\n        You can call it from different threads only if you are holding explicit `AsyncExecutor` lock,\n        because the main thread is always holding this lock when running HA cycle."
  },
  {
    "code": "def get_model_alias(self):\n        if self.model_alias:\n            return self.model_alias\n        return '{}.{}'.format(self.get_app_label(), self.get_model_name())",
    "docstring": "Get model alias"
  },
  {
    "code": "def _GetConnection(self):\n\t\twhile self.conn is None:\n\t\t\tself.conn = Pool().GetConnection(self.connInfo)\n\t\t\tif self.conn is not None:\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\ttime.sleep(1)",
    "docstring": "Retieves a prelocked connection from the Pool\n\t\t\n\t\t@author: Nick Verbeck\n\t\t@since: 9/7/2008"
  },
  {
    "code": "def properties(self):\n        value = self._schema.get(\"properties\", {})\n        if not isinstance(value, dict):\n            raise SchemaError(\n                \"properties value {0!r} is not an object\".format(value))\n        return value",
    "docstring": "Schema for particular properties of the object."
  },
  {
    "code": "def batch(self, requests):\n        for request in requests:\n            if 'body' in request:\n                request['body'] = urlencode(request['body'])\n        def _grouper(complete_list, n=1):\n            for i in range(0, len(complete_list), n):\n                yield complete_list[i:i + n]\n        responses = []\n        for group in _grouper(requests, 50):\n            responses += self.post(\n                batch=json.dumps(group)\n            )\n        for response, request in zip(responses, requests):\n            if not response:\n                yield None\n                continue\n            try:\n                yield self._parse(response['body'])\n            except FacepyError as exception:\n                exception.request = request\n                yield exception",
    "docstring": "Make a batch request.\n\n        :param requests: A list of dictionaries with keys 'method', 'relative_url' and optionally 'body'.\n\n        Yields a list of responses and/or exceptions."
  },
  {
    "code": "def from_series(cls, series, offset=0):\n        return cls(data=series.data, index=series.index, data_name=series.data_name, index_name=series.index_name,\n                   sort=series.sort, offset=offset)",
    "docstring": "Creates and return a Series from a Series\n\n        :param series: raccoon Series\n        :param offset: offset value must be provided as there is no equivalent for a DataFrame\n        :return: Series"
  },
  {
    "code": "def post(self, url: StrOrURL,\n             *, data: Any=None, **kwargs: Any) -> '_RequestContextManager':\n        return _RequestContextManager(\n            self._request(hdrs.METH_POST, url,\n                          data=data,\n                          **kwargs))",
    "docstring": "Perform HTTP POST request."
  },
  {
    "code": "def detect_images_and_galleries(generators):\n    for generator in generators:\n        if isinstance(generator, ArticlesGenerator):\n            for article in itertools.chain(generator.articles, generator.translations, generator.drafts):\n                detect_image(generator, article)\n                detect_gallery(generator, article)\n        elif isinstance(generator, PagesGenerator):\n            for page in itertools.chain(generator.pages, generator.translations, generator.hidden_pages):\n                detect_image(generator, page)\n                detect_gallery(generator, page)",
    "docstring": "Runs generator on both pages and articles."
  },
  {
    "code": "def abort_job(self, job_id):\n        response = requests.post(self._get_abort_job_url(job_id),\n                                 headers=self._get_abort_job_headers(),\n                                 data=self._get_abort_job_xml())\n        response.raise_for_status()\n        return response",
    "docstring": "Abort an existing job. When a job is aborted, no more records are processed.\n        Changes to data may already have been committed and aren't rolled back.\n\n        :param job_id: job_id as returned by 'create_operation_job(...)'\n        :return: abort response as xml"
  },
  {
    "code": "def gaussfill(dem, size=3, newmask=None):\n    smooth = gauss_fltr_astropy(dem, size=size)\n    smooth[~dem.mask] = dem[~dem.mask]\n    if newmask is not None:\n        smooth = np.ma.array(smooth, mask=newmask)\n    return smooth",
    "docstring": "Gaussian filter with filling"
  },
  {
    "code": "def from_fits(cls, filename):\n        table = Table.read(filename)\n        intervals = np.vstack((table['UNIQ'], table['UNIQ']+1)).T\n        nuniq_interval_set = IntervalSet(intervals)\n        interval_set = IntervalSet.from_nuniq_interval_set(nuniq_interval_set)\n        return cls(interval_set)",
    "docstring": "Loads a MOC from a FITS file.\n\n        The specified FITS file must store the MOC (i.e. the list of HEALPix cells it contains) in a binary HDU table.\n\n        Parameters\n        ----------\n        filename : str\n            The path to the FITS file.\n\n        Returns\n        -------\n        result : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC`\n            The resulting MOC."
  },
  {
    "code": "def _cryptography_cipher(key, iv):\n    return Cipher(\n        algorithm=algorithms.TripleDES(key),\n        mode=modes.CBC(iv),\n        backend=default_backend()\n    )",
    "docstring": "Build a cryptography TripleDES Cipher object.\n\n    :param bytes key: Encryption key\n    :param bytesiv iv: Initialization vector\n    :returns: TripleDES Cipher instance\n    :rtype: cryptography.hazmat.primitives.ciphers.Cipher"
  },
  {
    "code": "def build_event_graph(graph, tree, node):\n    if node_key(node) in graph:\n        return\n    type = get_type(node)\n    text = get_text(node)\n    label = '%s (%s)' % (type, text)\n    graph.add_node(node_key(node), type=type, label=label, text=text)\n    args = get_args(node)\n    for arg_role, (arg_id, arg_tag) in args.items():\n        arg = get_node_by_id(tree, arg_id)\n        if arg is None:\n            arg = arg_tag\n        build_event_graph(graph, tree, arg)\n        graph.add_edge(node_key(node), node_key(arg), type=arg_role,\n                       label=arg_role)",
    "docstring": "Return a DiGraph of a specific event structure, built recursively"
  },
  {
    "code": "def is_ome(self):\n        if self.index > 1 or not self.description:\n            return False\n        d = self.description\n        return d[:14] == '<?xml version=' and d[-6:] == '</OME>'",
    "docstring": "Page contains OME-XML in ImageDescription tag."
  },
  {
    "code": "def _get_parameter(self, name, eopatch):\n        if hasattr(self, name) and getattr(self, name) is not None:\n            return getattr(self, name)\n        if name == 'bbox' and eopatch.bbox:\n            return eopatch.bbox\n        if name in eopatch.meta_info:\n            return eopatch.meta_info[name]\n        if name == 'maxcc':\n            return 1.0\n        if name == 'time_difference':\n            return dt.timedelta(seconds=-1)\n        if name in ('size_x', 'size_y'):\n            return None\n        raise ValueError('Parameter {} was neither defined in initialization of {} nor is contained in '\n                         'EOPatch'.format(name, self.__class__.__name__))",
    "docstring": "Collects the parameter either from initialization parameters or from EOPatch"
  },
  {
    "code": "def report_message(report):\n    body = 'Error: return code != 0\\n\\n'\n    body += 'Archive: {}\\n\\n'.format(report['archive'])\n    body += 'Docker image: {}\\n\\n'.format(report['image'])\n    body += 'Docker container: {}\\n\\n'.format(report['container_id'])\n    return body",
    "docstring": "Report message."
  },
  {
    "code": "def predict(self, x):\n        if self._is_leaf():\n            d1 = self.predict_initialize['count_dict']\n            d2 = count_dict(self.Y)\n            for key, value in d1.iteritems():\n                if key in d2:\n                    d2[key] += value\n                else:\n                    d2[key] = value\n            return argmax(d2)\n        else:\n            if self.criterion(x):\n                return self.right.predict(x)\n            else:\n                return self.left.predict(x)",
    "docstring": "Make prediction recursively. Use both the samples inside the current\n        node and the statistics inherited from parent."
  },
  {
    "code": "def generate_cert(domain):\n    result = __salt__['cmd.run_all']([\"icinga2\", \"pki\", \"new-cert\", \"--cn\", domain, \"--key\", \"{0}{1}.key\".format(get_certs_path(), domain), \"--cert\", \"{0}{1}.crt\".format(get_certs_path(), domain)], python_shell=False)\n    return result",
    "docstring": "Generate an icinga2 client certificate and key.\n\n    Returns::\n        icinga2 pki new-cert --cn domain.tld --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' icinga2.generate_cert domain.tld"
  },
  {
    "code": "def find(cls, api_key=None, fetch_all=True, endpoint=None, maximum=None,\n             **kwargs):\n        exclude = kwargs.pop('exclude', None)\n        if isinstance(exclude, six.string_types):\n            exclude = [exclude, ]\n        query_params = cls.translate_query_params(**kwargs)\n        if endpoint is None:\n            endpoint = cls.get_endpoint()\n        if fetch_all:\n            result = cls._fetch_all(api_key=api_key, endpoint=endpoint,\n                                    maximum=maximum,\n                                    **query_params)\n        else:\n            result = cls._fetch_page(api_key=api_key, endpoint=endpoint,\n                                     maximum=maximum,\n                                     **query_params)\n        collection = [r for r in result\n                      if not cls._find_exclude_filter(exclude, r)]\n        return collection",
    "docstring": "Find some entities from the API endpoint.\n\n        If no api_key is provided, the global api key will be used.\n        If fetch_all is True, page through all the data and find every record\n        that exists.\n        If add_headers is provided (as a dict) use it to add headers to the\n        HTTP request, eg.\n\n            {'host': 'some.hidden.host'}\n\n        Capitalizing header keys does not matter.\n\n        Remaining keyword arguments will be passed as `query_params` to the\n        instant method `request` (ClientMixin)."
  },
  {
    "code": "def create_template(self, s, provider_name=None):\n        if provider_name is None:\n            provider_name = self.supported_providers[0]\n        return template_exception_handler(\n            lambda: self.get_provider(provider_name).create_template(s),\n            self.error_context\n        )",
    "docstring": "Creates a template from the given string based on the specified provider or the provider with\n        highest precedence.\n\n        Args:\n            s: The string to convert to a template.\n            provider_name: The name of the provider to use to create the template."
  },
  {
    "code": "def book_name(self, number):\n        try:\n            name = self.cur.execute(\"SELECT name FROM book WHERE number = ?;\", [number]).fetchone()\n        except:\n            self.error(\"cannot look up name of book number %s\" % number)\n        return(str(name[0]))",
    "docstring": "Return name of book with given index."
  },
  {
    "code": "def datapath4file(filename, ext:str='.tgz', archive=True):\n    \"Return data path to `filename`, checking locally first then in the config file.\"\n    local_path = URLs.LOCAL_PATH/'data'/filename\n    if local_path.exists() or local_path.with_suffix(ext).exists(): return local_path\n    elif archive: return Config.data_archive_path() / filename\n    else: return Config.data_path() / filename",
    "docstring": "Return data path to `filename`, checking locally first then in the config file."
  },
  {
    "code": "def level_i18n_name(self):\n        for level, name in spatial_granularities:\n            if self.level == level:\n                return name\n        return self.level_name",
    "docstring": "In use within templates for dynamic translations."
  },
  {
    "code": "def _check_point(self, lat, lng):\n        if abs(lat) > 90 or abs(lng) > 180:\n            msg = \"Illegal lat and/or lng, (%s, %s) provided.\" % (lat, lng)\n            raise IllegalPointException(msg)",
    "docstring": "Checks if latitude and longitude correct"
  },
  {
    "code": "def calculate_hash_of_files(files, root):\n    file_hash = hashlib.md5()\n    for fname in sorted(files):\n        fileobj = os.path.join(root, fname)\n        file_hash.update((fname + \"\\0\").encode())\n        with open(fileobj, \"rb\") as filedes:\n            for chunk in iter(lambda: filedes.read(4096), \"\"):\n                if not chunk:\n                    break\n                file_hash.update(chunk)\n            file_hash.update(\"\\0\".encode())\n    return file_hash.hexdigest()",
    "docstring": "Return a hash of all of the given files at the given root.\n\n    Adapted from stacker.hooks.aws_lambda; used according to its license:\n    https://github.com/cloudtools/stacker/blob/1.4.0/LICENSE\n\n    Args:\n        files (list[str]): file names to include in the hash calculation,\n            relative to ``root``.\n        root (str): base directory to analyze files in.\n    Returns:\n        str: A hash of the hashes of the given files."
  },
  {
    "code": "def _construct_auto_distance(features, column_types):\n    numeric_ftrs = []\n    string_ftrs = []\n    dict_ftrs = []\n    for ftr in features:\n        try:\n            ftr_type = column_types[ftr]\n        except:\n            raise ValueError(\"The specified feature does not exist in the \" +\n                             \"input data.\")\n        if ftr_type == str:\n            string_ftrs.append(ftr)\n        elif ftr_type == dict:\n            dict_ftrs.append(ftr)\n        elif ftr_type in [int, float, _array.array]:\n            numeric_ftrs.append(ftr)\n        else:\n            raise TypeError(\"Unable to automatically construct a distance \" +\n                            \"function for feature '{}'. \".format(ftr) +\n                            \"For the nearest neighbor classifier, features \" +\n                            \"must be of type integer, float, string, dictionary, \" +\n                            \"or array.array.\")\n    dist = []\n    for ftr in string_ftrs:\n        dist.append([[ftr], 'levenshtein', 1])\n    if len(dict_ftrs) > 0:\n        dist.append([dict_ftrs, 'weighted_jaccard', len(dict_ftrs)])\n    if len(numeric_ftrs) > 0:\n        dist.append([numeric_ftrs, 'euclidean', len(numeric_ftrs)])\n    return dist",
    "docstring": "Construct a composite distance function for a set of features, based on the\n    types of those features.\n\n    NOTE: This function is very similar to\n    `:func:_nearest_neighbors.choose_auto_distance`. The function is separate\n    because the auto-distance logic different than for each nearest\n    neighbors-based toolkit.\n\n    Parameters\n    ----------\n    features : list[str]\n        Names of for which to construct a distance function.\n\n    column_types : dict(string, type)\n        Names and types of all columns.\n\n    Returns\n    -------\n    dist : list[list]\n        A composite distance function. Each element of the inner list has three\n        elements: a list of feature names (strings), a distance function name\n        (string), and a weight (float)."
  },
  {
    "code": "def from_geom(geom):\n        name = geom.params['stat']\n        kwargs = geom._kwargs\n        if (not isinstance(name, type) and\n                hasattr(name, 'compute_layer')):\n            return name\n        if isinstance(name, stat):\n            return name\n        elif isinstance(name, type) and issubclass(name, stat):\n            klass = name\n        elif is_string(name):\n            if not name.startswith('stat_'):\n                name = 'stat_{}'.format(name)\n            klass = Registry[name]\n        else:\n            raise PlotnineError(\n                'Unknown stat of type {}'.format(type(name)))\n        valid_kwargs = (\n             (klass.aesthetics() |\n              klass.DEFAULT_PARAMS.keys()) &\n             kwargs.keys())\n        params = {k: kwargs[k] for k in valid_kwargs}\n        return klass(geom=geom, **params)",
    "docstring": "Return an instantiated stat object\n\n        stats should not override this method.\n\n        Parameters\n        ----------\n        geom : geom\n            `geom`\n\n        Returns\n        -------\n        out : stat\n            A stat object\n\n        Raises\n        ------\n        :class:`PlotnineError` if unable to create a `stat`."
  },
  {
    "code": "def mmInformation(NetworkName_presence=0, NetworkName_presence1=0,\n                  TimeZone_presence=0, TimeZoneAndTime_presence=0,\n                  LsaIdentifier_presence=0):\n    a = TpPd(pd=0x5)\n    b = MessageType(mesType=0x32)\n    packet = a / b\n    if NetworkName_presence is 1:\n        c = NetworkNameHdr(ieiNN=0x43, eightBitNN=0x0)\n        packet = packet / c\n    if NetworkName_presence1 is 1:\n        d = NetworkNameHdr(ieiNN=0x45, eightBitNN=0x0)\n        packet = packet / d\n    if TimeZone_presence is 1:\n        e = TimeZoneHdr(ieiTZ=0x46, eightBitTZ=0x0)\n        packet = packet / e\n    if TimeZoneAndTime_presence is 1:\n        f = TimeZoneAndTimeHdr(ieiTZAT=0x47, eightBitTZAT=0x0)\n        packet = packet / f\n    if LsaIdentifier_presence is 1:\n        g = LsaIdentifierHdr(ieiLI=0x48, eightBitLI=0x0)\n        packet = packet / g\n    return packet",
    "docstring": "MM INFORMATION Section 9.2.15a"
  },
  {
    "code": "def full_research_organism(soup):\n    \"research-organism list including inline tags, such as italic\"\n    if not raw_parser.research_organism_keywords(soup):\n        return []\n    return list(map(node_contents_str, raw_parser.research_organism_keywords(soup)))",
    "docstring": "research-organism list including inline tags, such as italic"
  },
  {
    "code": "def get_region_from_metadata():\n    global __Location__\n    if __Location__ == 'do-not-get-from-metadata':\n        log.debug('Previously failed to get AWS region from metadata. Not trying again.')\n        return None\n    if __Location__ != '':\n        return __Location__\n    try:\n        result = requests.get(\n            \"http://169.254.169.254/latest/dynamic/instance-identity/document\",\n            proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT,\n        )\n    except requests.exceptions.RequestException:\n        log.warning('Failed to get AWS region from instance metadata.', exc_info=True)\n        __Location__ = 'do-not-get-from-metadata'\n        return None\n    try:\n        region = result.json()['region']\n        __Location__ = region\n        return __Location__\n    except (ValueError, KeyError):\n        log.warning('Failed to decode JSON from instance metadata.')\n        return None\n    return None",
    "docstring": "Try to get region from instance identity document and cache it\n\n    .. versionadded:: 2015.5.6"
  },
  {
    "code": "def benchmark(self, func, c_args, threads, grid, times):\n        time = []\n        for _ in range(self.iterations):\n            value = self.run_kernel(func, c_args, threads, grid)\n            if value < 0.0:\n                raise Exception(\"too many resources requested for launch\")\n            time.append(value)\n        time = sorted(time)\n        if times:\n            return time\n        else:\n            if self.iterations > 4:\n                return numpy.mean(time[1:-1])\n            else:\n                return numpy.mean(time)",
    "docstring": "runs the kernel repeatedly, returns averaged returned value\n\n        The C function tuning is a little bit more flexible than direct CUDA\n        or OpenCL kernel tuning. The C function needs to measure time, or some\n        other quality metric you wish to tune on, on its own and should\n        therefore return a single floating-point value.\n\n        Benchmark runs the C function repeatedly and returns the average of the\n        values returned by the C function. The number of iterations is set\n        during the creation of the CFunctions object. For all measurements the\n        lowest and highest values are discarded and the rest is included in the\n        average. The reason for this is to be robust against initialization\n        artifacts and other exceptional cases.\n\n        :param func: A C function compiled for this specific configuration\n        :type func: ctypes._FuncPtr\n\n        :param c_args: A list of arguments to the function, order should match the\n            order in the code. The list should be prepared using\n            ready_argument_list().\n        :type c_args: list(Argument)\n\n        :param threads: Ignored, but left as argument for now to have the same\n            interface as CudaFunctions and OpenCLFunctions.\n        :type threads: any\n\n        :param grid: Ignored, but left as argument for now to have the same\n            interface as CudaFunctions and OpenCLFunctions.\n        :type grid: any\n\n        :param times: Return the execution time of all iterations.\n        :type times: bool\n\n        :returns: All execution times, if times=True, or a robust average for the\n            kernel execution time.\n        :rtype: float"
  },
  {
    "code": "def OnWidgetToolbarToggle(self, event):\n        self.main_window.widget_toolbar.SetGripperVisible(True)\n        widget_toolbar_info = self.main_window._mgr.GetPane(\"widget_toolbar\")\n        self._toggle_pane(widget_toolbar_info)\n        event.Skip()",
    "docstring": "Widget toolbar toggle event handler"
  },
  {
    "code": "def dirichlet_covariance(alpha):\n    r\n    alpha0 = alpha.sum()\n    norm = alpha0 ** 2 * (alpha0 + 1.0)\n    Z = -alpha[:, np.newaxis] * alpha[np.newaxis, :]\n    ind = np.diag_indices(Z.shape[0])\n    Z[ind] += alpha0 * alpha\n    cov = Z / norm\n    return cov",
    "docstring": "r\"\"\"Covariance matrix for Dirichlet distribution.\n\n    Parameters\n    ----------\n    alpha : (M, ) ndarray\n        Parameters of Dirichlet distribution\n\n    Returns\n    -------\n    cov : (M, M) ndarray\n        Covariance matrix"
  },
  {
    "code": "def set(self, image_file, source=None):\n        image_file.set_size()\n        self._set(image_file.key, image_file)\n        if source is not None:\n            if not self.get(source):\n                raise ThumbnailError('Cannot add thumbnails for source: `%s` '\n                                     'that is not in kvstore.' % source.name)\n            thumbnails = self._get(source.key, identity='thumbnails') or []\n            thumbnails = set(thumbnails)\n            thumbnails.add(image_file.key)\n            self._set(source.key, list(thumbnails), identity='thumbnails')",
    "docstring": "Updates store for the `image_file`. Makes sure the `image_file` has a\n        size set."
  },
  {
    "code": "def _ParseItem(self, parser_mediator, olecf_item):\n    result = False\n    event_data = OLECFItemEventData()\n    event_data.name = olecf_item.name\n    event_data.offset = 0\n    event_data.size = olecf_item.size\n    creation_time, modification_time = self._GetTimestamps(olecf_item)\n    if creation_time:\n      date_time = dfdatetime_filetime.Filetime(timestamp=creation_time)\n      event = time_events.DateTimeValuesEvent(\n          date_time, definitions.TIME_DESCRIPTION_CREATION)\n      parser_mediator.ProduceEventWithEventData(event, event_data)\n      result = True\n    if modification_time:\n      date_time = dfdatetime_filetime.Filetime(timestamp=modification_time)\n      event = time_events.DateTimeValuesEvent(\n          date_time, definitions.TIME_DESCRIPTION_MODIFICATION)\n      parser_mediator.ProduceEventWithEventData(event, event_data)\n      result = True\n    for sub_item in olecf_item.sub_items:\n      if self._ParseItem(parser_mediator, sub_item):\n        result = True\n    return result",
    "docstring": "Parses an OLECF item.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      olecf_item (pyolecf.item): OLECF item.\n\n    Returns:\n      bool: True if an event was produced."
  },
  {
    "code": "def ManuallyScheduleClients(self, token=None):\n    client_ids = set()\n    for flow_request in self.args.flows:\n      for client_id in flow_request.client_ids:\n        client_ids.add(client_id)\n    self.StartClients(self.session_id, client_ids, token=token)",
    "docstring": "Schedule all flows without using the Foreman.\n\n    Since we know all the client ids to run on we might as well just schedule\n    all the flows and wait for the results.\n\n    Args:\n      token: A datastore access token."
  },
  {
    "code": "def split_query(query: str) -> List[str]:\n    try:\n        _query = query.strip()\n    except (ValueError, AttributeError):\n        raise QueryParserException('query is not valid, received instead {}'.format(query))\n    expressions = _query.split(',')\n    expressions = [exp.strip() for exp in expressions if exp.strip()]\n    if not expressions:\n        raise QueryParserException('Query is not valid: {}'.format(query))\n    return expressions",
    "docstring": "Split a query into different expressions.\n\n    Example:\n        name:bla, foo:<=1"
  },
  {
    "code": "def update_route53_records(self, domain_name, dns_name):\n        zone_id = self.get_hosted_zone_id_for_domain(domain_name)\n        is_apex = self.route53.get_hosted_zone(Id=zone_id)['HostedZone']['Name'][:-1] == domain_name\n        if is_apex:\n            record_set = {\n                'Name': domain_name,\n                'Type': 'A',\n                'AliasTarget': {\n                    'HostedZoneId': 'Z2FDTNDATAQYW2',\n                    'DNSName': dns_name,\n                    'EvaluateTargetHealth': False\n                }\n            }\n        else:\n            record_set = {\n                'Name': domain_name,\n                'Type': 'CNAME',\n                'ResourceRecords': [\n                    {\n                        'Value': dns_name\n                    }\n                ],\n                'TTL': 60\n            }\n        response = self.route53.change_resource_record_sets(\n            HostedZoneId=zone_id,\n            ChangeBatch={\n                'Changes': [\n                    {\n                        'Action': 'UPSERT',\n                        'ResourceRecordSet': record_set\n                    }\n                ]\n            }\n        )\n        return response",
    "docstring": "Updates Route53 Records following GW domain creation"
  },
  {
    "code": "def size_to_content(self):\n        new_sizing = self.copy_sizing()\n        new_sizing.minimum_height = 0\n        new_sizing.maximum_height = 0\n        axes = self.__axes\n        if axes and axes.is_valid:\n            if axes.x_calibration and axes.x_calibration.units:\n                new_sizing.minimum_height = self.font_size + 4\n                new_sizing.maximum_height = self.font_size + 4\n        self.update_sizing(new_sizing)",
    "docstring": "Size the canvas item to the proper height."
  },
  {
    "code": "def _get_stddevs(self, C, stddev_types, rup, imt, num_sites):\n        stddevs = []\n        for stddev_type in stddev_types:\n            sigma_mean = self._compute_standard_dev(rup, imt, C)\n            sigma_tot = np.sqrt((sigma_mean ** 2) + (C['SigmaReg'] ** 2))\n            sigma_tot = np.log10(np.exp(sigma_tot))\n            stddevs.append(sigma_tot + np.zeros(num_sites))\n        return stddevs",
    "docstring": "Return standard deviations as defined in eq. 4 and 5, page 744,\n        based on table 8, page 744.\n        Eq. 5 yields std dev in natural log, so convert to log10"
  },
  {
    "code": "def tap(f):\n    @wraps(f)\n    def _cb(res, *a, **kw):\n        d = maybeDeferred(f, res, *a, **kw)\n        d.addCallback(lambda ignored: res)\n        return d\n    return _cb",
    "docstring": "\"Tap\" a Deferred callback chain with a function whose return value is\n    ignored."
  },
  {
    "code": "def _writeLinks(self, links, fileObject, replaceParamFile):\n        for link in links:\n            linkType = link.type\n            fileObject.write('LINK           %s\\n' % link.linkNumber)\n            if 'TRAP' in linkType or 'TRAPEZOID' in linkType or 'BREAKPOINT' in linkType:\n                self._writeCrossSectionLink(link, fileObject, replaceParamFile)\n            elif linkType == 'STRUCTURE':\n                self._writeStructureLink(link, fileObject, replaceParamFile)\n            elif linkType in ('RESERVOIR', 'LAKE'):\n                self._writeReservoirLink(link, fileObject, replaceParamFile)\n            else:\n                log.error('OOPS: CIF LINE 417')\n            fileObject.write('\\n')",
    "docstring": "Write Link Lines to File Method"
  },
  {
    "code": "def geq_multiple(self, other):\n        if other == TimeValue(\"0.000\"):\n            return self\n        return int(math.ceil(other / self)) * self",
    "docstring": "Return the next multiple of this time value,\n        greater than or equal to ``other``.\n        If ``other`` is zero, return this time value.\n\n        :rtype: :class:`~aeneas.exacttiming.TimeValue`"
  },
  {
    "code": "def extract_fields(lines, delim, searches, match_lineno=1, **kwargs):\n    keep_idx = []\n    for lineno, line in lines:\n        if lineno < match_lineno or delim not in line:\n            if lineno == match_lineno:\n                raise WcutError('Delimter not found in line {}'.format(\n                    match_lineno))\n            yield [line]\n            continue\n        fields = line.split(delim)\n        if lineno == match_lineno:\n            keep_idx = list(match_fields(fields, searches, **kwargs))\n        keep_fields = [fields[i] for i in keep_idx]\n        if keep_fields:\n            yield keep_fields",
    "docstring": "Return generator of fields matching `searches`.\n\n    Parameters\n    ----------\n    lines : iterable\n        Provides line number (1-based) and line (str)\n    delim : str\n        Delimiter to split line by to produce fields\n    searches : iterable\n        Returns search (str) to match against line fields.\n    match_lineno : int\n        Line number of line to split and search fields\n\n    Remaining keyword arguments are passed to `match_fields`."
  },
  {
    "code": "def get_token_network(\n            self,\n            token_address: TokenAddress,\n            block_identifier: BlockSpecification = 'latest',\n    ) -> Optional[Address]:\n        if not isinstance(token_address, T_TargetAddress):\n            raise ValueError('token_address must be an address')\n        address = self.proxy.contract.functions.token_to_token_networks(\n            to_checksum_address(token_address),\n        ).call(block_identifier=block_identifier)\n        address = to_canonical_address(address)\n        if is_same_address(address, NULL_ADDRESS):\n            return None\n        return address",
    "docstring": "Return the token network address for the given token or None if\n        there is no correspoding address."
  },
  {
    "code": "def word_wrap(text, columns=80, indent=4, padding=2):\n    paragraphs = _PARA_BREAK.split(text)\n    lines = []\n    columns -= padding\n    for para in paragraphs:\n        if para.isspace():\n            continue\n        line = ' ' * indent\n        for word in para.split():\n            if (len(line) + 1 + len(word)) > columns:\n                lines.append(line)\n                line = ' ' * padding\n                line += word\n            else:\n                line += ' ' + word\n        if not line.isspace():\n            lines.append(line)\n    return lines",
    "docstring": "Given a block of text, breaks into a list of lines wrapped to\n    length."
  },
  {
    "code": "def get(path, objectType, user=None):\n    ret = {'Path': path,\n           'ACLs': []}\n    sidRet = _getUserSid(user)\n    if path and objectType:\n        dc = daclConstants()\n        objectTypeBit = dc.getObjectTypeBit(objectType)\n        path = dc.processPath(path, objectTypeBit)\n        tdacl = _get_dacl(path, objectTypeBit)\n        if tdacl:\n            for counter in range(0, tdacl.GetAceCount()):\n                tAce = tdacl.GetAce(counter)\n                if not sidRet['sid'] or (tAce[2] == sidRet['sid']):\n                    ret['ACLs'].append(_ace_to_text(tAce, objectTypeBit))\n    return ret",
    "docstring": "Get the ACL of an object. Will filter by user if one is provided.\n\n    Args:\n        path: The path to the object\n        objectType: The type of object (FILE, DIRECTORY, REGISTRY)\n        user: A user name to filter by\n\n    Returns (dict): A dictionary containing the ACL\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'minion-id' win_dacl.get c:\\temp directory"
  },
  {
    "code": "def distinct_values_of(self, field, count_deleted=False):\n        solr_params = \"facet=true&facet.field=%s&rows=0\" % field\n        result = self.riak_http_search_query(self.index_name, solr_params, count_deleted)\n        facet_fields = result['facet_counts']['facet_fields'][field]\n        keys = facet_fields[0::2]\n        vals = facet_fields[1::2]\n        return dict(zip(keys, vals))",
    "docstring": "Uses riak http search query endpoint for advanced SOLR queries.\n\n        Args:\n            field (str): facet field\n            count_deleted (bool): ignore deleted or not\n\n        Returns: \n            (dict): pairs of field values and number of counts"
  },
  {
    "code": "def add_tarball(self, tarball, package):\n        if tarball is None:\n            logger.error(\n                \"No tarball found for %s: probably a renamed project?\",\n                package)\n            return\n        target_dir = os.path.join(self.root_directory, package)\n        if not os.path.exists(target_dir):\n            os.mkdir(target_dir)\n            logger.info(\"Created %s\", target_dir)\n        logger.info(\"Copying tarball to %s\", target_dir)\n        shutil.copy(tarball, target_dir)",
    "docstring": "Add a tarball, possibly creating the directory if needed."
  },
  {
    "code": "def population_variant_regions(items, merged=False):\n    def _get_variant_regions(data):\n        out = dd.get_variant_regions(data) or dd.get_sample_callable(data)\n        if merged and dd.get_variant_regions(data):\n            merged_out = dd.get_variant_regions_merged(data)\n            if merged_out:\n                out = merged_out\n            else:\n                out = merge_overlaps(out, data)\n        return out\n    import pybedtools\n    if len(items) == 1:\n        return _get_variant_regions(items[0])\n    else:\n        paired = vcfutils.get_paired(items)\n        if paired:\n            return _get_variant_regions(paired.tumor_data)\n        else:\n            vrs = []\n            for data in items:\n                vr_bed = _get_variant_regions(data)\n                if vr_bed:\n                    vrs.append((pybedtools.BedTool(vr_bed).total_coverage(), vr_bed))\n            vrs.sort(reverse=True)\n            if vrs:\n                return vrs[0][1]",
    "docstring": "Retrieve the variant region BED file from a population of items.\n\n    If tumor/normal, return the tumor BED file. If a population, return\n    the BED file covering the most bases."
  },
  {
    "code": "def validate(self, form, extra_validators=tuple()):\n        if not self.has_data:\n            return True\n        if self.is_list_data:\n            if not isinstance(self._formdata[self.name], (list, tuple)):\n                return False\n        return super(NestedModelList, self).validate(form, extra_validators)",
    "docstring": "Perform validation only if data has been submitted"
  },
  {
    "code": "def from_array(self, array, propname):\n        r\n        array = sp.atleast_3d(array)\n        if sp.shape(array) != self._shape:\n            raise Exception('The array shape does not match the network')\n        temp = array.flatten()\n        Ps = sp.array(self['pore.index'][self.pores('internal')], dtype=int)\n        propname = 'pore.' + propname.split('.')[-1]\n        self[propname] = sp.nan\n        self[propname][self.pores('internal')] = temp[Ps]",
    "docstring": "r\"\"\"\n        Apply data to the network based on a rectangular array filled with\n        values.  Each array location corresponds to a pore in the network.\n\n        Parameters\n        ----------\n        array : array_like\n            The rectangular array containing the values to be added to the\n            network. This array must be the same shape as the original network.\n\n        propname : string\n            The name of the pore property being added."
  },
  {
    "code": "def get_fields(self):\n        ret = OrderedDict()\n        if not self.user:\n            return ret\n        fields = super(ModelPermissionsSerializer, self).get_fields()\n        if self.user.is_superuser:\n            return fields\n        allowed_fields = self._get_user_allowed_fields()\n        for allowed_field in allowed_fields:\n            field = fields[allowed_field.name]\n            if isinstance(field, ModelPermissionsSerializer):\n                if not field.get_fields():\n                    field_cls = field._related_class\n                    kwargs = get_relation_kwargs(allowed_field.name,\n                                                 field.info)\n                    if not issubclass(field_cls,\n                                      serializers.HyperlinkedRelatedField):\n                        kwargs.pop('view_name', None)\n                    field = field_cls(**kwargs)\n            ret[allowed_field.name] = field\n        return ret",
    "docstring": "Calculate fields that can be accessed by authenticated user."
  },
  {
    "code": "def get_waveform_end_frequency(template=None, **kwargs):\n    input_params = props(template,**kwargs)\n    approximant = kwargs['approximant']\n    if approximant in _filter_ends:\n        return _filter_ends[approximant](**input_params)\n    else:\n        return None",
    "docstring": "Return the stop frequency of a template"
  },
  {
    "code": "def SearchDependencies(self,\n                         os_name,\n                         artifact_name_list,\n                         existing_artifact_deps=None,\n                         existing_expansion_deps=None):\n    artifact_deps = existing_artifact_deps or set()\n    expansion_deps = existing_expansion_deps or set()\n    artifact_objs = self.GetArtifacts(\n        os_name=os_name, name_list=artifact_name_list)\n    artifact_deps = artifact_deps.union([a.name for a in artifact_objs])\n    for artifact in artifact_objs:\n      expansions = GetArtifactPathDependencies(artifact)\n      if expansions:\n        expansion_deps = expansion_deps.union(set(expansions))\n        new_artifact_names = self.GetArtifactNames(\n            os_name=os_name, provides=expansions)\n        missing_artifacts = new_artifact_names - artifact_deps\n        if missing_artifacts:\n          new_artifacts, new_expansions = self.SearchDependencies(\n              os_name,\n              new_artifact_names,\n              existing_artifact_deps=artifact_deps,\n              existing_expansion_deps=expansion_deps)\n          artifact_deps = artifact_deps.union(new_artifacts)\n          expansion_deps = expansion_deps.union(new_expansions)\n    return artifact_deps, expansion_deps",
    "docstring": "Return a set of artifact names needed to fulfill dependencies.\n\n    Search the path dependency tree for all artifacts that can fulfill\n    dependencies of artifact_name_list.  If multiple artifacts provide a\n    dependency, they are all included.\n\n    Args:\n      os_name: operating system string\n      artifact_name_list: list of artifact names to find dependencies for.\n      existing_artifact_deps: existing dependencies to add to, for recursion,\n        e.g. set([\"WindowsRegistryProfiles\", \"WindowsEnvironmentVariablePath\"])\n      existing_expansion_deps: existing expansion dependencies to add to, for\n        recursion, e.g. set([\"users.userprofile\", \"users.homedir\"])\n\n    Returns:\n      (artifact_names, expansion_names): a tuple of sets, one with artifact\n          names, the other expansion names"
  },
  {
    "code": "def description(self):\n        for line in self.SLACKBUILDS_TXT.splitlines():\n            if line.startswith(self.line_name):\n                sbo_name = line[17:].strip()\n            if line.startswith(self.line_des):\n                if sbo_name == self.name:\n                    return line[31:].strip()",
    "docstring": "Grab package verion"
  },
  {
    "code": "def max_pool(inputs, kernel_size, stride=2, padding='VALID', scope=None):\n  with tf.name_scope(scope, 'MaxPool', [inputs]):\n    kernel_h, kernel_w = _two_element_tuple(kernel_size)\n    stride_h, stride_w = _two_element_tuple(stride)\n    return tf.nn.max_pool(inputs,\n                          ksize=[1, kernel_h, kernel_w, 1],\n                          strides=[1, stride_h, stride_w, 1],\n                          padding=padding)",
    "docstring": "Adds a Max Pooling layer.\n\n  It is assumed by the wrapper that the pooling is only done per image and not\n  in depth or batch.\n\n  Args:\n    inputs: a tensor of size [batch_size, height, width, depth].\n    kernel_size: a list of length 2: [kernel_height, kernel_width] of the\n      pooling kernel over which the op is computed. Can be an int if both\n      values are the same.\n    stride: a list of length 2: [stride_height, stride_width].\n      Can be an int if both strides are the same.  Note that presently\n      both strides must have the same value.\n    padding: the padding method, either 'VALID' or 'SAME'.\n    scope: Optional scope for name_scope.\n\n  Returns:\n    a tensor representing the results of the pooling operation.\n  Raises:\n    ValueError: if 'kernel_size' is not a 2-D list"
  },
  {
    "code": "def _display(node, indent, expandattrs, expandvals, output):\n    attrs = _displayattrs(node.attrib, expandattrs)\n    if node.text is None or not expandvals:\n        val = ''\n    elif isinstance(node.text, str):\n        val = ' %s' % repr(node.text.strip())\n    else:\n        val = ' %s' % repr(node.text)\n    output.write(encode(indent + striptag(node.tag) + attrs + val + '\\n'))\n    for sub_node in node:\n        _display(sub_node, indent + '  ', expandattrs, expandvals, output)",
    "docstring": "Core function to display a Node object"
  },
  {
    "code": "def downgrades(src):\n    def _(f):\n        destination = src - 1\n        @do(operator.setitem(_downgrade_methods, destination))\n        @wraps(f)\n        def wrapper(op, conn, version_info_table):\n            conn.execute(version_info_table.delete())\n            f(op)\n            write_version_info(conn, version_info_table, destination)\n        return wrapper\n    return _",
    "docstring": "Decorator for marking that a method is a downgrade to a version to the\n    previous version.\n\n    Parameters\n    ----------\n    src : int\n        The version this downgrades from.\n\n    Returns\n    -------\n    decorator : callable[(callable) -> callable]\n        The decorator to apply."
  },
  {
    "code": "def _remove_empty_lines(self, lines):\n        ret = []\n        for l in lines:\n            if (len(l) > 1 or len(l) == 1 and\n                    (not isinstance(l[0], str) or l[0].strip())):\n                ret.append(l)\n        return ret",
    "docstring": "Iterate through the lines and remove any that are\n        either empty or contain only one whitespace value\n\n        Parameters\n        ----------\n        lines : array-like\n            The array of lines that we are to filter.\n\n        Returns\n        -------\n        filtered_lines : array-like\n            The same array of lines with the \"empty\" ones removed."
  },
  {
    "code": "def atlas_node_stop( atlas_state ):\n    for component in atlas_state.keys():\n        log.debug(\"Stopping Atlas component '%s'\" % component)\n        atlas_state[component].ask_join()\n        atlas_state[component].join()\n    return True",
    "docstring": "Stop the atlas node threads"
  },
  {
    "code": "def select(self, table, cols, execute=True, select_type='SELECT', return_type=list):\n        select_type = select_type.upper()\n        assert select_type in SELECT_QUERY_TYPES\n        statement = '{0} {1} FROM {2}'.format(select_type, join_cols(cols), wrap(table))\n        if not execute:\n            return statement\n        values = self.fetch(statement)\n        return self._return_rows(table, cols, values, return_type)",
    "docstring": "Query every row and only certain columns from a table."
  },
  {
    "code": "def transfer_project(self, to_namespace, **kwargs):\n        path = '/projects/%s/transfer' % (self.id,)\n        self.manager.gitlab.http_put(path,\n                                     post_data={\"namespace\": to_namespace},\n                                     **kwargs)",
    "docstring": "Transfer a project to the given namespace ID\n\n        Args:\n            to_namespace (str): ID or path of the namespace to transfer the\n            project to\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabTransferProjectError: If the project could not be transfered"
  },
  {
    "code": "def _handle_tag_definesceneandframelabeldata(self):\n        obj = _make_object(\"DefineSceneAndFrameLabelData\")\n        obj.SceneCount = self._get_struct_encodedu32()\n        for i in range(1, obj.SceneCount + 1):\n            setattr(obj, 'Offset{}'.format(i), self._get_struct_encodedu32())\n            setattr(obj, 'Name{}'.format(i), self._get_struct_string())\n        obj.FrameLabelCount = self._get_struct_encodedu32()\n        for i in range(1, obj.FrameLabelCount + 1):\n            setattr(obj, 'FrameNum{}'.format(i), self._get_struct_encodedu32())\n            setattr(obj, 'FrameLabel{}'.format(i), self._get_struct_string())\n        return obj",
    "docstring": "Handle the DefineSceneAndFrameLabelData tag."
  },
  {
    "code": "def send(self, verb, params=None, source=None, tags=None):\n        m = RFC1459Message.from_data(verb, params=params, source=source, tags=tags)\n        self._send_message(m)",
    "docstring": "Send a generic IRC message to the server.\n\n        A message is created using the various parts of the message, then gets\n        assembled and sent to the server.\n\n        Args:\n            verb (str): Verb, such as PRIVMSG.\n            params (list of str): Message parameters, defaults to no params.\n            source (str): Source of the message, defaults to no source.\n            tags (dict): `Tags <http://ircv3.net/specs/core/message-tags-3.2.html>`_\n                to send with the message."
  },
  {
    "code": "def get_missing_bins(original, trimmed):\n    original_diag = np.diag(original)\n    trimmed_diag = np.diag(trimmed)\n    index = []\n    m = min(original.shape)\n    for j in range(min(trimmed.shape)):\n        k = 0\n        while original_diag[j + k] != trimmed_diag[j] and k < 2 * m:\n            k += 1\n        index.append(k + j)\n    return np.array(index)",
    "docstring": "Retrieve indices of a trimmed matrix with respect to the original matrix.\n    Fairly fast but is only correct if diagonal values are different, which is\n    always the case in practice."
  },
  {
    "code": "def gstd(data, channels=None):\n    if channels is None:\n        data_stats = data\n    else:\n        data_stats = data[:, channels]\n    return np.exp(np.std(np.log(data_stats), axis=0))",
    "docstring": "Calculate the geometric std. dev. of the events in an FCSData object.\n\n    Parameters\n    ----------\n    data : FCSData or numpy array\n        NxD flow cytometry data where N is the number of events and D is\n        the number of parameters (aka channels).\n    channels : int or str or list of int or list of str, optional\n        Channels on which to calculate the statistic. If None, use all\n        channels.\n\n    Returns\n    -------\n    float or numpy array\n        The geometric standard deviation of the events in the specified\n        channels of `data`."
  },
  {
    "code": "def initialize_pop(self):\n        self.toolbox.register(\"individual\", self.generate)\n        self.toolbox.register(\"population\", tools.initRepeat,\n                              list, self.toolbox.individual)\n        self.population = self.toolbox.population(n=self._params['popsize'])\n        self.assign_fitnesses(self.population)\n        self._params['model_count'] += len(self.population)",
    "docstring": "Assigns initial fitnesses."
  },
  {
    "code": "def potcar_eatom_list_from_outcar( filename='OUTCAR' ):\n    with open( filename ) as f:\n        outcar = f.read()\n    eatom_re = re.compile( \"energy of atom\\s+\\d+\\s+EATOM=\\s*([-\\d\\.]+)\" )\n    eatom = [ float( e ) for e in eatom_re.findall( outcar ) ]\n    return eatom",
    "docstring": "Returns a list of EATOM values for the pseudopotentials used.\n\n    Args:\n        filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'.\n\n    Returns:\n        (List(Float)): A list of EATOM values, in the order they appear in the OUTCAR."
  },
  {
    "code": "def lr_padding(self, terms):\n        lpad = rpad = []\n        if self.lpad:\n            lpad = [self.lpad] * (self.n - 1) \n        if self.rpad:\n            rpad = [self.rpad] * (self.n - 1) \n        return lpad + terms + rpad",
    "docstring": "Pad doc from the left and right before adding,\n        depending on what's in self.lpad and self.rpad\n        If any of them is '', then don't pad there."
  },
  {
    "code": "def start_logger(self):\n        level = self.real_level(self.level)\n        logging.basicConfig(level=level)\n        self.set_logger(self.name, self.level)\n        config.dictConfig(self.config)\n        self.logger = logging.getLogger(self.name)",
    "docstring": "Enables the root logger and configures extra loggers."
  },
  {
    "code": "def run_final_eval(train_session, module_spec, class_count, image_lists,\n                   jpeg_data_tensor, decoded_image_tensor,\n                   resized_image_tensor, bottleneck_tensor):\n  test_bottlenecks, test_ground_truth, test_filenames = (\n      get_random_cached_bottlenecks(train_session, image_lists,\n                                    FLAGS.test_batch_size,\n                                    'testing', FLAGS.bottleneck_dir,\n                                    FLAGS.image_dir, jpeg_data_tensor,\n                                    decoded_image_tensor, resized_image_tensor,\n                                    bottleneck_tensor, FLAGS.tfhub_module))\n  (eval_session, _, bottleneck_input, ground_truth_input, evaluation_step,\n   prediction) = build_eval_session(module_spec, class_count)\n  test_accuracy, predictions = eval_session.run(\n      [evaluation_step, prediction],\n      feed_dict={\n          bottleneck_input: test_bottlenecks,\n          ground_truth_input: test_ground_truth\n      })\n  tf.logging.info('Final test accuracy = %.1f%% (N=%d)' %\n                  (test_accuracy * 100, len(test_bottlenecks)))\n  if FLAGS.print_misclassified_test_images:\n    tf.logging.info('=== MISCLASSIFIED TEST IMAGES ===')\n    for i, test_filename in enumerate(test_filenames):\n      if predictions[i] != test_ground_truth[i]:\n        tf.logging.info('%70s  %s' % (test_filename,\n                                      list(image_lists.keys())[predictions[i]]))",
    "docstring": "Runs a final evaluation on an eval graph using the test data set.\n\n  Args:\n    train_session: Session for the train graph with the tensors below.\n    module_spec: The hub.ModuleSpec for the image module being used.\n    class_count: Number of classes\n    image_lists: OrderedDict of training images for each label.\n    jpeg_data_tensor: The layer to feed jpeg image data into.\n    decoded_image_tensor: The output of decoding and resizing the image.\n    resized_image_tensor: The input node of the recognition graph.\n    bottleneck_tensor: The bottleneck output layer of the CNN graph."
  },
  {
    "code": "def regex_extract(arg, pattern, index):\n    return ops.RegexExtract(arg, pattern, index).to_expr()",
    "docstring": "Returns specified index, 0 indexed, from string based on regex pattern\n    given\n\n    Parameters\n    ----------\n    pattern : string (regular expression string)\n    index : int, 0 indexed\n\n    Returns\n    -------\n    extracted : string"
  },
  {
    "code": "def delete_role(query):\n    role = _query_to_role(query)\n    if click.confirm(f'Are you sure you want to delete {role!r}?'):\n        role_manager.delete(role, commit=True)\n        click.echo(f'Successfully deleted {role!r}')\n    else:\n        click.echo('Cancelled.')",
    "docstring": "Delete a role."
  },
  {
    "code": "def makeRandomBinaryTree(leafNodeNumber=None):\n    while True:\n        nodeNo = [-1]\n        def fn():\n            nodeNo[0] += 1\n            if random.random() > 0.6:\n                i = str(nodeNo[0])\n                return BinaryTree(0.00001 + random.random()*0.8, True, fn(), fn(), i)\n            else:\n                return BinaryTree(0.00001 + random.random()*0.8, False, None, None, str(nodeNo[0]))\n        tree = fn()\n        def fn2(tree):\n            if tree.internal:\n                return fn2(tree.left) + fn2(tree.right)\n            return 1\n        if leafNodeNumber is None or fn2(tree) == leafNodeNumber:\n            return tree",
    "docstring": "Creates a random binary tree."
  },
  {
    "code": "def sorted(self, fsort):\n        if not self.params:\n            self.params = dict()\n        self.params['sort'] = fsort\n        return self",
    "docstring": "Allows to add one or more sort on specific fields. Each sort can be reversed as well. The sort is defined on a per field level, with special field name for _score to sort by score."
  },
  {
    "code": "def fetch(self, endpoint_name, identifier_input, query_params=None):\n        endpoint_url = constants.URL_PREFIX + \"/\" + self._version + \"/\" + endpoint_name\n        if query_params is None:\n            query_params = {}\n        if len(identifier_input) == 1:\n            query_params.update(identifier_input[0])\n            return self._request_client.get(endpoint_url, query_params)\n        return self._request_client.post(endpoint_url, identifier_input, query_params)",
    "docstring": "Calls this instance's request_client's post method with the\n        specified component endpoint\n\n        Args:\n            - endpoint_name (str) - The endpoint to call like \"property/value\".\n            - identifier_input - One or more identifiers to request data for. An identifier can\n                be in one of these forms:\n\n                - A list of property identifier dicts:\n                    - A property identifier dict can contain the following keys:\n                      (address, zipcode, unit, city, state, slug, meta).\n                      One of 'address' or 'slug' is required.\n\n                      Ex: [{\"address\": \"82 County Line Rd\",\n                           \"zipcode\": \"72173\",\n                           \"meta\": \"some ID\"}]\n\n                      A slug is a URL-safe string that identifies a property.\n                      These are obtained from HouseCanary.\n\n                      Ex: [{\"slug\": \"123-Example-St-San-Francisco-CA-94105\"}]\n\n                - A list of dicts representing a block:\n                  - A block identifier dict can contain the following keys:\n                      (block_id, num_bins, property_type, meta).\n                      'block_id' is required.\n\n                  Ex: [{\"block_id\": \"060750615003005\", \"meta\": \"some ID\"}]\n\n                - A list of dicts representing a zipcode:\n\n                  Ex: [{\"zipcode\": \"90274\", \"meta\": \"some ID\"}]\n\n                - A list of dicts representing an MSA:\n\n                  Ex: [{\"msa\": \"41860\", \"meta\": \"some ID\"}]\n\n                The \"meta\" field is always optional.\n\n        Returns:\n            A Response object, or the output of a custom OutputGenerator\n            if one was specified in the constructor."
  },
  {
    "code": "def rsem_stats_table(self):\n        headers = OrderedDict()\n        headers['alignable_percent'] = {\n            'title': '% Alignable'.format(config.read_count_prefix),\n            'description': '% Alignable reads'.format(config.read_count_desc),\n            'max': 100,\n            'min': 0,\n            'suffix': '%',\n            'scale': 'YlGn'\n        }\n        self.general_stats_addcols(self.rsem_mapped_data, headers)",
    "docstring": "Take the parsed stats from the rsem report and add them to the\n        basic stats table at the top of the report"
  },
  {
    "code": "def enable_fullquicklook(self):\n        self.args.disable_quicklook = False\n        for p in ['cpu', 'gpu', 'mem', 'memswap']:\n            setattr(self.args, 'disable_' + p, True)",
    "docstring": "Disable the full quicklook mode"
  },
  {
    "code": "def get(self, callback):\n        derived_path = self.context.request.url\n        logger.debug('[{log_prefix}]: get.derived_path: {path}'.format(\n            log_prefix=LOG_PREFIX, path=derived_path))\n        callback(self.storage.get(self.result_key_for(derived_path)))",
    "docstring": "Gets an item based on the path."
  },
  {
    "code": "def get_probs_for_labels(labels, prediction_results):\n  probs = []\n  if 'probability' in prediction_results:\n    for i, r in prediction_results.iterrows():\n      probs_one = [0.0] * len(labels)\n      for k, v in six.iteritems(r):\n        if v in labels and k.startswith('predicted'):\n          if k == 'predict':\n            prob_name = 'probability'\n          else:\n            prob_name = 'probability' + k[9:]\n          probs_one[labels.index(v)] = r[prob_name]\n      probs.append(probs_one)\n    return probs\n  else:\n    for i, r in prediction_results.iterrows():\n      probs_one = [0.0] * len(labels)\n      for k, v in six.iteritems(r):\n        if k in labels:\n          probs_one[labels.index(k)] = v\n      probs.append(probs_one)\n    return probs",
    "docstring": "Given ML Workbench prediction results, get probs of each label for each instance.\n\n  The prediction results are like:\n  [\n    {'predicted': 'daisy', 'probability': 0.8, 'predicted_2': 'rose', 'probability_2': 0.1},\n    {'predicted': 'sunflower', 'probability': 0.9, 'predicted_2': 'daisy', 'probability_2': 0.01},\n    ...\n  ]\n\n  Each instance is ordered by prob. But in some cases probs are needed for fixed\n  order of labels. For example, given labels = ['daisy', 'rose', 'sunflower'], the\n  results of above is expected to be:\n  [\n    [0.8, 0.1, 0.0],\n    [0.01, 0.0, 0.9],\n    ...\n  ]\n  Note that the sum of each instance may not be always 1. If model's top_n is set to\n  none-zero, and is less than number of labels, then prediction results may not contain\n  probs for all labels.\n\n  Args:\n    labels: a list of labels specifying the order of the labels.\n    prediction_results: a pandas DataFrame containing prediction results, usually returned\n        by get_prediction_results() call.\n\n  Returns:\n    A list of list of probs for each class."
  },
  {
    "code": "def _connect(self):\n        try:\n            db = pymysql.connect(user=self.user, passwd=self.passwd,\n                                 host=self.host, port=self.port,\n                                 db=self.shdb, use_unicode=True)\n            return db, db.cursor()\n        except Exception:\n            logger.error(\"Database connection error\")\n            raise",
    "docstring": "Connect to the MySQL database."
  },
  {
    "code": "def parse_disease_associations(path: str, excluded_disease_ids: set):\n    if os.path.isdir(path) or not os.path.exists(path):\n        logger.info(\"Couldn't find the disease associations file. Returning empty list.\")\n        return {}\n    disease_associations = defaultdict(list)\n    with open(path) as input_file:\n        for line in input_file:\n            target_id, disease_id = line.strip().split(\" \")\n            if disease_id not in excluded_disease_ids:\n                disease_associations[target_id].append(disease_id)\n    return disease_associations",
    "docstring": "Parse the disease-drug target associations file.\n\n    :param str path: Path to the disease-drug target associations file.\n    :param list excluded_disease_ids: Identifiers of the disease for which drug targets are being predicted.\n    :return: Dictionary of drug target-disease mappings."
  },
  {
    "code": "def complete_extra(self, args):\n        \"Completions for the 'extra' command.\"\n        if len(args) == 0:\n            return self._listdir('./')            \n        return self._complete_path(args[-1])",
    "docstring": "Completions for the 'extra' command."
  },
  {
    "code": "def step1(self, pin):\n        context = SRPContext(\n            'Pair-Setup', str(pin),\n            prime=constants.PRIME_3072,\n            generator=constants.PRIME_3072_GEN,\n            hash_func=hashlib.sha512)\n        self._session = SRPClientSession(\n            context, binascii.hexlify(self._auth_private).decode())",
    "docstring": "First pairing step."
  },
  {
    "code": "def get_dict(self, exclude_keys=None, include_keys=None):\n        d = {}\n        exclude_keys_list = exclude_keys or []\n        include_keys_list = include_keys or []\n        for k in self._get_keys():\n            if k not in exclude_keys_list and (\n                k in include_keys_list or not include_keys\n            ):\n                d[k] = getattr(self, k)\n        return d",
    "docstring": "return dictionary of keys and values corresponding to this model's\n        data - if include_keys is null the function will return all keys\n\n        :param exclude_keys: (optional) is a list of columns from model that\n        should not be returned by this function\n        :param include_keys: (optional) is a list of columns from model that\n        should be returned by this function\n        :return:"
  },
  {
    "code": "def assert_less(first, second, msg_fmt=\"{msg}\"):\n    if not first < second:\n        msg = \"{!r} is not less than {!r}\".format(first, second)\n        fail(msg_fmt.format(msg=msg, first=first, second=second))",
    "docstring": "Fail if first is not less than second.\n\n    >>> assert_less('bar', 'foo')\n    >>> assert_less(5, 5)\n    Traceback (most recent call last):\n        ...\n    AssertionError: 5 is not less than 5\n\n    The following msg_fmt arguments are supported:\n    * msg - the default error message\n    * first - the first argument\n    * second - the second argument"
  },
  {
    "code": "def get_belapi_handle(client, username=None, password=None):\n    (username, password) = get_user_creds(username, password)\n    sys_db = client.db(\"_system\", username=username, password=password)\n    try:\n        if username and password:\n            belapi_db = sys_db.create_database(\n                name=belapi_db_name,\n                users=[{\"username\": username, \"password\": password, \"active\": True}],\n            )\n        else:\n            belapi_db = sys_db.create_database(name=belapi_db_name)\n    except arango.exceptions.DatabaseCreateError:\n        if username and password:\n            belapi_db = client.db(belapi_db_name, username=username, password=password)\n        else:\n            belapi_db = client.db(belapi_db_name)\n    try:\n        belapi_db.create_collection(belapi_settings_name)\n    except Exception:\n        pass\n    try:\n        belapi_db.create_collection(belapi_statemgmt_name)\n    except Exception:\n        pass\n    return belapi_db",
    "docstring": "Get BEL API arango db handle"
  },
  {
    "code": "def execute_series_lead_lag_timedelta(\n    op, data, offset, default, aggcontext=None, **kwargs\n):\n    func = operator.add if isinstance(op, ops.Lag) else operator.sub\n    group_by = aggcontext.group_by\n    order_by = aggcontext.order_by\n    parent = aggcontext.parent\n    parent_df = getattr(parent, 'obj', parent)\n    indexed_original_df = parent_df.set_index(group_by + order_by)\n    adjusted_parent_df = parent_df.assign(\n        **{k: func(parent_df[k], offset) for k in order_by}\n    )\n    adjusted_indexed_parent = adjusted_parent_df.set_index(group_by + order_by)\n    result = adjusted_indexed_parent[getattr(data, 'obj', data).name]\n    result = result.reindex(indexed_original_df.index)\n    return post_lead_lag(result, default)",
    "docstring": "An implementation of shifting a column relative to another one that is\n    in units of time rather than rows."
  },
  {
    "code": "def __get_activator_method(self, method_name):\n        activator = getattr(self.__module, ACTIVATOR, None)\n        if activator is None:\n            activator = getattr(self.__module, ACTIVATOR_LEGACY, None)\n            if activator is not None:\n                _logger.warning(\n                    \"Bundle %s uses the deprecated '%s' to declare\"\n                    \" its activator. Use @BundleActivator instead.\",\n                    self.__name,\n                    ACTIVATOR_LEGACY,\n                )\n        return getattr(activator, method_name, None)",
    "docstring": "Retrieves the requested method of the activator, or returns None\n\n        :param method_name: A method name\n        :return: A method, or None"
  },
  {
    "code": "def maybe_upcast(values, fill_value=np.nan, dtype=None, copy=False):\n    if is_extension_type(values):\n        if copy:\n            values = values.copy()\n    else:\n        if dtype is None:\n            dtype = values.dtype\n        new_dtype, fill_value = maybe_promote(dtype, fill_value)\n        if new_dtype != values.dtype:\n            values = values.astype(new_dtype)\n        elif copy:\n            values = values.copy()\n    return values, fill_value",
    "docstring": "provide explicit type promotion and coercion\n\n    Parameters\n    ----------\n    values : the ndarray that we want to maybe upcast\n    fill_value : what we want to fill with\n    dtype : if None, then use the dtype of the values, else coerce to this type\n    copy : if True always make a copy even if no upcast is required"
  },
  {
    "code": "def can_join_group(self, project):\n        if project.class_.is_locked or project.group_max < 2:\n            return False\n        u2g = self.fetch_group_assoc(project)\n        if u2g:\n            return len(list(u2g.group.users)) < project.group_max\n        return True",
    "docstring": "Return whether or not user can join a group on `project`."
  },
  {
    "code": "def walkfiles(startdir, regex=None, recurse=True):\n    for r,_,fs in os.walk(startdir):\n        if not recurse and startdir != r:\n            return\n        for f in fs:\n            path = op.abspath(op.join(r,f))\n            if regex and not _is_match(regex, path):\n                    continue\n            if op.isfile(path):\n                yield path",
    "docstring": "Yields the absolute paths of files found within the given start\n    directory. Can optionally filter paths using a regex pattern."
  },
  {
    "code": "def get(self, field_path):\n        if not self._exists:\n            return None\n        nested_data = field_path_module.get_nested_value(field_path, self._data)\n        return copy.deepcopy(nested_data)",
    "docstring": "Get a value from the snapshot data.\n\n        If the data is nested, for example:\n\n        .. code-block:: python\n\n           >>> snapshot.to_dict()\n           {\n               'top1': {\n                   'middle2': {\n                       'bottom3': 20,\n                       'bottom4': 22,\n                   },\n                   'middle5': True,\n               },\n               'top6': b'\\x00\\x01 foo',\n           }\n\n        a **field path** can be used to access the nested data. For\n        example:\n\n        .. code-block:: python\n\n           >>> snapshot.get('top1')\n           {\n               'middle2': {\n                   'bottom3': 20,\n                   'bottom4': 22,\n               },\n               'middle5': True,\n           }\n           >>> snapshot.get('top1.middle2')\n           {\n               'bottom3': 20,\n               'bottom4': 22,\n           }\n           >>> snapshot.get('top1.middle2.bottom3')\n           20\n\n        See :meth:`~.firestore_v1beta1.client.Client.field_path` for\n        more information on **field paths**.\n\n        A copy is returned since the data may contain mutable values,\n        but the data stored in the snapshot must remain immutable.\n\n        Args:\n            field_path (str): A field path (``.``-delimited list of\n                field names).\n\n        Returns:\n            Any or None:\n                (A copy of) the value stored for the ``field_path`` or\n                None if snapshot document does not exist.\n\n        Raises:\n            KeyError: If the ``field_path`` does not match nested data\n                in the snapshot."
  },
  {
    "code": "def _update_offsets(start_x, spacing, terminations, offsets, length):\n    return (start_x + spacing[0] * terminations / 2.,\n            offsets[1] + spacing[1] * 2. + length)",
    "docstring": "Update the offsets"
  },
  {
    "code": "def get(object_ids):\n    worker = global_worker\n    worker.check_connected()\n    with profiling.profile(\"ray.get\"):\n        if worker.mode == LOCAL_MODE:\n            return object_ids\n        global last_task_error_raise_time\n        if isinstance(object_ids, list):\n            values = worker.get_object(object_ids)\n            for i, value in enumerate(values):\n                if isinstance(value, RayError):\n                    last_task_error_raise_time = time.time()\n                    raise value\n            return values\n        else:\n            value = worker.get_object([object_ids])[0]\n            if isinstance(value, RayError):\n                last_task_error_raise_time = time.time()\n                raise value\n            return value",
    "docstring": "Get a remote object or a list of remote objects from the object store.\n\n    This method blocks until the object corresponding to the object ID is\n    available in the local object store. If this object is not in the local\n    object store, it will be shipped from an object store that has it (once the\n    object has been created). If object_ids is a list, then the objects\n    corresponding to each object in the list will be returned.\n\n    Args:\n        object_ids: Object ID of the object to get or a list of object IDs to\n            get.\n\n    Returns:\n        A Python object or a list of Python objects.\n\n    Raises:\n        Exception: An exception is raised if the task that created the object\n            or that created one of the objects raised an exception."
  },
  {
    "code": "def object_isinstance(node, class_or_seq, context=None):\n    obj_type = object_type(node, context)\n    if obj_type is util.Uninferable:\n        return util.Uninferable\n    return _object_type_is_subclass(obj_type, class_or_seq, context=context)",
    "docstring": "Check if a node 'isinstance' any node in class_or_seq\n\n    :param node: A given node\n    :param class_or_seq: Union[nodes.NodeNG, Sequence[nodes.NodeNG]]\n    :rtype: bool\n\n    :raises AstroidTypeError: if the given ``classes_or_seq`` are not types"
  },
  {
    "code": "def send_exit_with_code(cls, sock, code):\n    encoded_exit_status = cls.encode_int(code)\n    cls.send_exit(sock, payload=encoded_exit_status)",
    "docstring": "Send an Exit chunk over the specified socket, containing the specified return code."
  },
  {
    "code": "def get_ir_reciprocal_mesh(mesh,\n                           cell,\n                           is_shift=None,\n                           is_time_reversal=True,\n                           symprec=1e-5,\n                           is_dense=False):\n    _set_no_error()\n    lattice, positions, numbers, _ = _expand_cell(cell)\n    if lattice is None:\n        return None\n    if is_dense:\n        dtype = 'uintp'\n    else:\n        dtype = 'intc'\n    grid_mapping_table = np.zeros(np.prod(mesh), dtype=dtype)\n    grid_address = np.zeros((np.prod(mesh), 3), dtype='intc')\n    if is_shift is None:\n        is_shift = [0, 0, 0]\n    if spg.ir_reciprocal_mesh(\n            grid_address,\n            grid_mapping_table,\n            np.array(mesh, dtype='intc'),\n            np.array(is_shift, dtype='intc'),\n            is_time_reversal * 1,\n            lattice,\n            positions,\n            numbers,\n            symprec) > 0:\n        return grid_mapping_table, grid_address\n    else:\n        return None",
    "docstring": "Return k-points mesh and k-point map to the irreducible k-points.\n\n    The symmetry is serched from the input cell.\n\n    Parameters\n    ----------\n    mesh : array_like\n        Uniform sampling mesh numbers.\n        dtype='intc', shape=(3,)\n    cell : spglib cell tuple\n        Crystal structure.\n    is_shift : array_like, optional\n        [0, 0, 0] gives Gamma center mesh and value 1 gives half mesh shift.\n        Default is None which equals to [0, 0, 0].\n        dtype='intc', shape=(3,)\n    is_time_reversal : bool, optional\n        Whether time reversal symmetry is included or not. Default is True.\n    symprec : float, optional\n        Symmetry tolerance in distance. Default is 1e-5.\n    is_dense : bool, optional\n        grid_mapping_table is returned with dtype='uintp' if True. Otherwise\n        its dtype='intc'. Default is False.\n\n    Returns\n    -------\n    grid_mapping_table : ndarray\n        Grid point mapping table to ir-gird-points.\n        dtype='intc' or 'uintp', shape=(prod(mesh),)\n    grid_address : ndarray\n        Address of all grid points.\n        dtype='intc', shspe=(prod(mesh), 3)"
  },
  {
    "code": "def reward_battery(self):\n        if not 'battery' in self.mode:\n            return\n        mode = self.mode['battery']\n        if mode and mode and self.__test_cond(mode):\n            self.logger.debug('Battery out')\n            self.player.stats['reward'] += mode['reward']\n            self.player.game_over = self.player.game_over or mode['terminal']",
    "docstring": "Add a battery level reward"
  },
  {
    "code": "def encode(self, tag):\n        sequence = str(tag.sequence_n)\n        if len(sequence) > self._sequence_l:\n            sequence = sequence[:self._sequence_l]\n        while len(sequence) < self._sequence_l:\n            sequence = '0' + sequence\n        version = str(tag.version)\n        if len(version) > 2:\n            version = version[:1] + version[-1:]\n        while len(version) < 2:\n            version = '0' + version\n        year = str(tag.year)[-2:]\n        sender = tag.sender[:3]\n        receiver = tag.receiver[:3]\n        rule = self._header + year + sequence + sender\n        rule = rule + self._ip_delimiter + receiver + \".V\" + version\n        return rule",
    "docstring": "Parses a CWR file name from a FileTag object.\n\n        The result will be a string following the format CWyynnnnsss_rrr.Vxx,\n        where the numeric sequence will have the length set on the encoder's\n        constructor.\n\n        :param tag: FileTag to parse\n        :return: a string file name parsed from the FileTag"
  },
  {
    "code": "def virtual_interface_create(provider, names, **kwargs):\n    client = _get_client()\n    return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs)",
    "docstring": "Attach private interfaces to a server\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'"
  },
  {
    "code": "def _tracker(self, _observer_, _self_, *args, **kwds):\n        self.track_object(_self_,\n                          name=_observer_.name,\n                          resolution_level=_observer_.detail,\n                          keep=_observer_.keep,\n                          trace=_observer_.trace)\n        _observer_.init(_self_, *args, **kwds)",
    "docstring": "Injected constructor for tracked classes.\n        Call the actual constructor of the object and track the object.\n        Attach to the object before calling the constructor to track the object with\n        the parameters of the most specialized class."
  },
  {
    "code": "def rmsd(V, W):\n    D = len(V[0])\n    N = len(V)\n    result = 0.0\n    for v, w in zip(V, W):\n        result += sum([(v[i] - w[i])**2.0 for i in range(D)])\n    return np.sqrt(result/N)",
    "docstring": "Calculate Root-mean-square deviation from two sets of vectors V and W.\n\n    Parameters\n    ----------\n    V : array\n        (N,D) matrix, where N is points and D is dimension.\n    W : array\n        (N,D) matrix, where N is points and D is dimension.\n\n    Returns\n    -------\n    rmsd : float\n        Root-mean-square deviation between the two vectors"
  },
  {
    "code": "def binarize_signal(signal, treshold=\"auto\", cut=\"higher\"):\n    if treshold == \"auto\":\n        treshold = (np.max(np.array(signal)) - np.min(np.array(signal)))/2\n    signal = list(signal)\n    binary_signal = []\n    for i in range(len(signal)):\n        if cut == \"higher\":\n            if signal[i] > treshold:\n                binary_signal.append(1)\n            else:\n                binary_signal.append(0)\n        else:\n            if signal[i] < treshold:\n                binary_signal.append(1)\n            else:\n                binary_signal.append(0)\n    return(binary_signal)",
    "docstring": "Binarize a channel based on a continuous channel.\n\n    Parameters\n    ----------\n    signal = array or list\n        The signal channel.\n    treshold = float\n        The treshold value by which to select the events. If \"auto\", takes the value between the max and the min.\n    cut = str\n        \"higher\" or \"lower\", define the events as above or under the treshold. For photosensors, a white screen corresponds usually to higher values. Therefore, if your events were signalled by a black colour, events values would be the lower ones, and you should set the cut to \"lower\".\n\n    Returns\n    ----------\n    list\n        binary_signal\n\n    Example\n    ----------\n    >>> import neurokit as nk\n    >>> binary_signal = nk.binarize_signal(signal, treshold=4)\n\n    Authors\n    ----------\n    - `Dominique Makowski <https://dominiquemakowski.github.io/>`_\n\n    Dependencies\n    ----------\n    None"
  },
  {
    "code": "def notifyReady(self):\n        if self.instance:\n            return defer.succeed(self.instance)\n        def on_cancel(d):\n            self.__notify_ready.remove(d)\n        df = defer.Deferred(on_cancel)\n        self.__notify_ready.append(df)\n        return df",
    "docstring": "Returns a deferred that will fire when the factory has created a\n            protocol that can be used to communicate with a Mongo server.\n\n            Note that this will not fire until we have connected to a Mongo\n            master, unless slaveOk was specified in the Mongo URI connection\n            options."
  },
  {
    "code": "def set_time_rate(self, value):\n        if isinstance(value, float) is False:\n            raise TypeError(\"The type of __time_rate must be float.\")\n        if value <= 0.0:\n            raise ValueError(\"The value of __time_rate must be greater than 0.0\")\n        self.__time_rate = value",
    "docstring": "setter\n        Time rate."
  },
  {
    "code": "def group_toggle(self, addr, use_cache=True):\n        data = self.group_read(addr, use_cache)\n        if len(data) != 1:\n            problem = \"Can't toggle a {}-octet group address {}\".format(\n                len(data), addr)\n            logging.error(problem)\n            raise KNXException(problem)\n        if data[0] == 0:\n            self.group_write(addr, [1])\n        elif data[0] == 1:\n            self.group_write(addr, [0])\n        else:\n            problem = \"Can't toggle group address {} as value is {}\".format(\n                addr, data[0])\n            logging.error(problem)\n            raise KNXException(problem)",
    "docstring": "Toggle the value of an 1-bit group address.\n\n        If the object has a value != 0, it will be set to 0, otherwise to 1"
  },
  {
    "code": "def get_translation(self, context_id, translation_id):\n        translation = next((x for x in self.get_translations(context_id)\n                            if x['id'] == translation_id), None)\n        if translation is None:\n            raise SoftLayerAPIError('SoftLayer_Exception_ObjectNotFound',\n                                    'Unable to find object with id of \\'{}\\''\n                                    .format(translation_id))\n        return translation",
    "docstring": "Retrieves a translation entry for the given id values.\n\n        :param int context_id: The id-value representing the context instance.\n        :param int translation_id: The id-value representing the translation\n               instance.\n        :return dict: Mapping of properties for the translation entry.\n        :raise SoftLayerAPIError: If a translation cannot be found."
  },
  {
    "code": "def _make_sj_out_dict(fns, jxns=None, define_sample_name=None):\n    if define_sample_name == None:\n        define_sample_name = lambda x: x\n    else:\n        assert len(set([define_sample_name(x) for x in fns])) == len(fns)\n    sj_outD = dict()\n    for fn in fns:\n        sample = define_sample_name(fn)\n        df = read_sj_out_tab(fn)\n        df = df[df.unique_junction_reads > 0]\n        index = (df.chrom + ':' + df.start.astype(str) + '-' \n                 +  df.end.astype(str))\n        assert len(index) == len(set(index))\n        df.index = index\n        if jxns:\n            df = df.ix[set(df.index) & jxns]\n        sj_outD[sample] = df\n    return sj_outD",
    "docstring": "Read multiple sj_outs, return dict with keys as sample names and values\n    as sj_out dataframes.\n\n    Parameters\n    ----------\n    fns : list of strs of filenames or file handles\n        List of filename of the SJ.out.tab files to read in\n\n    jxns : set\n        If provided, only keep junctions in this set.\n\n    define_sample_name : function that takes string as input\n        Function mapping filename to sample name. For instance, you may have the\n        sample name in the path and use a regex to extract it.  The sample names\n        will be used as the column names. If this is not provided, the columns\n        will be named as the input files.\n\n    Returns\n    -------\n    sj_outD : dict\n        Dict whose keys are sample names and values are sj_out dataframes"
  },
  {
    "code": "def restartIndyPool(**kwargs):\n    print(\"Restarting...\")\n    try:\n      stopIndyPool()\n      startIndyPool()\n      print(\"...restarted\")\n    except Exception as exc:\n      eprint(\"...failed to restart\")\n      raise exc",
    "docstring": "Restart the indy_pool docker container. Idempotent. Ensures that the\n    indy_pool container is a new running instance."
  },
  {
    "code": "def _insert_job(self, body_object):\n        logger.debug('Submitting job: %s' % body_object)\n        job_collection = self.bigquery.jobs()\n        return job_collection.insert(\n            projectId=self.project_id,\n            body=body_object\n        ).execute(num_retries=self.num_retries)",
    "docstring": "Submit a job to BigQuery\n\n            Direct proxy to the insert() method of the offical BigQuery\n            python client.\n\n            Able to submit load, link, query, copy, or extract jobs.\n\n            For more details, see:\n            https://google-api-client-libraries.appspot.com/documentation/bigquery/v2/python/latest/bigquery_v2.jobs.html#insert\n\n        Parameters\n        ----------\n        body_object : body object passed to bigquery.jobs().insert()\n\n        Returns\n        -------\n        response of the bigquery.jobs().insert().execute() call\n\n        Raises\n        ------\n        BigQueryTimeoutException on timeout"
  },
  {
    "code": "def put_job(self, data, pri=65536, delay=0, ttr=120):\n        with self._sock_ctx() as socket:\n            message = 'put {pri} {delay} {ttr} {datalen}\\r\\n'.format(\n                pri=pri, delay=delay, ttr=ttr, datalen=len(data), data=data\n            ).encode('utf-8')\n            if not isinstance(data, bytes):\n                data = data.encode('utf-8')\n            message += data\n            message += b'\\r\\n'\n            self._send_message(message, socket)\n            return self._receive_id(socket)",
    "docstring": "Insert a new job into whatever queue is currently USEd\n\n        :param data: Job body\n        :type data: Text (either str which will be encoded as utf-8, or bytes which are already utf-8\n        :param pri: Priority for the job\n        :type pri: int\n        :param delay: Delay in seconds before the job should be placed on the ready queue\n        :type delay: int\n        :param ttr: Time to reserve (how long a worker may work on this job before we assume the worker is blocked\n            and give the job to another worker\n        :type ttr: int\n\n        .. seealso::\n\n           :func:`put_job_into()`\n              Put a job into a specific tube\n\n           :func:`using()`\n              Insert a job using an external guard"
  },
  {
    "code": "def _check_codons(self):\n        for stop_codon in self.stop_codons:\n            if stop_codon in self.codon_table:\n                if self.codon_table[stop_codon] != \"*\":\n                    raise ValueError(\n                        (\"Codon '%s' not found in stop_codons, but codon table \"\n                         \"indicates that it should be\") % (stop_codon,))\n            else:\n                self.codon_table[stop_codon] = \"*\"\n        for start_codon in self.start_codons:\n            if start_codon not in self.codon_table:\n                raise ValueError(\n                    \"Start codon '%s' missing from codon table\" % (\n                        start_codon,))\n        for codon, amino_acid in self.codon_table.items():\n            if amino_acid == \"*\" and codon not in self.stop_codons:\n                raise ValueError(\n                    \"Non-stop codon '%s' can't translate to '*'\" % (\n                        codon,))\n        if len(self.codon_table) != 64:\n            raise ValueError(\n                \"Expected 64 codons but found %d in codon table\" % (\n                    len(self.codon_table,)))",
    "docstring": "If codon table is missing stop codons, then add them."
  },
  {
    "code": "def w(name, parallel, workflow, internal):\n    Workflow = collections.namedtuple(\"Workflow\", \"name parallel workflow internal\")\n    return Workflow(name, parallel, workflow, internal)",
    "docstring": "A workflow, allowing specification of sub-workflows for nested parallelization.\n\n    name and parallel are documented under the Step (s) function.\n    workflow -- a list of Step tuples defining the sub-workflow\n    internal -- variables used in the sub-workflow but not exposed to subsequent steps"
  },
  {
    "code": "def get_blocks_overview(block_representation_list, coin_symbol='btc', txn_limit=None, api_key=None):\n    for block_representation in block_representation_list:\n        assert is_valid_block_representation(\n                block_representation=block_representation,\n                coin_symbol=coin_symbol)\n    assert is_valid_coin_symbol(coin_symbol)\n    blocks = ';'.join([str(x) for x in block_representation_list])\n    url = make_url(coin_symbol, **dict(blocks=blocks))\n    logger.info(url)\n    params = {}\n    if api_key:\n        params['token'] = api_key\n    if txn_limit:\n        params['limit'] = txn_limit\n    r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)\n    r = get_valid_json(r)\n    return [_clean_tx(response_dict=d) for d in r]",
    "docstring": "Batch request version of get_blocks_overview"
  },
  {
    "code": "def dispatch(*funcs):\n    def _dispatch(*args, **kwargs):\n        for f in funcs:\n            result = f(*args, **kwargs)\n            if result is not None:\n                return result\n        return None\n    return _dispatch",
    "docstring": "Iterates through the functions\n    and calls them with given the parameters\n    and returns the first non-empty result\n\n    >>> f = dispatch(lambda: None, lambda: 1)\n    >>> f()\n    1\n\n    :param \\*funcs: funcs list of dispatched functions\n    :returns: dispatch functoin"
  },
  {
    "code": "def adjust_interleave(self, interleave):\n        if interleave == None and self.parent:\n            self.interleave = self.parent.interleave\n        else:\n            self.interleave = interleave",
    "docstring": "Inherit interleave status from parent if undefined."
  },
  {
    "code": "def _rpc(http, project, method, base_url, request_pb, response_pb_cls):\n    req_data = request_pb.SerializeToString()\n    response = _request(http, project, method, req_data, base_url)\n    return response_pb_cls.FromString(response)",
    "docstring": "Make a protobuf RPC request.\n\n    :type http: :class:`requests.Session`\n    :param http: HTTP object to make requests.\n\n    :type project: str\n    :param project: The project to connect to. This is\n                    usually your project name in the cloud console.\n\n    :type method: str\n    :param method: The name of the method to invoke.\n\n    :type base_url: str\n    :param base_url: The base URL where the API lives.\n\n    :type request_pb: :class:`google.protobuf.message.Message` instance\n    :param request_pb: the protobuf instance representing the request.\n\n    :type response_pb_cls: A :class:`google.protobuf.message.Message`\n                           subclass.\n    :param response_pb_cls: The class used to unmarshall the response\n                            protobuf.\n\n    :rtype: :class:`google.protobuf.message.Message`\n    :returns: The RPC message parsed from the response."
  },
  {
    "code": "def delete_scope(self, scope):\n        assert isinstance(scope, Scope), 'Scope \"{}\" is not a scope!'.format(scope.name)\n        response = self._request('DELETE', self._build_url('scope', scope_id=str(scope.id)))\n        if response.status_code != requests.codes.no_content:\n            raise APIError(\"Could not delete scope, {}: {}\".format(str(response), response.content))",
    "docstring": "Delete a scope.\n\n        This will delete a scope if the client has the right to do so. Sufficient permissions to delete a scope are a\n        superuser, a user in the `GG:Configurators` group or a user that is the Scope manager of the scope to be\n        deleted.\n\n        :param scope: Scope object to be deleted\n        :type scope: :class: `models.Scope`\n\n        :return: None\n        :raises APIError: in case of failure in the deletion of the scope"
  },
  {
    "code": "def _fingerprint_target_specs(self, specs):\n    assert self._build_graph is not None, (\n      'cannot fingerprint specs `{}` without a `BuildGraph`'.format(specs)\n    )\n    hasher = sha1()\n    for spec in sorted(specs):\n      for target in sorted(self._build_graph.resolve(spec)):\n        h = target.compute_invalidation_hash()\n        if h:\n          hasher.update(h.encode('utf-8'))\n    return hasher.hexdigest()",
    "docstring": "Returns a fingerprint of the targets resolved from given target specs."
  },
  {
    "code": "def buildFileList(input, output=None, ivmlist=None,\n                wcskey=None, updatewcs=True, **workinplace):\n    newfilelist, ivmlist, output, oldasndict, filelist = \\\n        buildFileListOrig(input=input, output=output, ivmlist=ivmlist,\n                    wcskey=wcskey, updatewcs=updatewcs, **workinplace)\n    return newfilelist, ivmlist, output, oldasndict",
    "docstring": "Builds a file list which has undergone various instrument-specific\n    checks for input to MultiDrizzle, including splitting STIS associations."
  },
  {
    "code": "def walkable(self, x, y):\n        return self.inside(x, y) and self.nodes[y][x].walkable",
    "docstring": "check, if the tile is inside grid and if it is set as walkable"
  },
  {
    "code": "def writelines(self, lines):\n        self.make_dir()\n        with open(self.path, \"w\") as f:\n            return f.writelines(lines)",
    "docstring": "Write a list of strings to file."
  },
  {
    "code": "def size(self):\n        pos = self._stream.tell()\n        self._stream.seek(0,2)\n        size = self._stream.tell()\n        self._stream.seek(pos, 0)\n        return size",
    "docstring": "Return the size of the stream, or -1 if it cannot\n        be determined."
  },
  {
    "code": "def _default_objc(self):\n        objc = ctypes.cdll.LoadLibrary(find_library('objc'))\n        objc.objc_getClass.restype = ctypes.c_void_p\n        objc.sel_registerName.restype = ctypes.c_void_p\n        objc.objc_msgSend.restype = ctypes.c_void_p\n        objc.objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p]\n        return objc",
    "docstring": "Load the objc library using ctypes."
  },
  {
    "code": "def parse_to_gvid(v):\n    from geoid.civick import GVid\n    from geoid.acs import AcsGeoid\n    m1 = ''\n    try:\n        return GVid.parse(v)\n    except ValueError as e:\n        m1 = str(e)\n    try:\n        return AcsGeoid.parse(v).convert(GVid)\n    except ValueError as e:\n        raise ValueError(\"Failed to parse to either ACS or GVid: {}; {}\".format(m1, str(e)))",
    "docstring": "Parse an ACS Geoid or a GVID to a GVID"
  },
  {
    "code": "def post_gist(content, description='', filename='file', auth=False):\n    post_data = json.dumps({\n      \"description\": description,\n      \"public\": True,\n      \"files\": {\n        filename: {\n          \"content\": content\n        }\n      }\n    }).encode('utf-8')\n    headers = make_auth_header() if auth else {}\n    response = requests.post(\"https://api.github.com/gists\", data=post_data, headers=headers)\n    response.raise_for_status()\n    response_data = json.loads(response.text)\n    return response_data['html_url']",
    "docstring": "Post some text to a Gist, and return the URL."
  },
  {
    "code": "def get_header(results):\n    ret = ['name', ]\n    values = next(iter(results.values()))\n    for k, v in values.items():\n        if isinstance(v, dict):\n            for metric in v.keys():\n                ret.append('%s:%s' % (k, metric))\n        else:\n            ret.append(k)\n    return ret",
    "docstring": "Extracts the headers, using the first value in the dict as the template"
  },
  {
    "code": "def wait(self, timeout=3):\n        start = time.time()\n        while not self.exists():\n            self.poco.sleep_for_polling_interval()\n            if time.time() - start > timeout:\n                break\n        return self",
    "docstring": "Block and wait for max given time before the UI element appears.\n\n        Args:\n            timeout: maximum waiting time in seconds\n\n        Returns:\n            :py:class:`UIObjectProxy <poco.proxy.UIObjectProxy>`: self"
  },
  {
    "code": "def AB(self):\n        try:\n            return self._AB\n        except AttributeError:\n            pass\n        self._AB = [self.A, self.B]\n        return self._AB",
    "docstring": "A list containing Points A and B."
  },
  {
    "code": "def supported_tifs(self):\n        buf = ctypes.c_uint32()\n        self._dll.JLINKARM_TIF_GetAvailable(ctypes.byref(buf))\n        return buf.value",
    "docstring": "Returns a bitmask of the supported target interfaces.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n\n        Returns:\n          Bitfield specifying which target interfaces are supported."
  },
  {
    "code": "def debug(msg):\n    if DEBUG:\n        sys.stderr.write(\"DEBUG: \" + msg + \"\\n\")\n        sys.stderr.flush()",
    "docstring": "Displays debug messages to stderr only if the Python interpreter was invoked with the -O flag."
  },
  {
    "code": "def has_reduction(expr):\n    def fn(expr):\n        op = expr.op()\n        if isinstance(op, ops.TableNode):\n            return lin.halt, None\n        if isinstance(op, ops.Reduction):\n            return lin.halt, True\n        return lin.proceed, None\n    reduction_status = lin.traverse(fn, expr)\n    return any(reduction_status)",
    "docstring": "Does `expr` contain a reduction?\n\n    Parameters\n    ----------\n    expr : ibis.expr.types.Expr\n        An ibis expression\n\n    Returns\n    -------\n    truth_value : bool\n        Whether or not there's at least one reduction in `expr`\n\n    Notes\n    -----\n    The ``isinstance(op, ops.TableNode)`` check in this function implies\n    that we only examine every non-table expression that precedes the first\n    table expression."
  },
  {
    "code": "def reset_state(self):\n        super(AugmentorList, self).reset_state()\n        for a in self.augmentors:\n            a.reset_state()",
    "docstring": "Will reset state of each augmentor"
  },
  {
    "code": "def make_error_response(self, validation_error, expose_errors):\n    authenticate_header = ['Bearer realm=\"{}\"'.format(settings.DJOAUTH2_REALM)]\n    if not expose_errors:\n      response = HttpResponse(status=400)\n      response['WWW-Authenticate'] = ', '.join(authenticate_header)\n      return response\n    status_code = 401\n    error_details = get_error_details(validation_error)\n    if isinstance(validation_error, InvalidRequest):\n      status_code = 400\n    elif isinstance(validation_error, InvalidToken):\n      status_code = 401\n    elif isinstance(validation_error, InsufficientScope):\n      error_details['scope'] = ' '.join(self.required_scope_names)\n      status_code = 403\n    response = HttpResponse(content=json.dumps(error_details),\n                            content_type='application/json',\n                            status=status_code)\n    for key, value in error_details.iteritems():\n      authenticate_header.append('{}=\"{}\"'.format(key, value))\n    response['WWW-Authenticate'] = ', '.join(authenticate_header)\n    return response",
    "docstring": "Return an appropriate ``HttpResponse`` on authentication failure.\n\n    In case of an error, the specification only details the inclusion of the\n    ``WWW-Authenticate`` header. Additionally, when allowed by the\n    specification, we respond with error details formatted in JSON in the body\n    of the response. For more information, read the specification:\n    http://tools.ietf.org/html/rfc6750#section-3.1 .\n\n    :param validation_error: A\n      :py:class:`djoauth2.access_token.AuthenticationError` raised by the\n      :py:meth:`validate` method.\n    :param expose_errors: A boolean describing whether or not to expose error\n      information in the error response, as described by the section of the\n      specification linked to above.\n\n    :rtype: a Django ``HttpResponse``."
  },
  {
    "code": "def build_footprint(node: ast.AST, first_line_no: int) -> Set[int]:\n    return set(\n        range(\n            get_first_token(node).start[0] - first_line_no,\n            get_last_token(node).end[0] - first_line_no + 1,\n        )\n    )",
    "docstring": "Generates a list of lines that the passed node covers, relative to the\n    marked lines list - i.e. start of function is line 0."
  },
  {
    "code": "def render_engine_or_search_template(template_name, **context):\n    from indico_search.plugin import SearchPlugin\n    assert current_plugin == SearchPlugin.instance\n    templates = ('{}:{}'.format(SearchPlugin.instance.engine_plugin.name, template_name),\n                 template_name)\n    return render_plugin_template(templates, **context)",
    "docstring": "Renders a template from the engine plugin or the search plugin\n\n    If the template is available in the engine plugin, it's taken\n    from there, otherwise the template from this plugin is used.\n\n    :param template_name: name of the template\n    :param context: the variables that should be available in the\n                    context of the template."
  },
  {
    "code": "def do_start_alerts(self, _):\n        if self._alerter_thread.is_alive():\n            print(\"The alert thread is already started\")\n        else:\n            self._stop_thread = False\n            self._alerter_thread = threading.Thread(name='alerter', target=self._alerter_thread_func)\n            self._alerter_thread.start()",
    "docstring": "Starts the alerter thread"
  },
  {
    "code": "def total_read_throughput(self):\n        total = self.read_throughput\n        for index in itervalues(self.global_indexes):\n            total += index.read_throughput\n        return total",
    "docstring": "Combined read throughput of table and global indexes"
  },
  {
    "code": "def video_pixel_noise_bottom(x, model_hparams, vocab_size):\n  input_noise = getattr(model_hparams, \"video_modality_input_noise\", 0.25)\n  inputs = x\n  if model_hparams.mode == tf.estimator.ModeKeys.TRAIN:\n    background = tfp.stats.percentile(inputs, 50., axis=[0, 1, 2, 3])\n    input_shape = common_layers.shape_list(inputs)\n    input_size = tf.reduce_prod(input_shape[:-1])\n    input_mask = tf.multinomial(\n        tf.log([[input_noise, 1.-input_noise]]), input_size)\n    input_mask = tf.reshape(tf.cast(input_mask, tf.int32),\n                            input_shape[:-1]+[1])\n    inputs = inputs * input_mask + background * (1 - input_mask)\n  return video_bottom(inputs, model_hparams, vocab_size)",
    "docstring": "Bottom transformation for video."
  },
  {
    "code": "def ping(self, message=None):\n        return self.write(self.parser.ping(message), encode=False)",
    "docstring": "Write a ping ``frame``."
  },
  {
    "code": "def range(cls, dataset, dimension):\n        dim = dataset.get_dimension(dimension, strict=True)\n        values = dataset.dimension_values(dim.name, False)\n        return (np.nanmin(values), np.nanmax(values))",
    "docstring": "Computes the range along a particular dimension."
  },
  {
    "code": "def tiles_to_pixels(self, tiles):\n        pixel_coords = Vector2()\n        pixel_coords.X = tiles[0] * self.spritesheet[0].width\n        pixel_coords.Y = tiles[1] * self.spritesheet[0].height\n        return pixel_coords",
    "docstring": "Convert tile coordinates into pixel coordinates"
  },
  {
    "code": "def find_for_player_id(player_id, connection=None, page_size=100,\n        page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER):\n        return pybrightcove.connection.ItemResultSet(\n            \"find_playlists_for_player_id\", Playlist, connection, page_size,\n            page_number, sort_by, sort_order, player_id=player_id)",
    "docstring": "List playlists for a for given player id."
  },
  {
    "code": "def hash_file(file_obj,\n              hash_function=hashlib.md5):\n    file_position = file_obj.tell()\n    hasher = hash_function()\n    hasher.update(file_obj.read())\n    hashed = hasher.hexdigest()\n    file_obj.seek(file_position)\n    return hashed",
    "docstring": "Get the hash of an open file- like object.\n\n    Parameters\n    ---------\n    file_obj: file like object\n    hash_function: function to use to hash data\n\n    Returns\n    ---------\n    hashed: str, hex version of result"
  },
  {
    "code": "def find_name(self, template_name, search_dirs):\n        file_name = self.make_file_name(template_name)\n        return self._find_path_required(search_dirs, file_name)",
    "docstring": "Return the path to a template with the given name.\n\n        Arguments:\n\n          template_name: the name of the template.\n\n          search_dirs: the list of directories in which to search."
  },
  {
    "code": "def load_configuration(configuration):\n    if isinstance(configuration, dict):\n        return configuration\n    else:\n        with open(configuration) as configfile:\n            return json.load(configfile)",
    "docstring": "Returns a dictionary, accepts a dictionary or a path to a JSON file."
  },
  {
    "code": "def _make_attr_element_from_resourceattr(parent, resource_attr_i):\n    attr = _make_attr_element(parent, resource_attr_i.attr)\n    attr_is_var    = etree.SubElement(attr, 'is_var')\n    attr_is_var.text = resource_attr_i.attr_is_var\n    return attr",
    "docstring": "General function to add an attribute element to a resource element."
  },
  {
    "code": "def check(self, line):\n        if not isinstance(line, str):\n            raise TypeError(\"Parameter 'line' not a 'string', is {0}\".format(type(line)))\n        if line in self.contents:\n            return line\n        return False",
    "docstring": "Find first occurrence of 'line' in file.\n\n        This searches each line as a whole, if you want to see if a substring is in a line, use .grep() or .egrep()\n\n        If found, return the line; this makes it easier to chain methods.\n\n        :param line: String; whole line to find.\n        :return: String or False."
  },
  {
    "code": "def remove(self, participant):\n        for topic, participants in list(self._participants_by_topic.items()):\n            self.unsubscribe(participant, topic)\n            if not participants:\n                del self._participants_by_topic[topic]",
    "docstring": "Unsubscribe this participant from all topic to which it is subscribed."
  },
  {
    "code": "def get_corpus(self, corpus_id):\n        try:\n            corpus = self.corpora[corpus_id]\n            return corpus\n        except KeyError:\n            raise InvalidCorpusError",
    "docstring": "Return a corpus given an ID.\n\n        If the corpus ID cannot be found, an InvalidCorpusError is raised.\n\n        Parameters\n        ----------\n        corpus_id : str\n            The ID of the corpus to return.\n\n        Returns\n        -------\n        Corpus\n            The corpus with the given ID."
  },
  {
    "code": "def gradient(x, a, c):\n    return jac(x, a).T.dot(g(x, a, c))",
    "docstring": "J'.G"
  },
  {
    "code": "def irreducible_purviews(cm, direction, mechanism, purviews):\n    def reducible(purview):\n        _from, to = direction.order(mechanism, purview)\n        return connectivity.block_reducible(cm, _from, to)\n    return [purview for purview in purviews if not reducible(purview)]",
    "docstring": "Return all purviews which are irreducible for the mechanism.\n\n    Args:\n        cm (np.ndarray): An |N x N| connectivity matrix.\n        direction (Direction): |CAUSE| or |EFFECT|.\n        purviews (list[tuple[int]]): The purviews to check.\n        mechanism (tuple[int]): The mechanism in question.\n\n    Returns:\n        list[tuple[int]]: All purviews in ``purviews`` which are not reducible\n        over ``mechanism``.\n\n    Raises:\n        ValueError: If ``direction`` is invalid."
  },
  {
    "code": "def GET_namespaces( self, path_info ):\n        qs_values = path_info['qs_values']\n        offset = qs_values.get('offset', None)\n        count = qs_values.get('count', None)\n        blockstackd_url = get_blockstackd_url()\n        namespaces = blockstackd_client.get_all_namespaces(offset=offset, count=count, hostport=blockstackd_url)\n        if json_is_error(namespaces):\n            status_code = namespaces.get('http_status', 502)\n            return self._reply_json({'error': namespaces['error']}, status_code=status_code)\n        self._reply_json(namespaces)\n        return",
    "docstring": "Get the list of all namespaces\n        Reply all existing namespaces\n        Reply 502 if we can't reach the server for whatever reason"
  },
  {
    "code": "def render_mako_template(self, template_path, context=None):\n        context = context or {}\n        template_str = self.load_unicode(template_path)\n        lookup = MakoTemplateLookup(directories=[pkg_resources.resource_filename(self.module_name, '')])\n        template = MakoTemplate(template_str, lookup=lookup)\n        return template.render(**context)",
    "docstring": "Evaluate a mako template by resource path, applying the provided context"
  },
  {
    "code": "def get_temperature(self, unit=DEGREES_C):\n        if self.type in self.TYPES_12BIT_STANDARD:\n            value = self.raw_sensor_count\n            value /= 16.0\n            if value == 85.0:\n                raise ResetValueError(self)\n            factor = self._get_unit_factor(unit)\n            return factor(value)\n        factor = self._get_unit_factor(unit)\n        return factor(self.raw_sensor_temp * 0.001)",
    "docstring": "Returns the temperature in the specified unit\n\n            :param int unit: the unit of the temperature requested\n\n            :returns: the temperature in the given unit\n            :rtype: float\n\n            :raises UnsupportedUnitError: if the unit is not supported\n            :raises NoSensorFoundError: if the sensor could not be found\n            :raises SensorNotReadyError: if the sensor is not ready yet\n            :raises ResetValueError: if the sensor has still the initial value and no measurment"
  },
  {
    "code": "def earliest_date(dates, full_date=False):\n    min_date = min(PartialDate.loads(date) for date in dates)\n    if not min_date.month and full_date:\n        min_date.month = 1\n    if not min_date.day and full_date:\n        min_date.day = 1\n    return min_date.dumps()",
    "docstring": "Return the earliest among the schema-compliant dates.\n\n    This is a convenience wrapper around :ref:`PartialDate`, which should be\n    used instead if more features are needed.\n\n    Args:\n        dates(list): List of dates from which oldest/earliest one will be returned\n        full_date(bool): Adds month and/or day as \"01\" if they are missing\n    Returns:\n        str: Earliest date from provided list"
  },
  {
    "code": "def form_valid(self, form):\n        response = super(FormAjaxMixin, self).form_valid(form)\n        if self.request.is_ajax():\n            return self.json_to_response()\n        return response",
    "docstring": "If form valid return response with action"
  },
  {
    "code": "def _transition_callback(self, is_on, transition):\n        if transition.state_stages:\n            state = transition.state_stages[transition.stage_index]\n            if self.is_on and is_on is False:\n                state['brightness'] = self.brightness\n            self.set(is_on=is_on, cancel_transition=False, **state)\n        self._active_transition = None",
    "docstring": "Callback that is called when a transition has ended.\n\n        :param is_on: The on-off state to transition to.\n        :param transition: The transition that has ended."
  },
  {
    "code": "def A_multiple_hole_cylinder(Do, L, holes):\n    r\n    side_o = pi*Do*L\n    cap_circle = pi*Do**2/4*2\n    A = cap_circle + side_o\n    for Di, n in holes:\n        side_i = pi*Di*L\n        cap_removed = pi*Di**2/4*2\n        A = A + side_i*n - cap_removed*n\n    return A",
    "docstring": "r'''Returns the surface area of a cylinder with multiple holes.\n    Calculation will naively return a negative value or other impossible\n    result if the number of cylinders added is physically impossible.\n    Holes may be of different shapes, but must be perpendicular to the\n    axis of the cylinder.\n\n    .. math::\n        A = \\pi D_o L + 2\\cdot \\frac{\\pi D_o^2}{4} +\n        \\sum_{i}^n \\left( \\pi D_i L  - 2\\cdot \\frac{\\pi D_i^2}{4}\\right)\n\n    Parameters\n    ----------\n    Do : float\n        Diameter of the exterior of the cylinder, [m]\n    L : float\n        Length of the cylinder, [m]\n    holes : list\n        List of tuples containing (diameter, count) pairs of descriptions for\n        each of the holes sizes.\n\n    Returns\n    -------\n    A : float\n        Surface area [m^2]\n\n    Examples\n    --------\n    >>> A_multiple_hole_cylinder(0.01, 0.1, [(0.005, 1)])\n    0.004830198704894308"
  },
  {
    "code": "def _get_repos(url):\n        current_page = 1\n        there_is_something_left = True\n        repos_list = []\n        while there_is_something_left:\n            api_driver = GithubRawApi(\n                url,\n                url_params={\"page\": current_page},\n                get_api_content_now=True\n            )\n            for repo in api_driver.api_content:\n                repo_name = repo[\"name\"]\n                repo_user = repo[\"owner\"][\"login\"]\n                repos_list.append(\n                    GithubUserRepository(repo_user, repo_name))\n            there_is_something_left = bool(api_driver.api_content)\n            current_page += 1\n        return repos_list",
    "docstring": "Gets repos in url\n\n        :param url: Url\n        :return: List of repositories in given url"
  },
  {
    "code": "def read_plain_int32(file_obj, count):\n    length = 4 * count\n    data = file_obj.read(length)\n    if len(data) != length:\n        raise EOFError(\"Expected {} bytes but got {} bytes\".format(length, len(data)))\n    res = struct.unpack(\"<{}i\".format(count).encode(\"utf-8\"), data)\n    return res",
    "docstring": "Read `count` 32-bit ints using the plain encoding."
  },
  {
    "code": "def _vote_disagreement(self, votes):\n        ret = []\n        for candidate in votes:\n            ret.append(0.0)\n            lab_count = {}\n            for lab in candidate:\n                lab_count[lab] = lab_count.setdefault(lab, 0) + 1\n            for lab in lab_count.keys():\n                ret[-1] -= lab_count[lab] / self.n_students * \\\n                    math.log(float(lab_count[lab]) / self.n_students)\n        return ret",
    "docstring": "Return the disagreement measurement of the given number of votes.\n        It uses the vote vote to measure the disagreement.\n\n        Parameters\n        ----------\n        votes : list of int, shape==(n_samples, n_students)\n            The predictions that each student gives to each sample.\n\n        Returns\n        -------\n        disagreement : list of float, shape=(n_samples)\n            The vote entropy of the given votes."
  },
  {
    "code": "def resume(self, instance_id):\n        nt_ks = self.compute_conn\n        response = nt_ks.servers.resume(instance_id)\n        return True",
    "docstring": "Resume a server"
  },
  {
    "code": "def load_data_table(table_name, meta_file, meta):\n    for table in meta['tables']:\n        if table['name'] == table_name:\n            prefix = os.path.dirname(meta_file)\n            relative_path = os.path.join(prefix, meta['path'], table['path'])\n            return pd.read_csv(relative_path), table",
    "docstring": "Return the contents and metadata of a given table.\n\n    Args:\n        table_name(str): Name of the table.\n        meta_file(str): Path to the meta.json file.\n        meta(dict): Contents of meta.json.\n\n    Returns:\n        tuple(pandas.DataFrame, dict)"
  },
  {
    "code": "def insertReadGroupSet(self, readGroupSet):\n        programsJson = json.dumps(\n            [protocol.toJsonDict(program) for program in\n             readGroupSet.getPrograms()])\n        statsJson = json.dumps(protocol.toJsonDict(readGroupSet.getStats()))\n        try:\n            models.Readgroupset.create(\n                id=readGroupSet.getId(),\n                datasetid=readGroupSet.getParentContainer().getId(),\n                referencesetid=readGroupSet.getReferenceSet().getId(),\n                name=readGroupSet.getLocalId(),\n                programs=programsJson,\n                stats=statsJson,\n                dataurl=readGroupSet.getDataUrl(),\n                indexfile=readGroupSet.getIndexFile(),\n                attributes=json.dumps(readGroupSet.getAttributes()))\n            for readGroup in readGroupSet.getReadGroups():\n                self.insertReadGroup(readGroup)\n        except Exception as e:\n            raise exceptions.RepoManagerException(e)",
    "docstring": "Inserts a the specified readGroupSet into this repository."
  },
  {
    "code": "def delete_nve_member(self, nexus_host, nve_int_num, vni):\n        starttime = time.time()\n        path_snip = snipp.PATH_VNI_UPDATE % (nve_int_num, vni)\n        self.client.rest_delete(path_snip, nexus_host)\n        self.capture_and_print_timeshot(\n            starttime, \"delete_nve\",\n            switch=nexus_host)",
    "docstring": "Delete a member configuration on the NVE interface."
  },
  {
    "code": "def connect(url, prefix=None, **kwargs):\n    return connection(url, prefix=get_prefix(prefix), **kwargs)",
    "docstring": "connect and return a connection instance from url\n\n    arguments:\n        - url (str): xbahn connection url"
  },
  {
    "code": "def read_lines(in_file):\n    with open(in_file, 'r') as inf:\n        in_contents = inf.read().split('\\n')\n    return in_contents",
    "docstring": "Returns a list of lines from a input markdown file."
  },
  {
    "code": "def ConfigureHostnames(config, external_hostname = None):\n  if not external_hostname:\n    try:\n      external_hostname = socket.gethostname()\n    except (OSError, IOError):\n      print(\"Sorry, we couldn't guess your hostname.\\n\")\n    external_hostname = RetryQuestion(\n        \"Please enter your hostname e.g. \"\n        \"grr.example.com\", \"^[\\\\.A-Za-z0-9-]+$\", external_hostname)\n  print(\n)\n  frontend_url = RetryQuestion(\"Frontend URL\", \"^http://.*/$\",\n                               \"http://%s:8080/\" % external_hostname)\n  config.Set(\"Client.server_urls\", [frontend_url])\n  frontend_port = urlparse.urlparse(frontend_url).port or grr_config.CONFIG.Get(\n      \"Frontend.bind_port\")\n  config.Set(\"Frontend.bind_port\", frontend_port)\n  print(\n)\n  ui_url = RetryQuestion(\"AdminUI URL\", \"^http[s]*://.*$\",\n                         \"http://%s:8000\" % external_hostname)\n  config.Set(\"AdminUI.url\", ui_url)\n  ui_port = urlparse.urlparse(ui_url).port or grr_config.CONFIG.Get(\n      \"AdminUI.port\")\n  config.Set(\"AdminUI.port\", ui_port)",
    "docstring": "This configures the hostnames stored in the config."
  },
  {
    "code": "def save(self, path: str):\n        with open(path, 'wb') as out:\n            np.save(out, self.lex)\n        logger.info(\"Saved top-k lexicon to \\\"%s\\\"\", path)",
    "docstring": "Save lexicon in Numpy array format.  Lexicon will be specific to Sockeye model.\n\n        :param path: Path to Numpy array output file."
  },
  {
    "code": "def setup(self):\n        for table_spec in self._table_specs:\n            with self._conn:\n                table_spec.setup(self._conn)",
    "docstring": "Setup cache tables."
  },
  {
    "code": "def clean(self, text, **kwargs):\n        if sys.version_info < (3, 0):\n            if not isinstance(text, unicode):\n                raise exceptions.UnicodeRequired\n        clean_chunks = []\n        filth = Filth()\n        for next_filth in self.iter_filth(text):\n            clean_chunks.append(text[filth.end:next_filth.beg])\n            clean_chunks.append(next_filth.replace_with(**kwargs))\n            filth = next_filth\n        clean_chunks.append(text[filth.end:])\n        return u''.join(clean_chunks)",
    "docstring": "This is the master method that cleans all of the filth out of the\n        dirty dirty ``text``. All keyword arguments to this function are passed\n        through to the  ``Filth.replace_with`` method to fine-tune how the\n        ``Filth`` is cleaned."
  },
  {
    "code": "def get_instance(self, payload):\n        return RecordingInstance(\n            self._version,\n            payload,\n            account_sid=self._solution['account_sid'],\n            call_sid=self._solution['call_sid'],\n        )",
    "docstring": "Build an instance of RecordingInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.api.v2010.account.call.recording.RecordingInstance\n        :rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance"
  },
  {
    "code": "def det_n(x):\n    assert x.ndim == 3\n    assert x.shape[1] == x.shape[2]\n    if x.shape[1] == 1:\n        return x[:,0,0]\n    result = np.zeros(x.shape[0])\n    for permutation in permutations(np.arange(x.shape[1])):\n        sign = parity(permutation)\n        result += np.prod([x[:, i, permutation[i]]\n                           for i in range(x.shape[1])], 0) * sign\n        sign = - sign\n    return result",
    "docstring": "given N matrices, return N determinants"
  },
  {
    "code": "def rule_function_not_found(self, fun=None):\n        sfun = str(fun)\n        self.cry('rule_function_not_found:' + sfun)\n        def not_found(*a, **k):\n            return(sfun + ':rule_function_not_found', k.keys())\n        return not_found",
    "docstring": "any function that does not exist will be added as a\n        dummy function that will gather inputs for easing into\n        the possible future implementation"
  },
  {
    "code": "def get_all_regions(db_connection):\n    if not hasattr(get_all_regions, '_results'):\n        sql = 'CALL get_all_regions();'\n        results = execute_sql(sql, db_connection)\n        get_all_regions._results = results\n    return get_all_regions._results",
    "docstring": "Gets a list of all regions.\n\n    :return: A list of all regions. Results have regionID and regionName.\n    :rtype: list"
  },
  {
    "code": "def template_hook_collect(module, hook_name, *args, **kwargs):\n    try:\n        templatehook = getattr(module, hook_name)\n    except AttributeError:\n        return \"\"\n    return format_html_join(\n        sep=\"\\n\",\n        format_string=\"{}\",\n        args_generator=(\n            (response, )\n            for response in templatehook(*args, **kwargs)\n        )\n    )",
    "docstring": "Helper to include in your own templatetag, for static TemplateHooks\n\n    Example::\n\n        import myhooks\n        from hooks.templatetags import template_hook_collect\n\n        @register.simple_tag(takes_context=True)\n        def hook(context, name, *args, **kwargs):\n            return template_hook_collect(myhooks, name, context, *args, **kwargs)\n\n    :param module module: Module containing the template hook definitions\n    :param str hook_name: The hook name to be dispatched\n    :param \\*args: Positional arguments, will be passed to hook callbacks\n    :param \\*\\*kwargs: Keyword arguments, will be passed to hook callbacks\n    :return: A concatenation of all callbacks\\\n    responses marked as safe (conditionally)\n    :rtype: str"
  },
  {
    "code": "def AddPmf(self, other):\n        pmf = Pmf()\n        for v1, p1 in self.Items():\n            for v2, p2 in other.Items():\n                pmf.Incr(v1 + v2, p1 * p2)\n        return pmf",
    "docstring": "Computes the Pmf of the sum of values drawn from self and other.\n\n        other: another Pmf\n\n        returns: new Pmf"
  },
  {
    "code": "def __validate(data, classes, labels):\n        \"Validator of inputs.\"\n        if not isinstance(data, dict):\n            raise TypeError(\n                'data must be a dict! keys: sample ID or any unique identifier')\n        if not isinstance(labels, dict):\n            raise TypeError(\n                'labels must be a dict! keys: sample ID or any unique identifier')\n        if classes is not None:\n            if not isinstance(classes, dict):\n                raise TypeError(\n                    'labels must be a dict! keys: sample ID or any unique identifier')\n        if not len(data) == len(labels) == len(classes):\n            raise ValueError('Lengths of data, labels and classes do not match!')\n        if not set(list(data)) == set(list(labels)) == set(list(classes)):\n            raise ValueError(\n                'data, classes and labels dictionaries must have the same keys!')\n        num_features_in_elements = np.unique([sample.size for sample in data.values()])\n        if len(num_features_in_elements) > 1:\n            raise ValueError(\n                'different samples have different number of features - invalid!')\n        return True",
    "docstring": "Validator of inputs."
  },
  {
    "code": "def _set_item(self, key, value):\n        self._ensure_valid_index(value)\n        value = self._sanitize_column(key, value)\n        NDFrame._set_item(self, key, value)\n        if len(self):\n            self._check_setitem_copy()",
    "docstring": "Add series to DataFrame in specified column.\n\n        If series is a numpy-array (not a Series/TimeSeries), it must be the\n        same length as the DataFrames index or an error will be thrown.\n\n        Series/TimeSeries will be conformed to the DataFrames index to\n        ensure homogeneity."
  },
  {
    "code": "def marvcli_user_rm(ctx, username):\n    app = create_app()\n    try:\n        app.um.user_rm(username)\n    except ValueError as e:\n        ctx.fail(e.args[0])",
    "docstring": "Remove a user"
  },
  {
    "code": "def get_module_path(exc_type):\n    module = inspect.getmodule(exc_type)\n    return \"{}.{}\".format(module.__name__, exc_type.__name__)",
    "docstring": "Return the dotted module path of `exc_type`, including the class name.\n\n    e.g.::\n\n        >>> get_module_path(MethodNotFound)\n        >>> \"nameko.exceptions.MethodNotFound\""
  },
  {
    "code": "def ancestor_paths(start=None, limit={}):\n    import utool as ut\n    limit = ut.ensure_iterable(limit)\n    limit = {expanduser(p) for p in limit}.union(set(limit))\n    if start is None:\n        start = os.getcwd()\n    path = start\n    prev = None\n    while path != prev and prev not in limit:\n        yield path\n        prev = path\n        path = dirname(path)",
    "docstring": "All paths above you"
  },
  {
    "code": "def interpolate_delta_t(delta_t_table, tt):\n    tt_array, delta_t_array = delta_t_table\n    delta_t = _to_array(interp(tt, tt_array, delta_t_array, nan, nan))\n    missing = isnan(delta_t)\n    if missing.any():\n        if missing.shape:\n            tt = tt[missing]\n            delta_t[missing] = delta_t_formula_morrison_and_stephenson_2004(tt)\n        else:\n            delta_t = delta_t_formula_morrison_and_stephenson_2004(tt)\n    return delta_t",
    "docstring": "Return interpolated Delta T values for the times in `tt`.\n\n    The 2xN table should provide TT values as element 0 and\n    corresponding Delta T values for element 1.  For times outside the\n    range of the table, a long-term formula is used instead."
  },
  {
    "code": "def deactivateAaPdpContextRequest():\n    a = TpPd(pd=0x8)\n    b = MessageType(mesType=0x53)\n    c = AaDeactivationCauseAndSpareHalfOctets()\n    packet = a / b / c\n    return packet",
    "docstring": "DEACTIVATE AA PDP CONTEXT REQUEST Section 9.5.13"
  },
  {
    "code": "def parse_attributes( fields ):\n    attributes = {}\n    for field in fields:\n        pair = field.split( '=' )\n        attributes[ pair[0] ] = pair[1]\n    return attributes",
    "docstring": "Parse list of key=value strings into a dict"
  },
  {
    "code": "def multipart_delete(self, multipart):\n        multipart.delete()\n        db.session.commit()\n        if multipart.file_id:\n            remove_file_data.delay(str(multipart.file_id))\n        return self.make_response('', 204)",
    "docstring": "Abort a multipart upload.\n\n        :param multipart: A :class:`invenio_files_rest.models.MultipartObject`\n            instance.\n        :returns: A Flask response."
  },
  {
    "code": "def validate_json(self):\n        if not hasattr(self, 'guidance_json'):\n            return False\n        checksum = self.guidance_json.get('checksum')\n        contents = self.guidance_json.get('db')\n        hash_key = (\"{}{}\".format(json.dumps(contents, sort_keys=True),\n                                  self.assignment.endpoint).encode())\n        digest = hashlib.md5(hash_key).hexdigest()\n        if not checksum:\n            log.warning(\"Checksum on guidance not found. Invalidating file\")\n            return False\n        if digest != checksum:\n            log.warning(\"Checksum %s did not match actual digest %s\", checksum, digest)\n            return False\n        return True",
    "docstring": "Ensure that the checksum matches."
  },
  {
    "code": "def _create_metadata_cache(cache_location):\n    cache_url = os.getenv('GUTENBERG_FUSEKI_URL')\n    if cache_url:\n        return FusekiMetadataCache(cache_location, cache_url)\n    try:\n        return SleepycatMetadataCache(cache_location)\n    except InvalidCacheException:\n        logging.warning('Unable to create cache based on BSD-DB. '\n                        'Falling back to SQLite backend. '\n                        'Performance may be degraded significantly.')\n    return SqliteMetadataCache(cache_location)",
    "docstring": "Creates a new metadata cache instance appropriate for this platform."
  },
  {
    "code": "def _submit_bundle(cmd_args, app):\n    sac = streamsx.rest.StreamingAnalyticsConnection(service_name=cmd_args.service_name)\n    sas = sac.get_streaming_analytics()\n    sr = sas.submit_job(bundle=app.app, job_config=app.cfg[ctx.ConfigParams.JOB_CONFIG])\n    if 'exception' in sr:\n        rc = 1\n    elif 'status_code' in sr:\n        try:\n            rc = 0 if int(sr['status_code'] == 200) else 1\n        except:\n            rc = 1\n    elif 'id' in sr or 'jobId' in sr:\n        rc = 0\n    sr['return_code'] = rc\n    return sr",
    "docstring": "Submit an existing bundle to the service"
  },
  {
    "code": "def getPeer(self, url):\n        peers = list(models.Peer.select().where(models.Peer.url == url))\n        if len(peers) == 0:\n            raise exceptions.PeerNotFoundException(url)\n        return peers[0]",
    "docstring": "Finds a peer by URL and return the first peer record with that URL."
  },
  {
    "code": "def get_default_ENV(env):\n    global default_ENV\n    try:\n        return env['ENV']\n    except KeyError:\n        if not default_ENV:\n            import SCons.Environment\n            default_ENV = SCons.Environment.Environment()['ENV']\n        return default_ENV",
    "docstring": "A fiddlin' little function that has an 'import SCons.Environment' which\n    can't be moved to the top level without creating an import loop.  Since\n    this import creates a local variable named 'SCons', it blocks access to\n    the global variable, so we move it here to prevent complaints about local\n    variables being used uninitialized."
  },
  {
    "code": "def ring_to_nested(ring_index, nside):\n    nside = np.asarray(nside, dtype=np.intc)\n    return _core.ring_to_nested(ring_index, nside)",
    "docstring": "Convert a HEALPix 'ring' index to a HEALPix 'nested' index\n\n    Parameters\n    ----------\n    ring_index : int or `~numpy.ndarray`\n        Healpix index using the 'ring' ordering\n    nside : int or `~numpy.ndarray`\n        Number of pixels along the side of each of the 12 top-level HEALPix tiles\n\n    Returns\n    -------\n    nested_index : int or `~numpy.ndarray`\n        Healpix index using the 'nested' ordering"
  },
  {
    "code": "def rgb2term(r: int, g: int, b: int) -> str:\n    return hex2term_map[rgb2termhex(r, g, b)]",
    "docstring": "Convert an rgb value to a terminal code."
  },
  {
    "code": "def dvcrss(s1, s2):\n    assert len(s1) is 6 and len(s2) is 6\n    s1 = stypes.toDoubleVector(s1)\n    s2 = stypes.toDoubleVector(s2)\n    sout = stypes.emptyDoubleVector(6)\n    libspice.dvcrss_c(s1, s2, sout)\n    return stypes.cVectorToPython(sout)",
    "docstring": "Compute the cross product of two 3-dimensional vectors\n    and the derivative of this cross product.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvcrss_c.html\n\n    :param s1: Left hand state for cross product and derivative.\n    :type s1: 6-Element Array of floats\n    :param s2: Right hand state for cross product and derivative.\n    :type s2: 6-Element Array of floats\n    :return: State associated with cross product of positions.\n    :rtype: 6-Element Array of floats"
  },
  {
    "code": "def are_equivalent(*args, **kwargs):\n    if len(args) == 1:\n        return True\n    first_item = args[0]\n    for item in args[1:]:\n        if type(item) != type(first_item):\n            return False\n        if isinstance(item, dict):\n            if not are_dicts_equivalent(item, first_item):\n                return False\n        elif hasattr(item, '__iter__') and not isinstance(item, (str, bytes, dict)):\n            if len(item) != len(first_item):\n                return False\n            for value in item:\n                if value not in first_item:\n                    return False\n            for value in first_item:\n                if value not in item:\n                    return False\n        else:\n            if item != first_item:\n                return False\n    return True",
    "docstring": "Indicate if arguments passed to this function are equivalent.\n\n    .. hint::\n\n      This checker operates recursively on the members contained within iterables\n      and :class:`dict <python:dict>` objects.\n\n    .. caution::\n\n      If you only pass one argument to this checker - even if it is an iterable -\n      the checker will *always* return ``True``.\n\n      To evaluate members of an iterable for equivalence, you should instead\n      unpack the iterable into the function like so:\n\n      .. code-block:: python\n\n        obj = [1, 1, 1, 2]\n\n        result = are_equivalent(*obj)\n        # Will return ``False`` by unpacking and evaluating the iterable's members\n\n        result = are_equivalent(obj)\n        # Will always return True\n\n    :param args: One or more values, passed as positional arguments.\n\n    :returns: ``True`` if ``args`` are equivalent, and ``False`` if not.\n    :rtype: :class:`bool <python:bool>`\n\n    :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates\n      keyword parameters passed to the underlying validator"
  },
  {
    "code": "def _validate_slices_form_uniform_grid(slice_datasets):\n    invariant_properties = [\n        'Modality',\n        'SOPClassUID',\n        'SeriesInstanceUID',\n        'Rows',\n        'Columns',\n        'PixelSpacing',\n        'PixelRepresentation',\n        'BitsAllocated',\n        'BitsStored',\n        'HighBit',\n    ]\n    for property_name in invariant_properties:\n        _slice_attribute_equal(slice_datasets, property_name)\n    _validate_image_orientation(slice_datasets[0].ImageOrientationPatient)\n    _slice_ndarray_attribute_almost_equal(slice_datasets, 'ImageOrientationPatient', 1e-5)\n    slice_positions = _slice_positions(slice_datasets)\n    _check_for_missing_slices(slice_positions)",
    "docstring": "Perform various data checks to ensure that the list of slices form a\n    evenly-spaced grid of data.\n    Some of these checks are probably not required if the data follows the\n    DICOM specification, however it seems pertinent to check anyway."
  },
  {
    "code": "def get_state_machine(self):\n        if self.parent:\n            if self.is_root_state:\n                return self.parent\n            else:\n                return self.parent.get_state_machine()\n        return None",
    "docstring": "Get a reference of the state_machine the state belongs to\n\n        :rtype rafcon.core.state_machine.StateMachine\n        :return: respective state machine"
  },
  {
    "code": "def ensure_each_wide_obs_chose_an_available_alternative(obs_id_col,\n                                                        choice_col,\n                                                        availability_vars,\n                                                        wide_data):\n    wide_availability_values = wide_data[list(\n        availability_vars.values())].values\n    unavailable_condition = ((wide_availability_values == 0).sum(axis=1)\n                                                            .astype(bool))\n    problem_obs = []\n    for idx, row in wide_data.loc[unavailable_condition].iterrows():\n        if row.at[availability_vars[row.at[choice_col]]] != 1:\n            problem_obs.append(row.at[obs_id_col])\n    if problem_obs != []:\n        msg = \"The following observations chose unavailable alternatives:\\n{}\"\n        raise ValueError(msg.format(problem_obs))\n    return None",
    "docstring": "Checks whether or not each observation with a restricted choice set chose\n    an alternative that was personally available to him or her. Will raise a\n    helpful ValueError if this is not the case.\n\n    Parameters\n    ----------\n    obs_id_col : str.\n        Denotes the column in `wide_data` that contains the observation ID\n        values for each row.\n    choice_col : str.\n        Denotes the column in `wide_data` that contains a one if the\n        alternative pertaining to the given row was the observed outcome for\n        the observation pertaining to the given row and a zero otherwise.\n    availability_vars : dict.\n        There should be one key value pair for each alternative that is\n        observed in the dataset. Each key should be the alternative id for the\n        alternative, and the value should be the column heading in `wide_data`\n        that denotes (using ones and zeros) whether an alternative is\n        available/unavailable, respectively, for a given observation.\n        Alternative id's, i.e. the keys, must be integers.\n    wide_data : pandas dataframe.\n        Contains one row for each observation. Should have the specified\n        `[obs_id_col, choice_col] + availability_vars.values()` columns.\n\n    Returns\n    -------\n    None"
  },
  {
    "code": "def header(msg):\n    width = len(msg) + 4\n    s = []\n    s.append('-' * width)\n    s.append(\"| %s |\" % msg)\n    s.append('-' * width)\n    return '\\n'.join(s)",
    "docstring": "Wrap `msg` in bars to create a header effect"
  },
  {
    "code": "def asynchronous(function, event):\n    thread = Thread(target=synchronous, args=(function, event))\n    thread.daemon = True\n    thread.start()",
    "docstring": "Runs the function asynchronously taking care of exceptions."
  },
  {
    "code": "def after_import(self, dataset, result, using_transactions, dry_run, **kwargs):\n        if not dry_run and any(r.import_type == RowResult.IMPORT_TYPE_NEW for r in result.rows):\n            connection = connections[DEFAULT_DB_ALIAS]\n            sequence_sql = connection.ops.sequence_reset_sql(no_style(), [self._meta.model])\n            if sequence_sql:\n                cursor = connection.cursor()\n                try:\n                    for line in sequence_sql:\n                        cursor.execute(line)\n                finally:\n                    cursor.close()",
    "docstring": "Reset the SQL sequences after new objects are imported"
  },
  {
    "code": "def newMail(self, data, message):\n        r = self.doQuery('mail', method='POST', postParameters={'response_id': str(data), 'message': str(message)})\n        if r.status_code == 200:\n            data = r.json()\n            return data['result'] == 'Ok'\n        return False",
    "docstring": "Send a mail to a plugit server"
  },
  {
    "code": "def __get_num_preds(self, num_iteration, nrow, predict_type):\n        if nrow > MAX_INT32:\n            raise LightGBMError('LightGBM cannot perform prediction for data'\n                                'with number of rows greater than MAX_INT32 (%d).\\n'\n                                'You can split your data into chunks'\n                                'and then concatenate predictions for them' % MAX_INT32)\n        n_preds = ctypes.c_int64(0)\n        _safe_call(_LIB.LGBM_BoosterCalcNumPredict(\n            self.handle,\n            ctypes.c_int(nrow),\n            ctypes.c_int(predict_type),\n            ctypes.c_int(num_iteration),\n            ctypes.byref(n_preds)))\n        return n_preds.value",
    "docstring": "Get size of prediction result."
  },
  {
    "code": "def rmgen(self, idx):\n        stagens = []\n        for device, stagen in zip(self.devman.devices, self.call.stagen):\n            if stagen:\n                stagens.append(device)\n        for gen in idx:\n            for stagen in stagens:\n                if gen in self.__dict__[stagen].uid.keys():\n                    self.__dict__[stagen].disable_gen(gen)",
    "docstring": "Remove the static generators if their dynamic models exist\n\n        Parameters\n        ----------\n        idx : list\n            A list of static generator idx\n        Returns\n        -------\n        None"
  },
  {
    "code": "def isObjectClassified(self, objectName, minOverlap=None, maxL2Size=None):\n    L2Representation = self.getL2Representations()\n    objectRepresentation = self.objectL2Representations[objectName]\n    sdrSize = self.config[\"L2Params\"][\"sdrSize\"]\n    if minOverlap is None:\n      minOverlap = sdrSize / 2\n    if maxL2Size is None:\n      maxL2Size = 1.5*sdrSize\n    numCorrectClassifications = 0\n    for col in xrange(self.numColumns):\n      overlapWithObject = len(objectRepresentation[col] & L2Representation[col])\n      if ( overlapWithObject >= minOverlap  and\n           len(L2Representation[col]) <= maxL2Size ):\n        numCorrectClassifications += 1\n    return numCorrectClassifications == self.numColumns",
    "docstring": "Return True if objectName is currently unambiguously classified by every L2\n    column. Classification is correct and unambiguous if the current L2 overlap\n    with the true object is greater than minOverlap and if the size of the L2\n    representation is no more than maxL2Size\n\n    :param minOverlap: min overlap to consider the object as recognized.\n                       Defaults to half of the SDR size\n\n    :param maxL2Size: max size for the L2 representation\n                       Defaults to 1.5 * SDR size\n\n    :return: True/False"
  },
  {
    "code": "def add_rel(self, source_id, target_id, rel):\n        if (source_id, target_id) not in self.rel_cache:\n            self.workbench.add_rel(source_id, target_id, rel)\n            self.rel_cache.add((source_id, target_id))",
    "docstring": "Cache aware add_rel"
  },
  {
    "code": "def run(self):\n        target = getattr(self, '_Thread__target', getattr(self, '_target', None))\n        args = getattr(self, '_Thread__args', getattr(self, '_args', None))\n        kwargs = getattr(self, '_Thread__kwargs', getattr(self, '_kwargs', None))\n        if target is not None:\n            self._return = target(*args, **kwargs)\n        return None",
    "docstring": "Runs the thread.\n\n        Args:\n          self (ThreadReturn): the ``ThreadReturn`` instance\n\n        Returns:\n          ``None``"
  },
  {
    "code": "def toimages(self, chunk_size='auto'):\n        from thunder.images.images import Images\n        if chunk_size is 'auto':\n            chunk_size = str(max([int(1e5/prod(self.baseshape)), 1]))\n        n = len(self.shape) - 1\n        if self.mode == 'spark':\n            return Images(self.values.swap(tuple(range(n)), (0,), size=chunk_size))\n        if self.mode == 'local':\n            return Images(self.values.transpose((n,) + tuple(range(0, n))))",
    "docstring": "Converts to images data.\n\n        This method is equivalent to series.toblocks(size).toimages().\n\n        Parameters\n        ----------\n        chunk_size : str or tuple, size of series chunk used during conversion, default = 'auto'\n            String interpreted as memory size (in kilobytes, e.g. '64').\n            The exception is the string 'auto', which will choose a chunk size to make the\n            resulting blocks ~100 MB in size. Int interpreted as 'number of elements'.\n            Only valid in spark mode."
  },
  {
    "code": "def _get_prefix_length(number1, number2, bits):\n    for i in range(bits):\n        if number1 >> i == number2 >> i:\n            return bits - i\n    return 0",
    "docstring": "Get the number of leading bits that are same for two numbers.\n\n    Args:\n        number1: an integer.\n        number2: another integer.\n        bits: the maximum number of bits to compare.\n\n    Returns:\n        The number of leading bits that are the same for two numbers."
  },
  {
    "code": "def basic_lstm(inputs, state, num_units, name=None):\n  input_shape = common_layers.shape_list(inputs)\n  cell = tf.nn.rnn_cell.BasicLSTMCell(\n      num_units, name=name, reuse=tf.AUTO_REUSE)\n  if state is None:\n    state = cell.zero_state(input_shape[0], tf.float32)\n  outputs, new_state = cell(inputs, state)\n  return outputs, new_state",
    "docstring": "Basic LSTM."
  },
  {
    "code": "def make_subdirs(self):\n        subpath = self.full_path[len(self.context.root):]\n        log.debug(\"make_subdirs: subpath is %s\", subpath)\n        dirs = subpath.split(os.sep)[:-1]\n        log.debug(\"dirs is %s\", dirs)\n        current = self.context.root\n        for dir in dirs:\n            if dir:\n                current = os.path.join(current, dir)\n                if os.path.isdir(current):\n                    log.debug(\"%s is already an existing directory\", current)\n                else:\n                    os.mkdir(current, 0o700)",
    "docstring": "The purpose of this method is to, if necessary, create all of the\n        subdirectories leading up to the file to the written."
  },
  {
    "code": "def fetch(self):\n        since = time.mktime(self.options.since.datetime.timetuple())\n        until = time.mktime(self.options.until.datetime.timetuple())\n        log.info(\"Searching for links saved by {0}\".format(self.user))\n        self.stats = self.parent.bitly.user_link_history(created_after=since,\n                                                         created_before=until)",
    "docstring": "Bit.ly API expect unix timestamps"
  },
  {
    "code": "def _single_feature_logliks_one_step(self, feature, models):\n        x_non_na = feature[~feature.isnull()]\n        if x_non_na.empty:\n            return pd.DataFrame()\n        else:\n            dfs = []\n            for name, model in models.items():\n                df = model.single_feature_logliks(feature)\n                df['Modality'] = name\n                dfs.append(df)\n            return pd.concat(dfs, ignore_index=True)",
    "docstring": "Get log-likelihood of models at each parameterization for given data\n\n        Parameters\n        ----------\n        feature : pandas.Series\n            Percent-based values of a single feature. May contain NAs, but only\n            non-NA values are used.\n\n        Returns\n        -------\n        logliks : pandas.DataFrame"
  },
  {
    "code": "def convert_block_dicts_to_string(self, block_1st2nd, block_1st, block_2nd, block_3rd):\n        out = \"\"\n        if self.codon_positions in ['ALL', '1st-2nd']:\n            for gene_code, seqs in block_1st2nd.items():\n                out += '>{0}_1st-2nd\\n----\\n'.format(gene_code)\n                for seq in seqs:\n                    out += seq\n        elif self.codon_positions == '1st':\n            for gene_code, seqs in block_1st.items():\n                out += '>{0}_1st\\n----\\n'.format(gene_code)\n                for seq in seqs:\n                    out += seq\n        elif self.codon_positions == '2nd':\n            for gene_code, seqs in block_2nd.items():\n                out += '>{0}_2nd\\n----\\n'.format(gene_code)\n                for seq in seqs:\n                    out += seq\n        if self.codon_positions in ['ALL', '3rd']:\n            for gene_code, seqs in block_3rd.items():\n                out += '\\n>{0}_3rd\\n----\\n'.format(gene_code)\n                for seq in seqs:\n                    out += seq\n        return out",
    "docstring": "Takes into account whether we need to output all codon positions."
  },
  {
    "code": "def status(self, message, rofi_args=None, **kwargs):\n        rofi_args = rofi_args or []\n        args = ['rofi', '-e', message]\n        args.extend(self._common_args(allow_fullscreen=False, **kwargs))\n        args.extend(rofi_args)\n        self._run_nonblocking(args)",
    "docstring": "Show a status message.\n\n        This method is non-blocking, and intended to give a status update to\n        the user while something is happening in the background.\n\n        To close the window, either call the close() method or use any of the\n        display methods to replace it with a different window.\n\n        Fullscreen mode is not supported for status messages and if specified\n        will be ignored.\n\n        Parameters\n        ----------\n        message: string\n            Progress message to show."
  },
  {
    "code": "def json_decoder(content, *args, **kwargs):\n    if not content:\n        return None\n    json_value = content.decode()\n    return json.loads(json_value)",
    "docstring": "Json decoder parser to be used by service_client"
  },
  {
    "code": "def create_process_worker(self, cmd_list, environ=None):\n        worker = ProcessWorker(cmd_list, environ=environ)\n        self._create_worker(worker)\n        return worker",
    "docstring": "Create a new process worker instance."
  },
  {
    "code": "def normalize(name):\n    ret = name.replace(':', '')\n    ret = ret.replace('%', '')\n    ret = ret.replace(' ', '_')\n    return ret",
    "docstring": "Normalize name for the Statsd convention"
  },
  {
    "code": "def flip_alleles(genotypes):\n    warnings.warn(\"deprecated: use 'Genotypes.flip_coded'\", DeprecationWarning)\n    genotypes.reference, genotypes.coded = (genotypes.coded,\n                                            genotypes.reference)\n    genotypes.genotypes = 2 - genotypes.genotypes\n    return genotypes",
    "docstring": "Flip the alleles of an Genotypes instance."
  },
  {
    "code": "def s_demand(self, bus):\n        Svl = array([complex(g.p, g.q) for g in self.generators if\n                    (g.bus == bus) and g.is_load], dtype=complex64)\n        Sd = complex(bus.p_demand, bus.q_demand)\n        return -sum(Svl) + Sd",
    "docstring": "Returns the total complex power demand."
  },
  {
    "code": "def validate(self, signature, timestamp, nonce):\n        if not self.token:\n            raise RuntimeError('WEIXIN_TOKEN is missing')\n        if self.expires_in:\n            try:\n                timestamp = int(timestamp)\n            except (ValueError, TypeError):\n                return False\n            delta = time.time() - timestamp\n            if delta < 0:\n                return False\n            if delta > self.expires_in:\n                return False\n        values = [self.token, str(timestamp), str(nonce)]\n        s = ''.join(sorted(values))\n        hsh = hashlib.sha1(s.encode('utf-8')).hexdigest()\n        return signature == hsh",
    "docstring": "Validate request signature.\n\n        :param signature: A string signature parameter sent by weixin.\n        :param timestamp: A int timestamp parameter sent by weixin.\n        :param nonce: A int nonce parameter sent by weixin."
  },
  {
    "code": "def op_decanonicalize(op_name, canonical_op):\n    global DECANONICALIZE_METHODS\n    if op_name not in DECANONICALIZE_METHODS:\n        return canonical_op\n    else:\n        return DECANONICALIZE_METHODS[op_name](canonical_op)",
    "docstring": "Get the current representation of a parsed operation's data, given the canonical representation\n    Meant for backwards-compatibility"
  },
  {
    "code": "def get_data(histogram: HistogramBase, density: bool = False, cumulative: bool = False, flatten: bool = False) -> np.ndarray:\n    if density:\n        if cumulative:\n            data = (histogram / histogram.total).cumulative_frequencies\n        else:\n            data = histogram.densities\n    else:\n        if cumulative:\n            data = histogram.cumulative_frequencies\n        else:\n            data = histogram.frequencies\n    if flatten:\n        data = data.flatten()\n    return data",
    "docstring": "Get histogram data based on plotting parameters.\n\n    Parameters\n    ----------\n    density : Whether to divide bin contents by bin size\n    cumulative : Whether to return cumulative sums instead of individual\n    flatten : Whether to flatten multidimensional bins"
  },
  {
    "code": "def install(path, name=None):\n    if name is None:\n        name = os.path.splitext(os.path.basename(path))[0]\n    callermod = inspect.getmodule(inspect.stack()[1][0])\n    name = '%s.%s' % (callermod.__name__, name)\n    if name in sys.modules:\n        return sys.modules[name]\n    if not os.path.isabs(path):\n        callerfile = callermod.__file__\n        path = os.path.normpath(\n            os.path.join(os.path.dirname(callerfile), path)\n        )\n    sys.modules[name] = mod = load(path, name=name)\n    return mod",
    "docstring": "Compiles a Thrift file and installs it as a submodule of the caller.\n\n    Given a tree organized like so::\n\n        foo/\n            __init__.py\n            bar.py\n            my_service.thrift\n\n    You would do,\n\n    .. code-block:: python\n\n        my_service = thriftrw.install('my_service.thrift')\n\n    To install ``my_service`` as a submodule of the module from which you made\n    the call. If the call was made in ``foo/bar.py``, the compiled\n    Thrift file will be installed as ``foo.bar.my_service``. If the call was\n    made in ``foo/__init__.py``, the compiled Thrift file will be installed as\n    ``foo.my_service``. This allows other modules to import ``from`` the\n    compiled module like so,\n\n    .. code-block:: python\n\n        from foo.my_service import MyService\n\n    .. versionadded:: 0.2\n\n    :param path:\n        Path of the Thrift file. This may be an absolute path, or a path\n        relative to the Python module making the call.\n    :param str name:\n        Name of the submodule. Defaults to the basename of the Thrift file.\n    :returns:\n        The compiled module"
  },
  {
    "code": "def _render_relationships(self, resource):\n        relationships = {}\n        related_models = resource.__mapper__.relationships.keys()\n        primary_key_val = getattr(resource, self.primary_key)\n        if self.dasherize:\n            mapped_relationships = {\n                x: dasherize(underscore(x)) for x in related_models}\n        else:\n            mapped_relationships = {x: x for x in related_models}\n        for model in related_models:\n            relationships[mapped_relationships[model]] = {\n                'links': {\n                    'self': '/{}/{}/relationships/{}'.format(\n                        resource.__tablename__,\n                        primary_key_val,\n                        mapped_relationships[model]),\n                    'related': '/{}/{}/{}'.format(\n                        resource.__tablename__,\n                        primary_key_val,\n                        mapped_relationships[model])\n                }\n            }\n        return relationships",
    "docstring": "Render the resource's relationships."
  },
  {
    "code": "def get(self, key, lang=None):\n        if lang is not None:\n            for o in self.graph.objects(self.asNode(), key):\n                if o.language == lang:\n                    yield o\n        else:\n            for o in self.graph.objects(self.asNode(), key):\n                yield o",
    "docstring": "Returns triple related to this node. Can filter on lang\n\n        :param key: Predicate of the triple\n        :param lang: Language of the triple if applicable\n        :rtype: Literal or BNode or URIRef"
  },
  {
    "code": "def _make_scatter_logfile_name(cls, key, linkname, job_config):\n        logfile = job_config.get('logfile', \"%s_%s_%s.log\" %\n                                 (cls.default_prefix_logfile, linkname, key))\n        job_config['logfile'] = logfile",
    "docstring": "Hook to inster the name of a logfile into the input config"
  },
  {
    "code": "def maybe_convert_platform_interval(values):\n    if isinstance(values, (list, tuple)) and len(values) == 0:\n        return np.array([], dtype=np.int64)\n    elif is_categorical_dtype(values):\n        values = np.asarray(values)\n    return maybe_convert_platform(values)",
    "docstring": "Try to do platform conversion, with special casing for IntervalArray.\n    Wrapper around maybe_convert_platform that alters the default return\n    dtype in certain cases to be compatible with IntervalArray.  For example,\n    empty lists return with integer dtype instead of object dtype, which is\n    prohibited for IntervalArray.\n\n    Parameters\n    ----------\n    values : array-like\n\n    Returns\n    -------\n    array"
  },
  {
    "code": "def config_default(option, default=None, type=None, section=cli.name):\n    def f(option=option, default=default, type=type, section=section):\n        config = read_config()\n        if type is None and default is not None:\n            type = builtins.type(default)\n        get_option = option_getter(type)\n        try:\n            return get_option(config, section, option)\n        except (NoOptionError, NoSectionError):\n            return default\n    return f",
    "docstring": "Guesses a default value of a CLI option from the configuration.\n\n    ::\n\n       @click.option('--locale', default=config_default('locale'))"
  },
  {
    "code": "def register_pubkey(self):\n        p = pkcs_os2ip(self.dh_p)\n        g = pkcs_os2ip(self.dh_g)\n        pn = dh.DHParameterNumbers(p, g)\n        y = pkcs_os2ip(self.dh_Ys)\n        public_numbers = dh.DHPublicNumbers(y, pn)\n        s = self.tls_session\n        s.server_kx_pubkey = public_numbers.public_key(default_backend())\n        if not s.client_kx_ffdh_params:\n            s.client_kx_ffdh_params = pn.parameters(default_backend())",
    "docstring": "XXX Check that the pubkey received is in the group."
  },
  {
    "code": "def name(self):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('SL record not yet initialized!')\n        outlist = []\n        continued = False\n        for comp in self.symlink_components:\n            name = comp.name()\n            if name == b'/':\n                outlist = []\n                continued = False\n                name = b''\n            if not continued:\n                outlist.append(name)\n            else:\n                outlist[-1] += name\n            continued = comp.is_continued()\n        return b'/'.join(outlist)",
    "docstring": "Generate a string that contains all components of the symlink.\n\n        Parameters:\n         None\n        Returns:\n         String containing all components of the symlink."
  },
  {
    "code": "def get_default_location(self):\n        res = []\n        for location in self.distdefault:\n            res.extend(self.get_location(location))\n        return res",
    "docstring": "Return the default location."
  },
  {
    "code": "def new(self, **dict):\n        if not self._item_new_path:\n            raise AttributeError('new is not available for %s' % self._item_name)\n        for tag in self._object._remap_to_id:\n            self._object._remap_tag_to_tag_id(tag, dict)\n        target = self._item_new_path\n        payload = json.dumps({self._item_type:dict})\n        json_data = self._redmine.post(target, payload)\n        data = self._redmine.unwrap_json(self._item_type, json_data)\n        data['_source_path'] = target\n        return self._objectify(data=data)",
    "docstring": "Create a new item with the provided dict information.  Returns the new item."
  },
  {
    "code": "def get_week_start_end_day():\n    t = date.today()\n    wd = t.weekday()\n    return (t - timedelta(wd), t + timedelta(6 - wd))",
    "docstring": "Get the week start date and end date"
  },
  {
    "code": "def __recieve_raw_data(self, size):\n        data = []\n        if self.verbose: print (\"expecting {} bytes raw data\".format(size))\n        while size > 0:\n            data_recv = self.__sock.recv(size)\n            recieved = len(data_recv)\n            if self.verbose: print (\"partial recv {}\".format(recieved))\n            if recieved < 100 and self.verbose: print (\"   recv {}\".format(codecs.encode(data_recv, 'hex')))\n            data.append(data_recv)\n            size -= recieved\n            if self.verbose: print (\"still need {}\".format(size))\n        return b''.join(data)",
    "docstring": "partial data ?"
  },
  {
    "code": "def d(msg, *args, **kwargs):\n    return logging.log(DEBUG, msg, *args, **kwargs)",
    "docstring": "log a message at debug level;"
  },
  {
    "code": "def remove_group_roles(request, group, domain=None, project=None):\n    client = keystoneclient(request, admin=True)\n    roles = client.roles.list(group=group, domain=domain, project=project)\n    for role in roles:\n        remove_group_role(request, role=role.id, group=group,\n                          domain=domain, project=project)",
    "docstring": "Removes all roles from a group on a domain or project."
  },
  {
    "code": "def _as_array(self, fmt):\n        assert self.dimensions, \\\n            '{}: cannot get value as {} array!'.format(self.name, fmt)\n        elems = array.array(fmt)\n        elems.fromstring(self.bytes)\n        return np.array(elems).reshape(self.dimensions)",
    "docstring": "Unpack the raw bytes of this param using the given data format."
  },
  {
    "code": "def _gc_rule_from_pb(gc_rule_pb):\n    rule_name = gc_rule_pb.WhichOneof(\"rule\")\n    if rule_name is None:\n        return None\n    if rule_name == \"max_num_versions\":\n        return MaxVersionsGCRule(gc_rule_pb.max_num_versions)\n    elif rule_name == \"max_age\":\n        max_age = _helpers._duration_pb_to_timedelta(gc_rule_pb.max_age)\n        return MaxAgeGCRule(max_age)\n    elif rule_name == \"union\":\n        return GCRuleUnion([_gc_rule_from_pb(rule) for rule in gc_rule_pb.union.rules])\n    elif rule_name == \"intersection\":\n        rules = [_gc_rule_from_pb(rule) for rule in gc_rule_pb.intersection.rules]\n        return GCRuleIntersection(rules)\n    else:\n        raise ValueError(\"Unexpected rule name\", rule_name)",
    "docstring": "Convert a protobuf GC rule to a native object.\n\n    :type gc_rule_pb: :class:`.table_v2_pb2.GcRule`\n    :param gc_rule_pb: The GC rule to convert.\n\n    :rtype: :class:`GarbageCollectionRule` or :data:`NoneType <types.NoneType>`\n    :returns: An instance of one of the native rules defined\n              in :module:`column_family` or :data:`None` if no values were\n              set on the protobuf passed in.\n    :raises: :class:`ValueError <exceptions.ValueError>` if the rule name\n             is unexpected."
  },
  {
    "code": "def add_transaction(self, transaction):\n        for item in transaction:\n            if item not in self.__transaction_index_map:\n                self.__items.append(item)\n                self.__transaction_index_map[item] = set()\n            self.__transaction_index_map[item].add(self.__num_transaction)\n        self.__num_transaction += 1",
    "docstring": "Add a transaction.\n\n        Arguments:\n            transaction -- A transaction as an iterable object (eg. ['A', 'B'])."
  },
  {
    "code": "def _sorted_keys(self, keys, startkey, reverse=False):\n        tuple_key = lambda t: t[::-1]\n        if reverse:\n            tuple_cmp = lambda t: t[::-1] > startkey[::-1]\n        else:\n            tuple_cmp = lambda t: t[::-1] < startkey[::-1]\n        searchkeys = sorted(keys, key=tuple_key, reverse=reverse)\n        searchpos = sum(1 for _ in ifilter(tuple_cmp, searchkeys))\n        searchkeys = searchkeys[searchpos:] + searchkeys[:searchpos]\n        for key in searchkeys:\n            yield key",
    "docstring": "Generator that yields sorted keys starting with startkey\n\n        Parameters\n        ----------\n\n        keys: Iterable of tuple/list\n        \\tKey sequence that is sorted\n        startkey: Tuple/list\n        \\tFirst key to be yielded\n        reverse: Bool\n        \\tSort direction reversed if True"
  },
  {
    "code": "def list_components(self, dependency_order=True):\n        if dependency_order:\n            return list(itertools.chain.from_iterable([sorted(list(batch)) for batch in\n                                                       foundations.common.dependency_resolver(\n                                                           dict((key, value.require) for (key, value) in self))]))\n        else:\n            return [key for (key, value) in self]",
    "docstring": "Lists the Components by dependency resolving.\n\n        Usage::\n\n            >>> manager = Manager((\"./manager/tests/tests_manager/resources/components/core\",))\n            >>> manager.register_components()\n            True\n            >>> manager.list_components()\n            [u'core.tests_component_a', u'core.tests_component_b']\n\n        :param dependency_order: Components are returned by dependency order.\n        :type dependency_order: bool"
  },
  {
    "code": "def unbind(self, dependency, svc, svc_ref):\n        with self._lock:\n            self.check_lifecycle()\n            self.__unset_binding(dependency, svc, svc_ref)\n            if self.update_bindings():\n                self.check_lifecycle()",
    "docstring": "Called by a dependency manager to remove an injected service and to\n        update the component life cycle."
  },
  {
    "code": "def address(self, ip, **kwargs):\n        indicator_obj = Address(ip, **kwargs)\n        return self._indicator(indicator_obj)",
    "docstring": "Add Address data to Batch object.\n\n        Args:\n            ip (str): The value for this Indicator.\n            confidence (str, kwargs): The threat confidence for this Indicator.\n            date_added (str, kwargs): The date timestamp the Indicator was created.\n            last_modified (str, kwargs): The date timestamp the Indicator was last modified.\n            rating (str, kwargs): The threat rating for this Indicator.\n            xid (str, kwargs): The external id for this Indicator.\n\n        Returns:\n            obj: An instance of Address."
  },
  {
    "code": "def job_detail(job_id=None):\n    jobs = [job for job in get_jobs() if str(job['job_id']) == job_id]\n    if not jobs:\n        abort(404)\n    return render_template('job_detail.html', job=jobs[0], hosts=dagobah.get_hosts())",
    "docstring": "Show a detailed description of a Job's status."
  },
  {
    "code": "def cast(self, mapping):\n        for c, p in mapping.items():\n            self.doc.note_citation(c)\n            self.doc.note_explicit_target(c, c)\n            c.persona = p\n            self.log.debug(\"{0} to be played by {1}\".format(\n                c[\"names\"][0].capitalize(), p)\n            )\n        return self",
    "docstring": "Allocate the scene script a cast of personae for each of its entities.\n\n        :param mapping: A dictionary of {Entity, Persona}\n        :return: The SceneScript object."
  },
  {
    "code": "def with_arg_count(self, count):\n        exp = self._get_current_call()\n        exp.expected_arg_count = count\n        return self",
    "docstring": "Set the last call to expect an exact argument count.\n\n        I.E.::\n\n            >>> auth = Fake('auth').provides('login').with_arg_count(2)\n            >>> auth.login('joe_user') # forgot password\n            Traceback (most recent call last):\n            ...\n            AssertionError: fake:auth.login() was called with 1 arg(s) but expected 2"
  },
  {
    "code": "def memwarp_multi(src_ds_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, dst_ndv=0):\n    return warp_multi(src_ds_list, res, extent, t_srs, r, warptype=memwarp, verbose=verbose, dst_ndv=dst_ndv)",
    "docstring": "Helper function for memwarp of multiple input GDAL Datasets"
  },
  {
    "code": "def compare(self, item, article_candidates):\n        result = ArticleCandidate()\n        result.title = self.comparer_title.extract(item, article_candidates)\n        result.description = self.comparer_desciption.extract(item, article_candidates)\n        result.text = self.comparer_text.extract(item, article_candidates)\n        result.topimage = self.comparer_topimage.extract(item, article_candidates)\n        result.author = self.comparer_author.extract(item, article_candidates)\n        result.publish_date = self.comparer_date.extract(item, article_candidates)\n        result.language = self.comparer_language.extract(item, article_candidates)\n        return result",
    "docstring": "Compares the article candidates using the different submodules and saves the best results in\n        new ArticleCandidate object\n\n        :param item: The NewscrawlerItem related to the ArticleCandidates\n        :param article_candidates: The list of ArticleCandidate-Objects which have been extracted\n        :return: An ArticleCandidate-object containing the best results"
  },
  {
    "code": "def encloses_annulus(x_min, x_max, y_min, y_max, nx, ny, r_in, r_out):\n    gout = circular_overlap_grid(x_min, x_max, y_min, y_max, nx, ny, r_out, 1, 1)\n    gin = circular_overlap_grid(x_min, x_max, y_min, y_max, nx, ny, r_in, 1, 1)\n    return gout - gin",
    "docstring": "Encloses function backported from old photutils"
  },
  {
    "code": "def _parse(args):\n    ordered = []\n    opt_full = dict()\n    opt_abbrev = dict()\n    args = args + ['']\n    i = 0\n    while i < len(args) - 1:\n        arg = args[i]\n        arg_next = args[i+1]\n        if arg.startswith('--'):\n            if arg_next.startswith('-'):\n                raise ValueError('{} lacks value'.format(arg))\n            else:\n                opt_full[arg[2:]] = arg_next\n                i += 2\n        elif arg.startswith('-'):\n            if arg_next.startswith('-'):\n                raise ValueError('{} lacks value'.format(arg))\n            else:\n                opt_abbrev[arg[1:]] = arg_next\n                i += 2\n        else:\n            ordered.append(arg)\n            i += 1\n    return ordered, opt_full, opt_abbrev",
    "docstring": "Parse passed arguments from shell."
  },
  {
    "code": "def _apply_hardware_version(hardware_version, config_spec, operation='add'):\n    log.trace('Configuring virtual machine hardware '\n              'version version=%s', hardware_version)\n    if operation == 'edit':\n        log.trace('Scheduling hardware version '\n                  'upgrade to %s', hardware_version)\n        scheduled_hardware_upgrade = vim.vm.ScheduledHardwareUpgradeInfo()\n        scheduled_hardware_upgrade.upgradePolicy = 'always'\n        scheduled_hardware_upgrade.versionKey = hardware_version\n        config_spec.scheduledHardwareUpgradeInfo = scheduled_hardware_upgrade\n    elif operation == 'add':\n        config_spec.version = str(hardware_version)",
    "docstring": "Specifies vm container version or schedules upgrade,\n    returns True on change and False if nothing have been changed.\n\n    hardware_version\n        Hardware version string eg. vmx-08\n\n    config_spec\n        Configuration spec object\n\n    operation\n        Defines the operation which should be used,\n        the possibles values: 'add' and 'edit', the default value is 'add'"
  },
  {
    "code": "def delete_all_but_self(self):\n        prefix = self.settings.alias\n        name = self.settings.index\n        if prefix == name:\n            Log.note(\"{{index_name}} will not be deleted\",  index_name= prefix)\n        for a in self.cluster.get_aliases():\n            if re.match(re.escape(prefix) + \"\\\\d{8}_\\\\d{6}\", a.index) and a.index != name:\n                self.cluster.delete_index(a.index)",
    "docstring": "DELETE ALL INDEXES WITH GIVEN PREFIX, EXCEPT name"
  },
  {
    "code": "def hook(module):\n    if \"INSTANA_DEV\" in os.environ:\n        print(\"==============================================================\")\n        print(\"Instana: Running flask hook\")\n        print(\"==============================================================\")\n    wrapt.wrap_function_wrapper('flask', 'Flask.__init__', wrapper)",
    "docstring": "Hook method to install the Instana middleware into Flask"
  },
  {
    "code": "def union(self, other):\n        if self._jrdd_deserializer == other._jrdd_deserializer:\n            rdd = RDD(self._jrdd.union(other._jrdd), self.ctx,\n                      self._jrdd_deserializer)\n        else:\n            self_copy = self._reserialize()\n            other_copy = other._reserialize()\n            rdd = RDD(self_copy._jrdd.union(other_copy._jrdd), self.ctx,\n                      self.ctx.serializer)\n        if (self.partitioner == other.partitioner and\n                self.getNumPartitions() == rdd.getNumPartitions()):\n            rdd.partitioner = self.partitioner\n        return rdd",
    "docstring": "Return the union of this RDD and another one.\n\n        >>> rdd = sc.parallelize([1, 1, 2, 3])\n        >>> rdd.union(rdd).collect()\n        [1, 1, 2, 3, 1, 1, 2, 3]"
  },
  {
    "code": "def text(self):\n        try:\n            return self._text\n        except AttributeError:\n            if IS_PYTHON_3:\n                encoding = self._response.headers.get_content_charset(\"utf-8\")\n            else:\n                encoding = self._response.headers.getparam(\"charset\")\n            self._text = self._response.read().decode(encoding or \"utf-8\")\n        return self._text",
    "docstring": "Get the raw text for the response"
  },
  {
    "code": "def reset(self):\n        self._reset_ptr[0] = True\n        self._commands.clear()\n        for _ in range(self._pre_start_steps + 1):\n            self.tick()\n        return self._default_state_fn()",
    "docstring": "Resets the environment, and returns the state.\n        If it is a single agent environment, it returns that state for that agent. Otherwise, it returns a dict from\n        agent name to state.\n\n        Returns:\n            tuple or dict: For single agent environment, returns the same as `step`.\n                For multi-agent environment, returns the same as `tick`."
  },
  {
    "code": "def SafeLoadKextManager(self, fn_table):\n    dll = None\n    try:\n      dll = SetCTypesForLibrary('IOKit', fn_table)\n    except AttributeError as ae:\n      if 'KextManagerUnloadKextWithIdentifier' in str(ae):\n        logging.debug('Using legacy kextunload')\n        dll = self.SafeLoadKextManager(\n            FilterFnTable(fn_table, 'KextManagerUnloadKextWithIdentifier'))\n        dll.KextManagerUnloadKextWithIdentifier = self.LegacyKextunload\n      elif 'KextManagerLoadKextWithURL' in str(ae):\n        logging.debug('Using legacy kextload')\n        dll = self.SafeLoadKextManager(\n            FilterFnTable(fn_table, 'KextManagerLoadKextWithURL'))\n        dll.KextManagerLoadKextWithURL = self.LegacyKextload\n      else:\n        raise OSError('Can\\'t resolve KextManager symbols:{0}'.format(str(ae)))\n    return dll",
    "docstring": "Load the kextmanager, replacing unavailable symbols."
  },
  {
    "code": "def setdefault(self, key, value):\n        try:\n            super(FlaskConfigStorage, self).setdefault(key, value)\n        except RuntimeError:\n            self._defaults.__setitem__(key, value)",
    "docstring": "We may not always be connected to an app, but we still need\n        to provide a way to the base environment to set it's defaults."
  },
  {
    "code": "def get_all(self, security):\r\n        url = 'http://www.google.com/finance?q=%s' % security\r\n        page = self._request(url)\r\n        soup = BeautifulSoup(page)\r\n        snapData = soup.find(\"table\", {\"class\": \"snap-data\"})\r\n        if snapData is None:\r\n            raise UfException(Errors.STOCK_SYMBOL_ERROR, \"Can find data for stock %s, security error?\" % security)\r\n        data = {}\r\n        for row in snapData.findAll('tr'):\r\n            keyTd, valTd = row.findAll('td')\r\n            data[keyTd.getText()] = valTd.getText()\r\n        return data",
    "docstring": "Get all available quote data for the given ticker security.\r\n        Returns a dictionary."
  },
  {
    "code": "def guest_delete(self, userid):\n        userid = userid.upper()\n        if not self._vmops.check_guests_exist_in_db(userid, raise_exc=False):\n            if zvmutils.check_userid_exist(userid):\n                LOG.error(\"Guest '%s' does not exist in guests database\" %\n                          userid)\n                raise exception.SDKObjectNotExistError(\n                    obj_desc=(\"Guest '%s'\" % userid), modID='guest')\n            else:\n                LOG.debug(\"The guest %s does not exist.\" % userid)\n                return\n        action = \"delete guest '%s'\" % userid\n        with zvmutils.log_and_reraise_sdkbase_error(action):\n            return self._vmops.delete_vm(userid)",
    "docstring": "Delete guest.\n\n        :param userid: the user id of the vm"
  },
  {
    "code": "def install(self):\n        try:\n            if self.args.server is not None:\n                server = ServerLists(self.server_type)\n                DynamicImporter(\n                    'ezhost',\n                    server.name,\n                    args=self.args,\n                    configure=self.configure\n                )\n            else:\n                ServerCommand(self.args)\n        except Exception as e:\n            raise e",
    "docstring": "install the server"
  },
  {
    "code": "def validate_labels(known_classes, passed_labels, argument_name):\n    known_classes = np.array(known_classes)\n    passed_labels = np.array(passed_labels)\n    unique_labels, unique_indexes = np.unique(passed_labels, return_index=True)\n    if len(passed_labels) != len(unique_labels):\n        indexes = np.arange(0, len(passed_labels))\n        duplicate_indexes = indexes[~np.in1d(indexes, unique_indexes)]\n        duplicate_labels = [str(x) for x in passed_labels[duplicate_indexes]]\n        msg = \"The following duplicate labels were passed into {0}: {1}\" \\\n                .format(argument_name, \", \".join(duplicate_labels))\n        raise ValueError(msg)\n    passed_labels_absent = ~np.in1d(passed_labels, known_classes)\n    if np.any(passed_labels_absent):\n        absent_labels = [str(x) for x in passed_labels[passed_labels_absent]]\n        msg = (\"The following labels \"\n               \"were passed into {0}, \"\n               \"but were not found in \"\n               \"labels: {1}\").format(argument_name, \", \".join(absent_labels))\n        raise ValueError(msg)\n    return",
    "docstring": "Validates the labels passed into the true_labels or pred_labels\n    arguments in the plot_confusion_matrix function.\n\n    Raises a ValueError exception if any of the passed labels are not in the\n    set of known classes or if there are duplicate labels. Otherwise returns\n    None.\n\n    Args:\n        known_classes (array-like):\n            The classes that are known to appear in the data.\n        passed_labels (array-like):\n            The labels that were passed in through the argument.\n        argument_name (str):\n            The name of the argument being validated.\n\n    Example:\n        >>> known_classes = [\"A\", \"B\", \"C\"]\n        >>> passed_labels = [\"A\", \"B\"]\n        >>> validate_labels(known_classes, passed_labels, \"true_labels\")"
  },
  {
    "code": "def encode(self, pad=106):\n        opcode  = struct.pack('>H', self.defn.opcode)\n        offset  = len(opcode)\n        size    = max(offset + self.defn.argsize, pad)\n        encoded = bytearray(size)\n        encoded[0:offset] = opcode\n        encoded[offset]   = self.defn.argsize\n        offset           += 1\n        index             = 0\n        for defn in self.defn.argdefns:\n            if defn.fixed:\n                value = defn.value\n            else:\n                value  = self.args[index]\n                index += 1\n            encoded[defn.slice(offset)] = defn.encode(value)\n        return encoded",
    "docstring": "Encodes this AIT command to binary.\n\n        If pad is specified, it indicates the maximum size of the encoded\n        command in bytes.  If the encoded command is less than pad, the\n        remaining bytes are set to zero.\n\n        Commands sent to ISS payloads over 1553 are limited to 64 words\n        (128 bytes) with 11 words (22 bytes) of CCSDS overhead (SSP\n        52050J, Section 3.2.3.4).  This leaves 53 words (106 bytes) for\n        the command itself."
  },
  {
    "code": "def list_flags(self, only_name=False):\n        paths = glob.glob(os.path.join(self.outfolder, flag_name(\"*\")))\n        if only_name:\n            return [os.path.split(p)[1] for p in paths]\n        else:\n            return paths",
    "docstring": "Determine the flag files associated with this pipeline.\n\n        :param bool only_name: Whether to return only flag file name(s) (True),\n            or full flag file paths (False); default False (paths)\n        :return list[str]: flag files associated with this pipeline."
  },
  {
    "code": "def hierarchy_name(self, adjust_for_printing=True):\n        if adjust_for_printing: adjust = lambda x: adjust_name_for_printing(x)\n        else: adjust = lambda x: x\n        if self.has_parent():\n            return self._parent_.hierarchy_name() + \".\" + adjust(self.name)\n        return adjust(self.name)",
    "docstring": "return the name for this object with the parents names attached by dots.\n\n        :param bool adjust_for_printing: whether to call :func:`~adjust_for_printing()`\n                                         on the names, recursively"
  },
  {
    "code": "def windowing(size, padding=UNSET, window_type=tuple):\n    if size < 1:\n        raise ValueError(\"windowing() size {} is not at least 1\".format(size))\n    def windowing_transducer(reducer):\n        return Windowing(reducer, size, padding, window_type)\n    return windowing_transducer",
    "docstring": "Create a transducer which produces a moving window over items."
  },
  {
    "code": "def _cleanup_channel(self, channel_id):\n        with self.lock:\n            if channel_id not in self._channels:\n                return\n            del self._channels[channel_id]",
    "docstring": "Remove the the channel from the list of available channels.\n\n        :param int channel_id: Channel id\n\n        :return:"
  },
  {
    "code": "def extract_keyhandle(path, filepath):\n    keyhandle = filepath.lstrip(path)\n    keyhandle = keyhandle.split(\"/\")\n    return keyhandle[0]",
    "docstring": "extract keyhandle value from the path"
  },
  {
    "code": "def _encryption_context_hash(hasher, encryption_context):\n    serialized_encryption_context = serialize_encryption_context(encryption_context)\n    hasher.update(serialized_encryption_context)\n    return hasher.finalize()",
    "docstring": "Generates the expected hash for the provided encryption context.\n\n    :param hasher: Existing hasher to use\n    :type hasher: cryptography.hazmat.primitives.hashes.Hash\n    :param dict encryption_context: Encryption context to hash\n    :returns: Complete hash\n    :rtype: bytes"
  },
  {
    "code": "def update_subtotals(self, current, sub_key):\n        if not self.sub_counts.get(sub_key):\n            self.sub_counts[sub_key] = {}\n        for item in current:\n            try:\n                self.sub_counts[sub_key][item] += 1\n            except KeyError:\n                self.sub_counts[sub_key][item] = 1",
    "docstring": "updates sub_total counts for the class instance based on the\n            current dictionary counts\n\n        args:\n        -----\n            current: current dictionary counts\n            sub_key: the key/value to use for the subtotals"
  },
  {
    "code": "def wrap_field_error(self, data, renderer_context):\n        response = renderer_context.get(\"response\", None)\n        status_code = response and response.status_code\n        if status_code != 400:\n            raise WrapperNotApplicable('Status code must be 400.')\n        return self.wrap_error(\n            data, renderer_context, keys_are_fields=True, issue_is_title=False)",
    "docstring": "Convert field error native data to the JSON API Error format\n\n        See the note about the JSON API Error format on `wrap_error`.\n\n        The native format for field errors is a dictionary where the keys are\n        field names (or 'non_field_errors' for additional errors) and the\n        values are a list of error strings:\n\n        {\n            \"min\": [\n                \"min must be greater than 0.\",\n                \"min must be an even number.\"\n            ],\n            \"max\": [\"max must be a positive number.\"],\n            \"non_field_errors\": [\n                \"Select either a range or an enumeration, not both.\"]\n        }\n\n        It is rendered into this JSON API error format:\n\n        {\n            \"errors\": [{\n                \"status\": \"400\",\n                \"path\": \"/min\",\n                \"detail\": \"min must be greater than 0.\"\n            },{\n                \"status\": \"400\",\n                \"path\": \"/min\",\n                \"detail\": \"min must be an even number.\"\n            },{\n                \"status\": \"400\",\n                \"path\": \"/max\",\n                \"detail\": \"max must be a positive number.\"\n            },{\n                \"status\": \"400\",\n                \"path\": \"/-\",\n                \"detail\": \"Select either a range or an enumeration, not both.\"\n            }]\n        }"
  },
  {
    "code": "def add_check(self, check_item):\n        self.checks.append(check_item)\n        for other in self.others:\n            other.add_check(check_item)",
    "docstring": "Adds a check universally."
  },
  {
    "code": "def subsystem_dependencies_iter(cls):\n    for dep in cls.subsystem_dependencies():\n      if isinstance(dep, SubsystemDependency):\n        yield dep\n      else:\n        yield SubsystemDependency(dep, GLOBAL_SCOPE, removal_version=None, removal_hint=None)",
    "docstring": "Iterate over the direct subsystem dependencies of this Optionable."
  },
  {
    "code": "def _parse_user_flags():\n    try:\n        idx = list(sys.argv).index('--user-flags')\n        user_flags_file = sys.argv[idx + 1]\n    except (ValueError, IndexError):\n        user_flags_file = ''\n    if user_flags_file and os.path.isfile(user_flags_file):\n        from ryu.utils import _import_module_file\n        _import_module_file(user_flags_file)",
    "docstring": "Parses user-flags file and loads it to register user defined options."
  },
  {
    "code": "def centroid(self):\n        centroid = np.average(self.triangles_center,\n                              axis=0,\n                              weights=self.area_faces)\n        centroid.flags.writeable = False\n        return centroid",
    "docstring": "The point in space which is the average of the triangle centroids\n        weighted by the area of each triangle.\n\n        This will be valid even for non- watertight meshes,\n        unlike self.center_mass\n\n        Returns\n        ----------\n        centroid : (3,) float\n          The average vertex weighted by face area"
  },
  {
    "code": "def infer_operands_size(operands):\n    size = None\n    for oprnd in operands:\n        if oprnd.size:\n            size = oprnd.size\n            break\n    if size:\n        for oprnd in operands:\n            if not oprnd.size:\n                oprnd.size = size\n    else:\n        for oprnd in operands:\n            if isinstance(oprnd, X86ImmediateOperand) and not oprnd.size:\n                oprnd.size = arch_info.architecture_size",
    "docstring": "Infer x86 instruction operand size based on other operands."
  },
  {
    "code": "def _getProcessedImage(self):\n        if self.imageDisp is None:\n            self.imageDisp = self.image\n            self.levelMin, self.levelMax = self._quickLevels(\n                self.imageDisp)\n        return self.imageDisp",
    "docstring": "Returns the image data after it has been processed by any normalization options in use.\n        This method also sets the attributes self.levelMin and self.levelMax \n        to indicate the range of data in the image."
  },
  {
    "code": "def sem(self, ddof=1):\n        return self.std(ddof=ddof) / np.sqrt(self.count())",
    "docstring": "Compute standard error of the mean of groups, excluding missing values.\n\n        For multiple groupings, the result index will be a MultiIndex.\n\n        Parameters\n        ----------\n        ddof : integer, default 1\n            degrees of freedom"
  },
  {
    "code": "def login(self, login=None, password=None):\n        if (login is not None) and (password is not None):\n            login_data = {'user': login, 'pass': password}\n        elif (self.default_login is not None) and (self.default_password is not None):\n            login_data = {'user': self.default_login, 'pass': self.default_password}\n        elif self.session.auth:\n            login_data = None\n        else:\n            raise AuthorizationError('Credentials required, fill login and password.')\n        try:\n            self.login_result = self.__get_status_code(self.__request('',\n                                                                      post_data=login_data,\n                                                                      without_login=True)) == 200\n        except AuthorizationError:\n            return False\n        return self.login_result",
    "docstring": "Login with default or supplied credetials.\n\n        .. note::\n\n            Calling this method is not necessary when HTTP basic or HTTP\n            digest_auth authentication is used and RT accepts it as external\n            authentication method, because the login in this case is done\n            transparently by requests module. Anyway this method can be useful\n            to check whether given credentials are valid or not.\n\n        :keyword login: Username used for RT, if not supplied together with\n                        *password* :py:attr:`~Rt.default_login` and\n                        :py:attr:`~Rt.default_password` are used instead\n        :keyword password: Similarly as *login*\n\n        :returns: ``True``\n                      Successful login\n                  ``False``\n                      Otherwise\n        :raises AuthorizationError: In case that credentials are not supplied neither\n                                    during inicialization or call of this method."
  },
  {
    "code": "def run_ffitch(distfile, outtreefile, intreefile=None, **kwargs):\n    cl = FfitchCommandline(datafile=distfile, outtreefile=outtreefile, \\\n            intreefile=intreefile, **kwargs)\n    r, e = cl.run()\n    if e:\n        print(\"***ffitch could not run\", file=sys.stderr)\n        return None\n    else:\n        print(\"ffitch:\", cl, file=sys.stderr)\n        return outtreefile",
    "docstring": "Infer tree branch lengths using ffitch in EMBOSS PHYLIP"
  },
  {
    "code": "def reltags(self, src, cache=None):\n    if not self._tag_assocs:\n      return set()\n    if cache == None:\n      cache = {}\n    q = _otq()\n    q.append(src)\n    updateq = _otq()\n    while q:\n      i = q.popleft()\n      if i in cache:\n        continue\n      cache[i] = set()\n      for (s,t) in self.transitions_to(i):\n        q.append(s)\n        if self.is_tagged(t,s,i):\n          cache[i].add((self.tag(t,s,i),s, i))\n        updateq.appendleft((i, s))\n    while updateq:\n      i = updateq.popleft()\n      cache[i[0]].update(cache[i[1]])\n    return cache[src]",
    "docstring": "returns all the tags that are relevant at this state\n    cache should be a dictionary and it is updated\n    by the function"
  },
  {
    "code": "def get_default_gentation(gender, orientation):\n    gender = gender.lower()[0]\n    orientation = orientation.lower()\n    return gender_to_orientation_to_gentation[gender][orientation]",
    "docstring": "Return the default gentation for the given gender and orientation."
  },
  {
    "code": "def sort(in_file, out_file):\n    filehandle = open(in_file, 'r')\n    lines = filehandle.readlines()\n    filehandle.close()\n    lines.sort()\n    filehandle = open(out_file, 'w')\n    for line in lines:\n        filehandle.write(line)\n    filehandle.close()",
    "docstring": "Sorts the given file."
  },
  {
    "code": "def _scale_shape(dshape, scale = (1,1,1)):\n    nshape = np.round(np.array(dshape) * np.array(scale))\n    return tuple(nshape.astype(np.int))",
    "docstring": "returns the shape after scaling (should be the same as ndimage.zoom"
  },
  {
    "code": "def printParameters(self):\n    print \"------------PY  TemporalPooler Parameters ------------------\"\n    print \"numInputs                  = \", self.getNumInputs()\n    print \"numColumns                 = \", self.getNumColumns()\n    print \"columnDimensions           = \", self._columnDimensions\n    print \"numActiveColumnsPerInhArea = \", self.getNumActiveColumnsPerInhArea()\n    print \"potentialPct               = \", self.getPotentialPct()\n    print \"globalInhibition           = \", self.getGlobalInhibition()\n    print \"localAreaDensity           = \", self.getLocalAreaDensity()\n    print \"stimulusThreshold          = \", self.getStimulusThreshold()\n    print \"synPermActiveInc           = \", self.getSynPermActiveInc()\n    print \"synPermInactiveDec         = \", self.getSynPermInactiveDec()\n    print \"synPermConnected           = \", self.getSynPermConnected()\n    print \"minPctOverlapDutyCycle     = \", self.getMinPctOverlapDutyCycles()\n    print \"dutyCyclePeriod            = \", self.getDutyCyclePeriod()\n    print \"boostStrength              = \", self.getBoostStrength()\n    print \"spVerbosity                = \", self.getSpVerbosity()\n    print \"version                    = \", self._version",
    "docstring": "Useful for debugging."
  },
  {
    "code": "def execute(filelocation, outpath, executable, args=None, switchArgs=None):\n    procArgs = ['java', '-jar', executable]\n    procArgs.extend(['-output_path', outpath])\n    if args is not None:\n        for arg in args:\n            procArgs.extend(['-'+arg[0], arg[1]])\n    if switchArgs is not None:\n        procArgs.extend(['-'+arg for arg in switchArgs])\n    procArgs.extend(aux.toList(filelocation))\n    proc = subprocess.Popen(procArgs, stderr=subprocess.PIPE)\n    while True:\n        out = proc.stderr.read(1)\n        if out == '' and proc.poll() != None:\n            break\n        if out != '':\n            sys.stdout.write(out)\n            sys.stdout.flush()",
    "docstring": "Executes the dinosaur tool on Windows operating systems.\n\n    :param filelocation: either a single mgf file path or a list of file paths.\n    :param outpath: path of the output file, file must not exist\n    :param executable: must specify the complete file path of the\n        spectra-cluster-cli.jar file, supported version is 1.0.2 BETA.\n    :param args: list of arguments containing a value, for details see the\n        spectra-cluster-cli help. Arguments should be added as tuples or a list.\n        For example: [('precursor_tolerance', '0.5'), ('rounds', '3')]\n    :param switchArgs: list of arguments not containing a value, for details see\n        the spectra-cluster-cli help. Arguments should be added as strings.\n        For example: ['fast_mode', 'keep_binary_files']"
  },
  {
    "code": "def get_isa(self, oneq_type='Xhalves', twoq_type='CZ') -> ISA:\n        qubits = [Qubit(id=q.id, type=oneq_type, dead=q.dead) for q in self._isa.qubits]\n        edges = [Edge(targets=e.targets, type=twoq_type, dead=e.dead) for e in self._isa.edges]\n        return ISA(qubits, edges)",
    "docstring": "Construct an ISA suitable for targeting by compilation.\n\n        This will raise an exception if the requested ISA is not supported by the device.\n\n        :param oneq_type: The family of one-qubit gates to target\n        :param twoq_type: The family of two-qubit gates to target"
  },
  {
    "code": "def process_infile(f, fileStore):\n    if isinstance(f, tuple):\n        return f\n    elif isinstance(f, list):\n        return process_array_infile(f, fileStore)\n    elif isinstance(f, basestring):\n        return process_single_infile(f, fileStore)\n    else:\n        raise RuntimeError('Error processing file: '.format(str(f)))",
    "docstring": "Takes an array of files or a single file and imports into the jobstore.\n\n    This returns a tuple or an array of tuples replacing all previous path\n    strings.  Toil does not preserve a file's original name upon import and\n    so the tuple keeps track of this with the format: '(filepath, preserveThisFilename)'\n\n    :param f: String or an Array.  The smallest element must be a string,\n              so: an array of strings, an array of arrays of strings... etc.\n    :param fileStore: The filestore object that is called to load files into the filestore.\n    :return: A tuple or an array of tuples."
  },
  {
    "code": "def create(self, qname):\n        try:\n            if self.exists(qname):\n                log.error('Queues \"%s\" already exists. Nothing done.', qname)\n                return True\n            self.conn.create(qname)\n            return True\n        except pyrax.exceptions as err_msg:\n            log.error('RackSpace API got some problems during creation: %s',\n                      err_msg)\n        return False",
    "docstring": "Create RackSpace Queue."
  },
  {
    "code": "def main():\n    if '-h' in sys.argv:\n        print(main.__doc__)\n        sys.exit()\n    file=sys.argv[1]\n    f=open(file,'r')\n    Input=f.readlines()\n    f.close()\n    out=open(file,'w')\n    for line in Input:\n        out.write(line)\n    out.close()",
    "docstring": "NAME\n        convert2unix.py\n    \n    DESCRIPTION\n      converts mac or dos formatted file to unix file in place\n    \n    SYNTAX\n        convert2unix.py FILE \n    \n    OPTIONS\n        -h prints help and quits"
  },
  {
    "code": "def cpos(string, chars, start):\n    string = stypes.stringToCharP(string)\n    chars = stypes.stringToCharP(chars)\n    start = ctypes.c_int(start)\n    return libspice.cpos_c(string, chars, start)",
    "docstring": "Find the first occurrence in a string of a character belonging\n    to a collection of characters, starting at a specified location,\n    searching forward.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cpos_c.html\n\n    :param string: Any character string.\n    :type string: str\n    :param chars: A collection of characters.\n    :type chars: str\n    :param start: Position to begin looking for one of chars.\n    :type start: int\n    :return:\n            The index of the first character of str at or\n            following index start that is in the collection chars.\n    :rtype: int"
  },
  {
    "code": "def _get_colors(n):\n    import matplotlib.pyplot as plt\n    from matplotlib.colors import rgb2hex as r2h\n    from numpy import linspace\n    cols = linspace(0.05, .95, n)\n    cmap = plt.get_cmap('nipy_spectral')\n    return [r2h(cmap(i)) for i in cols]",
    "docstring": "Returns n unique and \"evenly\" spaced colors for the backgrounds\n    of the projects.\n\n    Args:\n        n (int): The number of unique colors wanted.\n\n    Returns:\n        colors (list of str): The colors in hex form."
  },
  {
    "code": "def capakey_rest_gateway_request(url, headers={}, params={}):\n    try:\n        res = requests.get(url, headers=headers, params=params)\n        res.raise_for_status()\n        return res\n    except requests.ConnectionError as ce:\n        raise GatewayRuntimeException(\n            'Could not execute request due to connection problems:\\n%s' % repr(ce),\n            ce\n        )\n    except requests.HTTPError as he:\n        raise GatewayResourceNotFoundException()\n    except requests.RequestException as re:\n        raise GatewayRuntimeException(\n            'Could not execute request due to:\\n%s' % repr(re),\n            re\n        )",
    "docstring": "Utility function that helps making requests to the CAPAKEY REST service.\n\n    :param string url: URL to request.\n    :param dict headers: Headers to send with the URL.\n    :param dict params: Parameters to send with the URL.\n    :returns: Result of the call."
  },
  {
    "code": "def _select(self, pointer):\n        return YAMLChunk(\n            self._ruamelparsed,\n            pointer=pointer,\n            label=self._label,\n            strictparsed=self._strictparsed,\n            key_association=copy(self._key_association),\n        )",
    "docstring": "Get a YAMLChunk referenced by a pointer."
  },
  {
    "code": "def populate_fw_dev(self, fw_id, mgmt_ip, new):\n        for cnt in self.res:\n            used = self.res.get(cnt).get('used')\n            if mgmt_ip == self.res[cnt].get('mgmt_ip'):\n                if new:\n                    self.res[cnt]['used'] = used + 1\n                self.res[cnt]['fw_id_lst'].append(fw_id)\n                return self.res[cnt].get('obj_dict'), (\n                    self.res[cnt].get('mgmt_ip'))\n        return None, None",
    "docstring": "Populate the class after a restart."
  },
  {
    "code": "def get_default_widget():\n    default_widget = forms.Textarea\n    if hasattr(settings, 'BLEACH_DEFAULT_WIDGET'):\n        default_widget = load_widget(settings.BLEACH_DEFAULT_WIDGET)\n    return default_widget",
    "docstring": "Get the default widget or the widget defined in settings"
  },
  {
    "code": "def parse_extras(extras_str):\n    from pkg_resources import Requirement\n    extras = Requirement.parse(\"fakepkg{0}\".format(extras_to_string(extras_str))).extras\n    return sorted(dedup([extra.lower() for extra in extras]))",
    "docstring": "Turn a string of extras into a parsed extras list"
  },
  {
    "code": "def map_data(self):\n        with open(self.src_file, \"r\") as f:\n            for line in f:\n                cols = line.split(',')\n                print(cols)",
    "docstring": "provides a mapping from the CSV file to the \n        aikif data structures."
  },
  {
    "code": "def get_min_distance(self, mesh):\n        dists = [surf.get_min_distance(mesh) for surf in self.surfaces]\n        return numpy.min(dists, axis=0)",
    "docstring": "For each point in ``mesh`` compute the minimum distance to each\n        surface element and return the smallest value.\n\n        See :meth:`superclass method\n        <.base.BaseSurface.get_min_distance>`\n        for spec of input and result values."
  },
  {
    "code": "def get_tokens_unprocessed(self, text, stack=('root',)):\n        self.content_type = None\n        return RegexLexer.get_tokens_unprocessed(self, text, stack)",
    "docstring": "Reset the content-type state."
  },
  {
    "code": "def decode_abi(self, types: Iterable[TypeStr], data: Decodable) -> Tuple[Any, ...]:\n        if not is_bytes(data):\n            raise TypeError(\"The `data` value must be of bytes type.  Got {0}\".format(type(data)))\n        decoders = [\n            self._registry.get_decoder(type_str)\n            for type_str in types\n        ]\n        decoder = TupleDecoder(decoders=decoders)\n        stream = ContextFramesBytesIO(data)\n        return decoder(stream)",
    "docstring": "Decodes the binary value ``data`` as a sequence of values of the ABI types\n        in ``types`` via the head-tail mechanism into a tuple of equivalent python\n        values.\n\n        :param types: An iterable of string representations of the ABI types that\n            will be used for decoding e.g. ``('uint256', 'bytes[]', '(int,int)')``\n        :param data: The binary value to be decoded.\n\n        :returns: A tuple of equivalent python values for the ABI values\n            represented in ``data``."
  },
  {
    "code": "def upd_doc(self, doc, index_update=True, label_guesser_update=True):\n        if not self.index_writer and index_update:\n            self.index_writer = self.index.writer()\n        if not self.label_guesser_updater and label_guesser_update:\n            self.label_guesser_updater = self.label_guesser.get_updater()\n        logger.info(\"Updating modified doc: %s\" % doc)\n        if index_update:\n            self._update_doc_in_index(self.index_writer, doc)\n        if label_guesser_update:\n            self.label_guesser_updater.upd_doc(doc)",
    "docstring": "Update a document in the index"
  },
  {
    "code": "def has_ssd(system_obj):\n    smart_value = False\n    storage_value = False\n    smart_resource = _get_attribute_value_of(system_obj, 'smart_storage')\n    if smart_resource is not None:\n        smart_value = _get_attribute_value_of(\n            smart_resource, 'has_ssd', default=False)\n    if smart_value:\n        return smart_value\n    storage_resource = _get_attribute_value_of(system_obj, 'storages')\n    if storage_resource is not None:\n        storage_value = _get_attribute_value_of(\n            storage_resource, 'has_ssd', default=False)\n    return storage_value",
    "docstring": "Gets if the system has any drive as SSD drive\n\n    :param system_obj: The HPESystem object.\n    :returns True if system has SSD drives."
  },
  {
    "code": "def keyval_typ2str(var, val):\n    varout = var.strip()\n    if isinstance(val, list):\n        data = \", \".join([keyval_typ2str(var, it)[1] for it in val])\n        valout = \"[\"+data+\"]\"\n    elif isinstance(val, float):\n        valout = \"{:.12f}\".format(val)\n    else:\n        valout = \"{}\".format(val)\n    return varout, valout",
    "docstring": "Convert a variable to a string\n\n    Parameters\n    ----------\n    var: str\n        The variable name\n    val: any type\n        The value of the variable\n\n    Returns\n    -------\n    varout: str\n        Stripped lowercase `var`\n    valout: any type\n        The value converted to a useful string representation\n\n    See Also\n    --------\n    keyval_str2typ: the opposite"
  },
  {
    "code": "def TXT(host, nameserver=None):\n    dig = ['dig', '+short', six.text_type(host), 'TXT']\n    if nameserver is not None:\n        dig.append('@{0}'.format(nameserver))\n    cmd = __salt__['cmd.run_all'](dig, python_shell=False)\n    if cmd['retcode'] != 0:\n        log.warning(\n            'dig returned exit code \\'%s\\'. Returning empty list as fallback.',\n            cmd['retcode']\n        )\n        return []\n    return [i for i in cmd['stdout'].split('\\n')]",
    "docstring": "Return the TXT record for ``host``.\n\n    Always returns a list.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt ns1 dig.TXT google.com"
  },
  {
    "code": "def target(key, full=True):\n    if not key.startswith('/sys'):\n        key = os.path.join('/sys', key)\n    key = os.path.realpath(key)\n    if not os.path.exists(key):\n        log.debug('Unkown SysFS key %s', key)\n        return False\n    elif full:\n        return key\n    else:\n        return os.path.basename(key)",
    "docstring": "Return the basename of a SysFS key path\n\n    :param key: the location to resolve within SysFS\n    :param full: full path instead of basename\n\n    :return: fullpath or basename of path\n\n    CLI example:\n     .. code-block:: bash\n\n        salt '*' sysfs.read class/ttyS0"
  },
  {
    "code": "def run(self, writer, reader):\n        self._page_data = self.initialize_page_data()\n        self._set_lastpage()\n        if not self.term.is_a_tty:\n            self._run_notty(writer)\n        else:\n            self._run_tty(writer, reader)",
    "docstring": "Pager entry point.\n\n        In interactive mode (terminal is a tty), run until\n        ``process_keystroke()`` detects quit keystroke ('q').  In\n        non-interactive mode, exit after displaying all unicode points.\n\n        :param writer: callable writes to output stream, receiving unicode.\n        :type writer: callable\n        :param reader: callable reads keystrokes from input stream, sending\n                       instance of blessed.keyboard.Keystroke.\n        :type reader: callable"
  },
  {
    "code": "def extract_images(bs4, lazy_image_attribute=None):\n    if lazy_image_attribute:\n        images = [image[lazy_image_attribute] for image in bs4.select('img') if image.has_attr(lazy_image_attribute)]\n    else:\n        images = [image['src'] for image in bs4.select('img') if image.has_attr('src')]\n    image_links = [link for link in extract_links(bs4) if link.endswith(('.jpg', '.JPG', '.png', '.PNG', '.gif', '.GIF'))]\n    image_metas = [meta['content'] for meta in extract_metas(bs4)\n                   if 'content' in meta\n                   if meta['content'].endswith(('.jpg', '.JPG', '.png', '.PNG', '.gif', '.GIF'))]\n    return list(set(images + image_links + image_metas))",
    "docstring": "If lazy attribute is supplied, find image url on that attribute\n\n    :param bs4:\n    :param lazy_image_attribute:\n    :return:"
  },
  {
    "code": "def encrypt_key(key, password):\n    public_key = load_pem_public_key(key.encode(), default_backend())\n    encrypted_password = public_key.encrypt(password, PKCS1v15())\n    return base64.b64encode(encrypted_password).decode('ascii')",
    "docstring": "Encrypt the password with the public key and return an ASCII representation.\n\n    The public key retrieved from the Travis API is loaded as an RSAPublicKey\n    object using Cryptography's default backend. Then the given password\n    is encrypted with the encrypt() method of RSAPublicKey. The encrypted\n    password is then encoded to base64 and decoded into ASCII in order to\n    convert the bytes object into a string object.\n\n    Parameters\n    ----------\n    key: str\n        Travis CI public RSA key that requires deserialization\n    password: str\n        the password to be encrypted\n\n    Returns\n    -------\n    encrypted_password: str\n        the base64 encoded encrypted password decoded as ASCII\n\n    Notes\n    -----\n    Travis CI uses the PKCS1v15 padding scheme. While PKCS1v15 is secure,\n    it is outdated and should be replaced with OAEP.\n\n    Example:\n    OAEP(mgf=MGF1(algorithm=SHA256()), algorithm=SHA256(), label=None))"
  },
  {
    "code": "def genl_ctrl_resolve_grp(sk, family_name, grp_name):\n    family = genl_ctrl_probe_by_name(sk, family_name)\n    if family is None:\n        return -NLE_OBJ_NOTFOUND\n    return genl_ctrl_grp_by_name(family, grp_name)",
    "docstring": "Resolve Generic Netlink family group name.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L471\n\n    Looks up the family object and resolves the group name to the numeric group identifier.\n\n    Positional arguments:\n    sk -- Generic Netlink socket (nl_sock class instance).\n    family_name -- name of Generic Netlink family (bytes).\n    grp_name -- name of group to resolve (bytes).\n\n    Returns:\n    The numeric group identifier or a negative error code."
  },
  {
    "code": "def bodn2c(name):\n    name = stypes.stringToCharP(name)\n    code = ctypes.c_int(0)\n    found = ctypes.c_int(0)\n    libspice.bodn2c_c(name, ctypes.byref(code), ctypes.byref(found))\n    return code.value, bool(found.value)",
    "docstring": "Translate the name of a body or object to the corresponding SPICE\n    integer ID code.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodn2c_c.html\n\n    :param name: Body name to be translated into a SPICE ID code.\n    :type name: str\n    :return: SPICE integer ID code for the named body.\n    :rtype: int"
  },
  {
    "code": "def _handle_options(self, option_line):\n        if option_line is not None:\n            usage =\n            options = docopt.docopt(usage, shlex.split(option_line))\n            if options['--retest']:\n                retest_file = options['--retest']\n                try:\n                    test_list_str = self._get_test_list_from_session_file(retest_file)\n                except Exception as ex:\n                    raise KittyException('Failed to open session file (%s) for retesting: %s' % (retest_file, ex))\n            else:\n                test_list_str = options['--test-list']\n            self._set_test_ranges(None, None, test_list_str)\n            session_file = options['--session']\n            if session_file is not None:\n                self.set_session_file(session_file)\n            delay = options['--delay']\n            if delay is not None:\n                self.set_delay_between_tests(float(delay))\n            skip_env_test = options['--no-env-test']\n            if skip_env_test:\n                self.set_skip_env_test(True)\n            verbosity = options['--verbose']\n            self.set_verbosity(verbosity)",
    "docstring": "Handle options from command line, in docopt style.\n        This allows passing arguments to the fuzzer from the command line\n        without the need to re-write it in each runner.\n\n        :param option_line: string with the command line options to be parsed."
  },
  {
    "code": "def all_descriptions():\n    para = []\n    para += build_parameter_descriptions(models.Soil()) + [\",,\\n\"]\n    para += build_parameter_descriptions(models.SoilProfile()) + [\",,\\n\"]\n    para += build_parameter_descriptions(models.Foundation()) + [\",,\\n\"]\n    para += build_parameter_descriptions(models.PadFoundation()) + [\",,\\n\"]\n    para += build_parameter_descriptions(models.SDOFBuilding()) + [\",,\\n\"]\n    para += build_parameter_descriptions(models.FrameBuilding2D(1, 1))\n    return para",
    "docstring": "Generates a list of descriptions of all the models\n\n    :return:"
  },
  {
    "code": "def load_data_file(filename, encoding='utf-8'):\n    data = pkgutil.get_data(PACKAGE_NAME, os.path.join(DATA_DIR, filename))\n    return data.decode(encoding).splitlines()",
    "docstring": "Load a data file and return it as a list of lines.\n\n    Parameters:\n        filename: The name of the file (no directories included).\n        encoding: The file encoding. Defaults to utf-8."
  },
  {
    "code": "def on_epoch_end(self, pbar, epoch, last_metrics, **kwargs):\n        \"Put the various losses in the recorder and show a sample image.\"\n        if not hasattr(self, 'last_gen') or not self.show_img: return\n        data = self.learn.data\n        img = self.last_gen[0]\n        norm = getattr(data,'norm',False)\n        if norm and norm.keywords.get('do_y',False): img = data.denorm(img)\n        img = data.train_ds.y.reconstruct(img)\n        self.imgs.append(img)\n        self.titles.append(f'Epoch {epoch}')\n        pbar.show_imgs(self.imgs, self.titles)\n        return add_metrics(last_metrics, [getattr(self.smoothenerG,'smooth',None),getattr(self.smoothenerC,'smooth',None)])",
    "docstring": "Put the various losses in the recorder and show a sample image."
  },
  {
    "code": "def save(path, im):\n    from PIL import Image\n    if im.dtype == np.uint8:\n        pil_im = Image.fromarray(im)\n    else:\n        pil_im = Image.fromarray((im*255).astype(np.uint8))\n    pil_im.save(path)",
    "docstring": "Saves an image to file.\n\n    If the image is type float, it will assume to have values in [0, 1].\n\n    Parameters\n    ----------\n    path : str\n        Path to which the image will be saved.\n    im : ndarray (image)\n        Image."
  },
  {
    "code": "def parse_sgf_to_examples(sgf_path):\n    return zip(*[(p.position, p.next_move, p.result)\n                 for p in sgf_wrapper.replay_sgf_file(sgf_path)])",
    "docstring": "Return supervised examples from positions\n\n    NOTE: last move is not played because no p.next_move after."
  },
  {
    "code": "def qualified_name(self):\n        idxstr = '' if self.index is None else str(self.index)\n        return \"%s[%s]\" % (self.qualified_package_name, idxstr)",
    "docstring": "Get the qualified name of the variant.\n\n        Returns:\n            str: Name of the variant with version and index, eg \"maya-2016.1[1]\"."
  },
  {
    "code": "def runSearchDatasets(self, request):\n        return self.runSearchRequest(\n            request, protocol.SearchDatasetsRequest,\n            protocol.SearchDatasetsResponse,\n            self.datasetsGenerator)",
    "docstring": "Runs the specified SearchDatasetsRequest."
  },
  {
    "code": "def wrap(ptr, base=None):\n    if ptr is None:\n        return None\n    ptr = long(ptr)\n    if base is None:\n        qObj = shiboken.wrapInstance(long(ptr), QtCore.QObject)\n        metaObj = qObj.metaObject()\n        cls = metaObj.className()\n        superCls = metaObj.superClass().className()\n        if hasattr(QtGui, cls):\n            base = getattr(QtGui, cls)\n        elif hasattr(QtGui, superCls):\n            base = getattr(QtGui, superCls)\n        else:\n            base = QtGui.QWidget\n    return shiboken.wrapInstance(long(ptr), base)",
    "docstring": "Wrap the given pointer with shiboken and return the appropriate QObject\n\n    :returns: if ptr is not None returns a QObject that is cast to the appropriate class\n    :rtype: QObject | None\n    :raises: None"
  },
  {
    "code": "def add_field(self, field_instance):\n        if isinstance(field_instance, BaseScriptField):\n            field_instance = field_instance\n        else:\n            raise ValueError('Expected a basetring or Field instance')\n        self.fields.append(field_instance)\n        return self",
    "docstring": "Appends a field."
  },
  {
    "code": "def verify_fresh_jwt_in_request():\n    if request.method not in config.exempt_methods:\n        jwt_data = _decode_jwt_from_request(request_type='access')\n        ctx_stack.top.jwt = jwt_data\n        fresh = jwt_data['fresh']\n        if isinstance(fresh, bool):\n            if not fresh:\n                raise FreshTokenRequired('Fresh token required')\n        else:\n            now = timegm(datetime.utcnow().utctimetuple())\n            if fresh < now:\n                raise FreshTokenRequired('Fresh token required')\n        verify_token_claims(jwt_data)\n        _load_user(jwt_data[config.identity_claim_key])",
    "docstring": "Ensure that the requester has a valid and fresh access token. Raises an\n    appropiate exception if there is no token, the token is invalid, or the\n    token is not marked as fresh."
  },
  {
    "code": "def get(vm, key='uuid'):\n    ret = {}\n    if key not in ['uuid', 'alias', 'hostname']:\n        ret['Error'] = 'Key must be either uuid, alias or hostname'\n        return ret\n    vm = lookup('{0}={1}'.format(key, vm), one=True)\n    if 'Error' in vm:\n        return vm\n    cmd = 'vmadm get {0}'.format(vm)\n    res = __salt__['cmd.run_all'](cmd)\n    retcode = res['retcode']\n    if retcode != 0:\n        ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode)\n        return ret\n    return salt.utils.json.loads(res['stdout'])",
    "docstring": "Output the JSON object describing a VM\n\n    vm : string\n        vm to be targeted\n    key : string [uuid|alias|hostname]\n        value type of 'vm' parameter\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' vmadm.get 186da9ab-7392-4f55-91a5-b8f1fe770543\n        salt '*' vmadm.get nacl key=alias"
  },
  {
    "code": "def release_udp_port(self, port, project):\n        if port in self._used_udp_ports:\n            self._used_udp_ports.remove(port)\n            project.remove_udp_port(port)\n            log.debug(\"UDP port {} has been released\".format(port))",
    "docstring": "Release a specific UDP port number\n\n        :param port: UDP port number\n        :param project: Project instance"
  },
  {
    "code": "def cross_successors(state, last_action=None):\n        centres, edges = state\n        acts = sum([\n            [s, s.inverse(), s * 2] for s in\n            map(Step, \"RUFDRB\".replace(last_action.face if last_action else \"\", \"\", 1))\n            ], [])\n        for step in acts:\n            yield step, (centres, CrossSolver._rotate(edges, step))",
    "docstring": "Successors function for solving the cross."
  },
  {
    "code": "def tmpdir(suffix='', prefix='tmp', dir=None):\n    tmp = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir)\n    yield tmp\n    shutil.rmtree(tmp)",
    "docstring": "Create a temporary directory with a context manager. The file is deleted when the context exits.\n\n    The prefix, suffix, and dir arguments are the same as for mkstemp().\n\n    Args:\n        suffix (str):  If suffix is specified, the file name will end with that suffix, otherwise there will be no\n                        suffix.\n        prefix (str):  If prefix is specified, the file name will begin with that prefix; otherwise,\n                        a default prefix is used.\n        dir (str):  If dir is specified, the file will be created in that directory; otherwise, a default directory is\n                        used.\n    Returns:\n        str: path to the directory"
  },
  {
    "code": "def eval(self, x):\n        aes = AES.new(self.key, AES.MODE_CFB, \"\\0\" * AES.block_size)\n        while True:\n            nonce = 0\n            data = KeyedPRF.pad(SHA256.new(str(x + nonce).encode()).digest(),\n                                (number.size(self.range) + 7) // 8)\n            num = self.mask & number.bytes_to_long(aes.encrypt(data))\n            if (num < self.range):\n                return num\n            nonce += 1",
    "docstring": "This method returns the evaluation of the function with input x\n\n        :param x: this is the input as a Long"
  },
  {
    "code": "def get_json_response(self, content, **kwargs):\n        if isinstance(content, dict):\n            response_content = {k: deepcopy(v) for k, v in content.items()\n                                if k not in ('form', 'view') or k in ('form', 'view')\n                                and not isinstance(v, (Form, View))}\n        else:\n            response_content = content\n        return HttpResponse(content=json.dumps(response_content),\n                            content_type='application/json; charset=utf-8',\n                            **kwargs)",
    "docstring": "Returns a json response object."
  },
  {
    "code": "def invoke(self):\n        if self.timeout_milliseconds > 0:\n            self.ready_time = (\n                datetime.now() +\n                timedelta(milliseconds=self.timeout_milliseconds))\n        self.callback(self.callback_args)",
    "docstring": "Run callback, optionally passing a variable number\n        of arguments `callback_args`"
  },
  {
    "code": "def actions(self):\n        r = self.session.query(models.Action).all()\n        return [x.type_name for x in r]",
    "docstring": "Gets the list of allowed actions\n\n        :rtype: list[str]"
  },
  {
    "code": "def _exception(etype, eval_, etrace):\n        if hasattr(sys, 'ps1') or not sys.stderr.isatty():\n            sys.__excepthook__(etype, eval_, etrace)\n        else:\n            traceback.print_exception(etype, eval_, etrace, limit=2,\n                                      file=sys.stdout)\n            six.print_()\n            pdb.pm()",
    "docstring": "Wrap exception in debugger if not in tty"
  },
  {
    "code": "def set_imu_callback(self, callback, data=None):\n        self.imu_callback = callback\n        self.imu_callback_data = data",
    "docstring": "Register a callback for incoming IMU data packets.\n        \n        This method allows you to pass in a callbable which will be called on\n        receipt of each IMU data packet sent by this SK8 device. Set to `None`\n        to disable it again.\n\n        Args:\n            callback: a callable with the following signature:\n                        (acc, gyro, mag, imu_index, seq, timestamp, data)\n                      where:\n                        acc, gyro, mag = sensor data ([x,y,z] in each case)\n                        imu_index = originating IMU number (int, 0-4)\n                        seq = packet sequence number (int, 0-255)\n                        timestamp = value of time.time() when packet received\n                        data = value of `data` parameter passed to this method\n            data: an optional arbitrary object that will be passed as a \n                parameter to the callback"
  },
  {
    "code": "def scale_rows_by_largest_entry(S):\n    if not isspmatrix_csr(S):\n        raise TypeError('expected csr_matrix')\n    largest_row_entry = np.zeros((S.shape[0],), dtype=S.dtype)\n    pyamg.amg_core.maximum_row_value(S.shape[0], largest_row_entry,\n                                     S.indptr, S.indices, S.data)\n    largest_row_entry[largest_row_entry != 0] =\\\n        1.0 / largest_row_entry[largest_row_entry != 0]\n    S = scale_rows(S, largest_row_entry, copy=True)\n    return S",
    "docstring": "Scale each row in S by it's largest in magnitude entry.\n\n    Parameters\n    ----------\n    S : csr_matrix\n\n    Returns\n    -------\n    S : csr_matrix\n        Each row has been scaled by it's largest in magnitude entry\n\n    Examples\n    --------\n    >>> from pyamg.gallery import poisson\n    >>> from pyamg.util.utils import scale_rows_by_largest_entry\n    >>> A = poisson( (4,), format='csr' )\n    >>> A.data[1] = 5.0\n    >>> A = scale_rows_by_largest_entry(A)\n    >>> A.todense()\n    matrix([[ 0.4,  1. ,  0. ,  0. ],\n            [-0.5,  1. , -0.5,  0. ],\n            [ 0. , -0.5,  1. , -0.5],\n            [ 0. ,  0. , -0.5,  1. ]])"
  },
  {
    "code": "def hash_file(path: str,\n              progress_callback: Callable[[float], None],\n              chunk_size: int = 1024,\n              file_size: int = None,\n              algo: str = 'sha256') -> bytes:\n    hasher = hashlib.new(algo)\n    have_read = 0\n    if not chunk_size:\n        chunk_size = 1024\n    with open(path, 'rb') as to_hash:\n        if not file_size:\n            file_size = to_hash.seek(0, 2)\n            to_hash.seek(0)\n        while True:\n            chunk = to_hash.read(chunk_size)\n            hasher.update(chunk)\n            have_read += len(chunk)\n            progress_callback(have_read/file_size)\n            if len(chunk) != chunk_size:\n                break\n    return binascii.hexlify(hasher.digest())",
    "docstring": "Hash a file and return the hash, providing progress callbacks\n\n    :param path: The file to hash\n    :param progress_callback: The callback to call with progress between 0 and\n                              1. May not ever be precisely 1.0.\n    :param chunk_size: If specified, the size of the chunks to hash in one call\n                       If not specified, defaults to 1024\n    :param file_size: If specified, the size of the file to hash (used for\n                      progress callback generation). If not specified,\n                      calculated internally.\n    :param algo: The algorithm to use. Can be anything used by\n                 :py:mod:`hashlib`\n    :returns: The output has ascii hex"
  },
  {
    "code": "async def apply_commandline(self, cmdline):\n        cmdline = cmdline.lstrip()\n        def apply_this_command(cmdstring):\n            logging.debug('%s command string: \"%s\"', self.mode, str(cmdstring))\n            cmd = commandfactory(cmdstring, self.mode)\n            if cmd.repeatable:\n                self.last_commandline = cmdline\n            return self.apply_command(cmd)\n        try:\n            for c in split_commandline(cmdline):\n                await apply_this_command(c)\n        except Exception as e:\n            self._error_handler(e)",
    "docstring": "interprets a command line string\n\n        i.e., splits it into separate command strings,\n        instanciates :class:`Commands <alot.commands.Command>`\n        accordingly and applies then in sequence.\n\n        :param cmdline: command line to interpret\n        :type cmdline: str"
  },
  {
    "code": "def get_asset_spatial_session_for_repository(self, repository_id, proxy):\n        if not repository_id:\n            raise NullArgument()\n        if not self.supports_asset_spatial() or not self.supports_visible_federation():\n            raise Unimplemented()\n        try:\n            from . import sessions\n        except ImportError:\n            raise OperationFailed('import error')\n        proxy = self._convert_proxy(proxy)\n        try:\n            session = sessions.AssetSpatialSession(repository_id, proxy, runtime=self._runtime)\n        except AttributeError:\n            raise OperationFailed('attribute error')\n        return session",
    "docstring": "Gets the session for retrieving spatial coverage of an asset for\n        the given repository.\n\n        arg:    repository_id (osid.id.Id): the Id of the repository\n        arg     proxy (osid.proxy.Proxy): a proxy\n        return: (osid.repository.AssetSpatialSession) - an\n                AssetSpatialSession\n        raise:  NotFound - repository_id not found\n        raise:  NullArgument - repository_id is null\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - supports_asset_spatial() or\n                supports_visible_federation() is false\n        compliance: optional - This method must be implemented if\n                    supports_asset_spatial() and\n                    supports_visible_federation() are true."
  },
  {
    "code": "def collect_hypervisors_metrics(\n        self,\n        servers,\n        custom_tags=None,\n        use_shortname=False,\n        collect_hypervisor_metrics=True,\n        collect_hypervisor_load=False,\n    ):\n        hyp_project_names = defaultdict(set)\n        for server in itervalues(servers):\n            hypervisor_hostname = server.get('hypervisor_hostname')\n            if not hypervisor_hostname:\n                self.log.debug(\n                    \"hypervisor_hostname is None for server %s. Check that your user is an administrative users.\",\n                    server['server_id'],\n                )\n            else:\n                hyp_project_names[hypervisor_hostname].add(server['project_name'])\n        hypervisors = self.get_os_hypervisors_detail()\n        for hyp in hypervisors:\n            self.get_stats_for_single_hypervisor(\n                hyp,\n                hyp_project_names,\n                custom_tags=custom_tags,\n                use_shortname=use_shortname,\n                collect_hypervisor_metrics=collect_hypervisor_metrics,\n                collect_hypervisor_load=collect_hypervisor_load,\n            )\n        if not hypervisors:\n            self.warning(\"Unable to collect any hypervisors from Nova response.\")",
    "docstring": "Submits stats for all hypervisors registered to this control plane\n        Raises specific exceptions based on response code"
  },
  {
    "code": "def debug(level=logging.DEBUG):\n    from jcvi.apps.console import magenta, yellow\n    format = yellow(\"%(asctime)s [%(module)s]\")\n    format += magenta(\" %(message)s\")\n    logging.basicConfig(level=level,\n            format=format,\n            datefmt=\"%H:%M:%S\")",
    "docstring": "Turn on the debugging"
  },
  {
    "code": "def get_aggregate_check(self, check, age=None):\n        data = {}\n        if age:\n            data['max_age'] = age\n        result = self._request('GET', '/aggregates/{}'.format(check),\n                               data=json.dumps(data))\n        return result.json()",
    "docstring": "Returns the list of aggregates for a given check"
  },
  {
    "code": "def OnViewTypeTool( self, event ):\n        new = self.viewTypeTool.GetStringSelection()\n        if new != self.viewType:\n            self.viewType = new\n            self.OnRootView( event )",
    "docstring": "When the user changes the selection, make that our selection"
  },
  {
    "code": "def tabActiveMarkupChanged(self, tab):\n\t\tif tab == self.currentTab:\n\t\t\tmarkupClass = tab.getActiveMarkupClass()\n\t\t\tdtMarkdown = (markupClass == markups.MarkdownMarkup)\n\t\t\tdtMkdOrReST = dtMarkdown or (markupClass == markups.ReStructuredTextMarkup)\n\t\t\tself.formattingBox.setEnabled(dtMarkdown)\n\t\t\tself.symbolBox.setEnabled(dtMarkdown)\n\t\t\tself.actionUnderline.setEnabled(dtMarkdown)\n\t\t\tself.actionBold.setEnabled(dtMkdOrReST)\n\t\t\tself.actionItalic.setEnabled(dtMkdOrReST)",
    "docstring": "Perform all UI state changes that need to be done when the\n\t\tactive markup class of the current tab has changed."
  },
  {
    "code": "def format_node(import_graph, node, indent):\n    if isinstance(node, graph.NodeSet):\n        ind = '  ' * indent\n        out = [ind + 'cycle {'] + [\n                format_file_node(import_graph, n, indent + 1)\n                for n in node.nodes\n        ] + [ind + '}']\n        return '\\n'.join(out)\n    else:\n        return format_file_node(import_graph, node, indent)",
    "docstring": "Helper function for print_tree"
  },
  {
    "code": "def register_gate(name, gateclass, allow_overwrite=False):\n        if hasattr(Circuit, name):\n            if allow_overwrite:\n                warnings.warn(f\"Circuit has attribute `{name}`.\")\n            else:\n                raise ValueError(f\"Circuit has attribute `{name}`.\")\n        if name.startswith(\"run_with_\"):\n            if allow_overwrite:\n                warnings.warn(f\"Gate name `{name}` may conflict with run of backend.\")\n            else:\n                raise ValueError(f\"Gate name `{name}` shall not start with 'run_with_'.\")\n        if not allow_overwrite:\n            if name in GATE_SET:\n                raise ValueError(f\"Gate '{name}' is already exists in gate set.\")\n            if name in GLOBAL_MACROS:\n                raise ValueError(f\"Macro '{name}' is already exists.\")\n        GATE_SET[name] = gateclass",
    "docstring": "Register new gate to gate set.\n\n        Args:\n            name (str): The name of gate.\n            gateclass (type): The type object of gate.\n            allow_overwrite (bool, optional): If True, allow to overwrite the existing gate.\n                Otherwise, raise the ValueError.\n\n        Raises:\n            ValueError: The name is duplicated with existing gate.\n                When `allow_overwrite=True`, this error is not raised."
  },
  {
    "code": "def compute_all_minutes(opens_in_ns, closes_in_ns):\n    deltas = closes_in_ns - opens_in_ns\n    daily_sizes = (deltas // NANOSECONDS_PER_MINUTE) + 1\n    num_minutes = daily_sizes.sum()\n    pieces = []\n    for open_, size in zip(opens_in_ns, daily_sizes):\n        pieces.append(\n            np.arange(open_,\n                      open_ + size * NANOSECONDS_PER_MINUTE,\n                      NANOSECONDS_PER_MINUTE)\n        )\n    out = np.concatenate(pieces).view('datetime64[ns]')\n    assert len(out) == num_minutes\n    return out",
    "docstring": "Given arrays of opens and closes, both in nanoseconds,\n    return an array of each minute between the opens and closes."
  },
  {
    "code": "def send_reply(self, context, reply):\n        print(\"Status: 200 OK\")\n        print(\"Content-Type: application/json\")\n        print(\"Cache-Control: no-cache\")\n        print(\"Pragma: no-cache\")\n        print(\"Content-Length: %d\" % len(reply))\n        print()\n        print(reply.decode())",
    "docstring": "Sends a reply to a client.\n\n        The client is usually identified by passing ``context`` as returned\n        from the original :py:func:`receive_message` call.\n\n        Messages must be bytes, it is up to the sender to convert the message\n        beforehand. A non-bytes value raises a :py:exc:`TypeError`.\n\n        :param any context: A context returned by :py:func:`receive_message`.\n        :param bytes reply: A binary to send back as the reply."
  },
  {
    "code": "def create_entity(self):\n        self._highest_id_seen += 1\n        entity = Entity(self._highest_id_seen, self)\n        self._entities.append(entity)\n        return entity",
    "docstring": "Create a new entity.\n\n        The entity will have a higher UID than any previously associated\n        with this world.\n\n        :return: the new entity\n        :rtype: :class:`essence.Entity`"
  },
  {
    "code": "def match(self, key=None, year=None, event=None, type='qm', number=None, round=None, simple=False):\n        if key:\n            return Match(self._get('match/%s%s' % (key, '/simple' if simple else '')))\n        else:\n            return Match(self._get('match/{year}{event}_{type}{number}{round}{simple}'.format(year=year if not event[0].isdigit() else '',\n                                                                                              event=event,\n                                                                                              type=type,\n                                                                                              number=number,\n                                                                                              round=('m%s' % round) if not type == 'qm' else '',\n                                                                                              simple='/simple' if simple else '')))",
    "docstring": "Get data on a match.\n\n        You may either pass the match's key directly, or pass `year`, `event`, `type`, `match` (the match number), and `round` if applicable (playoffs only). The event year may be specified as part of the event key or specified in the `year` parameter.\n\n        :param key: Key of match to get data on. First option for specifying a match (see above).\n        :param year: Year in which match took place. Optional; if excluded then must be included in event key.\n        :param event: Key of event in which match took place. Including year is optional; if excluded then must be specified in `year` parameter.\n        :param type: One of 'qm' (qualifier match), 'qf' (quarterfinal), 'sf' (semifinal), 'f' (final). If unspecified, 'qm' will be assumed.\n        :param number: Match number. For example, for qualifier 32, you'd pass 32. For Semifinal 2 round 3, you'd pass 2.\n        :param round: For playoff matches, you will need to specify a round.\n        :param simple: Get only vital data.\n        :return: A single Match object."
  },
  {
    "code": "def _assert_is_type(name, value, value_type):\n    if not isinstance(value, value_type):\n        if type(value_type) is tuple:\n            types = ', '.join(t.__name__ for t in value_type)\n            raise ValueError('{0} must be one of ({1})'.format(name, types))\n        else:\n            raise ValueError('{0} must be {1}'\n                             .format(name, value_type.__name__))",
    "docstring": "Assert that a value must be a given type."
  },
  {
    "code": "def isSurrounded(self):\n        malefics = [const.MARS, const.SATURN]\n        return self.__sepApp(malefics, aspList=[0, 90, 180])",
    "docstring": "Returns if the object is separating and applying to \n        a malefic considering bad aspects."
  },
  {
    "code": "def bundle(self, name: str) -> models.Bundle:\n        return self.Bundle.filter_by(name=name).first()",
    "docstring": "Fetch a bundle from the store."
  },
  {
    "code": "def _load_into_numpy(sf, np_array, start, end, strides=None, shape=None):\n    np_array[:] = 0.0\n    np_array_2d = np_array.reshape((np_array.shape[0], np_array.shape[1] * np_array.shape[2]))\n    _extensions.sframe_load_to_numpy(sf, np_array.ctypes.data,\n                                     np_array_2d.strides, np_array_2d.shape,\n                                     start, end)",
    "docstring": "Loads into numpy array from SFrame, assuming SFrame stores data flattened"
  },
  {
    "code": "def from_chars(cls, chars='', optimal=3):\n        if not chars:\n            chars = ''.join(ALNUM)\n        sets = most_even_chunk(chars, optimal)\n        return cls(sets)",
    "docstring": "Construct a Pat object from the specified string\n        and optimal position count."
  },
  {
    "code": "def method_not_allowed(cls, errors=None):\n        if cls.expose_status:\n            cls.response.content_type = 'application/json'\n            cls.response._status_line = '405 Method Not Allowed'\n        return cls(405, None, errors).to_json",
    "docstring": "Shortcut API for HTTP 405 `Method not allowed` response.\n\n        Args:\n            errors (list): Response key/value data.\n\n        Returns:\n            WSResponse Instance."
  },
  {
    "code": "def configure_bound(self, surface_size):\n        r = len(self.rows)\n        max_length = self.max_length\n        if self.key_size is None:\n            self.key_size = (surface_size[0] - (self.padding * (max_length + 1))) / max_length\n        height = self.key_size * r + self.padding * (r + 1)\n        if height >= surface_size[1] / 2:\n            logger.warning('Computed keyboard height outbound target surface, reducing key_size to match')\n            self.key_size = ((surface_size[1] / 2) - (self.padding * (r + 1))) / r\n            height = self.key_size * r + self.padding * (r + 1)\n            logger.warning('Normalized key_size to %spx' % self.key_size)\n        self.set_size((surface_size[0], height), surface_size)",
    "docstring": "Compute keyboard bound regarding of this layout.\n        \n        If key_size is None, then it will compute it regarding of the given surface_size.\n\n        :param surface_size: Size of the surface this layout will be rendered on.\n        :raise ValueError: If the layout model is empty."
  },
  {
    "code": "def attach_storage(self, server, storage, storage_type, address):\n        body = {'storage_device': {}}\n        if storage:\n            body['storage_device']['storage'] = str(storage)\n        if storage_type:\n            body['storage_device']['type'] = storage_type\n        if address:\n            body['storage_device']['address'] = address\n        url = '/server/{0}/storage/attach'.format(server)\n        res = self.post_request(url, body)\n        return Storage._create_storage_objs(res['server']['storage_devices'], cloud_manager=self)",
    "docstring": "Attach a Storage object to a Server. Return a list of the server's storages."
  },
  {
    "code": "def new_points(\n    factory: IterationPointFactory, solution, weights: List[List[float]] = None\n) -> List[Tuple[np.ndarray, List[float]]]:\n    from desdeo.preference.direct import DirectSpecification\n    points = []\n    nof = factory.optimization_method.optimization_problem.problem.nof_objectives()\n    if not weights:\n        weights = random_weights(nof, 50 * nof)\n    for pref in map(\n        lambda w: DirectSpecification(factory.optimization_method, np.array(w)), weights\n    ):\n        points.append(factory.result(pref, solution))\n    return points",
    "docstring": "Generate approximate set of points\n\n    Generate set of Pareto optimal solutions projecting from the Pareto optimal solution\n    using weights to determine the direction.\n\n\n    Parameters\n    ----------\n\n    factory:\n        IterationPointFactory with suitable optimization problem\n\n    solution:\n        Current solution from which new solutions are projected\n\n    weights:\n        Direction of the projection, if not given generate with\n        :func:random_weights"
  },
  {
    "code": "def display_paths(instances, type_str):\n    print('%ss: count=%s' % (type_str, len(instances),))\n    for path in [instance.path for instance in instances]:\n        print('%s: %s' % (type_str, path))\n    if len(instances):\n        print('')",
    "docstring": "Display the count and paths for the list of instances in instances."
  },
  {
    "code": "def conda_info(prefix):\n    cmd = [join(prefix, 'bin', 'conda')]\n    cmd.extend(['info', '--json'])\n    output = check_output(cmd)\n    return yaml.load(output)",
    "docstring": "returns conda infos"
  },
  {
    "code": "def execute_work_items(work_items, config):\n    return celery.group(\n        worker_task.s(work_item, config)\n        for work_item in work_items\n    )",
    "docstring": "Execute a suite of tests for a given set of work items.\n\n    Args:\n      work_items: An iterable of `work_db.WorkItem`s.\n      config: The configuration to use for the test execution.\n\n    Returns: An iterable of WorkItems."
  },
  {
    "code": "def discretize(self, method, *args, **kwargs):\n        super(CustomDistribution, self).discretize(method, *args, **kwargs)",
    "docstring": "Discretizes the continuous distribution into discrete\n        probability masses using specified method.\n\n        Parameters\n        ----------\n        method: string, BaseDiscretizer instance\n            A Discretizer Class from pgmpy.factors.discretize\n\n        *args, **kwargs: values\n            The parameters to be given to the Discretizer Class.\n\n        Returns\n        -------\n        An n-D array or a DiscreteFactor object according to the discretiztion\n        method used.\n\n        Examples\n        --------\n        >>> import numpy as np\n        >>> from scipy.special import beta\n        >>> from pgmpy.factors.continuous import ContinuousFactor\n        >>> from pgmpy.factors.continuous import RoundingDiscretizer\n        >>> def dirichlet_pdf(x, y):\n        ...     return (np.power(x, 1) * np.power(y, 2)) / beta(x, y)\n        >>> dirichlet_factor = ContinuousFactor(['x', 'y'], dirichlet_pdf)\n        >>> dirichlet_factor.discretize(RoundingDiscretizer,\n        ...                             low=1, high=2, cardinality=5)\n        # TODO: finish this"
  },
  {
    "code": "def resolution(self, values):\n        values = np.asanyarray(values, dtype=np.int64)\n        if values.shape != (2,):\n            raise ValueError('resolution must be (2,) float')\n        self._resolution = values",
    "docstring": "Set the camera resolution in pixels.\n\n        Parameters\n        ------------\n        resolution (2,) float\n          Camera resolution in pixels"
  },
  {
    "code": "def _fetch_data(self):\n        self._view_col0 = clamp(self._view_col0, 0, self._max_col0)\n        self._view_row0 = clamp(self._view_row0, 0, self._max_row0)\n        self._view_ncols = clamp(self._view_ncols, 0,\n                                 self._conn.frame_ncols - self._view_col0)\n        self._view_nrows = clamp(self._view_nrows, 0,\n                                 self._conn.frame_nrows - self._view_row0)\n        self._conn.fetch_data(\n            self._view_row0,\n            self._view_row0 + self._view_nrows,\n            self._view_col0,\n            self._view_col0 + self._view_ncols)",
    "docstring": "Retrieve frame data within the current view window.\n\n        This method will adjust the view window if it goes out-of-bounds."
  },
  {
    "code": "def wait_for(self, new_state):\n        if self._state == new_state:\n            return\n        if self._state > new_state:\n            raise OrderedStateSkipped(new_state)\n        fut = asyncio.Future(loop=self.loop)\n        self._exact_waiters.append((new_state, fut))\n        yield from fut",
    "docstring": "Wait for an exact state `new_state` to be reached by the state\n        machine.\n\n        If the state is skipped, that is, if a state which is greater than\n        `new_state` is written to :attr:`state`, the coroutine raises\n        :class:`OrderedStateSkipped` exception as it is not possible anymore\n        that it can return successfully (see :attr:`state`)."
  },
  {
    "code": "def update_line(self, resource_id, data):\n        return OrderLines(self.client).on(self).update(resource_id, data)",
    "docstring": "Update a line for an order."
  },
  {
    "code": "def download_file_from_bucket(self, bucket, file_path, key):\n        with open(file_path, 'wb') as data:\n            self.__s3.download_fileobj(bucket, key, data)\n            return file_path",
    "docstring": "Download file from S3 Bucket"
  },
  {
    "code": "def get_timestamps(cols, created_name, updated_name):\n  has_created = created_name in cols\n  has_updated = updated_name in cols\n  return (created_name if has_created else None, updated_name if has_updated else None)",
    "docstring": "Returns a 2-tuple of the timestamp columns that were found on the table definition."
  },
  {
    "code": "def get_term_frequency(self, term, document, normalized=False):\n        if document not in self._documents:\n            raise IndexError(DOCUMENT_DOES_NOT_EXIST)\n        if term not in self._terms:\n            raise IndexError(TERM_DOES_NOT_EXIST)\n        result = self._terms[term].get(document, 0)\n        if normalized:\n            result /= self.get_document_length(document)\n        return float(result)",
    "docstring": "Returns the frequency of the term specified in the document."
  },
  {
    "code": "def print_header(msg, sep='='):\n    \" More strong message \"\n    LOGGER.info(\"\\n%s\\n%s\" % (msg, ''.join(sep for _ in msg)))",
    "docstring": "More strong message"
  },
  {
    "code": "def browse_userjournals(self, username, featured=False, offset=0, limit=10):\n        response = self._req('/browse/user/journals', {\n            \"username\":username,\n            \"featured\":featured,\n            \"offset\":offset,\n            \"limit\":limit\n        })\n        deviations = []\n        for item in response['results']:\n            d = Deviation()\n            d.from_dict(item)\n            deviations.append(d)\n        return {\n            \"results\" : deviations,\n            \"has_more\" : response['has_more'],\n            \"next_offset\" : response['next_offset']\n        }",
    "docstring": "Fetch user journals from user\n\n        :param username: name of user to retrieve journals from\n        :param featured: fetch only featured or not\n        :param offset: the pagination offset\n        :param limit: the pagination limit"
  },
  {
    "code": "def verify_api(self, ret):\n        if self.restApiId:\n            deployed_label_json = self._get_current_deployment_label()\n            if deployed_label_json == self.deployment_label_json:\n                ret['comment'] = ('Already at desired state, the stage {0} is already at the desired '\n                                  'deployment label:\\n{1}'.format(self._stage_name, deployed_label_json))\n                ret['current'] = True\n                return ret\n            else:\n                self._deploymentId = self._get_desired_deployment_id()\n                if self._deploymentId:\n                    ret['publish'] = True\n        return ret",
    "docstring": "this method helps determine if the given stage_name is already on a deployment\n        label matching the input api_name, swagger_file.\n\n        If yes, returns abort with comment indicating already at desired state.\n        If not and there is previous deployment labels in AWS matching the given input api_name and\n        swagger file, indicate to the caller that we only need to reassociate stage_name to the\n        previously existing deployment label."
  },
  {
    "code": "def getUnionTemporalPoolerInput(self):\n    activeCells = numpy.zeros(self.tm.numberOfCells()).astype(realDType)\n    activeCells[list(self.tm.activeCellsIndices())] = 1\n    predictedActiveCells = numpy.zeros(self.tm.numberOfCells()).astype(\n      realDType)\n    predictedActiveCells[list(self.tm.predictedActiveCellsIndices())] = 1\n    burstingColumns = numpy.zeros(self.tm.numberOfColumns()).astype(realDType)\n    burstingColumns[list(self.tm.unpredictedActiveColumns)] = 1\n    return activeCells, predictedActiveCells, burstingColumns",
    "docstring": "Gets the Union Temporal Pooler input from the Temporal Memory"
  },
  {
    "code": "def main(argv=None):\n    parser = argparse.ArgumentParser(\n        description='Event storage and event proxy.',\n        usage='%(prog)s <configfile>'\n    )\n    parser.add_argument('--exit-codeword', metavar=\"MSG\", dest=\"exit_message\",\n                        default=None, help=\"An incoming message that makes\"\n                                           \" Rewind quit. Used for testing.\")\n    parser.add_argument('configfile')\n    args = argv if argv is not None else sys.argv[1:]\n    args = parser.parse_args(args)\n    config = configparser.SafeConfigParser()\n    with open(args.configfile) as f:\n        config.readfp(f)\n    exitcode = run(config, args.exit_message)\n    return exitcode",
    "docstring": "Entry point for Rewind.\n\n    Parses input and calls run() for the real work.\n\n    Parameters:\n    argv    -- sys.argv arguments. Can be set for testing purposes.\n\n    returns -- the proposed exit code for the program."
  },
  {
    "code": "def in_base(self, base):\n        if base == self.base:\n            return copy.deepcopy(self)\n        (result, _) = Radices.from_rational(self.as_rational(), base)\n        return result",
    "docstring": "Return value in ``base``.\n\n        :returns: Radix in ``base``\n        :rtype: Radix\n        :raises ConvertError: if ``base`` is less than 2"
  },
  {
    "code": "def authenticate_server(self, response):\n        log.debug(\"authenticate_server(): Authenticate header: {0}\".format(\n            _negotiate_value(response)))\n        host = urlparse(response.url).hostname\n        try:\n            if self.cbt_struct:\n                result = kerberos.authGSSClientStep(self.context[host],\n                                                    _negotiate_value(response),\n                                                    channel_bindings=self.cbt_struct)\n            else:\n                result = kerberos.authGSSClientStep(self.context[host],\n                                                    _negotiate_value(response))\n        except kerberos.GSSError:\n            log.exception(\"authenticate_server(): authGSSClientStep() failed:\")\n            return False\n        if result < 1:\n            log.error(\"authenticate_server(): authGSSClientStep() failed: \"\n                      \"{0}\".format(result))\n            return False\n        log.debug(\"authenticate_server(): returning {0}\".format(response))\n        return True",
    "docstring": "Uses GSSAPI to authenticate the server.\n\n        Returns True on success, False on failure."
  },
  {
    "code": "def get_records(self, records=None, timeout=1.0):\n        octets = b''.join(ndef.message_encoder(records)) if records else None\n        octets = self.get_octets(octets, timeout)\n        if octets and len(octets) >= 3:\n            return list(ndef.message_decoder(octets))",
    "docstring": "Get NDEF message records from a SNEP Server.\n\n        .. versionadded:: 0.13\n\n        The :class:`ndef.Record` list given by *records* is encoded as\n        the request message octets input to :meth:`get_octets`. The\n        return value is an :class:`ndef.Record` list decoded from the\n        response message octets returned by :meth:`get_octets`. Same\n        as::\n\n            import ndef\n            send_octets = ndef.message_encoder(records)\n            rcvd_octets = snep_client.get_octets(send_octets, timeout)\n            records = list(ndef.message_decoder(rcvd_octets))"
  },
  {
    "code": "def _Bound_TP(T, P):\n    region = None\n    if 1073.15 < T <= 2273.15 and Pmin <= P <= 50:\n        region = 5\n    elif Pmin <= P <= Ps_623:\n        Tsat = _TSat_P(P)\n        if 273.15 <= T <= Tsat:\n            region = 1\n        elif Tsat < T <= 1073.15:\n            region = 2\n    elif Ps_623 < P <= 100:\n        T_b23 = _t_P(P)\n        if 273.15 <= T <= 623.15:\n            region = 1\n        elif 623.15 < T < T_b23:\n            region = 3\n        elif T_b23 <= T <= 1073.15:\n            region = 2\n    return region",
    "docstring": "Region definition for input T and P\n\n    Parameters\n    ----------\n    T : float\n        Temperature, [K]\n    P : float\n        Pressure, [MPa]\n\n    Returns\n    -------\n    region : float\n        IAPWS-97 region code\n\n    References\n    ----------\n    Wagner, W; Kretzschmar, H-J: International Steam Tables: Properties of\n    Water and Steam Based on the Industrial Formulation IAPWS-IF97; Springer,\n    2008; doi: 10.1007/978-3-540-74234-0. Fig. 2.3"
  },
  {
    "code": "def parse_expression(clause):\n    if isinstance(clause, Expression):\n        return clause\n    elif hasattr(clause, \"getName\") and clause.getName() != \"field\":\n        if clause.getName() == \"nested\":\n            return AttributeSelection.from_statement(clause)\n        elif clause.getName() == \"function\":\n            return SelectFunction.from_statement(clause)\n        else:\n            return Value(resolve(clause[0]))\n    else:\n        return Field(clause[0])",
    "docstring": "For a clause that could be a field, value, or expression"
  },
  {
    "code": "def build_action(self, runnable, regime, action):\n        if isinstance(action, StateAssignment):\n            return self.build_state_assignment(runnable, regime, action)\n        if isinstance(action, EventOut):\n            return self.build_event_out(action)\n        if isinstance(action, Transition):\n            return self.build_transition(action)\n        else:\n            return ['pass']",
    "docstring": "Build event handler action code.\n\n        @param action: Event handler action object\n        @type action: lems.model.dynamics.Action\n\n        @return: Generated action code\n        @rtype: string"
  },
  {
    "code": "def _rndPointDisposition(dx, dy):\n        x = int(random.uniform(-dx, dx))\n        y = int(random.uniform(-dy, dy))\n        return (x, y)",
    "docstring": "Return random disposition point."
  },
  {
    "code": "def standardize_mapping(into):\n    if not inspect.isclass(into):\n        if isinstance(into, collections.defaultdict):\n            return partial(\n                collections.defaultdict, into.default_factory)\n        into = type(into)\n    if not issubclass(into, abc.Mapping):\n        raise TypeError('unsupported type: {into}'.format(into=into))\n    elif into == collections.defaultdict:\n        raise TypeError(\n            'to_dict() only accepts initialized defaultdicts')\n    return into",
    "docstring": "Helper function to standardize a supplied mapping.\n\n    .. versionadded:: 0.21.0\n\n    Parameters\n    ----------\n    into : instance or subclass of collections.abc.Mapping\n        Must be a class, an initialized collections.defaultdict,\n        or an instance of a collections.abc.Mapping subclass.\n\n    Returns\n    -------\n    mapping : a collections.abc.Mapping subclass or other constructor\n        a callable object that can accept an iterator to create\n        the desired Mapping.\n\n    See Also\n    --------\n    DataFrame.to_dict\n    Series.to_dict"
  },
  {
    "code": "def querystring(self):\n        return {key: value for (key, value) in self.qs.items()\n                if key.startswith(self.MANAGED_KEYS) or self._get_key_values('filter[')}",
    "docstring": "Return original querystring but containing only managed keys\n\n        :return dict: dict of managed querystring parameter"
  },
  {
    "code": "def _parse_desc_length_file(cls, fileobj):\n        value = 0\n        for i in xrange(4):\n            try:\n                b = cdata.uint8(fileobj.read(1))\n            except cdata.error as e:\n                raise ValueError(e)\n            value = (value << 7) | (b & 0x7f)\n            if not b >> 7:\n                break\n        else:\n            raise ValueError(\"invalid descriptor length\")\n        return value",
    "docstring": "May raise ValueError"
  },
  {
    "code": "def ensure_subclass(value, types):\n    ensure_class(value)\n    if not issubclass(value, types):\n        raise TypeError(\n            \"expected subclass of {}, not {}\".format(\n                types, value))",
    "docstring": "Ensure value is a subclass of types\n\n    >>> class Hello(object): pass\n    >>> ensure_subclass(Hello, Hello)\n    >>> ensure_subclass(object, Hello)\n    Traceback (most recent call last):\n    TypeError:"
  },
  {
    "code": "def connection_factory(self, endpoint, *args, **kwargs):\n        kwargs = self._make_connection_kwargs(endpoint, kwargs)\n        return self.connection_class.factory(endpoint, self.connect_timeout, *args, **kwargs)",
    "docstring": "Called to create a new connection with proper configuration.\n        Intended for internal use only."
  },
  {
    "code": "def metric(self):\n        if self._metric is None:\n            _log.debug(\"Computing and caching operator basis metric\")\n            self._metric = np.matrix([[(j.dag() * k).tr() for k in self.ops] for j in self.ops])\n        return self._metric",
    "docstring": "Compute a matrix of Hilbert-Schmidt inner products for the basis operators, update\n        self._metric, and return the value.\n\n        :return: The matrix of inner products.\n        :rtype: numpy.matrix"
  },
  {
    "code": "def play(self, sox_effects=()):\n    audio_data = self.getAudioData()\n    logging.getLogger().info(\"Playing speech segment (%s): '%s'\" % (self.lang, self))\n    cmd = [\"sox\", \"-q\", \"-t\", \"mp3\", \"-\"]\n    if sys.platform.startswith(\"win32\"):\n      cmd.extend((\"-t\", \"waveaudio\"))\n    cmd.extend((\"-d\", \"trim\", \"0.1\", \"reverse\", \"trim\", \"0.07\", \"reverse\"))\n    cmd.extend(sox_effects)\n    logging.getLogger().debug(\"Start player process\")\n    p = subprocess.Popen(cmd,\n                         stdin=subprocess.PIPE,\n                         stdout=subprocess.DEVNULL)\n    p.communicate(input=audio_data)\n    if p.returncode != 0:\n      raise RuntimeError()\n    logging.getLogger().debug(\"Done playing\")",
    "docstring": "Play the segment."
  },
  {
    "code": "def _construct_regex(cls, fmt):\n        return re.compile(fmt.format(**vars(cls)), flags=re.U)",
    "docstring": "Given a format string, construct the regex with class attributes."
  },
  {
    "code": "def authenticate(self, username=\"\", password=\"\", **kwargs):\n        try:\n            user = get_user_model().objects.filter(email__iexact=username)[0]\n            if check_password(password, user.password):\n                return user\n            else:\n                return None\n        except IndexError:\n            return None",
    "docstring": "Allow users to log in with their email address."
  },
  {
    "code": "def message(self):\n        name = self.__class__.__name__\n        return \"{0} {1}\".format(humanize(name),\n                                pp(*self.expectedArgs, **self.expectedKwArgs))",
    "docstring": "Override this to provide failure message"
  },
  {
    "code": "def safe_copyfile(src, dest):\n    fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(dest))\n    shutil.copyfileobj(open(src, 'rb'), os.fdopen(fd, 'wb'))\n    shutil.copystat(src, tmpname)\n    os.rename(tmpname, dest)",
    "docstring": "safely copy src to dest using a temporary intermediate and then renaming\n    to dest"
  },
  {
    "code": "def parse(content, *args, **kwargs):\r\n    global MECAB_PYTHON3\r\n    if 'mecab_loc' not in kwargs and MECAB_PYTHON3 and 'MeCab' in globals():\r\n        return MeCab.Tagger(*args).parse(content)\r\n    else:\r\n        return run_mecab_process(content, *args, **kwargs)",
    "docstring": "Use mecab-python3 by default to parse JP text. Fall back to mecab binary app if needed"
  },
  {
    "code": "def from_clock_time(cls, clock_time, epoch):\n        try:\n            clock_time = ClockTime(*clock_time)\n        except (TypeError, ValueError):\n            raise ValueError(\"Clock time must be a 2-tuple of (s, ns)\")\n        else:\n            ordinal = clock_time.seconds // 86400\n            return Date.from_ordinal(ordinal + epoch.date().to_ordinal())",
    "docstring": "Convert from a ClockTime relative to a given epoch."
  },
  {
    "code": "def get_parser():\n    from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\n    parser = ArgumentParser(description=__doc__,\n                            formatter_class=ArgumentDefaultsHelpFormatter)\n    parser.add_argument(\"-s1\", dest=\"s1\", help=\"sequence 1\")\n    parser.add_argument(\"-s2\", dest=\"s2\", help=\"sequence 2\")\n    return parser",
    "docstring": "Get a parser object"
  },
  {
    "code": "def custom(command, user=None, conf_file=None, bin_env=None):\n    ret = __salt__['cmd.run_all'](\n        _ctl_cmd(command, None, conf_file, bin_env),\n        runas=user,\n        python_shell=False,\n    )\n    return _get_return(ret)",
    "docstring": "Run any custom supervisord command\n\n    user\n        user to run supervisorctl as\n    conf_file\n        path to supervisord config file\n    bin_env\n        path to supervisorctl bin or path to virtualenv with supervisor\n        installed\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' supervisord.custom \"mstop '*gunicorn*'\""
  },
  {
    "code": "def task_failure_message(task_report):\n    trace_list = traceback.format_tb(task_report['traceback'])\n    body = 'Error: task failure\\n\\n'\n    body += 'Task ID: {}\\n\\n'.format(task_report['task_id'])\n    body += 'Archive: {}\\n\\n'.format(task_report['archive'])\n    body += 'Docker image: {}\\n\\n'.format(task_report['image'])\n    body += 'Exception: {}\\n\\n'.format(task_report['exception'])\n    body += 'Traceback:\\n {} {}'.format(\n        string.join(trace_list[:-1], ''), trace_list[-1])\n    return body",
    "docstring": "Task failure message."
  },
  {
    "code": "def filter_pythons(path):\n    if not isinstance(path, vistir.compat.Path):\n        path = vistir.compat.Path(str(path))\n    if not path.is_dir():\n        return path if path_is_python(path) else None\n    return filter(path_is_python, path.iterdir())",
    "docstring": "Return all valid pythons in a given path"
  },
  {
    "code": "def _init_compile_patterns(optional_attrs):\n        attr2cmp = {}\n        if optional_attrs is None:\n            return attr2cmp\n        if 'synonym' in optional_attrs:\n            attr2cmp['synonym'] = re.compile(r'\"(\\S.*\\S)\" ([A-Z]+) (.*)\\[(.*)\\](.*)$')\n            attr2cmp['synonym nt'] = cx.namedtuple(\"synonym\", \"text scope typename dbxrefs\")\n        if 'xref' in optional_attrs:\n            attr2cmp['xref'] = re.compile(r'^(\\S+:\\s*\\S+)\\b(.*)$')\n        return attr2cmp",
    "docstring": "Compile search patterns for optional attributes if needed."
  },
  {
    "code": "def _webTranslator(store, fallback):\n    if fallback is None:\n        fallback = IWebTranslator(store, None)\n        if fallback is None:\n            warnings.warn(\n                \"No IWebTranslator plugin when creating Scrolltable - broken \"\n                \"configuration, now deprecated!  Try passing webTranslator \"\n                \"keyword argument.\", category=DeprecationWarning,\n                stacklevel=4)\n    return fallback",
    "docstring": "Discover a web translator based on an Axiom store and a specified default.\n    Prefer the specified default.\n\n    This is an implementation detail of various initializers in this module\n    which require an L{IWebTranslator} provider.  Some of those initializers\n    did not previously require a webTranslator, so this function will issue a\n    L{UserWarning} if no L{IWebTranslator} powerup exists for the given store\n    and no fallback is provided.\n\n    @param store: an L{axiom.store.Store}\n    @param fallback: a provider of L{IWebTranslator}, or None\n\n    @return: 'fallback', if it is provided, or the L{IWebTranslator} powerup on\n    'store'."
  },
  {
    "code": "def ratechangebase(self, ratefactor, current_base, new_base):\n        if self._multiplier is None:\n            self.log(logging.WARNING, \"CurrencyHandler: changing base ourselves\")\n            if Decimal(1) != self.get_ratefactor(current_base, current_base):\n                raise RuntimeError(\"CurrencyHandler: current baserate: %s not 1\" % current_base)\n            self._multiplier = Decimal(1) / self.get_ratefactor(current_base, new_base)\n        return (ratefactor * self._multiplier).quantize(Decimal(\".0001\"))",
    "docstring": "Local helper function for changing currency base, returns new rate in new base\n        Defaults to ROUND_HALF_EVEN"
  },
  {
    "code": "def _extract_peaks(specgram, neighborhood, threshold):\n    kernel = np.ones(shape=neighborhood)\n    local_averages = convolve(specgram, kernel / kernel.sum(), mode=\"constant\", cval=0)\n    floor = (1 + threshold) * local_averages\n    candidates = np.where(specgram > floor, specgram, 0)\n    local_maximums = grey_dilation(candidates, footprint=kernel)\n    peak_coords = np.argwhere(specgram == local_maximums)\n    peaks = zip(peak_coords[:, 0], peak_coords[:, 1])\n    return peaks",
    "docstring": "Partition the spectrogram into subcells and extract peaks from each\n    cell if the peak is sufficiently energetic compared to the neighborhood."
  },
  {
    "code": "def OPERATING_SYSTEM(stats, info):\n    info.append(('architecture', platform.machine().lower()))\n    info.append(('distribution',\n                 \"%s;%s\" % (platform.linux_distribution()[0:2])))\n    info.append(('system',\n                 \"%s;%s\" % (platform.system(), platform.release())))",
    "docstring": "General information about the operating system.\n\n    This is a flag you can pass to `Stats.submit()`."
  },
  {
    "code": "def coerce(self, other, is_positive=True):\n        if hasattr(other, 'get_domain') and hasattr(other, 'lower') and hasattr(other, 'upper'):\n            if self.is_domain_equal(other):\n                return other\n            else:\n                msg = \"Cannot merge partial orders with different domains!\"\n                raise CellConstructionFailure(msg)\n        if isinstance(other, LinearOrderedCell):\n            raise NotImplemented(\"Please Implement me!\")\n        domain = self.get_domain()\n        if other in domain:\n            c = self.__class__()\n            if not is_positive:\n                c.lower = set([other])\n                c.upper = set()\n            else:\n                c.upper = set([other])\n                c.lower = set()\n            return c\n        else:       \n            raise CellConstructionFailure(\"Could not coerce value that is\"+\n                    \" outside order's domain . (Other = %s) \" % (str(other),))",
    "docstring": "Only copies a pointer to the new domain's cell"
  },
  {
    "code": "def authenticate_xmpp(self):\n        self.request_sid()\n        self.log.debug('Prepare the XMPP authentication')\n        sasl = SASLClient(\n            host=self.to,\n            service='xmpp',\n            username=self.jid,\n            password=self.password\n        )\n        sasl.choose_mechanism(self.server_auth, allow_anonymous=False)\n        challenge = self.get_challenge(sasl.mechanism)\n        response = sasl.process(base64.b64decode(challenge))\n        resp_root = self.send_challenge_response(response)\n        success = self.check_authenticate_success(resp_root)\n        if success is None and\\\n                resp_root.find('{{{0}}}challenge'.format(XMPP_SASL_NS)) is not None:\n            resp_root = self.send_challenge_response('')\n            return self.check_authenticate_success(resp_root)\n        return success",
    "docstring": "Authenticate the user to the XMPP server via the BOSH connection."
  },
  {
    "code": "def _install_exception_handler(self):\n        def handler(t, value, traceback):\n            if self.args.verbose:\n                sys.__excepthook__(t, value, traceback)\n            else:\n                sys.stderr.write('%s\\n' % unicode(value).encode('utf-8'))\n        sys.excepthook = handler",
    "docstring": "Installs a replacement for sys.excepthook, which handles pretty-printing uncaught exceptions."
  },
  {
    "code": "def _serialize(\n            self,\n            array_parent,\n            value,\n            state\n    ):\n        if not value:\n            return\n        for i, item_value in enumerate(value):\n            state.push_location(self._item_processor.element_path, i)\n            item_element = self._item_processor.serialize(item_value, state)\n            array_parent.append(item_element)\n            state.pop_location()",
    "docstring": "Serialize the array value and add it to the array parent element."
  },
  {
    "code": "def _update_ssl_config(opts):\n    if opts['ssl'] in (None, False):\n        opts['ssl'] = None\n        return\n    if opts['ssl'] is True:\n        opts['ssl'] = {}\n        return\n    import ssl\n    for key, prefix in (('cert_reqs', 'CERT_'),\n                        ('ssl_version', 'PROTOCOL_')):\n        val = opts['ssl'].get(key)\n        if val is None:\n            continue\n        if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):\n            message = 'SSL option \\'{0}\\' must be set to one of the following values: \\'{1}\\'.' \\\n                    .format(key, '\\', \\''.join([val for val in dir(ssl) if val.startswith(prefix)]))\n            log.error(message)\n            raise salt.exceptions.SaltConfigurationError(message)\n        opts['ssl'][key] = getattr(ssl, val)",
    "docstring": "Resolves string names to integer constant in ssl configuration."
  },
  {
    "code": "def load(dbname):\n    db = Database(dbname)\n    tables = get_table_list(db.cur)\n    chains = 0\n    for name in tables:\n        db._traces[name] = Trace(name=name, db=db)\n        db._traces[name]._shape = get_shape(db.cur, name)\n        setattr(db, name, db._traces[name])\n        db.cur.execute('SELECT MAX(trace) FROM [%s]' % name)\n        chains = max(chains, db.cur.fetchall()[0][0] + 1)\n    db.chains = chains\n    db.trace_names = chains * [tables, ]\n    db._state_ = {}\n    return db",
    "docstring": "Load an existing SQLite database.\n\n    Return a Database instance."
  },
  {
    "code": "def _read_opt_none(self, code, *, desc):\n        _type = self._read_opt_type(code)\n        _size = self._read_unpack(1)\n        _data = self._read_fileng(_size)\n        opt = dict(\n            desc=_IPv6_Opts_NULL.get(code, desc),\n            type=_type,\n            length=_size + 2,\n            data=_data,\n        )\n        return opt",
    "docstring": "Read IPv6_Opts unassigned options.\n\n        Structure of IPv6_Opts unassigned options [RFC 8200]:\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - -\n            |  Option Type  |  Opt Data Len |  Option Data\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - -\n\n            Octets      Bits        Name                        Description\n              0           0     ipv6_opts.opt.type          Option Type\n              0           0     ipv6_opts.opt.type.value    Option Number\n              0           0     ipv6_opts.opt.type.action   Action (00-11)\n              0           2     ipv6_opts.opt.type.change   Change Flag (0/1)\n              1           8     ipv6_opts.opt.length        Length of Option Data\n              2          16     ipv6_opts.opt.data          Option Data"
  },
  {
    "code": "def get_value(self, key):\n        try:\n            return self._dictionary[key]\n        except KeyError:\n            raise ConfigurationError(\"No such key - {}\".format(key))",
    "docstring": "Get a value from the configuration."
  },
  {
    "code": "def remove_this_opinion(self,opinion_id):\n        for opi in self.get_opinions():\n            if opi.get_id() == opinion_id:\n                self.node.remove(opi.get_node())\n                break",
    "docstring": "Removes the opinion for the given opinion identifier\n        @type opinion_id: string\n        @param opinion_id: the opinion identifier to be removed"
  },
  {
    "code": "def pretty_dict_str(d, indent=2):\n    b = StringIO()\n    write_pretty_dict_str(b, d, indent=indent)\n    return b.getvalue()",
    "docstring": "shows JSON indented representation of d"
  },
  {
    "code": "def check_server(self):\n        msg = 'API server not found. Please check your API url configuration.'\n        try:\n            response = self.session.head(self.domain)\n        except Exception as e:\n            raise_from(errors.ServerError(msg), e)\n        try:\n            self._check_response(response)\n        except errors.NotFound as e:\n            raise raise_from(errors.ServerError(msg), e)",
    "docstring": "Checks if the server is reachable and throws\n        and exception if it isn't"
  },
  {
    "code": "def tabs_obsolete(physical_line):\n    r\n    indent = INDENT_REGEX.match(physical_line).group(1)\n    if '\\t' in indent:\n        return indent.index('\\t'), \"W191 indentation contains tabs\"",
    "docstring": "r\"\"\"For new projects, spaces-only are strongly recommended over tabs.\n\n    Okay: if True:\\n    return\n    W191: if True:\\n\\treturn"
  },
  {
    "code": "def init(self):\n        if not self.call_delegate('will_start_debug_core', core=self):\n            if self.halt_on_connect:\n                self.halt()\n            self._read_core_type()\n            self._check_for_fpu()\n            self.build_target_xml()\n            self.sw_bp.init()\n        self.call_delegate('did_start_debug_core', core=self)",
    "docstring": "Cortex M initialization. The bus must be accessible when this method is called."
  },
  {
    "code": "def run_epoch(self, epoch_info: EpochInfo, source: 'vel.api.Source'):\n        epoch_info.on_epoch_begin()\n        lr = epoch_info.optimizer.param_groups[-1]['lr']\n        print(\"|-------- Epoch {:06} Lr={:.6f} ----------|\".format(epoch_info.global_epoch_idx, lr))\n        self.train_epoch(epoch_info, source)\n        epoch_info.result_accumulator.freeze_results('train')\n        self.validation_epoch(epoch_info, source)\n        epoch_info.result_accumulator.freeze_results('val')\n        epoch_info.on_epoch_end()",
    "docstring": "Run full epoch of learning"
  },
  {
    "code": "def _fetch_transfer_spec(self, node_action, token, bucket_name, paths):\n        aspera_access_key, aspera_secret_key, ats_endpoint = self._get_aspera_metadata(bucket_name)\n        _headers = {'accept': \"application/json\",\n                    'Content-Type': \"application/json\"}\n        credentials = {'type': 'token',\n                       'token': {'delegated_refresh_token': token}}\n        _url = ats_endpoint\n        _headers['X-Aspera-Storage-Credentials'] = json.dumps(credentials)\n        _data = {'transfer_requests': [\n                {'transfer_request': {'paths': paths, 'tags': {'aspera': {\n                 'node': {'storage_credentials': credentials}}}}}]}\n        _session = requests.Session()\n        _response = _session.post(url=_url + \"/files/\" + node_action,\n                                  auth=(aspera_access_key, aspera_secret_key),\n                                  headers=_headers, json=_data, verify=self._config.verify_ssl)\n        return _response",
    "docstring": "make hhtp call to Aspera to fetch back trasnfer spec"
  },
  {
    "code": "def create_jinja_environment(self) -> Environment:\n        options = dict(self.jinja_options)\n        if 'autoescape' not in options:\n            options['autoescape'] = self.select_jinja_autoescape\n        if 'auto_reload' not in options:\n            options['auto_reload'] = self.config['TEMPLATES_AUTO_RELOAD'] or self.debug\n        jinja_env = self.jinja_environment(self, **options)\n        jinja_env.globals.update({\n            'config': self.config,\n            'g': g,\n            'get_flashed_messages': get_flashed_messages,\n            'request': request,\n            'session': session,\n            'url_for': url_for,\n        })\n        jinja_env.filters['tojson'] = tojson_filter\n        return jinja_env",
    "docstring": "Create and return the jinja environment.\n\n        This will create the environment based on the\n        :attr:`jinja_options` and configuration settings. The\n        environment will include the Quart globals by default."
  },
  {
    "code": "def get_workspace_disk_usage(workspace, summarize=False):\n    command = ['du', '-h']\n    if summarize:\n        command.append('-s')\n    else:\n        command.append('-a')\n    command.append(workspace)\n    disk_usage_info = subprocess.check_output(command).decode().split()\n    filesize_pairs = list(zip(disk_usage_info[::2], disk_usage_info[1::2]))\n    filesizes = []\n    for filesize_pair in filesize_pairs:\n        size, name = filesize_pair\n        filesizes.append({'name': name[len(workspace):],\n                          'size': size})\n    return filesizes",
    "docstring": "Retrieve disk usage information of a workspace."
  },
  {
    "code": "def fit(self, images, reference=None):\n        images = check_images(images)\n        reference = check_reference(images, reference)\n        def func(item):\n            key, image = item\n            return asarray([key, self._get(image, reference)])\n        transformations = images.map(func, with_keys=True).toarray()\n        if images.shape[0] == 1: \n            transformations = [transformations]\n        algorithm = self.__class__.__name__\n        return RegistrationModel(dict(transformations), algorithm=algorithm)",
    "docstring": "Estimate registration model using cross-correlation.\n\n        Use cross correlation to compute displacements between \n        images or volumes and reference. Displacements will be \n        2D for images and 3D for volumes.\n\n        Parameters\n        ----------\n        images : array-like or thunder images\n            The sequence of images / volumes to register.\n\n        reference : array-like\n            A reference image to align to."
  },
  {
    "code": "def github_request(self, path, callback, access_token=None,\n                       post_args=None, **kwargs):\n        url = self._API_URL + path\n        all_args = {}\n        if access_token:\n            all_args[\"access_token\"] = access_token\n            all_args.update(kwargs)\n        if all_args:\n            url += \"?\" + auth.urllib_parse.urlencode(all_args)\n        callback = self.async_callback(self._on_github_request, callback)\n        http = self._get_auth_http_client()\n        if post_args is not None:\n            http.fetch(url, method=\"POST\",\n                       user_agent='Tinman/Tornado',\n                       body=auth.urllib_parse.urlencode(post_args),\n                       callback=callback)\n        else:\n            http.fetch(url, user_agent='Tinman/Tornado', callback=callback)",
    "docstring": "Make a request to the GitHub API, passing in the path, a callback,\n        the access token, optional post arguments and keyword arguments to be\n        added as values in the request body or URI"
  },
  {
    "code": "def compute_threat_list_diff(\n        self,\n        threat_type,\n        constraints,\n        version_token=None,\n        retry=google.api_core.gapic_v1.method.DEFAULT,\n        timeout=google.api_core.gapic_v1.method.DEFAULT,\n        metadata=None,\n    ):\n        if \"compute_threat_list_diff\" not in self._inner_api_calls:\n            self._inner_api_calls[\n                \"compute_threat_list_diff\"\n            ] = google.api_core.gapic_v1.method.wrap_method(\n                self.transport.compute_threat_list_diff,\n                default_retry=self._method_configs[\"ComputeThreatListDiff\"].retry,\n                default_timeout=self._method_configs[\"ComputeThreatListDiff\"].timeout,\n                client_info=self._client_info,\n            )\n        request = webrisk_pb2.ComputeThreatListDiffRequest(\n            threat_type=threat_type,\n            constraints=constraints,\n            version_token=version_token,\n        )\n        return self._inner_api_calls[\"compute_threat_list_diff\"](\n            request, retry=retry, timeout=timeout, metadata=metadata\n        )",
    "docstring": "Gets the most recent threat list diffs.\n\n        Example:\n            >>> from google.cloud import webrisk_v1beta1\n            >>> from google.cloud.webrisk_v1beta1 import enums\n            >>>\n            >>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client()\n            >>>\n            >>> # TODO: Initialize `threat_type`:\n            >>> threat_type = enums.ThreatType.THREAT_TYPE_UNSPECIFIED\n            >>>\n            >>> # TODO: Initialize `constraints`:\n            >>> constraints = {}\n            >>>\n            >>> response = client.compute_threat_list_diff(threat_type, constraints)\n\n        Args:\n            threat_type (~google.cloud.webrisk_v1beta1.types.ThreatType): Required. The ThreatList to update.\n            constraints (Union[dict, ~google.cloud.webrisk_v1beta1.types.Constraints]): The constraints associated with this request.\n\n                If a dict is provided, it must be of the same form as the protobuf\n                message :class:`~google.cloud.webrisk_v1beta1.types.Constraints`\n            version_token (bytes): The current version token of the client for the requested list (the\n                client version that was received from the last successful diff).\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.webrisk_v1beta1.types.ComputeThreatListDiffResponse` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def prange(*x):\n    try:\n        root = logging.getLogger()\n        if len(root.handlers):\n            for h in root.handlers:\n                if (type(h) is logging.StreamHandler) and \\\n                        (h.level != logging.CRITICAL):\n                    from tqdm import tqdm\n                    return tqdm(range(*x))\n            return range(*x)\n        else:\n            from tqdm import tqdm\n            return tqdm(range(*x))\n    except ImportError:\n        return range(*x)",
    "docstring": "Progress bar range with `tqdm`"
  },
  {
    "code": "def _is_nanpa_number_with_national_prefix(self):\n        return (self._current_metadata.country_code == 1 and self._national_number[0] == '1' and\n                self._national_number[1] != '0' and self._national_number[1] != '1')",
    "docstring": "Returns true if the current country is a NANPA country and the\n        national number begins with the national prefix."
  },
  {
    "code": "def native_types(code):\n    out = []\n    for c in code:\n        if isconstant(c, quoted=True):\n            if isstring(c, quoted=True):\n                v = c[1:-1]\n            elif isbool(c):\n                v = to_bool(c)\n            elif isnumber(c):\n                v = c\n            else:\n                raise CompileError(\"Unknown type %s: %s\" % (type(c).__name__, c))\n            out.append(make_embedded_push(v))\n        else:\n            try:\n                out.append(instructions.lookup(c))\n            except KeyError:\n                raise CompileError(\"Unknown word '%s'\" % c)\n    return out",
    "docstring": "Convert code elements from strings to native Python types."
  },
  {
    "code": "def add_sam2rnf_parser(subparsers, subcommand, help, description, simulator_name=None):\n    parser_sam2rnf = subparsers.add_parser(subcommand, help=help, description=description)\n    parser_sam2rnf.set_defaults(func=sam2rnf)\n    parser_sam2rnf.add_argument(\n        '-s', '--sam', type=str, metavar='file', dest='sam_fn', required=True,\n        help='Input SAM/BAM with true (expected) alignments of the reads  (- for standard input).'\n    )\n    _add_shared_params(parser_sam2rnf, unmapped_switcher=True)\n    parser_sam2rnf.add_argument(\n        '-n',\n        '--simulator-name',\n        type=str,\n        metavar='str',\n        dest='simulator_name',\n        default=simulator_name,\n        help='Name of the simulator (for RNF).' if simulator_name is not None else argparse.SUPPRESS,\n    )",
    "docstring": "Add another parser for a SAM2RNF-like command.\n\n\tArgs:\n\t\tsubparsers (subparsers): File name of the genome from which read tuples are created (FASTA file).\n\t\tsimulator_name (str): Name of the simulator used in comments."
  },
  {
    "code": "def move_dir(\n    src_fs,\n    src_path,\n    dst_fs,\n    dst_path,\n    workers=0,\n):\n    def src():\n        return manage_fs(src_fs, writeable=False)\n    def dst():\n        return manage_fs(dst_fs, create=True)\n    with src() as _src_fs, dst() as _dst_fs:\n        with _src_fs.lock(), _dst_fs.lock():\n            _dst_fs.makedir(dst_path, recreate=True)\n            copy_dir(src_fs, src_path, dst_fs, dst_path, workers=workers)\n            _src_fs.removetree(src_path)",
    "docstring": "Move a directory from one filesystem to another.\n\n    Arguments:\n        src_fs (FS or str): Source filesystem (instance or URL).\n        src_path (str): Path to a directory on ``src_fs``\n        dst_fs (FS or str): Destination filesystem (instance or URL).\n        dst_path (str): Path to a directory on ``dst_fs``.\n        workers (int): Use `worker` threads to copy data, or ``0`` (default) for\n            a single-threaded copy."
  },
  {
    "code": "def read_first_available_value(filename, field_name):\n    if not os.path.exists(filename):\n        return None\n    with open(filename, 'rb') as csvfile:\n        reader = csv.DictReader(csvfile)\n        for row in reader:\n            value = row.get(field_name)\n            if value:\n                return value\n    return None",
    "docstring": "Reads the first assigned value of the given field in the CSV table."
  },
  {
    "code": "def start_aeidon():\n    extensions = ['ass', 'srt', 'ssa', 'sub']\n    Config.filenames = prep_files(Config.args, extensions)\n    Config.patterns = pattern_logic_aeidon()\n    for filename in Config.filenames:\n        AeidonProject(filename)",
    "docstring": "Prepare filenames and patterns then process subtitles with aeidon."
  },
  {
    "code": "def ColorWithLightness(self, lightness):\n    h, s, l = self.__hsl\n    return Color((h, s, lightness), 'hsl', self.__a, self.__wref)",
    "docstring": "Create a new instance based on this one with a new lightness value.\n\n    Parameters:\n      :lightness:\n        The lightness of the new color [0...1].\n\n    Returns:\n      A grapefruit.Color instance.\n\n    >>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25)\n    (0.5, 0.25, 0.0, 1.0)\n    >>> Color.NewFromHsl(30, 1, 0.5).ColorWithLightness(0.25).hsl\n    (30, 1, 0.25)"
  },
  {
    "code": "def return_error(self, status, payload=None):\n        resp = None\n        if payload is not None:\n            payload = json.dumps(payload)\n            resp = self.make_response(payload, status=status)\n        if status in [405]:\n            abort(status)\n        else:\n            abort(status, response=resp)",
    "docstring": "Error handler called by request handlers when an error occurs and the request\n        should be aborted.\n\n        Usage::\n\n            def handle_post_request(self, *args, **kwargs):\n\n                self.request_handler = self.get_request_handler()\n                try:\n                    self.request_handler.process(self.get_data())\n                except SomeException as e:\n                    self.return_error(400, payload=self.request_handler.errors)\n\n                return self.return_create_response()"
  },
  {
    "code": "def cmd(send, msg, args):\n    if not msg:\n        send(\"Google what?\")\n        return\n    key = args['config']['api']['googleapikey']\n    cx = args['config']['api']['googlesearchid']\n    data = get('https://www.googleapis.com/customsearch/v1', params={'key': key, 'cx': cx, 'q': msg}).json()\n    if 'items' not in data:\n        send(\"Google didn't say much.\")\n    else:\n        url = data['items'][0]['link']\n        send(\"Google says %s\" % url)",
    "docstring": "Googles something.\n\n    Syntax: {command} <term>"
  },
  {
    "code": "def get_input_vector(self, ind):\n        dim = self.get_dimension()\n        b = fasttext.Vector(dim)\n        self.f.getInputVector(b, ind)\n        return np.array(b)",
    "docstring": "Given an index, get the corresponding vector of the Input Matrix."
  },
  {
    "code": "def pool_to_HW(shape, data_frmt):\n    if len(shape) != 4:\n        return shape\n    if data_frmt == 'NCHW':\n        return [shape[2], shape[3]]\n    return [shape[1], shape[2]]",
    "docstring": "Convert from NHWC|NCHW => HW"
  },
  {
    "code": "def visit_while(self, node):\n        whiles = \"while %s:\\n%s\" % (node.test.accept(self), self._stmt_list(node.body))\n        if node.orelse:\n            whiles = \"%s\\nelse:\\n%s\" % (whiles, self._stmt_list(node.orelse))\n        return whiles",
    "docstring": "return an astroid.While node as string"
  },
  {
    "code": "def add_request_handler(self, request_handler):\n        if request_handler is None:\n            raise RuntimeConfigException(\n                \"Valid Request Handler instance to be provided\")\n        if not isinstance(request_handler, AbstractRequestHandler):\n            raise RuntimeConfigException(\n                \"Input should be a RequestHandler instance\")\n        self.request_handler_chains.append(GenericRequestHandlerChain(\n            request_handler=request_handler))",
    "docstring": "Register input to the request handlers list.\n\n        :param request_handler: Request Handler instance to be\n            registered.\n        :type request_handler: AbstractRequestHandler\n        :return: None"
  },
  {
    "code": "def run(self):\n        try:\n            chunk_index = self.chunk_index_gen(self.array.shape,\n                                               self.iteration_order)\n            for key in chunk_index:\n                if self.masked:\n                    data = self.array[key].masked_array()\n                else:\n                    data = self.array[key].ndarray()\n                output_chunk = Chunk(key, data)\n                self.output(output_chunk)\n        except:\n            self.abort()\n            raise\n        else:\n            for queue in self.output_queues:\n                queue.put(QUEUE_FINISHED)",
    "docstring": "Emit the Chunk instances which cover the underlying Array.\n\n        The Array is divided into chunks with a size limit of\n        MAX_CHUNK_SIZE which are emitted into all registered output\n        queues."
  },
  {
    "code": "def register(self, table):\n        if table.table_type.is_system:\n            raise ValueError('Cannot add system table to catalog')\n        if not table.table_type.is_shared:\n            raise ValueError('Cannot add local table to catalog')\n        if table.is_substitute:\n            raise ValueError('Cannot add substitute table to catalog')\n        versions = self.__tables.get(table.name)\n        if versions is None:\n            versions = {}\n            self.__tables[table.name] = versions\n        versions[table.version] = table",
    "docstring": "Adds a shared table to the catalog.\n\n        Args:\n            table (SymbolTable): A non-system, shared symbol table."
  },
  {
    "code": "def serial_adapters(self, serial_adapters):\n        self._serial_adapters.clear()\n        for _ in range(0, serial_adapters):\n            self._serial_adapters.append(SerialAdapter(interfaces=4))\n        log.info('IOU \"{name}\" [{id}]: number of Serial adapters changed to {adapters}'.format(name=self._name,\n                                                                                               id=self._id,\n                                                                                               adapters=len(self._serial_adapters)))\n        self._adapters = self._ethernet_adapters + self._serial_adapters",
    "docstring": "Sets the number of Serial adapters for this IOU VM.\n\n        :param serial_adapters: number of adapters"
  },
  {
    "code": "def delete_collection(self, collection):\n        uri = str.join('/', [self.uri, collection])\n        return self.service._delete(uri)",
    "docstring": "Deletes an existing collection.\n\n        The collection being updated *is* expected to include the id."
  },
  {
    "code": "def RetrieveAsset(logdir, plugin_name, asset_name):\n  asset_path = os.path.join(PluginDirectory(logdir, plugin_name), asset_name)\n  try:\n    with tf.io.gfile.GFile(asset_path, \"r\") as f:\n      return f.read()\n  except tf.errors.NotFoundError:\n    raise KeyError(\"Asset path %s not found\" % asset_path)\n  except tf.errors.OpError as e:\n    raise KeyError(\"Couldn't read asset path: %s, OpError %s\" % (asset_path, e))",
    "docstring": "Retrieve a particular plugin asset from a logdir.\n\n  Args:\n    logdir: A directory that was created by a TensorFlow summary.FileWriter.\n    plugin_name: The plugin we want an asset from.\n    asset_name: The name of the requested asset.\n\n  Returns:\n    string contents of the plugin asset.\n\n  Raises:\n    KeyError: if the asset does not exist."
  },
  {
    "code": "def extract_paths(self, paths, ignore_nopath):\n        try:\n            super().extract_paths(\n                paths=paths,\n                ignore_nopath=ignore_nopath,\n            )\n        except ExtractPathError as err:\n            LOGGER.debug(\n                '%s: failed extracting files: %s', self.vm.name(), err.message\n            )\n            if self._has_guestfs:\n                self.extract_paths_dead(paths, ignore_nopath)\n            else:\n                raise",
    "docstring": "Extract the given paths from the domain\n\n        Attempt to extract all files defined in ``paths`` with the method\n        defined in :func:`~lago.plugins.vm.VMProviderPlugin.extract_paths`,\n        if it fails, and `guestfs` is available it will try extracting the\n        files with guestfs.\n\n        Args:\n            paths(list of tuples): files to extract in\n                `[(src1, dst1), (src2, dst2)...]` format.\n            ignore_nopath(boolean): if True will ignore none existing paths.\n\n        Returns:\n            None\n\n        Raises:\n            :exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing\n                path was found on the VM, and `ignore_nopath` is False.\n            :exc:`~lago.plugins.vm.ExtractPathError`: on all other failures."
  },
  {
    "code": "def useThis(self, *args, **kwargs):\n        self._callback = functools.partial(self._callback, *args, **kwargs)",
    "docstring": "Change parameter of the callback function.\n\n        :param *args, **kwargs: parameter(s) to use when executing the\n         callback function."
  },
  {
    "code": "def show_diff(before_editing, after_editing):\n    def listify(string):\n        return [l+'\\n' for l in string.rstrip('\\n').split('\\n')]\n    unified_diff = difflib.unified_diff(listify(before_editing), listify(after_editing))\n    if sys.stdout.isatty():\n        buf = io.StringIO()\n        for line in unified_diff:\n            buf.write(text_type(line))\n        buf.seek(0)\n        class opts:\n            side_by_side = False\n            width = 80\n            tab_width = 8\n        cdiff.markup_to_pager(cdiff.PatchStream(buf), opts)\n    else:\n        for line in unified_diff:\n            click.echo(line.rstrip('\\n'))",
    "docstring": "Shows a diff between two strings.\n\n    If the output is to a tty the diff will be colored. Inputs are expected to be unicode strings."
  },
  {
    "code": "def namespace_uri(self):\n        try:\n            return next(\n                iter(filter(lambda uri: URI(uri).namespace, self._uri))\n            )\n        except StopIteration:\n            return None",
    "docstring": "Finds and returns first applied URI of this node that has a namespace.\n\n        :return str: uri"
  },
  {
    "code": "def params(self):\n        params, complex = self.get_params()\n        url_params = self.default_params.copy()\n        url_params.update(self.serialize_params(params, complex))\n        return url_params",
    "docstring": "URL parameters for wq.io.loaders.NetLoader"
  },
  {
    "code": "def load_ipython_extension(ipython):\n    from google.cloud.bigquery.magics import _cell_magic\n    ipython.register_magic_function(\n        _cell_magic, magic_kind=\"cell\", magic_name=\"bigquery\"\n    )",
    "docstring": "Called by IPython when this module is loaded as an IPython extension."
  },
  {
    "code": "def _create_local_driver(self):\n        driver_type = self.config.get('Driver', 'type')\n        driver_name = driver_type.split('-')[0]\n        if driver_name in ('android', 'ios', 'iphone'):\n            driver = self._setup_appium()\n        else:\n            driver_setup = {\n                'firefox': self._setup_firefox,\n                'chrome': self._setup_chrome,\n                'safari': self._setup_safari,\n                'opera': self._setup_opera,\n                'iexplore': self._setup_explorer,\n                'edge': self._setup_edge,\n                'phantomjs': self._setup_phantomjs\n            }\n            driver_setup_method = driver_setup.get(driver_name)\n            if not driver_setup_method:\n                raise Exception('Unknown driver {0}'.format(driver_name))\n            capabilities = self._get_capabilities_from_driver_type(driver_name)\n            self._add_capabilities_from_properties(capabilities, 'Capabilities')\n            driver = driver_setup_method(capabilities)\n        return driver",
    "docstring": "Create a driver in local machine\n\n        :returns: a new local selenium driver"
  },
  {
    "code": "def fro(self, statement):\n        if not self.name_format:\n            return self.fail_safe_fro(statement)\n        result = {}\n        for attribute in statement.attribute:\n            if attribute.name_format and self.name_format and \\\n                    attribute.name_format != self.name_format:\n                continue\n            try:\n                (key, val) = self.ava_from(attribute)\n            except (KeyError, AttributeError):\n                pass\n            else:\n                result[key] = val\n        return result",
    "docstring": "Get the attributes and the attribute values.\n\n        :param statement: The AttributeStatement.\n        :return: A dictionary containing attributes and values"
  },
  {
    "code": "def reset(self, clear=False):\n        if self._executing:\n            self._executing = False\n            self._request_info['execute'] = {}\n        self._reading = False\n        self._highlighter.highlighting_on = False\n        if clear:\n            self._control.clear()\n            if self._display_banner:\n                if self.kernel_banner:\n                    self._append_plain_text(self.kernel_banner)\n                self._append_plain_text(self.banner)\n        self._show_interpreter_prompt()",
    "docstring": "Overridden to customize the order that the banners are printed"
  },
  {
    "code": "def xor(a, b):\n        return bytearray(i ^ j for i, j in zip(a, b))",
    "docstring": "Bitwise xor on equal length bytearrays."
  },
  {
    "code": "def add_column(filename,column,formula,force=False):\n    columns = parse_formula(formula)\n    logger.info(\"Running file: %s\"%filename)\n    logger.debug(\"  Reading columns: %s\"%columns)\n    data = fitsio.read(filename,columns=columns)\n    logger.debug('  Evaluating formula: %s'%formula)\n    col = eval(formula)\n    col = np.asarray(col,dtype=[(column,col.dtype)])\n    insert_columns(filename,col,force=force)\n    return True",
    "docstring": "Add a column to a FITS file.\n\n    ADW: Could this be replaced by a ftool?"
  },
  {
    "code": "def check_buffer(coords, length, buffer):\n    s = min(coords[0], buffer)\n    e = min(length - coords[1], buffer)\n    return [s, e]",
    "docstring": "check to see how much of the buffer is being used"
  },
  {
    "code": "def history_search_backward(self, e):\n        u\n        self.l_buffer=self._history.history_search_backward(self.l_buffer)",
    "docstring": "u'''Search backward through the history for the string of characters\r\n        between the start of the current line and the point. This is a\r\n        non-incremental search. By default, this command is unbound."
  },
  {
    "code": "def calc_bin(self, _bin=None):\n        if _bin is None:\n            try:\n                _bin = bins.bins(self.start, self.end, one=True)\n            except TypeError:\n                _bin = None\n        return _bin",
    "docstring": "Calculate the smallest UCSC genomic bin that will contain this feature."
  },
  {
    "code": "def get_endpoints_using_raw_json_emission(domain):\n    uri = \"http://{0}/data.json\".format(domain)\n    r = requests.get(uri)\n    r.raise_for_status()\n    return r.json()",
    "docstring": "Implements a raw HTTP GET against the entire Socrata portal for the domain in question. This method uses the\n    first of the two ways of getting this information, the raw JSON endpoint.\n\n    Parameters\n    ----------\n    domain: str\n        A Socrata data portal domain. \"data.seattle.gov\" or \"data.cityofnewyork.us\" for example.\n\n    Returns\n    -------\n    Portal dataset metadata from the JSON endpoint."
  },
  {
    "code": "def encode(cinfo, cio, image):\n    argtypes = [ctypes.POINTER(CompressionInfoType),\n                ctypes.POINTER(CioType),\n                ctypes.POINTER(ImageType)]\n    OPENJPEG.opj_encode.argtypes = argtypes\n    OPENJPEG.opj_encode.restype = ctypes.c_int\n    status = OPENJPEG.opj_encode(cinfo, cio, image)\n    return status",
    "docstring": "Wrapper for openjpeg library function opj_encode.\n\n    Encodes an image into a JPEG-2000 codestream.\n\n    Parameters\n    ----------\n    cinfo : compression handle\n\n    cio : output buffer stream\n\n    image : image to encode"
  },
  {
    "code": "def _joint_log_likelihood(self, X):\n        check_is_fitted(self, \"classes_\")\n        X = check_array(X, accept_sparse='csr')\n        X_bin = self._transform_data(X)\n        n_classes, n_features = self.feature_log_prob_.shape\n        n_samples, n_features_X = X_bin.shape\n        if n_features_X != n_features:\n            raise ValueError(\n                \"Expected input with %d features, got %d instead\" %\n                (n_features, n_features_X))\n        jll = safe_sparse_dot(X_bin, self.feature_log_prob_.T)\n        jll += self.class_log_prior_\n        return jll",
    "docstring": "Calculate the posterior log probability of the samples X"
  },
  {
    "code": "def rhsm_register(self, rhsm):\n        login = rhsm.get('login')\n        password = rhsm.get('password', os.environ.get('RHN_PW'))\n        pool_id = rhsm.get('pool_id')\n        self.run('rm /etc/pki/product/69.pem', ignore_error=True)\n        custom_log = 'subscription-manager register --username %s --password *******' % login\n        self.run(\n            'subscription-manager register --username %s --password \"%s\"' % (\n                login, password),\n            success_status=(0, 64),\n            custom_log=custom_log,\n            retry=3)\n        if pool_id:\n            self.run('subscription-manager attach --pool %s' % pool_id)\n        else:\n            self.run('subscription-manager attach --auto')\n        self.rhsm_active = True",
    "docstring": "Register the host on the RHSM.\n\n        :param rhsm: a dict of parameters (login, password, pool_id)"
  },
  {
    "code": "def allowed_methods(self, path_info=None):\n        try:\n            self.match(path_info, method=\"--\")\n        except MethodNotAllowed as e:\n            return e.valid_methods\n        except HTTPException:\n            pass\n        return []",
    "docstring": "Returns the valid methods that match for a given path.\n\n        .. versionadded:: 0.7"
  },
  {
    "code": "def _patch_expand_path(self, settings, name, value):\n        if os.path.isabs(value):\n            return os.path.normpath(value)\n        value = os.path.expanduser(value)\n        if not os.path.isabs(value) and self.projectdir:\n            value = os.path.join(self.projectdir, value)\n        return os.path.normpath(value)",
    "docstring": "Patch a path to expand home directory and make absolute path.\n\n        Args:\n            settings (dict): Current settings.\n            name (str): Setting name.\n            value (str): Path to patch.\n\n        Returns:\n            str: Patched path to an absolute path."
  },
  {
    "code": "def set_layout_settings(self, settings):\r\n        size = settings.get('size')\r\n        if size is not None:\r\n            self.resize( QSize(*size) )\r\n            self.window_size = self.size()\r\n        pos = settings.get('pos')\r\n        if pos is not None:\r\n            self.move( QPoint(*pos) )\r\n        hexstate = settings.get('hexstate')\r\n        if hexstate is not None:\r\n            self.restoreState( QByteArray().fromHex(\r\n                    str(hexstate).encode('utf-8')) )\r\n        if settings.get('is_maximized'):\r\n            self.setWindowState(Qt.WindowMaximized)\r\n        if settings.get('is_fullscreen'):\r\n            self.setWindowState(Qt.WindowFullScreen)\r\n        splitsettings = settings.get('splitsettings')\r\n        if splitsettings is not None:\r\n            self.editorwidget.editorsplitter.set_layout_settings(splitsettings)",
    "docstring": "Restore layout state"
  },
  {
    "code": "def add_entries_to_gallery(app, doctree, docname):\n    if docname != 'gallery':\n        return\n    if not has_gallery(app.builder.name):\n        return\n    try:\n        node = doctree.traverse(gallery)[0]\n    except TypeError:\n        return\n    content = []\n    for entry in app.env.gallery_entries:\n        raw_html_node = nodes.raw('', text=entry.html, format='html')\n        content.append(raw_html_node)\n    node.replace_self(content)",
    "docstring": "Add entries to the gallery node\n\n    Should happen when all the doctrees have been read\n    and the gallery entries have been collected. i.e at\n    doctree-resolved time."
  },
  {
    "code": "def open_python(self, message, namespace):\n        from code import InteractiveConsole\n        import readline\n        import rlcompleter\n        readline.set_completer(rlcompleter.Completer(namespace).complete)\n        readline.parse_and_bind('tab: complete')\n        console = InteractiveConsole(namespace)\n        console.interact(message)",
    "docstring": "Open interactive python console"
  },
  {
    "code": "def get_product_version(path: typing.Union[str, Path]) -> VersionInfo:\n    path = Path(path).absolute()\n    pe_info = pefile.PE(str(path))\n    try:\n        for file_info in pe_info.FileInfo:\n            if isinstance(file_info, list):\n                result = _parse_file_info(file_info)\n                if result:\n                    return result\n            else:\n                result = _parse_file_info(pe_info.FileInfo)\n                if result:\n                    return result\n        raise RuntimeError(f'unable to obtain version from {path}')\n    except (KeyError, AttributeError) as exc:\n        traceback.print_exc()\n        raise RuntimeError(f'unable to obtain version from {path}') from exc",
    "docstring": "Get version info from executable\n\n    Args:\n        path: path to the executable\n\n    Returns: VersionInfo"
  },
  {
    "code": "def append(self, function, update=True):\n        self._funcs.append(function)\n        self._add_dep(function)\n        if update:\n            self._update()",
    "docstring": "Append a new function to the end of this chain."
  },
  {
    "code": "def encodeMsg(self, mesg):\n        fmt = self.locs.get('log:fmt')\n        if fmt == 'jsonl':\n            s = json.dumps(mesg, sort_keys=True) + '\\n'\n            buf = s.encode()\n            return buf\n        elif fmt == 'mpk':\n            buf = s_msgpack.en(mesg)\n            return buf\n        mesg = f'Unknown encoding format: {fmt}'\n        raise s_exc.SynErr(mesg=mesg)",
    "docstring": "Get byts for a message"
  },
  {
    "code": "def load_embedding(path):\n    EMBEDDING_DIM = 300\n    embedding_dict = {}\n    with open(path, 'r', encoding='utf-8') as file:\n        pairs = [line.strip('\\r\\n').split() for line in file.readlines()]\n        for pair in pairs:\n            if len(pair) == EMBEDDING_DIM + 1:\n                embedding_dict[pair[0]] = [float(x) for x in pair[1:]]\n    logger.debug('embedding_dict size: %d', len(embedding_dict))\n    return embedding_dict",
    "docstring": "return embedding for a specific file by given file path."
  },
  {
    "code": "def _is_modified(self, filepath):\n        if self._is_new(filepath):\n            return False\n        mtime = self._get_modified_time(filepath)\n        return self._watched_files[filepath] < mtime",
    "docstring": "Returns True if the file has been modified since last seen.\n        Will return False if the file has not been seen before."
  },
  {
    "code": "def setup_logfile_raw(self, logfile, mode='w'):\n        self.logfile_raw = open(logfile, mode=mode)",
    "docstring": "start logging raw bytes to the given logfile, without timestamps"
  },
  {
    "code": "def status(self):\n        if self.report == None:\n            return SentSms.ENROUTE\n        else:\n            return SentSms.DELIVERED if self.report.deliveryStatus == StatusReport.DELIVERED else SentSms.FAILED",
    "docstring": "Status of this SMS. Can be ENROUTE, DELIVERED or FAILED\n        \n        The actual status report object may be accessed via the 'report' attribute\n        if status is 'DELIVERED' or 'FAILED'"
  },
  {
    "code": "def declare_param(self, id_, lineno, type_=None):\n        if not self.check_is_undeclared(id_, lineno, classname='parameter',\n                                        scope=self.current_scope, show_error=True):\n            return None\n        entry = self.declare(id_, lineno, symbols.PARAMDECL(id_, lineno, type_))\n        if entry is None:\n            return\n        entry.declared = True\n        if entry.type_.implicit:\n            warning_implicit_type(lineno, id_, type_)\n        return entry",
    "docstring": "Declares a parameter\n        Check if entry.declared is False. Otherwise raises an error."
  },
  {
    "code": "def html_to_xhtml(html_unicode_string):\n    try:\n        assert isinstance(html_unicode_string, basestring)\n    except AssertionError:\n        raise TypeError\n    root = BeautifulSoup(html_unicode_string, 'html.parser')\n    try:\n        assert root.html is not None\n    except AssertionError:\n        raise ValueError(''.join(['html_unicode_string cannot be a fragment.',\n                         'string is the following: %s', unicode(root)]))\n    root.html['xmlns'] = 'http://www.w3.org/1999/xhtml'\n    unicode_string = unicode(root.prettify(encoding='utf-8', formatter='html'), encoding='utf-8')\n    for tag in constants.SINGLETON_TAG_LIST:\n        unicode_string = unicode_string.replace(\n                '<' + tag + '/>',\n                '<' + tag + ' />')\n    return unicode_string",
    "docstring": "Converts html to xhtml\n\n    Args:\n        html_unicode_string: A (possible unicode) string representing HTML.\n\n    Returns:\n        A (possibly unicode) string representing XHTML.\n\n    Raises:\n        TypeError: Raised if input_string isn't a unicode string or string."
  },
  {
    "code": "def layers(self, rev=True):\n        image_layers = [\n            PodmanImage(None, identifier=x, pull_policy=PodmanImagePullPolicy.NEVER)\n            for x in self.get_layer_ids()\n        ]\n        if not rev:\n            image_layers.reverse()\n        return image_layers",
    "docstring": "Get list of PodmanImage for every layer in image\n\n        :param rev: get layers rev\n        :return: list of :class:`conu.PodmanImage`"
  },
  {
    "code": "def copy(self):\n        copyClass = self.copyClass\n        if copyClass is None:\n            copyClass = self.__class__\n        copied = copyClass()\n        copied.copyData(self)\n        return copied",
    "docstring": "Copy this object into a new object of the same type.\n        The returned object will not have a parent object."
  },
  {
    "code": "def tsiterator(ts, dateconverter=None, desc=None,\n               clean=False, start_value=None, **kwargs):\n    dateconverter = dateconverter or default_converter\n    yield ['Date'] + ts.names()\n    if clean == 'full':\n        for dt, value in full_clean(ts, dateconverter, desc, start_value):\n             yield (dt,) + tuple(value)\n    else:\n        if clean:\n            ts = ts.clean()\n        for dt, value in ts.items(desc=desc, start_value=start_value):\n            dt = dateconverter(dt)\n            yield (dt,) + tuple(value)",
    "docstring": "An iterator of timeseries as tuples."
  },
  {
    "code": "def add_args(parser, positional=False):\n    group = parser.add_argument_group(\"read loading\")\n    group.add_argument(\"reads\" if positional else \"--reads\",\n        nargs=\"+\", default=[],\n        help=\"Paths to bam files. Any number of paths may be specified.\")\n    group.add_argument(\n        \"--read-source-name\",\n        nargs=\"+\",\n        help=\"Names for each read source. The number of names specified \"\n        \"must match the number of bam files. If not specified, filenames are \"\n        \"used for names.\")\n    group = parser.add_argument_group(\n        \"read filtering\",\n        \"A number of read filters are available. See the pysam \"\n        \"documentation (http://pysam.readthedocs.org/en/latest/api.html) \"\n        \"for details on what these fields mean. When multiple filter \"\n        \"options are specified, reads must match *all* filters.\")\n    for (name, (kind, message, function)) in READ_FILTERS.items():\n        extra = {}\n        if kind is bool:\n            extra[\"action\"] = \"store_true\"\n            extra[\"default\"] = None\n        elif kind is int:\n            extra[\"type\"] = int\n            extra[\"metavar\"] = \"N\"\n        elif kind is str:\n            extra[\"metavar\"] = \"STRING\"\n        group.add_argument(\"--\" + name.replace(\"_\", \"-\"),\n            help=message,\n            **extra)",
    "docstring": "Extends a commandline argument parser with arguments for specifying\n    read sources."
  },
  {
    "code": "def enum(self):\n        value = self._schema.get(\"enum\", None)\n        if value is None:\n            return\n        if not isinstance(value, list):\n            raise SchemaError(\n                \"enum value {0!r} is not a list\".format(value))\n        if len(value) == 0:\n            raise SchemaError(\n                \"enum value {0!r} does not contain any\"\n                \" elements\".format(value))\n        seen = set()\n        for item in value:\n            if item in seen:\n                raise SchemaError(\n                    \"enum value {0!r} contains duplicate element\"\n                    \" {1!r}\".format(value, item))\n            else:\n                seen.add(item)\n        return value",
    "docstring": "Enumeration of allowed object values.\n\n        The enumeration must not contain duplicates."
  },
  {
    "code": "def append_json(\n            self,\n            obj: Any,\n            headers: Optional['MultiMapping[str]']=None\n    ) -> Payload:\n        if headers is None:\n            headers = CIMultiDict()\n        return self.append_payload(JsonPayload(obj, headers=headers))",
    "docstring": "Helper to append JSON part."
  },
  {
    "code": "def select(self, *properties, **aliased_properties):\n        if not (properties or aliased_properties):\n            return self\n        merged_properties = dict(zip(properties, properties))\n        merged_properties.update(aliased_properties)\n        for prop_name in (merged_properties.keys()):\n            if prop_name in self.selection:\n                raise Exception('The property {} has already been selected'.format(prop_name))\n        new_selection = self.selection.copy()\n        new_selection.update(merged_properties)\n        return self._copy(selection=new_selection)",
    "docstring": "Specify which properties of the dataset must be returned\n\n        Property extraction is based on `JMESPath <http://jmespath.org>`_ expressions.\n        This method returns a new Dataset narrowed down by the given selection.\n\n        :param properties: JMESPath to use for the property extraction.\n                           The JMESPath string will be used as a key in the output dictionary.\n        :param aliased_properties: Same as properties, but the output dictionary will contain\n                                   the parameter name instead of the JMESPath string."
  },
  {
    "code": "def getEvoBibAsBibtex(*keys, **kw):\n    res = []\n    for key in keys:\n        bib = get_url(\n            \"http://bibliography.lingpy.org/raw.php?key=\" + key,\n            log=kw.get('log')).text\n        try:\n            res.append('@' + bib.split('@')[1].split('</pre>')[0])\n        except IndexError:\n            res.append('@misc{' + key + ',\\nNote={missing source}\\n\\n}')\n    return '\\n\\n'.join(res)",
    "docstring": "Download bibtex format and parse it from EvoBib"
  },
  {
    "code": "def _charInfo(self, point, padding):\n        print('{0:0>4X} '.format(point).rjust(padding), ud.name(chr(point), '<code point {0:0>4X}>'.format(point)))",
    "docstring": "Displays character info."
  },
  {
    "code": "def get_recursive_subclasses(cls):\n    return cls.__subclasses__() + [g for s in cls.__subclasses__() for g in get_recursive_subclasses(s)]",
    "docstring": "Return list of all subclasses for a class, including subclasses of direct subclasses"
  },
  {
    "code": "def fit_transform(self, input, **fit_kwargs):\n        self.fit(input, **fit_kwargs)\n        X = self.transform(input)\n        return X",
    "docstring": "Execute fit and transform in sequence."
  },
  {
    "code": "def cybox_valueset_fact_handler(self, enrichment, fact, attr_info, add_fact_kargs):\n        value_list = attr_info['value_set'][fact['node_id']].split(\",\")\n        value_list = map(lambda x: x.strip(), value_list)\n        add_fact_kargs['values'] = value_list\n        return True",
    "docstring": "Handler for dealing with 'value_set' values.\n\n        Unfortunately, CybOX et al. sometimes use comma-separated\n        value lists rather than an XML structure that can contain\n        several values.\n\n        This handler is called for elements concerning a value-set\n        such as the following example::\n\n            <URIObj:Value condition=\"IsInSet\"\n            value_set=\"www.sample1.com/index.html, sample2.com/login.html, dev.sample3.com/index/kb.html\"\n            datatype=\"AnyURI\"/>"
  },
  {
    "code": "def update_wrapper(self, process_list):\n        self.set_count(len(process_list))\n        if self.should_update():\n            return self.update(process_list)\n        else:\n            return self.result()",
    "docstring": "Wrapper for the children update"
  },
  {
    "code": "def index(obj, index=INDEX_NAME, doc_type=DOC_TYPE):\n    doc = to_dict(obj)\n    if doc is None:\n        return\n    id = doc.pop('id')\n    return es_conn.index(index, doc_type, doc, id=id)",
    "docstring": "Index the given document.\n\n    https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.index\n    https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html"
  },
  {
    "code": "def upload(self, filename, directory=None):\n        filename = eval_path(filename)\n        if directory is None:\n            directory = self.downloads_directory\n        res1 = self._req_upload(filename, directory)\n        data1 = res1['data']\n        file_id = data1['file_id']\n        res2 = self._req_file(file_id)\n        data2 = res2['data'][0]\n        data2.update(**data1)\n        return _instantiate_uploaded_file(self, data2)",
    "docstring": "Upload a file ``filename`` to ``directory``\n\n        :param str filename: path to the file to upload\n        :param directory: destionation :class:`.Directory`, defaults to\n            :attribute:`.API.downloads_directory` if None\n        :return: the uploaded file\n        :rtype: :class:`.File`"
  },
  {
    "code": "def modifyInPlace(self, *, sort=None, purge=False, done=None):\n        self.data = self.modify(sort=sort, purge=purge, done=done)",
    "docstring": "Like Model.modify, but changes existing database instead of\n        returning a new one."
  },
  {
    "code": "def apply(coro, *args, **kw):\n    assert_corofunction(coro=coro)\n    @asyncio.coroutine\n    def wrapper(*_args, **_kw):\n        return (yield from coro(*args, **kw))\n    return wrapper",
    "docstring": "Creates a continuation coroutine function with some arguments\n    already applied.\n\n    Useful as a shorthand when combined with other control flow functions.\n    Any arguments passed to the returned function are added to the arguments\n    originally passed to apply.\n\n    This is similar to `paco.partial()`.\n\n    This function can be used as decorator.\n\n    arguments:\n        coro (coroutinefunction): coroutine function to wrap.\n        *args (mixed): mixed variadic arguments for partial application.\n        *kwargs (mixed): mixed variadic keyword arguments for partial\n            application.\n\n    Raises:\n        TypeError: if coro argument is not a coroutine function.\n\n    Returns:\n        coroutinefunction: wrapped coroutine function.\n\n    Usage::\n\n        async def hello(name, mark='!'):\n            print('Hello, {name}{mark}'.format(name=name, mark=mark))\n\n        hello_mike = paco.apply(hello, 'Mike')\n        await hello_mike()\n        # => Hello, Mike!\n\n        hello_mike = paco.apply(hello, 'Mike', mark='?')\n        await hello_mike()\n        # => Hello, Mike?"
  },
  {
    "code": "def document_create(index, doc_type, body=None, id=None, hosts=None, profile=None, source=None):\n    es = _get_instance(hosts, profile)\n    if source and body:\n        message = 'Either body or source should be specified but not both.'\n        raise SaltInvocationError(message)\n    if source:\n        body = __salt__['cp.get_file_str'](\n                  source,\n                  saltenv=__opts__.get('saltenv', 'base'))\n    try:\n        return es.index(index=index, doc_type=doc_type, body=body, id=id)\n    except elasticsearch.TransportError as e:\n        raise CommandExecutionError(\"Cannot create document in index {0}, server returned code {1} with message {2}\".format(index, e.status_code, e.error))",
    "docstring": "Create a document in a specified index\n\n    index\n        Index name where the document should reside\n    doc_type\n        Type of the document\n    body\n        Document to store\n    source\n        URL of file specifying document to store. Cannot be used in combination with ``body``.\n    id\n        Optional unique document identifier for specified doc_type (empty for random)\n\n    CLI example::\n\n        salt myminion elasticsearch.document_create testindex doctype1 '{}'"
  },
  {
    "code": "def max_enrichment(fg_vals, bg_vals, minbg=2):\n    scores = np.hstack((fg_vals, bg_vals))\n    idx = np.argsort(scores)\n    x = np.hstack((np.ones(len(fg_vals)), np.zeros(len(bg_vals))))\n    xsort = x[idx]\n    l_fg = len(fg_vals)\n    l_bg = len(bg_vals)\n    m = 0\n    s = 0\n    for i in range(len(scores), 0, -1):\n        bgcount = float(len(xsort[i:][xsort[i:] == 0])) \n        if bgcount >= minbg:\n            enr = (len(xsort[i:][xsort[i:] == 1]) / l_fg) / (bgcount / l_bg)\n            if enr > m:\n                m = enr\n                s = scores[idx[i]]\n    return m",
    "docstring": "Computes the maximum enrichment.\n\n    Parameters\n    ----------\n    fg_vals : array_like\n        The list of values for the positive set.\n\n    bg_vals : array_like\n        The list of values for the negative set.\n    \n    minbg : int, optional\n        Minimum number of matches in background. The default is 2.\n    \n    Returns\n    -------\n    enrichment : float\n        Maximum enrichment."
  },
  {
    "code": "def _resolve_image(ret, image, client_timeout):\n    image_id = __salt__['docker.resolve_image_id'](image)\n    if image_id is False:\n        if not __opts__['test']:\n            try:\n                pull_result = __salt__['docker.pull'](\n                    image,\n                    client_timeout=client_timeout,\n                )\n            except Exception as exc:\n                raise CommandExecutionError(\n                    'Failed to pull {0}: {1}'.format(image, exc)\n                )\n            else:\n                ret['changes']['image'] = pull_result\n                image_id = __salt__['docker.resolve_image_id'](image)\n                if image_id is False:\n                    raise CommandExecutionError(\n                        'Image \\'{0}\\' not present despite a docker pull '\n                        'raising no errors'.format(image)\n                    )\n    return image_id",
    "docstring": "Resolve the image ID and pull the image if necessary"
  },
  {
    "code": "def create(self, friendly_name=values.unset, domain_name=values.unset,\n               disaster_recovery_url=values.unset,\n               disaster_recovery_method=values.unset, recording=values.unset,\n               secure=values.unset, cnam_lookup_enabled=values.unset):\n        data = values.of({\n            'FriendlyName': friendly_name,\n            'DomainName': domain_name,\n            'DisasterRecoveryUrl': disaster_recovery_url,\n            'DisasterRecoveryMethod': disaster_recovery_method,\n            'Recording': recording,\n            'Secure': secure,\n            'CnamLookupEnabled': cnam_lookup_enabled,\n        })\n        payload = self._version.create(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return TrunkInstance(self._version, payload, )",
    "docstring": "Create a new TrunkInstance\n\n        :param unicode friendly_name: A string to describe the resource\n        :param unicode domain_name: The unique address you reserve on Twilio to which you route your SIP traffic\n        :param unicode disaster_recovery_url: The HTTP URL that we should call if an error occurs while sending SIP traffic towards your configured Origination URL\n        :param unicode disaster_recovery_method: The HTTP method we should use to call the disaster_recovery_url\n        :param TrunkInstance.RecordingSetting recording: The recording settings for the trunk\n        :param bool secure: Whether Secure Trunking is enabled for the trunk\n        :param bool cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk\n\n        :returns: Newly created TrunkInstance\n        :rtype: twilio.rest.trunking.v1.trunk.TrunkInstance"
  },
  {
    "code": "def _fulfills_version_string(installed_versions, version_conditions_string, ignore_epoch=False, allow_updates=False):\n    version_conditions = _parse_version_string(version_conditions_string)\n    for installed_version in installed_versions:\n        fullfills_all = True\n        for operator, version_string in version_conditions:\n            if allow_updates and len(version_conditions) == 1 and operator == '==':\n                operator = '>='\n            fullfills_all = fullfills_all and _fulfills_version_spec([installed_version], operator, version_string, ignore_epoch=ignore_epoch)\n        if fullfills_all:\n            return True\n    return False",
    "docstring": "Returns True if any of the installed versions match the specified version conditions,\n    otherwise returns False.\n\n    installed_versions\n        The installed versions\n\n    version_conditions_string\n        The string containing all version conditions. E.G.\n        1.2.3-4\n        >=1.2.3-4\n        >=1.2.3-4, <2.3.4-5\n        >=1.2.3-4, <2.3.4-5, !=1.2.4-1\n\n    ignore_epoch : False\n        When a package version contains an non-zero epoch (e.g.\n        ``1:3.14.159-2.el7``, and a specific version of a package is desired,\n        set this option to ``True`` to ignore the epoch when comparing\n        versions.\n\n    allow_updates : False\n        Allow the package to be updated outside Salt's control (e.g. auto updates on Windows).\n        This means a package on the Minion can have a newer version than the latest available in\n        the repository without enforcing a re-installation of the package.\n        (Only applicable if only one strict version condition is specified E.G. version: 2.0.6~ubuntu3)"
  },
  {
    "code": "def map_nested(function, data_struct, dict_only=False, map_tuple=False):\n  if isinstance(data_struct, dict):\n    return {\n        k: map_nested(function, v, dict_only, map_tuple)\n        for k, v in data_struct.items()\n    }\n  elif not dict_only:\n    types = [list]\n    if map_tuple:\n      types.append(tuple)\n    if isinstance(data_struct, tuple(types)):\n      mapped = [map_nested(function, v, dict_only, map_tuple)\n                for v in data_struct]\n      if isinstance(data_struct, list):\n        return mapped\n      else:\n        return tuple(mapped)\n  return function(data_struct)",
    "docstring": "Apply a function recursively to each element of a nested data struct."
  },
  {
    "code": "def GetAnalyzers(cls):\n    for analyzer_name, analyzer_class in iter(cls._analyzer_classes.items()):\n      yield analyzer_name, analyzer_class",
    "docstring": "Retrieves the registered analyzers.\n\n    Yields:\n      tuple: containing:\n\n        str: the uniquely identifying name of the analyzer\n        type: the analyzer class."
  },
  {
    "code": "def initialise():\n    global settings, project_settings\n    settings = Changes.load()\n    project_settings = Project.load(GitHubRepository(auth_token=settings.auth_token))",
    "docstring": "Detects, prompts and initialises the project.\n\n    Stores project and tool configuration in the `changes` module."
  },
  {
    "code": "def full_size(self):\n        self.dragpos = wx.Point(0, 0)\n        self.zoom = 1.0\n        self.need_redraw = True",
    "docstring": "show image at full size"
  },
  {
    "code": "def make_library(self, diffuse_yaml, catalog_yaml, binning_yaml):\n        ret_dict = {}\n        components_dict = Component.build_from_yamlfile(binning_yaml)\n        diffuse_ret_dict = make_diffuse_comp_info_dict(GalpropMapManager=self._gmm,\n                                                       DiffuseModelManager=self._dmm,\n                                                       library=diffuse_yaml,\n                                                       components=components_dict)\n        catalog_ret_dict = make_catalog_comp_dict(library=catalog_yaml,\n                                                  CatalogSourceManager=self._csm)\n        ret_dict.update(diffuse_ret_dict['comp_info_dict'])\n        ret_dict.update(catalog_ret_dict['comp_info_dict'])\n        self._library.update(ret_dict)\n        return ret_dict",
    "docstring": "Build up the library of all the components\n\n        Parameters\n        ----------\n\n        diffuse_yaml : str\n            Name of the yaml file with the library of diffuse component definitions\n        catalog_yaml : str\n            Name of the yaml file width the library of catalog split definitions\n        binning_yaml : str\n            Name of the yaml file with the binning definitions"
  },
  {
    "code": "def rowsAfterValue(self, value, count):\n        if value is None:\n            query = self.inequalityQuery(None, count, True)\n        else:\n            pyvalue = self._toComparableValue(value)\n            currentSortAttribute = self.currentSortColumn.sortAttribute()\n            query = self.inequalityQuery(currentSortAttribute >= pyvalue, count, True)\n        return self.constructRows(query)",
    "docstring": "Retrieve some rows at or after a given sort-column value.\n\n        @param value: Starting value in the index for the current sort column\n        at which to start returning results.  Rows with a column value for the\n        current sort column which is greater than or equal to this value will\n        be returned.\n\n        @type value: Some type compatible with the current sort column, or\n        None, to specify the beginning of the data.\n\n        @param count: The maximum number of rows to return.\n        @type count: C{int}\n\n        @return: A list of row data, ordered by the current sort column,\n        beginning at C{value} and containing at most C{count} elements."
  },
  {
    "code": "def suspend(name, call=None):\n    if call != 'action':\n        raise SaltCloudSystemExit(\n            'The suspend action must be called with '\n            '-a or --action.'\n        )\n    vm_properties = [\n        \"name\",\n        \"summary.runtime.powerState\"\n    ]\n    vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)\n    for vm in vm_list:\n        if vm[\"name\"] == name:\n            if vm[\"summary.runtime.powerState\"] == \"poweredOff\":\n                ret = 'cannot suspend in powered off state'\n                log.info('VM %s %s', name, ret)\n                return ret\n            elif vm[\"summary.runtime.powerState\"] == \"suspended\":\n                ret = 'already suspended'\n                log.info('VM %s %s', name, ret)\n                return ret\n            try:\n                log.info('Suspending VM %s', name)\n                task = vm[\"object\"].Suspend()\n                salt.utils.vmware.wait_for_task(task, name, 'suspend')\n            except Exception as exc:\n                log.error(\n                    'Error while suspending VM %s: %s',\n                    name, exc,\n                    exc_info_on_loglevel=logging.DEBUG\n                )\n                return 'failed to suspend'\n    return 'suspended'",
    "docstring": "To suspend a VM using its name\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -a suspend vmname"
  },
  {
    "code": "def process_header(self, data):\n        metadata = {\n            \"datacolumns\": data.read_chunk(\"I\"),\n            \"firstyear\": data.read_chunk(\"I\"),\n            \"lastyear\": data.read_chunk(\"I\"),\n            \"annualsteps\": data.read_chunk(\"I\"),\n        }\n        if metadata[\"annualsteps\"] != 1:\n            raise InvalidTemporalResError(\n                \"{}: Only annual files can currently be processed\".format(self.filepath)\n            )\n        return metadata",
    "docstring": "Reads the first part of the file to get some essential metadata\n\n        # Returns\n        return (dict): the metadata in the header"
  },
  {
    "code": "def binary_to_int(binary_list, lower_bound=0, upper_bound=None):\n    if binary_list == []:\n        return lower_bound\n    else:\n        integer = int(''.join([str(bit) for bit in binary_list]), 2)\n    if (upper_bound is not None) and integer + lower_bound > upper_bound:\n        return upper_bound - (integer % (upper_bound - lower_bound + 1))\n    else:\n        return integer + lower_bound",
    "docstring": "Return the base 10 integer corresponding to a binary list.\n\n   The maximum value is determined by the number of bits in binary_list,\n   and upper_bound. The greater allowed by the two.\n\n    Args:\n        binary_list: list<int>; List of 0s and 1s.\n        lower_bound: Minimum value for output, inclusive.\n            A binary list of 0s will have this value.\n        upper_bound: Maximum value for output, inclusive.\n            If greater than this bound, we \"bounce back\".\n            Ex. w/ upper_bound = 2: [0, 1, 2, 2, 1, 0]\n            Ex.\n                raw_integer = 11, upper_bound = 10, return = 10\n                raw_integer = 12, upper_bound = 10, return = 9\n\n    Returns:\n        int; Integer value of the binary input."
  },
  {
    "code": "def quote(code):\n    try:\n        code = code.rstrip()\n    except AttributeError:\n        return code\n    if code and code[0] + code[-1] not in ('\"\"', \"''\", \"u'\", '\"') \\\n       and '\"' not in code:\n        return 'u\"' + code + '\"'\n    else:\n        return code",
    "docstring": "Returns quoted code if not already quoted and if possible\n\n    Parameters\n    ----------\n\n    code: String\n    \\tCode thta is quoted"
  },
  {
    "code": "def connect(self, peer_address):\n        self._sock.connect(peer_address)\n        peer_address = self._sock.getpeername()\n        BIO_dgram_set_connected(self._wbio.value, peer_address)\n        assert self._wbio is self._rbio\n        if self._do_handshake_on_connect:\n            self.do_handshake()",
    "docstring": "Client-side UDP connection establishment\n\n        This method connects this object's underlying socket. It subsequently\n        performs a handshake if do_handshake_on_connect was set during\n        initialization.\n\n        Arguments:\n        peer_address - address tuple of server peer"
  },
  {
    "code": "def coerce_to_synchronous(func):\n    if inspect.iscoroutinefunction(func):\n        @functools.wraps(func)\n        def sync_wrapper(*args, **kwargs):\n            loop = asyncio.get_event_loop()\n            try:\n                loop.run_until_complete(func(*args, **kwargs))\n            finally:\n                loop.close()\n        return sync_wrapper\n    return func",
    "docstring": "Given a function that might be async, wrap it in an explicit loop so it can\n    be run in a synchronous context."
  },
  {
    "code": "def git_exec(self, command, **kwargs):\n        from .cli import verbose_echo\n        command.insert(0, self.git)\n        if kwargs.pop('no_verbose', False):\n            verbose = False\n        else:\n            verbose = self.verbose\n        verbose_echo(' '.join(command), verbose, self.fake)\n        if not self.fake:\n            result = self.repo.git.execute(command, **kwargs)\n        else:\n            if 'with_extended_output' in kwargs:\n                result = (0, '', '')\n            else:\n                result = ''\n        return result",
    "docstring": "Execute git commands"
  },
  {
    "code": "def vm_config(name, main, provider, profile, overrides):\n        vm = main.copy()\n        vm = salt.utils.dictupdate.update(vm, provider)\n        vm = salt.utils.dictupdate.update(vm, profile)\n        vm.update(overrides)\n        vm['name'] = name\n        return vm",
    "docstring": "Create vm config.\n\n        :param str name: The name of the vm\n        :param dict main: The main cloud config\n        :param dict provider: The provider config\n        :param dict profile: The profile config\n        :param dict overrides: The vm's config overrides"
  },
  {
    "code": "def side_by_side(left, right):\n    r\n    left_lines = list(left.split('\\n'))\n    right_lines = list(right.split('\\n'))\n    diff = abs(len(left_lines) - len(right_lines))\n    if len(left_lines) > len(right_lines):\n        fill = ' ' * len(right_lines[0])\n        right_lines += [fill] * diff\n    elif len(right_lines) > len(left_lines):\n        fill = ' ' * len(left_lines[0])\n        left_lines += [fill] * diff\n    return '\\n'.join(a + b for a, b in zip(left_lines, right_lines)) + '\\n'",
    "docstring": "r\"\"\"Put two boxes next to each other.\n\n    Assumes that all lines in the boxes are the same width.\n\n    Example:\n        >>> left = 'A \\nC '\n        >>> right = 'B\\nD'\n        >>> print(side_by_side(left, right))\n        A B\n        C D\n        <BLANKLINE>"
  },
  {
    "code": "def setText(self, text):\n        if self.text() == text:\n            return\n        self.touch()\n        maxSize = len(self.text()) + 1\n        self.device.press('KEYCODE_DEL', adbclient.DOWN_AND_UP, repeat=maxSize)\n        self.device.press('KEYCODE_FORWARD_DEL', adbclient.DOWN_AND_UP, repeat=maxSize)\n        self.type(text, alreadyTouched=True)",
    "docstring": "This function makes sure that any previously entered text is deleted before\n        setting the value of the field."
  },
  {
    "code": "def _is_path(instance, attribute, s, exists=True):\n    \"Validator for path-yness\"\n    if not s:\n        return\n    if exists:\n        if os.path.exists(s):\n            return\n        else:\n            raise OSError(\"path does not exist\")\n    else:\n        raise TypeError(\"Not a path?\")",
    "docstring": "Validator for path-yness"
  },
  {
    "code": "def unwrap(self, value, session=None):\n        self.validate_unwrap(value)\n        ret = {}\n        for value_dict in value:\n            k = value_dict['k']\n            v = value_dict['v']\n            ret[self.key_type.unwrap(k, session=session)] = self.value_type.unwrap(v, session=session)\n        return ret",
    "docstring": "Expects a list of dictionaries with ``k`` and ``v`` set to the\n            keys and values that will be unwrapped into the output python\n            dictionary should have.  Validates the input and then constructs the\n            dictionary from the list."
  },
  {
    "code": "def convert(source, to, format=None, extra_args=(), encoding='utf-8'):\n    return _convert(\n        _read_file, _process_file,\n        source, to,\n        format, extra_args,\n        encoding=encoding)",
    "docstring": "Convert given `source` from `format` `to` another.\n\n    `source` may be either a file path or a string to be converted.\n    It's possible to pass `extra_args` if needed.  In case `format` is not\n    provided, it will try to invert the format based on given `source`.\n\n    Raises OSError if pandoc is not found! Make sure it has been installed and\n    is available at path."
  },
  {
    "code": "def add_new_entry(self, entry):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('El Torito Section Header not yet initialized')\n        self.num_section_entries += 1\n        self.section_entries.append(entry)",
    "docstring": "A method to add a completely new entry to the list of entries of this\n        header.\n\n        Parameters:\n         entry - The new EltoritoEntry object to add to the list of entries.\n        Returns:\n         Nothing."
  },
  {
    "code": "def error(self, msg, n):\n        raise SyntaxError(msg, n.lineno, n.col_offset,\n                          filename=self.compile_info.filename)",
    "docstring": "Raise a SyntaxError with the lineno and col_offset set to n's."
  },
  {
    "code": "def fetch(self, recursive=1, exclude_children=False, exclude_back_refs=False):\n        if not self.path.is_resource and not self.path.is_uuid:\n            self.check()\n        params = {}\n        if exclude_children:\n            params['exclude_children'] = True\n        if exclude_back_refs:\n            params['exclude_back_refs'] = True\n        data = self.session.get_json(self.href, **params)[self.type]\n        self.from_dict(data)\n        return self",
    "docstring": "Fetch resource from the API server\n\n        :param recursive: level of recursion for fetching resources\n        :type recursive: int\n        :param exclude_children: don't get children references\n        :type exclude_children: bool\n        :param exclude_back_refs: don't get back_refs references\n        :type exclude_back_refs: bool\n\n        :rtype: Resource"
  },
  {
    "code": "def get(self, request):\n        if not self.hosts:\n            return self._get(request.path, request.method, \"\")\n        try:\n            return self._get(\n                request.path, request.method, request.headers.get(\"Host\", \"\")\n            )\n        except NotFound:\n            return self._get(request.path, request.method, \"\")",
    "docstring": "Get a request handler based on the URL of the request, or raises an\n        error\n\n        :param request: Request object\n        :return: handler, arguments, keyword arguments"
  },
  {
    "code": "def service_start(name):\n    r = salt.utils.http.query(DETAILS['url']+'service/start/'+name, decode_type='json', decode=True)\n    return r['dict']",
    "docstring": "Start a \"service\" on the REST server"
  },
  {
    "code": "def put_json(self, url, data, cls=None, **kwargs):\n        kwargs['data'] = to_json(data, cls=cls)\n        kwargs['headers'] = self.default_headers\n        return self.put(url, **kwargs).json()",
    "docstring": "PUT data to the api-server\n\n        :param url: resource location (eg: \"/type/uuid\")\n        :type url: str\n        :param cls: JSONEncoder class\n        :type cls: JSONEncoder"
  },
  {
    "code": "def parse_request(self):\n        ret = BaseHTTPRequestHandler.parse_request(self)\n        if ret:\n            mname = self.path.lstrip('/').split('/')[0]\n            mname = self.command + ('_' + mname if mname else '')\n            if hasattr(self, 'do_' + mname):\n                self.command = mname\n        return ret",
    "docstring": "Override parse_request method to enrich basic functionality of `BaseHTTPRequestHandler` class\n\n        Original class can only invoke do_GET, do_POST, do_PUT, etc method implementations if they are defined.\n        But we would like to have at least some simple routing mechanism, i.e.:\n        GET /uri1/part2 request should invoke `do_GET_uri1()`\n        POST /other should invoke `do_POST_other()`\n\n        If the `do_<REQUEST_METHOD>_<first_part_url>` method does not exists we'll fallback to original behavior."
  },
  {
    "code": "def GetFlagSuggestions(attempt, longopt_list):\n  if len(attempt) <= 2 or not longopt_list:\n    return []\n  option_names = [v.split('=')[0] for v in longopt_list]\n  distances = [(_DamerauLevenshtein(attempt, option[0:len(attempt)]), option)\n               for option in option_names]\n  distances.sort(key=lambda t: t[0])\n  least_errors, _ = distances[0]\n  if least_errors >= _SUGGESTION_ERROR_RATE_THRESHOLD * len(attempt):\n    return []\n  suggestions = []\n  for errors, name in distances:\n    if errors == least_errors:\n      suggestions.append(name)\n    else:\n      break\n  return suggestions",
    "docstring": "Get helpful similar matches for an invalid flag."
  },
  {
    "code": "def get_object(self, base_: Type, qualifier: str = None) -> Any:\n        egg_ = self._find_egg(base_, qualifier)\n        if egg_ is None:\n            raise UnknownDependency('Unknown dependency %s' % base_)\n        scope_id = getattr(egg_.egg, '__haps_custom_scope', INSTANCE_SCOPE)\n        try:\n            _scope = self.scopes[scope_id]\n        except KeyError:\n            raise UnknownScope('Unknown scopes with id %s' % scope_id)\n        else:\n            with self._lock:\n                return _scope.get_object(egg_.egg)",
    "docstring": "Get instance directly from the container.\n\n        If the qualifier is not None, proper method to create/retrieve instance\n        is  used.\n\n        :param base_: `base` of this object\n        :param qualifier: optional qualifier\n        :return: object instance"
  },
  {
    "code": "def lookup(source, keys, fallback = None):\n  try:\n    for key in keys:\n      source = source[key]\n    return source\n  except (KeyError, AttributeError, TypeError):\n    return fallback",
    "docstring": "Traverses the source, looking up each key.  Returns None if can't find anything instead of raising an exception."
  },
  {
    "code": "def dump_hex(ofd, start, len_, prefix=0):\n    prefix_whitespaces = '  ' * prefix\n    limit = 16 - (prefix * 2)\n    start_ = start[:len_]\n    for line in (start_[i:i + limit] for i in range(0, len(start_), limit)):\n        hex_lines, ascii_lines = list(), list()\n        for c in line:\n            hex_lines.append('{0:02x}'.format(c if hasattr(c, 'real') else ord(c)))\n            c2 = chr(c) if hasattr(c, 'real') else c\n            ascii_lines.append(c2 if c2 in string.printable[:95] else '.')\n        hex_line = ' '.join(hex_lines).ljust(limit * 3)\n        ascii_line = ''.join(ascii_lines)\n        ofd('    %s%s%s', prefix_whitespaces, hex_line, ascii_line)",
    "docstring": "Convert `start` to hex and logs it, 16 bytes per log statement.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L760\n\n    Positional arguments:\n    ofd -- function to call with arguments similar to `logging.debug`.\n    start -- bytearray() or bytearray_ptr() instance.\n    len_ -- size of `start` (integer).\n\n    Keyword arguments:\n    prefix -- additional number of whitespace pairs to prefix each log statement with."
  },
  {
    "code": "def launch_app(app_path, params=[], time_before_kill_app=15):\n    import subprocess\n    try:\n        res = subprocess.call([app_path, params], timeout=time_before_kill_app, shell=True)\n        print('res = ', res)\n        if res == 0:\n            return True\n        else:\n            return False\n    except Exception as ex:\n        print('error launching app  ' + str(app_path) + ' with params ' + str(params) + '\\n' + str(ex))\n        return False",
    "docstring": "start an app"
  },
  {
    "code": "def getTreeWalker(treeType, implementation=None, **kwargs):\n    treeType = treeType.lower()\n    if treeType not in treeWalkerCache:\n        if treeType == \"dom\":\n            from . import dom\n            treeWalkerCache[treeType] = dom.TreeWalker\n        elif treeType == \"genshi\":\n            from . import genshi\n            treeWalkerCache[treeType] = genshi.TreeWalker\n        elif treeType == \"lxml\":\n            from . import etree_lxml\n            treeWalkerCache[treeType] = etree_lxml.TreeWalker\n        elif treeType == \"etree\":\n            from . import etree\n            if implementation is None:\n                implementation = default_etree\n            return etree.getETreeModule(implementation, **kwargs).TreeWalker\n    return treeWalkerCache.get(treeType)",
    "docstring": "Get a TreeWalker class for various types of tree with built-in support\n\n    :arg str treeType: the name of the tree type required (case-insensitive).\n        Supported values are:\n\n        * \"dom\": The xml.dom.minidom DOM implementation\n        * \"etree\": A generic walker for tree implementations exposing an\n          elementtree-like interface (known to work with ElementTree,\n          cElementTree and lxml.etree).\n        * \"lxml\": Optimized walker for lxml.etree\n        * \"genshi\": a Genshi stream\n\n    :arg implementation: A module implementing the tree type e.g.\n        xml.etree.ElementTree or cElementTree (Currently applies to the \"etree\"\n        tree type only).\n\n    :arg kwargs: keyword arguments passed to the etree walker--for other\n        walkers, this has no effect\n\n    :returns: a TreeWalker class"
  },
  {
    "code": "def event(self, event_name):\n        self._event_dict.setdefault(event_name, 0)\n        self._event_dict[event_name] += 1\n        self._log_progress_if_interval_elapsed()",
    "docstring": "Register an event that occurred during processing of a task of the given\n        type.\n\n        Args:     event_name: str         A name for a type of events. Events of the\n        same type are displayed as         a single entry and a total count of\n        occurences."
  },
  {
    "code": "def instantiate_child(self, nurest_object, from_template, response_choice=None, async=False, callback=None, commit=True):\n        if not from_template.id:\n            raise InternalConsitencyError(\"Cannot instantiate a child from a template with no ID: %s.\" % from_template)\n        nurest_object.template_id = from_template.id\n        return self._manage_child_object(nurest_object=nurest_object,\n                                         async=async,\n                                         method=HTTP_METHOD_POST,\n                                         callback=callback,\n                                         handler=self._did_create_child,\n                                         response_choice=response_choice,\n                                         commit=commit)",
    "docstring": "Instantiate an nurest_object from a template object\n\n            Args:\n                nurest_object: the NURESTObject object to add\n                from_template: the NURESTObject template object\n                callback: callback containing the object and the connection\n\n            Returns:\n                Returns the object and connection (object, connection)\n\n            Example:\n                >>> parent_entity = NUParentEntity(id=\"xxxx-xxxx-xxx-xxxx\") # create a NUParentEntity with an existing ID (or retrieve one)\n                >>> other_entity_template = NUOtherEntityTemplate(id=\"yyyy-yyyy-yyyy-yyyy\") # create a NUOtherEntityTemplate with an existing ID (or retrieve one)\n                >>> other_entity_instance = NUOtherEntityInstance(name=\"my new instance\") # create a new NUOtherEntityInstance to be intantiated from other_entity_template\n                >>>\n                >>> parent_entity.instantiate_child(other_entity_instance, other_entity_template) # instatiate the new domain in the server"
  },
  {
    "code": "def _get_mouse_cursor(self):\n        if self.mouse_cursor is not None:\n            return self.mouse_cursor\n        elif self.interactive and self.draggable:\n            return gdk.CursorType.FLEUR\n        elif self.interactive:\n            return gdk.CursorType.HAND2",
    "docstring": "Determine mouse cursor.\n        By default look for self.mouse_cursor is defined and take that.\n        Otherwise use gdk.CursorType.FLEUR for draggable sprites and gdk.CursorType.HAND2 for\n        interactive sprites. Defaults to scenes cursor."
  },
  {
    "code": "def tar_archive(context):\n    logger.debug(\"start\")\n    mode = get_file_mode_for_writing(context)\n    for item in context['tar']['archive']:\n        destination = context.get_formatted_string(item['out'])\n        source = context.get_formatted_string(item['in'])\n        with tarfile.open(destination, mode) as archive_me:\n            logger.debug(f\"Archiving '{source}' to '{destination}'\")\n            archive_me.add(source, arcname='.')\n            logger.info(f\"Archived '{source}' to '{destination}'\")\n    logger.debug(\"end\")",
    "docstring": "Archive specified path to a tar archive.\n\n    Args:\n        context: dictionary-like. context is mandatory.\n            context['tar']['archive'] must exist. It's a dictionary.\n            keys are the paths to archive.\n            values are the destination output paths.\n\n    Example:\n        tar:\n            archive:\n                - in: path/to/dir\n                  out: path/to/destination.tar.xs\n                - in: another/my.file\n                  out: ./my.tar.xs\n\n        This will archive directory path/to/dir to path/to/destination.tar.xs,\n        and also archive file another/my.file to ./my.tar.xs"
  },
  {
    "code": "def XML(content, source=None):\n    try:\n        tree = ET.XML(content)\n    except ET.ParseError as err:\n        x_parse_error(err, content, source)\n    return tree",
    "docstring": "Parses the XML text using the ET.XML function, but handling the ParseError in\n    a user-friendly way."
  },
  {
    "code": "def remove_xml_element(name, tree):\n    remove = tree.findall(\n        \".//{{http://soap.sforce.com/2006/04/metadata}}{}\".format(name)\n    )\n    if not remove:\n        return tree\n    parent_map = {c: p for p in tree.iter() for c in p}\n    for elem in remove:\n        parent = parent_map[elem]\n        parent.remove(elem)\n    return tree",
    "docstring": "Removes XML elements from an ElementTree content tree"
  },
  {
    "code": "def list_devices(self, **kwargs):\n        kwargs = self._verify_sort_options(kwargs)\n        kwargs = self._verify_filters(kwargs, Device, True)\n        api = self._get_api(device_directory.DefaultApi)\n        return PaginatedResponse(api.device_list, lwrap_type=Device, **kwargs)",
    "docstring": "List devices in the device catalog.\n\n        Example usage, listing all registered devices in the catalog:\n\n        .. code-block:: python\n\n            filters = { 'state': {'$eq': 'registered' } }\n            devices = api.list_devices(order='asc', filters=filters)\n            for idx, d in enumerate(devices):\n                print(idx, d.id)\n\n        :param int limit: The number of devices to retrieve.\n        :param str order: The ordering direction, ascending (asc) or\n            descending (desc)\n        :param str after: Get devices after/starting at given `device_id`\n        :param filters: Dictionary of filters to apply.\n        :returns: a list of :py:class:`Device` objects registered in the catalog.\n        :rtype: PaginatedResponse"
  },
  {
    "code": "def append(self, item):\n        if isinstance(item, Monomer):\n            self._monomers.append(item)\n        else:\n            raise TypeError(\n                'Only Monomer objects can be appended to an Polymer.')\n        return",
    "docstring": "Appends a `Monomer to the `Polymer`.\n\n        Notes\n        -----\n        Does not update labelling."
  },
  {
    "code": "def convertDay(self, day, prefix=\"\", weekday=False):\n        def sameDay(d1, d2):\n            d = d1.day == d2.day\n            m = d1.month == d2.month\n            y = d1.year == d2.year\n            return d and m and y\n        tom = self.now + datetime.timedelta(days=1)\n        if sameDay(day, self.now):\n            return \"today\"\n        elif sameDay(day, tom):\n            return \"tomorrow\"\n        if weekday:\n            dayString = day.strftime(\"%A, %B %d\")\n        else:\n            dayString = day.strftime(\"%B %d\")\n        if not int(dayString[-2]):\n            dayString = dayString[:-2] + dayString[-1]\n        return prefix + \" \" + dayString",
    "docstring": "Convert a datetime object representing a day into a human-ready\n        string that can be read, spoken aloud, etc.\n\n        Args:\n            day (datetime.date): A datetime object to be converted into text.\n            prefix (str): An optional argument that prefixes the converted\n                string. For example, if prefix=\"in\", you'd receive \"in two\n                days\", rather than \"two days\", while the method would still\n                return \"tomorrow\" (rather than \"in tomorrow\").\n            weekday (bool): An optional argument that returns \"Monday, Oct. 1\"\n                if True, rather than \"Oct. 1\".\n\n        Returns:\n            A string representation of the input day, ignoring any time-related\n            information."
  },
  {
    "code": "def delete(name, wait=False, region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    try:\n        conn.delete_cache_cluster(name)\n        if not wait:\n            log.info('Deleted cache cluster %s.', name)\n            return True\n        while True:\n            config = get_config(name, region, key, keyid, profile)\n            if not config:\n                return True\n            if config['cache_cluster_status'] == 'deleting':\n                return True\n            time.sleep(2)\n        log.info('Deleted cache cluster %s.', name)\n        return True\n    except boto.exception.BotoServerError as e:\n        msg = 'Failed to delete cache cluster {0}.'.format(name)\n        log.error(msg)\n        log.debug(e)\n        return False",
    "docstring": "Delete a cache cluster.\n\n    CLI example::\n\n        salt myminion boto_elasticache.delete myelasticache"
  },
  {
    "code": "def peak_interval(self, name, alpha=_alpha, npoints=_npoints, **kwargs):\n        data = self.get(name, **kwargs)\n        return peak_interval(data,alpha,npoints)",
    "docstring": "Calculate peak interval for parameter."
  },
  {
    "code": "def global_symbols_in_children(self):\n        result = set()\n        for child in self.children:\n            result |= (\n                child.global_symbols |\n                child.global_symbols_in_children)\n        return result",
    "docstring": "This is based on all children referenced symbols that have not\n        been declared.\n\n        The intended use case is to ban the symbols from being used as\n        remapped symbol values."
  },
  {
    "code": "def K_to_F(self, K, method='doubling'):\n        A1 = self.A + dot(self.C, K)\n        B1 = self.B\n        Q1 = self.Q\n        R1 = self.R - self.beta * self.theta * dot(K.T, K)\n        lq = LQ(Q1, R1, A1, B1, beta=self.beta)\n        P, F, d = lq.stationary_values(method=method)\n        return F, P",
    "docstring": "Compute agent 1's best value-maximizing response F, given K.\n\n        Parameters\n        ----------\n        K : array_like(float, ndim=2)\n            A j x n array\n        method : str, optional(default='doubling')\n            Solution method used in solving the associated Riccati\n            equation, str in {'doubling', 'qz'}.\n\n        Returns\n        -------\n        F : array_like(float, ndim=2)\n            The policy function for a given K\n        P : array_like(float, ndim=2)\n            The value function for a given K"
  },
  {
    "code": "def _pagination(self):\n        oldest = self.oldest\n        newest = self.newest\n        base = {key: val for key, val in self.spec.items()\n                if key not in OFFSET_PRIORITY}\n        oldest_neighbor = View({\n            **base,\n            'before': oldest,\n            'order': 'newest'\n        }).first if oldest else None\n        newest_neighbor = View({\n            **base,\n            'after': newest,\n            'order': 'oldest'\n        }).first if newest else None\n        if 'date' in self.spec:\n            return self._get_date_pagination(base, oldest_neighbor, newest_neighbor)\n        if 'count' in self.spec:\n            return self._get_count_pagination(base, oldest_neighbor, newest_neighbor)\n        return None, None",
    "docstring": "Compute the neighboring pages from this view.\n\n        Returns a tuple of older page, newer page."
  },
  {
    "code": "def string(_object):\n    if is_callable(_object):\n        _validator = _object\n        @wraps(_validator)\n        def decorated(value):\n            ensure(isinstance(value, basestring), \"not of type string\")\n            return _validator(value)\n        return decorated\n    ensure(isinstance(_object, basestring), \"not of type string\")",
    "docstring": "Validates a given input is of type string.\n\n    Example usage::\n\n        data = {'a' : 21}\n        schema = (string, 21)\n\n    You can also use this as a decorator, as a way to check for the\n    input before it even hits a validator you may be writing.\n\n    .. note::\n        If the argument is a callable, the decorating behavior will be\n        triggered, otherwise it will act as a normal function."
  },
  {
    "code": "def decode_path(file_path):\n    if file_path is None:\n        return\n    if isinstance(file_path, six.binary_type):\n        file_path = file_path.decode(sys.getfilesystemencoding())\n    return file_path",
    "docstring": "Turn a path name into unicode."
  },
  {
    "code": "def expand_indent(line):\n    r\n    if '\\t' not in line:\n        return len(line) - len(line.lstrip())\n    result = 0\n    for char in line:\n        if char == '\\t':\n            result = result // 8 * 8 + 8\n        elif char == ' ':\n            result += 1\n        else:\n            break\n    return result",
    "docstring": "r\"\"\"Return the amount of indentation.\n\n    Tabs are expanded to the next multiple of 8.\n\n    >>> expand_indent('    ')\n    4\n    >>> expand_indent('\\t')\n    8\n    >>> expand_indent('       \\t')\n    8\n    >>> expand_indent('        \\t')\n    16"
  },
  {
    "code": "def get_jump_target_maps(code, opc):\n    offset2prev = {}\n    prev_offset = -1\n    for offset, op, arg in unpack_opargs_bytecode(code, opc):\n        if prev_offset >= 0:\n            prev_list = offset2prev.get(offset, [])\n            prev_list.append(prev_offset)\n            offset2prev[offset] = prev_list\n        if op in opc.NOFOLLOW:\n            prev_offset = -1\n        else:\n            prev_offset = offset\n        if arg is not None:\n            jump_offset = -1\n            if op in opc.JREL_OPS:\n                op_len = op_size(op, opc)\n                jump_offset = offset + op_len + arg\n            elif op in opc.JABS_OPS:\n                jump_offset = arg\n            if jump_offset >= 0:\n                prev_list = offset2prev.get(jump_offset, [])\n                prev_list.append(offset)\n                offset2prev[jump_offset] = prev_list\n    return offset2prev",
    "docstring": "Returns a dictionary where the key is an offset and the values are\n    a list of instruction offsets which can get run before that\n    instruction. This includes jump instructions as well as non-jump\n    instructions. Therefore, the keys of the dictionary are reachable\n    instructions. The values of the dictionary may be useful in control-flow\n    analysis."
  },
  {
    "code": "def match(self, subject: Union[Expression, FlatTerm]) -> Iterator[Tuple[T, Substitution]]:\n        for index in self._match(subject):\n            pattern, label = self._patterns[index]\n            subst = Substitution()\n            if subst.extract_substitution(subject, pattern.expression):\n                for constraint in pattern.constraints:\n                    if not constraint(subst):\n                        break\n                else:\n                    yield label, subst",
    "docstring": "Match the given subject against all patterns in the net.\n\n        Args:\n            subject:\n                The subject that is matched. Must be constant.\n\n        Yields:\n            A tuple :code:`(final label, substitution)`, where the first component is the final label associated with\n            the pattern as given when using :meth:`add()` and the second one is the match substitution."
  },
  {
    "code": "def loads(cls, data):\n        rep = cbor.loads(data)\n        if not isinstance(rep, Sequence):\n            raise SerializationError('expected a CBOR list')\n        if len(rep) != 2:\n            raise SerializationError('expected a CBOR list of 2 items')\n        metadata = rep[0]\n        if 'v' not in metadata:\n            raise SerializationError('no version in CBOR metadata')\n        if metadata['v'] != 'fc01':\n            raise SerializationError('invalid CBOR version {!r} '\n                                     '(expected \"fc01\")'\n                                     .format(metadata['v']))\n        read_only = metadata.get('ro', False)\n        contents = rep[1]\n        return cls.from_dict(contents, read_only=read_only)",
    "docstring": "Create a feature collection from a CBOR byte string."
  },
  {
    "code": "def _process_scrape_info(self, scraper: BaseScraper,\n                             scrape_result: ScrapeResult,\n                             item_session: ItemSession):\n        if not scrape_result:\n            return 0, 0\n        num_inline = 0\n        num_linked = 0\n        for link_context in scrape_result.link_contexts:\n            url_info = self.parse_url(link_context.link)\n            if not url_info:\n                continue\n            url_info = self.rewrite_url(url_info)\n            child_url_record = item_session.child_url_record(\n                url_info.url, inline=link_context.inline\n            )\n            if not self._fetch_rule.consult_filters(item_session.request.url_info, child_url_record)[0]:\n                continue\n            if link_context.inline:\n                num_inline += 1\n            else:\n                num_linked += 1\n            item_session.add_child_url(url_info.url, inline=link_context.inline,\n                                       link_type=link_context.link_type)\n        return num_inline, num_linked",
    "docstring": "Collect the URLs from the scrape info dict."
  },
  {
    "code": "def status_unpin(self, id):\n        id = self.__unpack_id(id)\n        url = '/api/v1/statuses/{0}/unpin'.format(str(id))\n        return self.__api_request('POST', url)",
    "docstring": "Unpin a pinned status for the logged-in user.\n\n        Returns a `toot dict`_ with the status that used to be pinned."
  },
  {
    "code": "def schema(self):\n        if not hasattr(self, \"_schema\"):\n            ret = None\n            o = self._type\n            if isinstance(o, type):\n                ret = getattr(o, \"schema\", None)\n            elif isinstance(o, Schema):\n                ret = o\n            else:\n                module, klass = utils.get_objects(o)\n                ret = klass.schema\n            self._schema = ret\n        return self._schema",
    "docstring": "return the schema instance if this is reference to another table"
  },
  {
    "code": "def _make_ctx_options(ctx_options, config_cls=ContextOptions):\n  if not ctx_options:\n    return None\n  for key in list(ctx_options):\n    translation = _OPTION_TRANSLATIONS.get(key)\n    if translation:\n      if translation in ctx_options:\n        raise ValueError('Cannot specify %s and %s at the same time' %\n                         (key, translation))\n      ctx_options[translation] = ctx_options.pop(key)\n  return config_cls(**ctx_options)",
    "docstring": "Helper to construct a ContextOptions object from keyword arguments.\n\n  Args:\n    ctx_options: A dict of keyword arguments.\n    config_cls: Optional Configuration class to use, default ContextOptions.\n\n  Note that either 'options' or 'config' can be used to pass another\n  Configuration object, but not both.  If another Configuration\n  object is given it provides default values.\n\n  Returns:\n    A Configuration object, or None if ctx_options is empty."
  },
  {
    "code": "def get_sync_start_position(self, document, lineno):\n        \" Scan backwards, and find a possible position to start. \"\n        pattern = self._compiled_pattern\n        lines = document.lines\n        for i in range(lineno, max(-1, lineno - self.MAX_BACKWARDS), -1):\n            match = pattern.match(lines[i])\n            if match:\n                return i, match.start()\n        if lineno < self.FROM_START_IF_NO_SYNC_POS_FOUND:\n            return 0, 0\n        else:\n            return lineno, 0",
    "docstring": "Scan backwards, and find a possible position to start."
  },
  {
    "code": "def if_then(self, classical_reg, if_program, else_program=None):\n        else_program = else_program if else_program is not None else Program()\n        label_then = LabelPlaceholder(\"THEN\")\n        label_end = LabelPlaceholder(\"END\")\n        self.inst(JumpWhen(target=label_then, condition=unpack_classical_reg(classical_reg)))\n        self.inst(else_program)\n        self.inst(Jump(label_end))\n        self.inst(JumpTarget(label_then))\n        self.inst(if_program)\n        self.inst(JumpTarget(label_end))\n        return self",
    "docstring": "If the classical register at index classical reg is 1, run if_program, else run\n        else_program.\n\n        Equivalent to the following construction:\n\n        .. code::\n\n            IF [c]:\n               instrA...\n            ELSE:\n               instrB...\n            =>\n              JUMP-WHEN @THEN [c]\n              instrB...\n              JUMP @END\n              LABEL @THEN\n              instrA...\n              LABEL @END\n\n        :param int classical_reg: The classical register to check as the condition\n        :param Program if_program: A Quil program to execute if classical_reg is 1\n        :param Program else_program: A Quil program to execute if classical_reg is 0. This\n            argument is optional and defaults to an empty Program.\n        :returns: The Quil Program with the branching instructions added.\n        :rtype: Program"
  },
  {
    "code": "def _islots(self):\n        if \"__slots__\" not in self.locals:\n            return None\n        for slots in self.igetattr(\"__slots__\"):\n            for meth in ITER_METHODS:\n                try:\n                    slots.getattr(meth)\n                    break\n                except exceptions.AttributeInferenceError:\n                    continue\n            else:\n                continue\n            if isinstance(slots, node_classes.Const):\n                if slots.value:\n                    yield slots\n                continue\n            if not hasattr(slots, \"itered\"):\n                continue\n            if isinstance(slots, node_classes.Dict):\n                values = [item[0] for item in slots.items]\n            else:\n                values = slots.itered()\n            if values is util.Uninferable:\n                continue\n            if not values:\n                return values\n            for elt in values:\n                try:\n                    for inferred in elt.infer():\n                        if inferred is util.Uninferable:\n                            continue\n                        if not isinstance(\n                            inferred, node_classes.Const\n                        ) or not isinstance(inferred.value, str):\n                            continue\n                        if not inferred.value:\n                            continue\n                        yield inferred\n                except exceptions.InferenceError:\n                    continue\n        return None",
    "docstring": "Return an iterator with the inferred slots."
  },
  {
    "code": "def collect(self, force=False):\n        if force or not self.changes:\n            self.changes = tuple(self.collect_impl())\n        return self.changes",
    "docstring": "calls collect_impl and stores the results as the child changes of\n        this super-change. Returns a tuple of the data generated from\n        collect_impl. Caches the result rather than re-computing each\n        time, unless force is True"
  },
  {
    "code": "def insertDatastore(self, index, store):\n    if not isinstance(store, Datastore):\n      raise TypeError(\"stores must be of type %s\" % Datastore)\n    self._stores.insert(index, store)",
    "docstring": "Inserts datastore `store` into this collection at `index`."
  },
  {
    "code": "async def wait_for_group(self, container, networkid, timeout = 120):\n        if networkid in self._current_groups:\n            return self._current_groups[networkid]\n        else:\n            if not self._connection.connected:\n                raise ConnectionResetException\n            groupchanged = VXLANGroupChanged.createMatcher(self._connection, networkid, VXLANGroupChanged.UPDATED)\n            conn_down = self._connection.protocol.statematcher(self._connection)\n            timeout_, ev, m = await container.wait_with_timeout(timeout, groupchanged, conn_down)\n            if timeout_:\n                raise ValueError('VXLAN group is still not created after a long time')\n            elif m is conn_down:\n                raise ConnectionResetException\n            else:\n                return ev.physicalportid",
    "docstring": "Wait for a VXLAN group to be created"
  },
  {
    "code": "def result(self, timeout=None):\n        if self.done:\n            return self._result\n        result = self.conn.process_packets(transaction_id=self.transaction_id,\n                                           timeout=timeout)\n        self._result = result\n        self.done = True\n        return result",
    "docstring": "Retrieves the result of the call.\n\n        :param timeout: The time to wait for a result from the server.\n\n        Raises :exc:`RTMPTimeoutError` on timeout."
  },
  {
    "code": "def get_club_members(self, club_id, limit=None):\n        result_fetcher = functools.partial(self.protocol.get,\n                                           '/clubs/{id}/members',\n                                           id=club_id)\n        return BatchedResultsIterator(entity=model.Athlete, bind_client=self,\n                                      result_fetcher=result_fetcher, limit=limit)",
    "docstring": "Gets the member objects for specified club ID.\n\n        http://strava.github.io/api/v3/clubs/#get-members\n\n        :param club_id: The numeric ID for the club.\n        :type club_id: int\n\n        :param limit: Maximum number of athletes to return. (default unlimited)\n        :type limit: int\n\n        :return: An iterator of :class:`stravalib.model.Athlete` objects.\n        :rtype: :class:`BatchedResultsIterator`"
  },
  {
    "code": "def _get_validate(data):\n    if data.get(\"vrn_file\") and tz.get_in([\"config\", \"algorithm\", \"validate\"], data):\n        return utils.deepish_copy(data)\n    elif \"group_orig\" in data:\n        for sub in multi.get_orig_items(data):\n            if \"validate\" in sub[\"config\"][\"algorithm\"]:\n                sub_val = utils.deepish_copy(sub)\n                sub_val[\"vrn_file\"] = data[\"vrn_file\"]\n                return sub_val\n    return None",
    "docstring": "Retrieve items to validate, from single samples or from combined joint calls."
  },
  {
    "code": "def is_downloaded(self, file_path):\n        if os.path.exists(file_path):\n            self.chatbot.logger.info('File is already downloaded')\n            return True\n        return False",
    "docstring": "Check if the data file is already downloaded."
  },
  {
    "code": "def isrot(m, ntol, dtol):\n    m = stypes.toDoubleMatrix(m)\n    ntol = ctypes.c_double(ntol)\n    dtol = ctypes.c_double(dtol)\n    return bool(libspice.isrot_c(m, ntol, dtol))",
    "docstring": "Indicate whether a 3x3 matrix is a rotation matrix.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrot_c.html\n\n    :param m: A matrix to be tested.\n    :type m: 3x3-Element Array of floats\n    :param ntol: Tolerance for the norms of the columns of m.\n    :type ntol: float\n    :param dtol:\n                Tolerance for the determinant of a matrix whose columns\n                are the unitized columns of m.\n    :type dtol: float\n    :return: True if and only if m is a rotation matrix.\n    :rtype: bool"
  },
  {
    "code": "def _get_voltage_magnitude_var(self, buses, generators):\n        Vm = array([b.v_magnitude for b in buses])\n        for g in generators:\n            Vm[g.bus._i] = g.v_magnitude\n        Vmin = array([b.v_min for b in buses])\n        Vmax = array([b.v_max for b in buses])\n        return Variable(\"Vm\", len(buses), Vm, Vmin, Vmax)",
    "docstring": "Returns the voltage magnitude variable set."
  },
  {
    "code": "def broadcast_channel(message, channel):\n    try:\n        socket = CLIENTS[CHANNELS.get(channel, [])[0]][1]\n    except (IndexError, KeyError):\n        raise NoSocket(\"There are no clients on the channel: \" + channel)\n    socket.send_and_broadcast_channel(message, channel)",
    "docstring": "Find the first socket for the given channel, and use it to\n    broadcast to the channel, including the socket itself."
  },
  {
    "code": "def make_prediction_pipeline(pipeline, args):\n  predicted_values, errors = (\n      pipeline |\n      'Read CSV Files' >>\n      beam.io.ReadFromText(str(args.predict_data),\n                           strip_trailing_newlines=True) |\n      'Batch Input' >>\n      beam.ParDo(EmitAsBatchDoFn(args.batch_size)) |\n      'Run TF Graph on Batches' >>\n      beam.ParDo(RunGraphDoFn(args.trained_model_dir)).with_outputs('errors', main='main'))\n  ((predicted_values, errors) |\n   'Format and Save' >>\n   FormatAndSave(args))",
    "docstring": "Builds the prediction pipeline.\n\n  Reads the csv files, prepends a ',' if the target column is missing, run\n  prediction, and then prints the formated results to a file.\n\n  Args:\n    pipeline: the pipeline\n    args: command line args"
  },
  {
    "code": "def didLastExecutedUpgradeSucceeded(self) -> bool:\n        lastEventInfo = self.lastActionEventInfo\n        if lastEventInfo:\n            ev_data = lastEventInfo.data\n            currentPkgVersion = NodeControlUtil.curr_pkg_info(ev_data.pkg_name)[0]\n            if currentPkgVersion:\n                return currentPkgVersion.upstream == ev_data.version\n            else:\n                logger.warning(\n                    \"{} failed to get information about package {} \"\n                    \"scheduled for last upgrade\"\n                    .format(self, ev_data.pkg_name)\n                )\n        return False",
    "docstring": "Checks last record in upgrade log to find out whether it\n        is about scheduling upgrade. If so - checks whether current version\n        is equals to the one in that record\n\n        :returns: upgrade execution result"
  },
  {
    "code": "def _pull_player_data(self):\n        player_info = self._retrieve_html_page()\n        if not player_info:\n            return\n        self._parse_player_information(player_info)\n        all_stats = self._combine_all_stats(player_info)\n        setattr(self, '_season', list(all_stats.keys()))\n        return all_stats",
    "docstring": "Pull and aggregate all player information.\n\n        Pull the player's HTML stats page and parse unique properties, such as\n        the player's height, weight, and name. Next, combine all stats for all\n        seasons plus the player's career stats into a single object which can\n        easily be iterated upon.\n\n        Returns\n        -------\n        dictionary\n            Returns a dictionary of the player's combined stats where each key\n            is a string of the season and the value is the season's associated\n            stats."
  },
  {
    "code": "def get_config(config_schema, env=None):\n    if env is None:\n        env = os.environ\n    return parser.parse_env(\n        config_schema,\n        env,\n    )",
    "docstring": "Parse config from the environment against a given schema\n\n    Args:\n        config_schema:\n            A dictionary mapping keys in the environment to envpy Schema\n            objects describing the expected value.\n        env:\n            An optional dictionary used to override the environment rather\n            than getting it from the os.\n\n    Returns:\n        A dictionary which maps the values pulled from the environment and\n        parsed against the given schema.\n\n    Raises:\n        MissingConfigError:\n            A value in the schema with no default could not be found in the\n            environment.\n        ParsingError:\n            A value was found in the environment but could not be parsed into\n            the given value type."
  },
  {
    "code": "def parse_options(given, available):\n    for key, value in sorted(given.items()):\n        if not value:\n            continue\n        if key in available:\n            yield \"--{0}={1}\".format(key, value)",
    "docstring": "Given a set of options, check if available"
  },
  {
    "code": "def export_to_hdf5(network, path, export_standard_types=False, **kwargs):\n    kwargs.setdefault('complevel', 4)\n    basename = os.path.basename(path)\n    with ExporterHDF5(path, **kwargs) as exporter:\n        _export_to_exporter(network, exporter, basename=basename,\n                            export_standard_types=export_standard_types)",
    "docstring": "Export network and components to an HDF store.\n\n    Both static and series attributes of components are exported, but only\n    if they have non-default values.\n\n    If path does not already exist, it is created.\n\n    Parameters\n    ----------\n    path : string\n        Name of hdf5 file to which to export (if it exists, it is overwritten)\n    **kwargs\n        Extra arguments for pd.HDFStore to specify f.i. compression\n        (default: complevel=4)\n\n    Examples\n    --------\n    >>> export_to_hdf5(network, filename)\n    OR\n    >>> network.export_to_hdf5(filename)"
  },
  {
    "code": "def protected_view(view, info):\n    if info.options.get('protected'):\n        def wrapper_view(context, request):\n            response = _advice(request)\n            if response is not None:\n                return response\n            else:\n                return view(context, request)\n        return wrapper_view\n    return view",
    "docstring": "allows adding `protected=True` to a view_config`"
  },
  {
    "code": "def deps_tree(self):\n        dependencies = self.dependencies + [self.name]\n        if self.repo == \"sbo\":\n            for dep in dependencies:\n                deps = Requires(flag=\"\").sbo(dep)\n                if dep not in self.deps_dict.values():\n                    self.deps_dict[dep] = Utils().dimensional_list(deps)\n        else:\n            for dep in dependencies:\n                deps = Dependencies(self.repo, self.black).binary(dep, flag=\"\")\n                if dep not in self.deps_dict.values():\n                    self.deps_dict[dep] = Utils().dimensional_list(deps)",
    "docstring": "Package dependencies image map file"
  },
  {
    "code": "def wait_for_parent_image_build(self, nvr):\n        self.log.info('Waiting for Koji build for parent image %s', nvr)\n        poll_start = time.time()\n        while time.time() - poll_start < self.poll_timeout:\n            build = self.koji_session.getBuild(nvr)\n            if build:\n                self.log.info('Parent image Koji build found with id %s', build.get('id'))\n                if build['state'] != koji.BUILD_STATES['COMPLETE']:\n                    exc_msg = ('Parent image Koji build for {} with id {} state is not COMPLETE.')\n                    raise KojiParentBuildMissing(exc_msg.format(nvr, build.get('id')))\n                return build\n            time.sleep(self.poll_interval)\n        raise KojiParentBuildMissing('Parent image Koji build NOT found for {}!'.format(nvr))",
    "docstring": "Given image NVR, wait for the build that produced it to show up in koji.\n        If it doesn't within the timeout, raise an error.\n\n        :return build info dict with 'nvr' and 'id' keys"
  },
  {
    "code": "def save(self, fname):\n        out = etree.tostring(self.root, xml_declaration=True,\n                             standalone=True,\n                             pretty_print=True)\n        with open(fname, 'wb') as fid:\n            fid.write(out)",
    "docstring": "Save figure to a file"
  },
  {
    "code": "def polymer_to_reference_axis_distances(p, reference_axis, tag=True, reference_axis_name='ref_axis'):\n    if not len(p) == len(reference_axis):\n        raise ValueError(\n            \"The reference axis must contain the same number of points \"\n            \"as the Polymer primitive.\")\n    prim_cas = p.primitive.coordinates\n    ref_points = reference_axis.coordinates\n    distances = [distance(prim_cas[i], ref_points[i])\n                 for i in range(len(prim_cas))]\n    if tag:\n        p.tags[reference_axis_name] = reference_axis\n        monomer_tag_name = 'distance_to_{0}'.format(reference_axis_name)\n        for m, d in zip(p._monomers, distances):\n            m.tags[monomer_tag_name] = d\n    return distances",
    "docstring": "Returns distances between the primitive of a Polymer and a reference_axis.\n\n    Notes\n    -----\n    Distances are calculated between each point of the Polymer primitive\n    and the corresponding point in reference_axis. In the special case\n    of the helical barrel, if the Polymer is a helix and the reference_axis\n    represents the centre of the barrel, then this function returns the\n    radius of the barrel at each point on the helix primitive. The points\n    of the primitive and the reference_axis are run through in the same\n    order, so take care with the relative orientation of the reference\n    axis when defining it.\n\n    Parameters\n    ----------\n    p : ampal.Polymer\n    reference_axis : list(numpy.array or tuple or list)\n        Length of reference_axis must equal length of the Polymer.\n        Each element of reference_axis represents a point in R^3.\n    tag : bool, optional\n        If True, tags the Chain with the reference axis coordinates\n        and each Residue with its distance to the ref axis.\n        Distances are stored at the Residue level, but refer to\n        distances from the CA atom.\n    reference_axis_name : str, optional\n        Used to name the keys in tags at Chain and Residue level.\n\n    Returns\n    -------\n    distances : list(float)\n        Distance values between corresponding points on the\n        reference axis and the `Polymer` `Primitive`.\n\n    Raises\n    ------\n    ValueError\n        If the Polymer and the reference_axis have unequal length."
  },
  {
    "code": "def put_info(self, key, value):\n        return self.instance.put_task_info(self.name, key, value)",
    "docstring": "Put associated information of the task."
  },
  {
    "code": "def locations_to_cache(locations, latest=False):\n    cum_cache = lal.Cache()\n    for source in locations:\n        flist = glob.glob(source)\n        if latest:\n            def relaxed_getctime(fn):\n                try:\n                    return os.path.getctime(fn)\n                except OSError:\n                    return 0\n            flist = [max(flist, key=relaxed_getctime)]\n        for file_path in flist:\n            dir_name, file_name = os.path.split(file_path)\n            _, file_extension = os.path.splitext(file_name)\n            if file_extension in [\".lcf\", \".cache\"]:\n                cache = lal.CacheImport(file_path)\n            elif file_extension == \".gwf\" or _is_gwf(file_path):\n                cache = lalframe.FrOpen(str(dir_name), str(file_name)).cache\n            else:\n                raise TypeError(\"Invalid location name\")\n            cum_cache = lal.CacheMerge(cum_cache, cache)\n    return cum_cache",
    "docstring": "Return a cumulative cache file build from the list of locations\n\n    Parameters\n    ----------\n    locations : list\n        A list of strings containing files, globs, or cache files used to build\n    a combined lal cache file object.\n    latest : Optional, {False, Boolean}\n        Only return a cache with the most recent frame in the locations.\n        If false, all results are returned.\n\n    Returns\n    -------\n    cache : lal.Cache\n        A cumulative lal cache object containing the files derived from the\n    list of locations"
  },
  {
    "code": "def component(self, extra_params=None):\n        if self.get('component_id', None):\n            components = self.space.components(id=self['component_id'], extra_params=extra_params)\n            if components:\n                return components[0]",
    "docstring": "The Component currently assigned to the Ticket"
  },
  {
    "code": "def tag_stuff(self):\n        for item in self.input_stream:\n            if 'tags' not in item:\n                item['tags'] = set()\n            for tag_method in self.tag_methods:\n                item['tags'].add(tag_method(item))\n            if None in item['tags']:\n                item['tags'].remove(None)\n            yield item",
    "docstring": "Look through my input stream for the fields to be tagged"
  },
  {
    "code": "def _ensure_value_is_valid(self, value):\n        if not isinstance(value, self.__class__.value_type):\n            raise TypeError('{0} is not valid collection value, instance '\n                            'of {1} required'.format(\n                                value, self.__class__.value_type))\n        return value",
    "docstring": "Ensure that value is a valid collection's value."
  },
  {
    "code": "def _get_request_args(method, **kwargs):\n    args = [\n        ('api_key', api_key),\n        ('format', 'json'),\n        ('method', method),\n        ('nojsoncallback', '1'),\n    ]\n    if kwargs:\n        for key, value in kwargs.iteritems():\n            args.append((key, value))\n    args.sort(key=lambda tup: tup[0])\n    api_sig = _get_api_sig(args)\n    args.append(api_sig)\n    return args",
    "docstring": "Use `method` and other settings to produce a flickr API arguments.\n    Here also use json as the return type.\n\n    :param method: The method provided by flickr,\n            ex: flickr.photosets.getPhotos\n    :type method: str\n    :param kwargs: Other settings\n    :type kwargs: dict\n    :return: An argument list used for post request\n    :rtype: list of sets"
  },
  {
    "code": "def add_xml_declaration(fn):\n    @wraps(fn)\n    def add_xml_declaration_decorator(*args, **kwargs):\n        return '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n\\n' + fn(\n            *args,\n            **kwargs\n        )\n    return add_xml_declaration_decorator",
    "docstring": "Decorator to add header with XML version declaration to output from FN."
  },
  {
    "code": "def _parse_config(self):\n        config = self.get_block('mlag configuration')\n        cfg = dict()\n        cfg.update(self._parse_domain_id(config))\n        cfg.update(self._parse_local_interface(config))\n        cfg.update(self._parse_peer_address(config))\n        cfg.update(self._parse_peer_link(config))\n        cfg.update(self._parse_shutdown(config))\n        return dict(config=cfg)",
    "docstring": "Parses the mlag global configuration\n\n        Returns:\n            dict: A dict object that is intended to be merged into the\n                resource dict"
  },
  {
    "code": "def from_pydatetime(cls, pydatetime):\n        return cls(date=Date.from_pydate(pydatetime.date),\n                   time=Time.from_pytime(pydatetime.time))",
    "docstring": "Creates sql datetime2 object from Python datetime object\n        ignoring timezone\n        @param pydatetime: Python datetime object\n        @return: sql datetime2 object"
  },
  {
    "code": "def init_logs(args, tool=\"NanoPlot\"):\n    start_time = dt.fromtimestamp(time()).strftime('%Y%m%d_%H%M')\n    logname = os.path.join(args.outdir, args.prefix + tool + \"_\" + start_time + \".log\")\n    handlers = [logging.FileHandler(logname)]\n    if args.verbose:\n        handlers.append(logging.StreamHandler())\n    logging.basicConfig(\n        format='%(asctime)s %(message)s',\n        handlers=handlers,\n        level=logging.INFO)\n    logging.info('{} {} started with arguments {}'.format(tool, __version__, args))\n    logging.info('Python version is: {}'.format(sys.version.replace('\\n', ' ')))\n    return logname",
    "docstring": "Initiate log file and log arguments."
  },
  {
    "code": "def process_geneways_files(input_folder=data_folder, get_evidence=True):\n    gp = GenewaysProcessor(input_folder, get_evidence)\n    return gp",
    "docstring": "Reads in Geneways data and returns a list of statements.\n\n    Parameters\n    ----------\n    input_folder : Optional[str]\n        A folder in which to search for Geneways data. Looks for these\n        Geneways extraction data files: human_action.txt,\n        human_actionmention.txt, human_symbols.txt.\n        Omit this parameter to use the default input folder which is\n        indra/data.\n    get_evidence : Optional[bool]\n        Attempt to find the evidence text for an extraction by downloading\n        the corresponding text content and searching for the given offset\n        in the text to get the evidence sentence. Default: True\n\n    Returns\n    -------\n    gp : GenewaysProcessor\n        A GenewaysProcessor object which contains a list of INDRA statements\n        generated from the Geneways action mentions."
  },
  {
    "code": "def subset_sum(x, R):\n    k = len(x) // 2\n    Y = [v for v in part_sum(x[:k])]\n    Z = [R - v for v in part_sum(x[k:])]\n    Y.sort()\n    Z.sort()\n    i = 0\n    j = 0\n    while i < len(Y) and j < len(Z):\n        if Y[i] == Z[j]:\n            return True\n        elif Y[i] < Z[j]:\n            i += 1\n        else:\n            j += 1\n    return False",
    "docstring": "Subsetsum by splitting\n\n    :param x: table of values\n    :param R: target value\n    :returns bool: if there is a subsequence of x with total sum R\n    :complexity: :math:`O(n^{\\\\lceil n/2 \\\\rceil})`"
  },
  {
    "code": "def save(self, file_path):\n        try:\n            file_path = os.path.abspath(file_path)\n            with open(file_path, 'wb') as df:\n                pickle.dump((self.__data, self.__classes, self.__labels,\n                             self.__dtype, self.__description, self.__num_features,\n                             self.__feature_names),\n                            df)\n            return\n        except IOError as ioe:\n            raise IOError('Unable to save the dataset to file: {}', format(ioe))\n        except:\n            raise",
    "docstring": "Method to save the dataset to disk.\n\n        Parameters\n        ----------\n        file_path : str\n            File path to save the current dataset to\n\n        Raises\n        ------\n        IOError\n            If saving to disk is not successful."
  },
  {
    "code": "def to_disk(self, path, exclude=tuple(), disable=None):\n        if disable is not None:\n            deprecation_warning(Warnings.W014)\n            exclude = disable\n        path = util.ensure_path(path)\n        serializers = OrderedDict()\n        serializers[\"tokenizer\"] = lambda p: self.tokenizer.to_disk(p, exclude=[\"vocab\"])\n        serializers[\"meta.json\"] = lambda p: p.open(\"w\").write(srsly.json_dumps(self.meta))\n        for name, proc in self.pipeline:\n            if not hasattr(proc, \"name\"):\n                continue\n            if name in exclude:\n                continue\n            if not hasattr(proc, \"to_disk\"):\n                continue\n            serializers[name] = lambda p, proc=proc: proc.to_disk(p, exclude=[\"vocab\"])\n        serializers[\"vocab\"] = lambda p: self.vocab.to_disk(p)\n        util.to_disk(path, serializers, exclude)",
    "docstring": "Save the current state to a directory.  If a model is loaded, this\n        will include the model.\n\n        path (unicode or Path): Path to a directory, which will be created if\n            it doesn't exist.\n        exclude (list): Names of components or serialization fields to exclude.\n\n        DOCS: https://spacy.io/api/language#to_disk"
  },
  {
    "code": "def start(self):\n        super().start()\n        try:\n            initial = self._get_initial_context()\n            self._stack = ContextCurrifier(self.wrapped, *initial.args, **initial.kwargs)\n            if isconfigurabletype(self.wrapped):\n                try:\n                    self.wrapped = self.wrapped(_final=True)\n                except Exception as exc:\n                    raise TypeError(\n                        \"Configurables should be instanciated before execution starts.\\nGot {!r}.\\n\".format(\n                            self.wrapped\n                        )\n                    ) from exc\n                else:\n                    raise TypeError(\n                        \"Configurables should be instanciated before execution starts.\\nGot {!r}.\\n\".format(\n                            self.wrapped\n                        )\n                    )\n            self._stack.setup(self)\n        except Exception:\n            self.fatal(sys.exc_info(), level=0)\n            raise",
    "docstring": "Starts this context, a.k.a the phase where you setup everything which will be necessary during the whole\n        lifetime of a transformation.\n\n        The \"ContextCurrifier\" is in charge of setting up a decorating stack, that includes both services and context\n        processors, and will call the actual node callable with additional parameters."
  },
  {
    "code": "def _format_command_usage(commands):\n    if not commands:\n        return \"\"\n    command_usage = \"\\nCommands:\\n\"\n    cmd_len = max([len(c) for c in commands] + [8])\n    command_doc = OrderedDict(\n        [(cmd_name, _get_first_line_of_docstring(cmd_doc))\n         for cmd_name, cmd_doc in commands.items()])\n    for cmd_name, cmd_doc in command_doc.items():\n        command_usage += (\"  {:%d}  {}\\n\" % cmd_len).format(cmd_name, cmd_doc)\n    return command_usage",
    "docstring": "Construct the Commands-part of the usage text.\n\n    Parameters\n    ----------\n        commands : dict[str, func]\n            dictionary of supported commands.\n            Each entry should be a tuple of (name, function).\n\n    Returns\n    -------\n        str\n            Text formatted as a description of the commands."
  },
  {
    "code": "def get_job_statuses(github_token, api_url, build_id,\n                     polling_interval, job_number):\n    auth = get_json('{api_url}/auth/github'.format(api_url=api_url),\n                    data={'github_token': github_token})['access_token']\n    while True:\n        build = get_json('{api_url}/builds/{build_id}'.format(\n            api_url=api_url, build_id=build_id), auth=auth)\n        jobs = [job for job in build['jobs']\n                if job['number'] != job_number and\n                not job['allow_failure']]\n        if all(job['finished_at'] for job in jobs):\n            break\n        elif any(job['state'] != 'passed'\n                 for job in jobs if job['finished_at']):\n            break\n        print('Waiting for jobs to complete: {job_numbers}'.format(\n            job_numbers=[job['number'] for job in jobs\n                         if not job['finished_at']]))\n        time.sleep(polling_interval)\n    return [job['state'] == 'passed' for job in jobs]",
    "docstring": "Wait for all the travis jobs to complete.\n\n    Once the other jobs are complete, return a list of booleans,\n    indicating whether or not the job was successful. Ignore jobs\n    marked \"allow_failure\"."
  },
  {
    "code": "def offset(self, index=0):\n        eta = self._geometry[self.camera][index][\"ra\"]\n        xi = self._geometry[self.camera][index][\"dec\"]\n        ra = self.origin.ra - (eta/math.cos(self.dec.radian))*units.degree\n        dec = self.origin.dec - xi * units.degree + 45 * units.arcsec\n        self._coordinate = SkyCoord(ra, dec)",
    "docstring": "Offset the camera pointing to be centred on a particular CCD."
  },
  {
    "code": "def _init_taxids(taxid, taxids):\n        ret = set()\n        if taxids is not None:\n            if taxids is True:\n                return True\n            if isinstance(taxids, int):\n                ret.add(taxids)\n            else:\n                ret.update(taxids)\n        if taxid is not None:\n            ret.add(taxid)\n        if not ret:\n            ret.add(9606)\n            print('**NOTE: DEFAULT TAXID STORED FROM gene2go IS 9606 (human)\\n')\n        return ret",
    "docstring": "Return taxid set"
  },
  {
    "code": "def tostring(self):\n        parser = etree.XMLParser(remove_blank_text=True)\n        outputtree = etree.XML(etree.tostring(self.__doc), parser)\n        return etree.tostring(outputtree, pretty_print=True)",
    "docstring": "return a pretty-printed string output for rpc reply"
  },
  {
    "code": "def check_error_response(self, body, status):\n    status_code = int(status.split(' ', 1)[0])\n    if status_code >= 300:\n      raise errors.BackendError(body, status)",
    "docstring": "Raise an exception if the response from the backend was an error.\n\n    Args:\n      body: A string containing the backend response body.\n      status: A string containing the backend response status.\n\n    Raises:\n      BackendError if the response is an error."
  },
  {
    "code": "def target(self, project_module):\n        assert isinstance(project_module, basestring)\n        if project_module not in self.module2target:\n            self.module2target[project_module] = \\\n                b2.build.targets.ProjectTarget(project_module, project_module,\n                              self.attribute(project_module, \"requirements\"))\n        return self.module2target[project_module]",
    "docstring": "Returns the project target corresponding to the 'project-module'."
  },
  {
    "code": "def _parse_banners(self):\n        motd_value = login_value = None\n        matches = re.findall('^banner\\s+(login|motd)\\s?$\\n(.*?)$\\nEOF$\\n',\n                             self.config, re.DOTALL | re.M)\n        for match in matches:\n            if match[0].strip() == \"motd\":\n                motd_value = match[1]\n            elif match[0].strip() == \"login\":\n                login_value = match[1]\n        return dict(banner_motd=motd_value, banner_login=login_value)",
    "docstring": "Parses the global config and returns the value for both motd\n            and login banners.\n\n        Returns:\n           dict: The configure value for modtd and login banners. If the\n                  banner is not set it will return a value of None for that\n                  key. The returned dict object is intendd to be merged\n                  into the resource dict"
  },
  {
    "code": "def as_symbols(self):\n        out = set()\n        for name in self.types:\n            out.add(('type', name))\n        for name in self.enums:\n            out.add(('enum', name))\n        for name in self.commands:\n            out.add(('command', name))\n        return out",
    "docstring": "Set of symbols required by this Require\n\n        :return: set of ``(symbol type, symbol name)`` tuples"
  },
  {
    "code": "def _config_win32_search(self, search):\n        search = str(search)\n        split_char = self._determine_split_char(search)\n        search_list = search.split(split_char)\n        for s in search_list:\n            if not s in self.search:\n                self.search.add(dns.name.from_text(s))",
    "docstring": "Configure a Search registry entry."
  },
  {
    "code": "def rewrite_url(self, url_info: URLInfo) -> URLInfo:\n        if self._url_rewriter:\n            return self._url_rewriter.rewrite(url_info)\n        else:\n            return url_info",
    "docstring": "Return a rewritten URL such as escaped fragment."
  },
  {
    "code": "def remove_identity(cls, sh_db, ident_id):\n        success = False\n        try:\n            api.delete_identity(sh_db, ident_id)\n            logger.debug(\"Identity %s deleted\", ident_id)\n            success = True\n        except Exception as e:\n            logger.debug(\"Identity not deleted due to %s\", str(e))\n        return success",
    "docstring": "Delete an identity from SortingHat.\n\n        :param sh_db: SortingHat database\n        :param ident_id: identity identifier"
  },
  {
    "code": "def _cleanup(self, domains):\n        for option in domains.values():\n            try:\n                os.remove(option['pot'])\n            except (IOError, OSError):\n                pass",
    "docstring": "Remove the temporary '.pot' files that were created for the domains."
  },
  {
    "code": "def set_rating(self, grade_id):\n        if self.get_rating_metadata().is_read_only():\n            raise errors.NoAccess()\n        if not self._is_valid_id(grade_id):\n            raise errors.InvalidArgument()\n        self._my_map['ratingId'] = str(grade_id)",
    "docstring": "Sets the rating.\n\n        arg:    grade_id (osid.id.Id): the new rating\n        raise:  InvalidArgument - ``grade_id`` is invalid\n        raise:  NoAccess - ``Metadata.isReadOnly()`` is ``true``\n        raise:  NullArgument - ``grade_id`` is ``null``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def list_user_page_views(self, user_id, end_time=None, start_time=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"user_id\"] = user_id\r\n        if start_time is not None:\r\n            params[\"start_time\"] = start_time\r\n        if end_time is not None:\r\n            params[\"end_time\"] = end_time\r\n        self.logger.debug(\"GET /api/v1/users/{user_id}/page_views with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"GET\", \"/api/v1/users/{user_id}/page_views\".format(**path), data=data, params=params, all_pages=True)",
    "docstring": "List user page views.\r\n\r\n        Return the user's page view history in json format, similar to the\r\n        available CSV download. Pagination is used as described in API basics\r\n        section. Page views are returned in descending order, newest to oldest."
  },
  {
    "code": "def get_ngroups(self, field=None):\n        field = field if field else self._determine_group_field(field)\n        if 'ngroups' in self.data['grouped'][field]:\n            return self.data['grouped'][field]['ngroups']\n        raise ValueError(\"ngroups not found in response. specify group.ngroups in the query.\")",
    "docstring": "Returns ngroups count if it was specified in the query, otherwise ValueError.\n\n        If grouping on more than one field, provide the field argument to specify which count you are looking for."
  },
  {
    "code": "def get(cls, id):\n        if CACHE:\n            if id in _cache['Pool']:\n                log.debug('cache hit for pool %d' % id)\n                return _cache['Pool'][id]\n            log.debug('cache miss for pool %d' % id)\n        try:\n            pool = Pool.list({'id': id})[0]\n        except (IndexError, KeyError):\n            raise NipapNonExistentError('no pool with ID ' + str(id) + ' found')\n        _cache['Pool'][id] = pool\n        return pool",
    "docstring": "Get the pool with id 'id'."
  },
  {
    "code": "def _request(self, resource, rtype, action=None, payload=None, offset=None, limit=None, requestId=None,\n                 is_crud=False):\n        end = self.__end\n        if end.is_set():\n            raise LinkShutdownException('Client stopped')\n        rng = None\n        if offset is not None and limit is not None:\n            Validation.limit_offset_check(limit, offset)\n            rng = \"%d/%d\" % (offset, limit)\n        with self.__requests:\n            if requestId is None:\n                requestId = self.__new_request_id()\n            elif requestId in self.__requests:\n                raise ValueError('requestId %s already in use' % requestId)\n            inner_msg = self.__make_innermsg(resource, rtype, requestId, action, payload, rng)\n            self.__requests[requestId] = ret = RequestEvent(requestId, inner_msg, is_crud=is_crud)\n        if not self.__retry_enqueue(PreparedMessage(inner_msg, requestId)):\n            raise LinkShutdownException('Client stopping')\n        return ret",
    "docstring": "_request amqp queue publish helper\n\n        return: RequestEvent object or None for failed to publish"
  },
  {
    "code": "def response_builder(self, response):\n        try:\n            r = response.json()\n            result = r['query']['results']\n            response = {\n                'num_result': r['query']['count'] ,\n                'result': result\n            }\n        except (Exception,) as e:\n            print(e)\n            return response.content\n        return response",
    "docstring": "Try to return a pretty formatted response object"
  },
  {
    "code": "def particle_covariance_mtx(weights,locations):\n    warnings.warn('particle_covariance_mtx is deprecated, please use distributions.ParticleDistribution',\n                  DeprecationWarning)\n    mu = particle_meanfn(weights, locations)\n    xs = locations.transpose([1, 0])\n    ws = weights\n    cov = (\n        np.einsum('i,mi,ni', ws, xs, xs)\n        - np.dot(mu[..., np.newaxis], mu[np.newaxis, ...])\n    )\n    assert np.all(np.isfinite(cov))\n    if not np.all(la.eig(cov)[0] >= 0):\n        warnings.warn('Numerical error in covariance estimation causing positive semidefinite violation.', ApproximationWarning)\n    return cov",
    "docstring": "Returns an estimate of the covariance of a distribution\n    represented by a given set of SMC particle.\n\n    :param weights: An array containing the weights of each\n        particle.\n    :param location: An array containing the locations of\n        each particle.\n    :rtype: :class:`numpy.ndarray`, shape\n        ``(n_modelparams, n_modelparams)``.\n    :returns: An array containing the estimated covariance matrix."
  },
  {
    "code": "def find_project_config_file(project_root: str) -> str:\n    if project_root:\n        project_config_file = os.path.join(project_root, YCONFIG_FILE)\n        if os.path.isfile(project_config_file):\n            return project_config_file",
    "docstring": "Return absolute path to project-specific config file, if it exists.\n\n    :param project_root: Absolute path to project root directory.\n\n    A project config file is a file named `YCONFIG_FILE` found at the top\n    level of the project root dir.\n\n    Return `None` if project root dir is not specified,\n    or if no such file is found."
  },
  {
    "code": "def add_to(self, parent, additions):\n        \"Modify parent to include all elements in additions\"\n        for x in additions:\n            if x not in parent:\n                parent.append(x)\n                self.changed()",
    "docstring": "Modify parent to include all elements in additions"
  },
  {
    "code": "def _write(self, item, labels, features):\n        data = Data([item], [labels], [features])\n        self._writer.write(data, self.groupname, append=True)",
    "docstring": "Writes the given item to the owned file."
  },
  {
    "code": "def semantic_version(tag):\n    try:\n        version = list(map(int, tag.split('.')))\n        assert len(version) == 3\n        return tuple(version)\n    except Exception as exc:\n        raise CommandError(\n            'Could not parse \"%s\", please use '\n            'MAJOR.MINOR.PATCH' % tag\n        ) from exc",
    "docstring": "Get a valid semantic version for tag"
  },
  {
    "code": "def status(self, value):\n        if self._bug.get('id', None):\n            if value in VALID_STATUS:\n                self._bug['status'] = value\n            else:\n                raise BugException(\"Invalid status type was used\")\n        else:\n            raise BugException(\"Can not set status unless there is a bug id.\"\n                               \" Please call Update() before setting\")",
    "docstring": "Property for getting or setting the bug status\n\n            >>> bug.status = \"REOPENED\""
  },
  {
    "code": "def check_ts_data_with_ts_target(X, y=None):\n    if y is not None:\n        Nx = len(X)\n        Ny = len(y)\n        if Nx != Ny:\n            raise ValueError(\"Number of time series different in X (%d) and y (%d)\"\n                             % (Nx, Ny))\n        Xt, _ = get_ts_data_parts(X)\n        Ntx = np.array([len(Xt[i]) for i in np.arange(Nx)])\n        Nty = np.array([len(np.atleast_1d(y[i])) for i in np.arange(Nx)])\n        if np.count_nonzero(Nty == Ntx) == Nx:\n            return\n        else:\n            raise ValueError(\"Invalid time series lengths.\\n\"\n                             \"Ns: \", Nx,\n                             \"Ntx: \", Ntx,\n                             \"Nty: \", Nty)",
    "docstring": "Checks time series data with time series target is good. If not raises value error.\n\n    Parameters\n    ----------\n    X : array-like, shape [n_series, ...]\n       Time series data and (optionally) contextual data\n    y : array-like, shape [n_series, ...]\n        target data"
  },
  {
    "code": "def genCaCert(self, name, signas=None, outp=None, save=True):\n        pkey, cert = self._genBasePkeyCert(name)\n        ext0 = crypto.X509Extension(b'basicConstraints', False, b'CA:TRUE')\n        cert.add_extensions([ext0])\n        if signas is not None:\n            self.signCertAs(cert, signas)\n        else:\n            self.selfSignCert(cert, pkey)\n        if save:\n            keypath = self._savePkeyTo(pkey, 'cas', '%s.key' % name)\n            if outp is not None:\n                outp.printf('key saved: %s' % (keypath,))\n            crtpath = self._saveCertTo(cert, 'cas', '%s.crt' % name)\n            if outp is not None:\n                outp.printf('cert saved: %s' % (crtpath,))\n        return pkey, cert",
    "docstring": "Generates a CA keypair.\n\n        Args:\n            name (str): The name of the CA keypair.\n            signas (str): The CA keypair to sign the new CA with.\n            outp (synapse.lib.output.Output): The output buffer.\n\n        Examples:\n            Make a CA named \"myca\":\n\n                mycakey, mycacert = cdir.genCaCert('myca')\n\n        Returns:\n            ((OpenSSL.crypto.PKey, OpenSSL.crypto.X509)): Tuple containing the private key and certificate objects."
  },
  {
    "code": "def from_clauses(self, clauses):\n        self.clauses = copy.deepcopy(clauses)\n        for cl in self.clauses:\n            self.nv = max([abs(l) for l in cl] + [self.nv])",
    "docstring": "This methods copies a list of clauses into a CNF object.\n\n            :param clauses: a list of clauses.\n            :type clauses: list(list(int))\n\n            Example:\n\n            .. code-block:: python\n\n                >>> from pysat.formula import CNF\n                >>> cnf = CNF(from_clauses=[[-1, 2], [1, -2], [5]])\n                >>> print cnf.clauses\n                [[-1, 2], [1, -2], [5]]\n                >>> print cnf.nv\n                5"
  },
  {
    "code": "def link_callback(uri, rel):\n    sUrl = settings.STATIC_URL\n    sRoot = settings.STATIC_ROOT\n    mUrl = settings.MEDIA_URL\n    mRoot = settings.MEDIA_ROOT\n    if uri.startswith(mUrl):\n        path = os.path.join(mRoot, uri.replace(mUrl, \"\"))\n    elif uri.startswith(sUrl):\n        path = os.path.join(sRoot, uri.replace(sUrl, \"\"))\n    else:\n        return uri\n    if not os.path.isfile(path):\n        raise Exception(\n            'media URI must start with %s or %s' % (sUrl, mUrl)\n        )\n    return path",
    "docstring": "Convert HTML URIs to absolute system paths so xhtml2pdf can access those\n    resources"
  },
  {
    "code": "def dict_of_lists(self):\n        result = {}\n        for key, value in self._items:\n            if key in result:\n                result[key].append(value)\n            else:\n                result[key] = [value]\n        return result",
    "docstring": "Returns a dictionary where each key is associated with a\n        list of values."
  },
  {
    "code": "def is_known_scalar(value):\n    def _is_datetime_or_timedelta(value):\n        return pd.Series(value).dtype.kind in ('M', 'm')\n    return not np.iterable(value) and (isinstance(value, numbers.Number) or\n                                       _is_datetime_or_timedelta(value))",
    "docstring": "Return True if value is a type we expect in a dataframe"
  },
  {
    "code": "def register(cls, name, type_):\n        if not issubclass(type_, Entry):\n            raise exceptions.InvalidEntryType(\"%s is not a subclass of Entry\" % str(type_))\n        cls._registry[name.lower()] = type_",
    "docstring": "Register a new type for an entry-type. The 2nd argument has to be a\n        subclass of structures.Entry."
  },
  {
    "code": "def _process(self, metric):\n        if not self.enabled:\n            return\n        try:\n            try:\n                self.lock.acquire()\n                self.process(metric)\n            except Exception:\n                self.log.error(traceback.format_exc())\n        finally:\n            if self.lock.locked():\n                self.lock.release()",
    "docstring": "Decorator for processing handlers with a lock, catching exceptions"
  },
  {
    "code": "def get_privkey(self, address: AddressHex, password: str) -> PrivateKey:\n        address = add_0x_prefix(address).lower()\n        if not self.address_in_keystore(address):\n            raise ValueError('Keystore file not found for %s' % address)\n        with open(self.accounts[address]) as data_file:\n            data = json.load(data_file)\n        acc = Account(data, password, self.accounts[address])\n        return acc.privkey",
    "docstring": "Find the keystore file for an account, unlock it and get the private key\n\n        Args:\n            address: The Ethereum address for which to find the keyfile in the system\n            password: Mostly for testing purposes. A password can be provided\n                           as the function argument here. If it's not then the\n                           user is interactively queried for one.\n        Returns\n            The private key associated with the address"
  },
  {
    "code": "def create_language_model(self,\n                              name,\n                              base_model_name,\n                              dialect=None,\n                              description=None,\n                              **kwargs):\n        if name is None:\n            raise ValueError('name must be provided')\n        if base_model_name is None:\n            raise ValueError('base_model_name must be provided')\n        headers = {}\n        if 'headers' in kwargs:\n            headers.update(kwargs.get('headers'))\n        sdk_headers = get_sdk_headers('speech_to_text', 'V1',\n                                      'create_language_model')\n        headers.update(sdk_headers)\n        data = {\n            'name': name,\n            'base_model_name': base_model_name,\n            'dialect': dialect,\n            'description': description\n        }\n        url = '/v1/customizations'\n        response = self.request(\n            method='POST',\n            url=url,\n            headers=headers,\n            json=data,\n            accept_json=True)\n        return response",
    "docstring": "Create a custom language model.\n\n        Creates a new custom language model for a specified base model. The custom\n        language model can be used only with the base model for which it is created. The\n        model is owned by the instance of the service whose credentials are used to create\n        it.\n        **See also:** [Create a custom language\n        model](https://cloud.ibm.com/docs/services/speech-to-text/language-create.html#createModel-language).\n\n        :param str name: A user-defined name for the new custom language model. Use a name\n        that is unique among all custom language models that you own. Use a localized name\n        that matches the language of the custom model. Use a name that describes the\n        domain of the custom model, such as `Medical custom model` or `Legal custom\n        model`.\n        :param str base_model_name: The name of the base language model that is to be\n        customized by the new custom language model. The new custom model can be used only\n        with the base model that it customizes.\n        To determine whether a base model supports language model customization, use the\n        **Get a model** method and check that the attribute `custom_language_model` is set\n        to `true`. You can also refer to [Language support for\n        customization](https://cloud.ibm.com/docs/services/speech-to-text/custom.html#languageSupport).\n        :param str dialect: The dialect of the specified language that is to be used with\n        the custom language model. The parameter is meaningful only for Spanish models,\n        for which the service creates a custom language model that is suited for speech in\n        one of the following dialects:\n        * `es-ES` for Castilian Spanish (the default)\n        * `es-LA` for Latin American Spanish\n        * `es-US` for North American (Mexican) Spanish\n        A specified dialect must be valid for the base model. By default, the dialect\n        matches the language of the base model; for example, `en-US` for either of the US\n        English language models.\n        :param str description: A description of the new custom language model. Use a\n        localized description that matches the language of the custom model.\n        :param dict headers: A `dict` containing the request headers\n        :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n        :rtype: DetailedResponse"
  },
  {
    "code": "def _check_cygwin_installed(cyg_arch='x86_64'):\n    path_to_cygcheck = os.sep.join(['C:',\n                                    _get_cyg_dir(cyg_arch),\n                                    'bin', 'cygcheck.exe'])\n    LOG.debug('Path to cygcheck.exe: %s', path_to_cygcheck)\n    if not os.path.exists(path_to_cygcheck):\n        LOG.debug('Could not find cygcheck.exe')\n        return False\n    return True",
    "docstring": "Return True or False if cygwin is installed.\n\n    Use the cygcheck executable to check install. It is installed as part of\n    the base package, and we use it to check packages"
  },
  {
    "code": "def load_data(directory, num):\n    root = os.path.abspath(os.path.dirname(__file__))\n    def get_path(i):\n        return os.path.join(root, 'data', directory, str(i) + '.npy')\n    return [np.load(get_path(i)) for i in range(num)]",
    "docstring": "Load numpy data from the data directory.\n\n    The files should stored in ``../data/<dir>`` and named\n    ``0.npy, 1.npy, ... <num - 1>.npy``.\n\n    Returns:\n        list: A list of loaded data, such that ``list[i]`` contains the the\n        contents of ``i.npy``."
  },
  {
    "code": "def compute_update_ratio(weight_tensors, before_weights, after_weights):\n    deltas = [after - before for after,\n              before in zip(after_weights, before_weights)]\n    delta_norms = [np.linalg.norm(d.ravel()) for d in deltas]\n    weight_norms = [np.linalg.norm(w.ravel()) for w in before_weights]\n    ratios = [d / w for d, w in zip(delta_norms, weight_norms)]\n    all_summaries = [\n        tf.Summary.Value(tag='update_ratios/' +\n                         tensor.name, simple_value=ratio)\n        for tensor, ratio in zip(weight_tensors, ratios)]\n    return tf.Summary(value=all_summaries)",
    "docstring": "Compute the ratio of gradient norm to weight norm."
  },
  {
    "code": "def collection_list(self, resource_id, resource_type=\"collection\"):\n        def fetch_children(children):\n            results = []\n            for child in children:\n                results.append(child[\"slug\"])\n                if \"children\" in child:\n                    results.extend(fetch_children(child[\"children\"]))\n            return results\n        response = self._get(\n            urljoin(self.base_url, \"informationobjects/tree/{}\".format(resource_id))\n        )\n        tree = response.json()\n        return fetch_children(tree[\"children\"])",
    "docstring": "Fetches a list of slug representing descriptions within the specified parent description.\n\n        :param resource_id str: The slug of the description to fetch children from.\n        :param resource_type str: no-op; not required or used in this implementation.\n\n        :return: A list of strings representing the slugs for all children of the requested description.\n        :rtype list:"
  },
  {
    "code": "def same_page(c):\n    return all(\n        [\n            _to_span(c[i]).sentence.is_visual()\n            and bbox_from_span(_to_span(c[i])).page\n            == bbox_from_span(_to_span(c[0])).page\n            for i in range(len(c))\n        ]\n    )",
    "docstring": "Return true if all the components of c are on the same page of the document.\n\n    Page numbers are based on the PDF rendering of the document. If a PDF file is\n    provided, it is used. Otherwise, if only a HTML/XML document is provided, a\n    PDF is created and then used to determine the page number of a Mention.\n\n    :param c: The candidate to evaluate\n    :rtype: boolean"
  },
  {
    "code": "def expose_event(self, widget, event):\n        x, y, width, height = event.area\n        self.logger.debug(\"surface is %s\" % self.surface)\n        if self.surface is not None:\n            win = widget.get_window()\n            cr = win.cairo_create()\n            cr.rectangle(x, y, width, height)\n            cr.clip()\n            cr.set_source_surface(self.surface, 0, 0)\n            cr.set_operator(cairo.OPERATOR_SOURCE)\n            cr.paint()\n        return False",
    "docstring": "When an area of the window is exposed, we just copy out of the\n        server-side, off-screen surface to that area."
  },
  {
    "code": "def _urls_for_js(urls=None):\n    if urls is None:\n        from .urls import urlpatterns\n        urls = [url.name for url in urlpatterns if getattr(url, 'name', None)]\n    urls = dict(zip(urls, [get_uri_template(url) for url in urls]))\n    urls.update(getattr(settings, 'LEAFLET_STORAGE_EXTRA_URLS', {}))\n    return urls",
    "docstring": "Return templated URLs prepared for javascript."
  },
  {
    "code": "def _parse_hunk_line(self, line):\n        components = line.split('@@')\n        if len(components) >= 2:\n            hunk_info = components[1]\n            groups = self.HUNK_LINE_RE.findall(hunk_info)\n            if len(groups) == 1:\n                try:\n                    return int(groups[0])\n                except ValueError:\n                    msg = \"Could not parse '{}' as a line number\".format(groups[0])\n                    raise GitDiffError(msg)\n            else:\n                msg = \"Could not find start of hunk in line '{}'\".format(line)\n                raise GitDiffError(msg)\n        else:\n            msg = \"Could not parse hunk in line '{}'\".format(line)\n            raise GitDiffError(msg)",
    "docstring": "Given a hunk line in `git diff` output, return the line number\n        at the start of the hunk.  A hunk is a segment of code that\n        contains changes.\n\n        The format of the hunk line is:\n\n            @@ -k,l +n,m @@ TEXT\n\n        where `k,l` represent the start line and length before the changes\n        and `n,m` represent the start line and length after the changes.\n\n        `git diff` will sometimes put a code excerpt from within the hunk\n        in the `TEXT` section of the line."
  },
  {
    "code": "def query_array(ncfile, name) -> numpy.ndarray:\n    variable = query_variable(ncfile, name)\n    maskedarray = variable[:]\n    fillvalue_ = getattr(variable, '_FillValue', numpy.nan)\n    if not numpy.isnan(fillvalue_):\n        maskedarray[maskedarray.mask] = numpy.nan\n    return maskedarray.data",
    "docstring": "Return the data of the variable with the given name from the given\n    NetCDF file.\n\n    The following example shows that |query_array| returns |nan| entries\n    to represent missing values even when the respective NetCDF variable\n    defines a different fill value:\n\n    >>> from hydpy import TestIO\n    >>> from hydpy.core.netcdftools import netcdf4\n    >>> from hydpy.core import netcdftools\n    >>> netcdftools.fillvalue = -999.0\n    >>> with TestIO():\n    ...     with netcdf4.Dataset('test.nc', 'w') as ncfile:\n    ...         netcdftools.create_dimension(ncfile, 'dim1', 5)\n    ...         netcdftools.create_variable(ncfile, 'var1', 'f8', ('dim1',))\n    ...     ncfile = netcdf4.Dataset('test.nc', 'r')\n    >>> netcdftools.query_variable(ncfile, 'var1')[:].data\n    array([-999., -999., -999., -999., -999.])\n    >>> netcdftools.query_array(ncfile, 'var1')\n    array([ nan,  nan,  nan,  nan,  nan])\n    >>> import numpy\n    >>> netcdftools.fillvalue = numpy.nan"
  },
  {
    "code": "def nodes(self, t=None, data=False):\n        return list(self.nodes_iter(t=t, data=data))",
    "docstring": "Return a list of the nodes in the graph at a given snapshot.\n\n        Parameters\n        ----------\n        t : snapshot id (default=None)\n            If None the the method returns all the nodes of the flattened graph.\n        data : boolean, optional (default=False)\n               If False return a list of nodes.  If True return a\n               two-tuple of node and node data dictionary\n\n        Returns\n        -------\n        nlist : list\n            A list of nodes.  If data=True a list of two-tuples containing\n            (node, node data dictionary).\n\n        Examples\n        --------\n        >>> G = dn.DynGraph()   # or DiGraph, MultiGraph, MultiDiGraph, etc\n        >>> G.add_path([0,1,2], 0)\n        >>> G.nodes(t=0)\n        [0, 1, 2]\n        >>> G.add_edge(1, 4, t=1)\n        >>> G.nodes(t=0)\n        [0, 1, 2]"
  },
  {
    "code": "def get_root_gradebook_ids(self):\n        if self._catalog_session is not None:\n            return self._catalog_session.get_root_catalog_ids()\n        return self._hierarchy_session.get_roots()",
    "docstring": "Gets the root gradebook ``Ids`` in this hierarchy.\n\n        return: (osid.id.IdList) - the root gradebook ``Ids``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_elements(self, filter_cls, elem_id=None):\n        result = []\n        if elem_id is not None:\n            try:\n                result = [self._class_collection_map[filter_cls][elem_id]]\n            except KeyError:\n                result = []\n        else:\n            for e in self._class_collection_map[filter_cls].values():\n                result.append(e)\n        return result",
    "docstring": "Get a list of elements from the result and filter the element type by a class.\n\n        :param filter_cls:\n        :param elem_id: ID of the object\n        :type elem_id: Integer\n        :return: List of available elements\n        :rtype: List"
  },
  {
    "code": "def _setup_converter_graph(self, converter_list, prune_converters):\n        for converter in converter_list:\n            if prune_converters:\n                try:\n                    converter.configure()\n                except ConverterUnavailable as e:\n                    log.warning('%s unavailable: %s' %\n                                (converter.__class__.__name__, str(e)))\n                    continue\n            for in_ in converter.inputs:\n                for out in converter.outputs:\n                    self.dgraph.add_edge(in_, out, converter.cost)\n                    self.converters[(in_, out)] = converter\n            if hasattr(converter, 'direct_outputs'):\n                self._setup_direct_converter(converter)",
    "docstring": "Set up directed conversion graph, pruning unavailable converters as\n        necessary"
  },
  {
    "code": "def get_value(self):\n        with self._lock:\n            if self._future_value is not None:\n                return {\n                    key: value[:] for key, value in self._future_value.items()\n                }\n            return None",
    "docstring": "Retrieves the value to inject in the component\n\n        :return: The value to inject"
  },
  {
    "code": "def get_news(self):\n        headers = {\"Content-type\": \"application/x-www-form-urlencoded\",\"Accept\": \"text/plain\",'Referer': 'http://'+self.domain+'/login.phtml',\"User-Agent\": user_agent}\n        req = self.session.get('http://'+self.domain+'/team_news.phtml',headers=headers).content\n        soup = BeautifulSoup(req)\n        news = []\n        for i in soup.find_all('div',{'class','article_content_text'}):\n            news.append(i.text)\n        return news",
    "docstring": "Get all the news from first page"
  },
  {
    "code": "def get_instance(self, payload):\n        return AssistantFallbackActionsInstance(\n            self._version,\n            payload,\n            assistant_sid=self._solution['assistant_sid'],\n        )",
    "docstring": "Build an instance of AssistantFallbackActionsInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsInstance\n        :rtype: twilio.rest.preview.understand.assistant.assistant_fallback_actions.AssistantFallbackActionsInstance"
  },
  {
    "code": "def total_vat(self):\n        q = Vat.objects.filter(receipt=self).aggregate(total=Sum('amount'))\n        return q['total'] or 0",
    "docstring": "Returns the sum of all Vat objects."
  },
  {
    "code": "def astensor(array: TensorLike) -> BKTensor:\n    tensor = tf.convert_to_tensor(array, dtype=CTYPE)\n    if DEVICE == 'gpu':\n        tensor = tensor.gpu()\n    N = int(math.log2(size(tensor)))\n    tensor = tf.reshape(tensor, ([2]*N))\n    return tensor",
    "docstring": "Convert to product tensor"
  },
  {
    "code": "def ListFiles(self, ext_attrs=False):\n    if not self.IsDirectory():\n      raise IOError(\"%s is not a directory.\" % self.path)\n    for path in self.files:\n      try:\n        filepath = utils.JoinPath(self.path, path)\n        response = self._Stat(filepath, ext_attrs=ext_attrs)\n        pathspec = self.pathspec.Copy()\n        pathspec.last.path = utils.JoinPath(pathspec.last.path, path)\n        response.pathspec = pathspec\n        yield response\n      except OSError:\n        pass",
    "docstring": "List all files in the dir."
  },
  {
    "code": "def _valid_directory(self, path):\n        abspath = os.path.abspath(path)\n        if not os.path.isdir(abspath):\n            raise argparse.ArgumentTypeError('Not a valid directory: {}'.format(abspath))\n        return abspath",
    "docstring": "Ensure that the given path is valid.\n\n        :param str path: A valid directory path.\n        :raises: :py:class:`argparse.ArgumentTypeError`\n        :returns: An absolute directory path."
  },
  {
    "code": "def schema_remove(dbname, name,\n                  user=None,\n                  db_user=None, db_password=None,\n                  db_host=None, db_port=None):\n    if not schema_exists(dbname, name, user=None,\n                         db_user=db_user, db_password=db_password,\n                         db_host=db_host, db_port=db_port):\n        log.info('Schema \\'%s\\' does not exist in \\'%s\\'', name, dbname)\n        return False\n    sub_cmd = 'DROP SCHEMA \"{0}\"'.format(name)\n    _psql_prepare_and_run(\n        ['-c', sub_cmd],\n        runas=user,\n        maintenance_db=dbname,\n        host=db_host, user=db_user, port=db_port, password=db_password)\n    if not schema_exists(dbname, name, user,\n                         db_user=db_user, db_password=db_password,\n                         db_host=db_host, db_port=db_port):\n        return True\n    else:\n        log.info('Failed to delete schema \\'%s\\'.', name)\n        return False",
    "docstring": "Removes a schema from the Postgres server.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' postgres.schema_remove dbname schemaname\n\n    dbname\n        Database name we work on\n\n    schemaname\n        The schema's name we'll remove\n\n    user\n        System user all operations should be performed on behalf of\n\n    db_user\n        database username if different from config or default\n\n    db_password\n        user password if any password for a specified user\n\n    db_host\n        Database host if different from config or default\n\n    db_port\n        Database port if different from config or default"
  },
  {
    "code": "def _include_environment_variables(self, program, executor_vars):\n        env_vars = {\n            'RESOLWE_HOST_URL': self.settings_actual.get('RESOLWE_HOST_URL', 'localhost'),\n        }\n        set_env = self.settings_actual.get('FLOW_EXECUTOR', {}).get('SET_ENV', {})\n        env_vars.update(executor_vars)\n        env_vars.update(set_env)\n        export_commands = ['export {}={}'.format(key, shlex.quote(value)) for key, value in env_vars.items()]\n        return os.linesep.join(export_commands) + os.linesep + program",
    "docstring": "Define environment variables."
  },
  {
    "code": "def user_list(database=None, user=None, password=None, host=None, port=None):\n    client = _client(user=user, password=password, host=host, port=port)\n    if not database:\n        return client.get_list_cluster_admins()\n    client.switch_database(database)\n    return client.get_list_users()",
    "docstring": "List cluster admins or database users.\n\n    If a database is specified: it will return database users list.\n    If a database is not specified: it will return cluster admins list.\n\n    database\n        The database to list the users from\n\n    user\n        The user to connect as\n\n    password\n        The password of the user\n\n    host\n        The host to connect to\n\n    port\n        The port to connect to\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' influxdb08.user_list\n        salt '*' influxdb08.user_list <database>\n        salt '*' influxdb08.user_list <database> <user> <password> <host> <port>"
  },
  {
    "code": "def _exchange_refresh_tokens(self):\n        'Exchanges a refresh token for an access token'\n        if self.token_cache is not None and 'refresh' in self.token_cache:\n            refresh_form = {\n                'grant_type': 'refresh_token',\n                'refresh_token': self.token_cache['refresh'],\n                'client_id': self.client_id,\n                'client_secret': self.client_secret,\n            }\n            try:\n                tokens = self._request_tokens_from_token_endpoint(refresh_form)\n                tokens['refresh'] = self.token_cache['refresh']\n                return tokens\n            except OAuth2Exception:\n                logging.exception(\n                    'Encountered an exception during refresh token flow.')\n        return None",
    "docstring": "Exchanges a refresh token for an access token"
  },
  {
    "code": "def _parse_domain_id(self, config):\n        match = re.search(r'domain-id (.+)$', config)\n        value = match.group(1) if match else None\n        return dict(domain_id=value)",
    "docstring": "Scans the config block and parses the domain-id value\n\n        Args:\n            config (str): The config block to scan\n\n        Returns:\n            dict: A dict object that is intended to be merged into the\n                resource dict"
  },
  {
    "code": "def clean_new(self, value):\n        value = self.schema_class(value).full_clean()\n        return self.object_class(**value)",
    "docstring": "Return a new object instantiated with cleaned data."
  },
  {
    "code": "def create_user_deliveryserver(self, domainid, data):\n        return self.api_call(\n            ENDPOINTS['userdeliveryservers']['new'],\n            dict(domainid=domainid),\n            body=data)",
    "docstring": "Create a user delivery server"
  },
  {
    "code": "def rewind(self):\n        self.__data = deque()\n        self.__id = None\n        self.__address = None\n        self.__retrieved = 0\n        self.__killed = False\n        return self",
    "docstring": "Rewind this cursor to its unevaluated state.\n\n        Reset this cursor if it has been partially or completely evaluated.\n        Any options that are present on the cursor will remain in effect.\n        Future iterating performed on this cursor will cause new queries to\n        be sent to the server, even if the resultant data has already been\n        retrieved by this cursor."
  },
  {
    "code": "def swap(self, a, b):\n        self.mem[a], self.mem[b] = self.mem[b], self.mem[a]\n        self.asm[a], self.asm[b] = self.asm[b], self.asm[a]",
    "docstring": "Swaps mem positions a and b"
  },
  {
    "code": "def pformat(tree):\n    if tree.empty():\n        return ''\n    buf = six.StringIO()\n    for line in _pformat(tree.root, 0):\n        buf.write(line + \"\\n\")\n    return buf.getvalue().strip()",
    "docstring": "Recursively formats a tree into a nice string representation.\n\n    Example Input:\n     yahoo = tt.Tree(tt.Node(\"CEO\"))\n     yahoo.root.add(tt.Node(\"Infra\"))\n     yahoo.root[0].add(tt.Node(\"Boss\"))\n     yahoo.root[0][0].add(tt.Node(\"Me\"))\n     yahoo.root.add(tt.Node(\"Mobile\"))\n     yahoo.root.add(tt.Node(\"Mail\"))\n\n    Example Output:\n     CEO\n     |__Infra\n     |  |__Boss\n     |     |__Me\n     |__Mobile\n     |__Mail"
  },
  {
    "code": "def create_server(cloud, **kwargs):\n    if cloud == 'ec2':\n        _create_server_ec2(**kwargs)\n    elif cloud == 'rackspace':\n        _create_server_rackspace(**kwargs)\n    elif cloud == 'gce':\n        _create_server_gce(**kwargs)\n    else:\n        raise ValueError(\"Unknown cloud type: {}\".format(cloud))",
    "docstring": "Create a new instance"
  },
  {
    "code": "def wait_for_jobs(self, job_ids, timeout, delay):\n        if self.skip:\n            return\n        logger.debug(\"Waiting up to %d sec for completion of the job IDs %s\", timeout, job_ids)\n        remaining_job_ids = set(job_ids)\n        found_jobs = []\n        countdown = timeout\n        while countdown > 0:\n            matched_jobs = self.find_jobs(remaining_job_ids)\n            if matched_jobs:\n                remaining_job_ids.difference_update({job[\"id\"] for job in matched_jobs})\n                found_jobs.extend(matched_jobs)\n            if not remaining_job_ids:\n                return found_jobs\n            time.sleep(delay)\n            countdown -= delay\n        logger.error(\n            \"Timed out while waiting for completion of the job IDs %s. Results not updated.\",\n            list(remaining_job_ids),\n        )",
    "docstring": "Waits until the jobs appears in the completed job queue."
  },
  {
    "code": "def S_star(u, dfs_data):\n    s_u = S(u, dfs_data)\n    if u not in s_u:\n        s_u.append(u)\n    return s_u",
    "docstring": "The set of all descendants of u, with u added."
  },
  {
    "code": "def _gen_full_path(self, filename, file_system=None):\n        if file_system is None:\n            return '{}/{}'.format(self.dest_file_system, filename)\n        else:\n            if \":\" not in file_system:\n                raise ValueError(\"Invalid file_system specified: {}\".format(file_system))\n            return '{}/{}'.format(file_system, filename)",
    "docstring": "Generate full file path on remote device."
  },
  {
    "code": "def setUser(self, *args, **kwargs):\n        try:\n            user = self.mambuuserclass(entid=self['assignedUserKey'], *args, **kwargs)\n        except KeyError as kerr:\n            err = MambuError(\"La cuenta %s no tiene asignado un usuario\" % self['id'])\n            err.noUser = True\n            raise err\n        except AttributeError as ae:\n            from .mambuuser import MambuUser\n            self.mambuuserclass = MambuUser\n            try:\n                user = self.mambuuserclass(entid=self['assignedUserKey'], *args, **kwargs)\n            except KeyError as kerr:\n                err = MambuError(\"La cuenta %s no tiene asignado un usuario\" % self['id'])\n                err.noUser = True\n                raise err\n        self['user'] = user\n        return 1",
    "docstring": "Adds the user for this loan to a 'user' field.\n\n        User is a MambuUser object.\n\n        Returns the number of requests done to Mambu."
  },
  {
    "code": "def get_xpath(stmt, qualified=False, prefix_to_module=False):\n    return mk_path_str(stmt, with_prefixes=qualified,\n                       prefix_onchange=True, prefix_to_module=prefix_to_module)",
    "docstring": "Gets the XPath of the statement.\n    Unless qualified=True, does not include prefixes unless the prefix\n      changes mid-XPath.\n\n    qualified will add a prefix to each node.\n\n    prefix_to_module will resolve prefixes to module names instead.\n\n    For RFC 8040, set prefix_to_module=True:\n      /prefix:root/node/prefix:node/...\n\n    qualified=True:\n      /prefix:root/prefix:node/prefix:node/...\n\n    qualified=True, prefix_to_module=True:\n      /module:root/module:node/module:node/...\n    prefix_to_module=True: /module:root/node/module:node/..."
  },
  {
    "code": "def clean_markup(self, markup, parser=None):\n        result_type = type(markup)\n        if isinstance(markup, six.string_types):\n            doc = fromstring(markup, parser=parser)\n        else:\n            doc = copy.deepcopy(markup)\n        self(doc)\n        if issubclass(result_type, six.binary_type):\n            return tostring(doc, encoding='utf-8')\n        elif issubclass(result_type, six.text_type):\n            return tostring(doc, encoding='unicode')\n        else:\n            return doc",
    "docstring": "Apply ``Cleaner`` to markup string or document and return a cleaned string or document."
  },
  {
    "code": "def _read_provenance_from_xml(self, root):\n        path = self._special_properties['provenance']\n        provenance = root.find(path, XML_NS)\n        for step in provenance.iter('provenance_step'):\n            title = step.find('title').text\n            description = step.find('description').text\n            timestamp = step.get('timestamp')\n            if 'IF Provenance' in title:\n                data = {}\n                from safe.metadata35.provenance import IFProvenanceStep\n                keys = IFProvenanceStep.impact_functions_fields\n                for key in keys:\n                    value = step.find(key)\n                    if value is not None:\n                        data[key] = value.text\n                    else:\n                        data[key] = ''\n                self.append_if_provenance_step(\n                    title, description, timestamp, data)\n            else:\n                self.append_provenance_step(title, description, timestamp)",
    "docstring": "read metadata provenance from xml.\n\n        :param root: container in which we search\n        :type root: ElementTree.Element"
  },
  {
    "code": "def empty_tree(input_list):\n    for item in input_list:\n        if not isinstance(item, list) or not empty_tree(item):\n            return False\n    return True",
    "docstring": "Recursively iterate through values in nested lists."
  },
  {
    "code": "def stp(br=None, state='disable', iface=None):\n    kernel = __grains__['kernel']\n    if kernel == 'Linux':\n        states = {'enable': 'on', 'disable': 'off'}\n        return _os_dispatch('stp', br, states[state])\n    elif kernel in SUPPORTED_BSD_LIKE:\n        states = {'enable': 'stp', 'disable': '-stp'}\n        return _os_dispatch('stp', br, states[state], iface)\n    else:\n        return False",
    "docstring": "Sets Spanning Tree Protocol state for a bridge\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' bridge.stp br0 enable\n        salt '*' bridge.stp br0 disable\n\n    For BSD-like operating systems, it is required to add the interface on\n    which to enable the STP.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' bridge.stp bridge0 enable fxp0\n        salt '*' bridge.stp bridge0 disable fxp0"
  },
  {
    "code": "def getCanonicalID(iname, xrd_tree):\n    xrd_list = xrd_tree.findall(xrd_tag)\n    xrd_list.reverse()\n    try:\n        canonicalID = xri.XRI(xrd_list[0].findall(canonicalID_tag)[0].text)\n    except IndexError:\n        return None\n    childID = canonicalID.lower()\n    for xrd in xrd_list[1:]:\n        parent_sought = childID[:childID.rindex('!')]\n        parent = xri.XRI(xrd.findtext(canonicalID_tag))\n        if parent_sought != parent.lower():\n            raise XRDSFraud(\"%r can not come from %s\" % (childID, parent))\n        childID = parent_sought\n    root = xri.rootAuthority(iname)\n    if not xri.providerIsAuthoritative(root, childID):\n        raise XRDSFraud(\"%r can not come from root %r\" % (childID, root))\n    return canonicalID",
    "docstring": "Return the CanonicalID from this XRDS document.\n\n    @param iname: the XRI being resolved.\n    @type iname: unicode\n\n    @param xrd_tree: The XRDS output from the resolver.\n    @type xrd_tree: ElementTree\n\n    @returns: The XRI CanonicalID or None.\n    @returntype: unicode or None"
  },
  {
    "code": "def _build_ds_from_instruction(instruction, ds_from_file_fn):\n  examples_ds = ds_from_file_fn(instruction[\"filepath\"])\n  mask_ds = _build_mask_ds(\n      mask_offset=instruction[\"mask_offset\"],\n      mask=instruction[\"mask\"],\n  )\n  ds = tf.data.Dataset.zip((examples_ds, mask_ds))\n  ds = ds.filter(lambda example, mask: mask)\n  ds = ds.map(lambda example, mask: example)\n  return ds",
    "docstring": "Map an instruction to a real datasets for one particular shard.\n\n  Args:\n    instruction: A `dict` of `tf.Tensor` containing the instruction to load\n      the particular shard (filename, mask,...)\n    ds_from_file_fn: `fct`, function which returns the dataset associated to\n      the filename\n\n  Returns:\n    dataset: `tf.data.Dataset`, The shard loaded from the instruction"
  },
  {
    "code": "def main():\n    args = parse_arguments()\n    pid = args.pid\n    title = get_programme_title(pid)\n    broadcast_date = get_broadcast_date(pid)\n    listing = extract_listing(pid)\n    filename = get_output_filename(args)\n    tracklisting = generate_output(listing, title, broadcast_date)\n    output_to_file(filename, tracklisting, args.action)\n    print(\"Done!\")",
    "docstring": "Get a tracklisting, write to audio file or text."
  },
  {
    "code": "def copy_file_links(self, src):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not yet initialized')\n        if src.dr_entries.px_record is None:\n            if src.ce_entries.px_record is None:\n                raise pycdlibexception.PyCdlibInvalidInput('No Rock Ridge file links')\n            num_links = src.ce_entries.px_record.posix_file_links\n        else:\n            num_links = src.dr_entries.px_record.posix_file_links\n        if self.dr_entries.px_record is None:\n            if self.ce_entries.px_record is None:\n                raise pycdlibexception.PyCdlibInvalidInput('No Rock Ridge file links')\n            self.ce_entries.px_record.posix_file_links = num_links\n        else:\n            self.dr_entries.px_record.posix_file_links = num_links",
    "docstring": "Copy the number of file links from the source Rock Ridge entry into\n        this Rock Ridge entry.\n\n        Parameters:\n         src - The source Rock Ridge entry to copy from.\n        Returns:\n         Nothing."
  },
  {
    "code": "def __fill_buffer(self, size=0):\n    read_size = min(max(size, self.__buffer_size), MAX_BLOB_FETCH_SIZE)\n    self.__buffer = fetch_data(self.__blob_key, self.__position,\n                               self.__position + read_size - 1)\n    self.__buffer_position = 0\n    self.__eof = len(self.__buffer) < read_size",
    "docstring": "Fills the internal buffer.\n\n    Args:\n      size: Number of bytes to read. Will be clamped to\n        [self.__buffer_size, MAX_BLOB_FETCH_SIZE]."
  },
  {
    "code": "def _cast_to_type(self, value):\n        if value in (True, False):\n            return bool(value)\n        if value in ('t', 'True', '1'):\n            return True\n        if value in ('f', 'False', '0'):\n            return False\n        self.fail('invalid', value=value)",
    "docstring": "Convert the value to a boolean and raise error on failures"
  },
  {
    "code": "def _parse_config(self, requires_cfg=True):\n        if len(self.config_paths) > 0:\n            try:\n                self._find_config()\n            except BisonError:\n                if not requires_cfg:\n                    return\n                raise\n            try:\n                with open(self.config_file, 'r') as f:\n                    parsed = self._fmt_to_parser[self.config_format](f)\n            except Exception as e:\n                raise BisonError(\n                    'Failed to parse config file: {}'.format(self.config_file)\n                ) from e\n            self._full_config = None\n            self._config = parsed",
    "docstring": "Parse the configuration file, if one is configured, and add it to\n        the `Bison` state.\n\n        Args:\n            requires_cfg (bool): Specify whether or not parsing should fail\n                if a config file is not found. (default: True)"
  },
  {
    "code": "def op_paths(self, path_prefix=None):\n        url_path = self.path\n        if path_prefix:\n            url_path = path_prefix + url_path\n        yield url_path, self",
    "docstring": "Yield operations paths stored in containers."
  },
  {
    "code": "def BoolEncoder(field_number, is_repeated, is_packed):\n  false_byte = b'\\x00'\n  true_byte = b'\\x01'\n  if is_packed:\n    tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)\n    local_EncodeVarint = _EncodeVarint\n    def EncodePackedField(write, value):\n      write(tag_bytes)\n      local_EncodeVarint(write, len(value))\n      for element in value:\n        if element:\n          write(true_byte)\n        else:\n          write(false_byte)\n    return EncodePackedField\n  elif is_repeated:\n    tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT)\n    def EncodeRepeatedField(write, value):\n      for element in value:\n        write(tag_bytes)\n        if element:\n          write(true_byte)\n        else:\n          write(false_byte)\n    return EncodeRepeatedField\n  else:\n    tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT)\n    def EncodeField(write, value):\n      write(tag_bytes)\n      if value:\n        return write(true_byte)\n      return write(false_byte)\n    return EncodeField",
    "docstring": "Returns an encoder for a boolean field."
  },
  {
    "code": "def get_python(self):\n        if self.multiselect:\n            return super(MultiSelectField, self).get_python()\n        return self._get()",
    "docstring": "Only return cursor instance if configured for multiselect"
  },
  {
    "code": "def update(self, sequence=None, **mapping):\n        if sequence is not None:\n            if isinstance(sequence, dict):\n                for slot in sequence:\n                    self[slot] = sequence[slot]\n            else:\n                for slot, value in sequence:\n                    self[slot] = value\n        if mapping:\n            for slot in sequence:\n                self[slot] = sequence[slot]",
    "docstring": "Add multiple elements to the fact."
  },
  {
    "code": "def OnUpdateFigurePanel(self, event):\n        if self.updating:\n            return\n        self.updating = True\n        self.figure_panel.update(self.get_figure(self.code))\n        self.updating = False",
    "docstring": "Redraw event handler for the figure panel"
  },
  {
    "code": "def triplify(binding):\n    triples = []\n    if binding.data is None:\n        return None, triples\n    if binding.is_object:\n        return triplify_object(binding)\n    elif binding.is_array:\n        for item in binding.items:\n            _, item_triples = triplify(item)\n            triples.extend(item_triples)\n        return None, triples\n    else:\n        subject = binding.parent.subject\n        triples.append((subject, binding.predicate, binding.object))\n        if binding.reverse is not None:\n            triples.append((binding.object, binding.reverse, subject))\n        return subject, triples",
    "docstring": "Recursively generate RDF statement triples from the data and\n    schema supplied to the application."
  },
  {
    "code": "def plug(self):\n        if self.__plugged:\n            return\n        for _, method in inspect.getmembers(self, predicate=inspect.ismethod):\n            if hasattr(method, '_callback_messages'):\n                for message in method._callback_messages:\n                    global_callbacks[message].add(method)\n        self.__plugged = True",
    "docstring": "Add the actor's methods to the callback registry."
  },
  {
    "code": "def validate_create_package(package_format, owner, repo, **kwargs):\n    client = get_packages_api()\n    with catch_raise_api_exception():\n        check = getattr(\n            client, \"packages_validate_upload_%s_with_http_info\" % package_format\n        )\n        _, _, headers = check(\n            owner=owner, repo=repo, data=make_create_payload(**kwargs)\n        )\n    ratelimits.maybe_rate_limit(client, headers)\n    return True",
    "docstring": "Validate parameters for creating a package."
  },
  {
    "code": "def main(args):\n  ui = getUI(args)\n  if ui.optionIsSet(\"test\"):\n    unittest.main(argv=[sys.argv[0]])\n  elif ui.optionIsSet(\"help\"):\n    ui.usage()\n  else:\n    verbose = ui.optionIsSet(\"verbose\")\n    stranded = ui.optionIsSet(\"stranded\")\n    if stranded:\n      sys.stderr.write(\"Sorry, stranded mode hasn't been implemented yet.\")\n      sys.exit()\n    regions_1 = [e for e in BEDIterator(ui.getArgument(0), verbose=verbose)]\n    regions_2 = [e for e in BEDIterator(ui.getArgument(1), verbose=verbose)]\n    print jaccardIndex(regions_1, regions_2)",
    "docstring": "main entry point for the GenomicIntJaccard script.\n\n  :param args: the arguments for this script, as a list of string. Should\n               already have had things like the script name stripped. That\n               is, if there are no args provided, this should be an empty\n               list."
  },
  {
    "code": "def get_assignable_objective_bank_ids(self, objective_bank_id):\n        mgr = self._get_provider_manager('LEARNING', local=True)\n        lookup_session = mgr.get_objective_bank_lookup_session(proxy=self._proxy)\n        objective_banks = lookup_session.get_objective_banks()\n        id_list = []\n        for objective_bank in objective_banks:\n            id_list.append(objective_bank.get_id())\n        return IdList(id_list)",
    "docstring": "Gets a list of objective banks including and under the given objective bank node in which any objective can be assigned.\n\n        arg:    objective_bank_id (osid.id.Id): the ``Id`` of the\n                ``ObjectiveBank``\n        return: (osid.id.IdList) - list of assignable objective bank\n                ``Ids``\n        raise:  NullArgument - ``objective_bank_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def do_types_conflict(type1: GraphQLOutputType, type2: GraphQLOutputType) -> bool:\n    if is_list_type(type1):\n        return (\n            do_types_conflict(\n                cast(GraphQLList, type1).of_type, cast(GraphQLList, type2).of_type\n            )\n            if is_list_type(type2)\n            else True\n        )\n    if is_list_type(type2):\n        return True\n    if is_non_null_type(type1):\n        return (\n            do_types_conflict(\n                cast(GraphQLNonNull, type1).of_type, cast(GraphQLNonNull, type2).of_type\n            )\n            if is_non_null_type(type2)\n            else True\n        )\n    if is_non_null_type(type2):\n        return True\n    if is_leaf_type(type1) or is_leaf_type(type2):\n        return type1 is not type2\n    return False",
    "docstring": "Check whether two types conflict\n\n    Two types conflict if both types could not apply to a value simultaneously.\n    Composite types are ignored as their individual field types will be compared later\n    recursively. However List and Non-Null types must match."
  },
  {
    "code": "def plan(self):\n\t\tfor invoiceitem in self.invoiceitems.all():\n\t\t\tif invoiceitem.plan:\n\t\t\t\treturn invoiceitem.plan\n\t\tif self.subscription:\n\t\t\treturn self.subscription.plan",
    "docstring": "Gets the associated plan for this invoice.\n\n\t\tIn order to provide a consistent view of invoices, the plan object\n\t\tshould be taken from the first invoice item that has one, rather than\n\t\tusing the plan associated with the subscription.\n\n\t\tSubscriptions (and their associated plan) are updated by the customer\n\t\tand represent what is current, but invoice items are immutable within\n\t\tthe invoice and stay static/unchanged.\n\n\t\tIn other words, a plan retrieved from an invoice item will represent\n\t\tthe plan as it was at the time an invoice was issued.  The plan\n\t\tretrieved from the subscription will be the currently active plan.\n\n\t\t:returns: The associated plan for the invoice.\n\t\t:rtype: ``djstripe.Plan``"
  },
  {
    "code": "def rotate_concurrent(self, *locations, **kw):\n        timer = Timer()\n        pool = CommandPool(concurrency=10)\n        logger.info(\"Scanning %s ..\", pluralize(len(locations), \"backup location\"))\n        for location in locations:\n            for cmd in self.rotate_backups(location, prepare=True, **kw):\n                pool.add(cmd)\n        if pool.num_commands > 0:\n            backups = pluralize(pool.num_commands, \"backup\")\n            logger.info(\"Preparing to rotate %s (in parallel) ..\", backups)\n            pool.run()\n            logger.info(\"Successfully rotated %s in %s.\", backups, timer)",
    "docstring": "Rotate the backups in the given locations concurrently.\n\n        :param locations: One or more values accepted by :func:`coerce_location()`.\n        :param kw: Any keyword arguments are passed on to :func:`rotate_backups()`.\n\n        This function uses :func:`rotate_backups()` to prepare rotation\n        commands for the given locations and then it removes backups in\n        parallel, one backup per mount point at a time.\n\n        The idea behind this approach is that parallel rotation is most useful\n        when the files to be removed are on different disks and so multiple\n        devices can be utilized at the same time.\n\n        Because mount points are per system :func:`rotate_concurrent()` will\n        also parallelize over backups located on multiple remote systems."
  },
  {
    "code": "def join(self):\n        for thread in self.worker_threads:\n            thread.join()\n        WorkerThread.join(self)",
    "docstring": "Joins the coordinator thread and all worker threads."
  },
  {
    "code": "def track(cls, obj, ptr):\n        cls._objects.add(cls(obj, ptr))",
    "docstring": "Track an object which needs destruction when it is garbage collected."
  },
  {
    "code": "def properties_for(self, index):\n        return vectorize(lambda i: [prop for prop in self.properties() if i in self[prop]], otypes=[list])(index)",
    "docstring": "Returns a list of properties, such that each entry in the list corresponds\n        to the element of the index given.\n\n        Example:\n        let properties: 'one':[1,2,3,4], 'two':[3,5,6]\n\n        >>> properties_for([2,3,5])\n        [['one'], ['one', 'two'], ['two']]"
  },
  {
    "code": "def schedule(\n        time: Union[datetime.time, datetime.datetime],\n        callback: Callable, *args):\n    dt = _fillDate(time)\n    now = datetime.datetime.now(dt.tzinfo)\n    delay = (dt - now).total_seconds()\n    loop = asyncio.get_event_loop()\n    loop.call_later(delay, callback, *args)",
    "docstring": "Schedule the callback to be run at the given time with\n    the given arguments.\n\n    Args:\n        time: Time to run callback. If given as :py:class:`datetime.time`\n            then use today as date.\n        callback: Callable scheduled to run.\n        args: Arguments for to call callback with."
  },
  {
    "code": "def url_read(url, verbose=True):\n    r\n    if url.find('://') == -1:\n        url = 'http://' + url\n    if verbose:\n        print('Reading data from url=%r' % (url,))\n    try:\n        file_ = _urllib.request.urlopen(url)\n    except IOError:\n        raise\n    data = file_.read()\n    file_.close()\n    return data",
    "docstring": "r\"\"\"\n    Directly reads data from url"
  },
  {
    "code": "def remove_stale_sockets(self):\n        if self.opts.max_idle_time_seconds is not None:\n            with self.lock:\n                while (self.sockets and\n                       self.sockets[-1].idle_time_seconds() > self.opts.max_idle_time_seconds):\n                    sock_info = self.sockets.pop()\n                    sock_info.close()\n        while True:\n            with self.lock:\n                if (len(self.sockets) + self.active_sockets >=\n                        self.opts.min_pool_size):\n                    break\n            if not self._socket_semaphore.acquire(False):\n                break\n            try:\n                sock_info = self.connect()\n                with self.lock:\n                    self.sockets.appendleft(sock_info)\n            finally:\n                self._socket_semaphore.release()",
    "docstring": "Removes stale sockets then adds new ones if pool is too small."
  },
  {
    "code": "def reset(self):\r\n        self._elapsed = datetime.timedelta()\r\n        self._delta = datetime.timedelta()\r\n        self._starttime = datetime.datetime.now()\r\n        self.refresh()",
    "docstring": "Stops the timer and resets its values to 0."
  },
  {
    "code": "def seek(self, offset, whence=os.SEEK_SET):\n        pos = None\n        if whence == os.SEEK_SET:\n            pos = self.offset + offset\n        elif whence == os.SEEK_CUR:\n            pos = self.tell() + offset\n        elif whence == os.SEEK_END:\n            pos = self.offset + self.len + offset\n        else:\n            raise ValueError(\"invalid whence {}\".format(whence))\n        if pos > self.offset + self.len or pos < self.offset:\n            raise ValueError(\"seek position beyond chunk area\")\n        self.parent_fd.seek(pos, os.SEEK_SET)",
    "docstring": "Seek to position in stream, see file.seek"
  },
  {
    "code": "def javadoc_role(name, rawtext, text, lineno, inliner, options={}, content=[]):\n    has_explicit_title, title, target = split_explicit_title(text)\n    title = utils.unescape(title)\n    target = utils.unescape(target)\n    if not has_explicit_title:\n        target = target.lstrip('~')\n        if title[0] == '~':\n            title = title[1:].rpartition('.')[2]\n    app = inliner.document.settings.env.app\n    ref = get_javadoc_ref(app, rawtext, target)\n    if not ref:\n         raise ValueError(\"no Javadoc source found for %s in javadoc_url_map\" % (target,))\n    ref.append(nodes.Text(title, title))\n    return [ref], []",
    "docstring": "Role for linking to external Javadoc"
  },
  {
    "code": "def _get_graph(graph, filename):\n    try:\n        rendered = graph.rendered_file\n    except AttributeError:\n        try:\n            graph.render(os.path.join(server.tmpdir, filename), format='png')\n            rendered = filename\n        except OSError:\n            rendered = None\n    graph.rendered_file = rendered\n    return rendered",
    "docstring": "Retrieve or render a graph."
  },
  {
    "code": "def read(self, size=None):\n        if size is None or size < 0:\n            raise exceptions.NotYetImplementedError(\n                'Illegal read of size %s requested on BufferedStream. '\n                'Wrapped stream %s is at position %s-%s, '\n                '%s bytes remaining.' %\n                (size, self.__stream, self.__start_pos, self.__end_pos,\n                 self._bytes_remaining))\n        data = ''\n        if self._bytes_remaining:\n            size = min(size, self._bytes_remaining)\n            data = self.__buffered_data[\n                self.__buffer_pos:self.__buffer_pos + size]\n            self.__buffer_pos += size\n        return data",
    "docstring": "Reads from the buffer."
  },
  {
    "code": "def get_file(self, filename):\n        log.debug('[%s]: reading: //%s/%s', self.name, self.name, filename)\n        try:\n            blob = self.repo.head.commit.tree/filename\n            return blob.data_stream\n        except KeyError as err:\n            raise GitError(err)",
    "docstring": "Get a file from the repo.\n\n        Returns a file-like stream with the data."
  },
  {
    "code": "def is_port_default(self):\n        if self.scheme in RELATIVE_SCHEME_DEFAULT_PORTS:\n            return RELATIVE_SCHEME_DEFAULT_PORTS[self.scheme] == self.port",
    "docstring": "Return whether the URL is using the default port."
  },
  {
    "code": "def jsonload(model, fp):\n    dumped_list = json.load(fp)\n    for link in dumped_list:\n        if len(link) == 2:\n            sid, (s, p, o, a) = link\n        elif len(link) == 4:\n            (s, p, o, a) = link\n            tt = a.get('@target-type')\n            if tt == '@iri-ref':\n                o = I(o)\n            a.pop('@target-type', None)\n        else:\n            continue\n        model.add(s, p, o, a)\n    return",
    "docstring": "Load Versa model dumped into JSON form, either raw or canonical"
  },
  {
    "code": "def policy_and_value_net(rng_key,\n                         batch_observations_shape,\n                         num_actions,\n                         bottom_layers=None):\n  cur_layers = []\n  if bottom_layers is not None:\n    cur_layers.extend(bottom_layers)\n  cur_layers.extend([layers.Branch(), layers.Parallel(\n      layers.Serial(layers.Dense(num_actions), layers.LogSoftmax()),\n      layers.Dense(1)\n  )])\n  net = layers.Serial(*cur_layers)\n  return net.initialize(batch_observations_shape, rng_key), net",
    "docstring": "A policy and value net function."
  },
  {
    "code": "def zlist(self, name_start, name_end, limit=10):\n        limit = get_positive_integer('limit', limit)\n        return self.execute_command('zlist', name_start, name_end, limit)",
    "docstring": "Return a list of the top ``limit`` zset's name between ``name_start`` and\n        ``name_end`` in ascending order\n\n        .. note:: The range is (``name_start``, ``name_end``]. The ``name_start``\n           isn't in the range, but ``name_end`` is.\n\n        :param string name_start: The lower bound(not included) of zset names to\n         be returned, empty string ``''`` means -inf\n        :param string name_end: The upper bound(included) of zset names to be\n         returned, empty string ``''`` means +inf\n        :param int limit: number of elements will be returned.\n        :return: a list of zset's name\n        :rtype: list\n        \n        >>> ssdb.zlist('zset_ ', 'zset_z', 10)\n        ['zset_1', 'zset_2']\n        >>> ssdb.zlist('zset_ ', '', 3)\n        ['zset_1', 'zset_2']\n        >>> ssdb.zlist('', 'aaa_not_exist', 10)\n        []"
  },
  {
    "code": "def GetLoggingLocation():\n  frame = inspect.currentframe()\n  this_file = frame.f_code.co_filename\n  frame = frame.f_back\n  while frame:\n    if this_file == frame.f_code.co_filename:\n      if 'cdbg_logging_location' in frame.f_locals:\n        ret = frame.f_locals['cdbg_logging_location']\n        if len(ret) != 3:\n          return (None, None, None)\n        return ret\n    frame = frame.f_back\n  return (None, None, None)",
    "docstring": "Search for and return the file and line number from the log collector.\n\n  Returns:\n    (pathname, lineno, func_name) The full path, line number, and function name\n    for the logpoint location."
  },
  {
    "code": "def subscribe_and_validate(self, topic, qos, payload, timeout=1):\n        seconds = convert_time(timeout)\n        self._verified = False\n        logger.info('Subscribing to topic: %s' % topic)\n        self._mqttc.subscribe(str(topic), int(qos))\n        self._payload = str(payload)\n        self._mqttc.on_message = self._on_message\n        timer_start = time.time()\n        while time.time() < timer_start + seconds:\n            if self._verified:\n                break\n            self._mqttc.loop()\n        if not self._verified:\n            raise AssertionError(\"The expected payload didn't arrive in the topic\")",
    "docstring": "Subscribe to a topic and validate that the specified payload is\n        received within timeout. It is required that a connection has been\n        established using `Connect` keyword. The payload can be specified as\n        a python regular expression. If the specified payload is not received\n        within timeout, an AssertionError is thrown.\n\n        `topic` topic to subscribe to\n\n        `qos` quality of service for the subscription\n\n        `payload` payload (message) that is expected to arrive\n\n        `timeout` time to wait for the payload to arrive\n\n        Examples:\n\n        | Subscribe And Validate | test/test | 1 | test message |"
  },
  {
    "code": "def validate_cmap(val):\n    from matplotlib.colors import Colormap\n    try:\n        return validate_str(val)\n    except ValueError:\n        if not isinstance(val, Colormap):\n            raise ValueError(\n                \"Could not find a valid colormap!\")\n        return val",
    "docstring": "Validate a colormap\n\n    Parameters\n    ----------\n    val: str or :class:`mpl.colors.Colormap`\n\n    Returns\n    -------\n    str or :class:`mpl.colors.Colormap`\n\n    Raises\n    ------\n    ValueError"
  },
  {
    "code": "def export_module_spec_with_checkpoint(module_spec,\n                                       checkpoint_path,\n                                       export_path,\n                                       scope_prefix=\"\"):\n  with tf.Graph().as_default():\n    m = hub.Module(module_spec)\n    assign_map = {\n        scope_prefix + name: value for name, value in m.variable_map.items()\n    }\n    tf.train.init_from_checkpoint(checkpoint_path, assign_map)\n    init_op = tf.initializers.global_variables()\n    with tf.Session() as session:\n      session.run(init_op)\n      m.export(export_path, session)",
    "docstring": "Exports given checkpoint as tfhub module with given spec."
  },
  {
    "code": "def integer(prompt=None, empty=False):\n    s = _prompt_input(prompt)\n    if empty and not s:\n        return None\n    else:\n        try:\n            return int(s)\n        except ValueError:\n            return integer(prompt=prompt, empty=empty)",
    "docstring": "Prompt an integer.\n\n    Parameters\n    ----------\n    prompt : str, optional\n        Use an alternative prompt.\n    empty : bool, optional\n        Allow an empty response.\n\n    Returns\n    -------\n    int or None\n        An int if the user entered a valid integer.\n        None if the user pressed only Enter and ``empty`` was True."
  },
  {
    "code": "def add_edge_fun(graph):\n    succ, pred, node = graph._succ, graph._pred, graph._node\n    def add_edge(u, v, **attr):\n        if v not in succ:\n            succ[v], pred[v], node[v] = {}, {}, {}\n        succ[u][v] = pred[v][u] = attr\n    return add_edge",
    "docstring": "Returns a function that adds an edge to the `graph` checking only the out\n    node.\n\n    :param graph:\n        A directed graph.\n    :type graph: networkx.classes.digraph.DiGraph\n\n    :return:\n        A function that adds an edge to the `graph`.\n    :rtype: callable"
  },
  {
    "code": "def wait_for(func):\n    @wraps(func)\n    def wrapped(*args, **kwargs):\n        timeout = kwargs.pop('timeout', TIMEOUT)\n        start = None\n        while True:\n            try:\n                return func(*args, **kwargs)\n            except AssertionError:\n                if not start:\n                    start = time()\n                if time() - start < timeout:\n                    sleep(CHECK_EVERY)\n                    continue\n                else:\n                    raise\n    return wrapped",
    "docstring": "A decorator to invoke a function, retrying on assertion errors for a\n    specified time interval.\n\n    Adds a kwarg `timeout` to `func` which is a number of seconds to try\n    for (default 15)."
  },
  {
    "code": "def _gcd_array(X):\n    greatest_common_divisor = 0.0\n    for x in X:\n        greatest_common_divisor = _gcd(greatest_common_divisor, x)\n    return greatest_common_divisor",
    "docstring": "Return the largest real value h such that all elements in x are integer\n    multiples of h."
  },
  {
    "code": "def print_update(self):\n        print(\"\\r\\n\")\n        now = datetime.datetime.now()\n        print(\"Update info: (from: %s)\" % now.strftime(\"%c\"))\n        current_total_size = self.total_stined_bytes + self.total_new_bytes\n        if self.total_errored_items:\n            print(\" * WARNING: %i omitted files!\" % self.total_errored_items)\n        print(\" * fast backup: %i files\" % self.total_fast_backup)\n        print(\n            \" * new content saved: %i files (%s %.1f%%)\"\n            % (\n                self.total_new_file_count,\n                human_filesize(self.total_new_bytes),\n                to_percent(self.total_new_bytes, current_total_size),\n            )\n        )\n        print(\n            \" * stint space via hardlinks: %i files (%s %.1f%%)\"\n            % (\n                self.total_file_link_count,\n                human_filesize(self.total_stined_bytes),\n                to_percent(self.total_stined_bytes, current_total_size),\n            )\n        )\n        duration = default_timer() - self.start_time\n        performance = current_total_size / duration / 1024.0 / 1024.0\n        print(\" * present performance: %.1fMB/s\\n\" % performance)",
    "docstring": "print some status information in between."
  },
  {
    "code": "def filter_parts(cls, part_info):\n        filtered = OrderedDict()\n        for part_name, info_list in part_info.items():\n            if info_list is None or isinstance(info_list, Exception):\n                continue\n            info_list = [i for i in info_list if isinstance(i, cls)]\n            if info_list:\n                filtered[part_name] = info_list\n        return filtered",
    "docstring": "Filter the part_info dict looking for instances of our class\n\n        Args:\n            part_info (dict): {part_name: [Info] or None} as returned from\n                Controller.run_hook()\n\n        Returns:\n            dict: {part_name: [info]} where info is a subclass of cls"
  },
  {
    "code": "def inspect_hash(path):\n    \" Calculate the hash of a database, efficiently. \"\n    m = hashlib.sha256()\n    with path.open(\"rb\") as fp:\n        while True:\n            data = fp.read(HASH_BLOCK_SIZE)\n            if not data:\n                break\n            m.update(data)\n    return m.hexdigest()",
    "docstring": "Calculate the hash of a database, efficiently."
  },
  {
    "code": "def get_parent_element(self):\n        return {AUDIT_REF_STATE: self.context.audit_record,\n                SIGNATURE_REF_STATE: self.context.signature}[self.ref_state]",
    "docstring": "Signatures and Audit elements share sub-elements, we need to know which to set attributes on"
  },
  {
    "code": "def chosen_view_factory(chooser_cls):\n    class ChosenView(chooser_cls):\n        def get(self, request, *args, **kwargs):\n            self.object = self.get_object()\n            return render_modal_workflow(\n                self.request,\n                None,\n                '{0}/chosen.js'.format(self.template_dir),\n                {'obj': self.get_json(self.object)}\n            )\n        def get_object(self, queryset=None):\n            if queryset is None:\n                queryset = self.get_queryset()\n            pk = self.kwargs.get('pk', None)\n            try:\n                return queryset.get(pk=pk)\n            except self.models.DoesNotExist:\n                raise Http404()\n        def post(self, request, *args, **kwargs):\n            return self.get(request, *args, **kwargs)\n    return ChosenView",
    "docstring": "Returns a ChosenView class that extends specified chooser class.\n\n    :param chooser_cls: the class to extend.\n    :rtype: class."
  },
  {
    "code": "def get_l(self):\n        cell_left = CellBorders(self.cell_attributes,\n                                *self.cell.get_left_key_rect())\n        return cell_left.get_r()",
    "docstring": "Returns the left border of the cell"
  },
  {
    "code": "def duplicates_removed(it, already_seen=()):\n    lst = []\n    seen = set()\n    for i in it:\n        if i in seen or i in already_seen:\n            continue\n        lst.append(i)\n        seen.add(i)\n    return lst",
    "docstring": "Returns a list with duplicates removed from the iterable `it`.\n\n    Order is preserved."
  },
  {
    "code": "def dtypes(self):\n        return Series(np.array(list(self._gather_dtypes().values()), dtype=np.bytes_),\n                      self.keys())",
    "docstring": "Series of NumPy dtypes present in the DataFrame with index of column names.\n\n        Returns\n        -------\n        Series"
  },
  {
    "code": "def getDocPath(fn, root=None):\n    cwd = pathlib.Path(os.getcwd())\n    if root:\n        cwd = pathlib.Path(root)\n    while True:\n        dpath = cwd.joinpath('docdata')\n        if dpath.is_dir():\n            break\n        parent = cwd.parent\n        if parent == cwd:\n            raise ValueError(f'Unable to find data directory from {os.getcwd()}.')\n        cwd = parent\n    fpath = os.path.abspath(os.path.join(dpath.as_posix(), fn))\n    if not fpath.startswith(dpath.as_posix()):\n        raise ValueError(f'Path escaping detected: {fn}')\n    if not os.path.isfile(fpath):\n        raise ValueError(f'File does not exist: {fn}')\n    return fpath",
    "docstring": "Helper for getting a documentation data file paths.\n\n    Args:\n        fn (str): Name of the file to retrieve the full path for.\n        root (str): Optional root path to look for a docdata in.\n\n    Notes:\n        Defaults to looking for the ``docdata`` directory in the current\n        working directory. This behavior works fine for notebooks nested\n        in the docs directory of synapse; but this root directory that\n        is looked for may be overridden by providing an alternative root.\n\n    Returns:\n        str: A file path.\n\n    Raises:\n        ValueError if the file does not exist or directory traversal attempted.."
  },
  {
    "code": "async def download_file(self, Bucket, Key, Filename, ExtraArgs=None, Callback=None, Config=None):\n    with open(Filename, 'wb') as open_file:\n        await download_fileobj(self, Bucket, Key, open_file, ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)",
    "docstring": "Download an S3 object to a file.\n\n    Usage::\n\n        import boto3\n        s3 = boto3.resource('s3')\n        s3.meta.client.download_file('mybucket', 'hello.txt', '/tmp/hello.txt')\n\n    Similar behavior as S3Transfer's download_file() method,\n    except that parameters are capitalized."
  },
  {
    "code": "def load(stream, overrides=None, **kwargs):\n    global is_initialized\n    if not is_initialized:\n        initialize()\n    if isinstance(stream, basestring):\n        string = stream\n    else:\n        string = '\\n'.join(stream.readlines())\n    proxy_graph = yaml.load(string, **kwargs)\n    from . import init\n    init_dict = proxy_graph.get('init', {})\n    init(**init_dict)\n    if overrides is not None:\n        handle_overrides(proxy_graph, overrides)\n    return instantiate_all(proxy_graph)",
    "docstring": "Loads a YAML configuration from a string or file-like object.\n\n    Parameters\n    ----------\n    stream : str or object\n        Either a string containing valid YAML or a file-like object\n        supporting the .read() interface.\n    overrides : dict, optional\n        A dictionary containing overrides to apply. The location of\n        the override is specified in the key as a dot-delimited path\n        to the desired parameter, e.g. \"model.corruptor.corruption_level\".\n\n    Returns\n    -------\n    graph : dict or object\n        The dictionary or object (if the top-level element specified an\n        Python object to instantiate).\n\n    Notes\n    -----\n    Other keyword arguments are passed on to `yaml.load`."
  },
  {
    "code": "def update(self, title=None, body=None, state=None):\n        data = {'title': title, 'body': body, 'state': state}\n        json = None\n        self._remove_none(data)\n        if data:\n            json = self._json(self._patch(self._api, data=dumps(data)), 200)\n        if json:\n            self._update_(json)\n            return True\n        return False",
    "docstring": "Update this pull request.\n\n        :param str title: (optional), title of the pull\n        :param str body: (optional), body of the pull request\n        :param str state: (optional), ('open', 'closed')\n        :returns: bool"
  },
  {
    "code": "def _attachToObject(self, anchorObj, relationName) :\n\t\t\"Attaches the rabalist to a raba object. Only attached rabalists can  be saved\"\n\t\tif self.anchorObj == None :\n\t\t\tself.relationName = relationName\n\t\t\tself.anchorObj = anchorObj\n\t\t\tself._setNamespaceConAndConf(anchorObj._rabaClass._raba_namespace)\n\t\t\tself.tableName = self.connection.makeRabaListTableName(self.anchorObj._rabaClass.__name__, self.relationName)\n\t\t\tfaultyElmt = self._checkSelf()\n\t\t\tif faultyElmt != None :\n\t\t\t\traise ValueError(\"Element %s violates specified list or relation constraints\" % faultyElmt)\n\t\telif self.anchorObj is not anchorObj :\n\t\t\traise ValueError(\"Ouch: attempt to steal rabalist, use RabaLict.copy() instead.\\nthief: %s\\nvictim: %s\\nlist: %s\" % (anchorObj, self.anchorObj, self))",
    "docstring": "Attaches the rabalist to a raba object. Only attached rabalists can  be saved"
  },
  {
    "code": "def generate_template(self, channeldir, filename, header):\n        file_path = get_metadata_file_path(channeldir, filename)\n        if not os.path.exists(file_path):\n            with open(file_path, 'w') as csv_file:\n                csvwriter = csv.DictWriter(csv_file, header)\n                csvwriter.writeheader()",
    "docstring": "Create empty template .csv file called `filename` as siblings of the\n        directory `channeldir` with header fields specified in `header`."
  },
  {
    "code": "def doArc8(arcs, domains, assignments):\n    check = dict.fromkeys(domains, True)\n    while check:\n        variable, _ = check.popitem()\n        if variable not in arcs or variable in assignments:\n            continue\n        domain = domains[variable]\n        arcsvariable = arcs[variable]\n        for othervariable in arcsvariable:\n            arcconstraints = arcsvariable[othervariable]\n            if othervariable in assignments:\n                otherdomain = [assignments[othervariable]]\n            else:\n                otherdomain = domains[othervariable]\n            if domain:\n                for value in domain[:]:\n                    assignments[variable] = value\n                    if otherdomain:\n                        for othervalue in otherdomain:\n                            assignments[othervariable] = othervalue\n                            for constraint, variables in arcconstraints:\n                                if not constraint(\n                                    variables, domains, assignments, True\n                                ):\n                                    break\n                            else:\n                                break\n                        else:\n                            domain.hideValue(value)\n                        del assignments[othervariable]\n                del assignments[variable]\n            if not domain:\n                return False\n    return True",
    "docstring": "Perform the ARC-8 arc checking algorithm and prune domains\n\n    @attention: Currently unused."
  },
  {
    "code": "def help_text(self, name, text, text_kind='plain', trim_pfx=0):\n        if trim_pfx > 0:\n            text = toolbox.trim_prefix(text, trim_pfx)\n        if text_kind == 'rst':\n            try:\n                overrides = {'input_encoding': 'ascii',\n                             'output_encoding': 'utf-8'}\n                text_html = publish_string(text, writer_name='html',\n                                           settings_overrides=overrides)\n                text = text_html.decode('utf-8')\n                text_kind = 'html'\n            except Exception as e:\n                self.logger.error(\"Error converting help text to HTML: %s\" % (\n                    str(e)))\n        else:\n            raise ValueError(\n                \"I don't know how to display text of kind '%s'\" % (text_kind))\n        if text_kind == 'html':\n            self.help(text=text, text_kind='html')\n        else:\n            self.show_help_text(name, text)",
    "docstring": "Provide help text for the user.\n\n        This method will convert the text as necessary with docutils and\n        display it in the WBrowser plugin, if available.  If the plugin is\n        not available and the text is type 'rst' then the text will be\n        displayed in a plain text widget.\n\n        Parameters\n        ----------\n        name : str\n            Category of help to show.\n\n        text : str\n            The text to show.  Should be plain, HTML or RST text\n\n        text_kind : str (optional)\n            One of 'plain', 'html', 'rst'.  Default is 'plain'.\n\n        trim_pfx : int (optional)\n            Number of spaces to trim off the beginning of each line of text."
  },
  {
    "code": "def _process_image_file(fobj, session, filename):\n  image = _decode_image(fobj, session, filename=filename)\n  return _encode_jpeg(image)",
    "docstring": "Process image files from the dataset."
  },
  {
    "code": "def copy(self, to_name):\n        return self.reddit_session.copy_multireddit(self._author, self.name,\n                                                    to_name)",
    "docstring": "Copy this multireddit.\n\n        Convenience function that utilizes\n        :meth:`.MultiredditMixin.copy_multireddit` populating both\n        the `from_redditor` and `from_name` parameters."
  },
  {
    "code": "def intermediate_cpfs(self) -> List[CPF]:\n        _, cpfs = self.cpfs\n        interm_cpfs = [cpf for cpf in cpfs if cpf.name in self.intermediate_fluents]\n        interm_cpfs = sorted(interm_cpfs, key=lambda cpf: (self.intermediate_fluents[cpf.name].level, cpf.name))\n        return interm_cpfs",
    "docstring": "Returns list of intermediate-fluent CPFs in level order."
  },
  {
    "code": "def create_from_tuple(cls, tube, the_tuple):\n        if the_tuple is None:\n            return\n        if not the_tuple.rowcount:\n            raise Queue.ZeroTupleException(\"Error creating task\")\n        row = the_tuple[0]\n        return cls(\n            tube,\n            task_id=row[0],\n            state=row[1],\n            data=row[2]\n        )",
    "docstring": "Create task from tuple.\n\n        Returns `Task` instance."
  },
  {
    "code": "def augmentation_transform(self, data, label):\n        for aug in self.auglist:\n            data, label = aug(data, label)\n        return (data, label)",
    "docstring": "Override Transforms input data with specified augmentations."
  },
  {
    "code": "def run_command(self, command_name, config_updates=None,\n                    named_configs=(), args=(), meta_info=None):\n        import warnings\n        warnings.warn(\"run_command is deprecated. Use run instead\",\n                      DeprecationWarning)\n        return self.run(command_name, config_updates, named_configs, meta_info,\n                        args)",
    "docstring": "Run the command with the given name.\n\n        .. note:: Deprecated in Sacred 0.7\n            run_command() will be removed in Sacred 1.0.\n            It is replaced by run() which can now also handle command_names."
  },
  {
    "code": "def system_update_column_family(self, cf_def):\n    self._seqid += 1\n    d = self._reqs[self._seqid] = defer.Deferred()\n    self.send_system_update_column_family(cf_def)\n    return d",
    "docstring": "updates properties of a column family. returns the new schema id.\n\n    Parameters:\n     - cf_def"
  },
  {
    "code": "def add_ok_action(self, action_arn=None):\n        if not action_arn:\n            return\n        self.actions_enabled = 'true'\n        self.ok_actions.append(action_arn)",
    "docstring": "Adds an ok action, represented as an SNS topic, to this alarm. What\n        to do when the ok state is reached.\n\n        :type action_arn: str\n        :param action_arn: SNS topics to which notification should be \n                           sent if the alarm goes to state INSUFFICIENT_DATA."
  },
  {
    "code": "def create(cls, obj):\n        self = cls.__new__(cls)\n        self.__proto__ = obj\n        return self",
    "docstring": "Create a new prototype object with the argument as the source\n        prototype.\n\n        .. Note:\n\n            This does not `initialize` the newly created object any\n            more than setting its prototype.\n            Calling the __init__ method is usually unnecessary as all\n            initialization data should be in the original prototype\n            object already.\n\n            If required, call __init__ explicitly:\n\n            >>> proto_obj = MyProtoObj(1, 2, 3)\n            >>> obj = MyProtoObj.create(proto_obj)\n            >>> obj.__init__(1, 2, 3)"
  },
  {
    "code": "def check_all_local(self):\n        all_local_chk = self.event['global']['all_local'].isChecked()\n        for buttons in self.event['local'].values():\n            buttons[0].setChecked(all_local_chk)\n            buttons[1].setEnabled(buttons[0].isChecked())",
    "docstring": "Check or uncheck all local event parameters."
  },
  {
    "code": "def checkversion(doc,\n                 metadata,\n                 enable_dev\n):\n    cdoc = None\n    if isinstance(doc, CommentedSeq):\n        if not isinstance(metadata, CommentedMap):\n            raise Exception(\"Expected metadata to be CommentedMap\")\n        lc = metadata.lc\n        metadata = copy.deepcopy(metadata)\n        metadata.lc.data = copy.copy(lc.data)\n        metadata.lc.filename = lc.filename\n        metadata[u\"$graph\"] = doc\n        cdoc = metadata\n    elif isinstance(doc, CommentedMap):\n        cdoc = doc\n    else:\n        raise Exception(\"Expected CommentedMap or CommentedSeq\")\n    version = metadata[u\"cwlVersion\"]\n    cdoc[\"cwlVersion\"] = version\n    if version not in UPDATES:\n        if version in DEVUPDATES:\n            if enable_dev:\n                pass\n            else:\n                raise validate.ValidationException(\n                    u\"Version '%s' is a development or deprecated version.\\n \"\n                    \"Update your document to a stable version (%s) or use \"\n                    \"--enable-dev to enable support for development and \"\n                    \"deprecated versions.\" % (version, \", \".join(\n                        list(UPDATES.keys()))))\n        else:\n            raise validate.ValidationException(\n                u\"Unrecognized version %s\" % version)\n    return (cdoc, version)",
    "docstring": "Checks the validity of the version of the give CWL document.\n\n    Returns the document and the validated version string."
  },
  {
    "code": "def ensure_clean_git(operation='operation'):\n    if os.system('git diff-index --quiet HEAD --'):\n        print(\"Unstaged or uncommitted changes detected. {} aborted.\".format(\n            operation.capitalize()))\n        sys.exit()",
    "docstring": "Verify that git has no uncommitted changes"
  },
  {
    "code": "def restore(self, request, *args, **kwargs):\n        paths = request.path_info.split('/')\n        object_id_index = paths.index(\"restore\") - 2\n        object_id = paths[object_id_index]\n        obj = super(VersionedAdmin, self).get_object(request, object_id)\n        obj.restore()\n        admin_wordIndex = object_id_index - 3\n        path = \"/%s\" % (\"/\".join(paths[admin_wordIndex:object_id_index]))\n        opts = self.model._meta\n        msg_dict = {\n            'name': force_text(opts.verbose_name),\n            'obj': format_html('<a href=\"{}\">{}</a>',\n                               urlquote(request.path), obj),\n        }\n        msg = format_html(_('The {name} \"{obj}\" was restored successfully.'),\n                          **msg_dict)\n        self.message_user(request, msg, messages.SUCCESS)\n        return HttpResponseRedirect(path)",
    "docstring": "View for restoring object from change view"
  },
  {
    "code": "def clean(self):\n        for f in self.catalog_names:\n            if 'match' in f:\n                if os.path.exists(self.catalog_names[f]):\n                    log.info('Deleting intermediate match file: %s'%\n                                self.catalog_names[f])\n                    os.remove(self.catalog_names[f])\n            else:\n                for extn in f:\n                    if os.path.exists(extn):\n                        log.info('Deleting intermediate catalog: %d'%extn)\n                        os.remove(extn)",
    "docstring": "Remove intermediate files created."
  },
  {
    "code": "def write_generator_data(self, file):\n        writer = self._get_writer(file)\n        writer.writerow([\"bus\"] + GENERATOR_ATTRS)\n        for g in self.case.generators:\n            i = g.bus._i\n            writer.writerow([i] + [getattr(g,a) for a in GENERATOR_ATTRS])",
    "docstring": "Write generator data as CSV."
  },
  {
    "code": "def suspend(rq, ctx, duration):\n    \"Suspends all workers.\"\n    ctx.invoke(\n        rq_cli.suspend,\n        duration=duration,\n        **shared_options(rq)\n    )",
    "docstring": "Suspends all workers."
  },
  {
    "code": "def fromstring(text, schema=None):\n    if schema:\n        parser = objectify.makeparser(schema = schema.schema)\n        return objectify.fromstring(text, parser=parser)\n    else:\n        return objectify.fromstring(text)",
    "docstring": "Parses a KML text string\n    \n    This function parses a KML text string and optionally validates it against \n    a provided schema object"
  },
  {
    "code": "def flatten(nested):\n    flat_return = list()\n    def __inner_flat(nested,flat):\n        for i in nested:\n            __inner_flat(i, flat) if isinstance(i, list) else flat.append(i)\n        return flat\n    __inner_flat(nested,flat_return)\n    return flat_return",
    "docstring": "Return a flatten version of the nested argument"
  },
  {
    "code": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n        if self.loop.is_running():\n            raise RuntimeError(\"Event loop is already running.\")\n        if not self.is_connected:\n            self.loop.run_until_complete(self.connect())\n        task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n        result = self.loop.run_until_complete(task)\n        self.loop.run_until_complete(self.quit())\n        return result",
    "docstring": "Utility method to run commands synchronously for testing."
  },
  {
    "code": "def deserialize(stream_or_string, **options):\n    options.setdefault('Loader', Loader)\n    try:\n        return yaml.load(stream_or_string, **options)\n    except ScannerError as error:\n        log.exception('Error encountered while deserializing')\n        err_type = ERROR_MAP.get(error.problem, 'Unknown yaml render error')\n        line_num = error.problem_mark.line + 1\n        raise DeserializationError(err_type,\n                                   line_num,\n                                   error.problem_mark.buffer)\n    except ConstructorError as error:\n        log.exception('Error encountered while deserializing')\n        raise DeserializationError(error)\n    except Exception as error:\n        log.exception('Error encountered while deserializing')\n        raise DeserializationError(error)",
    "docstring": "Deserialize any string of stream like object into a Python data structure.\n\n    :param stream_or_string: stream or string to deserialize.\n    :param options: options given to lower yaml module."
  },
  {
    "code": "def get_desktop_for_window(self, window):\n        desktop = ctypes.c_long(0)\n        _libxdo.xdo_get_desktop_for_window(\n            self._xdo, window, ctypes.byref(desktop))\n        return desktop.value",
    "docstring": "Get the desktop a window is on.\n        Uses _NET_WM_DESKTOP of the EWMH spec.\n\n        If your desktop does not support ``_NET_WM_DESKTOP``, then '*desktop'\n        remains unmodified.\n\n        :param wid: the window to query"
  },
  {
    "code": "def find_lib_directory(self):\n        lib_directory = None\n        if self.lib_micro_version in self.lib_directories:\n            lib_directory = self.lib_micro_version\n        elif self.lib_minor_version in self.lib_directories:\n            lib_directory = self.lib_minor_version\n        elif self.lib_major_version in self.lib_directories:\n            lib_directory = self.lib_major_version\n        else:\n            for lv in [self.lib_micro_version, self.lib_minor_version, self.lib_major_version]:\n                for d in self.lib_directories:\n                    if lv in d:\n                        lib_directory = d\n                        break\n                else:\n                    continue\n                break\n        return lib_directory",
    "docstring": "Find the optimal lib directory."
  },
  {
    "code": "def acquire(graftm_package_path):\n        contents_hash = json.load(\n                                   open(\n                                        os.path.join(\n                                                     graftm_package_path,\n                                                     GraftMPackage._CONTENTS_FILE_NAME\n                                                     ),\n                                         )\n                                   )\n        v=contents_hash[GraftMPackage.VERSION_KEY]\n        logging.debug(\"Loading version %i GraftM package: %s\" % (v, graftm_package_path))\n        if v == 2:\n            pkg = GraftMPackageVersion2()\n        elif v == 3:\n            pkg = GraftMPackageVersion3()\n        else:\n            raise InsufficientGraftMPackageException(\"Bad version: %s\" % v)\n        pkg._contents_hash = contents_hash\n        pkg._base_directory = graftm_package_path\n        pkg.check_universal_keys(v)\n        pkg.check_required_keys(GraftMPackage._REQUIRED_KEYS[str(v)])\n        return pkg",
    "docstring": "Acquire a new graftm Package\n\n        Parameters\n        ----------\n        graftm_output_path: str\n            path to base directory of graftm"
  },
  {
    "code": "def GetCustomerIDs(client):\n  managed_customer_service = client.GetService('ManagedCustomerService',\n                                               version='v201809')\n  offset = 0\n  selector = {\n      'fields': ['CustomerId'],\n      'predicates': [{\n          'field': 'CanManageClients',\n          'operator': 'EQUALS',\n          'values': [False]\n      }],\n      'paging': {\n          'startIndex': str(offset),\n          'numberResults': str(PAGE_SIZE)\n      }\n  }\n  queue = multiprocessing.Queue()\n  more_pages = True\n  while more_pages:\n    page = managed_customer_service.get(selector)\n    if page and 'entries' in page and page['entries']:\n      for entry in page['entries']:\n        queue.put(entry['customerId'])\n    else:\n      raise Exception('Can\\'t retrieve any customer ID.')\n    offset += PAGE_SIZE\n    selector['paging']['startIndex'] = str(offset)\n    more_pages = offset < int(page['totalNumEntries'])\n  return queue",
    "docstring": "Retrieves all CustomerIds in the account hierarchy.\n\n  Note that your configuration file must specify a client_customer_id belonging\n  to an AdWords manager account.\n\n  Args:\n    client: an AdWordsClient instance.\n  Raises:\n    Exception: if no CustomerIds could be found.\n  Returns:\n    A Queue instance containing all CustomerIds in the account hierarchy."
  },
  {
    "code": "def getargspec(func):\n    if inspect.ismethod(func):\n        func = func.__func__\n    try:\n        code = func.__code__\n    except AttributeError:\n        raise TypeError(\"{!r} is not a Python function\".format(func))\n    if hasattr(code, \"co_kwonlyargcount\") and code.co_kwonlyargcount > 0:\n        raise ValueError(\"keyword-only arguments are not supported by getargspec()\")\n    args, varargs, varkw = inspect.getargs(code)\n    return inspect.ArgSpec(args, varargs, varkw, func.__defaults__)",
    "docstring": "Variation of inspect.getargspec that works for more functions.\n\n    This function works for Cythonized, non-cpdef functions, which expose argspec information but\n    are not accepted by getargspec. It also works for Python 3 functions that use annotations, which\n    are simply ignored. However, keyword-only arguments are not supported."
  },
  {
    "code": "def add_user_to_group(iam_client, user, group, quiet = False):\n    if not quiet:\n        printInfo('Adding user to group %s...' % group)\n    iam_client.add_user_to_group(GroupName = group, UserName = user)",
    "docstring": "Add an IAM user to an IAM group\n\n    :param iam_client:\n    :param group:\n    :param user:\n    :param user_info:\n    :param dry_run:\n    :return:"
  },
  {
    "code": "def _run_mpi_cmd(self, cmd):\n        log(\"Number of Processes: {0}\".format(self.num_processors))\n        time_start = datetime.utcnow()\n        cmd = [self.mpiexec_path, '-n', str(self.num_processors)] + cmd\n        log(\"Command Line: {0}\".format(\" \".join(cmd)))\n        process = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=False)\n        out, err = process.communicate()\n        if out:\n            log(\"OUTPUT:\")\n            for line in out.split(b'\\n'):\n                log(line)\n        if err:\n            log(err, severity=\"WARNING\")\n        log(\"Time to complete: {0}\".format(datetime.utcnow()-time_start))",
    "docstring": "This runs the command you send in"
  },
  {
    "code": "def namedb_get_num_names_in_namespace( cur, namespace_id, current_block ):\n    unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block )\n    query = \"SELECT COUNT(name_records.name) FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id WHERE name_records.namespace_id = ? AND \" + unexpired_query + \" ORDER BY name;\"\n    args = (namespace_id,) + unexpired_args\n    num_rows = namedb_select_count_rows( cur, query, args, count_column='COUNT(name_records.name)' )\n    return num_rows",
    "docstring": "Get the number of names in a given namespace"
  },
  {
    "code": "def search(self, query: 're.Pattern') -> 'Iterable[_WorkTitles]':\n        titles: 'Titles'\n        for titles in self._titles_list:\n            title: 'AnimeTitle'\n            for title in titles.titles:\n                if query.search(title.title):\n                    yield WorkTitles(\n                        aid=titles.aid,\n                        main_title=_get_main_title(titles.titles),\n                        titles=[t.title for t in titles.titles],\n                    )\n                    continue",
    "docstring": "Search titles using a compiled RE query."
  },
  {
    "code": "def match_conditions(self, filepath, sourcedir=None, nopartial=True,\n                         exclude_patterns=[], excluded_libdirs=[]):\n        excluded_libdirs = [os.path.join(d, \"\") for d in excluded_libdirs]\n        filename, ext = os.path.splitext(filepath)\n        ext = ext[1:]\n        if ext not in self.FINDER_STYLESHEET_EXTS:\n            return False\n        if nopartial and self.is_partial(filepath):\n            return False\n        if any(\n            filepath.startswith(excluded_path)\n            for excluded_path in paths_by_depth(excluded_libdirs)\n        ):\n            return False\n        if sourcedir and exclude_patterns:\n            candidates = [sourcedir]+excluded_libdirs\n            relative_path = self.get_relative_from_paths(filepath, candidates)\n            if not self.is_allowed(relative_path, excludes=exclude_patterns):\n                return False\n        return True",
    "docstring": "Find if a filepath match all required conditions.\n\n        Available conditions are (in order):\n\n        * Is allowed file extension;\n        * Is a partial source;\n        * Is from an excluded directory;\n        * Is matching an exclude pattern;\n\n        Args:\n            filepath (str): Absolute filepath to match against conditions.\n\n        Keyword Arguments:\n            sourcedir (str or None): Absolute sources directory path. Can be\n                ``None`` but then the exclude_patterns won't be matched against\n                (because this method require to distinguish source dir from lib\n                dirs).\n            nopartial (bool): Accept partial sources if ``False``. Default is\n                ``True`` (partial sources fail matchind condition). See\n                ``Finder.is_partial()``.\n            exclude_patterns (list): List of glob patterns, if filepath match\n                one these pattern, it wont match conditions. See\n                ``Finder.is_allowed()``.\n            excluded_libdirs (list): A list of directory to match against\n                filepath, if filepath starts with one them, it won't\n                match condtions.\n\n        Returns:\n            bool: ``True`` if match all conditions, else ``False``."
  },
  {
    "code": "def _tseitin(ex, auxvarname, auxvars=None):\n    if isinstance(ex, Literal):\n        return ex, list()\n    else:\n        if auxvars is None:\n            auxvars = list()\n        lits = list()\n        constraints = list()\n        for x in ex.xs:\n            lit, subcons = _tseitin(x, auxvarname, auxvars)\n            lits.append(lit)\n            constraints.extend(subcons)\n        auxvarindex = len(auxvars)\n        auxvar = exprvar(auxvarname, auxvarindex)\n        auxvars.append(auxvar)\n        f = ASTOPS[ex.ASTOP](*lits)\n        constraints.append((auxvar, f))\n        return auxvar, constraints",
    "docstring": "Convert a factored expression to a literal, and a list of constraints."
  },
  {
    "code": "def is_ancestor_of(self, other, include_self=False):\n        return other.is_descendant_of(self, include_self=include_self)",
    "docstring": "Is this node an ancestor of `other`?"
  },
  {
    "code": "def type_from_ast(schema, type_node):\n    if isinstance(type_node, ListTypeNode):\n        inner_type = type_from_ast(schema, type_node.type)\n        return GraphQLList(inner_type) if inner_type else None\n    if isinstance(type_node, NonNullTypeNode):\n        inner_type = type_from_ast(schema, type_node.type)\n        return GraphQLNonNull(inner_type) if inner_type else None\n    if isinstance(type_node, NamedTypeNode):\n        return schema.get_type(type_node.name.value)\n    raise TypeError(\n        f\"Unexpected type node: '{inspect(type_node)}'.\"\n    )",
    "docstring": "Get the GraphQL type definition from an AST node.\n\n    Given a Schema and an AST node describing a type, return a GraphQLType definition\n    which applies to that type. For example, if provided the parsed AST node for\n    `[User]`, a GraphQLList instance will be returned, containing the type called\n    \"User\" found in the schema. If a type called \"User\" is not found in the schema,\n    then None will be returned."
  },
  {
    "code": "def get_available_positions(self):\n        available_positions = [\"new\"]\n        layout = self.context.getLayout()\n        used_positions = [int(slot[\"position\"]) for slot in layout]\n        if used_positions:\n            used = [\n                pos for pos in range(1, max(used_positions) + 1) if\n                pos not in used_positions]\n            available_positions.extend(used)\n        return available_positions",
    "docstring": "Return a list of empty slot numbers"
  },
  {
    "code": "def get_subdirectories(directory):\r\n    return [name for name in os.listdir(directory)\r\n            if name != '__pycache__'\r\n            if os.path.isdir(os.path.join(directory, name))]",
    "docstring": "Get subdirectories without pycache"
  },
  {
    "code": "def get_token(username, length=20, timeout=20):\n    redis = get_redis_client()\n    token = get_random_string(length)\n    token_key = 'token:{}'.format(token)\n    redis.set(token_key, username)\n    redis.expire(token_key, timeout)\n    return token",
    "docstring": "Obtain an access token that can be passed to a websocket client."
  },
  {
    "code": "def generate_sibling_distance(self):\n        sibling_distance = defaultdict(lambda: defaultdict(dict))\n        topics = {p.topic for p in self.partitions}\n        for source in self.brokers:\n            for dest in self.brokers:\n                if source != dest:\n                    for topic in topics:\n                        sibling_distance[dest][source][topic] = \\\n                            dest.count_partitions(topic) - \\\n                            source.count_partitions(topic)\n        return sibling_distance",
    "docstring": "Generate a dict containing the distance computed as difference in\n        in number of partitions of each topic from under_loaded_brokers\n        to over_loaded_brokers.\n\n        Negative distance means that the destination broker has got less\n        partitions of a certain topic than the source broker.\n\n        returns: dict {dest: {source: {topic: distance}}}"
  },
  {
    "code": "def sync_user_email_addresses(user):\n    from .models import EmailAddress\n    email = user_email(user)\n    if email and not EmailAddress.objects.filter(user=user,\n                                                 email__iexact=email).exists():\n        if app_settings.UNIQUE_EMAIL \\\n                and EmailAddress.objects.filter(email__iexact=email).exists():\n            return\n        EmailAddress.objects.create(user=user,\n                                    email=email,\n                                    primary=False,\n                                    verified=False)",
    "docstring": "Keep user.email in sync with user.emailaddress_set.\n\n    Under some circumstances the user.email may not have ended up as\n    an EmailAddress record, e.g. in the case of manually created admin\n    users."
  },
  {
    "code": "def populate_host_templates(host_templates,\n                            hardware_ids=None,\n                            virtual_guest_ids=None,\n                            ip_address_ids=None,\n                            subnet_ids=None):\n    if hardware_ids is not None:\n        for hardware_id in hardware_ids:\n            host_templates.append({\n                'objectType': 'SoftLayer_Hardware',\n                'id': hardware_id\n            })\n    if virtual_guest_ids is not None:\n        for virtual_guest_id in virtual_guest_ids:\n            host_templates.append({\n                'objectType': 'SoftLayer_Virtual_Guest',\n                'id': virtual_guest_id\n            })\n    if ip_address_ids is not None:\n        for ip_address_id in ip_address_ids:\n            host_templates.append({\n                'objectType': 'SoftLayer_Network_Subnet_IpAddress',\n                'id': ip_address_id\n            })\n    if subnet_ids is not None:\n        for subnet_id in subnet_ids:\n            host_templates.append({\n                'objectType': 'SoftLayer_Network_Subnet',\n                'id': subnet_id\n            })",
    "docstring": "Populate the given host_templates array with the IDs provided\n\n    :param host_templates: The array to which host templates will be added\n    :param hardware_ids: A List of SoftLayer_Hardware ids\n    :param virtual_guest_ids: A List of SoftLayer_Virtual_Guest ids\n    :param ip_address_ids: A List of SoftLayer_Network_Subnet_IpAddress ids\n    :param subnet_ids: A List of SoftLayer_Network_Subnet ids"
  },
  {
    "code": "def send(tag, data=None):\n    data = data or {}\n    event = salt.utils.event.get_master_event(__opts__, __opts__['sock_dir'],\n                                              listen=False)\n    return event.fire_event(data, tag)",
    "docstring": "Send an event with the given tag and data.\n\n    This is useful for sending events directly to the master from the shell\n    with salt-run. It is also quite useful for sending events in orchestration\n    states where the ``fire_event`` requisite isn't sufficient because it does\n    not support sending custom data with the event.\n\n    Note that event tags will *not* be namespaced like events sent with the\n    ``fire_event`` requisite! Whereas events produced from ``fire_event`` are\n    prefixed with ``salt/state_result/<jid>/<minion_id>/<name>``, events sent\n    using this runner module will have no such prefix. Make sure your reactors\n    don't expect a prefix!\n\n    :param tag: the tag to send with the event\n    :param data: an optional dictionary of data to send with the event\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-run event.send my/custom/event '{\"foo\": \"bar\"}'\n\n    Orchestration Example:\n\n    .. code-block:: yaml\n\n        # orch/command.sls\n\n        run_a_command:\n          salt.function:\n            - name: cmd.run\n            - tgt: my_minion\n            - arg:\n              - exit {{ pillar['exit_code'] }}\n\n        send_success_event:\n          salt.runner:\n            - name: event.send\n            - tag: my_event/success\n            - data:\n                foo: bar\n            - require:\n              - salt: run_a_command\n\n        send_failure_event:\n          salt.runner:\n            - name: event.send\n            - tag: my_event/failure\n            - data:\n                baz: qux\n            - onfail:\n              - salt: run_a_command\n\n    .. code-block:: bash\n\n        salt-run state.orchestrate orch.command pillar='{\"exit_code\": 0}'\n        salt-run state.orchestrate orch.command pillar='{\"exit_code\": 1}'"
  },
  {
    "code": "def _handle_userCount(self, data):\n        self.room.user_count = data\n        self.conn.enqueue_data(\"user_count\", self.room.user_count)",
    "docstring": "Handle user count changes"
  },
  {
    "code": "def empty( self, node ):\n        overall = self.overall( node )\n        if overall:\n            return (overall - self.children_sum( self.children(node), node))/float(overall)\n        return 0",
    "docstring": "Calculate empty space as a fraction of total space"
  },
  {
    "code": "def QueueResponse(self, response, timestamp=None):\n    if timestamp is None:\n      timestamp = self.frozen_timestamp\n    self.response_queue.append((response, timestamp))",
    "docstring": "Queues the message on the flow's state."
  },
  {
    "code": "def clean():\n    for queue in MyQueue.collection().instances():\n        queue.delete()\n    for job in MyJob.collection().instances():\n        job.delete()\n    for person in Person.collection().instances():\n        person.delete()",
    "docstring": "Clean data created by this script"
  },
  {
    "code": "def split(self, tValues):\n        if self.segmentType == \"curve\":\n            on1 = self.previousOnCurve\n            off1 = self.points[0].coordinates\n            off2 = self.points[1].coordinates\n            on2 = self.points[2].coordinates\n            return bezierTools.splitCubicAtT(on1, off1, off2, on2, *tValues)\n        elif self.segmentType == \"line\":\n            segments = []\n            x1, y1 = self.previousOnCurve\n            x2, y2 = self.points[0].coordinates\n            dx = x2 - x1\n            dy = y2 - y1\n            pp = x1, y1\n            for t in tValues:\n                np = (x1+dx*t, y1+dy*t)\n                segments.append([pp, np])\n                pp = np\n            segments.append([pp, (x2, y2)])\n            return segments\n        elif self.segmentType == \"qcurve\":\n            raise NotImplementedError\n        else:\n            raise NotImplementedError",
    "docstring": "Split the segment according the t values"
  },
  {
    "code": "def from_credentials(credentials, loop: asyncio.AbstractEventLoop=asyncio.get_event_loop()):\n        return API(username=credentials.username, password=credentials.password,\n                   database=credentials.database, session_id=credentials.session_id,\n                   server=credentials.server, loop=loop)",
    "docstring": "Returns a new async API object from an existing Credentials object.\n\n        :param credentials: The existing saved credentials.\n        :param loop: The asyncio loop.\n        :return: A new API object populated with MyGeotab credentials."
  },
  {
    "code": "def is_absolute_path (path):\n    if os.name == 'nt':\n        if re.search(r\"^[a-zA-Z]:\", path):\n            return True\n        path = path.replace(\"\\\\\", \"/\")\n    return path.startswith(\"/\")",
    "docstring": "Check if given path is absolute. On Windows absolute paths start\n    with a drive letter. On all other systems absolute paths start with\n    a slash."
  },
  {
    "code": "def has_nvme_ssd(self):\n        for member in self._drives_list():\n            if (member.media_type == constants.MEDIA_TYPE_SSD and\n                    member.protocol == constants.PROTOCOL_NVMe):\n                return True\n        return False",
    "docstring": "Return True if the drive is SSD and protocol is NVMe"
  },
  {
    "code": "def remove(self, class_name, name):\n        if class_name not in self.components:\n            logger.error(\"Component class {} not found\".format(class_name))\n            return None\n        cls_df = self.df(class_name)\n        cls_df.drop(name, inplace=True)\n        pnl = self.pnl(class_name)\n        for df in itervalues(pnl):\n            if name in df:\n                df.drop(name, axis=1, inplace=True)",
    "docstring": "Removes a single component from the network.\n\n        Removes it from component DataFrames.\n\n        Parameters\n        ----------\n        class_name : string\n            Component class name\n        name : string\n            Component name\n\n        Examples\n        --------\n        >>> network.remove(\"Line\",\"my_line 12345\")"
  },
  {
    "code": "def delete_jdbc_connection_pool(name, target='server', cascade=False, server=None):\n    data = {'target': target, 'cascade': cascade}\n    return _delete_element(name, 'resources/jdbc-connection-pool', data, server)",
    "docstring": "Delete a JDBC pool"
  },
  {
    "code": "def replaceWith(self, el):\n        self.childs = el.childs\n        self.params = el.params\n        self.endtag = el.endtag\n        self.openertag = el.openertag\n        self._tagname = el.getTagName()\n        self._element = el.tagToString()\n        self._istag = el.isTag()\n        self._isendtag = el.isEndTag()\n        self._iscomment = el.isComment()\n        self._isnonpairtag = el.isNonPairTag()",
    "docstring": "Replace value in this element with values from `el`.\n\n        This useful when you don't want change all references to object.\n\n        Args:\n            el (obj): :class:`HTMLElement` instance."
  },
  {
    "code": "def find(self, path):\n        path = path.split('.')\n        node = self\n        while node._parent:\n            node = node._parent\n        for name in path:\n            node = node._tree.get(name, None)\n            if node is None or type(node) is float:\n                return None\n        return node",
    "docstring": "Return the node for a path, or None."
  },
  {
    "code": "def split_scoped_hparams(scopes, merged_hparams):\n  split_values = {scope: {} for scope in scopes}\n  merged_values = merged_hparams.values()\n  for scoped_key, value in six.iteritems(merged_values):\n    scope = scoped_key.split(\".\")[0]\n    key = scoped_key[len(scope) + 1:]\n    split_values[scope][key] = value\n  return [\n      hparam.HParams(**split_values[scope]) for scope in scopes\n  ]",
    "docstring": "Split single HParams with scoped keys into multiple."
  },
  {
    "code": "def copy(self):\n        return Retry(max_tries=self.max_tries, delay=self.delay, backoff=self.backoff,\n                     max_jitter=self.max_jitter / 100.0, max_delay=self.max_delay, sleep_func=self.sleep_func,\n                     deadline=self.deadline, retry_exceptions=self.retry_exceptions)",
    "docstring": "Return a clone of this retry manager"
  },
  {
    "code": "def get_function_source(ft, **kwargs)->str:\n    \"Returns link to `ft` in source code.\"\n    try: line = inspect.getsourcelines(ft)[1]\n    except Exception: return ''\n    mod_path = get_module_name(ft).replace('.', '/') + '.py'\n    return get_source_link(mod_path, line, **kwargs)",
    "docstring": "Returns link to `ft` in source code."
  },
  {
    "code": "def export_as_json(self):\n        return {\n            \"items\": {\n                str(jid): item.export_as_json()\n                for jid, item in self.items.items()\n            },\n            \"ver\": self.version\n        }",
    "docstring": "Export the whole roster as currently stored on the client side into a\n        JSON-compatible dictionary and return that dictionary."
  },
  {
    "code": "def avail_images(call=None):\n    if call == 'action':\n        raise SaltCloudException(\n            'The avail_images function must be called with -f or --function.'\n        )\n    response = _query('avail', 'distributions')\n    ret = {}\n    for item in response['DATA']:\n        name = item['LABEL']\n        ret[name] = item\n    return ret",
    "docstring": "Return available Linode images.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud --list-images my-linode-config\n        salt-cloud -f avail_images my-linode-config"
  },
  {
    "code": "def apply(self, styler):\n        return styler.format(self.formatter, *self.args, **self.kwargs)",
    "docstring": "Apply Summary over Pandas Styler"
  },
  {
    "code": "def main(argv=None):\n    arguments = cli_common(__doc__, argv=argv)\n    campaign_file = arguments['CAMPAIGN_FILE']\n    if arguments['-g']:\n        if osp.exists(campaign_file):\n            raise Exception('Campaign file already exists')\n        with open(campaign_file, 'w') as ostr:\n            Generator().write(ostr)\n    else:\n        node = arguments.get('-n')\n        output_dir = arguments.get('--output-dir')\n        exclude_nodes = arguments.get('--exclude-nodes')\n        srun_tag = arguments.get('--srun')\n        driver = CampaignDriver(\n            campaign_file,\n            node=node,\n            output_dir=output_dir,\n            srun=srun_tag,\n            exclude_nodes=exclude_nodes,\n        )\n        driver()\n        if argv is not None:\n            return driver\n        campaign_fd = int(arguments.get('--campaign-path-fd') or 1)\n        message = (osp.abspath(driver.campaign_path) + '\\n').encode()\n        os.write(campaign_fd, message)",
    "docstring": "ben-sh entry point"
  },
  {
    "code": "def main():\n    parser = create_parser()\n    options = vars(parser.parse_args())\n    HASH_STORE.IGNORE_CACHE_FILE = options[constants.LABEL_FORCE]\n    moban_file = options[constants.LABEL_MOBANFILE]\n    load_engine_factory_and_engines()\n    if moban_file is None:\n        moban_file = mobanfile.find_default_moban_file()\n    if moban_file:\n        try:\n            count = handle_moban_file(moban_file, options)\n            moban_exit(options[constants.LABEL_EXIT_CODE], count)\n        except (\n            exceptions.DirectoryNotFound,\n            exceptions.NoThirdPartyEngine,\n            exceptions.MobanfileGrammarException,\n        ) as e:\n            reporter.report_error_message(str(e))\n            moban_exit(options[constants.LABEL_EXIT_CODE], constants.ERROR)\n    else:\n        try:\n            count = handle_command_line(options)\n            moban_exit(options[constants.LABEL_EXIT_CODE], count)\n        except exceptions.NoTemplate as e:\n            reporter.report_error_message(str(e))\n            moban_exit(options[constants.LABEL_EXIT_CODE], constants.ERROR)",
    "docstring": "program entry point"
  },
  {
    "code": "def merge_noun_chunks(doc):\n    if not doc.is_parsed:\n        return doc\n    with doc.retokenize() as retokenizer:\n        for np in doc.noun_chunks:\n            attrs = {\"tag\": np.root.tag, \"dep\": np.root.dep}\n            retokenizer.merge(np, attrs=attrs)\n    return doc",
    "docstring": "Merge noun chunks into a single token.\n\n    doc (Doc): The Doc object.\n    RETURNS (Doc): The Doc object with merged noun chunks.\n\n    DOCS: https://spacy.io/api/pipeline-functions#merge_noun_chunks"
  },
  {
    "code": "def _get_supercell_size(self, s1, s2):\n        if self._supercell_size == 'num_sites':\n            fu = s2.num_sites / s1.num_sites\n        elif self._supercell_size == 'num_atoms':\n            fu = s2.composition.num_atoms / s1.composition.num_atoms\n        elif self._supercell_size == 'volume':\n            fu = s2.volume / s1.volume\n        else:\n            try:\n                el = get_el_sp(self._supercell_size)\n                fu = s2.composition[el] / s1.composition[el]\n            except:\n                raise ValueError('Invalid argument for supercell_size.')\n        if fu < 2/3:\n            return int(round(1/fu)), False\n        else:\n            return int(round(fu)), True",
    "docstring": "Returns the supercell size, and whether the supercell should\n        be applied to s1. If fu == 1, s1_supercell is returned as\n        true, to avoid ambiguity."
  },
  {
    "code": "def __need_ssl(self, host_and_port=None):\n        if not host_and_port:\n            host_and_port = self.current_host_and_port\n        return host_and_port in self.__ssl_params",
    "docstring": "Whether current host needs SSL or not.\n\n        :param (str,int) host_and_port: the host/port pair to check, default current_host_and_port"
  },
  {
    "code": "def copy(self):\n        new_client = self._client.copy()\n        return self.__class__(\n            self.instance_id,\n            new_client,\n            self.configuration_name,\n            node_count=self.node_count,\n            display_name=self.display_name,\n        )",
    "docstring": "Make a copy of this instance.\n\n        Copies the local data stored as simple types and copies the client\n        attached to this instance.\n\n        :rtype: :class:`~google.cloud.spanner_v1.instance.Instance`\n        :returns: A copy of the current instance."
  },
  {
    "code": "def logout(self):\n        if not self.logged_in:\n            raise RuntimeError(\"User is not logged in\")\n        if self.conn.connected:\n            params = {\"room\": self.conn.room.room_id}\n            resp = self.conn.make_api_call(\"logout\", params)\n            if not resp.get(\"success\", False):\n                raise RuntimeError(\n                    f\"Logout unsuccessful: \"\n                    f\"{resp['error'].get('message') or resp['error']}\"\n                )\n            self.conn.make_call(\"logout\", params)\n            self.conn.cookies.pop(\"session\")\n        self.logged_in = False",
    "docstring": "Logs your user out"
  },
  {
    "code": "def acquire_write(self):\n        self.monitor.acquire()\n        while self.rwlock != 0:\n            self.writers_waiting += 1\n            self.writers_ok.wait()\n            self.writers_waiting -= 1\n        self.rwlock = -1\n        self.monitor.release()",
    "docstring": "Acquire a write lock. Only one thread can hold this lock, and\n        only when no read locks are also held."
  },
  {
    "code": "def AddAdGroup(self, client_customer_id, campaign_id, name, status):\n    self.client.SetClientCustomerId(client_customer_id)\n    ad_group_service = self.client.GetService('AdGroupService')\n    operations = [{\n        'operator': 'ADD',\n        'operand': {\n            'campaignId': campaign_id,\n            'name': name,\n            'status': status\n        }\n    }]\n    ad_group_service.mutate(operations)",
    "docstring": "Create a new ad group.\n\n    Args:\n      client_customer_id: str Client Customer Id used to create the AdGroup.\n      campaign_id: str Id of the campaign to use.\n      name: str Name to assign to the AdGroup.\n      status: str Status to assign to the AdGroup when it is created."
  },
  {
    "code": "def set_install_id(filename, install_id):\n    if get_install_id(filename) is None:\n        raise InstallNameError('{0} has no install id'.format(filename))\n    back_tick(['install_name_tool', '-id', install_id, filename])",
    "docstring": "Set install id for library named in `filename`\n\n    Parameters\n    ----------\n    filename : str\n        filename of library\n    install_id : str\n        install id for library `filename`\n\n    Raises\n    ------\n    RuntimeError if `filename` has not install id"
  },
  {
    "code": "def show_service_profile(self, flavor_profile, **_params):\n        return self.get(self.service_profile_path % (flavor_profile),\n                        params=_params)",
    "docstring": "Fetches information for a certain Neutron service flavor profile."
  },
  {
    "code": "def make_logger(scraper):\n    logger = logging.getLogger('')\n    logger.setLevel(logging.DEBUG)\n    requests_log = logging.getLogger(\"requests\")\n    requests_log.setLevel(logging.WARNING)\n    json_handler = logging.FileHandler(log_path(scraper))\n    json_handler.setLevel(logging.DEBUG)\n    json_formatter = jsonlogger.JsonFormatter(make_json_format())\n    json_handler.setFormatter(json_formatter)\n    logger.addHandler(json_handler)\n    console_handler = logging.StreamHandler()\n    console_handler.setLevel(logging.INFO)\n    fmt = '%(name)s [%(levelname)-8s]: %(message)s'\n    formatter = logging.Formatter(fmt)\n    console_handler.setFormatter(formatter)\n    logger.addHandler(console_handler)\n    logger = logging.getLogger(scraper.name)\n    logger = TaskAdapter(logger, scraper)\n    return logger",
    "docstring": "Create two log handlers, one to output info-level ouput to the\n    console, the other to store all logging in a JSON file which will\n    later be used to generate reports."
  },
  {
    "code": "def send_mail_worker(config, mail, event):\n    log = \"\"\n    try:\n        if config.mail_ssl:\n            server = SMTP_SSL(config.mail_server, port=config.mail_server_port, timeout=30)\n        else:\n            server = SMTP(config.mail_server, port=config.mail_server_port, timeout=30)\n        if config.mail_tls:\n            log += 'Starting TLS\\n'\n            server.starttls()\n        if config.mail_username != '':\n            log += 'Logging in with ' + str(config.mail_username) + \"\\n\"\n            server.login(config.mail_username, config.mail_password)\n        else:\n            log += 'No username, trying anonymous access\\n'\n        log += 'Sending Mail\\n'\n        response_send = server.send_message(mail)\n        server.quit()\n    except timeout as e:\n        log += 'Could not send email to enrollee, mailserver timeout: ' + str(e) + \"\\n\"\n        return False, log, event\n    log += 'Server response:' + str(response_send)\n    return True, log, event",
    "docstring": "Worker task to send out an email, which blocks the process unless it is threaded"
  },
  {
    "code": "def set_visible_func(self, visible_func):\n        self.model_filter.set_visible_func(\n                self._internal_visible_func,\n                visible_func,\n                )\n        self._visible_func = visible_func\n        self.model_filter.refilter()",
    "docstring": "Set the function to decide visibility of an item\n\n        :param visible_func: A callable that returns a boolean result to\n                             decide if an item should be visible, for\n                             example::\n\n                                def is_visible(item):\n                                    return True"
  },
  {
    "code": "def touch():\n    from .models import Bucket\n    bucket = Bucket.create()\n    db.session.commit()\n    click.secho(str(bucket), fg='green')",
    "docstring": "Create new bucket."
  },
  {
    "code": "def on_sighup(self, signal_unused, frame_unused):\n        for setting in self.http_config:\n            if getattr(self.http_server, setting) != self.http_config[setting]:\n                LOGGER.debug('Changing HTTPServer %s setting', setting)\n                setattr(self.http_server, setting, self.http_config[setting])\n        for setting in self.settings:\n            if self.app.settings[setting] != self.settings[setting]:\n                LOGGER.debug('Changing Application %s setting', setting)\n                self.app.settings[setting] = self.settings[setting]\n        self.app.handlers = []\n        self.app.named_handlers = {}\n        routes = self.namespace.config.get(config.ROUTES)\n        self.app.add_handlers(\".*$\", self.app.prepare_routes(routes))\n        LOGGER.info('Configuration reloaded')",
    "docstring": "Reload the configuration\n\n        :param int signal_unused: Unused signal number\n        :param frame frame_unused: Unused frame the signal was caught in"
  },
  {
    "code": "def setValues(self, values):\n        ncols = self.getNumCols()\n        nindices = self.getNumIndices()\n        for key, value in values.items():\n            key = Utils.convToList(key)\n            assert len(key) == nindices\n            value = Utils.convToList(value)\n            assert len(value) == ncols-nindices\n            self.addRow(key + value)",
    "docstring": "Set the values of a DataFrame from a dictionary.\n\n        Args:\n            values: Dictionary with the values to set."
  },
  {
    "code": "def compare_version(self, version_string, op):\n        from pkg_resources import parse_version\n        from monty.operator import operator_from_str\n        op = operator_from_str(op)\n        return op(parse_version(self.version), parse_version(version_string))",
    "docstring": "Compare Abinit version to `version_string` with operator `op`"
  },
  {
    "code": "def get_view(self, view_name):\n        return self.measure_to_view_map.get_view(view_name=view_name,\n                                                 timestamp=self.time)",
    "docstring": "gets the view given the view name"
  },
  {
    "code": "def obj_update_or_create(model, defaults=None, update_fields=UNSET, **kwargs):\n    obj, created = model.objects.get_or_create(defaults=defaults, **kwargs)\n    if created:\n        logger.debug('CREATED %s %s',\n                     model._meta.object_name,\n                     obj.pk,\n                     extra={'pk': obj.pk})\n    else:\n        obj_update(obj, defaults, update_fields=update_fields)\n    return obj, created",
    "docstring": "Mimic queryset.update_or_create but using obj_update."
  },
  {
    "code": "def get_rna(self) -> Rna:\n        if self.variants:\n            raise InferCentralDogmaException('can not get rna for variant')\n        return Rna(\n            namespace=self.namespace,\n            name=self.name,\n            identifier=self.identifier\n        )",
    "docstring": "Get the corresponding RNA or raise an exception if it's not the reference node.\n\n        :raises: InferCentralDogmaException"
  },
  {
    "code": "def write(self, outfname=None):\n        outfname = outfname or self.filename\n        with codecs.open(outfname, 'wb', 'windows-1252') as outf:\n            for survey in self.surveys:\n                outf.write('\\r\\n'.join(survey._serialize()))\n                outf.write('\\r\\n'+'\\f'+'\\r\\n')\n            outf.write('\\x1A')",
    "docstring": "Write or overwrite a `Survey` to the specified .DAT file"
  },
  {
    "code": "def _gather_field_values(\n\titem, *, fields=None, field_map=FIELD_MAP,\n\tnormalize_values=False, normalize_func=normalize_value):\n\tit = get_item_tags(item)\n\tif fields is None:\n\t\tfields = list(it.keys())\n\tnormalize = normalize_func if normalize_values else lambda x: str(x)\n\tfield_values = []\n\tfor field in fields:\n\t\tfield_values.append(\n\t\t\tnormalize(\n\t\t\t\tlist_to_single_value(\n\t\t\t\t\tget_field(it, field, field_map=field_map)\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\treturn tuple(field_values)",
    "docstring": "Create a tuple of normalized metadata field values.\n\n\tParameter:\n\t\titem (~collections.abc.Mapping, str, os.PathLike): Item dict or filepath.\n\t\tfields (list): A list of fields used to compare item dicts.\n\t\tfield_map (~collections.abc.Mapping): A mapping field name aliases.\n\t\t\tDefault: :data:`~google_music_utils.constants.FIELD_MAP`\n\t\tnormalize_values (bool): Normalize metadata values to remove common differences between sources.\n\t\t\tDefault: ``False``\n\t\tnormalize_func (function): Function to apply to metadata values if\n\t\t\t``normalize_values`` is ``True``.\n\t\t\tDefault: :func:`~google_music_utils.utils.normalize_value`\n\n\tReturns:\n\t\ttuple: Values from the given metadata fields."
  },
  {
    "code": "def attachment_state(self):\n        state = None\n        if self.attach_data:\n            state = self.attach_data.status\n        return state",
    "docstring": "Get the attachment state."
  },
  {
    "code": "def load_files(self, path):\n        if self.verbose == 2:\n            print(\"Indexing {}\".format(path))\n        for filename in os.listdir(path):\n            file_path = path + \"/\" + filename\n            if os.path.isdir(file_path):\n                self.load_files(file_path)\n            elif filename.endswith(\".yaml\") or filename.endswith(\".yml\"):\n                self.unfold_yaml(file_path)",
    "docstring": "Loads files in a given path and all its subdirectories"
  },
  {
    "code": "def read_version():\n    regex = re.compile('^(?P<number>\\d.*?) .*$')\n    with open('../CHANGELOG.rst') as f:\n        for line in f:\n            match = regex.match(line)\n            if match:\n                return match.group('number')",
    "docstring": "Read version from the first line starting with digit"
  },
  {
    "code": "def get_value(self, tag=None, field=None):\n        assert not (tag is not None and field is not None), \\\n            \"Cannot filter by tag and field simultaneously.\"\n        selected_fields = self._select_by_field_or_tag(tag, field)\n        missing_fields_idents = set(selected_fields) - set(self.field_values)\n        if missing_fields_idents:\n            raise ValueError(\n                \"Cannot generate value with undefined fields {}.\".format(\n                    \", \".join(\"'{}'\".format(f)\n                              for f in missing_fields_idents)))\n        value = 0\n        for identifier, field in iteritems(selected_fields):\n            if field.length is None or field.start_at is None:\n                raise ValueError(\n                    \"Field '{}' does not have a fixed size/position.\".format(\n                        identifier))\n            value |= (self.field_values[identifier] <<\n                      field.start_at)\n        return value",
    "docstring": "Generate an integer whose bits are set according to the values of\n        fields in this bit field. All other bits are set to zero.\n\n        Parameters\n        ----------\n        tag : str\n            Optionally specifies that the value should only include fields with\n            the specified tag.\n        field : str\n            Optionally specifies that the value should only include the\n            specified field.\n\n        Raises\n        ------\n        ValueError\n            If a field's value, length or position has not been defined. (e.g.\n            :py:meth:`.assign_fields` has not been called).\n        UnknownTagError\n            If the tag specified using the `tag` argument does not exist.\n        UnavailableFieldError\n            If the field specified using the `field` argument does not exist or\n            is not available."
  },
  {
    "code": "def get_contents_to_filename(self, filename, headers=None,\n                                 cb=None, num_cb=10,\n                                 torrent=False,\n                                 version_id=None,\n                                 res_download_handler=None,\n                                 response_headers=None, callback=None):\n        fp = open(filename, 'wb')\n        def got_contents_to_filename(response):\n            fp.close()\n            if self.last_modified != None:\n                try:\n                    modified_tuple = rfc822.parsedate_tz(self.last_modified)\n                    modified_stamp = int(rfc822.mktime_tz(modified_tuple))\n                    os.utime(fp.name, (modified_stamp, modified_stamp))\n                except Exception: pass\n            if callable(callback):\n                callback(response)\n        self.get_contents_to_file(fp, headers, cb, num_cb, torrent=torrent,\n                                  version_id=version_id,\n                                  res_download_handler=res_download_handler,\n                                  response_headers=response_headers, callback=got_contents_to_filename)",
    "docstring": "Retrieve an object from S3 using the name of the Key object as the\n        key in S3.  Store contents of the object to a file named by 'filename'.\n        See get_contents_to_file method for details about the\n        parameters.\n\n        :type filename: string\n        :param filename: The filename of where to put the file contents\n\n        :type headers: dict\n        :param headers: Any additional headers to send in the request\n\n        :type cb: function\n        :param cb: a callback function that will be called to report\n                   progress on the upload.  The callback should accept\n                   two integer parameters, the first representing the\n                   number of bytes that have been successfully\n                   transmitted to S3 and the second representing the\n                   size of the to be transmitted object.\n\n        :type cb: int\n        :param num_cb: (optional) If a callback is specified with\n                       the cb parameter this parameter determines the\n                       granularity of the callback by defining\n                       the maximum number of times the callback will\n                       be called during the file transfer.\n\n        :type torrent: bool\n        :param torrent: If True, returns the contents of a torrent file\n                        as a string.\n\n        :type res_upload_handler: ResumableDownloadHandler\n        :param res_download_handler: If provided, this handler will\n                                     perform the download.\n\n        :type response_headers: dict\n        :param response_headers: A dictionary containing HTTP headers/values\n                                 that will override any headers associated with\n                                 the stored object in the response.\n                                 See http://goo.gl/EWOPb for details."
  },
  {
    "code": "def datetime_to_timestamp(dt):\n    epoch = datetime.utcfromtimestamp(0).replace(tzinfo=UTC)\n    return (dt - epoch).total_seconds()",
    "docstring": "Convert timezone-aware `datetime` to POSIX timestamp and\n    return seconds since UNIX epoch.\n\n    Note: similar to `datetime.timestamp()` in Python 3.3+."
  },
  {
    "code": "def check_calling_sequence(name, function_name, function, possible_variables):\n        try:\n            calling_sequence = inspect.getargspec(function.input_object).args\n        except AttributeError:\n            calling_sequence = inspect.getargspec(function).args\n        assert calling_sequence[0] == 'self', \"Wrong syntax for 'evaluate' in %s. The first argument \" \\\n                                              \"should be called 'self'.\" % name\n        variables = filter(lambda var: var in possible_variables, calling_sequence)\n        assert len(variables) > 0, \"The name of the variables for 'evaluate' in %s must be one or more \" \\\n                                   \"among %s, instead of %s\" % (name, ','.join(possible_variables), \",\".join(variables))\n        if variables != possible_variables[:len(variables)]:\n            raise AssertionError(\"The variables %s are out of order in '%s' of %s. Should be %s.\"\n                                 % (\",\".join(variables), function_name, name, possible_variables[:len(variables)]))\n        other_parameters = filter(lambda var: var not in variables and var != 'self', calling_sequence)\n        return variables, other_parameters",
    "docstring": "Check the calling sequence for the function looking for the variables specified.\n        One or more of the variables can be in the calling sequence. Note that the\n        order of the variables will be enforced.\n        It will also enforce that the first parameter in the calling sequence is called 'self'.\n\n        :param function: the function to check\n        :param possible_variables: a list of variables to check, The order is important, and will be enforced\n        :return: a tuple containing the list of found variables, and the name of the other parameters in the calling\n        sequence"
  },
  {
    "code": "def fill_zero(\n    x=None,\n    y=None,\n    label=None,\n    color=None,\n    width=None,\n    dash=None,\n    opacity=None,\n    mode='lines+markers',\n    **kargs\n):\n    return line(\n        x=x,\n        y=y,\n        label=label,\n        color=color,\n        width=width,\n        dash=dash,\n        opacity=opacity,\n        mode=mode,\n        fill='tozeroy',\n        **kargs\n    )",
    "docstring": "Fill to zero.\n\n    Parameters\n    ----------\n    x : array-like, optional\n    y : TODO, optional\n    label : TODO, optional\n\n    Returns\n    -------\n    Chart"
  },
  {
    "code": "def wrap(stream, unicode=False, window=1024, echo=False, close_stream=True):\n    if hasattr(stream, 'read'):\n        proxy = PollingStreamAdapter(stream)\n    elif hasattr(stream, 'recv'):\n        proxy = PollingSocketStreamAdapter(stream)\n    else:\n        raise TypeError('stream must have either read or recv method')\n    if echo and unicode:\n        callback = _echo_text\n    elif echo and not unicode:\n        callback = _echo_bytes\n    else:\n        callback = None\n    if unicode:\n        expecter = TextExpecter(proxy, input_callback=callback, window=window,\n                                close_adapter=close_stream)\n    else:\n        expecter = BytesExpecter(proxy, input_callback=callback, window=window,\n                                 close_adapter=close_stream)\n    return expecter",
    "docstring": "Wrap a stream to implement expect functionality.\n\n    This function provides a convenient way to wrap any Python stream (a\n    file-like object) or socket with an appropriate :class:`Expecter` class for\n    the stream type. The returned object adds an :func:`Expect.expect` method\n    to the stream, while passing normal stream functions like *read*/*recv*\n    and *write*/*send* through to the underlying stream.\n\n    Here's an example of opening and wrapping a pair of network sockets::\n\n        import socket\n        import streamexpect\n\n        source, drain = socket.socketpair()\n        expecter = streamexpect.wrap(drain)\n        source.sendall(b'this is a test')\n        match = expecter.expect_bytes(b'test', timeout=5)\n\n        assert match is not None\n\n    :param stream: The stream/socket to wrap.\n    :param bool unicode: If ``True``, the wrapper will be configured for\n        Unicode matching, otherwise matching will be done on binary.\n    :param int window: Historical characters to buffer.\n    :param bool echo: If ``True``, echoes received characters to stdout.\n    :param bool close_stream: If ``True``, and the wrapper is used as a context\n        manager, closes the stream at the end of the context manager."
  },
  {
    "code": "def can_edit(self, user):\n        return self.class_.can_edit(user) and self.status != u'locked'",
    "docstring": "Return whether or not `user` can make changes to the project."
  },
  {
    "code": "def compress_monkey_patch():\n    from compressor.templatetags import compress as compress_tags\n    from compressor import base as compress_base\n    compress_base.Compressor.filter_input = filter_input\n    compress_base.Compressor.output = output\n    compress_base.Compressor.hunks = hunks\n    compress_base.Compressor.precompile = precompile\n    compress_tags.CompressorMixin.render_compressed = render_compressed\n    from django_pyscss import compressor as pyscss_compressor\n    pyscss_compressor.DjangoScssFilter.input = input",
    "docstring": "patch all compress\n\n    we need access to variables from widget scss\n\n    for example we have::\n\n        /themes/bootswatch/cyborg/_variables\n\n    but only if is cyborg active for this reasone we need\n    dynamically append import to every scss file"
  },
  {
    "code": "def xraw_command(self, netfn, command, bridge_request=(), data=(),\n                     delay_xmit=None, retry=True, timeout=None):\n        rsp = self.ipmi_session.raw_command(netfn=netfn, command=command,\n                                            bridge_request=bridge_request,\n                                            data=data, delay_xmit=delay_xmit,\n                                            retry=retry, timeout=timeout)\n        if 'error' in rsp:\n            raise exc.IpmiException(rsp['error'], rsp['code'])\n        rsp['data'] = buffer(rsp['data'])\n        return rsp",
    "docstring": "Send raw ipmi command to BMC, raising exception on error\n\n        This is identical to raw_command, except it raises exceptions\n        on IPMI errors and returns data as a buffer.  This is the recommend\n        function to use.  The response['data'] being a buffer allows\n        traditional indexed access as well as works nicely with\n        struct.unpack_from when certain data is coming back.\n\n        :param netfn: Net function number\n        :param command: Command value\n        :param bridge_request: The target slave address and channel number for\n                               the bridge request.\n        :param data: Command data as a tuple or list\n        :param retry: Whether to retry this particular payload or not, defaults\n                      to true.\n        :param timeout: A custom time to wait for initial reply, useful for\n                        a slow command.  This may interfere with retry logic.\n        :returns: dict -- The response from IPMI device"
  },
  {
    "code": "def get_all_submissions(course_id, item_id, item_type, read_replica=True):\n    submission_qs = Submission.objects\n    if read_replica:\n        submission_qs = _use_read_replica(submission_qs)\n    query = submission_qs.select_related('student_item').filter(\n        student_item__course_id=course_id,\n        student_item__item_id=item_id,\n        student_item__item_type=item_type,\n    ).order_by('student_item__student_id', '-submitted_at', '-id').iterator()\n    for unused_student_id, row_iter in itertools.groupby(query, operator.attrgetter('student_item.student_id')):\n        submission = next(row_iter)\n        data = SubmissionSerializer(submission).data\n        data['student_id'] = submission.student_item.student_id\n        yield data",
    "docstring": "For the given item, get the most recent submission for every student who has submitted.\n\n    This may return a very large result set! It is implemented as a generator for efficiency.\n\n    Args:\n        course_id, item_id, item_type (string): The values of the respective student_item fields\n            to filter the submissions by.\n        read_replica (bool): If true, attempt to use the read replica database.\n            If no read replica is available, use the default database.\n\n    Yields:\n        Dicts representing the submissions with the following fields:\n            student_item\n            student_id\n            attempt_number\n            submitted_at\n            created_at\n            answer\n\n    Raises:\n        Cannot fail unless there's a database error, but may return an empty iterable."
  },
  {
    "code": "def _to_utc(self, dt):\n        tz = self._get_tz()\n        loc_dt = tz.localize(dt)\n        return loc_dt.astimezone(pytz.utc)",
    "docstring": "Takes a naive timezone with an localized value and return it formatted\n        as utc."
  },
  {
    "code": "def check_key(self, key):\n        if self.key_size and len(key) not in self.key_size:\n            raise TypeError('invalid key size %s, must be one of %s' %\n                            (len(key), self.key_size))",
    "docstring": "Check that the key length is valid.\n\n        @param key:    a byte string"
  },
  {
    "code": "def _annotation_handler(ion_type, length, ctx):\n    _, self = yield\n    self_handler = _create_delegate_handler(self)\n    if ctx.annotations is not None:\n        raise IonException('Annotation cannot be nested in annotations')\n    ctx = ctx.derive_container_context(length, add_depth=0)\n    (ann_length, _), _ = yield ctx.immediate_transition(\n        _var_uint_field_handler(self_handler, ctx)\n    )\n    if ann_length < 1:\n        raise IonException('Invalid annotation length subfield; annotation wrapper must have at least one annotation.')\n    yield ctx.read_data_transition(ann_length, self)\n    ann_data = ctx.queue.read(ann_length)\n    annotations = tuple(_parse_sid_iter(ann_data))\n    if ctx.limit - ctx.queue.position < 1:\n        raise IonException('Incorrect annotation wrapper length.')\n    yield ctx.immediate_transition(\n        _start_type_handler(ctx.field_name, ctx.whence, ctx, annotations=annotations)\n    )",
    "docstring": "Handles annotations.  ``ion_type`` is ignored."
  },
  {
    "code": "def listen():\n        msg = MSG()\n        ctypes.windll.user32.GetMessageA(ctypes.byref(msg), 0, 0, 0)",
    "docstring": "Listen for keyboard input."
  },
  {
    "code": "def get_current_user(self):\n        url = self.current_user_url\n        result = self.get(url)\n        return result",
    "docstring": "Get data from the current user endpoint"
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'tokens' in _dict:\n            args['tokens'] = [\n                TokenResult._from_dict(x) for x in (_dict.get('tokens'))\n            ]\n        if 'sentences' in _dict:\n            args['sentences'] = [\n                SentenceResult._from_dict(x) for x in (_dict.get('sentences'))\n            ]\n        return cls(**args)",
    "docstring": "Initialize a SyntaxResult object from a json dictionary."
  },
  {
    "code": "def get_list_from_file(file_name):\n    with open(file_name, mode='r', encoding='utf-8') as f1:\n        lst = f1.readlines()\n    return lst",
    "docstring": "read the lines from a file into a list"
  },
  {
    "code": "def template_sunmoon(self, **kwargs):\n        kwargs_copy = self.base_dict.copy()\n        kwargs_copy.update(**kwargs)\n        kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs))\n        kwargs_copy['component'] = kwargs.get(\n            'component', self.component(**kwargs))\n        self._replace_none(kwargs_copy)        \n        localpath = NameFactory.templatesunmoon_format.format(**kwargs_copy)\n        if kwargs.get('fullpath', False):\n            return self.fullpath(localpath=localpath)\n        return localpath",
    "docstring": "return the file name for sun or moon template files"
  },
  {
    "code": "def visit_break(self, node, parent):\n        return nodes.Break(\n            getattr(node, \"lineno\", None), getattr(node, \"col_offset\", None), parent\n        )",
    "docstring": "visit a Break node by returning a fresh instance of it"
  },
  {
    "code": "def from_path(cls, *path, namespace=None):\n        parent = None\n        for i in range(0, len(path), 2):\n            parent = cls(*path[i:i + 2], parent=parent, namespace=namespace)\n        return parent",
    "docstring": "Build up a Datastore key from a path.\n\n        Parameters:\n          \\*path(tuple[str or int]): The path segments.\n          namespace(str): An optional namespace for the key. This is\n            applied to each key in the tree.\n\n        Returns:\n          anom.Key: The Datastore represented by the given path."
  },
  {
    "code": "def get_role(resource_root, service_name, name, cluster_name=\"default\"):\n  return _get_role(resource_root, _get_role_path(cluster_name, service_name, name))",
    "docstring": "Lookup a role by name\n  @param resource_root: The root Resource object.\n  @param service_name: Service name\n  @param name: Role name\n  @param cluster_name: Cluster name\n  @return: An ApiRole object"
  },
  {
    "code": "def ppo_original_world_model_stochastic_discrete():\n  hparams = ppo_original_params()\n  hparams.policy_network = \"next_frame_basic_stochastic_discrete\"\n  hparams_keys = hparams.values().keys()\n  video_hparams = basic_stochastic.next_frame_basic_stochastic_discrete()\n  for (name, value) in six.iteritems(video_hparams.values()):\n    if name in hparams_keys:\n      hparams.set_hparam(name, value)\n    else:\n      hparams.add_hparam(name, value)\n  hparams.optimization_batch_size = 1\n  hparams.weight_decay = 0\n  return hparams",
    "docstring": "Atari parameters with stochastic discrete world model as policy."
  },
  {
    "code": "def add_update(self, selector, update, multi=False, upsert=False,\n                   collation=None, array_filters=None):\n        validate_ok_for_update(update)\n        cmd = SON([('q', selector), ('u', update),\n                   ('multi', multi), ('upsert', upsert)])\n        collation = validate_collation_or_none(collation)\n        if collation is not None:\n            self.uses_collation = True\n            cmd['collation'] = collation\n        if array_filters is not None:\n            self.uses_array_filters = True\n            cmd['arrayFilters'] = array_filters\n        if multi:\n            self.is_retryable = False\n        self.ops.append((_UPDATE, cmd))",
    "docstring": "Create an update document and add it to the list of ops."
  },
  {
    "code": "def get_sig_info(hdr):\n    string = '%|DSAHEADER?{%{DSAHEADER:pgpsig}}:{%|RSAHEADER?{%{RSAHEADER:pgpsig}}:{%|SIGGPG?{%{SIGGPG:pgpsig}}:{%|SIGPGP?{%{SIGPGP:pgpsig}}:{(none)}|}|}|}|'\n    siginfo = hdr.sprintf(string)\n    if siginfo != '(none)':\n        error = 0\n        sigtype, sigdate, sigid = siginfo.split(',')\n    else:\n        error = 101\n        sigtype = 'MD5'\n        sigdate = 'None'\n        sigid = 'None'\n    infotuple = (sigtype, sigdate, sigid)\n    return error, infotuple",
    "docstring": "hand back signature information and an error code\n\n    Shamelessly stolen from Seth Vidal\n    http://yum.baseurl.org/download/misc/checksig.py"
  },
  {
    "code": "def name(self):\n        if self._name_map is None:\n            self._name_map = {}\n            for key, value in self.__class__.__dict__.items():\n                if isinstance(value, self.__class__):\n                    self._name_map[value] = key\n        return self._name_map[self]",
    "docstring": "Get the enumeration name of this cursor kind."
  },
  {
    "code": "def days_and_sids_for_frames(frames):\n    if not frames:\n        days = np.array([], dtype='datetime64[ns]')\n        sids = np.array([], dtype='int64')\n        return days, sids\n    check_indexes_all_same(\n        [frame.index for frame in frames],\n        message='Frames have mistmatched days.',\n    )\n    check_indexes_all_same(\n        [frame.columns for frame in frames],\n        message='Frames have mismatched sids.',\n    )\n    return frames[0].index.values, frames[0].columns.values",
    "docstring": "Returns the date index and sid columns shared by a list of dataframes,\n    ensuring they all match.\n\n    Parameters\n    ----------\n    frames : list[pd.DataFrame]\n        A list of dataframes indexed by day, with a column per sid.\n\n    Returns\n    -------\n    days : np.array[datetime64[ns]]\n        The days in these dataframes.\n    sids : np.array[int64]\n        The sids in these dataframes.\n\n    Raises\n    ------\n    ValueError\n        If the dataframes passed are not all indexed by the same days\n        and sids."
  },
  {
    "code": "def get_source(\n            self, environment: Environment, template: str,\n    ) -> Tuple[str, Optional[str], Callable]:\n        for loader in self._loaders():\n            try:\n                return loader.get_source(environment, template)\n            except TemplateNotFound:\n                continue\n        raise TemplateNotFound(template)",
    "docstring": "Returns the template source from the environment.\n\n        This considers the loaders on the :attr:`app` and blueprints."
  },
  {
    "code": "def get_public_orders(self, group=False):\n        self._log('get public orders')\n        return self._rest_client.get(\n            endpoint='/order_book',\n            params={'book': self.name, 'group': int(group)}\n        )",
    "docstring": "Return public orders that are currently open.\n\n        :param group: If set to True (default: False), orders with the same\n            price are grouped.\n        :type group: bool\n        :return: Public orders currently open.\n        :rtype: dict"
  },
  {
    "code": "def get_datastream(self, datastream):\n        response = self.http.get('/Datastream/' + str(datastream))\n        datastream = Schemas.Datastream(datastream=response)\n        return datastream",
    "docstring": "To get Datastream by id"
  },
  {
    "code": "def text_extents(self, text):\n        extents = ffi.new('cairo_text_extents_t *')\n        cairo.cairo_text_extents(self._pointer, _encode_string(text), extents)\n        self._check_status()\n        return (\n            extents.x_bearing, extents.y_bearing,\n            extents.width, extents.height,\n            extents.x_advance, extents.y_advance)",
    "docstring": "Returns the extents for a string of text.\n\n        The extents describe a user-space rectangle\n        that encloses the \"inked\" portion of the text,\n        (as it would be drawn by :meth:`show_text`).\n        Additionally, the :obj:`x_advance` and :obj:`y_advance` values\n        indicate the amount by which the current point would be advanced\n        by :meth:`show_text`.\n\n        Note that whitespace characters do not directly contribute\n        to the size of the rectangle (:obj:`width` and :obj:`height`).\n        They do contribute indirectly by changing the position\n        of non-whitespace characters.\n        In particular, trailing whitespace characters are likely\n        to not affect the size of the rectangle,\n        though they will affect the x_advance and y_advance values.\n\n        Because text extents are in user-space coordinates,\n        they are mostly, but not entirely,\n        independent of the current transformation matrix.\n        If you call :meth:`context.scale(2) <scale>`,\n        text will be drawn twice as big,\n        but the reported text extents will not be doubled.\n        They will change slightly due to hinting\n        (so you can't assume that metrics are independent\n        of the transformation matrix),\n        but otherwise will remain unchanged.\n\n        :param text: The text to measure, as an Unicode or UTF-8 string.\n        :returns:\n            A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)``\n            tuple of floats.\n\n        :obj:`x_bearing`\n            The horizontal distance\n            from the origin to the leftmost part of the glyphs as drawn.\n            Positive if the glyphs lie entirely to the right of the origin.\n\n        :obj:`y_bearing`\n            The vertical distance\n            from the origin to the topmost part of the glyphs as drawn.\n            Positive only if the glyphs lie completely below the origin;\n            will usually be negative.\n\n        :obj:`width`\n            Width of the glyphs as drawn.\n\n        :obj:`height`\n            Height of the glyphs as drawn.\n\n        :obj:`x_advance`\n            Distance to advance in the X direction\n            after drawing these glyphs.\n\n        :obj:`y_advance`\n            Distance to advance in the Y direction\n            after drawing these glyphs.\n            Will typically be zero except for vertical text layout\n            as found in East-Asian languages."
  },
  {
    "code": "def get_objective(self, sampler):\n        def objective(params):\n            circuit = self.get_circuit(params)\n            circuit.make_cache()\n            return self.get_energy(circuit, sampler)\n        return objective",
    "docstring": "Get an objective function to be optimized."
  },
  {
    "code": "def add_shortcut_to_tooltip(action, context, name):\r\n    action.setToolTip(action.toolTip() + ' (%s)' %\r\n                      get_shortcut(context=context, name=name))",
    "docstring": "Add the shortcut associated with a given action to its tooltip"
  },
  {
    "code": "def parse(self):\n\t\tc = Collection()\n\t\twhile self.index < self.datalen:\n\t\t\tg = self.parseOneGame()\n\t\t\tif g:\n\t\t\t\tc.append(g)\n\t\t\telse:\n\t\t\t\tbreak\n\t\treturn c",
    "docstring": "Parses the SGF data stored in 'self.data', and returns a 'Collection'."
  },
  {
    "code": "def load_model(modelname, add_sentencizer=False):\n    loading_start = time.time()\n    nlp = spacy.load(modelname)\n    if add_sentencizer:\n        nlp.add_pipe(nlp.create_pipe('sentencizer'))\n    loading_end = time.time()\n    loading_time = loading_end - loading_start\n    if add_sentencizer:\n        return nlp, loading_time, modelname + '_sentencizer'\n    return nlp, loading_time, modelname",
    "docstring": "Load a specific spaCy model"
  },
  {
    "code": "def _add_person_to_group(person, group):\n    from karaage.datastores import add_accounts_to_group\n    from karaage.datastores import add_accounts_to_project\n    from karaage.datastores import add_accounts_to_institute\n    a_list = person.account_set\n    add_accounts_to_group(a_list, group)\n    for project in group.project_set.all():\n        add_accounts_to_project(a_list, project)\n    for institute in group.institute_set.all():\n        add_accounts_to_institute(a_list, institute)",
    "docstring": "Call datastores after adding a person to a group."
  },
  {
    "code": "def _populate_ranking_payoff_arrays(payoff_arrays, scores, costs):\n    n = payoff_arrays[0].shape[0]\n    for p, payoff_array in enumerate(payoff_arrays):\n        payoff_array[0, :] = 0\n        for i in range(1, n):\n            for j in range(n):\n                payoff_array[i, j] = -costs[p, i-1]\n    prize = 1.\n    for i in range(n):\n        for j in range(n):\n            if scores[0, i] > scores[1, j]:\n                payoff_arrays[0][i, j] += prize\n            elif scores[0, i] < scores[1, j]:\n                payoff_arrays[1][j, i] += prize\n            else:\n                payoff_arrays[0][i, j] += prize / 2\n                payoff_arrays[1][j, i] += prize / 2",
    "docstring": "Populate the ndarrays in `payoff_arrays` with the payoff values of\n    the ranking game given `scores` and `costs`.\n\n    Parameters\n    ----------\n    payoff_arrays : tuple(ndarray(float, ndim=2))\n        Tuple of 2 ndarrays of shape (n, n). Modified in place.\n    scores : ndarray(int, ndim=2)\n        ndarray of shape (2, n) containing score values corresponding to\n        the effort levels for the two players.\n    costs : ndarray(float, ndim=2)\n        ndarray of shape (2, n-1) containing cost values corresponding\n        to the n-1 positive effort levels for the two players, with the\n        assumption that the cost of the zero effort action is zero."
  },
  {
    "code": "def _find_inline_images(contentsinfo):\n    \"Find inline images in the contentstream\"\n    for n, inline in enumerate(contentsinfo.inline_images):\n        yield ImageInfo(\n            name='inline-%02d' % n, shorthand=inline.shorthand, inline=inline\n        )",
    "docstring": "Find inline images in the contentstream"
  },
  {
    "code": "def width(self) -> int:\n        max_x = -1.0\n        for x, _ in self.entries.keys():\n            max_x = max(max_x, x)\n        for v in self.vertical_lines:\n            max_x = max(max_x, v.x)\n        for h in self.horizontal_lines:\n            max_x = max(max_x, h.x1, h.x2)\n        return 1 + int(max_x)",
    "docstring": "Determines how many entry columns are in the diagram."
  },
  {
    "code": "def _adjust_inferential_results_for_parameter_constraints(self,\n                                                              constraints):\n        if constraints is not None:\n            inferential_attributes = [\"standard_errors\",\n                                      \"tvalues\",\n                                      \"pvalues\",\n                                      \"robust_std_errs\",\n                                      \"robust_t_stats\",\n                                      \"robust_p_vals\"]\n            assert all([hasattr(self, x) for x in inferential_attributes])\n            assert hasattr(self, \"params\")\n            all_names = self.params.index.tolist()\n            for series in [getattr(self, x) for x in inferential_attributes]:\n                for pos in constraints:\n                    series.loc[all_names[pos]] = np.nan\n        return None",
    "docstring": "Ensure that parameters that were constrained during estimation do not\n        have any values showed for inferential results. After all, no inference\n        was performed.\n\n        Parameters\n        ----------\n        constraints : list of ints, or None.\n            If list, should contain the positions in the array of all estimated\n            parameters that were constrained to their initial values.\n\n        Returns\n        -------\n        None."
  },
  {
    "code": "def loadScopeGroupbyName(self, name, service_group_id, callback=None, errback=None):\n        import ns1.ipam\n        scope_group = ns1.ipam.Scopegroup(self.config, name=name, service_group_id=service_group_id)\n        return scope_group.load(callback=callback, errback=errback)",
    "docstring": "Load an existing Scope Group by name and service group id into a high level Scope Group object\n\n        :param str name: Name of an existing Scope Group\n        :param int service_group_id: id of the service group the Scope group is associated with"
  },
  {
    "code": "def _sign(self, data: bytes) -> bytes:\n        assert self._raiden_service is not None\n        return self._raiden_service.signer.sign(data=data)",
    "docstring": "Use eth_sign compatible hasher to sign matrix data"
  },
  {
    "code": "def compile(conf):\n    with errorprint():\n        config = ConfModule(conf)\n        for conf in config.configurations:\n            conf.format(do_print=True)",
    "docstring": "Compiles classic uWSGI configuration file using the default\n    or given `uwsgiconf` configuration module."
  },
  {
    "code": "def delete_jail(name):\n    if is_jail(name):\n        cmd = 'poudriere jail -d -j {0}'.format(name)\n        __salt__['cmd.run'](cmd)\n        if is_jail(name):\n            return 'Looks like there was an issue deleteing jail \\\n            {0}'.format(name)\n    else:\n        return 'Looks like jail {0} has not been created'.format(name)\n    make_file = os.path.join(_config_dir(), '{0}-make.conf'.format(name))\n    if os.path.isfile(make_file):\n        try:\n            os.remove(make_file)\n        except (IOError, OSError):\n            return ('Deleted jail \"{0}\" but was unable to remove jail make '\n                    'file').format(name)\n        __salt__['file.remove'](make_file)\n    return 'Deleted jail {0}'.format(name)",
    "docstring": "Deletes poudriere jail with `name`\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' poudriere.delete_jail 90amd64"
  },
  {
    "code": "def copy(self, newdata=None):\n        if newdata is None:\n            newdata = self.data.copy()\n        return self.__class__(\n            self.molecule, self.origin.copy(), self.axes.copy(),\n            self.nrep.copy(), newdata, self.subtitle, self.nuclear_charges\n        )",
    "docstring": "Return a copy of the cube with optionally new data."
  },
  {
    "code": "def bitcoin_address(self) -> str:\n        type_ = self.random.choice(['1', '3'])\n        letters = string.ascii_letters + string.digits\n        return type_ + ''.join(\n            self.random.choice(letters) for _ in range(33))",
    "docstring": "Generate a random bitcoin address.\n\n        :return: Bitcoin address.\n\n        :Example:\n            3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX"
  },
  {
    "code": "def derive_title(self):\n        if not self.title:\n            return _(\"Create %s\") % force_text(self.model._meta.verbose_name).title()\n        else:\n            return self.title",
    "docstring": "Derives our title from our object"
  },
  {
    "code": "def get_attribute(module_name: str, attribute_name: str):\n    assert isinstance(module_name, str)\n    assert isinstance(attribute_name, str)\n    _module = importlib.import_module(module_name)\n    return getattr(_module, attribute_name)",
    "docstring": "Get the specified module attribute. It most cases, it will be a class or function.\n\n    :param module_name: module name\n    :param attribute_name: attribute name\n    :return: module attribute"
  },
  {
    "code": "def log_middleware(store):\n    def wrapper(next_):\n        def log_dispatch(action):\n            print('Dispatch Action:', action)\n            return next_(action)\n        return log_dispatch\n    return wrapper",
    "docstring": "log all actions to console as they are dispatched"
  },
  {
    "code": "def adjustMinimumWidth( self ):\r\n        pw = self.pixmapSize().width()\r\n        self.setMinimumWidth(pw * self.maximum() + 3 * self.maximum())",
    "docstring": "Modifies the minimum width to factor in the size of the pixmaps and the\r\n        number for the maximum."
  },
  {
    "code": "def visit_Import(self, node):\n        for alias in node.names:\n            current_module = MODULES\n            for path in alias.name.split('.'):\n                if path not in current_module:\n                    raise PythranSyntaxError(\n                        \"Module '{0}' unknown.\".format(alias.name),\n                        node)\n                else:\n                    current_module = current_module[path]",
    "docstring": "Check if imported module exists in MODULES."
  },
  {
    "code": "def create_parser(self, prog_name, subcommand):\n        parser = OptionParser(prog=prog_name,\n                              usage=self.usage(subcommand),\n                              option_list=self.option_list)\n        return parser",
    "docstring": "Create an OptionParser\n        prog_name - Name of a command\n        subcommand - Name of a subcommand"
  },
  {
    "code": "def _recursive_getitem(d, key):\n    if key in d:\n        return d\n    else:\n        for v in d.values():\n            return _recursive_getitem(v, key)\n        else:\n            raise KeyError('Key not found: {}'.format(key))",
    "docstring": "Descend into a dict of dicts to return the one that contains\n    a given key. Every value in the dict must be another dict."
  },
  {
    "code": "def _get_raw_key(self, key_id):\n        try:\n            static_key = self._static_keys[key_id]\n        except KeyError:\n            static_key = os.urandom(32)\n            self._static_keys[key_id] = static_key\n        return WrappingKey(\n            wrapping_algorithm=WrappingAlgorithm.AES_256_GCM_IV12_TAG16_NO_PADDING,\n            wrapping_key=static_key,\n            wrapping_key_type=EncryptionKeyType.SYMMETRIC,\n        )",
    "docstring": "Returns a static, randomly-generated symmetric key for the specified key ID.\n\n        :param str key_id: Key ID\n        :returns: Wrapping key that contains the specified static key\n        :rtype: :class:`aws_encryption_sdk.internal.crypto.WrappingKey`"
  },
  {
    "code": "def add_before(self, pipeline):\n        if not isinstance(pipeline, Pipeline):\n            pipeline = Pipeline(pipeline)\n        self.pipes = pipeline.pipes[:] + self.pipes[:]\n        return self",
    "docstring": "Add a Pipeline to be applied before this processing pipeline.\n\n        Arguments:\n            pipeline: The Pipeline or callable to apply before this\n                Pipeline."
  },
  {
    "code": "def getvalue(self, v):\n        if not is_measure(v):\n            raise TypeError('Incorrect input type for getvalue()')\n        import re\n        rx = re.compile(\"m\\d+\")\n        out = []\n        keys = v.keys()[:]\n        keys.sort()\n        for key in keys:\n            if re.match(rx, key):\n                out.append(dq.quantity(v.get(key)))\n        return out",
    "docstring": "Return a list of quantities making up the measures' value.\n\n        :param v: a measure"
  },
  {
    "code": "def serialize(self):\n        if self.mate_chrom is None:\n            remote_tag = \".\"\n        else:\n            if self.within_main_assembly:\n                mate_chrom = self.mate_chrom\n            else:\n                mate_chrom = \"<{}>\".format(self.mate_chrom)\n            tpl = {FORWARD: \"[{}:{}[\", REVERSE: \"]{}:{}]\"}[self.mate_orientation]\n            remote_tag = tpl.format(mate_chrom, self.mate_pos)\n        if self.orientation == FORWARD:\n            return remote_tag + self.sequence\n        else:\n            return self.sequence + remote_tag",
    "docstring": "Return string representation for VCF"
  },
  {
    "code": "def print_config():\n    description =\n    parser = argparse.ArgumentParser(\n        description=textwrap.dedent(description)\n    )\n    parser.add_argument(\n        'config_uri', type=str, help='an integer for the accumulator'\n    )\n    parser.add_argument(\n        '-k', '--key',\n        dest='key',\n        metavar='PREFIX',\n        type=str,\n        action='store',\n        help=(\n            \"Tells script to print only specified\"\n            \" config tree provided by dotted name\"\n        )\n    )\n    args = parser.parse_args(sys.argv[1:])\n    config_uri = args.config_uri\n    env = bootstrap(config_uri)\n    config, closer = env['registry']['config'], env['closer']\n    try:\n        print(printer(slice_config(config, args.key)))\n    except KeyError:\n        print(\n            'Sorry, but the key path {0}, does not exists in Your config!'\n            .format(args.key)\n        )\n    finally:\n        closer()",
    "docstring": "Print config entry function."
  },
  {
    "code": "def start(self):\n        if self.running:\n            self.stop()\n        self._thread = threading.Thread(target=self._wrapped_target)\n        self._thread.daemon = True\n        self._thread.start()",
    "docstring": "Start the run method as a new thread.\n\n        It will first stop the thread if it is already running."
  },
  {
    "code": "def convert2wkt(self, set3D=True):\n        features = self.getfeatures()\n        for feature in features:\n            try:\n                feature.geometry().Set3D(set3D)\n            except AttributeError:\n                dim = 3 if set3D else 2\n                feature.geometry().SetCoordinateDimension(dim)\n        return [feature.geometry().ExportToWkt() for feature in features]",
    "docstring": "export the geometry of each feature as a wkt string\n\n        Parameters\n        ----------\n        set3D: bool\n            keep the third (height) dimension?\n\n        Returns\n        -------"
  },
  {
    "code": "def delete_database(self, database):\n        url = \"db/{0}\".format(database)\n        self.request(\n            url=url,\n            method='DELETE',\n            expected_response_code=204\n        )\n        return True",
    "docstring": "Drop a database on the InfluxDB server.\n\n        :param database: the name of the database to delete\n        :type database: string\n        :rtype: boolean"
  },
  {
    "code": "def deploy():\n    _require_root()\n    if not confirm(\"This will apply any available migrations to the database. Has the database been backed up?\"):\n        abort(\"Aborted.\")\n    if not confirm(\"Are you sure you want to deploy?\"):\n        abort(\"Aborted.\")\n    with lcd(PRODUCTION_DOCUMENT_ROOT):\n        with shell_env(PRODUCTION=\"TRUE\"):\n            local(\"git pull\")\n            with open(\"requirements.txt\", \"r\") as req_file:\n                requirements = req_file.read().strip().split()\n                try:\n                    pkg_resources.require(requirements)\n                except pkg_resources.DistributionNotFound:\n                    local(\"pip install -r requirements.txt\")\n                except Exception:\n                    traceback.format_exc()\n                    local(\"pip install -r requirements.txt\")\n                else:\n                    puts(\"Python requirements already satisfied.\")\n            with prefix(\"source /usr/local/virtualenvs/ion/bin/activate\"):\n                local(\"./manage.py collectstatic --noinput\", shell=\"/bin/bash\")\n                local(\"./manage.py migrate\", shell=\"/bin/bash\")\n            restart_production_gunicorn(skip=True)\n    puts(\"Deploy complete.\")",
    "docstring": "Deploy to production."
  },
  {
    "code": "def postToNodeInBox(self, msg, frm):\n        logger.trace(\"{} appending to nodeInbox {}\".format(self, msg))\n        self.nodeInBox.append((msg, frm))",
    "docstring": "Append the message to the node inbox\n\n        :param msg: a node message\n        :param frm: the name of the node that sent this `msg`"
  },
  {
    "code": "def wiki(self):\n        date = self.pull.created_at.strftime(\"%m/%d/%Y %H:%M\")\n        return \"{} {} ({} [{} github])\\n\".format(self.pull.avatar_url, self.pull.body, date,\n                                                 self.pull.html_url)",
    "docstring": "Returns the wiki markup describing the details of the github pull request\n        as well as a link to the details on github."
  },
  {
    "code": "def get(self, name=None, default=None):\n        if name is None:\n            return self.data\n        if not isinstance(name, list):\n            name = [name]\n        data = self.data\n        try:\n            for key in name:\n                data = data[key]\n        except KeyError:\n            return default\n        return data",
    "docstring": "Get attribute value or return default\n\n        Whole data dictionary is returned when no attribute provided.\n        Supports direct values retrieval from deep dictionaries as well.\n        Dictionary path should be provided as list. The following two\n        examples are equal:\n\n        tree.data['hardware']['memory']['size']\n        tree.get(['hardware', 'memory', 'size'])\n\n        However the latter approach will also correctly handle providing\n        default value when any of the dictionary keys does not exist."
  },
  {
    "code": "def place_market_order(self, side: Side, amount: Number) -> Order:\n        return self.place_order(side, OrderType.MARKET, amount)",
    "docstring": "Place a market order."
  },
  {
    "code": "async def dump_message(obj, msg, field_archiver=None):\n    mtype = msg.__class__\n    fields = mtype.f_specs()\n    obj = collections.OrderedDict() if obj is None else get_elem(obj)\n    for field in fields:\n        await dump_message_field(obj, msg=msg, field=field, field_archiver=field_archiver)\n    return obj",
    "docstring": "Dumps message to the object.\n    Returns message popo representation.\n\n    :param obj:\n    :param msg:\n    :param field_archiver:\n    :return:"
  },
  {
    "code": "def make_url(path, protocol=None, hosts=None):\n    protocol = 'https://' if not protocol else protocol\n    host = hosts[random.randrange(len(hosts))] if hosts else 'archive.org'\n    return protocol + host + path.strip()",
    "docstring": "Make an URL given a path, and optionally, a protocol and set of\n    hosts to select from randomly.\n\n    :param path: The Archive.org path.\n    :type path: str\n\n    :param protocol: (optional) The HTTP protocol to use. \"https://\" is\n                     used by default.\n    :type protocol: str\n\n    :param hosts: (optional) A set of hosts. A host will be chosen at\n                  random. The default host is \"archive.org\".\n    :type hosts: iterable\n\n    :rtype: str\n    :returns: An Absolute URI."
  },
  {
    "code": "def sg_summary_gradient(tensor, gradient, prefix=None, name=None):\n    r\n    prefix = '' if prefix is None else prefix + '/'\n    name = prefix + _pretty_name(tensor) if name is None else prefix + name\n    _scalar(name + '/grad', tf.reduce_mean(tf.abs(gradient)))\n    _histogram(name + '/grad-h', tf.abs(gradient))",
    "docstring": "r\"\"\"Register `tensor` to summary report as `gradient`\n\n    Args:\n      tensor: A `Tensor` to log as gradient\n      gradient: A 0-D `Tensor`. A gradient to log\n      prefix: A `string`. A prefix to display in the tensor board web UI.\n      name: A `string`. A name to display in the tensor board web UI.\n\n    Returns:\n        None"
  },
  {
    "code": "def get_gradients(self) -> Dict[str, List[mx.nd.NDArray]]:\n        return {\"dev_%d_%s\" % (i, name): exe.grad_arrays[j] for i, exe in enumerate(self.executors) for j, name in\n                enumerate(self.executor_group.arg_names)\n                if name in self.executor_group.param_names and self.executors[0].grad_arrays[j] is not None}",
    "docstring": "Returns a mapping of parameters names to gradient arrays. Parameter names are prefixed with the device."
  },
  {
    "code": "def get_cmd(self):\n        cmd = None\n        if self.test_program in ('nose', 'nosetests'):\n            cmd = \"nosetests %s\" % self.file_path\n        elif self.test_program == 'django':\n            executable = \"%s/manage.py\" % self.file_path\n            if os.path.exists(executable):\n                cmd = \"python %s/manage.py test\" % self.file_path\n            else:\n                cmd = \"django-admin.py test\"\n        elif self.test_program == 'py':\n            cmd = 'py.test %s' % self.file_path\n        elif self.test_program == 'symfony':\n            cmd = 'symfony test-all'\n        elif self.test_program == 'jelix':\n            cmd = 'php tests.php'\n        elif self.test_program == 'phpunit':\n            cmd = 'phpunit'\n        elif self.test_program == 'sphinx':\n            cmd = 'make html'\n        elif self.test_program == 'tox':\n            cmd = 'tox'\n        if not cmd:\n            raise InvalidTestProgram(\"The test program %s is unknown. Valid options are: `nose`, `django` and `py`\" % self.test_program)\n        if self.custom_args:\n            cmd = '%s %s' % (cmd, self.custom_args)\n        return cmd",
    "docstring": "Returns the full command to be executed at runtime"
  },
  {
    "code": "def from_edgelist(self, edges, strict=True):\n        for edge in edges:\n            if len(edge) == 3:\n                self.update(edge[1], edge[0], **edge[2])\n            elif len(edge) == 2:\n                self.update(edge[1], edge[0])\n            elif strict:\n                raise ValueError('edge incorrect shape: {}'.format(str(edge)))",
    "docstring": "Load transform data from an edge list into the current\n        scene graph.\n\n        Parameters\n        -------------\n        edgelist : (n,) tuples\n            (node_a, node_b, {key: value})\n        strict : bool\n            If true, raise a ValueError when a\n            malformed edge is passed in a tuple."
  },
  {
    "code": "def confidence_interval(self, confidenceLevel):\n        if not (confidenceLevel >= 0 and confidenceLevel <= 1):\n            raise ValueError(\"Parameter percentage has to be in [0,1]\")\n        underestimations = []\n        overestimations = []\n        for error in self._errorValues:\n            if error is None:\n                continue\n            if error >= 0:\n                overestimations.append(error)\n            if error <= 0:\n                underestimations.append(error)\n        overestimations.sort()\n        underestimations.sort(reverse=True)\n        overIdx  = int(len(overestimations) * confidenceLevel) - 1\n        underIdx = int(len(underestimations) * confidenceLevel) - 1\n        overestimation  = 0.0\n        underestimation = 0.0\n        if overIdx >= 0:\n            overestimation = overestimations[overIdx]\n        else:\n            print len(overestimations), confidenceLevel\n        if underIdx >= 0:\n            underestimation = underestimations[underIdx]\n        return underestimation, overestimation",
    "docstring": "Calculates for which value confidenceLevel% of the errors are closer to 0.\n\n        :param float confidenceLevel: percentage of the errors that should be\n            smaller than the returned value for overestimations and larger than\n            the returned value for underestimations.\n            confidenceLevel has to be in [0.0, 1.0]\n\n        :return:    return a tuple containing the underestimation and overestimation for\n            the given confidenceLevel\n        :rtype:     tuple\n\n        :warning:    Index is still not calculated correctly"
  },
  {
    "code": "def docgraph2freqt(docgraph, root=None, include_pos=False,\n                   escape_func=FREQT_ESCAPE_FUNC):\n    if root is None:\n        return u\"\\n\".join(\n            sentence2freqt(docgraph, sentence, include_pos=include_pos,\n                           escape_func=escape_func)\n            for sentence in docgraph.sentences)\n    else:\n        return sentence2freqt(docgraph, root, include_pos=include_pos,\n                              escape_func=escape_func)",
    "docstring": "convert a docgraph into a FREQT string."
  },
  {
    "code": "def lookup_data(self, lookup, data):\n        value = data\n        parts = lookup.split('.')\n        if not parts or not parts[0]:\n            return value\n        part = parts[0]\n        remaining_lookup = '.'.join(parts[1:])\n        if callable(getattr(data, 'keys', None)) and hasattr(data, '__getitem__'):\n            value = data[part]\n        elif data is not None:\n            value = getattr(data, part)\n        if callable(value) and not hasattr(value, 'db_manager'):\n            value = value()\n        if not remaining_lookup:\n            return value\n        return self.lookup_data(remaining_lookup, value)",
    "docstring": "Given a lookup string, attempts to descend through nested data looking for\n        the value.\n\n        Can work with either dictionary-alikes or objects (or any combination of\n        those).\n\n        Lookups should be a string. If it is a dotted path, it will be split on\n        ``.`` & it will traverse through to find the final value. If not, it will\n        simply attempt to find either a key or attribute of that name & return it.\n\n        Example::\n\n            >>> data = {\n            ...     'type': 'message',\n            ...     'greeting': {\n            ...         'en': 'hello',\n            ...         'fr': 'bonjour',\n            ...         'es': 'hola',\n            ...     },\n            ...     'person': Person(\n            ...         name='daniel'\n            ...     )\n            ... }\n            >>> lookup_data('type', data)\n            'message'\n            >>> lookup_data('greeting.en', data)\n            'hello'\n            >>> lookup_data('person.name', data)\n            'daniel'"
  },
  {
    "code": "def list_(runas=None):\n    ret = []\n    output = _rbenv_exec(['install', '--list'], runas=runas)\n    if output:\n        for line in output.splitlines():\n            if line == 'Available versions:':\n                continue\n            ret.append(line.strip())\n    return ret",
    "docstring": "List the installable versions of ruby\n\n    runas\n        The user under which to run rbenv. If not specified, then rbenv will be\n        run as the user under which Salt is running.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rbenv.list"
  },
  {
    "code": "def utc_dt(dt):\n    if not dt.tzinfo:\n        return pytz.utc.localize(dt)\n    return dt.astimezone(pytz.utc)",
    "docstring": "Set UTC timezone on a datetime object.\n\n    A naive datetime is assumed to be in UTC TZ."
  },
  {
    "code": "def connect(self):\n        try:\n            for group in ('inlets', 'receivers', 'outlets', 'senders'):\n                self._connect_subgroup(group)\n        except BaseException:\n            objecttools.augment_excmessage(\n                'While trying to build the node connection of the `%s` '\n                'sequences of the model handled by element `%s`'\n                % (group[:-1], objecttools.devicename(self)))",
    "docstring": "Connect the link sequences of the actual model."
  },
  {
    "code": "def wrap(self, string, width):\n        if not string or width <= 0:\n            logging.error(\"invalid string: %s or width: %s\" % (string, width))\n            return False\n        tmp = \"\"\n        for line in string.splitlines():\n            if len(line) <= width:\n                tmp += line + \"\\n\"\n                continue\n            cur = 0\n            length = len(line)\n            while cur + width < length:\n                cur = line[:cur+width].rfind(self.sep) + len(self.sep) - 1\n                line = line[:cur] + \"\\n\" + line[cur+1:]\n            tmp += line + \"\\n\\n\"\n        return tmp",
    "docstring": "Wrap lines according to width\n        Place '\\n' whenever necessary"
  },
  {
    "code": "def from_database(cls, database):\n        if isinstance(database, PostgresqlDatabase):\n            return PostgresqlMigrator(database)\n        if isinstance(database, SqliteDatabase):\n            return SqliteMigrator(database)\n        if isinstance(database, MySQLDatabase):\n            return MySQLMigrator(database)\n        return super(SchemaMigrator, cls).from_database(database)",
    "docstring": "Initialize migrator by db."
  },
  {
    "code": "def get_all_formulae(chebi_ids):\n    all_formulae = [get_formulae(chebi_id) for chebi_id in chebi_ids]\n    return [x for sublist in all_formulae for x in sublist]",
    "docstring": "Returns all formulae"
  },
  {
    "code": "def domain_score(self, domains):\n        warn(\n            'OpenDNS Domain Scores endpoint is deprecated. Use '\n            'InvestigateApi.categorization() instead', DeprecationWarning,\n        )\n        url_path = 'domains/score/'\n        return self._multi_post(url_path, domains)",
    "docstring": "Calls domain scores endpoint.\n\n        This method is deprecated since OpenDNS Investigate API\n        endpoint is also deprecated."
  },
  {
    "code": "def get_wide_unicode(self, i):\n        value = []\n        for x in range(3):\n            c = next(i)\n            if c == '0':\n                value.append(c)\n            else:\n                raise SyntaxError('Invalid wide Unicode character at %d!' % (i.index - 1))\n        c = next(i)\n        if c in ('0', '1'):\n            value.append(c)\n        else:\n            raise SyntaxError('Invalid wide Unicode character at %d!' % (i.index - 1))\n        for x in range(4):\n            c = next(i)\n            if c.lower() in _HEX:\n                value.append(c)\n            else:\n                raise SyntaxError('Invalid wide Unicode character at %d!' % (i.index - 1))\n        return ''.join(value)",
    "docstring": "Get narrow Unicode."
  },
  {
    "code": "def get_plugins_info(self):\n        d = {}\n        for p in self.plugins:\n            d.update(p.get_info())\n        return d",
    "docstring": "Collect the current live info from all the registered plugins.\n\n        Return a dictionary, keyed on the plugin name."
  },
  {
    "code": "def transaction(data_access):\n  old_autocommit = data_access.autocommit\n  data_access.autocommit = False\n  try:\n    yield data_access\n  except RollbackTransaction as ex:\n    data_access.rollback()\n  except Exception as ex:\n    data_access.rollback()\n    raise ex\n  else:\n    data_access.commit()\n  finally:\n    data_access.autocommit = old_autocommit",
    "docstring": "Wrap statements in a transaction. If the statements succeed, commit, otherwise rollback.\n\n  :param data_access: a DataAccess instance"
  },
  {
    "code": "def list_all_directories(self):\n        def list_dirs_recursively(directory):\n            if directory == self.filesystem:\n                yield directory\n            d_gen = itertools.chain(\n                directory.directories,\n                *tuple(list_dirs_recursively(d)\n                       for d in directory.directories))\n            for d in d_gen:\n                yield d\n        return list_dirs_recursively(self.filesystem)",
    "docstring": "Utility method that yields all directories on the device's file\n            systems."
  },
  {
    "code": "def _form_datetimes(days, msecs):\n    all_datetimes = []\n    for i in range(days.size):\n        day = int(days[i])\n        msec = msecs[i]\n        scanline_datetimes = []\n        for j in range(int(VALUES_PER_SCAN_LINE / 4)):\n            usec = 1000 * (j * VIEW_TIME_ADJUSTMENT + msec)\n            delta = (dt.timedelta(days=day, microseconds=usec))\n            for k in range(4):\n                scanline_datetimes.append(delta.total_seconds())\n        all_datetimes.append(scanline_datetimes)\n    return np.array(all_datetimes, dtype=np.float64)",
    "docstring": "Calculate seconds since EPOCH from days and milliseconds for each of IASI scan."
  },
  {
    "code": "def get_valid_cwd():\n    try:\n        cwd = _current_dir()\n    except:\n        warn(\"Your current directory is invalid. If you open a ticket at \" +\n            \"https://github.com/milkbikis/powerline-shell/issues/new \" +\n            \"we would love to help fix the issue.\")\n        sys.stdout.write(\"> \")\n        sys.exit(1)\n    parts = cwd.split(os.sep)\n    up = cwd\n    while parts and not os.path.exists(up):\n        parts.pop()\n        up = os.sep.join(parts)\n    if cwd != up:\n        warn(\"Your current directory is invalid. Lowest valid directory: \"\n             + up)\n    return cwd",
    "docstring": "Determine and check the current working directory for validity.\n\n    Typically, an directory arises when you checkout a different branch on git\n    that doesn't have this directory. When an invalid directory is found, a\n    warning is printed to the screen, but the directory is still returned\n    as-is, since this is what the shell considers to be the cwd."
  },
  {
    "code": "def get_history_by_tail_number(self, tail_number, page=1, limit=100):\n        url = REG_BASE.format(tail_number, str(self.AUTH_TOKEN), page, limit)\n        return self._fr24.get_data(url, True)",
    "docstring": "Fetch the history of a particular aircraft by its tail number.\n\n        This method can be used to get the history of a particular aircraft by its tail number.\n        It checks the user authentication and returns the data accordingly.\n\n        Args:\n            tail_number (str): The tail number, e.g. VT-ANL\n            page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data\n            limit (int): Optional limit on number of records returned\n\n        Returns:\n            A list of dicts with the data; one dict for each row of data from flightradar24\n\n        Example::\n\n            from pyflightdata import FlightData\n            f=FlightData()\n            #optional login\n            f.login(myemail,mypassword)\n            f.get_history_by_flight_number('VT-ANL')\n            f.get_history_by_flight_number('VT-ANL',page=1,limit=10)"
  },
  {
    "code": "def findPrevStmt(self, block):\n        stmtEnd = self._prevNonCommentBlock(block)\n        stmtStart = self.findStmtStart(stmtEnd)\n        return Statement(self._qpart, stmtStart, stmtEnd)",
    "docstring": "Returns a tuple that contains the first and last line of the\n        previous statement before line."
  },
  {
    "code": "def check_security_settings():\n    in_production = not (current_app.debug or current_app.testing)\n    secure = current_app.config.get('SESSION_COOKIE_SECURE')\n    if in_production and not secure:\n        current_app.logger.warning(\n            \"SESSION_COOKIE_SECURE setting must be set to True to prevent the \"\n            \"session cookie from being leaked over an insecure channel.\"\n        )",
    "docstring": "Warn if session cookie is not secure in production."
  },
  {
    "code": "def memoize(func):\n    cache = {}\n    def memoizer():\n        if 0 not in cache:\n            cache[0] = func()\n        return cache[0]\n    return functools.wraps(func)(memoizer)",
    "docstring": "Cache forever."
  },
  {
    "code": "def _split_match_steps_into_match_traversals(match_steps):\n    output = []\n    current_list = None\n    for step in match_steps:\n        if isinstance(step.root_block, QueryRoot):\n            if current_list is not None:\n                output.append(current_list)\n            current_list = [step]\n        else:\n            current_list.append(step)\n    if current_list is None:\n        raise AssertionError(u'current_list was unexpectedly None: {}'.format(match_steps))\n    output.append(current_list)\n    return output",
    "docstring": "Split a list of MatchSteps into multiple lists, each denoting a single MATCH traversal."
  },
  {
    "code": "async def hmset(self, name, mapping):\n        if not mapping:\n            raise DataError(\"'hmset' with 'mapping' of length 0\")\n        items = []\n        for pair in iteritems(mapping):\n            items.extend(pair)\n        return await self.execute_command('HMSET', name, *items)",
    "docstring": "Set key to value within hash ``name`` for each corresponding\n        key and value from the ``mapping`` dict."
  },
  {
    "code": "def get_access_token(self):\n        if (self.token is None) or (datetime.utcnow() > self.reuse_token_until):\n            headers = {'Ocp-Apim-Subscription-Key': self.client_secret}\n            response = requests.post(self.base_url, headers=headers)\n            response.raise_for_status()\n            self.token = response.content\n            self.reuse_token_until = datetime.utcnow() + timedelta(minutes=5)\n        return self.token.decode('utf-8')",
    "docstring": "Returns an access token for the specified subscription.\n\n        This method uses a cache to limit the number of requests to the token service.\n        A fresh token can be re-used during its lifetime of 10 minutes. After a successful\n        request to the token service, this method caches the access token. Subsequent\n        invocations of the method return the cached token for the next 5 minutes. After\n        5 minutes, a new token is fetched from the token service and the cache is updated."
  },
  {
    "code": "def str(self,local=False,ifempty=None):\n        ts = self.get(local)\n        if not ts: return ifempty\n        return ts.strftime('%Y-%m-%d %H:%M:%S')",
    "docstring": "Returns the string representation of the datetime"
  },
  {
    "code": "def single(self):\n        nodes = super(OneOrMore, self).all()\n        if nodes:\n            return nodes[0]\n        raise CardinalityViolation(self, 'none')",
    "docstring": "Fetch one of the related nodes\n\n        :return: Node"
  },
  {
    "code": "def getLogger(name=None, **kwargs):\n    adapter = _LOGGERS.get(name)\n    if not adapter:\n        adapter = KeywordArgumentAdapter(logging.getLogger(name), kwargs)\n        _LOGGERS[name] = adapter\n    return adapter",
    "docstring": "Build a logger with the given name.\n\n    :param name: The name for the logger. This is usually the module\n                 name, ``__name__``.\n    :type name: string"
  },
  {
    "code": "def check_notebooks_for_errors(notebooks_directory):\n    print(\"Checking notebooks in directory {} for errors\".format(notebooks_directory))\n    failed_notebooks_count = 0\n    for file in os.listdir(notebooks_directory):\n        if file.endswith(\".ipynb\"):\n            print(\"Checking notebook \" + file)\n            full_file_path = os.path.join(notebooks_directory, file)\n            output, errors = run_notebook(full_file_path)\n            if errors is not None and len(errors) > 0:\n                failed_notebooks_count += 1\n                print(\"Errors in notebook \" + file)\n                print(errors)\n    if failed_notebooks_count == 0:\n        print(\"No errors found in notebooks under \" + notebooks_directory)",
    "docstring": "Evaluates all notebooks in given directory and prints errors, if any"
  },
  {
    "code": "def utc_datetime_and_leap_second(self):\n        year, month, day, hour, minute, second = self._utc_tuple(\n            _half_millisecond)\n        second, fraction = divmod(second, 1.0)\n        second = second.astype(int)\n        leap_second = second // 60\n        second -= leap_second\n        milli = (fraction * 1000).astype(int) * 1000\n        if self.shape:\n            utcs = [utc] * self.shape[0]\n            argsets = zip(year, month, day, hour, minute, second, milli, utcs)\n            dt = array([datetime(*args) for args in argsets])\n        else:\n            dt = datetime(year, month, day, hour, minute, second, milli, utc)\n        return dt, leap_second",
    "docstring": "Convert to a Python ``datetime`` in UTC, plus a leap second value.\n\n        Convert this time to a `datetime`_ object and a leap second::\n\n            dt, leap_second = t.utc_datetime_and_leap_second()\n\n        If the third-party `pytz`_ package is available, then its\n        ``utc`` timezone will be used as the timezone of the return\n        value.  Otherwise, Skyfield uses its own ``utc`` timezone.\n\n        The leap second value is provided because a Python ``datetime``\n        can only number seconds ``0`` through ``59``, but leap seconds\n        have a designation of at least ``60``.  The leap second return\n        value will normally be ``0``, but will instead be ``1`` if the\n        date and time are a UTC leap second.  Add the leap second value\n        to the ``second`` field of the ``datetime`` to learn the real\n        name of the second.\n\n        If this time is an array, then an array of ``datetime`` objects\n        and an array of leap second integers is returned, instead of a\n        single value each."
  },
  {
    "code": "def get_quoted_foreign_columns(self, platform):\n        columns = []\n        for column in self._foreign_column_names.values():\n            columns.append(column.get_quoted_name(platform))\n        return columns",
    "docstring": "Returns the quoted representation of the referenced table column names\n        the foreign key constraint is associated with.\n\n        But only if they were defined with one or the referenced table column name\n        is a keyword reserved by the platform.\n        Otherwise the plain unquoted value as inserted is returned.\n\n        :param platform: The platform to use for quotation.\n        :type platform: Platform\n\n        :rtype: list"
  },
  {
    "code": "def dict_clip(a_dict, inlude_keys_lst=[]):\n    return dict([[i[0], i[1]] for i in list(a_dict.items()) if i[0] in inlude_keys_lst])",
    "docstring": "returns a new dict with keys not in included in inlude_keys_lst clipped off"
  },
  {
    "code": "def apply_trend_constraint(self, limit, dt, **kwargs):\n        if 'RV monitoring' not in self.constraints:\n            self.constraints.append('RV monitoring')\n        for pop in self.poplist:\n            if not hasattr(pop,'dRV'):\n                continue\n            pop.apply_trend_constraint(limit, dt, **kwargs)\n        self.trend_limit = limit\n        self.trend_dt = dt",
    "docstring": "Applies constraint corresponding to RV trend non-detection to each population\n\n        See :func:`stars.StarPopulation.apply_trend_constraint`;\n        all arguments passed to that function for each population."
  },
  {
    "code": "def warning(cls, name, message, *args):\n        cls.getLogger(name).warning(message, *args)",
    "docstring": "Convenience function to log a message at the WARNING level.\n\n        :param name:    The name of the logger instance in the VSG namespace (VSG.<name>)\n        :param message: A message format string.\n        :param args:    The arguments that are are merged into msg using the string formatting operator.\n        :..note:        The native logger's `kwargs` are not used in this function."
  },
  {
    "code": "def register_event(self, event_name, event_level, message):\n        self.events[event_name] = (event_level, message)",
    "docstring": "Registers an event so that it can be logged later."
  },
  {
    "code": "def assert_conditions(self):\n        self.assert_condition_md5()\n        etag = self.clean_etag(self.call_method('get_etag'))\n        self.response.last_modified = self.call_method('get_last_modified')\n        self.assert_condition_etag()\n        self.assert_condition_last_modified()",
    "docstring": "Handles various HTTP conditions and raises HTTP exceptions to\n        abort the request.\n\n            - Content-MD5 request header must match the MD5 hash of the full\n              input (:func:`assert_condition_md5`).\n            - If-Match and If-None-Match etags are checked against the ETag of\n              this resource (:func:`assert_condition_etag`).\n            - If-Modified-Since and If-Unmodified-Since are checked against\n              the modification date of this resource\n              (:func:`assert_condition_last_modified`).\n\n        .. todo:: Return a 501 exception when any Content-* headers have been\n                  set in the request. (See :rfc:`2616`, section 9.6)"
  },
  {
    "code": "def read(self, size = -1):\n\t\tif size < -1:\n\t\t\traise Exception('You shouldnt be doing this')\n\t\tif size == -1:\n\t\t\tt = self.current_segment.remaining_len(self.current_position)\n\t\t\tif not t:\n\t\t\t\treturn None\n\t\t\told_new_pos = self.current_position\n\t\t\tself.current_position = self.current_segment.end_address\n\t\t\treturn self.current_segment.data[old_new_pos - self.current_segment.start_address:]\n\t\tt = self.current_position + size\n\t\tif not self.current_segment.inrange(t):\n\t\t\traise Exception('Would read over segment boundaries!')\n\t\told_new_pos = self.current_position\n\t\tself.current_position = t\t\t\n\t\treturn self.current_segment.data[old_new_pos - self.current_segment.start_address :t - self.current_segment.start_address]",
    "docstring": "Returns data bytes of size size from the current segment. If size is -1 it returns all the remaining data bytes from memory segment"
  },
  {
    "code": "def _no_proxy(method):\n        @wraps(method)\n        def wrapper(self, *args, **kwargs):\n            notproxied = _oga(self, \"__notproxied__\")\n            _osa(self, \"__notproxied__\", True)\n            try:\n                return method(self, *args, **kwargs)\n            finally:\n                _osa(self, \"__notproxied__\", notproxied)\n        return wrapper",
    "docstring": "Returns a wrapped version of `method`, such that proxying is turned off\n        during the method call."
  },
  {
    "code": "def calc_path_and_create_folders(folder, import_path):\n    file_path = abspath(path_join(folder, import_path[:import_path.rfind(\".\")].replace(\".\", folder_seperator) + \".py\"))\n    mkdir_p(dirname(file_path))\n    return file_path",
    "docstring": "calculate the path and create the needed folders"
  },
  {
    "code": "def get_model(is_netfree=False, without_reset=False, seeds=None, effective=False):\n    try:\n        if seeds is not None or is_netfree:\n            m = ecell4_base.core.NetfreeModel()\n        else:\n            m = ecell4_base.core.NetworkModel()\n        for sp in SPECIES_ATTRIBUTES:\n            m.add_species_attribute(sp)\n        for rr in REACTION_RULES:\n            m.add_reaction_rule(rr)\n        if not without_reset:\n            reset_model()\n        if seeds is not None:\n            return m.expand(seeds)\n        if isinstance(m, ecell4_base.core.NetfreeModel):\n            m.set_effective(effective)\n    except Exception as e:\n        reset_model()\n        raise e\n    return m",
    "docstring": "Generate a model with parameters in the global scope, ``SPECIES_ATTRIBUTES``\n    and ``REACTIONRULES``.\n\n    Parameters\n    ----------\n    is_netfree : bool, optional\n        Return ``NetfreeModel`` if True, and ``NetworkModel`` if else.\n        Default is False.\n    without_reset : bool, optional\n        Do not reset the global variables after the generation if True.\n        Default is False.\n    seeds : list, optional\n        A list of seed ``Species`` for expanding the model.\n        If this is not None, generate a ``NetfreeModel`` once, and return a\n        ``NetworkModel``, which is an expanded form of that with the given seeds.\n        Default is None.\n    effective : bool, optional\n        See ``NetfreeModel.effective`` and ``Netfree.set_effective``.\n        Only meaningfull with option ``is_netfree=True``.\n        Default is False\n\n    Returns\n    -------\n    model : NetworkModel, NetfreeModel"
  },
  {
    "code": "def from_list(cls, database, key, data, clear=False):\n        arr = cls(database, key)\n        if clear:\n            arr.clear()\n        arr.extend(data)\n        return arr",
    "docstring": "Create and populate an Array object from a data dictionary."
  },
  {
    "code": "def read_datafiles(files, dtype, column):\n    pha = []\n    pha_fpi = []\n    for filename, filetype in zip(files, dtype):\n        if filetype == 'cov':\n            cov = load_cov(filename)\n        elif filetype == 'mag':\n            mag = load_rho(filename, column)\n        elif filetype == 'pha':\n            pha = load_rho(filename, 2)\n        elif filetype == 'pha_fpi':\n            pha_fpi = load_rho(filename, 2)\n    return cov, mag, pha, pha_fpi",
    "docstring": "Load the datafiles and return cov, mag, phase and fpi phase values."
  },
  {
    "code": "def report(data):\n    work_dir = dd.get_work_dir(data[0][0])\n    out_dir = op.join(work_dir, \"report\")\n    safe_makedir(out_dir)\n    summary_file = op.join(out_dir, \"summary.csv\")\n    with file_transaction(summary_file) as out_tx:\n        with open(out_tx, 'w') as out_handle:\n            out_handle.write(\"sample_id,%s\\n\" % _guess_header(data[0][0]))\n            for sample in data:\n                info = sample[0]\n                group = _guess_group(info)\n                files = info[\"seqbuster\"] if \"seqbuster\" in info else \"None\"\n                out_handle.write(\",\".join([dd.get_sample_name(info),\n                                           group]) + \"\\n\")\n    _modify_report(work_dir, out_dir)\n    return summary_file",
    "docstring": "Create a Rmd report for small RNAseq analysis"
  },
  {
    "code": "def cancel_signature_request(self, signature_request_id):\n        request = self._get_request()\n        request.post(url=self.SIGNATURE_REQUEST_CANCEL_URL + signature_request_id, get_json=False)",
    "docstring": "Cancels a SignatureRequest\n\n        Cancels a SignatureRequest. After canceling, no one will be able to sign\n        or access the SignatureRequest or its documents. Only the requester can\n        cancel and only before everyone has signed.\n\n        Args:\n\n            signing_request_id (str): The id of the signature request to cancel\n\n        Returns:\n            None"
  },
  {
    "code": "def do_move_to(self, element, decl, pseudo):\n        target = serialize(decl.value).strip()\n        step = self.state[self.state['current_step']]\n        elem = self.current_target().tree\n        actions = step['actions']\n        for pos, action in enumerate(reversed(actions)):\n            if action[0] == 'move' and action[1] == elem:\n                target_index = - pos - 1\n                actions[target_index:] = actions[target_index+1:]\n                break\n        _, valstep = self.lookup('pending', target)\n        if not valstep:\n            step['pending'][target] = [('move', elem)]\n        else:\n            self.state[valstep]['pending'][target].append(('move', elem))",
    "docstring": "Implement move-to declaration."
  },
  {
    "code": "def is_obtuse(p1, v, p2):\n    p1x = p1[:,1]\n    p1y = p1[:,0]\n    p2x = p2[:,1]\n    p2y = p2[:,0]\n    vx = v[:,1]\n    vy = v[:,0]\n    Dx = vx - p2x\n    Dy = vy - p2y\n    Dvp1x = p1x - vx\n    Dvp1y = p1y - vy\n    return Dvp1x * Dx + Dvp1y * Dy > 0",
    "docstring": "Determine whether the angle, p1 - v - p2 is obtuse\n    \n    p1 - N x 2 array of coordinates of first point on edge\n    v - N x 2 array of vertex coordinates\n    p2 - N x 2 array of coordinates of second point on edge\n    \n    returns vector of booleans"
  },
  {
    "code": "def discover_handler_classes(handlers_package):\n    if handlers_package is None:\n        return\n    sys.path.insert(0, os.getcwd())\n    package = import_module(handlers_package)\n    if hasattr(package, '__path__'):\n        for _, modname, _ in pkgutil.iter_modules(package.__path__):\n            import_module('{package}.{module}'.format(package=package.__name__, module=modname))\n    return registered_handlers",
    "docstring": "Looks for handler classes within handler path module.\n\n    Currently it's not looking deep into nested module.\n\n    :param handlers_package: module path to handlers\n    :type handlers_package: string\n    :return: list of handler classes"
  },
  {
    "code": "def track_change(self, instance, resolution_level=0):\n        tobj = self.objects[id(instance)]\n        tobj.set_resolution_level(resolution_level)",
    "docstring": "Change tracking options for the already tracked object 'instance'.\n        If instance is not tracked, a KeyError will be raised."
  },
  {
    "code": "def default_logging(grab_log=None,\n                    network_log=None,\n                    level=logging.DEBUG, mode='a',\n                    propagate_network_logger=False):\n    logging.basicConfig(level=level)\n    network_logger = logging.getLogger('grab.network')\n    network_logger.propagate = propagate_network_logger\n    if network_log:\n        hdl = logging.FileHandler(network_log, mode)\n        network_logger.addHandler(hdl)\n        network_logger.setLevel(level)\n    grab_logger = logging.getLogger('grab')\n    if grab_log:\n        hdl = logging.FileHandler(grab_log, mode)\n        grab_logger.addHandler(hdl)\n        grab_logger.setLevel(level)",
    "docstring": "Customize logging output to display all log messages\n    except grab network logs.\n\n    Redirect grab network logs into file."
  },
  {
    "code": "def get_current_url(request, ignore_params=None):\n    if ignore_params is None:\n        ignore_params = set()\n    protocol = u'https' if request.is_secure() else u\"http\"\n    service_url = u\"%s://%s%s\" % (protocol, request.get_host(), request.path)\n    if request.GET:\n        params = copy_params(request.GET, ignore_params)\n        if params:\n            service_url += u\"?%s\" % urlencode(params)\n    return service_url",
    "docstring": "Giving a django request, return the current http url, possibly ignoring some GET parameters\n\n        :param django.http.HttpRequest request: The current request object.\n        :param set ignore_params: An optional set of GET parameters to ignore\n        :return: The URL of the current page, possibly omitting some parameters from\n            ``ignore_params`` in the querystring.\n        :rtype: unicode"
  },
  {
    "code": "def shell_sqlalchemy(session: SqlalchemySession, backend: ShellBackend):\n    namespace = {\n        'session': session\n    }\n    namespace.update(backend.get_namespace())\n    embed(user_ns=namespace, header=backend.header)",
    "docstring": "This command includes SQLAlchemy DB Session"
  },
  {
    "code": "def _FlushCache(cls, format_categories):\n    if definitions.FORMAT_CATEGORY_ARCHIVE in format_categories:\n      cls._archive_remainder_list = None\n      cls._archive_scanner = None\n      cls._archive_store = None\n    if definitions.FORMAT_CATEGORY_COMPRESSED_STREAM in format_categories:\n      cls._compressed_stream_remainder_list = None\n      cls._compressed_stream_scanner = None\n      cls._compressed_stream_store = None\n    if definitions.FORMAT_CATEGORY_FILE_SYSTEM in format_categories:\n      cls._file_system_remainder_list = None\n      cls._file_system_scanner = None\n      cls._file_system_store = None\n    if definitions.FORMAT_CATEGORY_STORAGE_MEDIA_IMAGE in format_categories:\n      cls._storage_media_image_remainder_list = None\n      cls._storage_media_image_scanner = None\n      cls._storage_media_image_store = None\n    if definitions.FORMAT_CATEGORY_VOLUME_SYSTEM in format_categories:\n      cls._volume_system_remainder_list = None\n      cls._volume_system_scanner = None\n      cls._volume_system_store = None",
    "docstring": "Flushes the cached objects for the specified format categories.\n\n    Args:\n      format_categories (set[str]): format categories."
  },
  {
    "code": "def capture(self, event_type, data=None, date=None, time_spent=None,\n                extra=None, stack=None, tags=None, sample_rate=None,\n                **kwargs):\n        if not self.is_enabled():\n            return\n        exc_info = kwargs.get('exc_info')\n        if exc_info is not None:\n            if self.skip_error_for_logging(exc_info):\n                return\n            elif not self.should_capture(exc_info):\n                self.logger.info(\n                    'Not capturing exception due to filters: %s', exc_info[0],\n                    exc_info=sys.exc_info())\n                return\n            self.record_exception_seen(exc_info)\n        data = self.build_msg(\n            event_type, data, date, time_spent, extra, stack, tags=tags,\n            **kwargs)\n        if sample_rate is None:\n            sample_rate = self.sample_rate\n        if self._random.random() < sample_rate:\n            self.send(**data)\n        self._local_state.last_event_id = data['event_id']\n        return data['event_id']",
    "docstring": "Captures and processes an event and pipes it off to SentryClient.send.\n\n        To use structured data (interfaces) with capture:\n\n        >>> capture('raven.events.Message', message='foo', data={\n        >>>     'request': {\n        >>>         'url': '...',\n        >>>         'data': {},\n        >>>         'query_string': '...',\n        >>>         'method': 'POST',\n        >>>     },\n        >>>     'logger': 'logger.name',\n        >>> }, extra={\n        >>>     'key': 'value',\n        >>> })\n\n        The finalized ``data`` structure contains the following (some optional)\n        builtin values:\n\n        >>> {\n        >>>     # the culprit and version information\n        >>>     'culprit': 'full.module.name', # or /arbitrary/path\n        >>>\n        >>>     # all detectable installed modules\n        >>>     'modules': {\n        >>>         'full.module.name': 'version string',\n        >>>     },\n        >>>\n        >>>     # arbitrary data provided by user\n        >>>     'extra': {\n        >>>         'key': 'value',\n        >>>     }\n        >>> }\n\n        :param event_type: the module path to the Event class. Builtins can use\n                           shorthand class notation and exclude the full module\n                           path.\n        :param data: the data base, useful for specifying structured data\n                           interfaces. Any key which contains a '.' will be\n                           assumed to be a data interface.\n        :param date: the datetime of this event\n        :param time_spent: a integer value representing the duration of the\n                           event (in milliseconds)\n        :param extra: a dictionary of additional standard metadata\n        :param stack: a stacktrace for the event\n        :param tags: dict of extra tags\n        :param sample_rate: a float in the range [0, 1] to sample this message\n        :return: a 32-length string identifying this event"
  },
  {
    "code": "def prevmonday(num):\n    today = get_today()\n    lastmonday = today - timedelta(days=today.weekday(), weeks=num)\n    return lastmonday",
    "docstring": "Return unix SECOND timestamp of \"num\" mondays ago"
  },
  {
    "code": "def _load_physical_network_mappings(self, phys_net_vswitch_mappings):\n        for mapping in phys_net_vswitch_mappings:\n            parts = mapping.split(':')\n            if len(parts) != 2:\n                LOG.debug('Invalid physical network mapping: %s', mapping)\n            else:\n                pattern = re.escape(parts[0].strip()).replace('\\\\*', '.*')\n                pattern = pattern + '$'\n                vswitch = parts[1].strip()\n                self._physical_network_mappings[pattern] = vswitch",
    "docstring": "Load all the information regarding the physical network."
  },
  {
    "code": "def _add_current_quay_tag(repo, container_tags):\n    if ':' in repo:\n        return repo, container_tags\n    try:\n        latest_tag = container_tags[repo]\n    except KeyError:\n        repo_id = repo[repo.find('/') + 1:]\n        tags = requests.request(\"GET\", \"https://quay.io/api/v1/repository/\" + repo_id).json()[\"tags\"]\n        latest_tag = None\n        latest_modified = None\n        for tag, info in tags.items():\n            if latest_tag:\n                if (dateutil.parser.parse(info['last_modified']) > dateutil.parser.parse(latest_modified)\n                      and tag != 'latest'):\n                    latest_modified = info['last_modified']\n                    latest_tag = tag\n            else:\n                latest_modified = info['last_modified']\n                latest_tag = tag\n        container_tags[repo] = str(latest_tag)\n    latest_pull = repo + ':' + str(latest_tag)\n    return latest_pull, container_tags",
    "docstring": "Lookup the current quay tag for the repository, adding to repo string.\n\n    Enables generation of CWL explicitly tied to revisions."
  },
  {
    "code": "def monitor_deletion():\n    monitors = {}\n    def set_deleted(x):\n        def _(weakref):\n            del monitors[x]\n        return _\n    def monitor(item, name):\n        monitors[name] = ref(item, set_deleted(name))\n    def is_alive(name):\n        return monitors.get(name, None) is not None\n    return monitor, is_alive",
    "docstring": "Function for checking for correct deletion of weakref-able objects.\n\n    Example usage::\n\n        monitor, is_alive = monitor_deletion()\n        obj = set()\n        monitor(obj, \"obj\")\n        assert is_alive(\"obj\") # True because there is a ref to `obj` is_alive\n        del obj\n        assert not is_alive(\"obj\") # True because there `obj` is deleted"
  },
  {
    "code": "def splitkeyurl(url):\n    key = url[-22:]\n    urlid = url[-34:-24]\n    service = url[:-43]\n    return service, urlid, key",
    "docstring": "Splits a Send url into key, urlid and 'prefix' for the Send server\n       Should handle any hostname, but will brake on key & id length changes"
  },
  {
    "code": "def guess_file_name_stream_type_header(args):\n    ftype = None\n    fheader = None\n    if isinstance(args, (tuple, list)):\n        if len(args) == 2:\n            fname, fstream = args\n        elif len(args) == 3:\n            fname, fstream, ftype = args\n        else:\n            fname, fstream, ftype, fheader = args\n    else:\n        fname, fstream = guess_filename_stream(args)\n        ftype = guess_content_type(fname)\n    if isinstance(fstream, (str, bytes, bytearray)):\n        fdata = fstream\n    else:\n        fdata = fstream.read()\n    return fname, fdata, ftype, fheader",
    "docstring": "Guess filename, file stream, file type, file header from args.\n\n    :param args: may be string (filepath), 2-tuples (filename, fileobj), 3-tuples (filename, fileobj,\n    contentype) or 4-tuples (filename, fileobj, contentype, custom_headers).\n    :return: filename, file stream, file type, file header"
  },
  {
    "code": "def sortJobs(jobTypes, options):\n    longforms = {\"med\": \"median\",\n                 \"ave\": \"average\",\n                 \"min\": \"min\",\n                 \"total\": \"total\",\n                 \"max\": \"max\",}\n    sortField = longforms[options.sortField]\n    if (options.sortCategory == \"time\" or\n        options.sortCategory == \"clock\" or\n        options.sortCategory == \"wait\" or\n        options.sortCategory == \"memory\"\n        ):\n        return sorted(\n            jobTypes,\n            key=lambda tag: getattr(tag, \"%s_%s\"\n                                    % (sortField, options.sortCategory)),\n            reverse=options.sortReverse)\n    elif options.sortCategory == \"alpha\":\n        return sorted(\n            jobTypes, key=lambda tag: tag.name,\n            reverse=options.sortReverse)\n    elif options.sortCategory == \"count\":\n        return sorted(jobTypes, key=lambda tag: tag.total_number,\n                      reverse=options.sortReverse)",
    "docstring": "Return a jobTypes all sorted."
  },
  {
    "code": "def has_perm(self, user_obj, perm, obj=None):\n        if not is_authenticated(user_obj):\n            return False\n        change_permission = self.get_full_permission_string('change')\n        delete_permission = self.get_full_permission_string('delete')\n        if obj is None:\n            if self.any_permission:\n                return True\n            if self.change_permission and perm == change_permission:\n                return True\n            if self.delete_permission and perm == delete_permission:\n                return True\n            return False\n        elif user_obj.is_active:\n            if obj == user_obj:\n                if self.any_permission:\n                    return True\n                if (self.change_permission and\n                        perm == change_permission):\n                    return True\n                if (self.delete_permission and\n                        perm == delete_permission):\n                    return True\n        return False",
    "docstring": "Check if user have permission of himself\n\n        If the user_obj is not authenticated, it return ``False``.\n\n        If no object is specified, it return ``True`` when the corresponding\n        permission was specified to ``True`` (changed from v0.7.0).\n        This behavior is based on the django system.\n        https://code.djangoproject.com/wiki/RowLevelPermissions\n\n        If an object is specified, it will return ``True`` if the object is the\n        user.\n        So users can change or delete themselves (you can change this behavior\n        to set ``any_permission``, ``change_permissino`` or\n        ``delete_permission`` attributes of this instance).\n\n        Parameters\n        ----------\n        user_obj : django user model instance\n            A django user model instance which be checked\n        perm : string\n            `app_label.codename` formatted permission string\n        obj : None or django model instance\n            None or django model instance for object permission\n\n        Returns\n        -------\n        boolean\n            Whether the specified user have specified permission (of specified\n            object)."
  },
  {
    "code": "def choose(formatter, value, name, option, format):\n    if not option:\n        return\n    words = format.split('|')\n    num_words = len(words)\n    if num_words < 2:\n        return\n    choices = option.split('|')\n    num_choices = len(choices)\n    if num_words not in (num_choices, num_choices + 1):\n        n = num_choices\n        raise ValueError('specify %d or %d choices' % (n, n + 1))\n    choice = get_choice(value)\n    try:\n        index = choices.index(choice)\n    except ValueError:\n        if num_words == num_choices:\n            raise ValueError('no default choice supplied')\n        index = -1\n    return formatter.format(words[index], value)",
    "docstring": "Adds simple logic to format strings.\n\n    Spec: `{:c[hoose](choice1|choice2|...):word1|word2|...[|default]}`\n\n    Example::\n\n       >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=1)\n       u'one'\n       >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=4)\n       u'other'"
  },
  {
    "code": "def authorize(ctx, public_key, append):\n    wva = get_wva(ctx)\n    http_client = wva.get_http_client()\n    authorized_keys_uri = \"/files/userfs/WEB/python/.ssh/authorized_keys\"\n    authorized_key_contents = public_key\n    if append:\n        try:\n            existing_contents = http_client.get(authorized_keys_uri)\n            authorized_key_contents = \"{}\\n{}\".format(existing_contents, public_key)\n        except WVAHttpNotFoundError:\n            pass\n    http_client.put(authorized_keys_uri, authorized_key_contents)\n    print(\"Public key written to authorized_keys for python user.\")\n    print(\"You should now be able to ssh to the device by doing the following:\")\n    print(\"\")\n    print(\"  $ ssh python@{}\".format(get_root_ctx(ctx).hostname))",
    "docstring": "Enable ssh login as the Python user for the current user\n\nThis command will create an authorized_keys file on the target device\ncontaining the current users public key.  This will allow ssh to\nthe WVA from this machine."
  },
  {
    "code": "def output_snapshot_profile(gandi, profile, output_keys, justify=13):\n    schedules = 'schedules' in output_keys\n    if schedules:\n        output_keys.remove('schedules')\n    output_generic(gandi, profile, output_keys, justify)\n    if schedules:\n        schedule_keys = ['name', 'kept_version']\n        for schedule in profile['schedules']:\n            gandi.separator_line()\n            output_generic(gandi, schedule, schedule_keys, justify)",
    "docstring": "Helper to output a snapshot_profile."
  },
  {
    "code": "def _check_key(self, key):\n        if not len(key) == 2:\n            raise TypeError('invalid key: %r' % key)\n        elif key[1] not in TYPES:\n            raise TypeError('invalid datatype: %s' % key[1])",
    "docstring": "Ensures well-formedness of a key."
  },
  {
    "code": "def iter_events(self, public=False, number=-1, etag=None):\n        path = ['events']\n        if public:\n            path.append('public')\n        url = self._build_url(*path, base_url=self._api)\n        return self._iter(int(number), url, Event, etag=etag)",
    "docstring": "Iterate over events performed by this user.\n\n        :param bool public: (optional), only list public events for the\n            authenticated user\n        :param int number: (optional), number of events to return. Default: -1\n            returns all available events.\n        :param str etag: (optional), ETag from a previous request to the same\n            endpoint\n        :returns: list of :class:`Event <github3.events.Event>`\\ s"
  },
  {
    "code": "def wait_until(what, times=-1):\n    while times:\n        logger.info('Waiting times left %d', times)\n        try:\n            if what() is True:\n                return True\n        except:\n            logger.exception('Wait failed')\n        else:\n            logger.warning('Trial[%d] failed', times)\n        times -= 1\n        time.sleep(1)\n    return False",
    "docstring": "Wait until `what` return True\n\n    Args:\n        what (Callable[bool]): Call `wait()` again and again until it returns True\n        times (int): Maximum times of trials before giving up\n\n    Returns:\n        True if success, False if times threshold reached"
  },
  {
    "code": "def init(textCNN, vocab, model_mode, context, lr):\n    textCNN.initialize(mx.init.Xavier(), ctx=context, force_reinit=True)\n    if model_mode != 'rand':\n        textCNN.embedding.weight.set_data(vocab.embedding.idx_to_vec)\n    if model_mode == 'multichannel':\n        textCNN.embedding_extend.weight.set_data(vocab.embedding.idx_to_vec)\n    if model_mode == 'static' or model_mode == 'multichannel':\n        textCNN.embedding.collect_params().setattr('grad_req', 'null')\n    trainer = gluon.Trainer(textCNN.collect_params(), 'adam', {'learning_rate': lr})\n    return textCNN, trainer",
    "docstring": "Initialize parameters."
  },
  {
    "code": "def item(self):\n        url = self._contentURL\n        return Item(url=self._contentURL,\n                    securityHandler=self._securityHandler,\n                    proxy_url=self._proxy_url,\n                    proxy_port=self._proxy_port,\n                    initalize=True)",
    "docstring": "returns the Item class of an Item"
  },
  {
    "code": "def pending_assignment(self):\n        return {\n            self.partitions[pid].name: [\n                self.brokers[bid].id for bid in self.replicas[pid]\n            ]\n            for pid in set(self.pending_partitions)\n        }",
    "docstring": "Return the pending partition assignment that this state represents."
  },
  {
    "code": "def reset(self):\n        self.alive.value = False\n        qsize = 0\n        try:\n            while True:\n                self.queue.get(timeout=0.1)\n                qsize += 1\n        except QEmptyExcept:\n            pass\n        print(\"Queue size on reset: {}\".format(qsize))\n        for i, p in enumerate(self.proc):\n            p.join()\n        self.proc.clear()",
    "docstring": "Resets the generator by stopping all processes"
  },
  {
    "code": "def _make_property_from_dict(self, property_def: Dict) -> Property:\n        property_hash = hash_dump(property_def)\n        edge_property_model = self.object_cache_property.get(property_hash)\n        if edge_property_model is None:\n            edge_property_model = self.get_property_by_hash(property_hash)\n            if not edge_property_model:\n                property_def['sha512'] = property_hash\n                edge_property_model = Property(**property_def)\n            self.object_cache_property[property_hash] = edge_property_model\n        return edge_property_model",
    "docstring": "Build an edge property from a dictionary."
  },
  {
    "code": "def del_node(self, name, index=None):\n        if isinstance(name, Node):\n            name = name.get_name()\n        if name in self.obj_dict['nodes']:\n            if (index is not None and\n                index < len(self.obj_dict['nodes'][name])):\n                del self.obj_dict['nodes'][name][index]\n                return True\n            else:\n                del self.obj_dict['nodes'][name]\n                return True\n        return False",
    "docstring": "Delete a node from the graph.\n\n        Given a node's name all node(s) with that same name\n        will be deleted if 'index' is not specified or set\n        to None.\n        If there are several nodes with that same name and\n        'index' is given, only the node in that position\n        will be deleted.\n\n        'index' should be an integer specifying the position\n        of the node to delete. If index is larger than the\n        number of nodes with that name, no action is taken.\n\n        If nodes are deleted it returns True. If no action\n        is taken it returns False."
  },
  {
    "code": "def server_args(self, parsed_args):\n        args = {\n            arg: value\n            for arg, value in vars(parsed_args).items()\n            if not arg.startswith('_') and value is not None\n        }\n        args.update(vars(self))\n        return args",
    "docstring": "Return keyword args for Server class."
  },
  {
    "code": "def monitor(self, message, *args, **kws):\n    if self.isEnabledFor(MON):\n        self._log(MON, message, args, **kws)",
    "docstring": "Define a monitoring logger that will be added to Logger\n\n    :param self: The logging object\n    :param message: The logging message\n    :param args: Positional arguments\n    :param kws: Keyword arguments\n    :return:"
  },
  {
    "code": "def create_ecdsap256_key_pair():\n    pub  = ECDSAP256PublicKey()\n    priv = ECDSAP256PrivateKey()\n    rc = _lib.xtt_crypto_create_ecdsap256_key_pair(pub.native, priv.native)\n    if rc == RC.SUCCESS:\n        return (pub, priv)\n    else:\n        raise error_from_code(rc)",
    "docstring": "Create a new ECDSAP256 key pair.\n\n    :returns: a tuple of the public and private keys"
  },
  {
    "code": "def _distance_squared(self, p2: \"Point2\") -> Union[int, float]:\n        return (self[0] - p2[0]) ** 2 + (self[1] - p2[1]) ** 2",
    "docstring": "Function used to not take the square root as the distances will stay proportionally the same. This is to speed up the sorting process."
  },
  {
    "code": "def offsets(self, group=None):\n        if not group:\n            return {\n                'fetch': self.offsets('fetch'),\n                'commit': self.offsets('commit'),\n                'task_done': self.offsets('task_done'),\n                'highwater': self.offsets('highwater')\n            }\n        else:\n            return dict(deepcopy(getattr(self._offsets, group)))",
    "docstring": "Get internal consumer offset values\n\n        Keyword Arguments:\n            group: Either \"fetch\", \"commit\", \"task_done\", or \"highwater\".\n                If no group specified, returns all groups.\n\n        Returns:\n            A copy of internal offsets struct"
  },
  {
    "code": "def ufo_create_background_layer_for_all_glyphs(ufo_font):\n    if \"public.background\" in ufo_font.layers:\n        background = ufo_font.layers[\"public.background\"]\n    else:\n        background = ufo_font.newLayer(\"public.background\")\n    for glyph in ufo_font:\n        if glyph.name not in background:\n            background.newGlyph(glyph.name)",
    "docstring": "Create a background layer for all glyphs in ufo_font if not present to\n    reduce roundtrip differences."
  },
  {
    "code": "def get(self, key, filepath):\n        if not filepath:\n            raise RuntimeError(\"Configuration file not given\")\n        if not self.__check_config_key(key):\n            raise RuntimeError(\"%s parameter does not exists\" % key)\n        if not os.path.isfile(filepath):\n            raise RuntimeError(\"%s config file does not exist\" % filepath)\n        section, option = key.split('.')\n        config = configparser.SafeConfigParser()\n        config.read(filepath)\n        try:\n            option = config.get(section, option)\n            self.display('config.tmpl', key=key, option=option)\n        except (configparser.NoSectionError, configparser.NoOptionError):\n            pass\n        return CMD_SUCCESS",
    "docstring": "Get configuration parameter.\n\n        Reads 'key' configuration parameter from the configuration file given\n        in 'filepath'. Configuration parameter in 'key' must follow the schema\n        <section>.<option> .\n\n        :param key: key to get\n        :param filepath: configuration file"
  },
  {
    "code": "def compare(ctx, commands):\n    mp_pool = multiprocessing.Pool(multiprocessing.cpu_count() * 2)\n    for ip in ctx.obj['hosts']:\n        mp_pool.apply_async(wrap.open_connection, args=(ip,\n                            ctx.obj['conn']['username'],\n                            ctx.obj['conn']['password'],\n                            wrap.compare, [commands],\n                            ctx.obj['out'],\n                            ctx.obj['conn']['connect_timeout'],\n                            ctx.obj['conn']['session_timeout'],\n                            ctx.obj['conn']['port']), callback=write_out)\n    mp_pool.close()\n    mp_pool.join()",
    "docstring": "Run 'show | compare' for set commands.\n\n    @param ctx: The click context paramter, for receiving the object dictionary\n              | being manipulated by other previous functions. Needed by any\n              | function with the @click.pass_context decorator.\n    @type ctx: click.Context\n    @param commands: The Junos set commands that will be put into a candidate\n                   | configuration and used to create the 'show | compare'\n                   | against the running configuration. much like the commands\n                   | parameter for the commit() function, this can be one of\n                   | three things: a string containing a single command, a\n                   | string containing a comma separated list of commands, or\n                   | a string containing a filepath location for a file with\n                   | commands on each line.\n    @type commands: str\n\n    @returns: None. Functions part of click relating to the command group\n            | 'main' do not return anything. Click handles passing context\n            | between the functions and maintaing command order and chaining."
  },
  {
    "code": "def gill_king(mat, eps=1e-16):\n    if not scipy.sparse.issparse(mat):\n        mat = numpy.asfarray(mat)\n    assert numpy.allclose(mat, mat.T)\n    size = mat.shape[0]\n    mat_diag = mat.diagonal()\n    gamma = abs(mat_diag).max()\n    off_diag = abs(mat - numpy.diag(mat_diag)).max()\n    delta = eps*max(gamma + off_diag, 1)\n    beta = numpy.sqrt(max(gamma, off_diag/size, eps))\n    lowtri = _gill_king(mat, beta, delta)\n    return lowtri",
    "docstring": "Gill-King algorithm for modified cholesky decomposition.\n\n    Args:\n        mat (numpy.ndarray):\n            Must be a non-singular and symmetric matrix.  If sparse, the result\n            will also be sparse.\n        eps (float):\n            Error tolerance used in algorithm.\n\n\n    Returns:\n        (numpy.ndarray):\n            Lower triangular Cholesky factor.\n\n    Examples:\n        >>> mat = [[4, 2, 1], [2, 6, 3], [1, 3, -.004]]\n        >>> lowtri = gill_king(mat)\n        >>> print(numpy.around(lowtri, 4))\n        [[2.     0.     0.    ]\n         [1.     2.2361 0.    ]\n         [0.5    1.118  1.2264]]\n        >>> print(numpy.around(numpy.dot(lowtri, lowtri.T), 4))\n        [[4.    2.    1.   ]\n         [2.    6.    3.   ]\n         [1.    3.    3.004]]"
  },
  {
    "code": "def info_section(*tokens: Token, **kwargs: Any) -> None:\n    process_tokens_kwargs = kwargs.copy()\n    process_tokens_kwargs[\"color\"] = False\n    no_color = _process_tokens(tokens, **process_tokens_kwargs)\n    info(*tokens, **kwargs)\n    info(\"-\" * len(no_color), end=\"\\n\\n\")",
    "docstring": "Print an underlined section name"
  },
  {
    "code": "def generate_blob(self, container_name, blob_name, permission=None, \n                        expiry=None, start=None, id=None, ip=None, protocol=None,\n                        cache_control=None, content_disposition=None,\n                        content_encoding=None, content_language=None,\n                        content_type=None):\n        resource_path = container_name + '/' + blob_name\n        sas = _SharedAccessHelper()\n        sas.add_base(permission, expiry, start, ip, protocol)\n        sas.add_id(id)\n        sas.add_resource('b')\n        sas.add_override_response_headers(cache_control, content_disposition, \n                                          content_encoding, content_language, \n                                          content_type)\n        sas.add_resource_signature(self.account_name, self.account_key, 'blob', resource_path)\n        return sas.get_token()",
    "docstring": "Generates a shared access signature for the blob.\n        Use the returned signature with the sas_token parameter of any BlobService.\n\n        :param str container_name:\n            Name of container.\n        :param str blob_name:\n            Name of blob.\n        :param BlobPermissions permission:\n            The permissions associated with the shared access signature. The \n            user is restricted to operations allowed by the permissions.\n            Permissions must be ordered read, write, delete, list.\n            Required unless an id is given referencing a stored access policy \n            which contains this field. This field must be omitted if it has been \n            specified in an associated stored access policy.\n        :param expiry:\n            The time at which the shared access signature becomes invalid. \n            Required unless an id is given referencing a stored access policy \n            which contains this field. This field must be omitted if it has \n            been specified in an associated stored access policy. Azure will always \n            convert values to UTC. If a date is passed in without timezone info, it \n            is assumed to be UTC.\n        :type expiry: date or str\n        :param start:\n            The time at which the shared access signature becomes valid. If \n            omitted, start time for this call is assumed to be the time when the \n            storage service receives the request. Azure will always convert values \n            to UTC. If a date is passed in without timezone info, it is assumed to \n            be UTC.\n        :type start: date or str\n        :param str id:\n            A unique value up to 64 characters in length that correlates to a \n            stored access policy. To create a stored access policy, use \n            set_blob_service_properties.\n        :param str ip:\n            Specifies an IP address or a range of IP addresses from which to accept requests.\n            If the IP address from which the request originates does not match the IP address\n            or address range specified on the SAS token, the request is not authenticated.\n            For example, specifying sip=168.1.5.65 or sip=168.1.5.60-168.1.5.70 on the SAS\n            restricts the request to those IP addresses.\n        :param str protocol:\n            Specifies the protocol permitted for a request made. The default value\n            is https,http. See :class:`~azure.storage.models.Protocol` for possible values.\n        :param str cache_control:\n            Response header value for Cache-Control when resource is accessed\n            using this shared access signature.\n        :param str content_disposition:\n            Response header value for Content-Disposition when resource is accessed\n            using this shared access signature.\n        :param str content_encoding:\n            Response header value for Content-Encoding when resource is accessed\n            using this shared access signature.\n        :param str content_language:\n            Response header value for Content-Language when resource is accessed\n            using this shared access signature.\n        :param str content_type:\n            Response header value for Content-Type when resource is accessed\n            using this shared access signature."
  },
  {
    "code": "def _get_link(element: Element) -> Optional[str]:\n    link = get_text(element, 'link')\n    if link is not None:\n        return link\n    guid = get_child(element, 'guid')\n    if guid is not None and guid.attrib.get('isPermaLink') == 'true':\n        return get_text(element, 'guid')\n    return None",
    "docstring": "Attempt to retrieve item link.\n\n    Use the GUID as a fallback if it is a permalink."
  },
  {
    "code": "def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profile=None,\n                                 **args):\n    args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])\n    try:\n        Params = args['ParameterNameValues']\n    except ValueError as e:\n        raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')\n    while Params:\n        args.update({'ParameterNameValues': Params[:20]})\n        Params = Params[20:]\n        if not _modify_resource(name, name_param='CacheParameterGroupName',\n                                desc='cache parameter group', res_type='cache_parameter_group',\n                                region=region, key=key, keyid=keyid, profile=profile, **args):\n            return False\n    return True",
    "docstring": "Update a cache parameter group in place.\n\n    Note that due to a design limitation in AWS, this function is not atomic -- a maximum of 20\n    params may be modified in one underlying boto call.  This means that if more than 20 params\n    need to be changed, the update is performed in blocks of 20, which in turns means that if a\n    later sub-call fails after an earlier one has succeeded, the overall update will be left\n    partially applied.\n\n    CacheParameterGroupName\n        The name of the cache parameter group to modify.\n\n    ParameterNameValues\n        A [list] of {dicts}, each composed of a parameter name and a value, for the parameter\n        update.  At least one parameter/value pair is required.\n\n    .. code-block:: yaml\n\n        ParameterNameValues:\n        - ParameterName: timeout\n          # Amazon requires ALL VALUES to be strings...\n          ParameterValue: \"30\"\n        - ParameterName: appendonly\n          # The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...\n          ParameterValue: \"yes\"\n\n    Example:\n\n    .. code-block:: bash\n\n        salt myminion boto3_elasticache.modify_cache_parameter_group \\\n                CacheParameterGroupName=myParamGroup \\\n                ParameterNameValues='[ { ParameterName: timeout,\n                                         ParameterValue: \"30\" },\n                                       { ParameterName: appendonly,\n                                         ParameterValue: \"yes\" } ]'"
  },
  {
    "code": "def _assert_transition(self, event):\n        state = self.domain.state()[0]\n        if event not in STATES_MAP[state]:\n            raise RuntimeError(\"State transition %s not allowed\" % event)",
    "docstring": "Asserts the state transition validity."
  },
  {
    "code": "def _unpack_bitmap(bitmap, xenum):\n    unpacked = set()\n    for enval in xenum:\n        if enval.value & bitmap == enval.value:\n            unpacked.add(enval)\n    return unpacked",
    "docstring": "Given an integer bitmap and an enumerated type, build\n    a set that includes zero or more enumerated type values\n    corresponding to the bitmap."
  },
  {
    "code": "def equivalent_vertices(self):\n        level1 = {}\n        for i, row in enumerate(self.vertex_fingerprints):\n            key = row.tobytes()\n            l = level1.get(key)\n            if l is None:\n                l = set([i])\n                level1[key] = l\n            else:\n                l.add(i)\n        level2 = {}\n        for key, vertices in level1.items():\n            for vertex in vertices:\n                level2[vertex] = vertices\n        return level2",
    "docstring": "A dictionary with symmetrically equivalent vertices."
  },
  {
    "code": "def _repr_html_(self, **kwargs):\n        if self._parent is None:\n            self.add_to(Figure())\n            out = self._parent._repr_html_(**kwargs)\n            self._parent = None\n        else:\n            out = self._parent._repr_html_(**kwargs)\n        return out",
    "docstring": "Displays the HTML Map in a Jupyter notebook."
  },
  {
    "code": "def help(self, print_output=True):\n        help_text = self._rpc('help')\n        if print_output:\n            print(help_text)\n        else:\n            return help_text",
    "docstring": "Calls the help RPC, which returns the list of RPC calls available.\n\n        This RPC should normally be used in an interactive console environment\n        where the output should be printed instead of returned. Otherwise,\n        newlines will be escaped, which will make the output difficult to read.\n\n        Args:\n            print_output: A bool for whether the output should be printed.\n\n        Returns:\n            A str containing the help output otherwise None if print_output\n                wasn't set."
  },
  {
    "code": "def load_preset(self):\n        if 'preset' in self.settings.preview:\n            with open(os.path.join(os.path.dirname(__file__), 'presets.yaml')) as f:\n                presets = yaml.load(f.read())\n            if self.settings.preview['preset'] in presets:\n                self.preset = presets[self.settings.preview['preset']]\n            return self.preset",
    "docstring": "Loads preset if it is specified in the .frigg.yml"
  },
  {
    "code": "def acquire(self):\n        while self.size() == 0 or self.size() < self._minsize:\n            _conn = yield from self._create_new_conn()\n            if _conn is None:\n                break\n            self._pool.put_nowait(_conn)\n        conn = None\n        while not conn:\n            _conn = yield from self._pool.get()\n            if _conn.reader.at_eof() or _conn.reader.exception():\n                self._do_close(_conn)\n                conn = yield from self._create_new_conn()\n            else:\n                conn = _conn\n        self._in_use.add(conn)\n        return conn",
    "docstring": "Acquire connection from the pool, or spawn new one\n        if pool maxsize permits.\n\n        :return: ``tuple`` (reader, writer)"
  },
  {
    "code": "def _gen_condition(cls, initial, new_public_keys):\n        try:\n            threshold = len(new_public_keys)\n        except TypeError:\n            threshold = None\n        if isinstance(new_public_keys, list) and len(new_public_keys) > 1:\n            ffill = ThresholdSha256(threshold=threshold)\n            reduce(cls._gen_condition, new_public_keys, ffill)\n        elif isinstance(new_public_keys, list) and len(new_public_keys) <= 1:\n            raise ValueError('Sublist cannot contain single owner')\n        else:\n            try:\n                new_public_keys = new_public_keys.pop()\n            except AttributeError:\n                pass\n            if isinstance(new_public_keys, Fulfillment):\n                ffill = new_public_keys\n            else:\n                ffill = Ed25519Sha256(\n                    public_key=base58.b58decode(new_public_keys))\n        initial.add_subfulfillment(ffill)\n        return initial",
    "docstring": "Generates ThresholdSha256 conditions from a list of new owners.\n\n            Note:\n                This method is intended only to be used with a reduce function.\n                For a description on how to use this method, see\n                :meth:`~.Output.generate`.\n\n            Args:\n                initial (:class:`cryptoconditions.ThresholdSha256`):\n                    A Condition representing the overall root.\n                new_public_keys (:obj:`list` of :obj:`str`|str): A list of new\n                    owners or a single new owner.\n\n            Returns:\n                :class:`cryptoconditions.ThresholdSha256`:"
  },
  {
    "code": "def swarm_init(advertise_addr=str,\n               listen_addr=int,\n               force_new_cluster=bool):\n    try:\n        salt_return = {}\n        __context__['client'].swarm.init(advertise_addr,\n                                         listen_addr,\n                                         force_new_cluster)\n        output = 'Docker swarm has been initialized on {0} ' \\\n                 'and the worker/manager Join token is below'.format(__context__['server_name'])\n        salt_return.update({'Comment': output,\n                            'Tokens': swarm_tokens()})\n    except TypeError:\n        salt_return = {}\n        salt_return.update({'Error': 'Please make sure you are passing advertise_addr, '\n                                     'listen_addr and force_new_cluster correctly.'})\n    return salt_return",
    "docstring": "Initalize Docker on Minion as a Swarm Manager\n\n    advertise_addr\n        The ip of the manager\n\n    listen_addr\n        Listen address used for inter-manager communication,\n        as well as determining the networking interface used\n        for the VXLAN Tunnel Endpoint (VTEP).\n        This can either be an address/port combination in\n        the form 192.168.1.1:4567,\n        or an interface followed by a port number,\n        like eth0:4567\n\n    force_new_cluster\n        Force a new cluster if True is passed\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' swarm.swarm_init advertise_addr='192.168.50.10' listen_addr='0.0.0.0' force_new_cluster=False"
  },
  {
    "code": "def aloha_to_etree(html_source):\n    xml = _tidy2xhtml5(html_source)\n    for i, transform in enumerate(ALOHA2HTML_TRANSFORM_PIPELINE):\n        xml = transform(xml)\n    return xml",
    "docstring": "Converts HTML5 from Aloha editor output to a lxml etree."
  },
  {
    "code": "def get_name(model_id):\n    name = _names.get(model_id)\n    if name is None:\n        name = 'id = %s (no name)' % str(model_id)\n    return name",
    "docstring": "Get the name for a model.\n\n    :returns str: The model's name.  If the id has no associated name, then \"id = {ID} (no name)\" is returned."
  },
  {
    "code": "def splitpath(path):\n    c = []\n    head, tail = os.path.split(path)\n    while tail:\n        c.insert(0, tail)\n        head, tail = os.path.split(head)\n    return c",
    "docstring": "Split a path in its components."
  },
  {
    "code": "def rel_path(filename):\n    return os.path.join(os.getcwd(), os.path.dirname(__file__), filename)",
    "docstring": "Function that gets relative path to the filename"
  },
  {
    "code": "def collect(self, order_ref):\n        try:\n            out = self.client.service.Collect(order_ref)\n        except Error as e:\n            raise get_error_class(e, \"Could not complete Collect call.\")\n        return self._dictify(out)",
    "docstring": "Collect the progress status of the order with the specified\n        order reference.\n\n        :param order_ref: The UUID string specifying which order to\n            collect status from.\n        :type order_ref: str\n        :return: The CollectResponse parsed to a dictionary.\n        :rtype: dict\n        :raises BankIDError: raises a subclass of this error\n                             when error has been returned from server."
  },
  {
    "code": "def _update_rr_ce_entry(self, rec):\n        if rec.rock_ridge is not None and rec.rock_ridge.dr_entries.ce_record is not None:\n            celen = rec.rock_ridge.dr_entries.ce_record.len_cont_area\n            added_block, block, offset = self.pvd.add_rr_ce_entry(celen)\n            rec.rock_ridge.update_ce_block(block)\n            rec.rock_ridge.dr_entries.ce_record.update_offset(offset)\n            if added_block:\n                return self.pvd.logical_block_size()\n        return 0",
    "docstring": "An internal method to update the Rock Ridge CE entry for the given\n        record.\n\n        Parameters:\n         rec - The record to update the Rock Ridge CE entry for (if it exists).\n        Returns:\n         The number of additional bytes needed for this Rock Ridge CE entry."
  },
  {
    "code": "def pipeline(steps, initial=None):\n    def apply(result, step):\n        return step(result)\n    return reduce(apply, steps, initial)",
    "docstring": "Chain results from a list of functions. Inverted reduce.\n\n    :param (function) steps: List of function callbacks\n    :param initial: Starting value for pipeline."
  },
  {
    "code": "def resume_instance(self, paused_info):\n        if not paused_info.get(\"instance_id\"):\n            log.info(\"Instance to stop has no instance id.\")\n            return\n        gce = self._connect()\n        try:\n            request = gce.instances().start(project=self._project_id,\n                                            instance=paused_info[\"instance_id\"],\n                                            zone=self._zone)\n            operation = self._execute_request(request)\n            response = self._wait_until_done(operation)\n            self._check_response(response)\n            return\n        except HttpError as e:\n            log.error(\"Error restarting instance: `%s\", e)\n            raise InstanceError(\"Error restarting instance `%s`\", e)",
    "docstring": "Restarts a paused instance, retaining disk and config.\n\n        :param str instance_id: instance identifier\n        :raises: `InstanceError` if instance cannot be resumed.\n\n        :return: dict - information needed to restart instance."
  },
  {
    "code": "def start_worker(self):\n        if not self.include_rq:\n            return None\n        worker = Worker(queues=self.queues,\n                        connection=self.connection)\n        worker_pid_path = current_app.config.get(\n            \"{}_WORKER_PID\".format(self.config_prefix), 'rl_worker.pid'\n        )\n        try:\n            worker_pid_file = open(worker_pid_path, 'r')\n            worker_pid = int(worker_pid_file.read())\n            print(\"Worker already started with PID=%d\" % worker_pid)\n            worker_pid_file.close()\n            return worker_pid\n        except (IOError, TypeError):\n            self.worker_process = Process(target=worker_wrapper, kwargs={\n                'worker_instance': worker,\n                'pid_path': worker_pid_path\n            })\n            self.worker_process.start()\n            worker_pid_file = open(worker_pid_path, 'w')\n            worker_pid_file.write(\"%d\" % self.worker_process.pid)\n            worker_pid_file.close()\n            print(\"Start a worker process with PID=%d\" %\n                  self.worker_process.pid)\n            return self.worker_process.pid",
    "docstring": "Trigger new process as a RQ worker."
  },
  {
    "code": "def push_pq(self, tokens):\n        logger.debug(\"Pushing PQ data: %s\" % tokens)\n        bus = self.case.buses[tokens[\"bus_no\"] - 1]\n        bus.p_demand = tokens[\"p\"]\n        bus.q_demand = tokens[\"q\"]",
    "docstring": "Creates and Load object, populates it with data, finds its Bus and\n        adds it."
  },
  {
    "code": "def generate(self, x, **kwargs):\n    assert self.parse_params(**kwargs)\n    labels, _nb_classes = self.get_or_guess_labels(x, kwargs)\n    return fgm(\n        x,\n        self.model.get_logits(x),\n        y=labels,\n        eps=self.eps,\n        ord=self.ord,\n        clip_min=self.clip_min,\n        clip_max=self.clip_max,\n        targeted=(self.y_target is not None),\n        sanity_checks=self.sanity_checks)",
    "docstring": "Returns the graph for Fast Gradient Method adversarial examples.\n\n    :param x: The model's symbolic inputs.\n    :param kwargs: See `parse_params`"
  },
  {
    "code": "def dependencies(self, deps_dict):\n        try:\n            import pygraphviz as pgv\n        except ImportError:\n            graph_easy, comma = \"\", \"\"\n            if (self.image == \"ascii\" and\n                    not os.path.isfile(\"/usr/bin/graph-easy\")):\n                comma = \",\"\n                graph_easy = \" graph-easy\"\n            print(\"Require 'pygraphviz{0}{1}': Install with 'slpkg -s sbo \"\n                  \"pygraphviz{1}'\".format(comma, graph_easy))\n            raise SystemExit()\n        if self.image != \"ascii\":\n            self.check_file()\n        try:\n            G = pgv.AGraph(deps_dict)\n            G.layout(prog=\"fdp\")\n            if self.image == \"ascii\":\n                G.write(\"{0}.dot\".format(self.image))\n                self.graph_easy()\n            G.draw(self.image)\n        except IOError:\n            raise SystemExit()\n        if os.path.isfile(self.image):\n            print(\"Graph image file '{0}' created\".format(self.image))\n        raise SystemExit()",
    "docstring": "Generate graph file with depenndencies map tree"
  },
  {
    "code": "def save_spectre_plot(self, filename=\"spectre.pdf\", img_format=\"pdf\",\n                          sigma=0.05, step=0.01):\n        d, plt = self.get_spectre_plot(sigma, step)\n        plt.savefig(filename, format=img_format)",
    "docstring": "Save matplotlib plot of the spectre to a file.\n\n        Args:\n            filename: Filename to write to.\n            img_format: Image format to use. Defaults to EPS.\n            sigma: Full width at half maximum in eV for normal functions.\n            step: bin interval in eV"
  },
  {
    "code": "def download_results(self, savedir=None, raw=True, calib=False, index=None):\n        obsids = self.obsids if index is None else [self.obsids[index]]\n        for obsid in obsids:\n            pm = io.PathManager(obsid.img_id, savedir=savedir)\n            pm.basepath.mkdir(exist_ok=True)\n            to_download = []\n            if raw is True:\n                to_download.extend(obsid.raw_urls)\n            if calib is True:\n                to_download.extend(obsid.calib_urls)\n            for url in to_download:\n                basename = Path(url).name\n                print(\"Downloading\", basename)\n                store_path = str(pm.basepath / basename)\n                try:\n                    urlretrieve(url, store_path)\n                except Exception as e:\n                    urlretrieve(url.replace(\"https\", \"http\"), store_path)\n            return str(pm.basepath)",
    "docstring": "Download the previously found and stored Opus obsids.\n\n        Parameters\n        ==========\n        savedir: str or pathlib.Path, optional\n            If the database root folder as defined by the config.ini should not be used,\n            provide a different savedir here. It will be handed to PathManager."
  },
  {
    "code": "def update_floatingip(floatingip_id, port=None, profile=None):\n    conn = _auth(profile)\n    return conn.update_floatingip(floatingip_id, port)",
    "docstring": "Updates a floatingIP\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' neutron.update_floatingip network-name port-name\n\n    :param floatingip_id: ID of floatingIP\n    :param port: ID or name of port, to associate floatingip to `None` or do\n        not specify to disassociate the floatingip (Optional)\n    :param profile: Profile to build on (Optional)\n    :return: Value of updated floating IP information"
  },
  {
    "code": "def chdir(path: str) -> Iterator[None]:\n    curdir = os.getcwd()\n    os.chdir(path)\n    try:\n        yield\n    finally:\n        os.chdir(curdir)",
    "docstring": "Context manager for changing dir and restoring previous workdir after exit."
  },
  {
    "code": "def set_control_output(self, name: str, value: float, *, options: dict=None) -> None:\n        self.__instrument.set_control_output(name, value, options)",
    "docstring": "Set the value of a control asynchronously.\n\n        :param name: The name of the control (string).\n        :param value: The control value (float).\n        :param options: A dict of custom options to pass to the instrument for setting the value.\n\n        Options are:\n            value_type: local, delta, output. output is default.\n            confirm, confirm_tolerance_factor, confirm_timeout: confirm value gets set.\n            inform: True to keep dependent control outputs constant by adjusting their internal values. False is\n            default.\n\n        Default value of confirm is False.\n\n        Default confirm_tolerance_factor is 1.0. A value of 1.0 is the nominal tolerance for that control. Passing a\n        higher tolerance factor (for example 1.5) will increase the permitted error margin and passing lower tolerance\n        factor (for example 0.5) will decrease the permitted error margin and consequently make a timeout more likely.\n        The tolerance factor value 0.0 is a special value which removes all checking and only waits for any change at\n        all and then returns.\n\n        Default confirm_timeout is 16.0 (seconds).\n\n        Raises exception if control with name doesn't exist.\n\n        Raises TimeoutException if confirm is True and timeout occurs.\n\n        .. versionadded:: 1.0\n\n        Scriptable: Yes"
  },
  {
    "code": "def calc_qma_v1(self):\n    der = self.parameters.derived.fastaccess\n    flu = self.sequences.fluxes.fastaccess\n    log = self.sequences.logs.fastaccess\n    for idx in range(der.nmb):\n        flu.qma[idx] = 0.\n        for jdx in range(der.ma_order[idx]):\n            flu.qma[idx] += der.ma_coefs[idx, jdx] * log.login[idx, jdx]",
    "docstring": "Calculate the discharge responses of the different MA processes.\n\n    Required derived parameters:\n      |Nmb|\n      |MA_Order|\n      |MA_Coefs|\n\n    Required log sequence:\n      |LogIn|\n\n    Calculated flux sequence:\n      |QMA|\n\n    Examples:\n\n        Assume there are three response functions, involving one, two and\n        three MA coefficients respectively:\n\n        >>> from hydpy.models.arma import *\n        >>> parameterstep()\n        >>> derived.nmb(3)\n        >>> derived.ma_order.shape = 3\n        >>> derived.ma_order = 1, 2, 3\n        >>> derived.ma_coefs.shape = (3, 3)\n        >>> logs.login.shape = (3, 3)\n        >>> fluxes.qma.shape = 3\n\n        The coefficients of the different MA processes are stored in\n        separate rows of the 2-dimensional parameter `ma_coefs`:\n\n        >>> derived.ma_coefs = ((1.0, nan, nan),\n        ...                     (0.8, 0.2, nan),\n        ...                     (0.5, 0.3, 0.2))\n\n        The \"memory values\" of the different MA processes are defined as\n        follows (one row for each process).  The current values are stored\n        in first column, the values of the last time step in the second\n        column, and so on:\n\n        >>> logs.login = ((1.0, nan, nan),\n        ...               (2.0, 3.0, nan),\n        ...               (4.0, 5.0, 6.0))\n\n        Applying method |calc_qma_v1| is equivalent to calculating the\n        inner product of the different rows of both matrices:\n\n        >>> model.calc_qma_v1()\n        >>> fluxes.qma\n        qma(1.0, 2.2, 4.7)"
  },
  {
    "code": "def pout(*args, **kwargs):\n    if should_msg(kwargs.get(\"groups\", [\"normal\"])):\n        args = indent_text(*args, **kwargs)\n        sys.stderr.write(\"\".join(args))\n        sys.stderr.write(\"\\n\")",
    "docstring": "print to stdout, maintaining indent level"
  },
  {
    "code": "def email_report(job, univ_options):\n    fromadd = \"results@protect.cgl.genomics.ucsc.edu\"\n    msg = MIMEMultipart()\n    msg['From'] = fromadd\n    if  univ_options['mail_to'] is None:\n        return\n    else:\n        msg['To'] = univ_options['mail_to']\n    msg['Subject'] = \"Protect run for sample %s completed successfully.\" % univ_options['patient']\n    body = \"Protect run for sample %s completed successfully.\" % univ_options['patient']\n    msg.attach(MIMEText(body, 'plain'))\n    text = msg.as_string()\n    try:\n        server = smtplib.SMTP('localhost')\n    except socket.error as e:\n        if e.errno == 111:\n            print('No mail utils on this maachine')\n        else:\n            print('Unexpected error while attempting to send an email.')\n        print('Could not send email report')\n    except:\n        print('Could not send email report')\n    else:\n        server.sendmail(fromadd, msg['To'], text)\n        server.quit()",
    "docstring": "Send an email to the user when the run finishes.\n\n    :param dict univ_options: Dict of universal options used by almost all tools"
  },
  {
    "code": "def get_position_p(self):\n        data = []\n        data.append(0x09)\n        data.append(self.servoid)\n        data.append(RAM_READ_REQ)\n        data.append(POSITION_KP_RAM)\n        data.append(BYTE2)\n        send_data(data)\n        rxdata = []\n        try:\n            rxdata = SERPORT.read(13)\n            return (ord(rxdata[10])*256)+(ord(rxdata[9])&0xff)\n        except HerkulexError:\n            raise HerkulexError(\"could not communicate with motors\")",
    "docstring": "Get the P value of the current PID for position"
  },
  {
    "code": "def _gamma_difference_hrf(tr, oversampling=50, time_length=32., onset=0.,\n                          delay=6, undershoot=16., dispersion=1.,\n                          u_dispersion=1., ratio=0.167):\n    from scipy.stats import gamma\n    dt = tr / oversampling\n    time_stamps = np.linspace(0, time_length, np.rint(float(time_length) / dt).astype(np.int))\n    time_stamps -= onset\n    hrf = gamma.pdf(time_stamps, delay / dispersion, dt / dispersion) -\\\n        ratio * gamma.pdf(\n        time_stamps, undershoot / u_dispersion, dt / u_dispersion)\n    hrf /= hrf.sum()\n    return hrf",
    "docstring": "Compute an hrf as the difference of two gamma functions\n\n    Parameters\n    ----------\n\n    tr : float\n        scan repeat time, in seconds\n\n    oversampling : int, optional (default=16)\n        temporal oversampling factor\n\n    time_length : float, optional (default=32)\n        hrf kernel length, in seconds\n\n    onset: float\n        onset time of the hrf\n\n    delay: float, optional\n        delay parameter of the hrf (in s.)\n\n    undershoot: float, optional\n        undershoot parameter of the hrf (in s.)\n\n    dispersion : float, optional\n        dispersion parameter for the first gamma function\n\n    u_dispersion : float, optional\n        dispersion parameter for the second gamma function\n\n    ratio : float, optional\n        ratio of the two gamma components\n\n    Returns\n    -------\n    hrf : array of shape(length / tr * oversampling, dtype=float)\n         hrf sampling on the oversampled time grid"
  },
  {
    "code": "def get_feedback(self, block = True, timeout = None):\n\t\tif self._feedback_greenlet is None:\n\t\t\tself._feedback_greenlet = gevent.spawn(self._feedback_loop)\n\t\treturn self._feedback_queue.get(block = block, timeout = timeout)",
    "docstring": "Gets the next feedback message.\n\n\t\tEach feedback message is a 2-tuple of (timestamp, device_token)."
  },
  {
    "code": "def delete_cookie(self, cookie_name=None):\n        if cookie_name is None:\n            cookie_name = self.default_value['name']\n        return self.create_cookie(\"\", \"\", cookie_name=cookie_name, kill=True)",
    "docstring": "Create a cookie that will immediately expire when it hits the other\n        side.\n\n        :param cookie_name: Name of the cookie\n        :return: A tuple to be added to headers"
  },
  {
    "code": "def randomize(self, period=None):\n\t\tif period is not None:\n\t\t\tself.period = period\n\t\tperm = list(range(self.period))\n\t\tperm_right = self.period - 1\n\t\tfor i in list(perm):\n\t\t\tj = self.randint_function(0, perm_right)\n\t\t\tperm[i], perm[j] = perm[j], perm[i]\n\t\tself.permutation = tuple(perm) * 2",
    "docstring": "Randomize the permutation table used by the noise functions. This\n\t\tmakes them generate a different noise pattern for the same inputs."
  },
  {
    "code": "def rewrite_autodoc(app, what, name, obj, options, lines):\n    try:\n        lines[:] = parse_cartouche_text(lines)\n    except CartoucheSyntaxError as syntax_error:\n        args = syntax_error.args\n        arg0 = args[0] if args else ''\n        arg0 += \" in docstring for {what} {name} :\".format(what=what, name=name)\n        arg0 += \"\\n=== BEGIN DOCSTRING ===\\n{lines}\\n=== END DOCSTRING ===\\n\".format(lines='\\n'.join(lines))\n        syntax_error.args = (arg0,) + args[1:]\n        raise",
    "docstring": "Convert lines from Cartouche to Sphinx format.\n\n    The function to be called by the Sphinx autodoc extension when autodoc\n    has read and processed a docstring. This function modified its\n    ``lines`` argument *in place* replacing Cartouche syntax input into\n    Sphinx reStructuredText output.\n\n    Args:\n        apps: The Sphinx application object.\n\n        what: The type of object which the docstring belongs to. One of\n            'module', 'class', 'exception', 'function', 'method', 'attribute'\n\n        name: The fully qualified name of the object.\n\n        obj: The object itself.\n\n        options: The options given to the directive. An object with attributes\n            ``inherited_members``, ``undoc_members``, ``show_inheritance`` and\n            ``noindex`` that are ``True`` if the flag option of the same name\n            was given to the auto directive.\n\n        lines: The lines of the docstring.  Will be modified *in place*.\n\n    Raises:\n        CartoucheSyntaxError: If the docstring is malformed."
  },
  {
    "code": "def WSGIHandler(self):\n    sdm = werkzeug_wsgi.SharedDataMiddleware(self, {\n        \"/\": config.CONFIG[\"AdminUI.document_root\"],\n    })\n    return werkzeug_wsgi.DispatcherMiddleware(self, {\n        \"/static\": sdm,\n    })",
    "docstring": "Returns GRR's WSGI handler."
  },
  {
    "code": "def read(parser, stream):\n    source = stream() if callable(stream) else stream\n    try:\n        text = source.read()\n        stream_name = getattr(source, 'name', None)\n        try:\n            result = parser(text)\n        except ECMASyntaxError as e:\n            error_name = repr_compat(stream_name or source)\n            raise type(e)('%s in %s' % (str(e), error_name))\n    finally:\n        if callable(stream):\n            source.close()\n    result.sourcepath = stream_name\n    return result",
    "docstring": "Return an AST from the input ES5 stream.\n\n    Arguments\n\n    parser\n        A parser instance.\n    stream\n        Either a stream object or a callable that produces one.  The\n        stream object to read from; its 'read' method will be invoked.\n\n        If a callable was provided, the 'close' method on its return\n        value will be called to close the stream."
  },
  {
    "code": "def is_link(path):\n    if sys.getwindowsversion().major < 6:\n        raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')\n    try:\n        return salt.utils.path.islink(path)\n    except Exception as exc:\n        raise CommandExecutionError(exc)",
    "docstring": "Check if the path is a symlink\n\n    This is only supported on Windows Vista or later.\n\n    Inline with Unix behavior, this function will raise an error if the path\n    is not a symlink, however, the error raised will be a SaltInvocationError,\n    not an OSError.\n\n    Args:\n        path (str): The path to a file or directory\n\n    Returns:\n        bool: True if path is a symlink, otherwise False\n\n    CLI Example:\n\n    .. code-block:: bash\n\n       salt '*' file.is_link /path/to/link"
  },
  {
    "code": "def get_list_filter(self, request):\n        list_filter = super(VersionedAdmin, self).get_list_filter(request)\n        return list(list_filter) + [('version_start_date', DateTimeFilter),\n                                    IsCurrentFilter]",
    "docstring": "Adds versionable custom filtering ability to changelist"
  },
  {
    "code": "def extract_features(self, phrase):\n        words = nltk.word_tokenize(phrase)\n        features = {}\n        for word in words:\n            features['contains(%s)' % word] = (word in words)\n        return features",
    "docstring": "This function will extract features from the phrase being used. \n        Currently, the feature we are extracting are unigrams of the text corpus."
  },
  {
    "code": "async def get_identity_document(client: Client, current_block: dict, pubkey: str) -> Identity:\n    lookup_data = await client(bma.wot.lookup, pubkey)\n    uid = None\n    timestamp = BlockUID.empty()\n    signature = None\n    for result in lookup_data['results']:\n        if result[\"pubkey\"] == pubkey:\n            uids = result['uids']\n            for uid_data in uids:\n                timestamp = BlockUID.from_str(uid_data[\"meta\"][\"timestamp\"])\n                uid = uid_data[\"uid\"]\n                signature = uid_data[\"self\"]\n            return Identity(\n                version=10,\n                currency=current_block['currency'],\n                pubkey=pubkey,\n                uid=uid,\n                ts=timestamp,\n                signature=signature\n            )",
    "docstring": "Get the identity document of the pubkey\n\n    :param client: Client to connect to the api\n    :param current_block: Current block data\n    :param pubkey: UID/Public key\n\n    :rtype: Identity"
  },
  {
    "code": "def load(source):\n    parser = get_xml_parser()\n    return etree.parse(source, parser=parser).getroot()",
    "docstring": "Load OpenCorpora corpus.\n\n    The ``source`` can be any of the following:\n\n    - a file name/path\n    - a file object\n    - a file-like object\n    - a URL using the HTTP or FTP protocol"
  },
  {
    "code": "def defer(self, *args, **kwargs):\n        LOG.debug(\n            '%s on %s (awaitable %s async %s provider %s)',\n            'deferring',\n            self._func,\n            self._is_awaitable,\n            self._is_asyncio_provider,\n            self._concurrency_provider\n        )\n        if self._blocked:\n            raise RuntimeError('Already activated this deferred call by blocking on it')\n        with self._lock:\n            if not self._deferable:\n                func_partial = functools.partial(self._func, *args, **kwargs)\n                self._deferable = (\n                    asyncio.ensure_future(func_partial(), loop=self._concurrency_provider)\n                    if self._is_awaitable else (\n                        self._concurrency_provider.run_in_executor(\n                            func=func_partial,\n                            executor=None\n                        )\n                        if self._is_asyncio_provider else (\n                            self._concurrency_provider.apply_async(func_partial)\n                        )\n                    )\n                )\n        return self._deferable",
    "docstring": "Call the function and immediately return an asynchronous object.\n\n        The calling code will need to check for the result at a later time using:\n\n        In Python 2/3 using ThreadPools - an AsyncResult\n            (https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.AsyncResult)\n\n        In Python 3 using Asyncio - a Future\n            (https://docs.python.org/3/library/asyncio-task.html#future)\n\n        :param args:\n        :param kwargs:\n        :return:"
  },
  {
    "code": "def _bigger(interval1, interval2):\n        if interval2.cardinality > interval1.cardinality:\n            return interval2.copy()\n        return interval1.copy()",
    "docstring": "Return interval with bigger cardinality\n        Refer Section 3.1\n\n        :param interval1: first interval\n        :param interval2: second interval\n        :return: Interval or interval2 whichever has greater cardinality"
  },
  {
    "code": "def get_damage(self, amount: int, target) -> int:\n\t\tif target.immune:\n\t\t\tself.log(\"%r is immune to %s for %i damage\", target, self, amount)\n\t\t\treturn 0\n\t\treturn amount",
    "docstring": "Override to modify the damage dealt to a target from the given amount."
  },
  {
    "code": "def any_hook(*hook_patterns):\n    current_hook = hookenv.hook_name()\n    i_pat = re.compile(r'{([^:}]+):([^}]+)}')\n    hook_patterns = _expand_replacements(i_pat, hookenv.role_and_interface_to_relations, hook_patterns)\n    c_pat = re.compile(r'{((?:[^:,}]+,?)+)}')\n    hook_patterns = _expand_replacements(c_pat, lambda v: v.split(','), hook_patterns)\n    return current_hook in hook_patterns",
    "docstring": "Assert that the currently executing hook matches one of the given patterns.\n\n    Each pattern will match one or more hooks, and can use the following\n    special syntax:\n\n      * ``db-relation-{joined,changed}`` can be used to match multiple hooks\n        (in this case, ``db-relation-joined`` and ``db-relation-changed``).\n      * ``{provides:mysql}-relation-joined`` can be used to match a relation\n        hook by the role and interface instead of the relation name.  The role\n        must be one of ``provides``, ``requires``, or ``peer``.\n      * The previous two can be combined, of course: ``{provides:mysql}-relation-{joined,changed}``"
  },
  {
    "code": "def create_file_chooser_dialog(self, text, parent, name=Gtk.STOCK_OPEN):\n        text = None\n        dialog = Gtk.FileChooserDialog(\n            text, parent,\n            Gtk.FileChooserAction.SELECT_FOLDER,\n            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, name, Gtk.ResponseType.OK)\n        )\n        response = dialog.run()\n        if response == Gtk.ResponseType.OK:\n            text = dialog.get_filename()\n        dialog.destroy()\n        return text",
    "docstring": "Function creates a file chooser dialog with title text"
  },
  {
    "code": "def get_func_info(func):\n    name = func.__name__\n    doc = func.__doc__ or \"\"\n    try:\n        nicename = func.description\n    except AttributeError:\n        if doc:\n            nicename = doc.split('\\n')[0]\n            if len(nicename) > 80:\n                nicename = name\n        else:\n            nicename = name\n    parameters = []\n    try:\n        closure = func.func_closure\n    except AttributeError:\n        closure = func.__closure__\n    try:\n        varnames = func.func_code.co_freevars\n    except AttributeError:\n        varnames = func.__code__.co_freevars\n    if closure:\n        for index, arg in enumerate(closure):\n            if not callable(arg.cell_contents):\n                parameters.append((varnames[index],\n                                   text_type(arg.cell_contents)))\n    return ({\n        \"nicename\": nicename,\n        \"doc\": doc,\n        \"parameters\": parameters,\n        \"name\": name,\n        \"time\": str(datetime.datetime.now()),\n        \"hostname\": socket.gethostname(),\n    })",
    "docstring": "Retrieve a function's information."
  },
  {
    "code": "def update_template(self, template_dict, original_template_path, built_artifacts):\n        original_dir = os.path.dirname(original_template_path)\n        for logical_id, resource in template_dict.get(\"Resources\", {}).items():\n            if logical_id not in built_artifacts:\n                continue\n            artifact_relative_path = os.path.relpath(built_artifacts[logical_id], original_dir)\n            resource_type = resource.get(\"Type\")\n            properties = resource.setdefault(\"Properties\", {})\n            if resource_type == \"AWS::Serverless::Function\":\n                properties[\"CodeUri\"] = artifact_relative_path\n            if resource_type == \"AWS::Lambda::Function\":\n                properties[\"Code\"] = artifact_relative_path\n        return template_dict",
    "docstring": "Given the path to built artifacts, update the template to point appropriate resource CodeUris to the artifacts\n        folder\n\n        Parameters\n        ----------\n        template_dict\n        original_template_path : str\n            Path where the template file will be written to\n\n        built_artifacts : dict\n            Map of LogicalId of a resource to the path where the the built artifacts for this resource lives\n\n        Returns\n        -------\n        dict\n            Updated template"
  },
  {
    "code": "def auto_forward(auto=True):\n    global __auto_forward_state\n    prev = __auto_forward_state\n    __auto_forward_state = auto\n    yield\n    __auto_forward_state = prev",
    "docstring": "Context for dynamic graph execution mode.\n\n    Args:\n        auto (bool): Whether forward computation is executed during a\n            computation graph construction.\n\n    Returns: bool"
  },
  {
    "code": "def set_keepalive(sock, after_idle_sec=1, interval_sec=3, max_fails=5):\n    if hasattr(socket, \"SO_KEEPALIVE\"):\n        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)\n    if hasattr(socket, \"TCP_KEEPIDLE\"):\n        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)\n    if hasattr(socket, \"TCP_KEEPINTVL\"):\n        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)\n    if hasattr(socket, \"TCP_KEEPCNT\"):\n        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails)",
    "docstring": "Set TCP keepalive on an open socket.\n\n    It activates after 1 second (after_idle_sec) of idleness,\n    then sends a keepalive ping once every 3 seconds (interval_sec),\n    and closes the connection after 5 failed ping (max_fails), or 15 seconds"
  },
  {
    "code": "def setup_figure():\n    fig, axes = mplstereonet.subplots(ncols=2, figsize=(20,10))\n    for ax in axes:\n        ax.grid(ls='-')\n        ax.set_longitude_grid_ends(90)\n    return fig, axes",
    "docstring": "Setup the figure and axes"
  },
  {
    "code": "def create_action(self):\n        actions = {}\n        act = QAction('Load Montage...', self)\n        act.triggered.connect(self.load_channels)\n        act.setEnabled(False)\n        actions['load_channels'] = act\n        act = QAction('Save Montage...', self)\n        act.triggered.connect(self.save_channels)\n        act.setEnabled(False)\n        actions['save_channels'] = act\n        self.action = actions",
    "docstring": "Create actions related to channel selection."
  },
  {
    "code": "def show(self):\n        from matplotlib import pyplot as plt\n        if self.already_run:\n            for ref in self.volts.keys():\n                plt.plot(self.t, self.volts[ref], label=ref)\n                plt.title(\"Simulation voltage vs time\")\n                plt.legend()\n                plt.xlabel(\"Time [ms]\")\n                plt.ylabel(\"Voltage [mV]\")\n        else:\n            pynml.print_comment(\"First you have to 'go()' the simulation.\", True)\n        plt.show()",
    "docstring": "Plot the result of the simulation once it's been intialized"
  },
  {
    "code": "def delete_secret_versions(self, path, versions, mount_point=DEFAULT_MOUNT_POINT):\n        if not isinstance(versions, list) or len(versions) == 0:\n            error_msg = 'argument to \"versions\" must be a list containing one or more integers, \"{versions}\" provided.'.format(\n                versions=versions\n            )\n            raise exceptions.ParamValidationError(error_msg)\n        params = {\n            'versions': versions,\n        }\n        api_path = '/v1/{mount_point}/delete/{path}'.format(mount_point=mount_point, path=path)\n        return self._adapter.post(\n            url=api_path,\n            json=params,\n        )",
    "docstring": "Issue a soft delete of the specified versions of the secret.\n\n        This marks the versions as deleted and will stop them from being returned from reads,\n        but the underlying data will not be removed. A delete can be undone using the\n        undelete path.\n\n        Supported methods:\n            POST: /{mount_point}/delete/{path}. Produces: 204 (empty body)\n\n\n        :param path: Specifies the path of the secret to delete. This is specified as part of the URL.\n        :type path: str | unicode\n        :param versions: The versions to be deleted. The versioned data will not be deleted, but it will no longer be\n            returned in normal get requests.\n        :type versions: int\n        :param mount_point: The \"path\" the secret engine was mounted on.\n        :type mount_point: str | unicode\n        :return: The response of the request.\n        :rtype: requests.Response"
  },
  {
    "code": "def prepare_and_execute(self, connection_id, statement_id, sql, max_rows_total=None, first_frame_max_size=None):\n        request = requests_pb2.PrepareAndExecuteRequest()\n        request.connection_id = connection_id\n        request.statement_id = statement_id\n        request.sql = sql\n        if max_rows_total is not None:\n            request.max_rows_total = max_rows_total\n        if first_frame_max_size is not None:\n            request.first_frame_max_size = first_frame_max_size\n        response_data = self._apply(request, 'ExecuteResponse')\n        response = responses_pb2.ExecuteResponse()\n        response.ParseFromString(response_data)\n        return response.results",
    "docstring": "Prepares and immediately executes a statement.\n\n        :param connection_id:\n            ID of the current connection.\n\n        :param statement_id:\n            ID of the statement to prepare.\n\n        :param sql:\n            SQL query.\n\n        :param max_rows_total:\n            The maximum number of rows that will be allowed for this query.\n\n        :param first_frame_max_size:\n            The maximum number of rows that will be returned in the first Frame returned for this query.\n\n        :returns:\n            Result set with the signature of the prepared statement and the first frame data."
  },
  {
    "code": "def get_ccle_mrna(gene_list, cell_lines):\n    gene_list_str = ','.join(gene_list)\n    data = {'cmd': 'getProfileData',\n            'case_set_id': ccle_study + '_mrna',\n            'genetic_profile_id': ccle_study + '_mrna',\n            'gene_list': gene_list_str,\n            'skiprows': -1}\n    df = send_request(**data)\n    mrna_amounts = {cl: {g: [] for g in gene_list} for cl in cell_lines}\n    for cell_line in cell_lines:\n        if cell_line in df.columns:\n            for gene in gene_list:\n                value_cell = df[cell_line][df['COMMON'] == gene]\n                if value_cell.empty:\n                    mrna_amounts[cell_line][gene] = None\n                elif pandas.isnull(value_cell.values[0]):\n                    mrna_amounts[cell_line][gene] = None\n                else:\n                    value = value_cell.values[0]\n                    mrna_amounts[cell_line][gene] = value\n        else:\n            mrna_amounts[cell_line] = None\n    return mrna_amounts",
    "docstring": "Return a dict of mRNA amounts in given genes and cell lines from CCLE.\n\n    Parameters\n    ----------\n    gene_list : list[str]\n        A list of HGNC gene symbols to get mRNA amounts for.\n    cell_lines : list[str]\n        A list of CCLE cell line names to get mRNA amounts for.\n\n    Returns\n    -------\n    mrna_amounts : dict[dict[float]]\n        A dict keyed to cell lines containing a dict keyed to genes\n        containing float"
  },
  {
    "code": "def euclidean_dist(point1, point2):\n    (x1, y1) = point1\n    (x2, y2) = point2\n    return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)",
    "docstring": "Compute the Euclidean distance between two points.\n\n    Parameters\n    ----------\n    point1, point2 : 2-tuples of float\n        The input points.\n\n    Returns\n    -------\n    d : float\n        The distance between the input points.\n\n    Examples\n    --------\n    >>> point1 = (1.0, 2.0)\n    >>> point2 = (4.0, 6.0)  # (3., 4.) away, simplest Pythagorean triangle\n    >>> euclidean_dist(point1, point2)\n    5.0"
  },
  {
    "code": "def stem(self):\n        name = self.name\n        i = name.rfind('.')\n        if 0 < i < len(name) - 1:\n            return name[:i]\n        else:\n            return name",
    "docstring": "The final path component, minus its last suffix."
  },
  {
    "code": "def create(cls, zone_id, record):\n        cls.echo('Creating new zone version')\n        new_version_id = Zone.new(zone_id)\n        cls.echo('Updating zone version')\n        cls.add(zone_id, new_version_id, record)\n        cls.echo('Activation of new zone version')\n        Zone.set(zone_id, new_version_id)\n        return new_version_id",
    "docstring": "Create a new zone version for record."
  },
  {
    "code": "def deserialise(self, element_json: str) -> Element:\n        return self.deserialise_dict(json.loads(element_json))",
    "docstring": "Deserialises the given JSON into an element.\n\n        >>> json = '{\"element\": \"string\", \"content\": \"Hello\"'\n        >>> JSONDeserialiser().deserialise(json)\n        String(content='Hello')"
  },
  {
    "code": "def add_data_item(self, data_item: DataItem) -> None:\n        display_item = data_item._data_item.container.get_display_item_for_data_item(data_item._data_item) if data_item._data_item.container else None\n        if display_item:\n            self.__data_group.append_display_item(display_item)",
    "docstring": "Add a data item to the group.\n\n        :param data_item: The :py:class:`nion.swift.Facade.DataItem` object to add.\n\n        .. versionadded:: 1.0\n\n        Scriptable: Yes"
  },
  {
    "code": "def paginate(self, page=1, perpage=10, category=None):\n        q = db.select(self.table).fields('title', 'slug', 'description', 'html', 'css', 'js',\n                                         'category', 'status', 'comments', 'author', 'created', 'pid')\n        if category:\n            q.condition('category', category)\n        results = (q.limit(perpage).offset((page - 1) * perpage)\n                    .order_by('created', 'DESC').execute())\n        return [self.load(data, self.model) for data in results]",
    "docstring": "Paginate the posts"
  },
  {
    "code": "def __batch_update(self, train_events, test_events, n_epoch):\n        for epoch in range(n_epoch):\n            if n_epoch != 1:\n                np.random.shuffle(train_events)\n            for e in train_events:\n                self.rec.update(e, batch_train=True)\n            MPR = self.__batch_evaluate(test_events)\n            if self.debug:\n                logger.debug('epoch %2d: MPR = %f' % (epoch + 1, MPR))",
    "docstring": "Batch update called by the fitting method.\n\n        Args:\n            train_events (list of Event): Positive training events.\n            test_events (list of Event): Test events.\n            n_epoch (int): Number of epochs for the batch training."
  },
  {
    "code": "def __update_service_status(self, statuscode):\n        if self.__service_status != statuscode:\n            self.__service_status = statuscode\n            self.__send_service_status_to_frontend()",
    "docstring": "Set the internal status of the service object, and notify frontend."
  },
  {
    "code": "def kill_the_system(self, warning: str):\n        log.critical('Kill reason: ' + warning)\n        if self.DEBUG:\n            return\n        try:\n            self.mail_this(warning)\n        except socket.gaierror:\n            current_time = time.localtime()\n            formatted_time = time.strftime('%Y-%m-%d %I:%M:%S%p', current_time)\n            with open(self.config['global']['killer_file'], 'a', encoding='utf-8') as killer_file:\n                killer_file.write('Time: {0}\\nInternet is out.\\n'\n                                  'Failure: {1}\\n\\n'.format(formatted_time, warning))",
    "docstring": "Send an e-mail, and then\n        shut the system down quickly."
  },
  {
    "code": "def write(self, ontol, **args):\n        s = self.render(ontol, **args)\n        if self.outfile is None:\n            print(s)\n        else:\n            f = open(self.outfile, 'w')\n            f.write(s)\n            f.close()",
    "docstring": "Write a `ontology` object"
  },
  {
    "code": "def _check_pos(self, level, *tokens):\n        for record in self.records:\n            if all(record.levelno == level and token in record.message for token in tokens):\n                return\n        level_name = logging.getLevelName(level)\n        msgs = [\"Tokens {} not found in {}, all was logged is...\".format(tokens, level_name)]\n        for record in self.records:\n            msgs.append(\"    {:9s} {!r}\".format(record.levelname, record.message))\n        self.test_instance.fail(\"\\n\".join(msgs))",
    "docstring": "Check if the different tokens were logged in one record, assert by level."
  },
  {
    "code": "def getFile(self, file_xml_uri):\n\t\tfind = re.match('/fmi/xml/cnt/([\\w\\d.-]+)\\.([\\w]+)?-*', file_xml_uri)\n\t\tfile_name = find.group(1)\n\t\tfile_extension = find.group(2)\n\t\tfile_binary = self._doRequest(is_file=True, file_xml_uri=file_xml_uri)\n\t\treturn (file_name, file_extension, file_binary)",
    "docstring": "This will execute cmd to fetch file data from FMServer"
  },
  {
    "code": "def put(self, job, result):\n        \"Perform a job by a member in the pool and return the result.\"\n        self.job.put(job)\n        r = result.get()\n        return r",
    "docstring": "Perform a job by a member in the pool and return the result."
  },
  {
    "code": "def get_auth(host, app_name, database_name):\n    from .hooks import _get_auth_hook\n    return _get_auth_hook(host, app_name, database_name)",
    "docstring": "Authentication hook to allow plugging in custom authentication credential providers"
  },
  {
    "code": "def get_algorithm(self, name):\n        name = adapt_name_for_rest(name)\n        url = '/mdb/{}/algorithms{}'.format(self._instance, name)\n        response = self._client.get_proto(url)\n        message = mdb_pb2.AlgorithmInfo()\n        message.ParseFromString(response.content)\n        return Algorithm(message)",
    "docstring": "Gets a single algorithm by its unique name.\n\n        :param str name: Either a fully-qualified XTCE name or an alias in the\n                         format ``NAMESPACE/NAME``.\n        :rtype: .Algorithm"
  },
  {
    "code": "def build(ctx, inputs, output, cs):\n    click.echo('chemdataextractor.dict.build')\n    dt = DictionaryTagger(lexicon=ChemLexicon(), case_sensitive=cs)\n    names = []\n    for input in inputs:\n        for line in input:\n            tokens = line.split()\n            names.append(tokens)\n    dt.build(words=names)\n    dt.save(output)",
    "docstring": "Build chemical name dictionary."
  },
  {
    "code": "def deleteuser(self, user_id):\n        deleted = self.delete_user(user_id)\n        if deleted is False:\n            return False\n        else:\n            return True",
    "docstring": "Deletes a user. Available only for administrators.\n        This is an idempotent function, calling this function for a non-existent user id\n        still returns a status code 200 OK.\n        The JSON response differs if the user was actually deleted or not.\n        In the former the user is returned and in the latter not.\n\n        .. warning:: Warning this is being deprecated please use :func:`gitlab.Gitlab.delete_user`\n\n        :param user_id: The ID of the user\n        :return: True if it deleted, False if it couldn't"
  },
  {
    "code": "def hexbin(self, x, y, C=None, reduce_C_function=None, gridsize=None,\n               **kwds):\n        if reduce_C_function is not None:\n            kwds['reduce_C_function'] = reduce_C_function\n        if gridsize is not None:\n            kwds['gridsize'] = gridsize\n        return self(kind='hexbin', x=x, y=y, C=C, **kwds)",
    "docstring": "Generate a hexagonal binning plot.\n\n        Generate a hexagonal binning plot of `x` versus `y`. If `C` is `None`\n        (the default), this is a histogram of the number of occurrences\n        of the observations at ``(x[i], y[i])``.\n\n        If `C` is specified, specifies values at given coordinates\n        ``(x[i], y[i])``. These values are accumulated for each hexagonal\n        bin and then reduced according to `reduce_C_function`,\n        having as default the NumPy's mean function (:meth:`numpy.mean`).\n        (If `C` is specified, it must also be a 1-D sequence\n        of the same length as `x` and `y`, or a column label.)\n\n        Parameters\n        ----------\n        x : int or str\n            The column label or position for x points.\n        y : int or str\n            The column label or position for y points.\n        C : int or str, optional\n            The column label or position for the value of `(x, y)` point.\n        reduce_C_function : callable, default `np.mean`\n            Function of one argument that reduces all the values in a bin to\n            a single number (e.g. `np.mean`, `np.max`, `np.sum`, `np.std`).\n        gridsize : int or tuple of (int, int), default 100\n            The number of hexagons in the x-direction.\n            The corresponding number of hexagons in the y-direction is\n            chosen in a way that the hexagons are approximately regular.\n            Alternatively, gridsize can be a tuple with two elements\n            specifying the number of hexagons in the x-direction and the\n            y-direction.\n        **kwds\n            Additional keyword arguments are documented in\n            :meth:`DataFrame.plot`.\n\n        Returns\n        -------\n        matplotlib.AxesSubplot\n            The matplotlib ``Axes`` on which the hexbin is plotted.\n\n        See Also\n        --------\n        DataFrame.plot : Make plots of a DataFrame.\n        matplotlib.pyplot.hexbin : Hexagonal binning plot using matplotlib,\n            the matplotlib function that is used under the hood.\n\n        Examples\n        --------\n        The following examples are generated with random data from\n        a normal distribution.\n\n        .. plot::\n            :context: close-figs\n\n            >>> n = 10000\n            >>> df = pd.DataFrame({'x': np.random.randn(n),\n            ...                    'y': np.random.randn(n)})\n            >>> ax = df.plot.hexbin(x='x', y='y', gridsize=20)\n\n        The next example uses `C` and `np.sum` as `reduce_C_function`.\n        Note that `'observations'` values ranges from 1 to 5 but the result\n        plot shows values up to more than 25. This is because of the\n        `reduce_C_function`.\n\n        .. plot::\n            :context: close-figs\n\n            >>> n = 500\n            >>> df = pd.DataFrame({\n            ...     'coord_x': np.random.uniform(-3, 3, size=n),\n            ...     'coord_y': np.random.uniform(30, 50, size=n),\n            ...     'observations': np.random.randint(1,5, size=n)\n            ...     })\n            >>> ax = df.plot.hexbin(x='coord_x',\n            ...                     y='coord_y',\n            ...                     C='observations',\n            ...                     reduce_C_function=np.sum,\n            ...                     gridsize=10,\n            ...                     cmap=\"viridis\")"
  },
  {
    "code": "def commit_comment(self, comment_id):\n        url = self._build_url('comments', str(comment_id), base_url=self._api)\n        json = self._json(self._get(url), 200)\n        return RepoComment(json, self) if json else None",
    "docstring": "Get a single commit comment.\n\n        :param int comment_id: (required), id of the comment used by GitHub\n        :returns: :class:`RepoComment <github3.repos.comment.RepoComment>` if\n            successful, otherwise None"
  },
  {
    "code": "def join(self, delimiter=' ', overlap_threshold=0.1):\n        sorted_by_start = sorted(self.labels)\n        concat_values = []\n        last_label_end = None\n        for label in sorted_by_start:\n            if last_label_end is None or (last_label_end - label.start < overlap_threshold and last_label_end > 0):\n                concat_values.append(label.value)\n                last_label_end = label.end\n            else:\n                raise ValueError('Labels overlap, not able to define the correct order')\n        return delimiter.join(concat_values)",
    "docstring": "Return a string with all labels concatenated together.\n        The order of the labels is defined by the start of the label.\n        If the overlapping between two labels is greater than ``overlap_threshold``,\n        an Exception is thrown.\n\n        Args:\n            delimiter (str): A string to join two consecutive labels.\n            overlap_threshold (float): Maximum overlap between two consecutive labels.\n\n        Returns:\n            str: A string with all labels concatenated together.\n\n        Example:\n            >>> ll = LabelList(idx='some', labels=[\n            >>>     Label('a', start=0, end=4),\n            >>>     Label('b', start=3.95, end=6.0),\n            >>>     Label('c', start=7.0, end=10.2),\n            >>>     Label('d', start=10.3, end=14.0)\n            >>> ])\n            >>> ll.join(' - ')\n            'a - b - c - d'"
  },
  {
    "code": "def getPrintAddress(self):\n        address_lines = []\n        addresses = [\n            self.getPostalAddress(),\n            self.getPhysicalAddress(),\n            self.getBillingAddress(),\n        ]\n        for address in addresses:\n            city = address.get(\"city\", \"\")\n            zip = address.get(\"zip\", \"\")\n            state = address.get(\"state\", \"\")\n            country = address.get(\"country\", \"\")\n            if city:\n                address_lines = [\n                    address[\"address\"].strip(),\n                    \"{} {}\".format(city, zip).strip(),\n                    \"{} {}\".format(state, country).strip(),\n                ]\n                break\n        return address_lines",
    "docstring": "Get an address for printing"
  },
  {
    "code": "def reqHistogramData(\n            self, contract: Contract,\n            useRTH: bool, period: str) -> List[HistogramData]:\n        return self._run(\n            self.reqHistogramDataAsync(contract, useRTH, period))",
    "docstring": "Request histogram data.\n\n        This method is blocking.\n\n        https://interactivebrokers.github.io/tws-api/histograms.html\n\n        Args:\n            contract: Contract to query.\n            useRTH: If True then only show data from within Regular\n                Trading Hours, if False then show all data.\n            period: Period of which data is being requested, for example\n                '3 days'."
  },
  {
    "code": "def push(collector, image, **kwargs):\n    if not image.image_index:\n        raise BadOption(\"The chosen image does not have a image_index configuration\", wanted=image.name)\n    tag = kwargs[\"artifact\"]\n    if tag is NotSpecified:\n        tag = collector.configuration[\"harpoon\"].tag\n    if tag is not NotSpecified:\n        image.tag = tag\n    Builder().make_image(image, collector.configuration[\"images\"], pushing=True)\n    Syncer().push(image)",
    "docstring": "Push an image"
  },
  {
    "code": "def reroot(self, rppr=None, pretend=False):\n        with scratch_file(prefix='tree', suffix='.tre') as name:\n            subprocess.check_call([rppr or 'rppr', 'reroot',\n                                   '-c', self.path, '-o', name])\n            if not(pretend):\n                self.update_file('tree', name)\n        self._log('Rerooting refpkg')",
    "docstring": "Reroot the phylogenetic tree.\n\n        This operation calls ``rppr reroot`` to generate the rerooted\n        tree, so you must have ``pplacer`` and its auxiliary tools\n        ``rppr`` and ``guppy`` installed for it to work.  You can\n        specify the path to ``rppr`` by giving it as the *rppr*\n        argument.\n\n        If *pretend* is ``True``, the convexification is run, but the\n        refpkg is not actually updated."
  },
  {
    "code": "def annual_volatility(returns,\n                      period=DAILY,\n                      alpha=2.0,\n                      annualization=None,\n                      out=None):\n    allocated_output = out is None\n    if allocated_output:\n        out = np.empty(returns.shape[1:])\n    returns_1d = returns.ndim == 1\n    if len(returns) < 2:\n        out[()] = np.nan\n        if returns_1d:\n            out = out.item()\n        return out\n    ann_factor = annualization_factor(period, annualization)\n    nanstd(returns, ddof=1, axis=0, out=out)\n    out = np.multiply(out, ann_factor ** (1.0 / alpha), out=out)\n    if returns_1d:\n        out = out.item()\n    return out",
    "docstring": "Determines the annual volatility of a strategy.\n\n    Parameters\n    ----------\n    returns : pd.Series or np.ndarray\n        Periodic returns of the strategy, noncumulative.\n        - See full explanation in :func:`~empyrical.stats.cum_returns`.\n    period : str, optional\n        Defines the periodicity of the 'returns' data for purposes of\n        annualizing. Value ignored if `annualization` parameter is specified.\n        Defaults are::\n\n            'monthly':12\n            'weekly': 52\n            'daily': 252\n\n    alpha : float, optional\n        Scaling relation (Levy stability exponent).\n    annualization : int, optional\n        Used to suppress default values available in `period` to convert\n        returns into annual returns. Value should be the annual frequency of\n        `returns`.\n    out : array-like, optional\n        Array to use as output buffer.\n        If not passed, a new array will be created.\n\n    Returns\n    -------\n    annual_volatility : float"
  },
  {
    "code": "def state_transition_run(self, event_to_wait_on):\n        while event_to_wait_on.wait():\n            event_to_wait_on.clear()\n            if self.state_transition_callback_kill_event.is_set():\n                return\n            self.state_transition_func()",
    "docstring": "This is the thread that listens to an event from\n           the timer process to execute the state_transition_func callback\n           in the context of the main process."
  },
  {
    "code": "def apply_transformation(self, structure):\n        if self.species_map == None:\n            match = StructureMatcher()\n            s_map = \\\n                match.get_best_electronegativity_anonymous_mapping(self.unrelaxed_structure,\n                                                                   structure)\n        else:\n            s_map = self.species_map\n        params = list(structure.lattice.abc)\n        params.extend(structure.lattice.angles)\n        new_lattice = Lattice.from_parameters(*[p*self.params_percent_change[i] \\\n                                                for i, p in enumerate(params)])\n        species, frac_coords = [], []\n        for site in self.relaxed_structure:\n            species.append(s_map[site.specie])\n            frac_coords.append(site.frac_coords)\n        return Structure(new_lattice, species, frac_coords)",
    "docstring": "Returns a copy of structure with lattice parameters\n        and sites scaled to the same degree as the relaxed_structure.\n\n        Arg:\n            structure (Structure): A structurally similar structure in\n                regards to crystal and site positions."
  },
  {
    "code": "def decode(pieces, sequence_length, model_file=None, model_proto=None,\n           reverse=False, name=None):\n  return _gen_sentencepiece_processor_op.sentencepiece_decode(\n      pieces, sequence_length, model_file=model_file,\n      model_proto=model_proto, reverse=reverse, name=name)",
    "docstring": "Decode pieces into postprocessed text.\n\n  Args:\n    pieces: A 2D int32 or string tensor [batch_size x max_length] of\n            encoded sequences.\n    sequence_length: A 1D int32 tensor [batch_size] representing the\n                   length of pieces.\n    model_file: The sentencepiece model file path.\n    model_proto: The sentencepiece model serialized proto.\n                 Either `model_file` or `model_proto` must be set.\n    reverse: Reverses the tokenized sequence (Default = false)\n    name: The name argument that is passed to the op function.\n\n  Returns:\n    text: A 1D string tensor of decoded string."
  },
  {
    "code": "def fnmatches(entry, *pattern_list):\n    for pattern in pattern_list:\n        if pattern and fnmatch(entry, pattern):\n            return True\n    return False",
    "docstring": "returns true if entry matches any of the glob patterns, false\n    otherwise"
  },
  {
    "code": "def construct_item_args(self, domain_event):\n        sequence_id = domain_event.__dict__[self.sequence_id_attr_name]\n        position = getattr(domain_event, self.position_attr_name, None)\n        topic, state = self.get_item_topic_and_state(\n            domain_event.__class__,\n            domain_event.__dict__\n        )\n        other_args = tuple((getattr(domain_event, name) for name in self.other_attr_names))\n        return (sequence_id, position, topic, state) + other_args",
    "docstring": "Constructs attributes of a sequenced item from the given domain event."
  },
  {
    "code": "def autocommand(func):\n    name = func.__name__\n    title, desc = command.parse_docstring(func)\n    if not title:\n        title = 'Auto command for: %s' % name\n    if not desc:\n        desc = ' '\n    return AutoCommand(title=title, desc=desc, name=name, func=func)",
    "docstring": "A simplified decorator for making a single function a Command\n    instance.  In the future this will leverage PEP0484 to do really smart\n    function parsing and conversion to argparse actions."
  },
  {
    "code": "def _init_journal(self, permissive=True):\n        nowstamp = datetime.now().strftime(\"%d-%b-%Y %H:%M:%S.%f\")[:-3]\n        self._add_entry(templates.INIT\n                                 .format(time_stamp=nowstamp))\n        if permissive:\n            self._add_entry(templates.INIT_DEBUG)",
    "docstring": "Add the initialization lines to the journal.\n\n        By default adds JrnObj variable and timestamp to the journal contents.\n\n        Args:\n            permissive (bool): if True most errors in journal will not\n                               cause Revit to stop journal execution.\n                               Some still do."
  },
  {
    "code": "def get_squeezed_contents(contents):\n    line_between_example_code = substitute.Substitution(\n        '\\n\\n    ',\n        '\\n    ',\n        True\n    )\n    lines_between_examples = substitute.Substitution('\\n\\n\\n', '\\n\\n', True)\n    lines_between_sections = substitute.Substitution(\n        '\\n\\n\\n\\n', '\\n\\n\\n', True\n    )\n    result = contents\n    result = line_between_example_code.apply_and_get_result(result)\n    result = lines_between_examples.apply_and_get_result(result)\n    result = lines_between_sections.apply_and_get_result(result)\n    return result",
    "docstring": "Squeeze the contents by removing blank lines between definition and example\n    and remove duplicate blank lines except between sections."
  },
  {
    "code": "def reset(self):\n        for stat in six.itervalues(self._op_stats):\n            if stat._start_time is not None:\n                return False\n        self._op_stats = {}\n        return True",
    "docstring": "Reset all statistics and clear any statistic names.\n        All statistics must be inactive before a reset will execute\n\n        Returns: True if reset, False if not"
  },
  {
    "code": "def _validate_iterable(self, is_iterable, key, value):\n        if is_iterable:\n            try:\n                iter(value)\n            except TypeError:\n                self._error(key, \"Must be iterable (e.g. a list or array)\")",
    "docstring": "Validate fields with `iterable` key in schema set to True"
  },
  {
    "code": "def combine_action_handlers(*handlers):\n    for handler in handlers:\n        if not (iscoroutinefunction(handler) or iscoroutine(handler)):\n            raise ValueError(\"Provided handler is not a coroutine: %s\" % handler)\n    async def combined_handler(*args, **kwds):\n        for handler in handlers:\n            await handler(*args, **kwds)\n    return combined_handler",
    "docstring": "This function combines the given action handlers into a single function\n        which will call all of them."
  },
  {
    "code": "def offset(polygons,\n           distance,\n           join='miter',\n           tolerance=2,\n           precision=0.001,\n           join_first=False,\n           max_points=199,\n           layer=0,\n           datatype=0):\n    poly = []\n    if isinstance(polygons, PolygonSet):\n        poly.extend(polygons.polygons)\n    elif isinstance(polygons, CellReference) or isinstance(\n            polygons, CellArray):\n        poly.extend(polygons.get_polygons())\n    else:\n        for obj in polygons:\n            if isinstance(obj, PolygonSet):\n                poly.extend(obj.polygons)\n            elif isinstance(obj, CellReference) or isinstance(obj, CellArray):\n                poly.extend(obj.get_polygons())\n            else:\n                poly.append(obj)\n    result = clipper.offset(poly, distance, join, tolerance, 1 / precision, 1\n                            if join_first else 0)\n    return None if len(result) == 0 else PolygonSet(\n        result, layer, datatype, verbose=False).fracture(\n            max_points, precision)",
    "docstring": "Shrink or expand a polygon or polygon set.\n\n    Parameters\n    ----------\n    polygons : polygon or array-like\n        Polygons to be offset.  Must be a ``PolygonSet``,\n        ``CellReference``, ``CellArray``, or an array.  The array may\n        contain any of the previous objects or an array-like[N][2] of\n        vertices of a polygon.\n    distance : number\n        Offset distance.  Positive to expand, negative to shrink.\n    join : {'miter', 'bevel', 'round'}\n        Type of join used to create the offset polygon.\n    tolerance : number\n        For miter joints, this number must be at least 2 and it\n        represents the maximun distance in multiples of offset betwen\n        new vertices and their original position before beveling to\n        avoid spikes at acute joints.  For round joints, it indicates\n        the curvature resolution in number of points per full circle.\n    precision : float\n        Desired precision for rounding vertice coordinates.\n    join_first : bool\n        Join all paths before offseting to avoid unecessary joins in\n        adjacent polygon sides.\n    max_points : integer\n        If greater than 4, fracture the resulting polygons to ensure\n        they have at most ``max_points`` vertices.  This is not a\n        tessellating function, so this number should be as high as\n        possible.  For example, it should be set to 199 for polygons\n        being drawn in GDSII files.\n    layer : integer\n        The GDSII layer number for the resulting element.\n    datatype : integer\n        The GDSII datatype for the resulting element (between 0 and\n        255).\n\n    Returns\n    -------\n    out : ``PolygonSet`` or ``None``\n        Return the offset shape as a set of polygons."
  },
  {
    "code": "def get_random_string():\n    hash_string = \"%8x\" % random.getrandbits(32)\n    hash_string = hash_string.strip()\n    while is_number(hash_string):\n        hash_string = \"%8x\" % random.getrandbits(32)\n        hash_string = hash_string.strip()\n    return hash_string",
    "docstring": "make a random string, which we can use for bsub job IDs, so that\n    different jobs do not have the same job IDs."
  },
  {
    "code": "def update_tab_for_course(self, tab_id, course_id, hidden=None, position=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"course_id\"] = course_id\r\n        path[\"tab_id\"] = tab_id\r\n        if position is not None:\r\n            data[\"position\"] = position\r\n        if hidden is not None:\r\n            data[\"hidden\"] = hidden\r\n        self.logger.debug(\"PUT /api/v1/courses/{course_id}/tabs/{tab_id} with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"PUT\", \"/api/v1/courses/{course_id}/tabs/{tab_id}\".format(**path), data=data, params=params, single_item=True)",
    "docstring": "Update a tab for a course.\r\n\r\n        Home and Settings tabs are not manageable, and can't be hidden or moved\r\n        \r\n        Returns a tab object"
  },
  {
    "code": "def has_group_perms(self, perm, obj, approved):\n        if not self.group:\n            return False\n        if self.use_smart_cache:\n            content_type_pk = Permission.objects.get_content_type(obj).pk\n            def _group_has_perms(cached_perms):\n                return cached_perms.get((\n                    obj.pk,\n                    content_type_pk,\n                    perm,\n                    approved,\n                ))\n            return _group_has_perms(self._group_perm_cache)\n        return Permission.objects.group_permissions(\n            self.group,\n            perm, obj,\n            approved,\n        ).filter(\n            object_id=obj.pk,\n        ).exists()",
    "docstring": "Check if group has the permission for the given object"
  },
  {
    "code": "def do_GET(self):\n        if self.path.lower().endswith(\"?wsdl\"):\n            service_path = self.path[:-5]\n            service = self.server.getNode(service_path)\n            if hasattr(service, \"_wsdl\"):\n                wsdl = service._wsdl\n                proto = 'http'\n                if hasattr(self.server,'proto'):\n                    proto = self.server.proto\n                serviceUrl = '%s://%s:%d%s' % (proto,\n                                                self.server.server_name,\n                                                self.server.server_port,\n                                                service_path)\n                soapAddress = '<soap:address location=\"%s\"/>' % serviceUrl\n                wsdlre = re.compile('\\<soap:address[^\\>]*>',re.IGNORECASE)\n                wsdl = re.sub(wsdlre,soapAddress,wsdl)\n                self.send_xml(wsdl)\n            else:\n                self.send_error(404, \"WSDL not available for that service [%s].\" % self.path)\n        else:\n            self.send_error(404, \"Service not found [%s].\" % self.path)",
    "docstring": "The GET command."
  },
  {
    "code": "def _get_pull_requests(self):\n        for pull in self.repo.pull_requests(\n            state=\"closed\", base=self.github_info[\"master_branch\"], direction=\"asc\"\n        ):\n            if self._include_pull_request(pull):\n                yield pull",
    "docstring": "Gets all pull requests from the repo since we can't do a filtered\n        date merged search"
  },
  {
    "code": "def set_motor_force(self, motor_name, force):\n        self.call_remote_api('simxSetJointForce',\n                             self.get_object_handle(motor_name),\n                             force,\n                             sending=True)",
    "docstring": "Sets the maximum force or torque that a joint can exert."
  },
  {
    "code": "def create_ckan_ini(self):\n        self.run_command(\n            command='/scripts/run_as_user.sh /usr/lib/ckan/bin/paster make-config'\n            ' ckan /project/development.ini',\n            rw_project=True,\n            ro={scripts.get_script_path('run_as_user.sh'): '/scripts/run_as_user.sh'},\n            )",
    "docstring": "Use make-config to generate an initial development.ini file"
  },
  {
    "code": "def make_object(cls, data):\n    if issubclass(cls, Object):\n        self = object.__new__(cls)\n        self._data = data\n    else:\n        self = data\n    return self",
    "docstring": "Creates an API object of class `cls`, setting its `_data` to\n    data. Subclasses of `Object` are required to use this to build a\n    new, empty instance without using their constructor."
  },
  {
    "code": "def copy_from_model(cls, model_name, reference, **kwargs):\n        if isinstance(reference, cls):\n            settings = reference.__dict__.copy()\n            settings.pop('model')\n        else:\n            settings = _get_model_info(reference)\n            settings.pop('model_name')\n        settings.update(kwargs)\n        settings['reference'] = reference\n        return cls(model_name, **settings)",
    "docstring": "Set-up a user-defined grid using specifications of a reference\n        grid model.\n\n        Parameters\n        ----------\n        model_name : string\n            name of the user-defined grid model.\n        reference : string or :class:`CTMGrid` instance\n            Name of the reference model (see :func:`get_supported_models`),\n            or a :class:`CTMGrid` object from which grid set-up is copied.\n        **kwargs\n            Any set-up parameter which will override the settings of the\n            reference model (see :class:`CTMGrid` parameters).\n\n        Returns\n        -------\n        A :class:`CTMGrid` object."
  },
  {
    "code": "def timedelta_isoformat(td: datetime.timedelta) -> str:\n    minutes, seconds = divmod(td.seconds, 60)\n    hours, minutes = divmod(minutes, 60)\n    return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'",
    "docstring": "ISO 8601 encoding for timedeltas."
  },
  {
    "code": "def _toolkit_serialize_summary_struct(model, sections, section_titles):\n    output_dict = dict()\n    output_dict['sections'] = [ [ ( field[0], __extract_model_summary_value(model, field[1]) ) \\\n                                                                            for field in section ]\n                                                                            for section in sections ]\n    output_dict['section_titles'] = section_titles\n    return output_dict",
    "docstring": "Serialize model summary into a dict with ordered lists of sections and section titles\n\n    Parameters\n    ----------\n    model : Model object\n    sections : Ordered list of lists (sections) of tuples (field,value)\n      [\n        [(field1, value1), (field2, value2)],\n        [(field3, value3), (field4, value4)],\n\n      ]\n    section_titles : Ordered list of section titles\n\n\n    Returns\n    -------\n    output_dict : A dict with two entries:\n                    'sections' : ordered list with tuples of the form ('label',value)\n                    'section_titles' : ordered list of section labels"
  },
  {
    "code": "def arr_normalize(arr, *args, **kwargs):\n    f_max = arr.max()\n    f_min = arr.min()\n    f_range = f_max - f_min\n    arr_shifted = arr + -f_min\n    arr_norm = arr_shifted / f_range\n    for key, value in kwargs.items():\n        if key == 'scale': arr_norm *= value\n    return arr_norm",
    "docstring": "ARGS\n        arr                      array to normalize\n\n    **kargs\n        scale = <f_scale>        scale the normalized output by <f_scale>\n\n\n    DESC\n        Given an input array, <arr>, normalize all values to range\n        between 0 and 1.\n\n        If specified in the **kwargs, optionally set the scale with <f_scale>."
  },
  {
    "code": "def affine_map(points1, points2):\n    A = np.ones((4, 4))\n    A[:, :3] = points1\n    B = np.ones((4, 4))\n    B[:, :3] = points2\n    matrix = np.eye(4)\n    for i in range(3):\n        matrix[i] = np.linalg.solve(A, B[:, i])\n    return matrix",
    "docstring": "Find a 3D transformation matrix that maps points1 onto points2.\n\n    Arguments are specified as arrays of four 3D coordinates, shape (4, 3)."
  },
  {
    "code": "async def get_scm_level(context, project):\n    await context.populate_projects()\n    level = context.projects[project]['access'].replace(\"scm_level_\", \"\")\n    return level",
    "docstring": "Get the scm level for a project from ``projects.yml``.\n\n    We define all known projects in ``projects.yml``. Let's make sure we have\n    it populated in ``context``, then return the scm level of ``project``.\n\n    SCM levels are an integer, 1-3, matching Mozilla commit levels.\n    https://www.mozilla.org/en-US/about/governance/policies/commit/access-policy/\n\n    Args:\n        context (scriptworker.context.Context): the scriptworker context\n        project (str): the project to get the scm level for.\n\n    Returns:\n        str: the level of the project, as a string."
  },
  {
    "code": "def update_agent_db_refs(self, agent, agent_text, do_rename=True):\n        map_db_refs = deepcopy(self.gm.get(agent_text))\n        self.standardize_agent_db_refs(agent, map_db_refs, do_rename)",
    "docstring": "Update db_refs of agent using the grounding map\n\n        If the grounding map is missing one of the HGNC symbol or Uniprot ID,\n        attempts to reconstruct one from the other.\n\n        Parameters\n        ----------\n        agent : :py:class:`indra.statements.Agent`\n            The agent whose db_refs will be updated\n        agent_text : str\n            The agent_text to find a grounding for in the grounding map\n            dictionary. Typically this will be agent.db_refs['TEXT'] but\n            there may be situations where a different value should be used.\n        do_rename: Optional[bool]\n            If True, the Agent name is updated based on the mapped grounding.\n            If do_rename is True the priority for setting the name is\n            FamPlex ID, HGNC symbol, then the gene name\n            from Uniprot. Default: True\n\n        Raises\n        ------\n        ValueError\n            If the the grounding map contains and HGNC symbol for\n            agent_text but no HGNC ID can be found for it.\n        ValueError\n            If the grounding map contains both an HGNC symbol and a\n            Uniprot ID, but the HGNC symbol and the gene name associated with\n            the gene in Uniprot do not match or if there is no associated gene\n            name in Uniprot."
  },
  {
    "code": "def ask_dir(self):\n\t\targs ['directory'] = askdirectory(**self.dir_opt) \n\t\tself.dir_text.set(args ['directory'])",
    "docstring": "dialogue box for choosing directory"
  },
  {
    "code": "def _ufunc_helper(lhs, rhs, fn_array, fn_scalar, lfn_scalar, rfn_scalar=None):\n    if isinstance(lhs, numeric_types):\n        if isinstance(rhs, numeric_types):\n            return fn_scalar(lhs, rhs)\n        else:\n            if rfn_scalar is None:\n                return lfn_scalar(rhs, float(lhs))\n            else:\n                return rfn_scalar(rhs, float(lhs))\n    elif isinstance(rhs, numeric_types):\n        return lfn_scalar(lhs, float(rhs))\n    elif isinstance(rhs, NDArray):\n        return fn_array(lhs, rhs)\n    else:\n        raise TypeError('type %s not supported' % str(type(rhs)))",
    "docstring": "Helper function for element-wise operation.\n    The function will perform numpy-like broadcasting if needed and call different functions.\n\n    Parameters\n    --------\n    lhs : NDArray or numeric value\n        Left-hand side operand.\n\n    rhs : NDArray or numeric value\n        Right-hand operand,\n\n    fn_array : function\n        Function to be called if both lhs and rhs are of ``NDArray`` type.\n\n    fn_scalar : function\n        Function to be called if both lhs and rhs are numeric values.\n\n    lfn_scalar : function\n        Function to be called if lhs is ``NDArray`` while rhs is numeric value\n\n    rfn_scalar : function\n        Function to be called if lhs is numeric value while rhs is ``NDArray``;\n        if none is provided, then the function is commutative, so rfn_scalar is equal to lfn_scalar\n\n    Returns\n    --------\n    NDArray\n        result array"
  },
  {
    "code": "def to_array(self):\n        array = super(Document, self).to_array()\n        array['file_id'] = u(self.file_id)\n        if self.thumb is not None:\n            array['thumb'] = self.thumb.to_array()\n        if self.file_name is not None:\n            array['file_name'] = u(self.file_name)\n        if self.mime_type is not None:\n            array['mime_type'] = u(self.mime_type)\n        if self.file_size is not None:\n            array['file_size'] = int(self.file_size)\n        return array",
    "docstring": "Serializes this Document to a dictionary.\n\n        :return: dictionary representation of this object.\n        :rtype: dict"
  },
  {
    "code": "def text_wrap(text, length=None, indent='', firstline_indent=None):\n  if length is None:\n    length = get_help_width()\n  if indent is None:\n    indent = ''\n  if firstline_indent is None:\n    firstline_indent = indent\n  if len(indent) >= length:\n    raise ValueError('Length of indent exceeds length')\n  if len(firstline_indent) >= length:\n    raise ValueError('Length of first line indent exceeds length')\n  text = text.expandtabs(4)\n  result = []\n  wrapper = textwrap.TextWrapper(\n      width=length, initial_indent=firstline_indent, subsequent_indent=indent)\n  subsequent_wrapper = textwrap.TextWrapper(\n      width=length, initial_indent=indent, subsequent_indent=indent)\n  for paragraph in (p.strip() for p in text.splitlines()):\n    if paragraph:\n      result.extend(wrapper.wrap(paragraph))\n    else:\n      result.append('')\n    wrapper = subsequent_wrapper\n  return '\\n'.join(result)",
    "docstring": "Wraps a given text to a maximum line length and returns it.\n\n  It turns lines that only contain whitespace into empty lines, keeps new lines,\n  and expands tabs using 4 spaces.\n\n  Args:\n    text: str, text to wrap.\n    length: int, maximum length of a line, includes indentation.\n        If this is None then use get_help_width()\n    indent: str, indent for all but first line.\n    firstline_indent: str, indent for first line; if None, fall back to indent.\n\n  Returns:\n    str, the wrapped text.\n\n  Raises:\n    ValueError: Raised if indent or firstline_indent not shorter than length."
  },
  {
    "code": "def updated(self, user):\n        for who, what, old, new in self.history(user):\n            if (what == \"comment\" or what == \"description\") and new != \"\":\n                return True\n        return False",
    "docstring": "True if the user commented the ticket in given time frame"
  },
  {
    "code": "def create_log(self):\n        return EventLog(\n            self.networkapi_url,\n            self.user,\n            self.password,\n            self.user_ldap)",
    "docstring": "Get an instance of log services facade."
  },
  {
    "code": "def python_path(self, script):\n        if not script:\n            try:\n                import __main__\n                script = getfile(__main__)\n            except Exception:\n                return\n        script = os.path.realpath(script)\n        if self.cfg.get('python_path', True):\n            path = os.path.dirname(script)\n            if path not in sys.path:\n                sys.path.insert(0, path)\n        return script",
    "docstring": "Called during initialisation to obtain the ``script`` name.\n\n        If ``script`` does not evaluate to ``True`` it is evaluated from\n        the ``__main__`` import. Returns the real path of the python\n        script which runs the application."
  },
  {
    "code": "def precompute_sharp_round(nxk, nyk, xc, yc):\n    s4m = np.ones((nyk,nxk),dtype=np.int16)\n    s4m[yc, xc] = 0\n    s2m = np.ones((nyk,nxk),dtype=np.int16)\n    s2m[yc, xc] = 0\n    s2m[yc:nyk, 0:xc]     = -1;\n    s2m[0:yc+1, xc+1:nxk] = -1;\n    return s2m, s4m",
    "docstring": "Pre-computes mask arrays to be used by the 'sharp_round' function\n    for roundness computations based on two- and four-fold symmetries."
  },
  {
    "code": "def flatten( iterables ):\n    for it in iterables:\n        if isinstance(it, str):\n            yield it\n        else:\n            for element in it:\n                yield element",
    "docstring": "Flatten an iterable, except for string elements."
  },
  {
    "code": "def verify(password_hash, password):\n    if password_hash.startswith(argon2id.STRPREFIX):\n        return argon2id.verify(password_hash, password)\n    elif password_hash.startswith(argon2i.STRPREFIX):\n        return argon2id.verify(password_hash, password)\n    elif password_hash.startswith(scrypt.STRPREFIX):\n        return scrypt.verify(password_hash, password)\n    else:\n        raise(CryptPrefixError(\"given password_hash is not \"\n                               \"in a supported format\"\n                               )\n              )",
    "docstring": "Takes a modular crypt encoded stored password hash derived using one\n    of the algorithms supported by `libsodium` and checks if the user provided\n    password will hash to the same string when using the parameters saved\n    in the stored hash"
  },
  {
    "code": "def crc32File(filename, skip=0):\n    with open(filename, 'rb') as stream:\n        discard = stream.read(skip)\n        return zlib.crc32(stream.read()) & 0xffffffff",
    "docstring": "Computes the CRC-32 of the contents of filename, optionally\n    skipping a certain number of bytes at the beginning of the file."
  },
  {
    "code": "def _filter_names(names):\n    names = [n for n in names\n             if n not in EXCLUDE_NAMES]\n    for pattern in EXCLUDE_PATTERNS:\n        names = [n for n in names\n                 if (not fnmatch.fnmatch(n, pattern))\n                 and (not n.endswith('.py'))]\n    return names",
    "docstring": "Given a list of file names, return those names that should be copied."
  },
  {
    "code": "def build_vcf_parts(feature, genome_2bit, info=None):\n    base1 = genome_2bit[feature.chrom1].get(\n        feature.start1, feature.start1 + 1).upper()\n    id1 = \"hydra{0}a\".format(feature.name)\n    base2 = genome_2bit[feature.chrom2].get(\n        feature.start2, feature.start2 + 1).upper()\n    id2 = \"hydra{0}b\".format(feature.name)\n    orientation = _breakend_orientation(feature.strand1, feature.strand2)\n    return (VcfLine(feature.chrom1, feature.start1, id1, base1,\n                    _vcf_alt(base1, feature.chrom2, feature.start2,\n                             orientation.is_rc1, orientation.is_first1),\n                    _vcf_info(feature.start1, feature.end1, id2, info)),\n            VcfLine(feature.chrom2, feature.start2, id2, base2,\n                    _vcf_alt(base2, feature.chrom1, feature.start1,\n                             orientation.is_rc2, orientation.is_first2),\n                    _vcf_info(feature.start2, feature.end2, id1, info)))",
    "docstring": "Convert BedPe feature information into VCF part representation.\n\n    Each feature will have two VCF lines for each side of the breakpoint."
  },
  {
    "code": "def resource_set_create(self, token, name, **kwargs):\n        return self._realm.client.post(\n            self.well_known['resource_registration_endpoint'],\n            data=self._get_data(name=name, **kwargs),\n            headers=self.get_headers(token)\n        )",
    "docstring": "Create a resource set.\n\n        https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#rfc.section.2.2.1\n\n        :param str token: client access token\n        :param str id: Identifier of the resource set\n        :param str name:\n        :param str uri: (optional)\n        :param str type: (optional)\n        :param list scopes: (optional)\n        :param str icon_url: (optional)\n        :param str DisplayName: (optional)\n        :param boolean ownerManagedAccess: (optional)\n        :param str owner: (optional)\n        :rtype: str"
  },
  {
    "code": "def athalianatruth(args):\n    p = OptionParser(athalianatruth.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n    atxt, bctxt = args\n    g = Grouper()\n    pairs = set()\n    for txt in (atxt, bctxt):\n        extract_groups(g, pairs, txt)\n    fw = open(\"pairs\", \"w\")\n    for pair in sorted(pairs):\n        print(\"\\t\".join(pair), file=fw)\n    fw.close()\n    fw = open(\"groups\", \"w\")\n    for group in list(g):\n        print(\",\".join(group), file=fw)\n    fw.close()",
    "docstring": "%prog athalianatruth J_a.txt J_bc.txt\n\n    Prepare pairs data for At alpha/beta/gamma."
  },
  {
    "code": "def unique(new_cmp_dict, old_cmp_dict):\n    newkeys = set(new_cmp_dict)\n    oldkeys = set(old_cmp_dict)\n    unique = newkeys - oldkeys\n    unique_ldict = []\n    for key in unique:\n        unique_ldict.append(new_cmp_dict[key])\n    return unique_ldict",
    "docstring": "Return a list dict of\n       the unique keys in new_cmp_dict"
  },
  {
    "code": "def over(expr, window):\n    prior_op = expr.op()\n    if isinstance(prior_op, ops.WindowOp):\n        op = prior_op.over(window)\n    else:\n        op = ops.WindowOp(expr, window)\n    result = op.to_expr()\n    try:\n        name = expr.get_name()\n    except com.ExpressionError:\n        pass\n    else:\n        result = result.name(name)\n    return result",
    "docstring": "Turn an aggregation or full-sample analytic operation into a windowed\n    operation. See ibis.window for more details on window configuration\n\n    Parameters\n    ----------\n    expr : value expression\n    window : ibis.Window\n\n    Returns\n    -------\n    expr : type of input"
  },
  {
    "code": "def getFlaskResponse(responseString, httpStatus=200):\n    return flask.Response(responseString, status=httpStatus, mimetype=MIMETYPE)",
    "docstring": "Returns a Flask response object for the specified data and HTTP status."
  },
  {
    "code": "def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False):\n    ret = {}\n    if primary_server:\n        query = {'type': 'config',\n                 'action': 'set',\n                 'xpath': '/config/devices/entry[@name=\\'localhost.localdomain\\']/deviceconfig/system/ntp-servers/'\n                          'primary-ntp-server',\n                 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(primary_server)}\n        ret.update({'primary_server': __proxy__['panos.call'](query)})\n    if secondary_server:\n        query = {'type': 'config',\n                 'action': 'set',\n                 'xpath': '/config/devices/entry[@name=\\'localhost.localdomain\\']/deviceconfig/system/ntp-servers/'\n                          'secondary-ntp-server',\n                 'element': '<ntp-server-address>{0}</ntp-server-address>'.format(secondary_server)}\n        ret.update({'secondary_server': __proxy__['panos.call'](query)})\n    if deploy is True:\n        ret.update(commit())\n    return ret",
    "docstring": "Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed.\n\n    CLI Example:\n\n    Args:\n        primary_server(str): The primary NTP server IP address or FQDN.\n\n        secondary_server(str): The secondary NTP server IP address or FQDN.\n\n        deploy (bool): If true then commit the full candidate configuration, if false only set pending change.\n\n    .. code-block:: bash\n\n        salt '*' ntp.set_servers 0.pool.ntp.org 1.pool.ntp.org\n        salt '*' ntp.set_servers primary_server=0.pool.ntp.org secondary_server=1.pool.ntp.org\n        salt '*' ntp.ser_servers 0.pool.ntp.org 1.pool.ntp.org deploy=True"
  },
  {
    "code": "def next(self):\n        try:\n            return six.next(self._wrapped)\n        except grpc.RpcError as exc:\n            six.raise_from(exceptions.from_grpc_error(exc), exc)",
    "docstring": "Get the next response from the stream.\n\n        Returns:\n            protobuf.Message: A single response from the stream."
  },
  {
    "code": "def service_url_parse(url):\n    endpoint = get_sanitized_endpoint(url)\n    url_split_list = url.split(endpoint + '/')\n    if len(url_split_list) != 0:\n        url_split_list = url_split_list[1].split('/')\n    else:\n        raise Exception('Wrong url parsed')\n    parsed_url = [s for s in url_split_list if '?' not in s if 'Server' not in s]\n    return parsed_url",
    "docstring": "Function that parses from url the service and folder of services."
  },
  {
    "code": "def cancel_inquiry (self):\n        self.names_to_find = {}\n        if self.is_inquiring:\n            try:\n                _bt.hci_send_cmd (self.sock, _bt.OGF_LINK_CTL, \\\n                        _bt.OCF_INQUIRY_CANCEL)\n            except _bt.error as e:\n                self.sock.close ()\n                self.sock = None\n                raise BluetoothError (e.args[0],\n                                      \"error canceling inquiry: \" +\n                                      e.args[1])\n            self.is_inquiring = False",
    "docstring": "Call this method to cancel an inquiry in process.  inquiry_complete\n        will still be called."
  },
  {
    "code": "def free (self):\n        result = [p for p in self.lazy_properties\n                  if not p.feature.incidental and p.feature.free]\n        result.extend(self.free_)\n        return result",
    "docstring": "Returns free properties which are not dependency properties."
  },
  {
    "code": "def transform_properties(properties, schema):\n    new_properties = properties.copy()\n    for prop_value, (prop_name, prop_type) in zip(new_properties.values(), schema[\"properties\"].items()):\n        if prop_value is None:\n            continue\n        elif prop_type == \"time\":\n            new_properties[prop_name] = parse_date(prop_value).time()\n        elif prop_type == \"date\":\n            new_properties[prop_name] = parse_date(prop_value).date()\n        elif prop_type == \"datetime\":\n            new_properties[prop_name] = parse_date(prop_value)\n    return new_properties",
    "docstring": "Transform properties types according to a schema.\n\n    Parameters\n    ----------\n    properties : dict\n        Properties to transform.\n    schema : dict\n        Fiona schema containing the types."
  },
  {
    "code": "def get_letters_per_page(self, per_page=1000, page=1, params=None):\n        return self._get_resource_per_page(resource=LETTERS, per_page=per_page, page=page, params=params)",
    "docstring": "Get letters per page\n\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :param params: Search parameters. Default: {}\n        :return: list"
  },
  {
    "code": "def search(api_key, query, offset=0, type='personal'):\n    if not isinstance(api_key, str):\n        raise InvalidAPIKeyException('API key must be a string')\n    if not api_key or len(api_key) < 40:\n        raise InvalidAPIKeyException('Invalid API key.')\n    url = get_endpoint(api_key, query, offset, type)\n    try:\n        return requests.get(url).json()\n    except requests.exceptions.RequestException as err:\n        raise PunterException(err)",
    "docstring": "Get a list of email addresses for the provided domain.\n\n    The type of search executed will vary depending on the query provided.\n    Currently this query is restricted to either domain searches, in which\n    the email addresses (and other bits) for the domain are returned, or\n    searches for an email address. The latter is primary meant for checking\n    if an email address exists, although various other useful bits are also\n    provided (for example, the domain where the address was found).\n\n    :param api_key: Secret client API key.\n    :param query: URL or email address on which to search.\n    :param offset: Specifies the number of emails to skip.\n    :param type: Specifies email type (i.e. generic or personal)."
  },
  {
    "code": "def SaveData(self, raw_data):\n    if self.filename is None:\n      raise IOError(\"Unknown filename\")\n    logging.info(\"Writing back configuration to file %s\", self.filename)\n    try:\n      os.makedirs(os.path.dirname(self.filename))\n    except (IOError, OSError):\n      pass\n    try:\n      mode = os.O_WRONLY | os.O_CREAT | os.O_TRUNC\n      fd = os.open(self.filename, mode, 0o600)\n      with os.fdopen(fd, \"wb\") as config_file:\n        self.SaveDataToFD(raw_data, config_file)\n    except OSError as e:\n      logging.warning(\"Unable to write config file %s: %s.\", self.filename, e)",
    "docstring": "Store the raw data as our configuration."
  },
  {
    "code": "def float(self, **kwargs):\n        for key in kwargs:\n            setattr(self, key, kwargs[key])\n        self.command = self.COMMAND_FLOAT",
    "docstring": "Remove power from the motor."
  },
  {
    "code": "def _sexagesimalize_to_int(value, places=0):\n    sign = int(np.sign(value))\n    value = abs(value)\n    power = 10 ** places\n    n = int(7200 * power * value + 1) // 2\n    n, fraction = divmod(n, power)\n    n, seconds = divmod(n, 60)\n    n, minutes = divmod(n, 60)\n    return sign, n, minutes, seconds, fraction",
    "docstring": "Decompose `value` into units, minutes, seconds, and second fractions.\n\n    This routine prepares a value for sexagesimal display, with its\n    seconds fraction expressed as an integer with `places` digits.  The\n    result is a tuple of five integers:\n\n    ``(sign [either +1 or -1], units, minutes, seconds, second_fractions)``\n\n    The integers are properly rounded per astronomical convention so\n    that, for example, given ``places=3`` the result tuple ``(1, 11, 22,\n    33, 444)`` means that the input was closer to 11u 22' 33.444\" than\n    to either 33.443\" or 33.445\" in its value."
  },
  {
    "code": "def open_ioc(fn):\n        parsed_xml = xmlutils.read_xml_no_ns(fn)\n        if not parsed_xml:\n            raise IOCParseError('Error occured parsing XML')\n        root = parsed_xml.getroot()\n        metadata_node = root.find('metadata')\n        top_level_indicator = get_top_level_indicator_node(root)\n        parameters_node = root.find('parameters')\n        if parameters_node is None:\n            parameters_node = ioc_et.make_parameters_node()\n            root.append(parameters_node)\n        return root, metadata_node, top_level_indicator, parameters_node",
    "docstring": "Opens an IOC file, or XML string.  Returns the root element, top level\n        indicator element, and parameters element.  If the IOC or string fails\n        to parse, an IOCParseError is raised.\n\n        This is a helper function used by __init__.\n\n        :param fn: This is a path to a file to open, or a string containing XML representing an IOC.\n        :return: a tuple containing three elementTree Element objects\n         The first element, the root, contains the entire IOC itself.\n         The second element, the top level OR indicator, allows the user to add\n          additional IndicatorItem or Indicator nodes to the IOC easily.\n         The third element, the parameters node, allows the user to quickly\n          parse the parameters."
  },
  {
    "code": "async def _load(self, data, check=True):\n        log.debug('Load proxies from the raw data')\n        if isinstance(data, io.TextIOWrapper):\n            data = data.read()\n        if isinstance(data, str):\n            data = IPPortPatternLine.findall(data)\n        proxies = set(data)\n        for proxy in proxies:\n            await self._handle(proxy, check=check)\n        await self._on_check.join()\n        self._done()",
    "docstring": "Looking for proxies in the passed data.\n\n        Transform the passed data from [raw string | file-like object | list]\n        to set {(host, port), ...}: {('192.168.0.1', '80'), }"
  },
  {
    "code": "def list_arguments(self):\n        size = ctypes.c_uint()\n        sarr = ctypes.POINTER(ctypes.c_char_p)()\n        check_call(_LIB.MXSymbolListArguments(\n            self.handle, ctypes.byref(size), ctypes.byref(sarr)))\n        return [py_str(sarr[i]) for i in range(size.value)]",
    "docstring": "Lists all the arguments in the symbol.\n\n        Example\n        -------\n        >>> a = mx.sym.var('a')\n        >>> b = mx.sym.var('b')\n        >>> c = a + b\n        >>> c.list_arguments\n        ['a', 'b']\n\n        Returns\n        -------\n        args : list of string\n            List containing the names of all the arguments required to compute the symbol."
  },
  {
    "code": "def visit_Name(self, node):\n        if isinstance(node.ctx, (ast.Store, ast.Param)):\n            self.result.add(node.id)",
    "docstring": "Any node with Store or Param context is a new identifier."
  },
  {
    "code": "def parse_rule(rule: str, raise_error=False):\n    parser = Parser(raise_error)\n    return parser.parse(rule)",
    "docstring": "Parses policy to a tree of Check objects."
  },
  {
    "code": "def create(url, filename):\n        files = {'file': open(filename, 'rb')}\n        response = requests.post(url, files=files)\n        if response.status_code != 201:\n            raise ValueError('invalid file: ' + filename)\n            return references_to_dict(response.json()['links'])[REF_SELF]",
    "docstring": "Create new fMRI for given experiment by uploading local file.\n        Expects an tar-archive.\n\n        Parameters\n        ----------\n        url : string\n            Url to POST fMRI create request\n        filename : string\n            Path to tar-archive on local disk\n\n        Returns\n        -------\n        string\n            Url of created functional data resource"
  },
  {
    "code": "def _Notify(username, notification_type, message, object_reference):\n  if username in aff4_users.GRRUser.SYSTEM_USERS:\n    return\n  if object_reference:\n    uc = object_reference.UnionCast()\n    if hasattr(uc, \"client_id\"):\n      message = _HostPrefix(uc.client_id) + message\n  n = rdf_objects.UserNotification(\n      username=username,\n      notification_type=notification_type,\n      state=rdf_objects.UserNotification.State.STATE_PENDING,\n      message=message,\n      reference=object_reference)\n  data_store.REL_DB.WriteUserNotification(n)",
    "docstring": "Schedules a new-style REL_DB user notification."
  },
  {
    "code": "def create(cls, data=None, *args, **kwargs):\n        cls.validate(data)\n        getattr(Entity, 'create').__func__(cls, data=data, *args, **kwargs)",
    "docstring": "Validate and then create a Vendor entity."
  },
  {
    "code": "def dump(self, blob, stream):\n        json.dump(\n            blob, stream, indent=self.indent, sort_keys=True,\n            separators=self.separators,\n        )",
    "docstring": "Call json.dump with the attributes of this instance as\n        arguments."
  },
  {
    "code": "def on_accel_cleared(self, cellrendereraccel, path):\n        dconf_path = self.store[path][HOTKET_MODEL_INDEX_DCONF]\n        if dconf_path == \"show-hide\":\n            log.warn(\"Cannot disable 'show-hide' hotkey\")\n            self.settings.keybindingsGlobal.set_string(dconf_path, old_accel)\n        else:\n            self.store[path][HOTKET_MODEL_INDEX_HUMAN_ACCEL] = \"\"\n            self.store[path][HOTKET_MODEL_INDEX_ACCEL] = \"None\"\n            if dconf_path == \"show-focus\":\n                self.settings.keybindingsGlobal.set_string(dconf_path, 'disabled')\n            else:\n                self.settings.keybindingsLocal.set_string(dconf_path, 'disabled')",
    "docstring": "If the user tries to clear a keybinding with the backspace\n        key this callback will be called and it just fill the model\n        with an empty key and set the 'disabled' string in dconf path."
  },
  {
    "code": "def authenticate(self, username, password):\n        r = requests.post(self.apiurl + \"/token\",\n                          params={\"grant_type\": \"password\", \"username\": username, \"password\": password,\n                                  \"client_id\": self.cid, \"client_secret\": self.csecret})\n        if r.status_code != 200:\n            raise ServerError\n        jsd = r.json()\n        if self.remember:\n            self.token_storage[username] = {'token': jsd['access_token'], 'refresh': jsd['refresh_token'],\n                                            'expiration': int(jsd['created_at']) + int(jsd['expires_in'])}\n        return jsd['access_token'], int(jsd['expires_in']) + int(jsd['created_at']), jsd['refresh_token']",
    "docstring": "Obtain an oauth token. Pass username and password. Get a token back. If KitsuAuth is set to remember your tokens\n        for this session, it will store the token under the username given.\n\n        :param username: username\n        :param password: password\n        :param alias: A list of alternative names for a person if using the KitsuAuth token storage\n        :return: A tuple of (token, expiration time in unix time stamp, refresh_token) or ServerError"
  },
  {
    "code": "def read_gps_ifd(fh, byteorder, dtype, count, offsetsize):\n    return read_tags(fh, byteorder, offsetsize, TIFF.GPS_TAGS, maxifds=1)",
    "docstring": "Read GPS tags from file and return as dict."
  },
  {
    "code": "def read(self, fname, psw=None):\n        with self.open(fname, 'r', psw) as f:\n            return f.read()",
    "docstring": "Return uncompressed data for archive entry.\n\n        For longer files using :meth:`RarFile.open` may be better idea.\n\n        Parameters:\n\n            fname\n                filename or RarInfo instance\n            psw\n                password to use for extracting."
  },
  {
    "code": "def gen_WS_DF(df_WS_data):\n    df_fs = gen_FS_DF(df_WS_data)\n    list_index = [('mean', 'T2'), ('max', 'T2'), ('min', 'T2'),\n                  ('mean', 'U10'), ('max', 'U10'), ('min', 'U10'),\n                  ('mean', 'RH2'), ('max', 'RH2'), ('min', 'RH2'),\n                  ('mean', 'Kdown')]\n    list_const = [getattr(const, attr)\n                  for attr in ['T_MEAN', 'T_MAX', 'T_MIN',\n                               'WIND_MEAN', 'WIND_MAX', 'WIND_MIN',\n                               'RH_MEAN', 'RH_MAX', 'RH_MIN',\n                               'SOLAR_RADIATION_GLOBAL']]\n    list_ws = [df_fs.loc[idx] * cst\n               for idx, cst\n               in zip(list_index, list_const)]\n    df_ws = pd.concat(list_ws, axis=1).sum(axis=1).unstack().dropna()\n    return df_ws",
    "docstring": "generate DataFrame of weighted sums.\n\n    Parameters\n    ----------\n    df_WS_data : type\n        Description of parameter `df_WS_data`.\n\n    Returns\n    -------\n    type\n        Description of returned object."
  },
  {
    "code": "def average(self, rows: List[Row], column: NumberColumn) -> Number:\n        cell_values = [row.values[column.name] for row in rows]\n        if not cell_values:\n            return 0.0\n        return sum(cell_values) / len(cell_values)",
    "docstring": "Takes a list of rows and a column and returns the mean of the values under that column in\n        those rows."
  },
  {
    "code": "def name_resolve(self, name=None, recursive=False,\n                     nocache=False, **kwargs):\n        kwargs.setdefault(\"opts\", {\"recursive\": recursive,\n                                   \"nocache\": nocache})\n        args = (name,) if name is not None else ()\n        return self._client.request('/name/resolve', args,\n                                    decoder='json', **kwargs)",
    "docstring": "Gets the value currently published at an IPNS name.\n\n        IPNS is a PKI namespace, where names are the hashes of public keys, and\n        the private key enables publishing new (signed) values. In resolve, the\n        default value of ``name`` is your own identity public key.\n\n        .. code-block:: python\n\n            >>> c.name_resolve()\n            {'Path': '/ipfs/QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d'}\n\n        Parameters\n        ----------\n        name : str\n            The IPNS name to resolve (defaults to the connected node)\n        recursive : bool\n            Resolve until the result is not an IPFS name (default: false)\n        nocache : bool\n            Do not use cached entries (default: false)\n\n        Returns\n        -------\n            dict : The IPFS path the IPNS hash points at"
  },
  {
    "code": "def open_conn(host, db, user, password, retries=0, sleep=0.5):\n    assert retries >= 0\n    try:\n        return MySQLdb.connect(host=host, user=user, passwd=password, db=db)\n    except Exception:\n        if retries > 0:\n            time.sleep(sleep)\n            return open_conn(host, db, user, password, retries - 1, sleep)\n        else:\n            raise",
    "docstring": "Return an open mysql db connection using the given credentials.  Use\n    `retries` and `sleep` to be robust to the occassional transient connection\n    failure.\n\n    retries: if an exception when getting the connection, try again at most this many times.\n    sleep: pause between retries for this many seconds.  a float >= 0."
  },
  {
    "code": "def clone(self, repo, ref, deps=()):\n        if os.path.isdir(repo):\n            repo = os.path.abspath(repo)\n        def clone_strategy(directory):\n            env = git.no_git_env()\n            def _git_cmd(*args):\n                cmd_output('git', *args, cwd=directory, env=env)\n            _git_cmd('init', '.')\n            _git_cmd('remote', 'add', 'origin', repo)\n            try:\n                self._shallow_clone(ref, _git_cmd)\n            except CalledProcessError:\n                self._complete_clone(ref, _git_cmd)\n        return self._new_repo(repo, ref, deps, clone_strategy)",
    "docstring": "Clone the given url and checkout the specific ref."
  },
  {
    "code": "def write_grindstone(self):\n        with open(self.grindstone_path, 'w') as f:\n            f.write(json.dumps(self.grindstone))",
    "docstring": "Writes self.gs to self.grindstone_path."
  },
  {
    "code": "def likelihood(self, outcomes, modelparams, expparams):\n        r\n        self._call_count += (\n            safe_shape(outcomes) * safe_shape(modelparams) * safe_shape(expparams)\n        )",
    "docstring": "r\"\"\"\n        Calculates the probability of each given outcome, conditioned on each\n        given model parameter vector and each given experimental control setting.\n\n        :param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``\n            array of model parameter vectors describing the hypotheses for\n            which the likelihood function is to be calculated.\n        :param np.ndarray expparams: A shape ``(n_experiments, )`` array of\n            experimental control settings, with ``dtype`` given by \n            :attr:`~qinfer.Simulatable.expparams_dtype`, describing the\n            experiments from which the given outcomes were drawn.\n            \n        :rtype: np.ndarray\n        :return: A three-index tensor ``L[i, j, k]``, where ``i`` is the outcome\n            being considered, ``j`` indexes which vector of model parameters was used,\n            and where ``k`` indexes which experimental parameters where used.\n            Each element ``L[i, j, k]`` then corresponds to the likelihood\n            :math:`\\Pr(d_i | \\vec{x}_j; e_k)`."
  },
  {
    "code": "def to_files(self, resource, directory):\n        collections = self.__collect(resource)\n        for (mb_cls, coll) in iteritems_(collections):\n            fn = get_write_collection_path(mb_cls,\n                                           self.__content_type,\n                                           directory=directory)\n            with open_text(os.path.join(directory, fn)) as strm:\n                dump_resource(coll, strm, content_type=self.__content_type)",
    "docstring": "Dumps the given resource and all resources linked to it into a set of\n        representation files in the given directory."
  },
  {
    "code": "def status_code(code):\n    redirect = dict(headers=dict(location=REDIRECT_LOCATION))\n    code_map = {\n        301: redirect,\n        302: redirect,\n        303: redirect,\n        304: dict(data=''),\n        305: redirect,\n        307: redirect,\n        401: dict(headers={'WWW-Authenticate': 'Basic realm=\"Fake Realm\"'}),\n        402: dict(\n            data='Fuck you, pay me!',\n            headers={\n                'x-more-info': 'http://vimeo.com/22053820'\n            }\n        ),\n        406: dict(data=json.dumps({\n                'message': 'Client did not request a supported media type.',\n                'accept': ACCEPTED_MEDIA_TYPES\n            }),\n            headers={\n                'Content-Type': 'application/json'\n            }),\n        407: dict(headers={'Proxy-Authenticate': 'Basic realm=\"Fake Realm\"'}),\n        418: dict(\n            data=ASCII_ART,\n            headers={\n                'x-more-info': 'http://tools.ietf.org/html/rfc2324'\n            }\n        ),\n    }\n    r = make_response()\n    r.status_code = code\n    if code in code_map:\n        m = code_map[code]\n        if 'data' in m:\n            r.data = m['data']\n        if 'headers' in m:\n            r.headers = m['headers']\n    return r",
    "docstring": "Returns response object of given status code."
  },
  {
    "code": "def execute(self, *args, **options):\n        try:\n            super(EmailNotificationCommand, self).execute(*args, **options)\n        except Exception:\n            if options['email_exception'] or getattr(self, 'email_exception', False):\n                self.send_email_notification(include_traceback=True)\n            raise",
    "docstring": "Overriden in order to send emails on unhandled exception.\n\n        If an unhandled exception in ``def handle(self, *args, **options)``\n        occurs and `--email-exception` is set or `self.email_exception` is\n        set to True send an email to ADMINS with the traceback and then\n        reraise the exception."
  },
  {
    "code": "def open(self):\n        self.hwman = HardwareManager(port=self._port)\n        self.opened = True\n        if self._connection_string is not None:\n            try:\n                self.hwman.connect_direct(self._connection_string)\n            except HardwareError:\n                self.hwman.close()\n                raise\n        elif self._connect_id is not None:\n            try:\n                self.hwman.connect(self._connect_id)\n            except HardwareError:\n                self.hwman.close()\n                raise",
    "docstring": "Open and potentially connect to a device."
  },
  {
    "code": "def query_string_attribute(self, target, display_mask, attr):\n    reply = NVCtrlQueryStringAttributeReplyRequest(display=self.display,\n                                                   opcode=self.display.get_extension_major(extname),\n                                                   target_id=target.id(),\n                                                   target_type=target.type(),\n                                                   display_mask=display_mask,\n                                                   attr=attr)\n    if not reply._data.get('flags'):\n        return None\n    return str(reply._data.get('string')).strip('\\0')",
    "docstring": "Return the value of a string attribute"
  },
  {
    "code": "def compute_knot_vector(degree, num_points, params):\n    kv = [0.0 for _ in range(degree + 1)]\n    for i in range(num_points - degree - 1):\n        temp_kv = (1.0 / degree) * sum([params[j] for j in range(i + 1, i + degree + 1)])\n        kv.append(temp_kv)\n    kv += [1.0 for _ in range(degree + 1)]\n    return kv",
    "docstring": "Computes a knot vector from the parameter list using averaging method.\n\n    Please refer to the Equation 9.8 on The NURBS Book (2nd Edition), pp.365 for details.\n\n    :param degree: degree\n    :type degree: int\n    :param num_points: number of data points\n    :type num_points: int\n    :param params: list of parameters, :math:`\\\\overline{u}_{k}`\n    :type params: list, tuple\n    :return: knot vector\n    :rtype: list"
  },
  {
    "code": "def delete(self, task, params={}, **options): \n        path = \"/tasks/%s\" % (task)\n        return self.client.delete(path, params, **options)",
    "docstring": "A specific, existing task can be deleted by making a DELETE request on the\n        URL for that task. Deleted tasks go into the \"trash\" of the user making\n        the delete request. Tasks can be recovered from the trash within a period\n        of 30 days; afterward they are completely removed from the system.\n        \n        Returns an empty data record.\n\n        Parameters\n        ----------\n        task : {Id} The task to delete."
  },
  {
    "code": "def listen(ctx):\n    wva = get_wva(ctx)\n    es = wva.get_event_stream()\n    def cb(event):\n        cli_pprint(event)\n    es.add_event_listener(cb)\n    es.enable()\n    while True:\n        time.sleep(5)",
    "docstring": "Output the contents of the WVA event stream\n\nThis command shows the data being received from the WVA event stream based on\nthe subscriptions that have been set up and the data on the WVA vehicle bus.\n\n\\b\n    $ wva subscriptions listen\n    {'data': {'VehicleSpeed': {'timestamp': '2015-03-25T00:11:53Z',\n                                 'value': 198.272461},\n               'sequence': 124,\n               'short_name': 'speed',\n               'timestamp': '2015-03-25T00:11:53Z',\n               'uri': 'vehicle/data/VehicleSpeed'}}\n    {'data': {'EngineSpeed': {'timestamp': '2015-03-25T00:11:54Z',\n                                'value': 6425.5},\n               'sequence': 274,\n               'short_name': 'rpm',\n               'timestamp': '2015-03-25T00:11:54Z',\n               'uri': 'vehicle/data/EngineSpeed'}}\n    ...\n    ^C\n    Aborted!\n\nThis command can be useful for debugging subscriptions or getting a quick\nglimpse at what data is coming in to a WVA device."
  },
  {
    "code": "def asset(self, id):\n        data = None\n        if int(id) > 0:\n            url = self._build_url('releases', 'assets', str(id),\n                                  base_url=self._api)\n            data = self._json(self._get(url, headers=Release.CUSTOM_HEADERS),\n                              200)\n        return Asset(data, self) if data else None",
    "docstring": "Returns a single Asset.\n\n        :param int id: (required), id of the asset\n        :returns: :class:`Asset <github3.repos.release.Asset>`"
  },
  {
    "code": "def mean_cl_boot(series, n_samples=1000, confidence_interval=0.95,\n                 random_state=None):\n    return bootstrap_statistics(series, np.mean,\n                                n_samples=n_samples,\n                                confidence_interval=confidence_interval,\n                                random_state=random_state)",
    "docstring": "Bootstrapped mean with confidence limits"
  },
  {
    "code": "def assert_not_called(_mock_self):\n        self = _mock_self\n        if self.call_count != 0:\n            msg = (\"Expected '%s' to not have been called. Called %s times.\" %\n                   (self._mock_name or 'mock', self.call_count))\n            raise AssertionError(msg)",
    "docstring": "assert that the mock was never called."
  },
  {
    "code": "def rfc2822_format(val):\n    if isinstance(val, six.string_types):\n        return val\n    elif isinstance(val, (datetime.datetime, datetime.date)):\n        val = time.mktime(val.timetuple())\n    if isinstance(val, numbers.Number):\n        return email.utils.formatdate(val)\n    else:\n        return val",
    "docstring": "Takes either a date, a datetime, or a string, and returns a string that\n    represents the value in RFC 2822 format. If a string is passed it is\n    returned unchanged."
  },
  {
    "code": "def parse_url_to_dict(url):\n    p = urlparse(url)\n    return {\n        'scheme': p.scheme,\n        'netloc': p.netloc,\n        'path': p.path,\n        'params': p.params,\n        'query': p.query,\n        'fragment': p.fragment,\n        'username': p.username,\n        'password': p.password,\n        'hostname': p.hostname,\n        'port': p.port\n    }",
    "docstring": "Parse a url and return a dict with keys for all of the parts.\n\n    The urlparse function() returns a wacky combination of a namedtuple\n    with properties."
  },
  {
    "code": "def delete_project(self):\r\n        if self.current_active_project:\r\n            self.switch_to_plugin()\r\n            path = self.current_active_project.root_path\r\n            buttons = QMessageBox.Yes | QMessageBox.No\r\n            answer = QMessageBox.warning(\r\n                self,\r\n                _(\"Delete\"),\r\n                _(\"Do you really want to delete <b>{filename}</b>?<br><br>\"\r\n                  \"<b>Note:</b> This action will only delete the project. \"\r\n                  \"Its files are going to be preserved on disk.\"\r\n                  ).format(filename=osp.basename(path)),\r\n                buttons)\r\n            if answer == QMessageBox.Yes:\r\n                try:\r\n                    self.close_project()\r\n                    shutil.rmtree(osp.join(path, '.spyproject'))\r\n                except EnvironmentError as error:\r\n                    QMessageBox.critical(\r\n                        self,\r\n                        _(\"Project Explorer\"),\r\n                        _(\"<b>Unable to delete <i>{varpath}</i></b>\"\r\n                          \"<br><br>The error message was:<br>{error}\"\r\n                          ).format(varpath=path, error=to_text_string(error)))",
    "docstring": "Delete the current project without deleting the files in the directory."
  },
  {
    "code": "def real_dtype(self):\n        base = self.base_dtype\n        if base == complex64:\n            return float32\n        elif base == complex128:\n            return float64\n        else:\n            return self",
    "docstring": "Returns the dtype correspond to this dtype's real part."
  },
  {
    "code": "def is_adjacent_before(self, other):\n        if not isinstance(other, TimeInterval):\n            raise TypeError(u\"other is not an instance of TimeInterval\")\n        return (self.end == other.begin)",
    "docstring": "Return ``True`` if this time interval ends\n        when the given other time interval begins.\n\n        :param other: the other interval\n        :type  other: :class:`~aeneas.exacttiming.TimeInterval`\n        :raises TypeError: if ``other`` is not an instance of ``TimeInterval``\n        :rtype: bool"
  },
  {
    "code": "def csd(timeseries, other, segmentlength, noverlap=None, **kwargs):\n    try:\n        freqs, csd_ = scipy.signal.csd(\n            timeseries.value, other.value, noverlap=noverlap,\n            fs=timeseries.sample_rate.decompose().value,\n            nperseg=segmentlength, **kwargs)\n    except AttributeError as exc:\n        exc.args = ('{}, scipy>=0.16 is required'.format(str(exc)),)\n        raise\n    unit = scale_timeseries_unit(timeseries.unit,\n                                 kwargs.get('scaling', 'density'))\n    return FrequencySeries(\n        csd_, unit=unit, frequencies=freqs,\n        name=str(timeseries.name)+'---'+str(other.name),\n        epoch=timeseries.epoch, channel=timeseries.channel)",
    "docstring": "Calculate the CSD of two `TimeSeries` using Welch's method\n\n    Parameters\n    ----------\n    timeseries : `~gwpy.timeseries.TimeSeries`\n        time-series of data\n\n    other : `~gwpy.timeseries.TimeSeries`\n        time-series of data\n\n    segmentlength : `int`\n        number of samples in single average.\n\n    noverlap : `int`\n        number of samples to overlap between segments, defaults to 50%.\n\n    **kwargs\n        other keyword arguments are passed to :meth:`scipy.signal.csd`\n\n    Returns\n    -------\n    spectrum : `~gwpy.frequencyseries.FrequencySeries`\n        average power `FrequencySeries`\n\n    See also\n    --------\n    scipy.signal.csd"
  },
  {
    "code": "def cast_to_seq_record(obj, alphabet=IUPAC.extended_protein, id=\"<unknown id>\", name=\"<unknown name>\",\n                       description=\"<unknown description>\", dbxrefs=None,\n                       features=None, annotations=None,\n                       letter_annotations=None):\n    if isinstance(obj, SeqRecord):\n        return obj\n    if isinstance(obj, Seq):\n        return SeqRecord(obj, id, name, description, dbxrefs, features, annotations, letter_annotations)\n    if isinstance(obj, str):\n        obj = obj.upper()\n        return SeqRecord(Seq(obj, alphabet), id, name, description, dbxrefs, features, annotations, letter_annotations)\n    else:\n        raise ValueError('Must provide a string, Seq, or SeqRecord object.')",
    "docstring": "Return a SeqRecord representation of a string or Seq object.\n\n    Args:\n        obj (str, Seq, SeqRecord): Sequence string or Biopython Seq object\n        alphabet: See Biopython SeqRecord docs\n        id: See Biopython SeqRecord docs\n        name: See Biopython SeqRecord docs\n        description: See Biopython SeqRecord docs\n        dbxrefs: See Biopython SeqRecord docs\n        features: See Biopython SeqRecord docs\n        annotations: See Biopython SeqRecord docs\n        letter_annotations: See Biopython SeqRecord docs\n\n    Returns:\n        SeqRecord: SeqRecord representation of the sequence"
  },
  {
    "code": "def GetAdGroups(self, client_customer_id, campaign_id):\n    self.client.SetClientCustomerId(client_customer_id)\n    selector = {\n        'fields': ['Id', 'Name', 'Status'],\n        'predicates': [\n            {\n                'field': 'CampaignId',\n                'operator': 'EQUALS',\n                'values': [campaign_id]\n            },\n            {\n                'field': 'Status',\n                'operator': 'NOT_EQUALS',\n                'values': ['REMOVED']\n            }\n        ]\n    }\n    adgroups = self.client.GetService('AdGroupService').get(selector)\n    if int(adgroups['totalNumEntries']) > 0:\n      return adgroups['entries']\n    else:\n      return None",
    "docstring": "Retrieves all AdGroups for the given campaign that haven't been removed.\n\n    Args:\n      client_customer_id: str Client Customer Id being used in API request.\n      campaign_id: str id of the campaign for which to fetch ad groups.\n\n    Returns:\n      list List of AdGroup data objects."
  },
  {
    "code": "def flexibility(communities):\n    flex = np.zeros(communities.shape[0])\n    for t in range(1, communities.shape[1]):\n        flex[communities[:, t] != communities[:, t-1]] += 1\n    flex = flex / (communities.shape[1] - 1)\n    return flex",
    "docstring": "Amount a node changes community\n\n    Parameters\n    ----------\n    communities : array\n        Community array of shape (node,time)\n\n    Returns\n    --------\n    flex : array\n        Size with the flexibility of each node.\n\n    Notes\n    -----\n    Flexbility calculates the number of times a node switches its community label during a time series. It is normalized by the number of possible changes which could occur. It is important to make sure that the different community labels accross time points are not artbirary.\n\n    References\n    -----------\n    Bassett, DS, Wymbs N, Porter MA, Mucha P, Carlson JM, Grafton ST. Dynamic reconfiguration of human brain networks during learning. PNAS, 2011, 108(18):7641-6."
  },
  {
    "code": "def get_content_models(self):\n        models = super(PageAdmin, self).get_content_models()\n        order = [name.lower() for name in settings.ADD_PAGE_ORDER]\n        def sort_key(page):\n            name = \"%s.%s\" % (page._meta.app_label, page._meta.object_name)\n            unordered = len(order)\n            try:\n                return (order.index(name.lower()), \"\")\n            except ValueError:\n                return (unordered, page.meta_verbose_name)\n        return sorted(models, key=sort_key)",
    "docstring": "Return all Page subclasses that are admin registered, ordered\n        based on the ``ADD_PAGE_ORDER`` setting."
  },
  {
    "code": "def option_from_wire(otype, wire, current, olen):\n    cls = get_option_class(otype)\n    return cls.from_wire(otype, wire, current, olen)",
    "docstring": "Build an EDNS option object from wire format\n\n    @param otype: The option type\n    @type otype: int\n    @param wire: The wire-format message\n    @type wire: string\n    @param current: The offet in wire of the beginning of the rdata.\n    @type current: int\n    @param olen: The length of the wire-format option data\n    @type olen: int\n    @rtype: dns.ends.Option instance"
  },
  {
    "code": "async def execute(self, dc=None, token=None):\n        token_id = extract_attr(token, keys=[\"ID\"])\n        try:\n            response = await self._api.put(\n                \"/v1/txn\",\n                data=self.operations,\n                params={\n                    \"dc\": dc,\n                    \"token\": token_id\n                })\n        except ConflictError as error:\n            errors = {elt[\"OpIndex\"]: elt for elt in error.value[\"Errors\"]}\n            operations = [op[\"KV\"] for op in self.operations]\n            meta = error.meta\n            raise TransactionError(errors, operations, meta) from error\n        except Exception as error:\n            raise error\n        else:\n            self.operations[:] = []\n        results = []\n        for _ in response.body[\"Results\"]:\n            data = _[\"KV\"]\n            if data[\"Value\"] is not None:\n                data[\"Value\"] = decode_value(data[\"Value\"], data[\"Flags\"])\n            results.append(data)\n        return results",
    "docstring": "Execute stored operations\n\n        Parameters:\n            dc (str): Specify datacenter that will be used.\n                      Defaults to the agent's local datacenter.\n            token (ObjectID): Token ID\n        Returns:\n            Collection: Results of operations.\n        Raises:\n            TransactionError: Transaction failed"
  },
  {
    "code": "def create_view(self, callback, method, request=None):\n        view = super(WaldurSchemaGenerator, self).create_view(callback, method, request)\n        if is_disabled_action(view):\n            view.exclude_from_schema = True\n        return view",
    "docstring": "Given a callback, return an actual view instance."
  },
  {
    "code": "def get_initial_data(self, request, user, profile, client):\n        if INITAL_DATA_FUNCTION:\n            func = self.import_attribute(INITAL_DATA_FUNCTION)\n            return func(request, user, profile, client)\n        return {}",
    "docstring": "Return initial data for the setup form. The function can be\n        controlled with ``SOCIALREGISTRATION_INITIAL_DATA_FUNCTION``.\n\n        :param request: The current request object\n        :param user: The unsaved user object\n        :param profile: The unsaved profile object\n        :param client: The API client"
  },
  {
    "code": "def _get_credentials_from_settings(self):\n        remember_me = CONF.get('main', 'report_error/remember_me')\n        remember_token = CONF.get('main', 'report_error/remember_token')\n        username = CONF.get('main', 'report_error/username', '')\n        if not remember_me:\n            username = ''\n        return username, remember_me, remember_token",
    "docstring": "Get the stored credentials if any."
  },
  {
    "code": "def set_ylim(self, xlims, dx, xscale, reverse=False):\n        self._set_axis_limits('y', xlims, dx, xscale, reverse)\n        return",
    "docstring": "Set y limits for plot.\n\n        This will set the limits for the y axis\n        for the specific plot.\n\n        Args:\n            ylims (len-2 list of floats): The limits for the axis.\n            dy (float): Amount to increment by between the limits.\n            yscale (str): Scale of the axis. Either `log` or `lin`.\n            reverse (bool, optional): If True, reverse the axis tick marks. Default is False."
  },
  {
    "code": "def markAsDelivered(self, thread_id, message_id):\n        data = {\n            \"message_ids[0]\": message_id,\n            \"thread_ids[%s][0]\" % thread_id: message_id,\n        }\n        r = self._post(self.req_url.DELIVERED, data)\n        return r.ok",
    "docstring": "Mark a message as delivered\n\n        :param thread_id: User/Group ID to which the message belongs. See :ref:`intro_threads`\n        :param message_id: Message ID to set as delivered. See :ref:`intro_threads`\n        :return: Whether the request was successful\n        :raises: FBchatException if request failed"
  },
  {
    "code": "def Reset(self):\n    self._displayed = 0\n    self._currentpagelines = 0\n    self._lastscroll = 1\n    self._lines_to_show = self._cli_lines",
    "docstring": "Reset the pager to the top of the text."
  },
  {
    "code": "def reverse(self, query, lang='en', exactly_one=True,\n                timeout=DEFAULT_SENTINEL):\n        lang = lang.lower()\n        params = {\n            'coords': self._coerce_point_to_string(query),\n            'lang': lang.lower(),\n            'key': self.api_key,\n        }\n        url = \"?\".join((self.reverse_api, urlencode(params)))\n        logger.debug(\"%s.reverse: %s\", self.__class__.__name__, url)\n        return self._parse_reverse_json(\n            self._call_geocoder(url, timeout=timeout),\n            exactly_one=exactly_one\n        )",
    "docstring": "Return a `3 words` address by location point. Each point on surface has\n        a `3 words` address, so there's always a non-empty response.\n\n        :param query: The coordinates for which you wish to obtain the 3 word\n            address.\n        :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude,\n            longitude)``, or string as ``\"%(latitude)s, %(longitude)s\"``.\n\n        :param str lang: two character language codes as supported by the\n            API (https://docs.what3words.com/api/v2/#lang).\n\n        :param bool exactly_one: Return one result or a list of results, if\n            available. Due to the address scheme there is always exactly one\n            result for each `3 words` address, so this parameter is rather\n            useless for this geocoder.\n\n            .. versionchanged:: 1.14.0\n               ``exactly_one=False`` now returns a list of a single location.\n               This option wasn't respected before.\n\n        :param int timeout: Time, in seconds, to wait for the geocoding service\n            to respond before raising a :class:`geopy.exc.GeocoderTimedOut`\n            exception. Set this only if you wish to override, on this call\n            only, the value set during the geocoder's initialization.\n\n        :rtype: :class:`geopy.location.Location` or a list of them, if\n            ``exactly_one=False``."
  },
  {
    "code": "def set_status(self, value):\n        if not self._status == value:\n            old = self._status\n            self._status = value\n            logger.info(\"{} changing status from {} to {}\".format(self, old.name, value.name))\n            self._statusChanged(old, value)",
    "docstring": "Set the status of the motor to the specified value if not already set."
  },
  {
    "code": "def is_missing_variable(\n    value_node: ValueNode, variables: Dict[str, Any] = None\n) -> bool:\n    return isinstance(value_node, VariableNode) and (\n        not variables or is_invalid(variables.get(value_node.name.value, INVALID))\n    )",
    "docstring": "Check if `value_node` is a variable not defined in the `variables` dict."
  },
  {
    "code": "def almostequal(first, second, places=7, printit=True):\n    if first == second:\n        return True\n    if round(abs(second - first), places) != 0:\n        if printit:\n            print(round(abs(second - first), places))\n            print(\"notalmost: %s != %s to %i places\" % (first, second, places))\n        return False\n    else:\n        return True",
    "docstring": "Test if two values are equal to a given number of places.\n    This is based on python's unittest so may be covered by Python's\n    license."
  },
  {
    "code": "def parse(self, extent, length, fp, log_block_size):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('Inode is already initialized')\n        self.orig_extent_loc = extent\n        self.data_length = length\n        self.data_fp = fp\n        self.manage_fp = False\n        self.fp_offset = extent * log_block_size\n        self.original_data_location = self.DATA_ON_ORIGINAL_ISO\n        self._initialized = True",
    "docstring": "Parse an existing Inode.  This just saves off the extent for later use.\n\n        Parameters:\n         extent - The original extent that the data lives at.\n        Returns:\n         Nothing."
  },
  {
    "code": "def get_fragment(self, offset):\n        fragment_len = 10\n        s = '%r' % (self.source[offset:offset + fragment_len])\n        if offset + fragment_len < len(self.source):\n            s += '...'\n        return s",
    "docstring": "Get the part of the source which is causing a problem."
  },
  {
    "code": "def handle_reboot(self):\n        self.services.stop_all()\n        try:\n            yield\n        finally:\n            self.wait_for_boot_completion()\n            if self.is_rootable:\n                self.root_adb()\n        self.services.start_all()",
    "docstring": "Properly manage the service life cycle when the device needs to\n        temporarily disconnect.\n\n        The device can temporarily lose adb connection due to user-triggered\n        reboot. Use this function to make sure the services\n        started by Mobly are properly stopped and restored afterwards.\n\n        For sample usage, see self.reboot()."
  },
  {
    "code": "def label(self):\n        for c in self.table.columns:\n            if c.parent == self.name and 'label' in c.valuetype:\n                return PartitionColumn(c, self._partition)",
    "docstring": "Return first child that of the column that is marked as a label"
  },
  {
    "code": "def add_time(data):\n    payload = data['data']\n    updated = data['updated'].date()\n    if updated == date.today():\n        payload['last_updated'] = data['updated'].strftime('today at %H:%M:%S')\n    elif updated >= (date.today() - timedelta(days=1)):\n        payload['last_updated'] = 'yesterday'\n    elif updated >= (date.today() - timedelta(days=7)):\n        payload['last_updated'] = updated.strftime('on %A')\n    else:\n        payload['last_updated'] = updated.strftime('%Y-%m-%d')\n    return payload",
    "docstring": "And a friendly update time to the supplied data.\n\n    Arguments:\n      data (:py:class:`dict`): The response data and its update time.\n\n    Returns:\n      :py:class:`dict`: The data with a friendly update time."
  },
  {
    "code": "def calc_fwhm(img, region, fexpand=3, axis=0):\n    xpregion = expand_region(region, fexpand, fexpand)\n    cslit = img[xpregion]\n    pslit = cslit.mean(axis=axis)\n    x2 = len(pslit)\n    y1, y2 = pslit[0], pslit[-1]\n    mslope = (y2-y1) / x2\n    backstim = mslope*numpy.arange(x2) + y1\n    qslit = pslit-backstim\n    pidx = numpy.argmax(qslit)\n    peak, fwhm = fmod.compute_fwhm_1d_simple(qslit, pidx)\n    return fwhm",
    "docstring": "Compute the FWHM in the direction given by axis"
  },
  {
    "code": "def inspect(self, **kwargs):\n        what = kwargs.pop(\"what\", \"hist\")\n        if what == \"hist\":\n            with self.open_hist() as hist:\n                return hist.plot(**kwargs) if hist else None\n        elif what == \"scf\":\n            relaxation = abiinspect.Relaxation.from_file(self.output_file.path)\n            if \"title\" not in kwargs: kwargs[\"title\"] = str(self)\n            return relaxation.plot(**kwargs) if relaxation is not None else None\n        else:\n            raise ValueError(\"Wrong value for what %s\" % what)",
    "docstring": "Plot the evolution of the structural relaxation with matplotlib.\n\n        Args:\n            what: Either \"hist\" or \"scf\". The first option (default) extracts data\n                from the HIST file and plot the evolution of the structural\n                parameters, forces, pressures and energies.\n                The second option, extracts data from the main output file and\n                plot the evolution of the SCF cycles (etotal, residuals, etc).\n\n        Returns:\n            `matplotlib` figure, None if some error occurred."
  },
  {
    "code": "def freeze(self):\n        remote_path = os.path.join(self.venv, 'requirements.txt')\n        run('{} freeze > {}'.format(self.pip(), remote_path))\n        get(remote_path, self.requirements)",
    "docstring": "Use pip to freeze the requirements and save them to the local\n        requirements.txt file."
  },
  {
    "code": "def dump_json(obj):\n    return simplejson.dumps(obj, ignore_nan=True, default=json_util.default)",
    "docstring": "Dump Python object as JSON string."
  },
  {
    "code": "def exists(self, file_path, check_link=False):\n        if check_link and self.islink(file_path):\n            return True\n        file_path = make_string_path(file_path)\n        if file_path is None:\n            raise TypeError\n        if not file_path:\n            return False\n        if file_path == self.dev_null.name:\n            return not self.is_windows_fs\n        try:\n            if self.is_filepath_ending_with_separator(file_path):\n                return False\n            file_path = self.resolve_path(file_path)\n        except (IOError, OSError):\n            return False\n        if file_path == self.root.name:\n            return True\n        path_components = self._path_components(file_path)\n        current_dir = self.root\n        for component in path_components:\n            current_dir = self._directory_content(current_dir, component)[1]\n            if not current_dir:\n                return False\n        return True",
    "docstring": "Return true if a path points to an existing file system object.\n\n        Args:\n            file_path:  The path to examine.\n\n        Returns:\n            (bool) True if the corresponding object exists.\n\n        Raises:\n            TypeError: if file_path is None."
  },
  {
    "code": "def upload_profiler_report(url, filename, config):\n    try:\n        logger.debug(\"Uploading profiler report to IOpipe\")\n        with open(filename, \"rb\") as data:\n            response = requests.put(url, data=data, timeout=config[\"network_timeout\"])\n        response.raise_for_status()\n    except Exception as e:\n        logger.debug(\"Error while uploading profiler report: %s\", e)\n        if hasattr(e, \"response\"):\n            logger.debug(e.response.content)\n    else:\n        logger.debug(\"Profiler report uploaded successfully\")\n    finally:\n        if os.path.isfile(filename):\n            os.remove(filename)",
    "docstring": "Uploads a profiler report to IOpipe\n\n    :param url: The signed URL\n    :param filename: The profiler report file\n    :param config: The IOpipe config"
  },
  {
    "code": "def make_project(self, executable, target):\n        command = 'make -f ../Makefile -C {0} {1}'.format(SRC_PATH, target)\n        pipe = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT,\n                     env=CHILD_ENV)\n        output = pipe.communicate()[0]\n        if pipe.returncode != 0:\n            raise MakeFailed(output)\n        if not os.path.isfile(os.path.join(SRC_PATH, executable)):\n            raise NonexistentExecutable(output)\n        return output",
    "docstring": "Build the project and verify the executable exists."
  },
  {
    "code": "def _merge_default_values(self):\n        values = self._get_default_values()\n        for key, value in values.items():\n            if not self.data.get(key):\n                self.data[key] = value",
    "docstring": "Merge default values with resource data."
  },
  {
    "code": "def _check_fields(self, x, y):\n\t\tif x is None:\n\t\t\tif self.x is None:\n\t\t\t\tself.err(\n\t\t\t\t\tself._check_fields,\n\t\t\t\t\t\"X field is not set: please specify a parameter\")\n\t\t\t\treturn\n\t\t\tx = self.x\n\t\tif y is None:\n\t\t\tif self.y is None:\n\t\t\t\tself.err(\n\t\t\t\t\tself._check_fields,\n\t\t\t\t\t\"Y field is not set: please specify a parameter\")\n\t\t\t\treturn\n\t\t\ty = self.y\n\t\treturn x, y",
    "docstring": "Check x and y fields parameters and initialize"
  },
  {
    "code": "async def setup(self):\n        try:\n            db = await self.db\n            collections = await db.list_collection_names()\n            created = False\n            if self.table_name not in collections:\n                logger.info(\"Creating MongoDB collection [{}]\".format(self.table_name))\n                await db.create_collection(self.table_name)\n                await db[self.table_name].create_index([(\"target_id\", DESCENDING), (\"post_id\", DESCENDING)])\n                created = True\n            if self.control_table_name and self.control_table_name not in collections:\n                logger.info(\"Creating MongoDB control data collection [{}]\".format(self.control_table_name))\n                await db.create_collection(self.control_table_name)\n                created = True\n            return created\n        except Exception as exc:\n            logger.error(\"[DB] Error when setting up MongoDB collections: {}\".format(exc))\n        return False",
    "docstring": "Setting up MongoDB collections, if they not exist."
  },
  {
    "code": "def priv(x): \n    if x.startswith(u'172.'):\n        return 16 <= int(x.split(u'.')[1]) < 32\n    return x.startswith((u'192.168.', u'10.', u'172.'))",
    "docstring": "Quick and dirty method to find an IP on a private network given a correctly\n    formatted IPv4 quad."
  },
  {
    "code": "def find_column(t):\n    pos = t.lexer.lexpos\n    data = t.lexer.lexdata\n    last_cr = data.rfind('\\n', 0, pos)\n    if last_cr < 0:\n        last_cr = -1\n    column = pos - last_cr\n    return column",
    "docstring": "Get cursor position, based on previous newline"
  },
  {
    "code": "def get_sequence_rule_enablers_by_search(self, sequence_rule_enabler_query, sequence_rule_enabler_search):\n        if not self._can('search'):\n            raise PermissionDenied()\n        return self._provider_session.get_sequence_rule_enablers_by_search(sequence_rule_enabler_query, sequence_rule_enabler_search)",
    "docstring": "Pass through to provider SequenceRuleEnablerSearchSession.get_sequence_rule_enablers_by_search"
  },
  {
    "code": "def validate_tag(self, key, value):\n        if key == 'owner':\n            return validate_email(value, self.partial_owner_match)\n        elif key == self.gdpr_tag:\n            return value in self.gdpr_tag_values\n        else:\n            return True",
    "docstring": "Check whether a tag value is valid\n\n        Args:\n            key: A tag key\n            value: A tag value\n\n        Returns:\n            `(True or False)`\n            A boolean indicating whether or not the value is valid"
  },
  {
    "code": "def request(self, host, handler, request_body, verbose):\n        self.verbose = verbose\n        url = 'http://' + host + handler\n        request = urllib2.Request(url)\n        request.add_data(request_body)\n        request.add_header('User-Agent', self.user_agent)\n        request.add_header('Content-Type', 'text/xml')\n        proxy_handler = urllib2.ProxyHandler()\n        opener = urllib2.build_opener(proxy_handler)\n        fhandle = opener.open(request)\n        return(self.parse_response(fhandle))",
    "docstring": "Send xml-rpc request using proxy"
  },
  {
    "code": "def as_dict(self, voigt=False):\n        input_array = self.voigt if voigt else self\n        d = {\"@module\": self.__class__.__module__,\n             \"@class\": self.__class__.__name__,\n             \"input_array\": input_array.tolist()}\n        if voigt:\n            d.update({\"voigt\": voigt})\n        return d",
    "docstring": "Serializes the tensor object\n\n        Args:\n            voigt (bool): flag for whether to store entries in\n                voigt-notation.  Defaults to false, as information\n                may be lost in conversion.\n\n        Returns (Dict):\n            serialized format tensor object"
  },
  {
    "code": "def get_window_at_mouse(self):\n        window_ret = ctypes.c_ulong(0)\n        _libxdo.xdo_get_window_at_mouse(self._xdo, ctypes.byref(window_ret))\n        return window_ret.value",
    "docstring": "Get the window the mouse is currently over"
  },
  {
    "code": "def ReportLength(cls, header):\n        parsed_header = cls._parse_header(header)\n        auth_size = cls._AUTH_BLOCK_LENGTHS.get(parsed_header.auth_type)\n        if auth_size is None:\n            raise DataError(\"Unknown auth block size in BroadcastReport\")\n        return cls._HEADER_LENGTH + parsed_header.reading_length + auth_size",
    "docstring": "Given a header of HeaderLength bytes, calculate the size of this report.\n\n        Returns:\n            int: The total length of the report including the header that we are passed."
  },
  {
    "code": "def from_gpx(gpx_segment):\n        points = []\n        for point in gpx_segment.points:\n            points.append(Point.from_gpx(point))\n        return Segment(points)",
    "docstring": "Creates a segment from a GPX format.\n\n        No preprocessing is done.\n\n        Arguments:\n            gpx_segment (:obj:`gpxpy.GPXTrackSegment`)\n        Return:\n            :obj:`Segment`"
  },
  {
    "code": "def add_bgp_error_metadata(code, sub_code, def_desc='unknown'):\n    if _EXCEPTION_REGISTRY.get((code, sub_code)) is not None:\n        raise ValueError('BGPSException with code %d and sub-code %d '\n                         'already defined.' % (code, sub_code))\n    def decorator(subclass):\n        if issubclass(subclass, BGPSException):\n            _EXCEPTION_REGISTRY[(code, sub_code)] = subclass\n            subclass.CODE = code\n            subclass.SUB_CODE = sub_code\n            subclass.DEF_DESC = def_desc\n        return subclass\n    return decorator",
    "docstring": "Decorator for all exceptions that want to set exception class meta-data."
  },
  {
    "code": "def map_metabolite2kegg(metabolite):\n    logger.debug(\"Looking for KEGG compound identifier for %s.\", metabolite.id)\n    kegg_annotation = metabolite.annotation.get(\"kegg.compound\")\n    if kegg_annotation is None:\n        logger.warning(\"No kegg.compound annotation for metabolite %s.\",\n                       metabolite.id)\n        return\n    if isinstance(kegg_annotation, string_types) and \\\n            kegg_annotation.startswith(\"C\"):\n        return kegg_annotation\n    elif isinstance(kegg_annotation, Iterable):\n        try:\n            return get_smallest_compound_id(kegg_annotation)\n        except ValueError:\n            return\n    logger.warning(\n        \"No matching kegg.compound annotation for metabolite %s.\",\n        metabolite.id\n    )\n    return",
    "docstring": "Return a KEGG compound identifier for the metabolite if it exists.\n\n    First see if there is an unambiguous mapping to a single KEGG compound ID\n    provided with the model. If not, check if there is any KEGG compound ID in\n    a list of mappings. KEGG IDs may map to compounds, drugs and glycans. KEGG\n    compound IDs are sorted so we keep the lowest that is there. If none of\n    this works try mapping to KEGG via the CompoundMatcher by the name of the\n    metabolite. If the metabolite cannot be mapped at all we simply map it back\n    to its own ID.\n\n    Parameters\n    ----------\n    metabolite : cobra.Metabolite\n        The metabolite to be mapped to its KEGG compound identifier.\n\n    Returns\n    -------\n    None\n        If the metabolite could not be mapped.\n    str\n        The smallest KEGG compound identifier that was found."
  },
  {
    "code": "def uncheck_all_local(self):\n        for buttons in self.event['local'].values():\n            if not buttons[0].get_value():\n                self.event['global']['all_local'].setChecked(False)\n            if buttons[1].isEnabled() and not buttons[1].get_value():\n                self.event['global']['all_local_prep'].setChecked(False)",
    "docstring": "Uncheck 'all local' box when a local event is unchecked."
  },
  {
    "code": "def make_psf_kernel(psf, npix, cdelt, xpix, ypix, psf_scale_fn=None, normalize=False):\n    egy = psf.energies\n    x = make_pixel_distance(npix, xpix, ypix)\n    x *= cdelt\n    k = np.zeros((len(egy), npix, npix))\n    for i in range(len(egy)):\n        k[i] = psf.eval(i, x, scale_fn=psf_scale_fn)\n    if normalize:\n        k /= (np.sum(k, axis=0)[np.newaxis, ...] * np.radians(cdelt) ** 2)\n    return k",
    "docstring": "Generate a kernel for a point-source.\n\n    Parameters\n    ----------\n\n    psf : `~fermipy.irfs.PSFModel`\n\n    npix : int\n        Number of pixels in X and Y dimensions.\n\n    cdelt : float\n        Pixel size in degrees."
  },
  {
    "code": "def get(self, blc=(), trc=(), inc=()):\n        return nma.masked_array(self.getdata(blc, trc, inc),\n                                self.getmask(blc, trc, inc))",
    "docstring": "Get image data and mask.\n\n        Get the image data and mask (see ::func:`getdata` and :func:`getmask`)\n        as a numpy masked array."
  },
  {
    "code": "def get_credentials(self, **kwargs):\n        login = (\n            kwargs.get(\"user\") or os.environ.get(\"POLARION_USERNAME\") or self.config.get(\"username\")\n        )\n        pwd = (\n            kwargs.get(\"password\")\n            or os.environ.get(\"POLARION_PASSWORD\")\n            or self.config.get(\"password\")\n        )\n        if not all([login, pwd]):\n            raise Dump2PolarionException(\"Failed to submit to Polarion - missing credentials\")\n        self.credentials = (login, pwd)",
    "docstring": "Sets credentails."
  },
  {
    "code": "def get_child_vaults(self, vault_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.get_child_catalogs(catalog_id=vault_id)\n        return VaultLookupSession(\n            self._proxy,\n            self._runtime).get_vaults_by_ids(\n                list(self.get_child_vault_ids(vault_id)))",
    "docstring": "Gets the children of the given vault.\n\n        arg:    vault_id (osid.id.Id): the ``Id`` to query\n        return: (osid.authorization.VaultList) - the children of the\n                vault\n        raise:  NotFound - ``vault_id`` is not found\n        raise:  NullArgument - ``vault_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _create_keywords_wizard_action(self):\n        icon = resources_path('img', 'icons', 'show-keyword-wizard.svg')\n        self.action_keywords_wizard = QAction(\n            QIcon(icon),\n            self.tr('Keywords Creation Wizard'),\n            self.iface.mainWindow())\n        self.action_keywords_wizard.setStatusTip(self.tr(\n            'Open InaSAFE keywords creation wizard'))\n        self.action_keywords_wizard.setWhatsThis(self.tr(\n            'Open InaSAFE keywords creation wizard'))\n        self.action_keywords_wizard.setEnabled(False)\n        self.action_keywords_wizard.triggered.connect(\n            self.show_keywords_wizard)\n        self.add_action(self.action_keywords_wizard, add_to_legend=True)",
    "docstring": "Create action for keywords creation wizard."
  },
  {
    "code": "def _init_view(self):\n        views_engine = get_config('rails.views.engine', 'jinja')\n        templates_dir = os.path.join(self._project_dir, \"views\", \"templates\")\n        self._view = View(views_engine, templates_dir)",
    "docstring": "Initialize View with project settings."
  },
  {
    "code": "def __get_all_lowpoints(dfs_data):\n    lowpoint_1_lookup = {}\n    lowpoint_2_lookup = {}\n    ordering = dfs_data['ordering']\n    for node in ordering:\n        low_1, low_2 = __get_lowpoints(node, dfs_data)\n        lowpoint_1_lookup[node] = low_1\n        lowpoint_2_lookup[node] = low_2\n    return lowpoint_1_lookup, lowpoint_2_lookup",
    "docstring": "Calculates the lowpoints for each node in a graph."
  },
  {
    "code": "def contains(self, location):\n    for i, coord in enumerate(location):\n      if self.almostEqual(abs(coord), self.dimensions[i] / 2.):\n        return True\n    return False",
    "docstring": "A location is on the box if one of the dimension is \"satured\")."
  },
  {
    "code": "def create_result(self, env_name, other_val, meta, val, dividers):\n        args = [env_name]\n        if other_val is NotSpecified:\n            other_val = None\n        if not dividers:\n            args.extend([None, None])\n        elif dividers[0] == ':':\n            args.extend([other_val, None])\n        elif dividers[0] == '=':\n            args.extend([None, other_val])\n        return Environment(*args)",
    "docstring": "Set default_val and set_val depending on the seperator"
  },
  {
    "code": "def write(self, data, size=-1):\n        try:\n            data = self._ffi.from_buffer(data)\n        except TypeError:\n            pass\n        if size < 0:\n            size, rest = divmod(self._ffi.sizeof(data), self.elementsize)\n            if rest:\n                raise ValueError('data size must be multiple of elementsize')\n        return self._lib.PaUtil_WriteRingBuffer(self._ptr, data, size)",
    "docstring": "Write data to the ring buffer.\n\n        This advances the write index after writing;\n        calling :meth:`advance_write_index` is *not* necessary.\n\n        :param data: Data to write to the buffer.\n        :type data: CData pointer or buffer or bytes\n        :param size: The number of elements to be written.\n        :type size: int, optional\n\n        :returns: The number of elements written.\n        :rtype: int"
  },
  {
    "code": "def stop(self):\n        BufferedReader.stop(self)\n        self._stop_running_event.set()\n        self._writer_thread.join()\n        BaseIOHandler.stop(self)",
    "docstring": "Stops the reader an writes all remaining messages to the database. Thus, this\n        might take a while and block."
  },
  {
    "code": "def calculate_matrices(states, Omega=1):\n    r\n    iso = states[0].isotope\n    element = states[0].element\n    for state in states[1:]:\n        if state.element != element:\n            raise ValueError('All states must belong to the same element.')\n        if state.isotope != iso:\n            raise ValueError('All states must belong to the same isotope.')\n    fine_states = find_fine_states(states)\n    full_magnetic_states = make_list_of_states(fine_states, 'magnetic',\n                                               verbose=0)\n    omega_full = calculate_omega_matrix(full_magnetic_states, Omega)\n    gamma_full = calculate_gamma_matrix(full_magnetic_states, Omega)\n    reduced_matrix_elements = calculate_reduced_matrix_elements(fine_states)\n    r_full = calculate_r_matrices(fine_states, reduced_matrix_elements)\n    omega = omega_full\n    r = r_full\n    gamma = gamma_full\n    return omega, gamma, r",
    "docstring": "r\"\"\"Calculate the matrices omega_ij, gamma_ij, r_pij.\n\n    This function calculates the matrices omega_ij, gamma_ij and r_pij given a\n    list of atomic states. The states can be arbitrarily in their fine,\n    hyperfine or magnetic detail."
  },
  {
    "code": "def unshare(flags):\n    res = lib.unshare(flags)\n    if res != 0:\n        _check_error(ffi.errno)",
    "docstring": "Disassociate parts of the process execution context.\n\n    :param flags int: A bitmask that specifies which parts of the execution\n        context should be unshared."
  },
  {
    "code": "def number_of_trajectories(self, stride=None):\n        r\n        if not IteratorState.is_uniform_stride(stride):\n            n = len(np.unique(stride[:, 0]))\n        else:\n            n = self.ntraj\n        return n",
    "docstring": "r\"\"\" Returns the number of trajectories.\n\n        Parameters\n        ----------\n        stride: None (default) or np.ndarray\n\n        Returns\n        -------\n            int : number of trajectories"
  },
  {
    "code": "def get_stop_words(self, language, fail_safe=False):\n        try:\n            language = self.language_codes[language]\n        except KeyError:\n            pass\n        collection = self.LOADED_LANGUAGES_CACHE.get(language)\n        if collection is None:\n            try:\n                collection = self._get_stop_words(language)\n                self.LOADED_LANGUAGES_CACHE[language] = collection\n            except StopWordError as error:\n                if not fail_safe:\n                    raise error\n                collection = []\n        stop_words = StopWord(language, collection)\n        return stop_words",
    "docstring": "Returns a StopWord object initialized with the stop words collection\n        requested by ``language``.\n        If the requested language is not available a StopWordError is raised.\n        If ``fail_safe`` is set to True, an empty StopWord object is returned."
  },
  {
    "code": "def construct(generator, subtopic):\n        type = subtopic[3]\n        if type not in Item.constructors:\n            raise LookupError(type)\n        return Item.constructors[type](generator, subtopic)",
    "docstring": "Method constructor of Item-derived classes.\n\n        Given a subtopic tuple, this method attempts to construct an\n        Item-derived class, currently either ItemText or ItemImage, from the\n        subtopic's type, found in its 4th element.\n\n        :param generator: Reference to the owning ReportGenerator instance\n        :param subtopic: Tuple containing content_id, meta_url, subtopic_id,\n        type and type-specific data.\n\n        :returns An instantiated Item-derived class."
  },
  {
    "code": "def get_perms(self, username):\n        account = self.get_account(username)\n        return account and account.get_perms()",
    "docstring": "return user permissions"
  },
  {
    "code": "def invoke_in_mainloop(func, *args, **kwargs):\n    results = queue.Queue()\n    @gcall\n    def run():\n        try:\n            data = func(*args, **kwargs)\n            results.put(data)\n            results.put(None)\n        except BaseException:\n            results.put(None)\n            results.put(sys.exc_info())\n            raise\n    data = results.get()\n    exception = results.get()\n    if exception is None:\n        return data\n    else:\n        tp, val, tb = results.get()\n        raise tp, val, tb",
    "docstring": "Invoke a function in the mainloop, pass the data back."
  },
  {
    "code": "def get_adapted_session(adapter):\n        session = requests.Session()\n        session.mount(\"http://\", adapter)\n        session.mount(\"https://\", adapter)\n        return session",
    "docstring": "Mounts an adapter capable of communication over HTTP or HTTPS to the supplied session.\n\n        :param adapter:\n            A :class:`requests.adapters.HTTPAdapter` instance\n        :return:\n            The adapted :class:`requests.Session` instance"
  },
  {
    "code": "def _fetch_router_chunk_data(self, router_ids=None):\n        curr_router = []\n        if len(router_ids) > self.sync_routers_chunk_size:\n            for i in range(0, len(router_ids),\n                           self.sync_routers_chunk_size):\n                routers = self.plugin_rpc.get_routers(\n                                self.context, (router_ids[i:i +\n                                               self.sync_routers_chunk_size]))\n                LOG.debug('Processing :%r', routers)\n                for r in routers:\n                    curr_router.append(r)\n        else:\n            curr_router = self.plugin_rpc.get_routers(\n                self.context, router_ids=router_ids)\n        return curr_router",
    "docstring": "Fetch router data from the routing plugin in chunks.\n\n                :param router_ids: List of router_ids of routers to fetch\n                :return: List of router dicts of format:\n                         [ {router_dict1}, {router_dict2},.....]"
  },
  {
    "code": "def make_file_cm(filename, mode='a'):\n    @contextlib.contextmanager\n    def cm():\n        with open(filename, mode=mode) as fh:\n            yield fh\n    return cm",
    "docstring": "Open a file for appending and yield the open filehandle.  Close the \n    filehandle after yielding it.  This is useful for creating a context\n    manager for logging the output of a `Vagrant` instance.\n\n    filename: a path to a file\n    mode: The mode in which to open the file.  Defaults to 'a', append\n\n    Usage example:\n\n        log_cm = make_file_cm('application.log')\n        v = Vagrant(out_cm=log_cm, err_cm=log_cm)"
  },
  {
    "code": "def to_json(value, **kwargs):\n        serial_list = [\n            val.serialize(**kwargs) if isinstance(val, HasProperties)\n            else val for val in value\n        ]\n        return serial_list",
    "docstring": "Return a copy of the tuple as a list\n\n        If the tuple contains HasProperties instances, they are serialized."
  },
  {
    "code": "def execute(self, *args, **kwargs):\n        args = self.parser.parse_args(*args, **kwargs)\n        self.process(args)",
    "docstring": "Initializes and runs the tool.\n\n        This is shorhand to parse command line arguments, then calling:\n            self.setup(parsed_arguments)\n            self.process()"
  },
  {
    "code": "def get_alert_community(self, channel=None):\n        if channel is None:\n            channel = self.get_network_channel()\n        rsp = self.xraw_command(netfn=0xc, command=2, data=(channel, 16, 0, 0))\n        return rsp['data'][1:].partition('\\x00')[0]",
    "docstring": "Get the current community string for alerts\n\n        Returns the community string that will be in SNMP traps from this\n        BMC\n\n        :param channel: The channel to get configuration for, autodetect by\n                        default\n        :returns: The community string"
  },
  {
    "code": "def doWaitWebRequest(url, method=\"GET\", data=None, headers={}):\n    completed = False\n    while not completed:\n        completed = True\n        try:\n            response, content = doWebRequest(url, method, data, headers)\n        except urllib2.URLError:\n            completed = False\n            waitForURL(url)\n    return response, content",
    "docstring": "Same as doWebRequest, but with built in wait-looping"
  },
  {
    "code": "def is_visit_primitive(obj):\n    from .base import visit\n    if (isinstance(obj, tuple(PRIMITIVE_TYPES)) and not isinstance(obj, STR)\n        and not isinstance(obj, bytes)):\n        return True\n    if (isinstance(obj, CONTAINERS) and not isinstance(obj, STR) and not\n        isinstance(obj, bytes)):\n        return False\n    if isinstance(obj, STR) or isinstance(obj, bytes):\n        if len(obj) == 1:\n            return True\n        return False\n    return list(visit(obj, max_enum=2)) == [obj]",
    "docstring": "Returns true if properly visiting the object returns only the object itself."
  },
  {
    "code": "def finish(self):\n        self.update(self.maxval)\n        if self.signal_set:\n            signal.signal(signal.SIGWINCH, signal.SIG_DFL)",
    "docstring": "Used to tell the progress is finished."
  },
  {
    "code": "def fulfill_access_secret_store_condition(event, agreement_id, did, service_agreement,\n                                          consumer_address, publisher_account):\n    logger.debug(f\"release reward after event {event}.\")\n    name_to_parameter = {param.name: param for param in\n                         service_agreement.condition_by_name['accessSecretStore'].parameters}\n    document_id = add_0x_prefix(name_to_parameter['_documentId'].value)\n    asset_id = add_0x_prefix(did_to_id(did))\n    assert document_id == asset_id, f'document_id {document_id} <=> asset_id {asset_id} mismatch.'\n    try:\n        tx_hash = Keeper.get_instance().access_secret_store_condition.fulfill(\n            agreement_id, document_id, consumer_address, publisher_account\n        )\n        process_tx_receipt(\n            tx_hash,\n            Keeper.get_instance().access_secret_store_condition.FULFILLED_EVENT,\n            'AccessSecretStoreCondition.Fulfilled'\n        )\n    except Exception as e:\n        raise e",
    "docstring": "Fulfill the access condition.\n\n    :param event: AttributeDict with the event data.\n    :param agreement_id: id of the agreement, hex str\n    :param did: DID, str\n    :param service_agreement: ServiceAgreement instance\n    :param consumer_address: ethereum account address of consumer, hex str\n    :param publisher_account: Account instance of the publisher"
  },
  {
    "code": "def open(self, name, *args, **kwargs):\n        if self.basedir is not None:\n            name = os.path.join(self.basedir, name)\n        return em.Subsystem.open(self, name, *args, **kwargs)",
    "docstring": "Open file, possibly relative to a base directory."
  },
  {
    "code": "def publish_post(self):\n        payload = {'content': self.content_base64.decode('utf-8')}\n        sha_blob = self.get_sha_blob()\n        if sha_blob:\n            commit_msg = 'ghPublish UPDATE: {}'.format(self.title)\n            payload.update(sha=sha_blob)\n            payload.update(message=commit_msg)\n        else:\n            commit_msg = 'ghPublish ADD: {}'.format(self.title)\n            payload.update(message=commit_msg)\n        r = requests.put(self.api_url,\n                         auth=self.get_auth_details(),\n                         data=json.dumps(payload))\n        try:\n            url = r.json()['content']['html_url']\n            return r.status_code, url\n        except KeyError:\n            return r.status_code, None",
    "docstring": "If it's a new file, add it.\n        Else, update it."
  },
  {
    "code": "def _get_form_defaults(self):\n        return {\n            'response_format': 'html',\n            'geometry_type': 'esriGeometryPoint',\n            'projection': pyproj.Proj(str(self.service.projection)),\n            'return_geometry': True,\n            'maximum_allowable_offset': 2,\n            'geometry_precision': 3,\n            'return_z': False,\n            'return_m': False\n        }",
    "docstring": "Returns default values for the identify form"
  },
  {
    "code": "def constrain_cfgdict_list(cfgdict_list_, constraint_func):\n    cfgdict_list = []\n    for cfg_ in cfgdict_list_:\n        cfg = cfg_.copy()\n        if constraint_func(cfg) is not False and len(cfg) > 0:\n            if cfg not in cfgdict_list:\n                cfgdict_list.append(cfg)\n    return cfgdict_list",
    "docstring": "constrains configurations and removes duplicates"
  },
  {
    "code": "def use_quandl_data(self, authtoken):\n        dfs = {}\n        st = self.start.strftime(\"%Y-%m-%d\")\n        at = authtoken\n        for pair in self.pairs:\n            symbol = \"\".join(pair)\n            qsym = \"CURRFX/{}\".format(symbol)\n            dfs[symbol] = qdl.get(qsym,authtoken=at, trim_start=st)['Rate']\n        self.build_conversion_table(dfs)",
    "docstring": "Use quandl data to build conversion table"
  },
  {
    "code": "def highlight_matches(self):\r\n        if self.is_code_editor and self.highlight_button.isChecked():\r\n            text = self.search_text.currentText()\r\n            words = self.words_button.isChecked()\r\n            regexp = self.re_button.isChecked()\r\n            self.editor.highlight_found_results(text, words=words,\r\n                                                regexp=regexp)",
    "docstring": "Highlight found results"
  },
  {
    "code": "def connect_to_apple_tv(details, loop, protocol=None, session=None):\n    service = _get_service_used_to_connect(details, protocol)\n    if session is None:\n        session = ClientSession(loop=loop)\n    airplay = _setup_airplay(loop, session, details)\n    if service.protocol == PROTOCOL_DMAP:\n        return DmapAppleTV(loop, session, details, airplay)\n    return MrpAppleTV(loop, session, details, airplay)",
    "docstring": "Connect and logins to an Apple TV."
  },
  {
    "code": "def read(self):\n        try:\n            buf = os.read(self._fd, 8)\n        except OSError as e:\n            raise LEDError(e.errno, \"Reading LED brightness: \" + e.strerror)\n        try:\n            os.lseek(self._fd, 0, os.SEEK_SET)\n        except OSError as e:\n            raise LEDError(e.errno, \"Rewinding LED brightness: \" + e.strerror)\n        return int(buf)",
    "docstring": "Read the brightness of the LED.\n\n        Returns:\n            int: Current brightness.\n\n        Raises:\n            LEDError: if an I/O or OS error occurs."
  },
  {
    "code": "def update_contact(self, um_from_user, um_to_user, message):\n        contact, created = self.get_or_create(um_from_user,\n                                              um_to_user,\n                                              message)\n        if not created:\n            contact.latest_message = message\n            contact.save()\n        return contact",
    "docstring": "Get or update a contacts information"
  },
  {
    "code": "def add_def(self, def_item):\n        self.defs.append(def_item)\n        for other in self.others:\n            other.add_def(def_item)",
    "docstring": "Adds a def universally."
  },
  {
    "code": "def create_knowledge_base(self,\n                              parent,\n                              knowledge_base,\n                              retry=google.api_core.gapic_v1.method.DEFAULT,\n                              timeout=google.api_core.gapic_v1.method.DEFAULT,\n                              metadata=None):\n        if 'create_knowledge_base' not in self._inner_api_calls:\n            self._inner_api_calls[\n                'create_knowledge_base'] = google.api_core.gapic_v1.method.wrap_method(\n                    self.transport.create_knowledge_base,\n                    default_retry=self._method_configs[\n                        'CreateKnowledgeBase'].retry,\n                    default_timeout=self._method_configs['CreateKnowledgeBase']\n                    .timeout,\n                    client_info=self._client_info,\n                )\n        request = knowledge_base_pb2.CreateKnowledgeBaseRequest(\n            parent=parent,\n            knowledge_base=knowledge_base,\n        )\n        return self._inner_api_calls['create_knowledge_base'](\n            request, retry=retry, timeout=timeout, metadata=metadata)",
    "docstring": "Creates a knowledge base.\n\n        Example:\n            >>> import dialogflow_v2beta1\n            >>>\n            >>> client = dialogflow_v2beta1.KnowledgeBasesClient()\n            >>>\n            >>> parent = client.project_path('[PROJECT]')\n            >>>\n            >>> # TODO: Initialize ``knowledge_base``:\n            >>> knowledge_base = {}\n            >>>\n            >>> response = client.create_knowledge_base(parent, knowledge_base)\n\n        Args:\n            parent (str): Required. The agent to create a knowledge base for.\n                Format: ``projects/<Project ID>/agent``.\n            knowledge_base (Union[dict, ~google.cloud.dialogflow_v2beta1.types.KnowledgeBase]): Required. The knowledge base to create.\n                If a dict is provided, it must be of the same form as the protobuf\n                message :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase`\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.dialogflow_v2beta1.types.KnowledgeBase` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def remove_network(self, action, n_name, **kwargs):\n        c_kwargs = self.get_network_remove_kwargs(action, n_name, **kwargs)\n        res = action.client.remove_network(**c_kwargs)\n        del self._policy.network_names[action.client_name][n_name]\n        return res",
    "docstring": "Removes a network.\n\n        :param action: Action configuration.\n        :type action: dockermap.map.runner.ActionConfig\n        :param n_name: Network name or id.\n        :type n_name: unicode | str\n        :param kwargs: Additional keyword arguments.\n        :type kwargs: dict"
  },
  {
    "code": "def update_state_from_api(self):\n        if self.last_api_call is not None:\n            difference = (datetime.datetime.now() - self.last_api_call).seconds\n        else:\n            difference = 301\n        if difference >= 300:\n            url = BASE_URL + \"/rest/item\"\n            payload = {'usertoken': self.token}\n            arequest = requests.get(url, params=payload)\n            status = str(arequest.status_code)\n            if status == '401':\n                _LOGGER.info(\"Token expired? Trying to get a new one.\")\n                self.authenticate(True)\n                arequest = requests.get(url, params=payload)\n                status = arequest.status_code\n            elif status == '404':\n                _LOGGER.error(\"No devices associated with this account.\")\n            elif status != '200':\n                _LOGGER.error(\"API error not updating state. \" + status)\n            else:\n                self.state = arequest.json()\n            self.last_api_call = datetime.datetime.now()\n            _LOGGER.info(\"Pulled latest state from API.\")",
    "docstring": "Pull and update the current state from the API."
  },
  {
    "code": "def create(cls, entry):\n        try:\n            module = import_module(entry)\n        except ImportError:\n            module = None\n            mod_path, _, cls_name = entry.rpartition('.')\n            if not mod_path:\n                raise\n        else:\n            try:\n                entry = module.default_bot\n            except AttributeError:\n                return cls(f'{entry}.Bot', module)\n            else:\n                mod_path, _, cls_name = entry.rpartition('.')\n        mod = import_module(mod_path)\n        try:\n            bot_cls = getattr(mod, cls_name)\n        except AttributeError:\n            if module is None:\n                import_module(entry)\n            raise\n        if not issubclass(bot_cls, Bot):\n            raise ImproperlyConfigured(\n                \"'%s' isn't a subclass of Bot.\" % entry)\n        return cls(entry, mod, bot_cls.label)",
    "docstring": "Factory that creates an bot config from an entry in INSTALLED_APPS."
  },
  {
    "code": "def from_bundle(cls, b, feature):\n        feature_ps = b.get_feature(feature)\n        freq = feature_ps.get_value('freq', unit=u.d**-1)\n        radamp = feature_ps.get_value('radamp', unit=u.dimensionless_unscaled)\n        l = feature_ps.get_value('l', unit=u.dimensionless_unscaled)\n        m = feature_ps.get_value('m', unit=u.dimensionless_unscaled)\n        teffext = feature_ps.get_value('teffext')\n        GM = c.G.to('solRad3 / (solMass d2)').value*b.get_value(qualifier='mass', component=feature_ps.component, context='component', unit=u.solMass)\n        R = b.get_value(qualifier='rpole', component=feature_ps.component, section='component', unit=u.solRad)\n        tanamp = GM/R**3/freq**2\n        return cls(radamp, freq, l, m, tanamp, teffext)",
    "docstring": "Initialize a Pulsation feature from the bundle."
  },
  {
    "code": "def graph_from_edges(edges):\n    M = nx.MultiGraph()\n    for e in edges:\n        n0, n1, weight, key = e\n        M.add_edge(n0, n1, weight=weight, key=key)\n    return M",
    "docstring": "Constructs an undirected multigraph from a list containing data on\n    weighted edges.\n\n    Parameters\n    ----------\n    edges : list\n        List of tuples each containing first node, second node, weight, key.\n\n    Returns\n    -------\n    M : :class:`networkx.classes.multigraph.MultiGraph"
  },
  {
    "code": "def as_dataframe(self, pattern='*', max_rows=None):\n    data = []\n    for i, group in enumerate(self.list(pattern)):\n      if max_rows is not None and i >= max_rows:\n        break\n      parent = self._group_dict.get(group.parent_id)\n      parent_display_name = '' if parent is None else parent.display_name\n      data.append([\n          group.id, group.display_name, group.parent_id,\n          parent_display_name, group.is_cluster, group.filter])\n    return pandas.DataFrame(data, columns=self._DISPLAY_HEADERS)",
    "docstring": "Creates a pandas dataframe from the groups that match the filters.\n\n    Args:\n      pattern: An optional pattern to further filter the groups. This can\n          include Unix shell-style wildcards. E.g. ``\"Production *\"``,\n          ``\"*-backend\"``.\n      max_rows: The maximum number of groups to return. If None, return all.\n\n    Returns:\n      A pandas dataframe containing matching groups."
  },
  {
    "code": "def keyPressEvent(self, event):\r\n        if event.key() == Qt.Key_Down:\r\n            self.select_row(1)\r\n        elif event.key() == Qt.Key_Up:\r\n            self.select_row(-1)",
    "docstring": "Reimplement Qt method to allow cyclic behavior."
  },
  {
    "code": "def set_cache_value(self, name, value):\n        dev_info = self.json_state.get('deviceInfo')\n        if dev_info.get(name.lower()) is None:\n            logger.error(\"Could not set %s for %s (key does not exist).\",\n                      name, self.name)\n            logger.error(\"- dictionary %s\", dev_info)\n            return\n        dev_info[name.lower()] = str(value)",
    "docstring": "Set a variable in the local state dictionary.\n\n        This does not change the physical device. Useful if you want the\n        device state to refect a new value which has not yet updated drom\n        Vera."
  },
  {
    "code": "def get_all_database_accessions(chebi_ids):\n    all_database_accessions = [get_database_accessions(chebi_id)\n                               for chebi_id in chebi_ids]\n    return [x for sublist in all_database_accessions for x in sublist]",
    "docstring": "Returns all database accessions"
  },
  {
    "code": "def remove_obsolete_folders(states, path):\n    elements_in_folder = os.listdir(path)\n    state_folders_in_file_system = []\n    for folder_name in elements_in_folder:\n        if os.path.exists(os.path.join(path, folder_name, FILE_NAME_CORE_DATA)) or \\\n                os.path.exists(os.path.join(path, folder_name, FILE_NAME_CORE_DATA_OLD)):\n            state_folders_in_file_system.append(folder_name)\n    for state in states:\n        storage_folder_for_state = get_storage_id_for_state(state)\n        if storage_folder_for_state in state_folders_in_file_system:\n            state_folders_in_file_system.remove(storage_folder_for_state)\n    for folder_name in state_folders_in_file_system:\n        shutil.rmtree(os.path.join(path, folder_name))",
    "docstring": "Removes obsolete state machine folders\n\n    This function removes all folders in the file system folder `path` that do not belong to the states given by\n    `states`.\n    \n    :param list states: the states that should reside in this very folder\n    :param str path: the file system path to be checked for valid folders"
  },
  {
    "code": "def thumbUrl(self):\n        key = self.firstAttr('thumb', 'parentThumb', 'granparentThumb')\n        return self._server.url(key, includeToken=True) if key else None",
    "docstring": "Return url to for the thumbnail image."
  },
  {
    "code": "def cancel(self):\n        with self._condition:\n            if self._state in [RUNNING, FINISHED]:\n                return False\n            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:\n                return True\n            self._state = CANCELLED\n            self._condition.notify_all()\n        self._invoke_callbacks()\n        return True",
    "docstring": "Cancel the future if possible.\n\n        Returns True if the future was cancelled, False otherwise. A future\n        cannot be cancelled if it is running or has already completed."
  },
  {
    "code": "def addMonitor(self, monitorFriendlyName, monitorURL):\n        url = self.baseUrl\n        url += \"newMonitor?apiKey=%s\" % self.apiKey\n        url += \"&monitorFriendlyName=%s\" % monitorFriendlyName\n        url += \"&monitorURL=%s&monitorType=1\" % monitorURL\n        url += \"&monitorAlertContacts=%s\" % monitorAlertContacts\n        url += \"&noJsonCallback=1&format=json\"\n        success, response = self.requestApi(url)\n        if success:\n            return True\n        else:\n            return False",
    "docstring": "Returns True if Monitor was added, otherwise False."
  },
  {
    "code": "def get_annotations(self) -> Dict:\n        return {\n            EVIDENCE: self.evidence,\n            CITATION: self.citation.copy(),\n            ANNOTATIONS: self.annotations.copy()\n        }",
    "docstring": "Get the current annotations."
  },
  {
    "code": "def edit(filename, connection=None):\n    c = connection or connect()\n    rev = c.ls(filename)\n    if rev:\n        rev[0].edit()",
    "docstring": "Checks out a file into the default changelist\n\n    :param filename: File to check out\n    :type filename: str\n    :param connection: Connection object to use\n    :type connection: :py:class:`Connection`"
  },
  {
    "code": "def mesh_stable_pose(mesh, T_obj_table,\n                         T_table_world=RigidTransform(from_frame='table', to_frame='world'),\n                         style='wireframe', smooth=False, color=(0.5,0.5,0.5),\n                         dim=0.15, plot_table=True, plot_com=False, name=None):\n        T_obj_table = T_obj_table.as_frames('obj', 'table')\n        T_obj_world = T_table_world * T_obj_table\n        Visualizer3D.mesh(mesh, T_obj_world, style=style, smooth=smooth, color=color, name=name)\n        if plot_table:\n            Visualizer3D.table(T_table_world, dim=dim)\n        if plot_com:\n            Visualizer3D.points(Point(np.array(mesh.center_mass), 'obj'), T_obj_world, scale=0.01)\n        return T_obj_world",
    "docstring": "Visualize a mesh in a stable pose.\n\n        Parameters\n        ----------\n        mesh : trimesh.Trimesh\n            The mesh to visualize.\n        T_obj_table : autolab_core.RigidTransform\n            Pose of object relative to table.\n        T_table_world : autolab_core.RigidTransform\n            Pose of table relative to world.\n        style : str\n            Triangular mesh style, either 'surface' or 'wireframe'.\n        smooth : bool\n            If true, the mesh is smoothed before rendering.\n        color : 3-tuple\n            Color tuple.\n        dim : float\n            The side-length for the table.\n        plot_table : bool\n            If true, a table is visualized as well.\n        plot_com : bool\n            If true, a ball is visualized at the object's center of mass.\n        name : str\n            A name for the object to be added.\n\n        Returns\n        -------\n        autolab_core.RigidTransform\n            The pose of the mesh in world frame."
  },
  {
    "code": "def change_state(self, key, value):\n        if key not in VALID_KEYS:\n            raise InvalidState\n        self._data[key] = value",
    "docstring": "Changes the state of the instance data with the given\n        ``key`` and the provided ``value``.\n\n        Wrapping with a decorator is probably not necessary.\n\n        :param key: A ``str`` containing the key to update\n        :param value: A value to change the ``key`` to\n        :return: None"
  },
  {
    "code": "def stop(self, sig=signal.SIGINT):\n        for cpid in self.sandboxes:\n            logger.warn('Stopping %i...' % cpid)\n            try:\n                os.kill(cpid, sig)\n            except OSError:\n                logger.exception('Error stopping %s...' % cpid)\n        for cpid in list(self.sandboxes):\n            try:\n                logger.info('Waiting for %i...' % cpid)\n                pid, status = os.waitpid(cpid, 0)\n                logger.warn('%i stopped with status %i' % (pid, status >> 8))\n            except OSError:\n                logger.exception('Error waiting for %i...' % cpid)\n            finally:\n                self.sandboxes.pop(cpid, None)",
    "docstring": "Stop all the workers, and then wait for them"
  },
  {
    "code": "def get_params(self):\n        return self.timeout, self.xonxoff, self.rtscts, self.baudrate",
    "docstring": "Get parameters as a tuple.\n\n        :return: timeout, xonxoff, rtscts, baudrate"
  },
  {
    "code": "def integer_binning(data=None, **kwargs) -> StaticBinning:\n    if \"range\" in kwargs:\n        kwargs[\"range\"] = tuple(r - 0.5 for r in kwargs[\"range\"])\n    return fixed_width_binning(data=data, bin_width=kwargs.pop(\"bin_width\", 1),\n                               align=True, bin_shift=0.5, **kwargs)",
    "docstring": "Construct fixed-width binning schema with bins centered around integers.\n\n    Parameters\n    ----------\n    range: Optional[Tuple[int]]\n        min (included) and max integer (excluded) bin\n    bin_width: Optional[int]\n        group \"bin_width\" integers into one bin (not recommended)"
  },
  {
    "code": "def havdalah(self):\n        today = HDate(gdate=self.date, diaspora=self.location.diaspora)\n        tomorrow = HDate(gdate=self.date + dt.timedelta(days=1),\n                         diaspora=self.location.diaspora)\n        if today.is_shabbat or today.is_yom_tov:\n            if tomorrow.is_shabbat or tomorrow.is_yom_tov:\n                return None\n            return self._havdalah_datetime\n        return None",
    "docstring": "Return the time for havdalah, or None if not applicable.\n\n        If havdalah_offset is 0, uses the time for three_stars. Otherwise,\n        adds the offset to the time of sunset and uses that.\n        If it's currently a multi-day YomTov, and the end of the stretch is\n        after today, the havdalah value is defined to be None (to avoid\n        misleading the user that melacha is permitted)."
  },
  {
    "code": "def space_out_camel_case(stringAsCamelCase):\n    pattern = re.compile(r'([A-Z][A-Z][a-z])|([a-z][A-Z])')\n    if stringAsCamelCase is None:\n        return None\n    return pattern.sub(lambda m: m.group()[:1] + \" \" + m.group()[1:], stringAsCamelCase)",
    "docstring": "Adds spaces to a camel case string.  Failure to space out string returns the original string.\n\n    >>> space_out_camel_case('DMLSServicesOtherBSTextLLC')\n    'DMLS Services Other BS Text LLC'"
  },
  {
    "code": "def monthly(self):\n        if self._monthly is None:\n            self._monthly = MonthlyList(self._version, account_sid=self._solution['account_sid'], )\n        return self._monthly",
    "docstring": "Access the monthly\n\n        :returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList\n        :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList"
  },
  {
    "code": "def get_tensors_by_names(names):\n    ret = []\n    G = tfv1.get_default_graph()\n    for n in names:\n        opn, varn = get_op_tensor_name(n)\n        ret.append(G.get_tensor_by_name(varn))\n    return ret",
    "docstring": "Get a list of tensors in the default graph by a list of names.\n\n    Args:\n        names (list):"
  },
  {
    "code": "def dfbool2intervals(df,colbool):\n    df.index=range(len(df))\n    intervals=bools2intervals(df[colbool])\n    for intervali,interval in enumerate(intervals):\n        df.loc[interval[0]:interval[1],f'{colbool} interval id']=intervali\n        df.loc[interval[0]:interval[1],f'{colbool} interval start']=interval[0]\n        df.loc[interval[0]:interval[1],f'{colbool} interval stop']=interval[1]\n        df.loc[interval[0]:interval[1],f'{colbool} interval length']=interval[1]-interval[0]+1\n        df.loc[interval[0]:interval[1],f'{colbool} interval within index']=range(interval[1]-interval[0]+1)    \n    df[f'{colbool} interval index']=df.index    \n    return df",
    "docstring": "ds contains bool values"
  },
  {
    "code": "def send_note(self, to, subject=\"\", body=\"\", noetid=\"\"):\n        if self.standard_grant_type is not \"authorization_code\":\n            raise DeviantartError(\"Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.\")\n        response = self._req('/notes/send', post_data={\n            'to[]' : to,\n            'subject' : subject,\n            'body' : body,\n            'noetid' : noetid\n        })\n        sent_notes = []\n        for item in response['results']:\n            n = {}\n            n['success'] = item['success']\n            n['user'] = User()\n            n['user'].from_dict(item['user'])\n            sent_notes.append(n)\n        return sent_notes",
    "docstring": "Send a note\n\n        :param to: The username(s) that this note is to\n        :param subject: The subject of the note\n        :param body: The body of the note\n        :param noetid: The UUID of the note that is being responded to"
  },
  {
    "code": "def convert_from_rosetta(self, residue_id, to_scheme):\n        assert(type(residue_id) == types.IntType)\n        chain_id = None\n        for c, sequence in self.rosetta_sequences.iteritems():\n            for id, r in sequence:\n                if r.ResidueID == residue_id:\n                    assert(chain_id == None)\n                    chain_id = c\n        if chain_id:\n            return self.convert(chain_id, residue_id, 'rosetta', to_scheme)\n        else:\n            return None",
    "docstring": "A simpler conversion function to convert from Rosetta numbering without requiring the chain identifier."
  },
  {
    "code": "def json_pretty_print(s):\n    s = json.loads(s)\n    return json.dumps(s,\n                      sort_keys=True,\n                      indent=4,\n                      separators=(',', ': '))",
    "docstring": "pretty print JSON"
  },
  {
    "code": "def getPageType(name,number=False):\n    if not name in pageNames():\n        return None\n    pageType=PyOrigin.Pages(name).GetType()\n    if number:\n        return str(pageType)\n    if pageType==1:\n        return \"matrix\"\n    if pageType==2:\n        return \"book\"\n    if pageType==3:\n        return \"graph\"\n    if pageType==4:\n        return \"layout\"\n    if pageType==5:\n        return \"notes\"",
    "docstring": "Returns the type of the page with that name.\n    If that name doesn't exist, None is returned.\n\n    Args:\n        name (str): name of the page to get the folder from\n        number (bool): if True, return numbers (i.e., a graph will be 3)\n            if False, return words where appropriate (i.e, \"graph\")\n\n    Returns:\n        string of the type of object the page is"
  },
  {
    "code": "def SummaryMetadata(self, run, tag):\n    accumulator = self.GetAccumulator(run)\n    return accumulator.SummaryMetadata(tag)",
    "docstring": "Return the summary metadata for the given tag on the given run.\n\n    Args:\n      run: A string name of the run for which summary metadata is to be\n        retrieved.\n      tag: A string name of the tag whose summary metadata is to be\n        retrieved.\n\n    Raises:\n      KeyError: If the run is not found, or the tag is not available for\n        the given run.\n\n    Returns:\n      A `SummaryMetadata` protobuf."
  },
  {
    "code": "def callback(cfunc):\n    return C.c_voidp.from_address(C.cast(cfunc, C.c_voidp).value)",
    "docstring": "Turn a ctypes CFUNCTYPE instance into a value which can be passed into PyROOT"
  },
  {
    "code": "def _remove_debug_handlers(self):\n        remove = list()\n        for handler in self.config[self.HANDLERS]:\n            if self.config[self.HANDLERS][handler].get('debug_only'):\n                remove.append(handler)\n        for handler in remove:\n            del self.config[self.HANDLERS][handler]\n            for logger in self.config[self.LOGGERS].keys():\n                logger = self.config[self.LOGGERS][logger]\n                if handler in logger[self.HANDLERS]:\n                    logger[self.HANDLERS].remove(handler)\n        self._remove_debug_only()",
    "docstring": "Remove any handlers with an attribute of debug_only that is True and\n        remove the references to said handlers from any loggers that are\n        referencing them."
  },
  {
    "code": "def get_or_create(cls, issue, header, text=None):\n        for comment in get_comments(issue):\n            try:\n                if comment.body.splitlines()[0] == header:\n                    obj = cls(comment, header)\n                    break\n            except IndexError:\n                pass\n        else:\n            comment = create_comment(issue, header)\n            obj = cls(comment, header)\n        if text:\n            obj.edit(text)\n        return obj",
    "docstring": "Get or create the dashboard comment in this issue."
  },
  {
    "code": "def _compile(self, dirpath, makename, compiler, debug, profile):\n        from os import path\n        options = \"\"\n        if debug:\n            options += \" DEBUG=true\"\n        if profile:\n            options += \" GPROF=true\"\n        from os import system\n        codestr = \"cd {}; make -f '{}' F90={} FAM={}\" + options\n        code = system(codestr.format(dirpath, makename, compiler, compiler[0]))\n        lcount = 0\n        errors = []\n        log = path.join(dirpath, \"compile.log\")\n        with open(log) as f:\n            for line in f:\n                lcount += 1\n                if lcount > 21 and lcount < 32:\n                    errors.append(line)\n                elif lcount > 21:\n                    break\n        if len(errors) > 0:\n            code = 1\n            msg.warn(\"compile generated some errors or warnings:\")\n            msg.blank()\n            msg.info(''.join(errors))\n        return code",
    "docstring": "Compiles the makefile at the specified location with 'compiler'.\n\n        :arg dirpath: the full path to the directory where the makefile lives.\n        :arg compiler: one of ['ifort', 'gfortran'].\n        :arg makename: the name of the make file to compile."
  },
  {
    "code": "def _rgetattr(obj, key):\n    for k in key.split(\".\"):\n        obj = getattr(obj, k)\n    return obj",
    "docstring": "Recursive getattr for handling dots in keys."
  },
  {
    "code": "def decrypt_filedata(data, keys):\n    data.seek(-16, 2)\n    tag = data.read()\n    data.seek(-16, 2)\n    data.truncate()\n    data.seek(0)\n    plain = tempfile.NamedTemporaryFile(mode='w+b', delete=False)\n    pbar = progbar(fileSize(data))\n    obj = Cryptodome.Cipher.AES.new(keys.encryptKey, Cryptodome.Cipher.AES.MODE_GCM, keys.encryptIV)\n    prev_chunk = b''\n    for chunk in iter(lambda: data.read(CHUNK_SIZE), b''):\n        plain.write(obj.decrypt(prev_chunk))\n        pbar.update(len(chunk))\n        prev_chunk = chunk\n    plain.write(obj.decrypt_and_verify(prev_chunk, tag))\n    data.close()\n    pbar.close()\n    plain.seek(0)\n    return plain",
    "docstring": "Decrypts a file from Send"
  },
  {
    "code": "def _spawn(self):\n        self.queue = Queue(maxsize=self.num_threads * 10)\n        for i in range(self.num_threads):\n            t = Thread(target=self._consume)\n            t.daemon = True\n            t.start()",
    "docstring": "Initialize the queue and the threads."
  },
  {
    "code": "def make_context(self, docker_file=None):\n        kwargs = {\"silent_build\": self.harpoon.silent_build, \"extra_context\": self.commands.extra_context}\n        if docker_file is None:\n            docker_file = self.docker_file\n        with ContextBuilder().make_context(self.context, **kwargs) as ctxt:\n            self.add_docker_file_to_tarfile(docker_file, ctxt.t)\n            yield ctxt",
    "docstring": "Determine the docker lines for this image"
  },
  {
    "code": "def unit_doomed(unit=None):\n    if not has_juju_version(\"2.4.1\"):\n        raise NotImplementedError(\"is_doomed\")\n    if unit is None:\n        unit = local_unit()\n    gs = goal_state()\n    units = gs.get('units', {})\n    if unit not in units:\n        return True\n    return units[unit]['status'] in ('dying', 'dead')",
    "docstring": "Determines if the unit is being removed from the model\n\n    Requires Juju 2.4.1.\n\n    :param unit: string unit name, defaults to local_unit\n    :side effect: calls goal_state\n    :side effect: calls local_unit\n    :side effect: calls has_juju_version\n    :return: True if the unit is being removed, already gone, or never existed"
  },
  {
    "code": "def poke(library, session, address, width, data):\n    if width == 8:\n        return poke_8(library, session, address, data)\n    elif width == 16:\n        return poke_16(library, session, address, data)\n    elif width == 32:\n        return poke_32(library, session, address, data)\n    raise ValueError('%s is not a valid size. Valid values are 8, 16 or 32' % width)",
    "docstring": "Writes an 8, 16 or 32-bit value from the specified address.\n\n    Corresponds to viPoke* functions of the VISA library.\n\n    :param library: the visa library wrapped by ctypes.\n    :param session: Unique logical identifier to a session.\n    :param address: Source address to read the value.\n    :param width: Number of bits to read.\n    :param data: Data to be written to the bus.\n    :return: return value of the library call.\n    :rtype: :class:`pyvisa.constants.StatusCode`"
  },
  {
    "code": "def print_yielded(func):\n\tprint_all = functools.partial(map, print)\n\tprint_results = compose(more_itertools.recipes.consume, print_all, func)\n\treturn functools.wraps(func)(print_results)",
    "docstring": "Convert a generator into a function that prints all yielded elements\n\n\t>>> @print_yielded\n\t... def x():\n\t...     yield 3; yield None\n\t>>> x()\n\t3\n\tNone"
  },
  {
    "code": "def copy_shell__(self, new_i):\n        for prop in ONLY_COPY_PROP:\n            setattr(new_i, prop, getattr(self, prop))\n        return new_i",
    "docstring": "Create all attributes listed in 'ONLY_COPY_PROP' and return `self` with these attributes.\n\n        :param new_i: object to\n        :type new_i: object\n        :return: object with new properties added\n        :rtype: object"
  },
  {
    "code": "def remove_spawned_gates(self, spawn_gate=None):\n        if spawn_gate is None:\n            for sg in list(self.spawn_list):\n                self.spawn_list.remove(sg)\n                sg.remove()\n        else:\n            spawn_gate.remove()\n            self.spawn_list.remove(spawn_gate)",
    "docstring": "Removes all spawned gates."
  },
  {
    "code": "def update_resource(self, resource, underlined=None):\n        try:\n            pymodule = self.project.get_pymodule(resource)\n            modname = self._module_name(resource)\n            self._add_names(pymodule, modname, underlined)\n        except exceptions.ModuleSyntaxError:\n            pass",
    "docstring": "Update the cache for global names in `resource`"
  },
  {
    "code": "def blank_object(obj: T, fieldlist: Sequence[str]) -> None:\n    for f in fieldlist:\n        setattr(obj, f, None)",
    "docstring": "Within \"obj\", sets all fields in the fieldlist to None."
  },
  {
    "code": "def refresh(self):\r\n        table   = self.tableType()\r\n        search  = nativestring(self._pywidget.text())\r\n        if search == self._lastSearch:\r\n            return\r\n        self._lastSearch = search\r\n        if not search:\r\n            return\r\n        if search in self._cache:\r\n            records = self._cache[search]\r\n        else:\r\n            records = table.select(where = self.baseQuery(),\r\n                                   order = self.order())\r\n            records = list(records.search(search, limit=self.limit()))\r\n            self._cache[search] = records\r\n        self._records = records\r\n        self.model().setStringList(map(str, self._records))\r\n        self.complete()",
    "docstring": "Refreshes the contents of the completer based on the current text."
  },
  {
    "code": "def check_outputs(self):\n        self.outputs = self.expand_filenames(self.outputs)\n        result = False\n        if self.files_exist(self.outputs):\n            if self.dependencies_are_newer(self.outputs, self.inputs):\n                result = True\n                print(\"Dependencies are newer than outputs.\")\n                print(\"Running task.\")\n            elif self.force:\n                print(\"Dependencies are older than inputs, but 'force' option present.\")\n                print(\"Running task.\")\n                result = True\n            else:\n                print(\"Dependencies are older than inputs.\")\n        else:\n            print(\"No ouput file(s).\")\n            print(\"Running task.\")\n            result = True\n        return result",
    "docstring": "Check for the existence of output files"
  },
  {
    "code": "def _get_cookies_as_dict():\n    config = ConfigParser.SafeConfigParser()\n    config.read(_config)\n    if config.has_section('cookies'):\n        cookie_dict = {}\n        for option in config.options('cookies'):\n            option_key = option.upper() if option == 'jsessionid' else option\n            cookie_dict[option_key] = config.get('cookies', option)\n        return cookie_dict",
    "docstring": "Get cookies as a dict"
  },
  {
    "code": "def tuple_len(self):\n        try:\n            return self._tuple_len\n        except AttributeError:\n            raise NotImplementedError(\"Class {} does not implement attribute 'tuple_len'.\".format(self.__class__.__name__))",
    "docstring": "Length of tuples produced by this generator."
  },
  {
    "code": "def _k_value_square_reduction(ent_pipe_id, exit_pipe_id, re, f):\n    if re < 2500:\n        return (1.2 + (160 / re)) * ((ent_pipe_id / exit_pipe_id) ** 4)\n    else:\n        return (0.6 + 0.48 * f) * (ent_pipe_id / exit_pipe_id) ** 2\\\n            * ((ent_pipe_id / exit_pipe_id) ** 2 - 1)",
    "docstring": "Returns the minor loss coefficient for a square reducer.\n\n    Parameters:\n        ent_pipe_id: Entrance pipe's inner diameter.\n        exit_pipe_id: Exit pipe's inner diameter.\n        re: Reynold's number.\n        f: Darcy friction factor."
  },
  {
    "code": "def remove_not_requested_analyses_view(portal):\n    logger.info(\"Removing 'Analyses not requested' view ...\")\n    ar_ptype = portal.portal_types.AnalysisRequest\n    ar_ptype._actions = filter(lambda act: act.id != \"analyses_not_requested\",\n                               ar_ptype.listActions())",
    "docstring": "Remove the view 'Not requested analyses\" from inside AR"
  },
  {
    "code": "def count_unique(table, field=-1):\n    from collections import Counter\n    try:\n        ans = {}\n        for row in table.distinct().values(field).annotate(field_value_count=models.Count(field)):\n            ans[row[field]] = row['field_value_count']\n        return ans\n    except:\n        try:\n            return Counter(row[field] for row in table)\n        except:\n            try:\n                return Counter(row.get(field, None) for row in table)\n            except:\n                try:\n                    return Counter(row.getattr(field, None) for row in table)\n                except:\n                    pass",
    "docstring": "Use the Django ORM or collections.Counter to count unique values of a field in a table\n\n    `table` is one of:\n    1. An iterable of Django model instances for a database table (e.g. a Django queryset)\n    2. An iterable of dicts or lists with elements accessed by row[field] where field can be an integer or string\n    3. An iterable of objects or namedtuples with elements accessed by `row.field`\n\n    `field` can be any immutable object (the key or index in a row of the table that access the value to be counted)"
  },
  {
    "code": "def node2geoff(node_name, properties, encoder):\n    if properties:\n        return '({0} {1})'.format(node_name,\n                                  encoder.encode(properties))\n    else:\n        return '({0})'.format(node_name)",
    "docstring": "converts a NetworkX node into a Geoff string.\n\n    Parameters\n    ----------\n    node_name : str or int\n        the ID of a NetworkX node\n    properties : dict\n        a dictionary of node attributes\n    encoder : json.JSONEncoder\n        an instance of a JSON encoder (e.g. `json.JSONEncoder`)\n\n    Returns\n    -------\n    geoff : str\n        a Geoff string"
  },
  {
    "code": "def get_model(self, ids):\n        to_get_ids = [i for i in ids if i not in self._known_models]\n        models = [dxl_to_model(m) for m in self._get_model(to_get_ids, convert=False)]\n        self._known_models.update(zip(to_get_ids, models))\n        return tuple(self._known_models[id] for id in ids)",
    "docstring": "Gets the model for the specified motors."
  },
  {
    "code": "def backupIds(self) -> Sequence[int]:\n        return [id for id in self.started.keys() if id != 0]",
    "docstring": "Return the list of replicas that don't belong to the master protocol\n        instance"
  },
  {
    "code": "def read_pcap_from_source(self):\n        if self._capture_node:\n            compute = self._capture_node[\"node\"].compute\n            return compute.stream_file(self._project, \"tmp/captures/\" + self._capture_file_name)",
    "docstring": "Return a FileStream of the Pcap from the compute node"
  },
  {
    "code": "def _compute_length(nodes):\n    r\n    _, num_nodes = np.shape(nodes)\n    first_deriv = (num_nodes - 1) * (nodes[:, 1:] - nodes[:, :-1])\n    if num_nodes == 2:\n        return np.linalg.norm(first_deriv[:, 0], ord=2)\n    if _scipy_int is None:\n        raise OSError(\"This function requires SciPy for quadrature.\")\n    size_func = functools.partial(vec_size, first_deriv)\n    length, _ = _scipy_int.quad(size_func, 0.0, 1.0)\n    return length",
    "docstring": "r\"\"\"Approximately compute the length of a curve.\n\n    .. _QUADPACK: https://en.wikipedia.org/wiki/QUADPACK\n\n    If ``degree`` is :math:`n`, then the Hodograph curve\n    :math:`B'(s)` is degree :math:`d = n - 1`. Using this curve, we\n    approximate the integral:\n\n    .. math::\n\n       \\int_{B\\left(\\left[0, 1\\right]\\right)} 1 \\, d\\mathbf{x} =\n       \\int_0^1 \\left\\lVert B'(s) \\right\\rVert_2 \\, ds\n\n    using `QUADPACK`_ (via SciPy).\n\n    .. note::\n\n       There is also a Fortran implementation of this function, which\n       will be used if it can be built.\n\n    Args:\n        nodes (numpy.ndarray): The nodes defining a curve.\n\n    Returns:\n        float: The length of the curve.\n\n    Raises:\n        OSError: If SciPy is not installed."
  },
  {
    "code": "def config_get(self, pattern='*'):\n        result = {}\n        for name, value in self.redis_config.items():\n            if fnmatch.fnmatch(name, pattern):\n                try:\n                    result[name] = int(value)\n                except ValueError:\n                    result[name] = value\n        return result",
    "docstring": "Get one or more configuration parameters."
  },
  {
    "code": "def _replace(self, **kwds):\n        'Return a new NamedTuple object replacing specified fields with new values'\n        result = self._make(map(kwds.pop, self._fields, self))\n        if kwds:\n            raise ValueError('Got unexpected field names: %r' % kwds.keys())\n        return result",
    "docstring": "Return a new NamedTuple object replacing specified fields with new values"
  },
  {
    "code": "def handle(self, *args, **options):\n        comments = Comment.objects.filter(\n            Q(classifiedcomment__isnull=True) |\n            Q(classifiedcomment__cls='unsure')).order_by('?')\n        if options['count']:\n            comments = comments[:options['count']]\n        comment_count = comments.count()\n        self.stdout.write('Classifying %s comments, please wait...' %\n                          comment_count)\n        self.stdout.flush()\n        for comment in comments:\n            classified_comment = utils.classify_comment(comment)\n            self.stdout.write('%s,' % classified_comment.cls[0])\n            self.stdout.flush()\n        self.stdout.write('\\nDone!\\n')",
    "docstring": "Collect all comments that hasn't already been\n        classified or are classified as unsure.\n        Order randomly so we don't rehash previously unsure classifieds\n        when count limiting."
  },
  {
    "code": "def find_local_id(self, name_id):\n        try:\n            return self.db[name_id.text]\n        except KeyError:\n            logger.debug(\"name: %s\", name_id.text)\n            return None",
    "docstring": "Only find persistent IDs\n\n        :param name_id:\n        :return:"
  },
  {
    "code": "async def auth(self):\n        credentials = await self.atv.airplay.generate_credentials()\n        await self.atv.airplay.load_credentials(credentials)\n        try:\n            await self.atv.airplay.start_authentication()\n            pin = await _read_input(self.loop, 'Enter PIN on screen: ')\n            await self.atv.airplay.finish_authentication(pin)\n            print('You may now use these credentials:')\n            print(credentials)\n            return 0\n        except exceptions.DeviceAuthenticationError:\n            logging.exception('Failed to authenticate - invalid PIN?')\n            return 1",
    "docstring": "Perform AirPlay device authentication."
  },
  {
    "code": "def repr_args(args):\n    res = []\n    for x in args:\n        if isinstance(x, tuple) and len(x) == 2:\n            key, value = x\n            res += [\"%s=%s\" % (key, repr_arg(value))]\n        else:\n            res += [repr_arg(x)]\n    return ', '.join(res)",
    "docstring": "formats a list of function arguments prettily but as working code\n\n    (kwargs are tuples (argname, argvalue)"
  },
  {
    "code": "def facetintervallookupone(table, key, start='start', stop='stop',\n                           value=None, include_stop=False, strict=True):\n    trees = facettupletrees(table, key, start=start, stop=stop, value=value)\n    out = dict()\n    for k in trees:\n        out[k] = IntervalTreeLookupOne(trees[k], include_stop=include_stop,\n                                       strict=strict)\n    return out",
    "docstring": "Construct a faceted interval lookup for the given table, returning at most\n    one result for each query.\n    \n    If ``strict=True``, queries returning more than one result will\n    raise a `DuplicateKeyError`. If ``strict=False`` and there is\n    more than one result, the first result is returned."
  },
  {
    "code": "def filter_whitespace(mode: str, text: str) -> str:\n    if mode == \"all\":\n        return text\n    elif mode == \"single\":\n        text = re.sub(r\"([\\t ]+)\", \" \", text)\n        text = re.sub(r\"(\\s*\\n\\s*)\", \"\\n\", text)\n        return text\n    elif mode == \"oneline\":\n        return re.sub(r\"(\\s+)\", \" \", text)\n    else:\n        raise Exception(\"invalid whitespace mode %s\" % mode)",
    "docstring": "Transform whitespace in ``text`` according to ``mode``.\n\n    Available modes are:\n\n    * ``all``: Return all whitespace unmodified.\n    * ``single``: Collapse consecutive whitespace with a single whitespace\n      character, preserving newlines.\n    * ``oneline``: Collapse all runs of whitespace into a single space\n      character, removing all newlines in the process.\n\n    .. versionadded:: 4.3"
  },
  {
    "code": "def tail(self, n=None, **kwargs):\n        if n is None:\n            n = options.display.max_rows\n        return self._handle_delay_call('execute', self, tail=n, **kwargs)",
    "docstring": "Return the last n rows. Execute at once.\n\n        :param n:\n        :return: result frame\n        :rtype: :class:`odps.df.backends.frame.ResultFrame`"
  },
  {
    "code": "def build_insert(table_name, attributes):\n    sql = \"INSERT INTO %s\" %(table_name)\n    column_str = u\"\"\n    value_str = u\"\"\n    for index, (key, value) in enumerate(attributes.items()):\n        if index > 0:\n            column_str += u\",\"\n            value_str += u\",\"\n        column_str += key\n        value_str += value_to_sql_str(value)\n    sql = sql + u\"(%s) VALUES(%s)\" %(column_str, value_str)\n    return sql",
    "docstring": "Given the table_name and the data, return the sql to insert the data"
  },
  {
    "code": "def highpass(timeseries, frequency, filter_order=8, attenuation=0.1):\n    if not isinstance(timeseries, TimeSeries):\n        raise TypeError(\"Can only resample time series\")\n    if timeseries.kind is not 'real':\n        raise TypeError(\"Time series must be real\")\n    lal_data = timeseries.lal()\n    _highpass_func[timeseries.dtype](lal_data, frequency,\n                                     1-attenuation, filter_order)\n    return TimeSeries(lal_data.data.data, delta_t = lal_data.deltaT,\n                      dtype=timeseries.dtype, epoch=timeseries._epoch)",
    "docstring": "Return a new timeseries that is highpassed.\n\n    Return a new time series that is highpassed above the `frequency`.\n\n    Parameters\n    ----------\n    Time Series: TimeSeries\n        The time series to be high-passed.\n    frequency: float\n        The frequency below which is suppressed.\n    filter_order: {8, int}, optional\n        The order of the filter to use when high-passing the time series.\n    attenuation: {0.1, float}, optional\n        The attenuation of the filter.\n\n    Returns\n    -------\n    Time Series: TimeSeries\n        A  new TimeSeries that has been high-passed.\n\n    Raises\n    ------\n    TypeError:\n        time_series is not an instance of TimeSeries.\n    TypeError:\n        time_series is not real valued"
  },
  {
    "code": "def expose(*methods):\n    def setup(base):\n        return expose_as(base.__name__, base, *methods)\n    return setup",
    "docstring": "A decorator for exposing the methods of a class.\n\n    Parameters\n    ----------\n    *methods : str\n        A str representation of the methods that should be exposed to callbacks.\n\n    Returns\n    -------\n    decorator : function\n        A function accepting one argument - the class whose methods will be\n        exposed - and which returns a new :class:`Watchable` that will\n        notify a :class:`Spectator` when those methods are called.\n\n    Notes\n    -----\n    This is essentially a decorator version of :func:`expose_as`"
  },
  {
    "code": "def _next_file(self):\n    while True:\n      if self._bucket_iter:\n        try:\n          return self._bucket_iter.next().filename\n        except StopIteration:\n          self._bucket_iter = None\n          self._bucket = None\n      if self._index >= len(self._filenames):\n        return\n      filename = self._filenames[self._index]\n      self._index += 1\n      if self._delimiter is None or not filename.endswith(self._delimiter):\n        return filename\n      self._bucket = cloudstorage.listbucket(filename,\n                                             delimiter=self._delimiter)\n      self._bucket_iter = iter(self._bucket)",
    "docstring": "Find next filename.\n\n    self._filenames may need to be expanded via listbucket.\n\n    Returns:\n      None if no more file is left. Filename otherwise."
  },
  {
    "code": "def get_level():\n    handler, logger = find_handler(logging.getLogger(), match_stream_handler)\n    return handler.level if handler else DEFAULT_LOG_LEVEL",
    "docstring": "Get the logging level of the root handler.\n\n    :returns: The logging level of the root handler (an integer) or\n              :data:`DEFAULT_LOG_LEVEL` (if no root handler exists)."
  },
  {
    "code": "def list_vnets(access_token, subscription_id):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/providers/Microsoft.Network/',\n                        '/virtualNetworks?api-version=', NETWORK_API])\n    return do_get(endpoint, access_token)",
    "docstring": "List the VNETs in a subscription\t.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n\n    Returns:\n        HTTP response. JSON body of VNets list with properties."
  },
  {
    "code": "def tvdb_refresh_token(token):\n    url = \"https://api.thetvdb.com/refresh_token\"\n    headers = {\"Authorization\": \"Bearer %s\" % token}\n    status, content = _request_json(url, headers=headers, cache=False)\n    if status == 401:\n        raise MapiProviderException(\"invalid token\")\n    elif status != 200 or not content.get(\"token\"):\n        raise MapiNetworkException(\"TVDb down or unavailable?\")\n    return content[\"token\"]",
    "docstring": "Refreshes JWT token\n\n    Online docs: api.thetvdb.com/swagger#!/Authentication/get_refresh_token="
  },
  {
    "code": "def _callback(self, ch, method, properties, body):\n        get_logger().info(\"Message received! Calling listeners...\")\n        topic = method.routing_key\n        dct = json.loads(body.decode('utf-8'))\n        for listener in self.listeners:\n            listener(self, topic, dct)",
    "docstring": "Internal method that will be called when receiving message."
  },
  {
    "code": "def __load(self, redirect=True, preload=False):\n        query_params = {\n            \"prop\": \"info|pageprops\",\n            \"inprop\": \"url\",\n            \"ppprop\": \"disambiguation\",\n            \"redirects\": \"\",\n        }\n        query_params.update(self.__title_query_param())\n        request = self.mediawiki.wiki_request(query_params)\n        query = request[\"query\"]\n        pageid = list(query[\"pages\"].keys())[0]\n        page = query[\"pages\"][pageid]\n        if \"missing\" in page:\n            self._raise_page_error()\n        elif \"redirects\" in query:\n            self._handle_redirect(redirect, preload, query, page)\n        elif \"pageprops\" in page:\n            self._raise_disambiguation_error(page, pageid)\n        else:\n            self.pageid = pageid\n            self.title = page[\"title\"]\n            self.url = page[\"fullurl\"]",
    "docstring": "load the basic page information"
  },
  {
    "code": "def name(self):\n        try:\n            return TIFF.TAGS[self.code]\n        except KeyError:\n            return str(self.code)",
    "docstring": "Return name of tag from TIFF.TAGS registry."
  },
  {
    "code": "def total_number(slug, kind='1'):\n        return TabPost.select().join(\n            TabPost2Tag,\n            on=(TabPost.uid == TabPost2Tag.post_id)\n        ).where(\n            (TabPost2Tag.tag_id == slug) & (TabPost.kind == kind)\n        ).count()",
    "docstring": "Return the number of certian slug."
  },
  {
    "code": "def child(self, **kwargs):\n        return AutomatorDeviceObject(\n            self.device,\n            self.selector.clone().child(**kwargs)\n        )",
    "docstring": "set childSelector."
  },
  {
    "code": "def setup_handler(setup_fixtures_fn, setup_fn):\n        def handler(obj):\n            setup_fixtures_fn(obj)\n            setup_fn(obj)\n        return handler",
    "docstring": "Returns a function that adds fixtures handling to the setup method.\n\n        Makes sure that fixtures are setup before calling the given setup method."
  },
  {
    "code": "def _update_general_statistics(a_float, dist):\n    if not dist.count:\n        dist.count = 1\n        dist.maximum = a_float\n        dist.minimum = a_float\n        dist.mean = a_float\n        dist.sumOfSquaredDeviation = 0\n    else:\n        old_count = dist.count\n        old_mean = dist.mean\n        new_mean = ((old_count * old_mean) + a_float) / (old_count + 1)\n        delta_sum_squares = (a_float - old_mean) * (a_float - new_mean)\n        dist.count += 1\n        dist.mean = new_mean\n        dist.maximum = max(a_float, dist.maximum)\n        dist.minimum = min(a_float, dist.minimum)\n        dist.sumOfSquaredDeviation += delta_sum_squares",
    "docstring": "Adds a_float to distribution, updating the statistics fields.\n\n    Args:\n      a_float (float): a new value\n      dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):\n        the Distribution being updated"
  },
  {
    "code": "def _process_converter(self, f, filt=None):\n        if filt is None:\n            filt = lambda col, c: True\n        needs_new_obj = False\n        new_obj = dict()\n        for i, (col, c) in enumerate(self.obj.iteritems()):\n            if filt(col, c):\n                new_data, result = f(col, c)\n                if result:\n                    c = new_data\n                    needs_new_obj = True\n            new_obj[i] = c\n        if needs_new_obj:\n            new_obj = DataFrame(new_obj, index=self.obj.index)\n            new_obj.columns = self.obj.columns\n            self.obj = new_obj",
    "docstring": "Take a conversion function and possibly recreate the frame."
  },
  {
    "code": "def get_random_password(self, length=32, chars=None):\n        if chars is None:\n            chars = string.ascii_letters + string.digits\n        return ''.join(random.choice(chars) for x in range(length))",
    "docstring": "Helper function that gets a random password.\n\n        :param length: The length of the random password.\n        :type  length: int\n        :param  chars: A string with characters to choose from. Defaults to all ASCII letters and digits.\n        :type   chars: str"
  },
  {
    "code": "def text_to_url(self, text):\r\n        if text.startswith('/'):\r\n            text = text[1:]\r\n        return QUrl(self.home_url.toString()+text+'.html')",
    "docstring": "Convert text address into QUrl object"
  },
  {
    "code": "def setup_bash_in_container(builddir, _container, outfile, shell):\n    with local.cwd(builddir):\n        print(\"Entering bash inside User-Chroot. Prepare your image and \"\n              \"type 'exit' when you are done. If bash exits with a non-zero\"\n              \"exit code, no new container will be stored.\")\n        store_new_container = True\n        try:\n            run_in_container(shell, _container)\n        except ProcessExecutionError:\n            store_new_container = False\n        if store_new_container:\n            print(\"Packing new container image.\")\n            pack_container(_container, outfile)\n            config_path = str(CFG[\"config_file\"])\n            CFG.store(config_path)\n            print(\"Storing config in {0}\".format(os.path.abspath(config_path)))",
    "docstring": "Setup a bash environment inside a container.\n\n    Creates a new chroot, which the user can use as a bash to run the wanted\n    projects inside the mounted container, that also gets returned afterwards."
  },
  {
    "code": "def _determine_v1_goals(self, address_mapper, options):\n    v1_goals, ambiguous_goals, _ = options.goals_by_version\n    requested_goals = v1_goals + ambiguous_goals\n    spec_parser = CmdLineSpecParser(self._root_dir)\n    for goal in requested_goals:\n      if address_mapper.is_valid_single_address(spec_parser.parse_spec(goal)):\n        logger.warning(\"Command-line argument '{0}' is ambiguous and was assumed to be \"\n                       \"a goal. If this is incorrect, disambiguate it with ./{0}.\".format(goal))\n    return [Goal.by_name(goal) for goal in requested_goals]",
    "docstring": "Check and populate the requested goals for a given run."
  },
  {
    "code": "def create_user(self, ):\n        name = self.username_le.text()\n        if not name:\n            self.username_le.setPlaceholderText(\"Please provide a username.\")\n            return\n        first = self.first_le.text()\n        last = self.last_le.text()\n        email = self.email_le.text()\n        try:\n            user = djadapter.models.User(username=name, first_name=first, last_name=last, email=email)\n            user.save()\n            for prj in self.projects:\n                prj.users.add(user)\n            for task in self.tasks:\n                task.users.add(user)\n            self.user = user\n            self.accept()\n        except:\n            log.exception(\"Could not create new assettype\")",
    "docstring": "Create a user and store it in the self.user\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def simple_prot(x, start):\n    for i in range(start,len(x)-1):\n        a,b,c =  x[i-1], x[i], x[i+1]\n        if b - a > 0 and b -c >= 0:\n            return i\n    else:\n        return None",
    "docstring": "Find the first peak to the right of start"
  },
  {
    "code": "def get_code(self):\n        if self.code is None:\n            self.code = urlopen(self.url).read()\n        return self.code",
    "docstring": "Opens the link and returns the response's content."
  },
  {
    "code": "def _build_kernel(self, kernel_source, compile_flags=()):\n        return cl.Program(self._cl_context, kernel_source).build(' '.join(compile_flags))",
    "docstring": "Convenience function for building the kernel for this worker.\n\n        Args:\n            kernel_source (str): the kernel source to use for building the kernel\n\n        Returns:\n            cl.Program: a compiled CL kernel"
  },
  {
    "code": "def is_unicode(string):\n    str_type = str(type(string))\n    if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n        return True\n    return False",
    "docstring": "Validates that the object itself is some kinda string"
  },
  {
    "code": "def GetPathInfo(self, timestamp=None):\n    path_info_timestamp = self._LastEntryTimestamp(self._path_infos, timestamp)\n    try:\n      result = self._path_infos[path_info_timestamp].Copy()\n    except KeyError:\n      result = rdf_objects.PathInfo(\n          path_type=self._path_type, components=self._components)\n    stat_entry_timestamp = self._LastEntryTimestamp(self._stat_entries,\n                                                    timestamp)\n    result.last_stat_entry_timestamp = stat_entry_timestamp\n    result.stat_entry = self._stat_entries.get(stat_entry_timestamp)\n    hash_entry_timestamp = self._LastEntryTimestamp(self._hash_entries,\n                                                    timestamp)\n    result.last_hash_entry_timestamp = hash_entry_timestamp\n    result.hash_entry = self._hash_entries.get(hash_entry_timestamp)\n    return result",
    "docstring": "Generates a summary about the path record.\n\n    Args:\n      timestamp: A point in time from which the data should be retrieved.\n\n    Returns:\n      A `rdf_objects.PathInfo` instance."
  },
  {
    "code": "def get_interaction_energy(self, assign_ff=True, ff=None, mol2=False,\n                               force_ff_assign=False):\n        if not ff:\n            ff = global_settings['buff']['force_field']\n        if assign_ff:\n            for molecule in self._molecules:\n                if hasattr(molecule, 'update_ff'):\n                    molecule.update_ff(\n                        ff, mol2=mol2, force_ff_assign=force_ff_assign)\n                else:\n                    raise AttributeError(\n                        'The following molecule does not have a update_ff'\n                        'method:\\n{}\\nIf this is a custom molecule type it'\n                        'should inherit from BaseAmpal:'.format(molecule))\n        interactions = find_inter_ampal(self, ff.distance_cutoff)\n        buff_score = score_interactions(interactions, ff)\n        return buff_score",
    "docstring": "Calculates the interaction energy of the AMPAL object.\n\n        Parameters\n        ----------\n        assign_ff: bool, optional\n            If true the force field will be updated if required.\n        ff: BuffForceField, optional\n            The force field to be used for scoring.\n        mol2: bool, optional\n            If true, mol2 style labels will also be used.\n        force_ff_assign: bool, optional\n            If true, the force field will be completely reassigned, \n            ignoring the cached parameters.\n\n        Returns\n        -------\n        buff_score: buff.BUFFScore\n            A BUFFScore object with information about each of the\n            interactions and the `Atoms` involved.\n\n        Raises\n        ------\n        AttributeError\n            Raise if a component molecule does not have an `update_ff`\n            method."
  },
  {
    "code": "def find_users(session, *usernames):\n    user_string = ','.join(usernames)\n    return _make_request(session, FIND_USERS_URL, user_string)",
    "docstring": "Find multiple users by name."
  },
  {
    "code": "def _update_limits_from_api(self):\n        self.connect()\n        logger.info(\"Querying RDS DescribeAccountAttributes for limits\")\n        lims = self.conn.describe_account_attributes()['AccountQuotas']\n        for lim in lims:\n            if lim['AccountQuotaName'] not in self.API_NAME_TO_LIMIT:\n                logger.info('RDS DescribeAccountAttributes returned unknown'\n                            'limit: %s (max: %s; used: %s)',\n                            lim['AccountQuotaName'], lim['Max'], lim['Used'])\n                continue\n            lname = self.API_NAME_TO_LIMIT[lim['AccountQuotaName']]\n            self.limits[lname]._set_api_limit(lim['Max'])\n            if len(self.limits[lname].get_current_usage()) < 1:\n                self.limits[lname]._add_current_usage(lim['Used'])\n        logger.debug('Done setting limits from API.')",
    "docstring": "Query RDS's DescribeAccountAttributes API action, and update limits\n        with the quotas returned. Updates ``self.limits``.\n\n        We ignore the usage information from the API,"
  },
  {
    "code": "def get_user_orders(self):\n        self._log('get user orders')\n        return self._rest_client.post(\n            endpoint='/open_orders',\n            payload={'book': self.name}\n        )",
    "docstring": "Return user's orders that are currently open.\n\n        :return: User's orders currently open.\n        :rtype: [dict]"
  },
  {
    "code": "def create_birthday(min_age=18, max_age=80):\n    age = random.randint(min_age, max_age)\n    start = datetime.date.today() - datetime.timedelta(days=random.randint(0, 365))\n    return start - datetime.timedelta(days=age * 365)",
    "docstring": "Create a random birthday fomr someone between the ages of min_age and max_age"
  },
  {
    "code": "def eject_medium(self, attachment):\n        if not isinstance(attachment, IMediumAttachment):\n            raise TypeError(\"attachment can only be an instance of type IMediumAttachment\")\n        new_attachment = self._call(\"ejectMedium\",\n                     in_p=[attachment])\n        new_attachment = IMediumAttachment(new_attachment)\n        return new_attachment",
    "docstring": "Tells VBoxSVC that the guest has ejected the medium associated with\n        the medium attachment.\n\n        in attachment of type :class:`IMediumAttachment`\n            The medium attachment where the eject happened.\n\n        return new_attachment of type :class:`IMediumAttachment`\n            A new reference to the medium attachment, as the config change can\n            result in the creation of a new instance."
  },
  {
    "code": "def extract_constant(code, symbol, default=-1):\n    if symbol not in code.co_names:\n        return None\n    name_idx = list(code.co_names).index(symbol)\n    STORE_NAME = 90\n    STORE_GLOBAL = 97\n    LOAD_CONST = 100\n    const = default\n    for byte_code in Bytecode(code):\n        op = byte_code.opcode\n        arg = byte_code.arg\n        if op == LOAD_CONST:\n            const = code.co_consts[arg]\n        elif arg == name_idx and (op == STORE_NAME or op == STORE_GLOBAL):\n            return const\n        else:\n            const = default",
    "docstring": "Extract the constant value of 'symbol' from 'code'\n\n    If the name 'symbol' is bound to a constant value by the Python code\n    object 'code', return that value.  If 'symbol' is bound to an expression,\n    return 'default'.  Otherwise, return 'None'.\n\n    Return value is based on the first assignment to 'symbol'.  'symbol' must\n    be a global, or at least a non-\"fast\" local in the code block.  That is,\n    only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'\n    must be present in 'code.co_names'."
  },
  {
    "code": "def matches_extension(path, extension):\n    _, ext = os.path.splitext(path)\n    if ext == '':\n        return os.path.basename(path) == extension\n    else:\n        return fnmatch.fnmatch(ext[1:], extension)",
    "docstring": "Returns True if path has the given extension, or if\n    the last path component matches the extension. Supports\n    Unix glob matching.\n\n    >>> matches_extension(\"./www/profile.php\", \"php\")\n    True\n    >>> matches_extension(\"./scripts/menu.js\", \"html\")\n    False\n    >>> matches_extension(\"./LICENSE\", \"LICENSE\")\n    True"
  },
  {
    "code": "def get_file(self, key, file):\n        self._check_valid_key(key)\n        if isinstance(file, str):\n            return self._get_filename(key, file)\n        else:\n            return self._get_file(key, file)",
    "docstring": "Write contents of key to file\n\n        Like :meth:`.KeyValueStore.put_file`, this method allows backends to\n        implement a specialized function if data needs to be written to disk or\n        streamed.\n\n        If *file* is a string, contents of *key* are written to a newly\n        created file with the filename *file*. Otherwise, the data will be\n        written using the *write* method of *file*.\n\n        :param key: The key to be read\n        :param file: Output filename or an object with a *write* method.\n\n        :raises exceptions.ValueError: If the key is not valid.\n        :raises exceptions.IOError: If there was a problem reading or writing\n                                    data.\n        :raises exceptions.KeyError: If the key was not found."
  },
  {
    "code": "def zoom(self, zoom, center=(0, 0, 0), mapped=True):\n        zoom = as_vec4(zoom, default=(1, 1, 1, 1))\n        center = as_vec4(center, default=(0, 0, 0, 0))\n        scale = self.scale * zoom\n        if mapped:\n            trans = center - (center - self.translate) * zoom\n        else:\n            trans = self.scale * (1 - zoom) * center + self.translate\n        self._set_st(scale=scale, translate=trans)",
    "docstring": "Update the transform such that its scale factor is changed, but\n        the specified center point is left unchanged.\n\n        Parameters\n        ----------\n        zoom : array-like\n            Values to multiply the transform's current scale\n            factors.\n        center : array-like\n            The center point around which the scaling will take place.\n        mapped : bool\n            Whether *center* is expressed in mapped coordinates (True) or\n            unmapped coordinates (False)."
  },
  {
    "code": "def delete_subscription(self, subscription_id):\n        url = self.SUBSCRIPTIONS_ID_URL % subscription_id\n        connection = Connection(self.token)\n        connection.set_url(self.production, url)\n        return connection.delete_request()",
    "docstring": "Delete single subscription"
  },
  {
    "code": "def batch_norm_relu(inputs, is_training, relu=True):\n  inputs = mtf.layers.batch_norm(\n      inputs,\n      is_training,\n      BATCH_NORM_DECAY,\n      epsilon=BATCH_NORM_EPSILON,\n      init_zero=(not relu))\n  if relu:\n    inputs = mtf.relu(inputs)\n  return inputs",
    "docstring": "Block of batch norm and relu."
  },
  {
    "code": "def process_array_includes(self, array, json):\n        includes = json.get('includes') or {}\n        for key in array.items_mapped.keys():\n            if key in includes:\n                for resource in includes[key]:\n                    processed = self.from_json(resource)\n                    array.items_mapped[key][processed.sys['id']] = processed",
    "docstring": "Iterate through all `includes` and create a resource for every item.\n\n        In addition map the resources under the `items_mapped` by the resource id and type.\n\n        :param array: Array resource.\n        :param json: Raw JSON dictionary."
  },
  {
    "code": "def maintenance_mode(self, **kwargs):\n        is_get_config = kwargs.pop('get', False)\n        delete = kwargs.pop('delete', False)\n        rbridge_id = kwargs.pop('rbridge_id')\n        callback = kwargs.pop('callback', self._callback)\n        rid_args = dict(rbridge_id=rbridge_id)\n        rid = getattr(self._rbridge,\n                      'rbridge_id_system_mode_maintenance')\n        config = rid(**rid_args)\n        if is_get_config:\n            maint_mode = callback(config, handler='get_config')\n            mode = maint_mode.data_xml\n            root = ET.fromstring(mode)\n            namespace = 'urn:brocade.com:mgmt:brocade-rbridge'\n            for rbridge_id_node in root.findall('{%s}rbridge-id' % namespace):\n                system_mode = rbridge_id_node.find(\n                    '{%s}system-mode' % namespace)\n                if system_mode is not None:\n                    return True\n                else:\n                    return False\n        if delete:\n            config.find('.//*maintenance').set('operation', 'delete')\n        return callback(config)",
    "docstring": "Configures maintenance mode on the device\n\n        Args:\n            rbridge_id (str): The rbridge ID of the device on which\n            Maintenance mode\n                will be configured in a VCS fabric.\n\n            get (bool): Get config instead of editing config. (True, False)\n            callback (function): A function executed upon completion of the\n                method.  The only parameter passed to `callback` will be the\n                ``ElementTree`` `config`.\n\n        Returns:\n            Return value of `callback`.\n\n        Raises:\n            KeyError: if `rbridge_id` is not specified.\n\n        Examples:\n            >>> import pynos.device\n            >>> conn = ('10.24.39.202', '22')\n            >>> auth = ('admin', 'password')\n            >>> with pynos.device.Device(conn=conn, auth=auth) as dev:\n            ...     output = dev.system.maintenance_mode(rbridge_id='226')\n            ...     output = dev.system.maintenance_mode(rbridge_id='226',\n            ...     get=True)\n            ...     assert output == True\n            ...     output = dev.system.maintenance_mode(rbridge_id='226',\n            ...     delete=True)\n            ...     output = dev.system.maintenance_mode(rbridge_id='226',\n            ...     get=True)\n            ...     assert output == False"
  },
  {
    "code": "def _build_wheel_modern(ireq, output_dir, finder, wheel_cache, kwargs):\n    kwargs.update({\"progress_bar\": \"off\", \"build_isolation\": False})\n    with pip_shims.RequirementTracker() as req_tracker:\n        if req_tracker:\n            kwargs[\"req_tracker\"] = req_tracker\n        preparer = pip_shims.RequirementPreparer(**kwargs)\n        builder = pip_shims.WheelBuilder(finder, preparer, wheel_cache)\n        return builder._build_one(ireq, output_dir)",
    "docstring": "Build a wheel.\n\n    * ireq: The InstallRequirement object to build\n    * output_dir: The directory to build the wheel in.\n    * finder: pip's internal Finder object to find the source out of ireq.\n    * kwargs: Various keyword arguments from `_prepare_wheel_building_kwargs`."
  },
  {
    "code": "def split_text(text, separators=re.compile('\\s'), brackets=None, strip=False):\n    if not isinstance(separators, PATTERN_TYPE):\n        separators = re.compile(\n            '[{0}]'.format(''.join('\\{0}'.format(c) for c in separators)))\n    return nfilter(\n        s.strip() if strip else s for s in\n        separators.split(strip_brackets(text, brackets=brackets)))",
    "docstring": "Split text along the separators unless they appear within brackets.\n\n    :param separators: An iterable single characters or a compiled regex pattern.\n    :param brackets: `dict` mapping start tokens to end tokens of what is to be \\\n    recognized as brackets.\n\n    .. note:: This function will also strip content within brackets."
  },
  {
    "code": "def compile(self, script, bare=False):\n        if not hasattr(self, '_context'):\n            self._context = self._runtime.compile(self._compiler_script)\n        return self._context.call(\n            \"CoffeeScript.compile\", script, {'bare': bare})",
    "docstring": "compile a CoffeeScript code to a JavaScript code.\n\n        if bare is True, then compile the JavaScript without the top-level\n        function safety wrapper (like the coffee command)."
  },
  {
    "code": "def rewind(self):\n        if self.mode != READ:\n            raise OSError(\"Can't rewind in write mode\")\n        self.fileobj.seek(0)\n        self._new_member = True\n        self.extrabuf = b\"\"\n        self.extrasize = 0\n        self.extrastart = 0\n        self.offset = 0",
    "docstring": "Return the uncompressed stream file position indicator to the\n        beginning of the file"
  },
  {
    "code": "def stop(self, stop_context):\n        for p in self._providers:\n            p.stop(stop_context)\n        if self._clear_stop:\n            self.clear_cache()",
    "docstring": "Perform any logic on solution stop"
  },
  {
    "code": "def local_response_norm(attrs, inputs, proto_obj):\n    new_attrs = translation_utils._fix_attribute_names(attrs,\n                                                       {'bias': 'knorm',\n                                                        'size' : 'nsize'})\n    return 'LRN', new_attrs, inputs",
    "docstring": "Local Response Normalization."
  },
  {
    "code": "def _g(self, h, xp, s):\n        nphi = sum(self.phi)\n        return (nphi / 2.0) * log(2 * pi) + nphi * \\\n            log(s) + 0.5 * sum((h - xp) ** 2) / (s ** 2)",
    "docstring": "Density function for blow and hop moves"
  },
  {
    "code": "def _extract_labels(time_series):\n    labels = {\"resource_type\": time_series.resource.type}\n    labels.update(time_series.resource.labels)\n    labels.update(time_series.metric.labels)\n    return labels",
    "docstring": "Build the combined resource and metric labels, with resource_type."
  },
  {
    "code": "def read_release_version():\n    import re\n    dirname = os.path.abspath(os.path.dirname(__file__))\n    try:\n        f = open(os.path.join(dirname, \"_version.py\"), \"rt\")\n        for line in f.readlines():\n            m = re.match(\"__version__ = '([^']+)'\", line)\n            if m:\n                ver = m.group(1)\n                return ver\n    except:\n        return None\n    return None",
    "docstring": "Read the release version from ``_version.py``."
  },
  {
    "code": "def run_iperf_client(self, server_host, extra_args=''):\n        out = self.adb.shell('iperf3 -c %s %s' % (server_host, extra_args))\n        clean_out = new_str(out, 'utf-8').strip().split('\\n')\n        if 'error' in clean_out[0].lower():\n            return False, clean_out\n        return True, clean_out",
    "docstring": "Start iperf client on the device.\n\n        Return status as true if iperf client start successfully.\n        And data flow information as results.\n\n        Args:\n            server_host: Address of the iperf server.\n            extra_args: A string representing extra arguments for iperf client,\n                e.g. '-i 1 -t 30'.\n\n        Returns:\n            status: true if iperf client start successfully.\n            results: results have data flow information"
  },
  {
    "code": "def daylight_utc(self, date, latitude, longitude, observer_elevation=0):\n        start = self.sunrise_utc(date, latitude, longitude, observer_elevation)\n        end = self.sunset_utc(date, latitude, longitude, observer_elevation)\n        return start, end",
    "docstring": "Calculate daylight start and end times in the UTC timezone.\n\n        :param date:       Date to calculate for.\n        :type date:        :class:`datetime.date`\n        :param latitude:   Latitude - Northern latitudes should be positive\n        :type latitude:    float\n        :param longitude:  Longitude - Eastern longitudes should be positive\n        :type longitude:   float\n        :param observer_elevation:  Elevation in metres to calculate daylight for\n        :type observer_elevation:   int\n\n        :return: A tuple of the UTC date and time at which daylight starts and ends.\n        :rtype: (:class:`~datetime.datetime`, :class:`~datetime.datetime`)"
  },
  {
    "code": "def com_google_fonts_check_metadata_familyname(family_metadata):\n  name = \"\"\n  fail = False\n  for f in family_metadata.fonts:\n    if name and f.name != name:\n      fail = True\n    name = f.name\n  if fail:\n    yield FAIL, (\"METADATA.pb: Family name is not the same\"\n                 \" in all metadata \\\"fonts\\\" items.\")\n  else:\n    yield PASS, (\"METADATA.pb: Family name is the same\"\n                 \" in all metadata \\\"fonts\\\" items.\")",
    "docstring": "Check that METADATA.pb family values are all the same."
  },
  {
    "code": "def all_pkgs(self):\n        if not self.packages:\n            self.packages = self.get_pkg_list()\n        return self.packages",
    "docstring": "Return a list of all packages."
  },
  {
    "code": "def draw_layer(ax, layer):\n    ax.set_aspect('equal', 'datalim')\n    ax.plot(*layer)\n    ax.axis('off')",
    "docstring": "Draws a layer on the given matplotlib axis.\n\n    Args:\n        ax (axis): the matplotlib axis to draw on\n        layer (layer): the layers to plot"
  },
  {
    "code": "def part(self, target, reason=None):\n        if reason:\n            target += ' :' + reason\n        self.send_line('PART %s' % target)",
    "docstring": "quit a channel"
  },
  {
    "code": "def _search_inasafe_layer(self):\n        selected_nodes = self.iface.layerTreeView().selectedNodes()\n        for selected_node in selected_nodes:\n            tree_layers = [\n                child for child in selected_node.children() if (\n                    isinstance(child, QgsLayerTreeLayer))]\n            for tree_layer in tree_layers:\n                layer = tree_layer.layer()\n                keywords = self.keyword_io.read_keywords(layer)\n                if keywords.get('inasafe_fields'):\n                    return layer",
    "docstring": "Search for an inasafe layer in an active group.\n\n        :returns: A valid layer.\n        :rtype: QgsMapLayer\n\n        .. versionadded:: 4.3"
  },
  {
    "code": "def release_readme_verify():\n    version = \"{version}\"\n    expected = populate_readme(\n        version,\n        version,\n        pypi=\"\",\n        pypi_img=\"\",\n        versions=\"\\n\\n\",\n        versions_img=\"\",\n        circleci_badge=CIRCLECI_BADGE_RELEASE,\n        circleci_path=\"/{circleci_build}\",\n        travis_badge=TRAVIS_BADGE_RELEASE,\n        travis_path=\"/builds/{travis_build}\",\n        appveyor_badge=APPVEYOR_BADGE_RELEASE,\n        appveyor_path=\"/build/{appveyor_build}\",\n        coveralls_badge=COVERALLS_BADGE_RELEASE,\n        coveralls_path=\"builds/{coveralls_build}\",\n    )\n    with open(RELEASE_README_FILE, \"r\") as file_obj:\n        contents = file_obj.read()\n    if contents != expected:\n        err_msg = \"\\n\" + get_diff(\n            contents,\n            expected,\n            \"README.rst.release.actual\",\n            \"README.rst.release.expected\",\n        )\n        raise ValueError(err_msg)\n    else:\n        print(\"README.rst.release.template contents are as expected.\")",
    "docstring": "Specialize the template to a PyPI release template.\n\n    Once populated, compare to ``README.rst.release.template``.\n\n    Raises:\n        ValueError: If the current template doesn't agree with the expected\n            value specialized from the template."
  },
  {
    "code": "def remove_timedim(self, var):\n        if self.pps and var.dims[0] == 'time':\n            data = var[0, :, :]\n            data.attrs = var.attrs\n            var = data\n        return var",
    "docstring": "Remove time dimension from dataset"
  },
  {
    "code": "def merge_limits(axes, xlim=True, ylim=True):\n    xlims = list()\n    ylims = list()\n    for ax in axes:\n        [xlims.append(lim) for lim in ax.get_xlim()]\n        [ylims.append(lim) for lim in ax.get_ylim()]\n    for ax in axes:\n        if xlim:\n            ax.set_xlim(min(xlims), max(xlims))\n        if ylim:\n            ax.set_ylim(min(ylims), max(ylims))\n    return None",
    "docstring": "Set maximum and minimum limits from list of axis objects to each axis\n\n    Args\n    ----\n    axes: iterable\n        list of `matplotlib.pyplot` axis objects whose limits should be modified\n    xlim: bool\n        Flag to set modification of x axis limits\n    ylim: bool\n        Flag to set modification of y axis limits"
  },
  {
    "code": "def get_current_roles():\n    current_host = env.host_string\n    roledefs = env.get('roledefs')\n    if roledefs:\n        return [role for role, hosts in six.iteritems(roledefs) if current_host in hosts]\n    return []",
    "docstring": "Determines the list of roles, that the current host is assigned to. If ``env.roledefs`` is not set, an empty list\n    is returned.\n\n    :return: List of roles of the current host.\n    :rtype: list"
  },
  {
    "code": "def _validate_func_args(func, kwargs):\n    args, varargs, varkw, defaults = inspect.getargspec(func)\n    if set(kwargs.keys()) != set(args[1:]):\n        raise TypeError(\"decorator kwargs do not match %s()'s kwargs\"\n                        % func.__name__)",
    "docstring": "Validate decorator args when used to decorate a function."
  },
  {
    "code": "def split_pubnote(pubnote_str):\n    pubnote = {}\n    parts = pubnote_str.split(',')\n    if len(parts) > 2:\n        pubnote['journal_title'] = parts[0]\n        pubnote['journal_volume'] = parts[1]\n        pubnote['page_start'], pubnote['page_end'], pubnote['artid'] = split_page_artid(parts[2])\n    return {key: val for (key, val) in six.iteritems(pubnote) if val is not None}",
    "docstring": "Split pubnote into journal information."
  },
  {
    "code": "def get_domain_report(self, this_domain, timeout=None):\n        params = {'apikey': self.api_key, 'domain': this_domain}\n        try:\n            response = requests.get(self.base + 'domain/report', params=params, proxies=self.proxies, timeout=timeout)\n        except requests.RequestException as e:\n            return dict(error=str(e))\n        return _return_response_and_status_code(response)",
    "docstring": "Get information about a given domain.\n\n        :param this_domain: a domain name.\n        :param timeout: The amount of time in seconds the request should wait before timing out.\n\n        :return: JSON response"
  },
  {
    "code": "def do(self, command, files=None, use_long_polling=False, request_timeout=None, **query):\n        url, params = self._prepare_request(command, query)\n        return {\n            \"url\": url, \"params\": params, \"files\": files, \"stream\": use_long_polling,\n            \"verify\": True,\n            \"timeout\": request_timeout\n        }",
    "docstring": "Return the request params we would send to the api."
  },
  {
    "code": "def extract(ctx, input, output):\n    log.info('chemdataextractor.extract')\n    log.info('Reading %s' % input.name)\n    doc = Document.from_file(input, fname=input.name)\n    records = [record.serialize(primitive=True) for record in doc.records]\n    jsonstring = json.dumps(records, indent=2, ensure_ascii=False)\n    output.write(jsonstring)",
    "docstring": "Run ChemDataExtractor on a document."
  },
  {
    "code": "def json(self, **kwargs):\n        body = self._decompress(self.encoding)\n        return _json.loads(body, **kwargs)",
    "docstring": "If the response's body is valid json, we load it as a python dict\n        and return it."
  },
  {
    "code": "def remove(self, member):\n        if not self.client.zrem(self.name, member):\n            raise KeyError(member)",
    "docstring": "Remove member."
  },
  {
    "code": "def kruskal_mst(graph):\n    edges_accepted = 0\n    ds = DisjointSet()\n    pq = PriorityQueue()\n    accepted_edges = []\n    label_lookup = {}\n    nodes = graph.get_all_node_ids()\n    num_vertices = len(nodes)\n    for n in nodes:\n        label = ds.add_set()\n        label_lookup[n] = label\n    edges = graph.get_all_edge_objects()\n    for e in edges:\n        pq.put(e['id'], e['cost'])\n    while edges_accepted < (num_vertices - 1):\n        edge_id = pq.get()\n        edge = graph.get_edge(edge_id)\n        node_a, node_b = edge['vertices']\n        label_a = label_lookup[node_a]\n        label_b = label_lookup[node_b]\n        a_set = ds.find(label_a)\n        b_set = ds.find(label_b)\n        if a_set != b_set:\n            edges_accepted += 1\n            accepted_edges.append(edge_id)\n            ds.union(a_set, b_set)\n    return accepted_edges",
    "docstring": "Implements Kruskal's Algorithm for finding minimum spanning trees.\n    Assumes a non-empty, connected graph."
  },
  {
    "code": "def parse_media_range(range):\n    (type, subtype, params) = parse_mime_type(range)\n    params.setdefault('q', params.pop('Q', None))\n    try:\n        if not params['q'] or not 0 <= float(params['q']) <= 1:\n            params['q'] = '1'\n    except ValueError:\n        params['q'] = '1'\n    return (type, subtype, params)",
    "docstring": "Parse a media-range into its component parts.\n\n    Carves up a media range and returns a tuple of the (type, subtype,\n    params) where 'params' is a dictionary of all the parameters for the media\n    range.  For example, the media range 'application/*;q=0.5' would get parsed\n    into:\n\n       ('application', '*', {'q', '0.5'})\n\n    In addition this function also guarantees that there is a value for 'q'\n    in the params dictionary, filling it in with a proper default if\n    necessary.\n\n    :rtype: (str,str,dict)"
  },
  {
    "code": "def has_provider_support(provider, media_type):\n    if provider.lower() not in API_ALL:\n        return False\n    provider_const = \"API_\" + media_type.upper()\n    return provider in globals().get(provider_const, {})",
    "docstring": "Verifies if API provider has support for requested media type"
  },
  {
    "code": "def _sendto(self, data, addr=None, attempts=10):\n        tries = 0\n        slp_time = lambda: 0.5 / random.randint(10, 30)\n        slp = slp_time()\n        while tries < attempts:\n            try:\n                self.transport.sendto(data, addr=addr)\n                self.log.debug('Sent successfully')\n                return\n            except AttributeError as ex:\n                self.log.debug('Permission error: %s', ex)\n                time.sleep(slp)\n                tries += 1\n                slp += slp_time()",
    "docstring": "On multi-master environments, running on the same machine,\n        transport sending to the destination can be allowed only at once.\n        Since every machine will immediately respond, high chance to\n        get sending fired at the same time, which will result to a PermissionError\n        at socket level. We are attempting to send it in a different time.\n\n        :param data:\n        :param addr:\n        :return:"
  },
  {
    "code": "def compare(left: Optional[L], right: Optional[R]) -> 'Comparison[L, R]':\n        if isinstance(left, File) and isinstance(right, Directory):\n            return FileDirectoryComparison(left, right)\n        if isinstance(left, Directory) and isinstance(right, File):\n            return DirectoryFileComparison(left, right)\n        if isinstance(left, File) or isinstance(right, File):\n            return FileComparison(left, right)\n        if isinstance(left, Directory) or isinstance(right, Directory):\n            return DirectoryComparison(left, right)\n        raise TypeError(f'Cannot compare entities: {left}, {right}')",
    "docstring": "Calculate the comparison of two entities.\n\n        | left      | right     | Return Type             |\n        |===========|===========|=========================|\n        | file      | file      | FileComparison          |\n        | file      | directory | FileDirectoryComparison |\n        | file      | None      | FileComparison          |\n        | directory | file      | DirectoryFileComparison |\n        | directory | directory | DirectoryComparison     |\n        | directory | None      | DirectoryComparison     |\n        | None      | file      | FileComparison          |\n        | None      | directory | DirectoryComparison     |\n        | None      | None      | TypeError               |\n\n        :param left: The left side or \"before\" entity.\n        :param right: The right side or \"after\" entity.\n        :return: See table above."
  },
  {
    "code": "def get_submissions(student_item_dict, limit=None):\n    student_item_model = _get_or_create_student_item(student_item_dict)\n    try:\n        submission_models = Submission.objects.filter(\n            student_item=student_item_model)\n    except DatabaseError:\n        error_message = (\n            u\"Error getting submission request for student item {}\"\n            .format(student_item_dict)\n        )\n        logger.exception(error_message)\n        raise SubmissionNotFoundError(error_message)\n    if limit:\n        submission_models = submission_models[:limit]\n    return SubmissionSerializer(submission_models, many=True).data",
    "docstring": "Retrieves the submissions for the specified student item,\n    ordered by most recent submitted date.\n\n    Returns the submissions relative to the specified student item. Exception\n    thrown if no submission is found relative to this location.\n\n    Args:\n        student_item_dict (dict): The location of the problem this submission is\n            associated with, as defined by a course, student, and item.\n        limit (int): Optional parameter for limiting the returned number of\n            submissions associated with this student item. If not specified, all\n            associated submissions are returned.\n\n    Returns:\n        List dict: A list of dicts for the associated student item. The submission\n        contains five attributes: student_item, attempt_number, submitted_at,\n        created_at, and answer. 'student_item' is the ID of the related student\n        item for the submission. 'attempt_number' is the attempt this submission\n        represents for this question. 'submitted_at' represents the time this\n        submission was submitted, which can be configured, versus the\n        'created_at' date, which is when the submission is first created.\n\n    Raises:\n        SubmissionRequestError: Raised when the associated student item fails\n            validation.\n        SubmissionNotFoundError: Raised when a submission cannot be found for\n            the associated student item.\n\n    Examples:\n        >>> student_item_dict = dict(\n        >>>    student_id=\"Tim\",\n        >>>    item_id=\"item_1\",\n        >>>    course_id=\"course_1\",\n        >>>    item_type=\"type_one\"\n        >>> )\n        >>> get_submissions(student_item_dict, 3)\n        [{\n            'student_item': 2,\n            'attempt_number': 1,\n            'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>),\n            'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>),\n            'answer': u'The answer is 42.'\n        }]"
  },
  {
    "code": "def changeGroupImageRemote(self, image_url, thread_id=None):\n        (image_id, mimetype), = self._upload(get_files_from_urls([image_url]))\n        return self._changeGroupImage(image_id, thread_id)",
    "docstring": "Changes a thread image from a URL\n\n        :param image_url: URL of an image to upload and change\n        :param thread_id: User/Group ID to change image. See :ref:`intro_threads`\n        :raises: FBchatException if request failed"
  },
  {
    "code": "def _gen_explain_command(\n        coll, spec, projection, skip, limit, batch_size,\n        options, read_concern):\n    cmd = _gen_find_command(\n        coll, spec, projection, skip, limit, batch_size, options)\n    if read_concern.level:\n        return SON([('explain', cmd), ('readConcern', read_concern.document)])\n    return SON([('explain', cmd)])",
    "docstring": "Generate an explain command document."
  },
  {
    "code": "def add_rule(self, binding_type: str, rule: BindingRule):\n        if binding_type not in self._rules:\n            self._rules[binding_type] = []\n        self._rules[binding_type].insert(0, rule)",
    "docstring": "Adds new rule"
  },
  {
    "code": "def print_generic(self, msg, prefix=None):\n        if prefix is None:\n            self._log(msg, Logger.INFO)\n        else:\n            self._log(msg, prefix)\n        if self.use_sys:\n            if (prefix is not None) and (prefix in self.PREFIX_TO_PRINT_FUNCTION):\n                self.PREFIX_TO_PRINT_FUNCTION[prefix](msg)\n            else:\n                gf.safe_print(msg)",
    "docstring": "Print a message and log it.\n\n        :param msg: the message\n        :type  msg: Unicode string\n        :param prefix: the (optional) prefix\n        :type  prefix: Unicode string"
  },
  {
    "code": "def history(self):\n        params = {\"email\": self.email_address}\n        response = self._get(\"/subscribers/%s/history.json\" %\n                             self.list_id, params=params)\n        return json_to_py(response)",
    "docstring": "Gets the historical record of this subscriber's trackable actions."
  },
  {
    "code": "def extract_subsection(im, shape):\n    r\n    shape = sp.array(shape)\n    if shape[0] < 1:\n        shape = sp.array(im.shape) * shape\n    center = sp.array(im.shape) / 2\n    s_im = []\n    for dim in range(im.ndim):\n        r = shape[dim] / 2\n        lower_im = sp.amax((center[dim] - r, 0))\n        upper_im = sp.amin((center[dim] + r, im.shape[dim]))\n        s_im.append(slice(int(lower_im), int(upper_im)))\n    return im[tuple(s_im)]",
    "docstring": "r\"\"\"\n    Extracts the middle section of a image\n\n    Parameters\n    ----------\n    im : ND-array\n        Image from which to extract the subsection\n\n    shape : array_like\n        Can either specify the size of the extracted section or the fractional\n        size of the image to extact.\n\n    Returns\n    -------\n    image : ND-array\n        An ND-array of size given by the ``shape`` argument, taken from the\n        center of the image.\n\n    Examples\n    --------\n    >>> import scipy as sp\n    >>> from porespy.tools import extract_subsection\n    >>> im = sp.array([[1, 1, 1, 1], [1, 2, 2, 2], [1, 2, 3, 3], [1, 2, 3, 4]])\n    >>> print(im)\n    [[1 1 1 1]\n     [1 2 2 2]\n     [1 2 3 3]\n     [1 2 3 4]]\n    >>> im = extract_subsection(im=im, shape=[2, 2])\n    >>> print(im)\n    [[2 2]\n     [2 3]]"
  },
  {
    "code": "def set_denotation(onnx_model, input_name, denotation, target_opset, dimension_denotation=None):\n    if target_opset < 7:\n        warnings.warn('Denotation is not supported in targeted opset - %d' % target_opset)\n        return\n    for graph_input in onnx_model.graph.input:\n        if graph_input.name == input_name:\n            graph_input.type.denotation = denotation\n            if dimension_denotation:\n                dimensions = graph_input.type.tensor_type.shape.dim\n                if len(dimension_denotation) != len(dimensions):\n                    raise RuntimeError('Wrong number of dimensions: input \"{}\" has {} dimensions'.format(input_name, len(dimensions)))\n                for dimension, channel_denotation in zip(dimensions, dimension_denotation):\n                    dimension.denotation = channel_denotation\n            return onnx_model\n    raise RuntimeError('Input \"{}\" not found'.format(input_name))",
    "docstring": "Set input type denotation and dimension denotation.\n\n    Type denotation is a feature in ONNX 1.2.1 that let's the model specify the content of a tensor (e.g. IMAGE or AUDIO).\n    This information can be used by the backend. One example where it is useful is in images: Whenever data is bound to\n    a tensor with type denotation IMAGE, the backend can process the data (such as transforming the color space and\n    pixel format) based on model metadata properties.\n\n    :param onnx_model: ONNX model object\n    :param input_name: Name of input tensor to edit (example: `'data0'`)\n    :param denotation: Input type denotation (`documentation <https://github.com/onnx/onnx/blob/master/docs/TypeDenotation.md#type-denotation-definition>`_)\n    (example: `'IMAGE'`)\n    :param target_opset: Target ONNX opset\n    :param dimension_denotation: List of dimension type denotations. The length of the list must be the same of the number of dimensions in the tensor\n    (`documentation https://github.com/onnx/onnx/blob/master/docs/DimensionDenotation.md#denotation-definition>`_)\n    (example: `['DATA_BATCH', 'DATA_CHANNEL', 'DATA_FEATURE', 'DATA_FEATURE']`)"
  },
  {
    "code": "def on_failure(self, metadata):\n        self.connection.reset()\n        handler = self.handlers.get(\"on_failure\")\n        if callable(handler):\n            handler(metadata)\n        handler = self.handlers.get(\"on_summary\")\n        if callable(handler):\n            handler()\n        raise CypherError.hydrate(**metadata)",
    "docstring": "Called when a FAILURE message has been received."
  },
  {
    "code": "def get_command_signature(self, command):\n        parent = command.full_parent_name\n        if len(command.aliases) > 0:\n            aliases = '|'.join(command.aliases)\n            fmt = '[%s|%s]' % (command.name, aliases)\n            if parent:\n                fmt = parent + ' ' + fmt\n            alias = fmt\n        else:\n            alias = command.name if not parent else parent + ' ' + command.name\n        return '%s%s %s' % (self.clean_prefix, alias, command.signature)",
    "docstring": "Retrieves the signature portion of the help page.\n\n        Parameters\n        ------------\n        command: :class:`Command`\n            The command to get the signature of.\n\n        Returns\n        --------\n        :class:`str`\n            The signature for the command."
  },
  {
    "code": "def item_lister(command, _connection, page_size, page_number, sort_by,\n    sort_order, item_class, result_set, **kwargs):\n    page = page_number\n    while True:\n        item_collection = _connection.get_list(command,\n                                             page_size=page_size,\n                                             page_number=page,\n                                             sort_by=sort_by,\n                                             sort_order=sort_order,\n                                             item_class=item_class,\n                                             **kwargs)\n        result_set.total_count = item_collection.total_count\n        result_set.page_number = page\n        for item in item_collection.items:\n            yield item\n        if item_collection.total_count < 0 or item_collection.page_size == 0:\n            break\n        if len(item_collection.items) > 0:\n            page += 1\n        else:\n            break",
    "docstring": "A generator function for listing Video and Playlist objects."
  },
  {
    "code": "def set_params(self,**kwargs):\n        for key,value in list(kwargs.items()):\n            setattr(self,key,value)",
    "docstring": "Set the parameter values"
  },
  {
    "code": "def route(app_or_blueprint, context=default_context, **kwargs):\n    def decorator(fn):\n        fn = describe(**kwargs)(fn)\n        transmute_func = TransmuteFunction(fn)\n        routes, handler = create_routes_and_handler(transmute_func, context)\n        for r in routes:\n            if not hasattr(app_or_blueprint, SWAGGER_ATTR_NAME):\n                setattr(app_or_blueprint, SWAGGER_ATTR_NAME, SwaggerSpec())\n            swagger_obj = getattr(app_or_blueprint, SWAGGER_ATTR_NAME)\n            swagger_obj.add_func(transmute_func, context)\n            app_or_blueprint.route(r, methods=transmute_func.methods)(handler)\n        return handler\n    return decorator",
    "docstring": "attach a transmute route."
  },
  {
    "code": "def heightmap_add_voronoi(\n    hm: np.ndarray,\n    nbPoints: Any,\n    nbCoef: int,\n    coef: Sequence[float],\n    rnd: Optional[tcod.random.Random] = None,\n) -> None:\n    nbPoints = len(coef)\n    ccoef = ffi.new(\"float[]\", coef)\n    lib.TCOD_heightmap_add_voronoi(\n        _heightmap_cdata(hm),\n        nbPoints,\n        nbCoef,\n        ccoef,\n        rnd.random_c if rnd else ffi.NULL,\n    )",
    "docstring": "Add values from a Voronoi diagram to the heightmap.\n\n    Args:\n        hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.\n        nbPoints (Any): Number of Voronoi sites.\n        nbCoef (int): The diagram value is calculated from the nbCoef\n                      closest sites.\n        coef (Sequence[float]): The distance to each site is scaled by the\n                                corresponding coef.\n                                Closest site : coef[0],\n                                second closest site : coef[1], ...\n        rnd (Optional[Random]): A Random instance, or None."
  },
  {
    "code": "def get_changes(self, serialized=False, keep=False):\n        results = {}\n        for k, f, t in self._changes:\n            if k not in results:\n                results[k] = [f, None]\n            results[k][1] = (\n                self._serialize(k, t, self._fields)\n                if serialized else t\n            )\n        for k, v in six.iteritems(self):\n            if isinstance(v, Dirtyable):\n                result = v.get_changes(keep=keep)\n                if result:\n                    if not k in results:\n                        results[k] = [result[0], None]\n                    results[k][1] = (\n                        self._serialize(k, result[1], self._fields)\n                        if serialized else result[1]\n                    )\n        if not keep:\n            self._changes = []\n        return results",
    "docstring": "Get a journal of changes that have occurred\n\n        :param `serialized`:\n            Return changes in the serialized format used by TaskWarrior.\n        :param `keep_changes`:\n            By default, the list of changes is reset after running\n            ``.get_changes``; set this to `True` if you would like to\n            keep the changes recorded following running this command.\n\n        :returns: A dictionary of 2-tuples of changes, where the key is the\n            name of the field that has changed, and the value is a 2-tuple\n            containing the original value and the final value respectively."
  },
  {
    "code": "def _read_config(self):\n        if not self._file_path:\n            return None\n        elif self._file_path.startswith('s3://'):\n            return self._read_s3_config()\n        elif self._file_path.startswith('http://') or \\\n                self._file_path.startswith('https://'):\n            return self._read_remote_config()\n        elif not path.exists(self._file_path):\n            raise ValueError(\n                'Configuration file not found: {}'.format(self._file_path))\n        with open(self._file_path, 'r') as handle:\n            return handle.read()",
    "docstring": "Read the configuration from the various places it may be read from.\n\n        :rtype: str\n        :raises: ValueError"
  },
  {
    "code": "def graft(coll, branch, index):\n    pre = coll[:index]\n    post = coll[index:]\n    ret = pre + branch + post\n    return ret",
    "docstring": "Graft list branch into coll at index"
  },
  {
    "code": "def repartition(self, numPartitions):\n        return self.transform(\n            lambda rdd: (rdd.repartition(numPartitions)\n                         if not isinstance(rdd, EmptyRDD) else rdd)\n        )",
    "docstring": "Repartition every RDD.\n\n        :rtype: DStream\n\n\n        Example:\n\n        >>> import pysparkling\n        >>> sc = pysparkling.Context()\n        >>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)\n        >>> (\n        ...     ssc\n        ...     .queueStream([['hello', 'world']])\n        ...     .repartition(2)\n        ...     .foreachRDD(lambda rdd: print(len(rdd.partitions())))\n        ... )\n        >>> ssc.start()\n        >>> ssc.awaitTermination(0.25)\n        2\n        0"
  },
  {
    "code": "def sm_to_dot(model):\n    dot_str = HEADER\n    first = True\n    for state in model.states:\n        dot_str += '{}[label=\"{{{}{}|{}}}\"]\\n'.format(\n            id(state), r\"-\\> \" if first else \"\", state.name,\n            \"\\\\n\".join(action.name for action in state.actions))\n        first = False\n        for transition in state.transitions:\n            dot_str += '{} -> {} [label=\"{}\"]\\n'\\\n                .format(id(state), id(transition.to_state),\n                        transition.event.name)\n    if model.resetEvents:\n        dot_str += 'reset_events [label=\"{{Reset Events|{}}}\", style=\"\"]\\n'\\\n            .format(\"\\\\n\".join(event.name for event in model.resetEvents))\n    dot_str += '\\n}\\n'\n    return dot_str",
    "docstring": "Transforms given state machine model to dot str."
  },
  {
    "code": "def get_helper(name=None, quiet=True, **kwargs):\n    from helpme.defaults import HELPME_CLIENT\n    if name is not None:\n        HELPME_CLIENT = name\n    if   HELPME_CLIENT == 'github': from .github import Helper;\n    elif HELPME_CLIENT == 'uservoice': from .uservoice import Helper\n    elif HELPME_CLIENT == 'discourse': from .discourse import Helper\n    else: from .github import Helper\n    Helper.name = HELPME_CLIENT\n    Helper.quiet = quiet\n    return Helper()",
    "docstring": "get the correct helper depending on the environment variable\n       HELPME_CLIENT\n\n       quiet: if True, suppress most output about the client (e.g. speak)"
  },
  {
    "code": "def reduce(source, func, initializer=None):\n    acc = accumulate.raw(source, func, initializer)\n    return select.item.raw(acc, -1)",
    "docstring": "Apply a function of two arguments cumulatively to the items\n    of an asynchronous sequence, reducing the sequence to a single value.\n\n    If ``initializer`` is present, it is placed before the items\n    of the sequence in the calculation, and serves as a default when the\n    sequence is empty."
  },
  {
    "code": "def react(self, emojiname):\n        self._client.react_to_message(\n            emojiname=emojiname,\n            channel=self._body['channel'],\n            timestamp=self._body['ts'])",
    "docstring": "React to a message using the web api"
  },
  {
    "code": "def post_create_table(self, table):\n        table_opts = []\n        if 'impala_partition_by' in table.kwargs:\n            table_opts.append('PARTITION BY %s' % table.kwargs.get('impala_partition_by'))\n        if 'impala_stored_as' in table.kwargs:\n            table_opts.append('STORED AS %s' % table.kwargs.get('impala_stored_as'))\n        if 'impala_table_properties' in table.kwargs:\n            table_properties = [\"'{0}' = '{1}'\".format(property_, value)\n                                for property_, value\n                                in table.kwargs.get('impala_table_properties', {}).items()]\n            table_opts.append('TBLPROPERTIES (%s)' % ', '.join(table_properties))\n        return '\\n%s' % '\\n'.join(table_opts)",
    "docstring": "Build table-level CREATE options."
  },
  {
    "code": "def step_I_create_logrecords_with_table(context):\n    assert context.table, \"REQUIRE: context.table\"\n    context.table.require_columns([\"category\", \"level\", \"message\"])\n    for row in context.table.rows:\n        category = row[\"category\"]\n        if category == \"__ROOT__\":\n            category = None\n        level = LogLevel.parse_type(row[\"level\"])\n        message = row[\"message\"]\n        make_log_record(category, level, message)",
    "docstring": "Step definition that creates one more log records by using a table.\n\n    .. code-block: gherkin\n\n        When I create log records with:\n            | category | level | message   |\n            |  foo     | ERROR | Hello Foo |\n            |  foo.bar | WARN  | Hello Foo.Bar |\n\n    Table description\n    ------------------\n\n    | Column   | Type     | Required | Description |\n    | category | string   | yes      | Category (or logger) to use. |\n    | level    | LogLevel | yes      | Log level to use.   |\n    | message  | string   | yes      | Log message to use. |\n\n    .. code-block: python\n\n        import logging\n        from behave.configuration import LogLevel\n        for row in table.rows:\n            logger = logging.getLogger(row.category)\n            level  = LogLevel.parse_type(row.level)\n            logger.log(level, row.message)"
  },
  {
    "code": "def and_edge_predicates(edge_predicates: EdgePredicates) -> EdgePredicate:\n    if not isinstance(edge_predicates, Iterable):\n        return edge_predicates\n    edge_predicates = tuple(edge_predicates)\n    if 1 == len(edge_predicates):\n        return edge_predicates[0]\n    def concatenated_edge_predicate(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool:\n        return all(\n            edge_predicate(graph, u, v, k)\n            for edge_predicate in edge_predicates\n        )\n    return concatenated_edge_predicate",
    "docstring": "Concatenate multiple edge predicates to a new predicate that requires all predicates to be met."
  },
  {
    "code": "def on_http_error(error):\n    def wrap(f):\n        @functools.wraps(f)\n        def wrapped_f(*args, **kwargs):\n            try:\n                return f(*args, **kwargs)\n            except GitlabHttpError as e:\n                raise error(e.error_message, e.response_code, e.response_body)\n        return wrapped_f\n    return wrap",
    "docstring": "Manage GitlabHttpError exceptions.\n\n    This decorator function can be used to catch GitlabHttpError exceptions\n    raise specialized exceptions instead.\n\n    Args:\n        error(Exception): The exception type to raise -- must inherit from\n            GitlabError"
  },
  {
    "code": "def check_permission(self, request):\n        return all((permission.has_permission(request) for permission in self.permission_classes))",
    "docstring": "Check this field's permissions to determine whether or not it may be\n        shown."
  },
  {
    "code": "def _recurse_on_row(self, col_dict, nested_value):\n        row_value = None\n        if col_dict['mode'] == 'REPEATED' and isinstance(nested_value, list):\n            row_value = [self._transform_row(record['v'], col_dict['fields'])\n                         for record in nested_value]\n        else:\n            row_value = self._transform_row(nested_value, col_dict['fields'])\n        return row_value",
    "docstring": "Apply the schema specified by the given dict to the nested value by\n        recursing on it.\n\n        Parameters\n        ----------\n        col_dict : dict\n            The schema to apply to the nested value.\n        nested_value : A value nested in a BigQuery row.\n\n        Returns\n        -------\n        Union[dict, list]\n            ``dict`` or ``list`` of ``dict`` objects from applied schema."
  },
  {
    "code": "def _parseSegments(self, data, elfHeader):\n        offset = elfHeader.header.e_phoff\n        segments = []\n        for i in range(elfHeader.header.e_phnum):\n            phdr = self.__classes.PHDR.from_buffer(data, offset)\n            segment_bytes = (c_ubyte * phdr.p_filesz).from_buffer(data, phdr.p_offset)\n            phdrData = PhdrData(header=phdr, raw=segment_bytes, bytes=bytearray(segment_bytes), type=PT[phdr.p_type], vaddr=phdr.p_vaddr, offset=phdr.p_offset)\n            segments.append(phdrData)\n            offset += elfHeader.header.e_phentsize\n        return segments",
    "docstring": "Return a list of segments"
  },
  {
    "code": "def get_metadata_for_ids(pmid_list, get_issns_from_nlm=False,\n                         get_abstracts=False, prepend_title=False):\n    if len(pmid_list) > 200:\n        raise ValueError(\"Metadata query is limited to 200 PMIDs at a time.\")\n    params = {'db': 'pubmed',\n              'retmode': 'xml',\n              'id': pmid_list}\n    tree = send_request(pubmed_fetch, params)\n    if tree is None:\n        return None\n    return get_metadata_from_xml_tree(tree, get_issns_from_nlm, get_abstracts,\n                                      prepend_title)",
    "docstring": "Get article metadata for up to 200 PMIDs from the Pubmed database.\n\n    Parameters\n    ----------\n    pmid_list : list of PMIDs as strings\n        Can contain 1-200 PMIDs.\n    get_issns_from_nlm : boolean\n        Look up the full list of ISSN number for the journal associated with\n        the article, which helps to match articles to CrossRef search results.\n        Defaults to False, since it slows down performance.\n    get_abstracts : boolean\n        Indicates whether to include the Pubmed abstract in the results.\n    prepend_title : boolean\n        If get_abstracts is True, specifies whether the article title should\n        be prepended to the abstract text.\n\n    Returns\n    -------\n    dict of dicts\n        Dictionary indexed by PMID. Each value is a dict containing the\n        following fields: 'doi', 'title', 'authors', 'journal_title',\n        'journal_abbrev', 'journal_nlm_id', 'issn_list', 'page'."
  },
  {
    "code": "def js_extractor(response):\r\n    matches = rscript.findall(response)\r\n    for match in matches:\r\n        match = match[2].replace('\\'', '').replace('\"', '')\r\n        verb('JS file', match)\r\n        bad_scripts.add(match)",
    "docstring": "Extract js files from the response body"
  },
  {
    "code": "def _ctypes_out(parameter):\n    if (parameter.dimension is not None and \":\" in parameter.dimension\n        and \"out\" in parameter.direction and (\"allocatable\" in parameter.modifiers or\n                                              \"pointer\" in parameter.modifiers)):\n        if parameter.direction == \"(inout)\":\n            return (\"type(C_PTR), intent(inout) :: {}_o\".format(parameter.name), True)\n        else:\n            return (\"type(C_PTR), intent(inout) :: {}_c\".format(parameter.name), True)",
    "docstring": "Returns a parameter variable declaration for an output variable for the specified\n    parameter."
  },
  {
    "code": "def is_row_empty(self, row):\n    for cell in row:\n      if not self.is_cell_empty(cell):\n        return False\n    return True",
    "docstring": "Returns True if every cell in the row is empty."
  },
  {
    "code": "def _grid_in_property(field_name, docstring, read_only=False,\n                      closed_only=False):\n    def getter(self):\n        if closed_only and not self._closed:\n            raise AttributeError(\"can only get %r on a closed file\" %\n                                 field_name)\n        if field_name == 'length':\n            return self._file.get(field_name, 0)\n        return self._file.get(field_name, None)\n    def setter(self, value):\n        if self._closed:\n            self._coll.files.update_one({\"_id\": self._file[\"_id\"]},\n                                        {\"$set\": {field_name: value}})\n        self._file[field_name] = value\n    if read_only:\n        docstring += \"\\n\\nThis attribute is read-only.\"\n    elif closed_only:\n        docstring = \"%s\\n\\n%s\" % (docstring, \"This attribute is read-only and \"\n                                  \"can only be read after :meth:`close` \"\n                                  \"has been called.\")\n    if not read_only and not closed_only:\n        return property(getter, setter, doc=docstring)\n    return property(getter, doc=docstring)",
    "docstring": "Create a GridIn property."
  },
  {
    "code": "def stdrepr_iterable(self, obj, *,\n                         cls=None, before=None, after=None):\n        if cls is None:\n            cls = f'hrepr-{obj.__class__.__name__}'\n        children = [self(a) for a in obj]\n        return self.titled_box((before, after), children, 'h', 'h')[cls]",
    "docstring": "Helper function to represent iterables. StdHRepr calls this on\n        lists, tuples, sets and frozensets, but NOT on iterables in general.\n        This method may be called to produce custom representations.\n\n        Arguments:\n            obj (iterable): The iterable to represent.\n            cls (optional): The class name for the representation. If None,\n                stdrepr will use ``'hrepr-' + obj.__class__.___name__``\n            before (optional): A string or a Tag to prepend to the elements.\n            after (optional): A string or a Tag to append to the elements."
  },
  {
    "code": "def from_data(data):\n    if len(data) == 0:\n        return None\n    else:\n        ptable = PrettyTable()\n        ptable.field_names = data[0].keys()\n        for row in data:\n            ptable.add_row(row)\n        return ptable",
    "docstring": "Construct a Prettytable from list of rows."
  },
  {
    "code": "def seek(self, offset, whence=0):\n        self.flush()\n        if whence == self.SEEK_SET:\n            self._realpos = self._pos = offset\n        elif whence == self.SEEK_CUR:\n            self._pos += offset\n            self._realpos = self._pos\n        else:\n            self._realpos = self._pos = self._get_size() + offset\n        self._rbuffer = bytes()",
    "docstring": "Set the file's current position.\n\n        See `file.seek` for details."
  },
  {
    "code": "def _connect(dbfile: 'PathLike') -> apsw.Connection:\n    conn = apsw.Connection(os.fspath(dbfile))\n    _set_foreign_keys(conn, 1)\n    assert _get_foreign_keys(conn) == 1\n    return conn",
    "docstring": "Connect to SQLite database file."
  },
  {
    "code": "def regularpage(foldername=None, pagename=None):\n    if foldername is None and pagename is None:\n        raise ExperimentError('page_not_found')\n    if foldername is None and pagename is not None:\n        return render_template(pagename)\n    else:\n        return render_template(foldername+\"/\"+pagename)",
    "docstring": "Route not found by the other routes above. May point to a static template."
  },
  {
    "code": "def astimezone_and_leap_second(self, tz):\n        dt, leap_second = self.utc_datetime_and_leap_second()\n        normalize = getattr(tz, 'normalize', None)\n        if self.shape and normalize is not None:\n            dt = array([normalize(d.astimezone(tz)) for d in dt])\n        elif self.shape:\n            dt = array([d.astimezone(tz) for d in dt])\n        elif normalize is not None:\n            dt = normalize(dt.astimezone(tz))\n        else:\n            dt = dt.astimezone(tz)\n        return dt, leap_second",
    "docstring": "Convert to a Python ``datetime`` and leap second in a timezone.\n\n        Convert this time to a Python ``datetime`` and a leap second::\n\n            dt, leap_second = t.astimezone_and_leap_second(tz)\n\n        The argument ``tz`` should be a timezone from the third-party\n        ``pytz`` package, which must be installed separately.  The date\n        and time returned will be for that time zone.\n\n        The leap second value is provided because a Python ``datetime``\n        can only number seconds ``0`` through ``59``, but leap seconds\n        have a designation of at least ``60``.  The leap second return\n        value will normally be ``0``, but will instead be ``1`` if the\n        date and time are a UTC leap second.  Add the leap second value\n        to the ``second`` field of the ``datetime`` to learn the real\n        name of the second.\n\n        If this time is an array, then an array of ``datetime`` objects\n        and an array of leap second integers is returned, instead of a\n        single value each."
  },
  {
    "code": "def get_import_code(tlobject):\n    kind = 'functions' if tlobject.is_function else 'types'\n    ns = '.' + tlobject.namespace if tlobject.namespace else ''\n    return 'from telethon.tl.{}{} import {}'\\\n        .format(kind, ns, tlobject.class_name)",
    "docstring": "``TLObject -> from ... import ...``."
  },
  {
    "code": "def from_url(url, db=None, **kwargs):\n    from redis.client import Redis\n    return Redis.from_url(url, db, **kwargs)",
    "docstring": "Returns an active Redis client generated from the given database URL.\n\n    Will attempt to extract the database id from the path url fragment, if\n    none is provided."
  },
  {
    "code": "def addParts(parentPart, childPath, count, index):\n    if index == None:\n        index = 0\n    if index == len(childPath):\n        return\n    c = childPath[index]\n    parentPart.count = coalesce(parentPart.count, 0) + count\n    if parentPart.partitions == None:\n        parentPart.partitions = FlatList()\n    for i, part in enumerate(parentPart.partitions):\n        if part.name == c.name:\n            addParts(part, childPath, count, index + 1)\n            return\n    parentPart.partitions.append(c)\n    addParts(c, childPath, count, index + 1)",
    "docstring": "BUILD A hierarchy BY REPEATEDLY CALLING self METHOD WITH VARIOUS childPaths\n    count IS THE NUMBER FOUND FOR self PATH"
  },
  {
    "code": "def SADWindowSize(self, value):\n        if value >= 1 and value <= 11 and value % 2:\n            self._sad_window_size = value\n        else:\n            raise InvalidSADWindowSizeError(\"SADWindowSize must be odd and \"\n                                            \"between 1 and 11.\")\n        self._replace_bm()",
    "docstring": "Set private ``_sad_window_size`` and reset ``_block_matcher``."
  },
  {
    "code": "def target_to_source(target_adjacency, embedding):\n    source_adjacency = {v: set() for v in embedding}\n    reverse_embedding = {}\n    for v, chain in iteritems(embedding):\n        for u in chain:\n            if u in reverse_embedding:\n                raise ValueError(\"target node {} assigned to more than one source node\".format(u))\n            reverse_embedding[u] = v\n    for v, n in iteritems(reverse_embedding):\n        neighbors = target_adjacency[v]\n        for u in neighbors:\n            if u not in reverse_embedding:\n                continue\n            m = reverse_embedding[u]\n            if m == n:\n                continue\n            source_adjacency[n].add(m)\n            source_adjacency[m].add(n)\n    return source_adjacency",
    "docstring": "Derive the source adjacency from an embedding and target adjacency.\n\n    Args:\n        target_adjacency (dict/:class:`networkx.Graph`):\n            A dict of the form {v: Nv, ...} where v is a node in the target graph and Nv is the\n            neighbors of v as an iterable. This can also be a networkx graph.\n\n        embedding (dict):\n            A mapping from a source graph to a target graph.\n\n    Returns:\n        dict: The adjacency of the source graph.\n\n    Raises:\n        ValueError: If any node in the target_adjacency is assigned more\n            than  one node in the source graph by embedding.\n\n    Examples:\n\n        >>> target_adjacency = {0: {1, 3}, 1: {0, 2}, 2: {1, 3}, 3: {0, 2}}  # a square graph\n        >>> embedding = {'a': {0}, 'b': {1}, 'c': {2, 3}}\n        >>> source_adjacency = dimod.embedding.target_to_source(target_adjacency, embedding)\n        >>> source_adjacency  # triangle\n        {'a': {'b', 'c'}, 'b': {'a', 'c'}, 'c': {'a', 'b'}}\n\n        This function also works with networkx graphs.\n\n        >>> import networkx as nx\n        >>> target_graph = nx.complete_graph(5)\n        >>> embedding = {'a': {0, 1, 2}, 'b': {3, 4}}\n        >>> dimod.embedding.target_to_source(target_graph, embedding)"
  },
  {
    "code": "def setup(self, ds):\n        self._find_coord_vars(ds)\n        self._find_aux_coord_vars(ds)\n        self._find_ancillary_vars(ds)\n        self._find_clim_vars(ds)\n        self._find_boundary_vars(ds)\n        self._find_metadata_vars(ds)\n        self._find_cf_standard_name_table(ds)\n        self._find_geophysical_vars(ds)",
    "docstring": "Initialize various special variable types within the class.\n        Mutates a number of instance variables.\n\n        :param netCDF4.Dataset ds: An open netCDF dataset"
  },
  {
    "code": "def as_hyperbola(self, rotated=False):\n        idx = N.diag_indices(3)\n        _ = 1/self.covariance_matrix[idx]\n        d = list(_)\n        d[-1] *= -1\n        arr = N.identity(4)*-1\n        arr[idx] = d\n        hyp = conic(arr)\n        if rotated:\n            R = augment(self.axes)\n            hyp = hyp.transform(R)\n        return hyp",
    "docstring": "Hyperbolic error area"
  },
  {
    "code": "def attribute_read(self, sender, name):\n        \"Handles the creation of ExpectationBuilder when an attribute is read.\"\n        return ExpectationBuilder(self.sender, self.delegate, self.add_invocation, self.add_expectations, name)",
    "docstring": "Handles the creation of ExpectationBuilder when an attribute is read."
  },
  {
    "code": "def destroy(self, force=False):\n        if force:\n            super(UnmanagedLXC, self).destroy()\n        else:\n            raise UnmanagedLXCError('Destroying an unmanaged LXC might not '\n                'work. To continue please call this method with force=True')",
    "docstring": "UnmanagedLXC Destructor.\n\n        It requires force to be true in order to work. Otherwise it throws an\n        error."
  },
  {
    "code": "def worker_workerfinished(self, node):\n        self.config.hook.pytest_testnodedown(node=node, error=None)\n        if node.workeroutput[\"exitstatus\"] == 2:\n            self.shouldstop = \"%s received keyboard-interrupt\" % (node,)\n            self.worker_errordown(node, \"keyboard-interrupt\")\n            return\n        if node in self.sched.nodes:\n            crashitem = self.sched.remove_node(node)\n            assert not crashitem, (crashitem, node)\n        self._active_nodes.remove(node)",
    "docstring": "Emitted when node executes its pytest_sessionfinish hook.\n\n        Removes the node from the scheduler.\n\n        The node might not be in the scheduler if it had not emitted\n        workerready before shutdown was triggered."
  },
  {
    "code": "def inherit_dict(base, namespace, attr_name,\n                     inherit=lambda k, v: True):\n        items = []\n        base_dict = getattr(base, attr_name, {})\n        new_dict = namespace.setdefault(attr_name, {})\n        for key, value in base_dict.items():\n            if key in new_dict or (inherit and not inherit(key, value)):\n                continue\n            if inherit:\n                new_dict[key] = value\n            items.append((key, value))\n        return items",
    "docstring": "Perform inheritance of dictionaries.  Returns a list of key\n        and value pairs for values that were inherited, for\n        post-processing.\n\n        :param base: The base class being considered; see\n                     ``iter_bases()``.\n        :param namespace: The dictionary of the new class being built.\n        :param attr_name: The name of the attribute containing the\n                          dictionary to be inherited.\n        :param inherit: Filtering function to determine if a given\n                        item should be inherited.  If ``False`` or\n                        ``None``, item will not be added, but will be\n                        included in the returned items.  If a\n                        function, the function will be called with the\n                        key and value, and the item will be added and\n                        included in the items list only if the\n                        function returns ``True``.  By default, all\n                        items are added and included in the items\n                        list."
  },
  {
    "code": "def write_str(self, s):\n        self.write(s)\n        self.room -= len(s)",
    "docstring": "Add string s to the accumulated body."
  },
  {
    "code": "def lambda_not_found_response(*args):\n        response_data = jsonify(ServiceErrorResponses._NO_LAMBDA_INTEGRATION)\n        return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502)",
    "docstring": "Constructs a Flask Response for when a Lambda function is not found for an endpoint\n\n        :return: a Flask Response"
  },
  {
    "code": "def process_data(name=None):\n    ct = current_process()\n    if not hasattr(ct, '_pulsar_local'):\n        ct._pulsar_local = {}\n    loc = ct._pulsar_local\n    return loc.get(name) if name else loc",
    "docstring": "Fetch the current process local data dictionary.\n\n    If ``name`` is not ``None`` it returns the value at``name``,\n    otherwise it return the process data dictionary"
  },
  {
    "code": "def hijack_require_http_methods(fn):\n    required_methods = ['POST']\n    if hijack_settings.HIJACK_ALLOW_GET_REQUESTS:\n        required_methods.append('GET')\n    return require_http_methods(required_methods)(fn)",
    "docstring": "Wrapper for \"require_http_methods\" decorator. POST required by default, GET can optionally be allowed"
  },
  {
    "code": "def do_minus(self, parser, group):\n        grouper = group.__class__()\n        next_not = None\n        for node in group:\n            if isinstance(node, self.Minus):\n                if next_not is not None:\n                    continue\n                next_not = whoosh.qparser.syntax.NotGroup()\n                grouper.append(next_not)\n            else:\n                if isinstance(node, whoosh.qparser.syntax.GroupNode):\n                    node = self.do_minus(parser, node)\n                if next_not is not None:\n                    next_not.append(node)\n                    next_not = None\n                else:\n                    grouper.append(node)\n        if next_not is not None:\n            grouper.pop()\n        return grouper",
    "docstring": "This filter sorts nodes in a flat group into \"required\", \"default\",\n        and \"banned\" subgroups based on the presence of plus and minus nodes."
  },
  {
    "code": "def to_kaf(self):\n        if self.type == 'NAF':\n            for node in self.__get_opinion_nodes():\n                node.set('oid',node.get('id'))\n                del node.attrib['id']",
    "docstring": "Converts the opinion layer to KAF"
  },
  {
    "code": "def get_cell(self, row, column):\n        url = self.build_url(self._endpoints.get('get_cell').format(row=row, column=column))\n        response = self.session.get(url)\n        if not response:\n            return None\n        return self.range_constructor(parent=self, **{self._cloud_data_key: response.json()})",
    "docstring": "Gets the range object containing the single cell based on row and column numbers."
  },
  {
    "code": "def set_float_param(params, name, value, min=None, max=None):\n    if value is None:\n        return\n    try:\n        value = float(str(value))\n    except:\n        raise ValueError(\n            \"Parameter '%s' must be numeric (or a numeric string) or None,\"\n            \" got %r.\" % (name, value))\n    if min is not None and value < min:\n        raise ValueError(\n            \"Parameter '%s' must not be less than %r, got %r.\" % (\n                name, min, value))\n    if max is not None and value > max:\n        raise ValueError(\n            \"Parameter '%s' must not be greater than %r, got %r.\" % (\n                name, min, value))\n    params[name] = str(value)",
    "docstring": "Set a float parameter if applicable.\n\n    :param dict params: A dict containing API call parameters.\n\n    :param str name: The name of the parameter to set.\n\n    :param float value:\n        The value of the parameter. If ``None``, the field will not be set. If\n        an instance of a numeric type or a string that can be turned into a\n        ``float``, the relevant field will be set. Any other value will raise a\n        `ValueError`.\n\n    :param float min:\n        If provided, values less than this will raise ``ValueError``.\n\n    :param float max:\n        If provided, values greater than this will raise ``ValueError``.\n\n    :returns: ``None``"
  },
  {
    "code": "def add_plot(self, *args, extension='pdf', **kwargs):\n        add_image_kwargs = {}\n        for key in ('width', 'placement'):\n            if key in kwargs:\n                add_image_kwargs[key] = kwargs.pop(key)\n        filename = self._save_plot(*args, extension=extension, **kwargs)\n        self.add_image(filename, **add_image_kwargs)",
    "docstring": "Add the current Matplotlib plot to the figure.\n\n        The plot that gets added is the one that would normally be shown when\n        using ``plt.show()``.\n\n        Args\n        ----\n        args:\n            Arguments passed to plt.savefig for displaying the plot.\n        extension : str\n            extension of image file indicating figure file type\n        kwargs:\n            Keyword arguments passed to plt.savefig for displaying the plot. In\n            case these contain ``width`` or ``placement``, they will be used\n            for the same purpose as in the add_image command. Namely the width\n            and placement of the generated plot in the LaTeX document."
  },
  {
    "code": "def update_offer(self, offer_id, offer_dict):\n        return self._create_put_request(resource=OFFERS, billomat_id=offer_id, send_data=offer_dict)",
    "docstring": "Updates an offer\n\n        :param offer_id: the offer id\n        :param offer_dict: dict\n        :return: dict"
  },
  {
    "code": "def rvon_mises(mu, kappa, size=None):\n    return (np.random.mtrand.vonmises(\n        mu, kappa, size) + np.pi) % (2. * np.pi) - np.pi",
    "docstring": "Random von Mises variates."
  },
  {
    "code": "def get_all_reminders(self, params=None):\n        if not params:\n            params = {}\n        return self._iterate_through_pages(self.get_reminders_per_page, resource=REMINDERS, **{'params': params})",
    "docstring": "Get all reminders\n        This will iterate over all pages until it gets all elements.\n        So if the rate limit exceeded it will throw an Exception and you will get nothing\n\n        :param params: search params\n        :return: list"
  },
  {
    "code": "def memory():\n    memory_oper = ['read', 'write']\n    memory_scope = ['local', 'global']\n    test_command = 'sysbench --num-threads=64 --test=memory '\n    test_command += '--memory-oper={0} --memory-scope={1} '\n    test_command += '--memory-block-size=1K --memory-total-size=32G run '\n    result = None\n    ret_val = {}\n    for oper in memory_oper:\n        for scope in memory_scope:\n            key = 'Operation: {0} Scope: {1}'.format(oper, scope)\n            run_command = test_command.format(oper, scope)\n            result = __salt__['cmd.run'](run_command)\n            ret_val[key] = _parser(result)\n    return ret_val",
    "docstring": "This tests the memory for read and write operations.\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt '*' sysbench.memory"
  },
  {
    "code": "def eth_getBlockByNumber(self, number):\n        block_hash = self.reader._get_block_hash(number)\n        block_number = _format_block_number(number)\n        body_key = body_prefix + block_number + block_hash\n        block_data = self.db.get(body_key)\n        body = rlp.decode(block_data, sedes=Block)\n        return body",
    "docstring": "Get block body by block number.\n\n        :param number:\n        :return:"
  },
  {
    "code": "def memory_usage(self, index=True, deep=False):\n        result = Series([c.memory_usage(index=False, deep=deep)\n                         for col, c in self.iteritems()], index=self.columns)\n        if index:\n            result = Series(self.index.memory_usage(deep=deep),\n                            index=['Index']).append(result)\n        return result",
    "docstring": "Return the memory usage of each column in bytes.\n\n        The memory usage can optionally include the contribution of\n        the index and elements of `object` dtype.\n\n        This value is displayed in `DataFrame.info` by default. This can be\n        suppressed by setting ``pandas.options.display.memory_usage`` to False.\n\n        Parameters\n        ----------\n        index : bool, default True\n            Specifies whether to include the memory usage of the DataFrame's\n            index in returned Series. If ``index=True``, the memory usage of\n            the index is the first item in the output.\n        deep : bool, default False\n            If True, introspect the data deeply by interrogating\n            `object` dtypes for system-level memory consumption, and include\n            it in the returned values.\n\n        Returns\n        -------\n        Series\n            A Series whose index is the original column names and whose values\n            is the memory usage of each column in bytes.\n\n        See Also\n        --------\n        numpy.ndarray.nbytes : Total bytes consumed by the elements of an\n            ndarray.\n        Series.memory_usage : Bytes consumed by a Series.\n        Categorical : Memory-efficient array for string values with\n            many repeated values.\n        DataFrame.info : Concise summary of a DataFrame.\n\n        Examples\n        --------\n        >>> dtypes = ['int64', 'float64', 'complex128', 'object', 'bool']\n        >>> data = dict([(t, np.ones(shape=5000).astype(t))\n        ...              for t in dtypes])\n        >>> df = pd.DataFrame(data)\n        >>> df.head()\n           int64  float64  complex128  object  bool\n        0      1      1.0    1.0+0.0j       1  True\n        1      1      1.0    1.0+0.0j       1  True\n        2      1      1.0    1.0+0.0j       1  True\n        3      1      1.0    1.0+0.0j       1  True\n        4      1      1.0    1.0+0.0j       1  True\n\n        >>> df.memory_usage()\n        Index            80\n        int64         40000\n        float64       40000\n        complex128    80000\n        object        40000\n        bool           5000\n        dtype: int64\n\n        >>> df.memory_usage(index=False)\n        int64         40000\n        float64       40000\n        complex128    80000\n        object        40000\n        bool           5000\n        dtype: int64\n\n        The memory footprint of `object` dtype columns is ignored by default:\n\n        >>> df.memory_usage(deep=True)\n        Index             80\n        int64          40000\n        float64        40000\n        complex128     80000\n        object        160000\n        bool            5000\n        dtype: int64\n\n        Use a Categorical for efficient storage of an object-dtype column with\n        many repeated values.\n\n        >>> df['object'].astype('category').memory_usage(deep=True)\n        5168"
  },
  {
    "code": "def _check_user_parameters(self, user_parameters):\n        if not user_parameters:\n            return\n        for key in user_parameters:\n            if key not in submission_defaults:\n                raise ValueError(\"Unknown parameter {0}\".format(key))",
    "docstring": "Verifies that the parameter dict given by the user only contains\n        known keys. This ensures that the user detects typos faster."
  },
  {
    "code": "def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    try:\n        conn.create_saml_provider(saml_metadata_document, name)\n        log.info('Successfully created %s SAML provider.', name)\n        return True\n    except boto.exception.BotoServerError as e:\n        aws = __utils__['boto.get_error'](e)\n        log.debug(aws)\n        log.error('Failed to create SAML provider %s.', name)\n        return False",
    "docstring": "Create SAML provider\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document"
  },
  {
    "code": "def get_metadata(self):\n        try:\n            metadata = get_build_json()[\"metadata\"]\n            self.build_id = metadata[\"name\"]\n        except KeyError:\n            self.log.error(\"No build metadata\")\n            raise\n        for image in self.workflow.tag_conf.unique_images:\n            self.pullspec_image = image\n            break\n        for image in self.workflow.tag_conf.primary_images:\n            if '-' in image.tag[1:-1]:\n                self.pullspec_image = image\n                break\n        if not self.pullspec_image:\n            raise RuntimeError('Unable to determine pullspec_image')\n        metadata_version = 0\n        buildroot = self.get_buildroot(build_id=self.build_id)\n        output_files = self.get_output(buildroot['id'])\n        output = [output.metadata for output in output_files]\n        koji_metadata = {\n            'metadata_version': metadata_version,\n            'buildroots': [buildroot],\n            'output': output,\n        }\n        self.update_buildroot_koji(buildroot, output)\n        return koji_metadata, output_files",
    "docstring": "Build the metadata needed for importing the build\n\n        :return: tuple, the metadata and the list of Output instances"
  },
  {
    "code": "def tags(self, tags=None):\n        if tags is None or not tags:\n            return self\n        nodes = []\n        for node in self.nodes:\n            if any(tag in node.extra['tags'] for tag in tags):\n                nodes.append(node)\n        self.nodes = nodes\n        return self",
    "docstring": "Filter by tags.\n\n        :param  tags: Tags to filter.\n        :type   tags: ``list``\n\n        :return: A list of Node objects.\n        :rtype:  ``list`` of :class:`Node`"
  },
  {
    "code": "def _init_imu(self):\n        if not self._imu_init:\n            self._imu_init = self._imu.IMUInit()\n            if self._imu_init:\n                self._imu_poll_interval = self._imu.IMUGetPollInterval() * 0.001\n                self.set_imu_config(True, True, True)\n            else:\n                raise OSError('IMU Init Failed')",
    "docstring": "Internal. Initialises the IMU sensor via RTIMU"
  },
  {
    "code": "def ipv4(value, allow_empty = False):\n    if not value and allow_empty is False:\n        raise errors.EmptyValueError('value (%s) was empty' % value)\n    elif not value:\n        return None\n    try:\n        components = value.split('.')\n    except AttributeError:\n        raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)\n    if len(components) != 4 or not all(x.isdigit() for x in components):\n        raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)\n    for x in components:\n        try:\n            x = integer(x,\n                        minimum = 0,\n                        maximum = 255)\n        except ValueError:\n            raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)\n    return value",
    "docstring": "Validate that ``value`` is a valid IP version 4 address.\n\n    :param value: The value to validate.\n\n    :param allow_empty: If ``True``, returns :obj:`None <python:None>` if\n      ``value`` is empty. If ``False``, raises a\n      :class:`EmptyValueError <validator_collection.errors.EmptyValueError>`\n      if ``value`` is empty. Defaults to ``False``.\n    :type allow_empty: :class:`bool <python:bool>`\n\n    :returns: ``value`` / :obj:`None <python:None>`\n\n    :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``\n    :raises InvalidIPAddressError: if ``value`` is not a valid IP version 4 address or\n      empty with ``allow_empty`` set to ``True``"
  },
  {
    "code": "def setorigin(self):\n        try:\n            origin = self.repo.remotes.origin\n            if origin.url != self.origin_url:\n                log.debug('[%s] Changing origin url. Old: %s New: %s',\n                          self.name, origin.url, self.origin_url)\n                origin.config_writer.set('url', self.origin_url)\n        except AttributeError:\n            origin = self.repo.create_remote('origin', self.origin_url)\n            log.debug('[%s] Created remote \"origin\" with URL: %s',\n                      self.name, origin.url)",
    "docstring": "Set the 'origin' remote to the upstream url that we trust."
  },
  {
    "code": "def length_prepend(byte_string):\n    length = tx.VarInt(len(byte_string))\n    return length.to_bytes() + byte_string",
    "docstring": "bytes -> bytes"
  },
  {
    "code": "def delayed_assattr(self, node):\n        try:\n            frame = node.frame()\n            for inferred in node.expr.infer():\n                if inferred is util.Uninferable:\n                    continue\n                try:\n                    if inferred.__class__ is bases.Instance:\n                        inferred = inferred._proxied\n                        iattrs = inferred.instance_attrs\n                        if not _can_assign_attr(inferred, node.attrname):\n                            continue\n                    elif isinstance(inferred, bases.Instance):\n                        continue\n                    elif inferred.is_function:\n                        iattrs = inferred.instance_attrs\n                    else:\n                        iattrs = inferred.locals\n                except AttributeError:\n                    continue\n                values = iattrs.setdefault(node.attrname, [])\n                if node in values:\n                    continue\n                if (\n                    frame.name == \"__init__\"\n                    and values\n                    and values[0].frame().name != \"__init__\"\n                ):\n                    values.insert(0, node)\n                else:\n                    values.append(node)\n        except exceptions.InferenceError:\n            pass",
    "docstring": "Visit a AssAttr node\n\n        This adds name to locals and handle members definition."
  },
  {
    "code": "def show(self, visible=True, run=False):\n        self._backend._vispy_set_visible(visible)\n        if run:\n            self.app.run()",
    "docstring": "Show or hide the canvas\n\n        Parameters\n        ----------\n        visible : bool\n            Make the canvas visible.\n        run : bool\n            Run the backend event loop."
  },
  {
    "code": "def replace_meta(self, name, content=None, meta_key=None):\n        children = self.meta._children\n        if not content:\n            children = tuple(children)\n        meta_key = meta_key or 'name'\n        for child in children:\n            if child.attr(meta_key) == name:\n                if content:\n                    child.attr('content', content)\n                else:\n                    self.meta._children.remove(child)\n                return\n        if content:\n            self.add_meta(**{meta_key: name, 'content': content})",
    "docstring": "Replace the ``content`` attribute of meta tag ``name``\n\n        If the meta with ``name`` is not available, it is added, otherwise\n        its content is replaced. If ``content`` is not given or it is empty\n        the meta tag with ``name`` is removed."
  },
  {
    "code": "def add_bookmark(self, name, time, chan=''):\n        try:\n            bookmarks = self.rater.find('bookmarks')\n        except AttributeError:\n            raise IndexError('You need to have at least one rater')\n        new_bookmark = SubElement(bookmarks, 'bookmark')\n        bookmark_name = SubElement(new_bookmark, 'bookmark_name')\n        bookmark_name.text = name\n        bookmark_time = SubElement(new_bookmark, 'bookmark_start')\n        bookmark_time.text = str(time[0])\n        bookmark_time = SubElement(new_bookmark, 'bookmark_end')\n        bookmark_time.text = str(time[1])\n        if isinstance(chan, (tuple, list)):\n            chan = ', '.join(chan)\n        event_chan = SubElement(new_bookmark, 'bookmark_chan')\n        event_chan.text = chan\n        self.save()",
    "docstring": "Add a new bookmark\n\n        Parameters\n        ----------\n        name : str\n            name of the bookmark\n        time : (float, float)\n            float with start and end time in s\n\n        Raises\n        ------\n        IndexError\n            When there is no selected rater"
  },
  {
    "code": "def requestAvatarId(self, credentials):\n        username, domain = credentials.username.split(\"@\")\n        key = self.users.key(domain, username)\n        if key is None:\n            return defer.fail(UnauthorizedLogin())\n        def _cbPasswordChecked(passwordIsCorrect):\n            if passwordIsCorrect:\n                return username + '@' + domain\n            else:\n                raise UnauthorizedLogin()\n        return defer.maybeDeferred(credentials.checkPassword,\n                                   key).addCallback(_cbPasswordChecked)",
    "docstring": "Return the ID associated with these credentials.\n\n        @param credentials: something which implements one of the interfaces in\n        self.credentialInterfaces.\n\n        @return: a Deferred which will fire a string which identifies an\n        avatar, an empty tuple to specify an authenticated anonymous user\n        (provided as checkers.ANONYMOUS) or fire a Failure(UnauthorizedLogin).\n\n        @see: L{twisted.cred.credentials}"
  },
  {
    "code": "def save(self, fname=''):\n        if fname != '':\n            with open(fname, 'w') as f:\n                for i in self.lstPrograms:\n                    f.write(self.get_file_info_line(i, ','))\n        filemap = mod_filemap.FileMap([], [])\n        object_fileList = filemap.get_full_filename(filemap.find_type('OBJECT'), filemap.find_ontology('FILE-PROGRAM')[0])      \n        print('object_fileList = ' + object_fileList + '\\n')\n        if os.path.exists(object_fileList):\n            os.remove(object_fileList)\n        self.lstPrograms.sort()\n        try:\n            with open(object_fileList, 'a') as f:\n                f.write('\\n'.join([i[0] for i in self.lstPrograms]))\n        except Exception as ex:\n            print('ERROR = cant write to object_filelist ' , object_fileList, str(ex))",
    "docstring": "Save the list of items to AIKIF core and optionally to local file fname"
  },
  {
    "code": "def compile_with_symbol(self, func, theano_args=None, owner=None):\n        if theano_args is None:\n            theano_args = []\n        upc = UpdateCollector()\n        theano_ret = func(*theano_args) if owner is None \\\n            else func(owner, *theano_args)\n        out = copy.copy(self.default_options)\n        out['outputs'] = theano_ret\n        out['updates'] = upc.extract_updates()\n        return theano.function(theano_args, **out)",
    "docstring": "Compile the function with theano symbols"
  },
  {
    "code": "def _serialize(self, value, attr, obj):\n        try:\n            return super(DateString, self)._serialize(\n                arrow.get(value).date(), attr, obj)\n        except ParserError:\n            return missing",
    "docstring": "Serialize an ISO8601-formatted date."
  },
  {
    "code": "def get_authorizations_on_date(self, from_, to):\n        authorization_list = []\n        for authorization in self.get_authorizations():\n            if overlap(from_, to, authorization.start_date, authorization.end_date):\n                authorization_list.append(authorization)\n        return objects.AuthorizationList(authorization_list, runtime=self._runtime)",
    "docstring": "Gets an ``AuthorizationList`` effective during the entire given date range inclusive but not confined to the date range.\n\n        arg:    from (osid.calendaring.DateTime): starting date\n        arg:    to (osid.calendaring.DateTime): ending date\n        return: (osid.authorization.AuthorizationList) - the returned\n                ``Authorization`` list\n        raise:  InvalidArgument - ``from`` is greater than ``to``\n        raise:  NullArgument - ``from`` or ``to`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def read_message_type(file):\n    message_byte = file.read(1)\n    if message_byte == b'':\n        return ConnectionClosed\n    message_number = message_byte[0]\n    return _message_types.get(message_number, UnknownMessage)",
    "docstring": "Read the message type from a file."
  },
  {
    "code": "def ccifrm(frclss, clssid, lenout=_default_len_out):\n    frclss = ctypes.c_int(frclss)\n    clssid = ctypes.c_int(clssid)\n    lenout = ctypes.c_int(lenout)\n    frcode = ctypes.c_int()\n    frname = stypes.stringToCharP(lenout)\n    center = ctypes.c_int()\n    found = ctypes.c_int()\n    libspice.ccifrm_c(frclss, clssid, lenout, ctypes.byref(frcode), frname,\n                      ctypes.byref(center), ctypes.byref(found))\n    return frcode.value, stypes.toPythonString(\n        frname), center.value, bool(found.value)",
    "docstring": "Return the frame name, frame ID, and center associated with\n    a given frame class and class ID.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ccifrm_c.html\n\n    :param frclss: Class of frame.\n    :type frclss: int\n    :param clssid: Class ID of frame.\n    :type clssid: int\n    :param lenout: Maximum length of output string.\n    :type lenout: int\n    :return:\n            the frame name,\n            frame ID,\n            center.\n    :rtype: tuple"
  },
  {
    "code": "def get_fields(config):\n    for data in config['scraping']['data']:\n        if data['field'] != '': \n            yield data['field']\n    if 'next' in config['scraping']:\n        for n in config['scraping']['next']:\n            for f in get_fields(n): \n                yield f",
    "docstring": "Recursive generator that yields the field names in the config file\n\n    :param config: The configuration file that contains the specification of the extractor\n    :return: The field names in the config file, through a generator"
  },
  {
    "code": "def cluster_del_slots(self, slot, *slots):\n        slots = (slot,) + slots\n        if not all(isinstance(s, int) for s in slots):\n            raise TypeError(\"All parameters must be of type int\")\n        fut = self.execute(b'CLUSTER', b'DELSLOTS', *slots)\n        return wait_ok(fut)",
    "docstring": "Set hash slots as unbound in receiving node."
  },
  {
    "code": "def _set_value(self, entity, value):\n    if entity._projection:\n      raise ReadonlyPropertyError(\n          'You cannot set property values of a projection entity')\n    if self._repeated:\n      if not isinstance(value, (list, tuple, set, frozenset)):\n        raise datastore_errors.BadValueError('Expected list or tuple, got %r' %\n                                             (value,))\n      value = [self._do_validate(v) for v in value]\n    else:\n      if value is not None:\n        value = self._do_validate(value)\n    self._store_value(entity, value)",
    "docstring": "Internal helper to set a value in an entity for a Property.\n\n    This performs validation first.  For a repeated Property the value\n    should be a list."
  },
  {
    "code": "def closed_by(self, **kwargs):\n        path = '%s/%s/closed_by' % (self.manager.path, self.get_id())\n        return self.manager.gitlab.http_get(path, **kwargs)",
    "docstring": "List merge requests that will close the issue when merged.\n\n        Args:\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabGetErrot: If the merge requests could not be retrieved\n\n        Returns:\n            list: The list of merge requests."
  },
  {
    "code": "def get_zone_variable(self, zone_id, variable):\n        try:\n            return self._retrieve_cached_zone_variable(zone_id, variable)\n        except UncachedVariable:\n            return (yield from self._send_cmd(\"GET %s.%s\" % (\n                zone_id.device_str(), variable)))",
    "docstring": "Retrieve the current value of a zone variable.  If the variable is\n        not found in the local cache then the value is requested from the\n        controller."
  },
  {
    "code": "def socket_recv(self):\n        try:\n            data = self.sock.recv(2048)\n        except socket.error, ex:\n            print (\"?? socket.recv() error '%d:%s' from %s\" %\n                (ex[0], ex[1], self.addrport()))\n            raise BogConnectionLost()\n        size = len(data)\n        if size == 0:\n            raise BogConnectionLost()\n        self.last_input_time = time.time()\n        self.bytes_received += size\n        for byte in data:\n            self._iac_sniffer(byte)\n        while True:\n            mark = self.recv_buffer.find('\\n')\n            if mark == -1:\n                break\n            cmd = self.recv_buffer[:mark].strip()\n            self.command_list.append(cmd)\n            self.cmd_ready = True\n            self.recv_buffer = self.recv_buffer[mark+1:]",
    "docstring": "Called by TelnetServer when recv data is ready."
  },
  {
    "code": "def _load_themes(self):\n        with utils.temporary_chdir(utils.get_file_directory()):\n            self._append_theme_dir(\"themes\")\n            self.tk.eval(\"source themes/pkgIndex.tcl\")\n            theme_dir = \"gif\" if not self.png_support else \"png\"\n            self._append_theme_dir(theme_dir)\n            self.tk.eval(\"source {}/pkgIndex.tcl\".format(theme_dir))\n        self.tk.call(\"package\", \"require\", \"ttk::theme::scid\")",
    "docstring": "Load the themes into the Tkinter interpreter"
  },
  {
    "code": "def createBamHeader(self, baseHeader):\n        header = dict(baseHeader)\n        newSequences = []\n        for index, referenceInfo in enumerate(header['SQ']):\n            if index < self.numChromosomes:\n                referenceName = referenceInfo['SN']\n                assert referenceName == self.chromosomes[index]\n                newReferenceInfo = {\n                    'AS': self.referenceSetName,\n                    'SN': referenceName,\n                    'LN': 0,\n                    'UR': 'http://example.com',\n                    'M5': 'dbb6e8ece0b5de29da56601613007c2a',\n                    'SP': 'Human'\n                }\n                newSequences.append(newReferenceInfo)\n        header['SQ'] = newSequences\n        return header",
    "docstring": "Creates a new bam header based on the specified header from the\n        parent BAM file."
  },
  {
    "code": "def ceil_nearest(x, dx=1):\n    precision = get_sig_digits(dx)\n    return round(math.ceil(float(x) / dx) * dx, precision)",
    "docstring": "ceil a number to within a given rounding accuracy"
  },
  {
    "code": "def set_title(self, msg):\n        self.s.move(0, 0)\n        self.overwrite_line(msg, curses.A_REVERSE)",
    "docstring": "Set first header line text"
  },
  {
    "code": "def readfmt(stream, fmt):\n    size = struct.calcsize(fmt)\n    blob = stream.read(size)\n    return struct.unpack(fmt, blob)",
    "docstring": "Read and unpack an object from stream, using a struct format string."
  },
  {
    "code": "def lock_up_period(self, lock_up_period):\n        try:\n            if isinstance(lock_up_period, (str, int)):\n                self._lock_up_period = int(lock_up_period)\n        except Exception:\n            raise ValueError('invalid input of lock up period %s, cannot be converted to an int' %\n                             lock_up_period)",
    "docstring": "This lockup period is in months.  This might change to a relative delta."
  },
  {
    "code": "def set_timezone(rollback=False):\n    if not rollback:\n        if contains(filename='/etc/timezone', text=env.TIME_ZONE, use_sudo=True):\n            return False\n        if env.verbosity:\n            print env.host, \"CHANGING TIMEZONE /etc/timezone to \"+env.TIME_ZONE\n        _backup_file('/etc/timezone')\n        sudo('echo %s > /tmp/timezone'% env.TIME_ZONE)\n        sudo('cp -f /tmp/timezone /etc/timezone')\n        sudo('dpkg-reconfigure --frontend noninteractive tzdata')\n    else:\n        _restore_fie('/etc/timezone')\n        sudo('dpkg-reconfigure --frontend noninteractive tzdata')\n    return True",
    "docstring": "Set the time zone on the server using Django settings.TIME_ZONE"
  },
  {
    "code": "def EncryptPrivateKey(self, decrypted):\n        aes = AES.new(self._master_key, AES.MODE_CBC, self._iv)\n        return aes.encrypt(decrypted)",
    "docstring": "Encrypt the provided plaintext with the initialized private key.\n\n        Args:\n            decrypted (byte string): the plaintext to be encrypted.\n\n        Returns:\n            bytes: the ciphertext."
  },
  {
    "code": "def save_srm(self, filename):\n        with open(filename, 'wb') as fp:\n            raw_data = bread.write(self._song_data, spec.song)\n            fp.write(raw_data)",
    "docstring": "Save a project in .srm format to the target file.\n\n        :param filename: the name of the file to which to save"
  },
  {
    "code": "def reload(self):\n        text = self._read(self.location)\n        cursor_position = min(self.buffer.cursor_position, len(text))\n        self.buffer.document = Document(text, cursor_position)\n        self._file_content = text",
    "docstring": "Reload file again from storage."
  },
  {
    "code": "def create_customer(self, *, full_name, email):\n        payload = {\n            \"fullName\": full_name,\n            \"email\": email\n        }\n        return self.client._post(self.url + 'customers', json=payload, headers=self.get_headers())",
    "docstring": "Creation of a customer in the system.\n\n        Args:\n            full_name: Customer's complete name.\n            Alphanumeric. Max: 255.\n\n            email: Customer's email address.\n            Alphanumeric. Max: 255.\n\n        Returns:"
  },
  {
    "code": "def execute_process_async(func, *args, **kwargs):\n  global _GIPC_EXECUTOR\n  if _GIPC_EXECUTOR is None:\n    _GIPC_EXECUTOR = GIPCExecutor(\n      num_procs=settings.node.gipc_pool_size,\n      num_greenlets=settings.node.greenlet_pool_size)\n  return _GIPC_EXECUTOR.submit(func, *args, **kwargs)",
    "docstring": "Executes `func` in a separate process. Memory and other resources are not\n  available. This gives true concurrency at the cost of losing access to\n  these resources. `args` and `kwargs` are"
  },
  {
    "code": "def get_tunnels(self):\n        method = 'GET'\n        endpoint = '/rest/v1/{}/tunnels'.format(self.client.sauce_username)\n        return self.client.request(method, endpoint)",
    "docstring": "Retrieves all running tunnels for a specific user."
  },
  {
    "code": "def move_right(self):\n        self.at(ardrone.at.pcmd, True, self.speed, 0, 0, 0)",
    "docstring": "Make the drone move right."
  },
  {
    "code": "def salt_ssh():\n    import salt.cli.ssh\n    if '' in sys.path:\n        sys.path.remove('')\n    try:\n        client = salt.cli.ssh.SaltSSH()\n        _install_signal_handlers(client)\n        client.run()\n    except SaltClientError as err:\n        trace = traceback.format_exc()\n        try:\n            hardcrash = client.options.hard_crash\n        except (AttributeError, KeyError):\n            hardcrash = False\n        _handle_interrupt(\n            SystemExit(err),\n            err,\n            hardcrash, trace=trace)",
    "docstring": "Execute the salt-ssh system"
  },
  {
    "code": "def get_xpub(xpub, filter=None, limit=None, offset=None, api_code=None):\n    resource = 'multiaddr?active=' + xpub\n    if filter is not None:\n        if isinstance(filter, FilterType):\n            resource += '&filter=' + str(filter.value)\n        else:\n            raise ValueError('Filter must be of FilterType enum')\n    if limit is not None:\n        resource += '&limit=' + str(limit)\n    if offset is not None:\n        resource += '&offset=' + str(offset)\n    if api_code is not None:\n        resource += '&api_code=' + api_code\n    response = util.call_api(resource)\n    json_response = json.loads(response)\n    return Xpub(json_response)",
    "docstring": "Get data for a single xpub including balance and list of relevant transactions.\n\n    :param str xpub: address(xpub) to look up\n    :param FilterType filter: the filter for transactions selection (optional)\n    :param int limit: limit number of transactions to fetch (optional)\n    :param int offset: number of transactions to skip when fetch (optional)\n    :param str api_code: Blockchain.info API code (optional)\n    :return: an instance of :class:`Xpub` class"
  },
  {
    "code": "def on_btn_delete_fit(self, event):\n        self.delete_fit(self.current_fit, specimen=self.s)",
    "docstring": "removes the current interpretation\n\n        Parameters\n        ----------\n        event : the wx.ButtonEvent that triggered this function"
  },
  {
    "code": "def edit(self, request, id):\n        with pushd(tempfile.gettempdir()):\n            try:\n                self.clone(id)\n                with pushd(id):\n                    files = [f for f in os.listdir('.') if os.path.isfile(f)]\n                    quoted = ['\"{}\"'.format(f) for f in files]\n                    os.system(\"{} {}\".format(self.editor, ' '.join(quoted)))\n                    os.system('git commit -av && git push')\n            finally:\n                shutil.rmtree(id)",
    "docstring": "Edit a gist\n\n        The files in the gist a cloned to a temporary directory and passed to\n        the default editor (defined by the EDITOR environmental variable). When\n        the user exits the editor, they will be provided with a prompt to\n        commit the changes, which will then be pushed to the remote.\n\n        Arguments:\n            request: an initial request object\n            id:      the gist identifier"
  },
  {
    "code": "def _show_input_processor_key_buffer(self, cli, new_screen):\n        key_buffer = cli.input_processor.key_buffer\n        if key_buffer and _in_insert_mode(cli) and not cli.is_done:\n            data = key_buffer[-1].data\n            if get_cwidth(data) == 1:\n                cpos = new_screen.cursor_position\n                new_screen.data_buffer[cpos.y][cpos.x] = \\\n                    _CHAR_CACHE[data, Token.PartialKeyBinding]",
    "docstring": "When the user is typing a key binding that consists of several keys,\n        display the last pressed key if the user is in insert mode and the key\n        is meaningful to be displayed.\n        E.g. Some people want to bind 'jj' to escape in Vi insert mode. But the\n             first 'j' needs to be displayed in order to get some feedback."
  },
  {
    "code": "def get_restricted_sites(self, request):\n        try:\n            return request.user.get_sites()\n        except AttributeError:\n            return Site.objects.none()",
    "docstring": "The sites on which the user has permission on.\n\n        To return the permissions, the method check for the ``get_sites``\n        method on the user instance (e.g.: ``return request.user.get_sites()``)\n        which must return the queryset of enabled sites.\n        If the attribute does not exists, the user is considered enabled\n        for all the websites.\n\n        :param request: current request\n        :return: boolean or a queryset of available sites"
  },
  {
    "code": "async def async_connect(self):\n        kwargs = {\n            'username': self._username if self._username else None,\n            'client_keys': [self._ssh_key] if self._ssh_key else None,\n            'port': self._port,\n            'password': self._password if self._password else None,\n            'known_hosts': None\n        }\n        self._client = await asyncssh.connect(self._host, **kwargs)\n        self._connected = True",
    "docstring": "Fetches the client or creates a new one."
  },
  {
    "code": "def _explore_storage(self):\n        path = ''\n        dirs = [path]\n        while dirs:\n            path = dirs.pop()\n            subdirs, files = self.media_storage.listdir(path)\n            for media_filename in files:\n                yield os.path.join(path, media_filename)\n            dirs.extend([os.path.join(path, subdir) for subdir in subdirs])",
    "docstring": "Generator of all files contained in media storage."
  },
  {
    "code": "def load_config(self, custom_config):\n        self.config = configparser.ConfigParser()\n        if custom_config:\n            self.config.read(custom_config)\n            return f'Loading config from file {custom_config}.'\n        home = os.path.expanduser('~{}'.format(getpass.getuser()))\n        home_conf_file = os.path.join(home, '.cronyrc')\n        system_conf_file = '/etc/crony.conf'\n        conf_precedence = (home_conf_file, system_conf_file)\n        for conf_file in conf_precedence:\n            if os.path.exists(conf_file):\n                self.config.read(conf_file)\n                return f'Loading config from file {conf_file}.'\n        self.config['crony'] = {}\n        return 'No config file found.'",
    "docstring": "Attempt to load config from file.\n\n        If the command specified a --config parameter, then load that config file.\n        Otherwise, the user's home directory takes precedence over a system wide config.\n        Config file in the user's dir should be named \".cronyrc\".\n        System wide config should be located at \"/etc/crony.conf\""
  },
  {
    "code": "def crop_box(endpoint=None, filename=None):\n        crop_size = current_app.config['AVATARS_CROP_BASE_WIDTH']\n        if endpoint is None or filename is None:\n            url = url_for('avatars.static', filename='default/default_l.jpg')\n        else:\n            url = url_for(endpoint, filename=filename)\n        return Markup('<img src=\"%s\" id=\"crop-box\" style=\"max-width: %dpx; display: block;\">' % (url, crop_size))",
    "docstring": "Create a crop box.\n\n        :param endpoint: The endpoint of view function that serve avatar image file.\n        :param filename: The filename of the image that need to be crop."
  },
  {
    "code": "def _config_params(base_config, assoc_files, region, out_file, items):\n    params = []\n    dbsnp = assoc_files.get(\"dbsnp\")\n    if dbsnp:\n        params += [\"--dbsnp\", dbsnp]\n    cosmic = assoc_files.get(\"cosmic\")\n    if cosmic:\n        params += [\"--cosmic\", cosmic]\n    variant_regions = bedutils.population_variant_regions(items)\n    region = subset_variant_regions(variant_regions, region, out_file, items)\n    if region:\n        params += [\"-L\", bamprep.region_to_gatk(region), \"--interval_set_rule\",\n                   \"INTERSECTION\"]\n    min_af = tz.get_in([\"algorithm\", \"min_allele_fraction\"], base_config)\n    if min_af:\n        params += [\"--minimum_mutation_cell_fraction\", \"%.2f\" % (min_af / 100.0)]\n    resources = config_utils.get_resources(\"mutect\", base_config)\n    if resources.get(\"options\") is not None:\n        params += [str(x) for x in resources.get(\"options\", [])]\n    if \"--enable_qscore_output\" not in params:\n        params.append(\"--enable_qscore_output\")\n    return params",
    "docstring": "Add parameters based on configuration variables, associated files and genomic regions."
  },
  {
    "code": "def find_resistance(record):\n    for feature in record.features:\n        labels = set(feature.qualifiers.get(\"label\", []))\n        cassettes = labels.intersection(_ANTIBIOTICS)\n        if len(cassettes) > 1:\n            raise RuntimeError(\"multiple resistance cassettes detected\")\n        elif len(cassettes) == 1:\n            return _ANTIBIOTICS.get(cassettes.pop())\n    raise RuntimeError(\"could not find the resistance of '{}'\".format(record.id))",
    "docstring": "Infer the antibiotics resistance of the given record.\n\n    Arguments:\n        record (`~Bio.SeqRecord.SeqRecord`): an annotated sequence.\n\n    Raises:\n        RuntimeError: when there's not exactly one resistance cassette."
  },
  {
    "code": "def validate(self):\n        errors = []\n        app = errors.append\n        if not self.hint_cores >= self.mpi_procs * self.omp_threads >= self.min_cores:\n            app(\"self.hint_cores >= mpi_procs * omp_threads >= self.min_cores not satisfied\")\n        if self.omp_threads > self.hw.cores_per_node:\n            app(\"omp_threads > hw.cores_per_node\")\n        if self.mem_per_proc > self.hw.mem_per_node:\n            app(\"mem_mb >= self.hw.mem_per_node\")\n        if not self.max_mem_per_proc >= self.mem_per_proc >= self.min_mem_per_proc:\n            app(\"self.max_mem_per_proc >= mem_mb >= self.min_mem_per_proc not satisfied\")\n        if self.priority <= 0:\n            app(\"priority must be > 0\")\n        if not (1 <= self.min_cores <= self.hw.num_cores >= self.hint_cores):\n            app(\"1 <= min_cores <= hardware num_cores >= hint_cores not satisfied\")\n        if errors:\n            raise self.Error(str(self) + \"\\n\".join(errors))",
    "docstring": "Validate the parameters of the run. Raises self.Error if invalid parameters."
  },
  {
    "code": "def range_initialization(X, num_weights):\n    X_ = X.reshape(-1, X.shape[-1])\n    min_val, max_val = X_.min(0), X_.max(0)\n    data_range = max_val - min_val\n    return data_range * np.random.rand(num_weights,\n                                       X.shape[-1]) + min_val",
    "docstring": "Initialize the weights by calculating the range of the data.\n\n    The data range is calculated by reshaping the input matrix to a\n    2D matrix, and then taking the min and max values over the columns.\n\n    Parameters\n    ----------\n    X : numpy array\n        The input data. The data range is calculated over the last axis.\n    num_weights : int\n        The number of weights to initialize.\n\n    Returns\n    -------\n    new_weights : numpy array\n        A new version of the weights, initialized to the data range specified\n        by X."
  },
  {
    "code": "def set_alpha_for_selection(self, alpha):\n        selection = self.treeview_layers.get_selection()\n        list_store, selected_iter = selection.get_selected()\n        if selected_iter is None:\n            return\n        else:\n            surface_name, original_alpha = list_store[selected_iter]\n            self.set_alpha(surface_name, alpha)\n            self.set_scale_alpha_from_selection()",
    "docstring": "Set alpha for selected layer."
  },
  {
    "code": "def populate(self, **values):\n        values = values.copy()\n        fields = list(self.iterate_with_name())\n        for _, structure_name, field in fields:\n            if structure_name in values:\n                field.__set__(self, values.pop(structure_name))\n        for name, _, field in fields:\n            if name in values:\n                field.__set__(self, values.pop(name))",
    "docstring": "Populate values to fields. Skip non-existing."
  },
  {
    "code": "def fit_cosine_function(wind):\n    wind_daily = wind.groupby(wind.index.date).mean()\n    wind_daily_hourly = pd.Series(index=wind.index, data=wind_daily.loc[wind.index.date].values)\n    df = pd.DataFrame(data=dict(daily=wind_daily_hourly, hourly=wind)).dropna(how='any')\n    x = np.array([df.daily, df.index.hour])\n    popt, pcov = scipy.optimize.curve_fit(_cosine_function, x, df.hourly)\n    return popt",
    "docstring": "fits a cosine function to observed hourly windspeed data\n\n    Args:\n        wind: observed hourly windspeed data\n        \n    Returns:\n        parameters needed to generate diurnal features of windspeed using a cosine function"
  },
  {
    "code": "def init(opts):\n    if CONFIG_BASE_URL in opts['proxy']:\n        CONFIG[CONFIG_BASE_URL] = opts['proxy'][CONFIG_BASE_URL]\n    else:\n        log.error('missing proxy property %s', CONFIG_BASE_URL)\n    log.debug('CONFIG: %s', CONFIG)",
    "docstring": "Perform any needed setup."
  },
  {
    "code": "async def start(self):\n        self._loop.add_task(self._periodic_loop, name=\"periodic task for %s\" % self._adapter.__class__.__name__,\n                            parent=self._task)\n        self._adapter.add_callback('on_scan', functools.partial(_on_scan, self._loop, self))\n        self._adapter.add_callback('on_report', functools.partial(_on_report, self._loop, self))\n        self._adapter.add_callback('on_trace', functools.partial(_on_trace, self._loop, self))\n        self._adapter.add_callback('on_disconnect', functools.partial(_on_disconnect, self._loop, self))",
    "docstring": "Start the device adapter.\n\n        See :meth:`AbstractDeviceAdapter.start`."
  },
  {
    "code": "def group(self):\n        for group in self._server.groups:\n            if self.identifier in group.clients:\n                return group",
    "docstring": "Get group."
  },
  {
    "code": "def groupByNode(requestContext, seriesList, nodeNum, callback):\n    return groupByNodes(requestContext, seriesList, callback, nodeNum)",
    "docstring": "Takes a serieslist and maps a callback to subgroups within as defined by a\n    common node.\n\n    Example::\n\n        &target=groupByNode(ganglia.by-function.*.*.cpu.load5,2,\"sumSeries\")\n\n    Would return multiple series which are each the result of applying the\n    \"sumSeries\" function to groups joined on the second node (0 indexed)\n    resulting in a list of targets like::\n\n        sumSeries(ganglia.by-function.server1.*.cpu.load5),\n        sumSeries(ganglia.by-function.server2.*.cpu.load5),..."
  },
  {
    "code": "def remove_sbi_id(self, sbi_id):\n        sbi_ids = self.sbi_ids\n        sbi_ids.remove(sbi_id)\n        DB.set_hash_value(self._key, 'sbi_ids', sbi_ids)",
    "docstring": "Remove an SBI Identifier."
  },
  {
    "code": "def cleanup(self):\n        keys = self.client.smembers(self.keys_container)\n        for key in keys:\n            entry = self.client.get(key)\n            if entry:\n                entry = pickle.loads(entry)\n                if self._is_expired(entry, self.timeout):\n                    self.delete_entry(key)",
    "docstring": "Cleanup all the expired keys"
  },
  {
    "code": "def print_verbose(self):\n        print \"Nodes: \"\n        for a in (self.nodes(failed=\"all\")):\n            print a\n        print \"\\nVectors: \"\n        for v in (self.vectors(failed=\"all\")):\n            print v\n        print \"\\nInfos: \"\n        for i in (self.infos(failed=\"all\")):\n            print i\n        print \"\\nTransmissions: \"\n        for t in (self.transmissions(failed=\"all\")):\n            print t\n        print \"\\nTransformations: \"\n        for t in (self.transformations(failed=\"all\")):\n            print t",
    "docstring": "Print a verbose representation of a network."
  },
  {
    "code": "def union(self, another_moc, *args):\n        interval_set = self._interval_set.union(another_moc._interval_set)\n        for moc in args:\n            interval_set = interval_set.union(moc._interval_set)\n        return self.__class__(interval_set)",
    "docstring": "Union between the MOC instance and other MOCs.\n\n        Parameters\n        ----------\n        another_moc : `~mocpy.moc.MOC`\n            The MOC used for performing the union with self.\n        args : `~mocpy.moc.MOC`\n            Other additional MOCs to perform the union with.\n\n        Returns\n        -------\n        result : `~mocpy.moc.MOC`/`~mocpy.tmoc.TimeMOC`\n            The resulting MOC."
  },
  {
    "code": "def tell(self):\n        self._check_open_file()\n        if self._flushes_after_tell():\n            self.flush()\n        if not self._append:\n            return self._io.tell()\n        if self._read_whence:\n            write_seek = self._io.tell()\n            self._io.seek(self._read_seek, self._read_whence)\n            self._read_seek = self._io.tell()\n            self._read_whence = 0\n            self._io.seek(write_seek)\n        return self._read_seek",
    "docstring": "Return the file's current position.\n\n        Returns:\n          int, file's current position in bytes."
  },
  {
    "code": "def has_bom(self, f):\n        content = f.read(4)\n        encoding = None\n        m = RE_UTF_BOM.match(content)\n        if m is not None:\n            if m.group(1):\n                encoding = 'utf-8-sig'\n            elif m.group(2):\n                encoding = 'utf-32'\n            elif m.group(3):\n                encoding = 'utf-32'\n            elif m.group(4):\n                encoding = 'utf-16'\n            elif m.group(5):\n                encoding = 'utf-16'\n        return encoding",
    "docstring": "Check for UTF8, UTF16, and UTF32 BOMs."
  },
  {
    "code": "def full_photos(self):\n        if self._photos is None:\n            if self.total_photo_count > 0:\n                self.assert_bind_client()\n                self._photos = self.bind_client.get_activity_photos(self.id, only_instagram=False)\n            else:\n                self._photos = []\n        return self._photos",
    "docstring": "Gets a list of photos using default options.\n\n        :class:`list` of :class:`stravalib.model.ActivityPhoto` objects for this activity."
  },
  {
    "code": "def _register_user_models(user_models, admin=None, schema=None):\n    if any([issubclass(cls, AutomapModel) for cls in user_models]):\n        AutomapModel.prepare(\n                               db.engine, reflect=True, schema=schema)\n    for user_model in user_models:\n        register_model(user_model, admin)",
    "docstring": "Register any user-defined models with the API Service.\n\n    :param list user_models: A list of user-defined models to include in the\n                             API service"
  },
  {
    "code": "def pdf(self, mu):\n        if self.transform is not None:\n            mu = self.transform(mu)    \n        return self.pdf_internal(mu, df=self.df0, loc=self.loc0, scale=self.scale0, gamma=self.gamma0)",
    "docstring": "PDF for Skew t prior\n\n        Parameters\n        ----------\n        mu : float\n            Latent variable for which the prior is being formed over\n\n        Returns\n        ----------\n        - p(mu)"
  },
  {
    "code": "def get_entity(self,entity_id):\n        entity_node = self.map_entity_id_to_node.get(entity_id)\n        if entity_node is not None:\n            return Centity(node=entity_node,type=self.type)\n        else:\n            for entity_node in self.__get_entity_nodes():\n                if self.type == 'NAF': \n                    label_id = 'id'\n                elif self.type == 'KAF': \n                    label_id = 'eid'\n                if entity_node.get(label_id) == entity_id:\n                    return Centity(node=entity_node, type=self.type)                                                                \n            return None",
    "docstring": "Returns the entity object for the given entity identifier\n        @type entity_id: string\n        @param entity_id: the token identifier\n        @rtype: L{Centity}\n        @return: the entity object"
  },
  {
    "code": "def software_language(instance):\n    for key, obj in instance['objects'].items():\n        if ('type' in obj and obj['type'] == 'software' and\n                'languages' in obj):\n            for lang in obj['languages']:\n                if lang not in enums.SOFTWARE_LANG_CODES:\n                    yield JSONError(\"The 'languages' property of object '%s' \"\n                                    \"contains an invalid ISO 639-2 language \"\n                                    \" code ('%s').\"\n                                    % (key, lang), instance['id'])",
    "docstring": "Ensure the 'language' property of software objects is a valid ISO 639-2\n    language code."
  },
  {
    "code": "def glyph_extents(self, glyphs):\n        glyphs = ffi.new('cairo_glyph_t[]', glyphs)\n        extents = ffi.new('cairo_text_extents_t *')\n        cairo.cairo_glyph_extents(\n            self._pointer, glyphs, len(glyphs), extents)\n        self._check_status()\n        return (\n            extents.x_bearing, extents.y_bearing,\n            extents.width, extents.height,\n            extents.x_advance, extents.y_advance)",
    "docstring": "Returns the extents for a list of glyphs.\n\n        The extents describe a user-space rectangle\n        that encloses the \"inked\" portion of the glyphs,\n        (as it would be drawn by :meth:`show_glyphs`).\n        Additionally, the :obj:`x_advance` and :obj:`y_advance` values\n        indicate the amount by which the current point would be advanced\n        by :meth:`show_glyphs`.\n\n        :param glyphs:\n            A list of glyphs.\n            See :meth:`show_text_glyphs` for the data structure.\n        :returns:\n            A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)``\n            tuple of floats.\n            See :meth:`text_extents` for details."
  },
  {
    "code": "def add_point_feature(self, resnum, feat_type=None, feat_id=None, qualifiers=None):\n        if self.feature_file:\n            raise ValueError('Feature file associated with sequence, please remove file association to append '\n                             'additional features.')\n        if not feat_type:\n            feat_type = 'Manually added protein sequence single residue feature'\n        newfeat = SeqFeature(location=FeatureLocation(ExactPosition(resnum-1), ExactPosition(resnum)),\n                             type=feat_type,\n                             id=feat_id,\n                             qualifiers=qualifiers)\n        self.features.append(newfeat)",
    "docstring": "Add a feature to the features list describing a single residue.\n\n        Args:\n            resnum (int): Protein sequence residue number\n            feat_type (str, optional): Optional description of the feature type (ie. 'catalytic residue')\n            feat_id (str, optional): Optional ID of the feature type (ie. 'TM1')"
  },
  {
    "code": "def get_all_items_of_credit_note(self, credit_note_id):\n        return self._iterate_through_pages(\n            get_function=self.get_items_of_credit_note_per_page,\n            resource=CREDIT_NOTE_ITEMS,\n            **{'credit_note_id': credit_note_id}\n        )",
    "docstring": "Get all items of credit note\n        This will iterate over all pages until it gets all elements.\n        So if the rate limit exceeded it will throw an Exception and you will get nothing\n\n        :param credit_note_id: the credit note id\n        :return: list"
  },
  {
    "code": "def _generateInitialModel(self, output_model_type):\n        logger().info(\"Generating initial model for BHMM using MLHMM...\")\n        from bhmm.estimators.maximum_likelihood import MaximumLikelihoodEstimator\n        mlhmm = MaximumLikelihoodEstimator(self.observations, self.nstates, reversible=self.reversible,\n                                           output=output_model_type)\n        model = mlhmm.fit()\n        return model",
    "docstring": "Initialize using an MLHMM."
  },
  {
    "code": "def get_next_base26(prev=None):\n    if not prev:\n        return 'a'\n    r = re.compile(\"^[a-z]*$\")\n    if not r.match(prev):\n        raise ValueError(\"Invalid base26\")\n    if not prev.endswith('z'):\n        return prev[:-1] + chr(ord(prev[-1]) + 1)\n    return get_next_base26(prev[:-1]) + 'a'",
    "docstring": "Increment letter-based IDs.\n\n    Generates IDs like ['a', 'b', ..., 'z', 'aa', ab', ..., 'az', 'ba', ...]\n\n    Returns:\n        str: Next base-26 ID."
  },
  {
    "code": "def _read_xml_db(self):\n        try:\n            metadata_str = self.db_io.read_metadata_from_uri(\n                self.layer_uri, 'xml')\n            root = ElementTree.fromstring(metadata_str)\n            return root\n        except HashNotFoundError:\n            return None",
    "docstring": "read metadata from an xml string stored in a DB.\n\n        :return: the root element of the xml\n        :rtype: ElementTree.Element"
  },
  {
    "code": "def display(self):\n        lg.debug('GraphicsScene is between {}s and {}s'.format(self.minimum,\n                                                               self.maximum))\n        x_scale = 1 / self.parent.value('overview_scale')\n        lg.debug('Set scene x-scaling to {}'.format(x_scale))\n        self.scale(1 / self.transform().m11(), 1)\n        self.scale(x_scale, 1)\n        self.scene = QGraphicsScene(self.minimum, 0,\n                                    self.maximum,\n                                    TOTAL_HEIGHT)\n        self.setScene(self.scene)\n        self.idx_markers = []\n        self.idx_annot = []\n        self.display_current()\n        for name, pos in BARS.items():\n            item = QGraphicsRectItem(self.minimum, pos['pos0'],\n                                     self.maximum, pos['pos1'])\n            item.setToolTip(pos['tip'])\n            self.scene.addItem(item)\n        self.add_timestamps()",
    "docstring": "Updates the widgets, especially based on length of recordings."
  },
  {
    "code": "def altimeter(alt: Number, unit: str = 'inHg') -> str:\n    ret = 'Altimeter '\n    if not alt:\n        ret += 'unknown'\n    elif unit == 'inHg':\n        ret += core.spoken_number(alt.repr[:2]) + ' point ' + core.spoken_number(alt.repr[2:])\n    elif unit == 'hPa':\n        ret += core.spoken_number(alt.repr)\n    return ret",
    "docstring": "Format altimeter details into a spoken word string"
  },
  {
    "code": "def _populateFromVariantFile(self, varFile, dataUrl, indexFile):\n        if varFile.index is None:\n            raise exceptions.NotIndexedException(dataUrl)\n        for chrom in varFile.index:\n            chrom, _, _ = self.sanitizeVariantFileFetch(chrom)\n            if not isEmptyIter(varFile.fetch(chrom)):\n                if chrom in self._chromFileMap:\n                    raise exceptions.OverlappingVcfException(dataUrl, chrom)\n            self._chromFileMap[chrom] = dataUrl, indexFile\n        self._updateMetadata(varFile)\n        self._updateCallSetIds(varFile)\n        self._updateVariantAnnotationSets(varFile, dataUrl)",
    "docstring": "Populates the instance variables of this VariantSet from the specified\n        pysam VariantFile object."
  },
  {
    "code": "def get_issues():\n        issues = []\n        for entry in Logger.journal:\n            if entry.level >= WARNING:\n                issues.append(entry)\n        return issues",
    "docstring": "Get actual issues in the journal."
  },
  {
    "code": "def _attr_func_(self):\n        \"Special property containing functions to be lazily-evaluated.\"\n        try:\n            return self.__attr_func\n        except AttributeError:\n            self.__attr_func = type(\n                ''.join([type(self).__name__, 'EmptyFuncs']),\n                (),\n                {\n                    '__module__': type(self).__module__,\n                    '__slots__': ()\n                }\n            )()\n            return self.__attr_func",
    "docstring": "Special property containing functions to be lazily-evaluated."
  },
  {
    "code": "def create(cls, name, ne_ref=None, operator='exclusion',\n               sub_expression=None, comment=None):\n        sub_expression = [] if sub_expression is None else [sub_expression]\n        json = {'name': name,\n                'operator': operator,\n                'ne_ref': ne_ref,\n                'sub_expression': sub_expression,\n                'comment': comment}\n        return ElementCreator(cls, json)",
    "docstring": "Create the expression\n\n        :param str name: name of expression\n        :param list ne_ref: network element references for expression\n        :param str operator: 'exclusion' (negation), 'union', 'intersection'\n               (default: exclusion)\n        :param dict sub_expression: sub expression used\n        :param str comment: optional comment\n        :raises CreateElementFailed: element creation failed with reason\n        :return: instance with meta\n        :rtype: Expression"
  },
  {
    "code": "def get_name(self):\n        if self.OP > 0xff:\n            if self.OP >= 0xf2ff:\n                return DALVIK_OPCODES_OPTIMIZED[self.OP][1][0]\n            return DALVIK_OPCODES_EXTENDED_WIDTH[self.OP][1][0]\n        return DALVIK_OPCODES_FORMAT[self.OP][1][0]",
    "docstring": "Return the name of the instruction\n\n        :rtype: string"
  },
  {
    "code": "def _parse_uri_options(self, parsed_uri, use_ssl=False, ssl_options=None):\n        ssl_options = ssl_options or {}\n        kwargs = urlparse.parse_qs(parsed_uri.query)\n        vhost = urlparse.unquote(parsed_uri.path[1:]) or DEFAULT_VIRTUAL_HOST\n        options = {\n            'ssl': use_ssl,\n            'virtual_host': vhost,\n            'heartbeat': int(kwargs.pop('heartbeat',\n                                        [DEFAULT_HEARTBEAT_INTERVAL])[0]),\n            'timeout': int(kwargs.pop('timeout',\n                                      [DEFAULT_SOCKET_TIMEOUT])[0])\n        }\n        if use_ssl:\n            if not compatibility.SSL_SUPPORTED:\n                raise AMQPConnectionError(\n                    'Python not compiled with support '\n                    'for TLSv1 or higher'\n                )\n            ssl_options.update(self._parse_ssl_options(kwargs))\n            options['ssl_options'] = ssl_options\n        return options",
    "docstring": "Parse the uri options.\n\n        :param parsed_uri:\n        :param bool use_ssl:\n        :return:"
  },
  {
    "code": "def _EvaluateExpression(frame, expression):\n  try:\n    code = compile(expression, '<watched_expression>', 'eval')\n  except (TypeError, ValueError) as e:\n    return (False, {\n        'isError': True,\n        'refersTo': 'VARIABLE_NAME',\n        'description': {\n            'format': 'Invalid expression',\n            'parameters': [str(e)]}})\n  except SyntaxError as e:\n    return (False, {\n        'isError': True,\n        'refersTo': 'VARIABLE_NAME',\n        'description': {\n            'format': 'Expression could not be compiled: $0',\n            'parameters': [e.msg]}})\n  try:\n    return (True, native.CallImmutable(frame, code))\n  except BaseException as e:\n    return (False, {\n        'isError': True,\n        'refersTo': 'VARIABLE_VALUE',\n        'description': {\n            'format': 'Exception occurred: $0',\n            'parameters': [str(e)]}})",
    "docstring": "Compiles and evaluates watched expression.\n\n  Args:\n    frame: evaluation context.\n    expression: watched expression to compile and evaluate.\n\n  Returns:\n    (False, status) on error or (True, value) on success."
  },
  {
    "code": "def make_logging_api(client):\n    generated = LoggingServiceV2Client(\n        credentials=client._credentials, client_info=_CLIENT_INFO\n    )\n    return _LoggingAPI(generated, client)",
    "docstring": "Create an instance of the Logging API adapter.\n\n    :type client: :class:`~google.cloud.logging.client.Client`\n    :param client: The client that holds configuration details.\n\n    :rtype: :class:`_LoggingAPI`\n    :returns: A metrics API instance with the proper credentials."
  },
  {
    "code": "def equities(country='US'):\n    nasdaqblob, otherblob = _getrawdata()\n    eq_triples = []\n    eq_triples.extend(_get_nas_triples(nasdaqblob))\n    eq_triples.extend(_get_other_triples(otherblob))\n    eq_triples.sort()\n    index = [triple[0] for triple in eq_triples]\n    data = [triple[1:] for triple in eq_triples]\n    return pd.DataFrame(data, index, columns=['Security Name', 'Exchange'], dtype=str)",
    "docstring": "Return a DataFrame of current US equities.\n\n    .. versionadded:: 0.4.0\n\n    .. versionchanged:: 0.5.0\n       Return a DataFrame\n\n    Parameters\n    ----------\n    country : str, optional\n        Country code for equities to return, defaults to 'US'.\n\n    Returns\n    -------\n    eqs : :class:`pandas.DataFrame`\n        DataFrame whose index is a list of all current ticker symbols.\n        Columns are 'Security Name' (e.g. 'Zynerba Pharmaceuticals, Inc. - Common Stock')\n        and 'Exchange' ('NASDAQ', 'NYSE', 'NYSE MKT', etc.)\n\n    Examples\n    --------\n    >>> eqs = pn.data.equities('US')\n\n    Notes\n    -----\n    Currently only US markets are supported."
  },
  {
    "code": "def wait_for_stateful_block_init(context, mri, timeout=DEFAULT_TIMEOUT):\n    context.when_matches(\n        [mri, \"state\", \"value\"], StatefulStates.READY,\n        bad_values=[StatefulStates.FAULT, StatefulStates.DISABLED],\n        timeout=timeout)",
    "docstring": "Wait until a Block backed by a StatefulController has initialized\n\n    Args:\n        context (Context): The context to use to make the child block\n        mri (str): The mri of the child block\n        timeout (float): The maximum time to wait"
  },
  {
    "code": "def notify(self, force_notify=None, use_email=None, use_sms=None, **kwargs):\n        notified = False\n        instance = kwargs.get(\"instance\")\n        if instance._meta.label_lower == self.model:\n            notified = super().notify(\n                force_notify=force_notify,\n                use_email=use_email,\n                use_sms=use_sms,\n                **kwargs,\n            )\n        return notified",
    "docstring": "Overridden to only call `notify` if model matches."
  },
  {
    "code": "def safe_datetime_cast(self, col):\n        casted_dates = pd.to_datetime(col[self.col_name], format=self.date_format, errors='coerce')\n        if len(casted_dates[casted_dates.isnull()]):\n            slice_ = casted_dates.isnull() & ~col[self.col_name].isnull()\n            col[slice_][self.col_name].apply(self.strptime_format)\n        return casted_dates",
    "docstring": "Parses string values into datetime.\n\n        Args:\n            col(pandas.DataFrame): Data to transform.\n\n        Returns:\n            pandas.Series"
  },
  {
    "code": "def compliance_schedule(self, column=None, value=None, **kwargs):\n        return self._resolve_call('PCS_CMPL_SCHD', column, value, **kwargs)",
    "docstring": "A sequence of activities with associated milestones which pertains to a\n        given permit.\n\n        >>> PCS().compliance_schedule('cmpl_schd_evt', '62099')"
  },
  {
    "code": "def calcDeviationLimits(value, tolerance, mode):\n    values = toList(value)\n    if mode == 'relative':\n        lowerLimit = min(values) * (1 - tolerance)\n        upperLimit = max(values) * (1 + tolerance)\n    elif mode == 'absolute':\n        lowerLimit = min(values) - tolerance\n        upperLimit = max(values) + tolerance\n    else:\n        raise Exception('mode %s not specified' %(filepath, ))\n    return lowerLimit, upperLimit",
    "docstring": "Returns the upper and lower deviation limits for a value and a given\n    tolerance, either as relative or a absolute difference.\n\n    :param value: can be a single value or a list of values if a list of values\n        is given, the minimal value will be used to calculate the lower limit\n        and the maximum value to calculate the upper limit\n    :param tolerance: a number used to calculate the limits\n    :param mode: either ``absolute`` or ``relative``, specifies how the\n        ``tolerance`` should be applied to the ``value``."
  },
  {
    "code": "def _serialize(self):\n        result = { a: getattr(self, a) for a in type(self).properties\n            if type(self).properties[a].mutable }\n        for k, v in result.items():\n            if isinstance(v, Base):\n                result[k] = v.id\n        return result",
    "docstring": "A helper method to build a dict of all mutable Properties of\n        this object"
  },
  {
    "code": "def _get_gosrcs_upper(self, goids, max_upper, go2parentids):\n        gosrcs_upper = set()\n        get_nt = self.gosubdag.go2nt.get\n        go2nt = {g:get_nt(g) for g in goids}\n        go_nt = sorted(go2nt.items(), key=lambda t: -1*t[1].dcnt)\n        goids_upper = set()\n        for goid, _ in go_nt:\n            goids_upper.add(goid)\n            if goid in go2parentids:\n                goids_upper |= go2parentids[goid]\n            if len(goids_upper) < max_upper:\n                gosrcs_upper.add(goid)\n            else:\n                break\n        return gosrcs_upper",
    "docstring": "Get GO IDs for the upper portion of the GO DAG."
  },
  {
    "code": "def coro(f):\n    f = asyncio.coroutine(f)\n    def wrapper(*args, **kwargs):\n        loop = asyncio.get_event_loop()\n        try:\n            return loop.run_until_complete(f(*args, **kwargs))\n        except KeyboardInterrupt:\n            click.echo(\"Got CTRL+C, quitting..\")\n            dev = args[0]\n            loop.run_until_complete(dev.stop_listen_notifications())\n        except SongpalException as ex:\n            err(\"Error: %s\" % ex)\n            if len(args) > 0 and hasattr(args[0], \"debug\"):\n                if args[0].debug > 0:\n                    raise ex\n    return update_wrapper(wrapper, f)",
    "docstring": "Run a coroutine and handle possible errors for the click cli.\n\n    Source https://github.com/pallets/click/issues/85#issuecomment-43378930"
  },
  {
    "code": "def get_completion_context(args):\n    root_command = click.get_current_context().find_root().command\n    ctx = root_command.make_context(\"globus\", list(args), resilient_parsing=True)\n    while isinstance(ctx.command, click.MultiCommand) and args:\n        args = ctx.protected_args + ctx.args\n        if not args:\n            break\n        command = ctx.command.get_command(ctx, args[0])\n        if not command:\n            return None\n        else:\n            ctx = command.make_context(\n                args[0], args[1:], parent=ctx, resilient_parsing=True\n            )\n    return ctx",
    "docstring": "Walk the tree of commands to a terminal command or multicommand, using the\n    Click Context system.\n    Effectively, we'll be using the resilient_parsing mode of commands to stop\n    evaluation, then having them capture their options and arguments, passing\n    us on to the next subcommand. If we walk \"off the tree\" with a command that\n    we don't recognize, we have a hardstop condition, but otherwise, we walk as\n    far as we can go and that's the location from which we should do our\n    completion work."
  },
  {
    "code": "def _get_raw_data(self, name):\n        filestem = ''\n        for filestem, list_fvar in self._files.items():\n            if name in list_fvar:\n                break\n        fieldfile = self.step.sdat.filename(filestem, self.step.isnap,\n                                            force_legacy=True)\n        if not fieldfile.is_file():\n            fieldfile = self.step.sdat.filename(filestem, self.step.isnap)\n        parsed_data = None\n        if fieldfile.is_file():\n            parsed_data = stagyyparsers.fields(fieldfile)\n        elif self.step.sdat.hdf5 and self._filesh5:\n            for filestem, list_fvar in self._filesh5.items():\n                if name in list_fvar:\n                    break\n            parsed_data = stagyyparsers.read_field_h5(\n                self.step.sdat.hdf5 / 'Data.xmf', filestem, self.step.isnap)\n        return list_fvar, parsed_data",
    "docstring": "Find file holding data and return its content."
  },
  {
    "code": "def n_rows(self):\n        N_estimated = (self.hl * np.pi / (2 * self.stout_w_per_flow(self.hl) * self.q)).to(u.dimensionless)\n        variablerow = min(10, max(4, math.trunc(N_estimated.magnitude)))\n        return variablerow",
    "docstring": "This equation states that the open area corresponding to one row\n        can be set equal to two orifices of diameter=row height. If there\n        are more than two orifices per row at the top of the LFOM then there\n        are more orifices than are convenient to drill and more than\n        necessary for good accuracy. Thus this relationship can be used to\n        increase the spacing between the rows and thus increase the diameter\n        of the orifices. This spacing function also sets the lower depth on\n        the high flow rate LFOM with no accurate flows below a depth equal\n        to the first row height.\n        But it might be better to always set then number of rows to 10.\n        The challenge is to figure out a reasonable system of constraints that\n        reliably returns a valid solution."
  },
  {
    "code": "def _replace_and_publish(self, path, prettyname, value, device):\n        if value is None:\n            return\n        newpath = path\n        newpath = \".\".join([\".\".join(path.split(\".\")[:-1]), prettyname])\n        metric = Metric(newpath, value, precision=4, host=device)\n        self.publish_metric(metric)",
    "docstring": "Inputs a complete path for a metric and a value.\n        Replace the metric name and publish."
  },
  {
    "code": "def example_number_for_non_geo_entity(country_calling_code):\n    metadata = PhoneMetadata.metadata_for_nongeo_region(country_calling_code, None)\n    if metadata is not None:\n        for desc in (metadata.mobile, metadata.toll_free, metadata.shared_cost, metadata.voip,\n                     metadata.voicemail, metadata.uan, metadata.premium_rate):\n            try:\n                if (desc is not None and desc.example_number is not None):\n                    return parse(_PLUS_SIGN + unicod(country_calling_code) + desc.example_number, UNKNOWN_REGION)\n            except NumberParseException:\n                pass\n    return None",
    "docstring": "Gets a valid number for the specified country calling code for a non-geographical entity.\n\n    Arguments:\n    country_calling_code -- The country calling code for a non-geographical entity.\n\n    Returns a valid number for the non-geographical entity. Returns None when\n    the metadata does not contain such information, or the country calling\n    code passed in does not belong to a non-geographical entity."
  },
  {
    "code": "def get_available_versions(self, project_name):\n        available_versions = self.pypi_client.package_releases(project_name)\n        if not available_versions:\n            available_versions = self.pypi_client.package_releases(\n                project_name.capitalize()\n            )\n        return dict(\n            (self._parse_version(version), version)\n            for version in available_versions\n        )",
    "docstring": "Query PyPI to see if package has any available versions.\n\n        Args:\n            project_name (str): The name the project on PyPI.\n\n        Returns:\n            dict: Where keys are tuples of parsed versions and values are the\n                versions returned by PyPI."
  },
  {
    "code": "def apply_filter(self):\n    self._ensure_modification_is_safe()\n    if len(self.query.filters) > 0:\n      self._iterable = Filter.filter(self.query.filters, self._iterable)",
    "docstring": "Naively apply query filters."
  },
  {
    "code": "def has_submenu_items(self, current_page, allow_repeating_parents,\n                          original_menu_tag, menu_instance=None, request=None):\n        return menu_instance.page_has_children(self)",
    "docstring": "When rendering pages in a menu template a `has_children_in_menu`\n        attribute is added to each page, letting template developers know\n        whether or not the item has a submenu that must be rendered.\n\n        By default, we return a boolean indicating whether the page has\n        suitable child pages to include in such a menu. But, if you are\n        overriding the `modify_submenu_items` method to programatically add\n        items that aren't child pages, you'll likely need to alter this method\n        too, so the template knows there are sub items to be rendered."
  },
  {
    "code": "def make_while_loop(test_and_body_instrs, else_body_instrs, context):\n    top_of_loop = test_and_body_instrs[0]\n    test, body_instrs = make_while_loop_test_expr(test_and_body_instrs)\n    body, orelse_body = make_loop_body_and_orelse(\n        top_of_loop, body_instrs, else_body_instrs, context,\n    )\n    return ast.While(test=test, body=body, orelse=orelse_body)",
    "docstring": "Make an ast.While node.\n\n    Parameters\n    ----------\n    test_and_body_instrs : deque\n        Queue of instructions forming the loop test expression and body.\n    else_body_instrs : deque\n        Queue of instructions forming the else block of the loop.\n    context : DecompilationContext"
  },
  {
    "code": "def addend_ids(self):\n        return tuple(\n            arg\n            for arg in self._subtotal_dict.get(\"args\", [])\n            if arg in self.valid_elements.element_ids\n        )",
    "docstring": "tuple of int ids of elements contributing to this subtotal.\n\n        Any element id not present in the dimension or present but\n        representing missing data is excluded."
  },
  {
    "code": "def parse_readme(cls, readme_path: str = 'README.rst', encoding: str = 'utf-8') -> str:\n        with HERE.joinpath(readme_path).open(encoding=encoding) as readme_file:\n            long_description = readme_file.read()\n        if readme_path.endswith('.rst') and cls.download_url.startswith('https://github.com/'):\n            base_url = '{}/blob/v{}/'.format(cls.download_url, cls.version)\n            long_description = resolve_relative_rst_links(long_description, base_url)\n        return long_description",
    "docstring": "Parse readme and resolve relative links in it if it is feasible.\n\n        Links are resolved if readme is in rst format and the package is hosted on GitHub."
  },
  {
    "code": "def pexpect(self):\n        import pexpect\n        assert not self._ignore_errors\n        _check_directory(self.directory)\n        arguments = self.arguments\n        return pexpect.spawn(\n            arguments[0], args=arguments[1:], env=self.env, cwd=self.directory\n        )",
    "docstring": "Run command and return pexpect process object.\n\n        NOTE: Requires you to pip install 'pexpect' or will fail."
  },
  {
    "code": "def list_renderers(*args):\n    renderers_ = salt.loader.render(__opts__, [])\n    renderers = set()\n    if not args:\n        for rend in six.iterkeys(renderers_):\n            renderers.add(rend)\n        return sorted(renderers)\n    for module in args:\n        for rend in fnmatch.filter(renderers_, module):\n            renderers.add(rend)\n    return sorted(renderers)",
    "docstring": "List the renderers loaded on the minion\n\n    .. versionadded:: 2015.5.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' sys.list_renderers\n\n    Render names can be specified as globs.\n\n    .. code-block:: bash\n\n        salt '*' sys.list_renderers 'yaml*'"
  },
  {
    "code": "def run_command(self, command, message):\n        proc = subprocess.Popen([\n            'echo \\'%s\\' | %s' % (fedmsg.encoding.dumps(message), command)\n        ], shell=True, executable='/bin/bash')\n        return proc.wait()",
    "docstring": "Use subprocess; feed the message to our command over stdin"
  },
  {
    "code": "def main():\n    save_settings = None\n    stdin_fd = -1\n    try:\n        import termios\n        stdin_fd = sys.stdin.fileno()\n        save_settings = termios.tcgetattr(stdin_fd)\n    except:\n        pass\n    try:\n        real_main()\n    finally:\n        if save_settings:\n            termios.tcsetattr(stdin_fd, termios.TCSANOW, save_settings)",
    "docstring": "This main function saves the stdin termios settings, calls real_main,\n       and restores stdin termios settings when it returns."
  },
  {
    "code": "def load_user_options(self):\n        if self._profile_list is None:\n            if callable(self.profile_list):\n                self._profile_list = yield gen.maybe_future(self.profile_list(self))\n            else:\n                self._profile_list = self.profile_list\n        if self._profile_list:\n            yield self._load_profile(self.user_options.get('profile', None))",
    "docstring": "Load user options from self.user_options dict\n\n        This can be set via POST to the API or via options_from_form\n\n        Only supported argument by default is 'profile'.\n        Override in subclasses to support other options."
  },
  {
    "code": "def fetch(self):\n        params = values.of({})\n        payload = self._version.fetch(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return ExecutionInstance(\n            self._version,\n            payload,\n            flow_sid=self._solution['flow_sid'],\n            sid=self._solution['sid'],\n        )",
    "docstring": "Fetch a ExecutionInstance\n\n        :returns: Fetched ExecutionInstance\n        :rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance"
  },
  {
    "code": "def debug(self, msg, *args, **kwargs):\n        kwargs.setdefault('inc_stackinfo', True)\n        self.log(DEBUG, msg, args, **kwargs)",
    "docstring": "Log a message with DEBUG level. Automatically includes stack info\n        unless it is specifically not included."
  },
  {
    "code": "def chunks(iterable, size=50):\n    batch = []\n    for n in iterable:\n        batch.append(n)\n        if len(batch) % size == 0:\n            yield batch\n            batch = []\n    if batch:\n        yield batch",
    "docstring": "Break an iterable into lists of size"
  },
  {
    "code": "def visit_DictComp(self, node: AST, dfltChaining: bool = True) -> str:\n        return f\"{{{self.visit(node.key)}: {self.visit(node.value)} \" \\\n               f\"{' '.join(self.visit(gen) for gen in node.generators)}}}\"",
    "docstring": "Return `node`s representation as dict comprehension."
  },
  {
    "code": "def i2c_pullups(self):\n        ret = api.py_aa_i2c_pullup(self.handle, I2C_PULLUP_QUERY)\n        _raise_error_if_negative(ret)\n        return ret",
    "docstring": "Setting this to `True` will enable the I2C pullup resistors. If set\n        to `False` the pullup resistors will be disabled.\n\n        Raises an :exc:`IOError` if the hardware adapter does not support\n        pullup resistors."
  },
  {
    "code": "def command_check(string, vargs):\n    is_valid = is_valid_ipa(string)\n    print(is_valid)\n    if not is_valid:\n        valid_chars, invalid_chars = remove_invalid_ipa_characters(\n            unicode_string=string,\n            return_invalid=True\n        )\n        print_invalid_chars(invalid_chars, vargs)",
    "docstring": "Check if the given string is IPA valid.\n\n    If the given string is not IPA valid,\n    print the invalid characters.\n\n    :param str string: the string to act upon\n    :param dict vargs: the command line arguments"
  },
  {
    "code": "def _update_pvalcorr(ntmt, corrected_pvals):\n        if corrected_pvals is None:\n            return\n        for rec, val in zip(ntmt.results, corrected_pvals):\n            rec.set_corrected_pval(ntmt.nt_method, val)",
    "docstring": "Add data members to store multiple test corrections."
  },
  {
    "code": "def delete_queue(queues):\n    current_queues.delete(queues=queues)\n    click.secho(\n        'Queues {} have been deleted.'.format(\n            queues or current_queues.queues.keys()),\n        fg='green'\n    )",
    "docstring": "Delete the given queues."
  },
  {
    "code": "def create_java_executor(self, dist=None):\n    dist = dist or self.dist\n    if self.execution_strategy == self.NAILGUN:\n      classpath = os.pathsep.join(self.tool_classpath('nailgun-server'))\n      return NailgunExecutor(self._identity,\n                             self._executor_workdir,\n                             classpath,\n                             dist,\n                             startup_timeout=self.get_options().nailgun_subprocess_startup_timeout,\n                             connect_timeout=self.get_options().nailgun_timeout_seconds,\n                             connect_attempts=self.get_options().nailgun_connect_attempts)\n    else:\n      return SubprocessExecutor(dist)",
    "docstring": "Create java executor that uses this task's ng daemon, if allowed.\n\n    Call only in execute() or later. TODO: Enforce this."
  },
  {
    "code": "def get_grp2codes(self):\n        grp2codes = cx.defaultdict(set)\n        for code, ntd in self.code2nt.items():\n            grp2codes[ntd.group].add(code)\n        return dict(grp2codes)",
    "docstring": "Get dict of group name to namedtuples."
  },
  {
    "code": "def only(self, *keys):\n        items = []\n        for key, value in enumerate(self.items):\n            if key in keys:\n                items.append(value)\n        return self.__class__(items)",
    "docstring": "Get the items with the specified keys.\n\n        :param keys: The keys to keep\n        :type keys: tuple\n\n        :rtype: Collection"
  },
  {
    "code": "def lstm_cell(x, h, c, state_size, w_init=None, b_init=None, fix_parameters=False):\n    xh = F.concatenate(*(x, h), axis=1)\n    iofc = affine(xh, (4, state_size), w_init=w_init,\n                  b_init=b_init, fix_parameters=fix_parameters)\n    i_t, o_t, f_t, gate = F.split(iofc, axis=1)\n    c_t = F.sigmoid(f_t) * c + F.sigmoid(i_t) * F.tanh(gate)\n    h_t = F.sigmoid(o_t) * F.tanh(c_t)\n    return h_t, c_t",
    "docstring": "Long Short-Term Memory.\n\n    Long Short-Term Memory, or LSTM, is a building block for recurrent neural networks (RNN) layers.\n    LSTM unit consists of a cell and input, output, forget gates whose functions are defined as following:\n\n    .. math::\n        f_t&&=\\\\sigma(W_fx_t+U_fh_{t-1}+b_f) \\\\\\\\\n        i_t&&=\\\\sigma(W_ix_t+U_ih_{t-1}+b_i) \\\\\\\\\n        o_t&&=\\\\sigma(W_ox_t+U_oh_{t-1}+b_o) \\\\\\\\\n        c_t&&=f_t\\\\odot c_{t-1}+i_t\\\\odot\\\\tanh(W_cx_t+U_ch_{t-1}+b_c) \\\\\\\\\n        h_t&&=o_t\\\\odot\\\\tanh(c_t).\n\n    References:\n\n        S. Hochreiter, and J. Schmidhuber. \"Long Short-Term Memory.\"\n        Neural Computation. 1997.\n\n    Args:\n        x (~nnabla.Variable): Input N-D array with shape (batch_size, input_size).\n        h (~nnabla.Variable): Input N-D array with shape (batch_size, state_size).\n        c (~nnabla.Variable): Input N-D array with shape (batch_size, state_size).\n        state_size (int): Internal state size is set to `state_size`.\n        w_init (:obj:`nnabla.initializer.BaseInitializer` or :obj:`numpy.ndarray`, optional): Initializer for weight. By default, it is initialized with :obj:`nnabla.initializer.UniformInitializer` within the range determined by :obj:`nnabla.initializer.calc_uniform_lim_glorot`.  \n        b_init (:obj:`nnabla.initializer.BaseInitializer` or :obj:`numpy.ndarray`, optional): Initializer for bias. By default, it is initialized with zeros if `with_bias` is `True`.\n        fix_parameters (bool): When set to `True`, the weights and biases will not be updated.\n\n    Returns:\n        :class:`~nnabla.Variable`"
  },
  {
    "code": "def within_rupture_distance(self, surface, distance,  **kwargs):\n        upper_depth, lower_depth = _check_depth_limits(kwargs)\n        rrupt = surface.get_min_distance(self.catalogue.hypocentres_as_mesh())\n        is_valid = np.logical_and(\n            rrupt <= distance,\n            np.logical_and(self.catalogue.data['depth'] >= upper_depth,\n                           self.catalogue.data['depth'] < lower_depth))\n        return self.select_catalogue(is_valid)",
    "docstring": "Select events within a rupture distance from a fault surface\n\n        :param surface:\n            Fault surface as instance of nhlib.geo.surface.base.BaseSurface\n\n        :param float distance:\n            Rupture distance (km)\n\n        :returns:\n            Instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue`\n            containing only selected events"
  },
  {
    "code": "def _includes_base_class(self, iter_classes, base_class):\n        return any(\n            issubclass(auth_class, base_class) for auth_class in iter_classes,\n        )",
    "docstring": "Returns whether any class in iter_class is a subclass of the given base_class."
  },
  {
    "code": "def _checkIfClusterExists(self):\n        ansibleArgs = {\n            'resgrp': self.clusterName,\n            'region': self._zone\n        }\n        try:\n            self.callPlaybook(self.playbook['check-cluster'], ansibleArgs, wait=True)\n        except RuntimeError:\n            logger.info(\"The cluster could not be created. Try deleting the cluster if it already exits.\")\n            raise",
    "docstring": "Try deleting the resource group. This will fail if it exists and raise an exception."
  },
  {
    "code": "def multi_series_single_value(self, keys=None, ts=None, direction=None,\n                                  attrs={}, tags=[]):\n        url = 'single/'\n        if ts is not None:\n            vts = check_time_param(ts)\n        else:\n            vts = None\n        params = {\n            'key': keys,\n            'tag': tags,\n            'attr': attrs,\n            'ts': vts,\n            'direction': direction\n        }\n        url_args = endpoint.make_url_args(params)\n        url = '?'.join([url, url_args])\n        resp = self.session.get(url)\n        return resp",
    "docstring": "Return a single value for multiple series.  You can supply a\n        timestamp as the ts argument, otherwise the search defaults to the\n        current time.\n\n        The direction argument can be one of \"exact\", \"before\", \"after\", or\n        \"nearest\".\n\n        The id, key, tag, and attr arguments allow you to filter for series.\n        See the :meth:`list_series` method for an explanation of their use.\n\n        :param string keys: (optional) a list of keys for the series to use\n        :param ts: (optional) the time to begin searching from\n        :type ts: ISO8601 string or Datetime object\n        :param string direction: criterion for the search\n        :param tags: filter by one or more tags\n        :type tags: list or string\n        :param dict attrs: filter by one or more key-value attributes\n        :rtype: :class:`tempodb.protocol.cursor.SingleValueCursor` with an\n                iterator over :class:`tempodb.protocol.objects.SingleValue`\n                objects"
  },
  {
    "code": "def reference_preprocessing(job, samples, config):\n    job.fileStore.logToMaster('Processed reference files')\n    config.fai = job.addChildJobFn(run_samtools_faidx, config.reference).rv()\n    config.dict = job.addChildJobFn(run_picard_create_sequence_dictionary, config.reference).rv()\n    job.addFollowOnJobFn(map_job, download_sample, samples, config)",
    "docstring": "Spawn the jobs that create index and dict file for reference\n\n    :param JobFunctionWrappingJob job: passed automatically by Toil\n    :param Namespace config: Argparse Namespace object containing argument inputs\n    :param list[list] samples: A nested list of samples containing sample information"
  },
  {
    "code": "async def modify(cls, db, key, data: dict):\n        if data is None:\n            raise BadRequest('Failed to modify document. No data fields to modify')\n        cls._validate(data)\n        query = {cls.primary_key: key}\n        for i in cls.connection_retries():\n            try:\n                result = await db[cls.get_collection_name()].find_one_and_update(\n                    filter=query,\n                    update={'$set': data},\n                    return_document=ReturnDocument.AFTER\n                )\n                if result:\n                    updated_obj = cls.create_model(result)\n                    updated_obj._db = db\n                    asyncio.ensure_future(post_save.send(\n                        sender=cls,\n                        db=db,\n                        instance=updated_obj,\n                        created=False)\n                    )\n                    return updated_obj\n                return None\n            except ConnectionFailure as ex:\n                exceed = await cls.check_reconnect_tries_and_wait(i, 'update')\n                if exceed:\n                    raise ex",
    "docstring": "Partially modify a document by providing a subset of its data fields to be modified\n\n        :param db:\n            Handle to the MongoDB database\n\n        :param key:\n            The primary key of the database object being modified. Usually its ``_id``\n\n        :param data:\n            The data set to be modified\n\n        :type data:\n            ``dict``"
  },
  {
    "code": "async def on_raw_314(self, message):\n        target, nickname, username, hostname, _, realname = message.params\n        info = {\n            'username': username,\n            'hostname': hostname,\n            'realname': realname\n        }\n        if nickname in self._pending['whowas']:\n            self._whowas_info[nickname].update(info)",
    "docstring": "WHOWAS user info."
  },
  {
    "code": "def listed(self):\n        print(\"\\nPackages in the queue:\\n\")\n        for pkg in self.packages():\n            if pkg:\n                print(\"{0}{1}{2}\".format(self.meta.color[\"GREEN\"], pkg,\n                                         self.meta.color[\"ENDC\"]))\n                self.quit = True\n        if self.quit:\n            print(\"\")",
    "docstring": "Print packages from queue"
  },
  {
    "code": "def _store(self, messages, response, *args, **kwargs):\n        return [message for message in messages if not message.level in STICKY_MESSAGE_LEVELS]",
    "docstring": "Delete all messages that are sticky and return the other messages\n        This storage never save objects"
  },
  {
    "code": "def cpjoin(*args):\n    rooted = True if args[0].startswith('/') else False\n    def deslash(a): return a[1:] if a.startswith('/') else a\n    newargs = [deslash(arg) for arg in args]\n    path = os.path.join(*newargs)\n    if rooted: path = os.path.sep + path\n    return path",
    "docstring": "custom path join"
  },
  {
    "code": "def pop(self, index):\n        r\n        obj = self[index]\n        self.purge_object(obj, deep=False)\n        return obj",
    "docstring": "r\"\"\"\n        The object at the given index is removed from the list and returned.\n\n        Notes\n        -----\n        This method uses ``purge_object`` to perform the actual removal of the\n        object. It is reommended to just use that directly instead.\n\n        See Also\n        --------\n        purge_object"
  },
  {
    "code": "def set_log_level(verbose, quiet):\n    if quiet:\n        verbose = -1\n    if verbose < 0:\n        verbose = logging.CRITICAL\n    elif verbose == 0:\n        verbose = logging.WARNING\n    elif verbose == 1:\n        verbose = logging.INFO\n    elif 1 < verbose:\n        verbose = logging.DEBUG\n    LOGGER.setLevel(verbose)",
    "docstring": "Ses the logging level of the script based on command line options.\n\n    Arguments:\n    - `verbose`:\n    - `quiet`:"
  },
  {
    "code": "def set_duration(self, duration):\n        if duration == 0:\n            self.widget.setDuration(-2)\n        else:\n            self.widget.setDuration(0)",
    "docstring": "Android for whatever stupid reason doesn't let you set the time\n        it only allows 1-long or 0-short. So we have to repeatedly call show\n        until the duration expires, hence this method does nothing see \n        `set_show`."
  },
  {
    "code": "def _check_std(self, paths, cmd_pieces):\n        cmd_pieces.extend(paths)\n        process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE)\n        out, err = process.communicate()\n        lines = out.strip().splitlines() + err.strip().splitlines()\n        result = []\n        for line in lines:\n            match = self.tool_err_re.match(line)\n            if not match:\n                if self.break_on_tool_re_mismatch:\n                    raise ValueError(\n                        'Unexpected `%s` output: %r' % (\n                            ' '.join(cmd_pieces),\n                            paths,\n                            line))\n                continue\n            vals = match.groupdict()\n            vals['lineno'] = int(vals['lineno'])\n            vals['colno'] = \\\n                int(vals['colno']) if vals['colno'] is not None else ''\n            result.append(vals)\n        return result",
    "docstring": "Run `cmd` as a check on `paths`."
  },
  {
    "code": "def diff_config(base, target):\n    if not isinstance(base, collections.Mapping):\n        if base == target:\n            return {}\n        return target\n    if not isinstance(target, collections.Mapping):\n        return target\n    result = dict()\n    for k in iterkeys(base):\n        if k not in target:\n            result[k] = None\n    for k, v in iteritems(target):\n        if k in base:\n            merged = diff_config(base[k], v)\n            if merged != {}:\n                result[k] = merged\n        else:\n            result[k] = v\n    return result",
    "docstring": "Find the differences between two configurations.\n\n    This finds a delta configuration from `base` to `target`, such that\n    calling :func:`overlay_config` with `base` and the result of this\n    function yields `target`.  This works as follows:\n\n    * If both are identical (of any type), returns an empty dictionary.\n    * If either isn't a dictionary, returns `target`.\n    * Any key in `target` not present in `base` is included in the output\n      with its value from `target`.\n    * Any key in `base` not present in `target` is included in the output\n      with value :const:`None`.\n    * Any keys present in both dictionaries are recursively merged.\n\n    >>> diff_config({'a': 'b'}, {})\n    {'a': None}\n    >>> diff_config({'a': 'b'}, {'a': 'b', 'c': 'd'})\n    {'c': 'd'}\n\n    :param dict base: original configuration\n    :param dict target: new configuration\n    :return: overlay configuration\n    :returntype dict:"
  },
  {
    "code": "def convex_hull(features):\n    points = sorted([s.point() for s in features])\n    l = reduce(_keep_left, points, [])\n    u = reduce(_keep_left, reversed(points), [])\n    return l.extend(u[i] for i in xrange(1, len(u) - 1)) or l",
    "docstring": "Returns points on convex hull of an array of points in CCW order."
  },
  {
    "code": "def get_temp_directory():\n    directory = os.path.join(gettempdir(), \"ttkthemes\")\n    if not os.path.exists(directory):\n        os.makedirs(directory)\n    return directory",
    "docstring": "Return an absolute path to an existing temporary directory"
  },
  {
    "code": "def keys(self, key_type=None):\r\n        if key_type is not None:\r\n            intermediate_key = str(key_type)\r\n            if intermediate_key in self.__dict__:\r\n                return self.__dict__[intermediate_key].keys()\r\n        else:\r\n            all_keys = {}\n            for keys in self.items_dict.keys():\r\n                all_keys[keys] = None\r\n            return all_keys.keys()",
    "docstring": "Returns a copy of the dictionary's keys.\r\n            @param key_type if specified, only keys for this type will be returned.\r\n                 Otherwise list of tuples containing all (multiple) keys will be returned."
  },
  {
    "code": "def add_virtual_loss(self, up_to):\n        self.losses_applied += 1\n        loss = self.position.to_play\n        self.W += loss\n        if self.parent is None or self is up_to:\n            return\n        self.parent.add_virtual_loss(up_to)",
    "docstring": "Propagate a virtual loss up to the root node.\n\n        Args:\n            up_to: The node to propagate until. (Keep track of this! You'll\n                need it to reverse the virtual loss later.)"
  },
  {
    "code": "def hr_avg(self):\n        hr_data = self.hr_values()\n        return int(sum(hr_data) / len(hr_data))",
    "docstring": "Average heart rate of the workout"
  },
  {
    "code": "def add_constant(self, name, value, path=0):\n        assert isinstance(name, basestring)\n        assert is_iterable_typed(value, basestring)\n        assert isinstance(path, int)\n        if path:\n            l = self.location_\n            if not l:\n                l = self.get('source-location')\n            value = os.path.join(l, value[0])\n            value = [os.path.normpath(os.path.join(os.getcwd(), value))]\n        self.constants_[name] = value\n        bjam.call(\"set-variable\", self.project_module(), name, value)",
    "docstring": "Adds a new constant for this project.\n\n        The constant will be available for use in Jamfile\n        module for this project. If 'path' is true,\n        the constant will be interpreted relatively\n        to the location of project."
  },
  {
    "code": "def loadJSON(self, jdata):\n        super(StringColumn, self).loadJSON(jdata)\n        self.__maxLength = jdata.get('maxLength') or self.__maxLength",
    "docstring": "Loads JSON data for this column type.\n\n        :param jdata: <dict>"
  },
  {
    "code": "def classifer_metrics(label, pred):\n    prediction = np.argmax(pred, axis=1)\n    label = label.astype(int)\n    pred_is_entity = prediction != not_entity_index\n    label_is_entity = label != not_entity_index\n    corr_pred = (prediction == label) == (pred_is_entity == True)\n    num_entities = np.sum(label_is_entity)\n    entity_preds = np.sum(pred_is_entity)\n    correct_entitites = np.sum(corr_pred[pred_is_entity])\n    precision = correct_entitites/entity_preds\n    if entity_preds == 0:\n        precision = np.nan\n    recall = correct_entitites / num_entities\n    if num_entities == 0:\n        recall = np.nan\n    f1 = 2 * precision * recall / (precision + recall)\n    return precision, recall, f1",
    "docstring": "computes f1, precision and recall on the entity class"
  },
  {
    "code": "def example_lchab_to_lchuv():\n    print(\"=== Complex Example: LCHab->LCHuv ===\")\n    lchab = LCHabColor(0.903, 16.447, 352.252)\n    print(lchab)\n    lchuv = convert_color(lchab, LCHuvColor)\n    print(lchuv)\n    print(\"=== End Example ===\\n\")",
    "docstring": "This function shows very complex chain of conversions in action.\n\n    LCHab to LCHuv involves four different calculations, making this the\n    conversion requiring the most steps."
  },
  {
    "code": "def permute(self, qubits: Qubits) -> 'Channel':\n        vec = self.vec.permute(qubits)\n        return Channel(vec.tensor, qubits=vec.qubits)",
    "docstring": "Return a copy of this channel with qubits in new order"
  },
  {
    "code": "def GetMemTargetSizeMB(self):\n        counter = c_uint()\n        ret = vmGuestLib.VMGuestLib_GetMemTargetSizeMB(self.handle.value, byref(counter))\n        if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)\n        return counter.value",
    "docstring": "Retrieves the size of the target memory allocation for this virtual machine."
  },
  {
    "code": "def get_by_ip(cls, ip):\n        'Returns Host instance for the given ip address.'\n        ret = cls.hosts_by_ip.get(ip)\n        if ret is None:\n            ret = cls.hosts_by_ip[ip] = [Host(ip)]\n        return ret",
    "docstring": "Returns Host instance for the given ip address."
  },
  {
    "code": "def fetch_existing_token_of_user(self, client_id, grant_type, user_id):\n        token_data = self.fetchone(self.fetch_existing_token_of_user_query,\n                                   client_id, grant_type, user_id)\n        if token_data is None:\n            raise AccessTokenNotFound\n        scopes = self._fetch_scopes(access_token_id=token_data[0])\n        data = self._fetch_data(access_token_id=token_data[0])\n        return self._row_to_token(data=data, scopes=scopes, row=token_data)",
    "docstring": "Retrieve an access token issued to a client and user for a specific\n        grant.\n\n        :param client_id: The identifier of a client as a `str`.\n        :param grant_type: The type of grant.\n        :param user_id: The identifier of the user the access token has been\n                        issued to.\n\n        :return: An instance of :class:`oauth2.datatype.AccessToken`.\n\n        :raises: :class:`oauth2.error.AccessTokenNotFound` if not access token\n                 could be retrieved."
  },
  {
    "code": "def optimizer(self) -> Union[mx.optimizer.Optimizer, SockeyeOptimizer]:\n        return self.current_module._optimizer",
    "docstring": "Returns the optimizer of the underlying module."
  },
  {
    "code": "def block2(self, value):\n        option = Option()\n        option.number = defines.OptionRegistry.BLOCK2.number\n        num, m, size = value\n        if size > 512:\n            szx = 6\n        elif 256 < size <= 512:\n            szx = 5\n        elif 128 < size <= 256:\n            szx = 4\n        elif 64 < size <= 128:\n            szx = 3\n        elif 32 < size <= 64:\n            szx = 2\n        elif 16 < size <= 32:\n            szx = 1\n        else:\n            szx = 0\n        value = (num << 4)\n        value |= (m << 3)\n        value |= szx\n        option.value = value\n        self.add_option(option)",
    "docstring": "Set the Block2 option.\n\n        :param value: the Block2 value"
  },
  {
    "code": "def set_blocked(self, name):\n        self.unregister(name=name)\n        self._name2plugin[name] = None",
    "docstring": "block registrations of the given name, unregister if already registered."
  },
  {
    "code": "def predict(self, features, verbose=False):\n        probs = self.clf.predict_proba(features)\n        if verbose:\n            labels = self.labels.classes_\n            res = []\n            for prob in probs:\n                vals = {}\n                for i, val in enumerate(prob):\n                    label = labels[i]\n                    vals[label] = val\n                res.append(vals)\n            return res\n        else:\n            return probs",
    "docstring": "Probability estimates of each feature\n\n        See sklearn's SGDClassifier predict and predict_proba methods.\n\n        Args:\n            features (:obj:`list` of :obj:`list` of :obj:`float`)\n            verbose: Boolean, optional. If true returns an array where each\n                element is a dictionary, where keys are labels and values are\n                the respective probabilities. Defaults to False.\n        Returns:\n            Array of array of numbers, or array of dictionaries if verbose i\n            True"
  },
  {
    "code": "def describe(cls) -> None:\n        max_lengths = []\n        for attr_name in cls.attr_names():\n            attr_func = \"%ss\" % attr_name\n            attr_list = list(map(str, getattr(cls, attr_func)())) + [attr_name]\n            max_lengths.append(max(list(map(len, attr_list))))\n        row_format = \"{:>%d} | {:>%d} | {:>%d}\" % tuple(max_lengths)\n        headers = [attr_name.capitalize() for attr_name in cls.attr_names()]\n        header_line = row_format.format(*headers)\n        output = \"Class: %s\\n\" % cls.__name__\n        output += header_line + \"\\n\"\n        output += \"-\"*(len(header_line)) + \"\\n\"\n        for item in cls:\n            format_list = [str(getattr(item, attr_name))\n                           for attr_name in cls.attr_names()]\n            output += row_format.format(*format_list) + \"\\n\"\n        print(output)",
    "docstring": "Prints in the console a table showing all the attributes for all the\n        definitions inside the class\n\n        :return: None"
  },
  {
    "code": "def fulfill(self, value):\n        assert self._state==self.PENDING\n        self._state=self.FULFILLED;\n        self.value = value\n        for callback in self._callbacks:\n            try:\n                callback(value)\n            except Exception:\n                pass\n        self._callbacks = []",
    "docstring": "Fulfill the promise with a given value."
  },
  {
    "code": "def from_list(a, order='F'):\n        d = len(a)\n        res = vector()\n        n = _np.zeros(d, dtype=_np.int32)\n        r = _np.zeros(d+1, dtype=_np.int32)\n        cr = _np.array([])\n        for i in xrange(d):\n            cr = _np.concatenate((cr, a[i].flatten(order)))\n            r[i] = a[i].shape[0]\n            r[i+1] = a[i].shape[2]\n            n[i] = a[i].shape[1]\n        res.d = d\n        res.n = n\n        res.r = r\n        res.core = cr\n        res.get_ps()\n        return res",
    "docstring": "Generate TT-vectorr object from given TT cores.\n\n        :param a: List of TT cores.\n        :type a: list\n        :returns: vector -- TT-vector constructed from the given cores."
  },
  {
    "code": "def handle_molecular_activity_default(_: str, __: int, tokens: ParseResults) -> ParseResults:\n    upgraded = language.activity_labels[tokens[0]]\n    tokens[NAMESPACE] = BEL_DEFAULT_NAMESPACE\n    tokens[NAME] = upgraded\n    return tokens",
    "docstring": "Handle a BEL 2.0 style molecular activity with BEL default names."
  },
  {
    "code": "def setPlainText(self, txt, mime_type, encoding):\n        self.file.mimetype = mime_type\n        self.file._encoding = encoding\n        self._original_text = txt\n        self._modified_lines.clear()\n        import time\n        t = time.time()\n        super(CodeEdit, self).setPlainText(txt)\n        _logger().log(5, 'setPlainText duration: %fs' % (time.time() - t))\n        self.new_text_set.emit()\n        self.redoAvailable.emit(False)\n        self.undoAvailable.emit(False)",
    "docstring": "Extends setPlainText to force the user to setup an encoding and a\n        mime type.\n\n        Emits the new_text_set signal.\n\n        :param txt: The new text to set.\n        :param mime_type: Associated mimetype. Setting the mime will update the\n                          pygments lexer.\n        :param encoding: text encoding"
  },
  {
    "code": "def do_checkout(self, subcmd, opts, *args):\n        print \"'svn %s' opts: %s\" % (subcmd, opts)\n        print \"'svn %s' args: %s\" % (subcmd, args)",
    "docstring": "Check out a working copy from a repository.\n\n        usage:\n            checkout URL... [PATH]\n        \n        Note: If PATH is omitted, the basename of the URL will be used as\n        the destination. If multiple URLs are given each will be checked\n        out into a sub-directory of PATH, with the name of the sub-directory\n        being the basename of the URL.\n\n        ${cmd_option_list}"
  },
  {
    "code": "def mount(self, path, mount):\n        self._mountpoints[self._join_chunks(self._normalize_path(path))] = mount",
    "docstring": "Add a mountpoint to the filesystem."
  },
  {
    "code": "def record(self):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('Boot Record not yet initialized')\n        return struct.pack(self.FMT, VOLUME_DESCRIPTOR_TYPE_BOOT_RECORD,\n                           b'CD001', 1, self.boot_system_identifier,\n                           self.boot_identifier, self.boot_system_use)",
    "docstring": "A method to generate a string representing this Boot Record.\n\n        Parameters:\n         None.\n        Returns:\n         A string representing this Boot Record."
  },
  {
    "code": "def transform_flask_from_import(node):\n    new_names = []\n    for (name, as_name) in node.names:\n        actual_module_name = 'flask_{}'.format(name)\n        new_names.append((actual_module_name, as_name or name))\n    new_node = nodes.Import()\n    copy_node_info(node, new_node)\n    new_node.names = new_names\n    mark_transformed(new_node)\n    return new_node",
    "docstring": "Translates a flask.ext from-style import into a non-magical import.\n\n    Translates:\n        from flask.ext import wtf, bcrypt as fcrypt\n    Into:\n        import flask_wtf as wtf, flask_bcrypt as fcrypt"
  },
  {
    "code": "def asdensity(self) -> 'Density':\n        matrix = bk.outer(self.tensor, bk.conj(self.tensor))\n        return Density(matrix, self.qubits, self._memory)",
    "docstring": "Convert a pure state to a density matrix"
  },
  {
    "code": "def write_conf(self):\n        f = open(self.output_filename, 'w')\n        print(self.t.render(prefixes=self.prefixes), file=f)\n        f.close()",
    "docstring": "Write the config to file"
  },
  {
    "code": "def handle_button(self, event, event_type):\n        mouse_button_number = self._get_mouse_button_number(event)\n        if event_type in (25, 26):\n            event_type = event_type + (mouse_button_number * 0.1)\n        event_type_name, event_code, value, scan = self.codes[event_type]\n        if event_type_name == \"Key\":\n            scan_event, key_event = self.emulate_press(\n                event_code, scan, value, self.timeval)\n            self.events.append(scan_event)\n            self.events.append(key_event)",
    "docstring": "Handle mouse click."
  },
  {
    "code": "def encode(string):\n\t\tresult=\".\".join([ str(ord(s)) for s in string ])\n\t\treturn  \"%s.\" % (len(string)) + result",
    "docstring": "Encode the given string as an OID.\n\n\t\t>>> import snmp_passpersist as snmp\n\t\t>>> snmp.PassPersist.encode(\"hello\")\n\t\t'5.104.101.108.108.111'\n\t\t>>>"
  },
  {
    "code": "def get_field(self, path, name):\n        try:\n            value = self.get(path, name)\n            if not isinstance(value, str):\n                raise TypeError()\n            return value\n        except KeyError:\n            raise KeyError()",
    "docstring": "Retrieves the value of the field at the specified path.\n\n        :param path: str or Path instance\n        :param name:\n        :type name: str\n        :return:\n        :raises ValueError: A component of path is a field name.\n        :raises KeyError: A component of path doesn't exist.\n        :raises TypeError: The field name is a component of a path."
  },
  {
    "code": "def prune(self, minimum_word_frequency_percentage=1):\n        pruned_resulting_documents = []\n        for document in self.resulting_documents:\n            new_document = []\n            for word in document:\n                if self.word_in_how_many_documents[word] >= minimum_word_frequency_percentage / 100. * len(\n                        self.resulting_documents):\n                    new_document.append(word)\n            pruned_resulting_documents.append(new_document)\n        self.resulting_documents = pruned_resulting_documents",
    "docstring": "Filter out words that occur less than minimum_word_frequency times.\n\n            :param minimum_word_frequency_percentage: minimum frequency of words to keep"
  },
  {
    "code": "def inspect_network(self, net_id, verbose=None, scope=None):\n        params = {}\n        if verbose is not None:\n            if version_lt(self._version, '1.28'):\n                raise InvalidVersion('verbose was introduced in API 1.28')\n            params['verbose'] = verbose\n        if scope is not None:\n            if version_lt(self._version, '1.31'):\n                raise InvalidVersion('scope was introduced in API 1.31')\n            params['scope'] = scope\n        url = self._url(\"/networks/{0}\", net_id)\n        res = self._get(url, params=params)\n        return self._result(res, json=True)",
    "docstring": "Get detailed information about a network.\n\n        Args:\n            net_id (str): ID of network\n            verbose (bool): Show the service details across the cluster in\n                swarm mode.\n            scope (str): Filter the network by scope (``swarm``, ``global``\n                or ``local``)."
  },
  {
    "code": "def to_bytes(s, encoding=\"utf-8\"):\n    if isinstance(s, six.binary_type):\n        return s\n    else:\n        return six.text_type(s).encode(encoding)",
    "docstring": "Converts the string to a bytes type, if not already.\n\n    :s: the string to convert to bytes\n    :returns: `str` on Python2 and `bytes` on Python3."
  },
  {
    "code": "def decode_int(self, str):\n        n = 0\n        for c in str:\n            n = n * self.BASE + self.ALPHABET_REVERSE[c]\n        return n",
    "docstring": "Decodes a short Base64 string into an integer.\n\n        Example:\n            ``decode_int('B7')`` returns ``123``."
  },
  {
    "code": "def mangle_form(form):\n    \"Utility to monkeypatch forms into paperinputs, untested\"\n    for field, widget in form.fields.iteritems():\n        if type(widget) is forms.widgets.TextInput:\n            form.fields[field].widget = PaperTextInput()\n            form.fields[field].label = ''\n        if type(widget) is forms.widgets.PasswordInput:\n            field.widget = PaperPasswordInput()\n            field.label = ''\n    return form",
    "docstring": "Utility to monkeypatch forms into paperinputs, untested"
  },
  {
    "code": "def pty_wrapper_main():\n    sys.path.insert(0, os.path.dirname(__file__))\n    import _pty\n    _pty.spawn(sys.argv[1:])",
    "docstring": "Main function of the pty wrapper script"
  },
  {
    "code": "def list_entitlements_options(f):\n    @common_entitlements_options\n    @decorators.common_cli_config_options\n    @decorators.common_cli_list_options\n    @decorators.common_cli_output_options\n    @decorators.common_api_auth_options\n    @decorators.initialise_api\n    @click.argument(\n        \"owner_repo\", metavar=\"OWNER/REPO\", callback=validators.validate_owner_repo\n    )\n    @click.pass_context\n    @functools.wraps(f)\n    def wrapper(ctx, *args, **kwargs):\n        return ctx.invoke(f, *args, **kwargs)\n    return wrapper",
    "docstring": "Options for list entitlements subcommand."
  },
  {
    "code": "def update_settings(self, kwargs_model={}, kwargs_constraints={}, kwargs_likelihood={}, lens_add_fixed=[],\n                     source_add_fixed=[], lens_light_add_fixed=[], ps_add_fixed=[], cosmo_add_fixed=[], lens_remove_fixed=[],\n                     source_remove_fixed=[], lens_light_remove_fixed=[], ps_remove_fixed=[], cosmo_remove_fixed=[],\n                        change_source_lower_limit=None, change_source_upper_limit=None):\n        self._updateManager.update_options(kwargs_model, kwargs_constraints, kwargs_likelihood)\n        self._updateManager.update_fixed(self._lens_temp, self._source_temp, self._lens_light_temp, self._ps_temp,\n                                         self._cosmo_temp, lens_add_fixed, source_add_fixed, lens_light_add_fixed,\n                                         ps_add_fixed, cosmo_add_fixed, lens_remove_fixed, source_remove_fixed,\n                                         lens_light_remove_fixed, ps_remove_fixed, cosmo_remove_fixed)\n        self._updateManager.update_limits(change_source_lower_limit, change_source_upper_limit)\n        return 0",
    "docstring": "updates lenstronomy settings \"on the fly\"\n\n        :param kwargs_model: kwargs, specified keyword arguments overwrite the existing ones\n        :param kwargs_constraints: kwargs, specified keyword arguments overwrite the existing ones\n        :param kwargs_likelihood: kwargs, specified keyword arguments overwrite the existing ones\n        :param lens_add_fixed: [[i_model, ['param1', 'param2',...], [...]]\n        :param source_add_fixed: [[i_model, ['param1', 'param2',...], [...]]\n        :param lens_light_add_fixed: [[i_model, ['param1', 'param2',...], [...]]\n        :param ps_add_fixed: [[i_model, ['param1', 'param2',...], [...]]\n        :param cosmo_add_fixed: ['param1', 'param2',...]\n        :param lens_remove_fixed: [[i_model, ['param1', 'param2',...], [...]]\n        :param source_remove_fixed: [[i_model, ['param1', 'param2',...], [...]]\n        :param lens_light_remove_fixed: [[i_model, ['param1', 'param2',...], [...]]\n        :param ps_remove_fixed: [[i_model, ['param1', 'param2',...], [...]]\n        :param cosmo_remove_fixed: ['param1', 'param2',...]\n        :return: 0, the settings are overwritten for the next fitting step to come"
  },
  {
    "code": "def almutem(sign, lon):\n    planets = const.LIST_SEVEN_PLANETS\n    res = [None, 0]\n    for ID in planets:\n        sc = score(ID, sign, lon)\n        if sc > res[1]:\n            res = [ID, sc]\n    return res[0]",
    "docstring": "Returns the almutem for a given\n    sign and longitude."
  },
  {
    "code": "async def become(self, layer_type: Type[L], request: 'Request'):\n        if layer_type != RawText:\n            super(Text, self).become(layer_type, request)\n        return RawText(await render(self.text, request))",
    "docstring": "Transforms the translatable string into an actual string and put it\n        inside a RawText."
  },
  {
    "code": "def startAlertListener(self, callback=None):\n        notifier = AlertListener(self, callback)\n        notifier.start()\n        return notifier",
    "docstring": "Creates a websocket connection to the Plex Server to optionally recieve\n            notifications. These often include messages from Plex about media scans\n            as well as updates to currently running Transcode Sessions.\n\n            NOTE: You need websocket-client installed in order to use this feature.\n            >> pip install websocket-client\n\n            Parameters:\n                callback (func): Callback function to call on recieved messages.\n\n            raises:\n                :class:`plexapi.exception.Unsupported`: Websocket-client not installed."
  },
  {
    "code": "def _isValidQuery(self, query, mode=\"phonefy\"):\n        try:\n            validator = self.modes[mode].get(\"query_validator\")\n            if validator:\n                try:\n                    compiledRegexp = re.compile(\n                        \"^{expr}$\".format(\n                            expr=validator\n                        )\n                    )\n                    return compiledRegexp.match(query)\n                except AttributeError as e:\n                    return True\n        except AttributeError as e:\n            compiledRegexp = re.compile(\"^{r}$\".format(r=self.validQuery[mode]))\n            return compiledRegexp.match(query)",
    "docstring": "Method to verify if a given query is processable by the platform.\n\n        The system looks for the forbidden characters in self.Forbidden list.\n\n        Args:\n        -----\n            query: The query to be launched.\n            mode: To be chosen amongst mailfy, phonefy, usufy, searchfy.\n        Return:\n        -------\n            True | False"
  },
  {
    "code": "def import_pipeline(url, pipeline_id, auth, json_payload, verify_ssl, overwrite = False):\n    parameters = { 'overwrite' : overwrite }\n    import_result = requests.post(url + '/' + pipeline_id + '/import', params=parameters,\n                                  headers=X_REQ_BY, auth=auth, verify=verify_ssl, json=json_payload)\n    if import_result.status_code != 200:\n        logging.error('Import error response: ' + import_result.text)\n    import_result.raise_for_status()\n    logging.info('Pipeline import successful.')\n    return import_result.json()",
    "docstring": "Import a pipeline.\n\n    This will completely overwrite the existing pipeline.\n\n    Args:\n        url          (str): the host url in the form 'http://host:port/'.\n        pipeline_id   (str): the ID of of the exported pipeline.\n        auth       (tuple): a tuple of username, and password.\n        json_payload (dict): the exported json payload as a dictionary.\n        overwrite    (bool): overwrite existing pipeline\n        verify_ssl   (bool): whether to verify ssl certificates\n\n    Returns:\n        dict: the response json"
  },
  {
    "code": "def _init_nxapi(opts):\n    proxy_dict = opts.get('proxy', {})\n    conn_args = copy.deepcopy(proxy_dict)\n    conn_args.pop('proxytype', None)\n    opts['multiprocessing'] = conn_args.pop('multiprocessing', True)\n    try:\n        rpc_reply = __utils__['nxos.nxapi_request']('show clock', **conn_args)\n        DEVICE_DETAILS['conn_args'] = conn_args\n        DEVICE_DETAILS['initialized'] = True\n        DEVICE_DETAILS['up'] = True\n        DEVICE_DETAILS['no_save_config'] = opts['proxy'].get('no_save_config', False)\n    except Exception as ex:\n        log.error('Unable to connect to %s', conn_args['host'])\n        log.error('Please check the following:\\n')\n        log.error('-- Verify that \"feature nxapi\" is enabled on your NX-OS device: %s', conn_args['host'])\n        log.error('-- Verify that nxapi settings on the NX-OS device and proxy minion config file match')\n        log.error('-- Exception Generated: %s', ex)\n        exit()\n    log.info('nxapi DEVICE_DETAILS info: %s', DEVICE_DETAILS)\n    return True",
    "docstring": "Open a connection to the NX-OS switch over NX-API.\n\n    As the communication is HTTP(S) based, there is no connection to maintain,\n    however, in order to test the connectivity and make sure we are able to\n    bring up this Minion, we are executing a very simple command (``show clock``)\n    which doesn't come with much overhead and it's sufficient to confirm we are\n    indeed able to connect to the NX-API endpoint as configured."
  },
  {
    "code": "async def start_all_linking(self, linkcode, group, address=None):\n        _LOGGING.info('Starting the All-Linking process')\n        if address:\n            linkdevice = self.plm.devices[Address(address).id]\n            if not linkdevice:\n                linkdevice = create(self.plm, address, None, None)\n            _LOGGING.info('Attempting to link the PLM to device %s. ',\n                          address)\n            self.plm.start_all_linking(linkcode, group)\n            asyncio.sleep(.5, loop=self.loop)\n            linkdevice.enter_linking_mode(group=group)\n        else:\n            _LOGGING.info('Starting All-Linking on PLM. '\n                          'Waiting for button press')\n            self.plm.start_all_linking(linkcode, group)\n            await asyncio.sleep(self.wait_time, loop=self.loop)\n        _LOGGING.info('%d devices added to the All-Link Database',\n                      len(self.plm.devices))\n        await asyncio.sleep(.1, loop=self.loop)",
    "docstring": "Start the All-Linking process with the IM and device."
  },
  {
    "code": "def decorator(func):\n  r\n  def wrapper(__decorated__=None, *Args, **KwArgs):\n    if __decorated__ is None:\n      return lambda _func: func(_func, *Args, **KwArgs)\n    else:\n      return func(__decorated__, *Args, **KwArgs)\n  return wrap(wrapper, func)",
    "docstring": "r\"\"\"Makes the passed decorators to support optional args."
  },
  {
    "code": "def list(self, request, *args, **kwargs):\n        return super(ServicesViewSet, self).list(request, *args, **kwargs)",
    "docstring": "Filter services by type\n        ^^^^^^^^^^^^^^^^^^^^^^^\n\n        It is possible to filter services by their types. Example:\n\n          /api/services/?service_type=DigitalOcean&service_type=OpenStack"
  },
  {
    "code": "def execute(func, handler, args, kwargs):\n    tracing = handler.settings.get('opentracing_tracing')\n    with tracer_stack_context():\n        if tracing._trace_all:\n            attrs = handler.settings.get('opentracing_traced_attributes', [])\n            tracing._apply_tracing(handler, attrs)\n        return func(*args, **kwargs)",
    "docstring": "Wrap the handler ``_execute`` method to trace incoming requests,\n    extracting the context from the headers, if available."
  },
  {
    "code": "def noEmptyNests(node): \n    if type(node)==list:\n        for i in node:\n            noEmptyNests(i)\n    if type(node)==dict:\n        for i in node.values():\n            noEmptyNests(i)\n        if node[\"children\"] == []:\n            node.pop(\"children\")\n    return node",
    "docstring": "recursively make sure that no dictionaries inside node contain empty children lists"
  },
  {
    "code": "def as_string(self, chars, show_leaf=True, current_linkable=False, class_current=\"active_link\"):\n        return self.__do_menu(\"as_string\", show_leaf, current_linkable, class_current, chars)",
    "docstring": "It returns breadcrumb as string"
  },
  {
    "code": "def get_create_index_sql(self, index, table):\n        if isinstance(table, Table):\n            table = table.get_quoted_name(self)\n        name = index.get_quoted_name(self)\n        columns = index.get_quoted_columns(self)\n        if not columns:\n            raise DBALException('Incomplete definition. \"columns\" required.')\n        if index.is_primary():\n            return self.get_create_primary_key_sql(index, table)\n        query = \"CREATE %sINDEX %s ON %s\" % (\n            self.get_create_index_sql_flags(index),\n            name,\n            table,\n        )\n        query += \" (%s)%s\" % (\n            self.get_index_field_declaration_list_sql(columns),\n            self.get_partial_index_sql(index),\n        )\n        return query",
    "docstring": "Returns the SQL to create an index on a table on this platform.\n\n        :param index: The index\n        :type index: Index\n\n        :param table: The table\n        :type table: Table or str\n\n        :rtype: str"
  },
  {
    "code": "def get_object_name(obj):\n    name_dispatch = {\n        ast.Name: \"id\",\n        ast.Attribute: \"attr\",\n        ast.Call: \"func\",\n        ast.FunctionDef: \"name\",\n        ast.ClassDef: \"name\",\n        ast.Subscript: \"value\",\n    }\n    if hasattr(ast, \"arg\"):\n        name_dispatch[ast.arg] = \"arg\"\n    while not isinstance(obj, str):\n        assert type(obj) in name_dispatch\n        obj = getattr(obj, name_dispatch[type(obj)])\n    return obj",
    "docstring": "Return the name of a given object"
  },
  {
    "code": "def get_curricula_by_term(term, view_unpublished=False):\n    view_unpublished = \"true\" if view_unpublished else \"false\"\n    url = \"{}?{}\".format(\n        curriculum_search_url_prefix,\n        urlencode([\n                   (\"quarter\", term.quarter.lower(),),\n                   (\"year\", term.year,),\n                   (\"view_unpublished\", view_unpublished,)]))\n    return _json_to_curricula(get_resource(url))",
    "docstring": "Returns a list of restclients.Curriculum models, for the passed\n    Term model."
  },
  {
    "code": "def add_adjust(self, data, prehashed=False):\n        subtrees = self._get_whole_subtrees()\n        new_node = Node(data, prehashed=prehashed)\n        self.leaves.append(new_node)\n        for node in reversed(subtrees):\n            new_parent = Node(node.val + new_node.val)\n            node.p, new_node.p = new_parent, new_parent\n            new_parent.l, new_parent.r = node, new_node\n            node.sib, new_node.sib = new_node, node\n            node.side, new_node.side = 'L', 'R'\n            new_node = new_node.p\n        self.root = new_node",
    "docstring": "Add a new leaf, and adjust the tree, without rebuilding the whole thing."
  },
  {
    "code": "def get_application_parser(commands):\n    parser = argparse.ArgumentParser(\n        description=configuration.APPLICATION_DESCRIPTION,\n        usage =configuration.EXECUTABLE_NAME + ' [sub-command] [options]',\n        add_help=False)\n    parser.add_argument(\n        'sub_command',\n        choices=[name for name in commands],\n        nargs=\"?\")\n    parser.add_argument(\"-h\", \"--help\", action=\"store_true\")\n    return parser",
    "docstring": "Builds an argument parser for the application's CLI.\n\n    :param commands:\n    :return: ArgumentParser"
  },
  {
    "code": "def create_time_subscription(self, instance, on_data=None, timeout=60):\n        manager = WebSocketSubscriptionManager(self, resource='time')\n        subscription = TimeSubscription(manager)\n        wrapped_callback = functools.partial(\n            _wrap_callback_parse_time_info, subscription, on_data)\n        manager.open(wrapped_callback, instance)\n        subscription.reply(timeout=timeout)\n        return subscription",
    "docstring": "Create a new subscription for receiving time updates of an instance.\n        Time updates are emitted at 1Hz.\n\n        This method returns a future, then returns immediately. Stop the\n        subscription by canceling the future.\n\n        :param str instance: A Yamcs instance name\n\n        :param on_data: Function that gets called with\n                        :class:`~datetime.datetime` updates.\n        :type on_data: Optional[Callable[~datetime.datetime])\n\n        :param timeout: The amount of seconds to wait for the request to\n                        complete.\n        :type timeout: Optional[float]\n\n        :return: Future that can be used to manage the background websocket\n                 subscription.\n        :rtype: .TimeSubscription"
  },
  {
    "code": "def create_client_with_lazy_load(api_key, cache_time_to_live_seconds=60, config_cache_class=None,\n                                 base_url=None):\n    if api_key is None:\n        raise ConfigCatClientException('API Key is required.')\n    if cache_time_to_live_seconds < 1:\n        cache_time_to_live_seconds = 1\n    return ConfigCatClient(api_key, 0, 0, None, cache_time_to_live_seconds, config_cache_class, base_url)",
    "docstring": "Create an instance of ConfigCatClient and setup Lazy Load mode with custom options\n\n    :param api_key: ConfigCat ApiKey to access your configuration.\n    :param cache_time_to_live_seconds: The cache TTL.\n    :param config_cache_class: If you want to use custom caching instead of the client's default InMemoryConfigCache,\n    You can provide an implementation of ConfigCache.\n    :param base_url: You can set a base_url if you want to use a proxy server between your application and ConfigCat"
  },
  {
    "code": "def set_defaults(config, cluster_name):\n    config['postgresql'].setdefault('name', cluster_name)\n    config['postgresql'].setdefault('scope', cluster_name)\n    config['postgresql'].setdefault('listen', '127.0.0.1')\n    config['postgresql']['authentication'] = {'replication': None}\n    config['restapi']['listen'] = ':' in config['restapi']['listen'] and config['restapi']['listen'] or '127.0.0.1:8008'",
    "docstring": "fill-in some basic configuration parameters if config file is not set"
  },
  {
    "code": "def get_function_for_cognito_trigger(self, trigger):\n        print(\"get_function_for_cognito_trigger\", self.settings.COGNITO_TRIGGER_MAPPING, trigger, self.settings.COGNITO_TRIGGER_MAPPING.get(trigger))\n        return self.settings.COGNITO_TRIGGER_MAPPING.get(trigger)",
    "docstring": "Get the associated function to execute for a cognito trigger"
  },
  {
    "code": "def save_params(model_name: str):\n    with open(model_name + '.params', 'w') as f:\n        json.dump(pr.__dict__, f)",
    "docstring": "Save current global listener params to a file"
  },
  {
    "code": "def remove_accounts_from_institute(accounts_query, institute):\n    query = accounts_query.filter(date_deleted__isnull=True)\n    for account in query:\n        remove_account_from_institute(account, institute)",
    "docstring": "Remove accounts from institute."
  },
  {
    "code": "def clear_data(self):\n        self.__header.title = None\n        self.__header.subtitle = None\n        self.__prologue.text = None\n        self.__epilogue.text = None\n        self.__items_section.items = None",
    "docstring": "Clear menu data from previous menu generation."
  },
  {
    "code": "def transformFromNative(self):\n        if self.isNative and self.behavior and self.behavior.hasNative:\n            try:\n                return self.behavior.transformFromNative(self)\n            except Exception as e:\n                lineNumber = getattr(self, 'lineNumber', None)\n                if isinstance(e, NativeError):\n                    if lineNumber is not None:\n                        e.lineNumber = lineNumber\n                    raise\n                else:\n                    msg = \"In transformFromNative, unhandled exception on line %s %s: %s\"\n                    msg = msg % (lineNumber, sys.exc_info()[0], sys.exc_info()[1])\n                    raise NativeError(msg, lineNumber)\n        else:\n            return self",
    "docstring": "Return self transformed into a ContentLine or Component if needed.\n\n        May have side effects.  If it does, transformFromNative and\n        transformToNative MUST have perfectly inverse side effects. Allowing\n        such side effects is convenient for objects whose transformations only\n        change a few attributes.\n\n        Note that it isn't always possible for transformFromNative to be a\n        perfect inverse of transformToNative, in such cases transformFromNative\n        should return a new object, not self after modifications."
  },
  {
    "code": "def move_roles_to_base_role_config_group(resource_root, service_name,\n     role_names, cluster_name=\"default\"):\n  return call(resource_root.put,\n      _get_role_config_groups_path(cluster_name, service_name) + '/roles',\n      ApiRole, True, data=role_names, api_version=3)",
    "docstring": "Moves roles to the base role config group.\n\n  The roles can be moved from any role config group belonging to the same\n  service. The role type of the roles may vary. Each role will be moved to\n  its corresponding base group depending on its role type.\n\n  @param role_names: The names of the roles to move.\n  @return: List of roles which have been moved successfully.\n  @since: API v3"
  },
  {
    "code": "def _collapse_subitems(base, items):\n    out = []\n    for d in items:\n        newd = _diff_dict(base, d)\n        out.append(newd)\n    return out",
    "docstring": "Collapse full data representations relative to a standard base."
  },
  {
    "code": "def passwordReset1to2(old):\n    new = old.upgradeVersion(old.typeName, 1, 2, installedOn=None)\n    for iface in new.store.interfacesFor(new):\n        new.store.powerDown(new, iface)\n    new.deleteFromStore()",
    "docstring": "Power down and delete the item"
  },
  {
    "code": "def _emit_message(cls, message):\n        sys.stdout.write(message)\n        sys.stdout.flush()",
    "docstring": "Print a message to STDOUT."
  },
  {
    "code": "def save_source(driver, name):\n    source = driver.page_source\n    file_name = os.path.join(os.environ.get('SAVED_SOURCE_DIR'),\n                             '{name}.html'.format(name=name))\n    try:\n        with open(file_name, 'wb') as output_file:\n            output_file.write(source.encode('utf-8'))\n    except Exception:\n        msg = u\"Could not save the browser page source to {}.\".format(file_name)\n        LOGGER.warning(msg)",
    "docstring": "Save the rendered HTML of the browser.\n\n    The location of the source can be configured\n    by the environment variable `SAVED_SOURCE_DIR`.  If not set,\n    this defaults to the current working directory.\n\n    Args:\n        driver (selenium.webdriver): The Selenium-controlled browser.\n        name (str): A name to use in the output file name.\n            Note that \".html\" is appended automatically\n\n    Returns:\n        None"
  },
  {
    "code": "def _get_acquisition(self, model, space):\n        from copy import deepcopy        \n        acqOpt_config = deepcopy(self.config['acquisition']['optimizer'])\n        acqOpt_name = acqOpt_config['name']\n        del acqOpt_config['name']\n        from ..optimization import AcquisitionOptimizer\n        acqOpt = AcquisitionOptimizer(space, acqOpt_name, **acqOpt_config)\n        from ..acquisitions import select_acquisition\n        return select_acquisition(self.config['acquisition']['type']).fromConfig(model, space, acqOpt, None, self.config['acquisition'])",
    "docstring": "Imports the acquisition"
  },
  {
    "code": "def heatmap(z, x=None, y=None, colorscale='Viridis'):\n    z = np.atleast_1d(z)\n    data = [go.Heatmap(z=z, x=x, y=y, colorscale=colorscale)]\n    return Chart(data=data)",
    "docstring": "Create a heatmap.\n\n    Parameters\n    ----------\n    z : TODO\n    x : TODO, optional\n    y : TODO, optional\n    colorscale : TODO, optional\n\n    Returns\n    -------\n    Chart"
  },
  {
    "code": "def _loadable_get_(name, self):\n        \"Used to lazily-evaluate & memoize an attribute.\"\n        func = getattr(self._attr_func_, name)\n        ret = func()\n        setattr(self._attr_data_, name, ret)\n        setattr(\n            type(self),\n            name,\n            property(\n                functools.partial(self._simple_get_, name)\n            )\n        )\n        delattr(self._attr_func_, name)\n        return ret",
    "docstring": "Used to lazily-evaluate & memoize an attribute."
  },
  {
    "code": "def do_PUT(self):\n        self.do_initial_operations()\n        payload = self.coap_uri.get_payload()\n        if payload is None:\n            logger.error(\"BAD PUT REQUEST\")\n            self.send_error(BAD_REQUEST)\n            return\n        logger.debug(payload)\n        coap_response = self.client.put(self.coap_uri.path, payload)\n        self.client.stop()\n        logger.debug(\"Server response: %s\", coap_response.pretty_print())\n        self.set_http_response(coap_response)",
    "docstring": "Perform a PUT request"
  },
  {
    "code": "def compute_taxes(self, precision=None):\n        base = self.gross - self.total_discounts\n        return quantize(sum([t.compute(base, precision) for t in self.__taxes]),\n                        precision)",
    "docstring": "Returns the total amount of taxes for this line with a specific \n        number of decimals\n        @param precision: int Number of decimal places\n        @return: Decimal"
  },
  {
    "code": "def change(img):\n    if not os.path.isfile(img):\n        return\n    desktop = get_desktop_env()\n    if OS == \"Darwin\":\n        set_mac_wallpaper(img)\n    elif OS == \"Windows\":\n        set_win_wallpaper(img)\n    else:\n        set_desktop_wallpaper(desktop, img)\n    logging.info(\"Set the new wallpaper.\")",
    "docstring": "Set the wallpaper."
  },
  {
    "code": "def codes_match_any(self, codes):\n        for selector in self.code_selectors:\n            if selector.code in codes:\n                return True\n        return False",
    "docstring": "Match any code."
  },
  {
    "code": "def hash_pair(first: Keccak256, second: Optional[Keccak256]) -> Keccak256:\n    assert first is not None\n    if second is None:\n        return first\n    if first > second:\n        return sha3(second + first)\n    return sha3(first + second)",
    "docstring": "Computes the keccak hash of the elements ordered topologically.\n\n    Since a merkle proof will not include all the elements, but only the path\n    starting from the leaves up to the root, the order of the elements is not\n    known by the proof checker. The topological order is used as a\n    deterministic way of ordering the elements making sure the smart contract\n    verification and the python code are compatible."
  },
  {
    "code": "def handle(cls, value, **kwargs):\n        value = read_value_from_path(value)\n        region = None\n        if \"@\" in value:\n            region, value = value.split(\"@\", 1)\n        kms = get_session(region).client('kms')\n        value = value.encode('utf-8')\n        decoded = codecs.decode(value, 'base64')\n        return kms.decrypt(CiphertextBlob=decoded)[\"Plaintext\"]",
    "docstring": "Decrypt the specified value with a master key in KMS.\n\n        kmssimple field types should be in the following format:\n\n            [<region>@]<base64 encrypted value>\n\n        Note: The region is optional, and defaults to the environment's\n        `AWS_DEFAULT_REGION` if not specified.\n\n        For example:\n\n            # We use the aws cli to get the encrypted value for the string\n            # \"PASSWORD\" using the master key called \"myStackerKey\" in\n            # us-east-1\n            $ aws --region us-east-1 kms encrypt --key-id alias/myStackerKey \\\n                    --plaintext \"PASSWORD\" --output text --query CiphertextBlob\n\n            CiD6bC8t2Y<...encrypted blob...>\n\n            # In stacker we would reference the encrypted value like:\n            conf_key: ${kms us-east-1@CiD6bC8t2Y<...encrypted blob...>}\n\n            You can optionally store the encrypted value in a file, ie:\n\n            kms_value.txt\n            us-east-1@CiD6bC8t2Y<...encrypted blob...>\n\n            and reference it within stacker (NOTE: the path should be relative\n            to the stacker config file):\n\n            conf_key: ${kms file://kms_value.txt}\n\n            # Both of the above would resolve to\n            conf_key: PASSWORD"
  },
  {
    "code": "def load_config(data, *models, **kwargs):\n    if isinstance(models, tuple) and isinstance(models[0], list):\n        models = models[0]\n    config = get_config(data, *models, **kwargs)\n    test = kwargs.pop('test', False)\n    debug = kwargs.pop('debug', False)\n    commit = kwargs.pop('commit', True)\n    replace = kwargs.pop('replace', False)\n    return __salt__['net.load_config'](text=config,\n                                       test=test,\n                                       debug=debug,\n                                       commit=commit,\n                                       replace=replace,\n                                       inherit_napalm_device=napalm_device)",
    "docstring": "Generate and load the config on the device using the OpenConfig or IETF\n    models and device profiles.\n\n    data\n        Dictionary structured with respect to the models referenced.\n\n    models\n        A list of models to be used when generating the config.\n\n    profiles: ``None``\n        Use certain profiles to generate the config.\n        If not specified, will use the platform default profile(s).\n\n    test: ``False``\n        Dry run? If set as ``True``, will apply the config, discard\n        and return the changes. Default: ``False`` and will commit\n        the changes on the device.\n\n    commit: ``True``\n        Commit? Default: ``True``.\n\n    debug: ``False``\n        Debug mode. Will insert a new key under the output dictionary,\n        as ``loaded_config`` containing the raw configuration loaded on the device.\n\n    replace: ``False``\n        Should replace the config with the new generate one?\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' napalm_yang.load_config {} models.openconfig_interfaces test=True debug=True\n\n    Output Example:\n\n    .. code-block:: jinja\n\n        device1:\n            ----------\n            already_configured:\n                False\n            comment:\n            diff:\n                [edit interfaces ge-0/0/0]\n                -   mtu 1400;\n                [edit interfaces ge-0/0/0 unit 0 family inet]\n                -       dhcp;\n                [edit interfaces lo0]\n                -    unit 0 {\n                -        description lo0.0;\n                -    }\n                +    unit 1 {\n                +        description \"new loopback\";\n                +    }\n            loaded_config:\n                <configuration>\n                  <interfaces replace=\"replace\">\n                    <interface>\n                      <name>ge-0/0/0</name>\n                      <unit>\n                        <name>0</name>\n                        <family>\n                          <inet/>\n                        </family>\n                        <description>ge-0/0/0.0</description>\n                      </unit>\n                      <description>management interface</description>\n                    </interface>\n                    <interface>\n                      <name>ge-0/0/1</name>\n                      <disable/>\n                      <description>ge-0/0/1</description>\n                    </interface>\n                    <interface>\n                      <name>ae0</name>\n                      <unit>\n                        <name>0</name>\n                        <vlan-id>100</vlan-id>\n                        <family>\n                          <inet>\n                            <address>\n                              <name>192.168.100.1/24</name>\n                            </address>\n                            <address>\n                              <name>172.20.100.1/24</name>\n                            </address>\n                          </inet>\n                        </family>\n                        <description>a description</description>\n                      </unit>\n                      <vlan-tagging/>\n                      <unit>\n                        <name>1</name>\n                        <vlan-id>1</vlan-id>\n                        <family>\n                          <inet>\n                            <address>\n                              <name>192.168.101.1/24</name>\n                            </address>\n                          </inet>\n                        </family>\n                        <disable/>\n                        <description>ae0.1</description>\n                      </unit>\n                      <vlan-tagging/>\n                      <unit>\n                        <name>2</name>\n                        <vlan-id>2</vlan-id>\n                        <family>\n                          <inet>\n                            <address>\n                              <name>192.168.102.1/24</name>\n                            </address>\n                          </inet>\n                        </family>\n                        <description>ae0.2</description>\n                      </unit>\n                      <vlan-tagging/>\n                    </interface>\n                    <interface>\n                      <name>lo0</name>\n                      <unit>\n                        <name>1</name>\n                        <description>new loopback</description>\n                      </unit>\n                      <description>lo0</description>\n                    </interface>\n                  </interfaces>\n                </configuration>\n            result:\n                True"
  },
  {
    "code": "def retrieve_loadbalancer_status(self, loadbalancer, **_params):\n        return self.get(self.lbaas_loadbalancer_path_status % (loadbalancer),\n                        params=_params)",
    "docstring": "Retrieves status for a certain load balancer."
  },
  {
    "code": "def setCachedDataKey(engineVersionHash, key, value):\n\t\tcacheFile = CachedDataManager._cacheFileForHash(engineVersionHash)\n\t\treturn JsonDataManager(cacheFile).setKey(key, value)",
    "docstring": "Sets the cached data value for the specified engine version hash and dictionary key"
  },
  {
    "code": "def pole_from_endpoints(coord1, coord2):\n    c1 = coord1.cartesian / coord1.cartesian.norm()\n    coord2 = coord2.transform_to(coord1.frame)\n    c2 = coord2.cartesian / coord2.cartesian.norm()\n    pole = c1.cross(c2)\n    pole = pole / pole.norm()\n    return coord1.frame.realize_frame(pole)",
    "docstring": "Compute the pole from a great circle that connects the two specified\n    coordinates.\n\n    This assumes a right-handed rule from coord1 to coord2: the pole is the\n    north pole under that assumption.\n\n    Parameters\n    ----------\n    coord1 : `~astropy.coordinates.SkyCoord`\n        Coordinate of one point on a great circle.\n    coord2 : `~astropy.coordinates.SkyCoord`\n        Coordinate of the other point on a great circle.\n\n    Returns\n    -------\n    pole : `~astropy.coordinates.SkyCoord`\n        The coordinates of the pole."
  },
  {
    "code": "def write_byte(self, address, value):\n        LOGGER.debug(\"Writing byte %s to device %s!\", bin(value), hex(address))\n        return self.driver.write_byte(address, value)",
    "docstring": "Writes the byte to unaddressed register in a device."
  },
  {
    "code": "def getControllerStateWithPose(self, eOrigin, unControllerDeviceIndex, unControllerStateSize=sizeof(VRControllerState_t)):\n        fn = self.function_table.getControllerStateWithPose\n        pControllerState = VRControllerState_t()\n        pTrackedDevicePose = TrackedDevicePose_t()\n        result = fn(eOrigin, unControllerDeviceIndex, byref(pControllerState), unControllerStateSize, byref(pTrackedDevicePose))\n        return result, pControllerState, pTrackedDevicePose",
    "docstring": "fills the supplied struct with the current state of the controller and the provided pose with the pose of \n        the controller when the controller state was updated most recently. Use this form if you need a precise controller\n        pose as input to your application when the user presses or releases a button. This function is deprecated in favor of the new IVRInput system."
  },
  {
    "code": "def reinit_index(index=INDEX_NAME):\n    es_conn.indices.delete(index, ignore=404)\n    try:\n        es_conn.indices.create(index, INDEX_SETTINGS.get(index, None))\n    except TransportError as e:\n        raise Exception('Failed to created index, got: {}'.format(e.error))",
    "docstring": "Delete and then initialise the given index name\n\n    Gets settings if they exist in the mappings module.\n\n    https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.client.IndicesClient.create\n    https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html\n\n    https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.client.IndicesClient.delete\n    https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-delete-index.html"
  },
  {
    "code": "def from_dict(cls, d):\n        conf = {}\n        for k in d[\"config\"]:\n            v = d[\"config\"][k]\n            if isinstance(v, dict):\n                conf[str(k)] = get_dict_handler(d[\"config\"][\"type\"])(v)\n            else:\n                conf[str(k)] = v\n        return get_class(str(d[\"class\"]))(config=conf)",
    "docstring": "Restores its state from a dictionary, used in de-JSONification.\n\n        :param d: the object dictionary\n        :type d: dict"
  },
  {
    "code": "def conforms(self, json: str, name: str = \"\", verbose: bool=False) -> ValidationResult:\n        json = self._to_string(json) if not self.is_json(json) else json\n        try:\n            self.json_obj = loads(json, self.module)\n        except ValueError as v:\n            return ValidationResult(False, str(v), name, None)\n        logfile = StringIO()\n        logger = Logger(cast(TextIO, logfile))\n        if not is_valid(self.json_obj, logger):\n            return ValidationResult(False, logfile.getvalue().strip('\\n'), name, None)\n        return ValidationResult(True, \"\", name, type(self.json_obj).__name__)",
    "docstring": "Determine whether json conforms with the JSG specification\n\n        :param json: JSON string, URI to JSON or file name with JSON\n        :param name: Test name for ValidationResult -- printed in dx if present\n        :param verbose: True means print the response\n        :return: pass/fail + fail reason"
  },
  {
    "code": "def get_postalcodes_around_radius(self, pc, radius):\n        postalcodes = self.get(pc)\n        if postalcodes is None:\n            raise PostalCodeNotFoundException(\"Could not find postal code you're searching for.\")\n        else:\n            pc = postalcodes[0]\n        radius = float(radius)\n        earth_radius  = 6371\n        dlat = radius / earth_radius\n        dlon = asin(sin(dlat) / cos(radians(pc.latitude)))\n        lat_delta = degrees(dlat)\n        lon_delta = degrees(dlon)\n        if lat_delta < 0:\n            lat_range = (pc.latitude + lat_delta, pc.latitude - lat_delta)\n        else:\n            lat_range = (pc.latitude - lat_delta, pc.latitude + lat_delta)\n        long_range  = (pc.longitude - lat_delta, pc.longitude + lon_delta)    \n        return format_result(self.conn_manager.query(PC_RANGE_QUERY % (\n            long_range[0], long_range[1],\n            lat_range[0], lat_range[1]\n        )))",
    "docstring": "Bounding box calculations updated from pyzipcode"
  },
  {
    "code": "def find_faces(self, image, draw_box=False):\n        frame_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n        faces = self.cascade.detectMultiScale(\n            frame_gray,\n            scaleFactor=1.3,\n            minNeighbors=5,\n            minSize=(50, 50),\n            flags=0)\n        if draw_box:\n            for x, y, w, h in faces:\n                cv2.rectangle(image, (x, y),\n                              (x + w, y + h), (0, 255, 0), 2)\n        return faces",
    "docstring": "Uses a haarcascade to detect faces inside an image.\n\n        Args:\n            image: The image.\n            draw_box: If True, the image will be marked with a rectangle.\n\n        Return:\n            The faces as returned by OpenCV's detectMultiScale method for\n            cascades."
  },
  {
    "code": "def on_apply(self, event):\n        for label in self.setting_map.keys():\n            setting = self.setting_map[label]\n            ctrl = self.controls[label]\n            value = ctrl.GetValue()\n            if str(value) != str(setting.value):\n                oldvalue = setting.value\n                if not setting.set(value):\n                    print(\"Invalid value %s for %s\" % (value, setting.name))\n                    continue\n                if str(oldvalue) != str(setting.value):\n                    self.parent_pipe.send(setting)",
    "docstring": "called on apply"
  },
  {
    "code": "def write(editor, location, force=False):\n    if location and not force and os.path.exists(location):\n        editor.show_message('File exists (add ! to overriwe)')\n    else:\n        eb = editor.window_arrangement.active_editor_buffer\n        if location is None and eb.location is None:\n            editor.show_message(_NO_FILE_NAME)\n        else:\n            eb.write(location)",
    "docstring": "Write file."
  },
  {
    "code": "def get_safe_type(self):\n        product_type = self.product_id.split('_')[1]\n        if product_type.startswith('MSI'):\n            return EsaSafeType.COMPACT_TYPE\n        if product_type in ['OPER', 'USER']:\n            return EsaSafeType.OLD_TYPE\n        raise ValueError('Unrecognized product type of product id {}'.format(self.product_id))",
    "docstring": "Determines the type of ESA product.\n\n        In 2016 ESA changed structure and naming of data. Therefore the class must\n        distinguish between old product type and compact (new) product type.\n\n        :return: type of ESA product\n        :rtype: constants.EsaSafeType\n        :raises: ValueError"
  },
  {
    "code": "def check_declared(self, node):\n        for ident in node.undeclared_identifiers():\n            if ident != 'context' and\\\n                    ident not in self.declared.union(self.locally_declared):\n                self.undeclared.add(ident)\n        for ident in node.declared_identifiers():\n            self.locally_declared.add(ident)",
    "docstring": "update the state of this Identifiers with the undeclared\n            and declared identifiers of the given node."
  },
  {
    "code": "def press_keycode(self, keycode, metastate=None):\n        driver = self._current_application()\n        driver.press_keycode(keycode, metastate)",
    "docstring": "Sends a press of keycode to the device.\n\n        Android only.\n\n        Possible keycodes & meta states can be found in\n        http://developer.android.com/reference/android/view/KeyEvent.html\n\n        Meta state describe the pressed state of key modifiers such as\n        Shift, Ctrl & Alt keys. The Meta State is an integer in which each\n        bit set to 1 represents a pressed meta key.\n\n        For example\n        - META_SHIFT_ON = 1\n        - META_ALT_ON = 2\n\n        | metastate=1 --> Shift is pressed\n        | metastate=2 --> Alt is pressed\n        | metastate=3 --> Shift+Alt is pressed\n\n         - _keycode- - the keycode to be sent to the device\n         - _metastate- - status of the meta keys"
  },
  {
    "code": "def close(self):\n        with self.stop_lock:\n            self.stopped = True\n        return ioloop_util.submit(self._flush, io_loop=self.io_loop)",
    "docstring": "Ensure that all spans from the queue are submitted.\n        Returns Future that will be completed once the queue is empty."
  },
  {
    "code": "def in_navitem(self, resources, nav_href):\n        if nav_href.endswith('/index'):\n            nav_href = nav_href[:-6]\n        return self.docname.startswith(nav_href)",
    "docstring": "Given  href of nav item, determine if resource is in it"
  },
  {
    "code": "def disallow(self):\n        value = self._schema.get(\"disallow\", None)\n        if value is None:\n            return\n        if not isinstance(value, (basestring, dict, list)):\n            raise SchemaError(\n                \"disallow value {0!r} is not a simple type name, nested \"\n                \"schema nor a list of those\".format(value))\n        if isinstance(value, list):\n            disallow_list = value\n        else:\n            disallow_list = [value]\n        seen = set()\n        for js_disallow in disallow_list:\n            if isinstance(js_disallow, dict):\n                pass\n            else:\n                if js_disallow in seen:\n                    raise SchemaError(\n                        \"disallow value {0!r} contains duplicate element\"\n                        \" {1!r}\".format(value, js_disallow))\n                else:\n                    seen.add(js_disallow)\n                if js_disallow not in (\n                    \"string\", \"number\", \"integer\", \"boolean\", \"object\",\n                    \"array\", \"null\", \"any\"):\n                    raise SchemaError(\n                        \"disallow value {0!r} is not a simple type\"\n                        \" name\".format(js_disallow))\n        return disallow_list",
    "docstring": "Description of disallowed objects.\n\n        Disallow must be a type name, a nested schema or a list of those.  Type\n        name must be one of ``string``, ``number``, ``integer``, ``boolean``,\n        ``object``, ``array``, ``null`` or ``any``."
  },
  {
    "code": "def merged(cls, *flatterms: 'FlatTerm') -> 'FlatTerm':\n        return cls(cls._combined_wildcards_iter(sum(flatterms, cls.empty())))",
    "docstring": "Concatenate the given flatterms to a single flatterm.\n\n        Args:\n            *flatterms:\n                The flatterms which are concatenated.\n\n        Returns:\n            The concatenated flatterms."
  },
  {
    "code": "def to_ufo_background_image(self, ufo_glyph, layer):\n    image = layer.backgroundImage\n    if image is None:\n        return\n    ufo_image = ufo_glyph.image\n    ufo_image.fileName = image.path\n    ufo_image.transformation = image.transform\n    ufo_glyph.lib[CROP_KEY] = list(image.crop)\n    ufo_glyph.lib[LOCKED_KEY] = image.locked\n    ufo_glyph.lib[ALPHA_KEY] = image.alpha",
    "docstring": "Copy the backgound image from the GSLayer to the UFO Glyph."
  },
  {
    "code": "def unicode_wrapper(self, property, default=ugettext('Untitled')):\n        try:\n            value = getattr(self, property)\n        except ValueError:\n            logger.warn(\n                u'ValueError rendering unicode for %s object.',\n                self._meta.object_name\n            )\n            value = None\n        if not value:\n            value = default\n        return value",
    "docstring": "Wrapper to allow for easy unicode representation of an object by\n        the specified property. If this wrapper is not able to find the\n        right translation of the specified property, it will return the\n        default value instead.\n\n        Example::\n            def __unicode__(self):\n                return unicode_wrapper('name', default='Unnamed')"
  },
  {
    "code": "def from_class_name(name, theme_element):\n        msg = \"No such themeable element {}\".format(name)\n        try:\n            klass = themeable._registry[name]\n        except KeyError:\n            raise PlotnineError(msg)\n        if not issubclass(klass, themeable):\n            raise PlotnineError(msg)\n        return klass(theme_element)",
    "docstring": "Create an themeable by name\n\n        Parameters\n        ----------\n        name : str\n            Class name\n        theme_element : element object\n            One of :class:`element_line`, :class:`element_rect`,\n            :class:`element_text` or :class:`element_blank`\n\n        Returns\n        -------\n        out : Themeable"
  },
  {
    "code": "def min_heapify(arr, start, simulation, iteration):\n    end = len(arr) - 1\n    last_parent = (end - start - 1) // 2\n    for parent in range(last_parent, -1, -1):\n        current_parent = parent\n        while current_parent <= last_parent:\n            child = 2 * current_parent + 1\n            if child + 1 <= end - start and arr[child + start] > arr[\n                child + 1 + start]:\n                child = child + 1\n            if arr[child + start] < arr[current_parent + start]:\n                arr[current_parent + start], arr[child + start] = \\\n                    arr[child + start], arr[current_parent + start]\n                current_parent = child\n                if simulation:\n                    iteration = iteration + 1\n                    print(\"iteration\",iteration,\":\",*arr)\n            else:\n                break\n    return iteration",
    "docstring": "Min heapify helper for min_heap_sort"
  },
  {
    "code": "def as_plural(result_key):\n    if result_key.endswith('y'):\n        return re.sub(\"y$\", \"ies\", result_key)\n    elif result_key.endswith('address'):\n        return result_key + 'es'\n    elif result_key.endswith('us'):\n        return re.sub(\"us$\", \"uses\", result_key)\n    elif not result_key.endswith('s'):\n        return result_key + 's'\n    else:\n        return result_key",
    "docstring": "Given a result key, return in the plural form."
  },
  {
    "code": "def average_gradients(tower_gradients):\n    r\n    average_grads = []\n    with tf.device(Config.cpu_device):\n        for grad_and_vars in zip(*tower_gradients):\n            grads = []\n            for g, _ in grad_and_vars:\n                expanded_g = tf.expand_dims(g, 0)\n                grads.append(expanded_g)\n            grad = tf.concat(grads, 0)\n            grad = tf.reduce_mean(grad, 0)\n            grad_and_var = (grad, grad_and_vars[0][1])\n            average_grads.append(grad_and_var)\n    return average_grads",
    "docstring": "r'''\n    A routine for computing each variable's average of the gradients obtained from the GPUs.\n    Note also that this code acts as a synchronization point as it requires all\n    GPUs to be finished with their mini-batch before it can run to completion."
  },
  {
    "code": "def get_historical_data(self, uuid, start, end, average_by=0):\n        return self.parse_data((yield from self._get(\n            HISTORICAL_DATA_URL.format(uuid= uuid,\n                start = trunc(start.replace(tzinfo=timezone.utc).timestamp()),\n                end = trunc(end.replace(tzinfo=timezone.utc).timestamp()),\n                average_by= trunc(average_by)))))",
    "docstring": "Get the data from one device for a specified time range.\n\n        .. note::\n            Can fetch a maximum of 42 days of data.\n            To speed up query processing, you can use a combination of average factor\n            multiple of 1H in seconds (e.g. 3600), and o'clock start and end times\n\n        :param uuid: Id of the device\n        :type uuid: str\n        :param start: start of the range\n        :type start: datetime\n        :param end: end of the range\n        :type end: datetime\n        :param average_by: amount of seconds to average data over.\n            0 or 300 for no average. Use 3600 (average hourly) or a multiple for\n            long range requests (e.g. more than 1 day)\n        :type average_by: integer\n        :returns: list of datapoints\n        :raises: ClientError, AuthFailure, BadFormat, ForbiddenAccess,\n                 TooManyRequests, InternalError\n\n        .. seealso:: :func:`parse_data` for return data syntax"
  },
  {
    "code": "def get_documents_count(self):\n        db_collections = [\n            self.database[c] for c in self.get_collection_names()\n        ]\n        return sum([c.count() for c in db_collections])",
    "docstring": "Counts documents in database\n\n        :return: Number of documents in db"
  },
  {
    "code": "def load_image(name, n, m=None, gpu=None, square=None):\n    if m is None:\n        m = n\n    if gpu is None:\n        gpu = 0\n    if square is None:\n        square = 0\n    command = ('Shearlab.load_image(\"{}\", {}, {}, {}, {})'.format(name,\n               n, m, gpu, square))\n    return j.eval(command)",
    "docstring": "Function to load images with certain size."
  },
  {
    "code": "def update(self, networkipv4s):\n        data = {'networks': networkipv4s}\n        networkipv4s_ids = [str(networkipv4.get('id'))\n                            for networkipv4 in networkipv4s]\n        return super(ApiNetworkIPv4, self).put('api/v3/networkv4/%s/' %\n                                               ';'.join(networkipv4s_ids), data)",
    "docstring": "Method to update network-ipv4's\n\n        :param networkipv4s: List containing network-ipv4's desired to updated\n        :return: None"
  },
  {
    "code": "def get_instance(self, payload):\n        return SyncListItemInstance(\n            self._version,\n            payload,\n            service_sid=self._solution['service_sid'],\n            list_sid=self._solution['list_sid'],\n        )",
    "docstring": "Build an instance of SyncListItemInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance\n        :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance"
  },
  {
    "code": "def isdicom(fn):\n    fn = str(fn)\n    if fn.endswith('.dcm'):\n        return True\n    with open(fn,'rb') as fh:\n        fh.seek(0x80)\n        return fh.read(4)==b'DICM'",
    "docstring": "True if the fn points to a DICOM image"
  },
  {
    "code": "def hypot(x, y, context=None):\n    return _apply_function_in_current_context(\n        BigFloat,\n        mpfr.mpfr_hypot,\n        (\n            BigFloat._implicit_convert(x),\n            BigFloat._implicit_convert(y),\n        ),\n        context,\n    )",
    "docstring": "Return the Euclidean norm of x and y, i.e., the square root of the sum of\n    the squares of x and y."
  },
  {
    "code": "def _consumers(self):\n        app_config = self.lti_kwargs['app'].config\n        config = app_config.get('PYLTI_CONFIG', dict())\n        consumers = config.get('consumers', dict())\n        return consumers",
    "docstring": "Gets consumer's map from app config\n\n        :return: consumers map"
  },
  {
    "code": "def clean(file_, imports):\n    modules_not_imported = compare_modules(file_, imports)\n    re_remove = re.compile(\"|\".join(modules_not_imported))\n    to_write = []\n    try:\n        f = open_func(file_, \"r+\")\n    except OSError:\n        logging.error(\"Failed on file: {}\".format(file_))\n        raise\n    else:\n        for i in f.readlines():\n            if re_remove.match(i) is None:\n                to_write.append(i)\n        f.seek(0)\n        f.truncate()\n        for i in to_write:\n            f.write(i)\n    finally:\n        f.close()\n    logging.info(\"Successfully cleaned up requirements in \" + file_)",
    "docstring": "Remove modules that aren't imported in project from file."
  },
  {
    "code": "def random_expr(depth, vlist, ops):\n  if not depth:\n    return str(vlist[random.randrange(len(vlist))])\n  max_depth_side = random.randrange(2)\n  other_side_depth = random.randrange(depth)\n  left = random_expr(depth - 1\n                     if max_depth_side else other_side_depth, vlist, ops)\n  right = random_expr(depth - 1\n                      if not max_depth_side else other_side_depth, vlist, ops)\n  op = ops[random.randrange(len(ops))]\n  return ExprNode(left, right, op)",
    "docstring": "Generate a random expression tree.\n\n  Args:\n    depth: At least one leaf will be this many levels down from the top.\n    vlist: A list of chars. These chars are randomly selected as leaf values.\n    ops: A list of ExprOp instances.\n\n  Returns:\n    An ExprNode instance which is the root of the generated expression tree."
  },
  {
    "code": "def getItalianAccentedVocal(vocal, acc_type=\"g\"):\n    vocals = {'a': {'g': u'\\xe0', 'a': u'\\xe1'},\n              'e': {'g': u'\\xe8', 'a': u'\\xe9'},\n              'i': {'g': u'\\xec', 'a': u'\\xed'},\n              'o': {'g': u'\\xf2', 'a': u'\\xf3'},\n              'u': {'g': u'\\xf9', 'a': u'\\xfa'}}\n    return vocals[vocal][acc_type]",
    "docstring": "It returns given vocal with grave or acute accent"
  },
  {
    "code": "def use_sequestered_composition_view(self):\n        self._containable_views['composition'] = SEQUESTERED\n        for session in self._get_provider_sessions():\n            try:\n                session.use_sequestered_composition_view()\n            except AttributeError:\n                pass",
    "docstring": "Pass through to provider CompositionLookupSession.use_sequestered_composition_view"
  },
  {
    "code": "def eventFilter(self, object, event):\n        if object == self.parent() and event.type() == QtCore.QEvent.Resize:\n            self.resize(event.size())\n        elif event.type() == QtCore.QEvent.Close:\n            self.setResult(0)\n        return False",
    "docstring": "Resizes this overlay as the widget resizes.\n\n        :param      object | <QtCore.QObject>\n                    event  | <QtCore.QEvent>\n\n        :return     <bool>"
  },
  {
    "code": "def version(self, api_version=True):\n        url = self._url(\"/version\", versioned_api=api_version)\n        return self._result(self._get(url), json=True)",
    "docstring": "Returns version information from the server. Similar to the ``docker\n        version`` command.\n\n        Returns:\n            (dict): The server version information\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def export_draco(mesh):\n    with tempfile.NamedTemporaryFile(suffix='.ply') as temp_ply:\n        temp_ply.write(export_ply(mesh))\n        temp_ply.flush()\n        with tempfile.NamedTemporaryFile(suffix='.drc') as encoded:\n            subprocess.check_output([draco_encoder,\n                                     '-qp',\n                                     '28',\n                                     '-i',\n                                     temp_ply.name,\n                                     '-o',\n                                     encoded.name])\n            encoded.seek(0)\n            data = encoded.read()\n    return data",
    "docstring": "Export a mesh using Google's Draco compressed format.\n\n    Only works if draco_encoder is in your PATH:\n    https://github.com/google/draco\n\n    Parameters\n    ----------\n    mesh : Trimesh object\n\n    Returns\n    ----------\n    data : str or bytes\n      DRC file bytes"
  },
  {
    "code": "def _format_credentials(self):\n        tenant_name = self.tenant_name or self.username\n        tenant_id = self.tenant_id or self.username\n        return {\"auth\": {\"passwordCredentials\":\n                {\"username\": tenant_name,\n                \"password\": self.password,\n                },\n                \"tenantId\": tenant_id}}",
    "docstring": "Returns the current credentials in the format expected by\n        the authentication service."
  },
  {
    "code": "def describe_api_models(restApiId, region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        models = _multi_call(conn.get_models, 'items', restApiId=restApiId)\n        return {'models': [_convert_datetime_str(model) for model in models]}\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Get all models for a given API\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_apigateway.describe_api_models restApiId"
  },
  {
    "code": "def remove_handler(self, name):\n        index = None\n        for i, h in enumerate(self.capture_handlers):\n            if h['name'] == name:\n                index = i\n        if index is not None:\n            self.capture_handlers[index]['logger'].close()\n            del self.capture_handlers[index]",
    "docstring": "Remove a handler given a name\n\n        Note, if multiple handlers have the same name the last matching\n        instance in the handler list will be removed.\n\n        Args:\n            name:\n                The name of the handler to remove"
  },
  {
    "code": "def inflate_context_tuple(ast_rootpath, root_env):\n  with util.LogTime('inflate_context_tuple'):\n    inflated = ast_rootpath[0].eval(root_env)\n    current = inflated\n    env = root_env\n    try:\n      for node in ast_rootpath[1:]:\n        if is_tuple_member_node(node):\n          assert framework.is_tuple(current)\n          with util.LogTime('into tuple'):\n            thunk, env = inflated.get_thunk_env(node.name)\n            current = framework.eval(thunk, env)\n        elif framework.is_list(current):\n          with util.LogTime('eval thing'):\n            current = framework.eval(node, env)\n        if framework.is_tuple(current):\n          inflated = current\n    except (gcl.EvaluationError, ast.UnparseableAccess):\n      pass\n    return inflated",
    "docstring": "Instantiate a Tuple from a TupleNode.\n\n  Walking the AST tree upwards, evaluate from the root down again."
  },
  {
    "code": "def url_unescape(\n    value: Union[str, bytes], encoding: Optional[str] = \"utf-8\", plus: bool = True\n) -> Union[str, bytes]:\n    if encoding is None:\n        if plus:\n            value = to_basestring(value).replace(\"+\", \" \")\n        return urllib.parse.unquote_to_bytes(value)\n    else:\n        unquote = urllib.parse.unquote_plus if plus else urllib.parse.unquote\n        return unquote(to_basestring(value), encoding=encoding)",
    "docstring": "Decodes the given value from a URL.\n\n    The argument may be either a byte or unicode string.\n\n    If encoding is None, the result will be a byte string.  Otherwise,\n    the result is a unicode string in the specified encoding.\n\n    If ``plus`` is true (the default), plus signs will be interpreted\n    as spaces (literal plus signs must be represented as \"%2B\").  This\n    is appropriate for query strings and form-encoded values but not\n    for the path component of a URL.  Note that this default is the\n    reverse of Python's urllib module.\n\n    .. versionadded:: 3.1\n       The ``plus`` argument"
  },
  {
    "code": "def _get_sorted(self, resources):\n        tmp = []\n        for resource in resources:\n            path = resource._path\n            priority = path.count('/') * 10 - path.count('{')\n            tmp.append((priority, resource))\n        return [resource for prio, resource in reversed(sorted(tmp))]",
    "docstring": "Order the resources by priority - the most specific paths come\n        first.\n\n        :param resources: List of :class:`wsgiservice.resource.Resource`\n                          classes to be served by this application."
  },
  {
    "code": "def execute_template(self, template_name, variables, args=None):\n        js_text = self.build_js_from_template(template_name, variables)\n        try:\n            self.execute_script(js_text, args)\n        except WebDriverException:\n            return False\n        return True",
    "docstring": "Execute script from a template\n\n        @type template_name:    str\n        @value template_name:   Script template to implement\n        @type args:             dict\n        @value args:            Dictionary representing command line args\n\n        @rtype:                 bool\n        @rtype:                 Success or failure"
  },
  {
    "code": "def _parallel_downloader(voxforge_url, archive_dir, total, counter):\n    def download(d):\n        (i, file) = d\n        download_url = voxforge_url + '/' + file\n        c = counter.increment()\n        print('Downloading file {} ({}/{})...'.format(i+1, c, total))\n        maybe_download(filename_of(download_url), archive_dir, download_url)\n    return download",
    "docstring": "Generate a function to download a file based on given parameters\n    This works by currying the above given arguments into a closure\n    in the form of the following function.\n\n    :param voxforge_url: the base voxforge URL\n    :param archive_dir:  the location to store the downloaded file\n    :param total:        the total number of files to download\n    :param counter:      an atomic counter to keep track of # of downloaded files\n    :return:             a function that actually downloads a file given these params"
  },
  {
    "code": "def dimensions(self, dims):\n        nx, ny, nz = dims[0], dims[1], dims[2]\n        self.SetDimensions(nx, ny, nz)\n        self.Modified()",
    "docstring": "Sets the dataset dimensions. Pass a length three tuple of integers"
  },
  {
    "code": "def mkdir(dirname):\n    dir_list = []\n    while not client.isdir(dirname):\n        dir_list.append(dirname)\n        dirname = os.path.dirname(dirname)\n    while len(dir_list) > 0:\n        logging.info(\"Creating directory: %s\" % (dir_list[-1]))\n        try:\n            client.mkdir(dir_list.pop())\n        except IOError as e:\n            if e.errno == errno.EEXIST:\n                pass\n            else:\n                raise e",
    "docstring": "make directory tree in vospace.\n\n    @param dirname: name of the directory to make"
  },
  {
    "code": "def get_outcome(self, outcome):\n        from canvasapi.outcome import Outcome\n        outcome_id = obj_or_id(outcome, \"outcome\", (Outcome,))\n        response = self.__requester.request(\n            'GET',\n            'outcomes/{}'.format(outcome_id)\n        )\n        return Outcome(self.__requester, response.json())",
    "docstring": "Returns the details of the outcome with the given id.\n\n        :calls: `GET /api/v1/outcomes/:id \\\n        <https://canvas.instructure.com/doc/api/outcomes.html#method.outcomes_api.show>`_\n\n        :param outcome: The outcome object or ID to return.\n        :type outcome: :class:`canvasapi.outcome.Outcome` or int\n\n        :returns: An Outcome object.\n        :rtype: :class:`canvasapi.outcome.Outcome`"
  },
  {
    "code": "def tree_to_xml(self):\n        self.filter_remove(remember=True)\n        tree = self.treeview\n        root = ET.Element('interface')\n        items = tree.get_children()\n        for item in items:\n            node = self.tree_node_to_xml('', item)\n            root.append(node)\n        self.filter_restore()\n        return ET.ElementTree(root)",
    "docstring": "Traverses treeview and generates a ElementTree object"
  },
  {
    "code": "def getall(self, key, default=_marker):\n        identity = self._title(key)\n        res = [v for i, k, v in self._impl._items if i == identity]\n        if res:\n            return res\n        if not res and default is not _marker:\n            return default\n        raise KeyError('Key not found: %r' % key)",
    "docstring": "Return a list of all values matching the key."
  },
  {
    "code": "def get_item_ids_for_assessment_part(self, assessment_part_id):\n        item_ids = []\n        for question_map in self._my_map['questions']:\n            if question_map['assessmentPartId'] == str(assessment_part_id):\n                item_ids.append(Id(question_map['itemId']))\n        return item_ids",
    "docstring": "convenience method returns item ids associated with an assessment_part_id"
  },
  {
    "code": "def get_edit_url_link(self, text=None, cls=None, icon_class=None,\n                          **attrs):\n        if text is None:\n            text = 'Edit'\n        return build_link(href=self.get_edit_url(),\n                          text=text,\n                          cls=cls,\n                          icon_class=icon_class,\n                          **attrs)",
    "docstring": "Gets the html edit link for the object."
  },
  {
    "code": "def external2internal(xe, bounds):\n    xi = np.empty_like(xe)\n    for i, (v, bound) in enumerate(zip(xe, bounds)):\n        a = bound[0]\n        b = bound[1]\n        if a == None and b == None:\n            xi[i] = v\n        elif b == None:\n            xi[i] = np.sqrt((v - a + 1.) ** 2. - 1)\n        elif a == None:\n            xi[i] = np.sqrt((b - v + 1.) ** 2. - 1)\n        else:\n            xi[i] = np.arcsin((2. * (v - a) / (b - a)) - 1.)\n    return xi",
    "docstring": "Convert a series of external variables to internal variables"
  },
  {
    "code": "def unset(self, key):\n        params = {\n            'key': key\n        }\n        return self.client.delete(self._url(), params=params)",
    "docstring": "Removes the rules config for a given key.\n\n        Args:\n            key (str): rules config key to remove\n\n        See: https://auth0.com/docs/api/management/v2#!/Rules_Configs/delete_rules_configs_by_key"
  },
  {
    "code": "def credentials(self, area_uuid):\n        response = self._make_request(\"post\", path=\"/area/{uuid}/credentials\".format(uuid=area_uuid))\n        return response.json()",
    "docstring": "Get AWS credentials required to directly upload files to Upload Area in S3\n\n        :param str area_uuid: A RFC4122-compliant ID for the upload area\n        :return: a dict containing an AWS AccessKey, SecretKey and SessionToken\n        :rtype: dict\n        :raises UploadApiException: if credentials could not be obtained"
  },
  {
    "code": "def OnPaste(self, event):\n        data = self.main_window.clipboard.get_clipboard()\n        focus = self.main_window.FindFocus()\n        if isinstance(focus, wx.TextCtrl):\n            focus.WriteText(data)\n        else:\n            key = self.main_window.grid.actions.cursor\n            with undo.group(_(\"Paste\")):\n                self.main_window.actions.paste(key, data)\n        self.main_window.grid.ForceRefresh()\n        event.Skip()",
    "docstring": "Clipboard paste event handler"
  },
  {
    "code": "def get_service_address(\n            self,\n            block_identifier: BlockSpecification,\n            index: int,\n    ) -> Optional[AddressHex]:\n        try:\n            result = self.proxy.contract.functions.service_addresses(index).call(\n                block_identifier=block_identifier,\n            )\n        except web3.exceptions.BadFunctionCallOutput:\n            result = None\n        return result",
    "docstring": "Gets the address of a service by index. If index is out of range return None"
  },
  {
    "code": "def update_dependency_kinds(apps, schema_editor):\n    DataDependency = apps.get_model('flow', 'DataDependency')\n    for dependency in DataDependency.objects.all():\n        dependency.kind = 'subprocess'\n        child = dependency.child\n        parent = dependency.parent\n        for field_schema, fields in iterate_fields(child.input, child.process.input_schema):\n            name = field_schema['name']\n            value = fields[name]\n            if field_schema.get('type', '').startswith('data:'):\n                if value == parent.pk:\n                    dependency.kind = 'io'\n                    break\n            elif field_schema.get('type', '').startswith('list:data:'):\n                for data in value:\n                    if value == parent.pk:\n                        dependency.kind = 'io'\n                        break\n        dependency.save()",
    "docstring": "Update historical dependency kinds as they may be wrong."
  },
  {
    "code": "def crps_climo(self):\n        o_bar = self.errors[\"O\"].values / float(self.num_forecasts)\n        crps_c = np.sum(self.num_forecasts * (o_bar ** 2) - o_bar * self.errors[\"O\"].values * 2.0 +\n                        self.errors[\"O_2\"].values) / float(self.thresholds.size * self.num_forecasts)\n        return crps_c",
    "docstring": "Calculate the climatological CRPS."
  },
  {
    "code": "def order_by(self, field, orientation='ASC'):\n        if isinstance(field, list):\n            self.raw_order_by.append(field)\n        else:\n            self.raw_order_by.append([field, orientation])\n        return self",
    "docstring": "Indica los campos y el criterio de ordenamiento"
  },
  {
    "code": "def pathName(self, pathName: str):\n        if self.pathName == pathName:\n            return\n        pathName = self.sanitise(pathName)\n        before = self.realPath\n        after = self._realPath(pathName)\n        assert (not os.path.exists(after))\n        newRealDir = os.path.dirname(after)\n        if not os.path.exists(newRealDir):\n            os.makedirs(newRealDir, DirSettings.defaultDirChmod)\n        shutil.move(before, after)\n        oldPathName = self._pathName\n        self._pathName = pathName\n        self._directory()._fileMoved(oldPathName, self)",
    "docstring": "Path Name Setter\n\n        Set path name with passed in variable, create new directory and move\n        previous directory contents to new path name.\n\n        @param pathName: New path name string.\n        @type pathName: String"
  },
  {
    "code": "def run(self, reporter=None):\r\n        if not reporter: reporter = ConsoleReporter()\r\n        benchmarks = sorted(self._find_benchmarks())\r\n        reporter.write_titles(map(self._function_name_to_title, benchmarks))\r\n        for value in self.input():\r\n            results = []\r\n            for b in benchmarks:\r\n                method = getattr(self, b)\r\n                arg_count = len(inspect.getargspec(method)[0])\r\n                if arg_count == 2:\r\n                    results.append(self._run_benchmark(method, value))\r\n                elif arg_count == 1:\r\n                    results.append(self._run_benchmark(method))\r\n            reporter.write_results(str(value), results)",
    "docstring": "This should generally not be overloaded.  Runs the benchmark functions\r\n        that are found in the child class."
  },
  {
    "code": "def refuse_transfer(transfer, comment=None):\n    TransferResponsePermission(transfer).test()\n    transfer.responded = datetime.now()\n    transfer.responder = current_user._get_current_object()\n    transfer.status = 'refused'\n    transfer.response_comment = comment\n    transfer.save()\n    return transfer",
    "docstring": "Refuse an incoming a transfer request"
  },
  {
    "code": "def _qteGetLabelInstance(self):\n        layout = self.layout()\n        label = QtGui.QLabel(self)\n        style = 'QLabel { background-color : white; color : blue; }'\n        label.setStyleSheet(style)\n        return label",
    "docstring": "Return an instance of a ``QLabel`` with the correct color scheme.\n\n        |Args|\n\n        * **None**\n\n        |Returns|\n\n        * **QLabel**\n\n        |Raises|\n\n        * **None**"
  },
  {
    "code": "def get_answers(self):\n        return AnswerList(\n            self._my_map['answers'],\n            runtime=self._runtime,\n            proxy=self._proxy)",
    "docstring": "Gets the answers.\n\n        return: (osid.assessment.AnswerList) - the answers\n        raise:  OperationFailed - unable to complete request\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):\n        sender = '\"%s\" <%s>' % (sender_name, sender_email) if sender_name else sender_email\n        if not current_app.testing:\n            try:\n                from flask_mail import Message\n                message = Message(\n                    subject,\n                    sender=sender,\n                    recipients=[recipient],\n                    html=html_message,\n                    body=text_message)\n                self.mail.send(message)\n            except (socket.gaierror, socket.error) as e:\n                raise EmailError('SMTP Connection error: Check your MAIL_SERVER and MAIL_PORT settings.')\n            except smtplib.SMTPAuthenticationError:\n                raise EmailError('SMTP Authentication error: Check your MAIL_USERNAME and MAIL_PASSWORD settings.')",
    "docstring": "Send email message via Flask-Mail.\n\n        Args:\n            recipient: Email address or tuple of (Name, Email-address).\n            subject: Subject line.\n            html_message: The message body in HTML.\n            text_message: The message body in plain text."
  },
  {
    "code": "def _format_alignment(self, a1, a2):\n        html = []\n        for index, char in enumerate(a1):\n            output = self._substitutes.get(char, char)\n            if a2[index] == char:\n                html.append('<span class=\"match\">{}</span>'.format(output))\n            elif char != '-':\n                html.append(output)\n        return ''.join(html)",
    "docstring": "Returns `a1` marked up with HTML spans around characters that are\n        also at the same index in `a2`.\n\n        :param a1: text sequence from one witness\n        :type a1: `str`\n        :param a2: text sequence from another witness\n        :type a2: `str`\n        :rtype: `str`"
  },
  {
    "code": "def launch(self, resource):\n        schema = JobSchema(exclude=('id', 'status', 'package_name', 'config_name', 'device_name', 'result_id', 'user_id', 'created', 'updated', 'automatic'))\n        json = self.service.encode(schema, resource)\n        schema = JobSchema()\n        resp = self.service.create(self.base, json)\n        return self.service.decode(schema, resp)",
    "docstring": "Launch a new job.\n\n        :param resource: :class:`jobs.Job <jobs.Job>` object\n        :return: :class:`jobs.Job <jobs.Job>` object\n        :rtype: jobs.Job"
  },
  {
    "code": "def normalize(self):\n        cm = self.centerOfMass()\n        coords = self.coordinates()\n        if not len(coords):\n            return\n        pts = coords - cm\n        xyz2 = np.sum(pts * pts, axis=0)\n        scale = 1 / np.sqrt(np.sum(xyz2) / len(pts))\n        t = vtk.vtkTransform()\n        t.Scale(scale, scale, scale)\n        t.Translate(-cm)\n        tf = vtk.vtkTransformPolyDataFilter()\n        tf.SetInputData(self.poly)\n        tf.SetTransform(t)\n        tf.Update()\n        return self.updateMesh(tf.GetOutput())",
    "docstring": "Shift actor's center of mass at origin and scale its average size to unit."
  },
  {
    "code": "def get_next_repository(self):\n        try:\n            next_object = next(self)\n        except StopIteration:\n            raise IllegalState('no more elements available in this list')\n        except Exception:\n            raise OperationFailed()\n        else:\n            return next_object",
    "docstring": "Gets the next ``Repository`` in this list.\n\n        :return: the next ``Repository`` in this list. The ``has_next()`` method should be used to test that a next ``Repository`` is available before calling this method.\n        :rtype: ``osid.repository.Repository``\n        :raise: ``IllegalState`` -- no more elements available in this list\n        :raise: ``OperationFailed`` -- unable to complete request\n\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def reduceByKeyLocally(self, func):\n        func = fail_on_stopiteration(func)\n        def reducePartition(iterator):\n            m = {}\n            for k, v in iterator:\n                m[k] = func(m[k], v) if k in m else v\n            yield m\n        def mergeMaps(m1, m2):\n            for k, v in m2.items():\n                m1[k] = func(m1[k], v) if k in m1 else v\n            return m1\n        return self.mapPartitions(reducePartition).reduce(mergeMaps)",
    "docstring": "Merge the values for each key using an associative and commutative reduce function, but\n        return the results immediately to the master as a dictionary.\n\n        This will also perform the merging locally on each mapper before\n        sending results to a reducer, similarly to a \"combiner\" in MapReduce.\n\n        >>> from operator import add\n        >>> rdd = sc.parallelize([(\"a\", 1), (\"b\", 1), (\"a\", 1)])\n        >>> sorted(rdd.reduceByKeyLocally(add).items())\n        [('a', 2), ('b', 1)]"
  },
  {
    "code": "def getPassagePlus(self, reference=None):\n        if reference:\n            urn = \"{0}:{1}\".format(self.urn, reference)\n        else:\n            urn = str(self.urn)\n        response = xmlparser(self.retriever.getPassagePlus(urn=urn))\n        passage = CtsPassage(urn=urn, resource=response, retriever=self.retriever)\n        passage._parse_request(response.xpath(\"//ti:reply/ti:label\", namespaces=XPATH_NAMESPACES)[0])\n        self.citation = passage.citation\n        return passage",
    "docstring": "Retrieve a passage and informations around it and store it in the object\n\n        :param reference: Reference of the passage\n        :type reference: CtsReference or List of text_type\n        :rtype: CtsPassage\n        :returns: Object representing the passage\n        :raises: *TypeError* when reference is not a list or a Reference"
  },
  {
    "code": "def resolve_context(self):\n        merged = dict()\n        for context in self.located_context.values():\n            merged.update(context)\n        return merged",
    "docstring": "Create a new dictionary that corresponds to the union of all of the\n        contexts that have been entered but not exited at this point."
  },
  {
    "code": "def initialise_logging(level: str, target: str, short_format: bool):\n    try:\n        log_level = getattr(logging, level)\n    except AttributeError:\n        raise SystemExit(\n            \"invalid log level %r, expected any of 'DEBUG', 'INFO', 'WARNING', 'ERROR' or 'CRITICAL'\" % level\n        )\n    handler = create_handler(target=target)\n    logging.basicConfig(\n        level=log_level,\n        format='%(asctime)-15s (%(process)d) %(message)s' if not short_format else '%(message)s',\n        datefmt='%Y-%m-%d %H:%M:%S',\n        handlers=[handler]\n    )",
    "docstring": "Initialise basic logging facilities"
  },
  {
    "code": "def _list_interface_private_addrs(eni_desc):\n    primary = eni_desc.get('privateIpAddress')\n    if not primary:\n        return None\n    addresses = [primary]\n    lst = eni_desc.get('privateIpAddressesSet', {}).get('item', [])\n    if not isinstance(lst, list):\n        return addresses\n    for entry in lst:\n        if entry.get('primary') == 'true':\n            continue\n        if entry.get('privateIpAddress'):\n            addresses.append(entry.get('privateIpAddress'))\n    return addresses",
    "docstring": "Returns a list of all of the private IP addresses attached to a\n    network interface. The 'primary' address will be listed first."
  },
  {
    "code": "def acceptText(self):\r\n        if not self.signalsBlocked():\r\n            self.textEntered.emit(self.toPlainText())\r\n            self.htmlEntered.emit(self.toHtml())\r\n            self.returnPressed.emit()",
    "docstring": "Emits the editing finished signals for this widget."
  },
  {
    "code": "def process(self, line):\n        self.raw = self.raw + line\n        try:\n            if not line[-1] == self.eol_char:\n                line = line + self.eol_char\n        except IndexError:\n            line = self.eol_char\n        for char in line:\n            if char == self.escape_char:\n                self.last_process_char = self.process_char\n                self.process_char = self.process_escape\n                continue\n            self.process_char(char)\n        if not self.complete:\n            self.process( self.handler.readline(prompt=self.handler.CONTINUE_PROMPT) )",
    "docstring": "Step through the line and process each character"
  },
  {
    "code": "def get_var_dict_from_ctx(ctx: commands.Context, prefix: str = '_'):\n    raw_var_dict = {\n        'author': ctx.author,\n        'bot': ctx.bot,\n        'channel': ctx.channel,\n        'ctx': ctx,\n        'find': discord.utils.find,\n        'get': discord.utils.get,\n        'guild': ctx.guild,\n        'message': ctx.message,\n        'msg': ctx.message\n    }\n    return {f'{prefix}{k}': v for k, v in raw_var_dict.items()}",
    "docstring": "Returns the dict to be used in REPL for a given Context."
  },
  {
    "code": "def pole(conic, plane):\n        v = dot(N.linalg.inv(conic),plane)\n        return v[:-1]/v[-1]",
    "docstring": "Calculates the pole of a polar plane for\n        a given conic section."
  },
  {
    "code": "def create(cls, selective: typing.Optional[base.Boolean] = None):\n        return cls(selective=selective)",
    "docstring": "Create new force reply\n\n        :param selective:\n        :return:"
  },
  {
    "code": "def register_postcmd_hook(self, func: Callable[[plugin.PostcommandData], plugin.PostcommandData]) -> None:\n        self._validate_prepostcmd_hook(func, plugin.PostcommandData)\n        self._postcmd_hooks.append(func)",
    "docstring": "Register a hook to be called after the command function."
  },
  {
    "code": "def search_subscriptions(self, **kwargs):\n        params = [(key, kwargs[key]) for key in sorted(kwargs.keys())]\n        url = \"/notification/v1/subscription?{}\".format(\n            urlencode(params, doseq=True))\n        response = NWS_DAO().getURL(url, self._read_headers)\n        if response.status != 200:\n            raise DataFailureException(url, response.status, response.data)\n        data = json.loads(response.data)\n        subscriptions = []\n        for datum in data.get(\"Subscriptions\", []):\n            subscriptions.append(self._subscription_from_json(datum))\n        return subscriptions",
    "docstring": "Search for all subscriptions by parameters"
  },
  {
    "code": "def _check_curtailment_target(curtailment, curtailment_target,\n                              curtailment_key):\n    if not (abs(curtailment.sum(axis=1) - curtailment_target) < 1e-1).all():\n        message = 'Curtailment target not met for {}.'.format(curtailment_key)\n        logging.error(message)\n        raise TypeError(message)",
    "docstring": "Raises an error if curtailment target was not met in any time step.\n\n    Parameters\n    -----------\n    curtailment : :pandas:`pandas:DataFrame<dataframe>`\n        Dataframe containing the curtailment in kW per generator and time step.\n        Index is a :pandas:`pandas.DatetimeIndex<datetimeindex>`, columns are\n        the generator representatives.\n    curtailment_target : :pandas:`pandas.Series<series>`\n        The curtailment in kW that was to be distributed amongst the\n        generators. Index of the series is a\n        :pandas:`pandas.DatetimeIndex<datetimeindex>`.\n    curtailment_key : :obj:`str` or :obj:`tuple` with :obj:`str`\n        The technology and weather cell ID if :obj:`tuple` or only\n        the technology if :obj:`str` the curtailment was specified for."
  },
  {
    "code": "def generateCatalog(wcs, mode='automatic', catalog=None,\n                    src_find_filters=None, **kwargs):\n    if not isinstance(catalog,Catalog):\n        if mode == 'automatic':\n            catalog = ImageCatalog(wcs,catalog,src_find_filters,**kwargs)\n        else:\n            catalog = UserCatalog(wcs,catalog,**kwargs)\n    return catalog",
    "docstring": "Function which determines what type of catalog object needs to be\n    instantiated based on what type of source selection algorithm the user\n    specified.\n\n    Parameters\n    ----------\n    wcs : obj\n        WCS object generated by STWCS or PyWCS\n\n    catalog : str or ndarray\n        Filename of existing catalog or ndarray of image for generation of\n        source catalog.\n\n    kwargs : dict\n        Parameters needed to interpret source catalog from input catalog\n        with `findmode` being required.\n\n    Returns\n    -------\n    catalog : obj\n        A Catalog-based class instance for keeping track of WCS and\n        associated source catalog"
  },
  {
    "code": "def is_published(self):\n        citeable = 'publication_info' in self.record and \\\n            is_citeable(self.record['publication_info'])\n        submitted = 'dois' in self.record and any(\n            'journal_title' in el for el in\n            force_list(self.record.get('publication_info'))\n        )\n        return citeable or submitted",
    "docstring": "Return True if a record is published.\n\n        We say that a record is published if it is citeable, which means that\n        it has enough information in a ``publication_info``, or if we know its\n        DOI and a ``journal_title``, which means it is in press.\n\n        Returns:\n            bool: whether the record is published.\n\n        Examples:\n            >>> record = {\n            ...     'dois': [\n            ...         {'value': '10.1016/0029-5582(61)90469-2'},\n            ...     ],\n            ...     'publication_info': [\n            ...         {'journal_title': 'Nucl.Phys.'},\n            ...     ],\n            ... }\n            >>> LiteratureReader(record).is_published\n            True"
  },
  {
    "code": "def assert_not_in(self, actual_collection_or_string, unexpected_value,\n                      failure_message='Expected \"{1}\" not to be in \"{0}\"'):\n        assertion = lambda: unexpected_value not in actual_collection_or_string\n        self.webdriver_assert(assertion, unicode(failure_message).format(actual_collection_or_string, unexpected_value))",
    "docstring": "Calls smart_assert, but creates its own assertion closure using\n        the expected and provided values with the 'not in' operator"
  },
  {
    "code": "def get_services(self):\n        result = []\n        nodes = self.root.iterfind(\n            './/ns:service', namespaces={'ns': self.namespace})\n        for node in nodes:\n            result.append(FritzService(\n                node.find(self.nodename('serviceType')).text,\n                node.find(self.nodename('controlURL')).text,\n                node.find(self.nodename('SCPDURL')).text))\n        return result",
    "docstring": "Returns a list of FritzService-objects."
  },
  {
    "code": "def standings(self):\n        headers = {\"Content-type\": \"application/x-www-form-urlencoded\",\"Accept\": \"text/plain\",\"User-Agent\": user_agent}\n        req = self.session.get('http://'+self.domain+'/standings.phtml',headers=headers).content\n        soup = BeautifulSoup(req)\n        table = soup.find('table',{'id':'tablestandings'}).find_all('tr')\n        clasificacion = []\n        [clasificacion.append(('%s\\t%s\\t%s\\t%s\\t%s')%(tablas.find('td').text,tablas.find('div')['id'],tablas.a.text,tablas.find_all('td')[3].text,tablas.find_all('td')[4].text)) for tablas in table[1:]]\n        return clasificacion",
    "docstring": "Get standings from the community's account"
  },
  {
    "code": "def add_comment(self, text):\n        response = self.reddit_session._add_comment(self.fullname, text)\n        self.reddit_session.evict(self._api_link)\n        return response",
    "docstring": "Comment on the submission using the specified text.\n\n        :returns: A Comment object for the newly created comment."
  },
  {
    "code": "def page_index(request):\n    letters = {}\n    for page in Page.query.order_by(Page.name):\n        letters.setdefault(page.name.capitalize()[0], []).append(page)\n    return Response(\n        generate_template(\"page_index.html\", letters=sorted(letters.items()))\n    )",
    "docstring": "Index of all pages."
  },
  {
    "code": "def delete_file_system(filesystemid,\n                       keyid=None,\n                       key=None,\n                       profile=None,\n                       region=None,\n                       **kwargs):\n    client = _get_conn(key=key, keyid=keyid, profile=profile, region=region)\n    client.delete_file_system(FileSystemId=filesystemid)",
    "docstring": "Deletes a file system, permanently severing access to its contents.\n    Upon return, the file system no longer exists and you can't access\n    any contents of the deleted file system. You can't delete a file system\n    that is in use. That is, if the file system has any mount targets,\n    you must first delete them.\n\n    filesystemid\n        (string) - ID of the file system to delete.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'my-minion' boto_efs.delete_file_system filesystemid"
  },
  {
    "code": "def visit_binop(self, node, parent):\n        newnode = nodes.BinOp(\n            self._bin_op_classes[type(node.op)], node.lineno, node.col_offset, parent\n        )\n        newnode.postinit(\n            self.visit(node.left, newnode), self.visit(node.right, newnode)\n        )\n        return newnode",
    "docstring": "visit a BinOp node by returning a fresh instance of it"
  },
  {
    "code": "def absolute(self):\n        if self.is_absolute():\n            return self\n        obj = self._from_parts([os.getcwd()] + self._parts, init=False)\n        obj._init(template=self)\n        return obj",
    "docstring": "Return an absolute version of this path.  This function works\n        even if the path doesn't point to anything.\n\n        No normalization is done, i.e. all '.' and '..' will be kept along.\n        Use resolve() to get the canonical path to a file."
  },
  {
    "code": "def copy(self):\n        return self.__class__(self.tag, self.data.copy(), self.context.copy())",
    "docstring": "Make a new instance of this Token.\n\n        This method makes a copy of the mutable part of the token before\n        making the instance."
  },
  {
    "code": "def facts(puppet=False):\n    ret = {}\n    opt_puppet = '--puppet' if puppet else ''\n    cmd_ret = __salt__['cmd.run_all']('facter {0}'.format(opt_puppet))\n    if cmd_ret['retcode'] != 0:\n        raise CommandExecutionError(cmd_ret['stderr'])\n    output = cmd_ret['stdout']\n    for line in output.splitlines():\n        if not line:\n            continue\n        fact, value = _format_fact(line)\n        if not fact:\n            continue\n        ret[fact] = value\n    return ret",
    "docstring": "Run facter and return the results\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' puppet.facts"
  },
  {
    "code": "def _message_to_payload(cls, message):\n        try:\n            return json.loads(message.decode())\n        except UnicodeDecodeError:\n            message = 'messages must be encoded in UTF-8'\n        except json.JSONDecodeError:\n            message = 'invalid JSON'\n        raise cls._error(cls.PARSE_ERROR, message, True, None)",
    "docstring": "Returns a Python object or a ProtocolError."
  },
  {
    "code": "def onerror(self, message, source, lineno, colno):\n        return (message, source, lineno, colno)",
    "docstring": "Called when an error occurs."
  },
  {
    "code": "def package_regex_filter(config, message, pattern=None, *args, **kw):\n    pattern = kw.get('pattern', pattern)\n    if pattern:\n        packages = fmn.rules.utils.msg2packages(message, **config)\n        regex = fmn.rules.utils.compile_regex(pattern.encode('utf-8'))\n        return any([regex.search(p.encode('utf-8')) for p in packages])",
    "docstring": "All packages matching a regular expression\n\n    Use this rule to include messages that relate to packages that match\n    particular regular expressions\n    (*i.e., (maven|javapackages-tools|maven-surefire)*)."
  },
  {
    "code": "def requires_open_handle(method):\n  @functools.wraps(method)\n  def wrapper_requiring_open_handle(self, *args, **kwargs):\n    if self.is_closed():\n      raise usb_exceptions.HandleClosedError()\n    return method(self, *args, **kwargs)\n  return wrapper_requiring_open_handle",
    "docstring": "Decorator to ensure a handle is open for certain methods.\n\n  Subclasses should decorate their Read() and Write() with this rather than\n  checking their own internal state, keeping all \"is this handle open\" logic\n  in is_closed().\n\n  Args:\n    method: A class method on a subclass of UsbHandle\n\n  Raises:\n    HandleClosedError: If this handle has been closed.\n\n  Returns:\n    A wrapper around method that ensures the handle is open before calling through\n  to the wrapped method."
  },
  {
    "code": "def configure_logger(self, tc_config_log_filename=None, tc_output_log_filename=None):\n        config_log_filename = DriverWrappersPool.get_configured_value('Config_log_filename', tc_config_log_filename,\n                                                                      'logging.conf')\n        config_log_filename = os.path.join(DriverWrappersPool.config_directory, config_log_filename)\n        if self.config_log_filename != config_log_filename:\n            output_log_filename = DriverWrappersPool.get_configured_value('Output_log_filename', tc_output_log_filename,\n                                                                          'toolium.log')\n            output_log_filename = os.path.join(DriverWrappersPool.output_directory, output_log_filename)\n            output_log_filename = output_log_filename.replace('\\\\', '\\\\\\\\')\n            try:\n                logging.config.fileConfig(config_log_filename, {'logfilename': output_log_filename}, False)\n            except Exception as exc:\n                print(\"[WARN] Error reading logging config file '{}': {}\".format(config_log_filename, exc))\n            self.config_log_filename = config_log_filename\n            self.output_log_filename = output_log_filename\n            self.logger = logging.getLogger(__name__)",
    "docstring": "Configure selenium instance logger\n\n        :param tc_config_log_filename: test case specific logging config file\n        :param tc_output_log_filename: test case specific output logger file"
  },
  {
    "code": "def num_frames(self, num_samples):\n        return math.ceil(float(max(num_samples - self.frame_size, 0)) / float(self.hop_size)) + 1",
    "docstring": "Return the number of frames that will be used for a signal with the length of ``num_samples``."
  },
  {
    "code": "def request(self, msgtype, msgid, method, params=[]):\n        result = None\n        error = None\n        exception = None\n        try:\n            result = self.dispatch.call(method, params)\n        except Exception as e:\n            error = (e.__class__.__name__, str(e))\n            exception = e\n        if isinstance(result, Deferred):\n            result.add_callback(self._result, msgid)\n            result.add_errback(self._error, msgid)\n        else:\n            self.send_response(msgid, error, result)",
    "docstring": "Handle an incoming call request."
  },
  {
    "code": "def get_resource_mdata():\n    return {\n        'group': {\n            'element_label': {\n                'text': 'group',\n                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),\n                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),\n                'formatTypeId': str(DEFAULT_FORMAT_TYPE),\n            },\n            'instructions': {\n                'text': 'enter either true or false.',\n                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),\n                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),\n                'formatTypeId': str(DEFAULT_FORMAT_TYPE),\n            },\n            'required': False,\n            'read_only': False,\n            'linked': False,\n            'array': False,\n            'default_boolean_values': [None],\n            'syntax': 'BOOLEAN',\n        },\n        'avatar': {\n            'element_label': {\n                'text': 'avatar',\n                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),\n                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),\n                'formatTypeId': str(DEFAULT_FORMAT_TYPE),\n            },\n            'instructions': {\n                'text': 'accepts an osid.id.Id object',\n                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),\n                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),\n                'formatTypeId': str(DEFAULT_FORMAT_TYPE),\n            },\n            'required': False,\n            'read_only': False,\n            'linked': False,\n            'array': False,\n            'default_id_values': [''],\n            'syntax': 'ID',\n            'id_set': [],\n        },\n    }",
    "docstring": "Return default mdata map for Resource"
  },
  {
    "code": "def rating(self, value):\n        if not self.can_update():\n            self._tcex.handle_error(910, [self.type])\n        request_data = {'rating': value}\n        return self.tc_requests.update(\n            self.api_type, self.api_sub_type, self.unique_id, request_data, owner=self.owner\n        )",
    "docstring": "Updates the Indicators rating\n\n        Args:\n            value:"
  },
  {
    "code": "def _get_size(self):\n        if self._chan is None:\n            return Size(rows=20, columns=79)\n        else:\n            width, height, pixwidth, pixheight = self._chan.get_terminal_size()\n            return Size(rows=height, columns=width)",
    "docstring": "Callable that returns the current `Size`, required by Vt100_Output."
  },
  {
    "code": "def have(cmd):\n    try:\n        from shutil import which\n    except ImportError:\n        def which(cmd):\n            def _access_check(path):\n                return (os.path.exists(path) and os.access(\n                    path, os.F_OK | os.X_OK) and not os.path.isdir(path))\n            if os.path.dirname(cmd):\n                if _access_check(cmd):\n                    return cmd\n                return None\n            paths = os.environ.get('PATH', os.defpath.lstrip(':')).split(':')\n            seen = set()\n            for path in paths:\n                if path not in seen:\n                    seen.add(path)\n                    name = os.path.join(path, cmd)\n                    if _access_check(name):\n                        return name\n            return None\n    return which(cmd) is not None",
    "docstring": "Determine whether supplied argument is a command on the PATH."
  },
  {
    "code": "def _get_all_group_items(network_id):\n    base_qry = db.DBSession.query(ResourceGroupItem)\n    item_qry = base_qry.join(Scenario).filter(Scenario.network_id==network_id)\n    x = time.time()\n    logging.info(\"Getting all items\")\n    all_items = db.DBSession.execute(item_qry.statement).fetchall()\n    log.info(\"%s groups jointly retrieved in %s\", len(all_items), time.time()-x)\n    logging.info(\"items retrieved. Processing results...\")\n    x = time.time()\n    item_dict = dict()\n    for item in all_items:\n        items = item_dict.get(item.scenario_id, [])\n        items.append(item)\n        item_dict[item.scenario_id] = items\n    logging.info(\"items processed in %s\", time.time()-x)\n    return item_dict",
    "docstring": "Get all the resource group items in the network, across all scenarios\n        returns a dictionary of dict objects, keyed on scenario_id"
  },
  {
    "code": "def get_hash(input_string):\n    if os.path.islink(input_string):\n        directory, movie_hash = os.path.split(os.readlink(input_string))\n        input_string = movie_hash\n    return input_string.lower()",
    "docstring": "Return the hash of the movie depending on the input string.\n\n    If the input string looks like a symbolic link to a movie in a Kolekto\n    tree, return its movies hash, else, return the input directly in lowercase."
  },
  {
    "code": "def biopax_process_pc_pathsfromto():\n    if request.method == 'OPTIONS':\n        return {}\n    response = request.body.read().decode('utf-8')\n    body = json.loads(response)\n    source = body.get('source')\n    target = body.get('target')\n    bp = biopax.process_pc_pathsfromto(source, target)\n    return _stmts_from_proc(bp)",
    "docstring": "Process PathwayCommons paths from-to genes, return INDRA Statements."
  },
  {
    "code": "def set_wd_noise(self, wd_noise):\n        if isinstance(wd_noise, bool):\n            wd_noise = str(wd_noise)\n        if wd_noise.lower() == 'yes' or wd_noise.lower() == 'true':\n            wd_noise = 'True'\n        elif wd_noise.lower() == 'no' or wd_noise.lower() == 'false':\n            wd_noise = 'False'\n        elif wd_noise.lower() == 'both':\n            wd_noise = 'Both'\n        else:\n            raise ValueError('wd_noise must be yes, no, True, False, or Both.')\n        self.sensitivity_input.add_wd_noise = wd_noise\n        return",
    "docstring": "Add White Dwarf Background Noise\n\n        This adds the White Dwarf (WD) Background noise. This can either do calculations with,\n        without, or with and without WD noise.\n\n        Args:\n            wd_noise (bool or str, optional): Add or remove WD background noise. First option is to\n                have only calculations with the wd_noise. For this, use `yes` or True.\n                Second option is no WD noise. For this, use `no` or False. For both calculations\n                with and without WD noise, use `both`.\n\n        Raises:\n            ValueError: Input value is not one of the options."
  },
  {
    "code": "def _maintain_dep_graph(self, p_todo):\n        dep_id = p_todo.tag_value('id')\n        if dep_id:\n            self._parentdict[dep_id] = p_todo\n            self._depgraph.add_node(hash(p_todo))\n            for dep in \\\n                    [dep for dep in self._todos if dep.has_tag('p', dep_id)]:\n                self._add_edge(p_todo, dep, dep_id)\n        for dep_id in p_todo.tag_values('p'):\n            try:\n                parent = self._parentdict[dep_id]\n                self._add_edge(parent, p_todo, dep_id)\n            except KeyError:\n                pass",
    "docstring": "Makes sure that the dependency graph is consistent according to the\n        given todo."
  },
  {
    "code": "def od_reorder_keys(od, keys_in_new_order):\n    if set(od.keys()) != set(keys_in_new_order):\n        raise KeyError('Keys in the new order do not match existing keys')\n    for key in keys_in_new_order:\n        od[key] = od.pop(key)\n    return od",
    "docstring": "Reorder the keys in an OrderedDict ``od`` in-place."
  },
  {
    "code": "def generate(self, text):\n        if not text:\n            raise Exception(\"No text to speak\")\n        if len(text) >= self.MAX_CHARS:\n            raise Exception(\"Number of characters must be less than 2000\")\n        params = self.__params.copy()\n        params[\"text\"] = text\n        self._data = requests.get(self.TTS_URL, params=params,\n                                  stream=False).iter_content()",
    "docstring": "Try to get the generated file.\n\n        Args:\n            text: The text that you want to generate."
  },
  {
    "code": "def Gamma1_gasrad(beta):\n    Gamma3minus1 = (old_div(2.,3.))*(4.-3.*beta)/(8.-7.*beta) \n    Gamma1 = beta + (4.-3.*beta) * Gamma3minus1\n    return Gamma1",
    "docstring": "Gamma1 for a mix of ideal gas and radiation\n\n    Hansen & Kawaler, page 177, Eqn. 3.110\n    \n    Parameters\n    ----------\n    beta : float\n        Gas pressure fraction Pgas/(Pgas+Prad)"
  },
  {
    "code": "def _run_notty(self, writer):\n        page_idx = page_offset = 0\n        while True:\n            npage_idx, _ = self.draw(writer, page_idx + 1, page_offset)\n            if npage_idx == self.last_page:\n                break\n            page_idx = npage_idx\n            self.dirty = self.STATE_DIRTY\n        return",
    "docstring": "Pager run method for terminals that are not a tty."
  },
  {
    "code": "def setiddname(cls, iddname, testing=False):\n        if cls.iddname == None:\n            cls.iddname = iddname\n            cls.idd_info = None\n            cls.block = None\n        elif cls.iddname == iddname:\n            pass\n        else:\n            if testing == False:\n                errortxt = \"IDD file is set to: %s\" % (cls.iddname,)\n                raise IDDAlreadySetError(errortxt)",
    "docstring": "Set the path to the EnergyPlus IDD for the version of EnergyPlus which\n        is to be used by eppy.\n\n        Parameters\n        ----------\n        iddname : str\n            Path to the IDD file.\n        testing : bool\n            Flag to use if running tests since we may want to ignore the\n            `IDDAlreadySetError`.\n\n        Raises\n        ------\n        IDDAlreadySetError"
  },
  {
    "code": "def offset(self):\n        if not self._pages:\n            return None\n        pos = 0\n        for page in self._pages:\n            if page is None:\n                return None\n            if not page.is_final:\n                return None\n            if not pos:\n                pos = page.is_contiguous[0] + page.is_contiguous[1]\n                continue\n            if pos != page.is_contiguous[0]:\n                return None\n            pos += page.is_contiguous[1]\n        page = self._pages[0]\n        offset = page.is_contiguous[0]\n        if (page.is_imagej or page.is_shaped) and len(self._pages) == 1:\n            return offset\n        if pos == offset + product(self.shape) * self.dtype.itemsize:\n            return offset\n        return None",
    "docstring": "Return offset to series data in file, if any."
  },
  {
    "code": "def shutdown(self):\n        if not process.proc_alive(self.proc):\n            return\n        logger.info(\"Attempting to connect to %s\", self.hostname)\n        client = self.connection\n        attempts = 2\n        for i in range(attempts):\n            logger.info(\"Attempting to send shutdown command to %s\",\n                        self.hostname)\n            try:\n                client.admin.command(\"shutdown\", force=True)\n            except ConnectionFailure:\n                pass\n            try:\n                return process.wait_mprocess(self.proc, 5)\n            except TimeoutError as exc:\n                logger.info(\"Timed out waiting on process: %s\", exc)\n                continue\n        raise ServersError(\"Server %s failed to shutdown after %s attempts\" %\n                           (self.hostname, attempts))",
    "docstring": "Send shutdown command and wait for the process to exit."
  },
  {
    "code": "def run(self):\n        try:\n            import nose\n            arguments = [sys.argv[0]] + list(self.test_args)\n            return nose.run(argv=arguments)\n        except ImportError:\n            print()\n            print(\"*** Nose library missing. Please install it. ***\")\n            print()\n            raise",
    "docstring": "Runs the unit test framework. Can be overridden to run anything.\n        Returns True on passing and False on failure."
  },
  {
    "code": "def parse_modes(params, mode_types=None, prefixes=''):\n    params = list(params)\n    if params[0][0] not in '+-':\n        raise Exception('first param must start with + or -')\n    if mode_types is None:\n        mode_types = ['', '', '', '']\n    mode_string = params.pop(0)\n    args = params\n    assembled_modes = []\n    direction = mode_string[0]\n    for char in mode_string:\n        if char in '+-':\n            direction = char\n            continue\n        if (char in mode_types[0] or char in mode_types[1] or char in prefixes or\n                (char in mode_types[2] and direction == '+') and len(args)):\n            value = args.pop(0)\n        else:\n            value = None\n        assembled_modes.append([direction, char, value])\n    return assembled_modes",
    "docstring": "Return a modelist.\n\n    Args:\n        params (list of str): Parameters from MODE event.\n        mode_types (list): CHANMODES-like mode types.\n        prefixes (str): PREFIX-like mode types."
  },
  {
    "code": "def timecall(fn=None, immediate=True, timer=time.time):\n    if fn is None:\n        def decorator(fn):\n            return timecall(fn, immediate=immediate, timer=timer)\n        return decorator\n    fp = FuncTimer(fn, immediate=immediate, timer=timer)\n    def new_fn(*args, **kw):\n        return fp(*args, **kw)\n    new_fn.__doc__ = fn.__doc__\n    new_fn.__name__ = fn.__name__\n    new_fn.__dict__ = fn.__dict__\n    new_fn.__module__ = fn.__module__\n    return new_fn",
    "docstring": "Wrap `fn` and print its execution time.\n\n    Example::\n\n        @timecall\n        def somefunc(x, y):\n            time.sleep(x * y)\n\n        somefunc(2, 3)\n\n    will print the time taken by somefunc on every call.  If you want just\n    a summary at program termination, use\n\n        @timecall(immediate=False)\n\n    You can also choose a timing method other than the default ``time.time()``,\n    e.g.:\n\n        @timecall(timer=time.clock)"
  },
  {
    "code": "def find(self, path, match, flags):\n        try:\n            match = re.compile(match, flags)\n        except sre_constants.error as ex:\n            print(\"Bad regexp: %s\" % (ex))\n            return\n        offset = len(path)\n        for cpath in Tree(self, path).get():\n            if match.search(cpath[offset:]):\n                yield cpath",
    "docstring": "find every matching child path under path"
  },
  {
    "code": "def set_parent(self, parent):\n        assert self._parent is None or self._parent is parent,\\\n            \"Cannot change the parent. Can only set from None.\"\n        if parent and self._parent is parent:\n            return\n        self._parent = parent\n        if parent:\n            refobjinter = self.get_refobjinter()\n            refobj = self.get_refobj()\n            if refobj and not refobjinter.get_parent(refobj):\n                refobjinter.set_parent(refobj, parent.get_refobj())\n            self._parent.add_child(self)\n        if not self.get_refobj():\n            self.set_id(self.fetch_new_id())\n        pitem = self._parent._treeitem if self._parent else self.get_root().get_rootitem()\n        self._treeitem.set_parent(pitem)\n        self.fetch_alien()",
    "docstring": "Set the parent reftrack object\n\n        If a parent gets deleted, the children will be deleted too.\n\n        .. Note:: Once the parent is set, it cannot be set again!\n\n        :param parent: the parent reftrack object\n        :type parent: :class:`Reftrack` | None\n        :returns: None\n        :rtype: None\n        :raises: AssertionError"
  },
  {
    "code": "def cleanup_custom_options(id, weakref=None):\n    try:\n        if Store._options_context:\n            return\n        weakrefs = Store._weakrefs.get(id, [])\n        if weakref in weakrefs:\n            weakrefs.remove(weakref)\n        refs = []\n        for wr in list(weakrefs):\n            r = wr()\n            if r is None or r.id != id:\n                weakrefs.remove(wr)\n            else:\n                refs.append(r)\n        if not refs:\n            for bk in Store.loaded_backends():\n                if id in Store._custom_options[bk]:\n                    Store._custom_options[bk].pop(id)\n        if not weakrefs:\n            Store._weakrefs.pop(id, None)\n    except Exception as e:\n        raise Exception('Cleanup of custom options tree with id %s '\n                        'failed with the following exception: %s, '\n                        'an unreferenced orphan tree may persist in '\n                        'memory' % (e, id))",
    "docstring": "Cleans up unused custom trees if all objects referencing the\n    custom id have been garbage collected or tree is otherwise\n    unreferenced."
  },
  {
    "code": "def print_output(self, per_identity_data: 'RDD') -> None:\n        if not self._window_bts:\n            data = per_identity_data.flatMap(\n                lambda x: [json.dumps(data, cls=BlurrJSONEncoder) for data in x[1][0].items()])\n        else:\n            data = per_identity_data.map(\n                lambda x: json.dumps((x[0], x[1][1]), cls=BlurrJSONEncoder))\n        for row in data.collect():\n            print(row)",
    "docstring": "Basic helper function to write data to stdout. If window BTS was provided then the window\n        BTS output is written, otherwise, the streaming BTS output is written to stdout.\n\n        WARNING - For large datasets this will be extremely slow.\n\n        :param per_identity_data: Output of the `execute()` call."
  },
  {
    "code": "def get_iam_policy(self):\n        checker = AwsLimitChecker()\n        policy = checker.get_required_iam_policy()\n        return json.dumps(policy, sort_keys=True, indent=2)",
    "docstring": "Return the current IAM policy as a json-serialized string"
  },
  {
    "code": "def key(self) -> Tuple[int, int]:\r\n        return self._source.index, self._target.index",
    "docstring": "The unique identifier of the edge consisting of the indexes of its\r\n        source and target nodes."
  },
  {
    "code": "def wait_for_startup(self, timeout=None):\n        if not self.is_starting():\n            logger.warning(\"wait_for_startup() called when not in starting state\")\n        while not self.check_startup_state_changed():\n            with self._cancellable_lock:\n                if self._is_cancelled:\n                    return None\n            if timeout and self.time_in_state() > timeout:\n                return None\n            time.sleep(1)\n        return self.state == 'running'",
    "docstring": "Waits for PostgreSQL startup to complete or fail.\n\n        :returns: True if start was successful, False otherwise"
  },
  {
    "code": "def reset_highlights(self):\n        for dtype in [\"specimens\", \"samples\", \"sites\", \"locations\", \"ages\"]:\n            wind = self.FindWindowByName(dtype + '_btn')\n            wind.Unbind(wx.EVT_PAINT, handler=self.highlight_button)\n        self.Refresh()\n        self.bSizer_msg.ShowItems(False)\n        self.hbox.Fit(self)",
    "docstring": "Remove red outlines from all buttons"
  },
  {
    "code": "def gamma(alpha=1, beta=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs):\n    return _random_helper(_internal._random_gamma, _internal._sample_gamma,\n                          [alpha, beta], shape, dtype, ctx, out, kwargs)",
    "docstring": "Draw random samples from a gamma distribution.\n\n    Samples are distributed according to a gamma distribution parametrized\n    by *alpha* (shape) and *beta* (scale).\n\n    Parameters\n    ----------\n    alpha : float or NDArray, optional\n        The shape of the gamma distribution. Should be greater than zero.\n    beta : float or NDArray, optional\n        The scale of the gamma distribution. Should be greater than zero.\n        Default is equal to 1.\n    shape : int or tuple of ints, optional\n        The number of samples to draw. If shape is, e.g., `(m, n)` and `alpha` and\n        `beta` are scalars, output shape will be `(m, n)`. If `alpha` and `beta`\n        are NDArrays with shape, e.g., `(x, y)`, then output will have shape\n        `(x, y, m, n)`, where `m*n` samples are drawn for each `[alpha, beta)` pair.\n    dtype : {'float16', 'float32', 'float64'}, optional\n        Data type of output samples. Default is 'float32'\n    ctx : Context, optional\n        Device context of output. Default is current context. Overridden by\n        `alpha.context` when `alpha` is an NDArray.\n    out : NDArray, optional\n        Store output to an existing NDArray.\n\n    Returns\n    -------\n    NDArray\n        If input `shape` has shape, e.g., `(m, n)` and `alpha` and `beta` are scalars, output\n        shape will be `(m, n)`. If `alpha` and `beta` are NDArrays with shape, e.g.,\n        `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are\n        drawn for each `[alpha, beta)` pair.\n\n    Examples\n    --------\n    >>> mx.nd.random.gamma(1, 1)\n    [ 1.93308783]\n    <NDArray 1 @cpu(0)>\n    >>> mx.nd.random.gamma(1, 1, shape=(2,))\n    [ 0.48216391  2.09890771]\n    <NDArray 2 @cpu(0)>\n    >>> alpha = mx.nd.array([1,2,3])\n    >>> beta = mx.nd.array([2,3,4])\n    >>> mx.nd.random.gamma(alpha, beta, shape=2)\n    [[  3.24343276   0.94137681]\n     [  3.52734375   0.45568955]\n     [ 14.26264095  14.0170126 ]]\n    <NDArray 3x2 @cpu(0)>"
  },
  {
    "code": "def _check(self):\n        _logger.debug('Check if timeout.')\n        self._call_later_handle = None\n        if self._touch_time is not None:\n            difference = self._event_loop.time() - self._touch_time\n            _logger.debug('Time difference %s', difference)\n            if difference > self._timeout:\n                self._connection.close()\n                self._timed_out = True\n        if not self._connection.closed():\n            self._schedule()",
    "docstring": "Check and close connection if needed."
  },
  {
    "code": "def clean_html(self, html):\n        result_type = type(html)\n        if isinstance(html, six.string_types):\n            doc = html_fromstring(html)\n        else:\n            doc = copy.deepcopy(html)\n        self(doc)\n        if issubclass(result_type, six.binary_type):\n            return tostring(doc, encoding='utf-8')\n        elif issubclass(result_type, six.text_type):\n            return tostring(doc, encoding='unicode')\n        else:\n            return doc",
    "docstring": "Apply ``Cleaner`` to HTML string or document and return a cleaned string or document."
  },
  {
    "code": "def delete(self, endpoint, **kwargs):\n        kwargs.update(self.kwargs.copy())\n        response = requests.delete(self.make_url(endpoint), **kwargs)\n        return _decode_response(response)",
    "docstring": "Send HTTP DELETE to the endpoint.\n\n        :arg str endpoint: The endpoint to send to.\n\n        :returns:\n            JSON decoded result.\n\n        :raises:\n            requests.RequestException on timeout or connection error."
  },
  {
    "code": "def trim_N_nucleotides(prefix, suffix):\n    if 'N' in prefix:\n        rightmost_index = prefix.rfind('N')\n        logger.debug(\n            \"Trimming %d nucleotides from read prefix '%s'\",\n            rightmost_index + 1, prefix)\n        prefix = prefix[rightmost_index + 1:]\n    if 'N' in suffix:\n        leftmost_index = suffix.find('N')\n        logger.debug(\n            \"Trimming %d nucleotides from read suffix '%s'\",\n            len(suffix) - leftmost_index,\n            suffix)\n        suffix = suffix[:leftmost_index]\n    return prefix, suffix",
    "docstring": "Drop all occurrences of 'N' from prefix and suffix nucleotide strings\n    by trimming."
  },
  {
    "code": "def sizeof(self, context=None) -> int:\n        if context is None:\n            context = Context()\n        if not isinstance(context, Context):\n            context = Context(context)\n        try:\n            return self._sizeof(context)\n        except Error:\n            raise\n        except Exception as exc:\n            raise SizeofError(str(exc))",
    "docstring": "Return the size of the construct in bytes.\n\n        :param context: Optional context dictionary."
  },
  {
    "code": "def helper_list(access_token, oid, path):\n    if oid != \"\":\n        path = ''.join([path, \"('\", oid, \"')\"])\n    endpoint = ''.join([ams_rest_endpoint, path])\n    return do_ams_get(endpoint, path, access_token)",
    "docstring": "Helper Function to list a URL path.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        oid (str): An OID.\n        path (str): A URL Path.\n\n    Returns:\n        HTTP response. JSON body."
  },
  {
    "code": "async def scp_to(self, source, destination, user='ubuntu', proxy=False,\n                     scp_opts=''):\n        await self.machine.scp_to(source, destination, user=user, proxy=proxy,\n                                  scp_opts=scp_opts)",
    "docstring": "Transfer files to this unit.\n\n        :param str source: Local path of file(s) to transfer\n        :param str destination: Remote destination of transferred files\n        :param str user: Remote username\n        :param bool proxy: Proxy through the Juju API server\n        :param scp_opts: Additional options to the `scp` command\n        :type scp_opts: str or list"
  },
  {
    "code": "def _write_to_cache(self, expr, res):\n        res = dedent(res)\n        super()._write_to_cache(expr, res)",
    "docstring": "Store the cached result without indentation, and without the\n        keyname"
  },
  {
    "code": "def supported_auth_methods(self) -> List[str]:\n        return [auth for auth in self.AUTH_METHODS if auth in self.server_auth_methods]",
    "docstring": "Get all AUTH methods supported by the both server and by us."
  },
  {
    "code": "def clear(self):\n\t\tfor node in self.dli():\n\t\t\tnode.empty = True\n\t\t\tnode.key = None\n\t\t\tnode.value = None\n\t\tself.head = _dlnode()\n\t\tself.head.next = self.head\n\t\tself.head.prev = self.head\n\t\tself.listSize = 1\n\t\tself.table.clear()\n\t\tself.hit_cnt = 0 \n\t\tself.miss_cnt = 0\n\t\tself.remove_cnt = 0",
    "docstring": "claar all the cache, and release memory"
  },
  {
    "code": "def _checkFileExists(self):\n        if self._fileName and not os.path.exists(self._fileName):\n            msg = \"File not found: {}\".format(self._fileName)\n            logger.error(msg)\n            self.setException(IOError(msg))\n            return False\n        else:\n            return True",
    "docstring": "Verifies that the underlying file exists and sets the _exception attribute if not\n            Returns True if the file exists.\n            If self._fileName is None, nothing is checked and True is returned."
  },
  {
    "code": "def reset(self, value=None):\n    if value is None:\n      value = time.clock()\n    self.start = value\n    if self.value_on_reset:\n      self.value = self.value_on_reset",
    "docstring": "Resets the start time of the interval to now or the specified value."
  },
  {
    "code": "def get_recent_comments(number=5, template='zinnia/tags/comments_recent.html'):\n    entry_published_pks = map(smart_text,\n                              Entry.published.values_list('id', flat=True))\n    content_type = ContentType.objects.get_for_model(Entry)\n    comments = get_comment_model().objects.filter(\n        Q(flags=None) | Q(flags__flag=CommentFlag.MODERATOR_APPROVAL),\n        content_type=content_type, object_pk__in=entry_published_pks,\n        is_public=True).order_by('-pk')[:number]\n    comments = comments.prefetch_related('content_object')\n    return {'template': template,\n            'comments': comments}",
    "docstring": "Return the most recent comments."
  },
  {
    "code": "def first_and_second_harmonic_function(phi, c):\n    return (c[0] + c[1]*np.sin(phi) + c[2]*np.cos(phi) + c[3]*np.sin(2*phi) +\n            c[4]*np.cos(2*phi))",
    "docstring": "Compute the harmonic function value used to calculate the\n    corrections for ellipse fitting.\n\n    This function includes simultaneously both the first and second\n    order harmonics:\n\n    .. math::\n\n        f(phi) = c[0] + c[1]*\\\\sin(phi) + c[2]*\\\\cos(phi) +\n                 c[3]*\\\\sin(2*phi) + c[4]*\\\\cos(2*phi)\n\n    Parameters\n    ----------\n    phi : float or `~numpy.ndarray`\n        The angle(s) along the elliptical path, going towards the positive\n        y axis, starting coincident with the position angle. That is, the\n        angles are defined from the semimajor axis that lies in\n        the positive x quadrant.\n    c : `~numpy.ndarray` of shape (5,)\n        Array containing the five harmonic coefficients.\n\n    Returns\n    -------\n    result : float or `~numpy.ndarray`\n        The function value(s) at the given input angle(s)."
  },
  {
    "code": "def get_mean_table(self, imt, rctx):\n        if imt.name in 'PGA PGV':\n            interpolator = interp1d(self.magnitudes,\n                                    numpy.log10(self.mean[imt.name]), axis=2)\n            output_table = 10.0 ** (\n                interpolator(rctx.mag).reshape(self.shape[0], self.shape[3]))\n        else:\n            interpolator = interp1d(numpy.log10(self.periods),\n                                    numpy.log10(self.mean[\"SA\"]),\n                                    axis=1)\n            period_table = interpolator(numpy.log10(imt.period))\n            mag_interpolator = interp1d(self.magnitudes, period_table, axis=1)\n            output_table = 10.0 ** mag_interpolator(rctx.mag)\n        return output_table",
    "docstring": "Returns amplification factors for the mean, given the rupture and\n        intensity measure type.\n\n        :returns:\n            amplification table as an array of [Number Distances,\n            Number Levels]"
  },
  {
    "code": "def MatchBestComponentName(self, component):\n    fd = self.OpenAsContainer()\n    file_listing = set(fd.ListNames())\n    if component not in file_listing:\n      lower_component = component.lower()\n      for x in file_listing:\n        if lower_component == x.lower():\n          component = x\n          break\n    if fd.supported_pathtype != self.pathspec.pathtype:\n      new_pathspec = rdf_paths.PathSpec(\n          path=component, pathtype=fd.supported_pathtype)\n    else:\n      new_pathspec = self.pathspec.last.Copy()\n      new_pathspec.path = component\n    return new_pathspec",
    "docstring": "Returns the name of the component which matches best our base listing.\n\n    In order to do the best case insensitive matching we list the files in the\n    base handler and return the base match for this component.\n\n    Args:\n      component: A component name which should be present in this directory.\n\n    Returns:\n      the best component name."
  },
  {
    "code": "def extract_columns(data, *cols):\n    out = []\n    try:\n        for r in data:\n            col = []\n            for c in cols:\n                col.append(r[c])\n            out.append(col)\n    except IndexError:\n        raise IndexError(\"data=%s col=%s\" % (data, col))\n    return out",
    "docstring": "Extract columns specified in the argument list.\n\n>>> chart_data.extract_columns([[10,20], [30,40], [50,60]], 0)\n[[10],[30],[50]]"
  },
  {
    "code": "def tas53(msg):\n    d = hex2bin(data(msg))\n    if d[33] == '0':\n        return None\n    tas = bin2int(d[34:46]) * 0.5\n    return round(tas, 1)",
    "docstring": "Aircraft true airspeed, BDS 5,3 message\n\n    Args:\n        msg (String): 28 bytes hexadecimal message\n\n    Returns:\n        float: true airspeed in knots"
  },
  {
    "code": "def print_result(overview, *names):\n    if names:\n        for name in names:\n            toprint = overview\n            for part in name.split('/'):\n                toprint = toprint[part]\n            print(json.dumps(toprint, indent=4, separators=(',', ': ')))\n    else:\n        print(json.dumps(overview, indent=4, separators=(',', ': ')))",
    "docstring": "Print the result of a verisure request"
  },
  {
    "code": "def full_scope(self):\n        maps = [self.temps] + self.resolvers.maps + self.scope.maps\n        return DeepChainMap(*maps)",
    "docstring": "Return the full scope for use with passing to engines transparently\n        as a mapping.\n\n        Returns\n        -------\n        vars : DeepChainMap\n            All variables in this scope."
  },
  {
    "code": "def _clear_current_task(self):\n        self.current.task_name = None\n        self.current.task_type = None\n        self.current.task = None",
    "docstring": "Clear tasks related attributes, checks permissions\n        While switching WF to WF, authentication and permissions are checked for new WF."
  },
  {
    "code": "def parse(inp, format=None, encoding='utf-8', force_types=True):\n    proper_inp = inp\n    if hasattr(inp, 'read'):\n        proper_inp = inp.read()\n    if isinstance(proper_inp, six.text_type):\n        proper_inp = proper_inp.encode(encoding)\n    fname = None\n    if hasattr(inp, 'name'):\n        fname = inp.name\n    fmt = _get_format(format, fname, proper_inp)\n    proper_inp = six.BytesIO(proper_inp)\n    try:\n        res = _do_parse(proper_inp, fmt, encoding, force_types)\n    except Exception as e:\n        raise AnyMarkupError(e, traceback.format_exc())\n    if res is None:\n        res = {}\n    return res",
    "docstring": "Parse input from file-like object, unicode string or byte string.\n\n    Args:\n        inp: file-like object, unicode string or byte string with the markup\n        format: explicitly override the guessed `inp` markup format\n        encoding: `inp` encoding, defaults to utf-8\n        force_types:\n            if `True`, integers, floats, booleans and none/null\n                are recognized and returned as proper types instead of strings;\n            if `False`, everything is converted to strings\n            if `None`, backend return value is used\n    Returns:\n        parsed input (dict or list) containing unicode values\n    Raises:\n        AnyMarkupError if a problem occurs while parsing or inp"
  },
  {
    "code": "def get(self, section, option, as_list=False):\n        ret = super(GitConfigParser, self).get(section, option)\n        if as_list and not isinstance(ret, list):\n            ret = [ret]\n        return ret",
    "docstring": "Adds an optional \"as_list\" argument to ensure a list is returned. This\n        is helpful when iterating over an option which may or may not be a\n        multivar."
  },
  {
    "code": "def deleted(self, base: pathlib.PurePath = pathlib.PurePath(),\n                include_children: bool = True,\n                include_directories: bool = True) -> Iterator[str]:\n        if self.is_deleted:\n            yield str(base / self.left.name)",
    "docstring": "Find the paths of entities deleted between the left and right entities\n        in this comparison.\n\n        :param base: The base directory to recursively append to entities.\n        :param include_children: Whether to recursively include children of\n                                 deleted directories. These are themselves\n                                 deleted by definition, however it may be\n                                 useful to the caller to list them explicitly.\n        :param include_directories: Whether to include directories in the\n                                    returned iterable.\n        :return: An iterable of deleted paths."
  },
  {
    "code": "def to_string(self, obj):\n        try:\n            converted = [str(element) for element in obj]\n            string = ','.join(converted)\n        except TypeError:\n            string = str(obj)\n        return string",
    "docstring": "Picks up an object and transforms it\n        into a string, by coercing each element\n        in an iterable to a string and then joining\n        them, or by trying to coerce the object directly"
  },
  {
    "code": "def color(nickname):\n    _hex = md5(nickname).hexdigest()[:6]\n    darken = lambda s: str(int(round(int(s, 16) * .7)))\n    return \"rgb(%s)\" % \",\".join([darken(_hex[i:i+2]) for i in range(6)[::2]])",
    "docstring": "Provides a consistent color for a nickname. Uses first 6 chars\n    of nickname's md5 hash, and then slightly darkens the rgb values\n    for use on a light background."
  },
  {
    "code": "def post(self, ddata, url=SETUP_ENDPOINT, referer=SETUP_ENDPOINT):\n        headers = HEADERS.copy()\n        if referer is None:\n            headers.pop('Referer')\n        else:\n            headers['Referer'] = referer\n        if 'csrfmiddlewaretoken' not in ddata.keys():\n            ddata['csrfmiddlewaretoken'] = self._parent.csrftoken\n        req = self._parent.client.post(url, headers=headers, data=ddata)\n        if req.status_code == 200:\n            self.update()",
    "docstring": "Method to update some attributes on namespace."
  },
  {
    "code": "def int_check(*args, func=None):\n    func = func or inspect.stack()[2][3]\n    for var in args:\n        if not isinstance(var, numbers.Integral):\n            name = type(var).__name__\n            raise ComplexError(\n                f'Function {func} expected integral number, {name} got instead.')",
    "docstring": "Check if arguments are integrals."
  },
  {
    "code": "def stem_singular_word(self, word):\n        context = Context(word, self.dictionary, self.visitor_provider)\n        context.execute()\n        return context.result",
    "docstring": "Stem a singular word to its common stem form."
  },
  {
    "code": "def index_missing_documents(self, documents, request=None):\n        log.info('Trying to index documents of type `{}` missing from '\n                 '`{}` index'.format(self.doc_type, self.index_name))\n        if not documents:\n            log.info('No documents to index')\n            return\n        query_kwargs = dict(\n            index=self.index_name,\n            doc_type=self.doc_type,\n            fields=['_id'],\n            body={'ids': [d['_pk'] for d in documents]},\n        )\n        try:\n            response = self.api.mget(**query_kwargs)\n        except IndexNotFoundException:\n            indexed_ids = set()\n        else:\n            indexed_ids = set(\n                d['_id'] for d in response['docs'] if d.get('found'))\n        documents = [d for d in documents if str(d['_pk']) not in indexed_ids]\n        if not documents:\n            log.info('No documents of type `{}` are missing from '\n                     'index `{}`'.format(self.doc_type, self.index_name))\n            return\n        self._bulk('index', documents, request)",
    "docstring": "Index documents that are missing from ES index.\n\n        Determines which documents are missing using ES `mget` call which\n        returns a list of document IDs as `documents`. Then missing\n        `documents` from that list are indexed."
  },
  {
    "code": "def _print_err(*args):\n    if not CFG.debug:\n        return\n    if not args:\n        return\n    encoding = 'utf8' if os.name == 'posix' else 'gbk'\n    args = [_cs(a, encoding) for a in args]\n    f_back = None\n    try:\n        raise Exception\n    except:\n        f_back = sys.exc_traceback.tb_frame.f_back\n    f_name = f_back.f_code.co_name\n    filename = os.path.basename(f_back.f_code.co_filename)\n    m_name = os.path.splitext(filename)[0]\n    prefix = ('[%s.%s]'%(m_name, f_name)).ljust(20, ' ')\n    print bcolors.FAIL+'[%s]'%str(datetime.datetime.now()), prefix, ' '.join(args) + bcolors.ENDC",
    "docstring": "Print errors.\n\n        *args\n          list, list of printing contents"
  },
  {
    "code": "def iss_spi_divisor(self, sck):\n        _divisor = (6000000 / sck) - 1\n        divisor = int(_divisor)\n        if divisor != _divisor:\n            raise ValueError('Non-integer SCK divisor.')\n        if not 1 <= divisor < 256:\n            error = (\n                \"The value of sck_divisor, {}, \"\n                \"is not between 0 and 255\".format(divisor)\n            )\n            raise ValueError(error)\n        return divisor",
    "docstring": "Calculate a USBISS SPI divisor value from the input SPI clock speed\n\n        :param sck: SPI clock frequency\n        :type sck: int\n        :returns: ISS SCK divisor\n        :rtype: int"
  },
  {
    "code": "def _get_history_minute_window(self, assets, end_dt, bar_count,\n                                   field_to_use):\n        try:\n            minutes_for_window = self.trading_calendar.minutes_window(\n                end_dt, -bar_count\n            )\n        except KeyError:\n            self._handle_minute_history_out_of_bounds(bar_count)\n        if minutes_for_window[0] < self._first_trading_minute:\n            self._handle_minute_history_out_of_bounds(bar_count)\n        asset_minute_data = self._get_minute_window_data(\n            assets,\n            field_to_use,\n            minutes_for_window,\n        )\n        return pd.DataFrame(\n            asset_minute_data,\n            index=minutes_for_window,\n            columns=assets\n        )",
    "docstring": "Internal method that returns a dataframe containing history bars\n        of minute frequency for the given sids."
  },
  {
    "code": "def _get_value_from_match(self, key, match):\n        value = match.groups(1)[0]\n        clean_value = str(value).lstrip().rstrip()\n        if clean_value == 'true':\n            self._log.info('Got value of \"%s\" as boolean true.', key)\n            return True\n        if clean_value == 'false':\n            self._log.info('Got value of \"%s\" as boolean false.', key)\n            return False\n        try:\n            float_value = float(clean_value)\n            self._log.info('Got value of \"%s\" as float \"%f\".',\n                           key,\n                           float_value)\n            return float_value\n        except ValueError:\n            self._log.info('Got value of \"%s\" as string \"%s\".',\n                           key,\n                           clean_value)\n            return clean_value",
    "docstring": "Gets the value of the property in the given MatchObject.\n\n        Args:\n            key (str):           Key of the property looked-up.\n            match (MatchObject): The matched property.\n\n        Return:\n            The discovered value, as a string or boolean."
  },
  {
    "code": "def get(cls, scope=None):\n        if scope is None:\n            scope = cls.default\n        if isinstance(scope, string_types) and scope in cls._keywords:\n            return getattr(cls, scope)\n        return scope",
    "docstring": "Return default or predefined URLs from keyword, pass through ``scope``."
  },
  {
    "code": "def load(self, carddict):\n        self.code = carddict[\"code\"]\n        if isinstance(self.code, text_type):\n            self.code = eval(self.code)\n        self.name = carddict[\"name\"]\n        self.abilities = carddict[\"abilities\"]\n        if isinstance(self.abilities, text_type):\n            self.abilities = eval(self.abilities)\n        self.attributes = carddict[\"attributes\"]\n        if isinstance(self.attributes, text_type):\n            self.attributes = eval(self.attributes)\n        self.info = carddict[\"info\"]\n        if isinstance(self.info, text_type):\n            self.info = eval(self.info)\n        return self",
    "docstring": "Takes a carddict as produced by ``Card.save`` and sets this card\n        instances information to the previously saved cards information."
  },
  {
    "code": "def list(self, cart_glob=['*.json']):\n        carts = []\n        for glob in cart_glob:\n            if not glob.endswith('.json'):\n                search_glob = glob + \".json\"\n            else:\n                search_glob = glob\n            for cart in juicer.utils.find_pattern(Constants.CART_LOCATION, search_glob):\n                cart_name = cart.split('/')[-1].replace('.json', '')\n                carts.append(cart_name)\n        return carts",
    "docstring": "List all carts"
  },
  {
    "code": "def get_weights(self, data, F):\n        beta = np.var(data)\n        trans_F = F.T.copy()\n        W = np.zeros((self.K, data.shape[1]))\n        if self.weight_method == 'rr':\n            W = np.linalg.solve(trans_F.dot(F) + beta * np.identity(self.K),\n                                trans_F.dot(data))\n        else:\n            W = np.linalg.solve(trans_F.dot(F), trans_F.dot(data))\n        return W",
    "docstring": "Calculate weight matrix based on fMRI data and factors\n\n        Parameters\n        ----------\n\n        data : 2D array, with shape [n_voxel, n_tr]\n            fMRI data from one subject\n\n        F : 2D array, with shape [n_voxel,self.K]\n            The latent factors from fMRI data.\n\n\n        Returns\n        -------\n\n        W : 2D array, with shape [K, n_tr]\n            The weight matrix from fMRI data."
  },
  {
    "code": "def key_description(self):\n        \"Return a description of the key\"\n        vk, scan, flags = self._get_key_info()\n        desc = ''\n        if vk:\n            if vk in CODE_NAMES:\n                desc = CODE_NAMES[vk]\n            else:\n                desc = \"VK %d\"% vk\n        else:\n            desc = \"%s\"% self.key\n        return desc",
    "docstring": "Return a description of the key"
  },
  {
    "code": "def _sumterm_prime(lexer):\n    tok = next(lexer)\n    if isinstance(tok, OP_or):\n        xorterm = _xorterm(lexer)\n        sumterm_prime = _sumterm_prime(lexer)\n        if sumterm_prime is None:\n            return xorterm\n        else:\n            return ('or', xorterm, sumterm_prime)\n    else:\n        lexer.unpop_token(tok)\n        return None",
    "docstring": "Return a sum term' expression, eliminates left recursion."
  },
  {
    "code": "def module(command, *args):\n    if 'MODULESHOME' not in os.environ:\n        print('payu: warning: No Environment Modules found; skipping {0} call.'\n              ''.format(command))\n        return\n    modulecmd = ('{0}/bin/modulecmd'.format(os.environ['MODULESHOME']))\n    cmd = '{0} python {1} {2}'.format(modulecmd, command, ' '.join(args))\n    envs, _ = subprocess.Popen(shlex.split(cmd),\n                               stdout=subprocess.PIPE).communicate()\n    exec(envs)",
    "docstring": "Run the modulecmd tool and use its Python-formatted output to set the\n    environment variables."
  },
  {
    "code": "def removeDefaultAttributeValue(node, attribute):\n    if not node.hasAttribute(attribute.name):\n        return 0\n    if isinstance(attribute.value, str):\n        if node.getAttribute(attribute.name) == attribute.value:\n            if (attribute.conditions is None) or attribute.conditions(node):\n                node.removeAttribute(attribute.name)\n                return 1\n    else:\n        nodeValue = SVGLength(node.getAttribute(attribute.name))\n        if ((attribute.value is None)\n                or ((nodeValue.value == attribute.value) and not (nodeValue.units == Unit.INVALID))):\n            if ((attribute.units is None)\n                    or (nodeValue.units == attribute.units)\n                    or (isinstance(attribute.units, list) and nodeValue.units in attribute.units)):\n                if (attribute.conditions is None) or attribute.conditions(node):\n                    node.removeAttribute(attribute.name)\n                    return 1\n    return 0",
    "docstring": "Removes the DefaultAttribute 'attribute' from 'node' if specified conditions are fulfilled\n\n    Warning: Does NOT check if the attribute is actually valid for the passed element type for increased preformance!"
  },
  {
    "code": "def IOC_TYPECHECK(t):\n    result = ctypes.sizeof(t)\n    assert result <= _IOC_SIZEMASK, result\n    return result",
    "docstring": "Returns the size of given type, and check its suitability for use in an\n    ioctl command number."
  },
  {
    "code": "def _options_request(self, url, **kwargs):\r\n        request_kwargs = {\r\n            'method': 'OPTIONS',\r\n            'url': url\r\n        }\r\n        for key, value in kwargs.items():\r\n            request_kwargs[key] = value\r\n        return self._request(**request_kwargs)",
    "docstring": "a method to catch and report http options request connectivity errors"
  },
  {
    "code": "def gc(self):\n        gc = len([base for base in self.seq if base == 'C' or base == 'G'])\n        return float(gc) / len(self)",
    "docstring": "Find the frequency of G and C in the current sequence."
  },
  {
    "code": "def goal(self, goal_name, count=1):\n        for enrollment in self._get_all_enrollments():\n            if enrollment.experiment.is_displaying_alternatives():\n                self._experiment_goal(enrollment.experiment, enrollment.alternative, goal_name, count)",
    "docstring": "Record that this user has performed a particular goal\n\n        This will update the goal stats for all experiments the user is enrolled in."
  },
  {
    "code": "def rgevolve_leadinglog(self, scale_out):\n        self._check_initial()\n        return rge.smeft_evolve_leadinglog(C_in=self.C_in,\n                            scale_high=self.scale_high,\n                            scale_in=self.scale_in,\n                            scale_out=scale_out)",
    "docstring": "Compute the leading logarithmix approximation to the solution\n        of the SMEFT RGEs from the initial scale to `scale_out`.\n        Returns a dictionary with parameters and Wilson coefficients.\n        Much faster but less precise that `rgevolve`."
  },
  {
    "code": "def app_profile(\n        self,\n        app_profile_id,\n        routing_policy_type=None,\n        description=None,\n        cluster_id=None,\n        allow_transactional_writes=None,\n    ):\n        return AppProfile(\n            app_profile_id,\n            self,\n            routing_policy_type=routing_policy_type,\n            description=description,\n            cluster_id=cluster_id,\n            allow_transactional_writes=allow_transactional_writes,\n        )",
    "docstring": "Factory to create AppProfile associated with this instance.\n\n        For example:\n\n        .. literalinclude:: snippets.py\n            :start-after: [START bigtable_create_app_profile]\n            :end-before: [END bigtable_create_app_profile]\n\n        :type app_profile_id: str\n        :param app_profile_id: The ID of the AppProfile. Must be of the form\n                               ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.\n\n        :type: routing_policy_type: int\n        :param: routing_policy_type: The type of the routing policy.\n                                     Possible values are represented\n                                     by the following constants:\n                                     :data:`google.cloud.bigtable.enums.RoutingPolicyType.ANY`\n                                     :data:`google.cloud.bigtable.enums.RoutingPolicyType.SINGLE`\n\n        :type: description: str\n        :param: description: (Optional) Long form description of the use\n                             case for this AppProfile.\n\n        :type: cluster_id: str\n        :param: cluster_id: (Optional) Unique cluster_id which is only required\n                            when routing_policy_type is\n                            ROUTING_POLICY_TYPE_SINGLE.\n\n        :type: allow_transactional_writes: bool\n        :param: allow_transactional_writes: (Optional) If true, allow\n                                            transactional writes for\n                                            ROUTING_POLICY_TYPE_SINGLE.\n\n        :rtype: :class:`~google.cloud.bigtable.app_profile.AppProfile>`\n        :returns: AppProfile for this instance."
  },
  {
    "code": "def optimal_parameters(reconstruction, fom, phantoms, data,\n                       initial=None, univariate=False):\n    r\n    def func(lam):\n        return sum(fom(reconstruction(datai, lam), phantomi)\n                   for phantomi, datai in zip(phantoms, data))\n    tol = np.finfo(phantoms[0].space.dtype).resolution * 10\n    if univariate:\n        result = scipy.optimize.minimize_scalar(\n            func, bracket=initial, tol=tol, bounds=None,\n            options={'disp': False})\n        return result.x\n    else:\n        initial = np.asarray(initial)\n        parameters = scipy.optimize.fmin_powell(\n            func, initial, xtol=tol, ftol=tol, disp=False)\n        return parameters",
    "docstring": "r\"\"\"Find the optimal parameters for a reconstruction method.\n\n    Notes\n    -----\n    For a forward operator :math:`A : X \\to Y`, a reconstruction operator\n    parametrized by :math:`\\theta` is some operator\n    :math:`R_\\theta : Y \\to X`\n    such that\n\n    .. math::\n        R_\\theta(A(x)) \\approx x.\n\n    The optimal choice of :math:`\\theta` is given by\n\n    .. math::\n        \\theta = \\arg\\min_\\theta fom(R(A(x) + noise), x)\n\n    where :math:`fom : X \\times X \\to \\mathbb{R}` is a figure of merit.\n\n    Parameters\n    ----------\n    reconstruction : callable\n        Function that takes two parameters:\n\n            * data : The data to be reconstructed\n            * parameters : Parameters of the reconstruction method\n\n        The function should return the reconstructed image.\n    fom : callable\n        Function that takes two parameters:\n\n            * reconstructed_image\n            * true_image\n\n        and returns a scalar figure of merit.\n    phantoms : sequence\n        True images.\n    data : sequence\n        The data to reconstruct from.\n    initial : array-like or pair\n        Initial guess for the parameters. It is\n        - a required array in the multivariate case\n        - an optional pair in the univariate case.\n    univariate : bool, optional\n        Whether to use a univariate solver\n\n    Returns\n    -------\n    parameters : 'numpy.ndarray'\n        The  optimal parameters for the reconstruction problem."
  },
  {
    "code": "def identify(fn):\n        return (\n            fn.__globals__['__name__'],\n            getattr(fn, '__qualname__', getattr(fn, '__name__', ''))\n        )\n        def __init__(self, fn):\n            self.validate_function(fn)\n            self.configured = False\n            self.has_backup_plan = False\n            if self.has_args():\n                self.backup_plan = fn\n            else:\n                self.id = self.identify(fn)\n                self.backup_plan = big.overload._cache.get(self.id, None)\n                self.configure_with(fn)\n        def __call__(self, *args, **kwargs):\n            try:\n                return self.fn(*args, **kwargs)\n            except Exception as ex:\n                if self.has_backup_plan:\n                    return self.backup_plan(*args, **kwargs)\n                elif self.configured:\n                    raise ex\n                else:\n                    self.configure_with(*args, **kwargs)\n                    return self",
    "docstring": "returns a tuple that is used to match\n            functions to their neighbors in their\n            resident namespaces"
  },
  {
    "code": "def ln_growth(eqdata, **kwargs):\n    if 'outputcol' not in kwargs:\n        kwargs['outputcol'] = 'LnGrowth'\n    return np.log(growth(eqdata, **kwargs))",
    "docstring": "Return the natural log of growth.\n\n    See also\n    --------\n    :func:`growth`"
  },
  {
    "code": "def stop(self, id):\n        path = partial(_path, self.adapter)\n        path = path(id)\n        return self._delete(path)",
    "docstring": "stop the tracker."
  },
  {
    "code": "def get_content_models(cls):\n        concrete_model = base_concrete_model(ContentTyped, cls)\n        return [m for m in apps.get_models()\n                if m is not concrete_model and issubclass(m, concrete_model)]",
    "docstring": "Return all subclasses of the concrete model."
  },
  {
    "code": "def space_acl(args):\n    r = fapi.get_workspace_acl(args.project, args.workspace)\n    fapi._check_response_code(r, 200)\n    result = dict()\n    for user, info in sorted(r.json()['acl'].items()):\n        result[user] = info['accessLevel']\n    return result",
    "docstring": "Retrieve access control list for a workspace"
  },
  {
    "code": "def _safe_name(file_name, sep):\n    file_name = stringify(file_name)\n    if file_name is None:\n        return\n    file_name = ascii_text(file_name)\n    file_name = category_replace(file_name, UNICODE_CATEGORIES)\n    file_name = collapse_spaces(file_name)\n    if file_name is None or not len(file_name):\n        return\n    return file_name.replace(WS, sep)",
    "docstring": "Convert the file name to ASCII and normalize the string."
  },
  {
    "code": "def get(self, label, default=None):\n        if label in self.index:\n            loc = self.index.get_loc(label)\n            return self._get_val_at(loc)\n        else:\n            return default",
    "docstring": "Returns value occupying requested label, default to specified\n        missing value if not present. Analogous to dict.get\n\n        Parameters\n        ----------\n        label : object\n            Label value looking for\n        default : object, optional\n            Value to return if label not in index\n\n        Returns\n        -------\n        y : scalar"
  },
  {
    "code": "def actions(obj, **kwargs):\n    if 'exclude' in kwargs:\n        kwargs['exclude'] = kwargs['exclude'].split(',')\n    actions = obj.get_actions(**kwargs)\n    if isinstance(actions, dict):\n        actions = actions.values()\n    buttons = \"\".join(\"%s\" % action.render() for action in actions)\n    return '<div class=\"actions\">%s</div>' % buttons",
    "docstring": "Return actions available for an object"
  },
  {
    "code": "def action_draft(self):\n        for rec in self:\n            if not rec.state == 'cancelled':\n                raise UserError(\n                    _('You need to cancel it before reopening.'))\n            if not (rec.am_i_owner or rec.am_i_approver):\n                raise UserError(\n                    _('You are not authorized to do this.\\r\\n'\n                      'Only owners or approvers can reopen Change Requests.'))\n            rec.write({'state': 'draft'})",
    "docstring": "Set a change request as draft"
  },
  {
    "code": "def _prepare_corerelation_data(self, X1, X2,\n                                   start_voxel=0,\n                                   num_processed_voxels=None):\n        num_samples = len(X1)\n        assert num_samples > 0, \\\n            'at least one sample is needed for correlation computation'\n        num_voxels1 = X1[0].shape[1]\n        num_voxels2 = X2[0].shape[1]\n        assert num_voxels1 * num_voxels2 == self.num_features_, \\\n            'the number of features provided by the input data ' \\\n            'does not match the number of features defined in the model'\n        assert X1[0].shape[0] == X2[0].shape[0], \\\n            'the numbers of TRs of X1 and X2 are not identical'\n        if num_processed_voxels is None:\n            num_processed_voxels = num_voxels1\n        corr_data = np.zeros((num_samples, num_processed_voxels, num_voxels2),\n                             np.float32, order='C')\n        for idx, data in enumerate(X1):\n            data2 = X2[idx]\n            num_TRs = data.shape[0]\n            blas.compute_corr_vectors('N', 'T',\n                                      num_voxels2, num_processed_voxels,\n                                      num_TRs,\n                                      1.0, data2, num_voxels2,\n                                      data, num_voxels1,\n                                      0.0, corr_data, num_voxels2,\n                                      start_voxel, idx)\n        logger.debug(\n            'correlation computation done'\n        )\n        return corr_data",
    "docstring": "Compute auto-correlation for the input data X1 and X2.\n\n        it will generate the correlation between some voxels and all voxels\n\n        Parameters\n        ----------\n        X1: a list of numpy array in shape [num_TRs, num_voxels1]\n            X1 contains the activity data filtered by ROIs\n            and prepared for correlation computation.\n            All elements of X1 must have the same num_voxels value.\n        X2: a list of numpy array in shape [num_TRs, num_voxels2]\n            len(X1) equals len(X2).\n            All elements of X2 must have the same num_voxels value.\n            X2 can be identical to X1; if not, X1 must have more voxels\n            than X2 (guaranteed by self.fit and/or self.predict).\n        start_voxel: int, default 0\n            the starting voxel id for correlation computation\n        num_processed_voxels: int, default None\n            the number of voxels it computes for correlation computation\n            if it is None, it is set to self.num_voxels\n\n        Returns\n        -------\n        corr_data: the correlation data\n                    in shape [len(X), num_processed_voxels, num_voxels2]"
  },
  {
    "code": "def render(self):\n        if not self.available():\n            return \"\"\n        mtool = api.get_tool(\"portal_membership\")\n        member = mtool.getAuthenticatedMember()\n        roles = member.getRoles()\n        allowed = \"LabManager\" in roles or \"Manager\" in roles\n        self.get_failed_instruments()\n        if allowed and self.nr_failed:\n            return self.index()\n        else:\n            return \"\"",
    "docstring": "Render the viewlet"
  },
  {
    "code": "def get_owner_ids_value(self, obj):\n        return [\n            user.pk\n            for user in get_users_with_permission(obj, get_full_perm('owner', obj))\n        ]",
    "docstring": "Extract owners' ids."
  },
  {
    "code": "def gray2bin(G):\n    return farray([G[i:].uxor() for i, _ in enumerate(G)])",
    "docstring": "Convert a gray-coded vector into a binary-coded vector."
  },
  {
    "code": "def status(cls):\n        return cls.json_get('%s/status' % cls.api_url, empty_key=True,\n                            send_key=False)",
    "docstring": "Retrieve global status from status.gandi.net."
  },
  {
    "code": "def dirty(self):\n      return not os.path.exists(self.cachename) or \\\n            (os.path.getmtime(self.filename) >\n             os.path.getmtime(self.cachename))",
    "docstring": "True if the cache needs to be updated, False otherwise"
  },
  {
    "code": "def get_my_ip():\n    ip = subprocess.check_output(GET_IP_CMD, shell=True).decode('utf-8')[:-1]\n    return ip.strip()",
    "docstring": "Returns this computers IP address as a string."
  },
  {
    "code": "def sum(self):\n        return self._constructor(self.values.sum(axis=self.baseaxes, keepdims=True))",
    "docstring": "Compute the sum across records."
  },
  {
    "code": "def classify_catalog(catalog):\n    components = []\n    islands = []\n    simples = []\n    for source in catalog:\n        if isinstance(source, OutputSource):\n            components.append(source)\n        elif isinstance(source, IslandSource):\n            islands.append(source)\n        elif isinstance(source, SimpleSource):\n            simples.append(source)\n    return components, islands, simples",
    "docstring": "Look at a list of sources and split them according to their class.\n\n    Parameters\n    ----------\n    catalog : iterable\n        A list or iterable object of {SimpleSource, IslandSource, OutputSource} objects, possibly mixed.\n        Any other objects will be silently ignored.\n\n    Returns\n    -------\n    components : list\n        List of sources of type OutputSource\n\n    islands : list\n        List of sources of type IslandSource\n\n    simples : list\n        List of source of type SimpleSource"
  },
  {
    "code": "def wrap_io_os_err(e):\n    msg = ''\n    if e.strerror:\n        msg = e.strerror\n    if e.message:\n        msg = ' '.join([e.message, msg])\n    if e.filename:\n        msg = ': '.join([msg, e.filename])\n    return msg",
    "docstring": "Formats IO and OS error messages for wrapping in FSQExceptions"
  },
  {
    "code": "def get_userinfo(self):\r\n        wanted_fields = [\"name\", \"mobile\", \"orgEmail\", \"position\", \"avatar\"]\r\n        userinfo = {k: self.json_response.get(k, None) for k in wanted_fields}\r\n        return userinfo",
    "docstring": "Method to get current user's name, mobile, email and position."
  },
  {
    "code": "def _format_postconditions(postconditions: List[icontract._Contract], prefix: Optional[str] = None) -> List[str]:\n    if not postconditions:\n        return []\n    result = []\n    if prefix is not None:\n        result.append(\":{} ensures:\".format(prefix))\n    else:\n        result.append(\":ensures:\")\n    for postcondition in postconditions:\n        result.append(\"    * {}\".format(_format_contract(contract=postcondition)))\n    return result",
    "docstring": "Format postconditions as reST.\n\n    :param postconditions: postconditions of a function\n    :param prefix: prefix to be prepended to ``:ensures:`` directive\n    :return: list of lines describing the postconditions"
  },
  {
    "code": "def register_instance(self, instance, allow_dotted_names=False):\n        self.instance = instance\n        self.allow_dotted_names = allow_dotted_names",
    "docstring": "Registers an instance to respond to XML-RPC requests.\n\n        Only one instance can be installed at a time.\n\n        If the registered instance has a _dispatch method then that\n        method will be called with the name of the XML-RPC method and\n        its parameters as a tuple\n        e.g. instance._dispatch('add',(2,3))\n\n        If the registered instance does not have a _dispatch method\n        then the instance will be searched to find a matching method\n        and, if found, will be called. Methods beginning with an '_'\n        are considered private and will not be called by\n        SimpleXMLRPCServer.\n\n        If a registered function matches a XML-RPC request, then it\n        will be called instead of the registered instance.\n\n        If the optional allow_dotted_names argument is true and the\n        instance does not have a _dispatch method, method names\n        containing dots are supported and resolved, as long as none of\n        the name segments start with an '_'.\n\n            *** SECURITY WARNING: ***\n\n            Enabling the allow_dotted_names options allows intruders\n            to access your module's global variables and may allow\n            intruders to execute arbitrary code on your machine.  Only\n            use this option on a secure, closed network."
  },
  {
    "code": "def _get_url_hashes(path):\n  urls = _read_text_file(path)\n  def url_hash(u):\n    h = hashlib.sha1()\n    try:\n      u = u.encode('utf-8')\n    except UnicodeDecodeError:\n      logging.error('Cannot hash url: %s', u)\n    h.update(u)\n    return h.hexdigest()\n  return {url_hash(u): True for u in urls}",
    "docstring": "Get hashes of urls in file."
  },
  {
    "code": "def merge_paths(paths, weights=None):\n    G = make_paths(paths, weights=weights)\n    G = reduce_paths(G)\n    return G",
    "docstring": "Zip together sorted lists.\n\n    >>> paths = [[1, 2, 3], [1, 3, 4], [2, 4, 5]]\n    >>> G = merge_paths(paths)\n    >>> nx.topological_sort(G)\n    [1, 2, 3, 4, 5]\n    >>> paths = [[1, 2, 3, 4], [1, 2, 3, 2, 4]]\n    >>> G = merge_paths(paths, weights=(1, 2))\n    >>> nx.topological_sort(G)\n    [1, 2, 3, 4]"
  },
  {
    "code": "def _calc_new_threshold(self, score):\n        if self.threshold_mode == 'rel':\n            abs_threshold_change = self.threshold * score\n        else:\n            abs_threshold_change = self.threshold\n        if self.lower_is_better:\n            new_threshold = score - abs_threshold_change\n        else:\n            new_threshold = score + abs_threshold_change\n        return new_threshold",
    "docstring": "Determine threshold based on score."
  },
  {
    "code": "def locked(path, timeout=None):\n    def decor(func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            lock = FileLock(path, timeout=timeout)\n            lock.acquire()\n            try:\n                return func(*args, **kwargs)\n            finally:\n                lock.release()\n        return wrapper\n    return decor",
    "docstring": "Decorator which enables locks for decorated function.\n\n    Arguments:\n     - path: path for lockfile.\n     - timeout (optional): Timeout for acquiring lock.\n\n     Usage:\n         @locked('/var/run/myname', timeout=0)\n         def myname(...):\n             ..."
  },
  {
    "code": "def atlasdb_reset_zonefile_tried_storage( con=None, path=None ):\n    with AtlasDBOpen(con=con, path=path) as dbcon:\n        sql = \"UPDATE zonefiles SET tried_storage = ? WHERE present = ?;\"\n        args = (0, 0)\n        cur = dbcon.cursor()\n        res = atlasdb_query_execute( cur, sql, args )\n        dbcon.commit()\n    return True",
    "docstring": "For zonefiles that we don't have, re-attempt to fetch them from storage."
  },
  {
    "code": "def Terminate(self):\n\t\tself.lock.acquire()\n\t\ttry:\n\t\t\tfor bucket in self.connections.values():\n\t\t\t\ttry:\n\t\t\t\t\tfor conn in bucket:\n\t\t\t\t\t\tconn.lock()\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tconn.Close()\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\tpass\n\t\t\t\t\t\tconn.release()\n\t\t\t\texcept Exception:\n\t\t\t\t\tpass\n\t\t\tself.connections = {}\n\t\tfinally:\n\t\t\tself.lock.release()",
    "docstring": "Close all open connections\n\t\t\n\t\tLoop though all the connections and commit all queries and close all the connections. \n\t\tThis should be called at the end of your application.\n\t\t\n\t\t@author: Nick Verbeck\n\t\t@since: 5/12/2008"
  },
  {
    "code": "def end_namespace(self, prefix):\n        del self._ns[prefix]\n        self._g.endPrefixMapping(prefix)",
    "docstring": "Undeclare a namespace prefix."
  },
  {
    "code": "def place(self, value):\n        if (value is not None) and (not value in DG_C_PLACE):\n            raise ValueError(\"Unrecognized value for place: '%s'\" % value)\n        self.__place = value",
    "docstring": "Set the place of articulation of the consonant.\n\n        :param str value: the value to be set"
  },
  {
    "code": "def set_handler(self, language, obj):\n        if obj is None:\n            if language in self._handlers:\n                del self._handlers[language]\n        else:\n            self._handlers[language] = obj",
    "docstring": "Define a custom language handler for RiveScript objects.\n\n        Pass in a ``None`` value for the object to delete an existing handler (for\n        example, to prevent Python code from being able to be run by default).\n\n        Look in the ``eg`` folder of the rivescript-python distribution for\n        an example script that sets up a JavaScript language handler.\n\n        :param str language: The lowercased name of the programming language.\n            Examples: python, javascript, perl\n        :param class obj: An instance of an implementation class object.\n            It should provide the following interface::\n\n                class MyObjectHandler:\n                    def __init__(self):\n                        pass\n                    def load(self, name, code):\n                        # name = the name of the object from the RiveScript code\n                        # code = the source code of the object\n                    def call(self, rs, name, fields):\n                        # rs     = the current RiveScript interpreter object\n                        # name   = the name of the object being called\n                        # fields = array of arguments passed to the object\n                        return reply"
  },
  {
    "code": "def logged_command(cmds):\n    \"helper function to log a command and then run it\"\n    logger.info(' '.join(cmds))\n    os.system(' '.join(cmds))",
    "docstring": "helper function to log a command and then run it"
  },
  {
    "code": "def extras_msg(extras):\n    if len(extras) == 1:\n        verb = \"was\"\n    else:\n        verb = \"were\"\n    return \", \".join(repr(extra) for extra in extras), verb",
    "docstring": "Create an error message for extra items or properties."
  },
  {
    "code": "def accept_key(pki_dir, pub, id_):\n    for key_dir in 'minions', 'minions_pre', 'minions_rejected':\n        key_path = os.path.join(pki_dir, key_dir)\n        if not os.path.exists(key_path):\n            os.makedirs(key_path)\n    key = os.path.join(pki_dir, 'minions', id_)\n    with salt.utils.files.fopen(key, 'w+') as fp_:\n        fp_.write(salt.utils.stringutils.to_str(pub))\n    oldkey = os.path.join(pki_dir, 'minions_pre', id_)\n    if os.path.isfile(oldkey):\n        with salt.utils.files.fopen(oldkey) as fp_:\n            if fp_.read() == pub:\n                os.remove(oldkey)",
    "docstring": "If the master config was available then we will have a pki_dir key in\n    the opts directory, this method places the pub key in the accepted\n    keys dir and removes it from the unaccepted keys dir if that is the case."
  },
  {
    "code": "def save(self, session_file, verbose=False):\n        PARAMS={\"file\":session_file}\n        response=api(url=self.__url+\"/save\", PARAMS=PARAMS, verbose=verbose)\n        return response",
    "docstring": "Saves the current session to an existing file, which will be replaced.\n        If this is a new session that has not been saved yet, use 'save as'\n        instead.\n\n        :param session_file: The path to the file where the current session\n        must be saved to.\n        :param verbose: print more"
  },
  {
    "code": "def list_sku_versions(access_token, subscription_id, location, publisher, offer, sku):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/providers/Microsoft.Compute/',\n                        'locations/', location,\n                        '/publishers/', publisher,\n                        '/artifacttypes/vmimage/offers/', offer,\n                        '/skus/', sku,\n                        '/versions?api-version=', COMP_API])\n    return do_get(endpoint, access_token)",
    "docstring": "List available versions for a given publisher's sku.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n        location (str): Azure data center location. E.g. westus.\n        publisher (str): VM image publisher. E.g. MicrosoftWindowsServer.\n        offer (str): VM image offer. E.g. WindowsServer.\n        sku (str): VM image sku. E.g. 2016-Datacenter.\n\n    Returns:\n        HTTP response with JSON list of versions."
  },
  {
    "code": "def namespace_to_dict(obj):\n    if isinstance(obj, (argparse.Namespace, optparse.Values)):\n        return vars(obj)\n    return obj",
    "docstring": "If obj is argparse.Namespace or optparse.Values we'll return\n      a dict representation of it, else return the original object.\n\n    Redefine this method if using other parsers.\n\n    :param obj: *\n    :return:\n    :rtype: dict or *"
  },
  {
    "code": "def add_barplot(self):\n        cats = OrderedDict()\n        cats['n_nondups'] = {'name': 'Non-duplicates'}\n        cats['n_dups'] = {'name': 'Duplicates'}\n        pconfig = {\n            'id': 'samblaster_duplicates',\n            'title': 'Samblaster: Number of duplicate reads',\n            'ylab': 'Number of reads'\n        }\n        self.add_section( plot = bargraph.plot(self.samblaster_data, cats, pconfig) )",
    "docstring": "Generate the Samblaster bar plot."
  },
  {
    "code": "def space_labels(document):\n    for label in document.xpath('.//bold'):\n        if not label.text or not re.match('^\\(L?\\d\\d?[a-z]?\\):?$', label.text, re.I):\n            continue\n        parent = label.getparent()\n        previous = label.getprevious()\n        if previous is None:\n            text = parent.text or ''\n            if not text.endswith(' '):\n                parent.text = text + ' '\n        else:\n            text = previous.tail or ''\n            if not text.endswith(' '):\n                previous.tail = text + ' '\n        text = label.tail or ''\n        if not text.endswith(' '):\n            label.tail = text + ' '\n    return document",
    "docstring": "Ensure space around bold compound labels."
  },
  {
    "code": "def field_types(self):\n        if self._field_types is None:\n            self._field_types = FieldTypeList(self._version, assistant_sid=self._solution['sid'], )\n        return self._field_types",
    "docstring": "Access the field_types\n\n        :returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeList\n        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeList"
  },
  {
    "code": "def get_fields(model_class):\n    return [\n        attr for attr, value in model_class.__dict__.items()\n        if issubclass(type(value), (mongo.base.BaseField, mongo.EmbeddedDocumentField))\n    ]",
    "docstring": "Pass in a mongo model class and extract all the attributes which\n    are mongoengine fields\n\n    Returns:\n        list of strings of field attributes"
  },
  {
    "code": "def visit(self, node):\n        method = getattr(self, 'visit_' + node.expr_name, self.generic_visit)\n        try:\n            return method(node, [self.visit(child) for child in reversed(list(node))])\n        except (VisitationError, UndefinedLabel):\n            raise\n        except self.unwrapped_exceptions:\n            raise\n        except Exception:\n            exc_class, exc, traceback = exc_info()\n            reraise(VisitationError, VisitationError(exc, exc_class, node), traceback)",
    "docstring": "See the ``NodeVisitor`` visit method. This just changes the order in which\n        we visit nonterminals from right to left to left to right."
  },
  {
    "code": "def on_ok(self, sender):\n        logger.debug(\"in on_ok with sender %s\" % sender)\n        if sender == self.ion_task and not self.transfer_done:\n            ion_structure = self.ion_task.get_final_structure()\n            self.ioncell_task._change_structure(ion_structure)\n            self.transfer_done = True\n            self.ioncell_task.unlock(source_node=self)\n        elif sender == self.ioncell_task and self.target_dilatmx:\n            actual_dilatmx = self.ioncell_task.get_inpvar('dilatmx', 1.)\n            if self.target_dilatmx < actual_dilatmx:\n                self.ioncell_task.reduce_dilatmx(target=self.target_dilatmx)\n                self.history.info('Converging dilatmx. Value reduce from {} to {}.'\n                            .format(actual_dilatmx, self.ioncell_task.get_inpvar('dilatmx')))\n                self.ioncell_task.reset_from_scratch()\n        return super().on_ok(sender)",
    "docstring": "This callback is called when one task reaches status S_OK.\n        If sender == self.ion_task, we update the initial structure\n        used by self.ioncell_task and we unlock it so that the job can be submitted."
  },
  {
    "code": "def compile_delete(self, query):\n        table = self.wrap_table(query.from__)\n        if isinstance(query.wheres, list):\n            wheres = self._compile_wheres(query)\n        else:\n            wheres = \"\"\n        if query.joins:\n            joins = \" %s\" % self._compile_joins(query, query.joins)\n            sql = \"DELETE %s FROM %s%s %s\" % (table, table, joins, wheres)\n        else:\n            sql = \"DELETE FROM %s %s\" % (table, wheres)\n        sql = sql.strip()\n        if query.orders:\n            sql += \" %s\" % self._compile_orders(query, query.orders)\n        if query.limit_:\n            sql += \" %s\" % self._compile_limit(query, query.limit_)\n        return sql",
    "docstring": "Compile a delete statement into SQL\n\n        :param query: A QueryBuilder instance\n        :type query: QueryBuilder\n\n        :return: The compiled update\n        :rtype: str"
  },
  {
    "code": "def dir_import_table(self):\n        import_header = list(self.optional_data_directories)[1]\n        import_offset = self.resolve_rva(import_header.VirtualAddress)\n        i = 0\n        while True:\n            offset = import_offset + i*Import_DirectoryTable.get_size()\n            idt = Import_DirectoryTable(self.stream, offset, self)\n            if idt.is_empty():\n                break\n            else:\n                yield idt\n            i += 1",
    "docstring": "import table is terminated by a all-null entry, so we have to\n            check for that"
  },
  {
    "code": "def set_contents_from_filename(self, filename, headers=None, replace=True,\n                                   cb=None, num_cb=10, policy=None, md5=None,\n                                   reduced_redundancy=False,\n                                   encrypt_key=False):\n        fp = open(filename, 'rb')\n        self.set_contents_from_file(fp, headers, replace, cb, num_cb,\n                                    policy, md5, reduced_redundancy,\n                                    encrypt_key=encrypt_key)\n        fp.close()",
    "docstring": "Store an object in S3 using the name of the Key object as the\n        key in S3 and the contents of the file named by 'filename'.\n        See set_contents_from_file method for details about the\n        parameters.\n\n        :type filename: string\n        :param filename: The name of the file that you want to put onto S3\n\n        :type headers: dict\n        :param headers: Additional headers to pass along with the\n                        request to AWS.\n\n        :type replace: bool\n        :param replace: If True, replaces the contents of the file\n                        if it already exists.\n\n        :type cb: function\n        :param cb: a callback function that will be called to report\n                   progress on the upload.  The callback should accept\n                   two integer parameters, the first representing the\n                   number of bytes that have been successfully\n                   transmitted to S3 and the second representing the\n                   size of the to be transmitted object.\n\n        :type cb: int\n        :param num_cb: (optional) If a callback is specified with\n                       the cb parameter this parameter determines the\n                       granularity of the callback by defining\n                       the maximum number of times the callback will\n                       be called during the file transfer.\n\n        :type policy: :class:`boto.s3.acl.CannedACLStrings`\n        :param policy: A canned ACL policy that will be applied to the\n                       new key in S3.\n\n        :type md5: A tuple containing the hexdigest version of the MD5\n                   checksum of the file as the first element and the\n                   Base64-encoded version of the plain checksum as the\n                   second element.  This is the same format returned by\n                   the compute_md5 method.\n        :param md5: If you need to compute the MD5 for any reason prior\n                    to upload, it's silly to have to do it twice so this\n                    param, if present, will be used as the MD5 values\n                    of the file.  Otherwise, the checksum will be computed.\n\n        :type reduced_redundancy: bool\n        :param reduced_redundancy: If True, this will set the storage\n                                   class of the new Key to be\n                                   REDUCED_REDUNDANCY. The Reduced Redundancy\n                                   Storage (RRS) feature of S3, provides lower\n                                   redundancy at lower storage cost.\n        :type encrypt_key: bool\n        :param encrypt_key: If True, the new copy of the object will\n                            be encrypted on the server-side by S3 and\n                            will be stored in an encrypted form while\n                            at rest in S3."
  },
  {
    "code": "def link_href(self, rel):\n        link = self.link(rel)\n        if (link is not None):\n            link = link['href']\n        return(link)",
    "docstring": "Look for link with specified rel, return href from it or None."
  },
  {
    "code": "def to_frequencyseries(self, delta_f=None):\n        from pycbc.fft import fft\n        if not delta_f:\n            delta_f = 1.0 / self.duration\n        tlen  = int(1.0 / delta_f / self.delta_t + 0.5)\n        flen = int(tlen / 2 + 1)\n        if tlen < len(self):\n            raise ValueError(\"The value of delta_f (%s) would be \"\n                             \"undersampled. Maximum delta_f \"\n                             \"is %s.\" % (delta_f, 1.0 / self.duration))\n        if not delta_f:\n            tmp = self\n        else:\n            tmp = TimeSeries(zeros(tlen, dtype=self.dtype),\n                             delta_t=self.delta_t, epoch=self.start_time)\n            tmp[:len(self)] = self[:]\n        f = FrequencySeries(zeros(flen,\n                           dtype=complex_same_precision_as(self)),\n                           delta_f=delta_f)\n        fft(tmp, f)\n        return f",
    "docstring": "Return the Fourier transform of this time series\n\n        Parameters\n        ----------\n        delta_f : {None, float}, optional\n            The frequency resolution of the returned frequency series. By\n        default the resolution is determined by the duration of the timeseries.\n\n        Returns\n        -------\n        FrequencySeries:\n            The fourier transform of this time series."
  },
  {
    "code": "def fw_retry_failures_delete(self):\n        for tenant_id in self.fwid_attr:\n            try:\n                with self.fwid_attr[tenant_id].mutex_lock:\n                    fw_data = self.get_fw_by_tenant_id(tenant_id)\n                    if fw_data is None:\n                        LOG.info(\"No FW for tenant %s\", tenant_id)\n                        continue\n                    result = fw_data.get('result').split('(')[0]\n                    if result == fw_constants.RESULT_FW_DELETE_INIT:\n                        fw_dict = self.fwid_attr[tenant_id].get_fw_dict()\n                        if not fw_dict:\n                            fw_dict = self.fill_fw_dict_from_db(fw_data)\n                        self.retry_failure_fab_dev_delete(tenant_id, fw_data,\n                                                          fw_dict)\n            except Exception as exc:\n                LOG.error(\"Exception in retry failure delete %s\",\n                          str(exc))",
    "docstring": "This routine is called for retrying the delete cases."
  },
  {
    "code": "def _find_plugin_dir(module_type):\n    for install_dir in _get_plugin_install_dirs():\n        candidate = os.path.join(install_dir, module_type)\n        if os.path.isdir(candidate):\n            return candidate\n    else:\n        raise PluginCandidateError(\n            'No plugin found for `{}` module in paths:\\n{}'.format(\n                module_type, '\\n'.join(_get_plugin_install_dirs())))",
    "docstring": "Find the directory containing the plugin definition for the given type.\n    Do this by searching all the paths where plugins can live for a dir that\n    matches the type name."
  },
  {
    "code": "def subs2seqs(self) -> Dict[str, List[str]]:\n        subs2seqs = collections.defaultdict(list)\n        nodes = find(self.find('sequences'), 'node')\n        if nodes is not None:\n            for seq in nodes:\n                subs2seqs['node'].append(strip(seq.tag))\n        return subs2seqs",
    "docstring": "A |collections.defaultdict| containing the node-specific\n        information provided by XML `sequences` element.\n\n        >>> from hydpy.auxs.xmltools import XMLInterface\n        >>> from hydpy import data\n        >>> interface = XMLInterface('single_run.xml', data.get_path('LahnH'))\n        >>> series_io = interface.series_io\n        >>> subs2seqs = series_io.writers[2].subs2seqs\n        >>> for subs, seq in sorted(subs2seqs.items()):\n        ...     print(subs, seq)\n        node ['sim', 'obs']"
  },
  {
    "code": "def main(reactor):\n    control_ep = UNIXClientEndpoint(reactor, '/var/run/tor/control')\n    tor = yield txtorcon.connect(reactor, control_ep)\n    state = yield tor.create_state()\n    print(\"Closing all circuits:\")\n    for circuit in list(state.circuits.values()):\n        path = '->'.join(map(lambda r: r.id_hex, circuit.path))\n        print(\"Circuit {} through {}\".format(circuit.id, path))\n        for stream in circuit.streams:\n            print(\"  Stream {} to {}\".format(stream.id, stream.target_host))\n            yield stream.close()\n            print(\"  closed\")\n        yield circuit.close()\n        print(\"closed\")\n    yield tor.quit()",
    "docstring": "Close all open streams and circuits in the Tor we connect to"
  },
  {
    "code": "def result_type(*arrays_and_dtypes):\n    types = {np.result_type(t).type for t in arrays_and_dtypes}\n    for left, right in PROMOTE_TO_OBJECT:\n        if (any(issubclass(t, left) for t in types) and\n                any(issubclass(t, right) for t in types)):\n            return np.dtype(object)\n    return np.result_type(*arrays_and_dtypes)",
    "docstring": "Like np.result_type, but with type promotion rules matching pandas.\n\n    Examples of changed behavior:\n    number + string -> object (not string)\n    bytes + unicode -> object (not unicode)\n\n    Parameters\n    ----------\n    *arrays_and_dtypes : list of arrays and dtypes\n        The dtype is extracted from both numpy and dask arrays.\n\n    Returns\n    -------\n    numpy.dtype for the result."
  },
  {
    "code": "def mouseDown(self, button):\n        log.debug('mouseDown %s', button)\n        self.buttons |= 1 << (button - 1)\n        self.pointerEvent(self.x, self.y, buttonmask=self.buttons)\n        return self",
    "docstring": "Send a mouse button down at the last set position\n\n            button: int: [1-n]"
  },
  {
    "code": "def backward(self, loss):\n        with mx.autograd.record():\n            if isinstance(loss, (tuple, list)):\n                ls = [l * self._scaler.loss_scale for l in loss]\n            else:\n                ls = loss * self._scaler.loss_scale\n        mx.autograd.backward(ls)",
    "docstring": "backward propagation with loss"
  },
  {
    "code": "def isSquare(matrix):\n    try:\n        try:\n            dim1, dim2 = matrix.shape\n        except AttributeError:\n            dim1, dim2 = _np.array(matrix).shape\n    except ValueError:\n        return False\n    if dim1 == dim2:\n        return True\n    return False",
    "docstring": "Check that ``matrix`` is square.\n\n    Returns\n    =======\n    is_square : bool\n        ``True`` if ``matrix`` is square, ``False`` otherwise."
  },
  {
    "code": "def write(self, data, params=None, expected_response_code=204,\n              protocol='json'):\n        headers = self._headers\n        headers['Content-Type'] = 'application/octet-stream'\n        if params:\n            precision = params.get('precision')\n        else:\n            precision = None\n        if protocol == 'json':\n            data = make_lines(data, precision).encode('utf-8')\n        elif protocol == 'line':\n            if isinstance(data, str):\n                data = [data]\n            data = ('\\n'.join(data) + '\\n').encode('utf-8')\n        self.request(\n            url=\"write\",\n            method='POST',\n            params=params,\n            data=data,\n            expected_response_code=expected_response_code,\n            headers=headers\n        )\n        return True",
    "docstring": "Write data to InfluxDB.\n\n        :param data: the data to be written\n        :type data: (if protocol is 'json') dict\n                    (if protocol is 'line') sequence of line protocol strings\n                                            or single string\n        :param params: additional parameters for the request, defaults to None\n        :type params: dict\n        :param expected_response_code: the expected response code of the write\n            operation, defaults to 204\n        :type expected_response_code: int\n        :param protocol: protocol of input data, either 'json' or 'line'\n        :type protocol: str\n        :returns: True, if the write operation is successful\n        :rtype: bool"
  },
  {
    "code": "def GetUnscannedSubNode(self):\n    if not self.sub_nodes and not self.scanned:\n      return self\n    for sub_node in self.sub_nodes:\n      result = sub_node.GetUnscannedSubNode()\n      if result:\n        return result\n    return None",
    "docstring": "Retrieves the first unscanned sub node.\n\n    Returns:\n      SourceScanNode: sub scan node or None if not available."
  },
  {
    "code": "def addAnnotationsSearchOptions(parser):\n    addAnnotationSetIdArgument(parser)\n    addReferenceNameArgument(parser)\n    addReferenceIdArgument(parser)\n    addStartArgument(parser)\n    addEndArgument(parser)\n    addEffectsArgument(parser)\n    addPageSizeArgument(parser)",
    "docstring": "Adds common options to a annotation searches command line parser."
  },
  {
    "code": "def guess_pygments_highlighter(filename):\r\n    try:\r\n        from pygments.lexers import get_lexer_for_filename, get_lexer_by_name\r\n    except Exception:\r\n        return TextSH\r\n    root, ext = os.path.splitext(filename)\r\n    if ext in custom_extension_lexer_mapping:\r\n        try:\r\n            lexer = get_lexer_by_name(custom_extension_lexer_mapping[ext])\r\n        except Exception:\r\n            return TextSH\r\n    else:\r\n        try:\r\n            lexer = get_lexer_for_filename(filename)\r\n        except Exception:\r\n            return TextSH\r\n    class GuessedPygmentsSH(PygmentsSH):\r\n        _lexer = lexer\r\n    return GuessedPygmentsSH",
    "docstring": "Factory to generate syntax highlighter for the given filename.\r\n\r\n    If a syntax highlighter is not available for a particular file, this\r\n    function will attempt to generate one based on the lexers in Pygments.  If\r\n    Pygments is not available or does not have an appropriate lexer, TextSH\r\n    will be returned instead."
  },
  {
    "code": "def close_cursor(self, cursor_id, address=None):\n        warnings.warn(\n            \"close_cursor is deprecated.\",\n            DeprecationWarning,\n            stacklevel=2)\n        if not isinstance(cursor_id, integer_types):\n            raise TypeError(\"cursor_id must be an instance of (int, long)\")\n        self._close_cursor(cursor_id, address)",
    "docstring": "DEPRECATED - Send a kill cursors message soon with the given id.\n\n        Raises :class:`TypeError` if `cursor_id` is not an instance of\n        ``(int, long)``. What closing the cursor actually means\n        depends on this client's cursor manager.\n\n        This method may be called from a :class:`~pymongo.cursor.Cursor`\n        destructor during garbage collection, so it isn't safe to take a\n        lock or do network I/O. Instead, we schedule the cursor to be closed\n        soon on a background thread.\n\n        :Parameters:\n          - `cursor_id`: id of cursor to close\n          - `address` (optional): (host, port) pair of the cursor's server.\n            If it is not provided, the client attempts to close the cursor on\n            the primary or standalone, or a mongos server.\n\n        .. versionchanged:: 3.7\n           Deprecated.\n\n        .. versionchanged:: 3.0\n           Added ``address`` parameter."
  },
  {
    "code": "def analyse(self, path_and_filename, pattern):\n        with open(path_and_filename) as handle:\n            content = handle.read()\n            loc = content.count('\\n') + 1\n            com = 0\n            for match in re.findall(pattern, content, re.DOTALL):\n                com += match.count('\\n') + 1\n            return max(0, loc - com), com",
    "docstring": "Find out lines of code and lines of comments.\n\n        Args:\n            path_and_filename (str): path and filename to parse  for loc and com.\n            pattern (str): regex to search for line commens and block comments\n\n        Returns:\n            int, int: loc and com for given file."
  },
  {
    "code": "def fist() -> Histogram1D:\n    import numpy as np\n    from ..histogram1d import Histogram1D\n    widths = [0, 1.2, 0.2, 1, 0.1, 1, 0.1, 0.9, 0.1, 0.8]\n    edges = np.cumsum(widths)\n    heights = np.asarray([4, 1, 7.5, 6, 7.6, 6, 7.5, 6, 7.2]) + 5\n    return Histogram1D(edges, heights, axis_name=\"Is this a fist?\", title=\"Physt \\\"logo\\\"\")",
    "docstring": "A simple histogram in the shape of a fist."
  },
  {
    "code": "def get_prefix(self, form, name):\n        return '{form_prefix}{prefix_name}-{field_name}'.format(\n            form_prefix=form.prefix + '-' if form.prefix else '',\n            prefix_name=self.prefix_name,\n            field_name=name)",
    "docstring": "Return the prefix that is used for the formset."
  },
  {
    "code": "def connection(self, connection):\n        if connection is not None:\n            connection.subscribe(\"capacity\", self._on_capacity_data)\n            connection.default_return_capacity = True\n        if self._connection is not None:\n            connection.unsubscribe(\"capacity\", self._on_capacity_data)\n        self._connection = connection\n        self._cloudwatch_connection = None\n        self.cached_descriptions = {}",
    "docstring": "Change the dynamo connection"
  },
  {
    "code": "def parse(input_: Union[str, FileStream], source: str) -> Optional[str]:\n    error_listener = ParseErrorListener()\n    if not isinstance(input_, FileStream):\n        input_ = InputStream(input_)\n    lexer = jsgLexer(input_)\n    lexer.addErrorListener(error_listener)\n    tokens = CommonTokenStream(lexer)\n    tokens.fill()\n    if error_listener.n_errors:\n        return None\n    parser = jsgParser(tokens)\n    parser.addErrorListener(error_listener)\n    parse_tree = parser.doc()\n    if error_listener.n_errors:\n        return None\n    parser = JSGDocParser()\n    parser.visit(parse_tree)\n    if parser.undefined_tokens():\n        for tkn in parser.undefined_tokens():\n            print(\"Undefined token: \" + tkn)\n        return None\n    return parser.as_python(source)",
    "docstring": "Parse the text in infile and save the results in outfile\n\n    :param input_: string or stream to parse\n    :param source: source name for python file header\n    :return: python text if successful"
  },
  {
    "code": "def parse(self, data):\n        self.validate_packet(data)\n        packet_length = data[0]\n        packet_type = data[1]\n        sub_type = data[2]\n        sequence_number = data[3]\n        command_type = data[4]\n        transceiver_type = data[5]\n        transceiver_type_text = _MSG1_RECEIVER_TYPE.get(data[5])\n        firmware_version = data[6]\n        flags = self._int_to_binary_list(data[7])\n        flags.extend(self._int_to_binary_list(data[8]))\n        flags.extend(self._int_to_binary_list(data[9]))\n        enabled, disabled = self._log_enabled_protocols(flags, PROTOCOLS)\n        return {\n            'packet_length': packet_length,\n            'packet_type': packet_type,\n            'packet_type_name': self.PACKET_TYPES.get(packet_type),\n            'sequence_number': sequence_number,\n            'sub_type': sub_type,\n            'sub_type_name': self.PACKET_SUBTYPES.get(sub_type),\n            'command_type': command_type,\n            'transceiver_type': transceiver_type,\n            'transceiver_type_text': transceiver_type_text,\n            'firmware_version': firmware_version,\n            'enabled_protocols': enabled,\n            'disabled_protocols': disabled,\n        }",
    "docstring": "Parse a 13 byte packet in the Status format.\n\n        :param data: bytearray to be parsed\n        :type data: bytearray\n\n        :return: Data dictionary containing the parsed values\n        :rtype: dict"
  },
  {
    "code": "def setup_app(app, api):\n    api.add_resource(\n        KnwKBAllResource,\n        '/api/knowledge'\n    )\n    api.add_resource(\n        KnwKBResource,\n        '/api/knowledge/<string:slug>'\n    )\n    api.add_resource(\n        KnwKBMappingsResource,\n        '/api/knowledge/<string:slug>/mappings'\n    )\n    api.add_resource(\n        KnwKBMappingsToResource,\n        '/api/knowledge/<string:slug>/mappings/to'\n    )\n    api.add_resource(\n        KnwKBMappingsFromResource,\n        '/api/knowledge/<string:slug>/mappings/from'\n    )\n    api.add_resource(\n        NotImplementedKnowledegeResource,\n        '/api/knowledge/<string:slug>/<path:foo>'\n    )",
    "docstring": "setup the resources urls."
  },
  {
    "code": "def handlePosition(self, msg):\n        self.log_msg(\"position\", msg)\n        contract_tuple = self.contract_to_tuple(msg.contract)\n        contractString = self.contractString(contract_tuple)\n        self.registerContract(msg.contract)\n        if msg.account not in self._positions.keys():\n            self._positions[msg.account] = {}\n        self._positions[msg.account][contractString] = {\n            \"symbol\":        contractString,\n            \"position\":      int(msg.pos),\n            \"avgCost\":       float(msg.avgCost),\n            \"account\":       msg.account\n        }\n        self.ibCallback(caller=\"handlePosition\", msg=msg)",
    "docstring": "handle positions changes"
  },
  {
    "code": "def _update(self, rules: list):\n        self._rules = rules\n        to_store = '\\n'.join(\n            rule.config_string\n            for rule in rules\n        )\n        sftp_connection = self._sftp_connection\n        with sftp_connection.open(self.RULE_PATH, mode='w') as file_handle:\n            file_handle.write(to_store)",
    "docstring": "Updates the given rules and stores\n        them on the router."
  },
  {
    "code": "def update_pulled_fields(instance, imported_instance, fields):\n    modified = False\n    for field in fields:\n        pulled_value = getattr(imported_instance, field)\n        current_value = getattr(instance, field)\n        if current_value != pulled_value:\n            setattr(instance, field, pulled_value)\n            logger.info(\"%s's with PK %s %s field updated from value '%s' to value '%s'\",\n                        instance.__class__.__name__, instance.pk, field, current_value, pulled_value)\n            modified = True\n    error_message = getattr(imported_instance, 'error_message', '') or getattr(instance, 'error_message', '')\n    if error_message and instance.error_message != error_message:\n        instance.error_message = imported_instance.error_message\n        modified = True\n    if modified:\n        instance.save()",
    "docstring": "Update instance fields based on imported from backend data.\n    Save changes to DB only one or more fields were changed."
  },
  {
    "code": "def prepare_soap_body(self, method, parameters, namespace):\n        tags = []\n        for name, value in parameters:\n            tag = \"<{name}>{value}</{name}>\".format(\n                name=name, value=escape(\"%s\" % value, {'\"': \"&quot;\"}))\n            tags.append(tag)\n        wrapped_params = \"\".join(tags)\n        if namespace is not None:\n            soap_body = (\n                '<{method} xmlns=\"{namespace}\">'\n                '{params}'\n                '</{method}>'.format(\n                    method=method, params=wrapped_params,\n                    namespace=namespace\n                ))\n        else:\n            soap_body = (\n                '<{method}>'\n                '{params}'\n                '</{method}>'.format(\n                    method=method, params=wrapped_params\n                ))\n        return soap_body",
    "docstring": "Prepare the SOAP message body for sending.\n\n        Args:\n            method (str): The name of the method to call.\n            parameters (list): A list of (name, value) tuples containing\n                the parameters to pass to the method.\n            namespace (str): tThe XML namespace to use for the method.\n\n        Returns:\n            str: A properly formatted SOAP Body."
  },
  {
    "code": "def during(f):\n    def decorator(g):\n        @wraps(g)\n        def h(*args, **kargs):\n            tf = Thread(target=f, args=args, kwargs=kargs)\n            tf.start()\n            r = g(*args, **kargs)\n            tf.join()\n            return r\n        return h\n    return decorator",
    "docstring": "Runs f during the decorated function's execution in a separate thread."
  },
  {
    "code": "def render(self):\n        f1 = self._format_alignment(self._alignment[0], self._alignment[1])\n        f2 = self._format_alignment(self._alignment[1], self._alignment[0])\n        return f1, f2",
    "docstring": "Returns a tuple of HTML fragments rendering each element of the\n        sequence."
  },
  {
    "code": "def send(self, url, **kwargs):\n        if self.config.server_url:\n            return super(DjangoClient, self).send(url, **kwargs)\n        else:\n            self.error_logger.error(\"No server configured, and elasticapm not installed. Cannot send message\")\n            return None",
    "docstring": "Serializes and signs ``data`` and passes the payload off to ``send_remote``\n\n        If ``server`` was passed into the constructor, this will serialize the data and pipe it to\n        the server using ``send_remote()``."
  },
  {
    "code": "def convert(self, imtls, idx=0):\n        curve = numpy.zeros(1, imtls.dt)\n        for imt in imtls:\n            curve[imt] = self.array[imtls(imt), idx]\n        return curve[0]",
    "docstring": "Convert a probability curve into a record of dtype `imtls.dt`.\n\n        :param imtls: DictArray instance\n        :param idx: extract the data corresponding to the given inner index"
  },
  {
    "code": "def make_request(self, model, action, url_params={}, post_data=None):\n        url = self._create_url(model, **url_params)\n        headers = self._headers(action)\n        try:\n            response = requests.request(action, url, headers=headers, data=post_data)\n        except Exception as e:\n            raise APIError(\"There was an error communicating with Union: %s\" % e)\n        if not self._is_valid(response):\n            raise ValidationError(\"The Union response returned an error: %s\" % response.content)\n        return self._parse_response(response)",
    "docstring": "Send request to API then validate, parse, and return the response"
  },
  {
    "code": "def get_symbol_dict(self, voigt=True, zero_index=False, **kwargs):\n        d = {}\n        if voigt:\n            array = self.voigt\n        else:\n            array = self\n        grouped = self.get_grouped_indices(voigt=voigt, **kwargs)\n        if zero_index:\n            p = 0\n        else:\n            p = 1\n        for indices in grouped:\n            sym_string = self.symbol + '_'\n            sym_string += ''.join([str(i + p) for i in indices[0]])\n            value = array[indices[0]]\n            if not np.isclose(value, 0):\n                d[sym_string] = array[indices[0]]\n        return d",
    "docstring": "Creates a summary dict for tensor with associated symbol\n\n        Args:\n            voigt (bool): whether to get symbol dict for voigt\n                notation tensor, as opposed to full notation,\n                defaults to true\n            zero_index (bool): whether to set initial index to zero,\n                defaults to false, since tensor notations tend to use\n                one-indexing, rather than zero indexing like python\n            **kwargs: keyword args for np.isclose.  Can take atol\n                and rtol for absolute and relative tolerance, e. g.\n\n                >>> tensor.get_symbol_dict(atol=1e-8)\n\n                or\n\n                >>> tensor.get_symbol_dict(rtol=1e-5)\n\n        Returns:\n            list of index groups where tensor values are equivalent to\n            within tolerances\n\n        Returns:"
  },
  {
    "code": "def sequence_length(fasta):\n    sequences = SeqIO.parse(fasta, \"fasta\")\n    records = {record.id: len(record) for record in sequences}\n    return records",
    "docstring": "return a dict of the lengths of sequences in a fasta file"
  },
  {
    "code": "def _get_custom_contract(param_contract):\n    if not isinstance(param_contract, str):\n        return None\n    for custom_contract in _CUSTOM_CONTRACTS:\n        if re.search(r\"\\b{0}\\b\".format(custom_contract), param_contract):\n            return custom_contract\n    return None",
    "docstring": "Return True if parameter contract is a custom contract, False otherwise."
  },
  {
    "code": "def on_delete(self, btn):\n        \"Flag this image as delete or keep.\"\n        btn.button_style = \"\" if btn.flagged_for_delete else \"danger\"\n        btn.flagged_for_delete = not btn.flagged_for_delete",
    "docstring": "Flag this image as delete or keep."
  },
  {
    "code": "def on_exception(self, exception):\n        logger.error('Exception from stream!', exc_info=True)\n        self.streaming_exception = exception",
    "docstring": "An exception occurred in the streaming thread"
  },
  {
    "code": "def connectionJustEstablished(self):\n        assert not self.disconnecting\n        assert not self.disconnected\n        try:\n            p = self.factory.buildProtocol(PTCPAddress(\n                    self.peerAddressTuple, self.pseudoPortPair))\n            p.makeConnection(self)\n        except:\n            log.msg(\"Exception during PTCP connection setup.\")\n            log.err()\n            self.loseConnection()\n        else:\n            self.protocol = p",
    "docstring": "We sent out SYN, they acknowledged it.  Congratulations, you\n        have a new baby connection."
  },
  {
    "code": "def load(self, id, *args, **kwargs):\n        self._pre_load(id, *args, **kwargs)\n        response = self._load(id, *args, **kwargs)\n        response = self._post_load(response, *args, **kwargs)\n        return response",
    "docstring": "loads a remote resource by id"
  },
  {
    "code": "def dump(self, zone, output_dir, lenient, split, source, *sources):\n        self.log.info('dump: zone=%s, sources=%s', zone, sources)\n        sources = [source] + list(sources)\n        try:\n            sources = [self.providers[s] for s in sources]\n        except KeyError as e:\n            raise Exception('Unknown source: {}'.format(e.args[0]))\n        clz = YamlProvider\n        if split:\n            clz = SplitYamlProvider\n        target = clz('dump', output_dir)\n        zone = Zone(zone, self.configured_sub_zones(zone))\n        for source in sources:\n            source.populate(zone, lenient=lenient)\n        plan = target.plan(zone)\n        if plan is None:\n            plan = Plan(zone, zone, [], False)\n        target.apply(plan)",
    "docstring": "Dump zone data from the specified source"
  },
  {
    "code": "def ParseNetworkDataUsage(\n      self, parser_mediator, cache=None, database=None, table=None,\n      **unused_kwargs):\n    self._ParseGUIDTable(\n        parser_mediator, cache, database, table,\n        self._NETWORK_DATA_USAGE_VALUES_MAP, SRUMNetworkDataUsageEventData)",
    "docstring": "Parses the network data usage monitor table.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      cache (Optional[ESEDBCache]): cache, which contains information about\n          the identifiers stored in the SruDbIdMapTable table.\n      database (Optional[pyesedb.file]): ESE database.\n      table (Optional[pyesedb.table]): table."
  },
  {
    "code": "def fin(self):\n        self.connection.fin(self.id)\n        self.processed = True",
    "docstring": "Indicate that this message is finished processing"
  },
  {
    "code": "def _get_index_urls_locations(self, project_name):\n        def mkurl_pypi_url(url):\n            loc = posixpath.join(\n                url,\n                urllib_parse.quote(canonicalize_name(project_name)))\n            if not loc.endswith('/'):\n                loc = loc + '/'\n            return loc\n        return [mkurl_pypi_url(url) for url in self.index_urls]",
    "docstring": "Returns the locations found via self.index_urls\n\n        Checks the url_name on the main (first in the list) index and\n        use this url_name to produce all locations"
  },
  {
    "code": "def generate_scheduling_block_id(num_blocks, project='test'):\n    _date = strftime(\"%Y%m%d\", gmtime())\n    _project = project\n    for i in range(num_blocks):\n        yield '{}-{}-sbi{:03d}'.format(_date, _project, i)",
    "docstring": "Generate a scheduling_block id"
  },
  {
    "code": "def _quantize_wp(wp, nbits, qm, axis=0, **kwargs):\n    scale = bias = lut = None\n    if qm == _QUANTIZATION_MODE_LINEAR_QUANTIZATION:\n        qw, scale, bias = _quantize_channelwise_linear(wp, nbits, axis)\n    elif qm == _QUANTIZATION_MODE_LOOKUP_TABLE_KMEANS:\n        lut, qw = _get_kmeans_lookup_table_and_weight(nbits, wp)\n    elif qm == _QUANTIZATION_MODE_CUSTOM_LOOKUP_TABLE:\n        if 'lut_function' not in kwargs.keys():\n            raise Exception('Custom lookup table quantization mode '\n                            'selected but no lookup table function passed')\n        lut_function = kwargs['lut_function']\n        if not callable(lut_function):\n            raise Exception('Argument for Lookup Table passed in but is '\n                            'not callable')\n        try:\n            lut, qw = lut_function(nbits, wp)\n        except Exception as e:\n            raise Exception('{}\\nCall to Lookup Table function failed'\n                            .format(e.message))\n    elif qm == _QUANTIZATION_MODE_LOOKUP_TABLE_LINEAR:\n        lut, qw = _get_linear_lookup_table_and_weight(nbits, wp)\n    else:\n        raise NotImplementedError('Quantization method \"{}\" not supported'.format(qm))\n    quantized_wp = _np.uint8(qw)\n    return scale, bias, lut, quantized_wp",
    "docstring": "Quantize the weight blob\n\n    :param wp: numpy.array\n        Weight parameters\n    :param nbits: int\n        Number of bits\n    :param qm:\n        Quantization mode\n    :param lut_function: (``callable function``)\n        Python callable representing a look-up table\n\n    Returns\n    -------\n    scale: numpy.array\n        Per-channel scale\n    bias: numpy.array\n        Per-channel bias\n    lut: numpy.array\n        Lookup table\n    quantized_wp: numpy.array\n        Quantized weight of same shape as wp, with dtype numpy.uint8"
  },
  {
    "code": "def _get_frdata(stream, num, name, ctype=None):\n    ctypes = (ctype,) if ctype else ('adc', 'proc', 'sim')\n    for ctype in ctypes:\n        _reader = getattr(stream, 'ReadFr{0}Data'.format(ctype.title()))\n        try:\n            return _reader(num, name)\n        except IndexError as exc:\n            if FRERR_NO_CHANNEL_OF_TYPE.match(str(exc)):\n                continue\n            raise\n    raise ValueError(\"no Fr{{Adc,Proc,Sim}}Data structures with the \"\n                     \"name {0}\".format(name))",
    "docstring": "Brute force-ish method to return the FrData structure for a channel\n\n    This saves on pulling the channel type from the TOC"
  },
  {
    "code": "def smart_guess_lexer(file_name, local_file):\n    lexer = None\n    text = get_file_head(file_name)\n    lexer1, accuracy1 = guess_lexer_using_filename(local_file or file_name, text)\n    lexer2, accuracy2 = guess_lexer_using_modeline(text)\n    if lexer1:\n        lexer = lexer1\n    if (lexer2 and accuracy2 and\n            (not accuracy1 or accuracy2 > accuracy1)):\n        lexer = lexer2\n    return lexer",
    "docstring": "Guess Pygments lexer for a file.\n\n    Looks for a vim modeline in file contents, then compares the accuracy\n    of that lexer with a second guess. The second guess looks up all lexers\n    matching the file name, then runs a text analysis for the best choice."
  },
  {
    "code": "def delete(self, key):\n    self._cur_batch.delete(key)\n    self._num_mutations += 1\n    if self._num_mutations >= MAX_MUTATIONS_IN_BATCH:\n      self.commit()\n      self.begin()",
    "docstring": "Adds deletion of the entity with given key to the mutation buffer.\n\n    If mutation buffer reaches its capacity then this method commit all pending\n    mutations from the buffer and emties it.\n\n    Args:\n      key: key of the entity which should be deleted"
  },
  {
    "code": "def most_seen_creators_by_works(work_kind=None, role_name=None, num=10):\n    return Creator.objects.by_works(kind=work_kind, role_name=role_name)[:num]",
    "docstring": "Returns a QuerySet of the Creators that are associated with the most Works."
  },
  {
    "code": "def hmget(self, hashkey, keys, *args):\n        redis_hash = self._get_hash(hashkey, 'HMGET')\n        attributes = self._list_or_args(keys, args)\n        return [redis_hash.get(self._encode(attribute)) for attribute in attributes]",
    "docstring": "Emulate hmget."
  },
  {
    "code": "def configure_stream_logger(logger='', level=None, formatter='%(levelname)-8s %(message)s'):\n\tlevel = level or logging.WARNING\n\tif isinstance(level, str):\n\t\tlevel = getattr(logging, level, None)\n\t\tif level is None:\n\t\t\traise ValueError('invalid log level: ' + level)\n\troot_logger = logging.getLogger('')\n\tfor handler in root_logger.handlers:\n\t\troot_logger.removeHandler(handler)\n\tlogging.getLogger(logger).setLevel(logging.DEBUG)\n\tconsole_log_handler = logging.StreamHandler()\n\tconsole_log_handler.setLevel(level)\n\tif isinstance(formatter, str):\n\t\tformatter = logging.Formatter(formatter)\n\telif not isinstance(formatter, logging.Formatter):\n\t\traise TypeError('formatter must be an instance of logging.Formatter')\n\tconsole_log_handler.setFormatter(formatter)\n\tlogging.getLogger(logger).addHandler(console_log_handler)\n\tlogging.captureWarnings(True)\n\treturn console_log_handler",
    "docstring": "Configure the default stream handler for logging messages to the console,\n\tremove other logging handlers, and enable capturing warnings.\n\n\t.. versionadded:: 1.3.0\n\n\t:param str logger: The logger to add the stream handler for.\n\t:param level: The level to set the logger to, will default to WARNING if no level is specified.\n\t:type level: None, int, str\n\t:param formatter: The format to use for logging messages to the console.\n\t:type formatter: str, :py:class:`logging.Formatter`\n\t:return: The new configured stream handler.\n\t:rtype: :py:class:`logging.StreamHandler`"
  },
  {
    "code": "def snake_to_camel(value):\n    camel = \"\".join(word.title() for word in value.split(\"_\"))\n    return value[:1].lower() + camel[1:]",
    "docstring": "Converts a snake_case_string to a camelCaseString.\n\n    >>> snake_to_camel(\"foo_bar_baz\")\n    'fooBarBaz'"
  },
  {
    "code": "def mutate(self, row):\n        mutation_count = len(row._get_mutations())\n        if mutation_count > MAX_MUTATIONS:\n            raise MaxMutationsError(\n                \"The row key {} exceeds the number of mutations {}.\".format(\n                    row.row_key, mutation_count\n                )\n            )\n        if (self.total_mutation_count + mutation_count) >= MAX_MUTATIONS:\n            self.flush()\n        self.rows.append(row)\n        self.total_mutation_count += mutation_count\n        self.total_size += row.get_mutations_size()\n        if self.total_size >= self.max_row_bytes or len(self.rows) >= self.flush_count:\n            self.flush()",
    "docstring": "Add a row to the batch. If the current batch meets one of the size\n        limits, the batch is sent synchronously.\n\n        For example:\n\n        .. literalinclude:: snippets.py\n            :start-after: [START bigtable_batcher_mutate]\n            :end-before: [END bigtable_batcher_mutate]\n\n        :type row: class\n        :param row: class:`~google.cloud.bigtable.row.DirectRow`.\n\n        :raises: One of the following:\n                 * :exc:`~.table._BigtableRetryableError` if any\n                   row returned a transient error.\n                 * :exc:`RuntimeError` if the number of responses doesn't\n                   match the number of rows that were retried\n                 * :exc:`.batcher.MaxMutationsError` if any row exceeds max\n                   mutations count."
  },
  {
    "code": "def inserir(self, name):\n        net_type_map = dict()\n        net_type_map['name'] = name\n        code, xml = self.submit(\n            {'net_type': net_type_map}, 'POST', 'net_type/')\n        return self.response(code, xml)",
    "docstring": "Insert new network type and return its identifier.\n\n        :param name: Network type name.\n\n        :return: Following dictionary: {'net_type': {'id': < id >}}\n\n        :raise InvalidParameterError: Network type is none or invalid.\n        :raise NomeTipoRedeDuplicadoError: A network type with this name already exists.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def update(self):\n        stats = self.get_init_value()\n        if self.input_method == 'local':\n            for k, v in iteritems(self.glances_amps.update()):\n                stats.append({'key': k,\n                              'name': v.NAME,\n                              'result': v.result(),\n                              'refresh': v.refresh(),\n                              'timer': v.time_until_refresh(),\n                              'count': v.count(),\n                              'countmin': v.count_min(),\n                              'countmax': v.count_max()})\n        else:\n            pass\n        self.stats = stats\n        return self.stats",
    "docstring": "Update the AMP list."
  },
  {
    "code": "def standardize_names_groundings(stmts):\n    print('Standardize names to groundings')\n    for stmt in stmts:\n        for concept in stmt.agent_list():\n            db_ns, db_id = concept.get_grounding()\n            if db_id is not None:\n                if isinstance(db_id, list):\n                    db_id = db_id[0][0].split('/')[-1]\n                else:\n                    db_id = db_id.split('/')[-1]\n                db_id = db_id.replace('|', ' ')\n                db_id = db_id.replace('_', ' ')\n                db_id = db_id.replace('ONT::', '')\n                db_id = db_id.capitalize()\n                concept.name = db_id\n    return stmts",
    "docstring": "Standardize the names of Concepts with respect to an ontology.\n\n    NOTE: this function is currently optimized for Influence Statements\n    obtained from Eidos, Hume, Sofia and CWMS. It will possibly yield\n    unexpected results for biology-specific Statements."
  },
  {
    "code": "def mode(self, set_bytes):\n        self._mode = set_bytes\n        data = [self.ISS_CMD, self.ISS_SET_MODE] + set_bytes\n        self.write_data(data)\n        response = self.read_data(2)\n        if response[0] == 0:\n            error_dict = {\n                0x05: 'Unknown Command',\n                0x06: 'Internal Error 1',\n                0x07: 'Internal Error 2'\n            }\n            try:\n                raise USBISSError(error_dict[response(1)])\n            except KeyError:\n                raise USBISSError('Undocumented Error')",
    "docstring": "Set the operating protocol of the USB-ISS with additional\n        parameters for the  protocol"
  },
  {
    "code": "def set_close_callback(self, cb):\n        assert self._close_cb is None, (\n            'A close_callback has already been set for this connection.'\n        )\n        self._close_cb = stack_context.wrap(cb)\n        if self.closed:\n            self._close_cb()",
    "docstring": "Specify a function to be called when this connection is closed.\n\n        :param cb:\n            A callable that takes no arguments. This callable will be called\n            when this connection is closed."
  },
  {
    "code": "def _get_access_token(self, verifier=None):\n        response, content = self.client(verifier).request(\n            self.access_token_url, \"POST\")\n        content = smart_unicode(content)\n        if not response['status'] == '200':\n            raise OAuthError(_(\n                u\"Invalid status code %s while obtaining access token from %s: %s\") % \n                (response['status'], self.access_token_url, content))\n        token = dict(urlparse.parse_qsl(content))\n        return (oauth.Token(token['oauth_token'], token['oauth_token_secret']),\n            token)",
    "docstring": "Fetch an access token from `self.access_token_url`."
  },
  {
    "code": "def _ttl(self):\n        return self.hlim if isinstance(self, scapy.layers.inet6.IPv6) else self.ttl",
    "docstring": "Returns ttl or hlim, depending on the IP version"
  },
  {
    "code": "def register_element(self, model, idx):\n        if idx is None:\n            idx = model + '_' + str(len(self._idx_model))\n        self._idx_model[idx] = model\n        self._idx.append(idx)\n        return idx",
    "docstring": "Register element with index ``idx`` to ``model``\n\n        :param model: model name\n        :param idx: element idx\n        :return: final element idx"
  },
  {
    "code": "def create_cfg(self, cfg_file, defaults=None, mode='json'):\n        assert mode in ('json', 'yaml')\n        self.cfg_mode = mode\n        self.cfg_file = cfg_file\n        try:\n            self.cfg = CfgDict(app=self, cfg=self.load_cfg())\n            logging.info('cfg file found : %s' % self.cfg_file)\n        except FileNotFoundError:\n            self.cfg = CfgDict(app=self, cfg={'first_run': True})\n            with suppress(TypeError):\n                self.cfg.update(defaults)\n            self.cfg.save()\n            set_windows_permissions(self.cfg_file)\n            logging.info(\n                'Created cfg file for first time!: %s' %\n                self.cfg_file)\n        if self._check_first_run():\n            self.first_run = True\n        else:\n            self.first_run = False",
    "docstring": "set mode to json or yaml? probably remove this option..Todo\n\n        Creates the config file for your app with default values\n        The file will only be created if it doesn't exits\n\n        also sets up the first_run attribute.\n\n        also sets correct windows permissions\n\n        you can add custom stuff to the config by doing\n        app.cfg['fkdsfa'] = 'fdsaf'\n        # todo auto save on change\n        remember to call cfg.save()"
  },
  {
    "code": "def future(self, request, timeout=None, metadata=None, credentials=None):\n        return _utils.wrap_future_call(self._inner.future(request, timeout, metadata, credentials),\n                                       self._loop, self._executor)",
    "docstring": "Asynchronously invokes the underlying RPC.\n\n    Args:\n      request: The request value for the RPC.\n      timeout: An optional duration of time in seconds to allow for the RPC.\n      metadata: Optional :term:`metadata` to be transmitted to the\n        service-side of the RPC.\n      credentials: An optional CallCredentials for the RPC.\n\n    Returns:\n        An object that is both a Call for the RPC and a Future. In the event of\n        RPC completion, the return Call-Future's result value will be the\n        response message of the RPC. Should the event terminate with non-OK\n        status, the returned Call-Future's exception value will be an RpcError."
  },
  {
    "code": "def top(**kwargs):\n    if 'id' not in kwargs['opts']:\n        return {}\n    cmd = '{0} {1}'.format(\n            __opts__['master_tops']['ext_nodes'],\n            kwargs['opts']['id']\n            )\n    ndata = salt.utils.yaml.safe_load(\n        subprocess.Popen(\n            cmd,\n            shell=True,\n            stdout=subprocess.PIPE).communicate()[0]\n    )\n    if not ndata:\n        log.info('master_tops ext_nodes call did not return any data')\n    ret = {}\n    if 'environment' in ndata:\n        env = ndata['environment']\n    else:\n        env = 'base'\n    if 'classes' in ndata:\n        if isinstance(ndata['classes'], dict):\n            ret[env] = list(ndata['classes'])\n        elif isinstance(ndata['classes'], list):\n            ret[env] = ndata['classes']\n        else:\n            return ret\n    else:\n        log.info('master_tops ext_nodes call did not have a dictionary with a \"classes\" key.')\n    return ret",
    "docstring": "Run the command configured"
  },
  {
    "code": "def _guess_package(self, path):\n    supported_prefixes = ('com', 'org', 'net',)\n    package = ''\n    slash = path.rfind(os.path.sep)\n    prefix_with_slash = max(path.rfind(os.path.join('', prefix, ''))\n                            for prefix in supported_prefixes)\n    if prefix_with_slash < 0:\n      package = path[:slash]\n    elif prefix_with_slash >= 0:\n      package = path[prefix_with_slash:slash]\n    package = package.replace(os.path.sep, ' ')\n    package = package.strip().replace(' ', '.')\n    return package",
    "docstring": "Used in execute_codegen to actually invoke the compiler with the proper arguments, and in\n    _sources_to_be_generated to declare what the generated files will be."
  },
  {
    "code": "def fill_form(form, data):\n    for (key, value) in data.items():\n        if hasattr(form, key):\n            if isinstance(value, dict):\n                fill_form(getattr(form, key), value)\n            else:\n                getattr(form, key).data = value\n    return form",
    "docstring": "Prefill form with data.\n\n    :param form: The form to fill.\n    :param data: The data to insert in the form.\n    :returns: A pre-filled form."
  },
  {
    "code": "def get_role(role_id,**kwargs):\n    try:\n        role = db.DBSession.query(Role).filter(Role.id==role_id).one()\n        return role\n    except NoResultFound:\n        raise HydraError(\"Role not found (role_id={})\".format(role_id))",
    "docstring": "Get a role by its ID."
  },
  {
    "code": "def read_string(self, len):\n        format = '!' + str(len) + 's'\n        length = struct.calcsize(format)\n        info = struct.unpack(format,\n                self.data[self.offset:self.offset + length])\n        self.offset += length\n        return info[0]",
    "docstring": "Reads a string of a given length from the packet"
  },
  {
    "code": "def query(self, query):\n    path = self.path(query.key)\n    if os.path.exists(path):\n      filenames = os.listdir(path)\n      filenames = list(set(filenames) - set(self.ignore_list))\n      filenames = map(lambda f: os.path.join(path, f), filenames)\n      iterable = self._read_object_gen(filenames)\n    else:\n      iterable = list()\n    return query(iterable)",
    "docstring": "Returns an iterable of objects matching criteria expressed in `query`\n    FSDatastore.query queries all the `.obj` files within the directory\n    specified by the query.key.\n\n    Args:\n      query: Query object describing the objects to return.\n\n    Raturns:\n      Cursor with all objects matching criteria"
  },
  {
    "code": "def parse_blockwise(value):\n    length = byte_len(value)\n    if length == 1:\n        num = value & 0xF0\n        num >>= 4\n        m = value & 0x08\n        m >>= 3\n        size = value & 0x07\n    elif length == 2:\n        num = value & 0xFFF0\n        num >>= 4\n        m = value & 0x0008\n        m >>= 3\n        size = value & 0x0007\n    else:\n        num = value & 0xFFFFF0\n        num >>= 4\n        m = value & 0x000008\n        m >>= 3\n        size = value & 0x000007\n    return num, int(m), pow(2, (size + 4))",
    "docstring": "Parse Blockwise option.\n\n    :param value: option value\n    :return: num, m, size"
  },
  {
    "code": "def split(args):\n    p = OptionParser(split.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n    gffile, outdir = args\n    mkdir(outdir)\n    g = Gff(gffile)\n    seqids = g.seqids\n    for s in seqids:\n        outfile = op.join(outdir, s + \".gff\")\n        extract([gffile, \"--contigs=\" + s, \"--outfile=\" + outfile])",
    "docstring": "%prog split gffile outdir\n\n    Split the gff into one contig per file. Will also take sequences if the file\n    contains FASTA sequences."
  },
  {
    "code": "def returnOneEntry(self, last=False):\n        if len(self.table)==0:\n            return None\n        else:\n            if last:\n                return self.table[len(self.table)-1]\n            else:\n                return self.table[0]",
    "docstring": "Return the first entry in the current list. If 'last=True', then\n        the last entry is returned.\"\n\n        Returns None is the list is empty.\n\n        Example of use:\n\n        >>> test = [\n        ...    {\"name\": \"Jim\",   \"age\": 18, \"income\": 93000, \"order\": 2},\n        ...    {\"name\": \"Larry\", \"age\": 18,                  \"order\": 3},\n        ...    {\"name\": \"Joe\",   \"age\": 20, \"income\": 15000, \"order\": 1},\n        ...    {\"name\": \"Bill\",  \"age\": 19, \"income\": 29000, \"order\": 4},\n        ... ]\n        >>> print PLOD(test).returnOneEntry()\n        {'age': 18, 'order': 2, 'name': 'Jim', 'income': 93000}\n        >>> print PLOD(test).returnOneEntry(last=True)\n        {'age': 19, 'order': 4, 'name': 'Bill', 'income': 29000}\n\n        :param last:\n           If True, the last entry is returned rather than the first.\n        :return:\n           A list entry, or None if the list is empty."
  },
  {
    "code": "def emit(self, span_datas):\n        try:\n            zipkin_spans = self.translate_to_zipkin(span_datas)\n            result = requests.post(\n                url=self.url,\n                data=json.dumps(zipkin_spans),\n                headers=ZIPKIN_HEADERS)\n            if result.status_code not in SUCCESS_STATUS_CODE:\n                logging.error(\n                    \"Failed to send spans to Zipkin server! Spans are {}\"\n                    .format(zipkin_spans))\n        except Exception as e:\n            logging.error(getattr(e, 'message', e))",
    "docstring": "Send SpanData tuples to Zipkin server, default using the v2 API.\n\n        :type span_datas: list of :class:\n            `~opencensus.trace.span_data.SpanData`\n        :param list of opencensus.trace.span_data.SpanData span_datas:\n            SpanData tuples to emit"
  },
  {
    "code": "def genome_name_from_fasta_path(fasta_path):\n    filename = os.path.basename(fasta_path)\n    return re.sub(r'(\\.fa$)|(\\.fas$)|(\\.fasta$)|(\\.fna$)|(\\.\\w{1,}$)', '', filename)",
    "docstring": "Extract genome name from fasta filename\n\n    Get the filename without directory and remove the file extension.\n\n    Example:\n        With fasta file path ``/path/to/genome_1.fasta``::\n\n            fasta_path = '/path/to/genome_1.fasta'\n            genome_name = genome_name_from_fasta_path(fasta_path)\n            print(genome_name)\n            # => \"genome_1\"\n\n    Args:\n        fasta_path (str): fasta file path\n\n    Returns:\n        str: genome name"
  },
  {
    "code": "def hdf5(self):\n        if self._rundir['hdf5'] is UNDETERMINED:\n            h5_folder = self.path / self.par['ioin']['hdf5_output_folder']\n            if (h5_folder / 'Data.xmf').is_file():\n                self._rundir['hdf5'] = h5_folder\n            else:\n                self._rundir['hdf5'] = None\n        return self._rundir['hdf5']",
    "docstring": "Path of output hdf5 folder if relevant, None otherwise."
  },
  {
    "code": "def control(controllee: Union['cirq.Gate', op_tree.OP_TREE],\n            control_qubits: Sequence['cirq.Qid'] = None,\n            default: Any = RaiseTypeErrorIfNotProvided) -> Any:\n    if control_qubits is None:\n        control_qubits = []\n    controller = getattr(controllee, 'controlled_by', None)\n    result = NotImplemented if controller is None else controller(\n                                                           *control_qubits)\n    if result is not NotImplemented:\n        return result\n    if isinstance(controllee, collections.Iterable):\n        return op_tree.transform_op_tree(\n            controllee,\n            op_transformation=lambda op: control(op, control_qubits))\n    if default is not RaiseTypeErrorIfNotProvided:\n        return default\n    if controller is None:\n        raise TypeError(\"object of type '{}' has no controlled_by \"\n                        \"method.\".format(type(controllee)))\n    raise TypeError(\"object of type '{}' does have a controlled_by method, \"\n                    \"but it returned NotImplemented.\".format(type(controllee)))",
    "docstring": "Returns a Controlled version of the given value, if defined.\n\n    Controllees define how to be controlled by defining a method\n    controlled_by(self, control_qubits). Note that the method may return\n    NotImplemented to indicate a particular controlling can't be done.\n\n    Args:\n        controllee: The gate, operation or iterable of operations to control.\n        control_qubits: A list of Qids that would control this controllee.\n        default: Determines the fallback behavior when `controllee` doesn't\n            have a controlling defined. If `default` is not set and the\n            fallback occurs, a TypeError is raised instead.\n\n    Returns:\n        If `controllee` has a controlled_by method that returns something\n        besides NotImplemented, that result is returned. For an OP_TREE,\n        transformation is applied at the leaf. Otherwise, if a default value\n        was specified, the default value is returned.\n\n    Raises:\n        TypeError: `controllee` doesn't have a controlled_by method (or that\n            method returned NotImplemented) and no `default` was specified."
  },
  {
    "code": "def gpu_load(wproc=0.5, wmem=0.5):\n    GPULoad = namedtuple('GPULoad', ['processor', 'memory', 'weighted'])\n    gpus = GPUtil.getGPUs()\n    load = []\n    for g in gpus:\n        wload = (wproc * g.load + wmem * g.memoryUtil) / (wproc + wmem)\n        load.append(GPULoad(g.load, g.memoryUtil, wload))\n    return load",
    "docstring": "Return a list of namedtuples representing the current load for\n    each GPU device. The processor and memory loads are fractions\n    between 0 and 1. The weighted load represents a weighted average\n    of processor and memory loads using the parameters `wproc` and\n    `wmem` respectively."
  },
  {
    "code": "def _inquire(self, **kwargs):\n        if rname_rfc6680 is None:\n            raise NotImplementedError(\"Your GSSAPI implementation does not \"\n                                      \"support RFC 6680 (the GSSAPI naming \"\n                                      \"extensions)\")\n        if not kwargs:\n            default_val = True\n        else:\n            default_val = False\n        attrs = kwargs.get('attrs', default_val)\n        mech_name = kwargs.get('mech_name', default_val)\n        return rname_rfc6680.inquire_name(self, mech_name=mech_name,\n                                          attrs=attrs)",
    "docstring": "Inspect this name for information.\n\n        This method inspects the name for information.\n\n        If no keyword arguments are passed, all available information\n        is returned.  Otherwise, only the keyword arguments that\n        are passed and set to `True` are returned.\n\n        Args:\n            mech_name (bool): get whether this is a mechanism name,\n                and, if so, the associated mechanism\n            attrs (bool): get the attributes names for this name\n\n        Returns:\n            InquireNameResult: the results of the inquiry, with unused\n                fields set to None\n\n        Raises:\n            GSSError"
  },
  {
    "code": "def _check_filter_specific_md(self, specific_md: list):\n        if isinstance(specific_md, list):\n            if len(specific_md) > 0:\n                for md in specific_md:\n                    if not self.check_is_uuid(md):\n                        specific_md.remove(md)\n                        logging.error(\"Metadata UUID is not correct: {}\".format(md))\n                specific_md = \",\".join(specific_md)\n            else:\n                specific_md = \"\"\n        else:\n            raise TypeError(\"'specific_md' expects a list\")\n        return specific_md",
    "docstring": "Check if specific_md parameter is valid.\n\n        :param list specific_md: list of specific metadata UUID to check"
  },
  {
    "code": "async def extend(self, additional_time):\n        if self.local.token is None:\n            raise LockError(\"Cannot extend an unlocked lock\")\n        if self.timeout is None:\n            raise LockError(\"Cannot extend a lock with no timeout\")\n        return await self.do_extend(additional_time)",
    "docstring": "Adds more time to an already acquired lock.\n\n        ``additional_time`` can be specified as an integer or a float, both\n        representing the number of seconds to add."
  },
  {
    "code": "def until_state(self, state, timeout=None):\n        return self._state.until_state(state, timeout=timeout)",
    "docstring": "Future that resolves when a certain client state is attained\n\n        Parameters\n        ----------\n\n        state : str\n            Desired state, one of (\"disconnected\", \"syncing\", \"synced\")\n        timeout: float\n            Timeout for operation in seconds."
  },
  {
    "code": "def parse_n3(row, src='csv'):\n    if row.strip() == '':\n        return '',''\n    l_root = 'opencyc'\n    key = ''\n    val = ''\n    if src == 'csv': \n        cols = row.split(',')\n        if len(cols) < 3:\n            return '',''\n        key = ''\n        val = ''\n        key = l_root + ':' + cols[1].strip('\"').strip() + ':' + cols[2].strip('\"').strip()\n        try:\n            val = cols[3].strip('\"').strip()\n        except Exception:\n            val = \"Error parsing \" + row\n    elif src == 'n3':\n        pass\n    return key, val",
    "docstring": "takes a row from an n3 file and returns the triple\n    NOTE - currently parses a CSV line already split via\n    cyc_extract.py"
  },
  {
    "code": "def geojson(self):\n        return {\n            \"type\": \"FeatureCollection\",\n            \"features\": [f.geojson(i) for i, f in self._features.items()]\n        }",
    "docstring": "Render features as a FeatureCollection."
  },
  {
    "code": "def _load_config_file(self):\n        with open(self._config_file) as f:\n            config = yaml.safe_load(f)\n            patch_config(config, self.__environment_configuration)\n            return config",
    "docstring": "Loads config.yaml from filesystem and applies some values which were set via ENV"
  },
  {
    "code": "def get_resource_pool(self, cluster, pool_name):\n        pool_obj = None\n        cluster_pools_list = cluster.resourcePool.resourcePool\n        pool_selections = self.get_obj(\n            [vim.ResourcePool],\n            pool_name,\n            return_all=True\n        )\n        if pool_selections:\n            for p in pool_selections:\n                if p in cluster_pools_list:\n                    pool_obj = p\n                    break\n        return pool_obj",
    "docstring": "Find a resource pool given a pool name for desired cluster"
  },
  {
    "code": "def save(self, async=False, callback=None, encrypted=True):\n        if self._new_password and encrypted:\n            self.password = Sha1.encrypt(self._new_password)\n        controller = NURESTSession.get_current_session().login_controller\n        controller.password = self._new_password\n        controller.api_key = None\n        data = json.dumps(self.to_dict())\n        request = NURESTRequest(method=HTTP_METHOD_PUT, url=self.get_resource_url(), data=data)\n        if async:\n            return self.send_request(request=request, async=async, local_callback=self._did_save, remote_callback=callback)\n        else:\n            connection = self.send_request(request=request)\n            return self._did_save(connection)",
    "docstring": "Updates the user and perform the callback method"
  },
  {
    "code": "def get_image_dimensions(request):\n        if request.service_type is ServiceType.WCS or (isinstance(request.size_x, int) and\n                                                       isinstance(request.size_y, int)):\n            return request.size_x, request.size_y\n        if not isinstance(request.size_x, int) and not isinstance(request.size_y, int):\n            raise ValueError(\"At least one of parameters 'width' and 'height' must have an integer value\")\n        missing_dimension = get_image_dimension(request.bbox, width=request.size_x, height=request.size_y)\n        if request.size_x is None:\n            return missing_dimension, request.size_y\n        if request.size_y is None:\n            return request.size_x, missing_dimension\n        raise ValueError(\"Parameters 'width' and 'height' must be integers or None\")",
    "docstring": "Verifies or calculates image dimensions.\n\n        :param request: OGC-type request\n        :type request: WmsRequest or WcsRequest\n        :return: horizontal and vertical dimensions of requested image\n        :rtype: (int or str, int or str)"
  },
  {
    "code": "def getPackage(self, name, **kwargs):\n        packageinfo = yield self.call('getPackage', name, **kwargs)\n        package = Package.fromDict(packageinfo)\n        if package:\n            package.connection = self\n        defer.returnValue(package)",
    "docstring": "Load information about a package and return a custom Package class.\n\n        Calls \"getPackage\" XML-RPC.\n\n        :param package_id: ``int``, for example 12345\n        :returns: deferred that when fired returns a Package (Munch, dict-like)\n                  object representing this Koji package, or None if no build\n                  was found."
  },
  {
    "code": "def alt_click(self, locator, params=None, timeout=None):\n        self._click(locator, params, timeout, Keys.ALT)",
    "docstring": "Alt-click web element.\n\n        :param locator: locator tuple or WebElement instance\n        :param params: (optional) locator parameters\n        :param timeout: (optional) time to wait for element\n        :return: None"
  },
  {
    "code": "def add_prefix(self, prefix, flags, prf):\n        self._req('prefix add %s %s %s' % (prefix, flags, prf))\n        time.sleep(1)\n        self._req('netdataregister')",
    "docstring": "Add network prefix.\n\n        Args:\n            prefix (str): network prefix.\n            flags (str): network prefix flags, please refer thread documentation for details\n            prf (str): network prf, please refer thread documentation for details"
  },
  {
    "code": "async def start_serving(self, address=None, sockets=None,\n                            backlog=100, sslcontext=None):\n        if self._server:\n            raise RuntimeError('Already serving')\n        create_server = self._loop.create_server\n        server = None\n        if sockets:\n            for sock in sockets:\n                srv = await create_server(self.create_protocol,\n                                          sock=sock,\n                                          backlog=backlog,\n                                          ssl=sslcontext)\n                if server:\n                    server.sockets.extend(srv.sockets)\n                else:\n                    server = srv\n        elif isinstance(address, tuple):\n            server = await create_server(self.create_protocol,\n                                         host=address[0],\n                                         port=address[1],\n                                         backlog=backlog,\n                                         ssl=sslcontext)\n        else:\n            raise RuntimeError('sockets or address must be supplied')\n        self._set_server(server)",
    "docstring": "Start serving.\n\n        :param address: optional address to bind to\n        :param sockets: optional list of sockets to bind to\n        :param backlog: Number of maximum connections\n        :param sslcontext: optional SSLContext object"
  },
  {
    "code": "def set_system_time(self, time_source, ntp_server, date_format,\n                        time_format, time_zone, is_dst, dst, year,\n                        mon, day, hour, minute, sec, callback=None):\n        if ntp_server not in ['time.nist.gov',\n                              'time.kriss.re.kr',\n                              'time.windows.com',\n                              'time.nuri.net',\n                             ]:\n            raise ValueError('Unsupported ntpServer')\n        params = {'timeSource': time_source,\n                  'ntpServer' : ntp_server,\n                  'dateFormat': date_format,\n                  'timeFormat': time_format,\n                  'timeZone'  : time_zone,\n                  'isDst'     : is_dst,\n                  'dst'       : dst,\n                  'year'      : year,\n                  'mon'       : mon,\n                  'day'       : day,\n                  'hour'      : hour,\n                  'minute'    : minute,\n                  'sec'       : sec\n                 }\n        return self.execute_command('setSystemTime', params, callback=callback)",
    "docstring": "Set systeim time"
  },
  {
    "code": "def add_ignore(self, depend):\n        try:\n            self._add_child(self.ignore, self.ignore_set, depend)\n        except TypeError as e:\n            e = e.args[0]\n            if SCons.Util.is_List(e):\n                s = list(map(str, e))\n            else:\n                s = str(e)\n            raise SCons.Errors.UserError(\"attempted to ignore a non-Node dependency of %s:\\n\\t%s is a %s, not a Node\" % (str(self), s, type(e)))",
    "docstring": "Adds dependencies to ignore."
  },
  {
    "code": "def set_historylog(self, historylog):\r\n        historylog.add_history(self.shell.history_filename)\r\n        self.shell.append_to_history.connect(historylog.append_to_history)",
    "docstring": "Bind historylog instance to this console\r\n        Not used anymore since v2.0"
  },
  {
    "code": "def getCallSet(self, id_):\n        if id_ not in self._callSetIdMap:\n            raise exceptions.CallSetNotFoundException(id_)\n        return self._callSetIdMap[id_]",
    "docstring": "Returns a CallSet with the specified id, or raises a\n        CallSetNotFoundException if it does not exist."
  },
  {
    "code": "def and_(*fs):\n    ensure_argcount(fs, min_=1)\n    fs = list(imap(ensure_callable, fs))\n    if len(fs) == 1:\n        return fs[0]\n    if len(fs) == 2:\n        f1, f2 = fs\n        return lambda *args, **kwargs: (\n            f1(*args, **kwargs) and f2(*args, **kwargs))\n    if len(fs) == 3:\n        f1, f2, f3 = fs\n        return lambda *args, **kwargs: (\n            f1(*args, **kwargs) and f2(*args, **kwargs) and f3(*args, **kwargs))\n    def g(*args, **kwargs):\n        for f in fs:\n            if not f(*args, **kwargs):\n                return False\n        return True\n    return g",
    "docstring": "Creates a function that returns true for given arguments\n    iff every given function evalutes to true for those arguments.\n\n    :param fs: Functions to combine\n\n    :return: Short-circuiting function performing logical conjunction\n             on results of ``fs`` applied to its arguments"
  },
  {
    "code": "def cancel_lb(self, loadbal_id):\n        lb_billing = self.lb_svc.getBillingItem(id=loadbal_id)\n        billing_id = lb_billing['id']\n        billing_item = self.client['Billing_Item']\n        return billing_item.cancelService(id=billing_id)",
    "docstring": "Cancels the specified load balancer.\n\n        :param int loadbal_id: Load Balancer ID to be cancelled."
  },
  {
    "code": "def install (self):\n        outs = super(MyInstallLib, self).install()\n        infile = self.create_conf_file()\n        outfile = os.path.join(self.install_dir, os.path.basename(infile))\n        self.copy_file(infile, outfile)\n        outs.append(outfile)\n        return outs",
    "docstring": "Install the generated config file."
  },
  {
    "code": "def debug_complete():\n    if not 'uniqueId' in request.args:\n        raise ExperimentError('improper_inputs')\n    else:\n        unique_id = request.args['uniqueId']\n        mode = request.args['mode']\n        try:\n            user = Participant.query.\\\n                filter(Participant.uniqueid == unique_id).one()\n            user.status = COMPLETED\n            user.endhit = datetime.datetime.now()\n            db_session.add(user)\n            db_session.commit()\n        except:\n            raise ExperimentError('error_setting_worker_complete')\n        else:\n            if (mode == 'sandbox' or mode == 'live'):\n                return render_template('closepopup.html')\n            else:\n                return render_template('complete.html')",
    "docstring": "Debugging route for complete."
  },
  {
    "code": "def mpool(self,\n              k_height,\n              k_width,\n              d_height=2,\n              d_width=2,\n              mode=\"VALID\",\n              input_layer=None,\n              num_channels_in=None):\n        return self._pool(\"mpool\", pooling_layers.max_pooling2d, k_height,\n                          k_width, d_height, d_width, mode, input_layer,\n                          num_channels_in)",
    "docstring": "Construct a max pooling layer."
  },
  {
    "code": "def cleanup():\n        for install_dir in linters.INSTALL_DIRS:\n            try:\n                shutil.rmtree(install_dir, ignore_errors=True)\n            except Exception:\n                print(\n                    \"{0}\\nFailed to delete {1}\".format(\n                        traceback.format_exc(), install_dir\n                    )\n                )\n                sys.stdout.flush()",
    "docstring": "Delete standard installation directories."
  },
  {
    "code": "def set_log_level(verbose, match=None, return_old=False):\n    if isinstance(verbose, bool):\n        verbose = 'info' if verbose else 'warning'\n    if isinstance(verbose, string_types):\n        verbose = verbose.lower()\n        if verbose not in logging_types:\n            raise ValueError('Invalid argument \"%s\"' % verbose)\n        verbose = logging_types[verbose]\n    else:\n        raise TypeError('verbose must be a bool or string')\n    logger = logging.getLogger('vispy')\n    old_verbose = logger.level\n    old_match = _lh._vispy_set_match(match)\n    logger.setLevel(verbose)\n    if verbose <= logging.DEBUG:\n        _lf._vispy_set_prepend(True)\n    else:\n        _lf._vispy_set_prepend(False)\n    out = None\n    if return_old:\n        out = (old_verbose, old_match)\n    return out",
    "docstring": "Convenience function for setting the logging level\n\n    Parameters\n    ----------\n    verbose : bool, str, int, or None\n        The verbosity of messages to print. If a str, it can be either DEBUG,\n        INFO, WARNING, ERROR, or CRITICAL. Note that these are for\n        convenience and are equivalent to passing in logging.DEBUG, etc.\n        For bool, True is the same as 'INFO', False is the same as 'WARNING'.\n    match : str | None\n        String to match. Only those messages that both contain a substring\n        that regexp matches ``'match'`` (and the ``verbose`` level) will be\n        displayed.\n    return_old : bool\n        If True, return the old verbosity level and old match.\n\n    Notes\n    -----\n    If ``verbose=='debug'``, then the ``vispy`` method emitting the log\n    message will be prepended to each log message, which is useful for\n    debugging. If ``verbose=='debug'`` or ``match is not None``, then a\n    small performance overhead is added. Thus it is suggested to only use\n    these options when performance is not crucial.\n\n    See also\n    --------\n    vispy.util.use_log_level"
  },
  {
    "code": "def ToByteArray(self):\n    lc = self.InternalEncodeLc()\n    out = bytearray(4)\n    out[0] = self.cla\n    out[1] = self.ins\n    out[2] = self.p1\n    out[3] = self.p2\n    if self.data:\n      out.extend(lc)\n      out.extend(self.data)\n      out.extend([0x00, 0x00])\n    else:\n      out.extend([0x00, 0x00, 0x00])\n    return out",
    "docstring": "Serialize the command.\n\n    Encodes the command as per the U2F specs, using the standard\n    ISO 7816-4 extended encoding.  All Commands expect data, so\n    Le is always present.\n\n    Returns:\n      Python bytearray of the encoded command."
  },
  {
    "code": "def demote_admin(self, group_jid, peer_jid):\n        log.info(\"[+] Demoting user {} to a regular member in group {}\".format(peer_jid, group_jid))\n        return self._send_xmpp_element(group_adminship.DemoteAdminRequest(group_jid, peer_jid))",
    "docstring": "Turns an admin of a group into a regular user with no amidships capabilities.\n\n        :param group_jid: The group JID in which the rights apply\n        :param peer_jid: The admin user to demote\n        :return:"
  },
  {
    "code": "def ok_hash(token: str) -> bool:\n        LOGGER.debug('Tails.ok_hash >>> token: %s', token)\n        rv = re.match('[{}]{{42,44}}$'.format(B58), token) is not None\n        LOGGER.debug('Tails.ok_hash <<< %s', rv)\n        return rv",
    "docstring": "Whether input token looks like a valid tails hash.\n\n        :param token: candidate string\n        :return: whether input token looks like a valid tails hash"
  },
  {
    "code": "def _construct_filename(self, batchno):\n        return os.path.join(self.dirpath,\n                            \"{0}.{1}\".format(self.prefix, batchno))",
    "docstring": "Construct a filename for a database.\n\n        Parameters:\n        batchno -- batch number for the rotated database.\n\n        Returns the constructed path as a string."
  },
  {
    "code": "def expires(self):\n        not_after = self._cert.get_notAfter().decode('ascii')\n        return datetime.datetime.strptime(not_after, '%Y%m%d%H%M%SZ').replace(\n            tzinfo=datetime.timezone.utc)",
    "docstring": "The date and time after which the certificate will be considered invalid."
  },
  {
    "code": "def _handle_conflict(self, name):\n        err = HTTPConflict('Member \"%s\" already exists!' % name).exception\n        return self.request.get_response(err)",
    "docstring": "Handles requests that triggered a conflict.\n\n        Respond with a 409 \"Conflict\""
  },
  {
    "code": "def get_file_md5sum(path):\n    with open(path, 'rb') as fh:\n        h = str(hashlib.md5(fh.read()).hexdigest())\n    return h",
    "docstring": "Calculate the MD5 hash for a file."
  },
  {
    "code": "def to_dict(self, remove_nones=False):\n        if remove_nones:\n            return super().to_dict(remove_nones=True)\n        tags = None\n        if self.tags is not None:\n            tags = [tag.to_dict(remove_nones=remove_nones) for tag in self.tags]\n        return {\n            'value': self.value,\n            'indicatorType': self.type,\n            'priorityLevel': self.priority_level,\n            'correlationCount': self.correlation_count,\n            'whitelisted': self.whitelisted,\n            'weight': self.weight,\n            'reason': self.reason,\n            'firstSeen': self.first_seen,\n            'lastSeen': self.last_seen,\n            'source': self.source,\n            'notes': self.notes,\n            'tags': tags,\n            'enclaveIds': self.enclave_ids\n        }",
    "docstring": "Creates a dictionary representation of the indicator.\n\n        :param remove_nones: Whether ``None`` values should be filtered out of the dictionary.  Defaults to ``False``.\n        :return: A dictionary representation of the indicator."
  },
  {
    "code": "def stop(self):\n        self.logger.warning(\"Stop executed\")\n        try:\n            self._reader.close()\n        except serial.serialutil.SerialException:\n            self.logger.error(\"Error while closing device\")\n            raise VelbusException(\"Error while closing device\")\n        time.sleep(1)",
    "docstring": "Close serial port."
  },
  {
    "code": "def _unpack_msg(self, *msg):\n        l = []\n        for m in msg:\n            l.append(str(m))\n        return \" \".join(l)",
    "docstring": "Convert all message elements to string"
  },
  {
    "code": "def OnCut(self, event):\n        entry_line = \\\n            self.main_window.entry_line_panel.entry_line_panel.entry_line\n        if wx.Window.FindFocus() != entry_line:\n            selection = self.main_window.grid.selection\n            with undo.group(_(\"Cut\")):\n                data = self.main_window.actions.cut(selection)\n            self.main_window.clipboard.set_clipboard(data)\n            self.main_window.grid.ForceRefresh()\n        else:\n            entry_line.Cut()\n        event.Skip()",
    "docstring": "Clipboard cut event handler"
  },
  {
    "code": "def list_repos(owner=None, **kwargs):\n    client = get_repos_api()\n    api_kwargs = {}\n    api_kwargs.update(utils.get_page_kwargs(**kwargs))\n    repos_list = client.repos_list_with_http_info\n    if owner is not None:\n        api_kwargs[\"owner\"] = owner\n        if hasattr(client, \"repos_list0_with_http_info\"):\n            repos_list = client.repos_list0_with_http_info\n    else:\n        if hasattr(client, \"repos_all_list_with_http_info\"):\n            repos_list = client.repos_all_list_with_http_info\n    with catch_raise_api_exception():\n        res, _, headers = repos_list(**api_kwargs)\n    ratelimits.maybe_rate_limit(client, headers)\n    page_info = PageInfo.from_headers(headers)\n    return [x.to_dict() for x in res], page_info",
    "docstring": "List repositories in a namespace."
  },
  {
    "code": "def reject(self, f, *args):\n        match = self.match(f, *args)\n        if match:\n            token = self.peek(0)\n            raise errors.EfilterParseError(\n                query=self.tokenizer.source, token=token,\n                message=\"Was not expecting a %s here.\" % token.name)",
    "docstring": "Like 'match', but throw a parse error if 'f' matches.\n\n        This is useful when a parser wants to be strict about specific things\n        being prohibited. For example, DottySQL bans the use of SQL keywords as\n        variable names."
  },
  {
    "code": "def threshold_count(da, op, thresh, freq):\n    from xarray.core.ops import get_op\n    if op in binary_ops:\n        op = binary_ops[op]\n    elif op in binary_ops.values():\n        pass\n    else:\n        raise ValueError(\"Operation `{}` not recognized.\".format(op))\n    func = getattr(da, '_binary_op')(get_op(op))\n    c = func(da, thresh) * 1\n    return c.resample(time=freq).sum(dim='time')",
    "docstring": "Count number of days above or below threshold.\n\n    Parameters\n    ----------\n    da : xarray.DataArray\n      Input data.\n    op : {>, <, >=, <=, gt, lt, ge, le }\n      Logical operator, e.g. arr > thresh.\n    thresh : float\n      Threshold value.\n    freq : str\n      Resampling frequency defining the periods\n      defined in http://pandas.pydata.org/pandas-docs/stable/timeseries.html#resampling.\n\n    Returns\n    -------\n    xarray.DataArray\n      The number of days meeting the constraints for each period."
  },
  {
    "code": "def _target_classes(self, target):\n    target_classes = set()\n    contents = ClasspathUtil.classpath_contents((target,), self.runtime_classpath)\n    for f in contents:\n      classname = ClasspathUtil.classname_for_rel_classfile(f)\n      if classname:\n        target_classes.add(classname)\n    return target_classes",
    "docstring": "Set of target's provided classes.\n\n    Call at the target level is to memoize efficiently."
  },
  {
    "code": "def get_smtp_header(self):\n        header = \"From: %s\\r\\n\" % self.get_sender()\n        header += \"To: %s\\r\\n\" % ',\\r\\n '.join(self.get_to())\n        header += \"Cc: %s\\r\\n\" % ',\\r\\n '.join(self.get_cc())\n        header += \"Bcc: %s\\r\\n\" % ',\\r\\n '.join(self.get_bcc())\n        header += \"Subject: %s\\r\\n\" % self.get_subject()\n        return header",
    "docstring": "Returns the SMTP formatted header of the line.\n\n        :rtype:  string\n        :return: The SMTP header."
  },
  {
    "code": "def _get_schema(self):\n\t\td={}\n\t\tlayout_kwargs=dict((_,'') for _ in get_layout_kwargs())\n\t\tfor _ in ('data','layout','theme','panels'):\n\t\t\td[_]={}\n\t\t\tfor __ in eval('__QUANT_FIGURE_{0}'.format(_.upper())):\n\t\t\t\tlayout_kwargs.pop(__,None)\n\t\t\t\td[_][__]=None\n\t\td['layout'].update(annotations=dict(values=[],\n\t\t\t\t\t\t\t\t\t\t\tparams=utils.make_dict_from_list(get_annotation_kwargs())))\n\t\td['layout'].update(shapes=utils.make_dict_from_list(get_shapes_kwargs()))\n\t\t[layout_kwargs.pop(_,None) for _ in get_annotation_kwargs()+get_shapes_kwargs()]\n\t\td['layout'].update(**layout_kwargs)\n\t\treturn d",
    "docstring": "Returns a dictionary with the schema for a QuantFigure"
  },
  {
    "code": "def validate_otp(hsm, args):\n    try:\n        res = pyhsm.yubikey.validate_otp(hsm, args.otp)\n        if args.verbose:\n            print \"OK counter=%04x low=%04x high=%02x use=%02x\" % \\\n                (res.use_ctr, res.ts_low, res.ts_high, res.session_ctr)\n        return 0\n    except pyhsm.exception.YHSM_CommandFailed, e:\n        if args.verbose:\n            print \"%s\" % (pyhsm.defines.status2str(e.status))\n        for r in [pyhsm.defines.YSM_OTP_INVALID, \\\n                      pyhsm.defines.YSM_OTP_REPLAY, \\\n                      pyhsm.defines.YSM_ID_NOT_FOUND]:\n            if e.status == r:\n                return r - pyhsm.defines.YSM_RESPONSE\n        return 0xff",
    "docstring": "Validate an OTP."
  },
  {
    "code": "def _update_data_dict(self, data_dict, back_or_front):\n        data_dict['back_or_front'] = back_or_front\n        if 'slim' in data_dict and 'scur' in data_dict:\n            try:\n                data_dict['spct'] = (data_dict['scur'] / data_dict['slim']) * 100\n            except (TypeError, ZeroDivisionError):\n                pass",
    "docstring": "Adds spct if relevant, adds service"
  },
  {
    "code": "def filtered_notebook_metadata(notebook):\n    metadata = copy(notebook.metadata)\n    metadata = filter_metadata(metadata,\n                               notebook.metadata.get('jupytext', {}).get('notebook_metadata_filter'),\n                               _DEFAULT_NOTEBOOK_METADATA)\n    if 'jupytext' in metadata:\n        del metadata['jupytext']\n    return metadata",
    "docstring": "Notebook metadata, filtered for metadata added by Jupytext itself"
  },
  {
    "code": "def UQRatio(s1, s2, full_process=True):\n    return QRatio(s1, s2, force_ascii=False, full_process=full_process)",
    "docstring": "Unicode quick ratio\n\n    Calls QRatio with force_ascii set to False\n\n    :param s1:\n    :param s2:\n    :return: similarity ratio"
  },
  {
    "code": "def _load_market_scheme(self):\n        try:\n            self.scheme = yaml.load(open(self.scheme_path, 'r'))\n        except Exception, error:\n            raise LoadMarketSchemeFailed(reason=error)",
    "docstring": "Load market yaml description"
  },
  {
    "code": "def colstack(self, new, mode='abort'):\n        if isinstance(new,list):\n            return tab_colstack([self] + new,mode)\n        else:\n            return tab_colstack([self, new], mode)",
    "docstring": "Horizontal stacking for tabarrays.\n\n        Stack tabarray(s) in `new` to the right of `self`.\n\n        **See also**\n\n                :func:`tabular.tabarray.tab_colstack`, \n                :func:`tabular.spreadsheet.colstack`"
  },
  {
    "code": "def other_Orange_tables(self):\n        target_table = self.db.target_table\n        if not self.db.orng_tables:\n            return [self.convert_table(table, None) for table in self.db.tables if table != target_table]\n        else:\n            return [table for name, table in list(self.db.orng_tables.items()) if name != target_table]",
    "docstring": "Returns the related tables as Orange example tables.\n\n            :rtype: list"
  },
  {
    "code": "def multis_2_mono(table):\n    for row in range(len(table)):\n        for column in range(len(table[row])):\n            table[row][column] = table[row][column].replace('\\n', ' ')\n    return table",
    "docstring": "Converts each multiline string in a table to single line.\n\n    Parameters\n    ----------\n    table : list of list of str\n        A list of rows containing strings\n\n    Returns\n    -------\n    table : list of lists of str"
  },
  {
    "code": "def get_mysql_args(db_config):\n    db = db_config['NAME']\n    mapping = [('--user={0}', db_config.get('USER')),\n               ('--password={0}', db_config.get('PASSWORD')),\n               ('--host={0}', db_config.get('HOST')),\n               ('--port={0}', db_config.get('PORT'))]\n    args = apply_arg_values(mapping)\n    args.append(db)\n    return args",
    "docstring": "Returns an array of argument values that will be passed to a `mysql` or\n    `mysqldump` process when it is started based on the given database\n    configuration."
  },
  {
    "code": "def _mantissa(dval):\n    bb = _double_as_bytes(dval)\n    mantissa =  bb[1] & 0x0f << 48\n    mantissa += bb[2] << 40\n    mantissa += bb[3] << 32\n    mantissa += bb[4]\n    return mantissa",
    "docstring": "Extract the _mantissa bits from a double-precision floating\n    point value."
  },
  {
    "code": "def unset_required_for(cls, sharable_fields):\n        if 'link_content' in cls.base_fields and 'link_content' not in sharable_fields:\n            cls.base_fields['link_content'].required = False\n        if 'link_type' in cls.base_fields and 'link' not in sharable_fields:\n            cls.base_fields['link_type'].required = False",
    "docstring": "Fields borrowed by `SharedGlossaryAdmin` to build its temporary change form, only are\n        required if they are declared in `sharable_fields`. Otherwise just deactivate them."
  },
  {
    "code": "def _generate_report_all(self):\n        assert self.workbook is not None\n        count = 0\n        for sid in self.folders.subfolders(self.folder_id, self.user):\n            count += 1\n            self._generate_for_subfolder(sid)\n        if count == 0:\n            print(\"I: empty workbook created: no subfolders found\")",
    "docstring": "Generate report for all subfolders contained by self.folder_id."
  },
  {
    "code": "def prox_zero(X, step):\n    return np.zeros(X.shape, dtype=X.dtype)",
    "docstring": "Proximal operator to project onto zero"
  },
  {
    "code": "def _make_item(model):\n    item = Item(model.id, model.content, model.media_type)\n    return item",
    "docstring": "Makes an ``.epub.Item`` from\n    a ``.models.Document`` or ``.models.Resource``"
  },
  {
    "code": "def add_constraint(self, func, variables, default_values=None):\n        self._constraints.append((func, variables, default_values or ()))",
    "docstring": "Adds a constraint that applies to one or more variables.\n\n        The function must return true or false to indicate which combinations\n        of variable values are valid."
  },
  {
    "code": "def set_value(self, value):\n        parsed_value = self._parse_value(value)\n        self.value = parsed_value",
    "docstring": "Parses, and sets the value attribute for the field.\n\n        :param value: The value to be parsed and set, the allowed input types\n            vary depending on the Field used"
  },
  {
    "code": "def limitsChanged(self, param, limits):\n        ParameterItem.limitsChanged(self, param, limits)\n        t = self.param.opts['type']\n        if t == 'int' or t == 'float':\n            self.widget.setOpts(bounds=limits)\n        else:\n            return",
    "docstring": "Called when the parameter's limits have changed"
  },
  {
    "code": "def export_public_keys(env=None, sp=subprocess):\n    args = gpg_command(['--export'])\n    result = check_output(args=args, env=env, sp=sp)\n    if not result:\n        raise KeyError('No GPG public keys found at env: {!r}'.format(env))\n    return result",
    "docstring": "Export all GPG public keys."
  },
  {
    "code": "def flush(self):\n        annotation = self.get_annotation()\n        if annotation.get(ATTACHMENTS_STORAGE) is not None:\n            del annotation[ATTACHMENTS_STORAGE]",
    "docstring": "Remove the whole storage"
  },
  {
    "code": "def write_warning (self, url_data):\n        self.write(self.part(\"warning\") + self.spaces(\"warning\"))\n        warning_msgs = [u\"[%s] %s\" % x for x in url_data.warnings]\n        self.writeln(self.wrap(warning_msgs, 65), color=self.colorwarning)",
    "docstring": "Write url_data.warning."
  },
  {
    "code": "def _get_local_folder(self, root=None):\n        if root is None:\n            root = Path()\n        for folders in ['.'], [self.user, self.napp]:\n            kytos_json = root / Path(*folders) / 'kytos.json'\n            if kytos_json.exists():\n                with kytos_json.open() as file_descriptor:\n                    meta = json.load(file_descriptor)\n                    username = meta.get('username', meta.get('author'))\n                    if username == self.user and meta.get('name') == self.napp:\n                        return kytos_json.parent\n        raise FileNotFoundError('kytos.json not found.')",
    "docstring": "Return local NApp root folder.\n\n        Search for kytos.json in _./_ folder and _./user/napp_.\n\n        Args:\n            root (pathlib.Path): Where to begin searching.\n\n        Return:\n            pathlib.Path: NApp root folder.\n\n        Raises:\n            FileNotFoundError: If there is no such local NApp."
  },
  {
    "code": "def read_line(self, fid):\n        lin = '\n        while lin[0] == '\n            lin = fid.readline().strip()\n            if lin == '':\n                return lin\n        return lin",
    "docstring": "Read a line from a file string and check it isn't either empty or commented before returning."
  },
  {
    "code": "def _deflate(cls):\n        data = {k: v for k, v in vars(cls).items() if not k.startswith(\"_\")}\n        return {Constants.CONFIG_KEY: data}",
    "docstring": "Prepare for serialisation - returns a dictionary"
  },
  {
    "code": "def _configure_interrupt(self, function_name, timeout, container, is_debugging):\n        def timer_handler():\n            LOG.info(\"Function '%s' timed out after %d seconds\", function_name, timeout)\n            self._container_manager.stop(container)\n        def signal_handler(sig, frame):\n            LOG.info(\"Execution of function %s was interrupted\", function_name)\n            self._container_manager.stop(container)\n        if is_debugging:\n            LOG.debug(\"Setting up SIGTERM interrupt handler\")\n            signal.signal(signal.SIGTERM, signal_handler)\n        else:\n            LOG.debug(\"Starting a timer for %s seconds for function '%s'\", timeout, function_name)\n            timer = threading.Timer(timeout, timer_handler, ())\n            timer.start()\n            return timer",
    "docstring": "When a Lambda function is executing, we setup certain interrupt handlers to stop the execution.\n        Usually, we setup a function timeout interrupt to kill the container after timeout expires. If debugging though,\n        we don't enforce a timeout. But we setup a SIGINT interrupt to catch Ctrl+C and terminate the container.\n\n        :param string function_name: Name of the function we are running\n        :param integer timeout: Timeout in seconds\n        :param samcli.local.docker.container.Container container: Instance of a container to terminate\n        :param bool is_debugging: Are we debugging?\n        :return threading.Timer: Timer object, if we setup a timer. None otherwise"
  },
  {
    "code": "def get_api_url(\n        self,\n        api_resource,\n        auth_token_ticket,\n        authenticator,\n        private_key,\n        service_url=None,\n        **kwargs\n    ):\n        auth_token, auth_token_signature = self._build_auth_token_data(\n            auth_token_ticket,\n            authenticator,\n            private_key,\n            **kwargs\n            )\n        params = {\n            'at': auth_token,\n            'ats': auth_token_signature,\n            }\n        if service_url is not None:\n            params['service'] = service_url\n        url = '{}?{}'.format(\n            self._get_api_url(api_resource),\n            urlencode(params),\n            )\n        return url",
    "docstring": "Build an auth-token-protected CAS API url."
  },
  {
    "code": "def compute(self,\n              activeColumns,\n              apicalInput=(),\n              apicalGrowthCandidates=None,\n              learn=True):\n    activeColumns = np.asarray(activeColumns)\n    apicalInput = np.asarray(apicalInput)\n    if apicalGrowthCandidates is None:\n      apicalGrowthCandidates = apicalInput\n    apicalGrowthCandidates = np.asarray(apicalGrowthCandidates)\n    self.prevPredictedCells = self.predictedCells\n    self.activateCells(activeColumns, self.activeCells, self.prevApicalInput,\n                       self.winnerCells, self.prevApicalGrowthCandidates, learn)\n    self.depolarizeCells(self.activeCells, apicalInput, learn)\n    self.prevApicalInput = apicalInput.copy()\n    self.prevApicalGrowthCandidates = apicalGrowthCandidates.copy()",
    "docstring": "Perform one timestep. Activate the specified columns, using the predictions\n    from the previous timestep, then learn. Then form a new set of predictions\n    using the new active cells and the apicalInput.\n\n    @param activeColumns (numpy array)\n    List of active columns\n\n    @param apicalInput (numpy array)\n    List of active input bits for the apical dendrite segments\n\n    @param apicalGrowthCandidates (numpy array or None)\n    List of bits that the active cells may grow new apical synapses to\n    If None, the apicalInput is assumed to be growth candidates.\n\n    @param learn (bool)\n    Whether to grow / reinforce / punish synapses"
  },
  {
    "code": "def iter_insert_items(tree):\n    if tree.list_values:\n        keys = tree.attrs\n        for values in tree.list_values:\n            if len(keys) != len(values):\n                raise SyntaxError(\n                    \"Values '%s' do not match attributes \" \"'%s'\" % (values, keys)\n                )\n            yield dict(zip(keys, map(resolve, values)))\n    elif tree.map_values:\n        for item in tree.map_values:\n            data = {}\n            for (key, val) in item:\n                data[key] = resolve(val)\n            yield data\n    else:\n        raise SyntaxError(\"No insert data found\")",
    "docstring": "Iterate over the items to insert from an INSERT statement"
  },
  {
    "code": "def uninstall(self):\n        for filename in self.files:\n            (home_filepath, mackup_filepath) = self.getFilepaths(filename)\n            if (os.path.isfile(mackup_filepath) or\n                    os.path.isdir(mackup_filepath)):\n                if os.path.exists(home_filepath):\n                    if self.verbose:\n                        print(\"Reverting {}\\n  at {} ...\"\n                              .format(mackup_filepath, home_filepath))\n                    else:\n                        print(\"Reverting {} ...\".format(filename))\n                    if self.dry_run:\n                        continue\n                    utils.delete(home_filepath)\n                    utils.copy(mackup_filepath, home_filepath)\n            elif self.verbose:\n                print(\"Doing nothing, {} does not exist\"\n                      .format(mackup_filepath))",
    "docstring": "Uninstall Mackup.\n\n        Restore any file where it was before the 1st Mackup backup.\n\n        Algorithm:\n            for each file in config\n                if mackup/file exists\n                    if home/file exists\n                        delete home/file\n                    copy mackup/file home/file\n            delete the mackup folder\n            print how to delete mackup"
  },
  {
    "code": "def iter_filtered_dir_entry(dir_entries, match_patterns, on_skip):\n    def match(dir_entry_path, match_patterns, on_skip):\n        for match_pattern in match_patterns:\n            if dir_entry_path.path_instance.match(match_pattern):\n                on_skip(dir_entry_path, match_pattern)\n                return True\n        return False\n    for entry in dir_entries:\n        try:\n            dir_entry_path = DirEntryPath(entry)\n        except FileNotFoundError as err:\n            log.error(\"Can't make DirEntryPath() instance: %s\" % err)\n            continue\n        if match(dir_entry_path, match_patterns, on_skip):\n            yield None\n        else:\n            yield dir_entry_path",
    "docstring": "Filter a list of DirEntryPath instances with the given pattern\n\n    :param dir_entries: list of DirEntryPath instances\n    :param match_patterns: used with Path.match()\n        e.g.: \"__pycache__/*\", \"*.tmp\", \"*.cache\"\n    :param on_skip: function that will be called if 'match_patterns' hits.\n        e.g.:\n        def on_skip(entry, pattern):\n            log.error(\"Skip pattern %r hit: %s\" % (pattern, entry.path))\n    :return: yields None or DirEntryPath instances"
  },
  {
    "code": "def find_channels(channels, connection=None, host=None, port=None,\n                  sample_rate=None, type=Nds2ChannelType.any(),\n                  dtype=Nds2DataType.any(), unique=False, epoch='ALL'):\n    if not isinstance(epoch, tuple):\n        epoch = (epoch or 'All',)\n    connection.set_epoch(*epoch)\n    if isinstance(sample_rate, (int, float)):\n        sample_rate = (sample_rate, sample_rate)\n    elif sample_rate is None:\n        sample_rate = tuple()\n    out = []\n    for name in _get_nds2_names(channels):\n        out.extend(_find_channel(connection, name, type, dtype, sample_rate,\n                                 unique=unique))\n    return out",
    "docstring": "Query an NDS2 server for channel information\n\n    Parameters\n    ----------\n    channels : `list` of `str`\n        list of channel names to query, each can include bash-style globs\n\n    connection : `nds2.connection`, optional\n        open NDS2 connection to use for query\n\n    host : `str`, optional\n        name of NDS2 server to query, required if ``connection`` is not\n        given\n\n    port : `int`, optional\n        port number on host to use for NDS2 connection\n\n    sample_rate : `int`, `float`, `tuple`, optional\n        a single number, representing a specific sample rate to match,\n        or a tuple representing a ``(low, high)` interval to match\n\n    type : `int`, optional\n        the NDS2 channel type to match\n\n    dtype : `int`, optional\n        the NDS2 data type to match\n\n    unique : `bool`, optional, default: `False`\n        require one (and only one) match per channel\n\n    epoch : `str`, `tuple` of `int`, optional\n        the NDS epoch to restrict to, either the name of a known epoch,\n        or a 2-tuple of GPS ``[start, stop)`` times\n\n    Returns\n    -------\n    channels : `list` of `nds2.channel`\n        list of NDS2 channel objects\n\n    See also\n    --------\n    nds2.connection.find_channels\n        for documentation on the underlying query method\n\n    Examples\n    --------\n    >>> from gwpy.io.nds2 import find_channels\n    >>> find_channels(['G1:DER_DATA_H'], host='nds.ligo.caltech.edu')\n    [<G1:DER_DATA_H (16384Hz, RDS, FLOAT64)>]"
  },
  {
    "code": "def volume_delete(self, name):\n        if self.volume_conn is None:\n            raise SaltCloudSystemExit('No cinder endpoint available')\n        nt_ks = self.volume_conn\n        try:\n            volume = self.volume_show(name)\n        except KeyError as exc:\n            raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))\n        if volume['status'] == 'deleted':\n            return volume\n        response = nt_ks.volumes.delete(volume['id'])\n        return volume",
    "docstring": "Delete a block device"
  },
  {
    "code": "def OverwriteAndClose(self, compressed_data, size):\n    self.Set(self.Schema.CONTENT(compressed_data))\n    self.Set(self.Schema.SIZE(size))\n    super(AFF4MemoryStreamBase, self).Close()",
    "docstring": "Directly overwrite the current contents.\n\n    Replaces the data currently in the stream with compressed_data,\n    and closes the object. Makes it possible to avoid recompressing\n    the data.\n    Args:\n      compressed_data: The data to write, must be zlib compressed.\n      size: The uncompressed size of the data."
  },
  {
    "code": "def sum_biomass_weight(reaction):\n    return sum(-coef * met.formula_weight\n               for (met, coef) in iteritems(reaction.metabolites)) / 1000.0",
    "docstring": "Compute the sum of all reaction compounds.\n\n    This function expects all metabolites of the biomass reaction to have\n    formula information assigned.\n\n    Parameters\n    ----------\n    reaction : cobra.core.reaction.Reaction\n        The biomass reaction of the model under investigation.\n\n    Returns\n    -------\n    float\n        The molecular weight of the biomass reaction in units of g/mmol."
  },
  {
    "code": "def djd_to_datetime(djd, tz='UTC'):\n    djd_start = pytz.utc.localize(dt.datetime(1899, 12, 31, 12))\n    utc_time = djd_start + dt.timedelta(days=djd)\n    return utc_time.astimezone(pytz.timezone(tz))",
    "docstring": "Converts a Dublin Julian Day float to a datetime.datetime object\n\n    Parameters\n    ----------\n    djd : float\n        fractional days since 12/31/1899+0000\n    tz : str, default 'UTC'\n        timezone to localize the result to\n\n    Returns\n    -------\n    datetime.datetime\n       The resultant datetime localized to tz"
  },
  {
    "code": "def _delete_collection(self, ctx):\n        assert isinstance(ctx, ResourceQueryContext)\n        filter_by = ctx.get_filter_by()\n        q = self._orm.query(self.model_cls)\n        if filter_by is not None:\n            q = self.to_filter(q, filter_by)\n        return q.delete()",
    "docstring": "Delete a collection from DB, optionally filtered by ``filter_by``"
  },
  {
    "code": "def _to_tuple(self, _list):\n        result = list()\n        for l in _list:\n            if isinstance(l, list):\n                result.append(tuple(self._to_tuple(l)))\n            else:\n                result.append(l)\n        return tuple(result)",
    "docstring": "Recursively converts lists to tuples"
  },
  {
    "code": "def add_default_fields(self, names, **kwargs):\n        if isinstance(names, string_types):\n            names = [names]\n        default_fields = self.default_fields(include_virtual=False, **kwargs)\n        arr = self.__class__(1, field_kwargs=kwargs)\n        sortdict = dict([[nm, ii] for ii,nm in enumerate(names)])\n        names = list(get_needed_fieldnames(arr, names))\n        names.sort(key=lambda x: sortdict[x] if x in sortdict\n            else len(names))\n        fields = [(name, default_fields[name]) for name in names]\n        arrays = []\n        names = []\n        for name,dt in fields:\n            arrays.append(default_empty(self.size, dtype=[(name, dt)]))\n            names.append(name)\n        return self.add_fields(arrays, names)",
    "docstring": "Adds one or more empty default fields to self.\n\n        Parameters\n        ----------\n        names : (list of) string(s)\n            The names of the fields to add. Must be a field in self's default\n            fields.\n\n        Other keyword args are any arguments passed to self's default fields.\n\n        Returns\n        -------\n        new array : instance of this array\n            A copy of this array with the field added."
  },
  {
    "code": "def decode(cls, s):\n        b = ByteString(s)\n        bd = base64.b64decode(b)\n        return String(bd)",
    "docstring": "decodes a base64 string to plain text\n\n        :param s: unicode str|bytes, the base64 encoded string\n        :returns: unicode str"
  },
  {
    "code": "def s2b(s):\n    ret = []\n    for c in s:\n        ret.append(bin(ord(c))[2:].zfill(8))\n    return \"\".join(ret)",
    "docstring": "String to binary."
  },
  {
    "code": "def graphviz_imshow(self, ax=None, figsize=None, dpi=300, fmt=\"png\", **kwargs):\n        graph = self.get_graphviz(**kwargs)\n        graph.format = fmt\n        graph.attr(dpi=str(dpi))\n        _, tmpname = tempfile.mkstemp()\n        path = graph.render(tmpname, view=False, cleanup=True)\n        ax, fig, _ = get_ax_fig_plt(ax=ax, figsize=figsize, dpi=dpi)\n        import matplotlib.image as mpimg\n        ax.imshow(mpimg.imread(path, format=\"png\"))\n        ax.axis(\"off\")\n        return fig",
    "docstring": "Generate flow graph in the DOT language and plot it with matplotlib.\n\n        Args:\n            ax: matplotlib :class:`Axes` or None if a new figure should be created.\n            figsize: matplotlib figure size (None to use default)\n            dpi: DPI value.\n            fmt: Select format for output image\n\n        Return: matplotlib Figure"
  },
  {
    "code": "def DEFINE_multi_enum(\n    name, default, enum_values, help, flag_values=_flagvalues.FLAGS,\n    case_sensitive=True, **args):\n  parser = _argument_parser.EnumParser(enum_values, case_sensitive)\n  serializer = _argument_parser.ArgumentSerializer()\n  DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)",
    "docstring": "Registers a flag whose value can be a list strings from enum_values.\n\n  Use the flag on the command line multiple times to place multiple\n  enum values into the list.  The 'default' may be a single string\n  (which will be converted into a single-element list) or a list of\n  strings.\n\n  Args:\n    name: str, the flag name.\n    default: Union[Iterable[Text], Text, None], the default value of the flag;\n        see `DEFINE_multi`.\n    enum_values: [str], a non-empty list of strings with the possible values for\n        the flag.\n    help: str, the help message.\n    flag_values: FlagValues, the FlagValues instance with which the flag will\n        be registered. This should almost never need to be overridden.\n    case_sensitive: Whether or not the enum is to be case-sensitive.\n    **args: Dictionary with extra keyword args that are passed to the\n        Flag __init__."
  },
  {
    "code": "def split(self, frac):\n        from .. import preprocess\n        split_obj = getattr(preprocess, '_Split')(fraction=frac)\n        return split_obj.transform(self)",
    "docstring": "Split the DataFrame into two DataFrames with certain ratio.\n\n        :param frac: Split ratio\n        :type frac: float\n\n        :return: two split DataFrame objects\n        :rtype: list[DataFrame]"
  },
  {
    "code": "def parallel_map(func, iterable, args=None, kwargs=None, workers=None):\n    if args is None:\n        args = ()\n    if kwargs is None:\n        kwargs = {}\n    if workers is not None:\n        pool = Pool(workers)\n    else:\n        pool = Group()\n    iterable = [pool.spawn(func, i, *args, **kwargs) for i in iterable]\n    pool.join(raise_error=True)\n    for idx, i in enumerate(iterable):\n        i_type = type(i.get())\n        i_value = i.get()\n        if issubclass(i_type, BaseException):\n            raise i_value\n        iterable[idx] = i_value\n    return iterable",
    "docstring": "Map func on a list using gevent greenlets.\n\n    :param func: function applied on iterable elements\n    :type func: function\n    :param iterable: elements to map the function over\n    :type iterable: iterable\n    :param args: arguments of func\n    :type args: tuple\n    :param kwargs: keyword arguments of func\n    :type kwargs: dict\n    :param workers: limit the number of greenlets\n                    running in parrallel\n    :type workers: int"
  },
  {
    "code": "def getsourcelines(object):\n    lines, lnum = findsource(object)\n    if ismodule(object): return lines, 0\n    else: return getblock(lines[lnum:]), lnum + 1",
    "docstring": "Return a list of source lines and starting line number for an object.\n\n    The argument may be a module, class, method, function, traceback, frame,\n    or code object.  The source code is returned as a list of the lines\n    corresponding to the object and the line number indicates where in the\n    original source file the first line of code was found.  An IOError is\n    raised if the source code cannot be retrieved."
  },
  {
    "code": "def create_from_previous_version(cls, previous_shadow, payload):\n        version, previous_payload = (previous_shadow.version + 1, previous_shadow.to_dict(include_delta=False)) if previous_shadow else (1, {})\n        if payload is None:\n            shadow = FakeShadow(None, None, None, version, deleted=True)\n            return shadow\n        desired = payload['state'].get(\n            'desired',\n            previous_payload.get('state', {}).get('desired', None)\n        )\n        reported = payload['state'].get(\n            'reported',\n            previous_payload.get('state', {}).get('reported', None)\n        )\n        shadow = FakeShadow(desired, reported, payload, version)\n        return shadow",
    "docstring": "set None to payload when you want to delete shadow"
  },
  {
    "code": "def degree_histogram(G, t=None):\n    counts = Counter(d for n, d in G.degree(t=t).items())\n    return [counts.get(i, 0) for i in range(max(counts) + 1)]",
    "docstring": "Return a list of the frequency of each degree value.\n\n        Parameters\n        ----------\n\n        G : Graph opject\n            DyNetx graph object\n\n\n        t : snapshot id (default=None)\n            snapshot id\n\n\n        Returns\n        -------\n        hist : list\n           A list of frequencies of degrees.\n           The degree values are the index in the list.\n\n        Notes\n        -----\n        Note: the bins are width one, hence len(list) can be large\n        (Order(number_of_edges))"
  },
  {
    "code": "def set_current_context(self, name):\n        if self.context_exists(name):\n            self.data['current-context'] = name\n        else:\n            raise KubeConfError(\"Context does not exist.\")",
    "docstring": "Set the current context in kubeconfig."
  },
  {
    "code": "def url_converter(self, *args, **kwargs):\n        upstream_converter = super(PatchedManifestStaticFilesStorage, self).url_converter(*args, **kwargs)\n        def converter(matchobj):\n            try:\n                upstream_converter(matchobj)\n            except ValueError:\n                matched, url = matchobj.groups()\n                return matched\n        return converter",
    "docstring": "Return the custom URL converter for the given file name."
  },
  {
    "code": "def _get_core_transform(self, resolution):\n        return self._base_transform(self._center_longitude,\n                                    self._center_latitude,\n                                    resolution)",
    "docstring": "The projection for the stereonet as a matplotlib transform. This is\n        primarily called by LambertAxes._set_lim_and_transforms."
  },
  {
    "code": "def tail(filename, number_of_bytes):\n    with open(filename, \"rb\") as f:\n        if os.stat(filename).st_size > number_of_bytes:\n            f.seek(-number_of_bytes, 2)\n        return f.read()",
    "docstring": "Returns the last number_of_bytes of filename"
  },
  {
    "code": "def parse(self, val):\n        s = str(val).lower()\n        if s == \"true\":\n            return True\n        elif s == \"false\":\n            return False\n        else:\n            raise ValueError(\"cannot interpret '{}' as boolean\".format(val))",
    "docstring": "Parses a ``bool`` from the string, matching 'true' or 'false' ignoring case."
  },
  {
    "code": "def _apply_commit_rules(rules, commit):\n        all_violations = []\n        for rule in rules:\n            violations = rule.validate(commit)\n            if violations:\n                all_violations.extend(violations)\n        return all_violations",
    "docstring": "Applies a set of rules against a given commit and gitcontext"
  },
  {
    "code": "def remove(self, names):\n        if not isinstance(names, list):\n            raise TypeError(\"names can only be an instance of type list\")\n        for a in names[:10]:\n            if not isinstance(a, basestring):\n                raise TypeError(\n                        \"array can only contain objects of type basestring\")\n        progress = self._call(\"remove\",\n                     in_p=[names])\n        progress = IProgress(progress)\n        return progress",
    "docstring": "Deletes the given files in the current directory level.\n\n        in names of type str\n            The names to remove.\n\n        return progress of type :class:`IProgress`\n            Progress object to track the operation completion."
  },
  {
    "code": "def to_latlon(geojson, origin_espg=None):\n    if isinstance(geojson, dict):\n        if origin_espg:\n            code = origin_espg\n        else:\n            code = epsg_code(geojson)\n        if code:\n            origin = Proj(init='epsg:%s' % code)\n            wgs84 = Proj(init='epsg:4326')\n            wrapped = test_wrap_coordinates(geojson['coordinates'], origin, wgs84)\n            new_coords = convert_coordinates(geojson['coordinates'], origin, wgs84, wrapped)\n            if new_coords:\n                geojson['coordinates'] = new_coords\n            try:\n                del geojson['crs']\n            except KeyError:\n                pass\n    return geojson",
    "docstring": "Convert a given geojson to wgs84. The original epsg must be included insde the crs\n    tag of geojson"
  },
  {
    "code": "def compute(mechanism, subsystem, purviews, cause_purviews,\n                effect_purviews):\n        concept = subsystem.concept(mechanism,\n                                    purviews=purviews,\n                                    cause_purviews=cause_purviews,\n                                    effect_purviews=effect_purviews)\n        concept.subsystem = None\n        return concept",
    "docstring": "Compute a |Concept| for a mechanism, in this |Subsystem| with the\n        provided purviews."
  },
  {
    "code": "def perturb_vec(q, cone_half_angle=2):\n    r\n    rand_vec = tan_rand(q)\n    cross_vector = attitude.unit_vector(np.cross(q, rand_vec))\n    s = np.random.uniform(0, 1, 1)\n    r = np.random.uniform(0, 1, 1)\n    h = np.cos(np.deg2rad(cone_half_angle))\n    phi = 2 * np.pi * s\n    z = h + ( 1- h) * r\n    sinT = np.sqrt(1 - z**2)\n    x = np.cos(phi) * sinT\n    y = np.sin(phi) * sinT\n    perturbed = rand_vec * x + cross_vector * y + q * z\n    return perturbed",
    "docstring": "r\"\"\"Perturb a vector randomly\n\n    qp = perturb_vec(q, cone_half_angle=2)\n\n    Parameters\n    ----------\n    q : (n,) numpy array\n        Vector to perturb\n    cone_half_angle : float\n        Maximum angle to perturb the vector in degrees\n\n    Returns\n    -------\n    perturbed : (n,) numpy array\n        Perturbed numpy array\n\n    Author\n    ------\n    Shankar Kulumani\t\tGWU\t\tskulumani@gwu.edu\n\n    References\n    ----------\n\n    .. [1] https://stackoverflow.com/questions/2659257/perturb-vector-by-some-angle"
  },
  {
    "code": "def compile(self):\n        self.content = \"\".join(map(lambda x: x.compile(), self.children))\n        return self._generate_html()",
    "docstring": "Recursively compile this widget as well as all of its children to HTML.\n\n        :returns: HTML string representation of this widget."
  },
  {
    "code": "def removeDomain(self, subnetId, domainId):\n        subnetDomainIds = []\n        for domain in self[subnetId]['domains']:\n            subnetDomainIds.append(domain['id'])\n        subnetDomainIds.remove(domainId)\n        self[subnetId][\"domain_ids\"] = subnetDomainIds\n        return len(self[subnetId][\"domains\"]) is len(subnetDomainIds)",
    "docstring": "Function removeDomain\n        Delete a domain from a subnet\n\n        @param subnetId: The subnet Id\n        @param domainId: The domainId to be attached wiuth the subnet\n        @return RETURN: boolean"
  },
  {
    "code": "def probe_disable(cls, resource):\n        oper = cls.call('hosting.rproxy.probe.disable',\n                        cls.usable_id(resource))\n        cls.echo('Desactivating probe on %s' % resource)\n        cls.display_progress(oper)\n        cls.echo('The probe have been desactivated')\n        return oper",
    "docstring": "Disable a probe on a webaccelerator"
  },
  {
    "code": "def get_meta(self):\n        rdf = self.get_meta_rdf(fmt='n3')\n        return ThingMeta(self, rdf, self._client.default_lang, fmt='n3')",
    "docstring": "Get the metadata object for this Thing\n\n        Returns a [ThingMeta](ThingMeta.m.html#IoticAgent.IOT.ThingMeta.ThingMeta) object"
  },
  {
    "code": "def from_files(cls, ID, datafiles, parser='name',\n                   position_mapper=None,\n                   readdata_kwargs={}, readmeta_kwargs={}, ID_kwargs={}, **kwargs):\n        if position_mapper is None:\n            if isinstance(parser, six.string_types):\n                position_mapper = parser\n            else:\n                msg = \"When using a custom parser, you must specify the position_mapper keyword.\"\n                raise ValueError(msg)\n        d = _assign_IDS_to_datafiles(datafiles, parser, cls._measurement_class, **ID_kwargs)\n        measurements = []\n        for sID, dfile in d.items():\n            try:\n                measurements.append(cls._measurement_class(sID, datafile=dfile,\n                                                           readdata_kwargs=readdata_kwargs,\n                                                           readmeta_kwargs=readmeta_kwargs))\n            except:\n                msg = 'Error occured while trying to parse file: %s' % dfile\n                raise IOError(msg)\n        return cls(ID, measurements, position_mapper, **kwargs)",
    "docstring": "Create an OrderedCollection of measurements from a set of data files.\n\n        Parameters\n        ----------\n        {_bases_ID}\n        {_bases_data_files}\n        {_bases_filename_parser}\n        {_bases_position_mapper}\n        {_bases_ID_kwargs}\n        kwargs : dict\n            Additional key word arguments to be passed to constructor."
  },
  {
    "code": "def _get_files_modified():\n    cmd = \"git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD\"\n    _, files_modified, _ = run(cmd)\n    extensions = [re.escape(ext) for ext in list(SUPPORTED_FILES) + [\".rst\"]]\n    test = \"(?:{0})$\".format(\"|\".join(extensions))\n    return list(filter(lambda f: re.search(test, f), files_modified))",
    "docstring": "Get the list of modified files that are Python or Jinja2."
  },
  {
    "code": "def unnest(elem):\n    if isinstance(elem, Iterable) and not isinstance(elem, six.string_types):\n        elem, target = tee(elem, 2)\n    else:\n        target = elem\n    for el in target:\n        if isinstance(el, Iterable) and not isinstance(el, six.string_types):\n            el, el_copy = tee(el, 2)\n            for sub in unnest(el_copy):\n                yield sub\n        else:\n            yield el",
    "docstring": "Flatten an arbitrarily nested iterable\n\n    :param elem: An iterable to flatten\n    :type elem: :class:`~collections.Iterable`\n\n    >>> nested_iterable = (1234, (3456, 4398345, (234234)), (2396, (23895750, 9283798, 29384, (289375983275, 293759, 2347, (2098, 7987, 27599)))))\n    >>> list(vistir.misc.unnest(nested_iterable))\n    [1234, 3456, 4398345, 234234, 2396, 23895750, 9283798, 29384, 289375983275, 293759, 2347, 2098, 7987, 27599]"
  },
  {
    "code": "def destroy(self):\n        v = vagrant.Vagrant(root=os.getcwd(),\n                            quiet_stdout=False,\n                            quiet_stderr=True)\n        v.destroy()",
    "docstring": "Destroy all vagrant box involved in the deployment."
  },
  {
    "code": "def time(ctx: Context, command: str):\n    with timer.Timing(verbose=True):\n        proc = run(command, shell=True)\n    ctx.exit(proc.returncode)",
    "docstring": "Time the output of a command."
  },
  {
    "code": "def is_file_secure(file_name):\n\tif not os.path.isfile(file_name):\n\t\treturn True\n\tfile_mode = os.stat(file_name).st_mode\n\tif file_mode & (stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH):\n\t\treturn False\n\treturn True",
    "docstring": "Returns false if file is considered insecure, true if secure.\n\tIf file doesn't exist, it's considered secure!"
  },
  {
    "code": "def inferTM(self, bottomUp, externalInput):\n    self.reset()\n    self.tm.compute(bottomUp,\n                    basalInput=externalInput,\n                    learn=False)\n    return self.tm.getPredictiveCells()",
    "docstring": "Run inference and return the set of predicted cells"
  },
  {
    "code": "def create(self, provider, names, **kwargs):\n        mapper = salt.cloud.Map(self._opts_defaults())\n        providers = self.opts['providers']\n        if provider in providers:\n            provider += ':{0}'.format(next(six.iterkeys(providers[provider])))\n        else:\n            return False\n        if isinstance(names, six.string_types):\n            names = names.split(',')\n        ret = {}\n        for name in names:\n            vm_ = kwargs.copy()\n            vm_['name'] = name\n            vm_['driver'] = provider\n            vm_['profile'] = None\n            vm_['provider'] = provider\n            ret[name] = salt.utils.data.simple_types_filter(\n                mapper.create(vm_))\n        return ret",
    "docstring": "Create the named VMs, without using a profile\n\n        Example:\n\n        .. code-block:: python\n\n            client.create(provider='my-ec2-config', names=['myinstance'],\n                image='ami-1624987f', size='t1.micro', ssh_username='ec2-user',\n                securitygroup='default', delvol_on_destroy=True)"
  },
  {
    "code": "def has_next_async(self):\n    if self._fut is None:\n      self._fut = self._iter.getq()\n    flag = True\n    try:\n      yield self._fut\n    except EOFError:\n      flag = False\n    raise tasklets.Return(flag)",
    "docstring": "Return a Future whose result will say whether a next item is available.\n\n    See the module docstring for the usage pattern."
  },
  {
    "code": "def get_xy(self, yidx, xidx=0):\n        assert isinstance(xidx, int)\n        if isinstance(yidx, int):\n            yidx = [yidx]\n        t_vars = self.concat_t_vars()\n        xdata = t_vars[:, xidx]\n        ydata = t_vars[:, yidx]\n        return xdata.tolist(), ydata.transpose().tolist()",
    "docstring": "Return stored data for the given indices for plot\n\n        :param yidx: the indices of the y-axis variables(1-indexing)\n        :param xidx: the index of the x-axis variables\n        :return: None"
  },
  {
    "code": "def target_timestamp(self) -> datetime:\n        timestamp = DB.get_hash_value(self._key, 'target_timestamp')\n        return datetime_from_isoformat(timestamp)",
    "docstring": "Get the target state timestamp."
  },
  {
    "code": "def countries(self):\n        if self._countries is None:\n            self._countries = CountryList(self._version, )\n        return self._countries",
    "docstring": "Access the countries\n\n        :returns: twilio.rest.voice.v1.dialing_permissions.country.CountryList\n        :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryList"
  },
  {
    "code": "def get_energies(atoms_list):\n    if len(atoms_list) == 1:\n        return atoms_list[0].get_potential_energy()\n    elif len(atoms_list) > 1:\n        energies = []\n        for atoms in atoms_list:\n            energies.append(atoms.get_potential_energy())\n        return energies",
    "docstring": "Potential energy for a list of atoms objects"
  },
  {
    "code": "def get_activity(self, activity_id, include_all_efforts=False):\n        raw = self.protocol.get('/activities/{id}', id=activity_id,\n                                include_all_efforts=include_all_efforts)\n        return model.Activity.deserialize(raw, bind_client=self)",
    "docstring": "Gets specified activity.\n\n        Will be detail-level if owned by authenticated user; otherwise summary-level.\n\n        http://strava.github.io/api/v3/activities/#get-details\n\n        :param activity_id: The ID of activity to fetch.\n        :type activity_id: int\n\n        :param inclue_all_efforts: Whether to include segment efforts - only\n                                   available to the owner of the activty.\n        :type include_all_efforts: bool\n\n        :rtype: :class:`stravalib.model.Activity`"
  },
  {
    "code": "def reorder(self, module=None):\n        module = module._mdl if module is not None else ffi.NULL\n        lib.EnvReorderAgenda(self._env, module)",
    "docstring": "Reorder the Activations in the Agenda.\n\n        If no Module is specified, the current one is used.\n\n        To be called after changing the conflict resolution strategy."
  },
  {
    "code": "def next_state(self, index, event_time, population_view):\n        return _next_state(index, event_time, self.transition_set, population_view)",
    "docstring": "Moves a population between different states using information this state's `transition_set`.\n\n        Parameters\n        ----------\n        index : iterable of ints\n            An iterable of integer labels for the simulants.\n        event_time : pandas.Timestamp\n            When this transition is occurring.\n        population_view : vivarium.framework.population.PopulationView\n            A view of the internal state of the simulation."
  },
  {
    "code": "def init_properties(self) -> 'PygalleBaseClass':\n        self._pigalle = {\n            PygalleBaseClass.__KEYS.INTERNALS: dict(),\n            PygalleBaseClass.__KEYS.PUBLIC: dict()\n        }\n        return self",
    "docstring": "Initialize the Pigalle properties.\n\n        # Returns:\n            PygalleBaseClass: The current instance."
  },
  {
    "code": "def _element_to_bson(key, value, check_keys, opts):\n    if not isinstance(key, string_type):\n        raise InvalidDocument(\"documents must have only string keys, \"\n                              \"key was %r\" % (key,))\n    if check_keys:\n        if key.startswith(\"$\"):\n            raise InvalidDocument(\"key %r must not start with '$'\" % (key,))\n        if \".\" in key:\n            raise InvalidDocument(\"key %r must not contain '.'\" % (key,))\n    name = _make_name(key)\n    return _name_value_to_bson(name, value, check_keys, opts)",
    "docstring": "Encode a single key, value pair."
  },
  {
    "code": "def process_from_web():\n    logger.info('Downloading table from %s' % trrust_human_url)\n    res = requests.get(trrust_human_url)\n    res.raise_for_status()\n    df = pandas.read_table(io.StringIO(res.text))\n    tp = TrrustProcessor(df)\n    tp.extract_statements()\n    return tp",
    "docstring": "Return a TrrustProcessor based on the online interaction table.\n\n    Returns\n    -------\n    TrrustProcessor\n        A TrrustProcessor object that has a list of INDRA Statements in its\n        statements attribute."
  },
  {
    "code": "def remove_accounts_from_group(accounts_query, group):\n    query = accounts_query.filter(date_deleted__isnull=True)\n    for account in query:\n        remove_account_from_group(account, group)",
    "docstring": "Remove accounts from group."
  },
  {
    "code": "def get_resource_name(context, expand_polymorphic_types=False):\n    from rest_framework_json_api.serializers import PolymorphicModelSerializer\n    view = context.get('view')\n    if not view:\n        return None\n    try:\n        code = str(view.response.status_code)\n    except (AttributeError, ValueError):\n        pass\n    else:\n        if code.startswith('4') or code.startswith('5'):\n            return 'errors'\n    try:\n        resource_name = getattr(view, 'resource_name')\n    except AttributeError:\n        try:\n            serializer = view.get_serializer_class()\n            if expand_polymorphic_types and issubclass(serializer, PolymorphicModelSerializer):\n                return serializer.get_polymorphic_types()\n            else:\n                return get_resource_type_from_serializer(serializer)\n        except AttributeError:\n            try:\n                resource_name = get_resource_type_from_model(view.model)\n            except AttributeError:\n                resource_name = view.__class__.__name__\n            if not isinstance(resource_name, six.string_types):\n                return resource_name\n            resource_name = format_resource_type(resource_name)\n    return resource_name",
    "docstring": "Return the name of a resource."
  },
  {
    "code": "def overlap(xl1, yl1, nx1, ny1, xl2, yl2, nx2, ny2):\n    return (xl2 < xl1+nx1 and xl2+nx2 > xl1 and\n            yl2 < yl1+ny1 and yl2+ny2 > yl1)",
    "docstring": "Determines whether two windows overlap"
  },
  {
    "code": "def get_random_theme(dark=True):\n    themes = [theme.path for theme in list_themes(dark)]\n    random.shuffle(themes)\n    return themes[0]",
    "docstring": "Get a random theme file."
  },
  {
    "code": "def create_api_ipv6(self):\n        return ApiIPv6(\n            self.networkapi_url,\n            self.user,\n            self.password,\n            self.user_ldap)",
    "docstring": "Get an instance of Api IPv6 services facade."
  },
  {
    "code": "def _status_change(id, new_status):\n    job_info = json.loads(r_client.get(id))\n    old_status = job_info['status']\n    job_info['status'] = new_status\n    _deposit_payload(job_info)\n    return old_status",
    "docstring": "Update the status of a job\n\n    The status associated with the id is updated, an update command is\n    issued to the job's pubsub, and and the old status is returned.\n\n    Parameters\n    ----------\n    id : str\n        The job ID\n    new_status : str\n        The status change\n\n    Returns\n    -------\n    str\n        The old status"
  },
  {
    "code": "def __load_yml(self, stream):\n        try:\n            return yaml.load(stream, Loader=yaml.SafeLoader)\n        except ValueError as e:\n            cause = \"invalid yml format. %s\" % str(e)\n            raise InvalidFormatError(cause=cause)",
    "docstring": "Load yml stream into a dict object"
  },
  {
    "code": "def get_entry(journal_location, date):\n    if not isinstance(date, datetime.date):\n        return None\n    try:\n        with open(build_journal_path(journal_location, date), \"r\") as entry_file:\n            return entry_file.read()\n    except IOError:\n        return None",
    "docstring": "args\n    date - date object\n    returns entry text or None if entry doesn't exist"
  },
  {
    "code": "def _dfs_preorder(node, visited):\n    if node not in visited:\n        visited.add(node)\n        yield node\n    if node.lo is not None:\n        yield from _dfs_preorder(node.lo, visited)\n    if node.hi is not None:\n        yield from _dfs_preorder(node.hi, visited)",
    "docstring": "Iterate through nodes in DFS pre-order."
  },
  {
    "code": "def make_het_matrix(fn):\n    vcf_df = vcf_as_df(fn)\n    variant_ids = vcf_df.apply(lambda x: df_variant_id(x), axis=1)\n    vcf_reader = pyvcf.Reader(open(fn, 'r'))\n    record = vcf_reader.next()\n    hets = pd.DataFrame(0, index=variant_ids,\n                        columns=[x.sample for x in record.samples])\n    vcf_reader = pyvcf.Reader(open(fn, 'r'))\n    for record in vcf_reader:\n        h = record.get_hets()\n        i = record_variant_id(record)\n        hets.ix[i, [x.sample for x in h]] = 1\n    return hets",
    "docstring": "Make boolean matrix of samples by variants. One indicates that the sample is\n    heterozygous for that variant.\n\n    Parameters:\n    -----------\n    vcf : str\n        Path to VCF file."
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'matching_results' in _dict:\n            args['matching_results'] = _dict.get('matching_results')\n        if 'results' in _dict:\n            args['results'] = [\n                QueryResult._from_dict(x) for x in (_dict.get('results'))\n            ]\n        if 'aggregations' in _dict:\n            args['aggregations'] = [\n                QueryAggregation._from_dict(x)\n                for x in (_dict.get('aggregations'))\n            ]\n        if 'passages' in _dict:\n            args['passages'] = [\n                QueryPassages._from_dict(x) for x in (_dict.get('passages'))\n            ]\n        if 'duplicates_removed' in _dict:\n            args['duplicates_removed'] = _dict.get('duplicates_removed')\n        if 'session_token' in _dict:\n            args['session_token'] = _dict.get('session_token')\n        if 'retrieval_details' in _dict:\n            args['retrieval_details'] = RetrievalDetails._from_dict(\n                _dict.get('retrieval_details'))\n        return cls(**args)",
    "docstring": "Initialize a QueryResponse object from a json dictionary."
  },
  {
    "code": "def get_revocation_key(self, user):\n        value = ''\n        if self.invalidate_on_password_change:\n            value += user.password\n        if self.one_time:\n            value += str(user.last_login)\n        return value",
    "docstring": "When the value returned by this method changes, this revocates tokens.\n\n        It always includes the password so that changing the password revokes\n        existing tokens.\n\n        In addition, for one-time tokens, it also contains the last login\n        datetime so that logging in revokes existing tokens."
  },
  {
    "code": "def split_spec(spec, sep):\n    parts = spec.rsplit(sep, 1)\n    spec_start = parts[0].strip()\n    spec_end = ''\n    if len(parts) == 2:\n        spec_end = parts[-1].strip()\n    return spec_start, spec_end",
    "docstring": "Split a spec by separator and return stripped start and end parts."
  },
  {
    "code": "def search_last_modified_unique_identities(db, after):\n    with db.connect() as session:\n        query = session.query(UniqueIdentity.uuid).\\\n            filter(UniqueIdentity.last_modified >= after)\n        uids = [uid.uuid for uid in query.order_by(UniqueIdentity.uuid).all()]\n    return uids",
    "docstring": "Look for the uuids of unique identities modified on or\n    after a given date.\n\n    This function returns the uuids of unique identities\n    modified on the given date or after it. The result is a\n    list of uuids unique identities.\n\n    :param db: database manager\n    :param after: look for identities modified on or after this date\n\n    :returns: a list of uuids of unique identities modified"
  },
  {
    "code": "def setPrivates(self, fieldDict) :\n        for priv in self.privates :\n            if priv in fieldDict :\n                setattr(self, priv, fieldDict[priv])\n            else :\n                setattr(self, priv, None)\n        if self._id is not None :\n            self.URL = \"%s/%s\" % (self.documentsURL, self._id)",
    "docstring": "will set self._id, self._rev and self._key field."
  },
  {
    "code": "def set_label(self):\r\n\t\tif not self.field.label or self.attrs.get(\"_no_label\"):\r\n\t\t\treturn\r\n\t\tself.values[\"label\"] = format_html(\r\n\t\t\tLABEL_TEMPLATE, self.field.html_name, mark_safe(self.field.label)\r\n\t\t)",
    "docstring": "Set label markup."
  },
  {
    "code": "def make_mapping(self) -> None:\n        start_mark = StreamMark('generated node', 0, 0, 0)\n        end_mark = StreamMark('generated node', 0, 0, 0)\n        self.yaml_node = yaml.MappingNode('tag:yaml.org,2002:map', list(),\n                                          start_mark, end_mark)",
    "docstring": "Replaces the node with a new, empty mapping.\n\n        Note that this will work on the Node object that is passed to \\\n        a yatiml_savorize() or yatiml_sweeten() function, but not on \\\n        any of its attributes or items. If you need to set an attribute \\\n        to a complex value, build a yaml.Node representing it and use \\\n        set_attribute with that."
  },
  {
    "code": "def add_rule(self, ip_protocol, from_port, to_port,\n                 src_group_name, src_group_owner_id, cidr_ip):\n        rule = IPPermissions(self)\n        rule.ip_protocol = ip_protocol\n        rule.from_port = from_port\n        rule.to_port = to_port\n        self.rules.append(rule)\n        rule.add_grant(src_group_name, src_group_owner_id, cidr_ip)",
    "docstring": "Add a rule to the SecurityGroup object.  Note that this method\n        only changes the local version of the object.  No information\n        is sent to EC2."
  },
  {
    "code": "def filter(self, chamber, congress=CURRENT_CONGRESS, **kwargs):\n        check_chamber(chamber)\n        kwargs.update(chamber=chamber, congress=congress)\n        if 'state' in kwargs and 'district' in kwargs:\n            path = (\"members/{chamber}/{state}/{district}/\"\n                    \"current.json\").format(**kwargs)\n        elif 'state' in kwargs:\n            path = (\"members/{chamber}/{state}/\"\n                    \"current.json\").format(**kwargs)\n        else:\n            path = (\"{congress}/{chamber}/\"\n                    \"members.json\").format(**kwargs)\n        return self.fetch(path, parse=lambda r: r['results'])",
    "docstring": "Takes a chamber and Congress,\n        OR state and district, returning a list of members"
  },
  {
    "code": "def data_received(self, data):\n        if self._on_data:\n            self._on_data(data)\n            return\n        self._queued_data.append(data)",
    "docstring": "Used to signal `asyncio.Protocol` of incoming data."
  },
  {
    "code": "def get_processor(self, entity_id, sp_config):\n        processor_string = sp_config.get('processor', None)\n        if processor_string:\n            try:\n                return import_string(processor_string)(entity_id)\n            except Exception as e:\n                logger.error(\"Failed to instantiate processor: {} - {}\".format(processor_string, e), exc_info=True)\n                raise\n        return BaseProcessor(entity_id)",
    "docstring": "Instantiate user-specified processor or default to an all-access base processor.\n            Raises an exception if the configured processor class can not be found or initialized."
  },
  {
    "code": "def write(self):\n        self.ix_command('write')\n        stream_warnings = self.streamRegion.generateWarningList()\n        warnings_list = (self.api.call('join ' + ' {' + stream_warnings + '} ' + ' LiStSeP').split('LiStSeP')\n                         if self.streamRegion.generateWarningList() else [])\n        for warning in warnings_list:\n            if warning:\n                raise StreamWarningsError(warning)",
    "docstring": "Write configuration to chassis.\n\n        Raise StreamWarningsError if configuration warnings found."
  },
  {
    "code": "def permission_to_perm(permission):\n    app_label = permission.content_type.app_label\n    codename = permission.codename\n    return '%s.%s' % (app_label, codename)",
    "docstring": "Convert a permission instance to a permission-string.\n\n    Examples\n    --------\n    >>> permission = Permission.objects.get(\n    ...     content_type__app_label='auth',\n    ...     codename='add_user',\n    ... )\n    >>> permission_to_perm(permission)\n    'auth.add_user'"
  },
  {
    "code": "def remove(self, template):\n        self.templates = [t for t in self.templates if t != template]\n        return self",
    "docstring": "Remove a template from the tribe.\n\n        :type template: :class:`eqcorrscan.core.match_filter.Template`\n        :param template: Template to remove from tribe\n\n        .. rubric:: Example\n\n        >>> tribe = Tribe(templates=[Template(name='c'), Template(name='b'),\n        ...                          Template(name='a')])\n        >>> tribe.remove(tribe.templates[0])\n        Tribe of 2 templates"
  },
  {
    "code": "def items(self):\r\n        return {dep.task: value for dep, value in self._result.items()}.items()",
    "docstring": "Returns dictionary items"
  },
  {
    "code": "def connect(self, socket_or_address):\n        if isinstance(socket_or_address, tuple):\n            import socket\n            self.socket = socket.create_connection(socket_or_address)\n        else:\n            self.socket = socket_or_address\n        address = None\n        self.handler = EPCClientHandler(self.socket, address, self)\n        self.call = self.handler.call\n        self.call_sync = self.handler.call_sync\n        self.methods = self.handler.methods\n        self.methods_sync = self.handler.methods_sync\n        self.handler_thread = newthread(self, target=self.handler.start)\n        self.handler_thread.daemon = self.thread_daemon\n        self.handler_thread.start()\n        self.handler.wait_until_ready()",
    "docstring": "Connect to server and start serving registered functions.\n\n        :type socket_or_address: tuple or socket object\n        :arg  socket_or_address: A ``(host, port)`` pair to be passed\n                                 to `socket.create_connection`, or\n                                 a socket object."
  },
  {
    "code": "def register_agent(self, host, sweep_id=None, project_name=None):\n        mutation = gql(\n)\n        if project_name is None:\n            project_name = self.settings('project')\n        def no_retry_400(e):\n            if not isinstance(e, requests.HTTPError):\n                return True\n            if e.response.status_code != 400:\n                return True\n            body = json.loads(e.response.content)\n            raise UsageError(body['errors'][0]['message'])\n        response = self.gql(mutation, variable_values={\n            'host': host,\n            'entityName': self.settings(\"entity\"),\n            'projectName': project_name,\n            'sweep': sweep_id}, check_retry_fn=no_retry_400)\n        return response['createAgent']['agent']",
    "docstring": "Register a new agent\n\n        Args:\n            host (str): hostname\n            persistent (bool): long running or oneoff\n            sweep (str): sweep id\n            project_name: (str): model that contains sweep"
  },
  {
    "code": "def show_input(self, template_helper, language, seed):\n        header = ParsableText(self.gettext(language,self._header), \"rst\",\n                              translation=self._translations.get(language, gettext.NullTranslations()))\n        return str(DisplayableCodeProblem.get_renderer(template_helper).tasks.code(self.get_id(), header, 8, 0, self._language, self._optional, self._default))",
    "docstring": "Show BasicCodeProblem and derivatives"
  },
  {
    "code": "def with_descriptor(self, descriptor):\n        res = {}\n        desc = \"%s_descriptor\" % descriptor\n        for eid, ent in self.items():\n            if desc in ent:\n                res[eid] = ent\n        return res",
    "docstring": "Returns any entities with the specified descriptor"
  },
  {
    "code": "def read_stream(self, file: IO, data_stream: DataStream) -> Reply:\n        yield from data_stream.read_file(file=file)\n        reply = yield from self._control_stream.read_reply()\n        self.raise_if_not_match(\n            'End stream',\n            ReplyCodes.closing_data_connection,\n            reply\n        )\n        data_stream.close()\n        return reply",
    "docstring": "Read from the data stream.\n\n        Args:\n            file: A destination file object or a stream writer.\n            data_stream: The stream of which to read from.\n\n        Coroutine.\n\n        Returns:\n            Reply: The final reply."
  },
  {
    "code": "def add(self, name, definition):\n        self._storage[name] = self._expand_definition(definition)",
    "docstring": "Register a definition to the registry. Existing definitions are\n        replaced silently.\n\n        :param name: The name which can be used as reference in a validation\n                     schema.\n        :type name: :class:`str`\n        :param definition: The definition.\n        :type definition: any :term:`mapping`"
  },
  {
    "code": "def pw_score_cosine(self, s1 : ClassId, s2 : ClassId) -> SimScore:\n        df = self.assoc_df\n        slice1 = df.loc[s1].values\n        slice2 = df.loc[s2].values\n        return 1 - cosine(slice1, slice2)",
    "docstring": "Cosine similarity of two subjects\n\n        Arguments\n        ---------\n        s1 : str\n            class id\n\n\n        Return\n        ------\n        number\n            A number between 0 and 1"
  },
  {
    "code": "def _run_nucmer(self, ref, qry, outfile):\n        n = pymummer.nucmer.Runner(\n            ref,\n            qry,\n            outfile,\n            min_id=self.nucmer_min_id,\n            min_length=self.nucmer_min_length,\n            diagdiff=self.nucmer_diagdiff,\n            maxmatch=True,\n            breaklen=self.nucmer_breaklen,\n            simplify=True,\n            verbose=self.verbose\n        )\n        n.run()",
    "docstring": "Run nucmer of new assembly vs original assembly"
  },
  {
    "code": "def remove_listener(self, registration_id):\n        try:\n            self._listeners.pop(registration_id)\n            return True\n        except KeyError:\n            return False",
    "docstring": "Removes a lifecycle listener.\n\n        :param registration_id: (str), the id of the listener to be removed.\n        :return: (bool), ``true`` if the listener is removed successfully, ``false`` otherwise."
  },
  {
    "code": "def first_order_score(y, mean, scale, shape, skewness):\n        return (y-mean)/float(scale*np.abs(y-mean))",
    "docstring": "GAS Laplace Update term using gradient only - native Python function\n\n        Parameters\n        ----------\n        y : float\n            datapoint for the time series\n\n        mean : float\n            location parameter for the Laplace distribution\n\n        scale : float\n            scale parameter for the Laplace distribution\n\n        shape : float\n            tail thickness parameter for the Laplace distribution\n\n        skewness : float\n            skewness parameter for the Laplace distribution\n\n        Returns\n        ----------\n        - Score of the Laplace family"
  },
  {
    "code": "def load(self, filename):\n        try:\n            with open(filename, 'rb') as fp:\n                self.counters = cPickle.load(fp)\n        except:\n            logging.debug(\"can't load counter from file: %s\", filename)\n            return False\n        return True",
    "docstring": "Load counters to file"
  },
  {
    "code": "def get_port_bindings(container_config, client_config):\n    port_bindings = {}\n    if_ipv4 = client_config.interfaces\n    if_ipv6 = client_config.interfaces_ipv6\n    for exposed_port, ex_port_bindings in itertools.groupby(\n            sorted(container_config.exposes, key=_get_ex_port), _get_ex_port):\n        bind_list = list(_get_port_bindings(ex_port_bindings, if_ipv4, if_ipv6))\n        if bind_list:\n            port_bindings[exposed_port] = bind_list\n    return port_bindings",
    "docstring": "Generates the input dictionary contents for the ``port_bindings`` argument.\n\n    :param container_config: Container configuration.\n    :type container_config: dockermap.map.config.container.ContainerConfiguration\n    :param client_config: Client configuration.\n    :type client_config: dockermap.map.config.client.ClientConfiguration\n    :return: Dictionary of ports with mapped port, and if applicable, with bind address\n    :rtype: dict[unicode | str, list[unicode | str | int | tuple]]"
  },
  {
    "code": "def get(self, transform=None):\n        if not self.has_expired() and self._cached_copy is not None:\n            return self._cached_copy, False\n        return self._refresh_cache(transform), True",
    "docstring": "Return the JSON defined at the S3 location in the constructor.\n\n        The get method will reload the S3 object after the TTL has\n        expired.\n        Fetch the JSON object from cache or S3 if necessary"
  },
  {
    "code": "def _rle(self, a):\n        ia = np.asarray(a)\n        n = len(ia)\n        y = np.array(ia[1:] != ia[:-1])\n        i = np.append(np.where(y), n - 1)\n        z = np.diff(np.append(-1, i))\n        p = np.cumsum(np.append(0, z))[:-1]\n        return (z, p, ia[i])",
    "docstring": "rle implementation credit to Thomas Browne from his SOF post Sept 2015\n\n        Parameters\n        ----------\n        a : array, shape[n,]\n            input vector\n\n        Returns\n        -------\n        z : array, shape[nt,]\n            run lengths\n        p : array, shape[nt,]\n            start positions of each run\n        ar : array, shape[nt,]\n            values for each run"
  },
  {
    "code": "def rand_bivar(X, rho):\n    import numpy as np\n    Y = np.empty(X.shape)\n    Y[:, 0] = X[:, 0]\n    Y[:, 1] = rho * X[:, 0] + np.sqrt(1.0 - rho**2) * X[:, 1]\n    return Y",
    "docstring": "Transform two unrelated random variables into correlated bivariate data\n\n    X : ndarray\n        two univariate random variables\n        with N observations as <N x 2> matrix\n\n    rho : float\n        The Pearson correlations coefficient\n        as number between [-1, +1]"
  },
  {
    "code": "def highlight(str1, str2):\n    print('------------------------------')\n    try:\n        str2 = str2[0]\n    except IndexError:\n        str2 = None\n    if str1 and str2:\n        return str1.replace(str2, \"<b>{}</b>\".format(str2))\n    else:\n        return str1",
    "docstring": "Highlight str1 with the contents of str2."
  },
  {
    "code": "def validate(self, value) :\n        for v in self.validators :\n            v.validate(value)\n        return True",
    "docstring": "checks the validity of 'value' given the lits of validators"
  },
  {
    "code": "def get_type_name(type_name, sub_type=None):\n    if type_name in (\"string\", \"enum\"):\n        return \"string\"\n    if type_name == \"float\":\n        return \"float64\"\n    if type_name == \"boolean\":\n        return \"bool\"\n    if type_name == \"list\":\n        st = get_type_name(type_name=sub_type, sub_type=None) if sub_type else \"interface{}\"\n        return \"[]%s\" % st\n    if type_name == \"integer\":\n        return \"int\"\n    if type_name == \"time\":\n        return \"float64\"\n    return \"interface{}\"",
    "docstring": "Returns a go type according to a spec type"
  },
  {
    "code": "def medium_integer(self, column, auto_increment=False, unsigned=False):\n        return self._add_column('medium_integer', column,\n                                auto_increment=auto_increment,\n                                unsigned=unsigned)",
    "docstring": "Create a new medium integer column on the table.\n\n        :param column: The column\n        :type column: str\n\n        :type auto_increment: bool\n\n        :type unsigned: bool\n\n        :rtype: Fluent"
  },
  {
    "code": "def closest_pair(arr, give=\"indicies\"):\n    idxs = [idx for idx in np.ndindex(arr.shape)]\n    outs = []\n    min_dist = arr.max() - arr.min()\n    for idxa in idxs:\n        for idxb in idxs:\n            if idxa == idxb:\n                continue\n            dist = abs(arr[idxa] - arr[idxb])\n            if dist == min_dist:\n                if not [idxb, idxa] in outs:\n                    outs.append([idxa, idxb])\n            elif dist < min_dist:\n                min_dist = dist\n                outs = [[idxa, idxb]]\n    if give == \"indicies\":\n        return outs\n    elif give == \"distance\":\n        return min_dist\n    else:\n        raise KeyError(\"give not recognized in closest_pair\")",
    "docstring": "Find the pair of indices corresponding to the closest elements in an array.\n\n    If multiple pairs are equally close, both pairs of indicies are returned.\n    Optionally returns the closest distance itself.\n\n    I am sure that this could be written as a cheaper operation. I\n    wrote this as a quick and dirty method because I need it now to use on some\n    relatively small arrays. Feel free to refactor if you need this operation\n    done as fast as possible. - Blaise 2016-02-07\n\n    Parameters\n    ----------\n    arr : numpy.ndarray\n        The array to search.\n    give : {'indicies', 'distance'} (optional)\n        Toggle return behavior. If 'distance', returns a single float - the\n        closest distance itself. Default is indicies.\n\n    Returns\n    -------\n    list of lists of two tuples\n        List containing lists of two tuples: indicies the nearest pair in the\n        array.\n\n        >>> arr = np.array([0, 1, 2, 3, 3, 4, 5, 6, 1])\n        >>> closest_pair(arr)\n        [[(1,), (8,)], [(3,), (4,)]]"
  },
  {
    "code": "def get_app_guid(self, app_name):\n        summary = self.space.get_space_summary()\n        for app in summary['apps']:\n            if app['name'] == app_name:\n                return app['guid']",
    "docstring": "Returns the GUID for the app instance with\n        the given name."
  },
  {
    "code": "def bcc(\n            self,\n            bcc_emails,\n            global_substitutions=None,\n            is_multiple=False,\n            p=0):\n        if isinstance(bcc_emails, list):\n            for email in bcc_emails:\n                if isinstance(email, str):\n                    email = Bcc(email, None)\n                if isinstance(email, tuple):\n                    email = Bcc(email[0], email[1])\n                self.add_bcc(email, global_substitutions, is_multiple, p)\n        else:\n            if isinstance(bcc_emails, str):\n                bcc_emails = Bcc(bcc_emails, None)\n            if isinstance(bcc_emails, tuple):\n                bcc_emails = Bcc(bcc_emails[0], bcc_emails[1])\n            self.add_bcc(bcc_emails, global_substitutions, is_multiple, p)",
    "docstring": "Adds Bcc objects to the Personalization object\n\n        :param bcc_emails: An Bcc or list of Bcc objects\n        :type bcc_emails: Bcc, list(Bcc), tuple\n        :param global_substitutions: A dict of substitutions for all recipients\n        :type global_substitutions: dict\n        :param is_multiple: Create a new personilization for each recipient\n        :type is_multiple: bool\n        :param p: p is the Personalization object or Personalization object\n                  index\n        :type p: Personalization, integer, optional"
  },
  {
    "code": "def is_python_interpreter(filename):\r\n    real_filename = os.path.realpath(filename)\n    if (not osp.isfile(real_filename) or \r\n        not is_python_interpreter_valid_name(filename)):\r\n        return False\r\n    elif is_pythonw(filename):\r\n        if os.name == 'nt':\r\n            if not encoding.is_text_file(real_filename):\r\n                return True\r\n            else:\r\n                return False\r\n        elif sys.platform == 'darwin':\r\n            if is_anaconda() and encoding.is_text_file(real_filename):\r\n                return True\r\n            elif not encoding.is_text_file(real_filename):\r\n                return True\r\n            else:\r\n                return False\r\n        else:\r\n            return False\r\n    elif encoding.is_text_file(real_filename):\r\n        return False\r\n    else:\r\n        return check_python_help(filename)",
    "docstring": "Evaluate wether a file is a python interpreter or not."
  },
  {
    "code": "def read_option_value_from_nibble(nibble, pos, values):\n        if nibble <= 12:\n            return nibble, pos\n        elif nibble == 13:\n            tmp = struct.unpack(\"!B\", values[pos].to_bytes(1, \"big\"))[0] + 13\n            pos += 1\n            return tmp, pos\n        elif nibble == 14:\n            s = struct.Struct(\"!H\")\n            tmp = s.unpack_from(values[pos:].to_bytes(2, \"big\"))[0] + 269\n            pos += 2\n            return tmp, pos\n        else:\n            raise AttributeError(\"Unsupported option nibble \" + str(nibble))",
    "docstring": "Calculates the value used in the extended option fields.\n\n        :param nibble: the 4-bit option header value.\n        :return: the value calculated from the nibble and the extended option value."
  },
  {
    "code": "def _ReadPropertySet(self, property_set):\n    for property_section in property_set.sections:\n      if property_section.class_identifier != self._CLASS_IDENTIFIER:\n        continue\n      for property_value in property_section.properties:\n        property_name = self._PROPERTY_NAMES.get(\n            property_value.identifier, None)\n        if not property_name:\n          property_name = '0x{0:04}'.format(property_value.identifier)\n        value = self._GetValueAsObject(property_value)\n        if self._PROPERTY_VALUE_MAPPINGS:\n          value_callback_name = self._PROPERTY_VALUE_MAPPINGS.get(\n              property_name, None)\n          if value_callback_name:\n            value_callback_method = getattr(self, value_callback_name, None)\n            if value_callback_method:\n              value = value_callback_method(value)\n        if property_name in self._DATE_TIME_PROPERTIES:\n          properties_dict = self.date_time_properties\n          value = dfdatetime_filetime.Filetime(timestamp=value)\n        else:\n          properties_dict = self._properties\n        if property_name not in properties_dict:\n          properties_dict[property_name] = value",
    "docstring": "Reads properties from a property set.\n\n    Args:\n      property_set (pyolecf.property_set): OLECF property set."
  },
  {
    "code": "def login(username, password, **kwargs):\n    user_id = util.hdb.login_user(username, password)\n    hydra_session = session.Session({},\n            validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'),\n            type='file',\n            cookie_expires=True,\n            data_dir=config.get('COOKIES', 'DATA_DIR', '/tmp'),\n            file_dir=config.get('COOKIES', 'FILE_DIR', '/tmp/auth'))\n    hydra_session['user_id'] = user_id\n    hydra_session['username'] = username\n    hydra_session.save()\n    return (user_id, hydra_session.id)",
    "docstring": "Login a user, returning a dict containing their user_id and session_id\n\n        This does the DB login to check the credentials, and then creates a session\n        so that requests from apps do not need to perform a login\n\n        args:\n            username (string): The user's username\n            password(string): The user's password (unencrypted)\n        returns:\n            A dict containing the user_id and session_id\n        raises:\n            HydraError if the login fails"
  },
  {
    "code": "def count(data, axis=None):\n    return np.sum(np.logical_not(isnull(data)), axis=axis)",
    "docstring": "Count the number of non-NA in this array along the given axis or axes"
  },
  {
    "code": "def get_el(el):\n        tag_name = el.elt.tagName.lower()\n        if tag_name in {\"input\", \"textarea\", \"select\"}:\n            return el.value\n        else:\n            raise ValueError(\n                \"Getter for %s (%s) not implemented!\" % (tag_name, el.id)\n            )",
    "docstring": "Get value of given `el` tag element.\n\n        Automatically choose proper method to set the `value` based on the type\n        of the `el`.\n\n        Args:\n            el (obj): Element reference to the input you want to convert to\n                typeahead.\n\n        Returns:\n            str: Value of the object."
  },
  {
    "code": "def dK_dr_via_X(self, X, X2):\n        return self.dK_dr(self._scaled_dist(X, X2))",
    "docstring": "compute the derivative of K wrt X going through X"
  },
  {
    "code": "def plot(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT):\n        if title == \"\":\n            title = \" \"\n        if xlabel == \"\":\n            xlabel = \" \"\n        if ylabel == \"\":\n            ylabel = \" \"\n        if title is None:\n            title = \"\"\n        if xlabel is None:\n            xlabel = \"\"\n        if ylabel is None:\n            ylabel = \"\"\n        return Plot(self.__proxy__.plot(title, xlabel, ylabel))",
    "docstring": "Create a Plot object representing the SArray.\n\n        Notes\n        -----\n        - The plot will render either inline in a Jupyter Notebook, or in a\n          native GUI window, depending on the value provided in\n          `turicreate.visualization.set_target` (defaults to 'auto').\n\n        Parameters\n        ----------\n        title : str\n            The plot title to show for the resulting visualization.\n            If the title is None, the title will be omitted.\n\n        xlabel : str\n            The X axis label to show for the resulting visualization.\n            If the xlabel is None, the X axis label will be omitted.\n\n        ylabel : str\n            The Y axis label to show for the resulting visualization.\n            If the ylabel is None, the Y axis label will be omitted.\n\n        Returns\n        -------\n        out : Plot\n        A :class: Plot object that is the visualization of the SArray.\n\n        Examples\n        --------\n        Suppose 'sa' is an SArray, we can create a plot of it using:\n\n        >>> plt = sa.plot()\n\n        To override the default plot title and axis labels:\n\n        >>> plt = sa.plot(title=\"My Plot Title\", xlabel=\"My X Axis\", ylabel=\"My Y Axis\")\n\n        We can then visualize the plot using:\n\n        >>> plt.show()"
  },
  {
    "code": "def delete_thumbnails(relative_source_path, root=None, basedir=None,\n                      subdir=None, prefix=None):\n    thumbs = thumbnails_for_file(relative_source_path, root, basedir, subdir,\n                                 prefix)\n    return _delete_using_thumbs_list(thumbs)",
    "docstring": "Delete all thumbnails for a source image."
  },
  {
    "code": "def where(cmd, path=None):\n    raw_result = shutil.which(cmd, os.X_OK, path)\n    if raw_result:\n        return os.path.abspath(raw_result)\n    else:\n        raise ValueError(\"Could not find '{}' in the path\".format(cmd))",
    "docstring": "A function to wrap shutil.which for universal usage"
  },
  {
    "code": "def mean_curve(values, weights=None):\n    if weights is None:\n        weights = [1. / len(values)] * len(values)\n    if not isinstance(values, numpy.ndarray):\n        values = numpy.array(values)\n    return numpy.average(values, axis=0, weights=weights)",
    "docstring": "Compute the mean by using numpy.average on the first axis."
  },
  {
    "code": "def urlsafe_b64decode(data):\n    pad = b'=' * (4 - (len(data) & 3))\n    return base64.urlsafe_b64decode(data + pad)",
    "docstring": "urlsafe_b64decode without padding"
  },
  {
    "code": "def calculate_descriptors(self,mol):\n\t\tself.ligand_atoms = {index:{\"name\":x.name} for index,x in enumerate(self.topology_data.universe.ligand_noH.atoms)}\n\t\tcontribs = self.calculate_logP(mol)\n\t\tself.calculate_Gasteiger_charges(mol)\n\t\tfcharges = self.calculate_formal_charge(mol)\n\t\tfor atom in self.ligand_atoms.keys():\n\t\t\tself.ligand_atoms[atom][\"logP\"]=contribs[atom][0]\n\t\t\tself.ligand_atoms[atom][\"MR\"]=contribs[atom][1]\n\t\t\tself.ligand_atoms[atom][\"Gasteiger_ch\"]=mol.GetAtomWithIdx(atom).GetProp(\"_GasteigerCharge\")\n\t\t\tself.ligand_atoms[atom][\"Formal charges\"]=fcharges[atom]\n\t\tself.rot_bonds=self.get_rotatable_bonds(mol)",
    "docstring": "Calculates descriptors such as logP, charges and MR and saves that in a dictionary."
  },
  {
    "code": "def _writeFeatures(self, i, image):\n        basename = 'features-%d.txt' % i\n        filename = '%s/%s' % (self._outputDir, basename)\n        featureList = image['graphInfo']['features']\n        with open(filename, 'w') as fp:\n            for feature in featureList:\n                fp.write('%s\\n\\n' % feature.feature)\n        return basename",
    "docstring": "Write a text file containing the features as a table.\n\n        @param i: The number of the image in self._images.\n        @param image: A member of self._images.\n        @return: The C{str} features file name - just the base name, not\n            including the path to the file."
  },
  {
    "code": "def parse_pseudo_open(self, sel, name, has_selector, iselector, index):\n        flags = FLG_PSEUDO | FLG_OPEN\n        if name == ':not':\n            flags |= FLG_NOT\n        if name == ':has':\n            flags |= FLG_RELATIVE\n        sel.selectors.append(self.parse_selectors(iselector, index, flags))\n        has_selector = True\n        return has_selector",
    "docstring": "Parse pseudo with opening bracket."
  },
  {
    "code": "def list_processed_parameter_groups(self):\n        path = '/archive/{}/parameter-groups'.format(self._instance)\n        response = self._client.get_proto(path=path)\n        message = archive_pb2.ParameterGroupInfo()\n        message.ParseFromString(response.content)\n        groups = getattr(message, 'group')\n        return iter(groups)",
    "docstring": "Returns the existing parameter groups.\n\n        :rtype: ~collections.Iterable[str]"
  },
  {
    "code": "def rename(store, src_path, dst_path):\n    src_path = normalize_storage_path(src_path)\n    dst_path = normalize_storage_path(dst_path)\n    if hasattr(store, 'rename'):\n        store.rename(src_path, dst_path)\n    else:\n        _rename_from_keys(store, src_path, dst_path)",
    "docstring": "Rename all items under the given path. If `store` provides a `rename` method,\n    this will be called, otherwise will fall back to implementation via the\n    `MutableMapping` interface."
  },
  {
    "code": "async def cycle(self, channel):\n        if not self.in_channel(channel):\n            raise NotInChannel(channel)\n        password = self.channels[channel]['password']\n        await self.part(channel)\n        await self.join(channel, password)",
    "docstring": "Rejoin channel."
  },
  {
    "code": "def _set_scores(self):\n        anom_scores = {}\n        self._generate_SAX()\n        self._construct_all_SAX_chunk_dict()\n        length = self.time_series_length\n        lws = self.lag_window_size\n        fws = self.future_window_size\n        for i, timestamp in enumerate(self.time_series.timestamps):\n            if i < lws or i > length - fws:\n                anom_scores[timestamp] = 0\n            else:\n                anom_scores[timestamp] = self._compute_anom_score_between_two_windows(i)\n        self.anom_scores = TimeSeries(self._denoise_scores(anom_scores))",
    "docstring": "Compute anomaly scores for the time series by sliding both lagging window and future window."
  },
  {
    "code": "def Equals(self, other):\n        if other is None:\n            return False\n        if other.PrevHash.ToBytes() == self.PrevHash.ToBytes() and other.PrevIndex == self.PrevIndex:\n            return True\n        return False",
    "docstring": "Test for equality.\n\n        Args:\n            other (obj):\n\n        Returns:\n            bool: True `other` equals self."
  },
  {
    "code": "def delete_state_changes(self, state_changes_to_delete: List[int]) -> None:\n        with self.write_lock, self.conn:\n            self.conn.executemany(\n                'DELETE FROM state_events WHERE identifier = ?',\n                state_changes_to_delete,\n            )",
    "docstring": "Delete state changes.\n\n        Args:\n            state_changes_to_delete: List of ids to delete."
  },
  {
    "code": "def get_real_end_line(token):\n    end_line = token.end_mark.line + 1\n    if not isinstance(token, yaml.ScalarToken):\n        return end_line\n    pos = token.end_mark.pointer - 1\n    while (pos >= token.start_mark.pointer - 1 and\n           token.end_mark.buffer[pos] in string.whitespace):\n        if token.end_mark.buffer[pos] == '\\n':\n            end_line -= 1\n        pos -= 1\n    return end_line",
    "docstring": "Finds the line on which the token really ends.\n\n    With pyyaml, scalar tokens often end on a next line."
  },
  {
    "code": "def get_msg(self):\n        width = 72\n        _msg = self.msg % {'distro': self.distro, 'vendor': self.vendor,\n                           'vendor_url': self.vendor_url,\n                           'vendor_text': self.vendor_text,\n                           'tmpdir': self.commons['tmpdir']}\n        _fmt = \"\"\n        for line in _msg.splitlines():\n            _fmt = _fmt + fill(line, width, replace_whitespace=False) + '\\n'\n        return _fmt",
    "docstring": "This method is used to prepare the preamble text to display to\n        the user in non-batch mode. If your policy sets self.distro that\n        text will be substituted accordingly. You can also override this\n        method to do something more complicated."
  },
  {
    "code": "def handle_dataframe(\n        df: pd.DataFrame,\n        entrez_id_name,\n        log2_fold_change_name,\n        adjusted_p_value_name,\n        entrez_delimiter,\n        base_mean=None,\n) -> List[Gene]:\n    logger.info(\"In _handle_df()\")\n    if base_mean is not None and base_mean in df.columns:\n        df = df[pd.notnull(df[base_mean])]\n    df = df[pd.notnull(df[entrez_id_name])]\n    df = df[pd.notnull(df[log2_fold_change_name])]\n    df = df[pd.notnull(df[adjusted_p_value_name])]\n    return [\n        Gene(\n            entrez_id=entrez_id,\n            log2_fold_change=data[log2_fold_change_name],\n            padj=data[adjusted_p_value_name]\n        )\n        for _, data in df.iterrows()\n        for entrez_id in str(data[entrez_id_name]).split(entrez_delimiter)\n    ]",
    "docstring": "Convert data frame on differential expression values as Gene objects.\n\n    :param df: Data frame with columns showing values on differential\n    expression.\n    :param cfp: An object that includes paths, cutoffs and other information.\n    :return list: A list of Gene objects."
  },
  {
    "code": "def build_routes(pfeed):\n    f = pfeed.frequencies[['route_short_name', 'route_long_name',\n      'route_type', 'shape_id']].drop_duplicates().copy()\n    f['route_id'] = 'r' + f['route_short_name'].map(str)\n    del f['shape_id']\n    return f",
    "docstring": "Given a ProtoFeed, return a DataFrame representing ``routes.txt``."
  },
  {
    "code": "def transitive_reduction(self):\n        combinations = []\n        for node, edges in self.graph.items():\n            combinations += [[node, edge] for edge in edges]\n        while True:\n            new_combinations = []\n            for comb1 in combinations:\n                for comb2 in combinations:\n                    if not comb1[-1] == comb2[0]:\n                        continue\n                    new_entry = comb1 + comb2[1:]\n                    if new_entry not in combinations:\n                        new_combinations.append(new_entry)\n            if not new_combinations:\n                break\n            combinations += new_combinations\n        constructed = {(c[0], c[-1]) for c in combinations if len(c) != 2}\n        for node, edges in self.graph.items():\n            bad_nodes = {e for n, e in constructed if node == n}\n            self.graph[node] = edges - bad_nodes",
    "docstring": "Performs a transitive reduction on the DAG. The transitive\n        reduction of a graph is a graph with as few edges as possible with the\n        same reachability as the original graph.\n\n        See https://en.wikipedia.org/wiki/Transitive_reduction"
  },
  {
    "code": "def arity_evaluation_checker(function):\n        is_class = inspect.isclass(function)\n        if is_class:\n            function = function.__init__\n        function_info = inspect.getargspec(function)\n        function_args = function_info.args\n        if is_class:\n            function_args = function_args[1:]\n        def evaluation_checker(*args, **kwargs):\n            kwarg_keys = set(kwargs.keys())\n            if function_info.keywords is None:\n                acceptable_kwargs = function_args[len(args):]\n                if not kwarg_keys.issubset(acceptable_kwargs):\n                    TypeError(\"Unrecognized Arguments: {0}\".format(\n                        [key for key in kwarg_keys\n                         if key not in acceptable_kwargs]\n                    ))\n            needed_args = function_args[len(args):]\n            if function_info.defaults:\n                needed_args = needed_args[:-len(function_info.defaults)]\n            return not needed_args or kwarg_keys.issuperset(needed_args)\n        return evaluation_checker",
    "docstring": "Build an evaluation checker that will return True when it is\n        guaranteed that all positional arguments have been accounted for."
  },
  {
    "code": "def update_config_value(self, config_m, config_key):\n        config_value = config_m.get_current_config_value(config_key)\n        if config_m is self.core_config_model:\n            list_store = self.core_list_store\n        elif config_m is self.gui_config_model:\n            list_store = self.gui_list_store\n        else:\n            return\n        self._update_list_store_entry(list_store, config_key, config_value)",
    "docstring": "Updates the corresponding list store of a changed config value\n\n        :param ConfigModel config_m: The config model that has been changed\n        :param str config_key: The config key who's value has been changed"
  },
  {
    "code": "def verify_param(self, param, must=[], r=None):\n        if APIKEY not in param:\n            param[APIKEY] = self.apikey()\n        r = Result() if r is None else r\n        for p in must:\n            if p not in param:\n                r.code(Code.ARGUMENT_MISSING).detail('missing-' + p)\n                break\n        return r",
    "docstring": "return Code.ARGUMENT_MISSING if every key in must not found in param"
  },
  {
    "code": "def write_csvs(self,\n                   asset_map,\n                   show_progress=False,\n                   invalid_data_behavior='warn'):\n        read = partial(\n            read_csv,\n            parse_dates=['day'],\n            index_col='day',\n            dtype=self._csv_dtypes,\n        )\n        return self.write(\n            ((asset, read(path)) for asset, path in iteritems(asset_map)),\n            assets=viewkeys(asset_map),\n            show_progress=show_progress,\n            invalid_data_behavior=invalid_data_behavior,\n        )",
    "docstring": "Read CSVs as DataFrames from our asset map.\n\n        Parameters\n        ----------\n        asset_map : dict[int -> str]\n            A mapping from asset id to file path with the CSV data for that\n            asset\n        show_progress : bool\n            Whether or not to show a progress bar while writing.\n        invalid_data_behavior : {'warn', 'raise', 'ignore'}\n            What to do when data is encountered that is outside the range of\n            a uint32."
  },
  {
    "code": "def decrypt(self, data):\n        decrypted_data = b\"\"\n        for i in range(0, len(data), 8):\n            block = data[i:i + 8]\n            block_length = len(block)\n            if block_length != 8:\n                raise ValueError(\"DES decryption must be a multiple of 8 \"\n                                 \"bytes\")\n            decrypted_data += self._decode_block(block)\n        return decrypted_data",
    "docstring": "DES decrypts the data based on the key it was initialised with.\n\n        :param data: The encrypted bytes string to decrypt\n        :return: The decrypted bytes string"
  },
  {
    "code": "def db(cls, path=None):\n        if cls.PATH is None and path is None:\n            raise Exception(\"No database specified\")\n        if path is None:\n            path = cls.PATH\n        if \".\" not in path:\n            raise Exception(('invalid path \"%s\"; database paths must be ' +\n                             'of the form \"database.collection\"') % (path,))\n        if CONNECTION.test_mode:\n            return CONNECTION.get_connection()[TEST_DATABASE_NAME][path]\n        (db, coll) = path.split('.', 1)\n        return CONNECTION.get_connection()[db][coll]",
    "docstring": "Returns a pymongo Collection object from the current database connection.\n        If the database connection is in test mode, collection will be in the\n        test database.\n        \n        @param path: if is None, the PATH attribute of the current class is used;\n            if is not None, this is used instead\n        \n        @raise Exception: if neither cls.PATH or path are valid"
  },
  {
    "code": "def recalibrate_quality(bam_file, sam_ref, dbsnp_file, picard_dir):\n    cl = [\"picard_gatk_recalibrate.py\", picard_dir, sam_ref, bam_file]\n    if dbsnp_file:\n        cl.append(dbsnp_file)\n    subprocess.check_call(cl)\n    out_file = glob.glob(\"%s*gatkrecal.bam\" % os.path.splitext(bam_file)[0])[0]\n    return out_file",
    "docstring": "Recalibrate alignments with GATK and provide pdf summary."
  },
  {
    "code": "def wait_for_task(upid, timeout=300):\n    start_time = time.time()\n    info = _lookup_proxmox_task(upid)\n    if not info:\n        log.error('wait_for_task: No task information '\n                  'retrieved based on given criteria.')\n        raise SaltCloudExecutionFailure\n    while True:\n        if 'status' in info and info['status'] == 'OK':\n            log.debug('Task has been finished!')\n            return True\n        time.sleep(3)\n        if time.time() - start_time > timeout:\n            log.debug('Timeout reached while waiting for task to be finished')\n            return False\n        info = _lookup_proxmox_task(upid)",
    "docstring": "Wait until a the task has been finished successfully"
  },
  {
    "code": "def sys_register_SDL_renderer(callback: Callable[[Any], None]) -> None:\n    with _PropagateException() as propagate:\n        @ffi.def_extern(onerror=propagate)\n        def _pycall_sdl_hook(sdl_surface: Any) -> None:\n            callback(sdl_surface)\n        lib.TCOD_sys_register_SDL_renderer(lib._pycall_sdl_hook)",
    "docstring": "Register a custom randering function with libtcod.\n\n    Note:\n        This callback will only be called by the SDL renderer.\n\n    The callack will receive a :any:`CData <ffi-cdata>` void* to an\n    SDL_Surface* struct.\n\n    The callback is called on every call to :any:`tcod.console_flush`.\n\n    Args:\n        callback Callable[[CData], None]:\n            A function which takes a single argument."
  },
  {
    "code": "def bind_type(python_value):\n    binding_table = {'bool': Bool, 'int': Int, 'float': Float}\n    if python_value is None:\n        return NoneType()\n    python_type = type(python_value)\n    gibica_type = binding_table.get(python_type.__name__)\n    if gibica_type is None:\n        raise TypeError('Impossible to recognize underlying type.')\n    return gibica_type(python_value)",
    "docstring": "Return a Gibica type derived from a Python type."
  },
  {
    "code": "def get_func_args(func):\n    if isinstance(func, functools.partial):\n        return _signature(func.func)\n    if inspect.isfunction(func) or inspect.ismethod(func):\n        return _signature(func)\n    return _signature(func.__call__)",
    "docstring": "Given a callable, return a tuple of argument names. Handles\n    `functools.partial` objects and class-based callables.\n\n    .. versionchanged:: 3.0.0a1\n        Do not return bound arguments, eg. ``self``."
  },
  {
    "code": "def make_interval(long_name, short_name):\n    return Group(\n        Regex(\"(-+)?[0-9]+\")\n        + (\n            upkey(long_name + \"s\")\n            | Regex(long_name + \"s\").setParseAction(upcaseTokens)\n            | upkey(long_name)\n            | Regex(long_name).setParseAction(upcaseTokens)\n            | upkey(short_name)\n            | Regex(short_name).setParseAction(upcaseTokens)\n        )\n    ).setResultsName(long_name)",
    "docstring": "Create an interval segment"
  },
  {
    "code": "def samples(self):\n        if not hasattr(self,'sampler') and self._samples is None:\n            raise AttributeError('Must run MCMC (or load from file) '+\n                                 'before accessing samples')\n        if self._samples is not None:\n            df = self._samples\n        else:\n            self._make_samples()\n            df = self._samples\n        return df",
    "docstring": "Dataframe with samples drawn from isochrone according to posterior\n\n        Columns include both the sampling parameters from the MCMC\n        fit (mass, age, Fe/H, [distance, A_V]), and also evaluation\n        of the :class:`Isochrone` at each of these sample points---this\n        is how chains of physical/observable parameters get produced."
  },
  {
    "code": "def _iter_keys(key):\n    for i in range(winreg.QueryInfoKey(key)[0]):\n        yield winreg.OpenKey(key, winreg.EnumKey(key, i))",
    "docstring": "! Iterate over subkeys of a key"
  },
  {
    "code": "def primers(self, tm=60):\n        self.primers = coral.design.primers(self.template, tm=tm)\n        return self.primers",
    "docstring": "Design primers for amplifying the assembled sequence.\n\n        :param tm: melting temperature (lower than overlaps is best).\n        :type tm: float\n        :returns: Primer list (the output of coral.design.primers).\n        :rtype: list"
  },
  {
    "code": "def gborders(img, alpha=1.0, sigma=1.0):\n    gradnorm = gaussian_gradient_magnitude(img, sigma, mode='constant')\n    return 1.0/np.sqrt(1.0 + alpha*gradnorm)",
    "docstring": "Stopping criterion for image borders."
  },
  {
    "code": "def get_wsgi_request_object(curr_request, method, url, headers, body):\n    x_headers = headers_to_include_from_request(curr_request)\n    method, t_headers = pre_process_method_headers(method, headers)\n    if \"CONTENT_TYPE\" not in t_headers:\n        t_headers.update({\"CONTENT_TYPE\": _settings.DEFAULT_CONTENT_TYPE})\n    x_headers.update(t_headers)\n    content_type = x_headers.get(\"CONTENT_TYPE\", _settings.DEFAULT_CONTENT_TYPE)\n    _request_factory = BatchRequestFactory()\n    _request_provider = getattr(_request_factory, method)\n    secure = _settings.USE_HTTPS\n    request = _request_provider(url, data=body, secure=secure,\n                                content_type=content_type, **x_headers)\n    return request",
    "docstring": "Based on the given request parameters, constructs and returns the WSGI request object."
  },
  {
    "code": "def from_snl(cls, snl):\n        hist = []\n        for h in snl.history:\n            d = h.description\n            d['_snl'] = {'url': h.url, 'name': h.name}\n            hist.append(d)\n        return cls(snl.structure, history=hist)",
    "docstring": "Create TransformedStructure from SNL.\n\n        Args:\n            snl (StructureNL): Starting snl\n\n        Returns:\n            TransformedStructure"
  },
  {
    "code": "def get_tissue_in_references(self, entry):\n        tissue_in_references = []\n        query = \"./reference/source/tissue\"\n        tissues = {x.text for x in entry.iterfind(query)}\n        for tissue in tissues:\n            if tissue not in self.tissues:\n                self.tissues[tissue] = models.TissueInReference(tissue=tissue)\n            tissue_in_references.append(self.tissues[tissue])\n        return tissue_in_references",
    "docstring": "get list of models.TissueInReference from XML node entry\n\n        :param entry: XML node entry\n        :return: list of :class:`pyuniprot.manager.models.TissueInReference` objects"
  },
  {
    "code": "def stream_members(self, stream_id):\n        response, status_code = self.__pod__.Streams.get_v1_admin_stream_id_membership_list(\n            sessionToken=self.__session__,\n            id=stream_id\n        ).result()\n        self.logger.debug('%s: %s' % (status_code, response))\n        return status_code, response",
    "docstring": "get stream members"
  },
  {
    "code": "def process_binding_statements(self):\n        G = self.G\n        statements = []\n        binding_nodes = self.find_event_with_outgoing_edges('Binding',\n                                                            ['Theme',\n                                                                'Theme2'])\n        for node in binding_nodes:\n            theme1 = self.get_entity_text_for_relation(node, 'Theme')\n            theme1_node = self.get_related_node(node, 'Theme')\n            theme2 = self.get_entity_text_for_relation(node, 'Theme2')\n            assert(theme1 is not None)\n            assert(theme2 is not None)\n            evidence = self.node_to_evidence(theme1_node, is_direct=True)\n            statements.append(Complex([s2a(theme1), s2a(theme2)],\n                              evidence=evidence))\n        return statements",
    "docstring": "Looks for Binding events in the graph and extracts them into INDRA\n        statements.\n\n        In particular, looks for a Binding event node with outgoing edges\n        with relations Theme and Theme2 - the entities these edges point to\n        are the two constituents of the Complex INDRA statement."
  },
  {
    "code": "def _get_parameter_conversion_entry(parameter_config):\n  entry = _PARAM_CONVERSION_MAP.get(parameter_config.get('type'))\n  if entry is None and 'enum' in parameter_config:\n    entry = _PARAM_CONVERSION_MAP['enum']\n  return entry",
    "docstring": "Get information needed to convert the given parameter to its API type.\n\n  Args:\n    parameter_config: The dictionary containing information specific to the\n      parameter in question. This is retrieved from request.parameters in the\n      method config.\n\n  Returns:\n    The entry from _PARAM_CONVERSION_MAP with functions/information needed to\n    validate and convert the given parameter from a string to the type expected\n    by the API."
  },
  {
    "code": "def _parse_deploy(self, deploy_values: dict, service_config: dict):\n        mode = {}\n        for d_value in deploy_values:\n            if 'restart_policy' in d_value:\n                restart_spec = docker.types.RestartPolicy(\n                    **deploy_values[d_value])\n                service_config['restart_policy'] = restart_spec\n            if 'placement' in d_value:\n                for constraints_key, constraints_value in \\\n                        deploy_values[d_value].items():\n                    service_config[constraints_key] = constraints_value\n            if 'mode' in d_value:\n                mode[d_value] = deploy_values[d_value]\n            if 'replicas' in d_value:\n                mode[d_value] = deploy_values[d_value]\n            if 'resources' in d_value:\n                resource_spec = self._parse_resources(\n                    deploy_values, d_value)\n                service_config['resources'] = resource_spec\n        mode_spec = docker.types.ServiceMode(**mode)\n        service_config['mode'] = mode_spec",
    "docstring": "Parse deploy key.\n\n        Args:\n            deploy_values (dict): deploy configuration values\n            service_config (dict): Service configuration"
  },
  {
    "code": "def supportsType(self, type_uri):\n        return (\n            (type_uri in self.type_uris) or \n            (type_uri == OPENID_2_0_TYPE and self.isOPIdentifier())\n            )",
    "docstring": "Does this endpoint support this type?\n\n        I consider C{/server} endpoints to implicitly support C{/signon}."
  },
  {
    "code": "def _RunSingleHook(self, hook_cls, executed_set, required=None):\n    if hook_cls in executed_set:\n      return\n    for pre_hook in hook_cls.pre:\n      self._RunSingleHook(pre_hook, executed_set, required=hook_cls.__name__)\n    cls_instance = hook_cls()\n    if required:\n      logging.debug(\"Initializing %s, required by %s\", hook_cls.__name__,\n                    required)\n    else:\n      logging.debug(\"Initializing %s\", hook_cls.__name__)\n    cls_instance.Run()\n    executed_set.add(hook_cls)\n    if hook_cls not in self.already_run_once:\n      cls_instance.RunOnce()\n      self.already_run_once.add(hook_cls)",
    "docstring": "Run the single hook specified by resolving all its prerequisites."
  },
  {
    "code": "def PyParseRangeCheck(lower_bound, upper_bound):\n  def CheckRange(string, location, tokens):\n    try:\n      check_number = tokens[0]\n    except IndexError:\n      check_number = -1\n    if check_number < lower_bound:\n      raise pyparsing.ParseException(\n          'Value: {0:d} precedes lower bound: {1:d}'.format(\n              check_number, lower_bound))\n    if check_number > upper_bound:\n      raise pyparsing.ParseException(\n          'Value: {0:d} exceeds upper bound: {1:d}'.format(\n              check_number, upper_bound))\n  return CheckRange",
    "docstring": "Verify that a number is within a defined range.\n\n  This is a callback method for pyparsing setParseAction\n  that verifies that a read number is within a certain range.\n\n  To use this method it needs to be defined as a callback method\n  in setParseAction with the upper and lower bound set as parameters.\n\n  Args:\n    lower_bound (int): lower bound of the range.\n    upper_bound (int): upper bound of the range.\n\n  Returns:\n    Function: callback method that can be used by pyparsing setParseAction."
  },
  {
    "code": "def read_hierarchy(self, fid):\n        lin = self.read_line(fid)\n        while lin != 'end':\n            parts = lin.split()\n            if lin != 'begin':\n                ind = self.get_index_by_name(parts[0])\n                for i in range(1, len(parts)):\n                    self.vertices[ind].children.append(self.get_index_by_name(parts[i]))\n            lin = self.read_line(fid)\n        lin = self.read_line(fid)\n        return lin",
    "docstring": "Read hierarchy information from acclaim skeleton file stream."
  },
  {
    "code": "def show_gateway_device(self, gateway_device_id, **_params):\n        return self.get(self.gateway_device_path % gateway_device_id,\n                        params=_params)",
    "docstring": "Fetch a gateway device."
  },
  {
    "code": "def restore(self):\n        signal.signal(signal.SIGINT, self.original_sigint)\n        signal.signal(signal.SIGTERM, self.original_sigterm)\n        if os.name == 'nt':\n            signal.signal(signal.SIGBREAK, self.original_sigbreak)",
    "docstring": "Restore signal handlers to their original settings."
  },
  {
    "code": "def post(url, data=None, json=None, **kwargs):\n    _set_content_type(kwargs)\n    if _content_type_is_json(kwargs) and data is not None:\n        data = dumps(data)\n    _log_request('POST', url, kwargs, data)\n    response = requests.post(url, data, json, **kwargs)\n    _log_response(response)\n    return response",
    "docstring": "A wrapper for ``requests.post``."
  },
  {
    "code": "def all(self):\n        self._check_layout()\n        return LayoutSlice(self.layout, slice(0, len(self.layout.fields), 1))",
    "docstring": "Returns all layout objects of first level of depth"
  },
  {
    "code": "def get_one(self, fields=list()):\n        response = self.session.get(self._get_table_url(),\n                                    params=self._get_formatted_query(fields, limit=None, order_by=list(), offset=None))\n        content = self._get_content(response)\n        l = len(content)\n        if l > 1:\n            raise MultipleResults('Multiple results for get_one()')\n        if len(content) == 0:\n            return {}\n        return content[0]",
    "docstring": "Convenience function for queries returning only one result. Validates response before returning.\n\n        :param fields: List of fields to return in the result\n        :raise:\n            :MultipleResults: if more than one match is found\n        :return:\n            - Record content"
  },
  {
    "code": "def init_logging():\n    fmt = '%(asctime)s.%(msecs)03d | %(name)-60s | %(levelname)-7s ' \\\n          '| %(message)s'\n    logging.basicConfig(format=fmt, datefmt='%H:%M:%S', level=logging.DEBUG)",
    "docstring": "Initialise Python logging."
  },
  {
    "code": "def frequencies_plot(self, xmin=0, xmax=200):\n        helptext =\n        pconfig = {\n            'id': 'Jellyfish_kmer_plot',\n            'title': 'Jellyfish: K-mer plot',\n            'ylab': 'Counts',\n            'xlab': 'k-mer frequency',\n            'xDecimals': False,\n            'xmin': xmin,\n            'xmax': xmax\n        }\n        self.add_section(\n            anchor = 'jellyfish_kmer_plot',\n            description = 'The K-mer plot lets you estimate library complexity and coverage from k-mer content.',\n            helptext = helptext,\n            plot = linegraph.plot(self.jellyfish_data, pconfig)\n        )",
    "docstring": "Generate the qualities plot"
  },
  {
    "code": "def get_shortcut(self, name):\n        name = self.__normalize_name(name)\n        action = self.get_action(name)\n        if not action:\n            return \"\"\n        return action.shortcut().toString()",
    "docstring": "Returns given action shortcut.\n\n        :param name: Action to retrieve the shortcut.\n        :type name: unicode\n        :return: Action shortcut.\n        :rtype: unicode"
  },
  {
    "code": "def get_pins(self):\n        result = []\n        for a in range(0, 7):\n            result.append(GPIOPin(self, '_action', {'pin': 'A{}'.format(a)}, name='A{}'.format(a)))\n        for b in range(0, 7):\n            result.append(GPIOPin(self, '_action', {'pin': 'B{}'.format(b)}, name='B{}'.format(b)))\n        return result",
    "docstring": "Get a list containing references to all 16 pins of the chip.\n\n        :Example:\n\n        >>> expander = MCP23017I2C(gw)\n        >>> pins = expander.get_pins()\n        >>> pprint.pprint(pins)\n        [<GPIOPin A0 on MCP23017I2C>,\n         <GPIOPin A1 on MCP23017I2C>,\n         <GPIOPin A2 on MCP23017I2C>,\n         <GPIOPin A3 on MCP23017I2C>,\n         <GPIOPin A4 on MCP23017I2C>,\n         <GPIOPin A5 on MCP23017I2C>,\n         <GPIOPin A6 on MCP23017I2C>,\n         <GPIOPin B0 on MCP23017I2C>,\n         <GPIOPin B1 on MCP23017I2C>,\n         <GPIOPin B2 on MCP23017I2C>,\n         <GPIOPin B3 on MCP23017I2C>,\n         <GPIOPin B4 on MCP23017I2C>,\n         <GPIOPin B5 on MCP23017I2C>,\n         <GPIOPin B6 on MCP23017I2C>]"
  },
  {
    "code": "def compose(f, *fs):\n    rfs = list(chain([f], fs))\n    rfs.reverse()\n    def composed(*args, **kwargs):\n        return reduce(\n            lambda result, fn: fn(result),\n            rfs[1:],\n            rfs[0](*args, **kwargs))\n    return composed",
    "docstring": "Compose functions right to left.\n\n    compose(f, g, h)(x) -> f(g(h(x)))\n\n    Args:\n        f, *fs: The head and rest of a sequence of callables. The\n                rightmost function passed can accept any arguments and\n                the returned function will have the same signature as\n                this last provided function.  All preceding functions\n                must be unary.\n\n    Returns:\n        The composition of the argument functions. The returned\n        function will accept the same arguments as the rightmost\n        passed in function."
  },
  {
    "code": "def _inputcooker_store(self, char):\n        if self.sb:\n            self.sbdataq = self.sbdataq + char\n        else:\n            self.inputcooker_store_queue(char)",
    "docstring": "Put the cooked data in the correct queue"
  },
  {
    "code": "def _changeGroupImage(self, image_id, thread_id=None):\n        thread_id, thread_type = self._getThread(thread_id, None)\n        data = {\"thread_image_id\": image_id, \"thread_id\": thread_id}\n        j = self._post(self.req_url.THREAD_IMAGE, data, fix_request=True, as_json=True)\n        return image_id",
    "docstring": "Changes a thread image from an image id\n\n        :param image_id: ID of uploaded image\n        :param thread_id: User/Group ID to change image. See :ref:`intro_threads`\n        :raises: FBchatException if request failed"
  },
  {
    "code": "def _update_field(self, action, field, value, max_tries, tries=0):\n        self.fetch()\n        action(self, field, value)\n        try:\n            self.save()\n        except requests.HTTPError as ex:\n            if tries < max_tries and ex.response.status_code == 409:\n                self._update_field(\n                    action, field, value, max_tries, tries=tries+1)\n            else:\n                raise",
    "docstring": "Private update_field method. Wrapped by Document.update_field.\n        Tracks a \"tries\" var to help limit recursion."
  },
  {
    "code": "def document_quote (document):\n    doc, query = urllib.splitquery(document)\n    doc = url_quote_part(doc, '/=,')\n    if query:\n        return \"%s?%s\" % (doc, query)\n    return doc",
    "docstring": "Quote given document."
  },
  {
    "code": "def is_text_extractor_available(extension: str) -> bool:\n    if extension is not None:\n        extension = extension.lower()\n    info = ext_map.get(extension)\n    if info is None:\n        return False\n    availability = info[AVAILABILITY]\n    if type(availability) == bool:\n        return availability\n    elif callable(availability):\n        return availability()\n    else:\n        raise ValueError(\n            \"Bad information object for extension: {}\".format(extension))",
    "docstring": "Is a text extractor available for the specified extension?"
  },
  {
    "code": "def set_of_vars(arg_plot):\n    return set(var for var in arg_plot.split(',') if var in phyvars.PLATES)",
    "docstring": "Build set of needed variables.\n\n    Args:\n        arg_plot (str): string with variable names separated with ``,``.\n    Returns:\n        set of str: set of variables."
  },
  {
    "code": "def match_gpus(available_devices, requirements):\n    if not requirements:\n        return []\n    if not available_devices:\n        raise InsufficientGPUError(\"No GPU devices available, but {} devices required.\".format(len(requirements)))\n    available_devices = available_devices.copy()\n    used_devices = []\n    for req in requirements:\n        dev = search_device(req, available_devices)\n        if dev:\n            used_devices.append(dev)\n            available_devices.remove(dev)\n        else:\n            raise InsufficientGPUError(\"Not all GPU requirements could be fulfilled.\")\n    return used_devices",
    "docstring": "Determines sufficient GPUs for the given requirements and returns a list of GPUDevices.\n    If there aren't sufficient GPUs a InsufficientGPUException is thrown.\n\n    :param available_devices: A list of GPUDevices\n    :param requirements: A list of GPURequirements\n\n    :return: A list of sufficient devices"
  },
  {
    "code": "def viewport_to_screen_space(framebuffer_size: vec2, point: vec4) -> vec2:\n    return (framebuffer_size * point.xy) / point.w",
    "docstring": "Transform point in viewport space to screen space."
  },
  {
    "code": "def ols_covariance(self):\n        Y = np.array([reg[self.lags:reg.shape[0]] for reg in self.data])        \n        return (1.0/(Y[0].shape[0]))*np.dot(self.residuals(Y),np.transpose(self.residuals(Y)))",
    "docstring": "Creates OLS estimate of the covariance matrix\n\n        Returns\n        ----------\n        The OLS estimate of the covariance matrix"
  },
  {
    "code": "def load_device(self, serial=None):\n        serials = android_device.list_adb_devices()\n        if not serials:\n            raise Error('No adb device found!')\n        if not serial:\n            env_serial = os.environ.get('ANDROID_SERIAL', None)\n            if env_serial is not None:\n                serial = env_serial\n            elif len(serials) == 1:\n                serial = serials[0]\n            else:\n                raise Error(\n                    'Expected one phone, but %d found. Use the -s flag or '\n                    'specify ANDROID_SERIAL.' % len(serials))\n        if serial not in serials:\n            raise Error('Device \"%s\" is not found by adb.' % serial)\n        ads = android_device.get_instances([serial])\n        assert len(ads) == 1\n        self._ad = ads[0]",
    "docstring": "Creates an AndroidDevice for the given serial number.\n\n        If no serial is given, it will read from the ANDROID_SERIAL\n        environmental variable. If the environmental variable is not set, then\n        it will read from 'adb devices' if there is only one."
  },
  {
    "code": "def exists(self, obj_id, obj_type=None):\n        return self.object_key(obj_id, obj_type) in self._data",
    "docstring": "Return whether the given object exists in the search index.\n\n        :param obj_id: The object's unique identifier.\n        :param obj_type: The object's type."
  },
  {
    "code": "def return_real_id(self):\n        if self._prepopulated is False:\n            raise errors.EmptyDatabase(self.dbpath)\n        else:\n            return return_real_id_base(self.dbpath, self._set_object)",
    "docstring": "Returns a list of real_id's\n\n        Parameters\n        ----------\n\n        Returns\n        -------\n        A list of real_id values for the dataset (a real_id is the filename minus the suffix and prefix)"
  },
  {
    "code": "def set_unobserved_before(self,tlen,qlen,nt,p):\n    self._unobservable.set_before(tlen,qlen,nt,p)",
    "docstring": "Set the unobservable sequence data before this base\n\n    :param tlen: target homopolymer length\n    :param qlen: query homopolymer length\n    :param nt: nucleotide\n    :param p: p is the probability of attributing this base to the unobserved error\n    :type tlen: int\n    :type qlen: int\n    :type nt: char\n    :type p: float"
  },
  {
    "code": "def model_deleted(sender, instance,\n                          using,\n                          **kwargs):\n    opts = get_opts(instance)\n    model = '.'.join([opts.app_label, opts.object_name])\n    distill_model_event(instance, model, 'deleted')",
    "docstring": "Automatically triggers \"deleted\" actions."
  },
  {
    "code": "def Sign(verifiable, keypair):\n        prikey = bytes(keypair.PrivateKey)\n        hashdata = verifiable.GetHashData()\n        res = Crypto.Default().Sign(hashdata, prikey)\n        return res",
    "docstring": "Sign the `verifiable` object with the private key from `keypair`.\n\n        Args:\n            verifiable:\n            keypair (neocore.KeyPair):\n\n        Returns:\n            bool: True if successfully signed. False otherwise."
  },
  {
    "code": "def load_vint(buf, pos):\n    limit = min(pos + 11, len(buf))\n    res = ofs = 0\n    while pos < limit:\n        b = _byte_code(buf[pos])\n        res += ((b & 0x7F) << ofs)\n        pos += 1\n        ofs += 7\n        if b < 0x80:\n            return res, pos\n    raise BadRarFile('cannot load vint')",
    "docstring": "Load variable-size int."
  },
  {
    "code": "def run(\n    categories, param_file, project_dir, plugin, target,\n    status_update_interval\n):\n    return _run(\n        categories, param_file, project_dir, plugin, target,\n        status_update_interval\n    )",
    "docstring": "Generate code for this project and run it"
  },
  {
    "code": "def query(cls, *criteria, **filters):\n        query = cls.dbmodel.query.filter(\n            *criteria).filter_by(**filters)\n        return [cls(obj) for obj in query.all()]",
    "docstring": "Wrap sqlalchemy query methods.\n\n        A wrapper for the filter and filter_by functions of sqlalchemy.\n        Define a dict with which columns should be filtered by which values.\n\n        .. codeblock:: python\n\n            WorkflowObject.query(id=123)\n            WorkflowObject.query(status=ObjectStatus.COMPLETED)\n\n        The function supports also \"hybrid\" arguments using WorkflowObjectModel\n        indirectly.\n\n        .. codeblock:: python\n\n            WorkflowObject.query(\n                WorkflowObject.dbmodel.status == ObjectStatus.COMPLETED,\n                user_id=user_id\n            )\n\n        See also SQLAlchemy BaseQuery's filter and filter_by documentation."
  },
  {
    "code": "def allan_variance(data, dt, tmax=10):\n    allanvar = []\n    nmax = len(data) if len(data) < tmax / dt else int(tmax / dt)\n    for i in range(1, nmax+1):\n        databis = data[len(data) % i:]\n        y = databis.reshape(len(data)//i, i).mean(axis=1)\n        allanvar.append(((y[1:] - y[:-1])**2).mean() / 2)\n    return dt * np.arange(1, nmax+1), np.array(allanvar)",
    "docstring": "Calculate Allan variance.\n\n    Args:\n        data (np.ndarray): Input data.\n        dt (float): Time between each data.\n        tmax (float): Maximum time.\n\n    Returns:\n        vk (np.ndarray): Frequency.\n        allanvar (np.ndarray): Allan variance."
  },
  {
    "code": "def to_type_with_default(value_type, value, default_value):\n        result = TypeConverter.to_nullable_type(value_type, value)\n        return result if result != None else default_value",
    "docstring": "Converts value into an object type specified by Type Code or returns default value when conversion is not possible.\n\n        :param value_type: the TypeCode for the data type into which 'value' is to be converted.\n\n        :param value: the value to convert.\n\n        :param default_value: the default value to return if conversion is not possible (returns None).\n\n        :return: object value of type corresponding to TypeCode, or default value when conversion is not supported."
  },
  {
    "code": "def zSaveFile(self, fileName):\n        cmd = \"SaveFile,{}\".format(fileName)\n        reply = self._sendDDEcommand(cmd)\n        return int(float(reply.rstrip()))",
    "docstring": "Saves the lens currently loaded in the server to a Zemax file"
  },
  {
    "code": "def expect_dimensions(__funcname=_qualified_name, **dimensions):\n    if isinstance(__funcname, str):\n        def get_funcname(_):\n            return __funcname\n    else:\n        get_funcname = __funcname\n    def _expect_dimension(expected_ndim):\n        def _check(func, argname, argvalue):\n            actual_ndim = argvalue.ndim\n            if actual_ndim != expected_ndim:\n                if actual_ndim == 0:\n                    actual_repr = 'scalar'\n                else:\n                    actual_repr = \"%d-D array\" % actual_ndim\n                raise ValueError(\n                    \"{func}() expected a {expected:d}-D array\"\n                    \" for argument {argname!r}, but got a {actual}\"\n                    \" instead.\".format(\n                        func=get_funcname(func),\n                        expected=expected_ndim,\n                        argname=argname,\n                        actual=actual_repr,\n                    )\n                )\n            return argvalue\n        return _check\n    return preprocess(**valmap(_expect_dimension, dimensions))",
    "docstring": "Preprocessing decorator that verifies inputs are numpy arrays with a\n    specific dimensionality.\n\n    Examples\n    --------\n    >>> from numpy import array\n    >>> @expect_dimensions(x=1, y=2)\n    ... def foo(x, y):\n    ...    return x[0] + y[0, 0]\n    ...\n    >>> foo(array([1, 1]), array([[1, 1], [2, 2]]))\n    2\n    >>> foo(array([1, 1]), array([1, 1]))  # doctest: +NORMALIZE_WHITESPACE\n    ...                                    # doctest: +ELLIPSIS\n    Traceback (most recent call last):\n       ...\n    ValueError: ...foo() expected a 2-D array for argument 'y',\n    but got a 1-D array instead."
  },
  {
    "code": "def token(name):\n    def wrap(f):\n        tokenizers.append((name, f))\n        return f\n    return wrap",
    "docstring": "Marker for a token\n\n    :param str name: Name of tokenizer"
  },
  {
    "code": "def complement(color):\n    r\n    (r, g, b) = parse_color(color)\n    gcolor = grapefruit.Color((r / 255.0, g / 255.0, b / 255.0))\n    complement = gcolor.ComplementaryColor()\n    (r, g, b) = [int(c * 255.0) for c in complement.rgb]\n    return (r, g, b)",
    "docstring": "r\"\"\"Calculates polar opposite of color\n\n    This isn't guaranteed to look good >_> (especially with brighter, higher\n    intensity colors.) This will be replaced with a formula that produces\n    better looking colors in the future.\n\n    >>> complement('red')\n    (0, 255, 76)\n    >>> complement((0, 100, 175))\n    (175, 101, 0)"
  },
  {
    "code": "def all(self, value, pos=None):\n        value = bool(value)\n        length = self.len\n        if pos is None:\n            pos = xrange(self.len)\n        for p in pos:\n            if p < 0:\n                p += length\n            if not 0 <= p < length:\n                raise IndexError(\"Bit position {0} out of range.\".format(p))\n            if not self._datastore.getbit(p) is value:\n                return False\n        return True",
    "docstring": "Return True if one or many bits are all set to value.\n\n        value -- If value is True then checks for bits set to 1, otherwise\n                 checks for bits set to 0.\n        pos -- An iterable of bit positions. Negative numbers are treated in\n               the same way as slice indices. Defaults to the whole bitstring."
  },
  {
    "code": "def toggle_bit(self, position: int):\n        if position > (self._bit_width - 1):\n            raise ValueError('position greater than the bit width')\n        self._value ^= (1 << position)\n        self._text_update()",
    "docstring": "Toggles the value at position\n\n        :param position: integer between 0 and 7, inclusive\n        :return: None"
  },
  {
    "code": "def get_tmp_file(dir=None):\n    \"Create and return a tmp filename, optionally at a specific path. `os.remove` when done with it.\"\n    with tempfile.NamedTemporaryFile(delete=False, dir=dir) as f: return f.name",
    "docstring": "Create and return a tmp filename, optionally at a specific path. `os.remove` when done with it."
  },
  {
    "code": "def create(cls, zmq_context, endpoint):\n        socket = zmq_context.socket(zmq.REQ)\n        socket.connect(endpoint)\n        return cls(socket)",
    "docstring": "Create new client transport.\n\n        Instead of creating the socket yourself, you can call this function and\n        merely pass the :py:class:`zmq.core.context.Context` instance.\n\n        By passing a context imported from :py:mod:`zmq.green`, you can use\n        green (gevent) 0mq sockets as well.\n\n        :param zmq_context: A 0mq context.\n        :param endpoint: The endpoint the server is bound to."
  },
  {
    "code": "def wait_all(jobs, timeout=None):\n    return Job._wait(jobs, timeout, concurrent.futures.ALL_COMPLETED)",
    "docstring": "Return when at all of the specified jobs have completed or timeout expires.\n\n    Args:\n      jobs: a Job or list of Jobs to wait on.\n      timeout: a timeout in seconds to wait for. None (the default) means no timeout.\n    Returns:\n      A list of the jobs that have now completed or None if there were no jobs."
  },
  {
    "code": "async def cursor_async(self):\n        await self.connect_async(loop=self._loop)\n        if self.transaction_depth_async() > 0:\n            conn = self.transaction_conn_async()\n        else:\n            conn = None\n        try:\n            return (await self._async_conn.cursor(conn=conn))\n        except:\n            await self.close_async()\n            raise",
    "docstring": "Acquire async cursor."
  },
  {
    "code": "def on_excepthandler(self, node):\n        return (self.run(node.type), node.name, node.body)",
    "docstring": "Exception handler..."
  },
  {
    "code": "def rename(self, new_name, range=None):\n        self.log.debug('rename: in')\n        if not new_name:\n            new_name = self.editor.ask_input(\"Rename to:\")\n        self.editor.write(noautocmd=True)\n        b, e = self.editor.word_under_cursor_pos()\n        current_file = self.editor.path()\n        self.editor.raw_message(current_file)\n        self.send_refactor_request(\n            \"RefactorReq\",\n            {\n                \"typehint\": \"RenameRefactorDesc\",\n                \"newName\": new_name,\n                \"start\": self.get_position(b[0], b[1]),\n                \"end\": self.get_position(e[0], e[1]) + 1,\n                \"file\": current_file,\n            },\n            {\"interactive\": False}\n        )",
    "docstring": "Request a rename to the server."
  },
  {
    "code": "def _get_upserts_distinct(queryset, model_objs_updated, model_objs_created, unique_fields):\n    created_models = []\n    if model_objs_created:\n        created_models.extend(\n            queryset.extra(\n                where=['({unique_fields_sql}) in %s'.format(\n                    unique_fields_sql=', '.join(unique_fields)\n                )],\n                params=[\n                    tuple([\n                        tuple([\n                            getattr(model_obj, field)\n                            for field in unique_fields\n                        ])\n                        for model_obj in model_objs_created\n                    ])\n                ]\n            )\n        )\n    return model_objs_updated, created_models",
    "docstring": "Given a list of model objects that were updated and model objects that were created,\n    fetch the pks of the newly created models and return the two lists in a tuple"
  },
  {
    "code": "def _initialize_application():\n    RuntimeGlobals.application = umbra.ui.common.get_application_instance()\n    umbra.ui.common.set_window_default_icon(RuntimeGlobals.application)\n    RuntimeGlobals.reporter = umbra.reporter.install_exception_reporter()",
    "docstring": "Initializes the Application."
  },
  {
    "code": "def delete(self, port, qos_policy=None):\n        LOG.info(\"Deleting QoS policy %(qos_policy)s on port %(port)s\",\n                 dict(qos_policy=qos_policy, port=port))\n        self._utils.remove_port_qos_rule(port[\"port_id\"])",
    "docstring": "Remove QoS rules from port.\n\n        :param port: port object.\n        :param qos_policy: the QoS policy to be removed from port."
  },
  {
    "code": "def get_attention(config: AttentionConfig, max_seq_len: int, prefix: str = C.ATTENTION_PREFIX) -> 'Attention':\n    att_cls = Attention.get_attention_cls(config.type)\n    params = config.__dict__.copy()\n    params.pop('_frozen')\n    params['max_seq_len'] = max_seq_len\n    params['prefix'] = prefix\n    return _instantiate(att_cls, params)",
    "docstring": "Returns an Attention instance based on attention_type.\n\n    :param config: Attention configuration.\n    :param max_seq_len: Maximum length of source sequences.\n    :param prefix: Name prefix.\n    :return: Instance of Attention."
  },
  {
    "code": "def imagedatadict_to_ndarray(imdict):\n    arr = imdict['Data']\n    im = None\n    if isinstance(arr, parse_dm3.array.array):\n        im = numpy.asarray(arr, dtype=arr.typecode)\n    elif isinstance(arr, parse_dm3.structarray):\n        t = tuple(arr.typecodes)\n        im = numpy.frombuffer(\n            arr.raw_data,\n            dtype=structarray_to_np_map[t])\n    assert dm_image_dtypes[imdict[\"DataType\"]][1] == im.dtype\n    assert imdict['PixelDepth'] == im.dtype.itemsize\n    im = im.reshape(imdict['Dimensions'][::-1])\n    if imdict[\"DataType\"] == 23:\n        im = im.view(numpy.uint8).reshape(im.shape + (-1, ))[..., :-1]\n    return im",
    "docstring": "Converts the ImageData dictionary, imdict, to an nd image."
  },
  {
    "code": "def read_feather(path, columns=None, use_threads=True):\n    feather, pyarrow = _try_import()\n    path = _stringify_path(path)\n    if LooseVersion(pyarrow.__version__) < LooseVersion('0.11.0'):\n        int_use_threads = int(use_threads)\n        if int_use_threads < 1:\n            int_use_threads = 1\n        return feather.read_feather(path, columns=columns,\n                                    nthreads=int_use_threads)\n    return feather.read_feather(path, columns=columns,\n                                use_threads=bool(use_threads))",
    "docstring": "Load a feather-format object from the file path\n\n    .. versionadded 0.20.0\n\n    Parameters\n    ----------\n    path : string file path, or file-like object\n    columns : sequence, default None\n        If not provided, all columns are read\n\n        .. versionadded 0.24.0\n    nthreads : int, default 1\n        Number of CPU threads to use when reading to pandas.DataFrame\n\n       .. versionadded 0.21.0\n       .. deprecated 0.24.0\n    use_threads : bool, default True\n        Whether to parallelize reading using multiple threads\n\n       .. versionadded 0.24.0\n\n    Returns\n    -------\n    type of object stored in file"
  },
  {
    "code": "def _remove_data_dir_path(self, inp=None):\n        if inp is not None:\n            split_str = os.path.join(self.data_path, '')\n            return inp.apply(lambda x: x.split(split_str)[-1])",
    "docstring": "Remove the data directory path from filenames"
  },
  {
    "code": "def rand_block(minimum, scale, maximum=1):\n    t = min(rand_pareto_float(minimum, scale), maximum)\n    time.sleep(t)\n    return t",
    "docstring": "block current thread at random pareto time ``minimum < block < 15`` and return the sleep time ``seconds``\n\n    :param minimum:\n    :type minimum:\n    :param scale:\n    :type scale:\n    :param slow_mode: a tuple e.g.(2, 5)\n    :type slow_mode: tuple\n    :return:"
  },
  {
    "code": "def has_chosen(state, correct, msgs):\n    ctxt = {}\n    exec(state.student_code, globals(), ctxt)\n    sel_indx = ctxt[\"selected_option\"]\n    if sel_indx != correct:\n        state.report(Feedback(msgs[sel_indx - 1]))\n    else:\n        state.reporter.success_msg = msgs[correct - 1]\n    return state",
    "docstring": "Verify exercises of the type MultipleChoiceExercise\n\n    Args:\n        state:    State instance describing student and solution code. Can be omitted if used with Ex().\n        correct:  index of correct option, where 1 is the first option.\n        msgs  :    list of feedback messages corresponding to each option.\n\n    :Example:\n        The following SCT is for a multiple choice exercise with 2 options, the first\n        of which is correct.::\n\n            Ex().has_chosen(1, ['Correct!', 'Incorrect. Try again!'])"
  },
  {
    "code": "def main():\n    if \"--help\" in sys.argv or \"-h\" in sys.argv or len(sys.argv) > 3:\n        raise SystemExit(__doc__)\n    try:\n        discordian_calendar(*sys.argv[1:])\n    except ValueError as error:\n        raise SystemExit(\"Error: {}\".format(\"\\n\".join(error.args)))",
    "docstring": "Command line entry point for dcal."
  },
  {
    "code": "def from_taxtable(cls, taxtable_fp):\n        r = csv.reader(taxtable_fp)\n        headers = next(r)\n        rows = (collections.OrderedDict(list(zip(headers, i))) for i in r)\n        row = next(rows)\n        root = cls(rank=row['rank'], tax_id=row[\n                   'tax_id'], name=row['tax_name'])\n        path_root = headers.index('root')\n        root.ranks = headers[path_root:]\n        for row in rows:\n            rank, tax_id, name = [\n                row[i] for i in ('rank', 'tax_id', 'tax_name')]\n            path = [_f for _f in list(row.values())[path_root:] if _f]\n            parent = root.path(path[:-1])\n            parent.add_child(cls(rank, tax_id, name=name))\n        return root",
    "docstring": "Generate a node from an open handle to a taxtable, as generated by\n        ``taxit taxtable``"
  },
  {
    "code": "async def save(self, db=None):\n        self._db = db or self.db\n        data = self.prepare_data()\n        self.validate()\n        for i in self.connection_retries():\n            try:\n                created = False if '_id' in data else True\n                result = await self.db[self.get_collection_name()].insert_one(data)\n                self._id = result.inserted_id\n                asyncio.ensure_future(post_save.send(\n                    sender=self.__class__,\n                    db=self.db,\n                    instance=self,\n                    created=created)\n                )\n                break\n            except ConnectionFailure as ex:\n                exceed = await self.check_reconnect_tries_and_wait(i, 'save')\n                if exceed:\n                    raise ex",
    "docstring": "If object has _id, then object will be created or fully rewritten.\n        If not, object will be inserted and _id will be assigned."
  },
  {
    "code": "def _do_help(self, cmd, args):\n        print(self.doc_string())\n        print()\n        data_unsorted = []\n        cls = self.__class__\n        for name in dir(cls):\n            obj = getattr(cls, name)\n            if iscommand(obj):\n                cmds = []\n                for cmd in getcommands(obj):\n                    cmds.append(cmd)\n                cmd_str = ','.join(sorted(cmds))\n                doc_str = textwrap.dedent(obj.__doc__).strip() if obj.__doc__ else \\\n                        '(no doc string available)'\n                data_unsorted.append([cmd_str, doc_str])\n        data_sorted = sorted(data_unsorted, key = lambda x: x[0])\n        data = [['COMMANDS', 'DOC STRING']] + data_sorted\n        table_banner = 'List of Available Commands'\n        table = terminaltables.SingleTable(data, table_banner)\n        table.inner_row_border = True\n        table.inner_heading_row_border = True\n        print(table.table)",
    "docstring": "Display doc strings of the shell and its commands."
  },
  {
    "code": "def order_target_value(self,\n                           asset,\n                           target,\n                           limit_price=None,\n                           stop_price=None,\n                           style=None):\n        if not self._can_order_asset(asset):\n            return None\n        target_amount = self._calculate_order_value_amount(asset, target)\n        amount = self._calculate_order_target_amount(asset, target_amount)\n        return self.order(asset, amount,\n                          limit_price=limit_price,\n                          stop_price=stop_price,\n                          style=style)",
    "docstring": "Place an order to adjust a position to a target value. If\n        the position doesn't already exist, this is equivalent to placing a new\n        order. If the position does exist, this is equivalent to placing an\n        order for the difference between the target value and the\n        current value.\n        If the Asset being ordered is a Future, the 'target value' calculated\n        is actually the target exposure, as Futures have no 'value'.\n\n        Parameters\n        ----------\n        asset : Asset\n            The asset that this order is for.\n        target : float\n            The desired total value of ``asset``.\n        limit_price : float, optional\n            The limit price for the order.\n        stop_price : float, optional\n            The stop price for the order.\n        style : ExecutionStyle\n            The execution style for the order.\n\n        Returns\n        -------\n        order_id : str\n            The unique identifier for this order.\n\n        Notes\n        -----\n        ``order_target_value`` does not take into account any open orders. For\n        example:\n\n        .. code-block:: python\n\n           order_target_value(sid(0), 10)\n           order_target_value(sid(0), 10)\n\n        This code will result in 20 dollars of ``sid(0)`` because the first\n        call to ``order_target_value`` will not have been filled when the\n        second ``order_target_value`` call is made.\n\n        See :func:`zipline.api.order` for more information about\n        ``limit_price``, ``stop_price``, and ``style``\n\n        See Also\n        --------\n        :class:`zipline.finance.execution.ExecutionStyle`\n        :func:`zipline.api.order`\n        :func:`zipline.api.order_target`\n        :func:`zipline.api.order_target_percent`"
  },
  {
    "code": "def export_xlsx(self, key):\n        spreadsheet_file = self.client.files().get(fileId=key).execute()\n        links = spreadsheet_file.get('exportLinks')\n        downloadurl = links.get('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')\n        resp, content = self.client._http.request(downloadurl)\n        return content",
    "docstring": "Download xlsx version of spreadsheet."
  },
  {
    "code": "def _get_ssh_config(config_path='~/.ssh/config'):\n        ssh_config = paramiko.SSHConfig()\n        try:\n            with open(os.path.realpath(os.path.expanduser(config_path))) as f:\n                ssh_config.parse(f)\n        except IOError:\n            pass\n        return ssh_config",
    "docstring": "Extract the configuration located at ``config_path``.\n\n        Returns:\n            paramiko.SSHConfig: the configuration instance."
  },
  {
    "code": "def load_gffutils_db(f):\n    import gffutils\n    db = gffutils.FeatureDB(f, keep_order=True)\n    return db",
    "docstring": "Load database for gffutils. \n\n    Parameters\n    ----------\n    f : str\n        Path to database.\n\n    Returns\n    -------\n    db : gffutils.FeatureDB\n        gffutils feature database."
  },
  {
    "code": "async def write(self, data):\n        if type(data) != bytes:\n            data = self._encode_body(data)\n        self.protocol.push_data(b\"%x\\r\\n%b\\r\\n\" % (len(data), data))\n        await self.protocol.drain()",
    "docstring": "Writes a chunk of data to the streaming response.\n\n        :param data: bytes-ish data to be written."
  },
  {
    "code": "def sanitize_html(value, valid_tags=VALID_TAGS, strip=True):\n    return bleach.clean(value, tags=list(VALID_TAGS.keys()), attributes=VALID_TAGS, strip=strip)",
    "docstring": "Strips unwanted markup out of HTML."
  },
  {
    "code": "def escape( text, newline=False ):\n    if isinstance( text, basestring ):\n        if '&' in text:\n            text = text.replace( '&', '&amp;' )\n        if '>' in text:\n            text = text.replace( '>', '&gt;' )\n        if '<' in text:\n            text = text.replace( '<', '&lt;' )\n        if '\\\"' in text:\n            text = text.replace( '\\\"', '&quot;' )\n        if '\\'' in text:\n            text = text.replace( '\\'', '&quot;' )\n        if newline:\n            if '\\n' in text:\n                text = text.replace( '\\n', '<br>' )\n    return text",
    "docstring": "Escape special html characters."
  },
  {
    "code": "def cancelled(self):\n        return self._state == self.S_EXCEPTION and isinstance(self._result, Cancelled)",
    "docstring": "Return whether this future was successfully cancelled."
  },
  {
    "code": "def _padding(self, image, geometry, options):\n        image['options']['background'] = options.get('padding_color')\n        image['options']['gravity'] = 'center'\n        image['options']['extent'] = '%sx%s' % (geometry[0], geometry[1])\n        return image",
    "docstring": "Pads the image"
  },
  {
    "code": "def __execute_bisz(self, instr):\n        op0_val = self.read_operand(instr.operands[0])\n        op2_val = 1 if op0_val == 0 else 0\n        self.write_operand(instr.operands[2], op2_val)\n        return None",
    "docstring": "Execute BISZ instruction."
  },
  {
    "code": "def getJson(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120):\n        if not 'Content-Type' in headers:\n            headers['Content-Type'] = ['application/json']\n        body = yield cls().getBody(url, method, headers, data, socket, timeout)\n        defer.returnValue(json.loads(body))",
    "docstring": "Fetch a JSON result via HTTP"
  },
  {
    "code": "def set_PLOS_2column_fig_style(self, ratio=1):\n        plt.rcParams.update({\n            'figure.figsize' : [self.PLOSwidth2Col, self.PLOSwidth2Col*ratio],\n        })",
    "docstring": "figure size corresponding to Plos 2 columns"
  },
  {
    "code": "def queue(p_queue, host=None):\n    if host is not None:\n        return _path(_c.FSQ_QUEUE, root=_path(host, root=hosts(p_queue)))\n    return _path(p_queue, _c.FSQ_QUEUE)",
    "docstring": "Construct a path to the queue dir for a queue"
  },
  {
    "code": "def __expr_str(cls, expr, level):\n        ident = ' ' * level * 4\n        if isinstance(expr, tuple):\n            return '{}{}'.format(ident, str(expr))\n        if expr.etype[0] in ['pvar', 'constant']:\n            return '{}Expression(etype={}, args={})'.format(ident, expr.etype, expr.args)\n        if not isinstance(expr, Expression):\n            return '{}{}'.format(ident, str(expr))\n        args = list(cls.__expr_str(arg, level + 1) for arg in expr.args)\n        args = '\\n'.join(args)\n        return '{}Expression(etype={}, args=\\n{})'.format(ident, expr.etype, args)",
    "docstring": "Returns string representing the expression."
  },
  {
    "code": "def next_frame_l2():\n  hparams = next_frame_basic_deterministic()\n  hparams.loss[\"targets\"] = modalities.video_l2_loss\n  hparams.top[\"targets\"] = modalities.video_l1_top\n  hparams.video_modality_loss_cutoff = 2.4\n  return hparams",
    "docstring": "Basic conv model with L2 modality."
  },
  {
    "code": "def _dedup_index(self, df_a):\n        pairs = self._link_index(df_a, df_a)\n        pairs = pairs[pairs.labels[0] > pairs.labels[1]]\n        return pairs",
    "docstring": "Build an index for deduplicating a dataset.\n\n        Parameters\n        ----------\n        df_a : (tuple of) pandas.Series\n            The data of the DataFrame to build the index with.\n\n        Returns\n        -------\n        pandas.MultiIndex\n            A pandas.MultiIndex with record pairs. Each record pair\n            contains the index values of two records. The records are\n            sampled from the lower triangular part of the matrix."
  },
  {
    "code": "def join_sources(source_module: DeploymentModule, contract_name: str):\n    joined_file = Path(__file__).parent.joinpath('joined.sol')\n    remapping = {module: str(path) for module, path in contracts_source_path().items()}\n    command = [\n        './utils/join-contracts.py',\n        '--import-map',\n        json.dumps(remapping),\n        str(contracts_source_path_of_deployment_module(\n            source_module,\n        ).joinpath(contract_name + '.sol')),\n        str(joined_file),\n    ]\n    working_dir = Path(__file__).parent.parent\n    try:\n        subprocess.check_call(command, cwd=working_dir)\n    except subprocess.CalledProcessError as ex:\n        print(f'cd {str(working_dir)}; {subprocess.list2cmdline(command)} failed.')\n        raise ex\n    return joined_file.read_text()",
    "docstring": "Use join-contracts.py to concatenate all imported Solidity files.\n\n    Args:\n        source_module: a module name to look up contracts_source_path()\n        contract_name: 'TokenNetworkRegistry', 'SecretRegistry' etc."
  },
  {
    "code": "def debug(method):\n    def new_method(*args, **kwargs):\n        import pdb\n        try:\n            import pudb\n        except ImportError:\n            pudb = pdb\n        try:\n            pudb.runcall(method, *args, **kwargs)\n        except pdb.bdb.BdbQuit:\n            sys.exit('Normal quit from debugger')\n    new_method.__doc__ = method.__doc__\n    new_method.__name__ = 'debug(%s)' % method.__name__\n    return new_method",
    "docstring": "Decorator to debug the given method"
  },
  {
    "code": "def memoize(fun):\n    argspec = inspect2.getfullargspec(fun)\n    arg_names = argspec.args + argspec.kwonlyargs\n    kwargs_defaults = get_kwargs_defaults(argspec)\n    def cache_key(args, kwargs):\n        return get_args_tuple(args, kwargs, arg_names, kwargs_defaults)\n    @functools.wraps(fun)\n    def new_fun(*args, **kwargs):\n        k = cache_key(args, kwargs)\n        if k not in new_fun.__cache:\n            new_fun.__cache[k] = fun(*args, **kwargs)\n        return new_fun.__cache[k]\n    def clear_cache():\n        new_fun.__cache.clear()\n    new_fun.__cache = {}\n    new_fun.clear_cache = clear_cache\n    return new_fun",
    "docstring": "Memoizes return values of the decorated function.\n\n    Similar to l0cache, but the cache persists for the duration of the process, unless clear_cache()\n    is called on the function."
  },
  {
    "code": "def delete(ids, yes):\n    failures = False\n    for id in ids:\n        data_source = get_data_object(id, use_data_config=True)\n        if not data_source:\n            failures = True\n            continue\n        data_name = normalize_data_name(data_source.name)\n        suffix = data_name.split('/')[-1]\n        if not suffix.isdigit():\n            failures = True\n            floyd_logger.error('%s is not a dataset, skipped.', id)\n            if suffix == 'output':\n                floyd_logger.error('To delete job output, please delete the job itself.')\n            continue\n        if not yes and not click.confirm(\"Delete Data: {}?\".format(data_name),\n                                         abort=False,\n                                         default=False):\n            floyd_logger.info(\"Data %s: Skipped\", data_name)\n            continue\n        if not DataClient().delete(data_source.id):\n            failures = True\n        else:\n            floyd_logger.info(\"Data %s: Deleted\", data_name)\n    if failures:\n        sys.exit(1)",
    "docstring": "Delete datasets."
  },
  {
    "code": "def extract_formats(config_handle):\n    configurations = dict(config_handle)\n    formats = dict(configurations.get('formats', {}))\n    return formats",
    "docstring": "Get application formats.\n\n    See :class:`gogoutils.Formats` for available options.\n\n    Args:\n        config_handle (configparser.ConfigParser): Instance of configurations.\n\n    Returns:\n        dict: Formats in ``{$format_type: $format_pattern}``."
  },
  {
    "code": "def get(self, slug):\n        kb = api.get_kb_by_slug(slug)\n        check_knowledge_access(kb)\n        parser = reqparse.RequestParser()\n        parser.add_argument(\n            'from', type=str,\n            help=\"Return only entries where key matches this.\")\n        parser.add_argument(\n            'to', type=str,\n            help=\"Return only entries where value matches this.\")\n        parser.add_argument('page', type=int,\n                            help=\"Require a specific page\")\n        parser.add_argument('per_page', type=int,\n                            help=\"Set how much result per page\")\n        parser.add_argument('match_type', type=str,\n                            help=\"s=substring, e=exact, sw=startswith\")\n        parser.add_argument('sortby', type=str,\n                            help=\"the sorting criteria ('from' or 'to')\")\n        args = parser.parse_args()\n        kb_dict = kb.to_dict()\n        kb_dict['mappings'] = KnwKBMappingsResource \\\n            .search_mappings(kb=kb, key=args['from'], value=args['to'],\n                             match_type=args['match_type'],\n                             sortby=args['sortby'], page=args['page'],\n                             per_page=args['per_page'])\n        return kb_dict",
    "docstring": "Get KnwKB.\n\n        Url parameters:\n            - from: filter \"mappings from\"\n            - to: filter \"mappings to\"\n            - page\n            - per_page\n            - match_type: s=substring, e=exact, sw=startswith\n            - sortby: 'from' or 'to'"
  },
  {
    "code": "def create_shot(self, sequence):\n        dialog = ShotCreatorDialog(sequence=sequence, parent=self)\n        dialog.exec_()\n        shot = dialog.shot\n        return shot",
    "docstring": "Create and return a new shot\n\n        :param sequence: the sequence for the shot\n        :type sequence: :class:`jukeboxcore.djadapter.models.Sequence`\n        :returns: The created shot or None\n        :rtype: None | :class:`jukeboxcore.djadapter.models.Shot`\n        :raises: None"
  },
  {
    "code": "def from_charmm(cls, path, positions=None, forcefield=None, strict=True, **kwargs):\n        psf = CharmmPsfFile(path)\n        if strict and forcefield is None:\n            raise ValueError('PSF files require key `forcefield`.')\n        if strict and positions is None:\n            raise ValueError('PSF files require key `positions`.')\n        psf.parmset = CharmmParameterSet(*forcefield)\n        psf.loadParameters(psf.parmset)\n        return cls(master=psf, topology=psf.topology, positions=positions, path=path,\n                   **kwargs)",
    "docstring": "Loads PSF Charmm structure from `path`. Requires `charmm_parameters`.\n\n        Parameters\n        ----------\n        path : str\n            Path to PSF file\n        forcefield : list of str\n            Paths to Charmm parameters files, such as *.par or *.str. REQUIRED\n\n        Returns\n        -------\n        psf : SystemHandler\n            SystemHandler with topology. Charmm parameters are embedded in\n            the `master` attribute."
  },
  {
    "code": "def rawselect(message: Text,\n              choices: List[Union[Text, Choice, Dict[Text, Any]]],\n              default: Optional[Text] = None,\n              qmark: Text = DEFAULT_QUESTION_PREFIX,\n              style: Optional[Style] = None,\n              **kwargs: Any) -> Question:\n    return select.select(message, choices, default, qmark, style,\n                         use_shortcuts=True,\n                         **kwargs)",
    "docstring": "Ask the user to select one item from a list of choices using shortcuts.\n\n       The user can only select one option.\n\n       Args:\n           message: Question text\n\n           choices: Items shown in the selection, this can contain `Choice` or\n                    or `Separator` objects or simple items as strings. Passing\n                    `Choice` objects, allows you to configure the item more\n                    (e.g. preselecting it or disabeling it).\n\n           default: Default return value (single value).\n\n           qmark: Question prefix displayed in front of the question.\n                  By default this is a `?`\n\n           style: A custom color and style for the question parts. You can\n                  configure colors as well as font types for different elements.\n\n       Returns:\n           Question: Question instance, ready to be prompted (using `.ask()`)."
  },
  {
    "code": "def parse_date(value):\n    if not value:\n        return None\n    if isinstance(value, datetime.date):\n        return value\n    return parse_datetime(value).date()",
    "docstring": "Attempts to parse `value` into an instance of ``datetime.date``. If\n    `value` is ``None``, this function will return ``None``.\n\n    Args:\n        value: A timestamp. This can be a string, datetime.date, or\n            datetime.datetime value."
  },
  {
    "code": "def configure_error_handlers(app):\n    def render_error(error):\n        return (render_template('errors/%s.html' % error.code,\n                title=error_messages[error.code], code=error.code), error.code)\n    for (errcode, title) in error_messages.iteritems():\n        app.errorhandler(errcode)(render_error)",
    "docstring": "Configure application error handlers"
  },
  {
    "code": "def get_renderers(self):\n        renderers = super(WithDynamicViewSetMixin, self).get_renderers()\n        if settings.ENABLE_BROWSABLE_API is False:\n            return [\n                r for r in renderers if not isinstance(r, BrowsableAPIRenderer)\n            ]\n        else:\n            return renderers",
    "docstring": "Optionally block Browsable API rendering."
  },
  {
    "code": "def create_account(self, **kwargs):\n        response = self.__requester.request(\n            'POST',\n            'accounts',\n            _kwargs=combine_kwargs(**kwargs)\n        )\n        return Account(self.__requester, response.json())",
    "docstring": "Create a new root account.\n\n        :calls: `POST /api/v1/accounts \\\n        <https://canvas.instructure.com/doc/api/accounts.html#method.accounts.create>`_\n\n        :rtype: :class:`canvasapi.account.Account`"
  },
  {
    "code": "def pull(self):\n        repo_root = settings.REPO_ROOT\n        pull_from_origin(join(repo_root, self.name))",
    "docstring": "Pull from the origin."
  },
  {
    "code": "def check_smart_storage_config_ids(self):\n        if self.smart_storage_config_identities is None:\n            msg = ('The Redfish controller failed to get the '\n                   'SmartStorageConfig controller configurations.')\n            LOG.debug(msg)\n            raise exception.IloError(msg)",
    "docstring": "Check SmartStorageConfig controllers is there in hardware.\n\n        :raises: IloError, on an error from iLO."
  },
  {
    "code": "def detect_interval(\n            self,\n            min_head_length=None,\n            max_head_length=None,\n            min_tail_length=None,\n            max_tail_length=None\n    ):\n        head = self.detect_head(min_head_length, max_head_length)\n        tail = self.detect_tail(min_tail_length, max_tail_length)\n        begin = head\n        end = self.real_wave_mfcc.audio_length - tail\n        self.log([u\"Audio length: %.3f\", self.real_wave_mfcc.audio_length])\n        self.log([u\"Head length:  %.3f\", head])\n        self.log([u\"Tail length:  %.3f\", tail])\n        self.log([u\"Begin:        %.3f\", begin])\n        self.log([u\"End:          %.3f\", end])\n        if (begin >= TimeValue(\"0.000\")) and (end > begin):\n            self.log([u\"Returning %.3f %.3f\", begin, end])\n            return (begin, end)\n        self.log(u\"Returning (0.000, 0.000)\")\n        return (TimeValue(\"0.000\"), TimeValue(\"0.000\"))",
    "docstring": "Detect the interval of the audio file\n        containing the fragments in the text file.\n\n        Return the audio interval as a tuple of two\n        :class:`~aeneas.exacttiming.TimeValue` objects,\n        representing the begin and end time, in seconds,\n        with respect to the full wave duration.\n\n        If one of the parameters is ``None``, the default value\n        (``0.0`` for min, ``10.0`` for max) will be used.\n\n        :param min_head_length: estimated minimum head length\n        :type  min_head_length: :class:`~aeneas.exacttiming.TimeValue`\n        :param max_head_length: estimated maximum head length\n        :type  max_head_length: :class:`~aeneas.exacttiming.TimeValue`\n        :param min_tail_length: estimated minimum tail length\n        :type  min_tail_length: :class:`~aeneas.exacttiming.TimeValue`\n        :param max_tail_length: estimated maximum tail length\n        :type  max_tail_length: :class:`~aeneas.exacttiming.TimeValue`\n        :rtype: (:class:`~aeneas.exacttiming.TimeValue`, :class:`~aeneas.exacttiming.TimeValue`)\n        :raises: TypeError: if one of the parameters is not ``None`` or a number\n        :raises: ValueError: if one of the parameters is negative"
  },
  {
    "code": "def login_required(func):\n        @wraps(func)\n        def wrapped(*args, **kwargs):\n            if g.user is None:\n                return redirect(url_for(current_app.config['LDAP_LOGIN_VIEW'],\n                                        next=request.path))\n            return func(*args, **kwargs)\n        return wrapped",
    "docstring": "When applied to a view function, any unauthenticated requests will\n        be redirected to the view named in LDAP_LOGIN_VIEW. Authenticated\n        requests do NOT require membership from a specific group.\n\n        The login view is responsible for asking for credentials, checking\n        them, and setting ``flask.g.user`` to the name of the authenticated\n        user if the credentials are acceptable.\n\n        :param func: The view function to decorate."
  },
  {
    "code": "def rsync_git(local_path, remote_path, exclude=None, extra_opts=None,\n              version_file='version.txt'):\n    with settings(hide('output', 'running'), warn_only=True):\n        print(green('Version On Server: ' + run('cat ' + '{}/{}'.format(\n              remote_path, version_file)).strip()))\n    print(green('Now Deploying Version ' +\n          write_version(join(local_path, version_file))))\n    rsync(local_path, remote_path, exclude, extra_opts)",
    "docstring": "Rsync deploy a git repo.  Write and compare version.txt"
  },
  {
    "code": "def wrap(tensor, books=None, tensor_shape=None):\n  if books is None:\n    books = bookkeeper.for_default_graph()\n  if isinstance(tensor, PrettyTensor):\n    return tensor.as_layer()\n  elif isinstance(tensor, UnboundVariable):\n    def set_input_from_unbound_var(data):\n      if data is not None:\n        return wrap(data, books)\n      else:\n        return None\n    return _DeferredLayer(books, set_input_from_unbound_var, [tensor], {})\n  else:\n    tensor = tf.convert_to_tensor(tensor, name='input')\n    if tensor_shape:\n      _set_shape_on_tensor(tensor, tensor_shape)\n    return Layer(books, tensor=tensor, name=tensor.name)",
    "docstring": "Creates an input layer representing the given tensor.\n\n  Args:\n    tensor: The tensor.\n    books: The bookkeeper; this is usually not required unless you are building\n      multiple `tf.Graphs.`\n    tensor_shape: An optional shape that will be set on the Tensor or verified\n      to match the tensor.\n  Returns:\n    A layer."
  },
  {
    "code": "def _build_schema(self, s):\n        w = self._whatis(s)\n        if w == self.IS_LIST:\n            w0 = self._whatis(s[0])\n            js = {\"type\": \"array\",\n                  \"items\": {\"type\": self._jstype(w0, s[0])}}\n        elif w == self.IS_DICT:\n            js = {\"type\": \"object\",\n                  \"properties\": {key: self._build_schema(val) for key, val in s.items()}}\n            req = [key for key, val in s.items() if not val.is_optional]\n            if req:\n                js[\"required\"] = req\n        else:\n            js = {\"type\": self._jstype(w, s)}\n        for k, v in self._json_schema_keys.items():\n            if k not in js:\n                js[k] = v\n        return js",
    "docstring": "Recursive schema builder, called by `json_schema`."
  },
  {
    "code": "def make_python_name(self, name):\n        for k, v in [('<', '_'), ('>', '_'), ('::', '__'), (',', ''), (' ', ''),\n                     (\"$\", \"DOLLAR\"), (\".\", \"DOT\"), (\"@\", \"_\"), (\":\", \"_\"),\n                     ('-', '_')]:\n            if k in name:\n                name = name.replace(k, v)\n            if name.startswith(\"__\"):\n                return \"_X\" + name\n        if len(name) == 0:\n            pass\n        elif name[0] in \"01234567879\":\n            return \"_\" + name\n        return name",
    "docstring": "Transforms an USR into a valid python name."
  },
  {
    "code": "def zip_currentdir(self) -> None:\n        with zipfile.ZipFile(f'{self.currentpath}.zip', 'w') as zipfile_:\n            for filepath, filename in zip(self.filepaths, self.filenames):\n                zipfile_.write(filename=filepath, arcname=filename)\n        del self.currentdir",
    "docstring": "Pack the current working directory in a `zip` file.\n\n        |FileManager| subclasses allow for manual packing and automatic\n        unpacking of working directories.  The only supported format is `zip`.\n        To avoid possible inconsistencies, origin directories and zip\n        files are removed after packing or unpacking, respectively.\n\n        As an example scenario, we prepare a |FileManager| object with\n        the current working directory `folder` containing the files\n        `test1.txt` and `text2.txt`:\n\n        >>> from hydpy.core.filetools import FileManager\n        >>> filemanager = FileManager()\n        >>> filemanager.BASEDIR = 'basename'\n        >>> filemanager.projectdir = 'projectname'\n        >>> import os\n        >>> from hydpy import repr_, TestIO\n        >>> TestIO.clear()\n        >>> basepath = 'projectname/basename'\n        >>> with TestIO():\n        ...     os.makedirs(basepath)\n        ...     filemanager.currentdir = 'folder'\n        ...     open(f'{basepath}/folder/file1.txt', 'w').close()\n        ...     open(f'{basepath}/folder/file2.txt', 'w').close()\n        ...     filemanager.filenames\n        ['file1.txt', 'file2.txt']\n\n        The directories existing under the base path are identical\n        with the ones returned by property |FileManager.availabledirs|:\n\n        >>> with TestIO():\n        ...     sorted(os.listdir(basepath))\n        ...     filemanager.availabledirs    # doctest: +ELLIPSIS\n        ['folder']\n        Folder2Path(folder=.../projectname/basename/folder)\n\n        After packing the current working directory manually, it is\n        still counted as a available directory:\n\n        >>> with TestIO():\n        ...     filemanager.zip_currentdir()\n        ...     sorted(os.listdir(basepath))\n        ...     filemanager.availabledirs    # doctest: +ELLIPSIS\n        ['folder.zip']\n        Folder2Path(folder=.../projectname/basename/folder.zip)\n\n        Instead of the complete directory, only the contained files\n        are packed:\n\n        >>> from zipfile import ZipFile\n        >>> with TestIO():\n        ...     with ZipFile('projectname/basename/folder.zip', 'r') as zp:\n        ...         sorted(zp.namelist())\n        ['file1.txt', 'file2.txt']\n\n        The zip file is unpacked again, as soon as `folder` becomes\n        the current working directory:\n\n        >>> with TestIO():\n        ...     filemanager.currentdir = 'folder'\n        ...     sorted(os.listdir(basepath))\n        ...     filemanager.availabledirs\n        ...     filemanager.filenames    # doctest: +ELLIPSIS\n        ['folder']\n        Folder2Path(folder=.../projectname/basename/folder)\n        ['file1.txt', 'file2.txt']"
  },
  {
    "code": "def parse_year_days(year_info):\n    leap_month, leap_days = _parse_leap(year_info)\n    res = leap_days\n    for month in range(1, 13):\n        res += (year_info >> (16 - month)) % 2 + 29\n    return res",
    "docstring": "Parse year days from a year info."
  },
  {
    "code": "def interactive_server(port=27017, verbose=True, all_ok=False, name='MockupDB',\n                       ssl=False, uds_path=None):\n    if uds_path is not None:\n        port = None\n    server = MockupDB(port=port,\n                      verbose=verbose,\n                      request_timeout=int(1e6),\n                      ssl=ssl,\n                      auto_ismaster=True,\n                      uds_path=uds_path)\n    if all_ok:\n        server.append_responder({})\n    server.autoresponds('whatsmyuri', you='localhost:12345')\n    server.autoresponds({'getLog': 'startupWarnings'},\n                        log=['hello from %s!' % name])\n    server.autoresponds(OpMsg('buildInfo'), version='MockupDB ' + __version__)\n    server.autoresponds(OpMsg('listCollections'))\n    server.autoresponds('replSetGetStatus', ok=0)\n    server.autoresponds('getFreeMonitoringStatus', ok=0)\n    return server",
    "docstring": "A `MockupDB` that the mongo shell can connect to.\n\n    Call `~.MockupDB.run` on the returned server, and clean it up with\n    `~.MockupDB.stop`.\n\n    If ``all_ok`` is True, replies {ok: 1} to anything unmatched by a specific\n    responder."
  },
  {
    "code": "def to_shcoeffs(self, itaper, normalization='4pi', csphase=1):\n        if type(normalization) != str:\n            raise ValueError('normalization must be a string. ' +\n                             'Input type was {:s}'\n                             .format(str(type(normalization))))\n        if normalization.lower() not in set(['4pi', 'ortho', 'schmidt']):\n            raise ValueError(\n                \"normalization must be '4pi', 'ortho' \" +\n                \"or 'schmidt'. Provided value was {:s}\"\n                .format(repr(normalization))\n                )\n        if csphase != 1 and csphase != -1:\n            raise ValueError(\n                \"csphase must be 1 or -1. Input value was {:s}\"\n                .format(repr(csphase))\n                )\n        coeffs = self.to_array(itaper, normalization=normalization.lower(),\n                               csphase=csphase)\n        return SHCoeffs.from_array(coeffs, normalization=normalization.lower(),\n                                   csphase=csphase, copy=False)",
    "docstring": "Return the spherical harmonic coefficients of taper i as a SHCoeffs\n        class instance.\n\n        Usage\n        -----\n        clm = x.to_shcoeffs(itaper, [normalization, csphase])\n\n        Returns\n        -------\n        clm : SHCoeffs class instance\n\n        Parameters\n        ----------\n        itaper : int\n            Taper number, where itaper=0 is the best concentrated.\n        normalization : str, optional, default = '4pi'\n            Normalization of the output class: '4pi', 'ortho' or 'schmidt' for\n            geodesy 4pi-normalized, orthonormalized, or Schmidt semi-normalized\n            coefficients, respectively.\n        csphase : int, optional, default = 1\n            Condon-Shortley phase convention: 1 to exclude the phase factor,\n            or -1 to include it."
  },
  {
    "code": "def finish(self):\n        stylesheet = ''.join(self._buffer)\n        parser = CSSParser()\n        css = parser.parseString(stylesheet)\n        replaceUrls(css, self._replace)\n        self.request.write(css.cssText)\n        return self.request.finish()",
    "docstring": "Parse the buffered response body, rewrite its URLs, write the result to\n        the wrapped request, and finish the wrapped request."
  },
  {
    "code": "def send_confirmation_email(self):\n        context= {'user': self,\n                  'new_email': self.email_unconfirmed,\n                  'protocol': get_protocol(),\n                  'confirmation_key': self.email_confirmation_key,\n                  'site': Site.objects.get_current()}\n        subject_old = ''.join(render_to_string(\n                        'accounts/emails/confirmation_email_subject_old.txt',\n                        context).splitlines())\n        message_old = render_to_string(\n                        'accounts/emails/confirmation_email_message_old.txt',\n                        context)\n        send_mail(subject_old,\n                  message_old,\n                  settings.DEFAULT_FROM_EMAIL,\n                  [self.email])\n        subject_new = ''.join(render_to_string(\n                        'accounts/emails/confirmation_email_subject_new.txt',\n                        context).splitlines())\n        message_new = render_to_string(\n                        'accounts/emails/confirmation_email_message_new.txt',\n                        context)\n        send_mail(subject_new,\n                  message_new,\n                  settings.DEFAULT_FROM_EMAIL,\n                  [self.email_unconfirmed,])",
    "docstring": "Sends an email to confirm the new email address.\n\n        This method sends out two emails. One to the new email address that\n        contains the ``email_confirmation_key`` which is used to verify this\n        this email address with :func:`User.objects.confirm_email`.\n\n        The other email is to the old email address to let the user know that\n        a request is made to change this email address."
  },
  {
    "code": "def from_moment_relative_to_crystal_axes(cls, moment, lattice):\n        unit_m = lattice.matrix / np.linalg.norm(lattice.matrix, axis=1)[:, None]\n        moment = np.matmul(list(moment), unit_m)\n        moment[np.abs(moment) < 1e-8] = 0\n        return cls(moment)",
    "docstring": "Obtaining a Magmom object from a magnetic moment provided\n        relative to crystal axes.\n\n        Used for obtaining moments from magCIF file.\n        :param magmom: list of floats specifying vector magmom\n        :param lattice: Lattice\n        :return: Magmom"
  },
  {
    "code": "def data_to_imagesurface (data, **kwargs):\n    import cairo\n    data = np.atleast_2d (data)\n    if data.ndim != 2:\n        raise ValueError ('input array may not have more than 2 dimensions')\n    argb32 = data_to_argb32 (data, **kwargs)\n    format = cairo.FORMAT_ARGB32\n    height, width = argb32.shape\n    stride = cairo.ImageSurface.format_stride_for_width (format, width)\n    if argb32.strides[0] != stride:\n        raise ValueError ('stride of data array not compatible with ARGB32')\n    return cairo.ImageSurface.create_for_data (argb32, format,\n                                               width, height, stride)",
    "docstring": "Turn arbitrary data values into a Cairo ImageSurface.\n\n    The method and arguments are the same as data_to_argb32, except that the\n    data array will be treated as 2D, and higher dimensionalities are not\n    allowed. The return value is a Cairo ImageSurface object.\n\n    Combined with the write_to_png() method on ImageSurfaces, this is an easy\n    way to quickly visualize 2D data."
  },
  {
    "code": "def blueprint(self) -> Optional[str]:\n        if self.endpoint is not None and '.' in self.endpoint:\n            return self.endpoint.rsplit('.', 1)[0]\n        else:\n            return None",
    "docstring": "Returns the blueprint the matched endpoint belongs to.\n\n        This can be None if the request has not been matched or the\n        endpoint is not in a blueprint."
  },
  {
    "code": "def is_third_friday(day=None):\n    day = day if day is not None else datetime.datetime.now()\n    defacto_friday = (day.weekday() == 4) or (\n        day.weekday() == 3 and day.hour() >= 17)\n    return defacto_friday and 14 < day.day < 22",
    "docstring": "check if day is month's 3rd friday"
  },
  {
    "code": "def get_zorder(self, overlay, key, el):\n        spec = util.get_overlay_spec(overlay, key, el)\n        return self.ordering.index(spec)",
    "docstring": "Computes the z-order of element in the NdOverlay\n        taking into account possible batching of elements."
  },
  {
    "code": "def parseLines(self):\n        inAst = parse(''.join(self.lines), self.inFilename)\n        self.visit(inAst)",
    "docstring": "Form an AST for the code and produce a new version of the source."
  },
  {
    "code": "def truncated_normal_log_likelihood(params, low, high, data):\n        mu = params[0]\n        sigma = params[1]\n        if sigma == 0:\n            return np.inf\n        ll = np.sum(norm.logpdf(data, mu, sigma))\n        ll -= len(data) * np.log((norm.cdf(high, mu, sigma) - norm.cdf(low, mu, sigma)))\n        return -ll",
    "docstring": "Calculate the log likelihood of the truncated normal distribution.\n\n        Args:\n            params: tuple with (mean, std), the parameters under which we evaluate the model\n            low (float): the lower truncation bound\n            high (float): the upper truncation bound\n            data (ndarray): the one dimension list of data points for which we want to calculate the likelihood\n\n        Returns:\n            float: the negative log likelihood of observing the given data under the given parameters.\n                This is meant to be used in minimization routines."
  },
  {
    "code": "def _heartbeat_loop(self):\n        self.logger.debug(\"running main heartbeat thread\")\n        while not self.closed:\n            time.sleep(self.settings['SLEEP_TIME'])\n            self._report_self()",
    "docstring": "A main run loop thread to do work"
  },
  {
    "code": "def _get_atomsection(mol2_lst):\n        started = False\n        for idx, s in enumerate(mol2_lst):\n            if s.startswith('@<TRIPOS>ATOM'):\n                first_idx = idx + 1\n                started = True\n            elif started and s.startswith('@<TRIPOS>'):\n                last_idx_plus1 = idx\n                break\n        return mol2_lst[first_idx:last_idx_plus1]",
    "docstring": "Returns atom section from mol2 provided as list of strings"
  },
  {
    "code": "def partition_list(pred, iterable):\n    left, right = partition_iter(pred, iterable)\n    return list(left), list(right)",
    "docstring": "Partitions an iterable with a predicate into two lists, one with elements satisfying\n    the predicate and one with elements that do not satisfy it.\n\n    .. note: this just converts the results of partition_iter to a list for you so that you don't\n    have to in most cases using `partition_iter` is a better option.\n\n    :returns: a tuple (satisfiers, unsatisfiers)."
  },
  {
    "code": "def upload_file_and_send_file_offer(self, file_name, user_id, data=None, input_file_path=None,\n                                        content_type='application/octet-stream', auto_open=False,\n                                        prevent_share=False, scope='content/send'):\n        if input_file_path:\n            with open(input_file_path, 'rb') as f:\n                data = f.read()\n        if not data:\n            raise ValueError('Either the data of a file or the path to a file must be provided')\n        params = {\n            'fileName': file_name,\n            'userId': user_id,\n            'autoOpen': 'true' if auto_open else 'false',\n            'preventShare': 'true' if prevent_share else 'false',\n        }\n        return _post(\n            token=self.oauth.get_app_token(scope),\n            uri='/user/media/file/send?' + urllib.urlencode(params),\n            data=data,\n            content_type=content_type\n        )",
    "docstring": "Upload a file of any type to store and return a FileId once file offer has been sent.\n        No user authentication required"
  },
  {
    "code": "def task_annotate(self, task, annotation):\n        self._execute(\n            task['uuid'],\n            'annotate',\n            '--',\n            annotation\n        )\n        id, annotated_task = self.get_task(uuid=task[six.u('uuid')])\n        return annotated_task",
    "docstring": "Annotates a task."
  },
  {
    "code": "def colors(self, color_code):\n        if color_code is None:\n            color_code = WINDOWS_CODES['/all']\n        current_fg, current_bg = self.colors\n        if color_code == WINDOWS_CODES['/fg']:\n            final_color_code = self.default_fg | current_bg\n        elif color_code == WINDOWS_CODES['/bg']:\n            final_color_code = current_fg | self.default_bg\n        elif color_code == WINDOWS_CODES['/all']:\n            final_color_code = self.default_fg | self.default_bg\n        elif color_code == WINDOWS_CODES['bgblack']:\n            final_color_code = current_fg\n        else:\n            new_is_bg = color_code in self.ALL_BG_CODES\n            final_color_code = color_code | (current_fg if new_is_bg else current_bg)\n        self._kernel32.SetConsoleTextAttribute(self._stream_handle, final_color_code)",
    "docstring": "Change the foreground and background colors for subsequently printed characters.\n\n        None resets colors to their original values (when class was instantiated).\n\n        Since setting a color requires including both foreground and background codes (merged), setting just the\n        foreground color resets the background color to black, and vice versa.\n\n        This function first gets the current background and foreground colors, merges in the requested color code, and\n        sets the result.\n\n        However if we need to remove just the foreground color but leave the background color the same (or vice versa)\n        such as when {/red} is used, we must merge the default foreground color with the current background color. This\n        is the reason for those negative values.\n\n        :param int color_code: Color code from WINDOWS_CODES."
  },
  {
    "code": "def process_nxml_file(file_name, citation=None, offline=False,\n                      output_fname=default_output_fname):\n    with open(file_name, 'rb') as f:\n        nxml_str = f.read().decode('utf-8')\n        return process_nxml_str(nxml_str, citation, False, output_fname)",
    "docstring": "Return a ReachProcessor by processing the given NXML file.\n\n    NXML is the format used by PubmedCentral for papers in the open\n    access subset.\n\n    Parameters\n    ----------\n    file_name : str\n        The name of the NXML file to be processed.\n    citation : Optional[str]\n        A PubMed ID passed to be used in the evidence for the extracted INDRA\n        Statements. Default: None\n    offline : Optional[bool]\n        If set to True, the REACH system is ran offline. Otherwise (by default)\n        the web service is called. Default: False\n    output_fname : Optional[str]\n        The file to output the REACH JSON output to.\n        Defaults to reach_output.json in current working directory.\n\n    Returns\n    -------\n    rp : ReachProcessor\n        A ReachProcessor containing the extracted INDRA Statements\n        in rp.statements."
  },
  {
    "code": "def f1_score(df, col_true=None, col_pred='precision_result', pos_label=1, average=None):\n    r\n    if not col_pred:\n        col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS)\n    return fbeta_score(df, col_true, col_pred, pos_label=pos_label, average=average)",
    "docstring": "r\"\"\"\n    Compute f-1 score of a predicted DataFrame. f-1 is defined as\n\n    .. math::\n\n        \\frac{2 \\cdot precision \\cdot recall}{precision + recall}\n\n\n    :Parameters:\n        - **df** - predicted data frame\n        - **col_true** - column name of true label\n        - **col_pred** - column name of predicted label, 'prediction_result' by default.\n        - **pos_label** - denote the desired class label when ``average`` == `binary`\n        - **average** - denote the method to compute average.\n    :Returns:\n        Recall score\n    :Return type:\n        float | numpy.array[float]\n\n    The parameter ``average`` controls the behavior of the function.\n\n    * When ``average`` == None (by default), f-1 of every class is given as a list.\n\n    * When ``average`` == 'binary', f-1 of class specified in ``pos_label`` is given.\n\n    * When ``average`` == 'micro', f-1 of overall precision and recall is given, where overall precision and recall are computed in micro-average mode.\n\n    * When ``average`` == 'macro', average f-1 of all the class is given.\n\n    * When ``average`` == `weighted`, average f-1 of all the class weighted by support of every true classes is given.\n\n\n    :Example:\n\n    Assume we have a table named 'predicted' as follows:\n\n    ======== ===================\n    label    prediction_result\n    ======== ===================\n    0        1\n    1        2\n    2        1\n    1        1\n    1        0\n    2        2\n    ======== ===================\n\n    Different options of ``average`` parameter outputs different values:\n\n.. code-block:: python\n\n    >>> f1_score(predicted, 'label', average=None)\n    array([ 0.        ,  0.33333333,  0.5       ])\n    >>> f1_score(predicted, 'label', average='macro')\n    0.27\n    >>> f1_score(predicted, 'label', average='micro')\n    0.33\n    >>> f1_score(predicted, 'label', average='weighted')\n    0.33"
  },
  {
    "code": "def pasa(args):\n    p = OptionParser(pasa.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n    pasa_db, fastafile = args\n    termexons = \"pasa.terminal_exons.gff3\"\n    if need_update(fastafile, termexons):\n        cmd = \"$ANNOT_DEVEL/PASA2/scripts/pasa_asmbls_to_training_set.dbi\"\n        cmd += ' -M \"{0}:mysql.tigr.org\" -p \"access:access\"'.format(pasa_db)\n        cmd += ' -g {0}'.format(fastafile)\n        sh(cmd)\n        cmd = \"$EVM/PasaUtils/retrieve_terminal_CDS_exons.pl\"\n        cmd += \" trainingSetCandidates.fasta trainingSetCandidates.gff\"\n        sh(cmd, outfile=termexons)\n    return termexons",
    "docstring": "%prog pasa pasa_db fastafile\n\n    Run EVM in TIGR-only mode."
  },
  {
    "code": "def _show_stat(self):\n        _show_stat_wrapper_multi_Progress(self.count,\n                                          self.last_count, \n                                          self.start_time, \n                                          self.max_count, \n                                          self.speed_calc_cycles,\n                                          self.width,\n                                          self.q,\n                                          self.last_speed,\n                                          self.prepend,\n                                          self.show_stat,\n                                          self.len, \n                                          self.add_args,\n                                          self.lock,\n                                          self.info_line,\n                                          no_move_up=True)",
    "docstring": "convenient functions to call the static show_stat_wrapper_multi with\n            the given class members"
  },
  {
    "code": "def check_script(vouts):\n        for vout in [v for v in vouts[::-1] if v['hex'].startswith('6a')]:\n            verb = BlockchainSpider.decode_op_return(vout['hex'])\n            action = Spoolverb.from_verb(verb).action\n            if action in Spoolverb.supported_actions:\n                return verb\n        raise Exception(\"Invalid ascribe transaction\")",
    "docstring": "Looks into the vouts list of a transaction\n        and returns the ``op_return`` if one exists.\n\n        Args;\n            vouts (list): List of outputs of a transaction.\n\n        Returns:\n            str: String representation of the ``op_return``.\n\n        Raises:\n            Exception: If no ``vout`` having a supported\n                verb (:attr:`supported_actions`) is found."
  },
  {
    "code": "def if_sqlserver_disable_constraints_triggers(session: SqlASession,\n                                              tablename: str) -> None:\n    with if_sqlserver_disable_constraints(session, tablename):\n        with if_sqlserver_disable_triggers(session, tablename):\n            yield",
    "docstring": "If we're running under SQL Server, disable triggers AND constraints for the\n    specified table while the resource is held.\n\n    Args:\n        session: SQLAlchemy :class:`Session`\n        tablename: table name"
  },
  {
    "code": "def set(self, key, val, time=0, min_compress_len=0):\n        return self._set(\"set\", key, val, time, min_compress_len)",
    "docstring": "Unconditionally sets a key to a given value in the memcache.\n\n        The C{key} can optionally be an tuple, with the first element\n        being the server hash value and the second being the key.\n        If you want to avoid making this module calculate a hash value.\n        You may prefer, for example, to keep all of a given user's objects\n        on the same memcache server, so you could use the user's unique\n        id as the hash value.\n\n        @return: Nonzero on success.\n        @rtype: int\n        @param time: Tells memcached the time which this value should expire, either\n        as a delta number of seconds, or an absolute unix time-since-the-epoch\n        value. See the memcached protocol docs section \"Storage Commands\"\n        for more info on <exptime>. We default to 0 == cache forever.\n        @param min_compress_len: The threshold length to kick in auto-compression\n        of the value using the zlib.compress() routine. If the value being cached is\n        a string, then the length of the string is measured, else if the value is an\n        object, then the length of the pickle result is measured. If the resulting\n        attempt at compression yeilds a larger string than the input, then it is\n        discarded. For backwards compatability, this parameter defaults to 0,\n        indicating don't ever try to compress."
  },
  {
    "code": "def _restore_backup(self):\n        input_filename, input_file = self._get_backup_file(database=self.database_name,\n                                                           servername=self.servername)\n        self.logger.info(\"Restoring backup for database '%s' and server '%s'\",\n                         self.database_name, self.servername)\n        self.logger.info(\"Restoring: %s\" % input_filename)\n        if self.decrypt:\n            unencrypted_file, input_filename = utils.unencrypt_file(input_file, input_filename,\n                                                                    self.passphrase)\n            input_file.close()\n            input_file = unencrypted_file\n        if self.uncompress:\n            uncompressed_file, input_filename = utils.uncompress_file(input_file, input_filename)\n            input_file.close()\n            input_file = uncompressed_file\n        self.logger.info(\"Restore tempfile created: %s\", utils.handle_size(input_file))\n        if self.interactive:\n            self._ask_confirmation()\n        input_file.seek(0)\n        self.connector = get_connector(self.database_name)\n        self.connector.restore_dump(input_file)",
    "docstring": "Restore the specified database."
  },
  {
    "code": "def email(anon, obj, field, val):\n    return anon.faker.email(field=field)",
    "docstring": "Generates a random email address."
  },
  {
    "code": "def _parse_dav_element(self, dav_response):\n        href = parse.unquote(\n            self._strip_dav_path(dav_response.find('{DAV:}href').text)\n        )\n        if six.PY2:\n            href = href.decode('utf-8')\n        file_type = 'file'\n        if href[-1] == '/':\n            file_type = 'dir'\n        file_attrs = {}\n        attrs = dav_response.find('{DAV:}propstat')\n        attrs = attrs.find('{DAV:}prop')\n        for attr in attrs:\n            file_attrs[attr.tag] = attr.text\n        return FileInfo(href, file_type, file_attrs)",
    "docstring": "Parses a single DAV element\n\n        :param dav_response: DAV response\n        :returns :class:`FileInfo`"
  },
  {
    "code": "def pelix_services(self):\n        return {\n            svc_ref.get_property(pelix.constants.SERVICE_ID): {\n                \"specifications\": svc_ref.get_property(\n                    pelix.constants.OBJECTCLASS\n                ),\n                \"ranking\": svc_ref.get_property(\n                    pelix.constants.SERVICE_RANKING\n                ),\n                \"properties\": svc_ref.get_properties(),\n                \"bundle.id\": svc_ref.get_bundle().get_bundle_id(),\n                \"bundle.name\": svc_ref.get_bundle().get_symbolic_name(),\n            }\n            for svc_ref in self.__context.get_all_service_references(None)\n        }",
    "docstring": "List of registered services"
  },
  {
    "code": "def gameloop(self):\n        try:\n            while True:\n                self.handle_events()\n                self.update()\n                self.render()\n        except KeyboardInterrupt:\n            pass",
    "docstring": "A game loop that circles through the methods."
  },
  {
    "code": "def _make_mask(self, data, lon_str=LON_STR, lat_str=LAT_STR):\n        mask = False\n        for west, east, south, north in self.mask_bounds:\n            if west < east:\n                mask_lon = (data[lon_str] > west) & (data[lon_str] < east)\n            else:\n                mask_lon = (data[lon_str] < west) | (data[lon_str] > east)\n            mask_lat = (data[lat_str] > south) & (data[lat_str] < north)\n            mask |= mask_lon & mask_lat\n        return mask",
    "docstring": "Construct the mask that defines a region on a given data's grid."
  },
  {
    "code": "def get_database_configuration():\n    db_config = get_database_config_file()\n    if db_config is None:\n        return None\n    with open(db_config, 'r') as ymlfile:\n        cfg = yaml.load(ymlfile)\n    return cfg",
    "docstring": "Get database configuration as dictionary."
  },
  {
    "code": "def _construct(self, context):\n    with self.g.as_default():\n      if self._pass_through:\n        return self._pass_through._construct(context)\n      current_value = context.get(self, None)\n      assert current_value is not _unspecified, 'Circular dependency'\n      if current_value is not None:\n        return current_value\n      context[self] = _unspecified\n      method_args = self._replace_deferred(self._method_args, context)\n      method_kwargs = self._replace_deferred(self._method_kwargs, context)\n      result = self._method(*method_args, **method_kwargs)\n      _strip_unnecessary_contents_from_stack(result, set())\n      context[self] = result\n      return result",
    "docstring": "Constructs this by calling the deferred method.\n\n    This assumes that all unbound_vars have been specified in context and if\n    this layer has already been computed in this context, then the previously\n    constructed value will be returned.\n\n    Args:\n      context: A dict of UnboundVariables/_DeferredLayers to their values.\n    Returns:\n      The result of calling the given method on this layer."
  },
  {
    "code": "def get_qualification_type_by_name(self, name):\n        max_fuzzy_matches_to_check = 100\n        query = name.upper()\n        start = time.time()\n        args = {\n            \"Query\": query,\n            \"MustBeRequestable\": False,\n            \"MustBeOwnedByCaller\": True,\n            \"MaxResults\": max_fuzzy_matches_to_check,\n        }\n        results = self.mturk.list_qualification_types(**args)[\"QualificationTypes\"]\n        while not results and time.time() - start < self.max_wait_secs:\n            time.sleep(1)\n            results = self.mturk.list_qualification_types(**args)[\"QualificationTypes\"]\n        if not results:\n            return None\n        qualifications = [self._translate_qtype(r) for r in results]\n        if len(qualifications) > 1:\n            for qualification in qualifications:\n                if qualification[\"name\"].upper() == query:\n                    return qualification\n            raise MTurkServiceException(\"{} was not a unique name\".format(query))\n        return qualifications[0]",
    "docstring": "Return a Qualification Type by name. If the provided name matches\n        more than one Qualification, check to see if any of the results\n        match the provided name exactly. If there's an exact match, return\n        that Qualification. Otherwise, raise an exception."
  },
  {
    "code": "def get_list_w_id2nts(ids, id2nts, flds, dflt_null=\"\"):\n    combined_nt_list = []\n    ntobj = cx.namedtuple(\"Nt\", \" \".join(flds))\n    for item_id in ids:\n        nts = [id2nt.get(item_id) for id2nt in id2nts]\n        vals = _combine_nt_vals(nts, flds, dflt_null)\n        combined_nt_list.append(ntobj._make(vals))\n    return combined_nt_list",
    "docstring": "Return a new list of namedtuples by combining \"dicts\" of namedtuples or objects."
  },
  {
    "code": "def get_pending_domain_join():\n    base_key = r'SYSTEM\\CurrentControlSet\\Services\\Netlogon'\n    avoid_key = r'{0}\\AvoidSpnSet'.format(base_key)\n    join_key = r'{0}\\JoinDomain'.format(base_key)\n    if __utils__['reg.key_exists']('HKLM', avoid_key):\n        log.debug('Key exists: %s', avoid_key)\n        return True\n    else:\n        log.debug('Key does not exist: %s', avoid_key)\n    if __utils__['reg.key_exists']('HKLM', join_key):\n        log.debug('Key exists: %s', join_key)\n        return True\n    else:\n        log.debug('Key does not exist: %s', join_key)\n    return False",
    "docstring": "Determine whether there is a pending domain join action that requires a\n    reboot.\n\n    .. versionadded:: 2016.11.0\n\n    Returns:\n        bool: ``True`` if there is a pending domain join action, otherwise\n        ``False``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' system.get_pending_domain_join"
  },
  {
    "code": "def check_dupl_sources(self):\n        dd = collections.defaultdict(list)\n        for src_group in self.src_groups:\n            for src in src_group:\n                try:\n                    srcid = src.source_id\n                except AttributeError:\n                    srcid = src['id']\n                dd[srcid].append(src)\n        dupl = []\n        for srcid, srcs in sorted(dd.items()):\n            if len(srcs) > 1:\n                _assert_equal_sources(srcs)\n                dupl.append(srcs)\n        return dupl",
    "docstring": "Extracts duplicated sources, i.e. sources with the same source_id in\n        different source groups. Raise an exception if there are sources with\n        the same ID which are not duplicated.\n\n        :returns: a list of list of sources, ordered by source_id"
  },
  {
    "code": "def write(self):\n        with open(self.log_path, \"w\") as f:\n            json.dump(self.log_dict, f, indent=1)",
    "docstring": "Dump JSON to file"
  },
  {
    "code": "def has_hlu(self, lun_or_snap, cg_member=None):\n        hlu = self.get_hlu(lun_or_snap, cg_member=cg_member)\n        return hlu is not None",
    "docstring": "Returns True if `lun_or_snap` is attached to the host.\n\n        :param lun_or_snap: can be lun, lun snap, cg snap or a member snap of\n            cg snap.\n        :param cg_member: the member lun of cg if `lun_or_snap` is cg snap.\n        :return: True - if `lun_or_snap` is attached, otherwise False."
  },
  {
    "code": "def _worker(reader: DatasetReader,\n            input_queue: Queue,\n            output_queue: Queue,\n            index: int) -> None:\n    while True:\n        file_path = input_queue.get()\n        if file_path is None:\n            output_queue.put(index)\n            break\n        logger.info(f\"reading instances from {file_path}\")\n        for instance in reader.read(file_path):\n            output_queue.put(instance)",
    "docstring": "A worker that pulls filenames off the input queue, uses the dataset reader\n    to read them, and places the generated instances on the output queue.\n    When there are no filenames left on the input queue, it puts its ``index``\n    on the output queue and doesn't do anything else."
  },
  {
    "code": "def listFieldsFromWorkitem(self, copied_from, keep=False):\n        return self.templater.listFieldsFromWorkitem(copied_from,\n                                                     keep=keep)",
    "docstring": "List all the attributes to be rendered directly from some\n        to-be-copied workitems\n\n        More details, please refer to\n        :class:`rtcclient.template.Templater.listFieldsFromWorkitem`"
  },
  {
    "code": "def remove(self, pointer):\n        doc = deepcopy(self.document)\n        parent, obj = None, doc\n        try:\n            for token in Pointer(pointer):\n                parent, obj = obj, token.extract(obj, bypass_ref=True)\n            if isinstance(parent, Mapping):\n                del parent[token]\n            if isinstance(parent, MutableSequence):\n                parent.pop(int(token))\n        except Exception as error:\n            raise Error(*error.args)\n        return Target(doc)",
    "docstring": "Remove element from sequence, member from mapping.\n\n        :param pointer: the path to search in\n        :return: resolved document\n        :rtype: Target"
  },
  {
    "code": "def shell_join(delim, it):\n    'Joins an iterable of ShellQuoted with a delimiter between each two'\n    return ShellQuoted(delim.join(raw_shell(s) for s in it))",
    "docstring": "Joins an iterable of ShellQuoted with a delimiter between each two"
  },
  {
    "code": "def import_module(self, modules, shared=False, into_spooler=False):\n        if all((shared, into_spooler)):\n            raise ConfigurationError('Unable to set both `shared` and `into_spooler` flags')\n        if into_spooler:\n            command = 'spooler-python-import'\n        else:\n            command = 'shared-python-import' if shared else 'python-import'\n        self._set(command, modules, multi=True)\n        return self._section",
    "docstring": "Imports a python module.\n\n        :param list|str|unicode modules:\n\n        :param bool shared: Import a python module in all of the processes.\n            This is done after fork but before request processing.\n\n        :param bool into_spooler: Import a python module in the spooler.\n            http://uwsgi-docs.readthedocs.io/en/latest/Spooler.html"
  },
  {
    "code": "def validateDatetime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,\n                     formats=('%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S',\n                              '%Y/%m/%d %H:%M', '%y/%m/%d %H:%M', '%m/%d/%Y %H:%M', '%m/%d/%y %H:%M', '%x %H:%M',\n                              '%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S'), excMsg=None):\n    try:\n        return _validateToDateTimeFormat(value, formats, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)\n    except ValidationException:\n        _raiseValidationException(_('%r is not a valid date and time.') % (_errstr(value)), excMsg)",
    "docstring": "Raises ValidationException if value is not a datetime formatted in one\n    of the formats formats. Returns a datetime.datetime object of value.\n\n    * value (str): The value being validated as a datetime.\n    * blank (bool): If True, a blank string will be accepted. Defaults to False.\n    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.\n    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.\n    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.\n    * formats: A tuple of strings that can be passed to time.strftime, dictating the possible formats for a valid datetime.\n    * excMsg (str): A custom message to use in the raised ValidationException.\n\n    >>> import pysimplevalidate as pysv\n    >>> pysv.validateDatetime('2018/10/31 12:00:01')\n    datetime.datetime(2018, 10, 31, 12, 0, 1)\n    >>> pysv.validateDatetime('10/31/2018 12:00:01')\n    datetime.datetime(2018, 10, 31, 12, 0, 1)\n    >>> pysv.validateDatetime('10/31/2018')\n    Traceback (most recent call last):\n        ...\n    pysimplevalidate.ValidationException: '10/31/2018' is not a valid date and time."
  },
  {
    "code": "def _query(self, host_object, classification=False):\n        template = 'http://verify.hosts-file.net/?v={}&s={}'\n        url = template.format(self.app_id, host_object.to_unicode())\n        url = url + '&class=true' if classification else url\n        return get(url).text",
    "docstring": "Query the client for data of given host.\n\n        :param host_object: an object representing a host value\n        :param classification: if True: hpHosts is queried also\n        for classification for given host, if listed\n        :returns: content of response to GET request to hpHosts\n        for data on the given host"
  },
  {
    "code": "def download_handler(feed, placeholders):\n    import shlex\n    value = feed.retrieve_config('downloadhandler', 'greg')\n    if value == 'greg':\n        while os.path.isfile(placeholders.fullpath):\n            placeholders.fullpath = placeholders.fullpath + '_'\n            placeholders.filename = placeholders.filename + '_'\n        urlretrieve(placeholders.link, placeholders.fullpath)\n    else:\n        value_list = shlex.split(value)\n        instruction_list = [substitute_placeholders(part, placeholders) for\n                            part in value_list]\n        returncode = subprocess.call(instruction_list)\n        if returncode:\n            raise URLError",
    "docstring": "Parse and execute the download handler"
  },
  {
    "code": "def _table_relabel(table, substitutions, replacements=None):\n    if replacements is not None:\n        raise NotImplementedError\n    observed = set()\n    exprs = []\n    for c in table.columns:\n        expr = table[c]\n        if c in substitutions:\n            expr = expr.name(substitutions[c])\n            observed.add(c)\n        exprs.append(expr)\n    for c in substitutions:\n        if c not in observed:\n            raise KeyError('{0!r} is not an existing column'.format(c))\n    return table.projection(exprs)",
    "docstring": "Change table column names, otherwise leaving table unaltered\n\n    Parameters\n    ----------\n    substitutions\n\n    Returns\n    -------\n    relabeled : TableExpr"
  },
  {
    "code": "def _bake_script(script):\n    if \"src\" in script.attrs:\n        if re.match(\"https?://\", script[\"src\"]):\n            script_data = _load_url(script[\"src\"]).read()\n        else:\n            script_data = _load_file(script[\"src\"]).read()\n        script.clear()\n        if USING_PYTHON2:\n            script.string = \"\\n\" + script_data + \"\\n\"\n        else:\n            script.string = \"\\n\" + str(script_data) + \"\\n\"\n        del script[\"src\"]\n        del script[\"type\"]",
    "docstring": "Takes a script element and bakes it in only if it contains a remote resource"
  },
  {
    "code": "def plot_sample(self, nsims=10, plot_data=True, **kwargs):\n        if self.latent_variables.estimation_method not in ['BBVI', 'M-H']:\n            raise Exception(\"No latent variables estimated!\")\n        else:\n            import matplotlib.pyplot as plt\n            import seaborn as sns\n            figsize = kwargs.get('figsize',(10,7))\n            plt.figure(figsize=figsize)\n            date_index = self.index[max(self.ar, self.sc):self.data_length]\n            mu, Y, scores = self._model(self.latent_variables.get_z_values())\n            draws = self.sample(nsims).T\n            plt.plot(date_index, draws, label='Posterior Draws', alpha=1.0)\n            if plot_data is True:\n                plt.plot(date_index, Y, label='Data', c='black', alpha=0.5, linestyle='', marker='s')\n            plt.title(self.data_name)\n            plt.show()",
    "docstring": "Plots draws from the posterior predictive density against the data\n\n        Parameters\n        ----------\n        nsims : int (default : 1000)\n            How many draws from the posterior predictive distribution\n\n        plot_data boolean\n            Whether to plot the data or not"
  },
  {
    "code": "def setWorkerInfo(self, hostname, workerAmount, origin):\n        scoop.logger.debug('Initialising {0}{1} worker {2} [{3}].'.format(\n            \"local\" if hostname in utils.localHostnames else \"remote\",\n            \" origin\" if origin else \"\",\n            self.workersLeft,\n            hostname,\n            )\n        )\n        add_args, add_kwargs = self._setWorker_args(origin)\n        self.workers[-1].setWorker(*add_args, **add_kwargs)\n        self.workers[-1].setWorkerAmount(workerAmount)",
    "docstring": "Sets the worker information for the current host."
  },
  {
    "code": "def delete(self, ip_dest, next_hop, **kwargs):\n        kwargs.update({'delete': True})\n        return self._set_route(ip_dest, next_hop, **kwargs)",
    "docstring": "Delete a static route\n\n        Args:\n            ip_dest (string): The ip address of the destination in the\n                form of A.B.C.D/E\n            next_hop (string): The next hop interface or ip address\n            **kwargs['next_hop_ip'] (string): The next hop address on\n                destination interface\n            **kwargs['distance'] (string): Administrative distance for this\n                route\n            **kwargs['tag'] (string): Route tag\n            **kwargs['route_name'] (string): Route name\n\n        Returns:\n            True if the operation succeeds, otherwise False."
  },
  {
    "code": "def purge(self):\n        def partial_file(item):\n            \"Filter out partial files\"\n            return item.completed_chunks < item.size_chunks\n        self.cull(file_filter=partial_file, attrs=[\"get_completed_chunks\", \"get_size_chunks\"])",
    "docstring": "Delete PARTIAL data files and remove torrent from client."
  },
  {
    "code": "def get_sort_field(request):\n    sort_direction = request.GET.get(\"dir\")\n    field_name = (request.GET.get(\"sort\") or \"\") if sort_direction else \"\"\n    sort_sign = \"-\" if sort_direction == \"desc\" else \"\"\n    result_field = \"{sign}{field}\".format(sign=sort_sign, field=field_name)\n    return result_field",
    "docstring": "Retrieve field used for sorting a queryset\n\n    :param request: HTTP request\n    :return: the sorted field name, prefixed with \"-\" if ordering is descending"
  },
  {
    "code": "def ReplaceStopTimeObject(self, stoptime, schedule=None):\n    if schedule is None:\n      schedule = self._schedule\n    new_secs = stoptime.GetTimeSecs()\n    cursor = schedule._connection.cursor()\n    cursor.execute(\"DELETE FROM stop_times WHERE trip_id=? and \"\n                   \"stop_sequence=? and stop_id=?\",\n                   (self.trip_id, stoptime.stop_sequence, stoptime.stop_id))\n    if cursor.rowcount == 0:\n      raise problems_module.Error('Attempted replacement of StopTime object which does not exist')\n    self._AddStopTimeObjectUnordered(stoptime, schedule)",
    "docstring": "Replace a StopTime object from this trip with the given one.\n\n    Keys the StopTime object to be replaced by trip_id, stop_sequence\n    and stop_id as 'stoptime', with the object 'stoptime'."
  },
  {
    "code": "def _close_stdio():\n    for fd in (sys.stdin, sys.stdout, sys.stderr):\n      file_no = fd.fileno()\n      fd.flush()\n      fd.close()\n      os.close(file_no)",
    "docstring": "Close stdio streams to avoid output in the tty that launched pantsd."
  },
  {
    "code": "async def update_notifications(self, on_match_open: bool = None, on_tournament_end: bool = None):\n        params = {}\n        if on_match_open is not None:\n            params['notify_users_when_matches_open'] = on_match_open\n        if on_tournament_end is not None:\n            params['notify_users_when_the_tournament_ends'] = on_tournament_end\n        assert_or_raise(len(params) > 0, ValueError, 'At least one of the notifications must be given')\n        await self.update(**params)",
    "docstring": "update participants notifications for this tournament\n\n        |methcoro|\n\n        Args:\n            on_match_open: Email registered Challonge participants when matches open up for them\n            on_tournament_end: Email registered Challonge participants the results when this tournament ends\n\n        Raises:\n            APIException"
  },
  {
    "code": "def _drop_membership_multicast_socket(self):\n        self._multicast_socket.setsockopt(\n            socket.IPPROTO_IP,\n            socket.IP_DROP_MEMBERSHIP,\n            self._membership_request\n        )\n        self._membership_request = None",
    "docstring": "Drop membership to multicast\n\n        :rtype: None"
  },
  {
    "code": "def write_template_file(source, target, content):\n    print(target)\n    data = format_template_file(source, content)\n    with open(target, 'w') as f:\n        for line in data:\n            if type(line) != str:\n                line = line.encode('utf-8')\n            f.write(line)",
    "docstring": "Write a new file from a given pystache template file and content"
  },
  {
    "code": "def generate_enum(self):\n        enum = self._definition['enum']\n        if not isinstance(enum, (list, tuple)):\n            raise JsonSchemaDefinitionException('enum must be an array')\n        with self.l('if {variable} not in {enum}:'):\n            enum = str(enum).replace('\"', '\\\\\"')\n            self.l('raise JsonSchemaException(\"{name} must be one of {}\")', enum)",
    "docstring": "Means that only value specified in the enum is valid.\n\n        .. code-block:: python\n\n            {\n                'enum': ['a', 'b'],\n            }"
  },
  {
    "code": "def put(self, path, data):\n        assert path is not None\n        assert data is None or isinstance(data, dict)\n        if data is None:\n            data = {}\n        response = self.conn.request_encode_body('PUT', path, data,\n                                                 self._get_headers(), False)\n        self._last_status = response_status = response.status\n        response_content = response.data.decode()\n        return Result(status=response_status, json=response_content)",
    "docstring": "Executes a PUT.\n\n        'path' may not be None. Should include the full path to the\n        resoure.\n        'data' may be None or a dictionary.\n\n        Returns a named tuple that includes:\n\n        status: the HTTP status code\n        json: the returned JSON-HAL\n\n        If the key was not set, throws an APIConfigurationException."
  },
  {
    "code": "def get_secret(self, handle, contributor):\n        queryset = self.all()\n        if contributor is not None:\n            queryset = queryset.filter(contributor=contributor)\n        secret = queryset.get(handle=handle)\n        return secret.value",
    "docstring": "Retrieve an existing secret's value.\n\n        :param handle: Secret handle\n        :param contributor: User instance to perform contributor validation,\n            which means that only secrets for the given contributor will be\n            looked up."
  },
  {
    "code": "def list_default_storage_policy_of_datastore(datastore, service_instance=None):\n    log.trace('Listing the default storage policy of datastore \\'%s\\'', datastore)\n    target_ref = _get_proxy_target(service_instance)\n    ds_refs = salt.utils.vmware.get_datastores(service_instance, target_ref,\n                                               datastore_names=[datastore])\n    if not ds_refs:\n        raise VMwareObjectRetrievalError('Datastore \\'{0}\\' was not '\n                                         'found'.format(datastore))\n    profile_manager = salt.utils.pbm.get_profile_manager(service_instance)\n    policy = salt.utils.pbm.get_default_storage_policy_of_datastore(\n        profile_manager, ds_refs[0])\n    return _get_policy_dict(policy)",
    "docstring": "Returns a list of datastores assign the the storage policies.\n\n    datastore\n        Name of the datastore to assign.\n        The datastore needs to be visible to the VMware entity the proxy\n        points to.\n\n    service_instance\n        Service instance (vim.ServiceInstance) of the vCenter.\n        Default is None.\n\n    .. code-block:: bash\n\n        salt '*' vsphere.list_default_storage_policy_of_datastore datastore=ds1"
  },
  {
    "code": "def eum_snippet(trace_id=None, eum_api_key=None, meta={}):\n    try:\n        eum_file = open(os.path.dirname(__file__) + '/eum.js')\n        eum_src = Template(eum_file.read())\n        ids = {}\n        ids['meta_kvs'] = ''\n        parent_span = tracer.active_span\n        if trace_id or parent_span:\n            ids['trace_id'] = trace_id or parent_span.trace_id\n        else:\n            return ''\n        if eum_api_key:\n            ids['eum_api_key'] = eum_api_key\n        else:\n            ids['eum_api_key'] = global_eum_api_key\n        for key, value in meta.items():\n            ids['meta_kvs'] += (\"'ineum('meta', '%s', '%s');'\" % (key, value))\n        return eum_src.substitute(ids)\n    except Exception as e:\n        logger.debug(e)\n        return ''",
    "docstring": "Return an EUM snippet for use in views, templates and layouts that reports\n    client side metrics to Instana that will automagically be linked to the\n    current trace.\n\n    @param trace_id [optional] the trace ID to insert into the EUM string\n    @param eum_api_key [optional] the EUM API key from your Instana dashboard\n    @param meta [optional] optional additional KVs you want reported with the\n                EUM metrics\n\n    @return string"
  },
  {
    "code": "def show(self):\n        if not self._error and not self.stats:\n            return\n        self.header()\n        for stat in self.stats:\n            utils.item(stat, level=1, options=self.options)",
    "docstring": "Display indented statistics."
  },
  {
    "code": "def dbr(self, value=None):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type float '\n                                 'for field `dbr`'.format(value))\n        self._dbr = value",
    "docstring": "Corresponds to IDD Field `dbr` Daily temperature range for hottest\n        month.\n\n        [defined as mean of the difference between daily maximum\n        and daily minimum dry-bulb temperatures for hottest month]\n\n        Args:\n            value (float): value for IDD Field `dbr`\n                Unit: C\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def get_cookie_header(queue_item):\n        header = []\n        path = URLHelper.get_path(queue_item.request.url)\n        for cookie in queue_item.request.cookies:\n            root_path = cookie.path == \"\" or cookie.path == \"/\"\n            if path.startswith(cookie.path) or root_path:\n                header.append(cookie.name + \"=\" + cookie.value)\n        return \"&\".join(header)",
    "docstring": "Convert a requests cookie jar to a HTTP request cookie header value.\n\n        Args:\n            queue_item (:class:`nyawc.QueueItem`): The parent queue item of the new request.\n\n        Returns:\n            str: The HTTP cookie header value."
  },
  {
    "code": "def get_participants_for_gradebook(gradebook_id, person=None):\n    if not valid_gradebook_id(gradebook_id):\n        raise InvalidGradebookID(gradebook_id)\n    url = \"/rest/gradebook/v1/book/{}/participants\".format(gradebook_id)\n    headers = {}\n    if person is not None:\n        headers[\"X-UW-Act-as\"] = person.uwnetid\n    data = get_resource(url, headers)\n    participants = []\n    for pt in data[\"participants\"]:\n        participants.append(_participant_from_json(pt))\n    return participants",
    "docstring": "Returns a list of gradebook participants for the passed gradebook_id and\n    person."
  },
  {
    "code": "def print_runs(query):\n    if query is None:\n        return\n    for tup in query:\n        print((\"{0} @ {1} - {2} id: {3} group: {4}\".format(\n            tup.end, tup.experiment_name, tup.project_name,\n            tup.experiment_group, tup.run_group)))",
    "docstring": "Print all rows in this result query."
  },
  {
    "code": "def cancel(self, consumer_tag=''):\n        if not compatibility.is_string(consumer_tag):\n            raise AMQPInvalidArgument('consumer_tag should be a string')\n        cancel_frame = specification.Basic.Cancel(consumer_tag=consumer_tag)\n        result = self._channel.rpc_request(cancel_frame)\n        self._channel.remove_consumer_tag(consumer_tag)\n        return result",
    "docstring": "Cancel a queue consumer.\n\n        :param str consumer_tag: Consumer tag\n\n        :raises AMQPInvalidArgument: Invalid Parameters\n        :raises AMQPChannelError: Raises if the channel encountered an error.\n        :raises AMQPConnectionError: Raises if the connection\n                                     encountered an error.\n\n        :rtype: dict"
  },
  {
    "code": "def conflict(request, target=None, template_name='409.html'):\n    try:\n        template = loader.get_template(template_name)\n    except TemplateDoesNotExist:\n        template = Template(\n            '<h1>Conflict</h1>'\n            '<p>The request was unsuccessful due to a conflict. '\n            'The object changed during the transaction.</p>')\n    try:\n        saved = target.__class__._default_manager.get(pk=target.pk)\n    except target.__class__.DoesNotExist:\n        saved = None\n    ctx = {'target': target,\n           'saved': saved,\n           'request_path': request.path}\n    return ConflictResponse(template.render(ctx))",
    "docstring": "409 error handler.\n\n    :param request: Request\n\n    :param template_name: `409.html`\n\n    :param target: The model to save"
  },
  {
    "code": "def save(self, force_insert=False):\n        delayed = {}\n        for field, value in self.data.items():\n            model_field = getattr(type(self.instance), field, None)\n            if isinstance(model_field, ManyToManyField):\n                if value is not None:\n                    delayed[field] = value\n                continue\n            setattr(self.instance, field, value)\n        rv = self.instance.save(force_insert=force_insert)\n        for field, value in delayed.items():\n            setattr(self.instance, field, value)\n        return rv",
    "docstring": "Save the model and any related many-to-many fields.\n\n        :param force_insert: Should the save force an insert?\n        :return: Number of rows impacted, or False."
  },
  {
    "code": "def get_plist_data_from_string (data):\n    if has_biplist:\n        return biplist.readPlistFromString(data)\n    try:\n        return plistlib.readPlistFromString(data)\n    except Exception:\n        return {}",
    "docstring": "Parse plist data for a string. Tries biplist, falling back to\n    plistlib."
  },
  {
    "code": "def update_email_template(self, template_id, template_dict):\n        return self._create_put_request(\n            resource=EMAIL_TEMPLATES,\n            billomat_id=template_id,\n            send_data=template_dict\n        )",
    "docstring": "Updates a emailtemplate\n\n        :param template_id: the template id\n        :param template_dict: dict\n        :return: dict"
  },
  {
    "code": "def python_version(self):\n        v = self.get('python-version', '')\n        if v == '':\n            v = \"{}.{}\".format(sys.version_info.major, sys.version_info.minor)\n        return v",
    "docstring": "Get the configured Python version.\n\n        If this is not set in the config, then it defaults to the version of the current runtime.\n\n        Returns: A string of the form \"MAJOR.MINOR\", e.g. \"3.6\"."
  },
  {
    "code": "def available(self):\n        disco_info = yield from self._disco_client.query_info(\n            self.client.local_jid.bare()\n        )\n        for item in disco_info.identities.filter(attrs={\"category\": \"pubsub\"}):\n            if item.type_ == \"pep\":\n                return True\n        return False",
    "docstring": "Check whether we have a PEP identity associated with our account."
  },
  {
    "code": "def _get_covered_keys_and_masks(merge, aliases):\n    for entry in merge.routing_table[merge.insertion_index:]:\n        key_mask = (entry.key, entry.mask)\n        keys_masks = aliases.get(key_mask, [key_mask])\n        for key, mask in keys_masks:\n            if intersect(merge.key, merge.mask, key, mask):\n                yield key, mask",
    "docstring": "Get keys and masks which would be covered by the entry resulting from\n    the merge.\n\n    Parameters\n    ----------\n    aliases : {(key, mask): {(key, mask), ...}, ...}\n        Map of key-mask pairs to the sets of key-mask pairs that they actually\n        represent.\n\n    Yields\n    ------\n    (key, mask)\n        Pairs of keys and masks which would be covered if the given `merge`\n        were to be applied to the routing table."
  },
  {
    "code": "def options(self, request, map, *args, **kwargs):\n        options = {}\n        for method, function in map.items():\n            options[method] = function.__doc__\n        return self._render(\n            request = request,\n            template = 'options',\n            context = {\n                'options': options\n            },\n            status = 200,\n            headers = {\n                'Allow': ', '.join(options.keys())\n            }\n        )",
    "docstring": "List communication options."
  },
  {
    "code": "def reg(name):\n    ret = {'name': name,\n           'changes': {},\n           'comment': '',\n           'result': True}\n    now = time.time()\n    if 'status' not in __reg__:\n        __reg__['status'] = {}\n        __reg__['status']['val'] = {}\n    for event in __events__:\n        if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'):\n            idata = {'recv_time': now}\n            for key in event['data']['data']:\n                if key in ('id', 'recv_time'):\n                    continue\n                idata[key] = event['data']['data'][key]\n            __reg__['status']['val'][event['data']['id']] = idata\n            ret['changes'][event['data']['id']] = True\n    return ret",
    "docstring": "Activate this register to turn on a minion status tracking register, this\n    register keeps the current status beacon data and the time that each beacon\n    was last checked in."
  },
  {
    "code": "def filter_significance(diff, significance):\n    changed = diff['changed']\n    reduced = [{'key': delta['key'],\n                'fields': {k: v\n                           for k, v in delta['fields'].items()\n                           if _is_significant(v, significance)}}\n               for delta in changed]\n    filtered = [delta for delta in reduced if delta['fields']]\n    diff = diff.copy()\n    diff['changed'] = filtered\n    return diff",
    "docstring": "Prune any changes in the patch which are due to numeric changes less than this level of\n    significance."
  },
  {
    "code": "def annotation_spec_set_path(cls, project, annotation_spec_set):\n        return google.api_core.path_template.expand(\n            \"projects/{project}/annotationSpecSets/{annotation_spec_set}\",\n            project=project,\n            annotation_spec_set=annotation_spec_set,\n        )",
    "docstring": "Return a fully-qualified annotation_spec_set string."
  },
  {
    "code": "def _slice(index, n_samples, margin=None):\n    if margin is None:\n        margin = (0, 0)\n    assert isinstance(n_samples, (tuple, list))\n    assert len(n_samples) == 2\n    before, after = n_samples\n    assert isinstance(margin, (tuple, list))\n    assert len(margin) == 2\n    margin_before, margin_after = margin\n    before += margin_before\n    after += margin_after\n    index = int(index)\n    before = int(before)\n    after = int(after)\n    return slice(max(0, index - before), index + after, None)",
    "docstring": "Return a waveform slice."
  },
  {
    "code": "def product(pc, service, attrib, sku):\n    pc.service = service.lower()\n    pc.sku = sku\n    pc.add_attributes(attribs=attrib)\n    click.echo(\"Service Alias: {0}\".format(pc.service_alias))\n    click.echo(\"URL: {0}\".format(pc.service_url))\n    click.echo(\"Region: {0}\".format(pc.region))\n    click.echo(\"Product Terms: {0}\".format(pc.terms))\n    click.echo(\"Filtering Attributes: {0}\".format(pc.attributes))\n    prods = pyutu.find_products(pc)\n    for p in prods:\n        click.echo(\"Product SKU: {0} product: {1}\".format(\n            p, json.dumps(prods[p], indent=2, sort_keys=True))\n        )\n    click.echo(\"Total Products Found: {0}\".format(len(prods)))\n    click.echo(\"Time: {0} secs\".format(time.process_time()))",
    "docstring": "Get a list of a service's products.\n    The list will be in the given region, matching the specific terms and\n    any given attribute filters or a SKU."
  },
  {
    "code": "def controlled(num_ptr_bits, U):\n    d = 2 ** (1 + num_ptr_bits)\n    m = np.eye(d)\n    m[d - 2:, d - 2:] = U\n    return m",
    "docstring": "Given a one-qubit gate matrix U, construct a controlled-U on all pointer\n    qubits."
  },
  {
    "code": "def _flat_values(self):\n        return tuple(\n            np.nan if type(x) is dict else x\n            for x in self._cube_dict[\"result\"][\"measures\"][\"mean\"][\"data\"]\n        )",
    "docstring": "Return tuple of mean values as found in cube response.\n\n        Mean data may include missing items represented by a dict like\n        {'?': -1} in the cube response. These are replaced by np.nan in the\n        returned value."
  },
  {
    "code": "def add_external_reference(self,term_id, external_ref):\n        if term_id in self.idx:\n            term_obj = Cterm(self.idx[term_id],self.type)\n            term_obj.add_external_reference(external_ref)\n        else:\n            print('{term_id} not in self.idx'.format(**locals()))",
    "docstring": "Adds an external reference for the given term\n        @type term_id: string\n        @param term_id: the term identifier\n        @type external_ref: L{CexternalReference}\n        @param external_ref: the external reference object"
  },
  {
    "code": "def prepare(cls) -> None:\n        if cls.version is None:\n            cls.version = find_version(cls.name)\n        if cls.long_description is None:\n            cls.long_description = cls.parse_readme()\n        if cls.packages is None:\n            cls.packages = find_packages(cls.root_directory)\n        if cls.install_requires is None:\n            cls.install_requires = parse_requirements()\n        if cls.python_requires is None:\n            cls.python_requires = find_required_python_version(cls.classifiers)",
    "docstring": "Fill in possibly missing package metadata."
  },
  {
    "code": "def _normalize_string(raw_str):\n  return \" \".join(\n      token.strip()\n      for token in tokenizer.encode(text_encoder.native_to_unicode(raw_str)))",
    "docstring": "Normalizes the string using tokenizer.encode.\n\n  Args:\n    raw_str: the input string\n\n  Returns:\n   A string which is ready to be tokenized using split()"
  },
  {
    "code": "def from_db_value(self, value, expression, connection, context):\n        if value is None:\n            return value\n        if value == '':\n            return None\n        return iso_string_to_python_datetime(value)",
    "docstring": "Convert database value to Python value.\n        Called when data is loaded from the database."
  },
  {
    "code": "def _unpack(struct, bc, offset=0):\n    return struct.unpack_from(bc, offset), offset + struct.size",
    "docstring": "returns the unpacked data tuple, and the next offset past the\n    unpacked data"
  },
  {
    "code": "def place_visual(self):\n        index = 0\n        bin_pos = string_to_array(self.bin2_body.get(\"pos\"))\n        bin_size = self.bin_size\n        for _, obj_mjcf in self.visual_objects:\n            bin_x_low = bin_pos[0]\n            bin_y_low = bin_pos[1]\n            if index == 0 or index == 2:\n                bin_x_low -= bin_size[0] / 2\n            if index < 2:\n                bin_y_low -= bin_size[1] / 2\n            bin_x_high = bin_x_low + bin_size[0] / 2\n            bin_y_high = bin_y_low + bin_size[1] / 2\n            bottom_offset = obj_mjcf.get_bottom_offset()\n            bin_range = [bin_x_low + bin_x_high, bin_y_low + bin_y_high, 2 * bin_pos[2]]\n            bin_center = np.array(bin_range) / 2.0\n            pos = bin_center - bottom_offset\n            self.visual_obj_mjcf[index].set(\"pos\", array_to_string(pos))\n            index += 1",
    "docstring": "Places visual objects randomly until no collisions or max iterations hit."
  },
  {
    "code": "def setPololuProtocol(self):\n        self._compact = False\n        self._log and self._log.debug(\"Pololu protocol has been set.\")",
    "docstring": "Set the pololu protocol."
  },
  {
    "code": "def _get_description(self):\n        return \", \".join([\n            part for part in [\n                \"missing: {}\".format(self.missing) if self.missing else \"\",\n                (\n                    \"forbidden: {}\".format(self.forbidden)\n                    if self.forbidden else \"\"\n                ),\n                \"invalid: {}:\".format(self.invalid) if self.invalid else \"\",\n                (\n                    \"failed to parse: {}\".format(self.failed)\n                    if self.failed else \"\"\n                )\n            ] if part\n        ])",
    "docstring": "Return human readable description error description.\n\n        This description should explain everything that went wrong during\n        deserialization."
  },
  {
    "code": "def find_and_modify(self, query=None, update=None):\n        update = update or {}\n        for document in self.find(query=query):\n            document.update(update)\n            self.update(document)",
    "docstring": "Finds documents in this collection that match a given query and updates them"
  },
  {
    "code": "def _parse_output(self, xml_response):\n        count = 0\n        xml_dict = {}\n        resp_message = None\n        xml_start_pos = []\n        for m in re.finditer(r\"\\<\\?xml\", xml_response):\n            xml_start_pos.append(m.start())\n        while count < len(xml_start_pos):\n            if (count == len(xml_start_pos) - 1):\n                result = xml_response[xml_start_pos[count]:]\n            else:\n                start = xml_start_pos[count]\n                end = xml_start_pos[count + 1]\n                result = xml_response[start:end]\n            result = result.strip()\n            message = etree.fromstring(result)\n            resp = self._validate_message(message)\n            if hasattr(resp, 'tag'):\n                xml_dict = self._elementtree_to_dict(resp)\n            elif resp is not None:\n                resp_message = resp\n            count = count + 1\n        if xml_dict:\n            return xml_dict\n        elif resp_message is not None:\n            return resp_message",
    "docstring": "Parse the response XML from iLO.\n\n        This function parses the output received from ILO.\n        As the output contains multiple XMLs, it extracts\n        one xml at a time and loops over till all the xmls\n        in the response are exhausted.\n\n        It returns the data to APIs either in dictionary\n        format or as the string.\n        It creates the dictionary only if the Ilo response\n        contains the data under the requested RIBCL command.\n        If the Ilo response contains only the string,\n        then the string is returned back."
  },
  {
    "code": "def dumps(self, data):\n\t\tdata = g_serializer_drivers[self.name]['dumps'](data)\n\t\tif sys.version_info[0] == 3 and isinstance(data, str):\n\t\t\tdata = data.encode(self._charset)\n\t\tif self._compression == 'zlib':\n\t\t\tdata = zlib.compress(data)\n\t\tassert isinstance(data, bytes)\n\t\treturn data",
    "docstring": "Serialize a python data type for transmission or storage.\n\n\t\t:param data: The python object to serialize.\n\t\t:return: The serialized representation of the object.\n\t\t:rtype: bytes"
  },
  {
    "code": "def dumps(self, separator='='):\n        s = six.StringIO()\n        self.dump(s, separator=separator)\n        return s.getvalue()",
    "docstring": "Convert the mapping to a text string in simple line-oriented\n        ``.properties`` format.\n\n        If the instance was originally created from a file or string with\n        `PropertiesFile.load()` or `PropertiesFile.loads()`, then the output\n        will include the comments and whitespace from the original input, and\n        any keys that haven't been deleted or reassigned will retain their\n        original formatting and multiplicity.  Key-value pairs that have been\n        modified or added to the mapping will be reformatted with\n        `join_key_value()` using the given separator.  All key-value pairs are\n        output in the order they were defined, with new keys added to the end.\n\n        .. note::\n\n            Serializing a `PropertiesFile` instance with the :func:`dumps()`\n            function instead will cause all formatting information to be\n            ignored, as :func:`dumps()` will treat the instance like a normal\n            mapping.\n\n        :param separator: The string to use for separating new or modified keys\n            & values.  Only ``\" \"``, ``\"=\"``, and ``\":\"`` (possibly with added\n            whitespace) should ever be used as the separator.\n        :type separator: text string\n        :rtype: text string"
  },
  {
    "code": "def put(self, url):\n        response = self.http_request(url, 'PUT', self, {'Content-Type': 'application/xml; charset=utf-8'})\n        if response.status != 200:\n            self.raise_http_error(response)\n        response_xml = response.read()\n        logging.getLogger('recurly.http.response').debug(response_xml)\n        self.update_from_element(ElementTree.fromstring(response_xml))",
    "docstring": "Sends this `Resource` instance to the service with a\n        ``PUT`` request to the given URL."
  },
  {
    "code": "def until_any_child_in_state(self, state, timeout=None):\n        return until_any(*[r.until_state(state) for r in dict.values(self.children)],\n                         timeout=timeout)",
    "docstring": "Return a tornado Future; resolves when any client is in specified state"
  },
  {
    "code": "def results(self) -> List[TrialResult]:\n        if not self._results:\n            job = self._update_job()\n            for _ in range(1000):\n                if job['executionStatus']['state'] in TERMINAL_STATES:\n                    break\n                time.sleep(0.5)\n                job = self._update_job()\n            if job['executionStatus']['state'] != 'SUCCESS':\n                raise RuntimeError(\n                    'Job %s did not succeed. It is in state %s.' % (\n                        job['name'], job['executionStatus']['state']))\n            self._results = self._engine.get_job_results(\n                self.job_resource_name)\n        return self._results",
    "docstring": "Returns the job results, blocking until the job is complete."
  },
  {
    "code": "def create_api_method(restApiId, resourcePath, httpMethod, authorizationType,\n                      apiKeyRequired=False, requestParameters=None, requestModels=None,\n                      region=None, key=None, keyid=None, profile=None):\n    try:\n        resource = describe_api_resource(restApiId, resourcePath, region=region,\n                                         key=key, keyid=keyid, profile=profile).get('resource')\n        if resource:\n            requestParameters = dict() if requestParameters is None else requestParameters\n            requestModels = dict() if requestModels is None else requestModels\n            conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n            method = conn.put_method(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod,\n                                     authorizationType=str(authorizationType), apiKeyRequired=apiKeyRequired,\n                                     requestParameters=requestParameters, requestModels=requestModels)\n            return {'created': True, 'method': method}\n        return {'created': False, 'error': 'Failed to create method'}\n    except ClientError as e:\n        return {'created': False, 'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Creates API method for a resource in the given API\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_apigateway.create_api_method restApiId resourcePath, httpMethod, authorizationType, \\\\\n            apiKeyRequired=False, requestParameters='{\"name\", \"value\"}', requestModels='{\"content-type\", \"value\"}'"
  },
  {
    "code": "def connect(nodes):\n    for a, b in zip(nodes[:-1], nodes[1:]):\n        a.output = b\n    b.output = queues.Queue()",
    "docstring": "Connect a list of nodes.\n\n    Connected nodes have an ``output`` member which is the following node in\n    the line. The last node's ``output`` is a :class:`Queue` for\n    easy plumbing."
  },
  {
    "code": "def load_fixtures():\n    if local(\"pwd\", capture=True) == PRODUCTION_DOCUMENT_ROOT:\n        abort(\"Refusing to automatically load fixtures into production database!\")\n    if not confirm(\"Are you sure you want to load all fixtures? This could have unintended consequences if the database is not empty.\"):\n        abort(\"Aborted.\")\n    files = [\n        \"fixtures/users/users.json\", \"fixtures/eighth/sponsors.json\", \"fixtures/eighth/rooms.json\", \"fixtures/eighth/blocks.json\",\n        \"fixtures/eighth/activities.json\", \"fixtures/eighth/scheduled_activities.json\", \"fixtures/eighth/signups.json\",\n        \"fixtures/announcements/announcements.json\"\n    ]\n    for f in files:\n        local(\"./manage.py loaddata \" + f)",
    "docstring": "Populate a database with data from fixtures."
  },
  {
    "code": "def add_metric(self, metric_name, measurable, config=None):\n        metric = KafkaMetric(metric_name, measurable, config or self.config)\n        self.register_metric(metric)",
    "docstring": "Add a metric to monitor an object that implements measurable.\n        This metric won't be associated with any sensor.\n        This is a way to expose existing values as metrics.\n\n        Arguments:\n            metricName (MetricName): The name of the metric\n            measurable (AbstractMeasurable): The measurable that will be\n                measured by this metric\n            config (MetricConfig, optional): The configuration to use when\n                measuring this measurable"
  },
  {
    "code": "def _make_expr_ops(self, op_list, op_dict=None, op_class=None):\n        for o in op_list:\n            if op_dict is not None:\n                if o in op_dict:\n                    self._op_expr[o] = op_dict[o]\n                else:\n                    l.warning(\"Operation %s not in op_dict.\", o)\n            else:\n                if hasattr(op_class, o):\n                    self._op_expr[o] = getattr(op_class, o)\n                else:\n                    l.warning(\"Operation %s not in op_class %s.\", o, op_class)",
    "docstring": "Fill up `self._op_expr` dict.\n\n        :param op_list:     A list of operation names.\n        :param op_dict:     A dictionary of operation methods.\n        :param op_class:    Where the operation method comes from.\n        :return:"
  },
  {
    "code": "def timing(func):\n    @functools.wraps(func)\n    def wrap(*args, **kw):\n        t0 = time()\n        result = func(*args, **kw)\n        t1 = time()\n        print('func:%r args:[%r, %r] took: %2.4f sec' %\n              (func.__name__, args, kw, t1 - t0))\n        return result\n    return wrap",
    "docstring": "Measure the execution time of a function call and print the result."
  },
  {
    "code": "def _adopt_notifications(self, state):\n        def iterator():\n            it = state.descriptor.pending_notifications.iteritems()\n            for _, nots in it:\n                for x in nots:\n                    yield x\n        to_adopt = list(iterator())\n        self.info(\"Will adopt %d pending notifications.\", len(to_adopt))\n        return state.sender.notify(to_adopt)",
    "docstring": "Part of the \"monitor\" restart strategy. The pending notifications\n        from descriptor of dead agent are imported to our pending list."
  },
  {
    "code": "def execute(self, env, args):\n        tasks = env.task.get_list_info()\n        if not tasks:\n            env.io.write(\"No tasks found.\")\n        else:\n            if args.verbose:\n                _print_tasks(env, tasks, mark_active=True)\n            else:\n                if env.task.active:\n                    active_task = env.task.name\n                else:\n                    active_task = None\n                for task, options, blocks in tasks:\n                    if task == active_task:\n                        env.io.success(task + ' *')\n                    else:\n                        if options is None and blocks is None:\n                            env.io.error(task + ' ~')\n                        else:\n                            env.io.write(task)",
    "docstring": "Lists all valid tasks.\n\n            `env`\n                Runtime ``Environment`` instance.\n            `args`\n                Arguments object from arg parser."
  },
  {
    "code": "def track_event(self, name, properties=None, measurements=None):\n        data = channel.contracts.EventData()\n        data.name = name or NULL_CONSTANT_STRING\n        if properties:\n            data.properties = properties\n        if measurements:\n            data.measurements = measurements\n        self.track(data, self._context)",
    "docstring": "Send information about a single event that has occurred in the context of the application.\n\n        Args:\n            name (str). the data to associate to this event.\\n\n            properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\\n\n            measurements (dict). the set of custom measurements the client wants to attach to this data item. (defaults to: None)"
  },
  {
    "code": "def iter_predict(self, X, include_init=False):\n        utils.validation.check_is_fitted(self, 'init_estimator_')\n        X = utils.check_array(X, accept_sparse=['csr', 'csc'], dtype=None, force_all_finite=False)\n        y_pred = self.init_estimator_.predict(X)\n        if include_init:\n            yield y_pred\n        for estimators, line_searchers, cols in itertools.zip_longest(self.estimators_,\n                                                                      self.line_searchers_,\n                                                                      self.columns_):\n            for i, (estimator, line_searcher) in enumerate(itertools.zip_longest(estimators,\n                                                                                 line_searchers or [])):\n                if cols is None:\n                    direction = estimator.predict(X)\n                else:\n                    direction = estimator.predict(X[:, cols])\n                if line_searcher:\n                    direction = line_searcher.update(direction)\n                y_pred[:, i] += self.learning_rate * direction\n            yield y_pred",
    "docstring": "Returns the predictions for ``X`` at every stage of the boosting procedure.\n\n        Args:\n            X (array-like or sparse matrix of shape (n_samples, n_features): The input samples.\n                Sparse matrices are accepted only if they are supported by the weak model.\n            include_init (bool, default=False): If ``True`` then the prediction from\n                ``init_estimator`` will also be returned.\n        Returns:\n            iterator of arrays of shape (n_samples,) containing the predicted values at each stage"
  },
  {
    "code": "def connect(self, target, acceptor, wrapper=None):\n        super(TCPTendrilManager, self).connect(target, acceptor, wrapper)\n        sock = socket.socket(self.addr_family, socket.SOCK_STREAM)\n        with utils.SocketCloser(sock, ignore=[application.RejectConnection]):\n            sock.bind(self.endpoint)\n            sock.connect(target)\n            if wrapper:\n                sock = wrapper(sock)\n            tend = TCPTendril(self, sock)\n            tend.application = acceptor(tend)\n            self._track_tendril(tend)\n            tend._start()\n            return tend\n        sock.close()\n        return None",
    "docstring": "Initiate a connection from the tendril manager's endpoint.\n        Once the connection is completed, a TCPTendril object will be\n        created and passed to the given acceptor.\n\n        :param target: The target of the connection attempt.\n        :param acceptor: A callable which will initialize the state of\n                         the new TCPTendril object.\n        :param wrapper: A callable taking, as its first argument, a\n                        socket.socket object.  The callable must\n                        return a valid proxy for the socket.socket\n                        object, which will subsequently be used to\n                        communicate on the connection.\n\n        For passing extra arguments to the acceptor or the wrapper,\n        see the ``TendrilPartial`` class; for chaining together\n        multiple wrappers, see the ``WrapperChain`` class."
  },
  {
    "code": "def zipentry_chunk(zipfile, name, size=_BUFFERING):\n    def chunks():\n        with zipfile.open(name) as fd:\n            buf = fd.read(size)\n            while buf:\n                yield buf\n                buf = fd.read(size)\n    return chunks",
    "docstring": "returns a generator function which when called will emit x-sized\n    chunks of the named entry in the zipfile object"
  },
  {
    "code": "def linspace2(a, b, n, dtype=None):\n    a = linspace(a, b, n + 1, dtype=dtype)[:-1]\n    if len(a) > 1:\n        diff01 = ((a[1] - a[0]) / 2).astype(a.dtype)\n        a += diff01\n    return a",
    "docstring": "similar to numpy.linspace but excluding the boundaries\n\n    this is the normal numpy.linspace:\n\n    >>> print linspace(0,1,5)\n    [ 0.    0.25  0.5   0.75  1.  ]\n\n    and this gives excludes the boundaries:\n\n    >>> print linspace2(0,1,5)\n    [ 0.1  0.3  0.5  0.7  0.9]"
  },
  {
    "code": "def as_subbundle(cls, name=None, title=None, title_plural=None):\n        return PromiseBundle(cls, name=name, title=title,\n                                title_plural=title_plural)",
    "docstring": "Wraps the given bundle so that it can be lazily\n        instantiated.\n\n        :param name: The slug for this bundle.\n        :param title: The verbose name for this bundle."
  },
  {
    "code": "def _index_impl(self):\n    runs = self._multiplexer.Runs()\n    result = {run: {} for run in runs}\n    mapping = self._multiplexer.PluginRunToTagToContent(metadata.PLUGIN_NAME)\n    for (run, tag_to_content) in six.iteritems(mapping):\n      for tag in tag_to_content:\n        summary_metadata = self._multiplexer.SummaryMetadata(run, tag)\n        tensor_events = self._multiplexer.Tensors(run, tag)\n        samples = max([self._number_of_samples(event.tensor_proto)\n                       for event in tensor_events] + [0])\n        result[run][tag] = {'displayName': summary_metadata.display_name,\n                            'description': plugin_util.markdown_to_safe_html(\n                                summary_metadata.summary_description),\n                            'samples': samples}\n    return result",
    "docstring": "Return information about the tags in each run.\n\n    Result is a dictionary of the form\n\n        {\n          \"runName1\": {\n            \"tagName1\": {\n              \"displayName\": \"The first tag\",\n              \"description\": \"<p>Long ago there was just one tag...</p>\",\n              \"samples\": 3\n            },\n            \"tagName2\": ...,\n            ...\n          },\n          \"runName2\": ...,\n          ...\n        }\n\n    For each tag, `samples` is the greatest number of audio clips that\n    appear at any particular step. (It's not related to \"samples of a\n    waveform.\") For example, if for tag `minibatch_input` there are\n    five audio clips at step 0 and ten audio clips at step 1, then the\n    dictionary for `\"minibatch_input\"` will contain `\"samples\": 10`."
  },
  {
    "code": "def generate_cutJ_genomic_CDR3_segs(self):\n        max_palindrome = self.max_delJ_palindrome\n        self.cutJ_genomic_CDR3_segs = []\n        for CDR3_J_seg in [x[1] for x in self.genJ]:\n            if len(CDR3_J_seg) < max_palindrome:\n                self.cutJ_genomic_CDR3_segs += [cutL_seq(CDR3_J_seg, 0, len(CDR3_J_seg))]\n            else:\n                self.cutJ_genomic_CDR3_segs += [cutL_seq(CDR3_J_seg, 0, max_palindrome)]",
    "docstring": "Add palindromic inserted nucleotides to germline J sequences.\n        \n        The maximum number of palindromic insertions are appended to the\n        germline J segments so that delJ can index directly for number of\n        nucleotides to delete from a segment.\n        \n        Sets the attribute cutJ_genomic_CDR3_segs."
  },
  {
    "code": "def __standardize_result(status, message, data=None, debug_msg=None):\n    result = {\n        'status': status,\n        'message': message\n    }\n    if data is not None:\n        result['return'] = data\n    if debug_msg is not None and debug:\n        result['debug'] = debug_msg\n    return result",
    "docstring": "Standardizes all responses\n\n    :param status:\n    :param message:\n    :param data:\n    :param debug_msg:\n    :return:"
  },
  {
    "code": "def srem(self, key, *values):\n        redis_set = self._get_set(key, 'SREM')\n        if not redis_set:\n            return 0\n        before_count = len(redis_set)\n        for value in values:\n            redis_set.discard(self._encode(value))\n        after_count = len(redis_set)\n        if before_count > 0 and len(redis_set) == 0:\n            self.delete(key)\n        return before_count - after_count",
    "docstring": "Emulate srem."
  },
  {
    "code": "def a_not_committed(ctx):\n    ctx.ctrl.sendline('n')\n    ctx.msg = \"Some active software packages are not yet committed. Reload may cause software rollback.\"\n    ctx.device.chain.connection.emit_message(ctx.msg, log_level=logging.ERROR)\n    ctx.failed = True\n    return False",
    "docstring": "Provide the message that current software is not committed and reload is not possible."
  },
  {
    "code": "def certify_required(value, required=False):\n    if not isinstance(required, bool):\n        raise CertifierParamError(\n            'required',\n            required,\n        )\n    if value is None:\n        if required:\n            raise CertifierValueError(\n                message=\"required value is None\",\n            )\n        return True",
    "docstring": "Certify that a value is present if required.\n\n    :param object value:\n        The value that is to be certified.\n    :param bool required:\n        Is the value required?\n    :raises CertifierValueError:\n        Required value is `None`."
  },
  {
    "code": "def t_coords(self, t_coords):\n        if not isinstance(t_coords, np.ndarray):\n            raise TypeError('Texture coordinates must be a numpy array')\n        if t_coords.ndim != 2:\n            raise AssertionError('Texture coordinates must be a 2-dimensional array')\n        if t_coords.shape[0] != self.n_points:\n            raise AssertionError('Number of texture coordinates ({}) must match number of points ({})'.format(t_coords.shape[0], self.n_points))\n        if t_coords.shape[1] != 2:\n            raise AssertionError('Texture coordinates must only have 2 components, not ({})'.format(t_coords.shape[1]))\n        if np.min(t_coords) < 0.0 or np.max(t_coords) > 1.0:\n            raise AssertionError('Texture coordinates must be within (0, 1) range.')\n        vtkarr = numpy_to_vtk(t_coords)\n        vtkarr.SetName('Texture Coordinates')\n        self.GetPointData().SetTCoords(vtkarr)\n        self.GetPointData().Modified()\n        return",
    "docstring": "Set the array to use as the texture coordinates"
  },
  {
    "code": "def makedirs(self, path, mode=0o700):\n        os.makedirs(os.path.join(self._archive_root, path), mode=mode)\n        self.log_debug(\"created directory at '%s' in FileCacheArchive '%s'\"\n                       % (path, self._archive_root))",
    "docstring": "Create path, including leading components.\n\n            Used by sos.sosreport to set up sos_* directories."
  },
  {
    "code": "def _can(self, func_name, qualifier_id=None):\n        function_id = self._get_function_id(func_name)\n        if qualifier_id is None:\n            qualifier_id = self._qualifier_id\n        agent_id = self.get_effective_agent_id()\n        try:\n            return self._authz_cache[str(agent_id) + str(function_id) + str(qualifier_id)]\n        except KeyError:\n            authz = self._authz_session.is_authorized(agent_id=agent_id,\n                                                      function_id=function_id,\n                                                      qualifier_id=qualifier_id)\n            self._authz_cache[str(agent_id) + str(function_id) + str(qualifier_id)] = authz\n            return authz",
    "docstring": "Tests if the named function is authorized with agent and qualifier.\n\n        Also, caches authz's in a dict.  It is expected that this will not grow to big, as\n        there are typically only a small number of qualifier + function combinations to\n        store for the agent.  However, if this becomes an issue, we can switch to something\n        like cachetools."
  },
  {
    "code": "def select_area(self, area_uuid):\n        self._config.upload.current_area = area_uuid\n        self.save()",
    "docstring": "Update the \"current area\" to be the area with this UUID.\n\n        :param str area_uuid: The RFC4122-compliant UUID of the Upload Area."
  },
  {
    "code": "def filter_spent_outputs(self, outputs):\n        links = [o.to_dict() for o in outputs]\n        txs = list(query.get_spending_transactions(self.connection, links))\n        spends = {TransactionLink.from_dict(input_['fulfills'])\n                  for tx in txs\n                  for input_ in tx['inputs']}\n        return [ff for ff in outputs if ff not in spends]",
    "docstring": "Remove outputs that have been spent\n\n        Args:\n            outputs: list of TransactionLink"
  },
  {
    "code": "def Description(self):\n        descr = \" \".join((self.getId(), self.aq_parent.Title()))\n        return safe_unicode(descr).encode('utf-8')",
    "docstring": "Returns searchable data as Description"
  },
  {
    "code": "def div_safe( numerator, denominator ):\n    if np.isscalar(numerator):\n        raise ValueError(\"div_safe should only be used with an array-like numerator\")\n    try:\n        with np.errstate(divide='ignore', invalid='ignore'):\n            result = np.true_divide( numerator, denominator )\n            result[ ~ np.isfinite( result )] = 0\n        return result\n    except ValueError as e:\n        raise e",
    "docstring": "Ufunc-extension that returns 0 instead of nan when dividing numpy arrays\n\n    Parameters\n    ----------\n    numerator: array-like\n\n    denominator: scalar or array-like that can be validly divided by the numerator\n\n    returns a numpy array\n\n    example: div_safe( [-1, 0, 1], 0 ) == [0, 0, 0]"
  },
  {
    "code": "def _try_instantiate(self, ipopo, factory, component):\n        try:\n            with self.__lock:\n                properties = self.__queue[factory][component]\n        except KeyError:\n            return\n        else:\n            try:\n                ipopo.instantiate(factory, component, properties)\n            except TypeError:\n                pass\n            except ValueError as ex:\n                _logger.error(\"Component already running: %s\", ex)\n            except Exception as ex:\n                _logger.exception(\"Error instantiating component: %s\", ex)",
    "docstring": "Tries to instantiate a component from the queue. Hides all exceptions.\n\n        :param ipopo: The iPOPO service\n        :param factory: Component factory\n        :param component: Component name"
  },
  {
    "code": "def generate_schedule(today=None):\n    schedule_days = {}\n    seen_items = {}\n    for slot in Slot.objects.all().order_by('end_time', 'start_time', 'day'):\n        day = slot.get_day()\n        if today and day != today:\n            continue\n        schedule_day = schedule_days.get(day)\n        if schedule_day is None:\n            schedule_day = schedule_days[day] = ScheduleDay(day)\n        row = make_schedule_row(schedule_day, slot, seen_items)\n        schedule_day.rows.append(row)\n    return sorted(schedule_days.values(), key=lambda x: x.day.date)",
    "docstring": "Helper function which creates an ordered list of schedule days"
  },
  {
    "code": "def value_from_datadict(self, data, files, name):\n        upload = super(StickyUploadWidget, self).value_from_datadict(data, files, name)\n        if upload is not None:\n            return upload\n        else:\n            hidden_name = self.get_hidden_name(name)\n            value = data.get(hidden_name, None)\n            if value is not None:\n                upload = open_stored_file(value, self.url)\n                if upload is not None:\n                    setattr(upload, '_seralized_location', value)\n        return upload",
    "docstring": "Returns uploaded file from serialized value."
  },
  {
    "code": "def _insert_data(self, connection, name, value, timestamp, interval, config):\n    cursor = connection.cursor()\n    try:\n      stmt = self._insert_stmt(name, value, timestamp, interval, config)\n      if stmt:\n        cursor.execute(stmt)\n    finally:\n      cursor.close()",
    "docstring": "Helper to insert data into cql."
  },
  {
    "code": "def add_atmost(self, lits, k, no_return=True):\n        if self.minicard:\n            res = pysolvers.minicard_add_am(self.minicard, lits, k)\n            if res == False:\n                self.status = False\n            if not no_return:\n                return res",
    "docstring": "Add a new atmost constraint to solver's internal formula."
  },
  {
    "code": "def diff(self, sym: Symbol, n: int = 1, expand_simplify: bool = True):\n        if not isinstance(sym, sympy.Basic):\n            raise TypeError(\"%s needs to be a Sympy symbol\" % sym)\n        if sym.free_symbols.issubset(self.free_symbols):\n            deriv = QuantumDerivative.create(self, derivs={sym: n}, vals=None)\n            if not deriv.is_zero and expand_simplify:\n                deriv = deriv.expand().simplify_scalar()\n            return deriv\n        else:\n            return self.__class__._zero",
    "docstring": "Differentiate by scalar parameter `sym`.\n\n        Args:\n            sym: What to differentiate by.\n            n: How often to differentiate\n            expand_simplify: Whether to simplify the result.\n\n        Returns:\n            The n-th derivative."
  },
  {
    "code": "def _StopStatusUpdateThread(self):\n    self._status_update_active = False\n    if self._status_update_thread.isAlive():\n      self._status_update_thread.join()\n    self._status_update_thread = None",
    "docstring": "Stops the status update thread."
  },
  {
    "code": "def showPopup(self):\r\n        as_dialog = QApplication.keyboardModifiers()\r\n        anchor = self.defaultAnchor()\r\n        if anchor:\r\n            self.popupWidget().setAnchor(anchor)\r\n        else:\r\n            anchor = self.popupWidget().anchor()\r\n        if ( anchor & (XPopupWidget.Anchor.BottomLeft |\r\n                       XPopupWidget.Anchor.BottomCenter |\r\n                       XPopupWidget.Anchor.BottomRight) ):\r\n            pos = QPoint(self.width() / 2, 0)\r\n        else:\r\n            pos = QPoint(self.width() / 2, self.height())\r\n        pos = self.mapToGlobal(pos)\r\n        if not self.signalsBlocked():\r\n            self.popupAboutToShow.emit()\r\n        self._popupWidget.popup(pos)\r\n        if as_dialog:\r\n            self._popupWidget.setCurrentMode(XPopupWidget.Mode.Dialog)",
    "docstring": "Shows the popup for this button."
  },
  {
    "code": "def restart(self):\n        self.initGrid()\n        self.win.clear()\n        self.current_gen = 1\n        self.start",
    "docstring": "Restart the game from a new generation 0"
  },
  {
    "code": "async def _process_latching(self, key, latching_entry):\n        if latching_entry[Constants.LATCH_CALLBACK]:\n            if latching_entry[Constants.LATCH_CALLBACK_TYPE]:\n                await latching_entry[Constants.LATCH_CALLBACK] \\\n                    ([key, latching_entry[Constants.LATCHED_DATA], time.time()])\n            else:\n                latching_entry[Constants.LATCH_CALLBACK] \\\n                    ([key, latching_entry[Constants.LATCHED_DATA], time.time()])\n            self.latch_map[key] = [0, 0, 0, 0, 0, None]\n        else:\n            updated_latch_entry = latching_entry\n            updated_latch_entry[Constants.LATCH_STATE] = \\\n                Constants.LATCH_LATCHED\n            updated_latch_entry[Constants.LATCHED_DATA] = \\\n                latching_entry[Constants.LATCHED_DATA]\n            updated_latch_entry[Constants.LATCHED_TIME_STAMP] = time.time()\n            self.latch_map[key] = updated_latch_entry",
    "docstring": "This is a private utility method.\n        This method process latching events and either returns them via\n        callback or stores them in the latch map\n\n        :param key: Encoded pin\n\n        :param latching_entry: a latch table entry\n\n        :returns: Callback or store data in latch map"
  },
  {
    "code": "def firmware_drivers(self):\n        if not self.__firmware_drivers:\n            self.__firmware_drivers = FirmwareDrivers(self.__connection)\n        return self.__firmware_drivers",
    "docstring": "Gets the FirmwareDrivers API client.\n\n        Returns:\n            FirmwareDrivers:"
  },
  {
    "code": "def decode(self, charset='utf-8', errors='replace'):\n        return URL(\n            self.scheme.decode('ascii'),\n            self.decode_netloc(),\n            self.path.decode(charset, errors),\n            self.query.decode(charset, errors),\n            self.fragment.decode(charset, errors)\n        )",
    "docstring": "Decodes the URL to a tuple made out of strings.  The charset is\n        only being used for the path, query and fragment."
  },
  {
    "code": "def write(self, s):\n        if self.comptype == \"gz\":\n            self.crc = self.zlib.crc32(s, self.crc)\n        self.pos += len(s)\n        if self.comptype != \"tar\":\n            s = self.cmp.compress(s)\n        self.__write(s)",
    "docstring": "Write string s to the stream."
  },
  {
    "code": "def get(self, href):\n        if self.is_fake:\n            return\n        uid = _trim_suffix(href, ('.ics', '.ical', '.vcf'))\n        etesync_item = self.collection.get(uid)\n        if etesync_item is None:\n            return None\n        try:\n            item = vobject.readOne(etesync_item.content)\n        except Exception as e:\n            raise RuntimeError(\"Failed to parse item %r in %r\" %\n                               (href, self.path)) from e\n        last_modified = time.strftime(\n            \"%a, %d %b %Y %H:%M:%S GMT\",\n            time.gmtime(time.time()))\n        return EteSyncItem(self, item, href, last_modified=last_modified, etesync_item=etesync_item)",
    "docstring": "Fetch a single item."
  },
  {
    "code": "def _cast(cls, base_info, take_ownership=True):\n        type_value = base_info.type.value\n        try:\n            new_obj = cast(base_info, cls.__types[type_value])\n        except KeyError:\n            new_obj = base_info\n        if take_ownership:\n            assert not base_info.__owns\n            new_obj._take_ownership()\n        return new_obj",
    "docstring": "Casts a GIBaseInfo instance to the right sub type.\n\n        The original GIBaseInfo can't have ownership.\n        Will take ownership."
  },
  {
    "code": "def create_secret(self, value, contributor, metadata=None, expires=None):\n        if metadata is None:\n            metadata = {}\n        secret = self.create(\n            value=value,\n            contributor=contributor,\n            metadata=metadata,\n            expires=expires,\n        )\n        return str(secret.handle)",
    "docstring": "Create a new secret, returning its handle.\n\n        :param value: Secret value to store\n        :param contributor: User owning the secret\n        :param metadata: Optional metadata dictionary (must be JSON serializable)\n        :param expires: Optional date/time of expiry (defaults to None, which means that\n            the secret never expires)\n        :return: Secret handle"
  },
  {
    "code": "def dump(self, fname):\n        with open(fname, 'wb') as f:\n            f.write(self.output)",
    "docstring": "Saves TZX file to fname"
  },
  {
    "code": "def record(self, chunk_size = None,\n                   dfmt = \"f\",\n                   channels = 1,\n                   rate = DEFAULT_SAMPLE_RATE,\n                   **kwargs\n            ):\n    if chunk_size is None:\n      chunk_size = chunks.size\n    if hasattr(self, \"api\"):\n      kwargs.setdefault(\"input_device_index\", self.api[\"defaultInputDevice\"])\n    channels = kwargs.pop(\"nchannels\", channels)\n    input_stream = RecStream(self,\n                             self._pa.open(format=_STRUCT2PYAUDIO[dfmt],\n                                           channels=channels,\n                                           rate=rate,\n                                           frames_per_buffer=chunk_size,\n                                           input=True,\n                                           **kwargs),\n                             chunk_size,\n                             dfmt\n                            )\n    self._recordings.append(input_stream)\n    return input_stream",
    "docstring": "Records audio from device into a Stream.\n\n    Parameters\n    ----------\n    chunk_size :\n      Number of samples per chunk (block sent to device).\n    dfmt :\n      Format, as in chunks(). Default is \"f\" (Float32).\n    channels :\n      Channels in audio stream (serialized).\n    rate :\n      Sample rate (same input used in sHz).\n\n    Returns\n    -------\n    Endless Stream instance that gather data from the audio input device."
  },
  {
    "code": "def merge_pres_feats(pres, features):\n    sub = []\n    for psub, fsub in zip(pres, features):\n        exp = []\n        for pexp, fexp in zip(psub, fsub):\n            lst = []\n            for p, f in zip(pexp, fexp):\n                p.update(f)\n                lst.append(p)\n            exp.append(lst)\n        sub.append(exp)\n    return sub",
    "docstring": "Helper function to merge pres and features to support legacy features argument"
  },
  {
    "code": "def get_arg_value_as_type(self, key, default=None, convert_int=False):\n        val = self.get_query_argument(key, default)\n        if isinstance(val, int):\n            return val\n        if val.lower() in ['true', 'yes']:\n            return True\n        if val.lower() in ['false', 'no']:\n            return False\n        return val",
    "docstring": "Allow users to pass through truthy type values like true, yes, no and get to a typed variable in your code\n\n        :param str val: The string reprensentation of the value you want to convert\n        :returns: adapted value\n        :rtype: dynamic"
  },
  {
    "code": "def do_printActivities(self,args):\n        parser = CommandArgumentParser(\"printActivities\")\n        parser.add_argument('-r','--refresh',action='store_true',dest='refresh',help='refresh');\n        args = vars(parser.parse_args(args))\n        refresh = args['refresh'] or not self.activities\n        if refresh:\n            response = self.client.describe_scaling_activities(AutoScalingGroupName=self.scalingGroup)\n            self.activities = response['Activities']\n        index = 0\n        for activity in self.activities:\n            print \"{}: {} -> {} {}: {}\".format(index,activity['StartTime'],stdplus.defaultifyDict(activity,'EndTime',''),activity['StatusCode'],activity['Description'])\n            index = index + 1",
    "docstring": "Print scaling activities"
  },
  {
    "code": "def _contextMenu(self, pos):\n        menu = QMenu(self)\n        menu.addAction(self._zoomBackAction)\n        plotArea = self.getWidgetHandle()\n        globalPosition = plotArea.mapToGlobal(pos)\n        menu.exec_(globalPosition)",
    "docstring": "Handle plot area customContextMenuRequested signal.\n\n        :param QPoint pos: Mouse position relative to plot area"
  },
  {
    "code": "def get(url, params={}):\n        request_url = url\n        if len(params):\n            request_url = \"{}?{}\".format(url, urlencode(params))\n        try:\n            req = Request(request_url, headers={'User-Agent': 'Mozilla/5.0'})\n            response = json.loads(urlopen(req).read().decode(\"utf-8\"))\n            return response\n        except HTTPError as err:\n            raise MtgException(err.read())",
    "docstring": "Invoke an HTTP GET request on a url\n\n        Args:\n            url (string): URL endpoint to request\n            params (dict): Dictionary of url parameters\n        Returns:\n            dict: JSON response as a dictionary"
  },
  {
    "code": "def equipable_classes(self):\n        sitem = self._schema_item\n        return [c for c in sitem.get(\"used_by_classes\", self.equipped.keys()) if c]",
    "docstring": "Returns a list of classes that _can_ use the item."
  },
  {
    "code": "def oauth2(self):\n        if self._url.endswith(\"/oauth2\"):\n            url = self._url\n        else:\n            url = self._url + \"/oauth2\"\n        return _oauth2.oauth2(oauth_url=url,\n                              securityHandler=self._securityHandler,\n                              proxy_url=self._proxy_url,\n                              proxy_port=self._proxy_port)",
    "docstring": "returns the oauth2 class"
  },
  {
    "code": "def failure_count(self):\n        return len([i for i, result in enumerate(self.data) if result.failure])",
    "docstring": "Amount of failed test cases in this list.\n\n        :return: integer"
  },
  {
    "code": "def uri(self):\n        if self._uds_path:\n            uri = 'mongodb://%s' % (quote_plus(self._uds_path),)\n        else:\n            uri = 'mongodb://%s' % (format_addr(self._address),)\n        return uri + '/?ssl=true' if self._ssl else uri",
    "docstring": "Connection string to pass to `~pymongo.mongo_client.MongoClient`."
  },
  {
    "code": "def remote_run(cmd, instance_name, detach=False, retries=1):\n  if detach:\n    cmd = SCREEN.format(command=cmd)\n  args = SSH.format(instance_name=instance_name).split()\n  args.append(cmd)\n  for i in range(retries + 1):\n    try:\n      if i > 0:\n        tf.logging.info(\"Retry %d for %s\", i, args)\n      return sp.check_call(args)\n    except sp.CalledProcessError as e:\n      if i == retries:\n        raise e",
    "docstring": "Run command on GCS instance, optionally detached."
  },
  {
    "code": "def setCentralWidget(self, widget):\n        self._centralWidget = widget\n        if widget is not None:\n            widget.setParent(self)\n            widget.installEventFilter(self)\n            effect = QtGui.QGraphicsDropShadowEffect(self)\n            effect.setColor(QtGui.QColor('black'))\n            effect.setBlurRadius(80)\n            effect.setOffset(0, 0)\n            widget.setGraphicsEffect(effect)",
    "docstring": "Sets the central widget for this overlay to the inputed widget.\n\n        :param      widget | <QtGui.QWidget>"
  },
  {
    "code": "def from_json(cls, data, result=None):\n        if data.get(\"type\") != cls._type_value:\n            raise exception.ElementDataWrongType(\n                type_expected=cls._type_value,\n                type_provided=data.get(\"type\")\n            )\n        tags = data.get(\"tags\", {})\n        node_id = data.get(\"id\")\n        lat = data.get(\"lat\")\n        lon = data.get(\"lon\")\n        attributes = {}\n        ignore = [\"type\", \"id\", \"lat\", \"lon\", \"tags\"]\n        for n, v in data.items():\n            if n in ignore:\n                continue\n            attributes[n] = v\n        return cls(node_id=node_id, lat=lat, lon=lon, tags=tags, attributes=attributes, result=result)",
    "docstring": "Create new Node element from JSON data\n\n        :param data: Element data from JSON\n        :type data: Dict\n        :param result: The result this element belongs to\n        :type result: overpy.Result\n        :return: New instance of Node\n        :rtype: overpy.Node\n        :raises overpy.exception.ElementDataWrongType: If type value of the passed JSON data does not match."
  },
  {
    "code": "def _select_concept(self, line):\n        g = self.current['graph']\n        if not line:\n            out = g.all_skos_concepts\n            using_pattern = False\n        else:\n            using_pattern = True\n            if line.isdigit():\n                line = int(line)\n            out = g.get_skos(line)\n        if out:\n            if type(out) == type([]):\n                choice = self._selectFromList(out, using_pattern, \"concept\")\n                if choice:\n                    self.currentEntity = {'name': choice.locale or choice.uri,\n                                          'object': choice, 'type': 'concept'}\n            else:\n                self.currentEntity = {'name': out.locale or out.uri,\n                                      'object': out, 'type': 'concept'}\n            if self.currentEntity:\n                self._print_entity_intro(entity=self.currentEntity)\n        else:\n            print(\"not found\")",
    "docstring": "try to match a class and load it"
  },
  {
    "code": "def _es_data(settings):\n        return {k: settings[k] for k in (ConsoleWidget.SETTING_DATA_FORMATING,\n                                         ConsoleWidget.SETTING_DATA_TYPE)}",
    "docstring": "Extract data formating related subset of widget settings."
  },
  {
    "code": "def get_filelikeobject(filename: str = None,\n                       blob: bytes = None) -> BinaryIO:\n    if not filename and not blob:\n        raise ValueError(\"no filename and no blob\")\n    if filename and blob:\n        raise ValueError(\"specify either filename or blob\")\n    if filename:\n        return open(filename, 'rb')\n    else:\n        return io.BytesIO(blob)",
    "docstring": "Open a file-like object.\n\n    Guard the use of this function with ``with``.\n\n    Args:\n        filename: for specifying via a filename\n        blob: for specifying via an in-memory ``bytes`` object\n\n    Returns:\n        a :class:`BinaryIO` object"
  },
  {
    "code": "def op(name,\n       data,\n       display_name=None,\n       description=None,\n       collections=None):\n  import tensorflow.compat.v1 as tf\n  if display_name is None:\n    display_name = name\n  summary_metadata = metadata.create_summary_metadata(\n      display_name=display_name, description=description)\n  with tf.name_scope(name):\n    with tf.control_dependencies([tf.assert_type(data, tf.string)]):\n      return tf.summary.tensor_summary(name='text_summary',\n                                       tensor=data,\n                                       collections=collections,\n                                       summary_metadata=summary_metadata)",
    "docstring": "Create a legacy text summary op.\n\n  Text data summarized via this plugin will be visible in the Text Dashboard\n  in TensorBoard. The standard TensorBoard Text Dashboard will render markdown\n  in the strings, and will automatically organize 1D and 2D tensors into tables.\n  If a tensor with more than 2 dimensions is provided, a 2D subarray will be\n  displayed along with a warning message. (Note that this behavior is not\n  intrinsic to the text summary API, but rather to the default TensorBoard text\n  plugin.)\n\n  Args:\n    name: A name for the generated node. Will also serve as a series name in\n      TensorBoard.\n    data: A string-type Tensor to summarize. The text must be encoded in UTF-8.\n    display_name: Optional name for this summary in TensorBoard, as a\n      constant `str`. Defaults to `name`.\n    description: Optional long-form description for this summary, as a\n      constant `str`. Markdown is supported. Defaults to empty.\n    collections: Optional list of ops.GraphKeys. The collections to which to add\n      the summary. Defaults to [Graph Keys.SUMMARIES].\n\n  Returns:\n    A TensorSummary op that is configured so that TensorBoard will recognize\n    that it contains textual data. The TensorSummary is a scalar `Tensor` of\n    type `string` which contains `Summary` protobufs.\n\n  Raises:\n    ValueError: If tensor has the wrong type."
  },
  {
    "code": "def delete_vlan(self, nexus_host, vlanid):\n        starttime = time.time()\n        path_snip = snipp.PATH_VLAN % vlanid\n        self.client.rest_delete(path_snip, nexus_host)\n        self.capture_and_print_timeshot(\n            starttime, \"del_vlan\",\n            switch=nexus_host)",
    "docstring": "Delete a VLAN on Nexus Switch given the VLAN ID."
  },
  {
    "code": "def heightmap_normalize(\n    hm: np.ndarray, mi: float = 0.0, ma: float = 1.0\n) -> None:\n    lib.TCOD_heightmap_normalize(_heightmap_cdata(hm), mi, ma)",
    "docstring": "Normalize heightmap values between ``mi`` and ``ma``.\n\n    Args:\n        mi (float): The lowest value after normalization.\n        ma (float): The highest value after normalization."
  },
  {
    "code": "def close(self, value):\n        if value is None:\n            status = Job.TERMINATED\n            status_comment = \"Job successfully terminated\"\n        else:\n            status = Job.FAILED\n            status_comment = str(value)[:255]\n        self._job.status = status\n        self._job.statusComment = status_comment \n        self._job.update()",
    "docstring": "Notify the Cytomine server of the job's end\n        Incurs a dataflows"
  },
  {
    "code": "def seg(reference_intervals, estimated_intervals):\n    return min(underseg(reference_intervals, estimated_intervals),\n               overseg(reference_intervals, estimated_intervals))",
    "docstring": "Compute the MIREX 'MeanSeg' score.\n\n    Examples\n    --------\n    >>> (ref_intervals,\n    ...  ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')\n    >>> (est_intervals,\n    ...  est_labels) = mir_eval.io.load_labeled_intervals('est.lab')\n    >>> score = mir_eval.chord.seg(ref_intervals, est_intervals)\n\n    Parameters\n    ----------\n    reference_intervals : np.ndarray, shape=(n, 2), dtype=float\n        Reference chord intervals to score against.\n    estimated_intervals : np.ndarray, shape=(m, 2), dtype=float\n        Estimated chord intervals to score against.\n\n    Returns\n    -------\n    segmentation score : float\n        Comparison score, in [0.0, 1.0], where 1.0 means perfect segmentation."
  },
  {
    "code": "def coarse_tag_str(pos_seq):\n\tglobal tag2coarse\n\ttags = [tag2coarse.get(tag, 'O') for tag in pos_seq]\n\treturn ''.join(tags)",
    "docstring": "Convert POS sequence to our coarse system, formatted as a string."
  },
  {
    "code": "def get_project_id():\n    if os.name == 'nt':\n        command = _CLOUD_SDK_WINDOWS_COMMAND\n    else:\n        command = _CLOUD_SDK_POSIX_COMMAND\n    try:\n        output = subprocess.check_output(\n            (command,) + _CLOUD_SDK_CONFIG_COMMAND,\n            stderr=subprocess.STDOUT)\n    except (subprocess.CalledProcessError, OSError, IOError):\n        return None\n    try:\n        configuration = json.loads(output.decode('utf-8'))\n    except ValueError:\n        return None\n    try:\n        return configuration['configuration']['properties']['core']['project']\n    except KeyError:\n        return None",
    "docstring": "Gets the project ID from the Cloud SDK.\n\n    Returns:\n        Optional[str]: The project ID."
  },
  {
    "code": "def add_phrase(self,\n                   phrase: List[int]) -> None:\n        if len(phrase) == 1:\n            self.final_ids.add(phrase[0])\n        else:\n            next_word = phrase[0]\n            if next_word not in self.children:\n                self.children[next_word] = AvoidTrie()\n            self.step(next_word).add_phrase(phrase[1:])",
    "docstring": "Recursively adds a phrase to this trie node.\n\n        :param phrase: A list of word IDs to add to this trie node."
  },
  {
    "code": "def parse_regions(self, path):\n        if self.schema_format.lower() == GTF.lower():\n            res = self._parse_gtf_regions(path)\n        else:\n            res = self._parse_tab_regions(path)\n        return res",
    "docstring": "Given a file path, it loads it into memory as a Pandas dataframe\n\n        :param path: file path\n        :return: a Pandas Dataframe"
  },
  {
    "code": "def body_block_paragraph_content(text):\n    \"for formatting of simple paragraphs of text only, and check if it is all whitespace\"\n    tag_content = OrderedDict()\n    if text and text != '':\n        tag_content[\"type\"] = \"paragraph\"\n        tag_content[\"text\"] = clean_whitespace(text)\n    return tag_content",
    "docstring": "for formatting of simple paragraphs of text only, and check if it is all whitespace"
  },
  {
    "code": "def bytes_from_string(value):\n    BYTE_POWER = {\n        'K': 1,\n        'KB': 1,\n        'M': 2,\n        'MB': 2,\n        'G': 3,\n        'GB': 3,\n        'T': 4,\n        'TB': 4,\n        'P': 5,\n        'PB': 5,\n    }\n    if isinstance(value, six.string_types):\n        value = six.text_type(value)\n    else:\n        msg = \"Unable to interpret non-string value '%s' as bytes\" % (value)\n        raise ValueError(msg)\n    matches = re.match(\"([0-9]+)([a-zA-Z]+)\", value)\n    if matches:\n        size = int(matches.group(1)) * (1024 ** BYTE_POWER[matches.group(2)])\n    else:\n        try:\n            size = int(value)\n        except ValueError:\n            msg = \"Unable to interpret string value '%s' as bytes\" % (value)\n            raise ValueError(msg)\n    return size",
    "docstring": "Interpret human readable string value as bytes.\n\n    Returns int"
  },
  {
    "code": "def group_by(keys, values=None, reduction=None, axis=0):\n    g = GroupBy(keys, axis)\n    if values is None:\n        return g\n    groups = g.split(values)\n    if reduction is None:\n        return g.unique, groups\n    return [(key, reduction(group)) for key, group in zip(g.unique, groups)]",
    "docstring": "construct a grouping object on the given keys, optionally performing the given reduction on the given values\n\n    Parameters\n    ----------\n    keys : indexable object\n        keys to group by\n    values : array_like, optional\n        sequence of values, of the same length as keys\n        if a reduction function is provided, the given values are reduced by key\n        if no reduction is provided, the given values are grouped and split by key\n    reduction : lambda, optional\n        reduction function to apply to the values in each group\n    axis : int, optional\n        axis to regard as the key-sequence, in case keys is multi-dimensional\n\n    Returns\n    -------\n    iterable\n        if values is None, a GroupBy object of the given keys object\n        if reduction is None, an tuple of a sequence of unique keys and a sequence of grouped values\n        else, a sequence of tuples of unique keys and reductions of values over that key-group\n\n    See Also\n    --------\n    numpy_indexed.as_index : for information regarding the casting rules to a valid Index object"
  },
  {
    "code": "def discrete(self, vertices, scale=1.0):\n        discrete = discretize_arc(vertices[self.points],\n                                  close=self.closed,\n                                  scale=scale)\n        return self._orient(discrete)",
    "docstring": "Discretize the arc entity into line sections.\n\n        Parameters\n        ------------\n        vertices : (n, dimension) float\n            Points in space\n        scale : float\n            Size of overall scene for numerical comparisons\n\n        Returns\n        -------------\n        discrete: (m, dimension) float, linear path in space"
  },
  {
    "code": "def push_build_status(id):\n    response = utils.checked_api_call(pnc_api.build_push, 'status', build_record_id=id)\n    if response:\n        return utils.format_json(response)",
    "docstring": "Get status of Brew push."
  },
  {
    "code": "def refresh(self):\n        client = self._get_client()\n        endpoint = self._endpoint.format(\n            resource_id=self.resource_id or \"\",\n            parent_id=self.parent_id or \"\",\n            grandparent_id=self.grandparent_id or \"\")\n        response = client.get_resource(endpoint)\n        self._reset_model(response)",
    "docstring": "Get the latest representation of the current model."
  },
  {
    "code": "def is_email_simple(value):\n        if '@' not in value or value.startswith('@') or value.endswith('@'):\n            return False\n        try:\n            p1, p2 = value.split('@')\n        except ValueError:\n            return False\n        if '.' not in p2 or p2.startswith('.'):\n            return False\n        return True",
    "docstring": "Return True if value looks like an email address."
  },
  {
    "code": "def create(fs, channels, application):\n    result_code = ctypes.c_int()\n    result = _create(fs, channels, application, ctypes.byref(result_code))\n    if result_code.value is not constants.OK:\n        raise OpusError(result_code.value)\n    return result",
    "docstring": "Allocates and initializes an encoder state."
  },
  {
    "code": "def generate_yaml_file(filename, contents):\n    with open(filename, 'w') as file:\n        file.write(yaml.dump(contents, default_flow_style=False))",
    "docstring": "Creates a yaml file with the given content."
  },
  {
    "code": "def _is_non_string_iterable(value):\n    if isinstance(value, str):\n        return False\n    if hasattr(value, '__iter__'):\n        return True\n    if isinstance(value, collections.abc.Sequence):\n        return True\n    return False",
    "docstring": "Whether a value is iterable."
  },
  {
    "code": "def PrependSOffsetTRelative(self, off):\n        self.Prep(N.SOffsetTFlags.bytewidth, 0)\n        if not (off <= self.Offset()):\n            msg = \"flatbuffers: Offset arithmetic error.\"\n            raise OffsetArithmeticError(msg)\n        off2 = self.Offset() - off + N.SOffsetTFlags.bytewidth\n        self.PlaceSOffsetT(off2)",
    "docstring": "PrependSOffsetTRelative prepends an SOffsetT, relative to where it\n        will be written."
  },
  {
    "code": "def login(self):\n        if self.reddit.is_oauth_session():\n            ch = self.term.show_notification('Log out? (y/n)')\n            if ch in (ord('y'), ord('Y')):\n                self.oauth.clear_oauth_data()\n                self.term.show_notification('Logged out')\n        else:\n            self.oauth.authorize()",
    "docstring": "Prompt to log into the user's account, or log out of the current\n        account."
  },
  {
    "code": "def set_input_by_xpath(self, xpath, value):\n        elem = self.select(xpath).node()\n        if self._lxml_form is None:\n            parent = elem\n            while True:\n                parent = parent.getparent()\n                if parent.tag == 'form':\n                    self._lxml_form = parent\n                    break\n        return self.set_input(elem.get('name'), value)",
    "docstring": "Set the value of form element by xpath\n\n        :param xpath: xpath path\n        :param value: value which should be set to element"
  },
  {
    "code": "def convert_items(self, items):\n        return ((key, self.convert(value, self)) for key, value in items)",
    "docstring": "Generator like `convert_iterable`, but for 2-tuple iterators."
  },
  {
    "code": "def slice_to(self, s):\n        result = ''\n        if self.slice_check():\n            result = self.current[self.bra:self.ket]\n        return result",
    "docstring": "Copy the slice into the supplied StringBuffer\n\n        @type s: string"
  },
  {
    "code": "def smart_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):\n    return force_unicode(s, encoding, strings_only, errors)",
    "docstring": "Returns a unicode object representing 's'. Treats bytestrings using the\n    'encoding' codec.\n\n    If strings_only is True, don't convert (some) non-string-like objects."
  },
  {
    "code": "def verify_keys(self):\n        verify_keys_endpoint = Template(\"${rest_root}/site/${public_key}\")\n        url = verify_keys_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key)\n        data = { \"clientName\": \"mollom_python\", \"clientVersion\": \"1.0\" }\n        self._client.headers[\"Content-Type\"] = \"application/x-www-form-urlencoded\"\n        response = self._client.post(url, data, timeout=self._timeout)\n        if response.status_code != 200:\n            raise MollomAuthenticationError\n        return True",
    "docstring": "Verify that the public and private key combination is valid; raises MollomAuthenticationError otherwise"
  },
  {
    "code": "def is_exact(needle, haystack, start, end, matchnot):\n    return ((start >= 0 and end < len(haystack) and\n             haystack[start:end] == needle) ^ matchnot)",
    "docstring": "Check exact occurrence of needle in haystack"
  },
  {
    "code": "def read_xso(src, xsomap):\n    xso_parser = xso.XSOParser()\n    for class_, cb in xsomap.items():\n        xso_parser.add_class(class_, cb)\n    driver = xso.SAXDriver(xso_parser)\n    parser = xml.sax.make_parser()\n    parser.setFeature(\n        xml.sax.handler.feature_namespaces,\n        True)\n    parser.setFeature(\n        xml.sax.handler.feature_external_ges,\n        False)\n    parser.setContentHandler(driver)\n    parser.parse(src)",
    "docstring": "Read a single XSO from a binary file-like input `src` containing an XML\n    document.\n\n    `xsomap` must be a mapping which maps :class:`~.XSO` subclasses\n    to callables. These will be registered at a newly created\n    :class:`.xso.XSOParser` instance which will be used to parse the  document\n    in `src`.\n\n    The `xsomap` is thus used to determine the class parsing the root element\n    of the XML document. This can be used to support multiple versions."
  },
  {
    "code": "def _CreateMultipleValuesCondition(self, values, operator):\n    values = ['\"%s\"' % value if isinstance(value, str) or\n              isinstance(value, unicode) else str(value) for value in values]\n    return '%s %s [%s]' % (self._field, operator, ', '.join(values))",
    "docstring": "Creates a condition with the provided list of values and operator."
  },
  {
    "code": "def is_transaction_invalidated(transaction, state_change):\n    is_our_failed_update_transfer = (\n        isinstance(state_change, ContractReceiveChannelSettled) and\n        isinstance(transaction, ContractSendChannelUpdateTransfer) and\n        state_change.token_network_identifier == transaction.token_network_identifier and\n        state_change.channel_identifier == transaction.channel_identifier\n    )\n    if is_our_failed_update_transfer:\n        return True\n    return False",
    "docstring": "True if the `transaction` is made invalid by `state_change`.\n\n    Some transactions will fail due to race conditions. The races are:\n\n    - Another transaction which has the same side effect is executed before.\n    - Another transaction which *invalidates* the state of the smart contract\n    required by the local transaction is executed before it.\n\n    The first case is handled by the predicate `is_transaction_effect_satisfied`,\n    where a transaction from a different source which does the same thing is\n    considered. This predicate handles the second scenario.\n\n    A transaction can **only** invalidate another iff both share a valid\n    initial state but a different end state.\n\n    Valid example:\n\n        A close can invalidate a deposit, because both a close and a deposit\n        can be executed from an opened state (same initial state), but a close\n        transaction will transition the channel to a closed state which doesn't\n        allow for deposits (different end state).\n\n    Invalid example:\n\n        A settle transaction cannot invalidate a deposit because a settle is\n        only allowed for the closed state and deposits are only allowed for\n        the open state. In such a case a deposit should never have been sent.\n        The deposit transaction for an invalid state is a bug and not a\n        transaction which was invalidated."
  },
  {
    "code": "def _after_request(self, response):\n        if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):\n            return response\n        try:\n            tracer = execution_context.get_opencensus_tracer()\n            tracer.add_attribute_to_current_span(\n                HTTP_STATUS_CODE,\n                str(response.status_code))\n        except Exception:\n            log.error('Failed to trace request', exc_info=True)\n        finally:\n            return response",
    "docstring": "A function to be run after each request.\n\n        See: http://flask.pocoo.org/docs/0.12/api/#flask.Flask.after_request"
  },
  {
    "code": "def get_catalog_admin_session(self, proxy):\n        if not self.supports_catalog_admin():\n            raise errors.Unimplemented()\n        return sessions.CatalogAdminSession(proxy=proxy, runtime=self._runtime)",
    "docstring": "Gets the catalog administrative session for creating, updating and deleting catalogs.\n\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.cataloging.CatalogAdminSession) - a\n                ``CatalogAdminSession``\n        raise:  NullArgument - ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_catalog_admin()`` is\n                ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_catalog_admin()`` is ``true``.*"
  },
  {
    "code": "def add_modules(self, package):\n        for name in os.listdir(package.__path__[0]):\n            if name.startswith('_'):\n                continue\n            name = name.split('.')[0]\n            short = '|%s|' % name\n            long = ':mod:`~%s.%s`' % (package.__package__, name)\n            self._short2long[short] = long",
    "docstring": "Add the modules of the given package without their members."
  },
  {
    "code": "def cli(log_level):\n    try:\n        has_minimum_version()\n    except TmuxCommandNotFound:\n        click.echo('tmux not found. tmuxp requires you install tmux first.')\n        sys.exit()\n    except exc.TmuxpException as e:\n        click.echo(e, err=True)\n        sys.exit()\n    setup_logger(level=log_level.upper())",
    "docstring": "Manage tmux sessions.\n\n    Pass the \"--help\" argument to any command to see detailed help.\n    See detailed documentation and examples at:\n    http://tmuxp.readthedocs.io/en/latest/"
  },
  {
    "code": "def registerCategory(category):\n    global _DEBUG\n    global _levels\n    global _categories\n    level = 0\n    chunks = _DEBUG.split(',')\n    for chunk in chunks:\n        if not chunk:\n            continue\n        if ':' in chunk:\n            spec, value = chunk.split(':')\n        else:\n            spec = '*'\n            value = chunk\n        if category in fnmatch.filter((category, ), spec):\n            if not value:\n                continue\n            try:\n                level = int(value)\n            except ValueError:\n                level = 5\n    _categories[category] = level",
    "docstring": "Register a given category in the debug system.\n    A level will be assigned to it based on previous calls to setDebug."
  },
  {
    "code": "def schedule(self, task):\n        self.task_manager.register(task)\n        self.worker_manager.dispatch(task)",
    "docstring": "Schedules a new Task in the PoolManager."
  },
  {
    "code": "def import_file(self, record, field, fname, fobj, event=None,\n            return_format='json'):\n        self._check_file_field(field)\n        pl = self.__basepl(content='file', format=return_format)\n        del pl['format']\n        pl['returnFormat'] = return_format\n        pl['action'] = 'import'\n        pl['field'] = field\n        pl['record'] = record\n        if event:\n            pl['event'] = event\n        file_kwargs = {'files': {'file': (fname, fobj)}}\n        return self._call_api(pl, 'imp_file', **file_kwargs)[0]",
    "docstring": "Import the contents of a file represented by fobj to a\n        particular records field\n\n        Parameters\n        ----------\n        record : str\n            record ID\n        field : str\n            field name where the file will go\n        fname : str\n            file name visible in REDCap UI\n        fobj : file object\n            file object as returned by `open`\n        event : str\n            for longitudinal projects, specify the unique event here\n        return_format : ('json'), 'csv', 'xml'\n            format of error message\n\n        Returns\n        -------\n        response :\n            response from server as specified by ``return_format``"
  },
  {
    "code": "def get_package_versions(intfs, props):\n    result = []\n    for intf in intfs:\n        pkg_name = get_package_from_classname(intf)\n        if pkg_name:\n            key = ENDPOINT_PACKAGE_VERSION_ + pkg_name\n            val = props.get(key, None)\n            if val:\n                result.append((key, val))\n    return result",
    "docstring": "Gets the package version of interfaces\n\n    :param intfs: A list of interfaces\n    :param props: A dictionary containing endpoint package versions\n    :return: A list of tuples (package name, version)"
  },
  {
    "code": "def minimum_multivariate_ess(nmr_params, alpha=0.05, epsilon=0.05):\n    r\n    tmp = 2.0 / nmr_params\n    log_min_ess = tmp * np.log(2) + np.log(np.pi) - tmp * (np.log(nmr_params) + gammaln(nmr_params / 2)) \\\n                  + np.log(chi2.ppf(1 - alpha, nmr_params)) - 2 * np.log(epsilon)\n    return int(round(np.exp(log_min_ess)))",
    "docstring": "r\"\"\"Calculate the minimum multivariate Effective Sample Size you will need to obtain the desired precision.\n\n    This implements the inequality from Vats et al. (2016):\n\n    .. math::\n\n        \\widehat{ESS} \\geq \\frac{2^{2/p}\\pi}{(p\\Gamma(p/2))^{2/p}} \\frac{\\chi^{2}_{1-\\alpha,p}}{\\epsilon^{2}}\n\n    Where :math:`p` is the number of free parameters.\n\n    Args:\n        nmr_params (int): the number of free parameters in the model\n        alpha (float): the level of confidence of the confidence region. For example, an alpha of 0.05 means\n            that we want to be in a 95% confidence region.\n        epsilon (float): the level of precision in our multivariate ESS estimate.\n            An epsilon of 0.05 means that we expect that the Monte Carlo error is 5% of the uncertainty in\n            the target distribution.\n\n    Returns:\n        float: the minimum multivariate Effective Sample Size that one should aim for in MCMC sample to\n            obtain the desired confidence region with the desired precision.\n\n    References:\n        Vats D, Flegal J, Jones G (2016). Multivariate Output Analysis for Markov Chain Monte Carlo.\n        arXiv:1512.07713v2 [math.ST]"
  },
  {
    "code": "async def download_media_by_id(self, media_id):\n        try:\n            msg = self.found_media[int(media_id)]\n        except (ValueError, KeyError):\n            print('Invalid media ID given or message not found!')\n            return\n        print('Downloading media to usermedia/...')\n        os.makedirs('usermedia', exist_ok=True)\n        output = await self.download_media(\n            msg.media,\n            file='usermedia/',\n            progress_callback=self.download_progress_callback\n        )\n        print('Media downloaded to {}!'.format(output))",
    "docstring": "Given a message ID, finds the media this message contained and\n           downloads it."
  },
  {
    "code": "def get_default_compartment(model):\n    default_compartment = 'c'\n    default_key = set()\n    for reaction in model.reactions:\n        equation = reaction.equation\n        if equation is None:\n            continue\n        for compound, _ in equation.compounds:\n            default_key.add(compound.compartment)\n    if None in default_key and default_compartment in default_key:\n        suffix = 1\n        while True:\n            new_key = '{}_{}'.format(default_compartment, suffix)\n            if new_key not in default_key:\n                default_compartment = new_key\n                break\n            suffix += 1\n    if None in default_key:\n        logger.warning(\n            'Compound(s) found without compartment, default'\n            ' compartment is set to {}.'.format(default_compartment))\n    return default_compartment",
    "docstring": "Return what the default compartment should be set to.\n\n    If some compounds have no compartment, unique compartment\n    name is returned to avoid collisions."
  },
  {
    "code": "def get_assessment_offered_query_session(self):\n        if not self.supports_assessment_offered_query():\n            raise errors.Unimplemented()\n        return sessions.AssessmentOfferedQuerySession(runtime=self._runtime)",
    "docstring": "Gets the ``OsidSession`` associated with the assessment offered query service.\n\n        return: (osid.assessment.AssessmentOfferedQuerySession) - an\n                ``AssessmentOfferedQuerySession``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_assessment_offered_query()``\n                is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_assessment_offered_query()`` is ``true``.*"
  },
  {
    "code": "def _extract_key_value(obj):\n    key = None; value = None\n    if isinstance(obj, Value):\n        key = _construct_new_key(obj.name, obj.units)\n        value = []\n        if obj.scalars:\n            value = [(val.value if isinstance(val, Scalar) else val)\n                     for val in obj.scalars]\n        elif obj.vectors and len(obj.vectors) == 1:\n            value = [(val.value if isinstance(val, Scalar) else val)\n                     for val in obj.vectors[0]]\n        if len(value) == 1:\n            value = value[0]\n        elif len(value) == 0:\n            value = None\n    if isinstance(obj, ProcessStep):\n        key = \"Processing\"\n        value = obj.name\n    return key, value",
    "docstring": "Extract the value from the object and make a descriptive key"
  },
  {
    "code": "def total_errors(self):\n        child_errors = sum(len(tree) for _, tree in iteritems(self._contents))\n        return len(self.errors) + child_errors",
    "docstring": "The total number of errors in the entire tree, including children."
  },
  {
    "code": "def socks_username(self, value):\n        self._verify_proxy_type_compatibility(ProxyType.MANUAL)\n        self.proxyType = ProxyType.MANUAL\n        self.socksUsername = value",
    "docstring": "Sets socks proxy username setting.\n\n        :Args:\n         - value: The socks proxy username value."
  },
  {
    "code": "def coinbase_tx(cls, public_key_sec, coin_value, coinbase_bytes=b'', version=1, lock_time=0):\n        tx_in = cls.TxIn.coinbase_tx_in(script=coinbase_bytes)\n        COINBASE_SCRIPT_OUT = \"%s OP_CHECKSIG\"\n        script_text = COINBASE_SCRIPT_OUT % b2h(public_key_sec)\n        script_bin = BitcoinScriptTools.compile(script_text)\n        tx_out = cls.TxOut(coin_value, script_bin)\n        return cls(version, [tx_in], [tx_out], lock_time)",
    "docstring": "Create the special \"first in block\" transaction that includes the mining fees."
  },
  {
    "code": "def average_sources(source_encoded: mx.sym.Symbol, source_encoded_length: mx.sym.Symbol) -> mx.nd.NDArray:\n        source_masked = mx.sym.SequenceMask(data=source_encoded,\n                                            axis=1,\n                                            sequence_length=source_encoded_length,\n                                            use_sequence_length=True,\n                                            value=0.)\n        averaged = mx.sym.broadcast_div(mx.sym.sum(source_masked, axis=1, keepdims=False),\n                                                   mx.sym.reshape(source_encoded_length, shape=(-1, 1)))\n        return averaged",
    "docstring": "Calculate the average of encoded sources taking into account their lengths.\n\n        :param source_encoded: Encoder representation for n elements. Shape: (n, source_encoded_length, hidden_size).\n        :param source_encoded_length: A vector of encoded sequence lengths. Shape: (n,).\n        :return: Average vectors. Shape(n, hidden_size)."
  },
  {
    "code": "def path_exists_or_creatable_portable(pathname: str) -> bool:\n    try:\n        return is_pathname_valid(pathname) and (\n            os.path.exists(pathname) or is_path_sibling_creatable(pathname))\n    except OSError:\n        return False",
    "docstring": "OS-portable check for whether current path exists or is creatable.\n\n    This function is guaranteed to _never_ raise exceptions.\n\n    Returns\n    ------\n    `True` if the passed pathname is a valid pathname on the current OS _and_\n    either currently exists or is hypothetically creatable in a cross-platform\n    manner optimized for POSIX-unfriendly filesystems; `False` otherwise."
  },
  {
    "code": "def pandas_series_to_biopython_seqrecord(\n    series,\n    id_col='uid',\n    sequence_col='sequence',\n    extra_data=None,\n    alphabet=None\n    ):\n    seq = Seq(series[sequence_col], alphabet=alphabet)\n    id = series[id_col]\n    description = \"\"\n    if extra_data is not None:\n        description = \" \".join([series[key] for key in extra_data])\n    record = SeqRecord(\n        seq=seq,\n        id=id,\n        description=description,\n    )\n    seq_records = [record]\n    return seq_records",
    "docstring": "Convert pandas series to biopython seqrecord for easy writing.\n\n    Parameters\n    ----------\n    series : Series\n        Pandas series to convert\n\n    id_col : str\n        column in dataframe to use as sequence label\n\n    sequence_col : str\n        column in dataframe to use as sequence data\n\n    extra_data : list\n        extra columns to use in sequence description line\n\n    Returns\n    -------\n    seq_records :\n        List of biopython seqrecords."
  },
  {
    "code": "def register_preset(cls, name, preset):\n        if cls._presets is None:\n            cls._presets = {}\n        cls._presets[name] = preset",
    "docstring": "Register a preset instance with the class of the hub it corresponds to. This allows individual plugin objects to\n        automatically register themselves with a preset by using a classmethod of their own with only the name of the\n        preset to register with."
  },
  {
    "code": "def _update_all_devices(self):\n        self.all_devices = []\n        self.all_devices.extend(self.keyboards)\n        self.all_devices.extend(self.mice)\n        self.all_devices.extend(self.gamepads)\n        self.all_devices.extend(self.other_devices)",
    "docstring": "Update the all_devices list."
  },
  {
    "code": "def deletescript(self, name):\n        code, data = self.__send_command(\n            \"DELETESCRIPT\", [name.encode(\"utf-8\")])\n        if code == \"OK\":\n            return True\n        return False",
    "docstring": "Delete a script from the server\n\n        See MANAGESIEVE specifications, section 2.10\n\n        :param name: script's name\n        :rtype: boolean"
  },
  {
    "code": "def init(image, root=None):\n    nbd = connect(image)\n    if not nbd:\n        return ''\n    return mount(nbd, root)",
    "docstring": "Mount the named image via qemu-nbd and return the mounted roots\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' qemu_nbd.init /srv/image.qcow2"
  },
  {
    "code": "def cudnnDestroy(handle):\n    status = _libcudnn.cudnnDestroy(ctypes.c_void_p(handle))\n    cudnnCheckStatus(status)",
    "docstring": "Release cuDNN resources.\n\n    Release hardware resources used by cuDNN.\n\n    Parameters\n    ----------\n    handle : cudnnHandle\n        cuDNN context."
  },
  {
    "code": "def getFeatureSet(self, id_):\n        if id_ not in self._featureSetIdMap:\n            raise exceptions.FeatureSetNotFoundException(id_)\n        return self._featureSetIdMap[id_]",
    "docstring": "Returns the FeatureSet with the specified id, or raises a\n        FeatureSetNotFoundException otherwise."
  },
  {
    "code": "def packbools(bools, dtype='L'):\n    r = NBITS[dtype]\n    atoms = ATOMS[dtype]\n    for chunk in zip_longest(*[iter(bools)] * r, fillvalue=False):\n        yield sum(compress(atoms, chunk))",
    "docstring": "Yield integers concatenating bools in chunks of dtype bit-length.\n\n    >>> list(packbools([False, True, False, True, False, True], 'B'))\n    [42]"
  },
  {
    "code": "def get_compare_version():\n    state, latest_version = compare_latest_version()\n    if state < 0:\n        return -1, \"A new version of Modis is available (v{})\".format(latest_version)\n    elif state == 0:\n        return 0, \"You are running the latest version of Modis (v{})\".format(version)\n    else:\n        return 1, \"You are running a preview version of Modis (v{} pre-release)\".format(version)",
    "docstring": "Get the version comparison info.\n\n    Returns: (tuple)\n        state (int): -1 for lower version, 0 for same version, 1 for higher version than latest.\n        response (str): The response string."
  },
  {
    "code": "def looks_like_url(url):\n    if not isinstance(url, basestring):\n        return False\n    if not isinstance(url, basestring) or len(url) >= 1024 or not cre_url.match(url):\n        return False\n    return True",
    "docstring": "Simplified check to see if the text appears to be a URL.\n\n    Similar to `urlparse` but much more basic.\n\n    Returns:\n      True if the url str appears to be valid.\n      False otherwise.\n\n    >>> url = looks_like_url(\"totalgood.org\")\n    >>> bool(url)\n    True"
  },
  {
    "code": "def reftrack_object_data(rt, role):\n    if role == QtCore.Qt.DisplayRole:\n        return str(rt)\n    if role == REFTRACK_OBJECT_ROLE:\n        return rt",
    "docstring": "Return the reftrack for REFTRACK_OBJECT_ROLE\n\n    :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data\n    :type rt: :class:`jukeboxcore.reftrack.Reftrack`\n    :param role: item data role\n    :type role: QtCore.Qt.ItemDataRole\n    :returns: data for the id\n    :rtype: depending on the role\n    :raises: None"
  },
  {
    "code": "def _from_derivatives(xi, yi, x, order=None, der=0, extrapolate=False):\n    from scipy import interpolate\n    method = interpolate.BPoly.from_derivatives\n    m = method(xi, yi.reshape(-1, 1),\n               orders=order, extrapolate=extrapolate)\n    return m(x)",
    "docstring": "Convenience function for interpolate.BPoly.from_derivatives.\n\n    Construct a piecewise polynomial in the Bernstein basis, compatible\n    with the specified values and derivatives at breakpoints.\n\n    Parameters\n    ----------\n    xi : array_like\n        sorted 1D array of x-coordinates\n    yi : array_like or list of array-likes\n        yi[i][j] is the j-th derivative known at xi[i]\n    order: None or int or array_like of ints. Default: None.\n        Specifies the degree of local polynomials. If not None, some\n        derivatives are ignored.\n    der : int or list\n        How many derivatives to extract; None for all potentially nonzero\n        derivatives (that is a number equal to the number of points), or a\n        list of derivatives to extract. This numberincludes the function\n        value as 0th derivative.\n     extrapolate : bool, optional\n        Whether to extrapolate to ouf-of-bounds points based on first and last\n        intervals, or to return NaNs. Default: True.\n\n    See Also\n    --------\n    scipy.interpolate.BPoly.from_derivatives\n\n    Returns\n    -------\n    y : scalar or array_like\n        The result, of length R or length M or M by R."
  },
  {
    "code": "def post(self, path, data, **kwargs):\n        url = self._make_url(path)\n        return self._make_request(\"POST\", url, data=data, **kwargs)",
    "docstring": "Perform an HTTP POST request of the specified path in Device Cloud\n\n        Make an HTTP POST request against Device Cloud with this accounts\n        credentials and base url.  This method uses the\n        `requests <http://docs.python-requests.org/en/latest/>`_ library\n        `request method <http://docs.python-requests.org/en/latest/api/#requests.request>`_\n        and all keyword arguments will be passed on to that method.\n\n        :param str path: Device Cloud path to POST\n        :param int retries: The number of times the request should be retried if an\n            unsuccessful response is received.  Most likely, you should leave this at 0.\n        :param data: The data to be posted in the body of the POST request (see docs for\n            ``requests.post``\n        :raises DeviceCloudHttpException: if a non-success response to the request is received\n            from Device Cloud\n        :returns: A requests ``Response`` object"
  },
  {
    "code": "def get_addon_id(addonxml):\n    xml = parse(addonxml)\n    addon_node = xml.getElementsByTagName('addon')[0]\n    return addon_node.getAttribute('id')",
    "docstring": "Parses an addon id from the given addon.xml filename."
  },
  {
    "code": "def _check_local_handlers(cls, signals, handlers, namespace, configs):\n        for aname, sig_name in handlers.items():\n            if sig_name not in signals:\n                disable_check = configs[aname].get('disable_check', False)\n                if not disable_check:\n                    raise SignalError(\"Cannot find a signal named '%s'\"\n                                      % sig_name)",
    "docstring": "For every marked handler, see if there is a suitable signal. If\n        not, raise an error."
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'entities' in _dict:\n            args['entities'] = [\n                QueryEntitiesResponseItem._from_dict(x)\n                for x in (_dict.get('entities'))\n            ]\n        return cls(**args)",
    "docstring": "Initialize a QueryEntitiesResponse object from a json dictionary."
  },
  {
    "code": "def _generate_grid(self):\n        grid_axes = []\n        for _, param in self.tunables:\n            grid_axes.append(param.get_grid_axis(self.grid_width))\n        return grid_axes",
    "docstring": "Get the all possible values for each of the tunables."
  },
  {
    "code": "def matches(self, verb, params):\n        return (self.ifset   is None or self.ifset          <= params) and \\\n               (self.ifnset  is None or self.ifnset.isdisjoint(params)) and \\\n               (self.methods is None or verb in self.methods)",
    "docstring": "Test if the method matches the provided set of arguments\n\n        :param verb: HTTP verb. Uppercase\n        :type verb: str\n        :param params: Existing route parameters\n        :type params: set\n        :returns: Whether this view matches\n        :rtype: bool"
  },
  {
    "code": "def attach_socket(self, container, params=None, ws=False):\n        if params is None:\n            params = {\n                'stdout': 1,\n                'stderr': 1,\n                'stream': 1\n            }\n        if 'detachKeys' not in params \\\n                and 'detachKeys' in self._general_configs:\n            params['detachKeys'] = self._general_configs['detachKeys']\n        if ws:\n            return self._attach_websocket(container, params)\n        headers = {\n            'Connection': 'Upgrade',\n            'Upgrade': 'tcp'\n        }\n        u = self._url(\"/containers/{0}/attach\", container)\n        return self._get_raw_response_socket(\n            self.post(\n                u, None, params=self._attach_params(params), stream=True,\n                headers=headers\n            )\n        )",
    "docstring": "Like ``attach``, but returns the underlying socket-like object for the\n        HTTP request.\n\n        Args:\n            container (str): The container to attach to.\n            params (dict): Dictionary of request parameters (e.g. ``stdout``,\n                ``stderr``, ``stream``).\n                For ``detachKeys``, ~/.docker/config.json is used by default.\n            ws (bool): Use websockets instead of raw HTTP.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def push(self, obj):\n        if isinstance(obj, str):\n            obj = KQMLToken(obj)\n        self.data.insert(0, obj)",
    "docstring": "Prepend an element to the beginnging of the list.\n\n        Parameters\n        ----------\n        obj : KQMLObject or str\n            If a string is passed, it is instantiated as a\n            KQMLToken before being added to the list."
  },
  {
    "code": "def ceph_is_installed(module):\n    ceph_package = Ceph(module.conn)\n    if not ceph_package.installed:\n        host = module.conn.hostname\n        raise RuntimeError(\n            'ceph needs to be installed in remote host: %s' % host\n        )",
    "docstring": "A helper callback to be executed after the connection is made to ensure\n    that Ceph is installed."
  },
  {
    "code": "def set_widgets(self):\n        last_layer = self.parent.layer and self.parent.layer.id() or None\n        self.lblDescribeCanvasAggLayer.clear()\n        self.list_compatible_canvas_layers()\n        self.auto_select_one_item(self.lstCanvasAggLayers)\n        if last_layer:\n            layers = []\n            for indx in range(self.lstCanvasAggLayers.count()):\n                item = self.lstCanvasAggLayers.item(indx)\n                layers += [item.data(QtCore.Qt.UserRole)]\n            if last_layer in layers:\n                self.lstCanvasAggLayers.setCurrentRow(layers.index(last_layer))\n        self.lblIconIFCWAggregationFromCanvas.setPixmap(QPixmap(None))",
    "docstring": "Set widgets on the Aggregation Layer from Canvas tab."
  },
  {
    "code": "def _fw_pointers_convert_append_to_write(previous_version):\n    prev_fw_config = get_fwptr_config(previous_version)\n    return prev_fw_config is FwPointersCfg.ENABLED and ARCTIC_FORWARD_POINTERS_CFG is not FwPointersCfg.ENABLED",
    "docstring": "This method decides whether to convert an append to a full write  in order to avoid data integrity errors"
  },
  {
    "code": "def get_range_string(self):\n    return self.left.chr+\":\"+str(self.left.end)+'/'+self.right.chr+\":\"+str(self.right.start)",
    "docstring": "Another string representation of the junction.  these may be redundant."
  },
  {
    "code": "def makeSer(segID, N, CA, C, O, geo):\n    CA_CB_length=geo.CA_CB_length\n    C_CA_CB_angle=geo.C_CA_CB_angle\n    N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle\n    CB_OG_length=geo.CB_OG_length\n    CA_CB_OG_angle=geo.CA_CB_OG_angle\n    N_CA_CB_OG_diangle=geo.N_CA_CB_OG_diangle\n    carbon_b= calculateCoordinates(N, C, CA, CA_CB_length, C_CA_CB_angle, N_C_CA_CB_diangle)\n    CB= Atom(\"CB\", carbon_b, 0.0 , 1.0, \" \",\" CB\", 0,\"C\")\n    oxygen_g= calculateCoordinates(N, CA, CB, CB_OG_length, CA_CB_OG_angle, N_CA_CB_OG_diangle)\n    OG= Atom(\"OG\", oxygen_g, 0.0, 1.0, \" \", \" OG\", 0, \"O\")\n    res= Residue((' ', segID, ' '), \"SER\", '    ')\n    res.add(N)\n    res.add(CA)\n    res.add(C)\n    res.add(O)\n    res.add(CB)\n    res.add(OG)\n    return res",
    "docstring": "Creates a Serine residue"
  },
  {
    "code": "def updateMedShockProcess(self):\n        MedShkDstn = []\n        for t in range(self.T_cycle):\n            MedShkAvgNow  = self.MedShkAvg[t]\n            MedShkStdNow  = self.MedShkStd[t]\n            MedShkDstnNow = approxLognormal(mu=np.log(MedShkAvgNow)-0.5*MedShkStdNow**2,\\\n                            sigma=MedShkStdNow,N=self.MedShkCount, tail_N=self.MedShkCountTail,\n                            tail_bound=[0,0.9])\n            MedShkDstnNow = addDiscreteOutcomeConstantMean(MedShkDstnNow,0.0,0.0,sort=True)\n            MedShkDstn.append(MedShkDstnNow)\n        self.MedShkDstn = MedShkDstn\n        self.addToTimeVary('MedShkDstn')",
    "docstring": "Constructs discrete distributions of medical preference shocks for each\n        period in the cycle.  Distributions are saved as attribute MedShkDstn,\n        which is added to time_vary.\n\n        Parameters\n        ----------\n        None\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def delete(self, cls, rid, user='undefined'):\n        self.validate_record_type(cls)\n        deletedcount = self.db.delete(cls, {ID: rid})\n        if deletedcount < 1:\n            raise KeyError('No record {}/{}'.format(cls, rid))",
    "docstring": "Delete a record by id.\n\n        `user` currently unused. Would be used with soft deletes.\n\n        >>> s = teststore()\n        >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})\n        >>> len(s.list('tstoretest'))\n        1\n        >>> s.delete('tstoretest', '1')\n        >>> len(s.list('tstoretest'))\n        0\n        >>> s.delete('tstoretest', '1')\n        Traceback (most recent call last):\n            ...\n        KeyError: 'No record tstoretest/1'"
  },
  {
    "code": "def get_binding(self, schema, data):\n        schema = self.parent.get_schema(schema)\n        return Binding(schema, self.parent.resolver, data=data)",
    "docstring": "For a given schema, get a binding mediator providing links to the\n        RDF terms matching that schema."
  },
  {
    "code": "def _add_remove_user_template(self, url, template_id, account_id=None, email_address=None):\n        if not email_address and not account_id:\n            raise HSException(\"No email address or account_id specified\")\n        data = {}\n        if account_id is not None:\n            data = {\n                \"account_id\": account_id\n            }\n        else:\n            data = {\n                \"email_address\": email_address\n            }\n        request = self._get_request()\n        response = request.post(url + template_id, data)\n        return response",
    "docstring": "Add or Remove user from a Template\n\n        We use this function for two tasks because they have the same API call\n\n        Args:\n\n            template_id (str):      The id of the template\n\n            account_id (str):       ID of the account to add/remove access to/from\n\n            email_address (str):    The email_address of the account to add/remove access to/from\n\n        Raises:\n            HSException: If no email address or account_id specified\n\n        Returns:\n            A Template object"
  },
  {
    "code": "def submissionfile_post_save(sender, instance, signal, created, **kwargs):\n    if created:\n        logger.debug(\"Running post-processing for new submission file.\")\n        instance.md5 = instance.attachment_md5()\n        instance.save()",
    "docstring": "Update MD5 field for newly uploaded files."
  },
  {
    "code": "def window_size(self, value):\n        if (value > 4 and\n            value < self.parameter_maxima[\"window_size\"] and\n            value % 2):\n            self._window_size = value\n        else:\n            raise InvalidWindowSizeError(\"Window size must be an odd number \"\n                                      \"between 0 and {}.\".format(\n                                      self.parameter_maxima[\"window_size\"] + 1))\n        self._replace_bm()",
    "docstring": "Set private ``_window_size`` and reset ``_block_matcher``."
  },
  {
    "code": "def _apply_decorator_to_methods(cls, decorator):\n        for method in cls.methods:\n            method_name = method.lower()\n            decorated_method_func = decorator(getattr(cls, method_name))\n            setattr(cls, method_name, decorated_method_func)",
    "docstring": "This helper can apply a given decorator to all methods on the current\n        Resource.\n\n        NOTE: In contrast to ``Resource.method_decorators``, which has a\n        similar use-case, this method applies decorators directly and override\n        methods in-place, while the decorators listed in\n        ``Resource.method_decorators`` are applied on every request which is\n        quite a waste of resources."
  },
  {
    "code": "def result_anything_found(result):\n    keys = ['version', 'themes', 'plugins', 'interesting urls']\n    anything_found = False\n    for k in keys:\n        if k not in result:\n            continue\n        else:\n            if not result[k]['is_empty']:\n                anything_found = True\n    return anything_found",
    "docstring": "Interim solution for the fact that sometimes determine_scanning_method can\n    legitimately return a valid scanning method, but it results that the site\n    does not belong to a particular CMS.\n    @param result: the result as passed to Output.result()\n    @return: whether anything was found."
  },
  {
    "code": "def create_order_keyword_list(keywords):\n    result = []\n    for keyword in keywords:\n        result.append((keyword, ''))\n        result.append(('-%s' % keyword, ''))\n    return result",
    "docstring": "Takes a given keyword list and returns a ready-to-go\n    list of possible ordering values.\n\n    Example: ['foo'] returns [('foo', ''), ('-foo', '')]"
  },
  {
    "code": "def import_object_ns(name_space, import_str, *args, **kwargs):\n    import_value = \"%s.%s\" % (name_space, import_str)\n    try:\n        return import_class(import_value)(*args, **kwargs)\n    except ImportError:\n        return import_class(import_str)(*args, **kwargs)",
    "docstring": "Tries to import object from default namespace.\n\n    Imports a class and return an instance of it, first by trying\n    to find the class in a default namespace, then failing back to\n    a full path if not found in the default namespace."
  },
  {
    "code": "def add_workflow_definitions(sbi_config: dict):\n    registered_workflows = []\n    for i in range(len(sbi_config['processing_blocks'])):\n        workflow_config = sbi_config['processing_blocks'][i]['workflow']\n        workflow_name = '{}:{}'.format(workflow_config['id'],\n                                       workflow_config['version'])\n        if workflow_name in registered_workflows:\n            continue\n        workflow_definition = dict(\n            id=workflow_config['id'],\n            version=workflow_config['version'],\n            stages=[]\n        )\n        key = \"workflow_definitions:{}:{}\".format(workflow_config['id'],\n                                                  workflow_config['version'])\n        DB.save_dict(key, workflow_definition, hierarchical=False)\n        registered_workflows.append(workflow_name)",
    "docstring": "Add any missing SBI workflow definitions as placeholders.\n\n    This is a utility function used in testing and adds mock / test workflow\n    definitions to the database for workflows defined in the specified\n    SBI config.\n\n    Args:\n        sbi_config (dict): SBI configuration dictionary."
  },
  {
    "code": "def map_cluster(events, cluster):\n    cluster = np.ascontiguousarray(cluster)\n    events = np.ascontiguousarray(events)\n    mapped_cluster = np.zeros((events.shape[0], ), dtype=dtype_from_descr(data_struct.ClusterInfoTable))\n    mapped_cluster = np.ascontiguousarray(mapped_cluster)\n    analysis_functions.map_cluster(events, cluster, mapped_cluster)\n    return mapped_cluster",
    "docstring": "Maps the cluster hits on events. Not existing hits in events have all values set to 0"
  },
  {
    "code": "def treeAggregate(self, zeroValue, seqOp, combOp, depth=2):\n        if depth < 1:\n            raise ValueError(\"Depth cannot be smaller than 1 but got %d.\" % depth)\n        if self.getNumPartitions() == 0:\n            return zeroValue\n        def aggregatePartition(iterator):\n            acc = zeroValue\n            for obj in iterator:\n                acc = seqOp(acc, obj)\n            yield acc\n        partiallyAggregated = self.mapPartitions(aggregatePartition)\n        numPartitions = partiallyAggregated.getNumPartitions()\n        scale = max(int(ceil(pow(numPartitions, 1.0 / depth))), 2)\n        while numPartitions > scale + numPartitions / scale:\n            numPartitions /= scale\n            curNumPartitions = int(numPartitions)\n            def mapPartition(i, iterator):\n                for obj in iterator:\n                    yield (i % curNumPartitions, obj)\n            partiallyAggregated = partiallyAggregated \\\n                .mapPartitionsWithIndex(mapPartition) \\\n                .reduceByKey(combOp, curNumPartitions) \\\n                .values()\n        return partiallyAggregated.reduce(combOp)",
    "docstring": "Aggregates the elements of this RDD in a multi-level tree\n        pattern.\n\n        :param depth: suggested depth of the tree (default: 2)\n\n        >>> add = lambda x, y: x + y\n        >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10)\n        >>> rdd.treeAggregate(0, add, add)\n        -5\n        >>> rdd.treeAggregate(0, add, add, 1)\n        -5\n        >>> rdd.treeAggregate(0, add, add, 2)\n        -5\n        >>> rdd.treeAggregate(0, add, add, 5)\n        -5\n        >>> rdd.treeAggregate(0, add, add, 10)\n        -5"
  },
  {
    "code": "def logout(self, refresh_token):\n        return self._realm.client.post(self.get_url('end_session_endpoint'),\n                                       data={\n                                           'refresh_token': refresh_token,\n                                           'client_id': self._client_id,\n                                           'client_secret': self._client_secret\n                                       })",
    "docstring": "The logout endpoint logs out the authenticated user.\n\n        :param str refresh_token:"
  },
  {
    "code": "def _insert_breathe_configs(c, *, project_name, doxygen_xml_dirname):\n    if doxygen_xml_dirname is not None:\n        c['breathe_projects'] = {project_name: doxygen_xml_dirname}\n        c['breathe_default_project'] = project_name\n    return c",
    "docstring": "Add breathe extension configurations to the state."
  },
  {
    "code": "def runSearchReadGroupSets(self, request):\n        return self.runSearchRequest(\n            request, protocol.SearchReadGroupSetsRequest,\n            protocol.SearchReadGroupSetsResponse,\n            self.readGroupSetsGenerator)",
    "docstring": "Runs the specified SearchReadGroupSetsRequest."
  },
  {
    "code": "def ip_in_ip_mask(ip, mask_ip, mask):\n    ip = ip2hex(ip)\n    if ip is None: raise Exception(\"bad ip format\")\n    if (mask_ip & mask) == (ip & mask):\n        return True\n    return False",
    "docstring": "Checks whether an ip is contained in an ip subnet where the subnet is stated as an ip in the dotted format, and a hex mask"
  },
  {
    "code": "def push_resource_cache(resourceid, info):\n        if not resourceid:\n            raise ResourceInitError(\"Resource id missing\")\n        if not DutInformationList._cache.get(resourceid):\n            DutInformationList._cache[resourceid] = dict()\n        DutInformationList._cache[resourceid] = merge(DutInformationList._cache[resourceid], info)",
    "docstring": "Cache resource specific information\n\n        :param resourceid: Resource id as string\n        :param info: Dict to push\n        :return: Nothing"
  },
  {
    "code": "def add_host(host):\n    p = new_prefix()\n    p.prefix = str(host['ipaddr'])\n    p.type = \"host\"\n    p.description = host['description']\n    p.node = host['fqdn']\n    p.avps = {}\n    if 'additional' in host:\n        p.comment = host['additional']\n    if len(host['location']) > 0:\n        p.avps['location'] = host['location']\n    if len(host['mac']) > 0:\n        p.avps['mac'] = host['mac']\n    if len(host['phone']) > 0:\n        p.avps['phone'] = host['phone']\n    if len(host['user']) > 0:\n        p.avps['user'] = host['user']\n    return p",
    "docstring": "Put your host information in the prefix object."
  },
  {
    "code": "def clean_session_table():\n    sessions = SessionActivity.query_by_expired().all()\n    for session in sessions:\n        delete_session(sid_s=session.sid_s)\n    db.session.commit()",
    "docstring": "Automatically clean session table.\n\n    To enable a periodically clean of the session table, you should configure\n    the task as a celery periodic task.\n\n    .. code-block:: python\n\n        from datetime import timedelta\n        CELERYBEAT_SCHEDULE = {\n            'session_cleaner': {\n                'task': 'invenio_accounts.tasks.clean_session_table',\n                'schedule': timedelta(days=1),\n            },\n        }\n\n    See `Invenio-Celery <https://invenio-celery.readthedocs.io/>`_\n    documentation for further details."
  },
  {
    "code": "def __read_docker_compose_file(file_path):\n    if not os.path.isfile(file_path):\n        return __standardize_result(False,\n                                    'Path {} is not present'.format(file_path),\n                                    None, None)\n    try:\n        with salt.utils.files.fopen(file_path, 'r') as fl:\n            file_name = os.path.basename(file_path)\n            result = {file_name: ''}\n            for line in fl:\n                result[file_name] += salt.utils.stringutils.to_unicode(line)\n    except EnvironmentError:\n        return __standardize_result(False,\n                                    'Could not read {0}'.format(file_path),\n                                    None, None)\n    return __standardize_result(True,\n                                'Reading content of {0}'.format(file_path),\n                                result, None)",
    "docstring": "Read the compose file if it exists in the directory\n\n    :param file_path:\n    :return:"
  },
  {
    "code": "def get_file_hash( fd, hashfunc, fd_len=None ):\n    h = hashfunc()\n    fd.seek(0, os.SEEK_SET)\n    count = 0\n    while True:\n        buf = fd.read(65536)\n        if len(buf) == 0:\n            break\n        if fd_len is not None:\n            if count + len(buf) > fd_len:\n                buf = buf[:fd_len - count]\n        h.update(buf)\n        count += len(buf)\n    hashed = h.hexdigest()\n    return hashed",
    "docstring": "Get the hex-encoded hash of the fd's data"
  },
  {
    "code": "def get_contents_sig(self):\n        try:\n            return self.contentsig\n        except AttributeError:\n            pass\n        executor = self.get_executor()\n        result = self.contentsig = SCons.Util.MD5signature(executor.get_contents())\n        return result",
    "docstring": "A helper method for get_cachedir_bsig.\n\n        It computes and returns the signature for this\n        node's contents."
  },
  {
    "code": "def _sge_info(queue):\n    qhost_out = subprocess.check_output([\"qhost\", \"-q\", \"-xml\"]).decode()\n    qstat_queue = [\"-q\", queue] if queue and \",\" not in queue else []\n    qstat_out = subprocess.check_output([\"qstat\", \"-f\", \"-xml\"] + qstat_queue).decode()\n    slot_info = _sge_get_slots(qstat_out)\n    mem_info = _sge_get_mem(qhost_out, queue)\n    machine_keys = slot_info.keys()\n    mem_per_slot = [mem_info[x][\"mem_total\"] / float(slot_info[x][\"slots_total\"]) for x in machine_keys]\n    min_ratio_index = mem_per_slot.index(median_left(mem_per_slot))\n    mem_info[machine_keys[min_ratio_index]][\"mem_total\"]\n    return [{\"cores\": slot_info[machine_keys[min_ratio_index]][\"slots_total\"],\n             \"memory\": mem_info[machine_keys[min_ratio_index]][\"mem_total\"],\n             \"name\": \"sge_machine\"}]",
    "docstring": "Returns machine information for an sge job scheduler."
  },
  {
    "code": "def from_dict(cls, metadata):\n        hyperparameters = metadata.get('hyperparameters')\n        tunable = metadata.get('tunable_hyperparameters')\n        pipeline = cls(\n            metadata['primitives'],\n            metadata.get('init_params'),\n            metadata.get('input_names'),\n            metadata.get('output_names'),\n        )\n        if hyperparameters:\n            pipeline.set_hyperparameters(hyperparameters)\n        if tunable is not None:\n            pipeline._tunable_hyperparameters = tunable\n        return pipeline",
    "docstring": "Create a new MLPipeline from a dict specification.\n\n        The dict structure is the same as the one created by the `to_dict` method.\n\n        Args:\n            metadata (dict): Dictionary containing the pipeline specification.\n\n        Returns:\n            MLPipeline:\n                A new MLPipeline instance with the details found in the\n                given specification dictionary."
  },
  {
    "code": "def send_quick_chat_from_agent(self, team_only, quick_chat):\n        rlbot_status = send_quick_chat_flat(self.game_interface, self.index, self.team, team_only, quick_chat)\n        if rlbot_status == RLBotCoreStatus.QuickChatRateExceeded:\n            self.logger.debug('quick chat disabled')\n        else:\n            send_quick_chat(self.quick_chat_queue_holder, self.index, self.team, team_only, quick_chat)",
    "docstring": "Passes the agents quick chats to the game, and also to other python bots.\n        This does perform limiting.\n        You are limited to 5 quick chats in a 2 second period starting from the first chat.\n        This means you can spread your chats out to be even within that 2 second period.\n        You could spam them in the first little bit but then will be throttled."
  },
  {
    "code": "def get_user_stats(self, name):\n        req = self.conn.get(BASE_URL + \"/user/\" + name)\n        if req.status_code != 200 or not name:\n            return None\n        return self.conn.make_api_call(\"getUserInfo\", {\"name\": name})",
    "docstring": "Return data about the given user. Returns None if user\n        does not exist."
  },
  {
    "code": "def apns_send_bulk_message(\n\tregistration_ids, alert, application_id=None, certfile=None, **kwargs\n):\n\tresults = _apns_send(\n\t\tregistration_ids, alert, batch=True, application_id=application_id,\n\t\tcertfile=certfile, **kwargs\n\t)\n\tinactive_tokens = [token for token, result in results.items() if result == \"Unregistered\"]\n\tmodels.APNSDevice.objects.filter(registration_id__in=inactive_tokens).update(active=False)\n\treturn results",
    "docstring": "Sends an APNS notification to one or more registration_ids.\n\tThe registration_ids argument needs to be a list.\n\n\tNote that if set alert should always be a string. If it is not set,\n\tit won\"t be included in the notification. You will need to pass None\n\tto this for silent notifications."
  },
  {
    "code": "def convert_transpose(net, node, module, builder):\n    input_name, output_name = _get_input_output_name(net, node)\n    name = node['name']\n    param = _get_attrs(node)\n    axes = literal_eval(param['axes'])\n    builder.add_permute(name, axes, input_name, output_name)",
    "docstring": "Convert a transpose layer from mxnet to coreml.\n\n    Parameters\n    ----------\n    network: net\n        A mxnet network object.\n\n    layer: node\n        Node to convert.\n\n    module: module\n        An module for MXNet\n\n    builder: NeuralNetworkBuilder\n        A neural network builder object."
  },
  {
    "code": "def rectangle_centroid(rectangle):\n    bbox = rectangle['coordinates'][0]\n    xmin = bbox[0][0]\n    ymin = bbox[0][1]\n    xmax = bbox[2][0]\n    ymax = bbox[2][1]\n    xwidth = xmax - xmin\n    ywidth = ymax - ymin\n    return {'type': 'Point', 'coordinates': [xmin + xwidth / 2, ymin + ywidth / 2]}",
    "docstring": "get the centroid of the rectangle\n\n    Keyword arguments:\n    rectangle  -- polygon geojson object\n\n    return centroid"
  },
  {
    "code": "def configure_logger(self):\n        logger_name = 'brome_runner'\n        self.logger = logging.getLogger(logger_name)\n        format_ = BROME_CONFIG['logger_runner']['format']\n        if BROME_CONFIG['logger_runner']['streamlogger']:\n            sh = logging.StreamHandler()\n            stream_formatter = logging.Formatter(format_)\n            sh.setFormatter(stream_formatter)\n            self.logger.addHandler(sh)\n        if BROME_CONFIG['logger_runner']['filelogger'] and \\\n                self.runner_dir:\n            self.log_file_path = os.path.join(\n                    self.runner_dir,\n                    '%s.log' % logger_name\n            )\n            self.relative_log_file_path = os.path.join(\n                    self.relative_runner_dir,\n                    '%s.log' % logger_name\n            )\n            fh = logging.FileHandler(\n                self.log_file_path\n            )\n            file_formatter = logging.Formatter(format_)\n            fh.setFormatter(file_formatter)\n            self.logger.addHandler(fh)\n        self.logger.setLevel(\n            getattr(\n                logging,\n                BROME_CONFIG['logger_runner']['level']\n                )\n            )",
    "docstring": "Configure the test batch runner logger"
  },
  {
    "code": "def has_pending(self):\n        if self.workqueue:\n            return True\n        for assigned_unit in self.assigned_work.values():\n            if self._pending_of(assigned_unit) > 0:\n                return True\n        return False",
    "docstring": "Return True if there are pending test items.\n\n        This indicates that collection has finished and nodes are still\n        processing test items, so this can be thought of as\n        \"the scheduler is active\"."
  },
  {
    "code": "def command(self, details):\n        log = self._params.get('log', self._discard)\n        if '_config_running' not in dir(self._parent) or 'commands' not in self._parent._config_running:\n            log.error(\"Event parent '%s' has no 'commands' config section\", self._name)\n            return\n        commands = self._parent._config_running['commands']\n        if self._handler_arg not in commands:\n            if self._handler_arg == 'stop':\n                self._parent.stop()\n            else:\n                log.error(\"Event parent '%s' has no '%s' command configured\", self._name, self._handler_arg)\n            return\n        pid = _exec_process(commands[self._handler_arg], self._parent._context, log=log)\n        log.info(\"Forked pid %d for %s(%s)\", pid, self._name, self._handler_arg)\n        self._parent._legion.proc_add(event_target(self._parent, 'command_exit', key=pid, arg=self._handler_arg, log=log))",
    "docstring": "Handles executing a command-based event.  This starts the command\n        as specified in the 'commands' section of the task config.\n\n        A separate event is registered to handle the command exit.  This\n        simply logs the exit status."
  },
  {
    "code": "def message_info(exchange, routing_key, properties):\n    output = []\n    if properties.message_id:\n        output.append(properties.message_id)\n    if properties.correlation_id:\n        output.append('[correlation_id=\"{}\"]'.format(\n            properties.correlation_id))\n    if exchange:\n        output.append('published to \"{}\"'.format(exchange))\n    if routing_key:\n        output.append('using \"{}\"'.format(routing_key))\n    return ' '.join(output)",
    "docstring": "Return info about a message using the same conditional constructs\n\n    :param str exchange: The exchange the message was published to\n    :param str routing_key: The routing key used\n    :param properties: The AMQP message properties\n    :type properties: pika.spec.Basic.Properties\n    :rtype: str"
  },
  {
    "code": "def create_chat(self, blogname, **kwargs):\n        kwargs.update({\"type\": \"chat\"})\n        return self._send_post(blogname, kwargs)",
    "docstring": "Create a chat post on a blog\n\n        :param blogname: a string, the url of the blog you want to post to.\n        :param state: a string, The state of the post.\n        :param tags: a list of tags that you want applied to the post\n        :param tweet: a string, the customized tweet that you want\n        :param date: a string, the GMT date and time of the post\n        :param format: a string, sets the format type of the post. html or markdown\n        :param slug: a string, a short text summary to the end of the post url\n        :param title: a string, the title of the conversation\n        :param conversation: a string, the conversation you are posting\n\n        :returns: a dict created from the JSON response"
  },
  {
    "code": "def save_map(self, map_path, map_data):\n    return self._client.send(save_map=sc_pb.RequestSaveMap(\n        map_path=map_path, map_data=map_data))",
    "docstring": "Save a map into temp dir so create game can access it in multiplayer."
  },
  {
    "code": "def _tokens_to_subtoken_ids(self, tokens):\n    ret = []\n    for token in tokens:\n      ret.extend(self._token_to_subtoken_ids(token))\n    return ret",
    "docstring": "Converts a list of tokens to a list of subtoken ids.\n\n    Args:\n      tokens: a list of strings.\n    Returns:\n      a list of integers in the range [0, vocab_size)"
  },
  {
    "code": "def yaml_encode(data):\n    yrepr = yaml.representer.SafeRepresenter()\n    ynode = yrepr.represent_data(data)\n    if not isinstance(ynode, yaml.ScalarNode):\n        raise TypeError(\n            \"yaml_encode() only works with YAML scalar data;\"\n            \" failed for {0}\".format(type(data))\n        )\n    tag = ynode.tag.rsplit(':', 1)[-1]\n    ret = ynode.value\n    if tag == \"str\":\n        ret = yaml_dquote(ynode.value)\n    return ret",
    "docstring": "A simple YAML encode that can take a single-element datatype and return\n    a string representation."
  },
  {
    "code": "def get_register(self, cpu_id, name):\n        if not isinstance(cpu_id, baseinteger):\n            raise TypeError(\"cpu_id can only be an instance of type baseinteger\")\n        if not isinstance(name, basestring):\n            raise TypeError(\"name can only be an instance of type basestring\")\n        value = self._call(\"getRegister\",\n                     in_p=[cpu_id, name])\n        return value",
    "docstring": "Gets one register.\n\n        in cpu_id of type int\n            The identifier of the Virtual CPU.\n\n        in name of type str\n            The register name, case is ignored.\n\n        return value of type str\n            The register value. This is usually a hex value (always 0x prefixed)\n            but other format may be used for floating point registers (TBD)."
  },
  {
    "code": "def console_get_height_rect(\n    con: tcod.console.Console, x: int, y: int, w: int, h: int, fmt: str\n) -> int:\n    return int(\n        lib.TCOD_console_get_height_rect_fmt(\n            _console(con), x, y, w, h, _fmt(fmt)\n        )\n    )",
    "docstring": "Return the height of this text once word-wrapped into this rectangle.\n\n    Returns:\n        int: The number of lines of text once word-wrapped.\n\n    .. deprecated:: 8.5\n        Use :any:`Console.get_height_rect` instead."
  },
  {
    "code": "def _chunkForSend(self, data):\n        LIMIT = self.CHUNK_LIMIT\n        for i in range(0, len(data), LIMIT):\n            yield data[i:i + LIMIT]",
    "docstring": "limit the chunks that we send over PB to 128k, since it has a hardwired\n        string-size limit of 640k."
  },
  {
    "code": "def get_password(hsm, args):\n    expected_len = 32\n    name = 'HSM password'\n    if hsm.version.have_key_store_decrypt():\n        expected_len = 64\n        name = 'master key'\n    if args.stdin:\n        password = sys.stdin.readline()\n        while password and password[-1] == '\\n':\n            password = password[:-1]\n    else:\n        if args.debug:\n            password = raw_input('Enter %s (press enter to skip) (will be echoed) : ' % (name))\n        else:\n            password = getpass.getpass('Enter %s (press enter to skip) : ' % (name))\n    if len(password) <= expected_len:\n        password = password.decode('hex')\n        if not password:\n            return None\n        return password\n    else:\n        sys.stderr.write(\"ERROR: Invalid HSM password (expected max %i chars, got %i)\\n\" % \\\n                              (expected_len, len(password)))\n        return 1",
    "docstring": "Get password of correct length for this YubiHSM version."
  },
  {
    "code": "def filter_lines_from_comments(lines):\n    for line_nb, raw_line in enumerate(lines):\n        clean_line = remove_comments_from_line(raw_line)\n        if clean_line == '':\n            continue\n        yield line_nb, clean_line, raw_line",
    "docstring": "Filter the lines from comments and non code lines."
  },
  {
    "code": "def get_word_app ():\n    if not has_word():\n        return None\n    pythoncom.CoInitialize()\n    import win32com.client\n    app = win32com.client.gencache.EnsureDispatch(\"Word.Application\")\n    app.Visible = False\n    return app",
    "docstring": "Return open Word.Application handle, or None if Word is not available\n    on this system."
  },
  {
    "code": "def list_queries(self, **kwargs):\n        kwargs = self._verify_sort_options(kwargs)\n        kwargs = self._verify_filters(kwargs, Query, True)\n        api = self._get_api(device_directory.DefaultApi)\n        return PaginatedResponse(api.device_query_list, lwrap_type=Query, **kwargs)",
    "docstring": "List queries in device query service.\n\n        :param int limit: The number of devices to retrieve.\n        :param str order: The ordering direction, ascending (asc) or\n            descending (desc)\n        :param str after: Get devices after/starting at given `device_id`\n        :param filters: Dictionary of filters to apply.\n        :returns: a list of :py:class:`Query` objects.\n        :rtype: PaginatedResponse"
  },
  {
    "code": "def copy(self, dst_bucket, dst_key, metadata=None,\n             reduced_redundancy=False, preserve_acl=False,\n             encrypt_key=False):\n        dst_bucket = self.bucket.connection.lookup(dst_bucket)\n        if reduced_redundancy:\n            storage_class = 'REDUCED_REDUNDANCY'\n        else:\n            storage_class = self.storage_class\n        return dst_bucket.copy_key(dst_key, self.bucket.name,\n                                   self.name, metadata,\n                                   storage_class=storage_class,\n                                   preserve_acl=preserve_acl,\n                                   encrypt_key=encrypt_key)",
    "docstring": "Copy this Key to another bucket.\n\n        :type dst_bucket: string\n        :param dst_bucket: The name of the destination bucket\n\n        :type dst_key: string\n        :param dst_key: The name of the destination key\n\n        :type metadata: dict\n        :param metadata: Metadata to be associated with new key.\n                         If metadata is supplied, it will replace the\n                         metadata of the source key being copied.\n                         If no metadata is supplied, the source key's\n                         metadata will be copied to the new key.\n\n        :type reduced_redundancy: bool\n        :param reduced_redundancy: If True, this will force the storage\n                                   class of the new Key to be\n                                   REDUCED_REDUNDANCY regardless of the\n                                   storage class of the key being copied.\n                                   The Reduced Redundancy Storage (RRS)\n                                   feature of S3, provides lower\n                                   redundancy at lower storage cost.\n\n        :type preserve_acl: bool\n        :param preserve_acl: If True, the ACL from the source key\n                             will be copied to the destination\n                             key.  If False, the destination key\n                             will have the default ACL.\n                             Note that preserving the ACL in the\n                             new key object will require two\n                             additional API calls to S3, one to\n                             retrieve the current ACL and one to\n                             set that ACL on the new object.  If\n                             you don't care about the ACL, a value\n                             of False will be significantly more\n                             efficient.\n\n        :type encrypt_key: bool\n        :param encrypt_key: If True, the new copy of the object will\n                            be encrypted on the server-side by S3 and\n                            will be stored in an encrypted form while\n                            at rest in S3.\n                            \n        :rtype: :class:`boto.s3.key.Key` or subclass\n        :returns: An instance of the newly created key object"
  },
  {
    "code": "def streaming_recognize(\n        self,\n        config,\n        requests,\n        retry=google.api_core.gapic_v1.method.DEFAULT,\n        timeout=google.api_core.gapic_v1.method.DEFAULT,\n    ):\n        return super(SpeechHelpers, self).streaming_recognize(\n            self._streaming_request_iterable(config, requests),\n            retry=retry,\n            timeout=timeout,\n        )",
    "docstring": "Perform bi-directional speech recognition.\n\n        This method allows you to receive results while sending audio;\n        it is only available via. gRPC (not REST).\n\n        .. warning::\n\n            This method is EXPERIMENTAL. Its interface might change in the\n            future.\n\n        Example:\n          >>> from google.cloud.speech_v1 import enums\n          >>> from google.cloud.speech_v1 import SpeechClient\n          >>> from google.cloud.speech_v1 import types\n          >>> client = SpeechClient()\n          >>> config = types.StreamingRecognitionConfig(\n          ...     config=types.RecognitionConfig(\n          ...         encoding=enums.RecognitionConfig.AudioEncoding.FLAC,\n          ...     ),\n          ... )\n          >>> request = types.StreamingRecognizeRequest(audio_content=b'...')\n          >>> requests = [request]\n          >>> for element in client.streaming_recognize(config, requests):\n          ...     # process element\n          ...     pass\n\n        Args:\n            config (:class:`~.types.StreamingRecognitionConfig`): The\n                configuration to use for the stream.\n            requests (Iterable[:class:`~.types.StreamingRecognizeRequest`]):\n                The input objects.\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n\n        Returns:\n          Iterable[:class:`~.types.StreamingRecognizeResponse`]\n\n        Raises:\n          :exc:`google.gax.errors.GaxError` if the RPC is aborted.\n          :exc:`ValueError` if the parameters are invalid."
  },
  {
    "code": "def respond_to_SIGHUP(signal_number, frame, logger=None):\n    global restart\n    restart = True\n    if logger:\n        logger.info('detected SIGHUP')\n    raise KeyboardInterrupt",
    "docstring": "raise the KeyboardInterrupt which will cause the app to effectively\n    shutdown, closing all it resources.  Then, because it sets 'restart' to\n    True, the app will reread all the configuration information, rebuild all\n    of its structures and resources and start running again"
  },
  {
    "code": "def parse_table_column_properties(doc, cell, prop):\n    \"Parse table column properties.\"\n    if not cell:\n        return\n    grid = prop.find(_name('{{{w}}}gridSpan'))\n    if grid is not None:\n        cell.grid_span = int(grid.attrib[_name('{{{w}}}val')])\n    vmerge = prop.find(_name('{{{w}}}vMerge'))\n    if vmerge is not None:\n        if _name('{{{w}}}val') in vmerge.attrib:\n            cell.vmerge = vmerge.attrib[_name('{{{w}}}val')]\n        else:\n            cell.vmerge = \"\"",
    "docstring": "Parse table column properties."
  },
  {
    "code": "def store_many_vectors(self, hash_name, bucket_keys, vs, data):\n        if data is None:\n            data = itertools.repeat(data)\n        for v, k, d in zip(vs, bucket_keys, data):\n            self.store_vector(hash_name, k, v, d)",
    "docstring": "Store a batch of vectors.\n        Stores vector and JSON-serializable data in bucket with specified key."
  },
  {
    "code": "def set_connection(connection=defaults.sqlalchemy_connection_string_default):\n    cfp = defaults.config_file_path\n    config = RawConfigParser()\n    if not os.path.exists(cfp):\n        with open(cfp, 'w') as config_file:\n            config['database'] = {'sqlalchemy_connection_string': connection}\n            config.write(config_file)\n            log.info('create configuration file %s', cfp)\n    else:\n        config.read(cfp)\n        config.set('database', 'sqlalchemy_connection_string', connection)\n        with open(cfp, 'w') as configfile:\n            config.write(configfile)",
    "docstring": "Set the connection string for SQLAlchemy\n\n    :param str connection: SQLAlchemy connection string"
  },
  {
    "code": "async def connection_exists(ssid: str) -> Optional[str]:\n    nmcli_conns = await connections()\n    for wifi in [c['name']\n                 for c in nmcli_conns if c['type'] == 'wireless']:\n        res, _ = await _call(['-t', '-f', '802-11-wireless.ssid',\n                              '-m', 'tabular',\n                              'connection', 'show', wifi])\n        if res == ssid:\n            return wifi\n    return None",
    "docstring": "If there is already a connection for this ssid, return the name of\n    the connection; if there is not, return None."
  },
  {
    "code": "def _GetConnectionArgs(host=None,\n                       port=None,\n                       user=None,\n                       password=None,\n                       database=None,\n                       client_key_path=None,\n                       client_cert_path=None,\n                       ca_cert_path=None):\n  connection_args = dict(\n      autocommit=False, use_unicode=True, charset=CHARACTER_SET)\n  if host is not None:\n    connection_args[\"host\"] = host\n  if port is not None:\n    connection_args[\"port\"] = port\n  if user is not None:\n    connection_args[\"user\"] = user\n  if password is not None:\n    connection_args[\"passwd\"] = password\n  if database is not None:\n    connection_args[\"db\"] = database\n  if client_key_path is not None:\n    connection_args[\"ssl\"] = {\n        \"key\": client_key_path,\n        \"cert\": client_cert_path,\n        \"ca\": ca_cert_path,\n    }\n  return connection_args",
    "docstring": "Builds connection arguments for MySQLdb.Connect function."
  },
  {
    "code": "def union(self, other):\n        if isinstance(other, tuple):\n            other = list(other)\n        return type(self)(super().__add__(other))",
    "docstring": "Returns a FrozenList with other concatenated to the end of self.\n\n        Parameters\n        ----------\n        other : array-like\n            The array-like whose elements we are concatenating.\n\n        Returns\n        -------\n        diff : FrozenList\n            The collection difference between self and other."
  },
  {
    "code": "def copy_and_sum_families(family_source, family_target):\n    for every in family_source:\n        if every not in family_target:\n            family_target[every] = family_source[every]\n        else:\n            family_target[every] += family_source[every]",
    "docstring": "methods iterates thru source family and copies its entries to target family\n    in case key already exists in both families - then the values are added"
  },
  {
    "code": "def safestr(str_):\n    str_ = str_ or \"\"\n    return \"\".join(x for x in str_ if x.isalnum())",
    "docstring": "get back an alphanumeric only version of source"
  },
  {
    "code": "def get_temp_url(self, obj, seconds, method=\"GET\", key=None, cached=True):\n        return self.manager.get_temp_url(self, obj, seconds, method=method,\n                key=key, cached=cached)",
    "docstring": "Given a storage object in this container, returns a URL that can be\n        used to access that object. The URL will expire after `seconds`\n        seconds.\n\n        The only methods supported are GET and PUT. Anything else will raise an\n        `InvalidTemporaryURLMethod` exception.\n\n        If you have your Temporary URL key, you can pass it in directly and\n        potentially save an API call to retrieve it. If you don't pass in the\n        key, and don't wish to use any cached value, pass `cached=False`."
  },
  {
    "code": "def get_theming_attribute(self, mode, name, part=None):\n        colours = int(self._config.get('colourmode'))\n        return self._theme.get_attribute(colours, mode, name, part)",
    "docstring": "looks up theming attribute\n\n        :param mode: ui-mode (e.g. `search`,`thread`...)\n        :type mode: str\n        :param name: identifier of the atttribute\n        :type name: str\n        :rtype: urwid.AttrSpec"
  },
  {
    "code": "def do_list_organizations(self, line):\n        org_list = self.dcnm_client.list_organizations()\n        if not org_list:\n            print('No organization found.')\n            return\n        org_table = PrettyTable(['Organization Name'])\n        for org in org_list:\n            org_table.add_row([org['organizationName']])\n        print(org_table)",
    "docstring": "Get list of organization on DCNM."
  },
  {
    "code": "def clone(cls, objective, model=None, **kwargs):\n        return cls(cls._substitute_variables(objective, model=model), name=objective.name,\n                   direction=objective.direction, sloppy=True, **kwargs)",
    "docstring": "Make a copy of an objective. The objective being copied can be of the same type or belong to\n        a different solver interface.\n\n        Example\n        ----------\n        >>> new_objective = Objective.clone(old_objective)"
  },
  {
    "code": "def get_available_translations():\r\n    locale_path = get_module_data_path(\"spyder\", relpath=\"locale\",\r\n                                       attr_name='LOCALEPATH')\r\n    listdir = os.listdir(locale_path)\r\n    langs = [d for d in listdir if osp.isdir(osp.join(locale_path, d))]\r\n    langs = [DEFAULT_LANGUAGE] + langs\r\n    langs = list( set(langs) - set(DISABLED_LANGUAGES) )\r\n    for lang in langs:\r\n        if lang not in LANGUAGE_CODES:\r\n            error = ('Update LANGUAGE_CODES (inside config/base.py) if a new '\r\n                     'translation has been added to Spyder')\r\n            print(error)\n            return ['en']\r\n    return langs",
    "docstring": "List available translations for spyder based on the folders found in the\r\n    locale folder. This function checks if LANGUAGE_CODES contain the same\r\n    information that is found in the 'locale' folder to ensure that when a new\r\n    language is added, LANGUAGE_CODES is updated."
  },
  {
    "code": "def html_to_tags(code):\n    code = ('<div>' + code + '</div>').encode('utf8')\n    el = ET.fromstring(code)\n    return [tag_from_element(c) for c in el]",
    "docstring": "Convert HTML code to tags.\n\n    ``code`` is a string containing HTML code. The return value is a\n    list of corresponding instances of ``TagBase``."
  },
  {
    "code": "def run_recipe_timed(task, recipe, rinput):\n    _logger.info('running recipe')\n    now1 = datetime.datetime.now()\n    task.state = 1\n    task.time_start = now1\n    result = recipe(rinput)\n    _logger.info('result: %r', result)\n    task.result = result\n    now2 = datetime.datetime.now()\n    task.state = 2\n    task.time_end = now2\n    return task",
    "docstring": "Run the recipe and count the time it takes."
  },
  {
    "code": "def parse_group(cls, group, lines, dist=None):\n        if not MODULE(group):\n            raise ValueError(\"Invalid group name\", group)\n        this = {}\n        for line in yield_lines(lines):\n            ep = cls.parse(line, dist)\n            if ep.name in this:\n                raise ValueError(\"Duplicate entry point\", group, ep.name)\n            this[ep.name] = ep\n        return this",
    "docstring": "Parse an entry point group"
  },
  {
    "code": "def set_menu(self, menu):\n        self.menu = menu\n        wx_menu = menu.wx_menu()\n        self.frame.SetMenuBar(wx_menu)\n        self.frame.Bind(wx.EVT_MENU, self.on_menu)",
    "docstring": "add a menu from the parent"
  },
  {
    "code": "def infer(self, sensationList, reset=True, objectName=None):\n    self._unsetLearningMode()\n    statistics = collections.defaultdict(list)\n    if objectName is not None:\n      if objectName not in self.objectRepresentationsL2:\n        raise ValueError(\"The provided objectName was not given during\"\n                         \" learning\")\n    for sensations in sensationList:\n      for col in xrange(self.numColumns):\n        location, coarseFeature, fineFeature = sensations[col]\n        self.locationInputs[col].addDataToQueue(list(location), 0, 0)\n        self.coarseSensors[col].addDataToQueue(list(coarseFeature), 0, 0)\n        self.sensors[col].addDataToQueue(list(fineFeature), 0, 0)\n      self.network.run(1)\n      self._updateInferenceStats(statistics, objectName)\n    if reset:\n      self._sendReset()\n    statistics[\"numSteps\"] = len(sensationList)\n    statistics[\"object\"] = objectName if objectName is not None else \"Unknown\"\n    self.statistics.append(statistics)",
    "docstring": "Infer on a given set of sensations for a single object.\n\n    The provided sensationList is a list of sensations, and each sensation is a\n    mapping from cortical column to a tuple of three SDR's respectively\n    corresponding to the locationInput, the coarseSensorInput, and the\n    sensorInput.\n\n    For example, the input can look as follows, if we are inferring a simple\n    object with two sensations (with very few active bits for simplicity):\n\n    sensationList = [\n        {\n          # location, coarse feature, fine feature for CC0, sensation 1\n          0: ( [1, 5, 10], [9, 32, 75], [6, 12, 52] ),\n          # location, coarse feature, fine feature for CC1, sensation 1\n          1: ( [6, 2, 15], [11, 42, 92], [7, 11, 50] ),\n        },\n        {\n          # location, coarse feature, fine feature for CC0, sensation 2\n          0: ( [2, 9, 10], [10, 35, 78], [6, 12, 52] ),\n          # location, coarse feature, fine feature for CC1, sensation 2\n          1: ( [1, 4, 12], [10, 32, 52], [6, 10, 52] ),\n        },\n    ]\n\n    If the object is known by the caller, an object name can be specified\n    as an optional argument, and must match the objects given while learning.\n    This is used later when evaluating inference statistics.\n\n    Parameters:\n    ----------------------------\n    @param   objects (dict)\n             Objects to learn, in the canonical format specified above\n\n    @param   reset (bool)\n             If set to True (which is the default value), the network will\n             be reset after learning.\n\n    @param   objectName (str)\n             Name of the objects (must match the names given during learning)."
  },
  {
    "code": "def update_devices(self, devices):\n        for qspacket in devices:\n            try:\n                qsid = qspacket[QS_ID]\n            except KeyError:\n                _LOGGER.debug(\"Device without ID: %s\", qspacket)\n                continue\n            if qsid not in self:\n                self[qsid] = QSDev(data=qspacket)\n            dev = self[qsid]\n            dev.data = qspacket\n            newqs = _legacy_status(qspacket[QS_VALUE])\n            if dev.is_dimmer:\n                newqs = min(round(math.pow(newqs, self.dim_adj)), 100)\n            newin = round(newqs * _MAX / 100)\n            if abs(dev.value - newin) > 1:\n                _LOGGER.debug(\"%s qs=%s  -->  %s\", qsid, newqs, newin)\n                dev.value = newin\n                self._cb_value_changed(self, qsid, newin)",
    "docstring": "Update values from response of URL_DEVICES, callback if changed."
  },
  {
    "code": "def pin_assets(self, file_or_dir_path: Path) -> List[Dict[str, str]]:\n        if file_or_dir_path.is_dir():\n            asset_data = [dummy_ipfs_pin(path) for path in file_or_dir_path.glob(\"*\")]\n        elif file_or_dir_path.is_file():\n            asset_data = [dummy_ipfs_pin(file_or_dir_path)]\n        else:\n            raise FileNotFoundError(\n                f\"{file_or_dir_path} is not a valid file or directory path.\"\n            )\n        return asset_data",
    "docstring": "Return a dict containing the IPFS hash, file name, and size of a file."
  },
  {
    "code": "def delete_telnet_template(auth, url, template_name= None, template_id= None):\n    try:\n        if template_id is None:\n            telnet_templates = get_telnet_template(auth, url)\n            if template_name is None:\n                template_name = telnet_template['name']\n            template_id = None\n            for template in telnet_templates:\n                if template['name'] == template_name:\n                    template_id = template['id']\n        f_url = url + \"/imcrs/plat/res/telnet/%s/delete\" % template_id\n        response = requests.delete(f_url, auth=auth, headers=HEADERS)\n        return response.status_code\n    except requests.exceptions.RequestException as error:\n        return \"Error:\\n\" + str(error) + \" delete_telnet_template: An Error has occured\"",
    "docstring": "Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific\n    telnet template from the IMC system\n\n    :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class\n\n    :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass\n\n    :param template_name: str value of template name\n\n    :param template_id: str value template template_id value\n\n    :return: int HTTP response code\n\n    :rtype  int"
  },
  {
    "code": "def solve(self):\n        Xi = self.cbpdn.solve()\n        self.timer = self.cbpdn.timer\n        self.itstat = self.cbpdn.itstat\n        return Xi",
    "docstring": "Call the solve method of the inner cbpdn object and return the\n        result."
  },
  {
    "code": "def get_templates(self, id_or_uri, start=0, count=-1, filter='', query='', sort=''):\n        uri = self._client.build_uri(id_or_uri) + \"/templates\"\n        return self._client.get(self._client.build_query_uri(start=start, count=count, filter=filter,\n                                                             query=query, sort=sort, uri=uri))",
    "docstring": "Gets a list of volume templates. Returns a list of storage templates belonging to the storage system.\n\n        Returns:\n            list: Storage Template List."
  },
  {
    "code": "def setProperty(self, name, value):\n        styleDict = self._styleDict\n        if value in ('', None):\n            try:\n                del styleDict[name]\n            except KeyError:\n                pass\n        else:\n            styleDict[name] = str(value)",
    "docstring": "setProperty - Set a style property to a value.\n\n                NOTE: To remove a style, use a value of empty string, or None\n\n                 @param name <str> - The style name.\n\n                    NOTE: The dash names are expected here, whereas dot-access expects the camel case names.\n\n                      Example:  name=\"font-weight\"  versus the dot-access  style.fontWeight\n\n                 @param value <str> - The style value, or empty string to remove property"
  },
  {
    "code": "def ttvar(name, index=None):\n    bvar = boolfunc.var(name, index)\n    try:\n        var = _VARS[bvar.uniqid]\n    except KeyError:\n        var = _VARS[bvar.uniqid] = TTVariable(bvar)\n    return var",
    "docstring": "Return a TruthTable variable.\n\n    Parameters\n    ----------\n    name : str\n        The variable's identifier string.\n    index : int or tuple[int], optional\n        One or more integer suffixes for variables that are part of a\n        multi-dimensional bit-vector, eg x[1], x[1][2][3]"
  },
  {
    "code": "def libvlc_audio_output_set(p_mi, psz_name):\n    f = _Cfunctions.get('libvlc_audio_output_set', None) or \\\n        _Cfunction('libvlc_audio_output_set', ((1,), (1,),), None,\n                    ctypes.c_int, MediaPlayer, ctypes.c_char_p)\n    return f(p_mi, psz_name)",
    "docstring": "Selects an audio output module.\n    @note: Any change will take be effect only after playback is stopped and\n    restarted. Audio output cannot be changed while playing.\n    @param p_mi: media player.\n    @param psz_name: name of audio output, use psz_name of See L{AudioOutput}.\n    @return: 0 if function succeded, -1 on error."
  },
  {
    "code": "def save_config(self, cmd=\"write\", confirm=False, confirm_response=\"\"):\n        return super(IpInfusionOcNOSBase, self).save_config(\n            cmd=cmd, confirm=confirm, confirm_response=confirm_response\n        )",
    "docstring": "Saves Config Using write command"
  },
  {
    "code": "def samples_by_indices(self, indices):\n        if not self._random_access:\n            raise TypeError('samples_by_indices method not supported as one '\n                            'or more of the underlying data sources does '\n                            'not support random access')\n        batch = self.source.samples_by_indices(indices)\n        return self.fn(*batch)",
    "docstring": "Gather a batch of samples by indices, applying any index\n        mapping defined by the underlying data sources.\n\n        Parameters\n        ----------\n        indices: 1D-array of ints or slice\n            An index array or a slice that selects the samples to retrieve\n\n        Returns\n        -------\n        nested list of arrays\n            A mini-batch"
  },
  {
    "code": "def client_auth(self):\n        if not self._client_auth:\n            self._client_auth = E.Element('merchantAuthentication')\n            E.SubElement(self._client_auth, 'name').text = self.config.login_id\n            E.SubElement(self._client_auth, 'transactionKey').text = self.config.transaction_key\n        return self._client_auth",
    "docstring": "Generate an XML element with client auth data populated."
  },
  {
    "code": "def delete(self, remove_tombstone=True):\n\t\tresponse = self.repo.api.http_request('DELETE', self.uri)\n\t\tif response.status_code == 204:\n\t\t\tself._empty_resource_attributes()\n\t\tif remove_tombstone:\n\t\t\tself.repo.api.http_request('DELETE', '%s/fcr:tombstone' % self.uri)\n\t\treturn True",
    "docstring": "Method to delete resources.\n\n\t\tArgs:\n\t\t\tremove_tombstone (bool): If True, will remove tombstone at uri/fcr:tombstone when removing resource.\n\n\t\tReturns:\n\t\t\t(bool)"
  },
  {
    "code": "def add_get(self, path: str, handler: _WebHandler, *,\n                name: Optional[str]=None, allow_head: bool=True,\n                **kwargs: Any) -> AbstractRoute:\n        resource = self.add_resource(path, name=name)\n        if allow_head:\n            resource.add_route(hdrs.METH_HEAD, handler, **kwargs)\n        return resource.add_route(hdrs.METH_GET, handler, **kwargs)",
    "docstring": "Shortcut for add_route with method GET, if allow_head is true another\n        route is added allowing head requests to the same endpoint"
  },
  {
    "code": "def _get_dependency_specification(dep_spec: typing.List[tuple]) -> str:\n    return \",\".join(dep_range[0] + dep_range[1] for dep_range in dep_spec)",
    "docstring": "Get string representation of dependency specification as provided by PythonDependencyParser."
  },
  {
    "code": "def add_log_type(self, logType, name=None, level=0, stdoutFlag=None, fileFlag=None, color=None, highlight=None, attributes=None):\n        assert logType not in self.__logTypeStdoutFlags.keys(), \"logType '%s' already defined\" %logType\n        assert isinstance(logType, basestring), \"logType must be a string\"\n        logType = str(logType)\n        self.__set_log_type(logType=logType, name=name, level=level,\n                            stdoutFlag=stdoutFlag, fileFlag=fileFlag,\n                            color=color, highlight=highlight, attributes=attributes)",
    "docstring": "Add a new logtype.\n\n        :Parameters:\n           #. logType (string): The logtype.\n           #. name (None, string): The logtype name. If None, name will be set to logtype.\n           #. level (number): The level of logging.\n           #. stdoutFlag (None, boolean): Force standard output logging flag.\n              If None, flag will be set according to minimum and maximum levels.\n           #. fileFlag (None, boolean): Force file logging flag.\n              If None, flag will be set according to minimum and maximum levels.\n           #. color (None, string): The logging text color. The defined colors are:\\n\n              black , red , green , orange , blue , magenta , cyan , grey , dark grey ,\n              light red , light green , yellow , light blue , pink , light cyan\n           #. highlight (None, string): The logging text highlight color. The defined highlights are:\\n\n              black , red , green , orange , blue , magenta , cyan , grey\n           #. attributes (None, string): The logging text attribute. The defined attributes are:\\n\n              bold , underline , blink , invisible , strike through\n\n        **N.B** *logging color, highlight and attributes are not allowed on all types of streams.*"
  },
  {
    "code": "def get(self, sid):\n        return TaskQueueContext(self._version, workspace_sid=self._solution['workspace_sid'], sid=sid, )",
    "docstring": "Constructs a TaskQueueContext\n\n        :param sid: The sid\n\n        :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueContext\n        :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueContext"
  },
  {
    "code": "def _repr_html_(self, **kwargs):\n        html = self.render(**kwargs)\n        html = \"data:text/html;charset=utf-8;base64,\" + base64.b64encode(html.encode('utf8')).decode('utf8')\n        if self.height is None:\n            iframe = (\n            '<div style=\"width:{width};\">'\n            '<div style=\"position:relative;width:100%;height:0;padding-bottom:{ratio};\">'\n            '<iframe src=\"{html}\" style=\"position:absolute;width:100%;height:100%;left:0;top:0;'\n            'border:none !important;\" '\n            'allowfullscreen webkitallowfullscreen mozallowfullscreen>'\n            '</iframe>'\n            '</div></div>').format\n            iframe = iframe(html=html,\n                            width=self.width,\n                            ratio=self.ratio)\n        else:\n            iframe = ('<iframe src=\"{html}\" width=\"{width}\" height=\"{height}\"'\n                      'style=\"border:none !important;\" '\n                      '\"allowfullscreen\" \"webkitallowfullscreen\" \"mozallowfullscreen\">'\n                      '</iframe>').format\n            iframe = iframe(html=html, width=self.width, height=self.height)\n        return iframe",
    "docstring": "Displays the Figure in a Jupyter notebook."
  },
  {
    "code": "def active(self) -> bool:\n        states = self._client.get_state(self._state_url)['states']\n        for state in states:\n            state = state['State']\n            if int(state['Id']) == self._state_id:\n                return state['IsActive'] == \"1\"\n        return False",
    "docstring": "Indicate if this RunState is currently active."
  },
  {
    "code": "def _load_connection_error(hostname, error):\n    ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\\n{error}'.format(host=hostname, error=error)}\n    return ret",
    "docstring": "Format and Return a connection error"
  },
  {
    "code": "def stop(self, timeout=None):\n        assert self.scan_id is not None, 'No scan_id has been set'\n        if timeout is None:\n            url = '/scans/%s/stop' % self.scan_id\n            self.conn.send_request(url, method='GET')\n            return\n        self.stop()\n        for _ in xrange(timeout):\n            time.sleep(1)\n            is_running = self.get_status()['is_running']\n            if not is_running:\n                return\n        msg = 'Failed to stop the scan in %s seconds'\n        raise ScanStopTimeoutException(msg % timeout)",
    "docstring": "Send the GET request required to stop the scan\n\n        If timeout is not specified we just send the request and return. When\n        it is the method will wait for (at most) :timeout: seconds until the\n        scan changes it's status/stops. If the timeout is reached then an\n        exception is raised.\n\n        :param timeout: The timeout in seconds\n        :return: None, an exception is raised if the timeout is exceeded"
  },
  {
    "code": "def add_insert(self, document):\n        validate_is_document_type(\"document\", document)\n        if not (isinstance(document, RawBSONDocument) or '_id' in document):\n            document['_id'] = ObjectId()\n        self.ops.append((_INSERT, document))",
    "docstring": "Add an insert document to the list of ops."
  },
  {
    "code": "def _ExtractGoogleSearchQuery(self, url):\n    if 'search' not in url or 'q=' not in url:\n      return None\n    line = self._GetBetweenQEqualsAndAmpersand(url)\n    if not line:\n      return None\n    return line.replace('+', ' ')",
    "docstring": "Extracts a search query from a Google URL.\n\n    Google Drive: https://drive.google.com/drive/search?q=query\n    Google Search: https://www.google.com/search?q=query\n    Google Sites: https://sites.google.com/site/.*/system/app/pages/\n                  search?q=query\n\n    Args:\n      url (str): URL.\n\n    Returns:\n      str: search query or None if no query was found."
  },
  {
    "code": "def comment(self, body):\n        self.github_request.comment(issue=self, body=body)\n        if self.state == 'closed':\n            self.open_issue()\n        return self",
    "docstring": "Adds a comment to the issue.\n\n        :params body: body, content of the comment\n        :returns: issue object\n        :rtype: :class:`exreporter.stores.github.GithubIssue`"
  },
  {
    "code": "def setUserAgent(self, uA=None):\n        logger = logging.getLogger(\"osrframework.utils\")\n        if not uA:\n            if self.userAgents:\n                logger = logging.debug(\"Selecting a new random User Agent.\")\n                uA = random.choice(self.userAgents)\n            else:\n                logger = logging.debug(\"No user agent was inserted.\")\n                return False\n        self.br.addheaders = [ ('User-agent', uA), ]\n        return True",
    "docstring": "This method will be called whenever a new query will be executed.\n\n            :param uA:    Any User Agent that was needed to be inserted. This parameter is optional.\n\n            :return:    Returns True if a User Agent was inserted and False if no User Agent could be inserted."
  },
  {
    "code": "def check_table(table=None, family='ipv4'):\n    ret = {'comment': '',\n           'result': False}\n    if not table:\n        ret['comment'] = 'Table needs to be specified'\n        return ret\n    nft_family = _NFTABLES_FAMILIES[family]\n    cmd = '{0} list tables {1}' . format(_nftables_cmd(), nft_family)\n    out = __salt__['cmd.run'](cmd, python_shell=False).find('table {0} {1}'.format(nft_family, table))\n    if out == -1:\n        ret['comment'] = 'Table {0} in family {1} does not exist'.\\\n                         format(table, family)\n    else:\n        ret['comment'] = 'Table {0} in family {1} exists'.\\\n                         format(table, family)\n        ret['result'] = True\n    return ret",
    "docstring": "Check for the existence of a table\n\n    CLI Example::\n\n        salt '*' nftables.check_table nat"
  },
  {
    "code": "def conll_ner2json(input_data, **kwargs):\n    delimit_docs = \"-DOCSTART- -X- O O\"\n    output_docs = []\n    for doc in input_data.strip().split(delimit_docs):\n        doc = doc.strip()\n        if not doc:\n            continue\n        output_doc = []\n        for sent in doc.split(\"\\n\\n\"):\n            sent = sent.strip()\n            if not sent:\n                continue\n            lines = [line.strip() for line in sent.split(\"\\n\") if line.strip()]\n            words, tags, chunks, iob_ents = zip(*[line.split() for line in lines])\n            biluo_ents = iob_to_biluo(iob_ents)\n            output_doc.append(\n                {\n                    \"tokens\": [\n                        {\"orth\": w, \"tag\": tag, \"ner\": ent}\n                        for (w, tag, ent) in zip(words, tags, biluo_ents)\n                    ]\n                }\n            )\n        output_docs.append(\n            {\"id\": len(output_docs), \"paragraphs\": [{\"sentences\": output_doc}]}\n        )\n        output_doc = []\n    return output_docs",
    "docstring": "Convert files in the CoNLL-2003 NER format into JSON format for use with\n    train cli."
  },
  {
    "code": "def ddb_path(self):\n        try:\n            return self._ddb_path\n        except AttributeError:\n            path = self.outdir.has_abiext(\"DDB\")\n            if path: self._ddb_path = path\n            return path",
    "docstring": "Absolute path of the DDB file. Empty string if file is not present."
  },
  {
    "code": "def get_preferred(self, addr_1, addr_2):\n        if addr_1 > addr_2:\n            addr_1, addr_2 = addr_2, addr_1\n        return self._cache.get((addr_1, addr_2))",
    "docstring": "Return the preferred address."
  },
  {
    "code": "def register_wcs(name, wrapper_class, coord_types):\n    global custom_wcs\n    custom_wcs[name] = Bunch.Bunch(name=name,\n                                   wrapper_class=wrapper_class,\n                                   coord_types=coord_types)",
    "docstring": "Register a custom WCS wrapper.\n\n    Parameters\n    ----------\n    name : str\n        The name of the custom WCS wrapper\n\n    wrapper_class : subclass of `~ginga.util.wcsmod.BaseWCS`\n        The class implementing the WCS wrapper\n\n    coord_types : list of str\n        List of names of coordinate types supported by the WCS"
  },
  {
    "code": "def _build_client(self, name=None):\n        url_path = self._url_path + [name] if name else self._url_path\n        return Client(host=self.host,\n                      version=self._version,\n                      request_headers=self.request_headers,\n                      url_path=url_path,\n                      append_slash=self.append_slash,\n                      timeout=self.timeout)",
    "docstring": "Make a new Client object\n\n        :param name: Name of the url segment\n        :type name: string\n        :return: A Client object"
  },
  {
    "code": "def next_session_label(self, session_label):\n        idx = self.schedule.index.get_loc(session_label)\n        try:\n            return self.schedule.index[idx + 1]\n        except IndexError:\n            if idx == len(self.schedule.index) - 1:\n                raise ValueError(\"There is no next session as this is the end\"\n                                 \" of the exchange calendar.\")\n            else:\n                raise",
    "docstring": "Given a session label, returns the label of the next session.\n\n        Parameters\n        ----------\n        session_label: pd.Timestamp\n            A session whose next session is desired.\n\n        Returns\n        -------\n        pd.Timestamp\n            The next session label (midnight UTC).\n\n        Notes\n        -----\n        Raises ValueError if the given session is the last session in this\n        calendar."
  },
  {
    "code": "def add_hypermedia(self, obj):\n        if hasattr(self, 'pk'):\n            obj['_links'] = {\n                'self': {\n                    'href': '{}{}/'.format(self.get_resource_uri(), obj[self.pk])\n                }\n            }",
    "docstring": "Adds HATEOAS links to the resource. Adds href link to self.\n        Override in subclasses to include additional functionality"
  },
  {
    "code": "def _date2int(date):\n        if isinstance(date, str):\n            if date.endswith(' 00:00:00') or date.endswith('T00:00:00'):\n                date = date[0:-9]\n            tmp = datetime.datetime.strptime(date, '%Y-%m-%d')\n            return tmp.toordinal()\n        if isinstance(date, datetime.date):\n            return date.toordinal()\n        if isinstance(date, int):\n            return date\n        raise ValueError('Unexpected type {0!s}'.format(date.__class__))",
    "docstring": "Returns an integer representation of a date.\n\n        :param str|datetime.date date: The date.\n\n        :rtype: int"
  },
  {
    "code": "def _match_setters(self, query):\n        q = query.decode('utf-8')\n        for name, parser, response, error_response in self._setters:\n            try:\n                value = parser(q)\n                logger.debug('Found response in setter of %s' % name)\n            except ValueError:\n                continue\n            try:\n                self._properties[name].set_value(value)\n                return response\n            except ValueError:\n                if isinstance(error_response, bytes):\n                    return error_response\n                return self.error_response('command_error')\n        return None",
    "docstring": "Tries to match in setters\n\n        :param query: message tuple\n        :type query: Tuple[bytes]\n        :return: response if found or None\n        :rtype: Tuple[bytes] | None"
  },
  {
    "code": "def get_to_persist(persisters):\n    def specs():\n        for p in persisters:\n            if isinstance(p, dict):\n                yield p[\"name\"], p.get(\"enabled\", True)\n            else:\n                yield p, True\n    components = sorted(dr.DELEGATES, key=dr.get_name)\n    names = dict((c, dr.get_name(c)) for c in components)\n    results = set()\n    for p, e in specs():\n        for c in components:\n            if names[c].startswith(p):\n                if e:\n                    results.add(c)\n                elif c in results:\n                    results.remove(c)\n    return results",
    "docstring": "Given a specification of what to persist, generates the corresponding set\n    of components."
  },
  {
    "code": "def op_right(op):\n    def method(self, other):\n        return op(value_left(self, other), value_right(self, other))\n    return method",
    "docstring": "Returns a type instance method for the given operator, applied\n    when the instance appears on the right side of the expression."
  },
  {
    "code": "def register_event_listener(coro):\n    if not asyncio.iscoroutinefunction(coro):\n        raise TypeError(\"Function is not a coroutine.\")\n    if coro not in _event_listeners:\n        _event_listeners.append(coro)",
    "docstring": "Registers a coroutine to receive lavalink event information.\n\n    This coroutine will accept three arguments: :py:class:`Player`,\n    :py:class:`LavalinkEvents`, and possibly an extra. The value of the extra depends\n    on the value of the second argument.\n\n    If the second argument is :py:attr:`LavalinkEvents.TRACK_END`, the extra will\n    be a :py:class:`TrackEndReason`.\n\n    If the second argument is :py:attr:`LavalinkEvents.TRACK_EXCEPTION`, the extra\n    will be an error string.\n\n    If the second argument is :py:attr:`LavalinkEvents.TRACK_STUCK`, the extra will\n    be the threshold milliseconds that the track has been stuck for.\n\n    If the second argument is :py:attr:`LavalinkEvents.TRACK_START`, the extra will be\n    a :py:class:`Track` object.\n\n    If the second argument is any other value, the third argument will not exist.\n\n    Parameters\n    ----------\n    coro\n        A coroutine function that accepts the arguments listed above.\n\n    Raises\n    ------\n    TypeError\n        If ``coro`` is not a coroutine."
  },
  {
    "code": "def create_supercut(composition, outputfile, padding):\n    print(\"[+] Creating clips.\")\n    demo_supercut(composition, padding)\n    for (clip, nextclip) in zip(composition, composition[1:]):\n        if ((nextclip['file'] == clip['file']) and (nextclip['start'] < clip['end'])):\n            nextclip['start'] += padding\n    all_filenames = set([c['file'] for c in composition])\n    videofileclips = dict([(f, VideoFileClip(f)) for f in all_filenames])\n    cut_clips = [videofileclips[c['file']].subclip(c['start'], c['end']) for c in composition]\n    print(\"[+] Concatenating clips.\")\n    final_clip = concatenate(cut_clips)\n    print(\"[+] Writing ouput file.\")\n    final_clip.to_videofile(outputfile, codec=\"libx264\", temp_audiofile='temp-audio.m4a', remove_temp=True, audio_codec='aac')",
    "docstring": "Concatenate video clips together and output finished video file to the\n    output directory."
  },
  {
    "code": "def noisy_operation(self, operation: 'cirq.Operation') -> 'cirq.OP_TREE':\n        if not hasattr(self.noisy_moments, '_not_overridden'):\n            return self.noisy_moments([ops.Moment([operation])],\n                                      operation.qubits)\n        if not hasattr(self.noisy_moment, '_not_overridden'):\n            return self.noisy_moment(ops.Moment([operation]), operation.qubits)\n        assert False, 'Should be unreachable.'",
    "docstring": "Adds noise to an individual operation.\n\n        Args:\n            operation: The operation to make noisy.\n\n        Returns:\n            An OP_TREE corresponding to the noisy operations implementing the\n            noisy version of the given operation."
  },
  {
    "code": "def update_domain_queues(self):\n        for key in self.domain_config:\n            final_key = \"{name}:{domain}:queue\".format(\n                    name=self.spider.name,\n                    domain=key)\n            if final_key in self.queue_dict:\n                self.queue_dict[final_key][0].window = float(self.domain_config[key]['window'])\n                self.logger.debug(\"Updated queue {q} with new config\"\n                                  .format(q=final_key))\n                if 'scale' in self.domain_config[key]:\n                    hits = int(self.domain_config[key]['hits'] * self.fit_scale(\n                               self.domain_config[key]['scale']))\n                    self.queue_dict[final_key][0].limit = float(hits)\n                else:\n                    self.queue_dict[final_key][0].limit = float(self.domain_config[key]['hits'])",
    "docstring": "Check to update existing queues already in memory\n        new queues are created elsewhere"
  },
  {
    "code": "def _crmod_to_abmn(self, configs):\n        A = configs[:, 0] % 1e4\n        B = np.floor(configs[:, 0] / 1e4).astype(int)\n        M = configs[:, 1] % 1e4\n        N = np.floor(configs[:, 1] / 1e4).astype(int)\n        ABMN = np.hstack((A[:, np.newaxis], B[:, np.newaxis], M[:, np.newaxis],\n                          N[:, np.newaxis])).astype(int)\n        return ABMN",
    "docstring": "convert crmod-style configurations to a Nx4 array\n\n        CRMod-style configurations merge A and B, and M and N, electrode\n        numbers into one large integer each:\n\n        .. math ::\n\n            AB = A \\cdot 10^4 + B\n\n            MN = M \\cdot 10^4 + N\n\n        Parameters\n        ----------\n        configs: numpy.ndarray\n            Nx2 array holding the configurations to convert\n\n        Examples\n        --------\n\n        >>> import numpy as np\n        >>> from reda.configs.configManager import ConfigManager\n        >>> config = ConfigManager(nr_of_electrodes=5)\n        >>> crmod_configs = np.array((\n        ...     (10002, 40003),\n        ...     (10010, 30004),\n        ... ))\n        >>> abmn = config._crmod_to_abmn(crmod_configs)\n        >>> print(abmn)\n        [[ 2  1  3  4]\n         [10  1  4  3]]"
  },
  {
    "code": "def remove_user(name, **client_args):\n    if not user_exists(name, **client_args):\n        log.info('User \\'%s\\' does not exist', name)\n        return False\n    client = _client(**client_args)\n    client.drop_user(name)\n    return True",
    "docstring": "Remove a user.\n\n    name\n        Name of the user to remove\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' influxdb.remove_user <name>"
  },
  {
    "code": "def __cache(self, file, content, document):\n        self.__files_cache.add_content(**{file: CacheData(content=content, document=document)})",
    "docstring": "Caches given file.\n\n        :param file: File to cache.\n        :type file: unicode\n        :param content: File content.\n        :type content: list\n        :param document: File document.\n        :type document: QTextDocument"
  },
  {
    "code": "def iter_init_append(self) :\n        \"creates a Message.AppendIter for appending arguments to the Message.\"\n        iter = self.AppendIter(None)\n        dbus.dbus_message_iter_init_append(self._dbobj, iter._dbobj)\n        return \\\n            iter",
    "docstring": "creates a Message.AppendIter for appending arguments to the Message."
  },
  {
    "code": "def release_package(\n        self, package_name: str, version: str, manifest_uri: str\n    ) -> bytes:\n        validate_is_supported_manifest_uri(manifest_uri)\n        raw_manifest = to_text(resolve_uri_contents(manifest_uri))\n        validate_raw_manifest_format(raw_manifest)\n        manifest = json.loads(raw_manifest)\n        validate_manifest_against_schema(manifest)\n        if package_name != manifest['package_name']:\n            raise ManifestValidationError(\n                f\"Provided package name: {package_name} does not match the package name \"\n                f\"found in the manifest: {manifest['package_name']}.\"\n            )\n        if version != manifest['version']:\n            raise ManifestValidationError(\n                f\"Provided package version: {version} does not match the package version \"\n                f\"found in the manifest: {manifest['version']}.\"\n            )\n        self._validate_set_registry()\n        return self.registry._release(package_name, version, manifest_uri)",
    "docstring": "Returns the release id generated by releasing a package on the current registry.\n        Requires ``web3.PM`` to have a registry set. Requires ``web3.eth.defaultAccount``\n        to be the registry owner.\n\n        * Parameters:\n            * ``package_name``: Must be a valid package name, matching the given manifest.\n            * ``version``: Must be a valid package version, matching the given manifest.\n            * ``manifest_uri``: Must be a valid content-addressed URI. Currently, only IPFS\n              and Github content-addressed URIs are supported."
  },
  {
    "code": "def _parse_parameter_options(self, options):\n        return self._select_options(options, self.ALL_OPTIONS, invert=True)",
    "docstring": "Select all unknown options.\n\n        Select all unknown options (not query string, API, or request\n        options)"
  },
  {
    "code": "def getSignalHeaders(self):\n        signalHeader = []\n        for chn in np.arange(self.signals_in_file):\n            signalHeader.append(self.getSignalHeader(chn))\n        return signalHeader",
    "docstring": "Returns the  header of all signals as array of dicts\n\n        Parameters\n        ----------\n        None"
  },
  {
    "code": "def get_sky_diffuse(surface_tilt, surface_azimuth,\n                    solar_zenith, solar_azimuth,\n                    dni, ghi, dhi, dni_extra=None, airmass=None,\n                    model='isotropic',\n                    model_perez='allsitescomposite1990'):\n    r\n    model = model.lower()\n    if model == 'isotropic':\n        sky = isotropic(surface_tilt, dhi)\n    elif model == 'klucher':\n        sky = klucher(surface_tilt, surface_azimuth, dhi, ghi,\n                      solar_zenith, solar_azimuth)\n    elif model == 'haydavies':\n        sky = haydavies(surface_tilt, surface_azimuth, dhi, dni, dni_extra,\n                        solar_zenith, solar_azimuth)\n    elif model == 'reindl':\n        sky = reindl(surface_tilt, surface_azimuth, dhi, dni, ghi, dni_extra,\n                     solar_zenith, solar_azimuth)\n    elif model == 'king':\n        sky = king(surface_tilt, dhi, ghi, solar_zenith)\n    elif model == 'perez':\n        sky = perez(surface_tilt, surface_azimuth, dhi, dni, dni_extra,\n                    solar_zenith, solar_azimuth, airmass,\n                    model=model_perez)\n    else:\n        raise ValueError('invalid model selection {}'.format(model))\n    return sky",
    "docstring": "r\"\"\"\n    Determine in-plane sky diffuse irradiance component\n    using the specified sky diffuse irradiance model.\n\n    Sky diffuse models include:\n        * isotropic (default)\n        * klucher\n        * haydavies\n        * reindl\n        * king\n        * perez\n\n    Parameters\n    ----------\n    surface_tilt : numeric\n        Panel tilt from horizontal.\n    surface_azimuth : numeric\n        Panel azimuth from north.\n    solar_zenith : numeric\n        Solar zenith angle.\n    solar_azimuth : numeric\n        Solar azimuth angle.\n    dni : numeric\n        Direct Normal Irradiance\n    ghi : numeric\n        Global horizontal irradiance\n    dhi : numeric\n        Diffuse horizontal irradiance\n    dni_extra : None or numeric, default None\n        Extraterrestrial direct normal irradiance\n    airmass : None or numeric, default None\n        Airmass\n    model : String, default 'isotropic'\n        Irradiance model.\n    model_perez : String, default 'allsitescomposite1990'\n        See perez.\n\n    Returns\n    -------\n    poa_sky_diffuse : numeric"
  },
  {
    "code": "def get_vertices(self, indexed=None):\n        if indexed is None:\n            if (self._vertices is None and\n                    self._vertices_indexed_by_faces is not None):\n                self._compute_unindexed_vertices()\n            return self._vertices\n        elif indexed == 'faces':\n            if (self._vertices_indexed_by_faces is None and\n                    self._vertices is not None):\n                self._vertices_indexed_by_faces = \\\n                    self._vertices[self.get_faces()]\n            return self._vertices_indexed_by_faces\n        else:\n            raise Exception(\"Invalid indexing mode. Accepts: None, 'faces'\")",
    "docstring": "Get the vertices\n\n        Parameters\n        ----------\n        indexed : str | None\n            If Note, return an array (N,3) of the positions of vertices in\n            the mesh. By default, each unique vertex appears only once.\n            If indexed is 'faces', then the array will instead contain three\n            vertices per face in the mesh (and a single vertex may appear more\n            than once in the array).\n\n        Returns\n        -------\n        vertices : ndarray\n            The vertices."
  },
  {
    "code": "def set_base_location(self, location):\n        self.base_location = location\n        self._utm_zone = location.zone\n        self._utm_datum = location.datum\n        self._utm_convergence = location.convergence",
    "docstring": "Configure the project's base location"
  },
  {
    "code": "def get_for_control_var_and_eval_expr(comm_type, kwargs):\n    control_vars, iter_type, expression = parse_for(comm_type)\n    eval_expression = evaluate_expression(expression, kwargs)[1]\n    iterval = []\n    if len(control_vars) == 2:\n        if not isinstance(eval_expression, dict):\n            raise exceptions.YamlSyntaxError('Can\\'t expand {t} to two control variables.'.\n                                             format(t=type(eval_expression)))\n        else:\n            iterval = list(eval_expression.items())\n    elif isinstance(eval_expression, six.string_types):\n        if iter_type == 'word_in':\n            iterval = eval_expression.split()\n        else:\n            iterval = eval_expression\n    else:\n        iterval = eval_expression\n    return control_vars, iterval",
    "docstring": "Returns tuple that consists of control variable name and iterable that is result\n    of evaluated expression of given for loop.\n\n    For example:\n    - given 'for $i in $(echo \"foo bar\")' it returns (['i'], ['foo', 'bar'])\n    - given 'for $i, $j in $foo' it returns (['i', 'j'], [('foo', 'bar')])"
  },
  {
    "code": "def logregularize(self, epsilon=2**-1074):\n        self.numerator.array[self.denominator.array == 0] = epsilon\n        self.denominator.array[self.denominator.array == 0] = 1\n        return self",
    "docstring": "Find bins in the denominator that are 0, and set them to 1,\n        while setting the corresponding bin in the numerator to\n        float epsilon.  This has the effect of allowing the\n        logarithm of the ratio array to be evaluated without error."
  },
  {
    "code": "def _title_uptodate(self,fullfile,pid,_title):\n        i=self.fb.get_object(pid)\n        if i.has_key('name'):\n            if _title == i['name']:\n                return True\n        return False",
    "docstring": "Check fb photo title against provided title,\n        returns true if they match"
  },
  {
    "code": "def generate_password(mode, length):\n    r = random.SystemRandom()\n    length = length or RANDOM_PASSWORD_DEFAULT_LENGTH\n    password = \"\".join(r.choice(RANDOM_PASSWORD_ALPHABET) for _ in range(length))\n    if mode == Mode.ECHO:\n        click.echo(style_password(password))\n    elif mode == Mode.COPY:\n        try:\n            import pyperclip\n            pyperclip.copy(password)\n            result = style_success(\"*** PASSWORD COPIED TO CLIPBOARD ***\")\n        except ImportError:\n            result = style_error('*** PYTHON PACKAGE \"PYPERCLIP\" NOT FOUND ***')\n        click.echo(result)\n    elif mode == Mode.RAW:\n        click.echo(password)",
    "docstring": "generate a random password"
  },
  {
    "code": "def make_certificate_signing_request(pkey, digest='sha512', **name):\n  csr = crypto.X509Req()\n  subj = csr.get_subject()\n  subj.C = name.get('C', 'US')\n  subj.ST = name.get('ST', 'CA')\n  subj.L = name.get('L', 'Home')\n  subj.O = name.get('O', 'Home')\n  subj.OU = name.get('OU', 'Unit')\n  subj.CN = name.get('CN', 'Common')\n  csr.set_pubkey(pkey)\n  csr.set_version(3)\n  csr.sign(pkey, digest)\n  return csr",
    "docstring": "Make a certificate signing request.\n\n  :param OpenSSL.crypto.PKey pkey: A private key.\n  :param str digest: A valid digest to use. For example, `sha512`.\n  :param name: Key word arguments containing subject name parts: C, ST, L, O,\n    OU, CN.\n  :return: A certificate signing request.\n  :rtype: :class:`OpenSSL.crypto.X509Request`"
  },
  {
    "code": "def read_stats(self):\n        captions, rows = self._get_pages()\n        name_caption_index = captions.index(self.name_caption)\n        captions.pop(name_caption_index)\n        self.captions = captions\n        self.statistics = OrderedDict()\n        for row in rows:\n            name = row.pop(name_caption_index)\n            self.statistics[name] = row",
    "docstring": "Reads the statistics view from IXN and saves it in statistics dictionary."
  },
  {
    "code": "def tag(self, path, name):\n    if not path[len(path) - 1] == '/':\n      path += '/'\n    config = self.get_config()\n    folder = self.find_folder({\n      'path' : path\n    }, config)\n    if not folder:\n      raise custom_errors.FileNotInConfig(path)\n    old_name = folder['label']\n    folder['label'] = name\n    dir_config = self.adapter.get_dir_config(path)\n    dir_config['label'] = name\n    self.adapter.set_dir_config(dir_config)\n    self.set_config(config)\n    return old_name",
    "docstring": "Change name associated with path"
  },
  {
    "code": "def getParameters(self, contactItem):\n        isVIP = False\n        if contactItem is not None:\n            isVIP = contactItem.person.vip\n        return [liveform.Parameter(\n            'vip', liveform.CHECKBOX_INPUT, bool, 'VIP', default=isVIP)]",
    "docstring": "Return a list containing a single parameter suitable for changing the\n        VIP status of a person.\n\n        @type contactItem: L{_PersonVIPStatus}\n\n        @rtype: C{list} of L{liveform.Parameter}"
  },
  {
    "code": "def addMonitor(self, monitor):\n    token = self.nextMonitorToken\n    self.nextMonitorToken += 1\n    self.monitors[token] = monitor\n    return token",
    "docstring": "Subscribe to SingleLayer2DExperiment events.\n\n    @param monitor (SingleLayer2DExperimentMonitor)\n    An object that implements a set of monitor methods\n\n    @return (object)\n    An opaque object that can be used to refer to this monitor."
  },
  {
    "code": "def unicode_to_string(self):\n        for tag in self.tags:\n            self.ununicode.append(str(tag))",
    "docstring": "Convert unicode in string"
  },
  {
    "code": "def _tile_image(self, data):\n        image = Image.open(BytesIO(data))\n        return image.convert('RGBA')",
    "docstring": "Tile binary content as PIL Image."
  },
  {
    "code": "def load(self, filename, offset):\n        try:\n            self.offset = offset\n            self.fd = open(filename, 'rb')\n            self.fd.seek(self.offset + VOLUME_HEADER_OFFSET)\n            data = self.fd.read(1024)\n            self.vol_header = VolumeHeader(data)\n            self.fd.close()\n        except IOError as e:\n            print(e)",
    "docstring": "Loads HFS+ volume information"
  },
  {
    "code": "def apply_change(self, path, *args):\n        if len(path) > 1:\n            self[path[0]].apply_change(path[1:], *args)\n        else:\n            assert len(path) == 1 and len(args) == 1, \\\n                \"Cannot process change %s\" % ([self.path + path] + list(args))\n            getattr(self, \"set_%s\" % path[0])(args[0])",
    "docstring": "Take a single change from a Delta and apply it to this model"
  },
  {
    "code": "def compute_mean_reward(rollouts, clipped):\n  reward_name = \"reward\" if clipped else \"unclipped_reward\"\n  rewards = []\n  for rollout in rollouts:\n    if rollout[-1].done:\n      rollout_reward = sum(getattr(frame, reward_name) for frame in rollout)\n      rewards.append(rollout_reward)\n  if rewards:\n    mean_rewards = np.mean(rewards)\n  else:\n    mean_rewards = 0\n  return mean_rewards",
    "docstring": "Calculate mean rewards from given epoch."
  },
  {
    "code": "def setDaemon(self, runnable, isdaemon, noregister = False):\n        if not noregister and runnable not in self.registerIndex:\n            self.register((), runnable)\n        if isdaemon:\n            self.daemons.add(runnable)\n        else:\n            self.daemons.discard(runnable)",
    "docstring": "If a runnable is a daemon, it will not keep the main loop running. The main loop will end when all alived runnables are daemons."
  },
  {
    "code": "def _output(self, message, verbosity, exact, stream):\n        if exact:\n            if self.config.verbosity == verbosity:\n                stream.write(message + \"\\n\")\n        else:\n            if self.config.verbosity >= verbosity:\n                stream.write(message + \"\\n\")",
    "docstring": "Output a message if the config's verbosity is >= to the given verbosity. If exact == True, the message\n        will only be outputted if the given verbosity exactly matches the config's verbosity."
  },
  {
    "code": "def fetch(code) :\n\t\tret = {}\n\t\tcode = KeywordFetcher._remove_strings(code)\n\t\tresult = KeywordFetcher.prog.findall(code)\n\t\tfor keyword in result :\n\t\t\tif len(keyword) <= 1: continue\n\t\t\tif keyword.isdigit(): continue\n\t\t\tif keyword[0] == '-' or keyword[0] == '*' : keyword = keyword[1:]\n\t\t\tif keyword[-1] == '-' or keyword[-1] == '*' : keyword = keyword[0:-1]\n\t\t\tif len(keyword) <= 1: continue\n\t\t\tret[ keyword ] = ret.get(keyword, 0) + 1\n\t\treturn ret",
    "docstring": "Fetch keywords by Code"
  },
  {
    "code": "def get_install_value(self, value_name, wanted_type=None):\n        try:\n            item_value, item_type = self.__reg_query_value(self.__reg_uninstall_handle, value_name)\n        except pywintypes.error as exc:\n            if exc.winerror == winerror.ERROR_FILE_NOT_FOUND:\n                return None\n            raise\n        if wanted_type and item_type not in self.__reg_types[wanted_type]:\n            item_value = None\n        return item_value",
    "docstring": "For the uninstall section of the registry return the name value.\n\n        Args:\n            value_name (str): Registry value name.\n            wanted_type (str):\n                The type of value wanted if the type does not match\n                None is return. wanted_type support values are\n                ``str`` ``int`` ``list`` ``bytes``.\n\n        Returns:\n            value: Value requested or None if not found."
  },
  {
    "code": "def fft_convolve(data, h, res_g = None,\n                 plan = None, inplace = False,\n                 kernel_is_fft = False,\n                 kernel_is_fftshifted = False):\n    if isinstance(data,np.ndarray):\n        return _fft_convolve_numpy(data, h,\n                                   plan = plan,\n                                   kernel_is_fft = kernel_is_fft,\n                                   kernel_is_fftshifted = kernel_is_fftshifted)\n    elif isinstance(data,OCLArray):\n        return _fft_convolve_gpu(data,h, res_g = res_g,\n                                 plan = plan, inplace = inplace,\n                                 kernel_is_fft = kernel_is_fft)\n    else:\n        raise TypeError(\"array argument (1) has bad type: %s\"%type(data))",
    "docstring": "convolves data with kernel h via FFTs\n\n    \n    data should be either a numpy array or a OCLArray (see doc for fft)\n    both data and h should be same shape\n\n    if data/h are OCLArrays, then:\n        - type should be complex64\n        - shape should be equal and power of two\n        - h is assumed to be already fftshifted\n         (otherwise set kernel_is_fftshifted  to true)"
  },
  {
    "code": "def from_int(cls, integer):\n        bin_string = bin(integer)\n        return cls(\n            text=len(bin_string) >= 1 and bin_string[-1] == \"1\",\n            comment=len(bin_string) >= 2 and bin_string[-2] == \"1\",\n            user=len(bin_string) >= 3 and bin_string[-3] == \"1\",\n            restricted=len(bin_string) >= 4 and bin_string[-4] == \"1\"\n        )",
    "docstring": "Constructs a `Deleted` using the `tinyint` value of the `rev_deleted`\n        column of the `revision` MariaDB table.\n\n        * DELETED_TEXT = 1\n        * DELETED_COMMENT = 2\n        * DELETED_USER = 4\n        * DELETED_RESTRICTED = 8"
  },
  {
    "code": "def split_all(reference, sep):\n    parts = partition_all(reference, sep)\n    return [p for p in parts if p not in sep]",
    "docstring": "Splits a given string at a given separator or list of separators.\n\n    :param reference: The reference to split.\n    :param sep: Separator string or list of separator strings.\n    :return: A list of split strings"
  },
  {
    "code": "def steady_state_potential(xdata,HistBins=100):\n    import numpy as _np\n    pops=_np.histogram(xdata,HistBins)[0]\n    bins=_np.histogram(xdata,HistBins)[1]\n    bins=bins[0:-1]\n    bins=bins+_np.mean(_np.diff(bins))\n    pops=pops/float(_np.sum(pops))\n    return bins,-_np.log(pops)",
    "docstring": "Calculates the steady state potential. Used in \n    fit_radius_from_potentials.\n\n    Parameters\n    ----------\n    xdata : ndarray\n        Position data for a degree of freedom\n    HistBins : int\n        Number of bins to use for histogram\n        of xdata. Number of position points\n        at which the potential is calculated.\n\n    Returns\n    -------\n    position : ndarray\n        positions at which potential has been \n        calculated\n    potential : ndarray\n        value of potential at the positions above"
  },
  {
    "code": "def load_writer_configs(writer_configs, ppp_config_dir,\n                        **writer_kwargs):\n    try:\n        writer_info = read_writer_config(writer_configs)\n        writer_class = writer_info['writer']\n    except (ValueError, KeyError, yaml.YAMLError):\n        raise ValueError(\"Invalid writer configs: \"\n                         \"'{}'\".format(writer_configs))\n    init_kwargs, kwargs = writer_class.separate_init_kwargs(writer_kwargs)\n    writer = writer_class(ppp_config_dir=ppp_config_dir,\n                          config_files=writer_configs,\n                          **init_kwargs)\n    return writer, kwargs",
    "docstring": "Load the writer from the provided `writer_configs`."
  },
  {
    "code": "def map_compute_fov(\n    m: tcod.map.Map,\n    x: int,\n    y: int,\n    radius: int = 0,\n    light_walls: bool = True,\n    algo: int = FOV_RESTRICTIVE,\n) -> None:\n    m.compute_fov(x, y, radius, light_walls, algo)",
    "docstring": "Compute the field-of-view for a map instance.\n\n    .. deprecated:: 4.5\n        Use :any:`tcod.map.Map.compute_fov` instead."
  },
  {
    "code": "def _get_char_pixels(self, s):\n        if len(s) == 1 and s in self._text_dict.keys():\n            return list(self._text_dict[s])\n        else:\n            return list(self._text_dict['?'])",
    "docstring": "Internal. Safeguards the character indexed dictionary for the\n        show_message function below"
  },
  {
    "code": "def get_lastfunction_header(self, header, default_return_value=None):\n        if self._last_call is None:\n            raise TwythonError('This function must be called after an API call. \\\n                               It delivers header information.')\n        return self._last_call['headers'].get(header, default_return_value)",
    "docstring": "Returns a specific header from the last API call\n        This will return None if the header is not present\n\n        :param header: (required) The name of the header you want to get\n                       the value of\n\n        Most useful for the following header information:\n            x-rate-limit-limit,\n            x-rate-limit-remaining,\n            x-rate-limit-class,\n            x-rate-limit-reset"
  },
  {
    "code": "def to_mapping(self,**values):\n        strike, dip, rake = self.strike_dip_rake()\n        min, max = self.angular_errors()\n        try:\n            disabled = self.disabled\n        except AttributeError:\n            disabled = False\n        mapping = dict(\n            uid=self.hash,\n            axes=self.axes.tolist(),\n            hyperbolic_axes=self.hyperbolic_axes.tolist(),\n            max_angular_error=max,\n            min_angular_error=min,\n            strike=strike,\n            dip=dip,\n            rake=rake,\n            disabled=disabled)\n        for k,v in values.items():\n            mapping[k] = v\n        return mapping",
    "docstring": "Create a JSON-serializable representation of the plane that is usable with the\n        javascript frontend"
  },
  {
    "code": "def to_str(self, separator=''):\n        if self.closed():\n            raise ValueError(\"Attempt to call to_str() on a closed Queryable.\")\n        return str(separator).join(self.select(str))",
    "docstring": "Build a string from the source sequence.\n\n        The elements of the query result will each coerced to a string and then\n        the resulting strings concatenated to return a single string. This\n        allows the natural processing of character sequences as strings. An\n        optional separator which will be inserted between each item may be\n        specified.\n\n        Note: this method uses immediate execution.\n\n        Args:\n            separator: An optional separator which will be coerced to a string\n                and inserted between each source item in the resulting string.\n\n        Returns:\n            A single string which is the result of stringifying each element\n            and concatenating the results into a single string.\n\n        Raises:\n            TypeError: If any element cannot be coerced to a string.\n            TypeError: If the separator cannot be coerced to a string.\n            ValueError: If the Queryable is closed."
  },
  {
    "code": "def _check_typecode_list(ofwhat, tcname):\n    for o in ofwhat:\n        if callable(o):\n            continue\n        if not isinstance(o, TypeCode):\n            raise TypeError(\n                tcname + ' ofwhat outside the TypeCode hierarchy, ' +\n                str(o.__class__))\n        if o.pname is None and not isinstance(o, AnyElement):\n            raise TypeError(tcname + ' element ' + str(o) + ' has no name')",
    "docstring": "Check a list of typecodes for compliance with Struct\n    requirements."
  },
  {
    "code": "def text(self):\n        def _problem_iter(problem_num):\n            problem_file = os.path.join(EULER_DATA, 'problems.txt')\n            with open(problem_file) as f:\n                is_problem = False\n                last_line = ''\n                for line in f:\n                    if line.strip() == 'Problem %i' % problem_num:\n                        is_problem = True\n                    if is_problem:\n                        if line == last_line == '\\n':\n                            break\n                        else:\n                            yield line[:-1]\n                            last_line = line\n        problem_lines = [line for line in _problem_iter(self.num)]\n        if problem_lines:\n            return '\\n'.join(problem_lines[3:-1])\n        else:\n            msg = 'Problem %i not found in problems.txt.' % self.num\n            click.secho(msg, fg='red')\n            click.echo('If this problem exists on Project Euler, consider '\n                       'submitting a pull request to EulerPy on GitHub.')\n            sys.exit(1)",
    "docstring": "Parses problems.txt and returns problem text"
  },
  {
    "code": "def edit_dedicated_fwl_rules(self, firewall_id, rules):\n        mask = ('mask[networkVlan[firewallInterfaces'\n                '[firewallContextAccessControlLists]]]')\n        svc = self.client['Network_Vlan_Firewall']\n        fwl = svc.getObject(id=firewall_id, mask=mask)\n        network_vlan = fwl['networkVlan']\n        for fwl1 in network_vlan['firewallInterfaces']:\n            if fwl1['name'] == 'inside':\n                continue\n            for control_list in fwl1['firewallContextAccessControlLists']:\n                if control_list['direction'] == 'out':\n                    continue\n                fwl_ctx_acl_id = control_list['id']\n        template = {'firewallContextAccessControlListId': fwl_ctx_acl_id,\n                    'rules': rules}\n        svc = self.client['Network_Firewall_Update_Request']\n        return svc.createObject(template)",
    "docstring": "Edit the rules for dedicated firewall.\n\n        :param integer firewall_id: the instance ID of the dedicated firewall\n        :param list rules: the rules to be pushed on the firewall as defined by\n                           SoftLayer_Network_Firewall_Update_Request_Rule"
  },
  {
    "code": "def tmsiReallocationCommand():\n    a = TpPd(pd=0x5)\n    b = MessageType(mesType=0x1a)\n    c = LocalAreaId()\n    d = MobileId()\n    packet = a / b / c / d\n    return packet",
    "docstring": "TMSI REALLOCATION COMMAND Section 9.2.17"
  },
  {
    "code": "def get_path(self, appendix=None, by_name=False):\n        if by_name:\n            state_identifier = self.name\n        else:\n            state_identifier = self.state_id\n        if not self.is_root_state:\n            if appendix is None:\n                return self.parent.get_path(state_identifier, by_name)\n            else:\n                return self.parent.get_path(state_identifier + PATH_SEPARATOR + appendix, by_name)\n        else:\n            if appendix is None:\n                return state_identifier\n            else:\n                return state_identifier + PATH_SEPARATOR + appendix",
    "docstring": "Recursively create the path of the state.\n\n        The path is generated in bottom up method i.e. from the nested child states to the root state. The method\n        concatenates either State.state_id (always unique) or State.name (maybe not unique but human readable) as\n        state identifier for the path.\n\n        :param str appendix: the part of the path that was already calculated by previous function calls\n        :param bool by_name: The boolean enables name usage to generate the path\n        :rtype: str\n        :return: the full path to the root state"
  },
  {
    "code": "def download(\n    state, host, source_url, destination,\n    user=None, group=None, mode=None, cache_time=None, force=False,\n):\n    info = host.fact.file(destination)\n    if info is False:\n        raise OperationError(\n            'Destination {0} already exists and is not a file'.format(destination),\n        )\n    download = force\n    if info is None:\n        download = True\n    elif cache_time:\n        cache_time = host.fact.date.replace(tzinfo=None) - timedelta(seconds=cache_time)\n        if info['mtime'] and info['mtime'] > cache_time:\n            download = True\n    if download:\n        yield 'wget -q {0} -O {1}'.format(source_url, destination)\n        if user or group:\n            yield chown(destination, user, group)\n        if mode:\n            yield chmod(destination, mode)",
    "docstring": "Download files from remote locations.\n\n    + source_url: source URl of the file\n    + destination: where to save the file\n    + user: user to own the files\n    + group: group to own the files\n    + mode: permissions of the files\n    + cache_time: if the file exists already, re-download after this time (in s)\n    + force: always download the file, even if it already exists"
  },
  {
    "code": "def _next_regular(target):\n    if target <= 6:\n        return target\n    if not (target & (target - 1)):\n        return target\n    match = float('inf')\n    p5 = 1\n    while p5 < target:\n        p35 = p5\n        while p35 < target:\n            quotient = -(-target // p35)\n            try:\n                p2 = 2 ** ((quotient - 1).bit_length())\n            except AttributeError:\n                p2 = 2 ** _bit_length_26(quotient - 1)\n            N = p2 * p35\n            if N == target:\n                return N\n            elif N < match:\n                match = N\n            p35 *= 3\n            if p35 == target:\n                return p35\n        if p35 < match:\n            match = p35\n        p5 *= 5\n        if p5 == target:\n            return p5\n    if p5 < match:\n        match = p5\n    return match",
    "docstring": "Find the next regular number greater than or equal to target.\n    Regular numbers are composites of the prime factors 2, 3, and 5.\n    Also known as 5-smooth numbers or Hamming numbers, these are the optimal\n    size for inputs to FFTPACK.\n    Target must be a positive integer."
  },
  {
    "code": "def _find_node_by_indices(self, point):\n        path_index, node_index = point\n        path = self.paths[int(path_index)]\n        node = path.nodes[int(node_index)]\n        return node",
    "docstring": "Find the GSNode that is refered to by the given indices.\n\n        See GSNode::_indices()"
  },
  {
    "code": "def resort(self, columnName):\n        csc = self.currentSortColumn\n        newSortColumn = self.columns[columnName]\n        if newSortColumn is None:\n            raise Unsortable('column %r has no sort attribute' % (columnName,))\n        if csc is newSortColumn:\n            self.isAscending = not self.isAscending\n        else:\n            self.currentSortColumn = newSortColumn\n            self.isAscending = True\n        return self.isAscending",
    "docstring": "Re-sort the table.\n\n        @param columnName: the name of the column to sort by.  This is a string\n        because it is passed from the browser."
  },
  {
    "code": "def OnExpandAll(self):\n        root = self.tree.GetRootItem()\n        fn = self.tree.Expand\n        self.traverse(root, fn)\n        self.tree.Expand(root)",
    "docstring": "expand all nodes"
  },
  {
    "code": "def getprimeover(N):\n    if HAVE_GMP:\n        randfunc = random.SystemRandom()\n        r = gmpy2.mpz(randfunc.getrandbits(N))\n        r = gmpy2.bit_set(r, N - 1)\n        return int(gmpy2.next_prime(r))\n    elif HAVE_CRYPTO:\n        return number.getPrime(N, os.urandom)\n    else:\n        randfunc = random.SystemRandom()\n        n = randfunc.randrange(2**(N-1), 2**N) | 1\n        while not is_prime(n):\n            n += 2\n        return n",
    "docstring": "Return a random N-bit prime number using the System's best\n    Cryptographic random source.\n\n    Use GMP if available, otherwise fallback to PyCrypto"
  },
  {
    "code": "def dumpBlock(self, block_name):\n        try:\n            return self.dbsBlock.dumpBlock(block_name)\n        except HTTPError as he:\n            raise he\n        except dbsException as de:\n            dbsExceptionHandler(de.eCode, de.message, self.logger.exception, de.serverError)\n        except Exception as ex:\n            sError = \"DBSReaderModel/dumpBlock. %s\\n. Exception trace: \\n %s\" \\\n                    % (ex, traceback.format_exc())\n            dbsExceptionHandler('dbsException-server-error', ex.message, self.logger.exception, sError)",
    "docstring": "API the list all information related with the block_name\n\n        :param block_name: Name of block to be dumped (Required)\n        :type block_name: str"
  },
  {
    "code": "def merge_adjacent(numbers, indicator='..', base=0):\n    integers = list(sorted([(int(\"%s\" % i, base), i) for i in numbers]))\n    idx = 0\n    result = []\n    while idx < len(numbers):\n        end = idx + 1\n        while end < len(numbers) and integers[end-1][0] == integers[end][0] - 1:\n            end += 1\n        result.append(\"%s%s%s\" % (integers[idx][1], indicator, integers[end-1][1])\n                      if end > idx + 1\n                      else \"%s\" % integers[idx][1])\n        idx = end\n    return result",
    "docstring": "Merge adjacent numbers in an iterable of numbers.\n\n        Parameters:\n            numbers (list): List of integers or numeric strings.\n            indicator (str): Delimiter to indicate generated ranges.\n            base (int): Passed to the `int()` conversion when comparing numbers.\n\n        Return:\n            list of str: Condensed sequence with either ranges or isolated numbers."
  },
  {
    "code": "def download_sample(job, sample, inputs):\n    uuid, url = sample\n    job.fileStore.logToMaster('Downloading sample: {}'.format(uuid))\n    tar_id = job.addChildJobFn(download_url_job, url, s3_key_path=inputs.ssec, disk='30G').rv()\n    sample_inputs = argparse.Namespace(**vars(inputs))\n    sample_inputs.uuid = uuid\n    sample_inputs.cores = multiprocessing.cpu_count()\n    job.addFollowOnJobFn(process_sample, sample_inputs, tar_id, cores=2, disk='60G')",
    "docstring": "Download the input sample\n\n    :param JobFunctionWrappingJob job: passed by Toil automatically\n    :param tuple sample: Tuple containing (UUID,URL) of a sample\n    :param Namespace inputs: Stores input arguments (see main)"
  },
  {
    "code": "def _find_observable_paths(extra_files=None):\n    rv = set(\n        os.path.dirname(os.path.abspath(x)) if os.path.isfile(x) else os.path.abspath(x)\n        for x in sys.path\n    )\n    for filename in extra_files or ():\n        rv.add(os.path.dirname(os.path.abspath(filename)))\n    for module in list(sys.modules.values()):\n        fn = getattr(module, \"__file__\", None)\n        if fn is None:\n            continue\n        fn = os.path.abspath(fn)\n        rv.add(os.path.dirname(fn))\n    return _find_common_roots(rv)",
    "docstring": "Finds all paths that should be observed."
  },
  {
    "code": "def _init_client():\n    if client is not None:\n        return\n    global _mysql_kwargs, _table_name\n    _mysql_kwargs = {\n        'host': __opts__.get('mysql.host', '127.0.0.1'),\n        'user': __opts__.get('mysql.user', None),\n        'passwd': __opts__.get('mysql.password', None),\n        'db': __opts__.get('mysql.database', _DEFAULT_DATABASE_NAME),\n        'port': __opts__.get('mysql.port', 3306),\n        'unix_socket': __opts__.get('mysql.unix_socket', None),\n        'connect_timeout': __opts__.get('mysql.connect_timeout', None),\n        'autocommit': True,\n    }\n    _table_name = __opts__.get('mysql.table_name', _table_name)\n    for k, v in _mysql_kwargs.items():\n        if v is None:\n            _mysql_kwargs.pop(k)\n    kwargs_copy = _mysql_kwargs.copy()\n    kwargs_copy['passwd'] = \"<hidden>\"\n    log.info(\"mysql_cache: Setting up client with params: %r\", kwargs_copy)\n    _create_table()",
    "docstring": "Initialize connection and create table if needed"
  },
  {
    "code": "def format_payload(self, api_version, data):\n        if (api_version in (1, 2)):\n            if type(data) == str:\n                logger.debug('Converting string to dict:\\n%s' % data)\n                data = data.lstrip('?')\n                data = data.rstrip('&')\n                data = parse_qs(data)\n                logger.debug('Converted:\\n%s' % str(data))\n        elif api_version in ('am', 'was', 'am2'):\n            if type(data) == etree._Element:\n                logger.debug('Converting lxml.builder.E to string')\n                data = etree.tostring(data)\n                logger.debug('Converted:\\n%s' % data)\n        return data",
    "docstring": "Return appropriate QualysGuard API call."
  },
  {
    "code": "def cto(self):\n        cto = -1\n        try:\n            if self.lnk.type == Lnk.CHARSPAN:\n                cto = self.lnk.data[1]\n        except AttributeError:\n            pass\n        return cto",
    "docstring": "The final character position in the surface string.\n\n        Defaults to -1 if there is no valid cto value."
  },
  {
    "code": "def get_default_config_directory():\n        test_path = os.path.dirname(os.path.realpath(inspect.getouterframes(inspect.currentframe())[2][1]))\n        return os.path.join(test_path, 'conf')",
    "docstring": "Return default config directory, based in the actual test path\n\n        :returns: default config directory"
  },
  {
    "code": "def set_mindays(name, mindays):\n    pre_info = info(name)\n    if mindays == pre_info['min']:\n        return True\n    cmd = 'passwd -n {0} {1}'.format(mindays, name)\n    __salt__['cmd.run'](cmd, python_shell=False)\n    post_info = info(name)\n    if post_info['min'] != pre_info['min']:\n        return post_info['min'] == mindays\n    return False",
    "docstring": "Set the minimum number of days between password changes. See man passwd.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' shadow.set_mindays username 7"
  },
  {
    "code": "def delete_word(word):\n    conn = sqlite3.connect(os.path.join(DEFAULT_PATH, 'word.db'))\n    curs = conn.cursor()\n    curs.execute('SELECT expl, pr FROM Word WHERE name = \"%s\"' % word)\n    res = curs.fetchall()\n    if res:\n        try:\n            curs.execute('DELETE FROM Word WHERE name = \"%s\"' % word)\n        except Exception as e:\n            print(e)\n        else:\n            print(colored('%s has been deleted from database' % word, 'green'))\n            conn.commit()\n        finally:\n            curs.close()\n            conn.close()\n    else:\n        print(colored('%s not exists in the database' % word, 'white', 'on_red'))",
    "docstring": "delete the word or phrase from database."
  },
  {
    "code": "def activate():\n    global PathFinder, FileFinder, ff_path_hook\n    path_hook_index = len(sys.path_hooks)\n    sys.path_hooks.append(ff_path_hook)\n    sys.path_importer_cache.clear()\n    pathfinder_index = len(sys.meta_path)\n    sys.meta_path.append(PathFinder)\n    return path_hook_index, pathfinder_index",
    "docstring": "Install the path-based import components."
  },
  {
    "code": "async def validate(state, holdout_glob):\n  if not glob.glob(holdout_glob):\n    print('Glob \"{}\" didn\\'t match any files, skipping validation'.format(\n          holdout_glob))\n  else:\n    await run(\n        'python3', 'validate.py', holdout_glob,\n        '--flagfile={}'.format(os.path.join(FLAGS.flags_dir, 'validate.flags')),\n        '--work_dir={}'.format(fsdb.working_dir()))",
    "docstring": "Validate the trained model against holdout games.\n\n  Args:\n    state: the RL loop State instance.\n    holdout_glob: a glob that matches holdout games."
  },
  {
    "code": "def get(self, cluster_id, show_progress=False):\n        url = ('/clusters/%(cluster_id)s?%(params)s' %\n               {\"cluster_id\": cluster_id,\n                \"params\": parse.urlencode({\"show_progress\": show_progress})})\n        return self._get(url, 'cluster')",
    "docstring": "Get information about a Cluster."
  },
  {
    "code": "def dcmtoquat(dcm):\n    quat = np.zeros(4)\n    quat[-1] = 1/2*np.sqrt(np.trace(dcm)+1)\n    quat[0:3] = 1/4/quat[-1]*vee_map(dcm-dcm.T)\n    return quat",
    "docstring": "Convert DCM to quaternion\n    \n    This function will convert a rotation matrix, also called a direction\n    cosine matrix into the equivalent quaternion.\n\n    Parameters:\n    ----------\n    dcm - (3,3) numpy array\n        Numpy rotation matrix which defines a rotation from the b to a frame\n\n    Returns:\n    --------\n    quat - (4,) numpy array\n        Array defining a quaterion where the quaternion is defined in terms of\n        a vector and a scalar part.  The vector is related to the eigen axis\n        and equivalent in both reference frames [x y z w]"
  },
  {
    "code": "def add_mixl_specific_results_to_estimation_res(estimator, results_dict):\n    prob_res = mlc.calc_choice_sequence_probs(results_dict[\"long_probs\"],\n                                              estimator.choice_vector,\n                                              estimator.rows_to_mixers,\n                                              return_type='all')\n    results_dict[\"simulated_sequence_probs\"] = prob_res[0]\n    results_dict[\"expanded_sequence_probs\"] = prob_res[1]\n    return results_dict",
    "docstring": "Stores particular items in the results dictionary that are unique to mixed\n    logit-type models. In particular, this function calculates and adds\n    `sequence_probs` and `expanded_sequence_probs` to the results dictionary.\n    The `constrained_pos` object is also stored to the results_dict.\n\n    Parameters\n    ----------\n    estimator : an instance of the MixedEstimator class.\n        Should contain a `choice_vector` attribute that is a 1D ndarray\n        representing the choices made for this model's dataset. Should also\n        contain a `rows_to_mixers` attribute that maps each row of the long\n        format data to a unit of observation that the mixing is being performed\n        over.\n    results_dict : dict.\n        This dictionary should be the dictionary returned from\n        scipy.optimize.minimize. In particular, it should have the following\n        `long_probs` key.\n\n    Returns\n    -------\n    results_dict."
  },
  {
    "code": "def _try_get_current_manager(cls):\n        if utils.get_distro_name().find('gentoo') == -1:\n            return None\n        if 'PACKAGE_MANAGER' in os.environ:\n            pm = os.environ['PACKAGE_MANAGER']\n            if pm == 'paludis':\n                try:\n                    import paludis\n                    return GentooPackageManager.PALUDIS\n                except ImportError:\n                    cls._debug_doesnt_work('can\\'t import paludis', name='PaludisPackageManager')\n                    return None\n            elif pm == 'portage':\n                pass\n            else:\n                return None\n        try:\n            import portage\n            return GentooPackageManager.PORTAGE\n        except ImportError:\n            cls._debug_doesnt_work('can\\'t import portage', name='EmergePackageManager')\n            return None",
    "docstring": "Try to detect a package manager used in a current Gentoo system."
  },
  {
    "code": "def _pause_all_nodes(self, max_thread_pool_size=0):\n        failed = 0\n        def _pause_specific_node(node):\n            if not node.instance_id:\n                log.warning(\"Node `%s` has no instance id.\"\n                            \" It is either already stopped, or\"\n                            \" never created properly.  Not attempting\"\n                            \" to stop it again.\", node.name)\n                return None\n            try:\n                return node.pause()\n            except Exception as err:\n                log.error(\n                    \"Could not stop node `%s` (instance ID `%s`): %s %s\",\n                    node.name, node.instance_id, err, err.__class__)\n                node.update_ips()\n                return None\n        nodes = self.get_all_nodes()\n        thread_pool = self._make_thread_pool(max_thread_pool_size)\n        for node, state in zip(nodes, thread_pool.map(_pause_specific_node, nodes)):\n            if state is None:\n                failed += 1\n            else:\n                self.paused_nodes[node.name] = state\n        return failed",
    "docstring": "Pause all cluster nodes - ensure that we store data so that in\n        the future the nodes can be restarted.\n\n        :return: int - number of failures."
  },
  {
    "code": "def update(self, name, modifiers):\n        self.update_name(name)\n        self.modifiers = modifiers",
    "docstring": "Updates the attributes for the subroutine instance, handles name changes\n        in the parent module as well."
  },
  {
    "code": "def coordinates(self):\n        i = self._coordinates\n        for name, _i in COORDINATES.items():\n            if i==_i:\n                return name\n        return i",
    "docstring": "Get or set the internal coordinate system.\n\n        Available coordinate systems are:\n\n        - ``'jacobi'`` (default)\n        - ``'democraticheliocentric'``\n        - ``'whds'``"
  },
  {
    "code": "def set_theme(self, theme_name, toplevel=None, themebg=None):\n        if self._toplevel is not None and toplevel is None:\n            toplevel = self._toplevel\n        if self._themebg is not None and themebg is None:\n            themebg = self._themebg\n        ThemedWidget.set_theme(self, theme_name)\n        color = self._get_bg_color()\n        if themebg is True:\n            self.config(background=color)\n        if toplevel is True:\n            self._setup_toplevel_hook(color)",
    "docstring": "Redirect the set_theme call to also set Tk background color"
  },
  {
    "code": "def ensure_path(path, mode=0o777):\n    if path:\n        try:\n            umask = os.umask(000)\n            os.makedirs(path, mode)\n            os.umask(umask)\n        except OSError as e:\n            if e.errno != errno.EEXIST:\n                raise",
    "docstring": "Ensure that path exists in a multiprocessing safe way.\n\n    If the path does not exist, recursively create it and its parent\n    directories using the provided mode.  If the path already exists,\n    do nothing.  The umask is cleared to enable the mode to be set,\n    and then reset to the original value after the mode is set.\n\n    Parameters\n    ----------\n    path : str\n        file system path to a non-existent directory\n        that should be created.\n    mode : int\n        octal representation of the mode to use when creating\n        the directory.\n\n    Raises\n    ------\n    OSError\n        If os.makedirs raises an OSError for any reason\n        other than if the directory already exists."
  },
  {
    "code": "def mget_list(item, index):\n    'get mulitple items via index of int, slice or list'\n    if isinstance(index, (int, slice)):\n        return item[index]\n    else:\n        return map(item.__getitem__, index)",
    "docstring": "get mulitple items via index of int, slice or list"
  },
  {
    "code": "def cmd_iter(\n            self,\n            tgt,\n            fun,\n            arg=(),\n            timeout=None,\n            tgt_type='glob',\n            ret='',\n            kwarg=None,\n            **kwargs):\n        was_listening = self.event.cpub\n        try:\n            pub_data = self.run_job(\n                tgt,\n                fun,\n                arg,\n                tgt_type,\n                ret,\n                timeout,\n                kwarg=kwarg,\n                listen=True,\n                **kwargs)\n            if not pub_data:\n                yield pub_data\n            else:\n                if kwargs.get('yield_pub_data'):\n                    yield pub_data\n                for fn_ret in self.get_iter_returns(pub_data['jid'],\n                                                    pub_data['minions'],\n                                                    timeout=self._get_timeout(timeout),\n                                                    tgt=tgt,\n                                                    tgt_type=tgt_type,\n                                                    **kwargs):\n                    if not fn_ret:\n                        continue\n                    yield fn_ret\n                self._clean_up_subscriptions(pub_data['jid'])\n        finally:\n            if not was_listening:\n                self.event.close_pub()",
    "docstring": "Yields the individual minion returns as they come in\n\n        The function signature is the same as :py:meth:`cmd` with the\n        following exceptions.\n\n        Normally :py:meth:`cmd_iter` does not yield results for minions that\n        are not connected. If you want it to return results for disconnected\n        minions set `expect_minions=True` in `kwargs`.\n\n        :return: A generator yielding the individual minion returns\n\n        .. code-block:: python\n\n            >>> ret = local.cmd_iter('*', 'test.ping')\n            >>> for i in ret:\n            ...     print(i)\n            {'jerry': {'ret': True}}\n            {'dave': {'ret': True}}\n            {'stewart': {'ret': True}}"
  },
  {
    "code": "def get_related(self, instance, number):\n        related_pks = self.compute_related(instance.pk)[:number]\n        related_pks = [pk for pk, score in related_pks]\n        related_objects = sorted(\n            self.queryset.model.objects.filter(pk__in=related_pks),\n            key=lambda x: related_pks.index(x.pk))\n        return related_objects",
    "docstring": "Return a list of the most related objects to instance."
  },
  {
    "code": "def get_arguments(self, name: str, strip: bool = True) -> List[str]:\n        assert isinstance(strip, bool)\n        return self._get_arguments(name, self.request.arguments, strip)",
    "docstring": "Returns a list of the arguments with the given name.\n\n        If the argument is not present, returns an empty list.\n\n        This method searches both the query and body arguments."
  },
  {
    "code": "def get_role_config_group(self, name):\n    return role_config_groups.get_role_config_group(\n        self._get_resource_root(), self.name, name, self._get_cluster_name())",
    "docstring": "Get a role configuration group in the service by name.\n\n    @param name: The name of the role config group.\n    @return: An ApiRoleConfigGroup object.\n    @since: API v3"
  },
  {
    "code": "def decode_consumer_metadata_response(cls, data):\n        ((correlation_id, error, nodeId), cur) = relative_unpack('>ihi', data, 0)\n        (host, cur) = read_short_string(data, cur)\n        ((port,), cur) = relative_unpack('>i', data, cur)\n        return kafka.structs.ConsumerMetadataResponse(error, nodeId, host, port)",
    "docstring": "Decode bytes to a kafka.structs.ConsumerMetadataResponse\n\n        Arguments:\n            data: bytes to decode"
  },
  {
    "code": "def _bibliography(doc, terms, converters=[], format='html'):\n    output_backend = 'latex' if format == 'latex' else MetatabHtmlBackend\n    def mk_cite(v):\n        for c in converters:\n            r = c(v)\n            if r is not False:\n                return r\n        return make_citation_dict(v)\n    if isinstance(doc, MetatabDoc):\n        d = [mk_cite(t) for t in terms]\n        cd = {e['name_link']: e for e in d}\n    else:\n        cd = {k: mk_cite(v, i) for i, (k, v) in enumerate(doc.items())}\n    return PybtexEngine().format_from_string(safe_dump({'entries': cd}),\n                                             style=MetatabStyle,\n                                             output_backend=output_backend,\n                                             bib_format='yaml')",
    "docstring": "Render citations, from a document or a doct of dicts\n\n    If the input is a dict, each key is the name of the citation, and the value is a BibTex\n    formatted dict\n\n    :param doc: A MetatabDoc, or a dict of BibTex dicts\n    :return:"
  },
  {
    "code": "def _nix_collect_garbage():\n    nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')\n    return [os.path.join(nixhome, 'nix-collect-garbage')]",
    "docstring": "Make sure we get the right nix-store, too."
  },
  {
    "code": "def get_connection_id_by_endpoint(self, endpoint):\n        with self._connections_lock:\n            for connection_id in self._connections:\n                connection_info = self._connections[connection_id]\n                if connection_info.uri == endpoint:\n                    return connection_id\n            raise KeyError()",
    "docstring": "Returns the connection id associated with a publically\n        reachable endpoint or raises KeyError if the endpoint is not\n        found.\n\n        Args:\n            endpoint (str): A zmq-style uri which identifies a publically\n                reachable endpoint."
  },
  {
    "code": "def _indexable_tags(self):\n        tags = current_app.extensions.get(\"tags\")\n        if not tags or not tags.supports_taggings(self):\n            return \"\"\n        default_ns = tags.entity_default_ns(self)\n        return [t for t in tags.entity_tags(self) if t.ns == default_ns]",
    "docstring": "Index tag ids for tags defined in this Entity's default tags\n        namespace."
  },
  {
    "code": "def get_tip_coordinates(self, axis=None):\n        coords = self.get_node_coordinates()\n        if axis == 'x':\n            return coords[:self.ntips, 0]\n        elif axis == 'y':\n            return coords[:self.ntips, 1]\n        return coords[:self.ntips]",
    "docstring": "Returns coordinates of the tip positions for a tree. If no argument\n        for axis then a 2-d array is returned. The first column is the x \n        coordinates the second column is the y-coordinates. If you enter an \n        argument for axis then a 1-d array will be returned of just that axis."
  },
  {
    "code": "def press_event(self):\n        if self.mouse_event.press_event is None:\n            return None\n        ev = self.copy()\n        ev.mouse_event = self.mouse_event.press_event\n        return ev",
    "docstring": "The mouse press event that initiated a mouse drag, if any."
  },
  {
    "code": "def _counts_at_position(positions, orig_reader, cmp_reader):\n    pos_counts = collections.defaultdict(lambda:\n                 collections.defaultdict(lambda:\n                 collections.defaultdict(int)))\n    for orig_parts in orig_reader:\n        cmp_parts = next(cmp_reader)\n        for pos in positions:\n            try:\n                pos_counts[pos][int(orig_parts[pos+1])][int(cmp_parts[pos+1])] += 1\n            except IndexError:\n                pass\n    for pos, count_dict in pos_counts.iteritems():\n        for orig_val, cmp_dict in count_dict.iteritems():\n            for cmp_val, count in cmp_dict.iteritems():\n                yield pos+1, orig_val, cmp_val, count",
    "docstring": "Combine orignal and new qualities at each position, generating counts."
  },
  {
    "code": "def command(self, func):\n        command = Command(func)\n        self._commands[func.__name__] = command\n        return func",
    "docstring": "Decorator to add a command function to the registry.\n\n        :param func: command function."
  },
  {
    "code": "def ffht(fEM, time, freq, ftarg):\n    r\n    ffhtfilt = ftarg[0]\n    pts_per_dec = ftarg[1]\n    kind = ftarg[2]\n    if pts_per_dec == 0:\n        fEM = fEM.reshape(time.size, -1)\n    tEM = dlf(fEM, 2*np.pi*freq, time, ffhtfilt, pts_per_dec, kind=kind)\n    return tEM, True",
    "docstring": "r\"\"\"Fourier Transform using the Digital Linear Filter method.\n\n\n    It follows the Filter methodology [Ande75]_, using Cosine- and\n    Sine-filters; see ``fht`` for more information.\n\n    The function is called from one of the modelling routines in :mod:`model`.\n    Consult these modelling routines for a description of the input and output\n    parameters.\n\n    This function is based on ``get_CSEM1D_TD_FHT.m`` from the source code\n    distributed with [Key12]_.\n\n    Returns\n    -------\n    tEM : array\n        Returns time-domain EM response of ``fEM`` for given ``time``.\n\n    conv : bool\n        Only relevant for QWE/QUAD."
  },
  {
    "code": "def value(self):\n        try:\n            if isinstance(self.__value, Expression):\n                return self.__value.value\n            return self.__value\n        except AttributeError:\n            return 0",
    "docstring": "Set a calculated value for this Expression.\n        Used when writing formulas using XlsxWriter to give cells\n        an initial value when the sheet is loaded without being calculated."
  },
  {
    "code": "def wait_for_event(event):\n    f = Future()\n    def ready():\n        get_event_loop().remove_win32_handle(event)\n        f.set_result(None)\n    get_event_loop().add_win32_handle(event, ready)\n    return f",
    "docstring": "Wraps a win32 event into a `Future` and wait for it."
  },
  {
    "code": "def parse_ppi_graph(path: str, min_edge_weight: float = 0.0) -> Graph:\n    logger.info(\"In parse_ppi_graph()\")\n    graph = igraph.read(os.path.expanduser(path), format=\"ncol\", directed=False, names=True)\n    graph.delete_edges(graph.es.select(weight_lt=min_edge_weight))\n    graph.delete_vertices(graph.vs.select(_degree=0))\n    logger.info(f\"Loaded PPI network.\\n\"\n                f\"Number of proteins: {len(graph.vs)}\\n\"\n                f\"Number of interactions: {len(graph.es)}\\n\")\n    return graph",
    "docstring": "Build an undirected graph of gene interactions from edgelist file.\n\n    :param str path: The path to the edgelist file\n    :param float min_edge_weight: Cutoff to keep/remove the edges, default is 0, but could also be 0.63.\n    :return Graph: Protein-protein interaction graph"
  },
  {
    "code": "def get_formatter(columns):\n    column_map = dict((column.name, column) for column in columns)\n    def validate(ctx, param, value):\n        if value == '':\n            raise click.BadParameter('At least one column is required.')\n        formatter = ColumnFormatter()\n        for column in [col.strip() for col in value.split(',')]:\n            if column in column_map:\n                formatter.add_column(column_map[column])\n            else:\n                formatter.add_column(Column(column, column.split('.')))\n        return formatter\n    return validate",
    "docstring": "This function returns a callback to use with click options.\n\n    The returned function parses a comma-separated value and returns a new\n    ColumnFormatter.\n\n    :param columns: a list of Column instances"
  },
  {
    "code": "def forward_algo(self,observations):\n        total_stages = len(observations)\n        ob_ind = self.obs_map[ observations[0] ]\n        alpha = np.multiply ( np.transpose(self.em_prob[:,ob_ind]) , self.start_prob )\n        for curr_t in range(1,total_stages):\n            ob_ind = self.obs_map[observations[curr_t]]\n            alpha = np.dot( alpha , self.trans_prob)\n            alpha = np.multiply( alpha , np.transpose( self.em_prob[:,ob_ind] ))\n        total_prob = alpha.sum()\n        return ( total_prob )",
    "docstring": "Finds the probability of an observation sequence for given model parameters\n\n        **Arguments**:\n\n        :param observations: The observation sequence, where each element belongs to 'observations' variable declared with __init__ object. \n        :type observations: A list or tuple\n\n        :return: The probability of occurence of the observation sequence\n        :rtype: float \n\n        **Example**:\n\n        >>> states = ('s', 't')\n        >>> possible_observation = ('A','B' )\n        >>> # Numpy arrays of the data\n        >>> start_probability = np.matrix( '0.5 0.5 ')\n        >>> transition_probability = np.matrix('0.6 0.4 ;  0.3 0.7 ')\n        >>> emission_probability = np.matrix( '0.3 0.7 ; 0.4 0.6 ' )\n        >>> # Initialize class object\n        >>> test = hmm(states,possible_observation,start_probability,transition_probability,emission_probability)\n        >>> observations = ('A', 'B','B','A')\n        >>> print(test.forward_algo(observations))\n\n        .. note::\n            No scaling applied here and hence this routine is susceptible to underflow errors. Use :func:`hmm.log_prob` instead."
  },
  {
    "code": "def _validate_tag_key(self, tag_key, exception_param='tags.X.member.key'):\n        if len(tag_key) > 128:\n            raise TagKeyTooBig(tag_key, param=exception_param)\n        match = re.findall(r'[\\w\\s_.:/=+\\-@]+', tag_key)\n        if not len(match) or len(match[0]) < len(tag_key):\n            raise InvalidTagCharacters(tag_key, param=exception_param)",
    "docstring": "Validates the tag key.\n\n        :param all_tags: Dict to check if there is a duplicate tag.\n        :param tag_key: The tag key to check against.\n        :param exception_param: The exception parameter to send over to help format the message. This is to reflect\n                                the difference between the tag and untag APIs.\n        :return:"
  },
  {
    "code": "def from_dict(cls, d):\n        key = d.get(\"name\")\n        options = d.get(\"options\", None)\n        subkey_list = d.get(\"subkeys\", [])\n        if len(subkey_list) > 0:\n            subkeys = list(map(lambda k: AdfKey.from_dict(k), subkey_list))\n        else:\n            subkeys = None\n        return cls(key, options, subkeys)",
    "docstring": "Construct a MSONable AdfKey object from the JSON dict.\n\n        Parameters\n        ----------\n        d : dict\n            A dict of saved attributes.\n\n        Returns\n        -------\n        adfkey : AdfKey\n            An AdfKey object recovered from the JSON dict ``d``."
  },
  {
    "code": "def _handle_hidden_tables(self, tbl_list, attr_name):\n        if not self.displayed_only:\n            return tbl_list\n        return [x for x in tbl_list if \"display:none\" not in\n                getattr(x, attr_name).get('style', '').replace(\" \", \"\")]",
    "docstring": "Return list of tables, potentially removing hidden elements\n\n        Parameters\n        ----------\n        tbl_list : list of node-like\n            Type of list elements will vary depending upon parser used\n        attr_name : str\n            Name of the accessor for retrieving HTML attributes\n\n        Returns\n        -------\n        list of node-like\n            Return type matches `tbl_list`"
  },
  {
    "code": "def unescape_code_start(source, ext, language='python'):\n    parser = StringParser(language)\n    for pos, line in enumerate(source):\n        if not parser.is_quoted() and is_escaped_code_start(line, ext):\n            unescaped = unesc(line, language)\n            if is_escaped_code_start(unescaped, ext):\n                source[pos] = unescaped\n        parser.read_line(line)\n    return source",
    "docstring": "Unescape code start"
  },
  {
    "code": "def _data_dep_init(self, inputs):\n    with tf.variable_scope(\"data_dep_init\"):\n      activation = self.layer.activation\n      self.layer.activation = None\n      x_init = self.layer.call(inputs)\n      m_init, v_init = tf.moments(x_init, self.norm_axes)\n      scale_init = 1. / tf.sqrt(v_init + 1e-10)\n    self.layer.g = self.layer.g * scale_init\n    self.layer.bias = (-m_init * scale_init)\n    self.layer.activation = activation\n    self.initialized = True",
    "docstring": "Data dependent initialization for eager execution."
  },
  {
    "code": "def _set_labels(self, catalogue):\n        with self._conn:\n            self._conn.execute(constants.UPDATE_LABELS_SQL, [''])\n            labels = {}\n            for work, label in catalogue.items():\n                self._conn.execute(constants.UPDATE_LABEL_SQL, [label, work])\n                cursor = self._conn.execute(\n                    constants.SELECT_TEXT_TOKEN_COUNT_SQL, [work])\n                token_count = cursor.fetchone()['token_count']\n                labels[label] = labels.get(label, 0) + token_count\n        return labels",
    "docstring": "Returns a dictionary of the unique labels in `catalogue` and the\n        count of all tokens associated with each, and sets the record\n        of each Text to its corresponding label.\n\n        Texts that do not have a label specified are set to the empty\n        string.\n\n        Token counts are included in the results to allow for\n        semi-accurate sorting based on corpora size.\n\n        :param catalogue: catalogue matching filenames to labels\n        :type catalogue: `Catalogue`\n        :rtype: `dict`"
  },
  {
    "code": "def read(path, encoding=\"utf-8\"):\n    with open(path, \"rb\") as f:\n        content = f.read()\n        try:\n            text = content.decode(encoding)\n        except:\n            res = chardet.detect(content)\n            text = content.decode(res[\"encoding\"])\n    return text",
    "docstring": "Auto-decoding string reader.\n\n    Usage::\n\n        >>> from angora.dataIO import textfile\n        or\n        >>> from angora.dataIO import *\n        >>> textfile.read(\"test.txt\")"
  },
  {
    "code": "def _prior_headerfooter(self):\n        preceding_sectPr = self._sectPr.preceding_sectPr\n        return (\n            None if preceding_sectPr is None\n            else _Header(preceding_sectPr, self._document_part, self._hdrftr_index)\n        )",
    "docstring": "|_Header| proxy on prior sectPr element or None if this is first section."
  },
  {
    "code": "def eye(N, M=0, k=0, ctx=None, dtype=None, **kwargs):\n    if ctx is None:\n        ctx = current_context()\n    dtype = mx_real_t if dtype is None else dtype\n    return _internal._eye(N=N, M=M, k=k, ctx=ctx, dtype=dtype, **kwargs)",
    "docstring": "Return a 2-D array with ones on the diagonal and zeros elsewhere.\n\n    Parameters\n    ----------\n    N: int\n        Number of rows in the output.\n    M: int, optional\n        Number of columns in the output. If 0, defaults to N.\n    k: int, optional\n        Index of the diagonal: 0 (the default) refers to the main diagonal,\n        a positive value refers to an upper diagonal,\n        and a negative value to a lower diagonal.\n    ctx: Context, optional\n        An optional device context (default is the current default context)\n    dtype: str or numpy.dtype, optional\n        An optional value type (default is `float32`)\n\n    Returns\n    -------\n    NDArray\n        A created array\n\n    Examples\n    --------\n    >>> mx.nd.eye(2)\n    [[ 1.  0.]\n     [ 0.  1.]]\n    <NDArray 2x2 @cpu(0)>\n    >>> mx.nd.eye(2, 3, 1)\n    [[ 0.  1.  0.]\n     [ 0.  0.  1.]]\n    <NDArray 2x3 @cpu(0)>"
  },
  {
    "code": "def get_fields_with_prop(cls, prop_key):\n        ret = []\n        for key, val in getattr(cls, '_fields').items():\n            if hasattr(val, prop_key):\n                ret.append((key, getattr(val, prop_key)))\n        return ret",
    "docstring": "Return a list of fields with a prop key defined\n\n        Each list item will be a tuple of field name containing\n        the prop key & the value of that prop key.\n\n        :param prop_key: key name\n        :return: list of tuples"
  },
  {
    "code": "def rst_to_html(in_rst, stderr):\n  if not in_rst:\n    return '', 0\n  orig_sys_exit = sys.exit\n  orig_sys_stderr = sys.stderr\n  returncodes = []\n  try:\n    sys.exit = returncodes.append\n    sys.stderr = stderr\n    pp = publish_parts(in_rst,\n                       writer_name='html',\n                       settings_overrides=dict(exit_status_level=2, report_level=2),\n                       enable_exit_status=True)\n  finally:\n    sys.exit = orig_sys_exit\n    sys.stderr = orig_sys_stderr\n  return_value = ''\n  if 'title' in pp and pp['title']:\n    return_value += '<title>{0}</title>\\n<p style=\"font: 200% bold\">{0}</p>\\n'.format(pp['title'])\n  return_value += pp['body'].strip()\n  return return_value, returncodes.pop() if returncodes else 0",
    "docstring": "Renders HTML from an RST fragment.\n\n  :param string in_rst: An rst formatted string.\n  :param stderr: An open stream to use for docutils stderr output.\n  :returns: A tuple of (html rendered rst, return code)"
  },
  {
    "code": "def in_(self, qfield, *values):\n        qfield = resolve_name(self.type, qfield)\n        self.filter(QueryExpression({ qfield : { '$in' : [qfield.wrap_value(value) for value in values]}}))\n        return self",
    "docstring": "Check to see that the value of ``qfield`` is one of ``values``\n\n            :param qfield: Instances of :class:`ommongo.query_expression.QueryExpression`\n            :param values: Values should be python values which ``qfield`` \\\n                understands"
  },
  {
    "code": "def hex2pub(pub_hex: str) -> PublicKey:\n    uncompressed = decode_hex(pub_hex)\n    if len(uncompressed) == 64:\n        uncompressed = b\"\\x04\" + uncompressed\n    return PublicKey(uncompressed)",
    "docstring": "Convert ethereum hex to EllipticCurvePublicKey\n    The hex should be 65 bytes, but ethereum public key only has 64 bytes\n    So have to add \\x04\n\n    Parameters\n    ----------\n    pub_hex: str\n        Ethereum public key hex string\n\n    Returns\n    -------\n    coincurve.PublicKey\n        A secp256k1 public key calculated from ethereum public key hex string\n\n    >>> data = b'0'*32\n    >>> data_hash = sha256(data)\n    >>> eth_prv = generate_eth_key()\n    >>> cc_prv = hex2prv(eth_prv.to_hex())\n    >>> eth_prv.sign_msg_hash(data_hash).to_bytes() == cc_prv.sign_recoverable(data)\n    True\n    >>> pubhex = eth_prv.public_key.to_hex()\n    >>> computed_pub = hex2pub(pubhex)\n    >>> computed_pub == cc_prv.public_key\n    True"
  },
  {
    "code": "def _getNextArticleBatch(self):\n        self._articlePage += 1\n        if self._totalPages != None and self._articlePage > self._totalPages:\n            return\n        self.setRequestedResult(RequestArticlesInfo(page=self._articlePage,\n            sortBy=self._sortBy, sortByAsc=self._sortByAsc,\n            returnInfo = self._returnInfo))\n        if self._er._verboseOutput:\n            print(\"Downloading article page %d...\" % (self._articlePage))\n        res = self._er.execQuery(self)\n        if \"error\" in res:\n            print(\"Error while obtaining a list of articles: \" + res[\"error\"])\n        else:\n            self._totalPages = res.get(\"articles\", {}).get(\"pages\", 0)\n        results = res.get(\"articles\", {}).get(\"results\", [])\n        self._articleList.extend(results)",
    "docstring": "download next batch of articles based on the article uris in the uri list"
  },
  {
    "code": "def _resolve_base_image(self, build_json):\n        spec = build_json.get(\"spec\")\n        try:\n            image_id = spec['triggeredBy'][0]['imageChangeBuild']['imageID']\n        except (TypeError, KeyError, IndexError):\n            base_image = self.workflow.builder.base_image\n            self.log.info(\"using %s as base image.\", base_image)\n        else:\n            self.log.info(\"using %s from build spec[triggeredBy] as base image.\", image_id)\n            base_image = ImageName.parse(image_id)\n        return base_image",
    "docstring": "If this is an auto-rebuild, adjust the base image to use the triggering build"
  },
  {
    "code": "def _serialize_datetime(value):\n    if not isinstance(value, (datetime, arrow.Arrow)):\n        raise ValueError(u'The received object was not a datetime: '\n                         u'{} {}'.format(type(value), value))\n    return value.isoformat()",
    "docstring": "Serialize a DateTime object to its proper ISO-8601 representation."
  },
  {
    "code": "def go_to_parent_directory(self):\r\n        self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))",
    "docstring": "Go to parent directory"
  },
  {
    "code": "def get_search_fields(self):\n        if self.search_fields:\n            return self.search_fields\n        raise NotImplementedError('%s, must implement \"search_fields\".' % self.__class__.__name__)",
    "docstring": "Return list of lookup names."
  },
  {
    "code": "def make_node(\n        op_type,\n        inputs,\n        outputs,\n        name=None,\n        doc_string=None,\n        domain=None,\n        **kwargs\n):\n    node = NodeProto()\n    node.op_type = op_type\n    node.input.extend(inputs)\n    node.output.extend(outputs)\n    if name:\n        node.name = name\n    if doc_string:\n        node.doc_string = doc_string\n    if domain is not None:\n        node.domain = domain\n    if kwargs:\n        node.attribute.extend(\n            make_attribute(key, value)\n            for key, value in sorted(kwargs.items()))\n    return node",
    "docstring": "Construct a NodeProto.\n\n    Arguments:\n        op_type (string): The name of the operator to construct\n        inputs (list of string): list of input names\n        outputs (list of string): list of output names\n        name (string, default None): optional unique identifier for NodeProto\n        doc_string (string, default None): optional documentation string for NodeProto\n        domain (string, default None): optional domain for NodeProto.\n            If it's None, we will just use default domain (which is empty)\n        **kwargs (dict): the attributes of the node.  The acceptable values\n            are documented in :func:`make_attribute`."
  },
  {
    "code": "def add(self, item):\n        check_not_none(item, \"Value can't be None\")\n        element_data = self._to_data(item)\n        return self._encode_invoke(list_add_codec, value=element_data)",
    "docstring": "Adds the specified item to the end of this list.\n\n        :param item: (object), the specified item to be appended to this list.\n        :return: (bool), ``true`` if item is added, ``false`` otherwise."
  },
  {
    "code": "def iter_followers(self, login=None, number=-1, etag=None):\n        if login:\n            return self.user(login).iter_followers()\n        return self._iter_follow('followers', int(number), etag=etag)",
    "docstring": "If login is provided, iterate over a generator of followers of that\n        login name; otherwise return a generator of followers of the\n        authenticated user.\n\n        :param str login: (optional), login of the user to check\n        :param int number: (optional), number of followers to return. Default:\n            -1 returns all followers\n        :param str etag: (optional), ETag from a previous request to the same\n            endpoint\n        :returns: generator of :class:`User <github3.users.User>`\\ s"
  },
  {
    "code": "def _SetYaraRules(self, yara_rules_string):\n    if not yara_rules_string:\n      return\n    analyzer_object = analyzers_manager.AnalyzersManager.GetAnalyzerInstance(\n        'yara')\n    analyzer_object.SetRules(yara_rules_string)\n    self._analyzers.append(analyzer_object)",
    "docstring": "Sets the Yara rules.\n\n    Args:\n      yara_rules_string (str): unparsed Yara rule definitions."
  },
  {
    "code": "def _strip_colors(self, message: str) -> str:\n        for c in self.COLORS:\n            message = message.replace(c, \"\")\n        return message",
    "docstring": "Remove all of the color tags from this message."
  },
  {
    "code": "def to_dict(self):\n        return {\"name\": self.table_name, \"kind\": self.table_kind, \"data\": [r.to_dict() for r in self]}",
    "docstring": "Converts the table to a dict."
  },
  {
    "code": "def remove_record(self, record):\n        assert self.has_record(record)\n        record['_oai']['sets'] = [\n            s for s in record['_oai']['sets'] if s != self.spec]",
    "docstring": "Remove a record from the OAISet.\n\n        :param record: Record to be removed.\n        :type record: `invenio_records.api.Record` or derivative."
  },
  {
    "code": "def union(cls):\n  assert isinstance(cls, type)\n  return type(cls.__name__, (cls,), {\n    '_is_union': True,\n  })",
    "docstring": "A class decorator which other classes can specify that they can resolve to with `UnionRule`.\n\n  Annotating a class with @union allows other classes to use a UnionRule() instance to indicate that\n  they can be resolved to this base union class. This class will never be instantiated, and should\n  have no members -- it is used as a tag only, and will be replaced with whatever object is passed\n  in as the subject of a `yield Get(...)`. See the following example:\n\n  @union\n  class UnionBase(object): pass\n\n  @rule(B, [X])\n  def get_some_union_type(x):\n    result = yield Get(ResultType, UnionBase, x.f())\n    # ...\n\n  If there exists a single path from (whatever type the expression `x.f()` returns) -> `ResultType`\n  in the rule graph, the engine will retrieve and execute that path to produce a `ResultType` from\n  `x.f()`. This requires also that whatever type `x.f()` returns was registered as a union member of\n  `UnionBase` with a `UnionRule`.\n\n  Unions allow @rule bodies to be written without knowledge of what types may eventually be provided\n  as input -- rather, they let the engine check that there is a valid path to the desired result."
  },
  {
    "code": "def create_client():\n    result = False\n    if g.client_id in drivers:\n        result = True\n    return jsonify({'Success': result})",
    "docstring": "Create a new client driver. The driver is automatically created in \n    before_request function."
  },
  {
    "code": "def provider(self, value):\n        result = None\n        defaulted_value = value or ProviderArchitecture.DEFAULT\n        try:\n            parsed_value = int(defaulted_value)\n        except ValueError:\n            pass\n        else:\n            if parsed_value in ProviderArchitecture:\n                result = parsed_value\n        if result is None:\n            self.logger.error(u\"Invalid '%s' WMI Provider Architecture. The parameter is ignored.\", value)\n        self._provider = result or ProviderArchitecture.DEFAULT",
    "docstring": "Validate and set a WMI provider. Default to `ProviderArchitecture.DEFAULT`"
  },
  {
    "code": "def get_if_set(self, addresses):\n        with self._lock:\n            results = []\n            for add in addresses:\n                results.append(self._get_if_set(add))\n            return results",
    "docstring": "Returns the value set in this context, or None, for each address in\n        addresses.\n\n        Args:\n            addresses (list of str): The addresses to return values for, if set\n                within this context.\n\n        Returns:\n            (list): bytes set at the address or None"
  },
  {
    "code": "def remove(self, oid):\n        port = self.lookup_by_oid(oid)\n        adapter = self.parent\n        if 'network-port-uris' in adapter.properties:\n            port_uris = adapter.properties['network-port-uris']\n            port_uris.remove(port.uri)\n        if 'storage-port-uris' in adapter.properties:\n            port_uris = adapter.properties['storage-port-uris']\n            port_uris.remove(port.uri)\n        super(FakedPortManager, self).remove(oid)",
    "docstring": "Remove a faked Port resource.\n\n        This method also updates the 'network-port-uris' or 'storage-port-uris'\n        property in the parent Adapter resource, by removing the URI for the\n        faked Port resource.\n\n        Parameters:\n\n          oid (string):\n            The object ID of the faked Port resource."
  },
  {
    "code": "def sort_aliases(self, aliases):\n        self._cache_init()\n        if not aliases:\n            return aliases\n        parent_aliases = self._cache_get_entry(self.CACHE_NAME_PARENTS).keys()\n        return [parent_alias for parent_alias in parent_aliases if parent_alias in aliases]",
    "docstring": "Sorts the given aliases list, returns a sorted list.\n\n        :param list aliases:\n        :return: sorted aliases list"
  },
  {
    "code": "def get_instance(self, payload):\n        return DocumentInstance(self._version, payload, service_sid=self._solution['service_sid'], )",
    "docstring": "Build an instance of DocumentInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.preview.sync.service.document.DocumentInstance\n        :rtype: twilio.rest.preview.sync.service.document.DocumentInstance"
  },
  {
    "code": "def sbo_case_insensitive(self):\n        if \"--case-ins\" in self.flag:\n            data = SBoGrep(name=\"\").names()\n            data_dict = Utils().case_sensitive(data)\n            for key, value in data_dict.iteritems():\n                if key == self.name.lower():\n                    self.name = value",
    "docstring": "Matching packages distinguish between uppercase and\n        lowercase for sbo repository"
  },
  {
    "code": "def release(self):\n        \"increment the counter, waking up a waiter if there was any\"\n        if self._waiters:\n            scheduler.state.awoken_from_events.add(self._waiters.popleft())\n        else:\n            self._value += 1",
    "docstring": "increment the counter, waking up a waiter if there was any"
  },
  {
    "code": "def _center_tile(self, position, size):\n        x, y = position\n        w, h = size\n        return x + (self.cell_width - w) / 2, y + (self.cell_height - h) / 2",
    "docstring": "Calculate the centre of a tile given the top-left corner and the size of the image."
  },
  {
    "code": "def subgraph(graph, nodes: Iterable[BaseEntity]):\n    sg = graph.subgraph(nodes)\n    result = graph.fresh_copy()\n    result.graph.update(sg.graph)\n    for node, data in sg.nodes(data=True):\n        result.add_node(node, **data)\n    result.add_edges_from(\n        (u, v, key, datadict.copy())\n        for u, v, key, datadict in sg.edges(keys=True, data=True)\n    )\n    return result",
    "docstring": "Induce a sub-graph over the given nodes.\n\n    :rtype: BELGraph"
  },
  {
    "code": "def get_task(task_id, completed=True):\n    tasks = get_tasks(task_id=task_id, completed=completed)\n    if len(tasks) == 0:\n        return None\n    assert len(tasks) == 1, 'get_task should return at max 1 task for a task id'\n    return tasks[0]",
    "docstring": "Get a task by task id where a task_id is required.\n\n        :param task_id: task ID\n        :type task_id: str\n        :param completed: include completed tasks?\n        :type completed: bool\n\n        :return: a task\n        :rtype: obj"
  },
  {
    "code": "def get_session_identifiers(cls, folder=None, inputfile=None):\n        sessions = []\n        if folder is None or not os.path.isdir(folder):\n            return sessions\n        for root, dirs, files in os.walk(folder):\n            for filename in files:\n                if filename.startswith('Session ') \\\n                        and filename.endswith('.mqo'):\n                    session = filename.split()[1]\n                    if session not in sessions:\n                        sessions.append(session)\n        return sessions",
    "docstring": "Retrieve the list of session identifiers contained in the\n        data on the folder.\n\n        :kwarg folder: the path to the folder containing the files to\n            check. This folder may contain sub-folders.\n        :kwarg inputfile: the path to the input file to use"
  },
  {
    "code": "def AddLeafNodes(self, prefix, node):\n    if not node:\n      self.AddPath(prefix)\n    for name in node:\n      child_path = prefix + '.' + name\n      self.AddLeafNodes(child_path, node[name])",
    "docstring": "Adds leaf nodes begin with prefix to this tree."
  },
  {
    "code": "def set_window_title(self):\r\n        if DEV is not None:\r\n            title = u\"Spyder %s (Python %s.%s)\" % (__version__,\r\n                                                   sys.version_info[0],\r\n                                                   sys.version_info[1])\r\n        else:\r\n            title = u\"Spyder (Python %s.%s)\" % (sys.version_info[0],\r\n                                                sys.version_info[1])\r\n        if get_debug_level():\r\n            title += u\" [DEBUG MODE %d]\" % get_debug_level()\r\n        if self.window_title is not None:\r\n            title += u' -- ' + to_text_string(self.window_title)\r\n        if self.projects is not None:\r\n            path = self.projects.get_active_project_path()\r\n            if path:\r\n                path = path.replace(get_home_dir(), u'~')\r\n                title = u'{0} - {1}'.format(path, title)\r\n        self.base_title = title\r\n        self.setWindowTitle(self.base_title)",
    "docstring": "Set window title."
  },
  {
    "code": "def _file_write(path, content):\n    with salt.utils.files.fopen(path, 'w+') as fp_:\n        fp_.write(salt.utils.stringutils.to_str(content))\n    fp_.close()",
    "docstring": "Write content to a file"
  },
  {
    "code": "def list(self):\n        for i in range(len(self.sections)):\n            self.sections[i].list(walkTrace=(i+1,))",
    "docstring": "Get an overview of the report content list"
  },
  {
    "code": "def AdaptiveOpticsCorrect(pupils,diameter,maxRadial,numRemove=None):\n    gridSize=pupils.shape[-1]\n    pupilsVector=np.reshape(pupils,(-1,gridSize**2))\n    zernikes=np.reshape(ZernikeGrid(gridSize,maxRadial,diameter),(-1,gridSize**2))\n    if numRemove is None: numRemove=zernikes.shape[0]\n    numScreen=pupilsVector.shape[0]\n    normalisation=1.0/np.sum(zernikes[0])\n    for i in list(range(numRemove))+[0,]:\n        amplitudes=np.inner(zernikes[i],pupilsVector)*normalisation\n        pupilsVector=pupilsVector-zernikes[i]*amplitudes[:,np.newaxis]\n    return np.reshape(pupilsVector,pupils.shape)",
    "docstring": "Correct a wavefront using Zernike rejection up to some maximal order. \n    Can operate on multiple telescopes in parallel.\n    Note that this version removes the piston mode as well"
  },
  {
    "code": "def add_tokens_for_group(self, with_pass=False):\n        kls = self.groups.super_kls\n        name = self.groups.kls_name\n        self.reset_indentation('')\n        self.result.extend(self.tokens.make_describe(kls, name))\n        if with_pass:\n            self.add_tokens_for_pass()\n        self.groups.finish_signature()",
    "docstring": "Add the tokens for the group signature"
  },
  {
    "code": "def _append_base_arguments(self):\n        if self.exc and self.only:\n            raise PackerException('Cannot provide both \"except\" and \"only\"')\n        elif self.exc:\n            self._add_opt('-except={0}'.format(self._join_comma(self.exc)))\n        elif self.only:\n            self._add_opt('-only={0}'.format(self._join_comma(self.only)))\n        for var, value in self.vars.items():\n            self._add_opt(\"-var\")\n            self._add_opt(\"{0}={1}\".format(var, value))\n        if self.var_file:\n            self._add_opt('-var-file={0}'.format(self.var_file))",
    "docstring": "Appends base arguments to packer commands.\n\n        -except, -only, -var and -var-file are appeneded to almost\n        all subcommands in packer. As such this can be called to add\n        these flags to the subcommand."
  },
  {
    "code": "def remove_profile(self):\n        profile_name = self.profile_combo.currentText()\n        button_selected = QMessageBox.warning(\n            None,\n            'Remove Profile',\n            self.tr('Remove %s.') % profile_name,\n            QMessageBox.Ok,\n            QMessageBox.Cancel\n        )\n        if button_selected == QMessageBox.Ok:\n            self.profile_combo.removeItem(\n                self.profile_combo.currentIndex()\n            )\n            self.minimum_needs.remove_profile(profile_name)\n            self.select_profile(self.profile_combo.currentIndex())",
    "docstring": "Remove the current profile.\n\n        Make sure the user is sure."
  },
  {
    "code": "def max_spline_jump(self):\n        sp = self.spline()\n        return max(self.energies - sp(range(len(self.energies))))",
    "docstring": "Get maximum difference between spline and energy trend."
  },
  {
    "code": "def status(self, name=''):\n        super(SystemD, self).status(name=name)\n        svc_list = sh.systemctl('--no-legend', '--no-pager', t='service')\n        svcs_info = [self._parse_service_info(svc) for svc in svc_list]\n        if name:\n            names = (name, name + '.service')\n            svcs_info = [s for s in svcs_info if s['name'] in names]\n        self.services['services'] = svcs_info\n        return self.services",
    "docstring": "Return a list of the statuses of the `name` service, or\n        if name is omitted, a list of the status of all services for this\n        specific init system.\n\n        There should be a standardization around the status fields.\n        There currently isn't.\n\n        `self.services` is set in `base.py`"
  },
  {
    "code": "def get_xsession(self, item):\n        subj_label, sess_label = self._get_item_labels(item)\n        with self:\n            xproject = self._login.projects[self.project_id]\n            try:\n                xsubject = xproject.subjects[subj_label]\n            except KeyError:\n                xsubject = self._login.classes.SubjectData(\n                    label=subj_label, parent=xproject)\n            try:\n                xsession = xsubject.experiments[sess_label]\n            except KeyError:\n                xsession = self._login.classes.MrSessionData(\n                    label=sess_label, parent=xsubject)\n                if item.derived:\n                    xsession.fields[\n                        self.DERIVED_FROM_FIELD] = self._get_item_labels(\n                            item, no_from_study=True)[1]\n        return xsession",
    "docstring": "Returns the XNAT session and cache dir corresponding to the\n        item."
  },
  {
    "code": "def find_entry(self, entry, exact=True):\n        if exact:\n            self.log([u\"Finding entry '%s' with exact=True\", entry])\n            if entry in self.entries:\n                self.log([u\"Found entry '%s'\", entry])\n                return entry\n        else:\n            self.log([u\"Finding entry '%s' with exact=False\", entry])\n            for ent in self.entries:\n                if os.path.basename(ent) == entry:\n                    self.log([u\"Found entry '%s'\", ent])\n                    return ent\n        self.log([u\"Entry '%s' not found\", entry])\n        return None",
    "docstring": "Return the full path to the first entry whose file name equals\n        the given ``entry`` path.\n\n        Return ``None`` if the entry cannot be found.\n\n        If ``exact`` is ``True``, the path must be exact,\n        otherwise the comparison is done only on the file name.\n\n        Example: ::\n\n            entry = \"config.txt\"\n\n        matches: ::\n\n            config.txt            (if exact == True or exact == False)\n            foo/config.txt        (if exact == False)\n            foo/bar/config.txt    (if exact == False)\n\n        :param string entry: the entry name to be searched for\n        :param bool exact: look for the exact entry path\n        :rtype: string\n        :raises: same as :func:`~aeneas.container.Container.entries`"
  },
  {
    "code": "def from_pb(cls, cell_pb):\n        if cell_pb.labels:\n            return cls(cell_pb.value, cell_pb.timestamp_micros, labels=cell_pb.labels)\n        else:\n            return cls(cell_pb.value, cell_pb.timestamp_micros)",
    "docstring": "Create a new cell from a Cell protobuf.\n\n        :type cell_pb: :class:`._generated.data_pb2.Cell`\n        :param cell_pb: The protobuf to convert.\n\n        :rtype: :class:`Cell`\n        :returns: The cell corresponding to the protobuf."
  },
  {
    "code": "def search_files(source: str, extensions: List[str]) -> List[Path]:\n    files = [\n        path for path in Path(source).glob('**/*')\n        if path.is_file() and path.suffix.lstrip('.') in extensions]\n    nb_files = len(files)\n    LOGGER.debug(\"Total files found: %d\", nb_files)\n    if nb_files < NB_FILES_MIN:\n        LOGGER.error(\"Too few source files\")\n        raise GuesslangError(\n            '{} source files found in {}. {} files minimum is required'.format(\n                nb_files, source, NB_FILES_MIN))\n    random.shuffle(files)\n    return files",
    "docstring": "Retrieve files located the source directory and its subdirectories,\n    whose extension match one of the listed extensions.\n\n    :raise GuesslangError: when there is not enough files in the directory\n    :param source: directory name\n    :param extensions: list of file extensions\n    :return: filenames"
  },
  {
    "code": "def getAttribute(self, attr: str) -> _AttrValueType:\n        if attr == 'class':\n            if self.classList:\n                return self.classList.toString()\n            return None\n        attr_node = self.getAttributeNode(attr)\n        if attr_node is None:\n            return None\n        return attr_node.value",
    "docstring": "Get attribute of this node as string format.\n\n        If this node does not have ``attr``, return None."
  },
  {
    "code": "def save_function(elements, module_path):\n    for elem, signature in elements.items():\n        if isinstance(signature, dict):\n            save_function(signature, module_path + (elem,))\n        elif signature.isstaticfunction():\n            functions.setdefault(elem, []).append((module_path, signature,))\n        elif isinstance(signature, Class):\n            save_function(signature.fields, module_path + (elem,))",
    "docstring": "Recursively save functions with module name and signature."
  },
  {
    "code": "def format_time(x):\n    if isinstance(x, (datetime64, datetime)):\n        return format_timestamp(x)\n    elif isinstance(x, (timedelta64, timedelta)):\n        return format_timedelta(x)\n    elif isinstance(x, ndarray):\n        return list(x) if x.ndim else x[()]\n    return x",
    "docstring": "Formats date values\n\n    This function formats :class:`datetime.datetime` and\n    :class:`datetime.timedelta` objects (and the corresponding numpy objects)\n    using the :func:`xarray.core.formatting.format_timestamp` and the\n    :func:`xarray.core.formatting.format_timedelta` functions.\n\n    Parameters\n    ----------\n    x: object\n        The value to format. If not a time object, the value is returned\n\n    Returns\n    -------\n    str or `x`\n        Either the formatted time object or the initial `x`"
  },
  {
    "code": "def _generate_arg_types(coordlist_length, shape_name):\n    from .ds9_region_parser import ds9_shape_defs\n    from .ds9_attr_parser import ds9_shape_in_comment_defs\n    if shape_name in ds9_shape_defs:\n        shape_def = ds9_shape_defs[shape_name]\n    else:\n        shape_def = ds9_shape_in_comment_defs[shape_name]\n    initial_arg_types = shape_def.args_list\n    arg_repeats = shape_def.args_repeat\n    if arg_repeats is None:\n        return initial_arg_types\n    n1, n2 = arg_repeats\n    arg_types = list(initial_arg_types[:n1])\n    num_of_repeats = coordlist_length - (len(initial_arg_types) - n2)\n    arg_types.extend((num_of_repeats - n1) //\n                     (n2 - n1) * initial_arg_types[n1:n2])\n    arg_types.extend(initial_arg_types[n2:])\n    return arg_types",
    "docstring": "Find coordinate types based on shape name and coordlist length\n\n    This function returns a list of coordinate types based on which\n    coordinates can be repeated for a given type of shap\n\n    Parameters\n    ----------\n    coordlist_length : int\n        The number of coordinates or arguments used to define the shape.\n\n    shape_name : str\n        One of the names in `pyregion.ds9_shape_defs`.\n\n    Returns\n    -------\n    arg_types : list\n        A list of objects from `pyregion.region_numbers` with a length equal to\n        coordlist_length."
  },
  {
    "code": "def _assign_as_root(self, id_):\n        rfc = self._ras.get_relationship_form_for_create(self._phantom_root_id, id_, [])\n        rfc.set_display_name('Implicit Root to ' + str(id_) + ' Parent-Child Relationship')\n        rfc.set_description(self._relationship_type.get_display_name().get_text() + ' relationship for implicit root and child: ' + str(id_))\n        rfc.set_genus_type(self._relationship_type)\n        self._ras.create_relationship(rfc)",
    "docstring": "Assign an id_ a root object in the hierarchy"
  },
  {
    "code": "def j9urlGenerator(nameDict = False):\n    start = \"https://images.webofknowledge.com/images/help/WOS/\"\n    end = \"_abrvjt.html\"\n    if nameDict:\n        urls = {\"0-9\" : start + \"0-9\" + end}\n        for c in string.ascii_uppercase:\n            urls[c] = start + c + end\n    else:\n        urls = [start + \"0-9\" + end]\n        for c in string.ascii_uppercase:\n            urls.append(start + c + end)\n    return urls",
    "docstring": "How to get all the urls for the WOS Journal Title Abbreviations. Each is varies by only a few characters. These are the currently in use urls they may change.\n\n    They are of the form:\n\n    > \"https://images.webofknowledge.com/images/help/WOS/{VAL}_abrvjt.html\"\n    > Where {VAL} is a capital letter or the string \"0-9\"\n\n    # Returns\n\n    `list[str]`\n\n    > A list of all the url's strings"
  },
  {
    "code": "def translate(self, text):\n        self.count = 0\n        return self._make_regex().sub(self, text)",
    "docstring": "Translate text, returns the modified text."
  },
  {
    "code": "def parse_access_token(self):\n        access_file = os.path.join(self.file_path, 'access_token')\n        if os.path.isfile(access_file):\n            access_list = list()\n            with open(access_file, 'r') as access_token:\n                for line in access_token:\n                    value, data = line.split('=')\n                    access_list.append(data.rstrip())\n            self.access_secret = access_list[0]\n            self.access_token = access_list[1]\n        else:\n            print('Missing access_token')\n            self.get_request_token()\n            self.get_access_token()",
    "docstring": "Extract the secret and token values from the access_token file"
  },
  {
    "code": "def parse_string(self):\n        aliased_value = LITERAL_ALIASES.get(self.current_token.value.lower())\n        if aliased_value is not None:\n            return aliased_value\n        return String(self.current_token.value)",
    "docstring": "Parse a regular unquoted string from the token stream."
  },
  {
    "code": "async def create_server(self, worker, protocol_factory, address=None,\n                            sockets=None, idx=0):\n        cfg = self.cfg\n        max_requests = cfg.max_requests\n        if max_requests:\n            max_requests = int(lognormvariate(log(max_requests), 0.2))\n        server = self.server_factory(\n            protocol_factory,\n            loop=worker._loop,\n            max_requests=max_requests,\n            keep_alive=cfg.keep_alive,\n            name=self.name,\n            logger=self.logger,\n            server_software=cfg.server_software,\n            cfg=cfg,\n            idx=idx\n        )\n        for event in ('connection_made', 'pre_request', 'post_request',\n                      'connection_lost'):\n            callback = getattr(cfg, event)\n            if callback != pass_through:\n                server.event(event).bind(callback)\n        await server.start_serving(\n            sockets=sockets,\n            address=address,\n            backlog=cfg.backlog,\n            sslcontext=self.sslcontext()\n        )\n        return server",
    "docstring": "Create the Server which will listen for requests.\n\n        :return: a :class:`.TcpServer`."
  },
  {
    "code": "def _lincomb(self, a, x1, b, x2, out):\n        _lincomb_impl(a, x1, b, x2, out)",
    "docstring": "Implement the linear combination of ``x1`` and ``x2``.\n\n        Compute ``out = a*x1 + b*x2`` using optimized\n        BLAS routines if possible.\n\n        This function is part of the subclassing API. Do not\n        call it directly.\n\n        Parameters\n        ----------\n        a, b : `TensorSpace.field` element\n            Scalars to multiply ``x1`` and ``x2`` with.\n        x1, x2 : `NumpyTensor`\n            Summands in the linear combination.\n        out : `NumpyTensor`\n            Tensor to which the result is written.\n\n        Examples\n        --------\n        >>> space = odl.rn(3)\n        >>> x = space.element([0, 1, 1])\n        >>> y = space.element([0, 0, 1])\n        >>> out = space.element()\n        >>> result = space.lincomb(1, x, 2, y, out)\n        >>> result\n        rn(3).element([ 0.,  1.,  3.])\n        >>> result is out\n        True"
  },
  {
    "code": "def cached(func):\n    cache = {}\n    @f.wraps(func)\n    def wrapper(*args, **kwargs):\n        key = func.__name__ + str(sorted(args)) + str(sorted(kwargs.items()))\n        if key not in cache:\n            cache[key] = func(*args, **kwargs)\n        return cache[key]\n    return wrapper",
    "docstring": "A decorator function to cache values. It uses the decorated\n    function's arguments as the keys to determine if the function\n    has been called previously."
  },
  {
    "code": "def _list_nodes(call=None):\n    local = salt.client.LocalClient()\n    ret = local.cmd('salt-cloud:driver:vagrant', 'grains.items', '', tgt_type='grain')\n    return ret",
    "docstring": "List the nodes, ask all 'vagrant' minions, return dict of grains."
  },
  {
    "code": "def get_all_importing_namespace_hashes( self ):\n        cur = self.db.cursor()\n        namespace_hashes = namedb_get_all_importing_namespace_hashes( cur, self.lastblock )\n        return namespace_hashes",
    "docstring": "Get the set of all preordered and revealed namespace hashes that have not expired."
  },
  {
    "code": "def get(self, url, status):\n        crl = self.cobj\n        try:\n            crl.setopt(pycurl.URL, url)\n        except UnicodeEncodeError:\n            crl.setopt(pycurl.URL, url.encode('utf-8'))\n        if not self.silent:\n            print(status, file=sys.stderr)\n        if self.DISABLED:\n            print(\"Requests DISABLED\", file=sys.stderr)\n        else:\n            return self.curl_perform(crl)",
    "docstring": "in favor of python-requests for speed"
  },
  {
    "code": "def _include_term_list(self, termlist):\n        ref_needed = False\n        for term in termlist:\n            ref_needed = ref_needed or self._include_term(term)\n        return ref_needed",
    "docstring": "Add terms from a TermList to the ontology."
  },
  {
    "code": "def __remove_service(self, key, service):\n        try:\n            prop_services = self._future_value[key]\n            prop_services.remove(service)\n            if not prop_services:\n                del self._future_value[key]\n        except KeyError:\n            pass",
    "docstring": "Removes the given service from the future dictionary\n\n        :param key: Dictionary key\n        :param service: Service to remove from the dictionary"
  },
  {
    "code": "def isdir(self, path):\n        try:\n            self.remote_context.check_output([\"test\", \"-d\", path])\n        except subprocess.CalledProcessError as e:\n            if e.returncode == 1:\n                return False\n            else:\n                raise\n        return True",
    "docstring": "Return `True` if directory at `path` exist, False otherwise."
  },
  {
    "code": "def get_currency_symbol(self):\n        locale = locales.getLocale('en')\n        setup = api.get_setup()\n        currency = setup.getCurrency()\n        return locale.numbers.currencies[currency].symbol",
    "docstring": "Get the currency Symbol"
  },
  {
    "code": "def _make_summary_tables(self):\n        try:\n            self._Bhat\n        except:\n            raise Exception(\"Regression hasn't been fit yet.  run .fit()\")\n        else:\n            num_pcs = self._basis_object.get_params()['num_components']\n            total_dof = self._X.shape[0] - self._X.shape[1] - num_pcs\n            if total_dof <= 0.0:\n                raise ValueError(\"degrees of freedom <= 0, Hotellings T2 not defined\")\n            cat_table = self._catalog_object.get_params().items()\n            bas_table = self._basis_object.get_params().items()\n            print tabulate(cat_table+bas_table,tablefmt='plain')\n            headers = self._results[0]\n            table   = self._results[1:]\n            print tabulate(table, headers, tablefmt=\"rst\")\n            print \"Formula Used: %s\" % self._designmatrix_object._formula\n            print \"Degrees of Freedom (n - p - k): %s\" % str(total_dof)\n            print \"Condition Number of X^T*X: %.2f\" % np.linalg.cond(np.dot(self._X.T, self._X))",
    "docstring": "prints the summary of the regression.  It shows\n        the waveform metadata, diagnostics of the fit, and results of the\n        hypothesis tests for each comparison encoded in the design matrix"
  },
  {
    "code": "def _get_full_paths(fastq_dir, config, config_file):\n    if fastq_dir:\n        fastq_dir = utils.add_full_path(fastq_dir)\n    config_dir = utils.add_full_path(os.path.dirname(config_file))\n    galaxy_config_file = utils.add_full_path(config.get(\"galaxy_config\", \"universe_wsgi.ini\"),\n                                             config_dir)\n    return fastq_dir, os.path.dirname(galaxy_config_file), config_dir",
    "docstring": "Retrieve full paths for directories in the case of relative locations."
  },
  {
    "code": "def to_glyphs_family_user_data_from_ufo(self, ufo):\n    target_user_data = self.font.userData\n    try:\n        for key, value in ufo.lib[FONT_USER_DATA_KEY].items():\n            if key not in target_user_data.keys():\n                target_user_data[key] = value\n    except KeyError:\n        pass",
    "docstring": "Set the GSFont userData from the UFO family-wide lib data."
  },
  {
    "code": "def sentinel2_toa_cloud_mask(input_img):\n    qa_img = input_img.select(['QA60'])\n    cloud_mask = qa_img.rightShift(10).bitwiseAnd(1).neq(0)\\\n        .Or(qa_img.rightShift(11).bitwiseAnd(1).neq(0))\n    return cloud_mask.Not()",
    "docstring": "Extract cloud mask from the Sentinel 2 TOA QA60 band\n\n    Parameters\n    ----------\n    input_img : ee.Image\n        Image from the COPERNICUS/S2 collection with a QA60 band.\n\n    Returns\n    -------\n    ee.Image\n\n    Notes\n    -----\n    Output image is structured to be applied directly with updateMask()\n        i.e. 0 is cloud, 1 is cloud free\n\n    Bits\n        10: Opaque clouds present\n        11: Cirrus clouds present\n\n    The Sentinel 2 TOA and SR cloud masks functions are currently identical\n\n    References\n    ----------\n    https://sentinel.esa.int/documents/247904/685211/Sentinel-2_User_Handbook\n    https://sentinel.esa.int/web/sentinel/technical-guides/sentinel-2-msi/level-1c/cloud-masks"
  },
  {
    "code": "def list_route_advertised_from_bgp_speaker(self, speaker_id, **_params):\n        return self.get((self.bgp_speaker_path % speaker_id) +\n                        \"/get_advertised_routes\", params=_params)",
    "docstring": "Fetches a list of all routes advertised by BGP speaker."
  },
  {
    "code": "def generate_airflow_spec(name, pipeline_spec):\n    task_definitions = ''\n    up_steam_statements = ''\n    parameters = pipeline_spec.get('parameters')\n    for (task_id, task_details) in sorted(pipeline_spec['tasks'].items()):\n      task_def = PipelineGenerator._get_operator_definition(task_id, task_details, parameters)\n      task_definitions = task_definitions + task_def\n      dependency_def = PipelineGenerator._get_dependency_definition(\n        task_id, task_details.get('up_stream', []))\n      up_steam_statements = up_steam_statements + dependency_def\n    schedule_config = pipeline_spec.get('schedule', {})\n    default_args = PipelineGenerator._get_default_args(schedule_config,\n                                                       pipeline_spec.get('emails', {}))\n    dag_definition = PipelineGenerator._get_dag_definition(\n      name, schedule_config.get('interval', '@once'), schedule_config.get('catchup', False))\n    return PipelineGenerator._imports + default_args + dag_definition + task_definitions + \\\n        up_steam_statements",
    "docstring": "Gets the airflow python spec for the Pipeline object."
  },
  {
    "code": "def pattern_logic_srt():\n    if Config.options.pattern_files and Config.options.regex:\n        return prep_regex(prep_patterns(Config.options.pattern_files))\n    elif Config.options.pattern_files:\n        return prep_patterns(Config.options.pattern_files)\n    elif Config.options.regex:\n        return prep_regex(Config.REGEX)\n    else:\n        return Config.TERMS",
    "docstring": "Return patterns to be used for searching srt subtitles."
  },
  {
    "code": "def dereference(self, session, ref, allow_none=False):\n        from ommongo.document import collection_registry\n        ref.type = collection_registry['global'][ref.collection]\n        obj = session.dereference(ref, allow_none=allow_none)\n        return obj",
    "docstring": "Dereference a pymongo \"DBRef\" to this field's underlying type"
  },
  {
    "code": "def _set_k8s_attribute(obj, attribute, value):\n    current_value = None\n    attribute_name = None\n    for python_attribute, json_attribute in obj.attribute_map.items():\n        if json_attribute == attribute:\n            attribute_name = python_attribute\n            break\n    else:\n        raise ValueError('Attribute must be one of {}'.format(obj.attribute_map.values()))\n    if hasattr(obj, attribute_name):\n        current_value = getattr(obj, attribute_name)\n    if current_value is not None:\n        current_value = SERIALIZATION_API_CLIENT.sanitize_for_serialization(\n            current_value\n        )\n    if isinstance(current_value, dict):\n        setattr(obj, attribute_name, merge_dictionaries(current_value, value))\n    elif isinstance(current_value, list):\n        setattr(obj, attribute_name, current_value + value)\n    else:\n        setattr(obj, attribute_name, value)",
    "docstring": "Set a specific value on a kubernetes object's attribute\n\n    obj\n        an object from Kubernetes Python API client\n    attribute\n        Should be a Kubernetes API style attribute (with camelCase)\n    value\n        Can be anything (string, list, dict, k8s objects) that can be\n        accepted by the k8s python client"
  },
  {
    "code": "def save_texts(fname:PathOrStr, texts:Collection[str]):\n    \"Save in `fname` the content of `texts`.\"\n    with open(fname, 'w') as f:\n        for t in texts: f.write(f'{t}\\n')",
    "docstring": "Save in `fname` the content of `texts`."
  },
  {
    "code": "def init_farm(farm_name):\n    utils.check_for_cloud_server()\n    utils.check_for_cloud_user()\n    old_farm_name = config[\"cloud_server\"][\"farm_name\"]\n    if old_farm_name and old_farm_name != farm_name:\n        raise click.ClickException(\n            \"Farm \\\"{}\\\" already initialized. Run `openag cloud deinit_farm` \"\n            \"to deinitialize it\".format(old_farm_name)\n        )\n    if config[\"local_server\"][\"url\"]:\n        utils.replicate_per_farm_dbs(farm_name=farm_name)\n    config[\"cloud_server\"][\"farm_name\"] = farm_name",
    "docstring": "Select a farm to use. This command sets up the replication between your\n    local database and the selected cloud server if you have already\n    initialized your local database with the `openag db init` command."
  },
  {
    "code": "def mkdirs(filename, mode=0o777):\n    dirname = os.path.dirname(filename)\n    if not dirname:\n        return\n    _compat.makedirs(dirname, mode=mode, exist_ok=True)",
    "docstring": "Recursively create directories up to the path of ``filename`` as needed."
  },
  {
    "code": "def hist(hist_function, *, options={}, **interact_params):\n    params = {\n        'marks': [{\n            'sample': _array_or_placeholder(hist_function),\n            'bins': _get_option('bins'),\n            'normalized': _get_option('normalized'),\n            'scales': (\n                lambda opts: {'sample': opts['x_sc'], 'count': opts['y_sc']}\n            ),\n        }],\n    }\n    fig = options.get('_fig', False) or _create_fig(options=options)\n    [hist] = _create_marks(\n        fig=fig, marks=[bq.Hist], options=options, params=params\n    )\n    _add_marks(fig, [hist])\n    def wrapped(**interact_params):\n        hist.sample = util.maybe_call(hist_function, interact_params)\n    controls = widgets.interactive(wrapped, **interact_params)\n    return widgets.VBox([controls, fig])",
    "docstring": "Generates an interactive histogram that allows users to change the\n    parameters of the input hist_function.\n\n    Args:\n        hist_function (Array | (*args -> Array int | Array float)):\n            Function that takes in parameters to interact with and returns an\n            array of numbers. These numbers will be plotted in the resulting\n            histogram.\n\n    Kwargs:\n        {options}\n\n        interact_params (dict): Keyword arguments in the same format as\n            `ipywidgets.interact`. One argument is required for each argument\n            of `hist_function`.\n\n    Returns:\n        VBox with two children: the interactive controls and the figure.\n\n    >>> def gen_random(n_points):\n    ...     return np.random.normal(size=n_points)\n    >>> hist(gen_random, n_points=(0, 1000, 10))\n    VBox(...)"
  },
  {
    "code": "def compose(self, parser: Any, grammar: Any = None, attr_of: str = None) -> str:\n        if type(self.left) is Condition:\n            left = \"({0})\".format(parser.compose(self.left, grammar=grammar, attr_of=attr_of))\n        else:\n            left = parser.compose(self.left, grammar=grammar, attr_of=attr_of)\n        if getattr(self, 'op', None):\n            if type(self.right) is Condition:\n                right = \"({0})\".format(parser.compose(self.right, grammar=grammar, attr_of=attr_of))\n            else:\n                right = parser.compose(self.right, grammar=grammar, attr_of=attr_of)\n            op = parser.compose(self.op, grammar=grammar, attr_of=attr_of)\n            result = \"{0} {1} {2}\".format(left, op, right)\n        else:\n            result = left\n        return result",
    "docstring": "Return the Condition as string format\n\n        :param parser: Parser instance\n        :param grammar: Grammar\n        :param attr_of: Attribute of..."
  },
  {
    "code": "def ConvBPDNMaskOptionsDefaults(method='admm'):\n    dflt = copy.deepcopy(cbpdnmsk_class_label_lookup(method).Options.defaults)\n    if method == 'admm':\n        dflt.update({'MaxMainIter': 1, 'AutoRho':\n                     {'Period': 10, 'AutoScaling': False,\n                      'RsdlRatio': 10.0, 'Scaling': 2.0,\n                      'RsdlTarget': 1.0}})\n    else:\n        dflt.update({'MaxMainIter': 1, 'BackTrack':\n                     {'gamma_u': 1.2, 'MaxIter': 50}})\n    return dflt",
    "docstring": "Get defaults dict for the ConvBPDNMask class specified by the\n    ``method`` parameter."
  },
  {
    "code": "def moment(expr, order, central=False):\n    if not isinstance(order, six.integer_types):\n        raise ValueError('Only integer-ordered moments are supported.')\n    if order < 0:\n        raise ValueError('Only non-negative orders are supported.')\n    output_type = _stats_type(expr)\n    return _reduction(expr, Moment, output_type, _order=order, _center=central)",
    "docstring": "Calculate the n-th order moment of the sequence\n\n    :param expr:\n    :param order: moment order, must be an integer\n    :param central: if central moments are to be computed.\n    :return:"
  },
  {
    "code": "def cf_t(self, temp):\n        index = int((temp - A4TempComp.__MIN_TEMP) // A4TempComp.__INTERVAL)\n        if temp % A4TempComp.__INTERVAL == 0:\n            return self.__values[index]\n        y1 = self.__values[index]\n        y2 = self.__values[index + 1]\n        delta_y = y2 - y1\n        delta_x = float(temp % A4TempComp.__INTERVAL) / A4TempComp.__INTERVAL\n        cf_t = y1 + (delta_y * delta_x)\n        return cf_t",
    "docstring": "Compute the linear-interpolated temperature compensation factor."
  },
  {
    "code": "def get_changed_columns(self):\n        return [k for k, v in self._values.items() if v.changed]",
    "docstring": "Returns a list of the columns that have been updated since instantiation or save"
  },
  {
    "code": "def curl_couchdb(url, method='GET', base_url=BASE_URL, data=None):\n    (username, password) = get_admin()\n    if username is None:\n        auth = None\n    else:\n        auth = (username, password)\n    if method == 'PUT':\n        req = requests.put('{}{}'.format(base_url, url), auth=auth, data=data)\n    elif method == 'DELETE':\n        req = requests.delete('{}{}'.format(base_url, url), auth=auth)\n    else:\n        req = requests.get('{}{}'.format(base_url, url), auth=auth)\n    if req.status_code not in [200, 201]:\n        raise HTTPError('{}: {}'.format(req.status_code, req.text))\n    return req",
    "docstring": "Launch a curl on CouchDB instance"
  },
  {
    "code": "def _urls(self):\n        info = (\n            self.model._meta.app_label, self.model._meta.model_name,\n            self.name,\n        )\n        urlpatterns = [\n            url(r'^%s/$' % self.name, self._view, name='%s_%s_%s' % info)\n        ]\n        return urlpatterns",
    "docstring": "URL patterns for tool linked to _view method."
  },
  {
    "code": "def parse_json_body(req):\n    content_type = req.headers.get(\"Content-Type\")\n    if content_type and core.is_json(content_type):\n        try:\n            return core.parse_json(req.body)\n        except TypeError:\n            pass\n        except json.JSONDecodeError as e:\n            if e.doc == \"\":\n                return core.missing\n            else:\n                raise\n    return {}",
    "docstring": "Return the decoded JSON body from the request."
  },
  {
    "code": "def run_in_subprocess(code, filename_suffix, arguments, working_directory):\n    temporary_file = tempfile.NamedTemporaryFile(mode='wb',\n                                                 suffix=filename_suffix)\n    temporary_file.write(code.encode('utf-8'))\n    temporary_file.flush()\n    process = subprocess.Popen(arguments + [temporary_file.name],\n                               stdout=subprocess.PIPE,\n                               stderr=subprocess.PIPE,\n                               cwd=working_directory)\n    def run():\n        raw_result = process.communicate()\n        if process.returncode != 0:\n            return (raw_result[1].decode(get_encoding()),\n                    temporary_file.name)\n    return run",
    "docstring": "Return None on success."
  },
  {
    "code": "def _FetchLinuxFlags(self):\n    if platform.system() != \"Linux\":\n      return 0\n    if self.IsSymlink():\n      return 0\n    try:\n      fd = os.open(self._path, os.O_RDONLY)\n    except (IOError, OSError):\n      return 0\n    try:\n      import fcntl\n      buf = array.array(compatibility.NativeStr(\"l\"), [0])\n      fcntl.ioctl(fd, self.FS_IOC_GETFLAGS, buf)\n      return buf[0]\n    except (IOError, OSError):\n      return 0\n    finally:\n      os.close(fd)",
    "docstring": "Fetches Linux extended file flags."
  },
  {
    "code": "def create_host(self, host_id, name, ipaddr, rack_id = None):\n    return hosts.create_host(self, host_id, name, ipaddr, rack_id)",
    "docstring": "Create a host.\n\n    @param host_id:  The host id.\n    @param name:     Host name\n    @param ipaddr:   IP address\n    @param rack_id:  Rack id. Default None.\n    @return: An ApiHost object"
  },
  {
    "code": "def wait_for_postgres(database, host, port, username, password):\n        connecting_string = 'Checking for PostgreSQL...'\n        if port is not None:\n            port = int(port)\n        while True:\n            try:\n                logger.info(connecting_string)\n                connection = psycopg2.connect(\n                    database=database,\n                    host=host,\n                    port=port,\n                    user=username,\n                    password=password,\n                    connect_timeout=3\n                )\n                connection.close()\n                logger.info('PostgreSQL is running!')\n                break\n            except psycopg2.OperationalError:\n                time.sleep(1)",
    "docstring": "Waits for PostgreSQL database to be up\n\n        Args:\n            database (Optional[str]): Database name\n            host (Optional[str]): Host where database is located\n            port (Union[int, str, None]): Database port\n            username (Optional[str]): Username to log into database\n            password (Optional[str]): Password to log into database\n\n        Returns:\n            None"
  },
  {
    "code": "def set_state(self, newState, timer=0):\n        if _debug: SSM._debug(\"set_state %r (%s) timer=%r\", newState, SSM.transactionLabels[newState], timer)\n        if (self.state == COMPLETED) or (self.state == ABORTED):\n            e = RuntimeError(\"invalid state transition from %s to %s\" % (SSM.transactionLabels[self.state], SSM.transactionLabels[newState]))\n            SSM._exception(e)\n            raise e\n        self.stop_timer()\n        self.state = newState\n        if timer:\n            self.start_timer(timer)",
    "docstring": "This function is called when the derived class wants to change state."
  },
  {
    "code": "def merge(self, other):\r\n        for key, value in other.items():\r\n            if key in self and (isinstance(self[key], Compound)\r\n                                and isinstance(value, dict)):\r\n                self[key].merge(value)\r\n            else:\r\n                self[key] = value",
    "docstring": "Recursively merge tags from another compound."
  },
  {
    "code": "def _resolve_categorical(self):\n        if self._is_array_cat:\n            return DT.MR_CAT if self._has_selected_category else DT.CA_CAT\n        return DT.LOGICAL if self._has_selected_category else DT.CAT",
    "docstring": "Return one of the categorical members of DIMENSION_TYPE.\n\n        This method distinguishes between CAT, CA_CAT, MR_CAT, and LOGICAL\n        dimension types, all of which have the base type 'categorical'. The\n        return value is only meaningful if the dimension is known to be one\n        of the categorical types (has base-type 'categorical')."
  },
  {
    "code": "def estimate_rotation(self, camera, ransac_threshold=7.0):\n        if self.axis is None:\n            x = self.points[:, 0, :].T\n            y = self.points[:, -1, :].T\n            inlier_ratio = 0.5\n            R, t, dist, idx = rotations.estimate_rotation_procrustes_ransac(x, y,\n                                                                     camera, \n                                                                     ransac_threshold,\n                                                                     inlier_ratio=inlier_ratio,\n                                                                     do_translation=False)\n            if R is not None:                                      \n                self.axis, self.angle = rotations.rotation_matrix_to_axis_angle(R)\n                if self.angle < 0:\n                    self.angle = -self.angle\n                    self.axis = -self.axis\n                self.inliers = idx\n        return self.axis is not None",
    "docstring": "Estimate the rotation between first and last frame\n\n        It uses RANSAC where the error metric is the reprojection error of the points\n        from the last frame to the first frame.\n\n        Parameters\n        -----------------\n        camera : CameraModel\n            Camera model\n        ransac_threshold : float\n            Distance threshold (in pixels) for a reprojected point to count as an inlier"
  },
  {
    "code": "def enable_cell_picking(self, mesh=None, callback=None):\n        if mesh is None:\n            if not hasattr(self, 'mesh'):\n                raise Exception('Input a mesh into the Plotter class first or '\n                                + 'or set it in this function')\n            mesh = self.mesh\n        def pick_call_back(picker, event_id):\n            extract = vtk.vtkExtractGeometry()\n            mesh.cell_arrays['orig_extract_id'] = np.arange(mesh.n_cells)\n            extract.SetInputData(mesh)\n            extract.SetImplicitFunction(picker.GetFrustum())\n            extract.Update()\n            self.picked_cells = vtki.wrap(extract.GetOutput())\n            if callback is not None:\n                callback(self.picked_cells)\n        area_picker = vtk.vtkAreaPicker()\n        area_picker.AddObserver(vtk.vtkCommand.EndPickEvent, pick_call_back)\n        self.enable_rubber_band_style()\n        self.iren.SetPicker(area_picker)",
    "docstring": "Enables picking of cells.  Press r to enable retangle based\n        selection.  Press \"r\" again to turn it off.  Selection will be\n        saved to self.picked_cells.\n\n        Uses last input mesh for input\n\n        Parameters\n        ----------\n        mesh : vtk.UnstructuredGrid, optional\n            UnstructuredGrid grid to select cells from.  Uses last\n            input grid by default.\n\n        callback : function, optional\n            When input, calls this function after a selection is made.\n            The picked_cells are input as the first parameter to this function."
  },
  {
    "code": "def value(self, t):\n        fraction = min(float(t) / max(1, self.schedule_timesteps), 1.0)\n        return self.initial_p + fraction * (self.final_p - self.initial_p)",
    "docstring": "See Schedule.value"
  },
  {
    "code": "def cuid(self):\n        identifier = \"c\"\n        millis = int(time.time() * 1000)\n        identifier += _to_base36(millis)\n        count = _pad(_to_base36(self.counter), BLOCK_SIZE)\n        identifier += count\n        identifier += self.fingerprint\n        identifier += _random_block()\n        identifier += _random_block()\n        return identifier",
    "docstring": "Generate a full-length cuid as a string."
  },
  {
    "code": "def ts_to_dt(jwt_dict):\n    d = jwt_dict.copy()\n    for k, v in [v[:2] for v in CLAIM_LIST if v[2]]:\n        if k in jwt_dict:\n            d[k] = d1_common.date_time.dt_from_ts(jwt_dict[k])\n    return d",
    "docstring": "Convert timestamps in JWT to datetime objects.\n\n    Args:\n      jwt_dict: dict\n        JWT with some keys containing timestamps.\n\n    Returns:\n      dict: Copy of input dict where timestamps have been replaced with\n      datetime.datetime() objects."
  },
  {
    "code": "def _list_object_parts(self, bucket_name, object_name, upload_id):\n        is_valid_bucket_name(bucket_name)\n        is_non_empty_string(object_name)\n        is_non_empty_string(upload_id)\n        query = {\n            'uploadId': upload_id,\n            'max-parts': '1000'\n        }\n        is_truncated = True\n        part_number_marker = ''\n        while is_truncated:\n            if part_number_marker:\n                query['part-number-marker'] = str(part_number_marker)\n            response = self._url_open('GET',\n                                      bucket_name=bucket_name,\n                                      object_name=object_name,\n                                      query=query)\n            parts, is_truncated, part_number_marker = parse_list_parts(\n                response.data,\n                bucket_name=bucket_name,\n                object_name=object_name,\n                upload_id=upload_id\n            )\n            for part in parts:\n                yield part",
    "docstring": "List all parts.\n\n        :param bucket_name: Bucket name to list parts for.\n        :param object_name: Object name to list parts for.\n        :param upload_id: Upload id of the previously uploaded object name."
  },
  {
    "code": "def population_analysis_summary_report(feature, parent):\n    _ = feature, parent\n    analysis_dir = get_analysis_dir(exposure_population['key'])\n    if analysis_dir:\n        return get_impact_report_as_string(analysis_dir)\n    return None",
    "docstring": "Retrieve an HTML population analysis table report from a multi exposure\n    analysis."
  },
  {
    "code": "def getRvaFromOffset(self, offset):\n        rva = -1\n        s = self.getSectionByOffset(offset)\n        if s:\n            rva = (offset - self.sectionHeaders[s].pointerToRawData.value) + self.sectionHeaders[s].virtualAddress.value\n        return rva",
    "docstring": "Converts a RVA to an offset.\n        \n        @type offset: int\n        @param offset: The offset value to be converted to RVA.\n        \n        @rtype: int\n        @return: The RVA obtained from the given offset."
  },
  {
    "code": "def _ring_2d(m, n):\n  if m == 1:\n    return [(0, i) for i in range(n)]\n  if n == 1:\n    return [(i, 0) for i in range(m)]\n  if m % 2 != 0:\n    tf.logging.warning(\"Odd dimension\")\n    return [(i % m, i // m) for i in range(n * m)]\n  ret = [(0, 0)]\n  for i in range(m // 2):\n    for j in range(1, n):\n      ret.append((2 * i, j))\n    for j in range(n-1, 0, -1):\n      ret.append((2 * i + 1, j))\n  for i in range(m-1, 0, -1):\n    ret.append((i, 0))\n  return ret",
    "docstring": "Ring-order of a mxn mesh.\n\n  Args:\n    m: an integer\n    n: an integer\n  Returns:\n    a list of mxn pairs"
  },
  {
    "code": "def translate_file(self, root, file_name, target_language):\n        logger.info('filling up translations for locale `{}`'.format(target_language))\n        po = polib.pofile(os.path.join(root, file_name))\n        strings = self.get_strings_to_translate(po)\n        tl = get_translator()\n        translated_strings = tl.translate_strings(strings, target_language, 'en', False)\n        self.update_translations(po, translated_strings)\n        po.save()",
    "docstring": "convenience method for translating a pot file\n\n        :param root:            the absolute path of folder where the file is present\n        :param file_name:       name of the file to be translated (it should be a pot file)\n        :param target_language: language in which the file needs to be translated"
  },
  {
    "code": "def list_containers(self, page_size=None):\n        params = {}\n        if page_size is not None:\n            params['limit'] = page_size\n        return pagination.Iterator(\n            client=self._client,\n            path='/mdb/{}/containers'.format(self._instance),\n            params=params,\n            response_class=mdb_pb2.ListContainersResponse,\n            items_key='container',\n            item_mapper=Container,\n        )",
    "docstring": "Lists the containers visible to this client.\n\n        Containers are returned in lexicographical order.\n\n        :rtype: :class:`.Container` iterator"
  },
  {
    "code": "def from_dict(d: Dict[str, Any]) -> 'BugZooException':\n        assert 'error' in d\n        d = d['error']\n        cls = getattr(sys.modules[__name__], d['kind'])\n        assert issubclass(cls, BugZooException)\n        return cls.from_message_and_data(d['message'],\n                                         d.get('data', {}))",
    "docstring": "Reconstructs a BugZoo exception from a dictionary-based description."
  },
  {
    "code": "def subsets(self):\n    source, target = self.builder_config.language_pair\n    filtered_subsets = {}\n    for split, ss_names in self._subsets.items():\n      filtered_subsets[split] = []\n      for ss_name in ss_names:\n        ds = DATASET_MAP[ss_name]\n        if ds.target != target or source not in ds.sources:\n          logging.info(\n              \"Skipping sub-dataset that does not include language pair: %s\",\n              ss_name)\n        else:\n          filtered_subsets[split].append(ss_name)\n    logging.info(\"Using sub-datasets: %s\", filtered_subsets)\n    return filtered_subsets",
    "docstring": "Subsets that make up each split of the dataset for the language pair."
  },
  {
    "code": "def map_statements(self):\n        for stmt in self.statements:\n            for agent in stmt.agent_list():\n                if agent is None:\n                    continue\n                all_mappings = []\n                for db_name, db_id in agent.db_refs.items():\n                    if isinstance(db_id, list):\n                        db_id = db_id[0][0]\n                    mappings = self._map_id(db_name, db_id)\n                    all_mappings += mappings\n                for map_db_name, map_db_id, score, orig_db_name in all_mappings:\n                    if map_db_name in agent.db_refs:\n                        continue\n                    if self.scored:\n                        try:\n                            orig_score = agent.db_refs[orig_db_name][0][1]\n                        except Exception:\n                            orig_score = 1.0\n                        agent.db_refs[map_db_name] = \\\n                            [(map_db_id, score * orig_score)]\n                    else:\n                        if map_db_name in ('UN', 'HUME'):\n                            agent.db_refs[map_db_name] = [(map_db_id, 1.0)]\n                        else:\n                            agent.db_refs[map_db_name] = map_db_id",
    "docstring": "Run the ontology mapping on the statements."
  },
  {
    "code": "def create(self, project_name, template_name, substitutions):\n        self.project_name = project_name\n        self.template_name = template_name\n        for subs in substitutions:\n            current_sub = subs.split(',')\n            current_key = current_sub[0].strip()\n            current_val = current_sub[1].strip()\n            self.substitutes_dict[current_key] = current_val\n        self.term.print_info(u\"Creating project '{0}' with template {1}\"\n            .format(self.term.text_in_color(project_name, TERM_PINK), template_name))\n        self.make_directories()\n        self.make_files()\n        self.make_posthook()",
    "docstring": "Launch the project creation."
  },
  {
    "code": "def pack(value, nbits=None):\n    if nbits is None:\n        nbits = pack_size(value) * BITS_PER_BYTE\n    elif nbits <= 0:\n        raise ValueError('Given number of bits must be greater than 0.')\n    buf_size = int(math.ceil(nbits / float(BITS_PER_BYTE)))\n    buf = (ctypes.c_uint8 * buf_size)()\n    for (idx, _) in enumerate(buf):\n        buf[idx] = (value >> (idx * BITS_PER_BYTE)) & 0xFF\n    return buf",
    "docstring": "Packs a given value into an array of 8-bit unsigned integers.\n\n    If ``nbits`` is not present, calculates the minimal number of bits required\n    to represent the given ``value``.  The result is little endian.\n\n    Args:\n      value (int): the integer value to pack\n      nbits (int): optional number of bits to use to represent the value\n\n    Returns:\n      An array of ``ctypes.c_uint8`` representing the packed ``value``.\n\n    Raises:\n      ValueError: if ``value < 0`` and ``nbits`` is ``None`` or ``nbits <= 0``.\n      TypeError: if ``nbits`` or ``value`` are not numbers."
  },
  {
    "code": "def _query_response_to_snapshot(response_pb, collection, expected_prefix):\n    if not response_pb.HasField(\"document\"):\n        return None\n    document_id = _helpers.get_doc_id(response_pb.document, expected_prefix)\n    reference = collection.document(document_id)\n    data = _helpers.decode_dict(response_pb.document.fields, collection._client)\n    snapshot = document.DocumentSnapshot(\n        reference,\n        data,\n        exists=True,\n        read_time=response_pb.read_time,\n        create_time=response_pb.document.create_time,\n        update_time=response_pb.document.update_time,\n    )\n    return snapshot",
    "docstring": "Parse a query response protobuf to a document snapshot.\n\n    Args:\n        response_pb (google.cloud.proto.firestore.v1beta1.\\\n            firestore_pb2.RunQueryResponse): A\n        collection (~.firestore_v1beta1.collection.CollectionReference): A\n            reference to the collection that initiated the query.\n        expected_prefix (str): The expected prefix for fully-qualified\n            document names returned in the query results. This can be computed\n            directly from ``collection`` via :meth:`_parent_info`.\n\n    Returns:\n        Optional[~.firestore.document.DocumentSnapshot]: A\n        snapshot of the data returned in the query. If ``response_pb.document``\n        is not set, the snapshot will be :data:`None`."
  },
  {
    "code": "def get_variables_substitution_dictionaries(self, lhs_graph, rhs_graph):\n        if not rhs_graph:\n            return {}, {}, {}\n        self.matching_code_container.add_graph_to_namespace(lhs_graph)\n        self.matching_code_container.add_graph_to_namespace(rhs_graph)\n        return self.__collect_variables_that_match_graph(lhs_graph, rhs_graph)",
    "docstring": "Looks for sub-isomorphisms of rhs into lhs\n\n        :param lhs_graph: The graph to look sub-isomorphisms into (the bigger graph)\n        :param rhs_graph: The smaller graph\n        :return: The list of matching names"
  },
  {
    "code": "def login(self, request, session, creds, segments):\n        self._maybeCleanSessions()\n        if isinstance(creds, credentials.Anonymous):\n            preauth = self.authenticatedUserForKey(session.uid)\n            if preauth is not None:\n                self.savorSessionCookie(request)\n                creds = userbase.Preauthenticated(preauth)\n        def cbLoginSuccess(input):\n            user = request.args.get('username')\n            if user is not None:\n                cookieValue = session.uid\n                if request.args.get('rememberMe'):\n                    self.createSessionForKey(cookieValue, creds.username)\n                    self.savorSessionCookie(request)\n            return input\n        return (\n            guard.SessionWrapper.login(\n                self, request, session, creds, segments)\n            .addCallback(cbLoginSuccess))",
    "docstring": "Called to check the credentials of a user.\n\n        Here we extend guard's implementation to preauthenticate users if they\n        have a valid persistent session.\n\n        @type request: L{nevow.inevow.IRequest}\n        @param request: The HTTP request being handled.\n\n        @type session: L{nevow.guard.GuardSession}\n        @param session: The user's current session.\n\n        @type creds: L{twisted.cred.credentials.ICredentials}\n        @param creds: The credentials the user presented.\n\n        @type segments: L{tuple}\n        @param segments: The remaining segments of the URL.\n\n        @return: A deferred firing with the user's avatar."
  },
  {
    "code": "def condition_from_code(condcode):\n    if condcode in __BRCONDITIONS:\n        cond_data = __BRCONDITIONS[condcode]\n        return {CONDCODE: condcode,\n                CONDITION: cond_data[0],\n                DETAILED: cond_data[1],\n                EXACT: cond_data[2],\n                EXACTNL: cond_data[3],\n                }\n    return None",
    "docstring": "Get the condition name from the condition code."
  },
  {
    "code": "def f(s):\n    frame = sys._getframe(1)\n    d = dict(builtins.__dict__)\n    d.update(frame.f_globals)\n    d.update(frame.f_locals)\n    return s.format_map(d)",
    "docstring": "Basic support for 3.6's f-strings, in 3.5!\n\n    Formats \"s\" using appropriate globals and locals\n    dictionaries.  This f-string:\n        f\"hello a is {a}\"\n    simply becomes\n        f(\"hello a is {a}\")\n    In other words, just throw parentheses around the\n    string, and you're done!\n\n    Implemented internally using str.format_map().\n    This means it doesn't support expressions:\n        f(\"two minus three is {2-3}\")\n    And it doesn't support function calls:\n        f(\"how many elements? {len(my_list)}\")\n    But most other f-string features work."
  },
  {
    "code": "def get_plugin_tabwidget(self, plugin):\n        try:\n            tabwidget = plugin.get_current_tab_manager().tabs\n        except AttributeError:\n            tabwidget = plugin.get_current_tab_manager().tabwidget\n        return tabwidget",
    "docstring": "Get the tabwidget of the plugin's current tab manager."
  },
  {
    "code": "def permissions_match(self, path):\n        audit = FilePermissionAudit(path, self.user, self.group, self.mode)\n        return audit.is_compliant(path)",
    "docstring": "Determines if the file owner and permissions match.\n\n        :param path: the path to check."
  },
  {
    "code": "def index_of_coincidence(*texts):\n    if not texts:\n        raise ValueError(\"texts must not be empty\")\n    return statistics.mean(_calculate_index_of_coincidence(frequency_analyze(text), len(text)) for text in texts)",
    "docstring": "Calculate the index of coincidence for one or more ``texts``.\n    The results are averaged over multiple texts to return the delta index of coincidence.\n\n    Examples:\n        >>> index_of_coincidence(\"aabbc\")\n        0.2\n\n        >>> index_of_coincidence(\"aabbc\", \"abbcc\")\n        0.2\n\n    Args:\n        *texts (variable length argument list): The texts to analyze\n\n    Returns:\n        Decimal value of the index of coincidence\n\n    Raises:\n        ValueError: If texts is empty\n        ValueError: If any text is less that 2 character long"
  },
  {
    "code": "def add_view(\n        self,\n        baseview,\n        name,\n        href=\"\",\n        icon=\"\",\n        label=\"\",\n        category=\"\",\n        category_icon=\"\",\n        category_label=\"\",\n    ):\n        baseview = self._check_and_init(baseview)\n        log.info(LOGMSG_INF_FAB_ADD_VIEW.format(baseview.__class__.__name__, name))\n        if not self._view_exists(baseview):\n            baseview.appbuilder = self\n            self.baseviews.append(baseview)\n            self._process_inner_views()\n            if self.app:\n                self.register_blueprint(baseview)\n                self._add_permission(baseview)\n        self.add_link(\n            name=name,\n            href=href,\n            icon=icon,\n            label=label,\n            category=category,\n            category_icon=category_icon,\n            category_label=category_label,\n            baseview=baseview,\n        )\n        return baseview",
    "docstring": "Add your views associated with menus using this method.\n\n        :param baseview:\n            A BaseView type class instantiated or not.\n            This method will instantiate the class for you if needed.\n        :param name:\n            The string name that identifies the menu.\n        :param href:\n            Override the generated href for the menu.\n            You can use an url string or an endpoint name\n            if non provided default_view from view will be set as href.\n        :param icon:\n            Font-Awesome icon name, optional.\n        :param label:\n            The label that will be displayed on the menu,\n            if absent param name will be used\n        :param category:\n            The menu category where the menu will be included,\n            if non provided the view will be acessible as a top menu.\n        :param category_icon:\n            Font-Awesome icon name for the category, optional.\n        :param category_label:\n            The label that will be displayed on the menu,\n            if absent param name will be used\n\n        Examples::\n\n            appbuilder = AppBuilder(app, db)\n            # Register a view, rendering a top menu without icon.\n            appbuilder.add_view(MyModelView(), \"My View\")\n            # or not instantiated\n            appbuilder.add_view(MyModelView, \"My View\")\n            # Register a view, a submenu \"Other View\" from \"Other\" with a phone icon.\n            appbuilder.add_view(\n                MyOtherModelView,\n                \"Other View\",\n                icon='fa-phone',\n                category=\"Others\"\n            )\n            # Register a view, with category icon and translation.\n            appbuilder.add_view(\n                YetOtherModelView,\n                \"Other View\",\n                icon='fa-phone',\n                label=_('Other View'),\n                category=\"Others\",\n                category_icon='fa-envelop',\n                category_label=_('Other View')\n            )\n            # Add a link\n            appbuilder.add_link(\"google\", href=\"www.google.com\", icon = \"fa-google-plus\")"
  },
  {
    "code": "def _unbuffered(self, proc, stream='stdout'):\n        if self.working_handler is not None:\n            t = Thread(target=self._handle_process, args=(proc, stream))\n            t.start()\n        out = getattr(proc, stream)\n        try:\n            for line in iter(out.readline, \"\"):\n                yield line.rstrip()\n        finally:\n            out.close()",
    "docstring": "Unbuffered output handler.\n\n        :type proc: subprocess.Popen\n        :type stream: six.text_types\n        :return:"
  },
  {
    "code": "def add_user(config, group, username):\n        client = Client()\n        client.prepare_connection()\n        group_api = API(client)\n        try:\n            group_api.add_user(group, username)\n        except ldap_tools.exceptions.NoGroupsFound:\n            print(\"Group ({}) not found\".format(group))\n        except ldap_tools.exceptions.TooManyResults:\n            print(\"Query for group ({}) returned multiple results.\".format(\n                group))\n        except ldap3.TYPE_OR_VALUE_EXISTS:\n            print(\"{} already exists in {}\".format(username, group))",
    "docstring": "Add specified user to specified group."
  },
  {
    "code": "def _try_resolve_sam_resource_id_refs(self, input, supported_resource_id_refs):\n        if not self._is_intrinsic_dict(input):\n            return input\n        function_type = list(input.keys())[0]\n        return self.supported_intrinsics[function_type].resolve_resource_id_refs(input, supported_resource_id_refs)",
    "docstring": "Try to resolve SAM resource id references on the given template. If the given object looks like one of the\n        supported intrinsics, it calls the appropriate resolution on it. If not, this method returns the original input\n        unmodified.\n\n        :param dict input: Dictionary that may represent an intrinsic function\n        :param dict supported_resource_id_refs: Dictionary that maps old logical ids to new ones.\n        :return: Modified input dictionary with id references resolved"
  },
  {
    "code": "def addhash(frame,**kw):\n    hashes = genhash(frame,**kw);\n    frame['data'] = rfn.rec_append_fields(\n        frame['data'],'hash',hashes);\n    return frame;",
    "docstring": "helper function to add hashes to the given frame\n    given in the dictionary d returned from firsthash.\n\n    Parameters:\n    -----------\n      frame :  frame to hash.\n\n    Keywords:\n    ---------\n      same as genhash\n    \n    Returns frame with added hashes, although it will be added in\n    place."
  },
  {
    "code": "def do_counter_reset(self, element, decl, pseudo):\n        step = self.state[self.state['current_step']]\n        counter_name = ''\n        for term in decl.value:\n            if type(term) is ast.WhitespaceToken:\n                continue\n            elif type(term) is ast.IdentToken:\n                if counter_name:\n                    step['counters'][counter_name] = 0\n                counter_name = term.value\n            elif type(term) is ast.LiteralToken:\n                if counter_name:\n                    step['counters'][counter_name] = 0\n                    counter_name = ''\n            elif type(term) is ast.NumberToken:\n                if counter_name:\n                    step['counters'][counter_name] = int(term.value)\n                    counter_name = ''\n            else:\n                log(WARN, u\"Unrecognized counter-reset term {}\"\n                    .format(type(term)).encode('utf-8'))\n        if counter_name:\n            step['counters'][counter_name] = 0",
    "docstring": "Clear specified counters."
  },
  {
    "code": "def from_text(text, origin = None, rdclass = dns.rdataclass.IN,\n              relativize = True, zone_factory=Zone, filename=None,\n              allow_include=False, check_origin=True):\n    if filename is None:\n        filename = '<string>'\n    tok = dns.tokenizer.Tokenizer(text, filename)\n    reader = _MasterReader(tok, origin, rdclass, relativize, zone_factory,\n                           allow_include=allow_include,\n                           check_origin=check_origin)\n    reader.read()\n    return reader.zone",
    "docstring": "Build a zone object from a master file format string.\n\n    @param text: the master file format input\n    @type text: string.\n    @param origin: The origin of the zone; if not specified, the first\n    $ORIGIN statement in the master file will determine the origin of the\n    zone.\n    @type origin: dns.name.Name object or string\n    @param rdclass: The zone's rdata class; the default is class IN.\n    @type rdclass: int\n    @param relativize: should names be relativized?  The default is True\n    @type relativize: bool\n    @param zone_factory: The zone factory to use\n    @type zone_factory: function returning a Zone\n    @param filename: The filename to emit when describing where an error\n    occurred; the default is '<string>'.\n    @type filename: string\n    @param allow_include: is $INCLUDE allowed?\n    @type allow_include: bool\n    @param check_origin: should sanity checks of the origin node be done?\n    The default is True.\n    @type check_origin: bool\n    @raises dns.zone.NoSOA: No SOA RR was found at the zone origin\n    @raises dns.zone.NoNS: No NS RRset was found at the zone origin\n    @rtype: dns.zone.Zone object"
  },
  {
    "code": "def general_node_label(self, node):\n        G = self.G\n        if G.node[node]['is_event']:\n            return 'event type=' + G.node[node]['type']\n        else:\n            return 'entity text=' + G.node[node]['text']",
    "docstring": "Used for debugging - gives a short text description of a\n        graph node."
  },
  {
    "code": "def use_comparative_vault_view(self):\n        self._catalog_view = COMPARATIVE\n        if self._catalog_session is not None:\n            self._catalog_session.use_comparative_catalog_view()",
    "docstring": "The returns from the lookup methods may omit or translate elements based on this session, such as authorization, and not result in an error.\n\n        This view is used when greater interoperability is desired at\n        the expense of precision.\n\n        *compliance: mandatory -- This method is must be implemented.*"
  },
  {
    "code": "def get_table_cache_key(db_alias, table):\n    cache_key = '%s:%s' % (db_alias, table)\n    return sha1(cache_key.encode('utf-8')).hexdigest()",
    "docstring": "Generates a cache key from a SQL table.\n\n    :arg db_alias: Alias of the used database\n    :type db_alias: str or unicode\n    :arg table: Name of the SQL table\n    :type table: str or unicode\n    :return: A cache key\n    :rtype: int"
  },
  {
    "code": "def concat(dfs):\n    if isstr(dfs) or not hasattr(dfs, '__iter__'):\n        msg = 'Argument must be a non-string iterable (e.g., list or tuple)'\n        raise TypeError(msg)\n    _df = None\n    for df in dfs:\n        df = df if isinstance(df, IamDataFrame) else IamDataFrame(df)\n        if _df is None:\n            _df = copy.deepcopy(df)\n        else:\n            _df.append(df, inplace=True)\n    return _df",
    "docstring": "Concatenate a series of `pyam.IamDataFrame`-like objects together"
  },
  {
    "code": "def deploy_gateway(collector):\n    configuration = collector.configuration\n    aws_syncr = configuration['aws_syncr']\n    aws_syncr, amazon, stage, gateway = find_gateway(aws_syncr, configuration)\n    gateway.deploy(aws_syncr, amazon, stage)\n    if not configuration['amazon'].changes:\n        log.info(\"No changes were made!!\")",
    "docstring": "Deploy the apigateway to a particular stage"
  },
  {
    "code": "def list_files(tag=None, sat_id=None, data_path=None, format_str=None):\n    desc = None\n    level = tag\n    if level == 'level_1':\n        code = 'L1'\n        desc = None\n    elif level == 'level_2':\n        code = 'L2'\n        desc = None\n    else:\n        raise ValueError('Unsupported level supplied: ' + level)\n    if format_str is None:\n        format_str = 'ICON_'+code+'_EUV_Daytime'\n        if desc is not None:\n            format_str += '_' + desc +'_'\n        format_str += '_{year:4d}-{month:02d}-{day:02d}_v{version:02d}r{revision:03d}.NC'\n    return pysat.Files.from_os(data_path=data_path,\n                                format_str=format_str)",
    "docstring": "Produce a list of ICON EUV files.\n\n    Notes\n    -----\n    Currently fixed to level-2"
  },
  {
    "code": "def empty_topic(self, topic):\n        nsq.assert_valid_topic_name(topic)\n        return self._request('POST', '/topic/empty', fields={'topic': topic})",
    "docstring": "Empty all the queued messages for an existing topic."
  },
  {
    "code": "def create_image(self, instance_id, name,\n                     description=None, no_reboot=False):\n        params = {'InstanceId' : instance_id,\n                  'Name' : name}\n        if description:\n            params['Description'] = description\n        if no_reboot:\n            params['NoReboot'] = 'true'\n        img = self.get_object('CreateImage', params, Image, verb='POST')\n        return img.id",
    "docstring": "Will create an AMI from the instance in the running or stopped\n        state.\n\n        :type instance_id: string\n        :param instance_id: the ID of the instance to image.\n\n        :type name: string\n        :param name: The name of the new image\n\n        :type description: string\n        :param description: An optional human-readable string describing\n                            the contents and purpose of the AMI.\n\n        :type no_reboot: bool\n        :param no_reboot: An optional flag indicating that the bundling process\n                          should not attempt to shutdown the instance before\n                          bundling.  If this flag is True, the responsibility\n                          of maintaining file system integrity is left to the\n                          owner of the instance.\n\n        :rtype: string\n        :return: The new image id"
  },
  {
    "code": "def _get_child_mock(mock, **kw):\n    attribute = \".\" + kw[\"name\"] if \"name\" in kw else \"()\"\n    mock_name = _extract_mock_name(mock) + attribute\n    raise AttributeError(mock_name)",
    "docstring": "Intercepts call to generate new mocks and raises instead"
  },
  {
    "code": "def medial_wall_to_nan(in_file, subjects_dir, target_subject, newpath=None):\n    import nibabel as nb\n    import numpy as np\n    import os\n    fn = os.path.basename(in_file)\n    if not target_subject.startswith('fs'):\n        return in_file\n    cortex = nb.freesurfer.read_label(os.path.join(\n        subjects_dir, target_subject, 'label', '{}.cortex.label'.format(fn[:2])))\n    func = nb.load(in_file)\n    medial = np.delete(np.arange(len(func.darrays[0].data)), cortex)\n    for darray in func.darrays:\n        darray.data[medial] = np.nan\n    out_file = os.path.join(newpath or os.getcwd(), fn)\n    func.to_filename(out_file)\n    return out_file",
    "docstring": "Convert values on medial wall to NaNs"
  },
  {
    "code": "def publishToOther(self, roomId, name, data):\n        tmpList = self.getRoom(roomId)\n        userList = [x for x in tmpList if x is not self]\n        self.publishToRoom(roomId, name, data, userList)",
    "docstring": "Publish to only other people than myself"
  },
  {
    "code": "def set_inteface_up(ifindex, auth, url, devid=None, devip=None):\n    if devip is not None:\n        devid = get_dev_details(devip, auth, url)['id']\n    set_int_up_url = \"/imcrs/plat/res/device/\" + str(devid) + \"/interface/\" + str(ifindex) + \"/up\"\n    f_url = url + set_int_up_url\n    try:\n        response = requests.put(f_url, auth=auth, headers=HEADERS)\n        if response.status_code == 204:\n            return response.status_code\n    except requests.exceptions.RequestException as error:\n        return \"Error:\\n\" + str(error) + \" set_inteface_up: An Error has occured\"",
    "docstring": "function takest devid and ifindex of specific device and interface and issues a RESTFUL call\n    to \"undo shut\" the specified interface on the target device.\n\n    :param devid: int or str value of the target device\n\n    :param devip: ipv4 address of the target devices\n\n    :param ifindex: int or str value of the target interface\n\n    :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class\n\n    :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass\n\n    :return: HTTP status code 204 with no values.\n\n    :rype: int\n\n    >>> from pyhpeimc.auth import *\n\n    >>> from pyhpeimc.plat.device import *\n\n    >>> auth = IMCAuth(\"http://\", \"10.101.0.203\", \"8080\", \"admin\", \"admin\")\n\n    >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10')\n    204\n\n    >>> int_up_response = set_inteface_up( '9', auth.creds, auth.url, devid = '10')\n\n    >>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10')\n    204\n\n    >>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221')\n\n    >>> assert type(int_up_response) is int\n\n    >>> assert int_up_response is 204"
  },
  {
    "code": "def is_mention_line(cls, word):\n        if word.startswith('@'):\n            return True\n        elif word.startswith('http://'):\n            return True\n        elif word.startswith('https://'):\n            return True\n        else:\n            return False",
    "docstring": "Detects links and mentions\n\n            :param word: Token to be evaluated"
  },
  {
    "code": "def wploader(self):\n        if self.target_system not in self.wploader_by_sysid:\n            self.wploader_by_sysid[self.target_system] = mavwp.MAVWPLoader()\n        return self.wploader_by_sysid[self.target_system]",
    "docstring": "per-sysid wploader"
  },
  {
    "code": "def get_version(version):\n    assert len(version) == 5\n    version_parts = version[:2] if version[2] == 0 else version[:3]\n    major = '.'.join(str(x) for x in version_parts)\n    if version[3] == 'final':\n        return major\n    sub = ''.join(str(x) for x in version[3:5])\n    if version[3] == 'dev':\n        timestamp = get_git_changeset()\n        sub = 'dev%s' % (timestamp if timestamp else version[4])\n        return '%s.%s' % (major, sub)\n    if version[3] == 'post':\n        return '%s.%s' % (major, sub)\n    elif version[3] in ('a', 'b', 'rc'):\n        return '%s%s' % (major, sub)\n    else:\n        raise ValueError('Invalid version: %s' % str(version))",
    "docstring": "Returns a PEP 440-compliant version number from VERSION.\n\n    Created by modifying django.utils.version.get_version"
  },
  {
    "code": "def _scalar_coef_op_left(func):\r\n        @wraps(func)\r\n        def verif(self, scoef):\r\n            if isinstance(scoef, ScalarCoefs):\r\n                if len(self._vec) == len(scoef._vec):\r\n                    return ScalarCoefs(func(self, self._vec, scoef._vec),\r\n                                        self.nmax,\r\n                                        self.mmax)\r\n                else:\r\n                    raise ValueError(err_msg['SC_sz_msmtch'] % \\\r\n                                    (self.nmax, self.mmax,\r\n                                     scoef.nmax, scoef.mmax))\r\n            elif isinstance(scoef, numbers.Number):\r\n                return ScalarCoefs(func(self, self._vec, scoef), self.nmax,\r\n                                   self.mmax)\r\n            else:\r\n                raise TypeError(err_msg['no_combi_SC'])\r\n        return verif",
    "docstring": "decorator for operator overloading when ScalarCoef is on the\r\n        left"
  },
  {
    "code": "def rasterToWKB(cls, rasterPath, srid, noData, raster2pgsql):\n        raster2pgsqlProcess = subprocess.Popen([raster2pgsql,\n                                                '-s', srid,\n                                                '-N', noData,\n                                                rasterPath,\n                                                'n_a'],stdout=subprocess.PIPE)\n        sql, error = raster2pgsqlProcess.communicate()\n        if sql:\n            wellKnownBinary = sql.split(\"'\")[1]\n        else:\n            print(error)\n            raise\n        return wellKnownBinary",
    "docstring": "Accepts a raster file and converts it to Well Known Binary text using the raster2pgsql\n        executable that comes with PostGIS. This is the format that rasters are stored in a\n        PostGIS database."
  },
  {
    "code": "def write_extra_resources(self, compile_context):\n    target = compile_context.target\n    if isinstance(target, ScalacPlugin):\n      self._write_scalac_plugin_info(compile_context.classes_dir.path, target)\n    elif isinstance(target, JavacPlugin):\n      self._write_javac_plugin_info(compile_context.classes_dir.path, target)\n    elif isinstance(target, AnnotationProcessor) and target.processors:\n      processor_info_file = os.path.join(compile_context.classes_dir.path, _PROCESSOR_INFO_FILE)\n      self._write_processor_info(processor_info_file, target.processors)",
    "docstring": "Override write_extra_resources to produce plugin and annotation processor files."
  },
  {
    "code": "def to_binary(self,filename):\n        retrans = False\n        if self.istransformed:\n            self._back_transform(inplace=True)\n            retrans = True\n        if self.isnull().values.any():\n            warnings.warn(\"NaN in par ensemble\",PyemuWarning)\n        self.as_pyemu_matrix().to_coo(filename)\n        if retrans:\n            self._transform(inplace=True)",
    "docstring": "write the parameter ensemble to a jco-style binary file\n\n        Parameters\n        ----------\n        filename : str\n            the filename to write\n\n        Returns\n        -------\n        None\n\n\n        Note\n        ----\n        this function back-transforms inplace with respect to\n        log10 before writing"
  },
  {
    "code": "def weekdays(first_day=None):\n    if first_day is None:\n        first_day = 'Monday'\n    ix = _lower_weekdays().index(first_day.lower())\n    return _double_weekdays()[ix:ix+7]",
    "docstring": "Returns a list of weekday names.\n\n    Arguments\n    ---------\n    first_day : str, default None\n        The first day of the week. If not given, 'Monday' is used.\n\n    Returns\n    -------\n    list\n        A list of weekday names."
  },
  {
    "code": "def register(self, name, fun, description=None):\n        self.methods[name] = fun\n        self.descriptions[name] = description",
    "docstring": "Register function on this service"
  },
  {
    "code": "def get_all_fix_names(fixer_pkg, remove_prefix=True):\n    pkg = __import__(fixer_pkg, [], [], [\"*\"])\n    fixer_dir = os.path.dirname(pkg.__file__)\n    fix_names = []\n    for name in sorted(os.listdir(fixer_dir)):\n        if name.startswith(\"fix_\") and name.endswith(\".py\"):\n            if remove_prefix:\n                name = name[4:]\n            fix_names.append(name[:-3])\n    return fix_names",
    "docstring": "Return a sorted list of all available fix names in the given package."
  },
  {
    "code": "def __get_obj_by_discriminator(self, payload, obj_type):\n        obj_cast = cast(Any, obj_type)\n        namespaced_class_name = obj_cast.get_real_child_model(payload)\n        if not namespaced_class_name:\n            raise SerializationException(\n                \"Couldn't resolve object by discriminator type \"\n                \"for {} class\".format(obj_type))\n        return self.__load_class_from_name(namespaced_class_name)",
    "docstring": "Get correct subclass instance using the discriminator in\n        payload.\n\n        :param payload: Payload for deserialization\n        :type payload: str\n        :param obj_type: parent class for deserializing payload into\n        :type obj_type: Union[object, str]\n        :return: Subclass of provided parent class, that resolves to\n            the discriminator in payload.\n        :rtype: object\n        :raises: :py:class:`ask_sdk_core.exceptions.SerializationException`"
  },
  {
    "code": "def add_listener(self, callback, event_type=None):\n        listener_uid = uuid4()\n        self.listeners.append(\n            {\n                'uid': listener_uid,\n                'callback': callback,\n                'event_type': event_type\n            }\n        )\n        return listener_uid",
    "docstring": "Add a listener that will send a callback when the client recieves\n        an event.\n\n        Args:\n            callback (func(roomchunk)): Callback called when an event arrives.\n            event_type (str): The event_type to filter for.\n\n        Returns:\n            uuid.UUID: Unique id of the listener, can be used to identify the listener."
  },
  {
    "code": "def _if_not_freed(f):\n    @add_signature_to_docstring(f)\n    @functools.wraps(f)\n    def f_(self, *args, **kwargs):\n        if self._freed:\n            raise OSError\n        return f(self, *args, **kwargs)\n    return f_",
    "docstring": "Run the method iff. the memory view hasn't been closed."
  },
  {
    "code": "def init_app(self, app):\n        app.config.setdefault('OPENERP_SERVER', 'http://localhost:8069')\n        app.config.setdefault('OPENERP_DATABASE', 'openerp')\n        app.config.setdefault('OPENERP_DEFAULT_USER', 'admin')\n        app.config.setdefault('OPENERP_DEFAULT_PASSWORD', 'admin')\n        app.jinja_env.globals.update(\n            get_data_from_record=get_data_from_record\n        )\n        cnx = Client(\n            server=app.config['OPENERP_SERVER'],\n            db=app.config['OPENERP_DATABASE'],\n            user=app.config['OPENERP_DEFAULT_USER'],\n            password=app.config['OPENERP_DEFAULT_PASSWORD']\n        )\n        self.default_user = cnx.user\n        app.before_request(self.before_request)",
    "docstring": "This callback can be used to initialize an application for use with\n        the OpenERP server."
  },
  {
    "code": "def Process(self, parser_mediator, plist_name, top_level, **kwargs):\n    if not plist_name.startswith(self.PLIST_PATH):\n      raise errors.WrongPlistPlugin(self.NAME, plist_name)\n    super(AppleAccountPlugin, self).Process(\n        parser_mediator, plist_name=self.PLIST_PATH, top_level=top_level)",
    "docstring": "Check if it is a valid Apple account plist file name.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      plist_name (str): name of the plist.\n      top_level (dict[str, object]): plist top-level key."
  },
  {
    "code": "def observer_update(self, message):\n        for action in ('added', 'changed', 'removed'):\n            for item in message[action]:\n                self.send_json(\n                    {\n                        'msg': action,\n                        'observer': message['observer'],\n                        'primary_key': message['primary_key'],\n                        'order': item['order'],\n                        'item': item['data'],\n                    }\n                )",
    "docstring": "Called when update from observer is received."
  },
  {
    "code": "def modify_phonetic_representation(self, phonetic_representation):\n        for i in range(len(phonetic_representation)):\n            phonetic_representation[i] = re.sub('\\d+', '', phonetic_representation[i])\n        multis = ['AA', 'AE', 'AH', 'AO', 'AW', 'AY', 'CH', 'DH', 'EH', 'ER',\n                  'EY', 'HH', 'IH', 'IY', 'JH', 'NG', 'OW', 'OY', 'SH',\n                  'TH', 'UH', 'UW', 'ZH']\n        singles = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',\n                   'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w']\n        for i in range(len(phonetic_representation)):\n            if phonetic_representation[i] in multis:\n                phonetic_representation[i] = singles[multis.index(phonetic_representation[i])]\n        phonetic_representation = ''.join(phonetic_representation)\n        return phonetic_representation",
    "docstring": "Returns a compact phonetic representation given a CMUdict-formatted representation.\n\n        :param list phonetic_representation: a phonetic representation in standard\n            CMUdict formatting, i.e. a list of phonemes like ['HH', 'EH0', 'L', 'OW1']\n        :returns: A string representing a custom phonetic representation, where each phoneme is\n            mapped to a single ascii character.\n\n        Changing the phonetic representation from a list to a string is useful for calculating phonetic\n        simlarity scores."
  },
  {
    "code": "def _connect_docker(spec):\n    return {\n        'method': 'docker',\n        'kwargs': {\n            'username': spec.remote_user(),\n            'container': spec.remote_addr(),\n            'python_path': spec.python_path(),\n            'connect_timeout': spec.ansible_ssh_timeout() or spec.timeout(),\n            'remote_name': get_remote_name(spec),\n        }\n    }",
    "docstring": "Return ContextService arguments for a Docker connection."
  },
  {
    "code": "def GetNumCoresOnHosts(hosts, private_key):\n  results = runner.Runner(host_list=hosts, private_key=private_key,\n                          module_name='setup').run()\n  num_cores_list = []\n  for _, props in results['contacted'].iteritems():\n    cores = props['ansible_facts']['ansible_processor_cores']\n    val = 0\n    try:\n      val = int(cores)\n    except ValueError:\n      pass\n    num_cores_list.append(val)\n  return num_cores_list",
    "docstring": "Returns list of the number of cores for each host requested in hosts."
  },
  {
    "code": "def _handle_actionpush(self, length):\n        init_pos = self._src.tell()\n        while self._src.tell() < init_pos + length:\n            obj = _make_object(\"ActionPush\")\n            obj.Type = unpack_ui8(self._src)\n            push_types = {\n                0: (\"String\", self._get_struct_string),\n                1: (\"Float\", lambda: unpack_float(self._src)),\n                2: (\"Null\", lambda: None),\n                4: (\"RegisterNumber\", lambda: unpack_ui8(self._src)),\n                5: (\"Boolean\", lambda: unpack_ui8(self._src)),\n                6: (\"Double\", lambda: unpack_double(self._src)),\n                7: (\"Integer\", lambda: unpack_ui32(self._src)),\n                8: (\"Constant8\", lambda: unpack_ui8(self._src)),\n                9: (\"Constant16\", lambda: unpack_ui16(self._src)),\n            }\n            name, func = push_types[obj.Type]\n            setattr(obj, name, func())\n            yield obj",
    "docstring": "Handle the ActionPush action."
  },
  {
    "code": "def random_sample(self):\n        data = np.empty((1, self.dim))\n        for col, (lower, upper) in enumerate(self._bounds):\n            data.T[col] = self.random_state.uniform(lower, upper, size=1)\n        return data.ravel()",
    "docstring": "Creates random points within the bounds of the space.\n\n        Returns\n        ----------\n        data: ndarray\n            [num x dim] array points with dimensions corresponding to `self._keys`\n\n        Example\n        -------\n        >>> target_func = lambda p1, p2: p1 + p2\n        >>> pbounds = {'p1': (0, 1), 'p2': (1, 100)}\n        >>> space = TargetSpace(target_func, pbounds, random_state=0)\n        >>> space.random_points(1)\n        array([[ 55.33253689,   0.54488318]])"
  },
  {
    "code": "def GetArtifactsForCollection(os_name, artifact_list):\n  artifact_arranger = ArtifactArranger(os_name, artifact_list)\n  artifact_names = artifact_arranger.GetArtifactsInProperOrder()\n  return artifact_names",
    "docstring": "Wrapper for the ArtifactArranger.\n\n  Extend the artifact list by dependencies and sort the artifacts to resolve the\n  dependencies.\n\n  Args:\n    os_name: String specifying the OS name.\n    artifact_list: List of requested artifact names.\n\n  Returns:\n    A list of artifacts such that if they are collected in the given order\n      their dependencies are resolved."
  },
  {
    "code": "def set_metadata(candidates, traces, dependencies, pythons):\n    metasets_mapping = _calculate_metasets_mapping(\n        dependencies, pythons, copy.deepcopy(traces),\n    )\n    for key, candidate in candidates.items():\n        candidate.markers = _format_metasets(metasets_mapping[key])",
    "docstring": "Add \"metadata\" to candidates based on the dependency tree.\n\n    Metadata for a candidate includes markers and a specifier for Python\n    version requirements.\n\n    :param candidates: A key-candidate mapping. Candidates in the mapping will\n        have their markers set.\n    :param traces: A graph trace (produced by `traces.trace_graph`) providing\n        information about dependency relationships between candidates.\n    :param dependencies: A key-collection mapping containing what dependencies\n        each candidate in `candidates` requested.\n    :param pythons: A key-str mapping containing Requires-Python information\n        of each candidate.\n\n    Keys in mappings and entries in the trace are identifiers of a package, as\n    implemented by the `identify` method of the resolver's provider.\n\n    The candidates are modified in-place."
  },
  {
    "code": "def get_fn_plan(callback=None, out_callback=None, name='pycbc_cufft', parameters=None):\n    if parameters is None:\n        parameters = []\n    source = fftsrc.render(input_callback=callback, output_callback=out_callback, parameters=parameters)\n    path = compile(source, name)\n    lib = ctypes.cdll.LoadLibrary(path)\n    fn = lib.execute\n    fn.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]\n    plan = lib.create_plan\n    plan.restype = ctypes.c_void_p\n    plan.argyptes = [ctypes.c_uint]\n    return fn, plan",
    "docstring": "Get the IFFT execute and plan functions"
  },
  {
    "code": "def write_padding_bits(buff, version, length):\n    if version not in (consts.VERSION_M1, consts.VERSION_M3):\n        buff.extend([0] * (8 - (length % 8)))",
    "docstring": "\\\n    Writes padding bits if the data stream does not meet the codeword boundary.\n\n    :param buff: The byte buffer.\n    :param int length: Data stream length."
  },
  {
    "code": "def canparse(argparser, args):\n    old_error_method = argparser.error\n    argparser.error = _raise_ValueError\n    try:\n        argparser.parse_args(args)\n    except ValueError:\n        return False\n    else:\n        return True\n    finally:\n        argparser.error = old_error_method",
    "docstring": "Determines if argparser can parse args."
  },
  {
    "code": "def touch(args):\n    p = OptionParser(touch.__doc__)\n    opts, args = p.parse_args(args)\n    fp = sys.stdin\n    for link_name in fp:\n        link_name = link_name.strip()\n        if not op.islink(link_name):\n            continue\n        if not op.exists(link_name):\n            continue\n        source = get_abs_path(link_name)\n        lnsf(source, link_name)",
    "docstring": "find . -type l | %prog touch\n\n    Linux commands `touch` wouldn't modify mtime for links, this script can.\n    Use find to pipe in all the symlinks."
  },
  {
    "code": "def load_model_by_id(self, model_id):\n        with open(os.path.join(self.path, str(model_id) + \".json\")) as fin:\n            json_str = fin.read().replace(\"\\n\", \"\")\n        load_model = json_to_graph(json_str)\n        return load_model",
    "docstring": "Get the model by model_id\n\n        Parameters\n        ----------\n        model_id : int\n            model index\n        \n        Returns\n        -------\n        load_model : Graph\n            the model graph representation"
  },
  {
    "code": "async def toggle(self):\n        self.logger.debug(\"toggle command\")\n        if not self.state == 'ready':\n            return\n        if self.streamer is None:\n            return\n        try:\n            if self.streamer.is_playing():\n                await self.pause()\n            else:\n                await self.resume()\n        except Exception as e:\n            logger.error(e)\n            pass",
    "docstring": "Toggles between pause and resume command"
  },
  {
    "code": "def collect_static() -> bool:\n    from django.core.management import execute_from_command_line\n    wf('Collecting static files... ', False)\n    execute_from_command_line(['./manage.py', 'collectstatic', '-c', '--noinput', '-v0'])\n    wf('[+]\\n')\n    return True",
    "docstring": "Runs Django ``collectstatic`` command in silent mode.\n\n    :return: always ``True``"
  },
  {
    "code": "def mangle_mako_loop(node, printer):\n    loop_variable = LoopVariable()\n    node.accept_visitor(loop_variable)\n    if loop_variable.detected:\n        node.nodes[-1].has_loop_context = True\n        match = _FOR_LOOP.match(node.text)\n        if match:\n            printer.writelines(\n                    'loop = __M_loop._enter(%s)' % match.group(2),\n                    'try:'\n            )\n            text = 'for %s in loop:' % match.group(1)\n        else:\n            raise SyntaxError(\"Couldn't apply loop context: %s\" % node.text)\n    else:\n        text = node.text\n    return text",
    "docstring": "converts a for loop into a context manager wrapped around a for loop\n    when access to the `loop` variable has been detected in the for loop body"
  },
  {
    "code": "def call_fsm(method):\n\tfsm_method = getattr(fsm.fsm, method.__name__)\n\tdef new_method(*legos):\n\t\talphabet = set().union(*[lego.alphabet() for lego in legos])\n\t\treturn from_fsm(fsm_method(*[lego.to_fsm(alphabet) for lego in legos]))\n\treturn new_method",
    "docstring": "Take a method which acts on 0 or more regular expression objects... return a\n\t\tnew method which simply converts them all to FSMs, calls the FSM method\n\t\ton them instead, then converts the result back to a regular expression.\n\t\tWe do this for several of the more annoying operations."
  },
  {
    "code": "def permission_denied(self, request, message=None):\n        if not request.successful_authenticator:\n            raise exceptions.NotAuthenticated()\n        raise exceptions.PermissionDenied(detail=message)",
    "docstring": "If request is not permitted, determine what kind of exception to raise."
  },
  {
    "code": "def server(self):\n        try:\n            tar = urllib2.urlopen(self.registry)\n            meta = tar.info()\n            return int(meta.getheaders(\"Content-Length\")[0])\n        except (urllib2.URLError, IndexError):\n            return \" \"",
    "docstring": "Returns the size of remote files"
  },
  {
    "code": "def control_low_limit(self) -> Optional[Union[int, float]]:\n        return self._get_field_value(SpecialDevice.PROP_CONTROL_LOW_LIMIT)",
    "docstring": "Control low limit setting for a special sensor.\n\n        For LS-10/LS-20 base units only."
  },
  {
    "code": "def get_usages(self):\r\n        \"Return a dictionary mapping full usages Ids to plain values\"\r\n        result = dict()\r\n        for key, usage in self.items():\r\n            result[key] = usage.value\r\n        return result",
    "docstring": "Return a dictionary mapping full usages Ids to plain values"
  },
  {
    "code": "def _process_mark_toggle(self, p_todo_id, p_force=None):\n        if p_force in ['mark', 'unmark']:\n            action = p_force\n        else:\n            action = 'mark' if p_todo_id not in self.marked_todos else 'unmark'\n        if action == 'mark':\n            self.marked_todos.add(p_todo_id)\n            return True\n        else:\n            self.marked_todos.remove(p_todo_id)\n            return False",
    "docstring": "Adds p_todo_id to marked_todos attribute and returns True if p_todo_id\n        is not already marked. Removes p_todo_id from marked_todos and returns\n        False otherwise.\n\n        p_force parameter accepting 'mark' or 'unmark' values, if set, can force\n        desired action without checking p_todo_id presence in marked_todos."
  },
  {
    "code": "def detect_aromatic_rings_in_ligand(self):\n        self.ligrings = {}\n        try:\n            ring_info = self.topology_data.mol.GetRingInfo()\n            self.ligand_ring_num = ring_info.NumRings()\n        except Exception as e:\n            m = Chem.MolFromPDBFile(\"lig.pdb\")\n            ring_info = m.GetRingInfo()\n            self.ligand_ring_num = ring_info.NumRings()\n        i=0\n        for ring in range(self.ligand_ring_num):\n            if 4 < len(ring_info.AtomRings()[ring]) <= 6 and  False not in [self.topology_data.mol.GetAtomWithIdx(x).GetIsAromatic() for x in ring_info.AtomRings()[ring]]:\n                atom_ids_in_ring = []\n                for atom in ring_info.AtomRings()[ring]:\n                    atom_ids_in_ring.append(self.topology_data.universe.ligand.atoms[atom].name)\n                self.ligrings[i]=atom_ids_in_ring\n                i+=1",
    "docstring": "Using rdkit to detect aromatic rings in ligand - size 4-6 atoms and all atoms are part of the ring. Saves this data in self.ligrings."
  },
  {
    "code": "def lines_diff(before_lines, after_lines, check_modified=False):\n    before_comps = [\n        LineComparator(line, check_modified=check_modified)\n        for line in before_lines\n    ]\n    after_comps = [\n        LineComparator(line, check_modified=check_modified)\n        for line in after_lines\n    ]\n    diff_result = diff(\n        before_comps,\n        after_comps,\n        check_modified=check_modified\n    )\n    return diff_result",
    "docstring": "Diff the lines in two strings.\n\n    Parameters\n    ----------\n    before_lines : iterable\n        Iterable containing lines used as the baseline version.\n    after_lines : iterable\n        Iterable containing lines to be compared against the baseline.\n\n    Returns\n    -------\n    diff_result : A list of dictionaries containing diff information."
  },
  {
    "code": "def _run_command(self, cmdline):\n        try:\n            if self.verbose:\n                print(cmdline)\n            subprocess.check_call(cmdline, shell=True)\n        except subprocess.CalledProcessError:\n            print('when running: ', cmdline)\n            raise",
    "docstring": "Run a subcommand, quietly.  Prints the full command on error."
  },
  {
    "code": "def truncate_to(value: Decimal, currency: str) -> Decimal:\n    decimal_places = DECIMALS.get(currency.upper(), 2)\n    return truncate(value, decimal_places)",
    "docstring": "Truncates a value to the number of decimals corresponding to the currency"
  },
  {
    "code": "def register_validator(flag_name,\n                       checker,\n                       message='Flag validation failed',\n                       flag_values=_flagvalues.FLAGS):\n  v = SingleFlagValidator(flag_name, checker, message)\n  _add_validator(flag_values, v)",
    "docstring": "Adds a constraint, which will be enforced during program execution.\n\n  The constraint is validated when flags are initially parsed, and after each\n  change of the corresponding flag's value.\n  Args:\n    flag_name: str, name of the flag to be checked.\n    checker: callable, a function to validate the flag.\n        input - A single positional argument: The value of the corresponding\n            flag (string, boolean, etc.  This value will be passed to checker\n            by the library).\n        output - bool, True if validator constraint is satisfied.\n            If constraint is not satisfied, it should either return False or\n            raise flags.ValidationError(desired_error_message).\n    message: str, error text to be shown to the user if checker returns False.\n        If checker raises flags.ValidationError, message from the raised\n        error will be shown.\n    flag_values: flags.FlagValues, optional FlagValues instance to validate\n        against.\n  Raises:\n    AttributeError: Raised when flag_name is not registered as a valid flag\n        name."
  },
  {
    "code": "def from_dict(cls, async):\n        async_options = decode_async_options(async)\n        target, args, kwargs = async_options.pop('job')\n        return cls(target, args, kwargs, **async_options)",
    "docstring": "Return an async job from a dict output by Async.to_dict."
  },
  {
    "code": "def _compile_re(self, expression):\n        meta_words = \"|\".join(self.sanitize_words)\n        expression = expression.replace(\"META_WORDS_HERE\", meta_words)\n        return re.compile(expression, re.IGNORECASE)",
    "docstring": "Compile given regular expression for current sanitize words"
  },
  {
    "code": "def iter_child_nodes(node):\n    for name, field in iter_fields(node):\n        if isinstance(field, AST):\n            yield field\n        elif isinstance(field, list):\n            for item in field:\n                if isinstance(item, AST):\n                    yield item",
    "docstring": "Iterate over all child nodes or a node."
  },
  {
    "code": "def name_from_path(self):\n        name = os.path.splitext(os.path.basename(self.path))[0]\n        if name == 'catalog':\n            name = os.path.basename(os.path.dirname(self.path))\n        return name.replace('.', '_')",
    "docstring": "If catalog is named 'catalog' take name from parent directory"
  },
  {
    "code": "def _snpeff_args_from_config(data):\n    config = data[\"config\"]\n    args = [\"-hgvs\"]\n    resources = config_utils.get_resources(\"snpeff\", config)\n    if resources.get(\"options\"):\n        args += [str(x) for x in resources.get(\"options\", [])]\n    if vcfutils.get_paired_phenotype(data):\n        args += [\"-cancer\"]\n    effects_transcripts = dd.get_effects_transcripts(data)\n    if effects_transcripts in set([\"canonical_cancer\"]):\n        _, snpeff_base_dir = get_db(data)\n        canon_list_file = os.path.join(snpeff_base_dir, \"transcripts\", \"%s.txt\" % effects_transcripts)\n        if not utils.file_exists(canon_list_file):\n            raise ValueError(\"Cannot find expected file for effects_transcripts: %s\" % canon_list_file)\n        args += [\"-canonList\", canon_list_file]\n    elif effects_transcripts == \"canonical\" or tz.get_in((\"config\", \"algorithm\", \"clinical_reporting\"), data):\n        args += [\"-canon\"]\n    return args",
    "docstring": "Retrieve snpEff arguments supplied through input configuration."
  },
  {
    "code": "def parse(self, generator):\n        gen = iter(generator)\n        for line in gen:\n            block = {}\n            for rule in self.rules:\n                if rule[0](line):\n                    block = rule[1](line, gen)\n                    break\n            yield block",
    "docstring": "Parse an iterable source of strings into a generator"
  },
  {
    "code": "def walk(self, visitor):\n        visitor(self)\n        for c in self.children:\n            c.walk(visitor)\n        return self",
    "docstring": "Walk the branch and call the visitor function\n        on each node.\n        @param visitor: A function.\n        @return: self\n        @rtype: L{Element}"
  },
  {
    "code": "def _setup_events(plugin):\n    events = plugin.events\n    if events and isinstance(events, (list, tuple)):\n        for event in [e for e in events if e in _EVENT_VALS]:\n            register('event', event, plugin)",
    "docstring": "Handles setup or teardown of event hook registration for the provided\n        plugin.\n\n        `plugin`\n            ``Plugin`` class."
  },
  {
    "code": "def unbare_repo(func):\n    @wraps(func)\n    def wrapper(self, *args, **kwargs):\n        if self.repo.bare:\n            raise InvalidGitRepositoryError(\"Method '%s' cannot operate on bare repositories\" % func.__name__)\n        return func(self, *args, **kwargs)\n    return wrapper",
    "docstring": "Methods with this decorator raise InvalidGitRepositoryError if they\n    encounter a bare repository"
  },
  {
    "code": "def setup(self, bitdepth=16):\n        fmt = self.get_file_format()\n        newfmt = copy.copy(fmt)\n        newfmt.mFormatID = AUDIO_ID_PCM\n        newfmt.mFormatFlags = \\\n            PCM_IS_SIGNED_INT | PCM_IS_PACKED\n        newfmt.mBitsPerChannel = bitdepth\n        newfmt.mBytesPerPacket = \\\n            (fmt.mChannelsPerFrame * newfmt.mBitsPerChannel // 8)\n        newfmt.mFramesPerPacket = 1\n        newfmt.mBytesPerFrame = newfmt.mBytesPerPacket\n        self.set_client_format(newfmt)",
    "docstring": "Set the client format parameters, specifying the desired PCM\n        audio data format to be read from the file. Must be called\n        before reading from the file."
  },
  {
    "code": "def alter(self, operation, timeout=None, metadata=None, credentials=None):\n        new_metadata = self.add_login_metadata(metadata)\n        try:\n            return self.any_client().alter(operation, timeout=timeout,\n                                           metadata=new_metadata,\n                                           credentials=credentials)\n        except Exception as error:\n            if util.is_jwt_expired(error):\n                self.retry_login()\n                new_metadata = self.add_login_metadata(metadata)\n                return self.any_client().alter(operation, timeout=timeout,\n                                               metadata=new_metadata,\n                                               credentials=credentials)\n            else:\n                raise error",
    "docstring": "Runs a modification via this client."
  },
  {
    "code": "def context_export(zap_helper, name, file_path):\n    with zap_error_handler():\n        result = zap_helper.zap.context.export_context(name, file_path)\n        if result != 'OK':\n            raise ZAPError('Exporting context to file failed: {}'.format(result))\n    console.info('Exported context {0} to {1}'.format(name, file_path))",
    "docstring": "Export a given context to a file."
  },
  {
    "code": "def detectWebOSTV(self):\n        return UAgentInfo.deviceWebOStv in self.__userAgent \\\n            and UAgentInfo.smartTV2 in self.__userAgent",
    "docstring": "Return detection of a WebOS smart TV\n\n        Detects if the current browser is on a WebOS smart TV."
  },
  {
    "code": "def soap(self):\n        logger.debug(\"- SOAP -\")\n        _dict = self.unpack_soap()\n        logger.debug(\"_dict: %s\", _dict)\n        return self.operation(_dict, BINDING_SOAP)",
    "docstring": "Single log out using HTTP_SOAP binding"
  },
  {
    "code": "def show_loadbalancer(self, lbaas_loadbalancer, **_params):\n        return self.get(self.lbaas_loadbalancer_path % (lbaas_loadbalancer),\n                        params=_params)",
    "docstring": "Fetches information for a load balancer."
  },
  {
    "code": "def items (self):\n        return [(key, value[1]) for key, value in super(LFUCache, self).items()]",
    "docstring": "Return list of items, not updating usage count."
  },
  {
    "code": "def parse_debug(self, inputstring):\n        return self.parse(inputstring, self.file_parser, {\"strip\": True}, {\"header\": \"none\", \"initial\": \"none\", \"final_endline\": False})",
    "docstring": "Parse debug code."
  },
  {
    "code": "def check_package_data(dist, attr, value):\n    if isinstance(value, dict):\n        for k, v in value.items():\n            if not isinstance(k, str):\n                break\n            try:\n                iter(v)\n            except TypeError:\n                break\n        else:\n            return\n    raise DistutilsSetupError(\n        attr + \" must be a dictionary mapping package names to lists of \"\n        \"wildcard patterns\"\n    )",
    "docstring": "Verify that value is a dictionary of package names to glob lists"
  },
  {
    "code": "def skip(self):\n        if self.skip_list and isinstance(self.skip_list, list):\n            for skip in self.skip_list:\n                if request.path.startswith('/{0}'.format(skip)):\n                    return True\n        return False",
    "docstring": "Checks the skip list."
  },
  {
    "code": "def path_to_pattern(path, metadata=None):\n    if not isinstance(path, str):\n        return\n    pattern = path\n    if metadata:\n        cache = metadata.get('cache')\n        if cache:\n            regex = next(c.get('regex') for c in cache if c.get('argkey') == 'urlpath')\n            pattern = pattern.split(regex)[-1]\n    return pattern",
    "docstring": "Remove source information from path when using chaching\n\n    Returns None if path is not str\n\n    Parameters\n    ----------\n    path : str\n        Path to data optionally containing format_strings\n    metadata : dict, optional\n        Extra arguments to the class, contains any cache information\n\n    Returns\n    -------\n    pattern : str\n        Pattern style path stripped of everything to the left of cache regex."
  },
  {
    "code": "def is45(msg):\n    if allzeros(msg):\n        return False\n    d = hex2bin(data(msg))\n    if wrongstatus(d, 1, 2, 3):\n        return False\n    if wrongstatus(d, 4, 5, 6):\n        return False\n    if wrongstatus(d, 7, 8, 9):\n        return False\n    if wrongstatus(d, 10, 11, 12):\n        return False\n    if wrongstatus(d, 13, 14, 15):\n        return False\n    if wrongstatus(d, 16, 17, 26):\n        return False\n    if wrongstatus(d, 27, 28, 38):\n        return False\n    if wrongstatus(d, 39, 40, 51):\n        return False\n    if bin2int(d[51:56]) != 0:\n        return False\n    temp = temp45(msg)\n    if temp:\n        if temp > 60 or temp < -80:\n            return False\n    return True",
    "docstring": "Check if a message is likely to be BDS code 4,5.\n\n    Meteorological hazard report\n\n    Args:\n        msg (String): 28 bytes hexadecimal message string\n\n    Returns:\n        bool: True or False"
  },
  {
    "code": "def _fields(self):\n        return (\n            ('reference_name', self.reference_name,),\n            ('annotation_name', self.annotation_name),\n            ('annotation_version', self.annotation_version),\n            ('cache_directory_path', self.cache_directory_path),\n            ('decompress_on_download', self.decompress_on_download),\n            ('copy_local_files_to_cache', self.copy_local_files_to_cache)\n        )",
    "docstring": "Fields used for hashing, string representation, equality comparison"
  },
  {
    "code": "def wait(self):\n        try:\n            SpawningProxy(self.containers, abort_on_error=True).wait()\n        except Exception:\n            self.stop()\n            raise",
    "docstring": "Wait for all running containers to stop."
  },
  {
    "code": "def serialize(ad_objects, output_format='json', indent=2, attributes_only=False):\n    if attributes_only:\n        ad_objects = [key for key in sorted(ad_objects[0].keys())]\n    if output_format == 'json':\n        return json.dumps(ad_objects, indent=indent, ensure_ascii=False, sort_keys=True)\n    elif output_format == 'yaml':\n        return yaml.dump(sorted(ad_objects), indent=indent)",
    "docstring": "Serialize the object to the specified format\n\n    :param ad_objects list: A list of ADObjects to serialize\n    :param output_format str: The output format, json or yaml.  Defaults to json\n    :param indent int: The number of spaces to indent, defaults to 2\n    :param attributes only: Only serialize the attributes found in the first record of the list\n        of ADObjects\n\n    :return: A serialized, formatted representation of the list of ADObjects\n    :rtype: str"
  },
  {
    "code": "def _build_qname(self, uri=None, namespaces=None):\n        if not uri:\n            uri = self.uri\n        if not namespaces:\n            namespaces = self.namespaces\n        return uri2niceString(uri, namespaces)",
    "docstring": "extracts a qualified name for a uri"
  },
  {
    "code": "def delete(cls, id):\n        client = cls._new_api_client()\n        return client.make_request(cls, 'delete', url_params={'id': id})",
    "docstring": "Destroy a Union object"
  },
  {
    "code": "def get_density(self):\n        strc = self.get_output_structure()\n        density = sum(strc.get_masses()) / strc.get_volume() * 1.660539040\n        return Property(scalars=[Scalar(value=density)], units=\"g/(cm^3)\")",
    "docstring": "Compute the density from the output structure"
  },
  {
    "code": "def _get_end_index(self):\n        return max(self.index + self.source_window,\n                   self._get_target_index() + self.target_window)",
    "docstring": "Return the end of both windows."
  },
  {
    "code": "def config_settings_loader(request=None):\n    conf = SPConfig()\n    conf.load(copy.deepcopy(settings.SAML_CONFIG))\n    return conf",
    "docstring": "Utility function to load the pysaml2 configuration.\n\n    This is also the default config loader."
  },
  {
    "code": "def Pop(self, key):\n    node = self._hash.get(key)\n    if node:\n      del self._hash[key]\n      self._age.Unlink(node)\n      return node.data",
    "docstring": "Remove the object from the cache completely."
  },
  {
    "code": "def get_delegates(self):\n        candidate_elections = CandidateElection.objects.filter(election=self)\n        delegates = None\n        for ce in candidate_elections:\n            delegates = delegates | ce.delegates.all()\n        return delegates",
    "docstring": "Get all pledged delegates for any candidate in this election."
  },
  {
    "code": "def loop(self):\n        logger.debug(\"Node loop starts for {!r}.\".format(self))\n        while self.should_loop:\n            try:\n                self.step()\n            except InactiveReadableError:\n                break\n        logger.debug(\"Node loop ends for {!r}.\".format(self))",
    "docstring": "The actual infinite loop for this transformation."
  },
  {
    "code": "def get_existing_keys(self, events):\n        data = [e[self.key] for e in events]\n        ss = ','.join(['%s' for _ in data])\n        query = 'SELECT %s FROM %s WHERE %s IN (%s)' % (self.key, self.table, self.key, ss)\n        cursor = self.conn.conn.cursor()\n        cursor.execute(query, data)\n        LOG.info(\"%s (data: %s)\", query, data)\n        existing = [r[0] for r in cursor.fetchall()]\n        LOG.info(\"Existing IDs: %s\" % existing)\n        return set(existing)",
    "docstring": "Returns the list of keys from the given event source that are already in the DB"
  },
  {
    "code": "def addreadergroup(self, newgroup):\n        hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)\n        if 0 != hresult:\n            raise error(\n                'Failed to establish context: ' + \\\n                SCardGetErrorMessage(hresult))\n        try:\n            hresult = SCardIntroduceReaderGroup(hcontext, newgroup)\n            if 0 != hresult:\n                raise error(\n                    'Unable to introduce reader group: ' + \\\n                    SCardGetErrorMessage(hresult))\n            else:\n                innerreadergroups.addreadergroup(self, newgroup)\n        finally:\n            hresult = SCardReleaseContext(hcontext)\n            if 0 != hresult:\n                raise error(\n                    'Failed to release context: ' + \\\n                    SCardGetErrorMessage(hresult))",
    "docstring": "Add a reader group"
  },
  {
    "code": "def content(self):\n        content = self._get_content()\n        if bool(content and '\\0' in content):\n            return content\n        return safe_unicode(content)",
    "docstring": "Returns lazily content of the FileNode. If possible, would try to\n        decode content from UTF-8."
  },
  {
    "code": "def prior_from_config(cp, variable_params, prior_section,\n                          constraint_section):\n        logging.info(\"Setting up priors for each parameter\")\n        dists = distributions.read_distributions_from_config(cp, prior_section)\n        constraints = distributions.read_constraints_from_config(\n            cp, constraint_section)\n        return distributions.JointDistribution(variable_params, *dists,\n                                               constraints=constraints)",
    "docstring": "Gets arguments and keyword arguments from a config file.\n\n        Parameters\n        ----------\n        cp : WorkflowConfigParser\n            Config file parser to read.\n        variable_params : list\n            List of of model parameter names.\n        prior_section : str\n            Section to read prior(s) from.\n        constraint_section : str\n            Section to read constraint(s) from.\n\n        Returns\n        -------\n        pycbc.distributions.JointDistribution\n            The prior."
  },
  {
    "code": "def prefetch_docker_image_on_private_agents(\n        image,\n        timeout=timedelta(minutes=5).total_seconds()):\n    agents = len(shakedown.get_private_agents())\n    app = {\n        \"id\": \"/prefetch\",\n        \"instances\": agents,\n        \"container\": {\n            \"type\": \"DOCKER\",\n            \"docker\": {\"image\": image}\n        },\n        \"cpus\": 0.1,\n        \"mem\": 128\n    }\n    client = marathon.create_client()\n    client.add_app(app)\n    shakedown.deployment_wait(timeout)\n    shakedown.delete_all_apps()\n    shakedown.deployment_wait(timeout)",
    "docstring": "Given a docker image. An app with the image is scale across the private\n        agents to ensure that the image is prefetched to all nodes.\n\n        :param image: docker image name\n        :type image: str\n        :param timeout: timeout for deployment wait in secs (default: 5m)\n        :type password: int"
  },
  {
    "code": "def select(self, *column_or_columns):\n        labels = self._varargs_as_labels(column_or_columns)\n        table = type(self)()\n        for label in labels:\n            self._add_column_and_format(table, label, np.copy(self[label]))\n        return table",
    "docstring": "Return a table with only the columns in ``column_or_columns``.\n\n        Args:\n            ``column_or_columns``: Columns to select from the ``Table`` as\n            either column labels (``str``) or column indices (``int``).\n\n        Returns:\n            A new instance of ``Table`` containing only selected columns.\n            The columns of the new ``Table`` are in the order given in\n            ``column_or_columns``.\n\n        Raises:\n            ``KeyError`` if any of ``column_or_columns`` are not in the table.\n\n        >>> flowers = Table().with_columns(\n        ...     'Number of petals', make_array(8, 34, 5),\n        ...     'Name', make_array('lotus', 'sunflower', 'rose'),\n        ...     'Weight', make_array(10, 5, 6)\n        ... )\n\n        >>> flowers\n        Number of petals | Name      | Weight\n        8                | lotus     | 10\n        34               | sunflower | 5\n        5                | rose      | 6\n\n        >>> flowers.select('Number of petals', 'Weight')\n        Number of petals | Weight\n        8                | 10\n        34               | 5\n        5                | 6\n\n        >>> flowers  # original table unchanged\n        Number of petals | Name      | Weight\n        8                | lotus     | 10\n        34               | sunflower | 5\n        5                | rose      | 6\n\n        >>> flowers.select(0, 2)\n        Number of petals | Weight\n        8                | 10\n        34               | 5\n        5                | 6"
  },
  {
    "code": "def serialize(self, value, entity=None, request=None):\n    ret = self.from_python(value)\n    self.validate(ret)\n    self.run_validators(value)\n    return ret",
    "docstring": "Validate and serialize the value.\n\n    This is the default implementation"
  },
  {
    "code": "def _async_open(self, session_id, proto_version):\n        try:\n            yield self.application_context.create_session_if_needed(session_id, self.request)\n            session = self.application_context.get_session(session_id)\n            protocol = Protocol(proto_version)\n            self.receiver = Receiver(protocol)\n            log.debug(\"Receiver created for %r\", protocol)\n            self.handler = ProtocolHandler()\n            log.debug(\"ProtocolHandler created for %r\", protocol)\n            self.connection = self.application.new_connection(protocol, self, self.application_context, session)\n            log.info(\"ServerConnection created\")\n        except ProtocolError as e:\n            log.error(\"Could not create new server session, reason: %s\", e)\n            self.close()\n            raise e\n        msg = self.connection.protocol.create('ACK')\n        yield self.send_message(msg)\n        raise gen.Return(None)",
    "docstring": "Perform the specific steps needed to open a connection to a Bokeh session\n\n        Specifically, this method coordinates:\n\n        * Getting a session for a session ID (creating a new one if needed)\n        * Creating a protocol receiver and hander\n        * Opening a new ServerConnection and sending it an ACK\n\n        Args:\n            session_id (str) :\n                A session ID to for a session to connect to\n\n                If no session exists with the given ID, a new session is made\n\n            proto_version (str):\n                The protocol version requested by the connecting client.\n\n        Returns:\n            None"
  },
  {
    "code": "def isDocumentCollection(cls, name) :\n        try :\n            col = cls.getCollectionClass(name)\n            return issubclass(col, Collection)\n        except KeyError :\n            return False",
    "docstring": "return true or false wether 'name' is the name of a document collection."
  },
  {
    "code": "def process_request(self, request, client_address):\n        thread = threading.Thread(\n            name=\"RemoteShell-{0}-Client-{1}\".format(\n                self.server_address[1], client_address[:2]\n            ),\n            target=self.process_request_thread,\n            args=(request, client_address),\n        )\n        thread.daemon = self.daemon_threads\n        thread.start()",
    "docstring": "Starts a new thread to process the request, adding the client address\n        in its name."
  },
  {
    "code": "def format_for_columns(pkgs, options):\n    running_outdated = options.outdated\n    if running_outdated:\n        header = [\"Package\", \"Version\", \"Latest\", \"Type\"]\n    else:\n        header = [\"Package\", \"Version\"]\n    data = []\n    if options.verbose >= 1 or any(dist_is_editable(x) for x in pkgs):\n        header.append(\"Location\")\n    if options.verbose >= 1:\n        header.append(\"Installer\")\n    for proj in pkgs:\n        row = [proj.project_name, proj.version]\n        if running_outdated:\n            row.append(proj.latest_version)\n            row.append(proj.latest_filetype)\n        if options.verbose >= 1 or dist_is_editable(proj):\n            row.append(proj.location)\n        if options.verbose >= 1:\n            row.append(get_installer(proj))\n        data.append(row)\n    return data, header",
    "docstring": "Convert the package data into something usable\n    by output_package_listing_columns."
  },
  {
    "code": "def index():\n    for k, v in current_index.items():\n        current_index[k] = 0\n    logging.info(\"Dashboard refreshed\")\n    return render_template(\"crystal_dashboard.html\")",
    "docstring": "Renders the dashboard when the server is initially run.\n\n    Usage description:\n    The rendered HTML allows the user to select a project and the desired run.\n\n    :return: Template to render, Object that is taken care by flask."
  },
  {
    "code": "def time_delta(self, end_datetime=None):\n        start_datetime = self._parse_start_datetime('now')\n        end_datetime = self._parse_end_datetime(end_datetime)\n        seconds = end_datetime - start_datetime\n        ts = self.generator.random.randint(*sorted([0, seconds]))\n        return timedelta(seconds=ts)",
    "docstring": "Get a timedelta object"
  },
  {
    "code": "def remove_router_interface(self, context, router_id, interface_info):\n        router_to_del = (\n            super(AristaL3ServicePlugin, self).remove_router_interface(\n                context,\n                router_id,\n                interface_info)\n            )\n        core = directory.get_plugin()\n        subnet = core.get_subnet(context, router_to_del['subnet_id'])\n        network_id = subnet['network_id']\n        ml2_db = NetworkContext(self, context, {'id': network_id})\n        seg_id = ml2_db.network_segments[0]['segmentation_id']\n        router = self.get_router(context, router_id)\n        router_info = copy.deepcopy(router_to_del)\n        router_info['seg_id'] = seg_id\n        router_info['name'] = router['name']\n        try:\n            self.driver.remove_router_interface(context, router_info)\n            return router_to_del\n        except Exception as exc:\n            LOG.error(_LE(\"Error removing interface %(interface)s from \"\n                          \"router %(router_id)s on Arista HW\"\n                          \"Exception =(exc)s\"),\n                      {'interface': interface_info, 'router_id': router_id,\n                       'exc': exc})",
    "docstring": "Remove a subnet of a network from an existing router."
  },
  {
    "code": "def associate_health_monitor(self, pool, body):\n        return self.post(self.associate_pool_health_monitors_path % (pool),\n                         body=body)",
    "docstring": "Associate  specified load balancer health monitor and pool."
  },
  {
    "code": "def run_send_nologin(*args):\n    for user_rec in MUser.query_nologin():\n        email_add = user_rec.user_email\n        print(email_add)\n        send_mail([email_add],\n                  \"{0}|{1}\".format(SMTP_CFG['name'], email_cfg['title']),\n                  email_cfg['content'])\n        MUser.set_sendemail_time(user_rec.uid)",
    "docstring": "Send email to who not logged in recently."
  },
  {
    "code": "def add(self, item, safe=None):\n\t\titem._set_session(self)\n\t\tif safe is None:\n\t\t\tsafe = self.safe\n\t\tself.queue.append(SaveOp(self.transaction_id, self, item, safe))\n\t\tself.cache_write(item)\n\t\tif self.autoflush:\n\t\t\treturn self.flush()",
    "docstring": "Add an item into the queue of things to be inserted.  Does not flush."
  },
  {
    "code": "def flatMap(self, f, preservesPartitioning=False):\n        return self.mapPartitions(\n            lambda p: (e for pp in p for e in f(pp)),\n            preservesPartitioning,\n        )",
    "docstring": "Apply function f and flatten.\n\n        :param f: mapping function\n        :rtype: DStream"
  },
  {
    "code": "def clear(self):\n        self.pos = [[0 for _ in range(self.board_size)] for _ in range(self.board_size)]\n        self.graph = copy.deepcopy(self.pos)\n        self._game_round = 1",
    "docstring": "Clear a chessboard"
  },
  {
    "code": "def do_mute(self, sender, body, args):\n        if sender.get('MUTED'):\n            self.send_message('you are already muted', sender)\n        else:\n            self.broadcast('%s has muted this chatroom' % (sender['NICK'],))\n            sender['QUEUED_MESSAGES'] = []\n            sender['MUTED'] = True",
    "docstring": "Temporarily mutes chatroom for a user"
  },
  {
    "code": "def requirement_spec(package_name, *args):\r\n    if not args or args == (None,):\r\n        return package_name\r\n    version_specs = []\r\n    for version_spec in args:\r\n        if isinstance(version_spec, (list, tuple)):\r\n            operator, version = version_spec\r\n        else:\r\n            assert isinstance(version_spec, str)\r\n            operator = \"==\"\r\n            version = version_spec\r\n        version_specs.append(\"%s%s\" % (operator, version))\r\n    return \"%s%s\" % (package_name, \",\".join(version_specs))",
    "docstring": "Identifier used when specifying a requirement to pip or setuptools."
  },
  {
    "code": "def humanize_timedelta(td):\n    secs = int(td.total_seconds())\n    hours, secs = divmod(secs, 60 * 60)\n    mins, secs = divmod(secs, 60)\n    if hours:\n        return '%dh %dm' % (hours, mins)\n    if mins:\n        return '%dm' % mins\n    return '%ds' % secs",
    "docstring": "Pretty-print a timedelta in a human readable format."
  },
  {
    "code": "def add_group_members(self, members):\n        if not isinstance(members, list):\n            members = [members]\n        if not getattr(self, 'group_members', None):\n            self.group_members = members\n        else:\n            self.group_members.extend(members)",
    "docstring": "Add a new group member to the groups list\n\n        :param members: member name\n        :type members: str\n        :return: None"
  },
  {
    "code": "def _insert_uncompressed(collection_name, docs, check_keys,\n            safe, last_error_args, continue_on_error, opts):\n    op_insert, max_bson_size = _insert(\n        collection_name, docs, check_keys, continue_on_error, opts)\n    rid, msg = __pack_message(2002, op_insert)\n    if safe:\n        rid, gle, _ = __last_error(collection_name, last_error_args)\n        return rid, msg + gle, max_bson_size\n    return rid, msg, max_bson_size",
    "docstring": "Internal insert message helper."
  },
  {
    "code": "def RGB_to_HSV(cobj, *args, **kwargs):\n    var_R = cobj.rgb_r\n    var_G = cobj.rgb_g\n    var_B = cobj.rgb_b\n    var_max = max(var_R, var_G, var_B)\n    var_min = min(var_R, var_G, var_B)\n    var_H = __RGB_to_Hue(var_R, var_G, var_B, var_min, var_max)\n    if var_max == 0:\n        var_S = 0\n    else:\n        var_S = 1.0 - (var_min / var_max)\n    var_V = var_max\n    return HSVColor(\n        var_H, var_S, var_V)",
    "docstring": "Converts from RGB to HSV.\n\n    H values are in degrees and are 0 to 360.\n    S values are a percentage, 0.0 to 1.0.\n    V values are a percentage, 0.0 to 1.0."
  },
  {
    "code": "def create_subgroup_global(self, id, title, description=None, vendor_guid=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"id\"] = id\r\n        data[\"title\"] = title\r\n        if description is not None:\r\n            data[\"description\"] = description\r\n        if vendor_guid is not None:\r\n            data[\"vendor_guid\"] = vendor_guid\r\n        self.logger.debug(\"POST /api/v1/global/outcome_groups/{id}/subgroups with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"POST\", \"/api/v1/global/outcome_groups/{id}/subgroups\".format(**path), data=data, params=params, single_item=True)",
    "docstring": "Create a subgroup.\r\n\r\n        Creates a new empty subgroup under the outcome group with the given title\r\n        and description."
  },
  {
    "code": "def rfft2d_freqs(h, w):\n    fy = np.fft.fftfreq(h)[:, None]\n    if w % 2 == 1:\n        fx = np.fft.fftfreq(w)[: w // 2 + 2]\n    else:\n        fx = np.fft.fftfreq(w)[: w // 2 + 1]\n    return np.sqrt(fx * fx + fy * fy)",
    "docstring": "Computes 2D spectrum frequencies."
  },
  {
    "code": "def purge_archives(self):\n        klass = self.get_version_class()\n        qs = klass.normal.filter(object_id=self.object_id,\n                                 state=self.ARCHIVED).order_by('-last_save')[self.NUM_KEEP_ARCHIVED:]\n        for obj in qs:\n            obj._delete_reverses()\n            klass.normal.filter(vid=obj.vid).delete()",
    "docstring": "Delete older archived items.\n\n        Use the class attribute NUM_KEEP_ARCHIVED to control\n        how many items are kept."
  },
  {
    "code": "def length_limits(max_length_limit, length_limit_step):\n    string_len = len(str(max_length_limit))\n    return [\n        str(i).zfill(string_len) for i in\n        xrange(\n            length_limit_step,\n            max_length_limit + length_limit_step - 1,\n            length_limit_step\n        )\n    ]",
    "docstring": "Generates the length limits"
  },
  {
    "code": "def schema(self):\n        if self.status == \"DELETING\":\n            return \"\"\n        parts = [\"GLOBAL\", self.index_type, \"INDEX\"]\n        parts.append(\"('%s', %s,\" % (self.name, self.hash_key.name))\n        if self.range_key:\n            parts.append(\"%s,\" % self.range_key.name)\n        if self.includes:\n            parts.append(\"[%s],\" % \", \".join((\"'%s'\" % i for i in self.includes)))\n        parts.append(\n            \"THROUGHPUT (%d, %d))\" % (self.read_throughput, self.write_throughput)\n        )\n        return \" \".join(parts)",
    "docstring": "The DQL fragment for constructing this index"
  },
  {
    "code": "def cmd_dhcp_discover(iface, timeout, verbose):\n    conf.verb = False\n    if iface:\n        conf.iface = iface\n    conf.checkIPaddr = False\n    hw = get_if_raw_hwaddr(conf.iface)\n    ether = Ether(dst=\"ff:ff:ff:ff:ff:ff\")\n    ip = IP(src=\"0.0.0.0\",dst=\"255.255.255.255\")\n    udp = UDP(sport=68,dport=67)\n    bootp = BOOTP(chaddr=hw)\n    dhcp = DHCP(options=[(\"message-type\",\"discover\"),\"end\"])\n    dhcp_discover = ether / ip / udp / bootp / dhcp\n    ans, unans = srp(dhcp_discover, multi=True, timeout=5)\n    for _, pkt in ans:\n        if verbose:\n            print(pkt.show())\n        else:\n            print(pkt.summary())",
    "docstring": "Send a DHCP request and show what devices has replied.\n\n    Note: Using '-v' you can see all the options (like DNS servers) included on the responses.\n\n    \\b\n    # habu.dhcp_discover\n    Ether / IP / UDP 192.168.0.1:bootps > 192.168.0.5:bootpc / BOOTP / DHCP"
  },
  {
    "code": "def latent_prediction_model(inputs,\n                            ed_attention_bias,\n                            latents_discrete,\n                            latents_dense,\n                            hparams,\n                            vocab_size=None,\n                            name=None):\n  with tf.variable_scope(name, default_name=\"latent_prediction\"):\n    if hparams.mode != tf.estimator.ModeKeys.PREDICT:\n      latents_pred = transformer_latent_decoder(tf.stop_gradient(latents_dense),\n                                                inputs,\n                                                ed_attention_bias,\n                                                hparams,\n                                                name)\n      if vocab_size is None:\n        vocab_size = 2**hparams.bottleneck_bits\n      if not hparams.soft_em:\n        latents_discrete = tf.one_hot(latents_discrete, depth=vocab_size)\n      _, latent_pred_loss = ae_latent_softmax(\n          latents_pred, tf.stop_gradient(latents_discrete), vocab_size, hparams)\n  return latents_pred, latent_pred_loss",
    "docstring": "Transformer-based latent prediction model.\n\n  It is an autoregressive decoder over latents_discrete given inputs.\n\n  Args:\n    inputs: Tensor of shape [batch, length_kv, hparams.hidden_size]. Inputs to\n      attend to for the decoder on latents.\n    ed_attention_bias: Tensor which broadcasts with shape [batch,\n      hparams.num_heads, length_q, length_kv]. Encoder-decoder attention bias.\n    latents_discrete: Tensor of shape [batch, length_q, vocab_size].\n      One-hot latents to compute log-probability of given inputs.\n    latents_dense: Tensor of shape [batch, length_q, hparams.hidden_size].\n      length_q is the latent length, which is\n      height * width * hparams.num_latents / (2**hparams.num_compress_steps).\n    hparams: HParams.\n    vocab_size: int or None. If None, it is 2**hparams.bottleneck_bits.\n    name: string, variable scope.\n\n  Returns:\n    latents_pred: Tensor of shape [batch, length_q, hparams.hidden_size].\n    latents_pred_loss: Tensor of shape [batch, length_q]."
  },
  {
    "code": "def context_id(ctx: Context_T, *,\n               mode: str = 'default', use_hash: bool = False) -> str:\n    ctx_id = ''\n    if mode == 'default':\n        if ctx.get('group_id'):\n            ctx_id = f'/group/{ctx[\"group_id\"]}'\n        elif ctx.get('discuss_id'):\n            ctx_id = f'/discuss/{ctx[\"discuss_id\"]}'\n        if ctx.get('user_id'):\n            ctx_id += f'/user/{ctx[\"user_id\"]}'\n    elif mode == 'group':\n        if ctx.get('group_id'):\n            ctx_id = f'/group/{ctx[\"group_id\"]}'\n        elif ctx.get('discuss_id'):\n            ctx_id = f'/discuss/{ctx[\"discuss_id\"]}'\n        elif ctx.get('user_id'):\n            ctx_id = f'/user/{ctx[\"user_id\"]}'\n    elif mode == 'user':\n        if ctx.get('user_id'):\n            ctx_id = f'/user/{ctx[\"user_id\"]}'\n    if ctx_id and use_hash:\n        ctx_id = hashlib.md5(ctx_id.encode('ascii')).hexdigest()\n    return ctx_id",
    "docstring": "Calculate a unique id representing the current context.\n\n    mode:\n      default: one id for one context\n      group: one id for one group or discuss\n      user: one id for one user\n\n    :param ctx: the context dict\n    :param mode: unique id mode: \"default\", \"group\", or \"user\"\n    :param use_hash: use md5 to hash the id or not"
  },
  {
    "code": "def get_names(self):\n        return (['do_' + x for x in self.commands['shell']]\n              + ['do_' + x for x in self.commands['forth']])",
    "docstring": "Get names for autocompletion."
  },
  {
    "code": "def _use_last_dir_name(self, path, prefix=''):\n        matching_dirs = (\n            dir_name\n            for dir_name in reversed(os.listdir(path))\n            if os.path.isdir(os.path.join(path, dir_name)) and\n            dir_name.startswith(prefix)\n        )\n        return next(matching_dirs, None) or ''",
    "docstring": "Return name of the last dir in path or '' if no dir found.\n\n        Parameters\n        ----------\n        path: str\n            Use dirs in this path\n        prefix: str\n            Use only dirs startings by this prefix"
  },
  {
    "code": "def check_element_by_selector(self, selector):\n    elems = find_elements_by_jquery(world.browser, selector)\n    if not elems:\n        raise AssertionError(\"Expected matching elements, none found.\")",
    "docstring": "Assert an element exists matching the given selector."
  },
  {
    "code": "def _write_critic_model_stats(self, iteration:int)->None:\n        \"Writes gradient statistics for critic to Tensorboard.\"\n        critic = self.learn.gan_trainer.critic\n        self.stats_writer.write(model=critic, iteration=iteration, tbwriter=self.tbwriter, name='crit_model_stats')\n        self.crit_stats_updated = True",
    "docstring": "Writes gradient statistics for critic to Tensorboard."
  },
  {
    "code": "def to_packets(pages, strict=False):\n        serial = pages[0].serial\n        sequence = pages[0].sequence\n        packets = []\n        if strict:\n            if pages[0].continued:\n                raise ValueError(\"first packet is continued\")\n            if not pages[-1].complete:\n                raise ValueError(\"last packet does not complete\")\n        elif pages and pages[0].continued:\n            packets.append([b\"\"])\n        for page in pages:\n            if serial != page.serial:\n                raise ValueError(\"invalid serial number in %r\" % page)\n            elif sequence != page.sequence:\n                raise ValueError(\"bad sequence number in %r\" % page)\n            else:\n                sequence += 1\n            if page.continued:\n                packets[-1].append(page.packets[0])\n            else:\n                packets.append([page.packets[0]])\n            packets.extend([p] for p in page.packets[1:])\n        return [b\"\".join(p) for p in packets]",
    "docstring": "Construct a list of packet data from a list of Ogg pages.\n\n        If strict is true, the first page must start a new packet,\n        and the last page must end the last packet."
  },
  {
    "code": "def registerJavaFunction(self, name, javaClassName, returnType=None):\n        jdt = None\n        if returnType is not None:\n            if not isinstance(returnType, DataType):\n                returnType = _parse_datatype_string(returnType)\n            jdt = self.sparkSession._jsparkSession.parseDataType(returnType.json())\n        self.sparkSession._jsparkSession.udf().registerJava(name, javaClassName, jdt)",
    "docstring": "Register a Java user-defined function as a SQL function.\n\n        In addition to a name and the function itself, the return type can be optionally specified.\n        When the return type is not specified we would infer it via reflection.\n\n        :param name: name of the user-defined function\n        :param javaClassName: fully qualified name of java class\n        :param returnType: the return type of the registered Java function. The value can be either\n            a :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.\n\n        >>> from pyspark.sql.types import IntegerType\n        >>> spark.udf.registerJavaFunction(\n        ...     \"javaStringLength\", \"test.org.apache.spark.sql.JavaStringLength\", IntegerType())\n        >>> spark.sql(\"SELECT javaStringLength('test')\").collect()\n        [Row(UDF:javaStringLength(test)=4)]\n\n        >>> spark.udf.registerJavaFunction(\n        ...     \"javaStringLength2\", \"test.org.apache.spark.sql.JavaStringLength\")\n        >>> spark.sql(\"SELECT javaStringLength2('test')\").collect()\n        [Row(UDF:javaStringLength2(test)=4)]\n\n        >>> spark.udf.registerJavaFunction(\n        ...     \"javaStringLength3\", \"test.org.apache.spark.sql.JavaStringLength\", \"integer\")\n        >>> spark.sql(\"SELECT javaStringLength3('test')\").collect()\n        [Row(UDF:javaStringLength3(test)=4)]"
  },
  {
    "code": "async def on_capability_sasl_enabled(self):\n        if self.sasl_mechanism:\n            if self._sasl_mechanisms and self.sasl_mechanism not in self._sasl_mechanisms:\n                self.logger.warning('Requested SASL mechanism is not in server mechanism list: aborting SASL authentication.')\n                return cap.failed\n            mechanisms = [self.sasl_mechanism]\n        else:\n            mechanisms = self._sasl_mechanisms or ['PLAIN']\n        if mechanisms == ['EXTERNAL']:\n            mechanism = 'EXTERNAL'\n        else:\n            self._sasl_client = puresasl.client.SASLClient(self.connection.hostname, 'irc',\n                username=self.sasl_username,\n                password=self.sasl_password,\n                identity=self.sasl_identity\n            )\n            try:\n                self._sasl_client.choose_mechanism(mechanisms, allow_anonymous=False)\n            except puresasl.SASLError:\n                self.logger.exception('SASL mechanism choice failed: aborting SASL authentication.')\n                return cap.FAILED\n            mechanism = self._sasl_client.mechanism.upper()\n        await self._sasl_start(mechanism)\n        return cap.NEGOTIATING",
    "docstring": "Start SASL authentication."
  },
  {
    "code": "def enclosing_frame(frame=None, level=2):\n    frame = frame or sys._getframe(level)\n    while frame.f_globals.get('__name__') == __name__: frame = frame.f_back\n    return frame",
    "docstring": "Get an enclosing frame that skips decorator code"
  },
  {
    "code": "def extend(self):\n        graph = GraphAPI()\n        response = graph.get('oauth/access_token',\n            client_id = FACEBOOK_APPLICATION_ID,\n            client_secret = FACEBOOK_APPLICATION_SECRET_KEY,\n            grant_type = 'fb_exchange_token',\n            fb_exchange_token = self.token\n        )\n        components = parse_qs(response)\n        self.token = components['access_token'][0]\n        self.expires_at = now() + timedelta(seconds = int(components['expires'][0]))\n        self.save()",
    "docstring": "Extend the OAuth token."
  },
  {
    "code": "def external_system_identifiers(endpoint):\n    @utils.flatten\n    @utils.for_each_value\n    def _external_system_identifiers(self, key, value):\n        new_recid = maybe_int(value.get('d'))\n        if new_recid:\n            self['new_record'] = get_record_ref(new_recid, endpoint)\n        return [\n            {\n                'schema': 'SPIRES',\n                'value': ext_sys_id,\n            } for ext_sys_id in force_list(value.get('a'))\n        ]\n    return _external_system_identifiers",
    "docstring": "Populate the ``external_system_identifiers`` key.\n\n    Also populates the ``new_record`` key through side effects."
  },
  {
    "code": "def convert_sbml_model(model):\n    biomass_reactions = set()\n    for reaction in model.reactions:\n        if reaction.id not in model.limits:\n            lower, upper = parse_flux_bounds(reaction)\n            if lower is not None or upper is not None:\n                model.limits[reaction.id] = reaction.id, lower, upper\n        objective = parse_objective_coefficient(reaction)\n        if objective is not None and objective != 0:\n            biomass_reactions.add(reaction.id)\n    if len(biomass_reactions) == 1:\n        model.biomass_reaction = next(iter(biomass_reactions))\n    convert_model_entries(model)\n    if model.extracellular_compartment is None:\n        extracellular = detect_extracellular_compartment(model)\n        model.extracellular_compartment = extracellular\n    convert_exchange_to_compounds(model)",
    "docstring": "Convert raw SBML model to extended model.\n\n    Args:\n        model: :class:`NativeModel` obtained from :class:`SBMLReader`."
  },
  {
    "code": "def add_resources(self, resources):\n    new_resources = self._build_resource_dictionary(resources)\n    for key in new_resources:\n      self._resources[key] = new_resources[key]\n    self._dirty_attributes.add(u'resources')",
    "docstring": "Adds new resources to the event.\n\n    *resources* can be a list of email addresses or :class:`ExchangeEventAttendee` objects."
  },
  {
    "code": "def rescue(f, on_success, on_error=reraise, on_complete=nop):\n    def _rescue(*args, **kwargs):\n        try:\n            return on_success(f(*args, **kwargs))\n        except Exception as e:\n            return on_error(e)\n        finally:\n            on_complete()\n    return _rescue",
    "docstring": "Functional try-except-finally\n\n    :param function f: guarded function\n    :param function on_succes: called when f is executed without error\n    :param function on_error: called with `error` parameter when f failed\n    :param function on_complete: called as finally block\n    :returns function: call signature is equal f signature"
  },
  {
    "code": "def call_next(self):\n        if self.handle is not None:\n            self.handle.cancel()\n        next_time = self.get_next()\n        self.handle = self.loop.call_at(next_time, self.call_next)\n        self.call_func()",
    "docstring": "Set next hop in the loop. Call task"
  },
  {
    "code": "def initialize(self, name, reuse=False):\n        user = self._kwargs['user']\n        password = self._kwargs['password']\n        host = self._kwargs['host']\n        port = self._kwargs['port']\n        if '-' in name:\n            self.error(\"dabase name '%s' cannot contain '-' characters\" % name)\n            return CODE_VALUE_ERROR\n        try:\n            Database.create(user, password, name, host, port)\n            db = Database(user, password, name, host, port)\n            self.__load_countries(db)\n        except DatabaseExists as e:\n            if not reuse:\n                self.error(str(e))\n                return CODE_DATABASE_EXISTS\n        except DatabaseError as e:\n            self.error(str(e))\n            return CODE_DATABASE_ERROR\n        except LoadError as e:\n            Database.drop(user, password, name, host, port)\n            self.error(str(e))\n            return CODE_LOAD_ERROR\n        return CMD_SUCCESS",
    "docstring": "Create an empty Sorting Hat registry.\n\n        This method creates a new database including the schema of Sorting Hat.\n        Any attempt to create a new registry over an existing instance will\n        produce an error, except if reuse=True. In that case, the\n        database will be reused, assuming the database schema is correct\n        (it won't be created in this case).\n\n        :param  name: name of the database\n        :param reuse: reuse database if it already exists"
  },
  {
    "code": "def get_nested_blocks_spec(self):\n        return [\n            block_spec if isinstance(block_spec, NestedXBlockSpec) else NestedXBlockSpec(block_spec)\n            for block_spec in self.allowed_nested_blocks\n        ]",
    "docstring": "Converts allowed_nested_blocks items to NestedXBlockSpec to provide common interface"
  },
  {
    "code": "def batch_delete_entities(self,\n                              parent,\n                              entity_values,\n                              language_code=None,\n                              retry=google.api_core.gapic_v1.method.DEFAULT,\n                              timeout=google.api_core.gapic_v1.method.DEFAULT,\n                              metadata=None):\n        if 'batch_delete_entities' not in self._inner_api_calls:\n            self._inner_api_calls[\n                'batch_delete_entities'] = google.api_core.gapic_v1.method.wrap_method(\n                    self.transport.batch_delete_entities,\n                    default_retry=self._method_configs[\n                        'BatchDeleteEntities'].retry,\n                    default_timeout=self._method_configs['BatchDeleteEntities']\n                    .timeout,\n                    client_info=self._client_info,\n                )\n        request = entity_type_pb2.BatchDeleteEntitiesRequest(\n            parent=parent,\n            entity_values=entity_values,\n            language_code=language_code,\n        )\n        operation = self._inner_api_calls['batch_delete_entities'](\n            request, retry=retry, timeout=timeout, metadata=metadata)\n        return google.api_core.operation.from_gapic(\n            operation,\n            self.transport._operations_client,\n            empty_pb2.Empty,\n            metadata_type=struct_pb2.Struct,\n        )",
    "docstring": "Deletes entities in the specified entity type.\n\n        Operation <response: ``google.protobuf.Empty``,\n        metadata: [google.protobuf.Struct][google.protobuf.Struct]>\n\n        Example:\n            >>> import dialogflow_v2\n            >>>\n            >>> client = dialogflow_v2.EntityTypesClient()\n            >>>\n            >>> parent = client.entity_type_path('[PROJECT]', '[ENTITY_TYPE]')\n            >>>\n            >>> # TODO: Initialize ``entity_values``:\n            >>> entity_values = []\n            >>>\n            >>> response = client.batch_delete_entities(parent, entity_values)\n            >>>\n            >>> def callback(operation_future):\n            ...     # Handle result.\n            ...     result = operation_future.result()\n            >>>\n            >>> response.add_done_callback(callback)\n            >>>\n            >>> # Handle metadata.\n            >>> metadata = response.metadata()\n\n        Args:\n            parent (str): Required. The name of the entity type to delete entries for. Format:\n                ``projects/<Project ID>/agent/entityTypes/<Entity Type ID>``.\n            entity_values (list[str]): Required. The canonical ``values`` of the entities to delete. Note that\n                these are not fully-qualified names, i.e. they don't start with\n                ``projects/<Project ID>``.\n            language_code (str): Optional. The language of entity synonyms defined in ``entities``. If not\n                specified, the agent's default language is used.\n                [More than a dozen\n                languages](https://dialogflow.com/docs/reference/language) are supported.\n                Note: languages must be enabled in the agent, before they can be used.\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "async def get_participant(self, p_id: int, force_update=False) -> Participant:\n        found_p = self._find_participant(p_id)\n        if force_update or found_p is None:\n            await self.get_participants()\n            found_p = self._find_participant(p_id)\n        return found_p",
    "docstring": "get a participant by its id\n\n        |methcoro|\n\n        Args:\n            p_id: participant id\n            force_update (dfault=False): True to force an update to the Challonge API\n\n        Returns:\n            Participant: None if not found\n\n        Raises:\n            APIException"
  },
  {
    "code": "def _get_result_paths(self, output_dir):\n        self._write_properties_file()\n        properties_fp = os.path.join(self.ModelDir, self.PropertiesFile)\n        result_paths = {\n            'properties': ResultPath(properties_fp, IsWritten=True,)\n        }\n        return result_paths",
    "docstring": "Return a dict of output files."
  },
  {
    "code": "def smartos():\n    grains = {}\n    if salt.utils.platform.is_smartos_zone():\n        grains = salt.utils.dictupdate.update(grains, _smartos_zone_data(), merge_lists=True)\n        grains = salt.utils.dictupdate.update(grains, _smartos_zone_pkgsrc_data(), merge_lists=True)\n        grains = salt.utils.dictupdate.update(grains, _smartos_zone_pkgin_data(), merge_lists=True)\n    elif salt.utils.platform.is_smartos_globalzone():\n        grains = salt.utils.dictupdate.update(grains, _smartos_computenode_data(), merge_lists=True)\n    return grains",
    "docstring": "Provide grains for SmartOS"
  },
  {
    "code": "def _setTag(self, tag):\n        if tag:\n            self._tagRef = weakref.ref(tag)\n        else:\n            self._tagRef = None",
    "docstring": "_setTag - INTERNAL METHOD. Associated a given AdvancedTag to this attributes dict.\n\n                        If bool(#tag) is True, will set the weakref to that tag.\n\n                        Otherwise, will clear the reference\n\n                      @param tag <AdvancedTag/None> - Either the AdvancedTag to associate, or None to clear current association"
  },
  {
    "code": "def list_env(saltenv='base'):\n    ret = {}\n    if saltenv not in __opts__['pillar_roots']:\n        return ret\n    for f_root in __opts__['pillar_roots'][saltenv]:\n        ret[f_root] = {}\n        for root, dirs, files in salt.utils.path.os_walk(f_root):\n            sub = ret[f_root]\n            if root != f_root:\n                sroot = root\n                above = []\n                while not os.path.samefile(sroot, f_root):\n                    base = os.path.basename(sroot)\n                    if base:\n                        above.insert(0, base)\n                    sroot = os.path.dirname(sroot)\n                for aroot in above:\n                    sub = sub[aroot]\n            for dir_ in dirs:\n                sub[dir_] = {}\n            for fn_ in files:\n                sub[fn_] = 'f'\n    return ret",
    "docstring": "Return all of the file paths found in an environment"
  },
  {
    "code": "def linestrings_to_path(multi):\n    entities = []\n    vertices = []\n    if not util.is_sequence(multi):\n        multi = [multi]\n    for line in multi:\n        if hasattr(line, 'coords'):\n            coords = np.array(line.coords)\n            if len(coords) < 2:\n                continue\n            entities.append(Line(np.arange(len(coords)) +\n                                 len(vertices)))\n            vertices.extend(coords)\n    kwargs = {'entities': np.array(entities),\n              'vertices': np.array(vertices)}\n    return kwargs",
    "docstring": "Load shapely LineString objects into a trimesh.path.Path2D object\n\n    Parameters\n    -------------\n    multi : shapely.geometry.LineString or MultiLineString\n      Input 2D geometry\n\n    Returns\n    -------------\n    kwargs : dict\n      Keyword arguments for Path2D constructor"
  },
  {
    "code": "def parameterized_send(self, request, parameter_list):\n        response_queues = OrderedDict()\n        for parameter in parameter_list:\n            response_queues[parameter] = self.send(request % parameter)\n        return response_queues",
    "docstring": "Send batched requests for a list of parameters\n\n        Args:\n            request (str): Request to send, like \"%s.*?\\n\"\n            parameter_list (list): parameters to format with, like\n                [\"TTLIN\", \"TTLOUT\"]\n\n        Returns:\n            dict: {parameter: response_queue}"
  },
  {
    "code": "def away_two_point_field_goal_percentage(self):\n        result = float(self.away_two_point_field_goals) / \\\n            float(self.away_two_point_field_goal_attempts)\n        return round(float(result), 3)",
    "docstring": "Returns a ``float`` of the number of two point field goals made divided\n        by the number of two point field goal attempts by the away team.\n        Percentage ranges from 0-1."
  },
  {
    "code": "def get(self, request):\n        user = request.user\n        serializer = PermissionsUserSerializer(\n            instance=user, context={'request': request})\n        return Response(data=serializer.data)",
    "docstring": "Get user information, with a list of permissions for that user."
  },
  {
    "code": "def rolling_upgrade(self, upgrade_from_cdh_version,\n                      upgrade_to_cdh_version,\n                      upgrade_service_names,\n                      slave_batch_size=None,\n                      slave_fail_count_threshold=None,\n                      sleep_seconds=None):\n    args = dict()\n    args['upgradeFromCdhVersion'] = upgrade_from_cdh_version\n    args['upgradeToCdhVersion'] = upgrade_to_cdh_version\n    args['upgradeServiceNames'] = upgrade_service_names\n    if slave_batch_size:\n      args['slaveBatchSize'] = slave_batch_size\n    if slave_fail_count_threshold:\n      args['slaveFailCountThreshold'] = slave_fail_count_threshold\n    if sleep_seconds:\n      args['sleepSeconds'] = sleep_seconds\n    return self._cmd('rollingUpgrade', data=args, api_version=10)",
    "docstring": "Command to do a rolling upgrade of services in the given cluster\n\n    This command does not handle any services that don't support rolling\n    upgrades. The command will throw an error and not start if upgrade of\n    any such service is requested.\n\n    This command does not upgrade the full CDH Cluster. You should normally\n    use the upgradeCDH Command for upgrading the cluster. This is primarily\n    helpful if you need to need to recover from an upgrade failure or for\n    advanced users to script an alternative to the upgradeCdhCommand.\n\n    This command expects the binaries to be available on hosts and activated.\n    It does not change any binaries on the hosts.\n\n    @param upgrade_from_cdh_version: Current CDH Version of the services.\n           Example versions are: \"5.1.0\", \"5.2.2\" or \"5.4.0\"\n    @param upgrade_to_cdh_version: Target CDH Version for the services.\n           The CDH version should already be present and activated on the nodes.\n           Example versions are: \"5.1.0\", \"5.2.2\" or \"5.4.0\"\n    @param upgrade_service_names: List of specific services to be upgraded and restarted.\n    @param slave_batch_size: Number of hosts with slave roles to restart at a time\n           Must be greater than 0. Default is 1.\n    @param slave_fail_count_threshold: The threshold for number of slave host batches that\n           are allowed to fail to restart before the entire command is considered failed.\n           Must be >= 0. Default is 0.\n    @param sleep_seconds: Number of seconds to sleep between restarts of slave host batches.\n           Must be >=0. Default is 0.\n\n    @return: Reference to the submitted command.\n    @since: API v10"
  },
  {
    "code": "def _static(self, target, value):\n        return 'static ' + self.__p(ast.Assign(targets=[target],value=value))",
    "docstring": "PHP's \"static\""
  },
  {
    "code": "def elapsed_time_from(start_time):\n    time_then = make_time(start_time)\n    time_now = datetime.utcnow().replace(microsecond=0)\n    if time_then is None:\n        return\n    delta_t = time_now - time_then\n    return delta_t",
    "docstring": "calculate time delta from latched time and current time"
  },
  {
    "code": "def assert_regex(text, regex, msg_fmt=\"{msg}\"):\n    compiled = re.compile(regex)\n    if not compiled.search(text):\n        msg = \"{!r} does not match {!r}\".format(text, compiled.pattern)\n        fail(msg_fmt.format(msg=msg, text=text, pattern=compiled.pattern))",
    "docstring": "Fail if text does not match the regular expression.\n\n    regex can be either a regular expression string or a compiled regular\n    expression object.\n\n    >>> assert_regex(\"Hello World!\", r\"llo.*rld!$\")\n    >>> assert_regex(\"Hello World!\", r\"\\\\d\")\n    Traceback (most recent call last):\n        ...\n    AssertionError: 'Hello World!' does not match '\\\\\\\\d'\n\n    The following msg_fmt arguments are supported:\n    * msg - the default error message\n    * text - text that is matched\n    * pattern - regular expression pattern as string"
  },
  {
    "code": "def get_compliance_expansion(self):\n        if not self.order <= 4:\n            raise ValueError(\"Compliance tensor expansion only \"\n                             \"supported for fourth-order and lower\")\n        ce_exp = [ElasticTensor(self[0]).compliance_tensor]\n        einstring = \"ijpq,pqrsuv,rskl,uvmn->ijklmn\"\n        ce_exp.append(np.einsum(einstring, -ce_exp[-1], self[1],\n                                ce_exp[-1], ce_exp[-1]))\n        if self.order == 4:\n            einstring_1 = \"pqab,cdij,efkl,ghmn,abcdefgh\"\n            tensors_1 = [ce_exp[0]]*4 + [self[-1]]\n            temp = -np.einsum(einstring_1, *tensors_1)\n            einstring_2 = \"pqab,abcdef,cdijmn,efkl\"\n            einstring_3 = \"pqab,abcdef,efklmn,cdij\"\n            einstring_4 = \"pqab,abcdef,cdijkl,efmn\"\n            for es in [einstring_2, einstring_3, einstring_4]:\n                temp -= np.einsum(es, ce_exp[0], self[-2], ce_exp[1], ce_exp[0])\n            ce_exp.append(temp)\n        return TensorCollection(ce_exp)",
    "docstring": "Gets a compliance tensor expansion from the elastic\n        tensor expansion."
  },
  {
    "code": "def get_url(self, version=None):\n        if self.fixed_bundle_url:\n            return self.fixed_bundle_url\n        return '%s.%s.%s' % (os.path.join(self.bundle_url_root, self.bundle_filename), version or self.get_version(), self.bundle_type)",
    "docstring": "Return the filename of the bundled bundle"
  },
  {
    "code": "def trace(f, *args, **kwargs):\n\tprint 'Calling %s() with args %s, %s ' % (f.__name__, args, kwargs)\n\treturn f(*args,**kwargs)",
    "docstring": "Decorator used to trace function calls for debugging purposes."
  },
  {
    "code": "def _connect(self, sock, addr, timeout):\n        if self.connection:\n            raise SocketClientConnectedError()\n        if self.connector:\n            raise SocketClientConnectingError()\n        self.connect_deferred = Deferred(self.loop)\n        self.sock = sock\n        self.addr = addr\n        self.connector = Connector(self.loop, sock, addr, timeout)\n        self.connector.deferred.add_callback(self._connected)\n        self.connector.deferred.add_errback(self._connect_failed)\n        self.connector.start()\n        return self.connect_deferred",
    "docstring": "Start watching the socket for it to be writtable."
  },
  {
    "code": "def charge(self, user, vault_id=None):\n        assert self.is_in_vault(user)\n        if vault_id:\n            user_vault = self.get(user=user, vault_id=vault_id)\n        else:\n            user_vault = self.get(user=user)",
    "docstring": "If vault_id is not passed this will assume that there is only one instane of user and vault_id in the db."
  },
  {
    "code": "def valid (names):\n    if isinstance(names, str):\n        names = [names]\n        assert is_iterable_typed(names, basestring)\n    return all(name in __all_features for name in names)",
    "docstring": "Returns true iff all elements of names are valid features."
  },
  {
    "code": "def insert(self, item, low_value):\n        return c_void_p(lib.zlistx_insert(self._as_parameter_, item, low_value))",
    "docstring": "Create a new node and insert it into a sorted list. Calls the item\nduplicator, if any, on the item. If low_value is true, starts searching\nfrom the start of the list, otherwise searches from the end. Use the item\ncomparator, if any, to find where to place the new node. Returns a handle\nto the new node, or NULL if memory was exhausted. Resets the cursor to the\nlist head."
  },
  {
    "code": "def task_log(self):\n        if self.task_id is None:\n            raise ValueError('task_id is None')\n        return self.get_task_log(self.task_id, self.session, self.request_kwargs)",
    "docstring": "Get task log.\n\n        :rtype: str\n        :returns: The task log as a string."
  },
  {
    "code": "def parse_protobuf(self, proto_type):\n        if 'protobuf' not in self.environ.get('CONTENT_TYPE', ''):\n            raise BadRequest('Not a Protobuf request')\n        obj = proto_type()\n        try:\n            obj.ParseFromString(self.data)\n        except Exception:\n            raise BadRequest(\"Unable to parse Protobuf request\")\n        if self.protobuf_check_initialization and not obj.IsInitialized():\n            raise BadRequest(\"Partial Protobuf request\")\n        return obj",
    "docstring": "Parse the data into an instance of proto_type."
  },
  {
    "code": "def get_topic_set(file_path):\n    topic_set = set()\n    file_row_gen = get_file_row_generator(file_path, \",\")\n    for file_row in file_row_gen:\n        topic_set.add(file_row[0])\n    return topic_set",
    "docstring": "Opens one of the topic set resource files and returns a set of topics.\n\n    - Input:  - file_path: The path pointing to the topic set resource file.\n\n    - Output: - topic_set: A python set of strings."
  },
  {
    "code": "def get_group(self, group_id):\n        def process_result(result):\n            return Group(self, result)\n        return Command('get', [ROOT_GROUPS, group_id],\n                       process_result=process_result)",
    "docstring": "Return specified group.\n\n        Returns a Command."
  },
  {
    "code": "def ways_in_bbox(lat_min, lng_min, lat_max, lng_max, network_type,\n                 timeout=180, memory=None,\n                 max_query_area_size=50*1000*50*1000,\n                 custom_osm_filter=None):\n    return parse_network_osm_query(\n        osm_net_download(lat_max=lat_max, lat_min=lat_min, lng_min=lng_min,\n                         lng_max=lng_max, network_type=network_type,\n                         timeout=timeout, memory=memory,\n                         max_query_area_size=max_query_area_size,\n                         custom_osm_filter=custom_osm_filter))",
    "docstring": "Get DataFrames of OSM data in a bounding box.\n\n    Parameters\n    ----------\n    lat_min : float\n        southern latitude of bounding box\n    lng_min : float\n        eastern longitude of bounding box\n    lat_max : float\n        northern latitude of bounding box\n    lng_max : float\n        western longitude of bounding box\n    network_type : {'walk', 'drive'}, optional\n        Specify the network type where value of 'walk' includes roadways\n        where pedestrians are allowed and pedestrian pathways and 'drive'\n        includes driveable roadways.\n    timeout : int\n        the timeout interval for requests and to pass to Overpass API\n    memory : int\n        server memory allocation size for the query, in bytes. If none,\n        server will use its default allocation size\n    max_query_area_size : float\n        max area for any part of the geometry, in the units the geometry is\n        in: any polygon bigger will get divided up for multiple queries to\n        Overpass API (default is 50,000 * 50,000 units (ie, 50km x 50km in\n        area, if units are meters))\n    custom_osm_filter : string, optional\n        specify custom arguments for the way[\"highway\"] query to OSM. Must\n        follow Overpass API schema. For\n        example to request highway ways that are service roads use:\n        '[\"highway\"=\"service\"]'\n\n    Returns\n    -------\n    nodes, ways, waynodes : pandas.DataFrame"
  },
  {
    "code": "def cmd_condition_yaw(self, args):\n        if ( len(args) != 3):\n            print(\"Usage: yaw ANGLE ANGULAR_SPEED MODE:[0 absolute / 1 relative]\")\n            return\n        if (len(args) == 3):\n            angle = float(args[0])\n            angular_speed = float(args[1])\n            angle_mode = float(args[2])\n            print(\"ANGLE %s\" % (str(angle)))\n            self.master.mav.command_long_send(\n                self.settings.target_system,\n                mavutil.mavlink.MAV_COMP_ID_SYSTEM_CONTROL,\n                mavutil.mavlink.MAV_CMD_CONDITION_YAW,\n                0,\n                angle,\n                angular_speed,\n                0,\n                angle_mode,\n                0,\n                0,\n                0)",
    "docstring": "yaw angle angular_speed angle_mode"
  },
  {
    "code": "def to_python_index(self, length, check_bounds=True, circular=False):\n        if not self.is_unitless:\n            raise ValueError(\"Index cannot have units: {0!r}\".format(self))\n        ret = int(self.value)\n        if ret != self.value:\n            raise ValueError(\"Index must be an integer: {0!r}\".format(ret))\n        if ret == 0:\n            raise ValueError(\"Index cannot be zero\")\n        if check_bounds and not circular and abs(ret) > length:\n            raise ValueError(\"Index {0!r} out of bounds for length {1}\".format(ret, length))\n        if ret > 0:\n            ret -= 1\n        if circular:\n            ret = ret % length\n        return ret",
    "docstring": "Return a plain Python integer appropriate for indexing a sequence of\n        the given length.  Raise if this is impossible for any reason\n        whatsoever."
  },
  {
    "code": "def find(s):\n    abbrev1 = None\n    origS = s\n    if ' ' in s:\n        first, rest = s.split(' ', 1)\n        s = first.title() + ' ' + rest.lower()\n    else:\n        s = s.title()\n    if s in NAMES:\n        abbrev1 = s\n    elif s in ABBREV3_TO_ABBREV1:\n        abbrev1 = ABBREV3_TO_ABBREV1[s]\n    elif s in NAMES_TO_ABBREV1:\n        abbrev1 = NAMES_TO_ABBREV1[s]\n    else:\n        def findCodon(target):\n            for abbrev1, codons in CODONS.items():\n                for codon in codons:\n                    if codon == target:\n                        return abbrev1\n        abbrev1 = findCodon(origS.upper())\n    if abbrev1:\n        return AminoAcid(\n            NAMES[abbrev1], ABBREV3[abbrev1], abbrev1, CODONS[abbrev1],\n            PROPERTIES[abbrev1], PROPERTY_DETAILS[abbrev1],\n            PROPERTY_CLUSTERS[abbrev1])",
    "docstring": "Find an amino acid whose name or abbreviation is s.\n\n    @param s: A C{str} amino acid specifier. This may be a full name,\n        a 3-letter abbreviation or a 1-letter abbreviation. Case is ignored.\n    return: An L{AminoAcid} instance or C{None} if no matching amino acid can\n        be located."
  },
  {
    "code": "def Q(name):\n    retval = PApplet.getDeclaredField(name).get(Sketch.get_instance())\n    if isinstance(retval, (long, int)):\n        return float(retval)\n    else:\n        return retval",
    "docstring": "Gets a variable from the current sketch. Processing has a number\n    of methods and variables with the same name, 'mousePressed' for\n    example. This allows us to disambiguate.\n\n    Also casts numeric values as floats to make it easier to translate\n    code from pde to python."
  },
  {
    "code": "def _check_align(self):\n        if not hasattr(self, \"_align\"):\n            self._align = [\"l\"]*self._row_size\n        if not hasattr(self, \"_valign\"):\n            self._valign = [\"t\"]*self._row_size",
    "docstring": "Check if alignment has been specified, set default one if not"
  },
  {
    "code": "def get_default_if():\n    f = open ('/proc/net/route', 'r')\n    for line in f:\n        words = line.split()\n        dest = words[1]\n        try:\n            if (int (dest) == 0):\n                interf = words[0]\n                break\n        except ValueError:\n            pass\n    return interf",
    "docstring": "Returns the default interface"
  },
  {
    "code": "def create():\n    if not os.path.isdir(options.path):\n        logger.info('creating working directory: ' + options.path)\n        os.makedirs(options.path)",
    "docstring": "Create workdir.options.path"
  },
  {
    "code": "def _initialize(self, boto_session, sagemaker_client, sagemaker_runtime_client):\n        self.boto_session = boto_session or boto3.Session()\n        self._region_name = self.boto_session.region_name\n        if self._region_name is None:\n            raise ValueError('Must setup local AWS configuration with a region supported by SageMaker.')\n        self.sagemaker_client = sagemaker_client or self.boto_session.client('sagemaker')\n        prepend_user_agent(self.sagemaker_client)\n        if sagemaker_runtime_client is not None:\n            self.sagemaker_runtime_client = sagemaker_runtime_client\n        else:\n            config = botocore.config.Config(read_timeout=80)\n            self.sagemaker_runtime_client = self.boto_session.client('runtime.sagemaker', config=config)\n        prepend_user_agent(self.sagemaker_runtime_client)\n        self.local_mode = False",
    "docstring": "Initialize this SageMaker Session.\n\n        Creates or uses a boto_session, sagemaker_client and sagemaker_runtime_client.\n        Sets the region_name."
  },
  {
    "code": "def max_intensity(self, time):\n        ti = np.where(time == self.times)[0][0]\n        return self.timesteps[ti].max()",
    "docstring": "Calculate the maximum intensity found at a timestep."
  },
  {
    "code": "def getheader(self, field, default=''):\n        if self.headers:\n            for header in self.headers:\n                if field.lower() == header.lower():\n                    return self.headers[header]\n        return default",
    "docstring": "Returns the HTTP response header field, case insensitively"
  },
  {
    "code": "def render_template(self, template_file, target_file, template_vars = {}):\n        template_dir = str(self.__class__.__name__).lower()\n        template = self.jinja_env.get_template(os.path.join(template_dir, template_file))\n        file_path = os.path.join(self.work_root, target_file)\n        with open(file_path, 'w') as f:\n            f.write(template.render(template_vars))",
    "docstring": "Render a Jinja2 template for the backend\n\n        The template file is expected in the directory templates/BACKEND_NAME."
  },
  {
    "code": "def render_django_response(self, **kwargs):\n        from django.http import HttpResponse\n        return HttpResponse(\n            self.render(**kwargs), content_type='image/svg+xml'\n        )",
    "docstring": "Render the graph, and return a Django response"
  },
  {
    "code": "def create_relation(self, event, content_object, distinction=''):\n        return EventRelation.objects.create(\n            event=event,\n            distinction=distinction,\n            content_object=content_object)",
    "docstring": "Creates a relation between event and content_object.\n        See EventRelation for help on distinction."
  },
  {
    "code": "def find_first_fit(unoccupied_columns, row, row_length):\n    for free_col in unoccupied_columns:\n        first_item_x = row[0][0]\n        offset = free_col - first_item_x\n        if check_columns_fit(unoccupied_columns, row, offset, row_length):\n            return offset\n    raise ValueError(\"Row cannot bossily fit in %r: %r\"\n                     % (list(unoccupied_columns.keys()), row))",
    "docstring": "Finds the first index that the row's items can fit."
  },
  {
    "code": "def remove_port_channel(self, **kwargs):\n        port_int = kwargs.pop('port_int')\n        callback = kwargs.pop('callback', self._callback)\n        if re.search('^[0-9]{1,4}$', port_int) is None:\n            raise ValueError('%s must be in the format of x for port channel '\n                             'interfaces.' % repr(port_int))\n        port_channel = getattr(self._interface, 'interface_port_channel_name')\n        port_channel_args = dict(name=port_int)\n        config = port_channel(**port_channel_args)\n        delete_channel = config.find('.//*port-channel')\n        delete_channel.set('operation', 'delete')\n        return callback(config)",
    "docstring": "Remove a port channel interface.\n\n        Args:\n            port_int (str): port-channel number (1, 2, 3, etc).\n            callback (function): A function executed upon completion of the\n                 method.  The only parameter passed to `callback` will be the\n                 ``ElementTree`` `config`.\n\n        Returns:\n            Return value of `callback`.\n\n        Raises:\n            KeyError: if `port_int` is not passed.\n            ValueError: if `port_int` is invalid.\n\n        Examples:\n            >>> import pynos.device\n            >>> switches = ['10.24.39.211', '10.24.39.203']\n            >>> auth = ('admin', 'password')\n            >>> for switch in switches:\n            ...     conn = (switch, '22')\n            ...     with pynos.device.Device(conn=conn, auth=auth) as dev:\n            ...         output = dev.interface.channel_group(name='225/0/20',\n            ...         int_type='tengigabitethernet',\n            ...         port_int='1', channel_type='standard', mode='active')\n            ...         output = dev.interface.remove_port_channel(\n            ...         port_int='1')"
  },
  {
    "code": "def to_networkx(self):\n        try:\n            from networkx import DiGraph, set_node_attributes\n        except ImportError:\n            raise ImportError('You must have networkx installed to export networkx graphs')\n        max_node = 2 * self._linkage.shape[0]\n        num_points = max_node - (self._linkage.shape[0] - 1)\n        result = DiGraph()\n        for parent, row in enumerate(self._linkage, num_points):\n            result.add_edge(parent, row[0], weight=row[2])\n            result.add_edge(parent, row[1], weight=row[2])\n        size_dict = {parent: row[3] for parent, row in enumerate(self._linkage, num_points)}\n        set_node_attributes(result, size_dict, 'size')\n        return result",
    "docstring": "Return a NetworkX DiGraph object representing the single linkage tree.\n\n        Edge weights in the graph are the distance values at which child nodes\n        merge to form the parent cluster.\n\n        Nodes have a `size` attribute attached giving the number of points\n        that are in the cluster."
  },
  {
    "code": "def write_case_data(self, file):\n        writer = self._get_writer(file)\n        writer.writerow([\"Name\", \"base_mva\"])\n        writer.writerow([self.case.name, self.case.base_mva])",
    "docstring": "Writes the case data as CSV."
  },
  {
    "code": "def get_vertex(self, key):\n    if key in self.vertex_map:\n      return self.vertex_map[key]\n    vertex = self.new_vertex()\n    self.vertex_map[key] = vertex\n    return vertex",
    "docstring": "Returns or Creates a Vertex mapped by key.\n\n    Args:\n      key: A string reference for a vertex.  May refer to a new Vertex in which\n      case it will be created.\n\n    Returns:\n      A the Vertex mapped to by key."
  },
  {
    "code": "def subtract_column_median(df, prefix='Intensity '):\n    df = df.copy()\n    df.replace([np.inf, -np.inf], np.nan, inplace=True)\n    mask = [l.startswith(prefix) for l in df.columns.values]\n    df.iloc[:, mask] = df.iloc[:, mask] - df.iloc[:, mask].median(axis=0)\n    return df",
    "docstring": "Apply column-wise normalisation to expression columns.\n\n    Default is median transform to expression columns beginning with Intensity\n\n\n    :param df:\n    :param prefix: The column prefix for expression columns\n    :return:"
  },
  {
    "code": "def get_objects(self, force=None, last_update=None, flush=False):\n        return self._run_object_import(force=force, last_update=last_update,\n                                       flush=flush, full_history=False)",
    "docstring": "Extract routine for SQL based cubes.\n\n        :param force:\n            for querying for all objects (True) or only those passed in as list\n        :param last_update: manual override for 'changed since date'"
  },
  {
    "code": "def unfold(tensor, mode):\n    return np.moveaxis(tensor, mode, 0).reshape((tensor.shape[mode], -1))",
    "docstring": "Returns the mode-`mode` unfolding of `tensor`.\n\n    Parameters\n    ----------\n    tensor : ndarray\n    mode : int\n\n    Returns\n    -------\n    ndarray\n        unfolded_tensor of shape ``(tensor.shape[mode], -1)``\n\n    Author\n    ------\n    Jean Kossaifi <https://github.com/tensorly>"
  },
  {
    "code": "def write(self):\n        index_file = self.path\n        new_index_file = index_file + '.new'\n        bak_index_file = index_file + '.bak'\n        if not self._db:\n            return\n        with open(new_index_file, 'w') as f:\n            json.dump(self._db, f, indent=4)\n        if exists(index_file):\n            copy(index_file, bak_index_file)\n        rename(new_index_file, index_file)",
    "docstring": "Safely write the index data to the index file"
  },
  {
    "code": "def update_remote_archive(self, save_uri, timeout=-1):\n        return self._client.update_with_zero_body(uri=save_uri, timeout=timeout)",
    "docstring": "Saves a backup of the appliance to a previously-configured remote location.\n\n        Args:\n            save_uri (dict): The URI for saving the backup to a previously configured location.\n            timeout:\n                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n                in OneView, just stop waiting for its completion.\n\n        Returns:\n            dict: Backup details."
  },
  {
    "code": "def progress(self, msg, onerror=None, sep='...', end='DONE', abrt='FAIL',\n                 prog='.', excs=(Exception,), reraise=True):\n        if not onerror:\n            onerror = self.error()\n        if type(onerror) is str:\n            onerror = self.error(msg=onerror)\n        self.pverb(msg, end=sep)\n        prog = progress.Progress(self.pverb, end=end, abrt=abrt, prog=prog)\n        try:\n            yield prog\n            prog.end()\n        except self.ProgressOK:\n            pass\n        except self.ProgressAbrt as err:\n            if reraise:\n                raise err\n        except KeyboardInterrupt:\n            raise\n        except excs as err:\n            prog.abrt(noraise=True)\n            if onerror:\n                onerror(err)\n            if self.debug:\n                traceback.print_exc()\n            if reraise:\n                raise self.ProgressAbrt()",
    "docstring": "Context manager for handling interactive prog indication\n\n        This context manager streamlines presenting banners and prog\n        indicators. To start the prog, pass ``msg`` argument as a start\n        message. For example::\n\n            printer = Console(verbose=True)\n            with printer.progress('Checking files') as prog:\n                # Do some checks\n                if errors:\n                    prog.abrt()\n                prog.end()\n\n        The context manager returns a ``Progress`` instance, which provides\n        methods like ``abrt()`` (abort), ``end()`` (end), and ``prog()`` (print\n        prog indicator).\n\n        The prog methods like ``abrt()`` and ``end()`` will raise an\n        exception that interrupts the prog. These exceptions are\n        ``ProgressEnd`` exception subclasses and are ``ProgressAbrt`` and\n        ``ProgressOK`` respectively. They are silenced and not handled in any\n        way as they only serve the purpose of flow control.\n\n        Other exceptions are trapped and ``abrt()`` is called. The exceptions\n        that should be trapped can be customized using the ``excs`` argument,\n        which should be a tuple of exception classes.\n\n        If a handler function is passed using ``onerror`` argument, then this\n        function takes the raised exception and handles it. By default, the\n        ``error()`` factory is called with no arguments to generate the default\n        error handler. If string is passed, then ``error()`` factory is called\n        with that string.\n\n        Finally, when prog is aborted either naturally or when exception is\n        raised, it is possible to reraise the ``ProgressAbrt`` exception. This\n        is done using the ``reraise`` flag. Default is to reraise."
  },
  {
    "code": "def _decode_ctrl_packet(self, version, packet):\n        for i in range(5):\n            input_bit = packet[i]\n            self._debug(PROP_LOGLEVEL_DEBUG, \"Byte \" + str(i) + \": \" + str((input_bit >> 7) & 1) + str((input_bit >> 6) & 1) + str((input_bit >> 5) & 1) + str((input_bit >> 4) & 1) + str((input_bit >> 3) & 1) + str((input_bit >> 2) & 1) + str((input_bit >> 1) & 1) + str(input_bit & 1))\n        for sensor in self._ctrl_sensor:\n            if (sensor.sensor_type == PROP_SENSOR_FLAG):\n                sensor.value = (packet[sensor.index // 8] >> (sensor.index % 8)) & 1\n            elif (sensor.sensor_type == PROP_SENSOR_RAW):\n                sensor.value = packet",
    "docstring": "Decode a control packet into the list of sensors."
  },
  {
    "code": "def dump_misspelling_list(self):\n    results = []\n    for bad_word in sorted(self._misspelling_dict.keys()):\n      for correction in self._misspelling_dict[bad_word]:\n        results.append([bad_word, correction])\n    return results",
    "docstring": "Returns a list of misspelled words and corrections."
  },
  {
    "code": "def bwar_pitch(return_all=False):\n    url = \"http://www.baseball-reference.com/data/war_daily_pitch.txt\"\n    s = requests.get(url).content\n    c=pd.read_csv(io.StringIO(s.decode('utf-8')))\n    if return_all:\n        return c\n    else:\n        cols_to_keep = ['name_common', 'mlb_ID', 'player_ID', 'year_ID', 'team_ID', 'stint_ID', 'lg_ID',\n                        'G', 'GS', 'RA','xRA', 'BIP', 'BIP_perc','salary', 'ERA_plus', 'WAR_rep', 'WAA',\n                        'WAA_adj','WAR']\n        return c[cols_to_keep]",
    "docstring": "Get data from war_daily_pitch table. Returns WAR, its components, and a few other useful stats. \n    To get all fields from this table, supply argument return_all=True."
  },
  {
    "code": "def to_hierarchical(self, n_repeat, n_shuffle=1):\n        levels = self.levels\n        codes = [np.repeat(level_codes, n_repeat) for\n                 level_codes in self.codes]\n        codes = [x.reshape(n_shuffle, -1).ravel(order='F') for x in codes]\n        names = self.names\n        warnings.warn(\"Method .to_hierarchical is deprecated and will \"\n                      \"be removed in a future version\",\n                      FutureWarning, stacklevel=2)\n        return MultiIndex(levels=levels, codes=codes, names=names)",
    "docstring": "Return a MultiIndex reshaped to conform to the\n        shapes given by n_repeat and n_shuffle.\n\n        .. deprecated:: 0.24.0\n\n        Useful to replicate and rearrange a MultiIndex for combination\n        with another Index with n_repeat items.\n\n        Parameters\n        ----------\n        n_repeat : int\n            Number of times to repeat the labels on self\n        n_shuffle : int\n            Controls the reordering of the labels. If the result is going\n            to be an inner level in a MultiIndex, n_shuffle will need to be\n            greater than one. The size of each label must divisible by\n            n_shuffle.\n\n        Returns\n        -------\n        MultiIndex\n\n        Examples\n        --------\n        >>> idx = pd.MultiIndex.from_tuples([(1, 'one'), (1, 'two'),\n                                            (2, 'one'), (2, 'two')])\n        >>> idx.to_hierarchical(3)\n        MultiIndex(levels=[[1, 2], ['one', 'two']],\n                   codes=[[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1],\n                          [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1]])"
  },
  {
    "code": "def polynomial(A, x, b, coefficients, iterations=1):\n    A, x, b = make_system(A, x, b, formats=None)\n    for i in range(iterations):\n        from pyamg.util.linalg import norm\n        if norm(x) == 0:\n            residual = b\n        else:\n            residual = (b - A*x)\n        h = coefficients[0]*residual\n        for c in coefficients[1:]:\n            h = c*residual + A*h\n        x += h",
    "docstring": "Apply a polynomial smoother to the system Ax=b.\n\n    Parameters\n    ----------\n    A : sparse matrix\n        Sparse NxN matrix\n    x : ndarray\n        Approximate solution (length N)\n    b : ndarray\n        Right-hand side (length N)\n    coefficients : array_like\n        Coefficients of the polynomial.  See Notes section for details.\n    iterations : int\n        Number of iterations to perform\n\n    Returns\n    -------\n    Nothing, x will be modified in place.\n\n    Notes\n    -----\n    The smoother has the form  x[:] = x + p(A) (b - A*x) where p(A) is a\n    polynomial in A whose scalar coefficients are specified (in descending\n    order) by argument 'coefficients'.\n\n    - Richardson iteration p(A) = c_0:\n        polynomial_smoother(A, x, b, [c_0])\n\n    - Linear smoother p(A) = c_1*A + c_0:\n        polynomial_smoother(A, x, b, [c_1, c_0])\n\n    - Quadratic smoother p(A) = c_2*A^2 + c_1*A + c_0:\n        polynomial_smoother(A, x, b, [c_2, c_1, c_0])\n\n    Here, Horner's Rule is applied to avoid computing A^k directly.\n\n    For efficience, the method detects the case x = 0 one matrix-vector\n    product is avoided (since (b - A*x) is b).\n\n    Examples\n    --------\n    >>> # The polynomial smoother is not currently used directly\n    >>> # in PyAMG.  It is only used by the chebyshev smoothing option,\n    >>> # which automatically calculates the correct coefficients.\n    >>> from pyamg.gallery import poisson\n    >>> from pyamg.util.linalg import norm\n    >>> import numpy as np\n    >>> from pyamg.aggregation import smoothed_aggregation_solver\n    >>> A = poisson((10,10), format='csr')\n    >>> b = np.ones((A.shape[0],1))\n    >>> sa = smoothed_aggregation_solver(A, B=np.ones((A.shape[0],1)),\n    ...         coarse_solver='pinv2', max_coarse=50,\n    ...         presmoother=('chebyshev', {'degree':3, 'iterations':1}),\n    ...         postsmoother=('chebyshev', {'degree':3, 'iterations':1}))\n    >>> x0=np.zeros((A.shape[0],1))\n    >>> residuals=[]\n    >>> x = sa.solve(b, x0=x0, tol=1e-8, residuals=residuals)"
  },
  {
    "code": "def merge_with(self, other):\n        other = as_shape(other)\n        if self._dims is None:\n            return other\n        else:\n            try:\n                self.assert_same_rank(other)\n                new_dims = []\n                for i, dim in enumerate(self._dims):\n                    new_dims.append(dim.merge_with(other[i]))\n                return TensorShape(new_dims)\n            except ValueError:\n                raise ValueError(\"Shapes %s and %s are not convertible\" % (self, other))",
    "docstring": "Returns a `TensorShape` combining the information in `self` and `other`.\n\n        The dimensions in `self` and `other` are merged elementwise,\n        according to the rules defined for `Dimension.merge_with()`.\n\n        Args:\n          other: Another `TensorShape`.\n\n        Returns:\n          A `TensorShape` containing the combined information of `self` and\n          `other`.\n\n        Raises:\n          ValueError: If `self` and `other` are not convertible."
  },
  {
    "code": "def add_cookies_to_web_driver(driver, cookies):\n    for cookie in cookies:\n        driver.add_cookie(convert_cookie_to_dict(cookie))\n    return driver",
    "docstring": "Sets cookies in an existing WebDriver session."
  },
  {
    "code": "def overlay_config(base, overlay):\n    if not isinstance(base, collections.Mapping):\n        return overlay\n    if not isinstance(overlay, collections.Mapping):\n        return overlay\n    result = dict()\n    for k in iterkeys(base):\n        if k not in overlay:\n            result[k] = base[k]\n    for k, v in iteritems(overlay):\n        if v is not None or (k in base and base[k] is None):\n            if k in base:\n                v = overlay_config(base[k], v)\n            result[k] = v\n    return result",
    "docstring": "Overlay one configuration over another.\n\n    This overlays `overlay` on top of `base` as follows:\n\n    * If either isn't a dictionary, returns `overlay`.\n    * Any key in `base` not present in `overlay` is present in the\n      result with its original value.\n    * Any key in `overlay` with value :const:`None` is not present in\n      the result, unless it also is :const:`None` in `base`.\n    * Any key in `overlay` not present in `base` and not :const:`None`\n      is present in the result with its new value.\n    * Any key in both `overlay` and `base` with a non-:const:`None` value\n      is recursively overlaid.\n\n    >>> overlay_config({'a': 'b'}, {'a': 'c'})\n    {'a': 'c'}\n    >>> overlay_config({'a': 'b'}, {'c': 'd'})\n    {'a': 'b', 'c': 'd'}\n    >>> overlay_config({'a': {'b': 'c'}},\n    ...                {'a': {'b': 'd', 'e': 'f'}})\n    {'a': {'b': 'd', 'e': 'f'}}\n    >>> overlay_config({'a': 'b', 'c': 'd'}, {'a': None})\n    {'c': 'd'}\n\n    :param dict base: original configuration\n    :param dict overlay: overlay configuration\n    :return: new overlaid configuration\n    :returntype dict:"
  },
  {
    "code": "def fixed_timezone(offset):\n    if offset in _tz_cache:\n        return _tz_cache[offset]\n    tz = _FixedTimezone(offset)\n    _tz_cache[offset] = tz\n    return tz",
    "docstring": "Return a Timezone instance given its offset in seconds."
  },
  {
    "code": "def outer_horizontal_border_bottom(self):\n        return u\"{lm}{lv}{hz}{rv}\".format(lm=' ' * self.margins.left,\n                                          lv=self.border_style.bottom_left_corner,\n                                          rv=self.border_style.bottom_right_corner,\n                                          hz=self.outer_horizontals())",
    "docstring": "The complete outer bottom horizontal border section, including left and right margins.\n\n        Returns:\n            str: The bottom menu border."
  },
  {
    "code": "def fetch_deposits_since(self, since: int) -> List[Deposit]:\n        return self._transactions_since(self._deposits_since, 'deposits', since)",
    "docstring": "Fetch all deposits since the given timestamp."
  },
  {
    "code": "def read_line(self):\n        try:\n            line = self.inp.readline().strip()\n        except KeyboardInterrupt:\n            raise EOFError()\n        if not line:\n            raise EOFError()\n        return line",
    "docstring": "Interrupted respecting reader for stdin.\n\n        Raises EOFError if the end of stream has been reached"
  },
  {
    "code": "def flags(self):\n        return set((name.lower() for name in sorted(TIFF.FILE_FLAGS)\n                    if getattr(self, 'is_' + name)))",
    "docstring": "Return set of flags."
  },
  {
    "code": "def system_exit(object):\n    @functools.wraps(object)\n    def system_exit_wrapper(*args, **kwargs):\n        try:\n            if object(*args, **kwargs):\n                foundations.core.exit(0)\n        except Exception as error:\n            sys.stderr.write(\"\\n\".join(foundations.exceptions.format_exception(*sys.exc_info())))\n            foundations.core.exit(1)\n    return system_exit_wrapper",
    "docstring": "Handles proper system exit in case of critical exception.\n\n    :param object: Object to decorate.\n    :type object: object\n    :return: Object.\n    :rtype: object"
  },
  {
    "code": "def srcname(self):\n        if self.rpm_name or self.name.startswith(('python-', 'Python-')):\n            return self.name_convertor.base_name(self.rpm_name or self.name)",
    "docstring": "Return srcname for the macro if the pypi name should be changed.\n\n        Those cases are:\n        - name was provided with -r option\n        - pypi name is like python-<name>"
  },
  {
    "code": "def responses_of(self, request):\n        responses = [response for index, response in self._responses(request)]\n        if responses:\n            return responses\n        raise UnhandledHTTPRequestError(\n            \"The cassette (%r) doesn't contain the request (%r) asked for\"\n            % (self._path, request)\n        )",
    "docstring": "Find the responses corresponding to a request.\n        This function isn't actually used by VCR internally, but is\n        provided as an external API."
  },
  {
    "code": "def purge_portlets(portal):\n    logger.info(\"Purging portlets ...\")\n    def remove_portlets(context_portlet):\n        mapping = portal.restrictedTraverse(context_portlet)\n        for key in mapping.keys():\n            if key not in PORTLETS_TO_PURGE:\n                logger.info(\"Skipping portlet: '{}'\".format(key))\n                continue\n            logger.info(\"Removing portlet: '{}'\".format(key))\n            del mapping[key]\n    remove_portlets(\"++contextportlets++plone.leftcolumn\")\n    remove_portlets(\"++contextportlets++plone.rightcolumn\")\n    setup = portal.portal_setup\n    setup.runImportStepFromProfile(profile, 'portlets')\n    logger.info(\"Purging portlets [DONE]\")",
    "docstring": "Remove old portlets. Leave the Navigation portlet only"
  },
  {
    "code": "def token_address(self) -> Address:\n        return to_canonical_address(self.proxy.contract.functions.token().call())",
    "docstring": "Return the token of this manager."
  },
  {
    "code": "def decrypt(self, data, decode=False):\n\t\tresult = self.cipher().decrypt_block(data)\n\t\tpadding = self.mode().padding()\n\t\tif padding is not None:\n\t\t\tresult = padding.reverse_pad(result, WAESMode.__data_padding_length__)\n\t\treturn result.decode() if decode else result",
    "docstring": "Decrypt the given data with cipher that is got from AES.cipher call.\n\n\t\t:param data: data to decrypt\n\t\t:param decode: whether to decode bytes to str or not\n\t\t:return: bytes or str (depends on decode flag)"
  },
  {
    "code": "def write(self, target, *args, **kwargs):\n        return io_registry.write(self, target, *args, **kwargs)",
    "docstring": "Write this `SegmentList` to a file\n\n        Arguments and keywords depend on the output format, see the\n        online documentation for full details for each format.\n\n        Parameters\n        ----------\n        target : `str`\n            output filename\n\n        Notes\n        -----"
  },
  {
    "code": "def generate_sphinx_all():\n        all_nicknames = []\n        def add_nickname(gtype, a, b):\n            nickname = nickname_find(gtype)\n            try:\n                Operation.generate_sphinx(nickname)\n                all_nicknames.append(nickname)\n            except Error:\n                pass\n            type_map(gtype, add_nickname)\n            return ffi.NULL\n        type_map(type_from_name('VipsOperation'), add_nickname)\n        all_nicknames.sort()\n        exclude = ['scale', 'ifthenelse', 'bandjoin', 'bandrank']\n        all_nicknames = [x for x in all_nicknames if x not in exclude]\n        print('.. class:: pyvips.Image\\n')\n        print('   .. rubric:: Methods\\n')\n        print('   .. autosummary::')\n        print('      :nosignatures:\\n')\n        for nickname in all_nicknames:\n            print('      ~{0}'.format(nickname))\n        print()\n        print()\n        for nickname in all_nicknames:\n            docstr = Operation.generate_sphinx(nickname)\n            docstr = docstr.replace('\\n', '\\n      ')\n            print('   ' + docstr)",
    "docstring": "Generate sphinx documentation.\n\n        This generates a .rst file for all auto-generated image methods. Use it\n        to regenerate the docs with something like::\n\n            $ python -c \\\n\"import pyvips; pyvips.Operation.generate_sphinx_all()\" > x\n\n        And copy-paste the file contents into doc/vimage.rst in the appropriate\n        place."
  },
  {
    "code": "def validate_overlap(comp1, comp2, force):\n    warnings = dict()\n    if force is None:\n        stat = comp2.check_overlap(comp1)\n        if stat=='full':\n            pass\n        elif stat == 'partial':\n            raise(exceptions.PartialOverlap('Spectrum and bandpass do not fully overlap. You may use force=[extrap|taper] to force this Observation anyway.'))\n        elif stat == 'none':\n            raise(exceptions.DisjointError('Spectrum and bandpass are disjoint'))\n    elif force.lower() == 'taper':\n        try:\n            comp1=comp1.taper()\n        except AttributeError:\n            comp1=comp1.tabulate().taper()\n            warnings['PartialOverlap']=force\n    elif force.lower().startswith('extrap'):\n        stat=comp2.check_overlap(comp1)\n        if stat == 'partial':\n            warnings['PartialOverlap']=force\n    else:\n        raise(KeyError(\"Illegal value force=%s; legal values=('taper','extrap')\"%force))\n    return comp1, comp2, warnings",
    "docstring": "Validate the overlap between the wavelength sets\n    of the two given components.\n\n    Parameters\n    ----------\n    comp1, comp2 : `~pysynphot.spectrum.SourceSpectrum` or `~pysynphot.spectrum.SpectralElement`\n        Source spectrum and bandpass of an observation.\n\n    force : {'extrap', 'taper', `None`}\n        If not `None`, the components may be adjusted by\n        extrapolation or tapering.\n\n    Returns\n    -------\n    comp1, comp2\n        Same as inputs. However, ``comp1`` might be tapered\n        if that option is selected.\n\n    warnings : dict\n        Maps warning keyword to its description.\n\n    Raises\n    ------\n    KeyError\n        Invalid ``force``.\n\n    pysynphot.exceptions.DisjointError\n        No overlap detected when ``force`` is `None`.\n\n    pysynphot.exceptions.PartialOverlap\n        Partial overlap detected when ``force`` is `None`."
  },
  {
    "code": "def smart_query_string(parser, token):\n    args = token.split_contents()\n    additions = args[1:]\n    addition_pairs = []\n    while additions:\n        addition_pairs.append(additions[0:2])\n        additions = additions[2:]\n    return SmartQueryStringNode(addition_pairs)",
    "docstring": "Outputs current GET query string with additions appended.\n    Additions are provided in token pairs."
  },
  {
    "code": "def trace_dependencies(req, requirement_set, dependencies, _visited=None):\r\n    _visited = _visited or set()\r\n    if req in _visited:\r\n        return\r\n    _visited.add(req)\r\n    for reqName in req.requirements():\r\n        try:\r\n            name = pkg_resources.Requirement.parse(reqName).project_name\r\n        except ValueError, e:\r\n            logger.error('Invalid requirement: %r (%s) in requirement %s' % (\r\n                reqName, e, req))\r\n            continue\r\n        subreq = requirement_set.get_requirement(name)\r\n        dependencies.append((req, subreq))\r\n        trace_dependencies(subreq, requirement_set, dependencies, _visited)",
    "docstring": "Trace all dependency relationship\r\n    \r\n    @param req: requirements to trace\r\n    @param requirement_set: RequirementSet\r\n    @param dependencies: list for storing dependencies relationships\r\n    @param _visited: visited requirement set"
  },
  {
    "code": "def pipeline_counter(self):\n        if 'pipeline_counter' in self.data:\n            return self.data.get('pipeline_counter')\n        elif self.pipeline is not None:\n            return self.pipeline.data.counter",
    "docstring": "Get pipeline counter of current stage instance.\n\n        Because instantiating stage instance could be performed in different ways and those return different results,\n        we have to check where from to get counter of the pipeline.\n\n        :return: pipeline counter."
  },
  {
    "code": "def ConnectionUpdate(self, settings):\n    connection_path = self.connection_path\n    NM = dbusmock.get_object(MANAGER_OBJ)\n    settings_obj = dbusmock.get_object(SETTINGS_OBJ)\n    main_connections = settings_obj.ListConnections()\n    if connection_path not in main_connections:\n        raise dbus.exceptions.DBusException(\n            'Connection %s does not exist' % connection_path,\n            name=MANAGER_IFACE + '.DoesNotExist',)\n    for setting_name in settings:\n        setting = settings[setting_name]\n        for k in setting:\n            if setting_name not in self.settings:\n                self.settings[setting_name] = {}\n            self.settings[setting_name][k] = setting[k]\n    self.EmitSignal(CSETTINGS_IFACE, 'Updated', '', [])\n    auto_connect = False\n    if 'autoconnect' in settings['connection']:\n        auto_connect = settings['connection']['autoconnect']\n    if auto_connect:\n        dev = None\n        devices = NM.GetDevices()\n        if len(devices) > 0:\n            dev = devices[0]\n        if dev:\n            activate_connection(NM, connection_path, dev, connection_path)\n    return connection_path",
    "docstring": "Update settings on a connection.\n\n    settings is a String String Variant Map Map. See\n    https://developer.gnome.org/NetworkManager/0.9/spec.html\n        #type-String_String_Variant_Map_Map"
  },
  {
    "code": "def eval_ast(self, ast):\n        new_ast = ast.replace_dict(self.replacements, leaf_operation=self._leaf_op)\n        return backends.concrete.eval(new_ast, 1)[0]",
    "docstring": "Eval the ast, replacing symbols by their last value in the model."
  },
  {
    "code": "def _create_sample_list(in_bams, vcf_file):\n    out_file = \"%s-sample_list.txt\" % os.path.splitext(vcf_file)[0]\n    with open(out_file, \"w\") as out_handle:\n        for in_bam in in_bams:\n            with pysam.Samfile(in_bam, \"rb\") as work_bam:\n                for rg in work_bam.header.get(\"RG\", []):\n                    out_handle.write(\"%s\\n\" % rg[\"SM\"])\n    return out_file",
    "docstring": "Pull sample names from input BAMs and create input sample list."
  },
  {
    "code": "def foreign(self, value, context=None):\n\t\tif self.separator is None:\n\t\t\tseparator = ' '\n\t\telse:\n\t\t\tseparator = self.separator.strip() if self.strip and hasattr(self.separator, 'strip') else self.separator\n\t\tvalue = self._clean(value)\n\t\ttry:\n\t\t\tvalue = separator.join(value)\n\t\texcept Exception as e:\n\t\t\traise Concern(\"{0} caught, failed to convert to string: {1}\", e.__class__.__name__, str(e))\n\t\treturn super().foreign(value)",
    "docstring": "Construct a string-like representation for an iterable of string-like objects."
  },
  {
    "code": "def setup_logging(verbosity, filename=None):\n    levels = [logging.WARNING, logging.INFO, logging.DEBUG]\n    level = levels[min(verbosity, len(levels) - 1)]\n    logging.root.setLevel(level)\n    fmt = logging.Formatter('%(asctime)s %(levelname)-12s %(message)-100s '\n                            '[%(filename)s:%(lineno)d]')\n    hdlr = logging.StreamHandler()\n    hdlr.setFormatter(fmt)\n    logging.root.addHandler(hdlr)\n    if filename:\n        hdlr = logging.FileHandler(filename, 'a')\n        hdlr.setFormatter(fmt)\n        logging.root.addHandler(hdlr)",
    "docstring": "Configure logging for this tool."
  },
  {
    "code": "def p(name=\"\", **kwargs):\n    with Reflect.context(**kwargs) as r:\n        if name:\n            instance = P_CLASS(r, stream, name, **kwargs)\n        else:\n            instance = P_CLASS.pop(r)\n            instance()\n    return instance",
    "docstring": "really quick and dirty profiling\n\n    you start a profile by passing in name, you stop the top profiling by not\n    passing in a name. You can also call this method using a with statement\n\n    This is for when you just want to get a really back of envelope view of\n    how your fast your code is, super handy, not super accurate\n\n    since -- 2013-5-9\n    example --\n        p(\"starting profile\")\n        time.sleep(1)\n        p() # stop the \"starting profile\" session\n\n        # you can go N levels deep\n        p(\"one\")\n        p(\"two\")\n        time.sleep(0.5)\n        p() # stop profiling of \"two\"\n        time.sleep(0.5)\n        p() # stop profiling of \"one\"\n\n        with pout.p(\"three\"):\n            time.sleep(0.5)\n\n    name -- string -- pass this in to start a profiling session\n    return -- context manager"
  },
  {
    "code": "def _nonmatch_class_pos(self):\n        if self.kernel.classes_.shape[0] != 2:\n            raise ValueError(\"Number of classes is {}, expected 2.\".format(\n                self.kernel.classes_.shape[0]))\n        return 0",
    "docstring": "Return the position of the non-match class."
  },
  {
    "code": "def run_transaction(self, command_list, do_commit=True):\n        pass\n        for c in command_list:\n            if c.find(\";\") != -1 or c.find(\"\\\\G\") != -1:\n                raise Exception(\"The SQL command '%s' contains a semi-colon or \\\\G. This is a potential SQL injection.\" % c)\n        if do_commit:\n            sql = \"START TRANSACTION;\\n%s;\\nCOMMIT\" % \"\\n\".join(command_list)\n        else:\n            sql = \"START TRANSACTION;\\n%s;\" % \"\\n\".join(command_list)\n        return",
    "docstring": "This can be used to stage multiple commands and roll back the transaction if an error occurs. This is useful\n            if you want to remove multiple records in multiple tables for one entity but do not want the deletion to occur\n            if the entity is tied to table not specified in the list of commands. Performing this as a transaction avoids\n            the situation where the records are partially removed. If do_commit is false, the entire transaction is cancelled."
  },
  {
    "code": "def SetupPrometheusEndpointOnPortRange(port_range, addr=''):\n    assert os.environ.get('RUN_MAIN') != 'true', (\n        'The thread-based exporter can\\'t be safely used when django\\'s '\n        'autoreloader is active. Use the URL exporter, or start django '\n        'with --noreload. See documentation/exports.md.')\n    for port in port_range:\n        try:\n            httpd = HTTPServer((addr, port), prometheus_client.MetricsHandler)\n        except (OSError, socket.error):\n            continue\n        thread = PrometheusEndpointServer(httpd)\n        thread.daemon = True\n        thread.start()\n        logger.info('Exporting Prometheus /metrics/ on port %s' % port)\n        return",
    "docstring": "Like SetupPrometheusEndpointOnPort, but tries several ports.\n\n    This is useful when you're running Django as a WSGI application\n    with multiple processes and you want Prometheus to discover all\n    workers. Each worker will grab a port and you can use Prometheus\n    to aggregate across workers.\n\n    port_range may be any iterable object that contains a list of\n    ports. Typically this would be an xrange of contiguous ports.\n\n    As soon as one port is found that can serve, use this one and stop\n    trying.\n\n    The same caveats regarding autoreload apply. Do not use this when\n    Django's autoreloader is active."
  },
  {
    "code": "def _magickfy_topics(topics):\n        if topics is None:\n            return None\n        if isinstance(topics, six.string_types):\n            topics = [topics, ]\n        ts_ = []\n        for t__ in topics:\n            if not t__.startswith(_MAGICK):\n                if t__ and t__[0] == '/':\n                    t__ = _MAGICK + t__\n                else:\n                    t__ = _MAGICK + '/' + t__\n            ts_.append(t__)\n        return ts_",
    "docstring": "Add the magick to the topics if missing."
  },
  {
    "code": "def validate(cls, data, name, **kwargs):\n        required = kwargs.get('required', False)\n        if required and data is None:\n            raise ValidationError(\"required\", name, True)\n        elif data is None:\n            return\n        elif kwargs.get('readonly'):\n            return\n        try:\n            for key, value in kwargs.items():\n                validator = cls.validation.get(key, lambda x, y: False)\n                if validator(data, value):\n                    raise ValidationError(key, name, value)\n        except TypeError:\n            raise ValidationError(\"unknown\", name, \"unknown\")\n        else:\n            return data",
    "docstring": "Validate that a piece of data meets certain conditions"
  },
  {
    "code": "def shuffle(self):\n        args = list(self)\n        random.shuffle(args)\n        self.clear()\n        super(DogeDeque, self).__init__(args)",
    "docstring": "Shuffle the deque\n\n        Deques themselves do not support this, so this will make all items into\n        a list, shuffle that list, clear the deque, and then re-init the deque."
  },
  {
    "code": "def unimapping(arg, level):\n    if not isinstance(arg, collections.Mapping):\n        raise TypeError(\n            'expected collections.Mapping, {} received'.format(type(arg).__name__)\n        )\n    result = []\n    for i in arg.items():\n        result.append(\n            pretty_spaces(level) + u': '.join(map(functools.partial(convert, level=level), i))\n        )\n    string = join_strings(result, level)\n    if level is not None:\n        string += pretty_spaces(level - 1)\n    return u'{{{}}}'.format(string)",
    "docstring": "Mapping object to unicode string.\n\n    :type arg: collections.Mapping\n    :param arg: mapping object\n    :type level: int\n    :param level: deep level\n\n    :rtype: unicode\n    :return: mapping object as unicode string"
  },
  {
    "code": "def metrics_api(self):\n        if self._metrics_api is None:\n            if self._use_grpc:\n                self._metrics_api = _gapic.make_metrics_api(self)\n            else:\n                self._metrics_api = JSONMetricsAPI(self)\n        return self._metrics_api",
    "docstring": "Helper for log metric-related API calls.\n\n        See\n        https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics"
  },
  {
    "code": "def add_request_ids_from_environment(logger, name, event_dict):\n    if ENV_APIG_REQUEST_ID in os.environ:\n        event_dict['api_request_id'] = os.environ[ENV_APIG_REQUEST_ID]\n    if ENV_LAMBDA_REQUEST_ID in os.environ:\n        event_dict['lambda_request_id'] = os.environ[ENV_LAMBDA_REQUEST_ID]\n    return event_dict",
    "docstring": "Custom processor adding request IDs to the log event, if available."
  },
  {
    "code": "def parse(source):\n    if isinstance(source, str):\n        return parse_stream(six.StringIO(source))\n    else:\n        return parse_stream(source)",
    "docstring": "Parses source code returns an array of instructions suitable for\n    optimization and execution by a Machine.\n\n    Args:\n        source: A string or stream containing source code."
  },
  {
    "code": "def get_view(self):\n        d = self.declaration\n        if d.cached and self.widget:\n            return self.widget\n        if d.defer_loading:\n             self.widget = FrameLayout(self.get_context())\n             app = self.get_context()\n             app.deferred_call(\n                 lambda: self.widget.addView(self.load_view(), 0))\n        else:\n            self.widget = self.load_view()\n        return self.widget",
    "docstring": "Get the page to display. If a view has already been created and\n        is cached, use that otherwise initialize the view and proxy. If defer\n        loading is used, wrap the view in a FrameLayout and defer add view \n        until later."
  },
  {
    "code": "def _save(self, stateName, path):\r\n        print('saving...')\r\n        state = {'session': dict(self.opts),\r\n                 'dialogs': self.dialogs.saveState()}\r\n        self.sigSave.emit(state)\r\n        self.saveThread.prepare(stateName, path, self.tmp_dir_session, state)\r\n        self.saveThread.start()\r\n        self.current_session = stateName\r\n        r = self.opts['recent sessions']\r\n        try:\r\n            r.pop(r.index(path))\r\n        except ValueError:\r\n            pass\r\n        r.insert(0, path)",
    "docstring": "save into 'stateName' to pyz-path"
  },
  {
    "code": "def create_admin(cls, email, password, **kwargs):\n        data = {\n            'email': email,\n            'password': cls.hash_password(password),\n            'has_agreed_to_terms': True,\n            'state': State.approved,\n            'role': cls.roles.administrator.value,\n            'organisations': {}\n        }\n        data.update(**kwargs)\n        user = cls(**data)\n        yield user._save()\n        raise Return(user)",
    "docstring": "Create an approved 'global' administrator\n\n        :param email: the user's email address\n        :param password: the user's plain text password\n        :returns: a User"
  },
  {
    "code": "def jwt_proccessor():\n    def jwt():\n        token = current_accounts.jwt_creation_factory()\n        return Markup(\n            render_template(\n                current_app.config['ACCOUNTS_JWT_DOM_TOKEN_TEMPLATE'],\n                token=token\n            )\n        )\n    def jwt_token():\n        return current_accounts.jwt_creation_factory()\n    return {\n        'jwt': jwt,\n        'jwt_token': jwt_token,\n    }",
    "docstring": "Context processor for jwt."
  },
  {
    "code": "def exists(self):\n        result = TimeSeries(default=False if self.default is None else True)\n        for t, v in self:\n            result[t] = False if v is None else True\n        return result",
    "docstring": "returns False when the timeseries has a None value,\n        True otherwise"
  },
  {
    "code": "def save(self, **kwargs):\n        translated_data = self._pop_translated_data()\n        instance = super(TranslatableModelSerializer, self).save(**kwargs)\n        self.save_translations(instance, translated_data)\n        return instance",
    "docstring": "Extract the translations and save them after main object save.\n\n        By default all translations will be saved no matter if creating\n        or updating an object. Users with more complex needs might define\n        their own save and handle translation saving themselves."
  },
  {
    "code": "def _create_broker(self, broker_id, metadata=None):\n        broker = Broker(broker_id, metadata)\n        if not metadata:\n            broker.mark_inactive()\n        rg_id = self.extract_group(broker)\n        group = self.rgs.setdefault(rg_id, ReplicationGroup(rg_id))\n        group.add_broker(broker)\n        broker.replication_group = group\n        return broker",
    "docstring": "Create a broker object and assign to a replication group.\n        A broker object with no metadata is considered inactive.\n        An inactive broker may or may not belong to a group."
  },
  {
    "code": "def bind_collection_to_model_cls(cls):\n        cls.Collection = type('{0}.Collection'.format(cls.__name__),\n                              (cls.Collection,),\n                              {'value_type': cls})\n        cls.Collection.__module__ = cls.__module__",
    "docstring": "Bind collection to model's class.\n\n        If collection was not specialized in process of model's declaration,\n        subclass of collection will be created."
  },
  {
    "code": "def get_logout_uri(self, id_token_hint=None, post_logout_redirect_uri=None,\n                       state=None, session_state=None):\n        params = {\"oxd_id\": self.oxd_id}\n        if id_token_hint:\n            params[\"id_token_hint\"] = id_token_hint\n        if post_logout_redirect_uri:\n            params[\"post_logout_redirect_uri\"] = post_logout_redirect_uri\n        if state:\n            params[\"state\"] = state\n        if session_state:\n            params[\"session_state\"] = session_state\n        logger.debug(\"Sending command `get_logout_uri` with params %s\", params)\n        response = self.msgr.request(\"get_logout_uri\", **params)\n        logger.debug(\"Received response: %s\", response)\n        if response['status'] == 'error':\n            raise OxdServerError(response['data'])\n        return response['data']['uri']",
    "docstring": "Function to logout the user.\n\n        Parameters:\n            * **id_token_hint (string, optional):** oxd server will use last used ID Token, if not provided\n            * **post_logout_redirect_uri (string, optional):** URI to redirect, this uri would override the value given in the site-config\n            * **state (string, optional):** site state\n            * **session_state (string, optional):** session state\n\n        Returns:\n            **string:** The URI to which the user must be directed in order to\n            perform the logout"
  },
  {
    "code": "def get_model_names(app_label, models):\n    return dict(\n        (model, get_model_name(app_label, model))\n        for model in models\n    )",
    "docstring": "Map model names to their swapped equivalents for the given app"
  },
  {
    "code": "def insertDict(self, tblname, d, fields = None):\n\t\tif fields == None:\n\t\t\tfields = sorted(d.keys())\n\t\tvalues = None\n\t\ttry:\n\t\t\tSQL = 'INSERT INTO %s (%s) VALUES (%s)' % (tblname, join(fields, \", \"), join(['%s' for x in range(len(fields))], ','))\n\t\t\tvalues = tuple([d[k] for k in fields])\n\t \t\tself.locked_execute(SQL, parameters = values)\n\t\texcept Exception, e:\n\t\t\tif SQL and values:\n\t\t\t\tsys.stderr.write(\"\\nSQL execution error in query '%s' %% %s at %s:\" % (SQL, values, datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")))\n\t\t\tsys.stderr.write(\"\\nError: '%s'.\\n\" % (str(e)))\n\t\t\tsys.stderr.flush()\n\t\t\traise Exception(\"Error occurred during database insertion: '%s'.\" % str(e))",
    "docstring": "Simple function for inserting a dictionary whose keys match the fieldnames of tblname."
  },
  {
    "code": "def resources(self,\n                  start=1,\n                  num=10):\n        url = self._url + \"/resources\"\n        params = {\n            \"f\" : \"json\",\n            \"start\" : start,\n            \"num\" : num\n        }\n        return self._get(url=url,\n                            param_dict=params,\n                            securityHandler=self._securityHandler,\n                            proxy_url=self._proxy_url,\n                            proxy_port=self._proxy_port)",
    "docstring": "Resources lists all file resources for the organization. The start\n        and num paging parameters are supported.\n\n        Inputs:\n           start - the number of the first entry in the result set response\n                   The index number is 1-based and the default is 1\n           num - the maximum number of results to be returned as a whole #"
  },
  {
    "code": "def _get_chemical_equation_piece(species_list, coefficients):\n    def _get_token(species, coefficient):\n        if coefficient == 1:\n            return '{}'.format(species)\n        else:\n            return '{:g} {}'.format(coefficient, species)\n    bag = []\n    for species, coefficient in zip(species_list, coefficients):\n        if coefficient < 0:\n            coefficient = -coefficient\n        if coefficient > 0:\n            bag.append(_get_token(species, coefficient))\n    return '{}'.format(' + '.join(bag))",
    "docstring": "Produce a string from chemical species and their coefficients.\n\n    Parameters\n    ----------\n    species_list : iterable of `str`\n        Iterable of chemical species.\n    coefficients : iterable of `float`\n        Nonzero stoichiometric coefficients. The length of `species_list` and\n        `coefficients` must be the same. Negative values are made positive and\n        zeros are ignored along with their respective species.\n\n    Examples\n    --------\n    >>> from pyrrole.core import _get_chemical_equation_piece\n    >>> _get_chemical_equation_piece([\"AcOH\"], [2])\n    '2 AcOH'\n    >>> _get_chemical_equation_piece([\"AcO-\", \"H+\"], [-1, -1])\n    'AcO- + H+'\n    >>> _get_chemical_equation_piece(\"ABCD\", [-2, -1, 0, -1])\n    '2 A + B + D'"
  },
  {
    "code": "def _put(self, uri, data):\n        headers = self._get_headers()\n        logging.debug(\"URI=\" + str(uri))\n        logging.debug(\"BODY=\" + json.dumps(data))\n        response = self.session.put(uri, headers=headers,\n                data=json.dumps(data))\n        if response.status_code in [201, 204]:\n            return data\n        else:\n            logging.error(response.content)\n            response.raise_for_status()",
    "docstring": "Simple PUT operation for a given path."
  },
  {
    "code": "def command_create_tables(self, meta_name=None, verbose=False):\n        def _create_metadata_tables(metadata):\n            for table in metadata.sorted_tables:\n                if verbose:\n                    print(self._schema(table))\n                else:\n                    print('  '+table.name)\n                engine = self.session.get_bind(clause=table)\n                metadata.create_all(bind=engine, tables=[table])\n        if isinstance(self.metadata, MetaData):\n            print('Creating tables...')\n            _create_metadata_tables(self.metadata)\n        else:\n            for current_meta_name, metadata in self.metadata.items():\n                if meta_name not in (current_meta_name, None):\n                    continue\n                print('Creating tables for {}...'.format(current_meta_name))\n                _create_metadata_tables(metadata)",
    "docstring": "Create tables according sqlalchemy data model.\n\n        Is not a complex migration tool like alembic, just creates tables that\n        does not exist::\n\n            ./manage.py sqla:create_tables [--verbose] [meta_name]"
  },
  {
    "code": "def inventory_maps(inv):\n        revinv = {}\n        rolnam = {}\n        for d in inv:\n            if d[0:3] == 'py:' and d in IntersphinxInventory.domainrole:\n                r = IntersphinxInventory.domainrole[d]\n                rolnam[r] = ''\n                for n in inv[d]:\n                    p = inv[d][n][2]\n                    revinv[p] = (r, n)\n                    rolnam[r] += ' ' + n + ','\n        return revinv, rolnam",
    "docstring": "Construct dicts facilitating information lookup in an\n        inventory dict. A reversed dict allows lookup of a tuple\n        specifying the sphinx cross-reference role and the name of the\n        referenced type from the intersphinx inventory url postfix\n        string. A role-specific name lookup string allows the set of all\n        names corresponding to a specific role to be searched via regex."
  },
  {
    "code": "def apply(cls, self, *args, **kwargs):\n        for key in kwargs:\n          if key in [ x.name for x in cls.INPUTS ]:\n            setattr(self, key, kwargs[key])\n          if key in [ x.name for x in cls.OUTPUTS ]:\n            setattr(self, key, kwargs[key])\n          if key in [ x.name for x in cls.PARAMETERS ]:\n            setattr(self, key, kwargs[key])",
    "docstring": "Applies kwargs arguments to the instance passed as the first\n        argument to the call.\n\n        For defined INPUTS, OUTPUTS and PARAMETERS the method extracts\n        a corresponding value from kwargs and sets it as an instance attribute.\n        For example, if the processor has a 'foo' parameter declared and\n        'foo = something' is passed to apply(), self.foo will become\n        'something'."
  },
  {
    "code": "def _generate_signature(url_path, secret_key, query_args, digest=None, encoder=None):\n    digest = digest or DEFAULT_DIGEST\n    encoder = encoder or DEFAULT_ENCODER\n    msg = \"%s?%s\" % (url_path, '&'.join('%s=%s' % i for i in query_args.sorteditems(multi=True)))\n    if _compat.text_type:\n        msg = msg.encode('UTF8')\n    signature = hmac.new(secret_key, msg, digestmod=digest).digest()\n    if _compat.PY2:\n        return encoder(signature).rstrip('=')\n    else:\n        return encoder(signature).decode().rstrip('=')",
    "docstring": "Generate signature from pre-parsed URL."
  },
  {
    "code": "def omit_loglevel(self, msg) -> bool:\n        return self.loglevels and (\n            self.loglevels[0] > fontbakery.checkrunner.Status(msg)\n        )",
    "docstring": "Determine if message is below log level."
  },
  {
    "code": "def is_capable(cls, requested_capability):\n        for c in requested_capability:\n            if not c in cls.capability:\n                return False\n        return True",
    "docstring": "Returns true if the requested capability is supported by this plugin"
  },
  {
    "code": "def initialize(\n    plugins,\n    exclude_files_regex=None,\n    exclude_lines_regex=None,\n    path='.',\n    scan_all_files=False,\n):\n    output = SecretsCollection(\n        plugins,\n        exclude_files=exclude_files_regex,\n        exclude_lines=exclude_lines_regex,\n    )\n    if os.path.isfile(path):\n        files_to_scan = [path]\n    elif scan_all_files:\n        files_to_scan = _get_files_recursively(path)\n    else:\n        files_to_scan = _get_git_tracked_files(path)\n    if not files_to_scan:\n        return output\n    if exclude_files_regex:\n        exclude_files_regex = re.compile(exclude_files_regex, re.IGNORECASE)\n        files_to_scan = filter(\n            lambda file: (\n                not exclude_files_regex.search(file)\n            ),\n            files_to_scan,\n        )\n    for file in files_to_scan:\n        output.scan_file(file)\n    return output",
    "docstring": "Scans the entire codebase for secrets, and returns a\n    SecretsCollection object.\n\n    :type plugins: tuple of detect_secrets.plugins.base.BasePlugin\n    :param plugins: rules to initialize the SecretsCollection with.\n\n    :type exclude_files_regex: str|None\n    :type exclude_lines_regex: str|None\n    :type path: str\n    :type scan_all_files: bool\n\n    :rtype: SecretsCollection"
  },
  {
    "code": "def from_seedhex_file(path: str) -> SigningKeyType:\n        with open(path, 'r') as fh:\n            seedhex = fh.read()\n        return SigningKey.from_seedhex(seedhex)",
    "docstring": "Return SigningKey instance from Seedhex file\n\n        :param str path: Hexadecimal seed file path"
  },
  {
    "code": "def get_repo_relpath(repo, relpath):\n    from os import path\n    if relpath[0:2] == \"./\":\n        return path.join(repo, relpath[2::])\n    else:\n        from os import chdir, getcwd\n        cd = getcwd()\n        chdir(path.expanduser(repo))\n        result = path.abspath(relpath)\n        chdir(cd)\n        return result",
    "docstring": "Returns the absolute path to the 'relpath' taken relative to the base\n    directory of the repository."
  },
  {
    "code": "def create_and_trunk_vlan(self, nexus_host, vlan_id, intf_type,\n                              nexus_port, vni, is_native):\n        starttime = time.time()\n        self.create_vlan(nexus_host, vlan_id, vni)\n        LOG.debug(\"NexusDriver created VLAN: %s\", vlan_id)\n        if nexus_port:\n            self.send_enable_vlan_on_trunk_int(\n                nexus_host, vlan_id,\n                intf_type, nexus_port,\n                is_native)\n        self.capture_and_print_timeshot(\n            starttime, \"create_all\",\n            switch=nexus_host)",
    "docstring": "Create VLAN and trunk it on the specified ports."
  },
  {
    "code": "def accounts(self):\n        return account.HPEAccountCollection(\n            self._conn, utils.get_subresource_path_by(self, 'Accounts'),\n            redfish_version=self.redfish_version)",
    "docstring": "Property to provide instance of HPEAccountCollection"
  },
  {
    "code": "def push(self, metric_name=None, metric_value=None, volume=None):\n        graphite_path = self.path_prefix\n        graphite_path += '.' + self.device + '.' + 'volume'\n        graphite_path += '.' + volume + '.' + metric_name\n        metric = Metric(graphite_path, metric_value, precision=4,\n                        host=self.device)\n        self.publish_metric(metric)",
    "docstring": "Ship that shit off to graphite broski"
  },
  {
    "code": "def pgettext(msgctxt, message):\n    key = msgctxt + '\\x04' + message\n    translation = get_translation().gettext(key)\n    return message if translation == key else translation",
    "docstring": "Particular gettext' function.\n    It works with 'msgctxt' .po modifiers and allow duplicate keys with\n    different translations.\n    Python 2 don't have support for this GNU gettext function, so we\n    reimplement it. It works by joining msgctx and msgid by '4' byte."
  },
  {
    "code": "def _ar_matrix(self):\n        X = np.ones(self.data_length-self.max_lag)\n        if self.ar != 0:\n            for i in range(0, self.ar):\n                X = np.vstack((X,self.data[(self.max_lag-i-1):-i-1]))\n        return X",
    "docstring": "Creates the Autoregressive matrix for the model\n\n        Returns\n        ----------\n        X : np.ndarray\n            Autoregressive Matrix"
  },
  {
    "code": "def form_validation_response(self, e):\n        resp = rc.BAD_REQUEST\n        resp.write(' '+str(e.form.errors))\n        return resp",
    "docstring": "Method to return form validation error information. \n        You will probably want to override this in your own\n        `Resource` subclass."
  },
  {
    "code": "def _protobuf_value_type(value):\n  if value.HasField(\"number_value\"):\n    return api_pb2.DATA_TYPE_FLOAT64\n  if value.HasField(\"string_value\"):\n    return api_pb2.DATA_TYPE_STRING\n  if value.HasField(\"bool_value\"):\n    return api_pb2.DATA_TYPE_BOOL\n  return None",
    "docstring": "Returns the type of the google.protobuf.Value message as an api.DataType.\n\n  Returns None if the type of 'value' is not one of the types supported in\n  api_pb2.DataType.\n\n  Args:\n    value: google.protobuf.Value message."
  },
  {
    "code": "def change_logger_levels(logger=None, level=logging.DEBUG):\n    if not isinstance(logger, logging.Logger):\n        logger = logging.getLogger(logger)\n    logger.setLevel(level)\n    for handler in logger.handlers:\n        handler.level = level",
    "docstring": "Go through the logger and handlers and update their levels to the\n    one specified.\n\n    :param logger: logging name or object to modify, defaults to root logger\n    :param level: logging level to set at (10=Debug, 20=Info, 30=Warn, 40=Error)"
  },
  {
    "code": "async def cache_instruments(self,\n                                require: Dict[top_types.Mount, str] = None):\n        checked_require = require or {}\n        self._log.info(\"Updating instrument model cache\")\n        found = self._backend.get_attached_instruments(checked_require)\n        for mount, instrument_data in found.items():\n            model = instrument_data.get('model')\n            if model is not None:\n                p = Pipette(model,\n                            self._config.instrument_offset[mount.name.lower()],\n                            instrument_data['id'])\n                self._attached_instruments[mount] = p\n            else:\n                self._attached_instruments[mount] = None\n        mod_log.info(\"Instruments found: {}\".format(\n            self._attached_instruments))",
    "docstring": "- Get the attached instrument on each mount and\n         - Cache their pipette configs from pipette-config.json\n\n        If specified, the require element should be a dict of mounts to\n        instrument models describing the instruments expected to be present.\n        This can save a subsequent of :py:attr:`attached_instruments` and also\n        serves as the hook for the hardware simulator to decide what is\n        attached."
  },
  {
    "code": "def cut(self):\r\n        text = self.selectedText()\r\n        for editor in self.editors():\r\n            editor.cut()\r\n        QtGui.QApplication.clipboard().setText(text)",
    "docstring": "Cuts the text from the serial to the clipboard."
  },
  {
    "code": "def parse_oxi_states(self, data):\n        try:\n            oxi_states = {\n                data[\"_atom_type_symbol\"][i]:\n                    str2float(data[\"_atom_type_oxidation_number\"][i])\n                for i in range(len(data[\"_atom_type_symbol\"]))}\n            for i, symbol in enumerate(data[\"_atom_type_symbol\"]):\n                oxi_states[re.sub(r\"\\d?[\\+,\\-]?$\", \"\", symbol)] = \\\n                    str2float(data[\"_atom_type_oxidation_number\"][i])\n        except (ValueError, KeyError):\n            oxi_states = None\n        return oxi_states",
    "docstring": "Parse oxidation states from data dictionary"
  },
  {
    "code": "def query(self):\n        tree = pypeg2.parse(self._query, parser(), whitespace=\"\")\n        for walker in query_walkers():\n            tree = tree.accept(walker)\n        return tree",
    "docstring": "Parse query string using given grammar.\n\n        :returns: AST that represents the query in the given grammar."
  },
  {
    "code": "def prettyln(text, fill='-', align='^', prefix='[ ', suffix=' ]', length=69):\n    text = '{prefix}{0}{suffix}'.format(text, prefix=prefix, suffix=suffix)\n    print(\n        \"{0:{fill}{align}{length}}\".format(\n            text, fill=fill, align=align, length=length\n        )\n    )",
    "docstring": "Wrap `text` in a pretty line with maximum length."
  },
  {
    "code": "def formfield_for_dbfield(self, db_field, **kwargs):\n        if isinstance(db_field, fields.OrderField):\n            kwargs['widget'] = widgets.HiddenTextInput\n        return super(ListView, self).formfield_for_dbfield(db_field, **kwargs)",
    "docstring": "Same as parent but sets the widget for any OrderFields to\n        HiddenTextInput."
  },
  {
    "code": "def get_view_selection(self):\n        if not self.MODEL_STORAGE_ID:\n            return None, None\n        if len(self.store) == 0:\n            paths = []\n        else:\n            model, paths = self._tree_selection.get_selected_rows()\n        selected_model_list = []\n        for path in paths:\n            model = self.store[path][self.MODEL_STORAGE_ID]\n            selected_model_list.append(model)\n        return self._tree_selection, selected_model_list",
    "docstring": "Get actual tree selection object and all respective models of selected rows"
  },
  {
    "code": "def install(zone, nodataset=False, brand_opts=None):\n    ret = {'status': True}\n    res = __salt__['cmd.run_all']('zoneadm -z {zone} install{nodataset}{brand_opts}'.format(\n        zone=zone,\n        nodataset=' -x nodataset' if nodataset else '',\n        brand_opts=' {0}'.format(brand_opts) if brand_opts else '',\n    ))\n    ret['status'] = res['retcode'] == 0\n    ret['message'] = res['stdout'] if ret['status'] else res['stderr']\n    ret['message'] = ret['message'].replace('zoneadm: ', '')\n    if ret['message'] == '':\n        del ret['message']\n    return ret",
    "docstring": "Install the specified zone from the system.\n\n    zone : string\n        name of the zone\n    nodataset : boolean\n        do not create a ZFS file system\n    brand_opts : string\n        brand specific options to pass\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' zoneadm.install dolores\n        salt '*' zoneadm.install teddy True"
  },
  {
    "code": "def my_notes(self, start_index=0, limit=100, get_all=False, sort_by='loanId', sort_dir='asc'):\n        index = start_index\n        notes = {\n            'loans': [],\n            'total': 0,\n            'result': 'success'\n        }\n        while True:\n            payload = {\n                'sortBy': sort_by,\n                'dir': sort_dir,\n                'startindex': index,\n                'pagesize': limit,\n                'namespace': '/account'\n            }\n            response = self.session.post('/account/loansAj.action', data=payload)\n            json_response = response.json()\n            if self.session.json_success(json_response):\n                notes['loans'] += json_response['searchresult']['loans']\n                notes['total'] = json_response['searchresult']['totalRecords']\n            else:\n                notes['result'] = json_response['result']\n                break\n            if get_all is True and len(notes['loans']) < notes['total']:\n                index += limit\n            else:\n                break\n        return notes",
    "docstring": "Return all the loan notes you've already invested in. By default it'll return 100 results at a time.\n\n        Parameters\n        ----------\n        start_index : int, optional\n            The result index to start on. By default only 100 records will be returned at a time, so use this\n            to start at a later index in the results. For example, to get results 200 - 300, set `start_index` to 200.\n            (default is 0)\n        limit : int, optional\n            The number of results to return per request. (default is 100)\n        get_all : boolean, optional\n            Return all results in one request, instead of 100 per request.\n        sort_by : string, optional\n            What key to sort on\n        sort_dir : {'asc', 'desc'}, optional\n            Which direction to sort\n\n        Returns\n        -------\n        dict\n            A dictionary with a list of matching notes on the `loans` key"
  },
  {
    "code": "def fixed_length(cls, l, allow_empty=False):\n        return cls(l, l, allow_empty=allow_empty)",
    "docstring": "Create a sedes for text data with exactly `l` encoded characters."
  },
  {
    "code": "def create_failure(self, exception=None):\n        if exception:\n            return FailedFuture(type(exception), exception, None)\n        return FailedFuture(*sys.exc_info())",
    "docstring": "This returns an object implementing IFailedFuture.\n\n        If exception is None (the default) we MUST be called within an\n        \"except\" block (such that sys.exc_info() returns useful\n        information)."
  },
  {
    "code": "def get_user(self, user_id):\n\t\tcontent = self._fetch(\"/user/%s\" % user_id)\n\t\treturn FastlyUser(self, content)",
    "docstring": "Get a specific user."
  },
  {
    "code": "def var(self, values, axis=0, weights=None, dtype=None):\n        values = np.asarray(values)\n        unique, mean = self.mean(values, axis, weights, dtype)\n        err = values - mean.take(self.inverse, axis)\n        if weights is None:\n            shape = [1] * values.ndim\n            shape[axis] = self.groups\n            group_weights = self.count.reshape(shape)\n            var = self.reduce(err ** 2, axis=axis, dtype=dtype)\n        else:\n            weights = np.asarray(weights)\n            group_weights = self.reduce(weights, axis=axis, dtype=dtype)\n            var = self.reduce(weights * err ** 2, axis=axis, dtype=dtype)\n        return unique, var / group_weights",
    "docstring": "compute the variance over each group\n\n        Parameters\n        ----------\n        values : array_like, [keys, ...]\n            values to take variance of per group\n        axis : int, optional\n            alternative reduction axis for values\n\n        Returns\n        -------\n        unique: ndarray, [groups]\n            unique keys\n        reduced : ndarray, [groups, ...]\n            value array, reduced over groups"
  },
  {
    "code": "def close(self):\n        self.logger = None\n        for exc in _EXCEPTIONS:\n            setattr(self, exc, None)\n        try:\n            self.mdr.close()\n        finally:\n            self.mdr = None",
    "docstring": "Close the connection this context wraps."
  },
  {
    "code": "def csv_header_and_defaults(features, schema, stats, keep_target):\n  target_name = get_target_name(features)\n  if keep_target and not target_name:\n    raise ValueError('Cannot find target transform')\n  csv_header = []\n  record_defaults = []\n  for col in schema:\n    if not keep_target and col['name'] == target_name:\n      continue\n    csv_header.append(col['name'])\n    if col['type'].lower() == INTEGER_SCHEMA:\n      dtype = tf.int64\n      default = int(stats['column_stats'].get(col['name'], {}).get('mean', 0))\n    elif col['type'].lower() == FLOAT_SCHEMA:\n      dtype = tf.float32\n      default = float(stats['column_stats'].get(col['name'], {}).get('mean', 0.0))\n    else:\n      dtype = tf.string\n      default = ''\n    record_defaults.append(tf.constant([default], dtype=dtype))\n  return csv_header, record_defaults",
    "docstring": "Gets csv header and default lists."
  },
  {
    "code": "def can_create_gradebook_with_record_types(self, gradebook_record_types):\n        if self._catalog_session is not None:\n            return self._catalog_session.can_create_catalog_with_record_types(catalog_record_types=gradebook_record_types)\n        return True",
    "docstring": "Tests if this user can create a single ``Gradebook`` using the desired record types.\n\n        While ``GradingManager.getGradebookRecordTypes()`` can be used\n        to examine which records are supported, this method tests which\n        record(s) are required for creating a specific ``Gradebook``.\n        Providing an empty array tests if a ``Gradebook`` can be created\n        with no records.\n\n        arg:    gradebook_record_types (osid.type.Type[]): array of\n                gradebook record types\n        return: (boolean) - ``true`` if ``Gradebook`` creation using the\n                specified ``Types`` is supported, ``false`` otherwise\n        raise:  NullArgument - ``gradebook_record_types`` is ``null``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def folderitems(self):\n        items = super(AddAnalysesView, self).folderitems(classic=False)\n        return items",
    "docstring": "Return folderitems as brains"
  },
  {
    "code": "def __get_default_layouts_settings(self):\n        LOGGER.debug(\"> Accessing '{0}' default layouts settings file!\".format(UiConstants.layouts_file))\n        self.__default_layouts_settings = QSettings(umbra.ui.common.get_resource_path(UiConstants.layouts_file),\n                                                    QSettings.IniFormat)",
    "docstring": "Gets the default layouts settings."
  },
  {
    "code": "def to_feather(self, fname):\n        from pandas.io.feather_format import to_feather\n        to_feather(self, fname)",
    "docstring": "Write out the binary feather-format for DataFrames.\n\n        .. versionadded:: 0.20.0\n\n        Parameters\n        ----------\n        fname : str\n            string file path"
  },
  {
    "code": "def _sanity_check_fold_scope_locations_are_unique(ir_blocks):\n    observed_locations = dict()\n    for block in ir_blocks:\n        if isinstance(block, Fold):\n            alternate = observed_locations.get(block.fold_scope_location, None)\n            if alternate is not None:\n                raise AssertionError(u'Found two Fold blocks with identical FoldScopeLocations: '\n                                     u'{} {} {}'.format(alternate, block, ir_blocks))\n            observed_locations[block.fold_scope_location] = block",
    "docstring": "Assert that every FoldScopeLocation that exists on a Fold block is unique."
  },
  {
    "code": "def validate_reference_data(self, ref_data):\n        try:\n            self._zotero_lib.check_items([ref_data])\n        except InvalidItemFields as e:\n            raise InvalidZoteroItemError from e",
    "docstring": "Validate the reference data.\n\n        Zotero.check_items() caches data after the first API call."
  },
  {
    "code": "def clean(self, critical=False):\n        clean_events_list = []\n        while self.len() > 0:\n            item = self.events_list.pop()\n            if item[1] < 0 or (not critical and item[2].startswith(\"CRITICAL\")):\n                clean_events_list.insert(0, item)\n        self.events_list = clean_events_list\n        return self.len()",
    "docstring": "Clean the logs list by deleting finished items.\n\n        By default, only delete WARNING message.\n        If critical = True, also delete CRITICAL message."
  },
  {
    "code": "def load_ipython_extension(ipython):\n    import IPython\n    ipy_version = LooseVersion(IPython.__version__)\n    if ipy_version < LooseVersion(\"3.0.0\"):\n        ipython.write_err(\"Your IPython version is older than \"\n                          \"version 3.0.0, the minimum for Vispy's\"\n                          \"IPython backend. Please upgrade your IPython\"\n                          \"version.\")\n        return\n    _load_webgl_backend(ipython)",
    "docstring": "Entry point of the IPython extension\n\n    Parameters\n    ----------\n\n    IPython : IPython interpreter\n        An instance of the IPython interpreter that is handed\n        over to the extension"
  },
  {
    "code": "def mask_and_mean_loss(input_tensor, binary_tensor, axis=None):\n    return mean_on_masked(mask_loss(input_tensor, binary_tensor), binary_tensor, axis=axis)",
    "docstring": "Mask a loss by using a tensor filled with 0 or 1 and average correctly.\n\n    :param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy\n    :param binary_tensor: A float tensor of shape [batch_size, ...] representing the mask.\n    :return: A float tensor of shape [batch_size, ...] representing the masked loss.\n    :param axis: The dimensions to reduce. If None (the default), reduces all dimensions.\n                 Must be in the range [-rank(input_tensor), rank(input_tensor))."
  },
  {
    "code": "def remove_listener(registry, listener):\n    if listener is not None and listener in registry:\n        registry.remove(listener)\n        return True\n    return False",
    "docstring": "Removes a listener from the registry\n\n    :param registry: A registry (a list)\n    :param listener: The listener to remove\n    :return: True if the listener was in the list"
  },
  {
    "code": "def set_error_callback(cbfun):\n    global _error_callback\n    previous_callback = _error_callback\n    if cbfun is None:\n        cbfun = 0\n    c_cbfun = _GLFWerrorfun(cbfun)\n    _error_callback = (cbfun, c_cbfun)\n    cbfun = c_cbfun\n    _glfw.glfwSetErrorCallback(cbfun)\n    if previous_callback is not None and previous_callback[0] != 0:\n        return previous_callback[0]",
    "docstring": "Sets the error callback.\n\n    Wrapper for:\n        GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun);"
  },
  {
    "code": "def hangul_to_jamo(hangul_string):\n    return (_ for _ in\n            chain.from_iterable(_hangul_char_to_jamo(_) for _ in\n                                hangul_string))",
    "docstring": "Convert a string of Hangul to jamo.\n    Arguments may be iterables of characters.\n\n    hangul_to_jamo should split every Hangul character into U+11xx jamo\n    characters for any given string. Non-hangul characters are not changed.\n\n    hangul_to_jamo is the generator version of h2j, the string version."
  },
  {
    "code": "def PathList(self, pathlist):\n        pathlist = self._PathList_key(pathlist)\n        try:\n            memo_dict = self._memo['PathList']\n        except KeyError:\n            memo_dict = {}\n            self._memo['PathList'] = memo_dict\n        else:\n            try:\n                return memo_dict[pathlist]\n            except KeyError:\n                pass\n        result = _PathList(pathlist)\n        memo_dict[pathlist] = result\n        return result",
    "docstring": "Returns the cached _PathList object for the specified pathlist,\n        creating and caching a new object as necessary."
  },
  {
    "code": "def set_learning_objectives(self, objective_ids):\n        if not isinstance(objective_ids, list):\n            raise errors.InvalidArgument()\n        if self.get_learning_objectives_metadata().is_read_only():\n            raise errors.NoAccess()\n        idstr_list = []\n        for object_id in objective_ids:\n            if not self._is_valid_id(object_id):\n                raise errors.InvalidArgument()\n            idstr_list.append(str(object_id))\n        self._my_map['learningObjectiveIds'] = idstr_list",
    "docstring": "Sets the learning objectives.\n\n        arg:    objective_ids (osid.id.Id[]): the learning objective\n                ``Ids``\n        raise:  InvalidArgument - ``objective_ids`` is invalid\n        raise:  NoAccess - ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def append(\n            self,\n            moment_or_operation_tree: Union[ops.Moment, ops.OP_TREE],\n            strategy: InsertStrategy = InsertStrategy.EARLIEST):\n        self.insert(len(self._moments), moment_or_operation_tree, strategy)",
    "docstring": "Appends operations onto the end of the circuit.\n\n        Moments within the operation tree are appended intact.\n\n        Args:\n            moment_or_operation_tree: The moment or operation tree to append.\n            strategy: How to pick/create the moment to put operations into."
  },
  {
    "code": "def _get_response(self, method, endpoint, params=None):\n        url = urljoin(self.api_url, endpoint)\n        try:\n            response = getattr(self._session, method)(url, params=params)\n            if response.status_code == 401:\n                raise TokenExpiredError\n        except TokenExpiredError:\n            self._refresh_oath_token()\n            self._session = OAuth2Session(\n                client_id=self._client_id,\n                token=self._token,\n            )\n            response = getattr(self._session, method)(url, params=params)\n        if response.status_code != requests.codes.ok:\n            raise MonzoAPIError(\n                \"Something went wrong: {}\".format(response.json())\n            )\n        return response",
    "docstring": "Helper method to handle HTTP requests and catch API errors\n\n        :param method: valid HTTP method\n        :type method: str\n        :param endpoint: API endpoint\n        :type endpoint: str\n        :param params: extra parameters passed with the request\n        :type params: dict\n        :returns: API response\n        :rtype: Response"
  },
  {
    "code": "def disable(name, runas=None):\n    service_target = _get_domain_target(name, service_target=True)[0]\n    return launchctl('disable', service_target, runas=runas)",
    "docstring": "Disable a launchd service. Raises an error if the service fails to be\n    disabled\n\n    :param str name: Service label, file name, or full path\n\n    :param str runas: User to run launchctl commands\n\n    :return: ``True`` if successful or if the service is already disabled\n    :rtype: bool\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' service.disable org.cups.cupsd"
  },
  {
    "code": "def matchall(r, s, flags=0):\n    try:\n        return [m.group(0) for m in matchiter(r, s, flags)]\n    except ValueError:\n        return None",
    "docstring": "Returns the list of contiguous string matches of r in s,\n    or None if r does not successively match the entire s."
  },
  {
    "code": "def create(self):\n        if self.path is not None:\n            logger.debug(\n                \"Skipped creation of temporary directory: {}\".format(self.path)\n            )\n            return\n        self.path = os.path.realpath(\n            tempfile.mkdtemp(prefix=\"pip-{}-\".format(self.kind))\n        )\n        self._register_finalizer()\n        logger.debug(\"Created temporary directory: {}\".format(self.path))",
    "docstring": "Create a temporary directory and store its path in self.path"
  },
  {
    "code": "def easeInOutCubic(n):\n    _checkRange(n)\n    n = 2 * n\n    if n < 1:\n        return 0.5 * n**3\n    else:\n        n = n - 2\n        return 0.5 * (n**3 + 2)",
    "docstring": "A cubic tween function that accelerates, reaches the midpoint, and then decelerates.\n\n    Args:\n      n (float): The time progress, starting at 0.0 and ending at 1.0.\n\n    Returns:\n      (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine()."
  },
  {
    "code": "def clamp(value, lower=0, upper=sys.maxsize):\n    return max(lower, min(upper, value))",
    "docstring": "Clamp float between given range"
  },
  {
    "code": "def sync_release_files(self):\n        release_files = []\n        for release in self.releases.values():\n            release_files.extend(release)\n        downloaded_files = set()\n        deferred_exception = None\n        for release_file in release_files:\n            try:\n                downloaded_file = self.download_file(\n                    release_file[\"url\"], release_file[\"digests\"][\"sha256\"]\n                )\n                if downloaded_file:\n                    downloaded_files.add(\n                        str(downloaded_file.relative_to(self.mirror.homedir))\n                    )\n            except Exception as e:\n                logger.exception(\n                    f\"Continuing to next file after error downloading: \"\n                    f\"{release_file['url']}\"\n                )\n                if not deferred_exception:\n                    deferred_exception = e\n        if deferred_exception:\n            raise deferred_exception\n        self.mirror.altered_packages[self.name] = downloaded_files",
    "docstring": "Purge + download files returning files removed + added"
  },
  {
    "code": "def viewport_changed(self, screen_id, x, y, width, height):\n        if not isinstance(screen_id, baseinteger):\n            raise TypeError(\"screen_id can only be an instance of type baseinteger\")\n        if not isinstance(x, baseinteger):\n            raise TypeError(\"x can only be an instance of type baseinteger\")\n        if not isinstance(y, baseinteger):\n            raise TypeError(\"y can only be an instance of type baseinteger\")\n        if not isinstance(width, baseinteger):\n            raise TypeError(\"width can only be an instance of type baseinteger\")\n        if not isinstance(height, baseinteger):\n            raise TypeError(\"height can only be an instance of type baseinteger\")\n        self._call(\"viewportChanged\",\n                     in_p=[screen_id, x, y, width, height])",
    "docstring": "Signals that framebuffer window viewport has changed.\n\n        in screen_id of type int\n            Monitor to take the screenshot from.\n\n        in x of type int\n            Framebuffer x offset.\n\n        in y of type int\n            Framebuffer y offset.\n\n        in width of type int\n            Viewport width.\n\n        in height of type int\n            Viewport height.\n\n        raises :class:`OleErrorInvalidarg`\n            The specified viewport data is invalid."
  },
  {
    "code": "def get_by_natural_key(self, *args):\n        kwargs = self.natural_key_kwargs(*args)\n        for name, rel_to in self.model.get_natural_key_info():\n            if not rel_to:\n                continue\n            nested_key = extract_nested_key(kwargs, rel_to, name)\n            if nested_key:\n                try:\n                    kwargs[name] = rel_to.objects.get_by_natural_key(\n                        *nested_key\n                    )\n                except rel_to.DoesNotExist:\n                    raise self.model.DoesNotExist()\n            else:\n                kwargs[name] = None\n        return self.get(**kwargs)",
    "docstring": "Return the object corresponding to the provided natural key.\n\n        (This is a generic implementation of the standard Django function)"
  },
  {
    "code": "def in_same_table(self):\n        if self._tc.tbl is self._other_tc.tbl:\n            return True\n        return False",
    "docstring": "True if both cells provided to constructor are in same table."
  },
  {
    "code": "def trajectory(self):\n        traj = np.zeros((2, self.times.size))\n        for t, time in enumerate(self.times):\n            traj[:, t] = self.center_of_mass(time)\n        return traj",
    "docstring": "Calculates the center of mass for each time step and outputs an array\n\n        Returns:"
  },
  {
    "code": "def get_as_integer(self, key):\n        value = self.get(key)\n        return IntegerConverter.to_integer(value)",
    "docstring": "Converts map element into an integer or returns 0 if conversion is not possible.\n\n        :param key: an index of element to get.\n\n        :return: integer value ot the element or 0 if conversion is not supported."
  },
  {
    "code": "def download_from_url(path, url):\n  filename = url.split(\"/\")[-1]\n  found_file = find_file(path, filename, max_depth=0)\n  if found_file is None:\n    filename = os.path.join(path, filename)\n    tf.logging.info(\"Downloading from %s to %s.\" % (url, filename))\n    inprogress_filepath = filename + \".incomplete\"\n    inprogress_filepath, _ = urllib.request.urlretrieve(\n        url, inprogress_filepath, reporthook=download_report_hook)\n    print()\n    tf.gfile.Rename(inprogress_filepath, filename)\n    return filename\n  else:\n    tf.logging.info(\"Already downloaded: %s (at %s).\" % (url, found_file))\n    return found_file",
    "docstring": "Download content from a url.\n\n  Args:\n    path: string directory where file will be downloaded\n    url: string url\n\n  Returns:\n    Full path to downloaded file"
  },
  {
    "code": "def probability_lt(self, x):\n        if self.mean is None:\n            return\n        return normdist(x=x, mu=self.mean, sigma=self.standard_deviation)",
    "docstring": "Returns the probability of a random variable being less than the\n        given value."
  },
  {
    "code": "def start(self):\n        if (self.cf.link is not None):\n            if (self._added is False):\n                self.create()\n                logger.debug('First time block is started, add block')\n            else:\n                logger.debug('Block already registered, starting logging'\n                             ' for id=%d', self.id)\n                pk = CRTPPacket()\n                pk.set_header(5, CHAN_SETTINGS)\n                pk.data = (CMD_START_LOGGING, self.id, self.period)\n                self.cf.send_packet(pk, expected_reply=(\n                    CMD_START_LOGGING, self.id))",
    "docstring": "Start the logging for this entry"
  },
  {
    "code": "def rsync(config_file, source, target, override_cluster_name, down):\n    config = yaml.load(open(config_file).read())\n    if override_cluster_name is not None:\n        config[\"cluster_name\"] = override_cluster_name\n    config = _bootstrap_config(config)\n    head_node = _get_head_node(\n        config, config_file, override_cluster_name, create_if_needed=False)\n    provider = get_node_provider(config[\"provider\"], config[\"cluster_name\"])\n    try:\n        updater = NodeUpdaterThread(\n            node_id=head_node,\n            provider_config=config[\"provider\"],\n            provider=provider,\n            auth_config=config[\"auth\"],\n            cluster_name=config[\"cluster_name\"],\n            file_mounts=config[\"file_mounts\"],\n            initialization_commands=[],\n            setup_commands=[],\n            runtime_hash=\"\",\n        )\n        if down:\n            rsync = updater.rsync_down\n        else:\n            rsync = updater.rsync_up\n        rsync(source, target, check_error=False)\n    finally:\n        provider.cleanup()",
    "docstring": "Rsyncs files.\n\n    Arguments:\n        config_file: path to the cluster yaml\n        source: source dir\n        target: target dir\n        override_cluster_name: set the name of the cluster\n        down: whether we're syncing remote -> local"
  },
  {
    "code": "def decorate_function(self, name, decorator):\n        self.functions[name] = decorator(self.functions[name])",
    "docstring": "Decorate function with given name with given decorator.\n\n        :param str name: Name of the function.\n        :param callable decorator: Decorator callback."
  },
  {
    "code": "def which(program):\n    def is_exe(_fpath):\n        return os.path.isfile(_fpath) and os.access(_fpath, os.X_OK)\n    fpath, fname = os.path.split(program)\n    if fpath:\n        if is_exe(program):\n            return program\n    else:\n        for path in os.environ[\"PATH\"].split(os.pathsep):\n            exe_file = os.path.join(path, program)\n            if is_exe(exe_file):\n                return exe_file\n    return None",
    "docstring": "returns the path to an executable or None if it can't be found"
  },
  {
    "code": "def kernels_pull_cli(self,\n                         kernel,\n                         kernel_opt=None,\n                         path=None,\n                         metadata=False):\n        kernel = kernel or kernel_opt\n        effective_path = self.kernels_pull(\n            kernel, path=path, metadata=metadata, quiet=False)\n        if metadata:\n            print('Source code and metadata downloaded to ' + effective_path)\n        else:\n            print('Source code downloaded to ' + effective_path)",
    "docstring": "client wrapper for kernels_pull"
  },
  {
    "code": "def logout(self):\n        if self._logged_in is True:\n            self.si.flush_cache()\n            self.sc.sessionManager.Logout()\n            self._logged_in = False",
    "docstring": "Logout of a vSphere server."
  },
  {
    "code": "def transformer_relative():\n  hparams = transformer_base()\n  hparams.pos = None\n  hparams.self_attention_type = \"dot_product_relative\"\n  hparams.max_relative_position = 20\n  return hparams",
    "docstring": "Use relative position embeddings instead of absolute position encodings."
  },
  {
    "code": "def cm_json_to_graph(im_json):\n    cmap_data = im_json['contact map']['map']\n    graph = AGraph()\n    edges = []\n    for node_idx, node in enumerate(cmap_data):\n        sites_in_node = []\n        for site_idx, site in enumerate(node['node_sites']):\n            site_key = (node_idx, site_idx)\n            sites_in_node.append(site_key)\n            graph.add_node(site_key, label=site['site_name'], style='filled',\n                           shape='ellipse')\n            if not site['site_type'] or not site['site_type'][0] == 'port':\n                continue\n            for port_link in site['site_type'][1]['port_links']:\n                edge = (site_key, tuple(port_link))\n                edges.append(edge)\n        graph.add_subgraph(sites_in_node,\n                           name='cluster_%s' % node['node_type'],\n                           label=node['node_type'])\n    for source, target in edges:\n        graph.add_edge(source, target)\n    return graph",
    "docstring": "Return pygraphviz Agraph from Kappy's contact map JSON.\n\n    Parameters\n    ----------\n    im_json : dict\n        A JSON dict which contains a contact map generated by Kappy.\n\n    Returns\n    -------\n    graph : pygraphviz.Agraph\n        A graph representing the contact map."
  },
  {
    "code": "def close(self):\n        if self._filename and self._fh:\n            self._fh.close()\n            self._fh = None",
    "docstring": "Close open file. Future asarray calls might fail."
  },
  {
    "code": "def on_modified(self, event):\n        if os.path.isdir(event.src_path):\n            return\n        logger.debug(\"file modified: %s\", event.src_path)\n        name = self.file_name(event)\n        try:\n            config = yaml.load(open(event.src_path))\n            self.target_class.from_config(name, config)\n        except Exception:\n            logger.exception(\n                \"Error when loading updated config file %s\", event.src_path,\n            )\n            return\n        self.on_update(self.target_class, name, config)",
    "docstring": "Modified config file handler.\n\n        If a config file is modified, the yaml contents are parsed and the\n        new results are validated by the target class.  Once validated, the\n        new config is passed to the on_update callback."
  },
  {
    "code": "def __get_registry_key(self, key):\n        import winreg\n        root = winreg.OpenKey(\n            winreg.HKEY_CURRENT_USER, r'SOFTWARE\\GSettings\\org\\gnucash\\general', 0, winreg.KEY_READ)\n        [pathname, regtype] = (winreg.QueryValueEx(root, key))\n        winreg.CloseKey(root)\n        return pathname",
    "docstring": "Read currency from windows registry"
  },
  {
    "code": "def with_subprocess(cls):\n    def run_process(self, command, input=None):\n        if isinstance(command, (tuple, list)):\n            command = ' '.join('\"%s\"' % x for x in command)\n        proc = subprocess.Popen(\n            command,\n            shell=True,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE\n        )\n        out, err = proc.communicate(input=input)\n        return proc.returncode, out.strip(), err.strip()\n    cls.run_process = run_process\n    return cls",
    "docstring": "a class decorator for Crontabber Apps.  This decorator gives the CronApp\n    a _run_proxy method that will execute the cron app as a single PG\n    transaction.  Commit and Rollback are automatic.  The cron app should do\n    no transaction management of its own.  The cron app should be short so that\n    the transaction is not held open too long."
  },
  {
    "code": "def get_connections(self):\n        con = []\n        maxconn = self.max_connectivity\n        for ii in range(0, maxconn.shape[0]):\n            for jj in range(0, maxconn.shape[1]):\n                if maxconn[ii][jj] != 0:\n                    dist = self.s.get_distance(ii, jj)\n                    con.append([ii, jj, dist])\n        return con",
    "docstring": "Returns a list of site pairs that are Voronoi Neighbors, along\n        with their real-space distances."
  },
  {
    "code": "def get_class_name(class_key, classification_key):\n    classification = definition(classification_key)\n    for the_class in classification['classes']:\n        if the_class.get('key') == class_key:\n            return the_class.get('name', class_key)\n    return class_key",
    "docstring": "Helper to get class name from a class_key of a classification.\n\n    :param class_key: The key of the class.\n    :type class_key: str\n\n    :type classification_key: The key of a classification.\n    :param classification_key: str\n\n    :returns: The name of the class.\n    :rtype: str"
  },
  {
    "code": "def close(self, *args, **kwargs):\n        if not self.__finalized:\n            self._file.write('</cml>')\n            self.__finalized = True\n        super().close(*args, **kwargs)",
    "docstring": "write close tag of MRV file and close opened file\n\n        :param force: force closing of externally opened file or buffer"
  },
  {
    "code": "def info(self, callback=None, **kwargs):\n        self.client.fetch(\n            self.mk_req('', method='GET', **kwargs),\n            callback = callback\n        )",
    "docstring": "Get the basic info from the current cluster."
  },
  {
    "code": "def create_group(self, name):\n        url = 'rest/api/2/group'\n        data = {'name': name}\n        return self.post(url, data=data)",
    "docstring": "Create a group by given group parameter\n\n        :param name: str\n        :return: New group params"
  },
  {
    "code": "def _unstack(self, unstacker_func, new_columns, n_rows, fill_value):\n        unstacker = unstacker_func(self.values.T)\n        new_items = unstacker.get_new_columns()\n        new_placement = new_columns.get_indexer(new_items)\n        new_values, mask = unstacker.get_new_values()\n        mask = mask.any(0)\n        new_values = new_values.T[mask]\n        new_placement = new_placement[mask]\n        blocks = [make_block(new_values, placement=new_placement)]\n        return blocks, mask",
    "docstring": "Return a list of unstacked blocks of self\n\n        Parameters\n        ----------\n        unstacker_func : callable\n            Partially applied unstacker.\n        new_columns : Index\n            All columns of the unstacked BlockManager.\n        n_rows : int\n            Only used in ExtensionBlock.unstack\n        fill_value : int\n            Only used in ExtensionBlock.unstack\n\n        Returns\n        -------\n        blocks : list of Block\n            New blocks of unstacked values.\n        mask : array_like of bool\n            The mask of columns of `blocks` we should keep."
  },
  {
    "code": "def update_keyjar(keyjar):\n    for iss, kbl in keyjar.items():\n        for kb in kbl:\n            kb.update()",
    "docstring": "Go through the whole key jar, key bundle by key bundle and update them one\n    by one.\n\n    :param keyjar: The key jar to update"
  },
  {
    "code": "def flatten(nested_list):\n    return_list = []\n    for i in nested_list:\n        if isinstance(i,list):\n            return_list += flatten(i)\n        else:\n            return_list.append(i)\n    return return_list",
    "docstring": "converts a list-of-lists to a single flat list"
  },
  {
    "code": "def light_to_gl(light, transform, lightN):\n    gl_color = vector_to_gl(light.color.astype(np.float64) / 255.0)\n    assert len(gl_color) == 4\n    gl_position = vector_to_gl(transform[:3, 3])\n    args = [(lightN, gl.GL_POSITION, gl_position),\n            (lightN, gl.GL_SPECULAR, gl_color),\n            (lightN, gl.GL_DIFFUSE, gl_color),\n            (lightN, gl.GL_AMBIENT, gl_color)]\n    return args",
    "docstring": "Convert trimesh.scene.lighting.Light objects into\n    args for gl.glLightFv calls\n\n    Parameters\n    --------------\n    light : trimesh.scene.lighting.Light\n      Light object to be converted to GL\n    transform : (4, 4) float\n      Transformation matrix of light\n    lightN : int\n      Result of gl.GL_LIGHT0, gl.GL_LIGHT1, etc\n\n    Returns\n    --------------\n    multiarg : [tuple]\n      List of args to pass to gl.glLightFv eg:\n      [gl.glLightfb(*a) for a in multiarg]"
  },
  {
    "code": "def atlas_peer_is_whitelisted( peer_hostport, peer_table=None ):\n    ret = None\n    with AtlasPeerTableLocked(peer_table) as ptbl:\n        if peer_hostport not in ptbl.keys():\n            return None \n        ret = ptbl[peer_hostport].get(\"whitelisted\", False)\n    return ret",
    "docstring": "Is a peer whitelisted"
  },
  {
    "code": "def date_range_filter(range_name):\n    filter_days = list(filter(\n        lambda time: time[\"label\"] == range_name,\n        settings.CUSTOM_SEARCH_TIME_PERIODS))\n    num_days = filter_days[0][\"days\"] if len(filter_days) else None\n    if num_days:\n        dt = timedelta(num_days)\n        start_time = timezone.now() - dt\n        return Range(published={\"gte\": start_time})\n    return MatchAll()",
    "docstring": "Create a filter from a named date range."
  },
  {
    "code": "def get_defaults_dict(self) -> Dict:\n        return deserializer.inventory.Defaults.serialize(self.defaults).dict()",
    "docstring": "Returns serialized dictionary of defaults from inventory"
  },
  {
    "code": "def best_assemblyfile(self):\n        for sample in self.metadata:\n            assembly_file = os.path.join(sample.general.spadesoutput, 'contigs.fasta')\n            if os.path.isfile(assembly_file):\n                sample.general.bestassemblyfile = assembly_file\n            else:\n                sample.general.bestassemblyfile = 'NA'\n            filteredfile = os.path.join(sample.general.outputdirectory, '{}.fasta'.format(sample.name))\n            sample.general.filteredfile = filteredfile",
    "docstring": "Determine whether the contigs.fasta output file from SPAdes is present. If not, set the .bestassembly\n        attribute to 'NA'"
  },
  {
    "code": "def _parse_apps_to_ignore(self):\n        apps_to_ignore = set()\n        section_title = 'applications_to_ignore'\n        if self._parser.has_section(section_title):\n            apps_to_ignore = set(self._parser.options(section_title))\n        return apps_to_ignore",
    "docstring": "Parse the applications to ignore in the config.\n\n        Returns:\n            set"
  },
  {
    "code": "def merge_obs(self):\n        for model_type in self.model_types:\n            self.matched_forecasts[model_type] = {}\n            for model_name in self.model_names[model_type]:\n                self.matched_forecasts[model_type][model_name] = pd.merge(self.forecasts[model_type][model_name],\n                                                                          self.obs, right_on=\"Step_ID\", how=\"left\",\n                                                                          left_index=True)",
    "docstring": "Match forecasts and observations."
  },
  {
    "code": "def replace_rep(t:str) -> str:\n    \"Replace repetitions at the character level in `t`.\"\n    def _replace_rep(m:Collection[str]) -> str:\n        c,cc = m.groups()\n        return f' {TK_REP} {len(cc)+1} {c} '\n    re_rep = re.compile(r'(\\S)(\\1{3,})')\n    return re_rep.sub(_replace_rep, t)",
    "docstring": "Replace repetitions at the character level in `t`."
  },
  {
    "code": "def is_empty(self):\n        return all(date.is_empty() for date in [self.created, self.issued]) \\\n               and not self.publisher",
    "docstring": "Returns True if all child date elements present are empty\n        and other nodes are not set.  Returns False if any child date\n        elements are not empty or other nodes are set."
  },
  {
    "code": "def update_w3(self, w3: Web3) -> \"Package\":\n        validate_w3_instance(w3)\n        return Package(self.manifest, w3, self.uri)",
    "docstring": "Returns a new instance of `Package` containing the same manifest,\n        but connected to a different web3 instance.\n\n        .. doctest::\n\n           >>> new_w3 = Web3(Web3.EthereumTesterProvider())\n           >>> NewPackage = OwnedPackage.update_w3(new_w3)\n           >>> assert NewPackage.w3 == new_w3\n           >>> assert OwnedPackage.manifest == NewPackage.manifest"
  },
  {
    "code": "def getConfiguration(self):\n        configuration = c_int()\n        mayRaiseUSBError(libusb1.libusb_get_configuration(\n            self.__handle, byref(configuration),\n        ))\n        return configuration.value",
    "docstring": "Get the current configuration number for this device."
  },
  {
    "code": "def validate_api_response(schema, raw_response, request_method='get', raw_request=None):\n    request = None\n    if raw_request is not None:\n        request = normalize_request(raw_request)\n    response = None\n    if raw_response is not None:\n        response = normalize_response(raw_response, request=request)\n    if response is not None:\n        validate_response(\n            response=response,\n            request_method=request_method,\n            schema=schema\n        )",
    "docstring": "Validate the response of an api call against a swagger schema."
  },
  {
    "code": "def read_file(rel_path, paths=None, raw=False, as_list=False, as_iter=False,\n              *args, **kwargs):\n    if not rel_path:\n        raise ValueError(\"rel_path can not be null!\")\n    paths = str2list(paths)\n    paths.extend([STATIC_DIR, os.path.join(SRC_DIR, 'static')])\n    paths = [os.path.expanduser(p) for p in set(paths)]\n    for path in paths:\n        path = os.path.join(path, rel_path)\n        logger.debug(\"trying to read: %s \" % path)\n        if os.path.exists(path):\n            break\n    else:\n        raise IOError(\"path %s does not exist!\" % rel_path)\n    args = args if args else ['rU']\n    fd = open(path, *args, **kwargs)\n    if raw:\n        return fd\n    if as_iter:\n        return read_in_chunks(fd)\n    else:\n        fd_lines = fd.readlines()\n    if as_list:\n        return fd_lines\n    else:\n        return ''.join(fd_lines)",
    "docstring": "find a file that lives somewhere within a set of paths and\n        return its contents. Default paths include 'static_dir'"
  },
  {
    "code": "def iter_token_lines(tokenlist):\n    line = []\n    for token, c in explode_tokens(tokenlist):\n        line.append((token, c))\n        if c == '\\n':\n            yield line\n            line = []\n    yield line",
    "docstring": "Iterator that yields tokenlists for each line."
  },
  {
    "code": "def http_list(self, path, query_data={}, as_list=None, **kwargs):\n        as_list = True if as_list is None else as_list\n        get_all = kwargs.pop('all', False)\n        url = self._build_url(path)\n        if get_all is True:\n            return list(GitlabList(self, url, query_data, **kwargs))\n        if 'page' in kwargs or as_list is True:\n            return list(GitlabList(self, url, query_data, get_next=False,\n                                   **kwargs))\n        return GitlabList(self, url, query_data, **kwargs)",
    "docstring": "Make a GET request to the Gitlab server for list-oriented queries.\n\n        Args:\n            path (str): Path or full URL to query ('/projects' or\n                        'http://whatever/v4/api/projecs')\n            query_data (dict): Data to send as query parameters\n            **kwargs: Extra options to send to the server (e.g. sudo, page,\n                      per_page)\n\n        Returns:\n            list: A list of the objects returned by the server. If `as_list` is\n            False and no pagination-related arguments (`page`, `per_page`,\n            `all`) are defined then a GitlabList object (generator) is returned\n            instead. This object will make API calls when needed to fetch the\n            next items from the server.\n\n        Raises:\n            GitlabHttpError: When the return code is not 2xx\n            GitlabParsingError: If the json data could not be parsed"
  },
  {
    "code": "def temp_to_spmatrix(self, ty):\n        assert ty in ('jac0', 'jac')\n        jac0s = ['Fx0', 'Fy0', 'Gx0', 'Gy0']\n        jacs = ['Fx', 'Fy', 'Gx', 'Gy']\n        if ty == 'jac0':\n            todo = jac0s\n        elif ty == 'jac':\n            todo = jacs\n        for m in todo:\n            self.__dict__[m] = spmatrix(self._temp[m]['V'],\n                                        self._temp[m]['I'], self._temp[m]['J'],\n                                        self.get_size(m), 'd')\n            if ty == 'jac':\n                self.__dict__[m] += self.__dict__[m + '0']\n        self.apply_set(ty)",
    "docstring": "Convert Jacobian tuples to matrices\n\n        :param ty: name of the matrices to convert in ``('jac0','jac')``\n\n        :return: None"
  },
  {
    "code": "def _get_color_size(self, style):\n        color = \"b\"\n        if \"color\" in style:\n            color = style[\"color\"]\n        size = 7\n        if \"size\" in style:\n            size = style[\"size\"]\n        return color, size",
    "docstring": "Get color and size from a style dict"
  },
  {
    "code": "def log_value(self, tag, val, desc=''):\n    logging.info('%s (%s): %.4f' % (desc, tag, val))\n    self.summary.value.add(tag=tag, simple_value=val)",
    "docstring": "Log values to standard output and Tensorflow summary.\n\n    :param tag: summary tag.\n    :param val: (required float or numpy array) value to be logged.\n    :param desc: (optional) additional description to be printed."
  },
  {
    "code": "def read(self, count):\n        if not self.data:\n            raise UnpackException(None, count, 0)\n        buff = self.data.read(count)\n        if len(buff) < count:\n            raise UnpackException(None, count, len(buff))\n        return buff",
    "docstring": "read count bytes from the unpacker and return it. Raises an\n        UnpackException if there is not enough data in the underlying\n        stream."
  },
  {
    "code": "def input(channel):\n    _check_configured(channel)\n    pin = get_gpio_pin(_mode, channel)\n    return sysfs.input(pin)",
    "docstring": "Read the value of a GPIO pin.\n\n    :param channel: the channel based on the numbering system you have specified\n        (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`).\n    :returns: This will return either :py:attr:`0` / :py:attr:`GPIO.LOW` /\n        :py:attr:`False` or :py:attr:`1` / :py:attr:`GPIO.HIGH` / :py:attr:`True`)."
  },
  {
    "code": "def RegisterPlugin(cls, plugin_class):\n    plugin_name = plugin_class.NAME.lower()\n    if plugin_name in cls._plugin_classes:\n      raise KeyError((\n          'Plugin class already set for name: {0:s}.').format(\n              plugin_class.NAME))\n    cls._plugin_classes[plugin_name] = plugin_class",
    "docstring": "Registers a plugin class.\n\n    The plugin classes are identified based on their lower case name.\n\n    Args:\n      plugin_class (type): class of the plugin.\n\n    Raises:\n      KeyError: if plugin class is already set for the corresponding name."
  },
  {
    "code": "def dbus_readBytesTwoFDs(self, fd1, fd2, byte_count):\n        result = bytearray()\n        for fd in (fd1, fd2):\n            f = os.fdopen(fd, 'rb')\n            result.extend(f.read(byte_count))\n            f.close()\n        return result",
    "docstring": "Reads byte_count from fd1 and fd2. Returns concatenation."
  },
  {
    "code": "def get(self, line_number):\n        if line_number not in self._get_cache:\n            self._get_cache[line_number] = self._get(line_number)\n        return self._get_cache[line_number]",
    "docstring": "Return the needle positions or None.\n\n        :param int line_number: the number of the line\n        :rtype: list\n        :return: the needle positions for a specific line specified by\n          :paramref:`line_number` or :obj:`None` if no were given"
  },
  {
    "code": "def _check_response_for_errors(self, response):\n        try:\n            doc = minidom.parseString(_string(response).replace(\"opensearch:\", \"\"))\n        except Exception as e:\n            raise MalformedResponseError(self.network, e)\n        e = doc.getElementsByTagName(\"lfm\")[0]\n        if e.getAttribute(\"status\") != \"ok\":\n            e = doc.getElementsByTagName(\"error\")[0]\n            status = e.getAttribute(\"code\")\n            details = e.firstChild.data.strip()\n            raise WSError(self.network, status, details)",
    "docstring": "Checks the response for errors and raises one if any exists."
  },
  {
    "code": "def get(self, sid):\n        return InteractionContext(\n            self._version,\n            service_sid=self._solution['service_sid'],\n            session_sid=self._solution['session_sid'],\n            sid=sid,\n        )",
    "docstring": "Constructs a InteractionContext\n\n        :param sid: The unique string that identifies the resource\n\n        :returns: twilio.rest.proxy.v1.service.session.interaction.InteractionContext\n        :rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionContext"
  },
  {
    "code": "def write(self, section, option, value):\n        self.config.read(self.filepath)\n        string = tidy_headers._parse_item.item2string(value, sep=\", \")\n        self.config.set(section, option, string)\n        with open(self.filepath, \"w\") as f:\n            self.config.write(f)",
    "docstring": "Write to file.\n\n        Parameters\n        ----------\n        section : string\n            Section.\n        option : string\n            Option.\n        value : string\n            Value."
  },
  {
    "code": "def assign_contributor_permissions(obj, contributor=None):\n    for permission in get_all_perms(obj):\n        assign_perm(permission, contributor if contributor else obj.contributor, obj)",
    "docstring": "Assign all permissions to object's contributor."
  },
  {
    "code": "def individuals(self, ind_ids=None):\n        query = self.query(Individual)\n        if ind_ids:\n            query = query.filter(Individual.ind_id.in_(ind_ids))\n        return query",
    "docstring": "Fetch all individuals from the database."
  },
  {
    "code": "def put_member(self, name: InstanceName, value: Value,\n                   raw: bool = False) -> \"InstanceNode\":\n        if not isinstance(self.value, ObjectValue):\n            raise InstanceValueError(self.json_pointer(), \"member of non-object\")\n        csn = self._member_schema_node(name)\n        newval = self.value.copy()\n        newval[name] = csn.from_raw(value, self.json_pointer()) if raw else value\n        return self._copy(newval)._member(name)",
    "docstring": "Return receiver's member with a new value.\n\n        If the member is permitted by the schema but doesn't exist, it\n        is created.\n\n        Args:\n            name: Instance name of the member.\n            value: New value of the member.\n            raw: Flag to be set if `value` is raw.\n\n        Raises:\n            NonexistentSchemaNode: If member `name` is not permitted by the\n                schema.\n            InstanceValueError: If the receiver's value is not an object."
  },
  {
    "code": "def elcm_profile_get_versions(irmc_info):\n    resp = elcm_request(irmc_info,\n                        method='GET',\n                        path=URL_PATH_PROFILE_MGMT + 'version')\n    if resp.status_code == 200:\n        return _parse_elcm_response_body_as_json(resp)\n    else:\n        raise scci.SCCIClientError(('Failed to get profile versions with '\n                                    'error code %s' % resp.status_code))",
    "docstring": "send an eLCM request to get profile versions\n\n    :param irmc_info: node info\n    :returns: dict object of profiles if succeed\n        {\n            \"Server\":{\n                \"@Version\": \"1.01\",\n                \"AdapterConfigIrmc\":{\n                    \"@Version\": \"1.00\"\n                },\n                \"HWConfigurationIrmc\":{\n                    \"@Version\": \"1.00\"\n                },\n                \"SystemConfig\":{\n                    \"IrmcConfig\":{\n                        \"@Version\": \"1.02\"\n                    },\n                    \"BiosConfig\":{\n                        \"@Version\": \"1.02\"\n                    }\n                }\n            }\n        }\n    :raises: SCCIClientError if SCCI failed"
  },
  {
    "code": "def _reduce_boolean_pair(self, config_dict, key1, key2):\n        if key1 in config_dict and key2 in config_dict \\\n                and config_dict[key1] == config_dict[key2]:\n            msg = 'Boolean pair, %s and %s, have same value: %s. If both ' \\\n                'are given to this method, they cannot be the same, as this ' \\\n                'method cannot decide which one should be True.' \\\n                % (key1, key2, config_dict[key1])\n            raise BooleansToReduceHaveSameValue(msg)\n        elif key1 in config_dict and not config_dict[key1]:\n            config_dict[key2] = True\n            config_dict.pop(key1)\n        elif key2 in config_dict and not config_dict[key2]:\n            config_dict[key1] = True\n            config_dict.pop(key2)\n        return config_dict",
    "docstring": "Ensure only one key with a boolean value is present in dict.\n\n        :param config_dict: dict -- dictionary of config or kwargs\n        :param key1: string -- first key name\n        :param key2: string -- second key name\n        :raises: BooleansToReduceHaveSameValue"
  },
  {
    "code": "def get_metrics(model: Model, total_loss: float, num_batches: int, reset: bool = False) -> Dict[str, float]:\n    metrics = model.get_metrics(reset=reset)\n    metrics[\"loss\"] = float(total_loss / num_batches) if num_batches > 0 else 0.0\n    return metrics",
    "docstring": "Gets the metrics but sets ``\"loss\"`` to\n    the total loss divided by the ``num_batches`` so that\n    the ``\"loss\"`` metric is \"average loss per batch\"."
  },
  {
    "code": "def begin_table(self, column_count):\n        self.table_columns = column_count\n        self.table_columns_left = 0\n        self.write('<table>')",
    "docstring": "Begins a table with the given 'column_count', required to automatically\n           create the right amount of columns when adding items to the rows"
  },
  {
    "code": "def _get_section_name(cls, parser):\n        for section_name in cls.POSSIBLE_SECTION_NAMES:\n            if parser.has_section(section_name):\n                return section_name\n        return None",
    "docstring": "Parse options from relevant section."
  },
  {
    "code": "def _get_subclass_list_for_enums(self, classname, namespace):\n        if self._repo_lite:\n            return NocaseDict({classname: classname})\n        if not self._class_exists(classname, namespace):\n            raise CIMError(\n                CIM_ERR_INVALID_CLASS,\n                _format(\"Class {0!A} not found in namespace {1!A}.\",\n                        classname, namespace))\n        if not self.classes:\n            return NocaseDict()\n        clnslist = self._get_subclass_names(classname, namespace, True)\n        clnsdict = NocaseDict()\n        for cln in clnslist:\n            clnsdict[cln] = cln\n        clnsdict[classname] = classname\n        return clnsdict",
    "docstring": "Get class list (i.e names of subclasses for classname for the\n            enumerateinstance methods. If conn.lite returns only classname but\n            no subclasses.\n\n            Returns NocaseDict where only the keys are important, This allows\n            case insensitive matches of the names with Python \"for cln in clns\"."
  },
  {
    "code": "async def delete(self, device, remove=True):\n        device = self._find_device(device)\n        if not self.is_handleable(device) or not device.is_loop:\n            self._log.warn(_('not deleting {0}: unhandled device', device))\n            return False\n        if remove:\n            await self.auto_remove(device, force=True)\n        self._log.debug(_('deleting {0}', device))\n        await device.delete()\n        self._log.info(_('deleted {0}', device))\n        return True",
    "docstring": "Detach the loop device.\n\n        :param device: device object, block device path or mount path\n        :param bool remove: whether to unmount the partition etc.\n        :returns: whether the loop device is deleted"
  },
  {
    "code": "def get_args(parser):\n    args = vars(parser.parse_args()).items()\n    return {key: val for key, val in args if not isinstance(val, NotSet)}",
    "docstring": "Converts arguments extracted from a parser to a dict,\n    and will dismiss arguments which default to NOT_SET.\n\n    :param parser: an ``argparse.ArgumentParser`` instance.\n    :type parser: argparse.ArgumentParser\n    :return: Dictionary with the configs found in the parsed CLI arguments.\n    :rtype: dict"
  },
  {
    "code": "def restore(self, image):\n        if isinstance(image, Image):\n            image = image.id\n        return self.act(type='restore', image=image)",
    "docstring": "Restore the droplet to the specified backup image\n\n            A Droplet restoration will rebuild an image using a backup image.\n            The image ID that is passed in must be a backup of the current\n            Droplet instance.  The operation will leave any embedded SSH keys\n            intact. [APIDocs]_\n\n        :param image: an image ID, an image slug, or an `Image` object\n            representing a backup image of the droplet\n        :type image: integer, string, or `Image`\n        :return: an `Action` representing the in-progress operation on the\n            droplet\n        :rtype: Action\n        :raises DOAPIError: if the API endpoint replies with an error"
  },
  {
    "code": "def get_files_changed(repository, review_id):\n    repository.git.fetch([next(iter(repository.remotes)), review_id])\n    files_changed = repository.git.diff_tree([\"--no-commit-id\",\n                                              \"--name-only\",\n                                              \"-r\",\n                                              \"FETCH_HEAD\"]).splitlines()\n    print(\"Found {} files changed\".format(len(files_changed)))\n    return files_changed",
    "docstring": "Get a list of files changed compared to the given review.\n    Compares against current directory.\n\n    :param repository: Git repository. Used to get remote.\n      - By default uses first remote in list.\n    :param review_id: Gerrit review ID.\n    :return: List of file paths relative to current directory."
  },
  {
    "code": "def start_sequence():\n    print('getting started!...')\n    t = threading.Thread(target=my_application, kwargs=dict(api=api))\n    t.daemon = True\n    t.start()\n    return 'ok, starting webhook to: %s' % (ngrok_url,)",
    "docstring": "Start the demo sequence\n\n    We must start this thread in the same process as the webserver to be certain\n    we are sharing the api instance in memory.\n\n    (ideally in future the async id database will be capable of being more than\n    just a dictionary)"
  },
  {
    "code": "def get_style_defs(self, arg=''):\n        cp = self.commandprefix\n        styles = []\n        for name, definition in iteritems(self.cmd2def):\n            styles.append(r'\\expandafter\\def\\csname %s@tok@%s\\endcsname{%s}' %\n                          (cp, name, definition))\n        return STYLE_TEMPLATE % {'cp': self.commandprefix,\n                                 'styles': '\\n'.join(styles)}",
    "docstring": "Return the command sequences needed to define the commands\n        used to format text in the verbatim environment. ``arg`` is ignored."
  },
  {
    "code": "def from_protocol(proto):\n        cfg = TorConfig(control=proto)\n        yield cfg.post_bootstrap\n        defer.returnValue(cfg)",
    "docstring": "This creates and returns a ready-to-go TorConfig instance from the\n        given protocol, which should be an instance of\n        TorControlProtocol."
  },
  {
    "code": "def set_vertices(self, verts=None, indexed=None, reset_normals=True):\n        if indexed is None:\n            if verts is not None:\n                self._vertices = verts\n            self._vertices_indexed_by_faces = None\n        elif indexed == 'faces':\n            self._vertices = None\n            if verts is not None:\n                self._vertices_indexed_by_faces = verts\n        else:\n            raise Exception(\"Invalid indexing mode. Accepts: None, 'faces'\")\n        if reset_normals:\n            self.reset_normals()",
    "docstring": "Set the mesh vertices\n\n        Parameters\n        ----------\n        verts : ndarray | None\n            The array (Nv, 3) of vertex coordinates.\n        indexed : str | None\n            If indexed=='faces', then the data must have shape (Nf, 3, 3) and\n            is assumed to be already indexed as a list of faces. This will\n            cause any pre-existing normal vectors to be cleared unless\n            reset_normals=False.\n        reset_normals : bool\n            If True, reset the normals."
  },
  {
    "code": "def run(self):\n        LOGGER.info('%s v%s started', self.APPNAME, self.VERSION)\n        self.setup()\n        while not any([self.is_stopping, self.is_stopped]):\n            self.set_state(self.STATE_SLEEPING)\n            try:\n                signum = self.pending_signals.get(True, self.wake_interval)\n            except queue.Empty:\n                pass\n            else:\n                self.process_signal(signum)\n                if any([self.is_stopping, self.is_stopped]):\n                    break\n            self.set_state(self.STATE_ACTIVE)\n            self.process()",
    "docstring": "The core method for starting the application. Will setup logging,\n        toggle the runtime state flag, block on loop, then call shutdown.\n\n        Redefine this method if you intend to use an IO Loop or some other\n        long running process."
  },
  {
    "code": "def add_prefix(self, name, stmt):\n        if self.gg_level: return name\n        pref, colon, local = name.partition(\":\")\n        if colon:\n            return (self.module_prefixes[stmt.i_module.i_prefixes[pref][0]]\n                    + \":\" + local)\n        else:\n            return self.prefix_stack[-1] + \":\" + pref",
    "docstring": "Return `name` prepended with correct prefix.\n\n        If the name is already prefixed, the prefix may be translated\n        to the value obtained from `self.module_prefixes`.  Unmodified\n        `name` is returned if we are inside a global grouping."
  },
  {
    "code": "def _removeSegment(self, segment, preserveCurve, **kwargs):\n        segment = self.segments[segment]\n        for point in segment.points:\n            self.removePoint(point, preserveCurve)",
    "docstring": "segment will be a valid segment index.\n        preserveCurve will be a boolean.\n\n        Subclasses may override this method."
  },
  {
    "code": "def _add_rr(self, name, ttl, rd, deleting=None, section=None):\n        if section is None:\n            section = self.authority\n        covers = rd.covers()\n        rrset = self.find_rrset(section, name, self.zone_rdclass, rd.rdtype,\n                                covers, deleting, True, True)\n        rrset.add(rd, ttl)",
    "docstring": "Add a single RR to the update section."
  },
  {
    "code": "def parse_args():\n    parser = argparse.ArgumentParser(\n        description=\"Build a Sphinx documentation site for an EUPS stack, \"\n                    \"such as pipelines.lsst.io.\",\n        epilog=\"Version {0}\".format(__version__)\n    )\n    parser.add_argument(\n        '-d', '--dir',\n        dest='root_project_dir',\n        help=\"Root Sphinx project directory\")\n    parser.add_argument(\n        '-v', '--verbose',\n        dest='verbose',\n        action='store_true', default=False,\n        help='Enable Verbose output (debug level logging)'\n    )\n    return parser.parse_args()",
    "docstring": "Create an argument parser for the ``build-stack-docs`` program.\n\n    Returns\n    -------\n    args : `argparse.Namespace`\n        Parsed argument object."
  },
  {
    "code": "def _spawn_producer(f, port, addr='tcp://127.0.0.1'):\n    process = Process(target=_producer_wrapper, args=(f, port, addr))\n    process.start()\n    return process",
    "docstring": "Start a process that sends results on a PUSH socket.\n\n    Parameters\n    ----------\n    f : callable\n        Callable that takes a single argument, a handle\n        for a ZeroMQ PUSH socket. Must be picklable.\n\n    Returns\n    -------\n    process : multiprocessing.Process\n        The process handle of the created producer process."
  },
  {
    "code": "def parse_csv(file_path: str,\n              entrez_id_header,\n              log_fold_change_header,\n              adjusted_p_value_header,\n              entrez_delimiter,\n              base_mean_header=None,\n              sep=\",\") -> List[Gene]:\n    logger.info(\"In parse_csv()\")\n    df = pd.read_csv(file_path, sep=sep)\n    return handle_dataframe(\n        df,\n        entrez_id_name=entrez_id_header,\n        log2_fold_change_name=log_fold_change_header,\n        adjusted_p_value_name=adjusted_p_value_header,\n        entrez_delimiter=entrez_delimiter,\n        base_mean=base_mean_header,\n    )",
    "docstring": "Read a csv file on differential expression values as Gene objects.\n\n    :param str file_path: The path to the differential expression file to be parsed.\n    :param config.Params params: An object that includes paths, cutoffs and other information.\n    :return list: A list of Gene objects."
  },
  {
    "code": "def list_user_permissions(self, name):\n        return self._api_get('/api/users/{0}/permissions'.format(\n            urllib.parse.quote_plus(name)\n        ))",
    "docstring": "A list of all permissions for a given user.\n\n        :param name: The user's name\n        :type name: str"
  },
  {
    "code": "def FloatStringToFloat(float_string, problems=None):\n  match = re.match(r\"^[+-]?\\d+(\\.\\d+)?$\", float_string)\n  parsed_value = float(float_string)\n  if \"x\" in float_string:\n    raise ValueError()\n  if not match and problems is not None:\n    problems.InvalidFloatValue(float_string)\n  return parsed_value",
    "docstring": "Convert a float as a string to a float or raise an exception"
  },
  {
    "code": "def with_output(verbosity=1):\n    def make_wrapper(func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            configure_output(verbosity=verbosity)\n            return func(*args, **kwargs)\n        return wrapper\n    return make_wrapper",
    "docstring": "Decorator that configures output verbosity."
  },
  {
    "code": "def print_boards(hwpack='arduino', verbose=False):\n    if verbose:\n        pp(boards(hwpack))\n    else:\n        print('\\n'.join(board_names(hwpack)))",
    "docstring": "print boards from boards.txt."
  },
  {
    "code": "def section(title, element_list):\n    sect = {\n            'Type': 'Section',\n            'Title': title,\n            }\n    if isinstance(element_list, list):\n        sect['Elements'] = element_list\n    else:\n        sect['Elements'] = [element_list]\n    return sect",
    "docstring": "Returns a dictionary representing a new section.  Sections\n    contain a list of elements that are displayed separately from\n    the global elements on the page.\n\n    Args:\n        title: The title of the section to be displayed\n        element_list: The list of elements to display within the section\n\n    Returns:\n        A dictionary with metadata specifying that it is to be rendered as\n        a section containing multiple elements"
  },
  {
    "code": "def update_parent_directory_number(self, parent_dir_num):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('Path Table Record not yet initialized')\n        self.parent_directory_num = parent_dir_num",
    "docstring": "A method to update the parent directory number for this Path Table\n        Record from the directory record.\n\n        Parameters:\n         parent_dir_num - The new parent directory number to assign to this PTR.\n        Returns:\n         Nothing."
  },
  {
    "code": "def send_response(self, request, result=None, error=None):\n        message = self._version.create_response(request, result, error)\n        self.send_message(message)",
    "docstring": "Respond to a JSON-RPC method call.\n\n        This is a response to the message in *request*. If *error* is not\n        provided, then this is a succesful response, and the value in *result*,\n        which may be ``None``, is passed back to the client. if *error* is\n        provided and not ``None`` then an error is sent back. In this case\n        *error* must be a dictionary as specified by the JSON-RPC spec."
  },
  {
    "code": "def AddEnvironmentVariable(self, environment_variable):\n    name = environment_variable.name.upper()\n    if name in self._environment_variables:\n      raise KeyError('Environment variable: {0:s} already exists.'.format(\n          environment_variable.name))\n    self._environment_variables[name] = environment_variable",
    "docstring": "Adds an environment variable.\n\n    Args:\n      environment_variable (EnvironmentVariableArtifact): environment variable\n          artifact.\n\n    Raises:\n      KeyError: if the environment variable already exists."
  },
  {
    "code": "def gone_online(stream):\r\n    while True:\r\n        packet = yield from stream.get()\r\n        session_id = packet.get('session_key')\r\n        if session_id:\r\n            user_owner = get_user_from_session(session_id)\r\n            if user_owner:\r\n                logger.debug('User ' + user_owner.username + ' gone online')\r\n                online_opponents = list(filter(lambda x: x[1] == user_owner.username, ws_connections))\r\n                online_opponents_sockets = [ws_connections[i] for i in online_opponents]\r\n                yield from fanout_message(online_opponents_sockets,\r\n                                          {'type': 'gone-online', 'usernames': [user_owner.username]})\r\n            else:\r\n                pass\n        else:\r\n            pass",
    "docstring": "Distributes the users online status to everyone he has dialog with"
  },
  {
    "code": "def distributions_route(self, request):\n    tag = request.args.get('tag')\n    run = request.args.get('run')\n    try:\n      (body, mime_type) = self.distributions_impl(tag, run)\n      code = 200\n    except ValueError as e:\n      (body, mime_type) = (str(e), 'text/plain')\n      code = 400\n    return http_util.Respond(request, body, mime_type, code=code)",
    "docstring": "Given a tag and single run, return an array of compressed histograms."
  },
  {
    "code": "def _accumulate(self, old_accum, next_val):\n        return old_accum * (1 - self.alpha) + next_val * self.alpha",
    "docstring": "Implement exponential moving average"
  },
  {
    "code": "def get_module(app, modname, verbose=False, failfast=False):\n    module_name = '%s.%s' % (app, modname)\n    try:\n        module = import_module(module_name)\n    except ImportError as e:\n        if failfast:\n            raise e\n        elif verbose:\n            print(\"Could not load %r from %r: %s\" % (modname, app, e))\n        return None\n    if verbose:\n        print(\"Loaded %r from %r\" % (modname, app))\n    return module",
    "docstring": "Internal function to load a module from a single app.\n\n    taken from https://github.com/ojii/django-load."
  },
  {
    "code": "def isBirthday(self):\n        if not self.birthday:\n            return False\n        birthday = self.birthdate()\n        today = date.today()\n        return (birthday.month == today.month and\n                birthday.day == today.day)",
    "docstring": "Is it the user's birthday today?"
  },
  {
    "code": "def add_link(self):\n        \"Create a new internal link\"\n        n=len(self.links)+1\n        self.links[n]=(0,0)\n        return n",
    "docstring": "Create a new internal link"
  },
  {
    "code": "def wait(self, limit=None):\n        it = self.iterconsume(limit)\n        while True:\n            it.next()",
    "docstring": "Go into consume mode.\n\n        Mostly for testing purposes and simple programs, you probably\n        want :meth:`iterconsume` or :meth:`iterqueue` instead.\n\n        This runs an infinite loop, processing all incoming messages\n        using :meth:`receive` to apply the message to all registered\n        callbacks."
  },
  {
    "code": "def fetch_credential_report(self, credentials, ignore_exception = False):\n        iam_report = {}\n        try:\n            api_client = connect_service('iam', credentials, silent = True)\n            response = api_client.generate_credential_report()\n            if response['State'] != 'COMPLETE':\n                if not ignore_exception:\n                    printError('Failed to generate a credential report.')\n                return\n            report = api_client.get_credential_report()['Content']\n            lines = report.splitlines()\n            keys = lines[0].decode('utf-8').split(',')\n            for line in lines[1:]:\n                values = line.decode('utf-8').split(',')\n                manage_dictionary(iam_report, values[0], {})\n                for key, value in zip(keys, values):\n                    iam_report[values[0]][key] = value\n            self.credential_report = iam_report\n            self.fetchstatuslogger.counts['credential_report']['fetched'] = 1\n        except Exception as e:\n            if ignore_exception:\n                return\n            printError('Failed to download a credential report.')\n            printException(e)",
    "docstring": "Fetch the credential report\n\n        :param: api_client\n        :type: FOO\n        :param: ignore_exception : initiate credential report creation as not  always ready\n        :type: Boolean"
  },
  {
    "code": "def _handleDecodeHextileRAW(self, block, bg, color, x, y, width, height, tx, ty, tw, th):\n        self.updateRectangle(tx, ty, tw, th, block)\n        self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)",
    "docstring": "the tile is in raw encoding"
  },
  {
    "code": "def get_handler_classes(self):\n        handler_classes = [import_string(handler_cls) for handler_cls in settings.MODERNRPC_HANDLERS]\n        if self.protocol == ALL:\n            return handler_classes\n        else:\n            return [cls for cls in handler_classes if cls.protocol in ensure_sequence(self.protocol)]",
    "docstring": "Return the list of handlers to use when receiving RPC requests."
  },
  {
    "code": "def display(self) -> typing.Union[None, report.Report]:\n        return (\n            self._project.current_step.report\n            if self._project and self._project.current_step else\n            None\n        )",
    "docstring": "The display report for the current project."
  },
  {
    "code": "def elements_are_numbers(array):\n    if len(array) == 0: return 0\n    output_value = 1\n    for x in array:\n        test = is_a_number(x)\n        if not test: return False\n        output_value = max(output_value,test)\n    return output_value",
    "docstring": "Tests whether the elements of the supplied array are numbers."
  },
  {
    "code": "def write(\n        self, filepath, fully_qualified=True, pretty_print=False, encoding=\"UTF-8\"\n    ):\n        root = self.serialize(fully_qualified=fully_qualified)\n        tree = root.getroottree()\n        kwargs = {\"pretty_print\": pretty_print, \"encoding\": encoding}\n        if encoding != \"unicode\":\n            kwargs[\"xml_declaration\"] = True\n        tree.write(filepath, **kwargs)",
    "docstring": "Serialize and write this METS document to `filepath`.\n\n        The default encoding is ``UTF-8``. This method will return a unicode\n        string when ``encoding`` is set to ``unicode``.\n\n        :param str filepath: Path to write the METS document to"
  },
  {
    "code": "def leaky_relu(x, name=None):\n  with tf.name_scope(name, 'leaky_relu', [x]) as scope:\n    x = tf.convert_to_tensor(x, name='x')\n    return tf.where(tf.less(x, 0.0), 0.01 * x, x, name=scope)",
    "docstring": "Creates a leaky_relu.\n\n  This is an alternate non-linearity to relu. The leaky part of the relu may\n  prevent dead Neurons in a model since the gradient doesn't go completely to\n  0.\n\n  Args:\n    x: The input tensor.\n    name: Optional name for this op.\n  Returns:\n    x if x > 0 otherwise 0.01 * x."
  },
  {
    "code": "def ping(host=None, core_name=None):\n    ret = _get_return_dict()\n    if _get_none_or_value(core_name) is None and _check_for_cores():\n        success = True\n        for name in __opts__['solr.cores']:\n            resp = _get_admin_info('ping', host=host, core_name=name)\n            if resp['success']:\n                data = {name: {'status': resp['data']['status']}}\n            else:\n                success = False\n                data = {name: {'status': None}}\n            ret = _update_return_dict(ret, success, data, resp['errors'])\n        return ret\n    else:\n        resp = _get_admin_info('ping', host=host, core_name=core_name)\n        return resp",
    "docstring": "Does a health check on solr, makes sure solr can talk to the indexes.\n\n    host : str (None)\n        The solr host to query. __opts__['host'] is default.\n    core_name : str (None)\n        The name of the solr core if using cores. Leave this blank if you are\n        not using cores or if you want to check all cores.\n\n    Return : dict<str,obj>::\n\n        {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' solr.ping music"
  },
  {
    "code": "def add_instance(self,\n                    role,\n                    instance,\n                    username='root',\n                    key_filename=None,\n                    output_shell=False):\n        if not role in self.Instances.keys():\n            self.Instances[role] = []\n        self.logger.debug('Adding ' + role + ' with private_hostname ' +\n                          instance['private_hostname'] +\n                          ', public_hostname ' + instance['public_hostname'])\n        self.Instances[role].append(Connection(instance,\n                                               username,\n                                               key_filename,\n                                               output_shell=output_shell))",
    "docstring": "Add instance to the setup\n\n        @param role: instance's role\n        @type role: str\n\n        @param instance: host parameters we would like to establish connection\n                         to\n        @type instance: dict\n\n        @param username: user name for creating ssh connection\n        @type username: str\n\n        @param key_filename: file name with ssh private key\n        @type key_filename: str\n\n        @param output_shell: write output from this connection to standard\n                             output\n        @type output_shell: bool"
  },
  {
    "code": "def stop(self):\n        self.state = STATE_STOPPED\n        if self.transport:\n            self.transport.close()",
    "docstring": "Close websocket connection."
  },
  {
    "code": "def _remove_deprecated_options(self, old_version):\r\n        old_defaults = self._load_old_defaults(old_version)\r\n        for section in old_defaults.sections():\r\n            for option, _ in old_defaults.items(section, raw=self.raw):\r\n                if self.get_default(section, option) is NoDefault:\r\n                    try:\r\n                        self.remove_option(section, option)\r\n                        if len(self.items(section, raw=self.raw)) == 0:\r\n                            self.remove_section(section)\r\n                    except cp.NoSectionError:\r\n                        self.remove_section(section)",
    "docstring": "Remove options which are present in the .ini file but not in defaults"
  },
  {
    "code": "def entries(self, region, queue, tier, division):\n        url, query = LeagueApiV4Urls.entries(\n            region=region, queue=queue, tier=tier, division=division\n        )\n        return self._raw_request(self.entries.__name__, region, url, query)",
    "docstring": "Get all the league entries\n\n        :param string region:   the region to execute this request on\n        :param string queue:    the queue to query, i.e. RANKED_SOLO_5x5\n        :param string tier:     the tier to query, i.e. DIAMOND\n        :param string division: the division to query, i.e. III\n\n        :returns: Set[LeagueEntryDTO]"
  },
  {
    "code": "def _batch_call_watchers(self_):\n        while self_.self_or_cls.param._events:\n            event_dict = OrderedDict([((event.name, event.what), event)\n                                      for event in self_.self_or_cls.param._events])\n            watchers = self_.self_or_cls.param._watchers[:]\n            self_.self_or_cls.param._events = []\n            self_.self_or_cls.param._watchers = []\n            for watcher in watchers:\n                events = [self_._update_event_type(watcher, event_dict[(name, watcher.what)],\n                                                   self_.self_or_cls.param._TRIGGER)\n                          for name in watcher.parameter_names\n                          if (name, watcher.what) in event_dict]\n                with batch_watch(self_.self_or_cls, run=False):\n                    if watcher.mode == 'args':\n                        watcher.fn(*events)\n                    else:\n                        watcher.fn(**{c.name:c.new for c in events})",
    "docstring": "Batch call a set of watchers based on the parameter value\n        settings in kwargs using the queued Event and watcher objects."
  },
  {
    "code": "def _get_container_id(self, labels):\n        namespace = CadvisorPrometheusScraperMixin._get_container_label(labels, \"namespace\")\n        pod_name = CadvisorPrometheusScraperMixin._get_container_label(labels, \"pod_name\")\n        container_name = CadvisorPrometheusScraperMixin._get_container_label(labels, \"container_name\")\n        return self.pod_list_utils.get_cid_by_name_tuple((namespace, pod_name, container_name))",
    "docstring": "Should only be called on a container-scoped metric\n        It gets the container id from the podlist using the metrics labels\n\n        :param labels\n        :return str or None"
  },
  {
    "code": "def maybe_copy_file_to_directory(source_filepath, target_directory):\n  if not tf.gfile.Exists(target_directory):\n    tf.logging.info(\"Creating directory %s\" % target_directory)\n    os.mkdir(target_directory)\n  target_filepath = os.path.join(target_directory,\n                                 os.path.basename(source_filepath))\n  if not tf.gfile.Exists(target_filepath):\n    tf.logging.info(\"Copying %s to %s\" % (source_filepath, target_filepath))\n    tf.gfile.Copy(source_filepath, target_filepath)\n    statinfo = os.stat(target_filepath)\n    tf.logging.info(\"Successfully copied %s, %s bytes.\" % (target_filepath,\n                                                           statinfo.st_size))\n  else:\n    tf.logging.info(\"Not copying, file already found: %s\" % target_filepath)\n  return target_filepath",
    "docstring": "Copy a file to a directory if it is not already there.\n\n  Returns the target filepath.\n\n  Args:\n    source_filepath: a string\n    target_directory: a string\n\n  Returns:\n    a string"
  },
  {
    "code": "def get_sequence_rule_lookup_session_for_bank(self, bank_id, proxy):\n        if not self.supports_sequence_rule_lookup():\n            raise errors.Unimplemented()\n        return sessions.SequenceRuleLookupSession(bank_id, proxy, self._runtime)",
    "docstring": "Gets the ``OsidSession`` associated with the sequence rule lookup service for the given bank.\n\n        arg:    bank_id (osid.id.Id): the ``Id`` of the ``Bank``\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.assessment.authoring.SequenceRuleLookupSession) -\n                a ``SequenceRuleLookupSession``\n        raise:  NotFound - no ``Bank`` found by the given ``Id``\n        raise:  NullArgument - ``bank_id or proxy is null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_sequence_rule_lookup()`` or\n                ``supports_visible_federation()`` is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_sequence_rule_lookup()`` and\n        ``supports_visible_federation()`` are ``true``.*"
  },
  {
    "code": "def store_object(self, obj_name, data, content_type=None, etag=None,\n            content_encoding=None, ttl=None, return_none=False,\n            headers=None, extra_info=None):\n        return self.create(obj_name=obj_name, data=data,\n                content_type=content_type, etag=etag,\n                content_encoding=content_encoding, ttl=ttl,\n                return_none=return_none, headers=headers)",
    "docstring": "Creates a new object in this container, and populates it with the given\n        data. A StorageObject reference to the uploaded file will be returned,\n        unless 'return_none' is set to True.\n\n        The 'extra_info' parameter is included for backwards compatibility. It\n        is no longer used at all, and will not be modified with swiftclient\n        info, since swiftclient is not used any more."
  },
  {
    "code": "def discriminator2(ndf, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12):\n    BatchNorm = mx.sym.BatchNorm\n    data = mx.sym.Variable('data')\n    label = mx.sym.Variable('label')\n    d4 = mx.sym.Convolution(data, name='d4', kernel=(5,5), stride=(2,2), pad=(2,2), num_filter=ndf*8, no_bias=no_bias)\n    dbn4 = BatchNorm(d4, name='dbn4', fix_gamma=fix_gamma, eps=eps)\n    dact4 = mx.sym.LeakyReLU(dbn4, name='dact4', act_type='leaky', slope=0.2)\n    h = mx.sym.Flatten(dact4)\n    d5 = mx.sym.FullyConnected(h, num_hidden=1, name=\"d5\")\n    dloss = mx.sym.LogisticRegressionOutput(data=d5, label=label, name='dloss')\n    return dloss",
    "docstring": "Second part of the discriminator which takes a 256x8x8 feature map as input\n    and generates the loss based on whether the input image was a real one or fake one"
  },
  {
    "code": "def _decode(hashid, salt, alphabet, separators, guards):\n    parts = tuple(_split(hashid, guards))\n    hashid = parts[1] if 2 <= len(parts) <= 3 else parts[0]\n    if not hashid:\n        return\n    lottery_char = hashid[0]\n    hashid = hashid[1:]\n    hash_parts = _split(hashid, separators)\n    for part in hash_parts:\n        alphabet_salt = (lottery_char + salt + alphabet)[:len(alphabet)]\n        alphabet = _reorder(alphabet, alphabet_salt)\n        yield _unhash(part, alphabet)",
    "docstring": "Helper method that restores the values encoded in a hashid without\n    argument checks."
  },
  {
    "code": "def _get_webapi_requests(self):\n        headers = {\n            'Accept':\n            '*/*',\n            'Accept-Language':\n            'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4',\n            'Connection':\n            'keep-alive',\n            'Content-Type':\n            'application/x-www-form-urlencoded',\n            'Referer':\n            'http://music.163.com',\n            'Host':\n            'music.163.com',\n            'User-Agent':\n            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36'\n        }\n        NCloudBot.req.headers.update(headers)\n        return NCloudBot.req",
    "docstring": "Update headers of webapi for Requests."
  },
  {
    "code": "def get_model_indexes(model):\n    indexes = []\n    for index in get_index_names():\n        for app_model in get_index_models(index):\n            if app_model == model:\n                indexes.append(index)\n    return indexes",
    "docstring": "Return list of all indexes in which a model is configured.\n\n    A model may be configured to appear in multiple indexes. This function\n    will return the names of the indexes as a list of strings. This is\n    useful if you want to know which indexes need updating when a model\n    is saved.\n\n    Args:\n        model: a Django model class."
  },
  {
    "code": "def parse_cdhit_clstr_file(lines):\n    clusters = []\n    curr_cluster = []\n    for l in lines:\n        if l.startswith('>Cluster'):\n            if not curr_cluster:\n                continue\n            clusters.append(curr_cluster)\n            curr_cluster = []\n        else:\n            curr_cluster.append(clean_cluster_seq_id(l.split()[2]))\n    if curr_cluster:\n        clusters.append(curr_cluster)\n    return clusters",
    "docstring": "Returns a list of list of sequence ids representing clusters"
  },
  {
    "code": "def _split_list(cls, items, separator=\",\", last_separator=\" and \"):\n        if items is None:\n            return None\n        items = items.split(separator)\n        last_item = items[-1]\n        last_split = last_item.split(last_separator)\n        if len(last_split) > 1:\n            items[-1] = last_split[0]\n            items.append(last_split[1])\n        return [e.strip() for e in items]",
    "docstring": "Splits a string listing elements into an actual list.\n\n        Parameters\n        ----------\n        items: :class:`str`\n            A string listing elements.\n        separator: :class:`str`\n            The separator between each item. A comma by default.\n        last_separator: :class:`str`\n            The separator used for the last item. ' and ' by default.\n\n        Returns\n        -------\n        :class:`list` of :class:`str`\n            A list containing each one of the items."
  },
  {
    "code": "def volreg(dset,suffix='_volreg',base=3,tshift=3,dfile_suffix='_volreg.1D'):\n    cmd = ['3dvolreg','-prefix',nl.suffix(dset,suffix),'-base',base,'-dfile',nl.prefix(dset)+dfile_suffix]\n    if tshift:\n        cmd += ['-tshift',tshift]\n    cmd += [dset]\n    nl.run(cmd,products=nl.suffix(dset,suffix))",
    "docstring": "simple interface to 3dvolreg\n\n        :suffix:        suffix to add to ``dset`` for volreg'ed file\n        :base:          either a number or ``dset[#]`` of the base image to register to\n        :tshift:        if a number, then tshift ignoring that many images, if ``None``\n                        then don't tshift\n        :dfile_suffix:  suffix to add to ``dset`` to save the motion parameters to"
  },
  {
    "code": "def write(self, b):\n        self._checkClosed()\n        if isinstance(b, str):\n            raise TypeError(\"can't write str to binary stream\")\n        with self._write_lock:\n            self._write_buf.extend(b)\n            self._flush_unlocked()\n            return len(b)",
    "docstring": "Write bytes to buffer."
  },
  {
    "code": "def DeleteList(self, listName):\n        soap_request = soap('DeleteList')\n        soap_request.add_parameter('listName', listName)\n        self.last_request = str(soap_request)\n        response = self._session.post(url=self._url('Lists'),\n                                      headers=self._headers('DeleteList'),\n                                      data=str(soap_request),\n                                      verify=self._verify_ssl,\n                                      timeout=self.timeout)\n        if response == 200:\n            return response.text\n        else:\n            return response",
    "docstring": "Delete a List with given name"
  },
  {
    "code": "def search_mode_provides(self, product, pipeline='default'):\n        pipeline = self.pipelines[pipeline]\n        for obj, mode, field in self.iterate_mode_provides(self.modes, pipeline):\n            if obj.name() == product:\n                return ProductEntry(obj.name(), mode.key, field)\n        else:\n            raise ValueError('no mode provides %s' % product)",
    "docstring": "Search the mode that provides a given product"
  },
  {
    "code": "def group_envs(envlist):\n    groups = {}\n    for env in envlist:\n        envpy, category = env.split('-')[0:2]\n        if category == 'lint':\n            category = 'unit'\n        try:\n            groups[envpy, category].append(env)\n        except KeyError:\n            groups[envpy, category] = [env]\n    return sorted((envpy, category, envs) for (envpy, category), envs in groups.items())",
    "docstring": "Group Tox environments for Travis CI builds\n\n    Separate by Python version so that they can go in different Travis jobs:\n\n    >>> group_envs('py37-int-snappy', 'py36-int')\n    [('py36', 'int', ['py36-int']), ('py37', 'int', ['py37-int-snappy'])]\n\n    Group unit tests and linting together:\n\n    >>> group_envs(['py27-unit', 'py27-lint'])\n    [('py27', 'unit', ['py27-unit', 'py27-lint'])]"
  },
  {
    "code": "def _get_repr(obj, pretty=False, indent=1):\n        if pretty:\n            repr_value = pformat(obj, indent)\n        else:\n            repr_value = repr(obj)\n        if sys.version_info[0] == 2:\n            try:\n                repr_value = repr_value.decode('raw_unicode_escape')\n            except UnicodeError:\n                repr_value = repr_value.decode('utf-8', 'replace')\n        return repr_value",
    "docstring": "Get string representation of an object\n\n        :param obj: object\n        :type obj: object\n        :param pretty: use pretty formatting\n        :type pretty: bool\n        :param indent: indentation for pretty formatting\n        :type indent: int\n        :return: string representation\n        :rtype: str"
  },
  {
    "code": "def process_boolean(self, tag):\n        tag.set_address(self.normal_register.current_bit_address)\n        self.normal_register.move_to_next_bit_address()",
    "docstring": "Process Boolean type tags"
  },
  {
    "code": "def _output_work(self, work, root):\n        output_filename = os.path.join(self._output_dir, work)\n        tree = etree.ElementTree(root)\n        tree.write(output_filename, encoding='utf-8', pretty_print=True)",
    "docstring": "Saves the TEI XML document `root` at the path `work`."
  },
  {
    "code": "def run(self):\n        try:\n            self.proxy = config_ini.engine.open()\n            items = list(config_ini.engine.items(self.VIEWNAME, cache=False))\n            if self.sort_key:\n                items.sort(key=self.sort_key)\n            self._start(items)\n            self.LOG.debug(\"%s - %s\" % (config_ini.engine.engine_id, self.proxy))\n        except (error.LoggableError, xmlrpc.ERRORS) as exc:\n            self.LOG.debug(str(exc))",
    "docstring": "Queue manager job callback."
  },
  {
    "code": "def namespace(self):\n        self._ns = {\n            'db': self.store,\n            'store': store,\n            'autocommit': False,\n            }\n        return self._ns",
    "docstring": "Return a dictionary representing the namespace which should be\n        available to the user."
  },
  {
    "code": "def get_model_agents(self):\n        model_stmts = self.get_statements()\n        agents = []\n        for stmt in model_stmts:\n            for a in stmt.agent_list():\n                if a is not None:\n                    agents.append(a)\n        return agents",
    "docstring": "Return a list of all Agents from all Statements.\n\n        Returns\n        -------\n        agents : list[indra.statements.Agent]\n           A list of Agents that are in the model."
  },
  {
    "code": "def read(self, address, size):\n        value = 0x0\n        for i in range(0, size):\n            value |= self._read_byte(address + i) << (i * 8)\n        return value",
    "docstring": "Read arbitrary size content from memory."
  },
  {
    "code": "def open_sciobj_file_by_pid(pid, write=False):\n    abs_path = get_abs_sciobj_file_path_by_pid(pid)\n    if write:\n        d1_common.utils.filesystem.create_missing_directories_for_file(abs_path)\n    return open_sciobj_file_by_path(abs_path, write)",
    "docstring": "Open the file containing the Science Object bytes at the custom location\n    ``abs_path`` in the local filesystem for read."
  },
  {
    "code": "def get_parent_families(self, family_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.get_parent_catalogs(catalog_id=family_id)\n        return FamilyLookupSession(\n            self._proxy,\n            self._runtime).get_families_by_ids(\n                list(self.get_parent_family_ids(family_id)))",
    "docstring": "Gets the parent families of the given ``id``.\n\n        arg:    family_id (osid.id.Id): the ``Id`` of the ``Family`` to\n                query\n        return: (osid.relationship.FamilyList) - the parent families of\n                the ``id``\n        raise:  NotFound - a ``Family`` identified by ``Id is`` not\n                found\n        raise:  NullArgument - ``family_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def execute_return_success(cmd):\n    ret = _run_all(cmd)\n    if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n        msg = 'Command Failed: {0}\\n'.format(cmd)\n        msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n        msg += 'Output: {0}\\n'.format(ret['stdout'])\n        msg += 'Error: {0}\\n'.format(ret['stderr'])\n        raise CommandExecutionError(msg)\n    return True",
    "docstring": "Executes the passed command. Returns True if successful\n\n    :param str cmd: The command to run\n\n    :return: True if successful, otherwise False\n    :rtype: bool\n\n    :raises: Error if command fails or is not supported"
  },
  {
    "code": "def clone(self, klass=None, memo=None, **kwargs):\n        obj = Empty()\n        obj.__class__ = klass or self.__class__\n        obj.resource = self.resource\n        obj.filters = self.filters.copy()\n        obj.order_by = self.order_by\n        obj.low_mark = self.low_mark\n        obj.high_mark = self.high_mark\n        obj.__dict__.update(kwargs)\n        return obj",
    "docstring": "Creates a copy of the current instance. The 'kwargs' parameter can be\n        used by clients to update attributes after copying has taken place."
  },
  {
    "code": "def default(self, obj):\n        if isinstance(obj, Sensor):\n            return {\n                'sensor_id': obj.sensor_id,\n                'children': obj.children,\n                'type': obj.type,\n                'sketch_name': obj.sketch_name,\n                'sketch_version': obj.sketch_version,\n                'battery_level': obj.battery_level,\n                'protocol_version': obj.protocol_version,\n                'heartbeat': obj.heartbeat,\n            }\n        if isinstance(obj, ChildSensor):\n            return {\n                'id': obj.id,\n                'type': obj.type,\n                'description': obj.description,\n                'values': obj.values,\n            }\n        return json.JSONEncoder.default(self, obj)",
    "docstring": "Serialize obj into JSON."
  },
  {
    "code": "def get_assignable_bank_ids(self, bank_id):\n        mgr = self._get_provider_manager('ASSESSMENT', local=True)\n        lookup_session = mgr.get_bank_lookup_session(proxy=self._proxy)\n        banks = lookup_session.get_banks()\n        id_list = []\n        for bank in banks:\n            id_list.append(bank.get_id())\n        return IdList(id_list)",
    "docstring": "Gets a list of bank including and under the given bank node in which any assessment part can be assigned.\n\n        arg:    bank_id (osid.id.Id): the ``Id`` of the ``Bank``\n        return: (osid.id.IdList) - list of assignable bank ``Ids``\n        raise:  NullArgument - ``bank_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def track_exists(self, localdir):\n        path = glob.glob(self.gen_localdir(localdir) +\n                         self.gen_filename() + \"*\")\n        if len(path) > 0 and os.path.getsize(path[0]) > 0:\n            return True\n        return False",
    "docstring": "Check if track exists in local directory."
  },
  {
    "code": "def notify_listeners(self, msg_type, params):\n        for c in self.listeners:\n            c.notify(msg_type, params)",
    "docstring": "Send a message to all the observers."
  },
  {
    "code": "def parse_singular_alphabetic_character(t, tag_name):\n    pos = t.getElementsByTagName(tag_name)\n    assert(len(pos) == 1)\n    pos = pos[0]\n    assert(len(pos.childNodes) == 1)\n    v = pos.childNodes[0].data\n    assert(len(v) == 1 and v >= 'A' and 'v' <= 'z')\n    return v",
    "docstring": "Parses the sole alphabetic character value with name tag_name in tag t. Heavy-handed with the asserts."
  },
  {
    "code": "def decode_string(self, string, cache, as_map_key):\n        if is_cache_key(string):\n            return self.parse_string(cache.decode(string, as_map_key),\n                                     cache, as_map_key)\n        if is_cacheable(string, as_map_key):\n            cache.encode(string, as_map_key)\n        return self.parse_string(string, cache, as_map_key)",
    "docstring": "Decode a string - arguments follow the same convention as the\n        top-level 'decode' function."
  },
  {
    "code": "def _make_table_formatter(f, offset=None):\n  format = f\n  delta = offset\n  return lambda v: _resolve_table(v, format, delta)",
    "docstring": "A closure-izer for table arguments that include a format and possibly an offset."
  },
  {
    "code": "def animation_add(sequence_number, animation_id, name):\n        return MessageWriter().string(\"animation.add\").uint64(sequence_number).uint32(animation_id).string(name).get()",
    "docstring": "Create a animation.add message"
  },
  {
    "code": "def dchisq(psr,formbats=False,renormalize=True):\n    if formbats:\n        psr.formbats()\n    res, err = psr.residuals(removemean=False)[psr.deleted == 0], psr.toaerrs[psr.deleted == 0]\n    res -= numpy.sum(res/err**2) / numpy.sum(1/err**2)\n    M = psr.designmatrix(updatebats=False,fixunits=True,fixsigns=True)[psr.deleted==0,1:]\n    if renormalize:\n        norm = numpy.sqrt(numpy.sum(M**2,axis=0))\n        M /= norm\n    else:\n        norm = 1.0\n    dr = -2 * numpy.dot(M.T,res / (1e-12 * err**2)) * norm\n    return dr",
    "docstring": "Return gradient of total chisq for the current timing solution,\n    after removing noise-averaged mean residual, and ignoring deleted points."
  },
  {
    "code": "def positive_report(binary_report, sha256hash, project, patch_file):\n    failure = True\n    report_url = binary_report['permalink']\n    scan_date = binary_report['scan_date']\n    logger.error(\"Virus Found!\")\n    logger.info('File scan date for %s shows a infected status on: %s', patch_file, scan_date)\n    logger.info('Full report avaliable here: %s', report_url)",
    "docstring": "If a Positive match is found"
  },
  {
    "code": "def scroll_one_line_up(event):\n    w = find_window_for_buffer_name(event.cli, event.cli.current_buffer_name)\n    b = event.cli.current_buffer\n    if w:\n        if w.render_info:\n            info = w.render_info\n            if w.vertical_scroll > 0:\n                first_line_height = info.get_height_for_line(info.first_visible_line())\n                cursor_up = info.cursor_position.y - (info.window_height - 1 - first_line_height -\n                                                      info.configured_scroll_offsets.bottom)\n                for _ in range(max(0, cursor_up)):\n                    b.cursor_position += b.document.get_cursor_up_position()\n                w.vertical_scroll -= 1",
    "docstring": "scroll_offset -= 1"
  },
  {
    "code": "def ParseByteStream(\n      self, parser_mediator, byte_stream, parent_path_segments=None,\n      codepage='cp1252'):\n    if parent_path_segments and isinstance(parent_path_segments, list):\n      self._path_segments = list(parent_path_segments)\n    else:\n      self._path_segments = []\n    shell_item_list = pyfwsi.item_list()\n    parser_mediator.AppendToParserChain(self)\n    try:\n      shell_item_list.copy_from_byte_stream(\n          byte_stream, ascii_codepage=codepage)\n      for shell_item in iter(shell_item_list.items):\n        self._ParseShellItem(parser_mediator, shell_item)\n    finally:\n      parser_mediator.PopFromParserChain()",
    "docstring": "Parses the shell items from the byte stream.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      byte_stream (bytes): shell items data.\n      parent_path_segments (Optional[list[str]]): parent shell item path\n          segments.\n      codepage (Optional[str]): byte stream codepage."
  },
  {
    "code": "def _make_cmake(config_info):\n    configure_args = [\"-DCMAKE_EXPORT_COMPILE_COMMANDS=ON\"]\n    cmake_args = {}\n    options, option_fns = _make_all_options()\n    def _add_value(value, key):\n        args_key, args_value = _EX_ARG_FNS[key](value)\n        cmake_args[args_key] = args_value\n    devpipeline_core.toolsupport.args_builder(\n        \"cmake\",\n        config_info,\n        options,\n        lambda v, key: configure_args.extend(option_fns[key](v)),\n    )\n    devpipeline_core.toolsupport.args_builder(\n        \"cmake\", config_info, _EX_ARGS, _add_value\n    )\n    cmake = CMake(cmake_args, config_info, configure_args)\n    build_type = config_info.config.get(\"cmake.build_type\")\n    if build_type:\n        cmake.set_build_type(build_type)\n    return devpipeline_build.make_simple_builder(cmake, config_info)",
    "docstring": "This function initializes a CMake builder for building the project."
  },
  {
    "code": "def add_parent(self, id, pid, relation='subClassOf'):\n        g = self.get_graph()\n        g.add_edge(pid, id, pred=relation)",
    "docstring": "Add a new edge to the ontology"
  },
  {
    "code": "def fail_run_group(group, session):\n    from datetime import datetime\n    group.end = datetime.now()\n    group.status = 'failed'\n    session.commit()",
    "docstring": "End the run_group unsuccessfully.\n\n    Args:\n        group: The run_group we want to complete.\n        session: The database transaction we will finish."
  },
  {
    "code": "def _append_object(self, value, _file):\n        _labs = ' {'\n        _file.write(_labs)\n        self._tctr += 1\n        for (_item, _text) in value.items():\n            _tabs = '\\t' * self._tctr\n            _cmma = ',' if self._vctr[self._tctr] else ''\n            _keys = '{cmma}\\n{tabs}\"{item}\" :'.format(cmma=_cmma, tabs=_tabs, item=_item)\n            _file.write(_keys)\n            self._vctr[self._tctr] += 1\n            _text = self.object_hook(_text)\n            _type = type(_text).__name__\n            _MAGIC_TYPES[_type](self, _text, _file)\n        self._vctr[self._tctr] = 0\n        self._tctr -= 1\n        _tabs = '\\t' * self._tctr\n        _labs = '\\n{tabs}{}'.format('}', tabs=_tabs)\n        _file.write(_labs)",
    "docstring": "Call this function to write object contents.\n\n        Keyword arguments:\n            * value - dict, content to be dumped\n            * _file - FileIO, output file"
  },
  {
    "code": "def copy(self, existing_inputs):\n        return PPOPolicyGraph(\n            self.observation_space,\n            self.action_space,\n            self.config,\n            existing_inputs=existing_inputs)",
    "docstring": "Creates a copy of self using existing input placeholders."
  },
  {
    "code": "def _CompileProtos():\n  proto_files = []\n  for dir_path, _, filenames in os.walk(THIS_DIRECTORY):\n    for filename in filenames:\n      if filename.endswith(\".proto\"):\n        proto_files.append(os.path.join(dir_path, filename))\n  if not proto_files:\n    return\n  protoc_command = [\n      \"python\", \"-m\", \"grpc_tools.protoc\",\n      \"--python_out\", THIS_DIRECTORY,\n      \"--grpc_python_out\", THIS_DIRECTORY,\n      \"--proto_path\", THIS_DIRECTORY,\n  ]\n  protoc_command.extend(proto_files)\n  subprocess.check_output(protoc_command)",
    "docstring": "Compiles all Fleetspeak protos."
  },
  {
    "code": "def preprocess_tree(self, tree):\n        visitor = RinohTreePreprocessor(tree, self)\n        tree.walkabout(visitor)",
    "docstring": "Transform internal refuri targets in reference nodes to refids and\n        transform footnote rubrics so that they do not end up in the output"
  },
  {
    "code": "def force_ascii_values(data):\n    return {\n        k: v.encode('utf8').decode('ascii', 'backslashreplace')\n        for k, v in data.items()\n    }",
    "docstring": "Ensures each value is ascii-only"
  },
  {
    "code": "def clean_exit(signum, frame=None):\n    global exiting\n    if exiting:\n        LOG.debug('Exit in progress clean_exit received additional signal %s' % signum)\n        return\n    LOG.info('Received signal %s, beginning graceful shutdown.' % signum)\n    exiting = True\n    wait_for_exit = False\n    for process in processors:\n        try:\n            if process.is_alive():\n                process.terminate()\n                wait_for_exit = True\n        except Exception:\n            pass\n    if wait_for_exit:\n        time.sleep(2)\n    for child in multiprocessing.active_children():\n        LOG.debug('Killing pid %s' % child.pid)\n        try:\n            os.kill(child.pid, signal.SIGKILL)\n        except Exception:\n            pass\n    if signum == signal.SIGTERM:\n        sys.exit(0)\n    sys.exit(signum)",
    "docstring": "Exit all processes attempting to finish uncommitted active work before exit.\n         Can be called on an os signal or no zookeeper losing connection."
  },
  {
    "code": "def get_witnesses(self, name='*'):\n        for filepath in glob.glob(os.path.join(self._path, name, '*.txt')):\n            if os.path.isfile(filepath):\n                name = os.path.split(os.path.split(filepath)[0])[1]\n                siglum = os.path.splitext(os.path.basename(filepath))[0]\n                yield self.get_witness(name, siglum)",
    "docstring": "Returns a generator supplying `WitnessText` objects for each work\n        in the corpus.\n\n        :rtype: `generator` of `WitnessText`"
  },
  {
    "code": "def make_python_xref_nodes(py_typestr, state, hide_namespace=False):\n    if hide_namespace:\n        template = ':py:obj:`~{}`\\n'\n    else:\n        template = ':py:obj:`{}`\\n'\n    xref_text = template.format(py_typestr)\n    return parse_rst_content(xref_text, state)",
    "docstring": "Make docutils nodes containing a cross-reference to a Python object.\n\n    Parameters\n    ----------\n    py_typestr : `str`\n        Name of the Python object. For example\n        ``'mypackage.mymodule.MyClass'``. If you have the object itself, or\n        its type, use the `make_python_xref_nodes_for_type` function instead.\n    state : ``docutils.statemachine.State``\n        Usually the directive's ``state`` attribute.\n    hide_namespace : `bool`, optional\n        If `True`, the namespace of the object is hidden in the rendered\n        cross reference. Internally, this uses ``:py:obj:`~{py_obj}` (note\n        tilde).\n\n    Returns\n    -------\n    instance from ``docutils.nodes``\n        Docutils node representing the cross reference.\n\n    Examples\n    --------\n    If called from within a directive:\n\n    .. code-block:: python\n\n       make_python_xref_nodes('numpy.sin', self.state)\n\n    See also\n    --------\n    `make_python_xref_nodes_for_type`"
  },
  {
    "code": "def _new_from_rft(self, base_template, rft_file):\n        self._add_entry(base_template)\n        self._add_entry(templates.NEW_FROM_RFT\n                                 .format(rft_file_path=rft_file,\n                                         rft_file_name=op.basename(rft_file)))",
    "docstring": "Append a new file from .rft entry to the journal.\n\n        This instructs Revit to create a new model based on\n        the provided .rft template.\n\n        Args:\n            base_template (str): new file journal template from rmj.templates\n            rft_file (str): full path to .rft template to be used"
  },
  {
    "code": "def get_next(intersection, intersections, unused):\n    result = None\n    if is_first(intersection.interior_curve):\n        result = get_next_first(intersection, intersections)\n    elif is_second(intersection.interior_curve):\n        result = get_next_second(intersection, intersections)\n    elif intersection.interior_curve == CLASSIFICATION_T.COINCIDENT:\n        result = get_next_coincident(intersection, intersections)\n    else:\n        raise ValueError(\n            'Cannot get next node if not starting from \"FIRST\", '\n            '\"TANGENT_FIRST\", \"SECOND\", \"TANGENT_SECOND\" or \"COINCIDENT\".'\n        )\n    if result in unused:\n        unused.remove(result)\n    return result",
    "docstring": "Gets the next node along a given edge.\n\n    .. note::\n\n       This is a helper used only by :func:`basic_interior_combine`, which in\n       turn is only used by :func:`combine_intersections`. This function does\n       the majority of the heavy lifting for :func:`basic_interior_combine`.\n\n    .. note::\n\n        This function returns :class:`.Intersection` objects even\n        when the point isn't strictly an intersection. This is\n        \"incorrect\" in some sense, but for now, we don't bother\n        implementing a class similar to, but different from,\n        :class:`.Intersection` to satisfy this need.\n\n    Args:\n        intersection (.Intersection): The current intersection.\n        intersections (List[.Intersection]): List of all detected\n            intersections, provided as a reference for potential\n            points to arrive at.\n        unused (List[.Intersection]): List of nodes that haven't been\n            used yet in an intersection curved polygon\n\n    Returns:\n        .Intersection: The \"next\" point along a surface of intersection.\n        This will produce the next intersection along the current edge or\n        the end of the current edge.\n\n    Raises:\n        ValueError: If the intersection is not classified as\n            :attr:`~.IntersectionClassification.FIRST`,\n            :attr:`~.IntersectionClassification.TANGENT_FIRST`,\n            :attr:`~.IntersectionClassification.SECOND`,\n            :attr:`~.IntersectionClassification.TANGENT_SECOND` or\n            :attr:`~.IntersectionClassification.COINCIDENT`."
  },
  {
    "code": "def get_dos(self, partial_dos=False, npts_mu=10000, T=None):\n        spin = self.data.spin if isinstance(self.data.spin,int) else 1\n        energies, densities, vvdos, cdos = BL.BTPDOS(self.eband, self.vvband, npts=npts_mu)\n        if T is not None:\n            densities = BL.smoothen_DOS(energies, densities, T)\n        tdos = Dos(self.efermi / units.eV, energies / units.eV,\n                   {Spin(spin): densities})\n        if partial_dos:\n            tdos = self.get_partial_doses(tdos=tdos, npts_mu=npts_mu, T=T)\n        return tdos",
    "docstring": "Return a Dos object interpolating bands\n\n            Args:\n                partial_dos: if True, projections will be interpolated as well\n                    and partial doses will be return. Projections must be available\n                    in the loader.\n                npts_mu: number of energy points of the Dos\n                T: parameter used to smooth the Dos"
  },
  {
    "code": "def eval_field(field, asc):\n    if isinstance(field, dict):\n        if asc:\n            return field\n        else:\n            field = copy.deepcopy(field)\n            key = list(field.keys())[0]\n            field[key]['order'] = reverse_order(field[key]['order'])\n            return field\n    elif callable(field):\n        return field(asc)\n    else:\n        key, key_asc = parse_sort_field(field)\n        if not asc:\n            key_asc = not key_asc\n        return {key: {'order': 'asc' if key_asc else 'desc'}}",
    "docstring": "Evaluate a field for sorting purpose.\n\n    :param field: Field definition (string, dict or callable).\n    :param asc: ``True`` if order is ascending, ``False`` if descending.\n    :returns: Dictionary with the sort field query."
  },
  {
    "code": "def _ref_prop_matches(prop, target_classname, ref_classname,\n                          resultclass_names, role):\n        assert prop.type == 'reference'\n        if prop.reference_class.lower() == target_classname.lower():\n            if resultclass_names and ref_classname not in resultclass_names:\n                return False\n            if role and prop.name.lower() != role:\n                return False\n            return True\n        return False",
    "docstring": "Test filters for a reference property\n        Returns `True` if matches the criteria.\n\n        Returns `False` if it does not match.\n\n        The match criteria are:\n          - target_classname == prop_reference_class\n          - if result_classes are not None, ref_classname is in result_classes\n          - If role is not None, prop name matches role"
  },
  {
    "code": "def json(self, **kwargs):\n        encoding = detect_encoding(self.content[:4])\n        value = self.content.decode(encoding)\n        return simplejson.loads(value, **kwargs)",
    "docstring": "Decodes response as JSON."
  },
  {
    "code": "def GetEstimatedYear(self):\n    if self._preferred_year:\n      return self._preferred_year\n    if self._knowledge_base.year:\n      return self._knowledge_base.year\n    year = self._GetEarliestYearFromFileEntry()\n    if not year:\n      year = self._GetLatestYearFromFileEntry()\n    if not year:\n      year = timelib.GetCurrentYear()\n    return year",
    "docstring": "Retrieves an estimate of the year.\n\n    This function determines the year in the following manner:\n    * see if the user provided a preferred year;\n    * see if knowledge base defines a year e.g. derived from preprocessing;\n    * determine the year based on the file entry metadata;\n    * default to the current year;\n\n    Returns:\n      int: estimated year."
  },
  {
    "code": "def _validate_slice(self, start, end):\n        if start is None:\n            start = 0\n        elif start < 0:\n            start += self.len\n        if end is None:\n            end = self.len\n        elif end < 0:\n            end += self.len\n        if not 0 <= end <= self.len:\n            raise ValueError(\"end is not a valid position in the bitstring.\")\n        if not 0 <= start <= self.len:\n            raise ValueError(\"start is not a valid position in the bitstring.\")\n        if end < start:\n            raise ValueError(\"end must not be less than start.\")\n        return start, end",
    "docstring": "Validate start and end and return them as positive bit positions."
  },
  {
    "code": "def getaddress(self, address: str) -> dict:\n        return cast(dict, self.ext_fetch('getaddress/' + address))",
    "docstring": "Returns information for given address."
  },
  {
    "code": "def _run(self):\n        def get_next_interval():\n            start_time = time.time()\n            start = 0 if self.eager else 1\n            for count in itertools.count(start=start):\n                yield max(start_time + count * self.interval - time.time(), 0)\n        interval = get_next_interval()\n        sleep_time = next(interval)\n        while True:\n            with Timeout(sleep_time, exception=False):\n                self.should_stop.wait()\n                break\n            self.handle_timer_tick()\n            self.worker_complete.wait()\n            self.worker_complete.reset()\n            sleep_time = next(interval)",
    "docstring": "Runs the interval loop."
  },
  {
    "code": "def adjust_properties (self, prop_set):\n        assert isinstance(prop_set, property_set.PropertySet)\n        s = self.targets () [0].creating_subvariant ()\n        return prop_set.add_raw (s.implicit_includes ('include', 'H'))",
    "docstring": "For all virtual targets for the same dependency graph as self,\n            i.e. which belong to the same main target, add their directories\n            to include path."
  },
  {
    "code": "def _BuildEventData(self, record):\n    event_data = FseventsdEventData()\n    event_data.path = record.path\n    event_data.flags = record.event_flags\n    event_data.event_identifier = record.event_identifier\n    event_data.node_identifier = getattr(record, 'node_identifier', None)\n    return event_data",
    "docstring": "Builds an FseventsdData object from a parsed structure.\n\n    Args:\n      record (dls_record_v1|dls_record_v2): parsed record structure.\n\n    Returns:\n      FseventsdEventData: event data attribute container."
  },
  {
    "code": "def ListDevices(self):\n    devices = []\n    for obj in mockobject.objects.keys():\n        if obj.startswith('/org/bluez/') and 'dev_' in obj:\n            devices.append(dbus.ObjectPath(obj, variant_level=1))\n    return dbus.Array(devices, variant_level=1)",
    "docstring": "List all known devices"
  },
  {
    "code": "def get_value(self, merge=True, createfunc=None,\n                  expiration_time=None, ignore_expiration=False):\n        cache, cache_key = self._get_cache_plus_key()\n        assert not ignore_expiration or not createfunc, \\\n            \"Can't ignore expiration and also provide createfunc\"\n        if ignore_expiration or not createfunc:\n            cached_value = cache.get(cache_key,\n                                     expiration_time=expiration_time,\n                                     ignore_expiration=ignore_expiration)\n        else:\n            cached_value = cache.get(cache_key)\n            if not cached_value:\n                cached_value = createfunc()\n                cache.set(cache_key, cached_value, timeout=expiration_time)\n        if cached_value and merge:\n            cached_value = self.merge_result(cached_value, load=False)\n        return cached_value",
    "docstring": "Return the value from the cache for this query."
  },
  {
    "code": "def getXRDExpiration(xrd_element, default=None):\n    expires_element = xrd_element.find(expires_tag)\n    if expires_element is None:\n        return default\n    else:\n        expires_string = expires_element.text\n        expires_time = strptime(expires_string, \"%Y-%m-%dT%H:%M:%SZ\")\n        return datetime(*expires_time[0:6])",
    "docstring": "Return the expiration date of this XRD element, or None if no\n    expiration was specified.\n\n    @type xrd_element: ElementTree node\n\n    @param default: The value to use as the expiration if no\n        expiration was specified in the XRD.\n\n    @rtype: datetime.datetime\n\n    @raises ValueError: If the xrd:Expires element is present, but its\n        contents are not formatted according to the specification."
  },
  {
    "code": "def add_channel_pulse(dma_channel, gpio, start, width):\n    return _PWM.add_channel_pulse(dma_channel, gpio, start, width)",
    "docstring": "Add a pulse for a specific GPIO to a dma channel subcycle. `start` and\n    `width` are multiples of the pulse-width increment granularity."
  },
  {
    "code": "def time_slices_to_layers(graphs,\n                          interslice_weight=1,\n                          slice_attr='slice',\n                          vertex_id_attr='id',\n                          edge_type_attr='type',\n                          weight_attr='weight'):\n  G_slices = _ig.Graph.Tree(len(graphs), 1, mode=_ig.TREE_UNDIRECTED)\n  G_slices.es[weight_attr] = interslice_weight\n  G_slices.vs[slice_attr] = graphs\n  return slices_to_layers(G_slices,\n                          slice_attr,\n                          vertex_id_attr,\n                          edge_type_attr,\n                          weight_attr)",
    "docstring": "Convert time slices to layer graphs.\n\n  Each graph is considered to represent a time slice. This function simply\n  connects all the consecutive slices (i.e. the slice graph) with an\n  ``interslice_weight``.  The further conversion is then delegated to\n  :func:`slices_to_layers`, which also provides further details.\n\n  See Also\n  --------\n  :func:`find_partition_temporal`\n\n  :func:`slices_to_layers`"
  },
  {
    "code": "def impact_path(self, value):\n        self._impact_path = value\n        if value is None:\n            self.action_show_report.setEnabled(False)\n            self.action_show_log.setEnabled(False)\n            self.report_path = None\n            self.log_path = None\n        else:\n            self.action_show_report.setEnabled(True)\n            self.action_show_log.setEnabled(True)\n            self.log_path = '%s.log.html' % self.impact_path\n            self.report_path = '%s.report.html' % self.impact_path\n        self.save_report_to_html()\n        self.save_log_to_html()\n        self.show_report()",
    "docstring": "Setter to impact path.\n\n        :param value: The impact path.\n        :type value: str"
  },
  {
    "code": "def get_coordinate_offset(self, other_reading):\n        my_x, my_y = self.reference_source_point\n        other_x, other_y = other_reading.reference_source_point\n        return my_x - other_x, my_y - other_y",
    "docstring": "Calculates the offsets between readings' coordinate systems.\n\n        Args:\n          other_reading: ossos.astrom.SourceReading\n            The reading to compare coordinate systems with.\n\n        Returns:\n          (offset_x, offset_y):\n            The x and y offsets between this reading and the other reading's\n            coordinate systems."
  },
  {
    "code": "def dump(self):\n        logger.warn('This function is deprecated and replaced by `dump_np_vars`.')\n        ret = False\n        if self.system.files.no_output:\n            return True\n        if self.write_lst() and self.write_dat():\n            ret = True\n        return ret",
    "docstring": "Dump the TDS results to the output `dat` file\n\n        :return: succeed flag"
  },
  {
    "code": "def __parse_stream(self, stream, parse_line):\n        if not stream:\n            raise InvalidFormatError(cause='stream cannot be empty or None')\n        nline = 0\n        lines = stream.split('\\n')\n        for line in lines:\n            nline += 1\n            m = re.match(self.LINES_TO_IGNORE_REGEX, line, re.UNICODE)\n            if m:\n                continue\n            m = re.match(self.VALID_LINE_REGEX, line, re.UNICODE)\n            if not m:\n                cause = \"line %s: invalid format\" % str(nline)\n                raise InvalidFormatError(cause=cause)\n            try:\n                result = parse_line(m.group(1), m.group(2))\n                yield result\n            except InvalidFormatError as e:\n                cause = \"line %s: %s\" % (str(nline), e)\n                raise InvalidFormatError(cause=cause)",
    "docstring": "Generic method to parse gitdm streams"
  },
  {
    "code": "def _push_entry(self, key):\n        \"Push entry onto our access log, invalidate the old entry if exists.\"\n        self._invalidate_entry(key)\n        new_entry = AccessEntry(key)\n        self.access_lookup[key] = new_entry\n        self.access_log_lock.acquire()\n        self.access_log.appendleft(new_entry)\n        self.access_log_lock.release()",
    "docstring": "Push entry onto our access log, invalidate the old entry if exists."
  },
  {
    "code": "def delete_rows_csr(mat, indices):\n    if not isinstance(mat, scipy.sparse.csr_matrix):\n        raise ValueError(\"works only for CSR format -- use .tocsr() first\")\n    indices = list(indices)\n    mask = np.ones(mat.shape[0], dtype=bool)\n    mask[indices] = False\n    return mat[mask]",
    "docstring": "Remove the rows denoted by ``indices`` form the CSR sparse matrix ``mat``."
  },
  {
    "code": "def pagination_for(context, current_page, page_var=\"page\", exclude_vars=\"\"):\n    querystring = context[\"request\"].GET.copy()\n    exclude_vars = [v for v in exclude_vars.split(\",\") if v] + [page_var]\n    for exclude_var in exclude_vars:\n        if exclude_var in querystring:\n            del querystring[exclude_var]\n    querystring = querystring.urlencode()\n    return {\n        \"current_page\": current_page,\n        \"querystring\": querystring,\n        \"page_var\": page_var,\n    }",
    "docstring": "Include the pagination template and data for persisting querystring\n    in pagination links. Can also contain a comma separated string of\n    var names in the current querystring to exclude from the pagination\n    links, via the ``exclude_vars`` arg."
  },
  {
    "code": "def matches_input(self, optimized_str):\n        if all([keyword in optimized_str for keyword in self['keywords']]):\n            logger.debug('Matched template %s', self['template_name'])\n            return True",
    "docstring": "See if string matches keywords set in template file"
  },
  {
    "code": "def model_to_objective(self, x_model):\n        idx_model = 0\n        x_objective = []\n        for idx_obj in range(self.objective_dimensionality):\n            variable = self.space_expanded[idx_obj]\n            new_entry = variable.model_to_objective(x_model, idx_model)\n            x_objective += new_entry\n            idx_model += variable.dimensionality_in_model\n        return x_objective",
    "docstring": "This function serves as interface between model input vectors and\n            objective input vectors"
  },
  {
    "code": "def create_random_string(length=7, chars='ABCDEFGHJKMNPQRSTUVWXYZ23456789',\n                         repetitions=False):\n    if repetitions:\n        return ''.join(random.choice(chars) for _ in range(length))\n    return ''.join(random.sample(chars, length))",
    "docstring": "Returns a random string, based on the provided arguments.\n\n    It returns capital letters and numbers by default.\n    Ambiguous characters are left out, repetitions will be avoided."
  },
  {
    "code": "def get_sid_string(principal):\n    if principal is None:\n        principal = 'NULL SID'\n    try:\n        return win32security.ConvertSidToStringSid(principal)\n    except TypeError:\n        principal = get_sid(principal)\n    try:\n        return win32security.ConvertSidToStringSid(principal)\n    except pywintypes.error:\n        log.exception('Invalid principal %s', principal)\n        raise CommandExecutionError('Invalid principal {0}'.format(principal))",
    "docstring": "Converts a PySID object to a string SID.\n\n    Args:\n\n        principal(str):\n            The principal to lookup the sid. Must be a PySID object.\n\n    Returns:\n        str: A string sid\n\n    Usage:\n\n    .. code-block:: python\n\n        # Get a PySID object\n        py_sid = salt.utils.win_dacl.get_sid('jsnuffy')\n\n        # Get the string version of the SID\n        salt.utils.win_dacl.get_sid_string(py_sid)"
  },
  {
    "code": "def check_cew(cls):\n        if gf.can_run_c_extension(\"cew\"):\n            gf.print_success(u\"aeneas.cew     AVAILABLE\")\n            return False\n        gf.print_warning(u\"aeneas.cew     NOT AVAILABLE\")\n        gf.print_info(u\"  You can still run aeneas but it will be a bit slower\")\n        gf.print_info(u\"  Please refer to the installation documentation for details\")\n        return True",
    "docstring": "Check whether Python C extension ``cew`` can be imported.\n\n        Return ``True`` on failure and ``False`` on success.\n\n        :rtype: bool"
  },
  {
    "code": "def check_serial_port(name):\n    try:\n        cdc = next(serial.tools.list_ports.grep(name))\n        return cdc[0]\n    except StopIteration:\n        msg = \"device {} not found. \".format(name)\n        msg += \"available devices are: \"\n        ports = list(serial.tools.list_ports.comports())\n        for p in ports:\n            msg += \"{},\".format(text_type(p))\n        raise ValueError(msg)",
    "docstring": "returns valid COM Port."
  },
  {
    "code": "def comments_for(context, obj):\n    form_class = import_dotted_path(settings.COMMENT_FORM_CLASS)\n    form = form_class(context[\"request\"], obj)\n    context_form = context.get(\"posted_comment_form\", form)\n    context.update({\n        'posted_comment_form':\n            context_form if context_form.target_object == obj else form,\n        'unposted_comment_form': form,\n        'comment_url': reverse(\"comment\"),\n        'object_for_comments': obj,\n    })\n    return context",
    "docstring": "Provides a generic context variable name for the object that\n    comments are being rendered for."
  },
  {
    "code": "def linearize_data_types(self):\n        linearized_data_types = []\n        seen_data_types = set()\n        def add_data_type(data_type):\n            if data_type in seen_data_types:\n                return\n            elif data_type.namespace != self:\n                return\n            if is_composite_type(data_type) and data_type.parent_type:\n                add_data_type(data_type.parent_type)\n            linearized_data_types.append(data_type)\n            seen_data_types.add(data_type)\n        for data_type in self.data_types:\n            add_data_type(data_type)\n        return linearized_data_types",
    "docstring": "Returns a list of all data types used in the namespace. Because the\n        inheritance of data types can be modeled as a DAG, the list will be a\n        linearization of the DAG. It's ideal to generate data types in this\n        order so that composite types that reference other composite types are\n        defined in the correct order."
  },
  {
    "code": "def _stop(self):\n        engine = self.current_engine()\n        if \"vm\" in self._controller.computes:\n            yield from self._controller.delete_compute(\"vm\")\n        if engine.running:\n            log.info(\"Stop the GNS3 VM\")\n            yield from engine.stop()",
    "docstring": "Stop the GNS3 VM"
  },
  {
    "code": "def create_new_csv(samples, args):\n    out_fn = os.path.splitext(args.csv)[0] + \"-merged.csv\"\n    logger.info(\"Preparing new csv: %s\" % out_fn)\n    with file_transaction(out_fn) as tx_out:\n        with open(tx_out, 'w') as handle:\n            handle.write(_header(args.csv))\n            for s in samples:\n                sample_name = s['name'] if isinstance(s['out_file'], list) else os.path.basename(s['out_file'])\n                handle.write(\"%s,%s,%s\\n\" % (sample_name, s['name'], \",\".join(s['anno'])))",
    "docstring": "create csv file that can be use with bcbio -w template"
  },
  {
    "code": "def update_cost_model(self, x, cost_x):\n        if self.cost_type == 'evaluation_time':\n            cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T)\n            if self.num_updates == 0:\n                X_all = x\n                costs_all = cost_evals\n            else:\n                X_all = np.vstack((self.cost_model.model.X,x))\n                costs_all = np.vstack((self.cost_model.model.Y,cost_evals))\n            self.num_updates += 1\n            self.cost_model.updateModel(X_all, costs_all, None, None)",
    "docstring": "Updates the GP used to handle the cost.\n\n        param x: input of the GP for the cost model.\n        param x_cost: values of the time cost at the input locations."
  },
  {
    "code": "def get_class(view_model_name):\n    from . import models; models\n    from .plotting import Figure; Figure\n    d = MetaModel.model_class_reverse_map\n    if view_model_name in d:\n        return d[view_model_name]\n    else:\n        raise KeyError(\"View model name '%s' not found\" % view_model_name)",
    "docstring": "Look up a Bokeh model class, given its view model name.\n\n    Args:\n        view_model_name (str) :\n            A view model name for a Bokeh model to look up\n\n    Returns:\n        Model: the model class corresponding to ``view_model_name``\n\n    Raises:\n        KeyError, if the model cannot be found\n\n    Example:\n\n        .. code-block:: python\n\n            >>> from bokeh.model import get_class\n            >>> get_class(\"Range1d\")\n            <class 'bokeh.models.ranges.Range1d'>"
  },
  {
    "code": "def write_config(cfg):\n    cfg_path = '/usr/local/etc/freelan'\n    cfg_file = 'freelan_TEST.cfg'\n    cfg_lines = []\n    if not isinstance(cfg, FreelanCFG):\n        if not isinstance(cfg, (list, tuple)):\n            print(\"Freelan write input can not be processed.\")\n            return\n        cfg_lines = cfg\n    else:\n        cfg_lines = cfg.build()\n    if not os.path.isdir(cfg_path):\n        print(\"Can not find default freelan config directory.\")\n        return\n    cfg_file_path = os.path.join(cfg_path,cfg_file)\n    if os.path.isfile( cfg_file_path ):\n        print(\"freelan config file already exists - moving to not replace content.\")\n        ts = time.time()\n        backup_file = cfg_file_path+'.ORG-'+datetime.datetime.fromtimestamp(ts).strftime('%y-%m-%d-%H-%M-%S')\n        shutil.move(cfg_file_path, backup_file)\n    cfg_lines = [cfg_line+'\\n' for cfg_line in cfg_lines]\n    with open(cfg_file_path, 'w') as cfg_f:\n        cfg_f.writelines(cfg_lines)",
    "docstring": "try writing config file to a default directory"
  },
  {
    "code": "def pick_action_todo():\n    for ndx, todo in enumerate(things_to_do):\n        if roll_dice(todo[\"chance\"]):\n            cur_act = actions[get_action_by_name(todo[\"name\"])]\n            if todo[\"WHERE_COL\"] == \"energy\" and my_char[\"energy\"] > todo[\"WHERE_VAL\"]:\n                return cur_act\n            if todo[\"WHERE_COL\"] == \"gold\" and my_char[\"gold\"] > todo[\"WHERE_VAL\"]:\n                return cur_act\n    return actions[3]",
    "docstring": "only for testing and AI - user will usually choose an action\n    Sort of works"
  },
  {
    "code": "def transformByDistance(wV, subModel, alphabetSize=4):\n    nc = [0.0]*alphabetSize\n    for i in xrange(0, alphabetSize):\n        j = wV[i]\n        k = subModel[i]\n        for l in xrange(0, alphabetSize):\n            nc[l] += j * k[l]\n    return nc",
    "docstring": "transform wV by given substitution matrix"
  },
  {
    "code": "def intersect(self, other):\n        intersection = Rect()\n        if lib.SDL_IntersectRect(self._ptr, self._ptr, intersection._ptr):\n            return intersection\n        else:\n            return None",
    "docstring": "Calculate the intersection of this rectangle and another rectangle.\n\n        Args:\n            other (Rect): The other rectangle.\n\n        Returns:\n            Rect: The intersection of this rectangle and the given other rectangle, or None if there is no such\n                intersection."
  },
  {
    "code": "def get_branch(self, i):\n        branch = MerkleBranch(self.order)\n        j = i + 2 ** self.order - 1\n        for k in range(0, self.order):\n            if (self.is_left(j)):\n                branch.set_row(k, (self.nodes[j], self.nodes[j + 1]))\n            else:\n                branch.set_row(k, (self.nodes[j - 1], self.nodes[j]))\n            j = MerkleTree.get_parent(j)\n        return branch",
    "docstring": "Gets a branch associated with leaf i.  This will trace the tree\n        from the leaves down to the root, constructing a list of tuples that\n        represent the pairs of nodes all the way from leaf i to the root.\n\n        :param i: the leaf identifying the branch to retrieve"
  },
  {
    "code": "def _output_dir(\n        self,\n        ext,\n        is_instance=False,\n        interpolatable=False,\n        autohinted=False,\n        is_variable=False,\n    ):\n        assert not (is_variable and any([is_instance, interpolatable]))\n        if is_variable:\n            dir_prefix = \"variable_\"\n        elif is_instance:\n            dir_prefix = \"instance_\"\n        else:\n            dir_prefix = \"master_\"\n        dir_suffix = \"_interpolatable\" if interpolatable else \"\"\n        output_dir = dir_prefix + ext + dir_suffix\n        if autohinted:\n            output_dir = os.path.join(\"autohinted\", output_dir)\n        return output_dir",
    "docstring": "Generate an output directory.\n\n            Args:\n                ext: extension string.\n                is_instance: The output is instance font or not.\n                interpolatable: The output is interpolatable or not.\n                autohinted: The output is autohinted or not.\n                is_variable: The output is variable font or not.\n            Return:\n                output directory string."
  },
  {
    "code": "def inverse_transform(self, maps):\n        out = {}\n        m1 = maps[parameters.mass1]\n        m2 = maps[parameters.mass2]\n        out[parameters.mchirp] = conversions.mchirp_from_mass1_mass2(m1, m2)\n        out[parameters.q] = m1 / m2\n        return self.format_output(maps, out)",
    "docstring": "This function transforms from component masses to chirp mass and\n        mass ratio.\n\n        Parameters\n        ----------\n        maps : a mapping object\n\n        Examples\n        --------\n        Convert a dict of numpy.array:\n\n        >>> import numpy\n        >>> from pycbc import transforms\n        >>> t = transforms.MchirpQToMass1Mass2()\n        >>> t.inverse_transform({'mass1': numpy.array([16.4]), 'mass2': numpy.array([8.2])})\n            {'mass1': array([ 16.4]), 'mass2': array([ 8.2]),\n             'mchirp': array([ 9.97717521]), 'q': 2.0}\n\n        Returns\n        -------\n        out : dict\n            A dict with key as parameter name and value as numpy.array or float\n            of transformed values."
  },
  {
    "code": "def mount_iso_image(self, image, image_name, ins_file_name):\n        query_parms_str = '?image-name={}&ins-file-name={}'. \\\n            format(quote(image_name, safe=''), quote(ins_file_name, safe=''))\n        self.manager.session.post(\n            self.uri + '/operations/mount-iso-image' + query_parms_str,\n            body=image)",
    "docstring": "Upload an ISO image and associate it to this Partition\n        using the HMC operation 'Mount ISO Image'.\n\n        When the partition already has an ISO image associated,\n        the newly uploaded image replaces the current one.\n\n        Authorization requirements:\n\n        * Object-access permission to this Partition.\n        * Task permission to the \"Partition Details\" task.\n\n        Parameters:\n\n          image (:term:`byte string` or file-like object):\n            The content of the ISO image.\n\n            Images larger than 2GB cannot be specified as a Byte string; they\n            must be specified as a file-like object.\n\n            File-like objects must have opened the file in binary mode.\n\n          image_name (:term:`string`): The displayable name of the image.\n\n            This value must be a valid Linux file name without directories,\n            must not contain blanks, and must end with '.iso' in lower case.\n\n            This value will be shown in the 'boot-iso-image-name' property of\n            this partition.\n\n          ins_file_name (:term:`string`): The path name of the INS file within\n            the file system of the ISO image.\n\n            This value will be shown in the 'boot-iso-ins-file' property of\n            this partition.\n\n        Raises:\n\n          :exc:`~zhmcclient.HTTPError`\n          :exc:`~zhmcclient.ParseError`\n          :exc:`~zhmcclient.AuthError`\n          :exc:`~zhmcclient.ConnectionError`"
  },
  {
    "code": "def getsystemhooks(self, page=1, per_page=20):\n        data = {'page': page, 'per_page': per_page}\n        request = requests.get(\n            self.hook_url, params=data, headers=self.headers,\n            verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)\n        if request.status_code == 200:\n            return request.json()\n        else:\n            return False",
    "docstring": "Get all system hooks\n\n        :param page: Page number\n        :param per_page: Records per page\n        :return: list of hooks"
  },
  {
    "code": "def fragment(self, message):\n        if message.message_type in [Types.CALL_RES,\n                                    Types.CALL_REQ,\n                                    Types.CALL_REQ_CONTINUE,\n                                    Types.CALL_RES_CONTINUE]:\n            rw = RW[message.message_type]\n            payload_space = (common.MAX_PAYLOAD_SIZE -\n                             rw.length_no_args(message))\n            fragment_msg = message.fragment(payload_space)\n            self.generate_checksum(message)\n            yield message\n            while fragment_msg is not None:\n                message = fragment_msg\n                rw = RW[message.message_type]\n                payload_space = (common.MAX_PAYLOAD_SIZE -\n                                 rw.length_no_args(message))\n                fragment_msg = message.fragment(payload_space)\n                self.generate_checksum(message)\n                yield message\n        else:\n            yield message",
    "docstring": "Fragment message based on max payload size\n\n        note: if the message doesn't need to fragment,\n        it will return a list which only contains original\n        message itself.\n\n        :param message: raw message\n        :return: list of messages whose sizes <= max\n            payload size"
  },
  {
    "code": "def net_recv(ws, conn):\n    in_data = conn.recv(RECEIVE_BYTES)\n    if not in_data:\n        print('Received 0 bytes (connection closed)')\n        ws.receive_data(None)\n    else:\n        print('Received {} bytes'.format(len(in_data)))\n        ws.receive_data(in_data)",
    "docstring": "Read pending data from network into websocket."
  },
  {
    "code": "def decode(self, integers):\n    integers = list(np.squeeze(integers))\n    return self.encoders[\"inputs\"].decode(integers)",
    "docstring": "List of ints to str."
  },
  {
    "code": "def reset(self):\n        logger.debug('StackInABox({0}): Resetting...'\n                     .format(self.__id))\n        for k, v in six.iteritems(self.services):\n            matcher, service = v\n            logger.debug('StackInABox({0}): Resetting Service {1}'\n                         .format(self.__id, service.name))\n            service.reset()\n        self.services = {}\n        self.holds = {}\n        logger.debug('StackInABox({0}): Reset Complete'\n                     .format(self.__id))",
    "docstring": "Reset StackInABox to a like-new state."
  },
  {
    "code": "def _get_opt(config, key, option, opt_type):\n    for opt_key in [option, option.replace('-', '_')]:\n        if not config.has_option(key, opt_key):\n            continue\n        if opt_type == bool:\n            return config.getbool(key, opt_key)\n        if opt_type == int:\n            return config.getint(key, opt_key)\n        if opt_type == str:\n            return config.get(key, opt_key)\n        if opt_type == list:\n            return _parse_list_opt(config.get(key, opt_key))\n        raise ValueError(\"Unknown option type: %s\" % opt_type)",
    "docstring": "Get an option from a configparser with the given type."
  },
  {
    "code": "def swap_across(idx, idy, mat_a, mat_r, perm):\n    size = mat_a.shape[0]\n    perm_new = numpy.eye(size, dtype=int)\n    perm_row = 1.0*perm[:, idx]\n    perm[:, idx] = perm[:, idy]\n    perm[:, idy] = perm_row\n    row_p = 1.0 * perm_new[idx]\n    perm_new[idx] = perm_new[idy]\n    perm_new[idy] = row_p\n    mat_a = numpy.dot(perm_new, numpy.dot(mat_a, perm_new))\n    mat_r = numpy.dot(mat_r, perm_new)\n    return mat_a, mat_r, perm",
    "docstring": "Interchange row and column idy and idx."
  },
  {
    "code": "def xgettext(self, template):\n        cmd = 'xgettext -d django -L Python --keyword=gettext_noop \\\n            --keyword=gettext_lazy --keyword=ngettext_lazy:1,2 --from-code=UTF-8 \\\n            --output=- -'\n        p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,\n            stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n        (msg, err) = p.communicate(input=templatize(template))\n        if err:\n            logging.warning(err)\n        if XGETTEXT_REENCODES_UTF8:\n            return msg.decode('utf-8').encode('iso-8859-1')\n        return msg",
    "docstring": "Extracts to be translated strings from template and turns it into po format."
  },
  {
    "code": "def create(self, query, **kwargs):\n        if kwargs.get(\"exec_mode\", None) == \"oneshot\":\n            raise TypeError(\"Cannot specify exec_mode=oneshot; use the oneshot method instead.\")\n        response = self.post(search=query, **kwargs)\n        sid = _load_sid(response)\n        return Job(self.service, sid)",
    "docstring": "Creates a search using a search query and any additional parameters\n        you provide.\n\n        :param query: The search query.\n        :type query: ``string``\n        :param kwargs: Additiona parameters (optional). For a list of available\n            parameters, see `Search job parameters\n            <http://dev.splunk.com/view/SP-CAAAEE5#searchjobparams>`_\n            on Splunk Developer Portal.\n        :type kwargs: ``dict``\n\n        :return: The :class:`Job`."
  },
  {
    "code": "def FxTools(self):\n        pi = self.pi\n        si = self.si\n        if self.vc_ver <= 10.0:\n            include32 = True\n            include64 = not pi.target_is_x86() and not pi.current_is_x86()\n        else:\n            include32 = pi.target_is_x86() or pi.current_is_x86()\n            include64 = pi.current_cpu == 'amd64' or pi.target_cpu == 'amd64'\n        tools = []\n        if include32:\n            tools += [os.path.join(si.FrameworkDir32, ver)\n                      for ver in si.FrameworkVersion32]\n        if include64:\n            tools += [os.path.join(si.FrameworkDir64, ver)\n                      for ver in si.FrameworkVersion64]\n        return tools",
    "docstring": "Microsoft .NET Framework Tools"
  },
  {
    "code": "def angular_distance_fast(ra1, dec1, ra2, dec2):\n    lon1 = np.deg2rad(ra1)\n    lat1 = np.deg2rad(dec1)\n    lon2 = np.deg2rad(ra2)\n    lat2 = np.deg2rad(dec2)\n    dlon = lon2 - lon1\n    dlat = lat2 - lat1\n    a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon /2.0)**2\n    c = 2 * np.arcsin(np.sqrt(a))\n    return np.rad2deg(c)",
    "docstring": "Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at\n    their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for\n    antipodes.\n\n    :param lon1:\n    :param lat1:\n    :param lon2:\n    :param lat2:\n    :return:"
  },
  {
    "code": "def computeNormals(self):\n        poly = self.polydata(False)\n        pnormals = poly.GetPointData().GetNormals()\n        cnormals = poly.GetCellData().GetNormals()\n        if pnormals and cnormals:\n            return self\n        pdnorm = vtk.vtkPolyDataNormals()\n        pdnorm.SetInputData(poly)\n        pdnorm.ComputePointNormalsOn()\n        pdnorm.ComputeCellNormalsOn()\n        pdnorm.FlipNormalsOff()\n        pdnorm.ConsistencyOn()\n        pdnorm.Update()\n        return self.updateMesh(pdnorm.GetOutput())",
    "docstring": "Compute cell and vertex normals for the actor's mesh.\n\n        .. warning:: Mesh gets modified, can have a different nr. of vertices."
  },
  {
    "code": "def get_panels(self):\n        all_panels = []\n        panel_groups = self.get_panel_groups()\n        for panel_group in panel_groups.values():\n            all_panels.extend(panel_group)\n        return all_panels",
    "docstring": "Returns the Panel instances registered with this dashboard in order.\n\n        Panel grouping information is not included."
  },
  {
    "code": "def add_album_art(file_name, album_art):\n    img = requests.get(album_art, stream=True)\n    img = img.raw\n    audio = EasyMP3(file_name, ID3=ID3)\n    try:\n        audio.add_tags()\n    except _util.error:\n        pass\n    audio.tags.add(\n        APIC(\n            encoding=3,\n            mime='image/png',\n            type=3,\n            desc='Cover',\n            data=img.read()\n        )\n    )\n    audio.save()\n    return album_art",
    "docstring": "Add album_art in .mp3's tags"
  },
  {
    "code": "def send(self, message):\n        for event in message.events:\n            self.events.append(event)\n        reply = riemann_client.riemann_pb2.Msg()\n        reply.ok = True\n        return reply",
    "docstring": "Adds a message to the list, returning a fake 'ok' response\n\n        :returns: A response message with ``ok = True``"
  },
  {
    "code": "def paused_partitions(self):\n        return set(partition for partition in self.assignment\n                   if self.is_paused(partition))",
    "docstring": "Return current set of paused TopicPartitions."
  },
  {
    "code": "def gnpool(name, start, room, lenout=_default_len_out):\n    name = stypes.stringToCharP(name)\n    start = ctypes.c_int(start)\n    kvars = stypes.emptyCharArray(yLen=room, xLen=lenout)\n    room = ctypes.c_int(room)\n    lenout = ctypes.c_int(lenout)\n    n = ctypes.c_int()\n    found = ctypes.c_int()\n    libspice.gnpool_c(name, start, room, lenout, ctypes.byref(n), kvars,\n                      ctypes.byref(found))\n    return stypes.cVectorToPython(kvars)[0:n.value], bool(found.value)",
    "docstring": "Return names of kernel variables matching a specified template.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gnpool_c.html\n\n    :param name: Template that names should match.\n    :type name: str\n    :param start: Index of first matching name to retrieve.\n    :type start: int\n    :param room: The largest number of values to return.\n    :type room: int\n    :param lenout: Length of strings in output array kvars.\n    :type lenout: int\n    :return: Kernel pool variables whose names match name.\n    :rtype: list of str"
  },
  {
    "code": "def command(self):\n        print('pynYNAB OFX import')\n        args = self.parser.parse_args()\n        verify_common_args(args)\n        client = clientfromkwargs(**args)\n        delta = do_ofximport(args.file, client)\n        client.push(expected_delta=delta)",
    "docstring": "Manually import an OFX into a nYNAB budget"
  },
  {
    "code": "def handle(self, object, *args, **kw):\n    if not bool(self):\n      if not self.spec or self.spec == SPEC_ALL:\n        raise ValueError('No plugins available in group %r' % (self.group,))\n      raise ValueError(\n        'No plugins in group %r matched %r' % (self.group, self.spec))\n    for plugin in self.plugins:\n      object = plugin.handle(object, *args, **kw)\n    return object",
    "docstring": "Calls each plugin in this PluginSet with the specified object,\n    arguments, and keywords in the standard group plugin order. The\n    return value from each successive invoked plugin is passed as the\n    first parameter to the next plugin. The final return value is the\n    object returned from the last plugin.\n\n    If this plugin set is empty (i.e. no plugins exist or matched the\n    spec), then a ValueError exception is thrown."
  },
  {
    "code": "def load_fn_matches_ext(file_path, file_type):\n    correct_ext = False\n    curr_ext = os.path.splitext(file_path)[1]\n    exts = [curr_ext, file_type]\n    try:\n        if \".xlsx\" in exts and \".xls\" in exts:\n            correct_ext = True\n        elif curr_ext == file_type:\n            correct_ext = True\n        else:\n            print(\"Use '{}' to load this file: {}\".format(FILE_TYPE_MAP[curr_ext][\"load_fn\"],\n                                                          os.path.basename(file_path)))\n    except Exception as e:\n        logger_misc.debug(\"load_fn_matches_ext: {}\".format(e))\n    return correct_ext",
    "docstring": "Check that the file extension matches the target extension given.\n\n    :param str file_path: Path to be checked\n    :param str file_type: Target extension\n    :return bool correct_ext: Extension match or does not match"
  },
  {
    "code": "def _isdictclass(obj):\n    c = getattr(obj, '__class__', None)\n    return c and c.__name__ in _dict_classes.get(c.__module__, ())",
    "docstring": "Return True for known dict objects."
  },
  {
    "code": "def make_float(s, default='', ignore_commas=True):\n    r\n    if ignore_commas and isinstance(s, basestring):\n        s = s.replace(',', '')\n    try:\n        return float(s)\n    except (IndexError, ValueError, AttributeError, TypeError):\n        try:\n            return float(str(s))\n        except ValueError:\n            try:\n                return float(normalize_scientific_notation(str(s), ignore_commas))\n            except ValueError:\n                try:\n                    return float(first_digits(s))\n                except ValueError:\n                    return default",
    "docstring": "r\"\"\"Coerce a string into a float\n\n    >>> make_float('12,345')\n    12345.0\n    >>> make_float('12.345')\n    12.345\n    >>> make_float('1+2')\n    3.0\n    >>> make_float('+42.0')\n    42.0\n    >>> make_float('\\r\\n-42?\\r\\n')\n    -42.0\n    >>> make_float('$42.42')\n    42.42\n    >>> make_float('B-52')\n    -52.0\n    >>> make_float('1.2 x 10^34')\n    1.2e+34\n    >>> make_float(float('nan'))\n    nan\n    >>> make_float(float('-INF'))\n    -inf"
  },
  {
    "code": "def clone_schema(self, base_schema_name, new_schema_name):\n        connection.set_schema_to_public()\n        cursor = connection.cursor()\n        try:\n            cursor.execute(\"SELECT 'clone_schema'::regproc\")\n        except ProgrammingError:\n            self._create_clone_schema_function()\n            transaction.commit()\n        sql = 'SELECT clone_schema(%(base_schema)s, %(new_schema)s, TRUE)'\n        cursor.execute(\n            sql,\n            {'base_schema': base_schema_name, 'new_schema': new_schema_name}\n        )\n        cursor.close()",
    "docstring": "Creates a new schema `new_schema_name` as a clone of an existing schema\n        `old_schema_name`."
  },
  {
    "code": "def prepare_notebook_context(request, notebook_context):\n    if not notebook_context:\n        notebook_context = {}\n    if \"extra_template_paths\" not in notebook_context:\n        notebook_context[\"extra_template_paths\"] = [os.path.join(os.path.dirname(__file__), \"server\", \"templates\")]\n    assert type(notebook_context[\"extra_template_paths\"]) == list, \"Got bad extra_template_paths {}\".format(notebook_context[\"extra_template_paths\"])\n    notebook_context[\"jinja_environment_options\"] = notebook_context.get(\"jinja_environment_options\", {})\n    assert type(notebook_context[\"jinja_environment_options\"]) == dict\n    notebook_context[\"allow_origin\"] = route_to_alt_domain(request, request.host_url)\n    notebook_context[\"notebook_path\"] = request.route_path(\"notebook_proxy\", remainder=\"\")\n    if \"context_hash\" not in notebook_context:\n        notebook_context[\"context_hash\"] = make_dict_hash(notebook_context)\n    print(notebook_context)",
    "docstring": "Fill in notebook context with default values."
  },
  {
    "code": "def transform(self, fseries, **kwargs):\n        weight = 1 + numpy.log10(self.qrange[1]/self.qrange[0]) / numpy.sqrt(2)\n        nind, nplanes, peak, result = (0, 0, 0, None)\n        for plane in self:\n            nplanes += 1\n            nind += sum([1 + row.ntiles * row.deltam for row in plane])\n            result = plane.transform(fseries, **kwargs)\n            if result.peak['energy'] > peak:\n                out = result\n                peak = out.peak['energy']\n        return (out, nind * weight / nplanes)",
    "docstring": "Compute the time-frequency plane at fixed Q with the most\n        significant tile\n\n        Parameters\n        ----------\n        fseries : `~gwpy.timeseries.FrequencySeries`\n            the complex FFT of a time-series data set\n\n        **kwargs\n            other keyword arguments to pass to `QPlane.transform`\n\n        Returns\n        -------\n        out : `QGram`\n            signal energies over the time-frequency plane containing the most\n            significant tile\n\n        N : `int`\n            estimated number of statistically independent tiles\n\n        See Also\n        --------\n        QPlane.transform\n            compute the Q-transform over a single time-frequency plane"
  },
  {
    "code": "def delete_by_ids(self, ids):\n        ids = utils.coerce_to_list(ids)\n        uri = \"/%s?ids=%s\" % (self.uri_base, \",\".join(ids))\n        return self.api.method_delete(uri)",
    "docstring": "Deletes the messages whose IDs are passed in from this queue."
  },
  {
    "code": "def has_duplicate_keys(config_data, base_conf, raise_error):\n    duplicate_keys = set(base_conf) & set(config_data)\n    if not duplicate_keys:\n        return\n    msg = \"Duplicate keys in config: %s\" % duplicate_keys\n    if raise_error:\n        raise errors.ConfigurationError(msg)\n    log.info(msg)\n    return True",
    "docstring": "Compare two dictionaries for duplicate keys. if raise_error is True\n    then raise on exception, otherwise log return True."
  },
  {
    "code": "def maybe_obj(str_or_obj):\n    if not isinstance(str_or_obj, six.string_types):\n        return str_or_obj\n    parts = str_or_obj.split(\".\")\n    mod, modname = None, None\n    for p in parts:\n        modname = p if modname is None else \"%s.%s\" % (modname, p)\n        try:\n            mod = __import__(modname)\n        except ImportError:\n            if mod is None:\n                raise\n            break\n    obj = mod\n    for p in parts[1:]:\n        obj = getattr(obj, p)\n    return obj",
    "docstring": "If argument is not a string, return it.\n\n    Otherwise import the dotted name and return that."
  },
  {
    "code": "def signature(array):\n    length = len(array)\n    index = _NUM_SIGNATURE_BYTES if length > _NUM_SIGNATURE_BYTES else length\n    return array[:index]",
    "docstring": "Returns the first 262 bytes of the given bytearray\n    as part of the file header signature.\n\n    Args:\n        array: bytearray to extract the header signature.\n\n    Returns:\n        First 262 bytes of the file content as bytearray type."
  },
  {
    "code": "def IPID_count(lst, funcID=lambda x: x[1].id, funcpres=lambda x: x[1].summary()):\n    idlst = [funcID(e) for e in lst]\n    idlst.sort()\n    classes = [idlst[0]]\n    classes += [t[1] for t in zip(idlst[:-1], idlst[1:]) if abs(t[0] - t[1]) > 50]\n    lst = [(funcID(x), funcpres(x)) for x in lst]\n    lst.sort()\n    print(\"Probably %i classes:\" % len(classes), classes)\n    for id, pr in lst:\n        print(\"%5i\" % id, pr)",
    "docstring": "Identify IP id values classes in a list of packets\n\nlst:      a list of packets\nfuncID:   a function that returns IP id values\nfuncpres: a function used to summarize packets"
  },
  {
    "code": "def _transform_to_dict(result):\n        result_dict = {}\n        property_list = result.item\n        for item in property_list:\n            result_dict[item.key[0]] = item.value[0]\n        return result_dict",
    "docstring": "Transform the array from Ideone into a Python dictionary."
  },
  {
    "code": "def _create_dictionary_of_marshall(\n            self,\n            marshallQuery,\n            marshallTable):\n        self.log.debug(\n            'starting the ``_create_dictionary_of_marshall`` method')\n        dictList = []\n        tableName = self.dbTableName\n        rows = readquery(\n            log=self.log,\n            sqlQuery=marshallQuery,\n            dbConn=self.pmDbConn,\n            quiet=False\n        )\n        totalCount = len(rows)\n        count = 0\n        for row in rows:\n            if \"dateCreated\" in row:\n                del row[\"dateCreated\"]\n            count += 1\n            if count > 1:\n                sys.stdout.write(\"\\x1b[1A\\x1b[2K\")\n            print \"%(count)s / %(totalCount)s `%(tableName)s` data added to memory\" % locals()\n            dictList.append(dict(row))\n        self.log.debug(\n            'completed the ``_create_dictionary_of_marshall`` method')\n        return dictList",
    "docstring": "create a list of dictionaries containing all the rows in the marshall stream\n\n        **Key Arguments:**\n            - ``marshallQuery`` -- the query used to lift the required data from the marshall database.\n            - ``marshallTable`` -- the name of the marshall table we are lifting the data from.\n\n        **Return:**\n            - ``dictList`` - a list of dictionaries containing all the rows in the marshall stream"
  },
  {
    "code": "def CompileFilter(self, filter_expression):\n    filter_parser = pfilter.BaseParser(filter_expression).Parse()\n    matcher = filter_parser.Compile(pfilter.PlasoAttributeFilterImplementation)\n    self._filter_expression = filter_expression\n    self._matcher = matcher",
    "docstring": "Compiles the filter expression.\n\n    The filter expression contains an object filter expression.\n\n    Args:\n      filter_expression (str): filter expression.\n\n    Raises:\n      ParseError: if the filter expression cannot be parsed."
  },
  {
    "code": "def add_rollback_panels(self):\r\n        from wagtailplus.utils.edit_handlers import add_panel_to_edit_handler\r\n        from wagtailplus.wagtailrollbacks.edit_handlers import HistoryPanel\r\n        for model in self.applicable_models:\r\n            add_panel_to_edit_handler(model, HistoryPanel, _(u'History'))",
    "docstring": "Adds rollback panel to applicable model class's edit handlers."
  },
  {
    "code": "def vb_stop_vm(name=None, timeout=10000, **kwargs):\n    vbox = vb_get_box()\n    machine = vbox.findMachine(name)\n    log.info('Stopping machine %s', name)\n    session = _virtualboxManager.openMachineSession(machine)\n    try:\n        console = session.console\n        progress = console.powerDown()\n        progress.waitForCompletion(timeout)\n    finally:\n        _virtualboxManager.closeMachineSession(session)\n        vb_wait_for_session_state(session)\n    log.info('Stopped machine %s is now %s', name, vb_machinestate_to_str(machine.state))\n    return vb_xpcom_to_attribute_dict(machine, 'IMachine')",
    "docstring": "Tells Virtualbox to stop a VM.\n    This is a blocking function!\n\n    @param name:\n    @type name: str\n    @param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely\n    @type timeout: int\n    @return untreated dict of stopped VM"
  },
  {
    "code": "def RemoveClass(self, class_name):\n    if class_name not in self._class_mapping:\n      raise problems.NonexistentMapping(class_name)\n    del self._class_mapping[class_name]",
    "docstring": "Removes an entry from the list of known classes.\n\n    Args:\n        class_name: A string with the class name that is to be removed.\n    Raises:\n        NonexistentMapping if there is no class with the specified class_name."
  },
  {
    "code": "def path(*components):\n    _path = os.path.join(*components)\n    _path = os.path.expanduser(_path)\n    return _path",
    "docstring": "Get a file path.\n\n    Concatenate all components into a path."
  },
  {
    "code": "def _get_vswitch_name(self, network_type, physical_network):\n        if network_type != constants.TYPE_LOCAL:\n            vswitch_name = self._get_vswitch_for_physical_network(\n                physical_network)\n        else:\n            vswitch_name = self._local_network_vswitch\n        if vswitch_name:\n            return vswitch_name\n        err_msg = _(\"No vSwitch configured for physical network \"\n                    \"'%(physical_network)s'. Neutron network type: \"\n                    \"'%(network_type)s'.\")\n        raise exception.NetworkingHyperVException(\n            err_msg % dict(physical_network=physical_network,\n                           network_type=network_type))",
    "docstring": "Get the vswitch name for the received network information."
  },
  {
    "code": "def DeviceReadThread(hid_device):\n  hid_device.run_loop_ref = cf.CFRunLoopGetCurrent()\n  if not hid_device.run_loop_ref:\n    logger.error('Failed to get current run loop')\n    return\n  iokit.IOHIDDeviceScheduleWithRunLoop(hid_device.device_handle,\n                                       hid_device.run_loop_ref,\n                                       K_CF_RUNLOOP_DEFAULT_MODE)\n  run_loop_run_result = K_CF_RUN_LOOP_RUN_TIMED_OUT\n  while (run_loop_run_result == K_CF_RUN_LOOP_RUN_TIMED_OUT or\n         run_loop_run_result == K_CF_RUN_LOOP_RUN_HANDLED_SOURCE):\n    run_loop_run_result = cf.CFRunLoopRunInMode(\n        K_CF_RUNLOOP_DEFAULT_MODE,\n        1000,\n        False)\n  if run_loop_run_result != K_CF_RUN_LOOP_RUN_STOPPED:\n    logger.error('Unexpected run loop exit code: %d', run_loop_run_result)\n  iokit.IOHIDDeviceUnscheduleFromRunLoop(hid_device.device_handle,\n                                         hid_device.run_loop_ref,\n                                         K_CF_RUNLOOP_DEFAULT_MODE)",
    "docstring": "Binds a device to the thread's run loop, then starts the run loop.\n\n  Args:\n    hid_device: The MacOsHidDevice object\n\n  The HID manager requires a run loop to handle Report reads. This thread\n  function serves that purpose."
  },
  {
    "code": "def _score_clusters(self, X, y=None):\n        stype = self.scoring.lower()\n        if stype == \"membership\":\n            return np.bincount(self.estimator.labels_)\n        raise YellowbrickValueError(\"unknown scoring method '{}'\".format(stype))",
    "docstring": "Determines the \"scores\" of the cluster, the metric that determines the\n        size of the cluster visualized on the visualization."
  },
  {
    "code": "def extract_declarations(map_el, dirs, scale=1, user_styles=[]):\n    styles = []\n    for stylesheet in map_el.findall('Stylesheet'):\n        map_el.remove(stylesheet)\n        content, mss_href = fetch_embedded_or_remote_src(stylesheet, dirs)\n        if content:\n            styles.append((content, mss_href))\n    for stylesheet in user_styles:\n        mss_href = urljoin(dirs.source.rstrip('/')+'/', stylesheet)\n        content = urllib.urlopen(mss_href).read().decode(DEFAULT_ENCODING)\n        styles.append((content, mss_href))\n    declarations = []\n    for (content, mss_href) in styles:\n        is_merc = is_merc_projection(map_el.get('srs',''))\n        for declaration in stylesheet_declarations(content, is_merc, scale):\n            uri_value = declaration.value.value\n            if uri_value.__class__ is uri:\n                uri_value.address = urljoin(mss_href, uri_value.address)\n            declarations.append(declaration)\n    return declarations",
    "docstring": "Given a Map element and directories object, remove and return a complete\n        list of style declarations from any Stylesheet elements found within."
  },
  {
    "code": "def up(force=True, env=None, **kwargs):\n    \"Starts a new experiment\"\n    inventory = os.path.join(os.getcwd(), \"hosts\")\n    conf = Configuration.from_dictionnary(provider_conf)\n    provider = Enos_vagrant(conf)\n    roles, networks = provider.init()\n    check_networks(roles, networks)\n    env[\"roles\"] = roles\n    env[\"networks\"] = networks",
    "docstring": "Starts a new experiment"
  },
  {
    "code": "def create_bare(self):\n        self.instances = []\n        for ip in self.settings['NODES']:\n            new_instance = Instance.new(settings=self.settings, cluster=self)\n            new_instance.ip = ip\n            self.instances.append(new_instance)",
    "docstring": "Create instances for the Bare provider"
  },
  {
    "code": "def getNamedActionValue(self, name):\n        actions = self._actions\n        if (type (actions) is list):\n            for a in actions:\n                if a.get('name', 'NoValue') == name:\n                    dict =a\n        else:\n            dict = actions\n        return dict.get('value', 'NoValue')",
    "docstring": "Get the value of the named Tropo action."
  },
  {
    "code": "def clean(self):\n        if self.pst_arg is None:\n            self.logger.statement(\"linear_analysis.clean(): not pst object\")\n            return\n        if not self.pst.estimation and self.pst.nprior > 0:\n            self.drop_prior_information()",
    "docstring": "drop regularization and prior information observation from the jco"
  },
  {
    "code": "def check_str(obj):\n        if isinstance(obj, str):\n            return obj\n        if isinstance(obj, float):\n            return str(int(obj))\n        else:\n            return str(obj)",
    "docstring": "Returns a string for various input types"
  },
  {
    "code": "def from_internal(self, attribute_profile, internal_dict):\n        external_dict = {}\n        for internal_attribute_name in internal_dict:\n            try:\n                attribute_mapping = self.from_internal_attributes[internal_attribute_name]\n            except KeyError:\n                logger.debug(\"no attribute mapping found for the internal attribute '%s'\", internal_attribute_name)\n                continue\n            if attribute_profile not in attribute_mapping:\n                logger.debug(\"no mapping found for '%s' in attribute profile '%s'\" %\n                             (internal_attribute_name,\n                             attribute_profile))\n                continue\n            external_attribute_names = self.from_internal_attributes[internal_attribute_name][attribute_profile]\n            external_attribute_name = external_attribute_names[0]\n            logger.debug(\"frontend attribute %s mapped from %s\" % (external_attribute_name,\n                                                                   internal_attribute_name))\n            if self.separator in external_attribute_name:\n                nested_attribute_names = external_attribute_name.split(self.separator)\n                nested_dict = self._create_nested_attribute_value(nested_attribute_names[1:],\n                                                                  internal_dict[internal_attribute_name])\n                external_dict[nested_attribute_names[0]] = nested_dict\n            else:\n                external_dict[external_attribute_name] = internal_dict[internal_attribute_name]\n        return external_dict",
    "docstring": "Converts the internal data to \"type\"\n\n        :type attribute_profile: str\n        :type internal_dict: dict[str, str]\n        :rtype: dict[str, str]\n\n        :param attribute_profile: To which external type to convert (ex: oidc, saml, ...)\n        :param internal_dict: attributes to map\n        :return: attribute values and names in the specified \"profile\""
  },
  {
    "code": "def to_python(self, value):\n        value = super(TimeZoneField, self).to_python(value)\n        if not value:\n            return value\n        try:\n            return pytz.timezone(str(value))\n        except pytz.UnknownTimeZoneError:\n            raise ValidationError(\n                message=self.error_messages['invalid'],\n                code='invalid',\n                params={'value': value}\n            )",
    "docstring": "Returns a datetime.tzinfo instance for the value."
  },
  {
    "code": "def __cond_from_desc(desc):\n    for code, [condition, detailed, exact, exact_nl] in __BRCONDITIONS.items():\n        if exact_nl == desc:\n            return {CONDCODE: code,\n                    CONDITION: condition,\n                    DETAILED: detailed,\n                    EXACT: exact,\n                    EXACTNL: exact_nl\n                    }\n    return None",
    "docstring": "Get the condition name from the condition description."
  },
  {
    "code": "def safe_kill(pid, signum):\n  assert(isinstance(pid, IntegerForPid))\n  assert(isinstance(signum, int))\n  try:\n    os.kill(pid, signum)\n  except (IOError, OSError) as e:\n    if e.errno in [errno.ESRCH, errno.EPERM]:\n      pass\n    elif e.errno == errno.EINVAL:\n      raise ValueError(\"Invalid signal number {}: {}\"\n                       .format(signum, e),\n                       e)\n    else:\n      raise",
    "docstring": "Kill a process with the specified signal, catching nonfatal errors."
  },
  {
    "code": "def _on_event(self, event):\n        if self.has_option(event):\n            on_event = self.get_option(event).upper()\n            if on_event not in [\"NO ACTION\", \"RESTRICT\"]:\n                return on_event\n        return False",
    "docstring": "Returns the referential action for a given database operation\n        on the referenced table the foreign key constraint is associated with.\n\n        :param event: Name of the database operation/event to return the referential action for.\n        :type event: str\n\n        :rtype: str or None"
  },
  {
    "code": "def retrieve_diaspora_host_meta(host):\n    document, code, exception = fetch_document(host=host, path=\"/.well-known/host-meta\")\n    if exception:\n        return None\n    xrd = XRD.parse_xrd(document)\n    return xrd",
    "docstring": "Retrieve a remote Diaspora host-meta document.\n\n    :arg host: Host to retrieve from\n    :returns: ``XRD`` instance"
  },
  {
    "code": "def devices(self):\n\t\tresponse = self._call(\n\t\t\tmc_calls.DeviceManagementInfo\n\t\t)\n\t\tregistered_devices = response.body.get('data', {}).get('items', [])\n\t\treturn registered_devices",
    "docstring": "Get a listing of devices registered to the Google Music account."
  },
  {
    "code": "def download_previews(self, savedir=None):\n        for obsid in self.obsids:\n            pm = io.PathManager(obsid.img_id, savedir=savedir)\n            pm.basepath.mkdir(exist_ok=True)\n            basename = Path(obsid.medium_img_url).name\n            print(\"Downloading\", basename)\n            urlretrieve(obsid.medium_img_url, str(pm.basepath / basename))",
    "docstring": "Download preview files for the previously found and stored Opus obsids.\n\n        Parameters\n        ==========\n        savedir: str or pathlib.Path, optional\n            If the database root folder as defined by the config.ini should not be used,\n            provide a different savedir here. It will be handed to PathManager."
  },
  {
    "code": "def loss_l2(self, l2=0):\n        if isinstance(l2, (int, float)):\n            D = l2 * torch.eye(self.d)\n        else:\n            D = torch.diag(torch.from_numpy(l2))\n        return torch.norm(D @ (self.mu - self.mu_init)) ** 2",
    "docstring": "L2 loss centered around mu_init, scaled optionally per-source.\n\n        In other words, diagonal Tikhonov regularization,\n            ||D(\\mu-\\mu_{init})||_2^2\n        where D is diagonal.\n\n        Args:\n            - l2: A float or np.array representing the per-source regularization\n                strengths to use"
  },
  {
    "code": "def detect_suicidal_func(func):\n        if func.is_constructor:\n            return False\n        if func.visibility != 'public':\n            return False\n        calls = [c.name for c in func.internal_calls]\n        if not ('suicide(address)' in calls or 'selfdestruct(address)' in calls):\n            return False\n        if func.is_protected():\n            return False\n        return True",
    "docstring": "Detect if the function is suicidal\n\n        Detect the public functions calling suicide/selfdestruct without protection\n        Returns:\n            (bool): True if the function is suicidal"
  },
  {
    "code": "def _Start_refresh_timer(self):\n\t\tif self._refreshPeriod > 60:\n\t\t\tinterval = self._refreshPeriod - 60\n\t\telse:\n\t\t\tinterval = 60\n\t\tself._refreshTimer = Timer(self._refreshPeriod, self.Refresh)\n\t\tself._refreshTimer.setDaemon(True)\n\t\tself._refreshTimer.start()",
    "docstring": "Internal method to support auto-refresh functionality."
  },
  {
    "code": "def as_fn(self, *binding_order):\n    if len(binding_order) != len(self.unbound_vars):\n      raise ValueError('All vars must be specified.')\n    for arg in binding_order:\n      if arg not in self.unbound_vars:\n        raise ValueError('Unknown binding: %s' % arg)\n    def func(*args, **kwargs):\n      if len(binding_order) != len(args):\n        raise ValueError('Missing values, expects: %s' % binding_order)\n      values = dict(zip(binding_order, args))\n      values.update(kwargs)\n      return self.construct(**values)\n    func.__doc__ = _gen_ipython_string(func, binding_order, [], func.__doc__)\n    return func",
    "docstring": "Creates a function by binding the arguments in the given order.\n\n    Args:\n      *binding_order: The unbound variables. This must include all values.\n    Returns:\n      A function that takes the arguments of binding_order.\n    Raises:\n      ValueError: If the bindings are missing values or include unknown values."
  },
  {
    "code": "def _postprocess_output(self, output):\n        if self.vowel_style == CIRCUMFLEX_STYLE:\n            try:\n                output = output.translate(vowels_to_circumflexes)\n            except TypeError:\n                pass\n        if self.uppercase:\n            output = output.upper()\n        return output",
    "docstring": "Performs the last modifications before the output is returned."
  },
  {
    "code": "def lazy_load(name):\n  def wrapper(load_fn):\n    @_memoize\n    def load_once(self):\n      if load_once.loading:\n        raise ImportError(\"Circular import when resolving LazyModule %r\" % name)\n      load_once.loading = True\n      try:\n        module = load_fn()\n      finally:\n        load_once.loading = False\n      self.__dict__.update(module.__dict__)\n      load_once.loaded = True\n      return module\n    load_once.loading = False\n    load_once.loaded = False\n    class LazyModule(types.ModuleType):\n      def __getattr__(self, attr_name):\n        return getattr(load_once(self), attr_name)\n      def __dir__(self):\n        return dir(load_once(self))\n      def __repr__(self):\n        if load_once.loaded:\n          return '<%r via LazyModule (loaded)>' % load_once(self)\n        return '<module %r via LazyModule (not yet loaded)>' % self.__name__\n    return LazyModule(name)\n  return wrapper",
    "docstring": "Decorator to define a function that lazily loads the module 'name'.\n\n  This can be used to defer importing troublesome dependencies - e.g. ones that\n  are large and infrequently used, or that cause a dependency cycle -\n  until they are actually used.\n\n  Args:\n    name: the fully-qualified name of the module; typically the last segment\n      of 'name' matches the name of the decorated function\n\n  Returns:\n    Decorator function that produces a lazy-loading module 'name' backed by the\n    underlying decorated function."
  },
  {
    "code": "def make_permalink(img_id):\n    profile, filename = img_id.split(':', 1)\n    new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename)\n    urls = get_files_by_img_id(img_id)\n    if urls is None:\n        return urls\n    move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))}\n    for var_label, var_file_path in urls['variants'].iteritems():\n        move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path)))\n    for file_path_from, file_path_to in move_list:\n        os.rename(media_path(file_path_from), media_path(file_path_to))\n    return new_img_id",
    "docstring": "Removes tmp prefix from filename and rename main and variant files.\n    Returns img_id without tmp prefix."
  },
  {
    "code": "def update_sandbox_site(comment_text):\n    file_to_deliver = NamedTemporaryFile(delete=False)\n    file_text = \"Deployed at: {} <br /> Comment: {}\".format(datetime.datetime.now().strftime('%c'), cgi.escape(comment_text))\n    file_to_deliver.write(file_text)\n    file_to_deliver.close()\n    put(file_to_deliver.name, '/var/www/html/index.html', use_sudo=True)",
    "docstring": "put's a text file on the server"
  },
  {
    "code": "def parse_data_port_mappings(mappings, default_bridge='br-data'):\n    _mappings = parse_mappings(mappings, key_rvalue=True)\n    if not _mappings or list(_mappings.values()) == ['']:\n        if not mappings:\n            return {}\n        _mappings = {mappings.split()[0]: default_bridge}\n    ports = _mappings.keys()\n    if len(set(ports)) != len(ports):\n        raise Exception(\"It is not allowed to have the same port configured \"\n                        \"on more than one bridge\")\n    return _mappings",
    "docstring": "Parse data port mappings.\n\n    Mappings must be a space-delimited list of bridge:port.\n\n    Returns dict of the form {port:bridge} where ports may be mac addresses or\n    interface names."
  },
  {
    "code": "def fill(h1: Histogram1D, ax: Axes, **kwargs):\n    show_stats = kwargs.pop(\"show_stats\", False)\n    density = kwargs.pop(\"density\", False)\n    cumulative = kwargs.pop(\"cumulative\", False)\n    kwargs[\"label\"] = kwargs.get(\"label\", h1.name)\n    data = get_data(h1, cumulative=cumulative, density=density)\n    _apply_xy_lims(ax, h1, data, kwargs)\n    _add_ticks(ax, h1, kwargs)\n    _add_labels(ax, h1, kwargs)\n    ax.fill_between(h1.bin_centers, 0, data, **kwargs)\n    if show_stats:\n        _add_stats_box(h1, ax, stats=show_stats)\n    return ax",
    "docstring": "Fill plot of 1D histogram."
  },
  {
    "code": "def readpipe(self, chunk=None):\n        read = []\n        while True:\n            l = sys.stdin.readline()\n            if not l:\n                if read:\n                    yield read\n                    return\n                return\n            if not chunk:\n                yield l\n            else:\n                read.append(l)\n                if len(read) == chunk:\n                    yield read",
    "docstring": "Return iterator that iterates over STDIN line by line\n\n        If ``chunk`` is set to a positive non-zero integer value, then the\n        reads are performed in chunks of that many lines, and returned as a\n        list. Otherwise the lines are returned one by one."
  },
  {
    "code": "def resume(self, trigger_duration=0):\n        if trigger_duration != 0:\n            self._mq.send(\"t%d\" % trigger_duration, True, type=1)\n        else:\n            self._mq.send(\"r\", True, type=1)\n        self._paused = False",
    "docstring": "Resumes pulse capture after an optional trigger pulse."
  },
  {
    "code": "def stylize(txt, bold=False, underline=False):\n    setting = ''\n    setting += _SET_BOLD if bold is True else ''\n    setting += _SET_UNDERLINE if underline is True else ''\n    return setting + str(txt) + _STYLE_RESET",
    "docstring": "Changes style of the text."
  },
  {
    "code": "def GetSchema(component):\n    parent = component\n    while not isinstance(parent, XMLSchema):\n        parent = parent._parent()\n    return parent",
    "docstring": "convience function for finding the parent XMLSchema instance."
  },
  {
    "code": "def db_dict(c):\n    db_d = {}\n    c.execute('SELECT * FROM library_spectra')\n    db_d['library_spectra'] = [list(row) for row in c]\n    c.execute('SELECT * FROM library_spectra_meta')\n    db_d['library_spectra_meta'] = [list(row) for row in c]\n    c.execute('SELECT * FROM library_spectra_annotation')\n    db_d['library_spectra_annotations'] = [list(row) for row in c]\n    c.execute('SELECT * FROM library_spectra_source')\n    db_d['library_spectra_source'] = [list(row) for row in c]\n    c.execute('SELECT * FROM metab_compound')\n    db_d['metab_compound'] = [list(row) for row in c]\n    return db_d",
    "docstring": "Get a dictionary of the library spectra from a database\n\n    Example:\n        >>> from msp2db.db import get_connection\n        >>> conn = get_connection('sqlite', 'library.db')\n        >>> test_db_d = db_dict(conn.cursor())\n\n    If using a large database the resulting dictionary will be very large!\n\n    Args:\n        c (cursor): SQL database connection cursor\n\n    Returns:\n       A dictionary with the following keys 'library_spectra', 'library_spectra_meta', 'library_spectra_annotations',\n       'library_spectra_source' and 'metab_compound'. Where corresponding values for each key are list of list containing\n       all the rows in the database."
  },
  {
    "code": "def verified_funds(pronac, dt):\n    dataframe = data.planilha_comprovacao\n    project = dataframe.loc[dataframe['PRONAC'] == pronac]\n    segment_id = project.iloc[0][\"idSegmento\"]\n    pronac_funds = project[\n        [\"idPlanilhaAprovacao\", \"PRONAC\", \"vlComprovacao\", \"idSegmento\"]\n    ]\n    funds_grp = pronac_funds.drop(columns=[\"idPlanilhaAprovacao\"]).groupby(\n        [\"PRONAC\"]\n    )\n    project_funds = funds_grp.sum().loc[pronac][\"vlComprovacao\"]\n    segments_info = data.verified_funds_by_segment_agg.to_dict(orient=\"index\")\n    mean = segments_info[segment_id][\"mean\"]\n    std = segments_info[segment_id][\"std\"]\n    is_outlier = gaussian_outlier.is_outlier(project_funds, mean, std)\n    maximum_expected_funds = gaussian_outlier.maximum_expected_value(mean, std)\n    return {\n            \"is_outlier\": is_outlier,\n            \"valor\": project_funds,\n            \"maximo_esperado\": maximum_expected_funds,\n            \"minimo_esperado\": 0,\n    }",
    "docstring": "Responsable for detecting anomalies in projects total verified funds."
  },
  {
    "code": "def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs):\n    return salt.utils.napalm.call(\n        napalm_device,\n        'ping',\n        **{\n            'destination': destination,\n            'source': source,\n            'ttl': ttl,\n            'timeout': timeout,\n            'size': size,\n            'count': count,\n            'vrf': vrf\n        }\n    )",
    "docstring": "Executes a ping on the network device and returns a dictionary as a result.\n\n    destination\n        Hostname or IP address of remote host\n\n    source\n        Source address of echo request\n\n    ttl\n        IP time-to-live value (IPv6 hop-limit value) (1..255 hops)\n\n    timeout\n        Maximum wait time after sending final packet (seconds)\n\n    size\n        Size of request packets (0..65468 bytes)\n\n    count\n        Number of ping requests to send (1..2000000000 packets)\n\n    vrf\n        VRF (routing instance) for ping attempt\n\n        .. versionadded:: 2016.11.4\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' net.ping 8.8.8.8\n        salt '*' net.ping 8.8.8.8 ttl=3 size=65468\n        salt '*' net.ping 8.8.8.8 source=127.0.0.1 timeout=1 count=100"
  },
  {
    "code": "def _run_markdownlint(matched_filenames, show_lint_files):\n    from prospector.message import Message, Location\n    for filename in matched_filenames:\n        _debug_linter_status(\"mdl\", filename, show_lint_files)\n    try:\n        proc = subprocess.Popen([\"mdl\"] + matched_filenames,\n                                stdout=subprocess.PIPE,\n                                stderr=subprocess.PIPE)\n        lines = proc.communicate()[0].decode().splitlines()\n    except OSError as error:\n        if error.errno == errno.ENOENT:\n            return []\n    lines = [\n        re.match(r\"([\\w\\-.\\/\\\\ ]+)\\:([0-9]+)\\: (\\w+) (.+)\", l).groups(1)\n        for l in lines\n    ]\n    return_dict = dict()\n    for filename, lineno, code, msg in lines:\n        key = _Key(filename, int(lineno), code)\n        loc = Location(filename, None, None, int(lineno), 0)\n        return_dict[key] = Message(\"markdownlint\", code, loc, msg)\n    return return_dict",
    "docstring": "Run markdownlint on matched_filenames."
  },
  {
    "code": "def run_cufflinks(data):\n    if \"cufflinks\" in dd.get_tools_off(data):\n        return [[data]]\n    work_bam = dd.get_work_bam(data)\n    ref_file = dd.get_sam_ref(data)\n    out_dir, fpkm_file, fpkm_isoform_file = cufflinks.run(work_bam, ref_file, data)\n    data = dd.set_cufflinks_dir(data, out_dir)\n    data = dd.set_fpkm(data, fpkm_file)\n    data = dd.set_fpkm_isoform(data, fpkm_isoform_file)\n    return [[data]]",
    "docstring": "Quantitate transcript expression with Cufflinks"
  },
  {
    "code": "def minimum_needs_section_header_element(feature, parent):\n    _ = feature, parent\n    header = minimum_needs_section_header['string_format']\n    return header.capitalize()",
    "docstring": "Retrieve minimum needs section header string from definitions."
  },
  {
    "code": "def show_syspath(self, syspath):\r\n        if syspath is not None:\r\n            editor = CollectionsEditor(self)\r\n            editor.setup(syspath, title=\"sys.path contents\", readonly=True,\r\n                         width=600, icon=ima.icon('syspath'))\r\n            self.dialog_manager.show(editor)\r\n        else:\r\n            return",
    "docstring": "Show sys.path contents."
  },
  {
    "code": "def update_standings(semester=None, pool_hours=None, moment=None):\n    if semester is None:\n        try:\n            semester = Semester.objects.get(current=True)\n        except (Semester.DoesNotExist, Semester.MultipleObjectsReturned):\n            return []\n    if moment is None:\n        moment = localtime(now())\n    if pool_hours is None:\n        pool_hours = PoolHours.objects.filter(pool__semester=semester)\n    for hours in pool_hours:\n        if hours.last_updated and \\\n           hours.last_updated.date() > semester.end_date:\n            continue\n        periods = hours.periods_since_last_update(moment=moment)\n        if periods > 0:\n            hours.standing -= hours.hours * periods\n            hours.last_updated = moment\n            hours.save(update_fields=[\"standing\", \"last_updated\"])",
    "docstring": "This function acts to update a list of PoolHours objects to adjust their\n    current standing based on the time in the semester.\n\n    Parameters\n    ----------\n    semester : workshift.models.Semester, optional\n    pool_hours : list of workshift.models.PoolHours, optional\n        If None, runs on all pool hours for semester.\n    moment : datetime, optional"
  },
  {
    "code": "def get_events(self, service_location_id, appliance_id, start, end,\n                   max_number=None):\n        start = self._to_milliseconds(start)\n        end = self._to_milliseconds(end)\n        url = urljoin(URLS['servicelocation'], service_location_id, \"events\")\n        headers = {\"Authorization\": \"Bearer {}\".format(self.access_token)}\n        params = {\n            \"from\": start,\n            \"to\": end,\n            \"applianceId\": appliance_id,\n            \"maxNumber\": max_number\n        }\n        r = requests.get(url, headers=headers, params=params)\n        r.raise_for_status()\n        return r.json()",
    "docstring": "Request events for a given appliance\n\n        Parameters\n        ----------\n        service_location_id : int\n        appliance_id : int\n        start : int | dt.datetime | pd.Timestamp\n        end : int | dt.datetime | pd.Timestamp\n            start and end support epoch (in milliseconds),\n            datetime and Pandas Timestamp\n            timezone-naive datetimes are assumed to be in UTC\n        max_number : int, optional\n            The maximum number of events that should be returned by this query\n            Default returns all events in the selected period\n\n        Returns\n        -------\n        dict"
  },
  {
    "code": "def exists(self, target, path, path_sep=\"/\"):\n        if path.endswith(path_sep):\n            path = path[:-len(path_sep)]\n        par_dir, filename = path.rsplit(path_sep, 1)\n        file_list = self.list_files(target, par_dir)\n        out_dict = {}\n        for device_id, device_data in six.iteritems(file_list):\n            if isinstance(device_data, ErrorInfo):\n                out_dict[device_id] = device_data\n            else:\n                out_dict[device_id] = False\n                for cur_file in device_data.files:\n                    if cur_file.path == path:\n                        out_dict[device_id] = True\n                for cur_dir in device_data.directories:\n                    if cur_dir.path == path:\n                        out_dict[device_id] = True\n        return out_dict",
    "docstring": "Check if path refers to an existing path on the device\n\n        :param target: The device(s) to be targeted with this request\n        :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances\n        :param path: The path on the target to check for existence.\n        :param path_sep: The path separator of the device\n        :return: A dictionary where the key is a device id and the value is either an :class:`~.ErrorInfo` if there\n            was a problem with the operation or a boolean with the existence status of the path on that device"
  },
  {
    "code": "def clone(self, substitutions, **kwargs):\n        dag = self.explain(**kwargs)\n        dag.substitutions.update(substitutions)\n        cloned_dag = dag.clone(ignore=self.ignore)\n        return self.update_nodes(self.add_edges(cloned_dag))",
    "docstring": "Clone a DAG."
  },
  {
    "code": "def _did_receive_response(self, response):\n        try:\n            data = response.json()\n        except:\n            data = None\n        self._response = NURESTResponse(status_code=response.status_code, headers=response.headers, data=data, reason=response.reason)\n        level = logging.WARNING if self._response.status_code >= 300 else logging.DEBUG\n        bambou_logger.info('< %s %s %s [%s] ' % (self._request.method, self._request.url, self._request.params if self._request.params else \"\", self._response.status_code))\n        bambou_logger.log(level, '< headers: %s' % self._response.headers)\n        bambou_logger.log(level, '< data:\\n%s' % json.dumps(self._response.data, indent=4))\n        self._callback(self)\n        return self",
    "docstring": "Called when a response is received"
  },
  {
    "code": "def remove_locations(node):\n    def fix(node):\n        if 'lineno' in node._attributes and hasattr(node, 'lineno'):\n            del node.lineno\n        if 'col_offset' in node._attributes and hasattr(node, 'col_offset'):\n            del node.col_offset\n        for child in iter_child_nodes(node):\n            fix(child)\n    fix(node)",
    "docstring": "Removes locations from the given AST tree completely"
  },
  {
    "code": "def delete(self, key):\n    super(DirectoryTreeDatastore, self).delete(key)\n    str_key = str(key)\n    if str_key == '/':\n      return\n    dir_key = key.parent.instance('directory')\n    directory = self.directory(dir_key)\n    if directory and str_key in directory:\n      directory.remove(str_key)\n      if len(directory) > 0:\n        super(DirectoryTreeDatastore, self).put(dir_key, directory)\n      else:\n        super(DirectoryTreeDatastore, self).delete(dir_key)",
    "docstring": "Removes the object named by `key`.\n       DirectoryTreeDatastore removes the directory entry."
  },
  {
    "code": "def get_listener_instance(self, cls):\n        with self._lock:\n            for listener in self._listeners:\n                if isinstance(listener, cls):\n                    return listener",
    "docstring": "If a listener of the specified type is registered, returns the\n        instance.\n\n        :type cls: :class:`SessionListener`"
  },
  {
    "code": "def writeInfo(self, stream):\n        for (fromUUID, size) in Diff.theKnownSizes[self.uuid].iteritems():\n            self.writeInfoLine(stream, fromUUID, size)",
    "docstring": "Write information about diffs into a file stream for use later."
  },
  {
    "code": "def related(self, *, exclude_self=False):\n        manager = type(self)._default_manager\n        queryset = manager.related_to(self)\n        if exclude_self:\n            queryset = queryset.exclude(id=self.id)\n        return queryset",
    "docstring": "Get a QuerySet for all trigger log objects for the same connected model.\n\n        Args:\n            exclude_self (bool): Whether to exclude this log object from the result list"
  },
  {
    "code": "def _maintain_LC(self, obj, slice_id, last_slice=False, begin_slice=True,\n                   shard_ctx=None, slice_ctx=None):\n    if obj is None or not isinstance(obj, shard_life_cycle._ShardLifeCycle):\n      return\n    shard_context = shard_ctx or self.shard_context\n    slice_context = slice_ctx or self.slice_context\n    if begin_slice:\n      if slice_id == 0:\n        obj.begin_shard(shard_context)\n      obj.begin_slice(slice_context)\n    else:\n      obj.end_slice(slice_context)\n      if last_slice:\n        obj.end_shard(shard_context)",
    "docstring": "Makes sure shard life cycle interface are respected.\n\n    Args:\n      obj: the obj that may have implemented _ShardLifeCycle.\n      slice_id: current slice_id\n      last_slice: whether this is the last slice.\n      begin_slice: whether this is the beginning or the end of a slice.\n      shard_ctx: shard ctx for dependency injection. If None, it will be read\n        from self.\n      slice_ctx: slice ctx for dependency injection. If None, it will be read\n        from self."
  },
  {
    "code": "def series_expand(\n            self, param: Symbol, about, order: int) -> tuple:\n        r\n        expansion = self._series_expand(param, about, order)\n        res = []\n        for v in expansion:\n            if v == 0 or v.is_zero:\n                v = self._zero\n            elif v == 1:\n                v = self._one\n            assert isinstance(v, self._base_cls)\n            res.append(v)\n        return tuple(res)",
    "docstring": "r\"\"\"Expand the expression as a truncated power series in a\n        scalar parameter.\n\n        When expanding an expr for a parameter $x$ about the point $x_0$ up to\n        order $N$, the resulting coefficients $(c_1, \\dots, c_N)$ fulfill\n\n        .. math::\n\n            \\text{expr} = \\sum_{n=0}^{N} c_n (x - x_0)^n + O(N+1)\n\n        Args:\n            param: Expansion parameter $x$\n            about (Scalar): Point $x_0$ about which to expand\n            order: Maximum order $N$ of expansion (>= 0)\n\n        Returns:\n            tuple of length ``order + 1``, where the entries are the\n            expansion coefficients, $(c_0, \\dots, c_N)$.\n\n        Note:\n            The expansion coefficients are\n            \"type-stable\", in that they share a common base class with the\n            original expression. In particular, this applies to \"zero\"\n            coefficients::\n\n                >>> expr = KetSymbol(\"Psi\", hs=0)\n                >>> t = sympy.symbols(\"t\")\n                >>> assert expr.series_expand(t, 0, 1) == (expr, ZeroKet)"
  },
  {
    "code": "def _clean_filepath(self, filepath):\n        if (os.path.isdir(filepath) and\n                os.path.isfile(os.path.join(filepath, '__init__.py'))):\n            filepath = os.path.join(filepath, '__init__.py')\n        if (not filepath.endswith('.py') and\n                os.path.isfile(filepath + '.py')):\n            filepath += '.py'\n        return filepath",
    "docstring": "processes the filepath by checking if it is a directory or not\n        and adding `.py` if not present."
  },
  {
    "code": "def decode_msg(msg, enc='utf-8'):\n    cte = str(msg.get('content-transfer-encoding', '')).lower()\n    decode = cte not in (\"8bit\", \"7bit\", \"binary\")\n    res = msg.get_payload(decode=decode)\n    return decode_bytes(res, enc)",
    "docstring": "Decodes a message fragment.\n\n    Args: msg - A Message object representing the fragment\n          enc - The encoding to use for decoding the message"
  },
  {
    "code": "def libvlc_video_set_adjust_float(p_mi, option, value):\n    f = _Cfunctions.get('libvlc_video_set_adjust_float', None) or \\\n        _Cfunction('libvlc_video_set_adjust_float', ((1,), (1,), (1,),), None,\n                    None, MediaPlayer, ctypes.c_uint, ctypes.c_float)\n    return f(p_mi, option, value)",
    "docstring": "Set adjust option as float. Options that take a different type value\n    are ignored.\n    @param p_mi: libvlc media player instance.\n    @param option: adust option to set, values of libvlc_video_adjust_option_t.\n    @param value: adjust option value.\n    @version: LibVLC 1.1.1 and later."
  },
  {
    "code": "def _get_shipped_from(row):\n    try:\n        spans = row.find('div', {'id': 'coltextR2'}).find_all('span')\n        if len(spans) < 2:\n            return None\n        return spans[1].string\n    except AttributeError:\n        return None",
    "docstring": "Get where package was shipped from."
  },
  {
    "code": "def filter_metadata(metadata, user_filter, default_filter):\n    actual_keys = set(metadata.keys())\n    keep_keys = apply_metadata_filters(user_filter, default_filter, actual_keys)\n    for key in actual_keys:\n        if key not in keep_keys:\n            metadata.pop(key)\n    return metadata",
    "docstring": "Filter the cell or notebook metadata, according to the user preference"
  },
  {
    "code": "def username_to_uuid(username):\n    if not username.startswith('u-') or len(username) != 28:\n        raise ValueError('Not an UUID based username: %r' % (username,))\n    decoded = base64.b32decode(username[2:].upper() + '======')\n    return UUID(bytes=decoded)",
    "docstring": "Convert username to UUID.\n\n    >>> username_to_uuid('u-ad52zgilvnpgnduefzlh5jgr6y')\n    UUID('00fbac99-0bab-5e66-8e84-2e567ea4d1f6')"
  },
  {
    "code": "def _process_output(self, node, **kwargs):\n        for n in node.nodes:\n            self._process_node(n, **kwargs)",
    "docstring": "Processes an output node, which will contain things like `Name` and `TemplateData` nodes."
  },
  {
    "code": "def set_ocha_url(cls, url=None):\n        if url is None:\n            url = cls._ochaurl_int\n        cls._ochaurl = url",
    "docstring": "Set World Bank url from which to retrieve countries data\n\n        Args:\n            url (str): World Bank url from which to retrieve countries data. Defaults to internal value.\n\n        Returns:\n            None"
  },
  {
    "code": "def str2actfunc(act_func):\n    if act_func == 'sigmoid':\n        return tf.nn.sigmoid\n    elif act_func == 'tanh':\n        return tf.nn.tanh\n    elif act_func == 'relu':\n        return tf.nn.relu",
    "docstring": "Convert activation function name to tf function."
  },
  {
    "code": "def ungrab_hotkey(self, item):\n        import copy\n        newItem = copy.copy(item)\n        if item.get_applicable_regex() is None:\n            self.__enqueue(self.__ungrabHotkey, newItem.hotKey, newItem.modifiers, self.rootWindow)\n            if self.__needsMutterWorkaround(item):\n                self.__enqueue(self.__ungrabRecurse, newItem, self.rootWindow, False)\n        else:\n            self.__enqueue(self.__ungrabRecurse, newItem, self.rootWindow)",
    "docstring": "Ungrab a hotkey.\n\n        If the hotkey has no filter regex, it is global and is grabbed recursively from the root window\n        If it has a filter regex, iterate over all children of the root and ungrab from matching windows"
  },
  {
    "code": "def _check_dynamic_acl_support(self):\n        cmds = ['ip access-list openstack-test dynamic',\n                'no ip access-list openstack-test']\n        for switch_ip, switch_client in self._switches.items():\n            try:\n                self.run_openstack_sg_cmds(cmds)\n            except Exception:\n                LOG.error(\"Switch %s does not support dynamic ACLs. SG \"\n                          \"support will not be enabled on this switch.\",\n                          switch_ip)",
    "docstring": "Log an error if any switches don't support dynamic ACLs"
  },
  {
    "code": "def full_block_key(self):\n        if self.block_key.run is None:\n            return self.block_key.replace(course_key=self.course_key)\n        return self.block_key",
    "docstring": "Returns the \"correct\" usage key value with the run filled in."
  },
  {
    "code": "def separate_directions(di_block):\n    ppars = doprinc(di_block)\n    di_df = pd.DataFrame(di_block)\n    di_df.columns = ['dec', 'inc']\n    di_df['pdec'] = ppars['dec']\n    di_df['pinc'] = ppars['inc']\n    di_df['angle'] = angle(di_df[['dec', 'inc']].values,\n                           di_df[['pdec', 'pinc']].values)\n    mode1_df = di_df[di_df['angle'] <= 90]\n    mode2_df = di_df[di_df['angle'] > 90]\n    mode1 = mode1_df[['dec', 'inc']].values.tolist()\n    mode2 = mode2_df[['dec', 'inc']].values.tolist()\n    return mode1, mode2",
    "docstring": "Separates set of directions into two modes based on principal direction\n\n    Parameters\n    _______________\n    di_block : block of nested dec,inc pairs\n\n    Return\n    mode_1_block,mode_2_block :  two lists of nested dec,inc pairs"
  },
  {
    "code": "def get_columns_diff(changes):\n    for change in changes:\n        change.diff = []\n        elt_changes = change.get_changes()\n        if elt_changes:\n            change.diff = elt_changes.columns\n    return changes",
    "docstring": "Add the changed columns as a diff attribute.\n\n    - changes: a list of changes (get_model_changes query.all())\n\n    Return: the same list, to which elements we added a \"diff\"\n    attribute containing the changed columns. Diff defaults to []."
  },
  {
    "code": "def color_for_thread(thread_id):\n    if thread_id not in seen_thread_colors:\n        seen_thread_colors[thread_id] = next(thread_colors)\n    return seen_thread_colors[thread_id]",
    "docstring": "Associates the thread ID with the next color in the `thread_colors` cycle,\n    so that thread-specific parts of a log have a consistent separate color."
  },
  {
    "code": "def reward(self):\n    raw_rewards, processed_rewards = 0, 0\n    for ts in self.time_steps:\n      if ts.raw_reward is not None:\n        raw_rewards += ts.raw_reward\n      if ts.processed_reward is not None:\n        processed_rewards += ts.processed_reward\n    return raw_rewards, processed_rewards",
    "docstring": "Returns a tuple of sum of raw and processed rewards."
  },
  {
    "code": "def property(self, *args, **kwargs):\n        _properties = self.properties(*args, **kwargs)\n        if len(_properties) == 0:\n            raise NotFoundError(\"No property fits criteria\")\n        if len(_properties) != 1:\n            raise MultipleFoundError(\"Multiple properties fit criteria\")\n        return _properties[0]",
    "docstring": "Retrieve single KE-chain Property.\n\n        Uses the same interface as the :func:`properties` method but returns only a single pykechain :class:\n        `models.Property` instance.\n\n        If additional `keyword=value` arguments are provided, these are added to the request parameters. Please\n        refer to the documentation of the KE-chain API for additional query parameters.\n\n        :return: a single :class:`models.Property`\n        :raises NotFoundError: When no `Property` is found\n        :raises MultipleFoundError: When more than a single `Property` is found"
  },
  {
    "code": "def json_path_components(path):\n    if isinstance(path, str):\n        path = path.split('.')\n    return list(path)",
    "docstring": "Convert JSON path to individual path components.\n\n    :param path: JSON path, which can be either an iterable of path\n        components or a dot-separated string\n    :return: A list of path components"
  },
  {
    "code": "def sma(arg, n):\n    if n == 0:\n        return pd.expanding_mean(arg)\n    else:\n        return pd.rolling_mean(arg, n, min_periods=n)",
    "docstring": "If n is 0 then return the ltd mean; else return the n day mean"
  },
  {
    "code": "def to_html(self, write_to):\n        page_html = self.get_html()\n        with open(write_to, \"wb\") as writefile:\n            writefile.write(page_html.encode(\"utf-8\"))",
    "docstring": "Method to convert the repository list to a search results page and\n        write it to a HTML file.\n\n        :param write_to: File/Path to write the html file to."
  },
  {
    "code": "def fn_get_mask(self, value):\n        value = self._to_ndarray(value)\n        if numpy.ma.is_masked(value):\n            return value.mask\n        else:\n            return numpy.zeros(value.shape).astype(bool)",
    "docstring": "Return an array mask.\n\n        :param value: The array.\n        :return: The array mask."
  },
  {
    "code": "def infer_year(date):\n    if isinstance(date, str):\n        pattern = r'(?P<year>\\d{4})'\n        result = re.match(pattern, date)\n        if result:\n            return int(result.groupdict()['year'])\n        else:\n            raise ValueError('Invalid date string provided: {}'.format(date))\n    elif isinstance(date, np.datetime64):\n        return date.item().year\n    else:\n        return date.year",
    "docstring": "Given a datetime-like object or string infer the year.\n\n    Parameters\n    ----------\n    date : datetime-like object or str\n        Input date\n\n    Returns\n    -------\n    int\n\n    Examples\n    --------\n    >>> infer_year('2000')\n    2000\n    >>> infer_year('2000-01')\n    2000\n    >>> infer_year('2000-01-31')\n    2000\n    >>> infer_year(datetime.datetime(2000, 1, 1))\n    2000\n    >>> infer_year(np.datetime64('2000-01-01'))\n    2000\n    >>> infer_year(DatetimeNoLeap(2000, 1, 1))\n    2000\n    >>>"
  },
  {
    "code": "def search_tor_node(self, ip):\n        data = {}\n        tmp = {}\n        present = datetime.utcnow().replace(tzinfo=pytz.utc)\n        for line in self._get_raw_data().splitlines():\n            params = line.split(' ')\n            if params[0] == 'ExitNode':\n                tmp['node'] = params[1]\n            elif params[0] == 'ExitAddress':\n                tmp['last_status'] = params[2] + 'T' + params[3] + '+0000'\n                last_status = parse(tmp['last_status'])\n                if (self.delta is None or\n                   (present - last_status) < self.delta):\n                    data[params[1]] = tmp\n                tmp = {}\n            else:\n                pass\n        return data.get(ip, {})",
    "docstring": "Lookup an IP address to check if it is a known tor exit node.\n\n        :param ip: The IP address to lookup\n        :type ip: str\n        :return: Data relative to the tor node. If `ip`is a tor exit node\n                 it will contain a `node` key with the hash of the node and\n                 a `last_status` key with the last update time of the node.\n                 If `ip` is not a tor exit node, the function will return an\n                 empty dictionary.\n        :rtype: dict"
  },
  {
    "code": "def __update_common(self):\n        if \"TCON\" in self:\n            self[\"TCON\"].genres = self[\"TCON\"].genres\n        mimes = {\"PNG\": \"image/png\", \"JPG\": \"image/jpeg\"}\n        for pic in self.getall(\"APIC\"):\n            if pic.mime in mimes:\n                newpic = APIC(\n                    encoding=pic.encoding, mime=mimes[pic.mime],\n                    type=pic.type, desc=pic.desc, data=pic.data)\n                self.add(newpic)",
    "docstring": "Updates done by both v23 and v24 update"
  },
  {
    "code": "def _save_html_report(self, heads=None, refresh=None):\n        report = ReportHtml(self)\n        heads = heads if heads else {}\n        test_report_filename = report.get_current_filename(\"html\")\n        report.generate(test_report_filename, title='Test Results', heads=heads, refresh=refresh)\n        latest_report_filename = report.get_latest_filename(\"html\")\n        report.generate(latest_report_filename, title='Test Results', heads=heads, refresh=refresh)",
    "docstring": "Save html report.\n\n        :param heads: headers as dict\n        :param refresh: Boolean, if True will add a reload-tag to the report\n        :return: Nothing"
  },
  {
    "code": "def VCIncludes(self):\n        return [os.path.join(self.si.VCInstallDir, 'Include'),\n                os.path.join(self.si.VCInstallDir, r'ATLMFC\\Include')]",
    "docstring": "Microsoft Visual C++ & Microsoft Foundation Class Includes"
  },
  {
    "code": "def get_code(module):\n    fp = open(module.path)\n    try:\n        return compile(fp.read(), str(module.name), 'exec')\n    finally:\n        fp.close()",
    "docstring": "Compile and return a Module's code object."
  },
  {
    "code": "def markov_blanket(y, mean, scale, shape, skewness):\n        return ss.cauchy.logpdf(y, loc=mean, scale=scale)",
    "docstring": "Markov blanket for each likelihood term - used for state space models\n\n        Parameters\n        ----------\n        y : np.ndarray\n            univariate time series\n\n        mean : np.ndarray\n            array of location parameters for the Cauchy distribution\n\n        scale : float\n            scale parameter for the Cauchy distribution\n\n        shape : float\n            tail thickness parameter for the Cauchy distribution\n\n        skewness : float\n            skewness parameter for the Cauchy distribution\n\n        Returns\n        ----------\n        - Markov blanket of the Cauchy family"
  },
  {
    "code": "def enable(cls, args):\n        mgr = NAppsManager()\n        if args['all']:\n            napps = mgr.get_disabled()\n        else:\n            napps = args['<napp>']\n        cls.enable_napps(napps)",
    "docstring": "Enable subcommand."
  },
  {
    "code": "def _get_slice_axis(self, slice_obj, axis=None):\n        if axis is None:\n            axis = self.axis or 0\n        obj = self.obj\n        if not need_slice(slice_obj):\n            return obj.copy(deep=False)\n        labels = obj._get_axis(axis)\n        indexer = labels.slice_indexer(slice_obj.start, slice_obj.stop,\n                                       slice_obj.step, kind=self.name)\n        if isinstance(indexer, slice):\n            return self._slice(indexer, axis=axis, kind='iloc')\n        else:\n            return self.obj._take(indexer, axis=axis)",
    "docstring": "this is pretty simple as we just have to deal with labels"
  },
  {
    "code": "def _client_receive(self):\n        try:\n            response = self._client.readline()\n            self.log.debug('Snippet received: %s', response)\n            return response\n        except socket.error as e:\n            raise Error(\n                self._ad,\n                'Encountered socket error reading RPC response \"%s\"' % e)",
    "docstring": "Receives the server's response of an Rpc message.\n\n        Returns:\n            Raw byte string of the response.\n\n        Raises:\n            Error: a socket error occurred during the read."
  },
  {
    "code": "def stop_server(self):\n        self.stop = True\n        while self.task_count:\n            time.sleep(END_RESP)\n        self.terminate = True",
    "docstring": "Stop receiving connections, wait for all tasks to end, and then \n        terminate the server."
  },
  {
    "code": "def path_end_to_end_distance(neurite):\n    trunk = neurite.root_node.points[0]\n    return max(morphmath.point_dist(l.points[-1], trunk)\n               for l in neurite.root_node.ileaf())",
    "docstring": "Calculate and return end-to-end-distance of a given neurite."
  },
  {
    "code": "def _check_model_types(self, models):\n        if not hasattr(models, \"__iter__\"):\n            models = {models}\n        if not all([isinstance(model, (AbstractStateModel, StateElementModel)) for model in models]):\n            raise TypeError(\"The selection supports only models with base class AbstractStateModel or \"\n                            \"StateElementModel, see handed elements {0}\".format(models))\n        return models if isinstance(models, set) else set(models)",
    "docstring": "Check types of passed models for correctness and in case raise exception\n\n        :rtype: set\n        :returns: set of models that are valid for the class"
  },
  {
    "code": "def _get_col_epsg(mapped_class, geom_attr):\n    col = class_mapper(mapped_class).get_property(geom_attr).columns[0]\n    return col.type.srid",
    "docstring": "Get the EPSG code associated with a geometry attribute.\n\n    Arguments:\n\n\n    geom_attr\n        the key of the geometry property as defined in the SQLAlchemy\n        mapper. If you use ``declarative_base`` this is the name of\n        the geometry attribute as defined in the mapped class."
  },
  {
    "code": "def contains_geometric_info(var):\n    return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)",
    "docstring": "Check whether the passed variable is a tuple with two floats or integers"
  },
  {
    "code": "def _SigSegvHandler(self, signal_number, stack_frame):\n    self._OnCriticalError()\n    if self._original_sigsegv_handler is not None:\n      signal.signal(signal.SIGSEGV, self._original_sigsegv_handler)\n      os.kill(self._pid, signal.SIGSEGV)",
    "docstring": "Signal handler for the SIGSEGV signal.\n\n    Args:\n      signal_number (int): numeric representation of the signal.\n      stack_frame (frame): current stack frame or None."
  },
  {
    "code": "def expanded_by(self, n):\n        return Rect(self.left - n, self.top - n, self.right + n, self.bottom + n)",
    "docstring": "Return a rectangle with extended borders.\n\n        Create a new rectangle that is wider and taller than the\n        immediate one. All sides are extended by \"n\" points."
  },
  {
    "code": "def get_cache_prefix(self, prefix=''):\n        if settings.CACHE_MIDDLEWARE_KEY_PREFIX:\n            prefix += settings.CACHE_MIDDLEWARE_KEY_PREFIX\n        if self.request.is_ajax():\n            prefix += 'ajax'\n        return prefix",
    "docstring": "Hook for any extra data you would like\n        to prepend to your cache key.\n\n        The default implementation ensures that ajax not non\n        ajax requests are cached separately. This can easily\n        be extended to differentiate on other criteria\n        like mobile os' for example."
  },
  {
    "code": "def from_file(filename):\n        spec = Spec()\n        with open(filename, \"r\", encoding=\"utf-8\") as f:\n            parse_context = {\"current_subpackage\": None}\n            for line in f:\n                spec, parse_context = _parse(spec, parse_context, line)\n        return spec",
    "docstring": "Creates a new Spec object from a given file.\n\n        :param filename: The path to the spec file.\n        :return: A new Spec object."
  },
  {
    "code": "def _check_task(taskid):\n    try:\n        taskurl = taskid.get('ref', '0000')\n    except AttributeError:\n        taskurl = taskid\n    taskid = taskurl.split('/tasks/')[-1]\n    LOG.info('Checking taskid %s', taskid)\n    url = '{}/tasks/{}'.format(API_URL, taskid)\n    task_response = requests.get(url, headers=HEADERS, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)\n    LOG.debug(task_response.json())\n    assert task_response.ok, 'Spinnaker communication error: {0}'.format(task_response.text)\n    task_state = task_response.json()\n    status = task_state['status']\n    LOG.info('Current task status: %s', status)\n    if status == 'SUCCEEDED':\n        return status\n    elif status == 'TERMINAL':\n        raise SpinnakerTaskError(task_state)\n    else:\n        raise ValueError",
    "docstring": "Check Spinnaker Task status.\n\n    Args:\n        taskid (str): Existing Spinnaker Task ID.\n\n    Returns:\n        str: Task status."
  },
  {
    "code": "def get_suitable_vis_classes(obj):\n    ret = []\n    for class_ in classes_vis():\n        if isinstance(obj, class_.input_classes):\n            ret.append(class_)\n    return ret",
    "docstring": "Retuns a list of Vis classes that can handle obj."
  },
  {
    "code": "def coord(self, func:CoordFunc, *args, **kwargs)->'ImagePoints':\n        \"Put `func` with `args` and `kwargs` in `self.flow_func` for later.\"\n        if 'invert' in kwargs: kwargs['invert'] = True\n        else: warn(f\"{func.__name__} isn't implemented for {self.__class__}.\")\n        self.flow_func.append(partial(func, *args, **kwargs))\n        return self",
    "docstring": "Put `func` with `args` and `kwargs` in `self.flow_func` for later."
  },
  {
    "code": "def transactional_async(func, args, kwds, **options):\n  options.setdefault('propagation', datastore_rpc.TransactionOptions.ALLOWED)\n  if args or kwds:\n    return transaction_async(lambda: func(*args, **kwds), **options)\n  return transaction_async(func, **options)",
    "docstring": "The async version of @ndb.transaction."
  },
  {
    "code": "def post_to_url(self, value):\n        if isinstance(value, SpamUrl):\n            self._post_to_url = value\n        else:\n            self._post_to_url = SpamUrl(value)",
    "docstring": "An Inbound Parse URL to send a copy of your email.\n        If defined, a copy of your email and its spam report will be sent here.\n\n        :param value: An Inbound Parse URL to send a copy of your email.\n        If defined, a copy of your email and its spam report will be sent here.\n        :type value: string"
  },
  {
    "code": "def savePattern(self):\n        if ( self.dev == None ): return ''\n        buf = [REPORT_ID, ord('W'), 0xBE, 0xEF, 0xCA, 0xFE, 0, 0, 0]\n        return self.write(buf);",
    "docstring": "Save internal RAM pattern to flash"
  },
  {
    "code": "def _pruning_base(self, axis=None, hs_dims=None):\n        if not self._is_axis_allowed(axis):\n            return self.as_array(weighted=False, include_transforms_for_dims=hs_dims)\n        return self.margin(\n            axis=axis, weighted=False, include_transforms_for_dims=hs_dims\n        )",
    "docstring": "Gets margin if across CAT dimension. Gets counts if across items.\n\n        Categorical variables are pruned based on their marginal values. If the\n        marginal is a 0 or a NaN, the corresponding row/column is pruned. In\n        case of a subvars (items) dimension, we only prune if all the counts\n        of the corresponding row/column are zero."
  },
  {
    "code": "def relevant_part(self, original, pos):\n        start = original.rfind(self._separator, 0, pos)\n        if start == -1:\n            start = 0\n        else:\n            start = start + len(self._separator)\n        end = original.find(self._separator, pos - 1)\n        if end == -1:\n            end = len(original)\n        return original[start:end], start, end, pos - start",
    "docstring": "calculates the subword of `original` that `pos` is in"
  },
  {
    "code": "def _migrate_single(self, conn, migration):\n        with contextlib.ExitStack() as stack:\n            for wrapper in self._wrappers:\n                stack.enter_context(wrapper(conn))\n            migration.func(conn)",
    "docstring": "Perform a single migration starting from the given version."
  },
  {
    "code": "def t_surf_parameter(self, num_frame, xax):\n        pyl.figure(num_frame)\n        if xax == 'time':\n            xaxisarray = self.get('star_age')\n        elif xax == 'model':\n            xaxisarray = self.get('model_number')\n        else:\n            print('kippenhahn_error: invalid string for x-axis selction. needs to be \"time\" or \"model\"')\n        logL    = self.get('log_L')\n        logTeff    = self.get('log_Teff')\n        pyl.plot(xaxisarray,logL,'-k',label='log L')\n        pyl.plot(xaxisarray,logTeff,'-k',label='log Teff')\n        pyl.ylabel('log L, log Teff')\n        pyl.legend(loc=2)\n        if xax == 'time':\n            pyl.xlabel('t / yrs')\n        elif xax == 'model':\n            pyl.xlabel('model number')",
    "docstring": "Surface parameter evolution as a function of time or model.\n\n        Parameters\n        ----------\n        num_frame : integer\n            Number of frame to plot this plot into.\n        xax : string\n            Either model or time to indicate what is to be used on the\n            x-axis"
  },
  {
    "code": "def load_data(handle, reader=None):\n    if not reader:\n        reader = os.path.splitext(handle)[1][1:].lower()\n    if reader not in _READERS:\n        raise NeuroMError('Do not have a loader for \"%s\" extension' % reader)\n    filename = _get_file(handle)\n    try:\n        return _READERS[reader](filename)\n    except Exception as e:\n        L.exception('Error reading file %s, using \"%s\" loader', filename, reader)\n        raise RawDataError('Error reading file %s:\\n%s' % (filename, str(e)))",
    "docstring": "Unpack data into a raw data wrapper"
  },
  {
    "code": "def ser_iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed):\n    wavelet_filter = (1./16)*np.array([1,4,6,4,1])\n    detail_coeffs = np.empty([scale_count-scale_adjust, in1.shape[0], in1.shape[1]])\n    C0 = in1\n    if scale_adjust>0:\n        for i in range(0, scale_adjust):\n            C0 = ser_a_trous(C0, wavelet_filter, i)\n    for i in range(scale_adjust,scale_count):\n        C = ser_a_trous(C0, wavelet_filter, i)\n        C1 = ser_a_trous(C, wavelet_filter, i)\n        detail_coeffs[i-scale_adjust,:,:] = C0 - C1\n        C0 = C\n    if store_smoothed:\n        return detail_coeffs, C0\n    else:\n        return detail_coeffs",
    "docstring": "This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is\n    the isotropic undecimated wavelet transform implemented for a single CPU core.\n\n    INPUTS:\n    in1                 (no default):   Array on which the decomposition is to be performed.\n    scale_count         (no default):   Maximum scale to be considered.\n    scale_adjust        (default=0):    Adjustment to scale value if first scales are of no interest.\n    store_smoothed      (default=False):Boolean specifier for whether the smoothed image is stored or not.\n\n    OUTPUTS:\n    detail_coeffs                       Array containing the detail coefficients.\n    C0                  (optional):     Array containing the smoothest version of the input."
  },
  {
    "code": "def clear(self):\n        del self._statements_and_parameters[:]\n        self.keyspace = None\n        self.routing_key = None\n        if self.custom_payload:\n            self.custom_payload.clear()",
    "docstring": "This is a convenience method to clear a batch statement for reuse.\n\n        *Note:* it should not be used concurrently with uncompleted execution futures executing the same\n        ``BatchStatement``."
  },
  {
    "code": "def enclosure_shell(self):\n        pairs = [(r, self.connected_paths(r, include_self=False))\n                 for r in self.root]\n        corresponding = collections.OrderedDict(pairs)\n        return corresponding",
    "docstring": "A dictionary of path indexes which are 'shell' paths, and values\n        of 'hole' paths.\n\n        Returns\n        ----------\n        corresponding: dict, {index of self.paths of shell : [indexes of holes]}"
  },
  {
    "code": "def insert(self, loc, item):\n        if not isinstance(item, tuple):\n            item = (item, ) + ('', ) * (self.nlevels - 1)\n        elif len(item) != self.nlevels:\n            raise ValueError('Item must have length equal to number of '\n                             'levels.')\n        new_levels = []\n        new_codes = []\n        for k, level, level_codes in zip(item, self.levels, self.codes):\n            if k not in level:\n                lev_loc = len(level)\n                level = level.insert(lev_loc, k)\n            else:\n                lev_loc = level.get_loc(k)\n            new_levels.append(level)\n            new_codes.append(np.insert(\n                ensure_int64(level_codes), loc, lev_loc))\n        return MultiIndex(levels=new_levels, codes=new_codes,\n                          names=self.names, verify_integrity=False)",
    "docstring": "Make new MultiIndex inserting new item at location\n\n        Parameters\n        ----------\n        loc : int\n        item : tuple\n            Must be same length as number of levels in the MultiIndex\n\n        Returns\n        -------\n        new_index : Index"
  },
  {
    "code": "def _validate_config(strict=False):\n    for index in settings.get_index_names():\n        _validate_mapping(index, strict=strict)\n        for model in settings.get_index_models(index):\n            _validate_model(model)\n    if settings.get_setting(\"update_strategy\", \"full\") not in [\"full\", \"partial\"]:\n        raise ImproperlyConfigured(\n            \"Invalid SEARCH_SETTINGS: 'update_strategy' value must be 'full' or 'partial'.\"\n        )",
    "docstring": "Validate settings.SEARCH_SETTINGS."
  },
  {
    "code": "def _format_from_dict(self, format_string, **kwargs):\n        kwargs_copy = self.base_dict.copy()\n        kwargs_copy.update(**kwargs)\n        localpath = format_string.format(**kwargs_copy)\n        if kwargs.get('fullpath', False):\n            return self.fullpath(localpath=localpath)\n        return localpath",
    "docstring": "Return a formatted file name dictionary components"
  },
  {
    "code": "def add_user(self, username, password):\n        self.server.user_dict[username] = password\n        self.server.isAuth = True",
    "docstring": "Add an user to the dictionary."
  },
  {
    "code": "def main(args_list=None):\n    args = parse_args(args_list)\n    print(\"Topiary commandline arguments:\")\n    print(args)\n    df = predict_epitopes_from_args(args)\n    write_outputs(df, args)\n    print(\"Total count: %d\" % len(df))",
    "docstring": "Script entry-point to predict neo-epitopes from genomic variants using\n    Topiary."
  },
  {
    "code": "def stop(self):\n        self._presubs.remove(self._sdk_presub_params)\n        if self._immediacy == FirstValue.on_value_update:\n            self._unsubscribe_all_matching()\n        super(ResourceValues, self).stop()",
    "docstring": "Stop the channel"
  },
  {
    "code": "def get_file_contents(self, pointer=False):\n        if self.pointer:\n            if pointer:\n                return self.old_pointed\n            else:\n                return self.old_data\n        else:\n            return self.old_data",
    "docstring": "Gets any file contents you care about. Defaults to the main file\n        @param pointer: The the contents of the file pointer, not the pointed\n        at file\n        @return: A string of the contents"
  },
  {
    "code": "def _double_gamma_hrf(response_delay=6,\n                      undershoot_delay=12,\n                      response_dispersion=0.9,\n                      undershoot_dispersion=0.9,\n                      response_scale=1,\n                      undershoot_scale=0.035,\n                      temporal_resolution=100.0,\n                      ):\n    hrf_length = 30\n    hrf = [0] * int(hrf_length * temporal_resolution)\n    response_peak = response_delay * response_dispersion\n    undershoot_peak = undershoot_delay * undershoot_dispersion\n    for hrf_counter in list(range(len(hrf) - 1)):\n        resp_pow = math.pow((hrf_counter / temporal_resolution) /\n                            response_peak, response_delay)\n        resp_exp = math.exp(-((hrf_counter / temporal_resolution) -\n                              response_peak) /\n                            response_dispersion)\n        response_model = response_scale * resp_pow * resp_exp\n        undershoot_pow = math.pow((hrf_counter / temporal_resolution) /\n                                  undershoot_peak,\n                                  undershoot_delay)\n        undershoot_exp = math.exp(-((hrf_counter / temporal_resolution) -\n                                    undershoot_peak /\n                                    undershoot_dispersion))\n        undershoot_model = undershoot_scale * undershoot_pow * undershoot_exp\n        hrf[hrf_counter] = response_model - undershoot_model\n    return hrf",
    "docstring": "Create the double gamma HRF with the timecourse evoked activity.\n    Default values are based on Glover, 1999 and Walvaert, Durnez,\n    Moerkerke, Verdoolaege and Rosseel, 2011\n\n    Parameters\n    ----------\n\n    response_delay : float\n        How many seconds until the peak of the HRF\n\n    undershoot_delay : float\n        How many seconds until the trough of the HRF\n\n    response_dispersion : float\n        How wide is the rising peak dispersion\n\n    undershoot_dispersion : float\n        How wide is the undershoot dispersion\n\n    response_scale : float\n         How big is the response relative to the peak\n\n    undershoot_scale :float\n        How big is the undershoot relative to the trough\n\n    scale_function : bool\n        Do you want to scale the function to a range of 1\n\n    temporal_resolution : float\n        How many elements per second are you modeling for the stimfunction\n    Returns\n    ----------\n\n    hrf : multi dimensional array\n        A double gamma HRF to be used for convolution."
  },
  {
    "code": "def get_asset_details(self, **params):\n        res = self._request_withdraw_api('get', 'assetDetail.html', True, data=params)\n        if not res['success']:\n            raise BinanceWithdrawException(res['msg'])\n        return res",
    "docstring": "Fetch details on assets.\n\n        https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#asset-detail-user_data\n\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"success\": true,\n                \"assetDetail\": {\n                    \"CTR\": {\n                        \"minWithdrawAmount\": \"70.00000000\", //min withdraw amount\n                        \"depositStatus\": false,//deposit status\n                        \"withdrawFee\": 35, // withdraw fee\n                        \"withdrawStatus\": true, //withdraw status\n                        \"depositTip\": \"Delisted, Deposit Suspended\" //reason\n                    },\n                    \"SKY\": {\n                        \"minWithdrawAmount\": \"0.02000000\",\n                        \"depositStatus\": true,\n                        \"withdrawFee\": 0.01,\n                        \"withdrawStatus\": true\n                    }\n                }\n            }\n\n        :raises: BinanceWithdrawException"
  },
  {
    "code": "def git_show_file(path, ref):\n    root = get_root()\n    command = 'git show {}:{}'.format(ref, path)\n    with chdir(root):\n        return run_command(command, capture=True).stdout",
    "docstring": "Return the contents of a file at a given tag"
  },
  {
    "code": "def get_alert_destination_count(self, channel=None):\n        if channel is None:\n            channel = self.get_network_channel()\n        rqdata = (channel, 0x11, 0, 0)\n        rsp = self.xraw_command(netfn=0xc, command=2, data=rqdata)\n        return ord(rsp['data'][1])",
    "docstring": "Get the number of supported alert destinations\n\n        :param channel: Channel for alerts to be examined, defaults to current"
  },
  {
    "code": "def _serialize_ep(ep, varprops, version=_default_version):\n    args = ep[3]\n    arglist = ' '.join([_serialize_argument(rarg, args[rarg], varprops)\n                        for rarg in sorted(args, key=rargname_sortkey)])\n    if version < 1.1 or len(ep) < 6 or ep[5] is None:\n        surface = ''\n    else:\n        surface = ' \"%s\"' % ep[5]\n    lnk = None if len(ep) < 5 else ep[4]\n    pred = ep[1]\n    predstr = pred.string\n    return '[ {pred}{lnk}{surface} LBL: {label}{s}{args} ]'.format(\n        pred=predstr,\n        lnk=_serialize_lnk(lnk),\n        surface=surface,\n        label=str(ep[2]),\n        s=' ' if arglist else '',\n        args=arglist\n    )",
    "docstring": "Serialize an Elementary Predication into the SimpleMRS encoding."
  },
  {
    "code": "def swapon(name, priority=None):\n    ret = {}\n    on_ = swaps()\n    if name in on_:\n        ret['stats'] = on_[name]\n        ret['new'] = False\n        return ret\n    if __grains__['kernel'] == 'SunOS':\n        if __grains__['virtual'] != 'zone':\n            __salt__['cmd.run']('swap -a {0}'.format(name), python_shell=False)\n        else:\n            return False\n    else:\n        cmd = 'swapon {0}'.format(name)\n        if priority and 'AIX' not in __grains__['kernel']:\n            cmd += ' -p {0}'.format(priority)\n        __salt__['cmd.run'](cmd, python_shell=False)\n    on_ = swaps()\n    if name in on_:\n        ret['stats'] = on_[name]\n        ret['new'] = True\n        return ret\n    return ret",
    "docstring": "Activate a swap disk\n\n    .. versionchanged:: 2016.3.2\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' mount.swapon /root/swapfile"
  },
  {
    "code": "def _submit_topology(cmd_args, app):\n    cfg = app.cfg\n    if cmd_args.create_bundle:\n        ctxtype = ctx.ContextTypes.BUNDLE\n    elif cmd_args.service_name:\n        cfg[ctx.ConfigParams.FORCE_REMOTE_BUILD] = True\n        cfg[ctx.ConfigParams.SERVICE_NAME] = cmd_args.service_name\n        ctxtype = ctx.ContextTypes.STREAMING_ANALYTICS_SERVICE\n    sr = ctx.submit(ctxtype, app.app, cfg)\n    return sr",
    "docstring": "Submit a Python topology to the service.\n    This includes an SPL main composite wrapped in a Python topology."
  },
  {
    "code": "def getextensibleindex(self, key, name):\n        return getextensibleindex(\n            self.idfobjects, self.model, self.idd_info,\n            key, name)",
    "docstring": "Get the index of the first extensible item.\n\n        Only for internal use. # TODO : hide this\n\n        Parameters\n        ----------\n        key : str\n            The type of IDF object. This must be in ALL_CAPS.\n        name : str\n            The name of the object to fetch.\n\n        Returns\n        -------\n        int"
  },
  {
    "code": "def to_existing_absolute_path(string):\n    value = os.path.abspath(string)\n    if not os.path.exists( value ) or not os.path.isdir( value ):\n        msg = '\"%r\" is not a valid path to a directory.' % string\n        raise argparse.ArgumentTypeError(msg)\n    return value",
    "docstring": "Converts a path into its absolute path and verifies that it exists or throws an exception."
  },
  {
    "code": "def cp_string(self, source, dest, **kwargs):\n        assert isinstance(source, six.string_types), \"source must be a string\"\n        assert self._is_s3(dest), \"Destination must be s3 location\"\n        return self._put_string(source, dest, **kwargs)",
    "docstring": "Copies source string into the destination location.\n\n        Parameters\n        ----------\n        source: string\n            the string with the content to copy\n        dest: string\n            the s3 location"
  },
  {
    "code": "def recursively_resume_states(self):\n        super(ContainerState, self).recursively_resume_states()\n        for state in self.states.values():\n            state.recursively_resume_states()",
    "docstring": "Resume the state and all of it child states."
  },
  {
    "code": "def _initialize_initial_state_fluents(self):\n        state_fluents = self.rddl.domain.state_fluents\n        initializer = self.rddl.instance.init_state\n        self.initial_state_fluents = self._initialize_pvariables(\n            state_fluents,\n            self.rddl.domain.state_fluent_ordering,\n            initializer)\n        return self.initial_state_fluents",
    "docstring": "Returns the initial state-fluents instantiated."
  },
  {
    "code": "def main(args=None):\n    parser = argparse.ArgumentParser(description=main.__doc__)\n    parser.add_argument(\n        '--binary',\n        dest='mode',\n        action='store_const',\n        const=\"wb\",\n        default=\"w\",\n        help='write in binary mode')\n    parser.add_argument(\n        'output', metavar='FILE', type=unicode, help='Output file')\n    logging.basicConfig(\n        level=logging.DEBUG,\n        stream=sys.stderr,\n        format='[%(levelname)s elapsed=%(relativeCreated)dms] %(message)s')\n    args = parser.parse_args(args or sys.argv[1:])\n    with open(args.output, args.mode) as fd:\n        for line in sys.stdin:\n            fd.write(line)",
    "docstring": "Buffer stdin and flush, and avoid incomplete files."
  },
  {
    "code": "def as_dict(self):\n        if self.hidden:\n            rdict = {}\n        else:\n            def_selected = self.selected()\n            comps = [\n                {\n                    'name': comp.name,\n                    'default': comp.name in self.defaults,\n                    'options': comp.get_ordered_options() if isinstance(comp, Optionable) else None\n                }\n                for comp in self\n            ]\n            rdict = {\n                'name': self.name,\n                'required': self.required,\n                'multiple': self.multiple,\n                'args': self.in_name,\n                'returns': self.out_name,\n                'components': comps\n            }\n        return rdict",
    "docstring": "returns a dictionary representation of the block and of all\n        component options"
  },
  {
    "code": "def obfuscate(cls, idStr):\n        return unicode(base64.urlsafe_b64encode(\n            idStr.encode('utf-8')).replace(b'=', b''))",
    "docstring": "Mildly obfuscates the specified ID string in an easily reversible\n        fashion. This is not intended for security purposes, but rather to\n        dissuade users from depending on our internal ID structures."
  },
  {
    "code": "def bind(self, *args, **kw):\n    new_self = self.copy()\n    new_scopes = Object.translate_to_scopes(*args, **kw)\n    new_self._scopes = tuple(reversed(new_scopes)) + new_self._scopes\n    return new_self",
    "docstring": "Bind environment variables into this object's scope."
  },
  {
    "code": "def get_bounding_box(df_points):\n    xy_min = df_points[['x', 'y']].min()\n    xy_max = df_points[['x', 'y']].max()\n    wh = xy_max - xy_min\n    wh.index = 'width', 'height'\n    bbox = pd.concat([xy_min, wh])\n    bbox.name = 'bounding_box'\n    return bbox",
    "docstring": "Calculate the bounding box of all points in a data frame."
  },
  {
    "code": "def plot(self):\n        figure()\n        plot_envelope(self.M, self.C, self.xplot)\n        for i in range(3):\n            f = Realization(self.M, self.C)\n            plot(self.xplot,f(self.xplot))\n        plot(self.abundance, self.frye, 'k.', markersize=4)\n        xlabel('Female abundance')\n        ylabel('Frye density')\n        title(self.name)\n        axis('tight')",
    "docstring": "Plot posterior from simple nonstochetric regression."
  },
  {
    "code": "def _parse(self, stream, context, path):\n        objs = []\n        while True:\n            start = stream.tell()\n            test = stream.read(len(self.find))\n            stream.seek(start)\n            if test == self.find:\n                break\n            else:\n                subobj = self.subcon._parse(stream, context, path)\n                objs.append(subobj)\n        return objs",
    "docstring": "Parse until a given byte string is found."
  },
  {
    "code": "def read_config(config_file=CONFIG_FILE_DEFAULT, override_url=None):\n    config = ConfigParser()\n    config.read_dict(DEFAULT_SETTINGS)\n    try:\n        config.readfp(open(config_file))\n        logger.debug(\"Using config file at \" + config_file)\n    except:\n        logger.error(\n            \"Could not find {0}, running with defaults.\".format(config_file))\n    if not logger.handlers:\n        if config.getboolean(\"Logging\", \"to_file\"):\n            handler = logging.FileHandler(config.get(\"Logging\", \"file\"))\n        else:\n            handler = logging.StreamHandler()\n        handler.setFormatter(logging.Formatter(\n            config.get(\"Logging\", \"format\")))\n        logger.addHandler(handler)\n    logger.setLevel(config.get(\"Logging\", \"level\"))\n    if override_url:\n        config['Server']['url'] = override_url\n    return config",
    "docstring": "Read configuration file, perform sanity check and return configuration\n        dictionary used by other functions."
  },
  {
    "code": "def collapse_all(self):\n        if implementsCollapseAPI(self._tree):\n            self._tree.collapse_all()\n            self.set_focus(self._tree.root)\n            self._walker.clear_cache()\n            self.refresh()",
    "docstring": "Collapse all positions; works only if the underlying tree allows it."
  },
  {
    "code": "def max_rigid_id(self):\n        try:\n            return max([particle.rigid_id for particle in self.particles()\n                        if particle.rigid_id is not None])\n        except ValueError:\n            return",
    "docstring": "Returns the maximum rigid body ID contained in the Compound.\n\n        This is usually used by compound.root to determine the maximum\n        rigid_id in the containment hierarchy.\n\n        Returns\n        -------\n        int or None\n            The maximum rigid body ID contained in the Compound. If no\n            rigid body IDs are found, None is returned"
  },
  {
    "code": "def _import_status(data, item, repo_name, repo_tag):\n    status = item['status']\n    try:\n        if 'Downloading from' in status:\n            return\n        elif all(x in string.hexdigits for x in status):\n            data['Image'] = '{0}:{1}'.format(repo_name, repo_tag)\n            data['Id'] = status\n    except (AttributeError, TypeError):\n        pass",
    "docstring": "Process a status update from docker import, updating the data structure"
  },
  {
    "code": "def _get_band(self, high_res, low_res, color, ratio):\n        if self.high_resolution_band == color:\n            ret = high_res\n        else:\n            ret = low_res * ratio\n            ret.attrs = low_res.attrs.copy()\n        return ret",
    "docstring": "Figure out what data should represent this color."
  },
  {
    "code": "def override_account_fields(self,\n                                settled_cash=not_overridden,\n                                accrued_interest=not_overridden,\n                                buying_power=not_overridden,\n                                equity_with_loan=not_overridden,\n                                total_positions_value=not_overridden,\n                                total_positions_exposure=not_overridden,\n                                regt_equity=not_overridden,\n                                regt_margin=not_overridden,\n                                initial_margin_requirement=not_overridden,\n                                maintenance_margin_requirement=not_overridden,\n                                available_funds=not_overridden,\n                                excess_liquidity=not_overridden,\n                                cushion=not_overridden,\n                                day_trades_remaining=not_overridden,\n                                leverage=not_overridden,\n                                net_leverage=not_overridden,\n                                net_liquidation=not_overridden):\n        self._dirty_account = True\n        self._account_overrides = kwargs = {\n            k: v for k, v in locals().items() if v is not not_overridden\n        }\n        del kwargs['self']",
    "docstring": "Override fields on ``self.account``."
  },
  {
    "code": "def assert_count_equal(sequence1, sequence2, msg_fmt=\"{msg}\"):\n    def compare():\n        missing1 = list(sequence2)\n        missing2 = []\n        for item in sequence1:\n            try:\n                missing1.remove(item)\n            except ValueError:\n                missing2.append(item)\n        return missing1, missing2\n    def build_message():\n        msg = \"\"\n        if missing_from_1:\n            msg += \"missing from sequence 1: \" + \", \".join(\n                repr(i) for i in missing_from_1\n            )\n        if missing_from_1 and missing_from_2:\n            msg += \"; \"\n        if missing_from_2:\n            msg += \"missing from sequence 2: \" + \", \".join(\n                repr(i) for i in missing_from_2\n            )\n        return msg\n    missing_from_1, missing_from_2 = compare()\n    if missing_from_1 or missing_from_2:\n        fail(\n            msg_fmt.format(\n                msg=build_message(), first=sequence1, second=sequence2\n            )\n        )",
    "docstring": "Compare the items of two sequences, ignoring order.\n\n    >>> assert_count_equal([1, 2], {2, 1})\n\n    Items missing in either sequence will be listed:\n\n    >>> assert_count_equal([\"a\", \"b\", \"c\"], [\"a\", \"d\"])\n    Traceback (most recent call last):\n        ...\n    AssertionError: missing from sequence 1: 'd'; missing from sequence 2: 'b', 'c'\n\n    Items are counted in each sequence. This makes it useful to detect\n    duplicates:\n\n    >>> assert_count_equal({\"a\", \"b\"}, [\"a\", \"a\", \"b\"])\n    Traceback (most recent call last):\n        ...\n    AssertionError: missing from sequence 1: 'a'\n\n    The following msg_fmt arguments are supported:\n    * msg - the default error message\n    * first - first sequence\n    * second - second sequence"
  },
  {
    "code": "def execute(self, table_name=None, table_mode='create', use_cache=True, priority='interactive',\n              allow_large_results=False, dialect=None, billing_tier=None):\n    job = self.execute_async(table_name=table_name, table_mode=table_mode, use_cache=use_cache,\n                             priority=priority, allow_large_results=allow_large_results,\n                             dialect=dialect, billing_tier=billing_tier)\n    self._results = job.wait()\n    return self._results",
    "docstring": "Initiate the query, blocking until complete and then return the results.\n\n    Args:\n      table_name: the result table name as a string or TableName; if None (the default), then a\n          temporary table will be used.\n      table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request\n          will fail if the table exists.\n      use_cache: whether to use past query results or ignore cache. Has no effect if destination is\n          specified (default True).\n      priority:one of 'batch' or 'interactive' (default). 'interactive' jobs should be scheduled\n          to run quickly but are subject to rate limits; 'batch' jobs could be delayed by as much\n          as three hours but are not rate-limited.\n      allow_large_results: whether to allow large results; i.e. compressed data over 100MB. This is\n          slower and requires a table_name to be specified) (default False).\n      dialect : {'legacy', 'standard'}, default 'legacy'\n          'legacy' : Use BigQuery's legacy SQL dialect.\n          'standard' : Use BigQuery's standard SQL (beta), which is\n          compliant with the SQL 2011 standard.\n      billing_tier: Limits the billing tier for this job. Queries that have resource\n          usage beyond this tier will fail (without incurring a charge). If unspecified, this\n          will be set to your project default. This can also be used to override your\n          project-wide default billing tier on a per-query basis.\n    Returns:\n      The QueryResultsTable for the query.\n    Raises:\n      Exception if query could not be executed."
  },
  {
    "code": "def _draw_rectangle_path(self, context, width, height, only_get_extents=False):\n        c = context\n        c.save()\n        if self.side is SnappedSide.LEFT or self.side is SnappedSide.RIGHT:\n            c.rotate(deg2rad(90))\n        c.rel_move_to(-width / 2., - height / 2.)\n        c.rel_line_to(width, 0)\n        c.rel_line_to(0, height)\n        c.rel_line_to(-width, 0)\n        c.close_path()\n        c.restore()\n        if only_get_extents:\n            extents = c.path_extents()\n            c.new_path()\n            return extents",
    "docstring": "Draws the rectangle path for the port\n\n        The rectangle is correctly rotated. Height therefore refers to the border thickness and width to the length\n        of the port.\n\n        :param context: The context to draw on\n        :param float width: The width of the rectangle\n        :param float height: The height of the rectangle"
  },
  {
    "code": "def model_predictions(self):\n        if isinstance(self.observed, ContinuousColumn):\n            return ValueError(\"Cannot make model predictions on a continuous scale\")\n        pred = np.zeros(self.data_size).astype('object')\n        for node in self:\n            if node.is_terminal:\n                pred[node.indices] = max(node.members, key=node.members.get)\n        return pred",
    "docstring": "Determines the highest frequency of\n        categorical dependent variable in the\n        terminal node where that row fell"
  },
  {
    "code": "def console_width(kwargs):\n    if sys.platform.startswith('win'):\n        console_width = _find_windows_console_width()\n    else:\n        console_width = _find_unix_console_width()\n    _width = kwargs.get('width', None)\n    if _width:\n        console_width = _width\n    else:\n        if not console_width:\n            console_width = 80\n    return console_width",
    "docstring": "Determine console_width."
  },
  {
    "code": "def get_factory_bundle(self, name):\n        with self.__factories_lock:\n            try:\n                factory = self.__factories[name]\n            except KeyError:\n                raise ValueError(\"Unknown factory '{0}'\".format(name))\n            else:\n                factory_context = getattr(\n                    factory, constants.IPOPO_FACTORY_CONTEXT\n                )\n                return factory_context.bundle_context.get_bundle()",
    "docstring": "Retrieves the Pelix Bundle object that registered the given factory\n\n        :param name: The name of a factory\n        :return: The Bundle that registered the given factory\n        :raise ValueError: Invalid factory"
  },
  {
    "code": "def get_uris(self, base_uri, filter_list=None):\n        return {\n            re.sub(r'^/', base_uri, link.attrib['href'])\n            for link in self.parsedpage.get_nodes_by_selector('a')\n            if 'href' in link.attrib and (\n                link.attrib['href'].startswith(base_uri) or\n                link.attrib['href'].startswith('/')\n            ) and\n            not is_uri_to_be_filtered(link.attrib['href'], filter_list)\n        }",
    "docstring": "Return a set of internal URIs."
  },
  {
    "code": "def get_group_details(self, group):\n        result = {}\n        try:\n            lgroup = self._get_group(group.name)\n            lgroup = preload(lgroup, database=self._database)\n        except ObjectDoesNotExist:\n            return result\n        for i, j in lgroup.items():\n            if j is not None:\n                result[i] = j\n        return result",
    "docstring": "Get the group details."
  },
  {
    "code": "def make_qemu_dirs(max_qemu_id, output_dir, topology_name):\n    if max_qemu_id is not None:\n        for i in range(1, max_qemu_id + 1):\n            qemu_dir = os.path.join(output_dir, topology_name + '-files',\n                                    'qemu', 'vm-%s' % i)\n            os.makedirs(qemu_dir)",
    "docstring": "Create Qemu VM working directories if required\n\n    :param int max_qemu_id: Number of directories to create\n    :param str output_dir: Output directory\n    :param str topology_name: Topology name"
  },
  {
    "code": "def apply_request_and_page_to_values(self, request, page=None):\n        value_is_set = False\n        for value in self._values:\n            value.apply_request_and_page(request, page)",
    "docstring": "Use the request and page config to figure out which values are active"
  },
  {
    "code": "def _write_json_blob(encoded_value, pipeline_id=None):\n  default_bucket = app_identity.get_default_gcs_bucket_name()\n  if default_bucket is None:\n    raise Exception(\n      \"No default cloud storage bucket has been set for this application. \"\n      \"This app was likely created before v1.9.0, please see: \"\n      \"https://cloud.google.com/appengine/docs/php/googlestorage/setup\")\n  path_components = ['/', default_bucket, \"appengine_pipeline\"]\n  if pipeline_id:\n    path_components.append(pipeline_id)\n  path_components.append(uuid.uuid4().hex)\n  file_name = posixpath.join(*path_components)\n  with cloudstorage.open(file_name, 'w', content_type='application/json') as f:\n    for start_index in xrange(0, len(encoded_value), _MAX_JSON_SIZE):\n      end_index = start_index + _MAX_JSON_SIZE\n      f.write(encoded_value[start_index:end_index])\n  key_str = blobstore.create_gs_key(\"/gs\" + file_name)\n  logging.debug(\"Created blob for filename = %s gs_key = %s\", file_name, key_str)\n  return blobstore.BlobKey(key_str)",
    "docstring": "Writes a JSON encoded value to a Cloud Storage File.\n\n  This function will store the blob in a GCS file in the default bucket under\n  the appengine_pipeline directory. Optionally using another directory level\n  specified by pipeline_id\n  Args:\n    encoded_value: The encoded JSON string.\n    pipeline_id: A pipeline id to segment files in Cloud Storage, if none,\n      the file will be created under appengine_pipeline\n\n  Returns:\n    The blobstore.BlobKey for the file that was created."
  },
  {
    "code": "def update_from(self, mapping):\n        for key, value in mapping.items():\n            if key in self:\n                if isinstance(value, Parameter):\n                    value = value.value\n                self[key].value = value",
    "docstring": "Updates the set of parameters from a mapping for keys that already exist"
  },
  {
    "code": "def refresh(self):\n        self._changed = False\n        self.es.indices.refresh(index=self.index)",
    "docstring": "Explicitly refresh one or more index, making all operations\n        performed since the last refresh available for search."
  },
  {
    "code": "def check_arguments(cls, conf):\n        try:\n            f = open(conf['file'], \"r\")\n            f.close()\n        except IOError as e:\n            raise ArgsError(\"Cannot open config file '%s': %s\" %\n                            (conf['file'], e))",
    "docstring": "Sanity checks for options needed for configfile mode."
  },
  {
    "code": "def warn(message, category=PsyPlotWarning, logger=None):\n    if logger is not None:\n        message = \"[Warning by %s]\\n%s\" % (logger.name, message)\n    warnings.warn(message, category, stacklevel=3)",
    "docstring": "wrapper around the warnings.warn function for non-critical warnings.\n    logger may be a logging.Logger instance"
  },
  {
    "code": "def clearScreen(cls):\n        if \"win32\" in sys.platform:\n            os.system('cls')\n        elif \"linux\" in sys.platform:\n            os.system('clear')\n        elif 'darwin' in sys.platform:\n            os.system('clear')\n        else:\n            cit.err(\"No clearScreen for \" + sys.platform)",
    "docstring": "Clear the screen"
  },
  {
    "code": "def set_socket_address(self):\n        Global.LOGGER.debug('defining socket addresses for zmq')        \n        random.seed()\n        default_port = random.randrange(5001, 5999)\n        internal_0mq_address = \"tcp://127.0.0.1\"\n        internal_0mq_port_subscriber = str(default_port)\n        internal_0mq_port_publisher = str(default_port)\n        Global.LOGGER.info(str.format(\n            f\"zmq subsystem subscriber on {internal_0mq_port_subscriber} port\"))\n        Global.LOGGER.info(str.format(\n            f\"zmq subsystem publisher on {internal_0mq_port_publisher} port\"))\n        self.subscriber_socket_address = f\"{internal_0mq_address}:{internal_0mq_port_subscriber}\"\n        self.publisher_socket_address = f\"{internal_0mq_address}:{internal_0mq_port_publisher}\"",
    "docstring": "Set a random port to be used by zmq"
  },
  {
    "code": "def redirect_stdout(self, enabled=True, log_level=logging.INFO):\n        if enabled:\n            if self.__stdout_wrapper:\n                self.__stdout_wrapper.update_log_level(log_level=log_level)\n            else:\n                self.__stdout_wrapper = StdOutWrapper(logger=self, log_level=log_level)\n            self.__stdout_stream = self.__stdout_wrapper\n        else:\n            self.__stdout_stream = _original_stdout\n        sys.stdout = self.__stdout_stream",
    "docstring": "Redirect sys.stdout to file-like object."
  },
  {
    "code": "def _validate_handler(column_name, value, predicate_refs):\n    if value is not None:\n        for predicate_ref in predicate_refs:\n            predicate, predicate_name, predicate_args = _decode_predicate_ref(predicate_ref)\n            validate_result = predicate(value, *predicate_args)\n            if isinstance(validate_result, dict) and 'value' in validate_result:\n                value = validate_result['value']\n            elif type(validate_result) != bool:\n                raise Exception(\n                    'predicate (name={}) can only return bool or dict(value=new_value) value'.format(predicate_name))\n            elif not validate_result:\n                raise ModelInvalid(u'db model validate failed: column={}, value={}, predicate={}, arguments={}'.format(\n                    column_name, value, predicate_name, ','.join(map(str, predicate_args))\n                ))\n    return value",
    "docstring": "handle predicate's return value"
  },
  {
    "code": "def attach(self, attachments):\n        if not is_iterable(attachments, generators_allowed=True):\n            attachments = [attachments]\n        for a in attachments:\n            if not a.parent_item:\n                a.parent_item = self\n            if self.id and not a.attachment_id:\n                a.attach()\n            if a not in self.attachments:\n                self.attachments.append(a)",
    "docstring": "Add an attachment, or a list of attachments, to this item. If the item has already been saved, the\n        attachments will be created on the server immediately. If the item has not yet been saved, the attachments will\n        be created on the server the item is saved.\n\n        Adding attachments to an existing item will update the changekey of the item."
  },
  {
    "code": "def add_edge(edges, edge_points, coords, i, j):\n    if (i, j) in edges or (j, i) in edges:\n        return( edges.add((i, j)), edge_points.append(coords[[i, j]]))",
    "docstring": "Add a line between the i-th and j-th points,\n    if not in the list already"
  },
  {
    "code": "def list_tags():\n    ret = set()\n    for item in six.itervalues(images()):\n        if not item.get('RepoTags'):\n            continue\n        ret.update(set(item['RepoTags']))\n    return sorted(ret)",
    "docstring": "Returns a list of tagged images\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion docker.list_tags"
  },
  {
    "code": "def get_device_state(self, device, id_override=None, type_override=None):\n        _LOGGER.info(\"Getting state via online API\")\n        object_id = id_override or device.object_id()\n        object_type = type_override or device.object_type()\n        url_string = \"{}/{}s/{}\".format(self.BASE_URL,\n                                        object_type, object_id)\n        arequest = requests.get(url_string, headers=API_HEADERS)\n        response_json = arequest.json()\n        _LOGGER.debug('%s', response_json)\n        return response_json",
    "docstring": "Get device state via online API.\n\n        Args:\n            device (WinkDevice): The device the change is being requested for.\n            id_override (String, optional): A device ID used to override the\n                passed in device's ID. Used to make changes on sub-devices.\n                i.e. Outlet in a Powerstrip. The Parent device's ID.\n            type_override (String, optional): Used to override the device type\n                when a device inherits from a device other than WinkDevice.\n        Returns:\n            response_json (Dict): The API's response in dictionary format"
  },
  {
    "code": "def is_dir(self):\n        try:\n            return S_ISDIR(self.stat().st_mode)\n        except OSError as e:\n            if e.errno not in (ENOENT, ENOTDIR):\n                raise\n            return False",
    "docstring": "Whether this path is a directory."
  },
  {
    "code": "def get(self, sid):\n        return DomainContext(self._version, account_sid=self._solution['account_sid'], sid=sid, )",
    "docstring": "Constructs a DomainContext\n\n        :param sid: The unique string that identifies the resource\n\n        :returns: twilio.rest.api.v2010.account.sip.domain.DomainContext\n        :rtype: twilio.rest.api.v2010.account.sip.domain.DomainContext"
  },
  {
    "code": "def _merge_dict(self, global_dict, local_dict):\n        global_dict = global_dict.copy()\n        for key in local_dict.keys():\n            if key in global_dict:\n                global_dict[key] = self._do_merge(global_dict[key], local_dict[key])\n            else:\n                global_dict[key] = local_dict[key]\n        return global_dict",
    "docstring": "Merges the two dictionaries together\n\n        :param global_dict: Global dictionary to be merged\n        :param local_dict: Local dictionary to be merged\n        :return: New merged dictionary with values shallow copied"
  },
  {
    "code": "def getFilename(name):\n    name = re.sub(r\"[^0-9a-zA-Z_\\-\\.]\", \"_\", name)\n    while \"..\" in name:\n        name = name.replace('..', '.')\n    while \"__\" in name:\n        name = name.replace('__', '_')\n    if name.startswith((\".\", \"-\")):\n        name = name[1:]\n    return name",
    "docstring": "Get a filename from given name without dangerous or incompatible characters."
  },
  {
    "code": "def der_cert(der_data):\n    if isinstance(der_data, str):\n        der_data = bytes(der_data, 'utf-8')\n    return x509.load_der_x509_certificate(der_data, default_backend())",
    "docstring": "Load a DER encoded certificate\n\n    :param der_data: DER-encoded certificate\n    :return: A cryptography.x509.certificate instance"
  },
  {
    "code": "def _make_patterns(patterns):\n    field_registry = display_fields.FieldRegistry()\n    pattern_list = display_pattern.ScreenPatternList(\n        field_registry=field_registry,\n    )\n    for pattern in patterns:\n        pattern_list.add(pattern.split('\\n'))\n    return pattern_list",
    "docstring": "Create a ScreenPatternList from a given pattern text.\n\n    Args:\n        pattern_txt (str list): the patterns\n\n    Returns:\n        mpdlcd.display_pattern.ScreenPatternList: a list of patterns from the\n            given entries."
  },
  {
    "code": "def standalone_from_launchable(cls, launch):\n        attrs = copy.copy(launch.el_attrs)\n        del attrs[\"Type\"]\n        if attrs.has_key(\"DependsOn\"):\n            del attrs[\"DependsOn\"]\n        if attrs[\"Properties\"].has_key(\"SpotPrice\"):\n            del attrs[\"Properties\"][\"SpotPrice\"]\n        if attrs[\"Properties\"].has_key(\"InstanceMonitoring\"):\n            del attrs[\"Properties\"][\"InstanceMonitoring\"]\n        if attrs[\"Properties\"].has_key(\"SecurityGroups\"):\n            del attrs[\"Properties\"][\"SecurityGroups\"]\n        if attrs[\"Properties\"].has_key(\"InstanceId\"):\n            raise RuntimeError(\"Can't make instance from launchable containing InstanceId property\")\n        inst = EC2Instance(**attrs)\n        inst.iscm = launch.iscm\n        return inst",
    "docstring": "Given a launchable resource, create a definition of a standalone\n        instance, which doesn't depend on or contain references to other\n        elements."
  },
  {
    "code": "def to_json(self):\n        result = {\n            'name': self.name,\n            'id': self._real_id(),\n            'type': self.type,\n            'localized': self.localized,\n            'omitted': self.omitted,\n            'required': self.required,\n            'disabled': self.disabled,\n            'validations': [v.to_json() for v in self.validations]\n        }\n        if self.type == 'Array':\n            result['items'] = self.items\n        if self.type == 'Link':\n            result['linkType'] = self.link_type\n        return result",
    "docstring": "Returns the JSON Representation of the content type field."
  },
  {
    "code": "def copy(self):\n        properties = {}\n        for key, value in self.raw_values.items():\n            if key in self.UnhashableOptions:\n                properties[key] = value\n            else:\n                properties[key] = copy.copy(value)\n        return Context(**properties)",
    "docstring": "Returns a copy of this database option set.\n\n        :return     <orb.Context>"
  },
  {
    "code": "def dict_to_literal(dict_container: dict):\n    if isinstance(dict_container[\"@value\"], int):\n        return dict_container[\"@value\"],\n    else:\n        return dict_container[\"@value\"], dict_container.get(\"@language\", None)",
    "docstring": "Transforms a JSON+LD PyLD dictionary into\n    an RDFLib object"
  },
  {
    "code": "def set_energy_range(self, logemin, logemax):\n        if logemin is None:\n            logemin = self.log_energies[0]\n        else:\n            imin = int(utils.val_to_edge(self.log_energies, logemin)[0])\n            logemin = self.log_energies[imin]\n        if logemax is None:\n            logemax = self.log_energies[-1]\n        else:\n            imax = int(utils.val_to_edge(self.log_energies, logemax)[0])\n            logemax = self.log_energies[imax]\n        self._loge_bounds = np.array([logemin, logemax])\n        self._roi_data['loge_bounds'] = np.copy(self.loge_bounds)\n        for c in self.components:\n            c.set_energy_range(logemin, logemax)\n        return self._loge_bounds",
    "docstring": "Set the energy bounds of the analysis.  This restricts the\n        evaluation of the likelihood to the data that falls in this\n        range.  Input values will be rounded to the closest bin edge\n        value.  If either argument is None then the lower or upper\n        bound of the analysis instance will be used.\n\n        Parameters\n        ----------\n\n        logemin : float\n           Lower energy bound in log10(E/MeV).\n\n        logemax : float\n           Upper energy bound in log10(E/MeV).\n\n        Returns\n        -------\n\n        eminmax : array\n           Minimum and maximum energy in log10(E/MeV)."
  },
  {
    "code": "def config_hook(self, func):\n        argspec = inspect.getargspec(func)\n        args = ['config', 'command_name', 'logger']\n        if not (argspec.args == args and argspec.varargs is None and\n                argspec.keywords is None and argspec.defaults is None):\n            raise ValueError('Wrong signature for config_hook. Expected: '\n                             '(config, command_name, logger)')\n        self.config_hooks.append(func)\n        return self.config_hooks[-1]",
    "docstring": "Decorator to add a config hook to this ingredient.\n\n        Config hooks need to be a function that takes 3 parameters and returns\n        a dictionary:\n        (config, command_name, logger) --> dict\n\n        Config hooks are run after the configuration of this Ingredient, but\n        before any further ingredient-configurations are run.\n        The dictionary returned by a config hook is used to update the\n        config updates.\n        Note that they are not restricted to the local namespace of the\n        ingredient."
  },
  {
    "code": "def last_job_statuses(self) -> List[str]:\n        statuses = []\n        for status in self.jobs.values_list('status__status', flat=True):\n            if status is not None:\n                statuses.append(status)\n        return statuses",
    "docstring": "The last constants of the job in this experiment."
  },
  {
    "code": "async def create(self, **kwargs):\n        try:\n            obj = self._meta.object_class()\n            self.data.update(kwargs)\n            await obj.deserialize(self.data)\n            await obj.insert(db=self.db)\n            return await obj.serialize()\n        except Exception as ex:\n            logger.exception(ex)\n            raise BadRequest(ex)",
    "docstring": "Corresponds to POST request without a resource identifier, inserting a document into the database"
  },
  {
    "code": "def insert(self, thread):\n        thread_id = thread['id']\n        title = thread['title']\n        self.db.threads.new(thread_id, title)\n        comments = list(map(self._build_comment, thread['comments']))\n        comments.sort(key=lambda comment: comment['id'])\n        self.count += len(comments)\n        for comment in comments:\n            self.db.comments.add(thread_id, comment)",
    "docstring": "Process a thread and insert its comments in the DB."
  },
  {
    "code": "def build_joblist(jobgraph):\n    jobset = set()\n    for job in jobgraph:\n        jobset = populate_jobset(job, jobset, depth=1)\n    return list(jobset)",
    "docstring": "Returns a list of jobs, from a passed jobgraph."
  },
  {
    "code": "def html_for_modules_method(method_name, *args, **kwargs):\n    method = getattr(modules, method_name)\n    value = method(*args, **kwargs)\n    return KEY_VALUE_TEMPLATE.format(method_name, value)",
    "docstring": "Returns an HTML snippet for a Modules API method.\n\n    Args:\n        method_name: A string containing a Modules API method.\n        args: Positional arguments to be passed to the method.\n        kwargs: Keyword arguments to be passed to the method.\n\n    Returns:\n        String HTML representing the Modules API method and value."
  },
  {
    "code": "def filter(self, source_file, encoding):\n        with codecs.open(source_file, 'r', encoding=encoding) as f:\n            text = f.read()\n        return [filters.SourceText(self._filter(text), source_file, encoding, 'context')]",
    "docstring": "Parse file."
  },
  {
    "code": "def is_running(config, container, *args, **kwargs):\n    try:\n        infos = _get_container_infos(config, container)\n        return (infos if infos.get('State', {}).get('Running') else None)\n    except Exception:\n        return None",
    "docstring": "Is this container running\n\n    container\n        Container id\n\n    Return container"
  },
  {
    "code": "def error(name=None, message=''):\n    ret = {}\n    if name is not None:\n        salt.utils.error.raise_error(name=name, message=message)\n    return ret",
    "docstring": "If name is None Then return empty dict\n\n    Otherwise raise an exception with __name__ from name, message from message\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-wheel error\n        salt-wheel error.error name=\"Exception\" message=\"This is an error.\""
  },
  {
    "code": "def minmax(arrays, masks=None, dtype=None, out=None, zeros=None,\n           scales=None, weights=None, nmin=1, nmax=1):\n    return generic_combine(intl_combine.minmax_method(nmin, nmax), arrays,\n                           masks=masks, dtype=dtype, out=out,\n                           zeros=zeros, scales=scales, weights=weights)",
    "docstring": "Combine arrays using mix max rejection, with masks.\n\n    Inputs and masks are a list of array objects. All input arrays\n    have the same shape. If present, the masks have the same shape\n    also.\n\n    The function returns an array with one more dimension than the\n    inputs and with size (3, shape). out[0] contains the mean,\n    out[1] the variance and out[2] the number of points used.\n\n    :param arrays: a list of arrays\n    :param masks: a list of mask arrays, True values are masked\n    :param dtype: data type of the output\n    :param out: optional output, with one more axis than the input arrays\n    :param nmin:\n    :param nmax:\n    :return: mean, variance of the mean and number of points stored"
  },
  {
    "code": "def reset_internal_states(self, record=None):\n        self._record = None\n        self._count = 0\n        self._record = record",
    "docstring": "Resets the internal state of the recorder.\n\n        Args:\n            record: records.TestResultRecord, the test record for a test."
  },
  {
    "code": "def _search_env(keys):\n\t\tmatches = (os.environ[key] for key in keys if key in os.environ)\n\t\treturn next(matches, None)",
    "docstring": "Search the environment for the supplied keys, returning the first\n\t\tone found or None if none was found."
  },
  {
    "code": "def validate_email(email, partial_match=False):\n    rgx = re.compile(RGX_EMAIL_VALIDATION_PATTERN, re.I)\n    if partial_match:\n        return rgx.search(email) is not None\n    else:\n        return rgx.match(email) is not None",
    "docstring": "Perform email address validation\n\n    >>> validate_email('akjaer@riotgames.com')\n    True\n    >>> validate_email('Asbjorn Kjaer <akjaer@riotgames.com')\n    False\n    >>> validate_email('Asbjorn Kjaer <akjaer@riotgames.com', partial_match=True)\n    True\n\n    Args:\n        email (str): Email address to match\n        partial_match (bool): If False (default), the entire string must be a valid email address. If true, any valid\n         email address in the string will trigger a valid response\n\n    Returns:\n        True if the value contains an email address, else False"
  },
  {
    "code": "def data_nodes(self):\n        return {k: v for k, v in self.nodes.items() if v['type'] == 'data'}",
    "docstring": "Returns all data nodes of the dispatcher.\n\n        :return:\n            All data nodes of the dispatcher.\n        :rtype: dict[str, dict]"
  },
  {
    "code": "def get_date_info(value):\n    fmt = _get_date_format(value)\n    dt_value = _datetime_obj_factory(value, fmt)\n    return dt_value, fmt",
    "docstring": "Returns the datetime object and the format of the date in input\n\n    :type value: `str`"
  },
  {
    "code": "def _add_condition(self, operator, operand, types):\n        if not self.current_field:\n            raise QueryMissingField(\"Conditions requires a field()\")\n        elif not type(operand) in types:\n            caller = inspect.currentframe().f_back.f_code.co_name\n            raise QueryTypeError(\"Invalid type passed to %s() , expected: %s\" % (caller, types))\n        elif self.c_oper:\n            raise QueryMultipleExpressions(\"Expected logical operator after expression\")\n        self.c_oper = inspect.currentframe().f_back.f_code.co_name\n        self._query.append(\"%(current_field)s%(operator)s%(operand)s\" % {\n                               'current_field': self.current_field,\n                               'operator': operator,\n                               'operand': operand\n        })\n        return self",
    "docstring": "Appends condition to self._query after performing validation\n\n        :param operator: operator (str)\n        :param operand: operand\n        :param types: allowed types\n        :raise:\n            - QueryMissingField: if a field hasn't been set\n            - QueryMultipleExpressions: if a condition already has been set\n            - QueryTypeError: if the value is of an unexpected type"
  },
  {
    "code": "def make_key(*criteria):\n    criteria = [stringify(c) for c in criteria]\n    criteria = [c for c in criteria if c is not None]\n    if len(criteria):\n        return ':'.join(criteria)",
    "docstring": "Make a string key out of many criteria."
  },
  {
    "code": "def remove_remote_subnet(self, context_id, subnet_id):\n        return self.context.removeCustomerSubnetFromNetworkTunnel(subnet_id,\n                                                                  id=context_id)",
    "docstring": "Removes a remote subnet from a tunnel context.\n\n        :param int context_id: The id-value representing the context instance.\n        :param int subnet_id: The id-value representing the remote subnet.\n        :return bool: True if remote subnet removal was successful."
  },
  {
    "code": "def normalized_rgb(self):\n        r\n        r1 = self._r / 255\n        g1 = self._g / 255\n        b1 = self._b / 255\n        if r1 <= 0.03928:\n            r2 = r1 / 12.92\n        else:\n            r2 = math.pow(((r1 + 0.055) / 1.055), 2.4)\n        if g1 <= 0.03928:\n            g2 = g1 / 12.92\n        else:\n            g2 = math.pow(((g1 + 0.055) / 1.055), 2.4)\n        if b1 <= 0.03928:\n            b2 = b1 / 12.92\n        else:\n            b2 = math.pow(((b1 + 0.055) / 1.055), 2.4)\n        return (r2, g2, b2)",
    "docstring": "r\"\"\"\n        Returns a tuples of the normalized values of the red, green, and blue\n        channels of the Colour.\n\n        Returns:\n            tuple: the rgb values of the colour (with values normalized between\n                   0.0 and 1.0)\n\n        .. note::\n\n            Uses the formula:\n\n            \\\\[ r_{norm} = \\\\begin{cases}\n            \\\\frac{r_{255}}{12.92}\\\\ \\\\qquad &\\\\text{if $r_{255}$ $\\\\le$ 0.03928}\n            \\\\\\\\\n            \\\\left(\\\\frac{r_{255} + 0.055}{1.055}\\\\right)^{2.4}\n            \\\\quad &\\\\text{otherwise}\n            \\\\end{cases} \\\\]\n\n        `Source <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef>`_"
  },
  {
    "code": "def add_relation(self, source, destination):\n        if self.in_sources(source):\n            if self.forward[source] != destination:\n                raise ValueError(\"Source is already in use. Destination does \"\n                                 \"not match.\")\n            else:\n                raise ValueError(\"Source-Destination relation already exists.\")\n        elif self.in_destinations(destination):\n            raise ValueError(\"Destination is already in use. Source does not \"\n                             \"match.\")\n        else:\n            self.forward[source] = destination\n            self.reverse[destination] = source",
    "docstring": "Add new a relation to the bejection"
  },
  {
    "code": "def transitingPlanets(self):\n        transitingPlanets = []\n        for planet in self.planets:\n            try:\n                if planet.isTransiting:\n                    transitingPlanets.append(planet)\n            except KeyError:\n                pass\n        return transitingPlanets",
    "docstring": "Returns a list of transiting planet objects"
  },
  {
    "code": "def normalize_node(node, headers=None):\n    headers = {} if headers is None else headers\n    if isinstance(node, str):\n        url = normalize_url(node)\n        return {'endpoint': url, 'headers': headers}\n    url = normalize_url(node['endpoint'])\n    node_headers = node.get('headers', {})\n    return {'endpoint': url, 'headers': {**headers, **node_headers}}",
    "docstring": "Normalizes given node as str or dict with headers"
  },
  {
    "code": "def interrupt (aggregate):\n    while True:\n        try:\n            log.warn(LOG_CHECK,\n               _(\"interrupt; waiting for active threads to finish\"))\n            log.warn(LOG_CHECK,\n               _(\"another interrupt will exit immediately\"))\n            abort(aggregate)\n            break\n        except KeyboardInterrupt:\n            pass",
    "docstring": "Interrupt execution and shutdown, ignoring any subsequent\n    interrupts."
  },
  {
    "code": "def parse_qs(s, rx, parsef=None, length=2, quote=False):\n    if type(rx) != str:\n        rx = rx.pattern;\n    if re.match(\" *\\(.*\\)\", s):\n        if not parsef:\n            if parse_utuple(s,rx,length=length):\n                if quote:\n                    s=quote_subs(s);\n                return evalt(s);\n            else:\n                raise ValueError(\"{} did is not a valid tuple of {}\".format(\n                    s, rx));\n        else:\n            return parsef(s,length=length);\n    elif re.match('^ *{} *$'.format(rx), s):\n        if quote:\n            return eval('[\"{}\"]'.format(s));\n        return eval('[{}]'.format(s));\n    else:\n        raise ValueError(\"{} does not match '{}' or the passed parsef\".format(\n            s,rx));",
    "docstring": "helper for parsing a string that can both rx or parsef\n       which is obstensibly the parsef for rx.\n\n       Use parse colors for color tuples. This won't work with\n       those."
  },
  {
    "code": "def output_reference(self, name):\n        if name not in self.output_names:\n            raise ValueError('Invalid output \"{}\"'.format(name))\n        return Reference(step_name=self.name_in_workflow, output_name=name)",
    "docstring": "Return a reference to the given output for use in an input\n            of a next Step.\n\n        For a Step named `echo` that has an output called `echoed`, the\n        reference `echo/echoed` is returned.\n\n        Args:\n            name (str): the name of the Step output\n        Raises:\n            ValueError: The name provided is not a valid output name for this\n                Step."
  },
  {
    "code": "def get_value(self, property_name):\n        log = logging.getLogger(self.cls_logger + '.get_value')\n        if not isinstance(property_name, basestring):\n            log.error('property_name arg is not a string, found type: {t}'.format(t=property_name.__class__.__name__))\n            return None\n        prop = self.get_property(property_name)\n        if not prop:\n            log.debug('Property name not found matching: {n}'.format(n=property_name))\n            return None\n        value = self.properties[prop]\n        log.debug('Found value for property {n}: {v}'.format(n=property_name, v=value))\n        return value",
    "docstring": "Returns the value associated to the passed property\n\n        This public method is passed a specific property as a string\n        and returns the value of that property. If the property is not\n        found, None will be returned.\n\n        :param property_name (str) The name of the property\n        :return: (str) value for the passed property, or None."
  },
  {
    "code": "def redis_version(self):\n        if not hasattr(self, '_redis_version'):\n            self._redis_version = tuple(\n                map(int, self.connection.info().get('redis_version').split('.')[:3])\n            )\n        return self._redis_version",
    "docstring": "Return the redis version as a tuple"
  },
  {
    "code": "def create_tool(self, task):\n        gp_tool = dict(taskName=task.name,\n                       taskDisplayName=task.display_name,\n                       taskDescription=task.description,\n                       canRunInBackground=True,\n                       taskUri=task.uri)\n        gp_tool['execute'] = self._execute_template.substitute(gp_tool)\n        gp_tool['parameterInfo'] = param_builder.create_param_info(task.parameters,\n                                                                   self.parameter_map)\n        gp_tool['updateParameter'] = param_builder.create_update_parameter(task.parameters,\n                                                                           self.parameter_map)\n        gp_tool['preExecute'] = param_builder.create_pre_execute(task.parameters,\n                                                                 self.parameter_map)\n        gp_tool['postExecute'] = param_builder.create_post_execute(task.parameters,\n                                                                   self.parameter_map)\n        return self._tool_template.substitute(gp_tool)",
    "docstring": "Creates a new GPTool for the toolbox."
  },
  {
    "code": "def _defaults():\n    d = {}\n    d['url'] = os.environ.get('BUGZSCOUT_URL')\n    d['user'] = os.environ.get('BUGZSCOUT_USER')\n    d['project'] = os.environ.get('BUGZSCOUT_PROJECT')\n    d['area'] = os.environ.get('BUGZSCOUT_AREA')\n    return d",
    "docstring": "Returns a dict of default args from the environment, which can be\n    overridden by command line args."
  },
  {
    "code": "def _jseq(self, cols, converter=None):\n        return _to_seq(self.sql_ctx._sc, cols, converter)",
    "docstring": "Return a JVM Seq of Columns from a list of Column or names"
  },
  {
    "code": "def lazy_property(func):\n    attr_name = '_lazy_' + func.__name__\n    @property\n    def _lazy_property(self):\n        if not hasattr(self, attr_name):\n            setattr(self, attr_name, func(self))\n        return getattr(self, attr_name)\n    @_lazy_property.deleter\n    def _lazy_property(self):\n        if hasattr(self, attr_name):\n            delattr(self, attr_name)\n    @_lazy_property.setter\n    def _lazy_property(self, value):\n        setattr(self, attr_name, value)\n    return _lazy_property",
    "docstring": "Wraps a property to provide lazy evaluation. Eliminates boilerplate.\n    Also provides for setting and deleting the property.\n\n    Use as you would use the @property decorator::\n\n        # OLD:\n        class MyClass():\n            def __init__():\n                self._compute = None\n\n            @property\n            def compute(self):\n                if self._compute is None:\n                    # computationally intense stuff\n                    # ...\n                    # ...\n                    self._compute = result\n                return self._compute\n\n            @compute.setter\n            def compute(self, value):\n                self._compute = value\n\n\n        # NEW:\n        class MyClass():\n\n            def __init__():\n                pass\n\n            @lazy_property\n            def compute(self):\n                # computationally intense stuff\n                # ...\n                # ...\n                return result\n\n    .. note:\n\n        Properties wrapped with ``lazy_property`` are only evaluated once.\n        If the instance state changes, lazy properties will not be automatically\n        re-evaulated and the update must be explicitly called for::\n\n            c = MyClass(data)\n            prop = c.lazy_property\n\n            # If you update some data that affects c.lazy_property\n            c.data = new_data\n\n            # c.lazy_property won't change\n            prop == c.lazy_property  # TRUE\n\n            # If you want to update c.lazy_property, you can delete it, which will\n            # force it to be recomputed (with the new data) the next time you use it\n            del c.lazy_property\n            new_prop = c.lazy_property\n            new_prop == prop  # FALSE"
  },
  {
    "code": "def update_matches(self, other):\n        for match in self.error_matches.all():\n            other_matches = TextLogErrorMatch.objects.filter(\n                classified_failure=other,\n                text_log_error=match.text_log_error,\n            )\n            if not other_matches:\n                match.classified_failure = other\n                match.save(update_fields=['classified_failure'])\n                continue\n            other_matches.filter(score__lt=match.score).update(score=match.score)\n            yield match.id",
    "docstring": "Update this instance's Matches to point to the given other's Matches.\n\n        Find Matches with the same TextLogError as our Matches, updating their\n        score if less than ours and mark our matches for deletion.\n\n        If there are no other matches, update ours to point to the other\n        ClassifiedFailure."
  },
  {
    "code": "def get_method_analysis_by_name(self, class_name, method_name, method_descriptor):\n        method = self.get_method_by_name(class_name, method_name, method_descriptor)\n        if method:\n            return self.get_method_analysis(method)\n        return None",
    "docstring": "Returns the crossreferencing object for a given method.\n\n        This function is similar to :meth:`~get_method_analysis`, with the difference\n        that you can look up the Method by name\n\n        :param class_name: name of the class, for example `'Ljava/lang/Object;'`\n        :param method_name: name of the method, for example `'onCreate'`\n        :param method_descriptor: method descriptor, for example `'(I I)V'`\n        :return: :class:`MethodClassAnalysis`"
  },
  {
    "code": "def bfloat16_activations_var_getter(getter, *args, **kwargs):\n  requested_dtype = kwargs[\"dtype\"]\n  if requested_dtype == tf.bfloat16:\n    kwargs[\"dtype\"] = tf.float32\n  var = getter(*args, **kwargs)\n  if var.dtype.base_dtype != requested_dtype:\n    var = tf.cast(var, requested_dtype)\n  return var",
    "docstring": "A custom getter function for float32 parameters and bfloat16 activations.\n\n  Args:\n    getter: custom getter\n    *args: arguments\n    **kwargs: keyword arguments\n  Returns:\n    variables with the correct dtype.\n  Raises:\n    KeyError: if \"dtype\" is not provided as a kwarg."
  },
  {
    "code": "def is_convertible_with(self, other):\n        other = as_dimension(other)\n        return self._value is None or other.value is None or self._value == other.value",
    "docstring": "Returns true if `other` is convertible with this Dimension.\n\n        Two known Dimensions are convertible if they have the same value.\n        An unknown Dimension is convertible with all other Dimensions.\n\n        Args:\n          other: Another Dimension.\n\n        Returns:\n          True if this Dimension and `other` are convertible."
  },
  {
    "code": "def save(self):\n        headers = {}\n        headers.setdefault('Content-Type', 'application/json')\n        if not self.exists():\n            self.create()\n            return\n        put_resp = self.r_session.put(\n            self.document_url,\n            data=self.json(),\n            headers=headers\n        )\n        put_resp.raise_for_status()\n        data = response_to_json_dict(put_resp)\n        super(Document, self).__setitem__('_rev', data['rev'])\n        return",
    "docstring": "Saves changes made to the locally cached Document object's data\n        structures to the remote database.  If the document does not exist\n        remotely then it is created in the remote database.  If the object\n        does exist remotely then the document is updated remotely.  In either\n        case the locally cached Document object is also updated accordingly\n        based on the successful response of the operation."
  },
  {
    "code": "def prepare(self, session, event):\n        if not event:\n            self.logger.warn(\"event empty!\")\n            return\n        sp_key, sp_hkey = self._keygen(session)\n        def _pk(obj):\n            pk_values = tuple(getattr(obj, c.name)\n                              for c in obj.__mapper__.primary_key)\n            if len(pk_values) == 1:\n                return pk_values[0]\n            return pk_values\n        def _get_dump_value(value):\n            if hasattr(value, '__mapper__'):\n                return _pk(value)\n            return value\n        pickled_event = {\n            k: pickle.dumps({_get_dump_value(obj) for obj in objs})\n            for k, objs in event.items()}\n        with self.r.pipeline(transaction=False) as p:\n            p.sadd(sp_key, session.meepo_unique_id)\n            p.hmset(sp_hkey, pickled_event)\n            p.execute()",
    "docstring": "Prepare phase for session.\n\n        :param session: sqlalchemy session"
  },
  {
    "code": "async def unlock(self, key, value, *, flags=None, session):\n        value = encode_value(value, flags)\n        session_id = extract_attr(session, keys=[\"ID\"])\n        response = await self._write(key, value,\n                                     flags=flags,\n                                     release=session_id)\n        return response.body is True",
    "docstring": "Unlocks the Key with the given Session.\n\n        Parameters:\n            key (str): Key to set\n            value (Payload): Value to set, It will be encoded by flags\n            session (ObjectID): Session ID\n            flags (int): Flags to set with value\n        Response:\n            bool: ``True`` on success\n\n        The Key will only release the lock if the Session is valid and\n        currently has it locked."
  },
  {
    "code": "def _get_default_field_kwargs(model, field):\n        kwargs = {}\n        try:\n            field_name = field.model_attr or field.index_fieldname\n            model_field = model._meta.get_field(field_name)\n            kwargs.update(get_field_kwargs(field_name, model_field))\n            delete_attrs = [\n                \"allow_blank\",\n                \"choices\",\n                \"model_field\",\n                \"allow_unicode\",\n            ]\n            for attr in delete_attrs:\n                if attr in kwargs:\n                    del kwargs[attr]\n        except FieldDoesNotExist:\n            pass\n        return kwargs",
    "docstring": "Get the required attributes from the model field in order\n        to instantiate a REST Framework serializer field."
  },
  {
    "code": "def find_compilation_database(path):\n  result = './'\n  while not os.path.isfile(os.path.join(result, path)):\n    if os.path.realpath(result) == '/':\n      print('Error: could not find compilation database.')\n      sys.exit(1)\n    result += '../'\n  return os.path.realpath(result)",
    "docstring": "Adjusts the directory until a compilation database is found."
  },
  {
    "code": "def add(self, entities):\n        if not utils.is_list_like(entities):\n            entities = itertools.chain(\n                getattr(entities, 'chats', []),\n                getattr(entities, 'users', []),\n                (hasattr(entities, 'user') and [entities.user]) or []\n            )\n        for entity in entities:\n            try:\n                pid = utils.get_peer_id(entity)\n                if pid not in self.__dict__:\n                    self.__dict__[pid] = utils.get_input_peer(entity)\n            except TypeError:\n                pass",
    "docstring": "Adds the given entities to the cache, if they weren't saved before."
  },
  {
    "code": "def info_1(*tokens: Token, **kwargs: Any) -> None:\n    info(bold, blue, \"::\", reset, *tokens, **kwargs)",
    "docstring": "Print an important informative message"
  },
  {
    "code": "def greedy_merge_helper(\n        variant_sequences,\n        min_overlap_size=MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE):\n    merged_variant_sequences = {}\n    merged_any = False\n    unmerged_variant_sequences = set(variant_sequences)\n    for i in range(len(variant_sequences)):\n        sequence1 = variant_sequences[i]\n        for j in range(i + 1, len(variant_sequences)):\n            sequence2 = variant_sequences[j]\n            combined = sequence1.combine(sequence2)\n            if combined is None:\n                continue\n            if combined.sequence in merged_variant_sequences:\n                existing = merged_variant_sequences[combined.sequence]\n                combined = combined.add_reads(existing.reads)\n            merged_variant_sequences[combined.sequence] = combined\n            unmerged_variant_sequences.discard(sequence1)\n            unmerged_variant_sequences.discard(sequence2)\n            merged_any = True\n    result = list(merged_variant_sequences.values()) + list(unmerged_variant_sequences)\n    return result, merged_any",
    "docstring": "Returns a list of merged VariantSequence objects, and True if any\n    were successfully merged."
  },
  {
    "code": "def find_nodes(self, query_dict=None, exact=False, verbose=False, **kwargs):\n        assert self.use_v1\n        return self._do_query('{p}/singlePropertySearchForTreeNodes'.format(p=self.query_prefix),\n                              query_dict=query_dict,\n                              exact=exact,\n                              verbose=verbose,\n                              valid_keys=self.node_search_term_set,\n                              kwargs=kwargs)",
    "docstring": "Query on node properties. See documentation for _OTIWrapper class."
  },
  {
    "code": "def include_version(global_root: str, version_obj: models.Version, hardlink:bool=True):\n    global_root_dir = Path(global_root)\n    if version_obj.included_at:\n        raise VersionIncludedError(f\"version included on {version_obj.included_at}\")\n    version_root_dir = global_root_dir / version_obj.relative_root_dir\n    version_root_dir.mkdir(parents=True, exist_ok=True)\n    log.info(f\"created new bundle version dir: {version_root_dir}\")\n    for file_obj in version_obj.files:\n        file_obj_path = Path(file_obj.path)\n        new_path = version_root_dir / file_obj_path.name\n        if hardlink:\n            os.link(file_obj_path.resolve(), new_path)\n        else:\n            os.symlink(file_obj_path.resolve(), new_path)\n        log.info(f\"linked file: {file_obj.path} -> {new_path}\")\n        file_obj.path = str(new_path).replace(f\"{global_root_dir}/\", '', 1)",
    "docstring": "Include files in existing bundle version."
  },
  {
    "code": "def disable_availability_zones(self, load_balancer_name, zones_to_remove):\n        params = {'LoadBalancerName' : load_balancer_name}\n        self.build_list_params(params, zones_to_remove,\n                               'AvailabilityZones.member.%d')\n        return self.get_list('DisableAvailabilityZonesForLoadBalancer',\n                             params, None)",
    "docstring": "Remove availability zones from an existing Load Balancer.\n        All zones must be in the same region as the Load Balancer.\n        Removing zones that are not registered with the Load Balancer\n        has no effect.\n        You cannot remove all zones from an Load Balancer.\n\n        :type load_balancer_name: string\n        :param load_balancer_name: The name of the Load Balancer\n\n        :type zones: List of strings\n        :param zones: The name of the zone(s) to remove.\n\n        :rtype: List of strings\n        :return: An updated list of zones for this Load Balancer."
  },
  {
    "code": "def load(cls, cache_file, backend=None):\n        with open(cache_file, 'rb') as pickle_fh:\n            (remote, backend_name, max_sleep_interval, job_id, status,\n             epilogue, ssh, scp) = pickle.load(pickle_fh)\n        if backend is None:\n            backend = JobScript._backends[backend_name]\n        ar = cls(backend)\n        (ar.remote, ar.max_sleep_interval, ar.job_id, ar._status, ar.epilogue,\n         ar.ssh, ar.scp) \\\n            = (remote, max_sleep_interval, job_id, status, epilogue, ssh, scp)\n        ar.cache_file = cache_file\n        return ar",
    "docstring": "Instantiate AsyncResult from  dumped `cache_file`.\n\n        This is the inverse of :meth:`dump`.\n\n        Parameters\n        ----------\n\n            cache_file: str\n                Name of file from which the run should be read.\n\n            backend: clusterjob.backends.ClusterjobBackend or None\n                The backend instance for the job. If None, the backend will be\n                determined by the *name* of the dumped job's backend."
  },
  {
    "code": "def get_pidfile(pidfile):\n    try:\n        with salt.utils.files.fopen(pidfile) as pdf:\n            pid = pdf.read().strip()\n        return int(pid)\n    except (OSError, IOError, TypeError, ValueError):\n        return -1",
    "docstring": "Return the pid from a pidfile as an integer"
  },
  {
    "code": "def save(self):\n        self.session.add(self)\n        self.session.flush()\n        return self",
    "docstring": "Saves the updated model to the current entity db."
  },
  {
    "code": "def _check_if_tag_already_exists(self):\n        version = self.data['new_version']\n        if self.vcs.tag_exists(version):\n            return True\n        else:\n            return False",
    "docstring": "Check if tag already exists and show the difference if so"
  },
  {
    "code": "def _cast_to_type(self, value):\n        if isinstance(value, datetime.datetime):\n            return value.date()\n        if isinstance(value, datetime.date):\n            return value\n        try:\n            value = date_parser(value)\n            return value.date()\n        except ValueError:\n            self.fail('invalid', value=value)",
    "docstring": "Convert the value to a date and raise error on failures"
  },
  {
    "code": "def nic_v1(msg, NICs):\n    if typecode(msg) < 5 or typecode(msg) > 22:\n        raise RuntimeError(\n            \"%s: Not a surface position message (5<TC<8), \\\n            airborne position message (8<TC<19), \\\n            or airborne position with GNSS height (20<TC<22)\" % msg\n        )\n    tc = typecode(msg)\n    NIC = uncertainty.TC_NICv1_lookup[tc]\n    if isinstance(NIC, dict):\n        NIC = NIC[NICs]\n    try:\n        Rc = uncertainty.NICv1[NIC][NICs]['Rc']\n        VPL = uncertainty.NICv1[NIC][NICs]['VPL']\n    except KeyError:\n        Rc, VPL = uncertainty.NA, uncertainty.NA\n    return Rc, VPL",
    "docstring": "Calculate NIC, navigation integrity category, for ADS-B version 1\n\n    Args:\n        msg (string): 28 bytes hexadecimal message string\n        NICs (int or string): NIC supplement\n\n    Returns:\n        int or string: Horizontal Radius of Containment\n        int or string: Vertical Protection Limit"
  },
  {
    "code": "def order_market_buy(self, **params):\n        params.update({\n            'side': self.SIDE_BUY\n        })\n        return self.order_market(**params)",
    "docstring": "Send in a new market buy order\n\n        :param symbol: required\n        :type symbol: str\n        :param quantity: required\n        :type quantity: decimal\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        See order endpoint for full response options\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException"
  },
  {
    "code": "def sizeHint(self, option, index):\n        component = index.internalPointer()\n        width = self.component.duration() * self.pixelsPerms*1000\n        return QtCore.QSize(width, 50)",
    "docstring": "Size based on component duration and a fixed height"
  },
  {
    "code": "def device_state(device_id):\n    if device_id not in devices:\n        return jsonify(success=False)\n    return jsonify(state=devices[device_id].state)",
    "docstring": "Get device state via HTTP GET."
  },
  {
    "code": "def _parse_metadata(self, meta):\n        formatted_fields = self.settings['FORMATTED_FIELDS']\n        output = collections.OrderedDict()\n        for name, value in meta.items():\n            name = name.lower()\n            if name in formatted_fields:\n                rendered = self._render(value).strip()\n                output[name] = self.process_metadata(name, rendered)\n            else:\n                output[name] = self.process_metadata(name, value)\n        return output",
    "docstring": "Return the dict containing document metadata"
  },
  {
    "code": "def search_external_subtitles(path, directory=None):\n    dirpath, filename = os.path.split(path)\n    dirpath = dirpath or '.'\n    fileroot, fileext = os.path.splitext(filename)\n    subtitles = {}\n    for p in os.listdir(directory or dirpath):\n        if not p.startswith(fileroot) or not p.endswith(SUBTITLE_EXTENSIONS):\n            continue\n        language = Language('und')\n        language_code = p[len(fileroot):-len(os.path.splitext(p)[1])].replace(fileext, '').replace('_', '-')[1:]\n        if language_code:\n            try:\n                language = Language.fromietf(language_code)\n            except (ValueError, LanguageReverseError):\n                logger.error('Cannot parse language code %r', language_code)\n        subtitles[p] = language\n    logger.debug('Found subtitles %r', subtitles)\n    return subtitles",
    "docstring": "Search for external subtitles from a video `path` and their associated language.\n\n    Unless `directory` is provided, search will be made in the same directory as the video file.\n\n    :param str path: path to the video.\n    :param str directory: directory to search for subtitles.\n    :return: found subtitles with their languages.\n    :rtype: dict"
  },
  {
    "code": "def bridge_create(br, may_exist=True, parent=None, vlan=None):\n    param_may_exist = _param_may_exist(may_exist)\n    if parent is not None and vlan is None:\n        raise ArgumentValueError(\n            'If parent is specified, vlan must also be specified.')\n    if vlan is not None and parent is None:\n        raise ArgumentValueError(\n            'If vlan is specified, parent must also be specified.')\n    param_parent = '' if parent is None else ' {0}'.format(parent)\n    param_vlan = '' if vlan is None else ' {0}'.format(vlan)\n    cmd = 'ovs-vsctl {1}add-br {0}{2}{3}'.format(br, param_may_exist, param_parent,\n                                           param_vlan)\n    result = __salt__['cmd.run_all'](cmd)\n    return _retcode_to_bool(result['retcode'])",
    "docstring": "Creates a new bridge.\n\n    Args:\n        br: A string - bridge name\n        may_exist: Bool, if False - attempting to create a bridge that exists returns False.\n        parent: String, the name of the parent bridge (if the bridge shall be\n            created as a fake bridge). If specified, vlan must also be\n            specified.\n        vlan: Int, the VLAN ID of the bridge (if the bridge shall be created as\n            a fake bridge). If specified, parent must also be specified.\n\n    Returns:\n        True on success, else False.\n\n    .. versionadded:: 2016.3.0\n\n    CLI Example:\n    .. code-block:: bash\n\n        salt '*' openvswitch.bridge_create br0"
  },
  {
    "code": "def is_valid_timestamp(date, unit='millis'):\n    assert isinstance(date, int), \"Input is not instance of int\"\n    if unit is 'millis':\n        return is_positive(date) and len(str(date)) == 13\n    elif unit is 'seconds':\n        return is_positive(date) and len(str(date)) == 10\n    else:\n        raise ValueError('Unknown unit \"%s\"' % unit)",
    "docstring": "Checks that a number that represents a date as milliseconds is correct."
  },
  {
    "code": "def write_csv(self, path=None):\n        self.sort_sections(['Root', 'Contacts', 'Documentation', 'References', 'Resources', 'Citations', 'Schema'])\n        if self.description:\n            self.description = self.description\n        if self.abstract:\n            self.description = self.abstract\n        t = self['Root'].get_or_new_term('Root.Modified')\n        t.value = datetime_now()\n        self.sort_by_term()\n        return super().write_csv(str(path))",
    "docstring": "Write CSV file. Sorts the sections before calling the superclass write_csv"
  },
  {
    "code": "def overlaps(self, canvas, exclude=[]):\n        try:\n            exclude = list(exclude)\n        except TypeError:\n            exclude = [exclude]\n        exclude.append(self)\n        for selfY, row in enumerate(self.image.image()):\n            for selfX, pixel in enumerate(row):\n                canvasPixelOn = canvas.testPixel(\n                    (selfX + self.position[0], selfY + self.position[1]),\n                    excludedSprites=exclude\n                )\n                if pixel and canvasPixelOn:\n                    return True\n        return False",
    "docstring": "Returns True if sprite is touching any other sprite."
  },
  {
    "code": "def choices(self):\n        choice_list = getattr(\n            settings, 'MARKUP_CHOICES', DEFAULT_MARKUP_CHOICES\n        )\n        return [(f, self._get_filter_title(f)) for f in choice_list]",
    "docstring": "Returns the filter list as a tuple. Useful for model choices."
  },
  {
    "code": "def iterate_analogy_datasets(args):\n    for dataset_name in args.analogy_datasets:\n        parameters = nlp.data.list_datasets(dataset_name)\n        for key_values in itertools.product(*parameters.values()):\n            kwargs = dict(zip(parameters.keys(), key_values))\n            yield dataset_name, kwargs, nlp.data.create(dataset_name, **kwargs)",
    "docstring": "Generator over all analogy evaluation datasets.\n\n    Iterates over dataset names, keyword arguments for their creation and the\n    created dataset."
  },
  {
    "code": "def fork(self):\n        url = self._build_url('forks', base_url=self._api)\n        json = self._json(self._post(url), 201)\n        return Gist(json, self) if json else None",
    "docstring": "Fork this gist.\n\n        :returns: :class:`Gist <Gist>` if successful, ``None`` otherwise"
  },
  {
    "code": "def load_snps(\n        self,\n        raw_data,\n        discrepant_snp_positions_threshold=100,\n        discrepant_genotypes_threshold=500,\n        save_output=False,\n    ):\n        if type(raw_data) is list:\n            for file in raw_data:\n                self._load_snps_helper(\n                    file,\n                    discrepant_snp_positions_threshold,\n                    discrepant_genotypes_threshold,\n                    save_output,\n                )\n        elif type(raw_data) is str:\n            self._load_snps_helper(\n                raw_data,\n                discrepant_snp_positions_threshold,\n                discrepant_genotypes_threshold,\n                save_output,\n            )\n        else:\n            raise TypeError(\"invalid filetype\")",
    "docstring": "Load raw genotype data.\n\n        Parameters\n        ----------\n        raw_data : list or str\n            path(s) to file(s) with raw genotype data\n        discrepant_snp_positions_threshold : int\n            threshold for discrepant SNP positions between existing data and data to be loaded,\n            a large value could indicate mismatched genome assemblies\n        discrepant_genotypes_threshold : int\n            threshold for discrepant genotype data between existing data and data to be loaded,\n            a large value could indicated mismatched individuals\n        save_output : bool\n            specifies whether to save discrepant SNP output to CSV files in the output directory"
  },
  {
    "code": "def space(self):\n        arg_spaces = [o.space for o in self.matrix.ravel()\n                      if hasattr(o, 'space')]\n        if len(arg_spaces) == 0:\n            return TrivialSpace\n        else:\n            return ProductSpace.create(*arg_spaces)",
    "docstring": "Combined Hilbert space of all matrix elements."
  },
  {
    "code": "def get_community_badge_progress(self, steamID, badgeID, format=None):\n        parameters = {'steamid' : steamID, 'badgeid' : badgeID}\n        if format is not None:\n            parameters['format'] = format\n        url = self.create_request_url(self.interface, 'GetCommunityBadgeProgress', 1,\n            parameters)\n        data = self.retrieve_request(url)\n        return self.return_data(data, format=format)",
    "docstring": "Gets all the quests needed to get the specified badge, and which are completed.\n\n        steamID: The users ID\n        badgeID: The badge we're asking about\n        format: Return format. None defaults to json. (json, xml, vdf)"
  },
  {
    "code": "def doc(self):\n        if hasattr(self, '_doc'):\n            return self._doc\n        elements = self.etree\n        doc = self._doc = PyQuery(elements)\n        doc.make_links_absolute(utils.text(self.url))\n        return doc",
    "docstring": "Returns a PyQuery object of the response's content"
  },
  {
    "code": "def clear(self):\n        self.adj.clear()\n        self.node.clear()\n        self.graph.clear()",
    "docstring": "Remove all nodes and edges from the graph.\n\n        Unlike the regular networkx implementation, this does *not*\n        remove the graph's name. But all the other graph, node, and\n        edge attributes go away."
  },
  {
    "code": "def start_daemon():\n        if RequestLog.daemon is None:\n            parser = get_nginx_parser()\n            RequestLog.daemon = RequestLog.ParseToDBThread(parser, daemon=True)\n        RequestLog.daemon.start()\n        return RequestLog.daemon",
    "docstring": "Start a thread to continuously read log files and append lines in DB.\n\n        Work in progress. Currently the thread doesn't append anything,\n        it only print the information parsed from each line read.\n\n        Returns:\n            thread: the started thread."
  },
  {
    "code": "def chi_squared(source_frequency, target_frequency):\n    target_prob = frequency_to_probability(target_frequency)\n    source_len = sum(v for k, v in source_frequency.items() if k in target_frequency)\n    result = 0\n    for symbol, prob in target_prob.items():\n        symbol_frequency = source_frequency.get(symbol, 0)\n        result += _calculate_chi_squared(symbol_frequency, prob, source_len)\n    return result",
    "docstring": "Calculate the Chi Squared statistic by comparing ``source_frequency`` with ``target_frequency``.\n\n    Example:\n        >>> chi_squared({'a': 2, 'b': 3}, {'a': 1, 'b': 2})\n        0.1\n\n    Args:\n        source_frequency (dict): Frequency map of the text you are analyzing\n        target_frequency (dict): Frequency map of the target language to compare with\n\n    Returns:\n        Decimal value of the chi-squared statistic"
  },
  {
    "code": "def record_result(self, res, prg=''):\n        self._log(self.logFileResult , force_to_string(res), prg)",
    "docstring": "record the output of the command. Records the result, can have \n        multiple results, so will need to work out a consistent way to aggregate this"
  },
  {
    "code": "def camel_to_underscore(name):\n    as_list = []\n    length = len(name)\n    for index, i in enumerate(name):\n        if index != 0 and index != length - 1 and i.isupper():\n            as_list.append('_%s' % i.lower())\n        else:\n            as_list.append(i.lower())\n    return ''.join(as_list)",
    "docstring": "convert CamelCase style to under_score_case"
  },
  {
    "code": "def parser_available(fpath):\n    if isinstance(fpath, basestring):\n        fname = fpath\n    elif hasattr(fpath, 'open') and hasattr(fpath, 'name'):\n        fname = fpath.name\n    elif hasattr(fpath, 'readline') and hasattr(fpath, 'name'):\n        fname = fpath.name\n    else:\n        raise ValueError(\n            'fpath should be a str or file_like object: {}'.format(fpath))\n    for parser in get_plugins('parsers').values():\n        if fnmatch(fname, parser.file_regex):\n            return True\n    return False",
    "docstring": "test if parser plugin available for fpath\n\n    Examples\n    --------\n\n    >>> load_builtin_plugins('parsers')\n    []\n    >>> test_file = StringIO('{\"a\":[1,2,3.4]}')\n    >>> test_file.name = 'test.json'\n    >>> parser_available(test_file)\n    True\n    >>> test_file.name = 'test.other'\n    >>> parser_available(test_file)\n    False\n\n    >>> unload_all_plugins()"
  },
  {
    "code": "def read_stat():\n    return [\n        {\n            \"times\": {\n                \"user\": random.randint(0, 999999999),\n                \"nice\": random.randint(0, 999999999),\n                \"sys\": random.randint(0, 999999999),\n                \"idle\": random.randint(0, 999999999),\n                \"irq\": random.randint(0, 999999999),\n            }\n        }\n    ]",
    "docstring": "Mocks read_stat as this is a Linux-specific operation."
  },
  {
    "code": "def normrelpath(base, target):\n    if not all(map(isabs, [base, target])):\n        return target\n    return relpath(normpath(target), dirname(normpath(base)))",
    "docstring": "This function takes the base and target arguments as paths, and\n    returns an equivalent relative path from base to the target, if both\n    provided paths are absolute."
  },
  {
    "code": "def maxdiff_dtu_configurations(list_of_objects):\n    result = DtuConfiguration()\n    if len(list_of_objects) == 0:\n        return result\n    list_of_members = result.__dict__.keys()\n    for member in list_of_members:\n        tmp_array = np.array(\n            [tmp_dtu.__dict__[member] for tmp_dtu in list_of_objects]\n        )\n        minval = tmp_array.min()\n        maxval = tmp_array.max()\n        result.__dict__[member] = maxval - minval\n    return result",
    "docstring": "Return DtuConfiguration instance with maximum differences.\n\n    Parameters\n    ----------\n    list_of_objects : python list\n        List of DtuConfiguration instances to be averaged.\n\n    Returns\n    -------\n    result : DtuConfiguration instance\n        Object with averaged values."
  },
  {
    "code": "def close(self):\n        if self.hwman.stream.connected:\n            self.hwman.disconnect()\n        self.hwman.close()\n        self.opened = False",
    "docstring": "Close and potentially disconnect from a device."
  },
  {
    "code": "def add_qualified_edge(\n            self,\n            u,\n            v,\n            *,\n            relation: str,\n            evidence: str,\n            citation: Union[str, Mapping[str, str]],\n            annotations: Optional[AnnotationsHint] = None,\n            subject_modifier: Optional[Mapping] = None,\n            object_modifier: Optional[Mapping] = None,\n            **attr\n    ) -> str:\n        attr.update({\n            RELATION: relation,\n            EVIDENCE: evidence,\n        })\n        if isinstance(citation, str):\n            attr[CITATION] = {\n                CITATION_TYPE: CITATION_TYPE_PUBMED,\n                CITATION_REFERENCE: citation,\n            }\n        elif isinstance(citation, dict):\n            attr[CITATION] = citation\n        else:\n            raise TypeError\n        if annotations:\n            attr[ANNOTATIONS] = _clean_annotations(annotations)\n        if subject_modifier:\n            attr[SUBJECT] = subject_modifier\n        if object_modifier:\n            attr[OBJECT] = object_modifier\n        return self._help_add_edge(u, v, attr)",
    "docstring": "Add a qualified edge.\n\n        Qualified edges have a relation, evidence, citation, and optional annotations, subject modifications,\n        and object modifications.\n\n        :param u: The source node\n        :param v: The target node\n        :param relation: The type of relation this edge represents\n        :param evidence: The evidence string from an article\n        :param citation: The citation data dictionary for this evidence. If a string is given,\n         assumes it's a PubMed identifier and auto-fills the citation type.\n        :param annotations: The annotations data dictionary\n        :param subject_modifier: The modifiers (like activity) on the subject node. See data model documentation.\n        :param object_modifier: The modifiers (like activity) on the object node. See data model documentation.\n\n        :return: The hash of the edge"
  },
  {
    "code": "def web(host, port):\n    from .webserver.web import get_app\n    get_app().run(host=host, port=port)",
    "docstring": "Start web application"
  },
  {
    "code": "def render_form_template():\n    error = \"\"\n    remote_info = {}\n    registered_user_id = request.query.get(\"url_id\", False)\n    if registered_user_id:\n        try:\n            remote_info = seeder.get_remote_info(registered_user_id)\n        except AssertionError:\n            registered_user_id = False\n            error = \"Seeder neposlal očekávaná data.\\n\"\n    if registered_user_id and remote_info:\n        return render_registered(registered_user_id, remote_info)\n    if not remote_info:\n        error += \"Seeder je nedostupný!\\n\"\n    return render_unregistered(error)",
    "docstring": "Rennder template for user.\n\n    Decide whether the user is registered or not, pull remote info and so on."
  },
  {
    "code": "def activate_network_interface(iface):\n    iface = iface.encode()\n    SIOCGIFFLAGS = 0x8913\n    SIOCSIFFLAGS = 0x8914\n    IFF_UP = 0x1\n    STRUCT_IFREQ_LAYOUT_IFADDR_SAFAMILY = b\"16sH14s\"\n    STRUCT_IFREQ_LAYOUT_IFFLAGS = b\"16sH14s\"\n    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_IP)\n    try:\n        ifreq = struct.pack(STRUCT_IFREQ_LAYOUT_IFADDR_SAFAMILY, iface, socket.AF_INET, b'0' * 14)\n        ifreq = fcntl.ioctl(sock, SIOCGIFFLAGS, ifreq)\n        if_flags = struct.unpack(STRUCT_IFREQ_LAYOUT_IFFLAGS, ifreq)[1]\n        ifreq = struct.pack(STRUCT_IFREQ_LAYOUT_IFFLAGS, iface, if_flags | IFF_UP, b'0' * 14)\n        fcntl.ioctl(sock, SIOCSIFFLAGS, ifreq)\n    finally:\n        sock.close()",
    "docstring": "Bring up the given network interface.\n    @raise OSError: if interface does not exist or permissions are missing"
  },
  {
    "code": "def fit_transform(self, X, **kwargs):\n        tasklogger.log_start('PHATE')\n        self.fit(X)\n        embedding = self.transform(**kwargs)\n        tasklogger.log_complete('PHATE')\n        return embedding",
    "docstring": "Computes the diffusion operator and the position of the cells in the\n        embedding space\n\n        Parameters\n        ----------\n        X : array, shape=[n_samples, n_features]\n            input data with `n_samples` samples and `n_dimensions`\n            dimensions. Accepted data types: `numpy.ndarray`,\n            `scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData` If\n            `knn_dist` is 'precomputed', `data` should be a n_samples x\n            n_samples distance or affinity matrix\n\n        kwargs : further arguments for `PHATE.transform()`\n            Keyword arguments as specified in :func:`~phate.PHATE.transform`\n\n        Returns\n        -------\n        embedding : array, shape=[n_samples, n_dimensions]\n            The cells embedded in a lower dimensional space using PHATE"
  },
  {
    "code": "def str_extract(arr, pat, flags=0, expand=True):\n    r\n    if not isinstance(expand, bool):\n        raise ValueError(\"expand must be True or False\")\n    if expand:\n        return _str_extract_frame(arr._orig, pat, flags=flags)\n    else:\n        result, name = _str_extract_noexpand(arr._parent, pat, flags=flags)\n        return arr._wrap_result(result, name=name, expand=expand)",
    "docstring": "r\"\"\"\n    Extract capture groups in the regex `pat` as columns in a DataFrame.\n\n    For each subject string in the Series, extract groups from the\n    first match of regular expression `pat`.\n\n    Parameters\n    ----------\n    pat : str\n        Regular expression pattern with capturing groups.\n    flags : int, default 0 (no flags)\n        Flags from the ``re`` module, e.g. ``re.IGNORECASE``, that\n        modify regular expression matching for things like case,\n        spaces, etc. For more details, see :mod:`re`.\n    expand : bool, default True\n        If True, return DataFrame with one column per capture group.\n        If False, return a Series/Index if there is one capture group\n        or DataFrame if there are multiple capture groups.\n\n        .. versionadded:: 0.18.0\n\n    Returns\n    -------\n    DataFrame or Series or Index\n        A DataFrame with one row for each subject string, and one\n        column for each group. Any capture group names in regular\n        expression pat will be used for column names; otherwise\n        capture group numbers will be used. The dtype of each result\n        column is always object, even when no match is found. If\n        ``expand=False`` and pat has only one capture group, then\n        return a Series (if subject is a Series) or Index (if subject\n        is an Index).\n\n    See Also\n    --------\n    extractall : Returns all matches (not just the first match).\n\n    Examples\n    --------\n    A pattern with two groups will return a DataFrame with two columns.\n    Non-matches will be NaN.\n\n    >>> s = pd.Series(['a1', 'b2', 'c3'])\n    >>> s.str.extract(r'([ab])(\\d)')\n         0    1\n    0    a    1\n    1    b    2\n    2  NaN  NaN\n\n    A pattern may contain optional groups.\n\n    >>> s.str.extract(r'([ab])?(\\d)')\n         0  1\n    0    a  1\n    1    b  2\n    2  NaN  3\n\n    Named groups will become column names in the result.\n\n    >>> s.str.extract(r'(?P<letter>[ab])(?P<digit>\\d)')\n      letter digit\n    0      a     1\n    1      b     2\n    2    NaN   NaN\n\n    A pattern with one group will return a DataFrame with one column\n    if expand=True.\n\n    >>> s.str.extract(r'[ab](\\d)', expand=True)\n         0\n    0    1\n    1    2\n    2  NaN\n\n    A pattern with one group will return a Series if expand=False.\n\n    >>> s.str.extract(r'[ab](\\d)', expand=False)\n    0      1\n    1      2\n    2    NaN\n    dtype: object"
  },
  {
    "code": "def start(self):\n        while not self.is_start(self.current_tag):\n            self.next()\n        self.new_entry()",
    "docstring": "Find the first data entry and prepare to parse."
  },
  {
    "code": "def check_status(self, delay=0):\n        if not self.item_id:\n            while not self._request_status():\n                yield self.status, self.completion_percentage\n                if self.item_id is None:\n                    sleep(delay)\n        else:\n            yield self.status, self.completion_percentage",
    "docstring": "Checks the api endpoint in a loop\n\n        :param delay: number of seconds to wait between api calls.\n         Note Connection 'requests_delay' also apply.\n        :return: tuple of status and percentage complete\n        :rtype: tuple(str, float)"
  },
  {
    "code": "def level(self):\n        m = re.match(\n            self.compliance_prefix +\n            r'(\\d)' +\n            self.compliance_suffix +\n            r'$',\n            self.compliance)\n        if (m):\n            return int(m.group(1))\n        raise IIIFInfoError(\n            \"Bad compliance profile URI, failed to extract level number\")",
    "docstring": "Extract level number from compliance profile URI.\n\n        Returns integer level number or raises IIIFInfoError"
  },
  {
    "code": "def bitwise_dot_product(bs0: str, bs1: str) -> str:\n    if len(bs0) != len(bs1):\n        raise ValueError(\"Bit strings are not of equal length\")\n    return str(sum([int(bs0[i]) * int(bs1[i]) for i in range(len(bs0))]) % 2)",
    "docstring": "A helper to calculate the bitwise dot-product between two string representing bit-vectors\n\n    :param bs0: String of 0's and 1's representing a number in binary representations\n    :param bs1: String of 0's and 1's representing a number in binary representations\n    :return: 0 or 1 as a string corresponding to the dot-product value"
  },
  {
    "code": "def data_file(file_fmt, info=None, **kwargs):\n    if isinstance(info, dict):\n        kwargs['hash_key'] = hashlib.sha256(json.dumps(info).encode('utf-8')).hexdigest()\n        kwargs.update(info)\n    return utils.fstr(fmt=file_fmt, **kwargs)",
    "docstring": "Data file name for given infomation\n\n    Args:\n        file_fmt: file format in terms of f-strings\n        info: dict, to be hashed and then pass to f-string using 'hash_key'\n              these info will also be passed to f-strings\n        **kwargs: arguments for f-strings\n\n    Returns:\n        str: data file name"
  },
  {
    "code": "def row_is_filtered(self, row_subs, filters):\n        for filtername in filters:\n            filtervalue = filters[filtername]\n            if filtername in row_subs:\n                row_subs_value = row_subs[filtername]\n                if str(row_subs_value) != str(filtervalue):\n                    return True\n            else:\n                print(\"fw: Unknown filter keyword (%s)\" % (filtername,))\n        return False",
    "docstring": "returns True if row should NOT be included according to filters"
  },
  {
    "code": "def repeat(self, count):\n        x = HSeq()\n        for i in range(count):\n            x = x.concatenate(self)\n        return x",
    "docstring": "repeat sequence given number of times to produce a new sequence"
  },
  {
    "code": "def getfirstline(file, default):\n    with open(file, 'rb') as fh:\n        content = fh.readlines()\n        if len(content) == 1:\n            return content[0].decode('utf-8').strip('\\n')\n    return default",
    "docstring": "Returns the first line of a file."
  },
  {
    "code": "def _handle_archive(archive, command, verbosity=0, interactive=True,\n                    program=None, format=None, compression=None):\n    if format is None:\n        format, compression = get_archive_format(archive)\n    check_archive_format(format, compression)\n    if command not in ('list', 'test'):\n        raise util.PatoolError(\"invalid archive command `%s'\" % command)\n    program = find_archive_program(format, command, program=program)\n    check_program_compression(archive, command, program, compression)\n    get_archive_cmdlist = get_archive_cmdlist_func(program, command, format)\n    cmdlist = get_archive_cmdlist(archive, compression, program, verbosity, interactive)\n    if cmdlist:\n        run_archive_cmdlist(cmdlist, verbosity=verbosity)",
    "docstring": "Test and list archives."
  },
  {
    "code": "def finish_assessment(self, assessment_taken_id):\n        assessment_taken = self._get_assessment_taken(assessment_taken_id)\n        assessment_taken_map = assessment_taken._my_map\n        if assessment_taken.has_started() and not assessment_taken.has_ended():\n            assessment_taken_map['completionTime'] = DateTime.utcnow()\n            assessment_taken_map['ended'] = True\n            collection = JSONClientValidated('assessment',\n                                             collection='AssessmentTaken',\n                                             runtime=self._runtime)\n            collection.save(assessment_taken_map)\n        else:\n            raise errors.IllegalState()",
    "docstring": "Indicates the entire assessment is complete.\n\n        arg:    assessment_taken_id (osid.id.Id): ``Id`` of the\n                ``AssessmentTaken``\n        raise:  IllegalState - ``has_begun()`` is ``false or is_over()``\n                is ``true``\n        raise:  NotFound - ``assessment_taken_id`` is not found\n        raise:  NullArgument - ``assessment_taken_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def connected_edges(G, nodes):\n    nodes_in_G = collections.deque()\n    for node in nodes:\n        if not G.has_node(node):\n            continue\n        nodes_in_G.extend(nx.node_connected_component(G, node))\n    edges = G.subgraph(nodes_in_G).edges()\n    return edges",
    "docstring": "Given graph G and list of nodes, return the list of edges that\n    are connected to nodes"
  },
  {
    "code": "def add_event(\n    request,\n    template='swingtime/add_event.html',\n    event_form_class=forms.EventForm,\n    recurrence_form_class=forms.MultipleOccurrenceForm\n):\n    dtstart = None\n    if request.method == 'POST':\n        event_form = event_form_class(request.POST)\n        recurrence_form = recurrence_form_class(request.POST)\n        if event_form.is_valid() and recurrence_form.is_valid():\n            event = event_form.save()\n            recurrence_form.save(event)\n            return http.HttpResponseRedirect(event.get_absolute_url())\n    else:\n        if 'dtstart' in request.GET:\n            try:\n                dtstart = parser.parse(request.GET['dtstart'])\n            except(TypeError, ValueError) as exc:\n                logging.warning(exc)\n        dtstart = dtstart or datetime.now()\n        event_form = event_form_class()\n        recurrence_form = recurrence_form_class(initial={'dtstart': dtstart})\n    return render(\n        request,\n        template,\n        {'dtstart': dtstart, 'event_form': event_form, 'recurrence_form': recurrence_form}\n    )",
    "docstring": "Add a new ``Event`` instance and 1 or more associated ``Occurrence``s.\n\n    Context parameters:\n\n    ``dtstart``\n        a datetime.datetime object representing the GET request value if present,\n        otherwise None\n\n    ``event_form``\n        a form object for updating the event\n\n    ``recurrence_form``\n        a form object for adding occurrences"
  },
  {
    "code": "def rollback_app(self, app_id, version, force=False):\n        params = {'force': force}\n        data = json.dumps({'version': version})\n        response = self._do_request(\n            'PUT', '/v2/apps/{app_id}'.format(app_id=app_id), params=params, data=data)\n        return response.json()",
    "docstring": "Roll an app back to a previous version.\n\n        :param str app_id: application ID\n        :param str version: application version\n        :param bool force: apply even if a deployment is in progress\n\n        :returns: a dict containing the deployment id and version\n        :rtype: dict"
  },
  {
    "code": "def delete_unused(self, keyword_ids=None):\n        if keyword_ids is None:\n            keywords = self.all()\n        else:\n            keywords = self.filter(id__in=keyword_ids)\n        keywords.filter(assignments__isnull=True).delete()",
    "docstring": "Removes all instances that are not assigned to any object. Limits\n        processing to ``keyword_ids`` if given."
  },
  {
    "code": "def _flush(self):\n        self.classes_names = None\n        self.__cache_methods = None\n        self.__cached_methods_idx = None\n        self.__cache_fields = None\n        self.__cache_all_methods = None\n        self.__cache_all_fields = None",
    "docstring": "Flush all caches\n        Might be used after classes, methods or fields are added."
  },
  {
    "code": "def add(a, b):\n    if a is None:\n        if b is None:\n            return None\n        else:\n            return b\n    elif b is None:\n        return a\n    return a + b",
    "docstring": "Add two values, ignoring None"
  },
  {
    "code": "def get_instance(self, payload):\n        return TranscriptionInstance(\n            self._version,\n            payload,\n            account_sid=self._solution['account_sid'],\n            recording_sid=self._solution['recording_sid'],\n        )",
    "docstring": "Build an instance of TranscriptionInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance\n        :rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance"
  },
  {
    "code": "def _retrieve(self, *criterion):\n        try:\n            return self._query(*criterion).one()\n        except NoResultFound as error:\n            raise ModelNotFoundError(\n                \"{} not found\".format(\n                    self.model_class.__name__,\n                ),\n                error,\n            )",
    "docstring": "Retrieve a model by some criteria.\n\n        :raises `ModelNotFoundError` if the row cannot be deleted."
  },
  {
    "code": "def callable_name(callable_obj):\n    try:\n        if (isinstance(callable_obj, type)\n            and issubclass(callable_obj, param.ParameterizedFunction)):\n            return callable_obj.__name__\n        elif (isinstance(callable_obj, param.Parameterized)\n              and 'operation' in callable_obj.params()):\n            return callable_obj.operation.__name__\n        elif isinstance(callable_obj, partial):\n            return str(callable_obj)\n        elif inspect.isfunction(callable_obj):\n            return callable_obj.__name__\n        elif inspect.ismethod(callable_obj):\n            meth = callable_obj\n            if sys.version_info < (3,0):\n                owner =  meth.im_class if meth.im_self is None else meth.im_self\n            else:\n                owner =  meth.__self__\n            if meth.__name__ == '__call__':\n                return type(owner).__name__\n            return '.'.join([owner.__name__, meth.__name__])\n        elif isinstance(callable_obj, types.GeneratorType):\n            return callable_obj.__name__\n        else:\n            return type(callable_obj).__name__\n    except:\n        return str(callable_obj)",
    "docstring": "Attempt to return a meaningful name identifying a callable or generator"
  },
  {
    "code": "def truncate_table(self, tablename):\n        self.get(tablename).remove()\n        self.db.commit()",
    "docstring": "SQLite3 doesn't support direct truncate, so we just use delete here"
  },
  {
    "code": "def _ref_bib(key, ref):\n    s = ''\n    s += '@{}{{{},\\n'.format(ref['type'], key)\n    entry_lines = []\n    for k, v in ref.items():\n        if k == 'type':\n            continue\n        if k == 'authors':\n            entry_lines.append('    author = {{{}}}'.format(' and '.join(v)))\n        elif k == 'editors':\n            entry_lines.append('    editor = {{{}}}'.format(' and '.join(v)))\n        else:\n            entry_lines.append('    {} = {{{}}}'.format(k, v))\n    s += ',\\n'.join(entry_lines)\n    s += '\\n}'\n    return s",
    "docstring": "Convert a single reference to bibtex format"
  },
  {
    "code": "def attach(self):\n        s = self._sensor\n        self.update(s, s.read())\n        self._sensor.attach(self)",
    "docstring": "Attach strategy to its sensor and send initial update."
  },
  {
    "code": "def add_injectable(\n        name, value, autocall=True, cache=False, cache_scope=_CS_FOREVER,\n        memoize=False):\n    if isinstance(value, Callable):\n        if autocall:\n            value = _InjectableFuncWrapper(\n                name, value, cache=cache, cache_scope=cache_scope)\n            value.clear_cached()\n        elif not autocall and memoize:\n            value = _memoize_function(value, name, cache_scope=cache_scope)\n    logger.debug('registering injectable {!r}'.format(name))\n    _INJECTABLES[name] = value",
    "docstring": "Add a value that will be injected into other functions.\n\n    Parameters\n    ----------\n    name : str\n    value\n        If a callable and `autocall` is True then the function's\n        argument names and keyword argument values will be matched\n        to registered variables when the function needs to be\n        evaluated by Orca. The return value will\n        be passed to any functions using this injectable. In all other\n        cases, `value` will be passed through untouched.\n    autocall : bool, optional\n        Set to True to have injectable functions automatically called\n        (with argument matching) and the result injected instead of\n        the function itself.\n    cache : bool, optional\n        Whether to cache the return value of an injectable function.\n        Only applies when `value` is a callable and `autocall` is True.\n    cache_scope : {'step', 'iteration', 'forever'}, optional\n        Scope for which to cache data. Default is to cache forever\n        (or until manually cleared). 'iteration' caches data for each\n        complete iteration of the pipeline, 'step' caches data for\n        a single step of the pipeline.\n    memoize : bool, optional\n        If autocall is False it is still possible to cache function results\n        by setting this flag to True. Cached values are stored in a dictionary\n        keyed by argument values, so the argument values must be hashable.\n        Memoized functions have their caches cleared according to the same\n        rules as universal caching."
  },
  {
    "code": "def logs(ctx, services, num, follow):\n    logger.debug(\"running command %s (%s)\", ctx.command.name, ctx.params,\n                 extra={\"command\": ctx.command.name, \"params\": ctx.params})\n    home = ctx.obj[\"HOME\"]\n    services_path = os.path.join(home, SERVICES)\n    tail_threads = []\n    for service in services:\n        logpath = os.path.join(services_path, service, LOGS_DIR, STDOUTLOG)\n        if os.path.exists(logpath):\n            logger.debug(\"tailing %s\", logpath)\n            t = threading.Thread(target=Tailer, kwargs={\"name\": service,\n                                                        \"nlines\": num,\n                                                        \"filepath\": logpath,\n                                                        \"follow\": follow})\n            t.daemon = True\n            t.start()\n            tail_threads.append(t)\n    if tail_threads:\n        while tail_threads[0].isAlive():\n            tail_threads[0].join(0.1)",
    "docstring": "Show logs of daemonized service."
  },
  {
    "code": "def delete(self, key):\n        \"Delete a `key` from the keystore.\"\n        if key in self.data:\n            self.delete_from_index(key)\n        del self.data[key]",
    "docstring": "Delete a `key` from the keystore."
  },
  {
    "code": "def data(self) -> Sequence[Tuple[int, float]]:\n        return [(num, prob) for num, prob in zip(self._num_cfds_seq,\n                                                 self._gnd_state_probs)]",
    "docstring": "Returns a sequence of tuple pairs with the first item being a\n        number of Cliffords and the second item being the corresponding average\n        ground state probability."
  },
  {
    "code": "def add_chain(self, group_name, component_map):\n        self.assert_writeable()\n        for component, path in component_map.items():\n            if not path.startswith('Analyses/'):\n                path = 'Analyses/{}'.format(path)\n            component_map[component] = path\n        self.add_analysis_attributes(group_name, component_map)",
    "docstring": "Adds the component chain to ``group_name`` in the fast5.\n        These are added as attributes to the group.\n\n        :param group_name: The group name you wish to add chaining data to,\n            e.g. ``Test_000``\n        :param component_map: The set of components and corresponding\n            group names or group paths that contribute data to the analysis.\n            If group names are provided, these will be converted into group\n            paths.\n\n            If ``Test_000`` uses data from the results of\n            ``first_component`` stored at ``Analyses/First_000/``\n            the component_map could be ``{'first_component': 'First_000'}`` or\n            ``{'first_component': 'Analyses/First_000'}``."
  },
  {
    "code": "def pickle_to_param(obj, name):\n\treturn from_pyvalue(u\"pickle:%s\" % name, unicode(pickle.dumps(obj)))",
    "docstring": "Return the top-level element of a document sub-tree containing the\n\tpickled serialization of a Python object."
  },
  {
    "code": "def from_scf_input(cls, workdir, scf_input, manager=None, allocate=True):\n        flow = cls(workdir, manager=manager)\n        flow.register_scf_task(scf_input)\n        scf_task = flow[0][0]\n        nl_work = DteWork.from_scf_task(scf_task)\n        flow.register_work(nl_work)\n        if allocate: flow.allocate()\n        return flow",
    "docstring": "Create a `NonlinearFlow` for second order susceptibility calculations from\n        an `AbinitInput` defining a ground-state run.\n\n        Args:\n            workdir: Working directory of the flow.\n            scf_input: :class:`AbinitInput` object with the parameters for the GS-SCF run.\n            manager: :class:`TaskManager` object. Read from `manager.yml` if None.\n            allocate: True if the flow should be allocated before returning.\n\n        Return:\n            :class:`NonlinearFlow` object."
  },
  {
    "code": "def is_np_compat():\n    curr = ctypes.c_bool()\n    check_call(_LIB.MXIsNumpyCompatible(ctypes.byref(curr)))\n    return curr.value",
    "docstring": "Checks whether the NumPy compatibility is currently turned on.\n    NumPy-compatibility is turned off by default in backend.\n\n    Returns\n    -------\n        A bool value indicating whether the NumPy compatibility is currently on."
  },
  {
    "code": "def parse(self, input_text, syncmap):\n        self.log_exc(u\"%s is abstract and cannot be called directly\" % (self.TAG), None, True, NotImplementedError)",
    "docstring": "Parse the given ``input_text`` and\n        append the extracted fragments to ``syncmap``.\n\n        :param input_text: the input text as a Unicode string (read from file)\n        :type input_text: string\n        :param syncmap: the syncmap to append to\n        :type syncmap: :class:`~aeneas.syncmap.SyncMap`"
  },
  {
    "code": "def _get_memory_contents(self):\n    if self._memory_contents is not None:\n      return self._memory_contents\n    schedule = scheduler.minimize_peak_memory(self._graph, self._scheduler_alg)\n    self._memory_contents = self._graph.compute_memory_contents_under_schedule(\n        schedule)\n    return self._memory_contents",
    "docstring": "Runs the scheduler to determine memory contents at every point in time.\n\n    Returns:\n      a list of frozenset of strings, where the ith entry describes the tensors\n      in memory when executing operation i (where schedule[i] is an index into\n      GetAllOperationNames())."
  },
  {
    "code": "def rivermap_update(self, river, water_flow, rivermap, precipitations):\n        isSeed = True\n        px, py = (0, 0)\n        for x, y in river:\n            if isSeed:\n                rivermap[y, x] = water_flow[y, x]\n                isSeed = False\n            else:\n                rivermap[y, x] = precipitations[y, x] + rivermap[py, px]\n            px, py = x, y",
    "docstring": "Update the rivermap with the rainfall that is to become\n        the waterflow"
  },
  {
    "code": "def load_config(self):\n        config = Config()\n        self.config_obj = config.load('awsshellrc')\n        self.config_section = self.config_obj['aws-shell']\n        self.model_completer.match_fuzzy = self.config_section.as_bool(\n            'match_fuzzy')\n        self.enable_vi_bindings = self.config_section.as_bool(\n            'enable_vi_bindings')\n        self.show_completion_columns = self.config_section.as_bool(\n            'show_completion_columns')\n        self.show_help = self.config_section.as_bool('show_help')\n        self.theme = self.config_section['theme']",
    "docstring": "Load the config from the config file or template."
  },
  {
    "code": "def remove_ipv4addr(self, ipv4addr):\n        for addr in self.ipv4addrs:\n            if ((isinstance(addr, dict) and addr['ipv4addr'] == ipv4addr) or\n                (isinstance(addr, HostIPv4) and addr.ipv4addr == ipv4addr)):\n                self.ipv4addrs.remove(addr)\n                break",
    "docstring": "Remove an IPv4 address from the host.\n\n        :param str ipv4addr: The IP address to remove"
  },
  {
    "code": "def get_bitcoind_client():\n    bitcoind_opts = get_bitcoin_opts()\n    bitcoind_host = bitcoind_opts['bitcoind_server']\n    bitcoind_port = bitcoind_opts['bitcoind_port']\n    bitcoind_user = bitcoind_opts['bitcoind_user']\n    bitcoind_passwd = bitcoind_opts['bitcoind_passwd']\n    return create_bitcoind_service_proxy(bitcoind_user, bitcoind_passwd, server=bitcoind_host, port=bitcoind_port)",
    "docstring": "Connect to the bitcoind node"
  },
  {
    "code": "def datetime(self):\n        if 'dt_scale' not in self._cache.keys():\n            self._cache['dt_scale'] = self._datetime - timedelta(seconds=self._offset)\n        return self._cache['dt_scale']",
    "docstring": "Conversion of the Date object into a ``datetime.datetime``\n\n        The resulting object is a timezone-naive instance with the same scale\n        as the originating Date object."
  },
  {
    "code": "def com_daltonmaag_check_required_fields(ufo_font):\n  recommended_fields = []\n  for field in [\n      \"unitsPerEm\", \"ascender\", \"descender\", \"xHeight\", \"capHeight\",\n      \"familyName\"\n  ]:\n    if ufo_font.info.__dict__.get(\"_\" + field) is None:\n      recommended_fields.append(field)\n  if recommended_fields:\n    yield FAIL, f\"Required field(s) missing: {recommended_fields}\"\n  else:\n    yield PASS, \"Required fields present.\"",
    "docstring": "Check that required fields are present in the UFO fontinfo.\n\n    ufo2ft requires these info fields to compile a font binary:\n    unitsPerEm, ascender, descender, xHeight, capHeight and familyName."
  },
  {
    "code": "def remove_polygons(self, test):\n        empty = []\n        for element in self.elements:\n            if isinstance(element, PolygonSet):\n                ii = 0\n                while ii < len(element.polygons):\n                    if test(element.polygons[ii], element.layers[ii],\n                            element.datatypes[ii]):\n                        element.polygons.pop(ii)\n                        element.layers.pop(ii)\n                        element.datatypes.pop(ii)\n                    else:\n                        ii += 1\n                if len(element.polygons) == 0:\n                    empty.append(element)\n        for element in empty:\n            self.elements.remove(element)\n        return self",
    "docstring": "Remove polygons from this cell.\n\n        The function or callable ``test`` is called for each polygon in\n        the cell.  If its return value evaluates to ``True``, the\n        corresponding polygon is removed from the cell.\n\n        Parameters\n        ----------\n        test : callable\n            Test function to query whether a polygon should be removed.\n            The function is called with arguments:\n            ``(points, layer, datatype)``\n\n        Returns\n        -------\n        out : ``Cell``\n            This cell.\n\n        Examples\n        --------\n        Remove polygons in layer 1:\n\n        >>> cell.remove_polygons(lambda pts, layer, datatype:\n        ...                      layer == 1)\n\n        Remove polygons with negative x coordinates:\n\n        >>> cell.remove_polygons(lambda pts, layer, datatype:\n        ...                      any(pts[:, 0] < 0))"
  },
  {
    "code": "def as_list_data(self):\n        element = ElementTree.Element(self.list_type)\n        id_ = ElementTree.SubElement(element, \"id\")\n        id_.text = self.id\n        name = ElementTree.SubElement(element, \"name\")\n        name.text = self.name\n        return element",
    "docstring": "Return an Element to be used in a list.\n\n        Most lists want an element with tag of list_type, and\n        subelements of id and name.\n\n        Returns:\n            Element: list representation of object."
  },
  {
    "code": "def pull_cfg_from_parameters_out_file(\n    parameters_out_file, namelist_to_read=\"nml_allcfgs\"\n):\n    parameters_out = read_cfg_file(parameters_out_file)\n    return pull_cfg_from_parameters_out(\n        parameters_out, namelist_to_read=namelist_to_read\n    )",
    "docstring": "Pull out a single config set from a MAGICC ``PARAMETERS.OUT`` file.\n\n    This function reads in the ``PARAMETERS.OUT`` file and returns a single file with\n    the config that needs to be passed to MAGICC in order to do the same run as is\n    represented by the values in ``PARAMETERS.OUT``.\n\n    Parameters\n    ----------\n    parameters_out_file : str\n        The ``PARAMETERS.OUT`` file to read\n\n    namelist_to_read : str\n        The namelist to read from the file.\n\n    Returns\n    -------\n    :obj:`f90nml.Namelist`\n        An f90nml object with the cleaned, read out config.\n\n    Examples\n    --------\n    >>> cfg = pull_cfg_from_parameters_out_file(\"PARAMETERS.OUT\")\n    >>> cfg.write(\"/somewhere/else/ANOTHERNAME.cfg\")"
  },
  {
    "code": "def as_ordered_dict(self, preference_orders: List[List[str]] = None) -> OrderedDict:\n        params_dict = self.as_dict(quiet=True)\n        if not preference_orders:\n            preference_orders = []\n            preference_orders.append([\"dataset_reader\", \"iterator\", \"model\",\n                                      \"train_data_path\", \"validation_data_path\", \"test_data_path\",\n                                      \"trainer\", \"vocabulary\"])\n            preference_orders.append([\"type\"])\n        def order_func(key):\n            order_tuple = [order.index(key) if key in order else len(order) for order in preference_orders]\n            return order_tuple + [key]\n        def order_dict(dictionary, order_func):\n            result = OrderedDict()\n            for key, val in sorted(dictionary.items(), key=lambda item: order_func(item[0])):\n                result[key] = order_dict(val, order_func) if isinstance(val, dict) else val\n            return result\n        return order_dict(params_dict, order_func)",
    "docstring": "Returns Ordered Dict of Params from list of partial order preferences.\n\n        Parameters\n        ----------\n        preference_orders: List[List[str]], optional\n            ``preference_orders`` is list of partial preference orders. [\"A\", \"B\", \"C\"] means\n            \"A\" > \"B\" > \"C\". For multiple preference_orders first will be considered first.\n            Keys not found, will have last but alphabetical preference. Default Preferences:\n            ``[[\"dataset_reader\", \"iterator\", \"model\", \"train_data_path\", \"validation_data_path\",\n            \"test_data_path\", \"trainer\", \"vocabulary\"], [\"type\"]]``"
  },
  {
    "code": "def unserialize(cls, string):\n        id_s, created_s = string.split('_')\n        return cls(int(id_s, 16),\n                   datetime.utcfromtimestamp(int(created_s, 16)))",
    "docstring": "Unserializes from a string.\n\n        :param string: A string created by :meth:`serialize`."
  },
  {
    "code": "def _read_sequences(self, graph):\n        for e in self._get_elements(graph, SBOL.Sequence):\n            identity = e[0]\n            c = self._get_rdf_identified(graph, identity)\n            c['elements'] = self._get_triplet_value(graph, identity, SBOL.elements)\n            c['encoding'] = self._get_triplet_value(graph, identity, SBOL.encoding)\n            seq = Sequence(**c)\n            self._sequences[identity.toPython()] = seq\n            self._collection_store[identity.toPython()] = seq",
    "docstring": "Read graph and add sequences to document"
  },
  {
    "code": "def catch_exceptions(orig_func):\n    @functools.wraps(orig_func)\n    def catch_exceptions_wrapper(self, *args, **kwargs):\n        try:\n            return orig_func(self, *args, **kwargs)\n        except arvados.errors.ApiError as e:\n            logging.exception(\"Failure\")\n            return {\"msg\": e._get_reason(), \"status_code\": e.resp.status}, int(e.resp.status)\n        except subprocess.CalledProcessError as e:\n            return {\"msg\": str(e), \"status_code\": 500}, 500\n        except MissingAuthorization:\n            return {\"msg\": \"'Authorization' header is missing or empty, expecting Arvados API token\", \"status_code\": 401}, 401\n        except ValueError as e:\n            return {\"msg\": str(e), \"status_code\": 400}, 400\n        except Exception as e:\n            return {\"msg\": str(e), \"status_code\": 500}, 500\n    return catch_exceptions_wrapper",
    "docstring": "Catch uncaught exceptions and turn them into http errors"
  },
  {
    "code": "def infer_declared(ms, namespace=None):\n    conditions = []\n    for m in ms:\n        for cav in m.caveats:\n            if cav.location is None or cav.location == '':\n                conditions.append(cav.caveat_id_bytes.decode('utf-8'))\n    return infer_declared_from_conditions(conditions, namespace)",
    "docstring": "Retrieves any declared information from the given macaroons and returns\n    it as a key-value map.\n    Information is declared with a first party caveat as created by\n    declared_caveat.\n\n    If there are two caveats that declare the same key with different values,\n    the information is omitted from the map. When the caveats are later\n    checked, this will cause the check to fail.\n    namespace is the Namespace used to retrieve the prefix associated to the\n    uri, if None it will use the STD_NAMESPACE only."
  },
  {
    "code": "def to_datetime(value):\n    if value is None:\n        return None\n    if isinstance(value, six.integer_types):\n        return parser.parse(value)\n    return parser.isoparse(value)",
    "docstring": "Converts a string to a datetime."
  },
  {
    "code": "def send_message(self, msg):\n        if self.socket is not None:\n            msg.version = self.PROTOCOL_VERSION\n            serialized = msg.SerializeToString()\n            data = struct.pack(\">I\", len(serialized)) + serialized\n            try:\n                self.socket.send(data)\n            except Exception as e:\n                pass",
    "docstring": "Internal method used to send messages through Clementine remote network protocol."
  },
  {
    "code": "def reftrack_version_data(rt, role):\n    tfi = rt.get_taskfileinfo()\n    if not tfi:\n        return\n    return filesysitemdata.taskfileinfo_version_data(tfi, role)",
    "docstring": "Return the data for the version that is loaded by the reftrack\n\n    :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data\n    :type rt: :class:`jukeboxcore.reftrack.Reftrack`\n    :param role: item data role\n    :type role: QtCore.Qt.ItemDataRole\n    :returns: data for the version\n    :rtype: depending on role\n    :raises: None"
  },
  {
    "code": "def get_results(self, job_id):\n        url = self._url('%s/results' % job_id)\n        return self.client.get(url)",
    "docstring": "Get results of a job\n\n        Args:\n            job_id (str): The ID of the job.\n\n        See: https://auth0.com/docs/api/management/v2#!/Jobs/get_results"
  },
  {
    "code": "def s3path(self, rel_path):\n        import urlparse\n        path = self.path(rel_path, public_url=True)\n        parts = list(urlparse.urlparse(path))\n        parts[0] = 's3'\n        parts[1] = self.bucket_name\n        return urlparse.urlunparse(parts)",
    "docstring": "Return the path as an S3 schema"
  },
  {
    "code": "def postActivate_(self):\n        self.tmpfile = os.path.join(constant.tmpdir,\"valkka-\"+str(os.getpid()))\n        self.analyzer = ExternalDetector(\n            executable = self.executable,\n            image_dimensions = self.image_dimensions,\n            tmpfile = self.tmpfile\n            )",
    "docstring": "Create temporary file for image dumps and the analyzer itself"
  },
  {
    "code": "def group_id(self, resource_id):\n        if self._name != 'group':\n            self._request_uri = '{}/{}'.format(self._api_uri, resource_id)",
    "docstring": "Update the request URI to include the Group ID for specific group retrieval.\n\n        Args:\n            resource_id (string): The group id."
  },
  {
    "code": "def _setID(self, id):\n        if type(id) in (types.ListType, types.TupleType):\n            try:\n                for key in self._sqlPrimary:\n                    value = id[0]\n                    self.__dict__[key] = value\n                    id = id[1:]\n            except IndexError:\n                raise 'Not enough id fields, required: %s' % len(self._sqlPrimary)\n        elif len(self._sqlPrimary) <= 1:\n            key = self._sqlPrimary[0]\n            self.__dict__[key] = id\n        else:\n            raise 'Not enough id fields, required: %s' % len(self._sqlPrimary)\n        self._new = False",
    "docstring": "Set the ID, ie. the values for primary keys.\n\n        id can be either a list, following the\n        _sqlPrimary, or some other type, that will be set\n        as the singleton ID (requires 1-length sqlPrimary)."
  },
  {
    "code": "def non_interactions(graph, t=None):\n    nodes = set(graph)\n    while nodes:\n        u = nodes.pop()\n        for v in nodes - set(graph[u]):\n            yield (u, v)",
    "docstring": "Returns the non-existent edges in the graph at time t.\n\n        Parameters\n        ----------\n\n        graph : NetworkX graph.\n            Graph to find non-existent edges.\n\n        t : snapshot id (default=None)\n            If None the non-existent edges are identified on the flattened graph.\n\n\n        Returns\n        -------\n        non_edges : iterator\n            Iterator of edges that are not in the graph."
  },
  {
    "code": "def group_list(**kwargs):\n    ctx = Context(**kwargs)\n    ctx.execute_action('group:list', **{\n        'storage': ctx.repo.create_secure_service('storage'),\n    })",
    "docstring": "Show available routing groups."
  },
  {
    "code": "def get_hostinfo(self,callb=None):\n        response = self.req_with_resp(GetInfo, StateInfo,callb=callb )\n        return None",
    "docstring": "Convenience method to request the device info from the device\n\n        This will request the information from the device and request that callb be executed\n        when a response is received. The is no  default callback\n\n        :param callb: Callable to be used when the response is received. If not set,\n                      self.resp_set_label will be used.\n        :type callb: callable\n        :returns: None\n        :rtype: None"
  },
  {
    "code": "def user_add_link(self):\n        if self.check_post_role()['ADD']:\n            pass\n        else:\n            return False\n        post_data = self.get_post_data()\n        post_data['user_name'] = self.get_current_user()\n        cur_uid = tools.get_uudd(2)\n        while MLink.get_by_uid(cur_uid):\n            cur_uid = tools.get_uudd(2)\n        MLink.create_link(cur_uid, post_data)\n        self.redirect('/link/list')",
    "docstring": "Create link by user."
  },
  {
    "code": "def generate_command(self):\n        example = []\n        example.append(f\"{sys.argv[0]}\")\n        for key in sorted(list(self.spec.keys())):\n            if self.spec[key]['type'] == list:\n                value = \" \".join(self.spec[key].get('example', ''))\n            elif self.spec[key]['type'] == dict:\n                value = f\"\\'{json.dumps(self.spec[key].get('example', ''))}\\'\"\n            else:\n                value = self.spec[key].get('example', '')\n            string = f\"     --{key.lower()} {value}\"\n            example.append(string)\n        print(\" \\\\\\n\".join(example))",
    "docstring": "Generate a sample command"
  },
  {
    "code": "def vfolders(access_key):\n    fields = [\n        ('Name', 'name'),\n        ('Created At', 'created_at'),\n        ('Last Used', 'last_used'),\n        ('Max Files', 'max_files'),\n        ('Max Size', 'max_size'),\n    ]\n    if access_key is None:\n        q = 'query { vfolders { $fields } }'\n    else:\n        q = 'query($ak:String) { vfolders(access_key:$ak) { $fields } }'\n    q = q.replace('$fields', ' '.join(item[1] for item in fields))\n    v = {'ak': access_key}\n    with Session() as session:\n        try:\n            resp = session.Admin.query(q, v)\n        except Exception as e:\n            print_error(e)\n            sys.exit(1)\n        print(tabulate((item.values() for item in resp['vfolders']),\n                       headers=(item[0] for item in fields)))",
    "docstring": "List and manage virtual folders."
  },
  {
    "code": "def send(self, message):\n        try:\n            self.ws.send(json.dumps(message))\n        except websocket._exceptions.WebSocketConnectionClosedException:\n            raise SelenolWebSocketClosedException()",
    "docstring": "Send a the defined message to the backend.\n\n        :param message: Message to be send, usually a Python dictionary."
  },
  {
    "code": "def load_private_key(self, priv_key):\n        with open(priv_key) as fd:\n            self._private_key = paramiko.RSAKey.from_private_key(fd)",
    "docstring": "Register the SSH private key."
  },
  {
    "code": "def _fragment_one_level(self, mol_graphs):\n        unique_fragments_on_this_level = []\n        for mol_graph in mol_graphs:\n            for edge in mol_graph.graph.edges:\n                bond = [(edge[0],edge[1])]\n                try:\n                    fragments = mol_graph.split_molecule_subgraphs(bond, allow_reverse=True)\n                    for fragment in fragments:\n                        found = False\n                        for unique_fragment in self.unique_fragments:\n                            if unique_fragment.isomorphic_to(fragment):\n                                found = True\n                                break\n                        if not found:\n                            self.unique_fragments.append(fragment)\n                            unique_fragments_on_this_level.append(fragment)\n                except MolGraphSplitError:\n                    if self.open_rings:\n                        fragment = open_ring(mol_graph, bond, self.opt_steps)\n                        found = False\n                        for unique_fragment in self.unique_fragments:\n                            if unique_fragment.isomorphic_to(fragment):\n                                found = True\n                                break\n                        if not found:\n                            self.unique_fragments.append(fragment)\n                            self.unique_fragments_from_ring_openings.append(fragment)\n                            unique_fragments_on_this_level.append(fragment)\n        return unique_fragments_on_this_level",
    "docstring": "Perform one step of iterative fragmentation on a list of molecule graphs. Loop through the graphs,\n        then loop through each graph's edges and attempt to remove that edge in order to obtain two\n        disconnected subgraphs, aka two new fragments. If successful, check to see if the new fragments\n        are already present in self.unique_fragments, and append them if not. If unsucessful, we know\n        that edge belongs to a ring. If we are opening rings, do so with that bond, and then again\n        check if the resulting fragment is present in self.unique_fragments and add it if it is not."
  },
  {
    "code": "def _make_transitions(self) -> List[Transition]:\n        module_name = settings.TRANSITIONS_MODULE\n        module_ = importlib.import_module(module_name)\n        return module_.transitions",
    "docstring": "Load the transitions file."
  },
  {
    "code": "def last(self):\n        start = max(self.number - 1, 0) * self.size\n        return Batch(start, self.size, self.total_size)",
    "docstring": "Returns the last batch for the batched sequence.\n\n        :rtype: :class:`Batch` instance."
  },
  {
    "code": "def worldview(self) -> str:\n        views = self._data['worldview']\n        return self.random.choice(views)",
    "docstring": "Get a random worldview.\n\n        :return: Worldview.\n\n        :Example:\n            Pantheism."
  },
  {
    "code": "def get_obs_function(self):\n        obs_function = []\n        for variable in self.network.findall('ObsFunction'):\n            for var in variable.findall('CondProb'):\n                cond_prob = defaultdict(list)\n                cond_prob['Var'] = var.find('Var').text\n                cond_prob['Parent'] = var.find('Parent').text.split()\n                if not var.find('Parameter').get('type'):\n                    cond_prob['Type'] = 'TBL'\n                else:\n                    cond_prob['Type'] = var.find('Parameter').get('type')\n                cond_prob['Parameter'] = self.get_parameter(var)\n                obs_function.append(cond_prob)\n        return obs_function",
    "docstring": "Returns the observation function as nested dict in the case of table-\n        type parameter and a nested structure in case of\n        decision diagram parameter\n\n        Example\n        --------\n        >>> reader = PomdpXReader('Test_PomdpX.xml')\n        >>> reader.get_obs_function()\n        [{'Var': 'obs_sensor',\n              'Parent': ['action_rover', 'rover_1', 'rock_1'],\n              'Type': 'TBL',\n              'Parameter': [{'Instance': ['amw', '*', '*', '-'],\n                             'ProbTable': ['1.0', '0.0']},\n                         ...\n                        ]\n        }]"
  },
  {
    "code": "def _get_template_dirs():\n    return filter(lambda x: os.path.exists(x), [\n        os.path.join(os.path.expanduser('~'), '.py2pack', 'templates'),\n        os.path.join('/', 'usr', 'share', 'py2pack', 'templates'),\n        os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'),\n    ])",
    "docstring": "existing directories where to search for jinja2 templates. The order\n    is important. The first found template from the first found dir wins!"
  },
  {
    "code": "def in_unit_of(self, unit, as_quantity=False):\n        new_unit = u.Unit(unit)\n        new_quantity = self.as_quantity.to(new_unit)\n        if as_quantity:\n            return new_quantity\n        else:\n            return new_quantity.value",
    "docstring": "Return the current value transformed to the new units\n\n        :param unit: either an astropy.Unit instance, or a string which can be converted to an astropy.Unit\n            instance, like \"1 / (erg cm**2 s)\"\n        :param as_quantity: if True, the method return an astropy.Quantity, if False just a floating point number.\n            Default is False\n        :return: either a floating point or a astropy.Quantity depending on the value of \"as_quantity\""
  },
  {
    "code": "def pdf_row_limiter(rows, limits=None, **kwargs):\n    limits = limits or [None, None]\n    upper_limit = limits[0] if limits else None\n    lower_limit = limits[1] if len(limits) > 1 else None\n    return rows[upper_limit: lower_limit]",
    "docstring": "Limit row passing a value. In this case we dont implementate a best effort\n    algorithm because the posibilities are infite with a data text structure\n    from a pdf."
  },
  {
    "code": "def login(self, username, password):\n        d = self.send_command('login', keys={'client_login_name': username, 'client_login_password': password})\n        if d == 0:\n            self._log.info('Login Successful')\n            return True\n        return False",
    "docstring": "Login to the TS3 Server\n        @param username: Username\n        @type username: str\n        @param password: Password\n        @type password: str"
  },
  {
    "code": "def start(self):\n        self.stop()\n        self._task = asyncio.ensure_future(self._pinger(), loop=self._loop)",
    "docstring": "Start the pinging coroutine using the client and event loop which was\n        passed to the constructor.\n\n        :meth:`start` always behaves as if :meth:`stop` was called right before\n        it."
  },
  {
    "code": "def callback(self, cats):\n        enable = bool(cats)\n        if not enable:\n            self.search.visible = False\n        enable_widget(self.search_widget, enable)\n        enable_widget(self.remove_widget, enable)\n        if self.done_callback:\n            self.done_callback(cats)",
    "docstring": "When a catalog is selected, enable widgets that depend on that condition\n        and do done_callback"
  },
  {
    "code": "def secgroup_create(self, name, description):\n        nt_ks = self.compute_conn\n        nt_ks.security_groups.create(name, description)\n        ret = {'name': name, 'description': description}\n        return ret",
    "docstring": "Create a security group"
  },
  {
    "code": "def add_section(self, section_name):\n        if section_name == \"DEFAULT\":\n            raise Exception(\"'DEFAULT' is reserved section name.\")\n        if section_name in self._sections:\n            raise Exception(\n                \"Error! %s is already one of the sections\" % section_name)\n        else:\n            self._sections[section_name] = Section(section_name)",
    "docstring": "Add an empty section."
  },
  {
    "code": "def _filter_response(self, response_dict):\n        filtered_dict = {}\n        for key, value in response_dict.items():\n            if key == \"_jsns\":\n                continue\n            if key == \"xmlns\":\n                continue\n            if type(value) == list and len(value) == 1:\n                filtered_dict[key] = value[0]\n            elif type(value) == dict and len(value.keys()) == 1 and \"_content\" \\\n                    in value.keys():\n                filtered_dict[key] = value[\"_content\"]\n            elif type(value) == dict:\n                tmp_dict = self._filter_response(value)\n                filtered_dict[key] = tmp_dict\n            else:\n                filtered_dict[key] = value\n        return filtered_dict",
    "docstring": "Add additional filters to the response dictionary\n\n        Currently the response dictionary is filtered like this:\n\n          * If a list only has one item, the list is replaced by that item\n          * Namespace-Keys (_jsns and xmlns) are removed\n\n        :param response_dict: the pregenerated, but unfiltered response dict\n        :type response_dict: dict\n        :return: The filtered dictionary\n        :rtype: dict"
  },
  {
    "code": "def _call_config(self, method, *args, **kwargs):\n        return getattr(self._config, method)(self._section_name, *args, **kwargs)",
    "docstring": "Call the configuration at the given method which must take a section name\n        as first argument"
  },
  {
    "code": "def _select_options(pat):\n    if pat in _registered_options:\n        return [pat]\n    keys = sorted(_registered_options.keys())\n    if pat == 'all':\n        return keys\n    return [k for k in keys if re.search(pat, k, re.I)]",
    "docstring": "returns a list of keys matching `pat`\n\n    if pat==\"all\", returns all registered options"
  },
  {
    "code": "def findCampaignsByName(target):\n    try:\n        from astropy.coordinates import SkyCoord\n        from astropy.coordinates.name_resolve import NameResolveError\n        from astropy.utils.data import conf\n        conf.remote_timeout = 90\n    except ImportError:\n        print('Error: AstroPy needs to be installed for this feature.')\n        sys.exit(1)\n    try:\n        crd = SkyCoord.from_name(target)\n    except NameResolveError:\n        raise ValueError('Could not find coordinates '\n                         'for target \"{0}\".'.format(target))\n    return findCampaigns(crd.ra.deg, crd.dec.deg), crd.ra.deg, crd.dec.deg",
    "docstring": "Returns a list of the campaigns that cover a given target.\n\n    Parameters\n    ----------\n    target : str\n        Name of the celestial object.\n\n    Returns\n    -------\n    campaigns : list of int\n        A list of the campaigns that cover the given target name.\n\n    ra, dec : float, float\n        Resolved coordinates in decimal degrees (J2000).\n\n    Exceptions\n    ----------\n    Raises an ImportError if AstroPy is not installed.\n    Raises a ValueError if `name` cannot be resolved to coordinates."
  },
  {
    "code": "def delete(self, file_path, branch, commit_message, **kwargs):\n        path = '%s/%s' % (self.path, file_path.replace('/', '%2F'))\n        data = {'branch': branch, 'commit_message': commit_message}\n        self.gitlab.http_delete(path, query_data=data, **kwargs)",
    "docstring": "Delete a file on the server.\n\n        Args:\n            file_path (str): Path of the file to remove\n            branch (str): Branch from which the file will be removed\n            commit_message (str): Commit message for the deletion\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabDeleteError: If the server cannot perform the request"
  },
  {
    "code": "def getDataPath(_system=thisSystem, _FilePath=FilePath):\n    if _system == \"Windows\":\n        pathName = \"~/Crypto101/\"\n    else:\n        pathName = \"~/.crypto101/\"\n    path = _FilePath(expanduser(pathName))\n    if not path.exists():\n        path.makedirs()\n    return path",
    "docstring": "Gets an appropriate path for storing some local data, such as TLS\n    credentials.\n\n    If the path doesn't exist, it is created."
  },
  {
    "code": "def p_startswith(self, st, ignorecase=False):\n        \"Return True if the input starts with `st` at current position\"\n        length = len(st)\n        matcher = result = self.input[self.pos:self.pos + length]\n        if ignorecase:\n            matcher = result.lower()\n            st = st.lower()\n        if matcher == st:\n            self.pos += length\n            return result\n        return False",
    "docstring": "Return True if the input starts with `st` at current position"
  },
  {
    "code": "def add_text(self, end, next=None):\n        if self.str_begin != end:\n            self.fmt.append_text(self.format[self.str_begin:end])\n        if next is not None:\n            self.str_begin = next",
    "docstring": "Adds the text from string beginning to the specified ending\n        index to the format.\n\n        :param end: The ending index of the string.\n        :param next: The next string begin index.  If None, the string\n                     index will not be updated."
  },
  {
    "code": "def hash(*cols):\n    sc = SparkContext._active_spark_context\n    jc = sc._jvm.functions.hash(_to_seq(sc, cols, _to_java_column))\n    return Column(jc)",
    "docstring": "Calculates the hash code of given columns, and returns the result as an int column.\n\n    >>> spark.createDataFrame([('ABC',)], ['a']).select(hash('a').alias('hash')).collect()\n    [Row(hash=-757602832)]"
  },
  {
    "code": "def delete(self):\n        if self.parent is None:\n            raise RuntimeError(\n                \"Current statement has no parent, so it cannot \"\n                + \"be deleted form a procmailrc structure\"\n            )\n        elif self.id is None:\n            raise RuntimeError(\"id not set but have a parent, this should not be happening\")\n        else:\n            parent_id = self.parent.id\n            index = int(self.id.split('.')[-1])\n            self.parent.pop(index)\n            self.parent = None\n            self.id = None\n            return parent_id",
    "docstring": "Remove the statement from a ProcmailRC structure, raise a\n        RuntimeError if the statement is not inside a ProcmailRC structure\n        return the parent id"
  },
  {
    "code": "def on_exception(func):\n    class OnExceptionDecorator(LambdaDecorator):\n        def on_exception(self, exception):\n            return func(exception)\n    return OnExceptionDecorator",
    "docstring": "Run a function when a handler thows an exception. It's return value is\n    returned to AWS.\n\n    Usage::\n\n        >>> # to create a reusable decorator\n        >>> @on_exception\n        ... def handle_errors(exception):\n        ...     print(exception)\n        ...     return {'statusCode': 500, 'body': 'uh oh'}\n        >>> @handle_errors\n        ... def handler(event, context):\n        ...     raise Exception('it broke!')\n        >>> handler({}, object())\n        it broke!\n        {'statusCode': 500, 'body': 'uh oh'}\n        >>> # or a one off\n        >>> @on_exception(lambda e: {'statusCode': 500})\n        ... def handler(body, context):\n        ...     raise Exception\n        >>> handler({}, object())\n        {'statusCode': 500}"
  },
  {
    "code": "def reflected_light_intensity(self):\n        self._ensure_mode(self.MODE_REFLECT)\n        return self.value(0) * self._scale('REFLECT')",
    "docstring": "A measurement of the reflected light intensity, as a percentage."
  },
  {
    "code": "def call_requests(\n    requests: Union[Request, Iterable[Request]], methods: Methods, debug: bool\n) -> Response:\n    if isinstance(requests, collections.Iterable):\n        return BatchResponse(safe_call(r, methods, debug=debug) for r in requests)\n    return safe_call(requests, methods, debug=debug)",
    "docstring": "Takes a request or list of Requests and calls them.\n\n    Args:\n        requests: Request object, or a collection of them.\n        methods: The list of methods that can be called.\n        debug: Include more information in error responses."
  },
  {
    "code": "def update_terms_translations(self, project_id, file_path=None,\n                                 language_code=None, overwrite=False,\n                                 sync_terms=False, tags=None, fuzzy_trigger=None):\n        return self._upload(\n            project_id=project_id,\n            updating=self.UPDATING_TERMS_TRANSLATIONS,\n            file_path=file_path,\n            language_code=language_code,\n            overwrite=overwrite,\n            sync_terms=sync_terms,\n            tags=tags,\n            fuzzy_trigger=fuzzy_trigger\n        )",
    "docstring": "Updates terms translations\n\n        overwrite: set it to True if you want to overwrite translations\n        sync_terms: set it to True if you want to sync your terms (terms that\n            are not found in the uploaded file will be deleted from project\n            and the new ones added). Ignored if updating = translations\n        tags: Add tags to the project terms; available when updating terms or terms_translations;\n              you can use the following keys: \"all\" - for the all the imported terms, \"new\" - for\n              the terms which aren't already in the project, \"obsolete\" - for the terms which are\n              in the project but not in the imported file and \"overwritten_translations\" - for the\n              terms for which translations change\n        fuzzy_trigger: set it to True to mark corresponding translations from the\n            other languages as fuzzy for the updated values"
  },
  {
    "code": "def init_controller(url):\n    global _VERA_CONTROLLER\n    created = False\n    if _VERA_CONTROLLER is None:\n        _VERA_CONTROLLER = VeraController(url)\n        created = True\n        _VERA_CONTROLLER.start()\n    return [_VERA_CONTROLLER, created]",
    "docstring": "Initialize a controller.\n\n    Provides a single global controller for applications that can't do this\n    themselves"
  },
  {
    "code": "def as_scipy_functional(func, return_gradient=False):\n    def func_call(arr):\n        return func(np.asarray(arr).reshape(func.domain.shape))\n    if return_gradient:\n        def func_gradient_call(arr):\n            return np.asarray(\n                func.gradient(np.asarray(arr).reshape(func.domain.shape)))\n        return func_call, func_gradient_call\n    else:\n        return func_call",
    "docstring": "Wrap ``op`` as a function operating on linear arrays.\n\n    This is intended to be used with the `scipy solvers\n    <https://docs.scipy.org/doc/scipy/reference/optimize.html>`_.\n\n    Parameters\n    ----------\n    func : `Functional`.\n        A functional that should be wrapped\n    return_gradient : bool, optional\n        ``True`` if the gradient of the functional should also be returned,\n        ``False`` otherwise.\n\n    Returns\n    -------\n    function : ``callable``\n        The wrapped functional.\n    gradient : ``callable``, optional\n        The wrapped gradient. Only returned if ``return_gradient`` is true.\n\n    Examples\n    --------\n    Wrap functional and solve simple problem\n    (here toy problem ``min_x ||x||^2``):\n\n    >>> func = odl.solvers.L2NormSquared(odl.rn(3))\n    >>> scipy_func = odl.as_scipy_functional(func)\n    >>> from scipy.optimize import minimize\n    >>> result = minimize(scipy_func, x0=[0, 1, 0])\n    >>> np.allclose(result.x, [0, 0, 0])\n    True\n\n    The gradient (jacobian) can also be provided:\n\n    >>> func = odl.solvers.L2NormSquared(odl.rn(3))\n    >>> scipy_func, scipy_grad = odl.as_scipy_functional(func, True)\n    >>> from scipy.optimize import minimize\n    >>> result = minimize(scipy_func, x0=[0, 1, 0], jac=scipy_grad)\n    >>> np.allclose(result.x, [0, 0, 0])\n    True\n\n    Notes\n    -----\n    If the data representation of ``op``'s domain is of type\n    `NumpyTensorSpace`, this incurs no significant overhead. If the space type\n    is ``CudaFn`` or some other nonlocal type, the overhead is significant."
  },
  {
    "code": "def webhook_handler(request):\n    body = request.stream.read().decode('utf8')\n    print('webhook handler saw:', body)\n    api.notify_webhook_received(payload=body)\n    print('key store contains:', api._db.keys())",
    "docstring": "Receives the webhook from mbed cloud services\n\n    Passes the raw http body directly to mbed sdk, to notify that a webhook was received"
  },
  {
    "code": "def is_superset(reference_set\n                ):\n    def is_superset_of(x):\n        missing = reference_set - x\n        if len(missing) == 0:\n            return True\n        else:\n            raise NotSuperset(wrong_value=x, reference_set=reference_set, missing=missing)\n    is_superset_of.__name__ = 'is_superset_of_{}'.format(reference_set)\n    return is_superset_of",
    "docstring": "'Is superset' validation_function generator.\n    Returns a validation_function to check that x is a superset of reference_set\n\n    :param reference_set: the reference set\n    :return:"
  },
  {
    "code": "def select_subscription(subs_code, subscriptions):\n    if subs_code and subscriptions:\n        for subs in subscriptions:\n            if (subs.subscription_code == subs_code):\n                return subs\n    return None",
    "docstring": "Return the uwnetid.subscription object with the subs_code."
  },
  {
    "code": "def pickle_dict(items):\n    ret = {}\n    pickled_keys = []\n    for key, val in items.items():\n        if isinstance(val, basestring):\n            ret[key] = val\n        else:\n            pickled_keys.append(key)\n            ret[key] = pickle.dumps(val)\n    if pickled_keys:\n        ret['_pickled'] = ','.join(pickled_keys)\n    return ret",
    "docstring": "Returns a new dictionary where values which aren't instances of\n    basestring are pickled. Also, a new key '_pickled' contains a comma\n    separated list of keys corresponding to the pickled values."
  },
  {
    "code": "def GET(self, url):\n        r = requests.get(url)\n        if self.verbose:\n            sys.stdout.write(\"%s %s\\n\" % (r.status_code, r.encoding))\n            sys.stdout.write(str(r.headers) + \"\\n\")\n        self.encoding = r.encoding\n        return r.text",
    "docstring": "returns text content of HTTP GET response."
  },
  {
    "code": "def _case_stmt(self, stmt: Statement, sctx: SchemaContext) -> None:\n        self._handle_child(CaseNode(), stmt, sctx)",
    "docstring": "Handle case statement."
  },
  {
    "code": "def delete(self):\n        key = 'https://plex.tv/devices/%s.xml' % self.id\n        self._server.query(key, self._server._session.delete)",
    "docstring": "Remove this device from your account."
  },
  {
    "code": "def rotate_key(self, name, mount_point=DEFAULT_MOUNT_POINT):\n        api_path = '/v1/{mount_point}/keys/{name}/rotate'.format(\n            mount_point=mount_point,\n            name=name,\n        )\n        return self._adapter.post(\n            url=api_path,\n        )",
    "docstring": "Rotate the version of the named key.\n\n        After rotation, new plaintext requests will be encrypted with the new version of the key. To upgrade ciphertext\n        to be encrypted with the latest version of the key, use the rewrap endpoint. This is only supported with keys\n        that support encryption and decryption operations.\n\n        Supported methods:\n            POST: /{mount_point}/keys/{name}/rotate. Produces: 204 (empty body)\n\n        :param name: Specifies the name of the key to read information about. This is specified as part of the URL.\n        :type name: str | unicode\n        :param mount_point: The \"path\" the method/backend was mounted on.\n        :type mount_point: str | unicode\n        :return: The response of the request.\n        :rtype: requests.Response"
  },
  {
    "code": "def build_script(data):\n        return bitcoin.core.script.CScript(\n            bytes([bitcoin.core.script.OP_RETURN]) + bitcoin.core.script.CScriptOp.encode_op_pushdata(data))",
    "docstring": "Creates an output script containing an OP_RETURN and a PUSHDATA.\n\n        :param bytes data: The content of the PUSHDATA.\n        :return: The final script.\n        :rtype: CScript"
  },
  {
    "code": "def serialize_for_header(key, value):\n    if key in QUOTE_FIELDS:\n        return json.dumps(value)\n    elif isinstance(value, str):\n        if \" \" in value or \"\\t\" in value:\n            return json.dumps(value)\n        else:\n            return value\n    elif isinstance(value, list):\n        return \"[{}]\".format(\", \".join(value))\n    else:\n        return str(value)",
    "docstring": "Serialize value for the given mapping key for a VCF header line"
  },
  {
    "code": "def get_clusters_interfaces(clusters, extra_cond=lambda nic: True):\n    interfaces = {}\n    for cluster in clusters:\n        nics = get_cluster_interfaces(cluster, extra_cond=extra_cond)\n        interfaces.setdefault(cluster, nics)\n    return interfaces",
    "docstring": "Returns for each cluster the available cluster interfaces\n\n    Args:\n        clusters (str): list of the clusters\n        extra_cond (lambda): extra predicate to filter network card retrieved\n    from the API. E.g lambda nic: not nic['mounted'] will retrieve all the\n    usable network cards that are not mounted by default.\n\n    Returns:\n        dict of cluster with their associated nic names\n\n    Examples:\n        .. code-block:: python\n\n            # pseudo code\n            actual = get_clusters_interfaces([\"paravance\"])\n            expected = {\"paravance\": [\"eth0\", \"eth1\"]}\n            assertDictEquals(expected, actual)"
  },
  {
    "code": "def disable_key(self):\n        print(\"This command will disable a enabled key.\")\n        apiKeyID = input(\"API Key ID: \")\n        try:\n            key = self._curl_bitmex(\"/apiKey/disable\",\n                                    postdict={\"apiKeyID\": apiKeyID})\n            print(\"Key with ID %s disabled.\" % key[\"id\"])\n        except:\n            print(\"Unable to disable key, please try again.\")\n            self.disable_key()",
    "docstring": "Disable an existing API Key."
  },
  {
    "code": "def network_stop(name, **kwargs):\n    conn = __get_conn(**kwargs)\n    try:\n        net = conn.networkLookupByName(name)\n        return not bool(net.destroy())\n    finally:\n        conn.close()",
    "docstring": "Stop a defined virtual network.\n\n    :param name: virtual network name\n    :param connection: libvirt connection URI, overriding defaults\n    :param username: username to connect with, overriding defaults\n    :param password: password to connect with, overriding defaults\n\n    .. versionadded:: 2019.2.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' virt.network_stop default"
  },
  {
    "code": "def _handle_events(self, fd: int, events: int) -> None:\n        action = 0\n        if events & ioloop.IOLoop.READ:\n            action |= pycurl.CSELECT_IN\n        if events & ioloop.IOLoop.WRITE:\n            action |= pycurl.CSELECT_OUT\n        while True:\n            try:\n                ret, num_handles = self._multi.socket_action(fd, action)\n            except pycurl.error as e:\n                ret = e.args[0]\n            if ret != pycurl.E_CALL_MULTI_PERFORM:\n                break\n        self._finish_pending_requests()",
    "docstring": "Called by IOLoop when there is activity on one of our\n        file descriptors."
  },
  {
    "code": "def all_replica_set_links(rs_id, rel_to=None):\n    return [\n        replica_set_link(rel, rs_id, self_rel=(rel == rel_to))\n        for rel in (\n            'get-replica-set-info',\n            'delete-replica-set', 'replica-set-command',\n            'get-replica-set-members', 'add-replica-set-member',\n            'get-replica-set-secondaries', 'get-replica-set-primary',\n            'get-replica-set-arbiters', 'get-replica-set-hidden-members',\n            'get-replica-set-passive-members', 'get-replica-set-servers'\n        )\n    ]",
    "docstring": "Get a list of all links to be included with replica sets."
  },
  {
    "code": "def _regex_flags_from_bits(self, bits):\n        flags = 'ilmsuxa'\n        return ''.join(flags[i - 1] if (1 << i) & bits else '' for i in range(1, len(flags) + 1))",
    "docstring": "Return the textual equivalent of numerically encoded regex flags."
  },
  {
    "code": "def range(self):\n    chrs = set([x.range.chr for x in self.get_transcripts()])\n    if len(chrs) != 1: return None\n    start = min([x.range.start for x in self.get_transcripts()])\n    end = max([x.range.end for x in self.get_transcripts()])\n    return GenomicRange(list(chrs)[0],start,end)",
    "docstring": "Return the range the transcript loci covers\n\n    :return: range\n    :rtype: GenomicRange"
  },
  {
    "code": "def retrieve_dcnm_subnet_info(self, tenant_id, direc):\n        serv_obj = self.get_service_obj(tenant_id)\n        subnet_dict = serv_obj.get_dcnm_subnet_dict(direc)\n        return subnet_dict",
    "docstring": "Retrieves the DCNM subnet info for a tenant."
  },
  {
    "code": "def k2g(kml_path, output_dir, separate_folders, style_type, \n  style_filename):\n    m.convert(kml_path, output_dir, separate_folders, style_type, style_filename)",
    "docstring": "Given a path to a KML file, convert it to a a GeoJSON FeatureCollection file and save it to the given output directory.\n\n    If ``--separate_folders``, then create several GeoJSON files, one for each folder in the KML file that contains geodata or that has a descendant node that contains geodata.\n    Warning: this can produce GeoJSON files with the same geodata in case the KML file has nested folders with geodata.\n\n    If ``--style_type`` is specified, then also build a JSON style file of the given style type and save it to the output directory under the file name given by ``--style_filename``."
  },
  {
    "code": "def parse_lock(self):\n        try:\n            with open(self.lock_file, \"r\") as reader:\n                data = json.loads(reader.read())\n                self.last_update = datetime.datetime.strptime(\n                    data[\"last_update\"],\n                    AppCronLock.DATETIME_FORMAT\n                )\n        except:\n            self.write_lock(last_update=datetime.datetime.fromtimestamp(0))\n            self.parse_lock()",
    "docstring": "Parses app lock file\n\n        :return: Details about last update"
  },
  {
    "code": "def _call_analysis_function(options, module):\n    args, kwargs = _get_args_kwargs(options, module)\n    return eval(\"%s.%s(*args, **kwargs)\" % (module, options['analysis']))",
    "docstring": "Call function from module and get result, using inputs from options\n\n    Parameters\n    ----------\n    options : dict\n        Option names and values for analysis\n    module : str\n        Short name of module within macroeco containing analysis function\n\n    Returns\n    -------\n    dataframe, array, value, list of tuples\n        Functions from emp module return a list of tuples in which first\n        element of the tuple gives a string describing the result and the\n        second element giving the result of the analysis as a dataframe.\n        Functions in other modules return dataframe, array, or value."
  },
  {
    "code": "def stream_logs(self, stdout=True, stderr=True, tail='all', timeout=10.0):\n        return stream_logs(\n            self.inner(), stdout=stdout, stderr=stderr, tail=tail,\n            timeout=timeout)",
    "docstring": "Stream container output."
  },
  {
    "code": "def main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--host\", type=str, required=True)\n    parser.add_argument(\"--user\", type=str, required=True)\n    parser.add_argument(\"--password\", type=str)\n    parser.add_argument(\"--token\", type=str)\n    args = parser.parse_args()\n    if not args.password and not args.token:\n        print('password or token is required')\n        exit(1)\n    example(args.host, args.user, args.password, args.token)",
    "docstring": "Main entry."
  },
  {
    "code": "def get_cleaned_args(self, args):\n        if not args:\n            return args\n        cleaned_args = []\n        for arg in args:\n            condition = self._get_linguist_condition(arg, True)\n            if condition:\n                cleaned_args.append(condition)\n        return cleaned_args",
    "docstring": "Returns positional arguments for related model query."
  },
  {
    "code": "def prox_gradf12(x, step, j=None, Xs=None):\n    if j == 0:\n        return x - step*grad_fx(Xs[0][0], Xs[1][0])\n    if j == 1:\n        y = x\n        return y - step*grad_fy(Xs[0][0], Xs[1][0])\n    raise NotImplementedError",
    "docstring": "1D gradient operator for x or y"
  },
  {
    "code": "def on_modified(self, event):\n        self._logger.debug('Detected modify event on watched path: %s', event.src_path)\n        self._process_event(event)",
    "docstring": "Function called everytime a new file is modified.\n\n        Args:\n            event: Event to process."
  },
  {
    "code": "def get_mzid_specfile_ids(mzidfn, namespace):\n    sid_fn = {}\n    for specdata in mzid_specdata_generator(mzidfn, namespace):\n        sid_fn[specdata.attrib['id']] = specdata.attrib['name']\n    return sid_fn",
    "docstring": "Returns mzid spectra data filenames and their IDs used in the\n    mzIdentML file as a dict. Keys == IDs, values == fns"
  },
  {
    "code": "def loc(lexer: Lexer, start_token: Token) -> Optional[Location]:\n    if not lexer.no_location:\n        end_token = lexer.last_token\n        source = lexer.source\n        return Location(\n            start_token.start, end_token.end, start_token, end_token, source\n        )\n    return None",
    "docstring": "Return a location object.\n\n    Used to identify the place in the source that created a given parsed object."
  },
  {
    "code": "def get_valid_residue(residue):\n    if residue is not None and amino_acids.get(residue) is None:\n        res = amino_acids_reverse.get(residue.lower())\n        if res is None:\n            raise InvalidResidueError(residue)\n        else:\n            return res\n    return residue",
    "docstring": "Check if the given string represents a valid amino acid residue."
  },
  {
    "code": "def one_of(self, chset: str) -> str:\n        res = self.peek()\n        if res in chset:\n            self.offset += 1\n            return res\n        raise UnexpectedInput(self, \"one of \" + chset)",
    "docstring": "Parse one character form the specified set.\n\n        Args:\n            chset: string of characters to try as alternatives.\n\n        Returns:\n            The character that was actually matched.\n\n        Raises:\n            UnexpectedInput: If the next character is not in `chset`."
  },
  {
    "code": "def transform_raw_abundance(biomf, fn=math.log10, sampleIDs=None, sample_abd=True):\n    totals = raw_abundance(biomf, sampleIDs, sample_abd)\n    return {sid: fn(abd) for sid, abd in totals.items()}",
    "docstring": "Function to transform the total abundance calculation for each sample ID to another\n    format based on user given transformation function.\n\n    :type biomf: A BIOM file.\n    :param biomf: OTU table format.\n\n    :param fn: Mathematical function which is used to transform smax to another format.\n               By default, the function has been given as base 10 logarithm.\n\n    :rtype: dict\n    :return: Returns a dictionary similar to output of raw_abundance function but with\n             the abundance values modified by the mathematical operation. By default, the\n             operation performed on the abundances is base 10 logarithm."
  },
  {
    "code": "def reload(self):\n        if time.time() - self.updated > self.ttl:\n            self.force_reload()",
    "docstring": "Reload catalog if sufficient time has passed"
  },
  {
    "code": "def merge_configs(self, config, datas):\n        if not isinstance(config, dict) or len([x for x in datas if not isinstance(x, dict)]) > 0:\n            raise TypeError(\"Unable to merge: Dictionnary expected\")\n        for key, value in config.items():\n            others = [x[key] for x in datas if key in x]\n            if len(others) > 0:\n                if isinstance(value, dict):\n                    config[key] = self.merge_configs(value, others)\n                else:\n                    config[key] = others[-1]\n        return config",
    "docstring": "Merge configs files"
  },
  {
    "code": "def from_proto(cls, repeated_split_infos):\n    split_dict = cls()\n    for split_info_proto in repeated_split_infos:\n      split_info = SplitInfo()\n      split_info.CopyFrom(split_info_proto)\n      split_dict.add(split_info)\n    return split_dict",
    "docstring": "Returns a new SplitDict initialized from the `repeated_split_infos`."
  },
  {
    "code": "def get_goobjs_altgo2goobj(go2obj):\n    goobjs = set()\n    altgo2goobj = {}\n    for goid, goobj in go2obj.items():\n        goobjs.add(goobj)\n        if goid != goobj.id:\n            altgo2goobj[goid] = goobj\n    return goobjs, altgo2goobj",
    "docstring": "Separate alt GO IDs and key GO IDs."
  },
  {
    "code": "def multi_mask_sequences(records, slices):\n    for record in records:\n        record_indices = list(range(len(record)))\n        keep_indices = reduce(lambda i, s: i - frozenset(record_indices[s]),\n                              slices, frozenset(record_indices))\n        seq = ''.join(b if i in keep_indices else '-'\n                      for i, b in enumerate(str(record.seq)))\n        record.seq = Seq(seq)\n        yield record",
    "docstring": "Replace characters sliced by slices with gap characters."
  },
  {
    "code": "def __reset_crosshair(self):\n        self.lhor.set_ydata(self.y_coord)\n        self.lver.set_xdata(self.x_coord)",
    "docstring": "redraw the cross-hair on the horizontal slice plot\n\n        Parameters\n        ----------\n        x: int\n            the x image coordinate\n        y: int\n            the y image coordinate\n\n        Returns\n        -------"
  },
  {
    "code": "def embed_data_in_blockchain(data, private_key,\n        blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,\n        change_address=None, format='bin'):\n    signed_tx = make_op_return_tx(data, private_key, blockchain_client,\n        fee=fee, change_address=change_address, format=format)\n    response = broadcast_transaction(signed_tx, blockchain_client)\n    return response",
    "docstring": "Builds, signs, and dispatches an OP_RETURN transaction."
  },
  {
    "code": "def remove_flag(self, flag):\n        super(Entry, self).remove_flag(flag)\n        self._changed_attrs.add('flags')",
    "docstring": "Remove flag to the flags and memorize this attribute has changed so we\n        can regenerate it when outputting text."
  },
  {
    "code": "def issubclass(cls, ifaces):\n    ifaces = _ensure_ifaces_tuple(ifaces)\n    for iface in ifaces:\n        return all((\n            _check_for_definition(\n                iface,\n                cls,\n                '__iclassattribute__',\n                _is_attribute,\n            ),\n            _check_for_definition(\n                iface,\n                cls,\n                '__iproperty__',\n                _is_property,\n            ),\n            _check_for_definition(\n                iface,\n                cls,\n                '__imethod__',\n                _is_method,\n            ),\n            _check_for_definition(\n                iface,\n                cls,\n                '__iclassmethod__',\n                _is_classmethod,\n            ),\n        ))",
    "docstring": "Check if the given class is an implementation of the given iface."
  },
  {
    "code": "def import_field(field_classpath):\n    if '.' in field_classpath:\n        fully_qualified = field_classpath\n    else:\n        fully_qualified = \"django.db.models.%s\" % field_classpath\n    try:\n        return import_dotted_path(fully_qualified)\n    except ImportError:\n        raise ImproperlyConfigured(\"The EXTRA_MODEL_FIELDS setting contains \"\n                                   \"the field '%s' which could not be \"\n                                   \"imported.\" % field_classpath)",
    "docstring": "Imports a field by its dotted class path, prepending \"django.db.models\"\n    to raw class names and raising an exception if the import fails."
  },
  {
    "code": "def get_datetime_properties(self, recursive=True):\n        res = {}\n        for name, field in self.properties.items():\n            if isinstance(field, DateField):\n                res[name] = field\n            elif recursive and isinstance(field, ObjectField):\n                for n, f in field.get_datetime_properties(recursive=recursive):\n                    res[name + \".\" + n] = f\n        return res",
    "docstring": "Returns a dict of property.path and property.\n\n        :param recursive the name of the property\n        :returns a dict"
  },
  {
    "code": "def logpath(self):\n        name = '{}-{}.catan'.format(self.timestamp_str(),\n                                    '-'.join([p.name for p in self._players]))\n        path = os.path.join(self._log_dir, name)\n        if not os.path.exists(self._log_dir):\n            os.mkdir(self._log_dir)\n        return path",
    "docstring": "Return the logfile path and filename as a string.\n\n        The file with name self.logpath() is written to on flush().\n\n        The filename contains the log's timestamp and the names of players in the game.\n        The logpath changes when reset() or _set_players() are called, as they change the\n        timestamp and the players, respectively."
  },
  {
    "code": "def new_keypair(key, value, ambig, unambig):\n    if key in ambig:\n        return\n    if key in unambig and value != unambig[key]:\n            ambig.add(key)\n            del unambig[key]\n            return\n    unambig[key] = value\n    return",
    "docstring": "Check new keypair against existing unambiguous dict\n\n    :param key: of pair\n    :param value: of pair\n    :param ambig: set of keys with ambig decoding\n    :param unambig: set of keys with unambig decoding\n    :return:"
  },
  {
    "code": "def yearly_average(arr, dt):\n    assert_matching_time_coord(arr, dt)\n    yr_str = TIME_STR + '.year'\n    dt = dt.where(np.isfinite(arr))\n    return ((arr*dt).groupby(yr_str).sum(TIME_STR) /\n            dt.groupby(yr_str).sum(TIME_STR))",
    "docstring": "Average a sub-yearly time-series over each year.\n\n    Resulting timeseries comprises one value for each year in which the\n    original array had valid data.  Accounts for (i.e. ignores) masked values\n    in original data when computing the annual averages.\n\n    Parameters\n    ----------\n    arr : xarray.DataArray\n        The array to be averaged\n    dt : xarray.DataArray\n        Array of the duration of each timestep\n\n    Returns\n    -------\n    xarray.DataArray\n        Has the same shape and mask as the original ``arr``, except for the\n        time dimension, which is truncated to one value for each year that\n        ``arr`` spanned"
  },
  {
    "code": "def set_units(self, unit):\n        self._units = validate_type(unit, type(None), *six.string_types)",
    "docstring": "Set the unit for this data point\n\n        Unit, as with data_type, are actually associated with the stream and not\n        the individual data point.  As such, changing this within a stream is\n        not encouraged.  Setting the unit on the data point is useful when the\n        stream might be created with the write of a data point."
  },
  {
    "code": "def _load_sequences_to_strain(self, strain_id, force_rerun=False):\n        gp_seqs_path = op.join(self.model_dir, '{}_gp_withseqs.pckl'.format(strain_id))\n        if ssbio.utils.force_rerun(flag=force_rerun, outfile=gp_seqs_path):\n            gp_noseqs = ssbio.io.load_pickle(self.strain_infodict[strain_id]['gp_noseqs_path'])\n            strain_sequences = SeqIO.index(self.strain_infodict[strain_id]['genome_path'], 'fasta')\n            for strain_gene in gp_noseqs.functional_genes:\n                strain_gene_key = self.df_orthology_matrix.at[strain_gene.id, strain_id]\n                new_id = '{}_{}'.format(strain_gene.id, strain_id)\n                if strain_gene.protein.sequences.has_id(new_id):\n                    continue\n                strain_gene.protein.load_manual_sequence(seq=strain_sequences[strain_gene_key], ident=new_id,\n                                                         set_as_representative=True)\n            gp_noseqs.save_pickle(outfile=gp_seqs_path)\n        return strain_id, gp_seqs_path",
    "docstring": "Load strain GEMPRO with functional genes defined, load sequences to it, save as new GEMPRO"
  },
  {
    "code": "def _extract_local_mean_gauss(image, mask = slice(None), sigma = 1, voxelspacing = None):\n    if voxelspacing is None:\n        voxelspacing = [1.] * image.ndim\n    sigma = _create_structure_array(sigma, voxelspacing)\n    return _extract_intensities(gaussian_filter(image, sigma), mask)",
    "docstring": "Internal, single-image version of `local_mean_gauss`."
  },
  {
    "code": "def _continuous_colormap(hue, cmap, vmin, vmax):\n    mn = min(hue) if vmin is None else vmin\n    mx = max(hue) if vmax is None else vmax\n    norm = mpl.colors.Normalize(vmin=mn, vmax=mx)\n    return mpl.cm.ScalarMappable(norm=norm, cmap=cmap)",
    "docstring": "Creates a continuous colormap.\n\n    Parameters\n    ----------\n    hue : iterable\n        The data column whose entries are being discretely colorized. Note that although top-level plotter ``hue``\n        parameters ingest many argument signatures, not just iterables, they are all preprocessed to standardized\n        iterables before this method is called.\n    cmap : ``matplotlib.cm`` instance\n        The `matplotlib` colormap instance which will be used to colorize the geometries.\n    vmin : float\n        A strict floor on the value associated with the \"bottom\" of the colormap spectrum. Data column entries whose\n        value is below this level will all be colored by the same threshold value. The value for this variable is\n        meant to be inherited from the top-level variable of the same name.\n    vmax : float\n        A strict ceiling on the value associated with the \"top\" of the colormap spectrum. Data column entries whose\n        value is above this level will all be colored by the same threshold value. The value for this variable is\n        meant to be inherited from the top-level variable of the same name.\n\n    Returns\n    -------\n    cmap : ``mpl.cm.ScalarMappable`` instance\n        A normalized scalar version of the input ``cmap`` which has been fitted to the data and inputs."
  },
  {
    "code": "def add(self, properties):\n        resource = self.resource_class(self, properties)\n        self._resources[resource.oid] = resource\n        self._hmc.all_resources[resource.uri] = resource\n        return resource",
    "docstring": "Add a faked resource to this manager.\n\n        For URI-based lookup, the resource is also added to the faked HMC.\n\n        Parameters:\n\n          properties (dict):\n            Resource properties. If the URI property (e.g. 'object-uri') or the\n            object ID property (e.g. 'object-id') are not specified, they\n            will be auto-generated.\n\n        Returns:\n          FakedBaseResource: The faked resource object."
  },
  {
    "code": "def get_freesurfer_cmap(vis_type):\n    if vis_type in ('cortical_volumetric', 'cortical_contour'):\n            LUT = get_freesurfer_cortical_LUT()\n            cmap = ListedColormap(LUT)\n    elif vis_type in ('labels_volumetric', 'labels_contour'):\n        black = np.array([0, 0, 0, 1])\n        cmap = plt.get_cmap('hsv')\n        cmap = cmap(np.linspace(0, 1, 20))\n        colors = np.vstack((black, cmap))\n        cmap = ListedColormap(colors, 'my_colormap')\n    else:\n        raise NotImplementedError('color map for the visualization type {} has not been implemented!'.format(vis_type))\n    return cmap",
    "docstring": "Provides different colormaps for different visualization types."
  },
  {
    "code": "def _get_missing_trees(self, path, root_tree):\n        dirpath = posixpath.split(path)[0]\n        dirs = dirpath.split('/')\n        if not dirs or dirs == ['']:\n            return []\n        def get_tree_for_dir(tree, dirname):\n            for name, mode, id in tree.iteritems():\n                if name == dirname:\n                    obj = self.repository._repo[id]\n                    if isinstance(obj, objects.Tree):\n                        return obj\n                    else:\n                        raise RepositoryError(\"Cannot create directory %s \"\n                        \"at tree %s as path is occupied and is not a \"\n                        \"Tree\" % (dirname, tree))\n            return None\n        trees = []\n        parent = root_tree\n        for dirname in dirs:\n            tree = get_tree_for_dir(parent, dirname)\n            if tree is None:\n                tree = objects.Tree()\n                dirmode = 040000\n                parent.add(dirmode, dirname, tree.id)\n                parent = tree\n            trees.append(tree)\n        return trees",
    "docstring": "Creates missing ``Tree`` objects for the given path.\n\n        :param path: path given as a string. It may be a path to a file node\n          (i.e. ``foo/bar/baz.txt``) or directory path - in that case it must\n          end with slash (i.e. ``foo/bar/``).\n        :param root_tree: ``dulwich.objects.Tree`` object from which we start\n          traversing (should be commit's root tree)"
  },
  {
    "code": "def get_component(self, component=None, **kwargs):\n        if component is not None:\n            kwargs['component'] = component\n        kwargs['context'] = 'component'\n        return self.filter(**kwargs)",
    "docstring": "Filter in the 'component' context\n\n        :parameter str component: name of the component (optional)\n        :parameter **kwargs: any other tags to do the filter\n            (except component or context)\n        :return: :class:`phoebe.parameters.parameters.ParameterSet`"
  },
  {
    "code": "def get_tags(instance_id=None, keyid=None, key=None, profile=None,\n             region=None):\n    tags = []\n    client = _get_conn(key=key, keyid=keyid, profile=profile, region=region)\n    result = client.get_all_tags(filters={\"resource-id\": instance_id})\n    if result:\n        for tag in result:\n            tags.append({tag.name: tag.value})\n    else:\n        log.info(\"No tags found for instance_id %s\", instance_id)\n    return tags",
    "docstring": "Given an instance_id, return a list of tags associated with that instance.\n\n    returns\n        (list) - list of tags as key/value pairs\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_ec2.get_tags instance_id"
  },
  {
    "code": "def post_video(self, videoUrl, name=None, ingestMedia=True):\n        if name is None:\n            name = os.path.basename(videoUrl)\n        url = '/videos'\n        data = {'name': name}\n        new_video = self._make_request(self.CMS_Server, 'POST', url, data=data)\n        if ingestMedia:\n            self.ingest_video(new_video['id'], videoUrl)\n        return new_video",
    "docstring": "Post and optionally ingest media from the specified URL"
  },
  {
    "code": "def AddProcessingOptions(self, argument_group):\n    argument_helper_names = ['temporary_directory', 'zeromq']\n    if self._CanEnforceProcessMemoryLimit():\n      argument_helper_names.append('process_resources')\n    helpers_manager.ArgumentHelperManager.AddCommandLineArguments(\n        argument_group, names=argument_helper_names)\n    argument_group.add_argument(\n        '--worker-memory-limit', '--worker_memory_limit',\n        dest='worker_memory_limit', action='store', type=int,\n        metavar='SIZE', help=(\n            'Maximum amount of memory (data segment and shared memory) '\n            'a worker process is allowed to consume in bytes, where 0 '\n            'represents no limit. The default limit is 2147483648 (2 GiB). '\n            'If a worker process exceeds this limit is is killed by the main '\n            '(foreman) process.'))",
    "docstring": "Adds processing options to the argument group\n\n    Args:\n      argument_group (argparse._ArgumentGroup): argparse argument group."
  },
  {
    "code": "def lock(self, seconds=5):\r\n        self._current_application().lock(robot.utils.timestr_to_secs(seconds))",
    "docstring": "Lock the device for a certain period of time. iOS only."
  },
  {
    "code": "def assert_raises_regex(exception, regex, msg_fmt=\"{msg}\"):\n    def test(exc):\n        compiled = re.compile(regex)\n        if not exc.args:\n            msg = \"{} without message\".format(exception.__name__)\n            fail(\n                msg_fmt.format(\n                    msg=msg,\n                    text=None,\n                    pattern=compiled.pattern,\n                    exc_type=exception,\n                    exc_name=exception.__name__,\n                )\n            )\n        text = exc.args[0]\n        if not compiled.search(text):\n            msg = \"{!r} does not match {!r}\".format(text, compiled.pattern)\n            fail(\n                msg_fmt.format(\n                    msg=msg,\n                    text=text,\n                    pattern=compiled.pattern,\n                    exc_type=exception,\n                    exc_name=exception.__name__,\n                )\n            )\n    context = AssertRaisesRegexContext(exception, regex, msg_fmt)\n    context.add_test(test)\n    return context",
    "docstring": "Fail unless an exception with a message that matches a regular\n     expression is raised within the context.\n\n    The regular expression can be a regular expression string or object.\n\n    >>> with assert_raises_regex(ValueError, r\"\\\\d+\"):\n    ...     raise ValueError(\"Error #42\")\n    ...\n    >>> with assert_raises_regex(ValueError, r\"\\\\d+\"):\n    ...     raise ValueError(\"Generic Error\")\n    ...\n    Traceback (most recent call last):\n        ...\n    AssertionError: 'Generic Error' does not match '\\\\\\\\d+'\n\n    The following msg_fmt arguments are supported:\n    * msg - the default error message\n    * exc_type - exception type that is expected\n    * exc_name - expected exception type name\n    * text - actual error text\n    * pattern - expected error message as regular expression string"
  },
  {
    "code": "def select_projects(self, *args):\n        new_query = copy.deepcopy(self)\n        new_query._filter.projects = args\n        return new_query",
    "docstring": "Copy the query and add filtering by monitored projects.\n\n        This is only useful if the target project represents a Stackdriver\n        account containing the specified monitored projects.\n\n        Examples::\n\n            query = query.select_projects('project-1')\n            query = query.select_projects('project-1', 'project-2')\n\n        :type args: tuple\n        :param args: Project IDs limiting the resources to be included\n            in the query.\n\n        :rtype: :class:`Query`\n        :returns: The new query object."
  },
  {
    "code": "def _onInstanceAttribute(self, name, line, pos, absPosition, level):\n        attributes = self.objectsStack[level - 1].instanceAttributes\n        for item in attributes:\n            if item.name == name:\n                return\n        attributes.append(InstanceAttribute(name, line, pos, absPosition))",
    "docstring": "Memorizes a class instance attribute"
  },
  {
    "code": "def add_install_button(self, grid_lang, row, column):\n        btn = self.button_with_label('<b>Install more...</b>')\n        if row == 0 and column == 0:\n            grid_lang.add(btn)\n        else:\n            grid_lang.attach(btn, column, row, 1, 1)\n        btn.connect(\"clicked\", self.parent.install_btn_clicked)\n        return btn",
    "docstring": "Add button that opens the window for installing more assistants"
  },
  {
    "code": "def deep_merge(dict_one, dict_two):\n    merged = dict_one.copy()\n    for key, value in dict_two.items():\n        if (key in dict_one and\n                isinstance(dict_one[key], dict) and\n                isinstance(value, dict)):\n            merged[key] = deep_merge(dict_one[key], value)\n        elif (key in dict_one and\n              isinstance(dict_one[key], list) and\n              isinstance(value, list)):\n            merged[key] = list(set(dict_one[key] + value))\n        else:\n            merged[key] = value\n    return merged",
    "docstring": "Deep merge two dicts."
  },
  {
    "code": "def handle_packet(self, packet):\n        if self.packet_callback:\n            self.packet_callback(packet)\n        else:\n            print('packet', packet)",
    "docstring": "Process incoming packet dict and optionally call callback."
  },
  {
    "code": "def _load_managed_entries(self):\n        for process_name, process_entry in context.process_context.items():\n            if isinstance(process_entry, ManagedProcessEntry):\n                function = self.fire_managed_worker\n            else:\n                self.logger.warning('Skipping non-managed context entry {0} of type {1}.'\n                                    .format(process_name, process_entry.__class__.__name__))\n                continue\n            try:\n                self._register_process_entry(process_entry, function)\n            except Exception:\n                self.logger.error('Managed Thread Handler {0} failed to start. Skipping it.'\n                                  .format(process_entry.key), exc_info=True)",
    "docstring": "loads scheduler managed entries. no start-up procedures are performed"
  },
  {
    "code": "def comments(self, article):\n        return self._query_zendesk(self.endpoint.comments, object_type='comment', id=article)",
    "docstring": "Retrieve comments for an article\n\n        :param article: Article ID or object"
  },
  {
    "code": "def is_slice_or_dim_range_request(key, depth=0):\n    return (is_slice_or_dim_range(key) or\n            (depth == 0 and non_str_len_no_throw(key) > 0 and\n             all(is_slice_or_dim_range_request(subkey, depth+1) for subkey in key)))",
    "docstring": "Checks if a particular key is a slice, DimensionRange or\n    list of those types"
  },
  {
    "code": "def _mount(self):\n        if is_osx():\n            if self.connection[\"jss\"].verbose:\n                print self.connection[\"mount_url\"]\n            if mount_share:\n                self.connection[\"mount_point\"] = mount_share(\n                    self.connection[\"mount_url\"])\n            else:\n                args = [\"mount\", \"-t\", self.protocol,\n                        self.connection[\"mount_url\"],\n                        self.connection[\"mount_point\"]]\n                if self.connection[\"jss\"].verbose:\n                    print \" \".join(args)\n                subprocess.check_call(args)\n        elif is_linux():\n            args = [\"mount_afp\", \"-t\", self.protocol,\n                    self.connection[\"mount_url\"],\n                    self.connection[\"mount_point\"]]\n            if self.connection[\"jss\"].verbose:\n                print \" \".join(args)\n            subprocess.check_call(args)\n        else:\n            raise JSSError(\"Unsupported OS.\")",
    "docstring": "Mount based on which OS is running."
  },
  {
    "code": "def untranslateName(s):\n    s = s.replace('DOT', '.')\n    s = s.replace('DOLLAR', '$')\n    if s[:2] == 'PY': s = s[2:]\n    s = s.replace('.PY', '.')\n    return s",
    "docstring": "Undo Python conversion of CL parameter or variable name."
  },
  {
    "code": "def write_json(data, path, file_name):\n    if os.path.exists(path) and not os.path.isdir(path):\n        return\n    elif not os.path.exists(path):\n        mkdir_p(path)\n    with open(os.path.join(path, file_name), 'w') as f:\n        json_tricks.dump(data, f, indent=4, primitives=True, allow_nan=True)",
    "docstring": "Write out data to a json file.\n\n    Args:\n        data: A dictionary representation of the data to write out\n        path: The directory to output the file in\n        file_name: The name of the file to write out"
  },
  {
    "code": "def panels(self):\n        ax1 = self.fig.add_subplot(211)\n        ax2 = self.fig.add_subplot(212, sharex=ax1)\n        return (ax2, self.gene_panel), (ax1, self.signal_panel)",
    "docstring": "Add 2 panels to the figure, top for signal and bottom for gene models"
  },
  {
    "code": "def update_extent_location(self, extent_loc):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('Path Table Record not yet initialized')\n        self.extent_location = extent_loc",
    "docstring": "A method to update the extent location for this Path Table Record.\n\n        Parameters:\n         extent_loc - The new extent location.\n        Returns:\n         Nothing."
  },
  {
    "code": "def ext_pillar(minion_id, pillar, *args, **kwargs):\n    for i in args:\n        if 'path' not in i:\n            path = '/srv/saltclass'\n            args[i]['path'] = path\n            log.warning('path variable unset, using default: %s', path)\n        else:\n            path = i['path']\n    salt_data = {\n        '__opts__': __opts__,\n        '__salt__': __salt__,\n        '__grains__': __grains__,\n        '__pillar__': pillar,\n        'minion_id': minion_id,\n        'path': path\n    }\n    return sc.get_pillars(minion_id, salt_data)",
    "docstring": "Compile pillar data"
  },
  {
    "code": "def topological_order(self):\n        q = Queue()\n        in_degree = {}\n        for i in range(self.n_nodes):\n            in_degree[i] = 0\n        for u in range(self.n_nodes):\n            for v, _ in self.adj_list[u]:\n                in_degree[v] += 1\n        for i in range(self.n_nodes):\n            if in_degree[i] == 0:\n                q.put(i)\n        order_list = []\n        while not q.empty():\n            u = q.get()\n            order_list.append(u)\n            for v, _ in self.adj_list[u]:\n                in_degree[v] -= 1\n                if in_degree[v] == 0:\n                    q.put(v)\n        return order_list",
    "docstring": "Return the topological order of the node IDs from the input node to the output node."
  },
  {
    "code": "def map_components(notsplit_packages, components):\n    packages = set()\n    for c in components:\n        if c in notsplit_packages:\n            packages.add('ceph')\n        else:\n            packages.add(c)\n    return list(packages)",
    "docstring": "Returns a list of packages to install based on component names\n\n    This is done by checking if a component is in notsplit_packages,\n    if it is, we know we need to install 'ceph' instead of the\n    raw component name.  Essentially, this component hasn't been\n    'split' from the master 'ceph' package yet."
  },
  {
    "code": "def _blas_is_applicable(*args):\n    if any(x.dtype != args[0].dtype for x in args[1:]):\n        return False\n    elif any(x.dtype not in _BLAS_DTYPES for x in args):\n        return False\n    elif not (all(x.flags.f_contiguous for x in args) or\n              all(x.flags.c_contiguous for x in args)):\n        return False\n    elif any(x.size > np.iinfo('int32').max for x in args):\n        return False\n    else:\n        return True",
    "docstring": "Whether BLAS routines can be applied or not.\n\n    BLAS routines are available for single and double precision\n    float or complex data only. If the arrays are non-contiguous,\n    BLAS methods are usually slower, and array-writing routines do\n    not work at all. Hence, only contiguous arrays are allowed.\n\n    Parameters\n    ----------\n    x1,...,xN : `NumpyTensor`\n        The tensors to be tested for BLAS conformity.\n\n    Returns\n    -------\n    blas_is_applicable : bool\n        ``True`` if all mentioned requirements are met, ``False`` otherwise."
  },
  {
    "code": "def rename(self, oldpath, newpath):\n        oldpath = self._adjust_cwd(oldpath)\n        newpath = self._adjust_cwd(newpath)\n        self._log(DEBUG, \"rename({!r}, {!r})\".format(oldpath, newpath))\n        self._request(CMD_RENAME, oldpath, newpath)",
    "docstring": "Rename a file or folder from ``oldpath`` to ``newpath``.\n\n        .. note::\n            This method implements 'standard' SFTP ``RENAME`` behavior; those\n            seeking the OpenSSH \"POSIX rename\" extension behavior should use\n            `posix_rename`.\n\n        :param str oldpath:\n            existing name of the file or folder\n        :param str newpath:\n            new name for the file or folder, must not exist already\n\n        :raises:\n            ``IOError`` -- if ``newpath`` is a folder, or something else goes\n            wrong"
  },
  {
    "code": "def values(self):\n        lower = float(self.lowerSpnbx.value())\n        upper = float(self.upperSpnbx.value())\n        return (lower, upper)",
    "docstring": "Gets the user enter max and min values of where the \n        raster points should appear on the y-axis\n\n        :returns: (float, float) -- (min, max) y-values to bound the raster plot by"
  },
  {
    "code": "def is_clustered(self):\n        self.open()\n        clust = lvm_vg_is_clustered(self.handle)\n        self.close()\n        return bool(clust)",
    "docstring": "Returns True if the VG is clustered, False otherwise."
  },
  {
    "code": "def exists(project, credentials):\n        user, oauth_access_token = parsecredentials(credentials)\n        printdebug(\"Checking if project \" + project + \" exists for \" + user)\n        return os.path.isdir(Project.path(project, user))",
    "docstring": "Check if the project exists"
  },
  {
    "code": "def deferral():\n    deferred = []\n    defer = lambda f, *a, **k: deferred.append((f, a, k))\n    try:\n        yield defer\n    finally:\n        while deferred:\n            f, a, k = deferred.pop()\n            f(*a, **k)",
    "docstring": "Defers a function call when it is being required like Go.\n\n    ::\n\n       with deferral() as defer:\n           sys.setprofile(f)\n           defer(sys.setprofile, None)\n           # do something."
  },
  {
    "code": "def update_stream(self, data):\n        self._group['stream_id'] = data['stream_id']\n        self.callback()\n        _LOGGER.info('updated stream to %s on %s', self.stream, self.friendly_name)",
    "docstring": "Update stream."
  },
  {
    "code": "def resolve_code_path(cwd, codeuri):\n    LOG.debug(\"Resolving code path. Cwd=%s, CodeUri=%s\", cwd, codeuri)\n    if not cwd or cwd == PRESENT_DIR:\n        cwd = os.getcwd()\n    cwd = os.path.abspath(cwd)\n    if not os.path.isabs(codeuri):\n        codeuri = os.path.normpath(os.path.join(cwd, codeuri))\n    return codeuri",
    "docstring": "Returns path to the function code resolved based on current working directory.\n\n    Parameters\n    ----------\n    cwd str\n        Current working directory\n    codeuri\n        CodeURI of the function. This should contain the path to the function code\n\n    Returns\n    -------\n    str\n        Absolute path to the function code"
  },
  {
    "code": "def validate_IRkernel(venv_dir):\n    r_exe_name = find_exe(venv_dir, \"R\")\n    if r_exe_name is None:\n        return [], None, None\n    import subprocess\n    ressources_dir = None\n    try:\n        print_resources = 'cat(as.character(system.file(\"kernelspec\", package = \"IRkernel\")))'\n        resources_dir_bytes = subprocess.check_output([r_exe_name, '--slave', '-e', print_resources])\n        resources_dir = resources_dir_bytes.decode(errors='ignore')\n    except:\n        return [], None, None\n    argv = [r_exe_name, \"--slave\", \"-e\", \"IRkernel::main()\", \"--args\", \"{connection_file}\"]\n    if not os.path.exists(resources_dir.strip()):\n        resources_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"logos\", \"r\")\n    return argv, \"r\", resources_dir",
    "docstring": "Validates that this env contains an IRkernel kernel and returns info to start it\n\n\n    Returns: tuple\n        (ARGV, language, resource_dir)"
  },
  {
    "code": "async def destroy_unit(self, *unit_names):\n        connection = self.connection()\n        app_facade = client.ApplicationFacade.from_connection(connection)\n        log.debug(\n            'Destroying unit%s %s',\n            's' if len(unit_names) == 1 else '',\n            ' '.join(unit_names))\n        return await app_facade.DestroyUnits(list(unit_names))",
    "docstring": "Destroy units by name."
  },
  {
    "code": "def qteStopRecordingHook(self, msgObj):\n        if self.qteRecording:\n            self.qteRecording = False\n            self.qteMain.qteStatus('Macro recording stopped')\n            self.qteMain.qtesigKeyparsed.disconnect(self.qteKeyPress)\n            self.qteMain.qtesigAbort.disconnect(self.qteStopRecordingHook)",
    "docstring": "Stop macro recording.\n\n        The signals from the event handler are disconnected and the\n        event handler policy set to default."
  },
  {
    "code": "def _task_batcher(tasks, batch_size=None):\n    from itertools import izip_longest\n    if not batch_size:\n        batch_size = DEFAULT_TASK_BATCH_SIZE\n    batch_size = min(batch_size, 100)\n    args = [iter(tasks)] * batch_size\n    return ([task for task in group if task] for group in izip_longest(*args))",
    "docstring": "Batches large task lists into groups of 100 so that they can all be\n    inserted."
  },
  {
    "code": "def create(self, body=None, raise_exc=True, headers=None, **kwargs):\n        return self._request(POST, body, raise_exc, headers, **kwargs)",
    "docstring": "Performs an HTTP POST to the server, to create a\n        subordinate resource. Returns a new HALNavigator representing\n        that resource.\n\n        `body` may either be a string or a dictionary representing json\n        `headers` are additional headers to send in the request"
  },
  {
    "code": "def paginate(data: typing.Iterable, page: int = 0, limit: int = 10) -> typing.Iterable:\n    return data[page * limit:page * limit + limit]",
    "docstring": "Slice data over pages\n\n    :param data: any iterable object\n    :type data: :obj:`typing.Iterable`\n    :param page: number of page\n    :type page: :obj:`int`\n    :param limit: items per page\n    :type limit: :obj:`int`\n    :return: sliced object\n    :rtype: :obj:`typing.Iterable`"
  },
  {
    "code": "async def add_relation(self, local_relation, remote_relation):\n        if ':' not in local_relation:\n            local_relation = '{}:{}'.format(self.name, local_relation)\n        return await self.model.add_relation(local_relation, remote_relation)",
    "docstring": "Add a relation to another application.\n\n        :param str local_relation: Name of relation on this application\n        :param str remote_relation: Name of relation on the other\n            application in the form '<application>[:<relation_name>]'"
  },
  {
    "code": "def queryFilter(self, function=None):\n        if function is not None:\n            self.__query_filter = function\n            return function\n        def wrapper(func):\n            self.__query_filter = func\n            return func\n        return wrapper",
    "docstring": "Defines a decorator that can be used to filter\n        queries.  It will assume the function being associated\n        with the decorator will take a query as an input and\n        return a modified query to use.\n\n        :usage\n\n            class MyModel(orb.Model):\n                objects = orb.ReverseLookup('Object')\n\n                @classmethod\n                @objects.queryFilter()\n                def objectsFilter(cls, query, **context):\n                    return orb.Query()\n\n        :param function: <callable>\n\n        :return: <wrapper>"
  },
  {
    "code": "def delete(self):\n        if lib.EnvDeleteInstance(self._env, self._ist) != 1:\n            raise CLIPSError(self._env)",
    "docstring": "Delete the instance."
  },
  {
    "code": "def getDiscountAmount(self):\n        has_client_discount = self.aq_parent.getMemberDiscountApplies()\n        if has_client_discount:\n            discount = Decimal(self.getDefaultMemberDiscount())\n            return Decimal(self.getSubtotal() * discount / 100)\n        else:\n            return 0",
    "docstring": "It computes and returns the analysis service's discount amount\n        without VAT"
  },
  {
    "code": "def _getEventFromUid(self, request, uid):\n        event = getEventFromUid(request, uid)\n        if event.get_ancestors().filter(id=self.id).exists():\n            return event",
    "docstring": "Try and find a child event with the given UID."
  },
  {
    "code": "def add_record_set(self, record_set):\n        if not isinstance(record_set, ResourceRecordSet):\n            raise ValueError(\"Pass a ResourceRecordSet\")\n        self._additions += (record_set,)",
    "docstring": "Append a record set to the 'additions' for the change set.\n\n        :type record_set:\n            :class:`google.cloud.dns.resource_record_set.ResourceRecordSet`\n        :param record_set: the record set to append.\n\n        :raises: ``ValueError`` if ``record_set`` is not of the required type."
  },
  {
    "code": "def setImageMode(self):\n        if self._version_server == 3.889:\n            self.setPixelFormat(\n                    bpp = 16, depth = 16, bigendian = 0, truecolor = 1,\n                    redmax = 31, greenmax = 63, bluemax = 31,\n                    redshift = 11, greenshift = 5, blueshift = 0\n                    )\n            self.image_mode = \"BGR;16\"\n        elif (self.truecolor and (not self.bigendian) and self.depth == 24\n                and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255):\n            pixel = [\"X\"] * self.bypp\n            offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)]\n            for offset, color in zip(offsets, \"RGB\"):\n                pixel[offset] = color\n            self.image_mode = \"\".join(pixel)\n        else:\n            self.setPixelFormat()",
    "docstring": "Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information"
  },
  {
    "code": "def load_rule_definitions(self, ruleset_generator = False, rule_dirs = []):\n        self.rule_definitions = {}\n        for rule_filename in self.rules:\n            for rule in self.rules[rule_filename]:\n                if not rule.enabled and not ruleset_generator:\n                    continue\n            self.rule_definitions[os.path.basename(rule_filename)] = RuleDefinition(rule_filename, rule_dirs = rule_dirs)\n        if ruleset_generator:\n            rule_dirs.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/findings'))\n            rule_filenames = []\n            for rule_dir in rule_dirs:\n                rule_filenames += [f for f in os.listdir(rule_dir) if os.path.isfile(os.path.join(rule_dir, f))]\n            for rule_filename in rule_filenames:\n                if rule_filename not in self.rule_definitions:\n                    self.rule_definitions[os.path.basename(rule_filename)] = RuleDefinition(rule_filename)",
    "docstring": "Load definition of rules declared in the ruleset\n\n        :param services:\n        :param ip_ranges:\n        :param aws_account_id:\n        :param generator:\n        :return:"
  },
  {
    "code": "def _fetch(self, params, required, defaults):\n        defaults.update(params)\n        pp_params = self._check_and_update_params(required, defaults)\n        pp_string = self.signature + urlencode(pp_params)\n        response = self._request(pp_string)\n        response_params = self._parse_response(response)\n        log.debug('PayPal Request:\\n%s\\n', pprint.pformat(defaults))\n        log.debug('PayPal Response:\\n%s\\n', pprint.pformat(response_params))\n        nvp_params = {}\n        tmpd = defaults.copy()\n        tmpd.update(response_params)\n        for k, v in tmpd.items():\n            if k in self.NVP_FIELDS:\n                nvp_params[str(k)] = v\n        if 'timestamp' in nvp_params:\n            nvp_params['timestamp'] = paypaltime2datetime(nvp_params['timestamp'])\n        nvp_obj = PayPalNVP(**nvp_params)\n        nvp_obj.init(self.request, params, response_params)\n        nvp_obj.save()\n        return nvp_obj",
    "docstring": "Make the NVP request and store the response."
  },
  {
    "code": "def aead_filename(aead_dir, key_handle, public_id):\n    parts = [aead_dir, key_handle] + pyhsm.util.group(public_id, 2)\n    path = os.path.join(*parts)\n    if not os.path.isdir(path):\n        os.makedirs(path)\n    return os.path.join(path, public_id)",
    "docstring": "Return the filename of the AEAD for this public_id,\n    and create any missing directorys."
  },
  {
    "code": "def start(self, build_requests=None, callback=None):\n        if callback:\n            self.callback = callback\n        if build_requests:\n            self.build_requests = build_requests\n        self.sw = threading.Thread(target=self.run)\n        self.sw.start()",
    "docstring": "Run the client using a background thread."
  },
  {
    "code": "def get_data(model, instance_id, kind=''):\n    instance = get_instance(model, instance_id)\n    if not instance:\n        return\n    return ins2dict(instance, kind)",
    "docstring": "Get instance data by id.\n\n    :param model: a string, model name in rio.models\n    :param id: an integer, instance id.\n    :param kind: a string specified which kind of dict tranformer should be called.\n    :return: data."
  },
  {
    "code": "def tableexists(tablename):\n    result = True\n    try:\n        t = table(tablename, ack=False)\n    except:\n        result = False\n    return result",
    "docstring": "Test if a table exists."
  },
  {
    "code": "def sendRequest(self, name, args):\n        (respEvt, id) = self.newResponseEvent()\n        self.sendMessage({\"id\":id, \"method\":name, \"params\": args})\n        return respEvt",
    "docstring": "sends a request to the peer"
  },
  {
    "code": "def load(self, name, location='local'):\n        path = self._get_path(name, location, file_ext='.json')\n        if op.exists(path):\n            return _load_json(path)\n        path = self._get_path(name, location, file_ext='.pkl')\n        if op.exists(path):\n            return _load_pickle(path)\n        logger.debug(\"The file `%s` doesn't exist.\", path)\n        return {}",
    "docstring": "Load saved data from the cache directory."
  },
  {
    "code": "def load_configuration(app_name):\n    if sys.prefix == '/usr':\n        conf_dir = '/etc'\n        share_dir = '/usr/share'\n    else:\n        conf_dir = os.path.join(sys.prefix, 'etc')\n        share_dir = os.path.join(sys.prefix, 'share')\n    yml_config = {}\n    for fname in [\n            '%s.yml'%(app_name,),\n            os.path.expanduser('~/.%s.yml'%(app_name,)),\n            os.path.join(conf_dir, '%s.yml'%(app_name,))]:\n        if os.path.exists(fname):\n            yml_config = yaml.load(open(fname))\n            break\n    try:\n        data_dir = yml_config['paths']['data_dir']\n    except KeyError:\n        try:\n            data_dir = os.environ[app_name.upper()]\n        except KeyError:\n            data_dir = os.path.join(share_dir, app_name)\n    return AppContext(yml_config, data_dir)",
    "docstring": "creates a new configuration and loads the appropriate\n    files."
  },
  {
    "code": "def Throughput(self):\n        try:\n            throughput = spectrum.TabularSpectralElement()\n            product = self._multiplyThroughputs(0)\n            throughput._wavetable = product.GetWaveSet()\n            throughput._throughputtable = product(throughput._wavetable)\n            throughput.waveunits = product.waveunits\n            throughput.name='*'.join([str(x) for x in self.components])\n            return throughput\n        except IndexError:\n            return None",
    "docstring": "Combined throughput from multiplying all the components together.\n\n        Returns\n        -------\n        throughput : `~pysynphot.spectrum.TabularSpectralElement` or `None`\n            Combined throughput."
  },
  {
    "code": "def handle_abort(self, reason):\n        self._welcome_queue.put(reason)\n        self.close()\n        self.disconnect()",
    "docstring": "We're out?"
  },
  {
    "code": "def get_mode(self, gpio):\n        res = yield from self._pigpio_aio_command(_PI_CMD_MODEG, gpio, 0)\n        return _u2i(res)",
    "docstring": "Returns the gpio mode.\n\n        gpio:= 0-53.\n\n        Returns a value as follows\n\n        . .\n        0 = INPUT\n        1 = OUTPUT\n        2 = ALT5\n        3 = ALT4\n        4 = ALT0\n        5 = ALT1\n        6 = ALT2\n        7 = ALT3\n        . .\n\n        ...\n        print(pi.get_mode(0))\n        4\n        ..."
  },
  {
    "code": "def _encoder(self):\n    if self.source_lang == 'en':\n      return Transliterator._dummy_coder\n    else:\n      weights = load_transliteration_table(self.source_lang)\n      encoder_weights = weights[\"encoder\"]\n      return Transliterator._transliterate_string(encoder_weights)",
    "docstring": "Transliterate a string from the input language to English."
  },
  {
    "code": "def automatic_parser(result, dtypes={}, converters={}):\n    np.seterr(all='raise')\n    parsed = {}\n    for filename, contents in result['output'].items():\n        if dtypes.get(filename) is None:\n            dtypes[filename] = None\n        if converters.get(filename) is None:\n            converters[filename] = None\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            parsed[filename] = np.genfromtxt(io.StringIO(contents),\n                                             dtype=dtypes[filename],\n                                             converters=converters[filename]\n                                             ).tolist()\n    return parsed",
    "docstring": "Try and automatically convert strings formatted as tables into nested\n    list structures.\n\n    Under the hood, this function essentially applies the genfromtxt function\n    to all files in the output, and passes it the additional kwargs.\n\n    Args:\n      result (dict): the result to parse.\n      dtypes (dict): a dictionary containing the dtype specification to perform\n        parsing for each available filename. See the numpy genfromtxt\n        documentation for more details on how to format these."
  },
  {
    "code": "def insert(table, values=(), **kwargs):\r\n    values = dict(values, **kwargs).items()\r\n    sql, args = makeSQL(\"INSERT\", table, values=values)\r\n    return execute(sql, args).lastrowid",
    "docstring": "Convenience wrapper for database INSERT."
  },
  {
    "code": "def blow_out(self,\n                 location: Union[types.Location, Well] = None\n                 ) -> 'InstrumentContext':\n        if location is None:\n            if not self._ctx.location_cache:\n                raise RuntimeError('No valid current location cache present')\n            else:\n                location = self._ctx.location_cache.labware\n        if isinstance(location, Well):\n            if location.parent.is_tiprack:\n                self._log.warning('Blow_out being performed on a tiprack. '\n                                  'Please re-check your code')\n            target = location.top()\n        elif isinstance(location, types.Location) and not \\\n                isinstance(location.labware, Well):\n            raise TypeError(\n                'location should be a Well or None, but it is {}'\n                .format(location))\n        else:\n            raise TypeError(\n                'location should be a Well or None, but it is {}'\n                .format(location))\n        self.move_to(target)\n        self._hw_manager.hardware.blow_out(self._mount)\n        return self",
    "docstring": "Blow liquid out of the tip.\n\n        If :py:attr:`dispense` is used to completely empty a pipette,\n        usually a small amount of liquid will remain in the tip. This\n        method moves the plunger past its usual stops to fully remove\n        any remaining liquid from the tip. Regardless of how much liquid\n        was in the tip when this function is called, after it is done\n        the tip will be empty.\n\n        :param location: The location to blow out into. If not specified,\n                         defaults to the current location of the pipette\n        :type location: :py:class:`.Well` or :py:class:`.Location` or None\n\n        :raises RuntimeError: If no location is specified and location cache is\n                              None. This should happen if `blow_out` is called\n                              without first calling a method that takes a\n                              location (eg, :py:meth:`.aspirate`,\n                              :py:meth:`dispense`)\n        :returns: This instance"
  },
  {
    "code": "def image_create(self, disk, label=None, description=None):\n        params = {\n            \"disk_id\": disk.id if issubclass(type(disk), Base) else disk,\n        }\n        if label is not None:\n            params[\"label\"] = label\n        if description is not None:\n            params[\"description\"] = description\n        result = self.post('/images', data=params)\n        if not 'id' in result:\n            raise UnexpectedResponseError('Unexpected response when creating an '\n                                          'Image from disk {}'.format(disk))\n        return Image(self, result['id'], result)",
    "docstring": "Creates a new Image from a disk you own.\n\n        :param disk: The Disk to imagize.\n        :type disk: Disk or int\n        :param label: The label for the resulting Image (defaults to the disk's\n                      label.\n        :type label: str\n        :param description: The description for the new Image.\n        :type description: str\n\n        :returns: The new Image.\n        :rtype: Image"
  },
  {
    "code": "def anonymized_formula(self):\n        anon_formula = super().anonymized_formula\n        chg = self._charge\n        chg_str = \"\"\n        if chg > 0:\n            chg_str += (\"{}{}\".format('+', str(int(chg))))\n        elif chg < 0:\n            chg_str += (\"{}{}\".format('-', str(int(np.abs(chg)))))\n        return anon_formula + chg_str",
    "docstring": "An anonymized formula. Appends charge to the end\n        of anonymized composition"
  },
  {
    "code": "def make_student(user):\n    tutor_group, owner_group = _get_user_groups()\n    user.is_staff = False\n    user.is_superuser = False\n    user.save()\n    owner_group.user_set.remove(user)\n    owner_group.save()\n    tutor_group.user_set.remove(user)\n    tutor_group.save()",
    "docstring": "Makes the given user a student."
  },
  {
    "code": "def connect(self, *names):\n        fromName, toName, rest = names[0], names[1], names[2:]\n        self.connectAt(fromName, toName)\n        if len(rest) != 0:\n            self.connect(toName, *rest)",
    "docstring": "Connects a list of names, one to the next."
  },
  {
    "code": "def on_message(self, message):\n        message = ObjectDict(escape.json_decode(message))\n        if message.command == 'hello':\n            handshake = {\n                'command': 'hello',\n                'protocols': [\n                    'http://livereload.com/protocols/official-7',\n                ],\n                'serverName': 'livereload-tornado',\n            }\n            self.send_message(handshake)\n        if message.command == 'info' and 'url' in message:\n            logger.info('Browser Connected: %s' % message.url)\n            LiveReloadHandler.waiters.add(self)",
    "docstring": "Handshake with livereload.js\n\n        1. client send 'hello'\n        2. server reply 'hello'\n        3. client send 'info'"
  },
  {
    "code": "def send_query(text, service_endpoint='drum', query_args=None):\n    if service_endpoint in ['drum', 'drum-dev', 'cwms', 'cwmsreader']:\n        url = base_url + service_endpoint\n    else:\n        logger.error('Invalid service endpoint: %s' % service_endpoint)\n        return ''\n    if query_args is None:\n        query_args = {}\n    query_args.update({'input': text})\n    res = requests.get(url, query_args, timeout=3600)\n    if not res.status_code == 200:\n        logger.error('Problem with TRIPS query: status code %s' %\n                     res.status_code)\n        return ''\n    return res.text",
    "docstring": "Send a query to the TRIPS web service.\n\n    Parameters\n    ----------\n    text : str\n        The text to be processed.\n    service_endpoint : Optional[str]\n        Selects the TRIPS/DRUM web service endpoint to use. Is a choice between\n        \"drum\" (default), \"drum-dev\", a nightly build, and \"cwms\" for use with\n        more general knowledge extraction.\n    query_args : Optional[dict]\n        A dictionary of arguments to be passed with the query.\n\n    Returns\n    -------\n    html : str\n        The HTML result returned by the web service."
  },
  {
    "code": "def _get_names(node, result):\n    if isinstance(node, ast.Name):\n        return node.id + result\n    elif isinstance(node, ast.Subscript):\n        return result\n    elif isinstance(node, ast.Starred):\n        return _get_names(node.value, result)\n    else:\n        return _get_names(node.value, result + '.' + node.attr)",
    "docstring": "Recursively finds all names."
  },
  {
    "code": "def fetch(self, no_ack=None, auto_ack=None, enable_callbacks=False):\n        no_ack = no_ack or self.no_ack\n        auto_ack = auto_ack or self.auto_ack\n        message = self.backend.get(self.queue, no_ack=no_ack)\n        if message:\n            if auto_ack and not message.acknowledged:\n                message.ack()\n            if enable_callbacks:\n                self.receive(message.payload, message)\n        return message",
    "docstring": "Receive the next message waiting on the queue.\n\n        :returns: A :class:`carrot.backends.base.BaseMessage` instance,\n            or ``None`` if there's no messages to be received.\n\n        :keyword enable_callbacks: Enable callbacks. The message will be\n            processed with all registered callbacks. Default is disabled.\n        :keyword auto_ack: Override the default :attr:`auto_ack` setting.\n        :keyword no_ack: Override the default :attr:`no_ack` setting."
  },
  {
    "code": "def delete_cookie(self, key, path='/', domain=None):\n        self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)",
    "docstring": "Delete a cookie.  Fails silently if key doesn't exist.\n\n        :param key: the key (name) of the cookie to be deleted.\n        :param path: if the cookie that should be deleted was limited to a\n                     path, the path has to be defined here.\n        :param domain: if the cookie that should be deleted was limited to a\n                       domain, that domain has to be defined here."
  },
  {
    "code": "def _check_for_python_keywords(self, kwargs):\n        kwargs_copy = copy.deepcopy(kwargs)\n        for key, val in iteritems(kwargs):\n            if isinstance(val, dict):\n                kwargs_copy[key] = self._check_for_python_keywords(val)\n            elif isinstance(val, list):\n                kwargs_copy[key] = self._iter_list_for_dicts(val)\n            else:\n                if key.endswith('_'):\n                    strip_key = key.rstrip('_')\n                    if keyword.iskeyword(strip_key):\n                        kwargs_copy[strip_key] = val\n                        kwargs_copy.pop(key)\n        return kwargs_copy",
    "docstring": "When Python keywords seen, mutate to remove trailing underscore."
  },
  {
    "code": "def clean_tarinfo(cls, tar_info):\n        ti = copy(tar_info)\n        ti.uid = 0\n        ti.gid = 0\n        ti.uname = \"\"\n        ti.gname = \"\"\n        ti.mode = normalize_file_permissions(ti.mode)\n        return ti",
    "docstring": "Clean metadata from a TarInfo object to make it more reproducible.\n\n            - Set uid & gid to 0\n            - Set uname and gname to \"\"\n            - Normalise permissions to 644 or 755\n            - Set mtime if not None"
  },
  {
    "code": "def remove_listener(self, event_name, listener):\n        self.listeners[event_name].remove(listener)\n        return self",
    "docstring": "Removes a listener."
  },
  {
    "code": "def get_disk_usage(self, path=None):\n        DiskUsage = namedtuple('usage', 'total, used, free')\n        if path is None:\n            mount_point = self.mount_points[self.root.name]\n        else:\n            mount_point = self._mount_point_for_path(path)\n        if mount_point and mount_point['total_size'] is not None:\n            return DiskUsage(mount_point['total_size'],\n                             mount_point['used_size'],\n                             mount_point['total_size'] -\n                             mount_point['used_size'])\n        return DiskUsage(\n            1024 * 1024 * 1024 * 1024, 0, 1024 * 1024 * 1024 * 1024)",
    "docstring": "Return the total, used and free disk space in bytes as named tuple,\n        or placeholder values simulating unlimited space if not set.\n\n        .. note:: This matches the return value of shutil.disk_usage().\n\n        Args:\n            path: The disk space is returned for the file system device where\n                `path` resides.\n                Defaults to the root path (e.g. '/' on Unix systems)."
  },
  {
    "code": "def add_handler(self, message_type, handler):\n        if message_type not in self._handlers:\n            self._handlers[message_type] = []\n        if handler not in self._handlers[message_type]:\n            self._handlers[message_type].append(handler)",
    "docstring": "Manage callbacks for message handlers."
  },
  {
    "code": "def get_random_hex(length):\n    if length <= 0:\n        return ''\n    return hexify(random.randint(pow(2, length*2), pow(2, length*4)))[0:length]",
    "docstring": "Return random hex string of a given length"
  },
  {
    "code": "def Execute(self, action, *args, **kw):\n        action = self.Action(action, *args, **kw)\n        result = action([], [], self)\n        if isinstance(result, SCons.Errors.BuildError):\n            errstr = result.errstr\n            if result.filename:\n                errstr = result.filename + ': ' + errstr\n            sys.stderr.write(\"scons: *** %s\\n\" % errstr)\n            return result.status\n        else:\n            return result",
    "docstring": "Directly execute an action through an Environment"
  },
  {
    "code": "def centroid_distance(item_a, time_a, item_b, time_b, max_value):\n    ax, ay = item_a.center_of_mass(time_a)\n    bx, by = item_b.center_of_mass(time_b)\n    return np.minimum(np.sqrt((ax - bx) ** 2 + (ay - by) ** 2), max_value) / float(max_value)",
    "docstring": "Euclidean distance between the centroids of item_a and item_b.\n\n    Args:\n        item_a: STObject from the first set in ObjectMatcher\n        time_a: Time integer being evaluated\n        item_b: STObject from the second set in ObjectMatcher\n        time_b: Time integer being evaluated\n        max_value: Maximum distance value used as scaling value and upper constraint.\n\n    Returns:\n        Distance value between 0 and 1."
  },
  {
    "code": "def get(self, path, default=_NoDefault, as_type=None, resolve_references=True):\n        value = self._source\n        steps_taken = []\n        try:\n            for step in path.split(self._separator):\n                steps_taken.append(step)\n                value = value[step]\n            if as_type:\n                return as_type(value)\n            elif isinstance(value, Mapping):\n                namespace = type(self)(separator=self._separator, missing=self._missing)\n                namespace._source = value\n                namespace._root = self._root\n                return namespace\n            elif resolve_references and isinstance(value, str):\n                return self._resolve(value)\n            else:\n                return value\n        except ConfiguredReferenceError:\n            raise\n        except KeyError as e:\n            if default is not _NoDefault:\n                return default\n            else:\n                missing_key = self._separator.join(steps_taken)\n                raise NotConfiguredError('no configuration for key {}'.format(missing_key), key=missing_key) from e",
    "docstring": "Gets a value for the specified path.\n\n        :param path: the configuration key to fetch a value for, steps\n            separated by the separator supplied to the constructor (default\n            ``.``)\n        :param default: a value to return if no value is found for the\n            supplied path (``None`` is allowed)\n        :param as_type: an optional callable to apply to the value found for\n            the supplied path (possibly raising exceptions of its own if the\n            value can not be coerced to the expected type)\n        :param resolve_references: whether to resolve references in values\n        :return: the value associated with the supplied configuration key, if\n            available, or a supplied default value if the key was not found\n        :raises ConfigurationError: when no value was found for *path* and\n            *default* was not provided or a reference could not be resolved"
  },
  {
    "code": "def get(self, name=None):\n        return self.app.shared_objects.get(name, self.plugin)",
    "docstring": "Returns requested shared objects, which were registered by the current plugin.\n\n        If access to objects of other plugins are needed, use :func:`access` or perform get on application level::\n\n            my_app.shared_objects.get(name=\"...\")\n\n        :param name: Name of a request shared object\n        :type name: str or None"
  },
  {
    "code": "def start(self, id):\n        path = partial(_path, self.adapter)\n        path = path(id)\n        return self._put(path)",
    "docstring": "start a specific tracker."
  },
  {
    "code": "def findInvariantPartitioning(self):\n        symorders = self.symorders[:]\n        _range = range(len(symorders))\n        while 1:\n            pos = self.findLowest(symorders)\n            if pos == -1:\n                self.symorders = symorders\n                return\n            for i in _range:\n                symorders[i] = symorders[i] * 2 + 1\n            symorders[pos] = symorders[pos] - 1\n            symorders = self.findInvariant(symorders)",
    "docstring": "Keep the initial ordering of the symmetry orders\n        but make all values unique.  For example, if there are\n        two symmetry orders equal to 0, convert them to 0 and 1\n        and add 1 to the remaining orders\n\n          [0, 1, 0, 1]\n        should become\n          [0, 2, 1, 3]"
  },
  {
    "code": "def int_args(self):\n        if self.ARG_REGS is None:\n            raise NotImplementedError()\n        for reg in self.ARG_REGS:\n            yield SimRegArg(reg, self.arch.bytes)",
    "docstring": "Iterate through all the possible arg positions that can only be used to store integer or pointer values\n        Does not take into account customizations.\n\n        Returns an iterator of SimFunctionArguments"
  },
  {
    "code": "def new(self):\n        new_dashboard = models.Dashboard(\n            dashboard_title='[ untitled dashboard ]',\n            owners=[g.user],\n        )\n        db.session.add(new_dashboard)\n        db.session.commit()\n        return redirect(f'/superset/dashboard/{new_dashboard.id}/?edit=true')",
    "docstring": "Creates a new, blank dashboard and redirects to it in edit mode"
  },
  {
    "code": "def set_data(self, data):\n\t\t\"Use this method to set the data for this blob\"\n\t\tif data is None:\n\t\t\tself.data_size = 0\n\t\t\tself.data = None\n\t\t\treturn\n\t\tself.data_size = len(data)\n\t\tself.data = ctypes.cast(ctypes.create_string_buffer(data), ctypes.c_void_p)",
    "docstring": "Use this method to set the data for this blob"
  },
  {
    "code": "def retry(self):\n\t\tif not self.paid and not self.forgiven and not self.closed:\n\t\t\tstripe_invoice = self.api_retrieve()\n\t\t\tupdated_stripe_invoice = (\n\t\t\t\tstripe_invoice.pay()\n\t\t\t)\n\t\t\ttype(self).sync_from_stripe_data(updated_stripe_invoice)\n\t\t\treturn True\n\t\treturn False",
    "docstring": "Retry payment on this invoice if it isn't paid, closed, or forgiven."
  },
  {
    "code": "def capabilities(self):\n\t\tcaps = []\n\t\tfor cap in DeviceCapability:\n\t\t\tif self._libinput.libinput_device_has_capability(self._handle, cap):\n\t\t\t\tcaps.append(cap)\n\t\treturn tuple(caps)",
    "docstring": "A tuple of capabilities this device supports.\n\n\t\tReturns:\n\t\t\t(~libinput.constant.DeviceCapability): Device capabilities."
  },
  {
    "code": "def logger(self):\n        if self._experiment:\n            return logging.getLogger('.'.join([self.name, self.experiment]))\n        elif self._projectname:\n            return logging.getLogger('.'.join([self.name, self.projectname]))\n        else:\n            return logging.getLogger('.'.join([self.name]))",
    "docstring": "The logger of this organizer"
  },
  {
    "code": "def process_param(self):\n        self.log_response_message('got RETURNVALUE message')\n        r = self._reader\n        if tds_base.IS_TDS72_PLUS(self):\n            ordinal = r.get_usmallint()\n        else:\n            r.get_usmallint()\n            ordinal = self._out_params_indexes[self.return_value_index]\n        name = r.read_ucs2(r.get_byte())\n        r.get_byte()\n        param = tds_base.Column()\n        param.column_name = name\n        self.get_type_info(param)\n        param.value = param.serializer.read(r)\n        self.output_params[ordinal] = param\n        self.return_value_index += 1",
    "docstring": "Reads and processes RETURNVALUE stream.\n\n        This stream is used to send OUTPUT parameters from RPC to client.\n        Stream format url: http://msdn.microsoft.com/en-us/library/dd303881.aspx"
  },
  {
    "code": "def reduce(self, show_noisy=False):\n        if not show_noisy:\n            for log in self.quiet_logs:\n                yield log['raw'].strip()\n        else:\n            for log in self.noisy_logs:\n                yield log['raw'].strip()",
    "docstring": "Yield the reduced log lines\n\n        :param show_noisy: If this is true, shows the reduced log file. If this is false, it shows the logs that\n        were deleted."
  },
  {
    "code": "def validate_schema(schema: GraphQLSchema) -> List[GraphQLError]:\n    assert_schema(schema)\n    errors = schema._validation_errors\n    if errors is None:\n        context = SchemaValidationContext(schema)\n        context.validate_root_types()\n        context.validate_directives()\n        context.validate_types()\n        errors = context.errors\n        schema._validation_errors = errors\n    return errors",
    "docstring": "Validate a GraphQL schema.\n\n    Implements the \"Type Validation\" sub-sections of the specification's \"Type System\"\n    section.\n\n    Validation runs synchronously, returning a list of encountered errors, or an empty\n    list if no errors were encountered and the Schema is valid."
  },
  {
    "code": "def merge_class(base, other):\n        try:\n            other = other.rules\n        except AttributeError:\n            pass\n        if not isinstance(other, list):\n            other = [other]\n        other_holidays = {holiday.name: holiday for holiday in other}\n        try:\n            base = base.rules\n        except AttributeError:\n            pass\n        if not isinstance(base, list):\n            base = [base]\n        base_holidays = {holiday.name: holiday for holiday in base}\n        other_holidays.update(base_holidays)\n        return list(other_holidays.values())",
    "docstring": "Merge holiday calendars together. The base calendar\n        will take precedence to other. The merge will be done\n        based on each holiday's name.\n\n        Parameters\n        ----------\n        base : AbstractHolidayCalendar\n          instance/subclass or array of Holiday objects\n        other : AbstractHolidayCalendar\n          instance/subclass or array of Holiday objects"
  },
  {
    "code": "def get_structural_variant(self, variant):\n        query = {\n                'chrom': variant['chrom'],\n                'end_chrom': variant['end_chrom'],\n                'sv_type': variant['sv_type'],\n                '$and': [\n                    {'pos_left': {'$lte': variant['pos']}},\n                    {'pos_right': {'$gte': variant['pos']}},\n                ]\n            }\n        res = self.db.structural_variant.find(query).sort('pos_left',1)\n        match = None\n        distance = None\n        closest_hit = None\n        for hit in res:\n            if hit['end_left'] > variant['end']:\n                continue\n            if hit['end_right'] < variant['end']:\n                continue\n            distance = (abs(variant['pos'] - (hit['pos_left'] + hit['pos_right'])/2) + \n                        abs(variant['end'] - (hit['end_left'] + hit['end_right'])/2))\n            if closest_hit is None:\n                match = hit\n                closest_hit = distance\n                continue\n            if distance < closest_hit:\n                match = hit\n                closest_hit = distance\n        return match",
    "docstring": "Check if there are any overlapping sv clusters\n\n       Search the sv variants with chrom start end_chrom end and sv_type\n\n       Args:\n           variant (dict): A variant dictionary\n\n       Returns:\n           variant (dict): A variant dictionary"
  },
  {
    "code": "def get_next_property(self):\n        try:\n            next_object = self.next()\n        except StopIteration:\n            raise IllegalState('no more elements available in this list')\n        except Exception:\n            raise OperationFailed()\n        else:\n            return next_object",
    "docstring": "Gets the next ``Property`` in this list.\n\n        :return: the next ``Property`` in this list. The ``has_next()`` method should be used to test that a next ``Property`` is available before calling this method.\n        :rtype: ``osid.Property``\n        :raise: ``IllegalState`` -- no more elements available in this list\n        :raise: ``OperationFailed`` -- unable to complete request\n\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_source_and_pgp_key(source_and_key):\n    try:\n        source, key = source_and_key.split('|', 2)\n        return source, key or None\n    except ValueError:\n        return source_and_key, None",
    "docstring": "Look for a pgp key ID or ascii-armor key in the given input.\n\n    :param source_and_key: Sting, \"source_spec|keyid\" where '|keyid' is\n        optional.\n    :returns (source_spec, key_id OR None) as a tuple.  Returns None for key_id\n        if there was no '|' in the source_and_key string."
  },
  {
    "code": "def get_watchman_sockpath(binpath='watchman'):\n    path = os.getenv('WATCHMAN_SOCK')\n    if path:\n        return path\n    cmd = [binpath, '--output-encoding=json', 'get-sockname']\n    result = subprocess.check_output(cmd)\n    result = json.loads(result)\n    return result['sockname']",
    "docstring": "Find the watchman socket or raise."
  },
  {
    "code": "def append(self, fdata, offset, query='/content/uploads'):\n        query = '%s/%s/%s/' % (query, self.uid, offset)\n        _r = self.connector.put(query, fdata, log_data=False, auto_create_json_str=False)\n        juicer.utils.Log.log_notice(\"Appending to: %s\" % query)\n        juicer.utils.Log.log_debug(\"Continuing upload with append. POST returned with data: %s\" % str(_r.content))\n        return _r.status_code",
    "docstring": "append binary data to an upload\n        `fdata` - binary data to send to pulp\n        `offset` - the amount of previously-uploaded data"
  },
  {
    "code": "def get_var_shape(self, name):\n        rank = self.get_var_rank(name)\n        name = create_string_buffer(name)\n        arraytype = ndpointer(dtype='int32',\n                              ndim=1,\n                              shape=(MAXDIMS, ),\n                              flags='F')\n        shape = np.empty((MAXDIMS, ), dtype='int32', order='F')\n        self.library.get_var_shape.argtypes = [c_char_p, arraytype]\n        self.library.get_var_shape(name, shape)\n        return tuple(shape[:rank])",
    "docstring": "Return shape of the array."
  },
  {
    "code": "def delete_node_nto1(node_list, begin, node, end):\n        if begin is None:\n            assert node is not None\n            begin = node.precedence\n        elif not isinstance(begin, list):\n            begin = [begin]\n        if end.in_or_out:\n            for nb_ in begin:\n                nb_.out_redirect(node.single_input, node.single_output)\n        else:\n            for nb_ in begin:\n                target_var_name = node.single_input\n                assert target_var_name in nb_.output.values()\n                end.in_redirect(node.single_output, target_var_name)\n        for nb_ in begin:\n            nb_.successor = [end if v_ == node else v_ for v_ in nb_.successor]\n        end.precedence = [v_ for v_ in end.precedence if v_ != node] + node.precedence\n        node_list.remove(node)\n        return node_list",
    "docstring": "delete the node which has n-input and 1-output"
  },
  {
    "code": "def beacon(config):\n    log.trace('salt proxy beacon called')\n    _config = {}\n    list(map(_config.update, config))\n    return _run_proxy_processes(_config['proxies'])",
    "docstring": "Handle configured proxies\n\n    .. code-block:: yaml\n\n        beacons:\n          salt_proxy:\n            - proxies:\n                p8000: {}\n                p8001: {}"
  },
  {
    "code": "def update(self, entity):\n        assert isinstance(entity, Entity), \"Error: entity must have an instance of Entity\"\n        return self.__collection.update({'_id': entity._id}, {'$set': entity.as_dict()})",
    "docstring": "Executes collection's update method based on keyword args.\n\n        Example::\n\n            manager = EntityManager(Product)\n            p = Product()\n            p.name = 'new name'\n            p.description = 'new description'\n            p.price = 300.0\n\n            yield manager.update(p)"
  },
  {
    "code": "def dns(self):\n        dns = {\n            'elb': self.dns_elb(),\n            'elb_region': self.dns_elb_region(),\n            'global': self.dns_global(),\n            'region': self.dns_region(),\n            'instance': self.dns_instance(),\n        }\n        return dns",
    "docstring": "DNS details."
  },
  {
    "code": "def clear_duration(self):\n        if (self.get_duration_metadata().is_read_only() or\n                self.get_duration_metadata().is_required()):\n            raise errors.NoAccess()\n        self._my_map['duration'] = self._duration_default",
    "docstring": "Clears the duration.\n\n        raise:  NoAccess - ``Metadata.isRequired()`` or\n                ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def normalize_datetime_to_utc(dt):\n    return datetime.datetime(\n        *dt.utctimetuple()[:6], microsecond=dt.microsecond, tzinfo=datetime.timezone.utc\n    )",
    "docstring": "Adjust datetime to UTC.\n\n    Apply the timezone offset to the datetime and set the timezone to UTC.\n\n    This is a no-op if the datetime is already in UTC.\n\n    Args:\n      dt : datetime\n        - tz-aware: Used in the formatted string.\n        - tz-naive: Assumed to be in UTC.\n\n    Returns:\n      datetime\n        The returned datetime is always timezone aware and in UTC.\n\n    Notes:\n      This forces a new object to be returned, which fixes an issue with\n      serialization to XML in PyXB. PyXB uses a mixin together with\n      datetime to handle the XML xs:dateTime. That type keeps track of\n      timezone information included in the original XML doc, which conflicts if we\n      return it here as part of a datetime mixin.\n\n    See Also:\n      ``cast_naive_datetime_to_tz()``"
  },
  {
    "code": "def mds(means, weights, d):\n    X = dim_reduce(means, weights, d)\n    if X.shape[0]==2:\n        return X.dot(weights)\n    else:\n        return X.T.dot(weights)",
    "docstring": "Dimensionality reduction using MDS.\n\n    Args:\n        means (array): genes x clusters\n        weights (array): clusters x cells\n        d (int): desired dimensionality\n\n    Returns:\n        W_reduced (array): array of shape (d, cells)"
  },
  {
    "code": "def get_version(self, as_tuple=False):\n        if as_tuple:\n            return uwsgi.version_info\n        return decode(uwsgi.version)",
    "docstring": "Returns uWSGI version string or tuple.\n\n        :param bool as_tuple:\n\n        :rtype: str|tuple"
  },
  {
    "code": "def get_email_address(self):\n        if self.login is None:\n            self.login = self.generate_login()\n        available_domains = self.available_domains\n        if self.domain is None:\n            self.domain = random.choice(available_domains)\n        elif self.domain not in available_domains:\n            raise ValueError('Domain not found in available domains!')\n        return u'{0}{1}'.format(self.login, self.domain)",
    "docstring": "Return full email address from login and domain from params in class\n        initialization or generate new."
  },
  {
    "code": "def _call(self, x, out=None):\n        if out is None:\n            return x * self.multiplicand\n        elif not self.__range_is_field:\n            if self.__domain_is_field:\n                out.lincomb(x, self.multiplicand)\n            else:\n                out.assign(self.multiplicand * x)\n        else:\n            raise ValueError('can only use `out` with `LinearSpace` range')",
    "docstring": "Multiply ``x`` and write to ``out`` if given."
  },
  {
    "code": "def report_non_responding_hosting_devices(self, context, host,\n                                              hosting_device_ids):\n        self.update_hosting_device_status(context, host,\n                                          {const.HD_DEAD: hosting_device_ids})",
    "docstring": "Report that a hosting device is determined to be dead.\n\n        :param context: contains user information\n        :param host: originator of callback\n        :param hosting_device_ids: list of non-responding hosting devices"
  },
  {
    "code": "def _visual_center(line, width):\n    spaces = max(width - _visual_width(line), 0)\n    left_padding = int(spaces / 2)\n    right_padding = spaces - left_padding\n    return (left_padding * \" \") + line + (right_padding * \" \")",
    "docstring": "Center align string according to it's visual width"
  },
  {
    "code": "def check_user_permissions(payload, user_pk):\n    for perm_type in ['add', 'remove']:\n        user_pks = payload.get('users', {}).get(perm_type, {}).keys()\n        if user_pk in user_pks:\n            raise exceptions.PermissionDenied(\"You cannot change your own permissions\")",
    "docstring": "Raise ``PermissionDenied`` if ``payload`` includes ``user_pk``."
  },
  {
    "code": "def ssm_create_association(name=None, kwargs=None, instance_id=None, call=None):\n    if call != 'action':\n        raise SaltCloudSystemExit(\n            'The ssm_create_association action must be called with '\n            '-a or --action.'\n        )\n    if not kwargs:\n        kwargs = {}\n    if 'instance_id' in kwargs:\n        instance_id = kwargs['instance_id']\n    if name and not instance_id:\n        instance_id = _get_node(name)['instanceId']\n    if not name and not instance_id:\n        log.error('Either a name or an instance_id is required.')\n        return False\n    if 'ssm_document' not in kwargs:\n        log.error('A ssm_document is required.')\n        return False\n    params = {'Action': 'CreateAssociation',\n              'InstanceId': instance_id,\n              'Name': kwargs['ssm_document']}\n    result = aws.query(params,\n                       return_root=True,\n                       location=get_location(),\n                       provider=get_provider(),\n                       product='ssm',\n                       opts=__opts__,\n                       sigver='4')\n    log.info(result)\n    return result",
    "docstring": "Associates the specified SSM document with the specified instance\n\n    http://docs.aws.amazon.com/ssm/latest/APIReference/API_CreateAssociation.html\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt-cloud -a ssm_create_association ec2-instance-name ssm_document=ssm-document-name"
  },
  {
    "code": "def policy_create(request, **kwargs):\n    body = {'policy': kwargs}\n    policy = neutronclient(request).create_qos_policy(body=body).get('policy')\n    return QoSPolicy(policy)",
    "docstring": "Create a QoS Policy.\n\n    :param request: request context\n    :param name: name of the policy\n    :param description: description of policy\n    :param shared: boolean (true or false)\n    :return: QoSPolicy object"
  },
  {
    "code": "def transform_cb(self, setting, value):\n        self.make_callback('transform')\n        whence = 0\n        self.redraw(whence=whence)",
    "docstring": "Handle callback related to changes in transformations."
  },
  {
    "code": "def max(self):\n        if len(self.regions) != 1:\n            raise ClaripyVSAOperationError(\"'max()' onlly works on single-region value-sets.\")\n        return self.get_si(next(iter(self.regions))).max",
    "docstring": "The maximum integer value of a value-set. It is only defined when there is exactly one region.\n\n        :return: A integer that represents the maximum integer value of this value-set.\n        :rtype:  int"
  },
  {
    "code": "def _show_context_menu(self, point):\n        tc = self.textCursor()\n        nc = self.cursorForPosition(point)\n        if not nc.position() in range(tc.selectionStart(), tc.selectionEnd()):\n            self.setTextCursor(nc)\n        self._mnu = self.get_context_menu()\n        if len(self._mnu.actions()) > 1 and self.show_context_menu:\n            self._mnu.popup(self.mapToGlobal(point))",
    "docstring": "Shows the context menu"
  },
  {
    "code": "def to_pixel(self, wcs, mode='all'):\n        pixel_params = self._to_pixel_params(wcs, mode=mode)\n        return EllipticalAnnulus(**pixel_params)",
    "docstring": "Convert the aperture to an `EllipticalAnnulus` object defined in\n        pixel coordinates.\n\n        Parameters\n        ----------\n        wcs : `~astropy.wcs.WCS`\n            The world coordinate system (WCS) transformation to use.\n\n        mode : {'all', 'wcs'}, optional\n            Whether to do the transformation including distortions\n            (``'all'``; default) or only including only the core WCS\n            transformation (``'wcs'``).\n\n        Returns\n        -------\n        aperture : `EllipticalAnnulus` object\n            An `EllipticalAnnulus` object."
  },
  {
    "code": "def get_blob(profile, sha):\n    resource = \"/blobs/\" + sha\n    data = api.get_request(profile, resource)\n    return prepare(data)",
    "docstring": "Fetch a blob.\n\n    Args:\n\n        profile\n            A profile generated from ``simplygithub.authentication.profile``.\n            Such profiles tell this module (i) the ``repo`` to connect to,\n            and (ii) the ``token`` to connect with.\n\n        sha\n            The SHA of the blob to fetch.\n\n    Returns:\n        A dict with data about the blob."
  },
  {
    "code": "def population(self):\n        \"Class containing the population and all the individuals generated\"\n        try:\n            return self._p\n        except AttributeError:\n            self._p = self._population_class(base=self,\n                                             tournament_size=self._tournament_size,\n                                             classifier=self.classifier,\n                                             labels=self._labels,\n                                             es_extra_test=self.es_extra_test,\n                                             popsize=self._popsize,\n                                             random_generations=self._random_generations,\n                                             negative_selection=self._negative_selection)\n            return self._p",
    "docstring": "Class containing the population and all the individuals generated"
  },
  {
    "code": "def populate_from_seqinfo(self, seqinfo):\n        for row in csv.DictReader(seqinfo):\n            node = self.index.get(row['tax_id'])\n            if node:\n                node.sequence_ids.add(row['seqname'])",
    "docstring": "Populate sequence_ids below this node from a seqinfo file object."
  },
  {
    "code": "def functions(self):\n        def is_function(comment):\n            return isinstance(comment, FunctionDoc) and not comment.member\n        return self._filtered_iter(is_function)",
    "docstring": "Returns a generator of all standalone functions in the file, in textual\n        order.\n\n        >>> file = FileDoc('module.js', read_file('examples/module.js'))\n        >>> list(file.functions)[0].name\n        'the_first_function'\n        >>> list(file.functions)[3].name\n        'not_auto_discovered'"
  },
  {
    "code": "def rename(self, name_dict=None, inplace=None, **names):\n        inplace = _check_inplace(inplace)\n        name_dict = either_dict_or_kwargs(name_dict, names, 'rename')\n        for k, v in name_dict.items():\n            if k not in self and k not in self.dims:\n                raise ValueError(\"cannot rename %r because it is not a \"\n                                 \"variable or dimension in this dataset\" % k)\n        variables, coord_names, dims, indexes = self._rename_all(\n            name_dict=name_dict, dim_dict=name_dict)\n        return self._replace(variables, coord_names, dims=dims,\n                             indexes=indexes, inplace=inplace)",
    "docstring": "Returns a new object with renamed variables and dimensions.\n\n        Parameters\n        ----------\n        name_dict : dict-like, optional\n            Dictionary whose keys are current variable or dimension names and\n            whose values are the desired names.\n        inplace : bool, optional\n            If True, rename variables and dimensions in-place. Otherwise,\n            return a new dataset object.\n        **names, optional\n            Keyword form of ``name_dict``.\n            One of name_dict or names must be provided.\n\n        Returns\n        -------\n        renamed : Dataset\n            Dataset with renamed variables and dimensions.\n\n        See Also\n        --------\n        Dataset.swap_dims\n        DataArray.rename"
  },
  {
    "code": "def asDictionary(self):\n        template =  {\n            \"type\": \"dataLayer\",\n            \"dataSource\": self._dataSource\n        }\n        if not self._fields is None:\n            template['fields'] = self._fields\n        return template",
    "docstring": "returns the value as a dictionary"
  },
  {
    "code": "def built_datetime(self):\n        from datetime import datetime\n        try:\n            return datetime.fromtimestamp(self.state.build_done)\n        except TypeError:\n            return None",
    "docstring": "Return the built time as a datetime object"
  },
  {
    "code": "def _notify_single_item(self, item):\n        triggered_channels = set()\n        for key_set in self.watch_keys:\n            plucked = {\n                key_name: item[key_name]\n                for key_name in key_set if key_name in item\n            }\n            route_keys = expand_dict_as_keys(plucked)\n            for route in route_keys:\n                channels = self.get_route_items(route) or {}\n                LOG.debug('route table match: %s -> %s', route, channels)\n                if not channels:\n                    LOG.debug(\n                        'no subscribers for message.\\nkey %s\\nroutes: %s',\n                        route,\n                        self._routes\n                    )\n                for channel in channels:\n                    if channel in triggered_channels:\n                        LOG.debug('skipping dispatch to %s', channel)\n                        continue\n                    LOG.debug('routing dispatch to %s: %s', channel, item)\n                    try:\n                        channel.notify(item) and triggered_channels.add(channel)\n                    except Exception:\n                        LOG.exception('Channel notification failed')\n        return triggered_channels",
    "docstring": "Route inbound items to individual channels"
  },
  {
    "code": "def _process_list(self, l):\n        if hasattr(self, l):\n            t = getattr(self, l)\n            def proc(inp):\n                w = inp.strip()\n                if w.startswith('`'):\n                    r = re.compile(w[1:-1])\n                    return [u for u in [m.group() for m in [r.match(x) for x in dir(self)] if m] if isinstance(getattr(self, u), QObject)]\n                else:\n                    return [w]\n            return list(set([y for x in map(proc, t.split(',')) for y in x]))\n        return []",
    "docstring": "Processes a list of widget names.\n\n        If any name is between `` then it is supposed to be a regex."
  },
  {
    "code": "def printstartfinish(verb, inp=None, kcount=None):\n    r\n    if inp:\n        if verb > 1:\n            ttxt = str(timedelta(seconds=default_timer() - inp))\n            ktxt = ' '\n            if kcount:\n                ktxt += str(kcount) + ' kernel call(s)'\n            print('\\n:: empymod END; runtime = ' + ttxt + ' ::' + ktxt + '\\n')\n    else:\n        t0 = default_timer()\n        if verb > 2:\n            print(\"\\n:: empymod START  ::\\n\")\n        return t0",
    "docstring": "r\"\"\"Print start and finish with time measure and kernel count."
  },
  {
    "code": "def rpXRDS(request):\n    return util.renderXRDS(\n        request,\n        [RP_RETURN_TO_URL_TYPE],\n        [util.getViewURL(request, finishOpenID)])",
    "docstring": "Return a relying party verification XRDS document"
  },
  {
    "code": "def accelerator_experiments(self, key, value):\n    result = []\n    a_value = force_single_element(value.get('a'))\n    e_values = [el for el in force_list(value.get('e')) if el != '-']\n    zero_values = force_list(value.get('0'))\n    if a_value and not e_values:\n        result.append({'accelerator': a_value})\n    if len(e_values) == len(zero_values):\n        for e_value, zero_value in zip(e_values, zero_values):\n            result.append({\n                'legacy_name': e_value,\n                'record': get_record_ref(zero_value, 'experiments'),\n            })\n    else:\n        for e_value in e_values:\n            result.append({'legacy_name': e_value})\n    return result",
    "docstring": "Populate the ``accelerator_experiments`` key."
  },
  {
    "code": "def coord_list_mapping_pbc(subset, superset, atol=1e-8):\n    atol = np.array([1., 1. ,1.]) * atol\n    return cuc.coord_list_mapping_pbc(subset, superset, atol)",
    "docstring": "Gives the index mapping from a subset to a superset.\n    Superset cannot contain duplicate matching rows\n\n    Args:\n        subset, superset: List of frac_coords\n\n    Returns:\n        list of indices such that superset[indices] = subset"
  },
  {
    "code": "def create(self, name, *args, **kwargs):\n        cont = kwargs.get(\"cont\")\n        if cont:\n            api = self.api\n            rgn = api.region_name\n            cf = api.identity.object_store[rgn].client\n            cf.get_container(cont)\n        return super(ImageTasksManager, self).create(name, *args, **kwargs)",
    "docstring": "Standard task creation, but first check for the existence of the\n        containers, and raise an exception if they don't exist."
  },
  {
    "code": "def update_trackers(self):\n        direct_approved_topics = self.topics.filter(approved=True).order_by('-last_post_on')\n        self.direct_topics_count = direct_approved_topics.count()\n        self.direct_posts_count = direct_approved_topics.aggregate(\n            total_posts_count=Sum('posts_count'))['total_posts_count'] or 0\n        if direct_approved_topics.exists():\n            self.last_post_id = direct_approved_topics[0].last_post_id\n            self.last_post_on = direct_approved_topics[0].last_post_on\n        else:\n            self.last_post_id = None\n            self.last_post_on = None\n        self._simple_save()",
    "docstring": "Updates the denormalized trackers associated with the forum instance."
  },
  {
    "code": "def get_archive_formats():\n    formats = [(name, registry[2]) for name, registry in\n               _ARCHIVE_FORMATS.items()]\n    formats.sort()\n    return formats",
    "docstring": "Returns a list of supported formats for archiving and unarchiving.\n\n    Each element of the returned sequence is a tuple (name, description)"
  },
  {
    "code": "def _find_data_path_schema(data_path, schema_name):\n    if not data_path or data_path == '/' or data_path == '.':\n        return None\n    directory = os.path.dirname(data_path)\n    path = glob.glob(os.path.join(directory, schema_name))\n    if not path:\n        return _find_schema(directory, schema_name)\n    return path[0]",
    "docstring": "Starts in the data file folder and recursively looks\n    in parents for `schema_name`"
  },
  {
    "code": "def findAll(haystack, needle) :\n\th = haystack\n\tres = []\n\tf = haystack.find(needle)\n\toffset = 0\n\twhile (f >= 0) :\n\t\tres.append(f+offset)\n\t\toffset += f+len(needle)\n\t\th = h[f+len(needle):]\n\t\tf = h.find(needle)\n\treturn res",
    "docstring": "returns a list of all occurances of needle in haystack"
  },
  {
    "code": "def project_ranges(cb, msg, attributes):\n    if skip(cb, msg, attributes):\n        return msg\n    plot = get_cb_plot(cb)\n    x0, x1 = msg.get('x_range', (0, 1000))\n    y0, y1 = msg.get('y_range', (0, 1000))\n    extents = x0, y0, x1, y1\n    x0, y0, x1, y1 = project_extents(extents, plot.projection,\n                                     plot.current_frame.crs)\n    coords = {'x_range': (x0, x1), 'y_range': (y0, y1)}\n    return {k: v for k, v in coords.items() if k in attributes}",
    "docstring": "Projects ranges supplied by a callback."
  },
  {
    "code": "def prune_by_ngram_count_per_work(self, minimum=None, maximum=None,\n                                      label=None):\n        self._logger.info('Pruning results by n-gram count per work')\n        matches = self._matches\n        keep_ngrams = matches[constants.NGRAM_FIELDNAME].unique()\n        if label is not None:\n            matches = matches[matches[constants.LABEL_FIELDNAME] == label]\n        if minimum and maximum:\n            keep_ngrams = matches[\n                (matches[constants.COUNT_FIELDNAME] >= minimum) &\n                (matches[constants.COUNT_FIELDNAME] <= maximum)][\n                    constants.NGRAM_FIELDNAME].unique()\n        elif minimum:\n            keep_ngrams = matches[\n                matches[constants.COUNT_FIELDNAME] >= minimum][\n                    constants.NGRAM_FIELDNAME].unique()\n        elif maximum:\n            keep_ngrams = matches[\n                self._matches[constants.COUNT_FIELDNAME] <= maximum][\n                    constants.NGRAM_FIELDNAME].unique()\n        self._matches = self._matches[self._matches[\n            constants.NGRAM_FIELDNAME].isin(keep_ngrams)]",
    "docstring": "Removes results rows if the n-gram count for all works bearing that\n        n-gram is outside the range specified by `minimum` and\n        `maximum`.\n\n        That is, if a single witness of a single work has an n-gram\n        count that falls within the specified range, all result rows\n        for that n-gram are kept.\n\n        If `label` is specified, the works checked are restricted to\n        those associated with `label`.\n\n        :param minimum: minimum n-gram count\n        :type minimum: `int`\n        :param maximum: maximum n-gram count\n        :type maximum: `int`\n        :param label: optional label to restrict requirement to\n        :type label: `str`"
  },
  {
    "code": "def create_variable(ncfile, name, datatype, dimensions) -> None:\n    default = fillvalue if (datatype == 'f8') else None\n    try:\n        ncfile.createVariable(\n            name, datatype, dimensions=dimensions, fill_value=default)\n        ncfile[name].long_name = name\n    except BaseException:\n        objecttools.augment_excmessage(\n            'While trying to add variable `%s` with datatype `%s` '\n            'and dimensions `%s` to the NetCDF file `%s`'\n            % (name, datatype, dimensions, get_filepath(ncfile)))",
    "docstring": "Add a new variable with the given name, datatype, and dimensions\n    to the given NetCDF file.\n\n    Essentially, |create_variable| just calls the equally named method\n    of the NetCDF library, but adds information to possible error messages:\n\n    >>> from hydpy import TestIO\n    >>> from hydpy.core.netcdftools import netcdf4\n    >>> with TestIO():\n    ...     ncfile = netcdf4.Dataset('test.nc', 'w')\n    >>> from hydpy.core.netcdftools import create_variable\n    >>> try:\n    ...     create_variable(ncfile, 'var1', 'f8', ('dim1',))\n    ... except BaseException as exc:\n    ...     print(str(exc).strip('\"'))    # doctest: +ELLIPSIS\n    While trying to add variable `var1` with datatype `f8` and \\\ndimensions `('dim1',)` to the NetCDF file `test.nc`, the following error \\\noccurred: ...\n\n    >>> from hydpy.core.netcdftools import create_dimension\n    >>> create_dimension(ncfile, 'dim1', 5)\n    >>> create_variable(ncfile, 'var1', 'f8', ('dim1',))\n    >>> import numpy\n    >>> numpy.array(ncfile['var1'][:])\n    array([ nan,  nan,  nan,  nan,  nan])\n\n    >>> ncfile.close()"
  },
  {
    "code": "def do_set(self, params):\n        self.set(params.path, decoded(params.value), version=params.version)",
    "docstring": "\\x1b[1mNAME\\x1b[0m\n        set - Updates the znode's value\n\n\\x1b[1mSYNOPSIS\\x1b[0m\n        set <path> <value> [version]\n\n\\x1b[1mOPTIONS\\x1b[0m\n        * version: only update if version matches (default: -1)\n\n\\x1b[1mEXAMPLES\\x1b[0m\n        > set /foo 'bar'\n        > set /foo 'verybar' 3"
  },
  {
    "code": "def modify_user(self, username, data):\n        if 'password' in data:\n            char_set = string.ascii_letters + string.digits\n            data['pwd_salt'] = ''.join(random.choice(char_set) for x in range(8))\n            data['pwd_hash'] = self._gen_hash(data['password'], data['pwd_salt'])\n            del(data['password'])\n        sql = \"UPDATE user SET \"\n        sql += ', '.join(\"%s = ?\" % k for k in sorted(data))\n        sql += \" WHERE username = ?\"\n        vals = []\n        for k in sorted(data):\n            vals.append(data[k])\n        vals.append(username)\n        try:\n            self._db_curs.execute(sql, vals)\n            self._db_conn.commit()\n        except (sqlite3.OperationalError, sqlite3.IntegrityError) as error:\n            raise AuthError(error)",
    "docstring": "Modify user in SQLite database.\n\n            Since username is used as primary key and we only have a single\n            argument for it we can't modify the username right now."
  },
  {
    "code": "def _validate_int(name, value, limits=(), strip='%'):\n    comment = ''\n    try:\n        if isinstance(value, string_types):\n            value = value.strip(' ' + strip)\n        value = int(value)\n    except (TypeError, ValueError):\n        comment += '{0} must be an integer '.format(name)\n    else:\n        if len(limits) == 2:\n            if value < limits[0] or value > limits[1]:\n                comment += '{0} must be in the range [{1[0]}, {1[1]}] '.format(name, limits)\n    return value, comment",
    "docstring": "Validate the named integer within the supplied limits inclusive and\n    strip supplied unit characters"
  },
  {
    "code": "def api_run_get(run_id):\n    data = current_app.config[\"data\"]\n    run = data.get_run_dao().get(run_id)\n    records_total = 1 if run is not None else 0\n    if records_total == 0:\n        return Response(\n            render_template(\n                \"api/error.js\",\n                error_code=404,\n                error_message=\"Run %s not found.\" % run_id),\n            status=404,\n            mimetype=\"application/json\")\n    records_filtered = records_total\n    return Response(render_template(\"api/runs.js\", runs=[run], draw=1,\n                                    recordsTotal=records_total,\n                                    recordsFiltered=records_filtered,\n                                    full_object=True),\n                    mimetype=\"application/json\")",
    "docstring": "Return a single run as a JSON object."
  },
  {
    "code": "def start(self):\n        self.loop.run_until_complete(self._consumer.start())\n        self.loop.run_until_complete(self._producer.start())\n        self._consumer_task = self.loop.create_task(self._consume_event_callback())",
    "docstring": "This function starts the brokers interaction with the kafka stream"
  },
  {
    "code": "def _parse_model(topology, scope, model, inputs=None, outputs=None):\n    if inputs is None:\n        inputs = list()\n    if outputs is None:\n        outputs = list()\n    model_type = model.WhichOneof('Type')\n    if model_type in ['pipeline', 'pipelineClassifier', 'pipelineRegressor']:\n        _parse_pipeline_model(topology, scope, model, inputs, outputs)\n    elif model_type in ['neuralNetworkClassifier', 'neuralNetworkRegressor', 'neuralNetwork']:\n        _parse_neural_network_model(topology, scope, model, inputs, outputs)\n    else:\n        _parse_simple_model(topology, scope, model, inputs, outputs)",
    "docstring": "This is a delegate function of all top-level parsing functions. It does nothing but call a proper function\n    to parse the given model."
  },
  {
    "code": "def remove_all(self, items):\n        check_not_none(items, \"Value can't be None\")\n        data_items = []\n        for item in items:\n            check_not_none(item, \"Value can't be None\")\n            data_items.append(self._to_data(item))\n        return self._encode_invoke(list_compare_and_remove_all_codec, values=data_items)",
    "docstring": "Removes all of the elements that is present in the specified collection from this list.\n\n        :param items: (Collection), the specified collection.\n        :return: (bool), ``true`` if this list changed as a result of the call."
  },
  {
    "code": "def _init(self):\n        self.tn = telnetlib.Telnet(self.ip, self.port)\n        self.tn.read_until('User Name')\n        self.tn.write('apc\\r\\n')\n        self.tn.read_until('Password')\n        self.tn.write('apc\\r\\n')\n        self.until_done()",
    "docstring": "Initialize the telnet connection"
  },
  {
    "code": "def evaluate(self, x, y, flux, x_0, y_0, sigma):\n        return (flux / 4 *\n                ((self._erf((x - x_0 + 0.5) / (np.sqrt(2) * sigma)) -\n                  self._erf((x - x_0 - 0.5) / (np.sqrt(2) * sigma))) *\n                 (self._erf((y - y_0 + 0.5) / (np.sqrt(2) * sigma)) -\n                  self._erf((y - y_0 - 0.5) / (np.sqrt(2) * sigma)))))",
    "docstring": "Model function Gaussian PSF model."
  },
  {
    "code": "def process_log_event(event, context):\n    init()\n    serialized = event['awslogs'].pop('data')\n    data = json.loads(zlib.decompress(\n        base64.b64decode(serialized), 16 + zlib.MAX_WBITS))\n    msg = get_sentry_message(config, data)\n    if msg is None:\n        return\n    if config['sentry_dsn']:\n        send_sentry_message(config['sentry_dsn'], msg)\n    elif config['sentry_sqs']:\n        sqs.send_message(\n            QueueUrl=config['sentry_sqs'])",
    "docstring": "Lambda Entrypoint - Log Subscriber\n\n    Format log events and relay to sentry (direct or sqs)"
  },
  {
    "code": "def endure_multi(self, keys, persist_to=-1, replicate_to=-1,\n                     timeout=5.0, interval=0.010, check_removed=False):\n        return _Base.endure_multi(self, keys, persist_to=persist_to,\n                                  replicate_to=replicate_to,\n                                  timeout=timeout, interval=interval,\n                                  check_removed=check_removed)",
    "docstring": "Check durability requirements for multiple keys\n\n        :param keys: The keys to check\n\n        The type of keys may be one of the following:\n            * Sequence of keys\n            * A :class:`~couchbase.result.MultiResult` object\n            * A ``dict`` with CAS values as the dictionary value\n            * A sequence of :class:`~couchbase.result.Result` objects\n\n        :return: A :class:`~.MultiResult` object\n            of :class:`~.OperationResult` items.\n\n        .. seealso:: :meth:`endure`"
  },
  {
    "code": "def create_storage(self, size=10, tier='maxiops', title='Storage disk', zone='fi-hel1', backup_rule={}):\n        body = {\n            'storage': {\n                'size': size,\n                'tier': tier,\n                'title': title,\n                'zone': zone,\n                'backup_rule': backup_rule\n            }\n        }\n        res = self.post_request('/storage', body)\n        return Storage(cloud_manager=self, **res['storage'])",
    "docstring": "Create a Storage object. Returns an object based on the API's response."
  },
  {
    "code": "def pix2sky_vec(self, pixel, r, theta):\n        ra1, dec1 = self.pix2sky(pixel)\n        x, y = pixel\n        a = [x + r * np.cos(np.radians(theta)),\n             y + r * np.sin(np.radians(theta))]\n        locations = self.pix2sky(a)\n        ra2, dec2 = locations\n        a = gcd(ra1, dec1, ra2, dec2)\n        pa = bear(ra1, dec1, ra2, dec2)\n        return ra1, dec1, a, pa",
    "docstring": "Given and input position and vector in pixel coordinates, calculate\n        the equivalent position and vector in sky coordinates.\n\n        Parameters\n        ----------\n        pixel : (int,int)\n            origin of vector in pixel coordinates\n        r : float\n            magnitude of vector in pixels\n        theta : float\n            angle of vector in degrees\n\n        Returns\n        -------\n        ra, dec : float\n            The (ra, dec) of the origin point (degrees).\n        r, pa : float\n            The magnitude and position angle of the vector (degrees)."
  },
  {
    "code": "def plot_contour_labels(self, new_fig=True):\n        timestamps = []\n        pitch = []\n        if new_fig:\n            p.figure()\n        for interval, contours in self.contour_labels.items():\n            for contour in contours:\n                x = self.pitch_obj.timestamps[contour[0]:contour[1]]\n                y = [interval]*len(x)\n                timestamps.extend(x)\n                pitch.extend(y)\n        data = np.array([timestamps, pitch]).T\n        data = np.array(sorted(data, key=lambda xx: xx[0]))\n        p.plot(data[:, 0], data[:, 1], 'g-')",
    "docstring": "Plots the labelled contours!"
  },
  {
    "code": "def json_exception(context, request):\n    request.response.status = context.code\n    return {'error': context._status, 'messages': context.message}",
    "docstring": "Always return json content in the body of Exceptions to xhr requests."
  },
  {
    "code": "def _read(self, command, future):\n        response = self._reader.gets()\n        if response is not False:\n            if isinstance(response, hiredis.ReplyError):\n                if response.args[0].startswith('MOVED '):\n                    self._on_cluster_data_moved(response.args[0], command,\n                                                future)\n                elif response.args[0].startswith('READONLY '):\n                    self._on_read_only_error(command, future)\n                else:\n                    future.set_exception(exceptions.RedisError(response))\n            elif command.callback is not None:\n                future.set_result(command.callback(response))\n            elif command.expectation is not None:\n                self._eval_expectation(command, response, future)\n            else:\n                future.set_result(response)\n        else:\n            def on_data(data):\n                self._reader.feed(data)\n                self._read(command, future)\n            command.connection.read(on_data)",
    "docstring": "Invoked when a command is executed to read and parse its results.\n        It will loop on the IOLoop until the response is complete and then\n        set the value of the response in the execution future.\n\n        :param command: The command that was being executed\n        :type command: tredis.client.Command\n        :param future: The execution future\n        :type future: tornado.concurrent.Future"
  },
  {
    "code": "def _encode_batched_write_command(\n        namespace, operation, command, docs, check_keys, opts, ctx):\n    buf = StringIO()\n    to_send, _ = _batched_write_command_impl(\n        namespace, operation, command, docs, check_keys, opts, ctx, buf)\n    return buf.getvalue(), to_send",
    "docstring": "Encode the next batched insert, update, or delete command."
  },
  {
    "code": "def _parse_show_output(cmd_ret):\n    parsed_data = dict()\n    list_key = None\n    for line in cmd_ret.splitlines():\n        if not line.strip():\n            continue\n        if not salt.utils.stringutils.contains_whitespace(line[0]):\n            list_key = None\n        if list_key:\n            list_value = _convert_to_closest_type(line)\n            parsed_data.setdefault(list_key, []).append(list_value)\n            continue\n        items = [item.strip() for item in line.split(':', 1)]\n        key = items[0].lower()\n        key = ' '.join(key.split()).replace(' ', '_')\n        list_key = key\n        try:\n            value = items[1]\n        except IndexError:\n            log.debug('Skipping line: %s', line)\n            continue\n        if value:\n            parsed_data[key] = _convert_to_closest_type(value)\n    return _convert_parsed_show_output(parsed_data=parsed_data)",
    "docstring": "Parse the output of an aptly show command.\n\n    :param str cmd_ret: The text of the command output that needs to be parsed.\n\n    :return: A dictionary containing the configuration data.\n    :rtype: dict"
  },
  {
    "code": "def set_secondary_state(self, value):\n        if value not in (_STATE_RUNNING, _STATE_SHUTDOWN, _STATE_FORCED_SHUTDOWN):\n            raise ValueError(\n                \"State {!r} is invalid - needs to be one of _STATE_RUNNING, _STATE_SHUTDOWN, or _STATE_FORCED_SHUTDOWN\".format(\n                    value)\n                )\n        if self.manager is None:\n            raise RuntimeError(\"Manager not started\")\n        self.manager.set_state(value)",
    "docstring": "Sets the value for 'secondary_state'."
  },
  {
    "code": "def wait(value, must_be_child=False):\n    current = getcurrent()\n    parent = current.parent\n    if must_be_child and not parent:\n        raise MustBeInChildGreenlet('Cannot wait on main greenlet')\n    return parent.switch(value) if parent else value",
    "docstring": "Wait for a possible asynchronous value to complete."
  },
  {
    "code": "def new_file(self, path, track_idx, copy_file=False):\n        new_file_idx = track_idx\n        new_file_path = os.path.abspath(path)\n        if new_file_idx in self._tracks.keys():\n            new_file_idx = naming.index_name_if_in_list(new_file_idx, self._tracks.keys())\n        if copy_file:\n            if not os.path.isdir(self.path):\n                raise ValueError('To copy file the dataset needs to have a path.')\n            __, ext = os.path.splitext(path)\n            new_file_folder = os.path.join(self.path, DEFAULT_FILE_SUBDIR)\n            new_file_path = os.path.join(new_file_folder, '{}{}'.format(new_file_idx, ext))\n            os.makedirs(new_file_folder, exist_ok=True)\n            shutil.copy(path, new_file_path)\n        new_file = tracks.FileTrack(new_file_idx, new_file_path)\n        self._tracks[new_file_idx] = new_file\n        return new_file",
    "docstring": "Adds a new audio file to the corpus with the given data.\n\n        Parameters:\n            path (str): Path of the file to add.\n            track_idx (str): The id to associate the file-track with.\n            copy_file (bool): If True the file is copied to the data set folder, otherwise the given\n                              path is used directly.\n\n        Returns:\n            FileTrack: The newly added file."
  },
  {
    "code": "def merge(self, others, merge_conditions, common_ancestor=None):\n        merging_occurred = False\n        for o in others:\n            for region_id, region in o._regions.items():\n                if region_id in self._regions:\n                    merging_occurred |= self._regions[region_id].merge(\n                        [region], merge_conditions, common_ancestor=common_ancestor\n                    )\n                else:\n                    merging_occurred = True\n                    self._regions[region_id] = region\n        return merging_occurred",
    "docstring": "Merge this guy with another SimAbstractMemory instance"
  },
  {
    "code": "def detect_complexity(bam_in, genome, out):\n    if not genome:\n        logger.info(\"No genome given. skipping.\")\n        return None\n    out_file = op.join(out, op.basename(bam_in) + \"_cov.tsv\")\n    if file_exists(out_file):\n        return None\n    fai = genome + \".fai\"\n    cov = pybedtools.BedTool(bam_in).genome_coverage(g=fai, max=1)\n    cov.saveas(out_file)\n    total = 0\n    for region in cov:\n        if region[0] == \"genome\" and int(region[1]) != 0:\n            total += float(region[4])\n    logger.info(\"Total genome with sequences: %s \" % total)",
    "docstring": "genome coverage of small RNA"
  },
  {
    "code": "def write_length_and_key(fp, value):\n    written = write_fmt(fp, 'I', 0 if value in _TERMS else len(value))\n    written += write_bytes(fp, value)\n    return written",
    "docstring": "Helper to write descriptor key."
  },
  {
    "code": "def sorted_product_set(array_a, array_b):\n  return np.sort(\n      np.concatenate(\n          [array_a[i] * array_b for i in xrange(len(array_a))], axis=0)\n  )[::-1]",
    "docstring": "Compute the product set of array_a and array_b and sort it."
  },
  {
    "code": "def upload(target):\n    log.info(\"Uploading to pypi server <33>{}\".format(target))\n    with conf.within_proj_dir():\n        shell.run('python setup.py sdist register -r \"{}\"'.format(target))\n        shell.run('python setup.py sdist upload -r \"{}\"'.format(target))",
    "docstring": "Upload the release to a pypi server.\n\n    TODO: Make sure the git directory is clean before allowing a release.\n\n    Args:\n        target (str):\n            pypi target as defined in ~/.pypirc"
  },
  {
    "code": "def generate_checks(fact):\n    yield TypeCheck(type(fact))\n    fact_captured = False\n    for key, value in fact.items():\n        if (isinstance(key, str)\n                and key.startswith('__')\n                and key.endswith('__')):\n            if key == '__bind__':\n                yield FactCapture(value)\n                fact_captured = True\n            else:\n                yield FeatureCheck(key, value)\n        else:\n            yield FeatureCheck(key, value)\n    if not fact_captured:\n        yield FactCapture(\"__pattern_%s__\" % id(fact))",
    "docstring": "Given a fact, generate a list of Check objects for checking it."
  },
  {
    "code": "def persistent_load(self, pid):\n        if len(pid) == 2:\n            type_tag, filename = pid\n            abs_path = _os.path.join(self.gl_temp_storage_path, filename)\n            return  _get_gl_object_from_persistent_id(type_tag, abs_path)\n        else:\n            type_tag, filename, object_id = pid\n            if object_id in self.gl_object_memo:\n                return self.gl_object_memo[object_id]\n            else:\n                abs_path = _os.path.join(self.gl_temp_storage_path, filename)\n                obj = _get_gl_object_from_persistent_id(type_tag, abs_path)\n                self.gl_object_memo[object_id] = obj\n                return obj",
    "docstring": "Reconstruct a GLC object using the persistent ID.\n\n        This method should not be used externally. It is required by the unpickler super class.\n\n        Parameters\n        ----------\n        pid      : The persistent ID used in pickle file to save the GLC object.\n\n        Returns\n        ----------\n        The GLC object."
  },
  {
    "code": "def _make_context(context=None):\n    namespace = {'db': db, 'session': db.session}\n    namespace.update(_iter_context())\n    if context is not None:\n        namespace.update(context)\n    return namespace",
    "docstring": "Create the namespace of items already pre-imported when using shell.\n\n    Accepts a dict with the desired namespace as the key, and the object as the\n    value."
  },
  {
    "code": "def get(self):\n        return EngagementContextContext(\n            self._version,\n            flow_sid=self._solution['flow_sid'],\n            engagement_sid=self._solution['engagement_sid'],\n        )",
    "docstring": "Constructs a EngagementContextContext\n\n        :returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext\n        :rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext"
  },
  {
    "code": "def format_BLB():\r\n    rc(\"figure\", facecolor=\"white\")\r\n    rc('font', family = 'serif', size=10)\n    rc('xtick', labelsize=10)\r\n    rc('ytick', labelsize=10)\r\n    rc('axes', linewidth=1)\r\n    rc('xtick.major', size=4, width=1)\r\n    rc('xtick.minor', size=2, width=1)\r\n    rc('ytick.major', size=4, width=1)\r\n    rc('ytick.minor', size=2, width=1)",
    "docstring": "Sets some formatting options in Matplotlib."
  },
  {
    "code": "def described_as(self, description, *args):\n        if len(args):\n            description = description.format(*args)\n        self.description = description\n        return self",
    "docstring": "Specify a custom message for the matcher"
  },
  {
    "code": "def filter_by_device_owner(query, device_owners=None):\n    port_model = models_v2.Port\n    if not device_owners:\n        device_owners = utils.SUPPORTED_DEVICE_OWNERS\n    supported_device_owner_filter = [\n        port_model.device_owner.ilike('%s%%' % owner)\n        for owner in device_owners]\n    unsupported_device_owner_filter = [\n        port_model.device_owner.notilike('%s%%' % owner)\n        for owner in utils.UNSUPPORTED_DEVICE_OWNERS]\n    query = (query\n             .filter(\n                 and_(*unsupported_device_owner_filter),\n                 or_(*supported_device_owner_filter)))\n    return query",
    "docstring": "Filter ports by device_owner\n\n    Either filter using specified device_owner or using the list of all\n    device_owners supported and unsupported by the arista ML2 plugin"
  },
  {
    "code": "def _order_params(self, data):\n        has_signature = False\n        params = []\n        for key, value in data.items():\n            if key == 'signature':\n                has_signature = True\n            else:\n                params.append((key, value))\n        params.sort(key=itemgetter(0))\n        if has_signature:\n            params.append(('signature', data['signature']))\n        return params",
    "docstring": "Convert params to list with signature as last element\n\n        :param data:\n        :return:"
  },
  {
    "code": "def dupstack(newtask):\n    stack = s_task.varget('provstack')\n    s_task.varset('provstack', stack.copy(), newtask)",
    "docstring": "Duplicate the current provenance stack onto another task"
  },
  {
    "code": "def get_model(app_dot_model):\n    try:\n        app, model = app_dot_model.split('.')\n    except ValueError:\n        msg = (f'Passed in value \\'{app_dot_model}\\' was not in the format '\n               '`<app_name>.<model_name>`.')\n        raise ValueError(msg)\n    return apps.get_app_config(app).get_model(model)",
    "docstring": "Returns Django model class corresponding to passed-in `app_dot_model`\n    string. This is helpful for preventing circular-import errors in a Django\n    project.\n\n    Positional Arguments:\n    =====================\n    - `app_dot_model`: Django's `<app_name>.<model_name>` syntax. For example,\n                       the default Django User model would be `auth.User`,\n                       where `auth` is the app and `User` is the model."
  },
  {
    "code": "def aliasstr(self):\n\t\treturn ', '.join(repr(self.ns + x) for x in self.aliases)",
    "docstring": "Concatenate the aliases tuple into a string."
  },
  {
    "code": "def make_request_fn():\n  if FLAGS.cloud_mlengine_model_name:\n    request_fn = serving_utils.make_cloud_mlengine_request_fn(\n        credentials=GoogleCredentials.get_application_default(),\n        model_name=FLAGS.cloud_mlengine_model_name,\n        version=FLAGS.cloud_mlengine_model_version)\n  else:\n    request_fn = serving_utils.make_grpc_request_fn(\n        servable_name=FLAGS.servable_name,\n        server=FLAGS.server,\n        timeout_secs=FLAGS.timeout_secs)\n  return request_fn",
    "docstring": "Returns a request function."
  },
  {
    "code": "def _randomString():\n    return ''.join(\n        random.choice(string.ascii_uppercase + string.digits)\n        for x in range(10))",
    "docstring": "Random string for message signing"
  },
  {
    "code": "def save(self):\n        try:\n            self.node.move_to(self.cleaned_data['target'],\n                              self.cleaned_data['position'])\n            return self.node\n        except InvalidMove, e:\n            self.errors[NON_FIELD_ERRORS] = ErrorList(e)\n            raise",
    "docstring": "Attempts to move the node using the selected target and\n        position.\n\n        If an invalid move is attempted, the related error message will\n        be added to the form's non-field errors and the error will be\n        re-raised. Callers should attempt to catch ``InvalidNode`` to\n        redisplay the form with the error, should it occur."
  },
  {
    "code": "def _onOffset(self, dt, businesshours):\n        if self.n >= 0:\n            op = self._prev_opening_time(dt)\n        else:\n            op = self._next_opening_time(dt)\n        span = (dt - op).total_seconds()\n        if span <= businesshours:\n            return True\n        else:\n            return False",
    "docstring": "Slight speedups using calculated values."
  },
  {
    "code": "def OnTogglePlay(self, event):\n        if self.player.get_state() == vlc.State.Playing:\n            self.player.pause()\n        else:\n            self.player.play()\n        event.Skip()",
    "docstring": "Toggles the video status between play and hold"
  },
  {
    "code": "def add_item(self, item):\n        self.beginInsertRows(QtCore.QModelIndex(),\n                             self.rowCount(),\n                             self.rowCount())\n        item[\"parent\"] = self\n        item = Item(**item)\n        self.items.append(item)\n        self.endInsertRows()\n        item.__datachanged__.connect(self._dataChanged)\n        return item",
    "docstring": "Add new item to model\n\n        Each keyword argument is passed to the :func:Item\n        factory function."
  },
  {
    "code": "def read_packets(self):\n        while self.running:\n            packet_length = self.client.recv(2)\n            if len(packet_length) < 2:\n                self.stop()\n                continue\n            packet_length = struct.unpack(\"<h\", packet_length)[0] - 2\n            data = self.client.recv(packet_length)\n            packno = data[0]\n            try:\n                parser = \"Packet\" + format(packno, 'x').upper() + \"Parser\"\n                packet_class = getattr(packets, parser)\n                packet_class().parse(self.world, self.player, data, self._evman)\n            except AttributeError as e:\n                pass\n            if packno == 2:\n                self.stop()\n                continue",
    "docstring": "Read packets from the socket and parse them"
  },
  {
    "code": "def _lazy_listen(self):\n        if all([\n            self._loop,\n            not self.running,\n            self._subscriptions or (self._pending and not self._pending.empty()),\n        ]):\n            self._task = self._loop.create_task(self._listen())",
    "docstring": "Ensures that the listener task only runs when actually needed.\n        This function is a no-op if any of the preconditions is not met.\n\n        Preconditions are:\n        * The application is running (self._loop is set)\n        * The task is not already running\n        * There are subscriptions: either pending, or active"
  },
  {
    "code": "def _write_gen_model_stats(self, iteration:int)->None:\n        \"Writes gradient statistics for generator to Tensorboard.\"\n        generator = self.learn.gan_trainer.generator\n        self.stats_writer.write(model=generator, iteration=iteration, tbwriter=self.tbwriter, name='gen_model_stats')\n        self.gen_stats_updated = True",
    "docstring": "Writes gradient statistics for generator to Tensorboard."
  },
  {
    "code": "def formatall(self, *args, **kargs):\n        \" Add-on method for fits returned by chained_nonlinear_fit. \"\n        ans = ''\n        for x in self.chained_fits:\n            ans += 10 * '=' + ' ' + str(x) + '\\n'\n            ans += self.chained_fits[x].format(*args, **kargs)\n            ans += '\\n'\n        return ans[:-1]",
    "docstring": "Add-on method for fits returned by chained_nonlinear_fit."
  },
  {
    "code": "def _timeout_to_float(self, timeout):\n        if timeout is not None:\n            try:\n                timeout_float = float(timeout)\n            except ValueError:\n                raise ValueError(\n                    'timeout_sec must be a valid number or None. timeout=\"{}\"'.format(\n                        timeout\n                    )\n                )\n            if timeout_float:\n                return timeout_float",
    "docstring": "Convert timeout to float.\n\n        Return None if timeout is None, 0 or 0.0. timeout=None disables timeouts in\n        Requests."
  },
  {
    "code": "def get_features(cls, entry):\n        features = []\n        for feature in entry.iterfind(\"./feature\"):\n            feature_dict = {\n                'description': feature.attrib.get('description'),\n                'type_': feature.attrib['type'],\n                'identifier': feature.attrib.get('id')\n            }\n            features.append(models.Feature(**feature_dict))\n        return features",
    "docstring": "get list of `models.Feature` from XML node entry\n\n        :param entry: XML node entry\n        :return: list of :class:`pyuniprot.manager.models.Feature`"
  },
  {
    "code": "def parts(self, *args, **kwargs):\n        return self._client.parts(*args, activity=self.id, **kwargs)",
    "docstring": "Retrieve parts belonging to this activity.\n\n        Without any arguments it retrieves the Instances related to this task only.\n\n        This call only returns the configured properties in an activity. So properties that are not configured\n        are not in the returned parts.\n\n        See :class:`pykechain.Client.parts` for additional available parameters.\n\n        Example\n        -------\n        >>> task = project.activity('Specify Wheel Diameter')\n        >>> parts = task.parts()\n\n        To retrieve the models only.\n        >>> parts = task.parts(category=Category.MODEL)"
  },
  {
    "code": "def setEditorData(self, spinBox, index):\n        if index.isValid():\n            value = index.model().data(index, QtCore.Qt.EditRole)\n            spinBox.setValue(value)",
    "docstring": "Sets the data to be displayed and edited by the editor from the data model item specified by the model index.\n\n        Args:\n            spinBox (BigIntSpinbox): editor widget.\n            index (QModelIndex): model data index."
  },
  {
    "code": "def LockRetryWrapper(self,\n                       subject,\n                       retrywrap_timeout=1,\n                       retrywrap_max_timeout=10,\n                       blocking=True,\n                       lease_time=None):\n    timeout = 0\n    while timeout < retrywrap_max_timeout:\n      try:\n        return self.DBSubjectLock(subject, lease_time=lease_time)\n      except DBSubjectLockError:\n        if not blocking:\n          raise\n        stats_collector_instance.Get().IncrementCounter(\"datastore_retries\")\n        time.sleep(retrywrap_timeout)\n        timeout += retrywrap_timeout\n    raise DBSubjectLockError(\"Retry number exceeded.\")",
    "docstring": "Retry a DBSubjectLock until it succeeds.\n\n    Args:\n      subject: The subject which the lock applies to.\n      retrywrap_timeout: How long to wait before retrying the lock.\n      retrywrap_max_timeout: The maximum time to wait for a retry until we\n        raise.\n      blocking: If False, raise on first lock failure.\n      lease_time: lock lease time in seconds.\n\n    Returns:\n      The DBSubjectLock object\n\n    Raises:\n      DBSubjectLockError: If the maximum retry count has been reached."
  },
  {
    "code": "def load_plugins(plugin_dir: str, module_prefix: str) -> int:\n    count = 0\n    for name in os.listdir(plugin_dir):\n        path = os.path.join(plugin_dir, name)\n        if os.path.isfile(path) and \\\n                (name.startswith('_') or not name.endswith('.py')):\n            continue\n        if os.path.isdir(path) and \\\n                (name.startswith('_') or not os.path.exists(\n                    os.path.join(path, '__init__.py'))):\n            continue\n        m = re.match(r'([_A-Z0-9a-z]+)(.py)?', name)\n        if not m:\n            continue\n        if load_plugin(f'{module_prefix}.{m.group(1)}'):\n            count += 1\n    return count",
    "docstring": "Find all non-hidden modules or packages in a given directory,\n    and import them with the given module prefix.\n\n    :param plugin_dir: plugin directory to search\n    :param module_prefix: module prefix used while importing\n    :return: number of plugins successfully loaded"
  },
  {
    "code": "def get_text(nodelist):\n    value = []\n    for node in nodelist:\n        if node.nodeType == node.TEXT_NODE:\n            value.append(node.data)\n    return ''.join(value)",
    "docstring": "Get the value from a text node."
  },
  {
    "code": "def set_idle_priority(pid=None):\n    if pid is None:\n        pid = os.getpid()\n    lib.ioprio_set(\n        lib.IOPRIO_WHO_PROCESS, pid,\n        lib.IOPRIO_PRIO_VALUE(lib.IOPRIO_CLASS_IDLE, 0))",
    "docstring": "Puts a process in the idle io priority class.\n\n    If pid is omitted, applies to the current process."
  },
  {
    "code": "def merge_context(self, src=None):\n        if src is None:\n            return\n        if self._ctx.start_ts == 0:\n            self._ctx.start_ts = src.start_ts\n        elif self._ctx.start_ts != src.start_ts:\n            raise Exception('StartTs mismatch')\n        self._ctx.keys.extend(src.keys)\n        self._ctx.preds.extend(src.preds)",
    "docstring": "Merges context from this instance with src."
  },
  {
    "code": "def draw_screen(self, size):\n        self.tui.clear()\n        canvas = self.top.render(size, focus=True)\n        self.tui.draw_screen(size, canvas)",
    "docstring": "Render curses screen"
  },
  {
    "code": "def get_python():\n    if sys.platform == 'win32':\n        python = path.join(VE_ROOT, 'Scripts', 'python.exe')\n    else:\n        python = path.join(VE_ROOT, 'bin', 'python')\n    return python",
    "docstring": "Determine the path to the virtualenv python"
  },
  {
    "code": "def add(self, resource):\n        if isinstance(resource, collections.Iterable):\n            for r in resource:\n                self.add_if_changed(r)\n        else:\n            self.add_if_changed(resource)",
    "docstring": "Add a resource change or an iterable collection of them.\n\n        Allows multiple resource_change objects for the same\n        resource (ie. URI) and preserves the order of addition."
  },
  {
    "code": "def build_publish_pkt(self, mid, topic, payload, qos, retain, dup):\n        pkt = MqttPkt()\n        payloadlen = len(payload)\n        packetlen = 2 + len(topic) + payloadlen\n        if qos > 0:\n            packetlen += 2\n        pkt.mid = mid\n        pkt.command = NC.CMD_PUBLISH | ((dup & 0x1) << 3) | (qos << 1) | retain\n        pkt.remaining_length = packetlen\n        ret = pkt.alloc()\n        if ret != NC.ERR_SUCCESS:\n            return ret, None\n        pkt.write_string(topic)\n        if qos > 0:\n            pkt.write_uint16(mid)\n        if payloadlen > 0:\n            pkt.write_bytes(payload, payloadlen)\n        return NC.ERR_SUCCESS, pkt",
    "docstring": "Build PUBLISH packet."
  },
  {
    "code": "def from_lal(cls, lalts, copy=True):\n        from ..utils.lal import from_lal_unit\n        try:\n            unit = from_lal_unit(lalts.sampleUnits)\n        except (TypeError, ValueError) as exc:\n            warnings.warn(\"%s, defaulting to 'dimensionless'\" % str(exc))\n            unit = None\n        channel = Channel(lalts.name, sample_rate=1/lalts.deltaT, unit=unit,\n                          dtype=lalts.data.data.dtype)\n        out = cls(lalts.data.data, channel=channel, t0=lalts.epoch,\n                  dt=lalts.deltaT, unit=unit, name=lalts.name, copy=False)\n        if copy:\n            return out.copy()\n        return out",
    "docstring": "Generate a new TimeSeries from a LAL TimeSeries of any type."
  },
  {
    "code": "def _sortValue_isMonospace(font):\n    if font.info.postscriptIsFixedPitch:\n        return 0\n    if not len(font):\n        return 1\n    testWidth = None\n    for glyph in font:\n        if testWidth is None:\n            testWidth = glyph.width\n        else:\n            if testWidth != glyph.width:\n                return 1\n    return 0",
    "docstring": "Returns 0 if the font is monospace.\n    Returns 1 if the font is not monospace."
  },
  {
    "code": "def contains_group(store, path=None):\n    path = normalize_storage_path(path)\n    prefix = _path_to_prefix(path)\n    key = prefix + group_meta_key\n    return key in store",
    "docstring": "Return True if the store contains a group at the given logical path."
  },
  {
    "code": "def _set_other(self):\n        if self.dst.style['in'] == 'numpydoc':\n            if self.docs['in']['raw'] is not None:\n                self.docs['out']['post'] = self.dst.numpydoc.get_raw_not_managed(self.docs['in']['raw'])\n            elif 'post' not in self.docs['out'] or self.docs['out']['post'] is None:\n                self.docs['out']['post'] = ''",
    "docstring": "Sets other specific sections"
  },
  {
    "code": "def select_eep(self, rorg_func, rorg_type, direction=None, command=None):\n        self.rorg_func = rorg_func\n        self.rorg_type = rorg_type\n        self._profile = self.eep.find_profile(self._bit_data, self.rorg, rorg_func, rorg_type, direction, command)\n        return self._profile is not None",
    "docstring": "Set EEP based on FUNC and TYPE"
  },
  {
    "code": "def rewind(self, count):\n        if count > self._index:\n            raise ValueError(\"Can't rewind past beginning!\")\n        self._index -= count",
    "docstring": "Rewind index."
  },
  {
    "code": "def minusExtras(self):\n        assert self.isOpen()\n        trimmed = self.clone()\n        equals = {}\n        for test in trimmed.tests:\n            if test.op == '=':\n                equals[test.property] = test.value\n        extras = []\n        for (i, test) in enumerate(trimmed.tests):\n            if test.op == '!=' and equals.has_key(test.property) and equals[test.property] != test.value:\n                extras.append(i)\n        while extras:\n            trimmed.tests.pop(extras.pop())\n        return trimmed",
    "docstring": "Return a new Filter that's equal to this one,\n            without extra terms that don't add meaning."
  },
  {
    "code": "def func_dump(func):\n    code = marshal.dumps(func.__code__).decode('raw_unicode_escape')\n    defaults = func.__defaults__\n    if func.__closure__:\n        closure = tuple(c.cell_contents for c in func.__closure__)\n    else:\n        closure = None\n    return code, defaults, closure",
    "docstring": "Serialize user defined function."
  },
  {
    "code": "def save_to_mat_file(self, parameter_space,\n                         result_parsing_function,\n                         filename, runs):\n        for key in parameter_space:\n            if not isinstance(parameter_space[key], list):\n                parameter_space[key] = [parameter_space[key]]\n        dimension_labels = [{key: str(parameter_space[key])} for key in\n                            parameter_space.keys() if len(parameter_space[key])\n                            > 1] + [{'runs': range(runs)}]\n        return savemat(\n            filename,\n            {'results':\n             self.get_results_as_numpy_array(parameter_space,\n                                             result_parsing_function,\n                                             runs=runs),\n             'dimension_labels': dimension_labels})",
    "docstring": "Return the results relative to the desired parameter space in the form\n        of a .mat file.\n\n        Args:\n            parameter_space (dict): dictionary containing\n                parameter/list-of-values pairs.\n            result_parsing_function (function): user-defined function, taking a\n                result dictionary as argument, that can be used to parse the\n                result files and return a list of values.\n            filename (path): name of output .mat file.\n            runs (int): number of runs to gather for each parameter\n                combination."
  },
  {
    "code": "def compute_err(self, solution_y, coefficients):\n        error = 0\n        for modeled, expected in zip(solution_y, self.expected_values):\n            error += abs(modeled - expected)\n        if any([c < 0 for c in coefficients]):\n            error *= 1.5\n        return error",
    "docstring": "Return an error value by finding the absolute difference for each\n        element in a list of solution-generated y-values versus expected values.\n\n        Compounds error by 50% for each negative coefficient in the solution.\n\n        solution_y:  list of y-values produced by a solution\n        coefficients:  list of polynomial coefficients represented by the solution\n\n        return:  error value"
  },
  {
    "code": "def set_probe_position(self, new_probe_position):\n        if new_probe_position is not None:\n            new_probe_position = Geometry.FloatPoint.make(new_probe_position)\n            new_probe_position = Geometry.FloatPoint(y=max(min(new_probe_position.y, 1.0), 0.0),\n                                                     x=max(min(new_probe_position.x, 1.0), 0.0))\n        old_probe_position = self.__probe_position_value.value\n        if ((old_probe_position is None) != (new_probe_position is None)) or (old_probe_position != new_probe_position):\n            self.__probe_position_value.value = new_probe_position\n        self.probe_state_changed_event.fire(self.probe_state, self.probe_position)",
    "docstring": "Set the probe position, in normalized coordinates with origin at top left."
  },
  {
    "code": "def get_info_consistent(self, ndim):\n        if ndim > len(self.spacing):\n            spacing = self.spacing + (1.0, ) * (ndim - len(self.spacing))\n        else:\n            spacing = self.spacing[:ndim]\n        if ndim > len(self.offset):\n            offset = self.offset + (0.0, ) * (ndim - len(self.offset))\n        else:\n            offset = self.offset[:ndim]\n        if ndim > self.direction.shape[0]:\n            direction = np.identity(ndim)\n            direction[:self.direction.shape[0], :self.direction.shape[0]] = self.direction\n        else:\n            direction = self.direction[:ndim, :ndim]\n        return spacing, offset, direction",
    "docstring": "Returns the main meta-data information adapted to the supplied\n        image dimensionality.\n\n        It will try to resolve inconsistencies and other conflicts,\n        altering the information avilable int he most plausible way.\n\n        Parameters\n        ----------\n        ndim : int\n            image's dimensionality\n        \n        Returns\n        -------\n        spacing : tuple of floats\n        offset : tuple of floats\n        direction : ndarray"
  },
  {
    "code": "def clean_new_password2(self):\n        password1 = self.cleaned_data.get('new_password1')\n        password2 = self.cleaned_data.get('new_password2')\n        try:\n            directory = APPLICATION.default_account_store_mapping.account_store\n            directory.password_policy.strength.validate_password(password2)\n        except ValueError as e:\n            raise forms.ValidationError(str(e))\n        if password1 and password2:\n            if password1 != password2:\n                raise forms.ValidationError(\"The two passwords didn't match.\")\n        return password2",
    "docstring": "Check if passwords match and are valid."
  },
  {
    "code": "def stemming_processor(words):\n    stem = PorterStemmer().stem\n    for word in words:\n        word = stem(word, 0, len(word)-1)\n        yield word",
    "docstring": "Porter Stemmer word processor"
  },
  {
    "code": "def ray_triangle_candidates(ray_origins,\n                            ray_directions,\n                            tree):\n    ray_bounding = ray_bounds(ray_origins=ray_origins,\n                              ray_directions=ray_directions,\n                              bounds=tree.bounds)\n    ray_candidates = [[]] * len(ray_origins)\n    ray_id = [[]] * len(ray_origins)\n    for i, bounds in enumerate(ray_bounding):\n        ray_candidates[i] = np.array(list(tree.intersection(bounds)),\n                                     dtype=np.int)\n        ray_id[i] = np.ones(len(ray_candidates[i]), dtype=np.int) * i\n    ray_id = np.hstack(ray_id)\n    ray_candidates = np.hstack(ray_candidates)\n    return ray_candidates, ray_id",
    "docstring": "Do broad- phase search for triangles that the rays\n    may intersect.\n\n    Does this by creating a bounding box for the ray as it\n    passes through the volume occupied by the tree\n\n    Parameters\n    ------------\n    ray_origins:      (m,3) float, ray origin points\n    ray_directions:   (m,3) float, ray direction vectors\n    tree:             rtree object, contains AABB of each triangle\n\n    Returns\n    ----------\n    ray_candidates: (n,) int, triangle indexes\n    ray_id:         (n,) int, corresponding ray index for a triangle candidate"
  },
  {
    "code": "def generate_uuid4(self) -> list:\n        hexstr = randhex(30)\n        uuid4 = [\n            hexstr[:8],\n            hexstr[8:12],\n            '4' + hexstr[12:15],\n            '{:x}{}'.format(randbetween(8, 11), hexstr[15:18]),\n            hexstr[18:]\n        ]\n        self.last_result = uuid4\n        return uuid4",
    "docstring": "Generate a list of parts of a UUID version 4 string.\n\n        Usually, these parts are concatenated together using dashes."
  },
  {
    "code": "def create_network(userid, os_version, network_info):\n    print(\"\\nConfiguring network interface for %s ...\" % userid)\n    network_create_info = client.send_request('guest_create_network_interface', \n                                              userid, os_version, network_info)\n    if network_create_info['overallRC']:\n        raise RuntimeError(\"Failed to create network for guest %s!\\n%s\" % \n                           (userid, network_create_info))\n    else:\n        print(\"Succeeded to create network for guest %s!\" % userid)",
    "docstring": "Create network device and configure network interface.\n\n    Input parameters:\n    :userid:            USERID of the guest, last 8 if length > 8\n    :os_version:        os version of the image file\n    :network_info:      dict of network info"
  },
  {
    "code": "def is_dir(dirname):\n    if not os.path.isdir(dirname):\n        msg = \"{0} is not a directory\".format(dirname)\n        raise argparse.ArgumentTypeError(msg)\n    else:\n        return dirname",
    "docstring": "Checks if a path is an actual directory that exists"
  },
  {
    "code": "def create_bwa_index_from_fasta_file(fasta_in, params=None):\n    if params is None:\n        params = {}\n    index = BWA_index(params)\n    results = index({'fasta_in': fasta_in})\n    return results",
    "docstring": "Create a BWA index from an input fasta file.\n\n    fasta_in: the input fasta file from which to create the index\n    params: dict of bwa index specific paramters\n\n    This method returns a dictionary where the keys are the various\n    output suffixes (.amb, .ann, .bwt, .pac, .sa) and the values\n    are open file objects.\n\n    The index prefix will be the same as fasta_in, unless the -p parameter\n    is passed in params."
  },
  {
    "code": "def close_alert(name=None, api_key=None, reason=\"Conditions are met.\",\n                action_type=\"Close\"):\n    if name is None:\n        raise salt.exceptions.SaltInvocationError(\n            'Name cannot be None.')\n    return create_alert(name, api_key, reason, action_type)",
    "docstring": "Close an alert in OpsGenie. It's a wrapper function for create_alert.\n    Example usage with Salt's requisites and other global state arguments\n    could be found above.\n\n    Required Parameters:\n\n    name\n        It will be used as alert's alias. If you want to use the close\n        functionality you must provide name field for both states like\n        in above case.\n\n    Optional Parameters:\n\n    api_key\n        It's the API Key you've copied while adding integration in OpsGenie.\n\n    reason\n        It will be used as alert's default message in OpsGenie.\n\n    action_type\n        OpsGenie supports the default values Create/Close for action_type.\n        You can customize this field with OpsGenie's custom actions for\n        other purposes like adding notes or acknowledging alerts."
  },
  {
    "code": "def is_decimal(self):\n        dt = DATA_TYPES['decimal']\n        if type(self.data) in dt['type']:\n            self.type = 'DECIMAL'\n            num_split = str(self.data).split('.', 1)\n            self.len = len(num_split[0])\n            self.len_decimal = len(num_split[1])\n            return True",
    "docstring": "Determine if a data record is of the type float."
  },
  {
    "code": "def get_hostname_text(self):\n        try:\n            hostname_text = self.device.send('hostname', timeout=10)\n            if hostname_text:\n                self.device.hostname = hostname_text.splitlines()[0]\n                return hostname_text\n        except CommandError:\n            self.log(\"Non Unix jumphost type detected\")\n            return None",
    "docstring": "Return hostname information from the Unix host."
  },
  {
    "code": "def start(name, timeout=90, with_deps=False, with_parents=False):\n    if disabled(name):\n        modify(name, start_type='Manual')\n    ret = set()\n    services = ServiceDependencies(name, get_all, info)\n    start = services.start_order(with_deps=with_deps, with_parents=with_parents)\n    log.debug(\"Starting services %s\", start)\n    for name in start:\n        try:\n            win32serviceutil.StartService(name)\n        except pywintypes.error as exc:\n            if exc.winerror != 1056:\n                raise CommandExecutionError(\n                    'Failed To Start {0}: {1}'.format(name, exc.strerror))\n            log.debug('Service \"%s\" is running', name)\n        srv_status = _status_wait(service_name=name,\n                                  end_time=time.time() + int(timeout),\n                                  service_states=['Start Pending', 'Stopped'])\n        ret.add(srv_status['Status'] == 'Running')\n    return False not in ret",
    "docstring": "Start the specified service.\n\n    .. warning::\n        You cannot start a disabled service in Windows. If the service is\n        disabled, it will be changed to ``Manual`` start.\n\n    Args:\n        name (str): The name of the service to start\n\n        timeout (int):\n            The time in seconds to wait for the service to start before\n            returning. Default is 90 seconds\n\n            .. versionadded:: 2017.7.9,2018.3.4\n\n        with_deps (bool):\n            If enabled start the given service and the services the current\n            service depends on.\n\n        with_parents (bool):\n            If enabled and in case other running services depend on the to be start\n            service, this flag indicates that those other services will be started\n            as well.\n\n    Returns:\n        bool: ``True`` if successful, otherwise ``False``. Also returns ``True``\n            if the service is already started\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' service.start <service name>"
  },
  {
    "code": "def evalsha(self, digest, keys=[], args=[]):\n        return self.execute(b'EVALSHA', digest, len(keys), *(keys + args))",
    "docstring": "Execute a Lua script server side by its SHA1 digest."
  },
  {
    "code": "def first_true(iterable, default=False, pred=None):\n    return next(filter(pred, iterable), default)",
    "docstring": "Returns the first true value in the iterable.\n\n    If no true value is found, returns *default*\n\n    If *pred* is not None, returns the first item\n    for which pred(item) is true."
  },
  {
    "code": "def redirect(self,\n                 where: Optional[str] = None,\n                 default: Optional[str] = None,\n                 override: Optional[str] = None,\n                 **url_kwargs):\n        return redirect(where, default, override, _cls=self, **url_kwargs)",
    "docstring": "Convenience method for returning redirect responses.\n\n        :param where: A URL, endpoint, or config key name to redirect to.\n        :param default: A URL, endpoint, or config key name to redirect to if\n                        ``where`` is invalid.\n        :param override: explicitly redirect to a URL, endpoint, or config key name\n                         (takes precedence over the ``next`` value in query strings\n                         or forms)\n        :param url_kwargs: the variable arguments of the URL rule\n        :param _anchor: if provided this is added as anchor to the URL.\n        :param _external: if set to ``True``, an absolute URL is generated. Server\n                          address can be changed via ``SERVER_NAME`` configuration\n                          variable which defaults to `localhost`.\n        :param _external_host: if specified, the host of an external server to\n                               generate urls for (eg https://example.com or\n                               localhost:8888)\n        :param _method: if provided this explicitly specifies an HTTP method.\n        :param _scheme: a string specifying the desired URL scheme. The `_external`\n                        parameter must be set to ``True`` or a :exc:`ValueError`\n                        is raised. The default behavior uses the same scheme as\n                        the current request, or ``PREFERRED_URL_SCHEME`` from the\n                        :ref:`app configuration <config>` if no request context is\n                        available. As of Werkzeug 0.10, this also can be set\n                        to an empty string to build protocol-relative URLs."
  },
  {
    "code": "def link(self, pid, to):\n    self._assert_started()\n    def really_link():\n      self._links[pid].add(to)\n      log.info('Added link from %s to %s' % (pid, to))\n    def on_connect(stream):\n      really_link()\n    if self._is_local(pid):\n      really_link()\n    else:\n      self.__loop.add_callback(self._maybe_connect, to, on_connect)",
    "docstring": "Link a local process to a possibly remote process.\n\n    Note: It is more idiomatic to call ``link`` directly on the bound Process\n    object instead.\n\n    When ``pid`` is linked to ``to``, the termination of the ``to`` process\n    (or the severing of its connection from the Process ``pid``) will result\n    in the local process' ``exited`` method to be called with ``to``.\n\n    This method returns immediately.\n\n    :param pid: The pid of the linking process.\n    :type pid: :class:`PID`\n    :param to: The pid of the linked process.\n    :type to: :class:`PID`\n    :returns: Nothing"
  },
  {
    "code": "def write_seq_as_temp_fasta(seq):\n    sr = ssbio.protein.sequence.utils.cast_to_seq_record(seq, id='tempfasta')\n    return write_fasta_file(seq_records=sr, outname='temp', outdir=tempfile.gettempdir(), force_rerun=True)",
    "docstring": "Write a sequence as a temporary FASTA file\n\n    Args:\n        seq (str, Seq, SeqRecord): Sequence string, Biopython Seq or SeqRecord object\n\n    Returns:\n        str: Path to temporary FASTA file (located in system temporary files directory)"
  },
  {
    "code": "def set_value(self, name, value):\n        value = to_text_string(value)\n        code = u\"get_ipython().kernel.set_value('%s', %s, %s)\" % (name, value,\n                                                                  PY2)\n        if self._reading:\n            self.kernel_client.input(u'!' + code)\n        else:\n            self.silent_execute(code)",
    "docstring": "Set value for a variable"
  },
  {
    "code": "def setup(sphinx):\n    from flask import has_app_context\n    from invenio_base.factory import create_app\n    PACKAGES = ['invenio_base', 'invenio.modules.accounts',\n                'invenio.modules.records', 'invenio_knowledge']\n    if not has_app_context():\n        app = create_app(PACKAGES=PACKAGES)\n        ctx = app.test_request_context('/')\n        ctx.push()",
    "docstring": "Setup Sphinx object."
  },
  {
    "code": "def cor(y_true, y_pred):\n    y_true, y_pred = _mask_nan(y_true, y_pred)\n    return np.corrcoef(y_true, y_pred)[0, 1]",
    "docstring": "Compute Pearson correlation coefficient."
  },
  {
    "code": "def pdf_saver(filehandle, *args, **kwargs):\n    \"Uses werkzeug.FileStorage instance to save the converted image.\"\n    fullpath = get_save_path(filehandle.filename)\n    filehandle.save(fullpath, buffer_size=kwargs.get('buffer_size', 16384))",
    "docstring": "Uses werkzeug.FileStorage instance to save the converted image."
  },
  {
    "code": "def get_default_storage_policy_of_datastore(profile_manager, datastore):\n    hub = pbm.placement.PlacementHub(\n        hubId=datastore._moId, hubType='Datastore')\n    log.trace('placement_hub = %s', hub)\n    try:\n        policy_id = profile_manager.QueryDefaultRequirementProfile(hub)\n    except vim.fault.NoPermission as exc:\n        log.exception(exc)\n        raise VMwareApiError('Not enough permissions. Required privilege: '\n                             '{0}'.format(exc.privilegeId))\n    except vim.fault.VimFault as exc:\n        log.exception(exc)\n        raise VMwareApiError(exc.msg)\n    except vmodl.RuntimeFault as exc:\n        log.exception(exc)\n        raise VMwareRuntimeError(exc.msg)\n    policy_refs = get_policies_by_id(profile_manager, [policy_id])\n    if not policy_refs:\n        raise VMwareObjectRetrievalError('Storage policy with id \\'{0}\\' was '\n                                         'not found'.format(policy_id))\n    return policy_refs[0]",
    "docstring": "Returns the default storage policy reference assigned to a datastore.\n\n    profile_manager\n        Reference to the profile manager.\n\n    datastore\n        Reference to the datastore."
  },
  {
    "code": "def on_delete(self, node):\n        for tnode in node.targets:\n            if tnode.ctx.__class__ != ast.Del:\n                break\n            children = []\n            while tnode.__class__ == ast.Attribute:\n                children.append(tnode.attr)\n                tnode = tnode.value\n            if tnode.__class__ == ast.Name and tnode.id not in self.readonly_symbols:\n                children.append(tnode.id)\n                children.reverse()\n                self.symtable.pop('.'.join(children))\n            else:\n                msg = \"could not delete symbol\"\n                self.raise_exception(node, msg=msg)",
    "docstring": "Delete statement."
  },
  {
    "code": "def to_op(self):\n        if not self._adds:\n            return None\n        changes = {}\n        if self._adds:\n            changes['adds'] = list(self._adds)\n        return changes",
    "docstring": "Extracts the modification operation from the Hll.\n\n        :rtype: dict, None"
  },
  {
    "code": "def get_reverse_index(self, base_index):\n        r = self.reverse_index_mapping[base_index]\n        if r < 0:\n            raise IndexError(\"index %d not mapped in this segment\" % base_index)\n        return r",
    "docstring": "Get index into this segment's data given the index into the base data\n\n        Raises IndexError if the base index doesn't map to anything in this\n        segment's data"
  },
  {
    "code": "def Group(params, name=None, type=None):\n    atts = {}\n    if name:\n        atts['name'] = name\n    if type:\n        atts['type'] = type\n    g = objectify.Element('Group', attrib=atts)\n    for p in params:\n        g.append(p)\n    return g",
    "docstring": "Groups together Params for adding under the 'What' section.\n\n    Args:\n        params(list of :func:`Param`): Parameter elements to go in this group.\n        name(str): Group name. NB ``None`` is valid, since the group may be\n            best identified by its type.\n        type(str): Type of group, e.g. 'complex' (for real and imaginary)."
  },
  {
    "code": "def collapse(cls, holomap, ranges=None, mode='data'):\n        if cls.definitions == []:\n            return holomap\n        clone = holomap.clone(shared_data=False)\n        data = zip(ranges[1], holomap.data.values()) if ranges else holomap.data.items()\n        for key, overlay in data:\n            clone[key] = cls.collapse_element(overlay, ranges, mode)\n        return clone",
    "docstring": "Given a map of Overlays, apply all applicable compositors."
  },
  {
    "code": "def guard(params, guardian, error_class=GuardError, message=''):\n    params = [params] if isinstance(params, string_types) else params\n    def guard_decorate(f):\n        @wraps(f)\n        def _guard_decorate(*args, **kwargs):\n            if guardian(**_params(f, args, kwargs, params)):\n                return f(*args, **kwargs)\n            else:\n                raise error_class(message)\n        return _guard_decorate\n    return guard_decorate",
    "docstring": "A guard function - check parameters\n    with guardian function on decorated function\n\n    :param tuple or string params: guarded function parameter/s\n    :param function guardian: verifying the conditions for the selected parameter\n    :param Exception error_class: raised class when guardian return false\n    :param string message: error message"
  },
  {
    "code": "def all_devices(cl_device_type=None, platform=None):\n        if isinstance(cl_device_type, str):\n            cl_device_type = device_type_from_string(cl_device_type)\n        runtime_list = []\n        if platform is None:\n            platforms = cl.get_platforms()\n        else:\n            platforms = [platform]\n        for platform in platforms:\n            if cl_device_type:\n                devices = platform.get_devices(device_type=cl_device_type)\n            else:\n                devices = platform.get_devices()\n            for device in devices:\n                if device_supports_double(device):\n                    env = CLEnvironment(platform, device)\n                    runtime_list.append(env)\n        return runtime_list",
    "docstring": "Get multiple device environments, optionally only of the indicated type.\n\n        This will only fetch devices that support double point precision.\n\n        Args:\n            cl_device_type (cl.device_type.* or string): The type of the device we want,\n                can be a opencl device type or a string matching 'GPU' or 'CPU'.\n            platform (opencl platform): The opencl platform to select the devices from\n\n        Returns:\n            list of CLEnvironment: List with the CL device environments."
  },
  {
    "code": "def generate_user_agent(os=None, navigator=None, platform=None,\n                        device_type=None):\n    return generate_navigator(os=os, navigator=navigator,\n                              platform=platform,\n                              device_type=device_type)['user_agent']",
    "docstring": "Generates HTTP User-Agent header\n\n    :param os: limit list of os for generation\n    :type os: string or list/tuple or None\n    :param navigator: limit list of browser engines for generation\n    :type navigator: string or list/tuple or None\n    :param device_type: limit possible oses by device type\n    :type device_type: list/tuple or None, possible values:\n        \"desktop\", \"smartphone\", \"tablet\", \"all\"\n    :return: User-Agent string\n    :rtype: string\n    :raises InvalidOption: if could not generate user-agent for\n        any combination of allowed oses and navigators\n    :raise InvalidOption: if any of passed options is invalid"
  },
  {
    "code": "def _ProcessCommandSource(self, source):\n    action = standard.ExecuteCommandFromClient\n    request = rdf_client_action.ExecuteRequest(\n        cmd=source.base_source.attributes[\"cmd\"],\n        args=source.base_source.attributes[\"args\"],\n    )\n    yield action, request",
    "docstring": "Prepare a request for calling the execute command action."
  },
  {
    "code": "def set_queue_callback(self, name, func):\n        if name in self.acquisition_hooks:\n            self.acquisition_hooks[name].append(func)\n        else:\n            self.acquisition_hooks[name] = [func]",
    "docstring": "Sets a function to execute when the named acquistion queue \n        has data placed in it.\n\n        :param name: name of the queue to pull data from\n        :type name: str\n        :param func: function reference to execute, expects queue contents as argument(s)\n        :type func: callable"
  },
  {
    "code": "def generate_format(self):\n        with self.l('if isinstance({variable}, str):'):\n            format_ = self._definition['format']\n            if format_ in self.FORMAT_REGEXS:\n                format_regex = self.FORMAT_REGEXS[format_]\n                self._generate_format(format_, format_ + '_re_pattern', format_regex)\n            elif format_ == 'regex':\n                with self.l('try:'):\n                    self.l('re.compile({variable})')\n                with self.l('except Exception:'):\n                    self.l('raise JsonSchemaException(\"{name} must be a valid regex\")')\n            else:\n                self.l('pass')",
    "docstring": "Means that value have to be in specified format. For example date, email or other.\n\n        .. code-block:: python\n\n            {'format': 'email'}\n\n        Valid value for this definition is user@example.com but not @username"
  },
  {
    "code": "def add(self, domain_accession, domain_type, match_quality):\n        self.matches[domain_type] = self.matches.get(domain_type, {})\n        self.matches[domain_type][domain_accession] = match_quality",
    "docstring": "match_quality should be a value between 0 and 1."
  },
  {
    "code": "def remove(self, path, recursive=True, skip_trash=True):\n        if recursive:\n            to_delete = []\n            for s in self.get_all_data().keys():\n                if s.startswith(path):\n                    to_delete.append(s)\n            for s in to_delete:\n                self.get_all_data().pop(s)\n        else:\n            self.get_all_data().pop(path)",
    "docstring": "Removes the given mockfile. skip_trash doesn't have any meaning."
  },
  {
    "code": "def get_container_mapping(self):\n        layout = self.context.getLayout()\n        container_mapping = {}\n        for slot in layout:\n            if slot[\"type\"] != \"a\":\n                continue\n            position = slot[\"position\"]\n            container_uid = slot[\"container_uid\"]\n            container_mapping[container_uid] = position\n        return container_mapping",
    "docstring": "Returns a mapping of container -> postition"
  },
  {
    "code": "def enable_autocenter(self, option):\n        option = option.lower()\n        assert(option in self.autocenter_options), \\\n            ImageViewError(\"Bad autocenter option '%s': must be one of %s\" % (\n                str(self.autocenter_options)))\n        self.t_.set(autocenter=option)",
    "docstring": "Set ``autocenter`` behavior.\n\n        Parameters\n        ----------\n        option : {'on', 'override', 'once', 'off'}\n            Option for auto-center behavior. A list of acceptable options can\n            also be obtained by :meth:`get_autocenter_options`.\n\n        Raises\n        ------\n        ginga.ImageView.ImageViewError\n            Invalid option."
  },
  {
    "code": "def eval_to_ast(self, e, n, extra_constraints=(), exact=None):\n        return [ ast.bv.BVV(v, e.size()) for v in self.eval(e, n, extra_constraints=extra_constraints, exact=exact) ]",
    "docstring": "Evaluates expression e, returning the results in the form of concrete ASTs."
  },
  {
    "code": "def get_ca_certs(environ=os.environ):\n    cert_paths = environ.get(\"TXAWS_CERTS_PATH\", DEFAULT_CERTS_PATH).split(\":\")\n    certificate_authority_map = {}\n    for path in cert_paths:\n        if not path:\n            continue\n        for cert_file_name in glob(os.path.join(path, \"*.pem\")):\n            if not os.path.exists(cert_file_name):\n                continue\n            cert_file = open(cert_file_name)\n            data = cert_file.read()\n            cert_file.close()\n            x509 = load_certificate(FILETYPE_PEM, data)\n            digest = x509.digest(\"sha1\")\n            certificate_authority_map[digest] = x509\n    values = certificate_authority_map.values()\n    if len(values) == 0:\n        raise exception.CertsNotFoundError(\"Could not find any .pem files.\")\n    return values",
    "docstring": "Retrieve a list of CAs at either the DEFAULT_CERTS_PATH or the env\n    override, TXAWS_CERTS_PATH.\n\n    In order to find .pem files, this function checks first for presence of the\n    TXAWS_CERTS_PATH environment variable that should point to a directory\n    containing cert files. In the absense of this variable, the module-level\n    DEFAULT_CERTS_PATH will be used instead.\n\n    Note that both of these variables have have multiple paths in them, just\n    like the familiar PATH environment variable (separated by colons)."
  },
  {
    "code": "def get_mors_with_properties(service_instance, object_type, property_list=None,\n                             container_ref=None, traversal_spec=None,\n                             local_properties=False):\n    content_args = [service_instance, object_type]\n    content_kwargs = {'property_list': property_list,\n                      'container_ref': container_ref,\n                      'traversal_spec': traversal_spec,\n                      'local_properties': local_properties}\n    try:\n        content = get_content(*content_args, **content_kwargs)\n    except BadStatusLine:\n        content = get_content(*content_args, **content_kwargs)\n    except IOError as exc:\n        if exc.errno != errno.EPIPE:\n            raise exc\n        content = get_content(*content_args, **content_kwargs)\n    object_list = []\n    for obj in content:\n        properties = {}\n        for prop in obj.propSet:\n            properties[prop.name] = prop.val\n        properties['object'] = obj.obj\n        object_list.append(properties)\n    log.trace('Retrieved %s objects', len(object_list))\n    return object_list",
    "docstring": "Returns a list containing properties and managed object references for the managed object.\n\n    service_instance\n        The Service Instance from which to obtain managed object references.\n\n    object_type\n        The type of content for which to obtain managed object references.\n\n    property_list\n        An optional list of object properties used to return even more filtered managed object reference results.\n\n    container_ref\n        An optional reference to the managed object to search under. Can either be an object of type Folder, Datacenter,\n        ComputeResource, Resource Pool or HostSystem. If not specified, default behaviour is to search under the inventory\n        rootFolder.\n\n    traversal_spec\n        An optional TraversalSpec to be used instead of the standard\n        ``Traverse All`` spec\n\n    local_properties\n        Flag specigying whether the properties to be retrieved are local to the\n        container. If that is the case, the traversal spec needs to be None."
  },
  {
    "code": "def ylabelsize(self, size, index=1):\n        self.layout['yaxis' + str(index)]['titlefont']['size'] = size\n        return self",
    "docstring": "Set the size of the label.\n\n        Parameters\n        ----------\n        size : int\n\n        Returns\n        -------\n        Chart"
  },
  {
    "code": "def add_to_manifest(self, manifest):\n        manifest.add_service(self.service.name)\n        manifest.write_manifest()",
    "docstring": "Add to the manifest to make sure it is bound to the\n        application."
  },
  {
    "code": "def create_table(table, dbo, tablename, schema=None, commit=True,\n                 constraints=True, metadata=None, dialect=None, sample=1000):\n    if sample > 0:\n        table = head(table, sample)\n    sql = make_create_table_statement(table, tablename, schema=schema,\n                                      constraints=constraints,\n                                      metadata=metadata, dialect=dialect)\n    _execute(sql, dbo, commit=commit)",
    "docstring": "Create a database table based on a sample of data in the given `table`.\n\n    Keyword arguments:\n\n    table : table container\n        Table data to load\n    dbo : database object\n        DB-API 2.0 connection, callable returning a DB-API 2.0 cursor, or\n        SQLAlchemy connection, engine or session\n    tablename : text\n        Name of the table\n    schema : text\n        Name of the database schema to create the table in\n    commit : bool\n        If True commit the changes\n    constraints : bool\n        If True use length and nullable constraints\n    metadata : sqlalchemy.MetaData\n        Custom table metadata\n    dialect : text\n        One of {'access', 'sybase', 'sqlite', 'informix', 'firebird', 'mysql',\n        'oracle', 'maxdb', 'postgresql', 'mssql'}\n    sample : int\n        Number of rows to sample when inferring types etc., set to 0 to use\n        the whole table"
  },
  {
    "code": "def sinc_window(num_zeros=64, precision=9, window=None, rolloff=0.945):\n    if window is None:\n        window = scipy.signal.blackmanharris\n    elif not six.callable(window):\n        raise TypeError('window must be callable, not type(window)={}'.format(type(window)))\n    if not 0 < rolloff <= 1:\n        raise ValueError('Invalid roll-off: rolloff={}'.format(rolloff))\n    if num_zeros < 1:\n        raise ValueError('Invalid num_zeros: num_zeros={}'.format(num_zeros))\n    if precision < 0:\n        raise ValueError('Invalid precision: precision={}'.format(precision))\n    num_bits = 2**precision\n    n = num_bits * num_zeros\n    sinc_win = rolloff * np.sinc(rolloff * np.linspace(0, num_zeros, num=n + 1,\n                                                       endpoint=True))\n    taper = window(2 * n + 1)[n:]\n    interp_win = (taper * sinc_win)\n    return interp_win, num_bits, rolloff",
    "docstring": "Construct a windowed sinc interpolation filter\n\n    Parameters\n    ----------\n    num_zeros : int > 0\n        The number of zero-crossings to retain in the sinc filter\n\n    precision : int > 0\n        The number of filter coefficients to retain for each zero-crossing\n\n    window : callable\n        The window function.  By default, uses Blackman-Harris.\n\n    rolloff : float > 0\n        The roll-off frequency (as a fraction of nyquist)\n\n    Returns\n    -------\n    interp_window: np.ndarray [shape=(num_zeros * num_table + 1)]\n        The interpolation window (right-hand side)\n\n    num_bits: int\n        The number of bits of precision to use in the filter table\n\n    rolloff : float > 0\n        The roll-off frequency of the filter, as a fraction of Nyquist\n\n    Raises\n    ------\n    TypeError\n        if `window` is not callable or `None`\n    ValueError\n        if `num_zeros < 1`, `precision < 1`,\n        or `rolloff` is outside the range `(0, 1]`.\n\n    Examples\n    --------\n    >>> # A filter with 10 zero-crossings, 32 samples per crossing, and a\n    ... # Hann window for tapering.\n    >>> halfwin, prec, rolloff = resampy.filters.sinc_window(num_zeros=10, precision=5,\n    ...                                                      window=scipy.signal.hann)\n    >>> halfwin\n    array([  9.450e-01,   9.436e-01, ...,  -7.455e-07,  -0.000e+00])\n    >>> prec\n    32\n    >>> rolloff\n    0.945\n\n    >>> # Or using sinc-window filter construction directly in resample\n    >>> y = resampy.resample(x, sr_orig, sr_new, filter='sinc_window',\n    ...                      num_zeros=10, precision=5,\n    ...                      window=scipy.signal.hann)"
  },
  {
    "code": "def form_valid(self, form):\n        response = super().form_valid(form)\n        messages.success(self.request, \"Successfully created ({})\".format(self.object))\n        return response",
    "docstring": "Add success message"
  },
  {
    "code": "def create_wiki(post_data):\n        logger.info('Call create wiki')\n        title = post_data['title'].strip()\n        if len(title) < 2:\n            logger.info(' ' * 4 + 'The title is too short.')\n            return False\n        the_wiki = MWiki.get_by_wiki(title)\n        if the_wiki:\n            logger.info(' ' * 4 + 'The title already exists.')\n            MWiki.update(the_wiki.uid, post_data)\n            return\n        uid = '_' + tools.get_uu8d()\n        return MWiki.__create_rec(uid, '1', post_data=post_data)",
    "docstring": "Create the wiki."
  },
  {
    "code": "def post_registration_redirect(self, request, user):\n        next_url = \"/registration/register/complete/\"\n        if \"next\" in request.GET or \"next\" in request.POST:\n            next_url = request.GET.get(\"next\", None) or request.POST.get(\"next\", None) or \"/\"\n        return (next_url, (), {})",
    "docstring": "After registration, redirect to the home page or supplied \"next\"\n        query string or hidden field value."
  },
  {
    "code": "def patternVector(self, vector):\n        if not self.patterned: return vector\n        if type(vector) == int:\n            if self.getWord(vector) != '':\n                return self.getWord(vector)\n            else:\n                return vector\n        elif type(vector) == float:\n            if self.getWord(vector) != '':\n                return self.getWord(vector)\n            else:\n                return vector\n        elif type(vector) == str:\n            return vector\n        elif type(vector) == list:\n            if self.getWord(vector) != '':\n                return self.getWord(vector)\n        vec = []\n        for v in vector:\n            if self.getWord(v) != '':\n                retval = self.getWord(v)\n                vec.append( retval )\n            else:\n                retval = self.patternVector(v)\n                vec.append( retval )                \n        return vec",
    "docstring": "Replaces vector with patterns. Used for loading inputs or\n        targets from a file and still preserving patterns."
  },
  {
    "code": "def _server_property(self, attr_name):\n        server = self._topology.select_server(\n            writable_server_selector)\n        return getattr(server.description, attr_name)",
    "docstring": "An attribute of the current server's description.\n\n        If the client is not connected, this will block until a connection is\n        established or raise ServerSelectionTimeoutError if no server is\n        available.\n\n        Not threadsafe if used multiple times in a single method, since\n        the server may change. In such cases, store a local reference to a\n        ServerDescription first, then use its properties."
  },
  {
    "code": "def _parse_response(self, respond):\n        mobj = self._max_qubit_error_re.match(respond.text)\n        if mobj:\n            raise RegisterSizeError(\n                'device register size must be <= {}'.format(mobj.group(1)))\n        return True",
    "docstring": "parse text of response for HTTP errors\n\n        This parses the text of the response to decide whether to\n        retry request or raise exception. At the moment this only\n        detects an exception condition.\n\n        Args:\n            respond (Response): requests.Response object\n\n        Returns:\n            bool: False if the request should be retried, True\n                if not.\n\n        Raises:\n            RegisterSizeError"
  },
  {
    "code": "def resetScale(self):\n        self.img.scale(1./self.imgScale[0], 1./self.imgScale[1])\n        self.imgScale = (1.,1.)",
    "docstring": "Resets the scale on this image. Correctly aligns time scale, undoes manual scaling"
  },
  {
    "code": "def find(self, start_address, end_address, byte_depth=20, instrs_depth=2):\n        self._max_bytes = byte_depth\n        self._instrs_depth = instrs_depth\n        if self._architecture == ARCH_X86:\n            candidates = self._find_x86_candidates(start_address, end_address)\n        elif self._architecture == ARCH_ARM:\n            candidates = self._find_arm_candidates(start_address, end_address)\n        else:\n            raise Exception(\"Architecture not supported.\")\n        return sorted(candidates, key=lambda g: g.address)",
    "docstring": "Find gadgets."
  },
  {
    "code": "def _default_headers(self):\r\n        headers = {\r\n            \"Authorization\": 'Bearer {}'.format(self.api_key),\r\n            \"User-agent\": self.useragent,\r\n            \"Accept\": 'application/json'\r\n        }\r\n        if self.impersonate_subuser:\r\n            headers['On-Behalf-Of'] = self.impersonate_subuser\r\n        return headers",
    "docstring": "Set the default header for a Twilio SendGrid v3 API call"
  },
  {
    "code": "def ordc(item, inset):\n    assert isinstance(inset, stypes.SpiceCell)\n    assert inset.is_char()\n    assert isinstance(item, str)\n    item = stypes.stringToCharP(item)\n    return libspice.ordc_c(item, ctypes.byref(inset))",
    "docstring": "The function returns the ordinal position of any given item in a\n    character set.  If the item does not appear in the set, the function\n    returns -1.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ordc_c.html\n\n    :param item: An item to locate within a set.\n    :type item: str\n    :param inset: A set to search for a given item.\n    :type inset: SpiceCharCell\n    :return: the ordinal position of item within the set\n    :rtype: int"
  },
  {
    "code": "def escape_query(query):\n    return query.replace(\"\\\\\", r\"\\5C\").replace(\"*\", r\"\\2A\").replace(\"(\", r\"\\28\").replace(\")\", r\"\\29\")",
    "docstring": "Escapes certain filter characters from an LDAP query."
  },
  {
    "code": "def _lxml_el_to_data(lxml_el, ns, nsmap, snake=True):\n    tag_name = _to_colon_ns(lxml_el.tag, default_ns=ns, nsmap=nsmap)\n    ret = [tag_name]\n    attributes = _get_el_attributes(lxml_el, ns=ns, nsmap=nsmap)\n    if attributes:\n        ret.append(attributes)\n    for sub_el in lxml_el:\n        ret.append(_lxml_el_to_data(sub_el, ns, nsmap, snake=snake))\n    text = lxml_el.text\n    if text:\n        ret.append(text)\n    return tuple(ret)",
    "docstring": "Convert an ``lxml._Element`` instance to a Python tuple."
  },
  {
    "code": "def register_id(self, id_string):\n        try:\n            prefix, count = id_string.rsplit(\"_\", 1)\n            count = int(count)\n        except ValueError:\n            pass\n        else:\n            if prefix == self.prefix:\n                self.counter = max(count, self.counter)",
    "docstring": "Register a manually assigned id as used, to avoid collisions."
  },
  {
    "code": "def facts(self):\n        fact = lib.EnvGetNextFact(self._env, ffi.NULL)\n        while fact != ffi.NULL:\n            yield new_fact(self._env, fact)\n            fact = lib.EnvGetNextFact(self._env, fact)",
    "docstring": "Iterate over the asserted Facts."
  },
  {
    "code": "def columns_in_filters(filters):\n    if not filters:\n        return []\n    if not isinstance(filters, str):\n        filters = ' '.join(filters)\n    columns = []\n    reserved = {'and', 'or', 'in', 'not'}\n    for toknum, tokval, _, _, _ in generate_tokens(StringIO(filters).readline):\n        if toknum == NAME and tokval not in reserved:\n            columns.append(tokval)\n    return list(tz.unique(columns))",
    "docstring": "Returns a list of the columns used in a set of query filters.\n\n    Parameters\n    ----------\n    filters : list of str or str\n        List of the filters as passed passed to ``apply_filter_query``.\n\n    Returns\n    -------\n    columns : list of str\n        List of all the strings mentioned in the filters."
  },
  {
    "code": "def yml_fnc(fname, *args, **options):\n    key = \"ac_safe\"\n    fnc = getattr(yaml, r\"safe_\" + fname if options.get(key) else fname)\n    return fnc(*args, **common.filter_from_options(key, options))",
    "docstring": "An wrapper of yaml.safe_load, yaml.load, yaml.safe_dump and yaml.dump.\n\n    :param fname:\n        \"load\" or \"dump\", not checked but it should be OK.\n        see also :func:`yml_load` and :func:`yml_dump`\n    :param args: [stream] for load or [cnf, stream] for dump\n    :param options: keyword args may contain \"ac_safe\" to load/dump safely"
  },
  {
    "code": "def set_attr_value(self, key, attr, value):\n        idx = self._keys[key]\n        self._attrs[attr][idx].set(value)",
    "docstring": "set the value of a given attribute for a given key"
  },
  {
    "code": "def _(obj):\n    tz_offset = obj.utcoffset()\n    if not tz_offset or tz_offset == UTC_ZERO:\n        iso_datetime = obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n    else:\n        iso_datetime = obj.isoformat()\n    return iso_datetime",
    "docstring": "ISO 8601 format. Interprets naive datetime as UTC with zulu suffix."
  },
  {
    "code": "def _check_panel(self, length):\n        n = len(self.index)\n        if divmod(n, length)[1] != 0:\n            raise ValueError(\"Panel length '%g' must evenly divide length of series '%g'\"\n                             % (length, n))\n        if n == length:\n            raise ValueError(\"Panel length '%g' cannot be length of series '%g'\"\n                             % (length, n))",
    "docstring": "Check that given fixed panel length evenly divides index.\n\n        Parameters\n        ----------\n        length : int\n            Fixed length with which to subdivide index"
  },
  {
    "code": "def run_alias():\n    mode = Path(sys.argv[0]).stem\n    help = True if len(sys.argv) <= 1 else False\n    if mode == 'lcc':\n        sys.argv.insert(1, 'c')\n    elif mode == 'lpython':\n        sys.argv.insert(1, 'python')\n    sys.argv.insert(1, 'run')\n    if help:\n        sys.argv.append('--help')\n    main.main(prog_name='backend.ai')",
    "docstring": "Quick aliases for run command."
  },
  {
    "code": "def knob_subgroup(self, cutoff=7.0):\n        if cutoff > self.cutoff:\n            raise ValueError(\"cutoff supplied ({0}) cannot be greater than self.cutoff ({1})\".format(cutoff,\n                                                                                                     self.cutoff))\n        return KnobGroup(monomers=[x for x in self.get_monomers()\n                                   if x.max_kh_distance <= cutoff], ampal_parent=self.ampal_parent)",
    "docstring": "KnobGroup where all KnobsIntoHoles have max_kh_distance <= cutoff."
  },
  {
    "code": "def _get_factor(self, belief_prop, evidence):\n        final_factor = factor_product(*belief_prop.junction_tree.get_factors())\n        if evidence:\n            for var in evidence:\n                if var in final_factor.scope():\n                    final_factor.reduce([(var, evidence[var])])\n        return final_factor",
    "docstring": "Extracts the required factor from the junction tree.\n\n        Parameters:\n        ----------\n        belief_prop: Belief Propagation\n            Belief Propagation which needs to be updated.\n\n        evidence: dict\n            a dict key, value pair as {var: state_of_var_observed}"
  },
  {
    "code": "def building(shape=None, gray=False):\n    name = 'cms.mat'\n    url = URL_CAM + name\n    dct = get_data(name, subset=DATA_SUBSET, url=url)\n    im = np.rot90(dct['im'], k=3)\n    return convert(im, shape, gray=gray)",
    "docstring": "Photo of the Centre for Mathematical Sciences in Cambridge.\n\n    Returns\n    -------\n    An image with the following properties:\n        image type: color (or gray scales if `gray=True`)\n        size: [442, 331] (if not specified by `size`)\n        scale: [0, 1]\n        type: float64"
  },
  {
    "code": "def cache_key(self, repo: str, branch: str, task: Task, git_repo: Repo) -> str:\n        return \"{repo}_{branch}_{hash}_{task}\".format(repo=self.repo_id(repo),\n                                                      branch=branch,\n                                                      hash=self.current_git_hash(repo, branch, git_repo),\n                                                      task=task.hash)",
    "docstring": "Returns the key used for storing results in cache."
  },
  {
    "code": "def humanize_filesize(filesize: int) -> Tuple[str, str]:\n    for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:\n        if filesize < 1024.0:\n            return '{:3.1f}'.format(filesize), unit+'B'\n        filesize /= 1024.0",
    "docstring": "Return human readable pair of size and unit from the given filesize in bytes."
  },
  {
    "code": "def contents_match(self, path):\n        checksum = file_hash(path)\n        kv = unitdata.kv()\n        stored_checksum = kv.get('hardening:%s' % path)\n        if not stored_checksum:\n            log('Checksum for %s has not been calculated.' % path, level=DEBUG)\n            return False\n        elif stored_checksum != checksum:\n            log('Checksum mismatch for %s.' % path, level=DEBUG)\n            return False\n        return True",
    "docstring": "Determines if the file content is the same.\n\n        This is determined by comparing hashsum of the file contents and\n        the saved hashsum. If there is no hashsum, then the content cannot\n        be sure to be the same so treat them as if they are not the same.\n        Otherwise, return True if the hashsums are the same, False if they\n        are not the same.\n\n        :param path: the file to check."
  },
  {
    "code": "def datasets(self, libref: str = '') -> str:\n        code = \"proc datasets\"\n        if libref:\n           code += \" dd=\" + libref\n        code += \"; quit;\"\n        if self.nosub:\n           print(code)\n        else:\n           if self.results.lower() == 'html':\n              ll = self._io.submit(code, \"html\")\n              if not self.batch:\n                 self.DISPLAY(self.HTML(ll['LST']))\n              else:\n                 return ll\n           else:\n              ll = self._io.submit(code, \"text\")\n              if self.batch:\n                 return ll['LOG'].rsplit(\";*\\';*\\\";*/;\\n\")[0]\n              else:\n                 print(ll['LOG'].rsplit(\";*\\';*\\\";*/;\\n\")[0])",
    "docstring": "This method is used to query a libref. The results show information about the libref including members.\n\n        :param libref: the libref to query\n        :return:"
  },
  {
    "code": "def _decode_linode_plan_label(label):\n    sizes = avail_sizes()\n    if label not in sizes:\n        if 'GB' in label:\n            raise SaltCloudException(\n                'Invalid Linode plan ({}) specified - call avail_sizes() for all available options'.format(label)\n            )\n        else:\n            plan = label.split()\n            if len(plan) != 2:\n                raise SaltCloudException(\n                    'Invalid Linode plan ({}) specified - call avail_sizes() for all available options'.format(label)\n                )\n            plan_type = plan[0]\n            try:\n                plan_size = int(plan[1])\n            except TypeError:\n                plan_size = 0\n                log.debug('Failed to decode Linode plan label in Cloud Profile: %s', label)\n            if plan_type == 'Linode' and plan_size == 1024:\n                plan_type = 'Nanode'\n            plan_size = plan_size/1024\n            new_label = \"{} {}GB\".format(plan_type, plan_size)\n            if new_label not in sizes:\n                raise SaltCloudException(\n                    'Invalid Linode plan ({}) specified - call avail_sizes() for all available options'.format(new_label)\n                )\n            log.warning(\n                'An outdated Linode plan label was detected in your Cloud '\n                'Profile (%s). Please update the profile to use the new '\n                'label format (%s) for the requested Linode plan size.',\n                label, new_label\n            )\n            label = new_label\n    return sizes[label]['PLANID']",
    "docstring": "Attempts to decode a user-supplied Linode plan label\n    into the format in Linode API output\n\n    label\n        The label, or name, of the plan to decode.\n\n    Example:\n        `Linode 2048` will decode to `Linode 2GB`"
  },
  {
    "code": "def sort_dict(self, data, key):\n    return sorted(data, key=itemgetter(key)) if data else []",
    "docstring": "Sort a list of dictionaries by dictionary key"
  },
  {
    "code": "def allow_exception(self, exc_class):\n        name = exc_class.__name__\n        self._allowed_exceptions[name] = exc_class",
    "docstring": "Allow raising this class of exceptions from commands.\n\n        When a command fails on the server side due to an exception, by\n        default it is turned into a string and raised on the client side as an\n        ExternalError.  The original class name is sent but ignored.  If you\n        would like to instead raise an instance of the same exception on the\n        client side, you can pass the exception class object to this method\n        and instances of that exception will be reraised.\n\n        The caveat is that the exception must be creatable with a single\n        string parameter and it should have a ``msg`` property.\n\n        Args:\n            exc_class (class): A class object with the exception that\n                we should allow to pass from server to client."
  },
  {
    "code": "def battlecry_requires_target(self):\n\t\tif self.has_combo and self.controller.combo:\n\t\t\tif PlayReq.REQ_TARGET_FOR_COMBO in self.requirements:\n\t\t\t\treturn True\n\t\tfor req in TARGETING_PREREQUISITES:\n\t\t\tif req in self.requirements:\n\t\t\t\treturn True\n\t\treturn False",
    "docstring": "True if the play action of the card requires a target"
  },
  {
    "code": "def signed_int_to_unsigned_hex(signed_int: int) -> str:\n    hex_string = hex(struct.unpack('Q', struct.pack('q', signed_int))[0])[2:]\n    if hex_string.endswith('L'):\n        return hex_string[:-1]\n    return hex_string",
    "docstring": "Converts a signed int value to a 64-bit hex string.\n\n    Examples:\n        1662740067609015813  => '17133d482ba4f605'\n        -5270423489115668655 => 'b6dbb1c2b362bf51'\n\n    :param signed_int: an int to convert\n    :returns: unsigned hex string"
  },
  {
    "code": "def keys(cls, name, hash_key, range_key=None, throughput=None):\n        return cls(cls.KEYS, name, hash_key, range_key,\n                   throughput=throughput)",
    "docstring": "Create an index that projects only key attributes"
  },
  {
    "code": "def get_property_dict(entity_proto):\n  return dict((p.key, p.value) for p in entity_proto.property)",
    "docstring": "Convert datastore.Entity to a dict of property name -> datastore.Value.\n\n  Args:\n    entity_proto: datastore.Entity proto message.\n\n  Usage:\n    >>> get_property_dict(entity_proto)\n    {'foo': {string_value='a'}, 'bar': {integer_value=2}}\n\n  Returns:\n    dict of entity properties."
  },
  {
    "code": "def unregister_event(self, event_name, handler):\n        try:\n            self._event_handlers[event_name].remove(handler)\n        except ValueError:\n            pass",
    "docstring": "Unregister a callable that will be called when event is raised.\n\n        :param event_name: The name of the event (see knack.events for in-built events)\n        :type event_name: str\n        :param handler: The callback that was used to register the event\n        :type handler: function"
  },
  {
    "code": "def hashes(self):\n        for url_variant in self.url_permutations(self.canonical):\n            url_hash = self.digest(url_variant)\n            yield url_hash",
    "docstring": "Hashes of all possible permutations of the URL in canonical form"
  },
  {
    "code": "def get_block_by_hash(self, block_hash: Hash32) -> BaseBlock:\n        validate_word(block_hash, title=\"Block Hash\")\n        block_header = self.get_block_header_by_hash(block_hash)\n        return self.get_block_by_header(block_header)",
    "docstring": "Returns the requested block as specified by block hash."
  },
  {
    "code": "def remote_file(self, branch='master', filename=''):\n        LOG.info('Retrieving \"%s\" from \"%s\".', filename, self.git_short)\n        file_contents = ''\n        try:\n            file_blob = self.project.files.get(file_path=filename, ref=branch)\n        except gitlab.exceptions.GitlabGetError:\n            file_blob = None\n        LOG.debug('GitLab file response:\\n%s', file_blob)\n        if not file_blob:\n            msg = 'Project \"{0}\" is missing file \"{1}\" in \"{2}\" branch.'.format(self.git_short, filename, branch)\n            LOG.warning(msg)\n            raise FileNotFoundError(msg)\n        else:\n            file_contents = b64decode(file_blob.content).decode()\n        LOG.debug('Remote file contents:\\n%s', file_contents)\n        return file_contents",
    "docstring": "Read the remote file on Git Server.\n\n        Args:\n            branch (str): Git Branch to find file.\n            filename (str): Name of file to retrieve relative to root of\n                repository.\n\n        Returns:\n            str: Contents of remote file.\n\n        Raises:\n            FileNotFoundError: Requested file missing."
  },
  {
    "code": "def get_instantiated_service(self, name):\n        if name not in self.instantiated_services:\n            raise UninstantiatedServiceException\n        return self.instantiated_services[name]",
    "docstring": "Get instantiated service by name"
  },
  {
    "code": "def register_area(self, area_code, index, userdata):\n        size = ctypes.sizeof(userdata)\n        logger.info(\"registering area %s, index %s, size %s\" % (area_code,\n                                                                index, size))\n        size = ctypes.sizeof(userdata)\n        return self.library.Srv_RegisterArea(self.pointer, area_code, index,\n                                             ctypes.byref(userdata), size)",
    "docstring": "Shares a memory area with the server. That memory block will be\n        visible by the clients."
  },
  {
    "code": "def Search(self, text, wholewords=0, titleonly=0):\n        if text and text != '' and self.file:\n            return extra.search(self.file, text, wholewords,\n                                titleonly)\n        else:\n            return None",
    "docstring": "Performs full-text search on the archive.\n        The first parameter is the word to look for, the second\n        indicates if the search should be for whole words only, and\n        the third parameter indicates if the search should be\n        restricted to page titles.\n        This method will return a tuple, the first item\n        indicating if the search results were partial, and the second\n        item being a dictionary containing the results."
  },
  {
    "code": "def stop(self):\n        if self._died.ready():\n            _log.debug('already stopped %s', self)\n            return\n        if self._being_killed:\n            _log.debug('already being killed %s', self)\n            try:\n                self._died.wait()\n            except:\n                pass\n            return\n        _log.debug('stopping %s', self)\n        with _log_time('stopped %s', self):\n            self.entrypoints.all.stop()\n            self._worker_pool.waitall()\n            self.dependencies.all.stop()\n            self.subextensions.all.stop()\n            self._kill_managed_threads()\n            self.started = False\n            if not self._died.ready():\n                self._died.send(None)",
    "docstring": "Stop the container gracefully.\n\n        First all entrypoints are asked to ``stop()``.\n        This ensures that no new worker threads are started.\n\n        It is the extensions' responsibility to gracefully shut down when\n        ``stop()`` is called on them and only return when they have stopped.\n\n        After all entrypoints have stopped the container waits for any\n        active workers to complete.\n\n        After all active workers have stopped the container stops all\n        dependency providers.\n\n        At this point there should be no more managed threads. In case there\n        are any managed threads, they are killed by the container."
  },
  {
    "code": "def add_tunnel_port(self, name, tunnel_type, remote_ip,\n                        local_ip=None, key=None, ofport=None):\n        options = 'remote_ip=%(remote_ip)s' % locals()\n        if key:\n            options += ',key=%(key)s' % locals()\n        if local_ip:\n            options += ',local_ip=%(local_ip)s' % locals()\n        args = ['Interface', name, 'type=%s' % tunnel_type,\n                'options:%s' % options]\n        if ofport:\n            args.append('ofport_request=%(ofport)s' % locals())\n        command_add = ovs_vsctl.VSCtlCommand('add-port', (self.br_name, name))\n        command_set = ovs_vsctl.VSCtlCommand('set', args)\n        self.run_command([command_add, command_set])",
    "docstring": "Creates a tunnel port.\n\n        :param name: Port name to be created\n        :param tunnel_type: Type of tunnel (gre or vxlan)\n        :param remote_ip: Remote IP address of tunnel\n        :param local_ip: Local IP address of tunnel\n        :param key: Key of GRE or VNI of VxLAN\n        :param ofport: Requested OpenFlow port number"
  },
  {
    "code": "def disable(self, retain_port=False):\n        self.update_server(disabled=True)\n        if retain_port:\n            return\n        self.update_device(disabled=True)\n        if self.conf.dhcp_delete_namespaces and self.network.namespace:\n            ns_ip = ip_lib.IPWrapper(self.root_helper,\n                                     self.network.namespace)\n            try:\n                ns_ip.netns.delete(self.network.namespace)\n            except RuntimeError:\n                msg = _('Failed trying to delete namespace: %s')\n                LOG.exception(msg, self.network.namespace)",
    "docstring": "Teardown DHCP.\n\n        Disable DHCP for this network by updating the remote server\n        and then destroying any local device and namespace."
  },
  {
    "code": "def getStreamNetworkAsWkt(self, session, withNodes=True):\n        wkt_list = []\n        for link in self.streamLinks:\n            wkt_link = link.getAsWkt(session)\n            if wkt_link:\n                wkt_list.append(wkt_link)\n            if withNodes:\n                for node in link.nodes:\n                    wkt_node = node.getAsWkt(session)\n                    if wkt_node:\n                        wkt_list.append(wkt_node)\n        return 'GEOMCOLLECTION ({0})'.format(', '.join(wkt_list))",
    "docstring": "Retrieve the stream network geometry in Well Known Text format.\n\n        Args:\n            session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database\n            withNodes (bool, optional): Include nodes. Defaults to False.\n\n        Returns:\n            str: Well Known Text string."
  },
  {
    "code": "def filter_product_filename_generator(obs_info,nn):\n    proposal_id = obs_info[0]\n    visit_id = obs_info[1]\n    instrument = obs_info[2]\n    detector = obs_info[3]\n    filter = obs_info[4]\n    product_filename_dict = {}\n    product_filename_dict[\"image\"] = \"hst_{}_{}_{}_{}_{}.fits\".format(proposal_id,visit_id,instrument,detector,filter)\n    product_filename_dict[\"source catalog\"] = product_filename_dict[\"image\"].replace(\".fits\",\".cat\")\n    return(product_filename_dict)",
    "docstring": "Generate image and sourcelist filenames for filter products\n\n    Parameters\n    ----------\n    obs_info : list\n        list of items that will be used to generate the filenames: proposal_id,\n        visit_id, instrument, detector, and filter\n    nn : string\n        the single-exposure image number (NOTE: only used in\n        single_exposure_product_filename_generator())\n\n    Returns\n    --------\n    product_filename_dict : dictionary\n        A dictionary containing the generated filenames."
  },
  {
    "code": "def iscsi_resource(self):\n        return iscsi.ISCSIResource(\n            self._conn, utils.get_subresource_path_by(\n                self, [\"Oem\", \"Hpe\", \"Links\", \"iScsi\"]),\n            redfish_version=self.redfish_version)",
    "docstring": "Property to provide reference to bios iscsi resource instance\n\n        It is calculated once when the first time it is queried. On refresh,\n        this property gets reset."
  },
  {
    "code": "def get_logger(self, name=\"deployment-logger\", level=logging.DEBUG):\n        log = logging\n        logger = log.getLogger(name)\n        fmt = log.Formatter(\"%(asctime)s %(funcName)s \"\n                            \"%(levelname)s: %(message)s\")\n        handler = log.StreamHandler(stream=sys.stdout)\n        handler.setLevel(level)\n        handler.setFormatter(fmt)\n        logger.addHandler(handler)\n        logger.setLevel(level)\n        return logger",
    "docstring": "Get a logger object that will log to stdout."
  },
  {
    "code": "def ascent(self):\n        total_ascent = 0.0\n        altitude_data = self.altitude_points()\n        for i in range(len(altitude_data) - 1):\n            diff = altitude_data[i+1] - altitude_data[i]\n            if diff > 0.0:\n                total_ascent += diff\n        return total_ascent",
    "docstring": "Returns ascent of workout in meters"
  },
  {
    "code": "def _load(self):\n        if self.is_sw or self.platform_name == 'EOS-Aqua':\n            scale = 0.001\n        else:\n            scale = 1.0\n        detector = read_modis_response(self.requested_band_filename, scale)\n        self.rsr = detector\n        if self._sort:\n            self.sort()",
    "docstring": "Load the MODIS RSR data for the band requested"
  },
  {
    "code": "def _create_body(self, name, flavor=None, volume=None, databases=None,\n            users=None, version=None, type=None):\n        if flavor is None:\n            flavor = 1\n        flavor_ref = self.api._get_flavor_ref(flavor)\n        if volume is None:\n            volume = 1\n        if databases is None:\n            databases = []\n        if users is None:\n            users = []\n        body = {\"instance\": {\n                \"name\": name,\n                \"flavorRef\": flavor_ref,\n                \"volume\": {\"size\": volume},\n                \"databases\": databases,\n                \"users\": users,\n                }}\n        if type is not None or version is not None:\n            required = (type, version)\n            if all(required):\n                body['instance']['datastore'] = {\"type\": type, \"version\": version}\n            else:\n                raise exc.MissingCloudDatabaseParameter(\"Specifying a datastore\"\n                    \" requires both the datastore type as well as the version.\")\n        return body",
    "docstring": "Used to create the dict required to create a Cloud Database instance."
  },
  {
    "code": "def renew_local_branch(branch, start_point, remote=False):\n    if branch in branches():\n        checkout(start_point)\n        delete(branch, force=True, remote=remote)\n    result = new_local_branch(branch, start_point)\n    if remote:\n        publish(branch)\n    return result",
    "docstring": "Make a new local branch from that start_point\n\n    start_point is a git \"commit-ish\", e.g branch, tag, commit\n\n    If a local branch already exists it is removed\n    If remote is true then push the new branch to origin"
  },
  {
    "code": "def example_method(self, i3s_output_list, i3s_config):\n        full_text = self.format.format(output='example')\n        response = {\n            'cached_until': time() + self.cache_timeout,\n            'full_text': full_text\n        }\n        return response",
    "docstring": "This method will return an empty text message\n        so it will NOT be displayed on your i3bar.\n\n        If you want something displayed you should write something\n        in the 'full_text' key of your response.\n\n        See the i3bar protocol spec for more information:\n        http://i3wm.org/docs/i3bar-protocol.html"
  },
  {
    "code": "def get_structure_with_nodes(self):\n        new_s = Structure.from_sites(self.structure)\n        for v in self.vnodes:\n            new_s.append(\"X\", v.frac_coords)\n        return new_s",
    "docstring": "Get the modified structure with the voronoi nodes inserted. The\n        species is set as a DummySpecie X."
  },
  {
    "code": "def create(self, article, attachment, inline=False, file_name=None, content_type=None):\n        return HelpdeskAttachmentRequest(self).post(self.endpoint.create,\n                                                    article=article,\n                                                    attachments=attachment,\n                                                    inline=inline,\n                                                    file_name=file_name,\n                                                    content_type=content_type)",
    "docstring": "This function creates attachment attached to article.\n\n        :param article: Numeric article id or :class:`Article` object.\n        :param attachment: File object or os path to file\n        :param inline: If true, the attached file is shown in the dedicated admin UI\n            for inline attachments and its url can be referenced in the HTML body of\n            the article. If false, the attachment is listed in the list of attachments.\n            Default is `false`\n        :param file_name: you can set filename on file upload.\n        :param content_type: The content type of the file. `Example: image/png`, Zendesk can ignore it.\n        :return: :class:`ArticleAttachment` object"
  },
  {
    "code": "def get_repo_revision():\n    repopath = _findrepo()\n    if not repopath:\n        return ''\n    try:\n        import mercurial.hg, mercurial.ui, mercurial.scmutil\n        from mercurial.node import short as hexfunc\n    except ImportError:\n        pass\n    else:\n        ui = mercurial.ui.ui()\n        repo = mercurial.hg.repository(ui, repopath)\n        parents = repo[None].parents()\n        changed = filter(None, repo.status()) and \"+\" or \"\"\n        return ';'.join(['%s:%s%s' % (p.rev(), hexfunc(p.node()), changed)\n                         for p in parents])\n    return ''",
    "docstring": "Returns mercurial revision string somelike `hg identify` does.\n\n    Format is rev1:short-id1+;rev2:short-id2+\n\n    Returns an empty string if anything goes wrong, such as missing\n    .hg files or an unexpected format of internal HG files or no\n    mercurial repository found."
  },
  {
    "code": "def singledispatch(*, nargs=None, nouts=None, ndefs=None):\n    def wrapper(f):\n        return wraps(f)(SingleDispatchFunction(f, nargs=nargs, nouts=nouts, ndefs=ndefs))\n    return wrapper",
    "docstring": "singledispatch decorate of both functools.singledispatch and func"
  },
  {
    "code": "def rmSelf(f):\n    def new_f(*args, **kwargs):\n        newArgs = args[1:]\n        result = f(*newArgs, **kwargs)\n        return result\n    return new_f",
    "docstring": "f -> function.\n    Decorator, removes first argument from f parameters."
  },
  {
    "code": "def parse_summary(content, reference_id=None):\n    summary = None\n    m = _END_SUMMARY_PATTERN.search(content)\n    if m:\n        end_of_summary = m.start()\n        m = _START_SUMMARY_PATTERN.search(content, 0, end_of_summary) or _ALTERNATIVE_START_SUMMARY_PATTERN.search(content, 0, end_of_summary)\n        if m:\n            summary = content[m.end():end_of_summary]\n        elif reference_id not in _CABLES_WITH_MALFORMED_SUMMARY:\n            logger.debug('Found \"end of summary\" but no start in \"%s\", content: \"%s\"' % (reference_id, content[:end_of_summary]))\n    else:\n        m = _PARSE_SUMMARY_PATTERN.search(content)\n        if m:\n            summary = content[m.start(1):m.end(1)]\n    if summary:\n        summary = _CLEAN_SUMMARY_CLS_PATTERN.sub(u'', summary)\n        summary = _CLEAN_SUMMARY_PATTERN.sub(u' ', summary)\n        summary = _CLEAN_SUMMARY_WS_PATTERN.sub(u' ', summary)\n        summary = summary.strip()\n    return summary",
    "docstring": "\\\n    Extracts the summary from the `content` of the cable.\n    \n    If no summary can be found, ``None`` is returned.\n    \n    `content`\n        The content of the cable.\n    `reference_id`\n        The reference identifier of the cable."
  },
  {
    "code": "def attach_framebuffer(self, screen_id, framebuffer):\n        if not isinstance(screen_id, baseinteger):\n            raise TypeError(\"screen_id can only be an instance of type baseinteger\")\n        if not isinstance(framebuffer, IFramebuffer):\n            raise TypeError(\"framebuffer can only be an instance of type IFramebuffer\")\n        id_p = self._call(\"attachFramebuffer\",\n                     in_p=[screen_id, framebuffer])\n        return id_p",
    "docstring": "Sets the graphics update target for a screen.\n\n        in screen_id of type int\n\n        in framebuffer of type :class:`IFramebuffer`\n\n        return id_p of type str"
  },
  {
    "code": "def create_archiver(typename):\n  archiver = _ARCHIVER_BY_TYPE.get(typename)\n  if not archiver:\n    raise ValueError('No archiver registered for {!r}'.format(typename))\n  return archiver",
    "docstring": "Returns Archivers in common configurations.\n\n  :API: public\n\n  The typename must correspond to one of the following:\n  'tar'   Returns a tar archiver that applies no compression and emits .tar files.\n  'tgz'   Returns a tar archiver that applies gzip compression and emits .tar.gz files.\n  'tbz2'  Returns a tar archiver that applies bzip2 compression and emits .tar.bz2 files.\n  'zip'   Returns a zip archiver that applies standard compression and emits .zip files.\n  'jar'   Returns a jar archiver that applies no compression and emits .jar files.\n    Note this is provided as a light way of zipping input files into a jar, without the\n    need to prepare Manifest etc. For more advanced usages, please refer to :class:\n    `pants.backend.jvm.subsystems.jar_tool.JarTool` or :class:\n    `pants.backend.jvm.tasks.jar_task.JarTask`."
  },
  {
    "code": "def resume_writing(self):\n        if not self._can_send.is_set():\n            self._can_send.set()\n            self.transport.resume_reading()",
    "docstring": "Transport calls when the send buffer has room."
  },
  {
    "code": "def patch(self, request, format=None):\n        data = request.data.copy()\n        try:\n            ct = ChatType.objects.get(id=data.pop(\"chat_type\"))\n            data[\"chat_type\"] = ct\n        except ChatType.DoesNotExist:\n            return typeNotFound404\n        if not self.is_path_unique(\n            data[\"id\"], data[\"publish_path\"], ct.publish_path\n        ):\n            return notUnique400\n        try:\n            c = Channel.objects.get(id=data.pop(\"id\"))\n        except Channel.DoesNotExist:\n            return channelNotFound404\n        for key, value in data.items():\n            setattr(c, key, value)\n        c.save()\n        self.handle_webhook(c)\n        return Response(\n            {\n                \"text\": \"Channel saved.\",\n                \"method\": \"PATCH\",\n                \"saved\": ChannelCMSSerializer(c).data,\n            },\n            200,\n        )",
    "docstring": "Update an existing Channel"
  },
  {
    "code": "def take_profit_replace(self, accountID, orderID, **kwargs):\n        return self.replace(\n            accountID,\n            orderID,\n            order=TakeProfitOrderRequest(**kwargs)\n        )",
    "docstring": "Shortcut to replace a pending Take Profit Order in an Account\n\n        Args:\n            accountID : The ID of the Account\n            orderID : The ID of the Take Profit Order to replace\n            kwargs : The arguments to create a TakeProfitOrderRequest\n\n        Returns:\n            v20.response.Response containing the results from submitting\n            the request"
  },
  {
    "code": "def parse_file(file):\n    lines = []\n    for line in file:\n        line = line.rstrip('\\n')\n        if line == '%%':\n            yield from parse_item(lines)\n            lines.clear()\n        elif line.startswith('  '):\n            lines[-1] += line[1:]\n        else:\n            lines.append(line)\n    yield from parse_item(lines)",
    "docstring": "Take an open file containing the IANA subtag registry, and yield a\n    dictionary of information for each subtag it describes."
  },
  {
    "code": "def lookup(alias):\n    if alias in matchers:\n        return matchers[alias]\n    else:\n        norm = normalize(alias)\n        if norm in normalized:\n            alias = normalized[norm]\n            return matchers[alias]\n    if -1 != alias.find('_'):\n        norm = normalize(alias).replace('_', '')\n        return lookup(norm)\n    return None",
    "docstring": "Tries to find a matcher callable associated to the given alias. If\n        an exact match does not exists it will try normalizing it and even\n        removing underscores to find one."
  },
  {
    "code": "def assign_ranks_to_grid(grid, ranks):\n    assignments = deepcopy(grid)\n    ranks[\"0b0\"] = 0\n    ranks[\"-0b1\"] = -1\n    for i in range(len(grid)):\n        for j in range(len(grid[i])):\n            if type(grid[i][j]) is list:\n                for k in range(len(grid[i][j])):\n                    assignments[i][j][k] = ranks[grid[i][j][k]]\n            else:\n                assignments[i][j] = ranks[grid[i][j]]\n    return assignments",
    "docstring": "Takes a 2D array of binary numbers represented as strings and a dictionary\n    mapping binary strings to integers representing the rank of the cluster\n    they belong to, and returns a grid in which each binary number has been\n    replaced with the rank of its cluster."
  },
  {
    "code": "def reset(self):\n        self.v = self.c\n        self.u = self.b * self.v\n        self.fired = 0.0\n        self.current = self.bias",
    "docstring": "Resets all state variables."
  },
  {
    "code": "def init_app(self, app, path='templates.yaml'):\n        if self._route is None:\n            raise TypeError(\"route is a required argument when app is not None\")\n        self.app = app\n        app.ask = self\n        app.add_url_rule(self._route, view_func=self._flask_view_func, methods=['POST'])\n        app.jinja_loader = ChoiceLoader([app.jinja_loader, YamlLoader(app, path)])",
    "docstring": "Initializes Ask app by setting configuration variables, loading templates, and maps Ask route to a flask view.\n\n        The Ask instance is given the following configuration variables by calling on Flask's configuration:\n\n        `ASK_APPLICATION_ID`:\n\n            Turn on application ID verification by setting this variable to an application ID or a\n            list of allowed application IDs. By default, application ID verification is disabled and a\n            warning is logged. This variable should be set in production to ensure\n            requests are being sent by the applications you specify.\n            Default: None\n\n        `ASK_VERIFY_REQUESTS`:\n\n            Enables or disables Alexa request verification, which ensures requests sent to your skill\n            are from Amazon's Alexa service. This setting should not be disabled in production.\n            It is useful for mocking JSON requests in automated tests.\n            Default: True\n\n        `ASK_VERIFY_TIMESTAMP_DEBUG`:\n\n            Turn on request timestamp verification while debugging by setting this to True.\n            Timestamp verification helps mitigate against replay attacks. It relies on the system clock\n            being synchronized with an NTP server. This setting should not be enabled in production.\n            Default: False\n\n        `ASK_PRETTY_DEBUG_LOGS`:\n\n            Add tabs and linebreaks to the Alexa request and response printed to the debug log.\n            This improves readability when printing to the console, but breaks formatting when logging to CloudWatch.\n            Default: False"
  },
  {
    "code": "def extended_capabilities(self):\n        buf = (ctypes.c_uint8 * 32)()\n        self._dll.JLINKARM_GetEmuCapsEx(buf, 32)\n        return list(buf)",
    "docstring": "Gets the capabilities of the connected emulator as a list.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n\n        Returns:\n          List of 32 integers which define the extended capabilities based on\n          their value and index within the list."
  },
  {
    "code": "def _do_lumping(self):\n        right_eigenvectors = self.right_eigenvectors_[:, :self.n_macrostates]\n        index = index_search(right_eigenvectors)\n        A = right_eigenvectors[index, :]\n        A = inv(A)\n        A = fill_A(A, right_eigenvectors)\n        if self.do_minimization:\n            A = self._optimize_A(A)\n        self.A_ = fill_A(A, right_eigenvectors)\n        self.chi_ = dot(right_eigenvectors, self.A_)\n        self.microstate_mapping_ = np.argmax(self.chi_, 1)",
    "docstring": "Perform PCCA+ algorithm by optimizing transformation matrix A.\n\n        Creates the following member variables:\n        -------\n        A : ndarray\n            The transformation matrix.\n        chi : ndarray\n            The membership matrix\n        microstate_mapping : ndarray\n            Mapping from microstates to macrostates."
  },
  {
    "code": "def as_stream(self):\n        if not self.singular:\n            raise ArgumentError(\"Attempted to convert a non-singular selector to a data stream, it matches multiple\", selector=self)\n        return DataStream(self.match_type, self.match_id, self.match_spec == DataStreamSelector.MatchSystemOnly)",
    "docstring": "Convert this selector to a DataStream.\n\n        This function will only work if this is a singular selector that\n        matches exactly one DataStream."
  },
  {
    "code": "def oracle_approximating(self):\n        X = np.nan_to_num(self.X.values)\n        shrunk_cov, self.delta = covariance.oas(X)\n        return self.format_and_annualise(shrunk_cov)",
    "docstring": "Calculate the Oracle Approximating Shrinkage estimate\n\n        :return: shrunk sample covariance matrix\n        :rtype: np.ndarray"
  },
  {
    "code": "def create_supercut_in_batches(composition, outputfile, padding):\n    total_clips = len(composition)\n    start_index = 0\n    end_index = BATCH_SIZE\n    batch_comp = []\n    while start_index < total_clips:\n        filename = outputfile + '.tmp' + str(start_index) + '.mp4'\n        try:\n            create_supercut(composition[start_index:end_index], filename, padding)\n            batch_comp.append(filename)\n            gc.collect()\n            start_index += BATCH_SIZE\n            end_index += BATCH_SIZE\n        except:\n            start_index += BATCH_SIZE\n            end_index += BATCH_SIZE\n            next\n    clips = [VideoFileClip(filename) for filename in batch_comp]\n    video = concatenate(clips)\n    video.to_videofile(outputfile, codec=\"libx264\", temp_audiofile='temp-audio.m4a', remove_temp=True, audio_codec='aac')\n    for filename in batch_comp:\n        os.remove(filename)\n    cleanup_log_files(outputfile)",
    "docstring": "Create & concatenate video clips in groups of size BATCH_SIZE and output\n    finished video file to output directory."
  },
  {
    "code": "def updated_dimensions(self):\n        return [(\"ntime\", args.ntime),\n                (\"nchan\", args.nchan),\n                (\"na\", args.na),\n                (\"npsrc\", len(lm_coords))]",
    "docstring": "Inform montblanc about dimension sizes"
  },
  {
    "code": "def string_to_response(content_type):\n    def outer_wrapper(req_function):\n        @wraps(req_function)\n        def newreq(request, *args, **kwargs):\n            try:\n                outp = req_function(request, *args, **kwargs)\n                if issubclass(outp.__class__, HttpResponse):\n                    response = outp\n                else:\n                    response = HttpResponse()\n                    response.write(outp)\n                    response['Content-Length'] = str(len(response.content))\n                response['Content-Type'] = content_type\n            except HttpBadRequestException as bad_request:\n                response = HttpResponseBadRequest(bad_request.message)\n            return response\n        return newreq\n    return outer_wrapper",
    "docstring": "Wrap a view-like function that returns a string and marshalls it into an\n    HttpResponse with the given Content-Type\n    If the view raises an HttpBadRequestException, it will be converted into\n    an HttpResponseBadRequest."
  },
  {
    "code": "def handle_update(self, args):\n    component = int(args[0])\n    action = int(args[1])\n    params = [int(x) for x in args[2:]]\n    _LOGGER.debug(\"Updating %d(%s): c=%d a=%d params=%s\" % (\n        self._integration_id, self._name, component, action, params))\n    if component in self._components:\n      return self._components[component].handle_update(action, params)\n    return False",
    "docstring": "The callback invoked by the main event loop if there's an event from this keypad."
  },
  {
    "code": "def all(cls, client, **kwargs):\n        max_date = kwargs['max_date'] if 'max_date' in kwargs else None\n        max_fetches = \\\n            kwargs['max_fetches'] if 'max_fetches' in kwargs else None\n        url = 'https://api.robinhood.com/options/positions/'\n        params = {}\n        data = client.get(url, params=params)\n        results = data[\"results\"]\n        if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]):\n            return results\n        if max_fetches == 1:\n            return results\n        fetches = 1\n        while data[\"next\"]:\n            fetches = fetches + 1\n            data = client.get(data[\"next\"])\n            results.extend(data[\"results\"])\n            if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]):\n                return results\n            if max_fetches and (fetches >= max_fetches):\n                return results\n        return results",
    "docstring": "fetch all option positions"
  },
  {
    "code": "def get_redshift(self, dist):\n        dist, input_is_array = ensurearray(dist)\n        try:\n            zs = self.nearby_d2z(dist)\n        except TypeError:\n            self.setup_interpolant()\n            zs = self.nearby_d2z(dist)\n        replacemask = numpy.isnan(zs)\n        if replacemask.any():\n            zs[replacemask] = self.faraway_d2z(dist[replacemask])\n            replacemask = numpy.isnan(zs)\n        if replacemask.any():\n            if not (dist > 0.).all() and numpy.isfinite(dist).all():\n                raise ValueError(\"distance must be finite and > 0\")\n            zs[replacemask] = _redshift(dist[replacemask],\n                                        cosmology=self.cosmology)\n        return formatreturn(zs, input_is_array)",
    "docstring": "Returns the redshift for the given distance."
  },
  {
    "code": "def phase_type(self, value):\n        self._params.phase_type = value\n        self._overwrite_lock.disable()",
    "docstring": "compresses the waveform horizontally; one of\n        ``\"normal\"``, ``\"resync\"``, ``\"resync2\"``"
  },
  {
    "code": "def product(target, prop1, prop2, **kwargs):\n    r\n    value = target[prop1]*target[prop2]\n    for item in kwargs.values():\n        value *= target[item]\n    return value",
    "docstring": "r\"\"\"\n    Calculates the product of multiple property values\n\n    Parameters\n    ----------\n    target : OpenPNM Object\n        The object which this model is associated with. This controls the\n        length of the calculated array, and also provides access to other\n        necessary properties.\n\n    prop1 : string\n        The name of the first argument\n\n    prop2 : string\n        The name of the second argument\n\n    Notes\n    -----\n    Additional properties can be specified beyond just ``prop1`` and ``prop2``\n    by including additional arguments in the function call (i.e. ``prop3 =\n    'pore.foo'``)."
  },
  {
    "code": "def getPeers(self, offset=0, limit=1000):\n        select = models.Peer.select().order_by(\n            models.Peer.url).limit(limit).offset(offset)\n        return [peers.Peer(p.url, record=p) for p in select]",
    "docstring": "Get the list of peers using an SQL offset and limit. Returns a list\n        of peer datamodel objects in a list."
  },
  {
    "code": "def prepare_sort_key(self):\n        if isinstance(self.convert_type, str):\n            try:\n                app_name, model_name = self.convert_type.split('.')\n            except ValueError:\n                raise ImproperlyConfigured('\"{}\" is not a valid converter type. String-based converter types must be specified in \"app.Model\" format.'.format(self.convert_type))\n            try:\n                self.convert_type = apps.get_model(app_name, model_name)\n            except LookupError as e:\n                raise ImproperlyConfigured('\"{}\" is not a valid model name. {}'.format(self.convert_type, e))\n        self.sort_key = ( -1 * len(inspect.getmro(self.convert_type)), -1 * self.source_order )",
    "docstring": "Triggered by view_function._sort_converters when our sort key should be created.\n        This can't be called in the constructor because Django models might not be ready yet."
  },
  {
    "code": "def list_streams(self, types=[], inactive=False):\n        req_hook = 'pod/v1/streams/list'\n        json_query = {\n                       \"streamTypes\": types,\n                       \"includeInactiveStreams\": inactive\n                     }\n        req_args = json.dumps(json_query)\n        status_code, response = self.__rest__.POST_query(req_hook, req_args)\n        self.logger.debug('%s: %s' % (status_code, response))\n        return status_code, response",
    "docstring": "list user streams"
  },
  {
    "code": "def _evaluate_usecols(usecols, names):\n    if callable(usecols):\n        return {i for i, name in enumerate(names) if usecols(name)}\n    return usecols",
    "docstring": "Check whether or not the 'usecols' parameter\n    is a callable.  If so, enumerates the 'names'\n    parameter and returns a set of indices for\n    each entry in 'names' that evaluates to True.\n    If not a callable, returns 'usecols'."
  },
  {
    "code": "def to_flat(coord):\n    if coord is None:\n        return go.N * go.N\n    return go.N * coord[0] + coord[1]",
    "docstring": "Converts from a Minigo coordinate to a flattened coordinate."
  },
  {
    "code": "def remove(path):\n    if not os.path.exists(path):\n        return\n    if os.path.isdir(path):\n        return shutil.rmtree(path)\n    if os.path.isfile(path):\n        return os.remove(path)",
    "docstring": "Wrapper that switches between os.remove and shutil.rmtree depending on\n    whether the provided path is a file or directory."
  },
  {
    "code": "def as_minimized(values: List[float], maximized: List[bool]) -> List[float]:\n    return [v * -1. if m else v for v, m in zip(values, maximized)]",
    "docstring": "Return vector values as minimized"
  },
  {
    "code": "def load_data():\n    boston = load_boston()\n    X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=99, test_size=0.25)\n    ss_X = StandardScaler()\n    ss_y = StandardScaler()\n    X_train = ss_X.fit_transform(X_train)\n    X_test = ss_X.transform(X_test)\n    y_train = ss_y.fit_transform(y_train[:, None])[:,0]\n    y_test = ss_y.transform(y_test[:, None])[:,0]\n    return X_train, X_test, y_train, y_test",
    "docstring": "Load dataset, use boston dataset"
  },
  {
    "code": "def _should_ignore(self, path):\n        for ignore in self.options.ignores:\n            if fnmatch.fnmatch(path, ignore):\n                return True\n        return False",
    "docstring": "Return True iff path should be ignored."
  },
  {
    "code": "def preview(self, obj, request=None):\n        source = self.get_thumbnail_source(obj)\n        if source:\n            try:\n                from easy_thumbnails.files import get_thumbnailer\n            except ImportError:\n                logger.warning(\n                    _(\n                        '`easy_thumbnails` is not installed and required for '\n                        'icekit.admin_tools.mixins.ThumbnailAdminMixin'\n                    )\n                )\n                return ''\n            try:\n                thumbnailer = get_thumbnailer(source)\n                thumbnail = thumbnailer.get_thumbnail(self.thumbnail_options)\n                return '<img class=\"thumbnail\" src=\"{0}\" />'.format(\n                    thumbnail.url)\n            except Exception as ex:\n                logger.warning(\n                    _(u'`easy_thumbnails` failed to generate a thumbnail image'\n                      u' for {0}'.format(source)))\n                if self.thumbnail_show_exceptions:\n                    return 'Thumbnail exception: {0}'.format(ex)\n        return ''",
    "docstring": "Generate the HTML to display for the image.\n\n        :param obj: An object with a thumbnail_field defined.\n        :return: HTML for image display."
  },
  {
    "code": "def _CreateShapePointFolder(self, shapes_folder, shape):\n    folder_name = shape.shape_id + ' Shape Points'\n    folder = self._CreateFolder(shapes_folder, folder_name, visible=False)\n    for (index, (lat, lon, dist)) in enumerate(shape.points):\n      placemark = self._CreatePlacemark(folder, str(index+1))\n      point = ET.SubElement(placemark, 'Point')\n      coordinates = ET.SubElement(point, 'coordinates')\n      coordinates.text = '%.6f,%.6f' % (lon, lat)\n    return folder",
    "docstring": "Create a KML Folder containing all the shape points in a shape.\n\n    The folder contains placemarks for each shapepoint.\n\n    Args:\n      shapes_folder: A KML Shape Folder ElementTree.Element instance\n      shape: The shape to plot.\n\n    Returns:\n      The Folder ElementTree.Element instance or None."
  },
  {
    "code": "def any_match(self, urls):\n        return any(urlparse(u).hostname in self for u in urls)",
    "docstring": "Check if any of the given URLs has a matching host.\n\n        :param urls: an iterable containing URLs\n        :returns: True if any host has a listed match\n        :raises InvalidURLError: if there are any invalid URLs in\n        the sequence"
  },
  {
    "code": "def QA_fetch_get_sh_margin(date):\n    if date in trade_date_sse:\n        data= pd.read_excel(_sh_url.format(QA_util_date_str2int\n                                            (date)), 1).assign(date=date).assign(sse='sh')             \n        data.columns=['code','name','leveraged_balance','leveraged_buyout','leveraged_payoff','margin_left','margin_sell','margin_repay','date','sse']\n        return data\n    else:\n        pass",
    "docstring": "return shanghai margin data\n\n    Arguments:\n        date {str YYYY-MM-DD} -- date format\n\n    Returns:\n        pandas.DataFrame -- res for margin data"
  },
  {
    "code": "def list_resources(self, device_id):\n        api = self._get_api(mds.EndpointsApi)\n        return [Resource(r) for r in api.get_endpoint_resources(device_id)]",
    "docstring": "List all resources registered to a connected device.\n\n        .. code-block:: python\n\n            >>> for r in api.list_resources(device_id):\n                    print(r.name, r.observable, r.uri)\n            None,True,/3/0/1\n            Update,False,/5/0/3\n            ...\n\n        :param str device_id: The ID of the device (Required)\n        :returns: A list of :py:class:`Resource` objects for the device\n        :rtype: list"
  },
  {
    "code": "def file_handler(self, handler_type, path, prefixed_path, source_storage):\n        if self.faster:\n            if prefixed_path not in self.found_files:\n                self.found_files[prefixed_path] = (source_storage, path)\n            self.task_queue.put({\n                'handler_type': handler_type,\n                'path': path,\n                'prefixed_path': prefixed_path,\n                'source_storage': source_storage\n            })\n            self.counter += 1\n        else:\n            if handler_type == 'link':\n                super(Command, self).link_file(path, prefixed_path, source_storage)\n            else:\n                super(Command, self).copy_file(path, prefixed_path, source_storage)",
    "docstring": "Create a dict with all kwargs of the `copy_file` or `link_file` method of the super class and add it to\n        the queue for later processing."
  },
  {
    "code": "def login_form_factory(Form, app):\n    class LoginForm(Form):\n        def __init__(self, *args, **kwargs):\n            super(LoginForm, self).__init__(*args, **kwargs)\n            self.remember.data = False\n    return LoginForm",
    "docstring": "Return extended login form."
  },
  {
    "code": "def purge(self):\n        while not self.stopped.isSet():\n            self.stopped.wait(timeout=defines.EXCHANGE_LIFETIME)\n            self._messageLayer.purge()",
    "docstring": "Clean old transactions"
  },
  {
    "code": "def delete(self):\n        self.bucket.size -= self.size\n        Part.query_by_multipart(self).delete()\n        self.query.filter_by(upload_id=self.upload_id).delete()",
    "docstring": "Delete a multipart object."
  },
  {
    "code": "def process_xml(xml_str):\n    try:\n        tree = ET.XML(xml_str, parser=UTB())\n    except ET.ParseError as e:\n        logger.error('Could not parse XML string')\n        logger.error(e)\n        return None\n    sp = _process_elementtree(tree)\n    return sp",
    "docstring": "Return processor with Statements extracted from a Sparser XML.\n\n    Parameters\n    ----------\n    xml_str : str\n        The XML string obtained by reading content with Sparser, using the\n        'xml' output mode.\n\n    Returns\n    -------\n    sp : SparserXMLProcessor\n        A SparserXMLProcessor which has extracted Statements as its\n        statements attribute."
  },
  {
    "code": "async def deactivate(cls, access_key: str) -> dict:\n        q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + \\\n            '  modify_keypair(access_key: $access_key, props: $input) {' \\\n            '    ok msg' \\\n            '  }' \\\n            '}'\n        variables = {\n            'access_key': access_key,\n            'input': {\n                'is_active': False,\n                'is_admin': None,\n                'resource_policy': None,\n                'rate_limit': None,\n            },\n        }\n        rqst = Request(cls.session, 'POST', '/admin/graphql')\n        rqst.set_json({\n            'query': q,\n            'variables': variables,\n        })\n        async with rqst.fetch() as resp:\n            data = await resp.json()\n            return data['modify_keypair']",
    "docstring": "Deactivates this keypair.\n        Deactivated keypairs cannot make any API requests\n        unless activated again by an administrator.\n        You need an admin privilege for this operation."
  },
  {
    "code": "def tween(self, t):\n        if t is None:\n            return None\n        if self.method in self.method_to_tween:\n            return self.method_to_tween[self.method](t)\n        elif self.method in self.method_1param:\n            return self.method_1param[self.method](t, self.param1)\n        elif self.method in self.method_2param:\n            return self.method_2param[self.method](t, self.param1, self.param2)\n        else:\n            raise Exception(\"Unsupported tween method {0}\".format(self.method))",
    "docstring": "t is number between 0 and 1 to indicate how far the tween has progressed"
  },
  {
    "code": "def _get_prepped_model_field(model_obj, field):\n    field = model_obj._meta.get_field(field)\n    value = field.get_db_prep_save(getattr(model_obj, field.attname), connection)\n    return value",
    "docstring": "Gets the value of a field of a model obj that is prepared for the db."
  },
  {
    "code": "def _update_version(connection, version):\n    if connection.engine.name == 'sqlite':\n        connection.execute('PRAGMA user_version = {}'.format(version))\n    elif connection.engine.name == 'postgresql':\n        connection.execute(DDL('CREATE SCHEMA IF NOT EXISTS {};'.format(POSTGRES_SCHEMA_NAME)))\n        connection.execute(DDL('CREATE SCHEMA IF NOT EXISTS {};'.format(POSTGRES_PARTITION_SCHEMA_NAME)))\n        connection.execute('CREATE TABLE IF NOT EXISTS {}.user_version(version INTEGER NOT NULL);'\n                           .format(POSTGRES_SCHEMA_NAME))\n        if connection.execute('SELECT * FROM {}.user_version;'.format(POSTGRES_SCHEMA_NAME)).fetchone():\n            connection.execute('UPDATE {}.user_version SET version = {};'\n                               .format(POSTGRES_SCHEMA_NAME, version))\n        else:\n            connection.execute('INSERT INTO {}.user_version (version) VALUES ({})'\n                               .format(POSTGRES_SCHEMA_NAME, version))\n    else:\n        raise DatabaseMissingError('Do not know how to migrate {} engine.'\n                                   .format(connection.engine.driver))",
    "docstring": "Updates version in the db to the given version.\n\n    Args:\n        connection (sqlalchemy connection): sqlalchemy session where to update version.\n        version (int): version of the migration."
  },
  {
    "code": "def create_criteria(cls, query):\n        criteria = []\n        for name, value in query.items():\n            if isinstance(value, list):\n                for inner_value in value:\n                    criteria += cls.create_criteria({name: inner_value})\n            else:\n                criteria.append({\n                    'criteria': {\n                        'field': name,\n                        'value': value,\n                    },\n                })\n        return criteria or None",
    "docstring": "Return a criteria from a dictionary containing a query.\n\n        Query should be a dictionary, keyed by field name. If the value is\n        a list, it will be divided into multiple criteria as required."
  },
  {
    "code": "def score(self, periods=None):\n        periods = np.asarray(periods)\n        return self._score(periods.ravel()).reshape(periods.shape)",
    "docstring": "Compute the periodogram for the given period or periods\n\n        Parameters\n        ----------\n        periods : float or array_like\n            Array of periods at which to compute the periodogram.\n\n        Returns\n        -------\n        scores : np.ndarray\n            Array of normalized powers (between 0 and 1) for each period.\n            Shape of scores matches the shape of the provided periods."
  },
  {
    "code": "def to_data_rows(self, brains):\n        fields = self.get_field_names()\n        return map(lambda brain: self.get_data_record(brain, fields), brains)",
    "docstring": "Returns a list of dictionaries representing the values of each brain"
  },
  {
    "code": "def _most_restrictive(date_elems):\n    most_index = len(DATE_ELEMENTS)\n    for date_elem in date_elems:\n        if date_elem in DATE_ELEMENTS and DATE_ELEMENTS.index(date_elem) < most_index:\n            most_index = DATE_ELEMENTS.index(date_elem)\n    if most_index < len(DATE_ELEMENTS):\n        return DATE_ELEMENTS[most_index]\n    else:\n        raise KeyError('No least restrictive date element found')",
    "docstring": "Return the date_elem that has the most restrictive range from date_elems"
  },
  {
    "code": "def sensor(self, name, config=None,\n               inactive_sensor_expiration_time_seconds=sys.maxsize,\n               parents=None):\n        sensor = self.get_sensor(name)\n        if sensor:\n            return sensor\n        with self._lock:\n            sensor = self.get_sensor(name)\n            if not sensor:\n                sensor = Sensor(self, name, parents, config or self.config,\n                                inactive_sensor_expiration_time_seconds)\n                self._sensors[name] = sensor\n                if parents:\n                    for parent in parents:\n                        children = self._children_sensors.get(parent)\n                        if not children:\n                            children = []\n                            self._children_sensors[parent] = children\n                        children.append(sensor)\n                logger.debug('Added sensor with name %s', name)\n            return sensor",
    "docstring": "Get or create a sensor with the given unique name and zero or\n        more parent sensors. All parent sensors will receive every value\n        recorded with this sensor.\n\n        Arguments:\n            name (str): The name of the sensor\n            config (MetricConfig, optional): A default configuration to use\n                for this sensor for metrics that don't have their own config\n            inactive_sensor_expiration_time_seconds (int, optional):\n                If no value if recorded on the Sensor for this duration of\n                time, it is eligible for removal\n            parents (list of Sensor): The parent sensors\n\n        Returns:\n            Sensor: The sensor that is created"
  },
  {
    "code": "def polls_slug_get(self, slug, **kwargs):\n        kwargs['_return_http_data_only'] = True\n        if kwargs.get('callback'):\n            return self.polls_slug_get_with_http_info(slug, **kwargs)\n        else:\n            (data) = self.polls_slug_get_with_http_info(slug, **kwargs)\n            return data",
    "docstring": "Poll\n        A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question.  Pollster editors don't include every question when they enter Polls, and they don't necessarily enter every subpopulation for the responses they _do_ enter. They make editorial decisions about which questions belong in the database. \n\n        This method makes a synchronous HTTP request by default. To make an\n        asynchronous HTTP request, please define a `callback` function\n        to be invoked when receiving the response.\n        >>> def callback_function(response):\n        >>>     pprint(response)\n        >>>\n        >>> thread = api.polls_slug_get(slug, callback=callback_function)\n\n        :param callback function: The callback function\n            for asynchronous request. (optional)\n        :param str slug: Unique Poll identifier. For example: `gallup-26892`. (required)\n        :return: Poll\n                 If the method is called asynchronously,\n                 returns the request thread."
  },
  {
    "code": "def encrypt(self, plaintext_data_key, encryption_context):\n        if self.wrapping_algorithm.encryption_type is EncryptionType.ASYMMETRIC:\n            if self.wrapping_key_type is EncryptionKeyType.PRIVATE:\n                encrypted_key = self._wrapping_key.public_key().encrypt(\n                    plaintext=plaintext_data_key, padding=self.wrapping_algorithm.padding\n                )\n            else:\n                encrypted_key = self._wrapping_key.encrypt(\n                    plaintext=plaintext_data_key, padding=self.wrapping_algorithm.padding\n                )\n            return EncryptedData(iv=None, ciphertext=encrypted_key, tag=None)\n        serialized_encryption_context = serialize_encryption_context(encryption_context=encryption_context)\n        iv = os.urandom(self.wrapping_algorithm.algorithm.iv_len)\n        return encrypt(\n            algorithm=self.wrapping_algorithm.algorithm,\n            key=self._derived_wrapping_key,\n            plaintext=plaintext_data_key,\n            associated_data=serialized_encryption_context,\n            iv=iv,\n        )",
    "docstring": "Encrypts a data key using a direct wrapping key.\n\n        :param bytes plaintext_data_key: Data key to encrypt\n        :param dict encryption_context: Encryption context to use in encryption\n        :returns: Deserialized object containing encrypted key\n        :rtype: aws_encryption_sdk.internal.structures.EncryptedData"
  },
  {
    "code": "def post(self, request, *args, **kwargs):\n        self.object = self.get_object()\n        self.object.content = request.POST['content']\n        self.object.title = request.POST['title']\n        self.object = self._mark_html_fields_as_safe(self.object)\n        context = self.get_context_data(object=self.object)\n        return self.render_to_response(context, content_type=self.get_mimetype())",
    "docstring": "Accepts POST requests, and substitute the data in for the page's attributes."
  },
  {
    "code": "def update_application_metadata(template, application_id, sar_client=None):\n    if not template or not application_id:\n        raise ValueError('Require SAM template and application ID to update application metadata')\n    if not sar_client:\n        sar_client = boto3.client('serverlessrepo')\n    template_dict = _get_template_dict(template)\n    app_metadata = get_app_metadata(template_dict)\n    request = _update_application_request(app_metadata, application_id)\n    sar_client.update_application(**request)",
    "docstring": "Update the application metadata.\n\n    :param template: Content of a packaged YAML or JSON SAM template\n    :type template: str_or_dict\n    :param application_id: The Amazon Resource Name (ARN) of the application\n    :type application_id: str\n    :param sar_client: The boto3 client used to access SAR\n    :type sar_client: boto3.client\n    :raises ValueError"
  },
  {
    "code": "def _create_logger(name='did', level=None):\n        logger = logging.getLogger(name)\n        handler = logging.StreamHandler()\n        handler.setFormatter(Logging.ColoredFormatter())\n        logger.addHandler(handler)\n        for level in Logging.LEVELS:\n            setattr(logger, level, getattr(logging, level))\n        logger.DATA = LOG_DATA\n        logger.DETAILS = LOG_DETAILS\n        logger.ALL = LOG_ALL\n        logger.details = lambda message: logger.log(\n            LOG_DETAILS, message)\n        logger.data = lambda message: logger.log(\n            LOG_DATA, message)\n        logger.all = lambda message: logger.log(\n            LOG_ALL, message)\n        return logger",
    "docstring": "Create did logger"
  },
  {
    "code": "def by_user_and_perm(cls, user_id, perm_name, db_session=None):\n        db_session = get_db_session(db_session)\n        query = db_session.query(cls.model).filter(cls.model.user_id == user_id)\n        query = query.filter(cls.model.perm_name == perm_name)\n        return query.first()",
    "docstring": "return by user and permission name\n\n        :param user_id:\n        :param perm_name:\n        :param db_session:\n        :return:"
  },
  {
    "code": "def ensure_header(self, header: BlockHeader=None) -> BlockHeader:\n        if header is None:\n            head = self.get_canonical_head()\n            return self.create_header_from_parent(head)\n        else:\n            return header",
    "docstring": "Return ``header`` if it is not ``None``, otherwise return the header\n        of the canonical head."
  },
  {
    "code": "def set_agent(self, agent):\n        self.agent = agent\n        self.queue = asyncio.Queue(loop=self.agent.loop)\n        self.presence = agent.presence\n        self.web = agent.web",
    "docstring": "Links behaviour with its owner agent\n\n        Args:\n          agent (spade.agent.Agent): the agent who owns the behaviour"
  },
  {
    "code": "def change_db_user_password(username, password):\n    sql = \"ALTER USER %s WITH PASSWORD '%s'\" % (username, password)\n    excute_query(sql, use_sudo=True)",
    "docstring": "Change a db user's password."
  },
  {
    "code": "def project_dev_requirements():\n    from peltak.core import conf\n    from peltak.core import shell\n    for dep in sorted(conf.requirements):\n        shell.cprint(dep)",
    "docstring": "List requirements for peltak commands configured for the project.\n\n    This list is dynamic and depends on the commands you have configured in\n    your project's pelconf.yaml. This will be the combined list of packages\n    needed to be installed in order for all the configured commands to work."
  },
  {
    "code": "def setup_function(self):\n        log.options.LogOptions.set_stderr_log_level('google:INFO')\n        if app.get_options().debug:\n            log.options.LogOptions.set_stderr_log_level('google:DEBUG')\n        if not app.get_options().build_root:\n            app.set_option('build_root', os.path.join(\n                app.get_options().butcher_basedir, 'build'))\n        self.buildroot = app.get_options().build_root\n        if not os.path.exists(self.buildroot):\n            os.makedirs(self.buildroot)\n        if app.get_options().disable_cache_fetch:\n            self.options['cache_fetch'] = False\n        if app.get_options().disable_hardlinks:\n            base.BaseBuilder.linkfiles = False",
    "docstring": "Runs prior to the global main function."
  },
  {
    "code": "def fwd_chunk(self):\n        raise NotImplementedError(\"%s not implemented for %s\" % (self.fwd_chunk.__func__.__name__,\n                                                                 self.__class__.__name__))",
    "docstring": "Returns the chunk following this chunk in the list of free chunks."
  },
  {
    "code": "def relabel(self, qubits: Qubits) -> 'Channel':\n        chan = copy(self)\n        chan.vec = chan.vec.relabel(qubits)\n        return chan",
    "docstring": "Return a copy of this channel with new qubits"
  },
  {
    "code": "def _filter_headers(self):\n        headers = {}\n        for user in self.usernames:\n            headers[\"fedora_messaging_user_{}\".format(user)] = True\n        for package in self.packages:\n            headers[\"fedora_messaging_rpm_{}\".format(package)] = True\n        for container in self.containers:\n            headers[\"fedora_messaging_container_{}\".format(container)] = True\n        for module in self.modules:\n            headers[\"fedora_messaging_module_{}\".format(module)] = True\n        for flatpak in self.flatpaks:\n            headers[\"fedora_messaging_flatpak_{}\".format(flatpak)] = True\n        return headers",
    "docstring": "Add headers designed for filtering messages based on objects.\n\n        Returns:\n            dict: Filter-related headers to be combined with the existing headers"
  },
  {
    "code": "def getShape3D(self, includeJunctions=False):\n        if includeJunctions and not self._edge.isSpecial():\n            if self._shapeWithJunctions3D is None:\n                self._shapeWithJunctions3D = addJunctionPos(self._shape3D,\n                                                            self._edge.getFromNode(\n                                                            ).getCoord3D(),\n                                                            self._edge.getToNode().getCoord3D())\n            return self._shapeWithJunctions3D\n        return self._shape3D",
    "docstring": "Returns the shape of the lane in 3d.\n\n        This function returns the shape of the lane, as defined in the net.xml\n        file. The returned shape is a list containing numerical\n        3-tuples representing the x,y,z coordinates of the shape points\n        where z defaults to zero.\n\n        For includeJunction=True the returned list will contain\n        additionally the coords (x,y,z) of the fromNode of the\n        corresponding edge as first element and the coords (x,y,z)\n        of the toNode as last element.\n\n        For internal lanes, includeJunctions is ignored and the unaltered\n        shape of the lane is returned."
  },
  {
    "code": "def offline(f):\n    @click.pass_context\n    @verbose\n    def new_func(ctx, *args, **kwargs):\n        ctx.obj[\"offline\"] = True\n        ctx.bitshares = BitShares(**ctx.obj)\n        ctx.blockchain = ctx.bitshares\n        ctx.bitshares.set_shared_instance()\n        return ctx.invoke(f, *args, **kwargs)\n    return update_wrapper(new_func, f)",
    "docstring": "This decorator allows you to access ``ctx.bitshares`` which is\n        an instance of BitShares with ``offline=True``."
  },
  {
    "code": "def managepy(cmd, extra=None):\n    extra = extra.split() if extra else []\n    run_django_cli(['invoke', cmd] + extra)",
    "docstring": "Run manage.py using this component's specific Django settings"
  },
  {
    "code": "def _format_extname(self, ext):\n        if ext is None:\n            outs = ext\n        else:\n            outs = '{0},{1}'.format(ext[0], ext[1])\n        return outs",
    "docstring": "Pretty print given extension name and number tuple."
  },
  {
    "code": "def main(argv):\n    _, black_model, white_model = argv\n    utils.ensure_dir_exists(FLAGS.eval_sgf_dir)\n    play_match(black_model, white_model, FLAGS.num_evaluation_games, FLAGS.eval_sgf_dir)",
    "docstring": "Play matches between two neural nets."
  },
  {
    "code": "def from_blob(cls, s):\n        atom_str, edge_str = s.split()\n        numbers = np.array([int(s) for s in atom_str.split(\",\")])\n        edges = []\n        orders = []\n        for s in edge_str.split(\",\"):\n            i, j, o = (int(w) for w in s.split(\"_\"))\n            edges.append((i, j))\n            orders.append(o)\n        return cls(edges, numbers, np.array(orders))",
    "docstring": "Construct a molecular graph from the blob representation"
  },
  {
    "code": "def _can_be_double(x):\n    return ((np.issubdtype(x.dtype, np.floating) and\n            x.dtype.itemsize <= np.dtype(float).itemsize) or\n            (np.issubdtype(x.dtype, np.signedinteger) and\n            np.can_cast(x, float)))",
    "docstring": "Return if the array can be safely converted to double.\n\n    That happens when the dtype is a float with the same size of\n    a double or narrower, or when is an integer that can be safely\n    converted to double (if the roundtrip conversion works)."
  },
  {
    "code": "def _collect_layer_output_min_max(mod, data, include_layer=None,\n                                  max_num_examples=None, logger=None):\n    collector = _LayerOutputMinMaxCollector(include_layer=include_layer, logger=logger)\n    num_examples = _collect_layer_statistics(mod, data, collector, max_num_examples, logger)\n    return collector.min_max_dict, num_examples",
    "docstring": "Collect min and max values from layer outputs and save them in\n    a dictionary mapped by layer names."
  },
  {
    "code": "def cors(*args, **kwargs):\n    def decorator(fn):\n        cors_fn = flask_cors.cross_origin(automatic_options=False, *args, **kwargs)\n        if inspect.isclass(fn):\n            apply_function_to_members(fn, cors_fn)\n        else:\n            return cors_fn(fn)\n        return fn\n    return decorator",
    "docstring": "A wrapper around flask-cors cross_origin, to also act on classes\n\n    **An extra note about cors, a response must be available before the\n    cors is applied. Dynamic return is applied after the fact, so use the\n    decorators, json, xml, or return self.render() for txt/html\n    ie:\n    @cors()\n    class Index(Mocha):\n        def index(self):\n            return self.render()\n\n        @json\n        def json(self):\n            return {}\n\n    class Index2(Mocha):\n        def index(self):\n            return self.render()\n\n        @cors()\n        @json\n        def json(self):\n            return {}\n\n\n    :return:"
  },
  {
    "code": "def _file_local_or_remote(f, get_retriever):\n    if os.path.exists(f):\n        return f\n    integration, config = get_retriever.integration_and_config(f)\n    if integration:\n        return integration.file_exists(f, config)",
    "docstring": "Check for presence of a local or remote file."
  },
  {
    "code": "def convert_to_shape(x):\n  if x is None:\n    return None\n  if isinstance(x, Shape):\n    return x\n  if isinstance(x, str):\n    x = _parse_string_to_list_of_pairs(x, seconds_to_int=True)\n  return Shape(x)",
    "docstring": "Converts input to a Shape.\n\n  Args:\n    x: Shape, str, or None.\n\n  Returns:\n    Shape or None.\n\n  Raises:\n    ValueError: If x cannot be converted to a Shape."
  },
  {
    "code": "def recov_date(self, return_date=False):\n        dd = self.drawdown_idx()\n        mask = nancumprod(dd != nanmin(dd)).astype(bool)\n        res = dd.mask(mask) == 0\n        if not res.any():\n            recov = pd.NaT\n        else:\n            recov = res.idxmax()\n        if return_date:\n            return recov.date()\n        return recov",
    "docstring": "Drawdown recovery date.\n\n        Date at which `self` recovered to previous high-water mark.\n\n        Parameters\n        ----------\n        return_date : bool, default False\n            If True, return a `datetime.date` object.\n            If False, return a Pandas Timestamp object.\n\n        Returns\n        -------\n        {datetime.date, pandas._libs.tslib.Timestamp, pd.NaT}\n            Returns NaT if recovery has not occured."
  },
  {
    "code": "def from_tushare(dataframe, dtype='day'):\n    if dtype in ['day']:\n        return QA_DataStruct_Stock_day(\n            dataframe.assign(date=pd.to_datetime(dataframe.date)\n                            ).set_index(['date',\n                                         'code'],\n                                        drop=False),\n            dtype='stock_day'\n        )\n    elif dtype in ['min']:\n        return QA_DataStruct_Stock_min(\n            dataframe.assign(datetime=pd.to_datetime(dataframe.datetime)\n                            ).set_index(['datetime',\n                                         'code'],\n                                        drop=False),\n            dtype='stock_min'\n        )",
    "docstring": "dataframe from tushare\n\n    Arguments:\n        dataframe {[type]} -- [description]\n\n    Returns:\n        [type] -- [description]"
  },
  {
    "code": "def translate_connect_args(self, names=[], **kw):\n        translated = {}\n        attribute_names = [\"host\", \"database\", \"username\", \"password\", \"port\"]\n        for sname in attribute_names:\n            if names:\n                name = names.pop(0)\n            elif sname in kw:\n                name = kw[sname]\n            else:\n                name = sname\n            if name is not None and getattr(self, sname, False):\n                translated[name] = getattr(self, sname)\n        return translated",
    "docstring": "Translate url attributes into a dictionary of connection arguments.\n\n        Returns attributes of this url (`host`, `database`, `username`,\n        `password`, `port`) as a plain dictionary.  The attribute names are\n        used as the keys by default.  Unset or false attributes are omitted\n        from the final dictionary.\n\n        :param \\**kw: Optional, alternate key names for url attributes.\n\n        :param names: Deprecated.  Same purpose as the keyword-based alternate\n            names, but correlates the name to the original positionally."
  },
  {
    "code": "def _init_user_stub(self, **stub_kwargs):\n        task_args = stub_kwargs.copy()\n        self.testbed.setup_env(overwrite=True,\n                               USER_ID=task_args.pop('USER_ID', 'testuser'),\n                               USER_EMAIL=task_args.pop('USER_EMAIL', 'testuser@example.org'),\n                               USER_IS_ADMIN=task_args.pop('USER_IS_ADMIN', '1'))\n        self.testbed.init_user_stub(**task_args)",
    "docstring": "Initializes the user stub using nosegae config magic"
  },
  {
    "code": "def cast(self, dtype):\n        for child in self._children.values():\n            child.cast(dtype)\n        for _, param in self.params.items():\n            param.cast(dtype)",
    "docstring": "Cast this Block to use another data type.\n\n        Parameters\n        ----------\n        dtype : str or numpy.dtype\n            The new data type."
  },
  {
    "code": "def update_cluster(cluster_ref, cluster_spec):\n    cluster_name = get_managed_object_name(cluster_ref)\n    log.trace('Updating cluster \\'%s\\'', cluster_name)\n    try:\n        task = cluster_ref.ReconfigureComputeResource_Task(cluster_spec,\n                                                           modify=True)\n    except vim.fault.NoPermission as exc:\n        log.exception(exc)\n        raise salt.exceptions.VMwareApiError(\n            'Not enough permissions. Required privilege: '\n            '{}'.format(exc.privilegeId))\n    except vim.fault.VimFault as exc:\n        log.exception(exc)\n        raise salt.exceptions.VMwareApiError(exc.msg)\n    except vmodl.RuntimeFault as exc:\n        log.exception(exc)\n        raise salt.exceptions.VMwareRuntimeError(exc.msg)\n    wait_for_task(task, cluster_name, 'ClusterUpdateTask')",
    "docstring": "Updates a cluster in a datacenter.\n\n    cluster_ref\n        The cluster reference.\n\n    cluster_spec\n        The cluster spec (vim.ClusterConfigSpecEx).\n        Defaults to None."
  },
  {
    "code": "def parse_yaml(self, y):\n        super(Preceding, self).parse_yaml(y)\n        c = y['condition']['preceding']\n        if 'timeout' in c:\n            self.timeout = int(c['timeout'])\n        else:\n            self.timeout = 0\n        if 'sendingTiming' in c:\n            self.sending_timing = c['sendingTiming']\n        else:\n            self.sending_timing = 'ASYNC'\n        self._preceding_components = []\n        if 'precedingComponents' in c:\n            for p in c.get('precedingComponents'):\n                self._preceding_components.append(TargetExecutionContext().parse_yaml(p))\n        return self",
    "docstring": "Parse a YAML specification of a preceding condition into this\n        object."
  },
  {
    "code": "def cli(env, billing_id, datacenter):\n    mgr = SoftLayer.LoadBalancerManager(env.client)\n    if not formatting.confirm(\"This action will incur charges on your \"\n                              \"account. Continue?\"):\n        raise exceptions.CLIAbort('Aborted.')\n    mgr.add_local_lb(billing_id, datacenter=datacenter)\n    env.fout(\"Load balancer is being created!\")",
    "docstring": "Adds a load balancer given the id returned from create-options."
  },
  {
    "code": "def _make_postfixes_1( analysis ):\n    assert FORM in analysis, '(!) The input analysis does not contain \"'+FORM+'\" key.'\n    if 'neg' in analysis[FORM]:\n        analysis[FORM] = re.sub( '^\\s*neg ([^,]*)$',  '\\\\1 Neg',  analysis[FORM] )\n    analysis[FORM] = re.sub( ' Neg Neg$',  ' Neg',  analysis[FORM] )\n    analysis[FORM] = re.sub( ' Aff Neg$',  ' Neg',  analysis[FORM] )\n    analysis[FORM] = re.sub( 'neg',  'Neg',  analysis[FORM] )\n    analysis[FORM] = analysis[FORM].rstrip().lstrip()\n    assert 'neg' not in analysis[FORM], \\\n                 '(!) The label \"neg\" should be removed by now.'\n    assert 'Neg' not in analysis[FORM] or ('Neg' in analysis[FORM] and analysis[FORM].endswith('Neg')), \\\n                 '(!) The label \"Neg\" should end the analysis line: '+str(analysis[FORM])\n    return analysis",
    "docstring": "Provides some post-fixes."
  },
  {
    "code": "def setTxPower(self, tx_power, peername=None):\n        if peername:\n            protocols = [p for p in self.protocols\n                         if p.peername[0] == peername]\n        else:\n            protocols = self.protocols\n        for proto in protocols:\n            proto.setTxPower(tx_power)",
    "docstring": "Set the transmit power on one or all readers\n\n        If peername is None, set the transmit power for all readers.\n        Otherwise, set it for that specific reader."
  },
  {
    "code": "def __auth_descriptor(self, api_info):\n    if api_info.auth is None:\n      return None\n    auth_descriptor = {}\n    if api_info.auth.allow_cookie_auth is not None:\n      auth_descriptor['allowCookieAuth'] = api_info.auth.allow_cookie_auth\n    if api_info.auth.blocked_regions:\n      auth_descriptor['blockedRegions'] = api_info.auth.blocked_regions\n    return auth_descriptor",
    "docstring": "Builds an auth descriptor from API info.\n\n    Args:\n      api_info: An _ApiInfo object.\n\n    Returns:\n      A dictionary with 'allowCookieAuth' and/or 'blockedRegions' keys."
  },
  {
    "code": "def addService(self, service, parentService=None):\n        if parentService is not None:\n            def check(services):\n                for jS in services:\n                    if jS.service == parentService or check(jS.service._childServices):\n                        return True\n                return False\n            if not check(self._services):\n                raise JobException(\"Parent service is not a service of the given job\")\n            return parentService._addChild(service)\n        else:\n            if service._hasParent:\n                raise JobException(\"The service already has a parent service\")\n            service._hasParent = True\n            jobService = ServiceJob(service)\n            self._services.append(jobService)\n            return jobService.rv()",
    "docstring": "Add a service.\n\n        The :func:`toil.job.Job.Service.start` method of the service will be called\n        after the run method has completed but before any successors are run.\n        The service's :func:`toil.job.Job.Service.stop` method will be called once\n        the successors of the job have been run.\n\n        Services allow things like databases and servers to be started and accessed\n        by jobs in a workflow.\n\n        :raises toil.job.JobException: If service has already been made the child of a job or another service.\n        :param toil.job.Job.Service service: Service to add.\n        :param toil.job.Job.Service parentService: Service that will be started before 'service' is\n            started. Allows trees of services to be established. parentService must be a service\n            of this job.\n        :return: a promise that will be replaced with the return value from\n            :func:`toil.job.Job.Service.start` of service in any successor of the job.\n        :rtype: toil.job.Promise"
  },
  {
    "code": "def valueRepr(self):\n        v = self.value\n        if self.behavior:\n            v = self.behavior.valueRepr(self)\n        return v",
    "docstring": "Transform the representation of the value\n        according to the behavior, if any."
  },
  {
    "code": "def _CheckPacketSize(cursor):\n  cur_packet_size = int(_ReadVariable(\"max_allowed_packet\", cursor))\n  if cur_packet_size < MAX_PACKET_SIZE:\n    raise Error(\n        \"MySQL max_allowed_packet of {0} is required, got {1}. \"\n        \"Please set max_allowed_packet={0} in your MySQL config.\".format(\n            MAX_PACKET_SIZE, cur_packet_size))",
    "docstring": "Checks that MySQL packet size is big enough for expected query size."
  },
  {
    "code": "def remove(self, label):\n        if label.id in self._labels:\n            self._labels[label.id] = None\n        self._dirty = True",
    "docstring": "Remove a label.\n\n        Args:\n            label (gkeepapi.node.Label): The Label object."
  },
  {
    "code": "def predict_encoding(file_path, n_lines=20):\n    import chardet\n    with open(file_path, 'rb') as f:\n        rawdata = b''.join([f.readline() for _ in range(n_lines)])\n    return chardet.detect(rawdata)['encoding']",
    "docstring": "Get file encoding of a text file"
  },
  {
    "code": "def save(self, url, storage_options=None):\n        from dask.bytes import open_files\n        with open_files([url], **(storage_options or {}), mode='wt')[0] as f:\n            f.write(self.serialize())",
    "docstring": "Output this catalog to a file as YAML\n\n        Parameters\n        ----------\n        url : str\n            Location to save to, perhaps remote\n        storage_options : dict\n            Extra arguments for the file-system"
  },
  {
    "code": "def add_section(self, id_, parent_id, section_type, points):\n        assert id_ not in self.sections, 'id %s already exists in sections' % id_\n        self.sections[id_] = BlockNeuronBuilder.BlockSection(parent_id, section_type, points)",
    "docstring": "add a section\n\n        Args:\n            id_(int): identifying number of the section\n            parent_id(int): identifying number of the parent of this section\n            section_type(int): the section type as defined by POINT_TYPE\n            points is an array of [X, Y, Z, R]"
  },
  {
    "code": "def get_value(self):\n        if self.value is not_computed:\n            self.value = self.value_provider()\n            if self.value is not_computed:\n                return None\n        return self.value",
    "docstring": "Returns the value of the constant."
  },
  {
    "code": "def sentinels(self, name):\n        fut = self.execute(b'SENTINELS', name, encoding='utf-8')\n        return wait_convert(fut, parse_sentinel_slaves_and_sentinels)",
    "docstring": "Returns a list of sentinels for ``name``."
  },
  {
    "code": "def _exclude_ipv4_networks(self, networks, networks_to_exclude):\n        for network_to_exclude in networks_to_exclude:\n            def _exclude_ipv4_network(network):\n                try:\n                    return list(network.address_exclude(network_to_exclude))\n                except ValueError:\n                    if network.overlaps(network_to_exclude):\n                        return []\n                    else:\n                        return [network]\n            networks = list(map(_exclude_ipv4_network, networks))\n            networks = [\n                item for nested in networks for item in nested\n            ]\n        return networks",
    "docstring": "Exclude the list of networks from another list of networks\n        and return a flat list of new networks.\n\n        :param networks: List of IPv4 networks to exclude from\n        :param networks_to_exclude: List of IPv4 networks to exclude\n        :returns: Flat list of IPv4 networks"
  },
  {
    "code": "def start_cmd(cmd, descr, data):\n    if data and \"provenance\" in data:\n        entity_id = tz.get_in([\"provenance\", \"entity\"], data)",
    "docstring": "Retain details about starting a command, returning a command identifier."
  },
  {
    "code": "def _start(self):\n        last_call = 42\n        while self._focus:\n            sleep(1 / 100)\n            mouse = pygame.mouse.get_pos()\n            last_value = self.get()\n            self.value_px = mouse[0]\n            if self.get() == last_value:\n                continue\n            if last_call + self.interval / 1000 < time():\n                last_call = time()\n                self.func(self.get())",
    "docstring": "Starts checking if the SB is shifted"
  },
  {
    "code": "def _eval_variables(self):\n        for k, v in listitems(self._variables):\n            self._variables[k] = v() if hasattr(v, '__call__') else v",
    "docstring": "evaluates callable _variables"
  },
  {
    "code": "def post_ticket(self, title, body):\n        ticket = {'subject': title,\n                  'message': body }\n        response = self.client.post(\"/api/v1/tickets.json\", {\n                                    'email': self.email,\n                                    'ticket': ticket })['ticket']\n        bot.info(response['url'])",
    "docstring": "post_ticket will post a ticket to the uservoice helpdesk\n\n           Parameters\n           ==========\n           title: the title (subject) of the issue\n           body: the message to send"
  },
  {
    "code": "def enable(self, size, block_size=None, store=None, store_sync_interval=None):\n        self._set('queue', size)\n        self._set('queue-blocksize', block_size)\n        self._set('queue-store', store)\n        self._set('queue-store-sync', store_sync_interval)\n        return self._section",
    "docstring": "Enables shared queue of the given size.\n\n        :param int size: Queue size.\n\n        :param int block_size: Block size in bytes. Default: 8 KiB.\n\n        :param str|unicode store: Persist the queue into file.\n\n        :param int store_sync_interval: Store sync interval in master cycles (usually seconds)."
  },
  {
    "code": "def cross_variance(self, x, z, sigmas_f, sigmas_h):\n        Pxz = zeros((sigmas_f.shape[1], sigmas_h.shape[1]))\n        N = sigmas_f.shape[0]\n        for i in range(N):\n            dx = self.residual_x(sigmas_f[i], x)\n            dz = self.residual_z(sigmas_h[i], z)\n            Pxz += self.Wc[i] * outer(dx, dz)\n        return Pxz",
    "docstring": "Compute cross variance of the state `x` and measurement `z`."
  },
  {
    "code": "def rot13_app(parser, cmd, args):\n    parser.add_argument('value', help='the value to rot13, read from stdin if omitted', nargs='?')\n    args = parser.parse_args(args)\n    return rot13(pwnypack.main.string_value_or_stdin(args.value))",
    "docstring": "rot13 encrypt a value."
  },
  {
    "code": "def authorize_client_credentials(\n        self, client_id, client_secret=None, scope=\"private_agent\"\n    ):\n        self.auth_data = {\n            \"grant_type\": \"client_credentials\",\n            \"scope\": [ scope ],\n            \"client_id\": client_id,\n            \"client_secret\": client_secret\n        }\n        self._do_authorize()",
    "docstring": "Authorize to platform with client credentials\n\n        This should be used if you posses client_id/client_secret pair\n        generated by platform."
  },
  {
    "code": "def _findLocation(self, reference_name, start, end):\n        try:\n            return self._locationMap['hg19'][reference_name][start][end]\n        except:\n            return None",
    "docstring": "return a location key form the locationMap"
  },
  {
    "code": "def fermion_avg(efermi, norm_hopping, func):\n    if func == 'ekin':\n        func = bethe_ekin_zeroT\n    elif func == 'ocupation':\n        func = bethe_filling_zeroT\n    return np.asarray([func(ef, tz) for ef, tz in zip(efermi, norm_hopping)])",
    "docstring": "calcules for every slave it's average over the desired observable"
  },
  {
    "code": "def connect(uri, factory=pymongo.MongoClient):\n    warnings.warn(\n        \"do not use. Just call MongoClient directly.\", DeprecationWarning)\n    return factory(uri)",
    "docstring": "Use the factory to establish a connection to uri."
  },
  {
    "code": "def bandwidth(self):\n    return np.abs(np.diff(self.pairs(), axis=1)).max()",
    "docstring": "Computes the 'bandwidth' of a graph."
  },
  {
    "code": "def getFileName(self, suffix=None, extension=\"jar\"):\n        assert (self._artifactId is not None)\n        assert (self._version is not None)\n        return \"{0}-{1}{2}{3}\".format(\n            self._artifactId,\n            self._version.getRawString(),\n            \"-\" + suffix.lstrip(\"-\") if suffix is not None else \"\",\n            \".\" + extension.lstrip(\".\") if extension is not None else \"\"\n        )",
    "docstring": "Returns the basename of the artifact's file, using Maven's conventions.\n\n        In particular, it will be:\n\n            <artifactId>-<version>[-<suffix>][.<extension>]"
  },
  {
    "code": "def responderForName(self, instance, commandName):\n        method = super(_AMPExposer, self).get(instance, commandName)\n        return method",
    "docstring": "When resolving a command to a method from the wire, the information\n        available is the command's name; look up a command.\n\n        @param instance: an instance of a class who has methods exposed via\n        this exposer's L{_AMPExposer.expose} method.\n\n        @param commandName: the C{commandName} attribute of a L{Command}\n        exposed on the given instance.\n\n        @return: a bound method with a C{command} attribute."
  },
  {
    "code": "def _one_diagonal_capture_square(self, capture_square, position):\n        if self.contains_opposite_color_piece(capture_square, position):\n            if self.would_move_be_promotion():\n                for move in self.create_promotion_moves(status=notation_const.CAPTURE_AND_PROMOTE,\n                                                        location=capture_square):\n                    yield move\n            else:\n                yield self.create_move(end_loc=capture_square,\n                                       status=notation_const.CAPTURE)",
    "docstring": "Adds specified diagonal as a capture move if it is one"
  },
  {
    "code": "def acgt_match(string):\n    search = re.compile(r'[^ACGT]').search\n    return not bool(search(string))",
    "docstring": "returns True if sting consist of only \"A \"C\" \"G\" \"T\""
  },
  {
    "code": "def delete_organization(session, organization):\n    last_modified = datetime.datetime.utcnow()\n    for enrollment in organization.enrollments:\n        enrollment.uidentity.last_modified = last_modified\n    session.delete(organization)\n    session.flush()",
    "docstring": "Remove an organization from the session.\n\n    Function that removes from the session the organization\n    given in `organization`. Data related such as domains\n    or enrollments are also removed.\n\n    :param session: database session\n    :param organization: organization to remove"
  },
  {
    "code": "def classify_single_recording(raw_data_json, model_folder, verbose=False):\n    evaluation_file = evaluate_model(raw_data_json, model_folder, verbose)\n    with open(os.path.join(model_folder, \"info.yml\")) as ymlfile:\n        model_description = yaml.load(ymlfile)\n    index2latex = get_index2latex(model_description)\n    with open(evaluation_file) as f:\n        probabilities = f.read()\n    probabilities = map(float, probabilities.split(\" \"))\n    results = []\n    for index, probability in enumerate(probabilities):\n        results.append((index2latex[index], probability))\n    results = sorted(results, key=lambda n: n[1], reverse=True)\n    return results",
    "docstring": "Get the classification as a list of tuples. The first value is the LaTeX\n    code, the second value is the probability."
  },
  {
    "code": "def getScriptLocation():\n\tlocation = os.path.abspath(\"./\")\n\tif __file__.rfind(\"/\") != -1:\n\t\tlocation = __file__[:__file__.rfind(\"/\")]\n\treturn location",
    "docstring": "Helper function to get the location of a Python file."
  },
  {
    "code": "def combine_keys(pks: Iterable[Ed25519PublicPoint]) -> Ed25519PublicPoint:\n    P = [_ed25519.decodepoint(pk) for pk in pks]\n    combine = reduce(_ed25519.edwards_add, P)\n    return Ed25519PublicPoint(_ed25519.encodepoint(combine))",
    "docstring": "Combine a list of Ed25519 points into a \"global\" CoSi key."
  },
  {
    "code": "def write_path(self, path_value):\n        parent_dir = os.path.dirname(self.path)\n        try:\n            os.makedirs(parent_dir)\n        except OSError:\n            pass\n        with open(self.path, \"w\") as fph:\n            fph.write(path_value.value)",
    "docstring": "this will overwrite dst path - be careful"
  },
  {
    "code": "def get_environ(self, key, default=None, cast=None):\n        key = key.upper()\n        data = self.environ.get(key, default)\n        if data:\n            if cast in converters:\n                data = converters.get(cast)(data)\n            if cast is True:\n                data = parse_conf_data(data, tomlfy=True)\n        return data",
    "docstring": "Get value from environment variable using os.environ.get\n\n        :param key: The name of the setting value, will always be upper case\n        :param default: In case of not found it will be returned\n        :param cast: Should cast in to @int, @float, @bool or @json ?\n         or cast must be true to use cast inference\n        :return: The value if found, default or None"
  },
  {
    "code": "def _add_res(line):\n    global resource\n    fields = line.strip().split()\n    if resource:\n        ret.append(resource)\n        resource = {}\n    resource[\"resource name\"] = fields[0]\n    resource[\"local role\"] = fields[1].split(\":\")[1]\n    resource[\"local volumes\"] = []\n    resource[\"peer nodes\"] = []",
    "docstring": "Analyse the line of local resource of ``drbdadm status``"
  },
  {
    "code": "def get_projected_fields(self, req):\n        try:\n            args = getattr(req, 'args', {})\n            return ','.join(json.loads(args.get('projections')))\n        except (AttributeError, TypeError):\n            return None",
    "docstring": "Returns the projected fields from request."
  },
  {
    "code": "def decode_json(cls, dct):\n        if not ('event_name' in dct and 'event_values' in dct):\n            return dct\n        event_name = dct['event_name']\n        if event_name not in _CONCRETE_EVENT_CLASSES:\n            raise ValueError(\"Could not find appropriate Event class for event_name: %r\" % event_name)\n        event_values = dct['event_values']\n        model_id = event_values.pop('model_id')\n        event = _CONCRETE_EVENT_CLASSES[event_name](model=None, **event_values)\n        event._model_id = model_id\n        return event",
    "docstring": "Custom JSON decoder for Events.\n\n        Can be used as the ``object_hook`` argument of ``json.load`` or\n        ``json.loads``.\n\n        Args:\n            dct (dict) : a JSON dictionary to decode\n                The dictionary should have keys ``event_name`` and ``event_values``\n\n        Raises:\n            ValueError, if the event_name is unknown\n\n        Examples:\n\n            .. code-block:: python\n\n                >>> import json\n                >>> from bokeh.events import Event\n                >>> data = '{\"event_name\": \"pan\", \"event_values\" : {\"model_id\": 1, \"x\": 10, \"y\": 20, \"sx\": 200, \"sy\": 37}}'\n                >>> json.loads(data, object_hook=Event.decode_json)\n                <bokeh.events.Pan object at 0x1040f84a8>"
  },
  {
    "code": "def _ordered_node_addrs(self, function_address):\n        try:\n            function = self.kb.functions[function_address]\n        except KeyError:\n            return [ ]\n        if function_address not in self._function_node_addrs:\n            sorted_nodes = CFGUtils.quasi_topological_sort_nodes(function.graph)\n            self._function_node_addrs[function_address] = [ n.addr for n in sorted_nodes ]\n        return self._function_node_addrs[function_address]",
    "docstring": "For a given function, return all nodes in an optimal traversal order. If the function does not exist, return an\n        empty list.\n\n        :param int function_address: Address of the function.\n        :return: A ordered list of the nodes.\n        :rtype: list"
  },
  {
    "code": "def payload_register(ptype, klass, pid):\n    cmd = ['payload-register']\n    for x in [ptype, klass, pid]:\n        cmd.append(x)\n    subprocess.check_call(cmd)",
    "docstring": "is used while a hook is running to let Juju know that a\n        payload has been started."
  },
  {
    "code": "def format_response(self, response):\n        conversion = self.shell_ctx.config.BOOLEAN_STATES\n        if response in conversion:\n            if conversion[response]:\n                return 'yes'\n            return 'no'\n        raise ValueError('Invalid response: input should equate to true or false')",
    "docstring": "formats a response in a binary"
  },
  {
    "code": "def asyncStarCmap(asyncCallable, iterable):\n    results = []\n    yield coopStar(asyncCallable, results.append, iterable)\n    returnValue(results)",
    "docstring": "itertools.starmap for deferred callables using cooperative multitasking"
  },
  {
    "code": "def _Comparator(self, operator):\n    if operator == \"=\":\n      return lambda x, y: x == y\n    elif operator == \">=\":\n      return lambda x, y: x >= y\n    elif operator == \">\":\n      return lambda x, y: x > y\n    elif operator == \"<=\":\n      return lambda x, y: x <= y\n    elif operator == \"<\":\n      return lambda x, y: x < y\n    elif operator == \"!\":\n      return lambda x, y: x != y\n    raise DefinitionError(\"Invalid comparison operator %s\" % operator)",
    "docstring": "Generate lambdas for uid and gid comparison."
  },
  {
    "code": "def wr_xlsx(self, fout_xlsx, goea_results, **kws):\n        objprt = PrtFmt()\n        prt_flds = kws.get('prt_flds', self.get_prtflds_default(goea_results))\n        xlsx_data = MgrNtGOEAs(goea_results).get_goea_nts_prt(prt_flds, **kws)\n        if 'fld2col_widths' not in kws:\n            kws['fld2col_widths'] = {f:objprt.default_fld2col_widths.get(f, 8) for f in prt_flds}\n        RPT.wr_xlsx(fout_xlsx, xlsx_data, **kws)",
    "docstring": "Write a xlsx file."
  },
  {
    "code": "def _attach_fields(obj):\n    for attr in base_fields.__all__:\n        if not hasattr(obj, attr):\n            setattr(obj, attr, getattr(base_fields, attr))\n    for attr in fields.__all__:\n        setattr(obj, attr, getattr(fields, attr))",
    "docstring": "Attach all the marshmallow fields classes to ``obj``, including\n    Flask-Marshmallow's custom fields."
  },
  {
    "code": "def cipher(self):\n\t\tcipher = Cipher(*self.mode().aes_args(), **self.mode().aes_kwargs())\n\t\treturn WAES.WAESCipher(cipher)",
    "docstring": "Generate AES-cipher\n\n\t\t:return: Crypto.Cipher.AES.AESCipher"
  },
  {
    "code": "def get_object_or_none(model, *args, **kwargs):\n    try:\n        return model._default_manager.get(*args, **kwargs)\n    except model.DoesNotExist:\n        return None",
    "docstring": "Like get_object_or_404, but doesn't throw an exception.\n\n    Allows querying for an object that might not exist without triggering\n    an exception."
  },
  {
    "code": "def date(self, year: Number, month: Number, day: Number) -> Date:\n        return Date(year, month, day)",
    "docstring": "Takes three numbers and returns a ``Date`` object whose year, month, and day are the three\n        numbers in that order."
  },
  {
    "code": "def workflow_states_column(self, obj):\n        workflow_states = models.WorkflowState.objects.filter(\n            content_type=self._get_obj_ct(obj),\n            object_id=obj.pk,\n        )\n        return ', '.join([unicode(wfs) for wfs in workflow_states])",
    "docstring": "Return text description of workflow states assigned to object"
  },
  {
    "code": "def project_create(auth=None, **kwargs):\n    cloud = get_openstack_cloud(auth)\n    kwargs = _clean_kwargs(keep_name=True, **kwargs)\n    return cloud.create_project(**kwargs)",
    "docstring": "Create a project\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' keystoneng.project_create name=project1\n        salt '*' keystoneng.project_create name=project2 domain_id=b62e76fbeeff4e8fb77073f591cf211e\n        salt '*' keystoneng.project_create name=project3 enabled=False description='my project3'"
  },
  {
    "code": "def is_symmetric(self, symprec=0.1):\n        sg = SpacegroupAnalyzer(self, symprec=symprec)\n        return sg.is_laue()",
    "docstring": "Checks if slab is symmetric, i.e., contains inversion symmetry.\n\n        Args:\n            symprec (float): Symmetry precision used for SpaceGroup analyzer.\n\n        Returns:\n            (bool) Whether slab contains inversion symmetry."
  },
  {
    "code": "def TimeField(formatter=types.DEFAULT_TIME_FORMAT, default=NOTHING,\n              required=True, repr=True, cmp=True, key=None):\n    default = _init_fields.init_default(required, default, None)\n    validator = _init_fields.init_validator(required, time)\n    converter = converters.to_time_field(formatter)\n    return attrib(default=default, converter=converter, validator=validator,\n                  repr=repr, cmp=cmp,\n                  metadata=dict(formatter=formatter, key=key))",
    "docstring": "Create new time field on a model.\n\n    :param formatter: time formatter string (default: \"%H:%M:%S\")\n    :param default: any time or string that can be converted to a time value\n    :param bool required: whether or not the object is invalid if not provided.\n    :param bool repr: include this field should appear in object's repr.\n    :param bool cmp: include this field in generated comparison.\n    :param string key: override name of the value when converted to dict."
  },
  {
    "code": "def rename(self, new_name, *args, **kwargs):\n        new = self.reddit_session.rename_multireddit(self.name, new_name,\n                                                     *args, **kwargs)\n        self.__dict__ = new.__dict__\n        return self",
    "docstring": "Rename this multireddit.\n\n        This function is a handy shortcut to\n        :meth:`rename_multireddit` of the reddit_session."
  },
  {
    "code": "def parse_authority(cls, authority):\n        userinfo, sep, host = authority.partition('@')\n        if not sep:\n            return '', userinfo\n        else:\n            return userinfo, host",
    "docstring": "Parse the authority part and return userinfo and host."
  },
  {
    "code": "def set_seat_logical_name(self, seat):\n\t\trc = self._libinput.libinput_device_set_seat_logical_name(\n\t\t\tself._handle, seat.encode())\n\t\tassert rc == 0, 'Cannot assign device to {}'.format(seat)",
    "docstring": "Change the logical seat associated with this device by removing\n\t\tthe device and adding it to the new seat.\n\n\t\tThis command is identical to physically unplugging the device, then\n\t\tre-plugging it as a member of the new seat. libinput will generate\n\t\ta :attr:`~libinput.constant.EventType.DEVICE_REMOVED` event and this\n\t\t:class:`Device` is considered removed from the context; it will not\n\t\tgenerate further events.\n\t\tA :attr:`~libinput.constant.EventType.DEVICE_ADDED` event is\n\t\tgenerated with a new :class:`Device`. It is the caller's\n\t\tresponsibility to update references to the new device accordingly.\n\n\t\tIf the logical seat name already exists in the device's physical seat,\n\t\tthe device is added to this seat. Otherwise, a new seat is created.\n\n\t\tNote:\n\t\t\tThis change applies to this device until removal or\n\t\t\t:meth:`~libinput.LibInput.suspend`, whichever happens earlier.\n\t\tArgs:\n\t\t\tseat (str): The new logical seat name.\n\t\tRaises:\n\t\t\tAssertionError"
  },
  {
    "code": "def kwds(self):\n        return _kwds(base=self.base, item=self.item,\n                     leng=self.leng, refs=self.refs,\n                     both=self.both, kind=self.kind, type=self.type)",
    "docstring": "Return all attributes as keywords dict."
  },
  {
    "code": "def _downloaded_filename(self):\n        link = self._link() or self._finder.find_requirement(self._req, upgrade=False)\n        if link:\n            lower_scheme = link.scheme.lower()\n            if lower_scheme == 'http' or lower_scheme == 'https':\n                file_path = self._download(link)\n                return basename(file_path)\n            elif lower_scheme == 'file':\n                link_path = url_to_path(link.url_without_fragment)\n                if isdir(link_path):\n                    raise UnsupportedRequirementError(\n                        \"%s: %s is a directory. So that it can compute \"\n                        \"a hash, peep supports only filesystem paths which \"\n                        \"point to files\" %\n                        (self._req, link.url_without_fragment))\n                else:\n                    copy(link_path, self._temp_path)\n                    return basename(link_path)\n            else:\n                raise UnsupportedRequirementError(\n                    \"%s: The download link, %s, would not result in a file \"\n                    \"that can be hashed. Peep supports only == requirements, \"\n                    \"file:// URLs pointing to files (not folders), and \"\n                    \"http:// and https:// URLs pointing to tarballs, zips, \"\n                    \"etc.\" % (self._req, link.url))\n        else:\n            raise UnsupportedRequirementError(\n                \"%s: couldn't determine where to download this requirement from.\"\n                % (self._req,))",
    "docstring": "Download the package's archive if necessary, and return its\n        filename.\n\n        --no-deps is implied, as we have reimplemented the bits that would\n        ordinarily do dependency resolution."
  },
  {
    "code": "def rndbytes(size=16, alphabet=\"\"):\n    x = rndstr(size, alphabet)\n    if isinstance(x, six.string_types):\n        return x.encode('utf-8')\n    return x",
    "docstring": "Returns rndstr always as a binary type"
  },
  {
    "code": "def _on_login(self, user):\n        self._bot = bool(user.bot)\n        self._self_input_peer = utils.get_input_peer(user, allow_self=False)\n        self._authorized = True\n        return user",
    "docstring": "Callback called whenever the login or sign up process completes.\n\n        Returns the input user parameter."
  },
  {
    "code": "def collect_github_config():\n\tgithub_config = {}\n\tfor field in [\"user\", \"token\"]:\n\t\ttry:\n\t\t\tgithub_config[field] = subprocess.check_output([\"git\", \"config\", \"github.{}\".format(field)]).decode('utf-8').strip()\n\t\texcept (OSError, subprocess.CalledProcessError):\n\t\t\tpass\n\treturn github_config",
    "docstring": "Try load Github configuration such as usernames from the local or global git config"
  },
  {
    "code": "def addPolylineAnnot(self, points):\n        CheckParent(self)\n        val = _fitz.Page_addPolylineAnnot(self, points)\n        if not val: return\n        val.thisown = True\n        val.parent = weakref.proxy(self)\n        self._annot_refs[id(val)] = val\n        return val",
    "docstring": "Add a 'Polyline' annotation for a sequence of points."
  },
  {
    "code": "def pose2mat(pose):\n    homo_pose_mat = np.zeros((4, 4), dtype=np.float32)\n    homo_pose_mat[:3, :3] = quat2mat(pose[1])\n    homo_pose_mat[:3, 3] = np.array(pose[0], dtype=np.float32)\n    homo_pose_mat[3, 3] = 1.\n    return homo_pose_mat",
    "docstring": "Converts pose to homogeneous matrix.\n\n    Args:\n        pose: a (pos, orn) tuple where pos is vec3 float cartesian, and\n            orn is vec4 float quaternion.\n\n    Returns:\n        4x4 homogeneous matrix"
  },
  {
    "code": "def ls(\n        self, rev, path, recursive=False, recursive_dirs=False,\n        directory=False, report=()\n    ):\n        raise NotImplementedError",
    "docstring": "List directory or file\n\n        :param rev: The revision to use.\n        :param path: The path to list. May start with a '/' or not. Directories\n                     may end with a '/' or not.\n        :param recursive: Recursively list files in subdirectories.\n        :param recursive_dirs: Used when recursive=True, also list directories.\n        :param directory: If path is a directory, list path itself instead of\n                          its contents.\n        :param report: A list or tuple of extra attributes to return that may\n                       require extra processing. Recognized values are 'size',\n                       'target', 'executable', and 'commit'.\n\n        Returns a list of dictionaries with the following keys:\n\n        **type**\n            The type of the file: 'f' for file, 'd' for directory, 'l' for\n            symlink.\n        **name**\n            The name of the file. Not present if directory=True.\n        **size**\n            The size of the file. Only present for files when 'size' is in\n            report.\n        **target**\n            The target of the symlink. Only present for symlinks when\n            'target' is in report.\n        **executable**\n            True if the file is executable, False otherwise.    Only present\n            for files when 'executable' is in report.\n\n        Raises PathDoesNotExist if the path does not exist."
  },
  {
    "code": "def element_name_from_Z(Z, normalize=False):\n    r = element_data_from_Z(Z)[2]\n    if normalize:\n        return r.capitalize()\n    else:\n        return r",
    "docstring": "Obtain an element's name from its Z number\n\n    An exception is thrown if the Z number is not found\n\n    If normalize is True, the first letter will be capitalized"
  },
  {
    "code": "def match(self, context, line):\n\t\treturn line.kind == 'code' and line.partitioned[0] in self._both",
    "docstring": "Match code lines prefixed with a variety of keywords."
  },
  {
    "code": "def reset(self):\n        self._undo_stack.clear()\n        self._spike_clusters = self._spike_clusters_base\n        self._new_cluster_id = self._new_cluster_id_0",
    "docstring": "Reset the clustering to the original clustering.\n\n        All changes are lost."
  },
  {
    "code": "def _kill_process(self, pid, sig=signal.SIGKILL):\n        try:\n            os.kill(pid, sig)\n        except OSError as e:\n            if e.errno == errno.ESRCH:\n                logging.debug(\"Failure %s while killing process %s with signal %s: %s\",\n                              e.errno, pid, sig, e.strerror)\n            else:\n                logging.warning(\"Failure %s while killing process %s with signal %s: %s\",\n                                e.errno, pid, sig, e.strerror)",
    "docstring": "Try to send signal to given process."
  },
  {
    "code": "def from_form(self, param_name, field):\n        return self.__from_source(param_name, field, lambda: request.form, 'form')",
    "docstring": "A decorator that converts a request form into a function parameter based on the specified field.\n\n        :param str param_name: The parameter which receives the argument.\n        :param Field field: The field class or instance used to deserialize the request form to a Python object.\n        :return: A function"
  },
  {
    "code": "def updateParams(self, newvalues):\n        for (param, value) in newvalues.items():\n            if param not in self.model.freeparams:\n                raise RuntimeError(\"Can't handle param: {0}\".format(\n                        param))\n        if newvalues:\n            self.model.updateParams(newvalues)\n            self._updateInternals()\n            self._paramsarray = None",
    "docstring": "Update model parameters and re-compute likelihoods.\n\n        This method is the **only** acceptable way to update model\n        parameters. The likelihood is re-computed as needed\n        by this method.\n\n        Args:\n            `newvalues` (dict)\n                A dictionary keyed by param name and with value as new\n                value to set. Each parameter name must either be a\n                valid model parameter (in `model.freeparams`)."
  },
  {
    "code": "def interp(self, date: timetools.Date) -> float:\n        xnew = timetools.TOY(date)\n        xys = list(self)\n        for idx, (x_1, y_1) in enumerate(xys):\n            if x_1 > xnew:\n                x_0, y_0 = xys[idx-1]\n                break\n        else:\n            x_0, y_0 = xys[-1]\n            x_1, y_1 = xys[0]\n        return y_0+(y_1-y_0)/(x_1-x_0)*(xnew-x_0)",
    "docstring": "Perform a linear value interpolation for the given `date` and\n        return the result.\n\n        Instantiate a 1-dimensional |SeasonalParameter| object:\n\n        >>> from hydpy.core.parametertools import SeasonalParameter\n        >>> class Par(SeasonalParameter):\n        ...     NDIM = 1\n        ...     TYPE = float\n        ...     TIME = None\n        >>> par = Par(None)\n        >>> par.simulationstep = '1d'\n        >>> par.shape = (None,)\n\n        Define three toy-value pairs:\n\n        >>> par(_1=2.0, _2=5.0, _12_31=4.0)\n\n        Passing a |Date| object matching a |TOY| object exactly returns\n        the corresponding |float| value:\n\n        >>> from hydpy import Date\n        >>> par.interp(Date('2000.01.01'))\n        2.0\n        >>> par.interp(Date('2000.02.01'))\n        5.0\n        >>> par.interp(Date('2000.12.31'))\n        4.0\n\n        For all intermediate points, |SeasonalParameter.interp| performs\n        a linear interpolation:\n\n        >>> from hydpy import round_\n        >>> round_(par.interp(Date('2000.01.02')))\n        2.096774\n        >>> round_(par.interp(Date('2000.01.31')))\n        4.903226\n        >>> round_(par.interp(Date('2000.02.02')))\n        4.997006\n        >>> round_(par.interp(Date('2000.12.30')))\n        4.002994\n\n        Linear interpolation is also allowed between the first and the\n        last pair when they do not capture the endpoints of the year:\n\n        >>> par(_1_2=2.0, _12_30=4.0)\n        >>> round_(par.interp(Date('2000.12.29')))\n        3.99449\n        >>> par.interp(Date('2000.12.30'))\n        4.0\n        >>> round_(par.interp(Date('2000.12.31')))\n        3.333333\n        >>> round_(par.interp(Date('2000.01.01')))\n        2.666667\n        >>> par.interp(Date('2000.01.02'))\n        2.0\n        >>> round_(par.interp(Date('2000.01.03')))\n        2.00551\n\n        The following example briefly shows interpolation performed for\n        a 2-dimensional parameter:\n\n        >>> Par.NDIM = 2\n        >>> par = Par(None)\n        >>> par.shape = (None, 2)\n        >>> par(_1_1=[1., 2.], _1_3=[-3, 0.])\n        >>> result = par.interp(Date('2000.01.02'))\n        >>> round_(result[0])\n        -1.0\n        >>> round_(result[1])\n        1.0"
  },
  {
    "code": "def _init_content_type_params(self):\n        ret = {}\n        if self.content_type:\n            params = self.content_type.split(';')[1:]\n            for param in params:\n                try:\n                    key, val = param.split('=')\n                    ret[naked(key)] = naked(val)\n                except ValueError:\n                    continue\n        return ret",
    "docstring": "Return the Content-Type request header parameters\n\n        Convert all of the semi-colon separated parameters into\n        a dict of key/vals. If for some stupid reason duplicate\n        & conflicting params are present then the last one\n        wins.\n\n        If a particular content-type param is non-compliant\n        by not being a simple key=val pair then it is skipped.\n\n        If no content-type header or params are present then\n        return an empty dict.\n\n        :return: dict"
  },
  {
    "code": "def send_messages(self, sms_messages):\n\t\tresults = []\n\t\tfor message in sms_messages:\n\t\t\ttry:\n\t\t\t\tassert message.connection is None\n\t\t\texcept AssertionError:\n\t\t\t\tif not self.fail_silently:\n\t\t\t\t\traise\n\t\t\tbackend = self.backend\n\t\t\tfail_silently = self.fail_silently\n\t\t\tresult = django_rq.enqueue(self._send, message, backend=backend, fail_silently=fail_silently)\n\t\t\tresults.append(result)\n\t\treturn results",
    "docstring": "Receives a list of SMSMessage instances and returns a list of RQ `Job` instances."
  },
  {
    "code": "def do_find(lookup, term):\n    space = defaultdict(list)\n    for name in lookup.keys():\n        space[name].append(name)\n    try:\n        iter_lookup = lookup.iteritems()\n    except AttributeError:\n        iter_lookup = lookup.items()\n    for name, definition in iter_lookup:\n        for keyword in definition['keywords']:\n            space[keyword].append(name)\n        space[definition['category']].append(name)\n    matches = fnmatch.filter(space.keys(), term)\n    results = set()\n    for match in matches:\n        results.update(space[match])\n    return [(r, translate(lookup, r)) for r in results]",
    "docstring": "Matches term glob against short-name, keywords and categories."
  },
  {
    "code": "def _is_common_text(self, inpath):\n        one_suffix = inpath[-2:]\n        two_suffix = inpath[-3:]\n        three_suffix = inpath[-4:]\n        four_suffix = inpath[-5:]\n        if one_suffix in self.common_text:\n            return True\n        elif two_suffix in self.common_text:\n            return True\n        elif three_suffix in self.common_text:\n            return True\n        elif four_suffix in self.common_text:\n            return True\n        else:\n            return False",
    "docstring": "private method to compare file path mime type to common text file types"
  },
  {
    "code": "def _load_resource_listing(resource_listing):\n    try:\n        with open(resource_listing) as resource_listing_file:\n            return simplejson.load(resource_listing_file)\n    except IOError:\n        raise ResourceListingNotFoundError(\n            'No resource listing found at {0}. Note that your json file '\n            'must be named {1}'.format(resource_listing, API_DOCS_FILENAME)\n        )",
    "docstring": "Load the resource listing from file, handling errors.\n\n    :param resource_listing: path to the api-docs resource listing file\n    :type  resource_listing: string\n    :returns: contents of the resource listing file\n    :rtype: dict"
  },
  {
    "code": "def _create_content_body(self, body):\n        frames = int(math.ceil(len(body) / float(self._max_frame_size)))\n        for offset in compatibility.RANGE(0, frames):\n            start_frame = self._max_frame_size * offset\n            end_frame = start_frame + self._max_frame_size\n            body_len = len(body)\n            if end_frame > body_len:\n                end_frame = body_len\n            yield pamqp_body.ContentBody(body[start_frame:end_frame])",
    "docstring": "Split body based on the maximum frame size.\n\n            This function is based on code from Rabbitpy.\n            https://github.com/gmr/rabbitpy\n\n        :param bytes|str|unicode body: Message payload\n\n        :rtype: collections.Iterable"
  },
  {
    "code": "def flush_pending(function):\n    s = boto3.Session()\n    client = s.client('lambda')\n    results = client.invoke(\n        FunctionName=function,\n        Payload=json.dumps({'detail-type': 'Scheduled Event'})\n    )\n    content = results.pop('Payload').read()\n    pprint.pprint(results)\n    pprint.pprint(json.loads(content))",
    "docstring": "Attempt to acquire any pending locks."
  },
  {
    "code": "def get_single_value(value):\n    if not all_elements_equal(value):\n        raise ValueError('Not all values are equal to each other.')\n    if is_scalar(value):\n        return value\n    return value.item(0)",
    "docstring": "Get a single value out of the given value.\n\n    This is meant to be used after a call to :func:`all_elements_equal` that returned True. With this\n    function we return a single number from the input value.\n\n    Args:\n        value (ndarray or number): a numpy array or a single number.\n\n    Returns:\n        number: a single number from the input\n\n    Raises:\n        ValueError: if not all elements are equal"
  },
  {
    "code": "def calc_normal_std_glorot(inmaps, outmaps, kernel=(1, 1)):\n    r\n    return np.sqrt(2. / (np.prod(kernel) * inmaps + outmaps))",
    "docstring": "r\"\"\"Calculates the standard deviation proposed by Glorot et al.\n\n    .. math::\n        \\sigma = \\sqrt{\\frac{2}{NK + M}}\n\n    Args:\n        inmaps (int): Map size of an input Variable, :math:`N`.\n        outmaps (int): Map size of an output Variable, :math:`M`.\n        kernel (:obj:`tuple` of :obj:`int`): Convolution kernel spatial shape.\n            In above definition, :math:`K` is the product of shape dimensions.\n            In Affine, the default value should be used.\n\n    Example:\n\n    .. code-block:: python\n\n        import nnabla as nn\n        import nnabla.parametric_functions as PF\n        import nnabla.initializer as I\n\n        x = nn.Variable([60,1,28,28])\n        s = I.calc_normal_std_glorot(x.shape[1],64)\n        w = I.NormalInitializer(s)\n        b = I.ConstantInitializer(0)\n        h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv')\n\n    References:\n        * `Glorot and Bengio. Understanding the difficulty of training deep\n          feedforward neural networks\n          <http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf>`_"
  },
  {
    "code": "def parse_css(self, css):\n        rulesets = self.ruleset_re.findall(css)\n        for (selector, declarations) in rulesets:\n            rule = Rule(self.parse_selector(selector))\n            rule.properties = self.parse_declarations(declarations)\n            self.rules.append(rule)",
    "docstring": "Parse a css style sheet into the CSS object.\n\n        For the moment this will only work for very simple css\n        documents.  It works by using regular expression matching css\n        syntax.  This is not bullet proof."
  },
  {
    "code": "def _validate_children(self):\n        for child in self._children:\n            if child.__class__ not in self._allowed_children:\n                raise ValueError(\n                    \"Child %s is not allowed as a children for this %s type entity.\" % (\n                        child, self.__class__\n                    )\n                )",
    "docstring": "Check that the children we have are allowed here."
  },
  {
    "code": "def refresh(self) -> None:\n        if not self:\n            self.values[:] = 0.\n        elif len(self) == 1:\n            values = list(self._toy2values.values())[0]\n            self.values[:] = self.apply_timefactor(values)\n        else:\n            for idx, date in enumerate(\n                    timetools.TOY.centred_timegrid(self.simulationstep)):\n                values = self.interp(date)\n                self.values[idx] = self.apply_timefactor(values)",
    "docstring": "Update the actual simulation values based on the toy-value pairs.\n\n        Usually, one does not need to call refresh explicitly.  The\n        \"magic\" methods __call__, __setattr__, and __delattr__ invoke\n        it automatically, when required.\n\n        Instantiate a 1-dimensional |SeasonalParameter| object:\n\n        >>> from hydpy.core.parametertools import SeasonalParameter\n        >>> class Par(SeasonalParameter):\n        ...     NDIM = 1\n        ...     TYPE = float\n        ...     TIME = None\n        >>> par = Par(None)\n        >>> par.simulationstep = '1d'\n        >>> par.shape = (None,)\n\n        When a |SeasonalParameter| object does not contain any toy-value\n        pairs yet, the method |SeasonalParameter.refresh| sets all actual\n        simulation values to zero:\n\n        >>> par.values = 1.\n        >>> par.refresh()\n        >>> par.values[0]\n        0.0\n\n        When there is only one toy-value pair, its values are relevant\n        for all actual simulation values:\n\n        >>> par.toy_1 = 2. # calls refresh automatically\n        >>> par.values[0]\n        2.0\n\n        Method |SeasonalParameter.refresh| performs a linear interpolation\n        for the central time points of each simulation time step.  Hence,\n        in the following example, the original values of the toy-value\n        pairs do not show up:\n\n        >>> par.toy_12_31 = 4.\n        >>> from hydpy import round_\n        >>> round_(par.values[0])\n        2.00274\n        >>> round_(par.values[-2])\n        3.99726\n        >>> par.values[-1]\n        3.0\n\n        If one wants to preserve the original values in this example, one\n        would have to set the corresponding toy instances in the middle of\n        some simulation step intervals:\n\n        >>> del par.toy_1\n        >>> del par.toy_12_31\n        >>> par.toy_1_1_12 = 2\n        >>> par.toy_12_31_12 = 4.\n        >>> par.values[0]\n        2.0\n        >>> round_(par.values[1])\n        2.005479\n        >>> round_(par.values[-2])\n        3.994521\n        >>> par.values[-1]\n        4.0"
  },
  {
    "code": "def trim_common_suffixes(strs, min_len=0):\n    if len(strs) < 2:\n        return 0, strs\n    rev_strs = [s[::-1] for s in strs]\n    trimmed, rev_strs = trim_common_prefixes(rev_strs, min_len)\n    if trimmed:\n        strs = [s[::-1] for s in rev_strs]\n    return trimmed, strs",
    "docstring": "trim common suffixes\n\n    >>> trim_common_suffixes('A', 1)\n    (0, 'A')"
  },
  {
    "code": "def slice_shift(self, periods=1, axis=0):\n        if periods == 0:\n            return self\n        if periods > 0:\n            vslicer = slice(None, -periods)\n            islicer = slice(periods, None)\n        else:\n            vslicer = slice(-periods, None)\n            islicer = slice(None, periods)\n        new_obj = self._slice(vslicer, axis=axis)\n        shifted_axis = self._get_axis(axis)[islicer]\n        new_obj.set_axis(shifted_axis, axis=axis, inplace=True)\n        return new_obj.__finalize__(self)",
    "docstring": "Equivalent to `shift` without copying data. The shifted data will\n        not include the dropped periods and the shifted axis will be smaller\n        than the original.\n\n        Parameters\n        ----------\n        periods : int\n            Number of periods to move, can be positive or negative\n\n        Returns\n        -------\n        shifted : same type as caller\n\n        Notes\n        -----\n        While the `slice_shift` is faster than `shift`, you may pay for it\n        later during alignment."
  },
  {
    "code": "def _exec_cmd(self, command, **kwargs):\n        kwargs['command'] = command\n        self._check_exclusive_parameters(**kwargs)\n        requests_params = self._handle_requests_params(kwargs)\n        session = self._meta_data['bigip']._meta_data['icr_session']\n        response = session.post(\n            self._meta_data['uri'], json=kwargs, **requests_params)\n        new_instance = self._stamp_out_core()\n        new_instance._local_update(response.json())\n        if 'commandResult' in new_instance.__dict__:\n            new_instance._check_command_result()\n        return new_instance",
    "docstring": "Create a new method as command has specific requirements.\n\n        There is a handful of the TMSH global commands supported,\n        so this method requires them as a parameter.\n\n        :raises: InvalidCommand"
  },
  {
    "code": "def remove_fields(layer, fields_to_remove):\n    index_to_remove = []\n    data_provider = layer.dataProvider()\n    for field in fields_to_remove:\n        index = layer.fields().lookupField(field)\n        if index != -1:\n            index_to_remove.append(index)\n    data_provider.deleteAttributes(index_to_remove)\n    layer.updateFields()",
    "docstring": "Remove fields from a vector layer.\n\n    :param layer: The vector layer.\n    :type layer: QgsVectorLayer\n\n    :param fields_to_remove: List of fields to remove.\n    :type fields_to_remove: list"
  },
  {
    "code": "def builtin_lookup(name):\n    builtin_astroid = MANAGER.ast_from_module(builtins)\n    if name == \"__dict__\":\n        return builtin_astroid, ()\n    try:\n        stmts = builtin_astroid.locals[name]\n    except KeyError:\n        stmts = ()\n    return builtin_astroid, stmts",
    "docstring": "lookup a name into the builtin module\n    return the list of matching statements and the astroid for the builtin\n    module"
  },
  {
    "code": "def num_lines(self):\n        if self.from_stdin:\n            return None\n        if not self._num_lines:\n            self._iterate_lines()\n        return self._num_lines",
    "docstring": "Lazy evaluation of the number of lines.\n\n        Returns None for stdin input currently."
  },
  {
    "code": "def competence(s):\n        if any([isinstance(s, cls)\n                for cls in [distributions.Wishart, distributions.WishartCov]]):\n            return 2\n        else:\n            return 0",
    "docstring": "The competence function for MatrixMetropolis"
  },
  {
    "code": "def search_drama_series(self, query_string):\n        result = self._android_api.list_series(\n            media_type=ANDROID.MEDIA_TYPE_DRAMA,\n            filter=ANDROID.FILTER_PREFIX + query_string)\n        return result",
    "docstring": "Search drama series list by series name, case-sensitive\n\n        @param str query_string     string to search for, note that the search\n                                        is very simplistic and only matches against\n                                        the start of the series name, ex) search\n                                        for \"space\" matches \"Space Brothers\" but\n                                        wouldn't match \"Brothers Space\"\n        @return list<crunchyroll.models.Series>"
  },
  {
    "code": "def _detect_timezone_windows():\n  global win32timezone_to_en\n  tzi = DTZI_c()\n  kernel32 = ctypes.windll.kernel32\n  getter = kernel32.GetTimeZoneInformation\n  getter = getattr(kernel32, \"GetDynamicTimeZoneInformation\", getter)\n  _ = getter(ctypes.byref(tzi))\n  win32tz_key_name = tzi.key_name\n  if not win32tz_key_name:\n    if win32timezone is None:\n      return None\n    win32tz_name = tzi.standard_name\n    if not win32timezone_to_en:\n      win32timezone_to_en = dict(\n          win32timezone.TimeZoneInfo._get_indexed_time_zone_keys(\"Std\"))\n    win32tz_key_name = win32timezone_to_en.get(win32tz_name, win32tz_name)\n  territory = locale.getdefaultlocale()[0].split(\"_\", 1)[1]\n  olson_name = win32tz_map.win32timezones.get((win32tz_key_name, territory), win32tz_map.win32timezones.get(win32tz_key_name, None))\n  if not olson_name:\n    return None\n  if not isinstance(olson_name, str):\n    olson_name = olson_name.encode(\"ascii\")\n  return pytz.timezone(olson_name)",
    "docstring": "Detect timezone on the windows platform."
  },
  {
    "code": "def ConfigureLogging(\n    debug_output=False, filename=None, mode='w', quiet_mode=False):\n  for handler in logging.root.handlers:\n    logging.root.removeHandler(handler)\n  logger = logging.getLogger()\n  if filename and filename.endswith('.gz'):\n    handler = CompressedFileHandler(filename, mode=mode)\n  elif filename:\n    handler = logging.FileHandler(filename, mode=mode)\n  else:\n    handler = logging.StreamHandler()\n  format_string = (\n      '%(asctime)s [%(levelname)s] (%(processName)-10s) PID:%(process)d '\n      '<%(module)s> %(message)s')\n  formatter = logging.Formatter(format_string)\n  handler.setFormatter(formatter)\n  if debug_output:\n    level = logging.DEBUG\n  elif quiet_mode:\n    level = logging.WARNING\n  else:\n    level = logging.INFO\n  logger.setLevel(level)\n  handler.setLevel(level)\n  logger.addHandler(handler)",
    "docstring": "Configures the logging root logger.\n\n  Args:\n    debug_output (Optional[bool]): True if the logging should include debug\n        output.\n    filename (Optional[str]): log filename.\n    mode (Optional[str]): log file access mode.\n    quiet_mode (Optional[bool]): True if the logging should not include\n        information output. Note that debug_output takes precedence over\n        quiet_mode."
  },
  {
    "code": "def search_directory(self, **kwargs):\n        search_response = self.request('SearchDirectory', kwargs)\n        result = {}\n        items = {\n            \"account\": zobjects.Account.from_dict,\n            \"domain\": zobjects.Domain.from_dict,\n            \"dl\": zobjects.DistributionList.from_dict,\n            \"cos\": zobjects.COS.from_dict,\n            \"calresource\": zobjects.CalendarResource.from_dict\n        }\n        for obj_type, func in items.items():\n            if obj_type in search_response:\n                if isinstance(search_response[obj_type], list):\n                    result[obj_type] = [\n                        func(v) for v in search_response[obj_type]]\n                else:\n                    result[obj_type] = func(search_response[obj_type])\n        return result",
    "docstring": "SearchAccount is deprecated, using SearchDirectory\n\n        :param query: Query string - should be an LDAP-style filter\n        string (RFC 2254)\n        :param limit: The maximum number of accounts to return\n        (0 is default and means all)\n        :param offset: The starting offset (0, 25, etc)\n        :param domain: The domain name to limit the search to\n        :param applyCos: applyCos - Flag whether or not to apply the COS\n        policy to account. Specify 0 (false) if only requesting attrs that\n        aren't inherited from COS\n        :param applyConfig: whether or not to apply the global config attrs to\n        account. specify 0 (false) if only requesting attrs that aren't\n        inherited from global config\n        :param sortBy: Name of attribute to sort on. Default is the account\n        name.\n        :param types: Comma-separated list of types to return. Legal values\n        are: accounts|distributionlists|aliases|resources|domains|coses\n        (default is accounts)\n        :param sortAscending: Whether to sort in ascending order. Default is\n        1 (true)\n        :param countOnly: Whether response should be count only. Default is\n        0 (false)\n        :param attrs: Comma-seperated list of attrs to return (\"displayName\",\n        \"zimbraId\", \"zimbraAccountStatus\")\n        :return: dict of list of \"account\" \"alias\" \"dl\" \"calresource\" \"domain\"\n        \"cos\""
  },
  {
    "code": "def xgb_progressbar(rounds=1000):\n    pbar = tqdm(total=rounds)\n    def callback(_, ):\n        pbar.update(1)\n    return callback",
    "docstring": "Progressbar for xgboost using tqdm library.\n\n    Examples\n    --------\n\n    >>> model = xgb.train(params, X_train, 1000, callbacks=[xgb_progress(1000), ])"
  },
  {
    "code": "def attr(obj, attr):\n    if not obj or not hasattr(obj, attr):\n        return ''\n    return getattr(obj, attr, '')",
    "docstring": "Does the same thing as getattr.\n\n    getattr(obj, attr, '')"
  },
  {
    "code": "def _get_hyperparameters(self):\n        hyperparameters = {}\n        for key in self._hyperparameters:\n            hyperparameters[key] = getattr(self, key)\n        return hyperparameters",
    "docstring": "Get internal optimization parameters."
  },
  {
    "code": "def guess_mime_type(self, path):\n\t\t_, ext = posixpath.splitext(path)\n\t\tif ext in self.extensions_map:\n\t\t\treturn self.extensions_map[ext]\n\t\text = ext.lower()\n\t\treturn self.extensions_map[ext if ext in self.extensions_map else '']",
    "docstring": "Guess an appropriate MIME type based on the extension of the\n\t\tprovided path.\n\n\t\t:param str path: The of the file to analyze.\n\t\t:return: The guessed MIME type of the default if non are found.\n\t\t:rtype: str"
  },
  {
    "code": "def moz_info(self):\n        if 'moz_info' not in self._memo:\n            self._memo['moz_info'] = _get_url(self.artifact_url('mozinfo.json')).json()\n        return self._memo['moz_info']",
    "docstring": "Return the build's mozinfo"
  },
  {
    "code": "def take_ownership(self, **kwargs):\n        path = '%s/%s/take_ownership' % (self.manager.path, self.get_id())\n        server_data = self.manager.gitlab.http_post(path, **kwargs)\n        self._update_attrs(server_data)",
    "docstring": "Update the owner of a pipeline schedule.\n\n        Args:\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabOwnershipError: If the request failed"
  },
  {
    "code": "def get(self, section, key):\n        try:\n            return self.parser.get(section, key)\n        except (NoOptionError, NoSectionError) as e:\n            logger.warning(\"%s\", e)\n            return None",
    "docstring": "get function reads the config value for the requested section and\n        key and returns it\n\n        Parameters:\n            * **section (string):** the section to look for the config value either - oxd, client\n            * **key (string):** the key for the config value required\n\n        Returns:\n            **value (string):** the function returns the value of the key in the appropriate format if found or returns None if such a section or key couldnot be found\n\n        Example:\n            config = Configurer(location)\n            oxd_port = config.get('oxd', 'port')  # returns the port of the oxd"
  },
  {
    "code": "def visualize_saliency(model, layer_idx, filter_indices, seed_input, wrt_tensor=None,\n                       backprop_modifier=None, grad_modifier='absolute', keepdims=False):\n    if backprop_modifier is not None:\n        modifier_fn = get(backprop_modifier)\n        model = modifier_fn(model)\n    losses = [\n        (ActivationMaximization(model.layers[layer_idx], filter_indices), -1)\n    ]\n    return visualize_saliency_with_losses(model.input, losses, seed_input, wrt_tensor, grad_modifier, keepdims)",
    "docstring": "Generates an attention heatmap over the `seed_input` for maximizing `filter_indices`\n    output in the given `layer_idx`.\n\n    Args:\n        model: The `keras.models.Model` instance. The model input shape must be: `(samples, channels, image_dims...)`\n            if `image_data_format=channels_first` or `(samples, image_dims..., channels)` if\n            `image_data_format=channels_last`.\n        layer_idx: The layer index within `model.layers` whose filters needs to be visualized.\n        filter_indices: filter indices within the layer to be maximized.\n            If None, all filters are visualized. (Default value = None)\n            For `keras.layers.Dense` layer, `filter_idx` is interpreted as the output index.\n            If you are visualizing final `keras.layers.Dense` layer, consider switching 'softmax' activation for\n            'linear' using [utils.apply_modifications](vis.utils.utils#apply_modifications) for better results.\n        seed_input: The model input for which activation map needs to be visualized.\n        wrt_tensor: Short for, with respect to. The gradients of losses are computed with respect to this tensor.\n            When None, this is assumed to be the same as `input_tensor` (Default value: None)\n        backprop_modifier: backprop modifier to use. See [backprop_modifiers](vis.backprop_modifiers.md). If you don't\n            specify anything, no backprop modification is applied. (Default value = None)\n        grad_modifier: gradient modifier to use. See [grad_modifiers](vis.grad_modifiers.md). By default `absolute`\n            value of gradients are used. To visualize positive or negative gradients, use `relu` and `negate`\n            respectively. (Default value = 'absolute')\n        keepdims: A boolean, whether to keep the dimensions or not.\n            If keepdims is False, the channels axis is deleted.\n            If keepdims is True, the grad with same shape as input_tensor is returned. (Default value: False)\n\n    Example:\n        If you wanted to visualize attention over 'bird' category, say output index 22 on the\n        final `keras.layers.Dense` layer, then, `filter_indices = [22]`, `layer = dense_layer`.\n\n        One could also set filter indices to more than one value. For example, `filter_indices = [22, 23]` should\n        (hopefully) show attention map that corresponds to both 22, 23 output categories.\n\n    Returns:\n        The heatmap image indicating the `seed_input` regions whose change would most contribute towards\n        maximizing the output of `filter_indices`."
  },
  {
    "code": "def set_auth_key_from_file(user,\n                           source,\n                           config='.ssh/authorized_keys',\n                           saltenv='base',\n                           fingerprint_hash_type=None):\n    lfile = __salt__['cp.cache_file'](source, saltenv)\n    if not os.path.isfile(lfile):\n        raise CommandExecutionError(\n            'Failed to pull key file from salt file server'\n        )\n    s_keys = _validate_keys(lfile, fingerprint_hash_type)\n    if not s_keys:\n        err = (\n            'No keys detected in {0}. Is file properly formatted?'.format(\n                source\n            )\n        )\n        log.error(err)\n        __context__['ssh_auth.error'] = err\n        return 'fail'\n    else:\n        rval = ''\n        for key in s_keys:\n            rval += set_auth_key(\n                user,\n                key,\n                enc=s_keys[key]['enc'],\n                comment=s_keys[key]['comment'],\n                options=s_keys[key]['options'],\n                config=config,\n                cache_keys=list(s_keys.keys()),\n                fingerprint_hash_type=fingerprint_hash_type\n            )\n        if 'fail' in rval:\n            return 'fail'\n        elif 'replace' in rval:\n            return 'replace'\n        elif 'new' in rval:\n            return 'new'\n        else:\n            return 'no change'",
    "docstring": "Add a key to the authorized_keys file, using a file as the source.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' ssh.set_auth_key_from_file <user> salt://ssh_keys/<user>.id_rsa.pub"
  },
  {
    "code": "def randomize_es(es_queryset):\n    return es_queryset.query(\n        query.FunctionScore(\n            functions=[function.RandomScore()]\n        )\n    ).sort(\"-_score\")",
    "docstring": "Randomize an elasticsearch queryset."
  },
  {
    "code": "def __is_valid_pos(pos_tuple, valid_pos):\n    def is_valid_pos(valid_pos_tuple):\n        length_valid_pos_tuple = len(valid_pos_tuple)\n        if valid_pos_tuple == pos_tuple[:length_valid_pos_tuple]:\n            return True\n        else:\n            return False\n    seq_bool_flags = [is_valid_pos(valid_pos_tuple) for valid_pos_tuple in valid_pos]\n    if True in set(seq_bool_flags):\n        return True\n    else:\n        return False",
    "docstring": "This function checks token's pos is with in POS set that user specified.\n    If token meets all conditions, Return True; else return False"
  },
  {
    "code": "def attrsignal(descriptor, signal_name, *, defer=False):\n    def decorator(f):\n        add_handler_spec(\n            f,\n            _attrsignal_spec(descriptor, signal_name, f, defer)\n        )\n        return f\n    return decorator",
    "docstring": "Connect the decorated method or coroutine method to the addressed signal on\n    a descriptor.\n\n    :param descriptor: The descriptor to connect to.\n    :type descriptor: :class:`Descriptor` subclass.\n    :param signal_name: Attribute name of the signal to connect to\n    :type signal_name: :class:`str`\n    :param defer: Flag indicating whether deferred execution of the decorated\n                  method is desired; see below for details.\n    :type defer: :class:`bool`\n\n    The signal is discovered by accessing the attribute with the name\n    `signal_name` on the :attr:`~Descriptor.value_type` of the `descriptor`.\n\n    During instantiation of the service, the value of the descriptor is used\n    to obtain the signal and then the decorated method is connected to the\n    signal.\n\n    If the signal is a :class:`.callbacks.Signal` and `defer` is false, the\n    decorated object is connected using the default\n    :attr:`~.callbacks.AdHocSignal.STRONG` mode.\n\n    If the signal is a :class:`.callbacks.Signal` and `defer` is true and the\n    decorated object is a coroutine function, the\n    :attr:`~.callbacks.AdHocSignal.SPAWN_WITH_LOOP` mode with the default\n    asyncio event loop is used. If the decorated object is not a coroutine\n    function, :attr:`~.callbacks.AdHocSignal.ASYNC_WITH_LOOP` is used instead.\n\n    If the signal is a :class:`.callbacks.SyncSignal`, `defer` must be false\n    and the decorated object must be a coroutine function.\n\n    .. versionadded:: 0.9"
  },
  {
    "code": "async def _set_annotations(entity_tag, annotations, connection):\n    log.debug('Updating annotations on %s', entity_tag)\n    facade = client.AnnotationsFacade.from_connection(connection)\n    args = client.EntityAnnotations(\n        entity=entity_tag,\n        annotations=annotations,\n    )\n    return await facade.Set([args])",
    "docstring": "Set annotations on the specified entity.\n\n    :param annotations map[string]string: the annotations as key/value\n        pairs."
  },
  {
    "code": "def clean_intersections(G, tolerance=15, dead_ends=False):\n    if not dead_ends:\n        if 'streets_per_node' in G.graph:\n            streets_per_node = G.graph['streets_per_node']\n        else:\n            streets_per_node = count_streets_per_node(G)\n        dead_end_nodes = [node for node, count in streets_per_node.items() if count <= 1]\n        G = G.copy()\n        G.remove_nodes_from(dead_end_nodes)\n    gdf_nodes = graph_to_gdfs(G, edges=False)\n    buffered_nodes = gdf_nodes.buffer(tolerance).unary_union\n    if isinstance(buffered_nodes, Polygon):\n        buffered_nodes = [buffered_nodes]\n    unified_intersections = gpd.GeoSeries(list(buffered_nodes))\n    intersection_centroids = unified_intersections.centroid\n    return intersection_centroids",
    "docstring": "Clean-up intersections comprising clusters of nodes by merging them and\n    returning their centroids.\n\n    Divided roads are represented by separate centerline edges. The intersection\n    of two divided roads thus creates 4 nodes, representing where each edge\n    intersects a perpendicular edge. These 4 nodes represent a single\n    intersection in the real world. This function cleans them up by buffering\n    their points to an arbitrary distance, merging overlapping buffers, and\n    taking their centroid. For best results, the tolerance argument should be\n    adjusted to approximately match street design standards in the specific\n    street network.\n\n    Parameters\n    ----------\n    G : networkx multidigraph\n    tolerance : float\n        nodes within this distance (in graph's geometry's units) will be\n        dissolved into a single intersection\n    dead_ends : bool\n        if False, discard dead-end nodes to return only street-intersection\n        points\n\n    Returns\n    ----------\n    intersection_centroids : geopandas.GeoSeries\n        a GeoSeries of shapely Points representing the centroids of street\n        intersections"
  },
  {
    "code": "def __parseDatasets(self):\n        datasets = []\n        if self.__dataItem.has_key('dataSets'):\n            for dataset in self.__dataItem['dataSets']:\n                datasets.append(DataSet(Sitools2Abstract.getBaseUrl(self), dataset))\n        return datasets",
    "docstring": "Returns the list of Dataset related to the project."
  },
  {
    "code": "def replace(self, key, val, time=0, min_compress_len=0):\n        return self._set(\"replace\", key, val, time, min_compress_len)",
    "docstring": "Replace existing key with value.\n\n        Like L{set}, but only stores in memcache if the key already exists.\n        The opposite of L{add}.\n\n        @return: Nonzero on success.\n        @rtype: int"
  },
  {
    "code": "def write(self, string):\n        string = string.rstrip()\n        if string:\n            self.logger.critical(string)",
    "docstring": "Erase newline from a string and write to the logger."
  },
  {
    "code": "def expand(sql, args=None):\n    sql, args = SqlModule.get_sql_statement_with_environment(sql, args)\n    return _sql_statement.SqlStatement.format(sql._sql, args)",
    "docstring": "Expand a SqlStatement, query string or SqlModule with a set of arguments.\n\n    Args:\n      sql: a SqlStatement, %%sql module, or string containing a query.\n      args: a string of command line arguments or a dictionary of values. If a string, it is\n          passed to the argument parser for the SqlModule associated with the SqlStatement or\n          SqlModule. If a dictionary, it is used to override any default arguments from the\n          argument parser. If the sql argument is a string then args must be None or a dictionary\n          as in this case there is no associated argument parser.\n    Returns:\n      The expanded SQL, list of referenced scripts, and list of referenced external tables."
  },
  {
    "code": "def _read_dataframes_100k(path):\n    import pandas\n    ratings = pandas.read_table(os.path.join(path, \"u.data\"),\n                                names=['userId', 'movieId', 'rating', 'timestamp'])\n    movies = pandas.read_csv(os.path.join(path, \"u.item\"),\n                             names=['movieId', 'title'],\n                             usecols=[0, 1],\n                             delimiter='|',\n                             encoding='ISO-8859-1')\n    return ratings, movies",
    "docstring": "reads in the movielens 100k dataset"
  },
  {
    "code": "def construct_url(ip_address: str) -> str:\r\n    if 'http://' not in ip_address and 'https://' not in ip_address:\r\n        ip_address = '{}{}'.format('http://', ip_address)\r\n    if ip_address[-1] == '/':\r\n        ip_address = ip_address[:-1]\r\n    return ip_address",
    "docstring": "Construct the URL with a given IP address."
  },
  {
    "code": "def normalize_response(response, request=None):\n    if isinstance(response, Response):\n        return response\n    if request is not None and not isinstance(request, Request):\n        request = normalize_request(request)\n    for normalizer in RESPONSE_NORMALIZERS:\n        try:\n            return normalizer(response, request=request)\n        except TypeError:\n            continue\n    raise ValueError(\"Unable to normalize the provided response\")",
    "docstring": "Given a response, normalize it to the internal Response class.  This also\n    involves normalizing the associated request object."
  },
  {
    "code": "def pieces(self, piece_type: PieceType, color: Color) -> \"SquareSet\":\n        return SquareSet(self.pieces_mask(piece_type, color))",
    "docstring": "Gets pieces of the given type and color.\n\n        Returns a :class:`set of squares <chess.SquareSet>`."
  },
  {
    "code": "def simulate(self):\n        min_ = (-sys.maxsize - 1) if self._min is None else self._min\n        max_ = sys.maxsize if self._max is None else self._max\n        return random.randint(min_, max_)",
    "docstring": "Generates a random integer in the available range."
  },
  {
    "code": "def start_log(level=logging.DEBUG, filename=None):\n    if filename is None:\n        tstr = time.ctime()\n        tstr = tstr.replace(' ', '.')\n        tstr = tstr.replace(':', '.')\n        filename = 'deblur.log.%s' % tstr\n    logging.basicConfig(filename=filename, level=level,\n                        format='%(levelname)s(%(thread)d)'\n                        '%(asctime)s:%(message)s')\n    logger = logging.getLogger(__name__)\n    logger.info('*************************')\n    logger.info('deblurring started')",
    "docstring": "start the logger for the run\n\n    Parameters\n    ----------\n    level : int, optional\n        logging.DEBUG, logging.INFO etc. for the log level (between 0-50).\n    filename : str, optional\n      name of the filename to save the log to or\n      None (default) to use deblur.log.TIMESTAMP"
  },
  {
    "code": "def fit_fn(distr, xvals, alpha, thresh):\n    xvals = numpy.array(xvals)\n    fit = fitfn_dict[distr](xvals, alpha, thresh)\n    numpy.putmask(fit, xvals < thresh, 0.)\n    return fit",
    "docstring": "The fitted function normalized to 1 above threshold\n\n    To normalize to a given total count multiply by the count.\n\n    Parameters\n    ----------\n    xvals : sequence of floats\n        Values where the function is to be evaluated\n    alpha : float\n        The fitted parameter\n    thresh : float\n        Threshold value applied to fitted values\n\n    Returns\n    -------\n    fit : array of floats\n        Fitted function at the requested xvals"
  },
  {
    "code": "def layers():\n  global _cached_layers\n  if _cached_layers is not None:\n    return _cached_layers\n  layers_module = tf.layers\n  try:\n    from tensorflow.python import tf2\n    if tf2.enabled():\n      tf.logging.info(\"Running in V2 mode, using Keras layers.\")\n      layers_module = tf.keras.layers\n  except ImportError:\n    pass\n  _cached_layers = layers_module\n  return layers_module",
    "docstring": "Get the layers module good for TF 1 and TF 2 work for now."
  },
  {
    "code": "def sha_hash(self) -> str:\n        return hashlib.sha256(self.signed_raw().encode(\"ascii\")).hexdigest().upper()",
    "docstring": "Return uppercase hex sha256 hash from signed raw document\n\n        :return:"
  },
  {
    "code": "def _generate_ngrams_with_context_helper(ngrams_iter: iter, ngrams_len: int) -> map:\n        return map(lambda term: (term[1], term[0], term[0] + ngrams_len), enumerate(ngrams_iter))",
    "docstring": "Updates the end index"
  },
  {
    "code": "def crypto_config_from_kwargs(fallback, **kwargs):\n    try:\n        crypto_config = kwargs.pop(\"crypto_config\")\n    except KeyError:\n        try:\n            fallback_kwargs = {\"table_name\": kwargs[\"TableName\"]}\n        except KeyError:\n            fallback_kwargs = {}\n        crypto_config = fallback(**fallback_kwargs)\n    return crypto_config, kwargs",
    "docstring": "Pull all encryption-specific parameters from the request and use them to build a crypto config.\n\n    :returns: crypto config and updated kwargs\n    :rtype: dynamodb_encryption_sdk.encrypted.CryptoConfig and dict"
  },
  {
    "code": "def notify(self):\n        if self._notify is None:\n            from twilio.rest.notify import Notify\n            self._notify = Notify(self)\n        return self._notify",
    "docstring": "Access the Notify Twilio Domain\n\n        :returns: Notify Twilio Domain\n        :rtype: twilio.rest.notify.Notify"
  },
  {
    "code": "def unhash(text, hashes):\n    def retrieve_match(match):\n        return hashes[match.group(0)]\n    while re_hash.search(text):\n        text = re_hash.sub(retrieve_match, text)\n    text = re_pre_tag.sub(lambda m: re.sub('^' + m.group(1), '', m.group(0), flags=re.M), text)\n    return text",
    "docstring": "Unhashes all hashed entites in the hashes dictionary.\n\n    The pattern for hashes is defined by re_hash. After everything is\n    unhashed, <pre> blocks are \"pulled out\" of whatever indentation\n    level in which they used to be (e.g. in a list)."
  },
  {
    "code": "def converter_loader(app, entry_points=None, modules=None):\n    if entry_points:\n        for entry_point in entry_points:\n            for ep in pkg_resources.iter_entry_points(entry_point):\n                try:\n                    app.url_map.converters[ep.name] = ep.load()\n                except Exception:\n                    app.logger.error(\n                        'Failed to initialize entry point: {0}'.format(ep))\n                    raise\n    if modules:\n        app.url_map.converters.update(**modules)",
    "docstring": "Run default converter loader.\n\n    :param entry_points: List of entry points providing to Blue.\n    :param modules: Map of coverters.\n\n    .. versionadded: 1.0.0"
  },
  {
    "code": "def deriv2(self, p):\n        return self.power * (self.power - 1) * np.power(p, self.power - 2)",
    "docstring": "Second derivative of the power transform\n\n        Parameters\n        ----------\n        p : array-like\n            Mean parameters\n\n        Returns\n        --------\n        g''(p) : array\n            Second derivative of the power transform of `p`\n\n        Notes\n        -----\n        g''(`p`) = `power` * (`power` - 1) * `p`**(`power` - 2)"
  },
  {
    "code": "def valid_loc(self,F=None):\n        if F is not None:\n            return [i for i,f in enumerate(F) if np.all(f < self.max_fit) and np.all(f >= 0)]\n        else:\n            return [i for i,f in enumerate(self.F) if np.all(f < self.max_fit) and np.all(f >= 0)]",
    "docstring": "returns the indices of individuals with valid fitness."
  },
  {
    "code": "def makediagram(edges):\n    graph = pydot.Dot(graph_type='digraph')\n    nodes = edges2nodes(edges)\n    epnodes = [(node, \n        makeanode(node[0])) for node in nodes if nodetype(node)==\"epnode\"]\n    endnodes = [(node, \n        makeendnode(node[0])) for node in nodes if nodetype(node)==\"EndNode\"]\n    epbr = [(node, makeabranch(node)) for node in nodes if not istuple(node)]\n    nodedict = dict(epnodes + epbr + endnodes)\n    for value in list(nodedict.values()):\n        graph.add_node(value)\n    for e1, e2 in edges:\n        graph.add_edge(pydot.Edge(nodedict[e1], nodedict[e2]))\n    return graph",
    "docstring": "make the diagram with the edges"
  },
  {
    "code": "def create_variable(self, varname, vtype=None):\n        var_types = ('string', 'int', 'boolean', 'double')\n        vname = varname\n        var = None\n        type_from_name = 'string'\n        if ':' in varname:\n            type_from_name, vname = varname.split(':')\n            if type_from_name not in (var_types):\n                type_from_name, vname = vname, type_from_name\n                if type_from_name not in (var_types):\n                    raise Exception('Undefined variable type in \"{0}\"'.format(varname))\n        if vname in self.tkvariables:\n            var = self.tkvariables[vname]\n        else:\n            if vtype is None:\n                if type_from_name == 'int':\n                    var = tkinter.IntVar()\n                elif type_from_name == 'boolean':\n                    var = tkinter.BooleanVar()\n                elif type_from_name == 'double':\n                    var = tkinter.DoubleVar()\n                else:\n                    var = tkinter.StringVar()\n            else:\n                var = vtype()\n            self.tkvariables[vname] = var\n        return var",
    "docstring": "Create a tk variable.\n        If the variable was created previously return that instance."
  },
  {
    "code": "def calculate_set_values(self):\n        for ac in self.asset_classes:\n            ac.alloc_value = self.total_amount * ac.allocation / Decimal(100)",
    "docstring": "Calculate the expected totals based on set allocations"
  },
  {
    "code": "def get(self, *, search, limit=0, headers=None):\n        return self.transport.forward_request(\n            method='GET',\n            path=self.path,\n            params={'search': search, 'limit': limit},\n            headers=headers\n        )",
    "docstring": "Retrieves the assets that match a given text search string.\n\n        Args:\n            search (str): Text search string.\n            limit (int): Limit the number of returned documents. Defaults to\n                zero meaning that it returns all the matching assets.\n            headers (dict): Optional headers to pass to the request.\n\n        Returns:\n            :obj:`list` of :obj:`dict`: List of assets that match the query."
  },
  {
    "code": "def setEnable(self, status, wifiInterfaceId=1, timeout=1):\n        namespace = Wifi.getServiceType(\"setEnable\") + str(wifiInterfaceId)\n        uri = self.getControlURL(namespace)\n        if status:\n            setStatus = 1\n        else:\n            setStatus = 0\n        self.execute(uri, namespace, \"SetEnable\", timeout=timeout, NewEnable=setStatus)",
    "docstring": "Set enable status for a Wifi interface, be careful you don't cut yourself off.\n\n        :param bool status: enable or disable the interface\n        :param int wifiInterfaceId: the id of the Wifi interface\n        :param float timeout: the timeout to wait for the action to be executed"
  },
  {
    "code": "def _with_primary(max_staleness, selection):\n    primary = selection.primary\n    sds = []\n    for s in selection.server_descriptions:\n        if s.server_type == SERVER_TYPE.RSSecondary:\n            staleness = (\n                (s.last_update_time - s.last_write_date) -\n                (primary.last_update_time - primary.last_write_date) +\n                selection.heartbeat_frequency)\n            if staleness <= max_staleness:\n                sds.append(s)\n        else:\n            sds.append(s)\n    return selection.with_server_descriptions(sds)",
    "docstring": "Apply max_staleness, in seconds, to a Selection with a known primary."
  },
  {
    "code": "def verify(obj, times=1, atleast=None, atmost=None, between=None,\n           inorder=False):\n    if isinstance(obj, str):\n        obj = get_obj(obj)\n    verification_fn = _get_wanted_verification(\n        times=times, atleast=atleast, atmost=atmost, between=between)\n    if inorder:\n        verification_fn = verification.InOrder(verification_fn)\n    theMock = _get_mock_or_raise(obj)\n    class Verify(object):\n        def __getattr__(self, method_name):\n            return invocation.VerifiableInvocation(\n                theMock, method_name, verification_fn)\n    return Verify()",
    "docstring": "Central interface to verify interactions.\n\n    `verify` uses a fluent interface::\n\n        verify(<obj>, times=2).<method_name>(<args>)\n\n    `args` can be as concrete as necessary. Often a catch-all is enough,\n    especially if you're working with strict mocks, bc they throw at call\n    time on unwanted, unconfigured arguments::\n\n        from mockito import ANY, ARGS, KWARGS\n        when(manager).add_tasks(1, 2, 3)\n        ...\n        # no need to duplicate the specification; every other argument pattern\n        # would have raised anyway.\n        verify(manager).add_tasks(1, 2, 3)  # duplicates `when`call\n        verify(manager).add_tasks(*ARGS)\n        verify(manager).add_tasks(...)       # Py3\n        verify(manager).add_tasks(Ellipsis)  # Py2"
  },
  {
    "code": "def list_functions(region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    ret = []\n    for funcs in __utils__['boto3.paged_call'](conn.list_functions):\n        ret += funcs['Functions']\n    return ret",
    "docstring": "List all Lambda functions visible in the current scope.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_lambda.list_functions"
  },
  {
    "code": "def push_build(id, tag_prefix):\n    req = swagger_client.BuildRecordPushRequestRest()\n    req.tag_prefix = tag_prefix\n    req.build_record_id = id\n    response = utils.checked_api_call(pnc_api.build_push, 'push', body=req)\n    if response:\n        return utils.format_json_list(response)",
    "docstring": "Push build to Brew"
  },
  {
    "code": "def get_processor_cpuid_leaf(self, cpu_id, leaf, sub_leaf):\n        if not isinstance(cpu_id, baseinteger):\n            raise TypeError(\"cpu_id can only be an instance of type baseinteger\")\n        if not isinstance(leaf, baseinteger):\n            raise TypeError(\"leaf can only be an instance of type baseinteger\")\n        if not isinstance(sub_leaf, baseinteger):\n            raise TypeError(\"sub_leaf can only be an instance of type baseinteger\")\n        (val_eax, val_ebx, val_ecx, val_edx) = self._call(\"getProcessorCPUIDLeaf\",\n                     in_p=[cpu_id, leaf, sub_leaf])\n        return (val_eax, val_ebx, val_ecx, val_edx)",
    "docstring": "Returns the CPU cpuid information for the specified leaf.\n\n        in cpu_id of type int\n            Identifier of the CPU. The CPU most be online.\n            \n            The current implementation might not necessarily return the\n            description for this exact CPU.\n\n        in leaf of type int\n            CPUID leaf index (eax).\n\n        in sub_leaf of type int\n            CPUID leaf sub index (ecx). This currently only applies to cache\n            information on Intel CPUs. Use 0 if retrieving values for\n            :py:func:`IMachine.set_cpuid_leaf` .\n\n        out val_eax of type int\n            CPUID leaf value for register eax.\n\n        out val_ebx of type int\n            CPUID leaf value for register ebx.\n\n        out val_ecx of type int\n            CPUID leaf value for register ecx.\n\n        out val_edx of type int\n            CPUID leaf value for register edx."
  },
  {
    "code": "def page(\n        self, title=None, pageid=None, auto_suggest=True, redirect=True, preload=False\n    ):\n        if (title is None or title.strip() == \"\") and pageid is None:\n            raise ValueError(\"Either a title or a pageid must be specified\")\n        elif title:\n            if auto_suggest:\n                temp_title = self.suggest(title)\n                if temp_title is None:\n                    raise PageError(title=title)\n                else:\n                    title = temp_title\n            return MediaWikiPage(self, title, redirect=redirect, preload=preload)\n        else:\n            return MediaWikiPage(self, pageid=pageid, preload=preload)",
    "docstring": "Get MediaWiki page based on the provided title or pageid\n\n            Args:\n                title (str): Page title\n                pageid (int): MediaWiki page identifier\n                auto-suggest (bool): **True:** Allow page title auto-suggest\n                redirect (bool): **True:** Follow page redirects\n                preload (bool): **True:** Load most page properties\n            Raises:\n                ValueError: when title is blank or None and no pageid is \\\n                            provided\n            Raises:\n                :py:func:`mediawiki.exceptions.PageError`: if page does \\\n                not exist\n            Note:\n                Title takes precedence over pageid if both are provided"
  },
  {
    "code": "def _get_unit_data_from_expr(unit_expr, unit_symbol_lut):\n    if isinstance(unit_expr, Number):\n        if unit_expr is sympy_one:\n            return (1.0, sympy_one)\n        return (float(unit_expr), sympy_one)\n    if isinstance(unit_expr, Symbol):\n        return _lookup_unit_symbol(unit_expr.name, unit_symbol_lut)\n    if isinstance(unit_expr, Pow):\n        unit_data = _get_unit_data_from_expr(unit_expr.args[0], unit_symbol_lut)\n        power = unit_expr.args[1]\n        if isinstance(power, Symbol):\n            raise UnitParseError(\"Invalid unit expression '%s'.\" % unit_expr)\n        conv = float(unit_data[0] ** power)\n        unit = unit_data[1] ** power\n        return (conv, unit)\n    if isinstance(unit_expr, Mul):\n        base_value = 1.0\n        dimensions = 1\n        for expr in unit_expr.args:\n            unit_data = _get_unit_data_from_expr(expr, unit_symbol_lut)\n            base_value *= unit_data[0]\n            dimensions *= unit_data[1]\n        return (float(base_value), dimensions)\n    raise UnitParseError(\n        \"Cannot parse for unit data from '%s'. Please supply\"\n        \" an expression of only Unit, Symbol, Pow, and Mul\"\n        \"objects.\" % str(unit_expr)\n    )",
    "docstring": "Grabs the total base_value and dimensions from a valid unit expression.\n\n    Parameters\n    ----------\n    unit_expr: Unit object, or sympy Expr object\n        The expression containing unit symbols.\n    unit_symbol_lut: dict\n        Provides the unit data for each valid unit symbol."
  },
  {
    "code": "def decorate_method(wrapped):\n    def wrapper(self):\n        lines = Lines()\n        if hasattr(self.model, wrapped.__name__):\n            print('            . %s' % wrapped.__name__)\n            lines.add(1, method_header(wrapped.__name__, nogil=True))\n            for line in wrapped(self):\n                lines.add(2, line)\n        return lines\n    functools.update_wrapper(wrapper, wrapped)\n    wrapper.__doc__ = 'Lines of model method %s.' % wrapped.__name__\n    return property(wrapper)",
    "docstring": "The decorated method will return a |Lines| object including\n    a method header.  However, the |Lines| object will be empty if\n    the respective model does not implement a method with the same\n    name as the wrapped method."
  },
  {
    "code": "def delete(self, *args, **kwargs):\n        hosted_zone = route53_backend.get_hosted_zone_by_name(\n            self.hosted_zone_name)\n        if not hosted_zone:\n            hosted_zone = route53_backend.get_hosted_zone(self.hosted_zone_id)\n        hosted_zone.delete_rrset_by_name(self.name)",
    "docstring": "Not exposed as part of the Route 53 API - used for CloudFormation. args are ignored"
  },
  {
    "code": "def create(self, name, address=None, enabled=True, balancing_mode='active',\n               ipsec_vpn=True, nat_t=False, force_nat_t=False, dynamic=False,\n               ike_phase1_id_type=None, ike_phase1_id_value=None):\n        json = {'name': name,\n                'address': address,\n                'balancing_mode': balancing_mode,\n                'dynamic': dynamic,\n                'enabled': enabled,\n                'nat_t': nat_t,\n                'force_nat_t': force_nat_t,\n                'ipsec_vpn': ipsec_vpn}\n        if dynamic:\n            json.pop('address')\n            json.update(\n                ike_phase1_id_type=ike_phase1_id_type,\n                ike_phase1_id_value=ike_phase1_id_value)\n        return ElementCreator(\n            self.__class__,\n            href=self.href,\n            json=json)",
    "docstring": "Create an test_external endpoint. Define common settings for that\n        specify the address, enabled, nat_t, name, etc. You can also omit\n        the IP address if the endpoint is dynamic. In that case, you must\n        also specify the ike_phase1 settings.\n\n        :param str name: name of test_external endpoint\n        :param str address: address of remote host\n        :param bool enabled: True|False (default: True)\n        :param str balancing_mode: active\n        :param bool ipsec_vpn: True|False (default: True)\n        :param bool nat_t: True|False (default: False)\n        :param bool force_nat_t: True|False (default: False)\n        :param bool dynamic: is a dynamic VPN (default: False)\n        :param int ike_phase1_id_type: If using a dynamic endpoint, you must\n            set this value. Valid options: 0=DNS name, 1=Email, 2=DN, 3=IP Address\n        :param str ike_phase1_id_value: value of ike_phase1_id. Required if\n            ike_phase1_id_type and dynamic set.\n        :raises CreateElementFailed: create element with reason\n        :return: newly created element\n        :rtype: ExternalEndpoint"
  },
  {
    "code": "def _read(self, fd, mask):\n        try:\n            if select.select([fd],[],[],0)[0]:\n                snew = os.read(fd, self.nbytes)\n                if PY3K: snew = snew.decode('ascii','replace')\n                self.value.append(snew)\n                self.nbytes -= len(snew)\n            else:\n                snew = ''\n            if (self.nbytes <= 0 or len(snew) == 0) and self.widget:\n                self.widget.quit()\n        except OSError:\n            raise IOError(\"Error reading from %s\" % (fd,))",
    "docstring": "Read waiting data and terminate Tk mainloop if done"
  },
  {
    "code": "def get_context_data(self):\n        buffer_name = self['buffer_name'].get_value()\n        structure = CreateContextName.get_response_structure(buffer_name)\n        if structure:\n            structure.unpack(self['buffer_data'].get_value())\n            return structure\n        else:\n            return self['buffer_data'].get_value()",
    "docstring": "Get the buffer_data value of a context response and try to convert it\n        to the relevant structure based on the buffer_name used. If it is an\n        unknown structure then the raw bytes are returned.\n\n        :return: relevant Structure of buffer_data or bytes if unknown name"
  },
  {
    "code": "def find_function_by_name(self, name):\n        cfg_rv = None\n        for cfg in self._cfgs:\n            if cfg.name == name:\n                cfg_rv = cfg\n                break\n        return cfg_rv",
    "docstring": "Return the cfg of the requested function by name."
  },
  {
    "code": "def new_method_call(celf, destination, path, iface, method) :\n        \"creates a new DBUS.MESSAGE_TYPE_METHOD_CALL message.\"\n        result = dbus.dbus_message_new_method_call \\\n          (\n            (lambda : None, lambda : destination.encode())[destination != None](),\n            path.encode(),\n            (lambda : None, lambda : iface.encode())[iface != None](),\n            method.encode(),\n          )\n        if result == None :\n            raise CallFailed(\"dbus_message_new_method_call\")\n        return \\\n            celf(result)",
    "docstring": "creates a new DBUS.MESSAGE_TYPE_METHOD_CALL message."
  },
  {
    "code": "def setup_logging(verbose=0, colors=False, name=None):\n    root_logger = logging.getLogger(name)\n    root_logger.setLevel(logging.DEBUG if verbose > 0 else logging.INFO)\n    formatter = ColorFormatter(verbose > 0, colors)\n    if colors:\n        colorclass.Windows.enable()\n    handler_stdout = logging.StreamHandler(sys.stdout)\n    handler_stdout.setFormatter(formatter)\n    handler_stdout.setLevel(logging.DEBUG)\n    handler_stdout.addFilter(type('', (logging.Filter,), {'filter': staticmethod(lambda r: r.levelno <= logging.INFO)}))\n    root_logger.addHandler(handler_stdout)\n    handler_stderr = logging.StreamHandler(sys.stderr)\n    handler_stderr.setFormatter(formatter)\n    handler_stderr.setLevel(logging.WARNING)\n    root_logger.addHandler(handler_stderr)",
    "docstring": "Configure console logging. Info and below go to stdout, others go to stderr.\n\n    :param int verbose: Verbosity level. > 0 print debug statements. > 1 passed to sphinx-build.\n    :param bool colors: Print color text in non-verbose mode.\n    :param str name: Which logger name to set handlers to. Used for testing."
  },
  {
    "code": "def check_constraint(self, pkge=None, constr=None):\n        if not pkge is None:\n            return javabridge.call(\n                self.jobject, \"checkConstraint\", \"(Lweka/core/packageManagement/Package;)Z\", pkge.jobject)\n        if not constr is None:\n            return javabridge.call(\n                self.jobject, \"checkConstraint\", \"(Lweka/core/packageManagement/PackageConstraint;)Z\", pkge.jobject)\n        raise Exception(\"Either package or package constraing must be provided!\")",
    "docstring": "Checks the constraints.\n\n        :param pkge: the package to check\n        :type pkge: Package\n        :param constr: the package constraint to check\n        :type constr: PackageConstraint"
  },
  {
    "code": "def initialTrendSmoothingFactors(self, timeSeries):\n        result = 0.0\n        seasonLength = self.get_parameter(\"seasonLength\")\n        k = min(len(timeSeries) - seasonLength, seasonLength)\n        for i in xrange(0, k):\n            result += (timeSeries[seasonLength + i][1] - timeSeries[i][1]) / seasonLength\n        return result / k",
    "docstring": "Calculate the initial Trend smoothing Factor b0.\n\n        Explanation:\n            http://en.wikipedia.org/wiki/Exponential_smoothing#Triple_exponential_smoothing\n\n        :return:   Returns the initial trend smoothing factor b0"
  },
  {
    "code": "def ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):\n    class OrderedLoader(Loader):\n        pass\n    def construct_mapping(loader, node):\n        loader.flatten_mapping(node)\n        return object_pairs_hook(loader.construct_pairs(node))\n    OrderedLoader.add_constructor(\n        yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,\n        construct_mapping)\n    return yaml.load(stream, OrderedLoader)",
    "docstring": "Loads an ordered dict into a yaml while preserving the order\n\n    :param stream: the name of the stream\n    :param Loader: the yam loader (such as yaml.SafeLoader)\n    :param object_pairs_hook: the ordered dict"
  },
  {
    "code": "def new(self):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('CE record already initialized!')\n        self.bl_cont_area = 0\n        self.offset_cont_area = 0\n        self.len_cont_area = 0\n        self._initialized = True",
    "docstring": "Create a new Rock Ridge Continuation Entry record.\n\n        Parameters:\n         None.\n        Returns:\n         Nothing."
  },
  {
    "code": "def extract_finditer(pos_seq, regex=SimpleNP):\n\tss = coarse_tag_str(pos_seq)\n\tdef gen():\n\t\tfor m in re.finditer(regex, ss):\n\t\t\tyield (m.start(), m.end())\n\treturn list(gen())",
    "docstring": "The \"GreedyFSA\" method in Handler et al. 2016.\n\tReturns token position spans of valid ngrams."
  },
  {
    "code": "def _ircounts2radiance(counts, scale, offset):\n        rad = (counts - offset) / scale\n        return rad.clip(min=0)",
    "docstring": "Convert IR counts to radiance\n\n        Reference: [IR].\n\n        Args:\n            counts: Raw detector counts\n            scale: Scale [mW-1 m2 cm sr]\n            offset: Offset [1]\n\n        Returns:\n            Radiance [mW m-2 cm-1 sr-1]"
  },
  {
    "code": "def conditional_expected_number_of_purchases_up_to_time(self, t, frequency, recency, T):\n        x = frequency\n        r, alpha, a, b = self._unload_params(\"r\", \"alpha\", \"a\", \"b\")\n        hyp_term = hyp2f1(r + x, b + x + 1, a + b + x, t / (alpha + T + t))\n        first_term = (a + b + x) / (a - 1)\n        second_term = 1 - hyp_term * ((alpha + T) / (alpha + t + T)) ** (r + x)\n        numerator = first_term * second_term\n        denominator = 1 + (a / (b + x)) * ((alpha + T) / (alpha + recency)) ** (r + x)\n        return numerator / denominator",
    "docstring": "Conditional expected number of repeat purchases up to time t.\n\n        Calculate the expected number of repeat purchases up to time t for a\n        randomly choose individual from the population, given they have\n        purchase history (frequency, recency, T)\n        See Wagner, U. and Hoppe D. (2008).\n\n        Parameters\n        ----------\n        t: array_like\n            times to calculate the expectation for.\n        frequency: array_like\n            historical frequency of customer.\n        recency: array_like\n            historical recency of customer.\n        T: array_like\n            age of the customer.\n\n        Returns\n        -------\n        array_like"
  },
  {
    "code": "def post(self, request, *args, **kwargs):\n        queryset = self.get_selected(request)\n        if request.POST.get('modify'):\n            response = self.process_action(request, queryset)\n            if not response:\n                url = self.get_done_url()\n                return self.render(request, redirect_url=url)\n            else:\n                return response\n        else:\n            return self.render(request, redirect_url=request.build_absolute_uri())",
    "docstring": "Method for handling POST requests.\n        Checks for a modify confirmation and performs\n        the action by calling `process_action`."
  },
  {
    "code": "def set_status(self, status_code: int, reason: str = None) -> None:\n        self._status_code = status_code\n        if reason is not None:\n            self._reason = escape.native_str(reason)\n        else:\n            self._reason = httputil.responses.get(status_code, \"Unknown\")",
    "docstring": "Sets the status code for our response.\n\n        :arg int status_code: Response status code.\n        :arg str reason: Human-readable reason phrase describing the status\n            code. If ``None``, it will be filled in from\n            `http.client.responses` or \"Unknown\".\n\n        .. versionchanged:: 5.0\n\n           No longer validates that the response code is in\n           `http.client.responses`."
  },
  {
    "code": "def _notify_remove_at(self, index, length=1):\n        slice_ = self._slice_at(index, length)\n        self._notify_remove(slice_)",
    "docstring": "Notify about an RemoveChange at a caertain index and length."
  },
  {
    "code": "def tube(self, radius=None, scalars=None, capping=True, n_sides=20,\n             radius_factor=10, preference='point', inplace=False):\n        if n_sides < 3:\n            n_sides = 3\n        tube = vtk.vtkTubeFilter()\n        tube.SetInputDataObject(self)\n        tube.SetCapping(capping)\n        if radius is not None:\n            tube.SetRadius(radius)\n        tube.SetNumberOfSides(n_sides)\n        tube.SetRadiusFactor(radius_factor)\n        if scalars is not None:\n            if not isinstance(scalars, str):\n                raise TypeError('Scalar array must be given as a string name')\n            _, field = self.get_scalar(scalars, preference=preference, info=True)\n            tube.SetInputArrayToProcess(0, 0, 0, field, scalars)\n            tube.SetVaryRadiusToVaryRadiusByScalar()\n        tube.Update()\n        mesh = _get_output(tube)\n        if inplace:\n            self.overwrite(mesh)\n        else:\n            return mesh",
    "docstring": "Generate a tube around each input line. The radius of the tube can be\n        set to linearly vary with a scalar value.\n\n        Parameters\n        ----------\n        radius : float\n            Minimum tube radius (minimum because the tube radius may vary).\n\n        scalars : str, optional\n            Scalar array by which the radius varies\n\n        capping : bool\n            Turn on/off whether to cap the ends with polygons. Default True.\n\n        n_sides : int\n            Set the number of sides for the tube. Minimum of 3.\n\n        radius_factor : float\n            Maximum tube radius in terms of a multiple of the minimum radius.\n\n        preference : str\n            The field preference when searching for the scalar array by name\n\n        inplace : bool, optional\n            Updates mesh in-place while returning nothing.\n\n        Returns\n        -------\n        mesh : vtki.PolyData\n            Tube-filtered mesh. None when inplace=True."
  },
  {
    "code": "def finalize_episode(self, params):\n        total_reward = sum(self.intermediate_rewards)\n        self.total_rewards.append(total_reward)\n        self.params.append(params)\n        self.intermediate_rewards = []",
    "docstring": "Closes the current episode, sums up rewards and stores the parameters\n\n        # Argument\n            params (object): Parameters associated with the episode to be stored and then retrieved back in sample()"
  },
  {
    "code": "def check_rotation(rotation):\n    if rotation not in ALLOWED_ROTATION:\n        allowed_rotation = ', '.join(ALLOWED_ROTATION)\n        raise UnsupportedRotation('Rotation %s is not allwoed. Allowed are %s'\n                                  % (rotation, allowed_rotation))",
    "docstring": "checks rotation parameter if illegal value raises exception"
  },
  {
    "code": "def set_state(self, newState, timer=0):\n        if _debug: ServerSSM._debug(\"set_state %r (%s) timer=%r\", newState, SSM.transactionLabels[newState], timer)\n        SSM.set_state(self, newState, timer)\n        if (newState == COMPLETED) or (newState == ABORTED):\n            if _debug: ServerSSM._debug(\"    - remove from active transactions\")\n            self.ssmSAP.serverTransactions.remove(self)\n            if self.device_info:\n                if _debug: ClientSSM._debug(\"    - release device information\")\n                self.ssmSAP.deviceInfoCache.release(self.device_info)",
    "docstring": "This function is called when the client wants to change state."
  },
  {
    "code": "def mpirun(self):\n        cmd = self.attributes['mpirun']\n        if cmd and cmd[0] != 'mpirun':\n            cmd = ['mpirun']\n        return [str(e) for e in cmd]",
    "docstring": "Additional options passed as a list to the ``mpirun`` command"
  },
  {
    "code": "def connect(\n            self, login, password, authz_id=b\"\", starttls=False,\n            authmech=None):\n        try:\n            self.sock = socket.create_connection((self.srvaddr, self.srvport))\n            self.sock.settimeout(Client.read_timeout)\n        except socket.error as msg:\n            raise Error(\"Connection to server failed: %s\" % str(msg))\n        if not self.__get_capabilities():\n            raise Error(\"Failed to read capabilities from server\")\n        if starttls and not self.__starttls():\n            return False\n        if self.__authenticate(login, password, authz_id, authmech):\n            return True\n        return False",
    "docstring": "Establish a connection with the server.\n\n        This function must be used. It read the server capabilities\n        and wraps calls to STARTTLS and AUTHENTICATE commands.\n\n        :param login: username\n        :param password: clear password\n        :param starttls: use a TLS connection or not\n        :param authmech: prefered authenticate mechanism\n        :rtype: boolean"
  },
  {
    "code": "def _compute_intra_event_std(self, C, vs30, pga1100, sigma_pga):\n        sig_lnyb = np.sqrt(C['s_lny'] ** 2. - C['s_lnAF'] ** 2.)\n        sig_lnab = np.sqrt(sigma_pga ** 2. - C['s_lnAF'] ** 2.)\n        alpha = self._compute_intra_event_alpha(C, vs30, pga1100)\n        return np.sqrt(\n            (sig_lnyb ** 2.) +\n            (C['s_lnAF'] ** 2.) +\n            ((alpha ** 2.) * (sig_lnab ** 2.)) +\n            (2.0 * alpha * C['rho'] * sig_lnyb * sig_lnab))",
    "docstring": "Returns the intra-event standard deviation at the site, as defined in\n        equation 15, page 147"
  },
  {
    "code": "def pad_to_power2(data, axis = None, mode=\"constant\"):\n    if axis is None:\n        axis = list(range(data.ndim))\n    if np.all([_is_power2(n) for i, n in enumerate(data.shape) if i in axis]):\n        return data\n    else:\n        return pad_to_shape(data,[(_next_power_of_2(n) if i in axis else n) for i,n in enumerate(data.shape)], mode)",
    "docstring": "pad data to a shape of power 2\n    if axis == None all axis are padded"
  },
  {
    "code": "def campaign(self, name, owner=None, **kwargs):\n        return Campaign(self.tcex, name, owner=owner, **kwargs)",
    "docstring": "Create the Campaign TI object.\n\n        Args:\n            owner:\n            name:\n            **kwargs:\n\n        Return:"
  },
  {
    "code": "def heater_level(self, value):\n        if self._ext_sw_heater_drive:\n            if value not in range(0, self._heater_bangbang_segments+1):\n                raise exceptions.RoasterValueError\n            self._heater_level.value = value\n        else:\n            raise exceptions.RoasterValueError",
    "docstring": "Verifies that the heater_level is between 0 and heater_segments.\n           Can only be called when freshroastsr700 object is initialized\n           with ext_sw_heater_drive=True. Will throw RoasterValueError\n           otherwise."
  },
  {
    "code": "def generate_entities_doc(ctx, out_path, package):\n    from canari.commands.generate_entities_doc import generate_entities_doc\n    generate_entities_doc(ctx.project, out_path, package)",
    "docstring": "Create entities documentation from Canari python classes file."
  },
  {
    "code": "def input_dir(dirname):\n    dirname = dirname.rstrip('/')\n    if excluded(dirname):\n        return 0\n    errors = 0\n    for root, dirs, files in os.walk(dirname):\n        if options.verbose:\n            message('directory ' + root)\n        options.counters['directories'] = \\\n            options.counters.get('directories', 0) + 1\n        dirs.sort()\n        for subdir in dirs:\n            if excluded(subdir):\n                dirs.remove(subdir)\n        files.sort()\n        for filename in files:\n            errors += input_file(os.path.join(root, filename))\n    return errors",
    "docstring": "Check all Python source files in this directory and all subdirectories."
  },
  {
    "code": "def execute_route(self, meta_data, request_pdu):\n        try:\n            function = create_function_from_request_pdu(request_pdu)\n            results =\\\n                function.execute(meta_data['unit_id'], self.route_map)\n            try:\n                return function.create_response_pdu(results)\n            except TypeError:\n                return function.create_response_pdu()\n        except ModbusError as e:\n            function_code = get_function_code_from_request_pdu(request_pdu)\n            return pack_exception_pdu(function_code, e.error_code)\n        except Exception as e:\n            log.exception('Could not handle request: {0}.'.format(e))\n            function_code = get_function_code_from_request_pdu(request_pdu)\n            return pack_exception_pdu(function_code,\n                                      ServerDeviceFailureError.error_code)",
    "docstring": "Execute configured route based on requests meta data and request\n        PDU.\n\n        :param meta_data: A dict with meta data. It must at least contain\n            key 'unit_id'.\n        :param request_pdu: A bytearray containing request PDU.\n        :return: A bytearry containing reponse PDU."
  },
  {
    "code": "def jbcorrelation(sites_or_distances, imt, vs30_clustering=False):\n        if hasattr(sites_or_distances, 'mesh'):\n            distances = sites_or_distances.mesh.get_distance_matrix()\n        else:\n            distances = sites_or_distances\n        if imt.period < 1:\n            if not vs30_clustering:\n                b = 8.5 + 17.2 * imt.period\n            else:\n                b = 40.7 - 15.0 * imt.period\n        else:\n            b = 22.0 + 3.7 * imt.period\n        return numpy.exp((- 3.0 / b) * distances)",
    "docstring": "Returns the Jayaram-Baker correlation model.\n\n        :param sites_or_distances:\n            SiteCollection instance o ristance matrix\n        :param imt:\n            Intensity Measure Type (PGA or SA)\n        :param vs30_clustering:\n            flag, defalt false"
  },
  {
    "code": "def remove_exclude_regions(orig_bed, base_file, items, remove_entire_feature=False):\n    from bcbio.structural import shared as sshared\n    out_bed = os.path.join(\"%s-noexclude.bed\" % (utils.splitext_plus(base_file)[0]))\n    if not utils.file_uptodate(out_bed, orig_bed):\n        exclude_bed = sshared.prepare_exclude_file(items, base_file)\n        with file_transaction(items[0], out_bed) as tx_out_bed:\n            pybedtools.BedTool(orig_bed).subtract(pybedtools.BedTool(exclude_bed),\n                                                  A=remove_entire_feature, nonamecheck=True).saveas(tx_out_bed)\n    if utils.file_exists(out_bed):\n        return out_bed\n    else:\n        return orig_bed",
    "docstring": "Remove centromere and short end regions from an existing BED file of regions to target."
  },
  {
    "code": "def shift(self, timezone):\n        try:\n            self._tzinfo = pytz.timezone(timezone)\n        except pytz.UnknownTimeZoneError:\n            raise DeloreanInvalidTimezone('Provide a valid timezone')\n        self._dt = self._tzinfo.normalize(self._dt.astimezone(self._tzinfo))\n        self._tzinfo = self._dt.tzinfo\n        return self",
    "docstring": "Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object,\n        modifying the Delorean object and returning the modified object.\n\n        .. testsetup::\n\n            from datetime import datetime\n            from delorean import Delorean\n\n        .. doctest::\n\n            >>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific')\n            >>> d.shift('UTC')\n            Delorean(datetime=datetime.datetime(2015, 1, 1, 8, 0), timezone='UTC')"
  },
  {
    "code": "def _get_result_paths(self,data):\n        result = {}\n        result['Tree'] = ResultPath(Path=splitext(self._input_filename)[0] + \\\n                                                  '.tree')\n        return result",
    "docstring": "Get the resulting tree"
  },
  {
    "code": "def add_issues_to_sprint(self, sprint_id, issue_keys):\n        if self._options['agile_rest_path'] == GreenHopperResource.AGILE_BASE_REST_PATH:\n            url = self._get_url('sprint/%s/issue' % sprint_id, base=self.AGILE_BASE_URL)\n            payload = {'issues': issue_keys}\n            try:\n                self._session.post(url, data=json.dumps(payload))\n            except JIRAError as e:\n                if e.status_code == 404:\n                    warnings.warn('Status code 404 may mean, that too old JIRA Agile version is installed.'\n                                  ' At least version 6.7.10 is required.')\n                raise\n        elif self._options['agile_rest_path'] == GreenHopperResource.GREENHOPPER_REST_PATH:\n            sprint_field_id = self._get_sprint_field_id()\n            data = {'idOrKeys': issue_keys, 'customFieldId': sprint_field_id,\n                    'sprintId': sprint_id, 'addToBacklog': False}\n            url = self._get_url('sprint/rank', base=self.AGILE_BASE_URL)\n            return self._session.put(url, data=json.dumps(data))\n        else:\n            raise NotImplementedError('No API for adding issues to sprint for agile_rest_path=\"%s\"' %\n                                      self._options['agile_rest_path'])",
    "docstring": "Add the issues in ``issue_keys`` to the ``sprint_id``.\n\n        The sprint must be started but not completed.\n\n        If a sprint was completed, then have to also edit the history of the\n        issue so that it was added to the sprint before it was completed,\n        preferably before it started. A completed sprint's issues also all have\n        a resolution set before the completion date.\n\n        If a sprint was not started, then have to edit the marker and copy the\n        rank of each issue too.\n\n        :param sprint_id: the sprint to add issues to\n        :type sprint_id: int\n        :param issue_keys: the issues to add to the sprint\n        :type issue_keys: List[str]\n\n        :rtype: Response"
  },
  {
    "code": "def bootstrap_histogram_1D(\n        values, intervals, uncertainties=None,\n        normalisation=False, number_bootstraps=None, boundaries=None):\n    if not number_bootstraps or np.all(np.fabs(uncertainties < PRECISION)):\n        output = hmtk_histogram_1D(values, intervals)\n        if normalisation:\n            output = output / float(np.sum(output))\n        else:\n            output = output\n        return output\n    else:\n        temp_hist = np.zeros([len(intervals) - 1, number_bootstraps],\n                             dtype=float)\n        for iloc in range(0, number_bootstraps):\n            sample = sample_truncated_gaussian_vector(values,\n                                                      uncertainties,\n                                                      boundaries)\n            output = hmtk_histogram_1D(sample, intervals)\n            temp_hist[:, iloc] = output\n        output = np.sum(temp_hist, axis=1)\n        if normalisation:\n            output = output / float(np.sum(output))\n        else:\n            output = output / float(number_bootstraps)\n        return output",
    "docstring": "Bootstrap samples a set of vectors\n\n    :param numpy.ndarray values:\n        The data values\n    :param numpy.ndarray intervals:\n        The bin edges\n    :param numpy.ndarray uncertainties:\n        The standard deviations of each observation\n    :param bool normalisation:\n        If True then returns the histogram as a density function\n    :param int number_bootstraps:\n        Number of bootstraps\n    :param tuple boundaries:\n        (Lower, Upper) bounds on the data\n\n    :param returns:\n        1-D histogram of data"
  },
  {
    "code": "def _is_in_keep_going(self, x, y):\n        x1, y1, x2, y2 = self._keep_going\n        return self.won == 1 and x1 <= x < x2 and y1 <= y < y2",
    "docstring": "Checks if the mouse is in the keep going button, and if the won overlay is shown."
  },
  {
    "code": "def im_watermark(im, inputtext, font=None, color=None, opacity=.6, margin=(30, 30)):\n    if im.mode != \"RGBA\":\n        im = im.convert(\"RGBA\")\n    textlayer = Image.new(\"RGBA\", im.size, (0, 0, 0, 0))\n    textdraw = ImageDraw.Draw(textlayer)\n    textsize = textdraw.textsize(inputtext, font=font)\n    textpos = [im.size[i] - textsize[i] - margin[i] for i in [0, 1]]\n    textdraw.text(textpos, inputtext, font=font, fill=color)\n    if opacity != 1:\n        textlayer = reduce_opacity(textlayer, opacity)\n    return Image.composite(textlayer, im, textlayer)",
    "docstring": "imprints a PIL image with the indicated text in lower-right corner"
  },
  {
    "code": "def hook(klass):\n    if not hasattr(klass, 'do_vim'):\n        setupMethod(klass, trace_dispatch)\n        klass.__bases__ += (SwitcherToVimpdb, )",
    "docstring": "monkey-patch pdb.Pdb class\n\n    adds a 'vim' (and 'v') command:\n    it switches to debugging with vimpdb"
  },
  {
    "code": "def rpc(self, name, handler, value, request=None):\n        chan = self._channel(name)\n        if value is None:\n            value = Value(Type([]))\n        return _p4p.ClientOperation(chan, handler=unwrapHandler(handler, self._nt),\n                                    value=value, pvRequest=wrapRequest(request), rpc=True)",
    "docstring": "Perform RPC operation on PV\n\n        :param name: A single name string or list of name strings\n        :param callable handler: Completion notification.  Called with a Value, RemoteError, or Cancelled\n        :param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default.\n\n        :returns: A object with a method cancel() which may be used to abort the operation."
  },
  {
    "code": "def nodes():\n    for name, provider in env.providers.items():\n        print name\n        provider.nodes()\n        print",
    "docstring": "List running nodes on all enabled cloud providers. Automatically flushes caches"
  },
  {
    "code": "def _create_lock_object(self, key):\n        return redis_lock.Lock(self.redis_conn, key,\n                               expire=self.settings['REDIS_LOCK_EXPIRATION'],\n                               auto_renewal=True)",
    "docstring": "Returns a lock object, split for testing"
  },
  {
    "code": "def init_logger(log_requests=False):\n    logger = logging.getLogger(__name__.split(\".\")[0])\n    for handler in logger.handlers:\n        logger.removeHandler(handler)\n    formatter = coloredlogs.ColoredFormatter(fmt=\"%(asctime)s: %(message)s\")\n    handler = logging.StreamHandler()\n    handler.setLevel(logging.DEBUG)\n    handler.setFormatter(formatter)\n    logger.addHandler(handler)\n    logger.setLevel(logging.DEBUG)\n    logger.propagate = False\n    if log_requests:\n        requests.packages.urllib3.add_stderr_logger()",
    "docstring": "Initialize the logger"
  },
  {
    "code": "def index(request, template_name=\"index.html\"):\n    if request.GET.get('ic-request'):\n        counter, created = Counter.objects.get_or_create(pk=1)\n        counter.value += 1\n        counter.save()\n    else:\n        counter, created = Counter.objects.get_or_create(pk=1)\n        print(counter.value)\n    context = dict(\n        value=counter.value,\n    )\n    return render(request, template_name, context=context)",
    "docstring": "\\\n    The index view, which basically just displays a button and increments\n    a counter."
  },
  {
    "code": "def set_address(network, address):\n    if network.find('.//ip') is not None:\n        raise RuntimeError(\"Address already specified in XML configuration.\")\n    netmask = str(address.netmask)\n    ipv4 = str(address[1])\n    dhcp_start = str(address[2])\n    dhcp_end = str(address[-2])\n    ip = etree.SubElement(network, 'ip', address=ipv4, netmask=netmask)\n    dhcp = etree.SubElement(ip, 'dhcp')\n    etree.SubElement(dhcp, 'range', start=dhcp_start, end=dhcp_end)",
    "docstring": "Sets the given address to the network XML element.\n\n    Libvirt bridge will have address and DHCP server configured\n    according to the subnet prefix length."
  },
  {
    "code": "def WriteFileHeader(self, arcname=None, compress_type=None, st=None):\n    if not self._stream:\n      raise ArchiveAlreadyClosedError(\n          \"Attempting to write to a ZIP archive that was already closed.\")\n    self.cur_zinfo = self._GenerateZipInfo(\n        arcname=arcname, compress_type=compress_type, st=st)\n    self.cur_file_size = 0\n    self.cur_compress_size = 0\n    if self.cur_zinfo.compress_type == zipfile.ZIP_DEFLATED:\n      self.cur_cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,\n                                       zlib.DEFLATED, -15)\n    else:\n      self.cur_cmpr = None\n    self.cur_crc = 0\n    if not self._stream:\n      raise ArchiveAlreadyClosedError(\n          \"Attempting to write to a ZIP archive that was already closed.\")\n    self.cur_zinfo.header_offset = self._stream.tell()\n    self._zip_fd._writecheck(self.cur_zinfo)\n    self._zip_fd._didModify = True\n    self._stream.write(self.cur_zinfo.FileHeader())\n    return self._stream.GetValueAndReset()",
    "docstring": "Writes a file header."
  },
  {
    "code": "def _copyValues(self, to, extra=None):\n        paramMap = self._paramMap.copy()\n        if extra is not None:\n            paramMap.update(extra)\n        for param in self.params:\n            if param in self._defaultParamMap and to.hasParam(param.name):\n                to._defaultParamMap[to.getParam(param.name)] = self._defaultParamMap[param]\n            if param in paramMap and to.hasParam(param.name):\n                to._set(**{param.name: paramMap[param]})\n        return to",
    "docstring": "Copies param values from this instance to another instance for\n        params shared by them.\n\n        :param to: the target instance\n        :param extra: extra params to be copied\n        :return: the target instance with param values copied"
  },
  {
    "code": "def nub(it):\n    seen = set()\n    for v in it:\n        h = hash(v)\n        if h in seen:\n            continue\n        seen.add(h)\n        yield v",
    "docstring": "Dedups an iterable in arbitrary order.\n\n    Uses memory proportional to the number of unique items in ``it``."
  },
  {
    "code": "def number_of_bytes_to_modify(buf_len, fuzz_factor):\n    return random.randrange(math.ceil((float(buf_len) / fuzz_factor))) + 1",
    "docstring": "Calculate number of bytes to modify.\n\n    :param buf_len: len of data buffer to fuzz.\n    :param fuzz_factor: degree of fuzzing.\n    :return: number of bytes to change."
  },
  {
    "code": "def handleError(self, test, err, capt=None):\n        if not hasattr(test.test, \"testcase_guid\"):\n            if err[0] == errors.BlockedTest:\n                raise SkipTest(err[1])\n                return True\n            elif err[0] == errors.DeprecatedTest:\n                raise SkipTest(err[1])\n                return True\n            elif err[0] == errors.SkipTest:\n                raise SkipTest(err[1])\n                return True",
    "docstring": "If the database plugin is not present, we have to handle capturing\n        \"errors\" that shouldn't be reported as such in base."
  },
  {
    "code": "def get_delta(D, k):\n    if k < 0:\n        raise Exception('k must be at least 0th order.')\n    result = D\n    for i in range(k):\n        result = D.T.dot(result) if i % 2 == 0 else D.dot(result)\n    return result",
    "docstring": "Calculate the k-th order trend filtering matrix given the oriented edge\n    incidence matrix and the value of k."
  },
  {
    "code": "def normalize(self):\n        self.__v = self.__v - np.amin(self.__v)\n        self.__v = self.__v / np.amax(self.__v)",
    "docstring": "Sets the potential range 0 to 1."
  },
  {
    "code": "def assign_nested_vars(variables, tensors, indices=None):\n  if isinstance(variables, (tuple, list)):\n    return tf.group(*[\n        assign_nested_vars(variable, tensor)\n        for variable, tensor in zip(variables, tensors)])\n  if indices is None:\n    return variables.assign(tensors)\n  else:\n    return tf.scatter_update(variables, indices, tensors)",
    "docstring": "Assign tensors to matching nested tuple of variables.\n\n  Args:\n    variables: Nested tuple or list of variables to update.\n    tensors: Nested tuple or list of tensors to assign.\n    indices: Batch indices to assign to; default to all.\n\n  Returns:\n    Operation."
  },
  {
    "code": "def check_output(self, cmd):\n        ret, output = self._call(cmd, True)\n        if ret != 0:\n            raise RemoteCommandFailure(command=cmd, ret=ret)\n        logger.debug(\"Output: %r\", output)\n        return output",
    "docstring": "Calls a command through SSH and returns its output."
  },
  {
    "code": "def com_google_fonts_check_fontv(ttFont):\n  from fontv.libfv import FontVersion\n  fv = FontVersion(ttFont)\n  if fv.version and (fv.is_development or fv.is_release):\n    yield PASS, \"Font version string looks GREAT!\"\n  else:\n    yield INFO, (\"Version string is: \\\"{}\\\"\\n\"\n                 \"The version string must ideally include a git commit hash\"\n                 \" and either a 'dev' or a 'release' suffix such as in the\"\n                 \" example below:\\n\"\n                 \"\\\"Version 1.3; git-0d08353-release\\\"\"\n                 \"\").format(fv.get_name_id5_version_string())",
    "docstring": "Check for font-v versioning"
  },
  {
    "code": "def _match_space_at_line(line):\n    regex = re.compile(r\"^{0}$\".format(_MDL_COMMENT))\n    return regex.match(line)",
    "docstring": "Return a re.match object if an empty comment was found on line."
  },
  {
    "code": "def projection_name(self, **kwargs: Dict[str, Any]) -> str:\n        return self.projection_name_format.format(**kwargs)",
    "docstring": "Define the projection name for this projector.\n\n        Note:\n            This function is just a basic placeholder and likely should be overridden.\n\n        Args:\n            kwargs: Projection information dict combined with additional arguments passed to the\n                projection function.\n        Returns:\n            Projection name string formatted with the passed options. By default, it returns\n                ``projection_name_format`` formatted with the arguments to this function."
  },
  {
    "code": "def reserved_quota(self, reserved_quota):\n        if reserved_quota is None:\n            raise ValueError(\"Invalid value for `reserved_quota`, must not be `None`\")\n        if reserved_quota is not None and reserved_quota < 0:\n            raise ValueError(\"Invalid value for `reserved_quota`, must be a value greater than or equal to `0`\")\n        self._reserved_quota = reserved_quota",
    "docstring": "Sets the reserved_quota of this ServicePackageMetadata.\n        Sum of all open reservations for this account.\n\n        :param reserved_quota: The reserved_quota of this ServicePackageMetadata.\n        :type: int"
  },
  {
    "code": "def _parse_tables(cls, parsed_content):\n        tables = parsed_content.find_all('table', attrs={\"width\": \"100%\"})\n        output = OrderedDict()\n        for table in tables:\n            title = table.find(\"td\").text\n            output[title] = table.find_all(\"tr\")[1:]\n        return output",
    "docstring": "Parses the information tables contained in a character's page.\n\n        Parameters\n        ----------\n        parsed_content: :class:`bs4.BeautifulSoup`\n            A :class:`BeautifulSoup` object containing all the content.\n\n        Returns\n        -------\n        :class:`OrderedDict`[str, :class:`list`of :class:`bs4.Tag`]\n            A dictionary containing all the table rows, with the table headers as keys."
  },
  {
    "code": "def partial_derivative_mu(mu, sigma, low, high, data):\n        pd_mu = np.sum(data - mu) / sigma ** 2\n        pd_mu -= len(data) * ((norm.pdf(low, mu, sigma) - norm.pdf(high, mu, sigma))\n                              / (norm.cdf(high, mu, sigma) - norm.cdf(low, mu, sigma)))\n        return -pd_mu",
    "docstring": "The partial derivative with respect to the mean.\n\n        Args:\n            mu (float): the mean of the truncated normal\n            sigma (float): the std of the truncated normal\n            low (float): the lower truncation bound\n            high (float): the upper truncation bound\n            data (ndarray): the one dimension list of data points for which we want to calculate the likelihood\n\n        Returns:\n            float: the partial derivative evaluated at the given point"
  },
  {
    "code": "def kldiv_model(prediction, fm):\n    (_, r_x) = calc_resize_factor(prediction, fm.image_size)\n    q = np.array(prediction, copy=True)\n    q -= np.min(q.flatten())\n    q /= np.sum(q.flatten())\n    return kldiv(None, q, distp = fm, scale_factor = r_x)",
    "docstring": "wraps kldiv functionality for model evaluation\n\n    input:\n        prediction: 2D matrix\n            the model salience map\n        fm : fixmat\n            Should be filtered for the image corresponding to the prediction"
  },
  {
    "code": "def download_images(query, path, size=1024):\n    im_size = \"thumb-{0}.jpg\".format(size)\n    im_list = []\n    for im in query:\n        key = im['properties']['key']\n        url = MAPILLARY_API_IM_RETRIEVE_URL + key + '/' + im_size\n        filename = key + \".jpg\"\n        try:\n            image = urllib.URLopener()\n            image.retrieve(url, path + filename)\n            coords = \",\".join(map(str, im['geometry']['coordinates']))\n            im_list.append([filename, coords])\n            print(\"Successfully downloaded: {0}\".format(filename))\n        except KeyboardInterrupt:\n            break\n        except Exception as e:\n            print(\"Failed to download: {} due to {}\".format(filename, e))\n    return im_list",
    "docstring": "Download images in query result to path.\n\n    Return list of downloaded images with lat,lon.\n    There are four sizes available: 320, 640, 1024 (default), or 2048."
  },
  {
    "code": "def get_shard_id2num_examples(num_shards, total_num_examples):\n  num_example_in_shard = total_num_examples // num_shards\n  shard_id2num_examples = [num_example_in_shard for _ in range(num_shards)]\n  for shard_id in range(total_num_examples % num_shards):\n    shard_id2num_examples[shard_id] += 1\n  return shard_id2num_examples",
    "docstring": "Return the mapping shard_id=>num_examples, assuming round-robin."
  },
  {
    "code": "def _get_biodata(base_file, args):\n    with open(base_file) as in_handle:\n        config = yaml.safe_load(in_handle)\n    config[\"install_liftover\"] = False\n    config[\"genome_indexes\"] = args.aligners\n    ann_groups = config.pop(\"annotation_groups\", {})\n    config[\"genomes\"] = [_setup_genome_annotations(g, args, ann_groups)\n                         for g in config[\"genomes\"] if g[\"dbkey\"] in args.genomes]\n    return config",
    "docstring": "Retrieve biodata genome targets customized by install parameters."
  },
  {
    "code": "def dumps(obj):\n    return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder)",
    "docstring": "Outputs json with formatting edits + object handling."
  },
  {
    "code": "def once(self):\n        ns = self.Namespace()\n        ns.memo = None\n        ns.run = False\n        def work_once(*args, **kwargs):\n            if ns.run is False:\n                ns.memo = self.obj(*args, **kwargs)\n            ns.run = True\n            return ns.memo\n        return self._wrap(work_once)",
    "docstring": "Returns a function that will be executed at most one time,\n        no matter how often you call it. Useful for lazy initialization."
  },
  {
    "code": "def complete_experiment(self, status):\n        self.log(\"Bot player completing experiment. Status: {}\".format(status))\n        while True:\n            url = \"{host}/{status}?participant_id={participant_id}\".format(\n                host=self.host, participant_id=self.participant_id, status=status\n            )\n            try:\n                result = requests.get(url)\n                result.raise_for_status()\n            except RequestException:\n                self.stochastic_sleep()\n                continue\n            return result",
    "docstring": "Record worker completion status to the experiment server.\n\n        This is done using a GET request to the /worker_complete\n        or /worker_failed endpoints."
  },
  {
    "code": "def _SGraphFromJsonTree(json_str):\n    g = json.loads(json_str)\n    vertices = [_Vertex(x['id'],\n                dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'id']))\n                                                      for x in g['vertices']]\n    edges = [_Edge(x['src'], x['dst'],\n             dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'src' and k != 'dst']))\n                                                      for x in g['edges']]\n    sg = _SGraph().add_vertices(vertices)\n    if len(edges) > 0:\n        sg = sg.add_edges(edges)\n    return sg",
    "docstring": "Convert the Json Tree to SGraph"
  },
  {
    "code": "def list_profile(hostname, username, password, profile_type, name=None, ):\n    bigip_session = _build_session(username, password)\n    try:\n        if name:\n            response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}/{name}?expandSubcollections=true'.format(type=profile_type, name=name))\n        else:\n            response = bigip_session.get(BIG_IP_URL_BASE.format(host=hostname)+'/ltm/profile/{type}'.format(type=profile_type))\n    except requests.exceptions.ConnectionError as e:\n        return _load_connection_error(hostname, e)\n    return _load_response(response)",
    "docstring": "A function to connect to a bigip device and list an existing profile.  If no name is provided than all\n    profiles of the specified type will be listed.\n\n    hostname\n        The host/address of the bigip device\n    username\n        The iControl REST username\n    password\n        The iControl REST password\n    profile_type\n        The type of profile(s) to list\n    name\n        The name of the profile to list\n\n    CLI Example::\n\n        salt '*' bigip.list_profile bigip admin admin http my-http-profile"
  },
  {
    "code": "def reward_goal(self):\n        if not 'goal' in self.mode:\n            return\n        mode = self.mode['goal']\n        if mode and mode['reward'] and self.__test_cond(mode):\n            if mode['reward'] > 0:\n                self.logger.info(\"Escaped!!\")\n            self.player.stats['reward'] += mode['reward']\n            self.player.stats['score'] += mode['reward']\n            self.player.game_over = self.player.game_over or mode['terminal']",
    "docstring": "Add an end goal reward"
  },
  {
    "code": "def resample(self, data, cache_dir=None, mask_area=None, **kwargs):\n        if mask_area is None and isinstance(\n                self.source_geo_def, SwathDefinition):\n            mask_area = True\n        if mask_area:\n            if isinstance(self.source_geo_def, SwathDefinition):\n                geo_dims = self.source_geo_def.lons.dims\n            else:\n                geo_dims = ('y', 'x')\n            flat_dims = [dim for dim in data.dims if dim not in geo_dims]\n            if np.issubdtype(data.dtype, np.integer):\n                kwargs['mask'] = data == data.attrs.get('_FillValue', np.iinfo(data.dtype.type).max)\n            else:\n                kwargs['mask'] = data.isnull()\n            kwargs['mask'] = kwargs['mask'].all(dim=flat_dims)\n        cache_id = self.precompute(cache_dir=cache_dir, **kwargs)\n        return self.compute(data, cache_id=cache_id, **kwargs)",
    "docstring": "Resample `data` by calling `precompute` and `compute` methods.\n\n        Only certain resampling classes may use `cache_dir` and the `mask`\n        provided when `mask_area` is True. The return value of calling the\n        `precompute` method is passed as the `cache_id` keyword argument\n        of the `compute` method, but may not be used directly for caching. It\n        is up to the individual resampler subclasses to determine how this\n        is used.\n\n        Args:\n            data (xarray.DataArray): Data to be resampled\n            cache_dir (str): directory to cache precomputed results\n                             (default False, optional)\n            mask_area (bool): Mask geolocation data where data values are\n                              invalid. This should be used when data values\n                              may affect what neighbors are considered valid.\n\n        Returns (xarray.DataArray): Data resampled to the target area"
  },
  {
    "code": "def add_str(self, seq, name=None, description=\"\"):\n        self.add_seq(SeqRecord(Seq(seq), id=name, description=description))",
    "docstring": "Use this method to add a sequence as a string to this fasta."
  },
  {
    "code": "def register(self, model_or_iterable, moderation_class):\n        if isinstance(model_or_iterable, ModelBase):\n            model_or_iterable = [model_or_iterable]\n        for model in model_or_iterable:\n            if model in self._registry:\n                raise AlreadyModerated(\n                    \"The model '%s' is already being moderated\" % model._meta.verbose_name\n                )\n            self._registry[model] = moderation_class(model)",
    "docstring": "Register a model or a list of models for comment moderation,\n        using a particular moderation class.\n\n        Raise ``AlreadyModerated`` if any of the models are already\n        registered."
  },
  {
    "code": "def apply_markup(value, arg=None):\n    if arg is not None:\n        return formatter(value, filter_name=arg)\n    return formatter(value)",
    "docstring": "Applies text-to-HTML conversion.\n    \n    Takes an optional argument to specify the name of a filter to use."
  },
  {
    "code": "def decrypt(self, key):\n        if 'ciphertext' not in self.objects:\n            raise InvalidJWEOperation(\"No available ciphertext\")\n        self.decryptlog = list()\n        if 'recipients' in self.objects:\n            for rec in self.objects['recipients']:\n                try:\n                    self._decrypt(key, rec)\n                except Exception as e:\n                    self.decryptlog.append('Failed: [%s]' % repr(e))\n        else:\n            try:\n                self._decrypt(key, self.objects)\n            except Exception as e:\n                self.decryptlog.append('Failed: [%s]' % repr(e))\n        if not self.plaintext:\n            raise InvalidJWEData('No recipient matched the provided '\n                                 'key' + repr(self.decryptlog))",
    "docstring": "Decrypt a JWE token.\n\n        :param key: The (:class:`jwcrypto.jwk.JWK`) decryption key.\n        :param key: A (:class:`jwcrypto.jwk.JWK`) decryption key or a password\n         string (optional).\n\n        :raises InvalidJWEOperation: if the key is not a JWK object.\n        :raises InvalidJWEData: if the ciphertext can't be decrypted or\n         the object is otherwise malformed."
  },
  {
    "code": "def call(self, method, *args):\n        payload = self.build_payload(method, args)\n        logging.debug('* Client will send payload: {}'.format(payload))\n        self.send(payload)\n        res = self.receive()\n        assert payload[2] == res['ref']\n        return res['result'], res['error']",
    "docstring": "Make a call to a `Responder` and return the result"
  },
  {
    "code": "def parse_section_entry_points(self, section_options):\n        parsed = self._parse_section_to_dict(section_options, self._parse_list)\n        self['entry_points'] = parsed",
    "docstring": "Parses `entry_points` configuration file section.\n\n        :param dict section_options:"
  },
  {
    "code": "def get_private_name(self, f):\n        f = self.__swagger_rename__[f] if f in self.__swagger_rename__.keys() else f\n        return '_' + self.__class__.__name__ + '__' + f",
    "docstring": "get private protected name of an attribute\n\n        :param str f: name of the private attribute to be accessed."
  },
  {
    "code": "def readn(self, n):\n        data = ''\n        while len(data) < n:\n            received = self.sock.recv(n - len(data))\n            if not len(received):\n                raise socket.error('no data read from socket')\n            data += received\n        return data",
    "docstring": "Keep receiving data until exactly `n` bytes have been read."
  },
  {
    "code": "def from_storage(source, source_format='csv', csv_options=None, ignore_unknown_values=False,\n                   max_bad_records=0, compressed=False, schema=None):\n    result = FederatedTable()\n    if source_format == 'csv':\n      result._bq_source_format = 'CSV'\n      if csv_options is None:\n        csv_options = _csv_options.CSVOptions()\n    elif source_format == 'json':\n      if csv_options:\n        raise Exception('CSV options are not support for JSON tables')\n      result._bq_source_format = 'NEWLINE_DELIMITED_JSON'\n    else:\n      raise Exception(\"Invalid source format %s\" % source_format)\n    result._source = source if isinstance(source, list) else [source]\n    result._source_format = source_format\n    result._csv_options = csv_options\n    result._ignore_unknown_values = ignore_unknown_values\n    result._max_bad_records = max_bad_records\n    result._compressed = compressed\n    result._schema = schema\n    return result",
    "docstring": "Create an external table for a GCS object.\n\n    Args:\n      source: the URL of the source objects(s). Can include a wildcard '*' at the end of the item\n         name. Can be a single source or a list.\n      source_format: the format of the data, 'csv' or 'json'; default 'csv'.\n      csv_options: For CSV files, the options such as quote character and delimiter.\n      ignore_unknown_values: If True, accept rows that contain values that do not match the schema;\n          the unknown values are ignored (default False).\n      max_bad_records: The maximum number of bad records that are allowed (and ignored) before\n          returning an 'invalid' error in the Job result (default 0).\n      compressed: whether the data is GZ compressed or not (default False). Note that compressed\n          data can be used as a federated table but cannot be loaded into a BQ Table.\n      schema: the schema of the data. This is required for this table to be used as a federated\n          table or to be loaded using a Table object that itself has no schema (default None)."
  },
  {
    "code": "def _get_free_display_port(self):\n        display = 100\n        if not os.path.exists(\"/tmp/.X11-unix/\"):\n            return display\n        while True:\n            if not os.path.exists(\"/tmp/.X11-unix/X{}\".format(display)):\n                return display\n            display += 1",
    "docstring": "Search a free display port"
  },
  {
    "code": "def reexport_tf_summary():\n  import sys\n  packages = [\n      'tensorflow',\n      'tensorflow.compat.v2',\n      'tensorflow._api.v2',\n      'tensorflow._api.v2.compat.v2',\n      'tensorflow._api.v1.compat.v2',\n  ]\n  if not getattr(tf, '__version__', '').startswith('2.'):\n    packages.remove('tensorflow')\n  def dynamic_wildcard_import(module):\n    symbols = getattr(module, '__all__', None)\n    if symbols is None:\n      symbols = [k for k in module.__dict__.keys() if not k.startswith('_')]\n    globals().update({symbol: getattr(module, symbol) for symbol in symbols})\n  notfound = object()\n  for package_name in packages:\n    package = sys.modules.get(package_name, notfound)\n    if package is notfound:\n      continue\n    module = getattr(package, 'summary', None)\n    if module is None:\n      continue\n    dynamic_wildcard_import(module)\n    return",
    "docstring": "Re-export all symbols from the original tf.summary.\n\n  This function finds the original tf.summary V2 API and re-exports all the\n  symbols from it within this module as well, so that when this module is\n  patched into the TF API namespace as the new tf.summary, the effect is an\n  overlay that just adds TensorBoard-provided symbols to the module.\n\n  Finding the original tf.summary V2 API module reliably is a challenge, since\n  this code runs *during* the overall TF API import process and depending on\n  the order of imports (which is subject to change), different parts of the API\n  may or may not be defined at the point in time we attempt to access them. This\n  code also may be inserted into two places in the API (tf and tf.compat.v2)\n  and may be re-executed multiple times even for the same place in the API (due\n  to the TF module import system not populating sys.modules properly), so it\n  needs to be robust to many different scenarios.\n\n  The one constraint we can count on is that everywhere this module is loaded\n  (via the component_api_helper mechanism in TF), it's going to be the 'summary'\n  submodule of a larger API package that already has a 'summary' attribute\n  that contains the TF-only summary API symbols we need to re-export. This\n  may either be the original TF-only summary module (the first time we load\n  this module) or a pre-existing copy of this module (if we're re-loading this\n  module again). We don't actually need to differentiate those two cases,\n  because it's okay if we re-import our own TensorBoard-provided symbols; they\n  will just be overwritten later on in this file.\n\n  So given that guarantee, the approach we take is to first attempt to locate\n  a TF V2 API package that already has a 'summary' attribute (most likely this\n  is the parent package into which we're being imported, but not necessarily),\n  and then do the dynamic version of \"from tf_api_package.summary import *\".\n\n  Lastly, this logic is encapsulated in a function to avoid symbol leakage."
  },
  {
    "code": "def return_fv_by_seeds(fv, seeds=None, unique_cls=None):\n    if seeds is not None:\n        if unique_cls is not None:\n            return select_from_fv_by_seeds(fv, seeds, unique_cls)\n        else:\n            raise AssertionError(\"Input unique_cls has to be not None if seeds is not None.\")\n    else:\n        return fv",
    "docstring": "Return features selected by seeds and unique_cls or selection from features and corresponding seed classes.\n\n    :param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number\n    of features\n    :param seeds: ndarray with seeds. Does not to be linear.\n    :param unique_cls: number of used seeds clases. Like [1, 2]\n    :return: fv, sd - selection from feature vector and selection from seeds or just fv for whole image"
  },
  {
    "code": "def map_concepts_to_indicators(\n        self, n: int = 1, min_temporal_res: Optional[str] = None\n    ):\n        for node in self.nodes(data=True):\n            query_parts = [\n                \"select Indicator from concept_to_indicator_mapping\",\n                f\"where `Concept` like '{node[0]}'\",\n            ]\n            query = \"  \".join(query_parts)\n            results = engine.execute(query)\n            if min_temporal_res is not None:\n                if min_temporal_res not in [\"month\"]:\n                    raise ValueError(\"min_temporal_res must be 'month'\")\n                vars_with_required_temporal_resolution = [\n                    r[0]\n                    for r in engine.execute(\n                        \"select distinct `Variable` from indicator where \"\n                        f\"`{min_temporal_res.capitalize()}` is not null\"\n                    )\n                ]\n                results = [\n                    r\n                    for r in results\n                    if r[0] in vars_with_required_temporal_resolution\n                ]\n            node[1][\"indicators\"] = {\n                x: Indicator(x, \"MITRE12\")\n                for x in [r[0] for r in take(n, results)]\n            }",
    "docstring": "Map each concept node in the AnalysisGraph instance to one or more\n        tangible quantities, known as 'indicators'.\n\n        Args:\n            n: Number of matches to keep\n            min_temporal_res: Minimum temporal resolution that the indicators\n            must have data for."
  },
  {
    "code": "def _stringify_number(v):\n    if isinstance(v, (float, Decimal)):\n        if math.isinf(v) and v > 0:\n            v = 'Infinity'\n        elif math.isinf(v) and v < 0:\n            v = '-Infinity'\n        else:\n            v = '{:f}'.format(v)\n    elif isinstance(v, BinarySize):\n        v = '{:d}'.format(int(v))\n    elif isinstance(v, int):\n        v = '{:d}'.format(v)\n    else:\n        v = str(v)\n    return v",
    "docstring": "Stringify a number, preventing unwanted scientific notations."
  },
  {
    "code": "def sql_program_name_func(command):\n    args = command.split(' ')\n    for prog in args:\n        if '=' not in prog:\n            return prog\n    return args[0]",
    "docstring": "Extract program name from `command`.\n\n    >>> sql_program_name_func('ls')\n    'ls'\n    >>> sql_program_name_func('git status')\n    'git'\n    >>> sql_program_name_func('EMACS=emacs make')\n    'make'\n\n    :type command: str"
  },
  {
    "code": "def create_project(self, name, client_id, budget = None, budget_by =\n    \t'none', notes = None, billable = True):\n        project = {'project':{\n            'name': name,\n            'client_id': client_id,\n            'budget_by': budget_by,\n            'budget': budget,\n            'notes': notes,\n            'billable': billable,\n        }}\n        response = self.post_request('projects/', project, follow = True)\n        if response:\n            return Project(self, response['project'])",
    "docstring": "Creates a Project with the given information."
  },
  {
    "code": "def get_config(self):\n        if not self._config:\n            namespace = {}\n            if os.path.exists(self.config_path):\n                execfile(self.config_path, namespace)\n            self._config = namespace.get('config') or Configuration()\n        return self._config",
    "docstring": "Load user configuration or return default when not found.\n\n        :rtype: :class:`Configuration`"
  },
  {
    "code": "def _determine_case(was_upper, words, string):\n    case_type = 'unknown'\n    if was_upper:\n        case_type = 'upper'\n    elif string.islower():\n        case_type = 'lower'\n    elif len(words) > 0:\n        camel_case = words[0].islower()\n        pascal_case = words[0].istitle() or words[0].isupper()\n        if camel_case or pascal_case:\n            for word in words[1:]:\n                c = word.istitle() or word.isupper()\n                camel_case &= c\n                pascal_case &= c\n                if not c:\n                    break\n        if camel_case:\n            case_type = 'camel'\n        elif pascal_case:\n            case_type = 'pascal'\n        else:\n            case_type = 'mixed'\n    return case_type",
    "docstring": "Determine case type of string.\n\n    Arguments:\n        was_upper {[type]} -- [description]\n        words {[type]} -- [description]\n        string {[type]} -- [description]\n\n    Returns:\n        - upper: All words are upper-case.\n        - lower: All words are lower-case.\n        - pascal: All words are title-case or upper-case. Note that the\n                  stringiable may still have separators.\n        - camel: First word is lower-case, the rest are title-case or\n                 upper-case. stringiable may still have separators.\n        - mixed: Any other mixing of word casing. Never occurs if there are\n                 no separators.\n        - unknown: stringiable contains no words."
  },
  {
    "code": "def plot_vxz(self, colorbar=True, cb_orientation='vertical',\n                 cb_label=None, ax=None, show=True, fname=None, **kwargs):\n        if cb_label is None:\n            cb_label = self._vxz_label\n        if ax is None:\n            fig, axes = self.vxz.plot(colorbar=colorbar,\n                                      cb_orientation=cb_orientation,\n                                      cb_label=cb_label, show=False, **kwargs)\n            if show:\n                fig.show()\n            if fname is not None:\n                fig.savefig(fname)\n            return fig, axes\n        else:\n            self.vxz.plot(colorbar=colorbar, cb_orientation=cb_orientation,\n                          cb_label=cb_label, ax=ax, **kwargs)",
    "docstring": "Plot the Vxz component of the tensor.\n\n        Usage\n        -----\n        x.plot_vxz([tick_interval, xlabel, ylabel, ax, colorbar,\n                    cb_orientation, cb_label, show, fname])\n\n        Parameters\n        ----------\n        tick_interval : list or tuple, optional, default = [30, 30]\n            Intervals to use when plotting the x and y ticks. If set to None,\n            ticks will not be plotted.\n        xlabel : str, optional, default = 'longitude'\n            Label for the longitude axis.\n        ylabel : str, optional, default = 'latitude'\n            Label for the latitude axis.\n        ax : matplotlib axes object, optional, default = None\n            A single matplotlib axes object where the plot will appear.\n        colorbar : bool, optional, default = True\n            If True, plot a colorbar.\n        cb_orientation : str, optional, default = 'vertical'\n            Orientation of the colorbar: either 'vertical' or 'horizontal'.\n        cb_label : str, optional, default = '$V_{xz}$'\n            Text label for the colorbar.\n        show : bool, optional, default = True\n            If True, plot the image to the screen.\n        fname : str, optional, default = None\n            If present, and if axes is not specified, save the image to the\n            specified file.\n        kwargs : optional\n            Keyword arguements that will be sent to the SHGrid.plot()\n            and plt.imshow() methods."
  },
  {
    "code": "def skipDryRun(logger, dryRun, level=logging.DEBUG):\n    if not isinstance(level, int):\n        level = logging.getLevelName(level)\n    return (\n        functools.partial(_logDryRun, logger, level) if dryRun\n        else functools.partial(logger.log, level)\n    )",
    "docstring": "Return logging function.\n\n    When logging function called, will return True if action should be skipped.\n    Log will indicate if skipped because of dry run."
  },
  {
    "code": "def get_harddisk_sleep():\n    ret = salt.utils.mac_utils.execute_return_result(\n        'systemsetup -getharddisksleep')\n    return salt.utils.mac_utils.parse_return(ret)",
    "docstring": "Display the amount of idle time until the hard disk sleeps.\n\n    :return: A string representing the sleep settings for the hard disk\n    :rtype: str\n\n    CLI Example:\n\n    ..code-block:: bash\n\n        salt '*' power.get_harddisk_sleep"
  },
  {
    "code": "def _stream_search(self, *args, **kwargs):\n        for hit in scan(\n            self.elastic, query=kwargs.pop(\"body\", None), scroll=\"10m\", **kwargs\n        ):\n            hit[\"_source\"][\"_id\"] = hit[\"_id\"]\n            yield hit[\"_source\"]",
    "docstring": "Helper method for iterating over ES search results."
  },
  {
    "code": "def change_numbering(self, rename_dict, inplace=False):\n        output = self if inplace else self.copy()\n        new_index = [rename_dict.get(key, key) for key in self.index]\n        output.index = new_index\n        if not inplace:\n            return output",
    "docstring": "Return the reindexed version of Cartesian.\n\n        Args:\n            rename_dict (dict): A dictionary mapping integers on integers.\n\n        Returns:\n            Cartesian: A renamed copy according to the dictionary passed."
  },
  {
    "code": "def put_tagging(Bucket,\n           region=None, key=None, keyid=None, profile=None, **kwargs):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        tagslist = []\n        for k, v in six.iteritems(kwargs):\n            if six.text_type(k).startswith('__'):\n                continue\n            tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})\n        conn.put_bucket_tagging(Bucket=Bucket, Tagging={\n                'TagSet': tagslist,\n        })\n        return {'updated': True, 'name': Bucket}\n    except ClientError as e:\n        return {'updated': False, 'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Given a valid config, update the tags for a bucket.\n\n    Returns {updated: true} if tags were updated and returns\n    {updated: False} if tags were not updated.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]"
  },
  {
    "code": "def setup_logging(level, console_stream=None, log_dir=None, scope=None, log_name=None, native=None):\n  log_filename = None\n  file_handler = None\n  def trace(self, message, *args, **kwargs):\n    if self.isEnabledFor(TRACE):\n      self._log(TRACE, message, args, **kwargs)\n  logging.Logger.trace = trace\n  logger = logging.getLogger(scope)\n  for handler in logger.handlers:\n    logger.removeHandler(handler)\n  if console_stream:\n    native_handler = create_native_stderr_log_handler(level, native, stream=console_stream)\n    logger.addHandler(native_handler)\n  if log_dir:\n    safe_mkdir(log_dir)\n    log_filename = os.path.join(log_dir, log_name or 'pants.log')\n    native_handler = create_native_pantsd_file_log_handler(level, native, log_filename)\n    file_handler = native_handler\n    logger.addHandler(native_handler)\n  logger.setLevel(level)\n  logging.captureWarnings(True)\n  _maybe_configure_extended_logging(logger)\n  return LoggingSetupResult(log_filename, file_handler)",
    "docstring": "Configures logging for a given scope, by default the global scope.\n\n  :param str level: The logging level to enable, must be one of the level names listed here:\n                    https://docs.python.org/2/library/logging.html#levels\n  :param file console_stream: The stream to use for default (console) logging. If None (default),\n                              this will disable console logging.\n  :param str log_dir: An optional directory to emit logs files in.  If unspecified, no disk logging\n                      will occur.  If supplied, the directory will be created if it does not already\n                      exist and all logs will be tee'd to a rolling set of log files in that\n                      directory.\n  :param str scope: A logging scope to configure.  The scopes are hierarchichal logger names, with\n                    The '.' separator providing the scope hierarchy.  By default the root logger is\n                    configured.\n  :param str log_name: The base name of the log file (defaults to 'pants.log').\n  :param Native native: An instance of the Native FFI lib, to register rust logging.\n  :returns: The full path to the main log file if file logging is configured or else `None`.\n  :rtype: str"
  },
  {
    "code": "def reset(self):\n        self.filename = None\n        self.groups = []\n        self.tabs.clear()\n        self.setEnabled(False)\n        self.button_color.setEnabled(False)\n        self.button_del.setEnabled(False)\n        self.button_apply.setEnabled(False)\n        self.action['load_channels'].setEnabled(False)\n        self.action['save_channels'].setEnabled(False)",
    "docstring": "Reset all the information of this widget."
  },
  {
    "code": "def amg_video_search(self, entitiy_type, query, **kwargs):\n        return self.make_request('amgvideo', entitiy_type, query, kwargs)",
    "docstring": "Search the Movies and TV database\n\n        Where ``entitiy_type`` is a comma separated list of:\n\n        ``movie``\n            Movies\n\n        ``tvseries``\n            TV series\n\n        ``credit``\n            people working in TV or movies"
  },
  {
    "code": "def to_pb(self):\n        return policy_pb2.Policy(\n            etag=self.etag,\n            version=self.version or 0,\n            bindings=[\n                policy_pb2.Binding(role=role, members=sorted(self[role]))\n                for role in self\n            ],\n        )",
    "docstring": "Render a protobuf message.\n\n        Returns:\n            google.iam.policy_pb2.Policy: a message to be passed to the\n            ``set_iam_policy`` gRPC API."
  },
  {
    "code": "def read_config_info(ini_file):\n    try:\n        config = RawConfigParser()\n        config.optionxform = lambda option: option\n        config.read(ini_file)\n        the_stuff = {}\n        for section in config.sections():\n            the_stuff[section] = {}\n            for option in config.options(section):\n                the_stuff[section][option] = config.get(section, option)\n        return the_stuff\n    except Exception as wtf:\n        logging.error('Exception caught in read_config_info(): {}'.format(wtf))\n        traceback.print_exc(file=sys.stdout)\n        return sys.exit(1)",
    "docstring": "Read the INI file\n\n    Args:\n        ini_file - path to the file\n\n    Returns:\n        A dictionary of stuff from the INI file\n\n    Exits:\n        1 - if problems are encountered"
  },
  {
    "code": "def _read(self):\n        self.json_file.seek(0)\n        try:\n            data = zlib.decompress(self.json_file.read())\n            self.backup_dict = json.loads(data.decode('utf-8'))\n        except (EOFError, zlib.error):\n            self.backup_dict = {}",
    "docstring": "Reads backup file from json_file property and sets backup_dict property\n        with data decompressed and deserialized from that file. If no usable\n        data is found backup_dict is set to the empty dict."
  },
  {
    "code": "def pull_cfg_from_parameters_out(parameters_out, namelist_to_read=\"nml_allcfgs\"):\n    single_cfg = Namelist({namelist_to_read: {}})\n    for key, value in parameters_out[namelist_to_read].items():\n        if \"file_tuning\" in key:\n            single_cfg[namelist_to_read][key] = \"\"\n        else:\n            try:\n                if isinstance(value, str):\n                    single_cfg[namelist_to_read][key] = value.strip(\" \\t\\n\\r\").replace(\n                        \"\\x00\", \"\"\n                    )\n                elif isinstance(value, list):\n                    clean_list = [v.strip(\" \\t\\n\\r\").replace(\"\\x00\", \"\") for v in value]\n                    single_cfg[namelist_to_read][key] = [v for v in clean_list if v]\n                else:\n                    assert isinstance(value, Number)\n                    single_cfg[namelist_to_read][key] = value\n            except AttributeError:\n                if isinstance(value, list):\n                    assert all([isinstance(v, Number) for v in value])\n                    single_cfg[namelist_to_read][key] = value\n                else:\n                    raise AssertionError(\n                        \"Unexpected cause in out parameters conversion\"\n                    )\n    return single_cfg",
    "docstring": "Pull out a single config set from a parameters_out namelist.\n\n    This function returns a single file with the config that needs to be passed to\n    MAGICC in order to do the same run as is represented by the values in\n    ``parameters_out``.\n\n    Parameters\n    ----------\n    parameters_out : dict, f90nml.Namelist\n        The parameters to dump\n\n    namelist_to_read : str\n        The namelist to read from the file.\n\n    Returns\n    -------\n    :obj:`f90nml.Namelist`\n        An f90nml object with the cleaned, read out config.\n\n    Examples\n    --------\n    >>> cfg = pull_cfg_from_parameters_out(magicc.metadata[\"parameters\"])\n    >>> cfg.write(\"/somewhere/else/ANOTHERNAME.cfg\")"
  },
  {
    "code": "def extract_args(cls, *args):\n        model = None\n        crudbuilder = None\n        for arg in args:\n            if issubclass(arg, models.Model):\n                model = arg\n            else:\n                crudbuilder = arg\n        return [model, crudbuilder]",
    "docstring": "Takes any arguments like a model and crud, or just one of\n        those, in any order, and return a model and crud."
  },
  {
    "code": "async def load_varint(reader):\n    buffer = _UINT_BUFFER\n    await reader.areadinto(buffer)\n    width = int_mark_to_size(buffer[0] & PortableRawSizeMark.MASK)\n    result = buffer[0]\n    shift = 8\n    for _ in range(width-1):\n        await reader.areadinto(buffer)\n        result += buffer[0] << shift\n        shift += 8\n    return result >> 2",
    "docstring": "Binary load of variable size integer serialized by dump_varint\n\n    :param reader:\n    :return:"
  },
  {
    "code": "def process_modules(modules):\n    for mod in modules['client']:\n        directory = '%s/client_modules' % HERE\n        if not exists(directory):\n            makedirs(directory)\n        write_module_file(mod, directory, 'pyeapi')\n    for mod in modules['api']:\n        directory = '%s/api_modules' % HERE\n        if not exists(directory):\n            makedirs(directory)\n        write_module_file(mod, directory, 'pyeapi.api')\n    create_index(modules)",
    "docstring": "Accepts dictionary of 'client' and 'api' modules and creates\n    the corresponding files."
  },
  {
    "code": "def filter_not_empty_values(value):\n    if not value:\n        return None\n    data = [x for x in value if x]\n    if not data:\n        return None\n    return data",
    "docstring": "Returns a list of non empty values or None"
  },
  {
    "code": "def get(self, *args, **kwargs) -> \"QuerySet\":\n        queryset = self.filter(*args, **kwargs)\n        queryset._limit = 2\n        queryset._get = True\n        return queryset",
    "docstring": "Fetch exactly one object matching the parameters."
  },
  {
    "code": "def plot_welch_perdiogram(x, fs, nperseg):\n    import scipy.signal\n    import numpy\n    N = len(x)\n    time = numpy.arange(N) / fs\n    f, Pxx_den = scipy.signal.welch(x, fs, nperseg=nperseg)\n    plt.semilogy(f, Pxx_den)\n    plt.ylim([0.5e-3, 1])\n    plt.xlabel('frequency [Hz]')\n    plt.ylabel('PSD [V**2/Hz]')\n    plt.show()\n    numpy.mean(Pxx_den[256:])\n    f, Pxx_spec = scipy.signal.welch(x, fs, 'flattop', 1024,\n                                     scaling='spectrum')\n    plt.figure()\n    plt.semilogy(f, numpy.sqrt(Pxx_spec))\n    plt.xlabel('frequency [Hz]')\n    plt.ylabel('Linear spectrum [V RMS]')\n    plt.show()\n    return None",
    "docstring": "Plot Welch perdiogram\n\n    Args\n    ----\n    x: ndarray\n        Signal array\n    fs: float\n        Sampling frequency\n    nperseg: float\n        Length of each data segment in PSD"
  },
  {
    "code": "def add_simple_link(self, issue, object):\n        data = {\"object\": object}\n        url = self._get_url('issue/' + str(issue) + '/remotelink')\n        r = self._session.post(\n            url, data=json.dumps(data))\n        simple_link = RemoteLink(\n            self._options, self._session, raw=json_loads(r))\n        return simple_link",
    "docstring": "Add a simple remote link from an issue to web resource.\n\n        This avoids the admin access problems from add_remote_link by just\n            using a simple object and presuming all fields are correct and not\n            requiring more complex ``application`` data.\n\n        ``object`` should be a dict containing at least ``url`` to the\n            linked external URL and ``title`` to display for the link inside JIRA.\n\n        For definitions of the allowable fields for ``object`` , see https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+for+Remote+Issue+Links.\n\n        :param issue: the issue to add the remote link to\n        :param object: the dictionary used to create remotelink data"
  },
  {
    "code": "def hashable(cls):\n    assert \"__hash__\" in cls.__dict__\n    assert cls.__dict__[\"__hash__\"] is not None\n    assert \"__eq__\" in cls.__dict__\n    cls.__ne__ = lambda self, other: not self.__eq__(other)\n    return cls",
    "docstring": "Makes sure the class is hashable.\n\n    Needs a working __eq__ and __hash__ and will add a __ne__."
  },
  {
    "code": "def command_str(self):\n        if isinstance(self.command, six.string_types):\n            return self.command\n        return ' '.join(map(six.moves.shlex_quote, self.command))",
    "docstring": "get command to execute as string properly escaped\n\n        :return: string"
  },
  {
    "code": "def run(self):\n        try:\n            Control().cursor_hide().write(file=self.file)\n            super().run()\n        except KeyboardInterrupt:\n            self.stop()\n        finally:\n            Control().cursor_show().write(file=self.file)",
    "docstring": "Overrides WriterProcess.run, to handle KeyboardInterrupts better.\n            This should not be called by any user. `multiprocessing` calls\n            this in a subprocess.\n            Use `self.start` to start this instance."
  },
  {
    "code": "def get_cancel_url(self):\n        if self.cancel_url:\n            return self.cancel_url\n        ModelClass = self.get_model_class()\n        return reverse('trionyx:model-list', kwargs={\n            'app': ModelClass._meta.app_label,\n            'model': ModelClass._meta.model_name,\n        })",
    "docstring": "Get cancel url"
  },
  {
    "code": "def create_for_rectangle(self, x, y, width, height):\n        return Surface._from_pointer(\n            cairo.cairo_surface_create_for_rectangle(\n                self._pointer, x, y, width, height),\n            incref=False)",
    "docstring": "Create a new surface that is a rectangle within this surface.\n        All operations drawn to this surface are then clipped and translated\n        onto the target surface.\n        Nothing drawn via this sub-surface outside of its bounds\n        is drawn onto the target surface,\n        making this a useful method for passing constrained child surfaces\n        to library routines that draw directly onto the parent surface,\n        i.e. with no further backend allocations,\n        double buffering or copies.\n\n        .. note::\n\n            As of cairo 1.12,\n            the semantics of subsurfaces have not been finalized yet\n            unless the rectangle is in full device units,\n            is contained within the extents of the target surface,\n            and the target or subsurface's device transforms are not changed.\n\n        :param x:\n            The x-origin of the sub-surface\n            from the top-left of the target surface (in device-space units)\n        :param y:\n            The y-origin of the sub-surface\n            from the top-left of the target surface (in device-space units)\n        :param width:\n            Width of the sub-surface (in device-space units)\n        :param height:\n            Height of the sub-surface (in device-space units)\n        :type x: float\n        :type y: float\n        :type width: float\n        :type height: float\n        :returns:\n            A new :class:`Surface` object.\n\n        *New in cairo 1.10.*"
  },
  {
    "code": "def _reschedule(self, node):\n        if node.shutting_down:\n            return\n        if not self.workqueue:\n            node.shutdown()\n            return\n        self.log(\"Number of units waiting for node:\", len(self.workqueue))\n        if self._pending_of(self.assigned_work[node]) > 2:\n            return\n        self._assign_work_unit(node)",
    "docstring": "Maybe schedule new items on the node.\n\n        If there are any globally pending work units left then this will check\n        if the given node should be given any more tests."
  },
  {
    "code": "def try_mongodb_opts(self, host=\"localhost\", database_name='INGInious'):\n        try:\n            mongo_client = MongoClient(host=host)\n        except Exception as e:\n            self._display_warning(\"Cannot connect to MongoDB on host %s: %s\" % (host, str(e)))\n            return None\n        try:\n            database = mongo_client[database_name]\n        except Exception as e:\n            self._display_warning(\"Cannot access database %s: %s\" % (database_name, str(e)))\n            return None\n        try:\n            GridFS(database)\n        except Exception as e:\n            self._display_warning(\"Cannot access gridfs %s: %s\" % (database_name, str(e)))\n            return None\n        return database",
    "docstring": "Try MongoDB configuration"
  },
  {
    "code": "def numpyview(arr, datatype, shape, raw=False):\n    if raw:\n        return n.frombuffer(arr, dtype=n.dtype(datatype)).view(n.dtype(datatype)).reshape(shape)\n    else:\n        return n.frombuffer(arr.get_obj(), dtype=n.dtype(datatype)).view(n.dtype(datatype)).reshape(shape)",
    "docstring": "Takes mp shared array and returns numpy array with given shape."
  },
  {
    "code": "def _getbug(self, objid, **kwargs):\n        return self._getbugs([objid], permissive=False, **kwargs)[0]",
    "docstring": "Thin wrapper around _getbugs to handle the slight argument tweaks\n        for fetching a single bug. The main bit is permissive=False, which\n        will tell bugzilla to raise an explicit error if we can't fetch\n        that bug.\n\n        This logic is called from Bug() too"
  },
  {
    "code": "def unicode_urlencode(obj, charset='utf-8', for_qs=False):\n    if not isinstance(obj, string_types):\n        obj = text_type(obj)\n    if isinstance(obj, text_type):\n        obj = obj.encode(charset)\n    safe = not for_qs and b'/' or b''\n    rv = text_type(url_quote(obj, safe))\n    if for_qs:\n        rv = rv.replace('%20', '+')\n    return rv",
    "docstring": "URL escapes a single bytestring or unicode string with the\n    given charset if applicable to URL safe quoting under all rules\n    that need to be considered under all supported Python versions.\n\n    If non strings are provided they are converted to their unicode\n    representation first."
  },
  {
    "code": "def stations(self, station, limit=10):\n        query = {\n            'start': 1,\n            'S': station + '?',\n            'REQ0JourneyStopsB': limit\n        }\n        rsp = requests.get('http://reiseauskunft.bahn.de/bin/ajax-getstop.exe/dn', params=query)\n        return parse_stations(rsp.text)",
    "docstring": "Find stations for given queries\n\n        Args:\n            station (str): search query\n            limit (int): limit number of results"
  },
  {
    "code": "def get_broadcast(self, broadcast_guid, **kwargs):\n        params = kwargs\n        broadcast = self._call('broadcasts/%s' % broadcast_guid,\n            params=params, content_type='application/json')\n        return Broadcast(broadcast)",
    "docstring": "Get a specific broadcast by guid"
  },
  {
    "code": "def _handle_produce_response(self, node_id, send_time, batches, response):\n        log.debug('Parsing produce response: %r', response)\n        if response:\n            batches_by_partition = dict([(batch.topic_partition, batch)\n                                         for batch in batches])\n            for topic, partitions in response.topics:\n                for partition_info in partitions:\n                    if response.API_VERSION < 2:\n                        partition, error_code, offset = partition_info\n                        ts = None\n                    else:\n                        partition, error_code, offset, ts = partition_info\n                    tp = TopicPartition(topic, partition)\n                    error = Errors.for_code(error_code)\n                    batch = batches_by_partition[tp]\n                    self._complete_batch(batch, error, offset, ts)\n            if response.API_VERSION > 0:\n                self._sensors.record_throttle_time(response.throttle_time_ms, node=node_id)\n        else:\n            for batch in batches:\n                self._complete_batch(batch, None, -1, None)",
    "docstring": "Handle a produce response."
  },
  {
    "code": "def update(self, command=None, **kwargs):\n        if command is None:\n            argparser = self.argparser\n        else:\n            argparser = self[command]\n        for k,v in kwargs.items():\n            setattr(argparser, k, v)",
    "docstring": "update data, which is usually passed in ArgumentParser initialization\n\n        e.g. command.update(prog=\"foo\")"
  },
  {
    "code": "def method_id(self, api_info):\n    if api_info.resource_name:\n      resource_part = '.%s' % self.__safe_name(api_info.resource_name)\n    else:\n      resource_part = ''\n    return '%s%s.%s' % (self.__safe_name(api_info.name), resource_part,\n                        self.__safe_name(self.name))",
    "docstring": "Computed method name."
  },
  {
    "code": "def get_properties(cls_def):\n    prop_list = {prop: value for prop, value in cls_def.items() \\\n                 if 'rdf_Property' in value.get('rdf_type', \"\") or \\\n                 value.get('rdfs_domain')}\n    return prop_list",
    "docstring": "cycles through the class definiton and returns all properties"
  },
  {
    "code": "def location_filter(files_with_tags, location, radius):\r\n    on_location = dict()\r\n    for f, tags in files_with_tags.items():\r\n        if 'GPS GPSLatitude' in tags:\r\n            try:\r\n                lat = convert_to_decimal(str(tags['GPS GPSLatitude']))\r\n                long = convert_to_decimal(str(tags['GPS GPSLongitude']))\r\n            except ValueError:\r\n                print('{0} has invalid gps info'.format(f))\r\n            try:\r\n                if haversine(lat, long, location['lat'], location['long']) < radius:\r\n                    on_location[f] = tags\r\n            except InvalidCoordinate:\r\n                print('{0} has invalid gps info'.format(f))\r\n    return on_location",
    "docstring": "Get photos taken within the specified radius from a given point."
  },
  {
    "code": "def _graphite_url(self, query, raw_data=False, graphite_url=None):\n        query = escape.url_escape(query)\n        graphite_url = graphite_url or self.reactor.options.get('public_graphite_url')\n        url = \"{base}/render/?target={query}&from=-{from_time}&until=-{until}\".format(\n            base=graphite_url, query=query,\n            from_time=self.from_time.as_graphite(),\n            until=self.until.as_graphite(),\n        )\n        if raw_data:\n            url = \"{}&format=raw\".format(url)\n        return url",
    "docstring": "Build Graphite URL."
  },
  {
    "code": "async def send_api(container, targetname, name, params = {}):\n    handle = object()\n    apiEvent = ModuleAPICall(handle, targetname, name, params = params)\n    await container.wait_for_send(apiEvent)",
    "docstring": "Send API and discard the result"
  },
  {
    "code": "def get_by_name(self, name):\n        rs, _ = self.list(filter=field('name').eq(name), limit=1)\n        if len(rs) is 0:\n            raise CDRouterError('no such device')\n        return rs[0]",
    "docstring": "Get a device by name.\n\n        :param name: Device name as string.\n        :return: :class:`devices.Device <devices.Device>` object\n        :rtype: devices.Device"
  },
  {
    "code": "def _handle_captcha(captcha_data, message=''):\n        from tempfile import NamedTemporaryFile\n        tmpf = NamedTemporaryFile(suffix='.png')\n        tmpf.write(captcha_data)\n        tmpf.flush()\n        captcha_text = input('Please take a look at the captcha image \"%s\" and provide the code:' % tmpf.name)\n        tmpf.close()\n        return captcha_text",
    "docstring": "Called when a captcha must be solved\n        Writes the image to a temporary file and asks the user to enter the code.\n\n        Args:\n            captcha_data: Bytestring of the PNG captcha image.\n            message: Optional. A message from Steam service.\n\n        Returns:\n            A string containing the solved captcha code."
  },
  {
    "code": "def upgrade_tools_all(call=None):\n    if call != 'function':\n        raise SaltCloudSystemExit(\n            'The upgrade_tools_all function must be called with '\n            '-f or --function.'\n        )\n    ret = {}\n    vm_properties = [\"name\"]\n    vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)\n    for vm in vm_list:\n        ret[vm['name']] = _upg_tools_helper(vm['object'])\n    return ret",
    "docstring": "To upgrade VMware Tools on all virtual machines present in\n    the specified provider\n\n    .. note::\n\n        If the virtual machine is running Windows OS, this function\n        will attempt to suppress the automatic reboot caused by a\n        VMware Tools upgrade.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -f upgrade_tools_all my-vmware-config"
  },
  {
    "code": "def _replace_match(m, env):\n    s = m.group()[1:-1].strip()\n    try:\n        return getattr(env, s)\n    except AttributeError:\n        pass\n    for r in [_replace_envvar, _replace_config, _replace_posargs]:\n        try:\n            return r(s, env)\n        except ValueError:\n            pass\n    raise NotImplementedError(\"{%s} not understood in tox.ini file.\" % s)",
    "docstring": "Given a match object, having matched something inside curly braces,\n    replace the contents if matches one of the supported tox-substitutions."
  },
  {
    "code": "def setup_and_load_epoch(hparams, data_dir, which_epoch_data=None):\n  t2t_env = rl_utils.setup_env(\n      hparams, batch_size=hparams.real_batch_size,\n      max_num_noops=hparams.max_num_noops\n  )\n  if which_epoch_data is not None:\n    if which_epoch_data == \"last\":\n      which_epoch_data = infer_last_epoch_num(data_dir)\n    assert isinstance(which_epoch_data, int), \\\n      \"{}\".format(type(which_epoch_data))\n    t2t_env.start_new_epoch(which_epoch_data, data_dir)\n  else:\n    t2t_env.start_new_epoch(-999)\n  return t2t_env",
    "docstring": "Load T2TGymEnv with data from one epoch.\n\n  Args:\n    hparams: hparams.\n    data_dir: data directory.\n    which_epoch_data: data from which epoch to load.\n\n  Returns:\n    env."
  },
  {
    "code": "def customer(self):\n        url = self._get_link('customer')\n        if url:\n            resp = self.client.customers.perform_api_call(self.client.customers.REST_READ, url)\n            return Customer(resp)",
    "docstring": "Return the customer for this subscription."
  },
  {
    "code": "def load(fp, expand_includes=True, include_position=False, include_comments=False, **kwargs):\n    p = Parser(expand_includes=expand_includes,\n               include_comments=include_comments, **kwargs)\n    ast = p.load(fp)\n    m = MapfileToDict(include_position=include_position,\n                      include_comments=include_comments, **kwargs)\n    d = m.transform(ast)\n    return d",
    "docstring": "Load a Mapfile from an open file or file-like object.\n\n    Parameters\n    ----------\n\n    fp: file\n        A file-like object - as with all Mapfiles this should be encoded in \"utf-8\"\n    expand_includes: boolean\n        Load any ``INCLUDE`` files in the MapFile\n    include_comments: boolean\n         Include or discard comment strings from the Mapfile - *experimental*\n    include_position: boolean\n         Include the position of the Mapfile tokens in the output\n\n    Returns\n    -------\n\n    dict\n        A Python dictionary representing the Mapfile in the mappyfile format\n\n    Example\n    -------\n\n    To open a Mapfile from a file and return it as a dictionary object::\n\n        with open('mymap.map') as fp:\n            d = mappyfile.load(fp)\n\n    Notes\n    -----\n\n    Partial Mapfiles can also be opened, for example a file containing a ``LAYER`` object."
  },
  {
    "code": "def all_settings(self, uppercase_keys=False):\n        d = {}\n        for k in self.all_keys(uppercase_keys):\n            d[k] = self.get(k)\n        return d",
    "docstring": "Return all settings as a `dict`."
  },
  {
    "code": "def _read_requires_python(metadata):\n    value = metadata.dictionary.get(\"requires_python\")\n    if value is not None:\n        return value\n    if metadata._legacy:\n        value = metadata._legacy.get(\"Requires-Python\")\n        if value is not None and value != \"UNKNOWN\":\n            return value\n    return \"\"",
    "docstring": "Read wheel metadata to know the value of Requires-Python.\n\n    This is surprisingly poorly supported in Distlib. This function tries\n    several ways to get this information:\n\n    * Metadata 2.0: metadata.dictionary.get(\"requires_python\") is not None\n    * Metadata 2.1: metadata._legacy.get(\"Requires-Python\") is not None\n    * Metadata 1.2: metadata._legacy.get(\"Requires-Python\") != \"UNKNOWN\""
  },
  {
    "code": "def get_allowed(allow, disallow):\n    if allow is None and disallow is None:\n        return SUMO_VEHICLE_CLASSES\n    elif disallow is None:\n        return allow.split()\n    else:\n        disallow = disallow.split()\n        return tuple([c for c in SUMO_VEHICLE_CLASSES if c not in disallow])",
    "docstring": "Normalize the given string attributes as a list of all allowed vClasses."
  },
  {
    "code": "def _mark_quoted_email_splitlines(markers, lines):\n    markerlist = list(markers)\n    for i, line in enumerate(lines):\n        if markerlist[i] != 'm':\n            continue\n        for pattern in SPLITTER_PATTERNS:\n            matcher = re.search(pattern, line)\n            if matcher:\n                markerlist[i] = 's'\n                break\n    return \"\".join(markerlist)",
    "docstring": "When there are headers indented with '>' characters, this method will\n    attempt to identify if the header is a splitline header. If it is, then we\n    mark it with 's' instead of leaving it as 'm' and return the new markers."
  },
  {
    "code": "def method(func):\n    attr = abc.abstractmethod(func)\n    attr.__imethod__ = True\n    return attr",
    "docstring": "Wrap a function as a method."
  },
  {
    "code": "def _resolve_version(version):\n    if version is not LATEST:\n        return version\n    resp = urlopen('https://pypi.python.org/pypi/setuptools/json')\n    with contextlib.closing(resp):\n        try:\n            charset = resp.info().get_content_charset()\n        except Exception:\n            charset = 'UTF-8'\n        reader = codecs.getreader(charset)\n        doc = json.load(reader(resp))\n    return str(doc['info']['version'])",
    "docstring": "Resolve LATEST version"
  },
  {
    "code": "def convert_x_www_form_urlencoded_to_dict(post_data):\n    if isinstance(post_data, str):\n        converted_dict = {}\n        for k_v in post_data.split(\"&\"):\n            try:\n                key, value = k_v.split(\"=\")\n            except ValueError:\n                raise Exception(\n                    \"Invalid x_www_form_urlencoded data format: {}\".format(post_data)\n                )\n            converted_dict[key] = unquote(value)\n        return converted_dict\n    else:\n        return post_data",
    "docstring": "convert x_www_form_urlencoded data to dict\n\n    Args:\n        post_data (str): a=1&b=2\n\n    Returns:\n        dict: {\"a\":1, \"b\":2}"
  },
  {
    "code": "def tag_reachable_scripts(cls, scratch):\n        if getattr(scratch, 'hairball_prepared', False):\n            return\n        reachable = set()\n        untriggered_events = {}\n        for script in cls.iter_scripts(scratch):\n            if not isinstance(script, kurt.Comment):\n                starting_type = cls.script_start_type(script)\n                if starting_type == cls.NO_HAT:\n                    script.reachable = False\n                elif starting_type == cls.HAT_WHEN_I_RECEIVE:\n                    script.reachable = False\n                    message = script[0].args[0].lower()\n                    untriggered_events.setdefault(message, set()).add(script)\n                else:\n                    script.reachable = True\n                    reachable.add(script)\n        while reachable:\n            for event in cls.get_broadcast_events(reachable.pop()):\n                if event in untriggered_events:\n                    for script in untriggered_events.pop(event):\n                        script.reachable = True\n                        reachable.add(script)\n        scratch.hairball_prepared = True",
    "docstring": "Tag each script with attribute reachable.\n\n        The reachable attribute will be set false for any script that does not\n        begin with a hat block. Additionally, any script that begins with a\n        'when I receive' block whose event-name doesn't appear in a\n        corresponding broadcast block is marked as unreachable."
  },
  {
    "code": "def operate_on(self, when=None, apply=False, **kwargs):\n        pzone = self.get(**kwargs)\n        now = timezone.now()\n        if when is None:\n            when = now\n        if when < now:\n            histories = pzone.history.filter(date__lte=when)\n            if histories.exists():\n                pzone.data = histories[0].data\n        else:\n            data = pzone.data\n            next_operation_time = cache.get('pzone-operation-expiry-' + pzone.name)\n            if next_operation_time is None or next_operation_time < when:\n                pending_operations = pzone.operations.filter(when__lte=when, applied=False)\n                for operation in pending_operations:\n                    data = operation.apply(data)\n                pzone.data = data\n                if apply and pending_operations.exists():\n                    update_pzone.delay(**kwargs)\n        return pzone",
    "docstring": "Do something with operate_on. If apply is True, all transactions will\n        be applied and saved via celery task."
  },
  {
    "code": "def KillOldFlows(self):\n    if not self.IsRunning():\n      return False\n    start_time = self.Get(self.Schema.LAST_RUN_TIME)\n    lifetime = self.Get(self.Schema.CRON_ARGS).lifetime\n    elapsed = rdfvalue.RDFDatetime.Now() - start_time\n    if lifetime and elapsed > lifetime:\n      self.StopCurrentRun()\n      stats_collector_instance.Get().IncrementCounter(\n          \"cron_job_timeout\", fields=[self.urn.Basename()])\n      stats_collector_instance.Get().RecordEvent(\n          \"cron_job_latency\", elapsed.seconds, fields=[self.urn.Basename()])\n      return True\n    return False",
    "docstring": "Disable cron flow if it has exceeded CRON_ARGS.lifetime.\n\n    Returns:\n      bool: True if the flow is was killed."
  },
  {
    "code": "def response(code, body='', etag=None, last_modified=None, expires=None, **kw):\n    if etag is not None:\n        if not (etag[0] == '\"' and etag[-1] == '\"'):\n            etag = '\"%s\"' % etag\n        kw['etag'] = etag\n    if last_modified is not None:\n        kw['last_modified'] = datetime_to_httpdate(last_modified)\n    if expires is not None:\n        if isinstance(expires, datetime):\n            kw['expires'] = datetime_to_httpdate(expires)\n        else:\n            kw['expires'] = timedelta_to_httpdate(expires)\n    headers = [(k.replace('_', '-').title(), v) for k, v in sorted(kw.items())]\n    return Response(code, headers, body)",
    "docstring": "Helper to build an HTTP response.\n\n    Parameters:\n\n    code\n     :  An integer status code.\n    body\n     :  The response body. See `Response.__init__` for details.\n    etag\n     :  A value for the ETag header. Double quotes will be added unless the\n        string starts and ends with a double quote.\n    last_modified\n     :  A value for the Last-Modified header as a datetime.datetime object\n        or Unix timestamp.\n    expires\n     :  A value for the Expires header as number of seconds, datetime.timedelta\n        or datetime.datetime object.\n        Note: a value of type int or float is interpreted as a number of\n        seconds in the future, *not* as Unix timestamp.\n    **kw\n     :  All other keyword arguments are interpreted as response headers.\n        The names will be converted to header names by replacing\n        underscores with hyphens and converting to title case\n        (e.g. `x_powered_by` => `X-Powered-By`)."
  },
  {
    "code": "def parse_footnotes(document, xmlcontent):\n    footnotes = etree.fromstring(xmlcontent)\n    document.footnotes = {}\n    for footnote in footnotes.xpath('.//w:footnote', namespaces=NAMESPACES):\n        _type = footnote.attrib.get(_name('{{{w}}}type'), None)\n        if _type in ['separator', 'continuationSeparator', 'continuationNotice']:\n            continue\n        paragraphs = [parse_paragraph(document, para) for para in footnote.xpath('.//w:p', namespaces=NAMESPACES)]\n        document.footnotes[footnote.attrib[_name('{{{w}}}id')]] = paragraphs",
    "docstring": "Parse footnotes document.\n\n    Footnotes are defined in file 'footnotes.xml'"
  },
  {
    "code": "def cancel(self):\n        try:\n            del self._protocol._consumers[self.queue]\n        except (KeyError, AttributeError):\n            pass\n        try:\n            del self._protocol.factory._consumers[self.queue]\n        except (KeyError, AttributeError):\n            pass\n        self._running = False\n        yield self._read_loop\n        try:\n            yield self._channel.basic_cancel(consumer_tag=self._tag)\n        except pika.exceptions.AMQPChannelError:\n            pass\n        try:\n            yield self._channel.close()\n        except pika.exceptions.AMQPChannelError:\n            pass\n        if not self.result.called:\n            self.result.callback(self)",
    "docstring": "Cancel the consumer and clean up resources associated with it.\n        Consumers that are canceled are allowed to finish processing any\n        messages before halting.\n\n        Returns:\n            defer.Deferred: A deferred that fires when the consumer has finished\n            processing any message it was in the middle of and has been successfully\n            canceled."
  },
  {
    "code": "def info(self, msg=None, *args, **kwargs):\n        return self._log(logging.INFO, msg, args, kwargs)",
    "docstring": "Similar to DEBUG but at INFO level."
  },
  {
    "code": "def gender(self):\n\t\telement = self._first('NN')\n\t\tif element:\n\t\t\tif re.search('([m|f|n)])\\.', element, re.U):\n\t\t\t\tgenus = re.findall('([m|f|n)])\\.', element, re.U)[0]\n\t\t\t\treturn genus",
    "docstring": "Tries to scrape the gender for a given noun from leo.org."
  },
  {
    "code": "def _shutdown_cherrypy(self):\n        if cherrypy.engine.state == cherrypy.engine.states.STARTED:\n            threading.Timer(1, cherrypy.engine.exit).start()",
    "docstring": "Shutdown cherrypy in one second, if it's running"
  },
  {
    "code": "def class_result(classname):\n    def wrap_errcheck(result, func, arguments):\n        if result is None:\n            return None\n        return classname(result)\n    return wrap_errcheck",
    "docstring": "Errcheck function. Returns a function that creates the specified class."
  },
  {
    "code": "def n_sections(neurites, neurite_type=NeuriteType.all, iterator_type=Tree.ipreorder):\n    return sum(1 for _ in iter_sections(neurites,\n                                        iterator_type=iterator_type,\n                                        neurite_filter=is_type(neurite_type)))",
    "docstring": "Number of sections in a collection of neurites"
  },
  {
    "code": "def stop_change(self):\n        self.logger.info(\"Dimmer %s stop_change\", self.device_id)\n        self.hub.direct_command(self.device_id, '18', '00')\n        success = self.hub.check_success(self.device_id, '18', '00')\n        if success:\n            self.logger.info(\"Dimmer %s stop_change: Light stopped changing successfully\",\n                             self.device_id)\n            self.hub.clear_device_command_cache(self.device_id)\n        else:\n            self.logger.error(\"Dimmer %s stop_change: Light did not stop\",\n                              self.device_id)\n        return success",
    "docstring": "Stop changing light level manually"
  },
  {
    "code": "def disable_all(self, disable):\n        commands = ['ENBH 0',\n                    'ENBL 0',\n                    'MODL 0'\n                    ]\n        command_string = '\\n'.join(commands)\n        print_string = '\\n\\t' + command_string.replace('\\n', '\\n\\t')\n        logging.info(print_string)\n        if disable:\n            self.instr.write(command_string)",
    "docstring": "Disables all modulation and outputs of the Standford MW func. generator"
  },
  {
    "code": "def tcpip(self, port: int or str = 5555) -> None:\n        self._execute('-s', self.device_sn, 'tcpip', str(port))",
    "docstring": "Restart adb server listening on TCP on PORT."
  },
  {
    "code": "def parent(self):\n        try:\n            return Resource(self['parent_type'], uuid=self['parent_uuid'], check=True)\n        except KeyError:\n            raise ResourceMissing('%s has no parent resource' % self)",
    "docstring": "Return parent resource\n\n        :rtype: Resource\n        :raises ResourceNotFound: parent resource doesn't exists\n        :raises ResourceMissing: parent resource is not defined"
  },
  {
    "code": "def from_filename(cls, filename):\n        if not filename:\n            logger.error('No filename specified')\n            return None\n        if not os.path.exists(filename):\n            logger.error(\"Err: File '%s' does not exist\", filename)\n            return None\n        if os.path.isdir(filename):\n            logger.error(\"Err: File '%s' is a directory\", filename)\n            return None\n        try:\n            audiofile = eyed3.load(filename)\n        except Exception as error:\n            print(type(error), error)\n            return None\n        if audiofile is None:\n            return None\n        tags = audiofile.tag\n        album = tags.album\n        title = tags.title\n        lyrics = ''.join([l.text for l in tags.lyrics])\n        artist = tags.album_artist\n        if not artist:\n            artist = tags.artist\n        song = cls(artist, title, album, lyrics)\n        song.filename = filename\n        return song",
    "docstring": "Class constructor using the path to the corresponding mp3 file. The\n        metadata will be read from this file to create the song object, so it\n        must at least contain valid ID3 tags for artist and title."
  },
  {
    "code": "def next_batch(self):\n        is_success, results = AtlasRequest(\n            url_path=self.atlas_url,\n            user_agent=self._user_agent,\n            server=self.server,\n            verify=self.verify,\n        ).get()\n        if not is_success:\n            raise APIResponseError(results)\n        self.total_count = results.get(\"count\")\n        self.atlas_url = self.build_next_url(results.get(\"next\"))\n        self.current_batch = results.get(\"results\", [])",
    "docstring": "Querying API for the next batch of objects and store next url and\n        batch of objects."
  },
  {
    "code": "def iget(self, irods_path, attempts=1, pause=15):\n        if attempts > 1:\n            cmd =\n            cmd = lstrip(cmd)\n            cmd = cmd.format(attempts, irods_path, pause)\n            self.add(cmd)\n        else:\n            self.add('iget -v \"{}\"'.format(irods_path))",
    "docstring": "Add an iget command to retrieve a file from iRODS.\n\n        Parameters\n        ----------\n            irods_path: str\n                Filepath which should be fetched using iget\n            attempts: int (default: 1)\n                Number of retries, if iRODS access fails\n            pause: int (default: 15)\n                Pause between two access attempts in seconds"
  },
  {
    "code": "def handle_bad_update(operation, ret):\n    print(\"Error \" + operation)\n    sys.exit('Return code: ' + str(ret.status_code) + ' Error: ' + ret.text)",
    "docstring": "report error for bad update"
  },
  {
    "code": "def from_csv(cls, path):\n        with open(path) as f:\n            fields = map(float, next(f).split(','))\n        if len(fields) == 3:\n            return u.Quantity([[fields[0], 0, 0],\n                               [0, fields[1], 0],\n                               [0, 0, fields[2]]], unit=u.nanometers)\n        elif len(fields) == 9:\n            return u.Quantity([fields[0:3],\n                               fields[3:6],\n                               fields[6:9]], unit=u.nanometers)\n        else:\n            raise ValueError('This type of CSV is not supported. Please '\n                             'provide a comma-separated list of three or nine '\n                             'floats in a single-line file.')",
    "docstring": "Get box vectors from comma-separated values in file `path`.\n\n        The csv file must containt only one line, which in turn can contain\n        three values (orthogonal vectors) or nine values (triclinic box).\n\n        The values should be in nanometers.\n\n        Parameters\n        ----------\n        path : str\n            Path to CSV file\n\n        Returns\n        -------\n        vectors : simtk.unit.Quantity([3, 3], unit=nanometers"
  },
  {
    "code": "def cal(self, opttype, strike, exp1, exp2):\n        assert pd.Timestamp(exp1) < pd.Timestamp(exp2)\n        _row1 = _relevant_rows(self.data, (strike, exp1, opttype,),\n                \"No key for {} strike {} {}\".format(exp1, strike, opttype))\n        _row2 = _relevant_rows(self.data, (strike, exp2, opttype,),\n                \"No key for {} strike {} {}\".format(exp2, strike, opttype))\n        _price1 = _getprice(_row1)\n        _price2 = _getprice(_row2)\n        _eq = _row1.loc[:, 'Underlying_Price'].values[0]\n        _qt = _row1.loc[:, 'Quote_Time'].values[0]\n        _index = ['Near', 'Far', 'Debit', 'Underlying_Price', 'Quote_Time']\n        _vals = np.array([_price1, _price2, _price2 - _price1, _eq, _qt])\n        return pd.DataFrame(_vals, index=_index, columns=['Value'])",
    "docstring": "Metrics for evaluating a calendar spread.\n\n        Parameters\n        ------------\n        opttype : str ('call' or 'put')\n            Type of option on which to collect data.\n        strike : numeric\n            Strike price.\n        exp1 : date or date str (e.g. '2015-01-01')\n            Earlier expiration date.\n        exp2 : date or date str (e.g. '2015-01-01')\n            Later expiration date.\n\n        Returns\n        ------------\n        metrics : DataFrame\n            Metrics for evaluating spread."
  },
  {
    "code": "def get_django_settings(cls, name, default=None):\n        if hasattr(cls, '__django_settings__'):\n            return getattr(cls.__django_settings__, name, default)\n        from django.conf import settings\n        cls.__django_settings__ = settings\n        return cls.get_django_settings(name)",
    "docstring": "Get params from Django settings.\n\n        :param name: name of param\n        :type name: str,unicode\n        :param default: default value of param\n        :type default: object\n        :return: Param from Django settings or default."
  },
  {
    "code": "def gendict(cls, *args, **kwargs):\n        gk = cls.genkey\n        return dict((gk(k), v) for k, v in dict(*args, **kwargs).items())",
    "docstring": "Pre-translated key dictionary constructor.\n\n        See :type:`dict` for more info.\n\n        :returns: dictionary with uppercase keys\n        :rtype: dict"
  },
  {
    "code": "def get_contacts_of_client_per_page(self, client_id, per_page=1000, page=1):\n        return self._get_resource_per_page(\n            resource=CONTACTS,\n            per_page=per_page,\n            page=page,\n            params={'client_id': client_id},\n        )",
    "docstring": "Get contacts of client per page\n\n        :param client_id: the client id\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :return: list"
  },
  {
    "code": "def get_uint32(self):\n        token = self.get().unescape()\n        if not token.is_identifier():\n            raise dns.exception.SyntaxError('expecting an identifier')\n        if not token.value.isdigit():\n            raise dns.exception.SyntaxError('expecting an integer')\n        value = long(token.value)\n        if value < 0 or value > 4294967296L:\n            raise dns.exception.SyntaxError('%d is not an unsigned 32-bit integer' % value)\n        return value",
    "docstring": "Read the next token and interpret it as a 32-bit unsigned\n        integer.\n\n        @raises dns.exception.SyntaxError:\n        @rtype: int"
  },
  {
    "code": "def print_typedefs(self, w=0, **print3opts):\n        for k in _all_kinds:\n            t = [(self._prepr(a), v) for a, v in _items(_typedefs) if v.kind == k and (v.both or self._code_)]\n            if t:\n                self._printf('%s%*d %s type%s:  basicsize, itemsize, _len_(), _refs()',\n                             linesep, w, len(t), k, _plural(len(t)), **print3opts)\n                for a, v in _sorted(t):\n                    self._printf('%*s %s:  %s', w, '', a, v, **print3opts)\n        t = _sum([len(v) for v in _values(_dict_classes)])\n        if t:\n            self._printf('%s%*d dict/-like classes:', linesep, w, t, **print3opts)\n            for m, v in _items(_dict_classes):\n                self._printf('%*s %s:  %s', w, '', m, self._prepr(v), **print3opts)",
    "docstring": "Print the types and dict tables.\n\n               *w=0*            -- indentation for each line\n\n               *print3options*  -- print options, as in Python 3.0"
  },
  {
    "code": "def disable_code_breakpoint(self, dwProcessId, address):\n        p  = self.system.get_process(dwProcessId)\n        bp = self.get_code_breakpoint(dwProcessId, address)\n        if bp.is_running():\n            self.__del_running_bp_from_all_threads(bp)\n        bp.disable(p, None)",
    "docstring": "Disables the code breakpoint at the given address.\n\n        @see:\n            L{define_code_breakpoint},\n            L{has_code_breakpoint},\n            L{get_code_breakpoint},\n            L{enable_code_breakpoint}\n            L{enable_one_shot_code_breakpoint},\n            L{erase_code_breakpoint},\n\n        @type  dwProcessId: int\n        @param dwProcessId: Process global ID.\n\n        @type  address: int\n        @param address: Memory address of breakpoint."
  },
  {
    "code": "def is_numeric(value,\n               minimum = None,\n               maximum = None,\n               **kwargs):\n    try:\n        value = validators.numeric(value,\n                                   minimum = minimum,\n                                   maximum = maximum,\n                                   **kwargs)\n    except SyntaxError as error:\n        raise error\n    except Exception:\n        return False\n    return True",
    "docstring": "Indicate whether ``value`` is a numeric value.\n\n    :param value: The value to evaluate.\n\n    :param minimum: If supplied, will make sure that ``value`` is greater than or\n      equal to this value.\n    :type minimum: numeric\n\n    :param maximum: If supplied, will make sure that ``value`` is less than or\n      equal to this value.\n    :type maximum: numeric\n\n    :returns: ``True`` if ``value`` is valid, ``False`` if it is not.\n    :rtype: :class:`bool <python:bool>`\n\n    :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates\n      keyword parameters passed to the underlying validator"
  },
  {
    "code": "def _glob(filenames):\n    if isinstance(filenames, string_types):\n        filenames = [filenames]\n    matches = []\n    for name in filenames:\n        matched_names = glob(name)\n        if not matched_names:\n            matches.append(name)\n        else:\n            matches.extend(matched_names)\n    return matches",
    "docstring": "Glob a filename or list of filenames but always return the original\n    string if the glob didn't match anything so URLs for remote file access\n    are not clobbered."
  },
  {
    "code": "async def send_message(self, message, **kwargs):\n        if 'end' in kwargs:\n            warnings.warn('\"end\" argument is deprecated, use '\n                          '\"stream.send_trailing_metadata\" explicitly',\n                          stacklevel=2)\n        end = kwargs.pop('end', False)\n        assert not kwargs, kwargs\n        if not self._send_initial_metadata_done:\n            await self.send_initial_metadata()\n        if not self._cardinality.server_streaming:\n            if self._send_message_count:\n                raise ProtocolError('Server should send exactly one message '\n                                    'in response')\n        message, = await self._dispatch.send_message(message)\n        await send_message(self._stream, self._codec, message, self._send_type)\n        self._send_message_count += 1\n        if end:\n            await self.send_trailing_metadata()",
    "docstring": "Coroutine to send message to the client.\n\n        If server sends UNARY response, then you should call this coroutine only\n        once. If server sends STREAM response, then you can call this coroutine\n        as many times as you need.\n\n        :param message: message object"
  },
  {
    "code": "def _QueryHash(self, digest):\n    if not self._url:\n      self._url = '{0:s}://{1:s}:{2:d}/file/find'.format(\n          self._protocol, self._host, self._port)\n    request_data = {self.lookup_hash: digest}\n    try:\n      json_response = self.MakeRequestAndDecodeJSON(\n          self._url, 'POST', data=request_data)\n    except errors.ConnectionError as exception:\n      json_response = None\n      logger.error('Unable to query Viper with error: {0!s}.'.format(\n          exception))\n    return json_response",
    "docstring": "Queries the Viper Server for a specfic hash.\n\n    Args:\n      digest (str): hash to look up.\n\n    Returns:\n      dict[str, object]: JSON response or None on error."
  },
  {
    "code": "def draw(self):\n        colors = resolve_colors(len(self.support_))\n        if self._mode == BALANCE:\n            self.ax.bar(\n                np.arange(len(self.support_)), self.support_,\n                color=colors, align='center', width=0.5\n            )\n        else:\n            bar_width = 0.35\n            labels = [\"train\", \"test\"]\n            for idx, support in enumerate(self.support_):\n                index = np.arange(len(self.classes_))\n                if idx > 0:\n                    index = index + bar_width\n                self.ax.bar(\n                    index, support, bar_width,\n                    color=colors[idx], label=labels[idx]\n                )\n        return self.ax",
    "docstring": "Renders the class balance chart on the specified axes from support."
  },
  {
    "code": "def similar(self, similarity):\n        pattern = Pattern(self.path)\n        pattern.similarity = similarity\n        return pattern",
    "docstring": "Returns a new Pattern with the specified similarity threshold"
  },
  {
    "code": "def max_knob_end_distance(self):\n        return max([distance(self.knob_end, h) for h in self.hole])",
    "docstring": "Maximum distance between knob_end and each of the hole side-chain centres."
  },
  {
    "code": "def prep_hla(work_dir, sample, calls, hlas, normal_bam, tumor_bam):\n    work_dir = utils.safe_makedir(os.path.join(work_dir, sample, \"inputs\"))\n    hla_file = os.path.join(work_dir, \"%s-hlas.txt\" % sample)\n    with open(calls) as in_handle:\n        with open(hla_file, \"w\") as out_handle:\n            next(in_handle)\n            for line in in_handle:\n                _, _, a, _, _ = line.strip().split(\",\")\n                a1, a2 = a.split(\";\")\n                out_handle.write(get_hla_choice(name_to_absolute(a1), hlas, normal_bam, tumor_bam) + \"\\n\")\n                out_handle.write(get_hla_choice(name_to_absolute(a2), hlas, normal_bam, tumor_bam) + \"\\n\")\n    return hla_file",
    "docstring": "Convert HLAs into ABSOLUTE format for use with LOHHLA.\n\n    LOHHLA hard codes names to hla_a, hla_b, hla_c so need to move"
  },
  {
    "code": "def AuthorizeUser(self, user, subject):\n    user_set = self.authorized_users.setdefault(subject, set())\n    user_set.add(user)",
    "docstring": "Allow given user access to a given subject."
  },
  {
    "code": "def _vars(ftype, name, *dims):\n    shape = _dims2shape(*dims)\n    objs = list()\n    for indices in itertools.product(*[range(i, j) for i, j in shape]):\n        objs.append(_VAR[ftype](name, indices))\n    return farray(objs, shape, ftype)",
    "docstring": "Return a new farray filled with Boolean variables."
  },
  {
    "code": "def delete(self, reason=None):\n        response = API.delete_user(self.api_token, self.password,\n                                   reason=reason, in_background=0)\n        _fail_if_contains_errors(response)",
    "docstring": "Delete the user's account from Todoist.\n\n        .. warning:: You cannot recover the user after deletion!\n\n        :param reason: The reason for deletion.\n        :type reason: str\n\n        >>> from pytodoist import todoist\n        >>> user = todoist.login('john.doe@gmail.com', 'password')\n        >>> user.delete()\n        ... # The user token is now invalid and Todoist operations will fail."
  },
  {
    "code": "def use_plenary_composition_view(self):\n        self._object_views['composition'] = PLENARY\n        for session in self._get_provider_sessions():\n            try:\n                session.use_plenary_composition_view()\n            except AttributeError:\n                pass",
    "docstring": "Pass through to provider CompositionLookupSession.use_plenary_composition_view"
  },
  {
    "code": "def more_search(self, more_page):\n        next_page = self.current_page + 1\n        top_page = more_page + self.current_page\n        for page in range(next_page, (top_page + 1)):\n            start = \"start={0}\".format(str((page - 1) * 10))\n            url = \"{0}{1}&{2}\".format(self.google, self.query, start)\n            self._execute_search_request(url)\n            self.current_page += 1",
    "docstring": "Method to add more result to an already exist result.\n\n        more_page determine how many result page should be added\n        to the current result."
  },
  {
    "code": "def cli(env, identifier):\n    mgr = SoftLayer.ObjectStorageManager(env.client)\n    credential_list = mgr.list_credential(identifier)\n    table = formatting.Table(['id', 'password', 'username', 'type_name'])\n    for credential in credential_list:\n        table.add_row([\n            credential['id'],\n            credential['password'],\n            credential['username'],\n            credential['type']['name']\n        ])\n    env.fout(table)",
    "docstring": "Retrieve credentials used for generating an AWS signature. Max of 2."
  },
  {
    "code": "def _populate_bunch_with_element(element):\n    if 'value' in element.attrib:\n        return element.get('value')\n    current_bunch = Bunch()\n    if element.get('id'):\n        current_bunch['nextra_element_id'] = element.get('id')\n    for subelement in element.getchildren():\n        current_bunch[subelement.tag] = _populate_bunch_with_element(\n            subelement)\n    return current_bunch",
    "docstring": "Helper function to recursively populates a Bunch from an XML tree.\n    Returns leaf XML elements as a simple value, branch elements are returned\n    as Bunches containing their subelements as value or recursively generated\n    Bunch members."
  },
  {
    "code": "def u(data, bits=None, endian=None, target=None):\n    return globals()['u%d' % _get_bits(bits, target)](data, endian=endian, target=target)",
    "docstring": "Unpack a signed pointer for a given target.\n\n    Args:\n        data(bytes): The data to unpack.\n        bits(:class:`pwnypack.target.Target.Bits`): Override the default\n            word size. If ``None`` it will look at the word size of\n            ``target``.\n        endian(:class:`~pwnypack.target.Target.Endian`): Override the default\n            byte order. If ``None``, it will look at the byte order of\n            the ``target`` argument.\n        target(:class:`~pwnypack.target.Target`): Override the default byte\n            order. If ``None``, it will look at the byte order of\n            the global :data:`~pwnypack.target.target`.\n\n    Returns:\n        int: The pointer value."
  },
  {
    "code": "def checksum(digits, scale):\n    chk_nbr = 11 - (sum(map(operator.mul, digits, scale)) % 11)\n    if chk_nbr == 11:\n        return 0\n    return chk_nbr",
    "docstring": "Calculate checksum of Norwegian personal identity code.\n\n    Checksum is calculated with \"Module 11\" method using a scale.\n    The digits of the personal code are multiplied by the corresponding\n    number in the scale and summed;\n    if remainder of module 11 of the sum is less than 10, checksum is the\n    remainder.\n    If remainder is 0, the checksum is 0.\n\n    https://no.wikipedia.org/wiki/F%C3%B8dselsnummer"
  },
  {
    "code": "def pathparse(value, sep=os.pathsep, os_sep=os.sep):\n    escapes = []\n    normpath = ntpath.normpath if os_sep == '\\\\' else posixpath.normpath\n    if '\\\\' not in (os_sep, sep):\n        escapes.extend((\n            ('\\\\\\\\', '<ESCAPE-ESCAPE>', '\\\\'),\n            ('\\\\\"', '<ESCAPE-DQUOTE>', '\"'),\n            ('\\\\\\'', '<ESCAPE-SQUOTE>', '\\''),\n            ('\\\\%s' % sep, '<ESCAPE-PATHSEP>', sep),\n            ))\n    for original, escape, unescape in escapes:\n        value = value.replace(original, escape)\n    for part in pathsplit(value, sep=sep):\n        if part[-1:] == os_sep and part != os_sep:\n            part = part[:-1]\n        for original, escape, unescape in escapes:\n            part = part.replace(escape, unescape)\n        yield normpath(fsdecode(part))",
    "docstring": "Get enviroment PATH directories as list.\n\n    This function cares about spliting, escapes and normalization of paths\n    across OSes.\n\n    :param value: path string, as given by os.environ['PATH']\n    :type value: str\n    :param sep: PATH separator, defaults to os.pathsep\n    :type sep: str\n    :param os_sep: OS filesystem path separator, defaults to os.sep\n    :type os_sep: str\n    :yields: every path\n    :ytype: str"
  },
  {
    "code": "def get(self, run_id, metric_id):\n        run_id = self._parse_run_id(run_id)\n        query = self._build_query(run_id, metric_id)\n        row = self._read_metric_from_db(metric_id, run_id, query)\n        metric = self._to_intermediary_object(row)\n        return metric",
    "docstring": "Read a metric of the given id and run.\n\n        The returned object has the following format (timestamps are datetime\n         objects).\n\n        .. code::\n\n            {\"steps\": [0,1,20,40,...],\n            \"timestamps\": [timestamp1,timestamp2,timestamp3,...],\n            \"values\": [0,1 2,3,4,5,6,...],\n            \"name\": \"name of the metric\",\n            \"metric_id\": \"metric_id\",\n            \"run_id\": \"run_id\"}\n\n        :param run_id: ID of the Run that the metric belongs to.\n        :param metric_id: The ID fo the metric.\n        :return: The whole metric as specified.\n\n        :raise NotFoundError"
  },
  {
    "code": "def _print_details(extra=None):\n    def print_node_handler(name, node, depth):\n        line = \"{0}{1} {2} ({3}:{4})\".format(depth,\n                                             (\" \" * depth),\n                                             name,\n                                             node.line,\n                                             node.col)\n        if extra is not None:\n            line += \" [{0}]\".format(extra(node))\n        sys.stdout.write(line + \"\\n\")\n    return print_node_handler",
    "docstring": "Return a function that prints node details."
  },
  {
    "code": "def get_server_alerts(call=None, for_output=True, **kwargs):\n    for key, value in kwargs.items():\n        servername = \"\"\n        if key == \"servername\":\n            servername = value\n    creds = get_creds()\n    clc.v2.SetCredentials(creds[\"user\"], creds[\"password\"])\n    alerts = clc.v2.Server(servername).Alerts()\n    return alerts",
    "docstring": "Return a list of alerts from CLC as reported by their infra"
  },
  {
    "code": "def ajax_login(request):\n    username = request.POST['username']\n    password = request.POST['password']\n    user = authenticate(username=username, password=password)\n    if user is not None:\n        if user.is_active:\n            login(request, user)\n            return HttpResponse(content='Successful login',\n                                content_type='text/plain', status=200)\n        else:\n            return HttpResponse(content='Disabled account',\n                                content_type='text/plain', status=403)\n    else:\n        return HttpResponse(content='Invalid login',\n                            content_type='text/plain', status=403)",
    "docstring": "Accept a POST request to login.\n\n    :param request:\n        `django.http.HttpRequest` object, containing mandatory parameters\n        username and password required."
  },
  {
    "code": "def update_pipe_channel(self, uid, channel_name, label):\n        pipe_group_name = _form_pipe_channel_name(channel_name)\n        if self.channel_layer:\n            current = self.channel_maps.get(uid, None)\n            if current != pipe_group_name:\n                if current:\n                    async_to_sync(self.channel_layer.group_discard)(current, self.channel_name)\n                self.channel_maps[uid] = pipe_group_name\n                async_to_sync(self.channel_layer.group_add)(pipe_group_name, self.channel_name)",
    "docstring": "Update this consumer to listen on channel_name for the js widget associated with uid"
  },
  {
    "code": "def indent(indent_str=None):\n    def indentation_rule():\n        inst = Indentator(indent_str)\n        return {'layout_handlers': {\n            Indent: inst.layout_handler_indent,\n            Dedent: inst.layout_handler_dedent,\n            Newline: inst.layout_handler_newline,\n            OptionalNewline: inst.layout_handler_newline_optional,\n            OpenBlock: layout_handler_openbrace,\n            CloseBlock: layout_handler_closebrace,\n            EndStatement: layout_handler_semicolon,\n        }}\n    return indentation_rule",
    "docstring": "An example indentation ruleset."
  },
  {
    "code": "def _load_torrents_directory(self):\n        r = self._req_lixian_get_id(torrent=True)\n        self._downloads_directory = self._load_directory(r['cid'])",
    "docstring": "Load torrents directory\n\n        If it does not exist yet, this request will cause the system to create\n        one"
  },
  {
    "code": "def get_parent(self, log_info):\n        if self.data.get('scope', 'log') == 'log':\n            if log_info.scope_type != 'projects':\n                raise ValueError(\"Invalid log subscriber scope\")\n            parent = \"%s/%s\" % (log_info.scope_type, log_info.scope_id)\n        elif self.data['scope'] == 'project':\n            parent = 'projects/{}'.format(\n                self.data.get('scope_id', self.session.get_default_project()))\n        elif self.data['scope'] == 'organization':\n            parent = 'organizations/{}'.format(self.data['scope_id'])\n        elif self.data['scope'] == 'folder':\n            parent = 'folders/{}'.format(self.data['scope_id'])\n        elif self.data['scope'] == 'billing':\n            parent = 'billingAccounts/{}'.format(self.data['scope_id'])\n        else:\n            raise ValueError(\n                'invalid log subscriber scope %s' % (self.data))\n        return parent",
    "docstring": "Get the parent container for the log sink"
  },
  {
    "code": "def _generate_cpu_stats():\n        cpu_name = urwid.Text(\"CPU Name N/A\", align=\"center\")\n        try:\n            cpu_name = urwid.Text(get_processor_name().strip(), align=\"center\")\n        except OSError:\n            logging.info(\"CPU name not available\")\n        return [urwid.Text(('bold text', \"CPU Detected\"),\n                           align=\"center\"), cpu_name, urwid.Divider()]",
    "docstring": "Read and display processor name"
  },
  {
    "code": "def root_manifest_id(self, root_manifest_id):\n        if root_manifest_id is not None and len(root_manifest_id) > 32:\n            raise ValueError(\"Invalid value for `root_manifest_id`, length must be less than or equal to `32`\")\n        self._root_manifest_id = root_manifest_id",
    "docstring": "Sets the root_manifest_id of this UpdateCampaignPutRequest.\n\n        :param root_manifest_id: The root_manifest_id of this UpdateCampaignPutRequest.\n        :type: str"
  },
  {
    "code": "def get(self, name):\n        return self.prepare_model(self.client.api.inspect_image(name))",
    "docstring": "Gets an image.\n\n        Args:\n            name (str): The name of the image.\n\n        Returns:\n            (:py:class:`Image`): The image.\n\n        Raises:\n            :py:class:`docker.errors.ImageNotFound`\n                If the image does not exist.\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def create_permission(self):\n        return Permission(\n            self.networkapi_url,\n            self.user,\n            self.password,\n            self.user_ldap)",
    "docstring": "Get an instance of permission services facade."
  },
  {
    "code": "def gnuplot_2d(x, y, filename, title='', x_label='', y_label=''):\n    _, ext = os.path.splitext(filename)\n    if ext != '.png':\n        filename += '.png'\n    gnuplot_cmds = \\\n    scr = _GnuplotScriptTemp(gnuplot_cmds)\n    data = _GnuplotDataTemp(x, y)\n    args_dict = {\n        'filename': filename,\n        'filename_data': data.name,\n        'title': title,\n        'x_label': x_label,\n        'y_label': y_label\n    }\n    gnuplot(scr.name, args_dict)",
    "docstring": "Function to produce a general 2D plot.\n\n    Args:\n        x (list): x points.\n        y (list): y points.\n        filename (str): Filename of the output image.\n        title (str): Title of the plot.  Default is '' (no title).\n        x_label (str): x-axis label.\n        y_label (str): y-axis label."
  },
  {
    "code": "def get_idle_pc_prop(self):\n        is_running = yield from self.is_running()\n        was_auto_started = False\n        if not is_running:\n            yield from self.start()\n            was_auto_started = True\n            yield from asyncio.sleep(20)\n        log.info('Router \"{name}\" [{id}] has started calculating Idle-PC values'.format(name=self._name, id=self._id))\n        begin = time.time()\n        idlepcs = yield from self._hypervisor.send('vm get_idle_pc_prop \"{}\" 0'.format(self._name))\n        log.info('Router \"{name}\" [{id}] has finished calculating Idle-PC values after {time:.4f} seconds'.format(name=self._name,\n                                                                                                                  id=self._id,\n                                                                                                                  time=time.time() - begin))\n        if was_auto_started:\n            yield from self.stop()\n        return idlepcs",
    "docstring": "Gets the idle PC proposals.\n        Takes 1000 measurements and records up to 10 idle PC proposals.\n        There is a 10ms wait between each measurement.\n\n        :returns: list of idle PC proposal"
  },
  {
    "code": "def Dump(self):\n        prefs_file = open(self.prefs_path, 'w')\n        for n in range(0,len(self.prefs)):\n            if len(list(self.prefs.items())[n]) > 1:\n                prefs_file.write(str(list(self.prefs.items())[n][0]) + ' = ' +\n                                 str(list(self.prefs.items())[n][1]) + '\\n')\n        prefs_file.close()",
    "docstring": "Dumps the current prefs to the preferences.txt file"
  },
  {
    "code": "def get_sum(qs, field):\n    sum_field = '%s__sum' % field\n    qty = qs.aggregate(Sum(field))[sum_field]\n    return qty if qty else 0",
    "docstring": "get sum for queryset.\n\n    ``qs``: queryset\n    ``field``: The field name to sum."
  },
  {
    "code": "def read_configs(__pkg: str, __name: str = 'config', *,\n                 local: bool = True) -> ConfigParser:\n    configs = get_configs(__pkg, __name)\n    if local:\n        localrc = path.abspath('.{}rc'.format(__pkg))\n        if path.exists(localrc):\n            configs.append(localrc)\n    cfg = ConfigParser(converters={\n        'datetime': parse_datetime,\n        'humandelta': parse_timedelta,\n        'timedelta': parse_delta,\n    })\n    cfg.read(configs, 'utf-8')\n    cfg.configs = configs\n    if 'NO_COLOUR' in environ or 'NO_COLOR' in environ:\n        cfg.colour = False\n    elif __pkg in cfg:\n        if 'colour' in cfg[__pkg]:\n            cfg.colour = cfg[__pkg].getboolean('colour')\n        if 'color' in cfg[__pkg]:\n            cfg.colour = cfg[__pkg].getboolean('color')\n    else:\n        cfg.colour = True\n    return cfg",
    "docstring": "Process configuration file stack.\n\n    We export the time parsing functionality of ``jnrbase`` as custom\n    converters for :class:`configparser.ConfigParser`:\n\n    ===================  ===========================================\n    Method               Function\n    ===================  ===========================================\n    ``.getdatetime()``   :func:`~jnrbase.iso_8601.parse_datetime`\n    ``.gethumantime()``  :func:`~jnrbase.human_time.parse_timedelta`\n    ``.gettimedelta()``  :func:`~jnrbase.iso_8601.parse_delta`\n    ===================  ===========================================\n\n    Args:\n        __pkg: Package name to use as base for config files\n        __name: File name to search for within config directories\n        local: Whether to include config files from current directory\n    Returns:\n        Parsed configuration files"
  },
  {
    "code": "def anonymize(self, value):\n        assert isinstance(value, bool)\n        if self._anonymize != value:\n            self.dirty = True\n            self._anonymize = value\n        return self.recipe",
    "docstring": "Should this recipe be anonymized"
  },
  {
    "code": "def _backup_bytes(target, offset, length):\n    click.echo('Backup {l} byes at position {offset} on file {file} to .bytes_backup'.format(\n        l=length, offset=offset, file=target))\n    with open(target, 'r+b') as f:\n        f.seek(offset)\n        with open(target + '.bytes_backup', 'w+b') as b:\n            for _ in xrange(length):\n                byte = f.read(1)\n                b.write(byte)\n            b.flush()\n        f.flush()",
    "docstring": "Read bytes from one file and write it to a\n        backup file with the .bytes_backup suffix"
  },
  {
    "code": "def getAmbientThreshold(self):\n    command = '$GO'\n    threshold = self.sendCommand(command)\n    if threshold[0] == 'NK':\n      return 0\n    else:\n      return float(threshold[1])/10",
    "docstring": "Returns the ambient temperature threshold in degrees Celcius, or 0 if no Threshold is set"
  },
  {
    "code": "def send_is_typing(self, peer_jid: str, is_typing: bool):\n        if self.is_group_jid(peer_jid):\n            return self._send_xmpp_element(chatting.OutgoingGroupIsTypingEvent(peer_jid, is_typing))\n        else:\n            return self._send_xmpp_element(chatting.OutgoingIsTypingEvent(peer_jid, is_typing))",
    "docstring": "Updates the 'is typing' status of the bot during a conversation.\n\n        :param peer_jid: The JID that the notification will be sent to\n        :param is_typing: If true, indicates that we're currently typing, or False otherwise."
  },
  {
    "code": "def parse_bytes(self, bytestr, isfinal=True):\n        with self._context():\n            self.filename = None\n            self.p.Parse(bytestr, isfinal)\n        return self._root",
    "docstring": "Parse a byte string. If the string is very large, split it in chuncks\n        and parse each chunk with isfinal=False, then parse an empty chunk\n        with isfinal=True."
  },
  {
    "code": "def observe(self, ob):\n        option = Option()\n        option.number = defines.OptionRegistry.OBSERVE.number\n        option.value = ob\n        self.del_option_by_number(defines.OptionRegistry.OBSERVE.number)\n        self.add_option(option)",
    "docstring": "Add the Observe option.\n\n        :param ob: observe count"
  },
  {
    "code": "def stage_import_from_filesystem(self, filepath):\n        schema = ImportSchema()\n        resp = self.service.post(self.base,\n                                 params={'path': filepath})\n        return self.service.decode(schema, resp)",
    "docstring": "Stage an import from a filesystem path.\n\n        :param filepath: Local filesystem path as string.\n        :return: :class:`imports.Import <imports.Import>` object"
  },
  {
    "code": "def get_notmuch_setting(self, section, key, fallback=None):\n        value = None\n        if section in self._notmuchconfig:\n            if key in self._notmuchconfig[section]:\n                value = self._notmuchconfig[section][key]\n        if value is None:\n            value = fallback\n        return value",
    "docstring": "look up config values from notmuch's config\n\n        :param section: key is in\n        :type section: str\n        :param key: key to look up\n        :type key: str\n        :param fallback: fallback returned if key is not present\n        :type fallback: str\n        :returns: config value with type as specified in the spec-file"
  },
  {
    "code": "def get_consumer_groups(self, consumer_group_id=None, names_only=False):\n        if consumer_group_id is None:\n            group_ids = self.get_children(\"/consumers\")\n        else:\n            group_ids = [consumer_group_id]\n        if names_only:\n            return {g_id: None for g_id in group_ids}\n        consumer_offsets = {}\n        for g_id in group_ids:\n            consumer_offsets[g_id] = self.get_group_offsets(g_id)\n        return consumer_offsets",
    "docstring": "Get information on all the available consumer-groups.\n\n        If names_only is False, only list of consumer-group ids are sent.\n        If names_only is True, Consumer group offset details are returned\n        for all consumer-groups or given consumer-group if given in dict\n        format as:-\n\n        {\n            'group-id':\n            {\n                'topic':\n                {\n                    'partition': offset-value,\n                    ...\n                    ...\n                }\n            }\n        }\n\n        :rtype: dict of consumer-group offset details"
  },
  {
    "code": "def backup_progress(self):\n        epoch_time = int(time.time() * 1000)\n        if self.deploymentType == 'Cloud':\n            url = self._options['server'] + '/rest/obm/1.0/getprogress?_=%i' % epoch_time\n        else:\n            logging.warning(\n                'This functionality is not available in Server version')\n            return None\n        r = self._session.get(\n            url, headers=self._options['headers'])\n        try:\n            return json.loads(r.text)\n        except Exception:\n            import defusedxml.ElementTree as etree\n            progress = {}\n            try:\n                root = etree.fromstring(r.text)\n            except etree.ParseError as pe:\n                logging.warning('Unable to find backup info.  You probably need to initiate a new backup. %s' % pe)\n                return None\n            for k in root.keys():\n                progress[k] = root.get(k)\n            return progress",
    "docstring": "Return status of cloud backup as a dict.\n\n        Is there a way to get progress for Server version?"
  },
  {
    "code": "def chmod_r(root: str, permission: int) -> None:\n    os.chmod(root, permission)\n    for dirpath, dirnames, filenames in os.walk(root):\n        for d in dirnames:\n            os.chmod(os.path.join(dirpath, d), permission)\n        for f in filenames:\n            os.chmod(os.path.join(dirpath, f), permission)",
    "docstring": "Recursive ``chmod``.\n\n    Args:\n        root: directory to walk down\n        permission: e.g. ``e.g. stat.S_IWUSR``"
  },
  {
    "code": "def requirements(filename):\n    with open(filename) as f:\n        return [x.strip() for x in f.readlines() if x.strip()]",
    "docstring": "Reads requirements from a file."
  },
  {
    "code": "def to_feature_reports(self, debug=False):\n        rest = self.to_string()\n        seq = 0\n        out = []\n        while rest:\n            this, rest = rest[:7], rest[7:]\n            if seq > 0 and rest:\n                if this != b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00':\n                    this += yubico_util.chr_byte(yubikey_defs.SLOT_WRITE_FLAG + seq)\n                    out.append(self._debug_string(debug, this))\n            else:\n                this += yubico_util.chr_byte(yubikey_defs.SLOT_WRITE_FLAG + seq)\n                out.append(self._debug_string(debug, this))\n            seq += 1\n        return out",
    "docstring": "Return the frame as an array of 8-byte parts, ready to be sent to a YubiKey."
  },
  {
    "code": "def run_step(self):\n        rewriter = StreamRewriter(self.context.iter_formatted_strings)\n        super().run_step(rewriter)",
    "docstring": "Do the file in-out rewrite."
  },
  {
    "code": "def publish(self, topic, data, defer=None):\n        if defer is None:\n            self.send(nsq.publish(topic, data))\n        else:\n            self.send(nsq.deferpublish(topic, data, defer))",
    "docstring": "Publish a message to the given topic over tcp.\n\n        :param topic: the topic to publish to\n\n        :param data: bytestring data to publish\n\n        :param defer: duration in milliseconds to defer before publishing\n            (requires nsq 0.3.6)"
  },
  {
    "code": "def ip_unnumbered(self, **kwargs):\n        kwargs['ip_donor_interface_name'] = kwargs.pop('donor_name')\n        kwargs['ip_donor_interface_type'] = kwargs.pop('donor_type')\n        kwargs['delete'] = kwargs.pop('delete', False)\n        callback = kwargs.pop('callback', self._callback)\n        valid_int_types = ['gigabitethernet', 'tengigabitethernet',\n                           'fortygigabitethernet', 'hundredgigabitethernet']\n        if kwargs['int_type'] not in valid_int_types:\n            raise ValueError('int_type must be one of: %s' %\n                             repr(valid_int_types))\n        unnumbered_type = self._ip_unnumbered_type(**kwargs)\n        unnumbered_name = self._ip_unnumbered_name(**kwargs)\n        if kwargs.pop('get', False):\n            return self._get_ip_unnumbered(unnumbered_type, unnumbered_name)\n        config = pynos.utilities.merge_xml(unnumbered_type, unnumbered_name)\n        return callback(config)",
    "docstring": "Configure an unnumbered interface.\n\n        Args:\n            int_type (str): Type of interface. (gigabitethernet,\n                 tengigabitethernet etc).\n            name (str): Name of interface id.\n                 (For interface: 1/0/5, 1/0/10 etc).\n            delete (bool): True is the IP address is added and False if its to\n                be deleted (True, False). Default value will be False if not\n                specified.\n            donor_type (str): Interface type of the donor interface.\n            donor_name (str): Interface name of the donor interface.\n            get (bool): Get config instead of editing config. (True, False)\n            callback (function): A function executed upon completion of the\n                 method.  The only parameter passed to `callback` will be the\n                 ``ElementTree`` `config`.\n\n        Returns:\n            Return value of `callback`.\n\n        Raises:\n            KeyError: if `int_type`, `name`, `donor_type`, or `donor_name` is\n                not passed.\n            ValueError: if `int_type`, `name`, `donor_type`, or `donor_name`\n                are invalid.\n\n        Examples:\n            >>> import pynos.device\n            >>> switches = ['10.24.39.230']\n            >>> auth = ('admin', 'password')\n            >>> for switch in switches:\n            ...    conn = (switch, '22')\n            ...    with pynos.device.Device(conn=conn, auth=auth) as dev:\n            ...        output = dev.interface.ip_address(int_type='loopback',\n            ...        name='1', ip_addr='4.4.4.4/32', rbridge_id='230')\n            ...        int_type = 'tengigabitethernet'\n            ...        name = '230/0/20'\n            ...        donor_type = 'loopback'\n            ...        donor_name = '1'\n            ...        output = dev.interface.disable_switchport(inter_type=\n            ...        int_type, inter=name)\n            ...        output = dev.interface.ip_unnumbered(int_type=int_type,\n            ...        name=name, donor_type=donor_type, donor_name=donor_name)\n            ...        output = dev.interface.ip_unnumbered(int_type=int_type,\n            ...        name=name, donor_type=donor_type, donor_name=donor_name,\n            ...        get=True)\n            ...        output = dev.interface.ip_unnumbered(int_type=int_type,\n            ...        name=name, donor_type=donor_type, donor_name=donor_name,\n            ...        delete=True)\n            ...        output = dev.interface.ip_address(int_type='loopback',\n            ...        name='1', ip_addr='4.4.4.4/32', rbridge_id='230',\n            ...        delete=True)\n            ...        output = dev.interface.ip_unnumbered(int_type='hodor',\n            ...        donor_name=donor_name, donor_type=donor_type, name=name)\n            ...        # doctest: +IGNORE_EXCEPTION_DETAIL\n            Traceback (most recent call last):\n            ValueError"
  },
  {
    "code": "def timestampFormat(self, timestampFormat):\n        if not isinstance(timestampFormat, str):\n            raise TypeError('not of type unicode')\n        self._timestampFormat = timestampFormat",
    "docstring": "Setter to _timestampFormat. Formatting string for conversion of timestamps to QtCore.QDateTime\n\n        Raises:\n            AssertionError: if timestampFormat is not of type unicode.\n\n        Args:\n            timestampFormat (unicode): assign timestampFormat to _timestampFormat.\n                Formatting string for conversion of timestamps to QtCore.QDateTime. Used in data method."
  },
  {
    "code": "def _merge_lib_dict(d1, d2):\n    for required, requirings in d2.items():\n        if required in d1:\n            d1[required].update(requirings)\n        else:\n            d1[required] = requirings\n    return None",
    "docstring": "Merges lib_dict `d2` into lib_dict `d1`"
  },
  {
    "code": "def add(self, dist):\n        new_path = (\n            dist.location not in self.paths and (\n                dist.location not in self.sitedirs or\n                dist.location == os.getcwd()\n            )\n        )\n        if new_path:\n            self.paths.append(dist.location)\n            self.dirty = True\n        Environment.add(self, dist)",
    "docstring": "Add `dist` to the distribution map"
  },
  {
    "code": "def delete_downloads():\n    shutil.rmtree(vtki.EXAMPLES_PATH)\n    os.makedirs(vtki.EXAMPLES_PATH)\n    return True",
    "docstring": "Delete all downloaded examples to free space or update the files"
  },
  {
    "code": "def data_size(metadata):\n    info = metadata['info']\n    if 'length' in info:\n        total_size = info['length']\n    else:\n        total_size = sum([f['length'] for f in info['files']])\n    return total_size",
    "docstring": "Calculate the size of a torrent based on parsed metadata."
  },
  {
    "code": "def snils(self) -> str:\n        numbers = []\n        control_codes = []\n        for i in range(0, 9):\n            numbers.append(self.random.randint(0, 9))\n        for i in range(9, 0, -1):\n            control_codes.append(numbers[9 - i] * i)\n        control_code = sum(control_codes)\n        code = ''.join(str(number) for number in numbers)\n        if control_code in (100, 101):\n            snils = code + '00'\n            return snils\n        if control_code < 100:\n            snils = code + str(control_code)\n            return snils\n        if control_code > 101:\n            control_code = control_code % 101\n            if control_code == 100:\n                control_code = 0\n            snils = code + '{:02}'.format(control_code)\n            return snils",
    "docstring": "Generate snils with special algorithm.\n\n        :return: SNILS.\n\n        :Example:\n            41917492600."
  },
  {
    "code": "def guess_encoding(request):\n    ctype = request.headers.get('content-type')\n    if not ctype:\n        LOGGER.warning(\"%s: no content-type; headers are %s\",\n                       request.url, request.headers)\n        return 'utf-8'\n    match = re.search(r'charset=([^ ;]*)(;| |$)', ctype)\n    if match:\n        return match[1]\n    if ctype.startswith('text/html'):\n        return 'iso-8859-1'\n    return 'utf-8'",
    "docstring": "Try to guess the encoding of a request without going through the slow chardet process"
  },
  {
    "code": "def walk(self, root=\"~/\"):\n        root = validate_type(root, *six.string_types)\n        directories = []\n        files = []\n        query_fd_path = root\n        if not query_fd_path.endswith(\"/\"):\n            query_fd_path += \"/\"\n        for fd_object in self.get_filedata(fd_path == query_fd_path):\n            if fd_object.get_type() == \"directory\":\n                directories.append(fd_object)\n            else:\n                files.append(fd_object)\n        yield (root, directories, files)\n        for directory in directories:\n            for dirpath, directories, files in self.walk(directory.get_full_path()):\n                yield (dirpath, directories, files)",
    "docstring": "Emulation of os.walk behavior against Device Cloud filedata store\n\n        This method will yield tuples in the form ``(dirpath, FileDataDirectory's, FileData's)``\n        recursively in pre-order (depth first from top down).\n\n        :param str root: The root path from which the search should commence.  By default, this\n            is the root directory for this device cloud account (~).\n        :return: Generator yielding 3-tuples of dirpath, directories, and files\n        :rtype: 3-tuple in form (dirpath, list of :class:`FileDataDirectory`, list of :class:`FileDataFile`)"
  },
  {
    "code": "def step(self, action):\n        if self.done:\n            raise ValueError('cannot step in a done environment! call `reset`')\n        self.controllers[0][:] = action\n        _LIB.Step(self._env)\n        reward = self._get_reward()\n        self.done = self._get_done()\n        info = self._get_info()\n        self._did_step(self.done)\n        if reward < self.reward_range[0]:\n            reward = self.reward_range[0]\n        elif reward > self.reward_range[1]:\n            reward = self.reward_range[1]\n        return self.screen, reward, self.done, info",
    "docstring": "Run one frame of the NES and return the relevant observation data.\n\n        Args:\n            action (byte): the bitmap determining which buttons to press\n\n        Returns:\n            a tuple of:\n            - state (np.ndarray): next frame as a result of the given action\n            - reward (float) : amount of reward returned after given action\n            - done (boolean): whether the episode has ended\n            - info (dict): contains auxiliary diagnostic information"
  },
  {
    "code": "def validate(self, require_all=True, scale='colors'):\n        super(self.__class__, self).validate()\n        required_attribs = ('data', 'scales', 'axes', 'marks')\n        for elem in required_attribs:\n            attr = getattr(self, elem)\n            if attr:\n                for entry in attr:\n                    entry.validate()\n                names = [a.name for a in attr]\n                if len(names) != len(set(names)):\n                    raise ValidationError(elem + ' has duplicate names')\n            elif require_all:\n                raise ValidationError(\n                    elem + ' must be defined for valid visualization')",
    "docstring": "Validate the visualization contents.\n\n        Parameters\n        ----------\n        require_all : boolean, default True\n            If True (default), then all fields ``data``, ``scales``,\n            ``axes``, and ``marks`` must be defined. The user is allowed to\n            disable this if the intent is to define the elements\n            client-side.\n\n        If the contents of the visualization are not valid Vega, then a\n        :class:`ValidationError` is raised."
  },
  {
    "code": "def get_qapp():\n    global app\n    app = QtGui.QApplication.instance()\n    if app is None:\n        app = QtGui.QApplication([], QtGui.QApplication.GuiClient)\n    return app",
    "docstring": "Return an instance of QApplication. Creates one if neccessary.\n\n    :returns: a QApplication instance\n    :rtype: QApplication\n    :raises: None"
  },
  {
    "code": "def get_handle():\n    global __handle__\n    if not __handle__:\n        __handle__ = FT_Library()\n        error = FT_Init_FreeType(byref(__handle__))\n        if error:\n            raise RuntimeError(hex(error))\n    return __handle__",
    "docstring": "Get unique FT_Library handle"
  },
  {
    "code": "def runner_argspec(module=''):\n    run_ = salt.runner.Runner(__opts__)\n    return salt.utils.args.argspec_report(run_.functions, module)",
    "docstring": "Return the argument specification of functions in Salt runner\n    modules.\n\n    .. versionadded:: 2015.5.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' sys.runner_argspec state\n        salt '*' sys.runner_argspec http\n        salt '*' sys.runner_argspec\n\n    Runner names can be specified as globs.\n\n    .. code-block:: bash\n\n        salt '*' sys.runner_argspec 'winrepo.*'"
  },
  {
    "code": "def train_step(self, Xi, yi, **fit_params):\n        step_accumulator = self.get_train_step_accumulator()\n        def step_fn():\n            step = self.train_step_single(Xi, yi, **fit_params)\n            step_accumulator.store_step(step)\n            return step['loss']\n        self.optimizer_.step(step_fn)\n        return step_accumulator.get_step()",
    "docstring": "Prepares a loss function callable and pass it to the optimizer,\n        hence performing one optimization step.\n\n        Loss function callable as required by some optimizers (and accepted by\n        all of them):\n        https://pytorch.org/docs/master/optim.html#optimizer-step-closure\n\n        The module is set to be in train mode (e.g. dropout is\n        applied).\n\n        Parameters\n        ----------\n        Xi : input data\n          A batch of the input data.\n\n        yi : target data\n          A batch of the target data.\n\n        **fit_params : dict\n          Additional parameters passed to the ``forward`` method of\n          the module and to the train_split call."
  },
  {
    "code": "def partition_pair(bif_point):\n    n = float(sum(1 for _ in bif_point.children[0].ipreorder()))\n    m = float(sum(1 for _ in bif_point.children[1].ipreorder()))\n    return (n, m)",
    "docstring": "Calculate the partition pairs at a bifurcation point\n\n    The number of nodes in each child tree is counted. The partition\n    pairs is the number of bifurcations in the two daughter subtrees\n    at each branch point."
  },
  {
    "code": "def _gather_beams(nested, beam_indices, batch_size, new_beam_size):\n  batch_pos = tf.range(batch_size * new_beam_size) // new_beam_size\n  batch_pos = tf.reshape(batch_pos, [batch_size, new_beam_size])\n  coordinates = tf.stack([batch_pos, beam_indices], axis=2)\n  return nest.map_structure(\n      lambda state: tf.gather_nd(state, coordinates), nested)",
    "docstring": "Gather beams from nested structure of tensors.\n\n  Each tensor in nested represents a batch of beams, where beam refers to a\n  single search state (beam search involves searching through multiple states\n  in parallel).\n\n  This function is used to gather the top beams, specified by\n  beam_indices, from the nested tensors.\n\n  Args:\n    nested: Nested structure (tensor, list, tuple or dict) containing tensors\n      with shape [batch_size, beam_size, ...].\n    beam_indices: int32 tensor with shape [batch_size, new_beam_size]. Each\n     value in beam_indices must be between [0, beam_size), and are not\n     necessarily unique.\n    batch_size: int size of batch\n    new_beam_size: int number of beams to be pulled from the nested tensors.\n\n  Returns:\n    Nested structure containing tensors with shape\n      [batch_size, new_beam_size, ...]"
  },
  {
    "code": "def set_waypoint_quota(self, waypoint_quota):\n        if self.get_waypoint_quota_metadata().is_read_only():\n            raise NoAccess()\n        if not self.my_osid_object_form._is_valid_cardinal(waypoint_quota,\n                                                           self.get_waypoint_quota_metadata()):\n            raise InvalidArgument()\n        self.my_osid_object_form._my_map['waypointQuota'] = waypoint_quota",
    "docstring": "how many waypoint questions need to be answered correctly"
  },
  {
    "code": "def _decode_value(self, value):\n        if isinstance(value, (int, float, str, bool, datetime)):\n            return value\n        elif isinstance(value, list):\n            return [self._decode_value(item) for item in value]\n        elif isinstance(value, dict):\n            result = {}\n            for key, item in value.items():\n                result[key] = self._decode_value(item)\n            return result\n        elif isinstance(value, ObjectId):\n            if self._gridfs.exists({\"_id\": value}):\n                return pickle.loads(self._gridfs.get(value).read())\n            else:\n                raise DataStoreGridfsIdInvalid()\n        else:\n            raise DataStoreDecodeUnknownType()",
    "docstring": "Decodes the value by turning any binary data back into Python objects.\n\n        The method searches for ObjectId values, loads the associated binary data from\n        GridFS and returns the decoded Python object.\n\n        Args:\n            value (object): The value that should be decoded.\n\n        Raises:\n            DataStoreDecodingError: An ObjectId was found but the id is not a valid\n                GridFS id.\n            DataStoreDecodeUnknownType: The type of the specified value is unknown.\n\n        Returns:\n            object: The decoded value as a valid Python object."
  },
  {
    "code": "def _find_pivot_addr(self, index):\n        if not self.addresses or index.start == 0:\n            return CharAddress('', self.tree, 'text', -1)\n        if index.start > len(self.addresses):\n            return self.addresses[-1]\n        return self.addresses[index.start]",
    "docstring": "Inserting by slicing can lead into situation where no addresses are\n        selected. In that case a pivot address has to be chosen so we know\n        where to add characters."
  },
  {
    "code": "def calc_qbgz_v1(self):\n    con = self.parameters.control.fastaccess\n    flu = self.sequences.fluxes.fastaccess\n    sta = self.sequences.states.fastaccess\n    sta.qbgz = 0.\n    for k in range(con.nhru):\n        if con.lnk[k] == SEE:\n            sta.qbgz += con.fhru[k]*(flu.nkor[k]-flu.evi[k])\n        elif con.lnk[k] not in (WASSER, FLUSS, VERS):\n            sta.qbgz += con.fhru[k]*flu.qbb[k]",
    "docstring": "Aggregate the amount of base flow released by all \"soil type\" HRUs\n    and the \"net precipitation\" above water areas of type |SEE|.\n\n    Water areas of type |SEE| are assumed to be directly connected with\n    groundwater, but not with the stream network.  This is modelled by\n    adding their (positive or negative) \"net input\" (|NKor|-|EvI|) to the\n    \"percolation output\" of the soil containing HRUs.\n\n    Required control parameters:\n      |Lnk|\n      |NHRU|\n      |FHRU|\n\n    Required flux sequences:\n      |QBB|\n      |NKor|\n      |EvI|\n\n    Calculated state sequence:\n      |QBGZ|\n\n    Basic equation:\n       :math:`QBGZ = \\\\Sigma(FHRU \\\\cdot QBB) +\n       \\\\Sigma(FHRU \\\\cdot (NKor_{SEE}-EvI_{SEE}))`\n\n    Examples:\n\n        The first example shows that |QBGZ| is the area weighted sum of\n        |QBB| from \"soil type\" HRUs like arable land (|ACKER|) and of\n        |NKor|-|EvI| from water areas of type |SEE|.  All other water\n        areas (|WASSER| and |FLUSS|) and also sealed surfaces (|VERS|)\n        have no impact on |QBGZ|:\n\n        >>> from hydpy.models.lland import *\n        >>> parameterstep()\n        >>> nhru(6)\n        >>> lnk(ACKER, ACKER, VERS, WASSER, FLUSS, SEE)\n        >>> fhru(0.1, 0.2, 0.1, 0.1, 0.1, 0.4)\n        >>> fluxes.qbb = 2., 4.0, 300.0, 300.0, 300.0, 300.0\n        >>> fluxes.nkor = 200.0, 200.0, 200.0, 200.0, 200.0, 20.0\n        >>> fluxes.evi = 100.0, 100.0, 100.0, 100.0, 100.0, 10.0\n        >>> model.calc_qbgz_v1()\n        >>> states.qbgz\n        qbgz(5.0)\n\n        The second example shows that large evaporation values above a\n        HRU of type |SEE| can result in negative values of |QBGZ|:\n\n        >>> fluxes.evi[5] = 30\n        >>> model.calc_qbgz_v1()\n        >>> states.qbgz\n        qbgz(-3.0)"
  },
  {
    "code": "def apply(self, axes=\"gca\"):\n        if axes == \"gca\": axes = _pylab.gca()\n        self.reset()\n        lines = axes.get_lines()\n        for l in lines:\n            l.set_color(self.get_line_color(1))\n            l.set_mfc(self.get_face_color(1))\n            l.set_marker(self.get_marker(1))\n            l.set_mec(self.get_edge_color(1))\n            l.set_linestyle(self.get_linestyle(1))\n        _pylab.draw()",
    "docstring": "Applies the style cycle to the lines in the axes specified"
  },
  {
    "code": "def victims(self, filters=None, params=None):\n        victim = self._tcex.ti.victim(None)\n        for v in self.tc_requests.victims_from_tag(\n            victim, self.name, filters=filters, params=params\n        ):\n            yield v",
    "docstring": "Gets all victims from a tag."
  },
  {
    "code": "def stage(self, name):\n        for stage in self.stages():\n            if stage.data.name == name:\n                return stage",
    "docstring": "Method for searching specific stage by it's name.\n\n        :param name: name of the stage to search.\n        :return: found stage or None.\n        :rtype: yagocd.resources.stage.StageInstance"
  },
  {
    "code": "def get_value(self, attribute, section, default=\"\"):\n        if not self.attribute_exists(attribute, section):\n            return default\n        if attribute in self.__sections[section]:\n            value = self.__sections[section][attribute]\n        elif foundations.namespace.set_namespace(section, attribute) in self.__sections[section]:\n            value = self.__sections[section][foundations.namespace.set_namespace(section, attribute)]\n        LOGGER.debug(\"> Attribute: '{0}', value: '{1}'.\".format(attribute, value))\n        return value",
    "docstring": "Returns requested attribute value.\n\n        Usage::\n\n            >>> content = [\"[Section A]\\\\n\", \"; Comment.\\\\n\", \"Attribute 1 = \\\\\"Value A\\\\\"\\\\n\", \"\\\\n\", \\\n\"[Section B]\\\\n\", \"Attribute 2 = \\\\\"Value B\\\\\"\\\\n\"]\n            >>> sections_file_parser = SectionsFileParser()\n            >>> sections_file_parser.content = content\n            >>> sections_file_parser.parse()\n            <foundations.parsers.SectionsFileParser object at 0x679302423>\n            >>> sections_file_parser.get_value(\"Attribute 1\", \"Section A\")\n            u'Value A'\n\n        :param attribute: Attribute name.\n        :type attribute: unicode\n        :param section: Section containing the searched attribute.\n        :type section: unicode\n        :param default: Default return value.\n        :type default: object\n        :return: Attribute value.\n        :rtype: unicode"
  },
  {
    "code": "def export_survey_participant_list(self, instrument, event=None, format='json'):\n        pl = self.__basepl(content='participantList', format=format)\n        pl['instrument'] = instrument\n        if event:\n            pl['event'] = event\n        return self._call_api(pl, 'exp_survey_participant_list')",
    "docstring": "Export the Survey Participant List\n\n        Notes\n        -----\n        The passed instrument must be set up as a survey instrument.\n\n        Parameters\n        ----------\n        instrument: str\n            Name of instrument as seen in second column of Data Dictionary.\n        event: str\n            Unique event name, only used in longitudinal projects\n        format: (json, xml, csv), json by default\n            Format of returned data"
  },
  {
    "code": "def create_schema(self, schema):\n        if schema not in self.schemas:\n            sql = \"CREATE SCHEMA \" + schema\n            self.execute(sql)",
    "docstring": "Create specified schema if it does not already exist"
  },
  {
    "code": "def _add_id_or_name(flat_path, element_pb, empty_allowed):\n    id_ = element_pb.id\n    name = element_pb.name\n    if id_ == 0:\n        if name == u\"\":\n            if not empty_allowed:\n                raise ValueError(_EMPTY_ELEMENT)\n        else:\n            flat_path.append(name)\n    else:\n        if name == u\"\":\n            flat_path.append(id_)\n        else:\n            msg = _BAD_ELEMENT_TEMPLATE.format(id_, name)\n            raise ValueError(msg)",
    "docstring": "Add the ID or name from an element to a list.\n\n    :type flat_path: list\n    :param flat_path: List of accumulated path parts.\n\n    :type element_pb: :class:`._app_engine_key_pb2.Path.Element`\n    :param element_pb: The element containing ID or name.\n\n    :type empty_allowed: bool\n    :param empty_allowed: Indicates if neither ID or name need be set. If\n                          :data:`False`, then **exactly** one of them must be.\n\n    :raises: :exc:`ValueError` if 0 or 2 of ID/name are set (unless\n             ``empty_allowed=True`` and 0 are set)."
  },
  {
    "code": "def shutdown(self):\n        with self._lock:\n            for cid in list(self.connections.keys()):\n                if self.connections[cid].executing:\n                    raise ConnectionBusyError(cid)\n                if self.connections[cid].locked:\n                    self.connections[cid].free()\n                self.connections[cid].close()\n                del self.connections[cid]",
    "docstring": "Forcefully shutdown the entire pool, closing all non-executing\n        connections.\n\n        :raises: ConnectionBusyError"
  },
  {
    "code": "def normalize(self, body):\n        resource = body['data']\n        data = {'rtype': resource['type']}\n        if 'attributes' in resource:\n            attributes = resource['attributes']\n            attributes = self._normalize_attributes(attributes)\n            data.update(attributes)\n        if 'relationships' in resource:\n            relationships = resource['relationships']\n            relationships = self._normalize_relationships(relationships)\n            data.update(relationships)\n        if resource.get('id'):\n            data['rid'] = resource['id']\n        return data",
    "docstring": "Invoke the JSON API normalizer\n\n        Perform the following:\n\n            * add the type as a rtype property\n            * flatten the payload\n            * add the id as a rid property ONLY if present\n\n        We don't need to vet the inputs much because the Parser\n        has already done all the work.\n\n        :param body:\n            the already vetted & parsed payload\n        :return:\n            normalized dict"
  },
  {
    "code": "def find_deck_spawns(provider: Provider, prod: bool=True) -> Iterable[str]:\n    pa_params = param_query(provider.network)\n    if isinstance(provider, RpcNode):\n        if prod:\n            decks = (i[\"txid\"] for i in provider.listtransactions(\"PAPROD\"))\n        else:\n            decks = (i[\"txid\"] for i in provider.listtransactions(\"PATEST\"))\n    if isinstance(provider, Cryptoid) or isinstance(provider, Explorer):\n        if prod:\n            decks = (i for i in provider.listtransactions(pa_params.P2TH_addr))\n        else:\n            decks = (i for i in provider.listtransactions(pa_params.test_P2TH_addr))\n    return decks",
    "docstring": "find deck spawn transactions via Provider,\n    it requires that Deck spawn P2TH were imported in local node or\n    that remote API knows about P2TH address."
  },
  {
    "code": "def labels(self, hs_dims=None, prune=False):\n        if self.ca_as_0th:\n            labels = self._cube.labels(include_transforms_for_dims=hs_dims)[1:]\n        else:\n            labels = self._cube.labels(include_transforms_for_dims=hs_dims)[-2:]\n        if not prune:\n            return labels\n        def prune_dimension_labels(labels, prune_indices):\n            labels = [label for label, prune in zip(labels, prune_indices) if not prune]\n            return labels\n        labels = [\n            prune_dimension_labels(dim_labels, dim_prune_inds)\n            for dim_labels, dim_prune_inds in zip(labels, self._prune_indices(hs_dims))\n        ]\n        return labels",
    "docstring": "Get labels for the cube slice, and perform pruning by slice."
  },
  {
    "code": "def rollforward(self, date):\n        if self.onOffset(date):\n            return date\n        else:\n            return date + QuarterEnd(month=self.month)",
    "docstring": "Roll date forward to nearest end of quarter"
  },
  {
    "code": "def _expression_to_sql(expression, node, context):\n    _expression_transformers = {\n        expressions.LocalField: _transform_local_field_to_expression,\n        expressions.Variable: _transform_variable_to_expression,\n        expressions.Literal: _transform_literal_to_expression,\n        expressions.BinaryComposition: _transform_binary_composition_to_expression,\n    }\n    expression_type = type(expression)\n    if expression_type not in _expression_transformers:\n        raise NotImplementedError(\n            u'Unsupported compiler expression \"{}\" of type \"{}\" cannot be converted to SQL '\n            u'expression.'.format(expression, type(expression)))\n    return _expression_transformers[expression_type](expression, node, context)",
    "docstring": "Recursively transform a Filter block predicate to its SQLAlchemy expression representation.\n\n    Args:\n        expression: expression, the compiler expression to transform.\n        node: SqlNode, the SqlNode the expression applies to.\n        context: CompilationContext, global compilation state and metadata.\n\n    Returns:\n        Expression, SQLAlchemy Expression equivalent to the passed compiler expression."
  },
  {
    "code": "def convert_to_xml(cls, degrees):\n        if degrees < 0.0:\n            degrees %= -360\n            degrees += 360\n        elif degrees > 0.0:\n            degrees %= 360\n        return str(int(round(degrees * cls.DEGREE_INCREMENTS)))",
    "docstring": "Convert signed angle float like -427.42 to int 60000 per degree.\n\n        Value is normalized to a positive value less than 360 degrees."
  },
  {
    "code": "def count_delayed_jobs(cls, names):\n        return sum([queue.delayed.zcard() for queue in cls.get_all(names)])",
    "docstring": "Return the number of all delayed jobs in queues with the given names"
  },
  {
    "code": "def log_likelihood(self):\n        if self._log_likelihood is None:\n            self._log_likelihood = logpdf(x=self.y, cov=self.S)\n        return self._log_likelihood",
    "docstring": "log-likelihood of the last measurement."
  },
  {
    "code": "def list():\n    kbs = []\n    ret = _pshell_json('Get-HotFix | Select HotFixID')\n    for item in ret:\n        kbs.append(item['HotFixID'])\n    return kbs",
    "docstring": "Get a list of updates installed on the machine\n\n    Returns:\n        list: A list of installed updates\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' wusa.list"
  },
  {
    "code": "def _get_match(self, prefix):\n        if _cpr_response_re.match(prefix):\n            return Keys.CPRResponse\n        elif _mouse_event_re.match(prefix):\n            return Keys.Vt100MouseEvent\n        try:\n            return ANSI_SEQUENCES[prefix]\n        except KeyError:\n            return None",
    "docstring": "Return the key that maps to this prefix."
  },
  {
    "code": "def subclass_exception(name, parents, module, attached_to=None):\n    class_dict = {'__module__': module}\n    if attached_to is not None:\n        def __reduce__(self):\n            return (unpickle_inner_exception, (attached_to, name), self.args)\n        def __setstate__(self, args):\n            self.args = args\n        class_dict['__reduce__'] = __reduce__\n        class_dict['__setstate__'] = __setstate__\n    return type(name, parents, class_dict)",
    "docstring": "Create exception subclass.\n\n    If 'attached_to' is supplied, the exception will be created in a way that\n    allows it to be pickled, assuming the returned exception class will be added\n    as an attribute to the 'attached_to' class."
  },
  {
    "code": "def parse_model_group(path, group):\n    context = FilePathContext(path)\n    for reaction_id in group.get('reactions', []):\n        yield reaction_id\n    for reaction_id in parse_model_group_list(\n            context, group.get('groups', [])):\n        yield reaction_id",
    "docstring": "Parse a structured model group as obtained from a YAML file\n\n    Path can be given as a string or a context."
  },
  {
    "code": "def on_selection_changed(self, sel):\n        m, self.editing_iter = sel.get_selected()\n        if self.editing_iter:\n            self.editing_model = m[self.editing_iter][0]\n            self.show_curr_model_view(self.editing_model, False)\n        else: self.view.remove_currency_view()\n        return",
    "docstring": "The user changed selection"
  },
  {
    "code": "def delay(self, params, now=None):\n        if now is None:\n            now = time.time()\n        if not self.last:\n            self.last = now\n        elif now < self.last:\n            now = self.last\n        leaked = now - self.last\n        self.last = now\n        self.level = max(self.level - leaked, 0)\n        difference = self.level + self.limit.cost - self.limit.unit_value\n        if difference >= self.eps:\n            self.next = now + difference\n            return difference\n        self.level += self.limit.cost\n        self.next = now\n        return None",
    "docstring": "Determine delay until next request."
  },
  {
    "code": "def NormalizePath(path, sep=\"/\"):\n  if not path:\n    return sep\n  path = SmartUnicode(path)\n  path_list = path.split(sep)\n  if path_list[0] in [\".\", \"..\", \"\"]:\n    path_list.pop(0)\n  i = 0\n  while True:\n    list_len = len(path_list)\n    for i in range(i, len(path_list)):\n      if path_list[i] == \".\" or not path_list[i]:\n        path_list.pop(i)\n        break\n      elif path_list[i] == \"..\":\n        path_list.pop(i)\n        if (i == 1 and path_list[0]) or i > 1:\n          i -= 1\n          path_list.pop(i)\n        break\n    if len(path_list) == list_len:\n      return sep + sep.join(path_list)",
    "docstring": "A sane implementation of os.path.normpath.\n\n  The standard implementation treats leading / and // as different leading to\n  incorrect normal forms.\n\n  NOTE: Its ok to use a relative path here (without leading /) but any /../ will\n  still be removed anchoring the path at the top level (e.g. foo/../../../../bar\n  => bar).\n\n  Args:\n     path: The path to normalize.\n     sep: Separator used.\n\n  Returns:\n     A normalized path. In this context normalized means that all input paths\n     that would result in the system opening the same physical file will produce\n     the same normalized path."
  },
  {
    "code": "def get_child_ids(self):\n        if self.has_magic_children():\n            if self._child_parts is None:\n                self.generate_children()\n            child_ids = list()\n            for part in self._child_parts:\n                child_ids.append(part.get_id())\n            return IdList(child_ids,\n                          runtime=self.my_osid_object._runtime,\n                          proxy=self.my_osid_object._runtime)\n        raise IllegalState()",
    "docstring": "gets the ids for the child parts"
  },
  {
    "code": "def tox_configure(config):\n    if 'TRAVIS' not in os.environ:\n        return\n    ini = config._cfg\n    if 'TOXENV' not in os.environ and not config.option.env:\n        envlist = detect_envlist(ini)\n        undeclared = set(envlist) - set(config.envconfigs)\n        if undeclared:\n            print('Matching undeclared envs is deprecated. Be sure all the '\n                  'envs that Tox should run are declared in the tox config.',\n                  file=sys.stderr)\n            autogen_envconfigs(config, undeclared)\n        config.envlist = envlist\n    if override_ignore_outcome(ini):\n        for envconfig in config.envconfigs.values():\n            envconfig.ignore_outcome = False\n    if config.option.travis_after:\n        print('The after all feature has been deprecated. Check out Travis\\' '\n              'build stages, which are a better solution. '\n              'See https://tox-travis.readthedocs.io/en/stable/after.html '\n              'for more details.', file=sys.stderr)",
    "docstring": "Check for the presence of the added options."
  },
  {
    "code": "def remove(self, row):\n        self._rows.remove(row)\n        self._deleted_rows.add(row)",
    "docstring": "Removes the row from the list."
  },
  {
    "code": "def process(self, job):\n        sandbox = self.sandboxes.pop(0)\n        try:\n            with Worker.sandbox(sandbox):\n                job.sandbox = sandbox\n                job.process()\n        finally:\n            self.greenlets.pop(job.jid, None)\n            self.sandboxes.append(sandbox)",
    "docstring": "Process a job"
  },
  {
    "code": "def cat_data(data_kw):\n    if len(data_kw) == 0: return pd.DataFrame()\n    return pd.DataFrame(pd.concat([\n        data.assign(ticker=ticker).set_index('ticker', append=True)\n            .unstack('ticker').swaplevel(0, 1, axis=1)\n        for ticker, data in data_kw.items()\n    ], axis=1))",
    "docstring": "Concatenate data with ticker as sub column index\n\n    Args:\n        data_kw: key = ticker, value = pd.DataFrame\n\n    Returns:\n        pd.DataFrame\n\n    Examples:\n        >>> start = '2018-09-10T10:10:00'\n        >>> tz = 'Australia/Sydney'\n        >>> idx = pd.date_range(start=start, periods=6, freq='min').tz_localize(tz)\n        >>> close_1 = [31.08, 31.10, 31.11, 31.07, 31.04, 31.04]\n        >>> vol_1 = [10166, 69981, 14343, 10096, 11506, 9718]\n        >>> d1 = pd.DataFrame(dict(price=close_1, volume=vol_1), index=idx)\n        >>> close_2 = [70.81, 70.78, 70.85, 70.79, 70.79, 70.79]\n        >>> vol_2 = [4749, 6762, 4908, 2002, 9170, 9791]\n        >>> d2 = pd.DataFrame(dict(price=close_2, volume=vol_2), index=idx)\n        >>> sample = cat_data({'BHP AU': d1, 'RIO AU': d2})\n        >>> sample.columns\n        MultiIndex(levels=[['BHP AU', 'RIO AU'], ['price', 'volume']],\n                   codes=[[0, 0, 1, 1], [0, 1, 0, 1]],\n                   names=['ticker', None])\n        >>> r = sample.transpose().iloc[:, :2]\n        >>> r.index.names = (None, None)\n        >>> r\n                       2018-09-10 10:10:00+10:00  2018-09-10 10:11:00+10:00\n        BHP AU price                       31.08                      31.10\n               volume                  10,166.00                  69,981.00\n        RIO AU price                       70.81                      70.78\n               volume                   4,749.00                   6,762.00"
  },
  {
    "code": "def lemmatize(self):\n        _lemmatizer = PatternParserLemmatizer(tokenizer=NLTKPunktTokenizer())\n        _raw = \" \".join(self) + \".\"\n        _lemmas = _lemmatizer.lemmatize(_raw)\n        return self.__class__([Word(l, t) for l, t in _lemmas])",
    "docstring": "Return the lemma of each word in this WordList.\n\n        Currently using NLTKPunktTokenizer() for all lemmatization\n        tasks. This might cause slightly different tokenization results\n        compared to the TextBlob.words property."
  },
  {
    "code": "def get_create_batch_env_fun(batch_env_fn, time_limit):\n  def create_env_fun(game_name=None, sticky_actions=None):\n    del game_name, sticky_actions\n    batch_env = batch_env_fn(in_graph=False)\n    batch_env = ResizeBatchObservation(batch_env)\n    batch_env = DopamineBatchEnv(batch_env, max_episode_steps=time_limit)\n    return batch_env\n  return create_env_fun",
    "docstring": "Factory for dopamine environment initialization function.\n\n  Args:\n    batch_env_fn: function(in_graph: bool) -> batch environment.\n    time_limit: time steps limit for environment.\n\n  Returns:\n    function (with optional, unused parameters) initializing environment."
  },
  {
    "code": "def name(self):\n        python = self._python\n        if self._python.startswith('pypy'):\n            python = python[2:]\n        return environment.get_env_name(self.tool_name, python, self._requirements)",
    "docstring": "Get a name to uniquely identify this environment."
  },
  {
    "code": "def context(self, id):\n        if id not in self.circuits:\n            self.circuits[id] = self.factory(self.clock, self.log.getChild(id),\n                                             self.error_types, self.maxfail,\n                                             self.reset_timeout,\n                                             self.time_unit,\n                                             backoff_cap=self.backoff_cap,\n                                             with_jitter=self.with_jitter)\n        return self.circuits[id]",
    "docstring": "Return a circuit breaker for the given ID."
  },
  {
    "code": "def id(opts):\n    r = salt.utils.http.query(opts['proxy']['url']+'id', decode_type='json', decode=True)\n    return r['dict']['id'].encode('ascii', 'ignore')",
    "docstring": "Return a unique ID for this proxy minion.  This ID MUST NOT CHANGE.\n    If it changes while the proxy is running the salt-master will get\n    really confused and may stop talking to this minion"
  },
  {
    "code": "def down(self, migration_id):\n        if not self.check_directory():\n            return\n        for migration in self.get_migrations_to_down(migration_id):\n            logger.info('Rollback migration %s' % migration.filename)\n            migration_module = self.load_migration_file(migration.filename)\n            if hasattr(migration_module, 'down'):\n                migration_module.down(self.db)\n            else:\n                logger.info('No down method on %s' % migration.filename)\n            self.collection.remove({'filename': migration.filename})",
    "docstring": "Rollback to migration."
  },
  {
    "code": "def nt_yielder(self, graph, size):\n        for grp in self.make_batch(size, graph):\n            tmpg = Graph()\n            tmpg += grp\n            yield (len(tmpg), tmpg.serialize(format='nt'))",
    "docstring": "Yield n sized ntriples for a given graph.\n        Used in sending chunks of data to the VIVO\n        SPARQL API."
  },
  {
    "code": "def interpolate(self):\n        self.latitude = self._interp(self.lat_tiepoint)\n        self.longitude = self._interp(self.lon_tiepoint)\n        return self.latitude, self.longitude",
    "docstring": "Do the interpolation and return resulting longitudes and latitudes."
  },
  {
    "code": "def encodeSequence(seq_vec, vocab, neutral_vocab, maxlen=None,\n                   seq_align=\"start\", pad_value=\"N\", encode_type=\"one_hot\"):\n    if isinstance(neutral_vocab, str):\n        neutral_vocab = [neutral_vocab]\n    if isinstance(seq_vec, str):\n        raise ValueError(\"seq_vec should be an iterable returning \" +\n                         \"strings not a string itself\")\n    assert len(vocab[0]) == len(pad_value)\n    assert pad_value in neutral_vocab\n    assert encode_type in [\"one_hot\", \"token\"]\n    seq_vec = pad_sequences(seq_vec, maxlen=maxlen,\n                            align=seq_align, value=pad_value)\n    if encode_type == \"one_hot\":\n        arr_list = [token2one_hot(tokenize(seq, vocab, neutral_vocab), len(vocab))\n                    for i, seq in enumerate(seq_vec)]\n    elif encode_type == \"token\":\n        arr_list = [1 + np.array(tokenize(seq, vocab, neutral_vocab)) for seq in seq_vec]\n    return np.stack(arr_list)",
    "docstring": "Convert a list of genetic sequences into one-hot-encoded array.\n\n    # Arguments\n       seq_vec: list of strings (genetic sequences)\n       vocab: list of chars: List of \"words\" to use as the vocabulary. Can be strings of length>0,\n            but all need to have the same length. For DNA, this is: [\"A\", \"C\", \"G\", \"T\"].\n       neutral_vocab: list of chars: Values used to pad the sequence or represent unknown-values. For DNA, this is: [\"N\"].\n       maxlen: int or None,\n            Should we trim (subset) the resulting sequence. If None don't trim.\n            Note that trims wrt the align parameter.\n            It should be smaller than the longest sequence.\n       seq_align: character; 'end' or 'start'\n            To which end should we align sequences?\n       encode_type: \"one_hot\" or \"token\". \"token\" represents each vocab element as a positive integer from 1 to len(vocab) + 1.\n                  neutral_vocab is represented with 0.\n\n    # Returns\n        Array with shape for encode_type:\n\n            - \"one_hot\": `(len(seq_vec), maxlen, len(vocab))`\n            - \"token\": `(len(seq_vec), maxlen)`\n\n        If `maxlen=None`, it gets the value of the longest sequence length from `seq_vec`."
  },
  {
    "code": "def __on_message(self, msg):\n        msgtype = msg['type']\n        msgfrom = msg['from']\n        if msgtype == 'groupchat':\n            if self._nick == msgfrom.resource:\n                return\n        elif msgtype not in ('normal', 'chat'):\n            return\n        self.__callback(msg)",
    "docstring": "XMPP message received"
  },
  {
    "code": "def make_token(cls, ephemeral_token: 'RedisEphemeralTokens') -> str:\n        value = ephemeral_token.key\n        if ephemeral_token.scope:\n            value += ''.join(ephemeral_token.scope)\n        return get_hmac(cls.KEY_SALT + ephemeral_token.salt, value)[::2]",
    "docstring": "Returns a token to be used x number of times to allow a user account to access\n        certain resource."
  },
  {
    "code": "def _get_marker_output(self, asset_quantities, metadata):\n        payload = openassets.protocol.MarkerOutput(asset_quantities, metadata).serialize_payload()\n        script = openassets.protocol.MarkerOutput.build_script(payload)\n        return bitcoin.core.CTxOut(0, script)",
    "docstring": "Creates a marker output.\n\n        :param list[int] asset_quantities: The asset quantity list.\n        :param bytes metadata: The metadata contained in the output.\n        :return: An object representing the marker output.\n        :rtype: TransactionOutput"
  },
  {
    "code": "def return_single_real_id_base(dbpath, set_object, object_id):\n    engine = create_engine('sqlite:////' + dbpath)\n    session_cl = sessionmaker(bind=engine)\n    session = session_cl()\n    tmp_object = session.query(set_object).get(object_id)\n    session.close()\n    return tmp_object.real_id",
    "docstring": "Generic function which returns a real_id string of an object specified by the object_id\n\n    Parameters\n    ----------\n    dbpath : string, path to SQLite database file\n    set_object : object (either TestSet or TrainSet) which is stored in the database\n    object_id : int, id of object in database\n\n    Returns\n    -------\n    real_id : string"
  },
  {
    "code": "def log_url (self, url_data, priority=None):\n        self.xml_starttag(u'url')\n        self.xml_tag(u'loc', url_data.url)\n        if url_data.modified:\n            self.xml_tag(u'lastmod', self.format_modified(url_data.modified, sep=\"T\"))\n        self.xml_tag(u'changefreq', self.frequency)\n        self.xml_tag(u'priority', \"%.2f\" % priority)\n        self.xml_endtag(u'url')\n        self.flush()",
    "docstring": "Log URL data in sitemap format."
  },
  {
    "code": "def _get_bufsize_linux(iface):\n    ret = {'result': False}\n    cmd = '/sbin/ethtool -g {0}'.format(iface)\n    out = __salt__['cmd.run'](cmd)\n    pat = re.compile(r'^(.+):\\s+(\\d+)$')\n    suffix = 'max-'\n    for line in out.splitlines():\n        res = pat.match(line)\n        if res:\n            ret[res.group(1).lower().replace(' ', '-') + suffix] = int(res.group(2))\n            ret['result'] = True\n        elif line.endswith('maximums:'):\n            suffix = '-max'\n        elif line.endswith('settings:'):\n            suffix = ''\n    if not ret['result']:\n        parts = out.split()\n        if parts[0].endswith('sh:'):\n            out = ' '.join(parts[1:])\n        ret['comment'] = out\n    return ret",
    "docstring": "Return network interface buffer information using ethtool"
  },
  {
    "code": "def monthly_build_list_regex(self):\n        return r'nightly/%(YEAR)s/%(MONTH)s/' % {\n            'YEAR': self.date.year,\n            'MONTH': str(self.date.month).zfill(2)}",
    "docstring": "Return the regex for the folder containing builds of a month."
  },
  {
    "code": "def precondition(precond):\n    def decorator(f):\n        def decorated(*args):\n            if len(args) > 2:\n                raise TypeError('%s takes only 1 argument (or 2 for instance methods)' % f.__name__)\n            try:\n                instance, data = args\n                if not isinstance(instance, Pipe):\n                    raise TypeError('%s is not a valid pipe instance' % instance)\n            except ValueError:\n                data = args[0]\n            try:\n                precond(data)\n            except UnmetPrecondition:\n                return data\n            else:\n                return f(*args)\n        return decorated\n    return decorator",
    "docstring": "Runs the callable responsible for making some assertions\n    about the data structure expected for the transformation.\n\n    If the precondition is not achieved, a UnmetPrecondition\n    exception must be raised, and then the transformation pipe\n    is bypassed."
  },
  {
    "code": "def get_directory_as_zip(self, remote_path, local_file):\n        remote_path = self._normalize_path(remote_path)\n        url = self.url + 'index.php/apps/files/ajax/download.php?dir=' \\\n              + parse.quote(remote_path)\n        res = self._session.get(url, stream=True)\n        if res.status_code == 200:\n            if local_file is None:\n                local_file = os.path.basename(remote_path)\n            file_handle = open(local_file, 'wb', 8192)\n            for chunk in res.iter_content(8192):\n                file_handle.write(chunk)\n            file_handle.close()\n            return True\n        elif res.status_code >= 400:\n            raise HTTPResponseError(res)\n        return False",
    "docstring": "Downloads a remote directory as zip\n\n        :param remote_path: path to the remote directory to download\n        :param local_file: path and name of the target local file\n        :returns: True if the operation succeeded, False otherwise\n        :raises: HTTPResponseError in case an HTTP error status was returned"
  },
  {
    "code": "def get_max_id(self, object_type, role):\n        if object_type == 'user':\n            objectclass = 'posixAccount'\n            ldap_attr = 'uidNumber'\n        elif object_type == 'group':\n            objectclass = 'posixGroup'\n            ldap_attr = 'gidNumber'\n        else:\n            raise ldap_tools.exceptions.InvalidResult('Unknown object type')\n        minID, maxID = Client.__set_id_boundary(role)\n        filter = [\n            \"(objectclass={})\".format(objectclass), \"({}>={})\".format(ldap_attr, minID)\n        ]\n        if maxID is not None:\n            filter.append(\"({}<={})\".format(ldap_attr, maxID))\n        id_list = self.search(filter, [ldap_attr])\n        if id_list == []:\n            id = minID\n        else:\n            if object_type == 'user':\n                id = max([i.uidNumber.value for i in id_list]) + 1\n            elif object_type == 'group':\n                id = max([i.gidNumber.value for i in id_list]) + 1\n            else:\n                raise ldap_tools.exceptions.InvalidResult('Unknown object')\n        return id",
    "docstring": "Get the highest used ID."
  },
  {
    "code": "def _pick_unused_port_without_server():\n    rng = random.Random()\n    for _ in range(10):\n        port = int(rng.randrange(15000, 25000))\n        if is_port_free(port):\n            _random_ports.add(port)\n            return port\n    for _ in range(10):\n        port = bind(0, _PROTOS[0][0], _PROTOS[0][1])\n        if port and bind(port, _PROTOS[1][0], _PROTOS[1][1]):\n            _random_ports.add(port)\n            return port\n    raise NoFreePortFoundError()",
    "docstring": "Pick an available network port without the help of a port server.\n\n    This code ensures that the port is available on both TCP and UDP.\n\n    This function is an implementation detail of PickUnusedPort(), and\n    should not be called by code outside of this module.\n\n    Returns:\n      A port number that is unused on both TCP and UDP.\n\n    Raises:\n      NoFreePortFoundError: No free port could be found."
  },
  {
    "code": "def readTableFromCSV(f, dialect=\"excel\"):\n    rowNames = []\n    columnNames = []\n    matrix = []\n    first = True\n    for row in csv.reader(f, dialect):\n        if first:\n            columnNames = row[1:]\n            first = False\n        else:\n            rowNames.append(row[0])\n            matrix.append([float(c) for c in row[1:]])\n    return Table(rowNames, columnNames, matrix)",
    "docstring": "Reads a table object from given CSV file."
  },
  {
    "code": "def get_encoding(input_string, guesses=None, is_html=False):\n    converted = UnicodeDammit(input_string, override_encodings=[guesses] if guesses else [], is_html=is_html)\n    return converted.original_encoding",
    "docstring": "Return the encoding of a byte string. Uses bs4 UnicodeDammit.\n\n    :param string input_string: Encoded byte string.\n    :param list[string] guesses: (Optional) List of encoding guesses to prioritize.\n    :param bool is_html: Whether the input is HTML."
  },
  {
    "code": "def delete_account_metadata(self, prefix=None):\n        if prefix is None:\n            prefix = ACCOUNT_META_PREFIX\n        curr_meta = self.get_account_metadata(prefix=prefix)\n        for ckey in curr_meta:\n            curr_meta[ckey] = \"\"\n        new_meta = _massage_metakeys(curr_meta, prefix)\n        uri = \"/\"\n        resp, resp_body = self.api.method_post(uri, headers=new_meta)\n        return 200 <= resp.status_code <= 299",
    "docstring": "Removes all metadata matching the specified prefix from the account.\n\n        By default, the standard account metadata prefix ('X-Account-Meta-') is\n        prepended to the header name if it isn't present. For non-standard\n        headers, you must include a non-None prefix, such as an empty string."
  },
  {
    "code": "def __read_chunk(self, start, size):\n        for _retries in range(3):\n            command = 1504\n            command_string = pack('<ii', start, size)\n            if self.tcp:\n                response_size = size + 32\n            else:\n                response_size = 1024 + 8\n            cmd_response = self.__send_command(command, command_string, response_size)\n            data = self.__recieve_chunk()\n            if data is not None:\n                return data\n        else:\n            raise ZKErrorResponse(\"can't read chunk %i:[%i]\" % (start, size))",
    "docstring": "read a chunk from buffer"
  },
  {
    "code": "def stop(self):\n        if self.server.eio.async_mode == 'threading':\n            func = flask.request.environ.get('werkzeug.server.shutdown')\n            if func:\n                func()\n            else:\n                raise RuntimeError('Cannot stop unknown web server')\n        elif self.server.eio.async_mode == 'eventlet':\n            raise SystemExit\n        elif self.server.eio.async_mode == 'gevent':\n            self.wsgi_server.stop()",
    "docstring": "Stop a running SocketIO web server.\n\n        This method must be called from a HTTP or SocketIO handler function."
  },
  {
    "code": "def get_protocol(handle: Handle, want_v2: bool) -> Protocol:\n    force_v1 = int(os.environ.get(\"TREZOR_PROTOCOL_V1\", 1))\n    if want_v2 and not force_v1:\n        return ProtocolV2(handle)\n    else:\n        return ProtocolV1(handle)",
    "docstring": "Make a Protocol instance for the given handle.\n\n    Each transport can have a preference for using a particular protocol version.\n    This preference is overridable through `TREZOR_PROTOCOL_V1` environment variable,\n    which forces the library to use V1 anyways.\n\n    As of 11/2018, no devices support V2, so we enforce V1 here. It is still possible\n    to set `TREZOR_PROTOCOL_V1=0` and thus enable V2 protocol for transports that ask\n    for it (i.e., USB transports for Trezor T)."
  },
  {
    "code": "def _post_build(self, module, encoding):\n        module.file_encoding = encoding\n        self._manager.cache_module(module)\n        for from_node in module._import_from_nodes:\n            if from_node.modname == \"__future__\":\n                for symbol, _ in from_node.names:\n                    module.future_imports.add(symbol)\n            self.add_from_names_to_locals(from_node)\n        for delayed in module._delayed_assattr:\n            self.delayed_assattr(delayed)\n        if self._apply_transforms:\n            module = self._manager.visit_transforms(module)\n        return module",
    "docstring": "Handles encoding and delayed nodes after a module has been built"
  },
  {
    "code": "def get_template(self, path):\n        if self.options['debug'] and self.options['cache_size']:\n            return self.cache.get(path, self.cache_template(path))\n        return self.load_template(path)",
    "docstring": "Load and compile template."
  },
  {
    "code": "def get_feature_report(self, report_id, length):\n        self._check_device_status()\n        bufp = ffi.new(\"unsigned char[]\", length+1)\n        buf = ffi.buffer(bufp, length+1)\n        buf[0] = report_id\n        rv = hidapi.hid_get_feature_report(self._device, bufp, length+1)\n        if rv == -1:\n            raise IOError(\"Failed to get feature report from HID device: {0}\"\n                          .format(self._get_last_error_string()))\n        return buf[1:]",
    "docstring": "Get a feature report from the device.\n\n        :param report_id:   The Report ID of the report to be read\n        :type report_id:    int\n        :return:            The report data\n        :rtype:             str/bytes"
  },
  {
    "code": "def GetGRRVersionString(self):\n    client_info = self.startup_info.client_info\n    client_name = client_info.client_description or client_info.client_name\n    if client_info.client_version > 0:\n      client_version = str(client_info.client_version)\n    else:\n      client_version = _UNKNOWN_GRR_VERSION\n    return \" \".join([client_name, client_version])",
    "docstring": "Returns the client installation-name and GRR version as a string."
  },
  {
    "code": "def parse_item(self, location: str, item_type: Type[T], item_name_for_log: str = None,\n                   file_mapping_conf: FileMappingConfiguration = None, options: Dict[str, Dict[str, Any]] = None) -> T:\n        item_name_for_log = item_name_for_log or ''\n        check_var(item_name_for_log, var_types=str, var_name='item_name_for_log')\n        if len(item_name_for_log) > 0:\n            item_name_for_log = item_name_for_log + ' '\n        self.logger.debug('**** Starting to parse single object ' + item_name_for_log + 'of type <'\n                          + get_pretty_type_str(item_type) + '> at location ' + location + ' ****')\n        return self._parse__item(item_type, location, file_mapping_conf, options=options)",
    "docstring": "Main method to parse an item of type item_type\n\n        :param location:\n        :param item_type:\n        :param item_name_for_log:\n        :param file_mapping_conf:\n        :param options:\n        :return:"
  },
  {
    "code": "def create_token(self, request, refresh_token=False, **kwargs):\n        if \"save_token\" in kwargs:\n            warnings.warn(\"`save_token` has been deprecated, it was not called internally.\"\n                          \"If you do, call `request_validator.save_token()` instead.\",\n                          DeprecationWarning)\n        if callable(self.expires_in):\n            expires_in = self.expires_in(request)\n        else:\n            expires_in = self.expires_in\n        request.expires_in = expires_in\n        token = {\n            'access_token': self.token_generator(request),\n            'expires_in': expires_in,\n            'token_type': 'Bearer',\n        }\n        if request.scopes is not None:\n            token['scope'] = ' '.join(request.scopes)\n        if refresh_token:\n            if (request.refresh_token and\n                    not self.request_validator.rotate_refresh_token(request)):\n                token['refresh_token'] = request.refresh_token\n            else:\n                token['refresh_token'] = self.refresh_token_generator(request)\n        token.update(request.extra_credentials or {})\n        return OAuth2Token(token)",
    "docstring": "Create a BearerToken, by default without refresh token.\n\n        :param request: OAuthlib request.\n        :type request: oauthlib.common.Request\n        :param refresh_token:"
  },
  {
    "code": "def stop(self):\n        if self.container_id is None:\n            raise Exception('No Docker Selenium container was running')\n        check_call(['docker', 'stop', self.container_id])\n        self.container_id = None",
    "docstring": "Stop the Docker container"
  },
  {
    "code": "def log_time(func):\n    @functools.wraps(func)\n    def _execute(*args, **kwargs):\n        func_name = get_method_name(func)\n        timer = Timer()\n        log_message(func_name, \"has started\")\n        with timer:\n            result = func(*args, **kwargs)\n        seconds = \"{:.3f}\".format(timer.elapsed_time())\n        log_message(func_name, \"has finished. Execution time:\", seconds, \"s\")\n        return result\n    return _execute",
    "docstring": "Executes function and logs time\n\n    :param func: function to call\n    :return: function result"
  },
  {
    "code": "def srun_nodes(self):\n        count = self.execution.get('srun_nodes', 0)\n        if isinstance(count, six.string_types):\n            tag = count\n            count = 0\n        elif isinstance(count, SEQUENCES):\n            return count\n        else:\n            assert isinstance(count, int)\n            tag = self.tag\n        nodes = self._srun_nodes(tag, count)\n        if 'srun_nodes' in self.execution:\n            self.execution['srun_nodes'] = nodes\n            self.execution['srun_nodes_count'] = len(nodes)\n        return nodes",
    "docstring": "Get list of nodes where to execute the command"
  },
  {
    "code": "def processor(ctx, processor_cls, process_time_limit, enable_stdout_capture=True, get_object=False):\n    g = ctx.obj\n    Processor = load_cls(None, None, processor_cls)\n    processor = Processor(projectdb=g.projectdb,\n                          inqueue=g.fetcher2processor, status_queue=g.status_queue,\n                          newtask_queue=g.newtask_queue, result_queue=g.processor2result,\n                          enable_stdout_capture=enable_stdout_capture,\n                          process_time_limit=process_time_limit)\n    g.instances.append(processor)\n    if g.get('testing_mode') or get_object:\n        return processor\n    processor.run()",
    "docstring": "Run Processor."
  },
  {
    "code": "def unregister(self, label: str) -> None:\n        self.unregister_encoder(label)\n        self.unregister_decoder(label)",
    "docstring": "Unregisters the entries in the encoder and decoder registries which\n        have the label ``label``."
  },
  {
    "code": "def eval(thunk, env):\n  key = Activation.key(thunk, env)\n  if Activation.activated(key):\n    raise exceptions.RecursionError('Reference cycle')\n  with Activation(key):\n    return eval_cache.get(key, thunk.eval, env)",
    "docstring": "Evaluate a thunk in an environment.\n\n  Will defer the actual evaluation to the thunk itself, but adds two things:\n  caching and recursion detection.\n\n  Since we have to use a global evaluation stack (because there is a variety of functions that may\n  be invoked, not just eval() but also __getitem__, and not all of them can pass along a context\n  object), GCL evaluation is not thread safe.\n\n  With regard to schemas:\n\n  - A schema can be passed in from outside. The returned object will be validated to see that it\n    conforms to the schema. The schema will be attached to the value if possible.\n  - Some objects may contain their own schema, such as tuples. This would be out of scope of the\n    eval() function, were it not for:\n  - Schema validation can be disabled in an evaluation call stack. This is useful if we're\n    evaluating a tuple only for its schema information. At that point, we're not interested if the\n    object is value-complete."
  },
  {
    "code": "def _process_event(self, event, tagged_data):\n    event_type = event.WhichOneof('what')\n    if event_type == 'summary':\n      for value in event.summary.value:\n        value = data_compat.migrate_value(value)\n        tag, metadata, values = tagged_data.get(value.tag, (None, None, []))\n        values.append((event.step, event.wall_time, value.tensor))\n        if tag is None:\n          tagged_data[value.tag] = sqlite_writer.TagData(\n              value.tag, value.metadata, values)\n    elif event_type == 'file_version':\n      pass\n    elif event_type == 'session_log':\n      if event.session_log.status == event_pb2.SessionLog.START:\n        pass\n    elif event_type in ('graph_def', 'meta_graph_def'):\n      pass\n    elif event_type == 'tagged_run_metadata':\n      pass",
    "docstring": "Processes a single tf.Event and records it in tagged_data."
  },
  {
    "code": "def _get_reader(self, network_reader):\n        with (yield from self._lock):\n            if self._reader_process is None:\n                self._reader_process = network_reader\n            if self._reader:\n                if self._reader_process == network_reader:\n                    self._current_read = asyncio.async(self._reader.read(READ_SIZE))\n                    return self._current_read\n        return None",
    "docstring": "Get a reader or None if another reader is already reading."
  },
  {
    "code": "def cleanup(self, cluster):\n        if self._storage_path and os.path.exists(self._storage_path):\n            fname = '%s.%s' % (AnsibleSetupProvider.inventory_file_ending,\n                               cluster.name)\n            inventory_path = os.path.join(self._storage_path, fname)\n            if os.path.exists(inventory_path):\n                try:\n                    os.unlink(inventory_path)\n                    if self._storage_path_tmp:\n                        if len(os.listdir(self._storage_path)) == 0:\n                            shutil.rmtree(self._storage_path)\n                except OSError as ex:\n                    log.warning(\n                        \"AnsibileProvider: Ignoring error while deleting \"\n                        \"inventory file %s: %s\", inventory_path, ex)",
    "docstring": "Deletes the inventory file used last recently used.\n\n        :param cluster: cluster to clear up inventory file for\n        :type cluster: :py:class:`elasticluster.cluster.Cluster`"
  },
  {
    "code": "def pil2tensor(image:Union[NPImage,NPArray],dtype:np.dtype)->TensorImage:\n    \"Convert PIL style `image` array to torch style image tensor.\"\n    a = np.asarray(image)\n    if a.ndim==2 : a = np.expand_dims(a,2)\n    a = np.transpose(a, (1, 0, 2))\n    a = np.transpose(a, (2, 1, 0))\n    return torch.from_numpy(a.astype(dtype, copy=False) )",
    "docstring": "Convert PIL style `image` array to torch style image tensor."
  },
  {
    "code": "def get_explicit_resnorms(self, indices=None):\n        res = self.get_explicit_residual(indices)\n        linear_system = self._deflated_solver.linear_system\n        Mres = linear_system.M * res\n        resnorms = numpy.zeros(res.shape[1])\n        for i in range(resnorms.shape[0]):\n            resnorms[i] = utils.norm(res[:, [i]], Mres[:, [i]],\n                                     ip_B=linear_system.ip_B)\n        return resnorms",
    "docstring": "Explicitly computes the Ritz residual norms."
  },
  {
    "code": "def metadata_get(self, path, cached=True):\n        try:\n            value = graceful_chain_get(self.inspect(cached=cached).response, *path)\n        except docker.errors.NotFound:\n            logger.warning(\"object %s is not available anymore\", self)\n            raise NotAvailableAnymore()\n        return value",
    "docstring": "get metadata from inspect, specified by path\n\n        :param path: list of str\n        :param cached: bool, use cached version of inspect if available"
  },
  {
    "code": "def _GetHeader(self):\n    header = []\n    for value in self.values:\n      try:\n        header.append(value.Header())\n      except SkipValue:\n        continue\n    return header",
    "docstring": "Returns header."
  },
  {
    "code": "def to_serializable_value(self):\n        return {\n            name: field.to_serializable_value()\n            for name, field in self.value.__dict__.items()\n            if isinstance(field, Field) and self.value\n        }",
    "docstring": "Run through all fields of the object and parse the values\n\n        :return:\n        :rtype: dict"
  },
  {
    "code": "def new_document(self):\n        doc = Document(self, None)\n        doc.create()\n        super(CouchDatabase, self).__setitem__(doc['_id'], doc)\n        return doc",
    "docstring": "Creates a new, empty document in the remote and locally cached database,\n        auto-generating the _id.\n\n        :returns: Document instance corresponding to the new document in the\n            database"
  },
  {
    "code": "def get_methodnames(self, node):\n        nodekey = self.get_nodekey(node)\n        prefix = self._method_prefix\n        if isinstance(nodekey, self.GeneratorType):\n            for nodekey in nodekey:\n                yield self._method_prefix + nodekey\n        else:\n            yield self._method_prefix + nodekey",
    "docstring": "Given a node, generate all names for matching visitor methods."
  },
  {
    "code": "def button_with_label(self, description, assistants=None):\n        btn = self.create_button()\n        label = self.create_label(description)\n        if assistants is not None:\n            h_box = self.create_box(orientation=Gtk.Orientation.VERTICAL)\n            h_box.pack_start(label, False, False, 0)\n            label_ass = self.create_label(\n                assistants, justify=Gtk.Justification.LEFT\n            )\n            label_ass.set_alignment(0, 0)\n            h_box.pack_start(label_ass, False, False, 12)\n            btn.add(h_box)\n        else:\n            btn.add(label)\n        return btn",
    "docstring": "Function creates a button with lave.\n            If assistant is specified then text is aligned"
  },
  {
    "code": "def get_field(self, page, language, initial=None):\n        if self.parsed:\n            help_text = _('Note: This field is evaluated as template code.')\n        else:\n            help_text = ''\n        widget = self.get_widget(page, language)\n        return self.field(\n            widget=widget, initial=initial,\n            help_text=help_text, required=False)",
    "docstring": "The field that will be shown within the admin."
  },
  {
    "code": "def add_listener(self, event_name: str, listener: Callable):\n        self.listeners[event_name].append(listener)\n        return self",
    "docstring": "Add a listener."
  },
  {
    "code": "def downloads_per_week(self):\n        if len(self.cache_dates) < 7:\n            logger.error(\"Only have %d days of data; cannot calculate \"\n                         \"downloads per week\", len(self.cache_dates))\n            return None\n        count, _ = self._downloads_for_num_days(7)\n        logger.debug(\"Downloads per week = %d\", count)\n        return count",
    "docstring": "Return the number of downloads in the last 7 days.\n\n        :return: number of downloads in the last 7 days; if we have less than\n          7 days of data, returns None.\n        :rtype: int"
  },
  {
    "code": "def delete_user_avatar(self, username, avatar):\n        params = {'username': username}\n        url = self._get_url('user/avatar/' + avatar)\n        return self._session.delete(url, params=params)",
    "docstring": "Delete a user's avatar.\n\n        :param username: the user to delete the avatar from\n        :param avatar: ID of the avatar to remove"
  },
  {
    "code": "def remove_message(self, message, afterwards=None):\n        if self.ro:\n            raise DatabaseROError()\n        path = message.get_filename()\n        self.writequeue.append(('remove', afterwards, path))",
    "docstring": "Remove a message from the notmuch index\n\n        :param message: message to remove\n        :type message: :class:`Message`\n        :param afterwards: callback to trigger after removing\n        :type afterwards: callable or None"
  },
  {
    "code": "def data_from_url(self, url, apple_fix=False):\n        if apple_fix:\n            url = apple_url_fix(url)\n        _, content = self.http.request(url)\n        if not content:\n            raise ConnectionError('Could not get data from %s!' % url)\n        return self.decode(content, apple_fix=apple_fix)",
    "docstring": "Download iCal data from URL.\n\n        :param url: URL to download\n        :param apple_fix: fix Apple bugs (protocol type and tzdata in iCal)\n        :return: decoded (and fixed) iCal data"
  },
  {
    "code": "def tag_fig_ordinal(tag):\n    tag_count = 0\n    if 'specific-use' not in tag.attrs:\n        return len(list(filter(lambda tag: 'specific-use' not in tag.attrs,\n                          tag.find_all_previous(tag.name)))) + 1",
    "docstring": "Meant for finding the position of fig tags with respect to whether\n    they are for a main figure or a child figure"
  },
  {
    "code": "def del_option_by_name(self, name):\n        for o in list(self._options):\n            assert isinstance(o, Option)\n            if o.name == name:\n                self._options.remove(o)",
    "docstring": "Delete an option from the message by name\n\n        :type name: String\n        :param name: option name"
  },
  {
    "code": "def as_view(cls, endpoint, protocol, *init_args, **init_kwargs):\n        def _wrapper(request, *args, **kwargs):\n            instance = cls(*init_args, endpoint=endpoint, request=request, **init_kwargs)\n            if protocol == Resource.Protocol.http:\n                return instance._wrap_http(cls.dispatch, endpoint=endpoint, *args, **kwargs)\n            elif protocol == Resource.Protocol.websocket:\n                return instance._wrap_ws(cls.dispatch, endpoint=endpoint, *args, **kwargs)\n            elif protocol == Resource.Protocol.amqp:\n                return instance._wrap_amqp(endpoint, *args, **kwargs)\n            else:\n                raise Exception('Communication protocol not specified')\n        return _wrapper",
    "docstring": "Used for hooking up the endpoints. Returns a wrapper function that creates\n        a new instance of the resource class and calls the correct view method for it."
  },
  {
    "code": "def open_external(self, fnames=None):\r\n        if fnames is None:\r\n            fnames = self.get_selected_filenames()\r\n        for fname in fnames:\r\n            self.open_outside_spyder([fname])",
    "docstring": "Open files with default application"
  },
  {
    "code": "def json_error(code, message):\n    message = repr(message)\n    return jsonify(dict(request=request.path, message=message)), code",
    "docstring": "Returns a JSON-ified error object"
  },
  {
    "code": "def get_absolute_url(self):\r\n        if self.override_url:\r\n            return self.override_url\r\n        if self.destination.is_blog:\r\n            return reverse('blog_entry_detail', args=[self.destination.slug, self.slug])\r\n        return reverse('article_detail', args=[self.slug])",
    "docstring": "If override_url was given, use that.\r\n        Otherwise, if the content belongs to a blog, use a blog url.\r\n        If not, use a regular article url."
  },
  {
    "code": "def get_items(self, maxlevel):\r\n        itemlist = []\r\n        def add_to_itemlist(item, maxlevel, level=1):\r\n            level += 1\r\n            for index in range(item.childCount()):\r\n                citem = item.child(index)\r\n                itemlist.append(citem)\r\n                if level <= maxlevel:\r\n                    add_to_itemlist(citem, maxlevel, level)\r\n        for tlitem in self.get_top_level_items():\r\n            itemlist.append(tlitem)\r\n            if maxlevel > 0:\r\n                add_to_itemlist(tlitem, maxlevel=maxlevel)\r\n        return itemlist",
    "docstring": "Return all items with a level <= `maxlevel`"
  },
  {
    "code": "def removeSpacePadding(str, blocksize=AES_blocksize):\n    'Remove padding with spaces' \n    pad_len = 0    \n    for char in str[::-1]:\n        if char == ' ':\n            pad_len += 1\n        else:\n            break\n    str = str[:-pad_len]\n    return str",
    "docstring": "Remove padding with spaces"
  },
  {
    "code": "def set_quiet(mres, parent, global_options):\n    quiet = global_options.get('quiet')\n    if quiet is not None:\n        mres._quiet = quiet\n    else:\n        mres._quiet = parent.quiet",
    "docstring": "Sets the 'quiet' property on the MultiResult"
  },
  {
    "code": "def get_service(self, name):\n        self._convert_connected_app()\n        if not self.project_config.services or name not in self.project_config.services:\n            self._raise_service_not_valid(name)\n        if name not in self.services:\n            self._raise_service_not_configured(name)\n        return self._get_service(name)",
    "docstring": "Retrieve a stored ServiceConfig from the keychain or exception\n\n        :param name: the service name to retrieve\n        :type name: str\n\n        :rtype ServiceConfig\n        :return the configured Service"
  },
  {
    "code": "def parse_option(self, option, block_name, *values):\n        _extra_subs = ('www', 'm', 'mobile')\n        if len(values) == 0:\n            raise ValueError\n        for value in values:\n            value = value.lower()\n            if not _RE_PROTOCOL.match(value):\n                value = 'http://' + value\n            parsed = urlparse.urlparse(value)\n            if parsed:\n                domain = parsed.hostname\n                if domain and _RE_TLD.search(domain):\n                    domain = _RE_WWW_SUB.sub('', domain)\n                    if len(domain.split('.')) == 2:\n                        for sub in _extra_subs:\n                            self.domains.add('{0}.{1}'.format(sub, domain))\n                    self.domains.add(domain)\n        if not self.domains:\n            raise ValueError",
    "docstring": "Parse domain values for option."
  },
  {
    "code": "def array_to_npy(array_like):\n    buffer = BytesIO()\n    np.save(buffer, array_like)\n    return buffer.getvalue()",
    "docstring": "Convert an array like object to the NPY format.\n\n    To understand better what an array like object is see:\n    https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays\n\n    Args:\n        array_like (np.array or Iterable or int or float): array like object to be converted to NPY.\n\n    Returns:\n        (obj): NPY array."
  },
  {
    "code": "def build(self, text, matrix, skim_depth=10, d_weights=False):\n        for anchor in bar(matrix.keys):\n            n1 = text.unstem(anchor)\n            pairs = matrix.anchored_pairs(anchor).items()\n            for term, weight in list(pairs)[:skim_depth]:\n                if d_weights: weight = 1-weight\n                n2 = text.unstem(term)\n                self.graph.add_edge(n1, n2, weight=float(weight))",
    "docstring": "1. For each term in the passed matrix, score its KDE similarity with\n        all other indexed terms.\n\n        2. With the ordered stack of similarities in hand, skim off the top X\n        pairs and add them as edges.\n\n        Args:\n            text (Text): The source text instance.\n            matrix (Matrix): An indexed term matrix.\n            skim_depth (int): The number of siblings for each term.\n            d_weights (bool): If true, give \"close\" words low edge weights."
  },
  {
    "code": "def print_projects(self, projects):\n        for project in projects:\n            print('{}: {}'.format(project.name, project.id))",
    "docstring": "Print method for projects."
  },
  {
    "code": "def get(self, uri, params={}):\n        logging.debug(\"Requesting URL: \"+str(urlparse.urljoin(self.BASE_URL, uri)))\n        return requests.get(urlparse.urljoin(self.BASE_URL, uri),\n            params=params, verify=False,\n            auth=self.auth)",
    "docstring": "A generic method to make GET requests"
  },
  {
    "code": "def param(self,key,default=None):\n        if key in self.parameters:\n            return self.parameters[key]\n        return default",
    "docstring": "for accessing global parameters"
  },
  {
    "code": "def show_instance(name, conn=None, call=None):\n    if call != 'action':\n        raise SaltCloudSystemExit(\n            'The show_instance action must be called with -a or --action.'\n        )\n    if conn is None:\n        conn = get_conn()\n    node = conn.get_server(name, bare=True)\n    ret = dict(node)\n    ret['id'] = node.id\n    ret['name'] = node.name\n    ret['size'] = conn.get_flavor(node.flavor.id).name\n    ret['state'] = node.status\n    ret['private_ips'] = _get_ips(node, 'private')\n    ret['public_ips'] = _get_ips(node, 'public')\n    ret['floating_ips'] = _get_ips(node, 'floating')\n    ret['fixed_ips'] = _get_ips(node, 'fixed')\n    if isinstance(node.image, six.string_types):\n        ret['image'] = node.image\n    else:\n        ret['image'] = conn.get_image(node.image.id).name\n    return ret",
    "docstring": "Get VM on this OpenStack account\n\n    name\n\n        name of the instance\n\n    CLI Example\n\n    .. code-block:: bash\n\n        salt-cloud -a show_instance myserver"
  },
  {
    "code": "def save(self, basename):\n        irom_segment = self.get_irom_segment()\n        if irom_segment is not None:\n            with open(\"%s0x%05x.bin\" % (basename, irom_segment.addr - ESP8266ROM.IROM_MAP_START), \"wb\") as f:\n                f.write(irom_segment.data)\n        normal_segments = self.get_non_irom_segments()\n        with open(\"%s0x00000.bin\" % basename, 'wb') as f:\n            self.write_common_header(f, normal_segments)\n            checksum = ESPLoader.ESP_CHECKSUM_MAGIC\n            for segment in normal_segments:\n                checksum = self.save_segment(f, segment, checksum)\n            self.append_checksum(f, checksum)",
    "docstring": "Save a set of V1 images for flashing. Parameter is a base filename."
  },
  {
    "code": "def dispatch(self, message):\n        for validator, callback in self.validators:\n            if not validator.matches(message):\n                continue\n            callback(message)\n            return\n        raise ArgumentError(\"No handler was registered for message\", message=message)",
    "docstring": "Dispatch a message to a callback based on its schema.\n\n        Args:\n            message (dict): The message to dispatch"
  },
  {
    "code": "def _trim_value(self, value):\n        if value[0] == '\"':\n            assert value[-1] == '\"'\n            value = value[1:-1].replace('\\\\\"', '\"').replace(\"\\\\\\\\\", \"\\\\\")\n            return Parser._unescape_re.sub(Parser._unescape_fn, value)\n        return value",
    "docstring": "Trim double quotes off the ends of a value, un-escaping inner\n        double quotes and literal backslashes. Also convert escapes to unicode.\n        If the string is not quoted, return it unmodified."
  },
  {
    "code": "def is_expanded(request, key):\n    expand = request.query_params.get(\"expand\", \"\")\n    expand_fields = []\n    for e in expand.split(\",\"):\n        expand_fields.extend([e for e in e.split(\".\")])\n    return \"~all\" in expand_fields or key in expand_fields",
    "docstring": "Examines request object to return boolean of whether\n        passed field is expanded."
  },
  {
    "code": "def allsame(list_, strict=True):\n    if len(list_) == 0:\n        return True\n    first_item = list_[0]\n    return list_all_eq_to(list_, first_item, strict)",
    "docstring": "checks to see if list is equal everywhere\n\n    Args:\n        list_ (list):\n\n    Returns:\n        True if all items in the list are equal"
  },
  {
    "code": "def analyze(self, id):\n        schema = AnalysisSchema()\n        resp = self.service.post(self.base+str(id)+'/', params={'process': 'analyze'})\n        return self.service.decode(schema, resp)",
    "docstring": "Get a list of tests that will be skipped for a package.\n\n        :param id: Package ID as an int.\n        :return: :class:`packages.Analysis <packages.Analysis>` object\n        :rtype: packages.Analysis"
  },
  {
    "code": "def parse_list(self):\n        try:\n            return List([self.parse() for _ in\n                         self.collect_tokens_until('CLOSE_BRACKET')])\n        except IncompatibleItemType as exc:\n            raise self.error(f'Item {str(exc.item)!r} is not a '\n                             f'{exc.subtype.__name__} tag') from None",
    "docstring": "Parse a list from the token stream."
  },
  {
    "code": "def verify(ctx, file, account):\n    if not file:\n        print_message(\"Prompting for message. Terminate with CTRL-D\", \"info\")\n        file = click.get_text_stream(\"stdin\")\n    m = Message(file.read(), bitshares_instance=ctx.bitshares)\n    try:\n        if m.verify():\n            print_message(\"Verified\", \"success\")\n        else:\n            print_message(\"not verified\", \"error\")\n    except InvalidMessageSignature:\n        print_message(\"Signature INVALID!\", \"error\")",
    "docstring": "Verify a signed message"
  },
  {
    "code": "def write_stilde(self, stilde_dict, group=None):\n        subgroup = self.data_group + \"/{ifo}/stilde\"\n        if group is None:\n            group = subgroup\n        else:\n            group = '/'.join([group, subgroup])\n        for ifo, stilde in stilde_dict.items():\n            self[group.format(ifo=ifo)] = stilde\n            self[group.format(ifo=ifo)].attrs['delta_f'] = stilde.delta_f\n            self[group.format(ifo=ifo)].attrs['epoch'] = float(stilde.epoch)",
    "docstring": "Writes stilde for each IFO to file.\n\n        Parameters\n        -----------\n        stilde : {dict, FrequencySeries}\n            A dict of FrequencySeries where the key is the IFO.\n        group : {None, str}\n            The group to write the strain to. If None, will write to the top\n            level."
  },
  {
    "code": "def unhook_wnd_proc(self):\r\n        if not self.__local_wnd_proc_wrapped:\r\n            return\r\n        SetWindowLong(self.__local_win_handle,\r\n                        GWL_WNDPROC,\r\n                        self.__old_wnd_proc)\r\n        self.__local_wnd_proc_wrapped = None",
    "docstring": "Restore previous Window message handler"
  },
  {
    "code": "def verify_account(self, email_address):\n        request = self._get_request()\n        resp = request.post(self.ACCOUNT_VERIFY_URL, {\n            'email_address': email_address\n        })\n        return ('account' in resp)",
    "docstring": "Verify whether a HelloSign Account exists\n\n            Args:\n\n                email_address (str): Email address for the account to verify\n\n            Returns:\n                True or False"
  },
  {
    "code": "def list_vcls(self, service_id, version_number):\n\t\tcontent = self._fetch(\"/service/%s/version/%d/vcl\" % (service_id, version_number))\n\t\treturn map(lambda x: FastlyVCL(self, x), content)",
    "docstring": "List the uploaded VCLs for a particular service and version."
  },
  {
    "code": "def full_path(self):\n        if Path(self.path).is_absolute():\n            return self.path\n        else:\n            return str(self.app_root / self.path)",
    "docstring": "Return the full path to the file."
  },
  {
    "code": "def project_version(full_version):\n    project_full_version=full_version\n    v = _parse_project_version(full_version)\n    name = project_name()\n    project_fullname = '-'.join([name,v])\n    return _setenv(project_full_version=project_full_version, project_version=v,project_name=name,project_fullname=project_fullname)",
    "docstring": "project_version context manager"
  },
  {
    "code": "def question_default_add_related_pks(self, obj):\n        if not hasattr(obj, '_choice_pks'):\n            obj._choice_pks = list(obj.choices.values_list('pk', flat=True))",
    "docstring": "Add related primary keys to a Question instance."
  },
  {
    "code": "def to_dict(self):\n        return {field_name: getattr(self, field_name, None)\n                for field_name in self.meta_.declared_fields}",
    "docstring": "Return entity data as a dictionary"
  },
  {
    "code": "def log2(x, context=None):\n    return _apply_function_in_current_context(\n        BigFloat,\n        mpfr.mpfr_log2,\n        (BigFloat._implicit_convert(x),),\n        context,\n    )",
    "docstring": "Return the base-two logarithm of x."
  },
  {
    "code": "def add_file_arg(self, filename):\n    self.__arguments.append(filename)\n    if filename not in self.__input_files:\n      self.__input_files.append(filename)",
    "docstring": "Add a file argument to the executable. Arguments are appended after any\n    options and their order is guaranteed. Also adds the file name to the\n    list of required input data for this job.\n    @param filename: file to add as argument."
  },
  {
    "code": "def on_heartbeat(self, message):\n        logger.info(\"Got a heartbeat\")\n        logger.info(\"Heartbeat message: {}\".format(message))\n        self.heartbeat_thread.update_sequence(message['d'])\n        return",
    "docstring": "Runs on a heartbeat event from websocket connection\n\n        Args:\n            message (dict): Full message from Discord websocket connection\""
  },
  {
    "code": "def tzinfo_eq(tzinfo1, tzinfo2, startYear = 2000, endYear=2020):\n    if tzinfo1 == tzinfo2:\n        return True\n    elif tzinfo1 is None or tzinfo2 is None:\n        return False\n    def dt_test(dt):\n        if dt is None:\n            return True\n        return tzinfo1.utcoffset(dt) == tzinfo2.utcoffset(dt)\n    if not dt_test(datetime.datetime(startYear, 1, 1)):\n        return False\n    for year in range(startYear, endYear):\n        for transitionTo in 'daylight', 'standard':\n            t1=getTransition(transitionTo, year, tzinfo1)\n            t2=getTransition(transitionTo, year, tzinfo2)\n            if t1 != t2 or not dt_test(t1):\n                return False\n    return True",
    "docstring": "Compare offsets and DST transitions from startYear to endYear."
  },
  {
    "code": "def download_file(fname, target_dir=None, force=False):\n    target_dir = target_dir or temporary_dir()\n    target_fname = os.path.join(target_dir, fname)\n    if force or not os.path.isfile(target_fname):\n        url = urljoin(datasets_url, fname)\n        urlretrieve(url, target_fname)\n    return target_fname",
    "docstring": "Download fname from the datasets_url, and save it to target_dir,\n    unless the file already exists, and force is False.\n\n    Parameters\n    ----------\n    fname : str\n        Name of the file to download\n\n    target_dir : str\n        Directory where to store the file\n\n    force : bool\n        Force downloading the file, if it already exists\n\n    Returns\n    -------\n    fname : str\n        Full path of the downloaded file"
  },
  {
    "code": "def output_vm(gandi, vm, datacenters, output_keys, justify=10):\n    output_generic(gandi, vm, output_keys, justify)\n    if 'datacenter' in output_keys:\n        for dc in datacenters:\n            if dc['id'] == vm['datacenter_id']:\n                dc_name = dc.get('dc_code', dc.get('iso', ''))\n                break\n        output_line(gandi, 'datacenter', dc_name, justify)\n    if 'ip' in output_keys:\n        for iface in vm['ifaces']:\n            gandi.separator_line()\n            output_line(gandi, 'bandwidth', iface['bandwidth'], justify)\n            for ip in iface['ips']:\n                ip_addr = ip['ip']\n                output_line(gandi, 'ip%s' % ip['version'], ip_addr, justify)",
    "docstring": "Helper to output a vm information."
  },
  {
    "code": "def repair(self, verbose=False, joincomp=False,\n               remove_smallest_components=True):\n        assert self.f.shape[1] == 3, 'Face array must contain three columns'\n        assert self.f.ndim == 2, 'Face array must be 2D'\n        self.v, self.f = _meshfix.clean_from_arrays(self.v, self.f,\n                                                    verbose, joincomp,\n                                                    remove_smallest_components)",
    "docstring": "Performs mesh repair using MeshFix's default repair\n        process.\n\n        Parameters\n        ----------\n        verbose : bool, optional\n            Enables or disables debug printing.  Disabled by default.\n\n        joincomp : bool, optional\n            Attempts to join nearby open components.\n\n        remove_smallest_components : bool, optional\n            Remove all but the largest isolated component from the\n            mesh before beginning the repair process.  Default True\n\n        Notes\n        -----\n        Vertex and face arrays are updated inplace.  Access them with:\n        meshfix.v\n        meshfix.f"
  },
  {
    "code": "def list_instance_configs(self, page_size=None, page_token=None):\n        metadata = _metadata_with_prefix(self.project_name)\n        path = \"projects/%s\" % (self.project,)\n        page_iter = self.instance_admin_api.list_instance_configs(\n            path, page_size=page_size, metadata=metadata\n        )\n        page_iter.next_page_token = page_token\n        page_iter.item_to_value = _item_to_instance_config\n        return page_iter",
    "docstring": "List available instance configurations for the client's project.\n\n        .. _RPC docs: https://cloud.google.com/spanner/docs/reference/rpc/\\\n                      google.spanner.admin.instance.v1#google.spanner.admin.\\\n                      instance.v1.InstanceAdmin.ListInstanceConfigs\n\n        See `RPC docs`_.\n\n        :type page_size: int\n        :param page_size:\n            Optional. The maximum number of configs in each page of results\n            from this request. Non-positive values are ignored. Defaults\n            to a sensible value set by the API.\n\n        :type page_token: str\n        :param page_token:\n            Optional. If present, return the next batch of configs, using\n            the value, which must correspond to the ``nextPageToken`` value\n            returned in the previous response.  Deprecated: use the ``pages``\n            property of the returned iterator instead of manually passing\n            the token.\n\n        :rtype: :class:`~google.api_core.page_iterator.Iterator`\n        :returns:\n            Iterator of\n            :class:`~google.cloud.spanner_v1.instance.InstanceConfig`\n            resources within the client's project."
  },
  {
    "code": "def create_repository(self):\n        schema = self.get_connection().get_schema_builder()\n        with schema.create(self._table) as table:\n            table.string(\"migration\")\n            table.integer(\"batch\")",
    "docstring": "Create the migration repository data store."
  },
  {
    "code": "def move_backend(self, from_path, to_path):\n        params = {\n            'from': from_path,\n            'to': to_path,\n        }\n        api_path = '/v1/sys/remount'\n        return self._adapter.post(\n            url=api_path,\n            json=params,\n        )",
    "docstring": "Move an already-mounted backend to a new mount point.\n\n        Supported methods:\n            POST: /sys/remount. Produces: 204 (empty body)\n\n        :param from_path: Specifies the previous mount point.\n        :type from_path: str | unicode\n        :param to_path: Specifies the new destination mount point.\n        :type to_path: str | unicode\n        :return: The response of the request.\n        :rtype: requests.Response"
  },
  {
    "code": "def _broadcast_shapes(s1, s2):\n    n1 = len(s1)\n    n2 = len(s2)\n    n = max(n1, n2)\n    res = [1] * n\n    for i in range(n):\n        if i >= n1:\n            c1 = 1\n        else:\n            c1 = s1[n1-1-i]\n        if i >= n2:\n            c2 = 1\n        else:\n            c2 = s2[n2-1-i]\n        if c1 == 1:\n            rc = c2\n        elif c2 == 1 or c1 == c2:\n            rc = c1\n        else:\n            raise ValueError('array shapes %r and %r are not compatible' % (s1, s2))\n        res[n-1-i] = rc\n    return tuple(res)",
    "docstring": "Given array shapes `s1` and `s2`, compute the shape of the array that would\n    result from broadcasting them together."
  },
  {
    "code": "def render_text(text, language=None):\n    text_filter = SUPPORTED_LANGUAGES.get(language, None)\n    if not text_filter:\n        raise ImproperlyConfigured(\"markup filter does not exist: {0}. Valid options are: {1}\".format(\n            language, ', '.join(list(SUPPORTED_LANGUAGES.keys()))\n        ))\n    return text_filter(text)",
    "docstring": "Render the text, reuses the template filters provided by Django."
  },
  {
    "code": "def UWRatio(s1, s2, full_process=True):\n    return WRatio(s1, s2, force_ascii=False, full_process=full_process)",
    "docstring": "Return a measure of the sequences' similarity between 0 and 100,\n    using different algorithms. Same as WRatio but preserving unicode."
  },
  {
    "code": "def loop_stopped(self):\n\t\ttransport = self.transport()\n\t\tif self.server_mode() is True:\n\t\t\ttransport.close_server_socket(self.config())\n\t\telse:\n\t\t\ttransport.close_client_socket(self.config())",
    "docstring": "Terminate socket connection because of stopping loop\n\n\t\t:return: None"
  },
  {
    "code": "def get_person_by_netid(self, netid):\n        if not self.valid_uwnetid(netid):\n            raise InvalidNetID(netid)\n        url = \"{}/{}/full.json\".format(PERSON_PREFIX, netid.lower())\n        response = DAO.getURL(url, {\"Accept\": \"application/json\"})\n        if response.status != 200:\n            raise DataFailureException(url, response.status, response.data)\n        return self._person_from_json(response.data)",
    "docstring": "Returns a restclients.Person object for the given netid.  If the\n        netid isn't found, or if there is an error communicating with the PWS,\n        a DataFailureException will be thrown."
  },
  {
    "code": "def _get_line(self) -> str:\n        line = self.in_lines[self.index]\n        self.index += 1\n        return line",
    "docstring": "Returns the current line from the file while incrementing the index."
  },
  {
    "code": "def release(self):\n        try:\n            self.pidfile.close()\n            os.remove(self._pidfile)\n        except OSError as err:\n            if err.errno != 2:\n                raise",
    "docstring": "Release the pidfile.\n\n        Close and delete the Pidfile.\n\n\n        :return: None"
  },
  {
    "code": "def trans(self, id, parameters=None, domain=None, locale=None):\n        if parameters is None:\n            parameters = {}\n        assert isinstance(parameters, dict)\n        if locale is None:\n            locale = self.locale\n        else:\n            self._assert_valid_locale(locale)\n        if domain is None:\n            domain = 'messages'\n        msg = self.get_catalogue(locale).get(id, domain)\n        return self.format(msg, parameters)",
    "docstring": "Translates the given message.\n\n        @type id: str\n        @param id: The message id\n\n        @type parameters: dict\n        @param parameters: A dict of parameters for the message\n\n        @type domain: str\n        @param domain: The domain for the message or null to use the default\n\n        @type locale: str\n        @param locale: The locale or null to use the default\n\n        @rtype: str\n        @return: Translated message"
  },
  {
    "code": "def getIndexStripUrl(self, index):\n        chapter, num = index.split('-')\n        return self.stripUrl % (chapter, chapter, num)",
    "docstring": "Get comic strip URL from index."
  },
  {
    "code": "def set_all_name_components(self, name, weight, width, custom_name):\n        self.weight = weight or \"Regular\"\n        self.width = width or \"Regular\"\n        self.customName = custom_name or \"\"\n        if self._joinName() == name:\n            self._name = None\n            del self.customParameters[\"Master Name\"]\n        else:\n            self._name = name\n            self.customParameters[\"Master Name\"] = name",
    "docstring": "This function ensures that after being called, the master.name,\n        master.weight, master.width, and master.customName match the given\n        values."
  },
  {
    "code": "def client_ident(self):\n        return irc.client.NickMask.from_params(\n            self.nick, self.user,\n            self.server.servername)",
    "docstring": "Return the client identifier as included in many command replies."
  },
  {
    "code": "def remove(self, **kwargs):\n        self.helper.remove(self.inner(), **kwargs)\n        self._inner = None",
    "docstring": "Remove an instance of this resource definition."
  },
  {
    "code": "def transition(value, maximum, start, end):\n    return round(start + (end - start) * value / maximum, 2)",
    "docstring": "Transition between two values.\n\n    :param value: Current iteration.\n    :param maximum: Maximum number of iterations.\n    :param start: Start value.\n    :param end: End value.\n    :returns: Transitional value."
  },
  {
    "code": "def seed_instance(self, seed=None):\n        if self.__random == random:\n            self.__random = random_module.Random()\n        self.__random.seed(seed)\n        return self",
    "docstring": "Calls random.seed"
  },
  {
    "code": "def get_status_key(self, instance):\n        key_id = \"inst_%s\" % id(instance) if instance.pk is None else instance.pk\n        return \"%s.%s-%s-%s\" % (instance._meta.app_label,\n                                get_model_name(instance),\n                                key_id,\n                                self.field.name)",
    "docstring": "Generates a key used to set a status on a field"
  },
  {
    "code": "def set_transition_down(self, p_self):\n        if p_self is None:\n            self.down_transition = None\n        else:\n            self.down_transition = transition_loop(2, p_self)",
    "docstring": "Set the downbeat-tracking transition matrix according to\n        self-loop probabilities.\n\n        Parameters\n        ----------\n        p_self : None, float in (0, 1), or np.ndarray [shape=(2,)]\n            Optional self-loop probability(ies), used for Viterbi decoding"
  },
  {
    "code": "def get_reversed_unification_program(angles, control_indices,\n                                     target, controls, mode):\n    if mode == 'phase':\n        gate = RZ\n    elif mode == 'magnitude':\n        gate = RY\n    else:\n        raise ValueError(\"mode must be \\'phase\\' or \\'magnitude\\'\")\n    reversed_gates = []\n    for j in range(len(angles)):\n        if angles[j] != 0:\n            reversed_gates.append(gate(-angles[j], target))\n        if len(controls) > 0:\n            reversed_gates.append(CNOT(controls[control_indices[j] - 1],\n                                       target))\n    return Program().inst(reversed_gates[::-1])",
    "docstring": "Gets the Program representing the reversed circuit\n    for the decomposition of the uniformly controlled\n    rotations in a unification step.\n\n    If :math:`n` is the number of controls, the indices within control indices\n    must range from 1 to :math:`n`, inclusive. The length of control_indices\n    and the length of angles must both be :math:`2^n`.\n\n    :param list angles: The angles of rotation in the the decomposition,\n                        in order from left to right\n    :param list control_indices: a list of positions for the controls of the\n                                 CNOTs used when decomposing uniformly\n                                 controlled rotations; see\n                                 get_cnot_control_positions for labelling\n                                 conventions.\n    :param int target: Index of the target of all rotations\n    :param list controls: Index of the controls, in order from bottom to top.\n    :param str mode: The unification mode. Is either 'phase', corresponding\n                     to controlled RZ rotations, or 'magnitude', corresponding\n                     to controlled RY rotations.\n    :return: The reversed circuit of this unification step.\n    :rtype: Program"
  },
  {
    "code": "def info_to_datatype_v4(signed, little_endian):\n    if signed:\n        if little_endian:\n            datatype = v4c.DATA_TYPE_SIGNED_INTEL\n        else:\n            datatype = v4c.DATA_TYPE_SIGNED_MOTOROLA\n    else:\n        if little_endian:\n            datatype = v4c.DATA_TYPE_UNSIGNED_INTEL\n        else:\n            datatype = v4c.DATA_TYPE_UNSIGNED_MOTOROLA\n    return datatype",
    "docstring": "map CAN signal to MDF integer types\n\n    Parameters\n    ----------\n    signed : bool\n        signal is flagged as signed in the CAN database\n    little_endian : bool\n        signal is flagged as little endian (Intel) in the CAN database\n\n    Returns\n    -------\n    datatype : int\n        integer code for MDF channel data type"
  },
  {
    "code": "def post_upgrade_checks(self, upgrades):\n        errors = []\n        for u in upgrades:\n            self._setup_log_prefix(plugin_id=u.name)\n            try:\n                u.post_upgrade()\n            except RuntimeError as e:\n                errors.append((u.name, e.args))\n        for check in self.global_post_upgrade:\n            self._setup_log_prefix(plugin_id=check.__name__)\n            try:\n                check()\n            except RuntimeError as e:\n                errors.append((check.__name__, e.args))\n        self._teardown_log_prefix()\n        self._check_errors(errors, \"Post-upgrade check for %s failed with the \"\n                           \"following errors:\")",
    "docstring": "Run post-upgrade checks after applying all pending upgrades.\n\n        Post checks may be used to emit warnings encountered when applying an\n        upgrade, but post-checks can also be used to advice the user to run\n        re-indexing or similar long running processes.\n\n        Post-checks may query for user-input, but should respect the\n        --yes-i-know option to run in an unattended mode.\n\n        All applied upgrades post-checks are executed.\n\n        :param upgrades: List of upgrades sorted in topological order."
  },
  {
    "code": "async def start(self, file_path, locale=None, kwargs=None):\n        self._file_path = os.path.realpath(file_path)\n        self._locale = locale\n        if kwargs:\n            self._kwargs = kwargs\n        if settings.I18N_LIVE_RELOAD:\n            loop = asyncio.get_event_loop()\n            self._running = True\n            self._watcher = aionotify.Watcher()\n            self._watcher.watch(\n                path=os.path.dirname(self._file_path),\n                flags=aionotify.Flags.MOVED_TO | aionotify.Flags.MODIFY,\n            )\n            await self._watcher.setup(loop)\n            await self._load()\n            loop.create_task(self._watch())\n        else:\n            await self._load()",
    "docstring": "Setup the watching utilities, start the loop and load data a first\n        time."
  },
  {
    "code": "def activate(lancet, method, project):\n    with taskstatus(\"Looking up project\") as ts:\n        if method == \"key\":\n            func = get_project_keys\n        elif method == \"dir\":\n            func = get_project_keys\n        for key, project_path in func(lancet):\n            if key.lower() == project.lower():\n                break\n        else:\n            ts.abort(\n                'Project \"{}\" not found (using {}-based lookup)',\n                project,\n                method,\n            )\n    config = load_config(os.path.join(project_path, LOCAL_CONFIG))\n    lancet.defer_to_shell(\"cd\", project_path)\n    venv = config.get(\"lancet\", \"virtualenv\", fallback=None)\n    if venv:\n        venv_path = os.path.join(project_path, os.path.expanduser(venv))\n        activate_script = os.path.join(venv_path, \"bin\", \"activate\")\n        lancet.defer_to_shell(\"source\", activate_script)\n    else:\n        if \"VIRTUAL_ENV\" in os.environ:\n            lancet.defer_to_shell(\"deactivate\")",
    "docstring": "Switch to this project."
  },
  {
    "code": "def calc_columns_rows(n):\n    num_columns = int(ceil(sqrt(n)))\n    num_rows = int(ceil(n / float(num_columns)))\n    return (num_columns, num_rows)",
    "docstring": "Calculate the number of columns and rows required to divide an image\n    into ``n`` parts.\n\n    Return a tuple of integers in the format (num_columns, num_rows)"
  },
  {
    "code": "def _wait(self, args, now, cap, consumed_history, consumed_capacity):\n        for key in ['read', 'write']:\n            if key in cap and cap[key] > 0:\n                consumed_history[key].add(now, consumed_capacity[key])\n                consumed = consumed_history[key].value\n                if consumed > 0 and consumed >= cap[key]:\n                    seconds = math.ceil(float(consumed) / cap[key])\n                    LOG.debug(\"Rate limited throughput exceeded. Sleeping \"\n                              \"for %d seconds.\", seconds)\n                    if callable(self.callback):\n                        callback_args = args + (seconds,)\n                        if self.callback(*callback_args):\n                            continue\n                    time.sleep(seconds)",
    "docstring": "Check the consumed capacity against the limit and sleep"
  },
  {
    "code": "def get_local_file_list(self):\n        file_list = []\n        for (dirpath, dirnames, filenames) in os.walk(self.build_dir):\n            for fname in filenames:\n                local_key = os.path.join(\n                    os.path.relpath(dirpath, self.build_dir),\n                    fname\n                )\n                if local_key.startswith('./'):\n                    local_key = local_key[2:]\n                file_list.append(local_key)\n        return file_list",
    "docstring": "Walk the local build directory and create a list of relative and\n        absolute paths to files."
  },
  {
    "code": "def _listeq_to_dict(jobconfs):\n    if not isinstance(jobconfs, dict):\n        jobconfs = dict(x.split('=', 1) for x in jobconfs)\n    return dict((str(k), str(v)) for k, v in jobconfs.items())",
    "docstring": "Convert iterators of 'key=val' into a dictionary with later values taking priority."
  },
  {
    "code": "def is_sparse_file(filename):\n    dirname, basename = os.path.split(filename)\n    name, ext = os.path.splitext(basename)\n    matrix_name, matrix_ext = os.path.splitext(name)\n    if matrix_ext == '.coo':\n        return True\n    else:\n        return False",
    "docstring": "Determine if the given filename indicates a dense or a sparse matrix\n\n       If pathname is xxx.coo.yyy return True otherwise False."
  },
  {
    "code": "def kill_window(pymux, variables):\n    \" Kill all panes in the current window. \"\n    for pane in pymux.arrangement.get_active_window().panes:\n        pymux.kill_pane(pane)",
    "docstring": "Kill all panes in the current window."
  },
  {
    "code": "def expect_column_values_to_match_json_schema(self,\n                                                  column,\n                                                  json_schema,\n                                                  mostly=None,\n                                                  result_format=None, include_config=False, catch_exceptions=None, meta=None\n                                                  ):\n        raise NotImplementedError",
    "docstring": "Expect column entries to be JSON objects matching a given JSON schema.\n\n        expect_column_values_to_match_json_schema is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`.\n\n        Args:\n            column (str): \\\n                The column name.\n\n        Keyword Args:\n            mostly (None or a float between 0 and 1): \\\n                Return `\"success\": True` if at least mostly percent of values match the expectation. \\\n                For more detail, see :ref:`mostly`.\n\n        Other Parameters:\n            result_format (str or None): \\\n                Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.\n                For more detail, see :ref:`result_format <result_format>`.\n            include_config (boolean): \\\n                If True, then include the expectation config as part of the result object. \\\n                For more detail, see :ref:`include_config`.\n            catch_exceptions (boolean or None): \\\n                If True, then catch exceptions and include them as part of the result object. \\\n                For more detail, see :ref:`catch_exceptions`.\n            meta (dict or None): \\\n                A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \\\n                For more detail, see :ref:`meta`.\n\n        Returns:\n            A JSON-serializable expectation result object.\n\n            Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and\n            :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.\n\n        See Also:\n            expect_column_values_to_be_json_parseable\n\n            The JSON-schema docs at: http://json-schema.org/"
  },
  {
    "code": "def cressman_point(sq_dist, values, radius):\n    r\n    weights = tools.cressman_weights(sq_dist, radius)\n    total_weights = np.sum(weights)\n    return sum(v * (w / total_weights) for (w, v) in zip(weights, values))",
    "docstring": "r\"\"\"Generate a Cressman interpolation value for a point.\n\n    The calculated value is based on the given distances and search radius.\n\n    Parameters\n    ----------\n    sq_dist: (N, ) ndarray\n        Squared distance between observations and grid point\n    values: (N, ) ndarray\n        Observation values in same order as sq_dist\n    radius: float\n        Maximum distance to search for observations to use for\n        interpolation.\n\n    Returns\n    -------\n    value: float\n        Interpolation value for grid point."
  },
  {
    "code": "def matrix_transpose(m):\n    num_cols = len(m)\n    num_rows = len(m[0])\n    m_t = []\n    for i in range(num_rows):\n        temp = []\n        for j in range(num_cols):\n            temp.append(m[j][i])\n        m_t.append(temp)\n    return m_t",
    "docstring": "Transposes the input matrix.\n\n    The input matrix :math:`m` is a 2-dimensional array.\n\n    :param m: input matrix with dimensions :math:`(n \\\\times m)`\n    :type m: list, tuple\n    :return: transpose matrix with dimensions :math:`(m \\\\times n)`\n    :rtype: list"
  },
  {
    "code": "def parse(self, rrstr):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('NM record already initialized!')\n        (su_len, su_entry_version_unused, self.posix_name_flags) = struct.unpack_from('=BBB', rrstr[:5], 2)\n        name_len = su_len - 5\n        if (self.posix_name_flags & 0x7) not in (0, 1, 2, 4):\n            raise pycdlibexception.PyCdlibInvalidISO('Invalid Rock Ridge NM flags')\n        if name_len != 0:\n            if (self.posix_name_flags & (1 << 1)) or (self.posix_name_flags & (1 << 2)) or (self.posix_name_flags & (1 << 5)):\n                raise pycdlibexception.PyCdlibInvalidISO('Invalid name in Rock Ridge NM entry (0x%x %d)' % (self.posix_name_flags, name_len))\n            self.posix_name += rrstr[5:5 + name_len]\n        self._initialized = True",
    "docstring": "Parse a Rock Ridge Alternate Name record out of a string.\n\n        Parameters:\n         rrstr - The string to parse the record out of.\n        Returns:\n         Nothing."
  },
  {
    "code": "def poly_to_power_basis(bezier_coeffs):\n    num_coeffs, = bezier_coeffs.shape\n    if num_coeffs == 1:\n        return bezier_coeffs\n    elif num_coeffs == 2:\n        coeff0, coeff1 = bezier_coeffs\n        return np.asfortranarray([coeff0, coeff1 - coeff0])\n    elif num_coeffs == 3:\n        coeff0, coeff1, coeff2 = bezier_coeffs\n        return np.asfortranarray(\n            [coeff0, 2.0 * (coeff1 - coeff0), coeff2 - 2.0 * coeff1 + coeff0]\n        )\n    elif num_coeffs == 4:\n        coeff0, coeff1, coeff2, coeff3 = bezier_coeffs\n        return np.asfortranarray(\n            [\n                coeff0,\n                3.0 * (coeff1 - coeff0),\n                3.0 * (coeff2 - 2.0 * coeff1 + coeff0),\n                coeff3 - 3.0 * coeff2 + 3.0 * coeff1 - coeff0,\n            ]\n        )\n    else:\n        raise _helpers.UnsupportedDegree(\n            num_coeffs - 1, supported=(0, 1, 2, 3)\n        )",
    "docstring": "Convert a B |eacute| zier curve to polynomial in power basis.\n\n    .. note::\n\n       This assumes, but does not verify, that the \"B |eacute| zier\n       degree\" matches the true degree of the curve. Callers can\n       guarantee this by calling :func:`.full_reduce`.\n\n    Args:\n        bezier_coeffs (numpy.ndarray): A 1D array of coefficients in\n            the Bernstein basis.\n\n    Returns:\n        numpy.ndarray: 1D array of coefficients in monomial basis.\n\n    Raises:\n        .UnsupportedDegree: If the degree of the curve is not among\n            0, 1, 2 or 3."
  },
  {
    "code": "def geo_point_n(arg, n):\n    op = ops.GeoPointN(arg, n)\n    return op.to_expr()",
    "docstring": "Return the Nth point in a single linestring in the geometry.\n    Negative values are counted backwards from the end of the LineString,\n    so that -1 is the last point. Returns NULL if there is no linestring in\n    the geometry\n\n    Parameters\n    ----------\n    arg : geometry\n    n : integer\n\n    Returns\n    -------\n    PointN : geometry scalar"
  },
  {
    "code": "def deprecated(func, msg='', *args, **kw):\n    msg = '%s.%s has been deprecated. %s' % (\n        func.__module__, func.__name__, msg)\n    if not hasattr(func, 'called'):\n        warnings.warn(msg, DeprecationWarning, stacklevel=2)\n        func.called = 0\n    func.called += 1\n    return func(*args, **kw)",
    "docstring": "A family of decorators to mark deprecated functions.\n\n    :param msg:\n        the message to print the first time the\n        deprecated function is used.\n\n    Here is an example of usage:\n\n    >>> @deprecated(msg='Use new_function instead')\n    ... def old_function():\n    ...     'Do something'\n\n    Notice that if the function is called several time, the deprecation\n    warning will be displayed only the first time."
  },
  {
    "code": "def remove_by_tag(self, tag):\n        obj = self.find_obj_by_tag(tag)\n        if obj != None:\n            self.remove_obj(obj)\n            return True\n        return False",
    "docstring": "Remove the first encountered object with the specified tag from the world.\n        Returns true if an object was found and removed.\n        Returns false if no object could be removed."
  },
  {
    "code": "def _encoder(self, obj):\n        return {'__class__': obj.__class__.__name__,\n                'ident': obj.ident,\n                'group': obj.group,\n                'name': obj.name,\n                'ctype': obj.ctype,\n                'pytype': obj.pytype,\n                'access': obj.access}\n        raise TypeError(repr(obj) + ' is not JSON serializable')",
    "docstring": "Encode a toc element leaf-node"
  },
  {
    "code": "def get_offset(self):\n        return self.p1.y-self.get_slope()*self.p1.x",
    "docstring": "Get the offset t of this line segment."
  },
  {
    "code": "def make_roi(cls, sources=None):\n        if sources is None:\n            sources = {}\n        src_fact = cls()\n        src_fact.add_sources(sources)\n        ret_model = roi_model.ROIModel(\n            {}, skydir=SkyCoord(0.0, 0.0, unit='deg'))\n        for source in src_fact.sources.values():\n            ret_model.load_source(source,\n                                  build_index=False, merge_sources=False)\n        return ret_model",
    "docstring": "Build and return a `fermipy.roi_model.ROIModel` object from\n        a dict with information about the sources"
  },
  {
    "code": "def show_instance(name=None, instance_id=None, call=None, kwargs=None):\n    if not name and call == 'action':\n        raise SaltCloudSystemExit(\n            'The show_instance action requires a name.'\n        )\n    if call == 'function':\n        name = kwargs.get('name', None)\n        instance_id = kwargs.get('instance_id', None)\n    if not name and not instance_id:\n        raise SaltCloudSystemExit(\n            'The show_instance function requires '\n            'either a name or an instance_id'\n        )\n    node = _get_node(name=name, instance_id=instance_id)\n    __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)\n    return node",
    "docstring": "Show the details from EC2 concerning an AMI.\n\n    Can be called as an action (which requires a name):\n\n    .. code-block:: bash\n\n        salt-cloud -a show_instance myinstance\n\n    ...or as a function (which requires either a name or instance_id):\n\n    .. code-block:: bash\n\n        salt-cloud -f show_instance my-ec2 name=myinstance\n        salt-cloud -f show_instance my-ec2 instance_id=i-d34db33f"
  },
  {
    "code": "def _extract(self, raw: str, station: str) -> str:\n        report = raw[raw.find(station.upper() + ' '):]\n        report = report[:report.find(' =')]\n        return report",
    "docstring": "Extracts the reports message using string finding"
  },
  {
    "code": "def find_matlab_version(process_path):\n    bin_path = os.path.dirname(process_path)\n    matlab_path = os.path.dirname(bin_path)\n    matlab_dir_name = os.path.basename(matlab_path)\n    version = matlab_dir_name\n    if not is_linux():\n        version = matlab_dir_name.replace('MATLAB_', '').replace('.app', '')\n    if not is_valid_release_version(version):\n        return None\n    return version",
    "docstring": "Tries to guess matlab's version according to its process path.\n\n    If we couldn't gues the version, None is returned."
  },
  {
    "code": "def _is_intrinsic_dict(self, input):\n        return isinstance(input, dict) \\\n            and len(input) == 1 \\\n            and list(input.keys())[0] in self.supported_intrinsics",
    "docstring": "Can the input represent an intrinsic function in it?\n\n        :param input: Object to be checked\n        :return: True, if the input contains a supported intrinsic function.  False otherwise"
  },
  {
    "code": "def filter(self, media_type, **params):\n        mtype, msubtype = self._split_media_type(media_type)\n        for x in self.__iter__():\n            matched = True\n            for k, v in params.items():\n                if x[2].get(k, None) != v:\n                    matched = False\n                    break\n            if matched:\n                if x[0][0] == '*':\n                    if x[0][1] == '*':\n                        yield x\n                    elif x[0][1] == msubtype:\n                        yield x\n                elif mtype == '*':\n                    if msubtype == '*':\n                        yield x\n                    elif x[0][1] == msubtype:\n                        yield x\n                elif x[0][0] == mtype:\n                    if msubtype == '*':\n                        yield x\n                    elif x[0][1] == '*':\n                        yield x\n                    elif x[0][1] == msubtype:\n                        yield x",
    "docstring": "iterate all the accept media types that match media_type\n\n        media_type -- string -- the media type to filter by\n        **params -- dict -- further filter by key: val\n\n        return -- generator -- yields all matching media type info things"
  },
  {
    "code": "def unescape(cls, text: str) -> str:\n        chop = text.split(\"\\\\\", 1)\n        try:\n            return (chop[0] if len(chop) == 1\n                    else chop[0] + cls.unescape_map[chop[1][0]] +\n                    cls.unescape(chop[1][1:]))\n        except KeyError:\n            raise InvalidArgument(text) from None",
    "docstring": "Replace escape sequence with corresponding characters.\n\n        Args:\n            text: Text to unescape."
  },
  {
    "code": "def get_message(self):\n        try:\n            m = self.get_from_backend()\n            if m and m[\"type\"] not in SKIP_TYPES:\n                return self.decrypt(m[\"data\"])\n        except AttributeError:\n            raise Exception(\"Tried to call get message without having subscribed first!\")\n        except (KeyboardInterrupt, SystemExit):\n            pass\n        except:\n            logging.critical(\"Error in watching pubsub get message: \\n%s\" % traceback.format_exc())\n        return None",
    "docstring": "Gets the latest object from the backend, and handles unpickling\n        and validation."
  },
  {
    "code": "def update_parser(self, parser):\n        self._parser = parser\n        ini_str = argparse_to_ini(parser)\n        configp = configparser.ConfigParser(allow_no_value=True)\n        configp.read_dict(self._config)\n        configp.read_string(ini_str)\n        self._config.update(\n            {s: dict(configp.items(s))\n             for s in configp.sections()}\n        )",
    "docstring": "Update config dictionary with declared arguments in an argparse.parser\n        New variables will be created, and existing ones overridden.\n\n        Args:\n            parser (argparse.ArgumentParser): parser to read variables from"
  },
  {
    "code": "def cd_previous(self):\n        if self._prev_dir is None or isinstance(self._prev_dir, ROOT.TROOT):\n            return False\n        if isinstance(self._prev_dir, ROOT.TFile):\n            if self._prev_dir.IsOpen() and self._prev_dir.IsWritable():\n                self._prev_dir.cd()\n                return True\n            return False\n        if not self._prev_dir.IsWritable():\n            return False\n        prev_file = self._prev_dir.GetFile()\n        if prev_file and prev_file.IsOpen():\n            self._prev_dir.cd()\n            return True\n        return False",
    "docstring": "cd to the gDirectory before this file was open."
  },
  {
    "code": "def _detach_received(self, error):\n        if error:\n            condition = error.condition\n            description = error.description\n            info = error.info\n        else:\n            condition = b\"amqp:unknown-error\"\n            description = None\n            info = None\n        self._error = errors._process_link_error(self.error_policy, condition, description, info)\n        _logger.info(\"Received Link detach event: %r\\nLink: %r\\nDescription: %r\"\n                     \"\\nDetails: %r\\nRetryable: %r\\nConnection: %r\",\n                     condition, self.name, description, info, self._error.action.retry,\n                     self._session._connection.container_id)",
    "docstring": "Callback called when a link DETACH frame is received.\n        This callback will process the received DETACH error to determine if\n        the link is recoverable or whether it should be shutdown.\n\n        :param error: The error information from the detach\n         frame.\n        :type error: ~uamqp.errors.ErrorResponse"
  },
  {
    "code": "def any2mb(s):\n    if is_string(s):\n        return int(Memory.from_string(s).to(\"Mb\"))\n    else:\n        return int(s)",
    "docstring": "Convert string or number to memory in megabytes."
  },
  {
    "code": "def impersonate_sid(sid, session_id=None, privs=None):\n    for tok in enumerate_tokens(sid, session_id, privs):\n        tok = dup_token(tok)\n        elevate_token(tok)\n        if win32security.ImpersonateLoggedOnUser(tok) == 0:\n            raise WindowsError(\"Impersonation failure\")\n        return tok\n    raise WindowsError(\"Impersonation failure\")",
    "docstring": "Find an existing process token for the given sid and impersonate the token."
  },
  {
    "code": "def send_packet(self, packet, protocol='json', time_precision=None):\n        if protocol == 'json':\n            data = make_lines(packet, time_precision).encode('utf-8')\n        elif protocol == 'line':\n            data = ('\\n'.join(packet) + '\\n').encode('utf-8')\n        self.udp_socket.sendto(data, (self._host, self._udp_port))",
    "docstring": "Send an UDP packet.\n\n        :param packet: the packet to be sent\n        :type packet: (if protocol is 'json') dict\n                      (if protocol is 'line') list of line protocol strings\n        :param protocol: protocol of input data, either 'json' or 'line'\n        :type protocol: str\n        :param time_precision: Either 's', 'm', 'ms' or 'u', defaults to None\n        :type time_precision: str"
  },
  {
    "code": "def update_active(self):\n        if self.active is not None:\n            self.update_state(self.active, \"normal\")\n        if self.current_iid == self.active:\n            self._active = None\n            return\n        self._active = self.current_iid\n        if self.active is not None:\n            self.update_state(self.active, \"active\")",
    "docstring": "Update the active marker on the marker Canvas"
  },
  {
    "code": "def map(self):\n        with Pool(self.cpu_count) as pool:\n            pool.map(self._func, self._iterable)\n            pool.close()\n        return True",
    "docstring": "Perform a function on every item in an iterable."
  },
  {
    "code": "def sanitize_metadata(self, metadata, replace_hyphen_with=\"-\"):\n        return {str(k).replace(\"-\", replace_hyphen_with): str(v)\n                for k, v in (metadata or {}).items() if v is not None}",
    "docstring": "Convert non-string metadata values to strings and drop null values"
  },
  {
    "code": "def set_credential_password(self, access_id, password):\n        return self.client.call('Network_Storage_Allowed_Host', 'setCredentialPassword',\n                                password, id=access_id)",
    "docstring": "Sets the password for an access host\n\n        :param integer access_id: id of the access host\n        :param string password: password to  set"
  },
  {
    "code": "def exists(self):\n        return self.rpc_model.search_count(\n            self.domain, context=self.context\n        ) > 0",
    "docstring": "A convenience method that returns True if a record\n        satisfying the query exists"
  },
  {
    "code": "def search_all_payments(payment_status=None, page_size=20, start_cursor=None, offset=0, use_cache=True,\n                        cache_begin=True, relations=None):\n    if payment_status:\n        return PaymentsByStatusSearch(payment_status, page_size, start_cursor, offset, use_cache,\n                                      cache_begin, relations)\n    return AllPaymentsSearch(page_size, start_cursor, offset, use_cache, cache_begin, relations)",
    "docstring": "Returns a command to search all payments ordered by creation desc\n    @param payment_status: The payment status. If None is going to return results independent from status\n    @param page_size: number of payments per page\n    @param start_cursor: cursor to continue the search\n    @param offset: offset number of payment on search\n    @param use_cache: indicates with should use cache or not for results\n    @param cache_begin: indicates with should use cache on beginning or not for results\n    @param relations: list of relations to bring with payment objects. possible values on list: logs, pay_items, owner\n    @return: Returns a command to search all payments ordered by creation desc"
  },
  {
    "code": "def keep_(self, *cols) -> \"Ds\":\n        try:\n            ds2 = self._duplicate_(self.df[list(cols)])\n        except Exception as e:\n            self.err(e, \"Can not remove colums\")\n            return\n        self.ok(\"Columns\", \" ,\".join(cols), \"kept\")\n        return ds2",
    "docstring": "Returns a dataswim instance with a dataframe limited\n        to some columns\n\n        :param cols: names of the columns\n        :type cols: str\n        :return: a dataswim instance\n        :rtype: Ds\n\n        :example: ``ds2 = ds.keep_(\"Col 1\", \"Col 2\")``"
  },
  {
    "code": "def serialize_with_sampled_logs(self, logs_limit=-1):\n        return {\n            'id': self.id,\n            'pathName': self.path_name,\n            'name': self.name,\n            'isUnregistered': self.is_unregistered,\n            'logs': [log.serialize for log in self.sampled_logs(logs_limit)],\n            'args': self.args.serialize if self.args is not None else [],\n            'commands': [cmd.serialize for cmd in self.commands],\n            'snapshots': [cmd.serialize for cmd in self.snapshots],\n            'logModifiedAt': self.log_modified_at.isoformat()\n        }",
    "docstring": "serialize a result with up to `logs_limit` logs.\n\n        If `logs_limit` is -1, this function will return a result with all its\n        logs."
  },
  {
    "code": "def recursive_refs(envs, name):\n    refs_by_name = {\n        env['name']: set(env['refs'])\n        for env in envs\n    }\n    refs = refs_by_name[name]\n    if refs:\n        indirect_refs = set(itertools.chain.from_iterable([\n            recursive_refs(envs, ref)\n            for ref in refs\n        ]))\n    else:\n        indirect_refs = set()\n    return set.union(refs, indirect_refs)",
    "docstring": "Return set of recursive refs for given env name\n\n    >>> local_refs = sorted(recursive_refs([\n    ...     {'name': 'base', 'refs': []},\n    ...     {'name': 'test', 'refs': ['base']},\n    ...     {'name': 'local', 'refs': ['test']},\n    ... ], 'local'))\n    >>> local_refs == ['base', 'test']\n    True"
  },
  {
    "code": "def pipe_substr(context=None, _INPUT=None, conf=None, **kwargs):\n    conf['start'] = conf.pop('from', dict.get(conf, 'start'))\n    splits = get_splits(_INPUT, conf, **cdicts(opts, kwargs))\n    parsed = utils.dispatch(splits, *get_dispatch_funcs())\n    _OUTPUT = starmap(parse_result, parsed)\n    return _OUTPUT",
    "docstring": "A string module that returns a substring. Loopable.\n\n    Parameters\n    ----------\n    context : pipe2py.Context object\n    _INPUT : iterable of items or strings\n    conf : {\n        'from': {'type': 'number', value': <starting position>},\n        'length': {'type': 'number', 'value': <count of characters to return>}\n    }\n\n    Returns\n    -------\n    _OUTPUT : generator of substrings"
  },
  {
    "code": "def new_record(self, key, value):\n    new_record = self.get('new_record', {})\n    ids = self.get('ids', [])\n    for value in force_list(value):\n        for id_ in force_list(value.get('a')):\n            ids.append({\n                'schema': 'SPIRES',\n                'value': id_,\n            })\n        new_recid = force_single_element(value.get('d', ''))\n        if new_recid:\n            new_record = get_record_ref(new_recid, 'authors')\n    self['ids'] = ids\n    return new_record",
    "docstring": "Populate the ``new_record`` key.\n\n    Also populates the ``ids`` key through side effects."
  },
  {
    "code": "def form_invalid(self, form):\n        if self.request.is_ajax():\n            return self.render_json_response(self.get_error_result(form))\n        return super(AjaxFormMixin, self).form_invalid(form)",
    "docstring": "We have errors in the form. If ajax, return them as json.\n        Otherwise, proceed as normal."
  },
  {
    "code": "def _isLastCodeColumn(self, block, column):\n        return column >= self._lastColumn(block) or \\\n               self._isComment(block, self._nextNonSpaceColumn(block, column + 1))",
    "docstring": "Return true if the given column is at least equal to the column that\n        contains the last non-whitespace character at the given line, or if\n        the rest of the line is a comment."
  },
  {
    "code": "def _get_metrics_to_collect(self, instance_key, additional_metrics):\n        if instance_key not in self.metrics_to_collect_by_instance:\n            self.metrics_to_collect_by_instance[instance_key] = self._build_metric_list_to_collect(additional_metrics)\n        return self.metrics_to_collect_by_instance[instance_key]",
    "docstring": "Return and cache the list of metrics to collect."
  },
  {
    "code": "def filter_files(self, path):\n        excludes = r'|'.join([fnmatch.translate(x) for x in self.project.EXCLUDES]) or r'$.'\n        for root, dirs, files in os.walk(path, topdown=True):\n            dirs[:] = [d for d in dirs if not re.match(excludes, d)]\n            dirs[:] = [os.path.join(root, d) for d in dirs]\n            rel_path = os.path.relpath(root, path)\n            paths = []\n            for f in files:\n                if rel_path == '.':\n                    file_path = f\n                else:\n                    file_path = os.path.join(rel_path, f)\n                if not re.match(excludes, file_path):\n                    paths.append(f)\n            files[:] = paths\n            yield root, dirs, files",
    "docstring": "Exclude files based on blueprint and project configuration as well as hidden files."
  },
  {
    "code": "def get_as_float_with_default(self, key, default_value):\n        value = self.get(key)\n        return FloatConverter.to_float_with_default(value, default_value)",
    "docstring": "Converts map element into a float or returns default value if conversion is not possible.\n\n        :param key: an index of element to get.\n\n        :param default_value: the default value\n\n        :return: float value ot the element or default value if conversion is not supported."
  },
  {
    "code": "def get_old_filename(diff_part):\n    regexps = (\n        r'^--- a/(.*)',\n        r'^\\-\\-\\- (.*)',\n    )\n    for regexp in regexps:\n        r = re.compile(regexp, re.MULTILINE)\n        match = r.search(diff_part)\n        if match is not None:\n            return match.groups()[0]\n    raise MalformedGitDiff(\"No old filename in diff part found.  \"\n                           \"Examined diff part: {}\".format(diff_part))",
    "docstring": "Returns the filename for the original file that was changed in a diff part."
  },
  {
    "code": "def _is_sparse(x):\n  return (\n      isinstance(x, (tf.SparseTensor, tf_v1.SparseTensorValue)) or\n      (hasattr(x, \"is_sparse\") and x.is_sparse))",
    "docstring": "Returns whether x is a SparseTensor or a parsed sparse tensor info."
  },
  {
    "code": "def files():\n    if not _scanned:\n        if not module_files(sys.modules['__main__'], _process_files):\n            for module in sys.modules.values():\n                if hasattr(module, '__file__'):\n                    filename = module.__file__\n                    if filename not in _process_files:\n                        realname, modified_time = _get_filename_and_modified(filename)\n                        if realname and realname not in _process_files:\n                            _process_files[realname] = modified_time\n    return _process_files",
    "docstring": "Scan all modules in the currently running app to create a dict of all\n    files and their modified time.\n\n    @note The scan only occurs the first time this function is called.\n        Subsequent calls simply return the global dict.\n\n    @return: A dict containing filenames as keys with their modified time\n        as value"
  },
  {
    "code": "def subset(data, sel0, sel1):\n    data = np.asarray(data)\n    if data.ndim < 2:\n        raise ValueError('data must have 2 or more dimensions')\n    sel0 = asarray_ndim(sel0, 1, allow_none=True)\n    sel1 = asarray_ndim(sel1, 1, allow_none=True)\n    if sel0 is not None and sel0.dtype.kind == 'b':\n        sel0, = np.nonzero(sel0)\n    if sel1 is not None and sel1.dtype.kind == 'b':\n        sel1, = np.nonzero(sel1)\n    if sel0 is not None and sel1 is not None:\n        sel0 = sel0[:, np.newaxis]\n    if sel0 is None:\n        sel0 = _total_slice\n    if sel1 is None:\n        sel1 = _total_slice\n    return data[sel0, sel1]",
    "docstring": "Apply selections on first and second axes."
  },
  {
    "code": "def _getOccurs(self, e):\n        minOccurs = maxOccurs = '1'\n        nillable = True\n        return minOccurs,maxOccurs,nillable",
    "docstring": "return a 3 item tuple"
  },
  {
    "code": "def _remove(self, removeList, selfValue):\n        for removeValue in removeList:\n            print(removeValue, removeList)\n            removeEverything(removeValue, selfValue)",
    "docstring": "Remove elements from a list by matching the elements in the other list.\n\n        This method only looks inside current instance's value, not recursive.\n        There is no need for a recursive one anyway.\n        Match by == operation.\n\n        Args:\n            removeList (list): The list of matching elements.\n            selfValue (list): The list you remove value from. Usually ``self.value``"
  },
  {
    "code": "def append(self, item):\n        if len(self) == 0:\n            self.index = 0\n        self.items.append(item)",
    "docstring": "Adds a new item to the end of the collection."
  },
  {
    "code": "def select_group(self, group_id):\n        new_query = copy.deepcopy(self)\n        new_query._filter.group_id = group_id\n        return new_query",
    "docstring": "Copy the query and add filtering by group.\n\n        Example::\n\n            query = query.select_group('1234567')\n\n        :type group_id: str\n        :param group_id: The ID of a group to filter by.\n\n        :rtype: :class:`Query`\n        :returns: The new query object."
  },
  {
    "code": "def read_tuple(self):\n        cmd = self.read_command()\n        source = cmd[\"comp\"]\n        stream = cmd[\"stream\"]\n        values = cmd[\"tuple\"]\n        val_type = self._source_tuple_types[source].get(stream)\n        return Tuple(\n            cmd[\"id\"],\n            source,\n            stream,\n            cmd[\"task\"],\n            tuple(values) if val_type is None else val_type(*values),\n        )",
    "docstring": "Read a tuple from the pipe to Storm."
  },
  {
    "code": "def get_team_players(self, team):\n        team_id = self.team_names.get(team, None)\n        try:\n            req = self._get('teams/{}/'.format(team_id))\n            team_players = req.json()['squad']\n            if not team_players:\n                click.secho(\"No players found for this team\", fg=\"red\", bold=True)\n            else:\n                self.writer.team_players(team_players)\n        except APIErrorException:\n            click.secho(\"No data for the team. Please check the team code.\",\n                        fg=\"red\", bold=True)",
    "docstring": "Queries the API and fetches the players\n        for a particular team"
  },
  {
    "code": "def init_datastore(config):\n    if 'datastore' in config:\n        return config['datastore']\n    factory = config.pop('factory')\n    if isinstance(factory, str):\n        factory = pkg_resources.EntryPoint.parse('x=' + factory).resolve()\n    return factory(**config)",
    "docstring": "Take the config definition and initialize the datastore.\n\n    The config must contain either a 'datastore' parameter, which\n    will be simply returned, or\n    must contain a 'factory' which is a callable or entry\n    point definition. The callable should take the remainder of\n    the params in config as kwargs and return a DataStore instance."
  },
  {
    "code": "def _cast_value(value, _type):\n    if _type.upper() == 'FLOAT64':\n        return float64(value)\n    elif _type.upper() == 'FLOAT32':\n        return float32(value)\n    elif _type.upper() == 'INT32':\n        return int32(value)\n    elif _type.upper() == 'UINT16':\n        return uint16(value)\n    elif _type.upper() == 'INT16':\n        return int16(value)\n    elif _type.upper() == 'BOOLEAN':\n        return uint8(value)\n    else:\n        return float64(value)",
    "docstring": "cast value to _type"
  },
  {
    "code": "def fieldstorage(self):\n        if self._fieldstorage is None:\n            if self._body is not None:\n                raise ReadBodyTwiceError()\n            self._fieldstorage = cgi.FieldStorage(\n                environ=self._environ,\n                fp=self._environ['wsgi.input']\n            )\n        return self._fieldstorage",
    "docstring": "`cgi.FieldStorage` from `wsgi.input`."
  },
  {
    "code": "def create_activity(self, name, activity_type, start_date_local, elapsed_time,\n                        description=None, distance=None):\n        if isinstance(elapsed_time, timedelta):\n            elapsed_time = unithelper.timedelta_to_seconds(elapsed_time)\n        if isinstance(distance, Quantity):\n            distance = float(unithelper.meters(distance))\n        if isinstance(start_date_local, datetime):\n            start_date_local = start_date_local.strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n        if not activity_type.lower() in [t.lower() for t in model.Activity.TYPES]:\n            raise ValueError(\"Invalid activity type: {0}.  Possible values: {1!r}\".format(activity_type, model.Activity.TYPES))\n        params = dict(name=name, type=activity_type, start_date_local=start_date_local,\n                      elapsed_time=elapsed_time)\n        if description is not None:\n            params['description'] = description\n        if distance is not None:\n            params['distance'] = distance\n        raw_activity = self.protocol.post('/activities', **params)\n        return model.Activity.deserialize(raw_activity, bind_client=self)",
    "docstring": "Create a new manual activity.\n\n        If you would like to create an activity from an uploaded GPS file, see the\n        :meth:`stravalib.client.Client.upload_activity` method instead.\n\n        :param name: The name of the activity.\n        :type name: str\n\n        :param activity_type: The activity type (case-insensitive).\n                              Possible values: ride, run, swim, workout, hike, walk, nordicski,\n                              alpineski, backcountryski, iceskate, inlineskate, kitesurf, rollerski,\n                              windsurf, workout, snowboard, snowshoe\n        :type activity_type: str\n\n        :param start_date_local: Local date/time of activity start. (TZ info will be ignored)\n        :type start_date_local: :class:`datetime.datetime` or string in ISO8601 format.\n\n        :param elapsed_time: The time in seconds or a :class:`datetime.timedelta` object.\n        :type elapsed_time: :class:`datetime.timedelta` or int (seconds)\n\n        :param description: The description for the activity.\n        :type description: str\n\n        :param distance: The distance in meters (float) or a :class:`units.quantity.Quantity` instance.\n        :type distance: :class:`units.quantity.Quantity` or float (meters)"
  },
  {
    "code": "def ensure_unicode_string(obj):\n    try:\n        return unicode_type(obj)\n    except UnicodeDecodeError:\n        if hasattr(obj, 'decode'):\n            return obj.decode('utf-8', 'replace')\n        return str(obj).decode('utf-8', 'replace')",
    "docstring": "Return a unicode string representation of the given obj.\n\n    :param obj:\n        The obj we want to represent in unicode\n    :type obj:\n        varies\n    :rtype:\n        `unicode`"
  },
  {
    "code": "def dynamize_value(self, val):\n        def _str(val):\n            if isinstance(val, bool):\n                return str(int(val))\n            return str(val)\n        dynamodb_type = self.get_dynamodb_type(val)\n        if dynamodb_type == 'N':\n            val = {dynamodb_type : _str(val)}\n        elif dynamodb_type == 'S':\n            val = {dynamodb_type : val}\n        elif dynamodb_type == 'NS':\n            val = {dynamodb_type : [ str(n) for n in val]}\n        elif dynamodb_type == 'SS':\n            val = {dynamodb_type : [ n for n in val]}\n        return val",
    "docstring": "Take a scalar Python value and return a dict consisting\n        of the Amazon DynamoDB type specification and the value that\n        needs to be sent to Amazon DynamoDB.  If the type of the value\n        is not supported, raise a TypeError"
  },
  {
    "code": "def blacklist_token():\n    req = flask.request.get_json(force=True)\n    data = guard.extract_jwt_token(req['token'])\n    blacklist.add(data['jti'])\n    return flask.jsonify(message='token blacklisted ({})'.format(req['token']))",
    "docstring": "Blacklists an existing JWT by registering its jti claim in the blacklist.\n\n    .. example::\n       $ curl http://localhost:5000/blacklist_token -X POST \\\n         -d '{\"token\":\"<your_token>\"}'"
  },
  {
    "code": "def _get_edge_tuple(source,\n                    target,\n                    edge_data: EdgeData,\n                    ) -> Tuple[str, str, str, Optional[str], Tuple[str, Optional[Tuple], Optional[Tuple]]]:\n    return (\n        source.as_bel(),\n        target.as_bel(),\n        _get_citation_str(edge_data),\n        edge_data.get(EVIDENCE),\n        canonicalize_edge(edge_data),\n    )",
    "docstring": "Convert an edge to a consistent tuple.\n\n    :param BaseEntity source: The source BEL node\n    :param BaseEntity target: The target BEL node\n    :param edge_data: The edge's data dictionary\n    :return: A tuple that can be hashed representing this edge. Makes no promises to its structure."
  },
  {
    "code": "def _split_rules(rules):\n    split = []\n    for rule in rules:\n        cidr_ip = rule.get('cidr_ip')\n        group_name = rule.get('source_group_name')\n        group_id = rule.get('source_group_group_id')\n        if cidr_ip and not isinstance(cidr_ip, six.string_types):\n            for ip in cidr_ip:\n                _rule = rule.copy()\n                _rule['cidr_ip'] = ip\n                split.append(_rule)\n        elif group_name and not isinstance(group_name, six.string_types):\n            for name in group_name:\n                _rule = rule.copy()\n                _rule['source_group_name'] = name\n                split.append(_rule)\n        elif group_id and not isinstance(group_id, six.string_types):\n            for _id in group_id:\n                _rule = rule.copy()\n                _rule['source_group_group_id'] = _id\n                split.append(_rule)\n        else:\n            split.append(rule)\n    return split",
    "docstring": "Split rules with lists into individual rules.\n\n    We accept some attributes as lists or strings. The data we get back from\n    the execution module lists rules as individual rules. We need to split the\n    provided rules into individual rules to compare them."
  },
  {
    "code": "def create_database(self):\n        self.print_message(\"Creating database '%s'\" % self.databases['destination']['name'])\n        self.export_pgpassword('destination')\n        args = [\n            \"createdb\",\n            self.databases['destination']['name'],\n        ]\n        args.extend(self.databases['destination']['args'])\n        for arg in self.databases['destination']['args']:\n            if arg[:7] == '--user=':\n                args.append('--owner=%s' % arg[7:])\n        subprocess.check_call(args)",
    "docstring": "Create postgres database."
  },
  {
    "code": "async def write(self, writer: Any,\n                    close_boundary: bool=True) -> None:\n        if not self._parts:\n            return\n        for part, encoding, te_encoding in self._parts:\n            await writer.write(b'--' + self._boundary + b'\\r\\n')\n            await writer.write(part._binary_headers)\n            if encoding or te_encoding:\n                w = MultipartPayloadWriter(writer)\n                if encoding:\n                    w.enable_compression(encoding)\n                if te_encoding:\n                    w.enable_encoding(te_encoding)\n                await part.write(w)\n                await w.write_eof()\n            else:\n                await part.write(writer)\n            await writer.write(b'\\r\\n')\n        if close_boundary:\n            await writer.write(b'--' + self._boundary + b'--\\r\\n')",
    "docstring": "Write body."
  },
  {
    "code": "def find_deepest_user_frame(tb):\n    tb.reverse()\n    for frame in tb:\n        filename = frame[0]\n        if filename.find(os.sep+'SCons'+os.sep) == -1:\n            return frame\n    return tb[0]",
    "docstring": "Find the deepest stack frame that is not part of SCons.\n\n    Input is a \"pre-processed\" stack trace in the form\n    returned by traceback.extract_tb() or traceback.extract_stack()"
  },
  {
    "code": "def unescape(b, encoding):\n    return string_literal_re.sub(\n        lambda m: unescape_string_literal(m.group(), encoding),\n        b\n    )",
    "docstring": "Unescape all string and unicode literals in bytes."
  },
  {
    "code": "def save(self, name, content, *args, **kwargs):\n        super(ThumbnailerFieldFile, self).save(name, content, *args, **kwargs)\n        self.get_source_cache(create=True, update=True)",
    "docstring": "Save the file, also saving a reference to the thumbnail cache Source\n        model."
  },
  {
    "code": "def recordtype_row_strategy(column_names):\n    try:\n        from namedlist import namedlist as recordtype\n    except ImportError:\n        from recordtype import recordtype\n    column_names = [name if is_valid_identifier(name) else 'col%s_' % idx for idx, name in enumerate(column_names)]\n    recordtype_row_class = recordtype('Row', column_names)\n    class Row(recordtype_row_class):\n        def __getitem__(self, index):\n            if isinstance(index, slice):\n                return tuple(getattr(self, x) for x in self.__slots__[index])\n            return getattr(self, self.__slots__[index])\n        def __setitem__(self, index, value):\n            setattr(self, self.__slots__[index], value)\n    def row_factory(row):\n        return Row(*row)\n    return row_factory",
    "docstring": "Recordtype row strategy, rows returned as recordtypes\n\n    Column names that are not valid Python identifiers will be replaced\n    with col<number>_"
  },
  {
    "code": "def getspectrum(self, index):\n        mz_bytes, intensity_bytes = self.get_spectrum_as_string(index)\n        mz_array = np.frombuffer(mz_bytes, dtype=self.mzPrecision)\n        intensity_array = np.frombuffer(intensity_bytes, dtype=self.intensityPrecision)\n        return mz_array, intensity_array",
    "docstring": "Reads the spectrum at specified index from the .ibd file.\n\n        :param index:\n            Index of the desired spectrum in the .imzML file\n\n        Output:\n\n        mz_array: numpy.ndarray\n            Sequence of m/z values representing the horizontal axis of the desired mass\n            spectrum\n        intensity_array: numpy.ndarray\n            Sequence of intensity values corresponding to mz_array"
  },
  {
    "code": "def filter(criterias, devices):\n        if not criterias:\n            return devices\n        result = []\n        for device in devices:\n            for criteria_name, criteria_values in criterias.items():\n                if criteria_name in device.keys():\n                    if isinstance(device[criteria_name], list):\n                        for criteria_value in criteria_values:\n                            if criteria_value in device[criteria_name]:\n                                result.append(device)\n                                break\n                    elif isinstance(device[criteria_name], str):\n                        for criteria_value in criteria_values:\n                            if criteria_value == device[criteria_name]:\n                                result.append(device)\n                    elif isinstance(device[criteria_name], int):\n                        for criteria_value in criteria_values:\n                            if criteria_value == device[criteria_name]:\n                                result.append(device)\n                    else:\n                        continue\n        return result",
    "docstring": "Filter a device by criterias on the root level of the dictionary."
  },
  {
    "code": "def _get_span_name(servicer_context):\n    method_name = servicer_context._rpc_event.call_details.method[1:]\n    if isinstance(method_name, bytes):\n        method_name = method_name.decode('utf-8')\n    method_name = method_name.replace('/', '.')\n    return '{}.{}'.format(RECV_PREFIX, method_name)",
    "docstring": "Generates a span name based off of the gRPC server rpc_request_info"
  },
  {
    "code": "def get_main_for(self, model):\n        try:\n            return self.for_model(model).get(is_main=True)\n        except models.ObjectDoesNotExist:\n            return None",
    "docstring": "Returns main image for given model"
  },
  {
    "code": "def _OpenFile(self, path):\n    if not self._registry_file_reader:\n      return None\n    return self._registry_file_reader.Open(\n        path, ascii_codepage=self._ascii_codepage)",
    "docstring": "Opens a Windows Registry file.\n\n    Args:\n      path (str): path of the Windows Registry file.\n\n    Returns:\n      WinRegistryFile: Windows Registry file or None if not available."
  },
  {
    "code": "def comment_urlview(self):\n        data = self.get_selected_item()\n        comment = data.get('body') or data.get('text') or data.get('url_full')\n        if comment:\n            self.term.open_urlview(comment)\n        else:\n            self.term.flash()",
    "docstring": "Open the selected comment with the URL viewer"
  },
  {
    "code": "def previous_weekday(day=None, as_datetime=False):\n    if day is None:\n        day = datetime.datetime.now()\n    else:\n        day = datetime.datetime.strptime(day, '%Y-%m-%d')\n    day -= datetime.timedelta(days=1)\n    while day.weekday() > 4:\n        day -= datetime.timedelta(days=1)\n    if as_datetime:\n        return day\n    return day.strftime(\"%Y-%m-%d\")",
    "docstring": "get the most recent business day"
  },
  {
    "code": "def should_indent(code):\n    last = rem_comment(code.splitlines()[-1])\n    return last.endswith(\":\") or last.endswith(\"\\\\\") or paren_change(last) < 0",
    "docstring": "Determines whether the next line should be indented."
  },
  {
    "code": "def add_url (self, url, line=0, column=0, page=0, name=u\"\", base=None):\n        webroot = self.aggregate.config[\"localwebroot\"]\n        if webroot and url and url.startswith(u\"/\"):\n            url = webroot + url[1:]\n            log.debug(LOG_CHECK, \"Applied local webroot `%s' to `%s'.\", webroot, url)\n        super(FileUrl, self).add_url(url, line=line, column=column, page=page, name=name, base=base)",
    "docstring": "If a local webroot directory is configured, replace absolute URLs\n        with it. After that queue the URL data for checking."
  },
  {
    "code": "def get_nehrp_classes(self, sites):\n        classes = sorted(self.NEHRP_VS30_UPPER_BOUNDS.keys())\n        bounds = [self.NEHRP_VS30_UPPER_BOUNDS[item] for item in classes]\n        bounds = np.reshape(np.array(bounds), (-1, 1))\n        vs30s = np.reshape(sites.vs30, (1, -1))\n        site_classes = np.choose((vs30s < bounds).sum(axis=0) - 1, classes)\n        return site_classes.astype('object')",
    "docstring": "Site classification threshholds from Section 4 \"Site correction\n        coefficients\" p. 205. Note that site classes E and F are not\n        supported."
  },
  {
    "code": "def _get_hypocentral_depth_term(self, C, rup):\n        if rup.hypo_depth <= 7.0:\n            fhyp_h = 0.0\n        elif rup.hypo_depth > 20.0:\n            fhyp_h = 13.0\n        else:\n            fhyp_h = rup.hypo_depth - 7.0\n        if rup.mag <= 5.5:\n            fhyp_m = C[\"c17\"]\n        elif rup.mag > 6.5:\n            fhyp_m = C[\"c18\"]\n        else:\n            fhyp_m = C[\"c17\"] + ((C[\"c18\"] - C[\"c17\"]) * (rup.mag - 5.5))\n        return fhyp_h * fhyp_m",
    "docstring": "Returns the hypocentral depth scaling term defined in equations 21 - 23"
  },
  {
    "code": "def process_chunks(self, chunks):\n        chunk, = chunks\n        if chunk.keys:\n            self.result[chunk.keys] = chunk.data\n        else:\n            self.result[...] = chunk.data",
    "docstring": "Store the incoming chunk at the corresponding position in the\n        result array."
  },
  {
    "code": "def question_default_loader(self, pk):\n        try:\n            obj = Question.objects.get(pk=pk)\n        except Question.DoesNotExist:\n            return None\n        else:\n            self.question_default_add_related_pks(obj)\n            return obj",
    "docstring": "Load a Question from the database."
  },
  {
    "code": "def read_ipv6_route(self, length, extension):\n        if length is None:\n            length = len(self)\n        _next = self._read_protos(1)\n        _hlen = self._read_unpack(1)\n        _type = self._read_unpack(1)\n        _left = self._read_unpack(1)\n        ipv6_route = dict(\n            next=_next,\n            length=(_hlen + 1) * 8,\n            type=_ROUTING_TYPE.get(_type, 'Unassigned'),\n            seg_left=_left,\n        )\n        _dlen = _hlen * 8 - 4\n        if _dlen:\n            _func = _ROUTE_PROC.get(_type, 'none')\n            _data = eval(f'self._read_data_type_{_func}')(_dlen)\n            ipv6_route.update(_data)\n        length -= ipv6_route['length']\n        ipv6_route['packet'] = self._read_packet(header=ipv6_route['length'], payload=length)\n        if extension:\n            self._protos = None\n            return ipv6_route\n        return self._decode_next_layer(ipv6_route, _next, length)",
    "docstring": "Read Routing Header for IPv6.\n\n        Structure of IPv6-Route header [RFC 8200][RFC 5095]:\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |  Next Header  |  Hdr Ext Len  |  Routing Type | Segments Left |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |                                                               |\n            .                                                               .\n            .                       type-specific data                      .\n            .                                                               .\n            |                                                               |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n            Octets      Bits        Name                    Description\n              0           0     route.next              Next Header\n              1           8     route.length            Header Extensive Length\n              2          16     route.type              Routing Type\n              3          24     route.seg_left          Segments Left\n              4          32     route.data              Type-Specific Data"
  },
  {
    "code": "def ReadStatusBit(self, bit):\n        ' Report given status bit '\n        spi.SPI_write_byte(self.CS, 0x39)\n        spi.SPI_write_byte(self.CS, 0x00)\n        data0 = spi.SPI_read_byte()\n        spi.SPI_write_byte(self.CS, 0x00)\n        data1 = spi.SPI_read_byte()\n        if bit > 7:\n            OutputBit = (data0 >> (bit - 8)) & 1\n        else:\n            OutputBit = (data1 >> bit) & 1        \n        return OutputBit",
    "docstring": "Report given status bit"
  },
  {
    "code": "def build_command_tree(pattern, cmd_params):\n    from docopt import Either, Optional, OneOrMore, Required, Option, Command, Argument\n    if type(pattern) in [Either, Optional, OneOrMore]:\n        for child in pattern.children:\n            build_command_tree(child, cmd_params)\n    elif type(pattern) in [Required]:\n        for child in pattern.children:\n            cmd_params = build_command_tree(child, cmd_params)\n    elif type(pattern) in [Option]:\n        suffix = \"=\" if pattern.argcount else \"\"\n        if pattern.short:\n            cmd_params.options.append(pattern.short + suffix)\n        if pattern.long:\n            cmd_params.options.append(pattern.long + suffix)\n    elif type(pattern) in [Command]:\n        cmd_params = cmd_params.get_subcommand(pattern.name)\n    elif type(pattern) in [Argument]:\n        cmd_params.arguments.append(pattern.name)\n    return cmd_params",
    "docstring": "Recursively fill in a command tree in cmd_params according to a docopt-parsed \"pattern\" object."
  },
  {
    "code": "def prepare_query_params(**kwargs):\n    return [\n        (sub_key, sub_value)\n        for key, value in kwargs.items()\n        for sub_key, sub_value in expand(value, key)\n        if sub_value is not None\n    ]",
    "docstring": "Prepares given parameters to be used in querystring."
  },
  {
    "code": "def world_info(world_name, world_config=None, initial_indent=\"\", next_indent=\"  \"):\n    if world_config is None:\n        for config, _ in _iter_packages():\n            for world in config[\"maps\"]:\n                if world[\"name\"] == world_name:\n                    world_config = world\n    if world_config is None:\n        raise HolodeckException(\"Couldn't find world \" + world_name)\n    second_indent = initial_indent + next_indent\n    agent_indent = second_indent + next_indent\n    sensor_indent = agent_indent + next_indent\n    print(initial_indent, world_config[\"name\"])\n    print(second_indent, \"Resolution:\", world_config[\"window_width\"], \"x\", world_config[\"window_height\"])\n    print(second_indent, \"Agents:\")\n    for agent in world_config[\"agents\"]:\n        print(agent_indent, \"Name:\", agent[\"agent_name\"])\n        print(agent_indent, \"Type:\", agent[\"agent_type\"])\n        print(agent_indent, \"Sensors:\")\n        for sensor in agent[\"sensors\"]:\n            print(sensor_indent, sensor)",
    "docstring": "Gets and prints the information of a world.\n\n    Args:\n        world_name (str): the name of the world to retrieve information for\n        world_config (dict optional): A dictionary containing the world's configuration. Will find the config if None. Defaults to None.\n        initial_indent (str optional): This indent will apply to each output line. Defaults to \"\".\n        next_indent (str optional): This indent will be applied within each nested line. Defaults to \"  \"."
  },
  {
    "code": "def sliceit(iterable, lower=0, upper=None):\n    if upper is None:\n        upper = len(iterable)\n    try:\n        result = iterable[lower: upper]\n    except TypeError:\n        result = []\n        if lower < 0:\n            lower += len(iterable)\n        if upper < 0:\n            upper += len(iterable)\n        if upper > lower:\n            iterator = iter(iterable)\n            for index in range(upper):\n                try:\n                    value = next(iterator)\n                except StopIteration:\n                    break\n                else:\n                    if index >= lower:\n                        result.append(value)\n    iterablecls = iterable.__class__\n    if not(isinstance(result, iterablecls) or issubclass(iterablecls, dict)):\n        try:\n            result = iterablecls(result)\n        except TypeError:\n            pass\n    return result",
    "docstring": "Apply a slice on input iterable.\n\n    :param iterable: object which provides the method __getitem__ or __iter__.\n    :param int lower: lower bound from where start to get items.\n    :param int upper: upper bound from where finish to get items.\n    :return: sliced object of the same type of iterable if not dict, or specific\n        object. otherwise, simple list of sliced items.\n    :rtype: Iterable"
  },
  {
    "code": "def _printable_id_code(self):\n        code = str(self.id_code)\n        while len(code) < self._code_size:\n            code = '0' + code\n        return code",
    "docstring": "Returns the code in a printable form, filling with zeros if needed.\n\n        :return: the ID code in a printable form"
  },
  {
    "code": "def save(self):\n    req = datastore.CommitRequest()\n    req.mode = datastore.CommitRequest.NON_TRANSACTIONAL\n    req.mutations.add().upsert.CopyFrom(self.to_proto())\n    resp = datastore.commit(req)\n    if not self.id:\n      self.id = resp.mutation_results[0].key.path[-1].id\n    return self",
    "docstring": "Update or insert a Todo item."
  },
  {
    "code": "def end(self):\n        _checkErr('vend', _C.Vfinish(self._hdf_inst._id),\n                  \"cannot terminate V interface\")\n        self._hdf_inst = None",
    "docstring": "Close the V interface.\n\n        Args::\n\n          No argument\n\n        Returns::\n\n          None\n\n        C library equivalent : Vend"
  },
  {
    "code": "def _executor(self, jobGraph, stats, fileStore):\n        if stats is not None:\n            startTime = time.time()\n            startClock = getTotalCpuTime()\n        baseDir = os.getcwd()\n        yield\n        if not self.checkpoint:\n            for jobStoreFileID in Promise.filesToDelete:\n                fileStore.deleteGlobalFile(jobStoreFileID)\n        else:\n            jobGraph.checkpointFilesToDelete = list(Promise.filesToDelete)\n        Promise.filesToDelete.clear()\n        fileStore._updateJobWhenDone()\n        if os.getcwd() != baseDir:\n            os.chdir(baseDir)\n        if stats is not None:\n            totalCpuTime, totalMemoryUsage = getTotalCpuTimeAndMemoryUsage()\n            stats.jobs.append(\n                Expando(\n                    time=str(time.time() - startTime),\n                    clock=str(totalCpuTime - startClock),\n                    class_name=self._jobName(),\n                    memory=str(totalMemoryUsage)\n                )\n            )",
    "docstring": "This is the core wrapping method for running the job within a worker.  It sets up the stats\n        and logging before yielding. After completion of the body, the function will finish up the\n        stats and logging, and starts the async update process for the job."
  },
  {
    "code": "def getRecentlyUpdatedSets(self, minutesAgo):\n        params = {\n            'apiKey': self.apiKey,\n            'minutesAgo': minutesAgo\n        }\n        url = Client.ENDPOINT.format('getRecentlyUpdatedSets')\n        returned = get(url, params=params)\n        self.checkResponse(returned)\n        root = ET.fromstring(returned.text)\n        return [Build(i, self) for i in root]",
    "docstring": "Gets the information of recently updated sets.\n\n        :param int minutesAgo: The amount of time ago that the set was updated.\n        :returns: A list of Build instances that were updated within the given time.\n        :rtype: list\n        .. warning:: An empty list will be returned if there are no sets in the given time limit."
  },
  {
    "code": "def cmd_update(args):\n    markov = load(MarkovText, args.state, args)\n    read(args.input, markov, args.progress)\n    if args.output is None:\n        if args.type == SQLITE:\n            save(markov, None, args)\n        elif args.type == JSON:\n            name, ext = path.splitext(args.state)\n            tmp = name + '.tmp' + ext\n            save(markov, tmp, args)\n            replace(tmp, args.state)\n    else:\n        save(markov, args.output, args)",
    "docstring": "Update a generator.\n\n    Parameters\n    ----------\n    args : `argparse.Namespace`\n        Command arguments."
  },
  {
    "code": "def is_normalized_address(value: Any) -> bool:\n    if not is_address(value):\n        return False\n    else:\n        return value == to_normalized_address(value)",
    "docstring": "Returns whether the provided value is an address in its normalized form."
  },
  {
    "code": "def dump_config(self):\n        yaml_content = self.get_merged_config()\n        print('YAML Configuration\\n%s\\n' % yaml_content.read())\n        try:\n            self.load()\n            print('Python Configuration\\n%s\\n' % pretty(self.yamldocs))\n        except ConfigError:\n            sys.stderr.write(\n                'config parse error. try running with --logfile=/dev/tty\\n')\n            raise",
    "docstring": "Pretty print the configuration dict to stdout."
  },
  {
    "code": "def _input_to_raw_value(self, value: int) -> float:\n        return (float(value) - self.min_raw_value) / self.max_raw_value",
    "docstring": "Convert the value read from evdev to a 0.0 to 1.0 range.\n\n        :internal:\n\n        :param value:\n            a value ranging from the defined minimum to the defined maximum value.\n        :return:\n            0.0 at minimum, 1.0 at maximum, linearly interpolating between those two points."
  },
  {
    "code": "def authors_et_al(self, max_authors=5):\n        author_list = self._author_list\n        if len(author_list) <= max_authors:\n            authors_et_al = self.authors\n        else:\n            authors_et_al = \", \".join(\n                self._author_list[:max_authors]) + \", et al.\"\n        return authors_et_al",
    "docstring": "Return string with a truncated author list followed by 'et al.'"
  },
  {
    "code": "def x10(cls, housecode, unitcode):\n        if housecode.lower() in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n                                 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']:\n            byte_housecode = insteonplm.utils.housecode_to_byte(housecode)\n        else:\n            if isinstance(housecode, str):\n                _LOGGER.error('X10 house code error: %s', housecode)\n            else:\n                _LOGGER.error('X10 house code is not a string')\n            raise ValueError\n        if unitcode in range(1, 17) or unitcode in range(20, 23):\n            byte_unitcode = insteonplm.utils.unitcode_to_byte(unitcode)\n        else:\n            if isinstance(unitcode, int):\n                _LOGGER.error('X10 unit code error: %d', unitcode)\n            else:\n                _LOGGER.error('X10 unit code is not an integer 1 - 16')\n            raise ValueError\n        addr = Address(bytearray([0x00, byte_housecode, byte_unitcode]))\n        addr.is_x10 = True\n        return addr",
    "docstring": "Create an X10 device address."
  },
  {
    "code": "def setup():\n    config_name = \".wallaceconfig\"\n    config_path = os.path.join(os.path.expanduser(\"~\"), config_name)\n    if os.path.isfile(config_path):\n        log(\"Wallace config file already exists.\", chevrons=False)\n    else:\n        log(\"Creating Wallace config file at ~/.wallaceconfig...\",\n            chevrons=False)\n        wallace_module_path = os.path.dirname(os.path.realpath(__file__))\n        src = os.path.join(wallace_module_path, \"config\", config_name)\n        shutil.copyfile(src, config_path)",
    "docstring": "Walk the user though the Wallace setup."
  },
  {
    "code": "def _astype(self, dtype, **kwargs):\n        dtype = pandas_dtype(dtype)\n        if is_datetime64tz_dtype(dtype):\n            values = self.values\n            if getattr(values, 'tz', None) is None:\n                values = DatetimeIndex(values).tz_localize('UTC')\n            values = values.tz_convert(dtype.tz)\n            return self.make_block(values)\n        return super()._astype(dtype=dtype, **kwargs)",
    "docstring": "these automatically copy, so copy=True has no effect\n        raise on an except if raise == True"
  },
  {
    "code": "def stop(self):\n        with self._lock:\n            self._stop_event.set()\n            self._shell_event.clear()\n        if self._context is not None:\n            self._context.remove_service_listener(self)\n            self.clear_shell()\n            self._context = None",
    "docstring": "Clears all members"
  },
  {
    "code": "def get_log_format_types():\n    ret = dict()\n    prefix = 'logging/'\n    with salt.utils.winapi.Com():\n        try:\n            connection = wmi.WMI(namespace=_WMI_NAMESPACE)\n            objs = connection.IISLogModuleSetting()\n            for obj in objs:\n                name = six.text_type(obj.Name).replace(prefix, '', 1)\n                ret[name] = six.text_type(obj.LogModuleId)\n        except wmi.x_wmi as error:\n            _LOG.error('Encountered WMI error: %s', error.com_error)\n        except (AttributeError, IndexError) as error:\n            _LOG.error('Error getting IISLogModuleSetting: %s', error)\n    if not ret:\n        _LOG.error('Unable to get log format types.')\n    return ret",
    "docstring": "Get all available log format names and ids.\n\n    :return: A dictionary of the log format names and ids.\n    :rtype: dict\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' win_smtp_server.get_log_format_types"
  },
  {
    "code": "def newFromSites(self, sites, exclude=False):\n        if exclude:\n            sites = set(range(len(self))) - sites\n        newSequence = []\n        newStructure = []\n        for index, (base, structure) in enumerate(zip(self.sequence,\n                                                      self.structure)):\n            if index in sites:\n                newSequence.append(base)\n                newStructure.append(structure)\n        read = self.__class__(self.id, ''.join(newSequence),\n                              ''.join(newStructure))\n        return read",
    "docstring": "Create a new read from self, with only certain sites.\n\n        @param sites: A set of C{int} 0-based sites (i.e., indices) in\n            sequences that should be kept. If C{None} (the default), all sites\n            are kept.\n        @param exclude: If C{True} the C{sites} will be excluded, not\n            included."
  },
  {
    "code": "def _run_tox_env(self, env_name, extra_env_vars={}):\n        projdir = self.projdir\n        env = deepcopy(os.environ)\n        env['PATH'] = self._fixed_path(projdir)\n        env.update(extra_env_vars)\n        cmd = [os.path.join(projdir, 'bin', 'tox'), '-e', env_name]\n        logger.info(\n            'Running tox environment %s: args=\"%s\" cwd=%s '\n            'timeout=1800', env_name, ' '.join(cmd), projdir\n        )\n        res = subprocess.run(\n            cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,\n            cwd=projdir, timeout=1800, env=env\n        )\n        logger.info('tox process exited %d', res.returncode)\n        if res.returncode != 0:\n            logger.error(\n                'ERROR: tox environment %s exitcode %d',\n                env_name, res.returncode\n            )\n            logger.error(\n                'tox output:\\n%s', res.stdout.decode()\n            )\n            res.check_returncode()\n        return res.stdout.decode()",
    "docstring": "Run the specified tox environment.\n\n        :param env_name: name of the tox environment to run\n        :type env_name: str\n        :param extra_env_vars: additional variables to set in the environment\n        :type extra_env_vars: dict\n        :raises: RuntimeError\n        :returns: combined STDOUT / STDERR\n        :rtype: str"
  },
  {
    "code": "def remove_network(self, net_id):\n        url = self._url(\"/networks/{0}\", net_id)\n        res = self._delete(url)\n        self._raise_for_status(res)",
    "docstring": "Remove a network. Similar to the ``docker network rm`` command.\n\n        Args:\n            net_id (str): The network's id"
  },
  {
    "code": "def authorize(self):\n        version = self.con.makefile().readline()\n        self.con.send(version.encode())\n        self.con.recv(2)\n        self.con.send(struct.pack('>B', 1))\n        msg = self.con.recv(4)\n        response = struct.unpack(\">I\", msg)\n        if response[0] != 0:\n            log.debug(\"Failed to authorize with set-top at %s:%s.\",\n                      self.ip, self.port)\n            raise AuthenticationError()\n        self.con.send(b'0')\n        log.debug('Authorized succesfully with set-top box at %s:%s.',\n                  self.ip, self.port)",
    "docstring": "Use the magic of a unicorn and summon the set-top box to listen\n        to us.\n\n                            /\n                       ,.. /\n                     ,'   ';\n          ,,.__    _,' /';  .\n         :','  ~~~~    '. '~\n        :' (   )         )::,\n        '. '. .=----=..-~  .;'\n         '  ;'  ::   ':.  '\"\n           (:   ':    ;)\n            \\\\   '\"  ./\n             '\"      '\"\n\n        Seriously, I've no idea what I'm doing here."
  },
  {
    "code": "def reftrack_status_data(rt, role):\n    status = rt.status()\n    if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:\n        if status:\n            return status\n        else:\n            return \"Not in scene!\"",
    "docstring": "Return the data for the status\n\n    :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data\n    :type rt: :class:`jukeboxcore.reftrack.Reftrack`\n    :param role: item data role\n    :type role: QtCore.Qt.ItemDataRole\n    :returns: data for the status\n    :rtype: depending on role\n    :raises: None"
  },
  {
    "code": "def get_access_token(self,\n                         method='POST',\n                         decoder=parse_utf8_qsl,\n                         key='access_token',\n                         **kwargs):\n        r = self.get_raw_access_token(method, **kwargs)\n        access_token, = process_token_request(r, decoder, key)\n        return access_token",
    "docstring": "Returns an access token.\n\n        :param method: A string representation of the HTTP method to be used,\n            defaults to `POST`.\n        :type method: str\n        :param decoder: A function used to parse the Response content. Should\n            return a dictionary.\n        :type decoder: func\n        :param key: The key the access token will be decoded by, defaults to\n            'access_token'.\n        :type string:\n        :param \\*\\*kwargs: Optional arguments. Same as Requests.\n        :type \\*\\*kwargs: dict"
  },
  {
    "code": "def get_modules(paths, toplevel=True):\n    modules = []\n    for path in paths:\n        path = os.path.abspath(path)\n        if toplevel and path.endswith('.pyc'):\n            sys.exit('.pyc files are not supported: {0}'.format(path))\n        if os.path.isfile(path) and (path.endswith('.py') or toplevel):\n            modules.append(path)\n        elif os.path.isdir(path):\n            subpaths = [\n                os.path.join(path, filename)\n                for filename in sorted(os.listdir(path))]\n            modules.extend(get_modules(subpaths, toplevel=False))\n        elif toplevel:\n            sys.exit('Error: {0} could not be found.'.format(path))\n    return modules",
    "docstring": "Take files from the command line even if they don't end with .py."
  },
  {
    "code": "def get_responsibles_data(self, reports):\n        if not reports:\n            return []\n        recipients = []\n        recipient_names = []\n        for num, report in enumerate(reports):\n            ar = report.getAnalysisRequest()\n            report_recipient_names = []\n            responsibles = ar.getResponsible()\n            for manager_id in responsibles.get(\"ids\", []):\n                responsible = responsibles[\"dict\"][manager_id]\n                name = responsible.get(\"name\")\n                email = responsible.get(\"email\")\n                record = {\n                    \"name\": name,\n                    \"email\": email,\n                    \"valid\": True,\n                }\n                if record not in recipients:\n                    recipients.append(record)\n                report_recipient_names.append(name)\n            recipient_names.append(report_recipient_names)\n        common_names = set(recipient_names[0]).intersection(*recipient_names)\n        for recipient in recipients:\n            if recipient.get(\"name\") not in common_names:\n                recipient[\"valid\"] = False\n        return recipients",
    "docstring": "Responsibles data to be used in the template"
  },
  {
    "code": "def get_student_email(cmd_args, endpoint=''):\n    log.info(\"Attempting to get student email\")\n    if cmd_args.local:\n        return None\n    access_token = authenticate(cmd_args, endpoint=endpoint, force=False)\n    if not access_token:\n        return None\n    try:\n        return get_info(cmd_args, access_token)['email']\n    except IOError as e:\n        return None",
    "docstring": "Attempts to get the student's email. Returns the email, or None."
  },
  {
    "code": "def get_point_name(self, context):\n        metadata_table = self.parse_context(context)\n        return metadata_table.apply(self.strip_point_name, axis=1)",
    "docstring": "Get point name.\n\n        Parameters\n        ----------\n        context     : ???\n            ???\n\n        Returns\n        -------\n        ???\n            ???"
  },
  {
    "code": "def _validate_cert_chain(self, cert_chain):\n        now = datetime.utcnow()\n        if not (cert_chain.not_valid_before <= now <=\n                cert_chain.not_valid_after):\n            raise VerificationException(\"Signing Certificate expired\")\n        ext = cert_chain.extensions.get_extension_for_oid(\n            ExtensionOID.SUBJECT_ALTERNATIVE_NAME)\n        if CERT_CHAIN_DOMAIN not in ext.value.get_values_for_type(\n                DNSName):\n            raise VerificationException(\n                \"{} domain missing in Signature Certificate Chain\".format(\n                    CERT_CHAIN_DOMAIN))",
    "docstring": "Validate the certificate chain.\n\n        This method checks if the passed in certificate chain is valid,\n        i.e it is not expired and the Alexa domain is present in the\n        SAN extensions of the certificate chain. A\n        :py:class:`VerificationException` is raised if the certificate\n        chain is not valid.\n\n        :param cert_chain: Certificate chain to be validated\n        :type cert_chain: cryptography.x509.Certificate\n        :return: None\n        :raises: :py:class:`VerificationException` if certificated is\n            not valid"
  },
  {
    "code": "def key_hash(key):\n    hashed = hashlib.md5()\n    for k, v in sorted(key.items()):\n        hashed.update(str(v).encode())\n    return hashed.hexdigest()",
    "docstring": "32-byte hash used for lookup of primary keys of jobs"
  },
  {
    "code": "def extract_file_args(subparsers):\n    extract_parser = subparsers.add_parser('extract_file',\n                                           help='Extract a single secret from'\n                                           'Vault to a local file')\n    extract_parser.add_argument('vault_path',\n                                help='Full path (including key) to secret')\n    extract_parser.add_argument('destination',\n                                help='Location of destination file')\n    base_args(extract_parser)",
    "docstring": "Add the command line options for the extract_file operation"
  },
  {
    "code": "def produce(self, **kwargs):\n        key_schema = kwargs.pop('key_schema', self._key_schema)\n        value_schema = kwargs.pop('value_schema', self._value_schema)\n        topic = kwargs.pop('topic', None)\n        if not topic:\n            raise ClientError(\"Topic name not specified.\")\n        value = kwargs.pop('value', None)\n        key = kwargs.pop('key', None)\n        if value is not None:\n            if value_schema:\n                value = self._serializer.encode_record_with_schema(topic, value_schema, value)\n            else:\n                raise ValueSerializerError(\"Avro schema required for values\")\n        if key is not None:\n            if key_schema:\n                key = self._serializer.encode_record_with_schema(topic, key_schema, key, True)\n            else:\n                raise KeySerializerError(\"Avro schema required for key\")\n        super(AvroProducer, self).produce(topic, value, key, **kwargs)",
    "docstring": "Asynchronously sends message to Kafka by encoding with specified or default avro schema.\n\n            :param str topic: topic name\n            :param object value: An object to serialize\n            :param str value_schema: Avro schema for value\n            :param object key: An object to serialize\n            :param str key_schema: Avro schema for key\n\n            Plus any other parameters accepted by confluent_kafka.Producer.produce\n\n            :raises SerializerError: On serialization failure\n            :raises BufferError: If producer queue is full.\n            :raises KafkaException: For other produce failures."
  },
  {
    "code": "def log_histogram(self, step, tag, val):\n        hist = Histogram()\n        hist.add(val)\n        summary = Summary(value=[Summary.Value(tag=tag, histo=hist.encode_to_proto())])\n        self._add_event(step, summary)",
    "docstring": "Write a histogram event.\n\n        :param int step: Time step (x-axis in TensorBoard graphs)\n        :param str tag: Label for this value\n        :param numpy.ndarray val: Arbitrary-dimensional array containing\n            values to be aggregated in the resulting histogram."
  },
  {
    "code": "def clean_pdb(pdb_file, out_suffix='_clean', outdir=None, force_rerun=False,\n              remove_atom_alt=True, keep_atom_alt_id='A', remove_atom_hydrogen=True, add_atom_occ=True,\n              remove_res_hetero=True, keep_chemicals=None, keep_res_only=None,\n              add_chain_id_if_empty='X', keep_chains=None):\n    outfile = ssbio.utils.outfile_maker(inname=pdb_file,\n                                        append_to_name=out_suffix,\n                                        outdir=outdir,\n                                        outext='.pdb')\n    if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):\n        my_pdb = StructureIO(pdb_file)\n        my_cleaner = CleanPDB(remove_atom_alt=remove_atom_alt,\n                              remove_atom_hydrogen=remove_atom_hydrogen,\n                              keep_atom_alt_id=keep_atom_alt_id,\n                              add_atom_occ=add_atom_occ,\n                              remove_res_hetero=remove_res_hetero,\n                              keep_res_only=keep_res_only,\n                              add_chain_id_if_empty=add_chain_id_if_empty,\n                              keep_chains=keep_chains,\n                              keep_chemicals=keep_chemicals)\n        my_clean_pdb = my_pdb.write_pdb(out_suffix=out_suffix,\n                                        out_dir=outdir,\n                                        custom_selection=my_cleaner,\n                                        force_rerun=force_rerun)\n        return my_clean_pdb\n    else:\n        return outfile",
    "docstring": "Clean a PDB file.\n\n    Args:\n        pdb_file (str): Path to input PDB file\n        out_suffix (str): Suffix to append to original filename\n        outdir (str): Path to output directory\n        force_rerun (bool): If structure should be re-cleaned if a clean file exists already\n        remove_atom_alt (bool): Remove alternate positions\n        keep_atom_alt_id (str): If removing alternate positions, which alternate ID to keep\n        remove_atom_hydrogen (bool): Remove hydrogen atoms\n        add_atom_occ (bool): Add atom occupancy fields if not present\n        remove_res_hetero (bool): Remove all HETATMs\n        keep_chemicals (str, list): If removing HETATMs, keep specified chemical names\n        keep_res_only (str, list): Keep ONLY specified resnames, deletes everything else!\n        add_chain_id_if_empty (str): Add a chain ID if not present\n        keep_chains (str, list): Keep only these chains\n\n    Returns:\n        str: Path to cleaned PDB file"
  },
  {
    "code": "async def get_all_platforms(self) -> AsyncIterator[Platform]:\n        for name in self._classes.keys():\n            yield await self.get_platform(name)",
    "docstring": "Returns all platform instances"
  },
  {
    "code": "def build_entity_from_uri(self, uri, ontospyClass=None):\n        if not ontospyClass:\n            ontospyClass = RDF_Entity\n        elif not issubclass(ontospyClass, RDF_Entity):\n            click.secho(\"Error: <%s> is not a subclass of ontospy.RDF_Entity\" % str(ontospyClass))\n            return None\n        else:\n            pass\n        qres = self.sparqlHelper.entityTriples(uri)\n        if qres:\n            entity = ontospyClass(rdflib.URIRef(uri), None, self.namespaces)\n            entity.triples = qres\n            entity._buildGraph()\n            test = entity.getValuesForProperty(rdflib.RDF.type)\n            if test:\n                entity.rdftype = test\n                entity.rdftype_qname = [entity._build_qname(x) for x in test]\n            return entity\n        else:\n            return None",
    "docstring": "Extract RDF statements having a URI as subject, then instantiate the RDF_Entity Python object so that it can be queried further.\n\n        Passing <ontospyClass> allows to instantiate a user-defined RDF_Entity subclass.\n\n        NOTE: the entity is not attached to any index. In future version we may create an index for these (individuals?) keeping into account that any existing model entity could be (re)created this way."
  },
  {
    "code": "def request_path(request):\n    url = request.get_full_url()\n    parts = urlsplit(url)\n    path = escape_path(parts.path)\n    if not path.startswith(\"/\"):\n        path = \"/\" + path\n    return path",
    "docstring": "Path component of request-URI, as defined by RFC 2965."
  },
  {
    "code": "def wait(self, container, timeout=None, condition=None):\n        url = self._url(\"/containers/{0}/wait\", container)\n        params = {}\n        if condition is not None:\n            if utils.version_lt(self._version, '1.30'):\n                raise errors.InvalidVersion(\n                    'wait condition is not supported for API version < 1.30'\n                )\n            params['condition'] = condition\n        res = self._post(url, timeout=timeout, params=params)\n        return self._result(res, True)",
    "docstring": "Block until a container stops, then return its exit code. Similar to\n        the ``docker wait`` command.\n\n        Args:\n            container (str or dict): The container to wait on. If a dict, the\n                ``Id`` key is used.\n            timeout (int): Request timeout\n            condition (str): Wait until a container state reaches the given\n                condition, either ``not-running`` (default), ``next-exit``,\n                or ``removed``\n\n        Returns:\n            (dict): The API's response as a Python dictionary, including\n                the container's exit code under the ``StatusCode`` attribute.\n\n        Raises:\n            :py:class:`requests.exceptions.ReadTimeout`\n                If the timeout is exceeded.\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def cast_callback(value):\n        if 'T' in value:\n            value = value.replace('T', ' ')\n        return datetime.strptime(value.split('.')[0], '%Y-%m-%d %H:%M:%S')",
    "docstring": "Override `cast_callback` method."
  },
  {
    "code": "def _attempt_to_choose_formatting_pattern(self):\n        if len(self._national_number) >= _MIN_LEADING_DIGITS_LENGTH:\n            self._get_available_formats(self._national_number)\n            formatted_number = self._attempt_to_format_accrued_digits()\n            if len(formatted_number) > 0:\n                return formatted_number\n            if self._maybe_create_new_template():\n                return self._input_accrued_national_number()\n            else:\n                return self._accrued_input\n        else:\n            return self._append_national_number(self._national_number)",
    "docstring": "Attempts to set the formatting template and returns a string which\n        contains the formatted version of the digits entered so far."
  },
  {
    "code": "def db_remove(name, **connection_args):\n    if not db_exists(name, **connection_args):\n        log.info('DB \\'%s\\' does not exist', name)\n        return False\n    if name in ('mysql', 'information_scheme'):\n        log.info('DB \\'%s\\' may not be removed', name)\n        return False\n    dbc = _connect(**connection_args)\n    if dbc is None:\n        return False\n    cur = dbc.cursor()\n    s_name = quote_identifier(name)\n    qry = 'DROP DATABASE {0};'.format(s_name)\n    try:\n        _execute(cur, qry)\n    except MySQLdb.OperationalError as exc:\n        err = 'MySQL Error {0}: {1}'.format(*exc.args)\n        __context__['mysql.error'] = err\n        log.error(err)\n        return False\n    if not db_exists(name, **connection_args):\n        log.info('Database \\'%s\\' has been removed', name)\n        return True\n    log.info('Database \\'%s\\' has not been removed', name)\n    return False",
    "docstring": "Removes a databases from the MySQL server.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' mysql.db_remove 'dbname'"
  },
  {
    "code": "def trainSequences(sequences, exp, idOffset=0):\n  for seqId in sequences:\n    iterations = 3*len(sequences[seqId])\n    for p in range(iterations):\n      s = sequences.provideObjectsToLearn([seqId])\n      objectSDRs = dict()\n      objectSDRs[seqId + idOffset] = s[seqId]\n      exp.learnObjects(objectSDRs, reset=False)\n      exp.TMColumns[0].reset()\n    exp.sendReset()",
    "docstring": "Train the network on all the sequences"
  },
  {
    "code": "def onesided_cl_to_dlnl(cl):\n    alpha = 1.0 - cl\n    return 0.5 * np.power(np.sqrt(2.) * special.erfinv(1 - 2 * alpha), 2.)",
    "docstring": "Compute the delta-loglikehood values that corresponds to an\n    upper limit of the given confidence level.\n\n    Parameters\n    ----------\n    cl : float\n        Confidence level.\n\n    Returns\n    -------\n    dlnl : float\n        Delta-loglikelihood value with respect to the maximum of the\n        likelihood function."
  },
  {
    "code": "def _remove_unexpected_query_parameters(schema, req):\n    additional_properties = schema.get('addtionalProperties', True)\n    if additional_properties:\n        pattern_regexes = []\n        patterns = schema.get('patternProperties', None)\n        if patterns:\n            for regex in patterns:\n                pattern_regexes.append(re.compile(regex))\n        for param in set(req.GET.keys()):\n            if param not in schema['properties'].keys():\n                if not (list(regex for regex in pattern_regexes if\n                             regex.match(param))):\n                    del req.GET[param]",
    "docstring": "Remove unexpected properties from the req.GET."
  },
  {
    "code": "def return_value(self, *args, **kwargs):\n        self._called()\n        return self._return_value(*args, **kwargs)",
    "docstring": "Extracts the real value to be returned from the wrapping callable.\n\n        :return: The value the double should return when called."
  },
  {
    "code": "def all(self, scope=None, **kwargs):\n        path = '/runners/all'\n        query_data = {}\n        if scope is not None:\n            query_data['scope'] = scope\n        return self.gitlab.http_list(path, query_data, **kwargs)",
    "docstring": "List all the runners.\n\n        Args:\n            scope (str): The scope of runners to show, one of: specific,\n                shared, active, paused, online\n            all (bool): If True, return all the items, without pagination\n            per_page (int): Number of items to retrieve per request\n            page (int): ID of the page to return (starts with page 1)\n            as_list (bool): If set to False and no pagination option is\n                defined, return a generator instead of a list\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabListError: If the server failed to perform the request\n\n        Returns:\n            list(Runner): a list of runners matching the scope."
  },
  {
    "code": "def update(self):\n        if self.input_method == 'local':\n            stats = self.update_local()\n        elif self.input_method == 'snmp':\n            stats = self.update_snmp()\n        else:\n            stats = self.get_init_value()\n        self.stats = stats\n        return self.stats",
    "docstring": "Update CPU stats using the input method."
  },
  {
    "code": "def pull_image(self, image_name, stream=None):\n        stream_writer = stream or StreamWriter(sys.stderr)\n        try:\n            result_itr = self.docker_client.api.pull(image_name, stream=True, decode=True)\n        except docker.errors.APIError as ex:\n            LOG.debug(\"Failed to download image with name %s\", image_name)\n            raise DockerImagePullFailedException(str(ex))\n        stream_writer.write(u\"\\nFetching {} Docker container image...\".format(image_name))\n        for _ in result_itr:\n            stream_writer.write(u'.')\n            stream_writer.flush()\n        stream_writer.write(u\"\\n\")",
    "docstring": "Ask Docker to pull the container image with given name.\n\n        Parameters\n        ----------\n        image_name str\n            Name of the image\n        stream samcli.lib.utils.stream_writer.StreamWriter\n            Optional stream writer to output to. Defaults to stderr\n\n        Raises\n        ------\n        DockerImagePullFailedException\n            If the Docker image was not available in the server"
  },
  {
    "code": "def getall(self):\n        vrfs_re = re.compile(r'(?<=^vrf definition\\s)(\\w+)', re.M)\n        response = dict()\n        for vrf in vrfs_re.findall(self.config):\n            response[vrf] = self.get(vrf)\n        return response",
    "docstring": "Returns a dict object of all VRFs in the running-config\n\n        Returns:\n            A dict object of VRF attributes"
  },
  {
    "code": "def artboards(src_path):\n  pages = list_artboards(src_path)\n  artboards = []\n  for page in pages:\n    artboards.extend(page.artboards)\n  return artboards",
    "docstring": "Return artboards as a flat list"
  },
  {
    "code": "def getHourTable(date, pos):\n    table = hourTable(date, pos)\n    return HourTable(table, date)",
    "docstring": "Returns an HourTable object."
  },
  {
    "code": "def get_query_str(query: Type[QueryDict], max_length: int = 1024) -> str:\n    query_dict = query.copy()\n    query_dict.pop('password', None)\n    query_dict.pop(settings.AXES_PASSWORD_FORM_FIELD, None)\n    query_str = '\\n'.join(\n        f'{key}={value}'\n        for key, value\n        in query_dict.items()\n    )\n    return query_str[:max_length]",
    "docstring": "Turns a query dictionary into an easy-to-read list of key-value pairs.\n\n    If a field is called either ``'password'`` or ``settings.AXES_PASSWORD_FORM_FIELD`` it will be excluded.\n\n    The length of the output is limited to max_length to avoid a DoS attack via excessively large payloads."
  },
  {
    "code": "def append_var_uint32(self, value):\n        if not 0 <= value <= wire_format.UINT32_MAX:\n            raise errors.EncodeError('Value out of range: %d' % value)\n        self.append_var_uint64(value)",
    "docstring": "Appends an unsigned 32-bit integer to the internal buffer,\n        encoded as a varint."
  },
  {
    "code": "def getTimeSinceLastVsync(self):\n        fn = self.function_table.getTimeSinceLastVsync\n        pfSecondsSinceLastVsync = c_float()\n        pulFrameCounter = c_uint64()\n        result = fn(byref(pfSecondsSinceLastVsync), byref(pulFrameCounter))\n        return result, pfSecondsSinceLastVsync.value, pulFrameCounter.value",
    "docstring": "Returns the number of elapsed seconds since the last recorded vsync event. This \n        will come from a vsync timer event in the timer if possible or from the application-reported\n          time if that is not available. If no vsync times are available the function will \n          return zero for vsync time and frame counter and return false from the method."
  },
  {
    "code": "def capture_packet(self):\n        data = self.socket.recv(self._buffer_size)\n        for h in self.capture_handlers:\n            h['reads'] += 1\n            h['data_read'] += len(data)\n            d = data\n            if 'pre_write_transforms' in h:\n                for data_transform in h['pre_write_transforms']:\n                    d = data_transform(d)\n            h['logger'].write(d)",
    "docstring": "Write packet data to the logger's log file."
  },
  {
    "code": "def getAllNodeUids(self):\n        ret = { self.uid }\n        ret.update(self.getAllChildNodeUids())\n        return ret",
    "docstring": "getAllNodeUids - Returns all the unique internal IDs from getAllChildNodeUids, but also includes this tag's uid\n\n            @return set<uuid.UUID> A set of uuid objects"
  },
  {
    "code": "def is_main_variation(self) -> bool:\n        if not self.parent:\n            return True\n        return not self.parent.variations or self.parent.variations[0] == self",
    "docstring": "Checks if this node is the first variation from the point of view of its\n        parent. The root node is also in the main variation."
  },
  {
    "code": "def _read_until(infile=sys.stdin, maxchars=20, end=RS):\n    chars = []\n    read = infile.read\n    if not isinstance(end, tuple):\n        end = (end,)\n    while maxchars:\n        char = read(1)\n        if char in end:\n            break\n        chars.append(char)\n        maxchars -= 1\n    return ''.join(chars)",
    "docstring": "Read a terminal response of up to a few characters from stdin."
  },
  {
    "code": "def remove_callback(self, callback, msg_type=None):\n        if msg_type is None:\n            msg_type = self._callbacks.keys()\n        cb_keys = self._to_iter(msg_type)\n        if cb_keys is not None:\n            for msg_type_ in cb_keys:\n                try:\n                    self._callbacks[msg_type_].remove(callback)\n                except KeyError:\n                    pass\n        else:\n            self._callbacks[msg_type].remove(callback)",
    "docstring": "Remove per message type of global callback.\n\n        Parameters\n        ----------\n        callback : fn\n          Callback function\n        msg_type : int | iterable\n          Message type to remove callback from. Default `None` means global callback.\n          Iterable type removes the callback from all the message types."
  },
  {
    "code": "def stonith_create(stonith_id, stonith_device_type, stonith_device_options=None, cibfile=None):\n    return item_create(item='stonith',\n                       item_id=stonith_id,\n                       item_type=stonith_device_type,\n                       extra_args=stonith_device_options,\n                       cibfile=cibfile)",
    "docstring": "Create a stonith resource via pcs command\n\n    stonith_id\n        name for the stonith resource\n    stonith_device_type\n        name of the stonith agent fence_eps, fence_xvm f.e.\n    stonith_device_options\n        additional options for creating the stonith resource\n    cibfile\n        use cibfile instead of the live CIB for manipulation\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' pcs.stonith_create stonith_id='eps_fence' stonith_device_type='fence_eps'\n                                    stonith_device_options=\"['pcmk_host_map=node1.example.org:01;node2.example.org:02', 'ipaddr=myepsdevice.example.org', 'action=reboot', 'power_wait=5', 'verbose=1', 'debug=/var/log/pcsd/eps_fence.log', 'login=hidden', 'passwd=hoonetorg']\" cibfile='/tmp/cib_for_stonith.cib'"
  },
  {
    "code": "def v1_tag_associate(request, tags, tag):\n    tag = tag.decode('utf-8').strip()\n    assoc = dict(json.loads(request.body.read()), **{'tag': tag})\n    tags.add(assoc)",
    "docstring": "Associate an HTML element with a tag.\n\n    The association should be a JSON serialized object on the\n    request body. Here is an example association that should\n    make the object's structure clear:\n\n    .. code-block:: python\n\n        {\n            \"url\": \"http://example.com/abc/xyz?foo=bar\",\n            \"text\": \"The text the user highlighted.\",\n            \"stream_id\": \"{unix timestamp}-{md5 of url}\",\n            \"hash\": \"{nilsimsa hash of the HTML}\",\n            \"timestamp\": {unix timestamp},\n            \"xpath\": {\n                \"start_node\": \"/html/body/p[1]/text()[2]\",\n                \"start_idx\": 3,\n                \"end_node\": \"/html/body/p[1]/text()[3]\",\n                \"end_idx\": 9\n            }\n        }\n\n    All fields are required and cannot be empty or ``null``.\n\n    The tag of the association should be specified in the URL\n    and is delimited by ``//``."
  },
  {
    "code": "def getedges(fname, iddfile):\n    data, commdct, _idd_index = readidf.readdatacommdct(fname, iddfile=iddfile)\n    edges = makeairplantloop(data, commdct)\n    return edges",
    "docstring": "return the edges of the idf file fname"
  },
  {
    "code": "def gff3_to_recarray(path, attributes=None, region=None, score_fill=-1,\n                     phase_fill=-1, attributes_fill='.', tabix='tabix', dtype=None):\n    recs = list(iter_gff3(path, attributes=attributes, region=region,\n                          score_fill=score_fill, phase_fill=phase_fill,\n                          attributes_fill=attributes_fill, tabix=tabix))\n    if not recs:\n        return None\n    if dtype is None:\n        dtype = [('seqid', object),\n                 ('source', object),\n                 ('type', object),\n                 ('start', int),\n                 ('end', int),\n                 ('score', float),\n                 ('strand', object),\n                 ('phase', int)]\n        if attributes:\n            for n in attributes:\n                dtype.append((n, object))\n    a = np.rec.fromrecords(recs, dtype=dtype)\n    return a",
    "docstring": "Load data from a GFF3 into a NumPy recarray.\n\n    Parameters\n    ----------\n    path : string\n        Path to input file.\n    attributes : list of strings, optional\n        List of columns to extract from the \"attributes\" field.\n    region : string, optional\n        Genome region to extract. If given, file must be position\n        sorted, bgzipped and tabix indexed. Tabix must also be installed\n        and on the system path.\n    score_fill : int, optional\n        Value to use where score field has a missing value.\n    phase_fill : int, optional\n        Value to use where phase field has a missing value.\n    attributes_fill : object or list of objects, optional\n        Value(s) to use where attribute field(s) have a missing value.\n    tabix : string, optional\n        Tabix command.\n    dtype : dtype, optional\n        Override dtype.\n\n    Returns\n    -------\n    np.recarray"
  },
  {
    "code": "def update_workspace_attributes(namespace, workspace, attrs):\n    headers = _fiss_agent_header({\"Content-type\":  \"application/json\"})\n    uri = \"{0}workspaces/{1}/{2}/updateAttributes\".format(fcconfig.root_url,\n                                                        namespace, workspace)\n    body = json.dumps(attrs)\n    return __SESSION.patch(uri, headers=headers, data=body)",
    "docstring": "Update or remove workspace attributes.\n\n    Args:\n        namespace (str): project to which workspace belongs\n        workspace (str): Workspace name\n        attrs (list(dict)): List of update operations for workspace attributes.\n            Use the helper dictionary construction functions to create these:\n\n            _attr_set()      : Set/Update attribute\n            _attr_rem()     : Remove attribute\n            _attr_ladd()    : Add list member to attribute\n            _attr_lrem()    : Remove list member from attribute\n\n    Swagger:\n        https://api.firecloud.org/#!/Workspaces/updateAttributes"
  },
  {
    "code": "def depth(sequence, func=max, _depth=0):\n    if isinstance(sequence, dict):\n        sequence = list(sequence.values())\n    depth_list = [depth(item, func=func, _depth=_depth + 1)\n                  for item in sequence if (isinstance(item, dict) or util_type.is_listlike(item))]\n    if len(depth_list) > 0:\n        return func(depth_list)\n    else:\n        return _depth",
    "docstring": "Find the nesting depth of a nested sequence"
  },
  {
    "code": "def from_str(cls, string):\n        return cls([Literal.from_str(lit) for lit in string.split('+')])",
    "docstring": "Creates a clause from a given string.\n\n        Parameters\n        ----------\n        string: str\n             A string of the form `a+!b` which translates to `a AND NOT b`.\n\n        Returns\n        -------\n        caspo.core.clause.Clause\n            Created object instance"
  },
  {
    "code": "def get_automatic_parser(exim_id, infile):\n    adapter = getExim(exim_id)\n    if IInstrumentAutoImportInterface.providedBy(adapter):\n        return adapter.get_automatic_parser(infile)\n    parser_func = filter(lambda i: i[0] == exim_id, PARSERS)\n    parser_func = parser_func and parser_func[0][1] or None\n    if not parser_func or not hasattr(adapter, parser_func):\n        return None\n    parser_func = getattr(adapter, parser_func)\n    return parser_func(infile)",
    "docstring": "Returns the parser to be used by default for the instrument id interface\n    and results file passed in."
  },
  {
    "code": "def iter_issues(self,\n                    milestone=None,\n                    state=None,\n                    assignee=None,\n                    mentioned=None,\n                    labels=None,\n                    sort=None,\n                    direction=None,\n                    since=None,\n                    number=-1,\n                    etag=None):\n        url = self._build_url('issues', base_url=self._api)\n        params = {'assignee': assignee, 'mentioned': mentioned}\n        if milestone in ('*', 'none') or isinstance(milestone, int):\n            params['milestone'] = milestone\n        self._remove_none(params)\n        params.update(\n            issue_params(None, state, labels, sort, direction,\n                         since)\n        )\n        return self._iter(int(number), url, Issue, params, etag)",
    "docstring": "Iterate over issues on this repo based upon parameters passed.\n\n        .. versionchanged:: 0.9.0\n\n            The ``state`` parameter now accepts 'all' in addition to 'open'\n            and 'closed'.\n\n        :param int milestone: (optional), 'none', or '*'\n        :param str state: (optional), accepted values: ('all', 'open',\n            'closed')\n        :param str assignee: (optional), 'none', '*', or login name\n        :param str mentioned: (optional), user's login name\n        :param str labels: (optional), comma-separated list of labels, e.g.\n            'bug,ui,@high'\n        :param sort: (optional), accepted values:\n            ('created', 'updated', 'comments', 'created')\n        :param str direction: (optional), accepted values: ('asc', 'desc')\n        :param since: (optional), Only issues after this date will\n            be returned. This can be a `datetime` or an `ISO8601` formatted\n            date string, e.g., 2012-05-20T23:10:27Z\n        :type since: datetime or string\n        :param int number: (optional), Number of issues to return.\n            By default all issues are returned\n        :param str etag: (optional), ETag from a previous request to the same\n            endpoint\n        :returns: generator of :class:`Issue <github3.issues.issue.Issue>`\\ s"
  },
  {
    "code": "def change_directory(self, directory):\n        self._process.write(('cd %s\\n' % directory).encode())\n        if sys.platform == 'win32':\n            self._process.write((os.path.splitdrive(directory)[0] + '\\r\\n').encode())\n            self.clear()\n        else:\n            self._process.write(b'\\x0C')",
    "docstring": "Changes the current directory.\n\n        Change is made by running a \"cd\" command followed by a \"clear\" command.\n        :param directory:\n        :return:"
  },
  {
    "code": "def _sync_enter(self):\n    if hasattr(self, 'loop'):\n        loop = self.loop\n    else:\n        loop = self._client.loop\n    if loop.is_running():\n        raise RuntimeError(\n            'You must use \"async with\" if the event loop '\n            'is running (i.e. you are inside an \"async def\")'\n        )\n    return loop.run_until_complete(self.__aenter__())",
    "docstring": "Helps to cut boilerplate on async context\n    managers that offer synchronous variants."
  },
  {
    "code": "def max_or(a, b, c, d, w):\n        m = (1 << (w - 1))\n        while m != 0:\n            if (b & d & m) != 0:\n                temp = (b - m) | (m - 1)\n                if temp >= a:\n                    b = temp\n                    break\n                temp = (d - m) | (m - 1)\n                if temp >= c:\n                    d = temp\n                    break\n            m >>= 1\n        return b | d",
    "docstring": "Upper bound of result of ORing 2-intervals.\n\n        :param a: Lower bound of first interval\n        :param b: Upper bound of first interval\n        :param c: Lower bound of second interval\n        :param d: Upper bound of second interval\n        :param w: bit width\n        :return: Upper bound of ORing 2-intervals"
  },
  {
    "code": "def netmask(mask):\n    if not isinstance(mask, string_types):\n        return False\n    octets = mask.split('.')\n    if not len(octets) == 4:\n        return False\n    return ipv4_addr(mask) and octets == sorted(octets, reverse=True)",
    "docstring": "Returns True if the value passed is a valid netmask, otherwise return False"
  },
  {
    "code": "def complain(error):\n    if callable(error):\n        if DEVELOP:\n            raise error()\n    elif DEVELOP:\n        raise error\n    else:\n        logger.warn_err(error)",
    "docstring": "Raises in develop; warns in release."
  },
  {
    "code": "def generate_config(directory):\n    default_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"config.yml\")\n    target_config_path = os.path.abspath(os.path.join(directory, 'config.yml'))\n    shutil.copy(default_config, target_config_path)\n    six.print_(\"Config file has been generated in\", target_config_path)",
    "docstring": "Generate default config file"
  },
  {
    "code": "def is_in(self, search_list, pair):\n        index = -1\n        for nr, i in enumerate(search_list):\n            if(np.all(i == pair)):\n                return nr\n        return index",
    "docstring": "If pair is in search_list, return the index. Otherwise return -1"
  },
  {
    "code": "def tabFileNameChanged(self, tab):\n\t\tif tab == self.currentTab:\n\t\t\tif tab.fileName:\n\t\t\t\tself.setWindowTitle(\"\")\n\t\t\t\tif globalSettings.windowTitleFullPath:\n\t\t\t\t\tself.setWindowTitle(tab.fileName + '[*]')\n\t\t\t\tself.setWindowFilePath(tab.fileName)\n\t\t\t\tself.tabWidget.setTabText(self.ind, tab.getBaseName())\n\t\t\t\tself.tabWidget.setTabToolTip(self.ind, tab.fileName)\n\t\t\t\tQDir.setCurrent(QFileInfo(tab.fileName).dir().path())\n\t\t\telse:\n\t\t\t\tself.setWindowFilePath('')\n\t\t\t\tself.setWindowTitle(self.tr('New document') + '[*]')\n\t\t\tcanReload = bool(tab.fileName) and not self.autoSaveActive(tab)\n\t\t\tself.actionSetEncoding.setEnabled(canReload)\n\t\t\tself.actionReload.setEnabled(canReload)",
    "docstring": "Perform all UI state changes that need to be done when the\n\t\tfilename of the current tab has changed."
  },
  {
    "code": "def get_subkey(self,name):\n        subkey = Key(name,self)\n        try:\n            hkey = subkey.hkey\n        except WindowsError:\n            raise AttributeError(\"subkey '%s' does not exist\" % (name,))\n        return subkey",
    "docstring": "Retreive the subkey with the specified name.\n\n        If the named subkey is not found, AttributeError is raised;\n        this is for consistency with the attribute-based access notation."
  },
  {
    "code": "def setColor(self, color):\n        if color == 'blue':\n            self.color = 'blue'\n            self.colorCode = self.colors['blue']\n            self.colorCodeDark = self.colors['dblue']\n        elif color == 'red':\n            self.color = 'red'\n            self.colorCode = self.colors['red']\n            self.colorCodeDark = self.colors['dred']\n        elif color == 'yellow':\n            self.color = 'yellow'\n            self.colorCode = self.colors['yellow']\n            self.colorCodeDark = self.colors['dyellow']\n        elif color == 'green':\n            self.color = 'green'\n            self.colorCode = self.colors['green']\n            self.colorCodeDark = self.colors['dgreen']\n        elif color == 'wild':\n            self.wild = True\n            self.color = 'wild'\n            self.colorCodeDark = self.colors['dwild']\n            self.colorCode = self.colors['wild']",
    "docstring": "Sets Card's color and escape code."
  },
  {
    "code": "def flatten_spec(spec, prefix,joiner=\" :: \"):\n  if any(filter(operator.methodcaller(\"startswith\",\"Test\"),spec.keys())):\n    flat_spec = {}\n    for (k,v) in spec.items():\n      flat_spec.update(flatten_spec(v,prefix + joiner + k[5:]))\n    return flat_spec \n  else:\n    return {\"Test \"+prefix: spec}",
    "docstring": "Flatten a canonical specification with nesting into one without nesting.\n  When building unique names, concatenate the given prefix to the local test\n  name without the \"Test \" tag."
  },
  {
    "code": "def All(*validators):\n    @wraps(All)\n    def built(value):\n        for validator in validators:\n            value = validator(value)\n        return value\n    return built",
    "docstring": "Combines all the given validator callables into one, running all the\n    validators in sequence on the given value."
  },
  {
    "code": "def parse_partial(self, text):\n        if not isinstance(text, str):\n            raise TypeError(\n                'Can only parsing string but got {!r}'.format(text))\n        res = self(text, 0)\n        if res.status:\n            return (res.value, text[res.index:])\n        else:\n            raise ParseError(res.expected, text, res.index)",
    "docstring": "Parse the longest possible prefix of a given string.\n        Return a tuple of the result value and the rest of the string.\n        If failed, raise a ParseError."
  },
  {
    "code": "def FundamentalType(self, _type):\n        log.debug('HERE in FundamentalType for %s %s', _type, _type.name)\n        if _type.name in [\"None\", \"c_long_double_t\", \"c_uint128\", \"c_int128\"]:\n            self.enable_fundamental_type_wrappers()\n            return _type.name\n        return \"ctypes.%s\" % (_type.name)",
    "docstring": "Returns the proper ctypes class name for a fundamental type\n\n        1) activates generation of appropriate headers for\n        ## int128_t\n        ## c_long_double_t\n        2) return appropriate name for type"
  },
  {
    "code": "def execute_with_retries(retryable_function,\n                         retryable_errors,\n                         logger,\n                         human_readable_action_name='Action',\n                         nonretryable_errors=None):\n    max_retries = 10\n    attempt = 0\n    if not nonretryable_errors:\n        nonretryable_errors = ()\n    while True:\n        try:\n            return retryable_function()\n        except tuple(nonretryable_errors):\n            raise\n        except tuple(retryable_errors) as e:\n            attempt += 1\n            if attempt > max_retries:\n                raise\n            delay = 2**attempt + random.random()\n            logger.info('\"%s\" failed with error \"%s\". '\\\n                        'Retry number %s of %s in %s seconds'\n                        % (human_readable_action_name, str(e),\n                           attempt, max_retries, delay))\n            time.sleep(delay)",
    "docstring": "This attempts to execute \"retryable_function\" with exponential backoff\n    on delay time.\n    10 retries adds up to about 34 minutes total delay before the last attempt.\n    \"human_readable_action_name\" is an option input to customize retry message."
  },
  {
    "code": "def getPageImageList(self, pno):\n        if self.isClosed or self.isEncrypted:\n            raise ValueError(\"operation illegal for closed / encrypted doc\")\n        if self.isPDF:\n            return self._getPageInfo(pno, 2)\n        return []",
    "docstring": "Retrieve a list of images used on a page."
  },
  {
    "code": "def chgroups(name, groups, append=False):\n    if isinstance(groups, six.string_types):\n        groups = groups.split(',')\n    ugrps = set(list_groups(name))\n    if ugrps == set(groups):\n        return True\n    if append:\n        groups.update(ugrps)\n    cmd = ['usermod', '-G', ','.join(groups), name]\n    return __salt__['cmd.retcode'](cmd, python_shell=False) == 0",
    "docstring": "Change the groups to which a user belongs\n\n    name\n        Username to modify\n\n    groups\n        List of groups to set for the user. Can be passed as a comma-separated\n        list or a Python list.\n\n    append : False\n        Set to ``True`` to append these groups to the user's existing list of\n        groups. Otherwise, the specified groups will replace any existing\n        groups for the user.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' user.chgroups foo wheel,root True"
  },
  {
    "code": "def get_cache_key(content, **kwargs):\n    cache_key = ''\n    for key in sorted(kwargs.keys()):\n        cache_key = '{cache_key}.{key}:{value}'.format(\n            cache_key=cache_key,\n            key=key,\n            value=kwargs[key],\n        )\n    cache_key = '{content}{cache_key}'.format(\n        content=content,\n        cache_key=cache_key,\n    )\n    cache_key = cache_key.encode('utf-8', 'ignore')\n    cache_key = md5(cache_key).hexdigest()\n    cache_key = '{prefix}.{version}.{language}.{cache_key}'.format(\n        prefix=settings.ACTIVE_URL_CACHE_PREFIX,\n        version=__version__,\n        language=get_language(),\n        cache_key=cache_key\n    )\n    return cache_key",
    "docstring": "generate cache key"
  },
  {
    "code": "def sync_remote_to_local(force=\"no\"):\n    assert \"local_wp_dir\" in env, \"Missing local_wp_dir in env\"\n    if force != \"yes\":\n        message = \"This will replace your local database with your \"\\\n            \"remote, are you sure [y/n]\"\n        answer = prompt(message, \"y\")\n        if answer != \"y\":\n            logger.info(\"Sync stopped\")\n            return\n    init_tasks()\n    remote_file = \"sync_%s.sql\" % int(time.time()*1000)\n    remote_path = \"/tmp/%s\" % remote_file\n    with env.cd(paths.get_current_path()):\n        env.run(\"wp db export %s\" % remote_path)\n    local_wp_dir = env.local_wp_dir\n    local_path = \"/tmp/%s\" % remote_file\n    get(remote_path, local_path)\n    with lcd(local_wp_dir):\n        elocal(\"wp db import %s\" % local_path)\n    env.run(\"rm %s\" % remote_path)\n    elocal(\"rm %s\" % local_path)",
    "docstring": "Replace your remote db with your local\n\n    Example:\n        sync_remote_to_local:force=yes"
  },
  {
    "code": "def _hmm_command(self, input_pipe, pairs_to_run):\n        r\n        element = pairs_to_run.pop()\n        hmmsearch_cmd = self._individual_hmm_command(element[0][0],\n                                                      element[0][1],\n                                                      element[1])\n        while len(pairs_to_run) > 0:\n            element = pairs_to_run.pop()\n            hmmsearch_cmd = \"tee >(%s) | %s\" % (self._individual_hmm_command(element[0][0],\n                                                                              element[0][1],\n                                                                              element[1]),\n                                                hmmsearch_cmd)\n        hmmsearch_cmd = \"%s | %s\" % (input_pipe, hmmsearch_cmd)\n        return hmmsearch_cmd",
    "docstring": "r\"\"\"INTERNAL method for getting cmdline for running a batch of HMMs.\n\n        Parameters\n        ----------\n        input_pipe: as hmmsearch\n        pairs_to_run: list\n            list with 2 members: (1) list of hmm and output file, (2) number of\n            CPUs to use when searching\n\n        Returns\n        -------\n        A string command to be run with bash"
  },
  {
    "code": "def _download_metadata_archive(self):\n        with tempfile.NamedTemporaryFile(delete=False) as metadata_archive:\n            shutil.copyfileobj(urlopen(self.catalog_source), metadata_archive)\n        yield metadata_archive.name\n        remove(metadata_archive.name)",
    "docstring": "Makes a remote call to the Project Gutenberg servers and downloads\n        the entire Project Gutenberg meta-data catalog. The catalog describes\n        the texts on Project Gutenberg in RDF. The function returns a\n        file-pointer to the catalog."
  },
  {
    "code": "def identify_degenerate_nests(nest_spec):\n    degenerate_positions = []\n    for pos, key in enumerate(nest_spec):\n        if len(nest_spec[key]) == 1:\n            degenerate_positions.append(pos)\n    return degenerate_positions",
    "docstring": "Identify the nests within nest_spec that are degenerate, i.e. those nests\n    with only a single alternative within the nest.\n\n    Parameters\n    ----------\n    nest_spec : OrderedDict.\n        Keys are strings that define the name of the nests. Values are lists\n        of alternative ids, denoting which alternatives belong to which nests.\n        Each alternative id must only be associated with a single nest!\n\n    Returns\n    -------\n    list.\n        Will contain the positions in the list of keys from `nest_spec` that\n        are degenerate."
  },
  {
    "code": "def _initialize(self):\n        self._graph = tf.Graph()\n        with self._graph.as_default():\n            self._input_node = tf.placeholder(tf.float32, (self._batch_size, self._im_height, self._im_width, self._num_channels))\n            weights = self.build_alexnet_weights()\n            self._output_tensor = self.build_alexnet(weights)\n            self._feature_tensor = self.build_alexnet(weights, output_layer=self._feature_layer)\n            self._initialized = True",
    "docstring": "Open from caffe weights"
  },
  {
    "code": "def bind_path_fallback(self, name, folder):\n        if not len(name) or name[0] != '/' or name[-1] != '/':\n            raise ValueError(\n                \"name must start and end with '/': {0}\".format(name))\n        self._folder_masks.append((name, folder))",
    "docstring": "Adds a fallback for a given folder relative to `base_path`."
  },
  {
    "code": "def toggle_sequential_download(self, infohash_list):\n        data = self._process_infohash_list(infohash_list)\n        return self._post('command/toggleSequentialDownload', data=data)",
    "docstring": "Toggle sequential download in supplied torrents.\n\n        :param infohash_list: Single or list() of infohashes."
  },
  {
    "code": "def get_knowledge_category_id(self):\n        if not bool(self._my_map['knowledgeCategoryId']):\n            raise errors.IllegalState('this Objective has no knowledge_category')\n        else:\n            return Id(self._my_map['knowledgeCategoryId'])",
    "docstring": "Gets the grade ``Id`` associated with the knowledge dimension.\n\n        return: (osid.id.Id) - the grade ``Id``\n        raise:  IllegalState - ``has_knowledge_category()`` is ``false``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "async def cleanup(self, app):\n        self.conn.close()\n        if self.pubsub_conn:\n            self.pubsub_reader.cancel()\n            self.pubsub_conn.close()\n        await asyncio.sleep(0)",
    "docstring": "Close self connections."
  },
  {
    "code": "def _reverse_indexer(self):\n        categories = self.categories\n        r, counts = libalgos.groupsort_indexer(self.codes.astype('int64'),\n                                               categories.size)\n        counts = counts.cumsum()\n        result = (r[start:end] for start, end in zip(counts, counts[1:]))\n        result = dict(zip(categories, result))\n        return result",
    "docstring": "Compute the inverse of a categorical, returning\n        a dict of categories -> indexers.\n\n        *This is an internal function*\n\n        Returns\n        -------\n        dict of categories -> indexers\n\n        Example\n        -------\n        In [1]: c = pd.Categorical(list('aabca'))\n\n        In [2]: c\n        Out[2]:\n        [a, a, b, c, a]\n        Categories (3, object): [a, b, c]\n\n        In [3]: c.categories\n        Out[3]: Index(['a', 'b', 'c'], dtype='object')\n\n        In [4]: c.codes\n        Out[4]: array([0, 0, 1, 2, 0], dtype=int8)\n\n        In [5]: c._reverse_indexer()\n        Out[5]: {'a': array([0, 1, 4]), 'b': array([2]), 'c': array([3])}"
  },
  {
    "code": "def acquire(self, signal=True):\n        if not self.needs_lock:\n            return\n        with self.synclock:\n            while not self.lock.acquire(False):\n                self.synclock.wait()\n            if signal:\n                self.acquired_event(self)\n            self.synclock.notify_all()",
    "docstring": "Locks the account.\n        Method has no effect if the constructor argument `needs_lock`\n        wsa set to False.\n\n        :type signal: bool\n        :param signal: Whether to emit the acquired_event signal."
  },
  {
    "code": "def _get_split_tasks(args, split_fn, file_key, outfile_i=-1):\n    split_args = []\n    combine_map = {}\n    finished_map = collections.OrderedDict()\n    extras = []\n    for data in args:\n        out_final, out_parts = split_fn(data)\n        for parts in out_parts:\n            split_args.append([utils.deepish_copy(data)] + list(parts))\n        for part_file in [x[outfile_i] for x in out_parts]:\n            combine_map[part_file] = out_final\n        if len(out_parts) == 0:\n            if out_final is not None:\n                if out_final not in finished_map:\n                    data[file_key] = out_final\n                    finished_map[out_final] = [data]\n                else:\n                    extras.append([data])\n            else:\n                extras.append([data])\n    return split_args, combine_map, list(finished_map.values()), extras",
    "docstring": "Split up input files and arguments, returning arguments for parallel processing.\n\n    outfile_i specifies the location of the output file in the arguments to\n    the processing function. Defaults to the last item in the list."
  },
  {
    "code": "def find_inherited_key_completions(rootpath, root_env):\n  tup = inflate_context_tuple(rootpath, root_env)\n  if isinstance(tup, runtime.CompositeTuple):\n    keys = set(k for t in tup.tuples[:-1] for k in t.keys())\n    return {n: get_completion(tup, n) for n in keys}\n  return {}",
    "docstring": "Return completion keys from INHERITED tuples.\n\n  Easiest way to get those is to evaluate the tuple, check if it is a CompositeTuple,\n  then enumerate the keys that are NOT in the rightmost tuple."
  },
  {
    "code": "def getitem_in(obj, name):\n    for part in name.split('.'):\n        obj = obj[part]\n    return obj",
    "docstring": "Finds a key in @obj via a period-delimited string @name.\n        @obj: (#dict)\n        @name: (#str) |.|-separated keys to search @obj in\n        ..\n            obj = {'foo': {'bar': {'baz': True}}}\n            getitem_in(obj, 'foo.bar.baz')\n        ..\n        |True|"
  },
  {
    "code": "def share(self, auth, resource, options={}, defer=False):\n        return self._call('share', auth, [resource, options], defer)",
    "docstring": "Generates a share code for the given resource.\n\n        Args:\n            auth: <cik>\n            resource: The identifier of the resource.\n            options: Dictonary of options."
  },
  {
    "code": "def check_version(ctx, param, value):\n    if ctx.resilient_parsing:\n        return\n    if not value and ctx.invoked_subcommand != 'run':\n        ctx.call_on_close(_check_version)",
    "docstring": "Check for latest version of renku on PyPI."
  },
  {
    "code": "def list_roles():\n    for role in lib.get_roles():\n        margin_left = lib.get_margin(len(role['fullname']))\n        print(\"{0}{1}{2}\".format(\n            role['fullname'], margin_left,\n            role.get('description', '(no description)')))",
    "docstring": "Show a list of all available roles"
  },
  {
    "code": "def remove(self):\n        from fs.errors import ResourceNotFoundError\n        try:\n            self._fs.remove(self.file_name)\n        except ResourceNotFoundError:\n            pass",
    "docstring": "Removes file from filesystem."
  },
  {
    "code": "def fundamental_frequency(s,FS):\n    s = s - mean(s)\n    f, fs = plotfft(s, FS, doplot=False)\n    fs = fs[1:int(len(fs) / 2)]\n    f = f[1:int(len(f) / 2)]\n    cond = find(f > 0.5)[0]\n    bp = bigPeaks(fs[cond:], 0)\n    if bp==[]:\n        f0=0\n    else:\n        bp = bp + cond\n        f0 = f[min(bp)]\n    return f0",
    "docstring": "Compute fundamental frequency along the specified axes.\n\n    Parameters\n    ----------\n    s: ndarray\n        input from which fundamental frequency is computed.\n    FS: int\n        sampling frequency    \n    Returns\n    -------\n    f0: int\n       its integer multiple best explain the content of the signal spectrum."
  },
  {
    "code": "def get_ip(request, real_ip_only=False, right_most_proxy=False):\n    best_matched_ip = None\n    warnings.warn('get_ip is deprecated and will be removed in 3.0.', DeprecationWarning)\n    for key in defs.IPWARE_META_PRECEDENCE_ORDER:\n        value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip()\n        if value is not None and value != '':\n            ips = [ip.strip().lower() for ip in value.split(',')]\n            if right_most_proxy and len(ips) > 1:\n                ips = reversed(ips)\n            for ip_str in ips:\n                if ip_str and is_valid_ip(ip_str):\n                    if not ip_str.startswith(NON_PUBLIC_IP_PREFIX):\n                        return ip_str\n                    if not real_ip_only:\n                        loopback = defs.IPWARE_LOOPBACK_PREFIX\n                        if best_matched_ip is None:\n                            best_matched_ip = ip_str\n                        elif best_matched_ip.startswith(loopback) and not ip_str.startswith(loopback):\n                            best_matched_ip = ip_str\n    return best_matched_ip",
    "docstring": "Returns client's best-matched ip-address, or None\n    @deprecated - Do not edit"
  },
  {
    "code": "def search_by_release(self, release_id, limit=0, order_by=None, sort_order=None, filter=None):\n        url = \"%s/release/series?release_id=%d\" % (self.root_url, release_id)\n        info = self.__get_search_results(url, limit, order_by, sort_order, filter)\n        if info is None:\n            raise ValueError('No series exists for release id: ' + str(release_id))\n        return info",
    "docstring": "Search for series that belongs to a release id. Returns information about matching series in a DataFrame.\n\n        Parameters\n        ----------\n        release_id : int\n            release id, e.g., 151\n        limit : int, optional\n            limit the number of results to this value. If limit is 0, it means fetching all results without limit.\n        order_by : str, optional\n            order the results by a criterion. Valid options are 'search_rank', 'series_id', 'title', 'units', 'frequency',\n            'seasonal_adjustment', 'realtime_start', 'realtime_end', 'last_updated', 'observation_start', 'observation_end',\n            'popularity'\n        sort_order : str, optional\n            sort the results by ascending or descending order. Valid options are 'asc' or 'desc'\n        filter : tuple, optional\n            filters the results. Expects a tuple like (filter_variable, filter_value).\n            Valid filter_variable values are 'frequency', 'units', and 'seasonal_adjustment'\n\n        Returns\n        -------\n        info : DataFrame\n            a DataFrame containing information about the matching Fred series"
  },
  {
    "code": "def __set_values(self, values):\n        array = tuple(tuple(self._clean_value(col) for col in row) for row in values)\n        self._get_target().setDataArray(array)",
    "docstring": "Sets values in this cell range from an iterable of iterables."
  },
  {
    "code": "def __prepare_namespaces(self):\n        self.namespaces = dict(\n            text=\"urn:text\",\n            draw=\"urn:draw\",\n            table=\"urn:table\",\n            office=\"urn:office\",\n            xlink=\"urn:xlink\",\n            svg=\"urn:svg\",\n            manifest=\"urn:manifest\",\n        )\n        for tree_root in self.tree_roots:\n            self.namespaces.update(tree_root.nsmap)\n        self.namespaces.pop(None, None)\n        self.namespaces['py'] = GENSHI_URI\n        self.namespaces['py3o'] = PY3O_URI",
    "docstring": "create proper namespaces for our document"
  },
  {
    "code": "def _write_sample_config(run_folder, ldetails):\n    out_file = os.path.join(run_folder, \"%s.yaml\" % os.path.basename(run_folder))\n    with open(out_file, \"w\") as out_handle:\n        fc_name, fc_date = flowcell.parse_dirname(run_folder)\n        out = {\"details\": sorted([_prepare_sample(x, run_folder) for x in ldetails],\n                                 key=operator.itemgetter(\"name\", \"description\")),\n               \"fc_name\": fc_name,\n               \"fc_date\": fc_date}\n        yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)\n    return out_file",
    "docstring": "Generate a bcbio-nextgen YAML configuration file for processing a sample."
  },
  {
    "code": "def negotiate_encoding (self):\n        try:\n            features = self.url_connection.sendcmd(\"FEAT\")\n        except ftplib.error_perm as msg:\n            log.debug(LOG_CHECK, \"Ignoring error when getting FTP features: %s\" % msg)\n            pass\n        else:\n            log.debug(LOG_CHECK, \"FTP features %s\", features)\n            if \" UTF-8\" in features.splitlines():\n                self.filename_encoding = \"utf-8\"",
    "docstring": "Check if server can handle UTF-8 encoded filenames.\n        See also RFC 2640."
  },
  {
    "code": "def open_external_file(self, fname):\r\n        fname = encoding.to_unicode_from_fs(fname)\r\n        if osp.isfile(fname):\r\n            self.open_file(fname, external=True)\r\n        elif osp.isfile(osp.join(CWD, fname)):\r\n            self.open_file(osp.join(CWD, fname), external=True)",
    "docstring": "Open external files that can be handled either by the Editor or the\r\n        variable explorer inside Spyder."
  },
  {
    "code": "def clear_cycle_mrkrs(self, test=False):\n        if not test:\n            msgBox = QMessageBox(QMessageBox.Question, 'Clear Cycle Markers',\n                                 'Are you sure you want to remove all cycle '\n                                 'markers for this rater?')\n            msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)\n            msgBox.setDefaultButton(QMessageBox.Yes)\n            response = msgBox.exec_()\n            if response == QMessageBox.No:\n                return\n        self.annot.clear_cycles()\n        self.parent.overview.display()\n        self.parent.overview.display_annotations()",
    "docstring": "Remove all cycle markers."
  },
  {
    "code": "def parameters_to_datetime(self, p):\n        dt = p[self._param_name]\n        return datetime(dt.year, dt.month, dt.day)",
    "docstring": "Given a dictionary of parameters, will extract the ranged task parameter value"
  },
  {
    "code": "def _cp_embeds_into(cp1, cp2):\n    if cp1 is None or cp2 is None:\n        return False\n    cp1 = as_complex_pattern(cp1)\n    cp2 = as_complex_pattern(cp2)\n    if len(cp2.monomer_patterns) == 1:\n        mp2 = cp2.monomer_patterns[0]\n        for mp1 in cp1.monomer_patterns:\n            if _mp_embeds_into(mp1, mp2):\n                return True\n    return False",
    "docstring": "Check that any state in ComplexPattern2 is matched in ComplexPattern1."
  },
  {
    "code": "def cleanup(self):\n        for instance in self.context:\n            del(instance)\n        for plugin in self.plugins:\n            del(plugin)",
    "docstring": "Forcefully delete objects from memory\n\n        In an ideal world, this shouldn't be necessary. Garbage\n        collection guarantees that anything without reference\n        is automatically removed.\n\n        However, because this application is designed to be run\n        multiple times from the same interpreter process, extra\n        case must be taken to ensure there are no memory leaks.\n\n        Explicitly deleting objects shines a light on where objects\n        may still be referenced in the form of an error. No errors\n        means this was uneccesary, but that's ok."
  },
  {
    "code": "def main(filename):\n    font_family = 'arial'\n    font = Font(font_family, bold=True)\n    if not font:\n        raise RuntimeError('No font found for %r' % font_family)\n    with Document('output.pdf') as document:\n        with document.Page() as ctx:\n            with Image(filename) as embed:\n                ctx.box = embed.box\n                ctx.embed(embed)\n            ctx.add(Text('Hello World', font, size=14, x=100, y=60))",
    "docstring": "Creates a PDF by embedding the first page from the given image and\n    writes some text to it.\n\n    @param[in] filename\n        The source filename of the image to embed."
  },
  {
    "code": "def zlines(f = None, sep = \"\\0\", osep = None, size = 8192):\n  if f is None: f = sys.stdin\n  if osep is None: osep = sep\n  buf = \"\"\n  while True:\n    chars = f.read(size)\n    if not chars: break\n    buf += chars; lines = buf.split(sep); buf = lines.pop()\n    for line in lines: yield line + osep\n  if buf: yield buf",
    "docstring": "File iterator that uses alternative line terminators."
  },
  {
    "code": "def get_order(self, order_id):\n        if order_id in self.blotter.orders:\n            return self.blotter.orders[order_id].to_api_obj()",
    "docstring": "Lookup an order based on the order id returned from one of the\n        order functions.\n\n        Parameters\n        ----------\n        order_id : str\n            The unique identifier for the order.\n\n        Returns\n        -------\n        order : Order\n            The order object."
  },
  {
    "code": "def get_primary_domain(self):\n        try:\n            domain = self.domains.get(is_primary=True)\n            return domain\n        except get_tenant_domain_model().DoesNotExist:\n            return None",
    "docstring": "Returns the primary domain of the tenant"
  },
  {
    "code": "def shift_select(self, first_element, last_element):\n        self.click(first_element)\n        self.shift_click(last_element)",
    "docstring": "Clicks a web element and shift clicks another web element.\n\n        :param first_element: WebElement instance\n        :param last_element: WebElement instance\n        :return: None"
  },
  {
    "code": "def get_anchor_contents(markup):\n    soup = BeautifulSoup(markup, 'lxml')\n    return ['%s' % link.contents[0] for link in soup.find_all('a')]",
    "docstring": "Given HTML markup, return a list of href inner html for each anchor tag."
  },
  {
    "code": "def _get_dispatches(filter_kwargs):\n    dispatches = Dispatch.objects.prefetch_related('message').filter(\n        **filter_kwargs\n    ).order_by('-message__time_created')\n    return list(dispatches)",
    "docstring": "Simplified version. Not distributed friendly."
  },
  {
    "code": "def get_value_prob(self, attr_name, value):\n        if attr_name not in self._attr_value_count_totals:\n            return\n        n = self._attr_value_counts[attr_name][value]\n        d = self._attr_value_count_totals[attr_name]\n        return n/float(d)",
    "docstring": "Returns the value probability of the given attribute at this node."
  },
  {
    "code": "def add(self, filename):\n        basename = os.path.basename(filename)\n        match = self.regexp.search(basename)\n        if match:\n            self.by_episode[int(match.group('ep'))].add(filename)",
    "docstring": "Try to add a file."
  },
  {
    "code": "def create(self, re='brunel-py-ex-*.gdf', index=True):\n        self.cursor.execute('CREATE TABLE IF NOT EXISTS spikes (neuron INT UNSIGNED, time REAL)')\n        tic = now()\n        for f in glob.glob(re):\n            print(f)\n            while True:\n                try:\n                    for data in self._blockread(f):\n                        self.cursor.executemany('INSERT INTO spikes VALUES (?, ?)', data)\n                        self.conn.commit()\n                except:\n                    continue\n                break                \n        toc = now()\n        if self.debug: print('Inserts took %g seconds.' % (toc-tic))\n        if index:\n            tic = now()\n            self.cursor.execute('CREATE INDEX neuron_index on spikes (neuron)')\n            toc = now()\n            if self.debug: print('Indexed db in %g seconds.' % (toc-tic))",
    "docstring": "Create db from list of gdf file glob\n\n\n        Parameters\n        ----------\n        re : str\n            File glob to load.\n        index : bool\n            Create index on neurons for speed.\n                    \n        \n        Returns\n        -------\n        None\n        \n        \n        See also\n        --------\n        sqlite3.connect.cursor, sqlite3.connect"
  },
  {
    "code": "def _get_price(self, package):\n        for price in package['prices']:\n            if not price.get('locationGroupId'):\n                return price['id']\n        raise SoftLayer.SoftLayerError(\"Could not find valid price\")",
    "docstring": "Returns valid price for ordering a dedicated host."
  },
  {
    "code": "def get_ancestors(self):\n        node = self\n        ancestor_list = []\n        while node.parent is not None:\n            ancestor_list.append(node.parent)\n            node = node.parent\n        return ancestor_list",
    "docstring": "Returns a list of ancestors of the node. Ordered from the earliest.\n\n        :return: node's ancestors, ordered from most recent\n        :rtype: list(FenwickNode)"
  },
  {
    "code": "def use_comparative_hierarchy_view(self):\n        self._hierarchy_view = COMPARATIVE\n        for session in self._get_provider_sessions():\n            try:\n                session.use_comparative_hierarchy_view()\n            except AttributeError:\n                pass",
    "docstring": "Pass through to provider HierarchyLookupSession.use_comparative_hierarchy_view"
  },
  {
    "code": "def fill_main_goids(go2obj, goids):\n    for goid in goids:\n        goobj = go2obj[goid]\n        if goid != goobj.id and goobj.id not in go2obj:\n            go2obj[goobj.id] = goobj",
    "docstring": "Ensure main GO IDs are included in go2obj."
  },
  {
    "code": "def remove_bucket(self, bucket_name):\n        is_valid_bucket_name(bucket_name)\n        self._url_open('DELETE', bucket_name=bucket_name)\n        self._delete_bucket_region(bucket_name)",
    "docstring": "Remove a bucket.\n\n        :param bucket_name: Bucket to remove"
  },
  {
    "code": "def annotation_path(cls, project, incident, annotation):\n        return google.api_core.path_template.expand(\n            \"projects/{project}/incidents/{incident}/annotations/{annotation}\",\n            project=project,\n            incident=incident,\n            annotation=annotation,\n        )",
    "docstring": "Return a fully-qualified annotation string."
  },
  {
    "code": "def getlines(self, bufnr=None):\n        buf = self._vim.buffers[bufnr] if bufnr else self._vim.current.buffer\n        return buf[:]",
    "docstring": "Get all lines of a buffer as a list.\n\n        Args:\n            bufnr (Optional[int]): A Vim buffer number, current if ``None``.\n\n        Returns:\n            List[str]"
  },
  {
    "code": "def get_time_now(self):\n        import datetime\n        import getpass\n        username = getpass.getuser()\n        timenow = str(datetime.datetime.now())\n        timenow = timenow.split('.')[0]\n        msg = '<div class=\"date\">Created on ' + timenow\n        msg += \" by \" + username +'</div>'\n        return msg",
    "docstring": "Returns a time stamp"
  },
  {
    "code": "def update_firewall_policy(self, firewall_policy, body=None):\n        return self.put(self.firewall_policy_path % (firewall_policy),\n                        body=body)",
    "docstring": "Updates a firewall policy."
  },
  {
    "code": "def release():\n    sh(\"paver bdist_egg\")\n    print\n    print \"~\" * 78\n    print \"TESTING SOURCE BUILD\"\n    sh(\n        \"{ cd dist/ && unzip -q %s-%s.zip && cd %s-%s/\"\n        \"  && /usr/bin/python setup.py sdist >/dev/null\"\n        \"  && if { unzip -ql ../%s-%s.zip; unzip -ql dist/%s-%s.zip; }\"\n        \"        | cut -b26- | sort | uniq -c| egrep -v '^ +2 +' ; then\"\n        \"       echo '^^^ Difference in file lists! ^^^'; false;\"\n        \"    else true; fi; } 2>&1\"\n        % tuple([project[\"name\"], version] * 4)\n    )\n    path(\"dist/%s-%s\" % (project[\"name\"], version)).rmtree()\n    print \"~\" * 78\n    print\n    print \"Created\", \" \".join([str(i) for i in path(\"dist\").listdir()])\n    print \"Use 'paver sdist bdist_egg upload' to upload to PyPI\"\n    print \"Use 'paver dist_docs' to prepare an API documentation upload\"",
    "docstring": "Check release before upload to PyPI."
  },
  {
    "code": "def get_journal_abstracts(self, refresh=True):\n        return [abstract for abstract in self.get_abstracts(refresh=refresh) if\n                abstract.aggregationType == 'Journal']",
    "docstring": "Return a list of ScopusAbstract objects using ScopusSearch,\n           but only if belonging to a Journal."
  },
  {
    "code": "def filter_queryset(self, request, queryset, view):\n        self.ordering_param = view.SORT\n        ordering = self.get_ordering(request, queryset, view)\n        if ordering:\n            return queryset.order_by(*ordering)\n        return queryset",
    "docstring": "Filter the queryset, applying the ordering.\n\n        The `ordering_param` can be overwritten here.\n        In DRF, the ordering_param is 'ordering', but we support changing it\n        to allow the viewset to control the parameter."
  },
  {
    "code": "def list(self,params=None, headers=None):\n        path = '/creditor_bank_accounts'\n        response = self._perform_request('GET', path, params, headers,\n                                         retry_failures=True)\n        return self._resource_for(response)",
    "docstring": "List creditor bank accounts.\n\n        Returns a [cursor-paginated](#api-usage-cursor-pagination) list of your\n        creditor bank accounts.\n\n        Args:\n              params (dict, optional): Query string parameters.\n\n        Returns:\n              CreditorBankAccount"
  },
  {
    "code": "def generic_visit(self, node):\n        super(RangeValues, self).generic_visit(node)\n        return self.add(node, UNKNOWN_RANGE)",
    "docstring": "Other nodes are not known and range value neither."
  },
  {
    "code": "def get_addresses_from_input_file(input_file_name):\n    mode = 'r'\n    if sys.version_info[0] < 3:\n        mode = 'rb'\n    with io.open(input_file_name, mode) as input_file:\n        reader = csv.reader(input_file, delimiter=',', quotechar='\"')\n        addresses = list(map(tuple, reader))\n        if len(addresses) == 0:\n            raise Exception('No addresses found in input file')\n        header_columns = list(column.lower() for column in addresses.pop(0))\n        try:\n            address_index = header_columns.index('address')\n            zipcode_index = header_columns.index('zipcode')\n        except ValueError:\n            raise Exception(\n)\n        return list((row[address_index], row[zipcode_index]) for row in addresses)",
    "docstring": "Read addresses from input file into list of tuples.\n       This only supports address and zipcode headers"
  },
  {
    "code": "def get_system_properties(server=None):\n    properties = {}\n    data = _api_get('system-properties', server)\n    if any(data['extraProperties']['systemProperties']):\n        for element in data['extraProperties']['systemProperties']:\n            properties[element['name']] = element['value']\n        return properties\n    return {}",
    "docstring": "Get system properties"
  },
  {
    "code": "def multiget(self, pairs, **params):\n        if self._multiget_pool:\n            params['pool'] = self._multiget_pool\n        return riak.client.multi.multiget(self, pairs, **params)",
    "docstring": "Fetches many keys in parallel via threads.\n\n        :param pairs: list of bucket_type/bucket/key tuple triples\n        :type pairs: list\n        :param params: additional request flags, e.g. r, pr\n        :type params: dict\n        :rtype: list of :class:`RiakObjects <riak.riak_object.RiakObject>`,\n            :class:`Datatypes <riak.datatypes.Datatype>`, or tuples of\n            bucket_type, bucket, key, and the exception raised on fetch"
  },
  {
    "code": "def bundle(self, ref, capture_exceptions=False):\n        from ..orm.exc import NotFoundError\n        if isinstance(ref, Dataset):\n            ds = ref\n        else:\n            try:\n                ds = self._db.dataset(ref)\n            except NotFoundError:\n                ds = None\n        if not ds:\n            try:\n                p = self.partition(ref)\n                ds = p._bundle.dataset\n            except NotFoundError:\n                ds = None\n        if not ds:\n            raise NotFoundError('Failed to find dataset for ref: {}'.format(ref))\n        b = Bundle(ds, self)\n        b.capture_exceptions = capture_exceptions\n        return b",
    "docstring": "Return a bundle build on a dataset, with the given vid or id reference"
  },
  {
    "code": "async def get_wallets(self, *args, **kwargs):\n\t\tlogging.debug(\"\\n [+] -- Get wallets debugging.\")\n\t\tif kwargs.get(\"message\"):\n\t\t\tkwargs = json.loads(kwargs.get(\"message\"))\n\t\tlogging.debug(kwargs)\n\t\tuid = kwargs.get(\"uid\",0)\n\t\taddress = kwargs.get(\"address\")\n\t\tcoinid = kwargs.get(\"coinid\")\n\t\ttry:\n\t\t\tcoinid = coinid.replace(\"TEST\", \"\")\n\t\texcept:\n\t\t\tpass\n\t\ttry:\n\t\t\tuid = int(uid)\n\t\texcept:\n\t\t\treturn await self.error_400(\"User id must be integer. \")\n\t\tif not uid and address:\n\t\t\tuid = await self.get_uid_by_address(address=address, coinid=coinid)\n\t\t\tif isinstance(uid, dict):\n\t\t\t\treturn uid\n\t\twallets = [i async for i in self.collect_wallets(uid)]\n\t\treturn {\"wallets\":wallets}",
    "docstring": "Get users wallets by uid\n\n\t\tAccepts:\n\t\t\t- uid [integer] (users id)\n\n\t\tReturns a list:\n\t\t\t- [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"address\": [string],\n\t\t\t\t\t\t\"uid\": [integer],\n\t\t\t\t\t\t\"amount_active\": [integer],\n\t\t\t\t\t\t\"amount_frozen\": [integer]\n\t\t\t\t\t},\n\t\t\t\t]"
  },
  {
    "code": "def get_extra_kwargs(self):\n        extra_kwargs = getattr(self.Meta, 'extra_kwargs', {})\n        read_only_fields = getattr(self.Meta, 'read_only_fields', None)\n        if read_only_fields is not None:\n            for field_name in read_only_fields:\n                kwargs = extra_kwargs.get(field_name, {})\n                kwargs['read_only'] = True\n                extra_kwargs[field_name] = kwargs\n        return extra_kwargs",
    "docstring": "Return a dictionary mapping field names to a dictionary of\n        additional keyword arguments."
  },
  {
    "code": "def update(self, scopes=[], add_scopes=[], rm_scopes=[], note='',\n               note_url=''):\n        success = False\n        json = None\n        if scopes:\n            d = {'scopes': scopes}\n            json = self._json(self._post(self._api, data=d), 200)\n        if add_scopes:\n            d = {'add_scopes': add_scopes}\n            json = self._json(self._post(self._api, data=d), 200)\n        if rm_scopes:\n            d = {'remove_scopes': rm_scopes}\n            json = self._json(self._post(self._api, data=d), 200)\n        if note or note_url:\n            d = {'note': note, 'note_url': note_url}\n            json = self._json(self._post(self._api, data=d), 200)\n        if json:\n            self._update_(json)\n            success = True\n        return success",
    "docstring": "Update this authorization.\n\n        :param list scopes: (optional), replaces the authorization scopes with\n            these\n        :param list add_scopes: (optional), scopes to be added\n        :param list rm_scopes: (optional), scopes to be removed\n        :param str note: (optional), new note about authorization\n        :param str note_url: (optional), new note URL about this authorization\n        :returns: bool"
  },
  {
    "code": "def touch_file(self, filename):\n        path_to_file = self.__file_class__(os.path.join(self, filename))\n        path_to_file.touch()\n        return path_to_file",
    "docstring": "Touch a file in the directory"
  },
  {
    "code": "def writexlsx(self, path, sheetname=\"default\"):\n        writer = ExcelRW.UnicodeWriter(path)\n        writer.set_active_sheet(sheetname)\n        writer.writerow(self.fields)\n        writer.writerows(self)\n        writer.save()",
    "docstring": "Writes this table to an .xlsx file at the specified path.\n\n        If you'd like to specify a sheetname, you may do so.\n\n        If you'd like to write one workbook with different DataTables\n        for each sheet, import the `excel` function from acrylic. You\n        can see that code in `utils.py`.\n\n        Note that the outgoing file is an .xlsx file, so it'd make sense to\n        name that way."
  },
  {
    "code": "def job_delayed_message(self, job, queue):\n        return '[%s|%s|%s] job delayed until %s' % (\n                queue._cached_name,\n                job.pk.get(),\n                job._cached_identifier,\n                job.delayed_until.hget())",
    "docstring": "Return the message to log when a job was delayed just before or during\n        its execution"
  },
  {
    "code": "def to_dict(self):\n        return {\n            \"all_set\": self._is_all_set(),\n            \"progress\": self.progress(),\n            \"values\": {\n                property_name: getattr(self, property_name) or []\n                for property_name in worker_mapping().keys()\n            }\n        }",
    "docstring": "This method is used in with connection to REST API. It basically\n        converts all important properties to dictionary, which may be used by\n        frontend.\n\n        Returns:\n            dict: ``{\"all_set\": bool, \"progress\": [int(done), int(how_many)], \\\n                  \"values\": {\"property\": [values], ..}}``"
  },
  {
    "code": "def nodes(self):\n        return (\n            devicetools.Nodes(\n                self.node_prefix+routers for routers in self._router_numbers) +\n            devicetools.Node(self.last_node))",
    "docstring": "A |Nodes| collection of all required nodes.\n\n        >>> from hydpy import RiverBasinNumbers2Selection\n        >>> rbns2s = RiverBasinNumbers2Selection(\n        ...                            (111, 113, 1129, 11269, 1125, 11261,\n        ...                             11262, 1123, 1124, 1122, 1121))\n\n        Note that the required outlet node is added:\n\n        >>> rbns2s.nodes\n        Nodes(\"node_1123\", \"node_1125\", \"node_11269\", \"node_1129\", \"node_113\",\n              \"node_outlet\")\n\n        It is both possible to change the prefix names of the nodes and\n        the name of the outlet node separately:\n\n        >>> rbns2s.node_prefix = 'b_'\n        >>> rbns2s.last_node = 'l_node'\n        >>> rbns2s.nodes\n        Nodes(\"b_1123\", \"b_1125\", \"b_11269\", \"b_1129\", \"b_113\", \"l_node\")"
  },
  {
    "code": "def _valid_table_name(name):\n    if name[0] not in \"_\" + string.ascii_letters or not set(name).issubset(\n        \"_\" + string.ascii_letters + string.digits\n    ):\n        return False\n    else:\n        return True",
    "docstring": "Verify if a given table name is valid for `rows`\n\n    Rules:\n    - Should start with a letter or '_'\n    - Letters can be capitalized or not\n    - Accepts letters, numbers and _"
  },
  {
    "code": "def process_nxml(nxml_filename, pmid=None, extra_annotations=None,\n                 cleanup=True, add_grounding=True):\n    if extra_annotations is None:\n        extra_annotations = {}\n    pp_dir = tempfile.mkdtemp('indra_isi_pp_output')\n    pp = IsiPreprocessor(pp_dir)\n    extra_annotations = {}\n    pp.preprocess_nxml_file(nxml_filename, pmid, extra_annotations)\n    ip = process_preprocessed(pp)\n    if add_grounding:\n        ip.add_grounding()\n    if cleanup:\n        shutil.rmtree(pp_dir)\n    else:\n        logger.info('Not cleaning up %s' % pp_dir)\n    return ip",
    "docstring": "Process an NXML file using the ISI reader\n\n    First converts NXML to plain text and preprocesses it, then runs the ISI\n    reader, and processes the output to extract INDRA Statements.\n\n    Parameters\n    ----------\n    nxml_filename : str\n        nxml file to process\n    pmid : Optional[str]\n        pmid of this nxml file, to be added to the Evidence object of the\n        extracted INDRA statements\n    extra_annotations : Optional[dict]\n        Additional annotations to add to the Evidence object of all extracted\n        INDRA statements. Extra annotations called 'interaction' are ignored\n        since this is used by the processor to store the corresponding\n        raw ISI output.\n    cleanup : Optional[bool]\n        If True, the temporary folders created for preprocessed reading input\n        and output are removed. Default: True\n    add_grounding : Optional[bool]\n        If True the extracted Statements' grounding is mapped\n\n    Returns\n    -------\n    ip : indra.sources.isi.processor.IsiProcessor\n        A processor containing extracted Statements"
  },
  {
    "code": "def score_samples(self, X):\n        check_is_fitted(self, 'means_')\n        X = check_array(X)\n        if X.ndim == 1:\n            X = X[:, np.newaxis]\n        if X.size == 0:\n            return np.array([]), np.empty((0, self.n_components))\n        if X.shape[1] != self.means_.shape[1]:\n            raise ValueError('The shape of X  is not compatible with self')\n        lpr = (log_multivariate_normal_density(X, self.means_, self.covars_,\n                                               self.covariance_type)\n               + np.log(self.weights_))\n        logprob = logsumexp(lpr, axis=1)\n        responsibilities = np.exp(lpr - logprob[:, np.newaxis])\n        return logprob, responsibilities",
    "docstring": "Return the per-sample likelihood of the data under the model.\n\n        Compute the log probability of X under the model and\n        return the posterior distribution (responsibilities) of each\n        mixture component for each element of X.\n\n        Parameters\n        ----------\n        X: array_like, shape (n_samples, n_features)\n            List of n_features-dimensional data points. Each row\n            corresponds to a single data point.\n\n        Returns\n        -------\n        logprob : array_like, shape (n_samples,)\n            Log probabilities of each data point in X.\n\n        responsibilities : array_like, shape (n_samples, n_components)\n            Posterior probabilities of each mixture component for each\n            observation"
  },
  {
    "code": "def head_tail_middle(src):\n    if len(src) == 0:\n        return None, [], None\n    if len(src) == 1:\n        return src[0], [], None\n    if len(src) == 2:\n        return src[0], [], src[1]\n    return src[0], src[1:-1], src[-1]",
    "docstring": "Returns a tuple consisting of the head of a enumerable, the middle\n    as a list and the tail of the enumerable. If the enumerable is 1 item, the\n    middle will be empty and the tail will be None. \n\n    >>> head_tail_middle([1, 2, 3, 4])\n    1, [2, 3], 4"
  },
  {
    "code": "def append_dict_key_value(\n        in_dict,\n        keys,\n        value,\n        delimiter=DEFAULT_TARGET_DELIM,\n        ordered_dict=False):\n    dict_pointer, last_key = _dict_rpartition(in_dict,\n                                              keys,\n                                              delimiter=delimiter,\n                                              ordered_dict=ordered_dict)\n    if last_key not in dict_pointer or dict_pointer[last_key] is None:\n        dict_pointer[last_key] = []\n    try:\n        dict_pointer[last_key].append(value)\n    except AttributeError:\n        raise SaltInvocationError('The last key contains a {}, which cannot append.'\n                                  ''.format(type(dict_pointer[last_key])))\n    return in_dict",
    "docstring": "Ensures that in_dict contains the series of recursive keys defined in keys.\n    Also appends `value` to the list that is at the end of `in_dict` traversed\n    with `keys`.\n\n    :param dict in_dict: The dictionary to work with\n    :param str keys: The delimited string with one or more keys.\n    :param any value: The value to append to the nested dict-key.\n    :param str delimiter: The delimiter to use in `keys`. Defaults to ':'.\n    :param bool ordered_dict: Create OrderedDicts if keys are missing.\n                              Default: create regular dicts.\n\n    :return dict: Though it updates in_dict in-place."
  },
  {
    "code": "def _prompt_started_hook(self):\n        if not self._reading:\n            self._highlighter.highlighting_on = True\n            self.sig_prompt_ready.emit()",
    "docstring": "Emit a signal when the prompt is ready."
  },
  {
    "code": "def figure(bgcolor=(1,1,1), size=(1000,1000)):\n        Visualizer3D._scene = Scene(background_color=np.array(bgcolor))\n        Visualizer3D._scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], strength=1.0)\n        Visualizer3D._init_size = np.array(size)",
    "docstring": "Create a blank figure.\n\n        Parameters\n        ----------\n        bgcolor : (3,) float\n           Color of the background with values in [0,1].\n        size : (2,) int\n           Width and height of the figure in pixels."
  },
  {
    "code": "def bind(self, data_shapes, label_shapes=None, for_training=True,\n             inputs_need_grad=False, force_rebind=False, shared_module=None, grad_req='write'):\n        super(SVRGModule, self).bind(data_shapes, label_shapes, for_training, inputs_need_grad, force_rebind,\n                                     shared_module, grad_req)\n        if for_training:\n            self._mod_aux.bind(data_shapes, label_shapes, for_training, inputs_need_grad, force_rebind, shared_module,\n                               grad_req)",
    "docstring": "Binds the symbols to construct executors for both two modules. This is necessary before one\n        can perform computation with the SVRGModule.\n\n        Parameters\n        ----------\n        data_shapes : list of (str, tuple)\n            Typically is ``data_iter.provide_data``.\n        label_shapes : list of (str, tuple)\n            Typically is ``data_iter.provide_label``.\n        for_training : bool\n            Default is ``True``. Whether the executors should be bound for training.\n        inputs_need_grad : bool\n            Default is ``False``. Whether the gradients to the input data need to be computed.\n            Typically this is not needed. But this might be needed when implementing composition\n            of modules.\n        force_rebind : bool\n            Default is ``False``. This function does nothing if the executors are already\n            bound. But with this ``True``, the executors will be forced to rebind.\n        shared_module : Module\n            Default is ``None``. This is used in bucketing. When not ``None``, the shared module\n            essentially corresponds to a different bucket -- a module with different symbol\n            but with the same sets of parameters (e.g. unrolled RNNs with different lengths)."
  },
  {
    "code": "def validate_unique_slug(self, cleaned_data):\n        date_kwargs = {}\n        error_msg = _(\"The slug is not unique\")\n        pubdate = cleaned_data['publication_date'] or now()\n        if '{year}' in appsettings.FLUENT_BLOGS_ENTRY_LINK_STYLE:\n            date_kwargs['year'] = pubdate.year\n            error_msg = _(\"The slug is not unique within it's publication year.\")\n        if '{month}' in appsettings.FLUENT_BLOGS_ENTRY_LINK_STYLE:\n            date_kwargs['month'] = pubdate.month\n            error_msg = _(\"The slug is not unique within it's publication month.\")\n        if '{day}' in appsettings.FLUENT_BLOGS_ENTRY_LINK_STYLE:\n            date_kwargs['day'] = pubdate.day\n            error_msg = _(\"The slug is not unique within it's publication day.\")\n        date_range = get_date_range(**date_kwargs)\n        dup_filters = self.get_unique_slug_filters(cleaned_data)\n        if date_range:\n            dup_filters['publication_date__range'] = date_range\n        dup_qs = EntryModel.objects.filter(**dup_filters)\n        if self.instance and self.instance.pk:\n            dup_qs = dup_qs.exclude(pk=self.instance.pk)\n        if dup_qs.exists():\n            raise ValidationError(error_msg)",
    "docstring": "Test whether the slug is unique within a given time period."
  },
  {
    "code": "def iri(uri_string):\n        uri_string = str(uri_string)\n        if uri_string[:1] == \"?\":\n            return uri_string\n        if uri_string[:1] == \"[\":\n            return uri_string\n        if uri_string[:1] != \"<\":\n            uri_string = \"<{}\".format(uri_string.strip())\n        if uri_string[len(uri_string)-1:] != \">\":\n            uri_string = \"{}>\".format(uri_string.strip())\n        return uri_string",
    "docstring": "converts a string to an IRI or returns an IRI if already formated\n\n        Args:\n            uri_string: uri in string format\n\n        Returns:\n            formated uri with <>"
  },
  {
    "code": "def attempt_social_login(self, provider, id):\n        if not provider or not id:\n            return False\n        params = dict()\n        params[provider.lower() + '_id'] = id\n        user = self.first(**params)\n        if not user:\n            return False\n        self.force_login(user)\n        return True",
    "docstring": "Attempt social login and return boolean result"
  },
  {
    "code": "def exit_proc(self, lineno):\n        __DEBUG__('Exiting current scope from lineno %i' % lineno)\n        if len(self.local_labels) <= 1:\n            error(lineno, 'ENDP in global scope (with no PROC)')\n            return\n        for label in self.local_labels[-1].values():\n            if label.local:\n                if not label.defined:\n                    error(lineno, \"Undefined LOCAL label '%s'\" % label.name)\n                    return\n                continue\n            name = label.name\n            _lineno = label.lineno\n            value = label.value\n            if name not in self.global_labels.keys():\n                self.global_labels[name] = label\n            else:\n                self.global_labels[name].define(value, _lineno)\n        self.local_labels.pop()\n        self.scopes.pop()",
    "docstring": "Exits current procedure. Local labels are transferred to global\n        scope unless they have been marked as local ones.\n\n        Raises an error if no current local context (stack underflow)"
  },
  {
    "code": "def _check_request(self, msg):\n        if \"jsonrpc\" not in msg:\n            raise InvalidRequestError(\"'\\\"jsonrpc\\\": \\\"2.0\\\"' must be included.\")\n        if msg[\"jsonrpc\"] != \"2.0\":\n            raise InvalidRequestError(\"'jsonrpc' must be exactly the string '2.0', but it was '{}'.\"\n                                      .format(msg[\"jsonrpc\"]))\n        if \"method\" not in msg:\n            raise InvalidRequestError(\"No method specified.\")\n        if \"id\" in msg:\n            if msg[\"id\"] is None:\n                raise InvalidRequestError(\"typedjsonrpc does not allow id to be None.\")\n            if isinstance(msg[\"id\"], float):\n                raise InvalidRequestError(\"typedjsonrpc does not support float ids.\")\n            if not isinstance(msg[\"id\"], (six.string_types, six.integer_types)):\n                raise InvalidRequestError(\"id must be a string or integer; '{}' is of type {}.\"\n                                          .format(msg[\"id\"], type(msg[\"id\"])))\n        if msg[\"method\"] not in self._name_to_method_info:\n            raise MethodNotFoundError(\"Could not find method '{}'.\".format(msg[\"method\"]))",
    "docstring": "Checks that the request json is well-formed.\n\n        :param msg: The request's json data\n        :type msg: dict[str, object]"
  },
  {
    "code": "def export_datasource_schema(back_references):\n    data = dict_import_export.export_schema_to_dict(\n        back_references=back_references)\n    yaml.safe_dump(data, stdout, default_flow_style=False)",
    "docstring": "Export datasource YAML schema to stdout"
  },
  {
    "code": "def get_system_info(self, x=255, y=255):\n        p2p_tables = self.get_p2p_routing_table(x, y)\n        max_x = max(x_ for (x_, y_), r in iteritems(p2p_tables)\n                    if r != consts.P2PTableEntry.none)\n        max_y = max(y_ for (x_, y_), r in iteritems(p2p_tables)\n                    if r != consts.P2PTableEntry.none)\n        sys_info = SystemInfo(max_x + 1, max_y + 1)\n        for (x, y), p2p_route in iteritems(p2p_tables):\n            if p2p_route != consts.P2PTableEntry.none:\n                try:\n                    sys_info[(x, y)] = self.get_chip_info(x, y)\n                except SCPError:\n                    pass\n        return sys_info",
    "docstring": "Discover the integrity and resource availability of a whole\n        SpiNNaker system.\n\n        This command performs :py:meth:`.get_chip_info` on all working chips in\n        the system returning an enhanced :py:class:`dict`\n        (:py:class:`.SystemInfo`) containing a look-up from chip coordinate to\n        :py:class:`.ChipInfo`. In addition to standard dictionary\n        functionality, :py:class:`.SystemInfo` provides a number of convenience\n        methods, which allow convenient iteration over various aspects of the\n        information stored.\n\n        .. note::\n            This method replaces the deprecated :py:meth:`.get_machine` method.\n            To build a :py:class:`~rig.place_and_route.Machine` for\n            place-and-route purposes, the\n            :py:func:`rig.place_and_route.utils.build_machine` utility function\n            may be used with :py:meth:`.get_system_info` like so::\n\n                >> from rig.place_and_route.utils import build_machine\n                >> sys_info = mc.get_system_info()\n                >> machine = build_machine(sys_info)\n\n        Parameters\n        ----------\n        x : int\n        y : int\n            The coordinates of the chip from which system exploration should\n            begin, by default (255, 255). Most users will not need to change\n            these parameters.\n\n        Returns\n        -------\n        :py:class:`.SystemInfo`\n            An enhanced :py:class:`dict` object {(x, y): :py:class:`.ChipInfo`,\n            ...} with a number of utility methods for accessing higher-level\n            system information."
  },
  {
    "code": "def get_ticker(self):\n        self._log('get ticker')\n        return self._rest_client.get(\n            endpoint='/ticker',\n            params={'book': self.name}\n        )",
    "docstring": "Return the latest ticker information.\n\n        :return: Latest ticker information.\n        :rtype: dict"
  },
  {
    "code": "def join_ext(name, extension):\n    if extension[0] == EXT:\n        ret = name + extension\n    else:\n        ret = name + EXT + extension\n    return ret",
    "docstring": "Joins a given name with an extension. If the extension doesn't have a '.'\n    it will add it for you"
  },
  {
    "code": "def move(self, source, destination):\n        if source.isfile():\n            source.copy(destination)\n            source.remove()\n        else:\n            source.copy(destination, recursive=True)\n            source.remove('r')",
    "docstring": "the semantic should be like unix 'mv' command"
  },
  {
    "code": "def latency(self):\n        with self.lock:\n            self.send('PING %s' % self.server)\n            ctime = self._m_time.time()\n            msg = self._recv(expected_replies=('PONG',))\n            if msg[0] == 'PONG':\n                latency = self._m_time.time() - ctime\n                return latency",
    "docstring": "Checks the connection latency."
  },
  {
    "code": "def remove_collection(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None):\n        if fourth_arg is None:\n            collection_id, branch_name, author = first_arg, sec_arg, third_arg\n            gh_user = branch_name.split('_collection_')[0]\n            parent_sha = self.get_master_sha()\n        else:\n            gh_user, collection_id, parent_sha, author = first_arg, sec_arg, third_arg, fourth_arg\n        if commit_msg is None:\n            commit_msg = \"Delete Collection '%s' via OpenTree API\" % collection_id\n        return self._remove_document(gh_user, collection_id, parent_sha, author, commit_msg)",
    "docstring": "Remove a collection\n        Given a collection_id, branch and optionally an\n        author, remove a collection on the given branch\n        and attribute the commit to author.\n        Returns the SHA of the commit on branch."
  },
  {
    "code": "def print_pole_mean(mean_dictionary):\n    print('Plon: ' + str(round(mean_dictionary['dec'], 1)) +\n          '  Plat: ' + str(round(mean_dictionary['inc'], 1)))\n    print('Number of directions in mean (n): ' + str(mean_dictionary['n']))\n    print('Angular radius of 95% confidence (A_95): ' +\n          str(round(mean_dictionary['alpha95'], 1)))\n    print('Precision parameter (k) estimate: ' +\n          str(round(mean_dictionary['k'], 1)))",
    "docstring": "Does a pretty job printing a Fisher mean and associated statistics for\n    mean paleomagnetic poles.\n\n    Parameters\n    ----------\n    mean_dictionary: output dictionary of pmag.fisher_mean\n\n    Examples\n    --------\n    Generate a Fisher mean using ``ipmag.fisher_mean`` and then print it nicely\n    using ``ipmag.print_pole_mean``\n\n    >>> my_mean = ipmag.fisher_mean(di_block=[[140,21],[127,23],[142,19],[136,22]])\n    >>> ipmag.print_pole_mean(my_mean)\n    Plon: 136.3  Plat: 21.3\n    Number of directions in mean (n): 4\n    Angular radius of 95% confidence (A_95): 7.3\n    Precision parameter (k) estimate: 159.7"
  },
  {
    "code": "def backup(path, name=None):\n    from PyHardLinkBackup.phlb.phlb_main import backup\n    backup(path, name)",
    "docstring": "Start a Backup run"
  },
  {
    "code": "def search(self, id_key=None, **parameters):\n        episode = parameters.get(\"episode\")\n        id_tvdb = parameters.get(\"id_tvdb\") or id_key\n        id_imdb = parameters.get(\"id_imdb\")\n        season = parameters.get(\"season\")\n        series = parameters.get(\"series\")\n        date = parameters.get(\"date\")\n        if id_tvdb:\n            for result in self._search_id_tvdb(id_tvdb, season, episode):\n                yield result\n        elif id_imdb:\n            for result in self._search_id_imdb(id_imdb, season, episode):\n                yield result\n        elif series and date:\n            if not match(\n                r\"(19|20)\\d{2}(-(?:0[1-9]|1[012])(-(?:[012][1-9]|3[01]))?)?\",\n                date,\n            ):\n                raise MapiProviderException(\"Date must be in YYYY-MM-DD format\")\n            for result in self._search_series_date(series, date):\n                yield result\n        elif series:\n            for result in self._search_series(series, season, episode):\n                yield result\n        else:\n            raise MapiNotFoundException",
    "docstring": "Searches TVDb for movie metadata\n\n        TODO: Consider making parameters for episode ids"
  },
  {
    "code": "def _CaptureExpression(self, frame, expression):\n    rc, value = _EvaluateExpression(frame, expression)\n    if not rc:\n      return {'name': expression, 'status': value}\n    return self.CaptureNamedVariable(expression, value, 0,\n                                     self.expression_capture_limits)",
    "docstring": "Evalutes the expression and captures it into a Variable object.\n\n    Args:\n      frame: evaluation context.\n      expression: watched expression to compile and evaluate.\n\n    Returns:\n      Variable object (which will have error status if the expression fails\n      to evaluate)."
  },
  {
    "code": "def get_lang_dict(self):\n        r = self.yandex_translate_request(\"getLangs\")\n        self.handle_errors(r)\n        return r.json()[\"langs\"]",
    "docstring": "gets supported langs as an dictionary"
  },
  {
    "code": "def _get_host_ref(service_instance, host, host_name=None):\n    search_index = salt.utils.vmware.get_inventory(service_instance).searchIndex\n    if host_name:\n        host_ref = search_index.FindByDnsName(dnsName=host_name, vmSearch=False)\n    else:\n        host_ref = search_index.FindByDnsName(dnsName=host, vmSearch=False)\n    if host_ref is None:\n        host_ref = search_index.FindByIp(ip=host, vmSearch=False)\n    return host_ref",
    "docstring": "Helper function that returns a host object either from the host location or the host_name.\n    If host_name is provided, that is the host_object that will be returned.\n\n    The function will first search for hosts by DNS Name. If no hosts are found, it will\n    try searching by IP Address."
  },
  {
    "code": "def background_estimator(bdata):\n    crowded = False\n    std = numpy.std(bdata)\n    std0 = std\n    mean = bdata.mean()\n    while True:\n        prep = len(bdata)\n        numpy.clip(bdata, mean - 3 * std, mean + 3 * std, out=bdata)\n        if prep == len(bdata):\n            if std < 0.8 * std0:\n                crowded = True\n            break\n        std = numpy.std(bdata)\n        mean = bdata.mean()\n    if crowded:\n        median = numpy.median(bdata)\n        mean = bdata.mean()\n        std = bdata.std()\n        return 2.5 * median - 1.5 * mean, std\n    return bdata.mean(), bdata.std()",
    "docstring": "Estimate the background in a 2D array"
  },
  {
    "code": "def add_group_email_grant(self, permission, email_address, headers=None):\n        acl = self.get_acl(headers=headers)\n        acl.add_group_email_grant(permission, email_address)\n        self.set_acl(acl, headers=headers)",
    "docstring": "Convenience method that provides a quick way to add an email group\n        grant to a key. This method retrieves the current ACL, creates a new\n        grant based on the parameters passed in, adds that grant to the ACL and\n        then PUT's the new ACL back to GS.\n\n        :type permission: string\n        :param permission: The permission being granted. Should be one of:\n            READ|FULL_CONTROL\n            See http://code.google.com/apis/storage/docs/developer-guide.html#authorization\n            for more details on permissions.\n\n        :type email_address: string\n        :param email_address: The email address associated with the Google\n            Group to which you are granting the permission."
  },
  {
    "code": "def _get_pk(self):\n        pk = None\n        if self._lazy_collection['pks']:\n            if len(self._lazy_collection['pks']) > 1:\n                raise ValueError('Too much pks !')\n            pk = list(self._lazy_collection['pks'])[0]\n        return pk",
    "docstring": "Return None if we don't have any filter on a pk, the pk if we have one,\n        or raise a ValueError if we have more than one.\n        For internal use only."
  },
  {
    "code": "def maybe_convert_to_index_date_type(index, date):\n    if isinstance(date, str):\n        return date\n    if isinstance(index, pd.DatetimeIndex):\n        if isinstance(date, np.datetime64):\n            return date\n        else:\n            return np.datetime64(str(date))\n    else:\n        date_type = index.date_type\n        if isinstance(date, date_type):\n            return date\n        else:\n            if isinstance(date, np.datetime64):\n                date = date.item()\n            if isinstance(date, datetime.date):\n                date = datetime.datetime.combine(\n                    date, datetime.datetime.min.time())\n            return date_type(date.year, date.month, date.day, date.hour,\n                             date.minute, date.second, date.microsecond)",
    "docstring": "Convert a datetime-like object to the index's date type.\n\n    Datetime indexing in xarray can be done using either a pandas\n    DatetimeIndex or a CFTimeIndex.  Both support partial-datetime string\n    indexing regardless of the calendar type of the underlying data;\n    therefore if a string is passed as a date, we return it unchanged.  If a\n    datetime-like object is provided, it will be converted to the underlying\n    date type of the index.  For a DatetimeIndex that is np.datetime64; for a\n    CFTimeIndex that is an object of type cftime.datetime specific to the\n    calendar used.\n\n    Parameters\n    ----------\n    index : pd.Index\n        Input time index\n    date : datetime-like object or str\n        Input datetime\n\n    Returns\n    -------\n    date of the type appropriate for the time index of the Dataset"
  },
  {
    "code": "def powerline():\n    bindings_dir, scripts_dir = install_upgrade_powerline()\n    set_up_powerline_fonts()\n    set_up_powerline_daemon(scripts_dir)\n    powerline_for_vim(bindings_dir)\n    powerline_for_bash_or_powerline_shell(bindings_dir)\n    powerline_for_tmux(bindings_dir)\n    powerline_for_i3(bindings_dir)\n    print('\\nYou may have to reboot for make changes take effect')",
    "docstring": "Install and set up powerline for vim, bash, tmux, and i3.\n\n    It uses pip (python2) and the most up to date powerline version (trunk) from\n    the github repository.\n\n    More infos:\n      https://github.com/powerline/powerline\n      https://powerline.readthedocs.io/en/latest/installation.html\n      https://github.com/powerline/fonts\n      https://youtu.be/_D6RkmgShvU\n      http://www.tecmint.com/powerline-adds-powerful-statuslines-and-prompts-to-vim-and-bash/"
  },
  {
    "code": "def change_password(self, old_password, new_password):\n\t\tbody = self._formdata({\n\t\t\t\"old_password\": old_password,\n\t\t\t\"password\": new_password,\n\t\t}, [\"old_password\", \"password\"])\n\t\tcontent = self._fetch(\"/current_user/password\", method=\"POST\", body=body)\n\t\treturn FastlyUser(self, content)",
    "docstring": "Update the user's password to a new one."
  },
  {
    "code": "async def message_throttled(self, message: types.Message, throttled: Throttled):\n        handler = current_handler.get()\n        dispatcher = Dispatcher.get_current()\n        if handler:\n            key = getattr(handler, 'throttling_key', f\"{self.prefix}_{handler.__name__}\")\n        else:\n            key = f\"{self.prefix}_message\"\n        delta = throttled.rate - throttled.delta\n        if throttled.exceeded_count <= 2:\n            await message.reply('Too many requests! ')\n        await asyncio.sleep(delta)\n        thr = await dispatcher.check_key(key)\n        if thr.exceeded_count == throttled.exceeded_count:\n            await message.reply('Unlocked.')",
    "docstring": "Notify user only on first exceed and notify about unlocking only on last exceed\n\n        :param message:\n        :param throttled:"
  },
  {
    "code": "def _l_cv_weight_factor(self):\n        b = 0.0047 * sqrt(0) + 0.0023 / 2\n        c = 0.02609 / (self.catchment.record_length - 1)\n        return c / (b + c)",
    "docstring": "Return multiplier for L-CV weightings in case of enhanced single site analysis.\n\n        Methodology source: Science Report SC050050, eqn. 6.15a and 6.15b"
  },
  {
    "code": "def _move_cursor_to_line(self, line):\n        last_line = self._text_edit.document().blockCount() - 1\n        self._cursor.clearSelection()\n        self._cursor.movePosition(self._cursor.End)\n        to_insert = ''\n        for i in range(line - last_line):\n            to_insert += '\\n'\n        if to_insert:\n            self._cursor.insertText(to_insert)\n        self._cursor.movePosition(self._cursor.Start)\n        self._cursor.movePosition(self._cursor.Down, self._cursor.MoveAnchor, line)\n        self._last_cursor_pos = self._cursor.position()",
    "docstring": "Moves the cursor to the specified line, if possible."
  },
  {
    "code": "def add_menu(self, name):\n        if self.menubar is None:\n            raise ValueError(\"No menu bar configured\")\n        return self.menubar.add_name(name)",
    "docstring": "Add a menu with name `name` to the global menu bar.\n        Returns a menu widget."
  },
  {
    "code": "def _log(self, priority, message, *args, **kwargs):\n        for arg in args:\n            message = message + \"\\n\" + self.pretty_printer.pformat(arg)\n        self.logger.log(priority, message)",
    "docstring": "Generic log functions"
  },
  {
    "code": "def _ignore_sql(self, query):\n        return any([\n            re.search(pattern, query.get('sql')) for pattern in QC_SETTINGS['IGNORE_SQL_PATTERNS']\n        ])",
    "docstring": "Check to see if we should ignore the sql query."
  },
  {
    "code": "def _xxrange(self, start, end, step_count):\n        _step = (end - start) / float(step_count)\n        return (start + (i * _step) for i in xrange(int(step_count)))",
    "docstring": "Generate n values between start and end."
  },
  {
    "code": "def display(self, tool):\n        self._tools.append(tool)\n        self._justDisplay(tool)",
    "docstring": "Displays the given tool above the current layer, and sets the\n        title to its name."
  },
  {
    "code": "def cancel_all(self, product_id=None):\n        if product_id is not None:\n            params = {'product_id': product_id}\n        else:\n            params = None\n        return self._send_message('delete', '/orders', params=params)",
    "docstring": "With best effort, cancel all open orders.\n\n        Args:\n            product_id (Optional[str]): Only cancel orders for this\n                product_id\n\n        Returns:\n            list: A list of ids of the canceled orders. Example::\n                [\n                    \"144c6f8e-713f-4682-8435-5280fbe8b2b4\",\n                    \"debe4907-95dc-442f-af3b-cec12f42ebda\",\n                    \"cf7aceee-7b08-4227-a76c-3858144323ab\",\n                    \"dfc5ae27-cadb-4c0c-beef-8994936fde8a\",\n                    \"34fecfbf-de33-4273-b2c6-baf8e8948be4\"\n                ]"
  },
  {
    "code": "def unregister_signals_oaiset(self):\n        from .models import OAISet\n        from .receivers import after_insert_oai_set, \\\n            after_update_oai_set, after_delete_oai_set\n        if contains(OAISet, 'after_insert', after_insert_oai_set):\n            remove(OAISet, 'after_insert', after_insert_oai_set)\n            remove(OAISet, 'after_update', after_update_oai_set)\n            remove(OAISet, 'after_delete', after_delete_oai_set)",
    "docstring": "Unregister signals oaiset."
  },
  {
    "code": "def compute_num_true_positives(ref_freqs, est_freqs, window=0.5, chroma=False):\n    n_frames = len(ref_freqs)\n    true_positives = np.zeros((n_frames, ))\n    for i, (ref_frame, est_frame) in enumerate(zip(ref_freqs, est_freqs)):\n        if chroma:\n            matching = util.match_events(\n                ref_frame, est_frame, window,\n                distance=util._outer_distance_mod_n)\n        else:\n            matching = util.match_events(ref_frame, est_frame, window)\n        true_positives[i] = len(matching)\n    return true_positives",
    "docstring": "Compute the number of true positives in an estimate given a reference.\n    A frequency is correct if it is within a quartertone of the\n    correct frequency.\n\n    Parameters\n    ----------\n    ref_freqs : list of np.ndarray\n        reference frequencies (MIDI)\n    est_freqs : list of np.ndarray\n        estimated frequencies (MIDI)\n    window : float\n        Window size, in semitones\n    chroma : bool\n        If True, computes distances modulo n.\n        If True, ``ref_freqs`` and ``est_freqs`` should be wrapped modulo n.\n\n    Returns\n    -------\n    true_positives : np.ndarray\n        Array the same length as ref_freqs containing the number of true\n        positives."
  },
  {
    "code": "def do_set_workdir(self, args):\n        params = args.split()\n        workdir = None\n        try:\n            workdir = params[0]\n        except IndexError:\n            _LOGGING.error('Device name required.')\n            self.do_help('set_workdir')\n        if workdir:\n            self.tools.workdir = workdir",
    "docstring": "Set the working directory.\n\n        The working directory is used to load and save known devices\n        to improve startup times. During startup the application\n        loads and saves a file `insteon_plm_device_info.dat`. This file\n        is saved in the working directory.\n\n        The working directory has no default value. If the working directory is\n        not set, the `insteon_plm_device_info.dat` file is not loaded or saved.\n\n        Usage:\n            set_workdir workdir\n        Arguments:\n            workdir: Required - Working directory to load and save devie list"
  },
  {
    "code": "def sha1_hexdigest(self):\n        if self._sha1_hexdigest is None:\n            self._sha1_hexdigest = hashlib.sha1(self._pem_bytes).hexdigest()\n        return self._sha1_hexdigest",
    "docstring": "A SHA-1 digest of the whole object for easy differentiation.\n\n        .. versionadded:: 18.1.0"
  },
  {
    "code": "def check_run(check, env, rate, times, pause, delay, log_level, as_json, break_point):\n    envs = get_configured_envs(check)\n    if not envs:\n        echo_failure('No active environments found for `{}`.'.format(check))\n        echo_info('See what is available to start via `ddev env ls {}`.'.format(check))\n        abort()\n    if not env:\n        if len(envs) > 1:\n            echo_failure('Multiple active environments found for `{}`, please specify one.'.format(check))\n            echo_info('See what is active via `ddev env ls`.')\n            abort()\n        env = envs[0]\n    if env not in envs:\n        echo_failure('`{}` is not an active environment.'.format(env))\n        echo_info('See what is active via `ddev env ls`.')\n        abort()\n    environment = create_interface(check, env)\n    environment.run_check(\n        rate=rate, times=times, pause=pause, delay=delay, log_level=log_level, as_json=as_json, break_point=break_point\n    )\n    echo_success('Note: ', nl=False)\n    echo_info('If some metrics are missing, you may want to try again with the -r / --rate flag.')",
    "docstring": "Run an Agent check."
  },
  {
    "code": "def assigned_state(instance):\n    analyses = instance.getAnalyses()\n    if not analyses:\n        return \"unassigned\"\n    for analysis in analyses:\n        analysis_object = api.get_object(analysis)\n        if not analysis_object.getWorksheet():\n            return \"unassigned\"\n    return \"assigned\"",
    "docstring": "Returns `assigned` or `unassigned` depending on the state of the\n    analyses the analysisrequest contains. Return `unassigned` if the Analysis\n    Request has at least one analysis in `unassigned` state.\n    Otherwise, returns `assigned`"
  },
  {
    "code": "async def fetch_state(self, request):\n        error_traps = [\n            error_handlers.InvalidAddressTrap,\n            error_handlers.StateNotFoundTrap]\n        address = request.match_info.get('address', '')\n        head = request.url.query.get('head', None)\n        head, root = await self._head_to_root(head)\n        response = await self._query_validator(\n            Message.CLIENT_STATE_GET_REQUEST,\n            client_state_pb2.ClientStateGetResponse,\n            client_state_pb2.ClientStateGetRequest(\n                state_root=root, address=address),\n            error_traps)\n        return self._wrap_response(\n            request,\n            data=response['value'],\n            metadata=self._get_metadata(request, response, head=head))",
    "docstring": "Fetches data from a specific address in the validator's state tree.\n\n        Request:\n            query:\n                - head: The id of the block to use as the head of the chain\n                - address: The 70 character address of the data to be fetched\n\n        Response:\n            data: The base64 encoded binary data stored at that address\n            head: The head used for this query (most recent if unspecified)\n            link: The link to this exact query, including head block"
  },
  {
    "code": "def get_langids(dev):\n    r\n    from usb.control import get_descriptor\n    buf = get_descriptor(\n                dev,\n                254,\n                DESC_TYPE_STRING,\n                0\n            )\n    if len(buf) < 4 or buf[0] < 4 or buf[0]&1 != 0:\n        return ()\n    return tuple(map(lambda x,y: x+(y<<8), buf[2:buf[0]:2], buf[3:buf[0]:2]))",
    "docstring": "r\"\"\"Retrieve the list of supported Language IDs from the device.\n\n    Most client code should not call this function directly, but instead use\n    the langids property on the Device object, which will call this function as\n    needed and cache the result.\n\n    USB LANGIDs are 16-bit integers familiar to Windows developers, where\n    for example instead of en-US you say 0x0409. See the file USB_LANGIDS.pdf\n    somewhere on the usb.org site for a list, which does not claim to be\n    complete. It requires \"system software must allow the enumeration and\n    selection of LANGIDs that are not currently on this list.\" It also requires\n    \"system software should never request a LANGID not defined in the LANGID\n    code array (string index = 0) presented by a device.\" Client code can\n    check this tuple before issuing string requests for a specific language ID.\n\n    dev is the Device object whose supported language IDs will be retrieved.\n\n    The return value is a tuple of integer LANGIDs, possibly empty if the\n    device does not support strings at all (which USB 3.1 r1.0 section\n    9.6.9 allows). In that case client code should not request strings at all.\n\n    A USBError may be raised from this function for some devices that have no\n    string support, instead of returning an empty tuple. The accessor for the\n    langids property on Device catches that case and supplies an empty tuple,\n    so client code can ignore this detail by using the langids property instead\n    of directly calling this function."
  },
  {
    "code": "def create(self, name, indexes = {}, fields = {}, **kwargs):\n        for k, v in six.iteritems(indexes):\n            if isinstance(v, dict):\n                v = json.dumps(v)\n            kwargs['index.' + k] = v\n        for k, v in six.iteritems(fields):\n            kwargs['field.' + k] = v\n        return self.post(name=name, **kwargs)",
    "docstring": "Creates a KV Store Collection.\n\n        :param name: name of collection to create\n        :type name: ``string``\n        :param indexes: dictionary of index definitions\n        :type indexes: ``dict``\n        :param fields: dictionary of field definitions\n        :type fields: ``dict``\n        :param kwargs: a dictionary of additional parameters specifying indexes and field definitions\n        :type kwargs: ``dict``\n\n        :return: Result of POST request"
  },
  {
    "code": "def move(self, i, lat, lng, change_time=True):\n        if i < 0 or i >= self.count():\n            print(\"Invalid fence point number %u\" % i)\n        self.points[i].lat = lat\n        self.points[i].lng = lng\n        if i == 1:\n                self.points[self.count()-1].lat = lat\n                self.points[self.count()-1].lng = lng\n        if i == self.count() - 1:\n                self.points[1].lat = lat\n                self.points[1].lng = lng\n        if change_time:\n            self.last_change = time.time()",
    "docstring": "move a fence point"
  },
  {
    "code": "def idsKEGG(organism):\n    ORG=urlopen(\"http://rest.kegg.jp/list/\"+organism).read()\n    ORG=ORG.split(\"\\n\")\n    final=[]\n    for k in ORG:\n        final.append(k.split(\"\\t\"))\n    df=pd.DataFrame(final[0:len(final)-1])[[0,1]]\n    df.columns=['KEGGid','description']\n    field = pd.DataFrame(df['description'].str.split(';',1).tolist())[0]\n    field = pd.DataFrame(field)\n    df = pd.concat([df[['KEGGid']],field],axis=1)\n    df.columns=['KEGGid','gene_name']\n    df=df[['gene_name','KEGGid']]\n    return df",
    "docstring": "Uses KEGG to retrieve all ids for a given KEGG organism\n\n    :param organism: an organism as listed in organismsKEGG()\n\n    :returns: a Pandas dataframe of with 'gene_name' and 'KEGGid'."
  },
  {
    "code": "def convert_magicc7_to_openscm_variables(variables, inverse=False):\n    if isinstance(variables, (list, pd.Index)):\n        return [\n            _apply_convert_magicc7_to_openscm_variables(v, inverse) for v in variables\n        ]\n    else:\n        return _apply_convert_magicc7_to_openscm_variables(variables, inverse)",
    "docstring": "Convert MAGICC7 variables to OpenSCM variables\n\n    Parameters\n    ----------\n    variables : list_like, str\n        Variables to convert\n\n    inverse : bool\n        If True, convert the other way i.e. convert OpenSCM variables to MAGICC7\n        variables\n\n    Returns\n    -------\n    ``type(variables)``\n        Set of converted variables"
  },
  {
    "code": "async def on_open(self):\n        self.__ensure_barrier()\n        while self.connected:\n            try:\n                if self.__lastping > self.__lastpong:\n                    raise IOError(\"Last ping remained unanswered\")\n                self.send_message(\"2\")\n                self.send_ack()\n                self.__lastping = time.time()\n                await asyncio.sleep(self.ping_interval)\n            except Exception as ex:\n                LOGGER.exception(\"Failed to ping\")\n                try:\n                    self.reraise(ex)\n                except Exception:\n                    LOGGER.exception(\n                        \"failed to force close connection after ping error\"\n                    )\n                break",
    "docstring": "DingDongmaster the connection is open"
  },
  {
    "code": "def parse_fade_requirement(text):\n    text = text.strip()\n    if \"::\" in text:\n        repo_raw, requirement = text.split(\"::\", 1)\n        try:\n            repo = {'pypi': REPO_PYPI, 'vcs': REPO_VCS}[repo_raw]\n        except KeyError:\n            logger.warning(\"Not understood fades repository: %r\", repo_raw)\n            return\n    else:\n        if \":\" in text and \"/\" in text:\n            repo = REPO_VCS\n        else:\n            repo = REPO_PYPI\n        requirement = text\n    if repo == REPO_VCS:\n        dependency = VCSDependency(requirement)\n    else:\n        dependency = list(parse_requirements(requirement))[0]\n    return repo, dependency",
    "docstring": "Return a requirement and repo from the given text, already parsed and converted."
  },
  {
    "code": "def launch(self, image, command, **kwargs):\n        if isinstance(command, PythonCall):\n            return PythonJob(self, image, command, **kwargs)\n        else:\n            return Job(self, image, command, **kwargs)",
    "docstring": "Create a job on this engine\n\n        Args:\n            image (str): name of the docker image to launch\n            command (str): shell command to run"
  },
  {
    "code": "def name(self, pretty=False):\n        name = self.os_release_attr('name') \\\n            or self.lsb_release_attr('distributor_id') \\\n            or self.distro_release_attr('name') \\\n            or self.uname_attr('name')\n        if pretty:\n            name = self.os_release_attr('pretty_name') \\\n                or self.lsb_release_attr('description')\n            if not name:\n                name = self.distro_release_attr('name') \\\n                       or self.uname_attr('name')\n                version = self.version(pretty=True)\n                if version:\n                    name = name + ' ' + version\n        return name or ''",
    "docstring": "Return the name of the OS distribution, as a string.\n\n        For details, see :func:`distro.name`."
  },
  {
    "code": "def dataframe(self):\n        if self._dataframe is None:\n            try:\n                import pandas as pd\n            except ImportError:\n                raise RuntimeError('To enable dataframe support, '\n                                   'run \\'pip install datadotworld[pandas]\\'')\n            self._dataframe = pd.DataFrame.from_records(self._iter_rows(),\n                                                        coerce_float=True)\n        return self._dataframe",
    "docstring": "Build and cache a dataframe from query results"
  },
  {
    "code": "def _zadd(self, key, pk, ts=None, ttl=None):\n        return self.r.eval(self.LUA_ZADD, 1, key, ts or self._time(), pk)",
    "docstring": "Redis lua func to add an event to the corresponding sorted set.\n\n        :param key: the key to be stored in redis server\n        :param pk: the primary key of event\n        :param ts: timestamp of the event, default to redis_server's\n         current timestamp\n        :param ttl: the expiration time of event since the last update"
  },
  {
    "code": "def runtime_paths(self):\n        runtimepath = self._vim.options['runtimepath']\n        plugin = \"ensime-vim\"\n        paths = []\n        for path in runtimepath.split(','):\n            if plugin in path:\n                paths.append(os.path.expanduser(path))\n        return paths",
    "docstring": "All the runtime paths of ensime-vim plugin files."
  },
  {
    "code": "def to_glyphs_font_attributes(self, source, master, is_initial):\n    if is_initial:\n        _set_glyphs_font_attributes(self, source)\n    else:\n        _compare_and_merge_glyphs_font_attributes(self, source)",
    "docstring": "Copy font attributes from `ufo` either to `self.font` or to `master`.\n\n    Arguments:\n    self -- The UFOBuilder\n    ufo -- The current UFO being read\n    master -- The current master being written\n    is_initial -- True iff this the first UFO that we process"
  },
  {
    "code": "def add(self, path):\n        if not path.startswith(os.sep):\n            raise ValueError(\"Non-absolute path '{}'\".format(path))\n        path = path.rstrip(os.sep)\n        while True:\n            self._paths[path] = None\n            path, _ = os.path.split(path)\n            if path == os.sep:\n                break",
    "docstring": "Add a path to the overlay filesytem.\n\n        Any filesystem operation involving the this path or any sub-paths\n        of it will be transparently redirected to temporary root dir.\n\n        @path: An absolute path string."
  },
  {
    "code": "def com_google_fonts_check_metadata_license(family_metadata):\n  licenses = [\"APACHE2\", \"OFL\", \"UFL\"]\n  if family_metadata.license in licenses:\n    yield PASS, (\"Font license is declared\"\n                 \" in METADATA.pb as \\\"{}\\\"\").format(family_metadata.license)\n  else:\n    yield FAIL, (\"METADATA.pb license field (\\\"{}\\\")\"\n                 \" must be one of the following:\"\n                 \" {}\").format(family_metadata.license,\n                               licenses)",
    "docstring": "METADATA.pb license is \"APACHE2\", \"UFL\" or \"OFL\"?"
  },
  {
    "code": "def print_diff(self, ignore=[]):\n        ignore.append(inspect.currentframe())\n        diff = self.get_diff(ignore)\n        print(\"Added objects:\")\n        summary.print_(summary.summarize(diff['+']))\n        print(\"Removed objects:\")\n        summary.print_(summary.summarize(diff['-']))\n        del ignore[:]",
    "docstring": "Print the diff to the last time the state of objects was measured.\n\n        keyword arguments\n        ignore -- list of objects to ignore"
  },
  {
    "code": "def connection_made(self):\n        LOG.info(\n            'Connection to peer: %s established',\n            self._neigh_conf.ip_address,\n            extra={\n                'resource_name': self._neigh_conf.name,\n                'resource_id': self._neigh_conf.id\n            }\n        )",
    "docstring": "Protocols connection established handler"
  },
  {
    "code": "def get_completed_tasks(self):\n        self.owner.sync()\n        tasks = []\n        offset = 0\n        while True:\n            response = API.get_all_completed_tasks(self.owner.api_token,\n                                                   limit=_PAGE_LIMIT,\n                                                   offset=offset,\n                                                   project_id=self.id)\n            _fail_if_contains_errors(response)\n            response_json = response.json()\n            tasks_json = response_json['items']\n            if len(tasks_json) == 0:\n                break\n            for task_json in tasks_json:\n                project = self.owner.projects[task_json['project_id']]\n                tasks.append(Task(task_json, project))\n            offset += _PAGE_LIMIT\n        return tasks",
    "docstring": "Return a list of all completed tasks in this project.\n\n        :return: A list of all completed tasks in this project.\n        :rtype: list of :class:`pytodoist.todoist.Task`\n\n        >>> from pytodoist import todoist\n        >>> user = todoist.login('john.doe@gmail.com', 'password')\n        >>> project = user.get_project('PyTodoist')\n        >>> task = project.add_task('Install PyTodoist')\n        >>> task.complete()\n        >>> completed_tasks = project.get_completed_tasks()\n        >>> for task in completed_tasks:\n        ...    task.uncomplete()"
  },
  {
    "code": "def get_extra_element_count(curr_count, opt_count, extra_allowed_cnt):\n    if curr_count > opt_count:\n        if extra_allowed_cnt > 0:\n            extra_allowed_cnt -= 1\n            extra_cnt = curr_count - opt_count - 1\n        else:\n            extra_cnt = curr_count - opt_count\n    else:\n        extra_cnt = 0\n    return extra_cnt, extra_allowed_cnt",
    "docstring": "Evaluate and return extra same element count based on given values.\n\n    :key-term:\n    group:  In here group can be any base where elements are place\n            i.e. replication-group while placing replicas (elements)\n            or  brokers while placing partitions (elements).\n    element:  Generic term for units which are optimally placed over group.\n\n    :params:\n    curr_count: Given count\n    opt_count:  Optimal count for each group.\n    extra_allowed_cnt:  Count of groups which can have 1 extra element\n                   _    on each group."
  },
  {
    "code": "def children_rest_names(self):\n        names = []\n        for fetcher in self.fetchers:\n            names.append(fetcher.__class__.managed_object_rest_name())\n        return names",
    "docstring": "Gets the list of all possible children ReST names.\n\n            Returns:\n                list: list containing all possible rest names as string\n\n            Example:\n                >>> entity = NUEntity()\n                >>> entity.children_rest_names\n                [\"foo\", \"bar\"]"
  },
  {
    "code": "def addCollector(self, collector):\n        collector.setSchema(self)\n        self.__collectors[collector.name()] = collector",
    "docstring": "Adds the inputted collector reference to this table schema.\n\n        :param      collector | <orb.Collector>"
  },
  {
    "code": "def resize_hess(self, func):\n        if func is None:\n            return None\n        @wraps(func)\n        def resized(*args, **kwargs):\n            out = func(*args, **kwargs)\n            out = np.atleast_2d(np.squeeze(out))\n            mask = [p not in self._fixed_params for p in self.parameters]\n            return np.atleast_2d(out[mask, mask])\n        return resized",
    "docstring": "Removes values with identical indices to fixed parameters from the\n        output of func. func has to return the Hessian of a scalar function.\n\n        :param func: Hessian function to be wrapped. Is assumed to be the\n            Hessian of a scalar function.\n        :return: Hessian corresponding to free parameters only."
  },
  {
    "code": "def build_output_partitions(cls, name='inputTablePartitions', output_name='output'):\n        obj = cls(name)\n        obj.exporter = 'get_output_table_partition'\n        obj.output_name = output_name\n        return obj",
    "docstring": "Build an output table partition parameter\n\n        :param name: parameter name\n        :type name: str\n        :param output_name: bind input port name\n        :type output_name: str\n        :return: output description\n        :rtype: ParamDef"
  },
  {
    "code": "def determine_encoding(path, default=None):\n    byte_order_marks = (\n        ('utf-8-sig', (codecs.BOM_UTF8, )),\n        ('utf-16', (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)),\n        ('utf-32', (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)),\n    )\n    try:\n        with open(path, 'rb') as infile:\n            raw = infile.read(4)\n    except IOError:\n        return default\n    for encoding, boms in byte_order_marks:\n        if any(raw.startswith(bom) for bom in boms):\n            return encoding\n    return default",
    "docstring": "Determines the encoding of a file based on byte order marks.\n\n    Arguments:\n        path (str): The path to the file.\n        default (str, optional): The encoding to return if the byte-order-mark\n            lookup does not return an answer.\n\n    Returns:\n        str: The encoding of the file."
  },
  {
    "code": "def flush(self, fsync=False):\n        if self._handle is not None:\n            self._handle.flush()\n            if fsync:\n                try:\n                    os.fsync(self._handle.fileno())\n                except OSError:\n                    pass",
    "docstring": "Force all buffered modifications to be written to disk.\n\n        Parameters\n        ----------\n        fsync : bool (default False)\n          call ``os.fsync()`` on the file handle to force writing to disk.\n\n        Notes\n        -----\n        Without ``fsync=True``, flushing may not guarantee that the OS writes\n        to disk. With fsync, the operation will block until the OS claims the\n        file has been written; however, other caching layers may still\n        interfere."
  },
  {
    "code": "def register_classes(yaml: ruamel.yaml.YAML, classes: Optional[Iterable[Any]] = None) -> ruamel.yaml.YAML:\n    if classes is None:\n        classes = []\n    for cls in classes:\n        logger.debug(f\"Registering class {cls} with YAML\")\n        yaml.register_class(cls)\n    return yaml",
    "docstring": "Register externally defined classes."
  },
  {
    "code": "def convertDatetime(t):\n    epoch = datetime.datetime.utcfromtimestamp(0)\n    delta = t - epoch\n    millis = delta.total_seconds() * 1000\n    return int(millis)",
    "docstring": "Converts the specified datetime object into its appropriate protocol\n    value. This is the number of milliseconds from the epoch."
  },
  {
    "code": "def ResolveMulti(self, subject, attributes, timestamp=None, limit=None):\n    for attribute in attributes:\n      query, args = self._BuildQuery(subject, attribute, timestamp, limit)\n      result, _ = self.ExecuteQuery(query, args)\n      for row in result:\n        value = self._Decode(attribute, row[\"value\"])\n        yield (attribute, value, row[\"timestamp\"])\n      if limit:\n        limit -= len(result)\n      if limit is not None and limit <= 0:\n        break",
    "docstring": "Resolves multiple attributes at once for one subject."
  },
  {
    "code": "def xmeans(cls, initial_centers=None, kmax=20, tolerance=0.025, criterion=splitting_type.BAYESIAN_INFORMATION_CRITERION, ccore=False):\n        model = xmeans(None, initial_centers, kmax, tolerance, criterion, ccore)\n        return cls(model)",
    "docstring": "Constructor of the x-means clustering.rst algorithm\n\n        :param initial_centers: Initial coordinates of centers of clusters that are represented by list: [center1, center2, ...]\n        Note: The dimensions of the initial centers should be same as of the dataset.\n        :param kmax: Maximum number of clusters that can be allocated.\n        :param tolerance: Stop condition for each iteration: if maximum value of change of centers of clusters is less than tolerance than algorithm will stop processing\n        :param criterion: Type of splitting creation.\n        :param ccore: Defines should be CCORE (C++ pyclustering library) used instead of Python code or not.\n        :return: returns the clustering.rst object"
  },
  {
    "code": "def _validated(self, data):\n        for sub in self.schemas:\n            data = sub(data)\n        return data",
    "docstring": "Validate data if all subschemas validate it."
  },
  {
    "code": "def aggregate(self):\n        for report in self.reportset:\n            printtime('Processing {}'.format(report.split('.')[0]), self.start)\n            header = '' if report != 'mlst.csv' else 'Strain,Genus,SequenceType,Matches,1,2,3,4,5,6,7\\n'\n            data = ''\n            with open(os.path.join(self.reportpath, report), 'w') as aggregate:\n                for sample in self.runmetadata.samples:\n                    try:\n                        with open(os.path.join(sample.general.reportpath, report), 'r') as runreport:\n                            if not header:\n                                header = runreport.readline()\n                            else:\n                                for row in runreport:\n                                    if not row.endswith('\\n'):\n                                        row += '\\n'\n                                    if row.split(',')[0] != header.split(',')[0]:\n                                        data += row\n                    except IOError:\n                        pass\n                aggregate.write(header)\n                aggregate.write(data)",
    "docstring": "Aggregate all reports of the same type into a master report"
  },
  {
    "code": "def print_locale_info (out=stderr):\n    for key in (\"LANGUAGE\", \"LC_ALL\", \"LC_CTYPE\", \"LANG\"):\n        print_env_info(key, out=out)\n    print(_(\"Default locale:\"), i18n.get_locale(), file=out)",
    "docstring": "Print locale info."
  },
  {
    "code": "def update(table, values, where=(), **kwargs):\r\n    where = dict(where, **kwargs).items()\r\n    sql, args = makeSQL(\"UPDATE\", table, values=values, where=where)\r\n    return execute(sql, args).rowcount",
    "docstring": "Convenience wrapper for database UPDATE."
  },
  {
    "code": "def get_default_ssl_version():\n    if hasattr(ssl, 'PROTOCOL_TLSv1_2'):\n        return ssl.PROTOCOL_TLSv1_2\n    elif hasattr(ssl, 'PROTOCOL_TLSv1_1'):\n        return ssl.PROTOCOL_TLSv1_1\n    elif hasattr(ssl, 'PROTOCOL_TLSv1'):\n        return ssl.PROTOCOL_TLSv1\n    return None",
    "docstring": "Get the highest support TLS version, if none is available, return None.\n\n    :rtype: bool|None"
  },
  {
    "code": "def weight_by_edge_odds_ratios(self,\n                                   edges_expected_weight,\n                                   flag_as_significant):\n        for edge_id, expected_weight in edges_expected_weight:\n            edge_obj = self.edges[edge_id]\n            edge_obj.weight /= expected_weight\n            if edge_id in flag_as_significant:\n                edge_obj.significant = True\n            else:\n                edge_obj.significant = False",
    "docstring": "Applied during the permutation test. Update the edges in the\n        network to be weighted by their odds ratios. The odds ratio measures\n        how unexpected the observed edge weight is based on the expected\n        weight.\n\n        Parameters\n        -----------\n        edges_expected_weight : list(tup(int, int), float)\n          A tuple list of (edge id, edge expected weight) generated from the\n          permutation test step.\n        flag_as_significant : [set|list](tup(int, int))\n          A set or list of edge ids that are considered significant against\n          the null model of random associations generated in the permutation\n          test"
  },
  {
    "code": "def scrub(zpool, stop=False, pause=False):\n    if stop:\n        action = ['-s']\n    elif pause:\n        action = ['-p']\n    else:\n        action = None\n    res = __salt__['cmd.run_all'](\n        __utils__['zfs.zpool_command'](\n            command='scrub',\n            flags=action,\n            target=zpool,\n        ),\n        python_shell=False,\n    )\n    if res['retcode'] != 0:\n        return __utils__['zfs.parse_command_result'](res, 'scrubbing')\n    ret = OrderedDict()\n    if stop or pause:\n        ret['scrubbing'] = False\n    else:\n        ret['scrubbing'] = True\n    return ret",
    "docstring": "Scrub a storage pool\n\n    zpool : string\n        Name of storage pool\n\n    stop : boolean\n        If ``True``, cancel ongoing scrub\n\n    pause : boolean\n        If ``True``, pause ongoing scrub\n\n        .. versionadded:: 2018.3.0\n\n        .. note::\n\n            Pause is only available on recent versions of ZFS.\n\n            If both ``pause`` and ``stop`` are ``True``, then ``stop`` will\n            win.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' zpool.scrub myzpool"
  },
  {
    "code": "def concretize(self, **kwargs):\n        lengths = [self.state.solver.eval(x[1], **kwargs) for x in self.content]\n        kwargs['cast_to'] = bytes\n        return [b'' if i == 0 else self.state.solver.eval(x[0][i*self.state.arch.byte_width-1:], **kwargs) for i, x in zip(lengths, self.content)]",
    "docstring": "Returns a list of the packets read or written as bytestrings."
  },
  {
    "code": "def get_one(self, key):\n        query = build_db_query(self.primary_key, key)\n        collection = self.ds.connection(self.collection_name)\n        document = collection.find_one(query)\n        if document is None:\n            raise LookupError('{0} with key {1} was not found'.format(self.model_klass.__name__, query))\n        return self.model_klass.from_json(document)",
    "docstring": "method finds single record base on the given primary key and returns it to the caller"
  },
  {
    "code": "def dictionary(_object, *args):\n    error_msg = 'not of type dictionary'\n    if is_callable(_object):\n        _validator = _object\n        @wraps(_validator)\n        def decorated(value):\n            ensure(isinstance(value, dict), error_msg)\n            return _validator(value)\n        return decorated\n    try:\n        ensure(isinstance(_object, dict), error_msg)\n    except AssertionError:\n        if args:\n            msg = 'did not pass validation against callable: dictionary'\n            raise Invalid('', msg=msg, reason=error_msg, *args)\n        raise",
    "docstring": "Validates a given input is of type dictionary.\n\n    Example usage::\n\n        data = {'a' : {'b': 1}}\n        schema = ('a', dictionary)\n\n    You can also use this as a decorator, as a way to check for the\n    input before it even hits a validator you may be writing.\n\n    .. note::\n        If the argument is a callable, the decorating behavior will be\n        triggered, otherwise it will act as a normal function."
  },
  {
    "code": "def qtiling(fseries, qrange, frange, mismatch=0.2):\n    qplane_tile_dict = {}\n    qs = list(_iter_qs(qrange, deltam_f(mismatch)))\n    for q in qs:\n        qtilefreq = _iter_frequencies(q, frange, mismatch, fseries.duration)\n        qplane_tile_dict[q] = numpy.array(list(qtilefreq))\n    return qplane_tile_dict",
    "docstring": "Iterable constructor of QTile tuples\n\n    Parameters\n    ----------\n    fseries: 'pycbc FrequencySeries'\n        frequency-series data set\n    qrange:\n        upper and lower bounds of q range\n    frange:\n        upper and lower bounds of frequency range\n    mismatch:\n        percentage of desired fractional mismatch\n\n    Returns\n    -------\n    qplane_tile_dict: 'dict'\n        dictionary containing Q-tile tuples for a set of Q-planes"
  },
  {
    "code": "def _construct_target(self, function):\n        target = {\n                'Arn': function.get_runtime_attr(\"arn\"),\n                'Id': self.logical_id + 'LambdaTarget'\n        }\n        if self.Input is not None:\n            target['Input'] = self.Input\n        if self.InputPath is not None:\n            target['InputPath'] = self.InputPath\n        return target",
    "docstring": "Constructs the Target property for the CloudWatch Events Rule.\n\n        :returns: the Target property\n        :rtype: dict"
  },
  {
    "code": "def array_keys(self):\n        for key in sorted(listdir(self._store, self._path)):\n            path = self._key_prefix + key\n            if contains_array(self._store, path):\n                yield key",
    "docstring": "Return an iterator over member names for arrays only.\n\n        Examples\n        --------\n        >>> import zarr\n        >>> g1 = zarr.group()\n        >>> g2 = g1.create_group('foo')\n        >>> g3 = g1.create_group('bar')\n        >>> d1 = g1.create_dataset('baz', shape=100, chunks=10)\n        >>> d2 = g1.create_dataset('quux', shape=200, chunks=20)\n        >>> sorted(g1.array_keys())\n        ['baz', 'quux']"
  },
  {
    "code": "def _clean_dic(self, dic):\n        aux_dic = dic.copy()\n        for key, value in iter(dic.items()):\n            if value is None or value == '':\n                del aux_dic[key]\n            elif type(value) is dict:\n                cleaned_dict = self._clean_dic(value)\n                if not cleaned_dict:\n                    del aux_dic[key]\n                    continue\n                aux_dic[key] = cleaned_dict\n        return aux_dic",
    "docstring": "Clean recursively all empty or None values inside a dict."
  },
  {
    "code": "def setup_completion(shell):\n    import glob\n    try:\n        import readline\n    except ImportError:\n        import pyreadline as readline\n    def _complete(text, state):\n        buf = readline.get_line_buffer()\n        if buf.startswith('help ') or \" \" not in buf:\n            return [x for x in shell.valid_identifiers() if x.startswith(text)][state]\n        return (glob.glob(os.path.expanduser(text)+'*')+[None])[state]\n    readline.set_completer_delims(' \\t\\n;')\n    if readline.__doc__ is not None and 'libedit' in readline.__doc__:\n        readline.parse_and_bind(\"bind ^I rl_complete\")\n    else:\n        readline.parse_and_bind(\"tab: complete\")\n    readline.set_completer(_complete)",
    "docstring": "Setup readline to tab complete in a cross platform way."
  },
  {
    "code": "def sinter(self, *other_sets):\n        return self.db.sinter([self.key] + [s.key for s in other_sets])",
    "docstring": "Performs an intersection between Sets.\n\n        Returns a set of common members. Uses Redis.sinter."
  },
  {
    "code": "def decode(self, frame: Frame, *, max_size: Optional[int] = None) -> Frame:\n        if frame.opcode in CTRL_OPCODES:\n            return frame\n        if frame.opcode == OP_CONT:\n            if not self.decode_cont_data:\n                return frame\n            if frame.fin:\n                self.decode_cont_data = False\n        else:\n            if not frame.rsv1:\n                return frame\n            if not frame.fin:\n                self.decode_cont_data = True\n            if self.remote_no_context_takeover:\n                self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits)\n        data = frame.data\n        if frame.fin:\n            data += _EMPTY_UNCOMPRESSED_BLOCK\n        max_length = 0 if max_size is None else max_size\n        data = self.decoder.decompress(data, max_length)\n        if self.decoder.unconsumed_tail:\n            raise PayloadTooBig(\n                f\"Uncompressed payload length exceeds size limit (? > {max_size} bytes)\"\n            )\n        if frame.fin and self.remote_no_context_takeover:\n            del self.decoder\n        return frame._replace(data=data, rsv1=False)",
    "docstring": "Decode an incoming frame."
  },
  {
    "code": "def abstract(cls, predstr):\n        lemma, pos, sense, _ = split_pred_string(predstr)\n        return cls(Pred.ABSTRACT, lemma, pos, sense, predstr)",
    "docstring": "Instantiate a Pred from its symbol string."
  },
  {
    "code": "def error(self):\n        for item in self:\n            if isinstance(item, WorkItem) and item.error:\n                return item.error\n        return None",
    "docstring": "Returns the error for this barrier and all work items, if any."
  },
  {
    "code": "def get_tan_mechanisms(self):\n        retval = OrderedDict()\n        for version in sorted(IMPLEMENTED_HKTAN_VERSIONS.keys()):\n            for seg in self.bpd.find_segments('HITANS', version):\n                for parameter in seg.parameter.twostep_parameters:\n                    if parameter.security_function in self.allowed_security_functions:\n                        retval[parameter.security_function] = parameter\n        return retval",
    "docstring": "Get the available TAN mechanisms.\n\n        Note: Only checks for HITANS versions listed in IMPLEMENTED_HKTAN_VERSIONS.\n\n        :return: Dictionary of security_function: TwoStepParameters objects."
  },
  {
    "code": "def from_url(reddit_session, url, comment_limit=0, comment_sort=None,\n                 comments_only=False, params=None):\n        if params is None:\n            params = {}\n        parsed = urlparse(url)\n        query_pairs = parse_qs(parsed.query)\n        get_params = dict((k, \",\".join(v)) for k, v in query_pairs.items())\n        params.update(get_params)\n        url = urlunparse(parsed[:3] + (\"\", \"\", \"\"))\n        if comment_limit is None:\n            params['limit'] = 2048\n        elif comment_limit > 0:\n            params['limit'] = comment_limit\n        if comment_sort:\n            params['sort'] = comment_sort\n        response = reddit_session.request_json(url, params=params)\n        if comments_only:\n            return response[1]['data']['children']\n        submission = Submission.from_json(response)\n        submission._comment_sort = comment_sort\n        submission._params = params\n        return submission",
    "docstring": "Request the url and return a Submission object.\n\n        :param reddit_session: The session to make the request with.\n        :param url: The url to build the Submission object from.\n        :param comment_limit: The desired number of comments to fetch. If <= 0\n            fetch the default number for the session's user. If None, fetch the\n            maximum possible.\n        :param comment_sort: The sort order for retrieved comments. When None\n            use the default for the session's user.\n        :param comments_only: Return only the list of comments.\n        :param params: dictionary containing extra GET data to put in the url."
  },
  {
    "code": "def kwarg(string, separator='='):\n    if separator not in string:\n        raise ValueError(\"Separator '%s' not in value '%s'\"\n                         % (separator, string))\n    if string.strip().startswith(separator):\n        raise ValueError(\"Value '%s' starts with separator '%s'\"\n                         % (string, separator))\n    if string.strip().endswith(separator):\n        raise ValueError(\"Value '%s' ends with separator '%s'\"\n                         % (string, separator))\n    if string.count(separator) != 1:\n        raise ValueError(\"Value '%s' should only have one '%s' separator\"\n                         % (string, separator))\n    key, value = string.split(separator)\n    return {key: value}",
    "docstring": "Return a dict from a delimited string."
  },
  {
    "code": "def start(self, version=None, **kwargs):\n    if not version:\n        version = self.mostRecentVersion\n    pysc2Version = lib.Version(\n        version.version,\n        version.baseVersion,\n        version.dataHash,\n        version.fixedHash)\n    return sc_process.StarcraftProcess(\n                self,\n                exec_path=self.exec_path(version.baseVersion),\n                version=pysc2Version,\n                **kwargs)",
    "docstring": "Launch the game process."
  },
  {
    "code": "def collect(self):\n        for func in self._caches:\n            cache = {}\n            for key in self._caches[func]:\n                if (time.time() - self._caches[func][key][1]) < self._timeouts[func]:\n                    cache[key] = self._caches[func][key]\n            self._caches[func] = cache",
    "docstring": "Clear cache of results which have timed out"
  },
  {
    "code": "def get_local_extrema(self, find_min=True, threshold_frac=None,\n                          threshold_abs=None):\n        sign, extrema_type = 1, \"local maxima\"\n        if find_min:\n            sign, extrema_type = -1, \"local minima\"\n        total_chg = sign * self.chgcar.data[\"total\"]\n        total_chg = np.tile(total_chg, reps=(3, 3, 3))\n        coordinates = peak_local_max(total_chg, min_distance=1)\n        f_coords = [coord / total_chg.shape * 3 for coord in coordinates]\n        f_coords = [f - 1 for f in f_coords if\n                    all(np.array(f) < 2) and all(np.array(f) >= 1)]\n        self._update_extrema(f_coords, extrema_type,\n                             threshold_frac=threshold_frac,\n                             threshold_abs=threshold_abs)\n        return self.extrema_coords",
    "docstring": "Get all local extrema fractional coordinates in charge density,\n        searching for local minimum by default. Note that sites are NOT grouped\n        symmetrically.\n\n        Args:\n            find_min (bool): True to find local minimum else maximum, otherwise\n                find local maximum.\n\n            threshold_frac (float): optional fraction of extrema shown, which\n                returns `threshold_frac * tot_num_extrema` extrema fractional\n                coordinates based on highest/lowest intensity.\n\n                E.g. set 0.2 to show the extrema with 20% highest or lowest\n                intensity. Value range: 0 <= threshold_frac <= 1\n\n                Note that threshold_abs and threshold_frac should not set in the\n                same time.\n\n            threshold_abs (float): optional filter. When searching for local\n                minima, intensity <= threshold_abs returns; when searching for\n                local maxima, intensity >= threshold_abs returns.\n\n                Note that threshold_abs and threshold_frac should not set in the\n                same time.\n\n        Returns:\n            extrema_coords (list): list of fractional coordinates corresponding\n                to local extrema."
  },
  {
    "code": "def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model):\n    X_train, X_test = to_array(X_train, X_test)\n    assert X_train.shape[1] == X_test.shape[1]\n    yp_test = trained_model.predict(X_test)\n    return metric(yp_test, strip_list(attr_test).sum(1))",
    "docstring": "The how well do the features plus a constant base rate sum up to the model output."
  },
  {
    "code": "def x_build_targets_target( self, node ):\n        target_node = node\n        name = self.get_child_data(target_node,tag='name',strip=True)\n        path = self.get_child_data(target_node,tag='path',strip=True)\n        jam_target = self.get_child_data(target_node,tag='jam-target',strip=True)\n        self.target[jam_target] = {\n            'name' : name,\n            'path' : path\n            }\n        dep_node = self.get_child(self.get_child(target_node,tag='dependencies'),tag='dependency')\n        while dep_node:\n            child = self.get_data(dep_node,strip=True)\n            child_jam_target = '<p%s>%s' % (path,child.split('//',1)[1])\n            self.parent[child_jam_target] = jam_target\n            dep_node = self.get_sibling(dep_node.nextSibling,tag='dependency')\n        return None",
    "docstring": "Process the target dependency DAG into an ancestry tree so we can look up\n        which top-level library and test targets specific build actions correspond to."
  },
  {
    "code": "def setnx(self, key, value):\n        return self.set(key, value, nx=True)",
    "docstring": "Set the value of ``key`` to ``value`` if key doesn't exist"
  },
  {
    "code": "def filter_host_by_regex(regex):\n    host_re = re.compile(regex)\n    def inner_filter(items):\n        host = items[\"host\"]\n        if host is None:\n            return False\n        return host_re.match(host.host_name) is not None\n    return inner_filter",
    "docstring": "Filter for host\n    Filter on regex\n\n    :param regex: regex to filter\n    :type regex: str\n    :return: Filter\n    :rtype: bool"
  },
  {
    "code": "def candle_lighting(self):\n        today = HDate(gdate=self.date, diaspora=self.location.diaspora)\n        tomorrow = HDate(gdate=self.date + dt.timedelta(days=1),\n                         diaspora=self.location.diaspora)\n        if ((today.is_yom_tov or today.is_shabbat)\n                and (tomorrow.is_yom_tov or tomorrow.is_shabbat)):\n            return self._havdalah_datetime\n        if tomorrow.is_shabbat or tomorrow.is_yom_tov:\n            return (self.zmanim[\"sunset\"]\n                    - dt.timedelta(minutes=self.candle_lighting_offset))\n        return None",
    "docstring": "Return the time for candle lighting, or None if not applicable."
  },
  {
    "code": "def _fetch_templates(src):\n    templates = []\n    log.debug('Listing contents of %s', src)\n    for item in os.listdir(src):\n        s = os.path.join(src, item)\n        if os.path.isdir(s):\n            template_path = os.path.join(s, TEMPLATE_FILE_NAME)\n            if os.path.isfile(template_path):\n                templates.append(_get_template(template_path, item))\n            else:\n                log.debug(\"Directory does not contain %s %s\", template_path,\n                          TEMPLATE_FILE_NAME)\n    return templates",
    "docstring": "Fetch all of the templates in the src directory\n\n    :param src: The source path\n    :type  src: ``str``\n\n    :rtype: ``list`` of ``tuple``\n    :returns: ``list`` of ('key', 'description')"
  },
  {
    "code": "def download(self, image, url_field='url', suffix=None):\n        url = getattr(image, url_field)\n        if suffix is not None:\n            url = '.'.join(url, suffix)\n        response = self.session.get(url)\n        return response.content",
    "docstring": "Download the binary data of an image attachment.\n\n        :param image: an image attachment\n        :type image: :class:`~groupy.api.attachments.Image`\n        :param str url_field: the field of the image with the right URL\n        :param str suffix: an optional URL suffix\n        :return: binary image data\n        :rtype: bytes"
  },
  {
    "code": "def __add_prop(self, key, admin=False):\n        def getter(self):\n            return self.config[key]\n        def setter(self, val):\n            if admin and not self.admin:\n                raise RuntimeError(\n                    f\"You can't set the {key} key without mod privileges\"\n                )\n            self.__set_config_value(self.config.get_real_key(key), val)\n        setattr(self.__class__, key, property(getter, setter))",
    "docstring": "Add gettable and settable room config property during runtime"
  },
  {
    "code": "def join_tables(left, right, key_left, key_right,\n                cols_right=None):\n    right = right.copy()\n    if cols_right is None:\n        cols_right = right.colnames\n    else:\n        cols_right = [c for c in cols_right if c in right.colnames]\n    if key_left != key_right:\n        right[key_right].name = key_left\n    if key_left not in cols_right:\n        cols_right += [key_left]\n    out = join(left, right[cols_right], keys=key_left,\n               join_type='left')\n    for col in out.colnames:\n        if out[col].dtype.kind in ['S', 'U']:\n            out[col].fill_value = ''\n        elif out[col].dtype.kind in ['i']:\n            out[col].fill_value = 0\n        else:\n            out[col].fill_value = np.nan\n    return out.filled()",
    "docstring": "Perform a join of two tables.\n\n    Parameters\n    ----------\n    left : `~astropy.Table`\n        Left table for join.\n\n    right : `~astropy.Table`\n        Right table for join.\n\n    key_left : str\n        Key used to match elements from ``left`` table.\n\n    key_right : str\n        Key used to match elements from ``right`` table.\n\n    cols_right : list    \n        Subset of columns from ``right`` table that will be appended\n        to joined table."
  },
  {
    "code": "def _counts(self):\n        rolling_dim = utils.get_temp_dimname(self.obj.dims, '_rolling_dim')\n        counts = (self.obj.notnull()\n                  .rolling(center=self.center, **{self.dim: self.window})\n                  .construct(rolling_dim, fill_value=False)\n                  .sum(dim=rolling_dim, skipna=False))\n        return counts",
    "docstring": "Number of non-nan entries in each rolling window."
  },
  {
    "code": "def handle_command_exit_code(self, code):\n        ca = self.call_args\n        exc_class = get_exc_exit_code_would_raise(code, ca[\"ok_code\"],\n                ca[\"piped\"])\n        if exc_class:\n            exc = exc_class(self.ran, self.process.stdout, self.process.stderr,\n                    ca[\"truncate_exc\"])\n            raise exc",
    "docstring": "here we determine if we had an exception, or an error code that we\n        weren't expecting to see.  if we did, we create and raise an exception"
  },
  {
    "code": "def parse(self, argument):\n    if not self.enum_values:\n      return argument\n    elif self.case_sensitive:\n      if argument not in self.enum_values:\n        raise ValueError('value should be one of <%s>' %\n                         '|'.join(self.enum_values))\n      else:\n        return argument\n    else:\n      if argument.upper() not in [value.upper() for value in self.enum_values]:\n        raise ValueError('value should be one of <%s>' %\n                         '|'.join(self.enum_values))\n      else:\n        return [value for value in self.enum_values\n                if value.upper() == argument.upper()][0]",
    "docstring": "Determine validity of argument and return the correct element of enum.\n\n    If self.enum_values is empty, then all arguments are valid and argument\n    will be returned.\n\n    Otherwise, if argument matches an element in enum, then the first\n    matching element will be returned.\n\n    Args:\n      argument: The supplied flag value.\n\n    Returns:\n      The matching element from enum_values, or argument if enum_values is\n      empty.\n\n    Raises:\n      ValueError: enum_values was non-empty, but argument didn't match\n        anything in enum."
  },
  {
    "code": "def delete(self, namespace, key):\n        if self.key_exists(namespace, key):\n            obj = db.ConfigItem.find_one(\n                ConfigItem.namespace_prefix == namespace,\n                ConfigItem.key == key\n            )\n            del self.__data[namespace][key]\n            db.session.delete(obj)\n            db.session.commit()\n        else:\n            raise KeyError('{}/{}'.format(namespace, key))",
    "docstring": "Remove a configuration item from the database\n\n        Args:\n            namespace (`str`): Namespace of the config item\n            key (`str`): Key to delete\n\n        Returns:\n            `None`"
  },
  {
    "code": "def change_password(self, new_password, email):\n        log.info(\"[+] Changing the password of the account\")\n        return self._send_xmpp_element(account.ChangePasswordRequest(self.password, new_password, email, self.username))",
    "docstring": "Changes the login password\n\n        :param new_password: The new login password to set for the account\n        :param email: The current email of the account"
  },
  {
    "code": "def create(cls, term, *ranges):\n        if not isinstance(term, Scalar):\n            term = ScalarValue.create(term)\n        return super().create(term, *ranges)",
    "docstring": "Instantiate the indexed sum while applying simplification rules"
  },
  {
    "code": "def proto_files(root):\n  for (dirpath, _, filenames) in os.walk(root):\n    for filename in filenames:\n      if filename.endswith('.proto'):\n        yield os.path.join(dirpath, filename)",
    "docstring": "Yields the path of all .proto files under the root."
  },
  {
    "code": "def toTag(self, output):\n        feed = output.createElement('feed')\n        feed.setAttribute('name', self.name)\n        feed.setAttribute('priority', str(self.priority))\n        schedule = output.createElement('schedule')\n        schedule.setAttribute('dayOfMonth', self.dayOfMonth)\n        schedule.setAttribute('dayOfWeek', self.dayOfWeek)\n        schedule.setAttribute('hour', self.hour)\n        schedule.setAttribute('minute', self.minute)\n        if self.retry:\n            schedule.setAttribute('retry', self.retry)\n        feed.appendChild(schedule)\n        url = output.createElement('url')\n        url.appendChild(output.createTextNode(self.url))\n        feed.appendChild(url)\n        if self.source:\n            source = output.createElement('source')\n            source.appendChild(output.createTextNode(self.source))\n            feed.appendChild(source)\n        return feed",
    "docstring": "This methods returns all data of this feed as feed xml tag\n\n        :param output: XML Document to which the data should be added\n        :type output: xml.dom.DOMImplementation.createDocument"
  },
  {
    "code": "def _remove(self, n):\n        if os.path.isfile(n):\n            os.remove(n)\n        if not os.path.isfile(n):\n            print(\"File '{0}' removed\".format(n))",
    "docstring": "Remove one single file"
  },
  {
    "code": "def getLocalDateAndTime(date, time, *args, **kwargs):\n    localDt = getLocalDatetime(date, time, *args, **kwargs)\n    if time is not None:\n        return (localDt.date(), localDt.timetz())\n    else:\n        return (localDt.date(), None)",
    "docstring": "Get the date and time in the local timezone from date and optionally time"
  },
  {
    "code": "def run_and_exit_if(opts, action, *names):\n    for name in names:\n        if name in opts:\n            action()\n            sys.exit(0)",
    "docstring": "Run the no-arg function `action` if any of `names` appears in the\n    option dict `opts`."
  },
  {
    "code": "def run_conditional_decorators(self, context):\n        logger.debug(\"starting\")\n        run_me = context.get_formatted_as_type(self.run_me, out_type=bool)\n        skip_me = context.get_formatted_as_type(self.skip_me, out_type=bool)\n        swallow_me = context.get_formatted_as_type(self.swallow_me,\n                                                   out_type=bool)\n        if run_me:\n            if not skip_me:\n                try:\n                    if self.retry_decorator:\n                        self.retry_decorator.retry_loop(context,\n                                                        self.invoke_step)\n                    else:\n                        self.invoke_step(context=context)\n                except Exception as ex_info:\n                    if swallow_me:\n                        logger.error(\n                            f\"{self.name} Ignoring error because swallow \"\n                            \"is True for this step.\\n\"\n                            f\"{type(ex_info).__name__}: {ex_info}\")\n                    else:\n                        raise\n            else:\n                logger.info(\n                    f\"{self.name} not running because skip is True.\")\n        else:\n            logger.info(f\"{self.name} not running because run is False.\")\n        logger.debug(\"done\")",
    "docstring": "Evaluate the step decorators to decide whether to run step or not.\n\n        Use pypyr.dsl.Step.run_step if you intend on executing the step the\n        same way pypyr does.\n\n        Args:\n            context: (pypyr.context.Context) The pypyr context. This arg will\n                     mutate."
  },
  {
    "code": "def camelResource(obj):\n    if not isinstance(obj, dict):\n        return obj\n    for k in list(obj.keys()):\n        v = obj.pop(k)\n        obj[\"%s%s\" % (k[0].upper(), k[1:])] = v\n        if isinstance(v, dict):\n            camelResource(v)\n        elif isinstance(v, list):\n            list(map(camelResource, v))\n    return obj",
    "docstring": "Some sources from apis return lowerCased where as describe calls\n\n    always return TitleCase, this function turns the former to the later"
  },
  {
    "code": "def update(self, workspace, params={}, **options): \n        path = \"/workspaces/%s\" % (workspace)\n        return self.client.put(path, params, **options)",
    "docstring": "A specific, existing workspace can be updated by making a PUT request on\n        the URL for that workspace. Only the fields provided in the data block\n        will be updated; any unspecified fields will remain unchanged.\n        \n        Currently the only field that can be modified for a workspace is its `name`.\n        \n        Returns the complete, updated workspace record.\n\n        Parameters\n        ----------\n        workspace : {Id} The workspace to update.\n        [data] : {Object} Data for the request"
  },
  {
    "code": "def make_retrieveParameters(offset=1, count=100, name='RS', sort='D'):\n        return _OrderedDict([\n            ('firstRecord', offset),\n            ('count', count),\n            ('sortField', _OrderedDict([('name', name), ('sort', sort)]))\n        ])",
    "docstring": "Create retrieve parameters dictionary to be used with APIs.\n\n        :count: Number of records to display in the result. Cannot be less than\n                0 and cannot be greater than 100. If count is 0 then only the\n                summary information will be returned.\n\n        :offset: First record in results to return. Must be greater than zero\n\n        :name: Name of the field to order by. Use a two-character abbreviation\n               to specify the field ('AU': Author, 'CF': Conference Title,\n               'CG': Page, 'CW': Source, 'CV': Volume, 'LC': Local Times Cited,\n               'LD': Load Date, 'PG': Page, 'PY': Publication Year, 'RS':\n               Relevance, 'SO': Source, 'TC': Times Cited, 'VL': Volume)\n\n        :sort: Must be A (ascending) or D (descending). The sort parameter can\n               only be D for Relevance and TimesCited."
  },
  {
    "code": "def setwrap(value: Any) -> Set[str]:\n    return set(map(str, set(flatten([value]))))",
    "docstring": "Returns a flattened and stringified set from the given object or iterable.\n\n    For use in public functions which accept argmuents or kwargs that can be\n    one object or a list of objects."
  },
  {
    "code": "def pop_event(self, event_name, timeout=DEFAULT_TIMEOUT):\n        if not self.started:\n            raise IllegalStateError(\n                \"Dispatcher needs to be started before popping.\")\n        e_queue = self.get_event_q(event_name)\n        if not e_queue:\n            raise TypeError(\"Failed to get an event queue for {}\".format(\n                event_name))\n        try:\n            if timeout:\n                return e_queue.get(True, timeout)\n            elif timeout == 0:\n                return e_queue.get(False)\n            else:\n                return e_queue.get(True)\n        except queue.Empty:\n            raise queue.Empty('Timeout after {}s waiting for event: {}'.format(\n                timeout, event_name))",
    "docstring": "Pop an event from its queue.\n\n        Return and remove the oldest entry of an event.\n        Block until an event of specified name is available or\n        times out if timeout is set.\n\n        Args:\n            event_name: Name of the event to be popped.\n            timeout: Number of seconds to wait when event is not present.\n                Never times out if None.\n\n        Returns:\n            The oldest entry of the specified event. None if timed out.\n\n        Raises:\n            IllegalStateError: Raised if pop is called before the dispatcher\n                starts polling."
  },
  {
    "code": "def to_sparse(self, fill_value=None, kind='block'):\n        from pandas.core.sparse.api import SparseDataFrame\n        return SparseDataFrame(self._series, index=self.index,\n                               columns=self.columns, default_kind=kind,\n                               default_fill_value=fill_value)",
    "docstring": "Convert to SparseDataFrame.\n\n        Implement the sparse version of the DataFrame meaning that any data\n        matching a specific value it's omitted in the representation.\n        The sparse DataFrame allows for a more efficient storage.\n\n        Parameters\n        ----------\n        fill_value : float, default None\n            The specific value that should be omitted in the representation.\n        kind : {'block', 'integer'}, default 'block'\n            The kind of the SparseIndex tracking where data is not equal to\n            the fill value:\n\n            - 'block' tracks only the locations and sizes of blocks of data.\n            - 'integer' keeps an array with all the locations of the data.\n\n            In most cases 'block' is recommended, since it's more memory\n            efficient.\n\n        Returns\n        -------\n        SparseDataFrame\n            The sparse representation of the DataFrame.\n\n        See Also\n        --------\n        DataFrame.to_dense :\n            Converts the DataFrame back to the its dense form.\n\n        Examples\n        --------\n        >>> df = pd.DataFrame([(np.nan, np.nan),\n        ...                    (1., np.nan),\n        ...                    (np.nan, 1.)])\n        >>> df\n             0    1\n        0  NaN  NaN\n        1  1.0  NaN\n        2  NaN  1.0\n        >>> type(df)\n        <class 'pandas.core.frame.DataFrame'>\n\n        >>> sdf = df.to_sparse()\n        >>> sdf\n             0    1\n        0  NaN  NaN\n        1  1.0  NaN\n        2  NaN  1.0\n        >>> type(sdf)\n        <class 'pandas.core.sparse.frame.SparseDataFrame'>"
  },
  {
    "code": "def begin_recording(self):\n        logger.info(\"[RewardProxyServer] [%d] Starting recording\", self.id)\n        if self._closed:\n            logger.error(\n                \"[RewardProxyServer] [%d] Attempted to start writing although client connection is already closed. Aborting\", self.id)\n            self.close()\n            return\n        if self._n_open_files != 0:\n            logger.error(\"[RewardProxyServer] [%d] WARNING: n open rewards files = %s. This is unexpected. Dropping connection.\", self.id, self._n_open_files)\n            self.close()\n            return\n        logfile_path = os.path.join(self.factory.logfile_dir, 'rewards.demo')\n        logger.info('Recording to {}'.format(logfile_path))\n        self.file = open(logfile_path, 'w')\n        self._n_open_files += 1\n        logger.info(\"[RewardProxyServer] [%d] n open rewards files incremented: %s\", self.id, self._n_open_files)\n        self.file.write(json.dumps({\n            'version': 1,\n            '_debug_version': '0.0.1',\n        }))\n        self.file.write('\\n')\n        self.file.flush()\n        logger.info(\"[RewardProxyServer] [%d] Wrote version number\", self.id)",
    "docstring": "Open the file and write the metadata header to describe this recording. Called after we establish an end-to-end connection\n        This uses Version 1 of our protocol\n\n        Version 0 can be seen here: https://github.com/openai/universe/blob/f85a7779c3847fa86ec7bb513a1da0d3158dda78/bin/recording_agent.py"
  },
  {
    "code": "def custom_arg(self, custom_arg):\n        if isinstance(custom_arg, list):\n            for c in custom_arg:\n                self.add_custom_arg(c)\n        else:\n            self.add_custom_arg(custom_arg)",
    "docstring": "Add custom args to the email\n\n        :param value: A list of CustomArg objects or a dict of custom arg\n                      key/values\n        :type value: CustomArg, list(CustomArg), dict"
  },
  {
    "code": "def set_logger(self, logger_name, level, handler=None):\n        if 'loggers' not in self.config:\n            self.config['loggers'] = {}\n        real_level = self.real_level(level)\n        self.config['loggers'][logger_name] = {'level': real_level}\n        if handler:\n            self.config['loggers'][logger_name]['handlers'] = [handler]",
    "docstring": "Sets the level of a logger"
  },
  {
    "code": "def add_tmpltbank_from_hdf_file(self, hdf_fp, vary_fupper=False):\n        mass1s = hdf_fp['mass1'][:]\n        mass2s = hdf_fp['mass2'][:]\n        spin1zs = hdf_fp['spin1z'][:]\n        spin2zs = hdf_fp['spin2z'][:]\n        for idx in xrange(len(mass1s)):\n            self.add_point_by_masses(mass1s[idx], mass2s[idx], spin1zs[idx],\n                                     spin2zs[idx], vary_fupper=vary_fupper)",
    "docstring": "This function will take a pointer to an open HDF File object containing\n        a list of templates and add them into the partitioned template bank\n        object.\n\n        Parameters\n        -----------\n        hdf_fp : h5py.File object\n            The template bank in HDF5 format.\n        vary_fupper : False\n            If given also include the additional information needed to compute\n            distances with a varying upper frequency cutoff."
  },
  {
    "code": "def regex(self):\n        if not self._compiled_regex:\n            self._compiled_regex = re.compile(self.raw)\n        return self._compiled_regex",
    "docstring": "Return compiled regex."
  },
  {
    "code": "def find_label(self, label: Label):\n        for index, action in enumerate(self.program):\n            if isinstance(action, JumpTarget):\n                if label == action.label:\n                    return index\n        raise RuntimeError(\"Improper program - Jump Target not found in the \"\n                           \"input program!\")",
    "docstring": "Helper function that iterates over the program and looks for a JumpTarget that has a\n        Label matching the input label.\n\n        :param label: Label object to search for in program\n        :return: Program index where ``label`` is found"
  },
  {
    "code": "def get_maps(A):\n    N = A.shape[0]\n    flat_map = []\n    for i in range(1, N):\n        for j in range(1, N):\n            flat_map.append([i, j])\n    flat_map = np.array(flat_map)\n    square_map = np.zeros(A.shape, 'int')\n    for k in range((N - 1) ** 2):\n        i, j = flat_map[k]\n        square_map[i, j] = k\n    return flat_map, square_map",
    "docstring": "Get mappings from the square array A to the flat vector of parameters\n    alpha.\n\n    Helper function for PCCA+ optimization.\n\n    Parameters\n    ----------\n    A : ndarray\n        The transformation matrix A.\n\n    Returns\n    -------\n    flat_map : ndarray\n        Mapping from flat indices (k) to square (i,j) indices.\n    square map : ndarray\n        Mapping from square indices (i,j) to flat indices (k)."
  },
  {
    "code": "def set_current_filename(self, filename, focus=True):\r\n        index = self.has_filename(filename)\r\n        if index is not None:\r\n            if focus:\r\n                self.set_stack_index(index)\r\n            editor = self.data[index].editor\r\n            if focus:\r\n                editor.setFocus()\r\n            else:\r\n                self.stack_history.remove_and_append(index)\r\n            return editor",
    "docstring": "Set current filename and return the associated editor instance."
  },
  {
    "code": "def Extinction(extval,name=None):\n   try:\n       ext=Cache.RedLaws[name].reddening(extval)\n   except AttributeError:\n       Cache.RedLaws[name]=RedLaw(Cache.RedLaws[name])\n       ext=Cache.RedLaws[name].reddening(extval)\n   except KeyError:\n       try:\n           Cache.RedLaws[name]=RedLaw(name)\n           ext=Cache.RedLaws[name].reddening(extval)\n       except IOError:\n           try:\n               ext=extinction.DeprecatedExtinction(extval,name)\n           except KeyError:\n               raise ValueError('No extinction law has been defined for \"%s\", and no such file exists'%name)\n   return ext",
    "docstring": "Generate extinction curve to be used with spectra.\n\n    By default, :meth:`~CustomRedLaw.reddening` is used to\n    generate the extinction curve. If a deprecated\n    reddening law is given, then\n    `~pysynphot.extinction.DeprecatedExtinction` is used\n    instead.\n\n   .. note::\n\n       Reddening laws are cached in ``pysynphot.Cache.RedLaws``\n       for better performance. Repeated calls to the same\n       reddening law here returns the cached result.\n\n   Parameters\n   ----------\n   extval : float\n       Value of :math:`E(B-V)` in magnitudes.\n\n   name : str or `None`\n       Name of reddening law (see :func:`print_red_laws`).\n       If `None` (default), the average Milky Way extinction\n       (``'mwavg'``) will be used.\n\n   Returns\n   -------\n   ext : `~pysynphot.spectrum.ArraySpectralElement` or `~pysynphot.extinction.DeprecatedExtinction`\n       Extinction curve.\n\n   Raises\n   ------\n   ValueError\n       Invalid reddening law.\n\n   Examples\n   --------\n   >>> ext = S.Extinction(0.3, 'mwavg')"
  },
  {
    "code": "def evaluate(self, env):\n        if self.ident in env.functions:\n            arg_vals = [expr.evaluate(env) for expr in self.args]\n            try:\n                out = env.functions[self.ident](*arg_vals)\n            except Exception as exc:\n                return u'<%s>' % str(exc)\n            return str(out)\n        else:\n            return self.original",
    "docstring": "Evaluate the function call in the environment, returning a\n        Unicode string."
  },
  {
    "code": "def validate_broker_ids_subset(broker_ids, subset_ids):\n    all_ids = set(broker_ids)\n    valid = True\n    for subset_id in subset_ids:\n        valid = valid and subset_id in all_ids\n        if subset_id not in all_ids:\n            print(\"Error: user specified broker id {0} does not exist in cluster.\".format(subset_id))\n    return valid",
    "docstring": "Validate that user specified broker ids to restart exist in the broker ids retrieved\n    from cluster config.\n\n    :param broker_ids: all broker IDs in a cluster\n    :type broker_ids: list of integers\n    :param subset_ids: broker IDs specified by user\n    :type subset_ids: list of integers\n    :returns: bool"
  },
  {
    "code": "async def close(self):\n        if not self._conn:\n            return\n        c = await self._execute(self._conn.close)\n        self._conn = None\n        return c",
    "docstring": "Close pyodbc connection"
  },
  {
    "code": "def set_qword_at_rva(self, rva, qword):\n        return self.set_bytes_at_rva(rva, self.get_data_from_qword(qword))",
    "docstring": "Set the quad-word value at the file offset corresponding to the given RVA."
  },
  {
    "code": "def simhash(self, content):\n        if content is None:\n            self.hash = -1\n            return\n        if isinstance(content, str):\n            features = self.tokenizer_func(content, self.keyword_weight_pari)\n            self.hash = self.build_from_features(features)\n        elif isinstance(content, collections.Iterable):\n            self.hash = self.build_from_features(content)\n        elif isinstance(content, int):\n            self.hash = content\n        else:\n            raise Exception(\"Unsupported parameter type %s\" % type(content))",
    "docstring": "Select policies for simhash on the different types of content."
  },
  {
    "code": "def _read_journal(self):\n        root = self._filesystem.inspect_get_roots()[0]\n        inode = self._filesystem.stat('C:\\\\$Extend\\\\$UsnJrnl')['ino']\n        with NamedTemporaryFile(buffering=0) as tempfile:\n            self._filesystem.download_inode(root, inode, tempfile.name)\n            journal = usn_journal(tempfile.name)\n            return parse_journal(journal)",
    "docstring": "Extracts the USN journal from the disk and parses its content."
  },
  {
    "code": "def clone(self, **data):\n        meta = self._meta\n        session = self.session\n        pkname = meta.pkname()\n        pkvalue = data.pop(pkname, None)\n        fields = self.todict(exclude_cache=True)\n        fields.update(data)\n        fields.pop('__dbdata__', None)\n        obj = self._meta.make_object((pkvalue, None, fields))\n        obj.session = session\n        return obj",
    "docstring": "Utility method for cloning the instance as a new object.\n\n:parameter data: additional which override field data.\n:rtype: a new instance of this class."
  },
  {
    "code": "def log_uuid(self, uuid):\n        if uuid not in self.uuids and uuid in uuids:\n            self.uuids[uuid] = uuids[uuid].describe()",
    "docstring": "Logs the object with the specified `uuid` to `self.uuids` if\n        possible.\n\n        Args:\n            uuid (str): string value of :meth:`uuid.uuid4` value for the\n              object."
  },
  {
    "code": "def disable_if_done(self, commit=True):\n        if self._is_billing_complete() and not self.disabled:\n            self.disabled = True\n            if commit:\n                self.save()",
    "docstring": "Set disabled=True if we have billed all we need to\n\n        Will only have an effect on one-off costs."
  },
  {
    "code": "def _remove_action_from_type(valid_actions: Dict[str, List[str]],\n                                 type_: str,\n                                 filter_function: Callable[[str], bool]) -> None:\n        action_list = valid_actions[type_]\n        matching_action_index = [i for i, action in enumerate(action_list) if filter_function(action)]\n        assert len(matching_action_index) == 1, \"Filter function didn't find one action\"\n        action_list.pop(matching_action_index[0])",
    "docstring": "Finds the production rule matching the filter function in the given type's valid action\n        list, and removes it.  If there is more than one matching function, we crash."
  },
  {
    "code": "def ComputeRoot(hashes):\n        if not len(hashes):\n            raise Exception('Hashes must have length')\n        if len(hashes) == 1:\n            return hashes[0]\n        tree = MerkleTree(hashes)\n        return tree.Root.Hash",
    "docstring": "Compute the root hash.\n\n        Args:\n            hashes (list): the list of hashes to build the root from.\n\n        Returns:\n            bytes: the root hash."
  },
  {
    "code": "def to_dicts(recarray):\n    for rec in recarray:\n        yield dict(zip(recarray.dtype.names, rec.tolist()))",
    "docstring": "convert record array to a dictionaries"
  },
  {
    "code": "def to_dict(self):\n        return {'schema': self.schema, 'table': self.table, 'name': self.name, 'type': self.type}",
    "docstring": "Serialize representation of the column for local caching."
  },
  {
    "code": "def allow_ip(*ips: typing.Union[str, ipaddress.IPv4Network, ipaddress.IPv4Address]):\n    for ip in ips:\n        if isinstance(ip, ipaddress.IPv4Address):\n            allowed_ips.add(ip)\n        elif isinstance(ip, str):\n            allowed_ips.add(ipaddress.IPv4Address(ip))\n        elif isinstance(ip, ipaddress.IPv4Network):\n            allowed_ips.update(ip.hosts())\n        else:\n            raise ValueError(f\"Bad type of ipaddress: {type(ip)} ('{ip}')\")",
    "docstring": "Allow ip address.\n\n    :param ips:\n    :return:"
  },
  {
    "code": "def group_perms_for_user(cls, instance, user, db_session=None):\n        db_session = get_db_session(db_session, instance)\n        perms = resource_permissions_for_users(\n            cls.models_proxy,\n            ANY_PERMISSION,\n            resource_ids=[instance.resource_id],\n            user_ids=[user.id],\n            db_session=db_session,\n        )\n        perms = [p for p in perms if p.type == \"group\"]\n        groups_dict = dict([(g.id, g) for g in user.groups])\n        if instance.owner_group_id in groups_dict:\n            perms.append(\n                PermissionTuple(\n                    user,\n                    ALL_PERMISSIONS,\n                    \"group\",\n                    groups_dict.get(instance.owner_group_id),\n                    instance,\n                    True,\n                    True,\n                )\n            )\n        return perms",
    "docstring": "returns permissions that given user has for this resource\n            that are inherited from groups\n\n        :param instance:\n        :param user:\n        :param db_session:\n        :return:"
  },
  {
    "code": "def GetReportData(self, get_report_args, token=None):\n    ret = rdf_report_plugins.ApiReportData(\n        representation_type=RepresentationType.AUDIT_CHART,\n        audit_chart=rdf_report_plugins.ApiAuditChartReportData(\n            used_fields=self.USED_FIELDS))\n    ret.audit_chart.rows = _LoadAuditEvents(\n        self.HANDLERS,\n        get_report_args,\n        transformers=[_ExtractClientIdFromPath],\n        token=token)\n    return ret",
    "docstring": "Filter the cron job approvals in the given timerange."
  },
  {
    "code": "def _get_len(self):\n        if hasattr(self._buffer, 'len'):\n            self._len = self._buffer.len\n            return\n        old_pos = self._buffer.tell()\n        self._buffer.seek(0, 2)\n        self._len = self._buffer.tell()\n        self._buffer.seek(old_pos)",
    "docstring": "Return total number of bytes in buffer."
  },
  {
    "code": "def other_object_webhook_handler(event):\n\tif event.parts[:2] == [\"charge\", \"dispute\"]:\n\t\ttarget_cls = models.Dispute\n\telse:\n\t\ttarget_cls = {\n\t\t\t\"charge\": models.Charge,\n\t\t\t\"coupon\": models.Coupon,\n\t\t\t\"invoice\": models.Invoice,\n\t\t\t\"invoiceitem\": models.InvoiceItem,\n\t\t\t\"plan\": models.Plan,\n\t\t\t\"product\": models.Product,\n\t\t\t\"transfer\": models.Transfer,\n\t\t\t\"source\": models.Source,\n\t\t}.get(event.category)\n\t_handle_crud_like_event(target_cls=target_cls, event=event)",
    "docstring": "Handle updates to transfer, charge, invoice, invoiceitem, plan, product and source objects.\n\n\tDocs for:\n\t- charge: https://stripe.com/docs/api#charges\n\t- coupon: https://stripe.com/docs/api#coupons\n\t- invoice: https://stripe.com/docs/api#invoices\n\t- invoiceitem: https://stripe.com/docs/api#invoiceitems\n\t- plan: https://stripe.com/docs/api#plans\n\t- product: https://stripe.com/docs/api#products\n\t- source: https://stripe.com/docs/api#sources"
  },
  {
    "code": "def _report(self, blocknr, blocksize, size):\n        current = blocknr * blocksize\n        sys.stdout.write(\"\\r{0:.2f}%\".format(100.0 * current / size))",
    "docstring": "helper for downloading the file"
  },
  {
    "code": "def is_ligolw(origin, filepath, fileobj, *args, **kwargs):\n    if fileobj is not None:\n        loc = fileobj.tell()\n        fileobj.seek(0)\n        try:\n            line1 = fileobj.readline().lower()\n            line2 = fileobj.readline().lower()\n            try:\n                return (line1.startswith(XML_SIGNATURE) and\n                        line2.startswith((LIGOLW_SIGNATURE, LIGOLW_ELEMENT)))\n            except TypeError:\n                return (line1.startswith(XML_SIGNATURE.decode('utf-8')) and\n                        line2.startswith((LIGOLW_SIGNATURE.decode('utf-8'),\n                                          LIGOLW_ELEMENT.decode('utf-8'))))\n        finally:\n            fileobj.seek(loc)\n    try:\n        from ligo.lw.ligolw import Element\n    except ImportError:\n        return False\n    try:\n        from glue.ligolw.ligolw import Element as GlueElement\n    except ImportError:\n        element_types = (Element,)\n    else:\n        element_types = (Element, GlueElement)\n    return len(args) > 0 and isinstance(args[0], element_types)",
    "docstring": "Identify a file object as LIGO_LW-format XML"
  },
  {
    "code": "def create_package(package_format, owner, repo, **kwargs):\n    client = get_packages_api()\n    with catch_raise_api_exception():\n        upload = getattr(client, \"packages_upload_%s_with_http_info\" % package_format)\n        data, _, headers = upload(\n            owner=owner, repo=repo, data=make_create_payload(**kwargs)\n        )\n    ratelimits.maybe_rate_limit(client, headers)\n    return data.slug_perm, data.slug",
    "docstring": "Create a new package in a repository."
  },
  {
    "code": "def unicode_char(ignored_chars=None):\n        return lambda e: e.unicode if e.type == pygame.KEYDOWN \\\n            and ((ignored_chars is None) \n                  or (e.unicode not in ignored_chars))\\\n            else EventConsumerInfo.DONT_CARE",
    "docstring": "returns a handler that listens for unicode characters"
  },
  {
    "code": "def del_subkey(self,name):\n        self.sam |= KEY_WRITE\n        subkey = self.get_subkey(name)\n        subkey.clear()\n        _winreg.DeleteKey(subkey.parent.hkey,subkey.name)",
    "docstring": "Delete the named subkey, and any values or keys it contains."
  },
  {
    "code": "def join(self, target):\n        password = self.config.passwords.get(\n            target.strip(self.server_config['CHANTYPES']))\n        if password:\n            target += ' ' + password\n        self.send_line('JOIN %s' % target)",
    "docstring": "join a channel"
  },
  {
    "code": "def get_raise_brok(self, host_name, service_name=''):\n        data = self.serialize()\n        data['host'] = host_name\n        if service_name != '':\n            data['service'] = service_name\n        return Brok({'type': 'downtime_raise', 'data': data})",
    "docstring": "Get a start downtime brok\n\n        :param host_name: host concerned by the downtime\n        :type host_name\n        :param service_name: service concerned by the downtime\n        :type service_name\n        :return: brok with wanted data\n        :rtype: alignak.brok.Brok"
  },
  {
    "code": "def getclientloansurl(idclient, *args, **kwargs):\n    getparams = []\n    if kwargs:\n        try:\n            if kwargs[\"fullDetails\"] == True:\n                getparams.append(\"fullDetails=true\")\n            else:\n                getparams.append(\"fullDetails=false\")\n        except Exception as ex:\n            pass\n        try:\n            getparams.append(\"accountState=%s\" % kwargs[\"accountState\"])\n        except Exception as ex:\n            pass\n    clientidparam = \"/\" + idclient\n    url = getmambuurl(*args,**kwargs) + \"clients\" + clientidparam  + \"/loans\" + ( \"\" if len(getparams) == 0 else \"?\" + \"&\".join(getparams) )\n    return url",
    "docstring": "Request Client loans URL.\n\n    How to use it? By default MambuLoan uses getloansurl as the urlfunc.\n    Override that behaviour by sending getclientloansurl (this function)\n    as the urlfunc to the constructor of MambuLoans (note the final 's')\n    and voila! you get the Loans just for a certain client.\n\n    If idclient is set, you'll get a response adequate for a\n    MambuLoans object.\n\n    If not set, you'll get a Jar Jar Binks object, or something quite\n    strange and useless as JarJar. A MambuError must likely since I\n    haven't needed it for anything but for loans of one and just\n    one client.\n\n    See mambuloan module and pydoc for further information.\n\n    Currently implemented filter parameters:\n    * accountState\n\n    See Mambu official developer documentation for further details, and\n    info on parameters that may be implemented here in the future."
  },
  {
    "code": "def _load_api(self):\n        self._add_url_route('get_scheduler_info', '', api.get_scheduler_info, 'GET')\n        self._add_url_route('add_job', '/jobs', api.add_job, 'POST')\n        self._add_url_route('get_job', '/jobs/<job_id>', api.get_job, 'GET')\n        self._add_url_route('get_jobs', '/jobs', api.get_jobs, 'GET')\n        self._add_url_route('delete_job', '/jobs/<job_id>', api.delete_job, 'DELETE')\n        self._add_url_route('update_job', '/jobs/<job_id>', api.update_job, 'PATCH')\n        self._add_url_route('pause_job', '/jobs/<job_id>/pause', api.pause_job, 'POST')\n        self._add_url_route('resume_job', '/jobs/<job_id>/resume', api.resume_job, 'POST')\n        self._add_url_route('run_job', '/jobs/<job_id>/run', api.run_job, 'POST')",
    "docstring": "Add the routes for the scheduler API."
  },
  {
    "code": "def com_google_fonts_check_family_single_directory(fonts):\n  directories = []\n  for target_file in fonts:\n    directory = os.path.dirname(target_file)\n    if directory not in directories:\n      directories.append(directory)\n  if len(directories) == 1:\n    yield PASS, \"All files are in the same directory.\"\n  else:\n    yield FAIL, (\"Not all fonts passed in the command line\"\n                 \" are in the same directory. This may lead to\"\n                 \" bad results as the tool will interpret all\"\n                 \" font files as belonging to a single\"\n                 \" font family. The detected directories are:\"\n                 \" {}\".format(directories))",
    "docstring": "Checking all files are in the same directory.\n\n  If the set of font files passed in the command line is not all in the\n  same directory, then we warn the user since the tool will interpret\n  the set of files as belonging to a single family (and it is unlikely\n  that the user would store the files from a single family spreaded in\n  several separate directories)."
  },
  {
    "code": "def clip_lower(self, threshold):\n        with cython_context():\n            return SArray(_proxy=self.__proxy__.clip(threshold, float('nan')))",
    "docstring": "Create new SArray with all values clipped to the given lower bound. This\n        function can operate on numeric arrays, as well as vector arrays, in\n        which case each individual element in each vector is clipped. Throws an\n        exception if the SArray is empty or the types are non-numeric.\n\n        Parameters\n        ----------\n        threshold : float\n            The lower bound used to clip values.\n\n        Returns\n        -------\n        out : SArray\n\n        See Also\n        --------\n        clip, clip_upper\n\n        Examples\n        --------\n        >>> sa = turicreate.SArray([1,2,3])\n        >>> sa.clip_lower(2)\n        dtype: int\n        Rows: 3\n        [2, 2, 3]"
  },
  {
    "code": "def update_app(id, config):\n    if 'id' not in config:\n        config['id'] = id\n    config.pop('version', None)\n    config.pop('fetch', None)\n    data = salt.utils.json.dumps(config)\n    try:\n        response = salt.utils.http.query(\n            \"{0}/v2/apps/{1}?force=true\".format(_base_url(), id),\n            method='PUT',\n            decode_type='json',\n            decode=True,\n            data=data,\n            header_dict={\n                'Content-Type': 'application/json',\n                'Accept': 'application/json',\n            },\n        )\n        log.debug('update response: %s', response)\n        return response['dict']\n    except Exception as ex:\n        log.error('unable to update marathon app: %s', get_error_message(ex))\n        return {\n            'exception': {\n                'message': get_error_message(ex),\n            }\n        }",
    "docstring": "Update the specified app with the given configuration.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt marathon-minion-id marathon.update_app my-app '<config yaml>'"
  },
  {
    "code": "def database_url(self):\n        return 'postgres://{}:{}@{}/{}'.format(\n            self.user, self.password, self.name, self.database)",
    "docstring": "Returns a \"database URL\" for use with DJ-Database-URL and similar\n        libraries."
  },
  {
    "code": "def register(self, entity):\n        response = self.api.post_entity(entity.serialize)\n        print(response)\n        print()\n        if response['status']['code'] == 200:\n            entity.id = response['id']\n        if response['status']['code'] == 409:\n            entity.id = next(i.id for i in self.api.agent_entities if i.name == entity.name)\n            self.update(entity)\n        return entity",
    "docstring": "Registers a new entity and returns the entity object with an ID"
  },
  {
    "code": "def stop(self):\n        self.__end.set()\n        if self.__recv_thread:\n            self.__recv_thread.join()\n            self.__recv_thread = None\n        if self.__send_thread:\n            self.__send_thread.join()\n            self.__send_thread = None",
    "docstring": "disconnect, blocks until stopped"
  },
  {
    "code": "def getmergerequest(self, project_id, mergerequest_id):\n        request = requests.get(\n            '{0}/{1}/merge_request/{2}'.format(self.projects_url, project_id, mergerequest_id),\n            headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)\n        if request.status_code == 200:\n            return request.json()\n        else:\n            return False",
    "docstring": "Get information about a specific merge request.\n\n        :param project_id: ID of the project\n        :param mergerequest_id: ID of the merge request\n        :return: dict of the merge request"
  },
  {
    "code": "def common_cli_list_options(f):\n    @click.option(\n        \"-p\",\n        \"--page\",\n        default=1,\n        type=int,\n        help=\"The page to view for lists, where 1 is the first page\",\n        callback=validators.validate_page,\n    )\n    @click.option(\n        \"-l\",\n        \"--page-size\",\n        default=30,\n        type=int,\n        help=\"The amount of items to view per page for lists.\",\n        callback=validators.validate_page_size,\n    )\n    @click.pass_context\n    @functools.wraps(f)\n    def wrapper(ctx, *args, **kwargs):\n        opts = config.get_or_create_options(ctx)\n        kwargs[\"opts\"] = opts\n        return ctx.invoke(f, *args, **kwargs)\n    return wrapper",
    "docstring": "Add common list options to commands."
  },
  {
    "code": "def parse_sacct(sacct_stream):\n    rows = (line.split() for line in sacct_stream)\n    relevant_rows = (row for row in rows if row[0].isdigit())\n    jobs = [convert_job(row) for row in relevant_rows]\n    return jobs",
    "docstring": "Parse out information from sacct status output."
  },
  {
    "code": "def ensure_direct_subclass(class_, of):\n    if not is_direct_subclass(class_, of):\n        raise TypeError(\"expected a direct subclass of %r, got %s instead\" % (\n            of, class_.__name__))\n    return class_",
    "docstring": "Check whether given class is a direct subclass of another.\n\n    :param class_: Class to check\n    :param of: Superclass to check against\n\n    :return: ``class_``, if the check succeeds\n    :raise TypeError: When the check fails\n\n    .. versionadded:: 0.0.4"
  },
  {
    "code": "def _zoom(scale:uniform=1.0, row_pct:uniform=0.5, col_pct:uniform=0.5):\n    \"Zoom image by `scale`. `row_pct`,`col_pct` select focal point of zoom.\"\n    s = 1-1/scale\n    col_c = s * (2*col_pct - 1)\n    row_c = s * (2*row_pct - 1)\n    return _get_zoom_mat(1/scale, 1/scale, col_c, row_c)",
    "docstring": "Zoom image by `scale`. `row_pct`,`col_pct` select focal point of zoom."
  },
  {
    "code": "def has_reset(self):\n        currentTime = self._read_as_int(Addr.Uptime, 4)\n        if currentTime <= self._ticks:\n            self._ticks = currentTime\n            return True\n        self._ticks = currentTime\n        return False",
    "docstring": "Checks the grizzly to see if it reset itself because of\n        voltage sag or other reasons. Useful to reinitialize acceleration or\n        current limiting."
  },
  {
    "code": "def validate(filename, verbose=False):\n    is_remote = filename.startswith(\"http://\") or filename.startswith(\n        \"https://\")\n    with tempfile.TemporaryFile() if is_remote else open(\n            filename, \"rb\") as f:\n        if is_remote:\n            r = requests.get(filename, verify=False)\n            f.write(r.content)\n            f.seek(0)\n        r = requests.post(\n            HTML_VALIDATOR_URL,\n            files={\"file\": (filename, f, \"text/html\")},\n            data={\n                \"out\": \"json\",\n                \"showsource\": \"yes\",\n            },\n            verify=False)\n    return r.json()",
    "docstring": "Validate file and return JSON result as dictionary.\n\n    \"filename\" can be a file name or an HTTP URL.\n    Return \"\" if the validator does not return valid JSON.\n    Raise OSError if curl command returns an error status."
  },
  {
    "code": "def closest_noaa(latitude, longitude):\n    with open(env.SRC_PATH + '/inswo-stns.txt') as index:\n        index.readline()\n        index.readline()\n        min_dist = 9999\n        station_name = ''\n        station_name = ''\n        for line in index:\n            try:\n                i = parse_noaa_line(line)\n                new_dist = great_circle((latitude, longitude),\n                                        (float(i['LAT']),\n                                         float(i['LON']))).miles\n            except:\n                logger.error(line)\n                raise IOError('Inventory Issue')\n            if new_dist < min_dist:\n                min_dist = new_dist\n                station_name = i['station_name']\n                station_code = i['station_code']\n        index.close()\n        return station_code, station_name\n    raise KeyError('station not found')",
    "docstring": "Find closest station from the old list."
  },
  {
    "code": "def get_keys(self, keymap):\n        keys = dict(modifiers=[], regular=[])\n        for keymap_index, keymap_byte in enumerate(keymap):\n            try:\n                keymap_values = self._keymap_values_dict[keymap_index]\n            except KeyError:\n                continue\n            for key, value in keymap_values.items():\n                if not keymap_byte & key:\n                    continue\n                elif value in self._modifiers:\n                    keys['modifiers'].append(value)\n                elif not keys['regular']:\n                    keys['regular'].append(value)\n        return keys",
    "docstring": "Extract keys pressed from transformed keymap"
  },
  {
    "code": "def as_currency(self, currency='USD', locale=LOCALE_OBJ, *args, **kwargs):\n        f = Formatter(\n            as_currency(currency=currency, locale=locale),\n            args,\n            kwargs\n        )\n        return self._add_formatter(f)",
    "docstring": "Format subset as currency\n\n        :param currency: Currency\n        :param locale: Babel locale for currency formatting\n        :param subset: Pandas subset"
  },
  {
    "code": "def validate_context(self):\n        if self.context and len(self.context) != len(set(self.context)):\n            LOGGER.error('Cannot have duplicated context objects')\n            raise Exception('Cannot have duplicated context objects.')",
    "docstring": "Make sure there are no duplicate context objects\n        or we might end up with switched data\n\n        Converting the tuple to a set gets rid of the\n        eventual duplicate objects, comparing the length\n        of the original tuple and set tells us if we\n        have duplicates in the tuple or not"
  },
  {
    "code": "def should_add_ServerHello(self):\n        if isinstance(self.mykey, PrivKeyRSA):\n            kx = \"RSA\"\n        elif isinstance(self.mykey, PrivKeyECDSA):\n            kx = \"ECDSA\"\n        usable_suites = get_usable_ciphersuites(self.cur_pkt.ciphers, kx)\n        c = usable_suites[0]\n        if self.preferred_ciphersuite in usable_suites:\n            c = self.preferred_ciphersuite\n        self.add_msg(TLSServerHello(cipher=c))\n        raise self.ADDED_SERVERHELLO()",
    "docstring": "Selecting a cipher suite should be no trouble as we already caught\n        the None case previously.\n\n        Also, we do not manage extensions at all."
  },
  {
    "code": "def gopro_heartbeat_send(self, status, capture_mode, flags, force_mavlink1=False):\n                return self.send(self.gopro_heartbeat_encode(status, capture_mode, flags), force_mavlink1=force_mavlink1)",
    "docstring": "Heartbeat from a HeroBus attached GoPro\n\n                status                    : Status (uint8_t)\n                capture_mode              : Current capture mode (uint8_t)\n                flags                     : additional status bits (uint8_t)"
  },
  {
    "code": "def get_client_entry(self, client_entry_name):\n        request_url = self._build_url(['ClientEntry', client_entry_name])\n        return self._do_request('GET', request_url)",
    "docstring": "Returns a specific client entry name details from CPNR server."
  },
  {
    "code": "def login(self, user: str, passwd: str) -> None:\n        self.context.login(user, passwd)",
    "docstring": "Log in to instagram with given username and password and internally store session object.\n\n        :raises InvalidArgumentException: If the provided username does not exist.\n        :raises BadCredentialsException: If the provided password is wrong.\n        :raises ConnectionException: If connection to Instagram failed.\n        :raises TwoFactorAuthRequiredException: First step of 2FA login done, now call :meth:`Instaloader.two_factor_login`."
  },
  {
    "code": "def parse_k(self,k,vals):\n        try:\n            k = int(k)\n        except:\n            pass\n        else:\n            assert k in vals,\"k {0} not in vals\".format(k)\n            return [k]\n        if k is None:\n            return vals\n        else:\n            try:\n                k_vals = vals[k]\n            except Exception as e:\n                raise Exception(\"error slicing vals with {0}:{1}\".\n                                format(k,str(e)))\n            return k_vals",
    "docstring": "parse the iterable from a property or boundary condition argument\n\n        Parameters\n        ----------\n        k : int or iterable int\n            the iterable\n        vals : iterable of ints\n            the acceptable values that k may contain\n\n        Returns\n        -------\n        k_vals : iterable of int\n            parsed k values"
  },
  {
    "code": "def rename_keys(d, keymap=None, list_of_dicts=False, deepcopy=True):\n    list_of_dicts = '__list__' if list_of_dicts else None\n    keymap = {} if keymap is None else keymap\n    flatd = flatten(d, list_of_dicts=list_of_dicts)\n    flatd = {\n        tuple([keymap.get(k, k) for k in path]): v for path, v in flatd.items()\n    }\n    return unflatten(flatd, list_of_dicts=list_of_dicts, deepcopy=deepcopy)",
    "docstring": "rename keys in dict\n\n    Parameters\n    ----------\n    d : dict\n    keymap : dict\n        dictionary of key name mappings\n    list_of_dicts: bool\n        treat list of dicts as additional branches\n    deepcopy: bool\n        deepcopy values\n\n    Examples\n    --------\n\n    >>> from pprint import pprint\n    >>> d = {'a':{'old_name':1}}\n    >>> pprint(rename_keys(d,{'old_name':'new_name'}))\n    {'a': {'new_name': 1}}"
  },
  {
    "code": "def gamma(phi1,phi2,theta1,theta2):\n    if phi1 == phi2 and theta1 == theta2:\n        gamma = 0\n    else:\n        gamma = atan( sin(theta2)*sin(phi2-phi1) / \\\n                      (cos(theta1)*sin(theta2)*cos(phi1-phi2) - \\\n                       sin(theta1)*cos(theta2)) )\n    dummy_arg = (cos(gamma)*cos(theta1)*sin(theta2)*cos(phi1-phi2) + \\\n                 sin(gamma)*sin(theta2)*sin(phi2-phi1) - \\\n                 cos(gamma)*sin(theta1)*cos(theta2))\n    if dummy_arg >= 0:\n        return gamma\n    else:\n        return pi + gamma",
    "docstring": "calculate third rotation angle\n    inputs are angles from 2 pulsars\n    returns the angle."
  },
  {
    "code": "def load_csv_stream(ctx, model, data,\n                    header=None, header_exclude=None, **fmtparams):\n    _header, _rows = read_csv(data, **fmtparams)\n    header = header if header else _header\n    if _rows:\n        if header != _header and not header_exclude:\n            header_exclude = [x for x in _header if x not in header]\n        if header_exclude:\n            header = [x for x in header if x not in header_exclude]\n            pop_idxs = [_header.index(x) for x in header_exclude]\n            rows = []\n            for i, row in enumerate(_rows):\n                rows.append(\n                    [x for j, x in enumerate(row) if j not in pop_idxs]\n                )\n        else:\n            rows = list(_rows)\n        if rows:\n            load_rows(ctx, model, header, rows)",
    "docstring": "Load a CSV from a stream.\n\n    :param ctx: current anthem context\n    :param model: model name as string or model klass\n    :param data: csv data to load\n    :param header: csv fieldnames whitelist\n    :param header_exclude: csv fieldnames blacklist\n\n    Usage example::\n\n      from pkg_resources import Requirement, resource_stream\n\n      req = Requirement.parse('my-project')\n      load_csv_stream(ctx, ctx.env['res.users'],\n                      resource_stream(req, 'data/users.csv'),\n                      delimiter=',')"
  },
  {
    "code": "def port_channel_minimum_links(self, **kwargs):\n        name = str(kwargs.pop('name'))\n        minimum_links = str(kwargs.pop('minimum_links'))\n        callback = kwargs.pop('callback', self._callback)\n        min_links_args = dict(name=name, minimum_links=minimum_links)\n        if not pynos.utilities.valid_interface('port_channel', name):\n            raise ValueError(\"`name` must match `^[0-9]{1,3}${1,3}$`\")\n        config = getattr(\n            self._interface,\n            'interface_port_channel_minimum_links'\n        )(**min_links_args)\n        return callback(config)",
    "docstring": "Set minimum number of links in a port channel.\n\n        Args:\n            name (str): Port-channel number. (1, 5, etc)\n            minimum_links (str): Minimum number of links in channel group.\n            callback (function): A function executed upon completion of the\n                method.  The only parameter passed to `callback` will be the\n                ``ElementTree`` `config`.\n\n        Returns:\n            Return value of `callback`.\n\n        Raises:\n            KeyError: if `name` or `minimum_links` is not specified.\n            ValueError: if `name` is not a valid value.\n\n        Examples:\n            >>> import pynos.device\n            >>> switches = ['10.24.39.211', '10.24.39.203']\n            >>> auth = ('admin', 'password')\n            >>> for switch in switches:\n            ...     conn = (switch, '22')\n            ...     with pynos.device.Device(conn=conn, auth=auth) as dev:\n            ...         output = dev.interface.port_channel_minimum_links(\n            ...         name='1', minimum_links='2')\n            ...         dev.interface.port_channel_minimum_links()\n            ...         # doctest: +IGNORE_EXCEPTION_DETAIL\n            Traceback (most recent call last):\n            KeyError"
  },
  {
    "code": "def initialize_simulants(self):\n        super().initialize_simulants()\n        self._initial_population = self.population.get_population(True)",
    "docstring": "Initialize this simulation's population. Should not be called\n        directly."
  },
  {
    "code": "def rados_parse_df(self,\n                       result):\n        parsed_results = []\n        HEADING = r\".*(pool name) *(category) *(KB) *(objects) *(clones)\" + \\\n            \" *(degraded) *(unfound) *(rd) *(rd KB) *(wr) *(wr KB)\"\n        HEADING_RE = re.compile(HEADING,\n                                re.IGNORECASE)\n        dict_keys = [\"pool_name\", \"category\", \"size_kb\", \"objects\",\n                     \"clones\", \"degraded\", \"unfound\", \"rd\", \"rd_kb\",\n                     \"wr\", \"wr_kb\"]\n        if result['contacted'].keys():\n            for node in result['contacted'].keys():\n                df_result = {}\n                nodeobj = result['contacted'][node]\n                df_output = nodeobj['stdout']\n                for line in df_output.splitlines():\n                    print \"Line: \", line\n                    reobj = HEADING_RE.match(line)\n                    if not reobj:\n                        row = line.split()\n                        if len(row) != len(dict_keys):\n                            print \"line not match: \", line\n                            continue\n                        key_count = 0\n                        for column in row:\n                            df_result[dict_keys[key_count]] = column\n                            key_count += 1\n                        print \"df_result: \", df_result\n                        parsed_results.append(df_result)\n                    nodeobj['parsed_results'] = parsed_results\n        return result",
    "docstring": "Parse the result from ansirunner module and save it as a json\n        object"
  },
  {
    "code": "def bind(node=None, source=None, destination=None,\n             edge_title=None, edge_label=None, edge_color=None, edge_weight=None,\n             point_title=None, point_label=None, point_color=None, point_size=None):\n        from . import plotter\n        return plotter.Plotter().bind(source, destination, node, \\\n                              edge_title, edge_label, edge_color, edge_weight, \\\n                              point_title, point_label, point_color, point_size)",
    "docstring": "Create a base plotter.\n\n        Typically called at start of a program. For parameters, see ``plotter.bind()`` .\n\n        :returns: Plotter.\n        :rtype: Plotter.\n\n        **Example**\n\n                ::\n\n                    import graphistry\n                    g = graphistry.bind()"
  },
  {
    "code": "def _gen_key(self, key):\n        b_key = self._md5_digest(key)\n        return self._hashi(b_key, lambda x: x)",
    "docstring": "Return long integer for a given key, that represent it place on\n            the hash ring."
  },
  {
    "code": "def primary_measures(self):\n        from ambry.valuetype.core import ROLE\n        for c in self.columns:\n            if not c.parent and c.role == ROLE.MEASURE:\n                    yield c",
    "docstring": "Iterate over the primary columns, columns which do not have a parent\n\n        Also sets the property partition_stats to the stats collection for the partition and column."
  },
  {
    "code": "def add_linked_station(self, datfile, station, location=None):\n        if datfile not in self.fixed_stations:\n            self.fixed_stations[datfile] = {station: location}\n        else:\n            self.fixed_stations[datfile][station] = location\n        if location and not self.base_location:\n            self._utm_zone = location.zone\n            self._utm_datum = location.datum\n            self._utm_convergence = location.convergence",
    "docstring": "Add a linked or fixed station"
  },
  {
    "code": "def history_backward(self, count=1):\n        self._set_history_search()\n        found_something = False\n        for i in range(self.working_index - 1, -1, -1):\n            if self._history_matches(i):\n                self.working_index = i\n                count -= 1\n                found_something = True\n            if count == 0:\n                break\n        if found_something:\n            self.cursor_position = len(self.text)",
    "docstring": "Move backwards through history."
  },
  {
    "code": "def downcast(self, dtypes=None):\n        if dtypes is False:\n            return self\n        values = self.values\n        if self._is_single_block:\n            if dtypes is None:\n                dtypes = 'infer'\n            nv = maybe_downcast_to_dtype(values, dtypes)\n            return self.make_block(nv)\n        if dtypes is None:\n            return self\n        if not (dtypes == 'infer' or isinstance(dtypes, dict)):\n            raise ValueError(\"downcast must have a dictionary or 'infer' as \"\n                             \"its argument\")\n        def f(m, v, i):\n            if dtypes == 'infer':\n                dtype = 'infer'\n            else:\n                raise AssertionError(\"dtypes as dict is not supported yet\")\n            if dtype is not None:\n                v = maybe_downcast_to_dtype(v, dtype)\n            return v\n        return self.split_and_operate(None, f, False)",
    "docstring": "try to downcast each item to the dict of dtypes if present"
  },
  {
    "code": "def send_confirmation_email(self):\n        form = self._get_form('SECURITY_SEND_CONFIRMATION_FORM')\n        if form.validate_on_submit():\n            self.security_service.send_email_confirmation_instructions(form.user)\n            self.flash(_('flask_unchained.bundles.security:flash.confirmation_request',\n                         email=form.user.email), category='info')\n            if request.is_json:\n                return '', HTTPStatus.NO_CONTENT\n        elif form.errors and request.is_json:\n            return self.errors(form.errors)\n        return self.render('send_confirmation_email',\n                           send_confirmation_form=form,\n                           **self.security.run_ctx_processor('send_confirmation_email'))",
    "docstring": "View function which sends confirmation token and instructions to a user."
  },
  {
    "code": "def expand_file_arguments():\n    new_args = []\n    expanded = False\n    for arg in sys.argv:\n        if arg.startswith(\"@\"):\n            expanded = True\n            with open(arg[1:],\"r\") as f:\n                for line in f.readlines():\n                    new_args += shlex.split(line)\n        else:\n            new_args.append(arg)\n    if expanded:\n        print(\"esptool.py %s\" % (\" \".join(new_args[1:])))\n        sys.argv = new_args",
    "docstring": "Any argument starting with \"@\" gets replaced with all values read from a text file.\n    Text file arguments can be split by newline or by space.\n    Values are added \"as-is\", as if they were specified in this order on the command line."
  },
  {
    "code": "def create_backup(name):\n    r\n    if name in list_backups():\n        raise CommandExecutionError('Backup already present: {0}'.format(name))\n    ps_cmd = ['Backup-WebConfiguration',\n              '-Name', \"'{0}'\".format(name)]\n    cmd_ret = _srvmgr(ps_cmd)\n    if cmd_ret['retcode'] != 0:\n        msg = 'Unable to backup web configuration: {0}\\nError: {1}' \\\n              ''.format(name, cmd_ret['stderr'])\n        raise CommandExecutionError(msg)\n    return name in list_backups()",
    "docstring": "r'''\n    Backup an IIS Configuration on the System.\n\n    .. versionadded:: 2017.7.0\n\n    .. note::\n        Backups are stored in the ``$env:Windir\\System32\\inetsrv\\backup``\n        folder.\n\n    Args:\n        name (str): The name to give the backup\n\n    Returns:\n        bool: True if successful, otherwise False\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' win_iis.create_backup good_config_20170209"
  },
  {
    "code": "def _write_bed_header(self):\n        final_byte = 1 if self._bed_format == \"SNP-major\" else 0\n        self._bed.write(bytearray((108, 27, final_byte)))",
    "docstring": "Writes the BED first 3 bytes."
  },
  {
    "code": "def range_piles(ranges):\n    endpoints = _make_endpoints(ranges)\n    for seqid, ends in groupby(endpoints, lambda x: x[0]):\n        active = []\n        depth = 0\n        for seqid, pos, leftright, i, score in ends:\n            if leftright == LEFT:\n                active.append(i)\n                depth += 1\n            else:\n                depth -= 1\n            if depth == 0 and active:\n                yield active\n                active = []",
    "docstring": "Return piles of intervals that overlap. The piles are only interrupted by\n    regions of zero coverage.\n\n    >>> ranges = [Range(\"2\", 0, 1, 3, 0), Range(\"2\", 1, 4, 3, 1), Range(\"3\", 5, 7, 3, 2)]\n    >>> list(range_piles(ranges))\n    [[0, 1], [2]]"
  },
  {
    "code": "def predict(self, X):\n        return self.__cost(self.__unroll(self.__thetas), 0, np.matrix(X))",
    "docstring": "Returns predictions of input test cases."
  },
  {
    "code": "def to_json(self, *, indent=None, sort_keys = False):\n        return json.dumps({k: v for k, v in dict(self).items() if v is not None}, indent=indent, sort_keys=sort_keys,\n                          default=self._try_dict)",
    "docstring": "Gets the object's JSON representation.\n\n        Parameters\n        ----------\n        indent: :class:`int`, optional\n            Number of spaces used as indentation, ``None`` will return the shortest possible string.\n        sort_keys: :class:`bool`, optional\n            Whether keys should be sorted alphabetically or preserve the order defined by the object.\n\n        Returns\n        -------\n        :class:`str`\n            JSON representation of the object."
  },
  {
    "code": "def data(self, index, role):\r\n        if not index.isValid() or \\\r\n           index.row() >= self._shape[0] or \\\r\n           index.column() >= self._shape[1]:\r\n            return None\r\n        row, col = ((index.row(), index.column()) if self.axis == 0\r\n                    else (index.column(), index.row()))\r\n        if role != Qt.DisplayRole:\r\n            return None\r\n        if self.axis == 0 and self._shape[0] <= 1:\r\n            return None\r\n        header = self.model.header(self.axis, col, row)\r\n        if not is_type_text_string(header):\r\n            header = to_text_string(header)\r\n        return header",
    "docstring": "Get the data for the header.\r\n\r\n        This is used when a header has levels."
  },
  {
    "code": "def reset_server_and_request_check(self, address):\n        with self._lock:\n            self._reset_server(address)\n            self._request_check(address)",
    "docstring": "Clear our pool for a server, mark it Unknown, and check it soon."
  },
  {
    "code": "def superuser_api_key_required(f):\n    @functools.wraps(f)\n    def wrapped(*args, **kwargs):\n        api_key = current_api_key()\n        g.api_key = api_key\n        utils.jsonify_assert(\n            api_key.superuser,\n            'API key=%r must be a super user' % api_key.id,\n            403)\n        return f(*args, **kwargs)\n    return wrapped",
    "docstring": "Decorator ensures only superuser API keys can request this function."
  },
  {
    "code": "def flow_pipemajor(Diam, HeadLossFric, Length, Nu, PipeRough):\n    FlowHagen = flow_hagen(Diam, HeadLossFric, Length, Nu).magnitude\n    if FlowHagen < flow_transition(Diam, Nu).magnitude:\n        return FlowHagen\n    else:\n        return flow_swamee(Diam, HeadLossFric, Length, Nu, PipeRough).magnitude",
    "docstring": "Return the flow rate with only major losses.\n\n    This function applies to both laminar and turbulent flows."
  },
  {
    "code": "async def create_turn_endpoint(protocol_factory, server_addr, username, password,\n                               lifetime=600, ssl=False, transport='udp'):\n    loop = asyncio.get_event_loop()\n    if transport == 'tcp':\n        _, inner_protocol = await loop.create_connection(\n            lambda: TurnClientTcpProtocol(server_addr,\n                                          username=username,\n                                          password=password,\n                                          lifetime=lifetime),\n            host=server_addr[0],\n            port=server_addr[1],\n            ssl=ssl)\n    else:\n        _, inner_protocol = await loop.create_datagram_endpoint(\n            lambda: TurnClientUdpProtocol(server_addr,\n                                          username=username,\n                                          password=password,\n                                          lifetime=lifetime),\n            remote_addr=server_addr)\n    protocol = protocol_factory()\n    transport = TurnTransport(protocol, inner_protocol)\n    await transport._connect()\n    return transport, protocol",
    "docstring": "Create datagram connection relayed over TURN."
  },
  {
    "code": "def get_snmp_information(self):\n        snmp_information = {}\n        snmp_config = junos_views.junos_snmp_config_table(self.device)\n        snmp_config.get()\n        snmp_items = snmp_config.items()\n        if not snmp_items:\n            return snmp_information\n        snmp_information = {\n            py23_compat.text_type(ele[0]): ele[1] if ele[1] else \"\"\n            for ele in snmp_items[0][1]\n        }\n        snmp_information[\"community\"] = {}\n        communities_table = snmp_information.pop(\"communities_table\")\n        if not communities_table:\n            return snmp_information\n        for community in communities_table.items():\n            community_name = py23_compat.text_type(community[0])\n            community_details = {\"acl\": \"\"}\n            community_details.update(\n                {\n                    py23_compat.text_type(ele[0]): py23_compat.text_type(\n                        ele[1]\n                        if ele[0] != \"mode\"\n                        else C.SNMP_AUTHORIZATION_MODE_MAP.get(ele[1])\n                    )\n                    for ele in community[1]\n                }\n            )\n            snmp_information[\"community\"][community_name] = community_details\n        return snmp_information",
    "docstring": "Return the SNMP configuration."
  },
  {
    "code": "def classify_format(f):\n    l0, l1 = _get_two_lines(f)\n    if loader.glove.check_valid(l0, l1):\n        return _glove\n    elif loader.word2vec_text.check_valid(l0, l1):\n        return _word2vec_text\n    elif loader.word2vec_bin.check_valid(l0, l1):\n        return _word2vec_bin\n    else:\n        raise OSError(b\"Invalid format\")",
    "docstring": "Determine the format of word embedding file by their content. This operation\n    only looks at the first two lines and does not check the sanity of input\n    file.\n\n    Args:\n        f (Filelike):\n\n    Returns:\n        class"
  },
  {
    "code": "def get_data(self, request=None):\n        if request is None:\n            raise ValueError\n        data = [[] for _ in self.sources]\n        for i in range(request):\n            try:\n                for source_data, example in zip(\n                        data, next(self.child_epoch_iterator)):\n                    source_data.append(example)\n            except StopIteration:\n                if not self.strictness and data[0]:\n                    break\n                elif self.strictness > 1 and data[0]:\n                    raise ValueError\n                raise\n        return tuple(numpy.asarray(source_data) for source_data in data)",
    "docstring": "Get data from the dataset."
  },
  {
    "code": "def safe_urlencode(params, doseq=0):\n    if IS_PY3:\n        return urlencode(params, doseq)\n    if hasattr(params, \"items\"):\n        params = params.items()\n    new_params = []\n    for k, v in params:\n        k = k.encode(\"utf-8\")\n        if isinstance(v, (list, tuple)):\n            new_params.append((k, [force_bytes(i) for i in v]))\n        else:\n            new_params.append((k, force_bytes(v)))\n    return urlencode(new_params, doseq)",
    "docstring": "UTF-8-safe version of safe_urlencode\n\n    The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values\n    which can't fail down to ascii."
  },
  {
    "code": "def copy(self):\n        return _TimeAnchor(self.reading_id, self.uptime, self.utc, self.is_break, self.exact)",
    "docstring": "Return a copy of this _TimeAnchor."
  },
  {
    "code": "def load_texture(self, file_path):\n        self.image = pygame.image.load(file_path)\n        self.apply_texture(self.image)",
    "docstring": "Generate our sprite's surface by loading the specified image from disk.\n         Note that this automatically centers the origin."
  },
  {
    "code": "def register_updates(self, callback):\n        _LOGGER.debug(\"Registered callback for state: %s\", self._stateName)\n        self._observer_callbacks.append(callback)",
    "docstring": "Register a callback to notify a listener of state changes."
  },
  {
    "code": "def post_migrate(cls, sender=None, **kwargs):\n        ContentType = apps.get_model('contenttypes', 'ContentType')\n        for model_name, proxy_model in sender.get_proxy_models().items():\n            ctype, created = ContentType.objects.get_or_create(app_label=sender.label, model=model_name)\n            if created:\n                sender.grant_permissions(proxy_model)",
    "docstring": "Iterate over fake_proxy_models and add contenttypes and permissions for missing proxy\n        models, if this has not been done by Django yet"
  },
  {
    "code": "def bind_field(\n        self,\n        form: DynamicForm,\n        unbound_field: UnboundField,\n        options: Dict[Any, Any],\n    ) -> Field:\n    filters = unbound_field.kwargs.get('filters', [])\n    filters.append(lambda x: x.strip() if isinstance(x, str) else x)\n    return unbound_field.bind(form=form, filters=filters, **options)",
    "docstring": "Customize how fields are bound by stripping all whitespace.\n\n    :param form: The form\n    :param unbound_field: The unbound field\n    :param options: The field options\n    :returns: The bound field"
  },
  {
    "code": "def validate_default_element(self, value):\n        if isinstance(value, (six.string_types, six.integer_types)):\n            if self.__type:\n                self.__type(value)\n            return value\n        return super(EnumField, self).validate_default_element(value)",
    "docstring": "Validate default element of Enum field.\n\n        Enum fields allow for delayed resolution of default values\n        when the type of the field has not been resolved. The default\n        value of a field may be a string or an integer. If the Enum\n        type of the field has been resolved, the default value is\n        validated against that type.\n\n        Args:\n          value: Value to validate.\n\n        Raises:\n          ValidationError if value is not expected message type."
  },
  {
    "code": "def get_example_features(example):\n  return (example.features.feature if isinstance(example, tf.train.Example)\n          else example.context.feature)",
    "docstring": "Returns the non-sequence features from the provided example."
  },
  {
    "code": "def clean_highlight(self):\n        if not self.valid:\n            return\n        for hit in self._results['hits']['hits']:\n            if 'highlight' in hit:\n                hl = hit['highlight']\n                for key, item in list(hl.items()):\n                    if not item:\n                        del hl[key]",
    "docstring": "Remove the empty highlight"
  },
  {
    "code": "def machines(self):\n        if self._resources is None:\n            self.__init()\n        if \"machines\" in self._resources:\n            url = self._url + \"/machines\"\n            return _machines.Machines(url,\n                                      securityHandler=self._securityHandler,\n                                      initialize=False,\n                                      proxy_url=self._proxy_url,\n                                      proxy_port=self._proxy_port)\n        else:\n            return None",
    "docstring": "gets a reference to the machines object"
  },
  {
    "code": "def evaluate_extracted_tokens(gold_content, extr_content):\n    if isinstance(gold_content, string_):\n        gold_content = simple_tokenizer(gold_content)\n    if isinstance(extr_content, string_):\n        extr_content = simple_tokenizer(extr_content)\n    gold_set = set(gold_content)\n    extr_set = set(extr_content)\n    jaccard = len(gold_set & extr_set) / len(gold_set | extr_set)\n    levenshtein = dameraulevenshtein(gold_content, extr_content)\n    return {'jaccard': jaccard, 'levenshtein': levenshtein}",
    "docstring": "Evaluate the similarity between gold-standard and extracted content,\n    typically for a single HTML document, as another way of evaluating the\n    performance of an extractor model.\n\n    Args:\n        gold_content (str or Sequence[str]): Gold-standard content, either as a\n            string or as an already-tokenized list of tokens.\n        extr_content (str or Sequence[str]): Extracted content, either as a\n            string or as an already-tokenized list of tokens.\n\n    Returns:\n        Dict[str, float]"
  },
  {
    "code": "def _start_console(self):\n        self._remote_pipe = yield from asyncio_open_serial(self._get_pipe_name())\n        server = AsyncioTelnetServer(reader=self._remote_pipe,\n                                     writer=self._remote_pipe,\n                                     binary=True,\n                                     echo=True)\n        self._telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console)",
    "docstring": "Starts remote console support for this VM."
  },
  {
    "code": "def find_npolfile(flist,detector,filters):\n    npolfile = None\n    for f in flist:\n        fdet = fits.getval(f, 'detector', memmap=False)\n        if fdet == detector:\n            filt1 = fits.getval(f, 'filter1', memmap=False)\n            filt2 = fits.getval(f, 'filter2', memmap=False)\n            fdate = fits.getval(f, 'date', memmap=False)\n            if filt1 == 'ANY' or \\\n             (filt1 == filters[0] and filt2 == filters[1]):\n                npolfile = f\n    return npolfile",
    "docstring": "Search a list of files for one that matches the configuration\n        of detector and filters used."
  },
  {
    "code": "def neurite_volume_density(neurites, neurite_type=NeuriteType.all):\n    def vol_density(neurite):\n        return neurite.volume / convex_hull(neurite).volume\n    return list(vol_density(n)\n                for n in iter_neurites(neurites, filt=is_type(neurite_type)))",
    "docstring": "Get the volume density per neurite\n\n    The volume density is defined as the ratio of the neurite volume and\n    the volume of the neurite's enclosing convex hull"
  },
  {
    "code": "def parse_items(self, field: Field) -> Mapping[str, Any]:\n        return self.build_parameter(field.container)",
    "docstring": "Parse the child item type for list fields, if any."
  },
  {
    "code": "def wait_for_next_completion(self, runtime_context):\n        if runtime_context.workflow_eval_lock is not None:\n            runtime_context.workflow_eval_lock.wait()\n        if self.exceptions:\n            raise self.exceptions[0]",
    "docstring": "Wait for jobs to finish."
  },
  {
    "code": "def make_db_data_fetcher(postgresql_conn_info, template_path, reload_templates,\n                         query_cfg, io_pool):\n    sources = parse_source_data(query_cfg)\n    queries_generator = make_queries_generator(\n        sources, template_path, reload_templates)\n    return DataFetcher(\n        postgresql_conn_info, queries_generator, io_pool)",
    "docstring": "Returns an object which is callable with the zoom and unpadded bounds and\n    which returns a list of rows."
  },
  {
    "code": "def convert_content(self, fpath: str) -> typing.Optional[dict]:\n        try:\n            loader = self.loader_cls(fpath)\n        except UnsupportedExtensionError:\n            return\n        return loader.convert_content()",
    "docstring": "Convert content of source file with loader, provided with\n        `loader_cls` self attribute.\n\n        Returns dict with converted content if loader class support source file\n        extenstions, otherwise return nothing."
  },
  {
    "code": "def as_json(self):\n        self._config['applyCss'] = self.applyCss\n        self._json['config'] = self._config\n        return self._json",
    "docstring": "Represent effect as JSON dict."
  },
  {
    "code": "def to_bayesian_model(self):\n        from pgmpy.models import BayesianModel\n        bm = BayesianModel()\n        var_clique_dict = defaultdict(tuple)\n        var_order = []\n        junction_tree = self.to_junction_tree()\n        root_node = next(iter(junction_tree.nodes()))\n        bfs_edges = nx.bfs_edges(junction_tree, root_node)\n        for node in root_node:\n            var_clique_dict[node] = root_node\n            var_order.append(node)\n        for edge in bfs_edges:\n            clique_node = edge[1]\n            for node in clique_node:\n                if not var_clique_dict[node]:\n                    var_clique_dict[node] = clique_node\n                    var_order.append(node)\n        for node_index in range(len(var_order)):\n            node = var_order[node_index]\n            node_parents = (set(var_clique_dict[node]) - set([node])).intersection(\n                set(var_order[:node_index]))\n            bm.add_edges_from([(parent, node) for parent in node_parents])\n        return bm",
    "docstring": "Creates a Bayesian Model which is a minimum I-Map for this markov model.\n\n        The ordering of parents may not remain constant. It would depend on the\n        ordering of variable in the junction tree (which is not constant) all the\n        time.\n\n        Examples\n        --------\n        >>> from pgmpy.models import MarkovModel\n        >>> from pgmpy.factors.discrete import DiscreteFactor\n        >>> mm = MarkovModel()\n        >>> mm.add_nodes_from(['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7'])\n        >>> mm.add_edges_from([('x1', 'x3'), ('x1', 'x4'), ('x2', 'x4'),\n        ...                    ('x2', 'x5'), ('x3', 'x6'), ('x4', 'x6'),\n        ...                    ('x4', 'x7'), ('x5', 'x7')])\n        >>> phi = [DiscreteFactor(edge, [2, 2], np.random.rand(4)) for edge in mm.edges()]\n        >>> mm.add_factors(*phi)\n        >>> bm = mm.to_bayesian_model()"
  },
  {
    "code": "def _get_states_from_samecodes(self, geocodes):\n        states = []\n        for code in geocodes:\n            if not isinstance(geocodes, list):\n                raise Exception(\"specified geocodes must be list\")\n            try:\n                state = self.samecodes[code]['state']\n            except KeyError:\n                raise Exception(\"Samecode Not Found\")\n            else:\n                if state not in states:\n                    states.append(state)\n        return states",
    "docstring": "Returns all states for a given list of SAME codes\n\n        *Shouldn't be used to determine feed scope, please use getfeedscope()*"
  },
  {
    "code": "def gmeta_pop(gmeta, info=False):\n    if type(gmeta) is GlobusHTTPResponse:\n        gmeta = json.loads(gmeta.text)\n    elif type(gmeta) is str:\n        gmeta = json.loads(gmeta)\n    elif type(gmeta) is not dict:\n        raise TypeError(\"gmeta must be dict, GlobusHTTPResponse, or JSON string\")\n    results = []\n    for res in gmeta[\"gmeta\"]:\n        for con in res[\"content\"]:\n            results.append(con)\n    if info:\n        fyi = {\n            \"total_query_matches\": gmeta.get(\"total\")\n            }\n        return results, fyi\n    else:\n        return results",
    "docstring": "Remove GMeta wrapping from a Globus Search result.\n    This function can be called on the raw GlobusHTTPResponse that Search returns,\n    or a string or dictionary representation of it.\n\n    Arguments:\n        gmeta (dict, str, or GlobusHTTPResponse): The Globus Search result to unwrap.\n        info (bool): If ``False``, will return a list of the results\n                and discard the metadata. If ``True``, will return a tuple containing\n                the results list, and other information about the query.\n                **Default**: ``False``.\n\n    Returns:\n        list (if ``info=False``): The unwrapped results.\n        tuple (if ``info=True``): The unwrapped results, and a dictionary of query information."
  },
  {
    "code": "def packtar(tarfile, files, srcdir):\n    nullfd = open(os.devnull, \"w\")\n    tarfile = cygpath(os.path.abspath(tarfile))\n    log.debug(\"pack tar %s from folder  %s with files \", tarfile, srcdir)\n    log.debug(files)\n    try:\n        check_call([TAR, '-czf', tarfile] + files, cwd=srcdir,\n                   stdout=nullfd, preexec_fn=_noumask)\n    except Exception:\n        log.exception(\"Error packing tar file %s to %s\", tarfile, srcdir)\n        raise\n    nullfd.close()",
    "docstring": "Pack the given files into a tar, setting cwd = srcdir"
  },
  {
    "code": "def build(self, root=\"runs\"):\n        for d, control in self.iter(root):\n            _mkdirs(d)\n            with open(os.path.join(d, self.control_name), 'w') as fp:\n                json.dump(control, fp, indent=self.indent)\n                fp.write('\\n')",
    "docstring": "Build a nested directory structure, starting in ``root``\n\n        :param root: Root directory for structure"
  },
  {
    "code": "def waypoint_current(self):\n        if self.mavlink10():\n            m = self.recv_match(type='MISSION_CURRENT', blocking=True)\n        else:\n            m = self.recv_match(type='WAYPOINT_CURRENT', blocking=True)\n        return m.seq",
    "docstring": "return current waypoint"
  },
  {
    "code": "def as_square_array(arr):\n    arr = np.atleast_2d(arr)\n    if len(arr.shape) != 2 or arr.shape[0] != arr.shape[1]:\n        raise ValueError(\"Expected square array\")\n    return arr",
    "docstring": "Return arr massaged into a square array. Raises ValueError if arr cannot be\n    so massaged."
  },
  {
    "code": "def new_genre(self, program, genre, relevance):\n        if self.__v_genre:\n            print(\"[Genre: %s, %s, %s]\" % (program, genre, relevance))",
    "docstring": "Callback run for each new program genre entry"
  },
  {
    "code": "def clone(name, repository, destination, debug=False):\n    msg = '  - cloning {} to {}'.format(name, destination)\n    util.print_info(msg)\n    cmd = sh.git.bake('clone', repository, destination)\n    util.run_command(cmd, debug=debug)",
    "docstring": "Clone the specified repository into a temporary directory and return None.\n\n    :param name: A string containing the name of the repository being cloned.\n    :param repository: A string containing the repository to clone.\n    :param destination: A string containing the directory to clone the\n     repository into.\n    :param debug: An optional bool to toggle debug output.\n    :return: None"
  },
  {
    "code": "def update_floatingip_statuses(self, context, router_id, fip_statuses):\n        cctxt = self.client.prepare(version='1.1')\n        return cctxt.call(context, 'update_floatingip_statuses_cfg',\n                          router_id=router_id, fip_statuses=fip_statuses)",
    "docstring": "Make a remote process call to update operational status for one or\n        several floating IPs.\n\n        @param context: contains user information\n        @param router_id: id of router associated with the floatingips\n        @param fip_statuses: dict with floatingip_id as key and status as value"
  },
  {
    "code": "def transform_sequence(f):\n    @wraps(f)\n    def wrapper(*args, **kwargs):\n        return lambda seq: seq.map_points(partial(f, *args, **kwargs))\n    return wrapper",
    "docstring": "A decorator to take a function operating on a point and\n    turn it into a function returning a callable operating on a sequence.\n    The functions passed to this decorator must define a kwarg called \"point\",\n    or have point be the last positional argument"
  },
  {
    "code": "def _adapt_response(self, response):\n        errors, meta = super(ServerError, self)._adapt_response(response)\n        return errors[0], meta",
    "docstring": "Convert various error responses to standardized ErrorDetails."
  },
  {
    "code": "def plot_discrete(self, show=False, annotations=True):\n        import matplotlib.pyplot as plt\n        axis = plt.axes()\n        axis.set_aspect('equal', 'datalim')\n        for i, points in enumerate(self.discrete):\n            color = ['g', 'k'][i in self.root]\n            axis.plot(*points.T, color=color)\n        if annotations:\n            for e in self.entities:\n                if not hasattr(e, 'plot'):\n                    continue\n                e.plot(self.vertices)\n        if show:\n            plt.show()\n        return axis",
    "docstring": "Plot the closed curves of the path."
  },
  {
    "code": "def default_tool_argparser(description, example_parameters):\n    import argparse\n    epilog = '\\n'\n    for k, v in sorted(example_parameters.items()):\n        epilog += '  ' + k + '\\n'\n    p = argparse.ArgumentParser(\n        description=description,\n        add_help=False,\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=('available values for examples (exkey):'+epilog))\n    return p",
    "docstring": "Create default parser for single tools."
  },
  {
    "code": "def fap_simple(Z, fmax, t, y, dy, normalization='standard'):\n    N = len(t)\n    T = max(t) - min(t)\n    N_eff = fmax * T\n    p_s = cdf_single(Z, N, normalization=normalization)\n    return 1 - p_s ** N_eff",
    "docstring": "False Alarm Probability based on estimated number of indep frequencies"
  },
  {
    "code": "def backlink(node):\n    seen = set()\n    to_see = [node]\n    while to_see:\n      node = to_see.pop()\n      seen.add(node)\n      for succ in node.next:\n        succ.prev.add(node)\n        if succ not in seen:\n          to_see.append(succ)",
    "docstring": "Given a CFG with outgoing links, create incoming links."
  },
  {
    "code": "def in_period(period, dt=None):\n    if dt is None:\n        dt = datetime.now()\n    period = re.sub(r\"^\\s*|\\s*$\", '', period)\n    period = re.sub(r\"\\s*(?={|$)\", '', period)\n    period = re.sub(r\",\\s*\", ',', period)\n    period = re.sub(r\"\\s*-\\s*\", '-', period)\n    period = re.sub(r\"{\\s*\", '{', period)\n    period = re.sub(r\"\\s*}\\s*\", '}', period)\n    period = re.sub(r\"}(?=[^,])\", '}|', period)\n    period = period.lower()\n    if period == '':\n        return True\n    sub_periods = re.split(',', period)\n    for sp in sub_periods:\n        if _is_in_sub_period(sp, dt):\n            return True\n    return False",
    "docstring": "Determines if a datetime is within a certain time period. If the time\n    is omitted the current time will be used.\n\n    in_period return True is the datetime is within the time period, False if not.\n    If the expression is malformed a TimePeriod.InvalidFormat exception\n    will be raised. (Note that this differs from Time::Period, which\n    returns -1 if the expression is invalid).\n\n    The format for the time period is like Perl's Time::Period module,\n    which is documented in some detail here:\n\n    http://search.cpan.org/~pryan/Period-1.20/Period.pm\n\n    Here's the quick and dirty version.\n\n    Each period is composed of one or more sub-period seperated by a comma.\n    A datetime must match at least one of the sub periods to be considered\n    in that time period.\n\n    Each sub-period is composed of one or more tests, like so:\n\n        scale {value}\n\n        scale {a-b}\n\n        scale {a b c}\n\n    The datetime must pass each test for a sub-period for the sub-period to\n    be considered true.\n\n    For example:\n\n        Match Mondays\n        wd {mon}\n\n        Match Monday mornings\n        wd {mon} hr {9-16}\n\n        Match Monday morning or Friday afternoon\n        wd {mon} hr {0-12}, wd {fri} hr {0-12}\n\n    Valid scales are:\n        year\n        month\n        week\n        yday\n        mday\n        wday\n        hour\n        minute\n        second\n\n    Those can be substituted with their corresponding code:\n        yd\n        mo\n        wk\n        yd\n        md\n        wd\n        hr\n        min\n        sec"
  },
  {
    "code": "def sent2examples(self, sent):\n    words = [w if w in self.embeddings else TaggerBase.UNK for w in sent]\n    ngrams = TaggerBase.ngrams(words, self.context, self.transfer)\n    fvs = []\n    for word, ngram in zip(sent, ngrams):\n      fv = np.array([self.embeddings.get(w, self.embeddings.zero_vector()) for w in ngram]).flatten()\n      if self.add_bias:\n        fv = np.hstack((fv, np.array(1)))\n      yield word, fv",
    "docstring": "Convert ngrams into feature vectors."
  },
  {
    "code": "def set_field(self, state, field_name, field_type, value):\n        field_ref = SimSootValue_InstanceFieldRef.get_ref(state=state,\n                                                          obj_alloc_id=self.heap_alloc_id,\n                                                          field_class_name=self.type,\n                                                          field_name=field_name,\n                                                          field_type=field_type)\n        state.memory.store(field_ref, value)",
    "docstring": "Sets an instance field."
  },
  {
    "code": "def create_db(with_postgis=False):\n    local_machine()\n    local('psql {0} -c \"CREATE USER {1} WITH PASSWORD \\'{2}\\'\"'.format(\n        USER_AND_HOST, env.db_role, DB_PASSWORD))\n    local('psql {0} -c \"CREATE DATABASE {1} ENCODING \\'UTF8\\'\"'.format(\n        USER_AND_HOST, env.db_name))\n    if with_postgis:\n        local('psql {0} {1} -c \"CREATE EXTENSION postgis\"'.format(\n            USER_AND_HOST, env.db_name))\n    local('psql {0} -c \"GRANT ALL PRIVILEGES ON DATABASE {1}'\n          ' to {2}\"'.format(USER_AND_HOST, env.db_name, env.db_role))\n    local('psql {0} -c \"GRANT ALL PRIVILEGES ON ALL TABLES'\n          ' IN SCHEMA public TO {1}\"'.format(\n              USER_AND_HOST, env.db_role))",
    "docstring": "Creates the local database.\n\n    :param with_postgis: If ``True``, the postgis extension will be installed."
  },
  {
    "code": "def create_smooth_contour(\n        shakemap_layer,\n        output_file_path='',\n        active_band=1,\n        smoothing_method=NUMPY_SMOOTHING,\n        smoothing_sigma=0.9):\n    timestamp = datetime.now()\n    temp_smoothed_shakemap_path = unique_filename(\n        prefix='temp-shake-map' + timestamp.strftime('%Y%m%d-%H%M%S'),\n        suffix='.tif',\n        dir=temp_dir('temp'))\n    temp_smoothed_shakemap_path = smooth_shakemap(\n        shakemap_layer.source(),\n        output_file_path=temp_smoothed_shakemap_path,\n        active_band=active_band,\n        smoothing_method=smoothing_method,\n        smoothing_sigma=smoothing_sigma\n    )\n    return shakemap_contour(\n        temp_smoothed_shakemap_path,\n        output_file_path=output_file_path,\n        active_band=active_band\n    )",
    "docstring": "Create contour from a shake map layer by using smoothing method.\n\n    :param shakemap_layer: The shake map raster layer.\n    :type shakemap_layer: QgsRasterLayer\n\n    :param active_band: The band which the data located, default to 1.\n    :type active_band: int\n\n    :param smoothing_method: The smoothing method that wanted to be used.\n    :type smoothing_method: NONE_SMOOTHING, NUMPY_SMOOTHING, SCIPY_SMOOTHING\n\n    :param smooth_sigma: parameter for gaussian filter used in smoothing\n        function.\n    :type smooth_sigma: float\n\n    :returns: The contour of the shake map layer path.\n    :rtype: basestring"
  },
  {
    "code": "def break_type_id(self, break_type_id):\n        if break_type_id is None:\n            raise ValueError(\"Invalid value for `break_type_id`, must not be `None`\")\n        if len(break_type_id) < 1:\n            raise ValueError(\"Invalid value for `break_type_id`, length must be greater than or equal to `1`\")\n        self._break_type_id = break_type_id",
    "docstring": "Sets the break_type_id of this ModelBreak.\n        The `BreakType` this `Break` was templated on.\n\n        :param break_type_id: The break_type_id of this ModelBreak.\n        :type: str"
  },
  {
    "code": "def between(start, delta, end=None):\n    toyield = start\n    while end is None or toyield < end:\n      yield toyield\n      toyield += delta",
    "docstring": "Return an iterator between this date till given end point.\n\n    Example usage:\n      >>> d = datetime_tz.smartparse(\"5 days ago\")\n      2008/05/12 11:45\n      >>> for i in d.between(timedelta(days=1), datetime_tz.now()):\n      >>>    print i\n      2008/05/12 11:45\n      2008/05/13 11:45\n      2008/05/14 11:45\n      2008/05/15 11:45\n      2008/05/16 11:45\n\n    Args:\n      start: The date to start at.\n      delta: The interval to iterate with.\n      end: (Optional) Date to end at. If not given the iterator will never\n           terminate.\n\n    Yields:\n      datetime_tz objects."
  },
  {
    "code": "def _active_case(self, value: ObjectValue) -> Optional[\"CaseNode\"]:\n        for c in self.children:\n            for cc in c.data_children():\n                if cc.iname() in value:\n                    return c",
    "docstring": "Return receiver's case that's active in an instance node value."
  },
  {
    "code": "def get_status(self, status_value, message=None):\n        status = etree.Element('Status')\n        status_code = etree.SubElement(status, 'StatusCode')\n        status_code.set('Value', 'samlp:' + status_value)\n        if message:\n            status_message = etree.SubElement(status, 'StatusMessage')\n            status_message.text = message\n        return status",
    "docstring": "Build a Status XML block for a SAML 1.1 Response."
  },
  {
    "code": "def get_klass_children(gi_name):\n    res = {}\n    children = __HIERARCHY_GRAPH.successors(gi_name)\n    for gi_name in children:\n        ctype_name = ALL_GI_TYPES[gi_name]\n        qs = QualifiedSymbol(type_tokens=[Link(None, ctype_name, ctype_name)])\n        qs.add_extension_attribute ('gi-extension', 'type_desc',\n                SymbolTypeDesc([], gi_name, ctype_name, 0))\n        res[ctype_name] = qs\n    return res",
    "docstring": "Returns a dict of qualified symbols representing\n    the children of the klass-like symbol named gi_name"
  },
  {
    "code": "def random_population(dna_size, pop_size, tune_params):\n    population = []\n    for _ in range(pop_size):\n        dna = []\n        for i in range(dna_size):\n            dna.append(random_val(i, tune_params))\n        population.append(dna)\n    return population",
    "docstring": "create a random population"
  },
  {
    "code": "def stop(self):\n        if self._stack:\n            try:\n                self._stack.teardown()\n            except Exception:\n                self.fatal(sys.exc_info())\n        super().stop()",
    "docstring": "Cleanup the context, after the loop ended."
  },
  {
    "code": "def cmd_gimbal_roi(self, args):\n        latlon = None\n        try:\n            latlon = self.module('map').click_position\n        except Exception:\n            print(\"No map available\")\n            return\n        if latlon is None:\n            print(\"No map click position available\")\n            return\n        self.master.mav.mount_control_send(self.target_system,\n                                           self.target_component,\n                                           latlon[0]*1e7,\n                                           latlon[1]*1e7,\n                                           0,\n                                           0)",
    "docstring": "control roi position"
  },
  {
    "code": "def _wrap_parse(code, filename):\n        code = 'async def wrapper():\\n' + indent(code, ' ')\n        return ast.parse(code, filename=filename).body[0].body[0].value",
    "docstring": "async wrapper is required to avoid await calls raising a SyntaxError"
  },
  {
    "code": "def timid_relpath(arg):\n    from os.path import isabs, relpath, sep\n    if isabs(arg):\n        result = relpath(arg)\n        if result.count(sep) + 1 < arg.count(sep):\n            return result\n    return arg",
    "docstring": "convert an argument to a relative path, carefully"
  },
  {
    "code": "def _configure_device(commands, **kwargs):\n    if salt.utils.platform.is_proxy():\n        return __proxy__['nxos.proxy_config'](commands, **kwargs)\n    else:\n        return _nxapi_config(commands, **kwargs)",
    "docstring": "Helper function to send configuration commands to the device over a\n    proxy minion or native minion using NX-API or SSH."
  },
  {
    "code": "def _browse_body(self, search_id):\n        xml = self._base_body()\n        XML.SubElement(xml, 's:Body')\n        item_attrib = {\n            'xmlns': 'http://www.sonos.com/Services/1.1'\n        }\n        search = XML.SubElement(xml[1], 'getMetadata', item_attrib)\n        XML.SubElement(search, 'id').text = search_id\n        XML.SubElement(search, 'index').text = '0'\n        XML.SubElement(search, 'count').text = '100'\n        return XML.tostring(xml)",
    "docstring": "Return the browse XML body.\n\n        The XML is formed by adding, to the envelope of the XML returned by\n        ``self._base_body``, the following ``Body`` part:\n\n        .. code :: xml\n\n         <s:Body>\n           <getMetadata xmlns=\"http://www.sonos.com/Services/1.1\">\n             <id>root</id>\n             <index>0</index>\n             <count>100</count>\n           </getMetadata>\n         </s:Body>\n\n        .. note:: The XML contains index and count, but the service does not\n        seem to respect them, so therefore they have not been included as\n        arguments."
  },
  {
    "code": "def get_min_isr(zk, topic):\n    ISR_CONF_NAME = 'min.insync.replicas'\n    try:\n        config = zk.get_topic_config(topic)\n    except NoNodeError:\n        return None\n    if ISR_CONF_NAME in config['config']:\n        return int(config['config'][ISR_CONF_NAME])\n    else:\n        return None",
    "docstring": "Return the min-isr for topic, or None if not specified"
  },
  {
    "code": "def full_name(self):\n        formatted_user = []\n        if self.user.first_name is not None:\n            formatted_user.append(self.user.first_name)\n        if self.user.last_name is not None:\n            formatted_user.append(self.user.last_name)\n        return \" \".join(formatted_user)",
    "docstring": "Returns the first and last name of the user separated by a space."
  },
  {
    "code": "def get_path(url):\n    url = urlsplit(url)\n    path = url.path\n    if url.query:\n        path += \"?{}\".format(url.query)\n    return path",
    "docstring": "Get the path from a given url, including the querystring.\n\n    Args:\n        url (str)\n    Returns:\n        str"
  },
  {
    "code": "def _handle_token(self, token):\n        try:\n            return _HANDLERS[type(token)](self, token)\n        except KeyError:\n            err = \"_handle_token() got unexpected {0}\"\n            raise ParserError(err.format(type(token).__name__))",
    "docstring": "Handle a single token."
  },
  {
    "code": "def _normalize_roots(file_roots):\n    for saltenv, dirs in six.iteritems(file_roots):\n        normalized_saltenv = six.text_type(saltenv)\n        if normalized_saltenv != saltenv:\n            file_roots[normalized_saltenv] = file_roots.pop(saltenv)\n        if not isinstance(dirs, (list, tuple)):\n            file_roots[normalized_saltenv] = []\n        file_roots[normalized_saltenv] = \\\n                _expand_glob_path(file_roots[normalized_saltenv])\n    return file_roots",
    "docstring": "Normalize file or pillar roots."
  },
  {
    "code": "def VAR_DECL(self, cursor):\n        name = self.get_unique_name(cursor)\n        log.debug('VAR_DECL: name: %s', name)\n        if self.is_registered(name):\n            return self.get_registered(name)\n        _type = self._VAR_DECL_type(cursor)\n        init_value = self._VAR_DECL_value(cursor, _type)\n        log.debug('VAR_DECL: _type:%s', _type.name)\n        log.debug('VAR_DECL: _init:%s', init_value)\n        log.debug('VAR_DECL: location:%s', getattr(cursor, 'location'))\n        obj = self.register(name, typedesc.Variable(name, _type, init_value))\n        self.set_location(obj, cursor)\n        self.set_comment(obj, cursor)\n        return True",
    "docstring": "Handles Variable declaration."
  },
  {
    "code": "def authenticate(remote_addr, password, cert, key, verify_cert=True):\n    client = pylxd_client_get(remote_addr, cert, key, verify_cert)\n    if client.trusted:\n        return True\n    try:\n        client.authenticate(password)\n    except pylxd.exceptions.LXDAPIException as e:\n        raise CommandExecutionError(six.text_type(e))\n    return client.trusted",
    "docstring": "Authenticate with a remote LXDaemon.\n\n    remote_addr :\n        An URL to a remote Server, you also have to give cert and key if you\n        provide remote_addr and its a TCP Address!\n\n        Examples:\n            https://myserver.lan:8443\n\n    password :\n        The password of the remote.\n\n    cert :\n        PEM Formatted SSL Certificate.\n\n        Examples:\n            ~/.config/lxc/client.crt\n\n    key :\n        PEM Formatted SSL Key.\n\n        Examples:\n            ~/.config/lxc/client.key\n\n    verify_cert : True\n        Wherever to verify the cert, this is by default True\n        but in the most cases you want to set it off as LXD\n        normaly uses self-signed certificates.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        $ salt '*' lxd.authenticate https://srv01:8443 <yourpass> ~/.config/lxc/client.crt ~/.config/lxc/client.key false\n\n    See the `requests-docs`_ for the SSL stuff.\n\n    .. _requests-docs: http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification"
  },
  {
    "code": "def to_bytes(self):\n        header = self._make_header(self._checksum)\n        return header + self._options.to_bytes()",
    "docstring": "Return packed byte representation of the TCP header."
  },
  {
    "code": "def has_publish_permission(self, request, obj=None):\n        permission_name = '{}.publish_{}'.format(self.opts.app_label, self.opts.model_name)\n        has_permission = request.user.has_perm(permission_name)\n        if obj is not None and has_permission is False:\n            has_permission = request.user.has_perm(permission_name, obj=obj)\n        return has_permission",
    "docstring": "Returns a boolean if the user in the request has publish permission for the object."
  },
  {
    "code": "def finish(self, status, response):\n        self.response = binascii.hexlify(response).decode('utf-8')\n        self.status = status\n        self.runtime = monotonic() - self._start_time",
    "docstring": "Mark the end of a recorded RPC."
  },
  {
    "code": "def add_order(self, order):\n        key = '%s_%s' % (order.region_id, order.type_id)\n        if not self._orders.has_key(key):\n            self.set_empty_region(\n                order.region_id,\n                order.type_id,\n                order.generated_at\n            )\n        self._orders[key].add_order(order)",
    "docstring": "Adds a MarketOrder instance to the list of market orders contained\n        within this order list. Does some behind-the-scenes magic to get it\n        all ready for serialization.\n\n        :param MarketOrder order: The order to add to this order list."
  },
  {
    "code": "def fast_memory_load(self, addr, size, data_type, endness='Iend_LE'):\n        if data_type is int:\n            try:\n                return self.project.loader.memory.unpack_word(addr, size=size, endness=endness)\n            except KeyError:\n                return None\n        try:\n            data = self.project.loader.memory.load(addr, size)\n            if data_type is str:\n                return \"\".join(chr(i) for i in data)\n            return data\n        except KeyError:\n            return None",
    "docstring": "Load memory bytes from loader's memory backend.\n\n        :param int addr:    The address to begin memory loading.\n        :param int size:    Size in bytes.\n        :param data_type:   Type of the data.\n        :param str endness: Endianness of this memory load.\n        :return:            Data read out of the memory.\n        :rtype:             int or bytes or str or None"
  },
  {
    "code": "def _create_compositional_array_(expanded_chemical_formaula_string):\n    element_array = re.findall(\n        '[A-Z][^A-Z]*',\n        expanded_chemical_formaula_string)\n    split_element_array = []\n    for s in element_array:\n        m = re.match(r\"([a-zA-Z]+)([0-9\\.]*)\", s, re.I)\n        if m:\n            items = m.groups()\n            if items[1] == \"\":\n                items = (items[0], 1)\n        this_e = {\"symbol\": items[0], \"occurances\": float(items[1])}\n        split_element_array.append(this_e)\n    return split_element_array",
    "docstring": "Splits an expanded chemical formula string into an array of dictionaries containing information about each element\n\n    :param expanded_chemical_formaula_string: a clean (not necessarily emperical, but without any special characters) chemical formula string, as returned by _expand_formula_()\n    :return: an array of dictionaries"
  },
  {
    "code": "def get_stream_action_type(stream_arn):\n    stream_type_map = {\n        \"kinesis\": awacs.kinesis.Action,\n        \"dynamodb\": awacs.dynamodb.Action,\n    }\n    stream_type = stream_arn.split(\":\")[2]\n    try:\n        return stream_type_map[stream_type]\n    except KeyError:\n        raise ValueError(\n            \"Invalid stream type '%s' in arn '%s'\" % (stream_type, stream_arn)\n        )",
    "docstring": "Returns the awacs Action for a stream type given an arn\n\n    Args:\n        stream_arn (str): The Arn of the stream.\n\n    Returns:\n        :class:`awacs.aws.Action`: The appropriate stream type awacs Action\n            class\n\n    Raises:\n        ValueError: If the stream type doesn't match kinesis or dynamodb."
  },
  {
    "code": "def sender(self) -> Optional[Sequence[SingleAddressHeader]]:\n        try:\n            return cast(Sequence[SingleAddressHeader], self[b'sender'])\n        except KeyError:\n            return None",
    "docstring": "The ``Sender`` header."
  },
  {
    "code": "def content_remove(self, key, model, contentid):\n        path = PROVISION_MANAGE_CONTENT + model + '/' + contentid\n        return self._request(path, key, '', 'DELETE', self._manage_by_cik)",
    "docstring": "Deletes the information for the given contentid under the given model.\n\n        This method maps to\n        https://github.com/exosite/docs/tree/master/provision#delete---delete-content\n\n        Args:\n            key: The CIK or Token for the device\n            model:"
  },
  {
    "code": "def _default_key_setter(self, name, subject):\n        if is_config_item(subject):\n            self.add_item(name, subject)\n        elif is_config_section(subject):\n            self.add_section(name, subject)\n        else:\n            raise TypeError(\n                'Section items can only be replaced with items, '\n                'got {type}. To set item value use ...{name}.value = <new_value>'.format(\n                    type=type(subject),\n                    name=name,\n                )\n            )",
    "docstring": "This method is used only when there is a custom key_setter set.\n\n        Do not override this method."
  },
  {
    "code": "def update_port_side(self):\n        from rafcon.utils.geometry import point_left_of_line\n        p = (self._initial_pos.x, self._initial_pos.y)\n        nw_x, nw_y, se_x, se_y = self.get_adjusted_border_positions()\n        if point_left_of_line(p, (nw_x, nw_y), (se_x, se_y)):\n            if point_left_of_line(p, (nw_x, se_y), (se_x, nw_y)):\n                self._port.side = SnappedSide.TOP\n                self.limit_pos(p[0], se_x, nw_x)\n            else:\n                self._port.side = SnappedSide.RIGHT\n                self.limit_pos(p[1], se_y, nw_y)\n        else:\n            if point_left_of_line(p, (nw_x, se_y), (se_x, nw_y)):\n                self._port.side = SnappedSide.LEFT\n                self.limit_pos(p[1], se_y, nw_y)\n            else:\n                self._port.side = SnappedSide.BOTTOM\n                self.limit_pos(p[0], se_x, nw_x)\n        self.set_nearest_border()",
    "docstring": "Updates the initial position of the port\n\n        The port side is ignored but calculated from the port position. Then the port position is limited to the four\n        side lines of the state."
  },
  {
    "code": "def get_current_client(self):\r\n        try:\r\n            client = self.tabwidget.currentWidget()\r\n        except AttributeError:\r\n            client = None\r\n        if client is not None:\r\n            return client",
    "docstring": "Return the currently selected notebook."
  },
  {
    "code": "def unpack_log_data(self, log_data, timestamp):\n        ret_data = {}\n        data_index = 0\n        for var in self.variables:\n            size = LogTocElement.get_size_from_id(var.fetch_as)\n            name = var.name\n            unpackstring = LogTocElement.get_unpack_string_from_id(\n                var.fetch_as)\n            value = struct.unpack(\n                unpackstring, log_data[data_index:data_index + size])[0]\n            data_index += size\n            ret_data[name] = value\n        self.data_received_cb.call(timestamp, ret_data, self)",
    "docstring": "Unpack received logging data so it represent real values according\n        to the configuration in the entry"
  },
  {
    "code": "def configure_owner(self, owner='www-data'):\n        if owner is not None:\n            self.main_process.set_owner_params(uid=owner, gid=owner)\n        return self",
    "docstring": "Shortcut to set process owner data.\n\n        :param str|unicode owner: Sets user and group. Default: ``www-data``."
  },
  {
    "code": "def degrees(x):\n    if isinstance(x, UncertainFunction):\n        mcpts = np.degrees(x._mcpts)\n        return UncertainFunction(mcpts)\n    else:\n        return np.degrees(x)",
    "docstring": "Convert radians to degrees"
  },
  {
    "code": "def get_long_description():\n    here = os.path.abspath(os.path.dirname(__file__))\n    with copen(os.path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as description:\n        return description.read()",
    "docstring": "Retrieve the long description from DESCRIPTION.rst"
  },
  {
    "code": "def get_data(self, collection):\n        data = self._filter_queryset('view_data', collection.data.all())\n        return self._serialize_data(data)",
    "docstring": "Return serialized list of data objects on collection that user has `view` permission on."
  },
  {
    "code": "def enable_aliases_autocomplete_interactive(_, **kwargs):\n    subtree = kwargs.get('subtree', None)\n    if not subtree or not hasattr(subtree, 'children'):\n        return\n    for alias, alias_command in filter_aliases(get_alias_table()):\n        if subtree.in_tree(alias_command.split()):\n            subtree.add_child(CommandBranch(alias))",
    "docstring": "Enable aliases autocomplete on interactive mode by injecting aliases in the command tree."
  },
  {
    "code": "def get_product_order_book(self, product_id, level=1):\n        params = {'level': level}\n        return self._send_message('get',\n                                  '/products/{}/book'.format(product_id),\n                                  params=params)",
    "docstring": "Get a list of open orders for a product.\n\n        The amount of detail shown can be customized with the `level`\n        parameter:\n        * 1: Only the best bid and ask\n        * 2: Top 50 bids and asks (aggregated)\n        * 3: Full order book (non aggregated)\n\n        Level 1 and Level 2 are recommended for polling. For the most\n        up-to-date data, consider using the websocket stream.\n\n        **Caution**: Level 3 is only recommended for users wishing to\n        maintain a full real-time order book using the websocket\n        stream. Abuse of Level 3 via polling will cause your access to\n        be limited or blocked.\n\n        Args:\n            product_id (str): Product\n            level (Optional[int]): Order book level (1, 2, or 3).\n                Default is 1.\n\n        Returns:\n            dict: Order book. Example for level 1::\n                {\n                    \"sequence\": \"3\",\n                    \"bids\": [\n                        [ price, size, num-orders ],\n                    ],\n                    \"asks\": [\n                        [ price, size, num-orders ],\n                    ]\n                }"
  },
  {
    "code": "def do_call(self, path, method, body=None, headers=None):\n        url = urljoin(self.base_url, path)\n        try:\n            resp = requests.request(method, url, data=body, headers=headers,\n                                    auth=self.auth, timeout=self.timeout)\n        except requests.exceptions.Timeout as out:\n            raise NetworkError(\"Timeout while trying to connect to RabbitMQ\")\n        except requests.exceptions.RequestException as err:\n            raise NetworkError(\"Error during request %s %s\" % (type(err), err))\n        try:\n            content = resp.json()\n        except ValueError as out:\n            content = None\n        if resp.status_code < 200 or resp.status_code > 206:\n            raise HTTPError(content, resp.status_code, resp.text, path, body)\n        else:\n            if content:\n                return content\n            else:\n                return None",
    "docstring": "Send an HTTP request to the REST API.\n\n        :param string path: A URL\n        :param string method: The HTTP method (GET, POST, etc.) to use\n            in the request.\n        :param string body: A string representing any data to be sent in the\n            body of the HTTP request.\n        :param dictionary headers:\n            \"{header-name: header-value}\" dictionary."
  },
  {
    "code": "def extras_to_string(extras):\n    if isinstance(extras, six.string_types):\n        if extras.startswith(\"[\"):\n            return extras\n        else:\n            extras = [extras]\n    if not extras:\n        return \"\"\n    return \"[{0}]\".format(\",\".join(sorted(set(extras))))",
    "docstring": "Turn a list of extras into a string"
  },
  {
    "code": "def with_batch_norm_control(self, is_training, test_local_stats=True):\n    return BatchNormLSTM.CoreWithExtraBuildArgs(\n        self, is_training=is_training, test_local_stats=test_local_stats)",
    "docstring": "Wraps this RNNCore with the additional control input to the `BatchNorm`s.\n\n    Example usage:\n\n      lstm = snt.BatchNormLSTM(4)\n      is_training = tf.placeholder(tf.bool)\n      rnn_input = ...\n      my_rnn = rnn.rnn(lstm.with_batch_norm_control(is_training), rnn_input)\n\n    Args:\n      is_training: Boolean that indicates whether we are in\n        training mode or testing mode. When in training mode, the batch norm\n        statistics are taken from the given batch, and moving statistics are\n        updated. When in testing mode, the moving statistics are not updated,\n        and in addition if `test_local_stats` is False then the moving\n        statistics are used for the batch statistics. See the `BatchNorm` module\n        for more details.\n      test_local_stats: Boolean scalar indicated whether to use local\n        batch statistics in test mode.\n\n    Returns:\n      snt.RNNCore wrapping this class with the extra input(s) added."
  },
  {
    "code": "def validate_list_of_identical_dicts(self, list_of_dicts):\n        hashes = []\n        for _dict in list_of_dicts:\n            hashes.append(hash(frozenset(_dict.items())))\n        self.log.debug('Hashes: {}'.format(hashes))\n        if len(set(hashes)) == 1:\n            self.log.debug('Dicts within list are identical')\n        else:\n            return 'Dicts within list are not identical'\n        return None",
    "docstring": "Check that all dicts within a list are identical."
  },
  {
    "code": "def new_profile(self):\n        dir = os.path.join(QgsApplication.qgisSettingsDirPath(),\n                           'inasafe', 'minimum_needs')\n        file_name, __ = QFileDialog.getSaveFileName(\n            self,\n            self.tr('Create a minimum needs profile'),\n            expanduser(dir),\n            self.tr('JSON files (*.json *.JSON)'),\n            options=QFileDialog.DontUseNativeDialog)\n        if not file_name:\n            return\n        file_name = basename(file_name)\n        if self.profile_combo.findText(file_name) == -1:\n            minimum_needs = {\n                'resources': [], 'provenance': '', 'profile': file_name}\n            self.minimum_needs.update_minimum_needs(minimum_needs)\n            self.minimum_needs.save_profile(file_name)\n            self.profile_combo.addItem(file_name)\n            self.clear_resource_list()\n            self.profile_combo.setCurrentIndex(\n                self.profile_combo.findText(file_name))\n        else:\n            self.profile_combo.setCurrentIndex(\n                self.profile_combo.findText(file_name))\n            self.select_profile_by_name(file_name)",
    "docstring": "Create a new profile by name."
  },
  {
    "code": "def terminal(self, out=None, border=None):\n        if out is None and sys.platform == 'win32':\n            try:\n                writers.write_terminal_win(self.matrix, self._version, border)\n            except OSError:\n                writers.write_terminal(self.matrix, self._version, sys.stdout,\n                                       border)\n        else:\n            writers.write_terminal(self.matrix, self._version, out or sys.stdout,\n                                   border)",
    "docstring": "\\\n        Serializes the matrix as ANSI escape code.\n\n        :param out: Filename or a file-like object supporting to write text.\n                If ``None`` (default), the matrix is written to ``sys.stdout``.\n        :param int border: Integer indicating the size of the quiet zone.\n                If set to ``None`` (default), the recommended border size\n                will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes)."
  },
  {
    "code": "def generate_values(self, *args, **kwargs):\n        sample_size = kwargs.get('size', self.size)\n        f = self.instantiate_distribution_function(self.module_name, self.distribution_name)\n        distribution_function = partial(f, *self.random_function_params, size=sample_size)\n        if self.sample_mean_value:\n            sample = np.full(sample_size, self.get_mean(distribution_function))\n        else:\n            sample = distribution_function()\n        return sample",
    "docstring": "Generate a sample of values by sampling from a distribution. The size of the sample can be overriden with the 'size' kwarg.\n\n        If `self.sample_mean_value == True` the sample will contain \"size\" times the mean value.\n\n        :param args:\n        :param kwargs:\n        :return: sample as vector of given size"
  },
  {
    "code": "def run(self, context=None, stdout=None, stderr=None):\n        \"Like execute, but records a skip if the should_skip method returns True.\"\n        if self.should_skip():\n            self._record_skipped_example(self.formatter)\n            self.num_skipped += 1\n        else:\n            self.execute(context, stdout, stderr)\n        return self.num_successes, self.num_failures, self.num_skipped",
    "docstring": "Like execute, but records a skip if the should_skip method returns True."
  },
  {
    "code": "def subsequent_mask(size: int, device: str = 'cpu') -> torch.Tensor:\n    mask = torch.tril(torch.ones(size, size, device=device, dtype=torch.int32)).unsqueeze(0)\n    return mask",
    "docstring": "Mask out subsequent positions."
  },
  {
    "code": "def _iter_info(self, niter, level=logging.INFO):\n        max_mis = self.iter_mis[niter - 1]\n        msg = ' Iter {:<d}.  max mismatch = {:8.7f}'.format(niter, max_mis)\n        logger.info(msg)",
    "docstring": "Log iteration number and mismatch\n\n        Parameters\n        ----------\n        level\n            logging level\n        Returns\n        -------\n        None"
  },
  {
    "code": "def __taint_move(self, instr):\n        op0_taint = self.get_operand_taint(instr.operands[0])\n        self.set_operand_taint(instr.operands[2], op0_taint)",
    "docstring": "Taint registers move instruction."
  },
  {
    "code": "def read_int64(self, little_endian=True):\n        if little_endian:\n            endian = \"<\"\n        else:\n            endian = \">\"\n        return self.unpack('%sq' % endian, 8)",
    "docstring": "Read 8 bytes as a signed integer value from the stream.\n\n        Args:\n            little_endian (bool): specify the endianness. (Default) Little endian.\n\n        Returns:\n            int:"
  },
  {
    "code": "def send_signal(self, s):\n        self._get_signal_event(s)\n        pid = self.get_pid()\n        if not pid:\n            raise ValueError('Daemon is not running.')\n        os.kill(pid, s)",
    "docstring": "Send a signal to the daemon process.\n\n        The signal must have been enabled using the ``signals``\n        parameter of :py:meth:`Service.__init__`. Otherwise, a\n        ``ValueError`` is raised."
  },
  {
    "code": "def created(self):\n        timestamp, current = self._created\n        if timestamp.endswith('ago'):\n            quantity, kind, ago = timestamp.split()\n            quantity = int(quantity)\n            if 'sec' in kind:\n                current -= quantity\n            elif 'min' in kind:\n                current -= quantity * 60\n            elif 'hour' in kind:\n                current -= quantity * 60 * 60\n            return datetime.datetime.fromtimestamp(current)\n        current = datetime.datetime.fromtimestamp(current)\n        timestamp = timestamp.replace(\n            'Y-day', str(current.date() - datetime.timedelta(days=1)))\n        timestamp = timestamp.replace('Today', current.date().isoformat())\n        try:\n            return dateutil.parser.parse(timestamp)\n        except:\n            return current",
    "docstring": "Attempt to parse the human readable torrent creation datetime."
  },
  {
    "code": "def command(self, request_type, uri, payload):\n        self.command_count += 1\n        if payload is None:\n            payload = {}\n        message = {\n            'id': \"{}_{}\".format(type, self.command_count),\n            'type': request_type,\n            'uri': \"ssap://{}\".format(uri),\n            'payload': payload,\n        }\n        self.last_response = None\n        try:\n            loop = asyncio.new_event_loop()\n            asyncio.set_event_loop(loop)\n            loop.run_until_complete(asyncio.wait_for(self._command(message), self.timeout_connect, loop=loop))\n        finally:\n            loop.close()",
    "docstring": "Build and send a command."
  },
  {
    "code": "def logline_timestamp_comparator(t1, t2):\n    dt1 = _parse_logline_timestamp(t1)\n    dt2 = _parse_logline_timestamp(t2)\n    for u1, u2 in zip(dt1, dt2):\n        if u1 < u2:\n            return -1\n        elif u1 > u2:\n            return 1\n    return 0",
    "docstring": "Comparator for timestamps in logline format.\n\n    Args:\n        t1: Timestamp in logline format.\n        t2: Timestamp in logline format.\n\n    Returns:\n        -1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2."
  },
  {
    "code": "def put(self, endpoint: str, **kwargs) -> dict:\n        return self._request('PUT', endpoint, **kwargs)",
    "docstring": "HTTP PUT operation to API endpoint."
  },
  {
    "code": "def destroy(self, request, pk=None):\n        org = self.get_object()\n        org.archived = True\n        org.save()\n        return Response(status=status.HTTP_204_NO_CONTENT)",
    "docstring": "For DELETE actions, archive the organization, don't delete."
  },
  {
    "code": "def run(self, **kwargs):\n        super().run(**kwargs)\n        scheduler = self.scheduler_plugins[self.active_scheduler]()\n        if not kwargs['no_daemon']:\n            self.log.info('Starting {} worker with {} threads checking for new messages every {} seconds'.format(\n                scheduler.name,\n                kwargs['threads'],\n                kwargs['delay']\n            ))\n            for i in range(kwargs['threads']):\n                thd = threading.Thread(\n                    target=self.execute_worker_thread,\n                    args=(scheduler.execute_worker, kwargs['delay'])\n                )\n                thd.start()\n        else:\n            self.log.info('Starting {} worker for a single non-daemon execution'.format(\n                scheduler.name\n            ))\n            scheduler.execute_worker()",
    "docstring": "Execute the worker thread.\n\n        Returns:\n            `None`"
  },
  {
    "code": "def get_appliance(self, id_or_uri, fields=''):\n        uri = self.URI + '/image-streamer-appliances/' + extract_id_from_uri(id_or_uri)\n        if fields:\n            uri += '?fields=' + fields\n        return self._client.get(uri)",
    "docstring": "Gets the particular Image Streamer resource based on its ID or URI.\n\n        Args:\n            id_or_uri:\n                Can be either the Os Deployment Server ID or the URI\n            fields:\n                Specifies which fields should be returned in the result.\n\n        Returns:\n             dict: Image Streamer resource."
  },
  {
    "code": "def _get_cached_response_from_django_cache(key):\n        if TieredCache._should_force_django_cache_miss():\n            return CachedResponse(is_found=False, key=key, value=None)\n        cached_value = django_cache.get(key, _CACHE_MISS)\n        is_found = cached_value is not _CACHE_MISS\n        return CachedResponse(is_found, key, cached_value)",
    "docstring": "Retrieves a CachedResponse for the given key from the django cache.\n\n        If the request was set to force cache misses, then this will always\n        return a cache miss response.\n\n        Args:\n            key (string)\n\n        Returns:\n            A CachedResponse with is_found status and value."
  },
  {
    "code": "def reset(self):\n        self.remaining_cycles = self.initial_training_cycles\n        self.needle_index = random.randrange(self.input_size)",
    "docstring": "Reset the scenario, starting it over for a new run.\n\n        Usage:\n            if not scenario.more():\n                scenario.reset()\n\n        Arguments: None\n        Return: None"
  },
  {
    "code": "def read_dbf(dbf_path, index = None, cols = False, incl_index = False):\n    db = ps.open(dbf_path)\n    if cols:\n        if incl_index:\n            cols.append(index)\n        vars_to_read = cols\n    else:\n        vars_to_read = db.header\n    data = dict([(var, db.by_col(var)) for var in vars_to_read])\n    if index:\n        index = db.by_col(index)\n        db.close()\n        return pd.DataFrame(data, index=index)\n    else:\n        db.close()\n        return pd.DataFrame(data)",
    "docstring": "Read a dbf file as a pandas.DataFrame, optionally selecting the index\n    variable and which columns are to be loaded.\n\n    __author__  = \"Dani Arribas-Bel <darribas@asu.edu> \"\n    ...\n\n    Arguments\n    ---------\n    dbf_path    : str\n                  Path to the DBF file to be read\n    index       : str\n                  Name of the column to be used as the index of the DataFrame\n    cols        : list\n                  List with the names of the columns to be read into the\n                  DataFrame. Defaults to False, which reads the whole dbf\n    incl_index  : Boolean\n                  If True index is included in the DataFrame as a\n                  column too. Defaults to False\n\n    Returns\n    -------\n    df          : DataFrame\n                  pandas.DataFrame object created"
  },
  {
    "code": "def _handle_expander_message(self, data):\n        msg = ExpanderMessage(data)\n        self._update_internal_states(msg)\n        self.on_expander_message(message=msg)\n        return msg",
    "docstring": "Handle expander messages.\n\n        :param data: expander message to parse\n        :type data: string\n\n        :returns: :py:class:`~alarmdecoder.messages.ExpanderMessage`"
  },
  {
    "code": "def parse_restriction_dist(self, f):\n        parsed_data = dict()\n        firstline = True\n        for l in f['f']:\n            if firstline:\n                firstline = False\n                continue\n            s = l.split(\"\\t\")\n            if len(s) > 1:\n                nuc = float(s[0].strip())\n                v1 = float(s[1].strip())\n                v2 = float(s[2].strip())\n                v = v1 + v2\n                parsed_data.update({nuc:v})\n        return parsed_data",
    "docstring": "Parse HOMER tagdirectory petagRestrictionDistribution file."
  },
  {
    "code": "def bulk_recover(workers, lbn, profile='default'):\n    ret = {}\n    if isinstance(workers, six.string_types):\n        workers = workers.split(',')\n    for worker in workers:\n        try:\n            ret[worker] = worker_recover(worker, lbn, profile)\n        except Exception:\n            ret[worker] = False\n    return ret",
    "docstring": "Recover all the given workers in the specific load balancer\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1\n        salt '*' modjk.bulk_recover node1,node2,node3 loadbalancer1 other-profile\n\n        salt '*' modjk.bulk_recover [\"node1\",\"node2\",\"node3\"] loadbalancer1\n        salt '*' modjk.bulk_recover [\"node1\",\"node2\",\"node3\"] loadbalancer1 other-profile"
  },
  {
    "code": "def list_commands(self, page_size=None):\n        params = {}\n        if page_size is not None:\n            params['limit'] = page_size\n        return pagination.Iterator(\n            client=self._client,\n            path='/mdb/{}/commands'.format(self._instance),\n            params=params,\n            response_class=mdb_pb2.ListCommandsResponse,\n            items_key='command',\n            item_mapper=Command,\n        )",
    "docstring": "Lists the commands visible to this client.\n\n        Commands are returned in lexicographical order.\n\n        :rtype: :class:`.Command` iterator"
  },
  {
    "code": "def delete_group(self, group_id, force=False):\n        params = {'force': force}\n        response = self._do_request(\n            'DELETE', '/v2/groups/{group_id}'.format(group_id=group_id), params=params)\n        return response.json()",
    "docstring": "Stop and destroy a group.\n\n        :param str group_id: group ID\n        :param bool force: apply even if a deployment is in progress\n\n        :returns: a dict containing the deleted version\n        :rtype: dict"
  },
  {
    "code": "def _sanitize_title(self, title):\n        title = re.sub(self.inside_brackets, \"\", title)\n        title = re.sub(self.after_delimiter, \"\", title)\n        return title.strip()",
    "docstring": "Remove redunant meta data from title and return it"
  },
  {
    "code": "def relativize(self, origin):\n        if not origin is None and self.is_subdomain(origin):\n            return Name(self[: -len(origin)])\n        else:\n            return self",
    "docstring": "If self is a subdomain of origin, return a new name which is self\n        relative to origin.  Otherwise return self.\n        @rtype: dns.name.Name object"
  },
  {
    "code": "def acl(self):\n        r = fapi.get_workspace_acl(self.namespace, self.name, self.api_url)\n        fapi._check_response_code(r, 200)\n        return r.json()",
    "docstring": "Get the access control list for this workspace."
  },
  {
    "code": "def reset(self, path, pretend=False):\n        self._notes = []\n        migrations = sorted(self._repository.get_ran(), reverse=True)\n        count = len(migrations)\n        if count == 0:\n            self._note(\"<info>Nothing to rollback.</info>\")\n        else:\n            for migration in migrations:\n                self._run_down(path, {\"migration\": migration}, pretend)\n        return count",
    "docstring": "Rolls all of the currently applied migrations back.\n\n        :param path: The path\n        :type path: str\n\n        :param pretend: Whether we execute the migrations as dry-run\n        :type pretend: bool\n\n        :rtype: count"
  },
  {
    "code": "def _AddMessageMethods(message_descriptor, cls):\n  _AddListFieldsMethod(message_descriptor, cls)\n  _AddHasFieldMethod(message_descriptor, cls)\n  _AddClearFieldMethod(message_descriptor, cls)\n  if message_descriptor.is_extendable:\n    _AddClearExtensionMethod(cls)\n    _AddHasExtensionMethod(cls)\n  _AddEqualsMethod(message_descriptor, cls)\n  _AddStrMethod(message_descriptor, cls)\n  _AddReprMethod(message_descriptor, cls)\n  _AddUnicodeMethod(message_descriptor, cls)\n  _AddByteSizeMethod(message_descriptor, cls)\n  _AddSerializeToStringMethod(message_descriptor, cls)\n  _AddSerializePartialToStringMethod(message_descriptor, cls)\n  _AddMergeFromStringMethod(message_descriptor, cls)\n  _AddIsInitializedMethod(message_descriptor, cls)\n  _AddMergeFromMethod(cls)\n  _AddWhichOneofMethod(message_descriptor, cls)\n  _AddReduceMethod(cls)\n  cls.Clear = _Clear\n  cls.DiscardUnknownFields = _DiscardUnknownFields\n  cls._SetListener = _SetListener",
    "docstring": "Adds implementations of all Message methods to cls."
  },
  {
    "code": "def _extract_file(zip_fp, info, path):\n    zip_fp.extract(info.filename, path=path)\n    out_path = os.path.join(path, info.filename)\n    perm = info.external_attr >> 16\n    perm |= stat.S_IREAD\n    os.chmod(out_path, perm)",
    "docstring": "Extract files while explicitly setting the proper permissions"
  },
  {
    "code": "def scale(self, scale, center=None):\n        scale = transforms.scale(as_vec4(scale, default=(1, 1, 1, 1))[0, :3])\n        if center is not None:\n            center = as_vec4(center)[0, :3]\n            scale = np.dot(np.dot(transforms.translate(-center), scale),\n                           transforms.translate(center))\n        self.matrix = np.dot(self.matrix, scale)",
    "docstring": "Scale the matrix about a given origin.\n\n        The scaling is applied *after* the transformations already present\n        in the matrix.\n\n        Parameters\n        ----------\n        scale : array-like\n            Scale factors along x, y and z axes.\n        center : array-like or None\n            The x, y and z coordinates to scale around. If None,\n            (0, 0, 0) will be used."
  },
  {
    "code": "def change_count(self):\r\n        status = self.git.status(porcelain=True, untracked_files='no').strip()\r\n        if not status:\r\n            return 0\r\n        else:\r\n            return len(status.split('\\n'))",
    "docstring": "The number of changes in the working directory."
  },
  {
    "code": "def link_contentkey_authorization_policy(access_token, ckap_id, options_id, \\\nams_redirected_rest_endpoint):\n    path = '/ContentKeyAuthorizationPolicies'\n    full_path = ''.join([path, \"('\", ckap_id, \"')\", \"/$links/Options\"])\n    full_path_encoded = urllib.parse.quote(full_path, safe='')\n    endpoint = ''.join([ams_rest_endpoint, full_path_encoded])\n    uri = ''.join([ams_redirected_rest_endpoint, 'ContentKeyAuthorizationPolicyOptions', \\\n    \"('\", options_id, \"')\"])\n    body = '{\"uri\": \"' + uri + '\"}'\n    return do_ams_post(endpoint, full_path_encoded, body, access_token, \"json_only\", \"1.0;NetFx\")",
    "docstring": "Link Media Service Content Key Authorization Policy.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        ckap_id (str): A Media Service Asset Content Key Authorization Policy ID.\n        options_id (str): A Media Service Content Key Authorization Policy Options .\n        ams_redirected_rest_endpoint (str): A Media Service Redirected Endpoint.\n\n    Returns:\n        HTTP response. JSON body."
  },
  {
    "code": "def total_seconds(td):\n  secs = td.seconds + td.days * 24 * 3600\n  if td.microseconds:\n    secs += 1\n  return secs",
    "docstring": "convert a timedelta to seconds.\n\n  This is patterned after timedelta.total_seconds, which is only\n  available in python 27.\n\n  Args:\n    td: a timedelta object.\n\n  Returns:\n    total seconds within a timedelta. Rounded up to seconds."
  },
  {
    "code": "def _extract_obo_synonyms(rawterm):\n        synonyms = set()\n        keys = set(owl_synonyms).intersection(rawterm.keys())\n        for k in keys:\n            for s in rawterm[k]:\n                synonyms.add(Synonym(s, owl_synonyms[k]))\n        return synonyms",
    "docstring": "Extract the synonyms defined in the rawterm."
  },
  {
    "code": "def set_deferred_transfer(self, enable):\n        if self._deferred_transfer and not enable:\n            self.flush()\n        self._deferred_transfer = enable",
    "docstring": "Allow transfers to be delayed and buffered\n\n        By default deferred transfers are turned off.  All reads and\n        writes will be completed by the time the function returns.\n\n        When enabled packets are buffered and sent all at once, which\n        increases speed.  When memory is written to, the transfer\n        might take place immediately, or might take place on a future\n        memory write.  This means that an invalid write could cause an\n        exception to occur on a later, unrelated write.  To guarantee\n        that previous writes are complete call the flush() function.\n\n        The behaviour of read operations is determined by the modes\n        READ_START, READ_NOW and READ_END.  The option READ_NOW is the\n        default and will cause the read to flush all previous writes,\n        and read the data immediately.  To improve performance, multiple\n        reads can be made using READ_START and finished later with READ_NOW.\n        This allows the reads to be buffered and sent at once.  Note - All\n        READ_ENDs must be called before a call using READ_NOW can be made."
  },
  {
    "code": "def validate_and_decode(jwt_bu64, cert_obj):\n    public_key = cert_obj.public_key()\n    message = '.'.join(d1_common.cert.jwt.get_bu64_tup(jwt_bu64)[:2])\n    signature = d1_common.cert.jwt.get_jwt_tup(jwt_bu64)[2]\n    try:\n        public_key.verify(\n            signature,\n            message,\n            cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15(),\n            cryptography.hazmat.primitives.hashes.SHA256(),\n        )\n    except cryptography.exceptions.InvalidSignature as e:\n        raise Exception('Signature is invalid. error=\"{}\"'.format(str(e)))\n    return d1_common.cert.jwt.get_jwt_dict(jwt_bu64)",
    "docstring": "Example for validating the signature of a JWT using only the cryptography\n    library.\n\n    Note that this does NOT validate the claims in the claim set."
  },
  {
    "code": "def merge_extra_options(self, needs_info):\n        extra_keys = set(self.options.keys()).difference(set(needs_info.keys()))\n        for key in extra_keys:\n            needs_info[key] = self.options[key]\n        for key in self.option_spec:\n            if key not in needs_info.keys():\n                needs_info[key] = \"\"\n        return extra_keys",
    "docstring": "Add any extra options introduced via options_ext to needs_info"
  },
  {
    "code": "def _get_triplet_scores(self, triangles_list):\n        triplet_scores = {}\n        for triplet in triangles_list:\n            triplet_intersections = [intersect for intersect in it.combinations(triplet, 2)]\n            ind_max = sum([np.amax(self.objective[frozenset(intersect)].values) for intersect in triplet_intersections])\n            joint_max = self.objective[frozenset(triplet_intersections[0])]\n            for intersect in triplet_intersections[1:]:\n                joint_max += self.objective[frozenset(intersect)]\n            joint_max = np.amax(joint_max.values)\n            score = ind_max - joint_max\n            triplet_scores[frozenset(triplet)] = score\n        return triplet_scores",
    "docstring": "Returns the score of each of the triplets found in the current model\n\n        Parameters\n        ---------\n        triangles_list: list\n                        The list of variables forming the triangles to be updated. It is of the form of\n                        [['var_5', 'var_8', 'var_7'], ['var_4', 'var_5', 'var_7']]\n\n        Return: {frozenset({'var_8', 'var_5', 'var_7'}): 5.024, frozenset({'var_5', 'var_4', 'var_7'}): 10.23}"
  },
  {
    "code": "def _pages_to_generate(self):\n        all_pages = self.get_page_names()\n        ptg = []\n        for slug in all_pages:\n            p = s2page.Page(self, slug, isslug=True)\n            if p.published:\n                ptg.append({'slug': p.slug, 'title':p.title, 'date': p.creation_date })\n        sptg = sorted(ptg, key=lambda x : x['date'],reverse=True)\n        res = [ pinfo['slug'] for pinfo in sptg]\n        return res",
    "docstring": "Return list of slugs that correspond to pages to generate."
  },
  {
    "code": "def main(dimension, iterations):\n    optimizer = PSOOptimizer()\n    solution = optimizer.minimize(sphere, -5.12, 5.12, dimension,\n                                  max_iterations(iterations))\n    return solution, optimizer",
    "docstring": "Main function for PSO optimizer example.\n\n    Instantiate PSOOptimizer to optimize 30-dimensional spherical function."
  },
  {
    "code": "def stats(self, result=None, counter=0):\n        if result is None:\n            result = dict()\n        if counter == 0:\n            if len(self):\n                result[0] = {\"depth\": 0, \"leaf\": 0, \"root\": 1}\n            else:\n                result[0] = {\"depth\": 0, \"leaf\": 1, \"root\": 0}\n        counter += 1\n        if len(self):\n            result.setdefault(\n                counter, {\"depth\": counter, \"leaf\": 0, \"root\": 0})\n            for dict_tree in self.values():\n                if len(dict_tree):\n                    result[counter][\"root\"] += 1\n                else:\n                    result[counter][\"leaf\"] += 1\n                dict_tree.stats(result, counter)\n        return [\n            collections.OrderedDict([\n                (\"depth\", info[\"depth\"]),\n                (\"leaf\", info[\"leaf\"]),\n                (\"root\", info[\"root\"]),\n            ]) for info in\n            sorted(result.values(), key=lambda x: x[\"depth\"])\n        ]",
    "docstring": "Display the node stats info on specific depth in this dict.\n\n        ::\n\n            [\n                {\"depth\": 0, \"leaf\": M0, \"root\": N0},\n                {\"depth\": 1, \"leaf\": M1, \"root\": N1},\n                ...\n                {\"depth\": k, \"leaf\": Mk, \"root\": Nk},\n            ]"
  },
  {
    "code": "def get(cls):\n        if cls.is_twoconspect:\n            return cls.subconspect_el.value or None\n        input_value = cls.input_el.value.strip()\n        if not input_value:\n            return None\n        mdt = conspectus.mdt_by_name.get(input_value)\n        if not mdt:\n            alert(\"Invalid sub-conspect `%s`!\" % input_value)\n            return None\n        return mdt",
    "docstring": "Get code selected by user.\n\n        Returns:\n            str: Code or None in case that user didn't selected anything yet."
  },
  {
    "code": "def update_state(self, state_arr, action_arr):\n        x, y = np.where(action_arr[-1] == 1)\n        self.__agent_pos = (x[0], y[0])\n        self.__route_memory_list.append((x[0], y[0]))\n        self.__route_long_memory_list.append((x[0], y[0]))\n        self.__route_long_memory_list = list(set(self.__route_long_memory_list))\n        while len(self.__route_memory_list) > self.__memory_num:\n            self.__route_memory_list = self.__route_memory_list[1:]\n        return self.extract_now_state()",
    "docstring": "Update state.\n        \n        Override.\n\n        Args:\n            state_arr:    `np.ndarray` of state in `self.t`.\n            action_arr:   `np.ndarray` of action in `self.t`.\n        \n        Returns:\n            `np.ndarray` of state in `self.t+1`."
  },
  {
    "code": "def validate(self):\n        changes = self.change_collector.collect_changes()\n        features = []\n        imported_okay = True\n        for importer, modname, modpath in changes.new_feature_info:\n            try:\n                mod = importer()\n                features.extend(_get_contrib_features(mod))\n            except (ImportError, SyntaxError):\n                logger.info(\n                    'Failed to import module at {}'\n                    .format(modpath))\n                logger.exception('Exception details: ')\n                imported_okay = False\n        if not imported_okay:\n            return False\n        if not features:\n            logger.info('Failed to collect any new features.')\n            return False\n        return all(\n            validate_feature_api(feature, self.X, self.y, subsample=False)\n            for feature in features\n        )",
    "docstring": "Collect and validate all new features"
  },
  {
    "code": "def add_to_history(self, command):\r\n        command = to_text_string(command)\r\n        if command in ['', '\\n'] or command.startswith('Traceback'):\r\n            return\r\n        if command.endswith('\\n'):\r\n            command = command[:-1]\r\n        self.histidx = None\r\n        if len(self.history) > 0 and self.history[-1] == command:\r\n            return\r\n        self.history.append(command)\r\n        text = os.linesep + command\r\n        if self.history_filename not in self.HISTORY_FILENAMES:\r\n            self.HISTORY_FILENAMES.append(self.history_filename)\r\n            text = self.SEPARATOR + text\r\n        try:\r\n            encoding.write(text, self.history_filename, mode='ab')\r\n        except EnvironmentError:\r\n            pass\r\n        if self.append_to_history is not None:\r\n            self.append_to_history.emit(self.history_filename, text)",
    "docstring": "Add command to history"
  },
  {
    "code": "def line_model(freq, data, tref, amp=1, phi=0):\n    freq_line = TimeSeries(zeros(len(data)), delta_t=data.delta_t,\n                           epoch=data.start_time)\n    times = data.sample_times - float(tref)\n    alpha = 2 * numpy.pi * freq * times + phi\n    freq_line.data = amp * numpy.exp(1.j * alpha)\n    return freq_line",
    "docstring": "Simple time-domain model for a frequency line.\n\n    Parameters\n    ----------\n    freq: float\n        Frequency of the line.\n    data: pycbc.types.TimeSeries\n        Reference data, to get delta_t, start_time, duration and sample_times.\n    tref: float\n        Reference time for the line model.\n    amp: {1., float}, optional\n        Amplitude of the frequency line.\n    phi: {0. float}, optional\n        Phase of the frequency line (radians).\n\n    Returns\n    -------\n    freq_line: pycbc.types.TimeSeries\n        A timeseries of the line model with frequency 'freq'. The returned\n        data are complex to allow measuring the amplitude and phase of the\n        corresponding frequency line in the strain data. For extraction, use\n        only the real part of the data."
  },
  {
    "code": "def set_year(self, year):\n        self.year = YEARS.get(year, year)\n        data = {'idCursus': self.year}\n        soup = self.post_soup('/~etudiant/login.php', data=data)\n        return bool(soup.select('ul.rMenu-hor'))",
    "docstring": "Set an user's year. This is required on magma just before the login.\n        It's called by default by ``login``."
  },
  {
    "code": "def transform_with(self, estimator, out_ds, fmt=None):\n        if isinstance(out_ds, str):\n            out_ds = self.create_derived(out_ds, fmt=fmt)\n        elif isinstance(out_ds, _BaseDataset):\n            err = \"Dataset must be opened in write mode.\"\n            assert out_ds.mode in ('w', 'a'), err\n        else:\n            err = \"Please specify a dataset path or an existing dataset.\"\n            raise ValueError(err)\n        for key in self.keys():\n            out_ds[key] = estimator.partial_transform(self[key])\n        return out_ds",
    "docstring": "Call the partial_transform method of the estimator on this dataset\n\n        Parameters\n        ----------\n        estimator : object with ``partial_fit`` method\n            This object will be used to transform this dataset into a new\n            dataset. The estimator should be fitted prior to calling\n            this method.\n        out_ds : str or Dataset\n            This dataset will be transformed and saved into out_ds. If\n            out_ds is a path, a new dataset will be created at that path.\n        fmt : str\n            The type of dataset to create if out_ds is a string.\n\n        Returns\n        -------\n        out_ds : Dataset\n            The tranformed dataset."
  },
  {
    "code": "def get_value(self, Meta: Type[object], base_classes_meta, mcs_args: McsArgs) -> Any:\n        value = self.default\n        if self.inherit and base_classes_meta is not None:\n            value = getattr(base_classes_meta, self.name, value)\n        if Meta is not None:\n            value = getattr(Meta, self.name, value)\n        return value",
    "docstring": "Returns the value for ``self.name`` given the class-under-construction's class\n        ``Meta``. If it's not found there, and ``self.inherit == True`` and there is a\n        base class that has a class ``Meta``, use that value, otherwise ``self.default``.\n\n        :param Meta: the class ``Meta`` (if any) from the class-under-construction\n                     (**NOTE:** this will be an ``object`` or ``None``, NOT an instance\n                     of :class:`MetaOptionsFactory`)\n        :param base_classes_meta: the :class:`MetaOptionsFactory` instance (if any) from\n                                  the base class of the class-under-construction\n        :param mcs_args: the :class:`McsArgs` for the class-under-construction"
  },
  {
    "code": "def atype_view_asset(self, ):\n        if not self.cur_atype:\n            return\n        i = self.atype_asset_treev.currentIndex()\n        item = i.internalPointer()\n        if item:\n            asset = item.internal_data()\n            if isinstance(asset, djadapter.models.Asset):\n                self.view_asset(asset)",
    "docstring": "View the project of the current assettype\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def sim_sedfile(self, **kwargs):\n        if 'seed' not in kwargs:\n            kwargs['seed'] = 'SEED'\n        return self._format_from_dict(NameFactory.sim_sedfile_format, **kwargs)",
    "docstring": "Return the name for the simulated SED file for a particular target"
  },
  {
    "code": "def _filter_by_m2m_schema(self, qs, lookup, sublookup, value, schema, model=None):\n        model = model or self.model\n        schemata = dict((s.name, s) for s in model.get_schemata_for_model())\n        try:\n            schema = schemata[lookup]\n        except KeyError:\n            raise ValueError(u'Could not find schema for lookup \"%s\"' % lookup)\n        sublookup = '__%s'%sublookup if sublookup else ''\n        return {\n            'attrs__schema': schema,\n            'attrs__choice%s'%sublookup: value,\n        }",
    "docstring": "Filters given entity queryset by an attribute which is linked to given\n        many-to-many schema."
  },
  {
    "code": "def _assemble_modification(stmt):\n    sub_str = _assemble_agent_str(stmt.sub)\n    if stmt.enz is not None:\n        enz_str = _assemble_agent_str(stmt.enz)\n        if _get_is_direct(stmt):\n            mod_str = ' ' + _mod_process_verb(stmt) + ' '\n        else:\n            mod_str = ' leads to the ' + _mod_process_noun(stmt) + ' of '\n        stmt_str = enz_str + mod_str + sub_str\n    else:\n        stmt_str = sub_str + ' is ' + _mod_state_stmt(stmt)\n    if stmt.residue is not None:\n        if stmt.position is None:\n            mod_str = 'on ' + ist.amino_acids[stmt.residue]['full_name']\n        else:\n            mod_str = 'on ' + stmt.residue + stmt.position\n    else:\n        mod_str = ''\n    stmt_str += ' ' + mod_str\n    return _make_sentence(stmt_str)",
    "docstring": "Assemble Modification statements into text."
  },
  {
    "code": "def _setup_model_loss(self, lr):\n        if not hasattr(self, \"loss\"):\n            self.loss = SoftCrossEntropyLoss()\n        if not hasattr(self, \"optimizer\"):\n            self.optimizer = optim.Adam(self.parameters(), lr=lr)",
    "docstring": "Setup loss and optimizer for PyTorch model."
  },
  {
    "code": "def smooth(self, n_iter=20, convergence=0.0, edge_angle=15, feature_angle=45,\n               boundary_smoothing=True, feature_smoothing=False, inplace=False):\n        alg = vtk.vtkSmoothPolyDataFilter()\n        alg.SetInputData(self)\n        alg.SetNumberOfIterations(n_iter)\n        alg.SetConvergence(convergence)\n        alg.SetFeatureEdgeSmoothing(feature_smoothing)\n        alg.SetFeatureAngle(feature_angle)\n        alg.SetEdgeAngle(edge_angle)\n        alg.SetBoundarySmoothing(boundary_smoothing)\n        alg.Update()\n        mesh = _get_output(alg)\n        if inplace:\n            self.overwrite(mesh)\n        else:\n            return mesh",
    "docstring": "Adjust point coordinates using Laplacian smoothing.\n        The effect is to \"relax\" the mesh, making the cells better shaped and\n        the vertices more evenly distributed.\n\n        Parameters\n        ----------\n        n_iter : int\n            Number of iterations for Laplacian smoothing,\n\n        convergence : float, optional\n            Convergence criterion for the iteration process. Smaller numbers\n            result in more smoothing iterations. Range from (0 to 1).\n\n        edge_angle : float, optional\n            Edge angle to control smoothing along edges (either interior or boundary).\n\n        feature_angle : float, optional\n            Feature angle for sharp edge identification.\n\n        boundary_smoothing : bool, optional\n            Boolean flag to control smoothing of boundary edges.\n\n        feature_smoothing : bool, optional\n            Boolean flag to control smoothing of feature edges.\n\n        inplace : bool, optional\n            Updates mesh in-place while returning nothing.\n\n        Returns\n        -------\n        mesh : vtki.PolyData\n            Decimated mesh. None when inplace=True."
  },
  {
    "code": "def list(self, filter_guid=None, filter_ids=None, detailed=None, page=None):\n        filters = [\n            'filter[guid]={0}'.format(filter_guid) if filter_guid else None,\n            'filter[ids]={0}'.format(','.join([str(app_id) for app_id in filter_ids])) if filter_ids else None,\n            'detailed={0}'.format(detailed) if detailed is not None else None,\n            'page={0}'.format(page) if page else None\n        ]\n        return self._get(\n            url='{0}plugins.json'.format(self.URL),\n            headers=self.headers,\n            params=self.build_param_string(filters)\n        )",
    "docstring": "This API endpoint returns a paginated list of the plugins associated\n        with your New Relic account.\n\n        Plugins can be filtered by their name or by a list of IDs.\n\n        :type filter_guid: str\n        :param filter_guid: Filter by name\n\n        :type filter_ids: list of ints\n        :param filter_ids: Filter by user ids\n\n        :type detailed: bool\n        :param detailed: Include all data about a plugin\n\n        :type page: int\n        :param page: Pagination index\n\n        :rtype: dict\n        :return: The JSON response of the API, with an additional 'pages' key\n            if there are paginated results\n\n        ::\n\n            {\n                \"plugins\": [\n                    {\n                        \"id\": \"integer\",\n                        \"name\": \"string\",\n                        \"guid\": \"string\",\n                        \"publisher\": \"string\",\n                        \"details\": {\n                            \"description\": \"integer\",\n                            \"is_public\": \"string\",\n                            \"created_at\": \"time\",\n                            \"updated_at\": \"time\",\n                            \"last_published_at\": \"time\",\n                            \"has_unpublished_changes\": \"boolean\",\n                            \"branding_image_url\": \"string\",\n                            \"upgraded_at\": \"time\",\n                            \"short_name\": \"string\",\n                            \"publisher_about_url\": \"string\",\n                            \"publisher_support_url\": \"string\",\n                            \"download_url\": \"string\",\n                            \"first_edited_at\": \"time\",\n                            \"last_edited_at\": \"time\",\n                            \"first_published_at\": \"time\",\n                            \"published_version\": \"string\"\n                        },\n                        \"summary_metrics\": [\n                            {\n                                \"id\": \"integer\",\n                                \"name\": \"string\",\n                                \"metric\": \"string\",\n                                \"value_function\": \"string\",\n                                \"thresholds\": {\n                                    \"caution\": \"float\",\n                                    \"critical\": \"float\"\n                                },\n                                \"values\": {\n                                    \"raw\": \"float\",\n                                    \"formatted\": \"string\"\n                                }\n                            }\n                        ]\n                    }\n                ],\n                \"pages\": {\n                    \"last\": {\n                        \"url\": \"https://api.newrelic.com/v2/plugins.json?page=2\",\n                        \"rel\": \"last\"\n                    },\n                    \"next\": {\n                        \"url\": \"https://api.newrelic.com/v2/plugins.json?page=2\",\n                        \"rel\": \"next\"\n                    }\n                }\n            }"
  },
  {
    "code": "def get_idp_sso_supported_bindings(idp_entity_id=None, config=None):\n    if config is None:\n        from djangosaml2.conf import get_config\n        config = get_config()\n    meta = getattr(config, 'metadata', {})\n    if idp_entity_id is None:\n        try:\n            idp_entity_id = list(available_idps(config).keys())[0]\n        except IndexError:\n            raise ImproperlyConfigured(\"No IdP configured!\")\n    try:\n        return meta.service(idp_entity_id, 'idpsso_descriptor', 'single_sign_on_service').keys()\n    except UnknownSystemEntity:\n        return []",
    "docstring": "Returns the list of bindings supported by an IDP\n    This is not clear in the pysaml2 code, so wrapping it in a util"
  },
  {
    "code": "def get_catalogue(self, locale):\n        if locale is None:\n            locale = self.locale\n        if locale not in self.catalogues or datetime.now() - self.last_reload > timedelta(seconds=1):\n            self._load_catalogue(locale)\n            self.last_reload = datetime.now()\n        return self.catalogues[locale]",
    "docstring": "Reloads messages catalogue if requested after more than one second\n        since last reload"
  },
  {
    "code": "def get_biased_correlations(data, threshold= 10):\n  data = data.toDense()\n  correlations = numpy.corrcoef(data, rowvar = False)\n  highest_correlations = []\n  for row in correlations:\n    highest_correlations += sorted(row, reverse = True)[1:threshold+1]\n  return numpy.mean(highest_correlations)",
    "docstring": "Gets the highest few correlations for each bit, across the entirety of the\n  data.  Meant to provide a comparison point for the pairwise correlations\n  reported in the literature, which are typically between neighboring neurons\n  tuned to the same inputs.  We would expect these neurons to be among the most\n  correlated in any region, so pairwise correlations between most likely do not\n  provide an unbiased estimator of correlations between arbitrary neurons."
  },
  {
    "code": "def score(\n        self,\n        data,\n        metric=\"accuracy\",\n        break_ties=\"random\",\n        verbose=True,\n        print_confusion_matrix=True,\n        **kwargs,\n    ):\n        Y_p, Y, Y_s = self._get_predictions(\n            data, break_ties=break_ties, return_probs=True, **kwargs\n        )\n        return_list = isinstance(metric, list)\n        metric_list = metric if isinstance(metric, list) else [metric]\n        scores = []\n        for metric in metric_list:\n            score = metric_score(Y, Y_p, metric, probs=Y_s, ignore_in_gold=[0])\n            scores.append(score)\n            if verbose:\n                print(f\"{metric.capitalize()}: {score:.3f}\")\n        if print_confusion_matrix and verbose:\n            confusion_matrix(Y, Y_p, pretty_print=True)\n        if len(scores) == 1 and not return_list:\n            return scores[0]\n        else:\n            return scores",
    "docstring": "Scores the predictive performance of the Classifier on all tasks\n\n        Args:\n            data: a Pytorch DataLoader, Dataset, or tuple with Tensors (X,Y):\n                X: The input for the predict method\n                Y: An [n] or [n, 1] torch.Tensor or np.ndarray of target labels\n                    in {1,...,k}\n            metric: A metric (string) with which to score performance or a\n                list of such metrics\n            break_ties: A tie-breaking policy (see Classifier._break_ties())\n            verbose: The verbosity for just this score method; it will not\n                update the class config.\n            print_confusion_matrix: Print confusion matrix (overwritten to False if\n                verbose=False)\n\n        Returns:\n            scores: A (float) score or a list of such scores if kwarg metric\n                is a list"
  },
  {
    "code": "def run(self, parameter_space, kernel_options, tuning_options):\n        logging.debug('sequential runner started for ' + kernel_options.kernel_name)\n        results = []\n        for element in parameter_space:\n            params = OrderedDict(zip(tuning_options.tune_params.keys(), element))\n            time = self.dev.compile_and_benchmark(self.gpu_args, params, kernel_options, tuning_options)\n            if time is None:\n                logging.debug('received time is None, kernel configuration was skipped silently due to compile or runtime failure')\n                continue\n            params['time'] = time\n            output_string = get_config_string(params, self.units)\n            logging.debug(output_string)\n            if not self.quiet:\n                print(output_string)\n            results.append(params)\n        return results, self.dev.get_environment()",
    "docstring": "Iterate through the entire parameter space using a single Python process\n\n        :param parameter_space: The parameter space as an iterable.\n        :type parameter_space: iterable\n\n        :param kernel_options: A dictionary with all options for the kernel.\n        :type kernel_options: kernel_tuner.interface.Options\n\n        :param tuning_options: A dictionary with all options regarding the tuning\n            process.\n        :type tuning_options: kernel_tuner.iterface.Options\n\n        :returns: A list of dictionaries for executed kernel configurations and their\n            execution times. And a dictionary that contains a information\n            about the hardware/software environment on which the tuning took place.\n        :rtype: list(dict()), dict()"
  },
  {
    "code": "def get_variable(name, temp_s):\n    return tf.Variable(tf.zeros(temp_s), name=name)",
    "docstring": "Get variable by name."
  },
  {
    "code": "def _OpenFilesForRead(self, metadata_value_pairs, token):\n    aff4_paths = [\n        result.AFF4Path(metadata.client_urn)\n        for metadata, result in metadata_value_pairs\n    ]\n    fds = aff4.FACTORY.MultiOpen(aff4_paths, mode=\"r\", token=token)\n    fds_dict = dict([(fd.urn, fd) for fd in fds])\n    return fds_dict",
    "docstring": "Open files all at once if necessary."
  },
  {
    "code": "def from_format(\n    string,\n    fmt,\n    tz=UTC,\n    locale=None,\n):\n    parts = _formatter.parse(string, fmt, now(), locale=locale)\n    if parts[\"tz\"] is None:\n        parts[\"tz\"] = tz\n    return datetime(**parts)",
    "docstring": "Creates a DateTime instance from a specific format."
  },
  {
    "code": "def update_links(self, request, admin_site=None):\n        if admin_site:\n            bundle = admin_site.get_bundle_for_model(self.model.to)\n            if bundle:\n                self._api_link = self._get_bundle_link(bundle, self.view,\n                                                       request.user)\n                self._add_link = self._get_bundle_link(bundle, self.add_view,\n                                                       request.user)",
    "docstring": "Called to update the widget's urls. Tries to find the\n        bundle for the model that this foreign key points to and then\n        asks it for the urls for adding and listing and sets them on\n        this widget instance. The urls are only set if request.user\n        has permissions on that url.\n\n        :param request: The request for which this widget is being rendered.\n        :param admin_site: If provided, the `admin_site` is used to lookup \\\n        the bundle that is registered as the primary url for the model \\\n        that this foreign key points to."
  },
  {
    "code": "def safe_import(self, name):\n        module = None\n        if name not in self._modules:\n            self._modules[name] = importlib.import_module(name)\n        module = self._modules[name]\n        if not module:\n            dist = next(iter(\n                dist for dist in self.base_working_set if dist.project_name == name\n            ), None)\n            if dist:\n                dist.activate()\n            module = importlib.import_module(name)\n        if name in sys.modules:\n            try:\n                six.moves.reload_module(module)\n                six.moves.reload_module(sys.modules[name])\n            except TypeError:\n                del sys.modules[name]\n                sys.modules[name] = self._modules[name]\n        return module",
    "docstring": "Helper utility for reimporting previously imported modules while inside the env"
  },
  {
    "code": "def fromimporterror(cls, bundle, importerid, rsid, exception, endpoint):\n        return RemoteServiceAdminEvent(\n            RemoteServiceAdminEvent.IMPORT_ERROR,\n            bundle,\n            importerid,\n            rsid,\n            None,\n            None,\n            exception,\n            endpoint,\n        )",
    "docstring": "Creates a RemoteServiceAdminEvent object from an import error"
  },
  {
    "code": "def _upload(self, files, voice_clip=False):\n        file_dict = {\"upload_{}\".format(i): f for i, f in enumerate(files)}\n        data = {\"voice_clip\": voice_clip}\n        j = self._postFile(\n            self.req_url.UPLOAD,\n            files=file_dict,\n            query=data,\n            fix_request=True,\n            as_json=True,\n        )\n        if len(j[\"payload\"][\"metadata\"]) != len(files):\n            raise FBchatException(\n                \"Some files could not be uploaded: {}, {}\".format(j, files)\n            )\n        return [\n            (data[mimetype_to_key(data[\"filetype\"])], data[\"filetype\"])\n            for data in j[\"payload\"][\"metadata\"]\n        ]",
    "docstring": "Uploads files to Facebook\n\n        `files` should be a list of files that requests can upload, see:\n        http://docs.python-requests.org/en/master/api/#requests.request\n\n        Returns a list of tuples with a file's ID and mimetype"
  },
  {
    "code": "def registration_update_or_create(self):\n        if not getattr(self, self.registration_unique_field):\n            raise UpdatesOrCreatesRegistrationModelError(\n                f'Cannot update or create RegisteredSubject. '\n                f'Field value for \\'{self.registration_unique_field}\\' is None.')\n        registration_value = getattr(self, self.registration_unique_field)\n        registration_value = self.to_string(registration_value)\n        try:\n            obj = self.registration_model.objects.get(\n                **{self.registered_subject_unique_field: registration_value})\n        except self.registration_model.DoesNotExist:\n            pass\n        else:\n            self.registration_raise_on_illegal_value_change(obj)\n        registered_subject, created = self.registration_model.objects.update_or_create(\n            **{self.registered_subject_unique_field: registration_value},\n            defaults=self.registration_options)\n        return registered_subject, created",
    "docstring": "Creates or Updates the registration model with attributes\n        from this instance.\n\n        Called from the signal"
  },
  {
    "code": "def flush(self):\n        for seq in self.buffer:\n            SeqIO.write(seq, self.handle, self.format)\n        self.buffer = []",
    "docstring": "Empty the buffer."
  },
  {
    "code": "def get_endpoint_by_endpoint_id(self, endpoint_id):\n        self._validate_uuid(endpoint_id)\n        url = \"/notification/v1/endpoint/{}\".format(endpoint_id)\n        response = NWS_DAO().getURL(url, self._read_headers)\n        if response.status != 200:\n            raise DataFailureException(url, response.status, response.data)\n        data = json.loads(response.data)\n        return self._endpoint_from_json(data.get(\"Endpoint\"))",
    "docstring": "Get an endpoint by endpoint id"
  },
  {
    "code": "def remove_collisions(self, min_dist=0.5):\n        s_f_coords = self.structure.frac_coords\n        f_coords = self.extrema_coords\n        if len(f_coords) == 0:\n            if self.extrema_type is None:\n                logger.warning(\n                    \"Please run ChargeDensityAnalyzer.get_local_extrema first!\")\n                return\n            new_f_coords = []\n            self._update_extrema(new_f_coords, self.extrema_type)\n            return new_f_coords\n        dist_matrix = self.structure.lattice.get_all_distances(f_coords,\n                                                               s_f_coords)\n        all_dist = np.min(dist_matrix, axis=1)\n        new_f_coords = []\n        for i, f in enumerate(f_coords):\n            if all_dist[i] > min_dist:\n                new_f_coords.append(f)\n        self._update_extrema(new_f_coords, self.extrema_type)\n        return new_f_coords",
    "docstring": "Remove predicted sites that are too close to existing atoms in the\n        structure.\n\n        Args:\n            min_dist (float): The minimum distance (in Angstrom) that\n                a predicted site needs to be from existing atoms. A min_dist\n                with value <= 0 returns all sites without distance checking."
  },
  {
    "code": "async def game(\n            self, short_name, *, id=None,\n            text=None, parse_mode=(), link_preview=True,\n            geo=None, period=60, contact=None, game=False, buttons=None\n    ):\n        result = types.InputBotInlineResultGame(\n            id=id or '',\n            short_name=short_name,\n            send_message=await self._message(\n                text=text, parse_mode=parse_mode, link_preview=link_preview,\n                geo=geo, period=period,\n                contact=contact,\n                game=game,\n                buttons=buttons\n            )\n        )\n        if id is None:\n            result.id = hashlib.sha256(bytes(result)).hexdigest()\n        return result",
    "docstring": "Creates a new inline result of game type.\n\n        Args:\n            short_name (`str`):\n                The short name of the game to use."
  },
  {
    "code": "def maybe_clean(self):\n        now = time.time()\n        if self.next_cleaning <= now:\n            keys_to_delete = []\n            for (k, v) in self.data.iteritems():\n                if v.expiration <= now:\n                    keys_to_delete.append(k)\n            for k in keys_to_delete:\n                del self.data[k]\n            now = time.time()\n            self.next_cleaning = now + self.cleaning_interval",
    "docstring": "Clean the cache if it's time to do so."
  },
  {
    "code": "def distribute(self,\n                   volume: float,\n                   source: Well,\n                   dest: List[Well],\n                   *args, **kwargs) -> 'InstrumentContext':\n        self._log.debug(\"Distributing {} from {} to {}\"\n                        .format(volume, source, dest))\n        kwargs['mode'] = 'distribute'\n        kwargs['disposal_volume'] = kwargs.get('disposal_vol', self.min_volume)\n        return self.transfer(volume, source, dest, **kwargs)",
    "docstring": "Move a volume of liquid from one source to multiple destinations.\n\n        :param volume: The amount of volume to distribute to each destination\n                       well.\n        :param source: A single well from where liquid will be aspirated.\n        :param dest: List of Wells where liquid will be dispensed to.\n        :param kwargs: See :py:meth:`transfer`.\n        :returns: This instance"
  },
  {
    "code": "def get_balance(self):\n        if not SMSGLOBAL_CHECK_BALANCE_COUNTRY:\n            raise Exception('SMSGLOBAL_CHECK_BALANCE_COUNTRY setting must be set to check balance.')\n        params = {\n          'user' : self.get_username(),\n          'password' : self.get_password(),\n          'country' : SMSGLOBAL_CHECK_BALANCE_COUNTRY,\n        }\n        req = urllib2.Request(SMSGLOBAL_API_URL_CHECKBALANCE, urllib.urlencode(params))\n        response = urllib2.urlopen(req).read()\n        if response.startswith('ERROR'):\n            raise Exception('Error retrieving balance: %s' % response.replace('ERROR:', ''))\n        return dict([(p.split(':')[0].lower(), p.split(':')[1]) for p in response.split(';') if len(p) > 0])",
    "docstring": "Get balance with provider."
  },
  {
    "code": "def extract(filepath, taxonomy, output_mode, output_limit,\n            spires, match_mode, detect_author_keywords, extract_acronyms,\n            rebuild_cache, only_core_tags, no_cache):\n    if not filepath or not taxonomy:\n        print(\"No PDF file or taxonomy given!\", file=sys.stderr)\n        sys.exit(0)\n    click.echo(\n        \">>> Going extract keywords from {0} as '{1}'...\".format(\n            filepath, output_mode\n        )\n    )\n    if not os.path.isfile(filepath):\n        click.echo(\n            \"Path to non-existing file\\n\",\n        )\n        sys.exit(1)\n    result = get_keywords_from_local_file(\n        local_file=filepath,\n        taxonomy_name=taxonomy,\n        output_mode=output_mode,\n        output_limit=output_limit,\n        spires=spires,\n        match_mode=match_mode,\n        no_cache=no_cache,\n        with_author_keywords=detect_author_keywords,\n        rebuild_cache=rebuild_cache,\n        only_core_tags=only_core_tags,\n        extract_acronyms=extract_acronyms\n    )\n    click.echo(result)",
    "docstring": "Run keyword extraction on given PDF file for given taxonomy."
  },
  {
    "code": "def array_prepend(path, *values, **kwargs):\n    return _gen_4spec(LCB_SDCMD_ARRAY_ADD_FIRST, path,\n                      MultiValue(*values),\n                      create_path=kwargs.pop('create_parents', False),\n                      **kwargs)",
    "docstring": "Add new values to the beginning of an array.\n\n    :param path: Path to the array. The path should contain the *array itself*\n        and not an element *within* the array\n    :param values: one or more values to append\n    :param create_parents: Create the array if it does not exist\n\n    This operation is only valid in :cb_bmeth:`mutate_in`.\n\n    .. seealso:: :func:`array_append`, :func:`upsert`"
  },
  {
    "code": "def ProcessHuntFlowLog(flow_obj, log_msg):\n  if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id):\n    return\n  hunt_urn = rdfvalue.RDFURN(\"hunts\").Add(flow_obj.parent_hunt_id)\n  flow_urn = hunt_urn.Add(flow_obj.flow_id)\n  log_entry = rdf_flows.FlowLog(\n      client_id=flow_obj.client_id,\n      urn=flow_urn,\n      flow_name=flow_obj.flow_class_name,\n      log_message=log_msg)\n  with data_store.DB.GetMutationPool() as pool:\n    grr_collections.LogCollection.StaticAdd(\n        hunt_urn.Add(\"Logs\"), log_entry, mutation_pool=pool)",
    "docstring": "Processes log message from a given hunt-induced flow."
  },
  {
    "code": "def finalize(self):\n        for name, count in sorted(self.blocks.items(), key=lambda x: x[1]):\n            print('{:3} {}'.format(count, name))\n        print('{:3} total'.format(sum(self.blocks.values())))",
    "docstring": "Output the aggregate block count results."
  },
  {
    "code": "def do_opt(self, *args, **kwargs):\n        args = list(args)\n        if not args:\n            largest = 0\n            keys = [key for key in self.conf if not key.startswith(\"_\")]\n            for key in keys:\n                largest = max(largest, len(key))\n            for key in keys:\n                print(\"%s : %s\" % (key.rjust(largest), self.conf[key]))\n            return\n        option = args.pop(0)\n        if not args and not kwargs:\n            method = getattr(self, \"getopt_\" + option, None)\n            if method is None:\n                self.getopt_default(option)\n            else:\n                method()\n        else:\n            method = getattr(self, \"opt_\" + option, None)\n            if method is None:\n                print(\"Unrecognized option %r\" % option)\n            else:\n                method(*args, **kwargs)\n                self.save_config()",
    "docstring": "Get and set options"
  },
  {
    "code": "def remove_span(self,span):\n        this_node = span.get_node()\n        self.node.remove(this_node)",
    "docstring": "Removes a specific span from the coref object"
  },
  {
    "code": "def ensemble_center(self, site_list, indices, cartesian=True):\n        if cartesian:\n            return np.average([site_list[i].coords for i in indices],\n                              axis=0)\n        else:\n            return np.average([site_list[i].frac_coords for i in indices],\n                              axis=0)",
    "docstring": "Finds the center of an ensemble of sites selected from\n        a list of sites.  Helper method for the find_adsorption_sites\n        algorithm.\n\n        Args:\n            site_list (list of sites): list of sites\n            indices (list of ints): list of ints from which to select\n                sites from site list\n            cartesian (bool): whether to get average fractional or\n                cartesian coordinate"
  },
  {
    "code": "def to_volume(self):\n        if hasattr(self.header.definitions, \"Lattice\"):\n            X, Y, Z = self.header.definitions.Lattice\n        else:\n            raise ValueError(\"Unable to determine data size\")\n        volume = self.decoded_data.reshape(Z, Y, X)\n        return volume",
    "docstring": "Return a 3D volume of the data"
  },
  {
    "code": "def dgeodr(x, y, z, re, f):\n    x = ctypes.c_double(x)\n    y = ctypes.c_double(y)\n    z = ctypes.c_double(z)\n    re = ctypes.c_double(re)\n    f = ctypes.c_double(f)\n    jacobi = stypes.emptyDoubleMatrix()\n    libspice.dgeodr_c(x, y, z, re, f, jacobi)\n    return stypes.cMatrixToNumpy(jacobi)",
    "docstring": "This routine computes the Jacobian of the transformation from\n    rectangular to geodetic coordinates.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dgeodr_c.html\n\n    :param x: X-coordinate of point.\n    :type x: float\n    :param y: Y-coordinate of point.\n    :type y: float\n    :param z: Z-coord\n    :type z: float\n    :param re: Equatorial radius of the reference spheroid.\n    :type re: float\n    :param f: Flattening coefficient.\n    :type f: float\n    :return: Matrix of partial derivatives.\n    :rtype: 3x3-Element Array of floats"
  },
  {
    "code": "def stop_func_accept_retry_state(stop_func):\n    if not six.callable(stop_func):\n        return stop_func\n    if func_takes_retry_state(stop_func):\n        return stop_func\n    @_utils.wraps(stop_func)\n    def wrapped_stop_func(retry_state):\n        warn_about_non_retry_state_deprecation(\n            'stop', stop_func, stacklevel=4)\n        return stop_func(\n            retry_state.attempt_number,\n            retry_state.seconds_since_start,\n        )\n    return wrapped_stop_func",
    "docstring": "Wrap \"stop\" function to accept \"retry_state\" parameter."
  },
  {
    "code": "def get_negative(self, cls=None, **kwargs):\n        for attr, set_of_values in kwargs.iteritems():\n            defaults = {key: kwargs[key][-1][\"default\"] for key in kwargs}\n            defaults.pop(attr)\n            for value in set_of_values[:-1]:\n                case = cls() if cls else self._CasesClass()\n                setattr(case, attr, value)\n                for key in defaults:\n                    setattr(case, key, defaults[key])\n                yield case",
    "docstring": "Returns a generator that generates negative cases by\n        \"each negative value in separate case\" algorithm."
  },
  {
    "code": "def get_todo_items(self, **kwargs):\n        def inner(self):\n            for item in self.get_all_as_list():\n                yield item\n            self._unlock()\n        if not self._is_locked():\n            if self._lock():\n                return inner(self)\n        raise RuntimeError(\"RuntimeError: Index Already Locked\")",
    "docstring": "Returns an iterator that will provide each item in the todo queue. Note that to complete each item you have to run complete method with the output of this iterator.\n\n        That will move the item to the done directory and prevent it from being retrieved in the future."
  },
  {
    "code": "def get_file_lines(self, subsystem, option):\n        assert subsystem in self\n        with open(os.path.join(self.per_subsystem[subsystem], subsystem + '.' + option)) as f:\n            for line in f:\n                yield line",
    "docstring": "Read the lines of the given file from the given subsystem.\n        Do not include the subsystem name in the option name.\n        Only call this method if the given subsystem is available."
  },
  {
    "code": "def demo(quiet, shell, speed, prompt, commentecho):\n    run(\n        DEMO,\n        shell=shell,\n        speed=speed,\n        test_mode=TESTING,\n        prompt_template=prompt,\n        quiet=quiet,\n        commentecho=commentecho,\n    )",
    "docstring": "Run a demo doitlive session."
  },
  {
    "code": "def delete_dcnm_in_nwk(self, tenant_id, fw_dict, is_fw_virt=False):\n        tenant_name = fw_dict.get('tenant_name')\n        ret = self._delete_service_nwk(tenant_id, tenant_name, 'in')\n        if ret:\n            res = fw_const.DCNM_IN_NETWORK_DEL_SUCCESS\n            LOG.info(\"In Service network deleted for tenant %s\",\n                     tenant_id)\n        else:\n            res = fw_const.DCNM_IN_NETWORK_DEL_FAIL\n            LOG.info(\"In Service network deleted failed for tenant %s\",\n                     tenant_id)\n        self.update_fw_db_result(tenant_id, dcnm_status=res)\n        return ret",
    "docstring": "Delete the DCNM In Network and store the result in DB."
  },
  {
    "code": "def write_config_file(self, params, path):\n        cfgp = ConfigParser()\n        cfgp.add_section(params['name'])\n        for p in params:\n            if p == 'name':\n                continue\n            cfgp.set(params['name'], p, params[p])\n        f = open(os.path.join(path, 'experiment.cfg'), 'w')\n        cfgp.write(f)\n        f.close()",
    "docstring": "write a config file for this single exp in the folder path."
  },
  {
    "code": "def error(self, msg):\n        body = msg['body'].replace(NULL, '')\n        brief_msg = \"\"\n        if 'message' in msg['headers']:\n            brief_msg = msg['headers']['message']\n        self.log.error(\"Received server error - message%s\\n\\n%s\" % (brief_msg, body))\n        returned = NO_RESPONSE_NEEDED\n        if self.testing:\n            returned = 'error'\n        return returned",
    "docstring": "Called to handle an error message received from the server.\n\n        This method just logs the error message\n\n        returned:\n            NO_RESPONSE_NEEDED"
  },
  {
    "code": "def get_new_version(self, last_version, last_commit,\n                        diff_to_increase_ratio):\n        version = Version(last_version)\n        diff = self.get_diff(last_commit, self.get_last_commit_hash())\n        total_changed = diff[Diff.ADD] + diff[Diff.DEL]\n        version.increase_by_changes(total_changed, diff_to_increase_ratio)\n        return version",
    "docstring": "Gets new version\n\n        :param last_version: last version known\n        :param last_commit: hash of commit of last version\n        :param diff_to_increase_ratio: Ratio to convert number of changes into\n        :return: new version"
  },
  {
    "code": "def get_input_files(self):\n    input_files = list(self.__input_files)\n    if isinstance(self.job(), CondorDAGJob):\n      input_files = input_files + self.job().get_input_files()\n    return input_files",
    "docstring": "Return list of input files for this DAG node and its job."
  },
  {
    "code": "def from_path(cls, path: pathlib.Path) -> 'File':\n        if not path.is_file():\n            raise ValueError('Path does not point to a file')\n        return File(path.name, path.stat().st_size, cls._md5(path))",
    "docstring": "Create a file entity from a file path.\n\n        :param path: The path of the file.\n        :return: A file entity instance representing the file.\n        :raises ValueError: If the path does not point to a file."
  },
  {
    "code": "def create_app(self, app_id, app, minimal=True):\n        app.id = app_id\n        data = app.to_json(minimal=minimal)\n        response = self._do_request('POST', '/v2/apps', data=data)\n        if response.status_code == 201:\n            return self._parse_response(response, MarathonApp)\n        else:\n            return False",
    "docstring": "Create and start an app.\n\n        :param str app_id: application ID\n        :param :class:`marathon.models.app.MarathonApp` app: the application to create\n        :param bool minimal: ignore nulls and empty collections\n\n        :returns: the created app (on success)\n        :rtype: :class:`marathon.models.app.MarathonApp` or False"
  },
  {
    "code": "def _iter_vals(key):\n    for i in range(winreg.QueryInfoKey(key)[1]):\n        yield winreg.EnumValue(key, i)",
    "docstring": "! Iterate over values of a key"
  },
  {
    "code": "async def stations(self):\n        data = await self.retrieve(API_DISTRITS)\n        Station = namedtuple('Station', ['latitude', 'longitude',\n                                         'idAreaAviso', 'idConselho',\n                                         'idDistrito', 'idRegiao',\n                                         'globalIdLocal', 'local'])\n        _stations = []\n        for station in data['data']:\n            _station = Station(\n                self._to_number(station['latitude']),\n                self._to_number(station['longitude']),\n                station['idAreaAviso'],\n                station['idConcelho'],\n                station['idDistrito'],\n                station['idRegiao'],\n                station['globalIdLocal']//100 * 100,\n                station['local'],\n                )\n            _stations.append(_station)\n        return _stations",
    "docstring": "Retrieve stations."
  },
  {
    "code": "def limit_range_for_scale(self, vmin, vmax, minpos):\n        vmin_bound = self._transform.transform_non_affine(0)\n        vmax_bound = self._transform.transform_non_affine(self._transform.M)\n        vmin = max(vmin, vmin_bound)\n        vmax = min(vmax, vmax_bound)\n        return vmin, vmax",
    "docstring": "Return minimum and maximum bounds for the logicle axis.\n\n        Parameters\n        ----------\n        vmin : float\n            Minimum data value.\n        vmax : float\n            Maximum data value.\n        minpos : float\n            Minimum positive value in the data. Ignored by this function.\n\n        Return\n        ------\n        float\n            Minimum axis bound.\n        float\n            Maximum axis bound."
  },
  {
    "code": "def populateMainMenu(self, parentMenu):\n        parentMenu.addAction(\"Configure\", self.configure)\n        parentMenu.addAction(\"Collect garbage\", self.__collectGarbage)",
    "docstring": "Populates the main menu.\n\n        The main menu looks as follows:\n        Plugins\n            - Plugin manager (fixed item)\n            - Separator (fixed item)\n            - <Plugin #1 name> (this is the parentMenu passed)\n            ...\n        If no items were populated by the plugin then there will be no\n        <Plugin #N name> menu item shown.\n        It is suggested to insert plugin configuration item here if so."
  },
  {
    "code": "def release(self, lock_transactions=None):\n        self.personal_lock.release()\n        self.with_count -= 1\n        if lock_transactions is None:\n            lock_transactions = self.lock_transactions\n        if not lock_transactions:\n            self.db_state.lock.release()\n            return\n        try:\n            in_transaction = self.in_transaction\n        except sqlite3.ProgrammingError:\n            in_transaction = False\n        if (self.was_in_transaction and not in_transaction) or not in_transaction:\n            if self.with_count == 0:\n                self.db_state.active_connection = None\n                self.db_state.transaction_lock.release()\n        self.db_state.lock.release()",
    "docstring": "Release the connection locks.\n\n            :param lock_transactions: `bool`, release the transaction lock\n                                      (`self.lock_transactions` is the default value)"
  },
  {
    "code": "def ida_connect(host='localhost', port=18861, retry=10):\n    for i in range(retry):\n        try:\n            LOG.debug('Connectint to %s:%d, try %d...', host, port, i + 1)\n            link = rpyc_classic.connect(host, port)\n            link.eval('2 + 2')\n        except socket.error:\n            time.sleep(1)\n            continue\n        else:\n            LOG.debug('Connected to %s:%d', host, port)\n            return link\n    raise IDALinkError(\"Could not connect to %s:%d after %d tries\" % (host, port, retry))",
    "docstring": "Connect to an instance of IDA running our server.py.\n\n    :param host:        The host to connect to\n    :param port:        The port to connect to\n    :param retry:       How many times to try after errors before giving up"
  },
  {
    "code": "def __create_rec(*args, **kwargs):\n        uid = args[0]\n        kind = args[1]\n        post_data = kwargs['post_data']\n        try:\n            TabWiki.create(\n                uid=uid,\n                title=post_data['title'].strip(),\n                date=datetime.datetime.now(),\n                cnt_html=tools.markdown2html(post_data['cnt_md']),\n                time_create=tools.timestamp(),\n                user_name=post_data['user_name'],\n                cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md']),\n                time_update=tools.timestamp(),\n                view_count=1,\n                kind=kind,\n            )\n            return True\n        except:\n            return False",
    "docstring": "Create the record."
  },
  {
    "code": "def _exit_handler(self):\n        if os.path.isfile(self.cleanup_file):\n            with open(self.cleanup_file, \"a\") as myfile:\n                myfile.write(\"rm \" + self.cleanup_file + \"\\n\")\n            os.chmod(self.cleanup_file, 0o755)\n        if not self._has_exit_status:\n            print(\"Pipeline status: {}\".format(self.status))\n            self.fail_pipeline(Exception(\"Pipeline failure. See details above.\"))\n        if self.tee:\n            self.tee.kill()",
    "docstring": "This function I register with atexit to run whenever the script is completing.\n        A catch-all for uncaught exceptions, setting status flag file to failed."
  },
  {
    "code": "def update_options(self) -> None:\n        options = hydpy.pub.options\n        for option in self.find('options'):\n            value = option.text\n            if value in ('true', 'false'):\n                value = value == 'true'\n            setattr(options, strip(option.tag), value)\n        options.printprogress = False\n        options.printincolor = False",
    "docstring": "Update the |Options| object available in module |pub| with the\n        values defined in the `options` XML element.\n\n        >>> from hydpy.auxs.xmltools import XMLInterface\n        >>> from hydpy import data, pub\n        >>> interface = XMLInterface('single_run.xml', data.get_path('LahnH'))\n        >>> pub.options.printprogress = True\n        >>> pub.options.printincolor = True\n        >>> pub.options.reprdigits = -1\n        >>> pub.options.utcoffset = -60\n        >>> pub.options.ellipsis = 0\n        >>> pub.options.warnsimulationstep = 0\n        >>> interface.update_options()\n        >>> pub.options\n        Options(\n            autocompile -> 1\n            checkseries -> 1\n            dirverbose -> 0\n            ellipsis -> 0\n            forcecompiling -> 0\n            printprogress -> 0\n            printincolor -> 0\n            reprcomments -> 0\n            reprdigits -> 6\n            skipdoctests -> 0\n            trimvariables -> 1\n            usecython -> 1\n            usedefaultvalues -> 0\n            utcoffset -> 60\n            warnmissingcontrolfile -> 0\n            warnmissingobsfile -> 1\n            warnmissingsimfile -> 1\n            warnsimulationstep -> 0\n            warntrim -> 1\n            flattennetcdf -> True\n            isolatenetcdf -> True\n            timeaxisnetcdf -> 0\n        )\n        >>> pub.options.printprogress = False\n        >>> pub.options.reprdigits = 6"
  },
  {
    "code": "def _get_agent_key(self, proxy=None):\n        if self._proxy is None:\n            self._proxy = proxy\n        if self._proxy is not None and self._proxy.has_effective_agent():\n            agent_key = self._proxy.get_effective_agent_id()\n        else:\n            agent_key = None\n        if agent_key not in self._provider_sessions:\n            self._provider_sessions[agent_key] = dict()\n        return agent_key",
    "docstring": "Gets an agent key for session management.\n\n        Side effect of setting a new proxy if one is sent along,\n        and initializing the provider session map if agent key has\n        not been seen before"
  },
  {
    "code": "def get_migrations(path):\n    pattern = re.compile(r\"\\d+_[\\w\\d]+\")\n    modules = [name for _, name, _ in pkgutil.iter_modules([path])\n                if pattern.match(name)\n            ]\n    return sorted(modules, key=lambda name: int(name.split(\"_\")[0]))",
    "docstring": "In the specified directory, get all the files which match the pattern\n    0001_migration.py"
  },
  {
    "code": "def private_props(obj):\n    props = [item for item in dir(obj)]\n    priv_props = [_PRIVATE_PROP_REGEXP.match(item) for item in props]\n    call_props = [callable(getattr(obj, item)) for item in props]\n    iobj = zip(props, priv_props, call_props)\n    for obj_name in [prop for prop, priv, call in iobj if priv and (not call)]:\n        yield obj_name",
    "docstring": "Yield private properties of an object.\n\n    A private property is defined as one that has a single underscore\n    (:code:`_`) before its name\n\n    :param obj: Object\n    :type  obj: object\n\n    :returns: iterator"
  },
  {
    "code": "def RdatabasesBM(host=rbiomart_host):\n    biomaRt = importr(\"biomaRt\")\n    print(biomaRt.listMarts(host=host))",
    "docstring": "Lists BioMart databases through a RPY2 connection.\n\n    :param host: address of the host server, default='www.ensembl.org'\n\n    :returns: nothing"
  },
  {
    "code": "def attention_lm_small():\n  hparams = attention_lm_base()\n  hparams.num_hidden_layers = 4\n  hparams.hidden_size = 512\n  hparams.filter_size = 2048\n  hparams.layer_prepostprocess_dropout = 0.5\n  return hparams",
    "docstring": "Cheap model.\n\n  on lm1b_32k:\n     45M params\n     2 steps/sec on  [GeForce GTX TITAN X]\n\n  Returns:\n    an hparams object."
  },
  {
    "code": "def _crop_default(x, size, row_pct:uniform=0.5, col_pct:uniform=0.5):\n    \"Crop `x` to `size` pixels. `row_pct`,`col_pct` select focal point of crop.\"\n    rows,cols = tis2hw(size)\n    row_pct,col_pct = _minus_epsilon(row_pct,col_pct)\n    row = int((x.size(1)-rows+1) * row_pct)\n    col = int((x.size(2)-cols+1) * col_pct)\n    return x[:, row:row+rows, col:col+cols].contiguous()",
    "docstring": "Crop `x` to `size` pixels. `row_pct`,`col_pct` select focal point of crop."
  },
  {
    "code": "def get_stop_times(feed: \"Feed\", date: Optional[str] = None) -> DataFrame:\n    f = feed.stop_times.copy()\n    if date is None:\n        return f\n    g = feed.get_trips(date)\n    return f[f[\"trip_id\"].isin(g[\"trip_id\"])]",
    "docstring": "Return a subset of ``feed.stop_times``.\n\n    Parameters\n    ----------\n    feed : Feed\n    date : string\n        YYYYMMDD date string restricting the output to trips active\n        on the date\n\n    Returns\n    -------\n    DataFrame\n        Subset of ``feed.stop_times``\n\n    Notes\n    -----\n    Assume the following feed attributes are not ``None``:\n\n    - ``feed.stop_times``\n    - Those used in :func:`.trips.get_trips`"
  },
  {
    "code": "def AddCampaign(self, client_customer_id, campaign_name, ad_channel_type,\n                  budget):\n    self.client.SetClientCustomerId(client_customer_id)\n    campaign_service = self.client.GetService('CampaignService')\n    budget_id = self.AddBudget(client_customer_id, budget)\n    operations = [{\n        'operator': 'ADD',\n        'operand': {\n            'name': campaign_name,\n            'status': 'PAUSED',\n            'biddingStrategyConfiguration': {\n                'biddingStrategyType': 'MANUAL_CPC',\n                'biddingScheme': {\n                    'xsi_type': 'ManualCpcBiddingScheme',\n                    'enhancedCpcEnabled': 'false'\n                }\n            },\n            'budget': {\n                'budgetId': budget_id\n            },\n            'advertisingChannelType': ad_channel_type\n        }\n    }]\n    campaign_service.mutate(operations)",
    "docstring": "Add a Campaign to the client account.\n\n    Args:\n      client_customer_id: str Client Customer Id to use when creating Campaign.\n      campaign_name: str Name of the campaign to be added.\n      ad_channel_type: str Primary serving target the campaign's ads.\n      budget: str a budget amount (in micros) to use."
  },
  {
    "code": "def visit_UnaryOperation(self, node):\n        if node.op.nature == Nature.PLUS:\n            return +self.visit(node.right)\n        elif node.op.nature == Nature.MINUS:\n            return -self.visit(node.right)\n        elif node.op.nature == Nature.NOT:\n            return Bool(not self.visit(node.right))",
    "docstring": "Visitor for `UnaryOperation` AST node."
  },
  {
    "code": "def fastq_to_csv(in_file, fastq_format, work_dir):\n    out_file = \"%s.csv\" % (os.path.splitext(os.path.basename(in_file))[0])\n    out_file = os.path.join(work_dir, out_file)\n    if not (os.path.exists(out_file) and os.path.getsize(out_file) > 0):\n        with open(in_file) as in_handle:\n            with open(out_file, \"w\") as out_handle:\n                writer = csv.writer(out_handle)\n                for rec in SeqIO.parse(in_handle, fastq_format):\n                    writer.writerow([rec.id] + rec.letter_annotations[\"phred_quality\"])\n    return out_file",
    "docstring": "Convert a fastq file into a CSV of phred quality scores."
  },
  {
    "code": "def create_readable_dir(entry, section, domain, output):\n    if domain != 'viral':\n        full_output_dir = os.path.join(output, 'human_readable', section, domain,\n                                       get_genus_label(entry),\n                                       get_species_label(entry),\n                                       get_strain_label(entry))\n    else:\n        full_output_dir = os.path.join(output, 'human_readable', section, domain,\n                                       entry['organism_name'].replace(' ', '_'),\n                                       get_strain_label(entry, viral=True))\n    try:\n        os.makedirs(full_output_dir)\n    except OSError as err:\n        if err.errno == errno.EEXIST and os.path.isdir(full_output_dir):\n            pass\n        else:\n            raise\n    return full_output_dir",
    "docstring": "Create the a human-readable directory to link the entry to if needed."
  },
  {
    "code": "def _set_es_workers(self, **kwargs):\n        def make_es_worker(search_conn, es_index, es_doc_type, class_name):\n            new_esbase = copy.copy(search_conn)\n            new_esbase.es_index = es_index\n            new_esbase.doc_type = es_doc_type\n            log.info(\"Indexing '%s' into ES index '%s' doctype '%s'\",\n                     class_name.pyuri,\n                     es_index,\n                     es_doc_type)\n            return new_esbase\n        def additional_indexers(rdf_class):\n            rtn_list = rdf_class.es_indexers()\n            rtn_list.remove(rdf_class)\n            return rtn_list\n        self.es_worker = make_es_worker(self.search_conn,\n                                        self.es_index,\n                                        self.es_doc_type,\n                                        self.rdf_class.__name__)\n        if not kwargs.get(\"idx_only_base\"):\n            self.other_indexers = {item.__name__: make_es_worker(\n                        self.search_conn,\n                        item.es_defs.get('kds_esIndex')[0],\n                        item.es_defs.get('kds_esDocType')[0],\n                        item.__name__)\n                    for item in additional_indexers(self.rdf_class)}\n        else:\n            self.other_indexers = {}",
    "docstring": "Creates index worker instances for each class to index\n\n        kwargs:\n        -------\n            idx_only_base[bool]: True will only index the base class"
  },
  {
    "code": "def deletefile(self, project_id, file_path, branch_name, commit_message):\n        data = {\n            'file_path': file_path,\n            'branch_name': branch_name,\n            'commit_message': commit_message\n        }\n        request = requests.delete(\n            '{0}/{1}/repository/files'.format(self.projects_url, project_id),\n            headers=self.headers, data=data, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)\n        return request.status_code == 200",
    "docstring": "Deletes existing file in the repository\n\n        :param project_id: project id\n        :param file_path: Full path to new file. Ex. lib/class.rb\n        :param branch_name: The name of branch\n        :param commit_message: Commit message\n        :return: true if success, false if not"
  },
  {
    "code": "def list_collections(self, session=None, filter=None, **kwargs):\n        if filter is not None:\n            kwargs['filter'] = filter\n        read_pref = ((session and session._txn_read_preference())\n                     or ReadPreference.PRIMARY)\n        def _cmd(session, server, sock_info, slave_okay):\n            return self._list_collections(\n                sock_info, slave_okay, session, read_preference=read_pref,\n                **kwargs)\n        return self.__client._retryable_read(\n            _cmd, read_pref, session)",
    "docstring": "Get a cursor over the collectons of this database.\n\n        :Parameters:\n          - `session` (optional): a\n            :class:`~pymongo.client_session.ClientSession`.\n          - `filter` (optional):  A query document to filter the list of\n            collections returned from the listCollections command.\n          - `**kwargs` (optional): Optional parameters of the\n            `listCollections command\n            <https://docs.mongodb.com/manual/reference/command/listCollections/>`_\n            can be passed as keyword arguments to this method. The supported\n            options differ by server version.\n\n        :Returns:\n          An instance of :class:`~pymongo.command_cursor.CommandCursor`.\n\n        .. versionadded:: 3.6"
  },
  {
    "code": "def _pseudoinverse(self, A, tol=1.0e-10):\n        return np.linalg.pinv(A, rcond=tol)",
    "docstring": "Compute the Moore-Penrose pseudoinverse, wraps np.linalg.pinv\n\n        REQUIRED ARGUMENTS\n          A (np KxK matrix) - the square matrix whose pseudoinverse is to be computed\n\n        RETURN VALUES\n          Ainv (np KxK matrix) - the pseudoinverse\n\n        OPTIONAL VALUES\n          tol - the tolerance (relative to largest magnitude singlular value) below which singular values are to not be include in forming pseudoinverse (default: 1.0e-10)\n\n        NOTES\n          In previous versions of pymbar / Numpy, we wrote our own pseudoinverse\n          because of a bug in Numpy."
  },
  {
    "code": "def softmax_cross_entropy_with_logits(sentinel=None,\n                                      labels=None,\n                                      logits=None,\n                                      dim=-1):\n  if sentinel is not None:\n    name = \"softmax_cross_entropy_with_logits\"\n    raise ValueError(\"Only call `%s` with \"\n                     \"named arguments (labels=..., logits=..., ...)\"\n                     % name)\n  if labels is None or logits is None:\n    raise ValueError(\"Both labels and logits must be provided.\")\n  try:\n    f = tf.nn.softmax_cross_entropy_with_logits_v2\n  except AttributeError:\n    raise RuntimeError(\"This version of TensorFlow is no longer supported. See cleverhans/README.md\")\n  labels = tf.stop_gradient(labels)\n  loss = f(labels=labels, logits=logits, dim=dim)\n  return loss",
    "docstring": "Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle\n  deprecated warning"
  },
  {
    "code": "def index(request, template_name='staffmembers/index.html'):\n    return render_to_response(template_name,\n                              {'staff': StaffMember.objects.active()},\n                              context_instance=RequestContext(request))",
    "docstring": "The list of employees or staff members"
  },
  {
    "code": "def file_sign( blockchain_id, hostname, input_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ):\n    config_dir = os.path.dirname(config_path)\n    key_info = file_key_lookup( blockchain_id, 0, hostname, config_path=config_path, wallet_keys=wallet_keys )\n    if 'error' in key_info:\n        return {'error': 'Failed to lookup encryption key'}\n    res = blockstack_gpg.gpg_sign( input_path, key_info, config_dir=config_dir )\n    if 'error' in res:\n        log.error(\"Failed to encrypt: %s\" % res['error'])\n        return {'error': 'Failed to encrypt'}\n    return {'status': True, 'sender_key_id': key_info['key_id'], 'sig': res['sig']}",
    "docstring": "Sign a file with the current blockchain ID's host's public key.\n    @config_path should be for the *client*, not blockstack-file\n    Return {'status': True, 'sender_key_id': ..., 'sig': ...} on success, and write ciphertext to output_path\n    Return {'error': ...} on error"
  },
  {
    "code": "def to_weld_vec(weld_type, ndim):\n    for i in range(ndim):\n        weld_type = WeldVec(weld_type)\n    return weld_type",
    "docstring": "Convert multi-dimensional data to WeldVec types.\n\n    Parameters\n    ----------\n    weld_type : WeldType\n        WeldType of data.\n    ndim : int\n        Number of dimensions.\n\n    Returns\n    -------\n    WeldVec\n        WeldVec of 1 or more dimensions."
  },
  {
    "code": "def download(request):\n    f = FileUpload()\n    f.title = request.GET['title'] or 'untitled'\n    f.description = request.GET['description']\n    url = urllib.unquote(request.GET['photo'])\n    file_content = urllib.urlopen(url).read()\n    file_name = url.split('/')[-1]\n    f.save_upload_file(file_name, file_content)\n    f.save()\n    return HttpResponse('%s' % (f.id))",
    "docstring": "Saves image from URL and returns ID for use with AJAX script"
  },
  {
    "code": "def load_factor(ts, resolution=None, norm=None):\n    if norm is None:\n        norm = ts.max()\n    if resolution is not None:\n        ts = ts.resample(rule=resolution).mean()\n    lf = ts / norm\n    return lf",
    "docstring": "Calculate the ratio of input vs. norm over a given interval.\n\n    Parameters\n    ----------\n    ts : pandas.Series\n        timeseries\n    resolution : str, optional\n        interval over which to calculate the ratio\n        default: resolution of the input timeseries\n    norm : int | float, optional\n        denominator of the ratio\n        default: the maximum of the input timeseries\n\n    Returns\n    -------\n    pandas.Series"
  },
  {
    "code": "def _sort(self):\n        self.__dict__['_z_ordered_sprites'] = sorted(self.sprites, key=lambda sprite:sprite.z_order)",
    "docstring": "sort sprites by z_order"
  },
  {
    "code": "async def pause(self):\n        self.logger.debug(\"pause command\")\n        if not self.state == 'ready':\n            return\n        if self.streamer is None:\n            return\n        try:\n            if self.streamer.is_playing():\n                self.streamer.pause()\n                self.pause_time = self.vclient.loop.time()\n                self.statuslog.info(\"Paused\")\n        except Exception as e:\n            logger.error(e)\n            pass",
    "docstring": "Pauses playback if playing"
  },
  {
    "code": "def toggle_item(self, item, test_func, field_name=None):\n        if test_func(item):\n            self.add_item(item, field_name)\n            return True\n        else:\n            self.remove_item(item, field_name)\n            return False",
    "docstring": "Toggles the section based on test_func.\n\n        test_func takes an item and returns a boolean. If it returns True, the\n        item will be added to the given section. It will be removed from the\n        section otherwise.\n\n        Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL.\n        Behavior on other items is undefined."
  },
  {
    "code": "def files(xscript=0, yscript=1, eyscript=None, exscript=None, g=None, plotter=xy_databoxes, paths=None, **kwargs):\n    if 'delimiter' in kwargs: delimiter = kwargs.pop('delimiter')\n    else:                           delimiter = None\n    if 'filters' in kwargs: filters = kwargs.pop('filters')\n    else:                         filters = '*.*'\n    ds = _data.load_multiple(paths=paths, delimiter=delimiter, filters=filters)\n    if ds is None or len(ds) == 0: return\n    if 'title' not in kwargs: kwargs['title']=_os.path.split(ds[0].path)[0]\n    plotter(ds, xscript=xscript, yscript=yscript, eyscript=eyscript, exscript=exscript, g=g, **kwargs)\n    return ds",
    "docstring": "This will load a bunch of data files, generate data based on the supplied\n    scripts, and then plot this data using the specified databox plotter.\n\n    xscript, yscript, eyscript, exscript    scripts to generate x, y, and errors\n    g                                       optional dictionary of globals\n\n    optional: filters=\"*.*\" to set the file filters for the dialog.\n\n    **kwargs are sent to plotter()"
  },
  {
    "code": "def ensure_object_is_ordered_dict(item, title):\n    assert isinstance(title, str)\n    if not isinstance(item, OrderedDict):\n        msg = \"{} must be an OrderedDict. {} passed instead.\"\n        raise TypeError(msg.format(title, type(item)))\n    return None",
    "docstring": "Checks that the item is an OrderedDict. If not, raises ValueError."
  },
  {
    "code": "def parse_mapreduce_yaml(contents):\n  try:\n    builder = yaml_object.ObjectBuilder(MapReduceYaml)\n    handler = yaml_builder.BuilderHandler(builder)\n    listener = yaml_listener.EventListener(handler)\n    listener.Parse(contents)\n    mr_info = handler.GetResults()\n  except (ValueError, yaml_errors.EventError), e:\n    raise errors.BadYamlError(e)\n  if len(mr_info) < 1:\n    raise errors.BadYamlError(\"No configs found in mapreduce.yaml\")\n  if len(mr_info) > 1:\n    raise errors.MultipleDocumentsInMrYaml(\"Found %d YAML documents\" %\n                                           len(mr_info))\n  jobs = mr_info[0]\n  job_names = set(j.name for j in jobs.mapreduce)\n  if len(jobs.mapreduce) != len(job_names):\n    raise errors.BadYamlError(\n        \"Overlapping mapreduce names; names must be unique\")\n  return jobs",
    "docstring": "Parses mapreduce.yaml file contents.\n\n  Args:\n    contents: mapreduce.yaml file contents.\n\n  Returns:\n    MapReduceYaml object with all the data from original file.\n\n  Raises:\n    errors.BadYamlError: when contents is not a valid mapreduce.yaml file."
  },
  {
    "code": "def enable_notifications(self, enabled=True):\n        try:\n            if enabled:\n                self._object.StartNotify(\n                    reply_handler=self._enable_notifications_succeeded,\n                    error_handler=self._enable_notifications_failed,\n                    dbus_interface='org.bluez.GattCharacteristic1')\n            else:\n                self._object.StopNotify(\n                    reply_handler=self._enable_notifications_succeeded,\n                    error_handler=self._enable_notifications_failed,\n                    dbus_interface='org.bluez.GattCharacteristic1')\n        except dbus.exceptions.DBusException as e:\n            self._enable_notifications_failed(error=e)",
    "docstring": "Enables or disables value change notifications.\n\n        Success or failure will be notified by calls to `characteristic_enable_notifications_succeeded`\n        or `enable_notifications_failed` respectively.\n\n        Each time when the device notifies a new value, `characteristic_value_updated()` of the related\n        device will be called."
  },
  {
    "code": "def createlabel(self, project_id, name, color):\n        data = {'name': name, 'color': color}\n        request = requests.post(\n            '{0}/{1}/labels'.format(self.projects_url, project_id), data=data,\n            verify=self.verify_ssl, auth=self.auth, headers=self.headers, timeout=self.timeout)\n        if request.status_code == 201:\n            return request.json()\n        else:\n            return False",
    "docstring": "Creates a new label for given repository with given name and color.\n\n        :param project_id: The ID of a project\n        :param name: The name of the label\n        :param color: Color of the label given in 6-digit hex notation with leading '#' sign (e.g. #FFAABB)\n        :return:"
  },
  {
    "code": "def multiplot(self, f, lfilter=None, **kargs):\n        d = defaultdict(list)\n        for i in self.res:\n            if lfilter and not lfilter(i):\n                continue \n            k, v = f(i)\n            d[k].append(v)\n        figure = plt.figure()\n        ax = figure.add_axes(plt.axes())\n        for i in d:\n            ax.plot(d[i], **kargs)\n        return figure",
    "docstring": "Uses a function that returns a label and a value for this label, then plots all the values label by label"
  },
  {
    "code": "def clean_prefix(self):\n        user = self.context.guild.me if self.context.guild else self.context.bot.user\n        return self.context.prefix.replace(user.mention, '@' + user.display_name)",
    "docstring": "The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``."
  },
  {
    "code": "def spammer_view(request):\n    context = RequestContext(request, {})\n    template = Template(\"\")\n    response = HttpResponse(template.render(context))\n    response.set_cookie(COOKIE_KEY, value=COOKIE_SPAM, httponly=True,\n                        expires=datetime.now()+timedelta(days=3650))\n    if DJANGOSPAM_LOG:\n        log(\"BLOCK RESPONSE\", request.method, request.path_info,\n            request.META.get(\"HTTP_USER_AGENT\", \"undefined\"))\n    return response",
    "docstring": "View for setting cookies on spammers."
  },
  {
    "code": "def findhight(data, ignoret=None, threshold=20):\n    time = np.sort(data['time'])\n    ww = np.ones(len(time), dtype=bool)\n    if ignoret:\n        for (t0, t1) in ignoret:\n            ww = ww & np.where( (time < t0) | (time > t1), True, False )\n    bins = np.round(time[ww]).astype('int')\n    counts = np.bincount(bins)\n    high = np.where(counts > np.median(counts) + threshold*counts.std())[0]\n    return high, counts[high]",
    "docstring": "Find bad time ranges from distribution of candidates.\n\n    ignoret is list of tuples [(t0, t1), (t2, t3)] defining ranges to ignore.\n    threshold is made above std of candidate distribution in time.\n    Returns the time (in seconds) and counts for bins above threshold."
  },
  {
    "code": "def get_advanced_search_form(self, data):\n        if self.get_advanced_search_form_class():\n            self._advanced_search_form = self.get_advanced_search_form_class()(\n                data=data\n            )\n            return self._advanced_search_form",
    "docstring": "Hook to dynamically change the advanced search form"
  },
  {
    "code": "def make_parent_bands(self, band, child_bands):\n        m = re.match(r'([pq][A-H\\d]+(?:\\.\\d+)?)', band)\n        if len(band) > 0:\n            if m:\n                p = str(band[0:len(band)-1])\n                p = re.sub(r'\\.$', '', p)\n                if p is not None:\n                    child_bands.add(p)\n                    self.make_parent_bands(p, child_bands)\n        else:\n            child_bands = set()\n        return child_bands",
    "docstring": "this will determine the grouping bands that it belongs to, recursively\n        13q21.31 ==>  13, 13q, 13q2, 13q21, 13q21.3, 13q21.31\n\n        :param band:\n        :param child_bands:\n        :return:"
  },
  {
    "code": "def ping(self):\n        url = self._build_url('pings', base_url=self._api)\n        return self._boolean(self._post(url), 204, 404)",
    "docstring": "Ping this hook.\n\n        :returns: bool"
  },
  {
    "code": "def run_marionette_script(script, chrome=False, async=False, host='localhost', port=2828):\n    m = DeviceHelper.getMarionette(host, port)\n    m.start_session()\n    if chrome:\n        m.set_context(marionette.Marionette.CONTEXT_CHROME)\n    if not async:\n        result = m.execute_script(script)\n    else:\n        result = m.execute_async_script(script)\n    m.delete_session()\n    return result",
    "docstring": "Create a Marionette instance and run the provided script"
  },
  {
    "code": "def _schema_to_json_file_object(self, schema_list, file_obj):\n        json.dump(schema_list, file_obj, indent=2, sort_keys=True)",
    "docstring": "Helper function for schema_to_json that takes a schema list and file\n        object and writes the schema list to the file object with json.dump"
  },
  {
    "code": "def iosequence(seq):\n        lines = Lines()\n        lines.add(1, 'cdef public bint _%s_diskflag' % seq.name)\n        lines.add(1, 'cdef public str _%s_path' % seq.name)\n        lines.add(1, 'cdef FILE *_%s_file' % seq.name)\n        lines.add(1, 'cdef public bint _%s_ramflag' % seq.name)\n        ctype = 'double' + NDIM2STR[seq.NDIM+1]\n        lines.add(1, 'cdef public %s _%s_array' % (ctype, seq.name))\n        return lines",
    "docstring": "Special declaration lines for the given |IOSequence| object."
  },
  {
    "code": "def stop(cls):\n        if any(cls.streams):\n            sys.stdout = cls.streams.pop(-1)\n        else:\n            sys.stdout = sys.__stdout__",
    "docstring": "Change back the normal stdout after the end"
  },
  {
    "code": "def shutdown(self):\n        try:\n            while True:\n                self._executor._work_queue.get(block=False)\n        except queue.Empty:\n            pass\n        self._executor.shutdown()",
    "docstring": "Shuts down the scheduler and immediately end all pending callbacks."
  },
  {
    "code": "def from_map(map_key):\n    'use resolved map as image'\n    image_id = subprocess.check_output(['plash', 'map',\n                                        map_key]).decode().strip('\\n')\n    if not image_id:\n        raise MapDoesNotExist('map {} not found'.format(repr(map_key)))\n    return hint('image', image_id)",
    "docstring": "use resolved map as image"
  },
  {
    "code": "def set_root_logger(root_log_level, log_path=None):\n    handlers = []\n    console_handler = logging.StreamHandler()\n    handlers.append(console_handler)\n    if log_path:\n        file_handler = logging.FileHandler(log_path)\n        handlers.append(file_handler)\n    set_logging_config(root_log_level, handlers=handlers)\n    root_logger = logging.getLogger(\"pypyr\")\n    root_logger.debug(\n        f\"Root logger {root_logger.name} configured with level \"\n        f\"{root_log_level}\")",
    "docstring": "Set the root logger 'pypyr'. Do this before you do anything else.\n\n    Run once and only once at initialization."
  },
  {
    "code": "def __clean_rouge_args(self, rouge_args):\n        if not rouge_args:\n            return\n        quot_mark_pattern = re.compile('\"(.+)\"')\n        match = quot_mark_pattern.match(rouge_args)\n        if match:\n            cleaned_args = match.group(1)\n            return cleaned_args\n        else:\n            return rouge_args",
    "docstring": "Remove enclosing quotation marks, if any."
  },
  {
    "code": "def pop_density(data: CityInfo) -> str:\n    if not isinstance(data, CityInfo):\n        raise AttributeError(\"Argument to pop_density() must be an instance of CityInfo\")\n    return no_dec(data.get_population() / data.get_area())",
    "docstring": "Calculate the population density from the data entry"
  },
  {
    "code": "def parse_changelog(args: Any) -> Tuple[str, str]:\n    with open(\"CHANGELOG.rst\", \"r\") as file:\n        match = re.match(\n            pattern=r\"(.*?Unreleased\\n---+\\n)(.+?)(\\n*[^\\n]+\\n---+\\n.*)\",\n            string=file.read(),\n            flags=re.DOTALL,\n        )\n    assert match\n    header, changes, tail = match.groups()\n    tag = \"%s - %s\" % (args.tag, datetime.date.today().isoformat())\n    tagged = \"\\n%s\\n%s\\n%s\" % (tag, \"-\" * len(tag), changes)\n    if args.verbose:\n        print(tagged)\n    return \"\".join((header, tagged, tail)), changes",
    "docstring": "Return an updated changelog and and the list of changes."
  },
  {
    "code": "def resistance_distance(G):\n    r\n    if sparse.issparse(G):\n        L = G.tocsc()\n    else:\n        if G.lap_type != 'combinatorial':\n            raise ValueError('Need a combinatorial Laplacian.')\n        L = G.L.tocsc()\n    try:\n        pseudo = sparse.linalg.inv(L)\n    except RuntimeError:\n        pseudo = sparse.lil_matrix(np.linalg.pinv(L.toarray()))\n    N = np.shape(L)[0]\n    d = sparse.csc_matrix(pseudo.diagonal())\n    rd = sparse.kron(d, sparse.csc_matrix(np.ones((N, 1)))).T \\\n        + sparse.kron(d, sparse.csc_matrix(np.ones((N, 1)))) \\\n        - pseudo - pseudo.T\n    return rd",
    "docstring": "r\"\"\"\n    Compute the resistance distances of a graph.\n\n    Parameters\n    ----------\n    G : Graph or sparse matrix\n        Graph structure or Laplacian matrix (L)\n\n    Returns\n    -------\n    rd : sparse matrix\n        distance matrix\n\n    References\n    ----------\n    :cite:`klein1993resistance`"
  },
  {
    "code": "def draw(self, **kwargs):\n        ax = mp.gca()\n        shape = matplotlib.patches.Polygon(self.polygon, **kwargs)\n        ax.add_artist(shape)",
    "docstring": "Draw the polygon\n\n        Optional Inputs:\n        ------------\n        All optional inputs are passed to ``matplotlib.patches.Polygon``\n\n        Notes:\n        ---------\n        Does not accept maptype as an argument."
  },
  {
    "code": "def paren_split(sep,string):\n    if len(sep) != 1: raise Exception(\"Separation string must be one character long\")\n    retlist = []\n    level = 0\n    blevel = 0\n    left = 0\n    for i in range(len(string)):\n        if string[i] == \"(\": level += 1\n        elif string[i] == \")\": level -= 1\n        elif string[i] == \"[\": blevel += 1\n        elif string[i] == \"]\": blevel -= 1\n        elif string[i] == sep and level == 0 and blevel == 0:\n            retlist.append(string[left:i])\n            left = i+1\n    retlist.append(string[left:])\n    return retlist",
    "docstring": "Splits the string into pieces divided by sep, when sep is outside of parentheses."
  },
  {
    "code": "def top(self, body_output, features):\n    if isinstance(body_output, dict):\n      logits = {}\n      for k, v in six.iteritems(body_output):\n        with tf.variable_scope(k) as top_vs:\n          self._add_variable_scope(\"top_%s\" % k, top_vs)\n          logits[k] = self._top_single(v, k, features)\n      return logits\n    else:\n      return self._top_single(body_output, \"targets\", features)",
    "docstring": "Computes logits given body output and features.\n\n    Args:\n      body_output: dict of str to Tensor, comprising one key-value pair for each\n        target. Each value denotes the target's pre-logit activations.\n        Alternatively, it may be a single Tensor denoting the pre-logits for\n        that target.\n      features: dict of str to Tensor. Typically it is the preprocessed data\n        batch after Problem's preprocess_example().\n\n    Returns:\n      logits: dict of str to Tensor, denoting each logits for each target; or\n        a single Tensor denoting the logits for that target.\n        When targets are generated at training time:\n          logits == {\n            \"self_generated_targets\": <generated targets tensor>\n            \"logits\": <original logits Tensor or dict>\n          }"
  },
  {
    "code": "def hierarchical(keys):\n    ndims = len(keys[0])\n    if ndims <= 1:\n        return True\n    dim_vals = list(zip(*keys))\n    combinations = (zip(*dim_vals[i:i+2])\n                    for i in range(ndims-1))\n    hierarchies = []\n    for combination in combinations:\n        hierarchy = True\n        store1 = defaultdict(list)\n        store2 = defaultdict(list)\n        for v1, v2 in combination:\n            if v2 not in store2[v1]:\n                store2[v1].append(v2)\n            previous = store1[v2]\n            if previous and previous[0] != v1:\n                hierarchy = False\n                break\n            if v1 not in store1[v2]:\n                store1[v2].append(v1)\n        hierarchies.append(store2 if hierarchy else {})\n    return hierarchies",
    "docstring": "Iterates over dimension values in keys, taking two sets\n    of dimension values at a time to determine whether two\n    consecutive dimensions have a one-to-many relationship.\n    If they do a mapping between the first and second dimension\n    values is returned. Returns a list of n-1 mappings, between\n    consecutive dimensions."
  },
  {
    "code": "def get_not_unique_values(array):\n    s = np.sort(array, axis=None)\n    s = s[s[1:] == s[:-1]]\n    return np.unique(s)",
    "docstring": "Returns the values that appear at least twice in array.\n\n    Parameters\n    ----------\n    array : array like\n\n    Returns\n    -------\n    numpy.array"
  },
  {
    "code": "def reset_headers(self):\r\n        rows = self.rowCount()\r\n        cols = self.columnCount()\r\n        for r in range(rows):\r\n            self.setVerticalHeaderItem(r, QTableWidgetItem(str(r)))\r\n        for c in range(cols):\r\n            self.setHorizontalHeaderItem(c, QTableWidgetItem(str(c)))\r\n            self.setColumnWidth(c, 40)",
    "docstring": "Update the column and row numbering in the headers."
  },
  {
    "code": "def get_form_type(self):\n        for field in self.fields:\n            if field.var == \"FORM_TYPE\" and field.type_ == FieldType.HIDDEN:\n                if len(field.values) != 1:\n                    return None\n                return field.values[0]",
    "docstring": "Extract the ``FORM_TYPE`` from the fields.\n\n        :return: ``FORM_TYPE`` value or :data:`None`\n        :rtype: :class:`str` or :data:`None`\n\n        Return :data:`None` if no well-formed ``FORM_TYPE`` field is found in\n        the list of fields.\n\n        .. versionadded:: 0.8"
  },
  {
    "code": "def to_json(self):\n        web_resp = collections.OrderedDict()\n        web_resp['status_code'] = self.status_code\n        web_resp['status_text'] = dict(HTTP_CODES).get(self.status_code)\n        web_resp['data'] = self.data if self.data is not None else {}\n        web_resp['errors'] = self.errors or []\n        return web_resp",
    "docstring": "Short cut for JSON response service data.\n\n        Returns:\n            Dict that implements JSON interface."
  },
  {
    "code": "def get_length(self):\n        length = 0\n        for i, point in enumerate(self.points):\n            if i != 0:\n                length += point.distance(self.points[i - 1])\n        return length",
    "docstring": "Calculate and return the length of the line as a sum of lengths\n        of all its segments.\n\n        :returns:\n            Total length in km."
  },
  {
    "code": "def escape(self, escape_func, quote_func=quote_spaces):\n        if self.is_literal():\n            return escape_func(self.data)\n        elif ' ' in self.data or '\\t' in self.data:\n            return quote_func(self.data)\n        else:\n            return self.data",
    "docstring": "Escape the string with the supplied function.  The\n        function is expected to take an arbitrary string, then\n        return it with all special characters escaped and ready\n        for passing to the command interpreter.\n\n        After calling this function, the next call to str() will\n        return the escaped string."
  },
  {
    "code": "def create_local_scope_from_def_args(\n        self,\n        call_args,\n        def_args,\n        line_number,\n        saved_function_call_index\n    ):\n        for i in range(len(call_args)):\n            def_arg_local_name = def_args[i]\n            def_arg_temp_name = 'temp_' + str(saved_function_call_index) + '_' + def_args[i]\n            local_scope_node = RestoreNode(\n                def_arg_local_name + ' = ' + def_arg_temp_name,\n                def_arg_local_name,\n                [def_arg_temp_name],\n                line_number=line_number,\n                path=self.filenames[-1]\n            )\n            self.nodes[-1].connect(local_scope_node)\n            self.nodes.append(local_scope_node)",
    "docstring": "Create the local scope before entering the body of a function call.\n\n        Args:\n            call_args(list[ast.Name]): Of the call being made.\n            def_args(ast_helper.Arguments): Of the definition being called.\n            line_number(int): Of the def of the function call about to be entered into.\n            saved_function_call_index(int): Unique number for each call.\n\n        Note: We do not need a connect_if_allowed because of the\n              preceding call to save_def_args_in_temp."
  },
  {
    "code": "def max_neg(self):\n        if self.__len__() == 0:\n            return ArgumentError('empty set has no maximum negative value.')\n        if self.contains(0):\n            return None\n        negative = [interval for interval in self.intervals\n                    if interval.right < 0]\n        if len(negative) == 0:\n            return None\n        return numpy.max(list(map(lambda i: i.right, negative)))",
    "docstring": "Returns maximum negative value or None."
  },
  {
    "code": "def load_fis(dir=None):\n    if dir is None:\n        import tkFileDialog\n        try:\n            dir=tkFileDialog.askdirectory()\n        except:\n            return\n    if dir is None:\n        return None\n    from os.path import walk\n    walk(dir,fits_list,\"*.fits\")",
    "docstring": "Load fits images in a directory"
  },
  {
    "code": "def get_default_currency(self) -> Commodity:\n        result = None\n        if self.default_currency:\n            result = self.default_currency\n        else:\n            def_currency = self.__get_default_currency()\n            self.default_currency = def_currency\n            result = def_currency\n        return result",
    "docstring": "returns the book default currency"
  },
  {
    "code": "def print_smart_tasks():\n    print(\"Printing information about smart tasks\")\n    tasks = api(gateway.get_smart_tasks())\n    if len(tasks) == 0:\n        exit(bold(\"No smart tasks defined\"))\n    container = []\n    for task in tasks:\n        container.append(api(task).task_control.raw)\n    print(jsonify(container))",
    "docstring": "Print smart tasks as JSON"
  },
  {
    "code": "def set_ghost_file(self, ghost_file):\n        yield from self._hypervisor.send('vm set_ghost_file \"{name}\" {ghost_file}'.format(name=self._name,\n                                                                                          ghost_file=shlex.quote(ghost_file)))\n        log.info('Router \"{name}\" [{id}]: ghost file set to {ghost_file}'.format(name=self._name,\n                                                                                 id=self._id,\n                                                                                 ghost_file=ghost_file))\n        self._ghost_file = ghost_file",
    "docstring": "Sets ghost RAM file\n\n        :ghost_file: path to ghost file"
  },
  {
    "code": "def _unescape_match(self, match):\n        char = match.group(1)\n        if char in self.ESCAPE_LOOKUP:\n            return self.ESCAPE_LOOKUP[char]\n        elif not char:\n            raise KatcpSyntaxError(\"Escape slash at end of argument.\")\n        else:\n            raise KatcpSyntaxError(\"Invalid escape character %r.\" % (char,))",
    "docstring": "Given an re.Match, unescape the escape code it represents."
  },
  {
    "code": "def get_host_power_status(self):\n        sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n        return GET_POWER_STATE_MAP.get(sushy_system.power_state)",
    "docstring": "Request the power state of the server.\n\n        :returns: Power State of the server, 'ON' or 'OFF'\n        :raises: IloError, on an error from iLO."
  },
  {
    "code": "def share_model_ndex():\n    if request.method == 'OPTIONS':\n        return {}\n    response = request.body.read().decode('utf-8')\n    body = json.loads(response)\n    stmts_str = body.get('stmts')\n    stmts_json = json.loads(stmts_str)\n    stmts = stmts_from_json(stmts_json[\"statements\"])\n    ca = CxAssembler(stmts)\n    for n, v in body.items():\n        ca.cx['networkAttributes'].append({'n': n, 'v': v, 'd': 'string'})\n    ca.make_model()\n    network_id = ca.upload_model(private=False)\n    return {'network_id': network_id}",
    "docstring": "Upload the model to NDEX"
  },
  {
    "code": "def _ReadParserPresetsFromFile(self):\n    self._presets_file = os.path.join(\n        self._data_location, self._PRESETS_FILE_NAME)\n    if not os.path.isfile(self._presets_file):\n      raise errors.BadConfigOption(\n          'No such parser presets file: {0:s}.'.format(self._presets_file))\n    try:\n      parsers_manager.ParsersManager.ReadPresetsFromFile(self._presets_file)\n    except errors.MalformedPresetError as exception:\n      raise errors.BadConfigOption(\n          'Unable to read presets from file with error: {0!s}'.format(\n              exception))",
    "docstring": "Reads the parser presets from the presets.yaml file.\n\n    Raises:\n      BadConfigOption: if the parser presets file cannot be read."
  },
  {
    "code": "def _set_named_args(self, **kv):\n        for k in kv:\n            self._body['${0}'.format(k)] = kv[k]\n        return self",
    "docstring": "Set a named parameter in the query. The named field must\n        exist in the query itself.\n\n        :param kv: Key-Value pairs representing values within the\n            query. These values should be stripped of their leading\n            `$` identifier."
  },
  {
    "code": "def highrisk_special_prefixes(self):\n        if self._highrisk_special_prefixes is None:\n            self._highrisk_special_prefixes = HighriskSpecialPrefixList(\n                self._version,\n                iso_code=self._solution['iso_code'],\n            )\n        return self._highrisk_special_prefixes",
    "docstring": "Access the highrisk_special_prefixes\n\n        :returns: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList\n        :rtype: twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix.HighriskSpecialPrefixList"
  },
  {
    "code": "def get_name(component):\n    if six.callable(component):\n        name = getattr(component, \"__qualname__\", component.__name__)\n        return '.'.join([component.__module__, name])\n    return str(component)",
    "docstring": "Attempt to get the string name of component, including module and class if\n    applicable."
  },
  {
    "code": "def workers(self):\n        worker_keys = self.redis_client.keys(\"Worker*\")\n        workers_data = {}\n        for worker_key in worker_keys:\n            worker_info = self.redis_client.hgetall(worker_key)\n            worker_id = binary_to_hex(worker_key[len(\"Workers:\"):])\n            workers_data[worker_id] = {\n                \"node_ip_address\": decode(worker_info[b\"node_ip_address\"]),\n                \"plasma_store_socket\": decode(\n                    worker_info[b\"plasma_store_socket\"])\n            }\n            if b\"stderr_file\" in worker_info:\n                workers_data[worker_id][\"stderr_file\"] = decode(\n                    worker_info[b\"stderr_file\"])\n            if b\"stdout_file\" in worker_info:\n                workers_data[worker_id][\"stdout_file\"] = decode(\n                    worker_info[b\"stdout_file\"])\n        return workers_data",
    "docstring": "Get a dictionary mapping worker ID to worker information."
  },
  {
    "code": "def validate_cookies(session, class_name):\n    if not do_we_have_enough_cookies(session.cookies, class_name):\n        return False\n    url = CLASS_URL.format(class_name=class_name) + '/class'\n    r = session.head(url, allow_redirects=False)\n    if r.status_code == 200:\n        return True\n    else:\n        logging.debug('Stale session.')\n        try:\n            session.cookies.clear('.coursera.org')\n        except KeyError:\n            pass\n        return False",
    "docstring": "Checks whether we have all the required cookies\n    to authenticate on class.coursera.org. Also check for and remove\n    stale session."
  },
  {
    "code": "def from_structures(structures, transformations=None, extend_collection=0):\n        tstruct = [TransformedStructure(s, []) for s in structures]\n        return StandardTransmuter(tstruct, transformations, extend_collection)",
    "docstring": "Alternative constructor from structures rather than\n        TransformedStructures.\n\n        Args:\n            structures: Sequence of structures\n            transformations: New transformations to be applied to all\n                structures\n            extend_collection: Whether to use more than one output structure\n                from one-to-many transformations. extend_collection can be a\n                number, which determines the maximum branching for each\n                transformation.\n\n        Returns:\n            StandardTransmuter"
  },
  {
    "code": "def setup():\n    init_tasks()\n    run_hook(\"before_setup\")\n    env.run(\"mkdir -p %s\" % (paths.get_shared_path()))\n    env.run(\"chmod 755 %s\" % (paths.get_shared_path()))\n    env.run(\"mkdir -p %s\" % (paths.get_backup_path()))\n    env.run(\"chmod 750 %s\" % (paths.get_backup_path()))\n    env.run(\"mkdir -p %s\" % (paths.get_upload_path()))\n    env.run(\"chmod 775 %s\" % (paths.get_upload_path()))\n    run_hook(\"setup\")\n    run_hook(\"after_setup\")",
    "docstring": "Creates shared and upload directory then fires setup to recipes."
  },
  {
    "code": "def restore_state(scan_codes):\n    _listener.is_replaying = True\n    with _pressed_events_lock:\n        current = set(_pressed_events)\n    target = set(scan_codes)\n    for scan_code in current - target:\n        _os_keyboard.release(scan_code)\n    for scan_code in target - current:\n        _os_keyboard.press(scan_code)\n    _listener.is_replaying = False",
    "docstring": "Given a list of scan_codes ensures these keys, and only these keys, are\n    pressed. Pairs well with `stash_state`, alternative to `restore_modifiers`."
  },
  {
    "code": "def find_previous(element, l):\n    length = len(l)\n    for index, current in enumerate(l):\n        if length - 1 == index:\n            return current\n        if index == 0:\n            if element < current:\n                return None\n        if current <= element < l[index+1]:\n            return current",
    "docstring": "find previous element in a sorted list\n\n    >>> find_previous(0, [0])\n    0\n    >>> find_previous(2, [1, 1, 3])\n    1\n    >>> find_previous(0, [1, 2])\n    >>> find_previous(1.5, [1, 2])\n    1\n    >>> find_previous(3, [1, 2])\n    2"
  },
  {
    "code": "def endnotemap(self, cache=True):\n        if self.__endnotemap is not None and cache==True:\n            return self.__endnotemap\n        else:\n            x = self.xml(src='word/endnotes.xml')\n            d = Dict()\n            if x is None: return d\n            for endnote in x.root.xpath(\"w:endnote\", namespaces=self.NS):\n                id = endnote.get(\"{%(w)s}id\" % self.NS)\n                typ = endnote.get(\"{%(w)s}type\" % self.NS)\n                d[id] = Dict(id=id, type=typ, elem=endnote)\n            if cache==True: self.__endnotemap = d\n            return d",
    "docstring": "return the endnotes from the docx, keyed to string id."
  },
  {
    "code": "def kick(self, bound: int) -> int:\n        return self._int_cmd(b'kick %d' % bound, b'KICKED')",
    "docstring": "Moves delayed and buried jobs into the ready queue and returns the\n        number of jobs effected.\n\n        Only jobs from the currently used tube are moved.\n\n        A kick will only move jobs in a single state. If there are any buried\n        jobs, only those will be moved. Otherwise delayed jobs will be moved.\n\n        :param bound: The maximum number of jobs to kick."
  },
  {
    "code": "def _normalize_timestamps(self, timestamp, intervals, config):\n    rval = [timestamp]\n    if intervals<0:\n      while intervals<0:\n        rval.append( config['i_calc'].normalize(timestamp, intervals) )\n        intervals += 1\n    elif intervals>0:\n      while intervals>0:\n        rval.append( config['i_calc'].normalize(timestamp, intervals) )\n        intervals -= 1\n    return rval",
    "docstring": "Helper for the subclasses to generate a list of timestamps."
  },
  {
    "code": "def attach_run_command(cmd):\n    if isinstance(cmd, tuple):\n        return _lxc.attach_run_command(cmd)\n    elif isinstance(cmd, list):\n        return _lxc.attach_run_command((cmd[0], cmd))\n    else:\n        return _lxc.attach_run_command((cmd, [cmd]))",
    "docstring": "Run a command when attaching\n\n        Please do not call directly, this will execvp the command.\n        This is to be used in conjunction with the attach method\n        of a container."
  },
  {
    "code": "def knuth_morris_pratt(s, t):\n    sep = '\\x00'\n    assert sep not in t and sep not in s\n    f = maximum_border_length(t + sep + s)\n    n = len(t)\n    for i, fi in enumerate(f):\n        if fi == n:\n            return i - 2 * n\n    return -1",
    "docstring": "Find a substring by Knuth-Morris-Pratt\n\n    :param s: the haystack string\n    :param t: the needle string\n    :returns: index i such that s[i: i + len(t)] == t, or -1\n    :complexity: O(len(s) + len(t))"
  },
  {
    "code": "def cache_master(self, saltenv='base', cachedir=None):\n        ret = []\n        for path in self.file_list(saltenv):\n            ret.append(\n                self.cache_file(\n                    salt.utils.url.create(path), saltenv, cachedir=cachedir)\n            )\n        return ret",
    "docstring": "Download and cache all files on a master in a specified environment"
  },
  {
    "code": "def monkey_patch_migration_template(self, app, fixture_path):\n        self._MIGRATION_TEMPLATE = writer.MIGRATION_TEMPLATE\n        module_split = app.module.__name__.split('.')\n        if len(module_split) == 1:\n            module_import = \"import %s\\n\" % module_split[0]\n        else:\n            module_import = \"from %s import %s\\n\" % (\n                '.'.join(module_split[:-1]),\n                module_split[-1:][0],\n            )\n        writer.MIGRATION_TEMPLATE = writer.MIGRATION_TEMPLATE\\\n            .replace(\n                '%(imports)s',\n                \"%(imports)s\" + \"\\nfrom django_migration_fixture import fixture\\n%s\" % module_import\n            )\\\n            .replace(\n                '%(operations)s', \n                \"        migrations.RunPython(**fixture(%s, ['%s'])),\\n\" % (\n                    app.label,\n                    os.path.basename(fixture_path)\n                ) + \"%(operations)s\\n\" \n            )",
    "docstring": "Monkey patch the django.db.migrations.writer.MIGRATION_TEMPLATE\n\n        Monkey patching django.db.migrations.writer.MIGRATION_TEMPLATE means that we \n        don't have to do any complex regex or reflection.\n\n        It's hacky... but works atm."
  },
  {
    "code": "def should_strip_auth(self, old_url, new_url):\n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if old_parsed.hostname != new_parsed.hostname:\n            return True\n        if (old_parsed.scheme == 'http' and old_parsed.port in (80, None)\n                and new_parsed.scheme == 'https' and new_parsed.port in (443, None)):\n            return False\n        changed_port = old_parsed.port != new_parsed.port\n        changed_scheme = old_parsed.scheme != new_parsed.scheme\n        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n        if (not changed_scheme and old_parsed.port in default_port\n                and new_parsed.port in default_port):\n            return False\n        return changed_port or changed_scheme",
    "docstring": "Decide whether Authorization header should be removed when redirecting"
  },
  {
    "code": "def bind(self, args, kwargs):\n        spec = self._spec\n        resolution = self.resolve(args, kwargs)\n        params = dict(zip(spec.args, resolution.slots))\n        if spec.varargs:\n            params[spec.varargs] = resolution.varargs\n        if spec.varkw:\n            params[spec.varkw] = resolution.varkw\n        if spec.kwonlyargs:\n            params.update(resolution.kwonlyargs)\n        return params",
    "docstring": "Bind arguments and keyword arguments to the encapsulated function.\n\n        Returns a dictionary of parameters (named according to function\n        parameters) with the values that were bound to each name."
  },
  {
    "code": "def _get_image_stream_info_for_build_request(self, build_request):\n        image_stream = None\n        image_stream_tag_name = None\n        if build_request.has_ist_trigger():\n            image_stream_tag_id = build_request.trigger_imagestreamtag\n            image_stream_id, image_stream_tag_name = image_stream_tag_id.split(':')\n            try:\n                image_stream = self.get_image_stream(image_stream_id).json()\n            except OsbsResponseException as x:\n                if x.status_code != 404:\n                    raise\n            if image_stream:\n                try:\n                    self.get_image_stream_tag(image_stream_tag_id).json()\n                except OsbsResponseException as x:\n                    if x.status_code != 404:\n                        raise\n        return image_stream, image_stream_tag_name",
    "docstring": "Return ImageStream, and ImageStreamTag name for base_image of build_request\n\n        If build_request is not auto instantiated, objects are not fetched\n        and None, None is returned."
  },
  {
    "code": "def dssps(self):\n        dssps_dict = {}\n        dssp_dir = os.path.join(self.parent_dir, 'dssp')\n        if not os.path.exists(dssp_dir):\n            os.makedirs(dssp_dir)\n        for i, mmol_file in self.mmols.items():\n            dssp_file_name = '{0}.dssp'.format(os.path.basename(mmol_file))\n            dssp_file = os.path.join(dssp_dir, dssp_file_name)\n            if not os.path.exists(dssp_file):\n                dssp_out = run_dssp(pdb=mmol_file, path=True, outfile=dssp_file)\n                if len(dssp_out) == 0:\n                    raise Warning(\"dssp file {0} is empty\".format(dssp_file))\n            dssps_dict[i] = dssp_file\n        return dssps_dict",
    "docstring": "Dict of filepaths for all dssp files associated with code.\n\n        Notes\n        -----\n        Runs dssp and stores writes output to files if not already present.\n        Also downloads mmol files if not already present.\n        Calls isambard.external_programs.dssp and so needs dssp to be installed.\n\n        Returns\n        -------\n        dssps_dict : dict, or None.\n            Keys : int\n                mmol number\n            Values : str\n                Filepath for the corresponding dssp file.\n\n        Raises\n        ------\n        Warning\n            If any of the dssp files are empty."
  },
  {
    "code": "def get_service_url(\n            self,\n            block_identifier: BlockSpecification,\n            service_hex_address: AddressHex,\n    ) -> Optional[str]:\n        result = self.proxy.contract.functions.urls(service_hex_address).call(\n            block_identifier=block_identifier,\n        )\n        if result == '':\n            return None\n        return result",
    "docstring": "Gets the URL of a service by address. If does not exist return None"
  },
  {
    "code": "def create_asset(self, asset_form):\n        collection = JSONClientValidated('repository',\n                                         collection='Asset',\n                                         runtime=self._runtime)\n        if not isinstance(asset_form, ABCAssetForm):\n            raise errors.InvalidArgument('argument type is not an AssetForm')\n        if asset_form.is_for_update():\n            raise errors.InvalidArgument('the AssetForm is for update only, not create')\n        try:\n            if self._forms[asset_form.get_id().get_identifier()] == CREATED:\n                raise errors.IllegalState('asset_form already used in a create transaction')\n        except KeyError:\n            raise errors.Unsupported('asset_form did not originate from this session')\n        if not asset_form.is_valid():\n            raise errors.InvalidArgument('one or more of the form elements is invalid')\n        insert_result = collection.insert_one(asset_form._my_map)\n        self._forms[asset_form.get_id().get_identifier()] = CREATED\n        result = objects.Asset(\n            osid_object_map=collection.find_one({'_id': insert_result.inserted_id}),\n            runtime=self._runtime,\n            proxy=self._proxy)\n        return result",
    "docstring": "Creates a new ``Asset``.\n\n        arg:    asset_form (osid.repository.AssetForm): the form for\n                this ``Asset``\n        return: (osid.repository.Asset) - the new ``Asset``\n        raise:  IllegalState - ``asset_form`` already used in a create\n                transaction\n        raise:  InvalidArgument - one or more of the form elements is\n                invalid\n        raise:  NullArgument - ``asset_form`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        raise:  Unsupported - ``asset_form`` did not originate from\n                ``get_asset_form_for_create()``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def index(self):\n        c.pynipap_version = pynipap.__version__\n        try:\n            c.nipapd_version = pynipap.nipapd_version()\n        except:\n            c.nipapd_version = 'unknown'\n        c.nipap_db_version = pynipap.nipap_db_version()\n        return render('/version.html')",
    "docstring": "Display NIPAP version info"
  },
  {
    "code": "def _index_resized(self, col, old_width, new_width):\r\n        self.table_index.setColumnWidth(col, new_width)\r\n        self._update_layout()",
    "docstring": "Resize the corresponding column of the index section selected."
  },
  {
    "code": "def stop_consuming(self):\n        if not self.consumer_tags:\n            return\n        if not self.is_closed:\n            for tag in self.consumer_tags:\n                self.basic.cancel(tag)\n        self.remove_consumer_tag()",
    "docstring": "Stop consuming messages.\n\n        :raises AMQPChannelError: Raises if the channel encountered an error.\n        :raises AMQPConnectionError: Raises if the connection\n                                     encountered an error.\n\n        :return:"
  },
  {
    "code": "def _get_vm_device_status(self,  device='FLOPPY'):\n        valid_devices = {'FLOPPY': 'floppy',\n                         'CDROM': 'cd'}\n        if device not in valid_devices:\n                raise exception.IloInvalidInputError(\n                    \"Invalid device. Valid devices: FLOPPY or CDROM.\")\n        manager, uri = self._get_ilo_details()\n        try:\n            vmedia_uri = manager['links']['VirtualMedia']['href']\n        except KeyError:\n            msg = ('\"VirtualMedia\" section in Manager/links does not exist')\n            raise exception.IloCommandNotSupportedError(msg)\n        for status, hds, vmed, memberuri in self._get_collection(vmedia_uri):\n            status, headers, response = self._rest_get(memberuri)\n            if status != 200:\n                msg = self._get_extended_error(response)\n                raise exception.IloError(msg)\n            if (valid_devices[device] in\n               [item.lower() for item in response['MediaTypes']]):\n                vm_device_uri = response['links']['self']['href']\n                return response, vm_device_uri\n        msg = ('Virtualmedia device \"' + device + '\" is not'\n               ' found on this system.')\n        raise exception.IloError(msg)",
    "docstring": "Returns the given virtual media device status and device URI\n\n        :param  device: virtual media device to be queried\n        :returns json format virtual media device status and its URI\n        :raises: IloError, on an error from iLO.\n        :raises: IloCommandNotSupportedError, if the command is not supported\n                 on the server."
  },
  {
    "code": "def list(self, limit=None, offset=None):\n        uri = \"/%s%s\" % (self.uri_base, self._get_pagination_qs(limit, offset))\n        return self._list(uri)",
    "docstring": "Gets a list of all domains, or optionally a page of domains."
  },
  {
    "code": "def toggle_attr(self, attr):\n        selection = self.grid.selection\n        if selection:\n            value = self.get_new_selection_attr_state(selection, attr)\n        else:\n            value = self.get_new_cell_attr_state(self.grid.actions.cursor,\n                                                 attr)\n        self.set_attr(attr, value)",
    "docstring": "Toggles an attribute attr for current selection"
  },
  {
    "code": "def normalize_name(s):\n    s = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore')\n    s = str(s)[2:-1]\n    return s",
    "docstring": "Remove foreign accents and characters to normalize the string. Prevents encoding errors.\n\n    :param str s: String\n    :return str s: String"
  },
  {
    "code": "def add_to_team(self, **kw):\n        group = self.context.participant_policy.title()\n        data = kw.copy()\n        if \"groups\" in data:\n            data[\"groups\"].add(group)\n        else:\n            data[\"groups\"] = set([group])\n        super(PloneIntranetWorkspace, self).add_to_team(**data)",
    "docstring": "We override this method to add our additional participation\n        policy groups, as detailed in available_groups above"
  },
  {
    "code": "def removetmp():\n    for path in _tmp_paths:\n        if os.path.exists(path):\n            try:\n                os.remove(path)\n            except PermissionError:\n                pass",
    "docstring": "Remove the temporary files created by gettemp"
  },
  {
    "code": "def send_message_tracked(self, msg):\n        msg.type_ = aioxmpp.MessageType.GROUPCHAT\n        msg.to = self._mucjid\n        msg.xep0045_muc_user = muc_xso.UserExt()\n        msg.autoset_id()\n        tracking_svc = self.service.dependencies[\n            aioxmpp.tracking.BasicTrackingService\n        ]\n        tracker = aioxmpp.tracking.MessageTracker()\n        id_key = msg.id_\n        body_key = _extract_one_pair(msg.body)\n        self._tracking_by_id[id_key] = tracker\n        self._tracking_metadata[tracker] = (\n            id_key,\n            body_key,\n        )\n        self._tracking_by_body.setdefault(\n            body_key,\n            []\n        ).append(tracker)\n        tracker.on_closed.connect(functools.partial(\n            self._tracker_closed,\n            tracker,\n        ))\n        token = tracking_svc.send_tracked(msg, tracker)\n        self.on_message(\n            msg,\n            self._this_occupant,\n            aioxmpp.im.dispatcher.MessageSource.STREAM,\n            tracker=tracker,\n        )\n        return token, tracker",
    "docstring": "Send a message to the MUC with tracking.\n\n        :param msg: The message to send.\n        :type msg: :class:`aioxmpp.Message`\n\n        .. warning::\n\n            Please read :ref:`api-tracking-memory`. This is especially relevant\n            for MUCs because tracking is not guaranteed to work due to how\n            :xep:`45` is written. It will work in many cases, probably in all\n            cases you test during development, but it may fail to work for some\n            individual messages and it may fail to work consistently for some\n            services. See the implementation details below for reasons.\n\n        The message is tracked and is considered\n        :attr:`~.MessageState.DELIVERED_TO_RECIPIENT` when it is reflected back\n        to us by the MUC service. The reflected message is then available in\n        the :attr:`~.MessageTracker.response` attribute.\n\n        .. note::\n\n            Two things:\n\n            1. The MUC service may change the contents of the message. An\n               example of this is the Prosody developer MUC which replaces\n               messages with more than a few lines with a pastebin link.\n            2. Reflected messages which are caught by tracking are not emitted\n               through :meth:`on_message`.\n\n        There is no need to set the address attributes or the type of the\n        message correctly; those will be overridden by this method to conform\n        to the requirements of a message to the MUC. Other attributes are left\n        untouched (except that :meth:`~.StanzaBase.autoset_id` is called) and\n        can be used as desired for the message.\n\n        .. warning::\n\n            Using :meth:`send_message_tracked` before :meth:`on_join` has\n            emitted will cause the `member` object in the resulting\n            :meth:`on_message` event to be :data:`None` (the message will be\n            delivered just fine).\n\n            Using :meth:`send_message_tracked` before history replay is over\n            will cause the :meth:`on_message` event to be emitted during\n            history replay, even though everyone else in the MUC will -- of\n            course -- only see the message after the history.\n\n            :meth:`send_message` is not affected by these quirks.\n\n        .. seealso::\n\n            :meth:`.AbstractConversation.send_message_tracked` for the full\n            interface specification.\n\n        **Implementation details:** Currently, we try to detect reflected\n        messages using two different criteria. First, if we see a message with\n        the same message ID (note that message IDs contain 120 bits of entropy)\n        as the message we sent, we consider it as the reflection. As some MUC\n        services re-write the message ID in the reflection, as a fallback, we\n        also consider messages which originate from the correct sender and have\n        the correct body a reflection.\n\n        Obviously, this fails consistently in MUCs which re-write the body and\n        re-write the ID and randomly if the MUC always re-writes the ID but\n        only sometimes the body."
  },
  {
    "code": "def format_from_extension(self, extension):\n        formats = [name\n                   for name, format in self._formats.items()\n                   if format.get('file_extension', None) == extension]\n        if len(formats) == 0:\n            return None\n        elif len(formats) == 2:\n            raise RuntimeError(\"Several extensions are registered with \"\n                               \"that extension; please specify the format \"\n                               \"explicitly.\")\n        else:\n            return formats[0]",
    "docstring": "Find a format from its extension."
  },
  {
    "code": "def find_price_by_category(package, price_category):\n    for item in package['items']:\n        price_id = _find_price_id(item['prices'], price_category)\n        if price_id:\n            return price_id\n    raise ValueError(\"Could not find price with the category, %s\" % price_category)",
    "docstring": "Find the price in the given package that has the specified category\n\n    :param package: The AsAService, Enterprise, or Performance product package\n    :param price_category: The price category code to search for\n    :return: Returns the price for the given category, or an error if not found"
  },
  {
    "code": "def add_monitor(self, pattern, callback, limit=80):\n        self.buffer.add_monitor(pattern, partial(callback, self), limit)",
    "docstring": "Calls the given function whenever the given pattern matches the\n        incoming data.\n\n        .. HINT::\n            If you want to catch all incoming data regardless of a\n            pattern, use the Protocol.data_received_event event instead.\n\n        Arguments passed to the callback are the protocol instance, the\n        index of the match, and the match object of the regular expression.\n\n        :type  pattern: str|re.RegexObject|list(str|re.RegexObject)\n        :param pattern: One or more regular expressions.\n        :type  callback: callable\n        :param callback: The function that is called.\n        :type  limit: int\n        :param limit: The maximum size of the tail of the buffer\n                      that is searched, in number of bytes."
  },
  {
    "code": "def close(self, virtual_account_id, data={}, **kwargs):\n        url = \"{}/{}\".format(self.base_url, virtual_account_id)\n        data['status'] = 'closed'\n        return self.patch_url(url, data, **kwargs)",
    "docstring": "Close Virtual Account from given Id\n\n        Args:\n            virtual_account_id :\n                Id for which Virtual Account objects has to be Closed"
  },
  {
    "code": "async def description(self):\n        resp = await self._call_web(f'nation={self.id}')\n        return html.unescape(\n            re.search(\n                '<div class=\"nationsummary\">(.+?)<p class=\"nationranktext\">',\n                resp.text,\n                flags=re.DOTALL\n            )\n            .group(1)\n            .replace('\\n', '')\n            .replace('</p>', '')\n            .replace('<p>', '\\n\\n')\n            .strip()\n        )",
    "docstring": "Nation's full description, as seen on its in-game page.\n\n        Returns\n        -------\n        an awaitable of str"
  },
  {
    "code": "def to_string(self):\n        return '%s   %s %s %s %s' % (\n            self.trait, self.start_position, self.peak_start_position,\n            self.peak_stop_position, self.stop_position)",
    "docstring": "Return the string as it should be presented in a MapChart\n        input file."
  },
  {
    "code": "def _authenticated_call_geocoder(self, url, timeout=DEFAULT_SENTINEL):\n        if self.token is None or int(time()) > self.token_expiry:\n            self._refresh_authentication_token()\n        request = Request(\n            \"&\".join((url, urlencode({\"token\": self.token}))),\n            headers={\"Referer\": self.referer}\n        )\n        return self._base_call_geocoder(request, timeout=timeout)",
    "docstring": "Wrap self._call_geocoder, handling tokens."
  },
  {
    "code": "def available_for_protocol(self, protocol):\n        if self.protocol == ALL or protocol == ALL:\n            return True\n        return protocol in ensure_sequence(self.protocol)",
    "docstring": "Check if the current function can be executed from a request defining the given protocol"
  },
  {
    "code": "def get_external_ip(self):\r\n        random.shuffle(self.server_list)\r\n        myip = ''\r\n        for server in self.server_list[:3]:\r\n            myip = self.fetch(server)\r\n            if myip != '':\r\n                return myip\r\n            else:\r\n                continue\r\n        return ''",
    "docstring": "This function gets your IP from a random server"
  },
  {
    "code": "def copy(self):\n        return Eq(\n            self._lhs, self._rhs, tag=self._tag,\n            _prev_lhs=self._prev_lhs, _prev_rhs=self._prev_rhs,\n            _prev_tags=self._prev_tags)",
    "docstring": "Return a copy of the equation"
  },
  {
    "code": "def _token_counts_from_generator(generator, max_chars, reserved_tokens):\n  reserved_tokens = list(reserved_tokens) + [_UNDERSCORE_REPLACEMENT]\n  tokenizer = text_encoder.Tokenizer(\n      alphanum_only=False, reserved_tokens=reserved_tokens)\n  num_chars = 0\n  token_counts = collections.defaultdict(int)\n  for s in generator:\n    s = tf.compat.as_text(s)\n    if max_chars and (num_chars + len(s)) >= max_chars:\n      s = s[:(max_chars - num_chars)]\n    tokens = tokenizer.tokenize(s)\n    tokens = _prepare_tokens_for_encode(tokens)\n    for t in tokens:\n      token_counts[t] += 1\n    if max_chars:\n      num_chars += len(s)\n      if num_chars > max_chars:\n        break\n  return token_counts",
    "docstring": "Builds token counts from generator."
  },
  {
    "code": "def load(self, rel_path=None):\n        for k, v in self.layer.iteritems():\n            self.add(k, v['module'], v.get('package'))\n            filename = v.get('filename')\n            path = v.get('path')\n            if filename:\n                warnings.warn(DeprecationWarning(SIMFILE_LOAD_WARNING))\n                if not path:\n                    path = rel_path\n                else:\n                    path = os.path.join(rel_path, path)\n                filename = os.path.join(path, filename)\n            self.open(k, filename)",
    "docstring": "Add sim_src to layer."
  },
  {
    "code": "def theta_str(theta, taustr=TAUSTR, fmtstr='{coeff:,.1f}{taustr}'):\n    r\n    coeff = theta / TAU\n    theta_str = fmtstr.format(coeff=coeff, taustr=taustr)\n    return theta_str",
    "docstring": "r\"\"\"\n    Format theta so it is interpretable in base 10\n\n    Args:\n        theta (float) angle in radians\n        taustr (str): default 2pi\n\n    Returns:\n        str : theta_str - the angle in tau units\n\n    Example1:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_str import *  # NOQA\n        >>> theta = 3.1415\n        >>> result = theta_str(theta)\n        >>> print(result)\n        0.5*2pi\n\n    Example2:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_str import *  # NOQA\n        >>> theta = 6.9932\n        >>> taustr = 'tau'\n        >>> result = theta_str(theta, taustr)\n        >>> print(result)\n        1.1tau"
  },
  {
    "code": "def align(self, out_path=None):\n        if out_path is None: out_path = self.prefix_path + '.aln'\n        sh.muscle38(\"-in\", self.path, \"-out\", out_path)\n        return AlignedFASTA(out_path)",
    "docstring": "We align the sequences in the fasta file with muscle."
  },
  {
    "code": "async def getItemCmdr(cell, outp=None, **opts):\n    cmdr = await s_cli.Cli.anit(cell, outp=outp)\n    typename = await cell.getCellType()\n    for ctor in cmdsbycell.get(typename, ()):\n        cmdr.addCmdClass(ctor)\n    return cmdr",
    "docstring": "Construct and return a cmdr for the given remote cell.\n\n    Example:\n\n        cmdr = await getItemCmdr(foo)"
  },
  {
    "code": "def date_add(start, days):\n    sc = SparkContext._active_spark_context\n    return Column(sc._jvm.functions.date_add(_to_java_column(start), days))",
    "docstring": "Returns the date that is `days` days after `start`\n\n    >>> df = spark.createDataFrame([('2015-04-08',)], ['dt'])\n    >>> df.select(date_add(df.dt, 1).alias('next_date')).collect()\n    [Row(next_date=datetime.date(2015, 4, 9))]"
  },
  {
    "code": "def order_delete(backend, kitchen, order_id):\n    use_kitchen = Backend.get_kitchen_name_soft(kitchen)\n    print use_kitchen\n    if use_kitchen is None and order_id is None:\n        raise click.ClickException('You must specify either a kitchen or an order_id or be in a kitchen directory')\n    if order_id is not None:\n        click.secho('%s - Delete an Order using id %s' % (get_datetime(), order_id), fg='green')\n        check_and_print(DKCloudCommandRunner.delete_one_order(backend.dki, order_id))\n    else:\n        click.secho('%s - Delete all orders in Kitchen %s' % (get_datetime(), use_kitchen), fg='green')\n        check_and_print(DKCloudCommandRunner.delete_all_order(backend.dki, use_kitchen))",
    "docstring": "Delete one order or all orders in a kitchen"
  },
  {
    "code": "async def storPropSet(self, buid, prop, valu):\n        assert self.buidcache.disabled\n        indx = prop.type.indx(valu)\n        if indx is not None and len(indx) > MAX_INDEX_LEN:\n            mesg = 'index bytes are too large'\n            raise s_exc.BadIndxValu(mesg=mesg, prop=prop, valu=valu)\n        univ = prop.utf8name[0] in (46, 35)\n        bpkey = buid + prop.utf8name\n        self._storPropSetCommon(buid, prop.utf8name, bpkey, prop.pref, univ, valu, indx)",
    "docstring": "Migration-only function"
  },
  {
    "code": "def where(self, exact=False, **kwargs):\n        for field_name in kwargs:\n            if isinstance(kwargs[field_name], list):\n                self.where_in(field_name, kwargs[field_name], exact)\n            else:\n                self.where_equals(field_name, kwargs[field_name], exact)\n        return self",
    "docstring": "To get all the document that equal to the value within kwargs with the specific key\n\n        @param bool exact: If True getting exact match of the query\n        @param kwargs: the keys of the kwargs will be the fields name in the index you want to query.\n        The value will be the the fields value you want to query\n        (if kwargs[field_name] is a list it will behave has the where_in method)"
  },
  {
    "code": "def shuffle(self, times=1):\n        for _ in xrange(times):\n            random.shuffle(self.cards)",
    "docstring": "Shuffles the Stack.\n\n        .. note::\n            Shuffling large numbers of cards (100,000+) may take a while.\n\n        :arg int times:\n            The number of times to shuffle."
  },
  {
    "code": "def get_by_index(self, index):\n        try:\n            return self[index]\n        except KeyError:\n            for v in self.get_volumes():\n                if v.index == str(index):\n                    return v\n        raise KeyError(index)",
    "docstring": "Returns a Volume or Disk by its index."
  },
  {
    "code": "def stop(self, force=False):\n\t\tif self._initialized:\n\t\t\tself.send(C1218TerminateRequest())\n\t\t\tdata = self.recv()\n\t\t\tif data == b'\\x00' or force:\n\t\t\t\tself._initialized = False\n\t\t\t\tself._toggle_bit = False\n\t\t\t\treturn True\n\t\treturn False",
    "docstring": "Send a terminate request.\n\n\t\t:param bool force: ignore the remote devices response"
  },
  {
    "code": "def queue_poll(self, sleep_t=0.5):\n        connection_alive = True\n        while self.running:\n            if self.ws:\n                def logger_and_close(msg):\n                    self.log.error('Websocket exception', exc_info=True)\n                    if not self.running:\n                        connection_alive = False\n                    else:\n                        if not self.number_try_connection:\n                            self.teardown()\n                            self._display_ws_warning()\n                with catch(websocket.WebSocketException, logger_and_close):\n                    result = self.ws.recv()\n                    self.queue.put(result)\n            if connection_alive:\n                time.sleep(sleep_t)",
    "docstring": "Put new messages on the queue as they arrive. Blocking in a thread.\n\n        Value of sleep is low to improve responsiveness."
  },
  {
    "code": "def cluster_reduce(idx, snr, window_size):\n    ind = findchirp_cluster_over_window(idx, snr, window_size)\n    return idx.take(ind), snr.take(ind)",
    "docstring": "Reduce the events by clustering over a window\n\n    Parameters\n    -----------\n    indices: Array\n        The list of indices of the SNR values\n    snr: Array\n        The list of SNR value\n    window_size: int\n        The size of the window in integer samples.\n\n    Returns\n    -------\n    indices: Array\n        The list of indices of the SNR values\n    snr: Array\n        The list of SNR values"
  },
  {
    "code": "def play(state):\n        filename = None\n        if state == SoundService.State.welcome:\n            filename = \"pad_glow_welcome1.wav\"\n        elif state == SoundService.State.goodbye:\n            filename = \"pad_glow_power_off.wav\"\n        elif state == SoundService.State.hotword_detected:\n            filename = \"pad_soft_on.wav\"\n        elif state == SoundService.State.asr_text_captured:\n            filename = \"pad_soft_off.wav\"\n        elif state == SoundService.State.error:\n            filename = \"music_marimba_error_chord_2x.wav\"\n        if filename is not None:\n            AudioPlayer.play_async(\"{}/{}\".format(ABS_SOUND_DIR, filename))",
    "docstring": "Play sound for a given state.\n\n        :param state: a State value."
  },
  {
    "code": "def _ixs(self, i, axis=0):\n        label = self.index[i]\n        if isinstance(label, Index):\n            return self.take(i, axis=axis)\n        else:\n            return self._get_val_at(i)",
    "docstring": "Return the i-th value or values in the SparseSeries by location\n\n        Parameters\n        ----------\n        i : int, slice, or sequence of integers\n\n        Returns\n        -------\n        value : scalar (int) or Series (slice, sequence)"
  },
  {
    "code": "def _closest_centroid(self, x):\n        closest_centroid = 0\n        distance = 10^9\n        for i in range(self.n_clusters):\n            current_distance = linalg.norm(x - self.centroids[i])\n            if current_distance < distance:\n                closest_centroid = i\n                distance = current_distance\n        return closest_centroid",
    "docstring": "Returns the index of the closest centroid to the sample"
  },
  {
    "code": "def sample(self, nsamples, nburn=0, nthin=1, save_hidden_state_trajectory=False,\n               call_back=None):\n        for iteration in range(nburn):\n            logger().info(\"Burn-in   %8d / %8d\" % (iteration, nburn))\n            self._update()\n        models = list()\n        for iteration in range(nsamples):\n            logger().info(\"Iteration %8d / %8d\" % (iteration, nsamples))\n            for thin in range(nthin):\n                self._update()\n            model_copy = copy.deepcopy(self.model)\n            if not save_hidden_state_trajectory:\n                model_copy.hidden_state_trajectory = None\n            models.append(model_copy)\n            if call_back is not None:\n                call_back()\n        return models",
    "docstring": "Sample from the BHMM posterior.\n\n        Parameters\n        ----------\n        nsamples : int\n            The number of samples to generate.\n        nburn : int, optional, default=0\n            The number of samples to discard to burn-in, following which `nsamples` will be generated.\n        nthin : int, optional, default=1\n            The number of Gibbs sampling updates used to generate each returned sample.\n        save_hidden_state_trajectory : bool, optional, default=False\n            If True, the hidden state trajectory for each sample will be saved as well.\n        call_back : function, optional, default=None\n            a call back function with no arguments, which if given is being called\n            after each computed sample. This is useful for implementing progress bars.\n\n        Returns\n        -------\n        models : list of bhmm.HMM\n            The sampled HMM models from the Bayesian posterior.\n\n        Examples\n        --------\n\n        >>> from bhmm import testsystems\n        >>> [model, observations, states, sampled_model] = testsystems.generate_random_bhmm(ntrajectories=5, length=1000)\n        >>> nburn = 5 # run the sampler a bit before recording samples\n        >>> nsamples = 10 # generate 10 samples\n        >>> nthin = 2 # discard one sample in between each recorded sample\n        >>> samples = sampled_model.sample(nsamples, nburn=nburn, nthin=nthin)"
  },
  {
    "code": "def setupnode(overwrite=False):\n    if not port_is_open():\n        if not skip_disable_root():\n            disable_root()\n        port_changed = change_ssh_port()\n    if server_state('setupnode-incomplete'):\n        env.overwrite=True\n    else: set_server_state('setupnode-incomplete')\n    upload_ssh_key()\n    restrict_ssh()\n    add_repositories()\n    upgrade_packages()\n    setup_ufw()\n    uninstall_packages()\n    install_packages()\n    upload_etc()\n    post_install_package()\n    setup_ufw_rules()\n    set_timezone()\n    set_server_state('setupnode-incomplete',delete=True)\n    for s in webserver_list():\n        stop_webserver(s)\n        start_webserver(s)",
    "docstring": "Install a baseline host. Can be run multiple times"
  },
  {
    "code": "def get_pretty_string(self, stat, verbose):\n        pretty_output = _PrettyOutputToStr()\n        self.generate_pretty_output(stat=stat,\n                                    verbose=verbose,\n                                    output_function=pretty_output.save_output)\n        return pretty_output.result",
    "docstring": "Pretty string representation of the results\n\n        :param stat: bool\n        :param verbose: bool\n        :return: str"
  },
  {
    "code": "def find(self, compile_failure_log, target):\n    not_found_classnames = [err.classname for err in\n                            self.compile_error_extractor.extract(compile_failure_log)]\n    return self._select_target_candidates_for_class(not_found_classnames, target)",
    "docstring": "Find missing deps on a best-effort basis from target's transitive dependencies.\n\n    Returns (class2deps, no_dep_found) tuple. `class2deps` contains classname\n    to deps that contain the class mapping. `no_dep_found` are the classnames that are\n    unable to find the deps."
  },
  {
    "code": "def _get_installations(self):\n        response = None\n        for base_url in urls.BASE_URLS:\n            urls.BASE_URL = base_url\n            try:\n                response = requests.get(\n                    urls.get_installations(self._username),\n                    headers={\n                        'Cookie': 'vid={}'.format(self._vid),\n                        'Accept': 'application/json,'\n                                  'text/javascript, */*; q=0.01',\n                    })\n                if 2 == response.status_code // 100:\n                    break\n                elif 503 == response.status_code:\n                    continue\n                else:\n                    raise ResponseError(response.status_code, response.text)\n            except requests.exceptions.RequestException as ex:\n                raise RequestError(ex)\n        _validate_response(response)\n        self.installations = json.loads(response.text)",
    "docstring": "Get information about installations"
  },
  {
    "code": "async def stop(self):\n        if self._rpc_task is not None:\n            self._rpc_task.cancel()\n        try:\n            await self._rpc_task\n        except asyncio.CancelledError:\n            pass\n        self._rpc_task = None",
    "docstring": "Stop the rpc queue from inside the event loop."
  },
  {
    "code": "def write_output(output, text=True, output_path=None):\n    if output_path is None and text is False:\n        print(\"ERROR: You must specify an output file using -o/--output for binary output formats\")\n        sys.exit(1)\n    if output_path is not None:\n        if text:\n            outfile = open(output_path, \"w\", encoding=\"utf-8\")\n        else:\n            outfile = open(output_path, \"wb\")\n    else:\n        outfile = sys.stdout\n    try:\n        if text and isinstance(output, bytes):\n            output = output.decode('utf-8')\n        outfile.write(output)\n    finally:\n        if outfile is not sys.stdout:\n            outfile.close()",
    "docstring": "Write binary or text output to a file or stdout."
  },
  {
    "code": "def print_permissions(permissions):\n    table = formatting.Table(['keyName', 'Description'])\n    for perm in permissions:\n        table.add_row([perm['keyName'], perm['name']])\n    return table",
    "docstring": "Prints out a users permissions"
  },
  {
    "code": "def from_template(cls, data, template):\n        name = DEFAULT_NAME\n        if isinstance(template, str):\n            name = template\n            table_info = TEMPLATES[name]\n        else:\n            table_info = template\n        if 'name' in table_info:\n            name = table_info['name']\n        dt = table_info['dtype']\n        loc = table_info['h5loc']\n        split = table_info['split_h5']\n        h5singleton = table_info['h5singleton']\n        return cls(\n            data,\n            h5loc=loc,\n            dtype=dt,\n            split_h5=split,\n            name=name,\n            h5singleton=h5singleton\n        )",
    "docstring": "Create a table from a predefined datatype.\n\n        See the ``templates_avail`` property for available names.\n\n        Parameters\n        ----------\n        data\n            Data in a format that the ``__init__`` understands.\n        template: str or dict\n            Name of the dtype template to use from ``kp.dataclasses_templates``\n            or a ``dict`` containing the required attributes (see the other\n            templates for reference)."
  },
  {
    "code": "def logout(config):\n    state = read(config.configfile)\n    if state.get(\"BUGZILLA\"):\n        remove(config.configfile, \"BUGZILLA\")\n        success_out(\"Forgotten\")\n    else:\n        error_out(\"No stored Bugzilla credentials\")",
    "docstring": "Remove and forget your Bugzilla credentials"
  },
  {
    "code": "def Add(self, file_desc_proto):\n    proto_name = file_desc_proto.name\n    if proto_name not in self._file_desc_protos_by_file:\n      self._file_desc_protos_by_file[proto_name] = file_desc_proto\n    elif self._file_desc_protos_by_file[proto_name] != file_desc_proto:\n      raise DescriptorDatabaseConflictingDefinitionError(\n          '%s already added, but with different descriptor.' % proto_name)\n    package = file_desc_proto.package\n    for message in file_desc_proto.message_type:\n      self._file_desc_protos_by_symbol.update(\n          (name, file_desc_proto) for name in _ExtractSymbols(message, package))\n    for enum in file_desc_proto.enum_type:\n      self._file_desc_protos_by_symbol[\n          '.'.join((package, enum.name))] = file_desc_proto\n    for extension in file_desc_proto.extension:\n      self._file_desc_protos_by_symbol[\n          '.'.join((package, extension.name))] = file_desc_proto\n    for service in file_desc_proto.service:\n      self._file_desc_protos_by_symbol[\n          '.'.join((package, service.name))] = file_desc_proto",
    "docstring": "Adds the FileDescriptorProto and its types to this database.\n\n    Args:\n      file_desc_proto: The FileDescriptorProto to add.\n    Raises:\n      DescriptorDatabaseConflictingDefinitionError: if an attempt is made to\n        add a proto with the same name but different definition than an\n        exisiting proto in the database."
  },
  {
    "code": "def duration(self):\n        durs = []\n        for track in self._segments:\n            durs.append(sum([comp.duration() for comp in track]))\n        return max(durs)",
    "docstring": "The duration of this stimulus\n\n        :returns: float -- duration in seconds"
  },
  {
    "code": "def get_subject_guide_for_section(section):\n    return get_subject_guide_for_section_params(\n        section.term.year, section.term.quarter, section.curriculum_abbr,\n        section.course_number, section.section_id)",
    "docstring": "Returns a SubjectGuide model for the passed SWS section model."
  },
  {
    "code": "def snippet(code, locations, sep=' | ', colmark=('-', '^'), context=5):\n        if not locations:\n            return []\n        lines = code.split('\\n')\n        offset = int(len(lines) / 10) + 1\n        linenofmt = '%{}d'.format(offset)\n        s = []\n        for loc in locations:\n            line = max(0, loc.get('line', 1) - 1)\n            column = max(0, loc.get('column', 1) - 1)\n            start_line = max(0, line - context)\n            for i, ln in enumerate(lines[start_line:line + 1], start_line):\n                s.append('{}{}{}'.format(linenofmt % i, sep, ln))\n            s.append('{}{}{}'.format(' ' * (offset + len(sep)),\n                                     colmark[0] * column,\n                                     colmark[1]))\n        return s",
    "docstring": "Given a code and list of locations, convert to snippet lines.\n\n        return will include line number, a separator (``sep``), then\n        line contents.\n\n        At most ``context`` lines are shown before each location line.\n\n        After each location line, the column is marked using\n        ``colmark``. The first character is repeated up to column, the\n        second character is used only once.\n\n        :return: list of lines of sources or column markups.\n        :rtype: list"
  },
  {
    "code": "def find(cls, *args, **kwargs):\n        return list(cls.collection.find(*args, **kwargs))",
    "docstring": "Returns all document dicts that pass the filter"
  },
  {
    "code": "def analyze(self):\n    class MockBindings(dict):\n      def __contains__(self, key):\n        self[key] = None\n        return True\n    bindings = MockBindings()\n    used = {}\n    ancestor = self.ancestor\n    if isinstance(ancestor, ParameterizedThing):\n      ancestor = ancestor.resolve(bindings, used)\n    filters = self.filters\n    if filters is not None:\n      filters = filters.resolve(bindings, used)\n    return sorted(used)",
    "docstring": "Return a list giving the parameters required by a query."
  },
  {
    "code": "def namespaced_view_name(view_name, metric_prefix):\n    metric_prefix = metric_prefix or \"custom.googleapis.com/opencensus\"\n    return os.path.join(metric_prefix, view_name).replace('\\\\', '/')",
    "docstring": "create string to be used as metric type"
  },
  {
    "code": "def _get_ref_lengths(self):\n        sam_reader = pysam.Samfile(self.bam, \"rb\")\n        return dict(zip(sam_reader.references, sam_reader.lengths))",
    "docstring": "Gets the length of each reference sequence from the header of the bam. Returns dict name => length"
  },
  {
    "code": "def get_assessment(self, assessment):\n        response = self.http.get('/Assessment/' + str(assessment))\n        assessment = Schemas.Assessment(assessment=response)\n        return assessment",
    "docstring": "To get Assessment by id"
  },
  {
    "code": "def lldp(interface='', **kwargs):\n    proxy_output = salt.utils.napalm.call(\n        napalm_device,\n        'get_lldp_neighbors_detail',\n        **{\n        }\n    )\n    if not proxy_output.get('result'):\n        return proxy_output\n    lldp_neighbors = proxy_output.get('out')\n    if interface:\n        lldp_neighbors = {interface: lldp_neighbors.get(interface)}\n    proxy_output.update({\n        'out': lldp_neighbors\n    })\n    return proxy_output",
    "docstring": "Returns a detailed view of the LLDP neighbors.\n\n    :param interface: interface name to filter on\n\n    :return:          A dictionary with the LLDL neighbors. The keys are the\n        interfaces with LLDP activated on.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' net.lldp\n        salt '*' net.lldp interface='TenGigE0/0/0/8'\n\n    Example output:\n\n    .. code-block:: python\n\n        {\n            'TenGigE0/0/0/8': [\n                {\n                    'parent_interface': 'Bundle-Ether8',\n                    'interface_description': 'TenGigE0/0/0/8',\n                    'remote_chassis_id': '8c60.4f69.e96c',\n                    'remote_system_name': 'switch',\n                    'remote_port': 'Eth2/2/1',\n                    'remote_port_description': 'Ethernet2/2/1',\n                    'remote_system_description': 'Cisco Nexus Operating System (NX-OS) Software 7.1(0)N1(1a)\n                          TAC support: http://www.cisco.com/tac\n                          Copyright (c) 2002-2015, Cisco Systems, Inc. All rights reserved.',\n                    'remote_system_capab': 'B, R',\n                    'remote_system_enable_capab': 'B'\n                }\n            ]\n        }"
  },
  {
    "code": "def from_json(value, native_datetimes=True):\n    hook = BasicJsonDecoder(native_datetimes=native_datetimes)\n    result = json.loads(value, object_hook=hook)\n    if native_datetimes and isinstance(result, string_types):\n        return get_date_or_string(result)\n    return result",
    "docstring": "Deserializes the given value from JSON.\n\n    :param value: the value to deserialize\n    :type value: str\n    :param native_datetimes:\n        whether or not strings that look like dates/times should be\n        automatically cast to the native objects, or left as strings; if not\n        specified, defaults to ``True``\n    :type native_datetimes: bool"
  },
  {
    "code": "def arrow(ctx, apollo_instance, verbose, log_level):\n    set_logging_level(log_level)\n    try:\n        ctx.gi = get_apollo_instance(apollo_instance)\n    except TypeError:\n        pass\n    ctx.verbose = verbose",
    "docstring": "Command line wrappers around Apollo functions. While this sounds\n    unexciting, with arrow and jq you can easily build powerful command line\n    scripts."
  },
  {
    "code": "def parse_set(string):\n    string = string.strip()\n    if string:\n        return set(string.split(\",\"))\n    else:\n        return set()",
    "docstring": "Parse set from comma separated string."
  },
  {
    "code": "def rotation_from_axes(x_axis, y_axis, z_axis):\n        return np.hstack((x_axis[:,np.newaxis], y_axis[:,np.newaxis], z_axis[:,np.newaxis]))",
    "docstring": "Convert specification of axis in target frame to\n        a rotation matrix from source to target frame.\n\n        Parameters\n        ----------\n        x_axis : :obj:`numpy.ndarray` of float\n            A normalized 3-vector for the target frame's x-axis.\n\n        y_axis : :obj:`numpy.ndarray` of float\n            A normalized 3-vector for the target frame's y-axis.\n\n        z_axis : :obj:`numpy.ndarray` of float\n            A normalized 3-vector for the target frame's z-axis.\n\n        Returns\n        -------\n        :obj:`numpy.ndarray` of float\n            A 3x3 rotation matrix that transforms from a source frame to the\n            given target frame."
  },
  {
    "code": "def getWindow(title, exact=False):\n    titles = getWindows()\n    hwnd = titles.get(title, None)\n    if not hwnd and not exact:\n        for k, v in titles.items():\n            if title in k:\n                hwnd = v\n                break\n    if hwnd:\n        return Window(hwnd)\n    else:\n        return None",
    "docstring": "Return Window object if 'title' or its part found in visible windows titles, else return None\n\n    Return only 1 window found first\n    Args:\n        title: unicode string\n        exact (bool): True if search only exact match"
  },
  {
    "code": "def find_synonymous_field(field, model=DEFAULT_MODEL, app=DEFAULT_APP, score_cutoff=50, root_preference=1.02):\n    fields = util.listify(field) + list(synonyms(field))\n    model = get_model(model, app)\n    available_field_names = model._meta.get_all_field_names()\n    best_match, best_ratio = None, None\n    for i, field_name in enumerate(fields):\n        match = fuzzy.extractOne(str(field_name), available_field_names)\n        if match and match[1] >= score_cutoff:\n            if not best_match or match[1] > (root_preference * best_ratio):\n                best_match, best_ratio = match\n    return best_match",
    "docstring": "Use a dictionary of synonyms and fuzzy string matching to find a similarly named field\n\n    Returns:\n      A single model field name (string)\n\n    Examples:\n\n      >>> find_synonymous_field('date', model='WikiItem')\n      'end_date_time'\n      >>> find_synonymous_field('date', model='WikiItem')\n      'date_time'\n      >>> find_synonymous_field('time', model='WikiItem')\n      'date_time'"
  },
  {
    "code": "def get_lmv2_response(domain, username, password, server_challenge, client_challenge):\n        ntlmv2_hash = PasswordAuthentication.ntowfv2(domain, username, password.encode('utf-16le'))\n        hmac_context = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend())\n        hmac_context.update(server_challenge)\n        hmac_context.update(client_challenge)\n        lmv2_hash = hmac_context.finalize()\n        session_key = hmac.HMAC(ntlmv2_hash, hashes.MD5(), backend=default_backend())\n        session_key.update(lmv2_hash)\n        return lmv2_hash + client_challenge, session_key.finalize()",
    "docstring": "Computes an appropriate LMv2 response based on the supplied arguments\n        The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash\n        concatenated with the 8 byte client client_challenge"
  },
  {
    "code": "def getBlocksTags(self):\n        myBlocks = self.blocks\n        return [ (myBlocks[i], i) for i in range( len(myBlocks) ) if issubclass(myBlocks[i].__class__, AdvancedTag) ]",
    "docstring": "getBlocksTags - Returns a list of tuples referencing the blocks which are direct children of this node, and the block is an AdvancedTag.\n\n                The tuples are ( block, blockIdx ) where \"blockIdx\" is the index of self.blocks wherein the tag resides.\n\n                @return list< tuple(block, blockIdx) > - A list of tuples of child blocks which are tags and their index in the self.blocks list"
  },
  {
    "code": "def list_elasticache(region, filter_by_kwargs):\n    conn = boto.elasticache.connect_to_region(region)\n    req = conn.describe_cache_clusters()\n    data = req[\"DescribeCacheClustersResponse\"][\"DescribeCacheClustersResult\"][\"CacheClusters\"]\n    if filter_by_kwargs:\n        clusters = [x['CacheClusterId'] for x in data if x[filter_by_kwargs.keys()[0]] == filter_by_kwargs.values()[0]]\n    else:\n        clusters = [x['CacheClusterId'] for x in data]\n    return clusters",
    "docstring": "List all ElastiCache Clusters."
  },
  {
    "code": "def remove(self, name, **params):\n        log = self._getparam('log', self._discard, **params)\n        if name not in self.names:\n            log.error(\"Attempt to remove %r which was never added\", name)\n            raise Exception(\"Command %r has never been added\" % (name,))\n        del self.names[name]\n        rebuild = False\n        for path in list(self.modules):\n            if name in self.modules[path]:\n                self.modules[path].remove(name)\n            if len(self.modules[path]) == 0:\n                del self.modules[path]\n                rebuild = True\n        if rebuild:\n            self._build(name, **params)",
    "docstring": "Delete a command from the watched list.  This involves removing\n        the command from the inverted watch list, then possibly\n        rebuilding the event set if any modules no longer need watching."
  },
  {
    "code": "def writeFace(self, val, what='f'):\n        val = [v + 1 for v in val]\n        if self._hasValues and self._hasNormals:\n            val = ' '.join(['%i/%i/%i' % (v, v, v) for v in val])\n        elif self._hasNormals:\n            val = ' '.join(['%i//%i' % (v, v) for v in val])\n        elif self._hasValues:\n            val = ' '.join(['%i/%i' % (v, v) for v in val])\n        else:\n            val = ' '.join(['%i' % v for v in val])\n        self.writeLine('%s %s' % (what, val))",
    "docstring": "Write the face info to the net line."
  },
  {
    "code": "def _on_client_volume_changed(self, data):\n        self._clients.get(data.get('id')).update_volume(data)",
    "docstring": "Handle client volume change."
  },
  {
    "code": "def namedb_create(path, genesis_block):\n    global BLOCKSTACK_DB_SCRIPT\n    if os.path.exists( path ):\n        raise Exception(\"Database '%s' already exists\" % path)\n    lines = [l + \";\" for l in BLOCKSTACK_DB_SCRIPT.split(\";\")]\n    con = sqlite3.connect( path, isolation_level=None, timeout=2**30 )\n    for line in lines:\n        db_query_execute(con, line, ())\n    con.row_factory = namedb_row_factory\n    namedb_create_token_genesis(con, genesis_block['rows'], genesis_block['history'])\n    return con",
    "docstring": "Create a sqlite3 db at the given path.\n    Create all the tables and indexes we need."
  },
  {
    "code": "def map_helper(data):\n    as_list = []\n    length = 2\n    for field, value in data.items():\n        as_list.append(Container(field=bytes(field, ENCODING),\n                                 value=bytes(value, ENCODING)))\n        length += len(field) + len(value) + 4\n    return (Container(\n        num=len(as_list),\n        map=as_list\n    ), length)",
    "docstring": "Build a map message."
  },
  {
    "code": "def abstract(class_):\n    if not inspect.isclass(class_):\n        raise TypeError(\"@abstract can only be applied to classes\")\n    abc_meta = None\n    class_meta = type(class_)\n    if class_meta not in (_ABCMetaclass, _ABCObjectMetaclass):\n        if class_meta is type:\n            abc_meta = _ABCMetaclass\n        elif class_meta is ObjectMetaclass:\n            abc_meta = _ABCObjectMetaclass\n        else:\n            raise ValueError(\n                \"@abstract cannot be applied to classes with custom metaclass\")\n    class_.__abstract__ = True\n    return metaclass(abc_meta)(class_) if abc_meta else class_",
    "docstring": "Mark the class as _abstract_ base class, forbidding its instantiation.\n\n    .. note::\n\n        Unlike other modifiers, ``@abstract`` can be applied\n        to all Python classes, not just subclasses of :class:`Object`.\n\n    .. versionadded:: 0.0.3"
  },
  {
    "code": "def generate_pages(self):\n\t\tfor page in self.pages:\n\t\t\tself.generate_page(page.slug, template='page.html.jinja', page=page)",
    "docstring": "Generate HTML out of the pages added to the blog."
  },
  {
    "code": "def parse_duration(duration, start=None, end=None):\n    if not start and not end:\n        return parse_simple_duration(duration)\n    if start:\n        return parse_duration_with_start(start, duration)\n    if end:\n        return parse_duration_with_end(duration, end)",
    "docstring": "Attepmt to parse an ISO8601 formatted duration.\n\n    Accepts a ``duration`` and optionally a start or end ``datetime``.\n    ``duration`` must be an ISO8601 formatted string.\n\n    Returns a ``datetime.timedelta`` object."
  },
  {
    "code": "def _input_as_lines(self, data):\n        filename = self._input_filename = \\\n            FilePath(self.getTmpFilename(self.TmpDir))\n        filename = FilePath(filename)\n        data_file = open(filename, 'w')\n        data_to_file = '\\n'.join([str(d).strip('\\n') for d in data])\n        data_file.write(data_to_file)\n        data_file.close()\n        return filename",
    "docstring": "Write a seq of lines to a temp file and return the filename string\n\n            data: a sequence to be written to a file, each element of the\n                sequence will compose a line in the file\n           * Note: the result will be the filename as a FilePath object\n            (which is a string subclass).\n\n           * Note: '\\n' will be stripped off the end of each sequence element\n                before writing to a file in order to avoid multiple new lines\n                accidentally be written to a file"
  },
  {
    "code": "def __up_cmp(self, obj1, obj2):\n        if obj1.update_order > obj2.update_order:\n            return 1\n        elif obj1.update_order < obj2.update_order:\n            return -1\n        else:\n            return 0",
    "docstring": "Defines how our updatable objects should be sorted"
  },
  {
    "code": "def images(self, type):\n        images = []\n        res = yield from self.http_query(\"GET\", \"/{}/images\".format(type), timeout=None)\n        images = res.json\n        try:\n            if type in [\"qemu\", \"dynamips\", \"iou\"]:\n                for local_image in list_images(type):\n                    if local_image['filename'] not in [i['filename'] for i in images]:\n                        images.append(local_image)\n                images = sorted(images, key=itemgetter('filename'))\n            else:\n                images = sorted(images, key=itemgetter('image'))\n        except OSError as e:\n            raise ComputeError(\"Can't list images: {}\".format(str(e)))\n        return images",
    "docstring": "Return the list of images available for this type on controller\n        and on the compute node."
  },
  {
    "code": "def delcal(mspath):\n    wantremove = 'MODEL_DATA CORRECTED_DATA'.split()\n    tb = util.tools.table()\n    tb.open(b(mspath), nomodify=False)\n    cols = frozenset(tb.colnames())\n    toremove = [b(c) for c in wantremove if c in cols]\n    if len(toremove):\n        tb.removecols(toremove)\n    tb.close()\n    if six.PY2:\n        return toremove\n    else:\n        return [c.decode('utf8') for c in toremove]",
    "docstring": "Delete the ``MODEL_DATA`` and ``CORRECTED_DATA`` columns from a measurement set.\n\n    mspath (str)\n      The path to the MS to modify\n\n    Example::\n\n      from pwkit.environments.casa import tasks\n      tasks.delcal('dataset.ms')"
  },
  {
    "code": "def filter_accept_reftrack(self, reftrack):\n        if reftrack.status() in self._forbidden_status:\n            return False\n        if reftrack.get_typ() in self._forbidden_types:\n            return False\n        if reftrack.uptodate() in self._forbidden_uptodate:\n            return False\n        if reftrack.alien() in self._forbidden_alien:\n            return False\n        return True",
    "docstring": "Return True, if the filter accepts the given reftrack\n\n        :param reftrack: the reftrack to filter\n        :type reftrack: :class:`jukeboxcore.reftrack.Reftrack`\n        :returns: True, if the filter accepts the reftrack\n        :rtype: :class:`bool`\n        :raises: None"
  },
  {
    "code": "def input(input_id, name, value_class=NumberValue):\n        def _init():\n            return value_class(\n                name,\n                input_id=input_id,\n                is_input=True,\n                index=-1\n            )\n        def _decorator(cls):\n            setattr(cls, input_id, _init())\n            return cls\n        return _decorator",
    "docstring": "Add input to controller"
  },
  {
    "code": "def get_subgraphs(graph=None):\n    graph = graph or DEPENDENCIES\n    keys = set(graph)\n    frontier = set()\n    seen = set()\n    while keys:\n        frontier.add(keys.pop())\n        while frontier:\n            component = frontier.pop()\n            seen.add(component)\n            frontier |= set([d for d in get_dependencies(component) if d in graph])\n            frontier |= set([d for d in get_dependents(component) if d in graph])\n            frontier -= seen\n        yield dict((s, get_dependencies(s)) for s in seen)\n        keys -= seen\n        seen.clear()",
    "docstring": "Given a graph of possibly disconnected components, generate all graphs of\n    connected components. graph is a dictionary of dependencies. Keys are\n    components, and values are sets of components on which they depend."
  },
  {
    "code": "def split_and_load(arrs, ctx):\n    assert isinstance(arrs, (list, tuple))\n    loaded_arrs = [mx.gluon.utils.split_and_load(arr, ctx, even_split=False) for arr in arrs]\n    return zip(*loaded_arrs)",
    "docstring": "split and load arrays to a list of contexts"
  },
  {
    "code": "def encrypt_document(self, document_id, content, threshold=0):\n        return self._secret_store_client(self._account).publish_document(\n            remove_0x_prefix(document_id), content, threshold\n        )",
    "docstring": "encrypt string data using the DID as an secret store id,\n        if secret store is enabled then return the result from secret store encryption\n\n        None for no encryption performed\n\n        :param document_id: hex str id of document to use for encryption session\n        :param content: str to be encrypted\n        :param threshold: int\n        :return:\n            None -- if encryption failed\n            hex str -- the encrypted document"
  },
  {
    "code": "def igetattr(self, attrname, context=None):\n        if attrname == \"start\":\n            yield self._wrap_attribute(self.lower)\n        elif attrname == \"stop\":\n            yield self._wrap_attribute(self.upper)\n        elif attrname == \"step\":\n            yield self._wrap_attribute(self.step)\n        else:\n            yield from self.getattr(attrname, context=context)",
    "docstring": "Infer the possible values of the given attribute on the slice.\n\n        :param attrname: The name of the attribute to infer.\n        :type attrname: str\n\n        :returns: The inferred possible values.\n        :rtype: iterable(NodeNG)"
  },
  {
    "code": "def context_import(zap_helper, file_path):\n    with zap_error_handler():\n        result = zap_helper.zap.context.import_context(file_path)\n        if not result.isdigit():\n            raise ZAPError('Importing context from file failed: {}'.format(result))\n    console.info('Imported context from {}'.format(file_path))",
    "docstring": "Import a saved context file."
  },
  {
    "code": "def _get_path_for_op_id(self, id: str) -> Optional[str]:\n        for path_key, path_value in self._get_spec()['paths'].items():\n            for method in self.METHODS:\n                if method in path_value:\n                    if self.OPERATION_ID_KEY in path_value[method]:\n                        if path_value[method][self.OPERATION_ID_KEY] == id:\n                            return path_key\n        return None",
    "docstring": "Searches the spec for a path matching the operation id.\n\n        Args:\n            id: operation id\n\n        Returns:\n            path to the endpoint, or None if not found"
  },
  {
    "code": "def plot_seebeck_mu(self, temp=600, output='eig', xlim=None):\n        import matplotlib.pyplot as plt\n        plt.figure(figsize=(9, 7))\n        seebeck = self._bz.get_seebeck(output=output, doping_levels=False)[\n            temp]\n        plt.plot(self._bz.mu_steps, seebeck,\n                 linewidth=3.0)\n        self._plot_bg_limits()\n        self._plot_doping(temp)\n        if output == 'eig':\n            plt.legend(['S$_1$', 'S$_2$', 'S$_3$'])\n        if xlim is None:\n            plt.xlim(-0.5, self._bz.gap + 0.5)\n        else:\n            plt.xlim(xlim[0], xlim[1])\n        plt.ylabel(\"Seebeck \\n coefficient  ($\\\\mu$V/K)\", fontsize=30.0)\n        plt.xlabel(\"E-E$_f$ (eV)\", fontsize=30)\n        plt.xticks(fontsize=25)\n        plt.yticks(fontsize=25)\n        plt.tight_layout()\n        return plt",
    "docstring": "Plot the seebeck coefficient in function of Fermi level\n\n        Args:\n            temp:\n                the temperature\n            xlim:\n                a list of min and max fermi energy by default (0, and band gap)\n        Returns:\n            a matplotlib object"
  },
  {
    "code": "def skip_child(self, child, ancestry):\n        if child.any(): return True\n        for x in ancestry:\n            if x.choice():\n                return True\n        return False",
    "docstring": "get whether or not to skip the specified child"
  },
  {
    "code": "async def run_with_interrupt(task, *events, loop=None):\n    loop = loop or asyncio.get_event_loop()\n    task = asyncio.ensure_future(task, loop=loop)\n    event_tasks = [loop.create_task(event.wait()) for event in events]\n    done, pending = await asyncio.wait([task] + event_tasks,\n                                       loop=loop,\n                                       return_when=asyncio.FIRST_COMPLETED)\n    for f in pending:\n        f.cancel()\n    for f in done:\n        f.exception()\n    if task in done:\n        return task.result()\n    else:\n        return None",
    "docstring": "Awaits a task while allowing it to be interrupted by one or more\n    `asyncio.Event`s.\n\n    If the task finishes without the events becoming set, the results of the\n    task will be returned.  If the event become set, the task will be cancelled\n    ``None`` will be returned.\n\n    :param task: Task to run\n    :param events: One or more `asyncio.Event`s which, if set, will interrupt\n        `task` and cause it to be cancelled.\n    :param loop: Optional event loop to use other than the default."
  },
  {
    "code": "def add(self, connection):\n        if id(connection) in self.connections:\n            raise ValueError('Connection already exists in pool')\n        if len(self.connections) == self.max_size:\n            LOGGER.warning('Race condition found when adding new connection')\n            try:\n                connection.close()\n            except (psycopg2.Error, psycopg2.Warning) as error:\n                LOGGER.error('Error closing the conn that cant be used: %s',\n                             error)\n            raise PoolFullError(self)\n        with self._lock:\n            self.connections[id(connection)] = Connection(connection)\n        LOGGER.debug('Pool %s added connection %s', self.id, id(connection))",
    "docstring": "Add a new connection to the pool\n\n        :param connection: The connection to add to the pool\n        :type connection: psycopg2.extensions.connection\n        :raises: PoolFullError"
  },
  {
    "code": "def sync(filename, connection=None):\n    c = connection or connect()\n    rev = c.ls(filename)\n    if rev:\n        rev[0].sync()",
    "docstring": "Syncs a file\n\n    :param filename: File to check out\n    :type filename: str\n    :param connection: Connection object to use\n    :type connection: :py:class:`Connection`"
  },
  {
    "code": "def apply_karhunen_loeve_scaling(self):\n        cnames = copy.deepcopy(self.jco.col_names)\n        self.__jco *= self.fehalf\n        self.__jco.col_names = cnames\n        self.__parcov = self.parcov.identity",
    "docstring": "apply karhuene-loeve scaling to the jacobian matrix.\n\n        Note\n        ----\n        This scaling is not necessary for analyses using Schur's\n        complement, but can be very important for error variance\n        analyses.  This operation effectively transfers prior knowledge\n        specified in the parcov to the jacobian and reset parcov to the\n        identity matrix."
  },
  {
    "code": "def maybe_open(infile, mode='r'):\n    if isinstance(infile, basestring):\n        handle = open(infile, mode)\n        do_close = True\n    else:\n        handle = infile\n        do_close = False\n    yield handle\n    if do_close:\n        handle.close()",
    "docstring": "Take a file name or a handle, and return a handle.\n\n    Simplifies creating functions that automagically accept either a file name\n    or an already opened file handle."
  },
  {
    "code": "def loop_template_list(loop_positions, instance, instance_type,\n                       default_template, registry):\n    templates = []\n    local_loop_position = loop_positions[1]\n    global_loop_position = loop_positions[0]\n    instance_string = slugify(str(instance))\n    for key in ['%s-%s' % (instance_type, instance_string),\n                instance_string,\n                instance_type,\n                'default']:\n        try:\n            templates.append(registry[key][global_loop_position])\n        except KeyError:\n            pass\n    templates.append(\n        append_position(default_template, global_loop_position, '-'))\n    templates.append(\n        append_position(default_template, local_loop_position, '_'))\n    templates.append(default_template)\n    return templates",
    "docstring": "Build a list of templates from a position within a loop\n    and a registry of templates."
  },
  {
    "code": "def remove_unsupported_kwargs(module_or_fn, all_kwargs_dict):\n  if all_kwargs_dict is None:\n    all_kwargs_dict = {}\n  if not isinstance(all_kwargs_dict, dict):\n    raise ValueError(\"all_kwargs_dict must be a dict with string keys.\")\n  return {\n      kwarg: value for kwarg, value in all_kwargs_dict.items()\n      if supports_kwargs(module_or_fn, kwarg) != NOT_SUPPORTED\n  }",
    "docstring": "Removes any kwargs not supported by `module_or_fn` from `all_kwargs_dict`.\n\n  A new dict is return with shallow copies of keys & values from\n  `all_kwargs_dict`, as long as the key is accepted by module_or_fn. The\n  returned dict can then be used to connect `module_or_fn` (along with some\n  other inputs, ie non-keyword arguments, in general).\n\n  `snt.supports_kwargs` is used to tell whether a given kwarg is supported. Note\n  that this method may give false negatives, which would lead to extraneous\n  removals in the result of this function. Please read the docstring for\n  `snt.supports_kwargs` for details, and manually inspect the results from this\n  function if in doubt.\n\n  Args:\n    module_or_fn: some callable which can be interrogated by\n      `snt.supports_kwargs`. Generally a Sonnet module or a method (wrapped in\n      `@reuse_variables`) of a Sonnet module.\n    all_kwargs_dict: a dict containing strings as keys, or None.\n\n  Raises:\n    ValueError: if `all_kwargs_dict` is not a dict.\n\n  Returns:\n    A dict containing some subset of the keys and values in `all_kwargs_dict`.\n    This subset may be empty. If `all_kwargs_dict` is None, this will be an\n    empty dict."
  },
  {
    "code": "def ensure_str(text):\r\n    u\r\n    if isinstance(text, unicode):\r\n        try:\r\n            return text.encode(pyreadline_codepage, u\"replace\")\r\n        except (LookupError, TypeError):\r\n            return text.encode(u\"ascii\", u\"replace\")\r\n    return text",
    "docstring": "u\"\"\"Convert unicode to str using pyreadline_codepage"
  },
  {
    "code": "def _is_shadowed(self, reaction_id, database):\n        for other_database in self._databases:\n            if other_database == database:\n                break\n            if other_database.has_reaction(reaction_id):\n                return True\n        return False",
    "docstring": "Whether reaction in database is shadowed by another database"
  },
  {
    "code": "def process_multinest_run(file_root, base_dir, **kwargs):\n    dead = np.loadtxt(os.path.join(base_dir, file_root) + '-dead-birth.txt')\n    live = np.loadtxt(os.path.join(base_dir, file_root)\n                      + '-phys_live-birth.txt')\n    dead = dead[:, :-2]\n    live = live[:, :-1]\n    assert dead[:, -2].max() < live[:, -2].min(), (\n        'final live points should have greater logls than any dead point!',\n        dead, live)\n    ns_run = process_samples_array(np.vstack((dead, live)), **kwargs)\n    assert np.all(ns_run['thread_min_max'][:, 0] == -np.inf), (\n        'As MultiNest does not currently perform dynamic nested sampling, all '\n        'threads should start by sampling the whole prior.')\n    ns_run['output'] = {}\n    ns_run['output']['file_root'] = file_root\n    ns_run['output']['base_dir'] = base_dir\n    return ns_run",
    "docstring": "Loads data from a MultiNest run into the nestcheck dictionary format for\n    analysis.\n\n    N.B. producing required output file containing information about the\n    iso-likelihood contours within which points were sampled (where they were\n    \"born\") requies MultiNest version 3.11 or later.\n\n    Parameters\n    ----------\n    file_root: str\n        Root name for output files. When running MultiNest, this is determined\n        by the nest_root parameter.\n    base_dir: str\n        Directory containing output files. When running MultiNest, this is\n        determined by the nest_root parameter.\n    kwargs: dict, optional\n        Passed to ns_run_utils.check_ns_run (via process_samples_array)\n\n\n    Returns\n    -------\n    ns_run: dict\n        Nested sampling run dict (see the module docstring for more details)."
  },
  {
    "code": "def prepare(self,\n            method=None, url=None, headers=None, files=None, data=None,\n            params=None, auth=None, cookies=None, hooks=None, json=None):\n        self.prepare_method(method)\n        self.prepare_url(url, params)\n        self.prepare_headers(headers)\n        self.prepare_cookies(cookies)\n        self.prepare_body(data, files, json)\n        self.prepare_auth(auth, url)\n        self.prepare_hooks(hooks)",
    "docstring": "Prepares the entire request with the given parameters."
  },
  {
    "code": "def get_modname_from_modpath(module_fpath):\n    modsubdir_list = get_module_subdir_list(module_fpath)\n    modname = '.'.join(modsubdir_list)\n    modname = modname.replace('.__init__', '').strip()\n    modname = modname.replace('.__main__', '').strip()\n    return modname",
    "docstring": "returns importable name from file path\n\n    get_modname_from_modpath\n\n    Args:\n        module_fpath (str): module filepath\n\n    Returns:\n        str: modname\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_path import *  # NOQA\n        >>> import utool as ut\n        >>> module_fpath = ut.util_path.__file__\n        >>> modname = ut.get_modname_from_modpath(module_fpath)\n        >>> result = modname\n        >>> print(result)\n        utool.util_path"
  },
  {
    "code": "def set_power(self, state):\n    packet = bytearray(16)\n    packet[0] = 2\n    if self.check_nightlight():\n      packet[4] = 3 if state else 2\n    else:\n      packet[4] = 1 if state else 0\n    self.send_packet(0x6a, packet)",
    "docstring": "Sets the power state of the smart plug."
  },
  {
    "code": "def _check_for_dyn_timed_auto_backup(self):\n        current_time = time.time()\n        self.timer_request_lock.acquire()\n        if self._timer_request_time is None:\n            return self.timer_request_lock.release()\n        if self.timed_temp_storage_interval < current_time - self._timer_request_time:\n            self.check_for_auto_backup(force=True)\n        else:\n            duration_to_wait = self.timed_temp_storage_interval - (current_time - self._timer_request_time)\n            hard_limit_duration_to_wait = self.force_temp_storage_interval - (current_time - self.last_backup_time)\n            hard_limit_active = hard_limit_duration_to_wait < duration_to_wait\n            if hard_limit_active:\n                self.set_timed_thread(hard_limit_duration_to_wait, self.check_for_auto_backup, True)\n            else:\n                self.set_timed_thread(duration_to_wait, self._check_for_dyn_timed_auto_backup)\n        self.timer_request_lock.release()",
    "docstring": "The method implements the timed storage feature.\n\n         The method re-initiating a new timed thread if the state-machine not already stored to backup\n         (what could be caused by the force_temp_storage_interval) or force the storing of the state-machine if there\n         is no new request for a timed backup. New timed backup request are intrinsically represented by\n         self._timer_request_time and initiated by the check_for_auto_backup-method.\n         The feature uses only one thread for each ModificationHistoryModel and lock to be thread save."
  },
  {
    "code": "def create_thread(cls, session, conversation, thread, imported=False):\n        return super(Conversations, cls).create(\n            session,\n            thread,\n            endpoint_override='/conversations/%s.json' % conversation.id,\n            imported=imported,\n        )",
    "docstring": "Create a conversation thread.\n\n        Please note that threads cannot be added to conversations with 100\n        threads (or more), if attempted the API will respond with HTTP 412.\n\n        Args:\n            conversation (helpscout.models.Conversation): The conversation\n             that the thread is being added to.\n            session (requests.sessions.Session): Authenticated session.\n            thread (helpscout.models.Thread): The thread to be created.\n            imported (bool, optional): The ``imported`` request parameter\n             enables conversations to be created for historical purposes (i.e.\n             if moving from a different platform, you can import your\n             history). When ``imported`` is set to ``True``, no outgoing\n             emails or notifications will be generated.\n\n        Returns:\n            helpscout.models.Conversation: Conversation including newly created\n                thread."
  },
  {
    "code": "def deactivate_object(brain_or_object):\n    obj = get_object(brain_or_object)\n    if is_root(obj):\n        fail(401, \"Deactivating the Portal is not allowed\")\n    try:\n        do_transition_for(brain_or_object, \"deactivate\")\n    except Unauthorized:\n        fail(401, \"Not allowed to deactivate object '%s'\" % obj.getId())",
    "docstring": "Deactivate the given object\n\n    :param brain_or_object: A single catalog brain or content object\n    :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain\n    :returns: Nothing\n    :rtype: None"
  },
  {
    "code": "def get_offers_per_page(self, per_page=1000, page=1, params=None):\n        return self._get_resource_per_page(resource=OFFERS, per_page=per_page, page=page, params=params)",
    "docstring": "Get offers per page\n\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :param params: Search parameters. Default: {}\n        :return: list"
  },
  {
    "code": "def get_pex_python_paths():\n    ppp = Variables.from_rc().get('PEX_PYTHON_PATH')\n    if ppp:\n      return ppp.split(os.pathsep)\n    else:\n      return []",
    "docstring": "Returns a list of paths to Python interpreters as defined in a pexrc file.\n\n    These are provided by a PEX_PYTHON_PATH in either of '/etc/pexrc', '~/.pexrc'.\n    PEX_PYTHON_PATH defines a colon-separated list of paths to interpreters\n    that a pex can be built and run against."
  },
  {
    "code": "def uuid1mc_from_datetime(dt):\n    fields = list(uuid1mc().fields)\n    if isinstance(dt, datetime):\n        timeval = time.mktime(dt.timetuple()) + dt.microsecond / 1e6\n    else:\n        timeval = dt\n    nanoseconds = int(timeval * 1e9)\n    timestamp = int(nanoseconds // 100) + 0x01b21dd213814000\n    time_low = timestamp & 0xffffffff\n    time_mid = (timestamp >> 32) & 0xffff\n    time_hi_version = (timestamp >> 48) & 0x0fff\n    fields[0] = time_low\n    fields[1] = time_mid\n    fields[2] = time_hi_version\n    return uuid.UUID(fields=tuple(fields))",
    "docstring": "Return a UUID1 with a random multicast MAC id and with a timestamp\n    matching the given datetime object or timestamp value.\n\n    .. warning::\n        This function does not consider the timezone, and is not guaranteed to\n        return a unique UUID. Use under controlled conditions only.\n\n    >>> dt = datetime.now()\n    >>> u1 = uuid1mc()\n    >>> u2 = uuid1mc_from_datetime(dt)\n    >>> # Both timestamps should be very close to each other but not an exact match\n    >>> u1.time > u2.time\n    True\n    >>> u1.time - u2.time < 5000\n    True\n    >>> d2 = datetime.fromtimestamp((u2.time - 0x01b21dd213814000) * 100 / 1e9)\n    >>> d2 == dt\n    True"
  },
  {
    "code": "def create(self, unique_name=values.unset, data=values.unset):\n        data = values.of({'UniqueName': unique_name, 'Data': serialize.object(data), })\n        payload = self._version.create(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return DocumentInstance(self._version, payload, service_sid=self._solution['service_sid'], )",
    "docstring": "Create a new DocumentInstance\n\n        :param unicode unique_name: The unique_name\n        :param dict data: The data\n\n        :returns: Newly created DocumentInstance\n        :rtype: twilio.rest.preview.sync.service.document.DocumentInstance"
  },
  {
    "code": "def _GetRoutingMap(self, router):\n    try:\n      routing_map = self._routing_maps_cache.Get(router.__class__)\n    except KeyError:\n      routing_map = self._BuildHttpRoutingMap(router.__class__)\n      self._routing_maps_cache.Put(router.__class__, routing_map)\n    return routing_map",
    "docstring": "Returns a routing map for a given router instance."
  },
  {
    "code": "def primitive(self, primitive):\n        self.entry = Entry()\n        self.entry.primitive = primitive\n        primitive = copy(primitive)\n        for field in self.entry.fields:\n            del primitive[field]\n        self.item = Item()\n        self.item.primitive = primitive",
    "docstring": "Record from Python primitive."
  },
  {
    "code": "def info():\n    print(\"convenience function for listing prms\")\n    print(type(prms))\n    print(prms.__name__)\n    print(f\"prm file: {_get_prm_file()}\")\n    for key in prms.__dict__:\n        if isinstance(prms.__dict__[key], box.Box):\n            print()\n            print(80 * \"=\")\n            print(f\"prms.{key}:\")\n            print(80 * \"-\")\n            for subkey in prms.__dict__[key]:\n                print(\n                    f\"prms.{key}.{subkey} = \",\n                    f\"{prms.__dict__[key][subkey]}\"\n                )\n            print(80 * \"=\")",
    "docstring": "this function will show only the 'box'-type\n    attributes and their content in the cellpy.prms module"
  },
  {
    "code": "def line_is_interesting(self, line):\n        if line.startswith('Name'):\n            return None\n        if line.startswith('--------'):\n            return None\n        if line.startswith('TOTAL'):\n            return None\n        if '100%' in line:\n            return False\n        if line == '\\n':\n            return None if self._last_line_was_printable else False\n        return True",
    "docstring": "Return True, False, or None.\n\n        True means always output, False means never output, None means output\n        only if there are interesting lines."
  },
  {
    "code": "def center(self, axis=1):\n        if axis == 1:\n            return self.map(lambda x: x - mean(x))\n        elif axis == 0:\n            meanval = self.mean().toarray()\n            return self.map(lambda x: x - meanval)\n        else:\n            raise Exception('Axis must be 0 or 1')",
    "docstring": "Subtract the mean either within or across records.\n\n        Parameters\n        ----------\n        axis : int, optional, default = 1\n            Which axis to center along, within (1) or across (0) records."
  },
  {
    "code": "def update(self):\n        stats = self.get_init_value()\n        if self.input_method == 'local':\n            self.uptime = datetime.now() - datetime.fromtimestamp(psutil.boot_time())\n            stats = str(self.uptime).split('.')[0]\n        elif self.input_method == 'snmp':\n            uptime = self.get_stats_snmp(snmp_oid=snmp_oid)['_uptime']\n            try:\n                stats = str(timedelta(seconds=int(uptime) / 100))\n            except Exception:\n                pass\n        self.stats = stats\n        return self.stats",
    "docstring": "Update uptime stat using the input method."
  },
  {
    "code": "def process_email(ctx, param, value):\n    user = User.query.filter(User.email == value).first()\n    if not user:\n        raise click.BadParameter('User with email \\'%s\\' not found.', value)\n    return user",
    "docstring": "Return an user if it exists."
  },
  {
    "code": "async def delete(self, query, *, dc=None):\n        query_id = extract_attr(query, keys=[\"ID\"])\n        response = await self._api.delete(\"/v1/query\", query_id,\n                                          params={\"dc\": dc})\n        return response.status == 200",
    "docstring": "Delete existing prepared query\n\n        Parameters:\n            query (ObjectID): Query ID\n            dc (str): Specify datacenter that will be used.\n                      Defaults to the agent's local datacenter.\n        Results:\n            bool: ``True`` on success"
  },
  {
    "code": "def find_repo_type(self):\n        is_git = self.call(['git', 'rev-parse', '--is-inside-work-tree'],\n                           devnull=True)\n        if is_git != 0:\n            if self.debug:\n                click.echo('not git')\n            is_hg = self.call(['hg', '-q', 'stat'], devnull=True)\n            if is_hg != 0:\n                if self.debug:\n                    click.echo('not hg')\n                exit(1)\n            else:\n                self.vc_name = 'hg'",
    "docstring": "Check for git or hg repository"
  },
  {
    "code": "def call(self, method, *args, **kwargs):\n        tried_reconnect = False\n        for _ in range(2):\n            try:\n                self._send_call(self.deluge_version, self.deluge_protocol_version, method, *args, **kwargs)\n                return self._receive_response(self.deluge_version, self.deluge_protocol_version)\n            except (socket.error, ConnectionLostException, CallTimeoutException):\n                if self.automatic_reconnect:\n                    if tried_reconnect:\n                        raise FailedToReconnectException()\n                    else:\n                        try:\n                            self.reconnect()\n                        except (socket.error, ConnectionLostException, CallTimeoutException):\n                            raise FailedToReconnectException()\n                    tried_reconnect = True\n                else:\n                    raise",
    "docstring": "Calls an RPC function"
  },
  {
    "code": "def _get(self, url: str) -> str:\n        resp = self.session.get(url, headers=self.HEADERS)\n        if resp.status_code is 200:\n            return resp.text\n        else:\n            raise RuneConnectionError(resp.status_code)",
    "docstring": "A small wrapper method which makes a quick GET request.\n\n        Parameters\n        ----------\n        url : str\n            The URL to get.\n\n        Returns\n        -------\n        str\n            The raw html of the requested page.\n\n        Raises\n        ------\n        RuneConnectionError\n            If the GET response status is not 200."
  },
  {
    "code": "def get_all_bandwidth_groups(self):\n        bandwidth_groups = self._call(\"getAllBandwidthGroups\")\n        bandwidth_groups = [IBandwidthGroup(a) for a in bandwidth_groups]\n        return bandwidth_groups",
    "docstring": "Get all managed bandwidth groups.\n\n        return bandwidth_groups of type :class:`IBandwidthGroup`\n            The array of managed bandwidth groups."
  },
  {
    "code": "def get_relation_kwargs(field_name, relation_info):\n    model_field, related_model = relation_info\n    kwargs = {}\n    if related_model and not issubclass(related_model, EmbeddedDocument):\n        kwargs['queryset'] = related_model.objects\n    if model_field:\n        if hasattr(model_field, 'verbose_name') and needs_label(model_field, field_name):\n            kwargs['label'] = capfirst(model_field.verbose_name)\n        if hasattr(model_field, 'help_text'):\n            kwargs['help_text'] = model_field.help_text\n        kwargs['required'] = model_field.required\n        if model_field.null:\n            kwargs['allow_null'] = True\n        if getattr(model_field, 'unique', False):\n            validator = UniqueValidator(queryset=related_model.objects)\n            kwargs['validators'] = [validator]\n    return kwargs",
    "docstring": "Creating a default instance of a flat relational field."
  },
  {
    "code": "def pivot_bin(self, pivot_columns, value_column, bins=None, **vargs) :\n        pivot_columns = _as_labels(pivot_columns)\n        selected = self.select(pivot_columns + [value_column])\n        grouped = selected.groups(pivot_columns, collect=lambda x:x)\n        if bins is not None:\n            vargs['bins'] = bins\n        _, rbins = np.histogram(self[value_column],**vargs)\n        vargs['bins'] = rbins\n        binned = type(self)().with_column('bin',rbins)\n        for group in grouped.rows:\n            col_label = \"-\".join(map(str,group[0:-1]))\n            col_vals = group[-1]\n            counts,_ = np.histogram(col_vals,**vargs)\n            binned[col_label] = np.append(counts,0)\n        return binned",
    "docstring": "Form a table with columns formed by the unique tuples in pivot_columns\n        containing counts per bin of the values associated with each tuple in the value_column.\n\n        By default, bins are chosen to contain all values in the value_column. The\n        following named arguments from numpy.histogram can be applied to\n        specialize bin widths:\n\n        Args:\n            ``bins`` (int or sequence of scalars): If bins is an int,\n                it defines the number of equal-width bins in the given range\n                (10, by default). If bins is a sequence, it defines the bin\n                edges, including the rightmost edge, allowing for non-uniform\n                bin widths.\n\n            ``range`` ((float, float)): The lower and upper range of\n                the bins. If not provided, range contains all values in the\n                table. Values outside the range are ignored.\n\n            ``normed`` (bool): If False, the result will contain the number of\n                samples in each bin. If True, the result is normalized such that\n                the integral over the range is 1."
  },
  {
    "code": "def to_user_agent(self):\n        ua = \"\"\n        if self.user_agent is not None:\n            ua += \"{user_agent} \"\n        ua += \"gl-python/{python_version} \"\n        if self.grpc_version is not None:\n            ua += \"grpc/{grpc_version} \"\n        ua += \"gax/{api_core_version} \"\n        if self.gapic_version is not None:\n            ua += \"gapic/{gapic_version} \"\n        if self.client_library_version is not None:\n            ua += \"gccl/{client_library_version} \"\n        return ua.format(**self.__dict__).strip()",
    "docstring": "Returns the user-agent string for this client info."
  },
  {
    "code": "def num_adjacent(self, i, j):\n        if i < 1 or i > self.height - 2 or j < 1 and j > self.width - 2:\n            raise ValueError('Pixels out of bounds')\n        count = 0\n        diffs = [[-1, 0], [1, 0], [0, -1], [0, 1]]\n        for d in diffs:\n            if self.data[i + d[0]][j + d[1]] > self._threshold:\n                count += 1\n        return count",
    "docstring": "Counts the number of adjacent nonzero pixels to a given pixel.\n\n        Parameters\n        ----------\n        i : int\n            row index of query pixel\n        j : int\n            col index of query pixel\n\n        Returns\n        -------\n        int\n            number of adjacent nonzero pixels"
  },
  {
    "code": "def _inhibitColumnsWithLateral(self, overlaps, lateralConnections):\n    n,m = self.shape\n    y   = np.zeros(n)\n    s   = self.sparsity\n    L   = lateralConnections\n    desiredWeight = self.codeWeight\n    inhSignal     = np.zeros(n)\n    sortedIndices = np.argsort(overlaps, kind='mergesort')[::-1]\n    currentWeight = 0\n    for i in sortedIndices:\n      if overlaps[i] < self._stimulusThreshold:\n        break\n      inhTooStrong = ( inhSignal[i] >= s )\n      if not inhTooStrong:\n        y[i]              = 1.\n        currentWeight    += 1\n        inhSignal[:]     += L[i,:]\n      if self.enforceDesiredWeight and currentWeight == desiredWeight:\n        break\n    activeColumns = np.where(y==1.0)[0]\n    return activeColumns",
    "docstring": "Performs an experimentatl local inhibition. Local inhibition is \n    iteratively performed on a column by column basis."
  },
  {
    "code": "def rollback(self, date):\n        if self.onOffset(date):\n            return date\n        else:\n            return date - YearEnd(month=self.month)",
    "docstring": "Roll date backward to nearest end of year"
  },
  {
    "code": "def set_link(self, prop, value):\n        if not isinstance(value, URIRef):\n            value = URIRef(value)\n        self.metadata.add(prop, value)",
    "docstring": "Set given link in CTS Namespace\n\n        .. example::\n            collection.set_link(NAMESPACES.CTS.about, \"urn:cts:latinLit:phi1294.phi002\")\n\n        :param prop: Property to set (Without namespace)\n        :param value: Value to set for given property"
  },
  {
    "code": "def _feature_first_back(self, results):\n        try:\n            first_back = results['hits']['hits'][0]['country_code3']\n        except (TypeError, IndexError):\n            first_back = \"\"\n        try:\n            second_back = results['hits']['hits'][1]['country_code3']\n        except (TypeError, IndexError):\n            second_back = \"\"\n        top = (first_back, second_back)\n        return top",
    "docstring": "Get the country of the first two results back from geonames.\n\n        Parameters\n        -----------\n        results: dict\n            elasticsearch results\n\n        Returns\n        -------\n        top: tuple\n            first and second results' country name (ISO)"
  },
  {
    "code": "def lincon(self, x, theta=0.01):\n        if x[0] < 0:\n            return np.NaN\n        return theta * x[1] + x[0]",
    "docstring": "ridge like linear function with one linear constraint"
  },
  {
    "code": "def make_block_same_class(self, values, placement=None, ndim=None,\n                              dtype=None):\n        if dtype is not None:\n            warnings.warn(\"dtype argument is deprecated, will be removed \"\n                          \"in a future release.\", DeprecationWarning)\n        if placement is None:\n            placement = self.mgr_locs\n        return make_block(values, placement=placement, ndim=ndim,\n                          klass=self.__class__, dtype=dtype)",
    "docstring": "Wrap given values in a block of same type as self."
  },
  {
    "code": "def DbDeleteClassProperty(self, argin):\n        self._log.debug(\"In DbDeleteClassProperty()\")\n        klass_name = argin[0]\n        for prop_name in argin[1:]:\n            self.db.delete_class_property(prop_name)",
    "docstring": "Delete class properties from database\n\n        :param argin: Str[0] = Tango class name\n        Str[1] = Property name\n        Str[n] = Property name\n        :type: tango.DevVarStringArray\n        :return:\n        :rtype: tango.DevVoid"
  },
  {
    "code": "def plotChIds(self, maptype=None, modout=False):\n        if maptype is None:\n            maptype = self.defaultMap\n        polyList = self.getAllChannelsAsPolygons(maptype)\n        for p in polyList:\n            p.identifyModule(modout=modout)",
    "docstring": "Print the channel numbers on the plotting display\n\n        Note:\n        ---------\n        This method will behave poorly if you are plotting in\n        mixed projections. Because the channel vertex polygons\n        are already projected using self.defaultMap, applying\n        this function when plotting in a different reference frame\n        may cause trouble."
  },
  {
    "code": "def _dispatch_gen(self):\n        if not os.path.isdir(self._args.output):\n            raise exception.Base(\"%s is not a writeable directory\" % self._args.output)\n        if not os.path.isfile(self._args.models_definition):\n            if not self.check_package_exists(self._args.models_definition):\n                raise exception.Base(\"failed to locate package or models definitions file at: %s\" % self._args.models_definition)\n        from prestans.devel.gen import Preplate\n        preplate = Preplate(\n            template_type=self._args.template,\n            models_definition=self._args.models_definition,\n            namespace=self._args.namespace,\n            filter_namespace=self._args.filter_namespace,\n            output_directory=self._args.output)\n        preplate.run()",
    "docstring": "Process the generate subset of commands."
  },
  {
    "code": "def get_fields(self, serializer_fields):\n        fields = OrderedDict()\n        for field_name, field in serializer_fields.items():\n            if field_name == 'tags':\n                continue\n            info = self.get_field_info(field, field_name)\n            if info:\n                fields[field_name] = info\n        return fields",
    "docstring": "Get fields metadata skipping empty fields"
  },
  {
    "code": "def _handle_function_call(tokens, tokens_len, index):\n    def _end_function_call(token_index, tokens):\n        return tokens[token_index].type == TokenType.RightParen\n    next_index, call_body = _ast_worker(tokens, tokens_len,\n                                        index + 2,\n                                        _end_function_call)\n    function_call = FunctionCall(name=tokens[index].content,\n                                 arguments=call_body.arguments,\n                                 line=tokens[index].line,\n                                 col=tokens[index].col,\n                                 index=index)\n    try:\n        handler = _FUNCTION_CALL_DISAMBIGUATE[tokens[index].content.lower()]\n    except KeyError:\n        handler = None\n    if handler:\n        return handler(tokens, tokens_len, next_index, function_call)\n    else:\n        return (next_index, function_call)",
    "docstring": "Handle function calls, which could include a control statement.\n\n    In CMake, all control flow statements are also function calls, so handle\n    the function call first and then direct tree construction to the\n    appropriate control flow statement constructor found in\n    _FUNCTION_CALL_DISAMBIGUATE"
  },
  {
    "code": "def serialize_tag(tag, *, indent=None, compact=False, quote=None):\n    serializer = Serializer(indent=indent, compact=compact, quote=quote)\n    return serializer.serialize(tag)",
    "docstring": "Serialize an nbt tag to its literal representation."
  },
  {
    "code": "def conj_phrase(list_, cond='or'):\n    if len(list_) == 0:\n        return ''\n    elif len(list_) == 1:\n        return list_[0]\n    elif len(list_) == 2:\n        return ' '.join((list_[0], cond, list_[1]))\n    else:\n        condstr = ''.join((', ' + cond, ' '))\n        return ', '.join((', '.join(list_[:-2]), condstr.join(list_[-2:])))",
    "docstring": "Joins a list of words using English conjunction rules\n\n    Args:\n        list_ (list):  of strings\n        cond (str): a conjunction (or, and, but)\n\n    Returns:\n        str: the joined cconjunction phrase\n\n    References:\n        http://en.wikipedia.org/wiki/Conjunction_(grammar)\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_str import *  # NOQA\n        >>> list_ = ['a', 'b', 'c']\n        >>> result = conj_phrase(list_, 'or')\n        >>> print(result)\n        a, b, or c\n\n    Example1:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_str import *  # NOQA\n        >>> list_ = ['a', 'b']\n        >>> result = conj_phrase(list_, 'and')\n        >>> print(result)\n        a and b"
  },
  {
    "code": "def header(self, method, client='htmlshark'):\n        return {'token': self._request_token(method, client),\n                'privacy': 0,\n                'uuid': self.session.user,\n                'clientRevision': grooveshark.const.CLIENTS[client]['version'],\n                'session': self.session.session,\n                'client': client,\n                'country': self.session.country}",
    "docstring": "generates Grooveshark API Json header"
  },
  {
    "code": "def serialize(self, raw=False):\n        if raw:\n            return self._key.encode()\n        return self._key.encode(nacl.encoding.Base64Encoder)",
    "docstring": "Encode the private part of the key in a base64 format by default,\n        but when raw is True it will return hex encoded bytes.\n        @return: bytes"
  },
  {
    "code": "def random_line(file_path: str, encoding: str = FORCED_ENCODING) -> str:\n    line_num = 0\n    selected_line = \"\"\n    with open(file_path, encoding=encoding) as stream:\n        while True:\n            line = stream.readline()\n            if not line:\n                break\n            line_num += 1\n            if random.uniform(0, line_num) < 1:\n                selected_line = line\n    return selected_line.strip()",
    "docstring": "Get random line from a file."
  },
  {
    "code": "def setspan(self, *args):\n        self.data = []\n        for child in args:\n            self.append(child)",
    "docstring": "Sets the span of the span element anew, erases all data inside.\n\n        Arguments:\n            *args: Instances of :class:`Word`, :class:`Morpheme` or :class:`Phoneme`"
  },
  {
    "code": "def channelModeModifyAcknowledge():\n    a = TpPd(pd=0x6)\n    b = MessageType(mesType=0x17)\n    c = ChannelDescription2()\n    d = ChannelMode()\n    packet = a / b / c / d\n    return packet",
    "docstring": "CHANNEL MODE MODIFY ACKNOWLEDGE Section 9.1.6"
  },
  {
    "code": "def make_monitoring_log(level, message, timestamp=None, to_logger=False):\n    level = level.lower()\n    if level not in ['debug', 'info', 'warning', 'error', 'critical']:\n        return False\n    if to_logger:\n        logging.getLogger(ALIGNAK_LOGGER_NAME).debug(\"Monitoring log: %s / %s\", level, message)\n        message = message.replace('\\r', '\\\\r')\n        message = message.replace('\\n', '\\\\n')\n        logger_ = logging.getLogger(MONITORING_LOGGER_NAME)\n        logging_function = getattr(logger_, level)\n        try:\n            message = message.decode('utf8', 'ignore')\n        except UnicodeEncodeError:\n            pass\n        except AttributeError:\n            pass\n        if timestamp:\n            st = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')\n            logging_function(message, extra={'my_date': st})\n        else:\n            logging_function(message)\n        return True\n    return Brok({'type': 'monitoring_log', 'data': {'level': level, 'message': message}})",
    "docstring": "Function used to build the monitoring log.\n\n    Emit a log message with the provided level to the monitoring log logger.\n    Build a Brok typed as monitoring_log with the provided message\n\n    When to_logger is True, the information is sent to the python logger, else a monitoring_log\n    Brok is returned. The Brok is managed by the daemons to build an Event that will br logged\n    by the Arbiter when it collects all the events.\n\n    TODO: replace with dedicated brok for each event to log - really useful?\n\n    :param level: log level as defined in logging\n    :type level: str\n    :param message: message to send to the monitoring log logger\n    :type message: str\n    :param to_logger: when set, send to the logger, else raise a brok\n    :type to_logger: bool\n    :param timestamp: if set, force the log event timestamp\n    :return: a monitoring_log Brok\n    :rtype: alignak.brok.Brok"
  },
  {
    "code": "def build_graph(self):\n        for child, parents in self.dependencies.items():\n            if child not in self.nodes:\n                raise NodeNotFoundError(\n                    \"App %s SQL item dependencies reference nonexistent child node %r\" % (\n                        child[0], child),\n                    child\n                )\n            for parent in parents:\n                if parent not in self.nodes:\n                    raise NodeNotFoundError(\n                        \"App %s SQL item dependencies reference nonexistent parent node %r\" % (\n                            child[0], parent),\n                        parent\n                    )\n                self.node_map[child].add_parent(self.node_map[parent])\n                self.node_map[parent].add_child(self.node_map[child])\n        for node in self.nodes:\n            self.ensure_not_cyclic(node,\n                                   lambda x: (parent.key for parent in self.node_map[x].parents))",
    "docstring": "Read lazy dependency list and build graph."
  },
  {
    "code": "def get_killer(args):\n    if POSIX:\n        log.debug('Platform: POSIX')\n        from killer.killer_posix import KillerPosix\n        return KillerPosix(config_path=args.config, debug=args.debug)\n    elif WINDOWS:\n        log.debug('Platform: Windows')\n        from killer.killer_windows import KillerWindows\n        return KillerWindows(config_path=args.config, debug=args.debug)\n    else:\n        raise NotImplementedError(\"Your platform is not currently supported.\"\n                                  \"If you would like support to be added, or \"\n                                  \"if your platform is supported and this is \"\n                                  \"a bug, please open an issue on GitHub!\")",
    "docstring": "Returns a KillerBase instance subclassed based on the OS."
  },
  {
    "code": "def from_string(cls, string, *, default_func=None):\n        if not isinstance(string, str):\n            raise TypeError(f'service must be a string: {string}')\n        parts = string.split('://', 1)\n        if len(parts) == 2:\n            protocol, address = parts\n        else:\n            item, = parts\n            protocol = None\n            if default_func:\n                if default_func(item, ServicePart.HOST) and default_func(item, ServicePart.PORT):\n                    protocol, address = item, ''\n                else:\n                    protocol, address = default_func(None, ServicePart.PROTOCOL), item\n            if not protocol:\n                raise ValueError(f'invalid service string: {string}')\n        if default_func:\n            default_func = partial(default_func, protocol.lower())\n        address = NetAddress.from_string(address, default_func=default_func)\n        return cls(protocol, address)",
    "docstring": "Construct a Service from a string.\n\n        If default_func is provided and any ServicePart is missing, it is called with\n        default_func(protocol, part) to obtain the missing part."
  },
  {
    "code": "def volume_create(self, label, region=None, linode=None, size=20, **kwargs):\n        if not (region or linode):\n            raise ValueError('region or linode required!')\n        params = {\n            \"label\": label,\n            \"size\": size,\n            \"region\": region.id if issubclass(type(region), Base) else region,\n            \"linode_id\": linode.id if issubclass(type(linode), Base) else linode,\n        }\n        params.update(kwargs)\n        result = self.post('/volumes', data=params)\n        if not 'id' in result:\n            raise UnexpectedResponseError('Unexpected response when creating volume!', json=result)\n        v = Volume(self, result['id'], result)\n        return v",
    "docstring": "Creates a new Block Storage Volume, either in the given Region or\n        attached to the given Instance.\n\n        :param label: The label for the new Volume.\n        :type label: str\n        :param region: The Region to create this Volume in.  Not required if\n                       `linode` is provided.\n        :type region: Region or str\n        :param linode: The Instance to attach this Volume to.  If not given, the\n                       new Volume will not be attached to anything.\n        :type linode: Instance or int\n        :param size: The size, in GB, of the new Volume.  Defaults to 20.\n        :type size: int\n\n        :returns: The new Volume.\n        :rtype: Volume"
  },
  {
    "code": "def make_path(base_uri, path, filename, path_dimensions, split_length):\n    assert len(path) > path_dimensions * split_length\n    uri_parts = []\n    for i in range(path_dimensions):\n        uri_parts.append(path[0:split_length])\n        path = path[split_length:]\n    uri_parts.append(path)\n    uri_parts.append(filename)\n    return os.path.join(base_uri, *uri_parts)",
    "docstring": "Generate a path as base location for file instance.\n\n    :param base_uri: The base URI.\n    :param path: The relative path.\n    :param path_dimensions: Number of chunks the path should be split into.\n    :param split_length: The length of any chunk.\n    :returns: A string representing the full path."
  },
  {
    "code": "def draw(self):\n        self.draw_nodes()\n        self.draw_edges()\n        if hasattr(self, \"groups\") and self.groups:\n            self.draw_group_labels()\n        logging.debug(\"DRAW: {0}\".format(self.sm))\n        if self.sm:\n            self.figure.subplots_adjust(right=0.8)\n            cax = self.figure.add_axes([0.85, 0.2, 0.05, 0.6])\n            self.figure.colorbar(self.sm, cax=cax)\n        self.ax.relim()\n        self.ax.autoscale_view()\n        self.ax.set_aspect(\"equal\")",
    "docstring": "Draws the Plot to screen.\n\n        If there is a continuous datatype for the nodes, it will be reflected\n        in self.sm being constructed (in `compute_node_colors`). It will then\n        automatically add in a colorbar to the plot and scale the plot axes\n        accordingly."
  },
  {
    "code": "def distance_landscape_as_3d_data(self, x_axis, y_axis):\n        if not self.distance_landscape:\n            raise Exception('No distance landscape returned. Re-run inference with return_distance_landscape=True')\n        index_x = self.parameter_index(x_axis)\n        index_y = self.parameter_index(y_axis)\n        x = []\n        y = []\n        z = []\n        for parameters, initial_conditions, distance in self.distance_landscape:\n            all_values = list(parameters) + list(initial_conditions)\n            x.append(all_values[index_x])\n            y.append(all_values[index_y])\n            z.append(distance)\n        return x, y, z",
    "docstring": "Returns the distance landscape as three-dimensional data for the specified projection.\n\n        :param x_axis: variable to be plotted on the x axis of projection\n        :param y_axis: variable to be plotted on the y axis of projection\n        :return: a 3-tuple (x, y, z) where x and y are the lists of coordinates and z the list of distances at\n                 respective coordinates"
  },
  {
    "code": "def get_variant_slice(self, package_name, range_):\n        variant_list = self.variant_lists.get(package_name)\n        if variant_list is None:\n            variant_list = _PackageVariantList(package_name, self.solver)\n            self.variant_lists[package_name] = variant_list\n        entries = variant_list.get_intersection(range_)\n        if not entries:\n            return None\n        slice_ = _PackageVariantSlice(package_name,\n                                      entries=entries,\n                                      solver=self.solver)\n        return slice_",
    "docstring": "Get a list of variants from the cache.\n\n        Args:\n            package_name (str): Name of package.\n            range_ (`VersionRange`): Package version range.\n\n        Returns:\n            `_PackageVariantSlice` object."
  },
  {
    "code": "def stop_refreshing_token(self):\n        with self.lock:\n            self.timer_stopped = True\n            self.timer.cancel()",
    "docstring": "The timer needs to be canceled if the application is terminating, if not the timer will keep going."
  },
  {
    "code": "def intToID(idnum, prefix):\n    rid = ''\n    while idnum > 0:\n        idnum -= 1\n        rid = chr((idnum % 26) + ord('a')) + rid\n        idnum = int(idnum / 26)\n    return prefix + rid",
    "docstring": "Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z,\n    then from aa to az, ba to bz, etc., until zz."
  },
  {
    "code": "def remove_role_from_user(user, role):\n    user = _query_to_user(user)\n    role = _query_to_role(role)\n    if click.confirm(f'Are you sure you want to remove {role!r} from {user!r}?'):\n        user.roles.remove(role)\n        user_manager.save(user, commit=True)\n        click.echo(f'Successfully removed {role!r} from {user!r}')\n    else:\n        click.echo('Cancelled.')",
    "docstring": "Remove a role from a user."
  },
  {
    "code": "def signMsg(self,\n                msg: Dict,\n                identifier: Identifier=None,\n                otherIdentifier: Identifier=None):\n        idr = self.requiredIdr(idr=identifier or otherIdentifier)\n        signer = self._signerById(idr)\n        signature = signer.sign(msg)\n        return signature",
    "docstring": "Creates signature for message using specified signer\n\n        :param msg: message to sign\n        :param identifier: signer identifier\n        :param otherIdentifier:\n        :return: signature that then can be assigned to request"
  },
  {
    "code": "def create(self, to, media_url, quality=values.unset,\n               status_callback=values.unset, from_=values.unset,\n               sip_auth_username=values.unset, sip_auth_password=values.unset,\n               store_media=values.unset, ttl=values.unset):\n        data = values.of({\n            'To': to,\n            'MediaUrl': media_url,\n            'Quality': quality,\n            'StatusCallback': status_callback,\n            'From': from_,\n            'SipAuthUsername': sip_auth_username,\n            'SipAuthPassword': sip_auth_password,\n            'StoreMedia': store_media,\n            'Ttl': ttl,\n        })\n        payload = self._version.create(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return FaxInstance(self._version, payload, )",
    "docstring": "Create a new FaxInstance\n\n        :param unicode to: The phone number to receive the fax\n        :param unicode media_url: The Twilio-hosted URL of the PDF that contains the fax\n        :param FaxInstance.Quality quality: The quality of this fax\n        :param unicode status_callback: The URL we should call to send status information to your application\n        :param unicode from_: The number the fax was sent from\n        :param unicode sip_auth_username: The username for SIP authentication\n        :param unicode sip_auth_password: The password for SIP authentication\n        :param bool store_media: Whether to store a copy of the sent media\n        :param unicode ttl: How long in minutes to try to send the fax\n\n        :returns: Newly created FaxInstance\n        :rtype: twilio.rest.fax.v1.fax.FaxInstance"
  },
  {
    "code": "def disable(iface):\n    if is_disabled(iface):\n        return True\n    cmd = ['netsh', 'interface', 'set', 'interface',\n           'name={0}'.format(iface),\n           'admin=DISABLED']\n    __salt__['cmd.run'](cmd, python_shell=False)\n    return is_disabled(iface)",
    "docstring": "Disable an interface\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt -G 'os_family:Windows' ip.disable 'Local Area Connection #2'"
  },
  {
    "code": "def dim_range_key(eldim):\n    if isinstance(eldim, dim):\n        dim_name = repr(eldim)\n        if dim_name.startswith(\"'\") and dim_name.endswith(\"'\"):\n            dim_name = dim_name[1:-1]\n    else:\n        dim_name = eldim.name\n    return dim_name",
    "docstring": "Returns the key to look up a dimension range."
  },
  {
    "code": "def parse_xml_node(self, node):\n        if node.getElementsByTagNameNS(RTS_NS, 'Participant').length != 1:\n            raise InvalidParticipantNodeError\n        self.target_component = TargetComponent().parse_xml_node(\\\n                node.getElementsByTagNameNS(RTS_NS, 'Participant')[0])\n        return self",
    "docstring": "Parse an xml.dom Node object representing a participant into this\n        object."
  },
  {
    "code": "def _compute_sync_map_file_path(\n            self,\n            root,\n            hierarchy_type,\n            custom_id,\n            file_name\n    ):\n        prefix = root\n        if hierarchy_type == HierarchyType.PAGED:\n            prefix = gf.norm_join(prefix, custom_id)\n        file_name_joined = gf.norm_join(prefix, file_name)\n        return self._replace_placeholder(file_name_joined, custom_id)",
    "docstring": "Compute the sync map file path inside the output container.\n\n        :param string root: the root of the sync map files inside the container\n        :param job_os_hierarchy_type: type of job output hierarchy\n        :type  job_os_hierarchy_type: :class:`~aeneas.hierarchytype.HierarchyType`\n        :param string custom_id: the task custom id (flat) or\n                                 page directory name (paged)\n        :param string file_name: the output file name for the sync map\n        :rtype: string"
  },
  {
    "code": "def write_xml(self):\n        key = None\n        if self. language is not None:\n            lang = {}\n            lang['{http://www.w3.org/XML/1998/namespace}lang'] = self.language\n            key = etree.Element('vocabulary-key', attrib=lang)\n        else:\n            key = etree.Element('vocabulary-key')\n        name = etree.Element('name')\n        name.text = self.name\n        key.append(name)\n        if self.family is not None:\n            family = etree.Element('family')\n            family.text = self.family\n            key.append(family)\n        if self.version is not None:\n            version = etree.Element('version')\n            version.text = self.version\n            key.append(version)\n        if self.code_value is not None:\n            code_value = etree.Element('code-value')\n            code_value.text = self.code_value\n            key.append(code_value)\n        return key",
    "docstring": "Writes a VocabularyKey Xml as per Healthvault schema.\n\n            :returns: lxml.etree.Element representing a single VocabularyKey"
  },
  {
    "code": "def _import_ucsmsdk(self):\n        if not CONF.ml2_cisco_ucsm.ucsm_https_verify:\n            LOG.warning(const.SSL_WARNING)\n        from networking_cisco.ml2_drivers.ucsm import ucs_ssl\n        ucs_driver = importutils.import_module('ucsmsdk.ucsdriver')\n        ucs_driver.ssl = ucs_ssl\n        class ucsmsdk(object):\n            handle = importutils.import_class(\n                    'ucsmsdk.ucshandle.UcsHandle')\n            fabricVlan = importutils.import_class(\n                    'ucsmsdk.mometa.fabric.FabricVlan.FabricVlan')\n            vnicProfile = importutils.import_class(\n                    'ucsmsdk.mometa.vnic.VnicProfile.VnicProfile')\n            vnicEtherIf = importutils.import_class(\n                    'ucsmsdk.mometa.vnic.VnicEtherIf.VnicEtherIf')\n            vmVnicProfCl = importutils.import_class(\n                    'ucsmsdk.mometa.vm.VmVnicProfCl.VmVnicProfCl')\n        return ucsmsdk",
    "docstring": "Imports the ucsmsdk module.\n\n        This module is not installed as part of the normal Neutron\n        distributions. It is imported dynamically in this module so that\n        the import can be mocked, allowing unit testing without requiring\n        the installation of ucsmsdk."
  },
  {
    "code": "def _write_vcf_breakend(brend, out_handle):\n    out_handle.write(\"{0}\\n\".format(\"\\t\".join(str(x) for x in\n        [brend.chrom, brend.pos + 1, brend.id, brend.ref, brend.alt,\n         \".\", \"PASS\", brend.info])))",
    "docstring": "Write out a single VCF line with breakpoint information."
  },
  {
    "code": "def _query_api(self, method, url, fields=None, extra_headers=None, req_body=None):\n        with self.auth.authenticate() as token:\n            logging.debug('PA Authentication returned token %s', token)\n            headers = {\n                'Authorization': 'Bearer %s' % (token,),\n                'Realm': self.auth_realm\n            }\n            if extra_headers is not None:\n                headers.update(extra_headers)\n            logging.info('[%s] %s', method, url)\n            if req_body is not None:\n                response = self.http.request(method, url, fields, headers, body=req_body)\n            else:\n                response = self.http.request(method, url, fields, headers)                \n            if response.status != 200:\n                print(response.data)\n                logging.warning('Got non-200 HTTP status from API: %d', response.status)\n                raise ApiQueryError(\"Failed to get API data\", response.status)\n            return json.loads(response.data.decode())",
    "docstring": "Abstracts http queries to the API"
  },
  {
    "code": "def get_current_temperature(self, refresh=False):\n        if refresh:\n            self.refresh()\n        try:\n            return float(self.get_value('temperature'))\n        except (TypeError, ValueError):\n            return None",
    "docstring": "Get current temperature"
  },
  {
    "code": "def result(self):\n        if not self._result:\n            if not self._persistence_engine:\n                return None\n            self._result = self._persistence_engine.get_context_result(self)\n        return self._result",
    "docstring": "Return the context result object pulled from the persistence_engine\n        if it has been set."
  },
  {
    "code": "def heartbeat(self):\n        if self._rpc is not None and self._rpc.is_active:\n            self._rpc.send(types.StreamingPullRequest())",
    "docstring": "Sends an empty request over the streaming pull RPC.\n\n        This always sends over the stream, regardless of if\n        ``self._UNARY_REQUESTS`` is set or not."
  },
  {
    "code": "def __is_block_data_move(self):\n        block_data_move_instructions = ('movs', 'stos', 'lods')\n        isBlockDataMove = False\n        instruction = None\n        if self.pc is not None and self.faultDisasm:\n            for disasm in self.faultDisasm:\n                if disasm[0] == self.pc:\n                    instruction = disasm[2].lower().strip()\n                    break\n        if instruction:\n            for x in block_data_move_instructions:\n                if x in instruction:\n                    isBlockDataMove = True\n                    break\n        return isBlockDataMove",
    "docstring": "Private method to tell if the instruction pointed to by the program\n        counter is a block data move instruction.\n\n        Currently only works for x86 and amd64 architectures."
  },
  {
    "code": "def _compile_path_pattern(pattern):\n    r\n    def replace_variable(match):\n      if match.lastindex > 1:\n        var_name = ApiConfigManager._to_safe_path_param_name(match.group(2))\n        return '%s(?P<%s>%s)' % (match.group(1), var_name,\n                                 _PATH_VALUE_PATTERN)\n      return match.group(0)\n    pattern = re.sub('(/|^){(%s)}(?=/|$|:)' % _PATH_VARIABLE_PATTERN,\n                     replace_variable, pattern)\n    return re.compile(pattern + '/?$')",
    "docstring": "r\"\"\"Generates a compiled regex pattern for a path pattern.\n\n    e.g. '/MyApi/v1/notes/{id}'\n    returns re.compile(r'/MyApi/v1/notes/(?P<id>[^/?#\\[\\]{}]*)')\n\n    Args:\n      pattern: A string, the parameterized path pattern to be checked.\n\n    Returns:\n      A compiled regex object to match this path pattern."
  },
  {
    "code": "def UpsertStoredProcedure(self, collection_link, sproc, options=None):\n        if options is None:\n            options = {}\n        collection_id, path, sproc = self._GetContainerIdWithPathForSproc(collection_link, sproc)\n        return self.Upsert(sproc,\n                           path,\n                           'sprocs',\n                           collection_id,\n                           None,\n                           options)",
    "docstring": "Upserts a stored procedure in a collection.\n\n        :param str collection_link:\n            The link to the document collection.\n        :param str sproc:\n        :param dict options:\n            The request options for the request.\n\n        :return:\n            The upserted Stored Procedure.\n        :rtype:\n            dict"
  },
  {
    "code": "def pots(self, refresh=False):\n        if not refresh and self._cached_pots:\n            return self._cached_pots\n        endpoint = '/pots/listV1'\n        response = self._get_response(\n            method='get', endpoint=endpoint,\n        )\n        pots_json = response.json()['pots']\n        pots = [MonzoPot(data=pot) for pot in pots_json]\n        self._cached_pots = pots\n        return pots",
    "docstring": "Returns a list of pots owned by the currently authorised user.\n\n        Official docs:\n            https://monzo.com/docs/#pots\n\n        :param refresh: decides if the pots information should be refreshed.\n        :type refresh: bool\n        :returns: list of Monzo pots\n        :rtype: list of MonzoPot"
  },
  {
    "code": "def nic_add(self, container, nic):\n        args = {\n            'container': container,\n            'nic': nic\n        }\n        self._nic_add.check(args)\n        return self._client.json('corex.nic-add', args)",
    "docstring": "Hot plug a nic into a container\n\n        :param container: container ID\n        :param nic: {\n                        'type': nic_type # one of default, bridge, zerotier, macvlan, passthrough, vlan, or vxlan (note, vlan and vxlan only supported by ovs)\n                        'id': id # depends on the type\n                            bridge: bridge name,\n                            zerotier: network id,\n                            macvlan: the parent link name,\n                            passthrough: the link name,\n                            vlan: the vlan tag,\n                            vxlan: the vxlan id\n                        'name': name of the nic inside the container (ignored in zerotier type)\n                        'hwaddr': Mac address of nic.\n                        'config': { # config is only honored for bridge, vlan, and vxlan types\n                            'dhcp': bool,\n                            'cidr': static_ip # ip/mask\n                            'gateway': gateway\n                            'dns': [dns]\n                        }\n                     }\n        :return:"
  },
  {
    "code": "def append(self, other, inplace=False, **kwargs):\n        if not isinstance(other, MAGICCData):\n            other = MAGICCData(other, **kwargs)\n        if inplace:\n            super().append(other, inplace=inplace)\n            self.metadata.update(other.metadata)\n        else:\n            res = super().append(other, inplace=inplace)\n            res.metadata = deepcopy(self.metadata)\n            res.metadata.update(other.metadata)\n            return res",
    "docstring": "Append any input which can be converted to MAGICCData to self.\n\n        Parameters\n        ----------\n        other : MAGICCData, pd.DataFrame, pd.Series, str\n            Source of data to append.\n\n        inplace : bool\n            If True, append ``other`` inplace, otherwise return a new ``MAGICCData``\n            instance.\n\n        **kwargs\n            Passed to ``MAGICCData`` constructor (only used if ``MAGICCData`` is not a\n            ``MAGICCData`` instance)."
  },
  {
    "code": "def add_string_widget(self, ref, text=\"Text\", x=1, y=1):\n        if ref not in self.widgets:\n            widget = widgets.StringWidget(screen=self, ref=ref, text=text, x=x, y=y)\n            self.widgets[ref] = widget\n            return self.widgets[ref]",
    "docstring": "Add String Widget"
  },
  {
    "code": "def wrap(self, data):\n        if self.nested:\n            return data\n        name = self.obj.__class__.__name__\n        self._nested_schema_classes[name] = data\n        root = {\n            'definitions': self._nested_schema_classes,\n            '$ref': '\n        }\n        return root",
    "docstring": "Wrap this with the root schema definitions."
  },
  {
    "code": "def get_random_name(sep: str='-'):\n    r = random.SystemRandom()\n    return '{}{}{}'.format(r.choice(_left), sep, r.choice(_right))",
    "docstring": "Generate random docker-like name with the given separator.\n\n    :param sep: adjective-name separator string\n    :return: random docker-like name"
  },
  {
    "code": "def distutils_servers(self):\n        if not multiple_pypi_support():\n            return []\n        try:\n            raw_index_servers = self.config.get('distutils', 'index-servers')\n        except (NoSectionError, NoOptionError):\n            return []\n        ignore_servers = ['']\n        if self.is_old_pypi_config():\n            ignore_servers.append('pypi')\n        index_servers = [\n            server.strip() for server in raw_index_servers.split('\\n')\n            if server.strip() not in ignore_servers]\n        return index_servers",
    "docstring": "Return a list of known distutils servers for collective.dist.\n\n        If the config has an old pypi config, remove the default pypi\n        server from the list."
  },
  {
    "code": "def store(self, value, l, dir_only):\n        if l and value in (b'', ''):\n            return\n        globstar = value in (b'**', '**') and self.globstar\n        magic = self.is_magic(value)\n        if magic:\n            value = compile(value, self.flags)\n        l.append(WcGlob(value, magic, globstar, dir_only, False))",
    "docstring": "Group patterns by literals and potential magic patterns."
  },
  {
    "code": "def stop(self):\n        vm_state = yield from self._get_state()\n        if vm_state == \"poweroff\":\n            self.running = False\n            return\n        yield from self._execute(\"controlvm\", [self._vmname, \"acpipowerbutton\"], timeout=3)\n        trial = 120\n        while True:\n            try:\n                vm_state = yield from self._get_state()\n            except GNS3VMError:\n                vm_state = \"running\"\n            if vm_state == \"poweroff\":\n                break\n            trial -= 1\n            if trial == 0:\n                yield from self._execute(\"controlvm\", [self._vmname, \"poweroff\"], timeout=3)\n                break\n            yield from asyncio.sleep(1)\n        log.info(\"GNS3 VM has been stopped\")\n        self.running = False",
    "docstring": "Stops the GNS3 VM."
  },
  {
    "code": "def _get_hangul_syllable_name(hangul_syllable):\n    if not _is_hangul_syllable(hangul_syllable):\n        raise ValueError(\"Value passed in does not represent a Hangul syllable!\")\n    jamo = decompose_hangul_syllable(hangul_syllable, fully_decompose=True)\n    result = ''\n    for j in jamo:\n        if j is not None:\n            result += _get_jamo_short_name(j)\n    return result",
    "docstring": "Function for taking a Unicode scalar value representing a Hangul syllable and converting it to its syllable name as\n    defined by the Unicode naming rule NR1.  See the Unicode Standard, ch. 04, section 4.8, Names, for more information.\n\n    :param hangul_syllable: Unicode scalar value representing the Hangul syllable to convert\n    :return: String representing its syllable name as transformed according to naming rule NR1."
  },
  {
    "code": "def total_flux(flux, A):\n    r\n    X = set(np.arange(flux.shape[0]))\n    A = set(A)\n    notA = X.difference(A)\n    W = flux.tocsr()\n    W = W[list(A), :]\n    W = W.tocsc()\n    W = W[:, list(notA)]\n    F = W.sum()\n    return F",
    "docstring": "r\"\"\"Compute the total flux between reactant and product.\n\n    Parameters\n    ----------\n    flux : (M, M) scipy.sparse matrix\n        Matrix of flux values between pairs of states.\n    A : array_like\n        List of integer state labels for set A (reactant)\n\n    Returns\n    -------\n    F : float\n        The total flux between reactant and product"
  },
  {
    "code": "def _MaybeWriteIndex(self, i, ts, mutation_pool):\n    if i > self._max_indexed and i % self.INDEX_SPACING == 0:\n      if ts[0] < (rdfvalue.RDFDatetime.Now() -\n                  self.INDEX_WRITE_DELAY).AsMicrosecondsSinceEpoch():\n        mutation_pool.CollectionAddIndex(self.collection_id, i, ts[0], ts[1])\n        self._index[i] = ts\n        self._max_indexed = max(i, self._max_indexed)",
    "docstring": "Write index marker i."
  },
  {
    "code": "def bits(self, count):\n        if count < 0:\n            raise ValueError\n        if count > self._bits:\n            n_bytes = (count - self._bits + 7) // 8\n            data = self._fileobj.read(n_bytes)\n            if len(data) != n_bytes:\n                raise BitReaderError(\"not enough data\")\n            for b in bytearray(data):\n                self._buffer = (self._buffer << 8) | b\n            self._bits += n_bytes * 8\n        self._bits -= count\n        value = self._buffer >> self._bits\n        self._buffer &= (1 << self._bits) - 1\n        assert self._bits < 8\n        return value",
    "docstring": "Reads `count` bits and returns an uint, MSB read first.\n\n        May raise BitReaderError if not enough data could be read or\n        IOError by the underlying file object."
  },
  {
    "code": "def formfield(self, **kwargs):\n        default = kwargs.get(\"widget\", None) or AdminTextareaWidget\n        if default is AdminTextareaWidget:\n            from yacms.conf import settings\n            richtext_widget_path = settings.RICHTEXT_WIDGET_CLASS\n            try:\n                widget_class = import_dotted_path(richtext_widget_path)\n            except ImportError:\n                raise ImproperlyConfigured(_(\"Could not import the value of \"\n                                             \"settings.RICHTEXT_WIDGET_CLASS: \"\n                                             \"%s\" % richtext_widget_path))\n            kwargs[\"widget\"] = widget_class()\n        kwargs.setdefault(\"required\", False)\n        formfield = super(RichTextField, self).formfield(**kwargs)\n        return formfield",
    "docstring": "Apply the widget class defined by the\n        ``RICHTEXT_WIDGET_CLASS`` setting."
  },
  {
    "code": "def user_filter(config, message, fasnick=None, *args, **kw):\n    fasnick = kw.get('fasnick', fasnick)\n    if fasnick:\n        return fasnick in fmn.rules.utils.msg2usernames(message, **config)",
    "docstring": "A particular user\n\n    Use this rule to include messages that are associated with a\n    specific user."
  },
  {
    "code": "def addPSF(self, psf, date=None, info='', light_spectrum='visible'):\r\n        self._registerLight(light_spectrum)\r\n        date = _toDate(date)\r\n        f = self.coeffs['psf']\r\n        if light_spectrum not in f:\r\n            f[light_spectrum] = []\r\n        f[light_spectrum].insert(_insertDateIndex(date, f[light_spectrum]),\r\n                                 [date, info, psf])",
    "docstring": "add a new point spread function"
  },
  {
    "code": "async def pulse(self, *args, **kwargs):\n        return await self._makeApiCall(self.funcinfo[\"pulse\"], *args, **kwargs)",
    "docstring": "Publish a Pulse Message\n\n        Publish a message on pulse with the given `routingKey`.\n\n        This method takes input: ``v1/pulse-request.json#``\n\n        This method is ``experimental``"
  },
  {
    "code": "def conditional_write(strm, fmt, value, *args, **kwargs):\n    if value is not None:\n        strm.write(fmt.format(value, *args, **kwargs))",
    "docstring": "Write to stream using fmt and value if value is not None"
  },
  {
    "code": "def get_queryset(self):\n        if self.queryset is not None:\n            queryset = self.queryset\n            if hasattr(queryset, '_clone'):\n                queryset = queryset._clone()\n        elif self.model is not None:\n            queryset = self.model._default_manager.all()\n        else:\n            msg = '{0} must define ``queryset`` or ``model``'\n            raise ImproperlyConfigured(msg.format(self.__class__.__name__))\n        return queryset",
    "docstring": "Get the list of items for this view.\n\n        This must be an interable, and may be a queryset\n        (in which qs-specific behavior will be enabled).\n\n        See original in ``django.views.generic.list.MultipleObjectMixin``."
  },
  {
    "code": "def solve(guess_a, guess_b, power, solver='scipy'):\n    x = sp.symbols('x:2', real=True)\n    p = sp.Symbol('p', real=True, negative=False, integer=True)\n    f = [x[0] + (x[0] - x[1])**p/2 - 1,\n         (x[1] - x[0])**p/2 + x[1]]\n    neqsys = SymbolicSys(x, f, [p])\n    return neqsys.solve([guess_a, guess_b], [power], solver=solver)",
    "docstring": "Constructs a pyneqsys.symbolic.SymbolicSys instance and returns from its ``solve`` method."
  },
  {
    "code": "def avail_sizes(call=None):\n    if call == 'action':\n        raise SaltCloudSystemExit(\n            'The avail_sizes function must be called with '\n            '-f or --function, or with the --list-sizes option'\n        )\n    conn = get_conn()\n    data = conn.list_role_sizes()\n    ret = {}\n    for item in data.role_sizes:\n        ret[item.name] = object_to_dict(item)\n    return ret",
    "docstring": "Return a list of sizes from Azure"
  },
  {
    "code": "def add_task(self, pid):\n        _register_process_with_cgrulesengd(pid)\n        for cgroup in self.paths:\n            with open(os.path.join(cgroup, 'tasks'), 'w') as tasksFile:\n                tasksFile.write(str(pid))",
    "docstring": "Add a process to the cgroups represented by this instance."
  },
  {
    "code": "def CopyTextToLabel(cls, text, prefix=''):\n    text = '{0:s}{1:s}'.format(prefix, text)\n    return cls._INVALID_LABEL_CHARACTERS_REGEX.sub('_', text)",
    "docstring": "Copies a string to a label.\n\n    A label only supports a limited set of characters therefore\n    unsupported characters are replaced with an underscore.\n\n    Args:\n      text (str): label text.\n      prefix (Optional[str]): label prefix.\n\n    Returns:\n      str: label."
  },
  {
    "code": "def ProcessMessage(self, message):\n    if (message.auth_state !=\n        rdf_flows.GrrMessage.AuthorizationState.AUTHENTICATED):\n      return\n    now = time.time()\n    with self.lock:\n      if (self.foreman_cache is None or\n          now > self.foreman_cache.age + self.cache_refresh_time):\n        self.foreman_cache = aff4.FACTORY.Open(\n            \"aff4:/foreman\", mode=\"rw\", token=self.token)\n        self.foreman_cache.age = now\n    if message.source:\n      self.foreman_cache.AssignTasksToClient(message.source.Basename())",
    "docstring": "Run the foreman on the client."
  },
  {
    "code": "def set_ys(self, word):\n        if word[0] == 'y':\n            word = 'Y' + word[1:]\n        for match in re.finditer(\"[aeiou]y\", word):\n            y_index = match.end() - 1\n            char_list = [x for x in word]\n            char_list[y_index] = 'Y'\n            word = ''.join(char_list)\n        return word",
    "docstring": "Identify Ys that are to be treated\n        as consonants and make them uppercase."
  },
  {
    "code": "def enriched(self, thresh=0.05, idx=True):\n        return self.upregulated(thresh=thresh, idx=idx)",
    "docstring": "Enriched features.\n\n        {threshdoc}"
  },
  {
    "code": "def progress(self):\n        total = len(self.all_jobs)\n        remaining = total - len(self.active_jobs) if total > 0 else 0\n        percent = int(100 * (float(remaining) / total)) if total > 0 else 0\n        return percent",
    "docstring": "Returns the percentage, current and total number of\n        jobs in the queue."
  },
  {
    "code": "def tar_dir(tarfile, srcdir):\n    files = os.listdir(srcdir)\n    packtar(tarfile, files, srcdir)",
    "docstring": "Pack a tar file using all the files in the given srcdir"
  },
  {
    "code": "def step(self, action, blocking=True):\n    promise = self.call('step', action)\n    if blocking:\n      return promise()\n    else:\n      return promise",
    "docstring": "Step the environment.\n\n    Args:\n      action: The action to apply to the environment.\n      blocking: Whether to wait for the result.\n\n    Returns:\n      Transition tuple when blocking, otherwise callable that returns the\n      transition tuple."
  },
  {
    "code": "def _generate_keys(self):\n        from helpme.defaults import HELPME_CLIENT_SECRETS\n        keypair_dir = os.path.join(os.path.dirname(HELPME_CLIENT_SECRETS),\n                                   'discourse')\n        self.keypair_file = os.path.join(keypair_dir, 'private.pem')\n        if not hasattr(self, 'key'):\n            self.key = generate_keypair(self.keypair_file)           \n        if not hasattr(self, 'public_key'):\n            self.public_key = load_keypair(self.keypair_file)",
    "docstring": "the discourse API requires the interactions to be signed, so we \n           generate a keypair on behalf of the user"
  },
  {
    "code": "def create(self, environment, target_name):\n        remote_server_command(\n            [\"ssh\", environment.deploy_target, \"create\", target_name],\n            environment, self,\n            clean_up=True,\n            )",
    "docstring": "Sends \"create project\" command to the remote server"
  },
  {
    "code": "def accept_best_match(accept_header, mimetypes):\n    for mimetype_pattern, _ in _parse_and_sort_accept_header(accept_header):\n        matched_types = fnmatch.filter(mimetypes, mimetype_pattern)\n        if matched_types:\n            return matched_types[0]\n    return mimetypes[0]",
    "docstring": "Return a mimetype best matched the accept headers.\n\n    >>> accept_best_match('application/json, text/html', ['application/json', 'text/plain'])\n    'application/json'\n\n    >>> accept_best_match('application/json;q=0.5, text/*', ['application/json', 'text/plain'])\n    'text/plain'"
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'element_pair' in _dict:\n            args['element_pair'] = [\n                ElementPair._from_dict(x) for x in (_dict.get('element_pair'))\n            ]\n        if 'identical_text' in _dict:\n            args['identical_text'] = _dict.get('identical_text')\n        if 'provenance_ids' in _dict:\n            args['provenance_ids'] = _dict.get('provenance_ids')\n        if 'significant_elements' in _dict:\n            args['significant_elements'] = _dict.get('significant_elements')\n        return cls(**args)",
    "docstring": "Initialize a AlignedElement object from a json dictionary."
  },
  {
    "code": "def Stop(self):\n    self._shutdown = True\n    self._new_updates.set()\n    if self._main_thread is not None:\n      self._main_thread.join()\n      self._main_thread = None\n    if self._transmission_thread is not None:\n      self._transmission_thread.join()\n      self._transmission_thread = None",
    "docstring": "Signals the worker threads to shut down and waits until it exits."
  },
  {
    "code": "def _approx_eq_(self, other: Any, atol: float) -> bool:\n        if not isinstance(other, LinearDict):\n            return NotImplemented\n        all_vs = set(self.keys()) | set(other.keys())\n        return all(abs(self[v] - other[v]) < atol for v in all_vs)",
    "docstring": "Checks whether two linear combinations are approximately equal."
  },
  {
    "code": "def _extract_cookies(self, response: Response):\n        self._cookie_jar.extract_cookies(\n            response, response.request, self._get_cookie_referrer_host()\n        )",
    "docstring": "Load the cookie headers from the Response."
  },
  {
    "code": "def gitrepo(cwd):\n    repo = Repository(cwd)\n    if not repo.valid():\n        return {}\n    return {\n        'head': {\n            'id': repo.gitlog('%H'),\n            'author_name': repo.gitlog('%aN'),\n            'author_email': repo.gitlog('%ae'),\n            'committer_name': repo.gitlog('%cN'),\n            'committer_email': repo.gitlog('%ce'),\n            'message': repo.gitlog('%s')\n        },\n        'branch': os.environ.get('TRAVIS_BRANCH',\n                  os.environ.get('APPVEYOR_REPO_BRANCH',\n                                 repo.git('rev-parse', '--abbrev-ref', 'HEAD')[1].strip())),\n        'remotes': [{'name': line.split()[0], 'url': line.split()[1]}\n                    for line in repo.git('remote', '-v')[1] if '(fetch)' in line]\n    }",
    "docstring": "Return hash of Git data that can be used to display more information to\n    users.\n\n    Example:\n        \"git\": {\n            \"head\": {\n                \"id\": \"5e837ce92220be64821128a70f6093f836dd2c05\",\n                \"author_name\": \"Wil Gieseler\",\n                \"author_email\": \"wil@example.com\",\n                \"committer_name\": \"Wil Gieseler\",\n                \"committer_email\": \"wil@example.com\",\n                \"message\": \"depend on simplecov >= 0.7\"\n            },\n            \"branch\": \"master\",\n            \"remotes\": [{\n                \"name\": \"origin\",\n                \"url\": \"https://github.com/lemurheavy/coveralls-ruby.git\"\n            }]\n        }\n\n    From https://github.com/coagulant/coveralls-python (with MIT license)."
  },
  {
    "code": "def get_instance(self, payload):\n        return EnvironmentInstance(self._version, payload, service_sid=self._solution['service_sid'], )",
    "docstring": "Build an instance of EnvironmentInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.serverless.v1.service.environment.EnvironmentInstance\n        :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentInstance"
  },
  {
    "code": "def begin(self):\n        if self.start:\n            self.at_beginning = True\n            self.pos = 0\n        else:\n            self.at_beginning = False\n            self._new_song()\n        return self._get_song()",
    "docstring": "Start over and get a track."
  },
  {
    "code": "async def delete_pool_ledger_config(config_name: str) -> None:\n    logger = logging.getLogger(__name__)\n    logger.debug(\"delete_pool_ledger_config: >>> config_name: %r\",\n                 config_name)\n    if not hasattr(delete_pool_ledger_config, \"cb\"):\n        logger.debug(\"delete_pool_ledger_config: Creating callback\")\n        delete_pool_ledger_config.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))\n    c_config_name = c_char_p(config_name.encode('utf-8'))\n    res = await do_call('indy_delete_pool_ledger_config',\n                        c_config_name,\n                        delete_pool_ledger_config.cb)\n    logger.debug(\"delete_pool_ledger_config: <<< res: %r\", res)\n    return res",
    "docstring": "Deletes created pool ledger configuration.\n\n    :param config_name: Name of the pool ledger configuration to delete.\n    :return: Error code"
  },
  {
    "code": "def find_distinct(self, collection, key):\n        obj = getattr(self.db, collection)\n        result = obj.distinct(key)\n        return result",
    "docstring": "Search a collection for the distinct key values provided.\n\n        Args:\n            collection: The db collection. See main class documentation.\n            key: The name of the key to find distinct values. For example with\n                 the indicators collection, the key could be \"type\".\n        Returns:\n            List of distinct values."
  },
  {
    "code": "def new_closure(vals):\n    args = ','.join('x%i' % i for i in range(len(vals)))\n    f = eval(\"lambda %s:lambda:(%s)\" % (args, args))\n    if sys.version_info[0] >= 3:\n        return f(*vals).__closure__\n    return f(*vals).func_closure",
    "docstring": "Build a new closure"
  },
  {
    "code": "def percent(self, value: float) -> 'Size':\n        raise_not_number(value)\n        self.maximum = '{}%'.format(value)\n        return self",
    "docstring": "Set the percentage of free space to use."
  },
  {
    "code": "def python(self, func, *args, **kwargs):\n        self.ops.append(lambda: func(*args, **kwargs))",
    "docstring": "Run python code."
  },
  {
    "code": "def existing_users(context):\n    members = IWorkspace(context).members\n    info = []\n    for userid, details in members.items():\n        user = api.user.get(userid)\n        if user is None:\n            continue\n        user = user.getUser()\n        title = user.getProperty('fullname') or user.getId() or userid\n        description = _(u'Here we could have a nice status of this person')\n        classes = description and 'has-description' or 'has-no-description'\n        portal = api.portal.get()\n        portrait = '%s/portal_memberdata/portraits/%s' % \\\n                   (portal.absolute_url(), userid)\n        info.append(\n            dict(\n                id=userid,\n                title=title,\n                description=description,\n                portrait=portrait,\n                cls=classes,\n                member=True,\n                admin='Admins' in details['groups'],\n            )\n        )\n    return info",
    "docstring": "Look up the full user details for current workspace members"
  },
  {
    "code": "def clean_url(self):\n        raw_url = self.request['url']\n        parsed_url = urlparse(raw_url)\n        qsl = parse_qsl(parsed_url.query)\n        for qs in qsl:\n            new_url = self._join_url(parsed_url,\n                                     [i for i in qsl if i is not qs])\n            new_request = deepcopy(self.request)\n            new_request['url'] = new_url\n            self._add_task('qsl', qs, new_request)\n        return self",
    "docstring": "Only clean the url params and return self."
  },
  {
    "code": "def get_session(credentials, config):\n    session = requests.Session()\n    session.verify = False\n    auth_url = config.get(\"auth_url\")\n    if auth_url:\n        cookie = session.post(\n            auth_url,\n            data={\n                \"j_username\": credentials[0],\n                \"j_password\": credentials[1],\n                \"submit\": \"Log In\",\n                \"rememberme\": \"true\",\n            },\n            headers={\"Content-Type\": \"application/x-www-form-urlencoded\"},\n        )\n        if not cookie:\n            raise Dump2PolarionException(\"Cookie was not retrieved from {}.\".format(auth_url))\n    else:\n        session.auth = credentials\n    return session",
    "docstring": "Gets requests session."
  },
  {
    "code": "def get_scoreboard(year, month, day):\n    try:\n        data = urlopen(BASE_URL.format(year, month, day) + 'scoreboard.xml')\n    except HTTPError:\n        data = os.path.join(PWD, 'default.xml')\n    return data",
    "docstring": "Return the game file for a certain day matching certain criteria."
  },
  {
    "code": "def limit(self, limit: int) -> \"QuerySet\":\n        queryset = self._clone()\n        queryset._limit = limit\n        return queryset",
    "docstring": "Limits QuerySet to given length."
  },
  {
    "code": "def footprints_from_place(place, footprint_type='building', retain_invalid=False):\n    city = gdf_from_place(place)\n    polygon = city['geometry'].iloc[0]\n    return create_footprints_gdf(polygon, retain_invalid=retain_invalid,\n                                 footprint_type=footprint_type)",
    "docstring": "Get footprints within the boundaries of some place.\n\n    The query must be geocodable and OSM must have polygon boundaries for the\n    geocode result. If OSM does not have a polygon for this place, you can\n    instead get its footprints using the footprints_from_address function, which\n    geocodes the place name to a point and gets the footprints within some distance\n    of that point.\n\n    Parameters\n    ----------\n    place : string\n        the query to geocode to get geojson boundary polygon\n    footprint_type : string\n        type of footprint to be downloaded. OSM tag key e.g. 'building', 'landuse', 'place', etc.\n    retain_invalid : bool\n        if False discard any footprints with an invalid geometry\n\n    Returns\n    -------\n    GeoDataFrame"
  },
  {
    "code": "def to_array(self):\n        array = super(InlineQueryResultAudio, self).to_array()\n        array['audio_url'] = u(self.audio_url)\n        array['title'] = u(self.title)\n        if self.caption is not None:\n            array['caption'] = u(self.caption)\n        if self.parse_mode is not None:\n            array['parse_mode'] = u(self.parse_mode)\n        if self.performer is not None:\n            array['performer'] = u(self.performer)\n        if self.audio_duration is not None:\n            array['audio_duration'] = int(self.audio_duration)\n        if self.reply_markup is not None:\n            array['reply_markup'] = self.reply_markup.to_array()\n        if self.input_message_content is not None:\n            array['input_message_content'] = self.input_message_content.to_array()\n        return array",
    "docstring": "Serializes this InlineQueryResultAudio to a dictionary.\n\n        :return: dictionary representation of this object.\n        :rtype: dict"
  },
  {
    "code": "def dict(self):\n        post_dict = {\n            'id': self.id,\n            'link': self.link,\n            'permalink': self.permalink,\n            'content_type': self.content_type,\n            'slug': self.slug,\n            'updated': self.updated,\n            'published': self.published,\n            'title': self.title,\n            'description': self.description,\n            'author': self.author,\n            'categories': self.categories[1:-1].split(',') if self.categories else None,\n            'summary': self.summary,\n            }\n        if self.attributes:\n            attributes = simplejson.loads(self.attributes)\n            post_dict.update(attributes)\n        return post_dict",
    "docstring": "Returns dictionary of post fields and attributes"
  },
  {
    "code": "def get_all(self):\n        if not self.vars:\n            return self.parent\n        if not self.parent:\n            return self.vars\n        return dict(self.parent, **self.vars)",
    "docstring": "Return the complete context as dict including the exported\n        variables.  For optimizations reasons this might not return an\n        actual copy so be careful with using it."
  },
  {
    "code": "def get_level(self):\n        if not bool(self._my_map['levelId']):\n            raise errors.IllegalState('this Assessment has no level')\n        mgr = self._get_provider_manager('GRADING')\n        if not mgr.supports_grade_lookup():\n            raise errors.OperationFailed('Grading does not support Grade lookup')\n        lookup_session = mgr.get_grade_lookup_session(proxy=getattr(self, \"_proxy\", None))\n        lookup_session.use_federated_gradebook_view()\n        osid_object = lookup_session.get_grade(self.get_level_id())\n        return osid_object",
    "docstring": "Gets the ``Grade`` corresponding to the assessment difficulty.\n\n        return: (osid.grading.Grade) - the level\n        raise:  OperationFailed - unable to complete request\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def decrease_priority(self, infohash_list):\n        data = self._process_infohash_list(infohash_list)\n        return self._post('command/decreasePrio', data=data)",
    "docstring": "Decrease priority of torrents.\n\n        :param infohash_list: Single or list() of infohashes."
  },
  {
    "code": "def wrap_json(cls, json):\n        u = User(usertype=json['type'],\n                 name=json['name'],\n                 logo=json['logo'],\n                 twitchid=json['_id'],\n                 displayname=json['display_name'],\n                 bio=json['bio'])\n        return u",
    "docstring": "Create a User instance for the given json\n\n        :param json: the dict with the information of the user\n        :type json: :class:`dict` | None\n        :returns: the new user instance\n        :rtype: :class:`User`\n        :raises: None"
  },
  {
    "code": "def add_index(self, model, *columns, **kwargs):\n        unique = kwargs.pop('unique', False)\n        model._meta.indexes.append((columns, unique))\n        columns_ = []\n        for col in columns:\n            field = model._meta.fields.get(col)\n            if len(columns) == 1:\n                field.unique = unique\n                field.index = not unique\n            if isinstance(field, pw.ForeignKeyField):\n                col = col + '_id'\n            columns_.append(col)\n        self.ops.append(self.migrator.add_index(model._meta.table_name, columns_, unique=unique))\n        return model",
    "docstring": "Create indexes."
  },
  {
    "code": "def _query(self, urls):\n        urls = list(set(urls))\n        for i in range(0, len(urls), self.max_urls_per_request):\n            chunk = urls[i:i+self.max_urls_per_request]\n            response = self._query_once(chunk)\n            if response.status_code == 200:\n                yield chunk, response",
    "docstring": "Test URLs for being listed by the service.\n\n        :param urls: a sequence of URLs  to be tested\n        :returns: a tuple containing chunk of URLs and a response\n        pertaining to them if the code of response was 200, which\n        means at least one of the queried URLs is matched in either\n        the phishing, malware, or unwanted software lists."
  },
  {
    "code": "def get_attr(obj, attr, default=None):\n    if '.' not in attr:\n        return getattr(obj, attr, default)\n    else:\n        L = attr.split('.')\n        return get_attr(getattr(obj, L[0], default), '.'.join(L[1:]), default)",
    "docstring": "Recursive get object's attribute. May use dot notation.\n\n    >>> class C(object): pass\n    >>> a = C()\n    >>> a.b = C()\n    >>> a.b.c = 4\n    >>> get_attr(a, 'b.c')\n    4\n\n    >>> get_attr(a, 'b.c.y', None)\n\n    >>> get_attr(a, 'b.c.y', 1)\n    1"
  },
  {
    "code": "def _get_keys(self, read, input_records):\n        for i in range(read.value):\n            ir = input_records[i]\n            if ir.EventType in EventTypes:\n                ev = getattr(ir.Event, EventTypes[ir.EventType])\n                if type(ev) == KEY_EVENT_RECORD and ev.KeyDown:\n                    for key_press in self._event_to_key_presses(ev):\n                        yield key_press\n                elif type(ev) == MOUSE_EVENT_RECORD:\n                    for key_press in self._handle_mouse(ev):\n                        yield key_press",
    "docstring": "Generator that yields `KeyPress` objects from the input records."
  },
  {
    "code": "def _init_c2ps(self, go_sources, traverse_child):\n        if not traverse_child:\n            return {}\n        c2ps = defaultdict(set)\n        goids_seen = set()\n        go2obj = self.go2obj\n        for goid_src in go_sources:\n            goobj_src = go2obj[goid_src]\n            if goid_src not in goids_seen:\n                self._traverse_child_objs(c2ps, goobj_src, goids_seen)\n        return c2ps",
    "docstring": "Traverse up children."
  },
  {
    "code": "def _process_req_body(self, body):\n    try:\n      return json.loads(body)\n    except ValueError:\n      return urlparse.parse_qs(body, keep_blank_values=True)",
    "docstring": "Process the body of the HTTP request.\n\n    If the body is valid JSON, return the JSON as a dict.\n    Else, convert the key=value format to a dict and return that.\n\n    Args:\n      body: The body of the HTTP request."
  },
  {
    "code": "def _get_pci_devices(self):\n        system = self._get_host_details()\n        if ('links' in system['Oem']['Hp'] and\n                'PCIDevices' in system['Oem']['Hp']['links']):\n            pci_uri = system['Oem']['Hp']['links']['PCIDevices']['href']\n            status, headers, pci_device_list = self._rest_get(pci_uri)\n            if status >= 300:\n                msg = self._get_extended_error(pci_device_list)\n                raise exception.IloError(msg)\n            return pci_device_list\n        else:\n            msg = ('links/PCIDevices section in ComputerSystem/Oem/Hp'\n                   ' does not exist')\n            raise exception.IloCommandNotSupportedError(msg)",
    "docstring": "Gets the PCI devices.\n\n        :returns: PCI devices list if the pci resource exist.\n        :raises: IloCommandNotSupportedError if the PCI resource\n            doesn't exist.\n        :raises: IloError, on an error from iLO."
  },
  {
    "code": "def get_conversation(self, conversation, **kwargs):\n        from canvasapi.conversation import Conversation\n        conversation_id = obj_or_id(conversation, \"conversation\", (Conversation,))\n        response = self.__requester.request(\n            'GET',\n            'conversations/{}'.format(conversation_id),\n            _kwargs=combine_kwargs(**kwargs)\n        )\n        return Conversation(self.__requester, response.json())",
    "docstring": "Return single Conversation\n\n        :calls: `GET /api/v1/conversations/:id \\\n        <https://canvas.instructure.com/doc/api/conversations.html#method.conversations.show>`_\n\n        :param conversation: The object or ID of the conversation.\n        :type conversation: :class:`canvasapi.conversation.Conversation` or int\n\n        :rtype: :class:`canvasapi.conversation.Conversation`"
  },
  {
    "code": "def build(X_df=None, y_df=None):\n    if X_df is None:\n        X_df, _ = load_data()\n    if y_df is None:\n        _, y_df = load_data()\n    features = get_contrib_features()\n    mapper_X = ballet.feature.make_mapper(features)\n    X = mapper_X.fit_transform(X_df)\n    encoder_y = get_target_encoder()\n    y = encoder_y.fit_transform(y_df)\n    return {\n        'X_df': X_df,\n        'features': features,\n        'mapper_X': mapper_X,\n        'X': X,\n        'y_df': y_df,\n        'encoder_y': encoder_y,\n        'y': y,\n    }",
    "docstring": "Build features and target\n\n    Args:\n        X_df (DataFrame): raw variables\n        y_df (DataFrame): raw target\n\n    Returns:\n        dict with keys X_df, features, mapper_X, X, y_df, encoder_y, y"
  },
  {
    "code": "def android_example():\n    env = holodeck.make(\"AndroidPlayground\")\n    command = np.ones(94) * 10\n    for i in range(10):\n        env.reset()\n        for j in range(1000):\n            if j % 50 == 0:\n                command *= -1\n            state, reward, terminal, _ = env.step(command)\n            pixels = state[Sensors.PIXEL_CAMERA]\n            orientation = state[Sensors.ORIENTATION_SENSOR]",
    "docstring": "A basic example of how to use the android agent."
  },
  {
    "code": "def stop(self, signal=None):\n        signal = signal or self.int_signal\n        self.out.log(\"Cleaning up local Heroku process...\")\n        if self._process is None:\n            self.out.log(\"No local Heroku process was running.\")\n            return\n        try:\n            os.killpg(os.getpgid(self._process.pid), signal)\n            self.out.log(\"Local Heroku process terminated.\")\n        except OSError:\n            self.out.log(\"Local Heroku was already terminated.\")\n            self.out.log(traceback.format_exc())\n        finally:\n            self._process = None",
    "docstring": "Stop the heroku local subprocess and all of its children."
  },
  {
    "code": "def all_coarse_grains_for_blackbox(blackbox):\n    for partition in all_partitions(blackbox.output_indices):\n        for grouping in all_groupings(partition):\n            coarse_grain = CoarseGrain(partition, grouping)\n            try:\n                validate.blackbox_and_coarse_grain(blackbox, coarse_grain)\n            except ValueError:\n                continue\n            yield coarse_grain",
    "docstring": "Generator over all |CoarseGrains| for the given blackbox.\n\n    If a box has multiple outputs, those outputs are partitioned into the same\n    coarse-grain macro-element."
  },
  {
    "code": "def canonical_name(sgf_name):\n    sgf_name = os.path.normpath(sgf_name)\n    assert sgf_name.endswith('.sgf'), sgf_name\n    sgf_name = sgf_name[:-4]\n    with_folder = re.search(r'/([^/]*/eval/.*)', sgf_name)\n    if with_folder:\n        return with_folder.group(1)\n    return os.path.basename(sgf_name)",
    "docstring": "Keep filename and some date folders"
  },
  {
    "code": "def registerJavaUDAF(self, name, javaClassName):\n        self.sparkSession._jsparkSession.udf().registerJavaUDAF(name, javaClassName)",
    "docstring": "Register a Java user-defined aggregate function as a SQL function.\n\n        :param name: name of the user-defined aggregate function\n        :param javaClassName: fully qualified name of java class\n\n        >>> spark.udf.registerJavaUDAF(\"javaUDAF\", \"test.org.apache.spark.sql.MyDoubleAvg\")\n        >>> df = spark.createDataFrame([(1, \"a\"),(2, \"b\"), (3, \"a\")],[\"id\", \"name\"])\n        >>> df.createOrReplaceTempView(\"df\")\n        >>> spark.sql(\"SELECT name, javaUDAF(id) as avg from df group by name\").collect()\n        [Row(name=u'b', avg=102.0), Row(name=u'a', avg=102.0)]"
  },
  {
    "code": "def cftime_to_nptime(times):\n    times = np.asarray(times)\n    new = np.empty(times.shape, dtype='M8[ns]')\n    for i, t in np.ndenumerate(times):\n        try:\n            dt = pd.Timestamp(t.year, t.month, t.day, t.hour, t.minute,\n                              t.second, t.microsecond)\n        except ValueError as e:\n            raise ValueError('Cannot convert date {} to a date in the '\n                             'standard calendar.  Reason: {}.'.format(t, e))\n        new[i] = np.datetime64(dt)\n    return new",
    "docstring": "Given an array of cftime.datetime objects, return an array of\n    numpy.datetime64 objects of the same size"
  },
  {
    "code": "def reportTimes(self):\n        self.end = _ptime()\n        total_time = 0\n        print(ProcSteps.__report_header)\n        for step in self.order:\n            if 'elapsed' in self.steps[step]:\n                _time = self.steps[step]['elapsed']\n            else:\n                _time = 0.0\n            total_time += _time\n            print('   %20s          %0.4f sec.' % (step, _time))\n        print('   %20s          %s' % ('=' * 20, '=' * 20))\n        print('   %20s          %0.4f sec.' % ('Total', total_time))",
    "docstring": "Print out a formatted summary of the elapsed times for all the\n        performed steps."
  },
  {
    "code": "def as_table(self, name=None):\n        if name is None:\n            name = self._id\n        return alias(self.subquery(), name=name)",
    "docstring": "Return an alias to a table"
  },
  {
    "code": "def update_status(self, helper, status):\n        if status:\n            self.status(status[0])\n            if status[0] == 0:\n                self.add_long_output(status[1])\n            else:\n                self.add_summary(status[1])",
    "docstring": "update the helper"
  },
  {
    "code": "def version_already_uploaded(project_name, version_str, index_url, requests_verify=True):\n    all_versions = _get_uploaded_versions(project_name, index_url, requests_verify)\n    return version_str in all_versions",
    "docstring": "Check to see if the version specified has already been uploaded to the configured index"
  },
  {
    "code": "def min(self):\n        if len(self._data) == 0:\n            return 10\n        return next(iter(sorted(self._data.keys())))",
    "docstring": "Return the minimum value in this histogram.\n\n        If there are no values in the histogram at all, return 10.\n\n        Returns:\n            int: The minimum value in the histogram."
  },
  {
    "code": "def send_no_servlet_response(self):\n        response = _HTTPServletResponse(self)\n        response.send_content(404, self._service.make_not_found_page(self.path))",
    "docstring": "Default response sent when no servlet is found for the requested path"
  },
  {
    "code": "def filelist_prune(self, at_data, *args, **kwargs):\n        b_status    = True\n        l_file      = []\n        str_path    = at_data[0]\n        al_file     = at_data[1]\n        if len(self.str_extension):\n            al_file = [x for x in al_file if self.str_extension in x]\n        if len(al_file):\n            al_file.sort()\n            l_file      = al_file\n            b_status    = True\n        else:\n            self.dp.qprint( \"No valid files to analyze found in path %s!\" % str_path, \n                            comms = 'error', level = 3)\n            l_file      = None\n            b_status    = False\n        return {\n            'status':   b_status,\n            'l_file':   l_file\n        }",
    "docstring": "Given a list of files, possibly prune list by \n        extension."
  },
  {
    "code": "def _toggle_term_protect(name, value):\n    instance_id = _get_node(name)['instanceId']\n    params = {'Action': 'ModifyInstanceAttribute',\n              'InstanceId': instance_id,\n              'DisableApiTermination.Value': value}\n    result = aws.query(params,\n                       location=get_location(),\n                       provider=get_provider(),\n                       return_root=True,\n                       opts=__opts__,\n                       sigver='4')\n    return show_term_protect(name=name, instance_id=instance_id, call='action')",
    "docstring": "Enable or Disable termination protection on a node"
  },
  {
    "code": "def transform(self, X):\n    X_checked = check_input(X, type_of_inputs='classic', estimator=self,\n                             preprocessor=self.preprocessor_,\n                             accept_sparse=True)\n    return X_checked.dot(self.transformer_.T)",
    "docstring": "Embeds data points in the learned linear embedding space.\n\n    Transforms samples in ``X`` into ``X_embedded``, samples inside a new\n    embedding space such that: ``X_embedded = X.dot(L.T)``, where ``L`` is\n    the learned linear transformation (See :class:`MahalanobisMixin`).\n\n    Parameters\n    ----------\n    X : `numpy.ndarray`, shape=(n_samples, n_features)\n      The data points to embed.\n\n    Returns\n    -------\n    X_embedded : `numpy.ndarray`, shape=(n_samples, num_dims)\n      The embedded data points."
  },
  {
    "code": "def save(self, *args, **kwargs):\n        super(Layer, self).save(*args, **kwargs)\n        if self.pk and self.is_published != self._current_is_published:\n            layer_is_published_changed.send(\n                sender=self.__class__,\n                instance=self,\n                old_is_published=self._current_is_published,\n                new_is_published=self.is_published\n            )\n            self.update_nodes_published()\n        self._current_is_published = self.is_published",
    "docstring": "intercepts changes to is_published and fires layer_is_published_changed signal"
  },
  {
    "code": "def regen_keys():\n    for fn_ in os.listdir(__opts__['pki_dir']):\n        path = os.path.join(__opts__['pki_dir'], fn_)\n        try:\n            os.remove(path)\n        except os.error:\n            pass\n    channel = salt.transport.client.ReqChannel.factory(__opts__)\n    channel.close()",
    "docstring": "Used to regenerate the minion keys.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' saltutil.regen_keys"
  },
  {
    "code": "def handle(self, *args, **options):\n        last_id = Submission._objects.all().aggregate(Max('id'))['id__max']\n        log.info(\"Beginning uuid update\")\n        current = options['start']\n        while current < last_id:\n            end_chunk = current + options['chunk'] if last_id - options['chunk'] >= current else last_id\n            log.info(\"Updating entries in range [{}, {}]\".format(current, end_chunk))\n            with transaction.atomic():\n                for submission in Submission._objects.filter(id__gte=current, id__lte=end_chunk).iterator():\n                    submission.save(update_fields=['uuid'])\n            time.sleep(options['wait'])\n            current = end_chunk + 1",
    "docstring": "By default, we're going to do this in chunks. This way, if there ends up being an error,\n        we can check log messages and continue from that point after fixing the issue."
  },
  {
    "code": "def from_file(cls, xml_path):\n    try:\n      parsed_xml = cls._parse(xml_path)\n    except OSError as e:\n      raise XmlParser.XmlError(\"Problem reading xml file at {}: {}\".format(xml_path, e))\n    return cls(xml_path, parsed_xml)",
    "docstring": "Parse .xml file and create a XmlParser object."
  },
  {
    "code": "def instances(self, **kwargs):\n        if self.category == Category.MODEL:\n            return self._client.parts(model=self, category=Category.INSTANCE, **kwargs)\n        else:\n            raise NotFoundError(\"Part {} is not a model\".format(self.name))",
    "docstring": "Retrieve the instances of this `Part` as a `PartSet`.\n\n        For instance, if you have a model part, you can get the list of instances that are created based on this\n        moodel. If there are no instances (only possible if the multiplicity is :attr:`enums.Multiplicity.ZERO_MANY`)\n        than a :exc:`NotFoundError` is returned\n\n        .. versionadded:: 1.8\n\n        :return: the instances of this part model :class:`PartSet` with category `INSTANCE`\n        :raises NotFoundError: if no instances found\n\n        Example\n        -------\n        >>> wheel_model = project.model('Wheel')\n        >>> wheel_instance_set = wheel_model.instances()\n\n        An example with retrieving the front wheels only using the 'name__contains' search argument.\n\n        >>> wheel_model = project.model('Wheel')\n        >>> front_wheel_instances = wheel_model.instances(name__contains='Front')"
  },
  {
    "code": "def CountClientPlatformsByLabel(self, day_buckets):\n    def ExtractPlatform(client_info):\n      return client_info.last_snapshot.knowledge_base.os\n    return self._CountClientStatisticByLabel(day_buckets, ExtractPlatform)",
    "docstring": "Computes client-activity stats for all client platforms in the DB."
  },
  {
    "code": "def filename(self):\n        if self.buildver:\n            buildver = '-' + self.buildver\n        else:\n            buildver = ''\n        pyver = '.'.join(self.pyver)\n        abi = '.'.join(self.abi)\n        arch = '.'.join(self.arch)\n        version = self.version.replace('-', '_')\n        return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver,\n                                         pyver, abi, arch)",
    "docstring": "Build and return a filename from the various components."
  },
  {
    "code": "def _get_aeff_corrections(intensity_ratio, mask):\n        nebins = len(intensity_ratio.data)\n        aeff_corrections = np.zeros((nebins))\n        for i in range(nebins):\n            bright_pixels_intensity = intensity_ratio.data[i][mask.data[i]]\n            mean_bright_pixel = bright_pixels_intensity.mean()\n            aeff_corrections[i] = 1. / mean_bright_pixel\n        print(\"Aeff correction: \", aeff_corrections)\n        return aeff_corrections",
    "docstring": "Compute a correction for the effective area from the brighter pixesl"
  },
  {
    "code": "def find_visible_birthdays(request, data):\n    if request.user and (request.user.is_teacher or request.user.is_eighthoffice or request.user.is_eighth_admin):\n        return data\n    data['today']['users'] = [u for u in data['today']['users'] if u['public']]\n    data['tomorrow']['users'] = [u for u in data['tomorrow']['users'] if u['public']]\n    return data",
    "docstring": "Return only the birthdays visible to current user."
  },
  {
    "code": "def ceiling_func(self, addr):\n        try:\n            next_addr = self._function_map.ceiling_addr(addr)\n            return self._function_map.get(next_addr)\n        except KeyError:\n            return None",
    "docstring": "Return the function who has the least address that is greater than or equal to `addr`.\n\n        :param int addr: The address to query.\n        :return:         A Function instance, or None if there is no other function after `addr`.\n        :rtype:          Function or None"
  },
  {
    "code": "def visit_return(self, node):\n        if node.is_tuple_return() and len(node.value.elts) > 1:\n            elts = [child.accept(self) for child in node.value.elts]\n            return \"return %s\" % \", \".join(elts)\n        if node.value:\n            return \"return %s\" % node.value.accept(self)\n        return \"return\"",
    "docstring": "return an astroid.Return node as string"
  },
  {
    "code": "def hour_angle(times, longitude, equation_of_time):\n    naive_times = times.tz_localize(None)\n    hrs_minus_tzs = 1 / NS_PER_HR * (\n        2 * times.astype(np.int64) - times.normalize().astype(np.int64) -\n        naive_times.astype(np.int64))\n    return np.asarray(\n        15. * (hrs_minus_tzs - 12.) + longitude + equation_of_time / 4.)",
    "docstring": "Hour angle in local solar time. Zero at local solar noon.\n\n    Parameters\n    ----------\n    times : :class:`pandas.DatetimeIndex`\n        Corresponding timestamps, must be localized to the timezone for the\n        ``longitude``.\n    longitude : numeric\n        Longitude in degrees\n    equation_of_time : numeric\n        Equation of time in minutes.\n\n    Returns\n    -------\n    hour_angle : numeric\n        Hour angle in local solar time in degrees.\n\n    References\n    ----------\n    [1] J. A. Duffie and W. A. Beckman,  \"Solar Engineering of Thermal\n    Processes, 3rd Edition\" pp. 13, J. Wiley and Sons, New York (2006)\n\n    [2] J. H. Seinfeld and S. N. Pandis, \"Atmospheric Chemistry and Physics\"\n    p. 132, J. Wiley (1998)\n\n    [3] Daryl R. Myers, \"Solar Radiation: Practical Modeling for Renewable\n    Energy Applications\", p. 5 CRC Press (2013)\n\n    See Also\n    --------\n    equation_of_time_Spencer71\n    equation_of_time_pvcdrom"
  },
  {
    "code": "def calculate_delay(original, delay):\n    original = datetime.strptime(original, '%H:%M')\n    delayed = datetime.strptime(delay, '%H:%M')\n    diff = delayed - original\n    return diff.total_seconds() // 60",
    "docstring": "Calculate the delay"
  },
  {
    "code": "def put(self, user_name: str) -> User:\n        current = current_user()\n        if current.name == user_name or current.is_admin:\n            user = self._get_or_abort(user_name)\n            self.update(user)\n            session.commit()\n            session.add(user)\n            return user\n        else:\n            abort(403)",
    "docstring": "Updates the User Resource with the\n        name."
  },
  {
    "code": "def save_to_disk(self, filename_pattern=None):\n    if not self._converter:\n      raise RuntimeError(\n          'Must set _converter on subclass or via set_converter before calling '\n          'save_to_disk.')\n    pattern = filename_pattern or self._default_filename_pattern\n    if not pattern:\n      raise RuntimeError(\n          'Must specify provide a filename_pattern or set a '\n          '_default_filename_pattern on subclass.')\n    def save_to_disk_callback(test_record_obj):\n      proto = self._convert(test_record_obj)\n      output_to_file = callbacks.OutputToFile(pattern)\n      with output_to_file.open_output_file(test_record_obj) as outfile:\n        outfile.write(proto.SerializeToString())\n    return save_to_disk_callback",
    "docstring": "Returns a callback to convert test record to proto and save to disk."
  },
  {
    "code": "def correct(self, image, keepSize=False, borderValue=0):\r\n        image = imread(image)\r\n        (h, w) = image.shape[:2]\r\n        mapx, mapy = self.getUndistortRectifyMap(w, h)\r\n        self.img = cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR,\r\n                             borderMode=cv2.BORDER_CONSTANT,\r\n                             borderValue=borderValue\r\n                             )\r\n        if not keepSize:\r\n            xx, yy, ww, hh = self.roi\r\n            self.img = self.img[yy: yy + hh, xx: xx + ww]\r\n        return self.img",
    "docstring": "remove lens distortion from given image"
  },
  {
    "code": "def data64_send(self, type, len, data, force_mavlink1=False):\n                return self.send(self.data64_encode(type, len, data), force_mavlink1=force_mavlink1)",
    "docstring": "Data packet, size 64\n\n                type                      : data type (uint8_t)\n                len                       : data length (uint8_t)\n                data                      : raw data (uint8_t)"
  },
  {
    "code": "def get_cmd_description(self):\n        try:\n            return self.description\n        except AttributeError:\n            pass\n        try:\n            return '\\n'.join(\n                get_localized_docstring(\n                    self, self.get_gettext_domain()\n                ).splitlines()[1:]\n            ).split('@EPILOG@', 1)[0].strip()\n        except (AttributeError, IndexError, ValueError):\n            pass",
    "docstring": "Get the leading, multi-line description of this command.\n\n        :returns:\n            ``self.description``, if defined\n        :returns:\n            A substring of the class docstring between the first line (which\n            is discarded) and the string ``@EPILOG@``, if present, or the end\n            of the docstring, if any\n        :returns:\n            None, otherwise\n\n        The description string will be displayed after the usage string but\n        before any of the detailed argument descriptions.\n\n        Please consider following good practice by keeping the description line\n        short enough not to require scrolling but useful enough to provide\n        additional information that cannot be inferred from the name of the\n        command or other arguments. Stating the purpose of the command is\n        highly recommended."
  },
  {
    "code": "def stop(self):\n        Global.LOGGER.info(\"stopping the flow manager\")\n        self._stop_actions()\n        self.isrunning = False\n        Global.LOGGER.debug(\"flow manager stopped\")",
    "docstring": "Stop all the processes"
  },
  {
    "code": "def location_path(self, path):\n        path = path.strip(\"/\")\n        tmp = path.split(\"?\")\n        path = tmp[0]\n        paths = path.split(\"/\")\n        for p in paths:\n            option = Option()\n            option.number = defines.OptionRegistry.LOCATION_PATH.number\n            option.value = p\n            self.add_option(option)",
    "docstring": "Set the Location-Path of the response.\n\n        :type path: String\n        :param path: the Location-Path as a string"
  },
  {
    "code": "def get_item_ids_metadata(self):\n        metadata = dict(self._item_ids_metadata)\n        metadata.update({'existing_id_values': self.my_osid_object_form._my_map['itemIds']})\n        return Metadata(**metadata)",
    "docstring": "get the metadata for item"
  },
  {
    "code": "def make_signature(signer_func, data_to_sign, public_algo,\n                   hashed_subpackets, unhashed_subpackets, sig_type=0):\n    header = struct.pack('>BBBB',\n                         4,\n                         sig_type,\n                         public_algo,\n                         8)\n    hashed = subpackets(*hashed_subpackets)\n    unhashed = subpackets(*unhashed_subpackets)\n    tail = b'\\x04\\xff' + struct.pack('>L', len(header) + len(hashed))\n    data_to_hash = data_to_sign + header + hashed + tail\n    log.debug('hashing %d bytes', len(data_to_hash))\n    digest = hashlib.sha256(data_to_hash).digest()\n    log.debug('signing digest: %s', util.hexlify(digest))\n    params = signer_func(digest=digest)\n    sig = b''.join(mpi(p) for p in params)\n    return bytes(header + hashed + unhashed +\n                 digest[:2] +\n                 sig)",
    "docstring": "Create new GPG signature."
  },
  {
    "code": "def show_cursor(self, show):\n        if show:\n            self.displaycontrol |= LCD_CURSORON\n        else:\n            self.displaycontrol &= ~LCD_CURSORON\n        self.write8(LCD_DISPLAYCONTROL | self.displaycontrol)",
    "docstring": "Show or hide the cursor.  Cursor is shown if show is True."
  },
  {
    "code": "def override(self, parameters, recursive = False):\n        result = Parameters()\n        if recursive:\n            RecursiveObjectWriter.copy_properties(result, self)\n            RecursiveObjectWriter.copy_properties(result, parameters)\n        else:\n            ObjectWriter.set_properties(result, self)\n            ObjectWriter.set_properties(result, parameters)\n        return result",
    "docstring": "Overrides parameters with new values from specified Parameters and returns a new Parameters object.\n\n        :param parameters: Parameters with parameters to override the current values.\n\n        :param recursive: (optional) true to perform deep copy, and false for shallow copy. Default: false\n\n        :return: a new Parameters object."
  },
  {
    "code": "def get_ip(self, access='public', addr_family=None, strict=None):\n        if addr_family not in ['IPv4', 'IPv6', None]:\n            raise Exception(\"`addr_family` must be 'IPv4', 'IPv6' or None\")\n        if access not in ['private', 'public']:\n            raise Exception(\"`access` must be 'public' or 'private'\")\n        if not hasattr(self, 'ip_addresses'):\n            self.populate()\n        ip_addrs = [\n            ip_addr for ip_addr in self.ip_addresses\n            if ip_addr.access == access\n        ]\n        preferred_family = addr_family if addr_family else 'IPv4'\n        for ip_addr in ip_addrs:\n            if ip_addr.family == preferred_family:\n                return ip_addr.address\n        return ip_addrs[0].address if ip_addrs and not addr_family else None",
    "docstring": "Return the server's IP address.\n\n        Params:\n        - addr_family: IPv4, IPv6 or None. None prefers IPv4 but will\n                       return IPv6 if IPv4 addr was not available.\n        - access: 'public' or 'private'"
  },
  {
    "code": "def ok_check(function, *args, **kwargs):\n    req = function(*args, **kwargs)\n    if req.content.lower() != 'ok':\n        raise ClientException(req.content)\n    return req.content",
    "docstring": "Ensure that the response body is OK"
  },
  {
    "code": "def construct(self, mapping: dict, **kwargs):\n        assert '__type__' not in kwargs and '__args__' not in kwargs\n        mapping = {**mapping, **kwargs}\n        factory_fqdn = mapping.pop('__type__')\n        factory = self.load_name(factory_fqdn)\n        args = mapping.pop('__args__', [])\n        return factory(*args, **mapping)",
    "docstring": "Construct an object from a mapping\n\n        :param mapping: the constructor definition, with ``__type__`` name and keyword arguments\n        :param kwargs: additional keyword arguments to pass to the constructor"
  },
  {
    "code": "def get_padding(x, padding_value=0):\n  with tf.name_scope(\"padding\"):\n    return tf.to_float(tf.equal(x, padding_value))",
    "docstring": "Return float tensor representing the padding values in x.\n\n  Args:\n    x: int tensor with any shape\n    padding_value: int value that\n\n  Returns:\n    flaot tensor with same shape as x containing values 0 or 1.\n      0 -> non-padding, 1 -> padding"
  },
  {
    "code": "def playpause(self):\n        msg = cr.Message()\n        msg.type = cr.PLAYPAUSE\n        self.send_message(msg)",
    "docstring": "Sends a \"playpause\" command to the player."
  },
  {
    "code": "def extractDates(self, inp):\n        def merge(param):\n            day, time = param\n            if not (day or time):\n                return None\n            if not day:\n                return time\n            if not time:\n                return day\n            return datetime.datetime(\n                day.year, day.month, day.day, time.hour, time.minute\n            )\n        days = self.extractDays(inp)\n        times = self.extractTimes(inp)\n        return map(merge, zip_longest(days, times, fillvalue=None))",
    "docstring": "Extract semantic date information from an input string.\n        In effect, runs both parseDay and parseTime on the input\n        string and merges the results to produce a comprehensive\n        datetime object.\n\n        Args:\n            inp (str): Input string to be parsed.\n\n        Returns:\n            A list of datetime objects containing the extracted dates from the\n            input snippet, or an empty list if not found."
  },
  {
    "code": "def matrix(mat):\n    import ROOT\n    if isinstance(mat, (ROOT.TMatrixD, ROOT.TMatrixDSym)):\n        return _librootnumpy.matrix_d(ROOT.AsCObject(mat))\n    elif isinstance(mat, (ROOT.TMatrixF, ROOT.TMatrixFSym)):\n        return _librootnumpy.matrix_f(ROOT.AsCObject(mat))\n    raise TypeError(\n        \"unable to convert object of type {0} \"\n        \"into a numpy matrix\".format(type(mat)))",
    "docstring": "Convert a ROOT TMatrix into a NumPy matrix.\n\n    Parameters\n    ----------\n    mat : ROOT TMatrixT\n        A ROOT TMatrixD or TMatrixF\n\n    Returns\n    -------\n    mat : numpy.matrix\n        A NumPy matrix\n\n    Examples\n    --------\n    >>> from root_numpy import matrix\n    >>> from ROOT import TMatrixD\n    >>> a = TMatrixD(4, 4)\n    >>> a[1][2] = 2\n    >>> matrix(a)\n    matrix([[ 0.,  0.,  0.,  0.],\n            [ 0.,  0.,  2.,  0.],\n            [ 0.,  0.,  0.,  0.],\n            [ 0.,  0.,  0.,  0.]])"
  },
  {
    "code": "def call(method: Method, *args: Any, **kwargs: Any) -> Any:\n    return validate_args(method, *args, **kwargs)(*args, **kwargs)",
    "docstring": "Validates arguments and then calls the method.\n\n    Args:\n        method: The method to call.\n        *args, **kwargs: Arguments to the method.\n\n    Returns:\n        The \"result\" part of the JSON-RPC response (the return value from the method).\n\n    Raises:\n        TypeError: If arguments don't match function signature."
  },
  {
    "code": "def _get_mpi_info(self):\n        rank = self.comm.Get_rank()\n        size = self.comm.Get_size()\n        return rank, size",
    "docstring": "get basic MPI info\n\n        Returns\n        -------\n        comm : Intracomm\n            Returns MPI communication group\n\n        rank : integer\n            Returns the rank of this process\n\n        size : integer\n            Returns total number of processes"
  },
  {
    "code": "def get_transition(self,\n                       line,\n                       line_index,\n                       column,\n                       is_escaped,\n                       comment_system_transitions,\n                       eof=False):\n        if (column == 0 and\n                comment_system_transitions.should_terminate_now(\n                    line,\n                    self._resume_waiting_for\n                )):\n            return (InTextParser(), 0, None)\n        if (_token_at_col_in_line(line,\n                                  column,\n                                  \"```\",\n                                  3) and\n                not _is_escaped(line, column, is_escaped)):\n            return (self._resume_parser((line_index, column + 3),\n                                        self._resume_waiting_for),\n                    3,\n                    None)\n        elif self._resume_waiting_for != ParserState.EOL:\n            wait_until_len = len(self._resume_waiting_for)\n            if (_token_at_col_in_line(line,\n                                      column,\n                                      self._resume_waiting_for,\n                                      wait_until_len) and\n                    not _is_escaped(line, column, is_escaped)):\n                return (InTextParser(),\n                        len(self._waiting_until),\n                        None)\n        elif eof:\n            return (InTextParser(), 0, None)\n        return (self, 1, None)",
    "docstring": "Get transition from DisabledParser."
  },
  {
    "code": "def _iter_over_selections(obj, dim, values):\n    from .groupby import _dummy_copy\n    dummy = None\n    for value in values:\n        try:\n            obj_sel = obj.sel(**{dim: value})\n        except (KeyError, IndexError):\n            if dummy is None:\n                dummy = _dummy_copy(obj)\n            obj_sel = dummy\n        yield obj_sel",
    "docstring": "Iterate over selections of an xarray object in the provided order."
  },
  {
    "code": "def checkGeneTreeMatchesSpeciesTree(speciesTree, geneTree, processID):\n    def fn(tree, l):\n        if tree.internal:\n            fn(tree.left, l)\n            fn(tree.right, l)\n        else:\n            l.append(processID(tree.iD))\n    l = []\n    fn(speciesTree, l)\n    l2 = []\n    fn(geneTree, l2)\n    for i in l2:\n        assert i in l",
    "docstring": "Function to check ids in gene tree all match nodes in species tree"
  },
  {
    "code": "def remove_major_minor_suffix(scripts):\n    minor_major_regex = re.compile(\"-\\d.?\\d?$\")\n    return [x for x in scripts if not minor_major_regex.search(x)]",
    "docstring": "Checks if executables already contain a \"-MAJOR.MINOR\" suffix."
  },
  {
    "code": "def conv1d(ni:int, no:int, ks:int=1, stride:int=1, padding:int=0, bias:bool=False):\n    \"Create and initialize a `nn.Conv1d` layer with spectral normalization.\"\n    conv = nn.Conv1d(ni, no, ks, stride=stride, padding=padding, bias=bias)\n    nn.init.kaiming_normal_(conv.weight)\n    if bias: conv.bias.data.zero_()\n    return spectral_norm(conv)",
    "docstring": "Create and initialize a `nn.Conv1d` layer with spectral normalization."
  },
  {
    "code": "def redraw_now(self, whence=0):\n        try:\n            time_start = time.time()\n            self.redraw_data(whence=whence)\n            self.update_image()\n            time_done = time.time()\n            time_delta = time_start - self.time_last_redraw\n            time_elapsed = time_done - time_start\n            self.time_last_redraw = time_done\n            self.logger.debug(\n                \"widget '%s' redraw (whence=%d) delta=%.4f elapsed=%.4f sec\" % (\n                    self.name, whence, time_delta, time_elapsed))\n        except Exception as e:\n            self.logger.error(\"Error redrawing image: %s\" % (str(e)))\n            try:\n                (type, value, tb) = sys.exc_info()\n                tb_str = \"\".join(traceback.format_tb(tb))\n                self.logger.error(\"Traceback:\\n%s\" % (tb_str))\n            except Exception:\n                tb_str = \"Traceback information unavailable.\"\n                self.logger.error(tb_str)",
    "docstring": "Redraw the displayed image.\n\n        Parameters\n        ----------\n        whence\n            See :meth:`get_rgb_object`."
  },
  {
    "code": "async def set_headline(self, name, level, message):\n        if name not in self.services:\n            raise ArgumentError(\"Unknown service name\", short_name=name)\n        self.services[name]['state'].set_headline(level, message)\n        headline = self.services[name]['state'].headline.to_dict()\n        await self._notify_update(name, 'new_headline', headline)",
    "docstring": "Set the sticky headline for a service.\n\n        Args:\n            name (string): The short name of the service to query\n            level (int): The level of the message (info, warning, error)\n            message (string): The message contents"
  },
  {
    "code": "def vectorize(e, tolerance=0.1):\n    tolerance = max(tolerance, e.linewidth)\n    is_high = e.height > tolerance\n    is_wide = e.width > tolerance\n    if is_wide and not is_high:\n        return (e.width, 0.0)\n    if is_high and not is_wide:\n        return (0.0, e.height)",
    "docstring": "vectorizes the pdf object's bounding box\n    min_width is the width under which we consider it a line\n    instead of a big rectangle"
  },
  {
    "code": "def parse_relative_path(root_path, experiment_config, key):\n    if experiment_config.get(key) and not os.path.isabs(experiment_config.get(key)):\n        absolute_path = os.path.join(root_path, experiment_config.get(key))\n        print_normal('expand %s: %s to %s ' % (key, experiment_config[key], absolute_path))\n        experiment_config[key] = absolute_path",
    "docstring": "Change relative path to absolute path"
  },
  {
    "code": "def list_aliases(self):\n        r = self.requests.get(self.index_url + \"/_alias\", headers=HEADER_JSON, verify=False)\n        try:\n            r.raise_for_status()\n        except requests.exceptions.HTTPError as ex:\n            logger.warning(\"Something went wrong when retrieving aliases on %s.\",\n                           self.anonymize_url(self.index_url))\n            logger.warning(ex)\n            return\n        aliases = r.json()[self.index]['aliases']\n        return aliases",
    "docstring": "List aliases linked to the index"
  },
  {
    "code": "def cleaned_date(day, keep_datetime=False):\n    if not isinstance(day, (date, datetime)):\n        raise UnsupportedDateType(\n            \"`{}` is of unsupported type ({})\".format(day, type(day)))\n    if not keep_datetime:\n        if hasattr(day, 'date') and callable(day.date):\n            day = day.date()\n    return day",
    "docstring": "Return a \"clean\" date type.\n\n    * keep a `date` unchanged\n    * convert a datetime into a date,\n    * convert any \"duck date\" type into a date using its `date()` method."
  },
  {
    "code": "def check_for_input_len_diff(*args):\n    arrays_len = [len(arr) for arr in args]\n    if not all(a == arrays_len[0] for a in arrays_len):\n        err_msg = (\"Error: mismatched data lengths, check to ensure that all \"\n                   \"input data is the same length and valid\")\n        raise Exception(err_msg)",
    "docstring": "Check for Input Length Difference.\n\n    This method checks if multiple data sets that are inputted are all the same\n    size. If they are not the same length an error is raised with a custom\n    message that informs the developer that the data set's lengths are not the\n    same."
  },
  {
    "code": "def _nonempty_project(string):\n    value = str(string)\n    if len(value) == 0:\n        msg = \"No project provided and no default project configured\"\n        raise argparse.ArgumentTypeError(msg)\n    return value",
    "docstring": "Argparse validator for ensuring a workspace is provided"
  },
  {
    "code": "def paramtypes(self):\n        for m in [p[1] for p in self.ports]:\n            for p in [p[1] for p in m]:\n                for pd in p:\n                    if pd[1] in self.params:\n                        continue\n                    item = (pd[1], pd[1].resolve())\n                    self.params.append(item)",
    "docstring": "get all parameter types"
  },
  {
    "code": "def with_source(self, lease):\n        self.partition_id = lease.partition_id\n        self.epoch = lease.epoch\n        self.owner = lease.owner\n        self.token = lease.token\n        self.event_processor_context = lease.event_processor_context",
    "docstring": "Init with existing lease.\n\n        :param lease: An existing Lease.\n        :type lease: ~azure.eventprocessorhost.lease.Lease"
  },
  {
    "code": "def add_transcript(self, transcript):\n        logger.debug(\"Adding transcript {0} to variant {1}\".format(\n            transcript, self['variant_id']))\n        self['transcripts'].append(transcript)",
    "docstring": "Add the information transcript\n\n            This adds a transcript dict to variant['transcripts']\n\n            Args:\n                transcript (dict): A transcript dictionary"
  },
  {
    "code": "def load_all(self, key, default=None):\n        value = getattr(self, key)\n        if default is not None:\n            def loader(path): return self.load_path_with_default(path, default)\n        else:\n            loader = self.load_path\n        if isinstance(value, dict):\n            return {key: loader(value) for key, value in value.items()}\n        elif isinstance(value, list):\n            return [loader(value) for value in value]\n        else:\n            raise ValueError('load_all must be list or dict')",
    "docstring": "Import settings key as a dict or list with values of importable paths\n        If a default constructor is specified, and a path is not importable, it\n        falls back to running the given constructor."
  },
  {
    "code": "def add_dependency(self,my_dep):\n        if self.dependency_layer is None:\n            self.dependency_layer = Cdependencies()\n            self.root.append(self.dependency_layer.get_node())\n        self.dependency_layer.add_dependency(my_dep)",
    "docstring": "Adds a dependency to the dependency layer\n        @type my_dep: L{Cdependency}\n        @param my_dep: dependency object"
  },
  {
    "code": "def get_connection(**kwargs):\n    kwargs = clean_kwargs(**kwargs)\n    if 'pyeapi.conn' in __proxy__:\n        return __proxy__['pyeapi.conn']()\n    conn, kwargs = _prepare_connection(**kwargs)\n    return conn",
    "docstring": "Return the connection object to the pyeapi Node.\n\n    .. warning::\n\n        This function returns an unserializable object, hence it is not meant\n        to be used on the CLI. This should mainly be used when invoked from\n        other modules for the low level connection with the network device.\n\n    kwargs\n        Key-value dictionary with the authentication details.\n\n    USAGE Example:\n\n    .. code-block:: python\n\n        conn = __salt__['pyeapi.get_connection'](host='router1.example.com',\n                                                 username='example',\n                                                 password='example')\n        show_ver = conn.run_commands(['show version', 'show interfaces'])"
  },
  {
    "code": "def lookup(self, lookup_url, url_key=None):\n        url_ending = self._get_ending(lookup_url)\n        params = {\n            'url_ending': url_ending,\n            'url_key': url_key\n        }\n        data, r = self._make_request(self.api_lookup_endpoint, params)\n        if r.status_code == 401:\n            if url_key is not None:\n                raise exceptions.UnauthorizedKeyError('given url_key is not valid for secret lookup.')\n            raise exceptions.UnauthorizedKeyError\n        elif r.status_code == 404:\n            return False\n        action = data.get('action')\n        full_url = data.get('result')\n        if action == 'lookup' and full_url is not None:\n            return full_url\n        raise exceptions.DebugTempWarning",
    "docstring": "Looks up the url_ending to obtain information about the short url.\n\n        If it exists, the API will return a dictionary with information, including\n        the long_url that is the destination of the given short url URL.\n\n\n        The lookup object looks like something like this:\n\n        .. code-block:: python\n\n            {\n                'clicks': 42,\n                'created_at':\n                    {\n                        'date': '2017-12-03 00:40:45.000000',\n                        'timezone': 'UTC',\n                        'timezone_type': 3\n                    },\n                'long_url': 'https://stackoverflow.com/questions/tagged/python',\n                'updated_at':\n                    {\n                        'date': '2017-12-24 13:37:00.000000',\n                        'timezone': 'UTC',\n                        'timezone_type': 3\n                    }\n            }\n\n        :param str lookup_url: An url ending or full short url address\n        :param url_key: optional URL ending key for lookups against secret URLs\n        :type url_key: str or None\n        :return: Lookup dictionary containing, among others things, the long url; or None if not existing\n        :rtype: dict or None"
  },
  {
    "code": "def main():\n    parser, args = parser_factory()\n    try:\n        action_runner(parser, args)\n    except Exception as uncaught:\n        unhandled(uncaught, args)\n        sys.exit(1)",
    "docstring": "Entrypoint, sweet Entrypoint"
  },
  {
    "code": "def encode_setid(uint128):\n    hi, lo = divmod(uint128, 2**64)\n    return b32encode(struct.pack('<QQ', lo, hi))[:-6].lower()",
    "docstring": "Encode uint128 setid as stripped b32encoded string"
  },
  {
    "code": "def __to_browser(self, message_no):\n        filename = self.__to_file(message_no)\n        try:\n            command = self.config.get('General', 'browser_command')\n        except (ConfigParser.NoOptionError, AttributeError):\n            print 'Incorrect or missing .ini file. See --help.'\n            sys.exit(5)\n        command = str(command).format(filename)\n        command_list = command.split(' ')\n        try:\n            subprocess.Popen(command_list, stdout=subprocess.PIPE,\n                             stderr=subprocess.PIPE)\n        except OSError:\n            print 'Unable to execute the browsercommand:'\n            print command\n            print 'Exiting!'\n            sys.exit(21)",
    "docstring": "Write a single message to file and open the file in a\n        browser"
  },
  {
    "code": "def run(self):\n        salt.utils.process.appendproctitle(self.__class__.__name__)\n        halite.start(self.hopts)",
    "docstring": "Fire up halite!"
  },
  {
    "code": "def show_env(self, env):\r\n        self.dialog_manager.show(RemoteEnvDialog(env, parent=self))",
    "docstring": "Show environment variables."
  },
  {
    "code": "def delete(self, alias_name, timeout=-1):\n        uri = self.URI + \"/\" + alias_name\n        return self._client.delete(uri, timeout=timeout)",
    "docstring": "Revokes a certificate signed by the internal CA. If client certificate to be revoked is RabbitMQ_readonly,\n        then the internal CA root certificate, RabbitMQ client certificate and RabbitMQ server certificate will be\n        regenerated. This will invalidate the previous version of RabbitMQ client certificate and the RabbitMQ server\n        will be restarted to read the latest certificates.\n\n        Args:\n            alias_name (str): Alias name.\n            timeout:\n                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n                in OneView, just stop waiting for its completion."
  },
  {
    "code": "def block(self, warn_only=False):\n        self._state = \"not finished\"\n        if self._return_code is None:\n            proc = subprocess.Popen(\n                self.cmd, cwd=self.cwd, env=self.env,\n                stdout=subprocess.PIPE,\n                stderr=subprocess.PIPE\n            )\n            self._stdout, self._stderr = proc.communicate(timeout=self.timeout)\n            self._return_code = proc.returncode\n        self._state = FINISHED\n        if not warn_only:\n            self.raise_for_error()",
    "docstring": "blocked executation."
  },
  {
    "code": "def config_read():\n    config_file = (u\"{0}config.ini\".format(CONFIG_DIR))\n    if not os.path.isfile(config_file):\n        config_make(config_file)\n    config = configparser.ConfigParser(allow_no_value=True)\n    try:\n        config.read(config_file, encoding='utf-8')\n    except IOError:\n        print(\"Error reading config file: {}\".format(config_file))\n        sys.exit()\n    providers = config_prov(config)\n    (cred, to_remove) = config_cred(config, providers)\n    for item in to_remove:\n        providers.remove(item)\n    return cred, providers",
    "docstring": "Read config info from config file."
  },
  {
    "code": "def get_calling_file(file_path=None, result='name'):\n    if file_path is None:\n        path = inspect.stack()[1][1]\n    else:\n        path = file_path\n    name = path.split('/')[-1].split('.')[0]\n    if result == 'name':\n        return name\n    elif result == 'path':\n        return path\n    else:\n        return path, name",
    "docstring": "Retrieve file_name or file_path of calling Python script"
  },
  {
    "code": "def download(self):\n        if not self.can_update():\n            self._tcex.handle_error(910, [self.type])\n        return self.tc_requests.download(self.api_type, self.api_sub_type, self.unique_id)",
    "docstring": "Downloads the signature.\n\n        Returns:"
  },
  {
    "code": "def _time_query_parms(begin_time, end_time):\n        query_parms = []\n        if begin_time is not None:\n            begin_ts = timestamp_from_datetime(begin_time)\n            qp = 'begin-time={}'.format(begin_ts)\n            query_parms.append(qp)\n        if end_time is not None:\n            end_ts = timestamp_from_datetime(end_time)\n            qp = 'end-time={}'.format(end_ts)\n            query_parms.append(qp)\n        query_parms_str = '&'.join(query_parms)\n        if query_parms_str:\n            query_parms_str = '?' + query_parms_str\n        return query_parms_str",
    "docstring": "Return the URI query paramterer string for the specified begin time\n        and end time."
  },
  {
    "code": "def event_date(self, event_date):\n        self._group_data['eventDate'] = self._utils.format_datetime(\n            event_date, date_format='%Y-%m-%dT%H:%M:%SZ'\n        )",
    "docstring": "Set the Events \"event date\" value."
  },
  {
    "code": "def version(self, event):\n        name = \"%s.%s\" % (self.__class__.__module__, self.__class__.__name__)\n        return \"%s [%s]\" % (settings.GNOTTY_VERSION_STRING, name)",
    "docstring": "Shows version information."
  },
  {
    "code": "def init_app(self, app):\n        self._key = app.config.get(CONF_KEY) or getenv(CONF_KEY)\n        if not self._key:\n            return\n        self._endpoint_uri = app.config.get(CONF_ENDPOINT_URI)\n        sender = AsynchronousSender(self._endpoint_uri)\n        queue = AsynchronousQueue(sender)\n        self._channel = TelemetryChannel(None, queue)\n        self._init_request_logging(app)\n        self._init_trace_logging(app)\n        self._init_exception_logging(app)",
    "docstring": "Initializes the extension for the provided Flask application.\n\n        Args:\n            app (flask.Flask). the Flask application for which to initialize the extension."
  },
  {
    "code": "def load(file_object, *transformers, **kwargs):\n    ignore_remaining_data = kwargs.get(\"ignore_remaining_data\", False)\n    marshaller = JavaObjectUnmarshaller(\n        file_object, kwargs.get(\"use_numpy_arrays\", False)\n    )\n    for transformer in transformers:\n        marshaller.add_transformer(transformer)\n    marshaller.add_transformer(DefaultObjectTransformer())\n    return marshaller.readObject(ignore_remaining_data=ignore_remaining_data)",
    "docstring": "Deserializes Java primitive data and objects serialized using\n    ObjectOutputStream from a file-like object.\n\n    :param file_object: A file-like object\n    :param transformers: Custom transformers to use\n    :param ignore_remaining_data: If True, don't log an error when unused\n                                  trailing bytes are remaining\n    :return: The deserialized object"
  },
  {
    "code": "def image_feature_engineering(features, feature_tensors_dict):\n  engineered_features = {}\n  for name, feature_tensor in six.iteritems(feature_tensors_dict):\n    if name in features and features[name]['transform'] == IMAGE_TRANSFORM:\n      with tf.name_scope(name, 'Wx_plus_b'):\n        hidden = tf.contrib.layers.fully_connected(\n            feature_tensor,\n            IMAGE_HIDDEN_TENSOR_SIZE)\n        engineered_features[name] = hidden\n    else:\n      engineered_features[name] = feature_tensor\n  return engineered_features",
    "docstring": "Add a hidden layer on image features.\n\n  Args:\n    features: features dict\n    feature_tensors_dict: dict of feature-name: tensor"
  },
  {
    "code": "def save(self, path=None):\n        if path==None: \n            if self._autosettings_path == None: return self\n            gui_settings_dir = _os.path.join(_cwd, 'egg_settings')\n            if not _os.path.exists(gui_settings_dir): _os.mkdir(gui_settings_dir)            \n            path = _os.path.join(gui_settings_dir, self._autosettings_path)\n        d = _d.databox()\n        keys, dictionary = self.get_dictionary()\n        for k in keys: \n            d.insert_header(k, dictionary[k])\n        try:\n            d.save_file(path, force_overwrite=True, header_only=True)\n        except:\n            print('Warning: could not save '+path.__repr__()+' once. Could be that this is being called too rapidly.')\n        return self",
    "docstring": "Saves all the parameters to a text file using the databox\n        functionality. If path=None, saves to self._autosettings_path. If\n        self._autosettings_path=None, does not save."
  },
  {
    "code": "def _modify_eni_properties(eni_id, properties=None, vm_=None):\n    if not isinstance(properties, dict):\n        raise SaltCloudException(\n            'ENI properties must be a dictionary'\n        )\n    params = {'Action': 'ModifyNetworkInterfaceAttribute',\n              'NetworkInterfaceId': eni_id}\n    for k, v in six.iteritems(properties):\n        params[k] = v\n    result = aws.query(params,\n                       return_root=True,\n                       location=get_location(vm_),\n                       provider=get_provider(),\n                       opts=__opts__,\n                       sigver='4')\n    if isinstance(result, dict) and result.get('error'):\n        raise SaltCloudException(\n            'Could not change interface <{0}> attributes <\\'{1}\\'>'.format(\n                eni_id, properties\n            )\n        )\n    else:\n        return result",
    "docstring": "Change properties of the interface\n    with id eni_id to the values in properties dict"
  },
  {
    "code": "def is_system_rpm(self):\n        sys_rpm_paths = [\n            '/usr/bin/rpm',\n            '/bin/rpm',\n        ]\n        matched = False\n        for sys_rpm_path in sys_rpm_paths:\n            if self.rpm_path.startswith(sys_rpm_path):\n                matched = True\n                break\n        return matched",
    "docstring": "Check if the RPM is system RPM."
  },
  {
    "code": "def reset(self):\n        logger.debug('StackInABoxService ({0}): Reset'\n                     .format(self.__id, self.name))\n        self.base_url = '/{0}'.format(self.name)\n        logger.debug('StackInABoxService ({0}): Hosting Service {1}'\n                     .format(self.__id, self.name))",
    "docstring": "Reset the service to its' initial state."
  },
  {
    "code": "def find_gsc_offset(image, input_catalog='GSC1', output_catalog='GAIA'):\n    serviceType = \"GSCConvert/GSCconvert.aspx\"\n    spec_str = \"TRANSFORM={}-{}&IPPPSSOOT={}\"\n    if 'rootname' in pf.getheader(image):\n        ippssoot = pf.getval(image, 'rootname').upper()\n    else:\n        ippssoot = fu.buildNewRootname(image).upper()\n    spec = spec_str.format(input_catalog, output_catalog, ippssoot)\n    serviceUrl = \"{}/{}?{}\".format(SERVICELOCATION, serviceType, spec)\n    rawcat = requests.get(serviceUrl)\n    if not rawcat.ok:\n        log.info(\"Problem accessing service with:\\n{{}\".format(serviceUrl))\n        raise ValueError\n    delta_ra = delta_dec = None\n    tree = BytesIO(rawcat.content)\n    for _, element in etree.iterparse(tree):\n        if element.tag == 'deltaRA':\n            delta_ra = float(element.text)\n        elif element.tag == 'deltaDEC':\n            delta_dec = float(element.text)\n    return delta_ra, delta_dec",
    "docstring": "Find the GSC to GAIA offset based on guide star coordinates\n\n    Parameters\n    ----------\n    image : str\n        Filename of image to be processed.\n\n    Returns\n    -------\n    delta_ra, delta_dec : tuple of floats\n        Offset in decimal degrees of image based on correction to guide star\n        coordinates relative to GAIA."
  },
  {
    "code": "def get_init_args(inst_type, init_args: dict, add_kwargs=False) -> Tuple[List, Dict]:\n    try:\n        parameters = signature(inst_type).parameters.values()\n        args_keys = [p.name for p in parameters \\\n                if p.kind in [Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD] \\\n                and p.default == Parameter.empty]\n        args = [init_args[key] for key in args_keys]\n        kwargs = _get_var_kwargs(parameters, args_keys, init_args)\\\n                 if add_kwargs else\\\n                 _get_kwargs(parameters, init_args)\n    except KeyError as key_error:\n        msg_format = 'parameter with key \"{0}\" is not found in node args'\n        raise RenderingError(msg_format.format(key_error.args[0]))\n    return (args, kwargs)",
    "docstring": "Returns tuple with args and kwargs to pass it to inst_type constructor"
  },
  {
    "code": "def jwt_grant(request, token_uri, assertion):\n    body = {\n        'assertion': assertion,\n        'grant_type': _JWT_GRANT_TYPE,\n    }\n    response_data = _token_endpoint_request(request, token_uri, body)\n    try:\n        access_token = response_data['access_token']\n    except KeyError as caught_exc:\n        new_exc = exceptions.RefreshError(\n            'No access token in response.', response_data)\n        six.raise_from(new_exc, caught_exc)\n    expiry = _parse_expiry(response_data)\n    return access_token, expiry, response_data",
    "docstring": "Implements the JWT Profile for OAuth 2.0 Authorization Grants.\n\n    For more details, see `rfc7523 section 4`_.\n\n    Args:\n        request (google.auth.transport.Request): A callable used to make\n            HTTP requests.\n        token_uri (str): The OAuth 2.0 authorizations server's token endpoint\n            URI.\n        assertion (str): The OAuth 2.0 assertion.\n\n    Returns:\n        Tuple[str, Optional[datetime], Mapping[str, str]]: The access token,\n            expiration, and additional data returned by the token endpoint.\n\n    Raises:\n        google.auth.exceptions.RefreshError: If the token endpoint returned\n            an error.\n\n    .. _rfc7523 section 4: https://tools.ietf.org/html/rfc7523#section-4"
  },
  {
    "code": "def limit(self, v):\n        if not (v is None or isinstance(v, six.integer_types)):\n            raise TypeError\n        if v == self._limit:\n            return self\n        if v < 0:\n            raise QueryException(\"Negative limit is not allowed\")\n        clone = copy.deepcopy(self)\n        clone._limit = v\n        return clone",
    "docstring": "Sets the limit on the number of results returned\n        CQL has a default limit of 10,000"
  },
  {
    "code": "def rank_member(self, member, score, member_data=None):\n        self.rank_member_in(self.leaderboard_name, member, score, member_data)",
    "docstring": "Rank a member in the leaderboard.\n\n        @param member [String] Member name.\n        @param score [float] Member score.\n        @param member_data [String] Optional member data."
  },
  {
    "code": "def mutate_json_record(self, json_record):\n        for attr_name in json_record:\n            attr = json_record[attr_name]\n            if isinstance(attr, datetime):\n                json_record[attr_name] = attr.isoformat()\n        return json_record",
    "docstring": "Override it to convert fields of `json_record` to needed types.\n\n        Default implementation converts `datetime` to string in ISO8601 format."
  },
  {
    "code": "def _chk_docopts(self, kws):\n        outfile = kws['outfile']\n        if len(kws) == 2 and os.path.basename(kws['obo']) == \"go-basic.obo\" and \\\n            kws['outfile'] == self.dflt_outfile:\n            self._err(\"NO GO IDS SPECFIED\", err=False)\n        if 'obo' in outfile:\n            self._err(\"BAD outfile({O})\".format(O=outfile))\n        if 'gaf' in kws and 'gene2go' in kws:\n            self._err(\"SPECIFY ANNOTAIONS FROM ONE FILE\")\n        if 'gene2go' in kws:\n            if 'taxid' not in kws:\n                self._err(\"SPECIFIY taxid WHEN READ NCBI'S gene2go FILE\")",
    "docstring": "Check for common user command-line errors."
  },
  {
    "code": "def save_matpower(self, fd):\n        from pylon.io import MATPOWERWriter\n        MATPOWERWriter(self).write(fd)",
    "docstring": "Serialize the case as a MATPOWER data file."
  },
  {
    "code": "def validate_digit(value, start, end):\n    if not str(value).isdigit() or int(value) < start or int(value) > end:\n        raise ValueError('%s must be a digit from %s to %s' % (value, start, end))",
    "docstring": "validate if a digit is valid"
  },
  {
    "code": "def remove_folder(self, tree, prefix):\n        while True:\n            child = tree\n            tree = tree.parent\n            if not child.folders and not child.files:\n                del self.cache[tuple(prefix)]\n                if tree:\n                    del tree.folders[prefix.pop()]\n            if not tree or tree.folders or tree.files:\n                break",
    "docstring": "Used to remove any empty folders\n\n        If this folder is empty then it is removed. If the parent is empty as a\n        result, then the parent is also removed, and so on."
  },
  {
    "code": "def debug(self, i: int=None) -> str:\n        head = \"[\" + colors.yellow(\"debug\") + \"]\"\n        if i is not None:\n            head = str(i) + \" \" + head\n        return head",
    "docstring": "Returns a debug message"
  },
  {
    "code": "def insert_child(self, child_pid):\n        self._check_child_limits(child_pid)\n        try:\n            with db.session.begin_nested():\n                if not isinstance(child_pid, PersistentIdentifier):\n                    child_pid = resolve_pid(child_pid)\n                return PIDRelation.create(\n                    self._resolved_pid, child_pid, self.relation_type.id, None\n                )\n        except IntegrityError:\n            raise PIDRelationConsistencyError(\"PID Relation already exists.\")",
    "docstring": "Add the given PID to the list of children PIDs."
  },
  {
    "code": "async def list_state(self, request):\n        paging_controls = self._get_paging_controls(request)\n        head, root = await self._head_to_root(request.url.query.get(\n            'head', None))\n        validator_query = client_state_pb2.ClientStateListRequest(\n            state_root=root,\n            address=request.url.query.get('address', None),\n            sorting=self._get_sorting_message(request, \"default\"),\n            paging=self._make_paging_message(paging_controls))\n        response = await self._query_validator(\n            Message.CLIENT_STATE_LIST_REQUEST,\n            client_state_pb2.ClientStateListResponse,\n            validator_query)\n        return self._wrap_paginated_response(\n            request=request,\n            response=response,\n            controls=paging_controls,\n            data=response.get('entries', []),\n            head=head)",
    "docstring": "Fetches list of data entries, optionally filtered by address prefix.\n\n        Request:\n            query:\n                - head: The id of the block to use as the head of the chain\n                - address: Return entries whose addresses begin with this\n                prefix\n\n        Response:\n            data: An array of leaf objects with address and data keys\n            head: The head used for this query (most recent if unspecified)\n            link: The link to this exact query, including head block\n            paging: Paging info and nav, like total resources and a next link"
  },
  {
    "code": "def context(self):\n        parent = _ACTION_CONTEXT.set(self)\n        try:\n            yield self\n        finally:\n            _ACTION_CONTEXT.reset(parent)",
    "docstring": "Create a context manager that ensures code runs within action's context.\n\n        The action does NOT finish when the context is exited."
  },
  {
    "code": "def parse_alert(output):\n    for x in output.splitlines():\n        match = ALERT_PATTERN.match(x)\n        if match:\n            rec = {'timestamp': datetime.strptime(match.group('timestamp'),\n                                                  '%m/%d/%y-%H:%M:%S.%f'),\n                   'sid': int(match.group('sid')),\n                   'revision': int(match.group('revision')),\n                   'priority': int(match.group('priority')),\n                   'message': match.group('message'),\n                   'source': match.group('src'),\n                   'destination': match.group('dest'),\n                   'protocol': match.group('protocol'),\n                   }\n            if match.group('classtype'):\n                rec['classtype'] = match.group('classtype')\n            yield rec",
    "docstring": "Parses the supplied output and yields any alerts.\n\n    Example alert format:\n    01/28/14-22:26:04.885446  [**] [1:1917:11] INDICATOR-SCAN UPnP service discover attempt [**] [Classification: Detection of a Network Scan] [Priority: 3] {UDP} 10.1.1.132:58650 -> 239.255.255.250:1900\n\n    :param output: A string containing the output of running snort\n    :returns: Generator of snort alert dicts"
  },
  {
    "code": "def set_row_gap(self, value):\n        value = str(value) + 'px'\n        value = value.replace('pxpx', 'px')\n        self.style['grid-row-gap'] = value",
    "docstring": "Sets the gap value between rows\n\n        Args:\n            value (int or str): gap value (i.e. 10 or \"10px\")"
  },
  {
    "code": "def conditional_expected_average_profit(self, frequency=None, monetary_value=None):\n        if monetary_value is None:\n            monetary_value = self.data[\"monetary_value\"]\n        if frequency is None:\n            frequency = self.data[\"frequency\"]\n        p, q, v = self._unload_params(\"p\", \"q\", \"v\")\n        individual_weight = p * frequency / (p * frequency + q - 1)\n        population_mean = v * p / (q - 1)\n        return (1 - individual_weight) * population_mean + individual_weight * monetary_value",
    "docstring": "Conditional expectation of the average profit.\n\n        This method computes the conditional expectation of the average profit\n        per transaction for a group of one or more customers.\n\n        Parameters\n        ----------\n        frequency: array_like, optional\n            a vector containing the customers' frequencies.\n            Defaults to the whole set of frequencies used for fitting the model.\n        monetary_value: array_like, optional\n            a vector containing the customers' monetary values.\n            Defaults to the whole set of monetary values used for\n            fitting the model.\n\n        Returns\n        -------\n        array_like:\n            The conditional expectation of the average profit per transaction"
  },
  {
    "code": "def _ParseDistributedTrackingIdentifier(\n      self, parser_mediator, uuid_object, origin):\n    if uuid_object.version == 1:\n      event_data = windows_events.WindowsDistributedLinkTrackingEventData(\n          uuid_object, origin)\n      date_time = dfdatetime_uuid_time.UUIDTime(timestamp=uuid_object.time)\n      event = time_events.DateTimeValuesEvent(\n          date_time, definitions.TIME_DESCRIPTION_CREATION)\n      parser_mediator.ProduceEventWithEventData(event, event_data)\n    return '{{{0!s}}}'.format(uuid_object)",
    "docstring": "Extracts data from a Distributed Tracking identifier.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      uuid_object (uuid.UUID): UUID of the Distributed Tracking identifier.\n      origin (str): origin of the event (event source).\n\n    Returns:\n      str: UUID string of the Distributed Tracking identifier."
  },
  {
    "code": "def allow_port(port, proto='tcp', direction='both'):\n    ports = get_ports(proto=proto, direction=direction)\n    direction = direction.upper()\n    _validate_direction_and_proto(direction, proto)\n    directions = build_directions(direction)\n    results = []\n    for direction in directions:\n        _ports = ports[direction]\n        _ports.append(port)\n        results += allow_ports(_ports, proto=proto, direction=direction)\n    return results",
    "docstring": "Like allow_ports, but it will append to the\n    existing entry instead of replacing it.\n    Takes a single port instead of a list of ports.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' csf.allow_port 22 proto='tcp' direction='in'"
  },
  {
    "code": "def _save(self):\n        if self.__modified_flag:\n            self.__filename_rep.update_id_counter()\n            indexfilename = os.path.join(self.__dir, \"index.dat\")\n            self._write_file(\n                indexfilename,\n                (self.__index,\n                 self.__filename_rep))\n            self.__modified_flag = False",
    "docstring": "save the cache index, in case it was modified.\n\n        Saves the index table and the file name repository in the file\n        `index.dat`"
  },
  {
    "code": "def order_by(self, *field_names):\n        obj = self._clone()\n        obj._clear_ordering()\n        self._insert_ordering(obj, *field_names)\n        return obj",
    "docstring": "Returns a new QuerySet instance with the ordering changed.\n        We have a special field \"_random\""
  },
  {
    "code": "def check_updates(self, startup=False):\r\n        from spyder.workers.updates import WorkerUpdates\r\n        self.check_updates_action.setDisabled(True)\r\n        if self.thread_updates is not None:\r\n            self.thread_updates.terminate()\r\n        self.thread_updates = QThread(self)\r\n        self.worker_updates = WorkerUpdates(self, startup=startup)\r\n        self.worker_updates.sig_ready.connect(self._check_updates_ready)\r\n        self.worker_updates.sig_ready.connect(self.thread_updates.quit)\r\n        self.worker_updates.moveToThread(self.thread_updates)\r\n        self.thread_updates.started.connect(self.worker_updates.start)\r\n        self.thread_updates.start()",
    "docstring": "Check for spyder updates on github releases using a QThread."
  },
  {
    "code": "def add_metadata_defaults(md):\n    defaults = {\"batch\": None,\n                \"phenotype\": \"\"}\n    for k, v in defaults.items():\n        if k not in md:\n            md[k] = v\n    return md",
    "docstring": "Central location for defaults for algorithm inputs."
  },
  {
    "code": "def add_batch_parser(subparsers, parent_parser):\n    parser = subparsers.add_parser(\n        'batch',\n        help='Displays information about batches and submit new batches',\n        description='Provides subcommands to display Batch information and '\n        'submit Batches to the validator via the REST API.')\n    grand_parsers = parser.add_subparsers(title='subcommands',\n                                          dest='subcommand')\n    grand_parsers.required = True\n    add_batch_list_parser(grand_parsers, parent_parser)\n    add_batch_show_parser(grand_parsers, parent_parser)\n    add_batch_status_parser(grand_parsers, parent_parser)\n    add_batch_submit_parser(grand_parsers, parent_parser)",
    "docstring": "Adds arguments parsers for the batch list, batch show and batch status\n    commands\n\n        Args:\n            subparsers: Add parsers to this subparser object\n            parent_parser: The parent argparse.ArgumentParser object"
  },
  {
    "code": "def _warn_on_old_config(self):\n        old_sections = ['Allowed Applications', 'Ignored Applications']\n        for old_section in old_sections:\n            if self._parser.has_section(old_section):\n                error(\"Old config file detected. Aborting.\\n\"\n                      \"\\n\"\n                      \"An old section (e.g. [Allowed Applications]\"\n                      \" or [Ignored Applications] has been detected\"\n                      \" in your {} file.\\n\"\n                      \"I'd rather do nothing than do something you\"\n                      \" do not want me to do.\\n\"\n                      \"\\n\"\n                      \"Please read the up to date documentation on\"\n                      \" <https://github.com/lra/mackup> and migrate\"\n                      \" your configuration file.\"\n                      .format(MACKUP_CONFIG_FILE))",
    "docstring": "Warn the user if an old config format is detected."
  },
  {
    "code": "def update_cache(force=False, cache_file=None):\n    if not cache_file:\n        cache_file = find_config()\n    cache_config = devpipeline_configure.parser.read_config(cache_file)\n    cache = devpipeline_configure.cache._CachedConfig(cache_config, cache_file)\n    if force or _is_outdated(cache_file, cache):\n        cache = devpipeline_configure.config.process_config(\n            cache_config.get(\"DEFAULT\", \"dp.build_config\"),\n            os.path.dirname(cache_file),\n            \"build.cache\",\n            profiles=cache_config.get(\"DEFAULT\", \"dp.profile_name\", fallback=None),\n            overrides=cache_config.get(\"DEFAULT\", \"dp.overrides\", fallback=None),\n        )\n        devpipeline_core.sanitizer.sanitize(\n            cache, lambda n, m: print(\"{} [{}]\".format(m, n))\n        )\n    return cache",
    "docstring": "Load a build cache, updating it if necessary.\n\n    A cache is considered outdated if any of its inputs have changed.\n\n    Arguments\n    force -- Consider a cache outdated regardless of whether its inputs have\n             been modified."
  },
  {
    "code": "def load_data():\n    digits = load_digits()\n    X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, random_state=99, test_size=0.25)\n    ss = StandardScaler()\n    X_train = ss.fit_transform(X_train)\n    X_test = ss.transform(X_test)\n    return X_train, X_test, y_train, y_test",
    "docstring": "Load dataset, use 20newsgroups dataset"
  },
  {
    "code": "def _vertical_x(axis, ticks=None, max_width=5):\n    if ticks is None:\n        ticks = axis.get_xticks()\n    if (np.array(ticks) == np.rint(ticks)).all():\n        ticks = np.rint(ticks).astype(np.int)\n    if max([len(str(tick)) for tick in ticks]) > max_width:\n        axis.set_xticklabels(ticks, rotation='vertical')",
    "docstring": "Switch labels to vertical if they are long."
  },
  {
    "code": "def read_dataset(args, dataset):\n    path = os.path.join(vars(args)[dataset])\n    logger.info('reading data from {}'.format(path))\n    examples = [line.strip().split('\\t') for line in open(path)]\n    if args.max_num_examples > 0:\n        examples = examples[:args.max_num_examples]\n    dataset = gluon.data.SimpleDataset([(e[0], e[1], LABEL_TO_IDX[e[2]]) for e in examples])\n    dataset = dataset.transform(lambda s1, s2, label: (\n        ['NULL'] + s1.lower().split(),\n        ['NULL'] + s2.lower().split(), label),\n                                lazy=False)\n    logger.info('read {} examples'.format(len(dataset)))\n    return dataset",
    "docstring": "Read dataset from tokenized files."
  },
  {
    "code": "def writeline(self, data, crlf=\"\\r\\n\"):\n        if self.read_thread:\n            if self.read_thread.has_error():\n                raise RuntimeError(\"Error writing PIPE\")\n        if self.proc.poll() is not None:\n            raise RuntimeError(\"Process stopped\")\n        if self.__print_io:\n            self.logger.info(data, extra={'type': '-->'})\n        self.proc.stdin.write(bytearray(data + crlf, 'ascii'))\n        self.proc.stdin.flush()",
    "docstring": "Writeline implementation.\n\n        :param data: Data to write\n        :param crlf: Line end characters, defailt is \\r\\n\n        :return: Nothing\n        :raises: RuntimeError if errors happen while writing to PIPE or process stops."
  },
  {
    "code": "def ngram_similarity(samegrams, allgrams, warp=1.0):\n        if abs(warp - 1.0) < 1e-9:\n            similarity = float(samegrams) / allgrams\n        else:\n            diffgrams = float(allgrams - samegrams)\n            similarity = ((allgrams ** warp - diffgrams ** warp)\n                    / (allgrams ** warp))\n        return similarity",
    "docstring": "Similarity for two sets of n-grams.\n\n        :note: ``similarity = (a**e - d**e)/a**e`` where `a` is \\\n        \"all n-grams\", `d` is \"different n-grams\" and `e` is the warp.\n\n        :param samegrams: number of n-grams shared by the two strings.\n\n        :param allgrams: total of the distinct n-grams across the two strings.\n        :return: similarity in the range 0.0 to 1.0.\n\n        >>> from ngram import NGram\n        >>> NGram.ngram_similarity(5, 10)\n        0.5\n        >>> NGram.ngram_similarity(5, 10, warp=2)\n        0.75\n        >>> NGram.ngram_similarity(5, 10, warp=3)\n        0.875\n        >>> NGram.ngram_similarity(2, 4, warp=2)\n        0.75\n        >>> NGram.ngram_similarity(3, 4)\n        0.75"
  },
  {
    "code": "def register_endpoint(self, path, app=None):\n        if is_running_from_reloader() and not os.environ.get('DEBUG_METRICS'):\n            return\n        if app is None:\n            app = self.app or current_app\n        @app.route(path)\n        @self.do_not_track()\n        def prometheus_metrics():\n            from prometheus_client import multiprocess, CollectorRegistry\n            if 'prometheus_multiproc_dir' in os.environ:\n                registry = CollectorRegistry()\n            else:\n                registry = self.registry\n            if 'name[]' in request.args:\n                registry = registry.restricted_registry(request.args.getlist('name[]'))\n            if 'prometheus_multiproc_dir' in os.environ:\n                multiprocess.MultiProcessCollector(registry)\n            headers = {'Content-Type': CONTENT_TYPE_LATEST}\n            return generate_latest(registry), 200, headers",
    "docstring": "Register the metrics endpoint on the Flask application.\n\n        :param path: the path of the endpoint\n        :param app: the Flask application to register the endpoint on\n            (by default it is the application registered with this class)"
  },
  {
    "code": "def setOverlayWidthInMeters(self, ulOverlayHandle, fWidthInMeters):\n        fn = self.function_table.setOverlayWidthInMeters\n        result = fn(ulOverlayHandle, fWidthInMeters)\n        return result",
    "docstring": "Sets the width of the overlay quad in meters. By default overlays are rendered on a quad that is 1 meter across"
  },
  {
    "code": "def _norm_squared(args: Dict[str, Any]) -> float:\n    state = _state_shard(args)\n    return np.sum(np.abs(state) ** 2)",
    "docstring": "Returns the norm for each state shard."
  },
  {
    "code": "def open(self):\n        if self.is_active:\n            raise ValueError(\"Can not open an already open stream.\")\n        request_generator = _RequestQueueGenerator(\n            self._request_queue, initial_request=self._initial_request\n        )\n        call = self._start_rpc(iter(request_generator), metadata=self._rpc_metadata)\n        request_generator.call = call\n        if hasattr(call, \"_wrapped\"):\n            call._wrapped.add_done_callback(self._on_call_done)\n        else:\n            call.add_done_callback(self._on_call_done)\n        self._request_generator = request_generator\n        self.call = call",
    "docstring": "Opens the stream."
  },
  {
    "code": "def randomize(length=6, choices=None):\n    if type(choices) == str:\n        choices = list(choices)\n    choices = choices or ascii_lowercase\n    return \"\".join(choice(choices) for _ in range(length))",
    "docstring": "Returns a random string of the given length."
  },
  {
    "code": "def delete(self, force=False):\n        if self.model is None:\n            raise WorkflowsMissingModel()\n        with db.session.begin_nested():\n            db.session.delete(self.model)\n        return self",
    "docstring": "Delete a workflow object.\n\n        If `force` is ``False``, the record is soft-deleted, i.e. the record\n        stays in the database. This ensures e.g. that the same record\n        identifier cannot be used twice, and that you can still retrieve the\n        history of an object. If `force` is True, the record is completely\n        removed from the database.\n\n        :param force: Completely remove record from database."
  },
  {
    "code": "def to_dict(self):\n        if self.version < VERSION_3:\n            if len(self._caveat_data) > 0:\n                raise ValueError('cannot serialize pre-version3 macaroon with '\n                                 'external caveat data')\n            return json.loads(self._macaroon.serialize(\n                json_serializer.JsonSerializer()))\n        serialized = {\n            'm': json.loads(self._macaroon.serialize(\n                json_serializer.JsonSerializer())),\n            'v': self._version,\n        }\n        if self._namespace is not None:\n            serialized['ns'] = self._namespace.serialize_text().decode('utf-8')\n        caveat_data = {}\n        for id in self._caveat_data:\n            key = base64.b64encode(id).decode('utf-8')\n            value = base64.b64encode(self._caveat_data[id]).decode('utf-8')\n            caveat_data[key] = value\n        if len(caveat_data) > 0:\n            serialized['cdata'] = caveat_data\n        return serialized",
    "docstring": "Return a dict representation of the macaroon data in JSON format.\n        @return a dict"
  },
  {
    "code": "def data_shape(self):\n        if not self.header:\n            return -1\n        try:\n            nx = self.header['nx']['value']\n            ny = self.header['ny']['value']\n            nz = self.header['nz']['value']\n        except KeyError:\n            return -1\n        else:\n            return tuple(int(n) for n in (nx, ny, nz))",
    "docstring": "Shape tuple of the whole data block as determined from `header`.\n\n        If no header is available (i.e., before it has been initialized),\n        or any of the header entries ``'nx', 'ny', 'nz'`` is missing,\n        -1 is returned, which makes reshaping a no-op.\n        Otherwise, the returned shape is ``(nx, ny, nz)``.\n\n        Note: this is the shape of the data as defined by the header.\n        For a non-trivial axis ordering, the shape of actual data will\n        be different.\n\n        See Also\n        --------\n        data_storage_shape\n        data_axis_order"
  },
  {
    "code": "def output_row(self, name):\n        \"Output a scoring row.\"\n        print(\"%10s        %4d     %0.3f        %0.3f        %0.3f\"%(\n            name, self.gold, self.precision(), self.recall(), self.fscore()))",
    "docstring": "Output a scoring row."
  },
  {
    "code": "def get_mutations(study_id, gene_list, mutation_type=None,\n                  case_id=None):\n    genetic_profile = get_genetic_profiles(study_id, 'mutation')[0]\n    gene_list_str = ','.join(gene_list)\n    data = {'cmd': 'getMutationData',\n            'case_set_id': study_id,\n            'genetic_profile_id': genetic_profile,\n            'gene_list': gene_list_str,\n            'skiprows': -1}\n    df = send_request(**data)\n    if case_id:\n        df = df[df['case_id'] == case_id]\n    res = _filter_data_frame(df, ['gene_symbol', 'amino_acid_change'],\n                             'mutation_type', mutation_type)\n    mutations = {'gene_symbol': list(res['gene_symbol'].values()),\n                 'amino_acid_change': list(res['amino_acid_change'].values())}\n    return mutations",
    "docstring": "Return mutations as a list of genes and list of amino acid changes.\n\n    Parameters\n    ----------\n    study_id : str\n        The ID of the cBio study.\n        Example: 'cellline_ccle_broad' or 'paad_icgc'\n    gene_list : list[str]\n        A list of genes with their HGNC symbols.\n        Example: ['BRAF', 'KRAS']\n    mutation_type : Optional[str]\n        The type of mutation to filter to.\n        mutation_type can be one of: missense, nonsense, frame_shift_ins,\n        frame_shift_del, splice_site\n    case_id : Optional[str]\n        The case ID within the study to filter to.\n\n    Returns\n    -------\n    mutations : tuple[list]\n        A tuple of two lists, the first one containing a list of genes, and\n        the second one a list of amino acid changes in those genes."
  },
  {
    "code": "def url_for(obj, **kw):\n    if isinstance(obj, str):\n        return flask_url_for(obj, **kw)\n    try:\n        return current_app.default_view.url_for(obj, **kw)\n    except KeyError:\n        if hasattr(obj, \"_url\"):\n            return obj._url\n        elif hasattr(obj, \"url\"):\n            return obj.url\n    raise BuildError(repr(obj), kw, \"GET\")",
    "docstring": "Polymorphic variant of Flask's `url_for` function.\n\n    Behaves like the original function when the first argument is a\n    string. When it's an object, it"
  },
  {
    "code": "def compare_lists(old=None, new=None):\n    ret = dict()\n    for item in new:\n        if item not in old:\n            ret['new'] = item\n    for item in old:\n        if item not in new:\n            ret['old'] = item\n    return ret",
    "docstring": "Compare before and after results from various salt functions, returning a\n    dict describing the changes that were made"
  },
  {
    "code": "def _configure_buffer_sizes():\n    global PIPE_BUF_BYTES\n    global OS_PIPE_SZ\n    PIPE_BUF_BYTES = 65536\n    OS_PIPE_SZ = None\n    if not hasattr(fcntl, 'F_SETPIPE_SZ'):\n        import platform\n        if platform.system() == 'Linux':\n            fcntl.F_SETPIPE_SZ = 1031\n    try:\n        with open('/proc/sys/fs/pipe-max-size', 'r') as f:\n            OS_PIPE_SZ = min(int(f.read()), 1024 * 1024)\n            PIPE_BUF_BYTES = max(OS_PIPE_SZ, PIPE_BUF_BYTES)\n    except Exception:\n        pass",
    "docstring": "Set up module globals controlling buffer sizes"
  },
  {
    "code": "def get_dimension_by_name(dimension_name,**kwargs):\n    try:\n        if dimension_name is None:\n            dimension_name = ''\n        dimension = db.DBSession.query(Dimension).filter(func.lower(Dimension.name)==func.lower(dimension_name.strip())).one()\n        return get_dimension(dimension.id)\n    except NoResultFound:\n        raise ResourceNotFoundError(\"Dimension %s not found\"%(dimension_name))",
    "docstring": "Given a dimension name returns all its data. Used in convert functions"
  },
  {
    "code": "def show_driver(devname):\n    try:\n        module = ethtool.get_module(devname)\n    except IOError:\n        log.error('Driver information not implemented on %s', devname)\n        return 'Not implemented'\n    try:\n        businfo = ethtool.get_businfo(devname)\n    except IOError:\n        log.error('Bus information no available on %s', devname)\n        return 'Not available'\n    ret = {\n        'driver': module,\n        'bus_info': businfo,\n    }\n    return ret",
    "docstring": "Queries the specified network device for associated driver information\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' ethtool.show_driver <devname>"
  },
  {
    "code": "def _notify_fn(self):\n        self._notifyrunning = True\n        while self._notifyrunning:\n            try:\n                with IHCController._mutex:\n                    if self._newnotifyids:\n                        self.client.enable_runtime_notifications(\n                            self._newnotifyids)\n                        self._newnotifyids = []\n                changes = self.client.wait_for_resource_value_changes()\n                if changes is False:\n                    self.re_authenticate(True)\n                    continue\n                for ihcid in changes:\n                    value = changes[ihcid]\n                    if ihcid in self._ihcevents:\n                        for callback in self._ihcevents[ihcid]:\n                            callback(ihcid, value)\n            except Exception as exp:\n                self.re_authenticate(True)",
    "docstring": "The notify thread function."
  },
  {
    "code": "def inMicrolensRegion_main(args=None):\n    import argparse\n    parser = argparse.ArgumentParser(\n                    description=\"Check if a celestial coordinate is \"\n                                \"inside the K2C9 microlensing superstamp.\")\n    parser.add_argument('ra', nargs=1, type=float,\n                        help=\"Right Ascension in decimal degrees (J2000).\")\n    parser.add_argument('dec', nargs=1, type=float,\n                        help=\"Declination in decimal degrees (J2000).\")\n    args = parser.parse_args(args)\n    if inMicrolensRegion(args.ra[0], args.dec[0]):\n        print(\"Yes! The coordinate is inside the K2C9 superstamp.\")\n    else:\n        print(\"Sorry, the coordinate is NOT inside the K2C9 superstamp.\")",
    "docstring": "Exposes K2visible to the command line."
  },
  {
    "code": "def create_tarfile(files: List[str], tar_path: str) -> None:\n    with tarfile.open(tar_path, \"w:gz\") as tar:\n        for f in files:\n            tar.add(f)",
    "docstring": "Create a tar file based on the list of files passed"
  },
  {
    "code": "def model_fields(model, allow_pk=False, only=None, exclude=None,\n                 field_args=None, converter=None):\n    converter = converter or ModelConverter()\n    field_args = field_args or {}\n    model_fields = list(model._meta.sorted_fields)\n    if not allow_pk:\n        model_fields.pop(0)\n    if only:\n        model_fields = [x for x in model_fields if x.name in only]\n    elif exclude:\n        model_fields = [x for x in model_fields if x.name not in exclude]\n    field_dict = {}\n    for model_field in model_fields:\n        name, field = converter.convert(\n            model,\n            model_field,\n            field_args.get(model_field.name))\n        field_dict[name] = field\n    return field_dict",
    "docstring": "Generate a dictionary of fields for a given Peewee model.\n\n    See `model_form` docstring for description of parameters."
  },
  {
    "code": "def receive(self, content, **kwargs):\n        self.connection_context = DjangoChannelConnectionContext(self.message)\n        self.subscription_server = DjangoChannelSubscriptionServer(graphene_settings.SCHEMA)\n        self.subscription_server.on_open(self.connection_context)\n        self.subscription_server.handle(content, self.connection_context)",
    "docstring": "Called when a message is received with either text or bytes\n        filled out."
  },
  {
    "code": "def add_specification(self, specification):\n\t\tname = specification.name()\n\t\tif name in self.__specs:\n\t\t\traise ValueError('WStrictURIQuery object already has specification for parameter \"%s\" ' % name)\n\t\tself.__specs[name] = specification",
    "docstring": "Add a new query parameter specification. If this object already has a specification for the\n\t\tspecified parameter - exception is raised. No checks for the specified or any parameter are made\n\t\tregarding specification appending\n\n\t\t:param specification: new specification that will be added\n\t\t:return: None"
  },
  {
    "code": "def __xinclude_libxml2(target, source, env):\n    doc = libxml2.readFile(str(source[0]), None, libxml2.XML_PARSE_NOENT)\n    doc.xincludeProcessFlags(libxml2.XML_PARSE_NOENT)\n    doc.saveFile(str(target[0]))\n    doc.freeDoc()\n    return None",
    "docstring": "Resolving XIncludes, using the libxml2 module."
  },
  {
    "code": "def open(cls, grammar_filename, rel_to=None, **options):\n        if rel_to:\n            basepath = os.path.dirname(rel_to)\n            grammar_filename = os.path.join(basepath, grammar_filename)\n        with open(grammar_filename, encoding='utf8') as f:\n            return cls(f, **options)",
    "docstring": "Create an instance of Lark with the grammar given by its filename\n\n        If rel_to is provided, the function will find the grammar filename in relation to it.\n\n        Example:\n\n            >>> Lark.open(\"grammar_file.lark\", rel_to=__file__, parser=\"lalr\")\n            Lark(...)"
  },
  {
    "code": "def fetch(self, x, y, w, h):\n        if not at_least_libvips(8, 8):\n            raise Error('libvips too old')\n        psize = ffi.new('size_t *')\n        pointer = vips_lib.vips_region_fetch(self.pointer, x, y, w, h, psize)\n        if pointer == ffi.NULL:\n            raise Error('unable to fetch from region')\n        pointer = ffi.gc(pointer, glib_lib.g_free)\n        return ffi.buffer(pointer, psize[0])",
    "docstring": "Fill a region with pixel data.\n\n        Pixels are filled with data!\n\n        Returns:\n            Pixel data.\n\n        Raises:\n            :class:`.Error`"
  },
  {
    "code": "def transform(self, attrs):\n        self.collect(attrs)\n        self.add_missing_implementations()\n        self.fill_attrs(attrs)",
    "docstring": "Perform all actions on a given attribute dict."
  },
  {
    "code": "def __validate_path_parameters(self, field, path_parameters):\n    for param in path_parameters:\n      segment_list = param.split('.')\n      if segment_list[0] != field.name:\n        raise TypeError('Subfield %r can\\'t come from field %r.'\n                        % (param, field.name))\n      self.__validate_simple_subfield(field.name, field, segment_list[1:])",
    "docstring": "Verifies that all path parameters correspond to an existing subfield.\n\n    Args:\n      field: An instance of a subclass of messages.Field. Should be the root\n          level property name in each path parameter in path_parameters. For\n          example, if the field is called 'foo', then each path parameter should\n          begin with 'foo.'.\n      path_parameters: A list of Strings representing URI parameter variables.\n\n    Raises:\n      TypeError: If one of the path parameters does not start with field.name."
  },
  {
    "code": "def group_shelf_fqfn(self):\n        if self._group_shelf_fqfn is None:\n            self._group_shelf_fqfn = os.path.join(\n                self.tcex.args.tc_temp_path, 'groups-{}'.format(str(uuid.uuid4()))\n            )\n            if self.saved_groups:\n                self._group_shelf_fqfn = os.path.join(self.tcex.args.tc_temp_path, 'groups-saved')\n        return self._group_shelf_fqfn",
    "docstring": "Return groups shelf fully qualified filename.\n\n        For testing/debugging a previous shelf file can be copied into the tc_temp_path directory\n        instead of creating a new shelf file."
  },
  {
    "code": "def __call_api(self, path, params=None, api_url=FORECAST_URL):\n        if not params:\n            params = dict()\n        payload = {'key': self.api_key}\n        payload.update(params)\n        url = \"%s/%s\" % (api_url, path)\n        sess = self.__retry_session()\n        req = sess.get(url, params=payload, timeout=1)\n        try:\n            data = req.json()\n        except ValueError:\n            raise APIException(\"DataPoint has not returned any data, this could be due to an incorrect API key\")\n        self.call_response = data\n        if req.status_code != 200:\n            msg = [data[m] for m in (\"message\", \"error_message\", \"status\") \\\n                      if m in data][0]\n            raise Exception(msg)\n        return data",
    "docstring": "Call the datapoint api using the requests module"
  },
  {
    "code": "def _dehex(s):\n    import re\n    import binascii\n    s = re.sub(br'[^a-fA-F\\d]', b'', s)\n    return binascii.unhexlify(s)",
    "docstring": "Liberally convert from hex string to binary string."
  },
  {
    "code": "def hosting_devices_assigned_to_cfg_agent(self, context, ids, host):\n        self._host_notification(context,\n                                'hosting_devices_assigned_to_cfg_agent',\n                                {'hosting_device_ids': ids}, host)",
    "docstring": "Notify cfg agent to now handle some hosting devices.\n\n        This notification relieves the cfg agent in <host> of responsibility\n        to monitor and configure hosting devices with id specified in <ids>."
  },
  {
    "code": "def show_tables():\n    _State.connection()\n    _State.reflect_metadata()\n    metadata = _State.metadata\n    response = select('name, sql from sqlite_master where type=\"table\"')\n    return {row['name']: row['sql'] for row in response}",
    "docstring": "Return the names of the tables currently in the database."
  },
  {
    "code": "def binary_dumps(obj, alt_format=False):\n    return b''.join(_binary_dump_gen(obj, alt_format=alt_format))",
    "docstring": "Serialize ``obj`` to a binary VDF formatted ``bytes``."
  },
  {
    "code": "def _compute_quads(self, element, data, mapping):\n        quad_mapping = {'left': 'x0', 'right': 'x1', 'bottom': 'y0', 'top': 'y1'}\n        quad_data = dict(data['scatter_1'])\n        quad_data.update({'x0': [], 'x1': [], 'y0': [], 'y1': []})\n        for node in element._sankey['nodes']:\n            quad_data['x0'].append(node['x0'])\n            quad_data['y0'].append(node['y0'])\n            quad_data['x1'].append(node['x1'])\n            quad_data['y1'].append(node['y1'])\n            data['scatter_1'].update(quad_data)\n        data['quad_1'] = data['scatter_1']\n        mapping['quad_1'] = quad_mapping",
    "docstring": "Computes the node quad glyph data.x"
  },
  {
    "code": "def architecture(self):\n        arch = {'class': self.__class__,\n                'n_in': self.n_in,\n                'n_units': self.n_units,\n                'activation_function': self.activation_function\n                if hasattr(self, 'activation_function') else None}\n        return arch",
    "docstring": "Returns a dictionary describing the architecture of the layer."
  },
  {
    "code": "def handle(self, record):\n        record = self.prepare(record)\n        for handler in self.handlers:\n            handler(record)",
    "docstring": "Handle an item.\n\n        This just loops through the handlers offering them the record\n        to handle."
  },
  {
    "code": "def createComment(self, *args, **kwargs):\n        return self._makeApiCall(self.funcinfo[\"createComment\"], *args, **kwargs)",
    "docstring": "Post a comment on a given GitHub Issue or Pull Request\n\n        For a given Issue or Pull Request of a repository, this will write a new message.\n\n        This method takes input: ``v1/create-comment.json#``\n\n        This method is ``experimental``"
  },
  {
    "code": "def Cinv(self):\n        try:\n            return np.linalg.inv(self.c)\n        except np.linalg.linalg.LinAlgError:\n            print('Warning: non-invertible noise covariance matrix c.')\n            return np.eye(self.c.shape[0])",
    "docstring": "Inverse of the noise covariance."
  },
  {
    "code": "def resize_psf(psf, input_pixel_scale, output_pixel_scale, order=3):\n    from scipy.ndimage import zoom\n    ratio = input_pixel_scale / output_pixel_scale\n    return zoom(psf, ratio, order=order) / ratio**2",
    "docstring": "Resize a PSF using spline interpolation of the requested order.\n\n    Parameters\n    ----------\n    psf : 2D `~numpy.ndarray`\n        The 2D data array of the PSF.\n\n    input_pixel_scale : float\n        The pixel scale of the input ``psf``.  The units must\n        match ``output_pixel_scale``.\n\n    output_pixel_scale : float\n        The pixel scale of the output ``psf``.  The units must\n        match ``input_pixel_scale``.\n\n    order : float, optional\n        The order of the spline interpolation (0-5).  The default is 3.\n\n    Returns\n    -------\n    result : 2D `~numpy.ndarray`\n        The resampled/interpolated 2D data array."
  },
  {
    "code": "def psychrometric_vapor_pressure_wet(dry_bulb_temperature, wet_bulb_temperature, pressure,\n                                     psychrometer_coefficient=6.21e-4 / units.kelvin):\n    r\n    return (saturation_vapor_pressure(wet_bulb_temperature) - psychrometer_coefficient\n            * pressure * (dry_bulb_temperature - wet_bulb_temperature).to('kelvin'))",
    "docstring": "r\"\"\"Calculate the vapor pressure with wet bulb and dry bulb temperatures.\n\n    This uses a psychrometric relationship as outlined in [WMO8-2014]_, with\n    coefficients from [Fan1987]_.\n\n    Parameters\n    ----------\n    dry_bulb_temperature: `pint.Quantity`\n        Dry bulb temperature\n    wet_bulb_temperature: `pint.Quantity`\n        Wet bulb temperature\n    pressure: `pint.Quantity`\n        Total atmospheric pressure\n    psychrometer_coefficient: `pint.Quantity`, optional\n        Psychrometer coefficient. Defaults to 6.21e-4 K^-1.\n\n    Returns\n    -------\n    `pint.Quantity`\n        Vapor pressure\n\n    Notes\n    -----\n    .. math:: e' = e'_w(T_w) - A p (T - T_w)\n\n    * :math:`e'` is vapor pressure\n    * :math:`e'_w(T_w)` is the saturation vapor pressure with respect to water at temperature\n      :math:`T_w`\n    * :math:`p` is the pressure of the wet bulb\n    * :math:`T` is the temperature of the dry bulb\n    * :math:`T_w` is the temperature of the wet bulb\n    * :math:`A` is the psychrometer coefficient\n\n    Psychrometer coefficient depends on the specific instrument being used and the ventilation\n    of the instrument.\n\n    See Also\n    --------\n    saturation_vapor_pressure"
  },
  {
    "code": "def flags(self, index):\r\n        if not index.isValid():\r\n            return Qt.ItemIsEnabled\r\n        return Qt.ItemFlags(QAbstractTableModel.flags(self, index)|\r\n                            Qt.ItemIsEditable)",
    "docstring": "Overriding method flags"
  },
  {
    "code": "def rm(self, path):\n        resp = self._sendRequest(\"DELETE\", path)\n        if not (resp.status_code in (200, 204)):\n            raise YaDiskException(resp.status_code, resp.content)",
    "docstring": "Delete file or directory."
  },
  {
    "code": "def put(self, rownr, value, matchingfields=True):\n        self._put(rownr, value, matchingfields)",
    "docstring": "Put the values into the given row.\n\n        The value should be a dict (as returned by method :func:`get`.\n        The names of the fields in the dict should match the names of the\n        columns used in the `tablerow` object.\n\n        `matchingfields=True` means that the value may contain more fields\n        and only fields matching a column name will be used."
  },
  {
    "code": "def parse_cuda_device(cuda_device: Union[str, int, List[int]]) -> Union[int, List[int]]:\n    def from_list(strings):\n        if len(strings) > 1:\n            return [int(d) for d in strings]\n        elif len(strings) == 1:\n            return int(strings[0])\n        else:\n            return -1\n    if isinstance(cuda_device, str):\n        return from_list(re.split(r',\\s*', cuda_device))\n    elif isinstance(cuda_device, int):\n        return cuda_device\n    elif isinstance(cuda_device, list):\n        return from_list(cuda_device)\n    else:\n        return int(cuda_device)",
    "docstring": "Disambiguates single GPU and multiple GPU settings for cuda_device param."
  },
  {
    "code": "def _compile_set(self, schema):\n        type_ = type(schema)\n        type_name = type_.__name__\n        def validate_set(path, data):\n            if not isinstance(data, type_):\n                raise er.Invalid('expected a %s' % type_name, path)\n            _compiled = [self._compile(s) for s in schema]\n            errors = []\n            for value in data:\n                for validate in _compiled:\n                    try:\n                        validate(path, value)\n                        break\n                    except er.Invalid:\n                        pass\n                else:\n                    invalid = er.Invalid('invalid value in %s' % type_name, path)\n                    errors.append(invalid)\n            if errors:\n                raise er.MultipleInvalid(errors)\n            return data\n        return validate_set",
    "docstring": "Validate a set.\n\n        A set is an unordered collection of unique elements.\n\n        >>> validator = Schema({int})\n        >>> validator(set([42])) == set([42])\n        True\n        >>> with raises(er.Invalid, 'expected a set'):\n        ...   validator(42)\n        >>> with raises(er.MultipleInvalid, 'invalid value in set'):\n        ...   validator(set(['a']))"
  },
  {
    "code": "def _QueryHash(self, nsrl_socket, digest):\n    try:\n      query = 'QUERY {0:s}\\n'.format(digest).encode('ascii')\n    except UnicodeDecodeError:\n      logger.error('Unable to encode digest: {0!s} to ASCII.'.format(digest))\n      return False\n    response = None\n    try:\n      nsrl_socket.sendall(query)\n      response = nsrl_socket.recv(self._RECEIVE_BUFFER_SIZE)\n    except socket.error as exception:\n      logger.error('Unable to query nsrlsvr with error: {0!s}.'.format(\n          exception))\n    if not response:\n      return False\n    response = response.strip()\n    return response == b'OK 1'",
    "docstring": "Queries nsrlsvr for a specific hash.\n\n    Args:\n      nsrl_socket (socket._socketobject): socket of connection to nsrlsvr.\n      digest (str): hash to look up.\n\n    Returns:\n      bool: True if the hash was found, False if not or None on error."
  },
  {
    "code": "def rounding(price, currency):\n\tcurrency = validate_currency(currency)\n\tprice = validate_price(price)\n\tif decimals(currency) == 0:\n\t\treturn round(int(price), decimals(currency))\n\treturn round(price, decimals(currency))",
    "docstring": "rounding currency value based on its max decimal digits"
  },
  {
    "code": "def attach(self, api_object, on_cloud=False):\n        if self.on_cloud:\n            return True\n        if api_object and getattr(api_object, 'attachments', None):\n            if on_cloud:\n                if not api_object.object_id:\n                    raise RuntimeError(\n                        'A valid object id is needed in order to attach a file')\n                url = api_object.build_url(self._endpoints.get('attach').format(\n                    id=api_object.object_id))\n                response = api_object.con.post(url, data=self.to_api_data())\n                return bool(response)\n            else:\n                if self.attachment_type == 'file':\n                    api_object.attachments.add([{\n                        'attachment_id': self.attachment_id,\n                        'path': str(\n                            self.attachment) if self.attachment else None,\n                        'name': self.name,\n                        'content': self.content,\n                        'on_disk': self.on_disk\n                    }])\n                else:\n                    raise RuntimeError('Only file attachments can be attached')",
    "docstring": "Attach this attachment to an existing api_object. This\n        BaseAttachment object must be an orphan BaseAttachment created for the\n        sole purpose of attach it to something and therefore run this method.\n\n        :param api_object: object to attach to\n        :param on_cloud: if the attachment is on cloud or not\n        :return: Success / Failure\n        :rtype: bool"
  },
  {
    "code": "def commands(self):\n        (self._commands, value) = self.get_cached_attr_set(self._commands, 'commands')\n        return value",
    "docstring": "Returns a list of commands that are supported by the motor\n        controller. Possible values are `run-forever`, `run-to-abs-pos`, `run-to-rel-pos`,\n        `run-timed`, `run-direct`, `stop` and `reset`. Not all commands may be supported.\n\n        - `run-forever` will cause the motor to run until another command is sent.\n        - `run-to-abs-pos` will run to an absolute position specified by `position_sp`\n          and then stop using the action specified in `stop_action`.\n        - `run-to-rel-pos` will run to a position relative to the current `position` value.\n          The new position will be current `position` + `position_sp`. When the new\n          position is reached, the motor will stop using the action specified by `stop_action`.\n        - `run-timed` will run the motor for the amount of time specified in `time_sp`\n          and then stop the motor using the action specified by `stop_action`.\n        - `run-direct` will run the motor at the duty cycle specified by `duty_cycle_sp`.\n          Unlike other run commands, changing `duty_cycle_sp` while running *will*\n          take effect immediately.\n        - `stop` will stop any of the run commands before they are complete using the\n          action specified by `stop_action`.\n        - `reset` will reset all of the motor parameter attributes to their default value.\n          This will also have the effect of stopping the motor."
  },
  {
    "code": "def snapshot(domain, name=None, suffix=None, **kwargs):\n    if name and name.lower() == domain.lower():\n        raise CommandExecutionError('Virtual Machine {name} is already defined. '\n                                    'Please choose another name for the snapshot'.format(name=name))\n    if not name:\n        name = \"{domain}-{tsnap}\".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime()))\n    if suffix:\n        name = \"{name}-{suffix}\".format(name=name, suffix=suffix)\n    doc = ElementTree.Element('domainsnapshot')\n    n_name = ElementTree.SubElement(doc, 'name')\n    n_name.text = name\n    conn = __get_conn(**kwargs)\n    _get_domain(conn, domain).snapshotCreateXML(\n        salt.utils.stringutils.to_str(ElementTree.tostring(doc))\n    )\n    conn.close()\n    return {'name': name}",
    "docstring": "Create a snapshot of a VM.\n\n    :param domain: domain name\n    :param name: Name of the snapshot. If the name is omitted, then will be used original domain\n                 name with ISO 8601 time as a suffix.\n\n    :param suffix: Add suffix for the new name. Useful in states, where such snapshots\n                   can be distinguished from manually created.\n    :param connection: libvirt connection URI, overriding defaults\n\n        .. versionadded:: 2019.2.0\n    :param username: username to connect with, overriding defaults\n\n        .. versionadded:: 2019.2.0\n    :param password: password to connect with, overriding defaults\n\n        .. versionadded:: 2019.2.0\n\n    .. versionadded:: 2016.3.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' virt.snapshot <domain>"
  },
  {
    "code": "def order(self, order):\n    order = order if isinstance(order, Order) else Order(order)\n    order.object_getattr = self.object_getattr\n    self.orders.append(order)\n    return self",
    "docstring": "Adds an Order to this query.\n\n    Args:\n      see :py:class:`Order <datastore.query.Order>` constructor\n\n    Returns self for JS-like method chaining::\n\n      query.order('+age').order('-home')"
  },
  {
    "code": "def getAggregator(cls, instanceId, name):\n    parent = cls.parentMap.get(instanceId)\n    while parent:\n      stat = cls.getStat(parent, name)\n      if stat:\n        return stat, parent\n      parent = cls.parentMap.get(statsId(parent))",
    "docstring": "Gets the aggregate stat for the given stat."
  },
  {
    "code": "def accept_quality(accept, default=1):\n    quality = default\n    if accept and \";\" in accept:\n        accept, rest = accept.split(\";\", 1)\n        accept_quality = RE_ACCEPT_QUALITY.search(rest)\n        if accept_quality:\n            quality = float(accept_quality.groupdict().get('quality', quality).strip())\n    return (quality, accept.strip())",
    "docstring": "Separates out the quality score from the accepted content_type"
  },
  {
    "code": "async def delay(source, delay):\n    await asyncio.sleep(delay)\n    async with streamcontext(source) as streamer:\n        async for item in streamer:\n            yield item",
    "docstring": "Delay the iteration of an asynchronous sequence."
  },
  {
    "code": "def _transfers(reaction, delta, elements, result, epsilon):\n    left = set(c for c, _ in reaction.left)\n    right = set(c for c, _ in reaction.right)\n    for c1, c2 in product(left, right):\n        items = {}\n        for e in elements:\n            v = result.get_value(delta[c1, c2, e])\n            nearest_int = round(v)\n            if abs(v - nearest_int) < epsilon:\n                v = int(nearest_int)\n            if v >= epsilon:\n                items[e] = v\n        if len(items) > 0:\n            yield (c1, c2), Formula(items)",
    "docstring": "Yield transfers obtained from result."
  },
  {
    "code": "def equal_length(*args):\n    for i, arg in enumerate(args):\n        if not isinstance(arg, Sized):\n            raise ExpectedTypeError(arg, [\"Sized\"])\n        if i >= 1 and len(arg) != len(args[0]):\n            raise DifferentLengthError(args, arg)",
    "docstring": "Check that arguments have the same length."
  },
  {
    "code": "def load_config(config, expand_env=False, force=False):\n    if not os.path.exists(config):\n        raise ConfigException('Unable to find configuration file: %s' % config)\n    file_extension = os.path.splitext(config)[1][1:]\n    conf = kaptan.Kaptan(handler=kaptan.HANDLER_EXT.get(file_extension))\n    if expand_env:\n        with open(config, 'r') as file_handler:\n            config = Template(file_handler.read())\n            config = config.substitute(os.environ)\n    conf.import_config(config)\n    return get_repos(conf.export('dict') or {}, force)",
    "docstring": "Return repos from a directory and fnmatch. Not recursive.\n\n    :param config: paths to config file\n    :type config: str\n    :param expand_env: True to expand environment varialbes in the config.\n    :type expand_env: bool\n    :param bool force: True to aggregate even if repo is dirty.\n    :returns: expanded config dict item\n    :rtype: iter(dict)"
  },
  {
    "code": "def module_can_run_parallel(test_module: unittest.TestSuite) -> bool:\n        for test_class in test_module:\n            if hasattr(unittest.loader, '_FailedTest'):\n                if isinstance(test_class, unittest.loader._FailedTest):\n                    continue\n            if not isinstance(test_class, collections.Iterable):\n                raise TestClassNotIterable()\n            for test_case in test_class:\n                return not getattr(sys.modules[test_case.__module__], \"__no_parallel__\", False)",
    "docstring": "Checks if a given module of tests can be run in parallel or not\n\n        :param test_module: the module to run\n        :return: True if the module can be run on parallel, False otherwise"
  },
  {
    "code": "def _record_call(func):\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        global global_error_context\n        if global_error_context is not None:\n            key = CallLogKey(name=func.__name__,\n                             args=[serialize_object_for_logging(arg) for arg in args],\n                             kwargs={k: serialize_object_for_logging(v) for k, v in kwargs.items()})\n            pre_entry = CallLogValue(timestamp_in=datetime.utcnow(),\n                                     timestamp_out=None,\n                                     return_value=None)\n            global_error_context.log[key] = pre_entry\n        val = func(*args, **kwargs)\n        if global_error_context is not None:\n            post_entry = CallLogValue(timestamp_in=pre_entry.timestamp_in,\n                                      timestamp_out=datetime.utcnow(),\n                                      return_value=serialize_object_for_logging(val))\n            global_error_context.log[key] = post_entry\n        return val\n    return wrapper",
    "docstring": "A decorator that logs a call into the global error context.\n\n    This is probably for internal use only."
  },
  {
    "code": "def clean():\n    os.chdir(os.path.join(project_root, 'docs'))\n    sh(\"make clean\")\n    os.chdir(project_root)\n    sh(\"rm -rf pyoauth2.egg-info\")",
    "docstring": "Clean up previous garbage"
  },
  {
    "code": "def blocks(self):\n        for block_addr, block in self._local_blocks.items():\n            try:\n                yield self._get_block(block_addr, size=block.size,\n                                      byte_string=block.bytestr if isinstance(block, BlockNode) else None)\n            except (SimEngineError, SimMemoryError):\n                pass",
    "docstring": "An iterator of all local blocks in the current function.\n\n        :return: angr.lifter.Block instances."
  },
  {
    "code": "def dump_dict(cfg, f, indent=0):\n    for key in cfg:\n        if not isstr(key):\n            raise ConfigSerializeError(\"Dict keys must be strings: %r\" %\n                                       (key,))\n        dump_value(key, cfg[key], f, indent)\n        f.write(u';\\n')",
    "docstring": "Save a dictionary of attributes"
  },
  {
    "code": "def get_parameters(params=None, path='', grad_only=True):\n    global current_scope\n    if params is None:\n        params = OrderedDict()\n    for k, v in iteritems(current_scope):\n        if isinstance(v, dict):\n            with parameter_scope(k):\n                params = get_parameters(\n                    params, '/'.join([path, k]) if path else k, grad_only=grad_only)\n        else:\n            assert isinstance(v, nn.Variable)\n            if not grad_only or v.need_grad:\n                params['/'.join([path, k]) if path else k] = v\n    return params",
    "docstring": "Get parameter Variables under the current parameter scope.\n\n    Args:\n        params (dict): Internal use. User doesn't set it manually.\n        path (str): Internal use.  User doesn't set it manually.\n        grad_only (bool): Retrieve all parameters under the current scope if\n            False, while only parameters with need_grad=True are retrieved\n            if True.\n\n    Returns:\n        dict: {:obj:`str` : :obj:`~nnabla.Variable`}"
  },
  {
    "code": "def export(self):\n        top = self._top_element()\n        properties = self._properties_element(top)\n        self._fill_requirements(top)\n        self._fill_lookup_prop(properties)\n        return utils.prettify_xml(top)",
    "docstring": "Returns requirements XML."
  },
  {
    "code": "def create_pull(self, title, base, head, body=None):\n        data = {'title': title, 'body': body, 'base': base,\n                'head': head}\n        return self._create_pull(data)",
    "docstring": "Create a pull request of ``head`` onto ``base`` branch in this repo.\n\n        :param str title: (required)\n        :param str base: (required), e.g., 'master'\n        :param str head: (required), e.g., 'username:branch'\n        :param str body: (optional), markdown formatted description\n        :returns: :class:`PullRequest <github3.pulls.PullRequest>` if\n            successful, else None"
  },
  {
    "code": "def plot(self):\n        import pylab as p\n        p.clf()\n        fig = p.figure(1)\n        nspw = len(self.gain[0])\n        ext = n.ceil(n.sqrt(nspw))\n        for spw in range(len(self.gain[0])):\n            ax = fig.add_subplot(ext, ext, spw+1)\n            for pol in [0,1]:\n                ax.scatter(range(len(self.gain)), n.abs(self.gain.data[:,spw,pol]), color=n.array(['k','y']).take(self.gain.mask[:,spw,pol]), marker=['x','.'][pol])\n        fig.show()",
    "docstring": "Quick visualization of calibration solution."
  },
  {
    "code": "def cyan(cls):\n        \"Make the text foreground color cyan.\"\n        wAttributes = cls._get_text_attributes()\n        wAttributes &= ~win32.FOREGROUND_MASK\n        wAttributes |=  win32.FOREGROUND_CYAN\n        cls._set_text_attributes(wAttributes)",
    "docstring": "Make the text foreground color cyan."
  },
  {
    "code": "def _load_custom(self, settings_name='localsettings.py'):\n        if settings_name[-3:] == '.py':\n            settings_name = settings_name[:-3]\n        new_settings = {}\n        try:\n            settings = importlib.import_module(settings_name)\n            new_settings = self._convert_to_dict(settings)\n        except ImportError:\n            log.info(\"No override settings found\")\n        for key in new_settings:\n            if key in self.my_settings:\n                item = new_settings[key]\n                if isinstance(item, dict) and \\\n                        isinstance(self.my_settings[key], dict):\n                    for key2 in item:\n                        self.my_settings[key][key2] = item[key2]\n                else:\n                    self.my_settings[key] = item\n            else:\n                self.my_settings[key] = new_settings[key]",
    "docstring": "Load the user defined settings, overriding the defaults"
  },
  {
    "code": "def hypergeometric_like(x, n, m, N):\n    R\n    return flib.hyperg(x, n, m, N)",
    "docstring": "R\"\"\"\n    Hypergeometric log-likelihood.\n\n    Discrete probability distribution that describes the number of successes in\n    a sequence of draws from a finite population without replacement.\n\n    .. math::\n\n        f(x \\mid n, m, N) = \\frac{\\left({ \\begin{array}{c} {m} \\\\ {x} \\\\\n        \\end{array} }\\right)\\left({ \\begin{array}{c} {N-m} \\\\ {n-x} \\\\\n        \\end{array}}\\right)}{\\left({ \\begin{array}{c} {N} \\\\ {n} \\\\\n        \\end{array}}\\right)}\n\n\n    :Parameters:\n      - `x` : [int] Number of successes in a sample drawn from a population.\n      - `n` : [int] Size of sample drawn from the population.\n      - `m` : [int] Number of successes in the population.\n      - `N` : [int] Total number of units in the population.\n\n    .. note::\n\n        :math:`E(X) = \\frac{n n}{N}`"
  },
  {
    "code": "def convert_camel_case_string(name: str) -> str:\n    string = re.sub(\"(.)([A-Z][a-z]+)\", r\"\\1_\\2\", name)\n    return re.sub(\"([a-z0-9])([A-Z])\", r\"\\1_\\2\", string).lower()",
    "docstring": "Convert camel case string to snake case"
  },
  {
    "code": "def find_all_declarations(\n        declarations,\n        decl_type=None,\n        name=None,\n        parent=None,\n        recursive=True,\n        fullname=None):\n    if recursive:\n        decls = make_flatten(declarations)\n    else:\n        decls = declarations\n    return list(\n        filter(\n            algorithm.match_declaration_t(\n                decl_type=decl_type,\n                name=name,\n                fullname=fullname,\n                parent=parent),\n            decls))",
    "docstring": "Returns a list of all declarations that match criteria, defined by\n    developer.\n\n    For more information about arguments see :class:`match_declaration_t`\n    class.\n\n    :rtype: [ matched declarations ]"
  },
  {
    "code": "def cmd_connection_type(self):\n        https = 0\n        non_https = 0\n        for line in self._valid_lines:\n            if line.is_https():\n                https += 1\n            else:\n                non_https += 1\n        return https, non_https",
    "docstring": "Generates statistics on how many requests are made via HTTP and how\n        many are made via SSL.\n\n        .. note::\n          This only works if the request path contains the default port for\n          SSL (443).\n\n        .. warning::\n          The ports are hardcoded, they should be configurable."
  },
  {
    "code": "def is_alive(self):\n        running = False\n        if not self.instance_id:\n            return False\n        try:\n            log.debug(\"Getting information for instance %s\",\n                      self.instance_id)\n            running = self._cloud_provider.is_instance_running(\n                self.instance_id)\n        except Exception as ex:\n            log.debug(\"Ignoring error while looking for vm id %s: %s\",\n                      self.instance_id, str(ex))\n        if running:\n            log.debug(\"node `%s` (instance id %s) is up and running\",\n                      self.name, self.instance_id)\n            self.update_ips()\n        else:\n            log.debug(\"node `%s` (instance id `%s`) still building...\",\n                      self.name, self.instance_id)\n        return running",
    "docstring": "Checks if the current node is up and running in the cloud. It\n        only checks the status provided by the cloud interface. Therefore a\n        node might be running, but not yet ready to ssh into it."
  },
  {
    "code": "def build_idx_set(branch_id, start_date):\n    code_set = branch_id.split(\"/\")\n    code_set.insert(3, \"Rates\")\n    idx_set = {\n        \"sec\": \"/\".join([code_set[0], code_set[1], \"Sections\"]),\n        \"mag\": \"/\".join([code_set[0], code_set[1], code_set[2], \"Magnitude\"])}\n    idx_set[\"rate\"] = \"/\".join(code_set)\n    idx_set[\"rake\"] = \"/\".join([code_set[0], code_set[1], \"Rake\"])\n    idx_set[\"msr\"] = \"-\".join(code_set[:3])\n    idx_set[\"geol\"] = code_set[0]\n    if start_date:\n        idx_set[\"grid_key\"] = \"_\".join(\n            branch_id.replace(\"/\", \"_\").split(\"_\")[:-1])\n    else:\n        idx_set[\"grid_key\"] = branch_id.replace(\"/\", \"_\")\n    idx_set[\"total_key\"] = branch_id.replace(\"/\", \"|\")\n    return idx_set",
    "docstring": "Builds a dictionary of keys based on the branch code"
  },
  {
    "code": "def split_thousands(s):\n    if s is None: return \"0\"\n    if isinstance(s, basestring): s = float(s)\n    if isinstance(s, float) and s.is_integer(): s = int(s)\n    result = \"{:,}\".format(s)\n    result = result.replace(',', \"'\")\n    return result",
    "docstring": "Splits a number on thousands.\n\n    >>> split_thousands(1000012)\n    \"1'000'012\""
  },
  {
    "code": "def _connect_nntp (self, nntpserver):\n        tries = 0\n        nntp = None\n        while tries < 2:\n            tries += 1\n            try:\n                nntp = nntplib.NNTP(nntpserver, usenetrc=False)\n            except nntplib.NNTPTemporaryError:\n                self.wait()\n            except nntplib.NNTPPermanentError as msg:\n                if re.compile(\"^50[45]\").search(str(msg)):\n                    self.wait()\n                else:\n                    raise\n        if nntp is None:\n            raise LinkCheckerError(\n               _(\"NNTP server too busy; tried more than %d times.\") % tries)\n        if log.is_debug(LOG_CHECK):\n            nntp.set_debuglevel(1)\n        self.add_info(nntp.getwelcome())\n        return nntp",
    "docstring": "This is done only once per checking task. Also, the newly\n        introduced error codes 504 and 505 (both inclining \"Too busy, retry\n        later\", are caught."
  },
  {
    "code": "def create_chunked_body_end(trailers=None):\n    chunk = []\n    chunk.append('0\\r\\n')\n    if trailers:\n        for name, value in trailers:\n            chunk.append(name)\n            chunk.append(': ')\n            chunk.append(value)\n            chunk.append('\\r\\n')\n    chunk.append('\\r\\n')\n    return s2b(''.join(chunk))",
    "docstring": "Create the ending that terminates a chunked body."
  },
  {
    "code": "def pipe_yql(context=None, _INPUT=None, conf=None, **kwargs):\n    url = \"http://query.yahooapis.com/v1/public/yql\"\n    conf = DotDict(conf)\n    query = conf['yqlquery']\n    for item in _INPUT:\n        item = DotDict(item)\n        yql = utils.get_value(query, item, **kwargs)\n        r = requests.get(url, params={'q': yql}, stream=True)\n        tree = parse(r.raw)\n        if context and context.verbose:\n            print \"pipe_yql loading xml:\", yql\n        root = tree.getroot()\n        results = root.find('results')\n        for element in results.getchildren():\n            yield utils.etree_to_dict(element)\n        if item.get('forever'):\n            break",
    "docstring": "A source that issues YQL queries. Loopable.\n\n    Parameters\n    ----------\n    context : pipe2py.Context object\n    _INPUT : pipeforever pipe or an iterable of items or fields\n    conf : yqlquery -- YQL query\n        # todo: handle envURL\n\n    Yields\n    ------\n    _OUTPUT : query results"
  },
  {
    "code": "def GetMemActiveMB(self):\n        counter = c_uint()\n        ret = vmGuestLib.VMGuestLib_GetMemActiveMB(self.handle.value, byref(counter))\n        if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)\n        return counter.value",
    "docstring": "Retrieves the amount of memory the virtual machine is actively using its\n           estimated working set size."
  },
  {
    "code": "def extensions():\n    import numpy\n    from Cython.Build import cythonize\n    ext = [\n            Extension('phydmslib.numutils', ['phydmslib/numutils.pyx'],\n                    include_dirs=[numpy.get_include()],\n                    extra_compile_args=['-Wno-unused-function']),\n          ]      \n    return cythonize(ext)",
    "docstring": "Returns list of `cython` extensions for `lazy_cythonize`."
  },
  {
    "code": "def get_confirmations_per_page(self, per_page=1000, page=1, params=None):\n        return self._get_resource_per_page(resource=CONFIRMATIONS, per_page=per_page, page=page, params=params)",
    "docstring": "Get confirmations per page\n\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :param params: Search parameters. Default: {}\n        :return: list"
  },
  {
    "code": "def close(self):\n        if self.connected:\n            obj = [self.proto.max_id, [[2], self.proto.send_count]]\n            ARBITRATOR.send_sync_message(self.proto, f\"4{to_json(obj)}\")\n            self.proto.send_count += 1\n            ARBITRATOR.close(self.proto)\n        self.listeners.clear()\n        self.proto.connected = False\n        super().close()\n        del self.room\n        del self.proto",
    "docstring": "Closes connection pair"
  },
  {
    "code": "def onChange(self, min_changed_pixels=None, handler=None):\n        if isinstance(min_changed_pixels, int) and (callable(handler) or handler is None):\n            return self._observer.register_event(\n                \"CHANGE\",\n                pattern=(min_changed_pixels, self.getBitmap()),\n                handler=handler)\n        elif (callable(min_changed_pixels) or min_changed_pixels is None) and (callable(handler) or handler is None):\n            handler = min_changed_pixels or handler\n            return self._observer.register_event(\n                \"CHANGE\",\n                pattern=(Settings.ObserveMinChangedPixels, self.getBitmap()),\n                handler=handler)\n        else:\n            raise ValueError(\"Unsupported arguments for onChange method\")",
    "docstring": "Registers an event to call ``handler`` when at least ``min_changed_pixels``\n        change in this region.\n\n        (Default for min_changed_pixels is set in Settings.ObserveMinChangedPixels)\n\n        The ``handler`` function should take one parameter, an ObserveEvent object\n        (see below). This event is ignored in the future unless the handler calls\n        the repeat() method on the provided ObserveEvent object.\n\n        Returns the event's ID as a string."
  },
  {
    "code": "def reset_logging_framework():\n    logging._lock = threading.RLock()\n    for name in [None] + list(logging.Logger.manager.loggerDict):\n        for handler in logging.getLogger(name).handlers:\n            handler.createLock()\n    root = logging.getLogger()\n    root.handlers = [\n        handler\n        for handler in root.handlers\n        if not isinstance(handler, mitogen.core.LogHandler)\n    ]",
    "docstring": "After fork, ensure any logging.Handler locks are recreated, as a variety of\n    threads in the parent may have been using the logging package at the moment\n    of fork.\n\n    It is not possible to solve this problem in general; see\n    https://github.com/dw/mitogen/issues/150 for a full discussion."
  },
  {
    "code": "def required_from_env(key):\n    val = os.environ.get(key)\n    if not val:\n        raise ValueError(\n            \"Required argument '{}' not supplied and not found in environment variables\".format(key))\n    return val",
    "docstring": "Retrieve a required variable from the current environment variables.\n\n    Raises a ValueError if the env variable is not found or has no value."
  },
  {
    "code": "def toggle_template_selector(self):\n        if self.search_directory_radio.isChecked():\n            self.template_combo.setEnabled(True)\n        else:\n            self.template_combo.setEnabled(False)\n        if self.search_on_disk_radio.isChecked():\n            self.template_path.setEnabled(True)\n            self.template_chooser.setEnabled(True)\n        else:\n            self.template_path.setEnabled(False)\n            self.template_chooser.setEnabled(False)",
    "docstring": "Slot for template selector elements behaviour.\n\n        .. versionadded: 4.3.0"
  },
  {
    "code": "def merge_lists(l, base):\n    for i in base:\n        if i not in l:\n            l.append(i)",
    "docstring": "Merge in undefined list entries from given list.\n    \n    @param l: List to be merged into.\n    @type l: list\n    \n    @param base: List to be merged into.\n    @type base: list"
  },
  {
    "code": "def _list_fields(self):\n        response = self.__proxy__.list_fields()\n        return [s for s in response['value'] if not s.startswith(\"_\")]",
    "docstring": "Get the current settings of the model. The keys depend on the type of\n        model.\n\n        Returns\n        -------\n        out : list\n            A list of fields that can be queried using the ``get`` method."
  },
  {
    "code": "def _build_url(self, host, handler):\n        scheme = 'https' if self.use_https else 'http'\n        return '%s://%s/%s' % (scheme, host, handler)",
    "docstring": "Build a url for our request based on the host, handler and use_http\n        property"
  },
  {
    "code": "def getctime(self, path):\n        try:\n            file_obj = self.filesystem.resolve(path)\n        except IOError:\n            self.filesystem.raise_os_error(errno.ENOENT)\n        return file_obj.st_ctime",
    "docstring": "Returns the creation time of the fake file.\n\n        Args:\n            path: the path to fake file.\n\n        Returns:\n            (int, float) the creation time of the fake file in number of\n                seconds since the epoch.\n\n        Raises:\n            OSError: if the file does not exist."
  },
  {
    "code": "def get_asset_url(self, path):\n\t\turl = self.root_url + '/assets/' + path\n\t\tif path in self.asset_hash:\n\t\t\turl += '?' + self.asset_hash[path]\n\t\treturn url",
    "docstring": "Get the URL of an asset. If asset hashes are added and one exists for\n\t\tthe path, it will be appended as a query string.\n\n\t\tArgs:\n\t\t  path (str): Path to the file, relative to your \"assets\" directory."
  },
  {
    "code": "def create(\n        self,\n        path,\n        value='',\n        acl=None,\n        ephemeral=False,\n        sequence=False,\n        makepath=False\n    ):\n        _log.debug(\"ZK: Creating node \" + path)\n        return self.zk.create(path, value, acl, ephemeral, sequence, makepath)",
    "docstring": "Creates a Zookeeper node.\n\n        :param: path: The zookeeper node path\n        :param: value: Zookeeper node value\n        :param: acl: ACL list\n        :param: ephemeral: Boolean indicating where this node is tied to\n          this session.\n        :param: sequence:  Boolean indicating whether path is suffixed\n          with a unique index.\n        :param: makepath: Whether the path should be created if it doesn't\n          exist."
  },
  {
    "code": "def upgrade_all(self):\n        for pkg in self.installed_package_names:\n            self.install(pkg, upgrade=True)",
    "docstring": "Upgrades all installed packages to their latest versions."
  },
  {
    "code": "def disable_key(key_id, region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    r = {}\n    try:\n        key = conn.disable_key(key_id)\n        r['result'] = True\n    except boto.exception.BotoServerError as e:\n        r['result'] = False\n        r['error'] = __utils__['boto.get_error'](e)\n    return r",
    "docstring": "Mark key as disabled.\n\n    CLI example::\n\n        salt myminion boto_kms.disable_key 'alias/mykey'"
  },
  {
    "code": "def handle_namespace_invalid(self, line: str, position: int, tokens: ParseResults) -> None:\n        name = tokens[NAME]\n        raise NakedNameWarning(self.get_line_number(), line, position, name)",
    "docstring": "Raise an exception when parsing a name missing a namespace."
  },
  {
    "code": "def softwareUpdateAvailable(self, timeout=1):\n        namespace = System.getServiceType(\"softwareUpdateAvailable\")\n        uri = self.getControlURL(namespace)\n        results = self.execute(uri, namespace, \"GetInfo\", timeout=timeout)\n        return bool(int(results[\"NewUpgradeAvailable\"]))",
    "docstring": "Returns if a software update is available\n\n        :return: if a software update is available\n        :rtype: bool"
  },
  {
    "code": "def entropy_variance(data, class_attr=None,\n    method=DEFAULT_CONTINUOUS_METRIC):\n    assert method in CONTINUOUS_METRICS, \"Unknown entropy variance metric: %s\" % (method,)\n    assert (class_attr is None and isinstance(data, dict)) \\\n        or (class_attr is not None and isinstance(data, list))\n    if isinstance(data, dict):\n        lst = data\n    else:\n        lst = [record.get(class_attr) for record in data]\n    return get_variance(lst)",
    "docstring": "Calculates the variance fo a continuous class attribute, to be used as an\n    entropy metric."
  },
  {
    "code": "def participation_policy_changed(ob, event):\n    workspace = IWorkspace(ob)\n    old_group_name = workspace.group_for_policy(event.old_policy)\n    old_group = api.group.get(old_group_name)\n    for member in old_group.getAllGroupMembers():\n        groups = workspace.get(member.getId()).groups\n        groups -= set([event.old_policy.title()])\n        groups.add(event.new_policy.title())",
    "docstring": "Move all the existing users to a new group"
  },
  {
    "code": "def parse_yaml(self, node):\n        self.group_id = y['groupId']\n        self._members = []\n        if 'members' in y:\n            for m in y.get('members'):\n                self._members.append(TargetComponent().parse_yaml(m))\n        return self",
    "docstring": "Parse a YAML specification of a component group into this\n        object."
  },
  {
    "code": "def write(self, pos, size, **kwargs):\n        if type(pos) is str:\n            raise TypeError(\"SimFileDescriptor.write takes an address and size. Did you mean write_data?\")\n        if self.state.solver.symbolic(size):\n            try:\n                passed_max_size = self.state.solver.max(size, extra_constraints=(size < self.state.libc.max_packet_size,))\n            except SimSolverError:\n                passed_max_size = self.state.solver.min(size)\n                l.warning(\"Symbolic write size is too large for threshold - concretizing to min (%d)\", passed_max_size)\n                self.state.solver.add(size == passed_max_size)\n        else:\n            passed_max_size = self.state.solver.eval(size)\n            if passed_max_size > 2**13:\n                l.warning(\"Program performing extremely large write\")\n        data = self.state.memory.load(pos, passed_max_size)\n        return self.write_data(data, size, **kwargs)",
    "docstring": "Writes some data, loaded from the state, into the file.\n\n        :param pos:     The address to read the data to write from in memory\n        :param size:    The requested size of the write\n        :return:        The real length of the write"
  },
  {
    "code": "def branches_containing(commit):\n    lines = run('branch --contains %s' % commit).splitlines()\n    return [l.lstrip('* ') for l in lines]",
    "docstring": "Return a list of branches conatining that commit"
  },
  {
    "code": "def storage_get(self, key):\n        if not self._module:\n            return\n        self._storage_init()\n        module_name = self._module.module_full_name\n        return self._storage.storage_get(module_name, key)",
    "docstring": "Retrieve a value for the module."
  },
  {
    "code": "def execute(self, transition):\n        self._transitions.append(transition)\n        if self._thread is None or not self._thread.isAlive():\n            self._thread = threading.Thread(target=self._transition_loop)\n            self._thread.setDaemon(True)\n            self._thread.start()",
    "docstring": "Queue a transition for execution.\n\n        :param transition: The transition"
  },
  {
    "code": "def read_file_to_string(path):\n  bytes_string = tf.gfile.Open(path, 'r').read()\n  return dlutils.python_portable_string(bytes_string)",
    "docstring": "Read a file into a string."
  },
  {
    "code": "def _request_internal(self, command, **kwargs):\n        args = dict(kwargs)\n        if self.ssid:\n            args['ssid'] = self.ssid\n        method = getattr(self.api, command)\n        response = method(**args)\n        if response and 'status' in response:\n            if response['status'] == 'error':\n                raise SubregError(\n                    message=response['error']['errormsg'],\n                    major=response['error']['errorcode']['major'],\n                    minor=response['error']['errorcode']['minor']\n                )\n            if response['status'] == 'ok':\n                return response['data'] if 'data' in response else dict()\n            raise Exception(\"Invalid status found in SOAP response\")\n        raise Exception('Invalid response')",
    "docstring": "Make request parse response"
  },
  {
    "code": "def _check_signal(self, s):\n        r\n        s = np.asanyarray(s)\n        if s.shape[0] != self.n_vertices:\n            raise ValueError('First dimension must be the number of vertices '\n                             'G.N = {}, got {}.'.format(self.N, s.shape))\n        return s",
    "docstring": "r\"\"\"Check if signal is valid."
  },
  {
    "code": "def mouseMoveEvent(self, event):\n        c = self.cursorForPosition(event.pos())\n        block = c.block()\n        self._link_match = None\n        self.viewport().setCursor(QtCore.Qt.IBeamCursor)\n        for match in self.link_regex.finditer(block.text()):\n            if not match:\n                continue\n            start, end = match.span()\n            if start <= c.positionInBlock() <= end:\n                self._link_match = match\n                self.viewport().setCursor(QtCore.Qt.PointingHandCursor)\n                break\n        self._last_hovered_block = block\n        super(OutputWindow, self).mouseMoveEvent(event)",
    "docstring": "Handle mouse over file link."
  },
  {
    "code": "def pages(self):\n        if self.per_page == 0 or self.total is None:\n            pages = 0\n        else:\n            pages = int(ceil(self.total / float(self.per_page)))\n        return pages",
    "docstring": "The total number of pages"
  },
  {
    "code": "def replant_tree(self, config=None, exclude=None):\n        self.__init__(key=self.key, config=config, update=True, exclude=exclude)",
    "docstring": "Replant the tree with a different config setup\n\n        Parameters:\n            config (str):\n                The config name to reload\n            exclude (list):\n                A list of environment variables to exclude\n                from forced updates"
  },
  {
    "code": "def process_bulk_queue(self, es_bulk_kwargs=None):\n        with current_celery_app.pool.acquire(block=True) as conn:\n            consumer = Consumer(\n                connection=conn,\n                queue=self.mq_queue.name,\n                exchange=self.mq_exchange.name,\n                routing_key=self.mq_routing_key,\n            )\n            req_timeout = current_app.config['INDEXER_BULK_REQUEST_TIMEOUT']\n            es_bulk_kwargs = es_bulk_kwargs or {}\n            count = bulk(\n                self.client,\n                self._actionsiter(consumer.iterqueue()),\n                stats_only=True,\n                request_timeout=req_timeout,\n                **es_bulk_kwargs\n            )\n            consumer.close()\n        return count",
    "docstring": "Process bulk indexing queue.\n\n        :param dict es_bulk_kwargs: Passed to\n            :func:`elasticsearch:elasticsearch.helpers.bulk`."
  },
  {
    "code": "def _get_file_md5(filename):\n    md5_data = md5()\n    with open(filename, 'rb') as f:\n        for chunk in iter(lambda: f.read(128*md5_data.block_size), b''):\n            md5_data.update(chunk)\n    return md5_data.hexdigest()",
    "docstring": "Compute the md5 checksum of a file"
  },
  {
    "code": "def _os_x_font_directories(cls):\n        os_x_font_dirs = [\n            '/Library/Fonts',\n            '/Network/Library/Fonts',\n            '/System/Library/Fonts',\n        ]\n        home = os.environ.get('HOME')\n        if home is not None:\n            os_x_font_dirs.extend([\n                os.path.join(home, 'Library', 'Fonts'),\n                os.path.join(home, '.fonts')\n            ])\n        return os_x_font_dirs",
    "docstring": "Return a sequence of directory paths on a Mac in which fonts are\n        likely to be located."
  },
  {
    "code": "def directories(self):\n        dirlist_p = new_gp_object(\"CameraList\")\n        lib.gp_camera_folder_list_folders(self._cam._cam, self.path.encode(),\n                                          dirlist_p, self._cam._ctx)\n        for idx in range(lib.gp_list_count(dirlist_p)):\n            name = os.path.join(\n                self.path, get_string(lib.gp_list_get_name, dirlist_p, idx))\n            yield Directory(name=name, parent=self, camera=self._cam)\n        lib.gp_list_free(dirlist_p)",
    "docstring": "Get a generator that yields all subdirectories in the directory."
  },
  {
    "code": "def pattern_input(self, question, message='Invalid entry', pattern='^[a-zA-Z0-9_ ]+$', default='',required=True):\n        result = ''\n        requiredFlag = True\n        while (not result and requiredFlag):\n            result = input('%s: ' % question)\n            if result and pattern and not re.match(pattern, result):\n                self.stdout.write(self.style.ERROR(message))\n                result = ''\n            elif not result and default:\n                return default\n            elif not result and required:\n                self.stdout.write(self.style.ERROR('Answer is required.'))\n            elif not required:\n                requiredFlag = False\n        return result",
    "docstring": "Method for input disallowing special characters, with optionally\n        specifiable regex pattern and error message."
  },
  {
    "code": "def _emit_table_tag(self, open_open_markup, tag, style, padding,\n                        close_open_markup, contents, open_close_markup):\n        self._emit(tokens.TagOpenOpen(wiki_markup=open_open_markup))\n        self._emit_text(tag)\n        if style:\n            self._emit_all(style)\n        if close_open_markup:\n            self._emit(tokens.TagCloseOpen(wiki_markup=close_open_markup,\n                                           padding=padding))\n        else:\n            self._emit(tokens.TagCloseOpen(padding=padding))\n        if contents:\n            self._emit_all(contents)\n        self._emit(tokens.TagOpenClose(wiki_markup=open_close_markup))\n        self._emit_text(tag)\n        self._emit(tokens.TagCloseClose())",
    "docstring": "Emit a table tag."
  },
  {
    "code": "def reverse_timezone(self, query, at_time=None, timeout=DEFAULT_SENTINEL):\n        ensure_pytz_is_installed()\n        location = self._coerce_point_to_string(query)\n        timestamp = self._normalize_timezone_at_time(at_time)\n        params = {\n            \"location\": location,\n            \"timestamp\": timestamp,\n        }\n        if self.api_key:\n            params['key'] = self.api_key\n        url = \"?\".join((self.tz_api, urlencode(params)))\n        logger.debug(\"%s.reverse_timezone: %s\", self.__class__.__name__, url)\n        return self._parse_json_timezone(\n            self._call_geocoder(url, timeout=timeout)\n        )",
    "docstring": "Find the timezone a point in `query` was in for a specified `at_time`.\n\n        .. versionadded:: 1.18.0\n\n        .. versionchanged:: 1.18.1\n           Previously a :class:`KeyError` was raised for a point without\n           an assigned Olson timezone id (e.g. for Antarctica).\n           Now this method returns None for such requests.\n\n        :param query: The coordinates for which you want a timezone.\n        :type query: :class:`geopy.point.Point`, list or tuple of (latitude,\n            longitude), or string as \"%(latitude)s, %(longitude)s\"\n\n        :param at_time: The time at which you want the timezone of this\n            location. This is optional, and defaults to the time that the\n            function is called in UTC. Timezone-aware datetimes are correctly\n            handled and naive datetimes are silently treated as UTC.\n        :type at_time: :class:`datetime.datetime` or None\n\n        :param int timeout: Time, in seconds, to wait for the geocoding service\n            to respond before raising a :class:`geopy.exc.GeocoderTimedOut`\n            exception. Set this only if you wish to override, on this call\n            only, the value set during the geocoder's initialization.\n\n        :rtype: ``None`` or :class:`geopy.timezone.Timezone`"
  },
  {
    "code": "def percentage_progress(self):\n        if self.total_progress != 0:\n            return float(self.progress) / self.total_progress\n        else:\n            return self.progress",
    "docstring": "Returns a float between 0 and 1, representing the current job's progress in its task.\n        If total_progress is not given or 0, just return self.progress.\n\n        :return: float corresponding to the total percentage progress of the job."
  },
  {
    "code": "def ycbcr2rgb(y__, cb_, cr_):\n    kb_ = 0.114\n    kr_ = 0.299\n    r__ = 2 * cr_ / (1 - kr_) + y__\n    b__ = 2 * cb_ / (1 - kb_) + y__\n    g__ = (y__ - kr_ * r__ - kb_ * b__) / (1 - kr_ - kb_)\n    return r__, g__, b__",
    "docstring": "Convert the three YCbCr channels to RGB channels."
  },
  {
    "code": "def canRender(filename):\n        name, ext = os.path.splitext(filename)\n        ext = ext.lstrip('.').lower()\n        if ext in ImageRenderer._extensions:\n            return 100\n        else:\n            return False",
    "docstring": "Check extensions."
  },
  {
    "code": "def frequencies_iter(self):\n        f = self.__matrix.mean(axis=0)\n        for i, m in self.mappings.iteritems():\n            yield m, f[i]",
    "docstring": "Iterates over all non-zero frequencies of logical conjunction mappings in this list\n\n        Yields\n        ------\n        tuple[caspo.core.mapping.Mapping, float]\n            The next pair (mapping,frequency)"
  },
  {
    "code": "def _unpack_episode(element: ET.Element):\n    return Episode(\n        epno=element.find('epno').text,\n        type=int(element.find('epno').get('type')),\n        length=int(element.find('length').text),\n        titles=tuple(_unpack_episode_title(title)\n                     for title in element.iterfind('title')),\n    )",
    "docstring": "Unpack Episode from episode XML element."
  },
  {
    "code": "def participants(self, **kwargs):\n        path = '%s/%s/participants' % (self.manager.path, self.get_id())\n        return self.manager.gitlab.http_get(path, **kwargs)",
    "docstring": "List the participants.\n\n        Args:\n            all (bool): If True, return all the items, without pagination\n            per_page (int): Number of items to retrieve per request\n            page (int): ID of the page to return (starts with page 1)\n            as_list (bool): If set to False and no pagination option is\n                defined, return a generator instead of a list\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabListError: If the list could not be retrieved\n\n        Returns:\n            RESTObjectList: The list of participants"
  },
  {
    "code": "def parse_resources(self, resources):\n        self.resources = {}\n        resource_factory = ResourceFactory()\n        for res_id, res_value in resources.items():\n            r = resource_factory.create_resource(res_id, res_value)\n            if r:\n                if r.resource_type in self.resources:\n                    self.resources[r.resource_type].append(r)\n                else:\n                    self.resources[r.resource_type] = [r]",
    "docstring": "Parses and sets resources in the model using a factory."
  },
  {
    "code": "def will_not_clone(self, request, *args, **kwargs):\n        paths = request.path_info.split('/')\n        index_of_object_id = paths.index(\"will_not_clone\") - 1\n        object_id = paths[index_of_object_id]\n        self.change_view(request, object_id)\n        admin_wordInUrl = index_of_object_id - 3\n        path = '/' + '/'.join(paths[admin_wordInUrl:index_of_object_id])\n        return HttpResponseRedirect(path)",
    "docstring": "Add save but not clone capability in the changeview"
  },
  {
    "code": "def _start_new_warc_file(self, meta=False):\n        if self._params.max_size and not meta and self._params.appending:\n            while True:\n                self._warc_filename = self._generate_warc_filename()\n                if os.path.exists(self._warc_filename):\n                    _logger.debug('Skip {0}', self._warc_filename)\n                    self._sequence_num += 1\n                else:\n                    break\n        else:\n            self._warc_filename = self._generate_warc_filename(meta=meta)\n        _logger.debug('WARC file at {0}', self._warc_filename)\n        if not self._params.appending:\n            wpull.util.truncate_file(self._warc_filename)\n        self._warcinfo_record = WARCRecord()\n        self._populate_warcinfo(self._params.extra_fields)\n        self.write_record(self._warcinfo_record)",
    "docstring": "Create and set as current WARC file."
  },
  {
    "code": "def scandir(self, relpath):\n    if self.isignored(relpath, directory=True):\n      self._raise_access_ignored(relpath)\n    return self._filter_ignored(self._scandir_raw(relpath), selector=lambda e: e.path)",
    "docstring": "Return paths relative to the root, which are in the given directory and not ignored."
  },
  {
    "code": "def _get_mixed_actions(tableaux, bases):\n    nums_actions = tableaux[1].shape[0], tableaux[0].shape[0]\n    num = nums_actions[0] + nums_actions[1]\n    out = np.zeros(num)\n    for pl, (start, stop) in enumerate(zip((0, nums_actions[0]),\n                                           (nums_actions[0], num))):\n        sum_ = 0.\n        for i in range(nums_actions[1-pl]):\n            k = bases[pl][i]\n            if start <= k < stop:\n                out[k] = tableaux[pl][i, -1]\n                sum_ += tableaux[pl][i, -1]\n        if sum_ != 0:\n            out[start:stop] /= sum_\n    return out[:nums_actions[0]], out[nums_actions[0]:]",
    "docstring": "From `tableaux` and `bases`, extract non-slack basic variables and\n    return a tuple of the corresponding, normalized mixed actions.\n\n    Parameters\n    ----------\n    tableaux : tuple(ndarray(float, ndim=2))\n        Tuple of two arrays containing the tableaux, of shape (n, m+n+1)\n        and (m, m+n+1), respectively.\n\n    bases : tuple(ndarray(int, ndim=1))\n        Tuple of two arrays containing the bases, of shape (n,) and\n        (m,), respectively.\n\n    Returns\n    -------\n    tuple(ndarray(float, ndim=1))\n        Tuple of mixed actions as given by the non-slack basic variables\n        in the tableaux."
  },
  {
    "code": "def execute_command_in_process(command, shell=False, cwd=None, logger=None):\n    if logger is None:\n        logger = _logger\n    logger.debug(\"Run shell command: {0}\".format(command))\n    try:\n        subprocess.Popen(command, shell=shell, cwd=cwd)\n        return True\n    except OSError as e:\n        logger.error('The operating system raised an error: {}'.format(e))\n    return False",
    "docstring": "Executes a specific command in a separate process\n\n    :param command: the command to be executed\n    :param bool shell: Whether to use a shell\n    :param str cwd: The working directory of the command\n    :param logger: optional logger instance which can be handed from other module\n    :return: None"
  },
  {
    "code": "def restriction(lam, mu, orbitals, U, beta):\n    return 2*orbitals*fermi_dist(-(mu + lam), beta) - expected_filling(-1*lam, orbitals, U, beta)",
    "docstring": "Equation that determines the restriction on lagrange multipier"
  },
  {
    "code": "def this_year(self):\n        start_date, end_date = get_date_range_this_year()\n        return self.filter(date__gte=start_date, date__lte=end_date)",
    "docstring": "Get EighthBlocks from this school year only."
  },
  {
    "code": "def on_arc_right(self, speed, radius_mm, distance_mm, brake=True, block=True):\n        self._on_arc(speed, radius_mm, distance_mm, brake, block, True)",
    "docstring": "Drive clockwise in a circle with 'radius_mm' for 'distance_mm'"
  },
  {
    "code": "def convert_path_to_module_parts(path):\n    module_parts = splitall(path)\n    if module_parts[-1] in ['__init__.py', '__init__.pyc']:\n        module_parts = module_parts[:-1]\n    else:\n        module_parts[-1], _ = os.path.splitext(module_parts[-1])\n    return module_parts",
    "docstring": "Convert path to a python file into list of module names."
  },
  {
    "code": "def get_sample(self, md5):\n        if len(md5) < 32:\n            md5 = self.get_full_md5(md5, self.sample_collection)\n        sample_info = self.database[self.sample_collection].find_one({'md5': md5})\n        if not sample_info:\n            return None\n        try:\n            grid_fs_id = sample_info['__grid_fs']\n            sample_info = self.clean_for_serialization(sample_info)\n            sample_info.update({'raw_bytes':self.gridfs_handle.get(grid_fs_id).read()})\n            return sample_info\n        except gridfs.errors.CorruptGridFile:\n            self.database[self.sample_collection].update({'md5': md5}, {'md5': None})\n            return None",
    "docstring": "Get the sample from the data store.\n\n        This method first fetches the data from datastore, then cleans it for serialization\n        and then updates it with 'raw_bytes' item.\n        \n        Args:\n            md5: The md5 digest of the sample to be fetched from datastore.\n\n        Returns:\n            The sample dictionary or None"
  },
  {
    "code": "async def processClaim(self, schemaId: ID, claimAttributes: Dict[str, ClaimAttributeValues], signature: Claims):\n        await self.wallet.submitContextAttr(schemaId, signature.primaryClaim.m2)\n        await self.wallet.submitClaimAttributes(schemaId, claimAttributes)\n        await self._initPrimaryClaim(schemaId, signature.primaryClaim)\n        if signature.nonRevocClaim:\n            await self._initNonRevocationClaim(schemaId, signature.nonRevocClaim)",
    "docstring": "Processes and saves a received Claim for the given Schema.\n\n        :param schemaId: The schema ID (reference to claim\n        definition schema)\n        :param claims: claims to be processed and saved"
  },
  {
    "code": "def request_bytesize(self):\n        return sum(len(str(e)) for elts in self._in_deque for e in elts)",
    "docstring": "The size of in bytes of the bundled field elements."
  },
  {
    "code": "def install_scripts(distributions):\n    try:\n        if \"__PEX_UNVENDORED__\" in __import__(\"os\").environ:\n          from setuptools.command import easy_install\n        else:\n          from pex.third_party.setuptools.command import easy_install\n        if \"__PEX_UNVENDORED__\" in __import__(\"os\").environ:\n          import pkg_resources\n        else:\n          import pex.third_party.pkg_resources as pkg_resources\n    except ImportError:\n        raise RuntimeError(\"'wheel install_scripts' needs setuptools.\")\n    for dist in distributions:\n        pkg_resources_dist = pkg_resources.get_distribution(dist)\n        install = get_install_command(dist)\n        command = easy_install.easy_install(install.distribution)\n        command.args = ['wheel']\n        command.finalize_options()\n        command.install_egg_scripts(pkg_resources_dist)",
    "docstring": "Regenerate the entry_points console_scripts for the named distribution."
  },
  {
    "code": "def start_pan(self, x, y, button):\n        bd = self.viewer.get_bindings()\n        data_x, data_y = self.viewer.get_data_xy(x, y)\n        event = PointEvent(button=button, state='down',\n                           data_x=data_x, data_y=data_y,\n                           viewer=self.viewer)\n        if button == 1:\n            bd.ms_pan(self.viewer, event, data_x, data_y)\n        elif button == 3:\n            bd.ms_zoom(self.viewer, event, data_x, data_y)",
    "docstring": "Called when a pan operation has started.\n\n        *x*, *y* are the mouse coordinates in display coords.\n        button is the mouse button number:\n\n        * 1: LEFT\n        * 2: MIDDLE\n        * 3: RIGHT\n\n        .. note::\n\n            Intended to be overridden by new projection types."
  },
  {
    "code": "def _do_create(di):\n    track = di['track'].strip()\n    artists = di['artist']\n    if isinstance(artists, StringType):\n        artists = [artists]\n    tracks = Track.objects.filter(title=track, state='published')\n    if tracks:\n        track = tracks[0]\n        track_created = False\n    else:\n        track = Track.objects.create(title=track, state='published')\n        track_created = True\n    last_played = di.get('last_played', None)\n    if last_played and (track.last_played != last_played):\n        track.last_played = last_played\n        track.save()\n    if track_created:\n        track.length = di.get('length', 240)\n        track.sites = Site.objects.all()\n        track.save(set_image=False)\n        for artist in artists:\n            track.create_credit(artist.strip(), 'artist')\n        track.set_image()",
    "docstring": "Function that interprets a dictionary and creates objects"
  },
  {
    "code": "def is_disjoint(self,other):\n        if self.is_empty() or other.is_empty():\n            return True\n        if self.bounds[0] < other.bounds[0]:\n            i1,i2 = self,other\n        elif self.bounds[0] > other.bounds[0]:\n            i2,i1 = self,other\n        else:\n            if self.is_discrete() and not other.included[0]:\n                return True\n            elif other.is_discrete() and not self.included[0]:\n                return True\n            else:\n                return False\n        return not i2.bounds[0] in i1",
    "docstring": "Check whether two Intervals are disjoint.\n\n        :param Interval other: The Interval to check disjointedness with."
  },
  {
    "code": "def assertNone(expr, message=None):\n    if expr is not None:\n        raise TestStepFail(\n            format_message(message) if message is not None else \"Assert: %s != None\" % str(expr))",
    "docstring": "Assert that expr is None.\n\n    :param expr: expression.\n    :param message: Message set to raised Exception\n    :raises: TestStepFail if expr is not None."
  },
  {
    "code": "def get_session(ec=None, create=True):\n    ec = ec or __default_engine__\n    if isinstance(ec, (str, unicode)):\n        session = engine_manager[ec].session(create=True)\n    elif isinstance(ec, Session):\n        session = ec\n    else:\n        raise Error(\"Connection %r should be existed engine name or Session object\" % ec)\n    return session",
    "docstring": "ec - engine_name or connection"
  },
  {
    "code": "def _configure_detail_level(cls, detail_level):\n        if isinstance(detail_level, six.string_types):\n            if detail_level not in LOG_DETAIL_LEVELS:\n                raise ValueError(\n                    _format(\"Invalid log detail level string: {0!A}; must be \"\n                            \"one of: {1!A}\", detail_level, LOG_DETAIL_LEVELS))\n        elif isinstance(detail_level, int):\n            if detail_level < 0:\n                raise ValueError(\n                    _format(\"Invalid log detail level integer: {0}; must be a \"\n                            \"positive integer.\", detail_level))\n        elif detail_level is None:\n            detail_level = DEFAULT_LOG_DETAIL_LEVEL\n        else:\n            raise ValueError(\n                _format(\"Invalid log detail level: {0!A}; must be one of: \"\n                        \"{1!A}, or a positive integer\",\n                        detail_level, LOG_DETAIL_LEVELS))\n        return detail_level",
    "docstring": "Validate the `detail_level` parameter and return it.\n\n        This accepts a string or integer for `detail_level`."
  },
  {
    "code": "def _initSwapInfo(self):\n        self._swapList = []\n        sysinfo = SystemInfo()\n        for (swap,attrs) in sysinfo.getSwapStats().iteritems():\n            if attrs['type'] == 'partition':\n                dev = self._getUniqueDev(swap)\n                if dev is not None:\n                    self._swapList.append(dev)",
    "docstring": "Initialize swap partition to device mappings."
  },
  {
    "code": "def handle(cls, value, context, **kwargs):\n        try:\n            hook_name, key = value.split(\"::\")\n        except ValueError:\n            raise ValueError(\"Invalid value for hook_data: %s. Must be in \"\n                             \"<hook_name>::<key> format.\" % value)\n        return context.hook_data[hook_name][key]",
    "docstring": "Returns the value of a key for a given hook in hook_data.\n\n        Format of value:\n\n            <hook_name>::<key>"
  },
  {
    "code": "def LinSpace(start, stop, num):\n    return np.linspace(start, stop, num=num, dtype=np.float32),",
    "docstring": "Linspace op."
  },
  {
    "code": "def getMask (self, ifname):\n        if sys.platform == 'darwin':\n            return ifconfig_inet(ifname).get('netmask')\n        return self._getaddr(ifname, self.SIOCGIFNETMASK)",
    "docstring": "Get the netmask for an interface.\n        @param ifname: interface name\n        @type ifname: string"
  },
  {
    "code": "def aes_encrypt(mode, aes_key, aes_iv, *data):\n    encryptor = Cipher(\n        algorithms.AES(aes_key),\n        mode(aes_iv),\n        backend=default_backend()).encryptor()\n    result = None\n    for value in data:\n        result = encryptor.update(value)\n    encryptor.finalize()\n    return result, None if not hasattr(encryptor, 'tag') else encryptor.tag",
    "docstring": "Encrypt data with AES in specified mode."
  },
  {
    "code": "def _sibpath(path, sibling):\n    return os.path.join(os.path.dirname(os.path.abspath(path)), sibling)",
    "docstring": "Return the path to a sibling of a file in the filesystem.\n\n    This is useful in conjunction with the special C{__file__} attribute\n    that Python provides for modules, so modules can load associated\n    resource files.\n\n    (Stolen from twisted.python.util)"
  },
  {
    "code": "def find_ip6_by_id(self, id_ip):\n        if not is_valid_int_param(id_ip):\n            raise InvalidParameterError(\n                u'Ipv6 identifier is invalid or was not informed.')\n        url = 'ipv6/get/' + str(id_ip) + \"/\"\n        code, xml = self.submit(None, 'GET', url)\n        return self.response(code, xml)",
    "docstring": "Get an IP6 by ID\n\n        :param id_ip: IP6 identifier. Integer value and greater than zero.\n\n        :return: Dictionary with the following structure:\n\n        ::\n\n            {'ip': {'id': < id >,\n            'block1': <block1>,\n            'block2': <block2>,\n            'block3': <block3>,\n            'block4': <block4>,\n            'block5': <block5>,\n            'block6': <block6>,\n            'block7': <block7>,\n            'block8': <block8>,\n            'descricao': < description >,\n            'equipamento': [ { all name equipamentos related} ], }}\n\n\n        :raise IpNotAvailableError: Network dont have available IPv6.\n        :raise NetworkIPv4NotFoundError: Network was not found.\n        :raise UserNotAuthorizedError: User dont have permission to perform operation.\n        :raise InvalidParameterError: IPv6 identifier is none or invalid.\n        :raise XMLError: Networkapi failed to generate the XML response.\n        :raise DataBaseError: Networkapi failed to access the database."
  },
  {
    "code": "def int_to_varbyte(self, value):\n        length = int(log(max(value, 1), 0x80)) + 1\n        bytes = [value >> i * 7 & 0x7F for i in range(length)]\n        bytes.reverse()\n        for i in range(len(bytes) - 1):\n            bytes[i] = bytes[i] | 0x80\n        return pack('%sB' % len(bytes), *bytes)",
    "docstring": "Convert an integer into a variable length byte.\n\n        How it works: the bytes are stored in big-endian (significant bit\n        first), the highest bit of the byte (mask 0x80) is set when there\n        are more bytes following. The remaining 7 bits (mask 0x7F) are used\n        to store the value."
  },
  {
    "code": "def df(self):\n        import pandas as pd\n        return pd.concat([w.df(uwi=True) for w in self])",
    "docstring": "Makes a pandas DataFrame containing Curve data for all the wells\n        in the Project. The DataFrame has a dual index of well UWI and\n        curve Depths. Requires `pandas`.\n\n        Args:\n            No arguments.\n\n        Returns:\n            `pandas.DataFrame`."
  },
  {
    "code": "def get_site(self, *args):\n        num_args = len(args)\n        if num_args == 1:\n            site = args[0]\n        elif num_args == 2:\n            host_name, path_to_site = args\n            path_to_site = '/' + path_to_site if not path_to_site.startswith(\n                '/') else path_to_site\n            site = '{}:{}:'.format(host_name, path_to_site)\n        elif num_args == 3:\n            site = ','.join(args)\n        else:\n            raise ValueError('Incorrect number of arguments')\n        url = self.build_url(self._endpoints.get('get_site').format(id=site))\n        response = self.con.get(url)\n        if not response:\n            return None\n        data = response.json()\n        return self.site_constructor(parent=self,\n                                     **{self._cloud_data_key: data})",
    "docstring": "Returns a sharepoint site\n\n        :param args: It accepts multiple ways of retrieving a site:\n\n         get_site(host_name): the host_name: host_name ej.\n         'contoso.sharepoint.com' or 'root'\n\n         get_site(site_id): the site_id: a comma separated string of\n         (host_name, site_collection_id, site_id)\n\n         get_site(host_name, path_to_site): host_name ej. 'contoso.\n         sharepoint.com', path_to_site: a url path (with a leading slash)\n\n         get_site(host_name, site_collection_id, site_id):\n         host_name ej. 'contoso.sharepoint.com'\n        :rtype: Site"
  },
  {
    "code": "def update(self):\n        con = self.subpars.pars.control\n        self(con.eqi1*con.tind)",
    "docstring": "Update |KI1| based on |EQI1| and |TInd|.\n\n        >>> from hydpy.models.lland import *\n        >>> parameterstep('1d')\n        >>> eqi1(5.0)\n        >>> tind.value = 10.0\n        >>> derived.ki1.update()\n        >>> derived.ki1\n        ki1(50.0)"
  },
  {
    "code": "def fuzzy_subset(str_):\n    if str_ is None:\n        return str_\n    if ':' in str_:\n        return smart_cast(str_, slice)\n    if str_.startswith('['):\n        return smart_cast(str_[1:-1], list)\n    else:\n        return smart_cast(str_, list)",
    "docstring": "converts a string into an argument to list_take"
  },
  {
    "code": "def notify(self, msg, color='green', notify='true', message_format='text'):\n        self.message_dict = {\n            'message': msg,\n            'color': color,\n            'notify': notify,\n            'message_format': message_format,\n        }\n        if not self.debug:\n            return requests.post(\n                self.notification_url,\n                json.dumps(self.message_dict),\n                headers=self.headers\n            )\n        else:\n            print('HipChat message: <{}>'.format(msg))\n            return []",
    "docstring": "Send notification to specified HipChat room"
  },
  {
    "code": "def _collapseMsg(self, msg):\n        retval = {}\n        for logname in msg:\n            data = u\"\"\n            for m in msg[logname]:\n                m = bytes2unicode(m, self.builder.unicode_encoding)\n                data += m\n            if isinstance(logname, tuple) and logname[0] == 'log':\n                retval['log'] = (logname[1], data)\n            else:\n                retval[logname] = data\n        return retval",
    "docstring": "Take msg, which is a dictionary of lists of output chunks, and\n        concatenate all the chunks into a single string"
  },
  {
    "code": "def make_link(title, url, blank=False):\n\tattrs = 'href=\"%s\"' % url\n\tif blank:\n\t\tattrs += ' target=\"_blank\" rel=\"noopener noreferrer\"'\n\treturn '<a %s>%s</a>' % (attrs, title)",
    "docstring": "Make a HTML link out of an URL.\n\n\tArgs:\n\t  title (str): Text to show for the link.\n\t  url (str): URL the link will point to.\n\t  blank (bool): If True, appends target=_blank, noopener and noreferrer to\n\t    the <a> element. Defaults to False."
  },
  {
    "code": "def resolve_filename(self, package_dir, filename):\n        sass_path = os.path.join(package_dir, self.sass_path, filename)\n        if self.strip_extension:\n            filename, _ = os.path.splitext(filename)\n        css_filename = filename + '.css'\n        css_path = os.path.join(package_dir, self.css_path, css_filename)\n        return sass_path, css_path",
    "docstring": "Gets a proper full relative path of Sass source and\n        CSS source that will be generated, according to ``package_dir``\n        and ``filename``.\n\n        :param package_dir: the path of package directory\n        :type package_dir: :class:`str`, :class:`basestring`\n        :param filename: the filename of Sass/SCSS source to compile\n        :type filename: :class:`str`, :class:`basestring`\n        :returns: a pair of (sass, css) path\n        :rtype: :class:`tuple`"
  },
  {
    "code": "def export_data_object_info(bpmn_diagram, data_object_params, output_element):\n        output_element.set(consts.Consts.is_collection, data_object_params[consts.Consts.is_collection])",
    "docstring": "Adds DataObject node attributes to exported XML element\n\n        :param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram,\n        :param data_object_params: dictionary with given subprocess parameters,\n        :param output_element: object representing BPMN XML 'subprocess' element."
  },
  {
    "code": "def _gate_pre_offset(self, gate):\n        try:\n            gates = self.settings['gates']\n            delta_pos = gates[gate.__class__.__name__]['pre_offset']\n        except KeyError:\n            delta_pos = self._gate_offset(gate)\n        return delta_pos",
    "docstring": "Return the offset to use before placing this gate.\n\n        :param string gate: The name of the gate whose pre-offset is desired.\n        :return: Offset to use before the gate.\n        :rtype: float"
  },
  {
    "code": "def sync_role_definitions(self):\n        from superset import conf\n        logging.info('Syncing role definition')\n        self.create_custom_permissions()\n        self.set_role('Admin', self.is_admin_pvm)\n        self.set_role('Alpha', self.is_alpha_pvm)\n        self.set_role('Gamma', self.is_gamma_pvm)\n        self.set_role('granter', self.is_granter_pvm)\n        self.set_role('sql_lab', self.is_sql_lab_pvm)\n        if conf.get('PUBLIC_ROLE_LIKE_GAMMA', False):\n            self.set_role('Public', self.is_gamma_pvm)\n        self.create_missing_perms()\n        self.get_session.commit()\n        self.clean_perms()",
    "docstring": "Inits the Superset application with security roles and such"
  },
  {
    "code": "def is_quote_artifact(orig_text, span):\n    res = False\n    cursor = re.finditer(r'(\"|\\')[^ .,:;?!()*+-].*?(\"|\\')', orig_text)\n    for item in cursor:\n        if item.span()[1] == span[1]:\n            res = True\n    return res",
    "docstring": "Distinguish between quotes and units."
  },
  {
    "code": "def visible_width(string):\n    if '\\033' in string:\n        string = RE_COLOR_ANSI.sub('', string)\n    try:\n        string = string.decode('u8')\n    except (AttributeError, UnicodeEncodeError):\n        pass\n    width = 0\n    for char in string:\n        if unicodedata.east_asian_width(char) in ('F', 'W'):\n            width += 2\n        else:\n            width += 1\n    return width",
    "docstring": "Get the visible width of a unicode string.\n\n    Some CJK unicode characters are more than one byte unlike ASCII and latin unicode characters.\n\n    From: https://github.com/Robpol86/terminaltables/pull/9\n\n    :param str string: String to measure.\n\n    :return: String's width.\n    :rtype: int"
  },
  {
    "code": "def temp_shell_task(cls, inp, mpi_procs=1, workdir=None, manager=None):\n        import tempfile\n        workdir = tempfile.mkdtemp() if workdir is None else workdir\n        if manager is None: manager = TaskManager.from_user_config()\n        task = cls.from_input(inp, workdir=workdir, manager=manager.to_shell_manager(mpi_procs=mpi_procs))\n        task.set_name('temp_shell_task')\n        return task",
    "docstring": "Build a Task with a temporary workdir. The task is executed via the shell with 1 MPI proc.\n        Mainly used for invoking Abinit to get important parameters needed to prepare the real task.\n\n        Args:\n            mpi_procs: Number of MPI processes to use."
  },
  {
    "code": "def _get_redis_keys_opts():\n    return {\n        'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX),\n        'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX),\n        'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX),\n        'separator': __opts__.get('cache.redis.separator', _SEPARATOR)\n    }",
    "docstring": "Build the key opts based on the user options."
  },
  {
    "code": "def set_path(dicts, keys, v):\n    for key in keys[:-1]:\n        dicts = dicts.setdefault(key, dict())\n    dicts = dicts.setdefault(keys[-1], list())\n    dicts.append(v)",
    "docstring": "Helper function for modifying nested dictionaries\n\n    :param dicts: dict: the given dictionary\n    :param keys: list str: path to added value\n    :param v: str: value to be added\n\n    Example:\n        >>> d = dict()\n\n        >>> set_path(d, ['a', 'b', 'c'],  'd')\n\n        >>> d\n        {'a': {'b': {'c': ['d']}}}\n\n        In case of duplicate paths, the additional value will\n        be added to the leaf node rather than simply replace it:\n\n        >>> set_path(d, ['a', 'b', 'c'],  'e')\n        \n        >>> d\n        {'a': {'b': {'c': ['d', 'e']}}}"
  },
  {
    "code": "def set_sample_probability(probability):\n    global _sample_probability\n    if not 0.0 <= probability <= 1.0:\n        raise ValueError('Invalid probability value')\n    LOGGER.debug('Setting sample probability to %.2f', probability)\n    _sample_probability = float(probability)",
    "docstring": "Set the probability that a batch will be submitted to the InfluxDB\n    server. This should be a value that is greater than or equal to ``0`` and\n    less than or equal to ``1.0``. A value of ``0.25`` would represent a\n    probability of 25% that a batch would be written to InfluxDB.\n\n    :param float probability: The value between 0 and 1.0 that represents the\n        probability that a batch will be submitted to the InfluxDB server."
  },
  {
    "code": "def getSampleFrequency(self,chn):\n        if 0 <= chn < self.signals_in_file:\n            return round(self.samplefrequency(chn))\n        else:\n            return 0",
    "docstring": "Returns the samplefrequency of signal edfsignal.\n\n        Parameters\n        ----------\n        chn : int\n            channel number\n\n        Examples\n        --------\n        >>> import pyedflib\n        >>> f = pyedflib.data.test_generator()\n        >>> f.getSampleFrequency(0)==200.0\n        True\n        >>> f._close()\n        >>> del f"
  },
  {
    "code": "def _get_rsa_key(self):\n        url = 'https://steamcommunity.com/mobilelogin/getrsakey/'\n        values = {\n                'username': self._username,\n                'donotcache' : self._get_donotcachetime(),\n        }\n        req = self.post(url, data=values)\n        data = req.json()\n        if not data['success']:\n            raise SteamWebError('Failed to get RSA key', data)\n        mod = int(str(data['publickey_mod']), 16)\n        exp = int(str(data['publickey_exp']), 16)\n        rsa = RSA.construct((mod, exp))\n        self.rsa_cipher = PKCS1_v1_5.new(rsa)\n        self.rsa_timestamp = data['timestamp']",
    "docstring": "get steam RSA key, build and return cipher"
  },
  {
    "code": "def get_meta(self, table_name, constraints=None, column_to_field_name=None, is_view=False, is_partition=None):\n        meta = [\"    class Meta(models.Model.Meta):\",\n                \"        db_table = '%s'\" % table_name]\n        if self.connection.vendor == 'salesforce':\n            for line in self.connection.introspection.get_additional_meta(table_name):\n                meta.append(\"        \" + line)\n        meta.append(\"\")\n        return meta",
    "docstring": "Return a sequence comprising the lines of code necessary\n        to construct the inner Meta class for the model corresponding\n        to the given database table name."
  },
  {
    "code": "def as_fs(self):\n        s = self._standard_value\n        result = []\n        idx = 0\n        while (idx < len(s)):\n            c = s[idx]\n            if c != \"\\\\\":\n                result.append(c)\n            else:\n                nextchr = s[idx + 1]\n                if (nextchr == \".\") or (nextchr == \"-\") or (nextchr == \"_\"):\n                    result.append(nextchr)\n                    idx += 1\n                else:\n                    result.append(\"\\\\\")\n                    result.append(nextchr)\n                    idx += 2\n                    continue\n            idx += 1\n        return \"\".join(result)",
    "docstring": "Returns the value of component encoded as formatted string.\n\n        Inspect each character in value of component.\n        Certain nonalpha characters pass thru without escaping\n        into the result, but most retain escaping.\n\n        :returns: Formatted string associated with component\n        :rtype: string"
  },
  {
    "code": "def _path_completer_grammar(self):\n        if self._path_completer_grammar_cache is None:\n            self._path_completer_grammar_cache = self._create_path_completer_grammar()\n        return self._path_completer_grammar_cache",
    "docstring": "Return the grammar for matching paths inside strings inside Python\n        code."
  },
  {
    "code": "def MakeDestinationKey(directory, filename):\n  return utils.SmartStr(utils.JoinPath(directory, filename)).lstrip(\"/\")",
    "docstring": "Creates a name that identifies a database file."
  },
  {
    "code": "def data_lookup_method(fields_list, mongo_db_obj, hist, record,\n                           lookup_type):\n        if hist is None:\n            hist = {}\n        for field in record:\n            if record[field] != '' and record[field] is not None:\n                if field in fields_list:\n                    if lookup_type in fields_list[field]['lookup']:\n                        field_val_new, hist = DataLookup(\n                            fieldVal=record[field],\n                            db=mongo_db_obj,\n                            lookupType=lookup_type,\n                            fieldName=field,\n                            histObj=hist)\n                        record[field] = field_val_new\n        return record, hist",
    "docstring": "Method to lookup the replacement value given a single input value from\n        the same field.\n\n        :param dict fields_list: Fields configurations\n        :param MongoClient mongo_db_obj: MongoDB collection object\n        :param dict hist: existing input of history values object\n        :param dict record: values to validate\n        :param str lookup_type: Type of lookup"
  },
  {
    "code": "def start_watcher_thread(self):\n        watcher_thread = threading.Thread(target=self.run_watcher)\n        if self._reload_mode == self.RELOAD_MODE_V_SPAWN_WAIT:\n            daemon = False\n        else:\n            daemon = True\n        watcher_thread.setDaemon(daemon)\n        watcher_thread.start()\n        return watcher_thread",
    "docstring": "Start watcher thread.\n\n        :return:\n            Watcher thread object."
  },
  {
    "code": "def detectOperaMobile(self):\n        return UAgentInfo.engineOpera in self.__userAgent \\\n            and (UAgentInfo.mini in self.__userAgent\n                or UAgentInfo.mobi in self.__userAgent)",
    "docstring": "Return detection of an Opera browser for a mobile device\n\n        Detects Opera Mobile or Opera Mini."
  },
  {
    "code": "def get_proposed_feature(project):\n    change_collector = ChangeCollector(project)\n    collected_changes = change_collector.collect_changes()\n    try:\n        new_feature_info = one_or_raise(collected_changes.new_feature_info)\n        importer, _, _ = new_feature_info\n    except ValueError:\n        raise BalletError('Too many features collected')\n    module = importer()\n    feature = _get_contrib_feature_from_module(module)\n    return feature",
    "docstring": "Get the proposed feature\n\n    The path of the proposed feature is determined by diffing the project\n    against a comparison branch, such as master. The feature is then imported\n    from that path and returned.\n\n    Args:\n        project (ballet.project.Project): project info\n\n    Raises:\n        ballet.exc.BalletError: more than one feature collected"
  },
  {
    "code": "def surface_or_abstract(cls, predstr):\n        if predstr.strip('\"').lstrip(\"'\").startswith('_'):\n            return cls.surface(predstr)\n        else:\n            return cls.abstract(predstr)",
    "docstring": "Instantiate a Pred from either its surface or abstract symbol."
  },
  {
    "code": "def quantile(data, weights, quantile):\n    nd = data.ndim\n    if nd == 0:\n        TypeError(\"data must have at least one dimension\")\n    elif nd == 1:\n        return quantile_1D(data, weights, quantile)\n    elif nd > 1:\n        n = data.shape\n        imr = data.reshape((np.prod(n[:-1]), n[-1]))\n        result = np.apply_along_axis(quantile_1D, -1, imr, weights, quantile)\n        return result.reshape(n[:-1])",
    "docstring": "Weighted quantile of an array with respect to the last axis.\n\n    Parameters\n    ----------\n    data : ndarray\n        Input array.\n    weights : ndarray\n        Array with the weights. It must have the same size of the last \n        axis of `data`.\n    quantile : float\n        Quantile to compute. It must have a value between 0 and 1.\n\n    Returns\n    -------\n    quantile : float\n        The output value."
  },
  {
    "code": "def shipping_rate(context, **kwargs):\n    settings = Configuration.for_site(context[\"request\"].site)\n    code = kwargs.get('code', None)\n    name = kwargs.get('name', None)\n    return get_shipping_cost(settings, code, name)",
    "docstring": "Return the shipping rate for a country & shipping option name."
  },
  {
    "code": "def values(self):\n        if self.ui.hzBtn.isChecked():\n            fscale = SmartSpinBox.Hz\n        else:\n            fscale = SmartSpinBox.kHz\n        if self.ui.msBtn.isChecked():\n            tscale = SmartSpinBox.MilliSeconds\n        else:\n            tscale = SmartSpinBox.Seconds\n        return fscale, tscale",
    "docstring": "Gets the scales that the user chose\n\n        | For frequency: 1 = Hz, 1000 = kHz\n        | For time: 1 = seconds, 0.001 = ms\n\n        :returns: float, float -- frequency scaling, time scaling"
  },
  {
    "code": "def _set_fqdn(self):\n        results = self._search(\n            'cn=config',\n            '(objectClass=*)',\n            ['nsslapd-localhost'],\n            scope=ldap.SCOPE_BASE\n        )\n        if not results and type(results) is not list:\n            r = None\n        else:\n            dn, attrs = results[0]\n            r = attrs['nsslapd-localhost'][0].decode('utf-8')\n        self._fqdn = r\n        log.debug('FQDN: %s' % self._fqdn)",
    "docstring": "Get FQDN from LDAP"
  },
  {
    "code": "def is_constant(self, qc: QuantumComputer, bitstring_map: Dict[str, str]) -> bool:\n        self._init_attr(bitstring_map)\n        prog = Program()\n        dj_ro = prog.declare('ro', 'BIT', len(self.computational_qubits))\n        prog += self.deutsch_jozsa_circuit\n        prog += [MEASURE(qubit, ro) for qubit, ro in zip(self.computational_qubits, dj_ro)]\n        executable = qc.compile(prog)\n        returned_bitstring = qc.run(executable)\n        bitstring = np.array(returned_bitstring, dtype=int)\n        constant = all([bit == 0 for bit in bitstring])\n        return constant",
    "docstring": "Computes whether bitstring_map represents a constant function, given that it is constant\n         or balanced. Constant means all inputs map to the same value, balanced means half of the\n         inputs maps to one value, and half to the other.\n\n        :param QVMConnection cxn: The connection object to the Rigetti cloud to run pyQuil programs.\n        :param bitstring_map: A dictionary whose keys are bitstrings, and whose values are bits\n         represented as strings.\n        :type bistring_map: Dict[String, String]\n        :return: True if the bitstring_map represented a constant function, false otherwise.\n        :rtype: bool"
  },
  {
    "code": "def _parse_stop_words_file(self, path):\n        language = None\n        loaded = False\n        if os.path.isfile(path):\n            self._logger.debug('Loading stop words in %s', path)\n            language = path.split('-')[-1]\n            if not language in self.__stop_words:\n                self.__stop_words[language] = set()\n            with codecs.open(path, 'r', 'UTF-8') as file:\n                loaded = True\n                for word in file:\n                    self.__stop_words[language].add(word.strip())\n        return loaded",
    "docstring": "Load stop words from the given path.\n\n        Parse the stop words file, saving each word found in it in a set\n        for the language of the file. This language is obtained from\n        the file name. If the file doesn't exist, the method will have\n        no effect.\n\n        Args:\n            path: Path to the stop words file.\n\n        Returns:\n            A boolean indicating whether the file was loaded."
  },
  {
    "code": "def mac_set_relative_dylib_deps(libname):\n    from PyInstaller.lib.macholib import util\n    from PyInstaller.lib.macholib.MachO import MachO\n    if os.path.basename(libname) in _BOOTLOADER_FNAMES:\n        return\n    def match_func(pth):\n        if not util.in_system_path(pth):\n            return os.path.join('@executable_path', os.path.basename(pth))\n    dll = MachO(libname)\n    dll.rewriteLoadCommands(match_func)\n    try:\n        f = open(dll.filename, 'rb+')\n        for header in dll.headers:\n            f.seek(0)\n            dll.write(f)\n        f.seek(0, 2)\n        f.flush()\n        f.close()\n    except Exception:\n        pass",
    "docstring": "On Mac OS X set relative paths to dynamic library dependencies of `libname`.\n\n    Relative paths allow to avoid using environment variable DYLD_LIBRARY_PATH.\n    There are known some issues with DYLD_LIBRARY_PATH. Relative paths is\n    more flexible mechanism.\n\n    Current location of dependend libraries is derived from the location\n    of the executable (paths start with '@executable_path').\n\n    @executable_path or @loader_path fail in some situations\n    (@loader_path - qt4 plugins, @executable_path -\n    Python built-in hashlib module)."
  },
  {
    "code": "def _read_console_output(self, ws, out):\n        while True:\n            msg = yield from ws.receive()\n            if msg.tp == aiohttp.WSMsgType.text:\n                out.feed_data(msg.data.encode())\n            elif msg.tp == aiohttp.WSMsgType.BINARY:\n                out.feed_data(msg.data)\n            elif msg.tp == aiohttp.WSMsgType.ERROR:\n                log.critical(\"Docker WebSocket Error: {}\".format(msg.data))\n            else:\n                out.feed_eof()\n                ws.close()\n                break\n        yield from self.stop()",
    "docstring": "Read Websocket and forward it to the telnet\n\n        :param ws: Websocket connection\n        :param out: Output stream"
  },
  {
    "code": "def get_all_dbparameter_groups(self, groupname=None, max_records=None,\n                                  marker=None):\n        params = {}\n        if groupname:\n            params['DBParameterGroupName'] = groupname\n        if max_records:\n            params['MaxRecords'] = max_records\n        if marker:\n            params['Marker'] = marker\n        return self.get_list('DescribeDBParameterGroups', params,\n                             [('DBParameterGroup', ParameterGroup)])",
    "docstring": "Get all parameter groups associated with your account in a region.\n\n        :type groupname: str\n        :param groupname: The name of the DBParameter group to retrieve.\n                          If not provided, all DBParameter groups will be returned.\n\n        :type max_records: int\n        :param max_records: The maximum number of records to be returned.\n                            If more results are available, a MoreToken will\n                            be returned in the response that can be used to\n                            retrieve additional records.  Default is 100.\n\n        :type marker: str\n        :param marker: The marker provided by a previous request.\n\n        :rtype: list\n        :return: A list of :class:`boto.ec2.parametergroup.ParameterGroup`"
  },
  {
    "code": "def patch_conf(settings_patch=None, settings_file=None):\n    if settings_patch is None:\n        settings_patch = {}\n    reload_config()\n    os.environ[ENVIRONMENT_VARIABLE] = settings_file if settings_file else ''\n    from bernard.conf import settings as l_settings\n    r_settings = l_settings._settings\n    r_settings.update(settings_patch)\n    if 'bernard.i18n' in modules:\n        from bernard.i18n import translate, intents\n        translate._regenerate_word_dict()\n        intents._refresh_intents_db()\n    yield",
    "docstring": "Reload the configuration form scratch. Only the default config is loaded,\n    not the environment-specified config.\n\n    Then the specified patch is applied.\n\n    This is for unit tests only!\n\n    :param settings_patch: Custom configuration values to insert\n    :param settings_file: Custom settings file to read"
  },
  {
    "code": "def topics(self):\n        cluster = self._client.cluster\n        if self._client._metadata_refresh_in_progress and self._client._topics:\n            future = cluster.request_update()\n            self._client.poll(future=future)\n        stash = cluster.need_all_topic_metadata\n        cluster.need_all_topic_metadata = True\n        future = cluster.request_update()\n        self._client.poll(future=future)\n        cluster.need_all_topic_metadata = stash\n        return cluster.topics()",
    "docstring": "Get all topics the user is authorized to view.\n\n        Returns:\n            set: topics"
  },
  {
    "code": "def output_shape(self):\n    if self._output_shape is None:\n      self._ensure_is_connected()\n    if callable(self._output_shape):\n      self._output_shape = tuple(self._output_shape())\n    return self._output_shape",
    "docstring": "Returns the output shape."
  },
  {
    "code": "def _wr_ver_n_key(self, fout_txt, verbose):\n        with open(fout_txt, 'w') as prt:\n            self._prt_ver_n_key(prt, verbose)\n            print('               WROTE: {TXT}'.format(TXT=fout_txt))",
    "docstring": "Write GO DAG version and key indicating presence of GO ID in a list."
  },
  {
    "code": "def _compute_document_meta(self):\n        meta = OrderedDict()\n        bounds_iter = xml_utils.bounds(self.filename,\n                            start_re=r'<text id=\"(\\d+)\"[^>]*name=\"([^\"]*)\"',\n                            end_re=r'</text>')\n        for match, bounds in bounds_iter:\n            doc_id, title = str(match.group(1)), match.group(2)\n            title = xml_utils.unescape_attribute(title)\n            xml_data = xml_utils.load_chunk(self.filename, bounds)\n            doc = Document(compat.ElementTree.XML(xml_data.encode('utf8')))\n            meta[doc_id] = _DocumentMeta(title, bounds, doc.categories())\n        return meta",
    "docstring": "Return documents meta information that can\n        be used for fast document lookups. Meta information\n        consists of documents titles, categories and positions\n        in file."
  },
  {
    "code": "def begin_pending_transactions(self):\n        while not self._pending_sessions.empty():\n            session = self._pending_sessions.get()\n            session._transaction.begin()\n            super(TransactionPingingPool, self).put(session)",
    "docstring": "Begin all transactions for sessions added to the pool."
  },
  {
    "code": "def setupData(self, dataPath, numLabels=0, ordered=False, stripCats=False, seed=42, **kwargs):\n    self.split(dataPath, numLabels, **kwargs)\n    if not ordered:\n      self.randomizeData(seed)\n    filename, ext = os.path.splitext(dataPath)\n    classificationFileName = \"{}_category.json\".format(filename)\n    dataFileName = \"{}_network{}\".format(filename, ext)\n    if stripCats:\n      self.stripCategories()\n    self.saveData(dataFileName, classificationFileName)\n    return dataFileName",
    "docstring": "Main method of this class. Use for setting up a network data file.\n    \n    @param dataPath        (str)    Path to CSV file.\n    @param numLabels       (int)    Number of columns of category labels.\n    @param textPreprocess  (bool)   True will preprocess text while tokenizing.\n    @param ordered         (bool)   Keep data samples (sequences) in order,\n                                    otherwise randomize.\n    @param seed            (int)    Random seed.\n    \n    @return dataFileName   (str)    Network data file name; same directory as\n                                    input data file."
  },
  {
    "code": "def stats(self, request):\n        request = _patch_stats_request(request)\n        body = json.dumps(request)\n        return self.dispatcher.response(models.Request(\n            self._url('data/v1/stats'), self.auth,\n            body_type=models.JSON, data=body, method='POST')).get_body()",
    "docstring": "Get stats for the provided request.\n\n        :param request dict: A search request that also contains the 'interval'\n                             property.\n        :returns: :py:class:`planet.api.models.JSON`\n        :raises planet.api.exceptions.APIException: On API error."
  },
  {
    "code": "def _stop(self):\n        duration = time.time() - self.start\n        self.result['stop'] = str(datetime.datetime.now())\n        self.result['delta'] = int(duration)\n        if self.duration_unit == 'minutes':\n            duration = round(duration / 60.0, 2)\n        else:\n            duration = round(duration, 2)\n        self.result['stdout'] = \"Paused for %s %s\" % (duration, self.duration_unit)",
    "docstring": "calculate the duration we actually paused for and then\n        finish building the task result string"
  },
  {
    "code": "def pack_commands(self, commands):\n        \"Pack multiple commands into the Redis protocol\"\n        output = []\n        pieces = []\n        buffer_length = 0\n        for cmd in commands:\n            for chunk in self.pack_command(*cmd):\n                pieces.append(chunk)\n                buffer_length += len(chunk)\n            if buffer_length > 6000:\n                output.append(SYM_EMPTY.join(pieces))\n                buffer_length = 0\n                pieces = []\n        if pieces:\n            output.append(SYM_EMPTY.join(pieces))\n        return output",
    "docstring": "Pack multiple commands into the Redis protocol"
  },
  {
    "code": "def abort_request(self, request):\n        self.timedout = True\n        try:\n            request.cancel()\n        except error.AlreadyCancelled:\n            return",
    "docstring": "Called to abort request on timeout"
  },
  {
    "code": "def compute_time_at_sun_angle(day, latitude, angle):\n    positive_angle_rad = radians(abs(angle))\n    angle_sign = abs(angle)/angle\n    latitude_rad = radians(latitude)\n    declination = radians(sun_declination(day))\n    numerator = -sin(positive_angle_rad) - sin(latitude_rad) * sin(declination)\n    denominator = cos(latitude_rad) * cos(declination)\n    time_diff = degrees(acos(numerator/denominator)) / 15\n    return time_diff * angle_sign",
    "docstring": "Compute the floating point time difference between mid-day and an angle.\n\n    All the prayers are defined as certain angles from mid-day (Zuhr).\n    This formula is taken from praytimes.org/calculation\n\n    :param day: The day to which to compute for\n    :param longitude: Longitude of the place of interest\n    :angle: The angle at which to compute the time\n    :returns: The floating point time delta between Zuhr and the angle, the\n              sign of the result corresponds to the sign of the angle"
  },
  {
    "code": "def cidr_broadcast(cidr):\n    ips = netaddr.IPNetwork(cidr)\n    return six.text_type(ips.broadcast)",
    "docstring": "Get the broadcast address associated with a CIDR address.\n\n    CLI example::\n\n        salt myminion netaddress.cidr_netmask 192.168.0.0/20"
  },
  {
    "code": "def _setup():\n    _SOCKET.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n    _SOCKET.bind(('', PORT))\n    udp = threading.Thread(target=_listen, daemon=True)\n    udp.start()",
    "docstring": "Set up module.\n\n    Open a UDP socket, and listen in a thread."
  },
  {
    "code": "def get(self, nb=0):\n        return {i: self.stats_history[i].history_raw(nb=nb) for i in self.stats_history}",
    "docstring": "Get the history as a dict of list"
  },
  {
    "code": "def disconnect(self, user):\n        self.remove_user(user)\n        self.send_message(create_message('RoomServer', 'Please all say goodbye to {name}!'.format(name=user.id.name)))\n        self.send_message(create_disconnect(user.id.name))",
    "docstring": "Disconnect a user and send a message to the \n            connected clients"
  },
  {
    "code": "def _build_all_dependencies(self):\n        ret = {}\n        for model, schema in six.iteritems(self._models()):\n            dep_list = self._build_dependent_model_list(schema)\n            ret[model] = dep_list\n        return ret",
    "docstring": "Helper function to build a map of model to their list of model reference dependencies"
  },
  {
    "code": "def remove_entry(self, **field_value):\n        field, value = next(iter(field_value.items()))\n        self.data['entries'][:] = [entry\n            for entry in self.data.get('entries')\n            if entry.get('{}_entry'.format(self.typeof))\n            .get(field) != str(value)]",
    "docstring": "Remove an AccessList entry by field specified. Use the supported\n        arguments for the inheriting class for keyword arguments.\n\n        :raises UpdateElementFailed: failed to modify with reason\n        :return: None"
  },
  {
    "code": "def is_ubuntu():\n    if sys.platform.startswith('linux') and osp.isfile('/etc/lsb-release'):\n        release_info = open('/etc/lsb-release').read()\n        if 'Ubuntu' in release_info:\n            return True\n        else:\n            return False\n    else:\n        return False",
    "docstring": "Detect if we are running in an Ubuntu-based distribution"
  },
  {
    "code": "async def enable(self, reason=None):\n        params = {\"enable\": False, \"reason\": reason}\n        response = await self._api.put(\"/v1/agent/maintenance\", params=params)\n        return response.status == 200",
    "docstring": "Resumes normal operation\n\n        Parameters:\n            reason (str): Reason of enabling\n        Returns:\n            bool: ``True`` on success"
  },
  {
    "code": "def dot(self, other):\n        dot_product = 0\n        a = self.elements\n        b = other.elements\n        a_len = len(a)\n        b_len = len(b)\n        i = j = 0\n        while i < a_len and j < b_len:\n            a_val = a[i]\n            b_val = b[j]\n            if a_val < b_val:\n                i += 2\n            elif a_val > b_val:\n                j += 2\n            else:\n                dot_product += a[i + 1] * b[j + 1]\n                i += 2\n                j += 2\n        return dot_product",
    "docstring": "Calculates the dot product of this vector and another vector."
  },
  {
    "code": "def generic_div(a, b):\n    logger.debug('Called generic_div({}, {})'.format(a, b))\n    return a / b",
    "docstring": "Simple function to divide two numbers"
  },
  {
    "code": "def init_argparser_build_dir(\n            self, argparser, help=(\n                'the build directory, where all sources will be copied to '\n                'as part of the build process; if left unspecified, the '\n                'default behavior is to create a new temporary directory '\n                'that will be removed upon conclusion of the build; if '\n                'specified, it must be an existing directory and all files '\n                'for the build will be copied there instead, overwriting any '\n                'existing file, with no cleanup done after.'\n            )):\n        argparser.add_argument(\n            '--build-dir', default=None, dest=BUILD_DIR,\n            metavar=metavar(BUILD_DIR), help=help,\n        )",
    "docstring": "For setting up build directory"
  },
  {
    "code": "def plotgwsrc(gwb):\n    theta, phi, omega, polarization = gwb.gw_dist()\n    rho = phi-N.pi\n    eta = 0.5*N.pi - theta\n    P.title(\"GWB source population\")\n    ax = P.axes(projection='mollweide')\n    foo = P.scatter(rho, eta, marker='.', s=1)\n    return foo",
    "docstring": "Plot a GWB source population as a mollweide projection."
  },
  {
    "code": "def execute_command_no_results(self, sock_info, generator):\n        full_result = {\n            \"writeErrors\": [],\n            \"writeConcernErrors\": [],\n            \"nInserted\": 0,\n            \"nUpserted\": 0,\n            \"nMatched\": 0,\n            \"nModified\": 0,\n            \"nRemoved\": 0,\n            \"upserted\": [],\n        }\n        write_concern = WriteConcern()\n        op_id = _randint()\n        try:\n            self._execute_command(\n                generator, write_concern, None,\n                sock_info, op_id, False, full_result)\n        except OperationFailure:\n            pass",
    "docstring": "Execute write commands with OP_MSG and w=0 WriteConcern, ordered."
  },
  {
    "code": "def addPolygonAnnot(self, points):\n        CheckParent(self)\n        val = _fitz.Page_addPolygonAnnot(self, points)\n        if not val: return\n        val.thisown = True\n        val.parent = weakref.proxy(self)\n        self._annot_refs[id(val)] = val\n        return val",
    "docstring": "Add a 'Polygon' annotation for a sequence of points."
  },
  {
    "code": "def get_output_jsonpath(self, sub_output=None):\n        output_jsonpath_field = self.get_output_jsonpath_field(sub_output)\n        metadata = self.extractor.get_metadata()\n        metadata['source'] = str(self.input_fields)\n        extractor_filter = \"\"\n        is_first = True\n        for key, value in metadata.iteritems():\n            if is_first:\n                is_first = False\n            else:\n                extractor_filter = extractor_filter + \" & \"\n            if isinstance(value, basestring):\n                extractor_filter = extractor_filter\\\n                    + \"{}=\\\"{}\\\"\".format(key,\n                                         re.sub('(?<=[^\\\\\\])\\\"', \"'\", value))\n            elif isinstance(value, types.ListType):\n                extractor_filter = extractor_filter\\\n                    + \"{}={}\".format(key, str(value))\n        output_jsonpath = \"{}[?{}].result.value\".format(\n            output_jsonpath_field, extractor_filter)\n        return output_jsonpath",
    "docstring": "Attempt to build a JSONPath filter for this ExtractorProcessor\n        that captures how to get at the outputs of the wrapped Extractor"
  },
  {
    "code": "def plot_rebit_prior(prior, rebit_axes=REBIT_AXES,\n        n_samples=2000, true_state=None, true_size=250,\n        force_mean=None,\n        legend=True,\n        mean_color_index=2\n    ):\n    pallette = plt.rcParams['axes.color_cycle']\n    plot_rebit_modelparams(prior.sample(n_samples),\n        c=pallette[0],\n        label='Prior',\n        rebit_axes=rebit_axes\n    )\n    if true_state is not None:\n        plot_rebit_modelparams(true_state,\n            c=pallette[1],\n            label='True', marker='*', s=true_size,\n            rebit_axes=rebit_axes\n        )\n    if hasattr(prior, '_mean') or force_mean is not None:\n        mean = force_mean if force_mean is not None else prior._mean\n        plot_rebit_modelparams(\n            prior._basis.state_to_modelparams(mean)[None, :],\n            edgecolors=pallette[mean_color_index], s=250, facecolors='none', linewidth=3,\n            label='Mean',\n            rebit_axes=rebit_axes\n        )\n    plot_decorate_rebits(prior.basis,\n        rebit_axes=rebit_axes\n    )\n    if legend:\n        plt.legend(loc='lower left', ncol=3, scatterpoints=1)",
    "docstring": "Plots rebit states drawn from a given prior.\n\n    :param qinfer.tomography.DensityOperatorDistribution prior: Distribution over\n        rebit states to plot.\n    :param list rebit_axes: List containing indices for the :math:`x`\n        and :math:`z` axes.\n    :param int n_samples: Number of samples to draw from the\n        prior.\n    :param np.ndarray true_state: State to be plotted as a \"true\" state for\n        comparison."
  },
  {
    "code": "def comicDownloaded(self, comic, filename, text=None):\n        if self.lastComic != comic.name:\n            self.newComic(comic)\n        size = None\n        if self.allowdownscale:\n            size = getDimensionForImage(filename, MaxImageSize)\n        imageUrl = self.getUrlFromFilename(filename)\n        pageUrl = comic.referrer\n        if pageUrl != self.lastUrl:\n            self.html.write(u'<li><a href=\"%s\">%s</a>\\n' % (pageUrl, pageUrl))\n        self.html.write(u'<br/><img src=\"%s\"' % imageUrl)\n        if size:\n            self.html.write(' width=\"%d\" height=\"%d\"' % size)\n        self.html.write('/>\\n')\n        if text:\n            self.html.write(u'<br/>%s\\n' % text)\n        self.lastComic = comic.name\n        self.lastUrl = pageUrl",
    "docstring": "Write HTML entry for downloaded comic."
  },
  {
    "code": "def _CalculateHashesFileEntry(\n      self, file_system, file_entry, parent_full_path, output_writer):\n    full_path = file_system.JoinPath([parent_full_path, file_entry.name])\n    for data_stream in file_entry.data_streams:\n      hash_value = self._CalculateHashDataStream(file_entry, data_stream.name)\n      display_path = self._GetDisplayPath(\n          file_entry.path_spec, full_path, data_stream.name)\n      output_writer.WriteFileHash(display_path, hash_value or 'N/A')\n    for sub_file_entry in file_entry.sub_file_entries:\n      self._CalculateHashesFileEntry(\n          file_system, sub_file_entry, full_path, output_writer)",
    "docstring": "Recursive calculates hashes starting with the file entry.\n\n    Args:\n      file_system (dfvfs.FileSystem): file system.\n      file_entry (dfvfs.FileEntry): file entry.\n      parent_full_path (str): full path of the parent file entry.\n      output_writer (StdoutWriter): output writer."
  },
  {
    "code": "def user_getfield(self, field, access_token=None):\n        info = self.user_getinfo([field], access_token)\n        return info.get(field)",
    "docstring": "Request a single field of information about the user.\n\n        :param field: The name of the field requested.\n        :type field: str\n        :returns: The value of the field. Depending on the type, this may be\n            a string, list, dict, or something else.\n        :rtype: object\n\n        .. versionadded:: 1.0"
  },
  {
    "code": "def on_binop(self, node):\n        return op2func(node.op)(self.run(node.left),\n                                self.run(node.right))",
    "docstring": "Binary operator."
  },
  {
    "code": "def get_significant_decimal(my_decimal):\n    if isinstance(my_decimal, Integral):\n        return my_decimal\n    if my_decimal != my_decimal:\n        return my_decimal\n    my_int_part = str(my_decimal).split('.')[0]\n    my_decimal_part = str(my_decimal).split('.')[1]\n    first_not_zero = 0\n    for i in range(len(my_decimal_part)):\n        if my_decimal_part[i] == '0':\n            continue\n        else:\n            first_not_zero = i\n            break\n    my_truncated_decimal = my_decimal_part[:first_not_zero + 3]\n    my_leftover_number = my_decimal_part[:first_not_zero + 3:]\n    my_leftover_number = int(float('0.' + my_leftover_number))\n    round_up = False\n    if my_leftover_number == 1:\n        round_up = True\n    my_truncated = float(my_int_part + '.' + my_truncated_decimal)\n    if round_up:\n        my_bonus = 1 * 10 ^ (-(first_not_zero + 4))\n        my_truncated += my_bonus\n    return my_truncated",
    "docstring": "Return a truncated decimal by last three digit after leading zero."
  },
  {
    "code": "def find_window(self, highlight_locations):\n        if len(self.text_block) <= self.max_length:\n            return (0, self.max_length)\n        num_chars_before = getattr(\n            settings,\n            'HIGHLIGHT_NUM_CHARS_BEFORE_MATCH',\n            0\n        )\n        best_start, best_end = super(ColabHighlighter, self).find_window(\n            highlight_locations\n        )\n        if best_start <= num_chars_before:\n            best_end -= best_start\n            best_start = 0\n        else:\n            best_start -= num_chars_before\n            best_end -= num_chars_before\n        return (best_start, best_end)",
    "docstring": "Getting the HIGHLIGHT_NUM_CHARS_BEFORE_MATCH setting\n        to find how many characters before the first word found should\n        be removed from the window"
  },
  {
    "code": "def send_all_messages(self, close_on_done=True):\n        self.open()\n        running = True\n        try:\n            messages = self._pending_messages[:]\n            running = self.wait()\n            results = [m.state for m in messages]\n            return results\n        finally:\n            if close_on_done or not running:\n                self.close()",
    "docstring": "Send all pending messages in the queue. This will return a list\n        of the send result of all the pending messages so it can be\n        determined if any messages failed to send.\n        This function will open the client if it is not already open.\n\n        :param close_on_done: Close the client once the messages are sent.\n         Default is `True`.\n        :type close_on_done: bool\n        :rtype: list[~uamqp.constants.MessageState]"
  },
  {
    "code": "def create_user(self, auth, login_name, username, email, password, send_notify=False):\n        data = {\n            \"login_name\": login_name,\n            \"username\": username,\n            \"email\": email,\n            \"password\": password,\n            \"send_notify\": send_notify\n        }\n        response = self.post(\"/admin/users\", auth=auth, data=data)\n        return GogsUser.from_json(response.json())",
    "docstring": "Creates a new user, and returns the created user.\n\n        :param auth.Authentication auth: authentication object, must be admin-level\n        :param str login_name: login name for created user\n        :param str username: username for created user\n        :param str email: email address for created user\n        :param str password: password for created user\n        :param bool send_notify: whether a notification email should be sent upon creation\n        :return: a representation of the created user\n        :rtype: GogsUser\n        :raises NetworkFailure: if there is an error communicating with the server\n        :raises ApiFailure: if the request cannot be serviced"
  },
  {
    "code": "def save_plot(fig, prefile='', postfile='', output_path='./', output_name='Figure',\n              output_format='png', dpi=300, transparent=False, **_):\n    if not os.path.exists(output_path):\n        os.makedirs(output_path)\n    output = os.path.join(output_path,\n                          prefile + output_name + postfile + \".\" + output_format)\n    fig.savefig(output, dpi=dpi, transparent=transparent)",
    "docstring": "Generates a figure file in the selected directory.\n\n    Args:\n        fig: matplotlib figure\n        prefile(str): Include before the general filename of the figure\n        postfile(str): Included after the general filename of the figure\n        output_path(str): Define the path to the output directory\n        output_name(str): String to define the name of the output figure\n        output_format(str): String to define the format of the output figure\n        dpi(int): Define the DPI (Dots per Inch) of the figure\n        transparent(bool): If True the saved figure will have a transparent background"
  },
  {
    "code": "def filter_format(filter_template, assertion_values):\n    assert isinstance(filter_template, bytes)\n    return filter_template % (\n        tuple(map(escape_filter_chars, assertion_values)))",
    "docstring": "filter_template\n          String containing %s as placeholder for assertion values.\n    assertion_values\n          List or tuple of assertion values. Length must match\n          count of %s in filter_template."
  },
  {
    "code": "def global_horizontal_irradiance(self):\n        analysis_period = AnalysisPeriod(timestep=self.timestep,\n                                         is_leap_year=self.is_leap_year)\n        header_ghr = Header(data_type=GlobalHorizontalIrradiance(),\n                            unit='W/m2',\n                            analysis_period=analysis_period,\n                            metadata=self.metadata)\n        glob_horiz = []\n        sp = Sunpath.from_location(self.location)\n        sp.is_leap_year = self.is_leap_year\n        for dt, dnr, dhr in zip(self.datetimes, self.direct_normal_irradiance,\n                                self.diffuse_horizontal_irradiance):\n            sun = sp.calculate_sun_from_date_time(dt)\n            glob_horiz.append(dhr + dnr * math.sin(math.radians(sun.altitude)))\n        return HourlyContinuousCollection(header_ghr, glob_horiz)",
    "docstring": "Returns the global horizontal irradiance at each timestep."
  },
  {
    "code": "def to_list_str(value, encode=None):\n    result = []\n    for index, v in enumerate(value):\n        if isinstance(v, dict):\n            result.append(to_dict_str(v, encode))\n            continue\n        if isinstance(v, list):\n            result.append(to_list_str(v, encode))\n            continue\n        if encode:\n            result.append(encode(v))\n        else:\n            result.append(default_encode(v))\n    return result",
    "docstring": "recursively convert list content into string\n\n    :arg list value: The list that need to be converted.\n    :arg function encode: Function used to encode object."
  },
  {
    "code": "def parse_value(self, val, display, rawdict = 0):\n        ret = {}\n        vno = 0\n        for f in self.static_fields:\n            if not f.name:\n                pass\n            elif isinstance(f, LengthField):\n                pass\n            elif isinstance(f, FormatField):\n                pass\n            else:\n                if f.structvalues == 1:\n                    field_val = val[vno]\n                else:\n                    field_val = val[vno:vno+f.structvalues]\n                if f.parse_value is not None:\n                    field_val = f.parse_value(field_val, display, rawdict=rawdict)\n                ret[f.name] = field_val\n            vno = vno + f.structvalues\n        if not rawdict:\n            return DictWrapper(ret)\n        return ret",
    "docstring": "This function is used by List and Object fields to convert\n        Struct objects with no var_fields into Python values."
  },
  {
    "code": "def create_build_system(working_dir, buildsys_type=None, package=None, opts=None,\n                        write_build_scripts=False, verbose=False,\n                        build_args=[], child_build_args=[]):\n    from rez.plugin_managers import plugin_manager\n    if not buildsys_type:\n        clss = get_valid_build_systems(working_dir, package=package)\n        if not clss:\n            raise BuildSystemError(\n                \"No build system is associated with the path %s\" % working_dir)\n        if len(clss) != 1:\n            s = ', '.join(x.name() for x in clss)\n            raise BuildSystemError((\"Source could be built with one of: %s; \"\n                                   \"Please specify a build system\") % s)\n        buildsys_type = iter(clss).next().name()\n    cls_ = plugin_manager.get_plugin_class('build_system', buildsys_type)\n    return cls_(working_dir,\n                opts=opts,\n                package=package,\n                write_build_scripts=write_build_scripts,\n                verbose=verbose,\n                build_args=build_args,\n                child_build_args=child_build_args)",
    "docstring": "Return a new build system that can build the source in working_dir."
  },
  {
    "code": "def load(self):\n        if isinstance(self.specfile, str):\n            f = open(self.specfile, 'r')\n        else:\n            f = self.specfile\n        for line in f:\n            if self.v_regex.match(line):\n                self._pkg_version = self.v_regex.match(line).group(1)\n            if self.n_regex.match(line):\n                self._pkg_name = self.n_regex.match(line).group(1)\n        f.close()\n        self._loaded = True",
    "docstring": "call this function after the file exists to populate properties"
  },
  {
    "code": "def upload():\n    def twine(*args):\n        process = run(sys.executable, '-m', 'twine', *args)\n        return process.wait() != 0\n    if run(sys.executable, 'setup.py', 'sdist', 'bdist_wheel').wait() != 0:\n        error('failed building packages')\n    if twine('register', glob.glob('dist/*')[0]):\n        error('register failed')\n    if twine('upload', '-s', '-i', 'CB164668', '--skip-existing', 'dist/*'):\n        error('upload failed')",
    "docstring": "build the files and upload to pypi"
  },
  {
    "code": "def imagetransformer_b12l_4h_b128_uncond_dr03_tpu():\n  hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet()\n  update_hparams_for_tpu(hparams)\n  hparams.batch_size = 2\n  hparams.num_heads = 4\n  hparams.num_decoder_layers = 12\n  hparams.block_length = 128\n  hparams.hidden_size = 256\n  hparams.filter_size = 2048\n  hparams.layer_preprocess_sequence = \"none\"\n  hparams.layer_postprocess_sequence = \"dan\"\n  hparams.layer_prepostprocess_dropout = 0.1\n  hparams.optimizer = \"Adafactor\"\n  hparams.learning_rate_schedule = \"rsqrt_decay\"\n  hparams.learning_rate_warmup_steps = 10000\n  return hparams",
    "docstring": "TPU config for cifar 10."
  },
  {
    "code": "def set_data(self, column, value, role):\n        if not self._data or column >= self._data.column_count():\n            return False\n        return self._data.set_data(column, value, role)",
    "docstring": "Set the data of column to value\n\n        :param column: the column to set\n        :type column: int\n        :param value: the value to set\n        :param role: the role, usually EditRole\n        :type role: :class:`QtCore.Qt.ItemDataRole`\n        :returns: True, if data successfully changed\n        :rtype: :class:`bool`\n        :raises: None"
  },
  {
    "code": "def sample(self, frame):\n        frames = self.frame_stack(frame)\n        if frames:\n            frames.pop()\n        parent_stats = self.stats\n        for f in frames:\n            parent_stats = parent_stats.ensure_child(f.f_code, void)\n        stats = parent_stats.ensure_child(frame.f_code, RecordingStatistics)\n        stats.own_hits += 1",
    "docstring": "Samples the given frame."
  },
  {
    "code": "def pub(self, topic=b'', embed_topic=False):\n        if not isinstance(topic, bytes):\n            error = 'Topic must be bytes'\n            log.error(error)\n            raise TypeError(error)\n        sock = self.__sock(zmq.PUB)\n        return self.__send_function(sock, topic, embed_topic)",
    "docstring": "Returns a callable that can be used to transmit a message, with a given\n        ``topic``, in a publisher-subscriber fashion. Note that the sender\n        function has a ``print`` like signature, with an infinite number of\n        arguments. Each one being a part of the complete message.\n\n        By default, no topic will be included into published messages. Being up\n        to developers to include the topic, at the beginning of the first part\n        (i.e. frame) of every published message, so that subscribers are able\n        to receive them. For a different behaviour, check the embed_topic\n        argument.\n\n        :param topic: the topic that will be published to (default=b'')\n        :type topic: bytes\n        :param embed_topic: set for the topic to be automatically sent as the\n                            first part (i.e. frame) of every published message\n                            (default=False)\n        :type embed_topic bool\n        :rtype: function"
  },
  {
    "code": "def _object_to_json(obj):\n        if isinstance(obj, datetime.datetime):\n            return obj.isoformat()\n        return repr(obj)",
    "docstring": "Convert objects that cannot be natively serialized into JSON\n        into their string representation\n\n        For datetime based objects convert them into their ISO formatted\n        string as specified by :meth:`datetime.datetime.isoformat`.\n\n        :param obj: object to convert into a JSON via getting its string\n            representation.\n        :type obj: object\n\n        :return: String value representing the given object ready to be\n            encoded into a JSON.\n        :rtype: str"
  },
  {
    "code": "def touch():\n    if not os.path.isfile(get_rc_path()):\n        open(get_rc_path(), 'a').close()\n        print('Created file: {}'.format(get_rc_path()))",
    "docstring": "Create a .vacationrc file if none exists."
  },
  {
    "code": "def options(self, **kwds):\n        opts = dict(self.opts)\n        for k in kwds:\n            try:\n                _ = opts[k]\n            except KeyError:\n                raise ValueError(\"invalid option {!r}\".format(k))\n            opts[k] = kwds[k]\n        return type(self)(self.cls, opts, self.kwargs)",
    "docstring": "Change options for interactive functions.\n\n        Returns\n        -------\n        A new :class:`_InteractFactory` which will apply the\n        options when called."
  },
  {
    "code": "def add_override(self, addr, key, value):\n        address = Address(str(addr)).id\n        _LOGGER.debug('New override for %s %s is %s', address, key, value)\n        device_override = self._overrides.get(address, {})\n        device_override[key] = value\n        self._overrides[address] = device_override",
    "docstring": "Register an attribute override for a device."
  },
  {
    "code": "def _to_date_in_588(date_str):\n    try:\n        date_tokens = (int(x) for x in date_str.split(\".\"))\n    except ValueError:\n        return date_str\n    return \".\".join(str(x) for x in date_tokens)",
    "docstring": "Convert date in the format ala 03.02.2017 to 3.2.2017.\n\n    Viz #100 for details."
  },
  {
    "code": "def _remove_till_caught_up_3pc(self, last_caught_up_3PC):\n        outdated_pre_prepares = {}\n        for key, pp in self.prePrepares.items():\n            if compare_3PC_keys(key, last_caught_up_3PC) >= 0:\n                outdated_pre_prepares[key] = pp\n        for key, pp in self.sentPrePrepares.items():\n            if compare_3PC_keys(key, last_caught_up_3PC) >= 0:\n                outdated_pre_prepares[key] = pp\n        self.logger.trace('{} going to remove messages for {} 3PC keys'.format(\n            self, len(outdated_pre_prepares)))\n        for key, pp in outdated_pre_prepares.items():\n            self.batches.pop(key, None)\n            self.sentPrePrepares.pop(key, None)\n            self.prePrepares.pop(key, None)\n            self.prepares.pop(key, None)\n            self.commits.pop(key, None)\n            self._discard_ordered_req_keys(pp)",
    "docstring": "Remove any 3 phase messages till the last ordered key and also remove\n        any corresponding request keys"
  },
  {
    "code": "def _text_position(size, text, font):\n        width, height = font.getsize(text)\n        left = (size - width) / 2.0\n        top = (size - height) / 3.0\n        return left, top",
    "docstring": "Returns the left-top point where the text should be positioned."
  },
  {
    "code": "def delete_subject(self, subject_id):\n        uri = self._get_subject_uri(guid=subject_id)\n        return self.service._delete(uri)",
    "docstring": "Remove a specific subject by its identifier."
  },
  {
    "code": "def stop_event_stream(self):\n        if self._stream:\n            self._stream.stop()\n            self._stream.join()\n            self._stream = None\n            with self._events.mutex:\n                self._events.queue.clear()",
    "docstring": "Stop streaming events from `gerrit stream-events`."
  },
  {
    "code": "def tb_capture(func):\n    @wraps(func)\n    def wrapper(*args, **kwds):\n        try:\n            return func(*args, **kwds)\n        except Exception:\n            raise MuchoChildError()\n    return wrapper",
    "docstring": "A decorator which captures worker tracebacks.\n\n    Tracebacks in particular, are captured. Inspired by an example in\n    https://bugs.python.org/issue13831.\n\n    This decorator wraps rio-mucho worker tasks.\n\n    Parameters\n    ----------\n    func : function\n        A function to be decorated.\n\n    Returns\n    -------\n    func"
  },
  {
    "code": "def upper_diag_self_prodx(list_):\n    return [(item1, item2)\n            for n1, item1 in enumerate(list_)\n            for n2, item2 in enumerate(list_) if n1 < n2]",
    "docstring": "upper diagnoal of cartesian product of self and self.\n    Weird name. fixme\n\n    Args:\n        list_ (list):\n\n    Returns:\n        list:\n\n    CommandLine:\n        python -m utool.util_alg --exec-upper_diag_self_prodx\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_alg import *  # NOQA\n        >>> list_ = [1, 2, 3]\n        >>> result = upper_diag_self_prodx(list_)\n        >>> print(result)\n        [(1, 2), (1, 3), (2, 3)]"
  },
  {
    "code": "def read(self):\n        buffer = BytesIO()\n        for chunk in self.buffer_iter():\n            log.debug('buffer.write(%r)', chunk)\n            buffer.write(chunk)\n        buffer.seek(0)\n        return buffer.read()",
    "docstring": "Read buffer out as a single stream.\n\n        .. warning::\n\n            Avoid using this function!\n\n            **Why?** This is a *convenience* function; it doesn't encourage good\n            memory management.\n\n            All memory required for a mesh is duplicated, and returned as a\n            single :class:`str`. So at best, using this function will double\n            the memory required for a single model.\n\n            **Instead:** Wherever possible, please use :meth:`buffer_iter`."
  },
  {
    "code": "def _async_requests(urls):\n    session = FuturesSession(max_workers=30)\n    futures = [\n        session.get(url)\n        for url in urls\n    ]\n    return [ future.result() for future in futures ]",
    "docstring": "Sends multiple non-blocking requests. Returns\n    a list of responses.\n\n    :param urls:\n        List of urls"
  },
  {
    "code": "def fave_dashboards_by_username(self, username):\n        user = security_manager.find_user(username=username)\n        return self.fave_dashboards(user.get_id())",
    "docstring": "This lets us use a user's username to pull favourite dashboards"
  },
  {
    "code": "def get_mesh(self, var, coords=None):\n        mesh = var.attrs.get('mesh')\n        if mesh is None:\n            return None\n        if coords is None:\n            coords = self.ds.coords\n        return coords.get(mesh, self.ds.coords.get(mesh))",
    "docstring": "Get the mesh variable for the given `var`\n\n        Parameters\n        ----------\n        var: xarray.Variable\n            The data source whith the ``'mesh'`` attribute\n        coords: dict\n            The coordinates to use. If None, the coordinates of the dataset of\n            this decoder is used\n\n        Returns\n        -------\n        xarray.Coordinate\n            The mesh coordinate"
  },
  {
    "code": "def on_backward_begin(self, last_loss, last_output, **kwargs):\n        \"Record `last_loss` in the proper list.\"\n        last_loss = last_loss.detach().cpu()\n        if self.gen_mode:\n            self.smoothenerG.add_value(last_loss)\n            self.glosses.append(self.smoothenerG.smooth)\n            self.last_gen = last_output.detach().cpu()\n        else:\n            self.smoothenerC.add_value(last_loss)\n            self.closses.append(self.smoothenerC.smooth)",
    "docstring": "Record `last_loss` in the proper list."
  },
  {
    "code": "def function_arg_count(fn):\n    assert callable(fn), 'function_arg_count needed a callable function, not {0}'.format(repr(fn))\n    if hasattr(fn, '__code__') and hasattr(fn.__code__, 'co_argcount'):\n        return fn.__code__.co_argcount\n    else:\n        return 1",
    "docstring": "returns how many arguments a funciton has"
  },
  {
    "code": "def DbImportDevice(self, argin):\n        self._log.debug(\"In DbImportDevice()\")\n        return self.db.import_device(argin.lower())",
    "docstring": "Import a device from the database\n\n        :param argin: Device name (or alias)\n        :type: tango.DevString\n        :return: Str[0] = device name\n        Str[1] = CORBA IOR\n        Str[2] = device version\n        Str[3] = device server process name\n        Str[4] = host name\n        Str[5] = Tango class name\n\n        Lg[0] = Exported flag\n        Lg[1] = Device server process PID\n        :rtype: tango.DevVarLongStringArray"
  },
  {
    "code": "def And(*predicates, **kwargs):\n    if kwargs:\n        predicates += Query(**kwargs),\n    return _flatten(_And, *predicates)",
    "docstring": "`And` predicate. Returns ``False`` at the first sub-predicate that returns ``False``."
  },
  {
    "code": "def write_short_at(self, n, pos, pack_into=Struct('>H').pack_into):\n        if 0 <= n <= 0xFFFF:\n            pack_into(self._output_buffer, pos, n)\n        else:\n            raise ValueError('Short %d out of range 0..0xFFFF', n)\n        return self",
    "docstring": "Write an unsigned 16bit value at a specific position in the buffer.\n        Used for writing tables and frames."
  },
  {
    "code": "def plugins(self):\n        if not self.loaded:\n            self.load_modules()\n        return get_plugins()[self.group]._filter(blacklist=self.blacklist, newest_only=True,\n                                                 type_filter=self.type_filter)",
    "docstring": "Newest version of all plugins in the group filtered by ``blacklist``\n\n        Returns:\n            dict: Nested dictionary of plugins accessible through dot-notation.\n\n        Plugins are returned in a nested dictionary, but can also be accessed through dot-notion.\n        Just as when accessing an undefined dictionary key with index-notation,\n        a :py:exc:`KeyError` will be raised if the plugin type or plugin does not exist.\n\n        Parent types are always included.\n        Child plugins will only be included if a valid, non-blacklisted plugin is available."
  },
  {
    "code": "def add_vrf(self):\n        v = VRF()\n        if 'rt' in request.json:\n            v.rt = validate_string(request.json, 'rt')\n        if 'name' in request.json:\n            v.name = validate_string(request.json, 'name')\n        if 'description' in request.json:\n            v.description = validate_string(request.json, 'description')\n        if 'tags' in request.json:\n            v.tags = request.json['tags']\n        if 'avps' in request.json:\n            v.avps = request.json['avps']\n        try:\n            v.save()\n        except NipapError, e:\n            return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})\n        return json.dumps(v, cls=NipapJSONEncoder)",
    "docstring": "Add a new VRF to NIPAP and return its data."
  },
  {
    "code": "def _try_then(self):\n        if self._cached is not None and self._callback is not None:\n            self._callback(*self._cached[0], **self._cached[1])",
    "docstring": "Check to see if self has been resolved yet, if so invoke then."
  },
  {
    "code": "def export_gcm_encrypted_private_key(self, password: str, salt: str, n: int = 16384) -> str:\n        r = 8\n        p = 8\n        dk_len = 64\n        scrypt = Scrypt(n, r, p, dk_len)\n        derived_key = scrypt.generate_kd(password, salt)\n        iv = derived_key[0:12]\n        key = derived_key[32:64]\n        hdr = self.__address.b58encode().encode()\n        mac_tag, cipher_text = AESHandler.aes_gcm_encrypt_with_iv(self.__private_key, hdr, key, iv)\n        encrypted_key = bytes.hex(cipher_text) + bytes.hex(mac_tag)\n        encrypted_key_str = base64.b64encode(bytes.fromhex(encrypted_key))\n        return encrypted_key_str.decode('utf-8')",
    "docstring": "This interface is used to export an AES algorithm encrypted private key with the mode of GCM.\n\n        :param password: the secret pass phrase to generate the keys from.\n        :param salt: A string to use for better protection from dictionary attacks.\n                      This value does not need to be kept secret, but it should be randomly chosen for each derivation.\n                      It is recommended to be at least 8 bytes long.\n        :param n: CPU/memory cost parameter. It must be a power of 2 and less than 2**32\n        :return: an gcm encrypted private key in the form of string."
  },
  {
    "code": "def body_encode(self, string):\n        if not string:\n            return string\n        if self.body_encoding is BASE64:\n            if isinstance(string, str):\n                string = string.encode(self.output_charset)\n            return email.base64mime.body_encode(string)\n        elif self.body_encoding is QP:\n            if isinstance(string, str):\n                string = string.encode(self.output_charset)\n            string = string.decode('latin1')\n            return email.quoprimime.body_encode(string)\n        else:\n            if isinstance(string, str):\n                string = string.encode(self.output_charset).decode('ascii')\n            return string",
    "docstring": "Body-encode a string by converting it first to bytes.\n\n        The type of encoding (base64 or quoted-printable) will be based on\n        self.body_encoding.  If body_encoding is None, we assume the\n        output charset is a 7bit encoding, so re-encoding the decoded\n        string using the ascii codec produces the correct string version\n        of the content."
  },
  {
    "code": "def copyData(self, source):\n        for attr in self.copyAttributes:\n            selfValue = getattr(self, attr)\n            sourceValue = getattr(source, attr)\n            if isinstance(selfValue, BaseObject):\n                selfValue.copyData(sourceValue)\n            else:\n                setattr(self, attr, sourceValue)",
    "docstring": "Subclasses may override this method.\n        If so, they should call the super."
  },
  {
    "code": "def open_subscription_page(self, content_type):\n        from .subscription_page import SubscriptionPage\n        with self.term.loader('Loading {0}s'.format(content_type)):\n            page = SubscriptionPage(self.reddit, self.term, self.config,\n                                    self.oauth, content_type=content_type)\n        if not self.term.loader.exception:\n            return page",
    "docstring": "Open an instance of the subscriptions page with the selected content."
  },
  {
    "code": "def create_context_menu_actions(self):\r\n        actions = []\r\n        fnames = self.get_selected_filenames()\r\n        new_actions = self.create_file_new_actions(fnames)\r\n        if len(new_actions) > 1:\r\n            new_act_menu = QMenu(_('New'), self)\r\n            add_actions(new_act_menu, new_actions)\r\n            actions.append(new_act_menu)\r\n        else:\r\n            actions += new_actions\r\n        import_actions = self.create_file_import_actions(fnames)\r\n        if len(import_actions) > 1:\r\n            import_act_menu = QMenu(_('Import'), self)\r\n            add_actions(import_act_menu, import_actions)\r\n            actions.append(import_act_menu)\r\n        else:\r\n            actions += import_actions\r\n        if actions:\r\n            actions.append(None)\r\n        if fnames:\r\n            actions += self.create_file_manage_actions(fnames)\r\n        if actions:\r\n            actions.append(None)\r\n        if fnames and all([osp.isdir(_fn) for _fn in fnames]):\r\n            actions += self.create_folder_manage_actions(fnames)\r\n        return actions",
    "docstring": "Create context menu actions"
  },
  {
    "code": "def duration(self):\n        if self._closed or \\\n                not self._result or \\\n                \"duration\" not in self._result:\n            return -1\n        return self._result.get(\"duration\", 0)",
    "docstring": "This read-only attribute specifies the server-side duration of a query\n        in milliseconds."
  },
  {
    "code": "def pop(self, key, default=None):\n        \"Standard pop semantics for all mapping types\"\n        if not isinstance(key, tuple): key = (key,)\n        return self.data.pop(key, default)",
    "docstring": "Standard pop semantics for all mapping types"
  },
  {
    "code": "def command(self, name, *args):\n        args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))\n                for arg in args if arg is not None ] + [None]\n        _mpv_command(self.handle, (c_char_p*len(args))(*args))",
    "docstring": "Execute a raw command."
  },
  {
    "code": "def from_source(source_name):\n        meta_bucket = 'net-mozaws-prod-us-west-2-pipeline-metadata'\n        store = S3Store(meta_bucket)\n        try:\n            source = json.loads(store.get_key('sources.json').read().decode('utf-8'))[source_name]\n        except KeyError:\n            raise Exception('Unknown source {}'.format(source_name))\n        schema = store.get_key('{}/schema.json'.format(source['metadata_prefix'])).read().decode('utf-8')\n        dimensions = [f['field_name'] for f in json.loads(schema)['dimensions']]\n        return Dataset(source['bucket'], dimensions, prefix=source['prefix'])",
    "docstring": "Create a Dataset configured for the given source_name\n\n        This is particularly convenient when the user doesn't know\n        the list of dimensions or the bucket name, but only the source name.\n\n        Usage example::\n\n            records = Dataset.from_source('telemetry').where(\n                docType='main',\n                submissionDate='20160701',\n                appUpdateChannel='nightly'\n            )"
  },
  {
    "code": "def expect(self, pattern, timeout=-1, searchwindowsize=-1, async_=False, **kw):\n        if 'async' in kw:\n            async_ = kw.pop('async')\n        if kw:\n            raise TypeError(\"Unknown keyword arguments: {}\".format(kw))\n        compiled_pattern_list = self.compile_pattern_list(pattern)\n        return self.expect_list(compiled_pattern_list,\n                timeout, searchwindowsize, async_)",
    "docstring": "This seeks through the stream until a pattern is matched. The\n        pattern is overloaded and may take several types. The pattern can be a\n        StringType, EOF, a compiled re, or a list of any of those types.\n        Strings will be compiled to re types. This returns the index into the\n        pattern list. If the pattern was not a list this returns index 0 on a\n        successful match. This may raise exceptions for EOF or TIMEOUT. To\n        avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern\n        list. That will cause expect to match an EOF or TIMEOUT condition\n        instead of raising an exception.\n\n        If you pass a list of patterns and more than one matches, the first\n        match in the stream is chosen. If more than one pattern matches at that\n        point, the leftmost in the pattern list is chosen. For example::\n\n            # the input is 'foobar'\n            index = p.expect(['bar', 'foo', 'foobar'])\n            # returns 1('foo') even though 'foobar' is a \"better\" match\n\n        Please note, however, that buffering can affect this behavior, since\n        input arrives in unpredictable chunks. For example::\n\n            # the input is 'foobar'\n            index = p.expect(['foobar', 'foo'])\n            # returns 0('foobar') if all input is available at once,\n            # but returns 1('foo') if parts of the final 'bar' arrive late\n\n        When a match is found for the given pattern, the class instance\n        attribute *match* becomes an re.MatchObject result.  Should an EOF\n        or TIMEOUT pattern match, then the match attribute will be an instance\n        of that exception class.  The pairing before and after class\n        instance attributes are views of the data preceding and following\n        the matching pattern.  On general exception, class attribute\n        *before* is all data received up to the exception, while *match* and\n        *after* attributes are value None.\n\n        When the keyword argument timeout is -1 (default), then TIMEOUT will\n        raise after the default value specified by the class timeout\n        attribute. When None, TIMEOUT will not be raised and may block\n        indefinitely until match.\n\n        When the keyword argument searchwindowsize is -1 (default), then the\n        value specified by the class maxread attribute is used.\n\n        A list entry may be EOF or TIMEOUT instead of a string. This will\n        catch these exceptions and return the index of the list entry instead\n        of raising the exception. The attribute 'after' will be set to the\n        exception type. The attribute 'match' will be None. This allows you to\n        write code like this::\n\n                index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])\n                if index == 0:\n                    do_something()\n                elif index == 1:\n                    do_something_else()\n                elif index == 2:\n                    do_some_other_thing()\n                elif index == 3:\n                    do_something_completely_different()\n\n        instead of code like this::\n\n                try:\n                    index = p.expect(['good', 'bad'])\n                    if index == 0:\n                        do_something()\n                    elif index == 1:\n                        do_something_else()\n                except EOF:\n                    do_some_other_thing()\n                except TIMEOUT:\n                    do_something_completely_different()\n\n        These two forms are equivalent. It all depends on what you want. You\n        can also just expect the EOF if you are waiting for all output of a\n        child to finish. For example::\n\n                p = pexpect.spawn('/bin/ls')\n                p.expect(pexpect.EOF)\n                print p.before\n\n        If you are trying to optimize for speed then see expect_list().\n\n        On Python 3.4, or Python 3.3 with asyncio installed, passing\n        ``async_=True``  will make this return an :mod:`asyncio` coroutine,\n        which you can yield from to get the same result that this method would\n        normally give directly. So, inside a coroutine, you can replace this code::\n\n            index = p.expect(patterns)\n\n        With this non-blocking form::\n\n            index = yield from p.expect(patterns, async_=True)"
  },
  {
    "code": "def transpose(self, semitone):\n        if semitone > 0 and semitone < 128:\n            self.pianoroll[:, semitone:] = self.pianoroll[:, :(128 - semitone)]\n            self.pianoroll[:, :semitone] = 0\n        elif semitone < 0 and semitone > -128:\n            self.pianoroll[:, :(128 + semitone)] = self.pianoroll[:, -semitone:]\n            self.pianoroll[:, (128 + semitone):] = 0",
    "docstring": "Transpose the pianoroll by a number of semitones, where positive\n        values are for higher key, while negative values are for lower key.\n\n        Parameters\n        ----------\n        semitone : int\n            The number of semitones to transpose the pianoroll."
  },
  {
    "code": "def _validate_compression_params(self, img_array, cparams, colorspace):\n        self._validate_j2k_colorspace(cparams, colorspace)\n        self._validate_codeblock_size(cparams)\n        self._validate_precinct_size(cparams)\n        self._validate_image_rank(img_array)\n        self._validate_image_datatype(img_array)",
    "docstring": "Check that the compression parameters are valid.\n\n        Parameters\n        ----------\n        img_array : ndarray\n            Image data to be written to file.\n        cparams : CompressionParametersType(ctypes.Structure)\n            Corresponds to cparameters_t type in openjp2 headers."
  },
  {
    "code": "def by_name(cls, name):\n    if name not in cls._goal_by_name:\n      cls._goal_by_name[name] = _Goal(name)\n    return cls._goal_by_name[name]",
    "docstring": "Returns the unique object representing the goal of the specified name.\n\n    :API: public"
  },
  {
    "code": "def add_string_pairs_from_text_field_element(xib_file, results, text_field, special_ui_components_prefix):\n    text_field_entry_comment = extract_element_internationalized_comment(text_field)\n    if text_field_entry_comment is None:\n        return\n    if text_field.hasAttribute('usesAttributedText') and text_field.attributes['usesAttributedText'].value == 'YES':\n        add_string_pairs_from_attributed_ui_element(results, text_field, text_field_entry_comment)\n    else:\n        try:\n            text_field_entry_key = text_field.attributes['text'].value\n            results.append((text_field_entry_key, text_field_entry_comment + ' default text value'))\n        except KeyError:\n            pass\n    try:\n        text_field_entry_key = text_field.attributes['placeholder'].value\n        results.append((text_field_entry_key, text_field_entry_comment + ' placeholder text value'))\n    except KeyError:\n        pass\n    warn_if_element_not_of_class(text_field, 'TextField', special_ui_components_prefix)",
    "docstring": "Adds string pairs from a textfield element.\n\n    Args:\n        xib_file (str): Path to the xib file.\n        results (list): The list to add the results to.\n        text_field(element): The textfield element from the xib, to extract the string pairs from.\n        special_ui_components_prefix (str):\n            If not None, extraction will not warn about internationalized UI components with this class prefix."
  },
  {
    "code": "def hook_point(self, hook_name, handle=None):\n        full_hook_name = 'hook_' + hook_name\n        for module in self.modules_manager.instances:\n            _ts = time.time()\n            if not hasattr(module, full_hook_name):\n                continue\n            fun = getattr(module, full_hook_name)\n            try:\n                fun(handle if handle is not None else self)\n            except Exception as exp:\n                logger.warning('The instance %s raised an exception %s. I disabled it,'\n                               ' and set it to restart later', module.name, str(exp))\n                logger.exception('Exception %s', exp)\n                self.modules_manager.set_to_restart(module)\n            else:\n                statsmgr.timer('hook.%s.%s' % (hook_name, module.name), time.time() - _ts)",
    "docstring": "Used to call module function that may define a hook function for hook_name\n\n        Available hook points:\n        - `tick`, called on each daemon loop turn\n        - `save_retention`; called by the scheduler when live state\n            saving is to be done\n        - `load_retention`; called by the scheduler when live state\n            restoring is necessary (on restart)\n        - `get_new_actions`; called by the scheduler before adding the actions to be executed\n        - `early_configuration`; called by the arbiter when it begins parsing the configuration\n        - `read_configuration`; called by the arbiter when it read the configuration\n        - `late_configuration`; called by the arbiter when it finishes parsing the configuration\n\n        As a default, the `handle` parameter provided to the hooked function is the\n        caller Daemon object. The scheduler will provide its own instance when it call this\n        function.\n\n        :param hook_name: function name we may hook in module\n        :type hook_name: str\n        :param handle: parameter to provide to the hook function\n        :type: handle: alignak.Satellite\n        :return: None"
  },
  {
    "code": "def n1ql_index_create_primary(self, defer=False, ignore_exists=False):\n        return self.n1ql_index_create(\n            '', defer=defer, primary=True, ignore_exists=ignore_exists)",
    "docstring": "Create the primary index on the bucket.\n\n        Equivalent to::\n\n            n1ql_index_create('', primary=True, **kwargs)\n\n        :param bool defer:\n        :param bool ignore_exists:\n\n        .. seealso:: :meth:`create_index`"
  },
  {
    "code": "def clear_lock(self, back=None, remote=None):\n        back = self.backends(back)\n        cleared = []\n        errors = []\n        for fsb in back:\n            fstr = '{0}.clear_lock'.format(fsb)\n            if fstr in self.servers:\n                good, bad = clear_lock(self.servers[fstr],\n                                       fsb,\n                                       remote=remote)\n                cleared.extend(good)\n                errors.extend(bad)\n        return cleared, errors",
    "docstring": "Clear the update lock for the enabled fileserver backends\n\n        back\n            Only clear the update lock for the specified backend(s). The\n            default is to clear the lock for all enabled backends\n\n        remote\n            If specified, then any remotes which contain the passed string will\n            have their lock cleared."
  },
  {
    "code": "def increment_bucket_count(self, value):\n        if len(self._bounds) == 0:\n            self._counts_per_bucket[0] += 1\n            return 0\n        for ii, bb in enumerate(self._bounds):\n            if value < bb:\n                self._counts_per_bucket[ii] += 1\n                return ii\n        else:\n            last_bucket_index = len(self._bounds)\n            self._counts_per_bucket[last_bucket_index] += 1\n            return last_bucket_index",
    "docstring": "Increment the bucket count based on a given value from the user"
  },
  {
    "code": "def ascii_listing2program_dump(self, basic_program_ascii, program_start=None):\n        if program_start is None:\n            program_start = self.DEFAULT_PROGRAM_START\n        basic_lines = self.ascii_listing2basic_lines(basic_program_ascii, program_start)\n        program_dump=self.listing.basic_lines2program_dump(basic_lines, program_start)\n        assert isinstance(program_dump, bytearray), (\n            \"is type: %s and not bytearray: %s\" % (type(program_dump), repr(program_dump))\n        )\n        return program_dump",
    "docstring": "convert a ASCII BASIC program listing into tokens.\n        This tokens list can be used to insert it into the\n        Emulator RAM."
  },
  {
    "code": "def _smcra_to_str(self, smcra, temp_dir='/tmp/'):\n        temp_path = tempfile.mktemp( '.pdb', dir=temp_dir )\n        io = PDBIO()\n        io.set_structure(smcra)\n        io.save(temp_path)\n        f = open(temp_path, 'r')\n        string = f.read()\n        f.close()\n        os.remove(temp_path)\n        return string",
    "docstring": "WHATIF's input are PDB format files.\n        Converts a SMCRA object to a PDB formatted string."
  },
  {
    "code": "def zGetRefresh(self):\n        OpticalSystem._dde_link.zGetRefresh()\n        OpticalSystem._dde_link.zSaveFile(self._sync_ui_file)\n        self._iopticalsystem.LoadFile (self._sync_ui_file, False)",
    "docstring": "Copy lens in UI to headless ZOS COM server"
  },
  {
    "code": "def get_pid(name, path=None):\n    if name not in list_(limit='running', path=path):\n        raise CommandExecutionError('Container {0} is not running, can\\'t determine PID'.format(name))\n    info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split(\"\\n\")\n    pid = [line.split(':')[1].strip() for line in info if re.match(r'\\s*PID', line)][0]\n    return pid",
    "docstring": "Returns a container pid.\n    Throw an exception if the container isn't running.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' lxc.get_pid name"
  },
  {
    "code": "def update(self, **kwargs):\n        self.inflate()\n        for model in self._models:\n            model.update(**kwargs)\n        return self",
    "docstring": "Update all resources in this collection."
  },
  {
    "code": "def json_data(self):\n        return {\n            \"number\": self.number,\n            \"type\": self.type,\n            \"participant_id\": self.participant_id,\n            \"question\": self.question,\n            \"response\": self.response,\n        }",
    "docstring": "Return json description of a question."
  },
  {
    "code": "def _expand_disk(disk):\n    ret = {}\n    ret.update(disk.__dict__)\n    zone = ret['extra']['zone']\n    ret['extra']['zone'] = {}\n    ret['extra']['zone'].update(zone.__dict__)\n    return ret",
    "docstring": "Convert the libcloud Volume object into something more serializable."
  },
  {
    "code": "def handle_msec_timestamp(self, m, master):\n        if m.get_type() == 'GLOBAL_POSITION_INT':\n            return\n        msec = m.time_boot_ms\n        if msec + 30000 < master.highest_msec:\n            self.say('Time has wrapped')\n            print('Time has wrapped', msec, master.highest_msec)\n            self.status.highest_msec = msec\n            for mm in self.mpstate.mav_master:\n                mm.link_delayed = False\n                mm.highest_msec = msec\n            return\n        master.highest_msec = msec\n        if msec > self.status.highest_msec:\n            self.status.highest_msec = msec\n        if msec < self.status.highest_msec and len(self.mpstate.mav_master) > 1 and self.mpstate.settings.checkdelay:\n            master.link_delayed = True\n        else:\n            master.link_delayed = False",
    "docstring": "special handling for MAVLink packets with a time_boot_ms field"
  },
  {
    "code": "def has_table(self, table):\n        sql = self._grammar.compile_table_exists()\n        table = self._connection.get_table_prefix() + table\n        return len(self._connection.select(sql, [table])) > 0",
    "docstring": "Determine if the given table exists.\n\n        :param table: The table\n        :type table: str\n\n        :rtype: bool"
  },
  {
    "code": "def write_config(config, filename=None):\n    if not filename:\n        filename = CONFIG_DEFAULT_PATH\n    with open(filename, 'w') as f:\n        json.dump(config, f, indent=4)",
    "docstring": "Write the provided configuration to a specific location.\n\n    Args:\n        config (dict): a dictionary with the configuration to load.\n        filename (str): the name of the file that will store the new configuration. Defaults to ``None``.\n            If ``None``, the HOME of the current user and the string ``.bigchaindb`` will be used."
  },
  {
    "code": "def number_crossing_m(x, m):\n    if not isinstance(x, (np.ndarray, pd.Series)):\n        x = np.asarray(x)\n    positive = x > m\n    return np.where(np.bitwise_xor(positive[1:], positive[:-1]))[0].size",
    "docstring": "Calculates the number of crossings of x on m. A crossing is defined as two sequential values where the first value\n    is lower than m and the next is greater, or vice-versa. If you set m to zero, you will get the number of zero\n    crossings.\n\n    :param x: the time series to calculate the feature of\n    :type x: numpy.ndarray\n    :param m: the threshold for the crossing\n    :type m: float\n    :return: the value of this feature\n    :return type: int"
  },
  {
    "code": "def mysql_aes_encrypt(val, key):\n    assert isinstance(val, binary_type) or isinstance(val, text_type)\n    assert isinstance(key, binary_type) or isinstance(key, text_type)\n    k = _mysql_aes_key(_to_binary(key))\n    v = _mysql_aes_pad(_to_binary(val))\n    e = _mysql_aes_engine(k).encryptor()\n    return e.update(v) + e.finalize()",
    "docstring": "Mysql AES encrypt value with secret key.\n\n    :param val: Plain text value.\n    :param key: The AES key.\n    :returns: The encrypted AES value."
  },
  {
    "code": "def getGenericInterface(interfaceVersion):\n    error = EVRInitError()\n    result =     _openvr.VR_GetGenericInterface(interfaceVersion, byref(error))\n    _checkInitError(error.value)\n    return result",
    "docstring": "Returns the interface of the specified version. This method must be called after VR_Init. The\r\n    pointer returned is valid until VR_Shutdown is called."
  },
  {
    "code": "def stack_pop(self):\n        sp = self.regs.sp\n        self.regs.sp = sp - self.arch.stack_change\n        return self.memory.load(sp, self.arch.bytes, endness=self.arch.memory_endness)",
    "docstring": "Pops from the stack and returns the popped thing. The length will be the architecture word size."
  },
  {
    "code": "def to_text(self, origin=None, relativize=True, **kw):\n        return super(RRset, self).to_text(self.name, origin, relativize,\n                                          self.deleting, **kw)",
    "docstring": "Convert the RRset into DNS master file format.\n\n        @see: L{dns.name.Name.choose_relativity} for more information\n        on how I{origin} and I{relativize} determine the way names\n        are emitted.\n\n        Any additional keyword arguments are passed on to the rdata\n        to_text() method.\n\n        @param origin: The origin for relative names, or None.\n        @type origin: dns.name.Name object\n        @param relativize: True if names should names be relativized\n        @type relativize: bool"
  },
  {
    "code": "def _pid_to_id(self, pid):\n        return d1_common.url.joinPathElements(\n            self._base_url,\n            self._version_tag,\n            \"resolve\",\n            d1_common.url.encodePathElement(pid),\n        )",
    "docstring": "Converts a pid to a URI that can be used as an OAI-ORE identifier."
  },
  {
    "code": "def to_grayscale(self):\n        gray_data = cv2.cvtColor(self.data, cv2.COLOR_RGB2GRAY)\n        return GrayscaleImage(gray_data, frame=self.frame)",
    "docstring": "Converts the color image to grayscale using OpenCV.\n\n        Returns\n        -------\n        :obj:`GrayscaleImage`\n            Grayscale image corresponding to original color image."
  },
  {
    "code": "def predict(self, X, with_noise=True):\n        m, v = self._predict(X, False, with_noise)\n        return m, np.sqrt(v)",
    "docstring": "Predictions with the model. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given.\n\n        Parameters:\n            X (np.ndarray) - points to run the prediction for.\n            with_noise (bool) - whether to add noise to the prediction. Default is True."
  },
  {
    "code": "def printDiagnostics(exp, sequences, objects, args, verbosity=0):\n  print \"Experiment start time:\", time.ctime()\n  print \"\\nExperiment arguments:\"\n  pprint.pprint(args)\n  r = sequences.objectConfusion()\n  print \"Average common pairs in sequences=\", r[0],\n  print \", features=\",r[2]\n  r = objects.objectConfusion()\n  print \"Average common pairs in objects=\", r[0],\n  print \", locations=\",r[1],\n  print \", features=\",r[2]\n  if verbosity > 0:\n    print \"\\nObjects are:\"\n    for o in objects:\n      pairs = objects[o]\n      pairs.sort()\n      print str(o) + \": \" + str(pairs)\n    print \"\\nSequences:\"\n    for i in sequences:\n      print i,sequences[i]\n  print \"\\nNetwork parameters:\"\n  pprint.pprint(exp.config)",
    "docstring": "Useful diagnostics for debugging."
  },
  {
    "code": "def _bp(editor, force=False):\n    eb = editor.window_arrangement.active_editor_buffer\n    if not force and eb.has_unsaved_changes:\n        editor.show_message(_NO_WRITE_SINCE_LAST_CHANGE_TEXT)\n    else:\n        editor.window_arrangement.go_to_previous_buffer()",
    "docstring": "Go to previous buffer."
  },
  {
    "code": "def from_notebook_node(self, nb, resources=None, **kw):\n        from weasyprint import HTML, CSS\n        nb = copy.deepcopy(nb)\n        output, resources = super(OneCodexPDFExporter, self).from_notebook_node(\n            nb, resources=resources, **kw\n        )\n        buf = BytesIO()\n        HTML(string=output).write_pdf(\n            buf, stylesheets=[CSS(os.path.join(ASSETS_PATH, CSS_TEMPLATE_FILE))]\n        )\n        buf.seek(0)\n        return buf.read(), resources",
    "docstring": "Takes output of OneCodexHTMLExporter and runs Weasyprint to get a PDF."
  },
  {
    "code": "def profile_associated(role_name, profile_name, region, key, keyid, profile):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    try:\n        profiles = conn.list_instance_profiles_for_role(role_name)\n    except boto.exception.BotoServerError as e:\n        log.debug(e)\n        return False\n    profiles = profiles.list_instance_profiles_for_role_response\n    profiles = profiles.list_instance_profiles_for_role_result\n    profiles = profiles.instance_profiles\n    for profile in profiles:\n        if profile.instance_profile_name == profile_name:\n            return True\n    return False",
    "docstring": "Check to see if an instance profile is associated with an IAM role.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_iam.profile_associated myirole myiprofile"
  },
  {
    "code": "def step(step_name=None):\n    def decorator(func):\n        if step_name:\n            name = step_name\n        else:\n            name = func.__name__\n        add_step(name, func)\n        return func\n    return decorator",
    "docstring": "Decorates functions that will be called by the `run` function.\n\n    Decorator version of `add_step`. step name defaults to\n    name of function.\n\n    The function's argument names and keyword argument values\n    will be matched to registered variables when the function\n    needs to be evaluated by Orca.\n    The argument name \"iter_var\" may be used to have the current\n    iteration variable injected."
  },
  {
    "code": "def decode(self, bytes):\n        opcode  = struct.unpack(\">H\", bytes[0:2])[0]\n        nbytes  = struct.unpack(\"B\",  bytes[2:3])[0]\n        name   = None\n        args   = []\n        if opcode in self.opcodes:\n            defn = self.opcodes[opcode]\n            name = defn.name\n            stop = 3\n            for arg in defn.argdefns:\n                start = stop\n                stop  = start + arg.nbytes\n                if arg.fixed:\n                    pass\n                else:\n                    args.append(arg.decode(bytes[start:stop]))\n        return self.create(name, *args)",
    "docstring": "Decodes the given bytes according to this AIT Command\n        Definition."
  },
  {
    "code": "def get_sequence(self,chr=None,start=None,end=None,dir=None,rng=None):\n    if rng: \n      chr = rng.chr\n      start = rng.start\n      end = rng.end\n      dir = rng.direction\n    if not start: start = 1\n    if not end: end = self.fai[chr]['length']\n    if not dir: dir = '+'\n    if dir == '-':\n      return sequence.Sequence.rc(self._seqs[chr][start-1:end])\n    return self._seqs[chr][start-1:end]",
    "docstring": "get a sequence\n\n    :param chr:\n    :param start:\n    :param end:\n    :param dir: charcter +/-\n    :parma rng:\n    :type chr: string\n    :type start: int\n    :type end: int\n    :type dir: char\n    :type rng: GenomicRange\n    :return: sequence \n    :rtype: string"
  },
  {
    "code": "def ask_question(self, question_text, question=None):\n        if question is not None:\n            q = question.to_dict()\n        else:\n            q = WatsonQuestion(question_text).to_dict()\n        r = requests.post(self.url + '/question', json={'question': q}, headers={\n            'Accept': 'application/json',\n            'X-SyncTimeout': 30\n        }, auth=(self.username, self.password))\n        try:\n            response_json = r.json()\n        except ValueError:\n            raise Exception('Failed to parse response JSON')\n        return WatsonAnswer(response_json)",
    "docstring": "Ask Watson a question via the Question and Answer API\n\n        :param question_text: question to ask Watson\n        :type question_text: str\n        :param question: if question_text is not provided, a Question object\n                         representing the question to ask Watson\n        :type question: WatsonQuestion\n        :return: Answer"
  },
  {
    "code": "def validate(self, password, user=None):\n        user_inputs = []\n        if user is not None:\n            for attribute in self.user_attributes:\n                if hasattr(user, attribute):\n                    user_inputs.append(getattr(user, attribute))\n        results = zxcvbn(password, user_inputs=user_inputs)\n        if results.get('score', 0) < self.min_score:\n            feedback = ', '.join(\n                results.get('feedback', {}).get('suggestions', []))\n            raise ValidationError(_(feedback), code=self.code, params={})",
    "docstring": "Validate method, run zxcvbn and check score."
  },
  {
    "code": "def start_consuming(self, to_tuple=False, auto_decode=True):\n        while not self.is_closed:\n            self.process_data_events(\n                to_tuple=to_tuple,\n                auto_decode=auto_decode\n            )\n            if self.consumer_tags:\n                sleep(IDLE_WAIT)\n                continue\n            break",
    "docstring": "Start consuming messages.\n\n        :param bool to_tuple: Should incoming messages be converted to a\n                              tuple before delivery.\n        :param bool auto_decode: Auto-decode strings when possible.\n\n        :raises AMQPChannelError: Raises if the channel encountered an error.\n        :raises AMQPConnectionError: Raises if the connection\n                                     encountered an error.\n\n        :return:"
  },
  {
    "code": "def override_unit(self, unit, parse_strict='raise'):\n        self._unit = parse_unit(unit, parse_strict=parse_strict)",
    "docstring": "Forcefully reset the unit of these data\n\n        Use of this method is discouraged in favour of `to()`,\n        which performs accurate conversions from one unit to another.\n        The method should really only be used when the original unit of the\n        array is plain wrong.\n\n        Parameters\n        ----------\n        unit : `~astropy.units.Unit`, `str`\n            the unit to force onto this array\n        parse_strict : `str`, optional\n            how to handle errors in the unit parsing, default is to\n            raise the underlying exception from `astropy.units`\n\n        Raises\n        ------\n        ValueError\n            if a `str` cannot be parsed as a valid unit"
  },
  {
    "code": "def read_csv(\n    filename: Union[PathLike, Iterator[str]],\n    delimiter: Optional[str]=',',\n    first_column_names: Optional[bool]=None,\n    dtype: str='float32',\n) -> AnnData:\n    return read_text(filename, delimiter, first_column_names, dtype)",
    "docstring": "Read ``.csv`` file.\n\n    Same as :func:`~anndata.read_text` but with default delimiter ``','``.\n\n    Parameters\n    ----------\n    filename\n        Data file.\n    delimiter\n        Delimiter that separates data within text file. If ``None``, will split at\n        arbitrary number of white spaces, which is different from enforcing\n        splitting at single white space ``' '``.\n    first_column_names\n        Assume the first column stores row names.\n    dtype\n        Numpy data type."
  },
  {
    "code": "def layout_json(self):\n        file_fqpn = os.path.join(self.app_path, 'layout.json')\n        if self._layout_json is None:\n            if os.path.isfile(file_fqpn):\n                try:\n                    with open(file_fqpn, 'r') as fh:\n                        self._layout_json = json.load(fh)\n                except ValueError as e:\n                    self.handle_error('Failed to load \"{}\" file ({}).'.format(file_fqpn, e))\n            else:\n                self.handle_error('File \"{}\" could not be found.'.format(file_fqpn))\n        return self._layout_json",
    "docstring": "Return layout.json contents."
  },
  {
    "code": "def traverse_inventory(self, item_filter=None):\n        not self._intentory_raw and self._get_inventory_raw()\n        for item in self._intentory_raw['rgDescriptions'].values():\n            tags = item['tags']\n            for tag in tags:\n                internal_name = tag['internal_name']\n                if item_filter is None or internal_name == item_filter:\n                    item_type = Item\n                    if internal_name == TAG_ITEM_CLASS_CARD:\n                        item_type = Card\n                    appid = item['market_fee_app']\n                    title = item['name']\n                    yield item_type(appid, title)",
    "docstring": "Generates market Item objects for each inventory item.\n\n        :param str item_filter: See `TAG_ITEM_CLASS_` contants from .market module."
  },
  {
    "code": "def encode_date_optional_time(obj):\n    if isinstance(obj, datetime.datetime):\n        return timezone(\"UTC\").normalize(obj.astimezone(timezone(\"UTC\"))).strftime('%Y-%m-%dT%H:%M:%SZ')\n    raise TypeError(\"{0} is not JSON serializable\".format(repr(obj)))",
    "docstring": "ISO encode timezone-aware datetimes"
  },
  {
    "code": "def _data_flow_chain(self):\n        if self.data_producer is None:\n            return []\n        res = []\n        ds = self.data_producer\n        while not ds.is_reader:\n            res.append(ds)\n            ds = ds.data_producer\n        res.append(ds)\n        res = res[::-1]\n        return res",
    "docstring": "Get a list of all elements in the data flow graph.\n        The first element is the original source, the next one reads from the prior and so on and so forth.\n\n        Returns\n        -------\n        list: list of data sources"
  },
  {
    "code": "def _getFullPolicyName(policy_item,\n                       policy_name,\n                       return_full_policy_names,\n                       adml_language):\n    adml_data = _get_policy_resources(language=adml_language)\n    if policy_name in adm_policy_name_map[return_full_policy_names]:\n        return adm_policy_name_map[return_full_policy_names][policy_name]\n    if return_full_policy_names and 'displayName' in policy_item.attrib:\n        fullPolicyName = _getAdmlDisplayName(adml_data, policy_item.attrib['displayName'])\n        if fullPolicyName:\n            adm_policy_name_map[return_full_policy_names][policy_name] = fullPolicyName\n            policy_name = fullPolicyName\n    elif return_full_policy_names and 'id' in policy_item.attrib:\n        fullPolicyName = _getAdmlPresentationRefId(adml_data, policy_item.attrib['id'])\n        if fullPolicyName:\n            adm_policy_name_map[return_full_policy_names][policy_name] = fullPolicyName\n            policy_name = fullPolicyName\n    policy_name = policy_name.rstrip(':').rstrip()\n    return policy_name",
    "docstring": "helper function to retrieve the full policy name if needed"
  },
  {
    "code": "def join(cls, splits, *namables):\n    isplits = []\n    unbound = []\n    for ref in splits:\n      if isinstance(ref, Ref):\n        resolved = False\n        for namable in namables:\n          try:\n            value = namable.find(ref)\n            resolved = True\n            break\n          except Namable.Error:\n            continue\n        if resolved:\n          isplits.append(value)\n        else:\n          isplits.append(ref)\n          unbound.append(ref)\n      else:\n        isplits.append(ref)\n    return (''.join(map(str if Compatibility.PY3 else unicode, isplits)), unbound)",
    "docstring": "Interpolate strings.\n\n      :params splits: The output of Parser.split(string)\n      :params namables: A sequence of Namable objects in which the interpolation should take place.\n\n      Returns 2-tuple containing:\n        joined string, list of unbound object ids (potentially empty)"
  },
  {
    "code": "def mk_dict(results,description):\n    rows=[]\n    for row in results:\n        row_dict={}\n        for idx in range(len(row)):\n            col=description[idx][0]\n            row_dict[col]=row[idx]\n        rows.append(row_dict)\n    return rows",
    "docstring": "Given a result list and descrition sequence, return a list\n    of dictionaries"
  },
  {
    "code": "def avro_name(url):\n    frg = urllib.parse.urldefrag(url)[1]\n    if frg != '':\n        if '/' in frg:\n            return frg[frg.rindex('/') + 1:]\n        return frg\n    return url",
    "docstring": "Turn a URL into an Avro-safe name.\n\n    If the URL has no fragment, return this plain URL.\n\n    Extract either the last part of the URL fragment past the slash, otherwise\n    the whole fragment."
  },
  {
    "code": "def _build_filter_methods(cls, **meths):\n        doc =\n        make_ifilter = lambda ftype: (lambda self, *a, **kw:\n                                      self.ifilter(forcetype=ftype, *a, **kw))\n        make_filter = lambda ftype: (lambda self, *a, **kw:\n                                     self.filter(forcetype=ftype, *a, **kw))\n        for name, ftype in (meths.items() if py3k else meths.iteritems()):\n            ifilter = make_ifilter(ftype)\n            filter = make_filter(ftype)\n            ifilter.__doc__ = doc.format(name, \"ifilter\", ftype)\n            filter.__doc__ = doc.format(name, \"filter\", ftype)\n            setattr(cls, \"ifilter_\" + name, ifilter)\n            setattr(cls, \"filter_\" + name, filter)",
    "docstring": "Given Node types, build the corresponding i?filter shortcuts.\n\n        The should be given as keys storing the method's base name paired with\n        values storing the corresponding :class:`.Node` type. For example, the\n        dict may contain the pair ``(\"templates\", Template)``, which will\n        produce the methods :meth:`ifilter_templates` and\n        :meth:`filter_templates`, which are shortcuts for\n        :meth:`ifilter(forcetype=Template) <ifilter>` and\n        :meth:`filter(forcetype=Template) <filter>`, respectively. These\n        shortcuts are added to the class itself, with an appropriate docstring."
  },
  {
    "code": "def background(cl, proto=EchoProcess, **kw):\n    if isinstance(cl, basestring):\n        cl = shlex.split(cl)\n    if not cl[0].startswith('/'):\n        path = which(cl[0])\n        assert path, '%s not found' % cl[0]\n        cl[0] = path[0]\n    d = Deferred()\n    proc = reactor.spawnProcess(\n            proto(name=basename(cl[0]), deferred=d),\n            cl[0],\n            cl,\n            env=os.environ,\n            **kw)\n    daycare.add(proc.pid)\n    return d",
    "docstring": "Use the reactor to run a process in the background.\n\n    Keep the pid around.\n\n    ``proto'' may be any callable which returns an instance of ProcessProtocol"
  },
  {
    "code": "def write_cert_items(xml_tree, records, api_ver=3, app_id=None, app_ver=None):\n    if not records or not should_include_certs(app_id, app_ver):\n        return\n    certItems = etree.SubElement(xml_tree, 'certItems')\n    for item in records:\n        if item.get('subject') and item.get('pubKeyHash'):\n            cert = etree.SubElement(certItems, 'certItem',\n                                    subject=item['subject'],\n                                    pubKeyHash=item['pubKeyHash'])\n        else:\n            cert = etree.SubElement(certItems, 'certItem',\n                                    issuerName=item['issuerName'])\n            serialNumber = etree.SubElement(cert, 'serialNumber')\n            serialNumber.text = item['serialNumber']",
    "docstring": "Generate the certificate blocklists.\n\n    <certItem issuerName=\"MIGQMQswCQYD...IENB\">\n      <serialNumber>UoRGnb96CUDTxIqVry6LBg==</serialNumber>\n    </certItem>\n\n    or\n\n    <certItem subject='MCIxIDAeBgNVBAMMF0Fub3RoZXIgVGVzdCBFbmQtZW50aXR5'\n              pubKeyHash='VCIlmPM9NkgFQtrs4Oa5TeFcDu6MWRTKSNdePEhOgD8='>\n    </certItem>"
  },
  {
    "code": "def process_formdata(self, valuelist):\n        if valuelist:\n            self.data = '\\n'.join([\n                x.strip() for x in\n                filter(lambda x: x, '\\n'.join(valuelist).splitlines())\n            ])",
    "docstring": "Process form data."
  },
  {
    "code": "def generate_big_urls_glove(bigurls=None):\n    bigurls = bigurls or {}\n    for num_dim in (50, 100, 200, 300):\n        for suffixes, num_words in zip(\n                                       ('sm -sm _sm -small _small'.split(),\n                                        'med -med _med -medium _medium'.split(),\n                                        'lg -lg _lg -large _large'.split()),\n                                       (6, 42, 840)\n                                      ):\n            for suf in suffixes[:-1]:\n                name = 'glove' + suf + str(num_dim)\n                dirname = 'glove.{num_words}B'.format(num_words=num_words)\n                filename = dirname + '.{num_dim}d.w2v.txt'.format(num_dim=num_dim)\n                bigurl_tuple = BIG_URLS['glove' + suffixes[-1]]\n                bigurls[name] =  list(bigurl_tuple[:2])\n                bigurls[name].append(os.path.join(dirname, filename))\n                bigurls[name].append(load_glove)\n                bigurls[name] = tuple(bigurls[name])\n    return bigurls",
    "docstring": "Generate a dictionary of URLs for various combinations of GloVe training set sizes and dimensionality"
  },
  {
    "code": "def normpath(path):\n    normalized = os.path.join(*path.split(\"/\"))\n    if os.path.isabs(path):\n        return os.path.abspath(\"/\") + normalized\n    else:\n        return normalized",
    "docstring": "Normalize UNIX path to a native path."
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'key' in _dict:\n            args['key'] = Key._from_dict(_dict.get('key'))\n        if 'value' in _dict:\n            args['value'] = Value._from_dict(_dict.get('value'))\n        return cls(**args)",
    "docstring": "Initialize a KeyValuePair object from a json dictionary."
  },
  {
    "code": "def addError(self, test, exception):\n        result = self._handle_result(\n            test, TestCompletionStatus.error, exception=exception)\n        self.errors.append(result)\n        self._mirror_output = True",
    "docstring": "Register that a test ended in an error.\n\n        Parameters\n        ----------\n        test : unittest.TestCase\n            The test that has completed.\n        exception : tuple\n            ``exc_info`` tuple ``(type, value, traceback)``."
  },
  {
    "code": "def join(self, timeout=None):\n        remaining = timeout\n        while self._cb_poll and (remaining is None or remaining > 0):\n            now = time.time()\n            rv = self._cb_poll.poll(remaining)\n            if remaining is not None:\n                remaining -= (time.time() - now)\n            for command_buffer, event in rv:\n                if command_buffer.has_pending_requests:\n                    if event == 'close':\n                        self._try_reconnect(command_buffer)\n                    elif event == 'write':\n                        self._send_or_reconnect(command_buffer)\n                elif event in ('read', 'close'):\n                    try:\n                        command_buffer.wait_for_responses(self)\n                    finally:\n                        self._release_command_buffer(command_buffer)\n        if self._cb_poll and timeout is not None:\n            raise TimeoutError('Did not receive all data in time.')",
    "docstring": "Waits for all outstanding responses to come back or the timeout\n        to be hit."
  },
  {
    "code": "def tobinary(self):\n        entrylen = struct.calcsize(self.ENTRYSTRUCT)\n        rslt = []\n        for (dpos, dlen, ulen, flag, typcd, nm) in self.data:\n            nmlen = len(nm) + 1\n            toclen = nmlen + entrylen\n            if toclen % 16 == 0:\n                pad = '\\0'\n            else:\n                padlen = 16 - (toclen % 16)\n                pad = '\\0'*padlen\n                nmlen = nmlen + padlen\n            rslt.append(struct.pack(self.ENTRYSTRUCT+`nmlen`+'s',\n                            nmlen+entrylen, dpos, dlen, ulen, flag, typcd, nm+pad))\n        return ''.join(rslt)",
    "docstring": "Return self as a binary string."
  },
  {
    "code": "def lux_unit(self):\n        if CONST.UNIT_LUX in self._get_status(CONST.LUX_STATUS_KEY):\n            return CONST.LUX\n        return None",
    "docstring": "Get unit of lux."
  },
  {
    "code": "def convert_crop(node, **kwargs):\n    name, inputs, attrs = get_inputs(node, kwargs)\n    num_inputs = len(inputs)\n    y, x = list(parse_helper(attrs, \"offset\", [0, 0]))\n    h, w = list(parse_helper(attrs, \"h_w\", [0, 0]))\n    if num_inputs > 1:\n        h, w = kwargs[\"out_shape\"][-2:]\n    border = [x, y, x + w, y + h]\n    crop_node = onnx.helper.make_node(\n        \"Crop\",\n        inputs=[inputs[0]],\n        outputs=[name],\n        border=border,\n        scale=[1, 1],\n        name=name\n    )\n    logging.warning(\n        \"Using an experimental ONNX operator: Crop. \" \\\n        \"Its definition can change.\")\n    return [crop_node]",
    "docstring": "Map MXNet's crop operator attributes to onnx's Crop operator\n    and return the created node."
  },
  {
    "code": "def info(dev):\n    if 'sys' in dev:\n        qtype = 'path'\n    else:\n        qtype = 'name'\n    cmd = 'udevadm info --export --query=all --{0}={1}'.format(qtype, dev)\n    udev_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')\n    if udev_result['retcode'] != 0:\n        raise CommandExecutionError(udev_result['stderr'])\n    return _parse_udevadm_info(udev_result['stdout'])[0]",
    "docstring": "Extract all info delivered by udevadm\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' udev.info /dev/sda\n        salt '*' udev.info /sys/class/net/eth0"
  },
  {
    "code": "def flat_map(self, flatmap_fn):\n        op = Operator(\n            _generate_uuid(),\n            OpType.FlatMap,\n            \"FlatMap\",\n            flatmap_fn,\n            num_instances=self.env.config.parallelism)\n        return self.__register(op)",
    "docstring": "Applies a flatmap operator to the stream.\n\n        Attributes:\n             flatmap_fn (function): The user-defined logic of the flatmap\n             (e.g. split())."
  },
  {
    "code": "def merge(self, *args):\n        values = []\n        for entry in args:\n            values = values + list(entry.items())\n        return dict(values)",
    "docstring": "Merge multiple dictionary objects into one.\n\n        :param variadic args: Multiple dictionary items\n\n        :return dict"
  },
  {
    "code": "def and_return_future(self, *return_values):\n        futures = []\n        for value in return_values:\n            future = _get_future()\n            future.set_result(value)\n            futures.append(future)\n        return self.and_return(*futures)",
    "docstring": "Similar to `and_return` but the doubled method returns a future.\n\n        :param object return_values: The values the double will return when called,"
  },
  {
    "code": "def _get_data(self, url, accept=None):\n        if self.parsed_endpoint.scheme == 'https':\n            conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc)\n        else:\n            conn = httplib.HTTPConnection(self.parsed_endpoint.netloc)\n        head = {\n            \"User-Agent\": USER_AGENT,\n            API_TOKEN_HEADER_NAME: self.api_token,\n        }\n        if self.api_version in ['0.1', '0.01a']:\n            head[API_VERSION_HEADER_NAME] = self.api_version\n        if accept:\n            head['Accept'] = accept\n        conn.request(\"GET\", url, \"\", head)\n        resp = conn.getresponse()\n        self._handle_response_errors('GET', url, resp)\n        content_type = resp.getheader('content-type')\n        if 'application/json' in content_type:\n            return json.loads(resp.read())\n        return resp.read()",
    "docstring": "GETs the resource at url and returns the raw response\n        If the accept parameter is not None, the request passes is as the Accept header"
  },
  {
    "code": "def Close(self):\n    if not self._connection:\n      raise RuntimeError('Cannot close database not opened.')\n    self._connection.commit()\n    self._connection.close()\n    self._connection = None\n    self._cursor = None\n    self.filename = None\n    self.read_only = None",
    "docstring": "Closes the database file.\n\n    Raises:\n      RuntimeError: if the database is not opened."
  },
  {
    "code": "def build_acl(self, tenant_name, rule):\n        if rule['action'] == 'allow':\n            action = 'permit'\n        else:\n            action = 'deny'\n        acl_str = \"access-list %(tenant)s extended %(action)s %(prot)s \"\n        acl = acl_str % {'tenant': tenant_name, 'action': action,\n                         'prot': rule.get('protocol')}\n        src_ip = self.get_ip_address(rule.get('source_ip_address'))\n        ip_acl = self.build_acl_ip(src_ip)\n        acl += ip_acl\n        acl += self.build_acl_port(rule.get('source_port'))\n        dst_ip = self.get_ip_address(rule.get('destination_ip_address'))\n        ip_acl = self.build_acl_ip(dst_ip)\n        acl += ip_acl\n        acl += self.build_acl_port(rule.get('destination_port'),\n                                   enabled=rule.get('enabled'))\n        return acl",
    "docstring": "Build the ACL."
  },
  {
    "code": "def get_task_summary(self, task_name):\n        params = {'instancesummary': '', 'taskname': task_name}\n        resp = self._client.get(self.resource(), params=params)\n        map_reduce = resp.json().get('Instance')\n        if map_reduce:\n            json_summary = map_reduce.get('JsonSummary')\n            if json_summary:\n                summary = Instance.TaskSummary(json.loads(json_summary))\n                summary.summary_text = map_reduce.get('Summary')\n                summary.json_summary = json_summary\n                return summary",
    "docstring": "Get a task's summary, mostly used for MapReduce.\n\n        :param task_name: task name\n        :return: summary as a dict parsed from JSON\n        :rtype: dict"
  },
  {
    "code": "def log_rule_info(self):\n        for c in sorted(self.broker.get_by_type(rule), key=dr.get_name):\n            v = self.broker[c]\n            _type = v.get(\"type\")\n            if _type:\n                if _type != \"skip\":\n                    msg = \"Running {0} \".format(dr.get_name(c))\n                    self.logit(msg, self.pid, self.user, \"insights-run\", logging.INFO)\n                else:\n                    msg = \"Rule skipped {0} \".format(dr.get_name(c))\n                    self.logit(msg, self.pid, self.user, \"insights-run\", logging.WARNING)",
    "docstring": "Collects rule information and send to logit function to log to syslog"
  },
  {
    "code": "def readPlist(pathOrFile):\n    didOpen = False\n    result = None\n    if isinstance(pathOrFile, (bytes, unicode)):\n        pathOrFile = open(pathOrFile, 'rb')\n        didOpen = True\n    try:\n        reader = PlistReader(pathOrFile)\n        result = reader.parse()\n    except NotBinaryPlistException as e:\n        try:\n            pathOrFile.seek(0)\n            result = None\n            if hasattr(plistlib, 'loads'):\n                contents = None\n                if isinstance(pathOrFile, (bytes, unicode)):\n                    with open(pathOrFile, 'rb') as f:\n                        contents = f.read()\n                else:\n                    contents = pathOrFile.read()\n                result = plistlib.loads(contents)\n            else:\n                result = plistlib.readPlist(pathOrFile)\n            result = wrapDataObject(result, for_binary=True)\n        except Exception as e:\n            raise InvalidPlistException(e)\n    finally:\n        if didOpen:\n            pathOrFile.close()\n    return result",
    "docstring": "Raises NotBinaryPlistException, InvalidPlistException"
  },
  {
    "code": "def add_tagfile(self, path, timestamp=None):\n        self.self_check()\n        checksums = {}\n        if os.path.isdir(path):\n            return\n        with open(path, \"rb\") as tag_file:\n            checksums[SHA1] = checksum_copy(tag_file, hasher=hashlib.sha1)\n            tag_file.seek(0)\n            checksums[SHA256] = checksum_copy(tag_file, hasher=hashlib.sha256)\n            tag_file.seek(0)\n            checksums[SHA512] = checksum_copy(tag_file, hasher=hashlib.sha512)\n        rel_path = _posix_path(os.path.relpath(path, self.folder))\n        self.tagfiles.add(rel_path)\n        self.add_to_manifest(rel_path, checksums)\n        if timestamp is not None:\n            self._file_provenance[rel_path] = {\"createdOn\": timestamp.isoformat()}",
    "docstring": "Add tag files to our research object."
  },
  {
    "code": "def create_or_update_export_configuration(self, export_config):\n        search_string = json.dumps(obj=export_config.search.as_dict())\n        user_id = export_config.user_id\n        password = export_config.password\n        target_url = export_config.target_url\n        enabled = export_config.enabled\n        name = export_config.name\n        description = export_config.description\n        export_type = export_config.type\n        if export_config.config_id is not None:\n            self.con.execute(\n                    'UPDATE archive_exportConfig c '\n                    'SET c.searchString = %s, c.targetUrl = %s, c.targetUser = %s, c.targetPassword = %s, '\n                    'c.exportName = %s, c.description = %s, c.active = %s, c.exportType = %s '\n                    'WHERE c.exportConfigId = %s',\n                    (search_string, target_url, user_id, password, name, description, enabled, export_type,\n                     export_config.config_id))\n        else:\n            item_id = mp.get_hash(mp.now(), name, export_type)\n            self.con.execute(\n                    'INSERT INTO archive_exportConfig '\n                    '(searchString, targetUrl, targetUser, targetPassword, '\n                    'exportName, description, active, exportType, exportConfigId) '\n                    'VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s) ',\n                    (search_string, target_url, user_id, password,\n                     name, description, enabled, export_type, item_id))\n            export_config.config_id = item_id\n        return export_config",
    "docstring": "Create a new file export configuration or update an existing one\n\n        :param ExportConfiguration export_config:\n            a :class:`meteorpi_model.ExportConfiguration` containing the specification for the export. If this\n            doesn't include a 'config_id' field it will be inserted as a new record in the database and the field will\n            be populated, updating the supplied object. If it does exist already this will update the other properties\n            in the database to match the supplied object.\n        :returns:\n            The supplied :class:`meteorpi_model.ExportConfiguration` as stored in the DB. This is guaranteed to have\n            its 'config_id' string field defined."
  },
  {
    "code": "def segment(f, output, target_duration, mpegts):\n    try:\n        target_duration = int(target_duration)\n    except ValueError:\n        exit('Error: Invalid target duration.')\n    try:\n        mpegts = int(mpegts)\n    except ValueError:\n        exit('Error: Invalid MPEGTS value.')\n    WebVTTSegmenter().segment(f, output, target_duration, mpegts)",
    "docstring": "Segment command."
  },
  {
    "code": "def content(self):\n        if not self._content:\n            self._content = self._read()\n        return self._content",
    "docstring": "Get the file contents.\n\n        This property is cached. The file is only read once."
  },
  {
    "code": "def unmapped(name,\n             config='/etc/crypttab',\n             persist=True,\n             immediate=False):\n    ret = {'name': name,\n           'changes': {},\n           'result': True,\n           'comment': ''}\n    if immediate:\n        active = __salt__['cryptdev.active']()\n        if name in active.keys():\n            if __opts__['test']:\n                ret['result'] = None\n                ret['commment'] = 'Device would be unmapped immediately'\n            else:\n                cryptsetup_result = __salt__['cryptdev.close'](name)\n                if cryptsetup_result:\n                    ret['changes']['cryptsetup'] = 'Device unmapped using cryptsetup'\n                else:\n                    ret['changes']['cryptsetup'] = 'Device failed to unmap using cryptsetup'\n                    ret['result'] = False\n    if persist and not __opts__['test']:\n        crypttab_result = __salt__['cryptdev.rm_crypttab'](name, config=config)\n        if crypttab_result:\n            if crypttab_result == 'change':\n                ret['changes']['crypttab'] = 'Entry removed from {0}'.format(config)\n        else:\n            ret['changes']['crypttab'] = 'Unable to remove entry in {0}'.format(config)\n            ret['result'] = False\n    return ret",
    "docstring": "Ensure that a device is unmapped\n\n    name\n        The name to ensure is not mapped\n\n    config\n        Set an alternative location for the crypttab, if the map is persistent,\n        Default is ``/etc/crypttab``\n\n    persist\n        Set if the map should be removed from the crypttab. Default is ``True``\n\n    immediate\n        Set if the device should be unmapped immediately. Default is ``False``."
  },
  {
    "code": "def publish_gsi_notification(\n        table_key, gsi_key, message, message_types, subject=None):\n    topic = get_gsi_option(table_key, gsi_key, 'sns_topic_arn')\n    if not topic:\n        return\n    for message_type in message_types:\n        if (message_type in\n                get_gsi_option(table_key, gsi_key, 'sns_message_types')):\n            __publish(topic, message, subject)\n            return",
    "docstring": "Publish a notification for a specific GSI\n\n    :type table_key: str\n    :param table_key: Table configuration option key name\n    :type gsi_key: str\n    :param gsi_key: Table configuration option key name\n    :type message: str\n    :param message: Message to send via SNS\n    :type message_types: list\n    :param message_types:\n        List with types:\n        - scale-up\n        - scale-down\n        - high-throughput-alarm\n        - low-throughput-alarm\n    :type subject: str\n    :param subject: Subject to use for e-mail notifications\n    :returns: None"
  },
  {
    "code": "def get_log_hierarchy_session(self, proxy):\n        if not self.supports_log_hierarchy():\n            raise errors.Unimplemented()\n        return sessions.LogHierarchySession(proxy=proxy, runtime=self._runtime)",
    "docstring": "Gets the ``OsidSession`` associated with the log hierarchy service.\n\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.logging.LogHierarchySession) - a\n                ``LogHierarchySession`` for logs\n        raise:  NullArgument - ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_log_hierarchy()`` is\n                ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_log_hierarchy()`` is ``true``.*"
  },
  {
    "code": "def bulk_copy(self, ids):\n        schema = self.GET_SCHEMA\n        return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)",
    "docstring": "Bulk copy a set of configs.\n\n        :param ids: Int list of config IDs.\n        :return: :class:`configs.Config <configs.Config>` list"
  },
  {
    "code": "def readMixedArray(self):\n        self.stream.read_ulong()\n        obj = pyamf.MixedArray()\n        self.context.addObject(obj)\n        attrs = self.readObjectAttributes(obj)\n        for key in attrs.keys():\n            try:\n                key = int(key)\n            except ValueError:\n                pass\n            obj[key] = attrs[key]\n        return obj",
    "docstring": "Read mixed array.\n\n        @rtype: L{pyamf.MixedArray}"
  },
  {
    "code": "def get_table_names(self, connection, schema=None, **kw):\n        return self._get_table_or_view_names('r', connection, schema, **kw)",
    "docstring": "Return a list of table names for `schema`.\n\n        Overrides interface\n        :meth:`~sqlalchemy.engine.interfaces.Dialect.get_table_names`."
  },
  {
    "code": "def load_user_config(args, log):\n    if not os.path.exists(_CONFIG_PATH):\n        err_str = (\n            \"Configuration file does not exists ({}).\\n\".format(_CONFIG_PATH) +\n            \"Run `python -m astrocats setup` to configure.\")\n        log_raise(log, err_str)\n    config = json.load(open(_CONFIG_PATH, 'r'))\n    setattr(args, _BASE_PATH_KEY, config[_BASE_PATH_KEY])\n    log.debug(\"Loaded configuration: {}: {}\".format(_BASE_PATH_KEY, config[\n        _BASE_PATH_KEY]))\n    return args",
    "docstring": "Load settings from the user's confiuration file, and add them to `args`.\n\n    Settings are loaded from the configuration file in the user's home\n    directory.  Those parameters are added (as attributes) to the `args`\n    object.\n\n    Arguments\n    ---------\n    args : `argparse.Namespace`\n        Namespace object to which configuration attributes will be added.\n\n    Returns\n    -------\n    args : `argparse.Namespace`\n        Namespace object with added attributes."
  },
  {
    "code": "def change_password(self, username, newpassword, raise_on_error=False):\n        response = self._put(self.rest_url + \"/user/password\",\n                             data=json.dumps({\"value\": newpassword}),\n                             params={\"username\": username})\n        if response.ok:\n            return True\n        if raise_on_error:\n            raise RuntimeError(response.json()['message'])\n        return False",
    "docstring": "Change new password for a user\n\n        Args:\n            username: The account username.\n\n            newpassword: The account new password.\n\n            raise_on_error: optional (default: False)\n\n        Returns:\n            True: Succeeded\n            False: If unsuccessful"
  },
  {
    "code": "def set_system_lock(cls, redis, name, timeout):\n        pipeline = redis.pipeline()\n        pipeline.zadd(name, SYSTEM_LOCK_ID, time.time() + timeout)\n        pipeline.expire(name, timeout + 10)\n        pipeline.execute()",
    "docstring": "Set system lock for the semaphore.\n\n        Sets a system lock that will expire in timeout seconds. This\n        overrides all other locks. Existing locks cannot be renewed\n        and no new locks will be permitted until the system lock\n        expires.\n\n        Arguments:\n            redis: Redis client\n            name: Name of lock. Used as ZSET key.\n            timeout: Timeout in seconds for system lock"
  },
  {
    "code": "def _send_output(self, message_body=None):\n        self._buffer.extend((bytes(b\"\"), bytes(b\"\")))\n        msg = bytes(b\"\\r\\n\").join(self._buffer)\n        del self._buffer[:]\n        if isinstance(message_body, bytes):\n            msg += message_body\n            message_body = None\n        self.send(msg)\n        if message_body is not None:\n            self.send(message_body)",
    "docstring": "Send the currently buffered request and clear the buffer.\n\n        Appends an extra \\\\r\\\\n to the buffer.\n        A message_body may be specified, to be appended to the request."
  },
  {
    "code": "def maybeDeferred(f, *args, **kw):\n    try:\n        result = f(*args, **kw)\n    except Exception:\n        return fail(failure.Failure())\n    if IFiber.providedBy(result):\n        import traceback\n        frames = traceback.extract_stack()\n        msg = \"%s returned a fiber instead of a deferred\" % (f, )\n        if len(frames) > 1:\n            msg += \"; called from %s\" % (frames[-2], )\n        raise RuntimeError(msg)\n    if isinstance(result, Deferred):\n        return result\n    elif isinstance(result, failure.Failure):\n        return fail(result)\n    else:\n        return succeed(result)",
    "docstring": "Copied from twsited.internet.defer and add a check to detect fibers."
  },
  {
    "code": "def update_ddl(self, ddl_statements, operation_id=\"\"):\n        client = self._instance._client\n        api = client.database_admin_api\n        metadata = _metadata_with_prefix(self.name)\n        future = api.update_database_ddl(\n            self.name, ddl_statements, operation_id=operation_id, metadata=metadata\n        )\n        return future",
    "docstring": "Update DDL for this database.\n\n        Apply any configured schema from :attr:`ddl_statements`.\n\n        See\n        https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabase\n\n        :type ddl_statements: Sequence[str]\n        :param ddl_statements: a list of DDL statements to use on this database\n        :type operation_id: str\n        :param operation_id: (optional) a string ID for the long-running operation\n\n        :rtype: :class:`google.api_core.operation.Operation`\n        :returns: an operation instance\n        :raises NotFound: if the database does not exist"
  },
  {
    "code": "def fail_api(channel):\n    gui = ui_embed.UI(\n        channel,\n        \"Couldn't get stats off RLTrackerNetwork.\",\n        \"Maybe the API changed, please tell Infraxion.\",\n        modulename=modulename,\n        colour=0x0088FF\n    )\n    return gui",
    "docstring": "Creates an embed UI for when the API call didn't work\n\n    Args:\n        channel (discord.Channel): The Discord channel to bind the embed to\n\n    Returns:\n        ui (ui_embed.UI): The embed UI object"
  },
  {
    "code": "def filtered(self):\n        if not is_tagged(self.tags, self.opt.tags):\n            LOG.info(\"Skipping %s as it does not have requested tags\",\n                     self.path)\n            return False\n        if not specific_path_check(self.path, self.opt):\n            LOG.info(\"Skipping %s as it does not match specified paths\",\n                     self.path)\n            return False\n        return True",
    "docstring": "Determines whether or not resource is filtered.\n        Resources may be filtered if the tags do not match\n        or the user has specified explict paths to include\n        or exclude via command line options"
  },
  {
    "code": "def get_job_ids(self):\n        if not self.parsed_response:\n            return None\n        try:\n            job_ids = self.parsed_response[\"files\"][\"results.xml\"][\"job-ids\"]\n        except KeyError:\n            return None\n        if not job_ids or job_ids == [0]:\n            return None\n        return job_ids",
    "docstring": "Returns job IDs of the import."
  },
  {
    "code": "def within(self, key, include_self=True, exclusive=False, biggest_first=True, only=None):\n        possibles = self.topology if only is None else {k: self[k] for k in only}\n        _ = lambda key: [key] if key in possibles else []\n        if 'RoW' not in self and key == 'RoW':\n            answer = [] + _('RoW') + _('GLO')\n            return list(reversed(answer)) if biggest_first else answer\n        faces = self[key]\n        lst = [\n            (k, len(v))\n            for k, v in possibles.items()\n            if faces.issubset(v)\n        ]\n        return self._finish_filter(lst, key, include_self, exclusive, biggest_first)",
    "docstring": "Get all locations that completely contain this location.\n\n        If the ``resolved_row`` context manager is not used, ``RoW`` doesn't have a spatial definition. Therefore, ``RoW`` can only be contained by ``GLO`` and ``RoW``."
  },
  {
    "code": "def do_resource(self,args):\n        parser = CommandArgumentParser(\"resource\")\n        parser.add_argument('-i','--logical-id',dest='logical-id',help='logical id of the child resource');\n        args = vars(parser.parse_args(args))\n        stackName = self.wrappedStack['rawStack'].name\n        logicalId = args['logical-id']\n        self.stackResource(stackName,logicalId)",
    "docstring": "Go to the specified resource. resource -h for detailed help"
  },
  {
    "code": "def curse_add_line(self, msg, decoration=\"DEFAULT\",\n                       optional=False, additional=False,\n                       splittable=False):\n        return {'msg': msg, 'decoration': decoration, 'optional': optional, 'additional': additional, 'splittable': splittable}",
    "docstring": "Return a dict with.\n\n        Where:\n            msg: string\n            decoration:\n                DEFAULT: no decoration\n                UNDERLINE: underline\n                BOLD: bold\n                TITLE: for stat title\n                PROCESS: for process name\n                STATUS: for process status\n                NICE: for process niceness\n                CPU_TIME: for process cpu time\n                OK: Value is OK and non logged\n                OK_LOG: Value is OK and logged\n                CAREFUL: Value is CAREFUL and non logged\n                CAREFUL_LOG: Value is CAREFUL and logged\n                WARNING: Value is WARINING and non logged\n                WARNING_LOG: Value is WARINING and logged\n                CRITICAL: Value is CRITICAL and non logged\n                CRITICAL_LOG: Value is CRITICAL and logged\n            optional: True if the stat is optional (display only if space is available)\n            additional: True if the stat is additional (display only if space is available after optional)\n            spittable: Line can be splitted to fit on the screen (default is not)"
  },
  {
    "code": "def login(self) -> bool:\n        response = self.get(self.LOGIN_URL)\n        login_url = get_base_url(response.text)\n        login_data = {'email': self._login, 'pass': self._password}\n        login_response = self.post(login_url, login_data)\n        url_params = get_url_params(login_response.url)\n        self.check_for_additional_actions(url_params,\n                                          login_response.text,\n                                          login_data)\n        if 'remixsid' in self.cookies or 'remixsid6' in self.cookies:\n            return True",
    "docstring": "Authorizes a user and returns a bool value of the result"
  },
  {
    "code": "def load_completions(self):\n        try:\n            index_str = self.load_index(utils.AWSCLI_VERSION)\n        except IndexLoadError:\n            return\n        index_str = self.load_index(utils.AWSCLI_VERSION)\n        index_data = json.loads(index_str)\n        index_root = index_data['aws']\n        self.commands = index_root['commands']\n        self.global_opts = index_root['arguments']\n        for command in self.commands:\n            subcommands_current = index_root['children'] \\\n                .get(command)['commands']\n            self.subcommands.extend(subcommands_current)\n            for subcommand_current in subcommands_current:\n                args_opts_current = index_root['children'] \\\n                    .get(command)['children'] \\\n                    .get(subcommand_current)['arguments']\n                self.args_opts.update(args_opts_current)",
    "docstring": "Load completions from the completion index.\n\n        Updates the following attributes:\n            * commands\n            * subcommands\n            * global_opts\n            * args_opts"
  },
  {
    "code": "def tweet_list_handler(request, tweet_list_builder, msg_prefix=\"\"):\n    tweets = tweet_list_builder(request.access_token())\n    print (len(tweets), 'tweets found')\n    if tweets:\n        twitter_cache.initialize_user_queue(user_id=request.access_token(),\n                                            queue=tweets)\n        text_to_read_out = twitter_cache.user_queue(request.access_token()).read_out_next(MAX_RESPONSE_TWEETS)        \n        message = msg_prefix + text_to_read_out + \", say 'next' to hear more, or reply to a tweet by number.\"\n        return alexa.create_response(message=message,\n                                     end_session=False)\n    else:\n        return alexa.create_response(message=\"Sorry, no tweets found, please try something else\", \n                                 end_session=False)",
    "docstring": "This is a generic function to handle any intent that reads out a list of tweets"
  },
  {
    "code": "async def get_supported_playback_functions(\n        self, uri=\"\"\n    ) -> List[SupportedFunctions]:\n        return [\n            SupportedFunctions.make(**x)\n            for x in await self.services[\"avContent\"][\"getSupportedPlaybackFunction\"](\n                uri=uri\n            )\n        ]",
    "docstring": "Return list of inputs and their supported functions."
  },
  {
    "code": "def print_event_count():\n    for source in archive.list_event_sources():\n        event_count = 0\n        for group in archive.list_event_histogram(source):\n            for rec in group.records:\n                event_count += rec.count\n        print('  {: <40} {: >20}'.format(source, event_count))",
    "docstring": "Print the number of events grouped by source."
  },
  {
    "code": "def is_generator(self, node):\n        if not isinstance(node.body, list):\n            return False\n        for item in node.body:\n            if isinstance(item, (ast.Assign, ast.Expr)):\n                if isinstance(item.value, ast.Yield):\n                    return True\n            elif not isinstance(item, ast.FunctionDef) and hasattr(item, 'body'):\n                if self.is_generator(item):\n                    return True\n        return False",
    "docstring": "Checks whether a function is a generator by looking for a yield\n        statement or expression."
  },
  {
    "code": "def tokenize_text(string):\n    string = six.text_type(string)\n    rez = []\n    for part in string.split('\\n'):\n        par = []\n        for sent in tokenize_sents(part):\n            par.append(tokenize_words(sent))\n        if par:\n            rez.append(par)\n    return rez",
    "docstring": "Tokenize input text to paragraphs, sentences and words.\n\n    Tokenization to paragraphs is done using simple Newline algorithm\n    For sentences and words tokenizers above are used\n\n    :param string: Text to tokenize\n    :type string: str or unicode\n    :return: text, tokenized into paragraphs, sentences and words\n    :rtype: list of list of list of words"
  },
  {
    "code": "def set_sound_mode(self, sound_mode):\n        if sound_mode == ALL_ZONE_STEREO:\n            if self._set_all_zone_stereo(True):\n                self._sound_mode_raw = ALL_ZONE_STEREO\n                return True\n            else:\n                return False\n        if self._sound_mode_raw == ALL_ZONE_STEREO:\n            if not self._set_all_zone_stereo(False):\n                return False\n        command_url = self._urls.command_sel_sound_mode + sound_mode\n        try:\n            if self.send_get_command(command_url):\n                self._sound_mode_raw = self._sound_mode_dict[sound_mode][0]\n                return True\n            else:\n                return False\n        except requests.exceptions.RequestException:\n            _LOGGER.error(\"Connection error: sound mode function %s not set.\",\n                          sound_mode)\n            return False",
    "docstring": "Set sound_mode of device.\n\n        Valid values depend on the device and should be taken from\n        \"sound_mode_list\".\n        Return \"True\" on success and \"False\" on fail."
  },
  {
    "code": "def i2c_read_data(self, address):\n        task = asyncio.ensure_future(self.core.i2c_read_data(address))\n        value = self.loop.run_until_complete(task)\n        return value",
    "docstring": "Retrieve result of last data read from i2c device.\n        i2c_read_request should be called before trying to retrieve data.\n        It is intended for use by a polling application.\n\n        :param address: i2c\n\n        :returns: last data read or None if no data is present."
  },
  {
    "code": "def operates_on(self, qubits: Iterable[raw_types.Qid]) -> bool:\n        return any(q in qubits for q in self.qubits)",
    "docstring": "Determines if the moment has operations touching the given qubits.\n\n        Args:\n            qubits: The qubits that may or may not be touched by operations.\n\n        Returns:\n            Whether this moment has operations involving the qubits."
  },
  {
    "code": "def sudo(self, command, **kwargs):\n        runner = self.config.runners.remote(self)\n        return self._sudo(runner, command, **kwargs)",
    "docstring": "Execute a shell command, via ``sudo``, on the remote end.\n\n        This method is identical to `invoke.context.Context.sudo` in every way,\n        except in that -- like `run` -- it honors per-host/per-connection\n        configuration overrides in addition to the generic/global ones. Thus,\n        for example, per-host sudo passwords may be configured.\n\n        .. versionadded:: 2.0"
  },
  {
    "code": "def fmt_val(val, shorten=True):\n    val = repr(val)\n    max = 50\n    if shorten:\n        if len(val) > max:\n            close = val[-1]\n            val = val[0:max-4] + \"...\"\n            if close in (\">\", \"'\", '\"', ']', '}', ')'):\n                val = val + close\n    return val",
    "docstring": "Format a value for inclusion in an \n    informative text string."
  },
  {
    "code": "def add_list_opt(self, opt, values):\n        self.add_opt(opt)\n        for val in values:\n            self.add_opt(val)",
    "docstring": "Add an option with a list of non-file parameters."
  },
  {
    "code": "def _standard_params(klass, ids, metric_groups, **kwargs):\n        end_time = kwargs.get('end_time', datetime.utcnow())\n        start_time = kwargs.get('start_time', end_time - timedelta(seconds=604800))\n        granularity = kwargs.get('granularity', GRANULARITY.HOUR)\n        placement = kwargs.get('placement', PLACEMENT.ALL_ON_TWITTER)\n        params = {\n            'metric_groups': ','.join(metric_groups),\n            'start_time': to_time(start_time, granularity),\n            'end_time': to_time(end_time, granularity),\n            'granularity': granularity.upper(),\n            'entity': klass.ANALYTICS_MAP[klass.__name__],\n            'placement': placement\n        }\n        params['entity_ids'] = ','.join(ids)\n        return params",
    "docstring": "Sets the standard params for a stats request"
  },
  {
    "code": "def derivative(self, point):\n        if self.pad_mode == 'constant' and self.pad_const != 0:\n            return ResizingOperator(\n                domain=self.domain, range=self.range, pad_mode='constant',\n                pad_const=0.0)\n        else:\n            return self",
    "docstring": "Derivative of this operator at ``point``.\n\n        For the particular case of constant padding with non-zero\n        constant, the derivative is the corresponding zero-padding\n        variant. In all other cases, this operator is linear, i.e.\n        the derivative is equal to ``self``."
  },
  {
    "code": "def score_segmentation(segmentation, table):\n    stroke_nr = sum(1 for symbol in segmentation for stroke in symbol)\n    score = 1\n    for i in range(stroke_nr):\n        for j in range(i+1, stroke_nr):\n            qval = q(segmentation, i, j)\n            if qval:\n                score *= table[i][j]\n            else:\n                score *= table[j][i]\n    return score",
    "docstring": "Get the score of a segmentation."
  },
  {
    "code": "def add_css_class(css_classes, css_class, prepend=False):\n    classes_list = split_css_classes(css_classes)\n    classes_to_add = [c for c in split_css_classes(css_class) if c not in classes_list]\n    if prepend:\n        classes_list = classes_to_add + classes_list\n    else:\n        classes_list += classes_to_add\n    return \" \".join(classes_list)",
    "docstring": "Add a CSS class to a string of CSS classes"
  },
  {
    "code": "def format_datetime(dt, usegmt=False):\n    now = dt.timetuple()\n    if usegmt:\n        if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc:\n            raise ValueError(\"usegmt option requires a UTC datetime\")\n        zone = 'GMT'\n    elif dt.tzinfo is None:\n        zone = '-0000'\n    else:\n        zone = dt.strftime(\"%z\")\n    return _format_timetuple_and_zone(now, zone)",
    "docstring": "Turn a datetime into a date string as specified in RFC 2822.\n\n    If usegmt is True, dt must be an aware datetime with an offset of zero.  In\n    this case 'GMT' will be rendered instead of the normal +0000 required by\n    RFC2822.  This is to support HTTP headers involving date stamps."
  },
  {
    "code": "def _instantiate_players(self, player_dict):\n        home_players = []\n        away_players = []\n        for player_id, details in player_dict.items():\n            player = BoxscorePlayer(player_id,\n                                    details['name'],\n                                    details['data'])\n            if details['team'] == HOME:\n                home_players.append(player)\n            else:\n                away_players.append(player)\n        return away_players, home_players",
    "docstring": "Create a list of player instances for both the home and away teams.\n\n        For every player listed on the boxscores page, create an instance of\n        the BoxscorePlayer class for that player and add them to a list of\n        players for their respective team.\n\n        Parameters\n        ----------\n        player_dict : dictionary\n            A dictionary containing information for every player on the\n            boxscores page. Each key is a string containing the player's ID\n            and each value is a dictionary with the player's full name, a\n            string representation of their HTML stats, and a string constant\n            denoting which team they play for as the values.\n\n        Returns\n        -------\n        tuple\n            Returns a ``tuple`` in the format (away_players, home_players)\n            where each element is a list of player instances for the away and\n            home teams, respectively."
  },
  {
    "code": "def attach_session(self):\n        assert self.session is None\n        root = self.find_root()\n        session = self.Session(root)\n        root.inject_context(session=session)\n        return session",
    "docstring": "Create a session and inject it as context for this command and any\n        subcommands."
  },
  {
    "code": "def _get_api_events(self, function):\n        if not (function.valid() and\n                isinstance(function.properties, dict) and\n                isinstance(function.properties.get(\"Events\"), dict)\n                ):\n            return {}\n        api_events = {}\n        for event_id, event in function.properties[\"Events\"].items():\n            if event and isinstance(event, dict) and event.get(\"Type\") == \"Api\":\n                api_events[event_id] = event\n        return api_events",
    "docstring": "Method to return a dictionary of API Events on the function\n\n        :param SamResource function: Function Resource object\n        :return dict: Dictionary of API events along with any other configuration passed to it.\n            Example: {\n                FooEvent: {Path: \"/foo\", Method: \"post\", RestApiId: blah, MethodSettings: {<something>},\n                            Cors: {<something>}, Auth: {<something>}},\n                BarEvent: {Path: \"/bar\", Method: \"any\", MethodSettings: {<something>}, Cors: {<something>},\n                            Auth: {<something>}}\"\n            }"
  },
  {
    "code": "def dict(self):\n        return {\n            'title': self.title,\n            'description': self.description,\n            'time': self.time.isoformat(),\n            'data': self.data()\n        }",
    "docstring": "the dict representation.\n\n        :return: the dict\n        :rtype: dict"
  },
  {
    "code": "def virtual_interface_create(name, net_name, **kwargs):\n    conn = get_conn()\n    return conn.virtual_interface_create(name, net_name)",
    "docstring": "Create private networks"
  },
  {
    "code": "def get_var(var, default='\"\"'):\n    ret = os.environ.get('NBCONVERT_' + var)\n    if ret is None:\n        return default\n    return json.loads(ret)",
    "docstring": "get var inside notebook"
  },
  {
    "code": "def intern(self, text):\n        if self.table_type.is_shared:\n            raise TypeError('Cannot intern on shared symbol table')\n        if not isinstance(text, six.text_type):\n            raise TypeError('Cannot intern non-Unicode sequence into symbol table: %r' % text)\n        token = self.get(text)\n        if token is None:\n            token = self.__add_text(text)\n        return token",
    "docstring": "Interns the given Unicode sequence into the symbol table.\n\n        Note:\n            This operation is only valid on local symbol tables.\n\n        Args:\n            text (unicode): The target to intern.\n\n        Returns:\n            SymbolToken: The mapped symbol token which may already exist in the table."
  },
  {
    "code": "def create_pred2common(self):\n        self.pred2common = {}\n        for common_name, ext_preds in self.common2preds.items():\n            for pred in ext_preds:\n                pred = pred.lower().strip()\n                self.pred2common[pred] = common_name",
    "docstring": "Takes list linked to common name and maps common name to accepted predicate\n            and their respected suffixes to decrease sensitivity."
  },
  {
    "code": "def mapping_get(uri, mapping):\n    ln = localname(uri)\n    for k, v in mapping.items():\n        if k == uri:\n            return v\n    for k, v in mapping.items():\n        if k == ln:\n            return v\n    l = list(mapping.items())\n    l.sort(key=lambda i: len(i[0]), reverse=True)\n    for k, v in l:\n        if k[0] == '*' and ln.endswith(k[1:]):\n            return v\n    raise KeyError(uri)",
    "docstring": "Look up the URI in the given mapping and return the result.\n\n    Throws KeyError if no matching mapping was found."
  },
  {
    "code": "def download_quad(self, quad, callback=None):\n        download_url = quad['_links']['download']\n        return self._get(download_url, models.Body, callback=callback)",
    "docstring": "Download the specified mosaic quad. If provided, the callback will\n        be invoked asynchronously.  Otherwise it is up to the caller to handle\n        the response Body.\n\n        :param asset dict: A mosaic quad representation from the API\n        :param callback: An optional function to aysnchronsously handle the\n                         download. See :py:func:`planet.api.write_to_file`\n        :returns: :py:Class:`planet.api.models.Response` containing a\n                  :py:Class:`planet.api.models.Body` of the asset.\n        :raises planet.api.exceptions.APIException: On API error."
  },
  {
    "code": "def getName(self):\n\t\tname=self.findattr('name')\n\t\tif not name:\n\t\t\tname=\"_directinput_\"\n\t\t\tif self.classname().lower()==\"line\":\n\t\t\t\tname+=\".\"+str(self).replace(\" \",\"_\").lower()\n\t\telse:\n\t\t\tname=name.replace('.txt','')\n\t\twhile name.startswith(\".\"):\n\t\t\tname=name[1:]\n\t\treturn name",
    "docstring": "Return a Name string for this object."
  },
  {
    "code": "def combine_columns(columns):\n    columns_zipped = itertools.zip_longest(*columns)\n    return ''.join(x for zipped in columns_zipped for x in zipped if x)",
    "docstring": "Combine ``columns`` into a single string.\n\n    Example:\n        >>> combine_columns(['eape', 'xml'])\n        'example'\n\n    Args:\n        columns (iterable): ordered columns to combine\n\n    Returns:\n        String of combined columns"
  },
  {
    "code": "def find_arg(self, name):\n        name = self.normalize_name(name)\n        return self.args.get(name)",
    "docstring": "Find arg by normalized arg name or parameter name."
  },
  {
    "code": "def wait_until_element_stops(self, element, times=1000, timeout=None):\n        return self._wait_until(self._expected_condition_find_element_stopped, (element, times), timeout)",
    "docstring": "Search element and wait until it has stopped moving\n\n        :param element: PageElement or element locator as a tuple (locator_type, locator_value) to be found\n        :param times: number of iterations checking the element's location that must be the same for all of them\n        in order to considering the element has stopped\n        :returns: the web element if the element is stopped\n        :rtype: selenium.webdriver.remote.webelement.WebElement or appium.webdriver.webelement.WebElement\n        :raises TimeoutException: If the element does not stop after the timeout"
  },
  {
    "code": "def _get_weekly_date_range(self, metric_date, delta):\n        dates = [metric_date]\n        end_date = metric_date + delta\n        spanning_years = end_date.year - metric_date.year\n        for i in range(spanning_years):\n            dates.append(\n                datetime.date(\n                    year=metric_date.year + (i + 1), month=1, day=1))\n        return dates",
    "docstring": "Gets the range of years that we need to use as keys to get metrics from redis."
  },
  {
    "code": "def _send(self, message):\n        params = {\n            'from': message.from_phone, \n            'to': \",\".join(message.to),\n            'text': message.body,\n            'api_key': self.get_api_key(),\n            'api_secret': self.get_api_secret(),\n        }\n        print(params)\n        logger.debug(\"POST to %r with body: %r\", NEXMO_API_URL, params)\n        return self.parse(NEXMO_API_URL, requests.post(NEXMO_API_URL, data=params))",
    "docstring": "A helper method that does the actual sending\n\n        :param SmsMessage message: SmsMessage class instance.\n        :returns: True if message is sent else False\n        :rtype: bool"
  },
  {
    "code": "def serror(message, *args, **kwargs):\n    if args or kwargs:\n        message = message.format(*args, **kwargs)\n    return secho(message, fg='white', bg='red', bold=True)",
    "docstring": "Print a styled error message, while using any arguments to format the message."
  },
  {
    "code": "def write_file(self, filename='HEADER'):\n        with open(filename, \"w\") as f:\n            f.write(str(self) + \"\\n\")",
    "docstring": "Writes Header into filename on disk.\n\n        Args:\n            filename: Filename and path for file to be written to disk"
  },
  {
    "code": "def find_all(self, name=None, **attrs):\n        r\n        for descendant in self.__descendants():\n            if hasattr(descendant, '__match__') and \\\n                    descendant.__match__(name, attrs):\n                yield descendant",
    "docstring": "r\"\"\"Return all descendant nodes matching criteria.\n\n        :param Union[None,str] name: name of LaTeX expression\n        :param attrs: LaTeX expression attributes, such as item text.\n        :return: All descendant nodes matching criteria\n        :rtype: Iterator[TexNode]\n\n        >>> from TexSoup import TexSoup\n        >>> soup = TexSoup(r'''\n        ... \\section{Ooo}\n        ... \\textit{eee}\n        ... \\textit{ooo}''')\n        >>> gen = soup.find_all('textit')\n        >>> next(gen)\n        \\textit{eee}\n        >>> next(gen)\n        \\textit{ooo}\n        >>> next(soup.find_all('textbf'))\n        Traceback (most recent call last):\n        ...\n        StopIteration"
  },
  {
    "code": "def read(self):\n        self.found_visible = False\n        is_multi_quote_header = self.MULTI_QUOTE_HDR_REGEX_MULTILINE.search(self.text)\n        if is_multi_quote_header:\n            self.text = self.MULTI_QUOTE_HDR_REGEX.sub(is_multi_quote_header.groups()[0].replace('\\n', ''), self.text)\n        self.text = re.sub('([^\\n])(?=\\n ?[_-]{7,})', '\\\\1\\n', self.text, re.MULTILINE)\n        self.lines = self.text.split('\\n')\n        self.lines.reverse()\n        for line in self.lines:\n            self._scan_line(line)\n        self._finish_fragment()\n        self.fragments.reverse()\n        return self",
    "docstring": "Creates new fragment for each line\n            and labels as a signature, quote, or hidden.\n\n            Returns EmailMessage instance"
  },
  {
    "code": "def _profiles_index(self):\n        prof_ind_name = self.prof_ind_name\n        f = open(self.sldir+'/'+prof_ind_name,'r')\n        line = f.readline()\n        numlines=int(line.split()[0])\n        print(str(numlines)+' in profiles.index file ...')\n        model=[]\n        log_file_num=[]\n        for line in f:\n            model.append(int(line.split()[0]))\n            log_file_num.append(int(line.split()[2]))\n        log_ind={}\n        for a,b in zip(model,log_file_num):\n            log_ind[a] = b\n        self.log_ind=log_ind\n        self.model=model",
    "docstring": "read profiles.index and make hash array\n\n        Notes\n        -----\n        sets the attributes.\n\n        log_ind : hash array that returns profile.data or log.data\n        file number from model number.\n\n        model : the models for which profile.data or log.data is\n        available"
  },
  {
    "code": "def to_utc(some_time):\n    if some_time.tzinfo and some_time.utcoffset():\n        some_time = some_time.astimezone(tzutc())\n    return some_time.replace(tzinfo=None)",
    "docstring": "Convert the given date to UTC, if the date contains a timezone.\n\n    Parameters\n    ----------\n    some_time : datetime.datetime\n        datetime object to convert to UTC\n\n    Returns\n    -------\n    datetime.datetime\n        Converted datetime object"
  },
  {
    "code": "def get_article_properties_per_page(self, per_page=1000, page=1, params=None):\n        return self._get_resource_per_page(resource=ARTICLE_PROPERTIES, per_page=per_page, page=page, params=params)",
    "docstring": "Get article properties per page\n\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :param params: Search parameters. Default: {}\n        :return: list"
  },
  {
    "code": "def _expected_condition_find_element_stopped(self, element_times):\n        element, times = element_times\n        web_element = self._expected_condition_find_element(element)\n        try:\n            locations_list = [tuple(web_element.location.values()) for i in range(int(times)) if not time.sleep(0.001)]\n            return web_element if set(locations_list) == set(locations_list[-1:]) else False\n        except StaleElementReferenceException:\n            return False",
    "docstring": "Tries to find the element and checks that it has stopped moving, but does not thrown an exception if the element\n            is not found\n\n        :param element_times: Tuple with 2 items where:\n            [0] element: PageElement or element locator as a tuple (locator_type, locator_value) to be found\n            [1] times: number of iterations checking the element's location that must be the same for all of them\n            in order to considering the element has stopped\n        :returns: the web element if it is clickable or False\n        :rtype: selenium.webdriver.remote.webelement.WebElement or appium.webdriver.webelement.WebElement"
  },
  {
    "code": "def _print_duration(self):\n        duration = int(time.time() - self._start_time)\n        self._print(datetime.timedelta(seconds=duration))",
    "docstring": "Print the elapsed download time."
  },
  {
    "code": "def check_used(self, pkg):\n        used = []\n        dep_path = self.meta.log_path + \"dep/\"\n        logs = find_package(\"\", dep_path)\n        for log in logs:\n            deps = Utils().read_file(dep_path + log)\n            for dep in deps.splitlines():\n                if pkg == dep:\n                    used.append(log)\n        return used",
    "docstring": "Check if dependencies used"
  },
  {
    "code": "def _parse_peer_link(self, config):\n        match = re.search(r'peer-link (\\S+)', config)\n        value = match.group(1) if match else None\n        return dict(peer_link=value)",
    "docstring": "Scans the config block and parses the peer-link value\n\n        Args:\n            config (str): The config block to scan\n\n        Returns:\n            dict: A dict object that is intended to be merged into the\n                resource dict"
  },
  {
    "code": "def runway_config(self):\n        if not self._runway_config:\n            self._runway_config = self.parse_runway_config()\n        return self._runway_config",
    "docstring": "Return parsed runway.yml."
  },
  {
    "code": "def _init_notes(self):\n        self.cached_json = {\n            'ver': self.schema,\n            'users': {},\n            'constants': {\n                'users': [x.name for x in self.subreddit.moderator()],\n                'warnings': Note.warnings\n            }\n        }\n        self.set_json('Initializing JSON via puni', True)",
    "docstring": "Set up the UserNotes page with the initial JSON schema."
  },
  {
    "code": "def _do_api_call(self, method, data):\n        data.update({\n            \"key\": self.api_key,\n            \"token\": self.api_auth_token,\n        })\n        url = \"%s%s\" % (self.endpoint, method)\n        response = requests.get(url, params=data)\n        root = etree.fromstring(response.content)\n        status_code = root.find(\"header/status/code\").text\n        exc_class = _get_exception_class_from_status_code(status_code)\n        if exc_class:\n            error_message = root.find(\"header/status/message\").text\n            raise exc_class(error_message)\n        return root",
    "docstring": "Convenience method to carry out a standard API call against the\n        Petfinder API.\n\n        :param basestring method: The API method name to call.\n        :param dict data: Key/value parameters to send to the API method.\n            This varies based on the method.\n        :raises: A number of :py:exc:`petfinder.exceptions.PetfinderAPIError``\n            sub-classes, depending on what went wrong.\n        :rtype: lxml.etree._Element\n        :returns: The parsed document."
  },
  {
    "code": "def count_emails(self, conditions={}):\n        url = self.EMAILS_COUNT_URL + \"?\"\n        for key, value in conditions.items():\n            if key is 'ids':\n                value = \",\".join(value)\n            url += '&%s=%s' % (key, value)\n        connection = Connection(self.token)\n        connection.set_url(self.production, url)\n        connection.set_url(self.production, url)\n        return connection.get_request()",
    "docstring": "Count all certified emails"
  },
  {
    "code": "def from_serializable(cls, object_dict):\n        key_class = cls._from_visible(cls.STARTS_WITH + 'class' + cls.ENDS_WITH)\n        key_module = cls._from_visible(cls.STARTS_WITH + 'module' + cls.ENDS_WITH)\n        obj_class = object_dict.pop(key_class)\n        obj_module = object_dict.pop(key_module) if key_module in object_dict else None\n        obj = cls._from_class(obj_class, obj_module)\n        obj.modify_object(object_dict)\n        return obj",
    "docstring": "core class method to create visible objects from a dictionary"
  },
  {
    "code": "def unassign_assessment_from_bank(self, assessment_id, bank_id):\n        mgr = self._get_provider_manager('ASSESSMENT', local=True)\n        lookup_session = mgr.get_bank_lookup_session(proxy=self._proxy)\n        lookup_session.get_bank(bank_id)\n        self._unassign_object_from_catalog(assessment_id, bank_id)",
    "docstring": "Removes an ``Assessment`` from a ``Bank``.\n\n        arg:    assessment_id (osid.id.Id): the ``Id`` of the\n                ``Assessment``\n        arg:    bank_id (osid.id.Id): the ``Id`` of the ``Bank``\n        raise:  NotFound - ``assessment_id`` or ``bank_id`` not found or\n                ``assessment_id`` not assigned to ``bank_id``\n        raise:  NullArgument - ``assessment_id`` or ``bank_id`` is\n                ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def parent(self, parent):\n        self._parent = parent\n        if parent:\n            pctx = dict((x, getattr(parent, x)) for x in parent.context_keys)\n            self.inject_context(pctx)\n            self.depth = parent.depth + 1\n            for command in self.subcommands.values():\n                command.parent = self\n        else:\n            self.depth = 0",
    "docstring": "Copy context from the parent into this instance as well as\n        adjusting or depth value to indicate where we exist in a command\n        tree."
  },
  {
    "code": "def append_child(self, name, child):\n        temp = ArTree(name, child)\n        self._array.append(temp)\n        return temp",
    "docstring": "Append new child and return it."
  },
  {
    "code": "def execute(self, *args, **kwargs):\n        self.walk(*args, **kwargs)\n        failed_steps = [step for step in self.steps if step.status == FAILED]\n        if failed_steps:\n            raise PlanFailed(failed_steps)",
    "docstring": "Walks each step in the underlying graph, and raises an exception if\n        any of the steps fail.\n\n        Raises:\n            PlanFailed: Raised if any of the steps fail."
  },
  {
    "code": "def numberOfYTilesAtZoom(self, zoom):\n        \"Retruns the number of tiles over y at a given zoom level\"\n        [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom)\n        return maxRow - minRow + 1",
    "docstring": "Retruns the number of tiles over y at a given zoom level"
  },
  {
    "code": "def fetch(self, webfonts):\n        sorted_keys = sorted(webfonts.keys())\n        for webfont_name in sorted_keys:\n            self.get(webfont_name, webfonts[webfont_name])",
    "docstring": "Store every defined webfonts.\n\n        Webfont are stored with sort on their name.\n\n        Args:\n            webfonts (dict): Dictionnary of webfont settings from\n                ``settings.ICOMOON_WEBFONTS``."
  },
  {
    "code": "def transformation_matrix(x_vector, y_vector, translation, spacing):\n    matrix = numpy.zeros((4, 4), dtype=numpy.float)\n    matrix[:3, 0] = x_vector\n    matrix[:3, 1] = y_vector\n    z_vector = numpy.cross(x_vector, y_vector)\n    matrix[:3, 2] = z_vector\n    matrix[:3, 3] = numpy.array(translation)\n    matrix[3, 3] = 1.0\n    spacing = list(spacing)\n    while len(spacing) < 4:\n        spacing.append(1.0)\n    for i in range(4):\n        for j in range(4):\n            matrix[i, j] *= spacing[j]\n    return matrix",
    "docstring": "Creates a transformation matrix which will convert from a specified\n    coordinate system to the scanner frame of reference.\n\n    :param x_vector: The unit vector along the space X axis in scanner coordinates\n    :param y_vector: The unit vector along the space Y axis in scanner coordinates\n    :param translation: The origin of the space in scanner coordinates\n    :param spacing: The size of a space unit in scanner units\n    :return:"
  },
  {
    "code": "def _dup_samples_by_variantcaller(samples, require_bam=True):\n    samples = [utils.to_single_data(x) for x in samples]\n    samples = germline.split_somatic(samples)\n    to_process = []\n    extras = []\n    for data in samples:\n        added = False\n        for i, add in enumerate(handle_multiple_callers(data, \"variantcaller\", require_bam=require_bam)):\n            added = True\n            add = dd.set_variantcaller_order(add, i)\n            to_process.append([add])\n        if not added:\n            data = _handle_precalled(data)\n            data = dd.set_variantcaller_order(data, 0)\n            extras.append([data])\n    return to_process, extras",
    "docstring": "Prepare samples by variant callers, duplicating any with multiple callers."
  },
  {
    "code": "def error(message, *args, **kwargs):\n    if 'end' in kwargs:\n        end = kwargs['end']\n    else:\n        end = '\\n'\n    if len(args) == 0:\n        sys.stderr.write(message)\n    else:\n        sys.stderr.write(message % args)\n    sys.stderr.write(end)\n    sys.stderr.flush()",
    "docstring": "write a message to stderr"
  },
  {
    "code": "def abbrev_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:\n        func = self.cmd_func(data.statement.command)\n        if func is None:\n            possible_cmds = [cmd for cmd in self.get_all_commands() if cmd.startswith(data.statement.command)]\n            if len(possible_cmds) == 1:\n                raw = data.statement.raw.replace(data.statement.command, possible_cmds[0], 1)\n                data.statement = self.statement_parser.parse(raw)\n        return data",
    "docstring": "Accept unique abbreviated commands"
  },
  {
    "code": "def image_corner(self, corner):\n        if corner not in self.corner_types():\n            raise GeoRaster2Error('corner %s invalid, expected: %s' % (corner, self.corner_types()))\n        x = 0 if corner[1] == 'l' else self.width\n        y = 0 if corner[0] == 'u' else self.height\n        return Point(x, y)",
    "docstring": "Return image corner in pixels, as shapely.Point."
  },
  {
    "code": "def pack(chunks, r=32):\n    if r < 1:\n        raise ValueError('pack needs r > 0')\n    n = shift = 0\n    for c in chunks:\n        n += c << shift\n        shift += r\n    return n",
    "docstring": "Return integer concatenating integer chunks of r > 0 bit-length.\n\n    >>> pack([0, 1, 0, 1, 0, 1], 1)\n    42\n\n    >>> pack([0, 1], 8)\n    256\n\n    >>> pack([0, 1], 0)\n    Traceback (most recent call last):\n        ...\n    ValueError: pack needs r > 0"
  },
  {
    "code": "def get_create_foreign_key_sql(self, foreign_key, table):\n        if isinstance(table, Table):\n            table = table.get_quoted_name(self)\n        query = \"ALTER TABLE %s ADD %s\" % (\n            table,\n            self.get_foreign_key_declaration_sql(foreign_key),\n        )\n        return query",
    "docstring": "Returns the SQL to create a new foreign key.\n\n        :rtype: sql"
  },
  {
    "code": "def libvlc_video_get_track_description(p_mi):\n    f = _Cfunctions.get('libvlc_video_get_track_description', None) or \\\n        _Cfunction('libvlc_video_get_track_description', ((1,),), None,\n                    ctypes.POINTER(TrackDescription), MediaPlayer)\n    return f(p_mi)",
    "docstring": "Get the description of available video tracks.\n    @param p_mi: media player.\n    @return: list with description of available video tracks, or NULL on error."
  },
  {
    "code": "def get_source_files(target, build_context) -> list:\n    all_sources = list(target.props.sources)\n    for proto_dep_name in target.props.protos:\n        proto_dep = build_context.targets[proto_dep_name]\n        all_sources.extend(proto_dep.artifacts.get(AT.gen_cc).keys())\n    return all_sources",
    "docstring": "Return list of source files for `target`."
  },
  {
    "code": "def mk_complex_format_func(fmt):\n\tfmt = fmt + u\"+i\" + fmt\n\tdef complex_format_func(z):\n\t\treturn fmt % (z.real, z.imag)\n\treturn complex_format_func",
    "docstring": "Function used internally to generate functions to format complex\n\tvalued data."
  },
  {
    "code": "def inbound_message_filter(f):\n    if asyncio.iscoroutinefunction(f):\n        raise TypeError(\n            \"inbound_message_filter must not be a coroutine function\"\n        )\n    add_handler_spec(\n        f,\n        HandlerSpec(\n            (_apply_inbound_message_filter, ())\n        ),\n    )\n    return f",
    "docstring": "Register the decorated function as a service-level inbound message filter.\n\n    :raise TypeError: if the decorated object is a coroutine function\n\n    .. seealso::\n\n       :class:`StanzaStream`\n          for important remarks regarding the use of stanza filters."
  },
  {
    "code": "def filter(self, value, table=None):\n        if table is not None:\n            filterable = self.filterable_func(value, table)\n        else:\n            filterable = self.filterable_func(value)\n        return filterable",
    "docstring": "Return True if the value should be pruned; False otherwise.\n\n        If a `table` argument was provided, pass it to filterable_func."
  },
  {
    "code": "def to_attrs(args, nocreate_if_none=['id', 'for', 'class']):\n    if not args:\n        return ''\n    s = ['']\n    for k, v in sorted(args.items()):\n        k = u_str(k)\n        v = u_str(v)\n        if k.startswith('_'):\n            k = k[1:]\n        if v is None:\n            if k not in nocreate_if_none:\n                s.append(k)\n        else:\n            if k.lower() in __noescape_attrs__:\n                t = u_str(v)\n            else:\n                t = cgi.escape(u_str(v))\n            t = '\"%s\"' % t.replace('\"', '&quot;')\n            s.append('%s=%s' % (k, t))\n    return ' '.join(s)",
    "docstring": "Make python dict to k=\"v\" format"
  },
  {
    "code": "def get_gradebook_column_lookup_session(self, proxy):\n        if not self.supports_gradebook_column_lookup():\n            raise errors.Unimplemented()\n        return sessions.GradebookColumnLookupSession(proxy=proxy, runtime=self._runtime)",
    "docstring": "Gets the ``OsidSession`` associated with the gradebook column lookup service.\n\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.grading.GradebookColumnLookupSession) - a\n                ``GradebookColumnLookupSession``\n        raise:  NullArgument - ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_gradebook_column_lookup()``\n                is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_gradebook_column_lookup()`` is ``true``.*"
  },
  {
    "code": "def addOntology(self):\n        self._openRepo()\n        name = self._args.name\n        filePath = self._getFilePath(self._args.filePath,\n                                     self._args.relativePath)\n        if name is None:\n            name = getNameFromPath(filePath)\n        ontology = ontologies.Ontology(name)\n        ontology.populateFromFile(filePath)\n        self._updateRepo(self._repo.insertOntology, ontology)",
    "docstring": "Adds a new Ontology to this repo."
  },
  {
    "code": "def get_gemini_files(data):\n    try:\n        from gemini import annotations, config\n    except ImportError:\n        return {}\n    return {\"base\": config.read_gemini_config()[\"annotation_dir\"],\n            \"files\": annotations.get_anno_files().values()}",
    "docstring": "Enumerate available gemini data files in a standard installation."
  },
  {
    "code": "def network_sub_create_notif(self, tenant_id, tenant_name, cidr):\n        if not self.fw_init:\n            return\n        self.network_create_notif(tenant_id, tenant_name, cidr)",
    "docstring": "Network create notification."
  },
  {
    "code": "def set_subresource(self, subresource, value, key_name = '', headers=None,\n                        version_id=None):\n        if not subresource:\n            raise TypeError('set_subresource called with subresource=None')\n        query_args = subresource\n        if version_id:\n            query_args += '&versionId=%s' % version_id\n        response = self.connection.make_request('PUT', self.name, key_name,\n                                                data=value.encode('UTF-8'),\n                                                query_args=query_args,\n                                                headers=headers)\n        body = response.read()\n        if response.status != 200:\n            raise self.connection.provider.storage_response_error(\n                response.status, response.reason, body)",
    "docstring": "Set a subresource for a bucket or key.\n\n        :type subresource: string\n        :param subresource: The subresource to set.\n\n        :type value: string\n        :param value: The value of the subresource.\n\n        :type key_name: string\n        :param key_name: The key to operate on, or None to operate on the\n                         bucket.\n\n        :type headers: dict\n        :param headers: Additional HTTP headers to include in the request.\n\n        :type src_version_id: string\n        :param src_version_id: Optional. The version id of the key to operate\n                               on. If not specified, operate on the newest\n                               version."
  },
  {
    "code": "def crypto_withdraw(self, amount, currency, crypto_address):\n        params = {'amount': amount,\n                  'currency': currency,\n                  'crypto_address': crypto_address}\n        return self._send_message('post', '/withdrawals/crypto',\n                                  data=json.dumps(params))",
    "docstring": "Withdraw funds to a crypto address.\n\n        Args:\n            amount (Decimal): The amount to withdraw\n            currency (str): The type of currency (eg. 'BTC')\n            crypto_address (str): Crypto address to withdraw to.\n\n        Returns:\n            dict: Withdraw details. Example::\n                {\n                    \"id\":\"593533d2-ff31-46e0-b22e-ca754147a96a\",\n                    \"amount\":\"10.00\",\n                    \"currency\": \"BTC\",\n                }"
  },
  {
    "code": "def get_date_bounds(self):\n        start = end = None\n        date_gt = '>='\n        date_lt = '<='\n        if self:\n            if self.start:\n                start = self.start\n            if self.end:\n                end = self.end\n            if self.startopen:\n                date_gt = '>'\n            if self.endopen:\n                date_lt = '<'\n        return date_gt, start, date_lt, end",
    "docstring": "Return the upper and lower bounds along\n        with operators that are needed to do an 'in range' test.\n        Useful for SQL commands.\n\n        Returns\n        -------\n        tuple: (`str`, `date`, `str`, `date`)\n                (date_gt, start, date_lt, end)\n        e.g.:\n                ('>=', start_date, '<', end_date)"
  },
  {
    "code": "def GetMetricMetadata():\n  return [\n      stats_utils.CreateCounterMetadata(\"grr_client_unknown\"),\n      stats_utils.CreateCounterMetadata(\"grr_decoding_error\"),\n      stats_utils.CreateCounterMetadata(\"grr_decryption_error\"),\n      stats_utils.CreateCounterMetadata(\"grr_authenticated_messages\"),\n      stats_utils.CreateCounterMetadata(\"grr_unauthenticated_messages\"),\n      stats_utils.CreateCounterMetadata(\"grr_rsa_operations\"),\n      stats_utils.CreateCounterMetadata(\n          \"grr_encrypted_cipher_cache\", fields=[(\"type\", str)]),\n  ]",
    "docstring": "Returns a list of MetricMetadata for communicator-related metrics."
  },
  {
    "code": "def delete(self):\n        self._pre_action_check('delete')\n        self.cypher(\"MATCH (self) WHERE id(self)={self} \"\n                    \"OPTIONAL MATCH (self)-[r]-()\"\n                    \" DELETE r, self\")\n        delattr(self, 'id')\n        self.deleted = True\n        return True",
    "docstring": "Delete a node and it's relationships\n\n        :return: True"
  },
  {
    "code": "def _validate_metadata(metadata_props):\n    if len(CaseInsensitiveDict(metadata_props)) != len(metadata_props):\n        raise RuntimeError('Duplicate metadata props found')\n    for key, value in metadata_props.items():\n        valid_values = KNOWN_METADATA_PROPS.get(key)\n        if valid_values and value.lower() not in valid_values:\n            warnings.warn('Key {} has invalid value {}. Valid values are {}'.format(key, value, valid_values))",
    "docstring": "Validate metadata properties and possibly show warnings or throw exceptions.\n\n    :param metadata_props: A dictionary of metadata properties, with property names and values (see :func:`~onnxmltools.utils.metadata_props.add_metadata_props` for examples)"
  },
  {
    "code": "def is_binary_address(value: Any) -> bool:\n    if not is_bytes(value):\n        return False\n    elif len(value) != 20:\n        return False\n    else:\n        return True",
    "docstring": "Checks if the given string is an address in raw bytes form."
  },
  {
    "code": "def _confirm_pos(self, pos):\n        candidate = None\n        if self._get_node(self._treelist, pos) is not None:\n            candidate = pos\n        return candidate",
    "docstring": "look up widget for pos and default to None"
  },
  {
    "code": "def push(self, metric_type, metric_id, value, timestamp=None):\n        if type(timestamp) is datetime:\n            timestamp = datetime_to_time_millis(timestamp)\n        item = create_metric(metric_type, metric_id, create_datapoint(value, timestamp))\n        self.put(item)",
    "docstring": "Pushes a single metric_id, datapoint combination to the server.\n\n        This method is an assistant method for the put method by removing the need to\n        create data structures first.\n\n        :param metric_type: MetricType to be matched (required)\n        :param metric_id: Exact string matching metric id\n        :param value: Datapoint value (depending on the MetricType)\n        :param timestamp: Timestamp of the datapoint. If left empty, uses current client time. Can be milliseconds since epoch or datetime instance"
  },
  {
    "code": "def toggle_logo_path(self):\n        is_checked = self.custom_organisation_logo_check_box.isChecked()\n        if is_checked:\n            path = setting(\n                key='organisation_logo_path',\n                default=supporters_logo_path(),\n                expected_type=str,\n                qsettings=self.settings)\n        else:\n            path = supporters_logo_path()\n        self.organisation_logo_path_line_edit.setText(path)\n        self.organisation_logo_path_line_edit.setEnabled(is_checked)\n        self.open_organisation_logo_path_button.setEnabled(is_checked)",
    "docstring": "Set state of logo path line edit and button."
  },
  {
    "code": "def list_files(path, extension=\".cpp\", exclude=\"S.cpp\"):\n    return [\"%s/%s\" % (path, f) for f in listdir(path) if f.endswith(extension) and (not f.endswith(exclude))]",
    "docstring": "List paths to all files that ends with a given extension"
  },
  {
    "code": "def rabin_miller(p):\n    if p < 2:\n        return False\n    if p != 2 and p & 1 == 0:\n        return False\n    s = p - 1\n    while s & 1 == 0:\n        s >>= 1\n    for x in range(10):\n        a = random.randrange(p - 1) + 1\n        temp = s\n        mod = pow(a, temp, p)\n        while temp != p - 1 and mod != 1 and mod != p - 1:\n            mod = (mod * mod) % p\n            temp = temp * 2\n        if mod != p - 1 and temp % 2 == 0:\n            return False\n    return True",
    "docstring": "Performs a rabin-miller primality test\n\n    :param p: Number to test\n    :return: Bool of whether num is prime"
  },
  {
    "code": "def floatize(self):\n        self.x = float(self.x)\n        self.y = float(self.y)",
    "docstring": "Convert co-ordinate values to floats."
  },
  {
    "code": "def find_all(root, path):\n  path = parse_path(path)\n  if len(path) == 1:\n    yield from get_children(root, path[0])\n  else:\n    for child in get_children(root, path[0]):\n      yield from find_all(child, path[1:])",
    "docstring": "Get all children that satisfy the path."
  },
  {
    "code": "def _patch(self, doc, source, patches, setter=None):\n        old = self._saved_copy()\n        for name, patch in patches.items():\n            for ind, value in patch:\n                if isinstance(ind, (int, slice)):\n                    self[name][ind] = value\n                else:\n                    shape = self[name][ind[0]][tuple(ind[1:])].shape\n                    self[name][ind[0]][tuple(ind[1:])] = np.array(value, copy=False).reshape(shape)\n        from ...document.events import ColumnsPatchedEvent\n        self._notify_owners(old,\n                            hint=ColumnsPatchedEvent(doc, source, patches, setter))",
    "docstring": "Internal implementation to handle special-casing patch events\n        on ``ColumnDataSource`` columns.\n\n        Normally any changes to the ``.data`` dict attribute on a\n        ``ColumnDataSource`` triggers a notification, causing all of the data\n        to be synchronized between server and clients.\n\n        The ``.patch`` method on column data sources exists to provide a\n        more efficient way to perform patching (i.e. random access) updates\n        to a data source, without having to perform a full synchronization,\n        which would needlessly re-send all the data.\n\n        To accomplish this, this function bypasses the wrapped methods on\n        ``PropertyValueDict`` and uses the unwrapped versions on the dict\n        superclass directly. It then explicitly makes a notification, adding\n        a special ``ColumnsPatchedEvent`` hint to the message containing\n        only the small patched data that BokehJS needs in order to efficiently\n        synchronize.\n\n        .. warning::\n            This function assumes the integrity of ``patches`` has already\n            been verified."
  },
  {
    "code": "def assert_list(obj, expected_type=string_types, can_be_none=True, default=(), key_arg=None,\n    allowable=(list, Fileset, OrderedSet, set, tuple), raise_type=ValueError):\n  def get_key_msg(key=None):\n    if key is None:\n      return ''\n    else:\n      return \"In key '{}': \".format(key)\n  allowable = tuple(allowable)\n  key_msg = get_key_msg(key_arg)\n  val = obj\n  if val is None:\n    if can_be_none:\n      val = list(default)\n    else:\n      raise raise_type(\n        '{}Expected an object of acceptable type {}, received None and can_be_none is False'\n          .format(key_msg, allowable))\n  if isinstance(val, allowable):\n    lst = list(val)\n    for e in lst:\n      if not isinstance(e, expected_type):\n        raise raise_type(\n            '{}Expected a list containing values of type {}, instead got a value {} of {}'\n            .format(key_msg, expected_type, e, e.__class__))\n    return lst\n  else:\n    raise raise_type(\n        '{}Expected an object of acceptable type {}, received {} instead'\n        .format(key_msg, allowable, val))",
    "docstring": "This function is used to ensure that parameters set by users in BUILD files are of acceptable types.\n\n  :API: public\n\n  :param obj           : the object that may be a list. It will pass if it is of type in allowable.\n  :param expected_type : this is the expected type of the returned list contents.\n  :param can_be_none   : this defines whether or not the obj can be None. If True, return default.\n  :param default       : this is the default to return if can_be_none is True and obj is None.\n  :param key_arg       : this is the name of the key to which obj belongs to\n  :param allowable     : the acceptable types for obj. We do not want to allow any iterable (eg string).\n  :param raise_type    : the error to throw if the type is not correct."
  },
  {
    "code": "def restart_required(self):\n        response = self.get(\"messages\").body.read()\n        messages = data.load(response)['feed']\n        if 'entry' not in messages:\n            result = False\n        else:\n            if isinstance(messages['entry'], dict):\n                titles = [messages['entry']['title']]\n            else:\n                titles = [x['title'] for x in messages['entry']]\n            result = 'restart_required' in titles\n        return result",
    "docstring": "Indicates whether splunkd is in a state that requires a restart.\n\n        :return: A ``boolean`` that indicates whether a restart is required."
  },
  {
    "code": "def transpose(self, *dims) -> 'DataArray':\n        variable = self.variable.transpose(*dims)\n        return self._replace(variable)",
    "docstring": "Return a new DataArray object with transposed dimensions.\n\n        Parameters\n        ----------\n        *dims : str, optional\n            By default, reverse the dimensions. Otherwise, reorder the\n            dimensions to this order.\n\n        Returns\n        -------\n        transposed : DataArray\n            The returned DataArray's array is transposed.\n\n        Notes\n        -----\n        This operation returns a view of this array's data. It is\n        lazy for dask-backed DataArrays but not for numpy-backed DataArrays\n        -- the data will be fully loaded.\n\n        See Also\n        --------\n        numpy.transpose\n        Dataset.transpose"
  },
  {
    "code": "def newAction(parent, text, slot=None, shortcut=None, icon=None,\n              tip=None, checkable=False, enabled=True):\n    a = QAction(text, parent)\n    if icon is not None:\n        a.setIcon(newIcon(icon))\n    if shortcut is not None:\n        if isinstance(shortcut, (list, tuple)):\n            a.setShortcuts(shortcut)\n        else:\n            a.setShortcut(shortcut)\n    if tip is not None:\n        a.setToolTip(tip)\n        a.setStatusTip(tip)\n    if slot is not None:\n        a.triggered.connect(slot)\n    if checkable:\n        a.setCheckable(True)\n    a.setEnabled(enabled)\n    return a",
    "docstring": "Create a new action and assign callbacks, shortcuts, etc."
  },
  {
    "code": "def get_language(self, language_id):\n        raw_response = requests_util.run_request('get', self.API_BASE_URL + '/languages/%d' % language_id,\n                                                 headers=self.__get_header_with_auth())\n        return self.parse_raw_response(raw_response)",
    "docstring": "Retrieves information about the language of the given id.\n\n        :param language_id: The TheTVDB Id of the language.\n        :return: a python dictionary with either the result of the search or an error from TheTVDB."
  },
  {
    "code": "def get_regex(self):\n        regex = ''\n        for flag in self.compound:\n            if flag == '?' or flag == '*':\n                regex += flag\n            else:\n                regex += '(' + '|'.join(self.flags[flag]) + ')'\n        return regex",
    "docstring": "Generates and returns compound regular expression"
  },
  {
    "code": "def _find_controller(self, *args):\n        for name in args:\n            obj = self._lookup_child(name)\n            if obj and iscontroller(obj):\n                return obj\n        return None",
    "docstring": "Returns the appropriate controller for routing a custom action."
  },
  {
    "code": "def get_replicas(self, service_id: str) -> str:\n        replicas = []\n        if not self._manager:\n            raise RuntimeError('Only the Swarm manager node can retrieve '\n                               'replication level of the service')\n        service_tasks = self._client.services.get(service_id).tasks()\n        for task in service_tasks:\n            if task['Status']['State'] == \"running\":\n                replicas.append(task)\n        return len(replicas)",
    "docstring": "Get the replication level of a service.\n\n        Args:\n            service_id (str): docker swarm service id\n\n        Returns:\n            str, replication level of the service"
  },
  {
    "code": "def pick_free_port():\n        test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        test_socket.bind(('127.0.0.1', 0))\n        free_port = int(test_socket.getsockname()[1])\n        test_socket.close()\n        return free_port",
    "docstring": "Picks a free port"
  },
  {
    "code": "def init_win32com ():\n    global _initialized\n    if _initialized:\n        return\n    import win32com.client\n    if win32com.client.gencache.is_readonly:\n        win32com.client.gencache.is_readonly = False\n        win32com.client.gencache.Rebuild()\n    _initialized = True",
    "docstring": "Initialize the win32com.client cache."
  },
  {
    "code": "def mode(self):\n        mu = self.mean()\n        sigma = self.std()\n        ret_val = math.exp(mu - sigma**2)\n        if math.isnan(ret_val):\n            ret_val = float(\"inf\")\n        return ret_val",
    "docstring": "Computes the mode of a log-normal distribution built with the stats data."
  },
  {
    "code": "def GetUcsPropertyMeta(classId, key):\n\t\tif classId in _ManagedObjectMeta:\n\t\t\tif key in _ManagedObjectMeta[classId]:\n\t\t\t\treturn _ManagedObjectMeta[classId][key]\n\t\treturn None",
    "docstring": "Methods returns the property meta of the provided key for the given classId."
  },
  {
    "code": "def _create_and_save_state(cls, mapreduce_spec, _app):\n    state = model.MapreduceState.create_new(mapreduce_spec.mapreduce_id)\n    state.mapreduce_spec = mapreduce_spec\n    state.active = True\n    state.active_shards = 0\n    if _app:\n      state.app_id = _app\n    config = util.create_datastore_write_config(mapreduce_spec)\n    state.put(config=config)\n    return state",
    "docstring": "Save mapreduce state to datastore.\n\n    Save state to datastore so that UI can see it immediately.\n\n    Args:\n      mapreduce_spec: model.MapreduceSpec,\n      _app: app id if specified. None otherwise.\n\n    Returns:\n      The saved Mapreduce state."
  },
  {
    "code": "def perform_get_or_create(self, request, *args, **kwargs):\n        serializer = self.get_serializer(data=request.data)\n        serializer.is_valid(raise_exception=True)\n        process = serializer.validated_data.get('process')\n        process_input = request.data.get('input', {})\n        fill_with_defaults(process_input, process.input_schema)\n        checksum = get_data_checksum(process_input, process.slug, process.version)\n        data_qs = Data.objects.filter(\n            checksum=checksum,\n            process__persistence__in=[Process.PERSISTENCE_CACHED, Process.PERSISTENCE_TEMP],\n        )\n        data_qs = get_objects_for_user(request.user, 'view_data', data_qs)\n        if data_qs.exists():\n            data = data_qs.order_by('created').last()\n            serializer = self.get_serializer(data)\n            return Response(serializer.data)",
    "docstring": "Perform \"get_or_create\" - return existing object if found."
  },
  {
    "code": "def csv_print(classes, class_stat, digit=5, class_param=None):\n    result = \"Class\"\n    classes.sort()\n    for item in classes:\n        result += ',\"' + str(item) + '\"'\n    result += \"\\n\"\n    class_stat_keys = sorted(class_stat.keys())\n    if isinstance(class_param, list):\n        if set(class_param) <= set(class_stat_keys):\n            class_stat_keys = class_param\n    if len(class_stat_keys) < 1 or len(classes) < 1:\n        return \"\"\n    for key in class_stat_keys:\n        row = [rounder(class_stat[key][i], digit) for i in classes]\n        result += key + \",\" + \",\".join(row)\n        result += \"\\n\"\n    return result",
    "docstring": "Return csv file data.\n\n    :param classes: classes list\n    :type classes:list\n    :param class_stat: statistic result for each class\n    :type class_stat:dict\n    :param digit: scale (the number of digits to the right of the decimal point in a number.)\n    :type digit : int\n    :param class_param : class parameters list for print, Example : [\"TPR\",\"TNR\",\"AUC\"]\n    :type class_param : list\n    :return: csv file data as str"
  },
  {
    "code": "def hashes(self):\n        hashes = set()\n        if (self.resources is not None):\n            for resource in self:\n                if (resource.md5 is not None):\n                    hashes.add('md5')\n                if (resource.sha1 is not None):\n                    hashes.add('sha-1')\n                if (resource.sha256 is not None):\n                    hashes.add('sha-256')\n        return(hashes)",
    "docstring": "Return set of hashes uses in this resource_list."
  },
  {
    "code": "def copyidfintoidf(toidf, fromidf):\n    idfobjlst = getidfobjectlist(fromidf)\n    for idfobj in idfobjlst:\n        toidf.copyidfobject(idfobj)",
    "docstring": "copy fromidf completely into toidf"
  },
  {
    "code": "def _maybe_wrap_exception(exception):\n    if isinstance(exception, grpc.RpcError):\n        return exceptions.from_grpc_error(exception)\n    return exception",
    "docstring": "Wraps a gRPC exception class, if needed."
  },
  {
    "code": "def _is_finished_dumping(directory):\n    run_info = os.path.join(directory, \"RunInfo.xml\")\n    hi_seq_checkpoint = \"Basecalling_Netcopy_complete_Read%s.txt\" % \\\n                        _expected_reads(run_info)\n    to_check = [\"Basecalling_Netcopy_complete_SINGLEREAD.txt\",\n                \"Basecalling_Netcopy_complete_READ2.txt\",\n                hi_seq_checkpoint]\n    return reduce(operator.or_,\n                  [os.path.exists(os.path.join(directory, f)) for f in to_check])",
    "docstring": "Determine if the sequencing directory has all files.\n\n    The final checkpoint file will differ depending if we are a\n    single or paired end run."
  },
  {
    "code": "def grab_names_from_emails(email_list):\n    all_staff = STAFF_LIST\n    emails_names = {}\n    for email in email_list:\n        for person in all_staff:\n            if email == person['email'] and email not in emails_names:\n                emails_names[email] = person['fullName']\n    for email in email_list:\n        matched = False\n        for assignment in emails_names:\n            if email == assignment:\n                matched = True\n        if not matched:\n            emails_names[email] = email\n    return emails_names",
    "docstring": "Return a dictionary mapping names to email addresses.\n\n    Only gives a response if the email is found\n    in the staff API/JSON.\n\n    Expects an API of the format =\n    [\n        {\n            'email': 'foo@bar.net',\n            ...\n            'fullName': 'Frank Oo'\n        },\n        ...\n    ]"
  },
  {
    "code": "def specstring(self):\n        if self.subgroup is None:\n            variable = self.variable\n        else:\n            variable = f'{self.subgroup}.{self.variable}'\n        if self.series:\n            variable = f'{variable}.series'\n        return variable",
    "docstring": "The string corresponding to the current values of `subgroup`,\n        `state`, and `variable`.\n\n        >>> from hydpy.core.itemtools import ExchangeSpecification\n        >>> spec = ExchangeSpecification('hland_v1', 'fluxes.qt')\n        >>> spec.specstring\n        'fluxes.qt'\n        >>> spec.series = True\n        >>> spec.specstring\n        'fluxes.qt.series'\n        >>> spec.subgroup = None\n        >>> spec.specstring\n        'qt.series'"
  },
  {
    "code": "def show_diff(original, modified, prefix='', suffix='',\n              prefix_unchanged=' ',\n              suffix_unchanged='',\n              prefix_removed='-',\n              suffix_removed='',\n              prefix_added='+',\n              suffix_added=''):\n    import difflib\n    differ = difflib.Differ()\n    result = [prefix]\n    for line in differ.compare(modified.splitlines(), original.splitlines()):\n        if line[0] == ' ':\n            result.append(\n                prefix_unchanged + line[2:].strip() + suffix_unchanged)\n        elif line[0] == '-':\n            result.append(prefix_removed + line[2:].strip() + suffix_removed)\n        elif line[0] == '+':\n            result.append(prefix_added + line[2:].strip() + suffix_added)\n    result.append(suffix)\n    return '\\n'.join(result)",
    "docstring": "Return the diff view between original and modified strings.\n\n    Function checks both arguments line by line and returns a string\n    with a:\n    - prefix_unchanged when line is common to both sequences\n    - prefix_removed when line is unique to sequence 1\n    - prefix_added when line is unique to sequence 2\n    and a corresponding suffix in each line\n    :param original: base string\n    :param modified: changed string\n    :param prefix: prefix of the output string\n    :param suffix: suffix of the output string\n    :param prefix_unchanged: prefix of the unchanged line\n    :param suffix_unchanged: suffix of the unchanged line\n    :param prefix_removed: prefix of the removed line\n    :param suffix_removed: suffix of the removed line\n    :param prefix_added: prefix of the added line\n    :param suffix_added: suffix of the added line\n\n    :return: string with the comparison of the records\n    :rtype: string"
  },
  {
    "code": "def reset_pw_confirm_view(request, uidb64=None, token=None):\n    return password_reset_confirm(request,\n        template_name=\"reset_confirmation.html\",\n        uidb64=uidb64, token=token, post_reset_redirect=reverse('login'))",
    "docstring": "View to confirm resetting password."
  },
  {
    "code": "def relaxParserSetFlag(self, flags):\n        ret = libxml2mod.xmlRelaxParserSetFlag(self._o, flags)\n        return ret",
    "docstring": "Semi private function used to pass informations to a parser\n           context which are a combination of xmlRelaxNGParserFlag ."
  },
  {
    "code": "def cursor_blink_mode_changed(self, settings, key, user_data):\n        for term in self.guake.notebook_manager.iter_terminals():\n            term.set_property(\"cursor-blink-mode\", settings.get_int(key))",
    "docstring": "Called when cursor blink mode settings has been changed"
  },
  {
    "code": "def compute_adjacency_matrix(X, method='auto', **kwargs):\n    if method == 'auto':\n        if X.shape[0] > 10000:\n            method = 'cyflann'\n        else:\n            method = 'kd_tree'\n    return Adjacency.init(method, **kwargs).adjacency_graph(X.astype('float'))",
    "docstring": "Compute an adjacency matrix with the given method"
  },
  {
    "code": "def libvlc_video_get_aspect_ratio(p_mi):\n    f = _Cfunctions.get('libvlc_video_get_aspect_ratio', None) or \\\n        _Cfunction('libvlc_video_get_aspect_ratio', ((1,),), string_result,\n                    ctypes.c_void_p, MediaPlayer)\n    return f(p_mi)",
    "docstring": "Get current video aspect ratio.\n    @param p_mi: the media player.\n    @return: the video aspect ratio or NULL if unspecified (the result must be released with free() or L{libvlc_free}())."
  },
  {
    "code": "def add_alt_goids(go2values, altgo2goobj):\n    for goobj_key in altgo2goobj.values():\n        values_curr = go2values[goobj_key.id]\n        for goid_alt in goobj_key.alt_ids:\n            go2values[goid_alt] = values_curr\n    return go2values",
    "docstring": "Add alternate source GO IDs."
  },
  {
    "code": "def GetSource(self, row, col, table=None):\n        if table is None:\n            table = self.grid.current_table\n        value = self.code_array((row, col, table))\n        if value is None:\n            return u\"\"\n        else:\n            return value",
    "docstring": "Return the source string of a cell"
  },
  {
    "code": "def stop(self):\n    log.info('Stopping %s' % self)\n    pids = list(self._processes)\n    for pid in pids:\n      self.terminate(pid)\n    while self._connections:\n      pid = next(iter(self._connections))\n      conn = self._connections.pop(pid, None)\n      if conn:\n        conn.close()\n    self.__loop.stop()",
    "docstring": "Stops the context.  This terminates all PIDs and closes all connections."
  },
  {
    "code": "def class_path(cls):\n    if cls.__module__ == '__main__':\n        path = None\n    else:\n        path = os.path.dirname(inspect.getfile(cls))\n    if not path:\n        path = os.getcwd()\n    return os.path.realpath(path)",
    "docstring": "Return the path to the source file of the given class."
  },
  {
    "code": "def _value_function(self, x_input, y_true, y_pred):\n        if len(y_true.shape) == 1:\n            return y_pred.argmax(1).eq(y_true).double().mean().item()\n        else:\n            raise NotImplementedError",
    "docstring": "Return classification accuracy of input"
  },
  {
    "code": "def as_json(self, force_object=True, name=None):\n        func = streamsx.topology.runtime._json_force_object if force_object else None\n        saj = self._change_schema(streamsx.topology.schema.CommonSchema.Json, 'as_json', name, func)._layout('AsJson')\n        saj.oport.operator.sl = _SourceLocation(_source_info(), 'as_json')\n        return saj",
    "docstring": "Declares a stream converting each tuple on this stream into\n        a JSON value.\n\n        The stream is typed as a :py:const:`JSON stream <streamsx.topology.schema.CommonSchema.Json>`.\n\n        Each tuple must be supported by `JSONEncoder`.\n\n        If `force_object` is `True` then each tuple that not a `dict` \n        will be converted to a JSON object with a single key `payload`\n        containing the tuple. Thus each object on the stream will\n        be a JSON object.\n\n        If `force_object` is `False` then each tuple is converted to\n        a JSON value directly using `json` package.\n\n        If this stream is already typed as a JSON stream then it will\n        be returned (with no additional processing against it and\n        `force_object` and `name` are ignored).\n\n        Args:\n            force_object(bool): Force conversion of non dicts to JSON objects.\n            name(str): Name of the resulting stream.\n                When `None` defaults to a generated name.\n\n        .. versionadded:: 1.6.1\n\n        Returns:\n            Stream: Stream containing the JSON representations of tuples on this stream."
  },
  {
    "code": "def connection(self):\n        if self._connection is None:\n            self._connection = self.client[self.database_name]\n            if self.disable_id_injector:\n                incoming = self._connection._Database__incoming_manipulators\n                for manipulator in incoming:\n                    if isinstance(manipulator,\n                                  pymongo.son_manipulator.ObjectIdInjector):\n                        incoming.remove(manipulator)\n                        LOG.debug(\"Disabling %s on mongodb connection to \"\n                                  \"'%s'.\",\n                                  manipulator.__class__.__name__,\n                                  self.database_name)\n                        break\n            for manipulator in self.manipulators:\n                self._connection.add_son_manipulator(manipulator)\n            LOG.info(\"Connected to mongodb on %s (database=%s)\",\n                     self.safe_connection_string, self.database_name)\n        return self._connection",
    "docstring": "Connect to and return mongodb database object."
  },
  {
    "code": "def write_squonk_datasetmetadata(outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps):\n    meta = {}\n    props = {}\n    if datasetMetaProps:\n        props.update(datasetMetaProps)\n    if fieldMetaProps:\n        meta[\"fieldMetaProps\"] = fieldMetaProps\n    if len(props) > 0:\n        meta[\"properties\"] = props\n    if valueClassMappings:\n        meta[\"valueClassMappings\"] = valueClassMappings\n    if thinOutput:\n        meta['type'] = 'org.squonk.types.BasicObject'\n    else:\n        meta['type'] = 'org.squonk.types.MoleculeObject'\n    s = json.dumps(meta)\n    meta = open(outputBase + '.metadata', 'w')\n    meta.write(s)\n    meta.close()",
    "docstring": "This is a temp hack to write the minimal metadata that Squonk needs.\n    Will needs to be replaced with something that allows something more complete to be written.\n\n    :param outputBase: Base name for the file to write to\n    :param thinOutput: Write only new data, not structures. Result type will be BasicObject\n    :param valueClasses: A dict that describes the Java class of the value properties (used by Squonk)\n    :param datasetMetaProps: A dict with metadata properties that describe the datset as a whole.\n            The keys used for these metadata are up to the user, but common ones include source, description, created, history.\n    :param fieldMetaProps: A list of dicts with the additional field metadata. Each dict has a key named fieldName whose value\n            is the name of the field being described, and a key name values wholes values is a map of metadata properties.\n            The keys used for these metadata are up to the user, but common ones include source, description, created, history."
  },
  {
    "code": "def _report_exception(self, msg, frame_skip=2):\n        msg_hash = hash(msg)\n        if msg_hash in self._report_exception_cache:\n            return\n        self._report_exception_cache.add(msg_hash)\n        error_frame = sys._getframe(0)\n        while frame_skip:\n            error_frame = error_frame.f_back\n            frame_skip -= 1\n        self._py3_wrapper.report_exception(\n            msg, notify_user=False, error_frame=error_frame\n        )",
    "docstring": "THIS IS PRIVATE AND UNSUPPORTED.\n        logs an exception that occurs inside of a Py3 method.  We only log the\n        exception once to prevent spamming the logs and we do not notify the\n        user.\n\n        frame_skip is used to change the place in the code that the error is\n        reported as coming from.  We want to show it as coming from the\n        py3status module where the Py3 method was called."
  },
  {
    "code": "def get_selected_values(self, selection):\n        return [v for b, v in self._choices if b & selection]",
    "docstring": "Return a list of values for the given selection."
  },
  {
    "code": "def attention_lm_ae_extended():\n  hparams = attention_lm_moe_base_long_seq()\n  hparams.attention_layers = \"eeee\"\n  hparams.attention_local = True\n  hparams.attention_moe_k = 2\n  hparams.attention_exp_factor = 4\n  hparams.layer_preprocess_sequence = \"n\"\n  hparams.layer_postprocess_sequence = \"da\"\n  return hparams",
    "docstring": "Experiment with the exp_factor params."
  },
  {
    "code": "def get_digests(self):\n        digests = {}\n        for registry in self.workflow.push_conf.docker_registries:\n            for image in self.workflow.tag_conf.images:\n                image_str = image.to_str()\n                if image_str in registry.digests:\n                    digest = registry.digests[image_str]\n                    digests[image.to_str(registry=False)] = digest\n        return digests",
    "docstring": "Returns a map of repositories to digests"
  },
  {
    "code": "def _add_version_to_request(self, url, headers, version):\n        if self._has_capability(SERVER_REQUIRES_VERSION_HEADER):\n            new_headers = headers.copy()\n            new_headers['Last-Modified'] = email.utils.formatdate(version)\n            return url, new_headers\n        else:\n            url_params = {\n                'last_modified': email.utils.formatdate(version)\n            }\n            new_url = url + \"?\" + urlencode(url_params)\n            return new_url, headers",
    "docstring": "Adds version to either url or headers, depending on protocol."
  },
  {
    "code": "def create_system(self, new_machine_id=False):\n        client_hostname = determine_hostname()\n        machine_id = generate_machine_id(new_machine_id)\n        branch_info = self.branch_info\n        if not branch_info:\n            return False\n        remote_branch = branch_info['remote_branch']\n        remote_leaf = branch_info['remote_leaf']\n        data = {'machine_id': machine_id,\n                'remote_branch': remote_branch,\n                'remote_leaf': remote_leaf,\n                'hostname': client_hostname}\n        if self.config.display_name is not None:\n            data['display_name'] = self.config.display_name\n        data = json.dumps(data)\n        post_system_url = self.api_url + '/v1/systems'\n        logger.debug(\"POST System: %s\", post_system_url)\n        logger.debug(data)\n        net_logger.info(\"POST %s\", post_system_url)\n        return self.session.post(post_system_url,\n                                 headers={'Content-Type': 'application/json'},\n                                 data=data)",
    "docstring": "Create the machine via the API"
  },
  {
    "code": "def add_vbar_widget(self, ref, x=1, y=1, length=10):\n        if ref not in self.widgets:\n            widget = widgets.VBarWidget(screen=self, ref=ref, x=x, y=y, length=length)\n            self.widgets[ref] = widget\n            return self.widgets[ref]",
    "docstring": "Add Vertical Bar Widget"
  },
  {
    "code": "def send(self, message, binary=False):\n        if not self.is_closed:\n            self.session.send_message(message, binary=binary)",
    "docstring": "Send message to the client.\n\n        `message`\n            Message to send."
  },
  {
    "code": "def remove_node(self, p_id, remove_unconnected_nodes=True):\n        if self.has_node(p_id):\n            for neighbor in self.incoming_neighbors(p_id):\n                self._edges[neighbor].remove(p_id)\n            neighbors = set()\n            if remove_unconnected_nodes:\n                neighbors = self.outgoing_neighbors(p_id)\n            del self._edges[p_id]\n            for neighbor in neighbors:\n                if self.is_isolated(neighbor):\n                    self.remove_node(neighbor)",
    "docstring": "Removes a node from the graph."
  },
  {
    "code": "def upgrade_cmd(argv=sys.argv[1:]):\n    arguments = docopt(upgrade_cmd.__doc__, argv=argv)\n    initialize_config(__mode__='fit')\n    upgrade(from_version=arguments['--from'], to_version=arguments['--to'])",
    "docstring": "\\\nUpgrade the database to the latest version.\n\nUsage:\n  pld-ugprade [options]\n\nOptions:\n  --from=<v>               Upgrade from a specific version, overriding\n                           the version stored in the database.\n\n  --to=<v>                 Upgrade to a specific version instead of the\n                           latest version.\n\n  -h --help                Show this screen."
  },
  {
    "code": "def _get_config_name():\n  p = subprocess.Popen('git config --get user.name', shell=True,\n                       stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n  output = p.stdout.readlines()\n  return _stripslashes(output[0])",
    "docstring": "Get git config user name"
  },
  {
    "code": "def first(self):\n        if self._first is None:\n            for target in self.targets:\n                if target is not None:\n                    self._first = target\n                    break\n            else:\n                self._first = False\n        return self._first",
    "docstring": "Returns the first module procedure embedded in the interface that has a valid\n        instance of a CodeElement."
  },
  {
    "code": "def create_tab(self, location=None):\n        eb = self._get_or_create_editor_buffer(location)\n        self.tab_pages.insert(self.active_tab_index + 1, TabPage(Window(eb)))\n        self.active_tab_index += 1",
    "docstring": "Create a new tab page."
  },
  {
    "code": "def to_ipv6(key):\n    if key[-2:] != '.k':\n        raise ValueError('Key does not end with .k')\n    key_bytes = base32.decode(key[:-2])\n    hash_one = sha512(key_bytes).digest()\n    hash_two = sha512(hash_one).hexdigest()\n    return ':'.join([hash_two[i:i+4] for i in range(0, 32, 4)])",
    "docstring": "Get IPv6 address from a public key."
  },
  {
    "code": "def _read_generated_broker_id(meta_properties_path):\n    try:\n        with open(meta_properties_path, 'r') as f:\n            broker_id = _parse_meta_properties_file(f)\n    except IOError:\n        raise IOError(\n            \"Cannot open meta.properties file: {path}\"\n            .format(path=meta_properties_path),\n        )\n    except ValueError:\n        raise ValueError(\"Broker id not valid\")\n    if broker_id is None:\n        raise ValueError(\"Autogenerated broker id missing from data directory\")\n    return broker_id",
    "docstring": "reads broker_id from meta.properties file.\n\n    :param string meta_properties_path: path for meta.properties file\n    :returns int: broker_id from meta_properties_path"
  },
  {
    "code": "def format_filter_value(self, element, value):\n        format_func = self.allowed_filter.get(element)\n        return format_func(value)",
    "docstring": "Calls the specific function to format value,\n        depending on the given element.\n\n        Arguments:\n            element (string): The element of the VT to be formatted.\n            value (dictionary): The element value.\n\n        Returns:\n            Returns a formatted value."
  },
  {
    "code": "def async_new_device_callback(self, device):\n        _LOGGING.info(\n            'New Device: %s cat: 0x%02x subcat: 0x%02x desc: %s, model: %s',\n            device.id, device.cat, device.subcat,\n            device.description, device.model)\n        for state in device.states:\n            device.states[state].register_updates(\n                self.async_state_change_callback)",
    "docstring": "Log that our new device callback worked."
  },
  {
    "code": "def sendFinalResponse(self):\n        self.requestProtocol.requestResponse[\"code\"] = (\n            self.responseCode\n        )\n        self.requestProtocol.requestResponse[\"content\"] = (\n            self.responseContent\n        )\n        self.requestProtocol.requestResponse[\"errors\"] = (\n            self.responseErrors\n        )\n        self.requestProtocol.sendFinalRequestResponse()",
    "docstring": "Send the final response and close the connection.\n\n        :return: <void>"
  },
  {
    "code": "def as_pyemu_matrix(self,typ=Matrix):\n        x = self.values.copy().astype(np.float)\n        return typ(x=x,row_names=list(self.index),\n                      col_names=list(self.columns))",
    "docstring": "Create a pyemu.Matrix from the Ensemble.\n\n        Parameters\n        ----------\n            typ : pyemu.Matrix or derived type\n                the type of matrix to return\n\n        Returns\n        -------\n        pyemu.Matrix : pyemu.Matrix"
  },
  {
    "code": "def RenderValue(value, limit_lists=-1):\n  if value is None:\n    return None\n  renderer = ApiValueRenderer.GetRendererForValueOrClass(\n      value, limit_lists=limit_lists)\n  return renderer.RenderValue(value)",
    "docstring": "Render given RDFValue as plain old python objects."
  },
  {
    "code": "def merge(self, other):\n        print \"MERGING\", self, other\n        other = self.coerce(other)\n        if self.is_contradictory(other):\n            raise Contradiction(\"Cannot merge %s and %s\" % (self, other))\n        elif self.value is None and not other.value is None:\n            self.r, self.g, self.b = other.r, other.g, other.b\n            self.value = RGBColor(self.r, self.b, self.g, rgb_type='sRGB')\n        return self",
    "docstring": "Merges the values"
  },
  {
    "code": "async def stop(self):\n        await self.node.stop(self.channel.guild.id)\n        self.queue = []\n        self.current = None\n        self.position = 0\n        self._paused = False",
    "docstring": "Stops playback from lavalink.\n\n        .. important::\n\n            This method will clear the queue."
  },
  {
    "code": "def get_web_element(self, element):\n        from toolium.pageelements.page_element import PageElement\n        if isinstance(element, WebElement):\n            web_element = element\n        elif isinstance(element, PageElement):\n            web_element = element.web_element\n        elif isinstance(element, tuple):\n            web_element = self.driver_wrapper.driver.find_element(*element)\n        else:\n            web_element = None\n        return web_element",
    "docstring": "Return the web element from a page element or its locator\n\n        :param element: either a WebElement, PageElement or element locator as a tuple (locator_type, locator_value)\n        :returns: WebElement object"
  },
  {
    "code": "def pretty_memory_info():\n    process = psutil.Process(os.getpid())\n    return '{}MB memory usage'.format(int(process.memory_info().rss / 2**20))",
    "docstring": "Pretty format memory info.\n\n    Returns\n    -------\n    str\n        Memory info.\n\n    Examples\n    --------\n    >>> pretty_memory_info()\n    '5MB memory usage'"
  },
  {
    "code": "def setup(self,\n              data,\n              view='hypergrid',\n              schema=None,\n              columns=None,\n              rowpivots=None,\n              columnpivots=None,\n              aggregates=None,\n              sort=None,\n              index='',\n              limit=-1,\n              computedcolumns=None,\n              settings=True,\n              embed=False,\n              dark=False,\n              *args,\n              **kwargs):\n        self.view = validate_view(view)\n        self.schema = schema or {}\n        self.sort = validate_sort(sort) or []\n        self.index = index\n        self.limit = limit\n        self.settings = settings\n        self.embed = embed\n        self.dark = dark\n        self.rowpivots = validate_rowpivots(rowpivots) or []\n        self.columnpivots = validate_columnpivots(columnpivots) or []\n        self.aggregates = validate_aggregates(aggregates) or {}\n        self.columns = validate_columns(columns) or []\n        self.computedcolumns = validate_computedcolumns(computedcolumns) or []\n        self.load(data)",
    "docstring": "Setup perspective base class\n\n        Arguments:\n            data : dataframe/list/dict\n                The static or live datasource\n\n        Keyword Arguments:\n            view : str or View\n                what view to use. available in the enum View (default: {'hypergrid'})\n            columns : list of str\n                what columns to display\n            rowpivots : list of str\n                what names to use as rowpivots\n            columnpivots : list of str\n                what names to use as columnpivots\n            aggregates:  dict(str: str or Aggregate)\n                dictionary of name to aggregate type (either string or enum Aggregate)\n            index : str\n                columns to use as index\n            limit : int\n                row limit\n            computedcolumns : list of dict\n                computed columns to set on the perspective viewer\n            settings : bool\n                display settings\n            settings : bool\n                embedded mode\n            dark : bool\n                use dark theme"
  },
  {
    "code": "async def apply(self, sender: str, recipient: str, mailbox: str,\n                    append_msg: AppendMessage) \\\n            -> Tuple[Optional[str], AppendMessage]:\n        ...",
    "docstring": "Run the filter and return the mailbox where it should be appended,\n        or None to discard, and the message to be appended, which is usually\n        the same as ``append_msg``.\n\n        Args:\n            sender: The envelope sender of the message.\n            recipient: The envelope recipient of the message.\n            mailbox: The intended mailbox to append the message.\n            append_msg: The message to be appended.\n\n        raises:\n            :exc:`~pymap.exceptions.AppendFailure`"
  },
  {
    "code": "def get_info(self):\n        info_response = self.send_command(\"show info\")\n        if not info_response:\n            return {}\n        def convert_camel_case(string):\n            return all_cap_re.sub(\n                r'\\1_\\2',\n                first_cap_re.sub(r'\\1_\\2', string)\n            ).lower()\n        return dict(\n            (convert_camel_case(label), value)\n            for label, value in [\n                line.split(\": \")\n                for line in info_response.split(\"\\n\")\n            ]\n        )",
    "docstring": "Parses the output of a \"show info\" HAProxy command and returns a\n        simple dictionary of the results."
  },
  {
    "code": "def egress_subnets(rid=None, unit=None):\n    def _to_range(addr):\n        if re.search(r'^(?:\\d{1,3}\\.){3}\\d{1,3}$', addr) is not None:\n            addr += '/32'\n        elif ':' in addr and '/' not in addr:\n            addr += '/128'\n        return addr\n    settings = relation_get(rid=rid, unit=unit)\n    if 'egress-subnets' in settings:\n        return [n.strip() for n in settings['egress-subnets'].split(',') if n.strip()]\n    if 'ingress-address' in settings:\n        return [_to_range(settings['ingress-address'])]\n    if 'private-address' in settings:\n        return [_to_range(settings['private-address'])]\n    return []",
    "docstring": "Retrieve the egress-subnets from a relation.\n\n    This function is to be used on the providing side of the\n    relation, and provides the ranges of addresses that client\n    connections may come from. The result is uninteresting on\n    the consuming side of a relation (unit == local_unit()).\n\n    Returns a stable list of subnets in CIDR format.\n    eg. ['192.168.1.0/24', '2001::F00F/128']\n\n    If egress-subnets is not available, falls back to using the published\n    ingress-address, or finally private-address.\n\n    :param rid: string relation id\n    :param unit: string unit name\n    :side effect: calls relation_get\n    :return: list of subnets in CIDR format. eg. ['192.168.1.0/24', '2001::F00F/128']"
  },
  {
    "code": "def _calibration_program(qc: QuantumComputer, tomo_experiment: TomographyExperiment,\n                         setting: ExperimentSetting) -> Program:\n    calibr_prog = Program()\n    readout_povm_instruction = [i for i in tomo_experiment.program.out().split('\\n') if 'PRAGMA READOUT-POVM' in i]\n    calibr_prog += readout_povm_instruction\n    kraus_instructions = [i for i in tomo_experiment.program.out().split('\\n') if 'PRAGMA ADD-KRAUS' in i]\n    calibr_prog += kraus_instructions\n    for q, op in setting.out_operator.operations_as_set():\n        calibr_prog += _one_q_pauli_prep(label=op, index=0, qubit=q)\n    for q, op in setting.out_operator.operations_as_set():\n        calibr_prog += _local_pauli_eig_meas(op, q)\n    return calibr_prog",
    "docstring": "Program required for calibration in a tomography-like experiment.\n\n    :param tomo_experiment: A suite of tomographic observables\n    :param ExperimentSetting: The particular tomographic observable to measure\n    :param symmetrize_readout: Method used to symmetrize the readout errors (see docstring for\n        `measure_observables` for more details)\n    :param cablir_shots: number of shots to take in the measurement process\n    :return: Program performing the calibration"
  },
  {
    "code": "def _call_api(self, url, method='GET', params=None, data=None):\n        req = self.session.request(\n            method=method,\n            url=url,\n            params=params,\n            headers=self.header,\n            data=data,\n            verify=not self.insecure,\n        )\n        output = None\n        try:\n            output = req.json()\n        except Exception as err:\n            LOG.debug(req.text)\n            raise Exception('Error while decoding JSON: {0}'.format(err))\n        if req.status_code != 200:\n            LOG.error(output)\n            if 'error_code' in output:\n                raise APIError(output['error'])\n        return output",
    "docstring": "Method used to call the API.\n        It returns the raw JSON returned by the API or raises an exception\n        if something goes wrong.\n\n        :arg url: the URL to call\n        :kwarg method: the HTTP method to use when calling the specified\n            URL, can be GET, POST, DELETE, UPDATE...\n            Defaults to GET\n        :kwarg params: the params to specify to a GET request\n        :kwarg data: the data to send to a POST request"
  },
  {
    "code": "def _load_client_cert_chain(keychain, *paths):\n    certificates = []\n    identities = []\n    paths = (path for path in paths if path)\n    try:\n        for file_path in paths:\n            new_identities, new_certs = _load_items_from_file(\n                keychain, file_path\n            )\n            identities.extend(new_identities)\n            certificates.extend(new_certs)\n        if not identities:\n            new_identity = Security.SecIdentityRef()\n            status = Security.SecIdentityCreateWithCertificate(\n                keychain,\n                certificates[0],\n                ctypes.byref(new_identity)\n            )\n            _assert_no_error(status)\n            identities.append(new_identity)\n            CoreFoundation.CFRelease(certificates.pop(0))\n        trust_chain = CoreFoundation.CFArrayCreateMutable(\n            CoreFoundation.kCFAllocatorDefault,\n            0,\n            ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n        )\n        for item in itertools.chain(identities, certificates):\n            CoreFoundation.CFArrayAppendValue(trust_chain, item)\n        return trust_chain\n    finally:\n        for obj in itertools.chain(identities, certificates):\n            CoreFoundation.CFRelease(obj)",
    "docstring": "Load certificates and maybe keys from a number of files. Has the end goal\n    of returning a CFArray containing one SecIdentityRef, and then zero or more\n    SecCertificateRef objects, suitable for use as a client certificate trust\n    chain."
  },
  {
    "code": "def expand(template_str, dictionary, **kwargs):\n    t = Template(template_str, **kwargs)\n    return t.expand(dictionary)",
    "docstring": "Free function to expands a template string with a data dictionary.\n\n  This is useful for cases where you don't care about saving the result of\n  compilation (similar to re.match('.*', s) vs DOT_STAR.match(s))"
  },
  {
    "code": "def _ReadN(self, n):\n    ret = \"\"\n    while True:\n      chunk = self._read_file.read(n - len(ret))\n      ret += chunk\n      if len(ret) == n or not chunk:\n        return ret",
    "docstring": "Reads n characters from the input stream, or until EOF.\n\n    This is equivalent to the current CPython implementation of read(n), but\n    not guaranteed by the docs.\n\n    Args:\n      n: int\n\n    Returns:\n      string"
  },
  {
    "code": "def wrap_constant(self, val):\n        from .queries import QueryBuilder\n        if isinstance(val, (Term, QueryBuilder, Interval)):\n            return val\n        if val is None:\n            return NullValue()\n        if isinstance(val, list):\n            return Array(*val)\n        if isinstance(val, tuple):\n            return Tuple(*val)\n        _ValueWrapper = getattr(self, '_wrapper_cls', ValueWrapper)\n        return _ValueWrapper(val)",
    "docstring": "Used for wrapping raw inputs such as numbers in Criterions and Operator.\n\n        For example, the expression F('abc')+1 stores the integer part in a ValueWrapper object.\n\n        :param val:\n            Any value.\n        :return:\n            Raw string, number, or decimal values will be returned in a ValueWrapper.  Fields and other parts of the\n            querybuilder will be returned as inputted."
  },
  {
    "code": "async def remove_items(self, *items):\n    items = [i.id for i in (await self.process(items)) if i in self.items]\n    if not items:\n      return\n    await self.connector.delete(\n      'Playlists/{Id}/Items'.format(Id=self.id),\n      EntryIds=','.join(items),\n      remote=False\n    )",
    "docstring": "remove items from the playlist\n\n    |coro|\n\n    Parameters\n    ----------\n    items : array_like\n      list of items to remove(or their ids)\n\n    See Also\n    --------\n      add_items :"
  },
  {
    "code": "def get(self, source_id=None, profile_id=None, profile_reference=None, filter_id=None, filter_reference=None):\n        query_params = {}\n        query_params[\"source_id\"] = _validate_source_id(source_id)\n        if profile_id:\n            query_params[\"profile_id\"] = _validate_profile_id(profile_id)\n        if profile_reference:\n            query_params[\"profile_reference\"] = _validate_profile_reference(profile_reference)\n        if filter_id:\n            query_params[\"filter_id\"] = _validate_filter_id(filter_id)\n        if filter_reference:\n            query_params[\"filter_reference\"] = _validate_filter_reference(filter_reference)\n        response = self.client.get('profile/revealing', query_params)\n        return response",
    "docstring": "Retrieve the interpretability information.\n\n        Args:\n            source_id:              <string>\n                                    source id\n            profile_id:             <string>\n                                    profile id\n            filter_id:              <string>\n                                    filter id\n\n        Returns\n            interpretability information"
  },
  {
    "code": "def join(self, source, op='LEFT JOIN', on=''):\n        if isinstance(source, SQLConstructor):\n            (sql, params, _) = source.compile()\n            self.join_params.extend(params)\n            jsrc = '( {0} )'.format(sql)\n            if source.table_alias:\n                jsrc += ' AS ' + source.table_alias\n                on = on.format(r=source.table_alias)\n        else:\n            jsrc = source\n            on = on.format(r=source)\n        constraint = 'ON {0}'.format(on) if on else ''\n        self.join_source = ' '.join([self.join_source, op, jsrc, constraint])",
    "docstring": "Join `source`.\n\n        >>> sc = SQLConstructor('main', ['c1', 'c2'])\n        >>> sc.join('sub', 'JOIN', 'main.id = sub.id')\n        >>> (sql, params, keys) = sc.compile()\n        >>> sql\n        'SELECT c1, c2 FROM main JOIN sub ON main.id = sub.id'\n\n        It is possible to pass another `SQLConstructor` as a source.\n\n        >>> sc = SQLConstructor('main', ['c1', 'c2'])\n        >>> sc.add_or_matches('{0} = {1}', 'c1', [111])\n        >>> subsc = SQLConstructor('sub', ['d1', 'd2'])\n        >>> subsc.add_or_matches('{0} = {1}', 'd1', ['abc'])\n        >>> sc.join(subsc, 'JOIN', 'main.id = sub.id')\n        >>> sc.add_column('d1')\n        >>> (sql, params, keys) = sc.compile()\n        >>> print(sql)                     # doctest: +NORMALIZE_WHITESPACE\n        SELECT c1, c2, d1 FROM main\n        JOIN ( SELECT d1, d2 FROM sub WHERE (d1 = ?) )\n        ON main.id = sub.id\n        WHERE (c1 = ?)\n\n        `params` is set appropriately to include parameters for joined\n        source:\n\n        >>> params\n        ['abc', 111]\n\n        Note that `subsc.compile` is called when `sc.join(subsc, ...)`\n        is called.  Therefore, calling `subsc.add_<predicate>` does not\n        effect `sc`.\n\n        :type source: str or SQLConstructor\n        :arg  source: table\n        :type     op: str\n        :arg      op: operation (e.g., 'JOIN')\n        :type     on: str\n        :arg      on: on clause.  `source` (\"right\" source) can be\n                      referred using `{r}` formatting field."
  },
  {
    "code": "def sasml(self) -> 'SASml':\n        if not self._loaded_macros:\n            self._loadmacros()\n            self._loaded_macros = True\n        return SASml(self)",
    "docstring": "This methods creates a SASML object which you can use to run various analytics. See the sasml.py module.\n\n        :return: sasml object"
  },
  {
    "code": "def _validate_state(state, valid_states):\n    if state in State:\n        return state.name\n    elif state in valid_states:\n        return state\n    else:\n        raise Invalid('Invalid state')",
    "docstring": "Validate a state string"
  },
  {
    "code": "def background_color(self):\n        if self._has_real():\n            return self._data.real_background_color\n        return self._data.background_color",
    "docstring": "Background color."
  },
  {
    "code": "def discover_base_dir(start_dir):\n    if is_base_dir(start_dir):\n        return start_dir\n    pcl = start_dir.split('/')\n    found_base_dir = None\n    for i in range(1, len(pcl)+1):\n        d2c = '/'.join(pcl[:-i])\n        if (d2c == ''):\n            d2c = '/'\n        if is_base_dir(d2c):\n            found_base_dir = d2c\n            break\n    return found_base_dir",
    "docstring": "Return start_dir or the parent dir that has the s2 marker.\n\n    Starting from the specified directory, and going up the parent\n    chain, check each directory to see if it's a base_dir (contains\n    the \"marker\" directory *s2*) and return it. Otherwise, return\n    the start_dir."
  },
  {
    "code": "def get_attrs(self, *names):\n        attrs = [getattr(self, name) for name in names]\n        return attrs",
    "docstring": "Get multiple attributes from multiple objects."
  },
  {
    "code": "def venue_healthcheck(self):\n        url = urljoin(self.base_url, 'venues/TESTEX/heartbeat')\n        return self.session.get(url).json()['ok']",
    "docstring": "Check A Venue Is Up.\n\n        https://starfighter.readme.io/docs/venue-healthcheck"
  },
  {
    "code": "def set_data_location(apps, schema_editor):\n    Data = apps.get_model('flow', 'Data')\n    DataLocation = apps.get_model('flow', 'DataLocation')\n    for data in Data.objects.all():\n        if os.path.isdir(os.path.join(settings.FLOW_EXECUTOR['DATA_DIR'], str(data.id))):\n            with transaction.atomic():\n                data_location = DataLocation.objects.create(id=data.id, subpath=str(data.id))\n                data_location.data.add(data)\n    if DataLocation.objects.exists():\n        max_id = DataLocation.objects.order_by('id').last().id\n        with connection.cursor() as cursor:\n            cursor.execute(\n                \"ALTER SEQUENCE flow_datalocation_id_seq RESTART WITH {};\".format(max_id + 1)\n            )",
    "docstring": "Create DataLocation for each Data."
  },
  {
    "code": "def state_not_literal(self, value):\n        value = negate = chr(value)\n        while value == negate:\n            value = choice(self.literals)\n        yield value",
    "docstring": "Parse not literal."
  },
  {
    "code": "def function_exists(self, fun):\n        res = fun in self._rule_functions\n        self.say('function exists:' + str(fun) + ':' + str(res),\n                 verbosity=10)\n        return res",
    "docstring": "get function's existense"
  },
  {
    "code": "def write_bits(self, *args):\n        if len(args) > 8:\n            raise ValueError(\"Can only write 8 bits at a time\")\n        self._output_buffer.append(chr(\n            reduce(lambda x, y: xor(x, args[y] << y), xrange(len(args)), 0)))\n        return self",
    "docstring": "Write multiple bits in a single byte field. The bits will be written in\n        little-endian order, but should be supplied in big endian order. Will\n        raise ValueError when more than 8 arguments are supplied.\n\n        write_bits(True, False) => 0x02"
  },
  {
    "code": "def _parse_current_member(self, previous_rank, values):\n        rank, name, vocation, level, joined, status = values\n        rank = previous_rank[1] if rank == \" \" else rank\n        title = None\n        previous_rank[1] = rank\n        m = title_regex.match(name)\n        if m:\n            name = m.group(1)\n            title = m.group(2)\n        self.members.append(GuildMember(name, rank, title, int(level), vocation, joined=joined,\n                                        online=status == \"online\"))",
    "docstring": "Parses the column texts of a member row into a member dictionary.\n\n        Parameters\n        ----------\n        previous_rank: :class:`dict`[int, str]\n            The last rank present in the rows.\n        values: tuple[:class:`str`]\n            A list of row contents."
  },
  {
    "code": "def ReadPermission(self, permission_link, options=None):\n        if options is None:\n            options = {}\n        path = base.GetPathFromLink(permission_link)\n        permission_id = base.GetResourceIdOrFullNameFromLink(permission_link)\n        return self.Read(path,\n                         'permissions',\n                          permission_id,\n                          None,\n                          options)",
    "docstring": "Reads a permission.\n\n        :param str permission_link:\n            The link to the permission.\n        :param dict options:\n            The request options for the request.\n\n        :return:\n            The read permission.\n        :rtype:\n            dict"
  },
  {
    "code": "def find_root(self):\n        cmd = self\n        while cmd.parent:\n            cmd = cmd.parent\n        return cmd",
    "docstring": "Traverse parent refs to top."
  },
  {
    "code": "def print_command(command: List[str], fname: str):\n    with open(fname, \"w\", encoding=\"utf-8\") as out:\n        print(\" \\\\\\n\".join(command), file=out)",
    "docstring": "Format and print command to file.\n\n    :param command: Command in args list form.\n    :param fname: File name to write out."
  },
  {
    "code": "def module_import(module_path):\n    try:\n        module = __import__(module_path)\n        components = module_path.split('.')\n        for component in components[1:]:\n            module = getattr(module, component)\n        return module\n    except ImportError:\n        raise BadModulePathError(\n            'Unable to find module \"%s\".' % (module_path,))",
    "docstring": "Imports the module indicated in name\n\n    Args:\n        module_path: string representing a module path such as\n        'app.config' or 'app.extras.my_module'\n    Returns:\n        the module matching name of the last component, ie: for\n        'app.extras.my_module' it returns a\n        reference to my_module\n    Raises:\n        BadModulePathError if the module is not found"
  },
  {
    "code": "def _set_pseudotime(self):\n        self.pseudotime = self.distances_dpt[self.iroot].copy()\n        self.pseudotime /= np.max(self.pseudotime[self.pseudotime < np.inf])",
    "docstring": "Return pseudotime with respect to root point."
  },
  {
    "code": "def _max_lengths():\n    max_header_length = max([len(x.byte_match) + x.offset\n                             for x in magic_header_array])\n    max_footer_length = max([len(x.byte_match) + abs(x.offset)\n                             for x in magic_footer_array])\n    return max_header_length, max_footer_length",
    "docstring": "The length of the largest magic string + its offset"
  },
  {
    "code": "def _clean_dict(target_dict, whitelist=None):\n    assert isinstance(target_dict, dict)\n    return {\n        ustr(k).strip(): ustr(v).strip()\n        for k, v in target_dict.items()\n        if v not in (None, Ellipsis, [], (), \"\")\n        and (not whitelist or k in whitelist)\n    }",
    "docstring": "Convenience function that removes a dicts keys that have falsy values"
  },
  {
    "code": "def map_version(self, requirement, local_version):\n        if isinstance(self._versions_map, dict):\n            version = self._versions_map.get(requirement, {}).get(\n                local_version, local_version)\n        else:\n            version = self._versions_map(requirement, local_version)\n        return version",
    "docstring": "Maps a local version name to one recognised by the Requirement class\n\n        Parameters\n        ----------\n        requirement : str\n            Name of the requirement\n        version : str\n            version string"
  },
  {
    "code": "def sample_correlations(self):\n        C = np.corrcoef(self.X.T)\n        corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C)\n        return corr_matrix",
    "docstring": "Returns an `ExpMatrix` containing all pairwise sample correlations.\n\n        Returns\n        -------\n        `ExpMatrix`\n            The sample correlation matrix."
  },
  {
    "code": "def assign(self, key, value):\n        key_split = key.split('.')\n        cur_dict = self\n        for k in key_split[:-1]:\n            try:\n                cur_dict = cur_dict[k]\n            except KeyError:\n                cur_dict[k] = self.__class__()\n                cur_dict = cur_dict[k]\n        cur_dict[key_split[-1]] = value",
    "docstring": "an alternative method for assigning values to nested DotDict\n        instances.  It accepts keys in the form of X.Y.Z.  If any nested\n        DotDict instances don't yet exist, they will be created."
  },
  {
    "code": "def publish_event(self, data, suffix=''):\n        try:\n            event_type = data.pop('event_type')\n        except KeyError:\n            return {'result': 'error', 'message': 'Missing event_type in JSON data'}\n        return self.publish_event_from_dict(event_type, data)",
    "docstring": "AJAX handler to allow client-side code to publish a server-side event"
  },
  {
    "code": "def encode_quorum(self, rw):\n        if rw in QUORUM_TO_PB:\n            return QUORUM_TO_PB[rw]\n        elif type(rw) is int and rw >= 0:\n            return rw\n        else:\n            return None",
    "docstring": "Converts a symbolic quorum value into its on-the-wire\n        equivalent.\n\n        :param rw: the quorum\n        :type rw: string, integer\n        :rtype: integer"
  },
  {
    "code": "def _crossProduct( self, ls ):\n        p = ls[0]\n        ds = []\n        if len(ls) == 1:\n            for i in self._parameters[p]:\n                dp = dict()\n                dp[p] = i\n                ds.append(dp)\n        else:\n            ps = self._crossProduct(ls[1:])\n            for i in self._parameters[p]:\n                for d in ps:\n                    dp = d.copy()\n                    dp[p] = i\n                    ds.append(dp)\n        return ds",
    "docstring": "Internal method to generate the cross product of all parameter\n        values, creating the parameter space for the experiment.\n\n        :param ls: an array of parameter names\n        :returns: list of dicts"
  },
  {
    "code": "def _filter_attribute(mcs, attribute_name, attribute_value):\n        if attribute_name == '__module__':\n            return True\n        elif hasattr(attribute_value, '_trace_disable'):\n            return True\n        return False",
    "docstring": "decides whether the given attribute should be excluded from tracing or not"
  },
  {
    "code": "def parse_requirements(\n    filename,\n    finder=None,\n    comes_from=None,\n    options=None,\n    session=None,\n    constraint=False,\n    wheel_cache=None,\n    use_pep517=None\n):\n    if session is None:\n        raise TypeError(\n            \"parse_requirements() missing 1 required keyword argument: \"\n            \"'session'\"\n        )\n    _, content = get_file_content(\n        filename, comes_from=comes_from, session=session\n    )\n    lines_enum = preprocess(content, options)\n    for line_number, line in lines_enum:\n        req_iter = process_line(line, filename, line_number, finder,\n                                comes_from, options, session, wheel_cache,\n                                use_pep517=use_pep517, constraint=constraint)\n        for req in req_iter:\n            yield req",
    "docstring": "Parse a requirements file and yield InstallRequirement instances.\n\n    :param filename:    Path or url of requirements file.\n    :param finder:      Instance of pip.index.PackageFinder.\n    :param comes_from:  Origin description of requirements.\n    :param options:     cli options.\n    :param session:     Instance of pip.download.PipSession.\n    :param constraint:  If true, parsing a constraint file rather than\n        requirements file.\n    :param wheel_cache: Instance of pip.wheel.WheelCache\n    :param use_pep517:  Value of the --use-pep517 option."
  },
  {
    "code": "def find_and_fire_hook(event_name, instance, user_override=None):\n    try:\n        from django.contrib.auth import get_user_model\n        User = get_user_model()\n    except ImportError:\n        from django.contrib.auth.models import User\n    from rest_hooks.models import HOOK_EVENTS\n    if not event_name in HOOK_EVENTS.keys():\n        raise Exception(\n            '\"{}\" does not exist in `settings.HOOK_EVENTS`.'.format(event_name)\n        )\n    filters = {'event': event_name}\n    if user_override is not False:\n        if user_override:\n            filters['user'] = user_override\n        elif hasattr(instance, 'user'):\n            filters['user'] = instance.user\n        elif isinstance(instance, User):\n            filters['user'] = instance\n        else:\n            raise Exception(\n                '{} has no `user` property. REST Hooks needs this.'.format(repr(instance))\n            )\n    HookModel = get_hook_model()\n    hooks = HookModel.objects.filter(**filters)\n    for hook in hooks:\n        hook.deliver_hook(instance)",
    "docstring": "Look up Hooks that apply"
  },
  {
    "code": "def filtering(queryset, query_dict):\n        for key, value in query_dict.items():\n            assert hasattr(queryset, key), \"Parameter 'query_dict' contains\"\\\n                                           \" non-existent attribute.\"\n            if isinstance(value, list):\n                queryset = getattr(queryset, key)(*value)\n            elif isinstance(value, dict):\n                queryset = getattr(queryset, key)(**value)\n            else:\n                queryset = getattr(queryset, key)(value)\n        return queryset",
    "docstring": "function to apply the pre search condition to the queryset to narrow\n        down the queryset's size\n\n        :param queryset: Django Queryset: queryset of all objects\n        :param query_dict: dict: contains selected_related, filter and other\n          customized filter functions\n        :return: queryset: result after applying the pre search condition dict"
  },
  {
    "code": "def redo(self, channel, image):\n        self._image = None\n        info = channel.extdata._header_info\n        self.set_header(info, image)",
    "docstring": "This is called when image changes."
  },
  {
    "code": "def check_picture(file_name, mediainfo_path=None):\n    D = call_MediaInfo(file_name, mediainfo_path)\n    if (\n        (\"Image\" not in D) or\n        (\"Width\" not in D[\"Image\"]) or\n        (\"Height\" not in D[\"Image\"])\n    ):\n        raise MediaInfoError(\"Could not determine all picture paramters\")\n    return D",
    "docstring": "Scans the given file with MediaInfo and returns the picture\n    information if all the required parameters were found."
  },
  {
    "code": "def _parse_to_recoverable_signature(sig):\n    assert isinstance(sig, bytes)\n    assert len(sig) == 65\n    rec_sig = ffi.new(\"secp256k1_ecdsa_recoverable_signature *\")\n    recid = ord(sig[64:65])\n    parsable_sig = lib.secp256k1_ecdsa_recoverable_signature_parse_compact(\n        ctx,\n        rec_sig,\n        sig,\n        recid\n    )\n    if not parsable_sig:\n        raise InvalidSignatureError()\n    return rec_sig",
    "docstring": "Returns a parsed recoverable signature of length 65 bytes"
  },
  {
    "code": "def available_composite_ids(self, available_datasets=None):\n        if available_datasets is None:\n            available_datasets = self.available_dataset_ids(composites=False)\n        else:\n            if not all(isinstance(ds_id, DatasetID) for ds_id in available_datasets):\n                raise ValueError(\n                    \"'available_datasets' must all be DatasetID objects\")\n        all_comps = self.all_composite_ids()\n        comps, mods = self.cpl.load_compositors(self.attrs['sensor'])\n        dep_tree = DependencyTree(self.readers, comps, mods)\n        dep_tree.find_dependencies(set(available_datasets + all_comps))\n        available_comps = set(x.name for x in dep_tree.trunk())\n        return sorted(available_comps & set(all_comps))",
    "docstring": "Get names of compositors that can be generated from the available datasets.\n\n        Returns: generator of available compositor's names"
  },
  {
    "code": "def min_count(self, n=1):\n    word_count = {w:c for w,c in iteritems(self.word_count) if c >= n}\n    return CountedVocabulary(word_count=word_count)",
    "docstring": "Returns a vocabulary after eliminating the words that appear < `n`.\n\n    Args:\n      n (integer): specifies the minimum word frequency allowed."
  },
  {
    "code": "def is_transition_matrix(T, tol=1e-10):\n    if T.ndim != 2:\n        return False\n    if T.shape[0] != T.shape[1]:\n        return False\n    dim = T.shape[0]\n    X = np.abs(T) - T\n    x = np.sum(T, axis=1)\n    return np.abs(x - np.ones(dim)).max() < dim * tol and X.max() < 2.0 * tol",
    "docstring": "Tests whether T is a transition matrix\n\n    Parameters\n    ----------\n    T : ndarray shape=(n, n)\n        matrix to test\n    tol : float\n        tolerance to check with\n\n    Returns\n    -------\n    Truth value : bool\n        True, if all elements are in interval [0, 1]\n            and each row of T sums up to 1.\n        False, otherwise"
  },
  {
    "code": "def InteractiveShell(self, cmd=None, strip_cmd=True, delim=None, strip_delim=True):\n        conn = self._get_service_connection(b'shell:')\n        return self.protocol_handler.InteractiveShellCommand(\n            conn, cmd=cmd, strip_cmd=strip_cmd,\n            delim=delim, strip_delim=strip_delim)",
    "docstring": "Get stdout from the currently open interactive shell and optionally run a command\n            on the device, returning all output.\n\n        Args:\n          cmd: Optional. Command to run on the target.\n          strip_cmd: Optional (default True). Strip command name from stdout.\n          delim: Optional. Delimiter to look for in the output to know when to stop expecting more output\n          (usually the shell prompt)\n          strip_delim: Optional (default True): Strip the provided delimiter from the output\n\n        Returns:\n          The stdout from the shell command."
  },
  {
    "code": "def _expire(self):\n        del self.map.addr[self.name]\n        self.map.notify(\"addrmap_expired\", *[self.name], **{})",
    "docstring": "callback done via callLater"
  },
  {
    "code": "def apply(self, reboot=False):\n        self.root.use_virtual_addresses = True\n        self.root.manage.manage = True\n        self.root.mode = 'new'\n        self.root.init_boot = reboot\n        self.client.set_profile(self.root.get_json())",
    "docstring": "Apply the configuration to iRMC."
  },
  {
    "code": "def format_field(self, field):\n        if field is None:\n            return \"NULL\"\n        elif isinstance(field, TypeError):\n            return \"TypeError\"\n        elif isinstance(field, Decimal):\n            if field % 1 == 0:\n                return str(int(field))\n            return str(float(field))\n        elif isinstance(field, set):\n            return \"(\" + \", \".join([self.format_field(v) for v in field]) + \")\"\n        elif isinstance(field, datetime):\n            return field.isoformat()\n        elif isinstance(field, timedelta):\n            rd = relativedelta(\n                seconds=int(field.total_seconds()), microseconds=field.microseconds\n            )\n            return delta_to_str(rd)\n        elif isinstance(field, Binary):\n            return \"<Binary %d>\" % len(field.value)\n        pretty = repr(field)\n        if pretty.startswith(\"u'\"):\n            return pretty[1:]\n        return pretty",
    "docstring": "Format a single Dynamo value"
  },
  {
    "code": "def fit_transform(self, X, y=None, **fit_params):\n        y = column_or_1d(X, warn=True)\n        _check_numpy_unicode_bug(X)\n        self.classes_, X = np.unique(X, return_inverse=True)\n        return X",
    "docstring": "Fit label encoder and return encoded labels\n\n        Parameters\n        ----------\n        y : array-like of shape [n_samples]\n            Target values.\n\n        Returns\n        -------\n        y : array-like of shape [n_samples]"
  },
  {
    "code": "def generate_hypergraph(num_nodes, num_edges, r = 0):\n    random_graph = hypergraph()\n    nodes = list(map(str, list(range(num_nodes))))\n    random_graph.add_nodes(nodes)\n    edges = list(map(str, list(range(num_nodes, num_nodes+num_edges))))\n    random_graph.add_hyperedges(edges)\n    if 0 == r:\n        for e in edges:\n            for n in nodes:\n                if choice([True, False]):\n                    random_graph.link(n, e)\n    else:\n        for e in edges:\n            shuffle(nodes)\n            for i in range(r):\n                random_graph.link(nodes[i], e)\n    return random_graph",
    "docstring": "Create a random hyper graph.\n    \n    @type  num_nodes: number\n    @param num_nodes: Number of nodes.\n    \n    @type  num_edges: number\n    @param num_edges: Number of edges.\n    \n    @type  r: number\n    @param r: Uniform edges of size r."
  },
  {
    "code": "def updateDynamics(self):\n        history_vars_string = ''\n        arg_names = list(getArgNames(self.calcDynamics))\n        if 'self' in arg_names:\n            arg_names.remove('self')\n        for name in arg_names:\n            history_vars_string += ' \\'' + name + '\\' : self.' + name + '_hist,'\n        update_dict = eval('{' + history_vars_string + '}')\n        dynamics = self.calcDynamics(**update_dict)\n        for var_name in self.dyn_vars:\n            this_obj = getattr(dynamics,var_name)\n            for this_type in self.agents:\n                setattr(this_type,var_name,this_obj)\n        return dynamics",
    "docstring": "Calculates a new \"aggregate dynamic rule\" using the history of variables\n        named in track_vars, and distributes this rule to AgentTypes in agents.\n\n        Parameters\n        ----------\n        none\n\n        Returns\n        -------\n        dynamics : instance\n            The new \"aggregate dynamic rule\" that agents believe in and act on.\n            Should have attributes named in dyn_vars."
  },
  {
    "code": "def stop_condition(self, condition):\n        for cond_format in self._known_conditions:\n            try:\n                cond = cond_format.FromString(condition)\n                self.stop_conditions.append(cond)\n                return\n            except ArgumentError:\n                continue\n        raise ArgumentError(\"Stop condition could not be processed by any known StopCondition type\", condition=condition, suggestion=\"It may be mistyped or otherwise invalid.\")",
    "docstring": "Add a stop condition to this simulation.\n\n        Stop conditions are specified as strings and parsed into\n        the appropriate internal structures.\n\n        Args:\n            condition (str): a string description of the stop condition"
  },
  {
    "code": "def _get_jar_fp(self):\n        if os.path.exists(self._command):\n            return self._command\n        elif 'RDP_JAR_PATH' in environ:\n            return getenv('RDP_JAR_PATH')\n        else:\n            return None",
    "docstring": "Returns the full path to the JAR file.\n\n        If the JAR file cannot be found in the current directory and\n        the environment variable RDP_JAR_PATH is not set, returns\n        None."
  },
  {
    "code": "def _get_lb(self, lb_or_id):\n        if isinstance(lb_or_id, CloudLoadBalancer):\n            ret = lb_or_id\n        else:\n            ret = self.get(lb_or_id)\n        return ret",
    "docstring": "Accepts either a loadbalancer or the ID of a loadbalancer, and returns\n        the CloudLoadBalancer instance."
  },
  {
    "code": "def IsFile(self):\n    if self._stat_object is None:\n      self._stat_object = self._GetStat()\n    if self._stat_object is not None:\n      self.entry_type = self._stat_object.type\n    return self.entry_type == definitions.FILE_ENTRY_TYPE_FILE",
    "docstring": "Determines if the file entry is a file.\n\n    Returns:\n      bool: True if the file entry is a file."
  },
  {
    "code": "def update_utxoset(self, transaction):\n        spent_outputs = [\n            spent_output for spent_output in transaction.spent_outputs\n        ]\n        if spent_outputs:\n            self.delete_unspent_outputs(*spent_outputs)\n        self.store_unspent_outputs(\n            *[utxo._asdict() for utxo in transaction.unspent_outputs]\n        )",
    "docstring": "Update the UTXO set given ``transaction``. That is, remove\n        the outputs that the given ``transaction`` spends, and add the\n        outputs that the given ``transaction`` creates.\n\n        Args:\n            transaction (:obj:`~bigchaindb.models.Transaction`): A new\n                transaction incoming into the system for which the UTXO\n                set needs to be updated."
  },
  {
    "code": "def score(ID, sign, lon):\n    info = getInfo(sign, lon)\n    dignities = [dign for (dign, objID) in info.items() if objID == ID]\n    return sum([SCORES[dign] for dign in dignities])",
    "docstring": "Returns the score of an object on\n    a sign and longitude."
  },
  {
    "code": "def phrase_replace(self, replace_dict):\n        def r(tokens):\n                text = ' ' + ' '.join(tokens)\n                for k, v in replace_dict.items():                    \n                    text = text.replace(\" \" + k + \" \", \" \" + v + \" \")\n                return text.split()\n        self.stems = list(map(r, self.stems))",
    "docstring": "Replace phrases with single token, mapping defined in replace_dict"
  },
  {
    "code": "def add_f77_to_env(env):\n    try:\n        F77Suffixes = env['F77FILESUFFIXES']\n    except KeyError:\n        F77Suffixes = ['.f77']\n    try:\n        F77PPSuffixes = env['F77PPFILESUFFIXES']\n    except KeyError:\n        F77PPSuffixes = []\n    DialectAddToEnv(env, \"F77\", F77Suffixes, F77PPSuffixes)",
    "docstring": "Add Builders and construction variables for f77 to an Environment."
  },
  {
    "code": "def run_id(self):\n        s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', self.__class__.__name__)\n        return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()",
    "docstring": "Run name without whitespace"
  },
  {
    "code": "def logon():\n    session = requests.session()\n    payload = {\"jsonrpc\": \"2.0\",\n               \"id\": \"ID0\",\n               \"method\": \"login\",\n               \"params\": [DETAILS['username'], DETAILS['password'], DETAILS['auth'], True]\n               }\n    logon_response = session.post(DETAILS['url'], data=json.dumps(payload), verify=False)\n    if logon_response.status_code != 200:\n        log.error(\"Error logging into proxy. HTTP Error code: %s\",\n                  logon_response.status_code)\n        raise salt.exceptions.CommandExecutionError(\n            \"Did not receive a valid response from host.\")\n    try:\n        cookies = {'sslng_csrf_token': logon_response.cookies['sslng_csrf_token'],\n                   'sslng_session_id': logon_response.cookies['sslng_session_id']}\n        csrf_token = logon_response.cookies['sslng_csrf_token']\n    except KeyError:\n        log.error(\"Unable to authentication to the bluecoat_sslv proxy.\")\n        raise salt.exceptions.CommandExecutionError(\n            \"Did not receive a valid response from host.\")\n    return session, cookies, csrf_token",
    "docstring": "Logs into the bluecoat_sslv device and returns the session cookies."
  },
  {
    "code": "def percentile(values=None, percentile=None):\n    if values in [None, tuple(), []] or len(values) < 1:\n        raise InsufficientData(\n            \"Expected a sequence of at least 1 integers, got {0!r}\".format(values))\n    if percentile is None:\n        raise ValueError(\"Expected a percentile choice, got {0}\".format(percentile))\n    sorted_values = sorted(values)\n    rank = len(values) * percentile / 100\n    if rank > 0:\n        index = rank - 1\n        if index < 0:\n            return sorted_values[0]\n    else:\n        index = rank\n    if index % 1 == 0:\n        return sorted_values[int(index)]\n    else:\n        fractional = index % 1\n        integer = int(index - fractional)\n        lower = sorted_values[integer]\n        higher = sorted_values[integer + 1]\n        return lower + fractional * (higher - lower)",
    "docstring": "Calculates a simplified weighted average percentile"
  },
  {
    "code": "def validate_type(prop, value, expected):\n    if value is not None and not isinstance(value, expected):\n        _validation_error(prop, type(value).__name__, None, expected)",
    "docstring": "Default validation for all types"
  },
  {
    "code": "def structs2pandas(structs):\n    try:\n        import pandas\n        records = list(structs2records(structs))\n        df = pandas.DataFrame.from_records(records)\n        if 'id' in df:\n            df[\"id\"] = df[\"id\"].apply(str.rstrip)\n        return df\n    except ImportError:\n        return structs",
    "docstring": "convert ctypes structure or structure array to pandas data frame"
  },
  {
    "code": "def _influxdb_url(self):\n        url = \"{0}/db/{1}/series\".format(self.influxdb.url.rstrip('/'), self.config.dbname)\n        if self.influxdb.user and self.influxdb.password:\n            url += \"?u={0}&p={1}\".format(self.influxdb.user, self.influxdb.password)\n        return url",
    "docstring": "Return REST API URL to access time series."
  },
  {
    "code": "def Bmatrix(C):\n    L, Q = eigh(C)\n    minL = 1e-9*L[-1]\n    L[L < minL] = minL\n    S = np.diag(1 / np.sqrt(L))\n    B = Q.dot(S)\n    return B",
    "docstring": "Calculate a matrix which is effectively the square root of the correlation matrix C\n\n\n    Parameters\n    ----------\n    C : 2d array\n        A covariance matrix\n\n    Returns\n    -------\n    B : 2d array\n        A matrix B such the B.dot(B') = inv(C)"
  },
  {
    "code": "def get_comments(self, sharekey=None):\n        if not sharekey:\n            raise Exception(\n                \"You must specify a sharekey of the file you\"\n                \"want to 'like'.\")\n        endpoint = '/api/sharedfile/{0}/comments'.format(sharekey)\n        data = self._make_request(\"GET\", endpoint=endpoint)\n        return [Comment.NewFromJSON(c) for c in data['comments']]",
    "docstring": "Retrieve comments on a SharedFile\n\n        Args:\n            sharekey (str): Sharekey for the file from which you want to return\n                the set of comments.\n\n        Returns:\n            List of Comment objects."
  },
  {
    "code": "def dependencies_as_list(self):\n        dependencies = []\n        for dependency in self.dependencies:\n            dependencies.append(dependency.name)\n        return dependencies",
    "docstring": "Returns a list of dependency names."
  },
  {
    "code": "def get_gains_losses(changes):\n    res = {'gains': [], 'losses': []}\n    for change in changes:\n        if change > 0:\n            res['gains'].append(change)\n        else:\n            res['losses'].append(change * -1)\n    logger.debug('Gains: {0}'.format(res['gains']))\n    logger.debug('Losses: {0}'.format(res['losses']))\n    return res",
    "docstring": "Categorizes changes into gains and losses\n\n    Args:\n        changes: List of floats of price changes between entries in JSON.\n\n    Returns:\n        Dict of changes with keys 'gains' and 'losses'.\n        All values are positive."
  },
  {
    "code": "def urlretrieve(url, dest, write_mode=\"w\"):\n    response = urllib2.urlopen(url)\n    mkdir_recursive(os.path.dirname(dest))\n    with open(dest, write_mode) as f:\n        f.write(response.read())\n        f.close()",
    "docstring": "save a file to disk from a given url"
  },
  {
    "code": "def upload(client, source_dir):\n    print('')\n    print('upload store listings')\n    print('---------------------')\n    listings_folder = os.path.join(source_dir, 'listings')\n    langfolders = filter(os.path.isdir, list_dir_abspath(listings_folder))\n    for language_dir in langfolders:\n        language = os.path.basename(language_dir)\n        with open(os.path.join(language_dir, 'listing.json')) as listings_file:\n            listing = json.load(listings_file)\n        listing_response = client.update(\n            'listings', language=language, body=listing)\n        print('  Listing for language %s was updated.' %\n              listing_response['language'])",
    "docstring": "Upload listing files in source_dir. folder herachy."
  },
  {
    "code": "def from_coffeescript(cls, func, v_func, args={}):\n        compiled = nodejs_compile(func, lang=\"coffeescript\", file=\"???\")\n        if \"error\" in compiled:\n            raise CompilationError(compiled.error)\n        v_compiled = nodejs_compile(v_func, lang=\"coffeescript\", file=\"???\")\n        if \"error\" in v_compiled:\n            raise CompilationError(v_compiled.error)\n        return cls(func=compiled.code, v_func=v_compiled.code, args=args)",
    "docstring": "Create a ``CustomJSTransform`` instance from a pair of CoffeeScript\n        snippets. The function bodies are translated to JavaScript functions\n        using node and therefore require return statements.\n\n        The ``func`` snippet namespace will contain the variable ``x`` (the\n        untransformed value) at render time. The ``v_func`` snippet namespace\n        will contain the variable ``xs`` (the untransformed vector) at render\n        time.\n\n        Example:\n\n        .. code-block:: coffeescript\n\n            func = \"return Math.cos(x)\"\n            v_func = \"return [Math.cos(x) for x in xs]\"\n\n            transform = CustomJSTransform.from_coffeescript(func, v_func)\n\n        Args:\n            func (str) : a coffeescript snippet to transform a single ``x`` value\n\n            v_func (str) : a coffeescript snippet function to transform a vector ``xs``\n\n        Returns:\n            CustomJSTransform"
  },
  {
    "code": "def copy(self):\n        doppel = type(self)(\n            self.unpack, self.apply, self.collect, self.reduce,\n            apply_empty_slots=self.apply_empty_slots,\n            extraneous=self.extraneous,\n            ignore_empty_string=self.ignore_empty_string,\n            ignore_none=self.ignore_none,\n            visit_filter=self.visit_filter,\n        )\n        for x in self.cue:\n            doppel.push(x)\n        doppel.seen = self.seen\n        return doppel",
    "docstring": "Be sure to implement this method when sub-classing, otherwise you\n        will lose any specialization context."
  },
  {
    "code": "def _related(self, concept):\n        return concept.hypernyms() + \\\n                concept.hyponyms() + \\\n                concept.member_meronyms() + \\\n                concept.substance_meronyms() + \\\n                concept.part_meronyms() + \\\n                concept.member_holonyms() + \\\n                concept.substance_holonyms() + \\\n                concept.part_holonyms() + \\\n                concept.attributes() + \\\n                concept.also_sees() + \\\n                concept.similar_tos()",
    "docstring": "Returns related concepts for a concept."
  },
  {
    "code": "def update_team(self, slug):\n        if self._org:\n            if not self._org.has_team(slug):\n                return self._org.update()\n            return self._org.update_team(slug)\n        return False",
    "docstring": "Trigger update and cache invalidation for the team identified by the\n        given `slug`, if any. Returns `True` if the update was successful,\n        `False` otherwise.\n\n        :param slug: GitHub 'slug' name for the team to be updated."
  },
  {
    "code": "def get_right_word(self, cursor=None):\n        if cursor is None:\n            cursor = self._editor.textCursor()\n        cursor.movePosition(QtGui.QTextCursor.WordRight,\n                            QtGui.QTextCursor.KeepAnchor)\n        return cursor.selectedText().strip()",
    "docstring": "Gets the character on the right of the text cursor.\n\n        :param cursor: QTextCursor where the search will start.\n\n        :return: The word that is on the right of the text cursor."
  },
  {
    "code": "def run(self, args):\n        jlink = self.create_jlink(args)\n        if args.downgrade:\n            if not jlink.firmware_newer():\n                print('DLL firmware is not older than J-Link firmware.')\n            else:\n                jlink.invalidate_firmware()\n                try:\n                    jlink.update_firmware()\n                except pylink.JLinkException as e:\n                    jlink = self.create_jlink(args)\n                print('Firmware Downgraded: %s' % jlink.firmware_version)\n        elif args.upgrade:\n            if not jlink.firmware_outdated():\n                print('DLL firmware is not newer than J-Link firmware.')\n            else:\n                try:\n                    jlink.update_firmware()\n                except pylink.JLinkException as e:\n                    jlink = self.create_jlink(args)\n                print('Firmware Updated: %s' % jlink.firmware_version)\n        return None",
    "docstring": "Runs the firmware command.\n\n        Args:\n          self (FirmwareCommand): the ``FirmwareCommand`` instance\n          args (Namespace): arguments to parse\n\n        Returns:\n          ``None``"
  },
  {
    "code": "def max_zoom(self):\n        zoom_levels = [map_layer.max_zoom for map_layer in self.layers]\n        return max(zoom_levels)",
    "docstring": "Get the maximal zoom level of all layers.\n\n        Returns:\n            int: the maximum of all zoom levels of all layers\n\n        Raises:\n            ValueError: if no layers exist"
  },
  {
    "code": "async def _cancel_payloads(self):\n        for task in self._tasks:\n            task.cancel()\n            await asyncio.sleep(0)\n        for task in self._tasks:\n            while not task.done():\n                await asyncio.sleep(0.1)\n                task.cancel()",
    "docstring": "Cancel all remaining payloads"
  },
  {
    "code": "def ensure_float_vector(F, require_order = False):\n    if is_float_vector(F):\n        return F\n    elif is_float(F):\n        return np.array([F])\n    elif is_iterable_of_float(F):\n        return np.array(F)\n    elif isinstance(F, set):\n        if require_order:\n            raise TypeError('Argument is an unordered set, but I require an ordered array of floats')\n        else:\n            lF = list(F)\n            if is_list_of_float(lF):\n                return np.array(lF)\n    else:\n        raise TypeError('Argument is not of a type that is convertible to an array of floats.')",
    "docstring": "Ensures that F is a numpy array of floats\n\n    If F is already a numpy array of floats, F is returned (no copied!)\n    Otherwise, checks if the argument can be converted to an array of floats and does that.\n\n    Parameters\n    ----------\n    F: float, or iterable of float\n    require_order : bool\n        If False (default), an unordered set is accepted. If True, a set is not accepted.\n\n    Returns\n    -------\n    arr : ndarray(n)\n        numpy array with the floats contained in the argument"
  },
  {
    "code": "def moveto(self, x, y, scale=1):\n        self.root.set(\"transform\", \"translate(%s, %s) scale(%s) %s\" %\n                      (x, y, scale, self.root.get(\"transform\") or ''))",
    "docstring": "Move and scale element.\n\n        Parameters\n        ----------\n        x, y : float\n             displacement in x and y coordinates in user units ('px').\n        scale : float\n             scaling factor. To scale down scale < 1,  scale up scale > 1.\n             For no scaling scale = 1."
  },
  {
    "code": "def custom_objective(self, objective_function, *args):\n        result = sco.minimize(\n            objective_function,\n            x0=self.initial_guess,\n            args=args,\n            method=\"SLSQP\",\n            bounds=self.bounds,\n            constraints=self.constraints,\n        )\n        self.weights = result[\"x\"]\n        return dict(zip(self.tickers, self.weights))",
    "docstring": "Optimise some objective function. While an implicit requirement is that the function\n        can be optimised via a quadratic optimiser, this is not enforced. Thus there is a\n        decent chance of silent failure.\n\n        :param objective_function: function which maps (weight, args) -> cost\n        :type objective_function: function with signature (np.ndarray, args) -> float\n        :return: asset weights that optimise the custom objective\n        :rtype: dict"
  },
  {
    "code": "def extract_fields(cls, schema):\n        for part in parse.PARSE_RE.split(schema):\n            if not part or part == '{{' or part == '}}':\n                continue\n            elif part[0] == '{':\n                yield cls.parse(part)",
    "docstring": "Extract fields in a parse expression schema.\n\n        :param schema: Parse expression schema/format to use (as string).\n        :return: Generator for fields in schema (as Field objects)."
  },
  {
    "code": "def dummynum(character, name):\n    num = 0\n    for nodename in character.node:\n        nodename = str(nodename)\n        if not nodename.startswith(name):\n            continue\n        try:\n            nodenum = int(nodename.lstrip(name))\n        except ValueError:\n            continue\n        num = max((nodenum, num))\n    return num",
    "docstring": "Count how many nodes there already are in the character whose name\n    starts the same."
  },
  {
    "code": "def remove_stage_from_deployed_values(key, filename):\n    final_values = {}\n    try:\n        with open(filename, 'r') as f:\n            final_values = json.load(f)\n    except IOError:\n        return\n    try:\n        del final_values[key]\n        with open(filename, 'wb') as f:\n            data = serialize_to_json(final_values)\n            f.write(data.encode('utf-8'))\n    except KeyError:\n        pass",
    "docstring": "Delete a top level key from the deployed JSON file."
  },
  {
    "code": "def install():\n    ceph_dir = \"/etc/ceph\"\n    if not os.path.exists(ceph_dir):\n        os.mkdir(ceph_dir)\n    apt_install('ceph-common', fatal=True)",
    "docstring": "Basic Ceph client installation."
  },
  {
    "code": "def _print_pgfplot_libs_message(data):\n    pgfplotslibs = \",\".join(list(data[\"pgfplots libs\"]))\n    tikzlibs = \",\".join(list(data[\"tikz libs\"]))\n    print(70 * \"=\")\n    print(\"Please add the following lines to your LaTeX preamble:\\n\")\n    print(\"\\\\usepackage[utf8]{inputenc}\")\n    print(\"\\\\usepackage{fontspec}  % This line only for XeLaTeX and LuaLaTeX\")\n    print(\"\\\\usepackage{pgfplots}\")\n    if tikzlibs:\n        print(\"\\\\usetikzlibrary{\" + tikzlibs + \"}\")\n    if pgfplotslibs:\n        print(\"\\\\usepgfplotslibrary{\" + pgfplotslibs + \"}\")\n    print(70 * \"=\")\n    return",
    "docstring": "Prints message to screen indicating the use of PGFPlots and its\n    libraries."
  },
  {
    "code": "def get_signing_policy(signing_policy_name):\n    signing_policy = _get_signing_policy(signing_policy_name)\n    if not signing_policy:\n        return 'Signing policy {0} does not exist.'.format(signing_policy_name)\n    if isinstance(signing_policy, list):\n        dict_ = {}\n        for item in signing_policy:\n            dict_.update(item)\n        signing_policy = dict_\n    try:\n        del signing_policy['signing_private_key']\n    except KeyError:\n        pass\n    try:\n        signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')\n    except KeyError:\n        log.debug('Unable to get \"certificate\" PEM entry')\n    return signing_policy",
    "docstring": "Returns the details of a names signing policy, including the text of\n    the public key that will be used to sign it. Does not return the\n    private key.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' x509.get_signing_policy www"
  },
  {
    "code": "def get_computers(self, filterTerm=None, domain=None):\n        cur = self.conn.cursor()\n        if self.is_computer_valid(filterTerm):\n            cur.execute(\"SELECT * FROM computers WHERE id=? LIMIT 1\", [filterTerm])\n        elif filterTerm == 'dc':\n            if domain:\n                cur.execute(\"SELECT * FROM computers WHERE dc=1 AND LOWER(domain)=LOWER(?)\", [domain])\n            else:\n                cur.execute(\"SELECT * FROM computers WHERE dc=1\")\n        elif filterTerm and filterTerm != \"\":\n            cur.execute(\"SELECT * FROM computers WHERE ip LIKE ? OR LOWER(hostname) LIKE LOWER(?)\", ['%{}%'.format(filterTerm), '%{}%'.format(filterTerm)])\n        else:\n            cur.execute(\"SELECT * FROM computers\")\n        results = cur.fetchall()\n        cur.close()\n        return results",
    "docstring": "Return hosts from the database."
  },
  {
    "code": "def getConstraints(self):\n        constraints = lock_and_call(\n            lambda: self._impl.getConstraints(),\n            self._lock\n        )\n        return EntityMap(constraints, Constraint)",
    "docstring": "Get all the constraints declared."
  },
  {
    "code": "def end_of_directory(self, succeeded=True, update_listing=False,\n                         cache_to_disc=True):\n        self._update_listing = update_listing\n        if not self._end_of_directory:\n            self._end_of_directory = True\n            return xbmcplugin.endOfDirectory(self.handle, succeeded,\n                                             update_listing, cache_to_disc)\n        assert False, 'Already called endOfDirectory.'",
    "docstring": "Wrapper for xbmcplugin.endOfDirectory. Records state in\n        self._end_of_directory.\n\n        Typically it is not necessary to call this method directly, as\n        calling :meth:`~xbmcswift2.Plugin.finish` will call this method."
  },
  {
    "code": "def new_port():\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)\n    for i in range(12042, 16042):\n        try:\n            s.bind(('127.0.0.1', i))\n            s.close()\n            return i\n        except socket.error:\n            pass\n    raise Exception('No local port available')",
    "docstring": "Find a free local port and allocate it"
  },
  {
    "code": "def set_parameter_vector(self, vector, include_frozen=False):\n        v = self.parameter_vector\n        if include_frozen:\n            v[:] = vector\n        else:\n            v[self.unfrozen_mask] = vector\n        self.parameter_vector = v\n        self.dirty = True",
    "docstring": "Set the parameter values to the given vector\n\n        Args:\n            vector (array[vector_size] or array[full_size]): The target\n                parameter vector. This must be in the same order as\n                ``parameter_names`` and it should only include frozen\n                parameters if ``include_frozen`` is ``True``.\n            include_frozen (Optional[bool]): Should the frozen parameters be\n                included in the returned value? (default: ``False``)"
  },
  {
    "code": "def printmp(msg):\n    filler = (80 - len(msg)) * ' '\n    print(msg + filler, end='\\r')\n    sys.stdout.flush()",
    "docstring": "Print temporarily, until next print overrides it."
  },
  {
    "code": "def remove_zero_normals(self):\n        points_of_interest = np.where(np.linalg.norm(self._data, axis=0) != 0.0)[0]\n        self._data = self._data[:, points_of_interest]",
    "docstring": "Removes normal vectors with a zero magnitude.\n\n        Note\n        ----\n        This returns nothing and updates the NormalCloud in-place."
  },
  {
    "code": "def get_model(name, **kwargs):\n    models = {'resnet18_v1': resnet18_v1,\n              'resnet34_v1': resnet34_v1,\n              'resnet50_v1': resnet50_v1,\n              'resnet101_v1': resnet101_v1,\n              'resnet152_v1': resnet152_v1,\n              'resnet18_v2': resnet18_v2,\n              'resnet34_v2': resnet34_v2,\n              'resnet50_v2': resnet50_v2,\n              'resnet101_v2': resnet101_v2,\n              'resnet152_v2': resnet152_v2,\n              'vgg11': vgg11,\n              'vgg13': vgg13,\n              'vgg16': vgg16,\n              'vgg19': vgg19,\n              'vgg11_bn': vgg11_bn,\n              'vgg13_bn': vgg13_bn,\n              'vgg16_bn': vgg16_bn,\n              'vgg19_bn': vgg19_bn,\n              'alexnet': alexnet,\n              'densenet121': densenet121,\n              'densenet161': densenet161,\n              'densenet169': densenet169,\n              'densenet201': densenet201,\n              'squeezenet1.0': squeezenet1_0,\n              'squeezenet1.1': squeezenet1_1,\n              'inceptionv3': inception_v3,\n              'mobilenet1.0': mobilenet1_0,\n              'mobilenet0.75': mobilenet0_75,\n              'mobilenet0.5': mobilenet0_5,\n              'mobilenet0.25': mobilenet0_25,\n              'mobilenetv2_1.0': mobilenet_v2_1_0,\n              'mobilenetv2_0.75': mobilenet_v2_0_75,\n              'mobilenetv2_0.5': mobilenet_v2_0_5,\n              'mobilenetv2_0.25': mobilenet_v2_0_25\n             }\n    name = name.lower()\n    if name not in models:\n        raise ValueError(\n            'Model %s is not supported. Available options are\\n\\t%s' % (\n                name, '\\n\\t'.join(sorted(models.keys()))))\n    return models[name](**kwargs)",
    "docstring": "Returns a pre-defined model by name\n\n    Parameters\n    ----------\n    name : str\n        Name of the model.\n    pretrained : bool\n        Whether to load the pretrained weights for model.\n    classes : int\n        Number of classes for the output layer.\n    ctx : Context, default CPU\n        The context in which to load the pretrained weights.\n    root : str, default '$MXNET_HOME/models'\n        Location for keeping the model parameters.\n\n    Returns\n    -------\n    HybridBlock\n        The model."
  },
  {
    "code": "def _agate_to_schema(self, agate_table, column_override):\n        bq_schema = []\n        for idx, col_name in enumerate(agate_table.column_names):\n            inferred_type = self.convert_agate_type(agate_table, idx)\n            type_ = column_override.get(col_name, inferred_type)\n            bq_schema.append(\n                google.cloud.bigquery.SchemaField(col_name, type_)\n            )\n        return bq_schema",
    "docstring": "Convert agate.Table with column names to a list of bigquery schemas."
  },
  {
    "code": "def tag_syntax_maltparser(self):\n        if not self.__syntactic_parser or not isinstance(self.__syntactic_parser, MaltParser):\n            self.__syntactic_parser = MaltParser()\n        return self.tag_syntax()",
    "docstring": "Changes default syntactic parser to MaltParser, performs syntactic analysis,\n            and stores the results in the layer named LAYER_CONLL."
  },
  {
    "code": "def read_until(self, expected_commands, timeout):\n    msg = timeouts.loop_until_timeout_or_valid(\n        timeout, lambda: self.read_message(timeout),\n        lambda m: m.command in expected_commands, 0)\n    if msg.command not in expected_commands:\n      raise usb_exceptions.AdbTimeoutError(\n          'Timed out establishing connection, waiting for: %s',\n          expected_commands)\n    return msg",
    "docstring": "Read AdbMessages from this transport until we get an expected command.\n\n    The ADB protocol specifies that before a successful CNXN handshake, any\n    other packets must be ignored, so this method provides the ability to\n    ignore unwanted commands.  It's primarily used during the initial\n    connection to the device.  See Read() for more details, including more\n    exceptions that may be raised.\n\n    Args:\n      expected_commands: Iterable of expected command responses, like\n          ('CNXN', 'AUTH').\n      timeout: timeouts.PolledTimeout object to use for timeout.\n\n    Returns:\n      The ADB message received that matched one of expected_commands.\n\n    Raises:\n      AdbProtocolError: If timeout expires between reads, this can happen\n        if we are getting spammed with unexpected commands."
  },
  {
    "code": "def match_route(self, reqpath):\n        route_dicts = [routes for _, routes in self.api.http.routes.items()][0]\n        routes = [route for route, _ in route_dicts.items()]\n        if reqpath in routes:\n            return reqpath\n        for route in routes:\n            if re.match(re.sub(r'/{[^{}]+}', '/\\w+', route) + '$', reqpath):\n                return route\n        return reqpath",
    "docstring": "match a request with parameter to it's corresponding route"
  },
  {
    "code": "def providerIsAuthoritative(providerID, canonicalID):\n    lastbang = canonicalID.rindex('!')\n    parent = canonicalID[:lastbang]\n    return parent == providerID",
    "docstring": "Is this provider ID authoritative for this XRI?\n\n    @returntype: bool"
  },
  {
    "code": "def iflatten(L):\n    for sublist in L:\n        if hasattr(sublist, '__iter__'):\n            for item in iflatten(sublist): yield item\n        else: yield sublist",
    "docstring": "Iterative flatten."
  },
  {
    "code": "def coders(self):\n        return (PrimitiveTypeCoder,\n                TensorFlowCoder,\n                FunctionCoder,\n                ListCoder,\n                DictCoder,\n                SliceCoder,\n                ParameterCoder,\n                ParamListCoder,\n                ParameterizedCoder,\n                TransformCoder,\n                PriorCoder)",
    "docstring": "List of default supported coders. First coder in the list has higher priority."
  },
  {
    "code": "def visit_GpxModel(self, gpx_model, *args, **kwargs):\n        result = OrderedDict()\n        put_scalar = lambda name, json_name=None: self.optional_attribute_scalar(result, gpx_model, name, json_name)\n        put_list = lambda name, json_name=None: self.optional_attribute_list(result, gpx_model, name, json_name)\n        put_scalar('creator')\n        put_scalar('metadata')\n        put_list('waypoints')\n        put_list('routes')\n        put_list('tracks')\n        put_list('extensions')\n        return result",
    "docstring": "Render a GPXModel as a single JSON structure."
  },
  {
    "code": "def get_execution(self, id_execution, access_token=None, user_id=None):\n        if access_token:\n            self.req.credential.set_token(access_token)\n        if user_id:\n            self.req.credential.set_user_id(user_id)\n        if not self.check_credentials():\n            raise CredentialsError('credentials invalid')\n        execution = self.req.get('/Executions/' + id_execution)\n        if \"codeId\" in execution:\n            execution['code'] = self.get_code(execution[\"codeId\"])\n        return execution",
    "docstring": "Get a execution, by its id"
  },
  {
    "code": "def lint(fmt='colorized'):\n    if fmt == 'html':\n        outfile = 'pylint_report.html'\n        local('pylint -f %s davies > %s || true' % (fmt, outfile))\n        local('open %s' % outfile)\n    else:\n        local('pylint -f %s davies || true' % fmt)",
    "docstring": "Run verbose PyLint on source. Optionally specify fmt=html for HTML output."
  },
  {
    "code": "def getconnections(self, vhost = None):\n        \"Return accepted connections, optionally filtered by vhost\"\n        if vhost is None:\n            return list(self.managed_connections)\n        else:\n            return [c for c in self.managed_connections if c.protocol.vhost == vhost]",
    "docstring": "Return accepted connections, optionally filtered by vhost"
  },
  {
    "code": "def _select_default_algorithm(analysis):\n    if not analysis or analysis == \"Standard\":\n        return \"Standard\", {\"aligner\": \"bwa\", \"platform\": \"illumina\", \"quality_format\": \"Standard\",\n                            \"recalibrate\": False, \"realign\": False, \"mark_duplicates\": True,\n                            \"variantcaller\": False}\n    elif \"variant\" in analysis:\n        try:\n            config, _ = template.name_to_config(analysis)\n        except ValueError:\n            config, _ = template.name_to_config(\"freebayes-variant\")\n        return \"variant\", config[\"details\"][0][\"algorithm\"]\n    else:\n        return analysis, {}",
    "docstring": "Provide default algorithm sections from templates or standard"
  },
  {
    "code": "def get_config_load_path(conf_path=None):\n    if conf_path is None:\n        if os.path.isfile('andes.conf'):\n            conf_path = 'andes.conf'\n        home_dir = os.path.expanduser('~')\n        if os.path.isfile(os.path.join(home_dir, '.andes', 'andes.conf')):\n            conf_path = os.path.join(home_dir, '.andes', 'andes.conf')\n    if conf_path is not None:\n        logger.debug('Found config file at {}.'.format(conf_path))\n    return conf_path",
    "docstring": "Return config file load path\n\n    Priority:\n        1. conf_path\n        2. current directory\n        3. home directory\n\n    Parameters\n    ----------\n    conf_path\n\n    Returns\n    -------"
  },
  {
    "code": "def badge_width(self):\n        return self.get_text_width('   ' + ' ' * int(float(self.num_padding_chars) * 2.0)) \\\n            + self.label_width + self.value_width",
    "docstring": "The total width of badge.\n\n        >>> badge = Badge('pylint', '5', font_name='DejaVu Sans,Verdana,Geneva,sans-serif',\n        ...               font_size=11)\n        >>> badge.badge_width\n        91"
  },
  {
    "code": "def __folder_size(self, path):\n        ret = 0\n        for f in scandir(path):\n            if f.is_dir() and (f.name != '.' or f.name != '..'):\n                ret += self.__folder_size(os.path.join(path, f.name))\n            else:\n                try:\n                    ret += f.stat().st_size\n                except OSError:\n                    pass\n        return ret",
    "docstring": "Return the size of the directory given by path\n\n        path: <string>"
  },
  {
    "code": "def listen(cls, event, func):\n        signal(event).connect(func, sender=cls)",
    "docstring": "Add a callback for a signal against the class"
  },
  {
    "code": "def get_forecast(self, latitude, longitude):\n        reply = self.http_get(self.url_builder(latitude, longitude))\n        self.forecast = json.loads(reply)\n        for item in self.forecast.keys():\n            setattr(self, item, self.forecast[item])",
    "docstring": "Gets the weather data from darksky api and stores it in \n        the respective dictionaries if available.\n        This function should be used to fetch weather information."
  },
  {
    "code": "def load_configuration_from_file(directory, args):\n    args = copy.copy(args)\n    directory_or_file = directory\n    if args.config is not None:\n        directory_or_file = args.config\n    options = _get_options(directory_or_file, debug=args.debug)\n    args.report = options.get('report', args.report)\n    threshold_dictionary = docutils.frontend.OptionParser.thresholds\n    args.report = int(threshold_dictionary.get(args.report, args.report))\n    args.ignore_language = get_and_split(\n        options, 'ignore_language', args.ignore_language)\n    args.ignore_messages = options.get(\n        'ignore_messages', args.ignore_messages)\n    args.ignore_directives = get_and_split(\n        options, 'ignore_directives', args.ignore_directives)\n    args.ignore_substitutions = get_and_split(\n        options, 'ignore_substitutions', args.ignore_substitutions)\n    args.ignore_roles = get_and_split(\n        options, 'ignore_roles', args.ignore_roles)\n    return args",
    "docstring": "Return new ``args`` with configuration loaded from file."
  },
  {
    "code": "def mda_count(self):\n        self.open()\n        mda = lvm_pv_get_mda_count(self.handle)\n        self.close()\n        return mda",
    "docstring": "Returns the physical volume mda count."
  },
  {
    "code": "def _check(self):\n        import time\n        if self.expires_in is None or self.authenticated is None:\n            return False\n        current = time.time()\n        expire_time = self.authenticated + self.expires_in\n        return expire_time > current",
    "docstring": "Check if the access token is expired or not."
  },
  {
    "code": "def _check_unit(new_unit, old_unit):\n    try:\n        new_unit.physical_type\n    except AttributeError:\n        raise UnitMismatch(\"The provided unit (%s) has no physical type. Was expecting a unit for %s\"\n                           % (new_unit, old_unit.physical_type))\n    if new_unit.physical_type != old_unit.physical_type:\n        raise UnitMismatch(\"Physical type mismatch: you provided a unit for %s instead of a unit for %s\"\n                           % (new_unit.physical_type, old_unit.physical_type))",
    "docstring": "Check that the new unit is compatible with the old unit for the quantity described by variable_name\n\n    :param new_unit: instance of astropy.units.Unit\n    :param old_unit: instance of astropy.units.Unit\n    :return: nothin"
  },
  {
    "code": "def get_trips(self, authentication_info, start, end):\n        import requests\n        if (authentication_info is None or\n            not authentication_info.is_valid()):\n            return []\n        data_url = \"https://api.ritassist.nl/api/trips/GetTrips\"\n        query = f\"?equipmentId={self.identifier}&from={start}&to={end}&extendedInfo=True\"\n        header = authentication_info.create_header()\n        response = requests.get(data_url + query, headers=header)\n        trips = response.json()\n        result = []\n        for trip_json in trips:\n            trip = Trip(trip_json)\n            result.append(trip)\n        return result",
    "docstring": "Get trips for this device between start and end."
  },
  {
    "code": "def block_comment(solver, start, end):\r\n  text, pos = solver.parse_state\r\n  length = len(text)\r\n  startlen = len(start)\r\n  endlen = len(end)\r\n  if pos==length: return\r\n  if not text[pos:].startswith(start):\r\n    return\r\n  level = 1\r\n  p = pos+1\r\n  while p<length:\r\n    if text[p:].startswith(end):\r\n      level -= 1\r\n      p += endlen\r\n      if level==0: break\r\n    elif text[p:].startswith(start):\r\n      level += 1\r\n      p += startlen\r\n    else:\r\n      p += 1\r\n  else: return\r\n  solver.parse_state = text, p\r\n  yield cont, text[pos:p]\r\n  solver.parse_state = text, pos",
    "docstring": "embedable block comment"
  },
  {
    "code": "def register_hit_type(\n        self, title, description, reward, duration_hours, keywords, qualifications\n    ):\n        reward = str(reward)\n        duration_secs = int(datetime.timedelta(hours=duration_hours).total_seconds())\n        hit_type = self.mturk.create_hit_type(\n            Title=title,\n            Description=description,\n            Reward=reward,\n            AssignmentDurationInSeconds=duration_secs,\n            Keywords=\",\".join(keywords),\n            AutoApprovalDelayInSeconds=0,\n            QualificationRequirements=qualifications,\n        )\n        return hit_type[\"HITTypeId\"]",
    "docstring": "Register HIT Type for this HIT and return the type's ID, which\n        is required for creating a HIT."
  },
  {
    "code": "def delete_leaderboard_named(self, leaderboard_name):\n        pipeline = self.redis_connection.pipeline()\n        pipeline.delete(leaderboard_name)\n        pipeline.delete(self._member_data_key(leaderboard_name))\n        pipeline.delete(self._ties_leaderboard_key(leaderboard_name))\n        pipeline.execute()",
    "docstring": "Delete the named leaderboard.\n\n        @param leaderboard_name [String] Name of the leaderboard."
  },
  {
    "code": "def get_dir_meta(fp, atts):\n    atts.reverse()\n    dirname = os.path.split(fp)[0]\n    meta = dirname.split('/')\n    res = {}\n    try:\n        for key in atts:\n            res[key] = meta.pop()\n    except IndexError:\n        raise PathError(dirname)\n    return res",
    "docstring": "Pop path information and map to supplied atts"
  },
  {
    "code": "def normalizeToTag(val):\n    try:\n        val = val.upper()\n    except AttributeError:\n        raise KeyError(\"{} is not a tag or name string\".format(val))\n    if val not in tagsAndNameSetUpper:\n        raise KeyError(\"{} is not a tag or name string\".format(val))\n    else:\n        try:\n            return fullToTagDictUpper[val]\n        except KeyError:\n            return val",
    "docstring": "Converts tags or full names to 2 character tags, case insensitive\n\n    # Parameters\n\n    _val_: `str`\n\n    > A two character string giving the tag or its full name\n\n    # Returns\n\n    `str`\n\n    > The short name of _val_"
  },
  {
    "code": "def numRegisteredForRole(self, role, includeTemporaryRegs=False):\n        count = self.eventregistration_set.filter(cancelled=False,dropIn=False,role=role).count()\n        if includeTemporaryRegs:\n            count += self.temporaryeventregistration_set.filter(dropIn=False,role=role).exclude(\n                registration__expirationDate__lte=timezone.now()).count()\n        return count",
    "docstring": "Accepts a DanceRole object and returns the number of registrations of that role."
  },
  {
    "code": "def _cb_inform_interface_change(self, msg):\n        self._logger.debug('cb_inform_interface_change(%s)', msg)\n        self._interface_changed.set()",
    "docstring": "Update the sensors and requests available."
  },
  {
    "code": "def filterlet(function=bool, iterable=None):\n    if iterable is None:\n        return _filterlet(function=function)\n    else:\n        return iterlet(elem for elem in iterable if function(elem))",
    "docstring": "Filter chunks of data from an iterable or a chain\n\n    :param function: callable selecting valid elements\n    :type function: callable\n    :param iterable: object providing chunks via iteration\n    :type iterable: iterable or None\n\n    For any chunk in ``iterable`` or the chain, it is passed on only if\n    ``function(chunk)`` returns true.\n\n    .. code::\n\n        chain = iterlet(range(10)) >> filterlet(lambda chunk: chunk % 2 == 0)\n        for value in chain:\n            print(value)  # prints 0, 2, 4, 6, 8"
  },
  {
    "code": "def benchmark_forward(self):\n        self._setup()\n        def f():\n            self._forward()\n            self.mod_ext.synchronize(**self.ext_kwargs)\n        f()\n        self.forward_stat = self._calc_benchmark_stat(f)",
    "docstring": "Benchmark forward execution."
  },
  {
    "code": "def emphasis(node):\n    o = nodes.emphasis()\n    for n in MarkDown(node):\n        o += n\n    return o",
    "docstring": "An italicized section"
  },
  {
    "code": "def cube(data, xcoords=None, ycoords=None, chcoords=None, scalarcoords=None, datacoords=None, attrs=None, name=None):\n    cube = xr.DataArray(data, dims=('x', 'y', 'ch'), attrs=attrs, name=name)\n    cube.dcc._initcoords()\n    if xcoords is not None:\n        cube.coords.update({key: ('x', xcoords[key]) for key in xcoords})\n    if ycoords is not None:\n        cube.coords.update({key: ('y', ycoords[key]) for key in ycoords})\n    if chcoords is not None:\n        cube.coords.update({key: ('ch', chcoords[key]) for key in chcoords})\n    if datacoords is not None:\n        cube.coords.update({key: (('x', 'y', 'ch'), datacoords[key]) for key in datacoords})\n    if scalarcoords is not None:\n        cube.coords.update(scalarcoords)\n    return cube",
    "docstring": "Create a cube as an instance of xarray.DataArray with Decode accessor.\n\n    Args:\n        data (numpy.ndarray): 3D (x x y x channel) array.\n        xcoords (dict, optional): Dictionary of arrays that label x axis.\n        ycoords (dict, optional): Dictionary of arrays that label y axis.\n        chcoords (dict, optional): Dictionary of arrays that label channel axis.\n        scalarcoords (dict, optional): Dictionary of values that don't label any axes (point-like).\n        datacoords (dict, optional): Dictionary of arrays that label x, y, and channel axes.\n        attrs (dict, optional): Dictionary of attributes to add to the instance.\n        name (str, optional): String that names the instance.\n\n    Returns:\n        decode cube (decode.cube): Decode cube."
  },
  {
    "code": "def call(self, method, *args):\n        try:\n            response = getattr(self.client.service, method)(*args)\n        except (URLError, SSLError) as e:\n            log.exception('Failed to connect to responsys service')\n            raise ConnectError(\"Request to service timed out\")\n        except WebFault as web_fault:\n            fault_name = getattr(web_fault.fault, 'faultstring', None)\n            error = str(web_fault.fault.detail)\n            if fault_name == 'TableFault':\n                raise TableFault(error)\n            if fault_name == 'ListFault':\n                raise ListFault(error)\n            if fault_name == 'API_LIMIT_EXCEEDED':\n                raise ApiLimitError(error)\n            if fault_name == 'AccountFault':\n                raise AccountFault(error)\n            raise ServiceError(web_fault.fault, web_fault.document)\n        return response",
    "docstring": "Calls the service method defined with the arguments provided"
  },
  {
    "code": "def success_rate(self):\n        if self.successes + self.fails == 0:\n            success_rate = 0\n        else:\n            total_attempts = self.successes + self.fails\n            success_rate = (self.successes * 100 / total_attempts)\n        return success_rate",
    "docstring": "Returns a float with the rate of success from all the logged results."
  },
  {
    "code": "def __populate_archive_files(self):\n        self.archive_files = []\n        for _ptr in _bfd.archive_list_files(self._ptr):\n            try:\n                self.archive_files.append(Bfd(_ptr))\n            except BfdException, err:\n                pass",
    "docstring": "Store the list of files inside an archive file."
  },
  {
    "code": "def domain_unblock(self, domain=None):\n        params = self.__generate_params(locals())\n        self.__api_request('DELETE', '/api/v1/domain_blocks', params)",
    "docstring": "Remove a domain block for the logged-in user."
  },
  {
    "code": "def get_max_distance_from_start(latlon_track):\n    latlon_list = []\n    for idx, point in enumerate(latlon_track):\n        lat = latlon_track[idx][1]\n        lon = latlon_track[idx][2]\n        alt = latlon_track[idx][3]\n        latlon_list.append([lat, lon, alt])\n    start_position = latlon_list[0]\n    max_distance = 0\n    for position in latlon_list:\n        distance = gps_distance(start_position, position)\n        if distance > max_distance:\n            max_distance = distance\n    return max_distance",
    "docstring": "Returns the radius of an entire GPS track. Used to calculate whether or not the entire sequence was just stationary video\n    Takes a sequence of points as input"
  },
  {
    "code": "def _get_url(cls, administration_id: int, resource_path: str):\n        url = urljoin(cls.base_url, '%s/' % cls.version)\n        if administration_id is not None:\n            url = urljoin(url, '%s/' % administration_id)\n        url = urljoin(url, '%s.json' % resource_path)\n        return url",
    "docstring": "Builds the URL to the API endpoint specified by the given parameters.\n\n        :param administration_id: The ID of the administration (may be None).\n        :param resource_path: The path to the resource.\n        :return: The absolute URL to the endpoint."
  },
  {
    "code": "def sum(self, only_valid=True) -> ErrorValue:\n        if not only_valid:\n            mask = 1\n        else:\n            mask = self.mask\n        return ErrorValue((self.intensity * mask).sum(),\n                          ((self.error * mask) ** 2).sum() ** 0.5)",
    "docstring": "Calculate the sum of pixels, not counting the masked ones if only_valid is True."
  },
  {
    "code": "def getNextSample(self, V):\n        W, WProb = self.drawRankingPlakettLuce(V)\n        VProb = self.calcProbOfVFromW(V, W)\n        acceptanceRatio = self.calcAcceptanceRatio(V, W)\n        prob = min(1.0, acceptanceRatio * (VProb/WProb))\n        if random.random() <= prob:\n            V = W\n        return V",
    "docstring": "Given a ranking over the candidates, generate a new ranking by assigning each candidate at\n        position i a Plakett-Luce weight of phi^i and draw a new ranking.\n\n        :ivar list<int> V: Contains integer representations of each candidate in order of their\n            ranking in a vote, from first to last."
  },
  {
    "code": "def sync(remote='origin', branch='master'):\n    pull(branch, remote)\n    push(branch, remote)\n    print(cyan(\"Git Synced!\"))",
    "docstring": "git pull and push commit"
  },
  {
    "code": "def cmd_list_identities(self, *args):\n        identities = self._get_available_identities()\n        print('Available identities:')\n        for x in identities:\n            print('  - {}'.format(x))",
    "docstring": "List the available identities to use for signing."
  },
  {
    "code": "def squeeze(self, axis=None):\n        axis = (self._AXIS_NAMES if axis is None else\n                (self._get_axis_number(axis),))\n        try:\n            return self.iloc[\n                tuple(0 if i in axis and len(a) == 1 else slice(None)\n                      for i, a in enumerate(self.axes))]\n        except Exception:\n            return self",
    "docstring": "Squeeze 1 dimensional axis objects into scalars.\n\n        Series or DataFrames with a single element are squeezed to a scalar.\n        DataFrames with a single column or a single row are squeezed to a\n        Series. Otherwise the object is unchanged.\n\n        This method is most useful when you don't know if your\n        object is a Series or DataFrame, but you do know it has just a single\n        column. In that case you can safely call `squeeze` to ensure you have a\n        Series.\n\n        Parameters\n        ----------\n        axis : {0 or 'index', 1 or 'columns', None}, default None\n            A specific axis to squeeze. By default, all length-1 axes are\n            squeezed.\n\n            .. versionadded:: 0.20.0\n\n        Returns\n        -------\n        DataFrame, Series, or scalar\n            The projection after squeezing `axis` or all the axes.\n\n        See Also\n        --------\n        Series.iloc : Integer-location based indexing for selecting scalars.\n        DataFrame.iloc : Integer-location based indexing for selecting Series.\n        Series.to_frame : Inverse of DataFrame.squeeze for a\n            single-column DataFrame.\n\n        Examples\n        --------\n        >>> primes = pd.Series([2, 3, 5, 7])\n\n        Slicing might produce a Series with a single value:\n\n        >>> even_primes = primes[primes % 2 == 0]\n        >>> even_primes\n        0    2\n        dtype: int64\n\n        >>> even_primes.squeeze()\n        2\n\n        Squeezing objects with more than one value in every axis does nothing:\n\n        >>> odd_primes = primes[primes % 2 == 1]\n        >>> odd_primes\n        1    3\n        2    5\n        3    7\n        dtype: int64\n\n        >>> odd_primes.squeeze()\n        1    3\n        2    5\n        3    7\n        dtype: int64\n\n        Squeezing is even more effective when used with DataFrames.\n\n        >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])\n        >>> df\n           a  b\n        0  1  2\n        1  3  4\n\n        Slicing a single column will produce a DataFrame with the columns\n        having only one value:\n\n        >>> df_a = df[['a']]\n        >>> df_a\n           a\n        0  1\n        1  3\n\n        So the columns can be squeezed down, resulting in a Series:\n\n        >>> df_a.squeeze('columns')\n        0    1\n        1    3\n        Name: a, dtype: int64\n\n        Slicing a single row from a single column will produce a single\n        scalar DataFrame:\n\n        >>> df_0a = df.loc[df.index < 1, ['a']]\n        >>> df_0a\n           a\n        0  1\n\n        Squeezing the rows produces a single scalar Series:\n\n        >>> df_0a.squeeze('rows')\n        a    1\n        Name: 0, dtype: int64\n\n        Squeezing all axes wil project directly into a scalar:\n\n        >>> df_0a.squeeze()\n        1"
  },
  {
    "code": "def is_deletion(reference_bases, alternate_bases):\n    if len(alternate_bases) > 1:\n        return False\n    if is_indel(reference_bases, alternate_bases):\n        alt_allele = alternate_bases[0]\n        if alt_allele is None:\n            return True\n        if len(reference_bases) > len(alt_allele):\n            return True\n        else:\n            return False\n    else:\n        return False",
    "docstring": "Return whether or not the INDEL is a deletion"
  },
  {
    "code": "def show_help(self):\n        self.main_stacked_widget.setCurrentIndex(0)\n        header = html_header()\n        footer = html_footer()\n        string = header\n        message = impact_report_help()\n        string += message.to_html()\n        string += footer\n        self.help_web_view.setHtml(string)",
    "docstring": "Show usage info to the user.\n\n        .. versionadded: 4.3.0"
  },
  {
    "code": "def drp_load(package, resource, confclass=None):\n    data = pkgutil.get_data(package, resource)\n    return drp_load_data(package, data, confclass=confclass)",
    "docstring": "Load the DRPS from a resource file."
  },
  {
    "code": "def get_matrix(self, indices):\n        new = numpy.empty(self.samples1.shape)\n        for idx in range(len(indices)):\n            if indices[idx]:\n                new[idx] = self.samples1[idx]\n            else:\n                new[idx] = self.samples2[idx]\n        if self.poly:\n            new = self.poly(*new)\n        return new",
    "docstring": "Retrieve Saltelli matrix."
  },
  {
    "code": "def __insert_frond_RF(d_w, d_u, dfs_data):\n    dfs_data['RF'].append( (d_w, d_u) )\n    dfs_data['FG']['r'] += 1\n    dfs_data['last_inserted_side'] = 'RF'",
    "docstring": "Encapsulates the process of inserting a frond uw into the right side frond group."
  },
  {
    "code": "def get_all_stations(self, station_type=None):\n        params = None\n        if station_type and station_type in STATION_TYPE_TO_CODE_DICT:\n            url = self.api_base_url + 'getAllStationsXML_WithStationType'\n            params = {\n                'stationType': STATION_TYPE_TO_CODE_DICT[station_type]\n            }\n        else:\n            url = self.api_base_url + 'getAllStationsXML'\n        response = requests.get(\n            url, params=params, timeout=10)\n        if response.status_code != 200:\n            return []\n        return self._parse_station_list(response.content)",
    "docstring": "Returns information of all stations.\n        @param<optional> station_type: ['mainline', 'suburban', 'dart']"
  },
  {
    "code": "def fetchUrls(cls, url, data, urlSearch):\n        searchUrls = []\n        if cls.css:\n            searchFun = data.cssselect\n        else:\n            searchFun = data.xpath\n        searches = makeSequence(urlSearch)\n        for search in searches:\n            for match in searchFun(search):\n                try:\n                    for attrib in html_link_attrs:\n                        if attrib in match.attrib:\n                            searchUrls.append(match.get(attrib))\n                except AttributeError:\n                    searchUrls.append(str(match))\n            if not cls.multipleImagesPerStrip and searchUrls:\n                break\n        if not searchUrls:\n            raise ValueError(\"XPath %s not found at URL %s.\" % (searches, url))\n        return searchUrls",
    "docstring": "Search all entries for given XPath in a HTML page."
  },
  {
    "code": "def get_stats_display_height(self, curse_msg):\n        r\n        try:\n            c = [i['msg'] for i in curse_msg['msgdict']].count('\\n')\n        except Exception as e:\n            logger.debug('ERROR: Can not compute plugin height ({})'.format(e))\n            return 0\n        else:\n            return c + 1",
    "docstring": "r\"\"\"Return the height of the formatted curses message.\n\n        The height is defined by the number of '\\n' (new line)."
  },
  {
    "code": "def _find_log_index(f):\n    global _last_asked, _log_cache\n    (begin, end) = (0, 128)\n    if _last_asked is not None:\n        (lastn, lastval) = _last_asked\n        if f >= lastval:\n            if f <= _log_cache[lastn]:\n                _last_asked = (lastn, f)\n                return lastn\n            elif f <= _log_cache[lastn + 1]:\n                _last_asked = (lastn + 1, f)\n                return lastn + 1\n            begin = lastn\n    if f > _log_cache[127] or f <= 0:\n        return 128\n    while begin != end:\n        n = (begin + end) // 2\n        c = _log_cache[n]\n        cp = _log_cache[n - 1] if n != 0 else 0\n        if cp < f <= c:\n            _last_asked = (n, f)\n            return n\n        if f < c:\n            end = n\n        else:\n            begin = n\n    _last_asked = (begin, f)\n    return begin",
    "docstring": "Look up the index of the frequency f in the frequency table.\n\n    Return the nearest index."
  },
  {
    "code": "def diskwarp_multi_fn(src_fn_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, outdir=None, dst_ndv=None):\n    if not iolib.fn_list_check(src_fn_list):\n        sys.exit('Missing input file(s)')\n    src_ds_list = [gdal.Open(fn, gdal.GA_ReadOnly) for fn in src_fn_list]\n    return diskwarp_multi(src_ds_list, res, extent, t_srs, r, verbose=verbose, outdir=outdir, dst_ndv=dst_ndv)",
    "docstring": "Helper function for diskwarp of multiple input filenames"
  },
  {
    "code": "def split_signature(klass, signature):\n        if signature == '()':\n            return []\n        if not signature.startswith('('):\n            return [signature]\n        result = []\n        head = ''\n        tail = signature[1:-1]\n        while tail:\n            c = tail[0]\n            head += c\n            tail = tail[1:]\n            if c in ('m', 'a'):\n                continue\n            if c in ('(', '{'):\n                level = 1\n                up = c\n                if up == '(':\n                    down = ')'\n                else:\n                    down = '}'\n                while level > 0:\n                    c = tail[0]\n                    head += c\n                    tail = tail[1:]\n                    if c == up:\n                        level += 1\n                    elif c == down:\n                        level -= 1\n            result.append(head)\n            head = ''\n        return result",
    "docstring": "Return a list of the element signatures of the topmost signature tuple.\n\n        If the signature is not a tuple, it returns one element with the entire\n        signature. If the signature is an empty tuple, the result is [].\n\n        This is useful for e. g. iterating over method parameters which are\n        passed as a single Variant."
  },
  {
    "code": "def _perform_merge(self, other):\n        if len(other.value) > len(self.value):\n            self.value = other.value[:]\n        return True",
    "docstring": "Merges the longer string"
  },
  {
    "code": "def SetWriteBack(self, filename):\n    try:\n      self.writeback = self.LoadSecondaryConfig(filename)\n      self.MergeData(self.writeback.RawData(), self.writeback_data)\n    except IOError as e:\n      logging.error(\"Unable to read writeback file: %s\", e)\n      return\n    except Exception as we:\n      if os.path.exists(filename):\n        try:\n          b = filename + \".bak\"\n          os.rename(filename, b)\n          logging.warning(\"Broken writeback (%s) renamed to: %s\", we, b)\n        except Exception as e:\n          logging.error(\"Unable to rename broken writeback: %s\", e)\n      raise we\n    logging.debug(\"Configuration writeback is set to %s\", filename)",
    "docstring": "Sets the config file which will receive any modifications.\n\n    The main config file can be made writable, but directing all Set()\n    operations into a secondary location. This secondary location will\n    receive any updates and will override the options for this file.\n\n    Args:\n      filename: A filename which will receive updates. The file is parsed first\n        and merged into the raw data from this object."
  },
  {
    "code": "def fetch(self, async=False, callback=None):\n        request = NURESTRequest(method=HTTP_METHOD_GET, url=self.get_resource_url())\n        if async:\n            return self.send_request(request=request, async=async, local_callback=self._did_fetch, remote_callback=callback)\n        else:\n            connection = self.send_request(request=request)\n            return self._did_retrieve(connection)",
    "docstring": "Fetch all information about the current object\n\n            Args:\n                async (bool): Boolean to make an asynchronous call. Default is False\n                callback (function): Callback method that will be triggered in case of asynchronous call\n\n            Returns:\n                tuple: (current_fetcher, callee_parent, fetched_bjects, connection)\n\n            Example:\n                >>> entity = NUEntity(id=\"xxx-xxx-xxx-xxx\")\n                >>> entity.fetch() # will get the entity with id \"xxx-xxx-xxx-xxx\"\n                >>> print entity.name\n                \"My Entity\""
  },
  {
    "code": "def setup_logging(self):\n        self.logger = logging.getLogger()\n        if os.path.exists('/dev/log'):\n            handler = SysLogHandler('/dev/log')\n        else:\n            handler = SysLogHandler()\n        self.logger.addHandler(handler)",
    "docstring": "Set up self.logger\n\n        This function is called after load_configuration() and after changing\n        to new user/group IDs (if configured). Logging to syslog using the\n        root logger is configured by default, you can override this method if\n        you want something else."
  },
  {
    "code": "def get_field_label(self, field_name, field=None):\n        label = None\n        if field is not None:\n            label = getattr(field, 'verbose_name', None)\n            if label is None:\n                label = getattr(field, 'name', None)\n        if label is None:\n            label = field_name\n        return label.capitalize()",
    "docstring": "Return a label to display for a field"
  },
  {
    "code": "def append(self, frame_p):\n        return lib.zmsg_append(self._as_parameter_, byref(zframe_p.from_param(frame_p)))",
    "docstring": "Add frame to the end of the message, i.e. after all other frames.\nMessage takes ownership of frame, will destroy it when message is sent.\nReturns 0 on success. Deprecates zmsg_add, which did not nullify the\ncaller's frame reference."
  },
  {
    "code": "def get_numeric_feature_names(example):\n  numeric_features = ('float_list', 'int64_list')\n  features = get_example_features(example)\n  return sorted([\n      feature_name for feature_name in features\n      if features[feature_name].WhichOneof('kind') in numeric_features\n  ])",
    "docstring": "Returns a list of feature names for float and int64 type features.\n\n  Args:\n    example: An example.\n\n  Returns:\n    A list of strings of the names of numeric features."
  },
  {
    "code": "def get_access_tokens(self, authorization_code):\n        response = self.box_request.get_access_token(authorization_code)\n        try:\n            att = response.json()\n        except Exception, ex:\n            raise BoxHttpResponseError(ex)\n        if response.status_code >= 400:\n            raise BoxError(response.status_code, att)\n        return att['access_token'], att['refresh_token']",
    "docstring": "From the authorization code, get the \"access token\" and the \"refresh token\" from Box.\n\n        Args:\n            authorization_code (str). Authorisation code emitted by Box at the url provided by the function :func:`get_authorization_url`.\n\n        Returns:\n            tuple. (access_token, refresh_token)\n\n        Raises:\n            BoxError: An error response is returned from Box (status_code >= 400).\n\n            BoxHttpResponseError: Response from Box is malformed.\n\n            requests.exceptions.*: Any connection related problem."
  },
  {
    "code": "def clean_html(context, data):\n    doc = _get_html_document(context, data)\n    if doc is None:\n        context.emit(data=data)\n        return\n    remove_paths = context.params.get('remove_paths')\n    for path in ensure_list(remove_paths):\n        for el in doc.findall(path):\n            el.drop_tree()\n    html_text = html.tostring(doc, pretty_print=True)\n    content_hash = context.store_data(html_text)\n    data['content_hash'] = content_hash\n    context.emit(data=data)",
    "docstring": "Clean an HTML DOM and store the changed version."
  },
  {
    "code": "def cleanup_defenses(self):\n    print_header('CLEANING UP DEFENSES DATA')\n    work_ancestor_key = self.datastore_client.key('WorkType', 'AllDefenses')\n    keys_to_delete = [\n        e.key\n        for e in self.datastore_client.query_fetch(kind=u'ClassificationBatch')\n    ] + [\n        e.key\n        for e in self.datastore_client.query_fetch(kind=u'Work',\n                                                   ancestor=work_ancestor_key)\n    ]\n    self._cleanup_keys_with_confirmation(keys_to_delete)",
    "docstring": "Cleans up all data about defense work in current round."
  },
  {
    "code": "async def _delete_agent(self, agent_addr):\n        self._available_agents = [agent for agent in self._available_agents if agent != agent_addr]\n        del self._registered_agents[agent_addr]\n        await self._recover_jobs(agent_addr)",
    "docstring": "Deletes an agent"
  },
  {
    "code": "def core_profile_check(self) -> None:\n        profile_mask = self.info['GL_CONTEXT_PROFILE_MASK']\n        if profile_mask != 1:\n            warnings.warn('The window should request a CORE OpenGL profile')\n        version_code = self.version_code\n        if not version_code:\n            major, minor = map(int, self.info['GL_VERSION'].split('.', 2)[:2])\n            version_code = major * 100 + minor * 10\n        if version_code < 330:\n            warnings.warn('The window should support OpenGL 3.3+ (version_code=%d)' % version_code)",
    "docstring": "Core profile check.\n\n            FOR DEBUG PURPOSES ONLY"
  },
  {
    "code": "def get_uint_info(self, field):\n        length = ctypes.c_ulong()\n        ret = ctypes.POINTER(ctypes.c_uint)()\n        _check_call(_LIB.XGDMatrixGetUIntInfo(self.handle,\n                                              c_str(field),\n                                              ctypes.byref(length),\n                                              ctypes.byref(ret)))\n        return ctypes2numpy(ret, length.value, np.uint32)",
    "docstring": "Get unsigned integer property from the DMatrix.\n\n        Parameters\n        ----------\n        field: str\n            The field name of the information\n\n        Returns\n        -------\n        info : array\n            a numpy array of float information of the data"
  },
  {
    "code": "def get_path(dest, file, cwd = None):\n\tif callable(dest):\n\t\treturn dest(file)\n\tif not cwd:\n\t\tcwd = file.cwd\n\tif not os.path.isabs(dest):\n\t\tdest = os.path.join(cwd, dest)\n\trelative = os.path.relpath(file.path, file.base)\n\treturn os.path.join(dest, relative)",
    "docstring": "Get the writing path of a file."
  },
  {
    "code": "def metalarchives(song):\n    artist = normalize(song.artist)\n    title = normalize(song.title)\n    url = 'https://www.metal-archives.com/search/ajax-advanced/searching/songs'\n    url += f'/?songTitle={title}&bandName={artist}&ExactBandMatch=1'\n    soup = get_url(url, parser='json')\n    if not soup:\n        return ''\n    song_id_re = re.compile(r'lyricsLink_([0-9]*)')\n    ids = set(re.search(song_id_re, a) for sub in soup['aaData'] for a in sub)\n    if not ids:\n        return ''\n    if None in ids:\n        ids.remove(None)\n    ids = map(lambda a: a.group(1), ids)\n    for song_id in ids:\n        url = 'https://www.metal-archives.com/release/ajax-view-lyrics/id/{}'\n        lyrics = get_url(url.format(song_id), parser='html')\n        lyrics = lyrics.get_text().strip()\n        if not re.search('lyrics not available', lyrics):\n            return lyrics\n    return ''",
    "docstring": "Returns the lyrics found in MetalArchives for the specified mp3 file or an\n    empty string if not found."
  },
  {
    "code": "def get_system_config_directory():\r\n    if platform.system().lower() == 'windows':\r\n        _cfg_directory = Path(os.getenv('APPDATA') or '~')\r\n    elif platform.system().lower() == 'darwin':\r\n        _cfg_directory = Path('~', 'Library', 'Preferences')\r\n    else:\r\n        _cfg_directory = Path(os.getenv('XDG_CONFIG_HOME') or '~/.config')\r\n    logger.debug('Fetching configt directory for {}.'\r\n                 .format(platform.system()))\r\n    return _cfg_directory.joinpath(Path('mayalauncher/.config'))",
    "docstring": "Return platform specific config directory."
  },
  {
    "code": "def _speak_none(self, element):\n        element.set_attribute('role', 'presentation')\n        element.set_attribute('aria-hidden', 'true')\n        element.set_attribute(AccessibleCSSImplementation.DATA_SPEAK, 'none')",
    "docstring": "No speak any content of element only.\n\n        :param element: The element.\n        :type element: hatemile.util.html.htmldomelement.HTMLDOMElement"
  },
  {
    "code": "def save(self, filename=None, tc=None):\n        if filename is None:\n            filename = self.filename\n        for sub in self.sub_workflows:\n            sub.save()\n        if tc is None:\n            tc = '{}.tc.txt'.format(filename)\n        p = os.path.dirname(tc)\n        f = os.path.basename(tc)\n        if not p:\n            p = '.'\n        tc = TransformationCatalog(p, f)\n        for e in self._adag.executables.copy():\n            tc.add(e)\n            try:\n                tc.add_container(e.container)\n            except:\n                pass\n            self._adag.removeExecutable(e)\n        f = open(filename, \"w\")\n        self._adag.writeXML(f)\n        tc.write()",
    "docstring": "Write this workflow to DAX file"
  },
  {
    "code": "def strip_encoding_cookie(filelike):\n    it = iter(filelike)\n    try:\n        first = next(it)\n        if not cookie_comment_re.match(first):\n            yield first\n        second = next(it)\n        if not cookie_comment_re.match(second):\n            yield second\n    except StopIteration:\n        return\n    for line in it:\n        yield line",
    "docstring": "Generator to pull lines from a text-mode file, skipping the encoding\n    cookie if it is found in the first two lines."
  },
  {
    "code": "def patch(self, url, callback,\n              params=None, json=None, headers=None):\n        return self.adapter.patch(url, callback,\n                                  params=params, json=json, headers=headers)",
    "docstring": "Patch a URL.\n\n        Args:\n\n            url(string): URL for the request\n\n            callback(func): The response callback function\n\n            headers(dict): HTTP headers for the request\n\n        Keyword Args:\n\n            params(dict): Parameters for the request\n\n            json(dict): JSON body for the request\n\n        Returns:\n\n            The result of the callback handling the resopnse from the\n                executed request"
  },
  {
    "code": "def intersects(self, other_grid_coordinates):\n        ogc = other_grid_coordinates\n        ax1, ay1, ax2, ay2 = self.ULC.lon, self.ULC.lat, self.LRC.lon, self.LRC.lat\n        bx1, by1, bx2, by2 = ogc.ULC.lon, ogc.ULC.lat, ogc.LRC.lon, ogc.LRC.lat\n        if ((ax1 <= bx2) and (ax2 >= bx1) and (ay1 >= by2) and (ay2 <= by1)):\n            return True\n        else:\n            return False",
    "docstring": "returns True if the GC's overlap."
  },
  {
    "code": "def specAutoRange(self):\n        trace_range = self.responsePlots.values()[0].viewRange()[0]\n        vb = self.specPlot.getViewBox()\n        vb.autoRange(padding=0)\n        self.specPlot.setXlim(trace_range)",
    "docstring": "Auto adjusts the visible range of the spectrogram"
  },
  {
    "code": "def fix_missing_lang_tags(marc_xml, dom):\n    def get_lang_tag(lang):\n        lang_str = '\\n  <mods:language>\\n'\n        lang_str += '    <mods:languageTerm authority=\"iso639-2b\" type=\"code\">'\n        lang_str += lang\n        lang_str += '</mods:languageTerm>\\n'\n        lang_str += '  </mods:language>\\n\\n'\n        lang_dom = dhtmlparser.parseString(lang_str)\n        return first(lang_dom.find(\"mods:language\"))\n    for lang in reversed(marc_xml[\"041a0 \"]):\n        lang_tag = dom.find(\n            \"mods:languageTerm\",\n            fn=lambda x: x.getContent().strip().lower() == lang.lower()\n        )\n        if not lang_tag:\n            insert_tag(\n                get_lang_tag(lang),\n                dom.find(\"mods:language\"),\n                get_mods_tag(dom)\n            )",
    "docstring": "If the lang tags are missing, add them to the MODS. Lang tags are parsed\n    from `marc_xml`."
  },
  {
    "code": "def removeActor(self, a):\n        if not self.initializedPlotter:\n            save_int = self.interactive\n            self.show(interactive=0)\n            self.interactive = save_int\n            return\n        if self.renderer:\n            self.renderer.RemoveActor(a)\n            if hasattr(a, 'renderedAt'):\n                ir = self.renderers.index(self.renderer)\n                a.renderedAt.discard(ir)\n        if a in self.actors:\n            i = self.actors.index(a)\n            del self.actors[i]",
    "docstring": "Remove ``vtkActor`` or actor index from current renderer."
  },
  {
    "code": "def sanity(request, sysmeta_pyxb):\n    _does_not_contain_replica_sections(sysmeta_pyxb)\n    _is_not_archived(sysmeta_pyxb)\n    _obsoleted_by_not_specified(sysmeta_pyxb)\n    if 'HTTP_VENDOR_GMN_REMOTE_URL' in request.META:\n        return\n    _has_correct_file_size(request, sysmeta_pyxb)\n    _is_supported_checksum_algorithm(sysmeta_pyxb)\n    _is_correct_checksum(request, sysmeta_pyxb)",
    "docstring": "Check that sysmeta_pyxb is suitable for creating a new object and matches the\n    uploaded sciobj bytes."
  },
  {
    "code": "def get_children(self, id_):\n        id_list = []\n        for r in self._rls.get_relationships_by_genus_type_for_source(id_, self._relationship_type):\n            id_list.append(r.get_destination_id())\n        return IdList(id_list)",
    "docstring": "Gets the children of the given ``Id``.\n\n        arg:    id (osid.id.Id): the ``Id`` to query\n        return: (osid.id.IdList) - the children of the ``id``\n        raise:  NotFound - ``id`` is not found\n        raise:  NullArgument - ``id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def connect(cls, dbname):\n        test_times_schema =\n        setup_times_schema =\n        schemas = [test_times_schema,\n                   setup_times_schema]\n        db_file = '{}.db'.format(dbname)\n        cls.connection = sqlite3.connect(db_file)\n        for s in schemas:\n            cls.connection.execute(s)",
    "docstring": "Create a new connection to the SQLite3 database.\n\n        :param dbname: The database name\n        :type dbname: str"
  },
  {
    "code": "def holiday_description(self):\n        entry = self._holiday_entry()\n        desc = entry.description\n        return desc.hebrew.long if self.hebrew else desc.english",
    "docstring": "Return the holiday description.\n\n        In case none exists will return None."
  },
  {
    "code": "def open_url(self, url):\n        try:\n            c = pycurl.Curl()\n            c.setopt(pycurl.FAILONERROR, True)\n            c.setopt(pycurl.URL, \"%s/api/v0/%s\" % (self.url, url))\n            c.setopt(pycurl.HTTPHEADER, [\"User-Agent: %s\" % self.userAgent,\n                                         \"apiToken: %s\" % self.apiToken])\n            b = StringIO.StringIO()\n            c.setopt(pycurl.WRITEFUNCTION, b.write)\n            c.setopt(pycurl.FOLLOWLOCATION, 1)\n            c.setopt(pycurl.MAXREDIRS, 5)\n            c.setopt(pycurl.SSLVERSION, pycurl.SSLVERSION_SSLv3) \n            c.setopt(pycurl.SSL_VERIFYPEER, 1)\n            c.setopt(pycurl.SSL_VERIFYHOST, 2) \n            c.perform()\n            return b.getvalue()\n        except pycurl.error, e:\n            raise MyTimetableError(e)",
    "docstring": "Open's URL with apiToken in the headers"
  },
  {
    "code": "def _build_generator_list(network):\n    genos_mv = pd.DataFrame(columns=\n                            ('id', 'obj'))\n    genos_lv = pd.DataFrame(columns=\n                            ('id', 'obj'))\n    genos_lv_agg = pd.DataFrame(columns=\n                                ('la_id', 'id', 'obj'))\n    for geno in network.mv_grid.graph.nodes_by_attribute('generator'):\n            genos_mv.loc[len(genos_mv)] = [int(geno.id), geno]\n    for geno in network.mv_grid.graph.nodes_by_attribute('generator_aggr'):\n            la_id = int(geno.id.split('-')[1].split('_')[-1])\n            genos_lv_agg.loc[len(genos_lv_agg)] = [la_id, geno.id, geno]\n    for lv_grid in network.mv_grid.lv_grids:\n        for geno in lv_grid.generators:\n            genos_lv.loc[len(genos_lv)] = [int(geno.id), geno]\n    return genos_mv, genos_lv, genos_lv_agg",
    "docstring": "Builds DataFrames with all generators in MV and LV grids\n\n    Returns\n    -------\n    :pandas:`pandas.DataFrame<dataframe>`\n            A DataFrame with id of and reference to MV generators\n    :pandas:`pandas.DataFrame<dataframe>`\n            A DataFrame with id of and reference to LV generators\n    :pandas:`pandas.DataFrame<dataframe>`\n            A DataFrame with id of and reference to aggregated LV generators"
  },
  {
    "code": "def is_open(self, refresh=False):\n        if refresh:\n            self.refresh()\n        return self.get_level(refresh) > 0",
    "docstring": "Get curtains state.\n\n        Refresh data from Vera if refresh is True, otherwise use local cache.\n        Refresh is only needed if you're not using subscriptions."
  },
  {
    "code": "def rotate(self):\n        item = self._address_infos.pop(0)\n        self._address_infos.append(item)",
    "docstring": "Move the first address to the last position."
  },
  {
    "code": "def format_op_hdr():\n    txt = 'Base Filename'.ljust(36) + ' '\n    txt += 'Lines'.rjust(7) + ' '\n    txt += 'Words'.rjust(7) + '  '\n    txt += 'Unique'.ljust(8) + ''\n    return txt",
    "docstring": "Build the header"
  },
  {
    "code": "def write_networking_file(version, pairs):\n    vmnets = OrderedDict(sorted(pairs.items(), key=lambda t: t[0]))\n    try:\n        with open(VMWARE_NETWORKING_FILE, \"w\", encoding=\"utf-8\") as f:\n            f.write(version)\n            for key, value in vmnets.items():\n                f.write(\"answer {} {}\\n\".format(key, value))\n    except OSError as e:\n        raise SystemExit(\"Cannot open {}: {}\".format(VMWARE_NETWORKING_FILE, e))\n    if sys.platform.startswith(\"darwin\"):\n        if not os.path.exists(\"/Applications/VMware Fusion.app/Contents/Library/vmnet-cli\"):\n            raise SystemExit(\"VMware Fusion is not installed in Applications\")\n        os.system(r\"/Applications/VMware\\ Fusion.app/Contents/Library/vmnet-cli --configure\")\n        os.system(r\"/Applications/VMware\\ Fusion.app/Contents/Library/vmnet-cli --stop\")\n        os.system(r\"/Applications/VMware\\ Fusion.app/Contents/Library/vmnet-cli --start\")\n    else:\n        os.system(\"vmware-networks --stop\")\n        os.system(\"vmware-networks --start\")",
    "docstring": "Write the VMware networking file."
  },
  {
    "code": "def get_command(self, ctx, cmd_name):\n        if cmd_name not in self.all_cmds:\n            return None\n        return EventTypeSubCommand(self.events_lib, cmd_name, self.all_cmds[cmd_name])",
    "docstring": "gets the subcommands under the service name\n\n        Parameters\n        ----------\n        ctx : Context\n            the context object passed into the method\n        cmd_name : str\n            the service name\n        Returns\n        -------\n        EventTypeSubCommand:\n            returns subcommand if successful, None if not."
  },
  {
    "code": "def from_grpc(operation, operations_stub, result_type, **kwargs):\n    refresh = functools.partial(_refresh_grpc, operations_stub, operation.name)\n    cancel = functools.partial(_cancel_grpc, operations_stub, operation.name)\n    return Operation(operation, refresh, cancel, result_type, **kwargs)",
    "docstring": "Create an operation future using a gRPC client.\n\n    This interacts with the long-running operations `service`_ (specific\n    to a given API) via gRPC.\n\n    .. _service: https://github.com/googleapis/googleapis/blob/\\\n                 050400df0fdb16f63b63e9dee53819044bffc857/\\\n                 google/longrunning/operations.proto#L38\n\n    Args:\n        operation (google.longrunning.operations_pb2.Operation): The operation.\n        operations_stub (google.longrunning.operations_pb2.OperationsStub):\n            The operations stub.\n        result_type (:func:`type`): The protobuf result type.\n        kwargs: Keyword args passed into the :class:`Operation` constructor.\n\n    Returns:\n        ~.api_core.operation.Operation: The operation future to track the given\n            operation."
  },
  {
    "code": "def generateAcceptHeader(*elements):\n    parts = []\n    for element in elements:\n        if type(element) is str:\n            qs = \"1.0\"\n            mtype = element\n        else:\n            mtype, q = element\n            q = float(q)\n            if q > 1 or q <= 0:\n                raise ValueError('Invalid preference factor: %r' % q)\n            qs = '%0.1f' % (q,)\n        parts.append((qs, mtype))\n    parts.sort()\n    chunks = []\n    for q, mtype in parts:\n        if q == '1.0':\n            chunks.append(mtype)\n        else:\n            chunks.append('%s; q=%s' % (mtype, q))\n    return ', '.join(chunks)",
    "docstring": "Generate an accept header value\n\n    [str or (str, float)] -> str"
  },
  {
    "code": "def set_mtime(self, name, mtime, size):\n        self.check_write(name)\n        os.utime(os.path.join(self.cur_dir, name), (-1, mtime))",
    "docstring": "Set modification time on file."
  },
  {
    "code": "def send_async(\n            self,\n            queue_identifier: QueueIdentifier,\n            message: Message,\n    ):\n        recipient = queue_identifier.recipient\n        if not is_binary_address(recipient):\n            raise ValueError('Invalid address {}'.format(pex(recipient)))\n        if isinstance(message, (Delivered, Ping, Pong)):\n            raise ValueError('Do not use send for {} messages'.format(message.__class__.__name__))\n        messagedata = message.encode()\n        if len(messagedata) > self.UDP_MAX_MESSAGE_SIZE:\n            raise ValueError(\n                'message size exceeds the maximum {}'.format(self.UDP_MAX_MESSAGE_SIZE),\n            )\n        message_id = message.message_identifier\n        if message_id not in self.messageids_to_asyncresults:\n            self.messageids_to_asyncresults[message_id] = AsyncResult()\n            queue = self.get_queue_for(queue_identifier)\n            queue.put((messagedata, message_id))\n            assert queue.is_set()\n            self.log.debug(\n                'Message queued',\n                queue_identifier=queue_identifier,\n                queue_size=len(queue),\n                message=message,\n            )",
    "docstring": "Send a new ordered message to recipient.\n\n        Messages that use the same `queue_identifier` are ordered."
  },
  {
    "code": "def liouvillian(H, Ls=None):\n    r\n    if Ls is None:\n        Ls = []\n    elif isinstance(Ls, Matrix):\n        Ls = Ls.matrix.ravel().tolist()\n    summands = [-I * commutator(H), ]\n    summands.extend([lindblad(L) for L in Ls])\n    return SuperOperatorPlus.create(*summands)",
    "docstring": "r\"\"\"Return the Liouvillian super-operator associated with `H` and `Ls`\n\n    The Liouvillian :math:`\\mathcal{L}` generates the Markovian-dynamics of a\n    system via the Master equation:\n\n    .. math::\n        \\dot{\\rho} = \\mathcal{L}\\rho\n            = -i[H,\\rho] + \\sum_{j=1}^n \\mathcal{D}[L_j] \\rho\n\n    Args:\n        H (Operator): The associated Hamilton operator\n        Ls (sequence or Matrix): A sequence of Lindblad operators.\n\n    Returns:\n        SuperOperator: The Liouvillian super-operator."
  },
  {
    "code": "def ignore_code(self, code):\n        if len(code) < 4 and any(s.startswith(code)\n                                 for s in self.options.select):\n            return False\n        return (code.startswith(self.options.ignore) and\n                not code.startswith(self.options.select))",
    "docstring": "Check if the error code should be ignored.\n\n        If 'options.select' contains a prefix of the error code,\n        return False.  Else, if 'options.ignore' contains a prefix of\n        the error code, return True."
  },
  {
    "code": "def put_path(self, url, path):\n        cache_path = self._url_to_path(url)\n        try:\n            dir = os.path.dirname(cache_path)\n            os.makedirs(dir)\n        except OSError as e:\n            if e.errno != errno.EEXIST:\n                raise Error('Failed to create cache directories for ' % cache_path)\n        try:\n            os.unlink(cache_path)\n        except OSError:\n            pass\n        try:\n            os.link(path, cache_path)\n        except OSError:\n            try:\n                shutil.copyfile(path, cache_path)\n            except IOError:\n                raise Error('Failed to cache %s as %s for %s' % (path, cache_path, url))",
    "docstring": "Puts a resource already on disk into the disk cache.\n\n        Args:\n            url: The original url of the resource\n            path: The resource already available on disk\n\n        Raises:\n            CacheError: If the file cannot be put in cache"
  },
  {
    "code": "def get_suggested_repositories(self):\n        if self.suggested_repositories is None:\n            repository_set = list()\n            for term_count in range(5, 2, -1):\n                query = self.__get_query_for_repos(term_count=term_count)\n                repository_set.extend(self.__get_repos_for_query(query))\n            catchy_repos = GitSuggest.minus(\n                repository_set, self.user_starred_repositories\n            )\n            filtered_repos = []\n            if len(catchy_repos) > 0:\n                for repo in catchy_repos:\n                    if (\n                        repo is not None\n                        and repo.description is not None\n                        and len(repo.description) <= GitSuggest.MAX_DESC_LEN\n                    ):\n                        filtered_repos.append(repo)\n            filtered_repos = sorted(\n                filtered_repos,\n                key=attrgetter(\"stargazers_count\"),\n                reverse=True,\n            )\n            self.suggested_repositories = GitSuggest.get_unique_repositories(\n                filtered_repos\n            )\n        for repository in self.suggested_repositories:\n            yield repository",
    "docstring": "Method to procure suggested repositories for the user.\n\n        :return: Iterator to procure suggested repositories for the user."
  },
  {
    "code": "def get_object_by_record(record):\n    if not record:\n        return None\n    if record.get(\"uid\"):\n        return get_object_by_uid(record[\"uid\"])\n    if record.get(\"path\"):\n        return get_object_by_path(record[\"path\"])\n    if record.get(\"parent_path\") and record.get(\"id\"):\n        path = \"/\".join([record[\"parent_path\"], record[\"id\"]])\n        return get_object_by_path(path)\n    logger.warn(\"get_object_by_record::No object found! record='%r'\" % record)\n    return None",
    "docstring": "Find an object by a given record\n\n    Inspects request the record to locate an object\n\n    :param record: A dictionary representation of an object\n    :type record: dict\n    :returns: Found Object or None\n    :rtype: object"
  },
  {
    "code": "def createLocationEncoder(t, w=15):\n  encoder = CoordinateEncoder(name=\"positionEncoder\", n=t.l6CellCount, w=w)\n  return encoder",
    "docstring": "A default coordinate encoder for encoding locations into sparse\n  distributed representations."
  },
  {
    "code": "def _update_evaluated_individuals_(self, result_score_list, eval_individuals_str, operator_counts, stats_dicts):\n        for result_score, individual_str in zip(result_score_list, eval_individuals_str):\n            if type(result_score) in [float, np.float64, np.float32]:\n                self.evaluated_individuals_[individual_str] = self._combine_individual_stats(operator_counts[individual_str],\n                                                                                             result_score,\n                                                                                             stats_dicts[individual_str])\n            else:\n                raise ValueError('Scoring function does not return a float.')",
    "docstring": "Update self.evaluated_individuals_ and error message during pipeline evaluation.\n\n        Parameters\n        ----------\n        result_score_list: list\n            A list of CV scores for evaluated pipelines\n        eval_individuals_str: list\n            A list of strings for evaluated pipelines\n        operator_counts: dict\n            A dict where 'key' is the string representation of an individual and 'value' is the number of operators in the pipeline\n        stats_dicts: dict\n            A dict where 'key' is the string representation of an individual and 'value' is a dict containing statistics about the individual\n\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def _read_stc(stc_file):\n    hdr = _read_hdr_file(stc_file)\n    stc_dtype = dtype([('segment_name', 'a256'),\n                       ('start_stamp', '<i'),\n                       ('end_stamp', '<i'),\n                       ('sample_num', '<i'),\n                       ('sample_span', '<i')])\n    with stc_file.open('rb') as f:\n        f.seek(352)\n        hdr['next_segment'] = unpack('<i', f.read(4))[0]\n        hdr['final'] = unpack('<i', f.read(4))[0]\n        hdr['padding'] = unpack('<' + 'i' * 12, f.read(48))\n        stamps = fromfile(f, dtype=stc_dtype)\n    return hdr, stamps",
    "docstring": "Read Segment Table of Contents file.\n\n    Returns\n    -------\n    hdr : dict\n        - next_segment : Sample frequency in Hertz\n        - final : Number of channels stored\n        - padding : Padding\n    stamps : ndarray of dtype\n        - segment_name : Name of ERD / ETC file segment\n        - start_stamp : First sample stamp that is found in the ERD / ETC pair\n        - end_stamp : Last sample stamp that is still found in the ERD / ETC\n          pair\n        - sample_num : Number of samples actually being recorded (gaps in the\n          data are not included in this number)\n        - sample_span : Number of samples in that .erd file\n\n    Notes\n    -----\n    The Segment Table of Contents file is an index into pairs of (raw data file\n    / table of contents file). It is used for mapping samples file segments.\n    EEG raw data is split into segments in order to break a single file size\n    limit (used to be 2GB) while still allowing quick searches. This file ends\n    in the extension '.stc'. Default segment size (size of ERD file after which\n    it is closed and new [ERD / ETC] pair is opened) is 50MB. The file starts\n    with a generic EEG file header, and is followed by a series of fixed length\n    records called the STC entries. ERD segments are named according to the\n    following schema:\n\n      - <FIRST_NAME>, <LAST_NAME>_<GUID>.ERD (first)\n      - <FIRST_NAME>, <LAST_NAME>_<GUID>.ETC (first)\n      - <FIRST_NAME>, <LAST_NAME>_<GUID>_<INDEX>.ERD (second and subsequent)\n      - <FIRST_NAME>, <LAST_NAME>_<GUID>_<INDEX>.ETC (second and subsequent)\n\n    <INDEX> is formatted with \"%03d\" format specifier and starts at 1 (initial\n    value being 0 and omitted for compatibility with the previous versions)."
  },
  {
    "code": "def requires_auth(func):\n    @six.wraps(func)\n    def wrapper(self, *args, **kwargs):\n        if self.token_expired:\n            self.authenticate()\n        return func(self, *args, **kwargs)\n    return wrapper",
    "docstring": "Handle authentication checks.\n\n    .. py:decorator:: requires_auth\n\n        Checks if the token has expired and performs authentication if needed."
  },
  {
    "code": "def do_proplist(self, subcmd, opts, *args):\n        print \"'svn %s' opts: %s\" % (subcmd, opts)\n        print \"'svn %s' args: %s\" % (subcmd, args)",
    "docstring": "List all properties on files, dirs, or revisions.\n\n        usage:\n            1. proplist [PATH...]\n            2. proplist --revprop -r REV [URL]\n        \n        1. Lists versioned props in working copy.\n        2. Lists unversioned remote props on repos revision.\n\n        ${cmd_option_list}"
  },
  {
    "code": "def distribution(self, **slice_kwargs):\n        values = []\n        keys = []\n        for key, size in self.slice(count_only=True, **slice_kwargs):\n            values.append(size)\n            keys.append(key)\n        return keys, values",
    "docstring": "Calculates the number of papers in each slice, as defined by\n        ``slice_kwargs``.\n\n        Examples\n        --------\n        .. code-block:: python\n\n           >>> corpus.distribution(step_size=1, window_size=1)\n           [5, 5]\n\n        Parameters\n        ----------\n        slice_kwargs : kwargs\n            Keyword arguments to be passed to :meth:`.Corpus.slice`\\.\n\n        Returns\n        -------\n        list"
  },
  {
    "code": "def stream(\n        self,\n        accountID,\n        **kwargs\n    ):\n        request = Request(\n            'GET',\n            '/v3/accounts/{accountID}/transactions/stream'\n        )\n        request.set_path_param(\n            'accountID',\n            accountID\n        )\n        request.set_stream(True)\n        class Parser():\n            def __init__(self, ctx):\n                self.ctx = ctx\n            def __call__(self, line):\n                j = json.loads(line.decode('utf-8'))\n                type = j.get(\"type\")\n                if type is None:\n                    return (\"unknown\", j)\n                elif type == \"HEARTBEAT\":\n                    return (\n                        \"transaction.TransactionHeartbeat\",\n                        self.ctx.transaction.TransactionHeartbeat.from_dict(\n                            j,\n                            self.ctx\n                        )\n                    )\n                transaction = self.ctx.transaction.Transaction.from_dict(\n                    j, self.ctx\n                )\n                return (\n                    \"transaction.Transaction\",\n                    transaction\n                )\n        request.set_line_parser(\n            Parser(self.ctx)\n        )\n        response = self.ctx.request(request)\n        return response",
    "docstring": "Get a stream of Transactions for an Account starting from when the\n        request is made.\n\n        Args:\n            accountID:\n                Account Identifier\n\n        Returns:\n            v20.response.Response containing the results from submitting the\n            request"
  },
  {
    "code": "def flatten(input_list):\n    for el in input_list:\n        if isinstance(el, collections.Iterable) \\\n                and not isinstance(el, basestring):\n            for sub in flatten(el):\n                yield sub\n        else:\n            yield el",
    "docstring": "Return a flattened genertor from an input list.\n\n    Usage:\n\n        input_list = [['a'], ['b', 'c', 'd'], [['e']], ['f']]\n        list(flatten(input_list))\n        >> ['a', 'b', 'c', 'd', 'e', 'f']"
  },
  {
    "code": "def search_shell(self):\n        with self._lock:\n            if self._shell is not None:\n                return\n            reference = self._context.get_service_reference(SERVICE_SHELL)\n            if reference is not None:\n                self.set_shell(reference)",
    "docstring": "Looks for a shell service"
  },
  {
    "code": "def create_assign_context_menu(self):\n        menu = QMenu(\"AutoKey\")\n        self._build_menu(menu)\n        self.setContextMenu(menu)",
    "docstring": "Create a context menu, then set the created QMenu as the context menu.\n        This builds the menu with all required actions and signal-slot connections."
  },
  {
    "code": "def write_terminal(matrix, version, out, border=None):\n    with writable(out, 'wt') as f:\n        write = f.write\n        colours = ['\\033[{0}m'.format(i) for i in (7, 49)]\n        for row in matrix_iter(matrix, version, scale=1, border=border):\n            prev_bit = -1\n            cnt = 0\n            for bit in row:\n                if bit == prev_bit:\n                    cnt += 1\n                else:\n                    if cnt:\n                        write(colours[prev_bit])\n                        write('  ' * cnt)\n                        write('\\033[0m')\n                    prev_bit = bit\n                    cnt = 1\n            if cnt:\n                write(colours[prev_bit])\n                write('  ' * cnt)\n                write('\\033[0m')\n            write('\\n')",
    "docstring": "\\\n    Function to write to a terminal which supports ANSI escape codes.\n\n    :param matrix: The matrix to serialize.\n    :param int version: The (Micro) QR code version.\n    :param out: Filename or a file-like object supporting to write text.\n    :param int border: Integer indicating the size of the quiet zone.\n            If set to ``None`` (default), the recommended border size\n            will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes)."
  },
  {
    "code": "def XstarT_dot(self,M):\n        if 0:\n            pass\n        else:\n            RV = np.dot(self.Xstar().T,M)\n        return RV",
    "docstring": "get dot product of Xhat and M"
  },
  {
    "code": "def flatten(l):\n    for el in l:\n        if _iterable_not_string(el):\n            for s in flatten(el):\n                yield s\n        else:\n            yield el",
    "docstring": "Flatten an arbitrarily nested sequence.\n\n    Parameters\n    ----------\n    l : sequence\n        The non string sequence to flatten\n\n    Notes\n    -----\n    This doesn't consider strings sequences.\n\n    Returns\n    -------\n    flattened : generator"
  },
  {
    "code": "def check_web_config(config_fname):\n    print(\"Looking for config file at {0} ...\".format(config_fname))\n    config = RawConfigParser()\n    try:\n        config.readfp(open(config_fname))\n        return config\n    except IOError:\n        print(\"ERROR: Seems like the config file does not exist. Please call 'opensubmit-web configcreate' first, or specify a location with the '-c' option.\")\n        return None",
    "docstring": "Try to load the Django settings.\n        If this does not work, than settings file does not exist.\n\n        Returns:\n            Loaded configuration, or None."
  },
  {
    "code": "def root_parent(self, category=None):\n        return next(filter(lambda c: c.is_root, self.hierarchy()))",
    "docstring": "Returns the topmost parent of the current category."
  },
  {
    "code": "def apply(self, func, *args, **kwds):\n        wrapped = self._wrapped_apply(func, *args, **kwds)\n        n_repeats = 3\n        timed = timeit.timeit(wrapped, number=n_repeats)\n        samp_proc_est = timed / n_repeats\n        est_apply_duration = samp_proc_est / self._SAMP_SIZE * self._nrows\n        if est_apply_duration > self._dask_threshold:\n            return self._dask_apply(func, *args, **kwds)\n        else:\n            if self._progress_bar:\n                tqdm.pandas(desc=\"Pandas Apply\")\n                return self._obj_pd.progress_apply(func, *args, **kwds)\n            else:\n                return self._obj_pd.apply(func, *args, **kwds)",
    "docstring": "Apply the function to the transformed swifter object"
  },
  {
    "code": "def run(self):\n        if not (self.table):\n            raise Exception(\"table need to be specified\")\n        path = self.s3_load_path()\n        output = self.output()\n        connection = output.connect()\n        cursor = connection.cursor()\n        self.init_copy(connection)\n        self.copy(cursor, path)\n        self.post_copy(cursor)\n        if self.enable_metadata_columns:\n            self.post_copy_metacolumns(cursor)\n        output.touch(connection)\n        connection.commit()\n        connection.close()",
    "docstring": "If the target table doesn't exist, self.create_table\n        will be called to attempt to create the table."
  },
  {
    "code": "def add_waveform(self, waveform):\n        if not isinstance(waveform, PlotWaveform):\n            self.log_exc(u\"waveform must be an instance of PlotWaveform\", None, True, TypeError)\n        self.waveform = waveform\n        self.log(u\"Added waveform\")",
    "docstring": "Add a waveform to the plot.\n\n        :param waveform: the waveform to be added\n        :type  waveform: :class:`~aeneas.plotter.PlotWaveform`\n        :raises: TypeError: if ``waveform`` is not an instance of :class:`~aeneas.plotter.PlotWaveform`"
  },
  {
    "code": "def next(self):\n        try:\n            results = self._stride_buffer.pop()\n        except (IndexError, AttributeError):\n            self._rebuffer()\n            results = self._stride_buffer.pop()\n        if not results:\n            raise StopIteration\n        return results",
    "docstring": "Returns the next sequence of results, given stride and n."
  },
  {
    "code": "def warning(self, amplexception):\n        msg = '\\t'+str(amplexception).replace('\\n', '\\n\\t')\n        print('Warning:\\n{:s}'.format(msg))",
    "docstring": "Receives notification of a warning."
  },
  {
    "code": "def append(self, ldap_filter):\n        if not isinstance(ldap_filter, (LDAPFilter, LDAPCriteria)):\n            raise TypeError(\n                \"Invalid filter type: {0}\".format(type(ldap_filter).__name__)\n            )\n        if len(self.subfilters) >= 1 and self.operator == NOT:\n            raise ValueError(\"Not operator only handles one child\")\n        self.subfilters.append(ldap_filter)",
    "docstring": "Appends a filter or a criterion to this filter\n\n        :param ldap_filter: An LDAP filter or criterion\n        :raise TypeError: If the parameter is not of a known type\n        :raise ValueError: If the more than one filter is associated to a\n                           NOT operator"
  },
  {
    "code": "def current(cls):\n        name = socket.getfqdn()\n        ip = socket.gethostbyname(name)\n        return cls(name, ip)",
    "docstring": "Helper method for getting the current peer of whichever host we're\n        running on."
  },
  {
    "code": "def align(self, input_path, output_path, directions, pipeline, \n              filter_minimum):\n        with tempfile.NamedTemporaryFile(prefix='for_conv_file', suffix='.fa') as fwd_fh:\n            fwd_conv_file = fwd_fh.name\n            with tempfile.NamedTemporaryFile(prefix='rev_conv_file', suffix='.fa') as rev_fh:\n                rev_conv_file = rev_fh.name\n                alignments = self._hmmalign(\n                    input_path,\n                    directions,\n                    pipeline,\n                    fwd_conv_file,\n                    rev_conv_file)\n                alignment_result = self.alignment_correcter(alignments,\n                                                            output_path,\n                                                            filter_minimum)\n                return alignment_result",
    "docstring": "align - Takes input path to fasta of unaligned reads, aligns them to\n        a HMM, and returns the aligned reads in the output path\n\n        Parameters\n        ----------\n        input_path : str\n        output_path : str\n        reverse_direction : dict\n            A dictionary of read names, with the entries being the complement\n            strand of the read (True = forward, False = reverse)\n        pipeline : str\n            Either \"P\" or \"D\" corresponding to the protein and nucleotide (DNA)\n            pipelines, respectively.\n\n\n        Returns\n        -------\n        N/A - output alignment path known."
  },
  {
    "code": "def _process_added_port_event(self, port_name):\n        LOG.info(\"Hyper-V VM vNIC added: %s\", port_name)\n        self._added_ports.add(port_name)",
    "docstring": "Callback for added ports."
  },
  {
    "code": "def set_components(self, params):\n        for key, value in params.items():\n            if isinstance(value, pd.Series):\n                new_function = self._timeseries_component(value)\n            elif callable(value):\n                new_function = value\n            else:\n                new_function = self._constant_component(value)\n            func_name = utils.get_value_by_insensitive_key_or_value(key, self.components._namespace)\n            if func_name is None:\n                raise NameError('%s is not recognized as a model component' % key)\n            if '_integ_' + func_name in dir(self.components):\n                warnings.warn(\"Replacing the equation of stock {} with params\".format(key),\n                              stacklevel=2)\n            setattr(self.components, func_name, new_function)",
    "docstring": "Set the value of exogenous model elements.\n        Element values can be passed as keyword=value pairs in the function call.\n        Values can be numeric type or pandas Series.\n        Series will be interpolated by integrator.\n\n        Examples\n        --------\n\n        >>> model.set_components({'birth_rate': 10})\n        >>> model.set_components({'Birth Rate': 10})\n\n        >>> br = pandas.Series(index=range(30), values=np.sin(range(30))\n        >>> model.set_components({'birth_rate': br})"
  },
  {
    "code": "def add(self, rd, ttl=None):\n        if self.rdclass != rd.rdclass or self.rdtype != rd.rdtype:\n            raise IncompatibleTypes\n        if not ttl is None:\n            self.update_ttl(ttl)\n        if self.rdtype == dns.rdatatype.RRSIG or \\\n           self.rdtype == dns.rdatatype.SIG:\n            covers = rd.covers()\n            if len(self) == 0 and self.covers == dns.rdatatype.NONE:\n                self.covers = covers\n            elif self.covers != covers:\n                raise DifferingCovers\n        if dns.rdatatype.is_singleton(rd.rdtype) and len(self) > 0:\n            self.clear()\n        super(Rdataset, self).add(rd)",
    "docstring": "Add the specified rdata to the rdataset.\n\n        If the optional I{ttl} parameter is supplied, then\n        self.update_ttl(ttl) will be called prior to adding the rdata.\n\n        @param rd: The rdata\n        @type rd: dns.rdata.Rdata object\n        @param ttl: The TTL\n        @type ttl: int"
  },
  {
    "code": "def _get_user(self, user):\n        return ' '.join([user.username, user.first_name, user.last_name])",
    "docstring": "Generate user filtering tokens."
  },
  {
    "code": "def merge_query(path, postmap, force_unicode=True):\n    if postmap:\n        p = postmap.copy()\n    else:\n        p = {}\n    p.update(get_query(path, force_unicode=False))\n    if force_unicode:\n        p = _unicode(p)\n    return p",
    "docstring": "Merges params parsed from the URI into the mapping from the POST body and\n    returns a new dict with the values.\n\n    This is a convenience function that gives use a dict a bit like PHP's $_REQUEST\n    array.  The original 'postmap' is preserved so the caller can identify a\n    param's source if necessary."
  },
  {
    "code": "def get_correctness_for_response(self, response):\n        for answer in self.my_osid_object.get_answers():\n            if self._is_match(response, answer):\n                try:\n                    return answer.get_score()\n                except AttributeError:\n                    return 100\n        for answer in self.my_osid_object.get_wrong_answers():\n            if self._is_match(response, answer):\n                try:\n                    return answer.get_score()\n                except AttributeError:\n                    return 0\n        return 0",
    "docstring": "get measure of correctness available for a particular response"
  },
  {
    "code": "def scan_file(self, this_file):\n        params = {'apikey': self.api_key}\n        try:\n            if type(this_file) == str and os.path.isfile(this_file):\n                files = {'file': (this_file, open(this_file, 'rb'))}\n            elif isinstance(this_file, StringIO.StringIO):\n                files = {'file': this_file.read()}\n            else:\n                files = {'file': this_file}\n        except TypeError as e:\n            return dict(error=e.message)\n        try:\n            response = requests.post(self.base + 'file/scan', files=files, params=params, proxies=self.proxies)\n        except requests.RequestException as e:\n            return dict(error=e.message)\n        return _return_response_and_status_code(response)",
    "docstring": "Submit a file to be scanned by VirusTotal\n\n        :param this_file: File to be scanned (32MB file size limit)\n        :return: JSON response that contains scan_id and permalink."
  },
  {
    "code": "def _get_websocket(self, reuse=True):\n        if self.ws and reuse:\n            if self.ws.connected:\n                return self.ws\n            logging.debug(\"Stale connection, reconnecting.\")\n        self.ws = self._create_connection()\n        return self.ws",
    "docstring": "Reuse existing connection or create a new connection."
  },
  {
    "code": "def cli(conf):\n    try:\n        config = init_config(conf)\n        debug = config.getboolean('DEFAULT', 'debug')\n        conn = get_conn(config.get('DEFAULT','statusdb'))\n        cur = conn.cursor()\n        sqlstr =\n        try:\n            cur.execute('drop table client_status')\n        except:\n            pass\n        cur.execute(sqlstr)\n        print 'flush client status database'\n        conn.commit()\n        conn.close()\n    except:\n        traceback.print_exc()",
    "docstring": "OpenVPN status initdb method"
  },
  {
    "code": "def log_status (self):\n        duration = time.time() - self.start_time\n        checked, in_progress, queue = self.aggregator.urlqueue.status()\n        num_urls = len(self.aggregator.result_cache)\n        self.logger.log_status(checked, in_progress, queue, duration, num_urls)",
    "docstring": "Log a status message."
  },
  {
    "code": "def find_log_dir(log_dir=None):\n  if log_dir:\n    dirs = [log_dir]\n  elif FLAGS['log_dir'].value:\n    dirs = [FLAGS['log_dir'].value]\n  else:\n    dirs = ['/tmp/', './']\n  for d in dirs:\n    if os.path.isdir(d) and os.access(d, os.W_OK):\n      return d\n  _absl_logger.fatal(\"Can't find a writable directory for logs, tried %s\", dirs)",
    "docstring": "Returns the most suitable directory to put log files into.\n\n  Args:\n    log_dir: str|None, if specified, the logfile(s) will be created in that\n        directory.  Otherwise if the --log_dir command-line flag is provided,\n        the logfile will be created in that directory.  Otherwise the logfile\n        will be created in a standard location."
  },
  {
    "code": "def addLNT(LocalName, phenoId, predicate, g=None):\n    if g is None:\n        s = inspect.stack(0)\n        checkCalledInside('LocalNameManager', s)\n        g = s[1][0].f_locals\n    addLN(LocalName, Phenotype(phenoId, predicate), g)",
    "docstring": "Add a local name for a phenotype from a pair of identifiers"
  },
  {
    "code": "def close(self):\n        try:\n            self.sock.shutdown(socket.SHUT_RDWR)\n            self.sock.close()\n        except socket.error:\n            pass",
    "docstring": "Closes the tunnel."
  },
  {
    "code": "def write(self, src, dest=None):\n    if not src or not isinstance(src, string_types):\n      raise ValueError('The src path must be a non-empty string, got {} of type {}.'.format(\n        src, type(src)))\n    if dest and not isinstance(dest, string_types):\n      raise ValueError('The dest entry path must be a non-empty string, got {} of type {}.'.format(\n        dest, type(dest)))\n    if not os.path.isdir(src) and not dest:\n      raise self.Error('Source file {} must have a jar destination specified'.format(src))\n    self._add_entry(self.FileSystemEntry(src, dest))",
    "docstring": "Schedules a write of the file at ``src`` to the ``dest`` path in this jar.\n\n    If the ``src`` is a file, then ``dest`` must be specified.\n\n    If the ``src`` is a directory then by default all descendant files will be added to the jar as\n    entries carrying their relative path.  If ``dest`` is specified it will be prefixed to each\n    descendant's relative path to form its jar entry path.\n\n    :param string src: the path to the pre-existing source file or directory\n    :param string dest: the path the source file or directory should have in this jar"
  },
  {
    "code": "def put(self, key, val, minutes):\n        minutes = self._get_minutes(minutes)\n        if minutes is not None:\n            self._store.put(key, val, minutes)",
    "docstring": "Store an item in the cache.\n\n        :param key: The cache key\n        :type key: str\n\n        :param val: The cache value\n        :type val: mixed\n\n        :param minutes: The lifetime in minutes of the cached value\n        :type minutes: int|datetime"
  },
  {
    "code": "def _set_ip(self):\n        self._ip = socket.gethostbyname(self._fqdn)\n        log.debug('IP: %s' % self._ip)",
    "docstring": "Resolve FQDN to IP address"
  },
  {
    "code": "def flatten_reducer(\n        flattened_list: list,\n        entry: typing.Union[list, tuple, COMPONENT]\n) -> list:\n    if hasattr(entry, 'includes') and hasattr(entry, 'files'):\n        flattened_list.append(entry)\n    elif entry:\n        flattened_list.extend(entry)\n    return flattened_list",
    "docstring": "Flattens a list of COMPONENT instances to remove any lists or tuples\n    of COMPONENTS contained within the list\n\n    :param flattened_list:\n        The existing flattened list that has been populated from previous\n        calls of this reducer function\n    :param entry:\n        An entry to be reduced. Either a COMPONENT instance or a list/tuple\n        of COMPONENT instances\n    :return:\n        The flattened list with the entry flatly added to it"
  },
  {
    "code": "def add_pyspark_path():\n    try:\n        spark_home = os.environ['SPARK_HOME']\n        sys.path.append(os.path.join(spark_home, 'python'))\n        py4j_src_zip = glob(os.path.join(spark_home, 'python',\n                                         'lib', 'py4j-*-src.zip'))\n        if len(py4j_src_zip) == 0:\n            raise ValueError('py4j source archive not found in %s'\n                             % os.path.join(spark_home, 'python', 'lib'))\n        else:\n            py4j_src_zip = sorted(py4j_src_zip)[::-1]\n            sys.path.append(py4j_src_zip[0])\n    except KeyError:\n        logging.error(\n)\n        exit(-1)\n    except ValueError as e:\n        logging.error(str(e))\n        exit(-1)",
    "docstring": "Add PySpark to the library path based on the value of SPARK_HOME."
  },
  {
    "code": "def provide_session(self, start_new=False):\n        if self.is_global:\n            self._session_info = self._global_session_info\n            self._session_start = self._global_session_start\n        if self._session_info is None or start_new or \\\n                datetime.datetime.now() > self._session_start + self.SESSION_DURATION:\n            self._start_new_session()\n        return self._session_info",
    "docstring": "Makes sure that session is still valid and provides session info\n\n        :param start_new: If `True` it will always create a new session. Otherwise it will create a new\n            session only if no session exists or the previous session timed out.\n        :type start_new: bool\n        :return: Current session info\n        :rtype: dict"
  },
  {
    "code": "def ctr_geom(geom, masses):\n    import numpy as np\n    shift = np.tile(ctr_mass(geom, masses), geom.shape[0] / 3)\n    ctr_geom = geom - shift\n    return ctr_geom",
    "docstring": "Returns geometry shifted to center of mass.\n\n    Helper function to automate / encapsulate translation of a geometry to its\n    center of mass.\n\n    Parameters\n    ----------\n    geom\n        length-3N |npfloat_| --\n        Original coordinates of the atoms\n\n    masses\n        length-N OR length-3N |npfloat_| --\n        Atomic masses of the atoms. Length-3N option is to allow calculation of\n        a per-coordinate perturbed value.\n\n    Returns\n    -------\n    ctr_geom\n        length-3N |npfloat_| --\n        Atomic coordinates after shift to center of mass\n\n    Raises\n    ------\n    ~exceptions.ValueError\n        If shapes of `geom` & `masses` are inconsistent"
  },
  {
    "code": "def supply(self, issuer):\n        def _retrieve_jwks():\n            jwks_uri = self._key_uri_supplier.supply(issuer)\n            if not jwks_uri:\n                raise UnauthenticatedException(u\"Cannot find the `jwks_uri` for issuer \"\n                                               u\"%s: either the issuer is unknown or \"\n                                               u\"the OpenID discovery failed\" % issuer)\n            try:\n                response = requests.get(jwks_uri)\n                json_response = response.json()\n            except Exception as exception:\n                message = u\"Cannot retrieve valid verification keys from the `jwks_uri`\"\n                raise UnauthenticatedException(message, exception)\n            if u\"keys\" in json_response:\n                jwks_keys = jwk.KEYS()\n                jwks_keys.load_jwks(response.text)\n                return jwks_keys._keys\n            else:\n                return _extract_x509_certificates(json_response)\n        return self._jwks_cache.get_or_create(issuer, _retrieve_jwks)",
    "docstring": "Supplies the `Json Web Key Set` for the given issuer.\n\n        Args:\n          issuer: the issuer.\n\n        Returns:\n          The successfully retrieved Json Web Key Set. None is returned if the\n            issuer is unknown or the retrieval process fails.\n\n        Raises:\n          UnauthenticatedException: When this method cannot supply JWKS for the\n            given issuer (e.g. unknown issuer, HTTP request error)."
  },
  {
    "code": "def remember_forever(self, key, callback):\n        val = self.get(key)\n        if val is not None:\n            return val\n        val = value(callback)\n        self.forever(key, val)\n        return val",
    "docstring": "Get an item from the cache, or store the default value forever.\n\n        :param key: The cache key\n        :type key: str\n\n        :param callback: The default function\n        :type callback: mixed\n\n        :rtype: mixed"
  },
  {
    "code": "def calculate_input(self, buffer):\n        if TriggerMode.ABBREVIATION in self.modes:\n            if self._should_trigger_abbreviation(buffer):\n                if self.immediate:\n                    return len(self._get_trigger_abbreviation(buffer))\n                else:\n                    return len(self._get_trigger_abbreviation(buffer)) + 1\n        if TriggerMode.HOTKEY in self.modes:\n            if buffer == '':\n                return len(self.modifiers) + 1\n        return self.parent.calculate_input(buffer)",
    "docstring": "Calculate how many keystrokes were used in triggering this phrase."
  },
  {
    "code": "def access_service_descriptor(price, consume_endpoint, service_endpoint, timeout, template_id):\n        return (ServiceTypes.ASSET_ACCESS,\n                {'price': price, 'consumeEndpoint': consume_endpoint,\n                 'serviceEndpoint': service_endpoint,\n                 'timeout': timeout, 'templateId': template_id})",
    "docstring": "Access service descriptor.\n\n        :param price: Asset price, int\n        :param consume_endpoint: url of the service provider, str\n        :param service_endpoint: identifier of the service inside the asset DDO, str\n        :param timeout: amount of time in seconds before the agreement expires, int\n        :param template_id: id of the template use to create the service, str\n        :return: Service descriptor."
  },
  {
    "code": "def update_view_bounds(self):\n        self.view_bounds.left = self.pan.X - self.world_center.X\n        self.view_bounds.top = self.pan.Y - self.world_center.Y\n        self.view_bounds.width = self.world_center.X * 2\n        self.view_bounds.height = self.world_center.Y * 2",
    "docstring": "Update the camera's view bounds."
  },
  {
    "code": "def tabledefinehypercolumn(tabdesc,\n                           name, ndim, datacolumns,\n                           coordcolumns=False,\n                           idcolumns=False):\n    rec = {'HCndim': ndim,\n           'HCdatanames': datacolumns}\n    if not isinstance(coordcolumns, bool):\n        rec['HCcoordnames'] = coordcolumns\n    if not isinstance(idcolumns, bool):\n        rec['HCidnames'] = idcolumns\n    if '_define_hypercolumn_' not in tabdesc:\n        tabdesc['_define_hypercolumn_'] = {}\n    tabdesc['_define_hypercolumn_'][name] = rec",
    "docstring": "Add a hypercolumn to a table description.\n\n    It defines a hypercolumn and adds it the given table description.\n    A hypercolumn is an entity used by the Tiled Storage Managers (TSM). It\n    defines which columns have to be stored together with a TSM.\n\n    It should only be used by expert users who want to use a TSM to its\n    full extent. For a basic TSM s hypercolumn definition is not needed.\n\n    tabledesc\n      A table description (result from :func:`maketabdesc`).\n    name\n      Name of hypercolumn\n    ndim\n      Dimensionality of hypercolumn; normally 1 more than the dimensionality\n      of the arrays in the data columns to be stored with the TSM\n    datacolumns\n      Data columns to be stored with TSM\n    coordcolumns\n      Optional coordinate columns to be stored with TSM\n    idcolumns\n      Optional id columns to be stored with TSM\n\n    For example::\n\n      scd1 = makescacoldesc(\"col2\", \"aa\")\n      scd2 = makescacoldesc(\"col1\", 1, \"IncrementalStMan\")\n      scd3 = makescacoldesc(\"colrec1\", {})\n      acd1 = makearrcoldesc(\"arr1\", 1, 0, [2,3,4])\n      acd2 = makearrcoldesc(\"arr2\", as_complex(0))\n      td = maketabdesc([scd1, scd2, scd3, acd1, acd2])\n      tabledefinehypercolumn(td, \"TiledArray\", 4, [\"arr1\"])\n      tab = table(\"mytable\", tabledesc=td, nrow=100)\n\n    | This creates a table description `td` from five column descriptions\n      and then creates a 100-row table called mytable from the table\n      description.\n    | The columns contain respectivily strings, integer scalars, records,\n      3D integer arrays with fixed shape [2,3,4], and complex arrays with\n      variable shape.\n    | The first array is stored with the Tiled Storage Manager (in this case\n      the TiledColumnStMan)."
  },
  {
    "code": "def trim_and_pad_all_features(features, length):\n  return {k: _trim_and_pad(v, length) for k, v in features.items()}",
    "docstring": "Trim and pad first dimension of all features to size length."
  },
  {
    "code": "def best_prefix(bytes, system=NIST):\n    if isinstance(bytes, Bitmath):\n        value = bytes.bytes\n    else:\n        value = bytes\n    return Byte(value).best_prefix(system=system)",
    "docstring": "Return a bitmath instance representing the best human-readable\nrepresentation of the number of bytes given by ``bytes``. In addition\nto a numeric type, the ``bytes`` parameter may also be a bitmath type.\n\nOptionally select a preferred unit system by specifying the ``system``\nkeyword. Choices for ``system`` are ``bitmath.NIST`` (default) and\n``bitmath.SI``.\n\nBasically a shortcut for:\n\n   >>> import bitmath\n   >>> b = bitmath.Byte(12345)\n   >>> best = b.best_prefix()\n\nOr:\n\n   >>> import bitmath\n   >>> best = (bitmath.KiB(12345) * 4201).best_prefix()"
  },
  {
    "code": "def _fill_and_verify_parameter_shape(x, n, parameter_label):\n  try:\n    return _fill_shape(x, n)\n  except TypeError as e:\n    raise base.IncompatibleShapeError(\"Invalid \" + parameter_label + \" shape: \"\n                                      \"{}\".format(e))",
    "docstring": "Expands x if necessary into a `n`-D kernel shape and reports errors."
  },
  {
    "code": "def send_commands(self, commands, timeout=1.0,\n                      max_retries=1, eor=('\\n', '\\n- ')):\n        if not isinstance(eor, list):\n            eor = [eor]*len(commands)\n        responses = []\n        for i, command in enumerate(commands):\n            rsp = self.send_command(command, timeout=timeout,\n                                    max_retries=max_retries,\n                                    eor=eor[i])\n            responses.append(rsp)\n            if self.command_error(rsp):\n                break\n            time.sleep(0.25)\n        return responses",
    "docstring": "Send a sequence of commands to the drive and collect output.\n\n        Takes a sequence of many commands and executes them one by one\n        till either all are executed or one runs out of retries\n        (`max_retries`). Retries are optionally performed if a command's\n        repsonse indicates that there was an error. Remaining commands\n        are not executed. The processed output of the final execution\n        (last try or retry) of each command that was actually executed\n        is returned.\n\n        This function basically feeds commands one by one to\n        ``send_command`` and collates the outputs.\n\n        Parameters\n        ----------\n        commands : iterable of str\n            Iterable of commands to send to the drive. Each command must\n            be an ``str``.\n        timeout : float or None, optional\n            Optional timeout in seconds to use when reading the\n            response. A negative value or ``None`` indicates that the\n            an infinite timeout should be used.\n        max_retries : int, optional\n            Maximum number of retries to do per command in the case of\n            errors.\n        eor : str or iterable of str, optional\n            End Of Resonse. An EOR is either a ``str`` or an iterable\n            of ``str`` that denote the possible endings of a response.\n            'eor' can be a single EOR, in which case it is used for all\n            commands, or it can be an iterable of EOR to use for each\n            individual command. For most commands, it should be\n            ``('\\\\n', '\\\\n- ')``, but for running a program, it should\n            be ``'*END\\\\n'``. The default is ``('\\\\n', '\\\\n- ')``.\n\n        Returns\n        -------\n        outputs : list of lists\n            ``list`` composed of the processed responses of each command\n            in the order that they were done up to and including the\n            last command executed. See ``send_command`` for the format\n            of processed responses.\n\n        See Also\n        --------\n        send_command : Send a single command.\n\n        Examples\n        --------\n\n        A sequence of commands to energize the motor, move it a bit away\n        from the starting position, and then do 4 forward/reverse\n        cycles, and de-energize the motor. **DO NOT** try these specific\n        movement distances without checking that the motion won't damage\n        something (very motor and application specific).\n\n        >>> from GeminiMotorDrive.drivers import ASCII_RS232\n        >>> ra = ASCII_RS232('/dev/ttyS1')\n        >>> ra.send_commands(['DRIVE1', 'D-10000', 'GO']\n        ...                  + ['D-10000','GO','D10000','GO']*4\n        ...                  + [ 'DRIVE0'])\n        [['DRIVE1', 'DRIVE1\\\\r', 'DRIVE1', None, []],\n         ['D-10000', 'D-10000\\\\r', 'D-10000', None, []],\n         ['GO', 'GO\\\\r', 'GO', None, []],\n         ['D-10000', 'D-10000\\\\r', 'D-10000', None, []],\n         ['GO', 'GO\\\\r', 'GO', None, []],\n         ['D10000', 'D10000\\\\r', 'D10000', None, []],\n         ['GO', 'GO\\\\r', 'GO', None, []],\n         ['D-10000', 'D-10000\\\\r', 'D-10000', None, []],\n         ['GO', 'GO\\\\r', 'GO', None, []],\n         ['D10000', 'D10000\\\\r', 'D10000', None, []],\n         ['GO', 'GO\\\\r', 'GO', None, []],\n         ['D-10000', 'D-10000\\\\r', 'D-10000', None, []],\n         ['GO', 'GO\\\\r', 'GO', None, []],\n         ['D10000', 'D10000\\\\r', 'D10000', None, []],\n         ['GO', 'GO\\\\r', 'GO', None, []],\n         ['D-10000', 'D-10000\\\\r', 'D-10000', None, []],\n         ['GO', 'GO\\\\r', 'GO', None, []],\n         ['D10000', 'D10000\\\\r', 'D10000', None, []],\n         ['GO', 'GO\\\\r', 'GO', None, []],\n         ['DRIVE0', 'DRIVE0\\\\r', 'DRIVE0', None, []]]"
  },
  {
    "code": "def variance(x):\n    if x.ndim > 1 and len(x[0]) > 1:\n        return np.var(x, axis=1)\n    return np.var(x)",
    "docstring": "Return a numpy array of column variance\n\n    Parameters\n    ----------\n    x : ndarray\n        A numpy array instance\n\n    Returns\n    -------\n    ndarray\n        A 1 x n numpy array instance of column variance\n\n    Examples\n    --------\n    >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n    >>> np.testing.assert_array_almost_equal(\n    ...     variance(a),\n    ...     [0.666666, 0.666666, 0.666666])\n    >>> a = np.array([1, 2, 3])\n    >>> np.testing.assert_array_almost_equal(\n    ...     variance(a),\n    ...     0.666666)"
  },
  {
    "code": "def get_etag(storage, path, prefixed_path):\n    cache_key = get_cache_key(path)\n    etag = cache.get(cache_key, False)\n    if etag is False:\n        etag = get_remote_etag(storage, prefixed_path)\n        cache.set(cache_key, etag)\n    return etag",
    "docstring": "Get etag of path from cache or S3 - in that order."
  },
  {
    "code": "def date_to_long_form_string(dt, locale_ = 'en_US.utf8'):\n    if locale_:\n        old_locale = locale.getlocale()\n        locale.setlocale(locale.LC_ALL, locale_)\n    v = dt.strftime(\"%A %B %d %Y\")\n    if locale_:\n        locale.setlocale(locale.LC_ALL, old_locale)\n    return v",
    "docstring": "dt should be a datetime.date object."
  },
  {
    "code": "def write(self):\n        with open(self.filepath, 'wb') as outfile:\n            outfile.write(\n                self.fernet.encrypt(\n                    yaml.dump(self.data, encoding='utf-8')))",
    "docstring": "Encrypts and writes the current state back onto the filesystem"
  },
  {
    "code": "def xpath(self, xpath, **kwargs):\n        result = self.adapter.xpath_on_node(self.impl_node, xpath, **kwargs)\n        if isinstance(result, (list, tuple)):\n            return [self._maybe_wrap_node(r) for r in result]\n        else:\n            return self._maybe_wrap_node(result)",
    "docstring": "Perform an XPath query on the current node.\n\n        :param string xpath: XPath query.\n        :param dict kwargs: Optional keyword arguments that are passed through\n            to the underlying XML library implementation.\n\n        :return: results of the query as a list of :class:`Node` objects, or\n            a list of base type objects if the XPath query does not reference\n            node objects."
  },
  {
    "code": "def get_item(env, name, default=None):\n  for key in name.split('.'):\n    if isinstance(env, dict) and key in env:\n      env = env[key]\n    elif isinstance(env, types.ModuleType) and key in env.__dict__:\n      env = env.__dict__[key]\n    else:\n      return default\n  return env",
    "docstring": "Get an item from a dictionary, handling nested lookups with dotted notation.\n\n  Args:\n    env: the environment (dictionary) to use to look up the name.\n    name: the name to look up, in dotted notation.\n    default: the value to return if the name if not found.\n\n  Returns:\n    The result of looking up the name, if found; else the default."
  },
  {
    "code": "def maxTreeDepthDivide(rootValue, currentDepth=0, parallelLevel=2):\n    thisRoot = shared.getConst('myTree').search(rootValue)\n    if currentDepth >= parallelLevel:\n        return thisRoot.maxDepth(currentDepth)\n    else:\n        if not any([thisRoot.left, thisRoot.right]):\n            return currentDepth\n        if not all([thisRoot.left, thisRoot.right]):\n            return thisRoot.maxDepth(currentDepth)\n        return max(\n            futures.map(\n                maxTreeDepthDivide,\n                [\n                    thisRoot.left.payload,\n                    thisRoot.right.payload,\n                ],\n                cycle([currentDepth + 1]),\n                cycle([parallelLevel]),\n            )\n        )",
    "docstring": "Finds a tree node that represents rootValue and computes the max depth\n       of this tree branch.\n       This function will emit new futures until currentDepth=parallelLevel"
  },
  {
    "code": "def header(self):\n        return \"place %s\\n\" % self.location.city + \\\n            \"latitude %.2f\\n\" % self.location.latitude + \\\n            \"longitude %.2f\\n\" % -self.location.longitude + \\\n            \"time_zone %d\\n\" % (-self.location.time_zone * 15) + \\\n            \"site_elevation %.1f\\n\" % self.location.elevation + \\\n            \"weather_data_file_units 1\\n\"",
    "docstring": "Wea header."
  },
  {
    "code": "def active_pt_window(self):\n        \" The active prompt_toolkit layout Window. \"\n        if self.active_tab:\n            w = self.active_tab.active_window\n            if w:\n                return w.pt_window",
    "docstring": "The active prompt_toolkit layout Window."
  },
  {
    "code": "def get_user_details(self, response):\n        account = response['account']\n        metadata = json.loads(account.get('json_metadata') or '{}')\n        account['json_metadata'] = metadata\n        return {\n            'id': account['id'],\n            'username': account['name'],\n            'name': metadata.get(\"profile\", {}).get('name', ''),\n            'account': account,\n        }",
    "docstring": "Return user details from GitHub account"
  },
  {
    "code": "def unmarshal( compoundSignature, data, offset = 0, lendian = True ):\n    values       = list()\n    start_offset = offset\n    for ct in genCompleteTypes( compoundSignature ):\n        tcode   = ct[0]\n        offset += len(pad[tcode]( offset ))\n        nbytes, value = unmarshallers[ tcode ]( ct, data, offset, lendian )\n        offset += nbytes\n        values.append( value )\n    return offset - start_offset, values",
    "docstring": "Unmarshals DBus encoded data.\n\n    @type compoundSignature: C{string}\n    @param compoundSignature: DBus signature specifying the encoded value types\n\n    @type data: C{string}\n    @param data: Binary data\n\n    @type offset: C{int}\n    @param offset: Offset within data at which data for compoundSignature\n                   starts (used during recursion)\n\n    @type lendian: C{bool}\n    @param lendian: True if data is encoded in little-endian format\n    \n    @returns: (number_of_bytes_decoded, list_of_values)"
  },
  {
    "code": "def DeserializeTX(buffer):\n        mstream = MemoryStream(buffer)\n        reader = BinaryReader(mstream)\n        tx = Transaction.DeserializeFrom(reader)\n        return tx",
    "docstring": "Deserialize the stream into a Transaction object.\n\n        Args:\n            buffer (BytesIO): stream to deserialize the Transaction from.\n\n        Returns:\n            neo.Core.TX.Transaction:"
  },
  {
    "code": "def run_in_greenlet(callable):\n    @wraps(callable)\n    async def _(*args, **kwargs):\n        green = greenlet(callable)\n        result = green.switch(*args, **kwargs)\n        while isawaitable(result):\n            try:\n                result = green.switch((await result))\n            except Exception:\n                exc_info = sys.exc_info()\n                result = green.throw(*exc_info)\n        return green.switch(result)\n    return _",
    "docstring": "Decorator to run a ``callable`` on a new greenlet.\n\n    A ``callable`` decorated with this decorator returns a coroutine"
  },
  {
    "code": "def CopyToDateTimeString(self):\n    if self._timestamp is None:\n      return None\n    number_of_days, hours, minutes, seconds = self._GetTimeValues(\n        int(self._timestamp))\n    year, month, day_of_month = self._GetDateValuesWithEpoch(\n        number_of_days, self._EPOCH)\n    microseconds = int(\n        (self._timestamp % 1) * definitions.MICROSECONDS_PER_SECOND)\n    return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:06d}'.format(\n        year, month, day_of_month, hours, minutes, seconds, microseconds)",
    "docstring": "Copies the Cocoa timestamp to a date and time string.\n\n    Returns:\n      str: date and time value formatted as: YYYY-MM-DD hh:mm:ss.###### or\n          None if the timestamp cannot be copied to a date and time string."
  },
  {
    "code": "def http_methods(self, urls=None, **route_data):\n        def decorator(class_definition):\n            instance = class_definition\n            if isinstance(class_definition, type):\n                instance = class_definition()\n            router = self.urls(urls if urls else \"/{0}\".format(instance.__class__.__name__.lower()), **route_data)\n            for method in HTTP_METHODS:\n                handler = getattr(instance, method.lower(), None)\n                if handler:\n                    http_routes = getattr(handler, '_hug_http_routes', ())\n                    if http_routes:\n                        for route in http_routes:\n                            http(**router.accept(method).where(**route).route)(handler)\n                    else:\n                        http(**router.accept(method).route)(handler)\n                    cli_routes = getattr(handler, '_hug_cli_routes', ())\n                    if cli_routes:\n                        for route in cli_routes:\n                            cli(**self.where(**route).route)(handler)\n            return class_definition\n        return decorator",
    "docstring": "Creates routes from a class, where the class method names should line up to HTTP METHOD types"
  },
  {
    "code": "def participating_ecs(self):\n        with self._mutex:\n            if not self._participating_ecs:\n                self._participating_ecs = [ExecutionContext(ec,\n                                    self._obj.get_context_handle(ec)) \\\n                             for ec in self._obj.get_participating_contexts()]\n        return self._participating_ecs",
    "docstring": "A list of the execution contexts this component is participating in."
  },
  {
    "code": "def iterrowproxy(self, cls=RowProxy):\n        row_proxy = None\n        headers = None\n        for row in self:\n            if not headers:\n                headers = row\n                row_proxy = cls(headers)\n                continue\n            yield row_proxy.set_row(row)",
    "docstring": "Iterate over the resource as row proxy objects, which allow acessing colums as attributes. Like iterrows,\n        but allows for setting a specific RowProxy class."
  },
  {
    "code": "def close(self):\n        if self.tabix_file and not self.tabix_file.closed:\n            self.tabix_file.close()\n        if self.stream:\n            self.stream.close()",
    "docstring": "Close underlying stream"
  },
  {
    "code": "def piped_bamprep(data, region=None, out_file=None):\n    data[\"region\"] = region\n    if not _need_prep(data):\n        return [data]\n    else:\n        utils.safe_makedir(os.path.dirname(out_file))\n        if region[0] == \"nochrom\":\n            prep_bam = shared.write_nochr_reads(data[\"work_bam\"], out_file, data[\"config\"])\n        elif region[0] == \"noanalysis\":\n            prep_bam = shared.write_noanalysis_reads(data[\"work_bam\"], region[1], out_file,\n                                                     data[\"config\"])\n        else:\n            if not utils.file_exists(out_file):\n                with tx_tmpdir(data) as tmp_dir:\n                    _piped_bamprep_region(data, region, out_file, tmp_dir)\n            prep_bam = out_file\n        bam.index(prep_bam, data[\"config\"])\n        data[\"work_bam\"] = prep_bam\n        return [data]",
    "docstring": "Perform full BAM preparation using pipes to avoid intermediate disk IO.\n\n    Handles realignment of original BAMs."
  },
  {
    "code": "def add_gate_option_group(parser):\n    gate_group = parser.add_argument_group(\"Options for gating data.\")\n    gate_group.add_argument(\"--gate\", nargs=\"+\", type=str,\n                            metavar=\"IFO:CENTRALTIME:HALFDUR:TAPERDUR\",\n                            help=\"Apply one or more gates to the data before \"\n                                 \"filtering.\")\n    gate_group.add_argument(\"--gate-overwhitened\", action=\"store_true\",\n                            help=\"Overwhiten data first, then apply the \"\n                                 \"gates specified in --gate. Overwhitening \"\n                                 \"allows for sharper tapers to be used, \"\n                                 \"since lines are not blurred.\")\n    gate_group.add_argument(\"--psd-gate\", nargs=\"+\", type=str,\n                            metavar=\"IFO:CENTRALTIME:HALFDUR:TAPERDUR\",\n                            help=\"Apply one or more gates to the data used \"\n                                 \"for computing the PSD. Gates are applied \"\n                                 \"prior to FFT-ing the data for PSD \"\n                                 \"estimation.\")\n    return gate_group",
    "docstring": "Adds the options needed to apply gates to data.\n\n    Parameters\n    ----------\n    parser : object\n        ArgumentParser instance."
  },
  {
    "code": "def write_ast(patched_ast_node):\n    result = []\n    for child in patched_ast_node.sorted_children:\n        if isinstance(child, ast.AST):\n            result.append(write_ast(child))\n        else:\n            result.append(child)\n    return ''.join(result)",
    "docstring": "Extract source form a patched AST node with `sorted_children` field\n\n    If the node is patched with sorted_children turned off you can use\n    `node_region` function for obtaining code using module source code."
  },
  {
    "code": "def create_business_rules(self, hosts, services, hostgroups, servicegroups,\n                              macromodulations, timeperiods):\n        for item in self:\n            item.create_business_rules(hosts, services, hostgroups,\n                                       servicegroups, macromodulations, timeperiods)",
    "docstring": "Loop on hosts or services and call SchedulingItem.create_business_rules\n\n        :param hosts: hosts to link to\n        :type hosts: alignak.objects.host.Hosts\n        :param services: services to link to\n        :type services: alignak.objects.service.Services\n        :param hostgroups: hostgroups to link to\n        :type hostgroups: alignak.objects.hostgroup.Hostgroups\n        :param servicegroups: servicegroups to link to\n        :type servicegroups: alignak.objects.servicegroup.Servicegroups\n        :param macromodulations: macromodulations to link to\n        :type macromodulations: alignak.objects.macromodulation.Macromodulations\n        :param timeperiods: timeperiods to link to\n        :type timeperiods: alignak.objects.timeperiod.Timeperiods\n        :return: None"
  },
  {
    "code": "def start_discovery(self, service_uuids=[]):\n        discovery_filter = {'Transport': 'le'}\n        if service_uuids:\n            discovery_filter['UUIDs'] = service_uuids\n        try:\n            self._adapter.SetDiscoveryFilter(discovery_filter)\n            self._adapter.StartDiscovery()\n        except dbus.exceptions.DBusException as e:\n            if e.get_dbus_name() == 'org.bluez.Error.NotReady':\n                raise errors.NotReady(\n                    \"Bluetooth adapter not ready. \"\n                    \"Set `is_adapter_powered` to `True` or run 'echo \\\"power on\\\" | sudo bluetoothctl'.\")\n            if e.get_dbus_name() == 'org.bluez.Error.InProgress':\n                pass\n            else:\n                raise _error_from_dbus_error(e)",
    "docstring": "Starts a discovery for BLE devices with given service UUIDs.\n\n        :param service_uuids: Filters the search to only return devices with given UUIDs."
  },
  {
    "code": "def build_pattern(body, features):\n    line_patterns = apply_features(body, features)\n    return reduce(lambda x, y: [i + j for i, j in zip(x, y)], line_patterns)",
    "docstring": "Converts body into a pattern i.e. a point in the features space.\n\n    Applies features to the body lines and sums up the results.\n    Elements of the pattern indicate how many times a certain feature occurred\n    in the last lines of the body."
  },
  {
    "code": "def print_logins(logins):\n    table = formatting.Table(['Date', 'IP Address', 'Successufl Login?'])\n    for login in logins:\n        table.add_row([login.get('createDate'), login.get('ipAddress'), login.get('successFlag')])\n    return table",
    "docstring": "Prints out the login history for a user"
  },
  {
    "code": "def is_constrained_reaction(model, rxn):\n    lower_bound, upper_bound = helpers.find_bounds(model)\n    if rxn.reversibility:\n        return rxn.lower_bound > lower_bound or rxn.upper_bound < upper_bound\n    else:\n        return rxn.lower_bound > 0 or rxn.upper_bound < upper_bound",
    "docstring": "Return whether a reaction has fixed constraints."
  },
  {
    "code": "def json_http_resp(handler):\n    @wraps(handler)\n    def wrapper(event, context):\n        response = handler(event, context)\n        try:\n            body = json.dumps(response)\n        except Exception as exception:\n            return {'statusCode': 500, 'body': str(exception)}\n        return {'statusCode': 200, 'body': body}\n    return wrapper",
    "docstring": "Automatically serialize return value to the body of a successfull HTTP\nresponse.\n\nReturns a 500 error if the response cannot be serialized\n\nUsage::\n\n    >>> from lambda_decorators import json_http_resp\n    >>> @json_http_resp\n    ... def handler(event, context):\n    ...     return {'hello': 'world'}\n    >>> handler({}, object())\n    {'statusCode': 200, 'body': '{\"hello\": \"world\"}'}\n\nin this example, the decorated handler returns:\n\n.. code:: python\n\n    {'statusCode': 200, 'body': '{\"hello\": \"world\"}'}"
  },
  {
    "code": "def binds(val, **kwargs):\n    if not isinstance(val, dict):\n        if not isinstance(val, list):\n            try:\n                val = helpers.split(val)\n            except AttributeError:\n                raise SaltInvocationError(\n                    '\\'{0}\\' is not a dictionary or list of bind '\n                    'definitions'.format(val)\n                )\n    return val",
    "docstring": "On the CLI, these are passed as multiple instances of a given CLI option.\n    In Salt, we accept these as a comma-delimited list but the API expects a\n    Python list."
  },
  {
    "code": "def stem(self, word):\n        if self.stemmer:\n            return unicode_to_ascii(self._stemmer.stem(word))\n        else:\n            return word",
    "docstring": "Perform stemming on an input word."
  },
  {
    "code": "def _qvm_run(self, quil_program, classical_addresses, trials,\n                 measurement_noise, gate_noise, random_seed) -> np.ndarray:\n        payload = qvm_run_payload(quil_program, classical_addresses, trials,\n                                  measurement_noise, gate_noise, random_seed)\n        response = post_json(self.session, self.sync_endpoint + \"/qvm\", payload)\n        ram = response.json()\n        for k in ram.keys():\n            ram[k] = np.array(ram[k])\n        return ram",
    "docstring": "Run a Forest ``run`` job on a QVM.\n\n        Users should use :py:func:`QVM.run` instead of calling this directly."
  },
  {
    "code": "def delete(gandi, address, force):\n    source, domain = address\n    if not force:\n        proceed = click.confirm('Are you sure to delete the domain '\n                                'mail forward %s@%s ?' % (source, domain))\n        if not proceed:\n            return\n    result = gandi.forward.delete(domain, source)\n    return result",
    "docstring": "Delete a domain mail forward."
  },
  {
    "code": "def embedding(x,\n              vocab_size,\n              dense_size,\n              name=None,\n              reuse=None,\n              multiplier=1.0,\n              symbol_dropout_rate=0.0,\n              embedding_var=None,\n              dtype=tf.float32):\n  with tf.variable_scope(\n      name, default_name=\"embedding\", values=[x], reuse=reuse, dtype=dtype):\n    if embedding_var is None:\n      embedding_var = tf.get_variable(\"kernel\", [vocab_size, dense_size])\n    if not tf.executing_eagerly():\n      embedding_var = convert_gradient_to_tensor(embedding_var)\n    x = dropout_no_scaling(x, 1.0 - symbol_dropout_rate)\n    emb_x = gather(embedding_var, x, dtype)\n    if multiplier != 1.0:\n      emb_x *= multiplier\n    static_shape = emb_x.shape.as_list()\n    if len(static_shape) < 5:\n      return emb_x\n    assert len(static_shape) == 5\n    return tf.squeeze(emb_x, 3)",
    "docstring": "Embed x of type int64 into dense vectors, reducing to max 4 dimensions."
  },
  {
    "code": "def resolve(self, link_resource_type, resource_id, array=None):\n        result = None\n        if array is not None:\n            container = array.items_mapped.get(link_resource_type)\n            result = container.get(resource_id)\n        if result is None:\n            clz = utils.class_for_type(link_resource_type)\n            result = self.fetch(clz).where({'sys.id': resource_id}).first()\n        return result",
    "docstring": "Resolve a link to a CDA resource.\n\n        Provided an `array` argument, attempt to retrieve the resource from the `mapped_items`\n        section of that array (containing both included and regular resources), in case the\n        resource cannot be found in the array (or if no `array` was provided) - attempt to fetch\n        the resource from the API by issuing a network request.\n\n        :param link_resource_type: (str) Resource type as str.\n        :param resource_id: (str) Remote ID of the linked resource.\n        :param array: (:class:`.Array`) Optional array resource.\n        :return: :class:`.Resource` subclass, `None` if it cannot be retrieved."
  },
  {
    "code": "def check_for_completion(self):\n        job_result_obj = self.session.get(self.uri)\n        job_status = job_result_obj['status']\n        if job_status == 'complete':\n            self.session.delete(self.uri)\n            op_status_code = job_result_obj['job-status-code']\n            if op_status_code in (200, 201):\n                op_result_obj = job_result_obj.get('job-results', None)\n            elif op_status_code == 204:\n                op_result_obj = None\n            else:\n                error_result_obj = job_result_obj.get('job-results', None)\n                if not error_result_obj:\n                    message = None\n                elif 'message' in error_result_obj:\n                    message = error_result_obj['message']\n                elif 'error' in error_result_obj:\n                    message = error_result_obj['error']\n                else:\n                    message = None\n                error_obj = {\n                    'http-status': op_status_code,\n                    'reason': job_result_obj['job-reason-code'],\n                    'message': message,\n                    'request-method': self.op_method,\n                    'request-uri': self.op_uri,\n                }\n                raise HTTPError(error_obj)\n        else:\n            op_result_obj = None\n        return job_status, op_result_obj",
    "docstring": "Check once for completion of the job and return completion status and\n        result if it has completed.\n\n        If the job completed in error, an :exc:`~zhmcclient.HTTPError`\n        exception is raised.\n\n        Returns:\n\n          : A tuple (status, result) with:\n\n          * status (:term:`string`): Completion status of the job, as\n            returned in the ``status`` field of the response body of the\n            \"Query Job Status\" HMC operation, as follows:\n\n            * ``\"complete\"``: Job completed (successfully).\n            * any other value: Job is not yet complete.\n\n          * result (:term:`json object` or `None`): `None` for incomplete\n            jobs. For completed jobs, the result of the original asynchronous\n            operation that was performed by the job, from the ``job-results``\n            field of the response body of the \"Query Job Status\" HMC\n            operation. That result is a :term:`json object` as described\n            for the asynchronous operation, or `None` if the operation has no\n            result.\n\n        Raises:\n\n          :exc:`~zhmcclient.HTTPError`: The job completed in error, or the job\n            status cannot be retrieved, or the job cannot be deleted.\n          :exc:`~zhmcclient.ParseError`\n          :exc:`~zhmcclient.ClientAuthError`\n          :exc:`~zhmcclient.ServerAuthError`\n          :exc:`~zhmcclient.ConnectionError`"
  },
  {
    "code": "def _ssh_client(self):\n        ssh = paramiko.SSHClient()\n        ssh.load_system_host_keys()\n        ssh.set_missing_host_key_policy(paramiko.RejectPolicy())\n        return ssh",
    "docstring": "Gets an SSH client to connect with."
  },
  {
    "code": "def get_app(opts):\n    apiopts = opts.get(__name__.rsplit('.', 2)[-2], {})\n    cherrypy.config['saltopts'] = opts\n    cherrypy.config['apiopts'] = apiopts\n    root = API()\n    cpyopts = root.get_conf()\n    return root, apiopts, cpyopts",
    "docstring": "Returns a WSGI app and a configuration dictionary"
  },
  {
    "code": "def list_extensions(request):\n    blacklist = set(getattr(settings,\n                            'OPENSTACK_NOVA_EXTENSIONS_BLACKLIST', []))\n    nova_api = _nova.novaclient(request)\n    return tuple(\n        extension for extension in\n        nova_list_extensions.ListExtManager(nova_api).show_all()\n        if extension.name not in blacklist\n    )",
    "docstring": "List all nova extensions, except the ones in the blacklist."
  },
  {
    "code": "def response(code, **kwargs):\n        _ret_json = jsonify(kwargs)\n        resp = make_response(_ret_json, code)\n        resp.headers[\"Content-Type\"] = \"application/json; charset=utf-8\"\n        return resp",
    "docstring": "Generic HTTP JSON response method\n\n        :param code: HTTP code (int)\n        :param kwargs: Data structure for response (dict)\n        :return: HTTP Json response"
  },
  {
    "code": "def trace2array(self, sl):\n        chain = []\n        for stochastic in self.stochastics:\n            tr = stochastic.trace.gettrace(slicing=sl)\n            if tr is None:\n                raise AttributeError\n            chain.append(tr)\n        return np.hstack(chain)",
    "docstring": "Return an array with the trace of all stochastics, sliced by sl."
  },
  {
    "code": "def _update_element(name, element_type, data, server=None):\n    name = quote(name, safe='')\n    if 'properties' in data:\n        properties = []\n        for key, value in data['properties'].items():\n            properties.append({'name': key, 'value': value})\n        _api_post('{0}/{1}/property'.format(element_type, name), properties, server)\n        del data['properties']\n        if not data:\n            return unquote(name)\n    update_data = _get_element(name, element_type, server, with_properties=False)\n    if update_data:\n        update_data.update(data)\n    else:\n        __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL\n        raise CommandExecutionError('Cannot update {0}'.format(name))\n    _api_post('{0}/{1}'.format(element_type, name), _clean_data(update_data), server)\n    return unquote(name)",
    "docstring": "Update an element, including it's properties"
  },
  {
    "code": "def vertical_percent(plot, percent=0.1):\n    plot_bottom, plot_top = plot.get_ylim()\n    return percent * (plot_top - plot_bottom)",
    "docstring": "Using the size of the y axis, return a fraction of that size."
  },
  {
    "code": "def source_components(self):\n        raw_sccs = self._component_graph()\n        vertex_to_root = self.vertex_dict()\n        non_sources = self.vertex_set()\n        for scc in raw_sccs:\n            root = scc[0][1]\n            for item_type, w in scc:\n                if item_type == 'VERTEX':\n                    vertex_to_root[w] = root\n                elif item_type == 'EDGE':\n                    non_sources.add(vertex_to_root[w])\n        sccs = []\n        for raw_scc in raw_sccs:\n            root = raw_scc[0][1]\n            if root not in non_sources:\n                sccs.append([v for vtype, v in raw_scc if vtype == 'VERTEX'])\n        return [self.full_subgraph(scc) for scc in sccs]",
    "docstring": "Return the strongly connected components not reachable from any other\n        component.  Any component in the graph is reachable from one of these."
  },
  {
    "code": "def noise_get_turbulence(\n    n: tcod.noise.Noise,\n    f: Sequence[float],\n    oc: float,\n    typ: int = NOISE_DEFAULT,\n) -> float:\n    return float(\n        lib.TCOD_noise_get_turbulence_ex(\n            n.noise_c, ffi.new(\"float[4]\", f), oc, typ\n        )\n    )",
    "docstring": "Return the turbulence noise sampled from the ``f`` coordinate.\n\n    Args:\n        n (Noise): A Noise instance.\n        f (Sequence[float]): The point to sample the noise from.\n        typ (int): The noise algorithm to use.\n        octaves (float): The level of level.  Should be more than 1.\n\n    Returns:\n        float: The sampled noise value."
  },
  {
    "code": "def create_aql_text(*args):\n        aql_query_text = \"\"\n        for arg in args:\n            if isinstance(arg, dict):\n                arg = \"({})\".format(json.dumps(arg))\n            elif isinstance(arg, list):\n                arg = \"({})\".format(json.dumps(arg)).replace(\"[\", \"\").replace(\"]\", \"\")\n            aql_query_text += arg\n        return aql_query_text",
    "docstring": "Create AQL querty from string or list or dict arguments"
  },
  {
    "code": "def _get_qvm_with_topology(name: str, topology: nx.Graph,\n                           noisy: bool = False,\n                           requires_executable: bool = True,\n                           connection: ForestConnection = None,\n                           qvm_type: str = 'qvm') -> QuantumComputer:\n    device = NxDevice(topology=topology)\n    if noisy:\n        noise_model = decoherence_noise_with_asymmetric_ro(gates=gates_in_isa(device.get_isa()))\n    else:\n        noise_model = None\n    return _get_qvm_qc(name=name, qvm_type=qvm_type, connection=connection, device=device,\n                       noise_model=noise_model, requires_executable=requires_executable)",
    "docstring": "Construct a QVM with the provided topology.\n\n    :param name: A name for your quantum computer. This field does not affect behavior of the\n        constructed QuantumComputer.\n    :param topology: A graph representing the desired qubit connectivity.\n    :param noisy: Whether to include a generic noise model. If you want more control over\n        the noise model, please construct your own :py:class:`NoiseModel` and use\n        :py:func:`_get_qvm_qc` instead of this function.\n    :param requires_executable: Whether this QVM will refuse to run a :py:class:`Program` and\n        only accept the result of :py:func:`compiler.native_quil_to_executable`. Setting this\n        to True better emulates the behavior of a QPU.\n    :param connection: An optional :py:class:`ForestConnection` object. If not specified,\n        the default values for URL endpoints will be used.\n    :param qvm_type: The type of QVM. Either 'qvm' or 'pyqvm'.\n    :return: A pre-configured QuantumComputer"
  },
  {
    "code": "def sort_url(self):\n        prefix = (self.sort_direction == \"asc\") and \"-\" or \"\"\n        return self.table.get_url(order_by=prefix + self.name)",
    "docstring": "Return the URL to sort the linked table by this column. If the\n        table is already sorted by this column, the order is reversed.\n\n        Since there is no canonical URL for a table the current URL (via\n        the HttpRequest linked to the Table instance) is reused, and any\n        unrelated parameters will be included in the output."
  },
  {
    "code": "def get_var_count(self):\n        n = c_int()\n        self.library.get_var_count.argtypes = [POINTER(c_int)]\n        self.library.get_var_count(byref(n))\n        return n.value",
    "docstring": "Return number of variables"
  },
  {
    "code": "def system_exit_exception_handler(*args):\n    reporter = Reporter()\n    reporter.Footer_label.setText(\n        \"The severity of this exception is critical, <b>{0}</b> cannot continue and will now close!\".format(\n            Constants.application_name))\n    base_exception_handler(*args)\n    foundations.core.exit(1)\n    return True",
    "docstring": "Provides a system exit exception handler.\n\n    :param \\*args: Arguments.\n    :type \\*args: \\*\n    :return: Definition success.\n    :rtype: bool"
  },
  {
    "code": "def append(a, vancestors):\n    add = True\n    for j, va in enumerate(vancestors):\n        if issubclass(va, a):\n            add = False\n            break\n        if issubclass(a, va):\n            vancestors[j] = a\n            add = False\n    if add:\n        vancestors.append(a)",
    "docstring": "Append ``a`` to the list of the virtual ancestors, unless it is already\n    included."
  },
  {
    "code": "def features(self):\n        return {\n            aioxmpp.im.conversation.ConversationFeature.BAN,\n            aioxmpp.im.conversation.ConversationFeature.BAN_WITH_KICK,\n            aioxmpp.im.conversation.ConversationFeature.KICK,\n            aioxmpp.im.conversation.ConversationFeature.SEND_MESSAGE,\n            aioxmpp.im.conversation.ConversationFeature.SEND_MESSAGE_TRACKED,\n            aioxmpp.im.conversation.ConversationFeature.SET_TOPIC,\n            aioxmpp.im.conversation.ConversationFeature.SET_NICK,\n            aioxmpp.im.conversation.ConversationFeature.INVITE,\n            aioxmpp.im.conversation.ConversationFeature.INVITE_DIRECT,\n        }",
    "docstring": "The set of features supported by this MUC. This may vary depending on\n        features exported by the MUC service, so be sure to check this for each\n        individual MUC."
  },
  {
    "code": "def match_date(date, date_pattern):\n    year, month, day, day_of_week = date\n    year_p, month_p, day_p, day_of_week_p = date_pattern\n    if year_p == 255:\n        pass\n    elif year != year_p:\n        return False\n    if month_p == 255:\n        pass\n    elif month_p == 13:\n        if (month % 2) == 0:\n            return False\n    elif month_p == 14:\n        if (month % 2) == 1:\n            return False\n    elif month != month_p:\n        return False\n    if day_p == 255:\n        pass\n    elif day_p == 32:\n        last_day = calendar.monthrange(year + 1900, month)[1]\n        if day != last_day:\n            return False\n    elif day_p == 33:\n        if (day % 2) == 0:\n            return False\n    elif day_p == 34:\n        if (day % 2) == 1:\n            return False\n    elif day != day_p:\n        return False\n    if day_of_week_p == 255:\n        pass\n    elif day_of_week != day_of_week_p:\n        return False\n    return True",
    "docstring": "Match a specific date, a four-tuple with no special values, with a date\n    pattern, four-tuple possibly having special values."
  },
  {
    "code": "def _get_entities(self, text, language=''):\n    body = {\n        'document': {\n            'type': 'PLAIN_TEXT',\n            'content': text,\n        },\n        'encodingType': 'UTF32',\n    }\n    if language:\n      body['document']['language'] = language\n    request = self.service.documents().analyzeEntities(body=body)\n    response = request.execute()\n    result = []\n    for entity in response.get('entities', []):\n      mentions = entity.get('mentions', [])\n      if not mentions:\n        continue\n      entity_text = mentions[0]['text']\n      offset = entity_text['beginOffset']\n      for word in entity_text['content'].split():\n        result.append({'content': word, 'beginOffset': offset})\n        offset += len(word)\n    return result",
    "docstring": "Returns the list of entities retrieved from the given text.\n\n    Args:\n      text (str): Input text.\n      language (:obj:`str`, optional): Language code.\n\n    Returns:\n      List of entities."
  },
  {
    "code": "def process_results(self):\n        for result in self._results:\n            provider = result.provider\n            self.providers.append(provider)\n            if result.error:\n                self.failed_providers.append(provider)\n                continue\n            if not result.response:\n                continue\n            self.blacklisted = True\n            provider_categories = provider.process_response(result.response)\n            assert provider_categories.issubset(DNSBL_CATEGORIES)\n            self.categories = self.categories.union(provider_categories)\n            self.detected_by[provider.host] = list(provider_categories)",
    "docstring": "Process results by providers"
  },
  {
    "code": "def should_log(self, logger_name: str, level: str) -> bool:\n        if (logger_name, level) not in self._should_log:\n            log_level_per_rule = self._get_log_level(logger_name)\n            log_level_per_rule_numeric = getattr(logging, log_level_per_rule.upper(), 10)\n            log_level_event_numeric = getattr(logging, level.upper(), 10)\n            should_log = log_level_event_numeric >= log_level_per_rule_numeric\n            self._should_log[(logger_name, level)] = should_log\n        return self._should_log[(logger_name, level)]",
    "docstring": "Returns if a message for the logger should be logged."
  },
  {
    "code": "def integer(token):\n        token = token.strip()\n        neg = False\n        if token.startswith(compat.b('-')):\n            token = token[1:]\n            neg = True\n        if token.startswith(compat.b('0x')):\n            result = int(token, 16)\n        elif token.startswith(compat.b('0b')):\n            result = int(token[2:], 2)\n        elif token.startswith(compat.b('0o')):\n            result = int(token, 8)\n        else:\n            try:\n                result = int(token)\n            except ValueError:\n                result = int(token, 16)\n        if neg:\n            result = -result\n        return result",
    "docstring": "Convert numeric strings into integers.\n\n        @type  token: str\n        @param token: String to parse.\n\n        @rtype:  int\n        @return: Parsed integer value."
  },
  {
    "code": "def _parse(cls, scope):\n    if not scope:\n      return ('default',)\n    if isinstance(scope, string_types):\n      scope = scope.split(' ')\n    scope = {str(s).lower() for s in scope if s}\n    return scope or ('default',)",
    "docstring": "Parses the input scope into a normalized set of strings.\n\n    :param scope: A string or tuple containing zero or more scope names.\n    :return: A set of scope name strings, or a tuple with the default scope name.\n    :rtype: set"
  },
  {
    "code": "def local_dt(dt):\n    if not dt.tzinfo:\n        dt = pytz.utc.localize(dt)\n    return LOCALTZ.normalize(dt.astimezone(LOCALTZ))",
    "docstring": "Return an aware datetime in system timezone, from a naive or aware\n    datetime.\n\n    Naive datetime are assumed to be in UTC TZ."
  },
  {
    "code": "def remove_node(self, node):\n        if node in self._nodes:\n            yield from node.delete()\n            self._nodes.remove(node)",
    "docstring": "Removes a node from the project.\n        In theory this should be called by the node manager.\n\n        :param node: Node instance"
  },
  {
    "code": "def to_json(self):\n        result = super(Webhook, self).to_json()\n        result.update({\n            'name': self.name,\n            'url': self.url,\n            'topics': self.topics,\n            'httpBasicUsername': self.http_basic_username,\n            'headers': self.headers\n        })\n        if self.filters:\n            result.update({'filters': self.filters})\n        if self.transformation:\n            result.update({'transformation': self.transformation})\n        return result",
    "docstring": "Returns the JSON representation of the webhook."
  },
  {
    "code": "def select(message=\"\", title=\"Lackey Input\", options=None, default=None):\n    if options is None or len(options) == 0:\n        return \"\"\n    if default is None:\n        default = options[0]\n    if default not in options:\n        raise ValueError(\"<<default>> not in options[]\")\n    root = tk.Tk()\n    input_text = tk.StringVar()\n    input_text.set(message)\n    PopupList(root, message, title, options, default, input_text)\n    root.focus_force()\n    root.mainloop()\n    return str(input_text.get())",
    "docstring": "Creates a dropdown selection dialog with the specified message and options\n\n     `default` must be one of the options.\n\n     Returns the selected value."
  },
  {
    "code": "def namedb_preorder_insert( cur, preorder_rec ):\n    preorder_row = copy.deepcopy( preorder_rec )\n    assert 'preorder_hash' in preorder_row, \"BUG: missing preorder_hash\"\n    try:\n        preorder_query, preorder_values = namedb_insert_prepare( cur, preorder_row, \"preorders\" )\n    except Exception, e:\n        log.exception(e)\n        log.error(\"FATAL: Failed to insert name preorder '%s'\" % preorder_row['preorder_hash']) \n        os.abort()\n    namedb_query_execute( cur, preorder_query, preorder_values )\n    return True",
    "docstring": "Add a name or namespace preorder record, if it doesn't exist already.\n\n    DO NOT CALL THIS DIRECTLY."
  },
  {
    "code": "def append(entry):\n    if not entry:\n        return\n    try:\n        with open(get_rc_path(), 'a') as f:\n            if isinstance(entry, list):\n                f.writelines(entry)\n            else:\n                f.write(entry + '\\n')\n    except IOError:\n        print('Error writing your ~/.vacationrc file!')",
    "docstring": "Append either a list of strings or a string to our file."
  },
  {
    "code": "def data_find_text(data, path):\n    el = data_find(data, path)\n    if not isinstance(el, (list, tuple)):\n        return None\n    texts = [child for child in el[1:] if not isinstance(child, (tuple, list, dict))]\n    if not texts:\n        return None\n    return \" \".join(\n        [\n            six.ensure_text(x, encoding=\"utf-8\", errors=\"strict\")\n            for x in texts\n        ]\n    )",
    "docstring": "Return the text value of the element-as-tuple in tuple ``data`` using\n    simplified XPath ``path``."
  },
  {
    "code": "def dbmax05years(self, value=None):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type float '\n                                 'for field `dbmax05years`'.format(value))\n        self._dbmax05years = value",
    "docstring": "Corresponds to IDD Field `dbmax05years`\n        5-year return period values for maximum extreme dry-bulb temperature\n\n        Args:\n            value (float): value for IDD Field `dbmax05years`\n                Unit: C\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def _req(self, req):\n        logger.debug('DUT> %s', req)\n        self._log and self.pause()\n        times = 3\n        res = None\n        while times:\n            times = times - 1\n            try:\n                self._sendline(req)\n                self._expect(req)\n                line = None\n                res = []\n                while True:\n                    line = self._readline()\n                    logger.debug('Got line %s', line)\n                    if line == 'Done':\n                        break\n                    if line:\n                        res.append(line)\n                break\n            except:\n                logger.exception('Failed to send command')\n                self.close()\n                self._init()\n        self._log and self.resume()\n        return res",
    "docstring": "Send command and wait for response.\n\n        The command will be repeated 3 times at most in case data loss of serial port.\n\n        Args:\n            req (str): Command to send, please do not include new line in the end.\n\n        Returns:\n            [str]: The output lines"
  },
  {
    "code": "def list_json_files(directory, recursive=False):\n    json_files = []\n    for top, dirs, files in os.walk(directory):\n        dirs.sort()\n        paths = (os.path.join(top, f) for f in sorted(files))\n        json_files.extend(x for x in paths if is_json(x))\n        if not recursive:\n            break\n    return json_files",
    "docstring": "Return a list of file paths for JSON files within `directory`.\n\n    Args:\n        directory: A path to a directory.\n        recursive: If ``True``, this function will descend into all\n            subdirectories.\n\n    Returns:\n        A list of JSON file paths directly under `directory`."
  },
  {
    "code": "def get_intended_direction(self):\n        x = 0\n        y = 0\n        if self.target_x == self.current_x and self.target_y == self.current_y:\n            return y,x\n        if self.target_y > self.current_y:\n            y = 1\n        elif self.target_y < self.current_y:\n            y = -1\n        if self.target_x > self.current_x:\n            x = 1\n        elif self.target_x < self.current_x:\n            x = -1\n        return y,x",
    "docstring": "returns a Y,X value showing which direction the\n        agent should move in order to get to the target"
  },
  {
    "code": "def __build_sms_data(self, message):\n        attributes = {}\n        attributes_to_translate = {\n            'to' : 'To',\n            'message' : 'Content',\n            'client_id' : 'ClientID',\n            'concat' : 'Concat',\n            'from_name': 'From',\n            'invalid_char_option' : 'InvalidCharOption',\n            'truncate' : 'Truncate',\n            'wrapper_id' : 'WrapperId'\n        }\n        for attr in attributes_to_translate:\n            val_to_use = None\n            if hasattr(message, attr):\n                val_to_use = getattr(message, attr)\n            if val_to_use is None and hasattr(self, attr):\n                val_to_use = getattr(self, attr)\n            if val_to_use is not None:\n                attributes[attributes_to_translate[attr]] = str(val_to_use)\n        return attributes",
    "docstring": "Build a dictionary of SMS message elements"
  },
  {
    "code": "def get_parent(port_id):\n    session = db.get_reader_session()\n    res = dict()\n    with session.begin():\n        subport_model = trunk_models.SubPort\n        trunk_model = trunk_models.Trunk\n        subport = (session.query(subport_model).\n                   filter(subport_model.port_id == port_id).first())\n        if subport:\n            trunk = (session.query(trunk_model).\n                     filter(trunk_model.id == subport.trunk_id).first())\n            if trunk:\n                trunk_port_id = trunk.port.id\n                res = get_ports(port_id=trunk_port_id, active=False)[0]\n    return res",
    "docstring": "Get trunk subport's parent port"
  },
  {
    "code": "def dumps(mesh):\n    from lxml import etree\n    dae = mesh_to_collada(mesh)\n    dae.save()\n    return etree.tostring(dae.xmlnode, encoding='UTF-8')",
    "docstring": "Generates a UTF-8 XML string containing the mesh, in collada format."
  },
  {
    "code": "def focus_prev_matching(self, querystring):\n        self.focus_property(lambda x: x._message.matches(querystring),\n                            self._tree.prev_position)",
    "docstring": "focus previous matching message in depth first order"
  },
  {
    "code": "def get_item_properties(item, fields, mixed_case_fields=(), formatters=None):\n    if formatters is None:\n        formatters = {}\n    row = []\n    for field in fields:\n        if field in formatters:\n            row.append(formatters[field](item))\n        else:\n            if field in mixed_case_fields:\n                field_name = field.replace(' ', '_')\n            else:\n                field_name = field.lower().replace(' ', '_')\n            if not hasattr(item, field_name) and isinstance(item, dict):\n                data = item[field_name]\n            else:\n                data = getattr(item, field_name, '')\n            if data is None:\n                data = ''\n            row.append(data)\n    return tuple(row)",
    "docstring": "Return a tuple containing the item properties.\n\n    :param item: a single item resource (e.g. Server, Tenant, etc)\n    :param fields: tuple of strings with the desired field names\n    :param mixed_case_fields: tuple of field names to preserve case\n    :param formatters: dictionary mapping field names to callables\n       to format the values"
  },
  {
    "code": "def create_statement(self, connection_id):\n        request = requests_pb2.CreateStatementRequest()\n        request.connection_id = connection_id\n        response_data = self._apply(request)\n        response = responses_pb2.CreateStatementResponse()\n        response.ParseFromString(response_data)\n        return response.statement_id",
    "docstring": "Creates a new statement.\n\n        :param connection_id:\n            ID of the current connection.\n\n        :returns:\n            New statement ID."
  },
  {
    "code": "def GetAnalyzerInstance(cls, analyzer_name):\n    analyzer_name = analyzer_name.lower()\n    if analyzer_name not in cls._analyzer_classes:\n      raise KeyError(\n          'analyzer class not set for name: {0:s}.'.format(analyzer_name))\n    analyzer_class = cls._analyzer_classes[analyzer_name]\n    return analyzer_class()",
    "docstring": "Retrieves an instance of a specific analyzer.\n\n    Args:\n      analyzer_name (str): name of the analyzer to retrieve.\n\n    Returns:\n      BaseAnalyzer: analyzer instance.\n\n    Raises:\n      KeyError: if analyzer class is not set for the corresponding name."
  },
  {
    "code": "def read(self, path, ext=None, start=None, stop=None, recursive=False, npartitions=None):\n        path = uri_to_path(path)\n        files = self.list(path, ext=ext, start=start, stop=stop, recursive=recursive)\n        nfiles = len(files)\n        self.nfiles = nfiles\n        if spark and isinstance(self.engine, spark):\n            npartitions = min(npartitions, nfiles) if npartitions else nfiles\n            rdd = self.engine.parallelize(enumerate(files), npartitions)\n            return rdd.map(lambda kv: (kv[0], readlocal(kv[1]), kv[1]))\n        else:\n            return [(k, readlocal(v), v) for k, v in enumerate(files)]",
    "docstring": "Sets up Spark RDD across files specified by dataPath on local filesystem.\n\n        Returns RDD of <integer file index, string buffer> k/v pairs."
  },
  {
    "code": "def queue_purge(self, queue='', nowait=False):\n        args = AMQPWriter()\n        args.write_short(0)\n        args.write_shortstr(queue)\n        args.write_bit(nowait)\n        self._send_method((50, 30), args)\n        if not nowait:\n            return self.wait(allowed_methods=[\n                (50, 31),\n            ])",
    "docstring": "Purge a queue\n\n        This method removes all messages from a queue.  It does not\n        cancel consumers.  Purged messages are deleted without any\n        formal \"undo\" mechanism.\n\n        RULE:\n\n            A call to purge MUST result in an empty queue.\n\n        RULE:\n\n            On transacted channels the server MUST not purge messages\n            that have already been sent to a client but not yet\n            acknowledged.\n\n        RULE:\n\n            The server MAY implement a purge queue or log that allows\n            system administrators to recover accidentally-purged\n            messages.  The server SHOULD NOT keep purged messages in\n            the same storage spaces as the live messages since the\n            volumes of purged messages may get very large.\n\n        PARAMETERS:\n            queue: shortstr\n\n                Specifies the name of the queue to purge.  If the\n                queue name is empty, refers to the current queue for\n                the channel, which is the last declared queue.\n\n                RULE:\n\n                    If the client did not previously declare a queue,\n                    and the queue name in this method is empty, the\n                    server MUST raise a connection exception with\n                    reply code 530 (not allowed).\n\n                RULE:\n\n                    The queue must exist. Attempting to purge a non-\n                    existing queue causes a channel exception.\n\n            nowait: boolean\n\n                do not send a reply method\n\n                If set, the server will not respond to the method. The\n                client should not wait for a reply method.  If the\n                server could not complete the method it will raise a\n                channel or connection exception.\n\n        if nowait is False, returns a message_count"
  },
  {
    "code": "def insrti(item, inset):\n    assert isinstance(inset, stypes.SpiceCell)\n    if hasattr(item, \"__iter__\"):\n        for i in item:\n            libspice.insrti_c(ctypes.c_int(i), ctypes.byref(inset))\n    else:\n        item = ctypes.c_int(item)\n        libspice.insrti_c(item, ctypes.byref(inset))",
    "docstring": "Insert an item into an integer set.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/insrti_c.html\n\n    :param item: Item to be inserted.\n    :type item: Union[float,Iterable[int]]\n    :param inset: Insertion set.\n    :type inset: spiceypy.utils.support_types.SpiceCell"
  },
  {
    "code": "def getConnectionStats(self):\n        cur = self._conn.cursor()\n        cur.execute()\n        rows = cur.fetchall()\n        if rows:\n            return dict(rows)\n        else:\n            return {}",
    "docstring": "Returns dictionary with number of connections for each database.\n        \n        @return: Dictionary of database connection statistics."
  },
  {
    "code": "def remove_service(self, zeroconf, srv_type, srv_name):\n        self.servers.remove_server(srv_name)\n        logger.info(\n            \"Glances server %s removed from the autodetect list\" % srv_name)",
    "docstring": "Remove the server from the list."
  },
  {
    "code": "def GetPublicCert(self):\n    cert_url = self.google_api_url + 'publicKeys'\n    resp, content = self.http.request(cert_url)\n    if resp.status == 200:\n      return simplejson.loads(content)\n    else:\n      raise errors.GitkitServerError('Error response for cert url: %s' %\n                                     content)",
    "docstring": "Download Gitkit public cert.\n\n    Returns:\n      dict of public certs."
  },
  {
    "code": "def authentication_url(self):\n        params = {\n            'client_id': self.client_id,\n            'response_type': self.type,\n            'redirect_uri': self.callback_url\n        }\n        return AUTHENTICATION_URL + \"?\" + urlencode(params)",
    "docstring": "Redirect your users to here to authenticate them."
  },
  {
    "code": "def geometrize_stops(stops: List[str], *, use_utm: bool = False) -> DataFrame:\n    import geopandas as gpd\n    g = (\n        stops.assign(\n            geometry=lambda x: [\n                sg.Point(p) for p in x[[\"stop_lon\", \"stop_lat\"]].values\n            ]\n        )\n        .drop([\"stop_lon\", \"stop_lat\"], axis=1)\n        .pipe(lambda x: gpd.GeoDataFrame(x, crs=cs.WGS84))\n    )\n    if use_utm:\n        lat, lon = stops.loc[0, [\"stop_lat\", \"stop_lon\"]].values\n        crs = hp.get_utm_crs(lat, lon)\n        g = g.to_crs(crs)\n    return g",
    "docstring": "Given a stops DataFrame, convert it to a GeoPandas GeoDataFrame\n    and return the result.\n\n    Parameters\n    ----------\n    stops : DataFrame\n        A GTFS stops table\n    use_utm : boolean\n        If ``True``, then convert the output to local UTM coordinates;\n        otherwise use WGS84 coordinates\n\n    Returns\n    -------\n    GeoPandas GeoDataFrame\n        Looks like the given stops DataFrame, but has a ``'geometry'``\n        column of Shapely Point objects that replaces\n        the ``'stop_lon'`` and ``'stop_lat'`` columns.\n\n    Notes\n    -----\n    Requires GeoPandas."
  },
  {
    "code": "def getcosIm(alat):\n    alat = np.float64(alat)\n    return np.cos(np.radians(alat))/np.sqrt(4 - 3*np.cos(np.radians(alat))**2)",
    "docstring": "Computes cosIm from modified apex latitude.\n\n    Parameters\n    ==========\n    alat : array_like\n        Modified apex latitude\n\n    Returns\n    =======\n    cosIm : ndarray or float"
  },
  {
    "code": "def set_scrollbars_cb(self, w, tf):\n        scrollbars = 'on' if tf else 'off'\n        self.t_.set(scrollbars=scrollbars)",
    "docstring": "This callback is invoked when the user checks the 'Use Scrollbars'\n        box in the preferences pane."
  },
  {
    "code": "def _lockfile(self):\n        pfile = pipfile.load(self.pipfile_location, inject_env=False)\n        lockfile = json.loads(pfile.lock())\n        for section in (\"default\", \"develop\"):\n            lock_section = lockfile.get(section, {})\n            for key in list(lock_section.keys()):\n                norm_key = pep423_name(key)\n                lockfile[section][norm_key] = lock_section.pop(key)\n        return lockfile",
    "docstring": "Pipfile.lock divided by PyPI and external dependencies."
  },
  {
    "code": "def get_keys_of_max_n(dict_obj, n):\n    return sorted([\n        item[0]\n        for item in sorted(\n            dict_obj.items(), key=lambda item: item[1], reverse=True\n        )[:n]\n    ])",
    "docstring": "Returns the keys that maps to the top n max values in the given dict.\n\n    Example:\n    --------\n    >>> dict_obj = {'a':2, 'b':1, 'c':5}\n    >>> get_keys_of_max_n(dict_obj, 2)\n    ['a', 'c']"
  },
  {
    "code": "def start(self):\n        if not self.valid:\n            err = (\"\\nMessengers and listeners that still need set:\\n\\n\"\n                   \"messengers : %s\\n\\n\"\n                   \"listeners : %s\\n\") \n            raise InvalidApplication(err % (self.needed_messengers,\n                                            self.needed_listeners))\n        self.dispatcher.start()",
    "docstring": "If we have a set of plugins that provide our expected listeners and\n        messengers, tell our dispatcher to start up. Otherwise, raise\n        InvalidApplication"
  },
  {
    "code": "def warning(self, msg):\n        self._execActions('warning', msg)\n        msg = self._execFilters('warning', msg)\n        self._processMsg('warning', msg)\n        self._sendMsg('warning', msg)",
    "docstring": "Log Warning Messages"
  },
  {
    "code": "def set_environment_variable(self, name, value):\n        m = Message()\n        m.add_byte(cMSG_CHANNEL_REQUEST)\n        m.add_int(self.remote_chanid)\n        m.add_string(\"env\")\n        m.add_boolean(False)\n        m.add_string(name)\n        m.add_string(value)\n        self.transport._send_user_message(m)",
    "docstring": "Set the value of an environment variable.\n\n        .. warning::\n            The server may reject this request depending on its ``AcceptEnv``\n            setting; such rejections will fail silently (which is common client\n            practice for this particular request type). Make sure you\n            understand your server's configuration before using!\n\n        :param str name: name of the environment variable\n        :param str value: value of the environment variable\n\n        :raises:\n            `.SSHException` -- if the request was rejected or the channel was\n            closed"
  },
  {
    "code": "def simple(self):\n        if self._days:\n            return '%sD' % self.totaldays\n        elif self.months:\n            return '%sM' % self._months\n        elif self.years:\n            return '%sY' % self.years\n        else:\n            return ''",
    "docstring": "A string representation with only one period delimiter."
  },
  {
    "code": "def file_upload(self, local_path, remote_path, l_st):\n        self.sftp.put(local_path, remote_path)\n        self._match_modes(remote_path, l_st)",
    "docstring": "Upload local_path to remote_path and set permission and mtime."
  },
  {
    "code": "def filter(self, value):\n        if self.env is None:\n            raise PluginException('The plugin must be installed to application.')\n        def wrapper(func):\n            name = func.__name__\n            if isinstance(value, str):\n                name = value\n            if callable(func):\n                self.env.filters[name] = func\n            return func\n        if callable(value):\n            return wrapper(value)\n        return wrapper",
    "docstring": "Register function to filters."
  },
  {
    "code": "def _CreateIndexIfNotExists(self, index_name, mappings):\n    try:\n      if not self._client.indices.exists(index_name):\n        self._client.indices.create(\n            body={'mappings': mappings}, index=index_name)\n    except elasticsearch.exceptions.ConnectionError as exception:\n      raise RuntimeError(\n          'Unable to create Elasticsearch index with error: {0!s}'.format(\n              exception))",
    "docstring": "Creates an Elasticsearch index if it does not exist.\n\n    Args:\n      index_name (str): mame of the index.\n      mappings (dict[str, object]): mappings of the index.\n\n    Raises:\n      RuntimeError: if the Elasticsearch index cannot be created."
  },
  {
    "code": "def replay(self, event, ts=0, end_ts=None, with_ts=False):\n        key = self._keygen(event, ts)\n        end_ts = end_ts if end_ts else \"+inf\"\n        elements = self.r.zrangebyscore(key, ts, end_ts, withscores=with_ts)\n        if not with_ts:\n            return [s(e) for e in elements]\n        else:\n            return [(s(e[0]), int(e[1])) for e in elements]",
    "docstring": "Replay events based on timestamp.\n\n        If you split namespace with ts, the replay will only return events\n        within the same namespace.\n\n        :param event: event name\n        :param ts: replay events after ts, default from 0.\n        :param end_ts: replay events to ts, default to \"+inf\".\n        :param with_ts: return timestamp with events, default to False.\n        :return: list of pks when with_ts set to False, list of (pk, ts) tuples\n         when with_ts is True."
  },
  {
    "code": "def _load_matcher(self) -> None:\n        for id_key in self._rule_lst:\n            if self._rule_lst[id_key].active:\n                pattern_lst = [a_pattern.spacy_token_lst for a_pattern in self._rule_lst[id_key].patterns]\n                for spacy_rule_id, spacy_rule in enumerate(itertools.product(*pattern_lst)):\n                    self._matcher.add(self._construct_key(id_key, spacy_rule_id), None, list(spacy_rule))",
    "docstring": "Add constructed spacy rule to Matcher"
  },
  {
    "code": "def reject_recursive_repeats(to_wrap):\n    to_wrap.__already_called = {}\n    @functools.wraps(to_wrap)\n    def wrapped(*args):\n        arg_instances = tuple(map(id, args))\n        thread_id = threading.get_ident()\n        thread_local_args = (thread_id,) + arg_instances\n        if thread_local_args in to_wrap.__already_called:\n            raise ValueError('Recursively called %s with %r' % (to_wrap, args))\n        to_wrap.__already_called[thread_local_args] = True\n        try:\n            wrapped_val = to_wrap(*args)\n        finally:\n            del to_wrap.__already_called[thread_local_args]\n        return wrapped_val\n    return wrapped",
    "docstring": "Prevent simple cycles by returning None when called recursively with same instance"
  },
  {
    "code": "def __is_subgraph_planar(graph):\n    num_nodes = graph.num_nodes()\n    num_edges = graph.num_edges()\n    if num_nodes < 5:\n        return True\n    if num_edges > 3*(num_nodes - 2):\n        return False\n    return kocay_planarity_test(graph)",
    "docstring": "Internal function to determine if a subgraph is planar."
  },
  {
    "code": "def merge_element_data(dest, sources, use_copy=True):\n    if dest is not None:\n        ret = dest.copy()\n    else:\n        ret = {}\n    if use_copy:\n        sources = copy.deepcopy(sources)\n    for s in sources:\n        if 'electron_shells' in s:\n            if 'electron_shells' not in ret:\n                ret['electron_shells'] = []\n            ret['electron_shells'].extend(s['electron_shells'])\n        if 'ecp_potentials' in s:\n            if 'ecp_potentials' in ret:\n                raise RuntimeError('Cannot overwrite existing ECP')\n            ret['ecp_potentials'] = s['ecp_potentials']\n            ret['ecp_electrons'] = s['ecp_electrons']\n        if 'references' in s:\n            if 'references' not in ret:\n                ret['references'] = []\n            for ref in s['references']:\n                if not ref in ret['references']:\n                    ret['references'].append(ref)\n    return ret",
    "docstring": "Merges the basis set data for an element from multiple sources\n    into dest.\n\n    The destination is not modified, and a (shallow) copy of dest is returned\n    with the data from sources added.\n\n    If use_copy is True, then the data merged into dest will be a (deep)\n    copy of that found in sources. Otherwise, data may be shared between dest\n    and sources"
  },
  {
    "code": "def _intersection(A,B):\n    intersection = []\n    for i in A:\n        if i in B:\n            intersection.append(i)\n    return intersection",
    "docstring": "A simple function to find an intersection between two arrays. \n    \n    @type A: List \n    @param A: First List\n    \n    @type B: List\n    @param B: Second List\n    \n    @rtype: List\n    @return: List of Intersections"
  },
  {
    "code": "def format_info(raw):\n    logging.debug(_('raw[0]: %s'), raw[0])\n    results, sense = raw\n    new = '\\n'.join(\n        '{} {} {} {}'.format(\n            i[0], sense.kind_id_to_name(i[1]),\n            sense.file_id_to_name(i[2]).lower(),\n            i[3] + ' ' if i[3] else '').strip()\n        for i in results)\n    return new",
    "docstring": "Format a string representing the information\n    concerning the name."
  },
  {
    "code": "def external(func):\n    def f(*args, **kwargs):\n        return func(*args, **kwargs)\n    f.external = True\n    f.__doc__ = func.__doc__\n    return f",
    "docstring": "Mark function as external.\n\n    :param func:\n    :return:"
  },
  {
    "code": "def _iupac_ambiguous_equal(ambig_base, unambig_base):\n    iupac_translation = {\n        'A': 'A',\n        'C': 'C',\n        'G': 'G',\n        'T': 'T',\n        'U': 'U',\n        'R': 'AG',\n        'Y': 'CT',\n        'S': 'GC',\n        'W': 'AT',\n        'K': 'GT',\n        'M': 'AC',\n        'B': 'CGT',\n        'D': 'AGT',\n        'H': 'ACT',\n        'V': 'ACG',\n        'N': 'ACGT',\n        '-': '-'\n    }\n    for i in (ambig_base, unambig_base):\n        if not len(i) == 1:\n            raise ValueError(\"only one base may be passed.\")\n    return unambig_base.upper() in iupac_translation[ambig_base.upper()]",
    "docstring": "Tests two bases for equality, accounting for IUPAC ambiguous DNA\n\n    ambiguous base may be IUPAC ambiguous, unambiguous must be one of ACGT"
  },
  {
    "code": "def _dict_key_priority(s):\n        if isinstance(s, Hook):\n            return _priority(s._schema) - 0.5\n        if isinstance(s, Optional):\n            return _priority(s._schema) + 0.5\n        return _priority(s)",
    "docstring": "Return priority for a given key object."
  },
  {
    "code": "def publish(self, topic, data, defer=None, block=True, timeout=None,\n                raise_error=True):\n        result = AsyncResult()\n        conn = self._get_connection(block=block, timeout=timeout)\n        try:\n            self._response_queues[conn].append(result)\n            conn.publish(topic, data, defer=defer)\n        finally:\n            self._put_connection(conn)\n        if raise_error:\n            return result.get()\n        return result",
    "docstring": "Publish a message to the given topic.\n\n        :param topic: the topic to publish to\n\n        :param data: bytestring data to publish\n\n        :param defer: duration in milliseconds to defer before publishing\n            (requires nsq 0.3.6)\n\n        :param block: wait for a connection to become available before\n            publishing the message. If block is `False` and no connections\n            are available, :class:`~gnsq.errors.NSQNoConnections` is raised\n\n        :param timeout: if timeout is a positive number, it blocks at most\n            ``timeout`` seconds before raising\n            :class:`~gnsq.errors.NSQNoConnections`\n\n        :param raise_error: if ``True``, it blocks until a response is received\n            from the nsqd server, and any error response is raised. Otherwise\n            an :class:`~gevent.event.AsyncResult` is returned"
  },
  {
    "code": "def dict_from_node(node, recursive=False):\n    dict = {}\n    for snode in node:\n        if len(snode) > 0:\n            if recursive:\n                value = dict_from_node(snode, True)\n            else:\n                value = len(snode)\n        elif snode.text is not None:\n            value = snode.text\n        else:\n            value = u''\n        if snode.tag in dict.keys():\n            if type(dict[snode.tag]) is list:\n                dict[snode.tag].append(value)\n            else:\n                dict[snode.tag] = [ dict[snode.tag], value ]\n        else:\n            dict[snode.tag] = value\n    return dict",
    "docstring": "Converts ElementTree node to a dictionary.\n\n    Parameters\n    ----------\n    node : ElementTree node\n    recursive : boolean\n        If recursive=False, the value of any field with children will be the\n        number of children.\n\n    Returns\n    -------\n    dict : nested dictionary.\n        Tags as keys and values as values. Sub-elements that occur multiple\n        times in an element are contained in a list."
  },
  {
    "code": "def confirmation_pdf(self, confirmation_id):\n        return self._create_get_request(resource=CONFIRMATIONS, billomat_id=confirmation_id, command=PDF)",
    "docstring": "Opens a pdf of a confirmation\n\n        :param confirmation_id: the confirmation id\n        :return: dict"
  },
  {
    "code": "def last_executed_query(self, cursor, sql, params):\n        return super(DatabaseOperations, self).last_executed_query(cursor, cursor.last_sql, cursor.last_params)",
    "docstring": "Returns a string of the query last executed by the given cursor, with\n        placeholders replaced with actual values.\n\n        `sql` is the raw query containing placeholders, and `params` is the\n        sequence of parameters. These are used by default, but this method\n        exists for database backends to provide a better implementation\n        according to their own quoting schemes."
  },
  {
    "code": "def engine(self):\n        pid = os.getpid()\n        conn = SQLAlchemyTarget._engine_dict.get(self.connection_string)\n        if not conn or conn.pid != pid:\n            engine = sqlalchemy.create_engine(\n                self.connection_string,\n                connect_args=self.connect_args,\n                echo=self.echo\n            )\n            SQLAlchemyTarget._engine_dict[self.connection_string] = self.Connection(engine, pid)\n        return SQLAlchemyTarget._engine_dict[self.connection_string].engine",
    "docstring": "Return an engine instance, creating it if it doesn't exist.\n\n        Recreate the engine connection if it wasn't originally created\n        by the current process."
  },
  {
    "code": "def write_sample_sheet(path, accessions, names, celfile_urls, sel=None):\n    with open(path, 'wb') as ofh:\n        writer = csv.writer(ofh, dialect='excel-tab',\n                            lineterminator=os.linesep,\n                            quoting=csv.QUOTE_NONE)\n        writer.writerow(['Accession', 'Name', 'CEL file', 'CEL file URL'])\n        n = len(names)\n        if sel is None:\n            sel = range(n)\n        for i in sel:\n            cf = celfile_urls[i].split('/')[-1]\n            writer.writerow([accessions[i], names[i], cf, celfile_urls[i]])",
    "docstring": "Write the sample sheet."
  },
  {
    "code": "def catalog_split_yaml(self, **kwargs):\n        kwargs_copy = self.base_dict.copy()\n        kwargs_copy.update(**kwargs)\n        self._replace_none(kwargs_copy)        \n        localpath = NameFactory.catalog_split_yaml_format.format(**kwargs_copy)\n        if kwargs.get('fullpath', False):\n            return self.fullpath(localpath=localpath)\n        return localpath",
    "docstring": "return the name of a catalog split yaml file"
  },
  {
    "code": "def train(self, content_objs, idx_labels):\n        if len(set([lab[0] for lab in idx_labels])) <= 1:\n            return None\n        fcs = [fc for _, fc in content_objs]\n        feature_names = vectorizable_features(fcs)\n        dis = dissimilarities(feature_names, fcs)\n        phi_dicts, labels = [], []\n        for coref_value, i, j in idx_labels:\n            labels.append(coref_value)\n            phi_dict = dict([(name, dis[name][i,j]) for name in feature_names])\n            phi_dicts.append(phi_dict)\n        vec = dict_vector()\n        training_data = vec.fit_transform(phi_dicts)\n        model = LogisticRegression(class_weight='auto', penalty='l1')\n        model.fit(training_data, labels)\n        self.feature_weights = dict([(name, model.coef_[0][i])\n                                     for i, name in enumerate(feature_names)])\n        return feature_names, model, vec",
    "docstring": "Trains and returns a model using sklearn.\n\n        If there are new labels to add, they can be added, returns an\n        sklearn model which can be used for prediction and getting\n        features.\n\n        This method may return ``None`` if there is insufficient\n        training data to produce a model.\n\n        :param labels: Ground truth data.\n        :type labels: list of ``({-1, 1}, index1, index2)``."
  },
  {
    "code": "def draw_address(canvas):\n    business_details = (\n        u'COMPANY NAME LTD',\n        u'STREET',\n        u'TOWN',\n        U'COUNTY',\n        U'POSTCODE',\n        U'COUNTRY',\n        u'',\n        u'',\n        u'Phone: +00 (0) 000 000 000',\n        u'Email: example@example.com',\n        u'Website: www.example.com',\n        u'Reg No: 00000000'\n    )\n    canvas.setFont('Helvetica', 9)\n    textobject = canvas.beginText(13 * cm, -2.5 * cm)\n    for line in business_details:\n        textobject.textLine(line)\n    canvas.drawText(textobject)",
    "docstring": "Draws the business address"
  },
  {
    "code": "def on_output_path_textChanged(self):\n        output_path = self.output_path.text()\n        output_not_xml_msg = tr('output file is not .tif')\n        if output_path and not output_path.endswith('.tif'):\n            self.warning_text.add(output_not_xml_msg)\n        elif output_path and output_not_xml_msg in self.warning_text:\n            self.warning_text.remove(output_not_xml_msg)\n        self.update_warning()",
    "docstring": "Action when output file name is changed."
  },
  {
    "code": "def _log_function(self, handler):\n        if handler.get_status() < 400:\n            log_method = request_log.info\n        elif handler.get_status() < 500:\n            log_method = request_log.warning\n        else:\n            log_method = request_log.error\n        for i in settings['LOGGING_IGNORE_URLS']:\n            if handler.request.uri.startswith(i):\n                log_method = request_log.debug\n                break\n        request_time = 1000.0 * handler.request.request_time()\n        log_method(\"%d %s %.2fms\", handler.get_status(),\n                   handler._request_summary(), request_time)",
    "docstring": "Override Application.log_function so that what to log can be controlled."
  },
  {
    "code": "def loadSettings(self, groupName=None):\n        groupName = groupName if groupName else self.settingsGroupName\n        settings = QtCore.QSettings()\n        logger.info(\"Reading {!r} from: {}\".format(groupName, settings.fileName()))\n        settings.beginGroup(groupName)\n        self.clear()\n        try:\n            for key in settings.childKeys():\n                if key.startswith('item'):\n                    dct = ast.literal_eval(settings.value(key))\n                    regItem = self._itemClass.createFromDict(dct)\n                    self.registerItem(regItem)\n        finally:\n            settings.endGroup()",
    "docstring": "Reads the registry items from the persistent settings store."
  },
  {
    "code": "def _signal_handler(self, signum, frame):\n        if self._options.config:\n            with open(self._options.config, \"w\") as cfg:\n                yaml.dump(self._home_assistant_config(), cfg)\n                print(\n                    \"Dumped home assistant configuration at\",\n                    self._options.config)\n        self._connection.close()\n        sys.exit(0)",
    "docstring": "Method called when handling signals"
  },
  {
    "code": "def permitted_actions(self, user, obj=None):\n        try:\n            if not self._obj_ok(obj):\n                raise InvalidPermissionObjectException\n            return user.permset_tree.permitted_actions(obj)\n        except ObjectDoesNotExist:\n            return []",
    "docstring": "Determine list of permitted actions for an object or object\n        pattern.\n\n        :param user: The user to test.\n        :type user: ``User``\n        :param obj: A function mapping from action names to object\n                    paths to test.\n        :type obj: callable\n        :returns: ``list(tutelary.engine.Action)`` -- permitted actions."
  },
  {
    "code": "def _get_variable_names(arr):\n    if VARIABLELABEL in arr.dims:\n        return arr.coords[VARIABLELABEL].tolist()\n    else:\n        return arr.name",
    "docstring": "Return the variable names of an array"
  },
  {
    "code": "def info(gandi, resource):\n    output_keys = ['name', 'state', 'size', 'type', 'id', 'dc', 'vm',\n                   'profile', 'kernel', 'cmdline']\n    resource = sorted(tuple(set(resource)))\n    vms = dict([(vm['id'], vm) for vm in gandi.iaas.list()])\n    datacenters = gandi.datacenter.list()\n    result = []\n    for num, item in enumerate(resource):\n        if num:\n            gandi.separator_line()\n        disk = gandi.disk.info(item)\n        output_disk(gandi, disk, datacenters, vms, [], output_keys)\n        result.append(disk)\n    return result",
    "docstring": "Display information about a disk.\n\n    Resource can be a disk name or ID"
  },
  {
    "code": "def readFile(self, pathToFile):\n        fd = open(pathToFile,  \"rb\")\n        data = fd.read()\n        fd.close()\n        return data",
    "docstring": "Returns data from a file.\n        \n        @type pathToFile: str\n        @param pathToFile: Path to the file.\n        \n        @rtype: str\n        @return: The data from file."
  },
  {
    "code": "def glyphs2ufo(options):\n    if options.output_dir is None:\n        options.output_dir = os.path.dirname(options.glyphs_file) or \".\"\n    if options.designspace_path is None:\n        options.designspace_path = os.path.join(\n            options.output_dir,\n            os.path.basename(os.path.splitext(options.glyphs_file)[0]) + \".designspace\",\n        )\n    glyphsLib.build_masters(\n        options.glyphs_file,\n        options.output_dir,\n        options.instance_dir,\n        designspace_path=options.designspace_path,\n        minimize_glyphs_diffs=options.no_preserve_glyphsapp_metadata,\n        propagate_anchors=options.propagate_anchors,\n        normalize_ufos=options.normalize_ufos,\n        create_background_layers=options.create_background_layers,\n        generate_GDEF=options.generate_GDEF,\n        store_editor_state=not options.no_store_editor_state,\n    )",
    "docstring": "Converts a Glyphs.app source file into UFO masters and a designspace file."
  },
  {
    "code": "def iter_tours(tourfile, frames=1):\n    fp = open(tourfile)\n    i = 0\n    for row in fp:\n        if row[0] == '>':\n            label = row[1:].strip()\n            if label.startswith(\"GA\"):\n                pf, j, score = label.split(\"-\", 2)\n                j = int(j)\n            else:\n                j = 0\n            i += 1\n        else:\n            if j % frames != 0:\n                continue\n            tour, tour_o = separate_tour_and_o(row)\n            yield i, label, tour, tour_o\n    fp.close()",
    "docstring": "Extract tours from tourfile. Tourfile contains a set of contig\n    configurations, generated at each iteration of the genetic algorithm. Each\n    configuration has two rows, first row contains iteration id and score,\n    second row contains list of contigs, separated by comma."
  },
  {
    "code": "def diff(self, mail_a, mail_b):\n        return len(''.join(unified_diff(\n            mail_a.body_lines, mail_b.body_lines,\n            fromfile='a', tofile='b',\n            fromfiledate='', tofiledate='',\n            n=0, lineterm='\\n')))",
    "docstring": "Return difference in bytes between two mails' normalized body.\n\n        TODO: rewrite the diff algorithm to not rely on naive unified diff\n        result parsing."
  },
  {
    "code": "def commit(self, id, impreq):\n        schema = RequestSchema()\n        json = self.service.encode(schema, impreq)\n        schema = RequestSchema()\n        resp = self.service.post(self.base+str(id)+'/', json=json)\n        return self.service.decode(schema, resp)",
    "docstring": "Commit a staged import.\n\n        :param id: Staged import ID as an int.\n        :param impreq: :class:`imports.Request <imports.Request>` object\n        :return: :class:`imports.Request <imports.Request>` object\n        :rtype: imports.Request"
  },
  {
    "code": "def deploy_from_template(self, context, deploy_action, cancellation_context):\n        deploy_from_template_model = self.resource_model_parser.convert_to_resource_model(\n            attributes=deploy_action.actionParams.deployment.attributes,\n            resource_model_type=vCenterVMFromTemplateResourceModel)\n        data_holder = DeployFromTemplateDetails(deploy_from_template_model, deploy_action.actionParams.appName)\n        deploy_result_action = self.command_wrapper.execute_command_with_connection(\n            context,\n            self.deploy_command.execute_deploy_from_template,\n            data_holder,\n            cancellation_context,\n            self.folder_manager)\n        deploy_result_action.actionId = deploy_action.actionId\n        return deploy_result_action",
    "docstring": "Deploy From Template Command, will deploy vm from template\n\n        :param CancellationContext cancellation_context:\n        :param ResourceCommandContext context: the context of the command\n        :param DeployApp deploy_action:\n        :return DeployAppResult deploy results"
  },
  {
    "code": "def authenticate_with_serviceaccount(reactor, **kw):\n    config = KubeConfig.from_service_account(**kw)\n    policy = https_policy_from_config(config)\n    token = config.user[\"token\"]\n    agent = HeaderInjectingAgent(\n        _to_inject=Headers({u\"authorization\": [u\"Bearer {}\".format(token)]}),\n        _agent=Agent(reactor, contextFactory=policy),\n    )\n    return agent",
    "docstring": "Create an ``IAgent`` which can issue authenticated requests to a\n    particular Kubernetes server using a service account token.\n\n    :param reactor: The reactor with which to configure the resulting agent.\n\n    :param bytes path: The location of the service account directory.  The\n        default should work fine for normal use within a container.\n\n    :return IAgent: An agent which will authenticate itself to a particular\n        Kubernetes server and which will verify that server or refuse to\n        interact with it."
  },
  {
    "code": "def get_region(self, x,z):\n        if (x,z) not in self.regions:\n            if (x,z) in self.regionfiles:\n                self.regions[(x,z)] = region.RegionFile(self.regionfiles[(x,z)])\n            else:\n                self.regions[(x,z)] = region.RegionFile()\n            self.regions[(x,z)].loc = Location(x=x,z=z)\n        return self.regions[(x,z)]",
    "docstring": "Get a region using x,z coordinates of a region. Cache results."
  },
  {
    "code": "def fields(self):\n        if self._fields is None:\n            self._fields = FieldList(\n                self._version,\n                assistant_sid=self._solution['assistant_sid'],\n                task_sid=self._solution['sid'],\n            )\n        return self._fields",
    "docstring": "Access the fields\n\n        :returns: twilio.rest.autopilot.v1.assistant.task.field.FieldList\n        :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldList"
  },
  {
    "code": "def get_allowed_domain(url, allow_subdomains=True):\n        if allow_subdomains:\n            return re.sub(re_www, '', re.search(r'[^/]+\\.[^/]+', url).group(0))\n        else:\n            return re.search(re_domain, UrlExtractor.get_allowed_domain(url)).group(0)",
    "docstring": "Determines the url's domain.\n\n        :param str url: the url to extract the allowed domain from\n        :param bool allow_subdomains: determines wether to include subdomains\n        :return str: subdomains.domain.topleveldomain or domain.topleveldomain"
  },
  {
    "code": "def unpack_struct(self, struct):\n        size = struct.size\n        offset = self.offset\n        if self.data:\n            avail = len(self.data) - offset\n        else:\n            avail = 0\n        if avail < size:\n            raise UnpackException(struct.format, size, avail)\n        self.offset = offset + size\n        return struct.unpack_from(self.data, offset)",
    "docstring": "unpacks the given struct from the underlying buffer and returns\n        the results. Will raise an UnpackException if there is not\n        enough data to satisfy the format of the structure"
  },
  {
    "code": "def _init_file(self):\n        self.keyring_key = self._get_new_password()\n        self.set_password('keyring-setting',\n                          'password reference',\n                          'password reference value')\n        self._write_config_value('keyring-setting',\n                                 'scheme',\n                                 self.scheme)\n        self._write_config_value('keyring-setting',\n                                 'version',\n                                 self.version)",
    "docstring": "Initialize a new password file and set the reference password."
  },
  {
    "code": "def _cfg(key, default=None):\n    root_cfg = __salt__.get('config.get', __opts__.get)\n    kms_cfg = root_cfg('aws_kms', {})\n    return kms_cfg.get(key, default)",
    "docstring": "Return the requested value from the aws_kms key in salt configuration.\n\n    If it's not set, return the default."
  },
  {
    "code": "def setScales(self,scales=None,term_num=None):\n        if scales==None:\n            for term_i in range(self.n_terms):\n                n_scales = self.vd.getTerm(term_i).getNumberScales()\n                self.vd.getTerm(term_i).setScales(SP.array(SP.randn(n_scales)))\n        elif term_num==None:\n            assert scales.shape[0]==self.vd.getNumberScales(), 'incompatible shape'\n            index = 0\n            for term_i in range(self.n_terms):\n                index1 = index+self.vd.getTerm(term_i).getNumberScales()\n                self.vd.getTerm(term_i).setScales(scales[index:index1])\n                index = index1\n        else:\n            assert scales.shape[0]==self.vd.getTerm(term_num).getNumberScales(), 'incompatible shape'\n            self.vd.getTerm(term_num).setScales(scales)",
    "docstring": "get random initialization of variances based on the empirical trait variance\n\n        Args:\n            scales:     if scales==None: set them randomly, \n                        else: set scales to term_num (if term_num==None: set to all terms)\n            term_num:   set scales to term_num"
  },
  {
    "code": "def _get_hanging_wall_coeffs_rrup(self, dists):\n        fhngrrup = np.ones(len(dists.rrup))\n        idx = dists.rrup > 0.0\n        fhngrrup[idx] = (dists.rrup[idx] - dists.rjb[idx]) / dists.rrup[idx]\n        return fhngrrup",
    "docstring": "Returns the hanging wall rrup term defined in equation 13"
  },
  {
    "code": "def get_phase(n_samples, des_mask, asc_mask):\n    import numpy\n    phase = numpy.zeros(n_samples, dtype=int)\n    phase[asc_mask] =  1\n    phase[des_mask] = -1\n    return phase",
    "docstring": "Get the directional phase sign for each sample in depths\n\n    Args\n    ----\n    n_samples: int\n        Length of output phase array\n    des_mask: numpy.ndarray, shape (n,)\n        Boolean mask of values where animal is descending\n    asc_mask: numpy.ndarray, shape(n,)\n        Boolean mask of values where animal is ascending\n\n    Returns\n    -------\n    phase: numpy.ndarray, shape (n,)\n        Signed integer array values representing animal's dive phase\n\n        *Phases*:\n\n        *  0: neither ascending/descending\n        *  1: ascending\n        * -1: descending."
  },
  {
    "code": "def _get_api_id(self, event_properties):\n        api_id = event_properties.get(\"RestApiId\")\n        if isinstance(api_id, dict) and \"Ref\" in api_id:\n            api_id = api_id[\"Ref\"]\n        return api_id",
    "docstring": "Get API logical id from API event properties.\n\n        Handles case where API id is not specified or is a reference to a logical id."
  },
  {
    "code": "def setup_dir(self):\n        cd = self.opts.cd or self.config['crony'].get('directory')\n        if cd:\n            self.logger.debug(f'Adding cd to {cd}')\n            self.cmd = f'cd {cd} && {self.cmd}'",
    "docstring": "Change directory for script if necessary."
  },
  {
    "code": "def add(self, key):\n        encodedKey = json.dumps(key)\n        with self.connect() as conn:\n            with doTransaction(conn):\n                sql = 'INSERT IGNORE INTO ' + self.table + ' (name) VALUES (%s)'\n                return insertSQL(conn, sql, args=[encodedKey])",
    "docstring": "add key to the namespace.  it is fine to add a key multiple times."
  },
  {
    "code": "def __start_connection(self, context, node, ccallbacks=None):\n        _logger.debug(\"Creating connection object: CONTEXT=[%s] NODE=[%s]\", \n                      context, node)\n        c = nsq.connection.Connection(\n                context,\n                node, \n                self.__identify, \n                self.__message_handler,\n                self.__quit_ev,\n                ccallbacks,\n                ignore_quit=self.__connection_ignore_quit)\n        g = gevent.spawn(c.run)\n        timeout_s = nsq.config.client.NEW_CONNECTION_NEGOTIATE_TIMEOUT_S\n        if c.connected_ev.wait(timeout_s) is False:\n            _logger.error(\"New connection to server [%s] timed-out. Cleaning-\"\n                          \"up thread.\", node)\n            g.kill()\n            g.join()\n            raise EnvironmentError(\"Connection to server [%s] failed.\" % \n                                   (node,))\n        self.__connections.append((node, c, g))",
    "docstring": "Start a new connection, and manage it from a new greenlet."
  },
  {
    "code": "def getYadisXRD(xrd_tree):\n    xrd = None\n    for xrd in xrd_tree.findall(xrd_tag):\n        pass\n    if xrd is None:\n        raise XRDSError('No XRD present in tree')\n    return xrd",
    "docstring": "Return the XRD element that should contain the Yadis services"
  },
  {
    "code": "def _exponential_timeout_generator(initial, maximum, multiplier, deadline):\n    if deadline is not None:\n        deadline_datetime = datetime_helpers.utcnow() + datetime.timedelta(\n            seconds=deadline\n        )\n    else:\n        deadline_datetime = datetime.datetime.max\n    timeout = initial\n    while True:\n        now = datetime_helpers.utcnow()\n        yield min(\n            timeout,\n            maximum,\n            float((deadline_datetime - now).seconds),\n        )\n        timeout = timeout * multiplier",
    "docstring": "A generator that yields exponential timeout values.\n\n    Args:\n        initial (float): The initial timeout.\n        maximum (float): The maximum timeout.\n        multiplier (float): The multiplier applied to the timeout.\n        deadline (float): The overall deadline across all invocations.\n\n    Yields:\n        float: A timeout value."
  },
  {
    "code": "def raise_error(error_type: str) -> None:\n    try:\n        error = next((v for k, v in ERROR_CODES.items() if k in error_type))\n    except StopIteration:\n        error = AirVisualError\n    raise error(error_type)",
    "docstring": "Raise the appropriate error based on error message."
  },
  {
    "code": "def _button_plus_clicked(self, n):\n        self._button_save.setEnabled(True)\n        self.insert_colorpoint(self._colorpoint_list[n][0],\n                               self._colorpoint_list[n][1],\n                               self._colorpoint_list[n][2])\n        self._build_gui()",
    "docstring": "Create a new colorpoint."
  },
  {
    "code": "def section(self, section):\n        if not isinstance(self._container, ConfigUpdater):\n            raise ValueError(\"Sections can only be added at section level!\")\n        if isinstance(section, str):\n            section = Section(section, container=self._container)\n        elif not isinstance(section, Section):\n            raise ValueError(\"Parameter must be a string or Section type!\")\n        if section.name in [block.name for block in self._container\n                            if isinstance(block, Section)]:\n            raise DuplicateSectionError(section.name)\n        self._container.structure.insert(self._idx, section)\n        self._idx += 1\n        return self",
    "docstring": "Creates a section block\n\n        Args:\n            section (str or :class:`Section`): name of section or object\n\n        Returns:\n            self for chaining"
  },
  {
    "code": "def normalized_start(self):\n    namespaces_after_key = list(self.make_datastore_query().Run(limit=1))\n    if not namespaces_after_key:\n      return None\n    namespace_after_key = namespaces_after_key[0].name() or ''\n    return NamespaceRange(namespace_after_key,\n                          self.namespace_end,\n                          _app=self.app)",
    "docstring": "Returns a NamespaceRange with leading non-existant namespaces removed.\n\n    Returns:\n      A copy of this NamespaceRange whose namespace_start is adjusted to exclude\n      the portion of the range that contains no actual namespaces in the\n      datastore. None is returned if the NamespaceRange contains no actual\n      namespaces in the datastore."
  },
  {
    "code": "def __locate_scubainit(self):\n        pkg_path = os.path.dirname(__file__)\n        self.scubainit_path = os.path.join(pkg_path, 'scubainit')\n        if not os.path.isfile(self.scubainit_path):\n            raise ScubaError('scubainit not found at \"{}\"'.format(self.scubainit_path))",
    "docstring": "Determine path to scubainit binary"
  },
  {
    "code": "def open_http(self, url, data=None):\n        return self._open_generic_http(http_client.HTTPConnection, url, data)",
    "docstring": "Use HTTP protocol."
  },
  {
    "code": "def find_packages():\n    packages = ['pyctools']\n    for root, dirs, files in os.walk(os.path.join('src', 'pyctools')):\n        package = '.'.join(root.split(os.sep)[1:])\n        for name in dirs:\n            packages.append(package + '.' + name)\n    return packages",
    "docstring": "Walk source directory tree and convert each sub directory to a\n    package name."
  },
  {
    "code": "def capacityForRole(self,role):\n        if isinstance(role, DanceRole):\n            role_id = role.id\n        else:\n            role_id = role\n        eventRoles = self.eventrole_set.filter(capacity__gt=0)\n        if eventRoles.count() > 0 and role_id not in [x.role.id for x in eventRoles]:\n            return 0\n        elif eventRoles.count() > 0:\n            return eventRoles.get(role=role).capacity\n        if isinstance(self,Series):\n            try:\n                availableRoles = self.classDescription.danceTypeLevel.danceType.roles.all()\n                if availableRoles.count() > 0 and role_id not in [x.id for x in availableRoles]:\n                    return 0\n                elif availableRoles.count() > 0 and self.capacity:\n                    return ceil(self.capacity / availableRoles.count())\n            except ObjectDoesNotExist as e:\n                logger.error('Error in calculating capacity for role: %s' % e)\n        return self.capacity",
    "docstring": "Accepts a DanceRole object and determines the capacity for that role at this event.this\n        Since roles are not always custom specified for events, this looks for the set of\n        available roles in multiple places, and only returns the overall capacity of the event\n        if roles are not found elsewhere."
  },
  {
    "code": "def create_and_run_collector(document, options):\n        collector = None\n        if not options.report == 'off':\n            collector = Collector()\n            collector.store.configure(document)\n            Event.configure(collector_queue=collector.queue)\n            collector.start()\n        return collector",
    "docstring": "Create and run collector process for report data."
  },
  {
    "code": "def time_until_expiration(self):\n        if self.password_expires_at is not None:\n            expiration_date = datetime.datetime.strptime(\n                self.password_expires_at, \"%Y-%m-%dT%H:%M:%S.%f\")\n            return expiration_date - datetime.datetime.now()",
    "docstring": "Returns the number of remaining days until user's password expires.\n\n        Calculates the number days until the user must change their password,\n        once the password expires the user will not able to log in until an\n        admin changes its password."
  },
  {
    "code": "def validate_port(port):\n    if not isinstance(port, (str, int)):\n        raise TypeError(f'port must be an integer or string: {port}')\n    if isinstance(port, str) and port.isdigit():\n        port = int(port)\n    if isinstance(port, int) and 0 < port <= 65535:\n        return port\n    raise ValueError(f'invalid port: {port}')",
    "docstring": "Validate port and return it as an integer.\n\n    A string, or its representation as an integer, is accepted."
  },
  {
    "code": "def default_token_implementation(self, user_id):\n        user = self.get(user_id)\n        if not user:\n            msg = 'No user with such id [{}]'\n            raise x.JwtNoUser(msg.format(user_id))\n        if user._token:\n            try:\n                self.decode_token(user._token)\n                return user._token\n            except jwt.exceptions.ExpiredSignatureError:\n                pass\n        from_now = datetime.timedelta(seconds=self.jwt_lifetime)\n        expires = datetime.datetime.utcnow() + from_now\n        issued = datetime.datetime.utcnow()\n        not_before = datetime.datetime.utcnow()\n        data = dict(\n            exp=expires,\n            nbf=not_before,\n            iat=issued,\n            user_id=user_id\n        )\n        token = jwt.encode(data, self.jwt_secret, algorithm=self.jwt_algo)\n        string_token = token.decode('utf-8')\n        user._token = string_token\n        self.save(user)\n        return string_token",
    "docstring": "Default JWT token implementation\n        This is used by default for generating user tokens if custom\n        implementation was not configured. The token will contain user_id and\n        expiration date. If you need more information added to the token,\n        register your custom implementation.\n\n        It will load a user to see if token is already on file. If it is, the\n        existing token will be checked for expiration and returned if valid.\n        Otherwise a new token will be generated and persisted. This can be used\n        to perform token revocation.\n\n        :param user_id: int, user id\n        :return: string"
  },
  {
    "code": "def get_all_tags_of_offer(self, offer_id):\n        return self._iterate_through_pages(\n            get_function=self.get_tags_of_offer_per_page,\n            resource=OFFER_TAGS,\n            **{'offer_id': offer_id}\n        )",
    "docstring": "Get all tags of offer\n        This will iterate over all pages until it gets all elements.\n        So if the rate limit exceeded it will throw an Exception and you will get nothing\n\n        :param offer_id: the offer id\n        :return: list"
  },
  {
    "code": "def get_state_map(meta_graph, state_ops, unsupported_state_ops,\n                  get_tensor_by_name):\n  state_map = {}\n  for node in meta_graph.graph_def.node:\n    if node.op in state_ops:\n      tensor_name = node.name + \":0\"\n      tensor = get_tensor_by_name(tensor_name)\n      num_outputs = len(tensor.op.outputs)\n      if num_outputs != 1:\n        raise ValueError(\"Stateful op %s has %d outputs, expected 1\" %\n                         (node.op, num_outputs))\n      state_map[tensor_name] = tensor\n    if node.op in unsupported_state_ops:\n      raise ValueError(\"Unsupported stateful op: %s\" % node.op)\n  return state_map",
    "docstring": "Returns a map from tensor names to tensors that hold the state."
  },
  {
    "code": "def _void_array_to_list(restuple, _func, _args):\n    shape = (restuple.e.len, 1)\n    array_size = np.prod(shape)\n    mem_size = 8 * array_size\n    array_str_e = string_at(restuple.e.data, mem_size)\n    array_str_n = string_at(restuple.n.data, mem_size)\n    ls_e = np.frombuffer(array_str_e, float, array_size).tolist()\n    ls_n = np.frombuffer(array_str_n, float, array_size).tolist()\n    return ls_e, ls_n",
    "docstring": "Convert the FFI result to Python data structures"
  },
  {
    "code": "def register(self, event, fn):\n        self._callbacks.setdefault(event, []).append(fn)\n        return fn",
    "docstring": "Tell the object to run `fn` whenever a message of type `event` is\n        received."
  },
  {
    "code": "def safe_stat(path, timeout=1, cmd=None):\n    \"Use threads and a subproc to bodge a timeout on top of filesystem access\"\n    global safe_stat_process\n    if cmd is None:\n        cmd = ['/usr/bin/stat']\n    cmd.append(path)\n    def target():\n        global safe_stat_process\n        logger.debug('Stat thread started')\n        safe_stat_process = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE)\n        _results = safe_stat_process.communicate()\n        logger.debug('Stat thread finished')\n    thread = threading.Thread(target=target)\n    thread.start()\n    thread.join(timeout)\n    if thread.is_alive():\n        safe_stat_process.terminate()\n        thread.join()\n    return safe_stat_process.returncode == 0",
    "docstring": "Use threads and a subproc to bodge a timeout on top of filesystem access"
  },
  {
    "code": "def rotateX(self, angle):\n        rad = angle * math.pi / 180\n        cosa = math.cos(rad)\n        sina = math.sin(rad)\n        y = self.y * cosa - self.z * sina\n        z = self.y * sina + self.z * cosa\n        return Point3D(self.x, y, z)",
    "docstring": "Rotates the point around the X axis by the given angle in degrees."
  },
  {
    "code": "def missing(self, dst):\n        for inst in six.itervalues(dst):\n            if inst.status != REMOVED:\n                inst.status = REMOVED\n                inst.save()",
    "docstring": "Mark all missing plugins, that exists in database, but are not\n        registered."
  },
  {
    "code": "def open(self):\n        if self.handle is None:\n            self.handle = fits.open(self.fname, mode='readonly')\n        if self.extn:\n            if len(self.extn) == 1:\n                hdu = self.handle[self.extn[0]]\n            else:\n                hdu = self.handle[self.extn[0],self.extn[1]]\n        else:\n            hdu = self.handle[0]\n        if isinstance(hdu,fits.hdu.compressed.CompImageHDU):\n            self.compress = True\n        return hdu",
    "docstring": "Opens the file for subsequent access."
  },
  {
    "code": "def setup_locale(lc_all: str,\n                 first_weekday: int = None,\n                 *,\n                 lc_collate: str = None,\n                 lc_ctype: str = None,\n                 lc_messages: str = None,\n                 lc_monetary: str = None,\n                 lc_numeric: str = None,\n                 lc_time: str = None) -> str:\n    if first_weekday is not None:\n        calendar.setfirstweekday(first_weekday)\n    locale.setlocale(locale.LC_COLLATE, lc_collate or lc_all)\n    locale.setlocale(locale.LC_CTYPE, lc_ctype or lc_all)\n    locale.setlocale(locale.LC_MESSAGES, lc_messages or lc_all)\n    locale.setlocale(locale.LC_MONETARY, lc_monetary or lc_all)\n    locale.setlocale(locale.LC_NUMERIC, lc_numeric or lc_all)\n    locale.setlocale(locale.LC_TIME, lc_time or lc_all)\n    return locale.setlocale(locale.LC_ALL, lc_all)",
    "docstring": "Shortcut helper to setup locale for backend application.\n\n    :param lc_all: Locale to use.\n    :param first_weekday:\n        Weekday for start week. 0 for Monday, 6 for Sunday. By default: None\n    :param lc_collate: Collate locale to use. By default: ``<lc_all>``\n    :param lc_ctype: Ctype locale to use. By default: ``<lc_all>``\n    :param lc_messages: Messages locale to use. By default: ``<lc_all>``\n    :param lc_monetary: Monetary locale to use. By default: ``<lc_all>``\n    :param lc_numeric: Numeric locale to use. By default: ``<lc_all>``\n    :param lc_time: Time locale to use. By default: ``<lc_all>``"
  },
  {
    "code": "def delete(self):\n        try:\n            self.revert()\n        except errors.ChangelistError:\n            pass\n        self._connection.run(['change', '-d', str(self._change)])",
    "docstring": "Reverts all files in this changelist then deletes the changelist from perforce"
  },
  {
    "code": "def remove_mapping(agent, prefix, ip):\n    return _broadcast(agent, RemoveMappingManager,\n                      RecordType.record_A, prefix, ip)",
    "docstring": "Removes a mapping with a contract.\n    It has high latency but gives some kind of guarantee."
  },
  {
    "code": "def register_directory(self, directory, parent, ensure_uniqueness=False):\n        if ensure_uniqueness:\n            if self.get_directory_nodes(directory):\n                raise foundations.exceptions.ProgrammingError(\"{0} | '{1}' directory is already registered!\".format(\n                    self.__class__.__name__, directory))\n        LOGGER.debug(\"> Registering '{0}' directory.\".format(directory))\n        row = parent.children_count()\n        self.beginInsertRows(self.get_node_index(parent), row, row)\n        directory_node = DirectoryNode(name=os.path.basename(directory),\n                                       path=directory,\n                                       parent=parent)\n        self.endInsertRows()\n        self.directory_registered.emit(directory_node)\n        return directory_node",
    "docstring": "Registers given directory in the Model.\n\n        :param directory: Directory to register.\n        :type directory: unicode\n        :param parent: DirectoryNode parent.\n        :type parent: GraphModelNode\n        :param ensure_uniqueness: Ensure registrar uniqueness.\n        :type ensure_uniqueness: bool\n        :return: DirectoryNode.\n        :rtype: DirectoryNode"
  },
  {
    "code": "def logout(self):\n        from flask_login import logout_user, current_user\n        if not current_user.is_authenticated:\n            return True\n        user = current_user\n        events.logout_event.send(user)\n        logout_user()\n        app = current_app._get_current_object()\n        identity_changed.send(app, identity=AnonymousIdentity())\n        return True",
    "docstring": "Logout user and emit event."
  },
  {
    "code": "def _build(self, inputs, prev_state):\n    next_state = self._model(prev_state)\n    return next_state, next_state",
    "docstring": "Connects the ModelRNN module into the graph.\n\n    If this is not the first time the module has been connected to the graph,\n    the Tensors provided as input_ and state must have the same final\n    dimension, in order for the existing variables to be the correct size for\n    their corresponding multiplications. The batch size may differ for each\n    connection.\n\n    Args:\n      inputs: Tensor input to the ModelRNN (ignored).\n      prev_state: Tensor of size `model.output_size`.\n\n    Returns:\n      output: Tensor of size `model.output_size`.\n      next_state: Tensor of size `model.output_size`."
  },
  {
    "code": "def clear(self):\n        for key in self.conn.keys():\n            self.conn.delete(key)",
    "docstring": "Helper for clearing all the keys in a database. Use with\n        caution!"
  },
  {
    "code": "def push(self, read_time, next_resume_token):\n        deletes, adds, updates = Watch._extract_changes(\n            self.doc_map, self.change_map, read_time\n        )\n        updated_tree, updated_map, appliedChanges = self._compute_snapshot(\n            self.doc_tree, self.doc_map, deletes, adds, updates\n        )\n        if not self.has_pushed or len(appliedChanges):\n            key = functools.cmp_to_key(self._comparator)\n            keys = sorted(updated_tree.keys(), key=key)\n            self._snapshot_callback(\n                keys,\n                appliedChanges,\n                datetime.datetime.fromtimestamp(read_time.seconds, pytz.utc),\n            )\n            self.has_pushed = True\n        self.doc_tree = updated_tree\n        self.doc_map = updated_map\n        self.change_map.clear()\n        self.resume_token = next_resume_token",
    "docstring": "Assembles a new snapshot from the current set of changes and invokes\n        the user's callback. Clears the current changes on completion."
  },
  {
    "code": "def node_label_absent(name, node, **kwargs):\n    ret = {'name': name,\n           'changes': {},\n           'result': False,\n           'comment': ''}\n    labels = __salt__['kubernetes.node_labels'](node, **kwargs)\n    if name not in labels:\n        ret['result'] = True if not __opts__['test'] else None\n        ret['comment'] = 'The label does not exist'\n        return ret\n    if __opts__['test']:\n        ret['comment'] = 'The label is going to be deleted'\n        ret['result'] = None\n        return ret\n    __salt__['kubernetes.node_remove_label'](\n        node_name=node,\n        label_name=name,\n        **kwargs)\n    ret['result'] = True\n    ret['changes'] = {\n        'kubernetes.node_label': {\n            'new': 'absent', 'old': 'present'}}\n    ret['comment'] = 'Label removed from node'\n    return ret",
    "docstring": "Ensures that the named label is absent from the node.\n\n    name\n        The name of the label\n\n    node\n        The name of the node"
  },
  {
    "code": "def show_wbridges(self):\n        grp = self.getPseudoBondGroup(\"Water Bridges-%i\" % self.tid, associateWith=[self.model])\n        grp.lineWidth = 3\n        for i, wbridge in enumerate(self.plcomplex.waterbridges):\n            c = grp.newPseudoBond(self.atoms[wbridge.water_id], self.atoms[wbridge.acc_id])\n            c.color = self.colorbyname('cornflower blue')\n            self.water_ids.append(wbridge.water_id)\n            b = grp.newPseudoBond(self.atoms[wbridge.don_id], self.atoms[wbridge.water_id])\n            b.color = self.colorbyname('cornflower blue')\n            self.water_ids.append(wbridge.water_id)\n            if wbridge.protisdon:\n                self.bs_res_ids.append(wbridge.don_id)\n            else:\n                self.bs_res_ids.append(wbridge.acc_id)",
    "docstring": "Visualizes water bridges"
  },
  {
    "code": "def get_snapshots_filename(impl, working_dir):\n    snapshots_filename = impl.get_virtual_chain_name() + \".snapshots\"\n    return os.path.join(working_dir, snapshots_filename)",
    "docstring": "Get the absolute path to the chain's consensus snapshots file."
  },
  {
    "code": "def name_to_system_object(self, name):\n        if isinstance(name, str):\n            if self.allow_name_referencing:\n                name = name\n            else:\n                raise NameError('System.allow_name_referencing is set to False, cannot convert string to name')\n        elif isinstance(name, Object):\n            name = str(name)\n        return self.namespace.get(name, None)",
    "docstring": "Give SystemObject instance corresponding to the name"
  },
  {
    "code": "def write(self, data):\n        self._check_can_write()\n        compressed = self._compressor.compress(data)\n        self._fp.write(compressed)\n        self._pos += len(data)\n        return len(data)",
    "docstring": "Write a bytes object to the file.\n\n        Returns the number of uncompressed bytes written, which is\n        always len(data). Note that due to buffering, the file on disk\n        may not reflect the data written until close() is called."
  },
  {
    "code": "def get_all_subnets(self, subnet_ids=None, filters=None):\n        params = {}\n        if subnet_ids:\n            self.build_list_params(params, subnet_ids, 'SubnetId')\n        if filters:\n            i = 1\n            for filter in filters:\n                params[('Filter.%d.Name' % i)] = filter[0]\n                params[('Filter.%d.Value.1' % i)] = filter[1]\n                i += 1\n        return self.get_list('DescribeSubnets', params, [('item', Subnet)])",
    "docstring": "Retrieve information about your Subnets.  You can filter results to\n        return information only about those Subnets that match your search\n        parameters.  Otherwise, all Subnets associated with your account\n        are returned.\n\n        :type subnet_ids: list\n        :param subnet_ids: A list of strings with the desired Subnet ID's\n\n        :type filters: list of tuples\n        :param filters: A list of tuples containing filters.  Each tuple\n                        consists of a filter key and a filter value.\n                        Possible filter keys are:\n\n                        - *state*, the state of the Subnet\n                          (pending,available)\n                        - *vpdId*, the ID of teh VPC the subnet is in.\n                        - *cidrBlock*, CIDR block of the subnet\n                        - *availabilityZone*, the Availability Zone\n                          the subnet is in.\n\n\n        :rtype: list\n        :return: A list of :class:`boto.vpc.subnet.Subnet`"
  },
  {
    "code": "def post(self, request, uri):\n        uri = self.decode_uri(uri)\n        data, meta = self.get_post_data(request)\n        meta['author'] = auth.get_username(request)\n        node = cio.set(uri, data, publish=False, **meta)\n        return self.render_to_json(node)",
    "docstring": "Set node data for uri, return rendered content.\n\n        JSON Response:\n            {uri: x, content: y}"
  },
  {
    "code": "def copy(self):\n    if self.object_getattr is Query.object_getattr:\n      other = Query(self.key)\n    else:\n      other = Query(self.key, object_getattr=self.object_getattr)\n    other.limit = self.limit\n    other.offset = self.offset\n    other.offset_key = self.offset_key\n    other.filters = self.filters\n    other.orders = self.orders\n    return other",
    "docstring": "Returns a copy of this query."
  },
  {
    "code": "def create(self):\n        api = self._instance._client.database_admin_api\n        metadata = _metadata_with_prefix(self.name)\n        db_name = self.database_id\n        if \"-\" in db_name:\n            db_name = \"`%s`\" % (db_name,)\n        future = api.create_database(\n            parent=self._instance.name,\n            create_statement=\"CREATE DATABASE %s\" % (db_name,),\n            extra_statements=list(self._ddl_statements),\n            metadata=metadata,\n        )\n        return future",
    "docstring": "Create this database within its instance\n\n        Inclues any configured schema assigned to :attr:`ddl_statements`.\n\n        See\n        https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabase\n\n        :rtype: :class:`~google.api_core.operation.Operation`\n        :returns: a future used to poll the status of the create request\n        :raises Conflict: if the database already exists\n        :raises NotFound: if the instance owning the database does not exist"
  },
  {
    "code": "def isPeregrine(self):\n        return isPeregrine(self.obj.id,\n                           self.obj.sign,\n                           self.obj.signlon)",
    "docstring": "Returns if this object is peregrine."
  },
  {
    "code": "def _management_form(self):\n        if self.is_bound:\n            form = ConcurrentManagementForm(self.data, auto_id=self.auto_id,\n                                            prefix=self.prefix)\n            if not form.is_valid():\n                raise ValidationError('ManagementForm data is missing or has been tampered with')\n        else:\n            form = ConcurrentManagementForm(auto_id=self.auto_id,\n                                            prefix=self.prefix,\n                                            initial={TOTAL_FORM_COUNT: self.total_form_count(),\n                                                     INITIAL_FORM_COUNT: self.initial_form_count(),\n                                                     MAX_NUM_FORM_COUNT: self.max_num},\n                                            versions=[(form.instance.pk, get_revision_of_object(form.instance)) for form\n                                                      in self.initial_forms])\n        return form",
    "docstring": "Returns the ManagementForm instance for this FormSet."
  },
  {
    "code": "def _match_depth(self, sect, depth):\n        while depth < sect.depth:\n            if sect is sect.parent:\n                raise SyntaxError()\n            sect = sect.parent\n        if sect.depth == depth:\n            return sect\n        raise SyntaxError()",
    "docstring": "Given a section and a depth level, walk back through the sections\n        parents to see if the depth level matches a previous section.\n\n        Return a reference to the right section,\n        or raise a SyntaxError."
  },
  {
    "code": "def list_firmware_manifests(self, **kwargs):\n        kwargs = self._verify_sort_options(kwargs)\n        kwargs = self._verify_filters(kwargs, FirmwareManifest, True)\n        api = self._get_api(update_service.DefaultApi)\n        return PaginatedResponse(api.firmware_manifest_list, lwrap_type=FirmwareManifest, **kwargs)",
    "docstring": "List all manifests.\n\n        :param int limit: number of manifests to retrieve\n        :param str order: sort direction of manifests when ordered by time. 'desc' or 'asc'\n        :param str after: get manifests after given `image_id`\n        :param dict filters: Dictionary of filters to apply\n        :return: list of :py:class:`FirmwareManifest` objects\n        :rtype: PaginatedResponse"
  },
  {
    "code": "def _consent_registration(self, consent_args):\n        jws = JWS(json.dumps(consent_args), alg=self.signing_key.alg).sign_compact([self.signing_key])\n        request = \"{}/creq/{}\".format(self.api_url, jws)\n        res = requests.get(request)\n        if res.status_code != 200:\n            raise UnexpectedResponseError(\"Consent service error: %s %s\", res.status_code, res.text)\n        return res.text",
    "docstring": "Register a request at the consent service\n\n        :type consent_args: dict\n        :rtype: str\n\n        :param consent_args: All necessary parameters for the consent request\n        :return: Ticket received from the consent service"
  },
  {
    "code": "def container_exists(self, id=None, name=None):\n        exists = False\n        if id and self.container_by_id(id):\n            exists = True\n        elif name and self.container_by_name(name):\n            exists = True\n        return exists",
    "docstring": "Checks if container exists already"
  },
  {
    "code": "def _load_dataframe(self, resource_name):\n        try:\n            import pandas\n        except ImportError:\n            raise RuntimeError('To enable dataframe support, '\n                               'run \\'pip install datadotworld[pandas]\\'')\n        tabular_resource = self.__tabular_resources[resource_name]\n        field_dtypes = fields_to_dtypes(tabular_resource.descriptor['schema'])\n        try:\n            return pandas.read_csv(\n                path.join(\n                    self.__base_path,\n                    tabular_resource.descriptor['path']),\n                dtype=field_dtypes['other'],\n                parse_dates=list(field_dtypes['dates'].keys()),\n                infer_datetime_format=True)\n        except ValueError as e:\n            warnings.warn(\n                'Unable to set data frame dtypes automatically using {} '\n                'schema. Data types may need to be adjusted manually. '\n                'Error: {}'.format(resource_name, e))\n            return pandas.read_csv(\n                path.join(\n                    self.__base_path,\n                    tabular_resource.descriptor['path']))",
    "docstring": "Build pandas.DataFrame from resource data\n\n        Lazy load any optional dependencies in order to allow users to\n        use package without installing pandas if so they wish.\n\n        :param resource_name:"
  },
  {
    "code": "def _build_query_string(q, default_field=None, default_operator='AND'):\n    def _is_phrase_search(query_string):\n        clean_query = query_string.strip()\n        return clean_query and clean_query.startswith('\"') and clean_query.endswith('\"')\n    def _get_phrase(query_string):\n        return query_string.strip().strip('\"')\n    if _is_phrase_search(q):\n        query = {'match_phrase': {'_all': _get_phrase(q)}}\n    else:\n        query = {'query_string': {'query': q, 'default_operator': default_operator}}\n        query['query_string'].update({'lenient': False} if default_field else {'default_field': default_field})\n    return query",
    "docstring": "Build ``query_string`` object from ``q``.\n\n    :param q: q of type String\n    :param default_field: default_field\n    :return: dictionary object."
  },
  {
    "code": "def _comic_archive_write_zipfile(new_filename, tmp_dir):\n    if Settings.verbose:\n        print('Rezipping archive', end='')\n    with zipfile.ZipFile(new_filename, 'w',\n                         compression=zipfile.ZIP_DEFLATED) as new_zf:\n        root_len = len(os.path.abspath(tmp_dir))\n        for r_d_f in os.walk(tmp_dir):\n            root = r_d_f[0]\n            filenames = r_d_f[2]\n            archive_root = os.path.abspath(root)[root_len:]\n            for fname in filenames:\n                fullpath = os.path.join(root, fname)\n                archive_name = os.path.join(archive_root, fname)\n                if Settings.verbose:\n                    print('.', end='')\n                new_zf.write(fullpath, archive_name, zipfile.ZIP_DEFLATED)",
    "docstring": "Zip up the files in the tempdir into the new filename."
  },
  {
    "code": "def read_transport(self):\n        if ('r' not in self.access_type):\n            raise BTIncompatibleTransportAccessType\n        return self.codec.decode(self.fd, self.read_mtu)",
    "docstring": "Read data from media transport.\n        The returned data payload is SBC decoded and has\n        all RTP encapsulation removed.\n\n        :return data: Payload data that has been decoded,\n            with RTP encapsulation removed.\n        :rtype: array{byte}"
  },
  {
    "code": "def add_options(self, path: str, handler: _WebHandler,\n                    **kwargs: Any) -> AbstractRoute:\n        return self.add_route(hdrs.METH_OPTIONS, path, handler, **kwargs)",
    "docstring": "Shortcut for add_route with method OPTIONS"
  },
  {
    "code": "def build_model_input(cls, name='input'):\n        return cls(name, PortDirection.INPUT, type=PortType.MODEL)",
    "docstring": "Build a model input port.\n\n        :param name: port name\n        :type name: str\n        :return: port object\n        :rtype: PortDef"
  },
  {
    "code": "def format_hsl(hsl_color):\n    hue, saturation, lightness = hsl_color\n    return 'hsl({}, {:.2%}, {:.2%})'.format(hue, saturation, lightness)",
    "docstring": "Format hsl color as css color string."
  },
  {
    "code": "def results(self, Pc):\n        r\n        Psatn = self['pore.invasion_pressure'] <= Pc\n        Tsatn = self['throat.invasion_pressure'] <= Pc\n        inv_phase = {}\n        inv_phase['pore.occupancy'] = sp.array(Psatn, dtype=float)\n        inv_phase['throat.occupancy'] = sp.array(Tsatn, dtype=float)\n        return inv_phase",
    "docstring": "r\"\"\"\n        This method determines which pores and throats are filled with invading\n        phase at the specified capillary pressure, and creates several arrays\n        indicating the occupancy status of each pore and throat for the given\n        pressure.\n\n        Parameters\n        ----------\n        Pc : scalar\n            The capillary pressure for which an invading phase configuration\n            is desired.\n\n        Returns\n        -------\n        A dictionary containing an assortment of data about distribution\n        of the invading phase at the specified capillary pressure.  The data\n        include:\n\n        **'pore.occupancy'** : A value between 0 and 1 indicating the\n        fractional volume of each pore that is invaded.  If no late pore\n        filling model was applied, then this will only be integer values\n        (either filled or not).\n\n        **'throat.occupancy'** : The same as 'pore.occupancy' but for throats.\n\n        This dictionary can be passed directly to the ``update`` method of\n        the *Phase* object. These values can then be accessed by models\n        or algorithms."
  },
  {
    "code": "def downloads_per_day(self):\n        count, num_days = self._downloads_for_num_days(7)\n        res = ceil(count / num_days)\n        logger.debug(\"Downloads per day = (%d / %d) = %d\", count, num_days, res)\n        return res",
    "docstring": "Return the number of downloads per day, averaged over the past 7 days\n        of data.\n\n        :return: average number of downloads per day\n        :rtype: int"
  },
  {
    "code": "def _calculate_weights(self, this_samples, N):\n        this_weights = self.weights.append(N)[:,0]\n        if self.target_values is None:\n            for i in range(N):\n                tmp = self.target(this_samples[i]) - self.proposal.evaluate(this_samples[i])\n                this_weights[i] = _exp(tmp)\n        else:\n            this_target_values = self.target_values.append(N)\n            for i in range(N):\n                this_target_values[i] = self.target(this_samples[i])\n                tmp = this_target_values[i] - self.proposal.evaluate(this_samples[i])\n                this_weights[i] = _exp(tmp)",
    "docstring": "Calculate and save the weights of a run."
  },
  {
    "code": "def load_from_sens_file(self, filename):\n        sens_data = np.loadtxt(filename, skiprows=1)\n        nid_re = self.add_data(sens_data[:, 2])\n        nid_im = self.add_data(sens_data[:, 3])\n        return nid_re, nid_im",
    "docstring": "Load real and imaginary parts from a sens.dat file generated by\n        CRMod\n\n        Parameters\n        ----------\n        filename: string\n            filename of sensitivity file\n\n        Returns\n        -------\n        nid_re: int\n            ID of real part of sensitivities\n        nid_im: int\n            ID of imaginary part of sensitivities"
  },
  {
    "code": "def read_wave(path):\n    with contextlib.closing(wave.open(path, 'rb')) as wf:\n        num_channels = wf.getnchannels()\n        assert num_channels == 1\n        sample_width = wf.getsampwidth()\n        assert sample_width == 2\n        sample_rate = wf.getframerate()\n        assert sample_rate in (8000, 16000, 32000)\n        frames = wf.getnframes()\n        pcm_data = wf.readframes(frames)\n        duration = frames / sample_rate\n        return pcm_data, sample_rate, duration",
    "docstring": "Reads a .wav file.\n\n    Takes the path, and returns (PCM audio data, sample rate)."
  },
  {
    "code": "def _get_jar(self, command, alts=None, allow_missing=False):\n        dirs = []\n        for bdir in [self._gatk_dir, self._picard_ref]:\n            dirs.extend([bdir,\n                         os.path.join(bdir, os.pardir, \"gatk\")])\n        if alts is None: alts = []\n        for check_cmd in [command] + alts:\n            for dir_check in dirs:\n                try:\n                    check_file = config_utils.get_jar(check_cmd, dir_check)\n                    return check_file\n                except ValueError as msg:\n                    if str(msg).find(\"multiple\") > 0:\n                        raise\n                    else:\n                        pass\n        if allow_missing:\n            return None\n        else:\n            raise ValueError(\"Could not find jar %s in %s:%s\" % (command, self._picard_ref, self._gatk_dir))",
    "docstring": "Retrieve the jar for running the specified command."
  },
  {
    "code": "def _drop_schema(self, force_drop=False):\n        connection = connections[get_tenant_database_alias()]\n        has_schema = hasattr(connection, 'schema_name')\n        if has_schema and connection.schema_name not in (self.schema_name, get_public_schema_name()):\n            raise Exception(\"Can't delete tenant outside it's own schema or \"\n                            \"the public schema. Current schema is %s.\"\n                            % connection.schema_name)\n        if has_schema and schema_exists(self.schema_name) and (self.auto_drop_schema or force_drop):\n            self.pre_drop()\n            cursor = connection.cursor()\n            cursor.execute('DROP SCHEMA %s CASCADE' % self.schema_name)",
    "docstring": "Drops the schema"
  },
  {
    "code": "def MarginalBeta(self, i):\n        alpha0 = self.params.sum()\n        alpha = self.params[i]\n        return Beta(alpha, alpha0 - alpha)",
    "docstring": "Computes the marginal distribution of the ith element.\n\n        See http://en.wikipedia.org/wiki/Dirichlet_distribution\n        #Marginal_distributions\n\n        i: int\n\n        Returns: Beta object"
  },
  {
    "code": "def get_jpp_revision(via_command='JPrint'):\n    try:\n        output = subprocess.check_output([via_command, '-v'],\n                                         stderr=subprocess.STDOUT)\n    except subprocess.CalledProcessError as e:\n        if e.returncode == 1:\n            output = e.output\n        else:\n            return None\n    except OSError:\n        return None\n    revision = output.decode().split('\\n')[0].split()[1].strip()\n    return revision",
    "docstring": "Retrieves the Jpp revision number"
  },
  {
    "code": "def histogram(self, name, description, labels=None, **kwargs):\n        return self._track(\n            Histogram,\n            lambda metric, time: metric.observe(time),\n            kwargs, name, description, labels,\n            registry=self.registry\n        )",
    "docstring": "Use a Histogram to track the execution time and invocation count\n        of the method.\n\n        :param name: the name of the metric\n        :param description: the description of the metric\n        :param labels: a dictionary of `{labelname: callable_or_value}` for labels\n        :param kwargs: additional keyword arguments for creating the Histogram"
  },
  {
    "code": "def _matches_location(price, location):\n    if not price.get('locationGroupId'):\n        return True\n    for group in location['location']['location']['priceGroups']:\n        if group['id'] == price['locationGroupId']:\n            return True\n    return False",
    "docstring": "Return True if the price object matches the location."
  },
  {
    "code": "def signup(request):\n    if request.method == 'GET':\n        return render(request, 'user_signup.html', {}, help_text=signup.__doc__)\n    elif request.method == 'POST':\n        if request.user.is_authenticated() and hasattr(request.user, \"userprofile\"):\n            return render_json(request, {\n                'error': _('User already logged in'),\n                'error_type': 'username_logged'\n            }, template='user_json.html', status=400)\n        credentials = json_body(request.body.decode(\"utf-8\"))\n        error = _save_user(request, credentials, new=True)\n        if error is not None:\n            return render_json(request, error, template='user_json.html', status=400)\n        else:\n            auth.login(request, request.user)\n            request.method = \"GET\"\n            return profile(request, status=201)\n    else:\n        return HttpResponseBadRequest(\"method %s is not allowed\".format(request.method))",
    "docstring": "Create a new user with the given credentials.\n\n    GET parameters:\n        html\n            turn on the HTML version of the API\n\n    POST parameters (JSON):\n        username:\n            user's name\n        email:\n            user's e-mail\n        password:\n            user's password\n        password_check:\n            user's password again to check it\n        first_name (optional):\n            user's first name\n        last_name (optional):\n            user's last name"
  },
  {
    "code": "def get_all_eip_addresses(addresses=None, allocation_ids=None, region=None,\n                           key=None, keyid=None, profile=None):\n    return [x.public_ip for x in _get_all_eip_addresses(addresses, allocation_ids, region,\n                key, keyid, profile)]",
    "docstring": "Get public addresses of some, or all EIPs associated with the current account.\n\n    addresses\n        (list) - Optional list of addresses.  If provided, only the addresses\n        associated with those in the list will be returned.\n    allocation_ids\n        (list) - Optional list of allocation IDs.  If provided, only the\n        addresses associated with the given allocation IDs will be returned.\n\n    returns\n        (list) - A list of the requested EIP addresses\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-call boto_ec2.get_all_eip_addresses\n\n    .. versionadded:: 2016.3.0"
  },
  {
    "code": "async def identity_of(client: Client, search: str) -> dict:\n    return await client.get(MODULE + '/identity-of/%s' % search, schema=IDENTITY_OF_SCHEMA)",
    "docstring": "GET Identity data written in the blockchain\n\n    :param client: Client to connect to the api\n    :param search: UID or public key\n    :return:"
  },
  {
    "code": "def list_databases(self, instance, limit=None, marker=None):\n        return instance.list_databases(limit=limit, marker=marker)",
    "docstring": "Returns all databases for the specified instance."
  },
  {
    "code": "def add_properties(entity_proto, property_dict, exclude_from_indexes=None):\n  for name, value in property_dict.iteritems():\n    set_property(entity_proto.properties, name, value, exclude_from_indexes)",
    "docstring": "Add values to the given datastore.Entity proto message.\n\n  Args:\n    entity_proto: datastore.Entity proto message.\n    property_dict: a dictionary from property name to either a python object or\n        datastore.Value.\n    exclude_from_indexes: if the value should be exclude from indexes. None\n        leaves indexing as is (defaults to False if value is not a Value\n        message).\n\n  Usage:\n    >>> add_properties(proto, {'foo': u'a', 'bar': [1, 2]})\n\n  Raises:\n    TypeError: if a given property value type is not supported."
  },
  {
    "code": "def config(self):\n\t\tresponse = self._call(\n\t\t\tmc_calls.Config\n\t\t)\n\t\tconfig_list = response.body.get('data', {}).get('entries', [])\n\t\treturn config_list",
    "docstring": "Get a listing of mobile client configuration settings."
  },
  {
    "code": "def create_class_from_element_tree(target_class, tree, namespace=None,\n                                   tag=None):\n    if namespace is None:\n        namespace = target_class.c_namespace\n    if tag is None:\n        tag = target_class.c_tag\n    if tree.tag == '{%s}%s' % (namespace, tag):\n        target = target_class()\n        target.harvest_element_tree(tree)\n        return target\n    else:\n        return None",
    "docstring": "Instantiates the class and populates members according to the tree.\n\n    Note: Only use this function with classes that have c_namespace and c_tag\n    class members.\n\n    :param target_class: The class which will be instantiated and populated\n        with the contents of the XML.\n    :param tree: An element tree whose contents will be converted into\n        members of the new target_class instance.\n    :param namespace: The namespace which the XML tree's root node must\n        match. If omitted, the namespace defaults to the c_namespace of the\n        target class.\n    :param tag: The tag which the XML tree's root node must match. If\n        omitted, the tag defaults to the c_tag class member of the target\n        class.\n\n    :return: An instance of the target class - or None if the tag and namespace\n        of the XML tree's root node did not match the desired namespace and tag."
  },
  {
    "code": "def get(self, name: str, default: Any = None) -> np.ndarray:\n\t\tif name in self:\n\t\t\treturn self[name]\n\t\telse:\n\t\t\treturn default",
    "docstring": "Return the value for a named attribute if it exists, else default.\n\t\tIf default is not given, it defaults to None, so that this method never raises a KeyError."
  },
  {
    "code": "def list(self, filter=None, type=None, sort=None, limit=None, page=None):\n        schema = PackageSchema(exclude=('testlist', 'extra_cli_args', 'agent_id', 'options', 'note'))\n        resp = self.service.list(self.base, filter, type, sort, limit, page)\n        ps, l = self.service.decode(schema, resp, many=True, links=True)\n        return Page(ps, l)",
    "docstring": "Get a list of packages.\n\n        :param filter: (optional) Filters to apply as a string list.\n        :param type: (optional) `union` or `inter` as string.\n        :param sort: (optional) Sort fields to apply as string list.\n        :param limit: (optional) Limit returned list length.\n        :param page: (optional) Page to return.\n        :return: :class:`packages.Page <packages.Page>` object"
  },
  {
    "code": "def get(self, key, env=None):\n        if env is None:\n            env = self.environment\n        try:\n            ret = self._settings[env][key]\n        except KeyError:\n            ret = None\n        if ret is None:\n            if key == \"identity_class\":\n                env_var = self.env_dct.get(\"identity_type\")\n                ityp = os.environ.get(env_var)\n                if ityp:\n                    return _import_identity(ityp)\n            else:\n                env_var = self.env_dct.get(key)\n            if env_var is not None:\n                ret = os.environ.get(env_var)\n        return ret",
    "docstring": "Returns the config setting for the specified environment. If no\n        environment is specified, the value for the current environment is\n        returned. If an unknown key or environment is passed, None is returned."
  },
  {
    "code": "def decode_argument(self, value: bytes, name: str = None) -> str:\n        try:\n            return _unicode(value)\n        except UnicodeDecodeError:\n            raise HTTPError(\n                400, \"Invalid unicode in %s: %r\" % (name or \"url\", value[:40])\n            )",
    "docstring": "Decodes an argument from the request.\n\n        The argument has been percent-decoded and is now a byte string.\n        By default, this method decodes the argument as utf-8 and returns\n        a unicode string, but this may be overridden in subclasses.\n\n        This method is used as a filter for both `get_argument()` and for\n        values extracted from the url and passed to `get()`/`post()`/etc.\n\n        The name of the argument is provided if known, but may be None\n        (e.g. for unnamed groups in the url regex)."
  },
  {
    "code": "def _find_joliet_record(self, joliet_path):\n        if self.joliet_vd is None:\n            raise pycdlibexception.PyCdlibInternalError('Joliet path requested on non-Joliet ISO')\n        return _find_dr_record_by_name(self.joliet_vd, joliet_path, 'utf-16_be')",
    "docstring": "An internal method to find an directory record on the ISO given a Joliet\n        path.  If the entry is found, it returns the directory record object\n        corresponding to that entry.  If the entry could not be found, a\n        pycdlibexception.PyCdlibInvalidInput is raised.\n\n        Parameters:\n         joliet_path - The Joliet path to lookup.\n        Returns:\n         The directory record entry representing the entry on the ISO."
  },
  {
    "code": "def list_timeline(self, list_id, since_id=None, max_id=None, count=20):\n        statuses = self._client.list_timeline(list_id=list_id, since_id=since_id, max_id=max_id, count=count)\n        return [Tweet(tweet._json) for tweet in statuses]",
    "docstring": "List the tweets of specified list.\n\n        :param list_id: list ID number\n        :param since_id: results will have ID greater than specified ID (more recent than)\n        :param max_id: results will have ID less than specified ID (older than)\n        :param count: number of results per page\n        :return: list of :class:`~responsebot.models.Tweet` objects"
  },
  {
    "code": "def read_bim(file_name):\n    marker_names_chr = None\n    with open(file_name, 'r') as input_file:\n        marker_names_chr = dict([\n            (i[1], encode_chr(i[0]))\n            for i in [\n                j.rstrip(\"\\r\\n\").split(\"\\t\") for j in input_file.readlines()\n            ] if encode_chr(i[0]) in {23, 24}\n        ])\n    return marker_names_chr",
    "docstring": "Reads the BIM file to gather marker names.\n\n    :param file_name: the name of the ``bim`` file.\n\n    :type file_name: str\n\n    :returns: a :py:class:`dict` containing the chromosomal location of each\n              marker on the sexual chromosomes.\n\n    It uses the :py:func:`encode_chr` to encode the chromosomes from ``X`` and\n    ``Y`` to ``23`` and ``24``, respectively."
  },
  {
    "code": "def namespace(self):\n        if self.prefix is None:\n            return self.defaultNamespace()\n        return self.resolvePrefix(self.prefix)",
    "docstring": "Get the element's namespace.\n\n        @return: The element's namespace by resolving the prefix, the explicit\n            namespace or the inherited namespace.\n        @rtype: (I{prefix}, I{name})"
  },
  {
    "code": "def unroll_auth_headers(self, authheaders, exclude_signature=False, sep=\",\", quote=True):\n        res = \"\"\n        ordered = collections.OrderedDict(sorted(authheaders.items()))\n        form = '{0}=\\\"{1}\\\"' if quote else '{0}={1}'\n        if exclude_signature:\n            return sep.join([form.format(k, urlquote(str(v), safe='')) for k, v in ordered.items() if k != 'signature'])\n        else:\n            return sep.join([form.format(k, urlquote(str(v), safe='') if k != 'signature' else str(v)) for k, v in ordered.items()])",
    "docstring": "Converts an authorization header dict-like object into a string representing the authorization.\n\n        Keyword arguments:\n        authheaders -- A string-indexable object which contains the headers appropriate for this signature version."
  },
  {
    "code": "def get_items_of_offer_per_page(self, offer_id, per_page=1000, page=1):\n        return self._get_resource_per_page(\n            resource=OFFER_ITEMS,\n            per_page=per_page,\n            page=page,\n            params={'offer_id': offer_id},\n        )",
    "docstring": "Get items of offer per page\n\n        :param offer_id: the offer id\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :return: list"
  },
  {
    "code": "def peek(init, exposes, debug=False):\n    def _peek(store, container, _stack=None):\n        args = [ store.peek(objname, container, _stack=_stack) \\\n            for objname in exposes ]\n        if debug:\n            print(args)\n        return init(*args)\n    return _peek",
    "docstring": "Default deserializer factory.\n\n    Arguments:\n\n        init (callable): type constructor.\n\n        exposes (iterable): attributes to be peeked and passed to `init`.\n\n    Returns:\n\n        callable: deserializer (`peek` routine)."
  },
  {
    "code": "def _run(name,\n         cmd,\n         exec_driver=None,\n         output=None,\n         stdin=None,\n         python_shell=True,\n         output_loglevel='debug',\n         ignore_retcode=False,\n         use_vt=False,\n         keep_env=None):\n    if exec_driver is None:\n        exec_driver = _get_exec_driver()\n    ret = __salt__['container_resource.run'](\n        name,\n        cmd,\n        container_type=__virtualname__,\n        exec_driver=exec_driver,\n        output=output,\n        stdin=stdin,\n        python_shell=python_shell,\n        output_loglevel=output_loglevel,\n        ignore_retcode=ignore_retcode,\n        use_vt=use_vt,\n        keep_env=keep_env)\n    if output in (None, 'all'):\n        return ret\n    else:\n        return ret[output]",
    "docstring": "Common logic for docker.run functions"
  },
  {
    "code": "def _get_default(self, obj):\n        if self.name in obj._property_values:\n            raise RuntimeError(\"Bokeh internal error, does not handle the case of self.name already in _property_values\")\n        is_themed = obj.themed_values() is not None and self.name in obj.themed_values()\n        default = self.instance_default(obj)\n        if is_themed:\n            unstable_dict = obj._unstable_themed_values\n        else:\n            unstable_dict = obj._unstable_default_values\n        if self.name in unstable_dict:\n            return unstable_dict[self.name]\n        if self.property._may_have_unstable_default():\n            if isinstance(default, PropertyValueContainer):\n                default._register_owner(obj, self)\n            unstable_dict[self.name] = default\n        return default",
    "docstring": "Internal implementation of instance attribute access for default\n        values.\n\n        Handles bookeeping around |PropertyContainer| value, etc."
  },
  {
    "code": "def _pad(input_signal, length, average=10):\n    padded_input_signal = numpy.zeros(length, input_signal.dtype)\n    start_offset = int((len(padded_input_signal) - len(input_signal)) / 2)\n    padded_input_signal[:start_offset] = numpy.average(input_signal[0:average])\n    padded_input_signal[start_offset:(start_offset + len(input_signal))] = input_signal[:]\n    padded_input_signal[(start_offset + len(input_signal)):] = numpy.average(input_signal[-average:])\n    return padded_input_signal",
    "docstring": "Helper function which increases the length of an input signal. The original\n    is inserted at the centre of the new signal and the extra values are set to\n    the average of the first and last parts of the original, respectively.\n\n    :param input_signal: the signal to be padded\n    :param length: the length of the padded signal\n    :param average: the number of points at the beginning/end of the signal\n    which are averaged to calculate the padded value\n    :return:"
  },
  {
    "code": "def delete_collection(mongo_uri, database_name, collection_name):\n    client = pymongo.MongoClient(mongo_uri)\n    db = client[database_name]\n    db.drop_collection(collection_name)",
    "docstring": "Delete a mongo document collection using pymongo. Mongo daemon assumed to be running.\n\n    Inputs: - mongo_uri: A MongoDB URI.\n            - database_name: The mongo database name as a python string.\n            - collection_name: The mongo collection as a python string."
  },
  {
    "code": "def _get_serializer(output):\n    serializers = salt.loader.serializers(__opts__)\n    try:\n        return getattr(serializers, output)\n    except AttributeError:\n        raise CommandExecutionError(\n            \"Unknown serializer '{0}' found for output option\".format(output)\n        )",
    "docstring": "Helper to return known serializer based on\n    pass output argument"
  },
  {
    "code": "def __add_images_to_manifest(self):\n        xpath_expr = \"//manifest:manifest[1]\"\n        for content_tree in self.content_trees:\n            manifest_e = content_tree.xpath(\n                xpath_expr,\n                namespaces=self.namespaces\n            )\n            if not manifest_e:\n                continue\n            for identifier in self.images.keys():\n                lxml.etree.SubElement(\n                    manifest_e[0],\n                    '{%s}file-entry' % self.namespaces['manifest'],\n                    attrib={\n                        '{%s}full-path' % self.namespaces['manifest']: (\n                            PY3O_IMAGE_PREFIX + identifier\n                        ),\n                        '{%s}media-type' % self.namespaces['manifest']: '',\n                    }\n                )",
    "docstring": "Add entries for py3o images into the manifest file."
  },
  {
    "code": "def simpleQuery(self, queryType, rawResults = False, **queryArgs) :\n        return SimpleQuery(self, queryType, rawResults, **queryArgs)",
    "docstring": "General interface for simple queries. queryType can be something like 'all', 'by-example' etc... everything is in the arango doc.\n        If rawResults, the query will return dictionaries instead of Document objetcs."
  },
  {
    "code": "def on_connect(client):\n    print \"++ Opened connection to %s\" % client.addrport()\n    broadcast('%s joins the conversation.\\n' % client.addrport() )\n    CLIENT_LIST.append(client)\n    client.send(\"Welcome to the Chat Server, %s.\\n\" % client.addrport() )",
    "docstring": "Sample on_connect function.\n    Handles new connections."
  },
  {
    "code": "def _speak_header_always_inherit(self, element):\n        self._speak_header_once_inherit(element)\n        cell_elements = self.html_parser.find(element).find_descendants(\n            'td[headers],th[headers]'\n        ).list_results()\n        accessible_display = AccessibleDisplayImplementation(\n            self.html_parser,\n            self.configure\n        )\n        for cell_element in cell_elements:\n            accessible_display.display_cell_header(cell_element)",
    "docstring": "The cells headers will be spoken for every data cell for element and\n        descendants.\n\n        :param element: The element.\n        :type element: hatemile.util.html.htmldomelement.HTMLDOMElement"
  },
  {
    "code": "def get_accounts(self, username=None):\n        url = \"{0}/{1}/accounts\".format(self.domain, self.API_VERSION)\n        params = {\"username\": username}\n        try:\n            return self._Client__call(uri=url, params=params, method=\"get\")\n        except RequestException:\n            return False\n        except AssertionError:\n            return False",
    "docstring": "Get a list of accounts owned by the user.\n\n            Parameters\n            ----------\n            username : string\n                The name of the user. Note: This is only required on the\n                sandbox, on production systems your access token will\n                identify you.\n\n            See more:\n            http://developer.oanda.com/rest-sandbox/accounts/#-a-name-getaccountsforuser-a-get-accounts-for-a-user"
  },
  {
    "code": "def validate_object_action(self, action_name, obj=None):\n        action_method = getattr(self, action_name)\n        if not getattr(action_method, 'detail', False) and action_name not in ('update', 'partial_update', 'destroy'):\n            return\n        validators = getattr(self, action_name + '_validators', [])\n        for validator in validators:\n            validator(obj or self.get_object())",
    "docstring": "Execute validation for actions that are related to particular object"
  },
  {
    "code": "def is_subdir(base_path, test_path, trailing_slash=False, wildcards=False):\n    if trailing_slash:\n        base_path = base_path.rsplit('/', 1)[0] + '/'\n        test_path = test_path.rsplit('/', 1)[0] + '/'\n    else:\n        if not base_path.endswith('/'):\n            base_path += '/'\n        if not test_path.endswith('/'):\n            test_path += '/'\n    if wildcards:\n        return fnmatch.fnmatchcase(test_path, base_path)\n    else:\n        return test_path.startswith(base_path)",
    "docstring": "Return whether the a path is a subpath of another.\n\n    Args:\n        base_path: The base path\n        test_path: The path which we are testing\n        trailing_slash: If True, the trailing slash is treated with importance.\n            For example, ``/images/`` is a directory while ``/images`` is a\n            file.\n        wildcards: If True, globbing wildcards are matched against paths"
  },
  {
    "code": "def deferToGreenletPool(*args, **kwargs):\n    reactor = args[0]\n    pool = args[1]\n    func = args[2]\n    d = defer.Deferred()\n    def task():\n        try:\n            reactor.callFromGreenlet(d.callback, func(*args[3:], **kwargs))\n        except:\n            reactor.callFromGreenlet(d.errback, failure.Failure())\n    pool.add(spawn(task))\n    return d",
    "docstring": "Call function using a greenlet from the given pool and return the result as a Deferred"
  },
  {
    "code": "def remove_children(self, id_):\n        results = self._rls.get_relationships_by_genus_type_for_source(id_, self._relationship_type)\n        if results.available() == 0:\n            raise errors.NotFound()\n        for r in results:\n            self._ras.delete_relationship(r.get_id())",
    "docstring": "Removes all childrenfrom an ``Id``.\n\n        arg:    id (osid.id.Id): the ``Id`` of the node\n        raise:  NotFound - an node identified by the given ``Id`` was\n                not found\n        raise:  NullArgument - ``id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def add_member_to_list(self, username, listname, member_type=\"USER\"):\n        return self.client.service.addMemberToList(\n            listname, username, member_type, self.proxy_id\n        )",
    "docstring": "Add a member to an existing list.\n\n        Args:\n            username (str): The username of the user to add\n            listname (str): The name of the list to add the user to\n            member_type (str): Normally, this should be \"USER\".\n                If you are adding a list as a member of another list,\n                set this to \"LIST\", instead."
  },
  {
    "code": "def bind(self, callback):\n        handlers = self._handlers\n        if self._self is None:\n            raise RuntimeError('%s already fired, cannot add callbacks' % self)\n        if handlers is None:\n            handlers = []\n            self._handlers = handlers\n        handlers.append(callback)",
    "docstring": "Bind a ``callback`` to this event."
  },
  {
    "code": "def applyconfiguration(targets, conf=None, *args, **kwargs):\n    result = []\n    for target in targets:\n        configurables = Configurable.get_annotations(target)\n        if not configurables:\n            configurables = [Configurable()]\n        for configurable in configurables:\n            configuredtargets = configurable.applyconfiguration(\n                targets=[target], conf=conf, *args, **kwargs\n            )\n            result += configuredtargets\n    return result",
    "docstring": "Apply configuration on input targets.\n\n    If targets are not annotated by a Configurable, a new one is instanciated.\n\n    :param Iterable targets: targets to configurate.\n    :param tuple args: applyconfiguration var args.\n    :param dict kwargs: applyconfiguration keywords.\n    :return: configured targets.\n    :rtype: list"
  },
  {
    "code": "def get(self, request, *args, **kwargs):\n        context = self.get_context_data(**kwargs)\n        context.update(self.extra_context)\n        context['crumbs'] = self.get_crumbs()\n        context['title'] = self.title\n        context['suit'] = 'suit' in settings.INSTALLED_APPS\n        if context.get('dashboard_grid', None) is None and self.grid:\n            context['dashboard_grid'] = self.grid\n        return self.render_to_response(context)",
    "docstring": "Django view get function.\n\n        Add items of extra_context, crumbs and grid to context.\n\n        Args:\n            request (): Django's request object.\n            *args (): request args.\n            **kwargs (): request kwargs.\n\n        Returns:\n            response: render to response with context."
  },
  {
    "code": "def from_status(cls, status_line, msg=None):\n        method = getattr(cls, status_line.lower()[4:].replace(' ', '_'))\n        return method(msg)",
    "docstring": "Returns a class method from bottle.HTTPError.status_line attribute.\n        Useful for patching `bottle.HTTPError` for web services.\n\n        Args:\n            status_line (str):  bottle.HTTPError.status_line text.\n            msg: The message data for response.\n\n        Returns:\n            Class method based on status_line arg.\n\n        Examples:\n            >>> status_line = '401 Unauthorized'\n            >>> error_msg = 'Get out!'\n            >>> resp = WSResponse.from_status(status_line, error_msg)\n            >>> resp['errors']\n            ['Get out!']\n            >>> resp['status_text']\n            'Unauthorized'"
  },
  {
    "code": "def cli(env, identifier):\n    mgr = SoftLayer.LoadBalancerManager(env.client)\n    loadbal_id, group_id = loadbal.parse_id(identifier)\n    mgr.reset_service_group(loadbal_id, group_id)\n    env.fout('Load balancer service group connections are being reset!')",
    "docstring": "Reset connections on a certain service group."
  },
  {
    "code": "def _make_pretty_arguments(arguments):\n    if arguments.startswith(\"\\n    Arguments:\"):\n        arguments = \"\\n\".join(map(lambda u: u[6:], arguments.strip().split(\"\\n\")[1:]))\n        return \"**Arguments:**\\n\\n%s\\n\\n\" % arguments",
    "docstring": "Makes the arguments description pretty and returns a formatted string if `arguments`\n    starts with the argument prefix. Otherwise, returns None.\n\n    Expected input:\n\n        Arguments:\n          * arg0 - ...\n              ...\n          * arg0 - ...\n              ...\n\n    Expected output:\n    **Arguments:**\n\n    * arg0 - ...\n        ...\n    * arg0 - ...\n        ..."
  },
  {
    "code": "def score_for_task(properties, category, result):\n    assert result is not None\n    if properties and Property.create_from_names(properties).is_svcomp:\n        return _svcomp_score(category, result)\n    return None",
    "docstring": "Return the possible score of task, depending on whether the result is correct or not."
  },
  {
    "code": "def kakwani(values, ineq_axis, weights = None):\n    from scipy.integrate import simps\n    if weights is None:\n        weights = ones(len(values))\n    PLCx, PLCy = pseudo_lorenz(values, ineq_axis, weights)\n    LCx, LCy = lorenz(ineq_axis, weights)\n    del PLCx\n    return simps((LCy - PLCy), LCx)",
    "docstring": "Computes the Kakwani index"
  },
  {
    "code": "def _fetch_pdb(pdb_code):\n        txt = None\n        url = 'http://www.rcsb.org/pdb/files/%s.pdb' % pdb_code.lower()\n        try:\n            response = urlopen(url)\n            txt = response.read()\n            if sys.version_info[0] >= 3:\n                txt = txt.decode('utf-8')\n            else:\n                txt = txt.encode('ascii')\n        except HTTPError as e:\n            print('HTTP Error %s' % e.code)\n        except URLError as e:\n            print('URL Error %s' % e.args)\n        return url, txt",
    "docstring": "Load PDB file from rcsb.org."
  },
  {
    "code": "def wrap_search(cls, response):\n        games = []\n        json = response.json()\n        gamejsons = json['games']\n        for j in gamejsons:\n            g = cls.wrap_json(j)\n            games.append(g)\n        return games",
    "docstring": "Wrap the response from a game search into instances\n        and return them\n\n        :param response: The response from searching a game\n        :type response: :class:`requests.Response`\n        :returns: the new game instances\n        :rtype: :class:`list` of :class:`Game`\n        :raises: None"
  },
  {
    "code": "def _get_relative_path(self, full_path):\n        try:\n            rel_path = Path(full_path).relative_to(Path().absolute())\n        except ValueError:\n            LOG.error(\"%s: Couldn't find relative path of '%s' from '%s'.\",\n                      self.name, full_path, Path().absolute())\n            return full_path\n        return str(rel_path)",
    "docstring": "Return the relative path from current path."
  },
  {
    "code": "def _config_chooser_dialog(self, title_text, description):\n        dialog = Gtk.Dialog(title_text, self.view[\"preferences_window\"],\n                            flags=0, buttons=\n                            (Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT,\n                             Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT))\n        label = Gtk.Label(label=description)\n        label.set_padding(xpad=10, ypad=10)\n        dialog.vbox.pack_start(label, True, True, 0)\n        label.show()\n        self._gui_checkbox = Gtk.CheckButton(label=\"GUI Config\")\n        dialog.vbox.pack_start(self._gui_checkbox, True, True, 0)\n        self._gui_checkbox.show()\n        self._core_checkbox = Gtk.CheckButton(label=\"Core Config\")\n        self._core_checkbox.show()\n        dialog.vbox.pack_start(self._core_checkbox, True, True, 0)\n        response = dialog.run()\n        dialog.destroy()\n        return response",
    "docstring": "Dialog to select which config shall be exported\n\n        :param title_text: Title text\n        :param description: Description"
  },
  {
    "code": "def add_missing_optional_args_with_value_none(args, optional_args):\n    for name in optional_args:\n        if not name in args.keys():\n            args[name] = None\n    return args",
    "docstring": "Adds key-value pairs to the passed dictionary, so that\n        afterwards, the dictionary can be used without needing\n        to check for KeyErrors.\n\n    If the keys passed as a second argument are not present,\n        they are added with None as a value.\n\n    :args: The dictionary to be completed.\n    :optional_args: The keys that need to be added, if\n        they are not present.\n    :return: The modified dictionary."
  },
  {
    "code": "def bltfrm(frmcls, outCell=None):\n    frmcls = ctypes.c_int(frmcls)\n    if not outCell:\n        outCell = stypes.SPICEINT_CELL(1000)\n    libspice.bltfrm_c(frmcls, outCell)\n    return outCell",
    "docstring": "Return a SPICE set containing the frame IDs of all built-in frames\n    of a specified class.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bltfrm_c.html\n\n    :param frmcls: Frame class.\n    :type frmcls: int\n    :param outCell: Optional SpiceInt Cell that is returned\n    :type outCell: spiceypy.utils.support_types.SpiceCell\n    :return: Set of ID codes of frames of the specified class.\n    :rtype: spiceypy.utils.support_types.SpiceCell"
  },
  {
    "code": "def isrchc(value, ndim, lenvals, array):\n    value = stypes.stringToCharP(value)\n    array = stypes.listToCharArrayPtr(array, xLen=lenvals, yLen=ndim)\n    ndim = ctypes.c_int(ndim)\n    lenvals = ctypes.c_int(lenvals)\n    return libspice.isrchc_c(value, ndim, lenvals, array)",
    "docstring": "Search for a given value within a character string array. Return\n    the index of the first matching array entry, or -1 if the key\n    value was not found.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrchc_c.html\n\n    :param value: Key value to be found in array.\n    :type value: str\n    :param ndim: Dimension of array.\n    :type ndim: int\n    :param lenvals: String length.\n    :type lenvals: int\n    :param array: Character string array to search.\n    :type array: list of str\n    :return:\n            The index of the first matching array element or -1\n            if the value is not found.\n    :rtype: int"
  },
  {
    "code": "def add_text_content_type(application, content_type, default_encoding,\n                          dumps, loads):\n    parsed = headers.parse_content_type(content_type)\n    parsed.parameters.pop('charset', None)\n    normalized = str(parsed)\n    add_transcoder(application,\n                   handlers.TextContentHandler(normalized, dumps, loads,\n                                               default_encoding))",
    "docstring": "Add handler for a text content type.\n\n    :param tornado.web.Application application: the application to modify\n    :param str content_type: the content type to add\n    :param str default_encoding: encoding to use when one is unspecified\n    :param dumps: function that dumps a dictionary to a string.\n        ``dumps(dict, encoding:str) -> str``\n    :param loads: function that loads a dictionary from a string.\n        ``loads(str, encoding:str) -> dict``\n\n    Note that the ``charset`` parameter is stripped from `content_type`\n    if it is present."
  },
  {
    "code": "def match_ref(self, ref):\n        if ref in self.refs:\n            self._matched_ref = ref\n            return True\n        return False",
    "docstring": "Check if the ref matches one the concept's aliases.\n            If so, mark the matched ref so that we use it as the column label."
  },
  {
    "code": "def sparkline_display_value_type(self, sparkline_display_value_type):\n        allowed_values = [\"VALUE\", \"LABEL\"]\n        if sparkline_display_value_type not in allowed_values:\n            raise ValueError(\n                \"Invalid value for `sparkline_display_value_type` ({0}), must be one of {1}\"\n                .format(sparkline_display_value_type, allowed_values)\n            )\n        self._sparkline_display_value_type = sparkline_display_value_type",
    "docstring": "Sets the sparkline_display_value_type of this ChartSettings.\n\n        For the single stat view, whether to display the name of the query or the value of query  # noqa: E501\n\n        :param sparkline_display_value_type: The sparkline_display_value_type of this ChartSettings.  # noqa: E501\n        :type: str"
  },
  {
    "code": "def check_bom(file):\n    lead = file.read(3)\n    if len(lead) == 3 and lead == codecs.BOM_UTF8:\n        return codecs.lookup('utf-8').name\n    elif len(lead) >= 2 and lead[:2] == codecs.BOM_UTF16_BE:\n        if len(lead) == 3:\n            file.seek(-1, os.SEEK_CUR)\n        return codecs.lookup('utf-16-be').name\n    elif len(lead) >= 2 and lead[:2] == codecs.BOM_UTF16_LE:\n        if len(lead) == 3:\n            file.seek(-1, os.SEEK_CUR)\n        return codecs.lookup('utf-16-le').name\n    else:\n        file.seek(-len(lead), os.SEEK_CUR)\n        return None",
    "docstring": "Determines file codec from from its BOM record.\n\n    If file starts with BOM record encoded with UTF-8 or UTF-16(BE/LE)\n    then corresponding encoding name is returned, otherwise None is returned.\n    In both cases file current position is set to after-BOM bytes. The file\n    must be open in binary mode and positioned at offset 0."
  },
  {
    "code": "def is_block_device(self):\n        try:\n            return S_ISBLK(self.stat().st_mode)\n        except OSError as e:\n            if e.errno != ENOENT:\n                raise\n            return False",
    "docstring": "Whether this path is a block device."
  },
  {
    "code": "def _get_loader(config):\n    if config.endswith('.yml') or config.endswith('.yaml'):\n        if not yaml:\n            LOGGER.error(\"pyyaml must be installed to use the YAML loader\")\n            return None, None\n        return 'yaml', yaml.load\n    else:\n        return 'json', json.loads",
    "docstring": "Determine which config file type and loader to use based on a filename.\n\n    :param config str: filename to config file\n    :return: a tuple of the loader type and callable to load\n    :rtype: (str, Callable)"
  },
  {
    "code": "def _free_sequence(tmp1, tmp2=False):\n    if not tmp1 and not tmp2:\n        return []\n    output = []\n    if tmp1 and tmp2:\n        output.append('pop de')\n        output.append('ex (sp), hl')\n        output.append('push de')\n        output.append('call __MEM_FREE')\n        output.append('pop hl')\n        output.append('call __MEM_FREE')\n    else:\n        output.append('ex (sp), hl')\n        output.append('call __MEM_FREE')\n    output.append('pop hl')\n    REQUIRES.add('alloc.asm')\n    return output",
    "docstring": "Outputs a FREEMEM sequence for 1 or 2 ops"
  },
  {
    "code": "def update_from_object(self, obj, criterion=lambda key: key.isupper()):\n        log.debug('Loading config from {0}'.format(obj))\n        if isinstance(obj, basestring):\n            if '.' in obj:\n                path, name = obj.rsplit('.', 1)\n                mod = __import__(path, globals(), locals(), [name], 0)\n                obj = getattr(mod, name)\n            else:\n                obj = __import__(obj, globals(), locals(), [], 0)\n        self.update(\n            (key, getattr(obj, key))\n            for key in filter(criterion, dir(obj))\n        )",
    "docstring": "Update dict from the attributes of a module, class or other object.\n\n        By default only attributes with all-uppercase names will be retrieved.\n        Use the ``criterion`` argument to modify that behaviour.\n\n        :arg obj: Either the actual module/object, or its absolute name, e.g.\n            'my_app.settings'.\n\n        :arg criterion: Callable that must return True when passed the name\n            of an attribute, if that attribute is to be used.\n        :type criterion: :py:class:`function`\n\n        .. versionadded:: 1.0"
  },
  {
    "code": "def numeric_columns(self, include_bool=True):\n        columns = []\n        for col, dtype in zip(self.columns, self.dtypes):\n            if is_numeric_dtype(dtype) and (\n                include_bool or (not include_bool and dtype != np.bool_)\n            ):\n                columns.append(col)\n        return columns",
    "docstring": "Returns the numeric columns of the Manager.\n\n        Returns:\n            List of index names."
  },
  {
    "code": "def build_funcs(modules):\n        kernel32 = ['kernel32_']\n        try:\n            kernel32 += remove_dups(modules['kernel32'])\n        except KeyError:\n            if len(modules) and 'LoadLibraryA' not in kernel32:\n                kernel32.insert(1, 'LoadLibraryA')\n        if len(modules) > 1 and 'LoadLibraryA' not in kernel32:\n            kernel32.insert(1, 'LoadLibraryA')\n        if 'GetProcAddress' not in kernel32:\n            kernel32.insert(1, 'GetProcAddress')\n        logging.debug('kernel32: %s', kernel32)\n        for module, funcs in modules.items():\n            logging.debug('%s: %s', module, funcs)\n            if module != 'kernel32':\n                kernel32.extend([module + '_'] + remove_dups(funcs))\n        return kernel32",
    "docstring": "Build a used functions and modules list\n        for later consumption."
  },
  {
    "code": "def volume(self):\n        volume = float(np.product(self.primitive.extents))\n        return volume",
    "docstring": "Volume of the box Primitive.\n\n        Returns\n        --------\n        volume: float, volume of box"
  },
  {
    "code": "def com_google_fonts_check_family_underline_thickness(ttFonts):\n  underTs = {}\n  underlineThickness = None\n  failed = False\n  for ttfont in ttFonts:\n    fontname = ttfont.reader.file.name\n    ut = ttfont['post'].underlineThickness\n    underTs[fontname] = ut\n    if underlineThickness is None:\n      underlineThickness = ut\n    if ut != underlineThickness:\n      failed = True\n  if failed:\n    msg = (\"Thickness of the underline is not\"\n           \" the same accross this family. In order to fix this,\"\n           \" please make sure that the underlineThickness value\"\n           \" is the same in the 'post' table of all of this family\"\n           \" font files.\\n\"\n           \"Detected underlineThickness values are:\\n\")\n    for style in underTs.keys():\n      msg += \"\\t{}: {}\\n\".format(style, underTs[style])\n    yield FAIL, msg\n  else:\n    yield PASS, \"Fonts have consistent underline thickness.\"",
    "docstring": "Fonts have consistent underline thickness?"
  },
  {
    "code": "def as_odict(self):\r\n        if hasattr(self, 'cust_odict'):\r\n            return self.cust_odict\r\n        if hasattr(self, 'attr_check'):\r\n            self.attr_check()\r\n        odc = odict()\r\n        for attr in self.attrorder:\r\n            odc[attr] = getattr(self, attr)\r\n        return odc",
    "docstring": "returns an odict version of the object, based on it's attributes"
  },
  {
    "code": "def nl_socket_modify_cb(sk, type_, kind, func, arg):\n    return int(nl_cb_set(sk.s_cb, type_, kind, func, arg))",
    "docstring": "Modify the callback handler associated with the socket.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L633\n\n    Sets specific callback functions in the existing nl_cb class instance stored in the nl_sock socket.\n\n    Positional arguments:\n    sk -- Netlink socket (nl_sock class instance).\n    type_ -- which type callback to set (integer).\n    kind -- kind of callback (integer).\n    func -- callback function.\n    arg -- argument to be passed to callback function.\n\n    Returns:\n    0 on success or a negative error code."
  },
  {
    "code": "def load_checkers():\n    for loader, name, _ in pkgutil.iter_modules([os.path.join(__path__[0], 'checkers')]):\n        loader.find_module(name).load_module(name)",
    "docstring": "Load the checkers"
  },
  {
    "code": "async def _analog_message(self, data):\n        pin = data[0]\n        value = (data[PrivateConstants.MSB] << 7) + data[PrivateConstants.LSB]\n        self.analog_pins[pin].current_value = value\n        message = [pin, value, Constants.ANALOG]\n        if self.analog_pins[pin].cb:\n            if self.analog_pins[pin].cb_type:\n                await self.analog_pins[pin].cb(message)\n            else:\n                loop = self.loop\n                loop.call_soon(self.analog_pins[pin].cb, message)\n        key = 'A' + str(pin)\n        if key in self.latch_map:\n            await self._check_latch_data(key, message[1])",
    "docstring": "This is a private message handler method.\n        It is a message handler for analog messages.\n\n        :param data: message data\n\n        :returns: None - but saves the data in the pins structure"
  },
  {
    "code": "def moderate(self, comment, entry, request):\n        if self.auto_moderate_comments:\n            return True\n        if check_is_spam(comment, entry, request,\n                         self.spam_checker_backends):\n            return True\n        return False",
    "docstring": "Determine if a new comment should be marked as non-public\n        and await approval.\n        Return ``True`` to put the comment into the moderator queue,\n        or ``False`` to allow it to be showed up immediately."
  },
  {
    "code": "def _sign_simple_signature_fulfillment(cls, input_, message, key_pairs):\n        input_ = deepcopy(input_)\n        public_key = input_.owners_before[0]\n        message = sha3_256(message.encode())\n        if input_.fulfills:\n            message.update('{}{}'.format(\n                input_.fulfills.txid, input_.fulfills.output).encode())\n        try:\n            input_.fulfillment.sign(\n                message.digest(), base58.b58decode(key_pairs[public_key].encode()))\n        except KeyError:\n            raise KeypairMismatchException('Public key {} is not a pair to '\n                                           'any of the private keys'\n                                           .format(public_key))\n        return input_",
    "docstring": "Signs a Ed25519Fulfillment.\n\n            Args:\n                input_ (:class:`~bigchaindb.common.transaction.\n                    Input`) The input to be signed.\n                message (str): The message to be signed\n                key_pairs (dict): The keys to sign the Transaction with."
  },
  {
    "code": "def run_parallel_with_display(wf, n_threads, display):\n    LogQ = Queue()\n    S = Scheduler(error_handler=display.error_handler)\n    threading.Thread(\n        target=patch,\n        args=(LogQ.source, sink_map(display)),\n        daemon=True).start()\n    W = Queue() \\\n        >> branch(log_job_start >> LogQ.sink) \\\n        >> thread_pool(*repeat(worker, n_threads)) \\\n        >> branch(LogQ.sink)\n    result = S.run(W, get_workflow(wf))\n    LogQ.wait()\n    return result",
    "docstring": "Adds a display to the parallel runner. Because messages come in\n    asynchronously now, we start an extra thread just for the display\n    routine."
  },
  {
    "code": "async def expn(\n        self, address: str, timeout: DefaultNumType = _default\n    ) -> SMTPResponse:\n        await self._ehlo_or_helo_if_needed()\n        parsed_address = parse_address(address)\n        async with self._command_lock:\n            response = await self.execute_command(\n                b\"EXPN\", parsed_address.encode(\"ascii\"), timeout=timeout\n            )\n        if response.code != SMTPStatus.completed:\n            raise SMTPResponseException(response.code, response.message)\n        return response",
    "docstring": "Send an SMTP EXPN command, which expands a mailing list.\n        Not many servers support this command.\n\n        :raises SMTPResponseException: on unexpected server response code"
  },
  {
    "code": "def calc_A_hat(A, S):\n    return np.dot(S, np.dot(A, np.transpose(S)))",
    "docstring": "Return the A_hat matrix of A given the skew matrix S"
  },
  {
    "code": "def check_corrupted_files_cmd(java_home, files):\n    files_str = \",\".join(files)\n    check_command = CHECK_COMMAND.format(\n        ionice=IONICE,\n        java_home=java_home,\n        files=files_str,\n    )\n    command = \"{check_command} | {reduce_output}\".format(\n        check_command=check_command,\n        reduce_output=REDUCE_OUTPUT,\n    )\n    return command",
    "docstring": "Check the file corruption of the specified files.\n\n    :param java_home: the JAVA_HOME\n    :type java_home: string\n    :param files: list of files to be checked\n    :type files: list of string"
  },
  {
    "code": "def get_exception(self):\n        with self.__lock:\n            return (\n                self.__updateexception\n                if self.__updateexception or self.__closed\n                else self.__exportref.get_exception()\n            )",
    "docstring": "Returns the exception associated to the export\n\n        :return: An exception tuple, if any"
  },
  {
    "code": "def absent(\n        name,\n        region,\n        user=None,\n        opts=False):\n    ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n    does_exist = __salt__['aws_sqs.queue_exists'](name, region, opts, user)\n    if does_exist:\n        if __opts__['test']:\n            ret['result'] = None\n            ret['comment'] = 'AWS SQS queue {0} is set to be removed'.format(\n                    name)\n            return ret\n        removed = __salt__['aws_sqs.delete_queue'](name, region, opts, user)\n        if removed['retcode'] == 0:\n            ret['changes']['removed'] = removed['stdout']\n        else:\n            ret['result'] = False\n            ret['comment'] = removed['stderr']\n    else:\n        ret['comment'] = '{0} does not exist in {1}'.format(name, region)\n    return ret",
    "docstring": "Remove the named SQS queue if it exists.\n\n    name\n        Name of the SQS queue.\n\n    region\n        Region to remove the queue from\n\n    user\n        Name of the user performing the SQS operations\n\n    opts\n        Include additional arguments and options to the aws command line"
  },
  {
    "code": "def wrap_paths(paths):\n    if isinstance(paths, string_types):\n        raise ValueError(\n            \"paths cannot be a string. \"\n            \"Use array with one element instead.\"\n        )\n    return ' '.join('\"' + path + '\"' for path in paths)",
    "docstring": "Put quotes around all paths and join them with space in-between."
  },
  {
    "code": "def kick_jobs(self, num_jobs):\n        with self._sock_ctx() as socket:\n            self._send_message('kick {0}'.format(num_jobs), socket)\n            return self._receive_id(socket)",
    "docstring": "Kick some number of jobs from the buried queue onto the ready queue.\n\n        :param num_jobs: Number of jobs to kick\n        :type num_jobs: int\n\n        If not that many jobs are in the buried queue, it will kick as many as it can."
  },
  {
    "code": "def disconnect_all(self):\n        with self._mutex:\n            for conn in self.connections:\n                self.object.disconnect(conn.id)\n            self.reparse_connections()",
    "docstring": "Disconnect all connections to this port."
  },
  {
    "code": "def salt_extend(extension, name, description, salt_dir, merge):\n    import salt.utils.extend\n    salt.utils.extend.run(extension=extension,\n                          name=name,\n                          description=description,\n                          salt_dir=salt_dir,\n                          merge=merge)",
    "docstring": "Quickstart for developing on the saltstack installation\n\n    .. versionadded:: 2016.11.0"
  },
  {
    "code": "def room_members(self, stream_id):\n        req_hook = 'pod/v2/room/' + str(stream_id) + '/membership/list'\n        req_args = None\n        status_code, response = self.__rest__.GET_query(req_hook, req_args)\n        self.logger.debug('%s: %s' % (status_code, response))\n        return status_code, response",
    "docstring": "get list of room members"
  },
  {
    "code": "def cancel(self):\n        if self.OBSERVE_UPDATES:\n            self.detach()\n        self.ioloop.add_callback(self.cancel_timeouts)",
    "docstring": "Detach strategy from its sensor and cancel ioloop callbacks."
  },
  {
    "code": "def calc_mean_time_deviation(timepoints, weights, mean_time=None):\n    timepoints = numpy.array(timepoints)\n    weights = numpy.array(weights)\n    validtools.test_equal_shape(timepoints=timepoints, weights=weights)\n    validtools.test_non_negative(weights=weights)\n    if mean_time is None:\n        mean_time = calc_mean_time(timepoints, weights)\n    return (numpy.sqrt(numpy.dot(weights, (timepoints-mean_time)**2) /\n                       numpy.sum(weights)))",
    "docstring": "Return the weighted deviation of the given timepoints from their mean\n    time.\n\n    With equal given weights, the is simply the standard deviation of the\n    given time points:\n\n    >>> from hydpy import calc_mean_time_deviation\n    >>> calc_mean_time_deviation(timepoints=[3., 7.],\n    ...                          weights=[2., 2.])\n    2.0\n\n    One can pass a precalculated or alternate mean time:\n\n    >>> from hydpy import round_\n    >>> round_(calc_mean_time_deviation(timepoints=[3., 7.],\n    ...                                 weights=[2., 2.],\n    ...                                 mean_time=4.))\n    2.236068\n\n    >>> round_(calc_mean_time_deviation(timepoints=[3., 7.],\n    ...                                 weights=[1., 3.]))\n    1.732051\n\n    Or, in the most extreme case:\n\n    >>> calc_mean_time_deviation(timepoints=[3., 7.],\n    ...                          weights=[0., 4.])\n    0.0\n\n    There will be some checks for input plausibility perfomed, e.g.:\n\n    >>> calc_mean_time_deviation(timepoints=[3., 7.],\n    ...                          weights=[-2., 2.])\n    Traceback (most recent call last):\n    ...\n    ValueError: While trying to calculate the weighted time deviation \\\nfrom mean time, the following error occurred: For the following objects, \\\nat least one value is negative: weights."
  },
  {
    "code": "def get_extra_keywords(self):\n        extra_keywords = {}\n        for key, widgets in list(self.widgets_dict.items()):\n            if widgets[0].isChecked():\n                if isinstance(widgets[1], QLineEdit):\n                    extra_keywords[key] = widgets[1].text()\n                elif isinstance(widgets[1], QComboBox):\n                    current_index = widgets[1].currentIndex()\n                    extra_keywords[key] = widgets[1].itemData(current_index)\n                elif isinstance(widgets[1], (QDoubleSpinBox, QSpinBox)):\n                    extra_keywords[key] = widgets[1].value()\n                elif isinstance(widgets[1], QDateTimeEdit):\n                    extra_keywords[key] = widgets[1].dateTime().toString(\n                        Qt.ISODate)\n        return extra_keywords",
    "docstring": "Obtain extra keywords from the current state."
  },
  {
    "code": "def _select_broker_pair(self, rg_destination, victim_partition):\n        broker_source = self._elect_source_broker(victim_partition)\n        broker_destination = rg_destination._elect_dest_broker(victim_partition)\n        return broker_source, broker_destination",
    "docstring": "Select best-fit source and destination brokers based on partition\n        count and presence of partition over the broker.\n\n        * Get overloaded and underloaded brokers\n        Best-fit Selection Criteria:\n        Source broker: Select broker containing the victim-partition with\n        maximum partitions.\n        Destination broker: NOT containing the victim-partition with minimum\n        partitions. If no such broker found, return first broker.\n\n        This helps in ensuring:-\n        * Topic-partitions are distributed across brokers.\n        * Partition-count is balanced across replication-groups."
  },
  {
    "code": "def get_revision():\n    proc = Process(\"git log\", [\"git\", \"log\", \"-1\"])\n    try:\n        while True:\n            line = proc.stdout.pop().strip().decode('utf8')\n            if not line:\n                continue\n            if line.startswith(\"commit \"):\n                return line[7:]\n    finally:\n        with suppress_exception:\n            proc.join()",
    "docstring": "GET THE CURRENT GIT REVISION"
  },
  {
    "code": "def get_collection(self, path, query, **options):\n        options = self._merge_options(options)\n        if options['iterator_type'] == 'items':\n            return CollectionPageIterator(self, path, query, options).items()\n        if options['iterator_type'] is None:\n            return self.get(path, query, **options)\n        raise Exception('Unknown value for \"iterator_type\" option: {}'.format(\n            str(options['iterator_type'])))",
    "docstring": "Get a collection from a collection endpoint.\n\n        Parses GET request options for a collection endpoint and dispatches a\n        request."
  },
  {
    "code": "def getValidCertifications(self):\n        certs = []\n        today = date.today()\n        for c in self.getCertifications():\n            validfrom = c.getValidFrom() if c else None\n            validto = c.getValidTo() if validfrom else None\n            if not validfrom or not validto:\n                continue\n            validfrom = validfrom.asdatetime().date()\n            validto = validto.asdatetime().date()\n            if (today >= validfrom and today <= validto):\n                certs.append(c)\n        return certs",
    "docstring": "Returns the certifications fully valid"
  },
  {
    "code": "def page(\n    request,\n    slug,\n    rev_id=None,\n    template_name='wakawaka/page.html',\n    extra_context=None,\n):\n    try:\n        queryset = WikiPage.objects.all()\n        page = queryset.get(slug=slug)\n        rev = page.current\n        if rev_id:\n            revision_queryset = Revision.objects.all()\n            rev_specific = revision_queryset.get(pk=rev_id)\n            if rev.pk != rev_specific.pk:\n                rev_specific.is_not_current = True\n            rev = rev_specific\n    except WikiPage.DoesNotExist:\n        if request.user.is_authenticated:\n            kwargs = {'slug': slug}\n            redirect_to = reverse('wakawaka_edit', kwargs=kwargs)\n            return HttpResponseRedirect(redirect_to)\n        raise Http404\n    template_context = {'page': page, 'rev': rev}\n    template_context.update(extra_context or {})\n    return render(request, template_name, template_context)",
    "docstring": "Displays a wiki page. Redirects to the edit view if the page doesn't exist."
  },
  {
    "code": "def check_vprint(s, vprinter):\n    if vprinter is True:\n        print(s);\n    elif callable(vprinter):\n        vprinter(s);",
    "docstring": "checked verbose printing"
  },
  {
    "code": "def build_frame(command, payload):\n        packet_length = 2 + len(payload) + 1\n        ret = struct.pack(\"BB\", 0, packet_length)\n        ret += struct.pack(\">H\", command.value)\n        ret += payload\n        ret += struct.pack(\"B\", calc_crc(ret))\n        return ret",
    "docstring": "Build raw bytes from command and payload."
  },
  {
    "code": "def get(self, name=None):\n        if name is None:\n            return self._classes\n        else:\n            if name not in self._classes.keys():\n                return None\n            else:\n                return self._classes[name]",
    "docstring": "Returns the plugin class object with the given name.\n        Or if a name is not given, the complete plugin dictionary is returned.\n\n        :param name: Name of a plugin\n        :return: None, single plugin or dictionary of plugins"
  },
  {
    "code": "def deps_status(self):\n        if not self.deps:\n            return [self.S_OK]\n        return [d.status for d in self.deps]",
    "docstring": "Returns a list with the status of the dependencies."
  },
  {
    "code": "def reset_stream(stream):\n    try:\n        position = stream.tell()\n    except Exception:\n        position = True\n    if position != 0:\n        try:\n            stream.seek(0)\n        except Exception:\n            message = 'It\\'s not possible to reset this stream'\n            raise exceptions.TabulatorException(message)",
    "docstring": "Reset stream pointer to the first element.\n\n    If stream is not seekable raise Exception."
  },
  {
    "code": "def com_google_fonts_check_smart_dropout(ttFont):\n  INSTRUCTIONS = b\"\\xb8\\x01\\xff\\x85\\xb0\\x04\\x8d\"\n  if (\"prep\" in ttFont and\n      INSTRUCTIONS in ttFont[\"prep\"].program.getBytecode()):\n    yield PASS, (\"'prep' table contains instructions\"\n                  \" enabling smart dropout control.\")\n  else:\n    yield FAIL, (\"'prep' table does not contain TrueType \"\n                  \" instructions enabling smart dropout control.\"\n                  \" To fix, export the font with autohinting enabled,\"\n                  \" or run ttfautohint on the font, or run the \"\n                  \" `gftools fix-nonhinting` script.\")",
    "docstring": "Font enables smart dropout control in \"prep\" table instructions?\n\n  B8 01 FF    PUSHW 0x01FF\n  85          SCANCTRL (unconditinally turn on\n                        dropout control mode)\n  B0 04       PUSHB 0x04\n  8D          SCANTYPE (enable smart dropout control)\n\n  Smart dropout control means activating rules 1, 2 and 5:\n  Rule 1: If a pixel's center falls within the glyph outline,\n          that pixel is turned on.\n  Rule 2: If a contour falls exactly on a pixel's center,\n          that pixel is turned on.\n  Rule 5: If a scan line between two adjacent pixel centers\n          (either vertical or horizontal) is intersected\n          by both an on-Transition contour and an off-Transition\n          contour and neither of the pixels was already turned on\n          by rules 1 and 2, turn on the pixel which is closer to\n          the midpoint between the on-Transition contour and\n          off-Transition contour. This is \"Smart\" dropout control."
  },
  {
    "code": "def auto_convert_cell_no_flags(cell, units=None, parens_as_neg=True):\n    units = units if units != None else {}\n    return auto_convert_cell(flagable=Flagable(), cell=cell, position=None, worksheet=0,\n                             flags={}, units=units, parens_as_neg=parens_as_neg)",
    "docstring": "Performs a first step conversion of the cell to check\n    it's type or try to convert if a valid conversion exists.\n    This version of conversion doesn't flag changes nor store\n    cell units.\n\n    Args:\n        units: The dictionary holder for cell units.\n        parens_as_neg: Converts numerics surrounded by parens to\n            negative values"
  },
  {
    "code": "def delete_ace(self, domain=None, user=None, sid=None):\n        if sid is None:\n            if domain is None:\n                domain = self.cifs_server.domain\n            sid = UnityAclUser.get_sid(self._cli, user=user, domain=domain)\n        if isinstance(sid, six.string_types):\n            sid = [sid]\n        ace_list = [self._make_remove_ace_entry(s) for s in sid]\n        resp = self.action(\"setACEs\", cifsShareACEs=ace_list)\n        resp.raise_if_err()\n        return resp",
    "docstring": "delete ACE for the share\n\n        delete ACE for the share.  User could either supply the domain and\n        username or the sid of the user.\n\n        :param domain: domain of the user\n        :param user: username\n        :param sid: sid of the user or sid list of the user\n        :return: REST API response"
  },
  {
    "code": "def segment_file(self, value):\n        assert os.path.isfile(value), \"%s is not a valid file\" % value\n        self._segment_file = value",
    "docstring": "Setter for _segment_file attribute"
  },
  {
    "code": "def ask_user_for_telemetry():\n    answer = \" \"\n    while answer.lower() != 'yes' and answer.lower() != 'no':\n        answer = prompt(u'\\nDo you agree to sending telemetry (yes/no)? Default answer is yes: ')\n        if answer == '':\n            answer = 'yes'\n    return answer",
    "docstring": "asks the user for if we can collect telemetry"
  },
  {
    "code": "def user_agent_info(sdk_version, custom_user_agent):\n    python_version = \".\".join(str(x) for x in sys.version_info[0:3])\n    user_agent = \"ask-python/{} Python/{}\".format(\n        sdk_version, python_version)\n    if custom_user_agent is None:\n        return user_agent\n    else:\n        return user_agent + \" {}\".format(custom_user_agent)",
    "docstring": "Return the user agent info along with the SDK and Python\n    Version information.\n\n    :param sdk_version: Version of the SDK being used.\n    :type sdk_version: str\n    :param custom_user_agent: Custom User Agent string provided by\n        the developer.\n    :type custom_user_agent: str\n    :return: User Agent Info string\n    :rtype: str"
  },
  {
    "code": "def create(self, data, *args, **kwargs):\n        super(MambuUser, self).create(data)\n        self['user'][self.customFieldName] = self['customInformation']\n        self.init(attrs=self['user'])",
    "docstring": "Creates an user in Mambu\n\n        Parameters\n        -data       dictionary with data to send"
  },
  {
    "code": "def importPuppetClasses(self, smartProxyId):\n        return self.api.create('{}/{}/import_puppetclasses'\n                               .format(self.objName, smartProxyId), '{}')",
    "docstring": "Function importPuppetClasses\n        Force the reload of puppet classes\n\n        @param smartProxyId: smartProxy Id\n        @return RETURN: the API result"
  },
  {
    "code": "def formatMessageForBuildResults(self, mode, buildername, buildset, build, master, previous_results, blamelist):\n        ss_list = buildset['sourcestamps']\n        results = build['results']\n        ctx = dict(results=build['results'],\n                   mode=mode,\n                   buildername=buildername,\n                   workername=build['properties'].get(\n                       'workername', [\"<unknown>\"])[0],\n                   buildset=buildset,\n                   build=build,\n                   projects=self.getProjects(ss_list, master),\n                   previous_results=previous_results,\n                   status_detected=self.getDetectedStatus(\n                       mode, results, previous_results),\n                   build_url=utils.getURLForBuild(\n                       master, build['builder']['builderid'], build['number']),\n                   buildbot_url=master.config.buildbotURL,\n                   blamelist=blamelist,\n                   summary=self.messageSummary(build, results),\n                   sourcestamps=self.messageSourceStamps(ss_list)\n                   )\n        yield self.buildAdditionalContext(master, ctx)\n        msgdict = self.renderMessage(ctx)\n        return msgdict",
    "docstring": "Generate a buildbot mail message and return a dictionary\n           containing the message body, type and subject."
  },
  {
    "code": "def open_file(filename, as_text=False):\n    if filename.lower().endswith('.gz'):\n        if as_text:\n            return gzip.open(filename, 'rt')\n        else:\n            return gzip.open(filename, 'rb')\n    else:\n        if as_text:\n            return open(filename, 'rt')\n        else:\n            return open(filename, 'rb')",
    "docstring": "Open the file gunzipping it if it ends with .gz.\n    If as_text the file is opened in text mode,\n    otherwise the file's opened in binary mode."
  },
  {
    "code": "def add_cmd_output(self, cmds, suggest_filename=None,\n                       root_symlink=None, timeout=300, stderr=True,\n                       chroot=True, runat=None, env=None, binary=False,\n                       sizelimit=None, pred=None):\n        if isinstance(cmds, six.string_types):\n            cmds = [cmds]\n        if len(cmds) > 1 and (suggest_filename or root_symlink):\n            self._log_warn(\"ambiguous filename or symlink for command list\")\n        if sizelimit is None:\n            sizelimit = self.get_option(\"log_size\")\n        for cmd in cmds:\n            self._add_cmd_output(cmd, suggest_filename=suggest_filename,\n                                 root_symlink=root_symlink, timeout=timeout,\n                                 stderr=stderr, chroot=chroot, runat=runat,\n                                 env=env, binary=binary, sizelimit=sizelimit,\n                                 pred=pred)",
    "docstring": "Run a program or a list of programs and collect the output"
  },
  {
    "code": "def resource_associate_permission(self, token, id, name, scopes, **kwargs):\n        return self._realm.client.post(\n            '{}/{}'.format(self.well_known['policy_endpoint'], id),\n            data=self._get_data(name=name, scopes=scopes, **kwargs),\n            headers=self.get_headers(token)\n        )",
    "docstring": "Associates a permission with a Resource.\n\n        https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_authorization_uma_policy_api\n\n        :param str token: client access token\n        :param str id: resource id\n        :param str name: permission name\n        :param list scopes: scopes access is wanted\n        :param str description:optional\n        :param list roles: (optional)\n        :param list groups: (optional)\n        :param list clients: (optional)\n        :param str condition: (optional)\n        :rtype: dict"
  },
  {
    "code": "def watch(args):\n    \" Watch directory for changes and auto pack sources \"\n    assert op.isdir(args.source), \"Watch mode allowed only for directories.\"\n    print 'Zeta-library v. %s watch mode' % VERSION\n    print '================================'\n    print 'Ctrl+C for exit\\n'\n    observer = Observer()\n    handler = ZetaTrick(args=args)\n    observer.schedule(handler, args.source, recursive=True)\n    observer.start()\n    try:\n        while True:\n            time.sleep(1)\n    except KeyboardInterrupt:\n        observer.stop()\n        print \"\\nWatch mode stoped.\"\n    observer.join()",
    "docstring": "Watch directory for changes and auto pack sources"
  },
  {
    "code": "def render_category(slug):\n    try:\n        category = EntryCategory.objects.get(slug=slug)\n    except EntryCategory.DoesNotExist:\n        pass\n    else:\n        return {'category': category}\n    return {}",
    "docstring": "Template tag to render a category with all it's entries."
  },
  {
    "code": "def factory(type, module=None, **kwargs):\n    cls = type\n    if module is None: module = __name__\n    fn = lambda member: inspect.isclass(member) and member.__module__==module\n    classes = odict(inspect.getmembers(sys.modules[module], fn))\n    members = odict([(k.lower(),v) for k,v in classes.items()])\n    lower = cls.lower()\n    if lower not in list(members.keys()):\n        msg = \"Unrecognized class: %s.%s\"%(module,cls)\n        raise KeyError(msg)\n    return members[lower](**kwargs)",
    "docstring": "Factory for creating objects. Arguments are passed directly to the\n    constructor of the chosen class."
  },
  {
    "code": "def decode_network_packet(buf):\n    off = 0\n    blen = len(buf)\n    while off < blen:\n        ptype, plen = header.unpack_from(buf, off)\n        if plen > blen - off:\n            raise ValueError(\"Packet longer than amount of data in buffer\")\n        if ptype not in _decoders:\n            raise ValueError(\"Message type %i not recognized\" % ptype)\n        yield ptype, _decoders[ptype](ptype, plen, buf[off:])\n        off += plen",
    "docstring": "Decodes a network packet in collectd format."
  },
  {
    "code": "def print_new(ctx, name, migration_type):\n    click.echo(ctx.obj.repository.generate_migration_name(name, migration_type))",
    "docstring": "Prints filename of a new migration"
  },
  {
    "code": "def replace_in_file(self, file_path, old_exp, new_exp):\n        self.term.print_info(u\"Making replacement into {}\"\n                                 .format(self.term.text_in_color(file_path,\n                                                                 TERM_GREEN)))\n        tmp_file = tempfile.NamedTemporaryFile(mode='w+t', delete=False)\n        for filelineno, line in enumerate(io.open(file_path, encoding=\"utf-8\")):\n            if old_exp in line:\n                line = line.replace(old_exp, new_exp)\n            try:\n                tmp_file.write(line.encode('utf-8'))\n            except TypeError:\n                tmp_file.write(line)\n        name = tmp_file.name\n        tmp_file.close()\n        shutil.copy(name, file_path)\n        os.remove(name)",
    "docstring": "In the given file, replace all 'old_exp' by 'new_exp'."
  },
  {
    "code": "def datetime(self):\n        date_string = '%s %s %s' % (self._day,\n                                    self._date,\n                                    self._year)\n        return datetime.strptime(date_string, '%a %B %d %Y')",
    "docstring": "Returns a datetime object representing the date the game was played."
  },
  {
    "code": "def comments(recid):\n    from invenio_access.local_config import VIEWRESTRCOLL\n    from invenio_access.mailcookie import \\\n        mail_cookie_create_authorize_action\n    from .api import check_user_can_view_comments\n    auth_code, auth_msg = check_user_can_view_comments(current_user, recid)\n    if auth_code and current_user.is_guest:\n        cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {\n            'collection': g.collection})\n        url_args = {'action': cookie, 'ln': g.ln, 'referer': request.referrer}\n        flash(_(\"Authorization failure\"), 'error')\n        return redirect(url_for('webaccount.login', **url_args))\n    elif auth_code:\n        flash(auth_msg, 'error')\n        abort(401)\n    comments = CmtRECORDCOMMENT.query.filter(db.and_(\n        CmtRECORDCOMMENT.id_bibrec == recid,\n        CmtRECORDCOMMENT.in_reply_to_id_cmtRECORDCOMMENT == 0,\n        CmtRECORDCOMMENT.star_score == 0\n    )).order_by(CmtRECORDCOMMENT.date_creation).all()\n    return render_template('comments/comments.html', comments=comments,\n                           option='comments')",
    "docstring": "Display comments."
  },
  {
    "code": "def _tl15(self, data, wavenumber):\n        return ((C2 * wavenumber) /\n                xu.log((1.0 / data) * C1 * wavenumber ** 3 + 1.0))",
    "docstring": "Compute the L15 temperature."
  },
  {
    "code": "def migrate_connections(new_data_path: str):\n    dest_connections = os.path.join(\n        new_data_path, 'lib', 'NetworkManager', 'system-connections')\n    os.makedirs(dest_connections, exist_ok=True)\n    with mount_state_partition() as state_path:\n        src_connections = os.path.join(\n            state_path, 'root-overlay', 'etc', 'NetworkManager',\n            'system-connections')\n        LOG.info(f\"migrate_connections: moving nmcli connections from\"\n                 f\" {src_connections} to {dest_connections}\")\n        found = migrate_system_connections(src_connections, dest_connections)\n    if found:\n        return\n    LOG.info(\n        \"migrate_connections: No connections found in state, checking boot\")\n    with mount_boot_partition() as boot_path:\n        src_connections = os.path.join(\n            boot_path, 'system-connections')\n        LOG.info(f\"migrate_connections: moving nmcli connections from\"\n                 f\" {src_connections} to {dest_connections}\")\n        found = migrate_system_connections(src_connections, dest_connections)\n        if not found:\n            LOG.info(\"migrate_connections: No connections found in boot\")",
    "docstring": "Migrate wifi connection files to new locations and patch them\n\n    :param new_data_path: The path to where the new data partition is mounted"
  },
  {
    "code": "def get_price(self):\n        for cond in self.conditions:\n            for p in cond.parameters:\n                if p.name == '_amount':\n                    return p.value",
    "docstring": "Return the price from the conditions parameters.\n\n        :return: Int"
  },
  {
    "code": "def _add_edges(self, ast_node, trunk=None):\n        atom_indices = self._atom_indices\n        for atom in ast_node.tail:\n            if atom.head == 'atom':\n                atom_idx = atom_indices[id(atom)]\n                if atom.is_first_kid and atom.parent().head == 'branch':\n                    trunk_idx = atom_indices[id(trunk)]\n                    self.add_edge(atom_idx, trunk_idx)\n                if not atom.is_last_kid:\n                    if atom.next_kid.head == 'atom':\n                        next_idx = atom_indices[id(atom.next_kid)]\n                        self.add_edge(atom_idx, next_idx)\n                    elif atom.next_kid.head == 'branch':\n                        trunk = atom\n                else:\n                    return\n            elif atom.head == 'branch':\n                self._add_edges(atom, trunk)",
    "docstring": "Add all bonds in the SMARTS string as edges in the graph."
  },
  {
    "code": "def save_subresource(self, subresource):\n        data = deepcopy(subresource._resource)\n        data.pop('id', None)\n        data.pop(self.resource_type + '_id', None)\n        subresources = getattr(self, subresource.parent_key, {})\n        subresources[subresource.id] = data\n        setattr(self, subresource.parent_key, subresources)\n        yield self._save()",
    "docstring": "Save the sub-resource\n\n        NOTE: Currently assumes subresources are stored within a dictionary,\n        keyed with the subresource's ID"
  },
  {
    "code": "def _run_atexit():\n    global _atexit\n    for callback, args, kwargs in reversed(_atexit):\n        callback(*args, **kwargs)\n    del _atexit[:]",
    "docstring": "Hook frameworks must invoke this after the main hook body has\n    successfully completed. Do not invoke it if the hook fails."
  },
  {
    "code": "def update(self, *args):\n        \"Appends any passed in byte arrays to the digest object.\"\n        for string in args:\n            self._hobj.update(string)\n        self._fobj = None",
    "docstring": "Appends any passed in byte arrays to the digest object."
  },
  {
    "code": "def process_rst_and_summaries(content_generators):\n    for generator in content_generators:\n        if isinstance(generator, generators.ArticlesGenerator):\n            for article in (\n                    generator.articles +\n                    generator.translations +\n                    generator.drafts):\n                rst_add_mathjax(article)\n                if process_summary.mathjax_script is not None:\n                    process_summary(article)\n        elif isinstance(generator, generators.PagesGenerator):\n            for page in generator.pages:\n                rst_add_mathjax(page)\n            for page in generator.hidden_pages:\n                rst_add_mathjax(page)",
    "docstring": "Ensure mathjax script is applied to RST and summaries are\n    corrected if specified in user settings.\n\n    Handles content attached to ArticleGenerator and PageGenerator objects,\n    since the plugin doesn't know how to handle other Generator types.\n\n    For reStructuredText content, examine both articles and pages.\n    If article or page is reStructuredText and there is math present,\n    append the mathjax script.\n\n    Also process summaries if present (only applies to articles)\n    and user wants summaries processed (via user settings)"
  },
  {
    "code": "def set_parent(self, key_name, new_parent):\n        self.unbake()\n        kf = self.dct[key_name]\n        kf['parent'] = new_parent\n        self.bake()",
    "docstring": "Sets the parent of the key."
  },
  {
    "code": "def _key(self):\n        return Key(self._schema.key_type, self._identity, self._name,\n                   [str(item.value) for item in self._dimension_fields.values()])",
    "docstring": "Generates the Key object based on dimension fields."
  },
  {
    "code": "def call(self, itemMethod):\n        item = itemMethod.im_self\n        method = itemMethod.im_func.func_name\n        return self.batchController.getProcess().addCallback(\n            CallItemMethod(storepath=item.store.dbdir,\n                           storeid=item.storeID,\n                           method=method).do)",
    "docstring": "Invoke the given bound item method in the batch process.\n\n        Return a Deferred which fires when the method has been invoked."
  },
  {
    "code": "def _from_rest_blank(model, props):\n    blank = model.get_fields_by_prop('allow_blank', True)\n    for field in blank:\n        try:\n            if props[field] == '':\n                props[field] = None\n        except KeyError:\n            continue",
    "docstring": "Set empty strings to None where allowed\n\n    This is done on fields with `allow_blank=True` which takes\n    an incoming empty string & sets it to None so validations\n    are skipped. This is useful on fields that aren't required\n    with format validations like URLType, EmailType, etc."
  },
  {
    "code": "def respond_static(self, environ):\n        path = os.path.normpath(environ[\"PATH_INFO\"])\n        if path == \"/\":\n            content = self.index()\n            content_type = \"text/html\"\n        else:\n            path = os.path.join(os.path.dirname(__file__), path.lstrip(\"/\"))\n            try:\n                with open(path, \"r\") as f:\n                    content = f.read()\n            except IOError:\n                return 404\n            content_type = guess_type(path)[0]\n        return (200, [(\"Content-Type\", content_type)], content)",
    "docstring": "Serves a static file when Django isn't being used."
  },
  {
    "code": "def notify_attached(room, event, user):\n    tpl = get_plugin_template_module('emails/attached.txt', chatroom=room, event=event, user=user)\n    _send(event, tpl)",
    "docstring": "Notifies about an existing chatroom being attached to an event.\n\n    :param room: the chatroom\n    :param event: the event\n    :param user: the user performing the action"
  },
  {
    "code": "def active_classification(keywords, exposure_key):\n    classifications = None\n    if 'classification' in keywords:\n        return keywords['classification']\n    if 'layer_mode' in keywords and keywords['layer_mode'] == \\\n            layer_mode_continuous['key']:\n        classifications = keywords['thresholds'].get(exposure_key)\n    elif 'value_maps' in keywords:\n        classifications = keywords['value_maps'].get(exposure_key)\n    if classifications is None:\n        return None\n    for classification, value in list(classifications.items()):\n        if value['active']:\n            return classification\n    return None",
    "docstring": "Helper to retrieve active classification for an exposure.\n\n    :param keywords: Hazard layer keywords.\n    :type keywords: dict\n\n    :param exposure_key: The exposure key.\n    :type exposure_key: str\n\n    :returns: The active classification key. None if there is no active one.\n    :rtype: str"
  },
  {
    "code": "def DbUnExportEvent(self, argin):\n        self._log.debug(\"In DbUnExportEvent()\")\n        event_name = argin[0].lower()\n        self.db.unexport_event(event_name)",
    "docstring": "Mark one event channel as non exported in database\n\n        :param argin: name of event channel or factory to unexport\n        :type: tango.DevString\n        :return: none\n        :rtype: tango.DevVoid"
  },
  {
    "code": "def _hierarchy(self):\n        self.hierarchy = {}\n        for rank in self.taxonomy:\n            taxslice = self._slice(level=self.taxonomy.index(rank))\n            self.hierarchy[rank] = self._group(taxslice)",
    "docstring": "Generate dictionary of referenced idents grouped by shared rank"
  },
  {
    "code": "def match(self, p_todo):\n        children = self.todolist.children(p_todo)\n        uncompleted = [todo for todo in children if not todo.is_completed()]\n        return not uncompleted",
    "docstring": "Returns True when there are no children that are uncompleted yet."
  },
  {
    "code": "def component_on_date(self, date: datetime.date) -> Optional[\"Interval\"]:\n        return self.intersection(Interval.wholeday(date))",
    "docstring": "Returns the part of this interval that falls on the date given, or\n        ``None`` if the interval doesn't have any part during that date."
  },
  {
    "code": "async def update_firmware(\n            self,\n            firmware_file: str,\n            loop: asyncio.AbstractEventLoop = None,\n            explicit_modeset: bool = True) -> str:\n        if None is loop:\n            checked_loop = self._loop\n        else:\n            checked_loop = loop\n        return await self._backend.update_firmware(firmware_file,\n                                                   checked_loop,\n                                                   explicit_modeset)",
    "docstring": "Update the firmware on the Smoothie board.\n\n        :param firmware_file: The path to the firmware file.\n        :param explicit_modeset: `True` to force the smoothie into programming\n                                 mode; `False` to assume it is already in\n                                 programming mode.\n        :param loop: An asyncio event loop to use; if not specified, the one\n                     associated with this instance will be used.\n        :returns: The stdout of the tool used to update the smoothie"
  },
  {
    "code": "def get_grade_id(self):\n        if not bool(self._my_map['gradeId']):\n            raise errors.IllegalState('grade empty')\n        return Id(self._my_map['gradeId'])",
    "docstring": "Gets the grade ``Id`` in this entry if the grading system is based on grades.\n\n        return: (osid.id.Id) - the grade ``Id``\n        raise:  IllegalState - ``is_graded()`` is ``false`` or\n                ``GradeSystem.isBasedOnGrades()`` is ``false``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def render_code(code, filetype, pygments_style):\n    if filetype:\n        lexer = pygments.lexers.get_lexer_by_name(filetype)\n        formatter = pygments.formatters.HtmlFormatter(style=pygments_style)\n        return pygments.highlight(code, lexer, formatter)\n    else:\n        return \"<pre><code>{}</code></pre>\".format(code)",
    "docstring": "Renders a piece of code into HTML. Highlights syntax if filetype is specfied"
  },
  {
    "code": "def _set_cpu_throttling(self):\n        if not self.is_running():\n            return\n        try:\n            if sys.platform.startswith(\"win\") and hasattr(sys, \"frozen\"):\n                cpulimit_exec = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), \"cpulimit\", \"cpulimit.exe\")\n            else:\n                cpulimit_exec = \"cpulimit\"\n            subprocess.Popen([cpulimit_exec, \"--lazy\", \"--pid={}\".format(self._process.pid), \"--limit={}\".format(self._cpu_throttling)], cwd=self.working_dir)\n            log.info(\"CPU throttled to {}%\".format(self._cpu_throttling))\n        except FileNotFoundError:\n            raise QemuError(\"cpulimit could not be found, please install it or deactivate CPU throttling\")\n        except (OSError, subprocess.SubprocessError) as e:\n            raise QemuError(\"Could not throttle CPU: {}\".format(e))",
    "docstring": "Limits the CPU usage for current QEMU process."
  },
  {
    "code": "def to_array(self):\n        array = super(InlineQueryResultCachedMpeg4Gif, self).to_array()\n        array['type'] = u(self.type)\n        array['id'] = u(self.id)\n        array['mpeg4_file_id'] = u(self.mpeg4_file_id)\n        if self.title is not None:\n            array['title'] = u(self.title)\n        if self.caption is not None:\n            array['caption'] = u(self.caption)\n        if self.parse_mode is not None:\n            array['parse_mode'] = u(self.parse_mode)\n        if self.reply_markup is not None:\n            array['reply_markup'] = self.reply_markup.to_array()\n        if self.input_message_content is not None:\n            array['input_message_content'] = self.input_message_content.to_array()\n        return array",
    "docstring": "Serializes this InlineQueryResultCachedMpeg4Gif to a dictionary.\n\n        :return: dictionary representation of this object.\n        :rtype: dict"
  },
  {
    "code": "def find_transport_reactions(model):\n    transport_reactions = []\n    transport_rxn_candidates = set(model.reactions) - set(model.boundary) \\\n        - set(find_biomass_reaction(model))\n    transport_rxn_candidates = set(\n        [rxn for rxn in transport_rxn_candidates if len(rxn.compartments) >= 2]\n    )\n    sbo_matches = set([rxn for rxn in transport_rxn_candidates if\n                       rxn.annotation is not None and\n                       'sbo' in rxn.annotation and\n                       rxn.annotation['sbo'] in TRANSPORT_RXN_SBO_TERMS])\n    if len(sbo_matches) > 0:\n        transport_reactions += list(sbo_matches)\n    for rxn in transport_rxn_candidates:\n        rxn_mets = set([met.formula for met in rxn.metabolites])\n        if (None not in rxn_mets) and (len(rxn_mets) != 0):\n            if is_transport_reaction_formulae(rxn):\n                transport_reactions.append(rxn)\n        elif is_transport_reaction_annotations(rxn):\n            transport_reactions.append(rxn)\n    return set(transport_reactions)",
    "docstring": "Return a list of all transport reactions.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model under investigation.\n\n    Notes\n    -----\n    A transport reaction is defined as follows:\n    1. It contains metabolites from at least 2 compartments and\n    2. at least 1 metabolite undergoes no chemical reaction, i.e.,\n    the formula and/or annotation stays the same on both sides of the equation.\n\n    A notable exception is transport via PTS, which also contains the following\n    restriction:\n    3. The transported metabolite(s) are transported into a compartment through\n    the exchange of a phosphate group.\n\n    An example of transport via PTS would be\n    pep(c) + glucose(e) -> glucose-6-phosphate(c) + pyr(c)\n\n    Reactions similar to transport via PTS (referred to as \"modified transport\n    reactions\") follow a similar pattern:\n    A(x) + B-R(y) -> A-R(y) + B(y)\n\n    Such modified transport reactions can be detected, but only when a formula\n    field exists for all metabolites in a particular reaction. If this is not\n    the case, transport reactions are identified through annotations, which\n    cannot detect modified transport reactions."
  },
  {
    "code": "def change(self) -> Tuple[bool, dict]:\n        next = self.next\n        self.next = None\n        if self.next or not self.running:\n            message = \"The Scene.change interface is deprecated. Use the events commands instead.\"\n            warn(message, DeprecationWarning)\n        return self.running, {\"scene_class\": next}",
    "docstring": "Default case, override in subclass as necessary."
  },
  {
    "code": "def plot_lines(f, x, samples, ax=None, **kwargs):\n    r\n    logZ = kwargs.pop('logZ', None)\n    weights = kwargs.pop('weights', None)\n    ntrim = kwargs.pop('ntrim', None)\n    cache = kwargs.pop('cache', '')\n    parallel = kwargs.pop('parallel', False)\n    tqdm_kwargs = kwargs.pop('tqdm_kwargs', {})\n    fsamps = compute_samples(f, x, samples, logZ=logZ,\n                             weights=weights, ntrim=ntrim,\n                             parallel=parallel, cache=cache,\n                             tqdm_kwargs=tqdm_kwargs)\n    fgivenx.plot.plot_lines(x, fsamps, ax, **kwargs)",
    "docstring": "r\"\"\"\n    Plot a representative set of functions to sample\n\n    Additionally, if a list of log-evidences are passed, along with list of\n    functions, and list of samples, this function plots the probability mass\n    function for all models marginalised according to the evidences.\n\n    Parameters\n    ----------\n    f: function\n        function :math:`f(x;\\theta)` (or list of functions for each model) with\n        dependent variable :math:`x`, parameterised by :math:`\\theta`.\n\n    x: 1D array-like\n        `x` values to evaluate :math:`f(x;\\theta)` at.\n\n    samples: 2D array-like\n        :math:`\\theta` samples (or list of :math:`\\theta` samples) to evaluate\n        :math:`f(x;\\theta)` at.\n        `shape = (nsamples, npars)`\n\n    ax: axes object, optional\n        :class:`matplotlib.axes._subplots.AxesSubplot` to plot the contours\n        onto. If unsupplied, then :func:`matplotlib.pyplot.gca()` is used to\n        get the last axis used, or create a new one.\n\n    logZ: 1D array-like, optional\n        log-evidences of each model if multiple models are passed.\n        Should be same length as the list `f`, and need not be normalised.\n        Default: `numpy.ones_like(f)`\n\n    weights: 1D array-like, optional\n        sample weights (or list of weights), if desired. Should have length\n        same as `samples.shape[0]`.\n        Default: `numpy.ones_like(samples)`\n\n    ntrim: int, optional\n        Approximate number of samples to trim down to, if desired. Useful if\n        the posterior is dramatically oversampled.\n        Default: None\n\n    cache: str, optional\n        File root for saving previous calculations for re-use\n\n    parallel, tqdm_args:\n        see docstring for :func:`fgivenx.parallel.parallel_apply`\n\n    kwargs: further keyword arguments\n        Any further keyword arguments are plotting keywords that are passed to\n        :func:`fgivenx.plot.plot_lines`."
  },
  {
    "code": "def as_object(obj):\n    LOGGER.debug('as_object(%s)', obj)\n    if isinstance(obj, datetime.date):\n        return as_date(obj)\n    elif hasattr(obj, '__dict__'):\n        out = {k: obj.__dict__[k] for k in obj.__dict__ if not k.startswith('_')}\n        for k, v in (\n                (p, getattr(obj, p))\n                for p, _ in inspect.getmembers(\n                    obj.__class__,\n                    lambda x: isinstance(x, property))\n        ):\n            out[k] = v\n        return out",
    "docstring": "Return a JSON serializable type for ``o``.\n\n    Args:\n        obj (:py:class:`object`): the object to be serialized.\n\n    Raises:\n        :py:class:`AttributeError`:\n            when ``o`` is not a Python object.\n\n    Returns:\n        (dict): JSON serializable type for the given object."
  },
  {
    "code": "def process_request(request):\n        if 'HTTP_X_OPERAMINI_FEATURES' in request.META:\n            request.mobile = True\n            return None\n        if 'HTTP_ACCEPT' in request.META:\n            s = request.META['HTTP_ACCEPT'].lower()\n            if 'application/vnd.wap.xhtml+xml' in s:\n                request.mobile = True\n                return None\n        if 'HTTP_USER_AGENT' in request.META:\n            s = request.META['HTTP_USER_AGENT'].lower()\n            for ua in search_strings:\n                if ua in s:\n                    if not ignore_user_agent(s):\n                        request.mobile = True\n                        if MOBI_DETECT_TABLET:\n                            request.tablet = _is_tablet(s)\n                        return None\n        request.mobile = False\n        request.tablet = False\n        return None",
    "docstring": "Adds a \"mobile\" attribute to the request which is True or False\n           depending on whether the request should be considered to come from a\n           small-screen device such as a phone or a PDA"
  },
  {
    "code": "def db_list(user=None, host=None, port=None, maintenance_db=None,\n            password=None, runas=None):\n    ret = {}\n    query = (\n        'SELECT datname as \"Name\", pga.rolname as \"Owner\", '\n        'pg_encoding_to_char(encoding) as \"Encoding\", '\n        'datcollate as \"Collate\", datctype as \"Ctype\", '\n        'datacl as \"Access privileges\", spcname as \"Tablespace\" '\n        'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts '\n        'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace'\n    )\n    rows = psql_query(query, runas=runas, host=host, user=user,\n                      port=port, maintenance_db=maintenance_db,\n                      password=password)\n    for row in rows:\n        ret[row['Name']] = row\n        ret[row['Name']].pop('Name')\n    return ret",
    "docstring": "Return dictionary with information about databases of a Postgres server.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' postgres.db_list"
  },
  {
    "code": "def _get_esxcluster_proxy_details():\n    det = __salt__['esxcluster.get_details']()\n    return det.get('vcenter'), det.get('username'), det.get('password'), \\\n            det.get('protocol'), det.get('port'), det.get('mechanism'), \\\n            det.get('principal'), det.get('domain'), det.get('datacenter'), \\\n            det.get('cluster')",
    "docstring": "Returns the running esxcluster's proxy details"
  },
  {
    "code": "def unicodestr(s, encoding='utf-8', fallback='iso-8859-1'):\n    if isinstance(s, unicode):\n        return s\n    try:\n        return s.decode(encoding)\n    except UnicodeError:\n        return s.decode(fallback)",
    "docstring": "Convert a string to unicode if it isn't already."
  },
  {
    "code": "def waitForEvent(self, event_name, predicate, timeout=DEFAULT_TIMEOUT):\n        deadline = time.time() + timeout\n        while time.time() <= deadline:\n            rpc_timeout = deadline - time.time()\n            if rpc_timeout < 0:\n                break\n            rpc_timeout = min(rpc_timeout, MAX_TIMEOUT)\n            try:\n                event = self.waitAndGet(event_name, rpc_timeout)\n            except TimeoutError:\n                break\n            if predicate(event):\n                return event\n        raise TimeoutError(\n            self._ad,\n            'Timed out after %ss waiting for an \"%s\" event that satisfies the '\n            'predicate \"%s\".' % (timeout, event_name, predicate.__name__))",
    "docstring": "Wait for an event of a specific name that satisfies the predicate.\n\n        This call will block until the expected event has been received or time\n        out.\n\n        The predicate function defines the condition the event is expected to\n        satisfy. It takes an event and returns True if the condition is\n        satisfied, False otherwise.\n\n        Note all events of the same name that are received but don't satisfy\n        the predicate will be discarded and not be available for further\n        consumption.\n\n        Args:\n            event_name: string, the name of the event to wait for.\n            predicate: function, a function that takes an event (dictionary) and\n                returns a bool.\n            timeout: float, default is 120s.\n\n        Returns:\n            dictionary, the event that satisfies the predicate if received.\n\n        Raises:\n            TimeoutError: raised if no event that satisfies the predicate is\n                received after timeout seconds."
  },
  {
    "code": "def query_balance(self, asset: str, b58_address: str) -> int:\n        raw_address = Address.b58decode(b58_address).to_bytes()\n        contract_address = self.get_asset_address(asset)\n        invoke_code = build_native_invoke_code(contract_address, b'\\x00', \"balanceOf\", raw_address)\n        tx = Transaction(0, 0xd1, int(time()), 0, 0, None, invoke_code, bytearray(), list())\n        response = self.__sdk.rpc.send_raw_transaction_pre_exec(tx)\n        try:\n            balance = ContractDataParser.to_int(response['Result'])\n            return balance\n        except SDKException:\n            return 0",
    "docstring": "This interface is used to query the account's ONT or ONG balance.\n\n        :param asset: a string which is used to indicate which asset we want to check the balance.\n        :param b58_address: a base58 encode account address.\n        :return: account balance."
  },
  {
    "code": "def set_forbidden_uptodate(self, uptodate):\n        if self._forbidden_uptodate == uptodate:\n            return\n        self._forbidden_uptodate = uptodate\n        self.invalidateFilter()",
    "docstring": "Set all forbidden uptodate values\n\n        :param uptodatees: a list with forbidden uptodate values\n        :uptodate uptodatees: list\n        :returns: None\n        :ruptodate: None\n        :raises: None"
  },
  {
    "code": "def update_role(u_name, newprivilege):\n        entry = TabMember.update(\n            role=newprivilege\n        ).where(TabMember.user_name == u_name)\n        try:\n            entry.execute()\n            return True\n        except:\n            return False",
    "docstring": "Update the role of the usr."
  },
  {
    "code": "def get_version(filepath='src/birding/version.py'):\n    with open(get_abspath(filepath)) as version_file:\n        return re.search(\n            r,\n            version_file.read()).group('version')",
    "docstring": "Get version without import, which avoids dependency issues."
  },
  {
    "code": "def compare_checkpoints(self, attr_mean):\n        if self._cmp_greater and attr_mean > self.best_checkpoint_attr_value:\n            return True\n        elif (not self._cmp_greater\n              and attr_mean < self.best_checkpoint_attr_value):\n            return True\n        return False",
    "docstring": "Compares two checkpoints based on the attribute attr_mean param.\n        Greater than is used by default. If  command-line parameter\n        checkpoint_score_attr starts with \"min-\" less than is used.\n\n        Arguments:\n            attr_mean: mean of attribute value for the current checkpoint\n\n        Returns:\n            True: when attr_mean is greater than previous checkpoint attr_mean\n                  and greater than function is selected\n                  when attr_mean is less than previous checkpoint attr_mean and\n                  less than function is selected\n            False: when attr_mean is not in alignment with selected cmp fn"
  },
  {
    "code": "def add_interface(self, interface):\n        if not isinstance(interface, Interface):\n            raise TypeError\n        self._interfaces[interface.name] = interface",
    "docstring": "Manually add or overwrite an interface definition from an Interface object.\n\n        :param interface: an Interface() object"
  },
  {
    "code": "def update_lbaas_member(self, lbaas_member, lbaas_pool, body=None):\n        return self.put(self.lbaas_member_path % (lbaas_pool, lbaas_member),\n                        body=body)",
    "docstring": "Updates a lbaas_member."
  },
  {
    "code": "def substr(self, name, start=None, size=None):\n        if start is not None and size is not None:\n            start = get_integer('start', start)\n            size = get_integer('size', size)\n            return self.execute_command('substr', name, start, size)\n        elif start is not None:\n            start = get_integer('start', start)            \n            return self.execute_command('substr', name, start)\n        return self.execute_command('substr', name)",
    "docstring": "Return a substring of the string at key ``name``. ``start`` and ``size``\n        are 0-based integers specifying the portion of the string to return.\n\n        Like **Redis.SUBSTR**\n\n        :param string name: the key name\n        :param int start: Optional, the offset of first byte returned. If start\n         is negative, the returned string will start at the start'th character\n         from the end of string.\n        :param int size: Optional, number of bytes returned. If size is\n         negative, then that many characters will be omitted from the end of string.\n        :return: The extracted part of the string.\n        :rtype: string\n        \n        >>> ssdb.set('str_test', 'abc12345678')\n        True\n        >>> ssdb.substr('str_test', 2, 4)\n        'c123'\n        >>> ssdb.substr('str_test', -2, 2)\n        '78'\n        >>> ssdb.substr('str_test', 1, -1)\n        'bc1234567'"
  },
  {
    "code": "def start(self):\n        if self.closed:\n            raise ConnectionClosed()\n        self.read_watcher.start()\n        if self.write == self.buffered_write:\n            self.write_watcher.start()",
    "docstring": "Start watching the socket."
  },
  {
    "code": "def _segment_with_tokens(text, tokens):\n        list_form = []\n        text_ptr = 0\n        for token in tokens:\n            inter_token_string = []\n            while not text[text_ptr:].startswith(token):\n                inter_token_string.append(text[text_ptr])\n                text_ptr += 1\n                if text_ptr >= len(text):\n                    raise ValueError(\"Tokenization produced tokens that do not belong in string!\")\n            text_ptr += len(token)\n            if inter_token_string:\n                list_form.append(''.join(inter_token_string))\n            list_form.append(token)\n        if text_ptr < len(text):\n            list_form.append(text[text_ptr:])\n        return list_form",
    "docstring": "Segment a string around the tokens created by a passed-in tokenizer"
  },
  {
    "code": "def get_linode_id_from_name(name):\n    nodes = _query('linode', 'list')['DATA']\n    linode_id = ''\n    for node in nodes:\n        if name == node['LABEL']:\n            linode_id = node['LINODEID']\n            return linode_id\n    if not linode_id:\n        raise SaltCloudNotFound(\n            'The specified name, {0}, could not be found.'.format(name)\n        )",
    "docstring": "Returns the Linode ID for a VM from the provided name.\n\n    name\n        The name of the Linode from which to get the Linode ID. Required."
  },
  {
    "code": "def create(model_config, path, num_workers, batch_size, augmentations=None, tta=None):\n    if not os.path.isabs(path):\n        path = model_config.project_top_dir(path)\n    train_path = os.path.join(path, 'train')\n    valid_path = os.path.join(path, 'valid')\n    train_ds = ImageDirSource(train_path)\n    val_ds = ImageDirSource(valid_path)\n    return TrainingData(\n        train_ds,\n        val_ds,\n        num_workers=num_workers,\n        batch_size=batch_size,\n        augmentations=augmentations,\n    )",
    "docstring": "Create an ImageDirSource with supplied arguments"
  },
  {
    "code": "def _none_value(self):\n        if self.out_type == int:\n            return 0\n        elif self.out_type == float:\n            return 0.0\n        elif self.out_type == bool:\n            return False\n        elif self.out_type == six.text_type:\n            return u''",
    "docstring": "Get an appropriate \"null\" value for this field's type. This\n        is used internally when setting the field to None."
  },
  {
    "code": "def remove_duplicate_edges_undirected(udg):\n    lookup = {}\n    edges = sorted(udg.get_all_edge_ids())\n    for edge_id in edges:\n        e = udg.get_edge(edge_id)\n        tpl_a = e['vertices']\n        tpl_b = (tpl_a[1], tpl_a[0])\n        if tpl_a in lookup or tpl_b in lookup:\n            udg.delete_edge_by_id(edge_id)\n        else:\n            lookup[tpl_a] = edge_id\n            lookup[tpl_b] = edge_id",
    "docstring": "Removes duplicate edges from an undirected graph."
  },
  {
    "code": "def descendents(self, cls):\n        if cls.cls == type or not hasattr(cls.cls, '__subclasses__'):\n            return []\n        downs = cls.cls.__subclasses__()\n        return list(map(lambda c: self.find_class(c), downs))",
    "docstring": "Returns a descendent list of documentation objects for `cls`,\n        which must be a documentation object.\n\n        The list will contain objects belonging to `pydoc.Class` or\n        `pydoc.External`. Objects belonging to the former are exported\n        classes either in this module or in one of its sub-modules."
  },
  {
    "code": "def _get_category_from_pars_var(template_var, context):\n    cat = template_var.resolve(context)\n    if isinstance(cat, basestring):\n        cat = Category.objects.get_by_tree_path(cat)\n    return cat",
    "docstring": "get category from template variable or from tree_path"
  },
  {
    "code": "def after(self, existing_fn, new_fn):\n        self.warn_if_function_not_registered(new_fn)\n        try:\n            index = self._stack.index(existing_fn)\n            self._stack.insert(index + 1, new_fn)\n        except ValueError as e:\n            six.raise_from(BaseLunrException(\"Cannot find existing_fn\"), e)",
    "docstring": "Adds a single function after a function that already exists in the\n        pipeline."
  },
  {
    "code": "def generate_name(self, name_format=DEFAULT_FILE_NAME_FORMAT):\n        if len(self.segments) > 0:\n            return self.segments[0].points[0].time.strftime(name_format) + \".gpx\"\n        else:\n            return \"EmptyTrack\"",
    "docstring": "Generates a name for the track\n\n        The name is generated based on the date of the first point of the\n        track, or in case it doesn't exist, \"EmptyTrack\"\n\n        Args:\n            name_format (str, optional): Name formar to give to the track, based on\n                its start time. Defaults to DEFAULT_FILE_NAME_FORMAT\n        Returns:\n            str"
  },
  {
    "code": "def make_context(self, **kwargs):\n        self.check_schema()\n        return Context(self.driver, self.config, **kwargs)",
    "docstring": "Create a new context for reading data"
  },
  {
    "code": "def only_manager(self):\n        assert len(self.managers) == 1, MULTIPLE_MANAGERS_MESSAGE\n        return list(self.managers.values())[0]",
    "docstring": "Convience accessor for tests and contexts with sole manager."
  },
  {
    "code": "def reply_message(self, reply_token, messages, timeout=None):\n        if not isinstance(messages, (list, tuple)):\n            messages = [messages]\n        data = {\n            'replyToken': reply_token,\n            'messages': [message.as_json_dict() for message in messages]\n        }\n        self._post(\n            '/v2/bot/message/reply', data=json.dumps(data), timeout=timeout\n        )",
    "docstring": "Call reply message API.\n\n        https://devdocs.line.me/en/#reply-message\n\n        Respond to events from users, groups, and rooms.\n\n        Webhooks are used to notify you when an event occurs.\n        For events that you can respond to, a replyToken is issued for replying to messages.\n\n        Because the replyToken becomes invalid after a certain period of time,\n        responses should be sent as soon as a message is received.\n\n        Reply tokens can only be used once.\n\n        :param str reply_token: replyToken received via webhook\n        :param messages: Messages.\n            Max: 5\n        :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` |\n            list[T <= :py:class:`linebot.models.send_messages.SendMessage`]\n        :param timeout: (optional) How long to wait for the server\n            to send data before giving up, as a float,\n            or a (connect timeout, read timeout) float tuple.\n            Default is self.http_client.timeout\n        :type timeout: float | tuple(float, float)"
  },
  {
    "code": "def _loadable_models():\n    classes = [\n        pyphi.Direction,\n        pyphi.Network,\n        pyphi.Subsystem,\n        pyphi.Transition,\n        pyphi.labels.NodeLabels,\n        pyphi.models.Cut,\n        pyphi.models.KCut,\n        pyphi.models.NullCut,\n        pyphi.models.Part,\n        pyphi.models.Bipartition,\n        pyphi.models.KPartition,\n        pyphi.models.Tripartition,\n        pyphi.models.RepertoireIrreducibilityAnalysis,\n        pyphi.models.MaximallyIrreducibleCauseOrEffect,\n        pyphi.models.MaximallyIrreducibleCause,\n        pyphi.models.MaximallyIrreducibleEffect,\n        pyphi.models.Concept,\n        pyphi.models.CauseEffectStructure,\n        pyphi.models.SystemIrreducibilityAnalysis,\n        pyphi.models.ActualCut,\n        pyphi.models.AcRepertoireIrreducibilityAnalysis,\n        pyphi.models.CausalLink,\n        pyphi.models.Account,\n        pyphi.models.AcSystemIrreducibilityAnalysis\n    ]\n    return {cls.__name__: cls for cls in classes}",
    "docstring": "A dictionary of loadable PyPhi models.\n\n    These are stored in this function (instead of module scope) to resolve\n    circular import issues."
  },
  {
    "code": "def _get_port_profile_id(self, request):\n        port_profile_id = request.path.split(\"/\")[-1].strip()\n        if uuidutils.is_uuid_like(port_profile_id):\n            LOG.debug(\"The instance id was found in request path.\")\n            return port_profile_id\n        LOG.debug(\"Failed to get the instance id from the request.\")\n        return None",
    "docstring": "Get the port profile ID from the request path."
  },
  {
    "code": "def _dispatch_trigger(self, msg):\n        if not msg.args[0].startswith(self.trigger_char):\n            return\n        split_args = msg.args[0].split()\n        trigger = split_args[0].lstrip(self.trigger_char)\n        if trigger in self.triggers:\n            method = getattr(self, trigger)\n            if msg.command == PRIVMSG:\n                if msg.dst == self.irc.nick:\n                    if EVT_PRIVATE in self.triggers[trigger]:\n                        msg.event = EVT_PRIVATE\n                        method(msg)\n                else:\n                    if EVT_PUBLIC in self.triggers[trigger]:\n                        msg.event = EVT_PUBLIC\n                        method(msg)\n            elif (msg.command == NOTICE) and (EVT_NOTICE in self.triggers[trigger]):\n                msg.event = EVT_NOTICE\n                method(msg)",
    "docstring": "Dispatches the message to the corresponding method."
  },
  {
    "code": "def apply_computation(cls,\n                          state: BaseState,\n                          message: Message,\n                          transaction_context: BaseTransactionContext) -> 'BaseComputation':\n        with cls(state, message, transaction_context) as computation:\n            if message.code_address in computation.precompiles:\n                computation.precompiles[message.code_address](computation)\n                return computation\n            show_debug2 = computation.logger.show_debug2\n            for opcode in computation.code:\n                opcode_fn = computation.get_opcode_fn(opcode)\n                if show_debug2:\n                    computation.logger.debug2(\n                        \"OPCODE: 0x%x (%s) | pc: %s\",\n                        opcode,\n                        opcode_fn.mnemonic,\n                        max(0, computation.code.pc - 1),\n                    )\n                try:\n                    opcode_fn(computation=computation)\n                except Halt:\n                    break\n        return computation",
    "docstring": "Perform the computation that would be triggered by the VM message."
  },
  {
    "code": "def value_as_datetime(self):\n        if self.value is None:\n            return None\n        v1, v2 = self.value\n        if isinstance(v1, numbers.Number):\n            d1 = datetime.utcfromtimestamp(v1 / 1000)\n        else:\n            d1 = v1\n        if isinstance(v2, numbers.Number):\n            d2 = datetime.utcfromtimestamp(v2 / 1000)\n        else:\n            d2 = v2\n        return d1, d2",
    "docstring": "Convenience property to retrieve the value tuple as a tuple of\n        datetime objects."
  },
  {
    "code": "def remove(cls, id):\n        api = Client.instance().api\n        api.index(id).delete()",
    "docstring": "Deletes an index with id\n\n            :param id string/document-handle"
  },
  {
    "code": "def peaks(data, method='max', axis='time', limits=None):\n    idx_axis = data.index_of(axis)\n    output = data._copy()\n    output.axis.pop(axis)\n    for trl in range(data.number_of('trial')):\n        values = data.axis[axis][trl]\n        dat = data(trial=trl)\n        if limits is not None:\n            limits = (values < limits[0]) | (values > limits[1])\n            idx = [slice(None)] * len(data.list_of_axes)\n            idx[idx_axis] = limits\n            dat[idx] = nan\n        if method == 'max':\n            peak_val = nanargmax(dat, axis=idx_axis)\n        elif method == 'min':\n            peak_val = nanargmin(dat, axis=idx_axis)\n        output.data[trl] = values[peak_val]\n    return output",
    "docstring": "Return the values of an index where the data is at max or min\n\n    Parameters\n    ----------\n    method : str, optional\n        'max' or 'min'\n    axis : str, optional\n        the axis where you want to detect the peaks\n    limits : tuple of two values, optional\n        the lowest and highest limits where to search for the peaks\n    data : instance of Data\n        one of the datatypes\n\n    Returns\n    -------\n    instance of Data\n        with one dimension less that the input data. The actual values in\n        the data can be not-numberic, for example, if you look for the\n        max value across electrodes\n\n    Notes\n    -----\n    This function is useful when you want to find the frequency value at which\n    the power is the largest, or to find the time point at which the signal is\n    largest, or the channel at which the activity is largest."
  },
  {
    "code": "def make_ical(self, csv_configs=None):\n        csv_configs = self._generate_configs_from_default(csv_configs)\n        self.cal = Calendar()\n        for row in self.csv_data:\n            event = Event()\n            event.add('summary', row[csv_configs['CSV_NAME']])\n            event.add('dtstart', row[csv_configs['CSV_START_DATE']])\n            event.add('dtend', row[csv_configs['CSV_END_DATE']])\n            event.add('description', row[csv_configs['CSV_DESCRIPTION']])\n            event.add('location', row[csv_configs['CSV_LOCATION']])\n            self.cal.add_component(event)\n        return self.cal",
    "docstring": "Make iCal entries"
  },
  {
    "code": "def all_equal(arg1,arg2):\n    if all(hasattr(el, '_infinitely_iterable') for el in [arg1,arg2]):\n        return arg1==arg2\n    try:\n        return all(a1 == a2 for a1, a2 in zip(arg1, arg2))\n    except TypeError:\n        return arg1==arg2",
    "docstring": "Return a single boolean for arg1==arg2, even for numpy arrays\n    using element-wise comparison.\n\n    Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise.\n\n    If both objects have an '_infinitely_iterable' attribute, they are\n    not be zipped together and are compared directly instead."
  },
  {
    "code": "def is_git(path):\n    try:\n        repo_dir = run_cmd(path, 'git', 'rev-parse', '--git-dir')\n        return True if repo_dir else False\n    except (OSError, RuntimeError):\n        return False",
    "docstring": "Return True if this is a git repo."
  },
  {
    "code": "def my_shared_endpoint_list(endpoint_id):\n    client = get_client()\n    ep_iterator = client.my_shared_endpoint_list(endpoint_id)\n    formatted_print(ep_iterator, fields=ENDPOINT_LIST_FIELDS)",
    "docstring": "Executor for `globus endpoint my-shared-endpoint-list`"
  },
  {
    "code": "def find_template(self, name):\n        deftemplate = lib.EnvFindDeftemplate(self._env, name.encode())\n        if deftemplate == ffi.NULL:\n            raise LookupError(\"Template '%s' not found\" % name)\n        return Template(self._env, deftemplate)",
    "docstring": "Find the Template by its name."
  },
  {
    "code": "def _match_directories(self, entries, root, regex_string):\n        self.log(u\"Matching directory names in paged hierarchy\")\n        self.log([u\"Matching within '%s'\", root])\n        self.log([u\"Matching regex '%s'\", regex_string])\n        regex = re.compile(r\"\" + regex_string)\n        directories = set()\n        root_len = len(root)\n        for entry in entries:\n            if entry.startswith(root):\n                self.log([u\"Examining '%s'\", entry])\n                entry = entry[root_len + 1:]\n                entry_splitted = entry.split(os.sep)\n                if ((len(entry_splitted) >= 2) and\n                        (re.match(regex, entry_splitted[0]) is not None)):\n                    directories.add(entry_splitted[0])\n                    self.log([u\"Match: '%s'\", entry_splitted[0]])\n                else:\n                    self.log([u\"No match: '%s'\", entry])\n        return sorted(directories)",
    "docstring": "Match directory names in paged hierarchies.\n\n        Example: ::\n\n            root = /foo/bar\n            regex_string = [0-9]+\n\n            /foo/bar/\n                     1/\n                       bar\n                       baz\n                     2/\n                       bar\n                     3/\n                       foo\n\n            => [\"/foo/bar/1\", \"/foo/bar/2\", \"/foo/bar/3\"]\n\n        :param list entries: the list of entries (paths) of a container\n        :param string root: the root directory to search within\n        :param string regex_string: regex string to match directory names\n        :rtype: list of matched directories"
  },
  {
    "code": "def _parse_response(self, response, target_object=strack):\n        objects = json.loads(response.read().decode(\"utf-8\"))\n        list = []\n        for obj in objects:\n            list.append(target_object(obj, client=self.client))\n        return list",
    "docstring": "Generic response parser method"
  },
  {
    "code": "def check_counts(self):\n        if \"counts\" in re.split(\"[/.]\", self.endpoint):\n            logger.info(\"disabling tweet parsing due to counts API usage\")\n            self._tweet_func = lambda x: x",
    "docstring": "Disables tweet parsing if the count API is used."
  },
  {
    "code": "def _getrsyncoptions(self):\n        ignores = list(self.DEFAULT_IGNORES)\n        ignores += self.config.option.rsyncignore\n        ignores += self.config.getini(\"rsyncignore\")\n        return {\"ignores\": ignores, \"verbose\": self.config.option.verbose}",
    "docstring": "Get options to be passed for rsync."
  },
  {
    "code": "def extract(dump_files, extractors=ALL_EXTRACTORS):\n    def process_dump(dump, path):\n        for page in dump:\n            if page.namespace != 0: continue\n            else:\n                for cite in extract_cite_history(page, extractors):\n                    yield cite\n    return mwxml.map(process_dump, dump_files)",
    "docstring": "Extracts cites from a set of `dump_files`.\n\n    :Parameters:\n        dump_files : str | `file`\n            A set of files MediaWiki XML dump files\n            (expects: pages-meta-history)\n        extractors : `list`(`extractor`)\n            A list of extractors to apply to the text\n\n    :Returns:\n        `iterable` -- a generator of extracted cites"
  },
  {
    "code": "def read(self, n):\n        out = ctypes.create_string_buffer(n)\n        ctypes.windll.kernel32.RtlMoveMemory(out, self.view + self.pos, n)\n        self.pos += n\n        return out.raw",
    "docstring": "Read n bytes from mapped view."
  },
  {
    "code": "def get_context(namespace, context_id):\n    context_obj = get_state(context_id, namespace=namespace)\n    if not context_obj:\n        raise ContextError(\"Context '{}' not found in namespace '{}'\".format(\n            context_id, namespace))\n    return context_obj",
    "docstring": "Get stored context object."
  },
  {
    "code": "def main_pred_type(self, value):\n        if value not in operators:\n            value = operator_lkup.get(value)\n        if value:\n            self._main_pred_type = value\n            self.payload['predicate']['type'] = self._main_pred_type\n        else:\n            raise Exception(\"main predicate combiner not a valid operator\")",
    "docstring": "set main predicate combination type\n\n        :param value: (character) One of ``equals`` (``=``), ``and`` (``&``), ``or`` (``|``),\n        ``lessThan`` (``<``), ``lessThanOrEquals`` (``<=``), ``greaterThan`` (``>``),\n        ``greaterThanOrEquals`` (``>=``), ``in``, ``within``, ``not`` (``!``), ``like``"
  },
  {
    "code": "def get_diff_coeff(hvec, n=1):\n    hvec = np.array(hvec, dtype=np.float)\n    acc = len(hvec)\n    exp = np.column_stack([np.arange(acc)]*acc)\n    a = np.vstack([hvec] * acc) ** exp\n    b = np.zeros(acc)\n    b[n] = factorial(n)\n    return np.linalg.solve(a, b)",
    "docstring": "Helper function to find difference coefficients of an\n    derivative on an arbitrary mesh.\n\n    Args:\n        hvec (1D array-like): sampling stencil\n        n (int): degree of derivative to find"
  },
  {
    "code": "def convert_namespaces_str(\n    bel_str: str,\n    api_url: str = None,\n    namespace_targets: Mapping[str, List[str]] = None,\n    canonicalize: bool = False,\n    decanonicalize: bool = False,\n) -> str:\n    matches = re.findall(r'([A-Z]+:\"(?:\\\\.|[^\"\\\\])*\"|[A-Z]+:(?:[^\\),\\s]+))', bel_str)\n    for nsarg in matches:\n        if \"DEFAULT:\" in nsarg:\n            continue\n        updated_nsarg = convert_nsarg(\n            nsarg,\n            api_url=api_url,\n            namespace_targets=namespace_targets,\n            canonicalize=canonicalize,\n            decanonicalize=decanonicalize,\n        )\n        if updated_nsarg != nsarg:\n            bel_str = bel_str.replace(nsarg, updated_nsarg)\n    return bel_str",
    "docstring": "Convert namespace in string\n\n    Uses a regex expression to extract all NSArgs and replace them with the\n    updated NSArg from the BEL.bio API terms endpoint.\n\n    Args:\n        bel_str (str): bel statement string or partial string (e.g. subject or object)\n        api_url (str): BEL.bio api url to use, e.g. https://api.bel.bio/v1\n        namespace_targets (Mapping[str, List[str]]): formatted as in configuration file example\n        canonicalize (bool): use canonicalize endpoint/namespace targets\n        decanonicalize (bool): use decanonicalize endpoint/namespace targets\n\n    Results:\n        str: bel statement with namespaces converted"
  },
  {
    "code": "def update_script_from_item(self, item):\n        script, path_to_script, script_item = item.get_script()\n        dictator = list(script_item.to_dict().values())[0]\n        for instrument in list(script.instruments.keys()):\n            script.instruments[instrument]['settings'] = dictator[instrument]['settings']\n            del dictator[instrument]\n        for sub_script_name in list(script.scripts.keys()):\n            sub_script_item = script_item.get_subscript(sub_script_name)\n            self.update_script_from_item(sub_script_item)\n            del dictator[sub_script_name]\n        script.update(dictator)\n        script.data_path = self.gui_settings['data_folder']",
    "docstring": "updates the script based on the information provided in item\n\n        Args:\n            script: script to be updated\n            item: B26QTreeItem that contains the new settings of the script"
  },
  {
    "code": "def _is_numeric(self, values):\n        if len(values) > 0:\n            assert isinstance(values[0], (float, int)), \\\n                \"values must be numbers to perform math operations. Got {}\".format(\n                    type(values[0]))\n        return True",
    "docstring": "Check to be sure values are numbers before doing numerical operations."
  },
  {
    "code": "def force_process_ordered(self):\n        for instance_id, messages in self.replicas.take_ordereds_out_of_turn():\n            num_processed = 0\n            for message in messages:\n                self.try_processing_ordered(message)\n                num_processed += 1\n            logger.info('{} processed {} Ordered batches for instance {} '\n                        'before starting catch up'\n                        .format(self, num_processed, instance_id))",
    "docstring": "Take any messages from replica that have been ordered and process\n        them, this should be done rarely, like before catchup starts\n        so a more current LedgerStatus can be sent.\n        can be called either\n        1. when node is participating, this happens just before catchup starts\n        so the node can have the latest ledger status or\n        2. when node is not participating but a round of catchup is about to be\n        started, here is forces all the replica ordered messages to be appended\n        to the stashed ordered requests and the stashed ordered requests are\n        processed with appropriate checks"
  },
  {
    "code": "def __get_precipfc_data(latitude, longitude):\n    url = 'https://gpsgadget.buienradar.nl/data/raintext?lat={}&lon={}'\n    url = url.format(\n        round(latitude, 2),\n        round(longitude, 2)\n    )\n    result = __get_url(url)\n    return result",
    "docstring": "Get buienradar forecasted precipitation."
  },
  {
    "code": "def get_results_from_passive(self, scheduler_instance_id):\n        if not self.schedulers:\n            logger.debug(\"I do not have any scheduler: %s\", self.schedulers)\n            return []\n        scheduler_link = None\n        for link in list(self.schedulers.values()):\n            if scheduler_instance_id == link.instance_id:\n                scheduler_link = link\n                break\n        else:\n            logger.warning(\"I do not know this scheduler: %s\", scheduler_instance_id)\n            return []\n        logger.debug(\"Get results for the scheduler: %s\", scheduler_instance_id)\n        ret, scheduler_link.wait_homerun = scheduler_link.wait_homerun, {}\n        logger.debug(\"Results: %s\" % (list(ret.values())) if ret else \"No results available\")\n        return list(ret.values())",
    "docstring": "Get executed actions results from a passive satellite for a specific scheduler\n\n        :param scheduler_instance_id: scheduler id\n        :type scheduler_instance_id: int\n        :return: Results list\n        :rtype: list"
  },
  {
    "code": "def _init_idxs_int(self, usr_hdrs):\n        self.idxs_int = [\n            Idx for Hdr, Idx in self.hdr2idx.items() if Hdr in usr_hdrs and Hdr in self.int_hdrs]",
    "docstring": "List of indexes whose values will be ints."
  },
  {
    "code": "def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,\n                filter_type=None, **kwds):\n        delegate = self._values\n        if axis is not None:\n            self._get_axis_number(axis)\n        if isinstance(delegate, Categorical):\n            return delegate._reduce(name, numeric_only=numeric_only, **kwds)\n        elif isinstance(delegate, ExtensionArray):\n            return delegate._reduce(name, skipna=skipna, **kwds)\n        elif is_datetime64_dtype(delegate):\n            delegate = DatetimeIndex(delegate)\n        elif isinstance(delegate, np.ndarray):\n            if numeric_only:\n                raise NotImplementedError('Series.{0} does not implement '\n                                          'numeric_only.'.format(name))\n            with np.errstate(all='ignore'):\n                return op(delegate, skipna=skipna, **kwds)\n        return delegate._reduce(op=op, name=name, axis=axis, skipna=skipna,\n                                numeric_only=numeric_only,\n                                filter_type=filter_type, **kwds)",
    "docstring": "Perform a reduction operation.\n\n        If we have an ndarray as a value, then simply perform the operation,\n        otherwise delegate to the object."
  },
  {
    "code": "def distance(self, method='haversine'):\n        distances = []\n        for segment in self:\n            if len(segment) < 2:\n                distances.append([])\n            else:\n                distances.append(segment.distance(method))\n        return distances",
    "docstring": "Calculate distances between locations in segments.\n\n        Args:\n            method (str): Method used to calculate distance\n\n        Returns:\n            list of list of float: Groups of distance between points in\n                segments"
  },
  {
    "code": "def verifyUniqueWcsname(fname,wcsname):\n    uniq = True\n    numsci,extname = count_sci_extensions(fname)\n    wnames = altwcs.wcsnames(fname,ext=(extname,1))\n    if wcsname in wnames.values():\n        uniq = False\n    return uniq",
    "docstring": "Report whether or not the specified WCSNAME already exists in the file"
  },
  {
    "code": "def fastq_convert_pipe_cl(in_file, data):\n    cmd = _seqtk_fastq_prep_cl(data, in_file)\n    if not cmd:\n        cat_cmd = \"zcat\" if in_file.endswith(\".gz\") else \"cat\"\n        cmd = cat_cmd + \" \" + in_file\n    return \"<(%s)\" % cmd",
    "docstring": "Create an anonymous pipe converting Illumina 1.3-1.7 to Sanger.\n\n    Uses seqtk: https://github.com/lh3/seqt"
  },
  {
    "code": "def safe_temp_edit(filename):\n  with temporary_file() as tmp_file:\n    try:\n      shutil.copyfile(filename, tmp_file.name)\n      yield filename\n    finally:\n      shutil.copyfile(tmp_file.name, filename)",
    "docstring": "Safely modify a file within context that automatically reverts any changes afterwards\n\n  The file mutatation occurs in place. The file is backed up in a temporary file before edits\n  occur and when the context is closed, the mutated file is discarded and replaced with the backup.\n\n  WARNING: There may be a chance that the file may not be restored and this method should be used\n  carefully with the known risk."
  },
  {
    "code": "def ylogydu(y, u):\n    mask = (np.atleast_1d(y)!=0.)\n    out = np.zeros_like(u)\n    out[mask] = y[mask] * np.log(y[mask] / u[mask])\n    return out",
    "docstring": "tool to give desired output for the limit as y -> 0, which is 0\n\n    Parameters\n    ----------\n    y : array-like of len(n)\n    u : array-like of len(n)\n\n    Returns\n    -------\n    np.array len(n)"
  },
  {
    "code": "def steal(self, instr):\n        instr._stolen_by = self\n        for jmp in instr._target_of:\n            jmp.arg = self\n        self._target_of = instr._target_of\n        instr._target_of = set()\n        return self",
    "docstring": "Steal the jump index off of `instr`.\n\n        This makes anything that would have jumped to `instr` jump to\n        this Instruction instead.\n\n        Parameters\n        ----------\n        instr : Instruction\n            The instruction to steal the jump sources from.\n\n        Returns\n        -------\n        self : Instruction\n            The instruction that owns this method.\n\n        Notes\n        -----\n        This mutates self and ``instr`` inplace."
  },
  {
    "code": "def _runOPF(self):\n        if self.decommit:\n            solver = UDOPF(self.case, dc=(self.locationalAdjustment == \"dc\"))\n        elif self.locationalAdjustment == \"dc\":\n            solver = OPF(self.case, dc=True)\n        else:\n            solver = OPF(self.case, dc=False, opt={\"verbose\": True})\n        self._solution = solver.solve()\n        return self._solution[\"converged\"]",
    "docstring": "Computes dispatch points and LMPs using OPF."
  },
  {
    "code": "def rectangle(self):\n        if self.start_point is None or self.end_point is None:\n            return QgsRectangle()\n        elif self.start_point.x() == self.end_point.x() or \\\n                self.start_point.y() == self.end_point.y():\n            return QgsRectangle()\n        return QgsRectangle(self.start_point, self.end_point)",
    "docstring": "Accessor for the rectangle.\n\n        :return: A rectangle showing the designed extent.\n        :rtype: QgsRectangle"
  },
  {
    "code": "def contains_container(self, path):\n        path = make_path(path)\n        try:\n            self.get_container(path)\n            return True\n        except KeyError:\n            return False",
    "docstring": "Returns True if a container exists at the specified path,\n        otherwise False.\n\n        :param path: str or Path instance\n        :return:\n        :rtype: bool\n        :raises ValueError: A component of path is a field name."
  },
  {
    "code": "def abi_splitext(filename):\n    filename = os.path.basename(filename)\n    is_ncfile = False\n    if filename.endswith(\".nc\"):\n        is_ncfile = True\n        filename = filename[:-3]\n    known_extensions = abi_extensions()\n    for i in range(len(filename)-1, -1, -1):\n        ext = filename[i:]\n        if ext in known_extensions:\n            break\n    else:\n        raise ValueError(\"Cannot find a registered extension in %s\" % filename)\n    root = filename[:i]\n    if is_ncfile:\n        ext += \".nc\"\n    return root, ext",
    "docstring": "Split the ABINIT extension from a filename.\n    \"Extension\" are found by searching in an internal database.\n\n    Returns \"(root, ext)\" where ext is the registered ABINIT extension\n    The final \".nc\" is included (if any)\n\n    >>> assert abi_splitext(\"foo_WFK\") == ('foo_', 'WFK')\n    >>> assert abi_splitext(\"/home/guido/foo_bar_WFK.nc\") == ('foo_bar_', 'WFK.nc')"
  },
  {
    "code": "def setup():\n    global _displayhooks, _excepthooks\n    if _displayhooks is not None:\n        return\n    _displayhooks = []\n    _excepthooks = []\n    if sys.displayhook != sys.__displayhook__:\n        _displayhooks.append(weakref.ref(sys.displayhook))\n    if sys.excepthook != sys.__excepthook__:\n        _excepthooks.append(weakref.ref(sys.excepthook))\n    sys.displayhook = displayhook\n    sys.excepthook = excepthook",
    "docstring": "Initializes the hook queues for the sys module.  This method will\n    automatically be called on the first registration for a hook to the system\n    by either the registerDisplay or registerExcept functions."
  },
  {
    "code": "def _add_edge(self, source, target, **kwargs):\n        edge_properties = self.edge_properties\n        for k, v in kwargs.items():\n            edge_properties[k] = v\n        self.graph.add_edge(source, target, **edge_properties)",
    "docstring": "Add an edge to the graph."
  },
  {
    "code": "def getDayStart(self, dateTime):\n        return ensure_localtime(dateTime).replace(hour=0,minute=0,second=0,microsecond=0)",
    "docstring": "Ensure local time and get the beginning of the day"
  },
  {
    "code": "def configure(self, settings_module=None, **kwargs):\n        default_settings.reload()\n        environment_var = self._kwargs.get(\n            \"ENVVAR_FOR_DYNACONF\", default_settings.ENVVAR_FOR_DYNACONF\n        )\n        settings_module = settings_module or os.environ.get(environment_var)\n        compat_kwargs(kwargs)\n        kwargs.update(self._kwargs)\n        self._wrapped = Settings(settings_module=settings_module, **kwargs)\n        self.logger.debug(\"Lazy Settings configured ...\")",
    "docstring": "Allows user to reconfigure settings object passing a new settings\n        module or separated kwargs\n\n        :param settings_module: defines the setttings file\n        :param kwargs:  override default settings"
  },
  {
    "code": "def fetch_alien(self, ):\n        parent = self.get_parent()\n        if parent:\n            parentelement = parent.get_element()\n        else:\n            parentelement = self.get_refobjinter().get_current_element()\n            if not parentelement:\n                self._alien = True\n                return self._alien\n        element = self.get_element()\n        if element == parentelement:\n            self._alien = False\n        elif isinstance(element, djadapter.models.Shot)\\\n            and (element.sequence.name == djadapter.GLOBAL_NAME\\\n            or (isinstance(parentelement, djadapter.models.Shot)\\\n                and parentelement.sequence == element.sequence and element.name == djadapter.GLOBAL_NAME)):\n            self._alien = False\n        else:\n            assets = parentelement.assets.all()\n            self._alien = element not in assets\n        return self._alien",
    "docstring": "Set and return, if the reftrack element is linked to the current scene.\n\n        Askes the refobj interface for the current scene.\n        If there is no current scene then True is returned.\n\n        :returns: whether the element is linked to the current scene\n        :rtype: bool\n        :raises: None"
  },
  {
    "code": "def get(self, instance_name):\n        url = self._url + instance_name + '/'\n        response = requests.get(url, **self._default_request_kwargs)\n        data = self._get_response_data(response)\n        return self._concrete_instance(data)",
    "docstring": "Get an ObjectRocket instance by name.\n\n        :param str instance_name: The name of the instance to retrieve.\n        :returns: A subclass of :py:class:`bases.BaseInstance`, or None if instance does not exist.\n        :rtype: :py:class:`bases.BaseInstance`"
  },
  {
    "code": "def encrypt(self, pubkey: str, nonce: Union[str, bytes], text: Union[str, bytes]) -> str:\n        text_bytes = ensure_bytes(text)\n        nonce_bytes = ensure_bytes(nonce)\n        recipient_pubkey = PublicKey(pubkey)\n        crypt_bytes = libnacl.public.Box(self, recipient_pubkey).encrypt(text_bytes, nonce_bytes)\n        return Base58Encoder.encode(crypt_bytes[24:])",
    "docstring": "Encrypt message text with the public key of the recipient and a nonce\n\n        The nonce must be a 24 character string (you can use libnacl.utils.rand_nonce() to get one)\n        and unique for each encrypted message.\n\n        Return base58 encoded encrypted message\n\n        :param pubkey: Base58 encoded public key of the recipient\n        :param nonce: Unique nonce\n        :param text: Message to encrypt\n        :return:"
  },
  {
    "code": "def reverse_point(self, latitude, longitude, **kwargs):\n        fields = \",\".join(kwargs.pop(\"fields\", []))\n        point_param = \"{0},{1}\".format(latitude, longitude)\n        response = self._req(\n            verb=\"reverse\", params={\"q\": point_param, \"fields\": fields}\n        )\n        if response.status_code != 200:\n            return error_response(response)\n        return Location(response.json())",
    "docstring": "Method for identifying an address from a geographic point"
  },
  {
    "code": "def count_relations(graph) -> Counter:\n    return Counter(\n        data[RELATION]\n        for _, _, data in graph.edges(data=True)\n    )",
    "docstring": "Return a histogram over all relationships in a graph.\n\n    :param pybel.BELGraph graph: A BEL graph\n    :return: A Counter from {relation type: frequency}"
  },
  {
    "code": "def lookup_deleted_folder(event, filesystem, journal):\n    folder_events = (e for e in journal[event.parent_inode]\n                     if 'DIRECTORY' in e.attributes\n                     and 'FILE_DELETE' in e.changes)\n    for folder_event in folder_events:\n        path = lookup_deleted_folder(folder_event, filesystem, journal)\n        return ntpath.join(path, event.name)\n    return lookup_folder(event, filesystem)",
    "docstring": "Lookup the parent folder in the journal content."
  },
  {
    "code": "def _attributeStr(self, name):\n        return \"{}={}\".format(\n            _encodeAttr(name),\n            \",\".join([_encodeAttr(v) for v in self.attributes[name]]))",
    "docstring": "Return name=value for a single attribute"
  },
  {
    "code": "def play(cls, file_path, on_done=None, logger=None):\n        pygame.mixer.init()\n        try:\n            pygame.mixer.music.load(file_path)\n        except pygame.error as e:\n            if logger is not None:\n                logger.warning(str(e))\n            return\n        pygame.mixer.music.play()\n        while pygame.mixer.music.get_busy():\n            time.sleep(0.1)\n            continue\n        if on_done:\n            on_done()",
    "docstring": "Play an audio file.\n\n        :param file_path: the path to the file to play.\n        :param on_done: callback when audio playback completes."
  },
  {
    "code": "def dAbr_dV(dSf_dVa, dSf_dVm, dSt_dVa, dSt_dVm, Sf, St):\n    dAf_dPf = spdiag(2 * Sf.real())\n    dAf_dQf = spdiag(2 * Sf.imag())\n    dAt_dPt = spdiag(2 * St.real())\n    dAt_dQt = spdiag(2 * St.imag())\n    dAf_dVa = dAf_dPf * dSf_dVa.real() + dAf_dQf * dSf_dVa.imag()\n    dAt_dVa = dAt_dPt * dSt_dVa.real() + dAt_dQt * dSt_dVa.imag()\n    dAf_dVm = dAf_dPf * dSf_dVm.real() + dAf_dQf * dSf_dVm.imag()\n    dAt_dVm = dAt_dPt * dSt_dVm.real() + dAt_dQt * dSt_dVm.imag()\n    return dAf_dVa, dAf_dVm, dAt_dVa, dAt_dVm",
    "docstring": "Partial derivatives of squared flow magnitudes w.r.t voltage.\n\n        Computes partial derivatives of apparent power w.r.t active and\n        reactive power flows.  Partial derivative must equal 1 for lines\n        with zero flow to avoid division by zero errors (1 comes from\n        L'Hopital)."
  },
  {
    "code": "def get(self, path, params=None):\n        r = requests.get(url=self.url + path, params=params, timeout=self.timeout)\n        r.raise_for_status()\n        return r.json()",
    "docstring": "Perform GET request"
  },
  {
    "code": "def block(self):\n        if (self.is_actinoid or self.is_lanthanoid) and self.Z not in [71, 103]:\n            return \"f\"\n        elif self.is_actinoid or self.is_lanthanoid:\n            return \"d\"\n        elif self.group in [1, 2]:\n            return \"s\"\n        elif self.group in range(13, 19):\n            return \"p\"\n        elif self.group in range(3, 13):\n            return \"d\"\n        raise ValueError(\"unable to determine block\")",
    "docstring": "Return the block character \"s,p,d,f\""
  },
  {
    "code": "def detect_timezone():\n  if sys.platform == \"win32\":\n    tz = _detect_timezone_windows()\n    if tz is not None:\n      return tz\n  tz = _detect_timezone_environ()\n  if tz is not None:\n    return tz\n  tz = _detect_timezone_etc_timezone()\n  if tz is not None:\n    return tz\n  tz = _detect_timezone_etc_localtime()\n  if tz is not None:\n    return tz\n  warnings.warn(\"Had to fall back to worst detection method (the 'PHP' \"\n                \"method).\")\n  tz = _detect_timezone_php()\n  if tz is not None:\n    return tz\n  raise pytz.UnknownTimeZoneError(\"Unable to detect your timezone!\")",
    "docstring": "Try and detect the timezone that Python is currently running in.\n\n  We have a bunch of different methods for trying to figure this out (listed in\n  order they are attempted).\n    * In windows, use win32timezone.TimeZoneInfo.local()\n    * Try TZ environment variable.\n    * Try and find /etc/timezone file (with timezone name).\n    * Try and find /etc/localtime file (with timezone data).\n    * Try and match a TZ to the current dst/offset/shortname.\n\n  Returns:\n    The detected local timezone as a tzinfo object\n\n  Raises:\n    pytz.UnknownTimeZoneError: If it was unable to detect a timezone."
  },
  {
    "code": "def loadImageData(filename, spacing=()):\n    if not os.path.isfile(filename):\n        colors.printc(\"~noentry File not found:\", filename, c=1)\n        return None\n    if \".tif\" in filename.lower():\n        reader = vtk.vtkTIFFReader()\n    elif \".slc\" in filename.lower():\n        reader = vtk.vtkSLCReader()\n        if not reader.CanReadFile(filename):\n            colors.printc(\"~prohibited Sorry bad slc file \" + filename, c=1)\n            exit(1)\n    elif \".vti\" in filename.lower():\n        reader = vtk.vtkXMLImageDataReader()\n    elif \".mhd\" in filename.lower():\n        reader = vtk.vtkMetaImageReader()\n    reader.SetFileName(filename)\n    reader.Update()\n    image = reader.GetOutput()\n    if len(spacing) == 3:\n        image.SetSpacing(spacing[0], spacing[1], spacing[2])\n    return image",
    "docstring": "Read and return a ``vtkImageData`` object from file."
  },
  {
    "code": "def get_avatar_metadata(self, jid, *, require_fresh=False,\n                            disable_pep=False):\n        if require_fresh:\n            self._metadata_cache.pop(jid, None)\n        else:\n            try:\n                return self._metadata_cache[jid]\n            except KeyError:\n                pass\n        if disable_pep:\n            metadata = []\n        else:\n            metadata = yield from self._get_avatar_metadata_pep(jid)\n        if not metadata and jid not in self._has_pep_avatar:\n            metadata = yield from self._get_avatar_metadata_vcard(jid)\n        if jid not in self._metadata_cache:\n            self._update_metadata(jid, metadata)\n        return self._metadata_cache[jid]",
    "docstring": "Retrieve a list of avatar descriptors.\n\n        :param jid: the JID for which to retrieve the avatar metadata.\n        :type jid: :class:`aioxmpp.JID`\n        :param require_fresh: if true, do not return results from the\n            avatar metadata chache, but retrieve them again from the server.\n        :type require_fresh: :class:`bool`\n        :param disable_pep: if true, do not try to retrieve the avatar\n            via pep, only try the vCard fallback. This usually only\n            useful when querying avatars via MUC, where the PEP request\n            would be invalid (since it would be for a full jid).\n        :type disable_pep: :class:`bool`\n\n        :returns: an iterable of avatar descriptors.\n        :rtype: a :class:`list` of\n            :class:`~aioxmpp.avatar.service.AbstractAvatarDescriptor`\n            instances\n\n        Returning an empty list means that the avatar not set.\n\n        We mask a :class:`XMPPCancelError` in the case that it is\n        ``feature-not-implemented`` or ``item-not-found`` and return\n        an empty list of avatar descriptors, since this is\n        semantically equivalent to not having an avatar.\n\n        .. note::\n\n           It is usually an error to get the avatar for a full jid,\n           normally, the avatar is set for the bare jid of a user. The\n           exception are vCard avatars over MUC, where the IQ requests\n           for the vCard may be translated by the MUC server. It is\n           recommended to use the `disable_pep` option in that case."
  },
  {
    "code": "def is_unclaimed(work):\n  if work['is_completed']:\n    return False\n  cutoff_time = time.time() - MAX_PROCESSING_TIME\n  if (work['claimed_worker_id'] and\n      work['claimed_worker_start_time'] is not None\n      and work['claimed_worker_start_time'] >= cutoff_time):\n    return False\n  return True",
    "docstring": "Returns True if work piece is unclaimed."
  },
  {
    "code": "def smart_reroot(treefile, outgroupfile, outfile, format=0):\n    tree = Tree(treefile, format=format)\n    leaves = [t.name for t in tree.get_leaves()][::-1]\n    outgroup = []\n    for o in must_open(outgroupfile):\n        o = o.strip()\n        for leaf in leaves:\n            if leaf[:len(o)] == o:\n                outgroup.append(leaf)\n        if outgroup:\n            break\n    if not outgroup:\n        print(\"Outgroup not found. Tree {0} cannot be rerooted.\".format(treefile), file=sys.stderr)\n        return treefile\n    try:\n        tree.set_outgroup(tree.get_common_ancestor(*outgroup))\n    except ValueError:\n        assert type(outgroup) == list\n        outgroup = outgroup[0]\n        tree.set_outgroup(outgroup)\n    tree.write(outfile=outfile, format=format)\n    logging.debug(\"Rerooted tree printed to {0}\".format(outfile))\n    return outfile",
    "docstring": "simple function to reroot Newick format tree using ete2\n\n    Tree reading format options see here:\n    http://packages.python.org/ete2/tutorial/tutorial_trees.html#reading-newick-trees"
  },
  {
    "code": "def start_cluster_server(self, num_gpus=1, rdma=False):\n    return TFNode.start_cluster_server(self, num_gpus, rdma)",
    "docstring": "Convenience function to access ``TFNode.start_cluster_server`` directly from this object instance."
  },
  {
    "code": "def tkvrsn(item):\n    item = stypes.stringToCharP(item)\n    return stypes.toPythonString(libspice.tkvrsn_c(item))",
    "docstring": "Given an item such as the Toolkit or an entry point name, return\n    the latest version string.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tkvrsn_c.html\n\n    :param item: Item for which a version string is desired.\n    :type item: str\n    :return: the latest version string.\n    :rtype: str"
  },
  {
    "code": "def _load_image(cls, rkey):\n        v = cls._stock[rkey]\n        img = None\n        itype = v['type']\n        if itype in ('stock', 'data'):\n            img = tk.PhotoImage(format=v['format'], data=v['data'])\n        elif itype == 'created':\n            img = v['image']\n        else:\n            img = tk.PhotoImage(file=v['filename'])\n        cls._cached[rkey] = img\n        logger.info('Loaded resource %s.' % rkey)\n        return img",
    "docstring": "Load image from file or return the cached instance."
  },
  {
    "code": "def get_data(self):\n        \"Return one SNMP response list for all status OIDs, and one list for all metric OIDs.\"\n        alarm_oids = [netsnmp.Varbind(status_mib[alarm_id]['oid']) for alarm_id in self.models[self.modem_type]['alarms']]\n        metric_oids = [netsnmp.Varbind(metric_mib[metric_id]['oid']) for metric_id in self.models[self.modem_type]['metrics']]\n        response = self.snmp_session.get(netsnmp.VarList(*alarm_oids + metric_oids))\n        return (\n            response[0:len(alarm_oids)],\n            response[len(alarm_oids):]\n        )",
    "docstring": "Return one SNMP response list for all status OIDs, and one list for all metric OIDs."
  },
  {
    "code": "def get_bookmarks(self, folder='unread', limit=25, have=None):\n        path = 'bookmarks/list'\n        params = {'folder_id': folder, 'limit': limit}\n        if have:\n            have_concat = ','.join(str(id_) for id_ in have)\n            params['have'] = have_concat\n        response = self.request(path, params)\n        items = response['data']\n        bookmarks = []\n        for item in items:\n            if item.get('type') == 'error':\n                raise Exception(item.get('message'))\n            elif item.get('type') == 'bookmark':\n                bookmarks.append(Bookmark(self, **item))\n        return bookmarks",
    "docstring": "Return list of user's bookmarks.\n\n        :param str folder: Optional. Possible values are unread (default),\n            starred, archive, or a folder_id value.\n        :param int limit: Optional. A number between 1 and 500, default 25.\n        :param list have: Optional. A list of IDs to exclude from results\n        :returns: List of user's bookmarks\n        :rtype: list"
  },
  {
    "code": "def exists(name, region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    try:\n        exists = conn.describe_stacks(name)\n        log.debug('Stack %s exists.', name)\n        return True\n    except BotoServerError as e:\n        log.debug('boto_cfn.exists raised an exception', exc_info=True)\n        return False",
    "docstring": "Check to see if a stack exists.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_cfn.exists mystack region=us-east-1"
  },
  {
    "code": "def build_groups(self, tokens):\n        groups = {}\n        for token in tokens:\n            match_type = MatchType.start if token.group_end else MatchType.single\n            groups[token.group_start] = (token, match_type)\n            if token.group_end:\n                groups[token.group_end] = (token, MatchType.end)\n        return groups",
    "docstring": "Build dict of groups from list of tokens"
  },
  {
    "code": "def find_files(self):\n\t\tall_files = self._invoke('locate', '-I', '.').splitlines()\n\t\tfrom_root = os.path.relpath(self.location, self.find_root())\n\t\tloc_rel_paths = [\n\t\t\tos.path.relpath(path, from_root)\n\t\t\tfor path in all_files]\n\t\treturn loc_rel_paths",
    "docstring": "Find versioned files in self.location"
  },
  {
    "code": "def parse_magmoms(self, data, lattice=None):\n        if lattice is None:\n            raise Exception(\n                'Magmoms given in terms of crystal axes in magCIF spec.')\n        try:\n            magmoms = {\n                data[\"_atom_site_moment_label\"][i]:\n                    np.array(\n                        [str2float(data[\"_atom_site_moment_crystalaxis_x\"][i]),\n                         str2float(data[\"_atom_site_moment_crystalaxis_y\"][i]),\n                         str2float(data[\"_atom_site_moment_crystalaxis_z\"][i])]\n                    )\n                for i in range(len(data[\"_atom_site_moment_label\"]))\n            }\n        except (ValueError, KeyError):\n            return None\n        return magmoms",
    "docstring": "Parse atomic magnetic moments from data dictionary"
  },
  {
    "code": "def data_url(self, image_format='png', add_quiet_zone=True):\n        memory_file = io.BytesIO()\n        pil_image = self.image(add_quiet_zone=add_quiet_zone)\n        if image_format == 'png':\n            pil_image.save(memory_file, format='png', compress_level=1)\n        elif image_format == 'bmp':\n            pil_image.save(memory_file, format='bmp')\n        else:\n            raise Code128.UnknownFormatError('Only png and bmp are supported.')\n        base64_image = base64.b64encode(memory_file.getvalue()).decode('ascii')\n        data_url = 'data:image/{format};base64,{base64_data}'.format(\n            format=image_format,\n            base64_data=base64_image\n        )\n        return data_url",
    "docstring": "Get a data URL representing the barcode.\n\n        >>> barcode = Code128('Hello!', charset='B')\n        >>> barcode.data_url()  # doctest: +ELLIPSIS\n        'data:image/png;base64,...'\n\n        :param image_format: Either 'png' or 'bmp'.\n        :param add_quiet_zone: Add a 10 white pixels on either side of the barcode.\n\n        :raises: Code128.UnknownFormatError\n        :raises: Code128.MissingDependencyError\n\n        :rtype: str\n        :returns: A data URL with the barcode as an image."
  },
  {
    "code": "def app_score(self):\n        precisions, pct_pred_pos, taus = self.precision_pct_pred_pos_curve(interval=False)\n        app = 0\n        total = 0\n        for k in range(len(precisions)-1):\n            cur_prec = precisions[k]\n            cur_pp = pct_pred_pos[k]\n            cur_tau = taus[k]\n            next_prec = precisions[k+1]\n            next_pp = pct_pred_pos[k+1]\n            next_tau = taus[k+1]\n            mid_prec = (cur_prec + next_prec) / 2.0\n            width_pp = np.abs(next_pp - cur_pp)\n            app += mid_prec * width_pp\n            total += width_pp\n        return app",
    "docstring": "Computes the area under the app curve."
  },
  {
    "code": "def load_all_yamls(cls, directories):\n        yaml_files = []\n        loaded_yamls = {}\n        for d in directories:\n            if d.startswith('/home') and not os.path.exists(d):\n                os.makedirs(d)\n            for dirname, subdirs, files in os.walk(d):\n                yaml_files.extend(map(lambda x: os.path.join(dirname, x),\n                                      filter(lambda x: x.endswith('.yaml'), files)))\n        for f in yaml_files:\n            loaded_yamls[f] = cls.load_yaml_by_path(f)\n        return loaded_yamls",
    "docstring": "Loads yaml files from all given directories.\n\n        Args:\n            directories: list of directories to search\n        Returns:\n            dict of {fullpath: loaded_yaml_structure}"
  },
  {
    "code": "def is_client(self):\n        return (self.args.client or self.args.browser) and not self.args.server",
    "docstring": "Return True if Glances is running in client mode."
  },
  {
    "code": "def count_lines(fname, mode='rU'):\n    with open(fname, mode) as f:\n        for i, l in enumerate(f):\n            pass\n    return i + 1",
    "docstring": "Count the number of lines in a file\n\n    Only faster way would be to utilize multiple processor cores to perform parallel reads.\n    http://stackoverflow.com/q/845058/623735"
  },
  {
    "code": "def timeit(method):\n    import datetime\n    @functools.wraps(method)\n    def timed_method(self, rinput):\n        time_start = datetime.datetime.utcnow()\n        result = method(self, rinput)\n        time_end = datetime.datetime.utcnow()\n        result.time_it(time_start, time_end)\n        self.logger.info('total time measured')\n        return result\n    return timed_method",
    "docstring": "Decorator to measure the time used by the recipe"
  },
  {
    "code": "def all():\n    return [goal for _, goal in sorted(Goal._goal_by_name.items()) if goal.active]",
    "docstring": "Returns all active registered goals, sorted alphabetically by name.\n\n    :API: public"
  },
  {
    "code": "def url_to_image(url, flag=cv2.IMREAD_COLOR):\n    resp = urlopen(url)\n    image = np.asarray(bytearray(resp.read()), dtype=\"uint8\")\n    image = cv2.imdecode(image, flag)\n    return image",
    "docstring": "download the image, convert it to a NumPy array, and then read\n    it into OpenCV format"
  },
  {
    "code": "def _reset_suffix_links(self):\n        self._suffix_links_set = False\n        for current, _parent in self.dfs():\n            current.suffix = None\n            current.dict_suffix = None\n            current.longest_prefix = None",
    "docstring": "Reset all suffix links in all nodes in this trie."
  },
  {
    "code": "def edit_dataset_metadata(request, dataset_id=None):\n    if request.method == 'POST':\n        return add_dataset(request, dataset_id)\n    elif request.method == 'GET':\n        if dataset_id:\n            metadata_form = DatasetUploadForm(\n                instance=get_object_or_404(Dataset, pk=dataset_id)\n            )\n        else:\n            metadata_form = DatasetUploadForm()\n        return render(\n            request,\n            'datafreezer/upload.html',\n            {\n                'fileUploadForm': metadata_form,\n            }\n        )",
    "docstring": "Renders a template to upload or edit a Dataset.\n\n    Most of the heavy lifting is done by add_dataset(...)."
  },
  {
    "code": "def rssi_bars(self) -> int:\n        rssi_db = self.rssi_db\n        if rssi_db < 45:\n            return 0\n        elif rssi_db < 60:\n            return 1\n        elif rssi_db < 75:\n            return 2\n        elif rssi_db < 90:\n            return 3\n        return 4",
    "docstring": "Received Signal Strength Indication, from 0 to 4 bars."
  },
  {
    "code": "def add_feature(feature,\n                package=None,\n                source=None,\n                limit_access=False,\n                enable_parent=False,\n                image=None,\n                restart=False):\n    cmd = ['DISM',\n           '/Quiet',\n           '/Image:{0}'.format(image) if image else '/Online',\n           '/Enable-Feature',\n           '/FeatureName:{0}'.format(feature)]\n    if package:\n        cmd.append('/PackageName:{0}'.format(package))\n    if source:\n        cmd.append('/Source:{0}'.format(source))\n    if limit_access:\n        cmd.append('/LimitAccess')\n    if enable_parent:\n        cmd.append('/All')\n    if not restart:\n        cmd.append('/NoRestart')\n    return __salt__['cmd.run_all'](cmd)",
    "docstring": "Install a feature using DISM\n\n    Args:\n        feature (str): The feature to install\n        package (Optional[str]): The parent package for the feature. You do not\n            have to specify the package if it is the Windows Foundation Package.\n            Otherwise, use package to specify the parent package of the feature\n        source (Optional[str]): The optional source of the capability. Default\n            is set by group policy and can be Windows Update\n        limit_access (Optional[bool]): Prevent DISM from contacting Windows\n            Update for the source package\n        enable_parent (Optional[bool]): True will enable all parent features of\n            the specified feature\n        image (Optional[str]): The path to the root directory of an offline\n            Windows image. If `None` is passed, the running operating system is\n            targeted. Default is None.\n        restart (Optional[bool]): Reboot the machine if required by the install\n\n    Returns:\n        dict: A dictionary containing the results of the command\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' dism.add_feature NetFx3"
  },
  {
    "code": "def sort(self, key, reverse=False, none_greater=False):\n        for i in range(0, len(self.table)):\n            min = i\n            for j in range(i + 1, len(self.table)):\n                if internal.is_first_lessor(self.table[j], self.table[min], key, none_greater=none_greater, reverse=reverse):\n                    min = j\n            if i!=min:\n                self.table[i], self.table[min] = self.table[min], self.table[i]\n                self.index_track[i], self.index_track[min] = self.index_track[min], self.index_track[i]\n        return self",
    "docstring": "Sort the list in the order of the dictionary key.\n\n        Example of use:\n\n        >>> test = [\n        ...    {\"name\": \"Jim\",   \"age\": 18, \"income\": 93000, \"wigs\": 68       },\n        ...    {\"name\": \"Larry\", \"age\": 18,                  \"wigs\": [3, 2, 9]},\n        ...    {\"name\": \"Joe\",   \"age\": 20, \"income\": 15000, \"wigs\": [1, 2, 3]},\n        ...    {\"name\": \"Bill\",  \"age\": 19, \"income\": 29000                   },\n        ... ]\n        >>> print PLOD(test).sort(\"name\").returnString()\n        [\n            {age: 19, income: 29000, name: 'Bill' , wigs: None     },\n            {age: 18, income: 93000, name: 'Jim'  , wigs:        68},\n            {age: 20, income: 15000, name: 'Joe'  , wigs: [1, 2, 3]},\n            {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]}\n        ]\n        >>> print PLOD(test).sort(\"income\").returnString()\n        [\n            {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]},\n            {age: 20, income: 15000, name: 'Joe'  , wigs: [1, 2, 3]},\n            {age: 19, income: 29000, name: 'Bill' , wigs: None     },\n            {age: 18, income: 93000, name: 'Jim'  , wigs:        68}\n        ]\n        >>> print PLOD(test).sort([\"age\", \"income\"]).returnString()\n        [\n            {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]},\n            {age: 18, income: 93000, name: 'Jim'  , wigs:        68},\n            {age: 19, income: 29000, name: 'Bill' , wigs: None     },\n            {age: 20, income: 15000, name: 'Joe'  , wigs: [1, 2, 3]}\n        ]\n        \n        .. versionadded:: 0.0.2\n        \n        :param key:\n           A dictionary key (or a list of keys) that should be the\n           basis of the sorting.\n        :param reverse:\n           Defaults to False. If True, then list is sorted decrementally.\n        :param none_greater:\n           Defaults to False. If True, then entries missing the key/value\n           pair are considered be of greater value than the non-missing values.\n        :returns: self"
  },
  {
    "code": "def gammaVectorRDD(sc, shape, scale, numRows, numCols, numPartitions=None, seed=None):\n        return callMLlibFunc(\"gammaVectorRDD\", sc._jsc, float(shape), float(scale),\n                             numRows, numCols, numPartitions, seed)",
    "docstring": "Generates an RDD comprised of vectors containing i.i.d. samples drawn\n        from the Gamma distribution.\n\n        :param sc: SparkContext used to create the RDD.\n        :param shape: Shape (> 0) of the Gamma distribution\n        :param scale: Scale (> 0) of the Gamma distribution\n        :param numRows: Number of Vectors in the RDD.\n        :param numCols: Number of elements in each Vector.\n        :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n        :param seed: Random seed (default: a random long integer).\n        :return: RDD of Vector with vectors containing i.i.d. samples ~ Gamma(shape, scale).\n\n        >>> import numpy as np\n        >>> from math import sqrt\n        >>> shape = 1.0\n        >>> scale = 2.0\n        >>> expMean = shape * scale\n        >>> expStd = sqrt(shape * scale * scale)\n        >>> mat = np.matrix(RandomRDDs.gammaVectorRDD(sc, shape, scale, 100, 100, seed=1).collect())\n        >>> mat.shape\n        (100, 100)\n        >>> abs(mat.mean() - expMean) < 0.1\n        True\n        >>> abs(mat.std() - expStd) < 0.1\n        True"
  },
  {
    "code": "def unicode_urlencode(query, doseq=True):\n    pairs = []\n    for key, value in query.items():\n        if isinstance(value, list):\n            value = list(map(to_utf8, value))\n        else:\n            value = to_utf8(value)\n        pairs.append((to_utf8(key), value))\n    encoded_query = dict(pairs)\n    xx = urlencode(encoded_query, doseq)\n    return xx",
    "docstring": "Custom wrapper around urlencode to support unicode\n\n    Python urlencode doesn't handle unicode well so we need to convert to\n    bytestrings before using it:\n    http://stackoverflow.com/questions/6480723/urllib-urlencode-doesnt-like-unicode-values-how-about-this-workaround"
  },
  {
    "code": "def append_sint32(self, value):\n        zigzag_value = wire_format.zig_zag_encode(value)\n        self._stream.append_var_uint32(zigzag_value)",
    "docstring": "Appends a 32-bit integer to our buffer, zigzag-encoded and then\n        varint-encoded."
  },
  {
    "code": "def describe_cache_parameters(name=None, conn=None, region=None, key=None, keyid=None,\n                              profile=None, **args):\n    ret = {}\n    generic = _describe_resource(name=name, name_param='CacheParameterGroupName',\n                                  res_type='cache_parameter', info_node='Parameters',\n                                  conn=conn, region=region, key=key, keyid=keyid, profile=profile,\n                                  **args)\n    specific = _describe_resource(name=name, name_param='CacheParameterGroupName',\n                                  res_type='cache_parameter',\n                                  info_node='CacheNodeTypeSpecificParameters', conn=conn,\n                                  region=region, key=key, keyid=keyid, profile=profile, **args)\n    ret.update({'Parameters': generic}) if generic else None\n    ret.update({'CacheNodeTypeSpecificParameters': specific}) if specific else None\n    return ret",
    "docstring": "Returns the detailed parameter list for a particular cache parameter group.\n\n    name\n        The name of a specific cache parameter group to return details for.\n\n    CacheParameterGroupName\n        The name of a specific cache parameter group to return details for.  Generally not\n        required, as `name` will be used if not provided.\n\n    Source\n        Optionally, limit the parameter types to return.\n        Valid values:\n        - user\n        - system\n        - engine-default\n\n    Example:\n\n    .. code-block:: bash\n\n        salt myminion boto3_elasticache.describe_cache_parameters name=myParamGroup Source=user"
  },
  {
    "code": "def fetch_data(self):\n        choices = self.available_data\n        choices.insert(0, 'All')\n        selected_data_type = utils.select_item(\n            choices,\n            'Please select what data to fetch:',\n            'Available data:',\n        )\n        if selected_data_type == 'All':\n            selected_data_type = ','.join(self.available_data)\n        utils.pending_message('Performing fetch data task...')\n        fetch_data_task = self.client.data(\n            account=self.account,\n            data=selected_data_type,\n        )\n        fetch_data_task.wait_for_result(timeout=self.timeout)\n        fetch_data_result = json.loads(fetch_data_task.result)\n        task_id = fetch_data_task.uuid\n        filepath = utils.get_or_create_filepath('%s.json' % task_id)\n        with open(filepath, 'w') as out:\n            json.dump(fetch_data_result, out, indent=2)\n        utils.info_message('Fetch data successful. Output file: %s.json' % task_id)\n        return fetch_data_result",
    "docstring": "Prompt for a data type choice and execute the `fetch_data` task.\n        The results are saved to a file in json format."
  },
  {
    "code": "def Unequal(*xs, simplify=True):\n    xs = [Expression.box(x).node for x in xs]\n    y = exprnode.not_(exprnode.eq(*xs))\n    if simplify:\n        y = y.simplify()\n    return _expr(y)",
    "docstring": "Expression inequality operator\n\n    If *simplify* is ``True``, return a simplified expression."
  },
  {
    "code": "def _encode_dict_as_string(value):\n        if value.startswith(\"{\\n\"):\n            value = \"{\" + value[2:]\n        if value.endswith(\"\\n}\"):\n            value = value[:-2] + \"}\"\n        return value.replace('\"', '\\\\\"').replace(\"\\\\n\", \"\\\\\\\\n\").replace(\"\\n\", \"\\\\n\")",
    "docstring": "Takes the PLIST string of a dict, and returns the same string\n        encoded such that it can be included in the string representation\n        of a GSNode."
  },
  {
    "code": "def handle_login_failure(self, provider, reason):\n        logger.error('Authenication Failure: {0}'.format(reason))\n        messages.error(self.request, 'Authenication Failed. Please try again')\n        return redirect(self.get_error_redirect(provider, reason))",
    "docstring": "Message user and redirect on error."
  },
  {
    "code": "def update(self, cont):\n        self.max_time = max(self.max_time, cont.max_time)\n        if cont.items is not None:\n            if self.items is None:\n                self.items = cont.items\n            else:\n                self.items.update(cont.items)",
    "docstring": "Update this instance with the contextualize passed."
  },
  {
    "code": "def reverse_iter(self, start=None, stop=None, count=2000):\n        cursor = '0'\n        count = 1000\n        start = start if start is not None else (-1 * count)\n        stop = stop if stop is not None else -1\n        _loads = self._loads\n        while cursor:\n            cursor = self._client.lrange(self.key_prefix, start, stop)\n            for x in reversed(cursor or []):\n                yield _loads(x)\n            start -= count\n            stop -= count",
    "docstring": "-> yields items of the list in reverse"
  },
  {
    "code": "def make_query(self, **kw):\n        query = kw.pop(\"query\", {})\n        query.update(self.get_request_query())\n        query.update(self.get_custom_query())\n        query.update(self.get_keyword_query(**kw))\n        sort_on, sort_order = self.get_sort_spec()\n        if sort_on and \"sort_on\" not in query:\n            query.update({\"sort_on\": sort_on})\n        if sort_order and \"sort_order\" not in query:\n            query.update({\"sort_order\": sort_order})\n        logger.info(\"make_query:: query={} | catalog={}\".format(\n            query, self.catalog))\n        return query",
    "docstring": "create a query suitable for the catalog"
  },
  {
    "code": "def load_config_from_cli_arguments(self, *args, **kwargs):\n        self._load_config_from_cli_argument(key='handlers_package', **kwargs)\n        self._load_config_from_cli_argument(key='auth', **kwargs)\n        self._load_config_from_cli_argument(key='user_stream', **kwargs)\n        self._load_config_from_cli_argument(key='min_seconds_between_errors', **kwargs)\n        self._load_config_from_cli_argument(key='sleep_seconds_on_consecutive_errors', **kwargs)",
    "docstring": "Get config values of passed in CLI options.\n\n        :param dict kwargs: CLI options"
  },
  {
    "code": "def _save(self, name, content):\n        name = self.clean_name(name)\n        if not self._exists_with_etag(name, content):\n            content.seek(0)\n            super(StaticCloudinaryStorage, self)._save(name, content)\n        return self._prepend_prefix(name)",
    "docstring": "Saves only when a file with a name and a content is not already uploaded to Cloudinary."
  },
  {
    "code": "def list_clusters(kwargs=None, call=None):\n    if call != 'function':\n        raise SaltCloudSystemExit(\n            'The list_clusters function must be called with '\n            '-f or --function.'\n        )\n    return {'Clusters': salt.utils.vmware.list_clusters(_get_si())}",
    "docstring": "List all the clusters for this VMware environment\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -f list_clusters my-vmware-config"
  },
  {
    "code": "def numeric(self, code, padded=False):\n        code = self.alpha2(code)\n        try:\n            num = self.alt_codes[code][1]\n        except KeyError:\n            return None\n        if padded:\n            return \"%03d\" % num\n        return num",
    "docstring": "Return the ISO 3166-1 numeric country code matching the provided\n        country code.\n\n        If no match is found, returns ``None``.\n\n        :param padded: Pass ``True`` to return a 0-padded three character\n            string, otherwise an integer will be returned."
  },
  {
    "code": "def contracts_source_path_with_stem(stem):\n    return {\n        'lib': _BASE.joinpath(stem, 'lib'),\n        'raiden': _BASE.joinpath(stem, 'raiden'),\n        'test': _BASE.joinpath(stem, 'test'),\n        'services': _BASE.joinpath(stem, 'services'),\n    }",
    "docstring": "The directory remapping given to the Solidity compiler."
  },
  {
    "code": "def load_image(name):\n    image = pyglet.image.load(name).texture\n    verify_dimensions(image)\n    return image",
    "docstring": "Load an image"
  },
  {
    "code": "def get_mapping_format(self):\n        if self.format == DataFormat.json or self.format == DataFormat.avro:\n            return self.format.name\n        else:\n            return DataFormat.csv.name",
    "docstring": "Dictating the corresponding mapping to the format."
  },
  {
    "code": "def get_farthest_node(self, topology_only=False):\n        farthest_node, farthest_dist = self.get_farthest_leaf(\n            topology_only=topology_only)\n        prev = self\n        cdist = 0.0 if topology_only else prev.dist\n        current = prev.up\n        while current is not None:\n            for ch in current.children:\n                if ch != prev:\n                    if not ch.is_leaf():\n                        fnode, fdist = ch.get_farthest_leaf(\n                            topology_only=topology_only)\n                    else:\n                        fnode = ch\n                        fdist = 0\n                    if topology_only:\n                        fdist += 1.0\n                    else:\n                        fdist += ch.dist\n                    if cdist+fdist > farthest_dist:\n                        farthest_dist = cdist + fdist\n                        farthest_node = fnode\n            prev = current\n            if topology_only:\n                cdist += 1\n            else:\n                cdist  += prev.dist\n            current = prev.up\n        return farthest_node, farthest_dist",
    "docstring": "Returns the node's farthest descendant or ancestor node, and the\n        distance to it.\n\n        :argument False topology_only: If set to True, distance\n          between nodes will be referred to the number of nodes\n          between them. In other words, topological distance will be\n          used instead of branch length distances.\n\n        :return: A tuple containing the farthest node referred to the\n          current node and the distance to it."
  },
  {
    "code": "def start(context, mip_config, email, priority, dryrun, command, start_with, family):\n    mip_cli = MipCli(context.obj['script'])\n    mip_config = mip_config or context.obj['mip_config']\n    email = email or environ_email()\n    kwargs = dict(config=mip_config, family=family, priority=priority, email=email, dryrun=dryrun, start_with=start_with)\n    if command:\n        mip_command = mip_cli.build_command(**kwargs)\n        click.echo(' '.join(mip_command))\n    else:\n        try:\n            mip_cli(**kwargs)\n            if not dryrun:\n                context.obj['store'].add_pending(family, email=email)\n        except MipStartError as error:\n            click.echo(click.style(error.message, fg='red'))",
    "docstring": "Start a new analysis."
  },
  {
    "code": "def weed(self):\n        _ext = [k for k in self._dict.keys() if k not in self.c_param]\n        for k in _ext:\n            del self._dict[k]",
    "docstring": "Get rid of key value pairs that are not standard"
  },
  {
    "code": "def run(self):\n        self._wake_up()\n        while not self._q.empty():\n            self._config = self._q.get()\n        while not self.exit.is_set():\n            settings = self._read_settings()\n            settings['valid'] = self._valid_config(settings)\n            self._cb(settings)\n            if self.cooldown.is_set():\n                self._log.debug(\"Cool down process triggered\")\n                self._config['drum_motor'] = 1\n                self._config['heater'] = 0\n                self._config['solenoid'] = 1\n                self._config['cooling_motor'] = 1\n                self._config['main_fan'] = 10\n            if settings['valid']:\n                self._log.debug(\"Settings were valid, sending...\")\n                self._send_config()\n            time.sleep(self._config['interval'])",
    "docstring": "Run the core loop of reading and writing configurations.\n\n        This is where all the roaster magic occurs. On the initial run, we\n        prime the roaster with some data to wake it up. Once awoke, we check\n        our shared queue to identify if the user has passed any updated\n        configuration. Once checked, start to read and write to the Hottop\n        roaster as long as the exit signal has not been set. All steps are\n        repeated after waiting for a specific time interval.\n\n        There are also specialized routines built into this function that are\n        controlled via events. These events are unique to the roasting process\n        and pre-configure the system with a configuration, so the user doesn't\n        need to do it themselves.\n\n        :returns: None"
  },
  {
    "code": "def simple_separated_format(separator):\n    return TableFormat(None, None, None, None,\n                       headerrow=DataRow('', separator, ''),\n                       datarow=DataRow('', separator, ''),\n                       padding=0, with_header_hide=None)",
    "docstring": "Construct a simple TableFormat with columns separated by a separator.\n\n    >>> tsv = simple_separated_format(\"\\\\t\") ; \\\n        tabulate([[\"foo\", 1], [\"spam\", 23]], tablefmt=tsv) == 'foo \\\\t 1\\\\nspam\\\\t23'\n    True"
  },
  {
    "code": "def _has_tag(version, debug=False):\n    cmd = sh.git.bake('show-ref', '--verify', '--quiet',\n                      \"refs/tags/{}\".format(version))\n    try:\n        util.run_command(cmd, debug=debug)\n        return True\n    except sh.ErrorReturnCode:\n        return False",
    "docstring": "Determine a version is a local git tag name or not.\n\n    :param version: A string containing the branch/tag/sha to be determined.\n    :param debug: An optional bool to toggle debug output.\n    :return: bool"
  },
  {
    "code": "def create_db(name, **client_args):\n    if db_exists(name, **client_args):\n        log.info('DB \\'%s\\' already exists', name)\n        return False\n    client = _client(**client_args)\n    client.create_database(name)\n    return True",
    "docstring": "Create a database.\n\n    name\n        Name of the database to create.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' influxdb.create_db <name>"
  },
  {
    "code": "def _get_filesystem_path(self, url_path, basedir=settings.MEDIA_ROOT):\n        if url_path.startswith(settings.MEDIA_URL):\n            url_path = url_path[len(settings.MEDIA_URL):]\n        return os.path.normpath(os.path.join(basedir, url2pathname(url_path)))",
    "docstring": "Makes a filesystem path from the specified URL path"
  },
  {
    "code": "def _write_plain_json(file_path, js):\n    if file_path.endswith('.bz2'):\n        with bz2.open(file_path, 'wt', encoding=_default_encoding) as f:\n            json.dump(js, f, indent=2, ensure_ascii=False)\n    else:\n        with open(file_path, 'w', encoding=_default_encoding) as f:\n            json.dump(js, f, indent=2, ensure_ascii=False)",
    "docstring": "Write information to a JSON file\n\n    This makes sure files are created with the proper encoding and consistent indenting\n\n    Parameters\n    ----------\n    file_path : str\n        Full path to the file to write to. It will be overwritten if it exists\n    js : dict\n        JSON information to write"
  },
  {
    "code": "def GetCompressedStreamTypeIndicators(cls, path_spec, resolver_context=None):\n    if (cls._compressed_stream_remainder_list is None or\n        cls._compressed_stream_store is None):\n      specification_store, remainder_list = cls._GetSpecificationStore(\n          definitions.FORMAT_CATEGORY_COMPRESSED_STREAM)\n      cls._compressed_stream_remainder_list = remainder_list\n      cls._compressed_stream_store = specification_store\n    if cls._compressed_stream_scanner is None:\n      cls._compressed_stream_scanner = cls._GetSignatureScanner(\n          cls._compressed_stream_store)\n    return cls._GetTypeIndicators(\n        cls._compressed_stream_scanner, cls._compressed_stream_store,\n        cls._compressed_stream_remainder_list, path_spec,\n        resolver_context=resolver_context)",
    "docstring": "Determines if a file contains a supported compressed stream types.\n\n    Args:\n      path_spec (PathSpec): path specification.\n      resolver_context (Optional[Context]): resolver context, where None\n          represents the built-in context which is not multi process safe.\n\n    Returns:\n      list[str]: supported format type indicators."
  },
  {
    "code": "def allow_pgcodes(cr, *codes):\n    try:\n        with cr.savepoint():\n            with core.tools.mute_logger('odoo.sql_db'):\n                yield\n    except (ProgrammingError, IntegrityError) as error:\n        msg = \"Code: {code}. Class: {class_}. Error: {error}.\".format(\n            code=error.pgcode,\n            class_=errorcodes.lookup(error.pgcode[:2]),\n            error=errorcodes.lookup(error.pgcode))\n        if error.pgcode in codes or error.pgcode[:2] in codes:\n            logger.info(msg)\n        else:\n            logger.exception(msg)\n            raise",
    "docstring": "Context manager that will omit specified error codes.\n\n    E.g., suppose you expect a migration to produce unique constraint\n    violations and you want to ignore them. Then you could just do::\n\n        with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):\n            cr.execute(\"INSERT INTO me (name) SELECT name FROM you\")\n\n    .. warning::\n        **All** sentences inside this context will be rolled back if **a single\n        error** is raised, so the above example would insert **nothing** if a\n        single row violates a unique constraint.\n\n        This would ignore duplicate files but insert the others::\n\n            cr.execute(\"SELECT name FROM you\")\n            for row in cr.fetchall():\n                with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):\n                    cr.execute(\"INSERT INTO me (name) VALUES (%s)\", row[0])\n\n    :param *str codes:\n        Undefined amount of error codes found in :mod:`psycopg2.errorcodes`\n        that are allowed. Codes can have either 2 characters (indicating an\n        error class) or 5 (indicating a concrete error). Any other errors\n        will be raised."
  },
  {
    "code": "def delete_api_stage(restApiId, stageName, region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        conn.delete_stage(restApiId=restApiId, stageName=stageName)\n        return {'deleted': True}\n    except ClientError as e:\n        return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Deletes stage identified by stageName from API identified by restApiId\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_apigateway.delete_api_stage restApiId stageName"
  },
  {
    "code": "def show_bgp_speaker(self, bgp_speaker_id, **_params):\n        return self.get(self.bgp_speaker_path % (bgp_speaker_id),\n                        params=_params)",
    "docstring": "Fetches information of a certain BGP speaker."
  },
  {
    "code": "async def render_template(template_name_or_list: Union[str, List[str]], **context: Any) -> str:\n    await current_app.update_template_context(context)\n    template = current_app.jinja_env.get_or_select_template(template_name_or_list)\n    return await _render(template, context)",
    "docstring": "Render the template with the context given.\n\n    Arguments:\n        template_name_or_list: Template name to render of a list of\n            possible template names.\n        context: The variables to pass to the template."
  },
  {
    "code": "def title_has_tag(page, lang, tag):\n    from .models import TitleTags\n    if hasattr(tag, 'slug'):\n        slug = tag.slug\n    else:\n        slug = tag\n    try:\n        return page.get_title_obj(\n            language=lang, fallback=False\n        ).titletags.tags.filter(slug=slug).exists()\n    except TitleTags.DoesNotExist:\n        return False",
    "docstring": "Check if a Title object is associated with the given tag.\n    This function does not use fallbacks to retrieve title object.\n\n    :param page: a Page instance\n    :param lang: a language code\n    :param tag: a Tag instance or a slug string.\n\n    :return: whether the Title instance has the given tag attached (False if no Title or no\n             attached TitleTags exists)\n    :type: Boolean"
  },
  {
    "code": "def stop_capture(self):\n        if self._capture_node:\n            yield from self._capture_node[\"node\"].post(\"/adapters/{adapter_number}/ports/{port_number}/stop_capture\".format(adapter_number=self._capture_node[\"adapter_number\"], port_number=self._capture_node[\"port_number\"]))\n            self._capture_node = None\n        yield from super().stop_capture()",
    "docstring": "Stop capture on a link"
  },
  {
    "code": "def get_mate_center(self, angle=0):\n        return Mate(self, CoordSystem.from_plane(\n            cadquery.Plane(\n                origin=(0, 0, self.width / 2),\n                xDir=(1, 0, 0),\n                normal=(0, 0, 1),\n            ).rotated((0, 0, angle))\n        ))",
    "docstring": "Mate at ring's center rotated ``angle`` degrees.\n\n        :param angle: rotation around z-axis (unit: deg)\n        :type angle: :class:`float`\n\n        :return: mate in ring's center rotated about z-axis\n        :rtype: :class:`Mate <cqparts.constraint.Mate>`"
  },
  {
    "code": "def get_incidents(self):\n        resp = requests.get(CRIME_URL, params=self._get_params(), headers=self.headers)\n        incidents = []\n        data = resp.json()\n        if ATTR_CRIMES not in data:\n            return incidents\n        for incident in data.get(ATTR_CRIMES):\n            if _validate_incident_date_range(incident, self.days):\n                if _incident_in_types(incident, self.incident_types):\n                    incidents.append(_incident_transform(incident))\n        return incidents",
    "docstring": "Get incidents."
  },
  {
    "code": "def update_user_label(self):\n        self._user_label = _uniqueid_to_uniquetwig(self._bundle, self.unique_label)\n        self._set_curly_label()",
    "docstring": "finds this parameter and gets the least_unique_twig from the bundle"
  },
  {
    "code": "def update_frequency(shell_ctx):\n    frequency_path = os.path.join(shell_ctx.config.get_config_dir(), shell_ctx.config.get_frequency())\n    if os.path.exists(frequency_path):\n        with open(frequency_path, 'r') as freq:\n            try:\n                frequency = json.load(freq)\n            except ValueError:\n                frequency = {}\n    else:\n        frequency = {}\n    with open(frequency_path, 'w') as freq:\n        now = day_format(datetime.datetime.utcnow())\n        val = frequency.get(now)\n        frequency[now] = val + 1 if val else 1\n        json.dump(frequency, freq)\n    return frequency",
    "docstring": "updates the frequency from files"
  },
  {
    "code": "def add(self, *args, **kwargs):\n        if self.start and self.start.state == 'done' and kwargs.get('log_action') != 'done':\n            raise ProgressLoggingError(\"Can't add -- process section is done\")\n        self.augment_args(args, kwargs)\n        kwargs['log_action'] = kwargs.get('log_action', 'add')\n        rec = Process(**kwargs)\n        self._session.add(rec)\n        self.rec = rec\n        if self._logger:\n            self._logger.info(self.rec.log_str)\n        self._session.commit()\n        self._ai_rec_id = None\n        return self.rec.id",
    "docstring": "Add a new record to the section"
  },
  {
    "code": "def FilterArgsFromSemanticProtobuf(protobuf, kwargs):\n  for descriptor in protobuf.type_infos:\n    value = kwargs.pop(descriptor.name, None)\n    if value is not None:\n      setattr(protobuf, descriptor.name, value)",
    "docstring": "Assign kwargs to the protobuf, and remove them from the kwargs dict."
  },
  {
    "code": "def clistream(reporter, *args, **kwargs):\n    files = kwargs.get('files')\n    encoding = kwargs.get('input_encoding', DEFAULT_ENCODING)\n    processes = kwargs.get('processes')\n    chunksize = kwargs.get('chunksize')\n    from clitool.processor import CliHandler, Streamer\n    Handler = kwargs.get('Handler')\n    if Handler:\n        warnings.warn('\"Handler\" keyword will be removed from next release.',\n            DeprecationWarning)\n    else:\n        Handler = CliHandler\n    s = Streamer(reporter, processes=processes, *args)\n    handler = Handler(s, kwargs.get('delimiter'))\n    return handler.handle(files, encoding, chunksize)",
    "docstring": "Handle stream data on command line interface,\n    and returns statistics of success, error, and total amount.\n\n    More detailed information is available on underlying feature,\n    :mod:`clitool.processor`.\n\n    :param Handler: [DEPRECATED] Handler for file-like streams.\n            (default: :class:`clitool.processor.CliHandler`)\n    :type Handler: object which supports `handle` method.\n    :param reporter: callback to report processed value\n    :type reporter: callable\n    :param delimiter: line delimiter [optional]\n    :type delimiter: string\n    :param args: functions to parse each item in the stream.\n    :param kwargs: keywords, including ``files`` and ``input_encoding``.\n    :rtype: list"
  },
  {
    "code": "def kill_all(self):\n        logger.info('Job {0} killing all currently running tasks'.format(self.name))\n        for task in self.tasks.itervalues():\n            if task.started_at and not task.completed_at:\n                task.kill()",
    "docstring": "Kill all currently running jobs."
  },
  {
    "code": "def SensorMetatagsGet(self, sensor_id, namespace = None):\r\n        ns = \"default\" if namespace is None else namespace\r\n        if self.__SenseApiCall__('/sensors/{0}/metatags.json'.format(sensor_id), 'GET', parameters = {'namespace': ns}):\r\n            return True\r\n        else:\r\n            self.__error__ = \"api call unsuccessful\"\r\n            return False",
    "docstring": "Retrieve the metatags of a sensor.\r\n            \r\n            @param sensor_id (int) - Id of the sensor to retrieve metatags from\r\n            @param namespace (stirng) - Namespace for which to retrieve metatags.\r\n            \r\n            @return (bool) - Boolean indicating whether SensorMetatagsGet was successful"
  },
  {
    "code": "def output_notebook(\n        d3js_url=\"//d3js.org/d3.v3.min\",\n        requirejs_url=\"//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js\",\n        html_template=None\n):\n    if html_template is None:\n        html_template = read_lib('html', 'setup')\n    setup_html = populate_template(\n        html_template,\n        d3js=d3js_url,\n        requirejs=requirejs_url\n    )\n    display_html(setup_html)\n    return",
    "docstring": "Import required Javascript libraries to Jupyter Notebook."
  },
  {
    "code": "def make_message(subject=\"\", body=\"\", from_email=None, to=None, bcc=None,\n                 attachments=None, headers=None, priority=None):\n    to = filter_recipient_list(to)\n    bcc = filter_recipient_list(bcc)\n    core_msg = EmailMessage(\n        subject=subject,\n        body=body,\n        from_email=from_email,\n        to=to,\n        bcc=bcc,\n        attachments=attachments,\n        headers=headers\n    )\n    db_msg = Message(priority=priority)\n    db_msg.email = core_msg\n    return db_msg",
    "docstring": "Creates a simple message for the email parameters supplied.\n    The 'to' and 'bcc' lists are filtered using DontSendEntry.\n\n    If needed, the 'email' attribute can be set to any instance of EmailMessage\n    if e-mails with attachments etc. need to be supported.\n\n    Call 'save()' on the result when it is ready to be sent, and not before."
  },
  {
    "code": "def _indent(x):\n    lines = x.splitlines()\n    for i, line in enumerate(lines):\n        lines[i] = '    ' + line\n    return '\\n'.join(lines)",
    "docstring": "Indent a string by 4 characters."
  },
  {
    "code": "def next(self):\n        while True:\n            self.cur_idx += 1\n            if self.__datasource.populate_iteration(self):\n                return self\n        raise StopIteration",
    "docstring": "Move to the next valid locus.\n\n        Will only return valid loci or exit via StopIteration exception"
  },
  {
    "code": "def create_tar_file(self, full_archive=False):\n        tar_file_name = os.path.join(self.archive_tmp_dir, self.archive_name)\n        ext = \"\" if self.compressor == \"none\" else \".%s\" % self.compressor\n        tar_file_name = tar_file_name + \".tar\" + ext\n        logger.debug(\"Tar File: \" + tar_file_name)\n        subprocess.call(shlex.split(\"tar c%sfS %s -C %s .\" % (\n            self.get_compression_flag(self.compressor),\n            tar_file_name,\n            self.tmp_dir if not full_archive else self.archive_dir)),\n            stderr=subprocess.PIPE)\n        self.delete_archive_dir()\n        logger.debug(\"Tar File Size: %s\", str(os.path.getsize(tar_file_name)))\n        return tar_file_name",
    "docstring": "Create tar file to be compressed"
  },
  {
    "code": "def init(self):\n        if not valid_ovsdb_addr(self.ovsdb_addr):\n            raise ValueError('Invalid OVSDB address: %s' % self.ovsdb_addr)\n        if self.br_name is None:\n            self.br_name = self._get_bridge_name()",
    "docstring": "Validates the given ``ovsdb_addr`` and connects to OVS instance.\n\n        If failed to connect to OVS instance or the given ``datapath_id`` does\n        not match with the Datapath ID of the connected OVS instance, raises\n        :py:mod:`ryu.lib.ovs.bridge.OVSBridgeNotFound` exception."
  },
  {
    "code": "def run_foreach_or_conditional(self, context):\n        logger.debug(\"starting\")\n        if self.foreach_items:\n            self.foreach_loop(context)\n        else:\n            self.run_conditional_decorators(context)\n        logger.debug(\"done\")",
    "docstring": "Run the foreach sequence or the conditional evaluation.\n\n        Args:\n            context: (pypyr.context.Context) The pypyr context. This arg will\n                     mutate."
  },
  {
    "code": "def delete(self, **kwargs):\n        response = self._requester.request(\n            'DELETE',\n            'calendar_events/{}'.format(self.id),\n            _kwargs=combine_kwargs(**kwargs)\n        )\n        return CalendarEvent(self._requester, response.json())",
    "docstring": "Delete this calendar event.\n\n        :calls: `DELETE /api/v1/calendar_events/:id \\\n        <https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.destroy>`_\n\n        :rtype: :class:`canvasapi.calendar_event.CalendarEvent`"
  },
  {
    "code": "def quantize(self, image):\n        if get_cKDTree():\n            return self.quantize_with_scipy(image)\n        else:\n            print('Scipy not available, falling back to slower version.')\n            return self.quantize_without_scipy(image)",
    "docstring": "Use a kdtree to quickly find the closest palette colors for the pixels"
  },
  {
    "code": "def search_references(\n            self, reference_set_id, accession=None, md5checksum=None):\n        request = protocol.SearchReferencesRequest()\n        request.reference_set_id = reference_set_id\n        request.accession = pb.string(accession)\n        request.md5checksum = pb.string(md5checksum)\n        request.page_size = pb.int(self._page_size)\n        return self._run_search_request(\n            request, \"references\", protocol.SearchReferencesResponse)",
    "docstring": "Returns an iterator over the References fulfilling the specified\n        conditions from the specified Dataset.\n\n        :param str reference_set_id: The ReferenceSet to search.\n        :param str accession: If not None, return the references for which the\n            `accession` matches this string (case-sensitive, exact match).\n        :param str md5checksum: If not None, return the references for which\n            the `md5checksum` matches this string (case-sensitive, exact\n            match).\n        :return: An iterator over the :class:`ga4gh.protocol.Reference`\n            objects defined by the query parameters."
  },
  {
    "code": "def get(self, index):\n        assert index <= self.count\n        assert index < self.size\n        offset = index * self.chunk_size\n        return self.data[offset:offset + self.chunk_size]",
    "docstring": "Get a chunk by index"
  },
  {
    "code": "def _verify(function):\r\n    def wrapped(pin, *args, **kwargs):\r\n        pin = int(pin)\r\n        if pin not in _open:\r\n            ppath = gpiopath(pin)\r\n            if not os.path.exists(ppath):\r\n                log.debug(\"Creating Pin {0}\".format(pin))\r\n                with _export_lock:\r\n                    with open(pjoin(gpio_root, 'export'), 'w') as f:\r\n                        _write(f, pin)\r\n            value = open(pjoin(ppath, 'value'), FMODE)\r\n            direction = open(pjoin(ppath, 'direction'), FMODE)\r\n            _open[pin] = PinState(value=value, direction=direction)\r\n        return function(pin, *args, **kwargs)\r\n    return wrapped",
    "docstring": "decorator to ensure pin is properly set up"
  },
  {
    "code": "def get_database_name(self):\n        uri_dict = uri_parser.parse_uri(self.host)\n        database = uri_dict.get('database', None)\n        if not database:\n            raise \"database name is missing\"\n        return database",
    "docstring": "extract database from connection string"
  },
  {
    "code": "def deviation(reference_intervals, estimated_intervals, trim=False):\n    validate_boundary(reference_intervals, estimated_intervals, trim)\n    reference_boundaries = util.intervals_to_boundaries(reference_intervals)\n    estimated_boundaries = util.intervals_to_boundaries(estimated_intervals)\n    if trim:\n        reference_boundaries = reference_boundaries[1:-1]\n        estimated_boundaries = estimated_boundaries[1:-1]\n    if len(reference_boundaries) == 0 or len(estimated_boundaries) == 0:\n        return np.nan, np.nan\n    dist = np.abs(np.subtract.outer(reference_boundaries,\n                                    estimated_boundaries))\n    estimated_to_reference = np.median(dist.min(axis=0))\n    reference_to_estimated = np.median(dist.min(axis=1))\n    return reference_to_estimated, estimated_to_reference",
    "docstring": "Compute the median deviations between reference\n    and estimated boundary times.\n\n    Examples\n    --------\n    >>> ref_intervals, _ = mir_eval.io.load_labeled_intervals('ref.lab')\n    >>> est_intervals, _ = mir_eval.io.load_labeled_intervals('est.lab')\n    >>> r_to_e, e_to_r = mir_eval.boundary.deviation(ref_intervals,\n    ...                                              est_intervals)\n\n    Parameters\n    ----------\n    reference_intervals : np.ndarray, shape=(n, 2)\n        reference segment intervals, in the format returned by\n        :func:`mir_eval.io.load_intervals` or\n        :func:`mir_eval.io.load_labeled_intervals`.\n    estimated_intervals : np.ndarray, shape=(m, 2)\n        estimated segment intervals, in the format returned by\n        :func:`mir_eval.io.load_intervals` or\n        :func:`mir_eval.io.load_labeled_intervals`.\n    trim : boolean\n        if ``True``, the first and last intervals are ignored.\n        Typically, these denote start (0.0) and end-of-track markers.\n        (Default value = False)\n\n    Returns\n    -------\n    reference_to_estimated : float\n        median time from each reference boundary to the\n        closest estimated boundary\n    estimated_to_reference : float\n        median time from each estimated boundary to the\n        closest reference boundary"
  },
  {
    "code": "def _rm_gos_edges_rel(self, rm_goids, edges_rel):\n        edges_ret = {}\n        for rname, edges_cur in edges_rel.items():\n            edges_new = self._rm_gos_edges(rm_goids, edges_cur)\n            if edges_new:\n                edges_ret[rname] = edges_new\n        return edges_ret",
    "docstring": "Remove any relationship that contain user-specified edges."
  },
  {
    "code": "def _resolve_parameters(parameters, blueprint):\n    params = {}\n    param_defs = blueprint.get_parameter_definitions()\n    for key, value in parameters.items():\n        if key not in param_defs:\n            logger.debug(\"Blueprint %s does not use parameter %s.\",\n                         blueprint.name, key)\n            continue\n        if value is None:\n            logger.debug(\"Got None value for parameter %s, not submitting it \"\n                         \"to cloudformation, default value should be used.\",\n                         key)\n            continue\n        if isinstance(value, bool):\n            logger.debug(\"Converting parameter %s boolean \\\"%s\\\" to string.\",\n                         key, value)\n            value = str(value).lower()\n        params[key] = value\n    return params",
    "docstring": "Resolves CloudFormation Parameters for a given blueprint.\n\n    Given a list of parameters, handles:\n        - discard any parameters that the blueprint does not use\n        - discard any empty values\n        - convert booleans to strings suitable for CloudFormation\n\n    Args:\n        parameters (dict): A dictionary of parameters provided by the\n            stack definition\n        blueprint (:class:`stacker.blueprint.base.Blueprint`): A Blueprint\n            object that is having the parameters applied to it.\n\n    Returns:\n        dict: The resolved parameters."
  },
  {
    "code": "def add(self, transport, address=None):\n        if not address:\n            address = str(uuid.uuid1())\n        if address in self.recipients:\n            self.recipients[address].add(transport)\n        else:\n            self.recipients[address] = RecipientManager(transport, address)\n        return address",
    "docstring": "add a new recipient to be addressable by this MessageDispatcher\n            generate a new uuid address if one is not specified"
  },
  {
    "code": "def buffer(self, frame):\n        frame.buffer = self.temporary_identifier()\n        self.writeline('%s = []' % frame.buffer)",
    "docstring": "Enable buffering for the frame from that point onwards."
  },
  {
    "code": "def inputs(self, name):\n        self._closed()\n        step = self._get_step(name, make_copy=False)\n        return step.list_inputs()",
    "docstring": "List input names and types of a step in the steps library.\n\n        Args:\n            name (str): name of a step in the steps library."
  },
  {
    "code": "def preprocess_bel_stmt(stmt: str) -> str:\n    stmt = stmt.strip()\n    stmt = re.sub(r\",+\", \",\", stmt)\n    stmt = re.sub(r\",\", \", \", stmt)\n    stmt = re.sub(r\" +\", \" \", stmt)\n    return stmt",
    "docstring": "Clean up basic formatting of BEL statement\n\n    Args:\n        stmt: BEL statement as single string\n\n    Returns:\n        cleaned BEL statement"
  },
  {
    "code": "def SaveState( self, config_parser ):\n        if not config_parser.has_section( 'window' ):\n            config_parser.add_section( 'window' )\n        if self.IsMaximized():\n            config_parser.set( 'window', 'maximized', str(True))\n        else:\n            config_parser.set( 'window', 'maximized', str(False))\n        size = self.GetSizeTuple()\n        position = self.GetPositionTuple()\n        config_parser.set( 'window', 'width', str(size[0]) )\n        config_parser.set( 'window', 'height', str(size[1]) )\n        config_parser.set( 'window', 'x', str(position[0]) )\n        config_parser.set( 'window', 'y', str(position[1]) )\n        for control in self.ProfileListControls:\n            control.SaveState( config_parser )\n        return config_parser",
    "docstring": "Retrieve window state to be restored on the next run..."
  },
  {
    "code": "def get_values(self, profile, bitarray, status):\n        if not self.init_ok or profile is None:\n            return [], {}\n        output = OrderedDict({})\n        for source in profile.contents:\n            if not source.name:\n                continue\n            if source.name == 'value':\n                output.update(self._get_value(source, bitarray))\n            if source.name == 'enum':\n                output.update(self._get_enum(source, bitarray))\n            if source.name == 'status':\n                output.update(self._get_boolean(source, status))\n        return output.keys(), output",
    "docstring": "Get keys and values from bitarray"
  },
  {
    "code": "def _path_from_module(module):\n        paths = list(getattr(module, '__path__', []))\n        if len(paths) != 1:\n            filename = getattr(module, '__file__', None)\n            if filename is not None:\n                paths = [os.path.dirname(filename)]\n            else:\n                paths = list(set(paths))\n        if len(paths) > 1:\n            raise ImproperlyConfigured(\n                \"The bot module %r has multiple filesystem locations (%r); \"\n                \"you must configure this bot with an AppConfig subclass \"\n                \"with a 'path' class attribute.\" % (module, paths))\n        elif not paths:\n            raise ImproperlyConfigured(\n                \"The bot module %r has no filesystem location, \"\n                \"you must configure this bot with an AppConfig subclass \"\n                \"with a 'path' class attribute.\" % (module,))\n        return paths[0]",
    "docstring": "Attempt to determine bot's filesystem path from its module."
  },
  {
    "code": "def create_seq(self, ):\n        name = self.name_le.text()\n        desc = self.desc_pte.toPlainText()\n        try:\n            seq = djadapter.models.Sequence(name=name, project=self._project, description=desc)\n            seq.save()\n            self.sequence = seq\n            self.accept()\n        except:\n            log.exception(\"Could not create new sequence\")",
    "docstring": "Create a sequence and store it in the self.sequence\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def prolong(self):\n\t\tD = self.__class__\n\t\tcollection = self.get_collection()\n\t\tidentity = self.Lock()\n\t\tquery = D.id == self\n\t\tquery &= D.lock.instance == identity.instance\n\t\tquery &= D.lock.time >= (identity.time - identity.__period__)\n\t\tprevious = collection.find_one_and_update(query, {'$set': {~D.lock.time: identity.time}}, {~D.lock: True})\n\t\tif previous is None:\n\t\t\tlock = getattr(self.find_one(self, projection={~D.lock: True}), 'lock', None)\n\t\t\tif lock and lock.expires <= identity.time:\n\t\t\t\tlock.expired(self)\n\t\t\traise self.Locked(\"Unable to prolong lock.\", lock)\n\t\tidentity.prolonged(self)\n\t\treturn identity",
    "docstring": "Prolong the working duration of an already held lock.\n\t\t\n\t\tAttempting to prolong a lock not already owned will result in a Locked exception."
  },
  {
    "code": "def after_invoke(self, coro):\n        if not asyncio.iscoroutinefunction(coro):\n            raise TypeError('The post-invoke hook must be a coroutine.')\n        self._after_invoke = coro\n        return coro",
    "docstring": "A decorator that registers a coroutine as a post-invoke hook.\n\n        A post-invoke hook is called directly after the command is\n        called. This makes it a useful function to clean-up database\n        connections or any type of clean up required.\n\n        This post-invoke hook takes a sole parameter, a :class:`.Context`.\n\n        See :meth:`.Bot.after_invoke` for more info.\n\n        Parameters\n        -----------\n        coro: :ref:`coroutine <coroutine>`\n            The coroutine to register as the post-invoke hook.\n\n        Raises\n        -------\n        TypeError\n            The coroutine passed is not actually a coroutine."
  },
  {
    "code": "def visit_yieldfrom(self, node):\n        yi_val = (\" \" + node.value.accept(self)) if node.value else \"\"\n        expr = \"yield from\" + yi_val\n        if node.parent.is_statement:\n            return expr\n        return \"(%s)\" % (expr,)",
    "docstring": "Return an astroid.YieldFrom node as string."
  },
  {
    "code": "def bake(self):\n        self._sh_command = getattr(sh, self.command)\n        self._sh_command = self._sh_command.bake(\n            self.options,\n            'overlay',\n            _env=self.env,\n            _out=LOG.out,\n            _err=LOG.error)",
    "docstring": "Bake a ``gilt`` command so it's ready to execute and returns None.\n\n        :return: None"
  },
  {
    "code": "def stop(self):\n        Global.LOGGER.debug(f\"action {self.name} stopped\")\n        self.is_running = False\n        self.on_stop()",
    "docstring": "Stop the current action"
  },
  {
    "code": "def get_bookmark(self, bookmark_id):\n        url = self._generate_url('bookmarks/{0}'.format(bookmark_id))\n        return self.get(url)",
    "docstring": "Get a single bookmark represented by `bookmark_id`.\n\n        The requested bookmark must belong to the current user.\n\n        :param bookmark_id: ID of the bookmark to retrieve."
  },
  {
    "code": "def read_csv_file(self, file_name):\n        result = []\n        with open(os.path.join(self.__path(), os.path.basename(file_name)),\n                  'rt') as csvfile:\n            headers_reader = csv.reader(csvfile, delimiter=',', quotechar='|')\n            for type_row in headers_reader:\n                for t in type_row:\n                    result.append(t)\n        return result",
    "docstring": "Parses a CSV file into a list.\n\n        :param file_name: name of the CSV file\n        :return: a list with the file's contents"
  },
  {
    "code": "def request_session(token, url=None):\n\tif url is None:\n\t\tapi = SlackApi()\n\telse:\n\t\tapi = SlackApi(url)\n\tresponse = api.rtm.start(token=token)\n\treturn SessionMetadata(response, api, token)",
    "docstring": "Requests a WebSocket session for the Real-Time Messaging API.\n\t\n\tReturns a SessionMetadata object containing the information retrieved from\n\tthe API call."
  },
  {
    "code": "def put(self, item):\n        check_not_none(item, \"Value can't be None\")\n        element_data = self._to_data(item)\n        return self._encode_invoke(queue_put_codec, value=element_data)",
    "docstring": "Adds the specified element into this queue. If there is no space, it waits until necessary space becomes\n        available.\n\n        :param item: (object), the specified item."
  },
  {
    "code": "def joint_sfs(dac1, dac2, n1=None, n2=None):\n    dac1, n1 = _check_dac_n(dac1, n1)\n    dac2, n2 = _check_dac_n(dac2, n2)\n    x = n1 + 1\n    y = n2 + 1\n    tmp = (dac1 * y + dac2).astype(int, copy=False)\n    s = np.bincount(tmp)\n    s.resize(x, y)\n    return s",
    "docstring": "Compute the joint site frequency spectrum between two populations.\n\n    Parameters\n    ----------\n    dac1 : array_like, int, shape (n_variants,)\n        Derived allele counts for the first population.\n    dac2 : array_like, int, shape (n_variants,)\n        Derived allele counts for the second population.\n    n1, n2 : int, optional\n        The total number of chromosomes called in each population.\n\n    Returns\n    -------\n    joint_sfs : ndarray, int, shape (m_chromosomes, n_chromosomes)\n        Array where the (i, j)th element is the number of variant sites with i\n        derived alleles in the first population and j derived alleles in the\n        second population."
  },
  {
    "code": "def not_storable(_type):\n    return Storable(_type, handlers=StorableHandler(poke=fake_poke, peek=fail_peek(_type)))",
    "docstring": "Helper for tagging unserializable types.\n\n    Arguments:\n\n        _type (type): type to be ignored.\n\n    Returns:\n\n        Storable: storable instance that does not poke."
  },
  {
    "code": "def after_insert(mapper, connection, target):\n    record_after_update.send(CmtRECORDCOMMENT, recid=target.id_bibrec)\n    from .api import get_reply_order_cache_data\n    if target.in_reply_to_id_cmtRECORDCOMMENT > 0:\n        parent = CmtRECORDCOMMENT.query.get(\n            target.in_reply_to_id_cmtRECORDCOMMENT)\n        if parent:\n            trans = connection.begin()\n            parent_reply_order = parent.reply_order_cached_data \\\n                if parent.reply_order_cached_data else ''\n            parent_reply_order += get_reply_order_cache_data(target.id)\n            connection.execute(\n                db.update(CmtRECORDCOMMENT.__table__).\n                where(CmtRECORDCOMMENT.id == parent.id).\n                values(reply_order_cached_data=parent_reply_order))\n            trans.commit()",
    "docstring": "Update reply order cache  and send record-after-update signal."
  },
  {
    "code": "def init(self, dict_or_str, val=None, warn=True):\n        self.check(dict_or_str)\n        dic = dict_or_str\n        if val is not None:\n            dic = {dict_or_str:val}\n        for key, val in dic.items():\n            key = self.corrected_key(key)\n            if key not in CMAOptions.defaults():\n                if warn:\n                    print('Warning in cma.CMAOptions.init(): key ' +\n                        str(key) + ' ignored')\n            else:\n                self[key] = val\n        return self",
    "docstring": "initialize one or several options.\n\n        Arguments\n        ---------\n            `dict_or_str`\n                a dictionary if ``val is None``, otherwise a key.\n                If `val` is provided `dict_or_str` must be a valid key.\n            `val`\n                value for key\n\n        Details\n        -------\n        Only known keys are accepted. Known keys are in `CMAOptions.defaults()`"
  },
  {
    "code": "def enable_logging(log_level):\n    root_logger = logging.getLogger()\n    root_logger.setLevel(logging.DEBUG)\n    logfile_handler = logging.StreamHandler(_LOGFILE_STREAM)\n    logfile_handler.setLevel(logging.DEBUG)\n    logfile_handler.setFormatter(logging.Formatter(\n        '%(levelname)s [%(asctime)s][%(name)s] %(message)s'))\n    root_logger.addHandler(logfile_handler)\n    if signal.getsignal(signal.SIGTERM) == signal.SIG_DFL:\n        signal.signal(signal.SIGTERM, _logfile_sigterm_handler)\n    if log_level:\n        handler = logging.StreamHandler()\n        handler.setFormatter(_LogColorFormatter())\n        root_logger.setLevel(log_level)\n        root_logger.addHandler(handler)",
    "docstring": "Configure the root logger and a logfile handler.\n\n    Args:\n        log_level: The logging level to set the logger handler."
  },
  {
    "code": "def _strip_invisible(s):\n    \"Remove invisible ANSI color codes.\"\n    if isinstance(s, _text_type):\n        return re.sub(_invisible_codes, \"\", s)\n    else:\n        return re.sub(_invisible_codes_bytes, \"\", s)",
    "docstring": "Remove invisible ANSI color codes."
  },
  {
    "code": "def uppercase(self, value):\n        if not isinstance(value, bool):\n            raise TypeError('uppercase attribute must be a logical type.')\n        self._uppercase = value",
    "docstring": "Validate and set the uppercase flag."
  },
  {
    "code": "def get_num_procs():\n    logger = logging.getLogger(__name__)\n    try:\n        py3nvml.nvmlInit()\n    except:\n        str_ = \n        warnings.warn(str_, RuntimeWarning)\n        logger.warn(str_)\n        return []\n    num_gpus = py3nvml.nvmlDeviceGetCount()\n    gpu_procs = [-1]*num_gpus\n    for i in range(num_gpus):\n        try:\n            h = py3nvml.nvmlDeviceGetHandleByIndex(i)\n        except:\n            continue\n        procs = try_get_info(py3nvml.nvmlDeviceGetComputeRunningProcesses, h,\n                             ['something'])\n        gpu_procs[i] = len(procs)\n    py3nvml.nvmlShutdown()\n    return gpu_procs",
    "docstring": "Gets the number of processes running on each gpu\n\n    Returns\n    -------\n    num_procs : list(int)\n        Number of processes running on each gpu\n\n    Note\n    ----\n    If function can't query the driver will return an empty list rather than raise an\n    Exception.\n\n    Note\n    ----\n    If function can't get the info from the gpu will return -1 in that gpu's place"
  },
  {
    "code": "def make_op_return_script(data, format='bin'):\n    if format == 'hex':\n        assert(is_hex(data))\n        hex_data = data\n    elif format == 'bin':\n        hex_data = hexlify(data)\n    else:\n        raise Exception(\"Format must be either 'hex' or 'bin'\")\n    num_bytes = count_bytes(hex_data)\n    if num_bytes > MAX_BYTES_AFTER_OP_RETURN:\n        raise Exception('Data is %i bytes - must not exceed 40.' % num_bytes)\n    script_string = 'OP_RETURN %s' % hex_data\n    return script_to_hex(script_string)",
    "docstring": "Takes in raw ascii data to be embedded and returns a script."
  },
  {
    "code": "def pitching_stats_bref(season=None):\n    if season is None:\n        season = datetime.datetime.today().strftime(\"%Y\")\n    season = str(season)\n    start_dt = season + '-03-01'\n    end_dt = season + '-11-01'\n    return(pitching_stats_range(start_dt, end_dt))",
    "docstring": "Get all pitching stats for a set season. If no argument is supplied, gives stats for \n    current season to date."
  },
  {
    "code": "def list_price(self):\n        price = self._safe_get_element_text('ItemAttributes.ListPrice.Amount')\n        currency = self._safe_get_element_text(\n            'ItemAttributes.ListPrice.CurrencyCode')\n        if price:\n            dprice = Decimal(\n                price) / 100 if 'JP' not in self.region else Decimal(price)\n            return dprice, currency\n        else:\n            return None, None",
    "docstring": "List Price.\n\n        :return:\n            A tuple containing:\n\n                1. Decimal representation of price.\n                2. ISO Currency code (string)."
  },
  {
    "code": "def last_version():\n    try:\n        last_update, version, success = last_version._cache\n    except AttributeError:\n        last_update = 0\n        version = None\n        success = False\n    cache_delta = 24 * 3600 if success else 600\n    if (time.time() - last_update) < cache_delta:\n        return version\n    else:\n        try:\n            req = requests.get(settings.CAS_NEW_VERSION_JSON_URL)\n            data = json.loads(req.text)\n            version = data[\"info\"][\"version\"]\n            last_version._cache = (time.time(), version, True)\n            return version\n        except (\n            KeyError,\n            ValueError,\n            requests.exceptions.RequestException\n        ) as error:\n            logger.error(\n                \"Unable to fetch %s: %s\" % (settings.CAS_NEW_VERSION_JSON_URL, error)\n            )\n            last_version._cache = (time.time(), version, False)",
    "docstring": "Fetch the last version from pypi and return it. On successful fetch from pypi, the response\n        is cached 24h, on error, it is cached 10 min.\n\n        :return: the last django-cas-server version\n        :rtype: unicode"
  },
  {
    "code": "def _get_bs4_string(soup):\n    if len(soup.find_all(\"script\")) == 0:\n        soup_str = soup.prettify(formatter=None).strip()\n    else:\n        soup_str = str(soup.html)\n        soup_str = re.sub(\"&amp;\", \"&\", soup_str)\n        soup_str = re.sub(\"&lt;\", \"<\", soup_str)\n        soup_str = re.sub(\"&gt;\", \">\", soup_str)\n    return soup_str",
    "docstring": "Outputs a BeautifulSoup object as a string that should hopefully be minimally modified"
  },
  {
    "code": "def get_item(key):\r\n    CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)\r\n    try:\r\n        return json.loads(open(CACHED_KEY_FILE, \"rb\").read().decode('UTF-8'))[\"_\"]\r\n    except (IOError, ValueError):\r\n        return None",
    "docstring": "Return content in cached file in JSON format"
  },
  {
    "code": "def from_yaml(data):\n    molecule_env_file = os.environ['MOLECULE_ENV_FILE']\n    env = os.environ.copy()\n    env = config.set_env_from_file(env, molecule_env_file)\n    i = interpolation.Interpolator(interpolation.TemplateWithDefaults, env)\n    interpolated_data = i.interpolate(data)\n    return util.safe_load(interpolated_data)",
    "docstring": "Interpolate the provided data and return a dict.\n\n    Currently, this is used to reinterpolate the `molecule.yml` inside an\n    Ansible playbook.  If there were any interpolation errors, they would\n    have been found and raised earlier.\n\n    :return: dict"
  },
  {
    "code": "def respond_fw_config(self, msg):\n        (req_fw_type,\n         req_fw_ver,\n         req_blocks,\n         req_crc,\n         bloader_ver) = fw_hex_to_int(msg.payload, 5)\n        _LOGGER.debug(\n            'Received firmware config request with firmware type %s, '\n            'firmware version %s, %s blocks, CRC %s, bootloader %s',\n            req_fw_type, req_fw_ver, req_blocks, req_crc, bloader_ver)\n        fw_type, fw_ver, fware = self._get_fw(\n            msg, (self.requested, self.unstarted))\n        if fware is None:\n            return None\n        if fw_type != req_fw_type:\n            _LOGGER.warning(\n                'Firmware type %s of update is not identical to existing '\n                'firmware type %s for node %s',\n                fw_type, req_fw_type, msg.node_id)\n        _LOGGER.info(\n            'Updating node %s to firmware type %s version %s from type %s '\n            'version %s', msg.node_id, fw_type, fw_ver, req_fw_type,\n            req_fw_ver)\n        msg = msg.copy(sub_type=self._const.Stream.ST_FIRMWARE_CONFIG_RESPONSE)\n        msg.payload = fw_int_to_hex(\n            fw_type, fw_ver, fware['blocks'], fware['crc'])\n        return msg",
    "docstring": "Respond to a firmware config request."
  },
  {
    "code": "def get_vector(self, max_choice=3):\n        vec = {}\n        for dim in ['forbidden', 'required', 'permitted']:\n            if self.meta[dim] is None:\n                continue\n            dim_vec = map(lambda x: (x, max_choice), self.meta[dim])\n            vec[dim] = dict(dim_vec)\n        return vec",
    "docstring": "Return pseudo-choice vectors."
  },
  {
    "code": "def to_hdf(self,path,key,mode='a'):\n        pd.DataFrame(self.serialize()).to_hdf(path,key,mode=mode,format='table',complib='zlib',complevel=9)\n        f = h5py.File(path,'r+')\n        f[key].attrs[\"microns_per_pixel\"] = float(self.microns_per_pixel) if self.microns_per_pixel is not None else np.nan\n        f.close()",
    "docstring": "Save the CellDataFrame to an hdf5 file.\n\n        Args:\n            path (str): the path to save to\n            key (str): the name of the location to save it to\n            mode (str): write mode"
  },
  {
    "code": "def get_xml_root(xml_file):\n    try:\n        xml_root = etree.parse(os.path.expanduser(xml_file), NO_BLANKS_PARSER).getroot()\n    except Exception as err:\n        raise Dump2PolarionException(\"Failed to parse XML file '{}': {}\".format(xml_file, err))\n    return xml_root",
    "docstring": "Returns XML root."
  },
  {
    "code": "def getNextJobID(self):\n        with self.localBatch.jobIndexLock:\n            jobID = self.localBatch.jobIndex\n            self.localBatch.jobIndex += 1\n        return jobID",
    "docstring": "Must be used to get job IDs so that the local and batch jobs do not\n        conflict."
  },
  {
    "code": "def params(self):\n        par = {\"radius\": self.radius,\n               \"sphere_index\": self.sphere_index,\n               \"pha_offset\": self.pha_offset,\n               \"center\": [self.posx_offset, self.posy_offset]\n               }\n        return par",
    "docstring": "Current interpolation parameter dictionary"
  },
  {
    "code": "def FromFile(cls, in_path):\n        with open(in_path, \"rb\") as infile:\n            in_data = json.load(infile)\n        if not ('trace', 'selectors') in in_data:\n            raise ArgumentError(\"Invalid trace file format\", keys=in_data.keys(), expected=('trace', 'selectors'))\n        selectors = [DataStreamSelector.FromString(x) for x in in_data['selectors']]\n        readings = [IOTileReading(x['time'], DataStream.FromString(x['stream']).encode(), x['value'], reading_id=x['reading_id']) for x in in_data['trace']]\n        return SimulationTrace(readings, selectors=selectors)",
    "docstring": "Load a previously saved ascii representation of this simulation trace.\n\n        Args:\n            in_path (str): The path of the input file that we should load.\n\n        Returns:\n            SimulationTrace: The loaded trace object."
  },
  {
    "code": "def set_matrix_dimensions(self, *args):\n        self._image = None\n        super(FileImage, self).set_matrix_dimensions(*args)",
    "docstring": "Subclassed to delete the cached image when matrix dimensions\n        are changed."
  },
  {
    "code": "def add_sample_meta(self,\n                        source,\n                        reference,\n                        method='',\n                        filename='',\n                        md5='',\n                        sha1='',\n                        sha256='',\n                        size='',\n                        mimetype='',\n                        campaign='',\n                        confidence='',\n                        description='',\n                        bucket_list=[]):\n        data = {\n            'api_key': self.api_key,\n            'username': self.username,\n            'source': source,\n            'reference': reference,\n            'method': method,\n            'filename': filename,\n            'md5': md5,\n            'sha1': sha1,\n            'sha256': sha256,\n            'size': size,\n            'mimetype': mimetype,\n            'upload_type': 'meta',\n            'campaign': campaign,\n            'confidence': confidence,\n            'bucket_list': ','.join(bucket_list),\n        }\n        r = requests.post('{0}/samples/'.format(self.url),\n                          data=data,\n                          verify=self.verify,\n                          proxies=self.proxies)\n        if r.status_code == 200:\n            result_data = json.loads(r.text)\n            return result_data\n        else:\n            log.error('Error with status code {0} and message '\n                      '{1}'.format(r.status_code, r.text))\n        return None",
    "docstring": "Adds a metadata sample. To add an actual file, use add_sample_file.\n\n        Args:\n            source: Source of the information\n            reference: A reference where more information can be found\n            method: The method for obtaining the sample.\n            filename: The name of the file.\n            md5: An MD5 hash of the file.\n            sha1: SHA1 hash of the file.\n            sha256: SHA256 hash of the file.\n            size: size of the file.\n            mimetype: The mimetype of the file.\n            campaign: An associated campaign\n            confidence: The campaign confidence\n            bucket_list: A list of bucket list items to add\n            upload_type: Either 'file' or 'meta'\n        Returns:\n            A JSON sample object or None if there was an error."
  },
  {
    "code": "def get_mac_dot_app_dir(directory):\n    return os.path.dirname(os.path.dirname(os.path.dirname(directory)))",
    "docstring": "Returns parent directory of mac .app\n\n    Args:\n\n       directory (str): Current directory\n\n    Returns:\n\n       (str): Parent directory of mac .app"
  },
  {
    "code": "def _add_monomer(self, monomer, mon_vector, move_direction):\n        translate_by = self.molecule.cart_coords[self.end] + \\\n                       self.link_distance * move_direction\n        monomer.translate_sites(range(len(monomer)), translate_by)\n        if not self.linear_chain:\n            self._align_monomer(monomer, mon_vector, move_direction)\n        does_cross = False\n        for i, site in enumerate(monomer):\n            try:\n                self.molecule.append(site.specie, site.coords,\n                                     properties=site.properties)\n            except:\n                does_cross = True\n                polymer_length = len(self.molecule)\n                self.molecule.remove_sites(\n                    range(polymer_length - i, polymer_length))\n                break\n        if not does_cross:\n            self.length += 1\n            self.end += len(self.monomer)",
    "docstring": "extend the polymer molecule by adding a monomer along mon_vector direction\n\n        Args:\n            monomer (Molecule): monomer molecule\n            mon_vector (numpy.array): monomer vector that points from head to tail.\n            move_direction (numpy.array): direction along which the monomer\n                will be positioned"
  },
  {
    "code": "def get_network(self, name, batch_size=None, callback=None):\n        network_proto = nnabla_pb2.Network()\n        network_proto.CopyFrom(self.network_dict[name])\n        return NnpNetwork(network_proto, self._params, batch_size, callback=callback)",
    "docstring": "Create a variable graph given  network by name\n\n        Returns: NnpNetwork"
  },
  {
    "code": "def get_context(self, publish=False):\n        context = self.project.DEFAULT_CONTEXT\n        try:\n            file = self.project.CONTEXT_SOURCE_FILE\n            if re.search(r'(csv|CSV)$', file):\n                context.update(self.get_context_from_csv())\n            if re.search(r'(xlsx|XLSX|xls|XLS)$', file):\n                context.update(self.get_context_from_xlsx())\n        except AttributeError:\n            context.update(self.get_context_from_gdoc())\n        return context",
    "docstring": "Use optional CONTEXT_SOURCE_FILE setting to determine data source.\n        Return the parsed data.\n\n        Can be an http|https url or local file. Supports csv and excel files."
  },
  {
    "code": "def default_update(self, step, T, E, acceptance, improvement):\n        elapsed = time.time() - self.start\n        if step == 0:\n            print(' Temperature        Energy    Accept   Improve     Elapsed   Remaining',\n                  file=sys.stderr)\n            print('\\r%12.5f  %12.2f                      %s            ' %\n                  (T, E, time_string(elapsed)), file=sys.stderr, end=\"\\r\")\n            sys.stderr.flush()\n        else:\n            remain = (self.steps - step) * (elapsed / step)\n            print('\\r%12.5f  %12.2f  %7.2f%%  %7.2f%%  %s  %s\\r' %\n                  (T, E, 100.0 * acceptance, 100.0 * improvement,\n                   time_string(elapsed), time_string(remain)), file=sys.stderr, end=\"\\r\")\n            sys.stderr.flush()",
    "docstring": "Default update, outputs to stderr.\n\n        Prints the current temperature, energy, acceptance rate,\n        improvement rate, elapsed time, and remaining time.\n\n        The acceptance rate indicates the percentage of moves since the last\n        update that were accepted by the Metropolis algorithm.  It includes\n        moves that decreased the energy, moves that left the energy\n        unchanged, and moves that increased the energy yet were reached by\n        thermal excitation.\n\n        The improvement rate indicates the percentage of moves since the\n        last update that strictly decreased the energy.  At high\n        temperatures it will include both moves that improved the overall\n        state and moves that simply undid previously accepted moves that\n        increased the energy by thermal excititation.  At low temperatures\n        it will tend toward zero as the moves that can decrease the energy\n        are exhausted and moves that would increase the energy are no longer\n        thermally accessible."
  },
  {
    "code": "def _ParseCmdItem(self, cmd_input, template_file=None):\n    fsm = textfsm.TextFSM(template_file)\n    if not self._keys:\n      self._keys = set(fsm.GetValuesByAttrib('Key'))\n    table = texttable.TextTable()\n    table.header = fsm.header\n    for record in fsm.ParseText(cmd_input):\n      table.Append(record)\n    return table",
    "docstring": "Creates Texttable with output of command.\n\n    Args:\n      cmd_input: String, Device response.\n      template_file: File object, template to parse with.\n\n    Returns:\n      TextTable containing command output.\n\n    Raises:\n      CliTableError: A template was not found for the given command."
  },
  {
    "code": "def add_ref(self, wordlist):\n\t\trefname = wordlist[0][:-1]\n\t\tif(refname in self.refs):\n\t\t\traise ReferenceError(\"[line {}]:{} already defined here (word) {} (line) {}\".format(self.line_count, \n\t\t\t\t\t\trefname, self.refs[refname][0], self.refs[refname][1]))\n\t\tself.refs[refname] = (self.word_count, self.line_count)",
    "docstring": "Adds a reference."
  },
  {
    "code": "def linkify_h_by_h(self):\n        for host in self:\n            new_parents = []\n            for parent in getattr(host, 'parents', []):\n                parent = parent.strip()\n                o_parent = self.find_by_name(parent)\n                if o_parent is not None:\n                    new_parents.append(o_parent.uuid)\n                else:\n                    err = \"the parent '%s' for the host '%s' is unknown!\" % (parent,\n                                                                             host.get_name())\n                    self.add_error(err)\n            host.parents = new_parents",
    "docstring": "Link hosts with their parents\n\n        :return: None"
  },
  {
    "code": "def symbol(self, index):\r\n        if isinstance(index, str):\r\n            return index\r\n        elif (index < 0) or (index >= self.symtab.table_len):\r\n            self.error(\"symbol table index out of range\")\r\n        sym = self.symtab.table[index]\r\n        if sym.kind == SharedData.KINDS.LOCAL_VAR:\r\n            return \"-{0}(1:%14)\".format(sym.attribute * 4 + 4)\r\n        elif sym.kind == SharedData.KINDS.PARAMETER:\r\n            return \"{0}(1:%14)\".format(8 + sym.attribute * 4)\r\n        elif sym.kind == SharedData.KINDS.CONSTANT:\r\n            return \"${0}\".format(sym.name)\r\n        else:\r\n            return \"{0}\".format(sym.name)",
    "docstring": "Generates symbol name from index"
  },
  {
    "code": "def state_machines_set_notification(self, model, prop_name, info):\n        if info['method_name'] == '__setitem__':\n            state_machine_m = info.args[1]\n            self.observe_model(state_machine_m)",
    "docstring": "Observe all open state machines and their root states"
  },
  {
    "code": "def size(self, time):\n        if self.start_time <= time <= self.end_time:\n            return self.masks[time - self.start_time].sum()\n        else:\n            return 0",
    "docstring": "Gets the size of the object at a given time.\n\n        Args:\n            time: Time value being queried.\n\n        Returns:\n            size of the object in pixels"
  },
  {
    "code": "def when_connected(self):\n        if self._client and not self._client.is_closed:\n            return defer.succeed(self._client)\n        else:\n            return self._client_deferred",
    "docstring": "Retrieve the currently-connected Protocol, or the next one to connect.\n\n        Returns:\n            defer.Deferred: A Deferred that fires with a connected\n                :class:`FedoraMessagingProtocolV2` instance. This is similar to\n                the whenConnected method from the Twisted endpoints APIs, which\n                is sadly isn't available before 16.1.0, which isn't available\n                in EL7."
  },
  {
    "code": "def translate_indirect(properties, context_module):\n    assert is_iterable_typed(properties, Property)\n    assert isinstance(context_module, basestring)\n    result = []\n    for p in properties:\n        if p.value[0] == '@':\n            q = qualify_jam_action(p.value[1:], context_module)\n            get_manager().engine().register_bjam_action(q)\n            result.append(Property(p.feature, '@' + q, p.condition))\n        else:\n            result.append(p)\n    return result",
    "docstring": "Assumes that all feature values that start with '@' are\n    names of rules, used in 'context-module'. Such rules can be\n    either local to the module or global. Qualified local rules\n    with the name of the module."
  },
  {
    "code": "def register_patches(self):\n        if not self.__paths:\n            return False\n        unregistered_patches = []\n        for path in self.paths:\n            for file in foundations.walkers.files_walker(path, (\"\\.{0}$\".format(self.__extension),), (\"\\._\",)):\n                name = foundations.strings.get_splitext_basename(file)\n                if not self.register_patch(name, file):\n                    unregistered_patches.append(name)\n        if not unregistered_patches:\n            return True\n        else:\n            raise umbra.exceptions.PatchRegistrationError(\n                \"{0} | '{1}' patches failed to register!\".format(self.__class__.__name__,\n                                                                 \", \".join(unregistered_patches)))",
    "docstring": "Registers the patches.\n\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def signed_in_users(session=None, today=None, full_name=True):\n    if session is None:\n        session = Session()\n    else:\n        session = session\n    if today is None:\n        today = date.today()\n    else:\n        today = today\n    signed_in_users = (\n        session\n        .query(User)\n        .filter(Entry.date == today)\n        .filter(Entry.time_out.is_(None))\n        .filter(User.user_id == Entry.user_id)\n        .all()\n    )\n    session.close()\n    return signed_in_users",
    "docstring": "Return list of names of currently signed in users.\n\n    :param session: SQLAlchemy session through which to access the database.\n    :param today: (optional) The current date as a `datetime.date` object. Used for testing.\n    :param full_name: (optional) Whether to display full user names, or just first names.\n    :return: List of currently signed in users."
  },
  {
    "code": "def AgregarAjusteFisico(self, cantidad, cantidad_cabezas=None, \n                            cantidad_kg_vivo=None, **kwargs):\n        \"Agrega campos al detalle de item por un ajuste fisico\"\n        d = {'cantidad': cantidad,\n             'cantidadCabezas': cantidad_cabezas, \n             'cantidadKgVivo': cantidad_kg_vivo, \n            }\n        item_liq = self.solicitud['itemDetalleAjusteLiquidacion'][-1]\n        item_liq['ajusteFisico'] = d\n        return True",
    "docstring": "Agrega campos al detalle de item por un ajuste fisico"
  },
  {
    "code": "def get_all_results(starting_page):\n    logging.info('Retrieving all results for {}'.format(starting_page))\n    page = starting_page\n    results = []\n    while True:\n        logging.debug('Getting data from: {}'.format(page))\n        data = get_page(page)\n        logging.debug('JSON data: {}'.format(data))\n        results = results + data['results']\n        if data['next']:\n            page = data['next']\n        else:\n            break\n    return results",
    "docstring": "Given starting API query for Open Humans, iterate to get all results.\n\n    :param starting page: This field is the first page, starting from which\n        results will be obtained."
  },
  {
    "code": "def create_typedef(self, typedef_name, unused=None, with_defaults=True):\n        return free_function_type_t.TYPEDEF_NAME_TEMPLATE % {\n            'typedef_name': typedef_name,\n            'return_type': self.return_type.build_decl_string(with_defaults),\n            'arguments': ','.join(\n                [_f(x, with_defaults) for x in self.arguments_types])}",
    "docstring": "returns string, that contains valid C++ code, that defines typedef\n        to function type\n\n        :param name: the desired name of typedef"
  },
  {
    "code": "def find_egg(self, egg_dist):\n        site_packages = self.libdir[1]\n        search_filename = \"{0}.egg-link\".format(egg_dist.project_name)\n        try:\n            user_site = site.getusersitepackages()\n        except AttributeError:\n            user_site = site.USER_SITE\n        search_locations = [site_packages, user_site]\n        for site_directory in search_locations:\n            egg = os.path.join(site_directory, search_filename)\n            if os.path.isfile(egg):\n                return egg",
    "docstring": "Find an egg by name in the given environment"
  },
  {
    "code": "def _directory (self):\n        if self._filename is None:\n            return os.path.join(self._ROOT_DIR, 'config')\n        else:\n            return os.path.dirname(self._filename)",
    "docstring": "The directory for this AitConfig."
  },
  {
    "code": "def _write_user_prefs(self, user_prefs):\n        with open(self.userPrefs, \"w\") as f:\n            for key, value in user_prefs.items():\n                f.write('user_pref(\"%s\", %s);\\n' % (key, json.dumps(value)))",
    "docstring": "writes the current user prefs dictionary to disk"
  },
  {
    "code": "def delete_pod(name, namespace='default', **kwargs):\n    cfg = _setup_conn(**kwargs)\n    body = kubernetes.client.V1DeleteOptions(orphan_dependents=True)\n    try:\n        api_instance = kubernetes.client.CoreV1Api()\n        api_response = api_instance.delete_namespaced_pod(\n            name=name,\n            namespace=namespace,\n            body=body)\n        return api_response.to_dict()\n    except (ApiException, HTTPError) as exc:\n        if isinstance(exc, ApiException) and exc.status == 404:\n            return None\n        else:\n            log.exception(\n                'Exception when calling '\n                'CoreV1Api->delete_namespaced_pod'\n            )\n            raise CommandExecutionError(exc)\n    finally:\n        _cleanup(**cfg)",
    "docstring": "Deletes the kubernetes pod defined by name and namespace\n\n    CLI Examples::\n\n        salt '*' kubernetes.delete_pod guestbook-708336848-5nl8c default\n        salt '*' kubernetes.delete_pod name=guestbook-708336848-5nl8c namespace=default"
  },
  {
    "code": "def free_symbols(self):\n        return set([\n            sym for sym in self.term.free_symbols\n            if sym not in self.bound_symbols])",
    "docstring": "Set of all free symbols"
  },
  {
    "code": "def ask(message='Are you sure? [y/N]'):\n    agree = False\n    answer = raw_input(message).lower()\n    if answer.startswith('y'):\n        agree = True\n    return agree",
    "docstring": "Asks the user his opinion."
  },
  {
    "code": "def better_sentences(func):\n    @wraps(func)\n    def wrapped(*args):\n            sentences = func(*args)\n            new_sentences = []\n            for i, l in enumerate(sentences):\n                if '\\n\\n' in l:\n                    splits = l.split('\\n\\n')\n                    if len(splits)>1:\n                        for ind,spl in enumerate(splits):\n                            if len(spl) <20:\n                                del splits[ind]\n                    new_sentences.extend(splits)\n                else:\n                    new_sentences.append(l)\n            return new_sentences\n    return wrapped",
    "docstring": "takes care of some edge cases of sentence\n    tokenization for cases when websites don't\n    close sentences properly, usually after\n    blockquotes, image captions or attributions"
  },
  {
    "code": "def update(self, ipv4s):\n        data = {'ips': ipv4s}\n        ipv4s_ids = [str(ipv4.get('id')) for ipv4 in ipv4s]\n        return super(ApiIPv4, self).put('api/v3/ipv4/%s/' %\n                                        ';'.join(ipv4s_ids), data)",
    "docstring": "Method to update ipv4's\n\n        :param ipv4s: List containing ipv4's desired to updated\n        :return: None"
  },
  {
    "code": "def nxapi_request(commands,\n                  method='cli_show',\n                  **kwargs):\n    client = NxapiClient(**kwargs)\n    return client.request(method, commands)",
    "docstring": "Send exec and config commands to the NX-OS device over NX-API.\n\n    commands\n        The exec or config commands to be sent.\n\n    method:\n        ``cli_show_ascii``: Return raw test or unstructured output.\n        ``cli_show``: Return structured output.\n        ``cli_conf``: Send configuration commands to the device.\n        Defaults to ``cli_show``.\n\n    transport: ``https``\n        Specifies the type of connection transport to use. Valid values for the\n        connection are ``http``, and  ``https``.\n\n    host: ``localhost``\n        The IP address or DNS host name of the device.\n\n    username: ``admin``\n        The username to pass to the device to authenticate the NX-API connection.\n\n    password\n        The password to pass to the device to authenticate the NX-API connection.\n\n    port\n        The TCP port of the endpoint for the NX-API connection. If this keyword is\n        not specified, the default value is automatically determined by the\n        transport type (``80`` for ``http``, or ``443`` for ``https``).\n\n    timeout: ``60``\n        Time in seconds to wait for the device to respond. Default: 60 seconds.\n\n    verify: ``True``\n        Either a boolean, in which case it controls whether we verify the NX-API\n        TLS certificate, or a string, in which case it must be a path to a CA bundle\n        to use. Defaults to ``True``."
  },
  {
    "code": "def _convert_params(sql, params):\n    args = [sql]\n    if params is not None:\n        if hasattr(params, 'keys'):\n            args += [params]\n        else:\n            args += [list(params)]\n    return args",
    "docstring": "Convert SQL and params args to DBAPI2.0 compliant format."
  },
  {
    "code": "def _query_params(self):\n        params = {}\n        if self.generation is not None:\n            params[\"generation\"] = self.generation\n        if self.user_project is not None:\n            params[\"userProject\"] = self.user_project\n        return params",
    "docstring": "Default query parameters."
  },
  {
    "code": "def __assert_not_empty(returned):\n        result = \"Pass\"\n        try:\n            assert (returned), \"value is empty\"\n        except AssertionError as err:\n            result = \"Fail: \" + six.text_type(err)\n        return result",
    "docstring": "Test if a returned value is not empty"
  },
  {
    "code": "def create_current_pb(self, ):\n        pb = QtGui.QPushButton(\"Select current\")\n        self.selection_tabw.setCornerWidget(pb)\n        return pb",
    "docstring": "Create a push button and place it in the corner of the tabwidget\n\n        :returns: the created button\n        :rtype: :class:`QtGui.QPushButton`\n        :raises: None"
  },
  {
    "code": "def run(targets, config_dir='.', check_licenses=False):\n    pylint_return_state = False\n    flake8_return_state = False\n    if check_licenses:\n        run_license_checker(config_path=get_license_checker_config_path(config_dir))\n    pylint_options = get_pylint_options(config_dir=config_dir)\n    flake8_options = get_flake8_options(config_dir=config_dir)\n    if targets:\n        pylint_return_state = _run_command(command='pylint', targets=targets,\n                                           options=pylint_options)\n        flake8_return_state = _run_command(command='flake8', targets=targets,\n                                           options=flake8_options)\n    if not flake8_return_state and not pylint_return_state:\n        sys.exit(0)\n    else:\n        sys.exit(1)",
    "docstring": "Runs `pylint` and `flake8` commands and exits based off the evaluation\n    of both command results.\n\n    :param targets: List[str]\n    :param config_dir: str\n    :param check_licenses: bool\n    :return:"
  },
  {
    "code": "def precision_recall(self):\n        return plot.precision_recall(self.y_true, self.y_score, ax=_gen_ax())",
    "docstring": "Precision-recall plot"
  },
  {
    "code": "def _start_data_json(self) -> str:\n        rv = {\n            'logging': {\n                'paths': []\n            },\n            'wallet': {\n            }\n        }\n        logger = LOGGER\n        while not logger.level:\n            logger = logger.parent\n            if logger is None:\n                break\n        rv['logging']['level'] = logger.level\n        logger = LOGGER\n        log_paths = [realpath(h.baseFilename) for h in logger.handlers if hasattr(h, 'baseFilename')]\n        while not log_paths:\n            logger = logger.parent\n            if logger is None:\n                break\n            log_paths = [realpath(h.baseFilename) for h in logger.handlers if hasattr(h, 'baseFilename')]\n        for log_path in log_paths:\n            rv['logging']['paths'].append(log_path)\n        rv['wallet']['storage_type'] = self.wallet.storage_type\n        rv['wallet']['config'] = self.wallet.config\n        rv['wallet']['access_creds'] = self.wallet.access_creds\n        return json.dumps(rv)",
    "docstring": "Output json with start data to write for external revocation registry builder process pickup.\n\n        :return: logging and wallet init data json"
  },
  {
    "code": "def main(argv=None):\n    opts = cmdparse.parse_args(argv)\n    assert validate_opts.validate(opts)\n    opts = normalize_opts.normalize(opts)\n    if opts.verbose:\n        messages.print_input_output(opts)\n    file_paths = fileparse.get_file_list(opts)\n    assert validate_files.validate(file_paths, opts)\n    if opts.verbose and opts.is_dir:\n        messages.print_files(opts, file_paths)\n    collector = make_github_markdown_collector(opts)\n    anchors, duplicate_tags = collector.collect(file_paths)\n    assert validate_anchors.validate(anchors, duplicate_tags, opts)\n    writer = make_github_markdown_writer(opts)\n    counter = writer.write(file_paths, anchors, opts)\n    if opts.verbose:\n        if opts.is_dir:\n            messages.print_modified_files(opts, anchors)\n        messages.print_summary_stats(counter)",
    "docstring": "Main entry method for AnchorHub. Takes in command-line arguments,\n    finds files to parse within the specified input directory, and outputs\n    parsed files to the specified output directory.\n\n    :param argv: a list of string command line arguments"
  },
  {
    "code": "def read_files(*files):\n    text = \"\"\n    for single_file in files:\n        content = read(single_file)\n        text = text + content + \"\\n\"\n    return text",
    "docstring": "Read files into setup"
  },
  {
    "code": "def _postprocess(self, filehandle, metadata):\n        \"Runs all attached postprocessors on the provided filehandle.\"\n        for process in self._postprocessors:\n            filehandle = process(filehandle, metadata)\n        return filehandle",
    "docstring": "Runs all attached postprocessors on the provided filehandle."
  },
  {
    "code": "def transformer_mlperf_tpu():\n  hparams = transformer_base_v3()\n  hparams.mlperf_mode = True\n  hparams.symbol_modality_num_shards = 1\n  hparams.max_length = 256\n  hparams.batch_size = 2048\n  hparams.hidden_size = 1024\n  hparams.filter_size = 4096\n  hparams.num_heads = 16\n  hparams.attention_dropout_broadcast_dims = \"0,1\"\n  hparams.relu_dropout_broadcast_dims = \"1\"\n  hparams.layer_prepostprocess_dropout_broadcast_dims = \"1\"\n  return hparams",
    "docstring": "HParams for Transformer model on TPU for MLPerf on TPU 2x2."
  },
  {
    "code": "def after_flush_postexec(self, session, context):\n        instances = self.instances[session]\n        while instances:\n            instance = instances.pop()\n            if instance not in session:\n                continue\n            parent = self.get_parent_value(instance)\n            while parent != NO_VALUE and parent is not None:\n                instances.discard(parent)\n                session.expire(parent, ['left', 'right', 'tree_id', 'level'])\n                parent = self.get_parent_value(parent)\n            else:\n                session.expire(instance, ['left', 'right', 'tree_id', 'level'])\n                self.expire_session_for_children(session, instance)",
    "docstring": "Event listener to recursively expire `left` and `right` attributes the\n        parents of all modified instances part of this flush."
  },
  {
    "code": "def request(func=None, timeout=600):\n    if func is None:\n        return partial(request, timeout=timeout)\n    @wraps(func)\n    def wrapper(self, *args, **kwargs):\n        params = func(self, *args, **kwargs)\n        self = params.pop('self', None)\n        entity = params.pop('entity', None)\n        app_name = params.pop('app_name', None)\n        request_id = unique_hex()\n        params['request_id'] = request_id\n        future = self._send_request(app_name, endpoint=func.__name__, entity=entity, params=params, timeout=timeout)\n        return future\n    wrapper.is_request = True\n    return wrapper",
    "docstring": "use to request an api call from a specific endpoint"
  },
  {
    "code": "def stop(self):\n        LOGGER.info('Shutting down controller')\n        self.set_state(self.STATE_STOP_REQUESTED)\n        signal.setitimer(signal.ITIMER_PROF, 0, 0)\n        self._mcp.stop_processes()\n        if self._mcp.is_running:\n            LOGGER.info('Waiting up to 3 seconds for MCP to shut things down')\n            signal.setitimer(signal.ITIMER_REAL, 3, 0)\n            signal.pause()\n            LOGGER.info('Post pause')\n        if self._mcp.is_running:\n            LOGGER.warning('MCP is taking too long, requesting process kills')\n            self._mcp.stop_processes()\n            del self._mcp\n        else:\n            LOGGER.info('MCP exited cleanly')\n        self._stopped()\n        LOGGER.info('Shutdown complete')",
    "docstring": "Shutdown the MCP and child processes cleanly"
  },
  {
    "code": "def from_dict(cls, tag=None):\n        if tag is None:\n            tag = {}\n        l = Tag()\n        l.name = tag['name']\n        return l",
    "docstring": "Create new Tag-object from dict.\n\n            Suitable for creating objects from XML-RPC data.\n            All available keys must exist."
  },
  {
    "code": "def datetime_to_djd(time):\n    if time.tzinfo is None:\n        time_utc = pytz.utc.localize(time)\n    else:\n        time_utc = time.astimezone(pytz.utc)\n    djd_start = pytz.utc.localize(dt.datetime(1899, 12, 31, 12))\n    djd = (time_utc - djd_start).total_seconds() * 1.0/(60 * 60 * 24)\n    return djd",
    "docstring": "Converts a datetime to the Dublin Julian Day\n\n    Parameters\n    ----------\n    time : datetime.datetime\n        time to convert\n\n    Returns\n    -------\n    float\n        fractional days since 12/31/1899+0000"
  },
  {
    "code": "def relfreq(inlist, numbins=10, defaultreallimits=None):\n    h, l, b, e = histogram(inlist, numbins, defaultreallimits)\n    for i in range(len(h)):\n        h[i] = h[i] / float(len(inlist))\n    return h, l, b, e",
    "docstring": "Returns a relative frequency histogram, using the histogram function.\n\nUsage:   lrelfreq(inlist,numbins=10,defaultreallimits=None)\nReturns: list of cumfreq bin values, lowerreallimit, binsize, extrapoints"
  },
  {
    "code": "def as_dict(self) -> Dict[str, str]:\n        items: Dict[str, str] = {}\n        for k, v in self.items():\n            if type(v) is str:\n                items.update({k: v})\n        return items",
    "docstring": "Export color register as dict."
  },
  {
    "code": "def dremove(self, **kwds):\n        filtered_dr = self.dfilter(**kwds)\n        for item in filtered_dr:\n            self.remove(item)\n        return filtered_dr",
    "docstring": "Removes from the object any element that matches the\n        given specification."
  },
  {
    "code": "def load(cls, v):\n        if v is None:\n            return []\n        if isinstance(v, list):\n            return [ Action(s) for s in v ]\n        elif isinstance(v, str):\n            return [Action(v)]\n        else:\n            raise ParseError(\"Couldn't parse action: %r\" % v)",
    "docstring": "Load the action from configuration"
  },
  {
    "code": "def rgb_to_xterm(r, g, b):\n    if r < 5 and g < 5 and b < 5:\n        return 16\n    best_match = 0\n    smallest_distance = 10000000000\n    for c in range(16, 256):\n        d = (COLOR_TABLE[c][0] - r) ** 2 + \\\n            (COLOR_TABLE[c][1] - g) ** 2 + \\\n            (COLOR_TABLE[c][2] - b) ** 2\n        if d < smallest_distance:\n            smallest_distance = d\n            best_match = c\n    return best_match",
    "docstring": "Quantize RGB values to an xterm 256-color ID\n\n    This works by envisioning the RGB values for all 256 xterm colors\n    as 3D euclidean space and brute-force searching for the nearest\n    neighbor.\n\n    This is very slow.  If you're very lucky, :func:`compile_speedup`\n    will replace this function automatically with routines in\n    `_xterm256.c`."
  },
  {
    "code": "def delete(self, accountId):\n        acct = BaseAccount.get(accountId)\n        if not acct:\n            raise Exception('No such account found')\n        acct.delete()\n        auditlog(event='account.delete', actor=session['user'].username, data={'accountId': accountId})\n        return self.make_response('Account deleted')",
    "docstring": "Delete an account"
  },
  {
    "code": "def write_info_file(tensorboard_info):\n  payload = \"%s\\n\" % _info_to_string(tensorboard_info)\n  with open(_get_info_file_path(), \"w\") as outfile:\n    outfile.write(payload)",
    "docstring": "Write TensorBoardInfo to the current process's info file.\n\n  This should be called by `main` once the server is ready. When the\n  server shuts down, `remove_info_file` should be called.\n\n  Args:\n    tensorboard_info: A valid `TensorBoardInfo` object.\n\n  Raises:\n    ValueError: If any field on `info` is not of the correct type."
  },
  {
    "code": "def debugArgsToDict(a):\n    s = a.replace('+', ' ')\n    s = s.replace('=', ':')\n    s = re.sub(r'([A-Z][A-Z_]+)', r\"'\\1'\", s)\n    return ast.literal_eval('{ ' + s + ' }')",
    "docstring": "Converts a string representation of debug arguments to a dictionary.\n    The string can be of the form\n\n       IDENTIFIER1=val1,IDENTIFIER2=val2\n\n\n     :param a: the argument string\n     :return: the dictionary"
  },
  {
    "code": "def printLn(self, respType, respString):\n        if 'E' in respType:\n            respString = '(Error) ' + respString\n        if 'W' in respType:\n            respString = '(Warning) ' + respString\n        if 'S' in respType:\n            self.printSysLog(respString)\n        self.results['response'] = (self.results['response'] +\n                                   respString.splitlines())\n        return",
    "docstring": "Add one or lines of output to the response list.\n\n        Input:\n           Response type: One or more characters indicate type of response.\n              E - Error message\n              N - Normal message\n              S - Output should be logged\n              W - Warning message"
  },
  {
    "code": "def flat(self, obj, mask=0):\n        s = self.base\n        if self.leng and self.item > 0:\n            s += self.leng(obj) * self.item\n        if _getsizeof:\n            s = _getsizeof(obj, s)\n        if mask:\n            s = (s + mask) & ~mask\n        return s",
    "docstring": "Return the aligned flat size."
  },
  {
    "code": "def process_messages_loop_internal(self):\n        while self.receiving_messages:\n            self.work_request = None\n            self.connection.receive_loop_with_callback(self.queue_name, self.save_work_request_and_close)\n            if self.work_request:\n                self.process_work_request()",
    "docstring": "Busy loop that processes incoming WorkRequest messages via functions specified by add_command.\n        Disconnects while servicing a message, reconnects once finished processing a message\n        Terminates if a command runs shutdown method"
  },
  {
    "code": "def getsize(self, key=None):\n        if key is None:\n            return os.path.getsize(self.filename)\n        return hdf5.ByteCounter.get_nbytes(\n            h5py.File.__getitem__(self.hdf5, key))",
    "docstring": "Return the size in byte of the output associated to the given key.\n        If no key is given, returns the total size of all files."
  },
  {
    "code": "def _is_number_matching_desc(national_number, number_desc):\n    if number_desc is None:\n        return False\n    actual_length = len(national_number)\n    possible_lengths = number_desc.possible_length\n    if len(possible_lengths) > 0 and actual_length not in possible_lengths:\n        return False\n    return _match_national_number(national_number, number_desc, False)",
    "docstring": "Determine if the number matches the given PhoneNumberDesc"
  },
  {
    "code": "def target_id(self):\n        if self._target_id:\n            return self._target_id\n        if self._existing:\n            self._target_id = self._existing.get(\"target_id\")\n        return self._target_id",
    "docstring": "Returns the id the target, to which this post has to be syndicated.\n\n        :returns: string"
  },
  {
    "code": "def set(self, dict_name, key, value, priority=None):\n        if priority is not None:\n            priorities = {key: priority}\n        else:\n            priorities = None\n        self.update(dict_name, {key: value}, priorities=priorities)",
    "docstring": "Set a single value for a single key.\n\n        This requires a session lock.\n\n        :param str dict_name: name of the dictionary to update\n        :param str key: key to update\n        :param str value: value to assign to `key`\n        :param int priority: priority score for the value (if any)"
  },
  {
    "code": "def _build_graph_run(self, run_args):\n    with tf.Graph().as_default() as g:\n      input_ = run_args.input\n      placeholder = tf.compat.v1.placeholder(\n          dtype=input_.dtype, shape=input_.shape)\n      output = run_args.fct(placeholder)\n    return GraphRun(\n        session=raw_nogpu_session(g),\n        graph=g,\n        placeholder=placeholder,\n        output=output,\n    )",
    "docstring": "Create a new graph for the given args."
  },
  {
    "code": "def query_events(resource_root, query_str=None):\n  params = None\n  if query_str:\n    params = dict(query=query_str)\n  return call(resource_root.get, EVENTS_PATH, ApiEventQueryResult,\n      params=params)",
    "docstring": "Search for events.\n  @param query_str: Query string.\n  @return: A list of ApiEvent."
  },
  {
    "code": "def setError(self, msg=None, title=None):\n        if msg is not None:\n            self.messageLabel.setText(msg)\n        if title is not None:\n            self.titleLabel.setText(title)",
    "docstring": "Shows and error message"
  },
  {
    "code": "def FQP_point_to_FQ2_point(pt: Tuple[FQP, FQP, FQP]) -> Tuple[FQ2, FQ2, FQ2]:\n    return (\n        FQ2(pt[0].coeffs),\n        FQ2(pt[1].coeffs),\n        FQ2(pt[2].coeffs),\n    )",
    "docstring": "Transform FQP to FQ2 for type hinting."
  },
  {
    "code": "def draw_rect(self, rect):\n        check_int_err(lib.SDL_RenderDrawRect(self._ptr, rect._ptr))",
    "docstring": "Draw a rectangle on the current rendering target.\n\n        Args:\n            rect (Rect): The destination rectangle, or None to outline the entire rendering target.\n\n        Raises:\n            SDLError: If an error is encountered."
  },
  {
    "code": "def raw(mime='application/octet-stream'):\n    def dfn(fn):\n        tags = getattr(fn, 'tags', set())\n        tags.add('raw')\n        fn.tags = tags\n        fn.mime = getattr(fn, 'mime', mime)\n        return fn\n    return dfn",
    "docstring": "Constructs a decorator that marks the fn\n    as raw response format"
  },
  {
    "code": "def verify_integrity(self):\n        if not self.__integrity_check:\n            if not self.__appid:\n                raise Exception('U2F_APPID was not defined! Please define it in configuration file.')\n            if self.__facets_enabled and not len(self.__facets_list):\n                raise Exception(\n)\n            undefined_message = 'U2F {name} handler is not defined! Please import {name} through {method}!'\n            if not self.__get_u2f_devices:\n                raise Exception(undefined_message.format(name='Read', method='@u2f.read'))\n            if not self.__save_u2f_devices:\n                raise Exception(undefined_message.format(name='Save', method='@u2f.save'))\n            if not self.__call_success_enroll:\n                raise Exception(undefined_message.format(name='enroll onSuccess', method='@u2f.enroll_on_success'))\n            if not self.__call_success_sign:\n                raise Exception(undefined_message.format(name='sign onSuccess', method='@u2f.sign_on_success'))\n            self.__integrity_check = True\n        return True",
    "docstring": "Verifies that all required functions been injected."
  },
  {
    "code": "def _read_data_type_src(self, length):\n        _resv = self._read_fileng(4)\n        _addr = list()\n        for _ in range((length - 4) // 16):\n            _addr.append(ipaddress.ip_address(self._read_fileng(16)))\n        data = dict(\n            ip=tuple(_addr),\n        )\n        return data",
    "docstring": "Read IPv6-Route Source Route data.\n\n        Structure of IPv6-Route Source Route data [RFC 5095]:\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |  Next Header  |  Hdr Ext Len  | Routing Type=0| Segments Left |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |                            Reserved                           |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |                                                               |\n            +                                                               +\n            |                                                               |\n            +                           Address[1]                          +\n            |                                                               |\n            +                                                               +\n            |                                                               |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |                                                               |\n            +                                                               +\n            |                                                               |\n            +                           Address[2]                          +\n            |                                                               |\n            +                                                               +\n            |                                                               |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            .                               .                               .\n            .                               .                               .\n            .                               .                               .\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |                                                               |\n            +                                                               +\n            |                                                               |\n            +                           Address[n]                          +\n            |                                                               |\n            +                                                               +\n            |                                                               |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n            Octets      Bits        Name                    Description\n              0           0     route.next              Next Header\n              1           8     route.length            Header Extensive Length\n              2          16     route.type              Routing Type\n              3          24     route.seg_left          Segments Left\n              4          32     -                       Reserved\n              8          64     route.ip                Address\n                                ............"
  },
  {
    "code": "def v_grammar_unique_defs(ctx, stmt):\n    defs = [('typedef', 'TYPE_ALREADY_DEFINED', stmt.i_typedefs),\n            ('grouping', 'GROUPING_ALREADY_DEFINED', stmt.i_groupings)]\n    if stmt.parent is None:\n        defs.extend(\n            [('feature', 'FEATURE_ALREADY_DEFINED', stmt.i_features),\n             ('identity', 'IDENTITY_ALREADY_DEFINED', stmt.i_identities),\n             ('extension', 'EXTENSION_ALREADY_DEFINED', stmt.i_extensions)])\n    for (keyword, errcode, dict) in defs:\n        for definition in stmt.search(keyword):\n            if definition.arg in dict:\n                other = dict[definition.arg]\n                err_add(ctx.errors, definition.pos,\n                        errcode, (definition.arg, other.pos))\n            else:\n                dict[definition.arg] = definition",
    "docstring": "Verify that all typedefs and groupings are unique\n    Called for every statement.\n    Stores all typedefs in stmt.i_typedef, groupings in stmt.i_grouping"
  },
  {
    "code": "def run(self):\n        while True:\n            try:\n                cursor = JSON_CLIENT.json_client['local']['oplog.rs'].find(\n                    {'ts': {'$gt': self.last_timestamp}})\n            except TypeError:\n                pass\n            else:\n                cursor.add_option(2)\n                cursor.add_option(8)\n                cursor.add_option(32)\n                self._retry()\n                for doc in cursor:\n                    self.last_timestamp = doc['ts']\n                    if doc['ns'] in self.receivers:\n                        self._run_namespace(doc)\n            time.sleep(1)",
    "docstring": "main control loop for thread"
  },
  {
    "code": "def macro_state(self, micro_state):\n        assert len(micro_state) == len(self.micro_indices)\n        reindexed = self.reindex()\n        micro_state = np.array(micro_state)\n        return tuple(0 if sum(micro_state[list(reindexed.partition[i])])\n                     in self.grouping[i][0] else 1\n                     for i in self.macro_indices)",
    "docstring": "Translate a micro state to a macro state\n\n        Args:\n            micro_state (tuple[int]): The state of the micro nodes in this\n                coarse-graining.\n\n        Returns:\n            tuple[int]: The state of the macro system, translated as specified\n            by this coarse-graining.\n\n        Example:\n            >>> coarse_grain = CoarseGrain(((1, 2),), (((0,), (1, 2)),))\n            >>> coarse_grain.macro_state((0, 0))\n            (0,)\n            >>> coarse_grain.macro_state((1, 0))\n            (1,)\n            >>> coarse_grain.macro_state((1, 1))\n            (1,)"
  },
  {
    "code": "def from_config(cls, pyvlx, item):\n        name = item['name']\n        ident = item['id']\n        subtype = item['subtype']\n        typeid = item['typeId']\n        return cls(pyvlx, ident, name, subtype, typeid)",
    "docstring": "Read roller shutter from config."
  },
  {
    "code": "def primary_from_id(self, tax_id):\n        s = select([self.names.c.tax_name],\n                   and_(self.names.c.tax_id == tax_id,\n                        self.names.c.is_primary))\n        res = s.execute()\n        output = res.fetchone()\n        if not output:\n            msg = 'value \"{}\" not found in names.tax_id'.format(tax_id)\n            raise ValueError(msg)\n        else:\n            return output[0]",
    "docstring": "Returns primary taxonomic name associated with tax_id"
  },
  {
    "code": "def is_compression_coordinate(ds, variable):\n    if not is_coordinate_variable(ds, variable):\n        return False\n    compress = getattr(ds.variables[variable], 'compress', None)\n    if not isinstance(compress, basestring):\n        return False\n    if not compress:\n        return False\n    if variable in compress:\n        return False\n    for dim in compress.split():\n        if dim not in ds.dimensions:\n            return False\n    return True",
    "docstring": "Returns True if the variable is a coordinate variable that defines a\n    compression scheme.\n\n    :param netCDF4.Dataset nc: An open netCDF dataset\n    :param str variable: Variable name"
  },
  {
    "code": "def enable() -> None:\n        if not isinstance(sys.stdout, DebugPrint):\n            sys.stdout = DebugPrint(sys.stdout)",
    "docstring": "Patch ``sys.stdout`` to use ``DebugPrint``."
  },
  {
    "code": "def _check_kets(*ops, same_space=False, disjunct_space=False):\n    if not all([(isinstance(o, State) and o.isket) for o in ops]):\n        raise TypeError(\"All operands must be Kets\")\n    if same_space:\n        if not len({o.space for o in ops if o is not ZeroKet}) == 1:\n            raise UnequalSpaces(str(ops))\n    if disjunct_space:\n        spc = TrivialSpace\n        for o in ops:\n            if o.space & spc > TrivialSpace:\n                raise OverlappingSpaces(str(ops))\n            spc *= o.space",
    "docstring": "Check that all operands are Kets from the same Hilbert space."
  },
  {
    "code": "def karbasa(self, result):\n        probs = result['all_probs']\n        probs.sort()\n        return float(probs[1] - probs[0]) / float(probs[-1] - probs[0])",
    "docstring": "Finding if class probabilities are close to eachother\n            Ratio of the distance between 1st and 2nd class,\n            to the distance between 1st and last class.\n\n            :param result: The dict returned by LM.calculate()"
  },
  {
    "code": "def install_supervisor(self, update=False):\n        script = supervisor.Recipe(\n            self.buildout,\n            self.name,\n            {'user': self.options.get('user'),\n             'program': self.options.get('program'),\n             'command': templ_cmd.render(config=self.conf_filename, prefix=self.prefix),\n             'stopwaitsecs': '30',\n             'killasgroup': 'true',\n             })\n        return script.install(update)",
    "docstring": "install supervisor config for redis"
  },
  {
    "code": "def docker_container():\n    if SETUP_SPLASH:\n        dm = DockerManager()\n        dm.start_container()\n    try:\n        requests.post(f'{SPLASH_URL}/_gc')\n    except requests.exceptions.RequestException:\n        pass\n    yield",
    "docstring": "Start the Splash server on a Docker container.\n    If the container doesn't exist, it is created and named 'splash-detectem'."
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        xtra = _dict.copy()\n        if 'id' in _dict:\n            args['id'] = _dict.get('id')\n            del xtra['id']\n        if 'metadata' in _dict:\n            args['metadata'] = _dict.get('metadata')\n            del xtra['metadata']\n        if 'collection_id' in _dict:\n            args['collection_id'] = _dict.get('collection_id')\n            del xtra['collection_id']\n        if 'result_metadata' in _dict:\n            args['result_metadata'] = QueryResultMetadata._from_dict(\n                _dict.get('result_metadata'))\n            del xtra['result_metadata']\n        if 'title' in _dict:\n            args['title'] = _dict.get('title')\n            del xtra['title']\n        args.update(xtra)\n        return cls(**args)",
    "docstring": "Initialize a QueryResult object from a json dictionary."
  },
  {
    "code": "def bill(self, year=None, month=None):\n        endpoint = '/'.join((self.server_url, '_api', 'v2', 'bill'))\n        return self._usage_endpoint(endpoint, year, month)",
    "docstring": "Retrieves Cloudant billing data, optionally for a given year and month.\n\n        :param int year: Year to query against, for example 2014.\n            Optional parameter.  Defaults to None.  If used, it must be\n            accompanied by ``month``.\n        :param int month: Month to query against that must be an integer\n            between 1 and 12.  Optional parameter.  Defaults to None.\n            If used, it must be accompanied by ``year``.\n\n        :returns: Billing data in JSON format"
  },
  {
    "code": "def run_process(*args, **kwargs):\n    warnings.warn(\n        \"procrunner.run_process() is deprecated and has been renamed to run()\",\n        DeprecationWarning,\n        stacklevel=2,\n    )\n    return run(*args, **kwargs)",
    "docstring": "API used up to version 0.2.0."
  },
  {
    "code": "def nanoFTPProxy(host, port, user, passwd, type):\n    libxml2mod.xmlNanoFTPProxy(host, port, user, passwd, type)",
    "docstring": "Setup the FTP proxy informations. This can also be done by\n      using ftp_proxy ftp_proxy_user and ftp_proxy_password\n       environment variables."
  },
  {
    "code": "def pprofile(line, cell=None):\n    if cell is None:\n        return run(line)\n    return _main(\n        ['%%pprofile', '-m', '-'] + shlex.split(line),\n        io.StringIO(cell),\n    )",
    "docstring": "Profile line execution."
  },
  {
    "code": "def Query(self, query):\n    cursor = self._database.cursor()\n    cursor.execute(query)\n    return cursor",
    "docstring": "Queries the database.\n\n    Args:\n      query (str): SQL query.\n\n    Returns:\n      sqlite3.Cursor: results.\n\n    Raises:\n      sqlite3.DatabaseError: if querying the database fails."
  },
  {
    "code": "def chosen_inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs):\n        def decorator(callback):\n            self.register_chosen_inline_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs)\n            return callback\n        return decorator",
    "docstring": "Decorator for chosen inline query handler\n\n        Example:\n\n        .. code-block:: python3\n\n            @dp.chosen_inline_handler(lambda chosen_inline_query: True)\n            async def some_chosen_inline_handler(chosen_inline_query: types.ChosenInlineResult)\n\n        :param state:\n        :param custom_filters:\n        :param run_task: run callback in task (no wait results)\n        :param kwargs:\n        :return:"
  },
  {
    "code": "def assign_candidate(self, verse: Verse, candidate: str) -> Verse:\n        verse.scansion = candidate\n        verse.valid = True\n        verse.accented = self.formatter.merge_line_scansion(\n            verse.original, verse.scansion)\n        return verse",
    "docstring": "Helper method; make sure that the verse object is properly packaged.\n\n        :param verse:\n        :param candidate:\n        :return:"
  },
  {
    "code": "def increment(method):\n        if not hasattr(method, '__context'):\n            raise ContextException(\"Method does not have context!\")\n        ctxt = getattr(method, '__context')\n        ctxt.enter()\n        return ctxt",
    "docstring": "Static method used to increment the depth of a context belonging to 'method'\n\n        :param function method: A method with a context\n\n        :rtype: caliendo.hooks.Context\n        :returns: The context instance for the method."
  },
  {
    "code": "def delete(name, region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    try:\n        url = conn.get_queue_url(QueueName=name)['QueueUrl']\n        conn.delete_queue(QueueUrl=url)\n    except botocore.exceptions.ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}\n    return {'result': True}",
    "docstring": "Delete an SQS queue.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_sqs.delete myqueue region=us-east-1"
  },
  {
    "code": "def sorted(collection):\n        if len(collection) < 1:\n            return collection\n        if isinstance(collection, dict):\n            return sorted(collection.items(), key=lambda x: x[0])\n        if isinstance(list(collection)[0], Operation):\n            key = lambda x: x.operation_id\n        elif isinstance(list(collection)[0], str):\n            key = lambda x: SchemaObjects.get(x).name\n        else:\n            raise TypeError(type(collection[0]))\n        return sorted(collection, key=key)",
    "docstring": "sorting dict by key,\n        schema-collection by schema-name\n        operations by id"
  },
  {
    "code": "def make_cube_slice(map_in, loge_bounds):\n    axis = map_in.geom.axes[0]\n    i0 = utils.val_to_edge(axis.edges, 10**loge_bounds[0])[0]\n    i1 = utils.val_to_edge(axis.edges, 10**loge_bounds[1])[0]\n    new_axis = map_in.geom.axes[0].slice(slice(i0, i1))\n    geom = map_in.geom.to_image()\n    geom = geom.to_cube([new_axis])\n    map_out = WcsNDMap(geom, map_in.data[slice(i0, i1), ...].copy())\n    return map_out",
    "docstring": "Extract a slice from a map cube object."
  },
  {
    "code": "def prettify_xml(xml_str):\n    parsed_xml = parseString(get_string(xml_str))\n    pretty_xml = '\\n'.join(\n        [line for line in parsed_xml.toprettyxml(indent=' ' * 2)\n         .split('\\n') if line.strip()])\n    if not pretty_xml.endswith('\\n'):\n        pretty_xml += '\\n'\n    return pretty_xml",
    "docstring": "returns prettified XML without blank lines\n\n    based on http://stackoverflow.com/questions/14479656/\n    :param xml_str: the XML to be prettified\n    :type xml_str: str\n    :return: the prettified XML\n    :rtype: str"
  },
  {
    "code": "def c_source(self):\n        relocs = Relocs(\n            ''.join(self.c_self_relocs()), *self.c_module_relocs()\n        )\n        return Source(\n            ''.join(self.c_typedefs()),\n            '' if self.opts.no_structs else self.c_struct(),\n            ''.join(self.c_hashes()),\n            ''.join(self.c_var_decls()),\n            relocs,\n            self.c_loadlib() + ''.join(self.c_getprocs())\n        )",
    "docstring": "Return strings."
  },
  {
    "code": "def resolve_request_path(requested_uri):\n    from settings import PATH_ALIASES\n    for key, val in PATH_ALIASES.items():\n        if re.match(key, requested_uri):\n            return re.sub(key, val, requested_uri)\n    return requested_uri",
    "docstring": "Check for any aliases and alter the path accordingly.\n\n    Returns resolved_uri"
  },
  {
    "code": "def as_index(keys, axis=semantics.axis_default, base=False, stable=True, lex_as_struct=False):\n    if isinstance(keys, Index):\n        if type(keys) is BaseIndex and base==False:\n            keys = keys.keys\n        else:\n            return keys\n    if isinstance(keys, tuple):\n        if lex_as_struct:\n            keys = as_struct_array(*keys)\n        else:\n            return LexIndex(keys, stable)\n    try:\n        keys = np.asarray(keys)\n    except:\n        raise TypeError('Given object does not form a valid set of keys')\n    if axis is None:\n        keys = keys.flatten()\n    if keys.ndim==1:\n        if base:\n            return BaseIndex(keys)\n        else:\n            return Index(keys, stable=stable)\n    else:\n        return ObjectIndex(keys, axis, stable=stable)",
    "docstring": "casting rules for a keys object to an index object\n\n    the preferred semantics is that keys is a sequence of key objects,\n    except when keys is an instance of tuple,\n    in which case the zipped elements of the tuple are the key objects\n\n    the axis keyword specifies the axis which enumerates the keys\n    if axis is None, the keys array is flattened\n    if axis is 0, the first axis enumerates the keys\n    which of these two is the default depends on whether backwards_compatible == True\n\n    if base==True, the most basic index possible is constructed.\n    this avoids an indirect sort; if it isnt required, this has better performance"
  },
  {
    "code": "def autocomplete(self):\n        params = self.set_lay_params()\n        logging.info(\"PARAMS=\"+str(params))\n        results = self.solr.search(**params)\n        logging.info(\"Docs found: {}\".format(results.hits))\n        return self._process_layperson_results(results)",
    "docstring": "Execute solr query for autocomplete"
  },
  {
    "code": "def multi_reciprocal_extra(xs, ys, noise=False):\n    ns = np.linspace(0.5, 6.0, num=56)\n    best = ['', np.inf]\n    fit_results = {}\n    weights = get_weights(xs, ys)\n    for n in ns:\n        popt = extrapolate_reciprocal(xs, ys, n, noise)\n        m = measure(reciprocal, xs, ys, popt, weights)\n        pcov = []\n        fit_results.update({n: {'measure': m, 'popt': popt, 'pcov': pcov}})\n    for n in fit_results:\n        if fit_results[n]['measure'] <= best[1]:\n            best = reciprocal, fit_results[n]['measure'], n\n    return fit_results[best[2]]['popt'], fit_results[best[2]]['pcov'], best",
    "docstring": "Calculates for a series of powers ns the parameters for which the last two points are at the curve.\n    With these parameters measure how well the other data points fit.\n    return the best fit."
  },
  {
    "code": "def init_distance_ttable(wordlist, distance_function):\n    n = len(wordlist)\n    t_table = numpy.zeros((n, n + 1))\n    for r, w in enumerate(wordlist):\n        for c, v in enumerate(wordlist):\n            if c < r:\n                t_table[r, c] = t_table[c, r]\n            else:\n                t_table[r, c] = distance_function(w, v) + 0.001\n    t_table[:, n] = numpy.mean(t_table[:, :-1], axis=1)\n    t_totals = numpy.sum(t_table, axis=0)\n    for i, t_total in enumerate(t_totals.tolist()):\n        t_table[:, i] /= t_total\n    return t_table",
    "docstring": "Initialize pair-wise rhyme strenghts according to the given word distance function"
  },
  {
    "code": "def force_log(self, logType, message, data=None, tback=None, stdout=True, file=True):\n        log = self._format_message(logType=logType, message=message, data=data, tback=tback)\n        if stdout:\n            self.__log_to_stdout(self.__logTypeFormat[logType][0] + log + self.__logTypeFormat[logType][1] + \"\\n\")\n            try:\n                self.__stdout.flush()\n            except:\n                pass\n            try:\n                os.fsync(self.__stdout.fileno())\n            except:\n                pass\n        if file:\n            self.__log_to_file(log)\n            self.__log_to_file(\"\\n\")\n            try:\n                self.__logFileStream.flush()\n            except:\n                pass\n            try:\n                os.fsync(self.__logFileStream.fileno())\n            except:\n                pass\n        self.__lastLogged[logType] = log\n        self.__lastLogged[-1]      = log",
    "docstring": "Force logging a message of a certain logtype whether logtype level is allowed or not.\n\n        :Parameters:\n           #. logType (string): A defined logging type.\n           #. message (string): Any message to log.\n           #. tback (None, str, list): Stack traceback to print and/or write to\n              log file. In general, this should be traceback.extract_stack\n           #. stdout (boolean): Whether to force logging to standard output.\n           #. file (boolean): Whether to force logging to file."
  },
  {
    "code": "def fetch_all_records(self):\n        r\n        api = self.doapi_manager\n        return map(self._record, api.paginate(self.record_url, 'domain_records'))",
    "docstring": "r\"\"\"\n        Returns a generator that yields all of the DNS records for the domain\n\n        :rtype: generator of `DomainRecord`\\ s\n        :raises DOAPIError: if the API endpoint replies with an error"
  },
  {
    "code": "def ccmodmsk_class_label_lookup(label):\n    clsmod = {'ism': admm_ccmod.ConvCnstrMODMaskDcpl_IterSM,\n              'cg': admm_ccmod.ConvCnstrMODMaskDcpl_CG,\n              'cns': admm_ccmod.ConvCnstrMODMaskDcpl_Consensus,\n              'fista': fista_ccmod.ConvCnstrMODMask}\n    if label in clsmod:\n        return clsmod[label]\n    else:\n        raise ValueError('Unknown ConvCnstrMODMask solver method %s' % label)",
    "docstring": "Get a ConvCnstrMODMask class from a label string."
  },
  {
    "code": "def add_property(self, prop, objects=()):\n        self._properties.add(prop)\n        self._objects |= objects\n        self._pairs.update((o, prop) for o in objects)",
    "docstring": "Add a property to the definition and add ``objects`` as related."
  },
  {
    "code": "def save(self, filename=None):\n        if self.__fname is None and filename is None:\n            raise ValueError('Config loaded from string, no filename specified')\n        conf = self.__config\n        cpa = dict_to_cp(conf)\n        with open(self.__fname if filename is None else filename, 'w') as f:\n            cpa.write(f)",
    "docstring": "Write config to file."
  },
  {
    "code": "def add(self, organization, domain=None, is_top_domain=False, overwrite=False):\n        if not organization:\n            return CMD_SUCCESS\n        if not domain:\n            try:\n                api.add_organization(self.db, organization)\n            except InvalidValueError as e:\n                raise RuntimeError(str(e))\n            except AlreadyExistsError as e:\n                msg = \"organization '%s' already exists in the registry\" % organization\n                self.error(msg)\n                return e.code\n        else:\n            try:\n                api.add_domain(self.db, organization, domain,\n                               is_top_domain=is_top_domain,\n                               overwrite=overwrite)\n            except InvalidValueError as e:\n                raise RuntimeError(str(e))\n            except AlreadyExistsError as e:\n                msg = \"domain '%s' already exists in the registry\" % domain\n                self.error(msg)\n                return e.code\n            except NotFoundError as e:\n                self.error(str(e))\n                return e.code\n        return CMD_SUCCESS",
    "docstring": "Add organizations and domains to the registry.\n\n        This method adds the given 'organization' or 'domain' to the registry,\n        but not both at the same time.\n\n        When 'organization' is the only parameter given, it will be added to\n        the registry. When 'domain' parameter is also given, the function will\n        assign it to 'organization'. In this case, 'organization' must exists in\n        the registry prior adding the domain.\n\n        A domain can only be assigned to one company. If the given domain is already\n        in the registry, the method will fail. Set 'overwrite' to 'True' to create\n        the new relationship. In this case, previous relationships will be removed.\n\n        The new domain can be also set as a top domain. That is useful to avoid\n        the insertion of sub-domains that belong to the same organization (i.e\n        eu.example.com, us.example.com). Take into account when 'overwrite' is set\n        it will update 'is_top_domain' flag too.\n\n        :param organization: name of the organization to add\n        :param domain: domain to add to the registry\n        :param is_top_domain: set the domain as a top domain\n        :param overwrite: force to reassign the domain to the given company"
  },
  {
    "code": "def get_nice_to_pegasus_fn(*args, **kwargs):\n    if args or kwargs:\n        warnings.warn(\"Deprecation warning: get_pegasus_to_nice_fn does not need / use parameters anymore\")\n    def c2p0(y, x, u, k): return (u, y+1 if u else x, 4+k if u else 4+k, x if u else y)\n    def c2p1(y, x, u, k): return (u, y+1 if u else x, k if u else 8+k, x if u else y)\n    def c2p2(y, x, u, k): return (u, y if u else x + 1, 8+k if u else k, x if u else y)\n    def n2p(t, y, x, u, k): return [c2p0, c2p1, c2p2][t](y, x, u, k)\n    return n2p",
    "docstring": "Returns a coordinate translation function from the 5-term \"nice\"\n    coordinates to the 4-term pegasus_index coordinates.\n\n    Details on the returned function, nice_to_pegasus(t, y, x, u, k)\n        Inputs are 5-tuples of ints, return is a 4-tuple of ints.  See\n        pegasus_graph for description of the pegasus_index and \"nice\"\n        coordinate systems.\n\n    Returns\n    -------\n    nice_to_pegasus_fn(pegasus_coordinates): a function\n        A function that accepts Pegasus coordinates and returns the corresponding \n        augmented chimera coordinates"
  },
  {
    "code": "def __thread_started(self):\n\t\tif self.__task is None:\n\t\t\traise RuntimeError('Unable to start thread without \"start\" method call')\n\t\tself.__task.start()\n\t\tself.__task.start_event().wait(self.__scheduled_task_startup_timeout__)",
    "docstring": "Start a scheduled task\n\n\t\t:return: None"
  },
  {
    "code": "def calcMhFromMz(mz, charge):\n    mh = (mz * charge) - (maspy.constants.atomicMassProton * (charge-1) )\n    return mh",
    "docstring": "Calculate the MH+ value from mz and charge.\n\n    :param mz: float, mass to charge ratio (Dalton / charge)\n    :param charge: int, charge state\n\n    :returns: mass to charge ratio of the mono protonated ion (charge = 1)"
  },
  {
    "code": "def using_config(_func=None):\n    def decorator(func):\n        @wraps(func)\n        def inner_dec(*args, **kwargs):\n            g = func.__globals__\n            var_name = 'config'\n            sentinel = object()\n            oldvalue = g.get(var_name, sentinel)\n            g[var_name] = apps.get_app_config('django_summernote').config\n            try:\n                res = func(*args, **kwargs)\n            finally:\n                if oldvalue is sentinel:\n                    del g[var_name]\n                else:\n                    g[var_name] = oldvalue\n            return res\n        return inner_dec\n    if _func is None:\n        return decorator\n    else:\n        return decorator(_func)",
    "docstring": "This allows a function to use Summernote configuration\n    as a global variable, temporarily."
  },
  {
    "code": "def generate(env):\n    add_all_to_env(env)\n    fcomp = env.Detect(compilers) or 'f90'\n    env['FORTRAN']  = fcomp\n    env['F90']      = fcomp\n    env['SHFORTRAN']  = '$FORTRAN'\n    env['SHF90']      = '$F90'\n    env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -KPIC')\n    env['SHF90FLAGS'] = SCons.Util.CLVar('$F90FLAGS -KPIC')",
    "docstring": "Add Builders and construction variables for sun f90 compiler to an\n    Environment."
  },
  {
    "code": "def get_uid(brain_or_object):\n    if is_portal(brain_or_object):\n        return '0'\n    if is_brain(brain_or_object) and base_hasattr(brain_or_object, \"UID\"):\n        return brain_or_object.UID\n    return get_object(brain_or_object).UID()",
    "docstring": "Get the Plone UID for this object\n\n    :param brain_or_object: A single catalog brain or content object\n    :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain\n    :returns: Plone UID\n    :rtype: string"
  },
  {
    "code": "def read(self):\n        if self.lines and self.chunksize:\n            obj = concat(self)\n        elif self.lines:\n            data = to_str(self.data)\n            obj = self._get_object_parser(\n                self._combine_lines(data.split('\\n'))\n            )\n        else:\n            obj = self._get_object_parser(self.data)\n        self.close()\n        return obj",
    "docstring": "Read the whole JSON input into a pandas object."
  },
  {
    "code": "def search_next(self, obj):\n        if 'meta' in obj and 'next' in obj['meta'] and obj['meta']['next'] != None:\n            uri = self.api_url % obj['meta']['next']\n            header, content = self._http_uri_request(uri)\n            resp = json.loads(content)\n            if not self._is_http_response_ok(header):\n                error = resp.get('error_message', 'Unknown Error')\n                raise HttpException(header.status, header.reason, error) \n            return resp\n        return {}",
    "docstring": "Takes the dictionary that is returned by 'search' or 'search_next' function and gets the next batch of results\n\n        Args: \n          obj: dictionary returned by the 'search' or 'search_next' function\n\n        Returns:\n          A dictionary with a data returned by the server\n\n        Raises:\n          HttpException with the error message from the server"
  },
  {
    "code": "def click(self, x: int, y: int) -> None:\n        self._execute('-s', self.device_sn, 'shell',\n                      'input', 'tap', str(x), str(y))",
    "docstring": "Simulate finger click."
  },
  {
    "code": "def get_intersection(self, division):\n        try:\n            return IntersectRelationship.objects.get(\n                from_division=self, to_division=division\n            ).intersection\n        except ObjectDoesNotExist:\n            raise Exception(\"No intersecting relationship with that division.\")",
    "docstring": "Get intersection percentage of intersecting divisions."
  },
  {
    "code": "def filter_data(df, filter_name, verbose=False):\n    \"Filter certain entries with given name.\"\n    df = df[df.stop_name.apply(\n        lambda cell: filter_name.encode('utf-8') in cell)]\n    if verbose:\n        msg = '- Filtered down to %d entries containing \"%s\".'\n        print(msg % (len(df), filter_name))\n    return df",
    "docstring": "Filter certain entries with given name."
  },
  {
    "code": "def random_output(self, max=100):\n        output = []\n        item1 = item2 = MarkovChain.START\n        for i in range(max-3):\n            item3 = self[(item1, item2)].roll()\n            if item3 is MarkovChain.END:\n                break\n            output.append(item3)\n            item1 = item2\n            item2 = item3\n        return output",
    "docstring": "Generate a list of elements from the markov chain.\n            The `max` value is in place in order to prevent excessive iteration."
  },
  {
    "code": "def _get_bounds(mapper, values):\n        array = np.array([mapper.get(x) for x in values])\n        return array[:, 0], array[:, 1]",
    "docstring": "Extract first and second value from tuples of mapped bins."
  },
  {
    "code": "def close(self):\n        self._outfile.write(struct.pack('>2h', 4, 0x0400))\n        if self._close:\n            self._outfile.close()",
    "docstring": "Finalize the GDSII stream library."
  },
  {
    "code": "async def set_topic(self, channel, topic):\n        if not self.is_channel(channel):\n            raise ValueError('Not a channel: {}'.format(channel))\n        elif not self.in_channel(channel):\n            raise NotInChannel(channel)\n        await self.rawmsg('TOPIC', channel, topic)",
    "docstring": "Set topic on channel.\n        Users should only rely on the topic actually being changed when receiving an on_topic_change callback."
  },
  {
    "code": "def replace_grist (features, new_grist):\n    assert is_iterable_typed(features, basestring) or isinstance(features, basestring)\n    assert isinstance(new_grist, basestring)\n    single_item = False\n    if isinstance(features, str):\n        features = [features]\n        single_item = True\n    result = []\n    for feature in features:\n        grist, split, value = feature.partition('>')\n        if not value and not split:\n            value = grist\n        result.append(new_grist + value)\n    if single_item:\n        return result[0]\n    return result",
    "docstring": "Replaces the grist of a string by a new one.\n        Returns the string with the new grist."
  },
  {
    "code": "def get_build_container_dir(self, arch):\n        dir_name = self.get_dir_name()\n        return join(self.ctx.build_dir, 'other_builds',\n                    dir_name, '{}__ndk_target_{}'.format(arch, self.ctx.ndk_api))",
    "docstring": "Given the arch name, returns the directory where it will be\n        built.\n\n        This returns a different directory depending on what\n        alternative or optional dependencies are being built."
  },
  {
    "code": "def spare_disk(self, disk_xml=None):\n        spare_disk = {}\n        disk_types = set()\n        for filer_disk in disk_xml:\n            disk_types.add(filer_disk.find('effective-disk-type').text)\n            if not filer_disk.find('raid-state').text == 'spare':\n                continue\n            disk_type = filer_disk.find('effective-disk-type').text\n            if disk_type in spare_disk:\n                spare_disk[disk_type] += 1\n            else:\n                spare_disk[disk_type] = 1\n        for disk_type in disk_types:\n            if disk_type in spare_disk:\n                self.push('spare_' + disk_type, 'disk', spare_disk[disk_type])\n            else:\n                self.push('spare_' + disk_type, 'disk', 0)",
    "docstring": "Number of spare disk per type.\n\n            For example: storage.ontap.filer201.disk.SATA"
  },
  {
    "code": "def save(self, fp, mode='wb'):\n        if hasattr(fp, 'write'):\n            self._record.write(fp)\n        else:\n            with open(fp, mode) as f:\n                self._record.write(f)",
    "docstring": "Save the PSD file.\n\n        :param fp: filename or file-like object.\n        :param mode: file open mode, default 'wb'."
  },
  {
    "code": "def sync_fork(gh_token, github_repo_id, repo, push=True):\n    if not gh_token:\n        _LOGGER.warning('Skipping the upstream repo sync, no token')\n        return\n    _LOGGER.info('Check if repo has to be sync with upstream')\n    github_con = Github(gh_token)\n    github_repo = github_con.get_repo(github_repo_id)\n    if not github_repo.parent:\n        _LOGGER.warning('This repo has no upstream')\n        return\n    upstream_url = 'https://github.com/{}.git'.format(github_repo.parent.full_name)\n    upstream = repo.create_remote('upstream', url=upstream_url)\n    upstream.fetch()\n    active_branch_name = repo.active_branch.name\n    if not active_branch_name in repo.remotes.upstream.refs:\n        _LOGGER.info('Upstream has no branch %s to merge from', active_branch_name)\n        return\n    else:\n        _LOGGER.info('Merge from upstream')\n    msg = repo.git.rebase('upstream/{}'.format(repo.active_branch.name))\n    _LOGGER.debug(msg)\n    if push:\n        msg = repo.git.push()\n        _LOGGER.debug(msg)",
    "docstring": "Sync the current branch in this fork against the direct parent on Github"
  },
  {
    "code": "def select_entry(self, *arguments):\n        matches = self.smart_search(*arguments)\n        if len(matches) > 1:\n            logger.info(\"More than one match, prompting for choice ..\")\n            labels = [entry.name for entry in matches]\n            return matches[labels.index(prompt_for_choice(labels))]\n        else:\n            logger.info(\"Matched one entry: %s\", matches[0].name)\n            return matches[0]",
    "docstring": "Select a password from the available choices.\n\n        :param arguments: Refer to :func:`smart_search()`.\n        :returns: The name of a password (a string) or :data:`None`\n                  (when no password matched the given `arguments`)."
  },
  {
    "code": "def shutdown_executors(wait=True):\n    return {k: shutdown_executor(k, wait) for k in list(_EXECUTORS.keys())}",
    "docstring": "Clean-up the resources of all initialized executors.\n\n    :param wait:\n        If True then shutdown will not return until all running futures have\n        finished executing and the resources used by the executors have been\n        reclaimed.\n    :type wait: bool\n\n    :return:\n        Shutdown pool executor.\n    :rtype: dict[str,dict]"
  },
  {
    "code": "def intersect(self, r):\n        if not len(r) == 4:\n            raise ValueError(\"bad sequ. length\")\n        self.x0, self.y0, self.x1, self.y1 = TOOLS._intersect_rect(self, r)\n        return self",
    "docstring": "Restrict self to common area with rectangle r."
  },
  {
    "code": "def names(self):\n        ret = set()\n        for arr in self:\n            if isinstance(arr, InteractiveList):\n                ret.update(arr.names)\n            else:\n                ret.add(arr.name)\n        return ret",
    "docstring": "Set of the variable in this list"
  },
  {
    "code": "def render(self, name, value, attrs=None, **kwargs):\n        output = super(Select2Mixin, self).render(\n            name, value, attrs=attrs, **kwargs)\n        id_ = attrs['id']\n        output += self.render_js_code(\n            id_, name, value, attrs=attrs, **kwargs)\n        return mark_safe(output)",
    "docstring": "Extend base class's `render` method by appending\n        javascript inline text to html output."
  },
  {
    "code": "def make_sentence(list_words):\n        lw_len = len(list_words)\n        if lw_len > 6:\n            list_words.insert(lw_len // 2 + random.choice(range(-2, 2)), ',')\n        sentence = ' '.join(list_words).replace(' ,', ',')\n        return sentence.capitalize() + '.'",
    "docstring": "Return a sentence from list of words.\n\n        :param list list_words: list of words\n        :returns: sentence\n        :rtype: str"
  },
  {
    "code": "def get_environment_vars(filename):\n    if sys.platform == \"linux\" or sys.platform == \"linux2\":\n        return {\n            'LD_PRELOAD': path.join(LIBFAKETIME_DIR, \"libfaketime.so.1\"),\n            'FAKETIME_SKIP_CMDS': 'nodejs',\n            'FAKETIME_TIMESTAMP_FILE': filename,\n        }\n    elif sys.platform == \"darwin\":\n        return {\n            'DYLD_INSERT_LIBRARIES': path.join(LIBFAKETIME_DIR, \"libfaketime.1.dylib\"),\n            'DYLD_FORCE_FLAT_NAMESPACE': '1',\n            'FAKETIME_TIMESTAMP_FILE': filename,\n        }\n    else:\n        raise RuntimeError(\"libfaketime does not support '{}' platform\".format(sys.platform))",
    "docstring": "Return a dict of environment variables required to run a service under faketime."
  },
  {
    "code": "def get_default_name(self):\n        long_names = [name for name in self.name if name.startswith(\"--\")]\n        short_names = [name for name in self.name if not name.startswith(\"--\")]\n        if long_names:\n            return to_snake_case(long_names[0].lstrip(\"-\"))\n        return to_snake_case(short_names[0].lstrip(\"-\"))",
    "docstring": "Return the default generated name to store value on the parser for this option.\n\n        eg. An option *['-s', '--use-ssl']* will generate the *use_ssl* name\n\n        Returns:\n            str: the default name of the option"
  },
  {
    "code": "def split_number_and_unit(s):\n    if not s:\n        raise ValueError('empty value')\n    s = s.strip()\n    pos = len(s)\n    while pos and not s[pos-1].isdigit():\n        pos -= 1\n    number = int(s[:pos])\n    unit = s[pos:].strip()\n    return (number, unit)",
    "docstring": "Parse a string that consists of a integer number and an optional unit.\n    @param s a non-empty string that starts with an int and is followed by some letters\n    @return a triple of the number (as int) and the unit"
  },
  {
    "code": "def suggestions(self, word):\n    suggestions = set(self._misspelling_dict.get(word, [])).union(\n        set(self._misspelling_dict.get(word.lower(), [])))\n    return sorted([same_case(source=word, destination=w)\n                   for w in suggestions])",
    "docstring": "Returns a list of suggestions for a misspelled word.\n\n    Args:\n      word: The word to check.\n\n    Returns:\n      List of zero or more suggested replacements for word."
  },
  {
    "code": "def stream_text(text, chunk_size=default_chunk_size):\n    if isgenerator(text):\n        def binary_stream():\n            for item in text:\n                if six.PY2 and isinstance(text, six.binary_type):\n                    yield text\n                else:\n                    yield text.encode(\"utf-8\")\n        data = binary_stream()\n    elif six.PY2 and isinstance(text, six.binary_type):\n        data = text\n    else:\n        data = text.encode(\"utf-8\")\n    return stream_bytes(data, chunk_size)",
    "docstring": "Gets a buffered generator for streaming text.\n\n    Returns a buffered generator which encodes a string as\n    :mimetype:`multipart/form-data` with the corresponding headers.\n\n    Parameters\n    ----------\n    text : str\n        The data bytes to stream\n    chunk_size : int\n        The maximum size of each stream chunk\n\n    Returns\n    -------\n        (generator, dict)"
  },
  {
    "code": "def heatmap_seaborn(dfr, outfilename=None, title=None, params=None):\n    maxfigsize = 120\n    calcfigsize = dfr.shape[0] * 1.1\n    figsize = min(max(8, calcfigsize), maxfigsize)\n    if figsize == maxfigsize:\n        scale = maxfigsize / calcfigsize\n        sns.set_context(\"notebook\", font_scale=scale)\n    if params.classes is None:\n        col_cb = None\n    else:\n        col_cb = get_seaborn_colorbar(dfr, params.classes)\n    params.labels = get_safe_seaborn_labels(dfr, params.labels)\n    params.colorbar = col_cb\n    params.figsize = figsize\n    params.linewidths = 0.25\n    fig = get_seaborn_clustermap(dfr, params, title=title)\n    if outfilename:\n        fig.savefig(outfilename)\n    return fig",
    "docstring": "Returns seaborn heatmap with cluster dendrograms.\n\n    - dfr - pandas DataFrame with relevant data\n    - outfilename - path to output file (indicates output format)"
  },
  {
    "code": "def length2mesh(length, lattice, rotations=None):\n    rec_lattice = np.linalg.inv(lattice)\n    rec_lat_lengths = np.sqrt(np.diagonal(np.dot(rec_lattice.T, rec_lattice)))\n    mesh_numbers = np.rint(rec_lat_lengths * length).astype(int)\n    if rotations is not None:\n        reclat_equiv = get_lattice_vector_equivalence(\n            [r.T for r in np.array(rotations)])\n        m = mesh_numbers\n        mesh_equiv = [m[1] == m[2], m[2] == m[0], m[0] == m[1]]\n        for i, pair in enumerate(([1, 2], [2, 0], [0, 1])):\n            if reclat_equiv[i] and not mesh_equiv:\n                m[pair] = max(m[pair])\n    return np.maximum(mesh_numbers, [1, 1, 1])",
    "docstring": "Convert length to mesh for q-point sampling\n\n    This conversion for each reciprocal axis follows VASP convention by\n        N = max(1, int(l * |a|^* + 0.5))\n    'int' means rounding down, not rounding to nearest integer.\n\n    Parameters\n    ----------\n    length : float\n        Length having the unit of direct space length.\n    lattice : array_like\n        Basis vectors of primitive cell in row vectors.\n        dtype='double', shape=(3, 3)\n    rotations: array_like, optional\n        Rotation matrices in real space. When given, mesh numbers that are\n        symmetrically reasonable are returned. Default is None.\n        dtype='intc', shape=(rotations, 3, 3)\n\n    Returns\n    -------\n    array_like\n        dtype=int, shape=(3,)"
  },
  {
    "code": "def run_export_db(filename=None):\n    if not filename:\n        filename = settings.DB_DUMP_FILENAME\n    with cd(settings.FAB_SETTING('SERVER_PROJECT_ROOT')):\n        run_workon('fab export_db:remote=True,filename={}'.format(filename))",
    "docstring": "Exports the database on the server.\n\n    Usage::\n\n        fab prod run_export_db\n        fab prod run_export_db:filename=foobar.dump"
  },
  {
    "code": "def class_name_for_data_type(data_type, ns=None):\n    assert is_user_defined_type(data_type) or is_alias(data_type), \\\n        'Expected composite type, got %r' % type(data_type)\n    name = fmt_class(data_type.name)\n    if ns:\n        return prefix_with_ns_if_necessary(name, data_type.namespace, ns)\n    return name",
    "docstring": "Returns the name of the Python class that maps to a user-defined type.\n    The name is identical to the name in the spec.\n\n    If ``ns`` is set to a Namespace and the namespace of `data_type` does\n    not match, then a namespace prefix is added to the returned name.\n    For example, ``foreign_ns.TypeName``."
  },
  {
    "code": "def _validate_applications(self, apps):\n\t\tfor application_id, application_config in apps.items():\n\t\t\tself._validate_config(application_id, application_config)\n\t\t\tapplication_config[\"APPLICATION_ID\"] = application_id",
    "docstring": "Validate the application collection"
  },
  {
    "code": "def showMonitors(cls):\n        Debug.info(\"*** monitor configuration [ {} Screen(s)] ***\".format(cls.getNumberScreens()))\n        Debug.info(\"*** Primary is Screen {}\".format(cls.primaryScreen))\n        for index, screen in enumerate(PlatformManager.getScreenDetails()):\n            Debug.info(\"Screen {}: ({}, {}, {}, {})\".format(index, *screen[\"rect\"]))\n        Debug.info(\"*** end monitor configuration ***\")",
    "docstring": "Prints debug information about currently detected screens"
  },
  {
    "code": "def get_street(self, **kwargs):\n        params = {\n            'description': kwargs.get('street_name'),\n            'streetNumber': kwargs.get('street_number'),\n            'Radius': kwargs.get('radius'),\n            'Stops': kwargs.get('stops'),\n            'cultureInfo': util.language_code(kwargs.get('lang'))\n        }\n        result = self.make_request('geo', 'get_street', **params)\n        if not util.check_result(result, 'site'):\n            return False, 'UNKNOWN ERROR'\n        values = util.response_list(result, 'site')\n        return True, [emtype.Site(**a) for a in values]",
    "docstring": "Obtain a list of nodes related to a location within a given radius.\n\n        Not sure of its use, but...\n\n        Args:\n            street_name (str): Name of the street to search.\n            street_number (int): Street number to search.\n            radius (int): Radius (in meters) of the search.\n            stops (int): Number of the stop to search.\n            lang (str): Language code (*es* or *en*).\n\n        Returns:\n            Status boolean and parsed response (list[Site]), or message string\n            in case of error."
  },
  {
    "code": "def restore_collection(backup):\n    for k, v in six.iteritems(backup):\n        del tf.get_collection_ref(k)[:]\n        tf.get_collection_ref(k).extend(v)",
    "docstring": "Restore from a collection backup.\n\n    Args:\n        backup (dict):"
  },
  {
    "code": "def _build_command_ids(issued_commands):\n    if isinstance(issued_commands, IssuedCommand):\n        entry = issued_commands._proto.commandQueueEntry\n        return [entry.cmdId]\n    else:\n        return [issued_command._proto.commandQueueEntry.cmdId\n                for issued_command in issued_commands]",
    "docstring": "Builds a list of CommandId."
  },
  {
    "code": "def _insert_text_buf(self, line, idx):\n        self._bytes_012[idx] = 0\n        self._bytes_345[idx] = 0\n        I = np.array([ord(c) - 32 for c in line[:self._n_cols]])\n        I = np.clip(I, 0, len(__font_6x8__)-1)\n        if len(I) > 0:\n            b = __font_6x8__[I]\n            self._bytes_012[idx, :len(I)] = b[:, :3]\n            self._bytes_345[idx, :len(I)] = b[:, 3:]",
    "docstring": "Insert text into bytes buffers"
  },
  {
    "code": "def get_accent_char(char):\n    index = utils.VOWELS.find(char.lower())\n    if (index != -1):\n        return 5 - index % 6\n    else:\n        return Accent.NONE",
    "docstring": "Get the accent of an single char, if any."
  },
  {
    "code": "def _verify_student_input(self, student_input, locked):\n        guesses = [student_input]\n        try:\n            guesses.append(repr(ast.literal_eval(student_input)))\n        except Exception:\n            pass\n        if student_input.title() in self.SPECIAL_INPUTS:\n            guesses.append(student_input.title())\n        for guess in guesses:\n            if self._verify(guess, locked):\n                return guess",
    "docstring": "If the student's answer is correct, returns the normalized answer.\n        Otherwise, returns None."
  },
  {
    "code": "def item_at_line(root_item, line):\r\n    previous_item = root_item\r\n    item = root_item\r\n    for item in get_item_children(root_item):\r\n        if item.line > line:\r\n            return previous_item\r\n        previous_item = item\r\n    else:\r\n        return item",
    "docstring": "Find and return the item of the outline explorer under which is located\r\n    the specified 'line' of the editor."
  },
  {
    "code": "def update(self, validate=False):\n        rs = self.connection.get_all_snapshots([self.id])\n        if len(rs) > 0:\n            self._update(rs[0])\n        elif validate:\n            raise ValueError('%s is not a valid Snapshot ID' % self.id)\n        return self.progress",
    "docstring": "Update the data associated with this snapshot by querying EC2.\n\n        :type validate: bool\n        :param validate: By default, if EC2 returns no data about the\n                         snapshot the update method returns quietly.  If\n                         the validate param is True, however, it will\n                         raise a ValueError exception if no data is\n                         returned from EC2."
  },
  {
    "code": "def get_full_description(self, s, base=None):\n        summary = self.get_summary(s)\n        extended_summary = self.get_extended_summary(s)\n        ret = (summary + '\\n\\n' + extended_summary).strip()\n        if base is not None:\n            self.params[base + '.full_desc'] = ret\n        return ret",
    "docstring": "Get the full description from a docstring\n\n        This here and the line above is the full description (i.e. the\n        combination of the :meth:`get_summary` and the\n        :meth:`get_extended_summary`) output\n\n        Parameters\n        ----------\n        s: str\n            The docstring to use\n        base: str or None\n            A key under which the description shall be stored in the\n            :attr:`params` attribute. If not None, the summary will be stored\n            in ``base + '.full_desc'``. Otherwise, it will not be stored\n            at all\n\n        Returns\n        -------\n        str\n            The extracted full description"
  },
  {
    "code": "def get(self, key, default=None):\n        try:\n            index = self.__keys.index(str(key))\n        except ValueError:\n            return default\n        if 0 <= index < len(self):\n            return super(Record, self).__getitem__(index)\n        else:\n            return default",
    "docstring": "Obtain a value from the record by key, returning a default\n        value if the key does not exist.\n\n        :param key:\n        :param default:\n        :return:"
  },
  {
    "code": "def do_print(filename):\n    with open(filename) as cmake_file:\n        body = ast.parse(cmake_file.read())\n        word_print = _print_details(lambda n: \"{0} {1}\".format(n.type,\n                                                               n.contents))\n        ast_visitor.recurse(body,\n                            while_stmnt=_print_details(),\n                            foreach=_print_details(),\n                            function_def=_print_details(),\n                            macro_def=_print_details(),\n                            if_block=_print_details(),\n                            if_stmnt=_print_details(),\n                            elseif_stmnt=_print_details(),\n                            else_stmnt=_print_details(),\n                            function_call=_print_details(lambda n: n.name),\n                            word=word_print)",
    "docstring": "Print the AST of filename."
  },
  {
    "code": "def _parse_relationship(self):\n        rs_dict = self.data.get('relationships', {})\n        for rs_name in self.KNOWN_RELATIONSHIPS:\n            if rs_name in rs_dict:\n                setattr(\n                    self, rs_name, Relationship(rs_name, rs_dict.get(rs_name)))\n            else:\n                setattr(self, rs_name, NoneRelationshipSingleton)",
    "docstring": "Nodes have Relationships, and similarly to properties,\n        we set it as an attribute on the Organization so we can make calls like\n            company.current_team\n            person.degrees"
  },
  {
    "code": "def retrieve(self, id) :\n        _, _, contact = self.http_client.get(\"/contacts/{id}\".format(id=id))\n        return contact",
    "docstring": "Retrieve a single contact\n\n        Returns a single contact available to the user, according to the unique contact ID provided\n        If the specified contact does not exist, the request will return an error\n\n        :calls: ``get /contacts/{id}``\n        :param int id: Unique identifier of a Contact.\n        :return: Dictionary that support attriubte-style access and represent Contact resource.\n        :rtype: dict"
  },
  {
    "code": "def get_compositions_by_search(self, composition_query, composition_search):\n        if not self._can('search'):\n            raise PermissionDenied()\n        return self._provider_session.get_compositions_by_search(composition_query, composition_search)",
    "docstring": "Pass through to provider CompositionSearchSession.get_compositions_by_search"
  },
  {
    "code": "def PopAttributeContainer(self):\n    try:\n      serialized_data = self._list.pop(0)\n      self.data_size -= len(serialized_data)\n      return serialized_data\n    except IndexError:\n      return None",
    "docstring": "Pops a serialized attribute container from the list.\n\n    Returns:\n      bytes: serialized attribute container data."
  },
  {
    "code": "def to_notional(instruments, prices, multipliers, desired_ccy=None,\n                instr_fx=None, fx_rates=None):\n    notionals = _instr_conv(instruments, prices, multipliers, True,\n                            desired_ccy, instr_fx, fx_rates)\n    return notionals",
    "docstring": "Convert number of contracts of tradeable instruments to notional value of\n    tradeable instruments in a desired currency.\n\n    Parameters\n    ----------\n    instruments: pandas.Series\n        Series of instrument holdings. Index is instrument name and values are\n        number of contracts.\n    prices: pandas.Series\n        Series of instrument prices. Index is instrument name and values are\n        instrument prices. prices.index should be a superset of\n        instruments.index otherwise NaN returned for instruments without prices\n    multipliers: pandas.Series\n        Series of instrument multipliers. Index is instrument name and\n        values are the multiplier associated with the contract.\n        multipliers.index should be a superset of instruments.index\n    desired_ccy: str\n        Three letter string representing desired currency to convert notional\n        values to, e.g. 'USD'. If None is given currency conversion is ignored.\n    instr_fx: pandas.Series\n        Series of instrument fx denominations. Index is instrument name and\n        values are three letter strings representing the currency the\n        instrument is denominated in. instr_fx.index should match prices.index\n    fx_rates: pandas.Series\n        Series of fx rates used for conversion to desired_ccy. Index is strings\n        representing the FX pair, e.g. 'AUDUSD' or 'USDCAD'. Values are the\n        corresponding exchange rates.\n\n    Returns\n    -------\n    pandas.Series of notional amounts of instruments with Index of instruments\n    names\n\n    Example\n    -------\n    >>> import pandas as pd\n    >>> import mapping.util as util\n    >>> current_contracts = pd.Series([-1, 1], index=['CLX16', 'CLZ16'])\n    >>> prices = pd.Series([50.32, 50.41], index=['CLX16', 'CLZ16'])\n    >>> multipliers = pd.Series([100, 100], index=['CLX16', 'CLZ16'])\n    >>> ntln = util.to_notional(current_contracts, prices, multipliers)"
  },
  {
    "code": "def get_occurrence(event_id, occurrence_id=None, year=None, month=None,\n                   day=None, hour=None, minute=None, second=None,\n                   tzinfo=None):\n    if(occurrence_id):\n        occurrence = get_object_or_404(Occurrence, id=occurrence_id)\n        event = occurrence.event\n    elif None not in (year, month, day, hour, minute, second):\n        event = get_object_or_404(Event, id=event_id)\n        date = timezone.make_aware(datetime.datetime(int(year), int(month),\n                                   int(day), int(hour), int(minute),\n                                   int(second)), tzinfo)\n        occurrence = event.get_occurrence(date)\n        if occurrence is None:\n            raise Http404\n    else:\n        raise Http404\n    return event, occurrence",
    "docstring": "Because occurrences don't have to be persisted, there must be two ways to\n    retrieve them. both need an event, but if its persisted the occurrence can\n    be retrieved with an id. If it is not persisted it takes a date to\n    retrieve it.  This function returns an event and occurrence regardless of\n    which method is used."
  },
  {
    "code": "def create_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED,\n                           options=None, ciphers=None):\n    context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)\n    if options is None:\n        options = 0\n        options |= OP_NO_SSLv2\n        options |= OP_NO_SSLv3\n        options |= OP_NO_COMPRESSION\n    context.options |= options\n    if getattr(context, 'supports_set_ciphers', True):\n        context.set_ciphers(ciphers or _DEFAULT_CIPHERS)\n    context.verify_mode = cert_reqs\n    if getattr(context, 'check_hostname', None) is not None:\n        context.check_hostname = False\n    return context",
    "docstring": "All arguments have the same meaning as ``ssl_wrap_socket``.\n\n    By default, this function does a lot of the same work that\n    ``ssl.create_default_context`` does on Python 3.4+. It:\n\n    - Disables SSLv2, SSLv3, and compression\n    - Sets a restricted set of server ciphers\n\n    If you wish to enable SSLv3, you can do::\n\n        from urllib3.util import ssl_\n        context = ssl_.create_urllib3_context()\n        context.options &= ~ssl_.OP_NO_SSLv3\n\n    You can do the same to enable compression (substituting ``COMPRESSION``\n    for ``SSLv3`` in the last line above).\n\n    :param ssl_version:\n        The desired protocol version to use. This will default to\n        PROTOCOL_SSLv23 which will negotiate the highest protocol that both\n        the server and your installation of OpenSSL support.\n    :param cert_reqs:\n        Whether to require the certificate verification. This defaults to\n        ``ssl.CERT_REQUIRED``.\n    :param options:\n        Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,\n        ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.\n    :param ciphers:\n        Which cipher suites to allow the server to select.\n    :returns:\n        Constructed SSLContext object with specified options\n    :rtype: SSLContext"
  },
  {
    "code": "def get_function_from_bot_intent_trigger(self, event):\n        intent = event.get('currentIntent')\n        if intent:\n            intent = intent.get('name')\n            if intent:\n                return self.settings.AWS_BOT_EVENT_MAPPING.get(\n                    \"{}:{}\".format(intent, event.get('invocationSource'))\n                )",
    "docstring": "For the given event build ARN and return the configured function"
  },
  {
    "code": "def _send_command(self, cmd_class, command, payload, timeout=3.0):\n        if len(payload) > 60:\n            return ValueError(\"Attempting to send a BGAPI packet with length > 60 is not allowed\", actual_length=len(payload), command=command, command_class=cmd_class)\n        header = bytearray(4)\n        header[0] = 0\n        header[1] = len(payload)\n        header[2] = cmd_class\n        header[3] = command\n        packet = header + bytearray(payload)\n        self._stream.write(bytes(packet))\n        response = self._receive_packet(timeout)\n        return response",
    "docstring": "Send a BGAPI packet to the dongle and return the response"
  },
  {
    "code": "def perform(self):\n        for request in self._cfg[Integrator._CFG_KEY_REQUESTS]:\n            request_type = self._cfg[Integrator._CFG_KEY_REQUESTS][request][Integrator._CFG_KEY_REQUEST_TYPE]\n            request_cfg_file = self._cfg[Integrator._CFG_KEY_REQUESTS][request][Integrator._CFG_KEY_REQUEST_CFG_FILE]\n            self._logger.debug('{}'.format(request_cfg_file))\n            self._process_request(request, request_type, request_cfg_file)",
    "docstring": "Performs bulk operation"
  },
  {
    "code": "def one_point_crossover(parents):\n    crossover_point = random.randint(1, len(parents[0]) - 1)\n    return (_one_parent_crossover(parents[0], parents[1], crossover_point),\n            _one_parent_crossover(parents[1], parents[0], crossover_point))",
    "docstring": "Perform one point crossover on two parent chromosomes.\n\n    Select a random position in the chromosome.\n    Take genes to the left from one parent and the rest from the other parent.\n    Ex. p1 = xxxxx, p2 = yyyyy, position = 2 (starting at 0), child = xxyyy"
  },
  {
    "code": "def await_paused(self, timeout=None):\n    deadline = time.time() + timeout if timeout else None\n    with self._lock:\n      while self._state != self._PAUSED:\n        if self._state != self._PAUSING:\n          raise AssertionError('Cannot wait for {} to reach `{}` while it is in `{}`.'.format(self, self._PAUSED, self._state))\n        timeout = deadline - time.time() if deadline else None\n        if timeout and timeout <= 0:\n          return False\n        self._condition.wait(timeout=timeout)\n      return True",
    "docstring": "Blocks until the service is in the Paused state, then returns True.\n\n    If a timeout is specified, the method may return False to indicate a timeout: with no timeout\n    it will always (eventually) return True.\n\n    Raises if the service is not currently in the Pausing state."
  },
  {
    "code": "def _get_url_params(self, shorten=True):\n        cable = True if self.category == 'cable' else False\n        url_date = convert_month(self.date, shorten=shorten, cable=cable)\n        return [\n            BASE_URL,\n            self.weekday.lower(),\n            self.category + '-ratings',\n            url_date.replace(' ', '-')\n        ]",
    "docstring": "Returns a list of each parameter to be used for the url format."
  },
  {
    "code": "def hyperparameters(self):\n        hp_dict = dict(force_dense='True')\n        hp_dict.update(super(KMeans, self).hyperparameters())\n        return hp_dict",
    "docstring": "Return the SageMaker hyperparameters for training this KMeans Estimator"
  },
  {
    "code": "def lookup_family(hostname):\n    fallback = socket.AF_INET\n    try:\n        hostnames = socket.getaddrinfo(\n            hostname or None, None, socket.AF_UNSPEC, socket.SOCK_STREAM\n        )\n        if not hostnames:\n            return fallback\n        h = hostnames[0]\n        return h[0]\n    except socket.gaierror:\n        return fallback",
    "docstring": "Lookup a hostname and determine its address family. The first address returned\n    will be AF_INET6 if the system is IPv6-enabled, and AF_INET otherwise."
  },
  {
    "code": "def verify_file(fp, password):\n        'Returns whether a scrypt encrypted file is valid.'\n        sf = ScryptFile(fp = fp, password = password)\n        for line in sf: pass\n        sf.close()\n        return sf.valid",
    "docstring": "Returns whether a scrypt encrypted file is valid."
  },
  {
    "code": "def on_epoch_end(self, last_metrics, **kwargs):\n        \"Set the final result in `last_metrics`.\"\n        return add_metrics(last_metrics, self.val/self.count)",
    "docstring": "Set the final result in `last_metrics`."
  },
  {
    "code": "def to_list(self, n=None):\n        if n is None:\n            self.cache()\n            return self._base_sequence\n        else:\n            return self.cache().take(n).list()",
    "docstring": "Converts sequence to list of elements.\n\n        >>> type(seq([]).to_list())\n        list\n\n        >>> type(seq([]))\n        functional.pipeline.Sequence\n\n        >>> seq([1, 2, 3]).to_list()\n        [1, 2, 3]\n\n        :param n: Take n elements of sequence if not None\n        :return: list of elements in sequence"
  },
  {
    "code": "def run(self):\n        for msg in self.messages:\n            col = getattr(msg, 'col', 0)\n            yield msg.lineno, col, (msg.tpl % msg.message_args), msg.__class__",
    "docstring": "Yield the error messages."
  },
  {
    "code": "def create_rectangular_prism(origin, size):\n    from lace.topology import quads_to_tris\n    lower_base_plane = np.array([\n        origin,\n        origin + np.array([size[0], 0, 0]),\n        origin + np.array([size[0], 0, size[2]]),\n        origin + np.array([0, 0, size[2]]),\n    ])\n    upper_base_plane = lower_base_plane + np.array([0, size[1], 0])\n    vertices = np.vstack([lower_base_plane, upper_base_plane])\n    faces = quads_to_tris(np.array([\n        [0, 1, 2, 3],\n        [7, 6, 5, 4],\n        [4, 5, 1, 0],\n        [5, 6, 2, 1],\n        [6, 7, 3, 2],\n        [3, 7, 4, 0],\n    ]))\n    return Mesh(v=vertices, f=faces)",
    "docstring": "Return a Mesh which is an axis-aligned rectangular prism. One vertex is\n    `origin`; the diametrically opposite vertex is `origin + size`.\n\n    size: 3x1 array."
  },
  {
    "code": "def simple_preprocess(doc, deacc=False, min_len=2, max_len=15):\n    tokens = [\n        token for token in tokenize(doc, lower=True, deacc=deacc, errors='ignore')\n        if min_len <= len(token) <= max_len and not token.startswith('_')\n    ]\n    return tokens",
    "docstring": "Convert a document into a list of tokens.\n\n    This lowercases, tokenizes, de-accents (optional). -- the output are final\n    tokens = unicode strings, that won't be processed any further."
  },
  {
    "code": "def unpack_nested_exception(error):\n    i = 0\n    while True:\n        if error.args[i:]:\n            if isinstance(error.args[i], Exception):\n                error = error.args[i]\n                i = 0\n            else:\n                i += 1\n        else:\n            break\n    return error",
    "docstring": "If exception are stacked, return the first one\n\n        :param error: A python exception with possible exception embeded within\n        :return: A python exception with no exception embeded within"
  },
  {
    "code": "def disconnect(self):\n        self._connected = False\n        if self._transport is not None:\n            try:\n                self._transport.disconnect()\n            except Exception:\n                self.logger.error(\n                    \"Failed to disconnect from %s\", self._host, exc_info=True)\n                raise\n            finally:\n                self._transport = None",
    "docstring": "Disconnect from the current host, but do not update the closed state.\n        After the transport is disconnected, the closed state will be True if\n        this is called after a protocol shutdown, or False if the disconnect\n        was in error.\n\n        TODO: do we really need closed vs. connected states? this only adds\n        complication and the whole reconnect process has been scrapped anyway."
  },
  {
    "code": "def calls(self):\n        return WebhookWebhooksCallProxy(self._client, self.sys['space'].id, self.sys['id'])",
    "docstring": "Provides access to call overview for the given webhook.\n\n        API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/webhook-calls\n\n        :return: :class:`WebhookWebhooksCallProxy <contentful_management.webhook_webhooks_call_proxy.WebhookWebhooksCallProxy>` object.\n        :rtype: contentful.webhook_webhooks_call_proxy.WebhookWebhooksCallProxy\n\n        Usage:\n\n            >>> webhook_webhooks_call_proxy = webhook.calls()\n            <WebhookWebhooksCallProxy space_id=\"cfexampleapi\" webhook_id=\"my_webhook\">"
  },
  {
    "code": "def check_user_token(self, request, user):\n        if not app_settings.REST_USER_TOKEN_ENABLED:\n            return False\n        try:\n            token = Token.objects.get(\n                user=user,\n                key=request.data.get('password')\n            )\n        except Token.DoesNotExist:\n            token = None\n        else:\n            if app_settings.DISPOSABLE_USER_TOKEN:\n                token.delete()\n        finally:\n            return token is not None",
    "docstring": "if user has no password set and has at least 1 social account\n        this is probably a social login, the password field is the\n        user's personal auth token"
  },
  {
    "code": "def hash_of_signed_transaction(txn_obj):\n    (chain_id, _v) = extract_chain_id(txn_obj.v)\n    unsigned_parts = strip_signature(txn_obj)\n    if chain_id is None:\n        signable_transaction = UnsignedTransaction(*unsigned_parts)\n    else:\n        extended_transaction = unsigned_parts + [chain_id, 0, 0]\n        signable_transaction = ChainAwareUnsignedTransaction(*extended_transaction)\n    return signable_transaction.hash()",
    "docstring": "Regenerate the hash of the signed transaction object.\n\n    1. Infer the chain ID from the signature\n    2. Strip out signature from transaction\n    3. Annotate the transaction with that ID, if available\n    4. Take the hash of the serialized, unsigned, chain-aware transaction\n\n    Chain ID inference and annotation is according to EIP-155\n    See details at https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md\n\n    :return: the hash of the provided transaction, to be signed"
  },
  {
    "code": "def get_variable_dtype(\n    master_dtype=tf.bfloat16,\n    slice_dtype=tf.float32,\n    activation_dtype=tf.float32):\n  return mtf.VariableDType(\n      master_dtype=tf.as_dtype(master_dtype),\n      slice_dtype=tf.as_dtype(slice_dtype),\n      activation_dtype=tf.as_dtype(activation_dtype))",
    "docstring": "Datatypes to use for the run.\n\n  Args:\n    master_dtype: string, datatype for checkpoints\n      keep this the same between training and eval/inference\n    slice_dtype: string, datatype for variables in memory\n      must be tf.float32 for training\n    activation_dtype: string, datatype for activations\n      less memory usage if tf.bfloat16 but possible numerical issues\n  Returns:\n    a mtf.VariableDtype"
  },
  {
    "code": "def trace(self, n):\n        \"Restore the position in the history of individual v's nodes\"\n        trace_map = {}\n        self._trace(n, trace_map)\n        s = list(trace_map.keys())\n        s.sort()\n        return s",
    "docstring": "Restore the position in the history of individual v's nodes"
  },
  {
    "code": "def parseFeatureRequest(response):\n    features = []\n    while (len(response) > 0):\n        tag = response[0]\n        control = ((((((response[2] << 8) +\n                        response[3]) << 8) +\n                        response[4]) << 8) +\n                        response[5])\n        try:\n            features.append([Features[tag], control])\n        except KeyError:\n            pass\n        del response[:6]\n    return features",
    "docstring": "Get the list of Part10 features supported by the reader.\n\n    @param response: result of CM_IOCTL_GET_FEATURE_REQUEST commmand\n\n    @rtype: list\n    @return: a list of list [[tag1, value1], [tag2, value2]]"
  },
  {
    "code": "def copy(self, datasets=None):\n        new_scn = self.__class__()\n        new_scn.attrs = self.attrs.copy()\n        new_scn.dep_tree = self.dep_tree.copy()\n        for ds_id in (datasets or self.keys()):\n            new_scn.datasets[ds_id] = self[ds_id]\n        if not datasets:\n            new_scn.wishlist = self.wishlist.copy()\n        else:\n            new_scn.wishlist = set([DatasetID.from_dict(ds.attrs)\n                                    for ds in new_scn])\n        return new_scn",
    "docstring": "Create a copy of the Scene including dependency information.\n\n        Args:\n            datasets (list, tuple): `DatasetID` objects for the datasets\n                                    to include in the new Scene object."
  },
  {
    "code": "def copy(self, **replacements):\n    cls = type(self)\n    kwargs = {'org': self.org, 'name': self.name, 'ext': self.ext, 'classifier': self.classifier, 'rev': self.rev}\n    for key, val in replacements.items():\n      kwargs[key] = val\n    return cls(**kwargs)",
    "docstring": "Returns a clone of this M2Coordinate with the given replacements kwargs overlaid."
  },
  {
    "code": "def time_range(self, start, end):\n        self._set_query(self.time_query, time_start=self._format_time(start),\n                        time_end=self._format_time(end))\n        return self",
    "docstring": "Add a request for a time range to the query.\n\n        This modifies the query in-place, but returns `self` so that multiple queries\n        can be chained together on one line.\n\n        This replaces any existing temporal queries that have been set.\n\n        Parameters\n        ----------\n        start : datetime.datetime\n            The start of the requested time range\n        end : datetime.datetime\n            The end of the requested time range\n\n        Returns\n        -------\n        self : DataQuery\n            Returns self for chaining calls"
  },
  {
    "code": "def filter_butter(samples, samplerate, filtertype, freq, order=5):\n    assert filtertype in ('low', 'high', 'band')\n    b, a = filter_butter_coeffs(filtertype, freq, samplerate, order=order)\n    return apply_multichannel(samples, lambda data:signal.lfilter(b, a, data))",
    "docstring": "Filters the samples with a digital butterworth filter\n\n    samples   : mono samples\n    filtertype: 'low', 'band', 'high'\n    freq      : for low or high, the cutoff freq\n                for band, (low, high)\n    samplerate: the sampling-rate\n    order     : the order of the butterworth filter\n\n    Returns --> the filtered samples\n\n    NB: calls filter_butter_coeffs to calculate the coefficients"
  },
  {
    "code": "def connect_network_gateway(self, gateway_id, body=None):\n        base_uri = self.network_gateway_path % gateway_id\n        return self.put(\"%s/connect_network\" % base_uri, body=body)",
    "docstring": "Connect a network gateway to the specified network."
  },
  {
    "code": "def _parse_check(self, rule):\n        for check_cls in (checks.FalseCheck, checks.TrueCheck):\n            check = check_cls()\n            if rule == str(check):\n                return check\n        try:\n            kind, match = rule.split(':', 1)\n        except Exception:\n            if self.raise_error:\n                raise InvalidRuleException(rule)\n            else:\n                LOG.exception('Failed to understand rule %r', rule)\n                return checks.FalseCheck()\n        if kind in checks.registered_checks:\n            return checks.registered_checks[kind](kind, match)\n        elif None in checks.registered_checks:\n            return checks.registered_checks[None](kind, match)\n        elif self.raise_error:\n            raise InvalidRuleException(rule)\n        else:\n            LOG.error('No handler for matches of kind %r', kind)\n            return checks.FalseCheck()",
    "docstring": "Parse a single base check rule into an appropriate Check object."
  },
  {
    "code": "def is_file_like(obj):\n    if not (hasattr(obj, 'read') or hasattr(obj, 'write')):\n        return False\n    if not hasattr(obj, \"__iter__\"):\n        return False\n    return True",
    "docstring": "Check if the object is a file-like object.\n\n    For objects to be considered file-like, they must\n    be an iterator AND have either a `read` and/or `write`\n    method as an attribute.\n\n    Note: file-like objects must be iterable, but\n    iterable objects need not be file-like.\n\n    .. versionadded:: 0.20.0\n\n    Parameters\n    ----------\n    obj : The object to check\n\n    Returns\n    -------\n    is_file_like : bool\n        Whether `obj` has file-like properties.\n\n    Examples\n    --------\n    >>> buffer(StringIO(\"data\"))\n    >>> is_file_like(buffer)\n    True\n    >>> is_file_like([1, 2, 3])\n    False"
  },
  {
    "code": "def n_orifices_per_row(self):\n        H = self.b_rows - 0.5*self.orifice_diameter\n        flow_per_orifice = pc.flow_orifice_vert(self.orifice_diameter, H, con.VC_ORIFICE_RATIO)\n        n = np.zeros(self.n_rows)\n        for i in range(self.n_rows):\n            flow_needed = self.flow_ramp[i] - self.flow_actual(i, n)\n            n_orifices_real = (flow_needed / flow_per_orifice).to(u.dimensionless)\n            n[i] = min((max(0, round(n_orifices_real))), self.n_orifices_per_row_max)\n        return n",
    "docstring": "Calculate number of orifices at each level given an orifice\n        diameter."
  },
  {
    "code": "def ensure_symlink (src, dst):\n    try:\n        os.symlink (src, dst)\n    except OSError as e:\n        if e.errno == 17:\n            return True\n        raise\n    return False",
    "docstring": "Ensure the existence of a symbolic link pointing to src named dst. Returns\n    a boolean indicating whether the symlink already existed."
  },
  {
    "code": "def _compute_predicates(table_op, predicates, data, scope, **kwargs):\n    for predicate in predicates:\n        root_tables = predicate.op().root_tables()\n        additional_scope = {}\n        data_columns = frozenset(data.columns)\n        for root_table in root_tables:\n            mapping = remap_overlapping_column_names(\n                table_op, root_table, data_columns\n            )\n            if mapping is not None:\n                new_data = data.loc[:, mapping.keys()].rename(columns=mapping)\n            else:\n                new_data = data\n            additional_scope[root_table] = new_data\n        new_scope = toolz.merge(scope, additional_scope)\n        yield execute(predicate, scope=new_scope, **kwargs)",
    "docstring": "Compute the predicates for a table operation.\n\n    Parameters\n    ----------\n    table_op : TableNode\n    predicates : List[ir.ColumnExpr]\n    data : pd.DataFrame\n    scope : dict\n    kwargs : dict\n\n    Returns\n    -------\n    computed_predicate : pd.Series[bool]\n\n    Notes\n    -----\n    This handles the cases where the predicates are computed columns, in\n    addition to the simple case of named columns coming directly from the input\n    table."
  },
  {
    "code": "def _check_required(self, value):\n        if value is None and self._required:\n            err_msg = self._errors['required'].format(self.__class__.__name__, self.name)\n            if self.container_model:\n                err_msg += self._errors['required_extra'].format(self.container_model.__name__)\n            raise ValueError(err_msg)",
    "docstring": "Internal method to check if assigned value is None while it is required.\n        Exception is thrown if ``True``"
  },
  {
    "code": "def handle_log(self, obj):\n        record_dict = json.loads(obj[ExecutorProtocol.LOG_MESSAGE])\n        record_dict['msg'] = record_dict['msg']\n        executors_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'executors')\n        record_dict['pathname'] = os.path.join(executors_dir, record_dict['pathname'])\n        logger.handle(logging.makeLogRecord(record_dict))",
    "docstring": "Handle an incoming log processing request.\n\n        :param obj: The Channels message object. Command object format:\n\n            .. code-block:: none\n\n                {\n                    'command': 'log',\n                    'message': [log message]\n                }"
  },
  {
    "code": "def run(self, tag=None, output=None, **kwargs):\n        start = datetime.datetime.now()\n        count = 0\n        if tag:\n            tag = Uri(tag)\n            xml_generator = etree.iterparse(self.source,\n                                            tag=tag.etree)\n        else:\n            xml_generator = etree.iterparse(self.source)\n        i = 0\n        for event, element in xml_generator:\n            type_tags = element.findall(_RDF_TYPE_TAG)\n            rdf_types = [el.get(_RES_TAG)\n                         for el in type_tags\n                         if el.get(_RES_TAG)]\n            if str(self.filter_val) in rdf_types:\n                pdb.set_trace()\n                count += 1\n            i += 1\n            element.clear()\n        print(\"Found '{}' items in {}\".format(count,\n                (datetime.datetime.now() - start)))",
    "docstring": "runs the extractor\n\n        Args:\n        -----\n            output: ['filepath', None]"
  },
  {
    "code": "def LoadFromXml(self, node):\n\t\timport os\n\t\tself.classId = node.localName\n\t\tmetaClassId = UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId)\n\t\tif metaClassId:\n\t\t\tself.classId = metaClassId\n\t\tif node.hasAttribute(NamingPropertyId.DN):\n\t\t\tself.dn = node.getAttribute(NamingPropertyId.DN)\n\t\tif self.dn:\n\t\t\tself.rn = os.path.basename(self.dn)\n\t\tself.WriteToAttributes(node)\n\t\tif (node.hasChildNodes()):\n\t\t\tchildList = node.childNodes\n\t\t\tchildCount = len(childList)\n\t\t\tfor i in range(childCount):\n\t\t\t\tchildNode = childList.item(i)\n\t\t\t\tif (childNode.nodeType != Node.ELEMENT_NODE):\n\t\t\t\t\tcontinue\n\t\t\t\tc = _GenericMO()\n\t\t\t\tself.child.append(c)\n\t\t\t\tc.LoadFromXml(childNode)",
    "docstring": "Method updates the object from the xml."
  },
  {
    "code": "def list_securitygroup_rules(self, group_id):\n        return self.security_group.getRules(id=group_id, iter=True)",
    "docstring": "List security group rules associated with a security group.\n\n        :param int group_id: The security group to list rules for"
  },
  {
    "code": "def load(self, model):\n        self._dawg.load(find_data(model))\n        self._loaded_model = True",
    "docstring": "Load pickled DAWG from disk."
  },
  {
    "code": "def extended(self):\n        if self.expires_at:\n            return self.expires_at - self.issued_at > timedelta(days=30)\n        else:\n            return False",
    "docstring": "Determine whether the OAuth token has been extended."
  },
  {
    "code": "def generic_ref_formatter(view, context, model, name, lazy=False):\n    try:\n        if lazy:\n            rel_model = getattr(model, name).fetch()\n        else:\n            rel_model = getattr(model, name)\n    except (mongoengine.DoesNotExist, AttributeError) as e:\n        return Markup(\n            '<span class=\"label label-danger\">Error</span> <small>%s</small>' % e\n        )\n    if rel_model is None:\n        return ''\n    try:\n        return Markup(\n            '<a href=\"%s\">%s</a>'\n            % (\n                url_for(\n                    '%s.details_view' % rel_model.__class__.__name__.lower(),\n                    id=rel_model.id,\n                ),\n                rel_model,\n            )\n        )\n    except werkzeug.routing.BuildError as e:\n        return Markup(\n            '<span class=\"label label-danger\">Error</span> <small>%s</small>' % e\n        )",
    "docstring": "For GenericReferenceField and LazyGenericReferenceField\n\n    See Also\n    --------\n    diff_formatter"
  },
  {
    "code": "def get_user_columns_list(self):\n        ret_lst = list()\n        for col_name in self.get_columns_list():\n            if (not self.is_pk(col_name)) and (not self.is_fk(col_name)):\n                ret_lst.append(col_name)\n        return ret_lst",
    "docstring": "Returns all model's columns except pk or fk"
  },
  {
    "code": "def substitute_array(a, d):\n    a = np.asarray(a, order=\"C\")\n    return np.array([substitute(v, d) for v in a.flat]).reshape(a.shape)",
    "docstring": "Apply ``substitute`` to all elements of an array ``a`` and return the resulting array.\n\n    :param Union[np.array,List] a: The expression array to substitute.\n    :param Dict[Parameter,Union[int,float]] d: Numerical substitutions for parameters.\n    :return: An array of partially substituted Expressions or numbers.\n    :rtype: np.array"
  },
  {
    "code": "def read_from_file(path, file_type='text', exception=ScriptWorkerException):\n    FILE_TYPE_MAP = {'text': 'r', 'binary': 'rb'}\n    if file_type not in FILE_TYPE_MAP:\n        raise exception(\"Unknown file_type {} not in {}!\".format(file_type, FILE_TYPE_MAP))\n    try:\n        with open(path, FILE_TYPE_MAP[file_type]) as fh:\n            return fh.read()\n    except (OSError, FileNotFoundError) as exc:\n        raise exception(\"Can't read_from_file {}: {}\".format(path, str(exc)))",
    "docstring": "Read from ``path``.\n\n    Small helper function to read from ``file``.\n\n    Args:\n        path (str): the path to read from.\n        file_type (str, optional): the type of file. Currently accepts\n            ``text`` or ``binary``. Defaults to ``text``.\n        exception (Exception, optional): the exception to raise\n            if unable to read from the file.  Defaults to ``ScriptWorkerException``.\n\n    Returns:\n        None: if unable to read from ``path`` and ``exception`` is ``None``\n        str or bytes: the contents of ``path``\n\n    Raises:\n        Exception: if ``exception`` is set."
  },
  {
    "code": "def publish(self, synchronous=True, **kwargs):\n        kwargs = kwargs.copy()\n        if 'data' in kwargs and 'id' not in kwargs['data']:\n            kwargs['data']['id'] = self.id\n        kwargs.update(self._server_config.get_client_kwargs())\n        response = client.post(self.path('publish'), **kwargs)\n        return _handle_response(response, self._server_config, synchronous)",
    "docstring": "Helper for publishing an existing content view.\n\n        :param synchronous: What should happen if the server returns an HTTP\n            202 (accepted) status code? Wait for the task to complete if\n            ``True``. Immediately return the server's response otherwise.\n        :param kwargs: Arguments to pass to requests.\n        :returns: The server's response, with all JSON decoded.\n        :raises: ``requests.exceptions.HTTPError`` If the server responds with\n            an HTTP 4XX or 5XX message."
  },
  {
    "code": "def bschoi(value, ndim, array, order):\n    value = ctypes.c_int(value)\n    ndim = ctypes.c_int(ndim)\n    array = stypes.toIntVector(array)\n    order = stypes.toIntVector(order)\n    return libspice.bschoi_c(value, ndim, array, order)",
    "docstring": "Do a binary search for a given value within an integer array,\n    accompanied by an order vector.  Return the index of the\n    matching array entry, or -1 if the key value is not found.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bschoi_c.html\n\n    :param value: Key value to be found in array.\n    :type value: int\n    :param ndim: Dimension of array.\n    :type ndim: int\n    :param array: Integer array to search.\n    :type array: Array of ints\n    :param order: Order vector.\n    :type order: Array of ints\n    :return: index\n    :rtype: int"
  },
  {
    "code": "def storagehandler(self):\n        if isinstance(self, StorageHandler):\n            return self\n        elif self.parent is not None:\n            return self.parent.storagehandler\n        else:\n            return None",
    "docstring": "Returns the storage handler available to thise actor.\n\n        :return: the storage handler, None if not available"
  },
  {
    "code": "def abort(self):\n        if self.resume_queue:\n            self.resume_queue.put(False)\n        self.try_aborting_function(ss.ABORTING, ss.ABORTED, self.do_abort)",
    "docstring": "Abort the current operation and block until aborted\n\n        Normally it will return in Aborted state. If something goes wrong it\n        will return in Fault state. If the user disables then it will return in\n        Disabled state."
  },
  {
    "code": "def service_checks(self, name):\n        return [\n            ServiceCheckStub(\n                ensure_unicode(stub.check_id),\n                ensure_unicode(stub.name),\n                stub.status,\n                normalize_tags(stub.tags),\n                ensure_unicode(stub.hostname),\n                ensure_unicode(stub.message),\n            )\n            for stub in self._service_checks.get(to_string(name), [])\n        ]",
    "docstring": "Return the service checks received under the given name"
  },
  {
    "code": "def solo(whyrun=False,\n         logfile=None,\n         **kwargs):\n    if logfile is None:\n        logfile = _default_logfile('chef-solo')\n    args = ['chef-solo',\n            '--no-color',\n            '--logfile \"{0}\"'.format(logfile),\n            '--format doc']\n    if whyrun:\n        args.append('--why-run')\n    return _exec_cmd(*args, **kwargs)",
    "docstring": "Execute a chef solo run and return a dict with the stderr, stdout,\n    return code, and pid.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' chef.solo override-runlist=test\n\n    config\n        The configuration file to use\n\n    environment\n        Set the Chef Environment on the node\n\n    group\n        Group to set privilege to\n\n    json-attributes\n        Load attributes from a JSON file or URL\n\n    log_level\n        Set the log level (debug, info, warn, error, fatal)\n\n    logfile\n        Set the log file location\n\n    node-name\n        The node name for this client\n\n    override-runlist\n        Replace current run list with specified items for a single run\n\n    recipe-url\n        Pull down a remote gzipped tarball of recipes and untar it to\n        the cookbook cache\n\n    run-lock-timeout\n        Set maximum duration to wait for another client run to finish,\n        default is indefinitely.\n\n    user\n        User to set privilege to\n\n    whyrun\n        Enable whyrun mode when set to True"
  },
  {
    "code": "def minimum_distance2(hull_a, center_a, hull_b, center_b):\n    if hull_a.shape[0] < 3 or hull_b.shape[0] < 3:\n        return slow_minimum_distance2(hull_a, hull_b)\n    else:\n        return faster_minimum_distance2(hull_a, center_a, hull_b, center_b)",
    "docstring": "Return the minimum distance or 0 if overlap between 2 convex hulls\n    \n    hull_a - list of points in clockwise direction\n    center_a - a point within the hull\n    hull_b - list of points in clockwise direction\n    center_b - a point within the hull"
  },
  {
    "code": "def get_config(ini_path=None, rootdir=None):\n    config = Namespace()\n    config.default_section = 'pylama'\n    if not ini_path:\n        path = get_default_config_file(rootdir)\n        if path:\n            config.read(path)\n    else:\n        config.read(ini_path)\n    return config",
    "docstring": "Load configuration from INI.\n\n    :return Namespace:"
  },
  {
    "code": "def get_batch(self, filename=None):\n        try:\n            history = self.history_model.objects.get(filename=filename)\n        except self.history_model.DoesNotExist as e:\n            raise TransactionsFileQueueError(\n                f\"Batch history not found for '{filename}'.\"\n            ) from e\n        if history.consumed:\n            raise TransactionsFileQueueError(\n                f\"Batch closed for '{filename}'. Got consumed=True\"\n            )\n        batch = self.batch_cls()\n        batch.batch_id = history.batch_id\n        batch.filename = history.filename\n        return batch",
    "docstring": "Returns a batch instance given the filename."
  },
  {
    "code": "def rename_dont_move(self, path, dest):\n        from snakebite.errors import FileAlreadyExistsException\n        try:\n            self.get_bite().rename2(path, dest, overwriteDest=False)\n        except FileAlreadyExistsException:\n            raise luigi.target.FileAlreadyExists()",
    "docstring": "Use snakebite.rename_dont_move, if available.\n\n        :param path: source path (single input)\n        :type path: string\n        :param dest: destination path\n        :type dest: string\n        :return: True if succeeded\n        :raises: snakebite.errors.FileAlreadyExistsException"
  },
  {
    "code": "async def remove_all(self, detach=False, eject=False, lock=False):\n        kw = dict(force=True, detach=detach, eject=eject, lock=lock)\n        tasks = [self.auto_remove(device, **kw)\n                 for device in self.get_all_handleable_roots()]\n        results = await gather(*tasks)\n        success = all(results)\n        return success",
    "docstring": "Remove all filesystems handleable by udiskie.\n\n        :param bool detach: detach the root drive\n        :param bool eject: remove media from the root drive\n        :param bool lock: lock the associated LUKS cleartext slave\n        :returns: whether all attempted operations succeeded"
  },
  {
    "code": "def get(self, name):\n        config = self.get_block('interface %s' % name)\n        if 'no switchport\\n' in config:\n            return\n        resource = dict(name=name)\n        resource.update(self._parse_mode(config))\n        resource.update(self._parse_access_vlan(config))\n        resource.update(self._parse_trunk_native_vlan(config))\n        resource.update(self._parse_trunk_allowed_vlans(config))\n        resource.update(self._parse_trunk_groups(config))\n        return resource",
    "docstring": "Returns a dictionary object that represents a switchport\n\n        The Switchport resource returns the following:\n\n            * name (str): The name of the interface\n            * mode (str): The switchport mode value\n            * access_vlan (str): The switchport access vlan value\n            * trunk_native_vlan (str): The switchport trunk native vlan vlaue\n            * trunk_allowed_vlans (str): The trunk allowed vlans value\n            * trunk_groups (list): The list of trunk groups configured\n\n        Args:\n            name (string): The interface identifier to get.  Note: Switchports\n                are only supported on Ethernet and Port-Channel interfaces\n\n        Returns:\n            dict: A Python dictionary object of key/value pairs that represent\n                the switchport configuration for the interface specified  If\n                the specified argument is not a switchport then None\n                is returned"
  },
  {
    "code": "def chunks(self, size=32, alignment=1):\n        if (size % alignment) != 0:\n            raise Error(\n                'size {} is not a multiple of alignment {}'.format(\n                    size,\n                    alignment))\n        address = self.address\n        data = self.data\n        chunk_offset = (address % alignment)\n        if chunk_offset != 0:\n            first_chunk_size = (alignment - chunk_offset)\n            yield self._Chunk(address, data[:first_chunk_size])\n            address += (first_chunk_size // self._word_size_bytes)\n            data = data[first_chunk_size:]\n        else:\n            first_chunk_size = 0\n        for offset in range(0, len(data), size):\n            yield self._Chunk(address + offset // self._word_size_bytes,\n                              data[offset:offset + size])",
    "docstring": "Return chunks of the data aligned as given by `alignment`. `size`\n        must be a multiple of `alignment`. Each chunk is returned as a\n        named two-tuple of its address and data."
  },
  {
    "code": "def container_device_get(name, device_name, remote_addr=None,\n                         cert=None, key=None, verify_cert=True):\n    container = container_get(\n        name, remote_addr, cert, key, verify_cert, _raw=True\n    )\n    return _get_property_dict_item(container, 'devices', device_name)",
    "docstring": "Get a container device\n\n    name :\n        Name of the container\n\n    device_name :\n        The device name to retrieve\n\n    remote_addr :\n        An URL to a remote Server, you also have to give cert and key if\n        you provide remote_addr and its a TCP Address!\n\n        Examples:\n            https://myserver.lan:8443\n            /var/lib/mysocket.sock\n\n    cert :\n        PEM Formatted SSL Certificate.\n\n        Examples:\n            ~/.config/lxc/client.crt\n\n    key :\n        PEM Formatted SSL Key.\n\n        Examples:\n            ~/.config/lxc/client.key\n\n    verify_cert : True\n        Wherever to verify the cert, this is by default True\n        but in the most cases you want to set it off as LXD\n        normaly uses self-signed certificates."
  },
  {
    "code": "def get_counters(counter_list):\n    if not isinstance(counter_list, list):\n        raise CommandExecutionError('counter_list must be a list of tuples')\n    try:\n        query = win32pdh.OpenQuery()\n        counters = build_counter_list(counter_list)\n        for counter in counters:\n            counter.add_to_query(query)\n        win32pdh.CollectQueryData(query)\n        time.sleep(1)\n        win32pdh.CollectQueryData(query)\n        ret = {}\n        for counter in counters:\n            try:\n                ret.update({counter.path: counter.value()})\n            except pywintypes.error as exc:\n                if exc.strerror == 'No data to return.':\n                    continue\n                else:\n                    raise\n    finally:\n        win32pdh.CloseQuery(query)\n    return ret",
    "docstring": "Get the values for the passes list of counters\n\n    Args:\n        counter_list (list):\n            A list of counters to lookup\n\n    Returns:\n        dict: A dictionary of counters and their values"
  },
  {
    "code": "def version():\n    cmd = ['varnishd', '-V']\n    out = __salt__['cmd.run'](cmd, python_shell=False)\n    ret = re.search(r'\\(varnish-([^\\)]+)\\)', out).group(1)\n    return ret",
    "docstring": "Return server version from varnishd -V\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' varnish.version"
  },
  {
    "code": "def broken_chains(samples, chains):\n    samples = np.asarray(samples)\n    if samples.ndim != 2:\n        raise ValueError(\"expected samples to be a numpy 2D array\")\n    num_samples, num_variables = samples.shape\n    num_chains = len(chains)\n    broken = np.zeros((num_samples, num_chains), dtype=bool, order='F')\n    for cidx, chain in enumerate(chains):\n        if isinstance(chain, set):\n            chain = list(chain)\n        chain = np.asarray(chain)\n        if chain.ndim > 1:\n            raise ValueError(\"chains should be 1D array_like objects\")\n        if len(chain) <= 1:\n            continue\n        all_ = (samples[:, chain] == 1).all(axis=1)\n        any_ = (samples[:, chain] == 1).any(axis=1)\n        broken[:, cidx] = np.bitwise_xor(all_, any_)\n    return broken",
    "docstring": "Find the broken chains.\n\n    Args:\n        samples (array_like):\n            Samples as a nS x nV array_like object where nS is the number of samples and nV is the\n            number of variables. The values should all be 0/1 or -1/+1.\n\n        chains (list[array_like]):\n            List of chains of length nC where nC is the number of chains.\n            Each chain should be an array_like collection of column indices in samples.\n\n    Returns:\n        :obj:`numpy.ndarray`: A nS x nC boolean array. If i, j is True, then chain j in sample i is\n        broken.\n\n    Examples:\n        >>> samples = np.array([[-1, +1, -1, +1], [-1, -1, +1, +1]], dtype=np.int8)\n        >>> chains = [[0, 1], [2, 3]]\n        >>> dwave.embedding.broken_chains(samples, chains)\n        array([[True, True],\n               [ False,  False]])\n\n        >>> samples = np.array([[-1, +1, -1, +1], [-1, -1, +1, +1]], dtype=np.int8)\n        >>> chains = [[0, 2], [1, 3]]\n        >>> dwave.embedding.broken_chains(samples, chains)\n        array([[False, False],\n               [ True,  True]])"
  },
  {
    "code": "def on_message(self, event):\n        metadata = self._parse_metadata(event)\n        message = Message(text=metadata['text'],\n                          metadata=metadata).__dict__\n        if message.get('text'):\n            message['text'] = self.find_and_replace_userids(message['text'])\n            message['text'] = self.find_and_replace_channel_refs(\n                message['text']\n            )\n        return message",
    "docstring": "Runs when a message event is received\n\n        Args:\n            event: RTM API event.\n\n        Returns:\n            Legobot.messge"
  },
  {
    "code": "def seek(self, offset, whence=Seek.set):\n        _whence = int(whence)\n        if _whence == Seek.current:\n            offset += self._pos\n        if _whence == Seek.current or _whence == Seek.set:\n            if offset < 0:\n                raise ValueError(\"Negative seek position {}\".format(offset))\n        elif _whence == Seek.end:\n            if offset > 0:\n                raise ValueError(\"Positive seek position {}\".format(offset))\n            offset += self._end\n        else:\n            raise ValueError(\n                \"Invalid whence ({}, should be {}, {} or {})\".format(\n                    _whence, Seek.set, Seek.current, Seek.end\n                )\n            )\n        if offset < self._pos:\n            self._f = self._zip.open(self.name)\n            self._pos = 0\n        self.read(offset - self._pos)\n        return self._pos",
    "docstring": "Change stream position.\n\n        Change the stream position to the given byte offset. The\n        offset is interpreted relative to the position indicated by\n        ``whence``.\n\n        Arguments:\n            offset (int): the offset to the new position, in bytes.\n            whence (int): the position reference. Possible values are:\n                * `Seek.set`: start of stream (the default).\n                * `Seek.current`: current position; offset may be negative.\n                * `Seek.end`: end of stream; offset must be negative.\n\n        Returns:\n            int: the new absolute position.\n\n        Raises:\n            ValueError: when ``whence`` is not known, or ``offset``\n                is invalid.\n\n        Note:\n            Zip compression does not support seeking, so the seeking\n            is emulated. Seeking somewhere else than the current position\n            will need to either:\n                * reopen the file and restart decompression\n                * read and discard data to advance in the file"
  },
  {
    "code": "def converged_ionic(self):\n        nsw = self.parameters.get(\"NSW\", 0)\n        return nsw <= 1 or len(self.ionic_steps) < nsw",
    "docstring": "Checks that ionic step convergence has been reached, i.e. that vasp\n        exited before reaching the max ionic steps for a relaxation run"
  },
  {
    "code": "def add_edge_bearings(G):\n    for u, v, data in G.edges(keys=False, data=True):\n        if u == v:\n            data['bearing'] = np.nan\n        else:\n            origin_point = (G.nodes[u]['y'], G.nodes[u]['x'])\n            destination_point = (G.nodes[v]['y'], G.nodes[v]['x'])\n            bearing = get_bearing(origin_point, destination_point)\n            data['bearing'] = round(bearing, 3)\n    return G",
    "docstring": "Calculate the compass bearing from origin node to destination node for each\n    edge in the directed graph then add each bearing as a new edge attribute.\n\n    Parameters\n    ----------\n    G : networkx multidigraph\n\n    Returns\n    -------\n    G : networkx multidigraph"
  },
  {
    "code": "def get_connection_string(connection=None):\n    if not connection:\n        config = configparser.ConfigParser()\n        cfp = defaults.config_file_path\n        if os.path.exists(cfp):\n            log.info('fetch database configuration from %s', cfp)\n            config.read(cfp)\n            connection = config['database']['sqlalchemy_connection_string']\n            log.info('load connection string from %s: %s', cfp, connection)\n        else:\n            with open(cfp, 'w') as config_file:\n                connection = defaults.sqlalchemy_connection_string_default\n                config['database'] = {'sqlalchemy_connection_string': connection}\n                config.write(config_file)\n                log.info('create configuration file %s', cfp)\n    return connection",
    "docstring": "return SQLAlchemy connection string if it is set\n\n    :param connection: get the SQLAlchemy connection string #TODO\n    :rtype: str"
  },
  {
    "code": "def _viewbox_unset(self, viewbox):\n        self._viewbox = None\n        viewbox.events.mouse_press.disconnect(self.viewbox_mouse_event)\n        viewbox.events.mouse_release.disconnect(self.viewbox_mouse_event)\n        viewbox.events.mouse_move.disconnect(self.viewbox_mouse_event)\n        viewbox.events.mouse_wheel.disconnect(self.viewbox_mouse_event)\n        viewbox.events.resize.disconnect(self.viewbox_resize_event)",
    "docstring": "Friend method of viewbox to unregister itself."
  },
  {
    "code": "def dump_registers_peek(registers, data, separator = ' ', width = 16):\n        if None in (registers, data):\n            return ''\n        names = compat.keys(data)\n        names.sort()\n        result = ''\n        for reg_name in names:\n            tag     = reg_name.lower()\n            dumped  = HexDump.hexline(data[reg_name], separator, width)\n            result += '%s -> %s\\n' % (tag, dumped)\n        return result",
    "docstring": "Dump data pointed to by the given registers, if any.\n\n        @type  registers: dict( str S{->} int )\n        @param registers: Dictionary mapping register names to their values.\n            This value is returned by L{Thread.get_context}.\n\n        @type  data: dict( str S{->} str )\n        @param data: Dictionary mapping register names to the data they point to.\n            This value is returned by L{Thread.peek_pointers_in_registers}.\n\n        @rtype:  str\n        @return: Text suitable for logging."
  },
  {
    "code": "def read(self, file_or_filename):\n        if isinstance(file_or_filename, basestring):\n            fname = os.path.basename(file_or_filename)\n            logger.info(\"Unpickling case file [%s].\" % fname)\n            file = None\n            try:\n                file = open(file_or_filename, \"rb\")\n            except:\n                logger.error(\"Error opening %s.\" % fname)\n                return None\n            finally:\n                if file is not None:\n                    case = pickle.load(file)\n                    file.close()\n        else:\n            file = file_or_filename\n            case = pickle.load(file)\n        return case",
    "docstring": "Loads a pickled case."
  },
  {
    "code": "def bind(self, cube):\n        table, column = self._physical_column(cube, self.column_name)\n        column = column.label(self.matched_ref)\n        column.quote = True\n        return table, column",
    "docstring": "Map a model reference to an physical column in the database."
  },
  {
    "code": "def close(self):\n        if not (yield from super().close()):\n            return False\n        for adapter in self._ethernet_adapters.values():\n            if adapter is not None:\n                for nio in adapter.ports.values():\n                    if nio and isinstance(nio, NIOUDP):\n                        self.manager.port_manager.release_udp_port(nio.lport, self._project)\n        try:\n            self.acpi_shutdown = False\n            yield from self.stop()\n        except VMwareError:\n            pass\n        if self.linked_clone:\n            yield from self.manager.remove_from_vmware_inventory(self._vmx_path)",
    "docstring": "Closes this VMware VM."
  },
  {
    "code": "def GetVolumeByIndex(self, volume_index):\n    if not self._is_parsed:\n      self._Parse()\n      self._is_parsed = True\n    if volume_index < 0 or volume_index >= len(self._volume_identifiers):\n      return None\n    volume_identifier = self._volume_identifiers[volume_index]\n    return self._volumes[volume_identifier]",
    "docstring": "Retrieves a specific volume based on the index.\n\n    Args:\n      volume_index (int): index of the volume.\n\n    Returns:\n      Volume: a volume or None if not available."
  },
  {
    "code": "def _validate_translation(self, aligned_prot, aligned_nucl):\n        codons = [''.join(i) for i in batch(str(aligned_nucl), 3)]\n        for codon, aa in zip(codons, str(aligned_prot)):\n            if codon == '---' and aa == '-':\n                continue\n            try:\n                trans = self.translation_table.forward_table[codon]\n                if not trans == aa:\n                    raise ValueError(\"Codon {0} translates to {1}, not {2}\".format(\n                        codon, trans, aa))\n            except (KeyError, CodonTable.TranslationError):\n                if aa != 'X':\n                    if self.unknown_action == 'fail':\n                        raise ValueError(\"Unknown codon: {0} mapped to {1}\".format(\n                            codon, aa))\n                    elif self.unknown_action == 'warn':\n                        logging.warn('Cannot verify that unknown codon %s '\n                                     'maps to %s', codon, aa)\n        return True",
    "docstring": "Given a seq for protein and nucleotide, ensure that the translation holds"
  },
  {
    "code": "def add_string_pairs_from_attributed_ui_element(results, ui_element, comment_prefix):\n    attributed_strings = ui_element.getElementsByTagName('attributedString')\n    if attributed_strings.length == 0:\n        return False\n    attributed_element = attributed_strings[0]\n    fragment_index = 1\n    for fragment in attributed_element.getElementsByTagName('fragment'):\n        try:\n            label_entry_key = fragment.attributes['content'].value\n        except KeyError:\n            label_entry_key = fragment.getElementsByTagName('string')[0].firstChild.nodeValue\n        comment = \"%s Part %d\" % (comment_prefix, fragment_index)\n        results.append((label_entry_key, comment))\n        fragment_index += 1\n    return fragment_index > 1",
    "docstring": "Adds string pairs from a UI element with attributed text\n\n    Args:\n        results (list): The list to add the results to.\n        attributed_element (element): The element from the xib that contains, to extract the fragments from.\n        comment_prefix (str): The prefix of the comment to use for extracted string\n                              (will be appended \"Part X\" suffices)\n\n    Returns:\n        bool: Whether or not an attributed string was found."
  },
  {
    "code": "def _post_process_yaml_data(self,\n                                fixture_data: Dict[str, Dict[str, Any]],\n                                relationship_columns: Set[str],\n                                ) -> Tuple[Dict[str, Dict[str, Any]], List[str]]:\n        rv = {}\n        relationships = set()\n        if not fixture_data:\n            return rv, relationships\n        for identifier_id, data in fixture_data.items():\n            new_data = {}\n            for col_name, value in data.items():\n                if col_name not in relationship_columns:\n                    new_data[col_name] = value\n                    continue\n                identifiers = normalize_identifiers(value)\n                if identifiers:\n                    relationships.add(identifiers[0].class_name)\n                if isinstance(value, str) and len(identifiers) <= 1:\n                    new_data[col_name] = identifiers[0] if identifiers else None\n                else:\n                    new_data[col_name] = identifiers\n            rv[identifier_id] = new_data\n        return rv, list(relationships)",
    "docstring": "Convert and normalize identifier strings to Identifiers, as well as determine\n        class relationships."
  },
  {
    "code": "def convert_objects(self, convert_dates=True, convert_numeric=False,\n                        convert_timedeltas=True, copy=True):\n        msg = (\"convert_objects is deprecated.  To re-infer data dtypes for \"\n               \"object columns, use {klass}.infer_objects()\\nFor all \"\n               \"other conversions use the data-type specific converters \"\n               \"pd.to_datetime, pd.to_timedelta and pd.to_numeric.\"\n               ).format(klass=self.__class__.__name__)\n        warnings.warn(msg, FutureWarning, stacklevel=2)\n        return self._constructor(\n            self._data.convert(convert_dates=convert_dates,\n                               convert_numeric=convert_numeric,\n                               convert_timedeltas=convert_timedeltas,\n                               copy=copy)).__finalize__(self)",
    "docstring": "Attempt to infer better dtype for object columns.\n\n        .. deprecated:: 0.21.0\n\n        Parameters\n        ----------\n        convert_dates : boolean, default True\n            If True, convert to date where possible. If 'coerce', force\n            conversion, with unconvertible values becoming NaT.\n        convert_numeric : boolean, default False\n            If True, attempt to coerce to numbers (including strings), with\n            unconvertible values becoming NaN.\n        convert_timedeltas : boolean, default True\n            If True, convert to timedelta where possible. If 'coerce', force\n            conversion, with unconvertible values becoming NaT.\n        copy : boolean, default True\n            If True, return a copy even if no copy is necessary (e.g. no\n            conversion was done). Note: This is meant for internal use, and\n            should not be confused with inplace.\n\n        Returns\n        -------\n        converted : same as input object\n\n        See Also\n        --------\n        to_datetime : Convert argument to datetime.\n        to_timedelta : Convert argument to timedelta.\n        to_numeric : Convert argument to numeric type."
  },
  {
    "code": "def reserve(self, timeout=None):\n        if timeout is not None:\n            command = 'reserve-with-timeout %d\\r\\n' % timeout\n        else:\n            command = 'reserve\\r\\n'\n        try:\n            return self._interact_job(command,\n                                      ['RESERVED'],\n                                      ['DEADLINE_SOON', 'TIMED_OUT'])\n        except CommandFailed:\n            exc = sys.exc_info()[1]\n            _, status, results = exc.args\n            if status == 'TIMED_OUT':\n                return None\n            elif status == 'DEADLINE_SOON':\n                raise DeadlineSoon(results)",
    "docstring": "Reserve a job from one of the watched tubes, with optional timeout\n        in seconds. Returns a Job object, or None if the request times out."
  },
  {
    "code": "def filter_short(terms):\n    return [term for i, term in enumerate(terms) if 26**(len(term)) > i]",
    "docstring": "only keep if brute-force possibilities are greater than this word's rank in the dictionary"
  },
  {
    "code": "def to_json(self, *, include_keys=None, exclude_keys=None, use_default_excludes=True,\n              pretty=False):\n    return to_json(\n      self.to_dict(\n        include_keys=include_keys,\n        exclude_keys=exclude_keys,\n        use_default_excludes=use_default_excludes),\n      pretty=pretty)",
    "docstring": "Converts the response from to_dict to a JSON string. If pretty is True then newlines,\n    indentation and key sorting are used."
  },
  {
    "code": "def adjust(color, attribute, percent):\n    r, g, b, a, type = parse_color(color)\n    r, g, b = hsl_to_rgb(*_adjust(rgb_to_hsl(r, g, b), attribute, percent))\n    return unparse_color(r, g, b, a, type)",
    "docstring": "Adjust an attribute of color by a percent"
  },
  {
    "code": "def open_channel(self):\n        if self._closing:\n            raise ConnectionClosed(\"Closed by application\")\n        if self.closed.done():\n            raise self.closed.exception()\n        channel = yield from self.channel_factory.open()\n        return channel",
    "docstring": "Open a new channel on this connection.\n\n        This method is a :ref:`coroutine <coroutine>`.\n\n        :return: The new :class:`Channel` object."
  },
  {
    "code": "def _loadOneSource(self, sourceFName):\n        sourceLines = open(sourceFName).readlines()\n        del sourceLines[0]\n        if len(sourceLines[0].split(\"\\t\"))==2:\n            self._loadTwoPartSource(sourceFName, sourceLines)\n        elif len(sourceLines[0].split(\"\\t\"))==3:\n            self._loadThreePartSource(sourceFName, sourceLines)\n        else:\n            raise Error, \"%s does not appear to be a source authority file\"",
    "docstring": "handles one authority file including format auto-detection."
  },
  {
    "code": "def apply_noise(data, noise):\n  if noise >= 1:\n    noise = noise/100.\n  for i in range(data.nRows()):\n    ones = data.rowNonZeros(i)[0]\n    replace_indices = numpy.random.choice(ones,\n        size = int(len(ones)*noise), replace = False)\n    for index in replace_indices:\n      data[i, index] = 0\n    new_indices = numpy.random.choice(data.nCols(),\n        size = int(len(ones)*noise), replace = False)\n    for index in new_indices:\n      while data[i, index] == 1:\n        index = numpy.random.randint(0, data.nCols())\n      data[i, index] = 1",
    "docstring": "Applies noise to a sparse matrix.  Noise can be an integer between 0 and\n  100, indicating the percentage of ones in the original input to move, or\n  a float in [0, 1), indicating the same thing.\n  The input matrix is modified in-place, and nothing is returned.\n  This operation does not affect the sparsity of the matrix, or of any\n  individual datapoint."
  },
  {
    "code": "def get_data(self, endpoint=\"privacy\"):\n        if endpoint == \"privacy\":\n            response = self._req('/data/privacy')\n        elif endpoint == \"submission\":\n            response = self._req('/data/submission')\n        elif endpoint == \"tos\":\n            response = self._req('/data/tos')\n        else:\n            raise DeviantartError(\"Unknown endpoint.\")\n        return response['text']",
    "docstring": "Returns policies of DeviantArt"
  },
  {
    "code": "def get_bytearray(self):\n        if isinstance(self._bytearray, DB):\n            return self._bytearray._bytearray\n        return self._bytearray",
    "docstring": "return bytearray from self or DB parent"
  },
  {
    "code": "async def start_timeout(self):\n        self.timeout_handle = self.pyvlx.connection.loop.call_later(\n            self.timeout_in_seconds, self.timeout)",
    "docstring": "Start timeout."
  },
  {
    "code": "def find_first_file_with_ext(base_paths, prefix, exts):\n    for base_path in base_paths:\n        for ext in exts:\n            filename = os.path.join(base_path, \"%s%s\" % (prefix, ext))\n            if os.path.exists(filename) and os.path.isfile(filename):\n                logger.debug(\"Found first file with relevant extension: %s\", filename)\n                return base_path, ext\n    logger.debug(\"No files found for prefix %s, extensions %s\", prefix, \", \".join(exts))\n    return None, None",
    "docstring": "Runs through the given list of file extensions and returns the first file with the given base\n    path and extension combination that actually exists.\n\n    Args:\n        base_paths: The base paths in which to search for files.\n        prefix: The filename prefix of the file for which to search.\n        exts: An ordered list of file extensions for which to search.\n\n    Returns:\n        On success, a 2-tuple containing the base path in which the file was found, and the extension of the file.\n        On failure, returns (None, None)."
  },
  {
    "code": "def runDynTask(task):\n    func = getDynLocal(task[0])\n    if func is None:\n        raise s_exc.NoSuchFunc(name=task[0])\n    return func(*task[1], **task[2])",
    "docstring": "Run a dynamic task and return the result.\n\n    Example:\n\n        foo = runDynTask( ('baz.faz.Foo', (), {} ) )"
  },
  {
    "code": "def get_description(self, language):\n        description = self.gettext(language, self._description) if self._description else ''\n        return ParsableText(description, \"rst\", self._translations.get(language, gettext.NullTranslations()))",
    "docstring": "Returns the course description"
  },
  {
    "code": "def find_pkg_dist(pkg_name, working_set=None):\n    working_set = working_set or default_working_set\n    req = Requirement.parse(pkg_name)\n    return working_set.find(req)",
    "docstring": "Locate a package's distribution by its name."
  },
  {
    "code": "def _es_margin(settings):\n        return {k: settings[k] for k in (ConsoleWidget.SETTING_MARGIN,\n                                         ConsoleWidget.SETTING_MARGIN_LEFT,\n                                         ConsoleWidget.SETTING_MARGIN_RIGHT,\n                                         ConsoleWidget.SETTING_MARGIN_CHAR)}",
    "docstring": "Extract margin formating related subset of widget settings."
  },
  {
    "code": "def is_dental(c,lang): \n    o=get_offset(c,lang)\n    return (o>=DENTAL_RANGE[0] and o<=DENTAL_RANGE[1])",
    "docstring": "Is the character a dental"
  },
  {
    "code": "def _read_hypocentre_from_ndk_string(self, linestring):\n        hypo = GCMTHypocentre()\n        hypo.source = linestring[0:4]\n        hypo.date = _read_date_from_string(linestring[5:15])\n        hypo.time = _read_time_from_string(linestring[16:26])\n        hypo.latitude = float(linestring[27:33])\n        hypo.longitude = float(linestring[34:41])\n        hypo.depth = float(linestring[42:47])\n        magnitudes = [float(x) for x in linestring[48:55].split(' ')]\n        if magnitudes[0] > 0.:\n            hypo.m_b = magnitudes[0]\n        if magnitudes[1] > 0.:\n            hypo.m_s = magnitudes[1]\n        hypo.location = linestring[56:]\n        return hypo",
    "docstring": "Reads the hypocentre data from the ndk string to return an\n        instance of the GCMTHypocentre class"
  },
  {
    "code": "def removeContainer(tag):\n    container = getContainerByTag(tag)\n    if container:\n        try:\n            container.remove(force=True)\n        except APIError as exc:\n            eprint(\"Unhandled error while removing container\", tag)\n            raise exc",
    "docstring": "Check if a container with a given tag exists. Kill it if it exists.\n    No extra side effects. Handles and reraises TypeError, and\n    APIError exceptions."
  },
  {
    "code": "def check_convert_string(obj, name=None,\n                             no_leading_trailing_whitespace=True,\n                             no_whitespace=False,\n                             no_newline=True,\n                             whole_word=False,\n                             min_len=1,\n                             max_len=0):\n        if not name:\n            name = 'Argument'\n        obj = ensure_unicode(obj, name=name)\n        if no_whitespace:\n            if _PATTERN_WHITESPACE.match(obj):\n                raise ValueError('%s cannot contain whitespace' % name)\n        elif no_leading_trailing_whitespace and _PATTERN_LEAD_TRAIL_WHITESPACE.match(obj):\n            raise ValueError('%s contains leading/trailing whitespace' % name)\n        if (min_len and len(obj) < min_len) or (max_len and len(obj) > max_len):\n            raise ValueError('%s too short/long (%d/%d)' % (name, min_len, max_len))\n        if whole_word:\n            if not _PATTERN_WORD.match(obj):\n                raise ValueError('%s can only contain alphanumeric (unicode) characters, numbers and the underscore'\n                                 % name)\n        elif no_newline and '\\n' in obj:\n            raise ValueError('%s cannot contain line breaks' % name)\n        return obj",
    "docstring": "Ensures the provided object can be interpreted as a unicode string, optionally with\n           additional restrictions imposed. By default this means a non-zero length string\n           which does not begin or end in whitespace."
  },
  {
    "code": "def get_seconds_description(self):\n        return self.get_segment_description(\n            self._expression_parts[0],\n            _(\"every second\"),\n            lambda s: s,\n            lambda s: _(\"every {0} seconds\").format(s),\n            lambda s: _(\"seconds {0} through {1} past the minute\"),\n            lambda s: _(\"at {0} seconds past the minute\")\n        )",
    "docstring": "Generates a description for only the SECONDS portion of the expression\n\n        Returns:\n            The SECONDS description"
  },
  {
    "code": "def _ensure_append(self, new_items, append_to, index=0):\n        append_to = append_to or []\n        append_to.insert(index, new_items)\n        return append_to",
    "docstring": "Ensure an item is appended to a list or create a new empty list\n\n        :param new_items: the item(s) to append\n        :type new_items: list(obj)\n        :param append_to: the list on which to append the items\n        :type append_to: list()\n        :param index: index of the list on which to append the items\n        :type index: int"
  },
  {
    "code": "def available_providers(request):\n    \"Adds the list of enabled providers to the context.\"\n    if APPENGINE:\n        qs = SimpleLazyObject(lambda: _get_enabled())\n    else:\n        qs = Provider.objects.filter(consumer_secret__isnull=False, consumer_key__isnull=False)\n    return {'allaccess_providers': qs}",
    "docstring": "Adds the list of enabled providers to the context."
  },
  {
    "code": "def find_users_by_email_starting_with(email_prefix=None, cursor=None, page_size=30):\n    email_prefix = email_prefix or ''\n    return ModelSearchCommand(MainUser.query_email_starts_with(email_prefix),\n                              page_size, cursor, cache_begin=None)",
    "docstring": "Returns a command that retrieves users by its email_prefix, ordered by email.\n    It returns a max number of users defined by page_size arg. Next result can be retrieved using cursor, in\n    a next call. It is provided in cursor attribute from command."
  },
  {
    "code": "def query_by_post(postid):\n        return TabPost2Tag.select().where(\n            TabPost2Tag.post_id == postid\n        ).order_by(TabPost2Tag.order)",
    "docstring": "Query records by post."
  },
  {
    "code": "def insert(self, index, *grids):\n        index, index_in = safe_int_conv(index), index\n        if not -self.ndim <= index <= self.ndim:\n            raise IndexError('index {0} outside the valid range -{1} ... {1}'\n                             ''.format(index_in, self.ndim))\n        if index < 0:\n            index += self.ndim\n        if len(grids) == 0:\n            return RectGrid(*self.coord_vectors)\n        elif len(grids) == 1:\n            grid = grids[0]\n            if not isinstance(grid, RectGrid):\n                raise TypeError('{!r} is not a `RectGrid` instance'\n                                ''.format(grid))\n            new_vecs = (self.coord_vectors[:index] + grid.coord_vectors +\n                        self.coord_vectors[index:])\n            return RectGrid(*new_vecs)\n        else:\n            return self.insert(index, grids[0]).insert(\n                index + grids[0].ndim, *(grids[1:]))",
    "docstring": "Return a copy with ``grids`` inserted before ``index``.\n\n        The given grids are inserted (as a block) into ``self``, yielding\n        a new grid whose number of dimensions is the sum of the numbers of\n        dimensions of all involved grids.\n        Note that no changes are made in-place.\n\n        Parameters\n        ----------\n        index : int\n            The index of the dimension before which ``grids`` are to\n            be inserted. Negative indices count backwards from\n            ``self.ndim``.\n        grid1, ..., gridN :  `RectGrid`\n            The grids to be inserted into ``self``.\n\n        Returns\n        -------\n        newgrid : `RectGrid`\n            The enlarged grid.\n\n        Examples\n        --------\n        >>> g1 = RectGrid([0, 1], [-1, 0, 2])\n        >>> g2 = RectGrid([1], [-6, 15])\n        >>> g1.insert(1, g2)\n        RectGrid(\n            [ 0.,  1.],\n            [ 1.],\n            [ -6.,  15.],\n            [-1.,  0.,  2.]\n        )\n        >>> g1.insert(1, g2, g2)\n        RectGrid(\n            [ 0.,  1.],\n            [ 1.],\n            [ -6.,  15.],\n            [ 1.],\n            [ -6.,  15.],\n            [-1.,  0.,  2.]\n        )\n\n        See Also\n        --------\n        append"
  },
  {
    "code": "def create_at_path(self, asset_content, url_path, tags=''):\n        return self._create_asset({\n            'asset': b64encode(asset_content),\n            'url-path': url_path,\n            'tags': tags,\n            'type': 'base64'\n        })",
    "docstring": "Create asset at a specific URL path on the server"
  },
  {
    "code": "def is_notifying(cls, user_or_email, instance):\n        return super(InstanceEvent, cls).is_notifying(user_or_email,\n                                                      object_id=instance.pk)",
    "docstring": "Check if the watch created by notify exists."
  },
  {
    "code": "def frame_to_seconds(self, frame_index, sr):\n        start_sample, end_sample = self.frame_to_sample(frame_index)\n        return sample_to_seconds(start_sample, sampling_rate=sr), sample_to_seconds(end_sample, sampling_rate=sr)",
    "docstring": "Return a tuple containing the start and end of the frame in seconds."
  },
  {
    "code": "def __pop_top_frame(self):\n        popped = self.__stack.pop()\n        if self.__stack:\n            self.__stack[-1].process_subframe(popped)",
    "docstring": "Pops the top frame off the frame stack."
  },
  {
    "code": "def merge_conf(to_hash, other_hash, path=[]):\n    \"merges other_hash into to_hash\"\n    for key in other_hash:\n        if (key in to_hash and isinstance(to_hash[key], dict)\n                and isinstance(other_hash[key], dict)):\n            merge_conf(to_hash[key], other_hash[key], path + [str(key)])\n        else:\n            to_hash[key] = other_hash[key]\n    return to_hash",
    "docstring": "merges other_hash into to_hash"
  },
  {
    "code": "def fetch_tweets(account_file, outfile, limit):\n    print('fetching tweets for accounts in', account_file)\n    outf = io.open(outfile, 'wt')\n    for screen_name in iter_lines(account_file):\n        print('\\nFetching tweets for %s' % screen_name)\n        for tweet in twutil.collect.tweets_for_user(screen_name, limit):\n            tweet['user']['screen_name'] = screen_name\n            outf.write('%s\\n' % json.dumps(tweet, ensure_ascii=False))\n            outf.flush()",
    "docstring": "Fetch up to limit tweets for each account in account_file and write to\n    outfile."
  },
  {
    "code": "def max(self):\n        return int(self._max) if not np.isinf(self._max) else self._max",
    "docstring": "Returns the maximum value of the domain.\n\n        :rtype: `float` or `np.inf`"
  },
  {
    "code": "def validate(self):\n        if self.required_languages:\n            if isinstance(self.required_languages, (tuple, list)):\n                self._check_languages(self.required_languages)\n            else:\n                self._check_languages(self.required_languages.keys(), extra=('default',))\n                for fieldnames in self.required_languages.values():\n                    if any(f not in self.fields for f in fieldnames):\n                        raise ImproperlyConfigured(\n                            'Fieldname in required_languages which is not in fields option.')",
    "docstring": "Perform options validation."
  },
  {
    "code": "def iter_items(cls, repo, rev, paths='', **kwargs):\n        if 'pretty' in kwargs:\n            raise ValueError(\"--pretty cannot be used as parsing expects single sha's only\")\n        args = ['--']\n        if paths:\n            args.extend((paths, ))\n        proc = repo.git.rev_list(rev, args, as_process=True, **kwargs)\n        return cls._iter_from_process_or_stream(repo, proc)",
    "docstring": "Find all commits matching the given criteria.\n\n        :param repo: is the Repo\n        :param rev: revision specifier, see git-rev-parse for viable options\n        :param paths:\n            is an optional path or list of paths, if set only Commits that include the path\n            or paths will be considered\n        :param kwargs:\n            optional keyword arguments to git rev-list where\n            ``max_count`` is the maximum number of commits to fetch\n            ``skip`` is the number of commits to skip\n            ``since`` all commits since i.e. '1970-01-01'\n        :return: iterator yielding Commit items"
  },
  {
    "code": "def count_series(y_true, y_score, countna=False):\n    y_true, y_score = to_float(y_true, y_score)\n    top = _argsort(y_score)\n    if not countna:\n        a = (~np.isnan(y_true[top])).cumsum()\n    else:\n        a = range(1, len(y_true)+1)\n    return pd.Series(a, index=range(1, len(a)+1))",
    "docstring": "Returns series whose i-th entry is the number of examples in the top i"
  },
  {
    "code": "def insert(self, table_name, record, attr_names=None):\n        self.insert_many(table_name, records=[record], attr_names=attr_names)",
    "docstring": "Send an INSERT query to the database.\n\n        :param str table_name: Table name of executing the query.\n        :param record: Record to be inserted.\n        :type record: |dict|/|namedtuple|/|list|/|tuple|\n        :raises IOError: |raises_write_permission|\n        :raises simplesqlite.NullDatabaseConnectionError:\n            |raises_check_connection|\n        :raises simplesqlite.OperationalError: |raises_operational_error|\n\n        :Example:\n            :ref:`example-insert-records`"
  },
  {
    "code": "def intervals_to_durations(intervals):\n    validate_intervals(intervals)\n    return np.abs(np.diff(intervals, axis=-1)).flatten()",
    "docstring": "Converts an array of n intervals to their n durations.\n\n    Parameters\n    ----------\n    intervals : np.ndarray, shape=(n, 2)\n        An array of time intervals, as returned by\n        :func:`mir_eval.io.load_intervals()`.\n        The ``i`` th interval spans time ``intervals[i, 0]`` to\n        ``intervals[i, 1]``.\n\n    Returns\n    -------\n    durations : np.ndarray, shape=(n,)\n        Array of the duration of each interval."
  },
  {
    "code": "def light(self):\n        sun = self.chart.getObject(const.SUN)\n        return light(self.obj, sun)",
    "docstring": "Returns if object is augmenting or diminishing its \n        light."
  },
  {
    "code": "def run_parallel(self, para_func):\n        if self.timer:\n            start_timer = time.time()\n        with mp.Pool(self.num_processors) as pool:\n            print('start pool with {} processors: {} total processes.\\n'.format(\n                    self.num_processors, len(self.args)))\n            results = [pool.apply_async(para_func, arg) for arg in self.args]\n            out = [r.get() for r in results]\n            out = {key: np.concatenate([out_i[key] for out_i in out]) for key in out[0].keys()}\n        if self.timer:\n            print(\"SNR calculation time:\", time.time()-start_timer)\n        return out",
    "docstring": "Run parallel calulation\n\n        This will run the parallel calculation on self.num_processors.\n\n        Args:\n            para_func (obj): Function object to be used in parallel.\n\n        Returns:\n            (dict): Dictionary with parallel results."
  },
  {
    "code": "def get_hosts(self, group=None):\n        hostlist = []\n        if group:\n            groupobj = self.inventory.groups.get(group)\n            if not groupobj:\n                print \"Group [%s] not found in inventory\" % group\n                return None\n            groupdict = {}\n            groupdict['hostlist'] = []\n            for host in groupobj.get_hosts():\n                groupdict['hostlist'].append(host.name)\n            hostlist.append(groupdict)\n        else:\n            for group in self.inventory.groups:\n                groupdict = {}\n                groupdict['group'] = group\n                groupdict['hostlist'] = []\n                groupobj = self.inventory.groups.get(group)\n                for host in groupobj.get_hosts():\n                    groupdict['hostlist'].append(host.name)\n                hostlist.append(groupdict)\n        return hostlist",
    "docstring": "Get the hosts"
  },
  {
    "code": "def split_ref_from_uri(uri):\n    if not isinstance(uri, six.string_types):\n        raise TypeError(\"Expected a string, received {0!r}\".format(uri))\n    parsed = urllib_parse.urlparse(uri)\n    path = parsed.path\n    ref = None\n    if \"@\" in path:\n        path, _, ref = path.rpartition(\"@\")\n    parsed = parsed._replace(path=path)\n    return (urllib_parse.urlunparse(parsed), ref)",
    "docstring": "Given a path or URI, check for a ref and split it from the path if it is present,\n    returning a tuple of the original input and the ref or None.\n\n    :param AnyStr uri: The path or URI to split\n    :returns: A 2-tuple of the path or URI and the ref\n    :rtype: Tuple[AnyStr, Optional[AnyStr]]"
  },
  {
    "code": "def zrem(self, key, *members):\n        return self._execute([b'ZREM', key] + list(members))",
    "docstring": "Removes the specified members from the sorted set stored at key.\n         Non existing members are ignored.\n\n        An error is returned when key exists and does not hold a sorted set.\n\n        .. note::\n\n           **Time complexity**: ``O(M*log(N))`` with ``N`` being the number of\n           elements in the sorted set and ``M`` the number of elements to be\n           removed.\n\n        :param key: The key of the sorted set\n        :type key: :class:`str`, :class:`bytes`\n        :param members: One or more member values to remove\n        :type members: :class:`str`, :class:`bytes`\n        :rtype: int\n        :raises: :exc:`~tredis.exceptions.RedisError`"
  },
  {
    "code": "def on_epoch_end(self, epoch, smooth_loss, last_metrics, **kwargs):\n        \"Logs training loss, validation loss and custom metrics & log prediction samples & save model\"\n        if self.save_model:\n            current = self.get_monitor_value()\n            if current is not None and self.operator(current, self.best):\n                print(\n                    f'Better model found at epoch {epoch} with {self.monitor} value: {current}.'\n                )\n                self.best = current\n                with self.model_path.open('wb') as model_file:\n                    self.learn.save(model_file)\n        if self.show_results:\n            self.learn.show_results()\n            wandb.log({\"Prediction Samples\": plt}, commit=False)\n        logs = {\n            name: stat\n            for name, stat in list(\n                zip(self.learn.recorder.names, [epoch, smooth_loss] +\n                    last_metrics))[1:]\n        }\n        wandb.log(logs)\n        if self.show_results:\n            plt.close('all')",
    "docstring": "Logs training loss, validation loss and custom metrics & log prediction samples & save model"
  },
  {
    "code": "def _write_info(self):\n        self.write(destination=self.output_directory,\n                   filename=\"vspk/SdkInfo.cs\",\n                   template_name=\"sdkinfo.cs.tpl\",\n                   version=self.api_version,\n                   product_accronym=self._product_accronym,\n                   class_prefix=self._class_prefix,\n                   root_api=self.api_root,\n                   api_prefix=self.api_prefix,\n                   product_name=self._product_name,\n                   name=self._name,\n                   header=self.header_content,\n                   version_string=self._api_version_string,\n                   package_name=self._package_name)",
    "docstring": "Write API Info file"
  },
  {
    "code": "def load_calibration_template(self, template):\n        self.tone_calibrator.stimulus.clearComponents()\n        self.tone_calibrator.stimulus.loadFromTemplate(template['tone_doc'], self.tone_calibrator.stimulus)\n        comp_doc = template['noise_doc']\n        for state, calstim in zip(comp_doc, self.bs_calibrator.get_stims()):\n            calstim.loadState(state)",
    "docstring": "Reloads calibration settings from saved template doc\n\n        :param template: Values for calibration stimuli (see calibration_template function)\n        :type template: dict"
  },
  {
    "code": "def __check_focus(self, event):\n        changed = False\n        if not self._curfocus:\n            changed = True\n        elif self._curfocus != self.focus():\n            self.__clear_inplace_widgets()\n            changed = True\n        newfocus = self.focus()\n        if changed:\n            if newfocus:\n                self._curfocus= newfocus\n                self.__focus(newfocus)\n            self.__updateWnds()",
    "docstring": "Checks if the focus has changed"
  },
  {
    "code": "def _calc_resp(password_hash, server_challenge):\n        password_hash += b'\\x00' * (21 - len(password_hash))\n        res = b''\n        dobj = DES(DES.key56_to_key64(password_hash[0:7]))\n        res = res + dobj.encrypt(server_challenge[0:8])\n        dobj = DES(DES.key56_to_key64(password_hash[7:14]))\n        res = res + dobj.encrypt(server_challenge[0:8])\n        dobj = DES(DES.key56_to_key64(password_hash[14:21]))\n        res = res + dobj.encrypt(server_challenge[0:8])\n        return res",
    "docstring": "Generate the LM response given a 16-byte password hash and the\n        challenge from the CHALLENGE_MESSAGE\n\n        :param password_hash: A 16-byte password hash\n        :param server_challenge: A random 8-byte response generated by the\n            server in the CHALLENGE_MESSAGE\n        :return res: A 24-byte buffer to contain the LM response upon return"
  },
  {
    "code": "def image(self, raw_url, title='', alt=''):\n        if self.check_url(raw_url, is_image_src=True):\n            url = self.rewrite_url(raw_url, is_image_src=True)\n            maybe_alt = ' alt=\"%s\"' % escape_html(alt) if alt else ''\n            maybe_title = ' title=\"%s\"' % escape_html(title) if title else ''\n            url = escape_html(url)\n            return '<img src=\"%s\"%s%s />' % (url, maybe_alt, maybe_title)\n        else:\n            return escape_html(\"![%s](%s)\" % (alt, raw_url))",
    "docstring": "Filters the ``src`` attribute of an image.\n\n        Note that filtering the source URL of an ``<img>`` tag is only a very\n        basic protection, and it's mostly useless in modern browsers (they block\n        JavaScript in there by default). An example of attack that filtering\n        does not thwart is phishing based on HTTP Auth, see `this issue\n        <https://github.com/liberapay/liberapay.com/issues/504>`_ for details.\n\n        To mitigate this issue you should only allow images from trusted services,\n        for example your own image store, or a proxy (see :meth:`rewrite_url`)."
  },
  {
    "code": "def line_nbr_from_position(self, y_pos):\n        editor = self._editor\n        height = editor.fontMetrics().height()\n        for top, line, block in editor.visible_blocks:\n            if top <= y_pos <= top + height:\n                return line\n        return -1",
    "docstring": "Returns the line number from the y_pos.\n\n        :param y_pos: Y pos in the editor\n        :return: Line number (0 based), -1 if out of range"
  },
  {
    "code": "def ext_pillar(minion_id,\n               pillar,\n               *args,\n               **kwargs):\n    return POSTGRESExtPillar().fetch(minion_id, pillar, *args, **kwargs)",
    "docstring": "Execute queries against POSTGRES, merge and return as a dict"
  },
  {
    "code": "def get_wrapped_instance(self, instance=None):\n        if instance._meta.label_lower not in self.registry:\n            raise ModelNotRegistered(f\"{repr(instance)} is not registered with {self}.\")\n        wrapper_cls = self.registry.get(instance._meta.label_lower) or self.wrapper_cls\n        if wrapper_cls:\n            return wrapper_cls(instance)\n        return instance",
    "docstring": "Returns a wrapped model instance."
  },
  {
    "code": "def unload(self, ):\n        assert self.status() == self.LOADED,\\\n            \"Cannot unload if there is no loaded reference. \\\nUse delete if you want to get rid of a reference or import.\"\n        childrentodelete = self.get_children_to_delete()\n        if childrentodelete:\n            raise ReftrackIntegrityError(\"Cannot unload because children of the reference would become orphans.\", childrentodelete)\n        self.get_refobjinter().unload(self._refobj)\n        self.set_status(self.UNLOADED)\n        self.throw_children_away()\n        self.update_restrictions()\n        self.emit_data_changed()",
    "docstring": "If the reference is loaded, unload it.\n\n        .. Note:: Do not confuse this with a delete. This means, that the reference stays in the\n                  scene, but no data is read from the reference.\n\n        This will call :meth:`RefobjInterface.unload` and set the status to :data:`Reftrack.UNLOADED`.\n        It will also throw away all children :class:`Reftrack`. They will return after :meth:`Reftrack.load`.\n\n        The problem might be that children depend on their parent, but will not get unloaded.\n        E.g. you imported a child. It will stay in the scene after the unload and become an orphan.\n        In this case an error is raised. It is not possible to unload such an entity.\n        The orphan might get its parents back after you call load, but it will introduce bugs when\n        wrapping children of unloaded entities. So we simply disable the feature in that case and raise\n        an :class:`IntegrityError`\n\n        :returns: None\n        :rtype: None\n        :raises: :class:`ReftrackIntegrityError`"
  },
  {
    "code": "def read_with_columns(func):\n    def wrapper(*args, **kwargs):\n        columns = kwargs.pop(\"columns\", None)\n        tab = func(*args, **kwargs)\n        if columns is None:\n            return tab\n        return tab[columns]\n    return _safe_wraps(wrapper, func)",
    "docstring": "Decorate a Table read method to use the ``columns`` keyword"
  },
  {
    "code": "def _build_params(self):\n        d = OrderedDict()\n        d['purpose_codes'] = 'ADULT'\n        d['queryDate'] = self._valid_date\n        d['from_station'] = self._from_station_telecode\n        d['to_station'] = self._to_station_telecode\n        return d",
    "docstring": "Have no idea why wrong params order can't get data.\n        So, use `OrderedDict` here."
  },
  {
    "code": "def _mark_candidate_indexes(lines, candidate):\n    markers = list('c' * len(candidate))\n    for i, line_idx in reversed(list(enumerate(candidate))):\n        if len(lines[line_idx].strip()) > TOO_LONG_SIGNATURE_LINE:\n            markers[i] = 'l'\n        else:\n            line = lines[line_idx].strip()\n            if line.startswith('-') and line.strip(\"-\"):\n                markers[i] = 'd'\n    return \"\".join(markers)",
    "docstring": "Mark candidate indexes with markers\n\n    Markers:\n\n    * c - line that could be a signature line\n    * l - long line\n    * d - line that starts with dashes but has other chars as well\n\n    >>> _mark_candidate_lines(['Some text', '', '-', 'Bob'], [0, 2, 3])\n    'cdc'"
  },
  {
    "code": "def get_desktop_size(self):\n        _ptr = ffi.new('SDL_DisplayMode *')\n        check_int_err(lib.SDL_GetDesktopDisplayMode(self._index, _ptr))\n        return (_ptr.w, _ptr.h)",
    "docstring": "Get the size of the desktop display"
  },
  {
    "code": "def Henry_H_at_T(T, H, Tderiv, T0=None, units=None, backend=None):\n    be = get_backend(backend)\n    if units is None:\n        K = 1\n    else:\n        K = units.Kelvin\n    if T0 is None:\n        T0 = 298.15*K\n    return H * be.exp(Tderiv*(1/T - 1/T0))",
    "docstring": "Evaluate Henry's constant H at temperature T\n\n    Parameters\n    ----------\n    T: float\n        Temperature (with units), assumed to be in Kelvin if ``units == None``\n    H: float\n        Henry's constant\n    Tderiv: float (optional)\n        dln(H)/d(1/T), assumed to be in Kelvin if ``units == None``.\n    T0: float\n        Reference temperature, assumed to be in Kelvin if ``units == None``\n        default: 298.15 K\n    units: object (optional)\n        object with attributes: kelvin (e.g. chempy.units.default_units)\n    backend : module (optional)\n        module with \"exp\", default: numpy, math"
  },
  {
    "code": "def alphafilter(request, queryset, template):\n    qs_filter = {}\n    for key in list(request.GET.keys()):\n        if '__istartswith' in key:\n            qs_filter[str(key)] = request.GET[key]\n            break\n    return render_to_response(\n        template,\n        {'objects': queryset.filter(**qs_filter),\n         'unfiltered_objects': queryset},\n        context_instance=RequestContext(request)\n    )",
    "docstring": "Render the template with the filtered queryset"
  },
  {
    "code": "def _resolve_time(value):\n  if value is None or isinstance(value,(int,long)):\n    return value\n  if NUMBER_TIME.match(value):\n    return long(value)\n  simple = SIMPLE_TIME.match(value)\n  if SIMPLE_TIME.match(value):\n    multiplier = long( simple.groups()[0] )\n    constant = SIMPLE_TIMES[ simple.groups()[1] ]\n    return multiplier * constant\n  if value in GREGORIAN_TIMES:\n    return value\n  raise ValueError('Unsupported time format %s'%value)",
    "docstring": "Resolve the time in seconds of a configuration value."
  },
  {
    "code": "async def list_keys(request: web.Request) -> web.Response:\n    keys_dir = CONFIG['wifi_keys_dir']\n    keys: List[Dict[str, str]] = []\n    for path in os.listdir(keys_dir):\n        full_path = os.path.join(keys_dir, path)\n        if os.path.isdir(full_path):\n            in_path = os.listdir(full_path)\n            if len(in_path) > 1:\n                log.warning(\"Garbage in key dir for key {}\".format(path))\n            keys.append(\n                {'uri': '/wifi/keys/{}'.format(path),\n                 'id': path,\n                 'name': os.path.basename(in_path[0])})\n        else:\n            log.warning(\"Garbage in wifi keys dir: {}\".format(full_path))\n    return web.json_response({'keys': keys}, status=200)",
    "docstring": "List the key files installed in the system.\n\n    This responds with a list of the same objects as key:\n\n    ```\n    GET /wifi/keys -> 200 OK\n    { keys: [\n         {\n          uri: '/wifi/keys/some-hex-digest',\n          id: 'some-hex-digest',\n          name: 'keyfile.pem'\n         },\n         ...\n       ]\n    }\n    ```"
  },
  {
    "code": "def save_file(filename, data, mk_parents=True):\n    parent = filename.parent\n    if not parent.exists() and mk_parents:\n        logger.debug(\"Creating directory: %s\", parent.as_posix())\n        parent.mkdir(parents=True)\n    with open(filename, mode=\"w\") as f:\n        logger.debug(\"Saving file: %s\", filename.as_posix())\n        f.write(data)",
    "docstring": "Save file to disk.\n\n    Paramaters\n    ----------\n    filename : pathlib.Path\n        Path to the file.\n    data : str\n        File contents.\n    mk_parents : bool, optional\n        If to create parent directories."
  },
  {
    "code": "def gen_send_stdout_url(ip, port):\n    return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, STDOUT_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID)",
    "docstring": "Generate send stdout url"
  },
  {
    "code": "def get_objective_banks_by_activity(self, activity_id):\n        mgr = self._get_provider_manager('LEARNING', local=True)\n        lookup_session = mgr.get_objective_bank_lookup_session(proxy=self._proxy)\n        return lookup_session.get_objective_banks_by_ids(\n            self.get_objective_bank_ids_by_activity(activity_id))",
    "docstring": "Gets the list of ``ObjectiveBanks`` mapped to a ``Activity``.\n\n        arg:    activity_id (osid.id.Id): ``Id`` of a ``Activity``\n        return: (osid.learning.ObjectiveBankList) - list of objective\n                bank ``Ids``\n        raise:  NotFound - ``activity_id`` is not found\n        raise:  NullArgument - ``activity_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def et(name, parallel, inputs, outputs, expression):\n    ExpressionTool = collections.namedtuple(\"ExpressionTool\", \"name inputs outputs expression parallel\")\n    return ExpressionTool(name, inputs, outputs, expression, parallel)",
    "docstring": "Represent an ExpressionTool that reorders inputs using javascript."
  },
  {
    "code": "def get_as_datadict(self):\n        return dict(type=self.__class__.__name__, tags=list(self.tags))",
    "docstring": "Get information about this object as a dictionary.  Used by WebSocket interface to pass some\n            relevant information to client applications."
  },
  {
    "code": "def update_with(self, update_fn, *maps):\n        evolver = self.evolver()\n        for map in maps:\n            for key, value in map.items():\n                evolver.set(key, update_fn(evolver[key], value) if key in evolver else value)\n        return evolver.persistent()",
    "docstring": "Return a new PMap with the items in Mappings maps inserted. If the same key is present in multiple\n        maps the values will be merged using merge_fn going from left to right.\n\n        >>> from operator import add\n        >>> m1 = m(a=1, b=2)\n        >>> m1.update_with(add, m(a=2))\n        pmap({'a': 3, 'b': 2})\n\n        The reverse behaviour of the regular merge. Keep the leftmost element instead of the rightmost.\n\n        >>> m1 = m(a=1)\n        >>> m1.update_with(lambda l, r: l, m(a=2), {'a':3})\n        pmap({'a': 1})"
  },
  {
    "code": "def _attend_process(self, proc, sleeptime):\n        try:\n            proc.wait(timeout=sleeptime)\n        except psutil.TimeoutExpired:\n            return True\n        return False",
    "docstring": "Waits on a process for a given time to see if it finishes, returns True\n        if it's still running after the given time or False as soon as it \n        returns.\n\n        :param psutil.Popen proc: Process object opened by psutil.Popen()\n        :param float sleeptime: Time to wait\n        :return bool: True if process is still running; otherwise false"
  },
  {
    "code": "def run_exitfuncs():\n    exc_info = None\n    for func, targs, kargs in _exithandlers:\n        try:\n            func(*targs, **kargs)\n        except SystemExit:\n            exc_info = sys.exc_info()\n        except:\n            exc_info = sys.exc_info()\n    if exc_info is not None:\n        six.reraise(exc_info[0], exc_info[1], exc_info[2])",
    "docstring": "Function that behaves exactly like Python's atexit, but runs atexit functions\n    in the order in which they were registered, not reversed."
  },
  {
    "code": "def configurationChangeAcknowledge():\n    a = TpPd(pd=0x6)\n    b = MessageType(mesType=0x31)\n    c = MobileId()\n    packet = a / b / c\n    return packet",
    "docstring": "CONFIGURATION CHANGE ACKNOWLEDGE Section 9.1.12c"
  },
  {
    "code": "def create_dir(path):\n    try:\n        os.makedirs(path, exist_ok=True)\n    except Exception as err:\n        print(err)\n        return False\n    if os.path.exists(path):\n        return True\n    else:\n        return False",
    "docstring": "Create directory specified by `path` if it doesn't already exist.\n\n    Parameters\n    ----------\n    path : str\n        path to directory\n\n    Returns\n    -------\n    bool\n        True if `path` exists"
  },
  {
    "code": "def text_should_be_visible(self, text, exact_match=False, loglevel='INFO'):\r\n        if not self._element_find_by_text(text, exact_match).is_displayed():\r\n            self.log_source(loglevel)\r\n            raise AssertionError(\"Text '%s' should be visible \"\r\n                                 \"but did not\" % text)",
    "docstring": "Verifies that element identified with text is visible.\r\n\r\n        New in AppiumLibrary 1.4.5"
  },
  {
    "code": "def download_file(self, remote_filename, local_filename=None):\n        status = 'Failed'\n        if local_filename is None:\n            local_filename = remote_filename\n        if not self.args.force and os.access(local_filename, os.F_OK):\n            if not self._confirm_overwrite(local_filename):\n                self._print_results(local_filename, 'Skipped')\n                return\n        url = '{}{}'.format(self.base_url, remote_filename)\n        r = requests.get(url, allow_redirects=True)\n        if r.ok:\n            open(local_filename, 'wb').write(r.content)\n            status = 'Success'\n        else:\n            self.handle_error('Error requesting: {}'.format(url), False)\n        self._print_results(local_filename, status)",
    "docstring": "Download file from github.\n\n        Args:\n            remote_filename (str): The name of the file as defined in git repository.\n            local_filename (str, optional): Defaults to None. The name of the file as it should be\n                be written to local filesystem."
  },
  {
    "code": "def register_blueprint(self, blueprint):\n        if blueprint not in self._blueprint_known:\n            self.app.register_blueprint(blueprint)\n            self._blueprint_known.add(blueprint)",
    "docstring": "Register given blueprint on curren app.\n\n        This method is provided for using inside plugin's module-level\n        :func:`register_plugin` functions.\n\n        :param blueprint: blueprint object with plugin endpoints\n        :type blueprint: flask.Blueprint"
  },
  {
    "code": "def run_interactive_command(command, env=None, **kwargs):\n    command_result = _run_command(\n        command=command,\n        out_pipe=sys.stdout,\n        err_pipe=sys.stderr,\n        stdin=sys.stdin,\n        env=env,\n        **kwargs\n    )\n    return command_result",
    "docstring": "Runs a command interactively, reusing the current stdin, stdout and stderr\n\n    Args:\n        command(list of str): args of the command to execute, including the\n            command itself as command[0] as `['ls', '-l']`\n        env(dict of str:str): If set, will use the given dict as env for the\n            subprocess\n        **kwargs: Any other keyword args passed will be passed to the\n            :ref:subprocess.Popen call\n\n    Returns:\n        lago.utils.CommandStatus: result of the interactive execution"
  },
  {
    "code": "def confirm(prompt, default=None, show_default=True, abort=False, input_function=None):\n\tvalid = {\n\t\t'yes': True,\n\t\t'y': True,\n\t\t'no': False,\n\t\t'n': False\n\t}\n\tinput_function = get_input_fn(input_function)\n\tif default not in ['yes', 'no', None]:\n\t\tdefault = None\n\tif show_default:\n\t\tprompt = '{} [{}/{}]: '.format(prompt,\n\t\t\t\t'Y' if default == 'yes' else 'y',\n\t\t\t\t'N' if default == 'no' else 'n')\n\twhile True:\n\t\tchoice = prompt_fn(input_function, prompt, default).lower()\n\t\tif choice in valid:\n\t\t\tif valid[choice] == False and abort:\n\t\t\t\traise_abort()\n\t\t\treturn valid[choice]\n\t\telse:\n\t\t\techo('Please respond with \"yes\" or \"no\" (or \"y\" or \"n\").')",
    "docstring": "Prompts for confirmation from the user."
  },
  {
    "code": "def process_cbn_jgif_file(file_name):\n    with open(file_name, 'r') as jgf:\n        return process_pybel_graph(pybel.from_cbn_jgif(json.load(jgf)))",
    "docstring": "Return a PybelProcessor by processing a CBN JGIF JSON file.\n\n    Parameters\n    ----------\n    file_name : str\n        The path to a CBN JGIF JSON file.\n\n    Returns\n    -------\n    bp : PybelProcessor\n        A PybelProcessor object which contains INDRA Statements in\n        bp.statements."
  },
  {
    "code": "def domain_create(self, domain, master=True, **kwargs):\n        params = {\n            'domain': domain,\n            'type': 'master' if master else 'slave',\n        }\n        params.update(kwargs)\n        result = self.post('/domains', data=params)\n        if not 'id' in result:\n            raise UnexpectedResponseError('Unexpected response when creating Domain!', json=result)\n        d = Domain(self, result['id'], result)\n        return d",
    "docstring": "Registers a new Domain on the acting user's account.  Make sure to point\n        your registrar to Linode's nameservers so that Linode's DNS manager will\n        correctly serve your domain.\n\n        :param domain: The domain to register to Linode's DNS manager.\n        :type domain: str\n        :param master: Whether this is a master (defaults to true)\n        :type master: bool\n\n        :returns: The new Domain object.\n        :rtype: Domain"
  },
  {
    "code": "def get_description(self):\n        return DisplayText(text='Agent representing ' + str(self.id_),\n                           language_type=DEFAULT_LANGUAGE_TYPE,\n                           script_type=DEFAULT_SCRIPT_TYPE,\n                           format_type=DEFAULT_FORMAT_TYPE,)",
    "docstring": "Creates a description"
  },
  {
    "code": "def _tscube_app(self, xmlfile):\n        xmlfile = self.get_model_path(xmlfile)\n        outfile = os.path.join(self.config['fileio']['workdir'],\n                               'tscube%s.fits' % (self.config['file_suffix']))\n        kw = dict(cmap=self.files['ccube'],\n                  expcube=self.files['ltcube'],\n                  bexpmap=self.files['bexpmap'],\n                  irfs=self.config['gtlike']['irfs'],\n                  evtype=self.config['selection']['evtype'],\n                  srcmdl=xmlfile,\n                  nxpix=self.npix, nypix=self.npix,\n                  binsz=self.config['binning']['binsz'],\n                  xref=float(self.roi.skydir.ra.deg),\n                  yref=float(self.roi.skydir.dec.deg),\n                  proj=self.config['binning']['proj'],\n                  stlevel=0,\n                  coordsys=self.config['binning']['coordsys'],\n                  outfile=outfile)\n        run_gtapp('gttscube', self.logger, kw)",
    "docstring": "Run gttscube as an application."
  },
  {
    "code": "def query(self, domain):\n        result = {}\n        try:\n            result = self.pdns.query(domain)\n        except:\n            self.error('Exception while querying passiveDNS. Check the domain format.')\n        clean_result = []\n        for ind, resultset in enumerate(result):\n            if resultset.get('time_first', None):\n                resultset['time_first'] = resultset.get('time_first').isoformat(' ')\n            if resultset.get('time_last', None):\n                resultset['time_last'] = resultset.get('time_last').isoformat(' ')\n            clean_result.append(resultset)\n        return clean_result",
    "docstring": "The actual query happens here. Time from queries is replaced with isoformat.\n\n        :param domain: The domain which should gets queried.\n        :type domain: str\n        :returns: List of dicts containing the search results.\n        :rtype: [list, dict]"
  },
  {
    "code": "def process_frames_face(self, frames):\n        detector = dlib.get_frontal_face_detector()\n        predictor = dlib.shape_predictor(self.face_predictor_path)\n        mouth_frames = self.get_frames_mouth(detector, predictor, frames)\n        self.face = np.array(frames)\n        self.mouth = np.array(mouth_frames)\n        if mouth_frames[0] is not None:\n            self.set_data(mouth_frames)",
    "docstring": "Preprocess from frames using face detector"
  },
  {
    "code": "def request_single(self, name, content={}):\n        resp = self.request(name, content)\n        for i in resp.values():\n            if type(i) == list:\n                return i[0]\n            elif type(i) == dict:\n                return i\n        return None",
    "docstring": "Simple wrapper arround request to extract a single response\n\n        :returns: the first tag in the response body"
  },
  {
    "code": "def users(self, query, page=1, per_page=10):\n        url = \"/search/users\"\n        data = self._search(url, query, page=page, per_page=per_page)\n        data[\"results\"] = UserModel.parse_list(data.get(\"results\"))\n        return data",
    "docstring": "Get a single page of user results for a query.\n\n        :param query [string]: Search terms.\n        :param page [integer]: Page number to retrieve. (Optional; default: 1)\n        :param per_page [integer]: Number of items per page. (Optional; default: 10)\n        :return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [User]}"
  },
  {
    "code": "def reverse_func(apps, schema_editor):\n    print(\"\\n\")\n    remove_count = 0\n    BackupRun = apps.get_model(\"backup_app\", \"BackupRun\")\n    backup_runs = BackupRun.objects.all()\n    for backup_run in backup_runs:\n        temp = OriginBackupRun(name=backup_run.name, backup_datetime=backup_run.backup_datetime)\n        config_path = temp.get_config_path()\n        try:\n            config_path.unlink()\n        except OSError as err:\n            print(\"ERROR removing config file: %s\" % err)\n        else:\n            remove_count += 1\n    print(\"%i config files removed.\\n\" % remove_count)",
    "docstring": "manage migrate backup_app 0003_auto_20160127_2002"
  },
  {
    "code": "def fetch_points_of_sales(self, ticket=None):\n        ticket = ticket or self.get_or_create_ticket('wsfe')\n        client = clients.get_client('wsfe', self.is_sandboxed)\n        response = client.service.FEParamGetPtosVenta(\n            serializers.serialize_ticket(ticket),\n        )\n        check_response(response)\n        results = []\n        for pos_data in response.ResultGet.PtoVenta:\n            results.append(PointOfSales.objects.update_or_create(\n                number=pos_data.Nro,\n                issuance_type=pos_data.EmisionTipo,\n                owner=self,\n                defaults={\n                    'blocked': pos_data.Bloqueado == 'N',\n                    'drop_date': parsers.parse_date(pos_data.FchBaja),\n                }\n            ))\n        return results",
    "docstring": "Fetch all point of sales objects.\n\n        Fetch all point of sales from the WS and store (or update) them\n        locally.\n\n        Returns a list of tuples with the format (pos, created,)."
  },
  {
    "code": "def _go_install(self, target, gopath, build_flags):\n    args = build_flags + [target.import_path]\n    result, go_cmd = self.go_dist.execute_go_cmd(\n      'install', gopath=gopath, args=args,\n      workunit_factory=self.context.new_workunit,\n      workunit_name='install {}'.format(target.import_path),\n      workunit_labels=[WorkUnitLabel.COMPILER])\n    if result != 0:\n      raise TaskError('{} failed with exit code {}'.format(go_cmd, result))",
    "docstring": "Create and execute a `go install` command."
  },
  {
    "code": "def _array_type_std_res(self, counts, total, colsum, rowsum):\n        if self.mr_dim_ind == 0:\n            total = total[:, np.newaxis]\n            rowsum = rowsum[:, np.newaxis]\n        expected_counts = rowsum * colsum / total\n        variance = rowsum * colsum * (total - rowsum) * (total - colsum) / total ** 3\n        return (counts - expected_counts) / np.sqrt(variance)",
    "docstring": "Return ndarray containing standard residuals for array values.\n\n        The shape of the return value is the same as that of *counts*.\n        Array variables require special processing because of the\n        underlying math. Essentially, it boils down to the fact that the\n        variable dimensions are mutually independent, and standard residuals\n        are calculated for each of them separately, and then stacked together\n        in the resulting array."
  },
  {
    "code": "def connect(self, format, *args):\n        return lib.zsock_connect(self._as_parameter_, format, *args)",
    "docstring": "Connect a socket to a formatted endpoint\nReturns 0 if OK, -1 if the endpoint was invalid."
  },
  {
    "code": "def hex_to_hsv(color):\n    color = normalize(color)\n    color = color[1:]\n    color = (int(color[0:2], base=16) / 255.0, int(color[2:4],\n                                                   base=16) / 255.0, int(color[4:6], base=16) / 255.0)\n    return colorsys.rgb_to_hsv(*color)",
    "docstring": "Converts from hex to hsv\n\n    Parameters:\n    -----------\n            color : string\n                    Color representation on color\n\n    Example:\n            hex_to_hsv('#ff9933')"
  },
  {
    "code": "def serialize(self, buf, offset):\n        fields = [ofproto.oxm_from_user(k, uv) for (k, uv)\n                  in self._fields2]\n        hdr_pack_str = '!HH'\n        field_offset = offset + struct.calcsize(hdr_pack_str)\n        for (n, value, mask) in fields:\n            field_offset += ofproto.oxm_serialize(n, value, mask, buf,\n                                                  field_offset)\n        length = field_offset - offset\n        msg_pack_into(hdr_pack_str, buf, offset, ofproto.OFPMT_OXM, length)\n        self.length = length\n        pad_len = utils.round_up(length, 8) - length\n        msg_pack_into(\"%dx\" % pad_len, buf, field_offset)\n        return length + pad_len",
    "docstring": "Outputs the expression of the wire protocol of the flow match into\n        the buf.\n        Returns the output length."
  },
  {
    "code": "def read_excitation_energies(self):\n        transitions = list()\n        with zopen(self.filename, \"r\") as f:\n            line = f.readline()\n            td = False\n            while line != \"\":\n                if re.search(r\"^\\sExcitation energies and oscillator strengths:\", line):\n                    td = True\n                if td:\n                    if re.search(r\"^\\sExcited State\\s*\\d\", line):\n                        val = [float(v) for v in float_patt.findall(line)]\n                        transitions.append(tuple(val[0:3]))\n                line = f.readline()\n        return transitions",
    "docstring": "Read a excitation energies after a TD-DFT calculation.\n\n        Returns:\n\n            A list: A list of tuple for each transition such as\n                    [(energie (eV), lambda (nm), oscillatory strength), ... ]"
  },
  {
    "code": "def format_datetime(d: PotentialDatetimeType,\n                    fmt: str,\n                    default: str = None) -> Optional[str]:\n    d = coerce_to_pendulum(d)\n    if d is None:\n        return default\n    return d.strftime(fmt)",
    "docstring": "Format a datetime with a ``strftime`` format specification string, or\n    return ``default`` if the input is ``None``."
  },
  {
    "code": "def _setup_transport(self):\n        if HAVE_PY26_SSL:\n            if hasattr(self, 'sslopts'):\n                self.sslobj = ssl.wrap_socket(self.sock, **self.sslopts)\n            else:\n                self.sslobj = ssl.wrap_socket(self.sock)\n            self.sslobj.do_handshake()\n        else:\n            self.sslobj = socket.ssl(self.sock)",
    "docstring": "Wrap the socket in an SSL object, either the\n        new Python 2.6 version, or the older Python 2.5 and\n        lower version."
  },
  {
    "code": "def new(self, filename=None):\r\n        path = (self.exec_path,)\r\n        if self.exec_path.filetype() in ('py', 'pyw', 'pyz', self.FTYPE):\r\n            p = find_executable(\"python\")\r\n            path = (p, 'python') + path\r\n        else:\r\n            path += (self.exec_path,)\r\n        if filename:\r\n            path += ('-o', filename)\r\n        os.spawnl(os.P_NOWAIT, *path)",
    "docstring": "start a session an independent process"
  },
  {
    "code": "def read_lease(self, lease_id):\n        params = {\n            'lease_id': lease_id\n        }\n        api_path = '/v1/sys/leases/lookup'\n        response = self._adapter.put(\n            url=api_path,\n            json=params\n        )\n        return response.json()",
    "docstring": "Retrieve lease metadata.\n\n        Supported methods:\n            PUT: /sys/leases/lookup. Produces: 200 application/json\n\n        :param lease_id: the ID of the lease to lookup.\n        :type lease_id: str | unicode\n        :return: Parsed JSON response from the leases PUT request\n        :rtype: dict."
  },
  {
    "code": "def maybeparens(lparen, item, rparen):\n    return item | lparen.suppress() + item + rparen.suppress()",
    "docstring": "Wrap an item in optional parentheses, only applying them if necessary."
  },
  {
    "code": "def get_search_fields(self):\n        search_fields = self._search_fields.copy()\n        if not search_fields:\n            for cls in reversed(self.model.__mro__):\n                super_fields = getattr(cls, \"search_fields\", {})\n                search_fields.update(search_fields_to_dict(super_fields))\n        if not search_fields:\n            search_fields = []\n            for f in self.model._meta.fields:\n                if isinstance(f, (CharField, TextField)):\n                    search_fields.append(f.name)\n            search_fields = search_fields_to_dict(search_fields)\n        return search_fields",
    "docstring": "Returns the search field names mapped to weights as a dict.\n        Used in ``get_queryset`` below to tell ``SearchableQuerySet``\n        which search fields to use. Also used by ``DisplayableAdmin``\n        to populate Django admin's ``search_fields`` attribute.\n\n        Search fields can be populated via\n        ``SearchableManager.__init__``, which then get stored in\n        ``SearchableManager._search_fields``, which serves as an\n        approach for defining an explicit set of fields to be used.\n\n        Alternatively and more commonly, ``search_fields`` can be\n        defined on models themselves. In this case, we look at the\n        model and all its base classes, and build up the search\n        fields from all of those, so the search fields are implicitly\n        built up from the inheritence chain.\n\n        Finally if no search fields have been defined at all, we\n        fall back to any fields that are ``CharField`` or ``TextField``\n        instances."
  },
  {
    "code": "def extract_new(cls) -> DevicesTypeUnbound:\n        devices = cls.get_handlerclass()(*_selection[cls])\n        _selection[cls].clear()\n        return devices",
    "docstring": "Gather all \"new\" |Node| or |Element| objects.\n\n        See the main documentation on module |devicetools| for further\n        information."
  },
  {
    "code": "def reset_component(self, component):\n\t\tif isinstance(component, str) is True:\n\t\t\tcomponent = WURI.Component(component)\n\t\tself.__components[component] = None",
    "docstring": "Unset component in this URI\n\n\t\t:param component: component name (or component type) to reset\n\n\t\t:return: None"
  },
  {
    "code": "def add_histogram_summary(self, x, tag=None):\n    if not self.summary_collections:\n      return\n    with self.g.as_default():\n      tag = tag or _tag_for(x.name)\n      summary = tf.summary.histogram(\n          tag, x, collections=self.summary_collections)\n      return summary",
    "docstring": "Add a summary operation to visualize the histogram of x's values."
  },
  {
    "code": "def set_baselines(self):\n        if self.style.xbaseline:\n            if self.style.orient in (\"up\", \"down\"):\n                self.coords.coords[:, 0] += self.style.xbaseline\n                self.coords.verts[:, 0] += self.style.xbaseline                \n            else:\n                self.coords.coords[:, 1] += self.style.xbaseline\n                self.coords.verts[:, 1] += self.style.xbaseline",
    "docstring": "Modify coords to shift tree position for x,y baseline arguments. This\n        is useful for arrangeing trees onto a Canvas with other plots, but \n        still sharing a common cartesian axes coordinates."
  },
  {
    "code": "def deliver_tx(self, raw_transaction):\n        self.abort_if_abci_chain_is_not_synced()\n        logger.debug('deliver_tx: %s', raw_transaction)\n        transaction = self.bigchaindb.is_valid_transaction(\n            decode_transaction(raw_transaction), self.block_transactions)\n        if not transaction:\n            logger.debug('deliver_tx: INVALID')\n            return ResponseDeliverTx(code=CodeTypeError)\n        else:\n            logger.debug('storing tx')\n            self.block_txn_ids.append(transaction.id)\n            self.block_transactions.append(transaction)\n            return ResponseDeliverTx(code=CodeTypeOk)",
    "docstring": "Validate the transaction before mutating the state.\n\n        Args:\n            raw_tx: a raw string (in bytes) transaction."
  },
  {
    "code": "def solve_assignement(self, costs):\n        if costs is None or len(costs) == 0:\n            return dict()\n        n = costs.shape[0]\n        pairs = [(i, j) for i in range(0, n) for j in range(0, n) if costs[i, j] < invalid_match]\n        costs_list = [costs[i, j] for (i, j) in pairs]\n        assignment = lapjv.lapjv(list(zip(*pairs))[0], list(zip(*pairs))[1], costs_list)\n        indexes = enumerate(list(assignment[0]))\n        return dict([(row, col) for row, col in indexes])",
    "docstring": "Solves assignment problem using Hungarian implementation by Brian M. Clapper.\n\n        @param costs: square cost matrix\n\n        @return: assignment function\n\n        @rtype: int->int"
  },
  {
    "code": "def is_docker_reachable(self):\n        try:\n            self.docker_client.ping()\n            return True\n        except (docker.errors.APIError, requests.exceptions.ConnectionError):\n            LOG.debug(\"Docker is not reachable\", exc_info=True)\n            return False",
    "docstring": "Checks if Docker daemon is running. This is required for us to invoke the function locally\n\n        Returns\n        -------\n        bool\n            True, if Docker is available, False otherwise"
  },
  {
    "code": "def is_sock_ok(self, timeout_select):\n        self._socket_lock.acquire()\n        try:\n            ret = self._is_socket_ok(timeout_select)\n        finally:\n            self._socket_lock.release()\n        return ret",
    "docstring": "check if socket is OK"
  },
  {
    "code": "def set_meta(self, meta=None, **kwargs):\n        if meta is None:\n            meta = self.get_meta(**kwargs)\n        setattr(self, '_meta', meta)",
    "docstring": "Assign values to self.meta.\n        Meta is not returned"
  },
  {
    "code": "def calcRandW(self,aLvlNow,pLvlNow):\n        AaggPrev = np.mean(np.array(aLvlNow))/np.mean(pLvlNow)\n        AggregateK = np.mean(np.array(aLvlNow))\n        PermShkAggNow = self.PermShkAggHist[self.Shk_idx]\n        TranShkAggNow = self.TranShkAggHist[self.Shk_idx]\n        self.Shk_idx += 1\n        AggregateL = np.mean(pLvlNow)*PermShkAggNow\n        KtoLnow = AggregateK/AggregateL\n        self.KtoYnow = KtoLnow**(1.0-self.CapShare)\n        RfreeNow = self.Rfunc(KtoLnow/TranShkAggNow)\n        wRteNow  = self.wFunc(KtoLnow/TranShkAggNow)\n        MaggNow  = KtoLnow*RfreeNow + wRteNow*TranShkAggNow\n        self.KtoLnow = KtoLnow\n        AggVarsNow = CobbDouglasAggVars(MaggNow,AaggPrev,KtoLnow,RfreeNow,wRteNow,PermShkAggNow,TranShkAggNow)\n        return AggVarsNow",
    "docstring": "Calculates the interest factor and wage rate this period using each agent's\n        capital stock to get the aggregate capital ratio.\n\n        Parameters\n        ----------\n        aLvlNow : [np.array]\n            Agents' current end-of-period assets.  Elements of the list correspond\n            to types in the economy, entries within arrays to agents of that type.\n\n        Returns\n        -------\n        AggVarsNow : CobbDouglasAggVars\n            An object containing the aggregate variables for the upcoming period:\n            capital-to-labor ratio, interest factor, (normalized) wage rate,\n            aggregate permanent and transitory shocks."
  },
  {
    "code": "def _cleanup(self):\n        self.device = None\n        self.doc = None\n        self.parser = None\n        self.resmgr = None\n        self.interpreter = None",
    "docstring": "Frees lots of non-textual information, such as the fonts\n        and images and the objects that were needed to parse the\n        PDF."
  },
  {
    "code": "def _is_national_number_suffix_of_other(numobj1, numobj2):\n    nn1 = str(numobj1.national_number)\n    nn2 = str(numobj2.national_number)\n    return nn1.endswith(nn2) or nn2.endswith(nn1)",
    "docstring": "Returns true when one national number is the suffix of the other or both\n    are the same."
  },
  {
    "code": "def write(text, path):\n    with open(path, \"wb\") as f:\n        f.write(text.encode(\"utf-8\"))",
    "docstring": "Writer text to file with utf-8 encoding.\n\n    Usage::\n\n        >>> from angora.dataIO import textfile\n        or\n        >>> from angora.dataIO import *\n        >>> textfile.write(\"hello world!\", \"test.txt\")"
  },
  {
    "code": "def insertFromMimeData(self, data):\n        undoObj = UndoPaste(self, data, self.pasteCnt)\n        self.pasteCnt += 1\n        self.qteUndoStack.push(undoObj)",
    "docstring": "Paste the MIME data at the current cursor position.\n\n        This method also adds another undo-object to the undo-stack."
  },
  {
    "code": "def get_model_class(self):\n        try:\n            c = ContentType.objects.get(app_label=self.app, model=self.model)\n        except ContentType.DoesNotExist:\n            if django.VERSION >= (1, 7):\n                return apps.get_model(self.app, self.model)\n        else:\n            return c.model_class()",
    "docstring": "Returns model class"
  },
  {
    "code": "def from_json_file(cls, path):\n        with open(path) as jsf:\n            template_json = json.load(jsf)\n            return cls(template_json=template_json)",
    "docstring": "Return a template from a json allocated in a path.\n\n        :param path: string\n        :return: ServiceAgreementTemplate"
  },
  {
    "code": "def pad(self, pad_width, **kwargs):\n        kwargs.setdefault('mode', 'constant')\n        if isinstance(pad_width, int):\n            pad_width = (pad_width,)\n        new = numpy.pad(self, pad_width, **kwargs).view(type(self))\n        new.__metadata_finalize__(self)\n        new._unit = self.unit\n        new.x0 -= self.dx * pad_width[0]\n        return new",
    "docstring": "Pad this series to a new size\n\n        Parameters\n        ----------\n        pad_width : `int`, pair of `ints`\n            number of samples by which to pad each end of the array.\n            Single int to pad both ends by the same amount, or\n            (before, after) `tuple` to give uneven padding\n        **kwargs\n            see :meth:`numpy.pad` for kwarg documentation\n\n        Returns\n        -------\n        series : `Series`\n            the padded version of the input\n\n        See also\n        --------\n        numpy.pad\n            for details on the underlying functionality"
  },
  {
    "code": "def handle_pagination(self, page_num=None, page_size=None):\n        self._response_json = self.get_next_page(page_num=page_num, page_size=page_size)\n        self.update_attrs()\n        self.position = 0\n        self.values = self.process_page()",
    "docstring": "Handle retrieving and processing the next page of results."
  },
  {
    "code": "def _set_iroot_via_xroot(self, xroot):\n        if self._adata.shape[1] != xroot.size:\n            raise ValueError(\n                'The root vector you provided does not have the '\n                'correct dimension.')\n        dsqroot = 1e10\n        iroot = 0\n        for i in range(self._adata.shape[0]):\n            diff = self._adata.X[i, :] - xroot\n            dsq = diff.dot(diff)\n            if dsq < dsqroot:\n                dsqroot = dsq\n                iroot = i\n                if np.sqrt(dsqroot) < 1e-10: break\n        logg.msg('setting root index to', iroot, v=4)\n        if self.iroot is not None and iroot != self.iroot:\n            logg.warn('Changing index of iroot from {} to {}.'.format(self.iroot, iroot))\n        self.iroot = iroot",
    "docstring": "Determine the index of the root cell.\n\n        Given an expression vector, find the observation index that is closest\n        to this vector.\n\n        Parameters\n        ----------\n        xroot : np.ndarray\n            Vector that marks the root cell, the vector storing the initial\n            condition, only relevant for computing pseudotime."
  },
  {
    "code": "def create_baseline(tag=\"baseline\", config='root'):\n    return __salt__['snapper.create_snapshot'](config=config,\n                                               snapshot_type='single',\n                                               description=\"baseline snapshot\",\n                                               cleanup_algorithm=\"number\",\n                                               userdata={\"baseline_tag\": tag})",
    "docstring": "Creates a snapshot marked as baseline\n\n    tag\n        Tag name for the baseline\n\n    config\n        Configuration name.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' snapper.create_baseline\n        salt '*' snapper.create_baseline my_custom_baseline"
  },
  {
    "code": "def lookup_rest_method(self, orig_request):\n    method_name, method, params = self.config_manager.lookup_rest_method(\n        orig_request.path, orig_request.request_uri, orig_request.http_method)\n    orig_request.method_name = method_name\n    return method, params",
    "docstring": "Looks up and returns rest method for the currently-pending request.\n\n    Args:\n      orig_request: An ApiRequest, the original request from the user.\n\n    Returns:\n      A tuple of (method descriptor, parameters), or (None, None) if no method\n      was found for the current request."
  },
  {
    "code": "def schedule_tasks(self):\n        url = 'api/v6/releases/%d/schedule-tasks' % self.id\n        tasks = yield self.connection._get(url)\n        defer.returnValue(munchify(tasks))",
    "docstring": "Get all the tasks for a release.\n\n        :param release_id: int, release id number.\n        :returns: deferred that when fired returns a list of Munch (dict-like)\n                  objects representing all tasks."
  },
  {
    "code": "def _ParseFile(self, file_obj, line_parser):\n    lines = [\n        l.strip() for l in utils.ReadFileBytesAsUnicode(file_obj).splitlines()\n    ]\n    try:\n      for index, line in enumerate(lines):\n        if line:\n          line_parser(line)\n    except (IndexError, KeyError) as e:\n      raise parser.ParseError(\"Invalid file at line %d: %s\" % (index + 1, e))",
    "docstring": "Process a file line by line.\n\n    Args:\n      file_obj: The file to parse.\n      line_parser: The parser method used to process and store line content.\n\n    Raises:\n      parser.ParseError if the parser is unable to process the line."
  },
  {
    "code": "def replace_key(self, key, new_key):\n        heap = self._heap\n        position = self._position\n        if new_key in self:\n            raise KeyError('%s is already in the queue' % repr(new_key))\n        pos = position.pop(key)\n        position[new_key] = pos\n        heap[pos].key = new_key",
    "docstring": "Replace the key of an existing heap node in place. Raises ``KeyError``\n        if the key to replace does not exist or if the new key is already in\n        the pqdict."
  },
  {
    "code": "def add_profile_variants(self, profile_variants):\n        results = self.db.profile_variant.insert_many(profile_variants)\n        return results",
    "docstring": "Add several variants to the profile_variant collection in the\n        database\n\n        Args:\n\n            profile_variants(list(models.ProfileVariant))"
  },
  {
    "code": "def start(self, historics_id):\n        return self.request.post('start', data=dict(id=historics_id))",
    "docstring": "Start the historics job with the given ID.\n\n            Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsstart\n\n            :param historics_id: hash of the job to start\n            :type historics_id: str\n            :return: dict of REST API output with headers attached\n            :rtype: :class:`~datasift.request.DictResponse`\n            :raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`"
  },
  {
    "code": "def submitQuest(self):\n        form = pg.form(action=\"kitchen2.phtml\")\n        pg = form.submit()\n        if \"Woohoo\" in pg.content:\n            try:\n                self.prize = pg.find(text = \"The Chef waves his hands, and you may collect your prize...\").parent.parent.find_all(\"b\")[-1].text\n            except Exception:\n                logging.getLogger(\"neolib.quest\").exception(\"Failed to parse kitchen quest prize\", {'pg': pg})\n                raise parseException\n            return True\n        else:\n            logging.getLogger(\"neolib.quest\").info(\"Failed to complete kitchen quest\", {'pg': pg})\n            return False",
    "docstring": "Submits the active quest, returns result\n           \n        Returns\n           bool - True if successful, otherwise False"
  },
  {
    "code": "def execute_add(args, root_dir=None):\n    command = ' '.join(args['command'])\n    instruction = {\n        'command': command,\n        'path': os.getcwd()\n    }\n    print_command_factory('add')(instruction, root_dir)",
    "docstring": "Add a new command to the daemon queue.\n\n    Args:\n        args['command'] (list(str)): The actual programm call. Something like ['ls', '-a'] or ['ls -al']\n        root_dir (string): The path to the root directory the daemon is running in."
  },
  {
    "code": "def raw_sign(message, secret):\n    digest = hmac.new(secret, message, hashlib.sha256).digest()\n    return base64.b64encode(digest)",
    "docstring": "Sign a message."
  },
  {
    "code": "def key(username, key, all):\n    if username and username not in current_app.config['ADMIN_USERS']:\n        raise click.UsageError('User {} not an admin'.format(username))\n    def create_key(admin, key):\n        key = ApiKey(\n            user=admin,\n            key=key,\n            scopes=[Scope.admin, Scope.write, Scope.read],\n            text='Admin key created by alertad script',\n            expire_time=None\n        )\n        try:\n            db.get_db()\n            key = key.create()\n        except Exception as e:\n            click.echo('ERROR: {}'.format(e))\n        else:\n            click.echo('{} {}'.format(key.key, key.user))\n    if all:\n        for admin in current_app.config['ADMIN_USERS']:\n            create_key(admin, key)\n    elif username:\n        create_key(username, key)\n    else:\n        raise click.UsageError(\"Must set '--username' or use '--all'\")",
    "docstring": "Create an admin API key."
  },
  {
    "code": "def getDataAtRva(self, rva, size):\n        return self.getDataAtOffset(self.getOffsetFromRva(rva),  size)",
    "docstring": "Gets binary data at a given RVA.\n        \n        @type rva: int\n        @param rva: The RVA to get the data from.\n        \n        @type size: int\n        @param size: The size of the data to be obtained. \n        \n        @rtype: str\n        @return: The data obtained at the given RVA."
  },
  {
    "code": "def after_processing(eng, objects):\n        super(InvenioProcessingFactory, InvenioProcessingFactory)\\\n            .after_processing(eng, objects)\n        if eng.has_completed:\n            eng.save(WorkflowStatus.COMPLETED)\n        else:\n            eng.save(WorkflowStatus.HALTED)\n        db.session.commit()",
    "docstring": "Process to update status."
  },
  {
    "code": "def wrap_with_monitor(env, video_dir):\n  env = ExtendToEvenDimentions(env)\n  env = RenderObservations(env)\n  env = gym.wrappers.Monitor(env, video_dir, force=True,\n                             video_callable=lambda idx: True,\n                             write_upon_reset=True)\n  return env",
    "docstring": "Wrap environment with gym.Monitor.\n\n  Video recording provided by Monitor requires\n    1) both height and width of observation to be even numbers.\n    2) rendering of environment\n\n  Args:\n    env: environment.\n    video_dir: video directory.\n\n  Returns:\n    wrapped environment."
  },
  {
    "code": "def findExtNum(self, extname=None, extver=1):\n        extnum = None\n        extname = extname.upper()\n        if not self._isSimpleFits:\n            for ext in self._image:\n                if (hasattr(ext,'_extension') and 'IMAGE' in ext._extension and\n                    (ext.extname == extname) and (ext.extver == extver)):\n                    extnum = ext.extnum\n        else:\n            log.info(\"Image is simple fits\")\n        return extnum",
    "docstring": "Find the extension number of the give extname and extver."
  },
  {
    "code": "def set_gl_transform(self):\n        tangent = np.tan(self.fov_deg / 2.0 / 180.0 * np.pi)\n        vport_radius = self.near_plane * tangent\n        if self.vport_wd_px < self.vport_ht_px:\n            vport_wd = 2.0 * vport_radius\n            vport_ht = vport_wd * self.vport_ht_px / float(self.vport_wd_px)\n        else:\n            vport_ht = 2.0 * vport_radius\n            vport_wd = vport_ht * self.vport_wd_px / float(self.vport_ht_px)\n        gl.glFrustum(\n            -0.5 * vport_wd, 0.5 * vport_wd,\n            -0.5 * vport_ht, 0.5 * vport_ht,\n            self.near_plane, self.far_plane\n        )\n        M = Matrix4x4.look_at(self.position, self.target, self.up, False)\n        gl.glMultMatrixf(M.get())",
    "docstring": "This side effects the OpenGL context to set the view to match\n        the camera."
  },
  {
    "code": "def validate_settings(settings):\n    if not (settings.STORMPATH_ID and settings.STORMPATH_SECRET):\n        raise ImproperlyConfigured('Both STORMPATH_ID and STORMPATH_SECRET must be specified in settings.py.')\n    if not settings.STORMPATH_APPLICATION:\n        raise ImproperlyConfigured('STORMPATH_APPLICATION must be specified in settings.py.')",
    "docstring": "Ensure all user-supplied settings exist, or throw a useful error message.\n\n    :param obj settings: The Django settings object."
  },
  {
    "code": "def _generate_overview_note(pass_count, only_warning_count, error_count, total_count):\n    note_html = ['<div class=\"progress\">']\n    pbars = [\n        [ float(error_count), 'danger', 'had errors' ],\n        [ float(only_warning_count), 'warning', 'had warnings' ],\n        [ float(pass_count), 'success', 'passed' ]\n    ]\n    for b in pbars:\n        if b[0]:\n            note_html.append(\n                '<div class=\"progress-bar progress-bar-{pbcol}\" style=\"width: {pct}%\" data-toggle=\"tooltip\" title=\"{count} {sample} {txt}\">{count}</div>'. \\\n                format(\n                    pbcol = b[1],\n                    count = int(b[0]),\n                    pct = (b[0]/float(total_count))*100.0,\n                    txt = b[2],\n                    sample = 'samples' if b[0] > 1 else 'sample'\n                )\n            )\n    note_html.append('</div>')\n    return \"\\n\".join(note_html)",
    "docstring": "Generates and returns the HTML note that provides a summary of validation status."
  },
  {
    "code": "def _hashfile(self,filename,blocksize=65536):\n        logger.debug(\"Hashing file %s\"%(filename))\n        hasher=hashlib.sha256()\n        afile=open(filename,'rb')\n        buf=afile.read(blocksize)\n        while len(buf) > 0:\n            hasher.update(buf)\n            buf = afile.read(blocksize)\n        return hasher.hexdigest()",
    "docstring": "Hashes the file and returns hash"
  },
  {
    "code": "def load_from_string(self, content, container, **kwargs):\n        _not_implemented(self, content, container, **kwargs)",
    "docstring": "Load config from given string 'content'.\n\n        :param content: Config content string\n        :param container: callble to make a container object later\n        :param kwargs: optional keyword parameters to be sanitized :: dict\n\n        :return: Dict-like object holding config parameters"
  },
  {
    "code": "def _format_job_instance(job):\n    if not job:\n        ret = {'Error': 'Cannot contact returner or no job with this jid'}\n        return ret\n    ret = {'Function': job.get('fun', 'unknown-function'),\n           'Arguments': list(job.get('arg', [])),\n           'Target': job.get('tgt', 'unknown-target'),\n           'Target-type': job.get('tgt_type', 'list'),\n           'User': job.get('user', 'root')}\n    if 'metadata' in job:\n        ret['Metadata'] = job.get('metadata', {})\n    else:\n        if 'kwargs' in job:\n            if 'metadata' in job['kwargs']:\n                ret['Metadata'] = job['kwargs'].get('metadata', {})\n    if 'Minions' in job:\n        ret['Minions'] = job['Minions']\n    return ret",
    "docstring": "Helper to format a job instance"
  },
  {
    "code": "async def terminateInstance(self, *args, **kwargs):\n        return await self._makeApiCall(self.funcinfo[\"terminateInstance\"], *args, **kwargs)",
    "docstring": "Terminate an instance\n\n        Terminate an instance in a specified region\n\n        This method is ``experimental``"
  },
  {
    "code": "def iterconnections(self):\n        return itertools.chain(\n            self.secureConnectionCache.cachedConnections.itervalues(),\n            iter(self.subConnections),\n            (self.dispatcher or ()) and self.dispatcher.iterconnections())",
    "docstring": "Iterator of all connections associated with this service,\n        whether cached or not.  For testing purposes only."
  },
  {
    "code": "async def prover_search_credentials(wallet_handle: int,\n                                    query_json: str) -> (int, int):\n    logger = logging.getLogger(__name__)\n    logger.debug(\"prover_search_credentials: >>> wallet_handle: %r, query_json: %r\",\n                 wallet_handle,\n                 query_json)\n    if not hasattr(prover_search_credentials, \"cb\"):\n        logger.debug(\"prover_search_credentials: Creating callback\")\n        prover_search_credentials.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_int32, c_uint))\n    c_wallet_handle = c_int32(wallet_handle)\n    c_query_json = c_char_p(query_json.encode('utf-8'))\n    res = await do_call('indy_prover_search_credentials',\n                        c_wallet_handle,\n                        c_query_json,\n                        prover_search_credentials.cb)\n    logger.debug(\"prover_search_credentials: <<< res: %r\", res)\n    return res",
    "docstring": "Search for credentials stored in wallet.\n    Credentials can be filtered by tags created during saving of credential.\n\n    Instead of immediately returning of fetched credentials this call returns search_handle that can be used later\n    to fetch records by small batches (with prover_credentials_search_fetch_records).\n\n    :param wallet_handle: wallet handler (created by open_wallet).\n    :param query_json: wql style filter for credentials searching based on tags.\n        where wql query: indy-sdk/docs/design/011-wallet-query-language/README.md\n    :return:\n        search_handle: Search handle that can be used later to fetch records by small batches\n            (with prover_credentials_search_fetch_records)\n        total_count: Total count of records"
  },
  {
    "code": "def getobjectswithnode(idf, nodekeys, nodename):\n    keys = nodekeys\n    listofidfobjects = (idf.idfobjects[key.upper()] \n                for key in keys if idf.idfobjects[key.upper()])\n    idfobjects = [idfobj \n                    for idfobjs in listofidfobjects \n                        for idfobj in idfobjs]\n    objwithnodes = []\n    for obj in idfobjects:\n        values = obj.fieldvalues\n        fdnames = obj.fieldnames\n        for value, fdname in zip(values, fdnames):\n            if fdname.endswith('Node_Name'):\n                if value == nodename:\n                    objwithnodes.append(obj)\n                    break\n    return objwithnodes",
    "docstring": "return all objects that mention this node name"
  },
  {
    "code": "def alchemyencoder(obj):\n    if isinstance(obj, datetime.date):\n        return obj.isoformat()\n    elif isinstance(obj, decimal.Decimal):\n        return float(obj)",
    "docstring": "JSON encoder function for SQLAlchemy special classes."
  },
  {
    "code": "def exists(self, query, **args):\n        return bool(self.find(query, **args).limit(1).count())",
    "docstring": "Returns True if the search matches at least one document"
  },
  {
    "code": "def start_optimisation(self, rounds: int, max_angle: float,\n                           max_distance: float, temp: float=298.15,\n                           stop_when=None, verbose=None):\n        self._generate_initial_score()\n        self._mmc_loop(rounds, max_angle, max_distance, temp=temp,\n                       stop_when=stop_when, verbose=verbose)\n        return",
    "docstring": "Starts the loop fitting protocol.\n\n        Parameters\n        ----------\n        rounds : int\n            The number of Monte Carlo moves to be evaluated.\n        max_angle : float\n            The maximum variation in rotation that can moved per\n            step.\n        max_distance : float\n            The maximum distance the can be moved per step.\n        temp : float, optional\n            Temperature used during fitting process.\n        stop_when : float, optional\n            Stops fitting when energy is less than or equal to this value."
  },
  {
    "code": "def same(*values):\n    if not values:\n        return True\n    first, rest = values[0], values[1:]\n    return all(value == first for value in rest)",
    "docstring": "Check if all values in a sequence are equal.\n\n    Returns True on empty sequences.\n\n    Examples\n    --------\n    >>> same(1, 1, 1, 1)\n    True\n    >>> same(1, 2, 1)\n    False\n    >>> same()\n    True"
  },
  {
    "code": "def basemz(df):\n    d = np.array(df.columns)[df.values.argmax(axis=1)]\n    return Trace(d, df.index, name='basemz')",
    "docstring": "The mz of the most abundant ion."
  },
  {
    "code": "def sample_within_cc(self, cc_index, nsamples=1):\n        polygon = self.geometries[cc_index]['polygon']\n        samples = []\n        while len(samples) < nsamples:\n            point = PointSampler.random_point(polygon.envelope.bounds)\n            if PointSampler.contains(polygon, point):\n                samples.append(point)\n        return samples",
    "docstring": "Returns randomly sampled points from a polygon.\n\n        Complexity of this procedure is (A/a * nsamples) where A=area(bbox(P))\n        and a=area(P) where P is the polygon of the connected component cc_index"
  },
  {
    "code": "def predictions_variance(df, filepath=None):\n    df = df.filter(regex=\"^VAR:\")\n    by_readout = df.mean(axis=0).reset_index(level=0)\n    by_readout.columns = ['Readout', 'Prediction variance (mean)']\n    by_readout['Readout'] = by_readout.Readout.map(lambda n: n[4:])\n    g1 = sns.factorplot(x='Readout', y='Prediction variance (mean)', data=by_readout, kind='bar', aspect=2)\n    for tick in g1.ax.get_xticklabels():\n        tick.set_rotation(90)\n    if filepath:\n        g1.savefig(os.path.join(filepath, 'predictions-variance.pdf'))\n    return g1",
    "docstring": "Plots the mean variance prediction for each readout\n\n    Parameters\n    ----------\n    df: `pandas.DataFrame`_\n        DataFrame with columns starting with `VAR:`\n\n    filepath: str\n        Absolute path to a folder where to write the plots\n\n\n    Returns\n    -------\n    plot\n        Generated plot\n\n\n    .. _pandas.DataFrame: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe"
  },
  {
    "code": "def _get_response_mime_type(self):\n        view_name = self.request.view_name\n        if view_name != '':\n            mime_type = get_registered_mime_type_for_name(view_name)\n        else:\n            mime_type = None\n            acc = None\n            for acc in self.request.accept:\n                if acc == '*/*':\n                    mime_type = self.__get_default_response_mime_type()\n                    break\n                try:\n                    mime_type = \\\n                            get_registered_mime_type_for_string(acc.lower())\n                except KeyError:\n                    pass\n                else:\n                    break\n            if mime_type is None:\n                if not acc is None:\n                    headers = \\\n                        [('Location', self.request.path_url),\n                         ('Content-Type', TextPlainMime.mime_type_string),\n                         ]\n                    mime_strings = get_registered_mime_strings()\n                    exc = HTTPNotAcceptable('Requested MIME content type(s) '\n                                            'not acceptable.',\n                                            body=','.join(mime_strings),\n                                            headers=headers)\n                    raise exc\n                mime_type = self.__get_default_response_mime_type()\n        return mime_type",
    "docstring": "Returns the reponse MIME type for this view.\n\n        :raises: :class:`pyramid.httpexceptions.HTTPNotAcceptable` if the\n          MIME content type(s) the client specified can not be handled by\n          the view."
  },
  {
    "code": "def get_monitoring_problems(self):\n        res = {}\n        if not self.sched:\n            return res\n        scheduler_stats = self.sched.get_scheduler_stats(details=True)\n        if 'livesynthesis' in scheduler_stats:\n            res['livesynthesis'] = scheduler_stats['livesynthesis']\n        if 'problems' in scheduler_stats:\n            res['problems'] = scheduler_stats['problems']\n        return res",
    "docstring": "Get the current scheduler livesynthesis\n\n        :return: live synthesis and problems dictionary\n        :rtype: dict"
  },
  {
    "code": "def underline(text):\n    text += \"\\n\"\n    for i in range(len(text)-1):\n        text += \"=\"\n    text += \"\\n\"\n    return text",
    "docstring": "Takes a string, and returns it underscored."
  },
  {
    "code": "def guid2bytes(s):\n    assert isinstance(s, str)\n    assert len(s) == 36\n    p = struct.pack\n    return b\"\".join([\n        p(\"<IHH\", int(s[:8], 16), int(s[9:13], 16), int(s[14:18], 16)),\n        p(\">H\", int(s[19:23], 16)),\n        p(\">Q\", int(s[24:], 16))[2:],\n    ])",
    "docstring": "Converts a GUID to the serialized bytes representation"
  },
  {
    "code": "def get_pending_reboot():\n    checks = (get_pending_update,\n              get_pending_file_rename,\n              get_pending_servermanager,\n              get_pending_component_servicing,\n              get_reboot_required_witnessed,\n              get_pending_computer_name,\n              get_pending_domain_join)\n    for check in checks:\n        if check():\n            return True\n    return False",
    "docstring": "Determine whether there is a reboot pending.\n\n    .. versionadded:: 2016.11.0\n\n    Returns:\n        bool: ``True`` if the system is pending reboot, otherwise ``False``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' system.get_pending_reboot"
  },
  {
    "code": "def send_reset_password_email(self, user, user_email):\n        if not self.user_manager.USER_ENABLE_EMAIL: return\n        assert self.user_manager.USER_ENABLE_FORGOT_PASSWORD\n        email = user_email.email if user_email else user.email\n        token = self.user_manager.generate_token(user.id)\n        reset_password_link = url_for('user.reset_password', token=token, _external=True)\n        self._render_and_send_email(\n            email,\n            user,\n            self.user_manager.USER_RESET_PASSWORD_EMAIL_TEMPLATE,\n            reset_password_link=reset_password_link,\n        )",
    "docstring": "Send the 'reset password' email."
  },
  {
    "code": "def _set_sysfs(self, fcp, target_wwpn, target_lun):\n        device = '0.0.%s' % fcp\n        port_add = \"echo '%s' > \" % target_wwpn\n        port_add += \"/sys/bus/ccw/drivers/zfcp/%s/port_add\" % device\n        unit_add = \"echo '%s' > \" % target_lun\n        unit_add += \"/sys/bus/ccw/drivers/zfcp/%(device)s/%(wwpn)s/unit_add\\n\"\\\n                    % {'device': device, 'wwpn': target_wwpn}\n        return '\\n'.join((port_add,\n                          unit_add))",
    "docstring": "rhel6 set WWPN and LUN in sysfs"
  },
  {
    "code": "async def _registration_completed(self, message):\n        if not self.registered:\n            self.registered = True\n            self.connection.throttle = True\n            target = message.params[0]\n            fakemsg = self._create_message('NICK', target, source=self.nickname)\n            await self.on_raw_nick(fakemsg)",
    "docstring": "We're connected and registered. Receive proper nickname and emit fake NICK message."
  },
  {
    "code": "def forwards(apps, schema_editor):\n    Movie = apps.get_model('spectator_events', 'Movie')\n    Work = apps.get_model('spectator_events', 'Work')\n    WorkRole = apps.get_model('spectator_events', 'WorkRole')\n    WorkSelection = apps.get_model('spectator_events', 'WorkSelection')\n    for m in Movie.objects.all():\n        work = Work.objects.create(\n            kind='movie',\n            title=m.title,\n            title_sort=m.title_sort,\n            year=m.year,\n            imdb_id=m.imdb_id\n        )\n        for role in m.roles.all():\n            WorkRole.objects.create(\n                creator=role.creator,\n                work=work,\n                role_name=role.role_name,\n                role_order=role.role_order\n            )\n        for selection in m.events.all():\n            WorkSelection.objects.create(\n                event=selection.event,\n                work=work,\n                order=selection.order\n            )\n        m.delete()",
    "docstring": "Change all Movie objects into Work objects, and their associated\n    data into WorkRole and WorkSelection models, then delete the Movie."
  },
  {
    "code": "def parse(self, argument):\n    if isinstance(argument, list):\n      return argument\n    elif not argument:\n      return []\n    else:\n      if self._comma_compat:\n        argument = argument.replace(',', ' ')\n      return argument.split()",
    "docstring": "Parses argument as whitespace-separated list of strings.\n\n    It also parses argument as comma-separated list of strings if requested.\n\n    Args:\n      argument: string argument passed in the commandline.\n\n    Returns:\n      [str], the parsed flag value."
  },
  {
    "code": "def get_availabilities_for_duration(duration, availabilities):\n    duration_availabilities = []\n    start_time = '10:00'\n    while start_time != '17:00':\n        if start_time in availabilities:\n            if duration == 30:\n                duration_availabilities.append(start_time)\n            elif increment_time_by_thirty_mins(start_time) in availabilities:\n                duration_availabilities.append(start_time)\n        start_time = increment_time_by_thirty_mins(start_time)\n    return duration_availabilities",
    "docstring": "Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows."
  },
  {
    "code": "def download_as_zip(name, filename):\n    location = list(IPList.objects.filter(name))\n    if location:\n        iplist = location[0]\n        return iplist.download(filename=filename)",
    "docstring": "Download IPList with zip compression. Recommended for IPLists\n    of larger sizes. This is the default format for downloading\n    IPLists.\n\n    :param str name: name of IPList\n    :param str filename: name of filename for IPList"
  },
  {
    "code": "def remove_prompt(self):\n    with self._cond:\n      self._prompt = None\n      if self._console_prompt:\n        self._console_prompt.Stop()\n        self._console_prompt = None\n      self.notify_update()",
    "docstring": "Remove the prompt."
  },
  {
    "code": "def set_parameter_error(self, name, par, error):\n        idx = self.like.par_index(name, par)\n        self.like[idx].setError(error)\n        self._sync_params(name)",
    "docstring": "Set the error on the value of a parameter.\n\n        Parameters\n        ----------\n\n        name : str\n            Source name.\n\n        par : str\n            Parameter name.\n\n        error : float\n            The value for the parameter error"
  },
  {
    "code": "def get_default_config_help(self):\n        config_help = super(UsersCollector, self).get_default_config_help()\n        config_help.update({\n        })\n        return config_help",
    "docstring": "Returns the default collector help text"
  },
  {
    "code": "def default_returns_func(symbol, start=None, end=None):\n    if start is None:\n        start = '1/1/1970'\n    if end is None:\n        end = _1_bday_ago()\n    start = get_utc_timestamp(start)\n    end = get_utc_timestamp(end)\n    if symbol == 'SPY':\n        filepath = data_path('spy.csv')\n        rets = get_returns_cached(filepath,\n                                  get_symbol_returns_from_yahoo,\n                                  end,\n                                  symbol='SPY',\n                                  start='1/1/1970',\n                                  end=datetime.now())\n        rets = rets[start:end]\n    else:\n        rets = get_symbol_returns_from_yahoo(symbol, start=start, end=end)\n    return rets[symbol]",
    "docstring": "Gets returns for a symbol.\n    Queries Yahoo Finance. Attempts to cache SPY.\n\n    Parameters\n    ----------\n    symbol : str\n        Ticker symbol, e.g. APPL.\n    start : date, optional\n        Earliest date to fetch data for.\n        Defaults to earliest date available.\n    end : date, optional\n        Latest date to fetch data for.\n        Defaults to latest date available.\n\n    Returns\n    -------\n    pd.Series\n        Daily returns for the symbol.\n         - See full explanation in tears.create_full_tear_sheet (returns)."
  },
  {
    "code": "def _send_command_wrapper(self, cmd):\n        cached_results = self._results_cache.get(cmd)\n        if not cached_results:\n            response = self._send_command(cmd)\n            self._results_cache[cmd] = response\n            return response\n        else:\n            return cached_results",
    "docstring": "Send command to the remote device with a caching feature to avoid sending the same command\n        twice based on the SSH_MAPPER_BASE dict cmd key.\n\n        Parameters\n        ----------\n        cmd : str\n            The command to send to the remote device after checking cache.\n\n        Returns\n        -------\n        response : str\n            The response from the remote device."
  },
  {
    "code": "def schedule(self, when=None, action=None, **kwargs):\n        action = '_publish'\n        super(BaseVersionedModel, self).schedule(when=when, action=action,\n                                                 **kwargs)",
    "docstring": "Schedule this item to be published.\n\n        :param when: Date/time when this item should go live. None means now."
  },
  {
    "code": "def search_datasets(\n        self,\n        license=None,\n        format=None,\n        query=None,\n        featured=None,\n        owner=None,\n        organization=None,\n        badge=None,\n        reuses=None,\n        page_size=20,\n        x_fields=None,\n    ):\n        payload = {\"badge\": badge, \"size\": page_size, \"X-Fields\": x_fields}\n        search_url = \"{}/datasets\".format(\n            self.base_url,\n        )\n        search_req = requests.get(\n            search_url,\n            params=payload,\n        )\n        logger.debug(search_req.url)\n        return search_req.json()",
    "docstring": "Search datasets within uData portal."
  },
  {
    "code": "def debit(self, amount, credit_account, description, debit_memo=\"\", credit_memo=\"\", datetime=None):\n        assert amount >= 0\n        return self.post(amount, credit_account, description, self_memo=debit_memo, other_memo=credit_memo, datetime=datetime)",
    "docstring": "Post a debit of 'amount' and a credit of -amount against this account and credit_account respectively.\n\n        note amount must be non-negative."
  },
  {
    "code": "async def disable_digital_reporting(self, pin):\n        port = pin // 8\n        command = [PrivateConstants.REPORT_DIGITAL + port,\n                   PrivateConstants.REPORTING_DISABLE]\n        await self._send_command(command)",
    "docstring": "Disables digital reporting. By turning reporting off for this pin,\n        Reporting is disabled for all 8 bits in the \"port\"\n\n        :param pin: Pin and all pins for this port\n\n        :returns: No return value"
  },
  {
    "code": "def check_type(value: typing.Any, hint: typing.Optional[type]) -> bool:\n    if hint is None:\n        hint = NoneType\n    actual_type = type(value)\n    if hint is NoneType:\n        correct = value is None\n    elif hint is typing.Any:\n        correct = True\n    elif hint is typing.Pattern or hint is typing.Match:\n        correct = isinstance(value, hint.impl_type)\n    elif isinstance(hint, typing.TypeVar):\n        correct = True\n    elif issubclass(hint, typing.Callable):\n        actual_type, correct = check_callable(value, hint)\n    elif issubclass(hint, typing.Tuple):\n        actual_type, correct = check_tuple(value, hint)\n    elif issubclass(hint, typing.Union):\n        actual_type, correct = check_union(value, hint)\n    else:\n        correct = isinstance(value, hint)\n    return actual_type, correct",
    "docstring": "Check given ``value``'s type.\n\n    :param value: given argument\n    :param hint: expected type of given ``value``.\n                 as like :mod:`typing` interprets, :const:`None` is interpreted\n                 as :class:`types.NoneType`\n    :type hint: :class:`typing.Optional`[:class:`type`]"
  },
  {
    "code": "def _learning_rate_warmup(warmup_steps, warmup_schedule=\"exp\", hparams=None):\n  if not warmup_steps:\n    return tf.constant(1.)\n  tf.logging.info(\"Applying %s learning rate warmup for %d steps\",\n                  warmup_schedule, warmup_steps)\n  warmup_steps = tf.to_float(warmup_steps)\n  global_step = _global_step(hparams)\n  if warmup_schedule == \"exp\":\n    return tf.exp(tf.log(0.01) / warmup_steps)**(warmup_steps - global_step)\n  else:\n    assert warmup_schedule == \"linear\"\n    start = tf.constant(0.35)\n    return ((tf.constant(1.) - start) / warmup_steps) * global_step + start",
    "docstring": "Learning rate warmup multiplier."
  },
  {
    "code": "def _get_es_version(self, config):\n        try:\n            data = self._get_data(config.url, config, send_sc=False)\n            version = data['version']['number'].split('-')[0]\n            version = [int(p) for p in version.split('.')[0:3]]\n        except AuthenticationError:\n            raise\n        except Exception as e:\n            self.warning(\"Error while trying to get Elasticsearch version from %s %s\" % (config.url, str(e)))\n            version = [1, 0, 0]\n        self.service_metadata('version', version)\n        self.log.debug(\"Elasticsearch version is %s\" % version)\n        return version",
    "docstring": "Get the running version of elasticsearch."
  },
  {
    "code": "def links(self):\n        ret = []\n        linkheader = self.getheader('link')\n        if not linkheader:\n            return ret\n        for i in linkheader.split(','):\n            try:\n                url, params = i.split(';', 1)\n            except ValueError:\n                url, params = i, ''\n            link = {}\n            link['url'] = url.strip()\n            for param in params.split(';'):\n                try:\n                    k, v = param.split('=')\n                except ValueError:\n                    break\n                link[k.strip()] = v.strip(''' '\"''')\n            ret.append(link)\n        return ret",
    "docstring": "Links parsed from HTTP Link header"
  },
  {
    "code": "def iter_comments(self, number=-1, etag=None):\n        url = self._build_url('comments', base_url=self._api)\n        return self._iter(int(number), url, ReviewComment, etag=etag)",
    "docstring": "Iterate over the comments on this pull request.\n\n        :param int number: (optional), number of comments to return. Default:\n            -1 returns all available comments.\n        :param str etag: (optional), ETag from a previous request to the same\n            endpoint\n        :returns: generator of :class:`ReviewComment <ReviewComment>`\\ s"
  },
  {
    "code": "def createMultipleL4L2Columns(network, networkConfig):\n  numCorticalColumns = networkConfig[\"numCorticalColumns\"]\n  for i in xrange(numCorticalColumns):\n    networkConfigCopy = copy.deepcopy(networkConfig)\n    layerConfig = networkConfigCopy[\"L2Params\"]\n    layerConfig[\"seed\"] = layerConfig.get(\"seed\", 42) + i\n    layerConfig[\"numOtherCorticalColumns\"] = numCorticalColumns - 1\n    suffix = \"_\" + str(i)\n    network = createL4L2Column(network, networkConfigCopy, suffix)\n  for i in range(networkConfig[\"numCorticalColumns\"]):\n    suffixSrc = \"_\" + str(i)\n    for j in range(networkConfig[\"numCorticalColumns\"]):\n      if i != j:\n        suffixDest = \"_\" + str(j)\n        network.link(\n          \"L2Column\" + suffixSrc, \"L2Column\" + suffixDest,\n          \"UniformLink\", \"\",\n          srcOutput=\"feedForwardOutput\", destInput=\"lateralInput\",\n          propagationDelay=1)\n  enableProfiling(network)\n  return network",
    "docstring": "Create a network consisting of multiple columns.  Each column contains one L4\n  and one L2, is identical in structure to the network created by\n  createL4L2Column. In addition all the L2 columns are fully connected to each\n  other through their lateral inputs.\n\n  Region names have a column number appended as in externalInput_0,\n  externalInput_1, etc.\n\n  networkConfig must be of the following format (see createL4L2Column for\n  further documentation):\n\n    {\n      \"networkType\": \"MultipleL4L2Columns\",\n      \"numCorticalColumns\": 3,\n      \"externalInputSize\": 1024,\n      \"sensorInputSize\": 1024,\n      \"L4Params\": {\n        <constructor parameters for ApicalTMPairRegion\n      },\n      \"L2Params\": {\n        <constructor parameters for ColumnPoolerRegion>\n      },\n      \"lateralSPParams\": {\n        <constructor parameters for optional SPRegion>\n      },\n      \"feedForwardSPParams\": {\n        <constructor parameters for optional SPRegion>\n      }\n    }"
  },
  {
    "code": "def make_definition(name, base, schema):\n    class_name = make_class_name(name)\n    cls = register(make(class_name, base, schema))\n    globals()[class_name] = cls",
    "docstring": "Create a new definition."
  },
  {
    "code": "def predict_array(self, arr):\n        precompute = self.precompute\n        self.precompute = False\n        pred = super().predict_array(arr)\n        self.precompute = precompute\n        return pred",
    "docstring": "This over-ride is necessary because otherwise the learner method accesses the wrong model when it is called\n        with precompute set to true\n\n        Args:\n            arr: a numpy array to be used as input to the model for prediction purposes\n        Returns:\n            a numpy array containing the predictions from the model"
  },
  {
    "code": "def search_definition(self, module, keyword, arg):\n        r = module.search_one(keyword, arg)\n        if r is not None:\n            return r\n        for i in module.search('include'):\n            modulename = i.arg\n            m = self.ctx.search_module(i.pos, modulename)\n            if m is not None:\n                r = m.search_one(keyword, arg)\n                if r is not None:\n                    return r\n        return None",
    "docstring": "Search for a defintion with `keyword` `name`\n        Search the module and its submodules."
  },
  {
    "code": "def between(self, minimum: int = 1, maximum: int = 1000) -> int:\n        return self.random.randint(minimum, maximum)",
    "docstring": "Generate a random number between minimum and maximum.\n\n        :param minimum: Minimum of range.\n        :param maximum: Maximum of range.\n        :return: Number."
  },
  {
    "code": "def tofile(self, file_):\n        close_file = False\n        if not hasattr(file_, 'write'):\n            file_ = open(file_, 'wb')\n            close_file = True\n        file_.write(self._f)\n        if close_file:\n            file_.close()",
    "docstring": "Dump all storage data to a file. The file_ argument can be a\n        file object or a string that represents a filename. If called\n        with a file object, it should be opened in binary mode, and\n        the caller is responsible for closing the file.\n\n        The method should only be called after the storage device has\n        been closed to ensure that the locked flag has been set to\n        False."
  },
  {
    "code": "def get_apphook_field_names(model):\n    key = APP_CONFIG_FIELDS_KEY.format(\n        app_label=model._meta.app_label,\n        model_name=model._meta.object_name\n    ).lower()\n    if not hasattr(model, key):\n        field_names = _get_apphook_field_names(model)\n        setattr(model, key, field_names)\n    return getattr(model, key)",
    "docstring": "Cache app-hook field names on model\n\n    :param model: model class or object\n    :return: list of foreign key field names to AppHookConfigs"
  },
  {
    "code": "def _argsort_and_resolve_ties(time, random_state):\n        n_samples = len(time)\n        order = numpy.argsort(time, kind=\"mergesort\")\n        i = 0\n        while i < n_samples - 1:\n            inext = i + 1\n            while inext < n_samples and time[order[i]] == time[order[inext]]:\n                inext += 1\n            if i + 1 != inext:\n                random_state.shuffle(order[i:inext])\n            i = inext\n        return order",
    "docstring": "Like numpy.argsort, but resolves ties uniformly at random"
  },
  {
    "code": "def list_leases(self, prefix):\n        api_path = '/v1/sys/leases/lookup/{prefix}'.format(prefix=prefix)\n        response = self._adapter.list(\n            url=api_path,\n        )\n        return response.json()",
    "docstring": "Retrieve a list of lease ids.\n\n        Supported methods:\n            LIST: /sys/leases/lookup/{prefix}. Produces: 200 application/json\n\n        :param prefix: Lease prefix to filter list by.\n        :type prefix: str | unicode\n        :return: The JSON response of the request.\n        :rtype: dict"
  },
  {
    "code": "def users_create(self, email, name, password, username, **kwargs):\n        return self.__call_api_post('users.create', email=email, name=name, password=password, username=username,\n                                    kwargs=kwargs)",
    "docstring": "Creates a user"
  },
  {
    "code": "def run(self, forever=True):\n        loop = self.create_connection()\n        self.add_signal_handlers()\n        if forever:\n            loop.run_forever()",
    "docstring": "start the bot"
  },
  {
    "code": "def continuous(self, *args):\n        new_df = copy_df(self)\n        fields = _render_field_set(args)\n        self._assert_ml_fields_valid(*fields)\n        new_df._perform_operation(op.FieldContinuityOperation(dict((_get_field_name(f), True) for f in fields)))\n        return new_df",
    "docstring": "Set fields to be continuous.\n\n        :rtype: DataFrame\n\n        :Example:\n\n        >>> # Table schema is create table test(f1 double, f2 string)\n        >>> # Original continuity: f1=DISCRETE, f2=DISCRETE\n        >>> # Now we want to set ``f1`` and ``f2`` into continuous\n        >>> new_ds = df.continuous('f1 f2')"
  },
  {
    "code": "def __within2(value, within=None, errmsg=None, dtype=None):\n    valid, _value = False, value\n    if dtype:\n        try:\n            _value = dtype(value)\n            valid = _value in within\n        except ValueError:\n            pass\n    else:\n        valid = _value in within\n    if errmsg is None:\n        if dtype:\n            typename = getattr(dtype, '__name__',\n                               hasattr(dtype, '__class__')\n                               and getattr(dtype.__class__, 'name', dtype))\n            errmsg = '{0} within \\'{1}\\''.format(typename, within)\n        else:\n            errmsg = 'within \\'{0}\\''.format(within)\n    return (valid, _value, errmsg)",
    "docstring": "validate that a value is in ``within`` and optionally a ``dtype``"
  },
  {
    "code": "def write(self, data):\n        if isinstance(data, bytearray):\n            data = bytes(data)\n        if not isinstance(data, byte_types):\n            raise ValueError(\"A bytes argument is required\")\n        res = librtmp.RTMP_Write(self.client.rtmp, data, len(data))\n        if res < 0:\n            raise IOError(\"Failed to write data\")\n        return res",
    "docstring": "Writes data to the stream.\n\n        :param data: bytes, FLV data to write to the stream\n\n        The data passed can contain multiple FLV tags, but it MUST\n        always contain complete tags or undefined behaviour might\n        occur.\n\n        Raises :exc:`IOError` on error."
  },
  {
    "code": "def snapshots_to_send(source_snaps, dest_snaps):\n    if len(source_snaps) == 0:\n        raise AssertionError(\"No snapshots exist locally!\")\n    if len(dest_snaps) == 0:\n        return None, source_snaps[-1]\n    last_remote = dest_snaps[-1]\n    for snap in reversed(source_snaps):\n        if snap == last_remote:\n            return last_remote, source_snaps[-1]\n    raise AssertionError(\"Latest snapshot on destination doesn't exist on source!\")",
    "docstring": "return pair of snapshots"
  },
  {
    "code": "def grok_state(self, obj):\n        if 'state' in obj:\n            my_state = obj['state'].lower()\n            if my_state != 'absent' and my_state != 'present':\n                raise aomi_excep \\\n                    .Validation('state must be either \"absent\" or \"present\"')\n        self.present = obj.get('state', 'present').lower() == 'present'",
    "docstring": "Determine the desired state of this\n        resource based on data present"
  },
  {
    "code": "def is_nested_list_like(obj):\n    return (is_list_like(obj) and hasattr(obj, '__len__') and\n            len(obj) > 0 and all(is_list_like(item) for item in obj))",
    "docstring": "Check if the object is list-like, and that all of its elements\n    are also list-like.\n\n    .. versionadded:: 0.20.0\n\n    Parameters\n    ----------\n    obj : The object to check\n\n    Returns\n    -------\n    is_list_like : bool\n        Whether `obj` has list-like properties.\n\n    Examples\n    --------\n    >>> is_nested_list_like([[1, 2, 3]])\n    True\n    >>> is_nested_list_like([{1, 2, 3}, {1, 2, 3}])\n    True\n    >>> is_nested_list_like([\"foo\"])\n    False\n    >>> is_nested_list_like([])\n    False\n    >>> is_nested_list_like([[1, 2, 3], 1])\n    False\n\n    Notes\n    -----\n    This won't reliably detect whether a consumable iterator (e. g.\n    a generator) is a nested-list-like without consuming the iterator.\n    To avoid consuming it, we always return False if the outer container\n    doesn't define `__len__`.\n\n    See Also\n    --------\n    is_list_like"
  },
  {
    "code": "def run(self, *args):\n        params = self.parser.parse_args(args)\n        code = self.initialize(name=params.name, reuse=params.reuse)\n        return code",
    "docstring": "Initialize a registry.\n\n        Create and initialize an empty registry which its name is defined by\n        <name> parameter. Required tables will be also created."
  },
  {
    "code": "def update(self,\n               message=None,\n               subject=None,\n               days=None,\n               downloads=None,\n               notify=None):\n        method, url = get_URL('update')\n        payload = {\n            'apikey': self.config.get('apikey'),\n            'logintoken': self.session.cookies.get('logintoken'),\n            'transferid': self.transfer_id,\n            }\n        data = {\n            'message': message or self.transfer_info.get('message'),\n            'message': subject or self.transfer_info.get('subject'),\n            'days': days or self.transfer_info.get('days'),\n            'downloads': downloads or self.transfer_info.get('downloads'),\n            'notify': notify or self.transfer_info.get('notify')\n            }\n        payload.update(data)\n        res = getattr(self.session, method)(url, params=payload)\n        if res.status_code:\n            self.transfer_info.update(data)\n            return True\n        hellraiser(res)",
    "docstring": "Update properties for a transfer.\n\n        :param message: updated message to recipient(s)\n        :param subject: updated subject for trasfer\n        :param days: updated amount of days transfer is available\n        :param downloads: update amount of downloads allowed for transfer\n        :param notify: update whether to notifiy on downloads or not\n        :type message: ``str`` or ``unicode``\n        :type subject: ``str`` or ``unicode``\n        :type days: ``int``\n        :type downloads: ``int``\n        :type notify: ``bool``\n        :rtype: ``bool``"
  },
  {
    "code": "def plot_all(self, show=True, **kwargs):\n        figs = []; app = figs.append\n        app(self.plot_stacked_hist(show=show))\n        app(self.plot_efficiency(show=show))\n        app(self.plot_pie(show=show))\n        return figs",
    "docstring": "Call all plot methods provided by the parser."
  },
  {
    "code": "def get_consensus_tree(self, cutoff=0.0, best_tree=None):\n        if best_tree:\n            raise NotImplementedError(\"best_tree option not yet supported.\")\n        cons = ConsensusTree(self.treelist, cutoff)\n        cons.update()\n        return cons.ttree",
    "docstring": "Returns an extended majority rule consensus tree as a Toytree object.\n        Node labels include 'support' values showing the occurrence of clades \n        in the consensus tree across trees in the input treelist. \n        Clades with support below 'cutoff' are collapsed into polytomies.\n        If you enter an optional 'best_tree' then support values from\n        the treelist calculated for clades in this tree, and the best_tree is\n        returned with support values added to nodes. \n\n        Params\n        ------\n        cutoff (float; default=0.0): \n            Cutoff below which clades are collapsed in the majority rule \n            consensus tree. This is a proportion (e.g., 0.5 means 50%). \n        best_tree (Toytree; optional):\n            A tree that support values should be calculated for and added to. \n            For example, you want to calculate how often clades in your best \n            ML tree are supported in 100 bootstrap trees."
  },
  {
    "code": "def add_scenario(self, parameter: 'Parameter', scenario_name: str = default_scenario):\n        self.scenarios[scenario_name] = parameter",
    "docstring": "Add a scenario for this parameter.\n\n        :param scenario_name:\n        :param parameter:\n        :return:"
  },
  {
    "code": "def dumps(self):\n        io = six.StringIO()\n        self.dump(io)\n        io.seek(0)\n        return io.read()",
    "docstring": "Dump data to a string.\n\n        :rtype: str"
  },
  {
    "code": "def from_pkg(self):\n        if self._version is None:\n            frame = caller(1)\n            pkg = frame.f_globals.get('__package__')\n            if pkg is not None:\n                self._version = pkg_version(pkg)\n        return self",
    "docstring": "Use pkg_resources to determine the installed package version."
  },
  {
    "code": "def components(self) -> List['DAGCircuit']:\n        comps = nx.weakly_connected_component_subgraphs(self.graph)\n        return [DAGCircuit(comp) for comp in comps]",
    "docstring": "Split DAGCircuit into independent components"
  },
  {
    "code": "def wp_draw_callback(self, points):\n        if len(points) < 3:\n            return\n        from MAVProxy.modules.lib import mp_util\n        home = self.wploader.wp(0)\n        self.wploader.clear()\n        self.wploader.target_system = self.target_system\n        self.wploader.target_component = self.target_component\n        self.wploader.add(home)\n        if self.get_default_frame() == mavutil.mavlink.MAV_FRAME_GLOBAL_TERRAIN_ALT:\n            use_terrain = True\n        else:\n            use_terrain = False\n        for p in points:\n            self.wploader.add_latlonalt(p[0], p[1], self.settings.wpalt, terrain_alt=use_terrain)\n        self.send_all_waypoints()",
    "docstring": "callback from drawing waypoints"
  },
  {
    "code": "def add_model(self, *args, **kwargs):\n        if self.category != Category.MODEL:\n            raise APIError(\"Part should be of category MODEL\")\n        return self._client.create_model(self, *args, **kwargs)",
    "docstring": "Add a new child model to this model.\n\n        In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as\n        additional keyword=value argument to this method. This will improve performance of the backend\n        against a trade-off that someone looking at the frontend won't notice any changes unless the page\n        is refreshed.\n\n        :return: a :class:`Part` of category `MODEL`"
  },
  {
    "code": "def spawn(self, *cmds: str) -> List[SublemonSubprocess]:\n        if not self._is_running:\n            raise SublemonRuntimeError(\n                'Attempted to spawn subprocesses from a non-started server')\n        subprocs = [SublemonSubprocess(self, cmd) for cmd in cmds]\n        for sp in subprocs:\n            asyncio.ensure_future(sp.spawn())\n        return subprocs",
    "docstring": "Coroutine to spawn shell commands.\n\n        If `max_concurrency` is reached during the attempt to spawn the\n        specified subprocesses, excess subprocesses will block while attempting\n        to acquire this server's semaphore."
  },
  {
    "code": "def _convert_many_to_one(self, col_name, label, description,\n                             lst_validators, filter_rel_fields,\n                             form_props):\n        query_func = self._get_related_query_func(col_name, filter_rel_fields)\n        get_pk_func = self._get_related_pk_func(col_name)\n        extra_classes = None\n        allow_blank = True\n        if not self.datamodel.is_nullable(col_name):\n            lst_validators.append(validators.DataRequired())\n            allow_blank = False\n        else:\n            lst_validators.append(validators.Optional())\n        form_props[col_name] = \\\n            QuerySelectField(label,\n                             description=description,\n                             query_func=query_func,\n                             get_pk_func=get_pk_func,\n                             allow_blank=allow_blank,\n                             validators=lst_validators,\n                             widget=Select2Widget(extra_classes=extra_classes))\n        return form_props",
    "docstring": "Creates a WTForm field for many to one related fields,\n            will use a Select box based on a query. Will only\n            work with SQLAlchemy interface."
  },
  {
    "code": "def get_archive_cmdlist_func (program, command, format):\n    key = util.stripext(os.path.basename(program).lower())\n    modulename = \".programs.\" + ProgramModules.get(key, key)\n    try:\n        module = importlib.import_module(modulename, __name__)\n    except ImportError as msg:\n        raise util.PatoolError(msg)\n    try:\n        return getattr(module, '%s_%s' % (command, format))\n    except AttributeError as msg:\n        raise util.PatoolError(msg)",
    "docstring": "Get the Python function that executes the given program."
  },
  {
    "code": "def get_config(basedir, files):\n    config_details = config.find(\n        basedir, files,\n        environment.Environment.from_env_file(basedir))\n    return config.load(config_details)",
    "docstring": "Returns the config object for the selected docker-compose.yml\n\n    This is an instance of `compose.config.config.Config`."
  },
  {
    "code": "def reqTickers(\n            self, *contracts: List[Contract],\n            regulatorySnapshot: bool = False) -> List[Ticker]:\n        return self._run(\n            self.reqTickersAsync(\n                *contracts, regulatorySnapshot=regulatorySnapshot))",
    "docstring": "Request and return a list of snapshot tickers.\n        The list is returned when all tickers are ready.\n\n        This method is blocking.\n\n        Args:\n            contracts: Contracts to get tickers for.\n            regulatorySnapshot: Request NBBO snapshots (may incur a fee)."
  },
  {
    "code": "def calc_support(self, items):\n        if not items:\n            return 1.0\n        if not self.num_transaction:\n            return 0.0\n        sum_indexes = None\n        for item in items:\n            indexes = self.__transaction_index_map.get(item)\n            if indexes is None:\n                return 0.0\n            if sum_indexes is None:\n                sum_indexes = indexes\n            else:\n                sum_indexes = sum_indexes.intersection(indexes)\n        return float(len(sum_indexes)) / self.__num_transaction",
    "docstring": "Returns a support for items.\n\n        Arguments:\n            items -- Items as an iterable object (eg. ['A', 'B'])."
  },
  {
    "code": "def makeService(self, options):\n        return NodeService(\n            port=options['port'],\n            host=options['host'],\n            broker_host=options['broker_host'],\n            broker_port=options['broker_port'],\n            debug=options['debug']\n        )",
    "docstring": "Construct a Node Server"
  },
  {
    "code": "def _skw_matches_comparator(kw0, kw1):\n    def compare(a, b):\n        return (a > b) - (a < b)\n    list_comparison = compare(len(kw1[1][0]), len(kw0[1][0]))\n    if list_comparison:\n        return list_comparison\n    if kw0[0].isComposite() and kw1[0].isComposite():\n        component_avg0 = sum(kw0[1][1]) / len(kw0[1][1])\n        component_avg1 = sum(kw1[1][1]) / len(kw1[1][1])\n        component_comparison = compare(component_avg1, component_avg0)\n        if component_comparison:\n            return component_comparison\n    return compare(len(str(kw1[0])), len(str(kw0[0])))",
    "docstring": "Compare 2 single keywords objects.\n\n    First by the number of their spans (ie. how many times they were found),\n    if it is equal it compares them by lenghts of their labels."
  },
  {
    "code": "def suppress_stdout():\n    save_stdout = sys.stdout\n    sys.stdout = DevNull()\n    yield\n    sys.stdout = save_stdout",
    "docstring": "Context manager that suppresses stdout.\n\n    Examples:\n        >>> with suppress_stdout():\n        ...     print('Test print')\n\n        >>> print('test')\n        test"
  },
  {
    "code": "def describe(self, resource=None):\n        if resource is None:\n            simple_descriptor = copy.deepcopy(self._datapackage.descriptor)\n            for resource in simple_descriptor['resources']:\n                resource.pop('schema', None)\n            return simple_descriptor\n        else:\n            return self.__resources[resource].descriptor",
    "docstring": "Describe dataset or resource within dataset\n\n        :param resource: The name of a specific resource (i.e. file or table)\n            contained in the dataset. If ``resource`` is None, this method\n            will describe the dataset itself. (Default value = None)\n        :type resource: str, optional\n        :returns: The descriptor of the dataset or of a specific resource, if\n        ``resource`` is specified in the call.\n        :rtype: dict"
  },
  {
    "code": "def libvlc_video_set_teletext(p_mi, i_page):\n    f = _Cfunctions.get('libvlc_video_set_teletext', None) or \\\n        _Cfunction('libvlc_video_set_teletext', ((1,), (1,),), None,\n                    None, MediaPlayer, ctypes.c_int)\n    return f(p_mi, i_page)",
    "docstring": "Set new teletext page to retrieve.\n    @param p_mi: the media player.\n    @param i_page: teletex page number requested."
  },
  {
    "code": "def _remove_non_methods():\n  cur_module = sys.modules[__name__]\n  my_globals = dict(globals())\n  from prettytensor.pretty_tensor_class import PrettyTensor\n  for name, _ in six.iteritems(my_globals):\n    if not hasattr(PrettyTensor, name):\n      delattr(cur_module, name)\n  if hasattr(cur_module, 'bookkeeper'):\n    delattr(cur_module, 'bookkeeper')",
    "docstring": "Removes any object in dict that is not a registered method."
  },
  {
    "code": "def validate_schema(yaml_def, branch=False):\n    schema = Schema({\n        'lane' if not branch else 'branch': {\n            Optional('name'): str,\n            Optional('run_parallel'): bool,\n            'tasks': list\n        }\n    })\n    schema.validate(yaml_def)\n    from schema import And, Use\n    task_schema = Schema({\n        'class': str,\n        Optional('kwargs'): Or({str: object}),\n        Optional('args'): Or([object], And(Use(lambda a: isinstance(a, dict)), False))\n    })\n    def validate_tasks(tasks):\n        for task in tasks:\n            try:\n                Schema({'branch': dict}).validate(task)\n                validate_schema(task, True)\n            except SchemaError:\n                task_schema.validate(task)\n        return True\n    return validate_tasks(yaml_def['lane']['tasks'] if not branch else yaml_def['branch']['tasks'])",
    "docstring": "Validates the schema of a dict\n\n    Parameters\n    ----------\n    yaml_def : dict\n        dict whose schema shall be validated\n    branch : bool\n        Indicates whether `yaml_def` is a dict of a top-level lane, or of a branch\n        inside a lane (needed for recursion)\n\n    Returns\n    -------\n    bool\n        True if validation was successful"
  },
  {
    "code": "def state(ctx):\n    dev = ctx.obj\n    click.echo(dev)\n    ctx.forward(locked)\n    ctx.forward(low_battery)\n    ctx.forward(window_open)\n    ctx.forward(boost)\n    ctx.forward(temp)\n    ctx.forward(mode)\n    ctx.forward(valve_state)",
    "docstring": "Prints out all available information."
  },
  {
    "code": "def get(self, name, acc=None, default=None):\n        if acc in self.data['accounts'] and name in self.data['accounts'][acc]:\n            return self.data['accounts'][acc][name]\n        if name in self.data:\n            return self.data[name]\n        return default",
    "docstring": "Return the named config for the given account.\n\n        If an account is given, first checks the account space for the name.\n        If no account given, or if the name not found in the account space,\n        look for the name in the global config space.  If still not found,\n        return the default, if given, otherwise ``None``."
  },
  {
    "code": "def scale_joint_sfs_folded(s, n1, n2):\n    out = np.empty_like(s)\n    for i in range(s.shape[0]):\n        for j in range(s.shape[1]):\n            out[i, j] = s[i, j] * i * j * (n1 - i) * (n2 - j)\n    return out",
    "docstring": "Scale a folded joint site frequency spectrum.\n\n    Parameters\n    ----------\n    s : array_like, int, shape (m_chromosomes//2, n_chromosomes//2)\n        Folded joint site frequency spectrum.\n    n1, n2 : int, optional\n        The total number of chromosomes called in each population.\n\n    Returns\n    -------\n    joint_sfs_folded_scaled : ndarray, int, shape (m_chromosomes//2, n_chromosomes//2)\n        Scaled folded joint site frequency spectrum."
  },
  {
    "code": "def OnGridEditorCreated(self, event):\n        editor = event.GetControl()\n        editor.Bind(wx.EVT_KILL_FOCUS, self.OnGridEditorClosed)\n        event.Skip()",
    "docstring": "Used to capture Editor close events"
  },
  {
    "code": "def atlas_peer_get_request_count( peer_hostport, peer_table=None ):\n    with AtlasPeerTableLocked(peer_table) as ptbl:\n        if peer_hostport not in ptbl.keys():\n            return 0\n        count = 0\n        for (t, r) in ptbl[peer_hostport]['time']:\n            if r:\n                count += 1\n    return count",
    "docstring": "How many times have we contacted this peer?"
  },
  {
    "code": "def content(self):\n        if not self._content_data:\n            if is_seekable(self.file):\n                with wpull.util.reset_file_offset(self.file):\n                    self._content_data = self.file.read()\n            else:\n                self._content_data = self.file.read()\n        return self._content_data",
    "docstring": "Return the content of the file.\n\n        If this function is invoked, the contents of the entire file is read\n        and cached.\n\n        Returns:\n            ``bytes``: The entire content of the file."
  },
  {
    "code": "def getall(self):\n        interfaces_re = re.compile(r'(?<=^interface\\s)([Et|Po].+)$', re.M)\n        response = dict()\n        for name in interfaces_re.findall(self.config):\n            interface = self.get(name)\n            if interface:\n                response[name] = interface\n        return response",
    "docstring": "Returns a dict object to all Switchports\n\n        This method will return all of the configured switchports as a\n        dictionary object keyed by the interface identifier.\n\n        Returns:\n            A Python dictionary object that represents all configured\n                switchports in the current running configuration"
  },
  {
    "code": "def insert(self, data):\n        row = {key:self._default_entry for key in self._headers}\n        row['_uid'] = self._get_new_uid()\n        for key, val in data.items():\n            if key in ('_uid', '_default'):\n                logging.warn(\"Cannot manually set columns _uid or _default of a row! Given data: {0}\".format(data))\n                continue\n            if not isinstance(val, CSVModel._KNOWN_TYPES_MAP[self._headers_types[key]]):\n                raise Exception('Data type mismatch for column {0}. Expected: {1}, got: {2}'.format(key,\n                                                        CSVModel._KNOWN_TYPES_MAP[self._headers_types[key]], type(val)))\n            row[key] = val\n        self._table.append(row)\n        self._save()\n        return row['_uid']",
    "docstring": "Insert a row into the .csv file.\n\n        Parameters\n        ----------\n        data : :obj:`dict`\n            A dictionary mapping keys (header strings) to values.\n\n        Returns\n        -------\n        int\n            The UID for the new row.\n\n        Raises\n        ------\n        Exception\n            If the value for a given header is not of the appropriate type."
  },
  {
    "code": "def send_vdp_assoc(self, vsiid=None, mgrid=None, typeid=None,\n                       typeid_ver=None, vsiid_frmt=vdp_const.VDP_VSIFRMT_UUID,\n                       filter_frmt=vdp_const.VDP_FILTER_GIDMACVID, gid=0,\n                       mac=\"\", vlan=0, oui_id=\"\", oui_data=\"\", sw_resp=False):\n        if sw_resp and filter_frmt == vdp_const.VDP_FILTER_GIDMACVID:\n            reply = self.send_vdp_query_msg(\"assoc\", mgrid, typeid, typeid_ver,\n                                            vsiid_frmt, vsiid, filter_frmt,\n                                            gid, mac, vlan, oui_id, oui_data)\n            vlan_resp, fail_reason = self.get_vlan_from_query_reply(\n                reply, vsiid, mac)\n            if vlan_resp != constants.INVALID_VLAN:\n                return vlan_resp, fail_reason\n        reply = self.send_vdp_msg(\"assoc\", mgrid, typeid, typeid_ver,\n                                  vsiid_frmt, vsiid, filter_frmt, gid, mac,\n                                  vlan, oui_id, oui_data, sw_resp)\n        if sw_resp:\n            vlan, fail_reason = self.get_vlan_from_associate_reply(\n                reply, vsiid, mac)\n            return vlan, fail_reason\n        return None, None",
    "docstring": "Sends the VDP Associate Message.\n\n        Please refer http://www.ieee802.org/1/pages/802.1bg.html VDP\n        Section for more detailed information\n        :param vsiid: VSI value, Only UUID supported for now\n        :param mgrid: MGR ID\n        :param typeid: Type ID\n        :param typeid_ver: Version of the Type ID\n        :param vsiid_frmt: Format of the following VSI argument\n        :param filter_frmt: Filter Format. Only <GID,MAC,VID> supported for now\n        :param gid: Group ID the vNIC belongs to\n        :param mac: MAC Address of the vNIC\n        :param vlan: VLAN of the vNIC\n        :param oui_id: OUI Type\n        :param oui_data: OUI Data\n        :param sw_resp: Flag indicating if response is required from the daemon\n        :return vlan: VLAN value returned by vdptool which in turn is given\n        :             by Switch"
  },
  {
    "code": "def close(self):\n        for impyla_connection in self._connections:\n            impyla_connection.close()\n        self._connections.clear()\n        self.connection_pool.clear()",
    "docstring": "Close all open Impyla sessions"
  },
  {
    "code": "def main():\n    if sys.argv[1:]:\n        copy(' '.join(sys.argv[1:]))\n    elif not sys.stdin.isatty():\n        copy(''.join(sys.stdin.readlines()).rstrip('\\n'))\n    else:\n        print(paste())",
    "docstring": "Entry point for cli."
  },
  {
    "code": "def _CollectHistory_(lookupType, fromVal, toVal, using={}, pattern=''):\n    histObj = {}\n    if fromVal != toVal:\n        histObj[lookupType] = {\"from\": fromVal, \"to\": toVal}\n        if lookupType in ['deriveValue', 'deriveRegex', 'copyValue', 'normIncludes', 'deriveIncludes'] and using!='':\n            histObj[lookupType][\"using\"] = using\n        if lookupType in ['genericRegex', 'fieldSpecificRegex', 'normRegex', 'deriveRegex'] and pattern!='':\n            histObj[lookupType][\"pattern\"] = pattern\n    return histObj",
    "docstring": "Return a dictionary detailing what, if any, change was made to a record field\n\n    :param string lookupType: what cleaning rule made the change; one of: genericLookup, genericRegex, fieldSpecificLookup, fieldSpecificRegex, normLookup, normRegex, normIncludes, deriveValue, copyValue, deriveRegex\n    :param string fromVal: previous field value\n    :param string toVal: new string value\n    :param dict using: field values used to derive new values; only applicable for deriveValue, copyValue, deriveRegex\n    :param string pattern: which regex pattern was matched to make the change; only applicable for genericRegex, fieldSpecificRegex, deriveRegex"
  },
  {
    "code": "def unique(transactions):\n    seen = set()\n    return [x for x in transactions if not (x in seen or seen.add(x))]",
    "docstring": "Remove any duplicate entries."
  },
  {
    "code": "def _filter_defs_at_call_sites(self, defs):\n        filtered_defs = LiveDefinitions()\n        for variable, locs in defs.items():\n            if isinstance(variable, SimRegisterVariable):\n                if self.project.arch.name == 'X86':\n                    if variable.reg in (self.project.arch.registers['eax'][0],\n                                        self.project.arch.registers['ecx'][0],\n                                        self.project.arch.registers['edx'][0]):\n                        continue\n            filtered_defs.add_defs(variable, locs)\n        return filtered_defs",
    "docstring": "If we are not tracing into the function that are called in a real execution, we should properly filter the defs\n        to account for the behavior of the skipped function at this call site.\n\n        This function is a WIP. See TODOs inside.\n\n        :param defs:\n        :return:"
  },
  {
    "code": "def footrule_dist(params1, params2=None):\n    r\n    assert params2 is None or len(params1) == len(params2)\n    ranks1 = rankdata(params1, method=\"average\")\n    if params2 is None:\n        ranks2 = np.arange(1, len(params1) + 1, dtype=float)\n    else:\n        ranks2 = rankdata(params2, method=\"average\")\n    return np.sum(np.abs(ranks1 - ranks2))",
    "docstring": "r\"\"\"Compute Spearman's footrule distance between two models.\n\n    This function computes Spearman's footrule distance between the rankings\n    induced by two parameter vectors. Let :math:`\\sigma_i` be the rank of item\n    ``i`` in the model described by ``params1``, and :math:`\\tau_i` be its rank\n    in the model described by ``params2``. Spearman's footrule distance is\n    defined by\n\n    .. math::\n\n      \\sum_{i=1}^N | \\sigma_i - \\tau_i |\n\n    By convention, items with the lowest parameters are ranked first (i.e.,\n    sorted using the natural order).\n\n    If the argument ``params2`` is ``None``, the second model is assumed to\n    rank the items by their index: item ``0`` has rank 1, item ``1`` has rank\n    2, etc.\n\n    Parameters\n    ----------\n    params1 : array_like\n        Parameters of the first model.\n    params2 : array_like, optional\n        Parameters of the second model.\n\n    Returns\n    -------\n    dist : float\n        Spearman's footrule distance."
  },
  {
    "code": "def variable(dims=1):\n    if dims == 1:\n        return Poly({(1,): 1}, dim=1, shape=())\n    return Poly({\n        tuple(indices): indices for indices in numpy.eye(dims, dtype=int)\n    }, dim=dims, shape=(dims,))",
    "docstring": "Simple constructor to create single variables to create polynomials.\n\n    Args:\n        dims (int):\n            Number of dimensions in the array.\n\n    Returns:\n        (Poly):\n            Polynomial array with unit components in each dimension.\n\n    Examples:\n        >>> print(variable())\n        q0\n        >>> print(variable(3))\n        [q0, q1, q2]"
  },
  {
    "code": "def log_learning_rates(self,\n                           model: Model,\n                           optimizer: torch.optim.Optimizer):\n        if self._should_log_learning_rate:\n            names = {param: name for name, param in model.named_parameters()}\n            for group in optimizer.param_groups:\n                if 'lr' not in group:\n                    continue\n                rate = group['lr']\n                for param in group['params']:\n                    effective_rate = rate * float(param.requires_grad)\n                    self.add_train_scalar(\"learning_rate/\" + names[param], effective_rate)",
    "docstring": "Send current parameter specific learning rates to tensorboard"
  },
  {
    "code": "def set_section_config(self, section, content):\n        if not self._config.has_section(section):\n            self._config.add_section(section)\n        for key in content:\n            if isinstance(content[key], bool):\n                content[key] = str(content[key]).lower()\n            self._config.set(section, key, content[key])\n        self._override_config[section] = content",
    "docstring": "Set a specific configuration section. It's not\n        dumped on the disk.\n\n        :param section: Section name\n        :param content: A dictionary with section content"
  },
  {
    "code": "def fetchAllUsers(self, rawResults = False) :\n        r = self.connection.session.get(self.URL)\n        if r.status_code == 200 :\n            data = r.json()\n            if rawResults :\n                return data[\"result\"]\n            else :\n                res = []\n                for resu in data[\"result\"] :\n                    u = User(self, resu)\n                    res.append(u)\n                return res\n        else :\n            raise ConnectionError(\"Unable to get user list\", r.url, r.status_code)",
    "docstring": "Returns all available users. if rawResults, the result will be a list of python dicts instead of User objects"
  },
  {
    "code": "def get_string(self, origin=None):\n        token = self.get().unescape()\n        if not (token.is_identifier() or token.is_quoted_string()):\n            raise dns.exception.SyntaxError('expecting a string')\n        return token.value",
    "docstring": "Read the next token and interpret it as a string.\n\n        @raises dns.exception.SyntaxError:\n        @rtype: string"
  },
  {
    "code": "def render(self, fname=''):\n        import qnet.visualization.circuit_pyx as circuit_visualization\n        from tempfile import gettempdir\n        from time import time, sleep\n        if not fname:\n            tmp_dir = gettempdir()\n            fname = os.path.join(tmp_dir, \"tmp_{}.png\".format(hash(time)))\n        if circuit_visualization.draw_circuit(self, fname):\n            done = False\n            for k in range(20):\n                if os.path.exists(fname):\n                    done = True\n                    break\n                else:\n                    sleep(.5)\n            if done:\n                return fname\n        raise CannotVisualize()",
    "docstring": "Render the circuit expression and store the result in a file\n\n        Args:\n            fname (str): Path to an image file to store the result in.\n\n        Returns:\n            str: The path to the image file"
  },
  {
    "code": "def list_snapshots(domain=None, **kwargs):\n    ret = dict()\n    conn = __get_conn(**kwargs)\n    for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True):\n        ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A'\n    conn.close()\n    return ret",
    "docstring": "List available snapshots for certain vm or for all.\n\n    :param domain: domain name\n    :param connection: libvirt connection URI, overriding defaults\n\n        .. versionadded:: 2019.2.0\n    :param username: username to connect with, overriding defaults\n\n        .. versionadded:: 2019.2.0\n    :param password: password to connect with, overriding defaults\n\n        .. versionadded:: 2019.2.0\n\n    .. versionadded:: 2016.3.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' virt.list_snapshots\n        salt '*' virt.list_snapshots <domain>"
  },
  {
    "code": "def validate_context(self, context):\n        return all(\n            [\n                hasattr(context, attr)\n                for attr in [\n                    \"aws_request_id\",\n                    \"function_name\",\n                    \"function_version\",\n                    \"get_remaining_time_in_millis\",\n                    \"invoked_function_arn\",\n                    \"log_group_name\",\n                    \"log_stream_name\",\n                    \"memory_limit_in_mb\",\n                ]\n            ]\n        ) and callable(context.get_remaining_time_in_millis)",
    "docstring": "Checks to see if we're working with a valid lambda context object.\n\n        :returns: True if valid, False if not\n        :rtype: bool"
  },
  {
    "code": "def add_menu(self, name):\n        if name in self._menus:\n            raise exceptions.MenuAlreadyExists(\"Menu name {!r} already exists.\".format(name))\n        menu = self._menu.addMenu(name)\n        self._menus[name] = menu",
    "docstring": "Add a top-level menu.\n\n        The menu manager only allows one menu of the same name. However, it does\n        not make sure that there are no pre-existing menus of that name."
  },
  {
    "code": "def persist_experiment(experiment):\n    from benchbuild.utils.schema import Experiment, Session\n    session = Session()\n    cfg_exp = experiment.id\n    LOG.debug(\"Using experiment ID stored in config: %s\", cfg_exp)\n    exps = session.query(Experiment).filter(Experiment.id == cfg_exp)\n    desc = str(CFG[\"experiment_description\"])\n    name = experiment.name\n    if exps.count() == 0:\n        newe = Experiment()\n        newe.id = cfg_exp\n        newe.name = name\n        newe.description = desc\n        session.add(newe)\n        ret = newe\n    else:\n        exps.update({'name': name, 'description': desc})\n        ret = exps.first()\n    try:\n        session.commit()\n    except IntegrityError:\n        session.rollback()\n        persist_experiment(experiment)\n    return (ret, session)",
    "docstring": "Persist this experiment in the benchbuild database.\n\n    Args:\n        experiment: The experiment we want to persist."
  },
  {
    "code": "def _get_ngrams(n, text):\n  ngram_set = set()\n  text_length = len(text)\n  max_index_ngram_start = text_length - n\n  for i in range(max_index_ngram_start + 1):\n    ngram_set.add(tuple(text[i:i + n]))\n  return ngram_set",
    "docstring": "Calculates n-grams.\n\n  Args:\n    n: which n-grams to calculate\n    text: An array of tokens\n\n  Returns:\n    A set of n-grams"
  },
  {
    "code": "def cycles(self):\n        def walk_node(node, seen):\n            if node in seen:\n                yield (node,)\n                return\n            seen.add(node)\n            for edge in self.edges[node]:\n                for cycle in walk_node(edge, set(seen)):\n                    yield (node,) + cycle\n        cycles = chain.from_iterable(\n            (walk_node(node, set()) for node in self.nodes))\n        shortest = set()\n        for cycle in sorted(cycles, key=len):\n            for el in shortest:\n                if set(el).issubset(set(cycle)):\n                    break\n            else:\n                shortest.add(cycle)\n        return shortest",
    "docstring": "Fairly expensive cycle detection algorithm. This method\n        will return the shortest unique cycles that were detected.\n\n        Debug usage may look something like:\n\n        print(\"The following cycles were found:\")\n        for cycle in network.cycles():\n            print(\"    \", \" -> \".join(cycle))"
  },
  {
    "code": "def setProfile(self, name):\n        if self.name or self.useBegin:\n            if self.name == name:\n                return\n            raise VObjectError(\"This component already has a PROFILE or \"\n                               \"uses BEGIN.\")\n        self.name = name.upper()",
    "docstring": "Assign a PROFILE to this unnamed component.\n\n        Used by vCard, not by vCalendar."
  },
  {
    "code": "def path(self):\n        if isinstance(self.dir, Directory):\n            return self.dir._path\n        elif isinstance(self.dir, ROOT.TDirectory):\n            return self.dir.GetPath()\n        elif isinstance(self.dir, _FolderView):\n            return self.dir.path()\n        else:\n            return str(self.dir)",
    "docstring": "Get the path of the wrapped folder"
  },
  {
    "code": "def get_current_venv():\n        if 'VIRTUAL_ENV' in os.environ:\n            venv = os.environ['VIRTUAL_ENV']\n        elif os.path.exists('.python-version'):\n            try:\n                subprocess.check_output(['pyenv', 'help'], stderr=subprocess.STDOUT)\n            except OSError:\n                print(\"This directory seems to have pyenv's local venv, \"\n                      \"but pyenv executable was not found.\")\n            with open('.python-version', 'r') as f:\n                env_name = f.readline().strip()\n            bin_path = subprocess.check_output(['pyenv', 'which', 'python']).decode('utf-8')\n            venv = bin_path[:bin_path.rfind(env_name)] + env_name\n        else:\n            return None\n        return venv",
    "docstring": "Returns the path to the current virtualenv"
  },
  {
    "code": "def _parse_include(self, include):\n        ret = {}\n        for item in include:\n            if '.' in item:\n                local, remote = item.split('.', 1)\n            else:\n                local = item\n                remote = None\n            ret.setdefault(local, [])\n            if remote:\n                ret[local].append(remote)\n        return ret",
    "docstring": "Parse the querystring args or parent includes for includes.\n\n        :param include: Dict of query args or includes"
  },
  {
    "code": "def is_ipynb():\n    try:\n        shell = get_ipython().__class__.__name__\n        if shell == 'ZMQInteractiveShell':\n            return True\n        elif shell == 'TerminalInteractiveShell':\n            return False\n        else:\n            return False\n    except NameError:\n        return False",
    "docstring": "Return True if the module is running in IPython kernel,\n    False if in IPython shell or other Python shell.\n\n    Copied from: http://stackoverflow.com/a/37661854/1592810\n    There are other methods there too\n\n    >>> is_ipynb()\n    False"
  },
  {
    "code": "def sad(patch, cols, splits, clean=True):\n    (spp_col, count_col), patch = \\\n        _get_cols(['spp_col', 'count_col'], cols, patch)\n    full_spp_list = np.unique(patch.table[spp_col])\n    result_list = []\n    for substring, subpatch in _yield_subpatches(patch, splits):\n        sad_list = []\n        for spp in full_spp_list:\n            this_spp = (subpatch.table[spp_col] == spp)\n            count = np.sum(subpatch.table[count_col][this_spp])\n            sad_list.append(count)\n        subdf = pd.DataFrame({'spp': full_spp_list, 'y': sad_list})\n        if clean:\n            subdf = subdf[subdf['y'] > 0]\n        result_list.append((substring, subdf))\n    return result_list",
    "docstring": "Calculates an empirical species abundance distribution\n\n    Parameters\n    ----------\n    {0}\n    clean : bool\n        If True, all species with zero abundance are removed from SAD results.\n        Default False.\n\n    Returns\n    -------\n    {1} Result has two columns: spp (species identifier) and y (individuals of\n    that species).\n\n    Notes\n    -----\n    {2}\n\n    {3}\n\n    Examples\n    --------\n\n    {4}\n\n    >>> # Get the SAD of the full plot\n    >>> sad = meco.empirical.sad(pat, 'spp_col:spp; count_col:count', '')\n\n    >>> # Extract the SAD\n    >>> sad_df = sad[0][1]\n    >>> sad_df\n           spp     y\n    0    arsp1     2\n    1     cabr    31\n    2   caspi1    58\n    3     chst     1\n    4    comp1     5\n    5     cran     4\n    6     crcr    65\n    7    crsp2    79\n    8     enfa     1\n    9     gnwe    41\n    10   grass  1110\n    11   lesp1     1\n    12    magl     1\n    13    mesp     6\n    14    mobe     4\n    15    phdi   210\n    16   plsp1     1\n    17    pypo    73\n    18    sasp     2\n    19    ticr   729\n    20   unsh1     1\n    21   unsp1    18\n    22   unsp3     1\n    23   unsp4     1\n\n    >>> # Get SAD for 4 subplots within the full plot and keep absent species\n    >>> # using clean = False\n    >>> sad_subplots = meco.empirical.sad(pat, 'spp_col:spp; count_col:count', splits = \"row:2; column:2\", clean=False)\n    >>> len(sad_subplots)\n    4\n\n    >>> # Look at SAD in one of the 4 cells\n    >>> sad_subplots[0]\n    ('row>=-0.5; row<1.5; column>=-0.5; column<1.5',\n           spp    y\n    0    arsp1    0\n    1     cabr    7\n    2   caspi1    0\n    3     chst    1\n    4    comp1    1\n    5     cran    3\n    6     crcr   21\n    7    crsp2   16\n    8     enfa    0\n    9     gnwe    8\n    10   grass  236\n    11   lesp1    0\n    12    magl    0\n    13    mesp    4\n    14    mobe    0\n    15    phdi   33\n    16   plsp1    1\n    17    pypo    8\n    18    sasp    2\n    19    ticr  317\n    20   unsh1    1\n    21   unsp1    0\n    22   unsp3    1\n    23   unsp4    1)\n\n    See http://www.macroeco.org/tutorial_macroeco.html for additional\n    examples and explanation"
  },
  {
    "code": "def get_statistics(self):\n        return {\n            'cumulative_elapsed_time': self.get_cumulative_elapsed_time(),\n            'percentage': self.get_percentage(),\n            'n_splits': self.get_n_splits(),\n            'mean_per_split': self.get_mean_per_split(),\n        }",
    "docstring": "Get all statistics as a dictionary.\n\n        Returns\n        -------\n        statistics : Dict[str, List]"
  },
  {
    "code": "def generate_slug(self, model_instance):\n        queryset = model_instance.__class__._default_manager.all()\n        lookup = {'%s__regex' % self.attname: r'^.{%s}$' % self.length}\n        if queryset.filter(**lookup).count() >= len(self.chars)**self.length:\n            raise FieldError(\"No available slugs remaining.\")\n        slug = get_random_string(self.length, self.chars)\n        if model_instance.pk:\n            queryset = queryset.exclude(pk=model_instance.pk)\n        kwargs = {}\n        for params in model_instance._meta.unique_together:\n            if self.attname in params:\n                for param in params:\n                    kwargs[param] = getattr(model_instance, param, None)\n        kwargs[self.attname] = slug\n        while queryset.filter(**kwargs):\n            slug = get_random_string(self.length, self.chars)\n            kwargs[self.attname] = slug\n        return slug",
    "docstring": "Returns a unique slug."
  },
  {
    "code": "def aln_tree_seqs(seqs,\n                 input_handler=None,\n                 tree_type='neighborjoining',\n                 params={},\n                 add_seq_names=True,\n                 WorkingDir=tempfile.gettempdir(),\n                 SuppressStderr=None,\n                 SuppressStdout=None,\n                 max_hours=5.0,\n                 constructor=PhyloNode,\n                 clean_up=True\n                 ):\n    params[\"-maxhours\"] = max_hours\n    if tree_type:\n        params[\"-cluster2\"] = tree_type\n    params[\"-tree2\"] = get_tmp_filename(WorkingDir)\n    params[\"-out\"] = get_tmp_filename(WorkingDir)\n    muscle_res = muscle_seqs(seqs,\n                 input_handler=input_handler,\n                 params=params,\n                 add_seq_names=add_seq_names,\n                 WorkingDir=WorkingDir,\n                 SuppressStderr=SuppressStderr,\n                 SuppressStdout=SuppressStdout)\n    tree = DndParser(muscle_res[\"Tree2Out\"], constructor=constructor)\n    aln = [line for line in muscle_res[\"MuscleOut\"]]\n    if clean_up:\n        muscle_res.cleanUp()\n    return tree, aln",
    "docstring": "Muscle align sequences and report tree from iteration2.\n\n    Unlike cluster_seqs, returns tree2 which is the tree made during the\n    second muscle iteration (it should be more accurate that the cluster from\n    the first iteration which is made fast based on  k-mer words)\n\n    seqs: either file name or list of sequence objects or list of strings or\n        single multiline string containing sequences.\n    tree_type: can be either neighborjoining (default) or upgmb for UPGMA\n    clean_up: When true, will clean up output files"
  },
  {
    "code": "def update(self, global_size=None, lower_extent=None, upper_extent=None,\n        description=None):\n        if global_size is not None: self._global_size = global_size\n        if lower_extent is not None: self._lower_extent = lower_extent\n        if upper_extent is not None: self._upper_extent = upper_extent\n        if description is not None: self._description = description\n        self.validate()",
    "docstring": "Update the dimension properties\n\n        Parameters\n        ----------\n        global_size : int\n            Global dimension size (Default value = None)\n        lower_extent : int\n            Lower dimension extent (Default value = None)\n        upper_extent : int\n            Upper dimension extent (Default value = None)\n        description : str\n            Dimension description (Default value = None)"
  },
  {
    "code": "def setup():\n    index_template = BlogPost._index.as_template(ALIAS, PATTERN)\n    index_template.save()\n    if not BlogPost._index.exists():\n        migrate(move_data=False)",
    "docstring": "Create the index template in elasticsearch specifying the mappings and any\n    settings to be used. This can be run at any time, ideally at every new code\n    deploy."
  },
  {
    "code": "def initialize_path(self, path_num=None):\n        for c in self.consumers:\n            c.initialize_path(path_num)\n        self.state = [c.state for c in self.consumers]",
    "docstring": "make the consumer_state ready for the next MC path\n\n        :param int path_num:"
  },
  {
    "code": "def _readbin(fid, fmt='i', nwords=1, file64=False, unpack=True):\n    if fmt in 'if':\n        fmt += '8' if file64 else '4'\n    elts = np.fromfile(fid, fmt, nwords)\n    if unpack and len(elts) == 1:\n        elts = elts[0]\n    return elts",
    "docstring": "Read n words of 4 or 8 bytes with fmt format.\n\n    fmt: 'i' or 'f' or 'b' (integer or float or bytes)\n    4 or 8 bytes: depends on header\n\n    Return an array of elements if more than one element.\n\n    Default: read 1 word formatted as an integer."
  },
  {
    "code": "def common_package_action_options(f):\n    @click.option(\n        \"-s\",\n        \"--skip-errors\",\n        default=False,\n        is_flag=True,\n        help=\"Skip/ignore errors when copying packages.\",\n    )\n    @click.option(\n        \"-W\",\n        \"--no-wait-for-sync\",\n        default=False,\n        is_flag=True,\n        help=\"Don't wait for package synchronisation to complete before \" \"exiting.\",\n    )\n    @click.option(\n        \"-I\",\n        \"--wait-interval\",\n        default=5.0,\n        type=float,\n        show_default=True,\n        help=\"The time in seconds to wait between checking synchronisation.\",\n    )\n    @click.option(\n        \"--sync-attempts\",\n        default=3,\n        type=int,\n        help=\"Number of times to attempt package synchronisation. If the \"\n        \"package fails the first time, the client will attempt to \"\n        \"automatically resynchronise it.\",\n    )\n    @click.pass_context\n    @functools.wraps(f)\n    def wrapper(ctx, *args, **kwargs):\n        return ctx.invoke(f, *args, **kwargs)\n    return wrapper",
    "docstring": "Add common options for package actions."
  },
  {
    "code": "def get_cursors(source, spelling):\n    cursors = []\n    children = []\n    if isinstance(source, Cursor):\n        children = source.get_children()\n    else:\n        children = source.cursor.get_children()\n    for cursor in children:\n        if cursor.spelling == spelling:\n            cursors.append(cursor)\n        cursors.extend(get_cursors(cursor, spelling))\n    return cursors",
    "docstring": "Obtain all cursors from a source object with a specific spelling.\n\n    This provides a convenient search mechanism to find all cursors with specific\n    spelling within a source. The first argument can be either a\n    TranslationUnit or Cursor instance.\n\n    If no cursors are found, an empty list is returned."
  },
  {
    "code": "def get_available_plugins(self):\n        available_plugins = []\n        PluginData = namedtuple('PluginData', 'name, plugin_class, conf, is_allowed_to_fail')\n        for plugin_request in self.plugins_conf:\n            plugin_name = plugin_request['name']\n            try:\n                plugin_class = self.plugin_classes[plugin_name]\n            except KeyError:\n                if plugin_request.get('required', True):\n                    msg = (\"no such plugin: '%s', did you set \"\n                           \"the correct plugin type?\") % plugin_name\n                    exc = PluginFailedException(msg)\n                    self.on_plugin_failed(plugin_name, exc)\n                    logger.error(msg)\n                    raise exc\n                else:\n                    logger.warning(\"plugin '%s' requested but not available\",\n                                   plugin_name)\n                    continue\n            plugin_is_allowed_to_fail = plugin_request.get('is_allowed_to_fail',\n                                                           getattr(plugin_class,\n                                                                   \"is_allowed_to_fail\", True))\n            plugin_conf = plugin_request.get(\"args\", {})\n            plugin = PluginData(plugin_name,\n                                plugin_class,\n                                plugin_conf,\n                                plugin_is_allowed_to_fail)\n            available_plugins.append(plugin)\n        return available_plugins",
    "docstring": "check requested plugins availability\n        and handle missing plugins\n\n        :return: list of namedtuples, runnable plugins data"
  },
  {
    "code": "def Validate(self, value):\n    if value is None:\n      return None\n    if not isinstance(value, self.rdfclass):\n      try:\n        r = self.rdfclass()\n        r.FromDict(value)\n        return r\n      except (AttributeError, TypeError, rdfvalue.InitializeError):\n        raise TypeValueError(\"Value for arg %s should be an %s\" %\n                             (self.name, self.rdfclass.__name__))\n    return value",
    "docstring": "Validate the value.\n\n    Args:\n      value: Value is expected to be a dict-like object that a given RDFStruct\n        can be initialized from.\n\n    Raises:\n      TypeValueError: If the value is not a valid dict-like object that a given\n        RDFStruct can be initialized from.\n\n    Returns:\n      A valid instance of self.rdfclass or None."
  },
  {
    "code": "def create_from_name_and_dictionary(self, name, datas):\n        category = ObjectCategory(name)\n        self.set_common_datas(category, name, datas)\n        if \"order\" in datas:\n            category.order = int(datas[\"order\"])\n        return category",
    "docstring": "Return a populated object Category from dictionary datas"
  },
  {
    "code": "def schedule_job(date, callable_name, content_object=None, expires='7d',\n                 args=(), kwargs={}):\n    assert callable_name and isinstance(callable_name, basestring), callable_name\n    if isinstance(date, basestring):\n        date = parse_timedelta(date)\n    if isinstance(date, datetime.timedelta):\n        date = datetime.datetime.now() + date\n    job = ScheduledJob(callable_name=callable_name, time_slot_start=date)\n    if expires:\n        if isinstance(expires, basestring):\n            expires = parse_timedelta(expires)\n        if isinstance(expires, datetime.timedelta):\n            expires = date + expires\n        job.time_slot_end = expires\n    if content_object:\n        job.content_object = content_object\n    job.args = args\n    job.kwargs = kwargs\n    job.save()\n    return job",
    "docstring": "Schedule a job.\n\n    `date` may be a datetime.datetime or a datetime.timedelta.\n\n    The callable to be executed may be specified in two ways:\n     - set `callable_name` to an identifier ('mypackage.myapp.some_function').\n     - specify an instance of a model as content_object and set\n       `callable_name` to a method name ('do_job')\n\n    The scheduler will not attempt to run the job if its expiration date has\n    passed."
  },
  {
    "code": "def prepare_for_reraise(error, exc_info=None):\n    if not hasattr(error, \"_type_\"):\n        if exc_info is None:\n            exc_info = sys.exc_info()\n        error._type_ = exc_info[0]\n        error._traceback = exc_info[2]\n    return error",
    "docstring": "Prepares the exception for re-raising with reraise method.\n\n    This method attaches type and traceback info to the error object\n    so that reraise can properly reraise it using this info."
  },
  {
    "code": "def call(self, rs, name, user, fields):\n        if name not in self._objects:\n            return '[ERR: Object Not Found]'\n        func = self._objects[name]\n        reply = ''\n        try:\n            reply = func(rs, fields)\n            if reply is None:\n                reply = ''\n        except Exception as e:\n            raise PythonObjectError(\"Error executing Python object: \" + str(e))\n        return text_type(reply)",
    "docstring": "Invoke a previously loaded object.\n\n        :param RiveScript rs: the parent RiveScript instance.\n        :param str name: The name of the object macro to be called.\n        :param str user: The user ID invoking the object macro.\n        :param []str fields: Array of words sent as the object's arguments.\n\n        :return str: The output of the object macro."
  },
  {
    "code": "def _register_key(fingerprint, gpg):\n    for private_key in gpg.list_keys(True):\n        try:\n            if str(fingerprint) == private_key['fingerprint']:\n                config[\"gpg_key_fingerprint\"] = \\\n                    repr(private_key['fingerprint'])\n        except KeyError:\n            pass",
    "docstring": "Registers key in config"
  },
  {
    "code": "def lazyread(f, delimiter):\n    try:\n        running = f.read(0)\n    except Exception as e:\n        if e.__class__.__name__ == 'IncompleteReadError':\n            running = b''\n        else:\n            raise\n    while True:\n        new_data = f.read(1024)\n        if not new_data:\n            yield running\n            return\n        running += new_data\n        while delimiter in running:\n            curr, running = running.split(delimiter, 1)\n            yield curr + delimiter",
    "docstring": "Generator which continually reads ``f`` to the next instance\n    of ``delimiter``.\n\n    This allows you to do batch processing on the contents of ``f`` without\n    loading the entire file into memory.\n\n    :param f: Any file-like object which has a ``.read()`` method.\n    :param delimiter: Delimiter on which to split up the file."
  },
  {
    "code": "def getBoundsColor(self, nNumOutputColors, flCollisionBoundsFadeDistance):\n        fn = self.function_table.getBoundsColor\n        pOutputColorArray = HmdColor_t()\n        pOutputCameraColor = HmdColor_t()\n        fn(byref(pOutputColorArray), nNumOutputColors, flCollisionBoundsFadeDistance, byref(pOutputCameraColor))\n        return pOutputColorArray, pOutputCameraColor",
    "docstring": "Get the current chaperone bounds draw color and brightness"
  },
  {
    "code": "def split_by_percent(self, spin_systems_list):\n        chunk_sizes = [int((i*len(spin_systems_list))/100) for i in self.plsplit]\n        if sum(chunk_sizes) < len(spin_systems_list):\n            difference = len(spin_systems_list) - sum(chunk_sizes)\n            chunk_sizes[chunk_sizes.index(min(chunk_sizes))] += difference\n        assert sum(chunk_sizes) == len(spin_systems_list), \\\n            \"sum of chunk sizes must be equal to spin systems list length.\"\n        intervals = self.calculate_intervals(chunk_sizes)\n        chunks_of_spin_systems_by_percentage = [itertools.islice(spin_systems_list, *interval) for interval in intervals]\n        return chunks_of_spin_systems_by_percentage",
    "docstring": "Split list of spin systems by specified percentages.\n\n        :param list spin_systems_list: List of spin systems.\n        :return: List of spin systems divided into sub-lists corresponding to specified split percentages.\n        :rtype: :py:class:`list`"
  },
  {
    "code": "def port_type(arg):\n\terror_msg = \"{0} is not a valid port\".format(repr(arg))\n\ttry:\n\t\targ = ast.literal_eval(arg)\n\texcept ValueError:\n\t\traise argparse.ArgumentTypeError(error_msg)\n\tif arg < 0 or arg > 65535:\n\t\traise argparse.ArgumentTypeError(error_msg)\n\treturn arg",
    "docstring": "An argparse type representing a tcp or udp port number."
  },
  {
    "code": "def relevant_kwargs(function, exclude_keys='self', exclude_values=None,\n                    extra_values=None):\n    args = function_args(function)\n    locals_values = function_kwargs(function_index=2, exclude_keys=exclude_keys)\n    if extra_values:\n        locals_values.update(extra_values)\n    return {k: v for k, v in locals_values.items() if k in args}",
    "docstring": "This will return a dictionary of local variables that are parameters to the\n    function provided in the arg.\n\n    Example:\n     function(**relevant_kwargs(function))\n\n    :param function:       function to select parameters for\n    :param exclude_keys:   str,list,func if not a function it will be converted\n                           into a funciton, defaults to excluding None\n    :param exclude_values: obj,list,func if not a function it will be convereted\n                           into one, defaults to excluding 'self'\n    :param extra_values:   dict of other values to include with local\n    :return:               dict of local variables for the function"
  },
  {
    "code": "def list_images(self):\n        response = []\n        for im in self.d.images():\n            try:\n                i_name, tag = parse_reference(im[\"RepoTags\"][0])\n            except (IndexError, TypeError):\n                i_name, tag = None, None\n            d_im = DockerImage(i_name, tag=tag, identifier=im[\"Id\"],\n                               pull_policy=DockerImagePullPolicy.NEVER)\n            inspect_to_metadata(d_im.metadata, im)\n            response.append(d_im)\n        return response",
    "docstring": "List all available docker images.\n\n        Image objects returned from this methods will contain a limited\n        amount of metadata in property `short_metadata`. These are just a subset\n        of `.inspect()`, but don't require an API call against dockerd.\n\n        :return: collection of instances of :class:`conu.DockerImage`"
  },
  {
    "code": "def int_subtype(i, bits, signed) :\n        \"returns integer i after checking that it fits in the given number of bits.\"\n        if not isinstance(i, int) :\n            raise TypeError(\"value is not int: %s\" % repr(i))\n        if signed :\n            lo = - 1 << bits - 1\n            hi = (1 << bits - 1) - 1\n        else :\n            lo = 0\n            hi = (1 << bits) - 1\n        if i < lo or i > hi :\n            raise ValueError \\\n              (\n                \"%d not in range of %s %d-bit value\" % (i, (\"unsigned\", \"signed\")[signed], bits)\n              )\n        return \\\n            i",
    "docstring": "returns integer i after checking that it fits in the given number of bits."
  },
  {
    "code": "def get_multi(\n        self, keys, missing=None, deferred=None, transaction=None, eventual=False\n    ):\n        if not keys:\n            return []\n        ids = set(key.project for key in keys)\n        for current_id in ids:\n            if current_id != self.project:\n                raise ValueError(\"Keys do not match project\")\n        if transaction is None:\n            transaction = self.current_transaction\n        entity_pbs = _extended_lookup(\n            datastore_api=self._datastore_api,\n            project=self.project,\n            key_pbs=[key.to_protobuf() for key in keys],\n            eventual=eventual,\n            missing=missing,\n            deferred=deferred,\n            transaction_id=transaction and transaction.id,\n        )\n        if missing is not None:\n            missing[:] = [\n                helpers.entity_from_protobuf(missed_pb) for missed_pb in missing\n            ]\n        if deferred is not None:\n            deferred[:] = [\n                helpers.key_from_protobuf(deferred_pb) for deferred_pb in deferred\n            ]\n        return [helpers.entity_from_protobuf(entity_pb) for entity_pb in entity_pbs]",
    "docstring": "Retrieve entities, along with their attributes.\n\n        :type keys: list of :class:`google.cloud.datastore.key.Key`\n        :param keys: The keys to be retrieved from the datastore.\n\n        :type missing: list\n        :param missing: (Optional) If a list is passed, the key-only entities\n                        returned by the backend as \"missing\" will be copied\n                        into it. If the list is not empty, an error will occur.\n\n        :type deferred: list\n        :param deferred: (Optional) If a list is passed, the keys returned\n                         by the backend as \"deferred\" will be copied into it.\n                         If the list is not empty, an error will occur.\n\n        :type transaction:\n            :class:`~google.cloud.datastore.transaction.Transaction`\n        :param transaction: (Optional) Transaction to use for read consistency.\n                            If not passed, uses current transaction, if set.\n\n        :type eventual: bool\n        :param eventual: (Optional) Defaults to strongly consistent (False).\n                         Setting True will use eventual consistency, but cannot\n                         be used inside a transaction or will raise ValueError.\n\n        :rtype: list of :class:`google.cloud.datastore.entity.Entity`\n        :returns: The requested entities.\n        :raises: :class:`ValueError` if one or more of ``keys`` has a project\n                 which does not match our project.\n        :raises: :class:`ValueError` if eventual is True and in a transaction."
  },
  {
    "code": "def set_transmit_mode(self, mode):\n        self.api.call_rc('port setTransmitMode {} {}'.format(mode, self.uri))",
    "docstring": "set port transmit mode\n\n        :param mode: request transmit mode\n        :type mode: ixexplorer.ixe_port.IxeTransmitMode"
  },
  {
    "code": "def public_url(self):\n        return \"{storage_base_url}/{bucket_name}/{quoted_name}\".format(\n            storage_base_url=_API_ACCESS_ENDPOINT,\n            bucket_name=self.bucket.name,\n            quoted_name=quote(self.name.encode(\"utf-8\")),\n        )",
    "docstring": "The public URL for this blob.\n\n        Use :meth:`make_public` to enable anonymous access via the returned\n        URL.\n\n        :rtype: `string`\n        :returns: The public URL for this blob."
  },
  {
    "code": "def count(self):\n        sql = u'SELECT count() FROM (%s)' % self.as_sql()\n        raw = self._database.raw(sql)\n        return int(raw) if raw else 0",
    "docstring": "Returns the number of rows after aggregation."
  },
  {
    "code": "def parse_yaml_node(self, y):\n        if 'participant' not in y:\n            raise InvalidParticipantNodeError\n        self.target_component = TargetComponent().parse_yaml_node(y['participant'])\n        return self",
    "docstring": "Parse a YAML specification of a participant into this object."
  },
  {
    "code": "def get_search_results(self, request, queryset, search_term):\n        def construct_search(field_name):\n            if field_name.startswith('^'):\n                return \"%s__istartswith\" % field_name[1:]\n            elif field_name.startswith('='):\n                return \"%s__iexact\" % field_name[1:]\n            elif field_name.startswith('@'):\n                return \"%s__search\" % field_name[1:]\n            else:\n                return \"%s__icontains\" % field_name\n        use_distinct = False\n        if self.search_fields and search_term:\n            orm_lookups = [construct_search(str(search_field))\n                           for search_field in self.search_fields]\n            for bit in search_term.split():\n                or_queries = [models.Q(**{orm_lookup: bit})\n                              for orm_lookup in orm_lookups]\n                queryset = queryset.filter(reduce(operator.or_, or_queries))\n            if not use_distinct:\n                for search_spec in orm_lookups:\n                    if lookup_needs_distinct(self.opts, search_spec):\n                        use_distinct = True\n                        break\n        return queryset, use_distinct",
    "docstring": "Returns a tuple containing a queryset to implement the search,\n        and a boolean indicating if the results may contain duplicates."
  },
  {
    "code": "def determine_emitter(self, request, *args, **kwargs):\n        em = kwargs.pop('emitter_format', None)\n        if not em:\n            em = request.GET.get('format', 'json')\n        return em",
    "docstring": "Function for determening which emitter to use\n        for output. It lives here so you can easily subclass\n        `Resource` in order to change how emission is detected.\n\n        You could also check for the `Accept` HTTP header here,\n        since that pretty much makes sense. Refer to `Mimer` for\n        that as well."
  },
  {
    "code": "def _scheduling_block_config(num_blocks=5, start_sbi_id=0, start_pb_id=0,\n                             project='sip'):\n    pb_id = start_pb_id\n    for sb_id, sbi_id in _scheduling_block_ids(num_blocks, start_sbi_id,\n                                               project):\n        sub_array_id = 'subarray-{:02d}'.format(random.choice(range(5)))\n        config = dict(id=sbi_id,\n                      sched_block_id=sb_id,\n                      sub_array_id=sub_array_id,\n                      processing_blocks=_generate_processing_blocks(pb_id))\n        pb_id += len(config['processing_blocks'])\n        yield config",
    "docstring": "Return a Scheduling Block Configuration dictionary"
  },
  {
    "code": "def add(self, operator):\n        if not isinstance(operator, (BaseTaskTransformer, FeatureExtractor)):\n            raise ParameterError('operator={} must be one of '\n                                 '(BaseTaskTransformer, FeatureExtractor)'\n                                 .format(operator))\n        if operator.name in self.opmap:\n            raise ParameterError('Duplicate operator name detected: '\n                                 '{}'.format(operator))\n        super(Pump, self).add(operator)\n        self.opmap[operator.name] = operator\n        self.ops.append(operator)",
    "docstring": "Add an operation to this pump.\n\n        Parameters\n        ----------\n        operator : BaseTaskTransformer, FeatureExtractor\n            The operation to add\n\n        Raises\n        ------\n        ParameterError\n            if `op` is not of a correct type"
  },
  {
    "code": "def sys_call(cmd):\n    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)\n    return p.stdout.readlines(), p.stderr.readlines()",
    "docstring": "Execute cmd and capture stdout and stderr\n\n    :param cmd: command to be executed\n    :return: (stdout, stderr)"
  },
  {
    "code": "def egg_name(self):\n        filename = \"%s-%s-py%s\" % (\n            to_filename(self.project_name), to_filename(self.version),\n            self.py_version or PY_MAJOR\n        )\n        if self.platform:\n            filename += '-' + self.platform\n        return filename",
    "docstring": "Return what this distribution's standard .egg filename should be"
  },
  {
    "code": "def flipwritable(fn, mode=None):\n    if os.access(fn, os.W_OK):\n        return None\n    old_mode = os.stat(fn).st_mode\n    os.chmod(fn, stat.S_IWRITE | old_mode)\n    return old_mode",
    "docstring": "Flip the writability of a file and return the old mode. Returns None\n    if the file is already writable."
  },
  {
    "code": "def delta_to_str(rd):\n    parts = []\n    if rd.days > 0:\n        parts.append(\"%d day%s\" % (rd.days, plural(rd.days)))\n    clock_parts = []\n    if rd.hours > 0:\n        clock_parts.append(\"%02d\" % rd.hours)\n    if rd.minutes > 0 or rd.hours > 0:\n        clock_parts.append(\"%02d\" % rd.minutes)\n    if rd.seconds > 0 or rd.minutes > 0 or rd.hours > 0:\n        clock_parts.append(\"%02d\" % rd.seconds)\n    if clock_parts:\n        parts.append(\":\".join(clock_parts))\n    return \" \".join(parts)",
    "docstring": "Convert a relativedelta to a human-readable string"
  },
  {
    "code": "def delete_line(self):\r\n        cursor = self.textCursor()\r\n        if self.has_selected_text():\r\n            self.extend_selection_to_complete_lines()\r\n            start_pos, end_pos = cursor.selectionStart(), cursor.selectionEnd()\r\n            cursor.setPosition(start_pos)\r\n        else:\r\n            start_pos = end_pos = cursor.position()\r\n        cursor.beginEditBlock()\r\n        cursor.setPosition(start_pos)\r\n        cursor.movePosition(QTextCursor.StartOfBlock)\r\n        while cursor.position() <= end_pos:\r\n            cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)\r\n            if cursor.atEnd():\r\n                break\r\n            cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor)\r\n        cursor.removeSelectedText()\r\n        cursor.endEditBlock()\r\n        self.ensureCursorVisible()",
    "docstring": "Delete current line"
  },
  {
    "code": "def brpop(self, keys, timeout=0):\n        if timeout is None:\n            timeout = 0\n        keys = list_or_args(keys, None)\n        keys.append(timeout)\n        return self.execute_command('BRPOP', *keys)",
    "docstring": "RPOP a value off of the first non-empty list\n        named in the ``keys`` list.\n\n        If none of the lists in ``keys`` has a value to RPOP, then block\n        for ``timeout`` seconds, or until a value gets pushed on to one\n        of the lists.\n\n        If timeout is 0, then block indefinitely."
  },
  {
    "code": "def get_raw_query(self):\n        query = self.base_query.copy()\n        search_query = self.search_query.copy()\n        query.update(search_query)\n        sorting = self.resolve_sorting(query)\n        query.update(sorting)\n        catalog = api.get_tool(self.catalog_name)\n        sort_on = query.get(\"sort_on\", None)\n        if sort_on and not self.is_sortable_index(sort_on, catalog):\n            del(query[\"sort_on\"])\n        return query",
    "docstring": "Returns the raw query to use for current search, based on the\n        base query + update query"
  },
  {
    "code": "def get_repos(path):\n    p = str(path)\n    ret = []\n    if not os.path.exists(p):\n        return ret\n    for d in os.listdir(p):\n        pd = os.path.join(p, d)\n        if os.path.exists(pd) and is_repo(pd):\n            ret.append(Local(pd))\n    return ret",
    "docstring": "Returns list of found branches.\n\n    :return: List of grit.Local objects"
  },
  {
    "code": "def alphabetize_attributes(self):\n        self.attributes.sort(key=lambda name: (name == self.class_attr_name, name))",
    "docstring": "Orders attributes names alphabetically, except for the class attribute, which is kept last."
  },
  {
    "code": "def exclude(self, col: str, val):\n        try:\n            self.df = self.df[self.df[col] != val]\n        except Exception as e:\n            self.err(e, \"Can not exclude rows based on value \" + str(val))",
    "docstring": "Delete rows based on value\n\n        :param col: column name\n        :type col: str\n        :param val: value to delete\n        :type val: any\n\n        :example: ``ds.exclude(\"Col 1\", \"value\")``"
  },
  {
    "code": "def match_function_pattern(self, first, rest=None, least=1, offset=0):\n        if not self.has_space(offset=offset):\n            return ''\n        firstchar = self.string[self.pos + offset]\n        if not first(firstchar):\n            return ''\n        output = [firstchar]\n        pattern = first if rest is None else rest\n        for char in self.string[self.pos + offset + 1:]:\n            if pattern(char):\n                output.append(char)\n            else:\n                break\n        if len(output) < least:\n            return ''\n        return ''.join(output)",
    "docstring": "Match each char sequentially from current SourceString position\n        until the pattern doesnt match and return all maches.\n\n        Integer argument least defines and minimum amount of chars that can\n        be matched.\n\n        This version takes functions instead of string patterns.\n        Each function must take one argument, a string, and return a\n        value that can be evauluated as True or False.\n\n        If rest is defined then first is used only to match the first arg\n        and the rest of the chars are matched against rest."
  },
  {
    "code": "def rename(self, req, parent, name, newparent, newname):\n        self.reply_err(req, errno.EROFS)",
    "docstring": "Rename a file\n\n        Valid replies:\n            reply_err"
  },
  {
    "code": "def replace_characters(self, text, characters, replacement=''):\n        if not characters:\n            return text\n        characters = ''.join(sorted(characters))\n        if characters in self._characters_regexes:\n            characters_regex = self._characters_regexes[characters]\n        else:\n            characters_regex = re.compile(\"[%s]\" % re.escape(characters))\n            self._characters_regexes[characters] = characters_regex\n        return characters_regex.sub(replacement, text)",
    "docstring": "Remove characters from text.\n\n        Removes custom characters from input text or replaces them\n        with a string if specified.\n\n        Args:\n            text: The text to be processed.\n            characters: Characters that will be replaced.\n            replacement: New text that will replace the custom characters.\n\n        Returns:\n            The text without the given characters."
  },
  {
    "code": "def guest_get_console_output(self, userid):\n        action = \"get the console output of guest '%s'\" % userid\n        with zvmutils.log_and_reraise_sdkbase_error(action):\n            output = self._vmops.get_console_output(userid)\n        return output",
    "docstring": "Get the console output of the guest virtual machine.\n\n        :param str userid: the user id of the vm\n        :returns: console log string\n        :rtype: str"
  },
  {
    "code": "def _unpack(self, record, key, expected):\n        attrs = record.get(key)\n        if attrs is None:\n            return\n        obj = unpack_from_dynamodb(\n            attrs=attrs,\n            expected=expected,\n            model=self.model,\n            engine=self.engine\n        )\n        object_loaded.send(self.engine, engine=self.engine, obj=obj)\n        record[key] = obj",
    "docstring": "Replaces the attr dict at the given key with an instance of a Model"
  },
  {
    "code": "def removi(item, inset):\n    assert isinstance(inset, stypes.SpiceCell)\n    assert inset.dtype == 2\n    item = ctypes.c_int(item)\n    libspice.removi_c(item, ctypes.byref(inset))",
    "docstring": "Remove an item from an integer set.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/removi_c.html\n\n    :param item: Item to be removed.\n    :type item: int\n    :param inset: Set to be updated.\n    :type inset: spiceypy.utils.support_types.SpiceCell"
  },
  {
    "code": "def get_channel_info(self):\n        self.request(EP_GET_CHANNEL_INFO)\n        return {} if self.last_response is None else self.last_response.get('payload')",
    "docstring": "Get the current channel info."
  },
  {
    "code": "def register(self, endpoint, scheme=None, handler=None, **kwargs):\n        assert endpoint is not None, \"endpoint is required\"\n        if endpoint is TChannel.FALLBACK:\n            decorator = partial(self._handler.register, TChannel.FALLBACK)\n            if handler is not None:\n                return decorator(handler)\n            else:\n                return decorator\n        if not scheme:\n            if inspect.ismodule(endpoint):\n                scheme = \"thrift\"\n            else:\n                scheme = \"raw\"\n        scheme = scheme.lower()\n        if scheme == 'thrift':\n            decorator = partial(self._register_thrift, endpoint, **kwargs)\n        else:\n            decorator = partial(\n                self._register_simple, endpoint, scheme, **kwargs\n            )\n        if handler is not None:\n            return decorator(handler)\n        else:\n            return decorator",
    "docstring": "Register a handler with this TChannel.\n\n        This may be used as a decorator:\n\n        .. code-block:: python\n\n            app = TChannel(name='bar')\n\n            @app.register(\"hello\", \"json\")\n            def hello_handler(request, response):\n                params = yield request.get_body()\n\n        Or as a function:\n\n        .. code-block:: python\n\n            # Here we have a Thrift handler for `Foo::hello`\n            app.register(Foo, \"hello\", hello_thrift_handler)\n\n        :param endpoint:\n            Name of the endpoint being registered. This should be a reference\n            to the Thrift-generated module if this is a Thrift endpoint. It\n            may also be ``TChannel.FALLBACK`` if it's intended to be a\n            catch-all endpoint.\n        :param scheme:\n            Name of the scheme under which the endpoint is being registered.\n            One of \"raw\", \"json\", and \"thrift\". Defaults to \"raw\", except if\n            \"endpoint\" was a module, in which case this defaults to \"thrift\".\n\n        :param handler:\n            If specified, this is the handler function. If ignored, this\n            function returns a decorator that can be used to register the\n            handler function.\n\n        :returns:\n            If ``handler`` was specified, this returns ``handler``. Otherwise,\n            it returns a decorator that can be applied to a function to\n            register it as the handler."
  },
  {
    "code": "def converter(input_string, block_size=2):\n    sentences = textprocessing.getSentences(input_string)\n    blocks = textprocessing.getBlocks(sentences, block_size)\n    parse.makeIdentifiers(blocks)",
    "docstring": "The cli tool as a built-in function.\n\n    :param input_string: A string that should be converted to a set of facts.\n    :type input_string: str.\n    :param blocks_size: Optional block size of sentences (Default: 2).\n    :type block_size: int."
  },
  {
    "code": "def _process_response(self, response):\n        rsp_lines = response.rstrip('\\r\\n').split('\\r')\n        if len(rsp_lines) > 0:\n            echoed_command = rsp_lines[0]\n            del rsp_lines[0]\n        else:\n            echoed_command = None\n        if len(rsp_lines) > 0 and \\\n                rsp_lines[0] in ('*INVALID_ADDRESS', '*INVALID_DATA', \\\n                '*INVALID_DATA_HIGH', '*INVALID_DATA_LOW', \\\n                '*UNDEFINED_LABEL'):\n            err = rsp_lines[0][1:]\n            del rsp_lines[0]\n        else:\n            err = None\n        return [response, echoed_command, err, rsp_lines]",
    "docstring": "Processes a response from the drive.\n\n        Processes the response returned from the drive. It is broken\n        down into the echoed command (drive echoes it back), any error\n        returned by the drive (leading '*' is stripped), and the\n        different lines of the response.\n\n        Parameters\n        ----------\n        response : str\n            The response returned by the drive.\n\n        Returns\n        -------\n        processed_response : list\n            A 4-element ``list``. The elements, in order, are `response`\n            (``str``), the echoed command (``str``), any error response\n            (``None`` if none, or the ``str`` of the error), and the\n            lines of the response that are not the echo or error line\n            (``list`` of ``str`` with newlines stripped)."
  },
  {
    "code": "def from_config(self, k, v):\n        if k == \"setup\":\n            return from_commandline(v, classname=to_commandline(datagen.DataGenerator()))\n        return super(DataGenerator, self).from_config(k, v)",
    "docstring": "Hook method that allows converting values from the dictionary.\n\n        :param k: the key in the dictionary\n        :type k: str\n        :param v: the value\n        :type v: object\n        :return: the potentially parsed value\n        :rtype: object"
  },
  {
    "code": "def rollback_migration(engine, connection, path, migration_to_rollback):\n    migrations_applied = get_migrations_applied(engine, connection)\n    if not is_applied(migrations_applied, migration_to_rollback):\n        raise RuntimeError(\n            '`%s` is not in the list of previously applied migrations.' % (migration_to_rollback))\n    file = path + migration_to_rollback + '/down.sql'\n    check_exists(file)\n    basename = os.path.basename(os.path.dirname(file))\n    source = get_migration_source(file)\n    run_migration(connection, source, engine)\n    delete_migration(connection, basename)\n    print('   -> Migration `%s` has been rolled back' % (basename))\n    return True",
    "docstring": "Rollback a migration"
  },
  {
    "code": "def _as_dict(self) -> Dict[str, JsonTypes]:\n        return {k: v._as_dict if isinstance(v, JsonObj) else\n                   self.__as_list(v) if isinstance(v, list) else\n                   v for k, v in self.__dict__.items()}",
    "docstring": "Convert a JsonObj into a straight dictionary\n\n        :return: dictionary that cooresponds to the json object"
  },
  {
    "code": "def image_coarsen(xlevel=0, ylevel=0, image=\"auto\", method='average'):\n    if image == \"auto\": image = _pylab.gca().images[0]\n    Z = _n.array(image.get_array())\n    global image_undo_list\n    image_undo_list.append([image, Z])\n    if len(image_undo_list) > 10: image_undo_list.pop(0)\n    image.set_array(_fun.coarsen_matrix(Z, ylevel, xlevel, method))\n    _pylab.draw()",
    "docstring": "This will coarsen the image data by binning each xlevel+1 along the x-axis\n    and each ylevel+1 points along the y-axis\n\n    type can be 'average', 'min', or 'max'"
  },
  {
    "code": "def make_type_consistent(s1, s2):\n    if isinstance(s1, str) and isinstance(s2, str):\n        return s1, s2\n    elif isinstance(s1, unicode) and isinstance(s2, unicode):\n        return s1, s2\n    else:\n        return unicode(s1), unicode(s2)",
    "docstring": "If both objects aren't either both string or unicode instances force them to unicode"
  },
  {
    "code": "def write_metadata(self, handler):\n        if self.metadata is not None:\n            handler.write_metadata(self.cname, self.metadata)",
    "docstring": "set the meta data"
  },
  {
    "code": "async def read_frame(self) -> DataFrame:\n        if self._data_frames.qsize() == 0 and self.closed:\n            raise StreamConsumedError(self.id)\n        frame = await self._data_frames.get()\n        self._data_frames.task_done()\n        if frame is None:\n            raise StreamConsumedError(self.id)\n        return frame",
    "docstring": "Read a single frame from the local buffer.\n\n        If no frames are available but the stream is still open, waits until\n        more frames arrive. Otherwise, raises StreamConsumedError.\n\n        When a stream is closed, a single `None` is added to the data frame\n        Queue to wake up any waiting `read_frame` coroutines."
  },
  {
    "code": "def _write(self, session, openFile, replaceParamFile):\n        timeSeries = self.timeSeries\n        numTS = len(timeSeries)\n        valList = []\n        for tsNum, ts in enumerate(timeSeries):\n            values = ts.values\n            for value in values:\n                valDict = {'time': value.simTime,\n                           'tsNum': tsNum,\n                           'value': value.value}\n                valList.append(valDict)\n        result = pivot(valList, ('time',), ('tsNum',), 'value')\n        for line in result:\n            valString = ''\n            for n in range(0, numTS):\n                val = '%.6f' % line[(n,)]\n                valString = '%s%s%s' % (\n                    valString,\n                    ' ' * (13 - len(str(val))),\n                    val)\n            openFile.write('   %.8f%s\\n' % (line['time'], valString))",
    "docstring": "Generic Time Series Write to File Method"
  },
  {
    "code": "def destroy_volume_snapshot(volume_id, snapshot_id, profile, **libcloud_kwargs):\n    conn = _get_driver(profile=profile)\n    libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs)\n    volume = _get_by_id(conn.list_volumes(), volume_id)\n    snapshot = _get_by_id(conn.list_volume_snapshots(volume), snapshot_id)\n    return conn.destroy_volume_snapshot(snapshot, **libcloud_kwargs)",
    "docstring": "Destroy a volume snapshot.\n\n    :param volume_id:  Volume ID from which the snapshot belongs\n    :type  volume_id: ``str``\n\n    :param snapshot_id:  Volume Snapshot ID from which to destroy\n    :type  snapshot_id: ``str``\n\n    :param profile: The profile key\n    :type  profile: ``str``\n\n    :param libcloud_kwargs: Extra arguments for the driver's destroy_volume_snapshot method\n    :type  libcloud_kwargs: ``dict``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion libcloud_compute.destroy_volume_snapshot snap1 profile1"
  },
  {
    "code": "def group_join(self, inner_iterable, outer_key_selector=identity, inner_key_selector=identity,\n             result_selector=lambda outer, grouping: grouping):\n        if self.closed():\n            raise ValueError(\"Attempt to call group_join() on a closed Queryable.\")\n        if not is_iterable(inner_iterable):\n            raise TypeError(\"Cannot compute group_join() with inner_iterable of non-iterable {type}\".format(\n                    type=str(type(inner_iterable))[7: -1]))\n        if not is_callable(outer_key_selector):\n            raise TypeError(\"group_join() parameter outer_key_selector={outer_key_selector} is not callable\".format(\n                    outer_key_selector=repr(outer_key_selector)))\n        if not is_callable(inner_key_selector):\n            raise TypeError(\"group_join() parameter inner_key_selector={inner_key_selector} is not callable\".format(\n                    inner_key_selector=repr(inner_key_selector)))\n        if not is_callable(result_selector):\n            raise TypeError(\"group_join() parameter result_selector={result_selector} is not callable\".format(\n                    result_selector=repr(result_selector)))\n        return self._create(self._generate_group_join_result(inner_iterable, outer_key_selector,\n                                                       inner_key_selector, result_selector))",
    "docstring": "Match elements of two sequences using keys and group the results.\n\n        The group_join() query produces a hierarchical result, with all of the\n        inner elements in the result grouped against the matching outer\n        element.\n\n        The order of elements from outer is maintained. For each of these the\n        order of elements from inner is also preserved.\n\n        Note: This method uses deferred execution.\n\n        Args:\n            inner_iterable: The sequence to join with the outer sequence.\n\n            outer_key_selector: An optional unary function to extract keys from\n                elements of the outer (source) sequence. The first positional\n                argument of the function should accept outer elements and the\n                result value should be the key. If omitted, the identity\n                function is used.\n\n            inner_key_selector: An optional  unary function to extract keys\n                from elements of the inner_iterable. The first positional\n                argument of the function should accept outer elements and the\n                result value should be the key.  If omitted, the identity\n                function is used.\n\n            result_selector: An optional binary function to create a result\n                element from an outer element and the Grouping of matching\n                inner elements. The first positional argument is the outer\n                elements and the second in the Grouping of inner elements\n                which match the outer element according to the key selectors\n                used. If omitted, the result elements will be the Groupings\n                directly.\n\n        Returns:\n            A Queryable over a sequence with one element for each group in the\n            result as returned by the result_selector. If the default result\n            selector is used, the result is a sequence of Grouping objects.\n\n        Raises:\n            ValueError: If the Queryable has been closed.\n            TypeError: If the inner_iterable is not in fact iterable.\n            TypeError: If the outer_key_selector is not callable.\n            TypeError: If the inner_key_selector is not callable.\n            TypeError: If the result_selector is not callable."
  },
  {
    "code": "def unindent(self, lines):\n        indent = min(\n            len(self.re.match(r'^ *', line).group()) for line in lines)\n        return [line[indent:].rstrip() for line in lines]",
    "docstring": "Removes any indentation that is common to all of the given lines."
  },
  {
    "code": "def _split_scheme(expression):\n        match = re.search(r'^([a-z]+):(.*)$', expression)\n        if not match:\n            scheme = 'plain'\n            actual = expression\n        else:\n            scheme = match.group(1)\n            actual = match.group(2)\n        return scheme, actual",
    "docstring": "Splits the scheme and actual expression\n\n        :param str expression: The expression.\n\n        :rtype: str"
  },
  {
    "code": "def listFigures(self,walkTrace=tuple(),case=None,element=None):\n        if case == 'sectionmain': print(walkTrace,self.title)\n        if case == 'figure':\n            caption,fig = element\n            try:\n                print(walkTrace,fig._leopardref,caption)\n            except AttributeError:\n                fig._leopardref = next(self._reportSection._fignr)\n                print(walkTrace,fig._leopardref,caption)",
    "docstring": "List section figures."
  },
  {
    "code": "def enable_policies(zap_helper, policy_ids):\n    if not policy_ids:\n        policy_ids = _get_all_policy_ids(zap_helper)\n    with zap_error_handler():\n        zap_helper.enable_policies_by_ids(policy_ids)",
    "docstring": "Set the enabled policies to use in a scan.\n\n    When you enable a selection of policies, all other policies are\n    disabled."
  },
  {
    "code": "def login_details(self):\n        if not self.__login_details:\n            self.__login_details = LoginDetails(self.__connection)\n        return self.__login_details",
    "docstring": "Gets the login details\n\n        Returns:\n        List of login details"
  },
  {
    "code": "def make_ring_filename(self, source_name, ring, galprop_run):\n        format_dict = self.__dict__.copy()\n        format_dict['sourcekey'] = self._name_factory.galprop_ringkey(source_name=source_name,\n                                                                      ringkey=\"ring_%i\" % ring)\n        format_dict['galprop_run'] = galprop_run\n        return self._name_factory.galprop_gasmap(**format_dict)",
    "docstring": "Make the name of a gasmap file for a single ring\n\n        Parameters\n        ----------\n\n        source_name : str\n            The galprop component, used to define path to gasmap files\n        ring : int\n            The ring index\n        galprop_run : str\n            String identifying the galprop parameters"
  },
  {
    "code": "def mark_bool_flags_as_mutual_exclusive(flag_names, required=False,\n                                        flag_values=_flagvalues.FLAGS):\n  for flag_name in flag_names:\n    if not flag_values[flag_name].boolean:\n      raise _exceptions.ValidationError(\n          'Flag --{} is not Boolean, which is required for flags used in '\n          'mark_bool_flags_as_mutual_exclusive.'.format(flag_name))\n  def validate_boolean_mutual_exclusion(flags_dict):\n    flag_count = sum(bool(val) for val in flags_dict.values())\n    if flag_count == 1 or (not required and flag_count == 0):\n      return True\n    raise _exceptions.ValidationError(\n        '{} one of ({}) must be True.'.format(\n            'Exactly' if required else 'At most', ', '.join(flag_names)))\n  register_multi_flags_validator(\n      flag_names, validate_boolean_mutual_exclusion, flag_values=flag_values)",
    "docstring": "Ensures that only one flag among flag_names is True.\n\n  Args:\n    flag_names: [str], names of the flags.\n    required: bool. If true, exactly one flag must be True. Otherwise, at most\n        one flag can be True, and it is valid for all flags to be False.\n    flag_values: flags.FlagValues, optional FlagValues instance where the flags\n        are defined."
  },
  {
    "code": "def convert(data):\n    if isinstance(data, unicode):\n        return data.encode('utf-8')\n    elif isinstance(data, str):\n        return data\n    elif isinstance(data, collections.Mapping):\n        return dict(map(convert, data.iteritems()))\n    elif isinstance(data, collections.Iterable):\n        return type(data)(map(convert, data))\n    else:\n        return data",
    "docstring": "convert a standalone unicode string or unicode strings in a\n    mapping or iterable into byte strings."
  },
  {
    "code": "def import_string_code_as_module(code):\n    sha256 = hashlib.sha256(code.encode('UTF-8')).hexdigest()\n    module = imp.new_module(sha256)\n    try:\n        exec_(code, module.__dict__)\n    except Exception as e:\n        raise exceptions.UserError('User code exception', exception_message=str(e))\n    sys.modules[sha256] = module\n    return module",
    "docstring": "Used to run arbitrary passed code as a module\n\n    Args:\n        code (string): Python code to import as module\n\n    Returns:\n        module: Python module"
  },
  {
    "code": "def html_content(self):\n        hilite = CodeHiliteExtension(linenums=False, css_class='highlight')\n        extras = ExtraExtension()\n        markdown_content = markdown(self.content, extensions=[hilite, extras])\n        oembed_content = parse_html(\n            markdown_content,\n            oembed_providers,\n            urlize_all=True,\n            maxwidth=app.config['SITE_WIDTH'])\n        return Markup(oembed_content)",
    "docstring": "Generate HTML representation of the markdown-formatted blog entry,\n        and also convert any media URLs into rich media objects such as video\n        players or images."
  },
  {
    "code": "def _exception_for(self, code):\n        if code in self.errors:\n            return self.errors[code]\n        elif 500 <= code < 599:\n            return exceptions.RemoteServerError\n        else:\n            return exceptions.UnknownError",
    "docstring": "Return the exception class suitable for the specified HTTP\n        status code.\n\n        Raises:\n            UnknownError: The HTTP status code is not one of the knowns."
  },
  {
    "code": "def freeze():\n    echo_waiting('Verifying collected packages...')\n    catalog, errors = make_catalog()\n    if errors:\n        for error in errors:\n            echo_failure(error)\n        abort()\n    static_file = get_agent_requirements()\n    echo_info('Static file: {}'.format(static_file))\n    pre_packages = list(read_packages(static_file))\n    catalog.write_packages(static_file)\n    post_packages = list(read_packages(static_file))\n    display_package_changes(pre_packages, post_packages)",
    "docstring": "Combine all dependencies for the Agent's static environment."
  },
  {
    "code": "def get_model_filepath(self, infodict):\n        u = infodict['uniprot_ac']\n        original_filename = '{}_{}_{}_{}'.format(infodict['from'], infodict['to'],\n                                                 infodict['template'], infodict['coordinate_id'])\n        file_path = op.join(self.metadata_dir, u[:2], u[2:4], u[4:6],\n                            'swissmodel', '{}.pdb'.format(original_filename))\n        if op.exists(file_path):\n            return file_path\n        else:\n            log.warning('{}: no file {} found for model'.format(u, file_path))\n            return None",
    "docstring": "Get the path to the homology model using information from the index dictionary for a single model.\n\n        Example: use self.get_models(UNIPROT_ID) to get all the models, which returns a list of dictionaries.\n            Use one of those dictionaries as input to this function to get the filepath to the model itself.\n\n        Args:\n            infodict (dict): Information about a model from get_models\n\n        Returns:\n            str: Path to homology model"
  },
  {
    "code": "def get_atoms(self, inc_alt_states=False):\n        if inc_alt_states:\n            return itertools.chain(*[x[1].values() for x in sorted(list(self.states.items()))])\n        return self.atoms.values()",
    "docstring": "Returns all atoms in the `Monomer`.\n\n        Parameters\n        ----------\n        inc_alt_states : bool, optional\n            If `True`, will return `Atoms` for alternate states."
  },
  {
    "code": "def list_buckets(self, instance):\n        response = self._client.get_proto(path='/buckets/' + instance)\n        message = rest_pb2.ListBucketsResponse()\n        message.ParseFromString(response.content)\n        buckets = getattr(message, 'bucket')\n        return iter([\n            Bucket(bucket, instance, self) for bucket in buckets])",
    "docstring": "List the buckets for an instance.\n\n        :param str instance: A Yamcs instance name.\n        :rtype: ~collections.Iterable[.Bucket]"
  },
  {
    "code": "def __DeclareMessageAlias(self, schema, alias_for):\n        message = extended_descriptor.ExtendedMessageDescriptor()\n        message.name = self.__names.ClassName(schema['id'])\n        message.alias_for = alias_for\n        self.__DeclareDescriptor(message.name)\n        self.__AddImport('from %s import extra_types' %\n                         self.__base_files_package)\n        self.__RegisterDescriptor(message)",
    "docstring": "Declare schema as an alias for alias_for."
  },
  {
    "code": "def _get_doc_by_line_offset(self, doc_id):\n        bounds = self._get_meta()[str(doc_id)].bounds\n        return xml_utils.load_chunk(self.filename, bounds, slow=True)",
    "docstring": "Load document from xml using line offset information.\n        This is much slower than _get_doc_by_raw_offset but should\n        work everywhere."
  },
  {
    "code": "def safe_setattr(obj, name, value):\n    try:\n        setattr(obj, name, value)\n        return True\n    except AttributeError:\n        return False",
    "docstring": "Attempt to setattr but catch AttributeErrors."
  },
  {
    "code": "def set_deployment_run_id(self):\n        log = logging.getLogger(self.cls_logger + '.set_deployment_run_id')\n        deployment_run_id_val = self.get_value('cons3rt.deploymentRun.id')\n        if not deployment_run_id_val:\n            log.debug('Deployment run ID not found in deployment properties')\n            return\n        try:\n            deployment_run_id = int(deployment_run_id_val)\n        except ValueError:\n            log.debug('Deployment run ID found was unable to convert to an int: {d}'.format(d=deployment_run_id_val))\n            return\n        self.deployment_run_id = deployment_run_id\n        log.info('Found deployment run ID: {i}'.format(i=str(self.deployment_run_id)))",
    "docstring": "Sets the deployment run ID from deployment properties\n\n        :return: None"
  },
  {
    "code": "def debug_video_writer_factory(output_dir):\n  if FLAGS.disable_ffmpeg:\n    return common_video.IndividualFrameWriter(output_dir)\n  else:\n    output_path = os.path.join(output_dir, \"video.avi\")\n    return common_video.WholeVideoWriter(\n        fps=10, output_path=output_path, file_format=\"avi\"\n    )",
    "docstring": "Creates a VideoWriter for debug videos."
  },
  {
    "code": "def revoke(self, token, pipe=None):\n      p = self.redis.pipeline() if pipe is None else pipe    \n      formatted_token = self.format_token(token)\n      try:         \n         p.watch(formatted_token)\n         key = p.get(formatted_token)\n         formatted_key = self.format_key(key)\n         p.multi()\n         p.delete(formatted_key, formatted_token)\n         if pipe is None:\n            if not p.execute()[-1]:\n               raise RevokeError(token, 'token not found')         \n      except WatchError:\n         raise\n      finally:\n         if pipe is None:\n            p.reset()",
    "docstring": "\\\n      Revokes the key associated with the given revokation token.\n\n      If the token does not exist, a :class:`KeyError <KeyError>` is thrown. \n      Otherwise `None` is returned.\n\n      If `pipe` is given, then a :class:`RevokeError <shorten.RevokeError>` \n      will not be thrown if the key does not exist. The n-th from last result\n      should be checked like so:\n\n      ::\n\n         pipe = redis.Pipeline()\n         store.revoke(token, pipe=pipe)\n        \n         results = pipe.execute()\n         if not results[-1]:\n            raise RevokeError(token)\n         \n\n      :param pipe:   a Redis pipeline. If `None`, the token will\n                     be revoked immediately. Otherwise they must be\n                     extracted from the pipeline results (see above)."
  },
  {
    "code": "def get_all():\n    ret = []\n    service = _cmd()\n    for svc in __salt__['cmd.run']('{0} ls all'.format(service)).splitlines():\n        ret.append(svc)\n    return sorted(ret)",
    "docstring": "Return all installed services.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' service.get_all"
  },
  {
    "code": "def sam_pair_to_insert(s1, s2):\n    if s1.is_unmapped or s2.is_unmapped or (s1.tid != s2.tid) or (s1.is_reverse == s2.is_reverse):\n        return None\n    if s1.is_reverse:\n        end = s1.reference_end - 1\n        start = s2.reference_start\n    else:\n        end = s2.reference_end - 1\n        start = s1.reference_start\n    if start < end:\n        return end - start + 1\n    else:\n        return None",
    "docstring": "Returns insert size from pair of sam records, as long as their orientation is \"innies\".\n       Otherwise returns None."
  },
  {
    "code": "def save(self, out_path):\n        out = {\n            'selectors': [str(x) for x in self.selectors],\n            'trace': [{'stream': str(DataStream.FromEncoded(x.stream)), 'time': x.raw_time, 'value': x.value, 'reading_id': x.reading_id} for x in self]\n        }\n        with open(out_path, \"wb\") as outfile:\n            json.dump(out, outfile, indent=4)",
    "docstring": "Save an ascii representation of this simulation trace.\n\n        Args:\n            out_path (str): The output path to save this simulation trace."
  },
  {
    "code": "def dumps_bytes(obj):\n    b = dumps(obj)\n    if isinstance(b, unicode):\n        b = b.encode(\"ascii\")\n    return b",
    "docstring": "Serialize ``obj`` to JSON formatted ``bytes``."
  },
  {
    "code": "def deconstruct(self, including_private: bool=False) -> bytes:\n        data = self._deconstruct_v1(including_private=including_private)\n        return compress_datablob(DATA_BLOB_MAGIC, 1, data)",
    "docstring": "Return state of this FinTSClient instance as an opaque datablob. You should not\n        use this object after calling this method.\n\n        Information about the connection is implicitly retrieved from the bank and\n        cached in the FinTSClient. This includes: system identifier, bank parameter\n        data, user parameter data. It's not strictly required to retain this information\n        across sessions, but beneficial. If possible, an API user SHOULD use this method\n        to serialize the client instance before destroying it, and provide the serialized\n        data next time an instance is constructed.\n\n        Parameter `including_private` should be set to True, if the storage is sufficiently\n        secure (with regards to confidentiality) to include private data, specifically,\n        account numbers and names. Most often this is the case.\n\n        Note: No connection information is stored in the datablob, neither is the PIN."
  },
  {
    "code": "def proj_units_to_meters(proj_str):\n    proj_parts = proj_str.split()\n    new_parts = []\n    for itm in proj_parts:\n        key, val = itm.split('=')\n        key = key.strip('+')\n        if key in ['a', 'b', 'h']:\n            val = float(val)\n            if val < 6e6:\n                val *= 1000.\n                val = '%.3f' % val\n        if key == 'units' and val == 'km':\n            continue\n        new_parts.append('+%s=%s' % (key, val))\n    return ' '.join(new_parts)",
    "docstring": "Convert projection units from kilometers to meters."
  },
  {
    "code": "def buildWorkbenchWithLauncher():\n    workbench = ui.Workbench()\n    tools = [exercises.SearchTool()]\n    launcher = ui.Launcher(workbench, tools)\n    workbench.display(launcher)\n    return workbench, launcher",
    "docstring": "Builds a workbench.\n\n    The workbench has a launcher with all of the default tools. The\n    launcher will be displayed on the workbench."
  },
  {
    "code": "def simulate(self):\n        return [t.simulate() for t in itertools.islice(self, random.choice(range(10)))]",
    "docstring": "Simulates a stream of types."
  },
  {
    "code": "def register_base_assets(self):\n        from abilian.web import assets as bundles\n        self.register_asset(\"css\", bundles.LESS)\n        self.register_asset(\"js-top\", bundles.TOP_JS)\n        self.register_asset(\"js\", bundles.JS)\n        self.register_i18n_js(*bundles.JS_I18N)",
    "docstring": "Register assets needed by Abilian.\n\n        This is done in a separate method in order to allow applications\n        to redefine it at will."
  },
  {
    "code": "def get_script_str(self, reset=True):\n        s = \"\\n\".join(l for l in self._lines)\n        if reset:\n            self.reset()\n        return s",
    "docstring": "Returns a string with the script and reset the editor if reset is True"
  },
  {
    "code": "def _load_lsm_data(self, data_var,\n                       conversion_factor=1,\n                       calc_4d_method=None,\n                       calc_4d_dim=None,\n                       time_step=None):\n        data = self.xd.lsm.getvar(data_var,\n                                  yslice=self.yslice,\n                                  xslice=self.xslice,\n                                  calc_4d_method=calc_4d_method,\n                                  calc_4d_dim=calc_4d_dim)\n        if isinstance(time_step, datetime):\n            data = data.loc[{self.lsm_time_dim: [pd.to_datetime(time_step)]}]\n        elif time_step is not None:\n            data = data[{self.lsm_time_dim: [time_step]}]\n        data = data.fillna(0)\n        data.values *= conversion_factor\n        return data",
    "docstring": "This extracts the LSM data from a folder of netcdf files"
  },
  {
    "code": "def parse(self, data, charset=None):\n        charset = charset or self.charset\n        return self._parse_data(data, charset)",
    "docstring": "Parse the data.\n\n        It is usually a better idea to override ``_parse_data()`` than\n        this method in derived classes.\n\n        :param charset: the charset of the data. Uses datamapper's\n        default (``self.charset``) if not given.\n        :returns:"
  },
  {
    "code": "def get_item_type(self, ttype):\n        for i in self.map_item:\n            if TYPE_MAP_ITEM[i.get_type()] == ttype:\n                return i.get_item()\n        return None",
    "docstring": "Get a particular item type\n\n            :param ttype: a string which represents the desired type\n\n            :rtype: None or the item object"
  },
  {
    "code": "def remote_command(function, self, *args, **kwargs):\n    try:\n        return function(self, *args, **kwargs)\n    except RuntimeError, exception:\n        error_message = str(exception)\n        match = CRE_REMOTE_ERROR.match(error_message)\n        if match:\n            command_code = int(match.group('command_int'))\n            return_code = int(match.group('return_code_int'))\n            raise FirmwareError(command_code, return_code)\n        match = CRE_REMOTE_COMMAND_ERROR.match(error_message)\n        if match:\n            command_code = int(match.group('command_int'))\n            command_name = NAMES_BY_COMMAND_CODE[command_code]\n            raise RuntimeError(CRE_REMOTE_COMMAND_ERROR.sub(command_name,\n                                                            error_message))\n        raise",
    "docstring": "Catch `RuntimeError` exceptions raised by remote control board firmware\n    commands and re-raise as more specific `FirmwareError` exception type,\n    which includes command code and return code."
  },
  {
    "code": "def _use_remote_connection(self, kwargs):\n        kwargs['host'] = kwargs.get('host')\n        kwargs['username'] = kwargs.get('username')\n        kwargs['password'] = kwargs.get('password')\n        if kwargs['host'] is None or \\\n           kwargs['username'] is None or \\\n           kwargs['password'] is None:\n            return False\n        else:\n            return True",
    "docstring": "Determine if connection is local or remote"
  },
  {
    "code": "def resolve_type_spec(self, name, lineno):\n        if name in self.type_specs:\n            return self.type_specs[name].link(self)\n        if '.' in name:\n            include_name, component = name.split('.', 1)\n            if include_name in self.included_scopes:\n                return self.included_scopes[include_name].resolve_type_spec(\n                    component, lineno\n                )\n        raise ThriftCompilerError(\n            'Unknown type \"%s\" referenced at line %d%s' % (\n                name, lineno, self.__in_path()\n            )\n        )",
    "docstring": "Finds and links the TypeSpec with the given name."
  },
  {
    "code": "def IsImage(self, filename):\n\t\tmimetype =  mimetypes.guess_type(filename)[0]\n\t\tif not mimetype:\n\t\t\treturn False\n\t\treturn mimetype.startswith(\"image/\")",
    "docstring": "Returns true if the filename has an image extension."
  },
  {
    "code": "def install(self, xmlpath):\n        from os import path\n        fullpath = path.abspath(path.expanduser(xmlpath))\n        if path.isfile(fullpath):\n            repo = RepositorySettings(self, fullpath)\n            if repo.name.lower() not in self.repositories:\n                self.installed.append(fullpath)\n                self._save_installed()\n                self.archive[repo.name.lower()] = {}\n                self._save_archive()\n                self.repositories[repo.name.lower()] = repo\n        else:\n            warn(\"The file {} does not exist; install aborted.\".format(fullpath))",
    "docstring": "Installs the repository at the specified XML path as an additional\n        repo to monitor pull requests for."
  },
  {
    "code": "def __sepApp(self, IDs, aspList):\n        sep, app = self.dyn.immediateAspects(self.obj.id, aspList)\n        if sep is None or app is None:\n            return False\n        else:\n            sepCondition = sep['id'] in IDs\n            appCondition = app['id'] in IDs\n            return sepCondition == appCondition == True",
    "docstring": "Returns true if the object last and next movement are\n        separations and applications to objects in list IDs.\n        It only considers aspects in aspList.\n        \n        This function is static since it does not test if the next\n        application will be indeed perfected. It considers only\n        a snapshot of the chart and not its astronomical movement."
  },
  {
    "code": "def _create_content_element(self, content, data_property_value):\n        content_element = self.html_parser.create_element('span')\n        content_element.set_attribute(\n            AccessibleCSSImplementation.DATA_ISOLATOR_ELEMENT,\n            'true'\n        )\n        content_element.set_attribute(\n            AccessibleCSSImplementation.DATA_SPEAK_AS,\n            data_property_value\n        )\n        content_element.append_text(content)\n        return content_element",
    "docstring": "Create a element to show the content.\n\n        :param content: The text content of element.\n        :type content: str\n        :param data_property_value: The value of custom attribute used to\n                                    identify the fix.\n        :type data_property_value: str\n        :return: The element to show the content.\n        :rtype: hatemile.util.html.htmldomelement.HTMLDOMElement"
  },
  {
    "code": "def user(self, username=None):\n        if username is None:\n            username = self.__getUsername()\n        parsedUsername = urlparse.quote(username)\n        url = self.root + \"/%s\" % parsedUsername\n        return User(url=url,\n                    securityHandler=self._securityHandler,\n                    proxy_url=self._proxy_url,\n                    proxy_port=self._proxy_port,\n                    initialize=False)",
    "docstring": "A user resource that represents a registered user in the portal."
  },
  {
    "code": "def validate(self, raw_data, **kwargs):\n        super(DateTimeField, self).validate(raw_data, **kwargs)\n        try:\n            if isinstance(raw_data, datetime.datetime):\n                self.converted = raw_data\n            elif self.serial_format is None:\n                self.converted = parse(raw_data)\n            else:\n                self.converted = datetime.datetime.strptime(raw_data,\n                                                            self.serial_format)\n            return raw_data\n        except (ParseError, ValueError) as e:\n            msg = self.messages['parse'] % dict(cls=self.__class__.__name__,\n                                                data=raw_data,\n                                                format=self.serial_format)\n            raise ValidationException(msg, raw_data)",
    "docstring": "The raw_data is returned unchanged."
  },
  {
    "code": "def new_event(self, event_data: str) -> None:\n        event = self.parse_event_xml(event_data)\n        if EVENT_OPERATION in event:\n            self.manage_event(event)",
    "docstring": "New event to process."
  },
  {
    "code": "def autoencoder_ordered_text_small():\n  hparams = autoencoder_ordered_text()\n  hparams.bottleneck_bits = 32\n  hparams.num_hidden_layers = 3\n  hparams.hidden_size = 64\n  hparams.max_hidden_size = 512\n  hparams.bottleneck_noise = 0.0\n  hparams.autoregressive_mode = \"conv5\"\n  hparams.sample_height = 4\n  return hparams",
    "docstring": "Ordered discrete autoencoder model for text, small version."
  },
  {
    "code": "def _d2f(self, x):\n        d2f_dPg2 = lil_matrix((self._ng, 1))\n        d2f_dQg2 = lil_matrix((self._ng, 1))\n        for i in self._ipol:\n            p_cost = list(self._gn[i].p_cost)\n            d2f_dPg2[i, 0] = polyval(polyder(p_cost, 2),\n                self._Pg.v0[i] * self._base_mva) * self._base_mva**2\n        i = r_[range(self._Pg.i1, self._Pg.iN + 1),\n               range(self._Qg.i1, self._Qg.iN + 1)]\n        d2f = csr_matrix((vstack([d2f_dPg2, d2f_dQg2]).toarray().flatten(),\n                          (i, i)), shape=(self._nxyz, self._nxyz))\n        return d2f",
    "docstring": "Evaluates the cost Hessian."
  },
  {
    "code": "def os_release(package, base='essex', reset_cache=False):\n    global _os_rel\n    if reset_cache:\n        reset_os_release()\n    if _os_rel:\n        return _os_rel\n    _os_rel = (\n        get_os_codename_package(package, fatal=False) or\n        get_os_codename_install_source(config('openstack-origin')) or\n        base)\n    return _os_rel",
    "docstring": "Returns OpenStack release codename from a cached global.\n\n    If reset_cache then unset the cached os_release version and return the\n    freshly determined version.\n\n    If the codename can not be determined from either an installed package or\n    the installation source, the earliest release supported by the charm should\n    be returned."
  },
  {
    "code": "async def _trim_old_connections(\n        new_name: str, con_type: CONNECTION_TYPES) -> Tuple[bool, str]:\n    existing_cons = await connections(for_type=con_type)\n    not_us = [c['name'] for c in existing_cons if c['name'] != new_name]\n    ok = True\n    res = []\n    for c in not_us:\n        this_ok, remove_res = await remove(name=c)\n        ok = ok and this_ok\n        if not this_ok:\n            log.warning(\"Could not remove wifi connection {}: {}\"\n                        .format(c, remove_res))\n            res.append(remove_res)\n        else:\n            log.debug(\"Removed old wifi connection {}\".format(c))\n    return ok, ';'.join(res)",
    "docstring": "Delete all connections of con_type but the one specified."
  },
  {
    "code": "def _stream_output(process):\n    exit_code = None\n    while exit_code is None:\n        stdout = process.stdout.readline().decode(\"utf-8\")\n        sys.stdout.write(stdout)\n        exit_code = process.poll()\n    if exit_code != 0:\n        raise RuntimeError(\"Process exited with code: %s\" % exit_code)\n    return exit_code",
    "docstring": "Stream the output of a process to stdout\n\n    This function takes an existing process that will be polled for output. Only stdout\n    will be polled and sent to sys.stdout.\n\n    Args:\n        process(subprocess.Popen): a process that has been started with\n            stdout=PIPE and stderr=STDOUT\n\n    Returns (int): process exit code"
  },
  {
    "code": "def process_temperature_sensors(helper, session):\n        snmp_result_temp_sensor_names = helper.walk_snmp_values(\n            session, helper,\n            DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_location'], \"temperature sensors\")\n        snmp_result_temp_sensor_states = helper.walk_snmp_values(\n            session, helper,\n            DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_status'], \"temperature sensors\")\n        snmp_result_temp_sensor_values = helper.walk_snmp_values(\n            session, helper,\n            DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_reading'], \"temperature sensors\")\n        for i, _result in enumerate(snmp_result_temp_sensor_states):\n            helper.update_status(\n                helper, probe_check(snmp_result_temp_sensor_names[i],\n                                    snmp_result_temp_sensor_states[i], \"Temperature sensor\"))\n            if i < len(snmp_result_temp_sensor_values):\n                helper.add_metric(label=snmp_result_temp_sensor_names[i] + \" -Celsius-\",\n                                  value=float(snmp_result_temp_sensor_values[i]) / 10)",
    "docstring": "process the temperature sensors"
  },
  {
    "code": "def pop(self):\n        if self.next is None:\n            raise SimEmptyCallStackError(\"Cannot pop a frame from an empty call stack.\")\n        new_list = self.next.copy({})\n        if self.state is not None:\n            self.state.register_plugin('callstack', new_list)\n            self.state.history.recent_stack_actions.append(CallStackAction(\n                hash(new_list), len(new_list), 'pop', ret_site_addr=self.ret_addr\n            ))\n        return new_list",
    "docstring": "Pop the top frame from the stack. Return the new stack."
  },
  {
    "code": "def _set_data(self, coors, ngroups, conns, mat_ids, descs, nodal_bcs=None):\n        self.coors = nm.ascontiguousarray(coors)\n        if ngroups is None:\n            self.ngroups = nm.zeros((self.coors.shape[0],), dtype=nm.int32)\n        else:\n            self.ngroups = nm.ascontiguousarray(ngroups)\n        self.conns = [nm.asarray(conn, dtype=nm.int32) for conn in conns]\n        self.mat_ids = [nm.asarray(mat_id, dtype=nm.int32)\n                        for mat_id in mat_ids]\n        self.descs = descs\n        self.nodal_bcs = get_default(nodal_bcs, {})",
    "docstring": "Set mesh data.\n\n        Parameters\n        ----------\n        coors : array\n            Coordinates of mesh nodes.\n        ngroups : array\n            Node groups.\n        conns : list of arrays\n            The array of mesh elements (connectivities) for each element group.\n        mat_ids : list of arrays\n            The array of material ids for each element group.\n        descs: list of strings\n            The element type for each element group.\n        nodal_bcs : dict of arrays, optional\n            The nodes defining regions for boundary conditions referred\n            to by the dict keys in problem description files."
  },
  {
    "code": "def _make_ndarray_function(handle, name, func_name):\n    code, doc_str = _generate_ndarray_function_code(handle, name, func_name)\n    local = {}\n    exec(code, None, local)\n    ndarray_function = local[func_name]\n    ndarray_function.__name__ = func_name\n    ndarray_function.__doc__ = doc_str\n    ndarray_function.__module__ = 'mxnet.ndarray'\n    return ndarray_function",
    "docstring": "Create a NDArray function from the FunctionHandle."
  },
  {
    "code": "def get_classes(modName):\n    classNames = []\n    for name, obj in inspect.getmembers(sys.modules[modName]):\n        if inspect.isclass(obj):\n            classNames.append(name)\n    return classNames",
    "docstring": "return a list of all classes in a module."
  },
  {
    "code": "def project_stored_info_type_path(cls, project, stored_info_type):\n        return google.api_core.path_template.expand(\n            \"projects/{project}/storedInfoTypes/{stored_info_type}\",\n            project=project,\n            stored_info_type=stored_info_type,\n        )",
    "docstring": "Return a fully-qualified project_stored_info_type string."
  },
  {
    "code": "def PortPathMatcher(cls, port_path):\n        if isinstance(port_path, str):\n            port_path = [int(part) for part in SYSFS_PORT_SPLIT_RE.split(port_path)]\n        return lambda device: device.port_path == port_path",
    "docstring": "Returns a device matcher for the given port path."
  },
  {
    "code": "def one_hot(x:Collection[int], c:int):\n    \"One-hot encode `x` with `c` classes.\"\n    res = np.zeros((c,), np.float32)\n    res[listify(x)] = 1.\n    return res",
    "docstring": "One-hot encode `x` with `c` classes."
  },
  {
    "code": "def get_cookie(self, name):\n        if self.w3c:\n            try:\n                return self.execute(Command.GET_COOKIE, {'name': name})['value']\n            except NoSuchCookieException:\n                return None\n        else:\n            cookies = self.get_cookies()\n            for cookie in cookies:\n                if cookie['name'] == name:\n                    return cookie\n            return None",
    "docstring": "Get a single cookie by name. Returns the cookie if found, None if not.\n\n        :Usage:\n            ::\n\n                driver.get_cookie('my_cookie')"
  },
  {
    "code": "def saveToClipboard(sheet, rows, filetype=None):\n    'copy rows from sheet to system clipboard'\n    filetype = filetype or options.save_filetype\n    vs = copy(sheet)\n    vs.rows = rows\n    status('copying rows to clipboard')\n    clipboard().save(vs, filetype)",
    "docstring": "copy rows from sheet to system clipboard"
  },
  {
    "code": "def wait_for_service_tasks_all_changed(\n        service_name,\n        old_task_ids,\n        task_predicate=None,\n        timeout_sec=120\n):\n    return time_wait(\n        lambda: tasks_all_replaced_predicate(service_name, old_task_ids, task_predicate),\n        timeout_seconds=timeout_sec)",
    "docstring": "Returns once ALL of old_task_ids have been replaced with new tasks\n\n        :param service_name: the service name\n        :type service_name: str\n        :param old_task_ids: list of original task ids as returned by get_service_task_ids\n        :type old_task_ids: [str]\n        :param task_predicate: filter to use when searching for tasks\n        :type task_predicate: func\n        :param timeout_sec: duration to wait\n        :type timeout_sec: int\n\n        :return: the duration waited in seconds\n        :rtype: int"
  },
  {
    "code": "def get_freq(self):\n        if not self.is_monotonic or not self.index._is_unique:\n            return None\n        delta = self.deltas[0]\n        if _is_multiple(delta, _ONE_DAY):\n            return self._infer_daily_rule()\n        if self.hour_deltas in ([1, 17], [1, 65], [1, 17, 65]):\n            return 'BH'\n        elif not self.is_unique_asi8:\n            return None\n        delta = self.deltas_asi8[0]\n        if _is_multiple(delta, _ONE_HOUR):\n            return _maybe_add_count('H', delta / _ONE_HOUR)\n        elif _is_multiple(delta, _ONE_MINUTE):\n            return _maybe_add_count('T', delta / _ONE_MINUTE)\n        elif _is_multiple(delta, _ONE_SECOND):\n            return _maybe_add_count('S', delta / _ONE_SECOND)\n        elif _is_multiple(delta, _ONE_MILLI):\n            return _maybe_add_count('L', delta / _ONE_MILLI)\n        elif _is_multiple(delta, _ONE_MICRO):\n            return _maybe_add_count('U', delta / _ONE_MICRO)\n        else:\n            return _maybe_add_count('N', delta)",
    "docstring": "Find the appropriate frequency string to describe the inferred\n        frequency of self.values\n\n        Returns\n        -------\n        str or None"
  },
  {
    "code": "def _get_segment(self, start, request_size, check_response=True):\n    end = start + request_size - 1\n    content_range = '%d-%d' % (start, end)\n    headers = {'Range': 'bytes=' + content_range}\n    status, resp_headers, content = yield self._api.get_object_async(\n        self._path, headers=headers)\n    def _checker():\n      errors.check_status(status, [200, 206], self._path, headers,\n                          resp_headers, body=content)\n      self._check_etag(resp_headers.get('etag'))\n    if check_response:\n      _checker()\n      raise ndb.Return(content)\n    raise ndb.Return(content, _checker)",
    "docstring": "Get a segment of the file from Google Storage.\n\n    Args:\n      start: start offset of the segment. Inclusive. Have to be within the\n        range of the file.\n      request_size: number of bytes to request. Have to be small enough\n        for a single urlfetch request. May go over the logical range of the\n        file.\n      check_response: True to check the validity of GCS response automatically\n        before the future returns. False otherwise. See Yields section.\n\n    Yields:\n      If check_response is True, the segment [start, start + request_size)\n      of the file.\n      Otherwise, a tuple. The first element is the unverified file segment.\n      The second element is a closure that checks response. Caller should\n      first invoke the closure before consuing the file segment.\n\n    Raises:\n      ValueError: if the file has changed while reading."
  },
  {
    "code": "def _send_outgoing_route(self, outgoing_route):\n        path = outgoing_route.path\n        block, blocked_cause = self._apply_out_filter(path)\n        nlri_str = outgoing_route.path.nlri.formatted_nlri_str\n        sent_route = SentRoute(outgoing_route.path, self, block)\n        self._adj_rib_out[nlri_str] = sent_route\n        self._signal_bus.adj_rib_out_changed(self, sent_route)\n        if not block:\n            update_msg = self._construct_update(outgoing_route)\n            self._protocol.send(update_msg)\n            self.state.incr(PeerCounterNames.SENT_UPDATES)\n        else:\n            LOG.debug('prefix : %s is not sent by filter : %s',\n                      path.nlri, blocked_cause)\n        if (not outgoing_route.path.is_withdraw and\n                not outgoing_route.for_route_refresh):\n            tm = self._core_service.table_manager\n            tm.remember_sent_route(sent_route)",
    "docstring": "Constructs `Update` message from given `outgoing_route` and sends\n        it to peer.\n\n        Also, checks if any policies prevent sending this message.\n        Populates Adj-RIB-out with corresponding `SentRoute`."
  },
  {
    "code": "def as_record(self, cls, content_type, strdata):\n        self.validate_record_type(cls)\n        parsedrecord = self.deserialize(content_type, strdata)\n        return self.post_process_record(cls, parsedrecord)",
    "docstring": "Returns a record from serialized string representation.\n\n        >>> s = teststore()\n        >>> s.as_record('tstoretest', 'application/json',\n        ... '{\"id\": \"1\", \"name\": \"Toto\"}')\n        {u'id': u'1', u'name': u'Toto'}"
  },
  {
    "code": "def bool_from_exists_clause(session: Session,\n                            exists_clause: Exists) -> bool:\n    if session.get_bind().dialect.name == SqlaDialectName.MSSQL:\n        result = session.query(literal(True)).filter(exists_clause).scalar()\n    else:\n        result = session.query(exists_clause).scalar()\n    return bool(result)",
    "docstring": "Database dialects are not consistent in how ``EXISTS`` clauses can be\n    converted to a boolean answer. This function manages the inconsistencies.\n\n    See:\n    \n    - https://bitbucket.org/zzzeek/sqlalchemy/issues/3212/misleading-documentation-for-queryexists\n    - http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.exists\n    \n    Specifically, we want this:\n    \n    *SQL Server*\n    \n    .. code-block:: sql\n    \n        SELECT 1 WHERE EXISTS (SELECT 1 FROM table WHERE ...)\n        -- ... giving 1 or None (no rows)\n        -- ... fine for SQL Server, but invalid for MySQL (no FROM clause)\n        \n    *Others, including MySQL*\n    \n    .. code-block:: sql\n    \n        SELECT EXISTS (SELECT 1 FROM table WHERE ...)\n        -- ... giving 1 or 0\n        -- ... fine for MySQL, but invalid syntax for SQL Server"
  },
  {
    "code": "def seek(self, offset, whence=os.SEEK_SET):\n        self.wrapped.seek(offset, whence)",
    "docstring": "Sets the file's current position.\n\n        :param offset: the offset to set\n        :type offset: :class:`numbers.Integral`\n        :param whence: see the docs of :meth:`file.seek()`.\n                       default is :const:`os.SEEK_SET`"
  },
  {
    "code": "def upload_napp(self, metadata, package):\n        endpoint = os.path.join(self._config.get('napps', 'api'), 'napps', '')\n        metadata['token'] = self._config.get('auth', 'token')\n        request = self.make_request(endpoint, json=metadata, package=package,\n                                    method=\"POST\")\n        if request.status_code != 201:\n            KytosConfig().clear_token()\n            LOG.error(\"%s: %s\", request.status_code, request.reason)\n            sys.exit(1)\n        username = metadata.get('username', metadata.get('author'))\n        name = metadata.get('name')\n        print(\"SUCCESS: NApp {}/{} uploaded.\".format(username, name))",
    "docstring": "Upload the napp from the current directory to the napps server."
  },
  {
    "code": "def add_ctx_property(self, name, fn, cached=True):\n        if name in [item[0] for item in self._ctx_properties]:\n             raise InvalidArgumentError(\"A context property name '%s' already exists.\" % name)\n        self._ctx_properties.append([name, (fn, cached)])",
    "docstring": "Install a context property.\n\n        A context property is a factory function whos return value will be\n        available as a property named `name` on `Context` objects passing\n        through this mapper. The result will be cached unless `cached` is\n        False.\n\n        The factory function will be called without arguments, or with the\n        context object if it requests an argument named 'ctx'."
  },
  {
    "code": "def call_command(self, name, *arguments, **options):\n        command, defaults = get_command_and_defaults(\n            name,\n            exclude_packages=self.get_exclude_packages(),\n            exclude_command_class=self.__class__)\n        if command is None:\n            raise management.CommandError(\n                \"Unknown command: {name:s}\".format(\n                    name=name))\n        defaults.update(options)\n        return command.execute(*arguments, **defaults)",
    "docstring": "Finds the given Django management command and default options,\n        excluding this command, and calls it with the given arguments\n        and override options."
  },
  {
    "code": "def open(cls, filename):\n        import boto\n        file_info = cls.parse_remote(filename)\n        connection = cls.connect(filename)\n        try:\n            s3_bucket = connection.get_bucket(file_info.bucket)\n        except boto.exception.S3ResponseError as error:\n            if error.status == 403:\n                s3_bucket = connection.get_bucket(file_info.bucket,\n                                                  validate=False)\n            else:\n                raise\n        s3_key = s3_bucket.get_key(file_info.key)\n        if s3_key is None:\n            raise ValueError(\"Did not find S3 key: %s\" % filename)\n        return S3Handle(s3_key)",
    "docstring": "Return a handle like object for streaming from S3."
  },
  {
    "code": "def calc_geo_dist_vincenty(network, node_source, node_target):\n    branch_detour_factor = network.config['grid_connection'][\n        'branch_detour_factor']\n    branch_length = branch_detour_factor * vincenty((node_source.geom.y, node_source.geom.x),\n                                                    (node_target.geom.y, node_target.geom.x)).m\n    if branch_length == 0:\n        branch_length = 1\n        logger.debug('Geo distance is zero, check objects\\' positions. '\n                     'Distance is set to 1m')\n    return branch_length",
    "docstring": "Calculates the geodesic distance between node_source and node_target\n    incorporating the detour factor in config.\n\n    Parameters\n    ----------\n    network : :class:`~.grid.network.Network`\n        The eDisGo container object\n    node_source : :class:`~.grid.components.Component`\n        Node to connect (e.g. :class:`~.grid.components.Generator`)\n    node_target : :class:`~.grid.components.Component`\n        Target node (e.g. :class:`~.grid.components.BranchTee`)\n\n    Returns\n    -------\n    :obj:`float`\n        Distance in m"
  },
  {
    "code": "def select_workers_to_close(scheduler, n_to_close):\n    workers = list(scheduler.workers.values())\n    assert n_to_close <= len(workers)\n    key = lambda ws: ws.metrics['memory']\n    to_close = set(sorted(scheduler.idle, key=key)[:n_to_close])\n    if len(to_close) < n_to_close:\n        rest = sorted(workers, key=key, reverse=True)\n        while len(to_close) < n_to_close:\n            to_close.add(rest.pop())\n    return [ws.address for ws in to_close]",
    "docstring": "Select n workers to close from scheduler"
  },
  {
    "code": "def _get_mean_deep_soil(self, mag, rake, rrup, is_reverse, imt):\n        if mag <= self.NEAR_FIELD_SATURATION_MAG:\n            c4 = self.COEFFS_SOIL_IMT_INDEPENDENT['c4lowmag']\n            c5 = self.COEFFS_SOIL_IMT_INDEPENDENT['c5lowmag']\n        else:\n            c4 = self.COEFFS_SOIL_IMT_INDEPENDENT['c4himag']\n            c5 = self.COEFFS_SOIL_IMT_INDEPENDENT['c5himag']\n        c2 = self.COEFFS_SOIL_IMT_INDEPENDENT['c2']\n        c3 = self.COEFFS_SOIL_IMT_INDEPENDENT['c3']\n        C = self.COEFFS_SOIL[imt]\n        if is_reverse:\n            c1 = self.COEFFS_SOIL_IMT_INDEPENDENT['c1r']\n            c6 = C['c6r']\n        else:\n            c1 = self.COEFFS_SOIL_IMT_INDEPENDENT['c1ss']\n            c6 = C['c6ss']\n        mag = 8.5 if mag > 8.5 else mag\n        return (c1 + c2 * mag + c6 + C['c7'] * ((8.5 - mag) ** 2.5)\n                - c3 * numpy.log(rrup + c4 * numpy.exp(c5 * mag)))",
    "docstring": "Calculate and return the mean intensity for deep soil sites.\n\n        Implements an equation from table 4."
  },
  {
    "code": "def quality_to_bitmap(quality):\n    if quality not in QUALITIES:\n        raise InvalidChordException(\n            \"Unsupported chord quality shorthand: '%s' \"\n            \"Did you mean to reduce extended chords?\" % quality)\n    return np.array(QUALITIES[quality])",
    "docstring": "Return the bitmap for a given quality.\n\n    Parameters\n    ----------\n    quality : str\n        Chord quality name.\n\n    Returns\n    -------\n    bitmap : np.ndarray\n        Bitmap representation of this quality (12-dim)."
  },
  {
    "code": "def collect_lockfile_dependencies(lockfile_data):\n    output = {}\n    for dependencyName, installedVersion in lockfile_data.items():\n        output[dependencyName] = {\n            'source': 'example-package-manager',\n            'installed': {'name': installedVersion},\n        }\n    return output",
    "docstring": "Convert the lockfile format to the dependencies schema"
  },
  {
    "code": "def DEFINE(parser, name, default, help, flag_values=_flagvalues.FLAGS,\n           serializer=None, module_name=None, **args):\n  DEFINE_flag(_flag.Flag(parser, serializer, name, default, help, **args),\n              flag_values, module_name)",
    "docstring": "Registers a generic Flag object.\n\n  NOTE: in the docstrings of all DEFINE* functions, \"registers\" is short\n  for \"creates a new flag and registers it\".\n\n  Auxiliary function: clients should use the specialized DEFINE_<type>\n  function instead.\n\n  Args:\n    parser: ArgumentParser, used to parse the flag arguments.\n    name: str, the flag name.\n    default: The default value of the flag.\n    help: str, the help message.\n    flag_values: FlagValues, the FlagValues instance with which the flag will\n        be registered. This should almost never need to be overridden.\n    serializer: ArgumentSerializer, the flag serializer instance.\n    module_name: str, the name of the Python module declaring this flag.\n        If not provided, it will be computed using the stack trace of this call.\n    **args: dict, the extra keyword args that are passed to Flag __init__."
  },
  {
    "code": "def _resolve_model(obj):\n    if isinstance(obj, six.string_types) and len(obj.split('.')) == 2:\n        app_name, model_name = obj.split('.')\n        resolved_model = apps.get_model(app_name, model_name)\n        if resolved_model is None:\n            msg = \"Django did not return a model for {0}.{1}\"\n            raise ImproperlyConfigured(msg.format(app_name, model_name))\n        return resolved_model\n    elif inspect.isclass(obj) and issubclass(obj, models.Model):\n        return obj\n    raise ValueError(\"{0} is not a Django model\".format(obj))",
    "docstring": "Resolve supplied `obj` to a Django model class.\n\n    `obj` must be a Django model class itself, or a string\n    representation of one.  Useful in situations like GH #1225 where\n    Django may not have resolved a string-based reference to a model in\n    another model's foreign key definition.\n\n    String representations should have the format:\n        'appname.ModelName'"
  },
  {
    "code": "def stop(config, container, timeout=10, *args, **kwargs):\n    err = \"Unknown\"\n    client = _get_client(config)\n    try:\n        dcontainer = _get_container_infos(config, container)['Id']\n        if is_running(config, dcontainer):\n            client.stop(dcontainer, timeout=timeout)\n            if not is_running(config, dcontainer):\n                print \"Container stopped.\"\n                return True\n            else:\n                i = 0\n                while is_running(config, dcontainer):\n                    time.sleep(0.1)\n                    if i > 100:\n                        return kill(config,container)\n                    i += 1\n                return True\n        else:\n            return True\n    except Exception as e:\n        err = e\n    utils.warning(\"Container not existing\")\n    return True",
    "docstring": "Stop a running container\n\n    :type container: string\n    :param container: The container id to stop\n\n    :type timeout: int\n    :param timeout: Wait for a timeout to let the container exit gracefully\n        before killing it\n\n    :rtype: dict\n    :returns: boolean"
  },
  {
    "code": "def calc_ethsw_port(self, port_num, port_def):\n        port_def = port_def.split(' ')\n        if len(port_def) == 4:\n            destination = {'device': port_def[2],\n                           'port': port_def[3]}\n        else:\n            destination = {'device': 'NIO',\n                           'port': port_def[2]}\n        port = {'id': self.port_id,\n                'name': str(port_num),\n                'port_number': int(port_num),\n                'type': port_def[0],\n                'vlan': int(port_def[1])}\n        self.node['ports'].append(port)\n        self.calc_link(self.node['id'], self.port_id, port['name'],\n                       destination)\n        self.port_id += 1",
    "docstring": "Split and create the port entry for an Ethernet Switch\n\n        :param port_num: port number\n        :type port_num: str or int\n        :param str port_def: port definition"
  },
  {
    "code": "async def serialize(self, native=False):\n        data = {}\n        for field_name, field in self._fields.items():\n            raw_data = self._data.get(field_name)\n            if field._projection != None:\n                field_data = await field.serialize(raw_data, native)\n                if field_data:\n                    data[field_name] = field_data\n                elif field._projection == True:\n                    data[field_name] = None\n        for name, func in self._serialize_methods.items():\n            data[name] = await func(self)\n        return data",
    "docstring": "Returns a serialized from of the model taking into account projection rules and ``@serialize`` decorated methods.\n        \n        :param native:\n            Deternines if data is serialized to Python native types or primitive form. Defaults to ``False``"
  },
  {
    "code": "def get_restart_power_failure():\n    ret = salt.utils.mac_utils.execute_return_result(\n        'systemsetup -getrestartpowerfailure')\n    return salt.utils.mac_utils.validate_enabled(\n        salt.utils.mac_utils.parse_return(ret)) == 'on'",
    "docstring": "Displays whether 'restart on power failure' is on or off if supported\n\n    :return: A string value representing the \"restart on power failure\" settings\n    :rtype: string\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' power.get_restart_power_failure"
  },
  {
    "code": "def path_to_attr(path):\n    return reduce(lambda hpath, last: ast.Attribute(hpath, last, ast.Load()),\n                  path[1:], ast.Name(mangle(path[0]), ast.Load(), None))",
    "docstring": "Transform path to ast.Attribute.\n\n    >>> import gast as ast\n    >>> path = ('__builtin__', 'my', 'constant')\n    >>> value = path_to_attr(path)\n    >>> ref = ast.Attribute(\n    ...     value=ast.Attribute(value=ast.Name(id=\"__builtin__\",\n    ...                                        ctx=ast.Load(),\n    ...                                        annotation=None),\n    ...                         attr=\"my\", ctx=ast.Load()),\n    ...     attr=\"constant\", ctx=ast.Load())\n    >>> ast.dump(ref) == ast.dump(value)\n    True"
  },
  {
    "code": "def service_status(self, short_name):\n        if short_name not in self.services:\n            raise ArgumentError(\"Unknown service name\", short_name=short_name)\n        info = {}\n        service = self.services[short_name]['state']\n        info['heartbeat_age'] = monotonic() - service.last_heartbeat\n        info['numeric_status'] = service.state\n        info['string_status'] = service.string_state\n        return info",
    "docstring": "Get the current status of a service.\n\n        Returns information about the service such as the length since the last\n        heartbeat, any status messages that have been posted about the service\n        and whether the heartbeat should be considered out of the ordinary.\n\n        Args:\n            short_name (string): The short name of the service to query\n\n        Returns:\n            dict: A dictionary with the status of the service"
  },
  {
    "code": "def srandmember(self, key, count=None, *, encoding=_NOTSET):\n        args = [key]\n        count is not None and args.append(count)\n        return self.execute(b'SRANDMEMBER', *args, encoding=encoding)",
    "docstring": "Get one or multiple random members from a set."
  },
  {
    "code": "def assert_valid_path(self, path):\n        if not isinstance(path, str):\n            raise NotFoundResourceException(\n                \"Resource passed to load() method must be a file path\")\n        if not os.path.isfile(path):\n            raise NotFoundResourceException(\n                'File \"{0}\" does not exist'.format(path))",
    "docstring": "Ensures that the path represents an existing file\n\n        @type path: str\n        @param path: path to check"
  },
  {
    "code": "def optimize_auto(self,max_iters=10000,verbose=True):\n        self.Z.fix(warning=False)\n        self.kern.fix(warning=False)\n        self.kern_row.fix(warning=False)\n        self.Zr.fix(warning=False)\n        self.Xr.fix(warning=False)\n        self.optimize(max_iters=int(0.1*max_iters),messages=verbose)\n        self.unfix()\n        self.optimize(max_iters=max_iters,messages=verbose)",
    "docstring": "Optimize the model parameters through a pre-defined protocol.\n\n        :param int max_iters: the maximum number of iterations.\n        :param boolean verbose: print the progress of optimization or not."
  },
  {
    "code": "def set_dtreat_indch(self, indch=None):\n        if indch is not None:\n            indch = np.asarray(indch)\n            assert indch.ndim==1\n        indch = _format_ind(indch, n=self._ddataRef['nch'])\n        self._dtreat['indch'] = indch\n        self._ddata['uptodate'] = False",
    "docstring": "Store the desired index array for the channels\n\n        If None => all channels\n        Must be a 1d array"
  },
  {
    "code": "def discard_incoming_messages(self):\n        self.inbox.clear()\n        previous = self._discard_incoming_messages\n        self._discard_incoming_messages = True\n        try:\n            yield\n        finally:\n            self._discard_incoming_messages = previous",
    "docstring": "Discard all incoming messages for the time of the context manager."
  },
  {
    "code": "def choice_explanation(value: str, choices: Iterable[Tuple[str, str]]) -> str:\n    for k, v in choices:\n        if k == value:\n            return v\n    return ''",
    "docstring": "Returns the explanation associated with a Django choice tuple-list."
  },
  {
    "code": "def to_decimal(number, points=None):\n    if not is_number(number):\n        return number\n    number = float(decimal.Decimal(number * 1.))\n    if is_number(points):\n        return round(number, points)\n    return number",
    "docstring": "convert datatypes into Decimals"
  },
  {
    "code": "def find_all(self, locator):\n        return self.driver_wrapper.find(locator, True, self.element)",
    "docstring": "Find wrapper, finds all elements\n\n        @type locator:          webdriverwrapper.support.locator.Locator\n        @param locator:         locator used in search\n\n        @rtype:                 list\n        @return:                A list of WebElementWrappers"
  },
  {
    "code": "def new_encoded_stream(args, stream):\n    if args.ascii_print:\n        return wpull.util.ASCIIStreamWriter(stream)\n    else:\n        return stream",
    "docstring": "Return a stream writer."
  },
  {
    "code": "def count_dataset(train=False,\n                  dev=False,\n                  test=False,\n                  train_rows=10000,\n                  dev_rows=1000,\n                  test_rows=1000,\n                  seq_max_length=10):\n    ret = []\n    for is_requested, n_rows in [(train, train_rows), (dev, dev_rows), (test, test_rows)]:\n        rows = []\n        for i in range(n_rows):\n            length = random.randint(1, seq_max_length)\n            seq = []\n            for _ in range(length):\n                seq.append(str(random.randint(0, 9)))\n            input_ = ' '.join(seq)\n            rows.append({'numbers': input_, 'count': str(length)})\n        if not is_requested:\n            continue\n        ret.append(Dataset(rows))\n    if len(ret) == 1:\n        return ret[0]\n    else:\n        return tuple(ret)",
    "docstring": "Load the Count dataset.\n\n    The Count dataset is a simple task of counting the number of integers in a sequence. This\n    dataset is useful for testing implementations of sequence to label models.\n\n    Args:\n        train (bool, optional): If to load the training split of the dataset.\n        dev (bool, optional): If to load the development split of the dataset.\n        test (bool, optional): If to load the test split of the dataset.\n        train_rows (int, optional): Number of training rows to generate.\n        dev_rows (int, optional): Number of development rows to generate.\n        test_rows (int, optional): Number of test rows to generate.\n        seq_max_length (int, optional): Maximum sequence length.\n\n    Returns:\n        :class:`tuple` of :class:`torchnlp.datasets.Dataset` or :class:`torchnlp.datasets.Dataset`:\n        Returns between one and all dataset splits (train, dev and test) depending on if their\n        respective boolean argument is ``True``.\n\n    Example:\n        >>> import random\n        >>> random.seed(321)\n        >>>\n        >>> from torchnlp.datasets import count_dataset\n        >>> train = count_dataset(train=True)\n        >>> train[0:2]\n        [{'numbers': '6 2 5 8 7', 'count': '5'}, {'numbers': '3 9 7 6 6 7', 'count': '6'}]"
  },
  {
    "code": "def has_metric_plateaued(steps, values, num_steps=100, delta=0.1,\n                         decrease=True):\n  assert num_steps > 0\n  if len(steps) < 2:\n    return False\n  steps_at_least_num_steps_ago = [\n      s for s in steps if s <= (steps[-1] - num_steps)\n  ]\n  if not steps_at_least_num_steps_ago:\n    return False\n  delta_step_idx = len(steps_at_least_num_steps_ago) - 1\n  start_val = values[delta_step_idx]\n  values_to_check = values[delta_step_idx:]\n  observed_deltas = []\n  for val in values_to_check:\n    if decrease:\n      observed_delta = start_val - val\n    else:\n      observed_delta = val - start_val\n    observed_deltas.append(observed_delta)\n  within_range = [obs < delta for obs in observed_deltas]\n  return all(within_range)",
    "docstring": "Check if metric has plateaued.\n\n  A metric has plateaued if the value has not increased/decreased (depending on\n  `decrease`) by `delta` for at least `num_steps`.\n\n  Args:\n    steps: list<int> list of global steps for values.\n    values: list<float> list of metric values.\n    num_steps: int, number of steps the metric has to have been plateaued for.\n    delta: float, how much the metric should have changed by over num_steps.\n    decrease: bool, whether to check if the metric has decreased by delta or\n      increased by delta.\n\n  Returns:\n    bool, whether the metric has plateaued."
  },
  {
    "code": "def revoke_access(src, dst='any', port=None, proto=None):\n    return modify_access(src, dst=dst, port=port, proto=proto, action='delete')",
    "docstring": "Revoke access to an address or subnet\n\n    :param src: address (e.g. 192.168.1.234) or subnet\n                (e.g. 192.168.1.0/24).\n    :param dst: destiny of the connection, if the machine has multiple IPs and\n                connections to only one of those have to accepted this is the\n                field has to be set.\n    :param port: destiny port\n    :param proto: protocol (tcp or udp)"
  },
  {
    "code": "def _process_scalar_value(name, parse_fn, var_type, m_dict, values,\n                          results_dictionary):\n  try:\n    parsed_value = parse_fn(m_dict['val'])\n  except ValueError:\n    _parse_fail(name, var_type, m_dict['val'], values)\n  if not m_dict['index']:\n    if name in results_dictionary:\n      _reuse_fail(name, values)\n    results_dictionary[name] = parsed_value\n  else:\n    if name in results_dictionary:\n      if not isinstance(results_dictionary.get(name), dict):\n        _reuse_fail(name, values)\n    else:\n      results_dictionary[name] = {}\n    index = int(m_dict['index'])\n    if index in results_dictionary[name]:\n      _reuse_fail('{}[{}]'.format(name, index), values)\n    results_dictionary[name][index] = parsed_value",
    "docstring": "Update results_dictionary with a scalar value.\n\n  Used to update the results_dictionary to be returned by parse_values when\n  encountering a clause with a scalar RHS (e.g.  \"s=5\" or \"arr[0]=5\".)\n\n  Mutates results_dictionary.\n\n  Args:\n    name: Name of variable in assignment (\"s\" or \"arr\").\n    parse_fn: Function for parsing the actual value.\n    var_type: Type of named variable.\n    m_dict: Dictionary constructed from regex parsing.\n      m_dict['val']: RHS value (scalar)\n      m_dict['index']: List index value (or None)\n    values: Full expression being parsed\n    results_dictionary: The dictionary being updated for return by the parsing\n      function.\n\n  Raises:\n    ValueError: If the name has already been used."
  },
  {
    "code": "def read_nmr_efg(self):\n        header_pattern = r'^\\s+NMR quadrupolar parameters\\s+$\\n' \\\n                         r'^\\s+Cq : quadrupolar parameter\\s+Cq=e[*]Q[*]V_zz/h$\\n' \\\n                         r'^\\s+eta: asymmetry parameters\\s+\\(V_yy - V_xx\\)/ V_zz$\\n' \\\n                         r'^\\s+Q  : nuclear electric quadrupole moment in mb \\(millibarn\\)$\\n' \\\n                         r'^-{50,}$\\n' \\\n                         r'^\\s+ion\\s+Cq\\(MHz\\)\\s+eta\\s+Q \\(mb\\)\\s+$\\n' \\\n                         r'^-{50,}\\s*$\\n'\n        row_pattern = r'\\d+\\s+(?P<cq>[-]?\\d+\\.\\d+)\\s+(?P<eta>[-]?\\d+\\.\\d+)\\s+' \\\n                      r'(?P<nuclear_quadrupole_moment>[-]?\\d+\\.\\d+)'\n        footer_pattern = r'-{50,}\\s*$'\n        self.read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=float,\n                                last_one_only=True, attribute_name=\"efg\")",
    "docstring": "Parse the NMR Electric Field Gradient interpretted values.\n\n        Returns:\n            Electric Field Gradient tensors as a list of dict in the order of atoms from OUTCAR.\n            Each dict key/value pair corresponds to a component of the tensors."
  },
  {
    "code": "def _get_struct_shapewithstyle(self, shape_number):\n        obj = _make_object(\"ShapeWithStyle\")\n        obj.FillStyles = self._get_struct_fillstylearray(shape_number)\n        obj.LineStyles = self._get_struct_linestylearray(shape_number)\n        bc = BitConsumer(self._src)\n        obj.NumFillBits = n_fill_bits = bc.u_get(4)\n        obj.NumlineBits = n_line_bits = bc.u_get(4)\n        obj.ShapeRecords = self._get_shaperecords(\n            n_fill_bits, n_line_bits, shape_number)\n        return obj",
    "docstring": "Get the values for the SHAPEWITHSTYLE record."
  },
  {
    "code": "def _split(string, splitters):\n    part = ''\n    for character in string:\n        if character in splitters:\n            yield part\n            part = ''\n        else:\n            part += character\n    yield part",
    "docstring": "Splits a string into parts at multiple characters"
  },
  {
    "code": "def populateFromRow(self, quantificationSetRecord):\n        self._dbFilePath = quantificationSetRecord.dataurl\n        self.setAttributesJson(quantificationSetRecord.attributes)\n        self._db = SqliteRnaBackend(self._dbFilePath)\n        self.addRnaQuants()",
    "docstring": "Populates the instance variables of this RnaQuantificationSet from the\n        specified DB row."
  },
  {
    "code": "def set_home(self, new_home):\n        if type(new_home) is Position:\n            self.home = new_home\n        elif type(new_home) is tuple:\n            self.home = Position(location=new_home)\n        else:\n            self.home = Position(antenna=new_home)\n        self.reset_cache()",
    "docstring": "Sets the user's home. The argument can be a Position object or a\n        tuple containing location data."
  },
  {
    "code": "def tokenize_paragraphs(self):\n        tok = self.__paragraph_tokenizer\n        spans = tok.span_tokenize(self.text)\n        dicts = []\n        for start, end in spans:\n            dicts.append({'start': start, 'end': end})\n        self[PARAGRAPHS] = dicts\n        return self",
    "docstring": "Apply paragraph tokenization to this Text instance. Creates ``paragraphs`` layer."
  },
  {
    "code": "def is_build_needed(self, data_sink, data_src):\n        return (self._gettask(data_src).last_build_time == 0 or\n                self._gettask(data_src).last_build_time <\n                self._gettask(data_sink).last_build_time)",
    "docstring": "returns true if data_src needs to be rebuilt, given that data_sink\n            has had a rebuild requested."
  },
  {
    "code": "def make_invalid_op(name):\n    def invalid_op(self, other=None):\n        raise TypeError(\"cannot perform {name} with this index type: \"\n                        \"{typ}\".format(name=name, typ=type(self).__name__))\n    invalid_op.__name__ = name\n    return invalid_op",
    "docstring": "Return a binary method that always raises a TypeError.\n\n    Parameters\n    ----------\n    name : str\n\n    Returns\n    -------\n    invalid_op : function"
  },
  {
    "code": "def play_NoteContainer(self, notecontainer):\n        if len(notecontainer) <= 1:\n            [self.play_Note(x) for x in notecontainer]\n        else:\n            self.play_Note(notecontainer[0])\n            self.set_deltatime(0)\n            [self.play_Note(x) for x in notecontainer[1:]]",
    "docstring": "Convert a mingus.containers.NoteContainer to the equivalent MIDI\n        events and add it to the track_data.\n\n        Note.channel and Note.velocity can be set as well."
  },
  {
    "code": "def get_siblings_score(self, top_node):\n        base = 100000\n        paragraphs_number = 0\n        paragraphs_score = 0\n        nodes_to_check = self.parser.getElementsByTag(top_node, tag='p')\n        for node in nodes_to_check:\n            text_node = self.parser.getText(node)\n            word_stats = self.stopwords_class(language=self.get_language()).get_stopword_count(text_node)\n            high_link_density = self.is_highlink_density(node)\n            if word_stats.get_stopword_count() > 2 and not high_link_density:\n                paragraphs_number += 1\n                paragraphs_score += word_stats.get_stopword_count()\n        if paragraphs_number > 0:\n            base = paragraphs_score / paragraphs_number\n        return base",
    "docstring": "\\\n        we could have long articles that have tons of paragraphs\n        so if we tried to calculate the base score against\n        the total text score of those paragraphs it would be unfair.\n        So we need to normalize the score based on the average scoring\n        of the paragraphs within the top node.\n        For example if our total score of 10 paragraphs was 1000\n        but each had an average value of 100 then 100 should be our base."
  },
  {
    "code": "def _get_instance_path(self, name):\n        \"Return a path to the pickled data with key ``name``.\"\n        fname = self.pattern.format(**{'name': name})\n        logger.debug(f'path {self.create_path}: {self.create_path.exists()}')\n        self._create_path_dir()\n        return Path(self.create_path, fname)",
    "docstring": "Return a path to the pickled data with key ``name``."
  },
  {
    "code": "def refreshUi( self ):\n        dataSet = self.dataSet()\n        if not dataSet:\n            return False\n        for widget in self.findChildren(QWidget):\n            prop = unwrapVariant(widget.property('dataName'))\n            if prop is None:\n                continue\n            prop_name = nativestring(prop)\n            if prop_name in dataSet:\n                value = dataSet.value(prop_name)\n                projexui.setWidgetValue(widget, value)\n        return True",
    "docstring": "Load the plugin information to the interface."
  },
  {
    "code": "def validate(self, obj):\n        if self.path:\n            for i in self.path:\n                obj = obj[i]\n        obj = obj[self.field]\n        raise NotImplementedError('Validation is not implemented yet')",
    "docstring": "check if obj has this api param"
  },
  {
    "code": "def standardizeMapName(mapName):\n    newName = os.path.basename(mapName)\n    newName = newName.split(\".\")[0]\n    newName = newName.split(\"(\")[0]\n    newName = re.sub(\"[LT]E+$\", \"\", newName)\n    newName = re.sub(\"-\", \"\", newName)\n    newName = re.sub(' ', '', newName, flags=re.UNICODE)\n    foreignName = newName\n    if foreignName in c.mapNameTranslations:\n        return c.mapNameTranslations[foreignName]\n    return newName",
    "docstring": "pretty-fy the name for pysc2 map lookup"
  },
  {
    "code": "def arch_size(self):\n        if not self._ptr:\n            raise BfdException(\"BFD not initialized\")\n        try:\n            return _bfd.get_arch_size(self._ptr)\n        except Exception, err:\n            raise BfdException(\"Unable to determine architeure size.\")",
    "docstring": "Return the architecure size in bits."
  },
  {
    "code": "def copy_abs(self):\n        result = mpfr.Mpfr_t.__new__(BigFloat)\n        mpfr.mpfr_init2(result, self.precision)\n        mpfr.mpfr_setsign(result, self, False, ROUND_TIES_TO_EVEN)\n        return result",
    "docstring": "Return a copy of self with the sign bit unset.\n\n        Unlike abs(self), this does not make use of the context: the result\n        has the same precision as the original."
  },
  {
    "code": "def run(self):\n        for fn in glob_all(self.args.random_data_folder, '*.wav'):\n            if fn in self.trained_fns:\n                print('Skipping ' + fn + '...')\n                continue\n            print('Starting file ' + fn + '...')\n            self.train_on_audio(fn)\n            print('\\r100%                 ')\n            self.trained_fns.append(fn)\n            save_trained_fns(self.trained_fns, self.args.model)",
    "docstring": "Begin reading through audio files, saving false\n        activations and retraining when necessary"
  },
  {
    "code": "def save_model(self, fname='model.js'):\n        exp_colorscale_str = json.dumps(self._exp_colorscale)\n        mut_colorscale_str = json.dumps(self._mut_colorscale)\n        cyjs_dict = {'edges': self._edges, 'nodes': self._nodes}\n        model_str = json.dumps(cyjs_dict, indent=1, sort_keys=True)\n        model_dict = {'exp_colorscale_str': exp_colorscale_str,\n                      'mut_colorscale_str': mut_colorscale_str,\n                      'model_elements_str': model_str}\n        s = ''\n        s += 'var exp_colorscale = %s;\\n' % model_dict['exp_colorscale_str']\n        s += 'var mut_colorscale = %s;\\n' % model_dict['mut_colorscale_str']\n        s += 'var model_elements = %s;\\n' % model_dict['model_elements_str']\n        with open(fname, 'wb') as fh:\n            fh.write(s.encode('utf-8'))",
    "docstring": "Save the assembled Cytoscape JS network in a js file.\n\n        Parameters\n        ----------\n        file_name : Optional[str]\n            The name of the file to save the Cytoscape JS network to.\n            Default: model.js"
  },
  {
    "code": "def run_callback(self, callback, *args):\n        if self._loop is None:\n            raise RuntimeError('hub is closed')\n        elif not callable(callback):\n            raise TypeError('\"callback\": expecting a callable')\n        self._callbacks.append((callback, args))\n        self._interrupt_loop()",
    "docstring": "Queue a callback.\n\n        The *callback* will be called with positional arguments *args* in the\n        next iteration of the event loop. If you add multiple callbacks, they\n        will be called in the order that you added them. The callback will run\n        in the Hub's fiber.\n\n        This method is thread-safe: it is allowed to queue a callback from a\n        different thread than the one running the Hub."
  },
  {
    "code": "def cross_goal(state):\n        centres, edges = state\n        for edge in edges:\n            if \"D\" not in edge.facings:\n                return False\n            if edge[\"D\"] != centres[\"D\"][\"D\"]:\n                return False\n            k = \"\".join(edge.facings.keys()).replace(\"D\", \"\")\n            if edge[k] != centres[k][k]:\n                return False\n        return True",
    "docstring": "The goal function for cross solving search."
  },
  {
    "code": "def get_translations(self, context_id):\n        _mask = ('[mask[addressTranslations[customerIpAddressRecord,'\n                 'internalIpAddressRecord]]]')\n        context = self.get_tunnel_context(context_id, mask=_mask)\n        for translation in context.get('addressTranslations', []):\n            remote_ip = translation.get('customerIpAddressRecord', {})\n            internal_ip = translation.get('internalIpAddressRecord', {})\n            translation['customerIpAddress'] = remote_ip.get('ipAddress', '')\n            translation['internalIpAddress'] = internal_ip.get('ipAddress', '')\n            translation.pop('customerIpAddressRecord', None)\n            translation.pop('internalIpAddressRecord', None)\n        return context['addressTranslations']",
    "docstring": "Retrieves all translation entries for a tunnel context.\n\n        :param int context_id: The id-value representing the context instance.\n        :return list(dict): Translations associated with the given context"
  },
  {
    "code": "def set_git_user_email():\n    username = subprocess.run(shlex.split('git config user.name'), stdout=subprocess.PIPE).stdout.strip().decode('utf-8')\n    if not username or username == \"Travis CI User\":\n        run(['git', 'config', '--global', 'user.name', \"Doctr (Travis CI)\"])\n    else:\n        print(\"Not setting git user name, as it's already set to %r\" % username)\n    email = subprocess.run(shlex.split('git config user.email'), stdout=subprocess.PIPE).stdout.strip().decode('utf-8')\n    if not email or email == \"travis@example.org\":\n        run(['git', 'config', '--global', 'user.email', 'drdoctr@users.noreply.github.com'])\n    else:\n        print(\"Not setting git user email, as it's already set to %r\" % email)",
    "docstring": "Set global user and email for git user if not already present on system"
  },
  {
    "code": "def _repr_latex_(self):\n        lines = []\n        lines.append(r\"<h1>{0}</h1>\".format(self.__class__.__name__))\n        lines.append(\"<p>Method: <code>{0!r}</code></p>\".format(self.method))\n        lines.append(\"<p>Parameters: <code>{0!r}</code></p>\".format(self.parameters))\n        lines.append(\"<p>Terms:</p>\")\n        lines.append(\"<ul>\")\n        lines.extend(['<li><code>{0!r}</code></li>'.format(lhs) for lhs in self.left_hand_side_descriptors])\n        lines.append(\"</ul>\")\n        lines.append('<hr />')\n        lines.append(r\"\\begin{align*}\")\n        for lhs, rhs in zip(self.left_hand_side_descriptors, self.right_hand_side):\n            lines.append(r\"\\dot{{{0}}} &= {1} \\\\\".format(sympy.latex(lhs.symbol), sympy.latex(rhs)))\n        lines.append(r\"\\end{align*}\")\n        return \"\\n\".join(lines)",
    "docstring": "This is used in IPython notebook it allows us to render the ODEProblem object in LaTeX.\n        How Cool is this?"
  },
  {
    "code": "def deprecated(replacement=None, version=None):\n    def outer(oldfun):\n        def inner(*args, **kwargs):\n            msg = \"%s is deprecated\" % oldfun.__name__\n            if version is not None:\n                msg += \"will be removed in version %s;\" % version\n            if replacement is not None:\n                msg += \"; use %s instead\" % (replacement)\n            warnings.warn(msg, DeprecationWarning, stacklevel=2)\n            if callable(replacement):\n                return replacement(*args, **kwargs)\n            else:\n                return oldfun(*args, **kwargs)\n        return inner\n    return outer",
    "docstring": "A decorator which can be used to mark functions as deprecated.\n    replacement is a callable that will be called with the same args\n    as the decorated function.\n    >>> import pytest\n    >>> @deprecated()\n    ... def foo1(x):\n    ...     return x\n    ...\n    >>> pytest.warns(DeprecationWarning, foo1, 1)\n    1\n    >>> def newfun(x):\n    ...     return 0\n    ...\n    >>> @deprecated(newfun, '1.1')\n    ... def foo2(x):\n    ...     return x\n    ...\n    >>> pytest.warns(DeprecationWarning, foo2, 1)\n    0\n    >>>"
  },
  {
    "code": "def num_available(self, work_spec_name):\n        return self.registry.len(WORK_UNITS_ + work_spec_name,\n                                 priority_max=time.time())",
    "docstring": "Get the number of available work units for some work spec.\n\n        These are work units that could be returned by :meth:`get_work`:\n        they are not complete, not currently executing, and not blocked\n        on some other work unit."
  },
  {
    "code": "def delete_archive_file(self):\n        logger.debug(\"Deleting %s\", self.archive_tmp_dir)\n        shutil.rmtree(self.archive_tmp_dir, True)",
    "docstring": "Delete the directory containing the constructed archive"
  },
  {
    "code": "def put_value(self, value, timeout=None):\n        self._context.put(self._data.path + [\"value\"], value, timeout=timeout)",
    "docstring": "Put a value to the Attribute and wait for completion"
  },
  {
    "code": "def add_and_shuffle(self, peer):\n        self.push_peer(peer)\n        r = random.randint(0, self.size() - 1)\n        self.swap_order(peer.index, r)",
    "docstring": "Push a new peer into the heap and shuffle the heap"
  },
  {
    "code": "def _get_int64(data, position, dummy0, dummy1, dummy2):\n    end = position + 8\n    return Int64(_UNPACK_LONG(data[position:end])[0]), end",
    "docstring": "Decode a BSON int64 to bson.int64.Int64."
  },
  {
    "code": "def request(self,\n                method,\n                path,\n                options=None,\n                payload=None,\n                heartbeater=None,\n                retry_count=0):\n        def _request(authHeaders, options, payload, heartbeater, retry_count):\n            tenantId = authHeaders['X-Tenant-Id']\n            requestUrl = self.baseUrl + tenantId + path\n            if options:\n                requestUrl += '?' + urlencode(options)\n            payload = StringProducer(json.dumps(payload)) if payload else None\n            d = self.agent.request(method=method,\n                                   uri=requestUrl,\n                                   headers=None,\n                                   bodyProducer=payload)\n            d.addCallback(self.cbRequest,\n                          method,\n                          path,\n                          options,\n                          payload,\n                          heartbeater,\n                          retry_count)\n            return d\n        d = self.agent.getAuthHeaders()\n        d.addCallback(_request, options, payload, heartbeater, retry_count)\n        return d",
    "docstring": "Make a request to the Service Registry API.\n        @param method: HTTP method ('POST', 'GET', etc.).\n        @type method: C{str}\n        @param path: Path to be appended to base URL ('/sessions', etc.).\n        @type path: C{str}\n        @param options: Options to be encoded as query parameters in the URL.\n        @type options: C{dict}\n        @param payload: Optional body\n        @type payload: C{dict}\n        @param heartbeater: Optional heartbeater passed in when\n        creating a session.\n        @type heartbeater: L{HeartBeater}"
  },
  {
    "code": "def delete_messages(\n        self,\n        chat_id: Union[int, str],\n        message_ids: Iterable[int],\n        revoke: bool = True\n    ) -> bool:\n        peer = self.resolve_peer(chat_id)\n        message_ids = list(message_ids) if not isinstance(message_ids, int) else [message_ids]\n        if isinstance(peer, types.InputPeerChannel):\n            r = self.send(\n                functions.channels.DeleteMessages(\n                    channel=peer,\n                    id=message_ids\n                )\n            )\n        else:\n            r = self.send(\n                functions.messages.DeleteMessages(\n                    id=message_ids,\n                    revoke=revoke or None\n                )\n            )\n        return bool(r.pts_count)",
    "docstring": "Use this method to delete messages, including service messages.\n\n        Args:\n            chat_id (``int`` | ``str``):\n                Unique identifier (int) or username (str) of the target chat.\n                For your personal cloud (Saved Messages) you can simply use \"me\" or \"self\".\n                For a contact that exists in your Telegram address book you can use his phone number (str).\n\n            message_ids (``iterable``):\n                A list of Message identifiers to delete or a single message id.\n                Iterators and Generators are also accepted.\n\n            revoke (``bool``, *optional*):\n                Deletes messages on both parts.\n                This is only for private cloud chats and normal groups, messages on\n                channels and supergroups are always revoked (i.e.: deleted for everyone).\n                Defaults to True.\n\n        Returns:\n            True on success, False otherwise.\n\n        Raises:\n            :class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error."
  },
  {
    "code": "def _get_auth(username, password):\n    if username and password:\n        return requests.auth.HTTPBasicAuth(username, password)\n    else:\n        return None",
    "docstring": "Returns the HTTP auth header"
  },
  {
    "code": "def hmget(self, key, *fields):\n        def format_response(val_array):\n            return dict(zip(fields, val_array))\n        command = [b'HMGET', key]\n        command.extend(fields)\n        return self._execute(command, format_callback=format_response)",
    "docstring": "Returns the values associated with the specified `fields` in a hash.\n\n        For every ``field`` that does not exist in the hash, :data:`None`\n        is returned.  Because a non-existing keys are treated as empty\n        hashes, calling :meth:`hmget` against a non-existing key will\n        return a list of :data:`None` values.\n\n        .. note::\n\n           *Time complexity*: ``O(N)`` where ``N`` is the number of fields\n           being requested.\n\n        :param key: The key of the hash\n        :type key: :class:`str`, :class:`bytes`\n        :param fields: iterable of field names to retrieve\n        :returns: a :class:`dict` of field name to value mappings for\n            each of the requested fields\n        :rtype: dict"
  },
  {
    "code": "def set_initial_representations(self):\n        self.standard_settings()\n        cmd.set('dash_gap', 0)\n        cmd.set('ray_shadow', 0)\n        cmd.set('cartoon_color', 'mylightblue')\n        cmd.clip('far', -1000)\n        cmd.clip('near', 1000)",
    "docstring": "General settings for PyMOL"
  },
  {
    "code": "def get_face_normals(self, indexed=None):\n        if self._face_normals is None:\n            v = self.get_vertices(indexed='faces')\n            self._face_normals = np.cross(v[:, 1] - v[:, 0],\n                                          v[:, 2] - v[:, 0])\n        if indexed is None:\n            return self._face_normals\n        elif indexed == 'faces':\n            if self._face_normals_indexed_by_faces is None:\n                norms = np.empty((self._face_normals.shape[0], 3, 3),\n                                 dtype=np.float32)\n                norms[:] = self._face_normals[:, np.newaxis, :]\n                self._face_normals_indexed_by_faces = norms\n            return self._face_normals_indexed_by_faces\n        else:\n            raise Exception(\"Invalid indexing mode. Accepts: None, 'faces'\")",
    "docstring": "Get face normals\n\n        Parameters\n        ----------\n        indexed : str | None\n            If None, return an array (Nf, 3) of normal vectors for each face.\n            If 'faces', then instead return an indexed array (Nf, 3, 3)\n            (this is just the same array with each vector copied three times).\n\n        Returns\n        -------\n        normals : ndarray\n            The normals."
  },
  {
    "code": "def get_queryset(self):\n        queryset = super(CachedViewMixin, self).get_queryset()\n        if self.action in ('list', 'retrieve'):\n            return CachedQueryset(self.get_queryset_cache(), queryset=queryset)\n        else:\n            return queryset",
    "docstring": "Get the queryset for the action.\n\n        If action is read action, return a CachedQueryset\n        Otherwise, return a Django queryset"
  },
  {
    "code": "def _string_to_record_type(string):\n    string = string.upper()\n    record_type = getattr(RecordType, string)\n    return record_type",
    "docstring": "Return a string representation of a DNS record type to a\n    libcloud RecordType ENUM.\n\n    :param string: A record type, e.g. A, TXT, NS\n    :type  string: ``str``\n\n    :rtype: :class:`RecordType`"
  },
  {
    "code": "def get_callback_url(self, provider):\n        info = self.model._meta.app_label, self.model._meta.model_name\n        return reverse('admin:%s_%s_callback' % info, kwargs={'provider': provider.id})",
    "docstring": "Return the callback url for this provider."
  },
  {
    "code": "def get(self):\n        with self._mutex:\n            entry = self._queue.pop()\n            del self._block_map[entry[2]]\n            return entry[2]",
    "docstring": "Get the highest priority Processing Block from the queue."
  },
  {
    "code": "def delete_translations(self, language=None):\n        from .models import Translation\n        return Translation.objects.delete_translations(obj=self, language=language)",
    "docstring": "Deletes related translations."
  },
  {
    "code": "def remove(self, key):\n        encodedKey = json.dumps(key)\n        sql = 'DELETE FROM ' + self.table + ' WHERE name = %s'\n        with self.connect() as conn:\n            with doTransaction(conn):\n                return executeSQL(conn, sql, args=[encodedKey])",
    "docstring": "remove key from the namespace.  it is fine to remove a key multiple times."
  },
  {
    "code": "def call_once(func):\n  argspec = inspect.getargspec(func)\n  if argspec.args or argspec.varargs or argspec.keywords:\n    raise ValueError('Can only decorate functions with no args', func, argspec)\n  @functools.wraps(func)\n  def _wrapper():\n    if not _wrapper.HasRun():\n      _wrapper.MarkAsRun()\n      _wrapper.return_value = func()\n    return _wrapper.return_value\n  _wrapper.has_run = False\n  _wrapper.HasRun = lambda: _wrapper.has_run\n  _wrapper.MarkAsRun = lambda: setattr(_wrapper, 'has_run', True)\n  return _wrapper",
    "docstring": "Decorate a function to only allow it to be called once.\n\n  Note that it doesn't make sense to only call a function once if it takes\n  arguments (use @functools.lru_cache for that sort of thing), so this only\n  works on callables that take no args."
  },
  {
    "code": "def translate(self):\n        varnames = set()\n        ident = self.ident\n        funcnames = set([ident])\n        arg_exprs = []\n        for arg in self.args:\n            subexprs, subvars, subfuncs = arg.translate()\n            varnames.update(subvars)\n            funcnames.update(subfuncs)\n            arg_exprs.append(ex_call(\n                ast.Attribute(ex_literal(u''), 'join', ast.Load()),\n                [ex_call(\n                    'map',\n                    [\n                        ex_rvalue(str.__name__),\n                        ast.List(subexprs, ast.Load()),\n                    ]\n                )],\n            ))\n        subexpr_call = ex_call(\n            FUNCTION_PREFIX + ident,\n            arg_exprs\n        )\n        return [subexpr_call], varnames, funcnames",
    "docstring": "Compile the function call."
  },
  {
    "code": "def remove_data_flow(self, data_flow_id, destroy=True):\n        if data_flow_id not in self._data_flows:\n            raise AttributeError(\"The data_flow_id %s does not exist\" % str(data_flow_id))\n        self._data_flows[data_flow_id].parent = None\n        return self._data_flows.pop(data_flow_id)",
    "docstring": "Removes a data flow from the container state\n\n        :param int data_flow_id: the id of the data_flow to remove\n        :raises exceptions.AttributeError: if the data_flow_id does not exist"
  },
  {
    "code": "def get_node_attribute(self, node, attribute_name):\n        if not self.has_node(node):\n            raise ValueError(\"No such node exists.\")\n        elif attribute_name not in self._node_attributes[node]:\n            raise ValueError(\"No such attribute exists.\")\n        else:\n            return copy.\\\n                copy(self._node_attributes[node][attribute_name])",
    "docstring": "Given a node and the name of an attribute, get a copy\n        of that node's attribute.\n\n        :param node: reference to the node to retrieve the attribute of.\n        :param attribute_name: name of the attribute to retrieve.\n        :returns: attribute value of the attribute_name key for the\n                specified node.\n        :raises: ValueError -- No such node exists.\n        :raises: ValueError -- No such attribute exists."
  },
  {
    "code": "def parse(self, uri=None, fh=None, str_data=None, **kwargs):\n        if (uri is not None):\n            try:\n                fh = URLopener().open(uri)\n            except IOError as e:\n                raise Exception(\n                    \"Failed to load sitemap/sitemapindex from %s (%s)\" %\n                    (uri, str(e)))\n        elif (str_data is not None):\n            fh = io.StringIO(str_data)\n        elif ('str' in kwargs):\n            self.logger.warn(\n                \"Legacy parse(str=...), use parse(str_data=...) instead\")\n            fh = io.StringIO(kwargs['str'])\n        if (fh is None):\n            raise Exception(\"Nothing to parse\")\n        s = self.new_sitemap()\n        s.parse_xml(\n            fh=fh,\n            resources=self,\n            capability=self.capability_name,\n            sitemapindex=False)\n        self.parsed_index = s.parsed_index",
    "docstring": "Parse a single XML document for this list.\n\n        Accepts either a uri (uri or default if parameter not specified),\n        or a filehandle (fh) or a string (str_data). Note that this method\n        does not handle the case of a sitemapindex+sitemaps.\n\n        LEGACY SUPPORT - the parameter str may be used in place of str_data\n        but is deprecated and will be removed in a later version."
  },
  {
    "code": "def fit(sim_mat, D_len, cidx):\n    min_energy = np.inf\n    for j in range(3):\n        inds = [np.argmin([sim_mat[idy].get(idx, 0) for idx in cidx]) for idy in range(D_len) if idy in sim_mat]\n        cidx = []\n        energy = 0\n        for i in np.unique(inds):\n            indsi = np.where(inds == i)[0]\n            minind, min_value = 0, 0\n            for index, idy in enumerate(indsi):\n                if idy in sim_mat:\n                    value = 0\n                    for idx in indsi:\n                        value += sim_mat[idy].get(idx, 0)\n                    if value < min_value:\n                        minind, min_value = index, value\n            energy += min_value\n            cidx.append(indsi[minind])\n        if energy < min_energy:\n            min_energy, inds_min, cidx_min = energy, inds, cidx\n    return inds_min, cidx_min",
    "docstring": "Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contains mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters.\n\n    D: numpy array - Symmetric distance matrix\n    k: int - number of clusters"
  },
  {
    "code": "def normal_from_points(a, b, c):\n    x1, y1, z1 = a\n    x2, y2, z2 = b\n    x3, y3, z3 = c\n    ab = (x2 - x1, y2 - y1, z2 - z1)\n    ac = (x3 - x1, y3 - y1, z3 - z1)\n    x, y, z = cross(ab, ac)\n    d = (x * x + y * y + z * z) ** 0.5\n    return (x / d, y / d, z / d)",
    "docstring": "Computes a normal vector given three points."
  },
  {
    "code": "def zero_downtime_index(index_name, index_config):\n    client = indices_client()\n    temporary_name = index_name + '_' + str(uuid.uuid4())\n    logging.info('creating index with config %s', index_config)\n    create_index(temporary_name, index_config, client)\n    try:\n        yield temporary_name\n        atomic_swap(index_name, temporary_name, client)\n    except Exception:\n        logging.error(\n            'deleting temporary index %s due to error:',\n            temporary_name,\n            exc_info=True\n        )\n        client.delete(index=temporary_name)",
    "docstring": "Context manager to create a new index based on a given alias,\n    allow the caller to index it, and then point the alias to the new index\n\n    Args:\n        index_name (str) Name of an alias that should point to the new index\n        index_config (dict) Configuration for the new index\n\n    Yields: (name) The full name of the new index"
  },
  {
    "code": "def handle_line(self, line):\n        if line.kind == ConfigLine.KIND_HEADER:\n            self.enter_block(line.header)\n        else:\n            self.insert_line(line)",
    "docstring": "Read one line."
  },
  {
    "code": "def one_symbol_ops_str(self) -> str:\n        return re.escape(''.join((key for key in self.ops.keys() if len(key) == 1)))",
    "docstring": "Regex-escaped string with all one-symbol operators"
  },
  {
    "code": "def individual_weights(self):\n        weights = self._raw_weights()\n        if weights.shape[1] == 0:\n            return np.zeros(weights.shape[0])\n        elif weights.shape[1] < self._ntaps:\n            return np.mean(weights, axis=1)\n        else:\n            return weights.dot(self._filter_coeffs)",
    "docstring": "Read individual weights from the load cells in grams.\n\n        Returns\n        -------\n        weight : float\n            The sensor weight in grams."
  },
  {
    "code": "def set(self, source_id=None, profile_id=None, filter_id=None, stage=None, profile_reference=None, filter_reference=None):\n        data = {}\n        data[\"source_id\"] = _validate_source_id(source_id)\n        if profile_id:\n            data[\"profile_id\"] = _validate_profile_id(profile_id)\n        if filter_id:\n            data[\"filter_id\"] = _validate_filter_id(filter_id)\n        if profile_reference:\n            data[\"profile_reference\"] = _validate_profile_reference(profile_reference)\n        if filter_reference:\n            data[\"filter_reference\"] = _validate_filter_reference(filter_reference)\n        data[\"stage\"] = _validate_stage(stage)\n        response = self.client.patch('profile/stage', data=data)\n        return response.json()",
    "docstring": "Edit the profile stage given a filter.\n\n        Args:\n            profile_id:             <string>\n                                    profile id\n        body params:\n            source_id:              <string>\n                                    source id associated to the profile\n\n            filter_id:                 <string>\n                                    filter id\n            stage:                 <string>\n                                    profiles' stage associated to the filter ( null for all, NEW, YES, LATER or NO).\n\n        Returns\n            Response that contains code 201 if successful\n            Other status codes otherwise."
  },
  {
    "code": "def search(self, buf):\n        self._check_type(buf)\n        normalized = unicodedata.normalize(self.FORM, buf)\n        idx = normalized.find(self._text)\n        if idx < 0:\n            return None\n        start = idx\n        end = idx + len(self._text)\n        return SequenceMatch(self, normalized[start:end], start, end)",
    "docstring": "Search the provided buffer for matching text.\n\n        Search the provided buffer for matching text. If the *match* is found,\n        returns a :class:`SequenceMatch` object, otherwise returns ``None``.\n\n        :param buf: Buffer to search for a match.\n        :return: :class:`SequenceMatch` if matched, None if no match was found."
  },
  {
    "code": "def componentsintobranch(idf, branch, listofcomponents, fluid=None):\n    if fluid is None:\n        fluid = ''\n    componentlist = [item[0] for item in listofcomponents]\n    thebranchname = branch.Name\n    thebranch = idf.removeextensibles('BRANCH', thebranchname)\n    e_index = idf.getextensibleindex('BRANCH', thebranchname)\n    theobj = thebranch.obj\n    modeleditor.extendlist(theobj, e_index)\n    for comp, compnode in listofcomponents:\n        theobj.append(comp.key)\n        theobj.append(comp.Name)\n        inletnodename = getnodefieldname(comp, \"Inlet_Node_Name\", fluid=fluid,\n                                         startswith=compnode)\n        theobj.append(comp[inletnodename])\n        outletnodename = getnodefieldname(comp, \"Outlet_Node_Name\",\n                                          fluid=fluid, startswith=compnode)\n        theobj.append(comp[outletnodename])\n        theobj.append('')\n    return thebranch",
    "docstring": "insert a list of components into a branch\n    fluid is only needed if there are air and water nodes in same object\n    fluid is Air or Water or ''.\n    if the fluid is Steam, use Water"
  },
  {
    "code": "def _get_codes_for_values(values, categories):\n    from pandas.core.algorithms import _get_data_algo, _hashtables\n    dtype_equal = is_dtype_equal(values.dtype, categories.dtype)\n    if dtype_equal:\n        values = getattr(values, '_ndarray_values', values)\n        categories = getattr(categories, '_ndarray_values', categories)\n    elif (is_extension_array_dtype(categories.dtype) and\n          is_object_dtype(values)):\n        try:\n            values = (\n                categories.dtype.construct_array_type()._from_sequence(values)\n            )\n        except Exception:\n            values = ensure_object(values)\n            categories = ensure_object(categories)\n    else:\n        values = ensure_object(values)\n        categories = ensure_object(categories)\n    (hash_klass, vec_klass), vals = _get_data_algo(values, _hashtables)\n    (_, _), cats = _get_data_algo(categories, _hashtables)\n    t = hash_klass(len(cats))\n    t.map_locations(cats)\n    return coerce_indexer_dtype(t.lookup(vals), cats)",
    "docstring": "utility routine to turn values into codes given the specified categories"
  },
  {
    "code": "def tasks(self, pattern=None, negate=False, state=None, limit=None, reverse=True,\n              params=None, success=False, error=True):\n        request = clearly_pb2.FilterTasksRequest(\n            tasks_filter=clearly_pb2.PatternFilter(pattern=pattern or '.',\n                                                   negate=negate),\n            state_pattern=state or '.', limit=limit, reverse=reverse\n        )\n        for task in about_time(ClearlyClient._fetched_callback, self._stub.filter_tasks(request)):\n            ClearlyClient._display_task(task, params, success, error)",
    "docstring": "Filters stored tasks and displays their current statuses.\n\n        Note that, to be able to list the tasks sorted chronologically, celery retrieves\n        tasks from the LRU event heap instead of the dict storage, so the total number\n        of tasks fetched may be different than the server `max_tasks` setting. For\n        instance, the `limit` field refers to max events searched, not max tasks.\n\n        Args:\n            Filter args:\n\n            pattern (Optional[str]): a pattern to filter tasks\n                ex.: '^dispatch|^email' to filter names starting with that\n                      or 'dispatch.*123456' to filter that exact name and number\n                      or even '123456' to filter that exact number anywhere.\n            negate (bool): if True, finds tasks that do not match criteria\n            state (Optional[str]): a celery task state to filter\n            limit (int): the maximum number of events to fetch\n                if None or 0, fetches all.\n            reverse (bool): if True (default), shows the most recent first\n\n            Display args:\n\n            params (Optional[bool]): if True shows args and kwargs in the first and\n                last seen states, if False never shows, and if None follows the\n                success and error arguments.\n                default is None\n            success (bool): if True shows successful tasks' results\n                default is False\n            error (bool): if True shows failed and retried tasks' tracebacks.\n                default is True, as you're monitoring to find errors, right?"
  },
  {
    "code": "def underscore_to_camelcase(value, first_upper=True):\n    value = str(value)\n    camelized = \"\".join(x.title() if x else '_' for x in value.split(\"_\"))\n    if not first_upper:\n        camelized = camelized[0].lower() + camelized[1:]\n    return camelized",
    "docstring": "Transform string from underscore_string to camelCase.\n\n    :param value: string with underscores\n    :param first_upper: the result will have its first character in upper case\n    :type value: str\n    :return: string in CamelCase or camelCase according to the first_upper\n    :rtype: str\n\n    :Example:\n        >>> underscore_to_camelcase('camel_case')\n        'CamelCase'\n        >>> underscore_to_camelcase('camel_case', False)\n        'camelCase'"
  },
  {
    "code": "def slackpkg_update(self):\n        NEW_ChangeLog_txt = URL(mirrors(\"ChangeLog.txt\", \"\")).reading()\n        if os.path.isfile(self.meta.slackpkg_lib_path + \"ChangeLog.txt.old\"):\n            os.remove(self.meta.slackpkg_lib_path + \"ChangeLog.txt.old\")\n        if os.path.isfile(self.meta.slackpkg_lib_path + \"ChangeLog.txt\"):\n            shutil.copy2(self.meta.slackpkg_lib_path + \"ChangeLog.txt\",\n                         self.meta.slackpkg_lib_path + \"ChangeLog.txt.old\")\n            os.remove(self.meta.slackpkg_lib_path + \"ChangeLog.txt\")\n        with open(self.meta.slackpkg_lib_path + \"ChangeLog.txt\", \"w\") as log:\n            log.write(NEW_ChangeLog_txt)\n            log.close()",
    "docstring": "This replace slackpkg ChangeLog.txt file with new\n        from Slackware official mirrors after update distribution."
  },
  {
    "code": "def get_projection(self, axis):\n        scale = axis.dot(self) / axis.dot(axis)\n        return axis * scale",
    "docstring": "Return the projection of this vector onto the given axis.  The \n        axis does not need to be normalized."
  },
  {
    "code": "def reboot(self, comment=None):\n        self.make_request(\n            NodeCommandFailed,\n            method='update',\n            resource='reboot',\n            params={'comment': comment})",
    "docstring": "Send reboot command to this node.\n\n        :param str comment: comment to audit\n        :raises NodeCommandFailed: reboot failed with reason\n        :return: None"
  },
  {
    "code": "def remove_role(role):\n    def processor(action, argument):\n        ActionRoles.query_by_action(action, argument=argument).filter(\n            ActionRoles.role_id == role.id\n        ).delete(synchronize_session=False)\n    return processor",
    "docstring": "Remove a action for a role."
  },
  {
    "code": "def is_config(python2=None, python3=None, windows=None, linux=None, osx=None):\n    return (\n        python2 in (None, is_python2)\n        and python3 in (None, is_python3)\n        and windows in (None, is_windows)\n        and linux in (None, is_linux)\n        and osx in (None, is_osx)\n    )",
    "docstring": "Check if a specific configuration of Python version and operating system\n    matches the user's setup. Mostly used to display targeted error messages.\n\n    python2 (bool): spaCy is executed with Python 2.x.\n    python3 (bool): spaCy is executed with Python 3.x.\n    windows (bool): spaCy is executed on Windows.\n    linux (bool): spaCy is executed on Linux.\n    osx (bool): spaCy is executed on OS X or macOS.\n    RETURNS (bool): Whether the configuration matches the user's platform.\n\n    DOCS: https://spacy.io/api/top-level#compat.is_config"
  },
  {
    "code": "def list_panes(pymux, variables):\n    w = pymux.arrangement.get_active_window()\n    active_pane = w.active_pane\n    result = []\n    for i, p in enumerate(w.panes):\n        process = p.process\n        result.append('%i: [%sx%s] [history %s/%s] %s' % (\n            i, process.sx, process.sy,\n            min(pymux.history_limit, process.screen.line_offset + process.sy),\n            pymux.history_limit,\n            ('(active)' if p == active_pane else '')))\n    result = '\\n'.join(sorted(result))\n    pymux.get_client_state().layout_manager.display_popup('list-keys', result)",
    "docstring": "Display a list of all the panes."
  },
  {
    "code": "def __track_job(self):\n        while not self.__verify_job_has_started():\n            time.sleep(self.__POLL_TIME)\n            self.__logger.debug(\"Waiting for Kubernetes job \" + self.uu_name + \" to start\")\n        self.__print_kubectl_hints()\n        status = self.__get_job_status()\n        while status == \"RUNNING\":\n            self.__logger.debug(\"Kubernetes job \" + self.uu_name + \" is running\")\n            time.sleep(self.__POLL_TIME)\n            status = self.__get_job_status()\n        assert status != \"FAILED\", \"Kubernetes job \" + self.uu_name + \" failed\"\n        self.__logger.info(\"Kubernetes job \" + self.uu_name + \" succeeded\")\n        self.signal_complete()",
    "docstring": "Poll job status while active"
  },
  {
    "code": "def set(key, value, timeout = -1, adapter = MemoryAdapter):\n\tif adapter(timeout = timeout).set(key, pickle.dumps(value)):\n\t\treturn value\n\telse:\n\t\treturn None",
    "docstring": "set cache by code, must set timeout length"
  },
  {
    "code": "def multiThreadCommands(agent_list,command_list,num_jobs=None):\n    if len(agent_list) == 1:\n        multiThreadCommandsFake(agent_list,command_list)\n        return None\n    if num_jobs is None:\n        num_jobs = min(len(agent_list),multiprocessing.cpu_count())\n    agent_list_out = Parallel(n_jobs=num_jobs)(delayed(runCommands)(*args) for args in zip(agent_list, len(agent_list)*[command_list]))\n    for j in range(len(agent_list)):\n        agent_list[j] = agent_list_out[j]",
    "docstring": "Executes the list of commands in command_list for each AgentType in agent_list\n    using a multithreaded system. Each command should be a method of that AgentType subclass.\n\n    Parameters\n    ----------\n    agent_list : [AgentType]\n        A list of instances of AgentType on which the commands will be run.\n    command_list : [string]\n        A list of commands to run for each AgentType in agent_list.\n\n    Returns\n    -------\n    None"
  },
  {
    "code": "def add_node_parents(root: ast.AST) -> None:\n    for node in ast.walk(root):\n        for child in ast.iter_child_nodes(node):\n            child.parent = node",
    "docstring": "Adds \"parent\" attribute to all child nodes of passed node.\n\n    Code taken from https://stackoverflow.com/a/43311383/1286705"
  },
  {
    "code": "def _get_domain_text_of_authoritative_zone(self):\n        from bs4 import BeautifulSoup\n        zones_response = self.session.get(self.URLS['domain_list'])\n        self._log('Zone', zones_response)\n        assert zones_response.status_code == 200, \\\n            'Could not retrieve domain list due to a network error.'\n        html = BeautifulSoup(zones_response.content, 'html.parser')\n        self._log('Zone', html)\n        domain_table = html.find('table', {'id': 'cp_domain_table'})\n        assert domain_table is not None, 'Could not find domain table'\n        domain = self.domain or ''\n        domain_text = None\n        subdomains = domain.split('.')\n        while True:\n            domain = '.'.join(subdomains)\n            LOGGER.debug('Check if %s has own zone', domain)\n            domain_text = domain_table.find(string=domain)\n            if domain_text is not None or len(subdomains) < 3:\n                break\n            subdomains.pop(0)\n        self.domain = domain\n        assert domain_text is not None, \\\n            'The domain does not exist on Easyname.'\n        return domain_text",
    "docstring": "Get the authoritative name zone."
  },
  {
    "code": "def register(self, signal, description):\n        return self.__app.signals.register(signal, self._plugin, description)",
    "docstring": "Registers a new signal.\n        Only registered signals are allowed to be send.\n\n        :param signal: Unique name of the signal\n        :param description: Description of the reason or use case, why this signal is needed.\n                            Used for documentation."
  },
  {
    "code": "def save(self, name):\n        with open(name, 'wb+') as f:\n            while True:\n                buf = self._fileobj.read()\n                if not buf:\n                    break\n                f.write(buf)",
    "docstring": "Saves the entire Docker context tarball to a separate file.\n\n        :param name: File path to save the tarball into.\n        :type name: unicode | str"
  },
  {
    "code": "def validate_index(self, rdf_class):\n        es_ids = set(self.get_es_ids())\n        tstore_ids = set([item[1]\n                          for item in self.get_uri_list(no_status=True)])\n        diff = es_ids - tstore_ids\n        if diff:\n            pdb.set_trace()\n            action_list = self.es_worker.make_action_list(diff,\n                                                          action_type=\"delete\")\n            results = self.es_worker.bulk_save(action_list)",
    "docstring": "Will compare the triplestore and elasticsearch index to ensure that\n        that elasticsearch and triplestore items match. elasticsearch records\n        that are not in the triplestore will be deleteed"
  },
  {
    "code": "def _handle_response(self, url, res, suppress_empty=True):\n        result = Connection._handle_response(self, url, res, suppress_empty)\n        if 'X-Rate-Limit-Time-Reset-Ms' in res.headers:\n            self.rate_limit = dict(ms_until_reset=int(res.headers['X-Rate-Limit-Time-Reset-Ms']),\n                                   window_size_ms=int(res.headers['X-Rate-Limit-Time-Window-Ms']),\n                                   requests_remaining=int(res.headers['X-Rate-Limit-Requests-Left']),\n                                   requests_quota=int(res.headers['X-Rate-Limit-Requests-Quota']))\n            if self.rate_limiting_management:\n                if self.rate_limiting_management['min_requests_remaining'] >= self.rate_limit['requests_remaining']:\n                    if self.rate_limiting_management['wait']:\n                        sleep(ceil(float(self.rate_limit['ms_until_reset']) / 1000))\n                    if self.rate_limiting_management.get('callback_function'):\n                        callback = self.rate_limiting_management['callback_function']\n                        args_dict = self.rate_limiting_management.get('callback_args')\n                        if args_dict:\n                            callback(args_dict)\n                        else:\n                            callback()\n        return result",
    "docstring": "Adds rate limiting information on to the response object"
  },
  {
    "code": "def _populate_attributes(self, config, record, context, data):\n        search_return_attributes = config['search_return_attributes']\n        for attr in search_return_attributes.keys():\n            if attr in record[\"attributes\"]:\n                if record[\"attributes\"][attr]:\n                    data.attributes[search_return_attributes[attr]] = record[\"attributes\"][attr]\n                    satosa_logging(\n                        logger,\n                        logging.DEBUG,\n                        \"Setting internal attribute {} with values {}\".format(\n                            search_return_attributes[attr],\n                            record[\"attributes\"][attr]\n                            ),\n                        context.state\n                        )\n                else:\n                    satosa_logging(\n                        logger,\n                        logging.DEBUG,\n                        \"Not setting internal attribute {} because value {} is null or empty\".format(\n                            search_return_attributes[attr],\n                            record[\"attributes\"][attr]\n                            ),\n                        context.state\n                        )",
    "docstring": "Use a record found in LDAP to populate attributes."
  },
  {
    "code": "async def set_loop(self, loop_value):\n        if loop_value not in ['on', 'off', 'shuffle']:\n            self.statuslog.error(\"Loop value must be `off`, `on`, or `shuffle`\")\n            return\n        self.loop_type = loop_value\n        if self.loop_type == 'on':\n            self.statuslog.info(\"Looping on\")\n        elif self.loop_type == 'off':\n            self.statuslog.info(\"Looping off\")\n        elif self.loop_type == 'shuffle':\n            self.statuslog.info(\"Looping on and shuffling\")",
    "docstring": "Updates the loop value, can be 'off', 'on', or 'shuffle"
  },
  {
    "code": "def subclasses(cls, lst=None):\n    if lst is None:\n        lst = []\n    for sc in cls.__subclasses__():\n        if sc not in lst:\n            lst.append(sc)\n        subclasses(sc, lst=lst)\n    return lst",
    "docstring": "Recursively gather subclasses of cls."
  },
  {
    "code": "def run(self, module, dependency=False, kwargs={}):\n        try:\n            obj = self.load(module, kwargs)\n            if isinstance(obj, binwalk.core.module.Module) and obj.enabled:\n                obj.main()\n                self.status.clear()\n            if not dependency:\n                self.executed_modules[module] = obj\n                obj._unload_dependencies()\n                obj.unload()\n        except KeyboardInterrupt as e:\n            if self.status.running:\n                self.status.shutdown = True\n                while not self.status.finished:\n                    time.sleep(0.1)\n            raise e\n        return obj",
    "docstring": "Runs a specific module."
  },
  {
    "code": "def cdist_sq_periodic(ra, rb, L):\n    return np.sum(np.square(csep_periodic(ra, rb, L)), axis=-1)",
    "docstring": "Return the squared distance between each point in on set,\n    and every point in a second set, in periodic space.\n\n    Parameters\n    ----------\n    ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.\n        Two sets of points.\n    L: float array, shape (d,)\n        System lengths.\n\n    Returns\n    -------\n    cdist_sq: float array-like, shape (n, m, d)\n        cdist_sq[i, j] is the squared distance between point j and point i."
  },
  {
    "code": "def list_length(queue, backend='sqlite'):\n    queue_funcs = salt.loader.queues(__opts__)\n    cmd = '{0}.list_length'.format(backend)\n    if cmd not in queue_funcs:\n        raise SaltInvocationError('Function \"{0}\" is not available'.format(cmd))\n    ret = queue_funcs[cmd](queue=queue)\n    return ret",
    "docstring": "Provide the number of items in a queue\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-run queue.list_length myqueue\n        salt-run queue.list_length myqueue backend=sqlite"
  },
  {
    "code": "def dataSource(self, value):\n        if isinstance(value, DataSource):\n            self._dataSource = value\n        else:\n            raise TypeError(\"value must be a DataSource object\")",
    "docstring": "sets the datasource object"
  },
  {
    "code": "def astype(self, type_name):\n        if type_name == 'nddata':\n            return self.as_nddata()\n        if type_name == 'hdu':\n            return self.as_hdu()\n        raise ValueError(\"Unrecognized conversion type '%s'\" % (type_name))",
    "docstring": "Convert AstroImage object to some other kind of object."
  },
  {
    "code": "def has(self, id, domain):\n        assert isinstance(id, (str, unicode))\n        assert isinstance(domain, (str, unicode))\n        if self.defines(id, domain):\n            return True\n        if self.fallback_catalogue is not None:\n            return self.fallback_catalogue.has(id, domain)\n        return False",
    "docstring": "Checks if a message has a translation.\n\n        @rtype: bool\n        @return: true if the message has a translation, false otherwise"
  },
  {
    "code": "def set_log_type_level(self, logType, level):\n        assert _is_number(level), \"level must be a number\"\n        level = float(level)\n        name = str(name)\n        self.__logTypeLevels[logType] = level",
    "docstring": "Set a logtype logging level.\n\n        :Parameters:\n           #. logType (string): A defined logging type.\n           #. level (number): The level of logging."
  },
  {
    "code": "def range_hourly(start=None, stop=None, timezone='UTC', count=None):\n    return stops(start=start, stop=stop, freq=HOURLY, timezone=timezone, count=count)",
    "docstring": "This an alternative way to generating sets of Delorean objects with\n    HOURLY stops"
  },
  {
    "code": "def get_objects(self):\n        objects = {}\n        for key in six.iterkeys(self.form_classes):\n            objects[key] = None\n        return objects",
    "docstring": "Returns dictionary with the instance objects for each form. Keys should match the\n        corresponding form."
  },
  {
    "code": "def update_vcs(self, fname, index):\n        fpath = os.path.dirname(fname)\n        branches, branch, files_modified = get_git_refs(fpath)\n        text = branch if branch else ''\n        if len(files_modified):\n            text = text + ' [{}]'.format(len(files_modified))\n        self.setVisible(bool(branch))\n        self.set_value(text)",
    "docstring": "Update vcs status."
  },
  {
    "code": "def EncodeMessageList(cls, message_list, packed_message_list):\n    uncompressed_data = message_list.SerializeToString()\n    packed_message_list.message_list = uncompressed_data\n    compressed_data = zlib.compress(uncompressed_data)\n    if len(compressed_data) < len(uncompressed_data):\n      packed_message_list.compression = (\n          rdf_flows.PackedMessageList.CompressionType.ZCOMPRESSION)\n      packed_message_list.message_list = compressed_data",
    "docstring": "Encode the MessageList into the packed_message_list rdfvalue."
  },
  {
    "code": "def get_protein_group_content(pgmap, master):\n    pg_content = [[0, master, protein, len(peptides), len([psm for pgpsms in\n                                                           peptides.values()\n                                                           for psm in pgpsms]),\n                   sum([psm[1] for pgpsms in peptides.values()\n                        for psm in pgpsms]),\n                   next(iter(next(iter(peptides.values()))))[3],\n                   next(iter(next(iter(peptides.values()))))[2],\n                   ]\n                  for protein, peptides in pgmap.items()]\n    return pg_content",
    "docstring": "For each master protein, we generate the protein group proteins\n    complete with sequences, psm_ids and scores. Master proteins are included\n    in this group.\n\n    Returns a list of [protein, master, pep_hits, psm_hits, protein_score],\n    which is ready to enter the DB table."
  },
  {
    "code": "def ls(ctx, available):\n    \"List installed datasets on path\"\n    path = ctx.obj['path']\n    global_ = ctx.obj['global_']\n    _ls(available=available, **ctx.obj)",
    "docstring": "List installed datasets on path"
  },
  {
    "code": "def pop_with_body_instrs(setup_with_instr, queue):\n    body_instrs = popwhile(op.is_not(setup_with_instr.arg), queue, side='left')\n    load_none = body_instrs.pop()\n    expect(load_none, instrs.LOAD_CONST, \"at end of with-block\")\n    pop_block = body_instrs.pop()\n    expect(pop_block, instrs.POP_BLOCK, \"at end of with-block\")\n    if load_none.arg is not None:\n        raise DecompilationError(\n            \"Expected LOAD_CONST(None), but got \"\n            \"%r instead\" % (load_none)\n        )\n    with_cleanup = queue.popleft()\n    expect(with_cleanup, instrs.WITH_CLEANUP, \"at end of with-block\")\n    end_finally = queue.popleft()\n    expect(end_finally, instrs.END_FINALLY, \"at end of with-block\")\n    return body_instrs",
    "docstring": "Pop instructions from `queue` that form the body of a with block."
  },
  {
    "code": "def _plain_or_callable(obj):\n    if callable(obj):\n        return obj()\n    elif isinstance(obj, types.GeneratorType):\n        return next(obj)\n    else:\n        return obj",
    "docstring": "Returns the value of the called object of obj is a callable,\n    otherwise the plain object.\n    Returns None if obj is None.\n\n    >>> obj = None\n    >>> _plain_or_callable(obj)\n\n    >>> stmt = 'select * from sys.nodes'\n    >>> _plain_or_callable(stmt)\n    'select * from sys.nodes'\n\n    >>> def _args():\n    ...     return [1, 'name']\n    >>> _plain_or_callable(_args)\n    [1, 'name']\n\n    >>> _plain_or_callable((x for x in range(10)))\n    0\n\n    >>> class BulkArgsGenerator:\n    ...     def __call__(self):\n    ...         return [[1, 'foo'], [2, 'bar'], [3, 'foobar']]\n    >>> _plain_or_callable(BulkArgsGenerator())\n    [[1, 'foo'], [2, 'bar'], [3, 'foobar']]"
  },
  {
    "code": "def hscan(self, name, cursor='0', match=None, count=10):\n        def value_function():\n            values = self.hgetall(name)\n            values = list(values.items())\n            values.sort(key=lambda x: x[0])\n            return values\n        scanned = self._common_scan(value_function, cursor=cursor, match=match, count=count, key=lambda v: v[0])\n        scanned[1] = dict(scanned[1])\n        return scanned",
    "docstring": "Emulate hscan."
  },
  {
    "code": "def _validate_entity(entity):\n    if entity['type'] == 'cluster':\n        schema = ESXClusterEntitySchema.serialize()\n    elif entity['type'] == 'vcenter':\n        schema = VCenterEntitySchema.serialize()\n    else:\n        raise ArgumentValueError('Unsupported entity type \\'{0}\\''\n                                 ''.format(entity['type']))\n    try:\n        jsonschema.validate(entity, schema)\n    except jsonschema.exceptions.ValidationError as exc:\n        raise InvalidEntityError(exc)",
    "docstring": "Validates the entity dict representation\n\n    entity\n        Dictionary representation of an entity.\n        See ``_get_entity`` docstrings for format."
  },
  {
    "code": "def get_ngrams(path):\n    with open(path, encoding='utf-8') as fh:\n        ngrams = [ngram.strip() for ngram in fh.readlines()]\n    return ngrams",
    "docstring": "Returns a list of n-grams read from the file at `path`."
  },
  {
    "code": "def get_extents(self, view, ranges, range_type='combined'):\n        if range_type not in ('data', 'combined'):\n            return (None,)*4\n        lower = -self.radius_outer\n        upper = 2 * self.max_radius + self.radius_outer\n        return (lower, lower, upper, upper)",
    "docstring": "Supply custom, static extents because radial heatmaps always have\n        the same boundaries."
  },
  {
    "code": "def buckets_delete(self, bucket):\n    url = Api._ENDPOINT + (Api._BUCKET_PATH % bucket)\n    google.datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials,\n                                      raw_response=True)",
    "docstring": "Issues a request to delete a bucket.\n\n    Args:\n      bucket: the name of the bucket.\n    Raises:\n      Exception if there is an error performing the operation."
  },
  {
    "code": "def from_nibabel(nib_image):\n    tmpfile = mktemp(suffix='.nii.gz')\n    nib_image.to_filename(tmpfile)\n    new_img = iio2.image_read(tmpfile)\n    os.remove(tmpfile)\n    return new_img",
    "docstring": "Convert a nibabel image to an ANTsImage"
  },
  {
    "code": "def check_config(data):\n    is_right = True\n    if \"title\" not in data:\n        logging.error(\"No 'title' in _config.yml\")\n        is_right = False\n    return is_right",
    "docstring": "Check if metadata is right\n\n    TODO(crow): check more"
  },
  {
    "code": "def _set_listener(instance, obs):\n    if obs.names is everything:\n        names = list(instance._props)\n    else:\n        names = obs.names\n    for name in names:\n        if name not in instance._listeners:\n            instance._listeners[name] = {typ: [] for typ in LISTENER_TYPES}\n        instance._listeners[name][obs.mode] += [obs]",
    "docstring": "Add listeners to a HasProperties instance"
  },
  {
    "code": "def set_default_subject(self, subject):\n        if not (\n            isinstance(subject, Subject)\n            or isinstance(subject, (int, str,))\n        ):\n            raise TypeError\n        if isinstance(subject, Subject):\n            _subject_id = subject.id\n        else:\n            _subject_id = str(subject)\n        self.http_post(\n            '{}/links/default_subject'.format(self.id),\n            json={'default_subject': _subject_id},\n        )",
    "docstring": "Sets the subject's location media URL as a link.\n        It displays as the default subject on PFE.\n\n        - **subject** can be a single :py:class:`.Subject` instance or a single\n          subject ID.\n\n        Examples::\n\n            collection.set_default_subject(1234)\n            collection.set_default_subject(Subject(1234))"
  },
  {
    "code": "def add_environment_information(meta):\n        meta[\"timestamp\"] = datetime.utcnow().isoformat(\" \")\n        meta[\"platform\"] = platform.system()\n        meta[\"release\"] = platform.release()\n        meta[\"python\"] = platform.python_version()\n        meta[\"packages\"] = get_pkg_info(\"memote\")",
    "docstring": "Record environment information."
  },
  {
    "code": "def _create_factor_rule(tok):\n        if tok[0] == 'IPV4':\n            return IPV4Rule(tok[1])\n        if tok[0] == 'IPV6':\n            return IPV6Rule(tok[1])\n        if tok[0] == 'DATETIME':\n            return DatetimeRule(tok[1])\n        if tok[0] == 'TIMEDELTA':\n            return TimedeltaRule(tok[1])\n        if tok[0] == 'INTEGER':\n            return IntegerRule(tok[1])\n        if tok[0] == 'FLOAT':\n            return FloatRule(tok[1])\n        if tok[0] == 'VARIABLE':\n            return VariableRule(tok[1])\n        return ConstantRule(tok[1])",
    "docstring": "Simple helper method for creating factor node objects based on node name."
  },
  {
    "code": "def resize_image(self, data, size):\n        from machina.core.compat import PILImage as Image\n        image = Image.open(BytesIO(data))\n        image.thumbnail(size, Image.ANTIALIAS)\n        string = BytesIO()\n        image.save(string, format='PNG')\n        return string.getvalue()",
    "docstring": "Resizes the given image to fit inside a box of the given size."
  },
  {
    "code": "def add_node_collection(self, node, collection):\n        assert node in self.assigned_work\n        if self.collection_is_completed:\n            assert self.collection\n            if collection != self.collection:\n                other_node = next(iter(self.registered_collections.keys()))\n                msg = report_collection_diff(\n                    self.collection, collection, other_node.gateway.id, node.gateway.id\n                )\n                self.log(msg)\n                return\n        self.registered_collections[node] = list(collection)",
    "docstring": "Add the collected test items from a node.\n\n        The collection is stored in the ``.registered_collections`` dictionary.\n\n        Called by the hook:\n\n        - ``DSession.worker_collectionfinish``."
  },
  {
    "code": "def spi_configure(self, polarity, phase, bitorder):\n        ret = api.py_aa_spi_configure(self.handle, polarity, phase, bitorder)\n        _raise_error_if_negative(ret)",
    "docstring": "Configure the SPI interface."
  },
  {
    "code": "def dispatch(table, args):\n    if len(args) == 1:\n        print_help(args[0], table)\n        sys.exit(0)\n    if args[1] not in table or len(args) != len(table[args[1]]) + 1:\n        print_help(args[0], table, dest=sys.stderr)\n        sys.exit(1)\n    sig = table[args[1]]\n    try:\n        fixed_args = [type_(arg) for arg, type_ in zip(args[2:], sig[1:])]\n    except TypeError:\n        print_help(args[0], table, dest=sys.stderr)\n        sys.exit(1)\n    sig[0](*fixed_args)",
    "docstring": "Dispatches to a function based on the contents of `args`."
  },
  {
    "code": "def set_sampled_topics(self, sampled_topics):\n        assert sampled_topics.dtype == np.int and \\\n            len(sampled_topics.shape) <= 2\n        if len(sampled_topics.shape) == 1:\n            self.sampled_topics = \\\n                sampled_topics.reshape(1, sampled_topics.shape[0])\n        else:\n            self.sampled_topics = sampled_topics\n        self.samples = self.sampled_topics.shape[0]\n        self.tt = self.tt_comp(self.sampled_topics)\n        self.dt = self.dt_comp(self.sampled_topics)",
    "docstring": "Allocate sampled topics to the documents rather than estimate them.\n        Automatically generate term-topic and document-topic matrices."
  },
  {
    "code": "def write(self, s):\n        if not self.isalive():\n            raise EOFError('Pty is closed')\n        if PY2:\n            s = _unicode(s)\n        success, nbytes = self.pty.write(s)\n        if not success:\n            raise IOError('Write failed')\n        return nbytes",
    "docstring": "Write the string ``s`` to the pseudoterminal.\n\n        Returns the number of bytes written."
  },
  {
    "code": "def auto_select_categorical_features(X, threshold=10):\n    feature_mask = []\n    for column in range(X.shape[1]):\n        if sparse.issparse(X):\n            indptr_start = X.indptr[column]\n            indptr_end = X.indptr[column + 1]\n            unique = np.unique(X.data[indptr_start:indptr_end])\n        else:\n            unique = np.unique(X[:, column])\n        feature_mask.append(len(unique) <= threshold)\n    return feature_mask",
    "docstring": "Make a feature mask of categorical features in X.\n\n    Features with less than 10 unique values are considered categorical.\n\n    Parameters\n    ----------\n    X : array-like or sparse matrix, shape=(n_samples, n_features)\n        Dense array or sparse matrix.\n\n    threshold : int\n        Maximum number of unique values per feature to consider the feature\n        to be categorical.\n\n    Returns\n    -------\n    feature_mask : array of booleans of size {n_features, }"
  },
  {
    "code": "def get_num_sequenced(study_id):\n    data = {'cmd': 'getCaseLists',\n            'cancer_study_id': study_id}\n    df = send_request(**data)\n    if df.empty:\n        return 0\n    row_filter = df['case_list_id'].str.contains('sequenced', case=False)\n    num_case = len(df[row_filter]['case_ids'].tolist()[0].split(' '))\n    return num_case",
    "docstring": "Return number of sequenced tumors for given study.\n\n    This is useful for calculating mutation statistics in terms of the\n    prevalence of certain mutations within a type of cancer.\n\n    Parameters\n    ----------\n    study_id : str\n        The ID of the cBio study.\n        Example: 'paad_icgc'\n\n    Returns\n    -------\n    num_case : int\n        The number of sequenced tumors in the given study"
  },
  {
    "code": "def _register_dependencies(self):\n        for tree_name, context_entry in context.timetable_context.items():\n            tree = self.trees[tree_name]\n            assert isinstance(tree, MultiLevelTree)\n            for dependent_on in context_entry.dependent_on:\n                dependent_on_tree = self.trees[dependent_on]\n                assert isinstance(dependent_on_tree, MultiLevelTree)\n                tree.register_dependent_on(dependent_on_tree)",
    "docstring": "register dependencies between trees"
  },
  {
    "code": "def raise_for_api_error(headers: MutableMapping, data: MutableMapping) -> None:\n    if not data[\"ok\"]:\n        raise exceptions.SlackAPIError(data.get(\"error\", \"unknow_error\"), headers, data)\n    if \"warning\" in data:\n        LOG.warning(\"Slack API WARNING: %s\", data[\"warning\"])",
    "docstring": "Check request response for Slack API error\n\n    Args:\n        headers: Response headers\n        data: Response data\n\n    Raises:\n        :class:`slack.exceptions.SlackAPIError`"
  },
  {
    "code": "def _get_memmap(self):\n        with open(self.filename) as fp:\n            data_dtype = self._get_data_dtype()\n            hdr_size = native_header.itemsize\n            return np.memmap(fp, dtype=data_dtype,\n                             shape=(self.mda['number_of_lines'],),\n                             offset=hdr_size, mode=\"r\")",
    "docstring": "Get the memory map for the SEVIRI data"
  },
  {
    "code": "def hist2d(self, da, **kwargs):\n        if self.value is None or self.value == 'counts':\n            normed = False\n        else:\n            normed = True\n        y = da.values\n        x = da.coords[da.dims[0]].values\n        counts, xedges, yedges = np.histogram2d(\n            x, y, normed=normed, **kwargs)\n        if self.value == 'counts':\n            counts = counts / counts.sum().astype(float)\n        return counts, xedges, yedges",
    "docstring": "Make the two dimensional histogram\n\n        Parameters\n        ----------\n        da: xarray.DataArray\n            The data source"
  },
  {
    "code": "def trigger_replication_schedule(self, schedule_id, dry_run=False):\n    return self._post(\"replications/%s/run\" % schedule_id, ApiCommand,\n        params=dict(dryRun=dry_run),\n        api_version=3)",
    "docstring": "Trigger replication immediately. Start and end dates on the schedule will be\n    ignored.\n\n    @param schedule_id: The id of the schedule to trigger.\n    @param dry_run: Whether to execute a dry run.\n    @return: The command corresponding to the replication job.\n    @since: API v3"
  },
  {
    "code": "def _return_tag_task(self, task):\n        if self.security is None:\n            raise Exception('Tags require security')\n        tasks = [task]\n        transform_url = get_transform_url(\n            tasks, handle=self.handle, security=self.security,\n            apikey=self.apikey\n        )\n        response = make_call(\n            CDN_URL, 'get', handle=self.handle, security=self.security,\n            transform_url=transform_url\n        )\n        return response.json()",
    "docstring": "Runs both SFW and Tags tasks"
  },
  {
    "code": "def git_handler(unused_build_context, target, fetch, package_dir, tar):\n    target_name = split_name(target.name)\n    repo_dir = join(package_dir, fetch.name) if fetch.name else package_dir\n    try:\n        repo = git.Repo(repo_dir)\n    except (InvalidGitRepositoryError, NoSuchPathError):\n        repo = git.Repo.clone_from(fetch.uri, repo_dir)\n    assert repo.working_tree_dir == repo_dir\n    tar.add(package_dir, arcname=target_name, filter=gitfilter)",
    "docstring": "Handle remote Git repository URI.\n\n    Clone the repository under the private builder workspace (unless already\n    cloned), and add it to the package tar (filtering out git internals).\n\n    TODO(itamar): Support branches / tags / specific commit hashes\n    TODO(itamar): Support updating a cloned repository\n    TODO(itamar): Handle submodules?\n    TODO(itamar): Handle force pulls?"
  },
  {
    "code": "def update(self, *args, **kwargs):\n        self.augment_args(args, kwargs)\n        kwargs['log_action'] = kwargs.get('log_action', 'update')\n        if not self.rec:\n            return self.add(**kwargs)\n        else:\n            for k, v in kwargs.items():\n                if k not in ('source', 's_vid', 'table', 't_vid', 'partition', 'p_vid'):\n                    setattr(self.rec, k, v)\n            self._session.merge(self.rec)\n            if self._logger:\n                self._logger.info(self.rec.log_str)\n            self._session.commit()\n            self._ai_rec_id = None\n            return self.rec.id",
    "docstring": "Update the last section record"
  },
  {
    "code": "def newPanelTab(self):\n        view = self._currentPanel.currentView()\n        if view:\n            new_view = view.duplicate(self._currentPanel)\n            self._currentPanel.addTab(new_view, new_view.windowTitle())",
    "docstring": "Creates a new panel with a copy of the current widget."
  },
  {
    "code": "def all(self, fields=None, include_fields=True, page=None, per_page=None, extra_params=None):\n        params = extra_params or {}\n        params['fields'] = fields and ','.join(fields) or None\n        params['include_fields'] = str(include_fields).lower()\n        params['page'] = page\n        params['per_page'] = per_page\n        return self.client.get(self._url(), params=params)",
    "docstring": "Retrieves a list of all the applications.\n\n        Important: The client_secret and encryption_key attributes can only be\n        retrieved with the read:client_keys scope.\n\n        Args:\n           fields (list of str, optional): A list of fields to include or\n              exclude from the result (depending on include_fields). Empty to\n              retrieve all fields.\n\n           include_fields (bool, optional): True if the fields specified are\n              to be included in the result, False otherwise.\n\n           page (int): The result's page number (zero based).\n\n           per_page (int, optional): The amount of entries per page.\n\n           extra_params (dictionary, optional): The extra parameters to add to\n             the request. The fields, include_fields, page and per_page values\n             specified as parameters take precedence over the ones defined here.\n\n\n        See: https://auth0.com/docs/api/management/v2#!/Clients/get_clients"
  },
  {
    "code": "async def get_real_ext_ip(self):\n        while self._ip_hosts:\n            try:\n                timeout = aiohttp.ClientTimeout(total=self._timeout)\n                async with aiohttp.ClientSession(\n                    timeout=timeout, loop=self._loop\n                ) as session, session.get(self._pop_random_ip_host()) as resp:\n                    ip = await resp.text()\n            except asyncio.TimeoutError:\n                pass\n            else:\n                ip = ip.strip()\n                if self.host_is_ip(ip):\n                    log.debug('Real external IP: %s', ip)\n                    break\n        else:\n            raise RuntimeError('Could not get the external IP')\n        return ip",
    "docstring": "Return real external IP address."
  },
  {
    "code": "def _generate_standard_transitions(cls):\n        allowed_transitions = cls.context.get_config('transitions', {})\n        for key, transitions in allowed_transitions.items():\n            key = cls.context.new_meta['translator'].translate(key)\n            new_transitions = set()\n            for trans in transitions:\n                if not isinstance(trans, Enum):\n                    trans = cls.context.new_meta['translator'].translate(trans)\n                new_transitions.add(trans)\n            cls.context.new_transitions[key] = new_transitions\n        for state in cls.context.states_enum:\n            if state not in cls.context.new_transitions:\n                cls.context.new_transitions[state] = set()",
    "docstring": "Generate methods used for transitions."
  },
  {
    "code": "def create_calcs(self):\n        specs = self._combine_core_aux_specs()\n        for spec in specs:\n            spec['dtype_out_time'] = _prune_invalid_time_reductions(spec)\n        return [Calc(**sp) for sp in specs]",
    "docstring": "Generate a Calc object for each requested parameter combination."
  },
  {
    "code": "def make_similar_sized_bins(x, n):\n    y = np.array(x).flatten()\n    y.sort()\n    bins = [y[0]]\n    step = len(y) // n\n    for i in range(step, len(y), step):\n        v = y[i]\n        if v > bins[-1]:\n            bins.append(v)\n    bins[-1] = y[-1]\n    return np.array(bins)",
    "docstring": "Utility function to create a set of bins over the range of values in `x`\n    such that each bin contains roughly the same number of values.\n\n    Parameters\n    ----------\n    x : array_like\n        The values to be binned.\n    n : int\n        The number of bins to create.\n\n    Returns\n    -------\n    bins : ndarray\n        An array of bin edges.\n\n    Notes\n    -----\n    The actual number of bins returned may be less than `n` if `x` contains\n    integer values and any single value is represented more than len(x)//n\n    times."
  },
  {
    "code": "def generate_table(self, rows):\n        table = PrettyTable(**self.kwargs)\n        for row in self.rows:\n            if len(row[0]) < self.max_row_width:\n                appends = self.max_row_width - len(row[0])\n                for i in range(1, appends):\n                    row[0].append(\"-\")\n            if row[1] is True:\n                self.make_fields_unique(row[0])\n                table.field_names = row[0]\n            else:\n                table.add_row(row[0])\n        return table",
    "docstring": "Generates from a list of rows a PrettyTable object."
  },
  {
    "code": "def getidfobjectlist(idf):\n    idfobjects = idf.idfobjects  \n    idfobjlst = [idfobjects[key] for key in idf.model.dtls if idfobjects[key]]\n    idfobjlst = itertools.chain.from_iterable(idfobjlst)\n    idfobjlst = list(idfobjlst)\n    return idfobjlst",
    "docstring": "return a list of all idfobjects in idf"
  },
  {
    "code": "def get_urls(self):\n        from django.conf.urls import patterns, url\n        from views import DashboardWelcomeView\n        urls = super(AdminMixin, self).get_urls()\n        del urls[0]\n        custom_url = patterns(\n            '',\n            url(r'^$', self.admin_view(DashboardWelcomeView.as_view()), name=\"index\")\n        )\n        return custom_url + urls",
    "docstring": "Add our dashboard view to the admin urlconf. Deleted the default index."
  },
  {
    "code": "def create_done_path(done_path, uid=-1, gid=-1):\n    with open(done_path, 'wb'):\n        pass\n    os.chown(done_path, uid, gid);",
    "docstring": "create a done file to avoid re-doing the mon deployment"
  },
  {
    "code": "def _ConvertAnnotations(self, annotations):\n      flags = 0\n      if annotations:\n         for annotation in annotations:\n            flags |= self._mapFlags.get(annotation.name, 0)\n      return flags",
    "docstring": "Convert annotations to pyVmomi flags"
  },
  {
    "code": "def jump_server(self, msg=\"Changing servers\"):\n        if self.connection.is_connected():\n            self.connection.disconnect(msg)\n        next(self.servers)\n        self._connect()",
    "docstring": "Connect to a new server, possibly disconnecting from the current.\n\n        The bot will skip to next server in the server_list each time\n        jump_server is called."
  },
  {
    "code": "def reset_generation(self):\n        with self._lock:\n            self._generation = Generation.NO_GENERATION\n            self.rejoin_needed = True\n            self.state = MemberState.UNJOINED",
    "docstring": "Reset the generation and memberId because we have fallen out of the group."
  },
  {
    "code": "def authenticate(self, auth_token, auth_info, service_name):\n        try:\n            jwt_claims = self.get_jwt_claims(auth_token)\n        except Exception as error:\n            raise suppliers.UnauthenticatedException(u\"Cannot decode the auth token\",\n                                                     error)\n        _check_jwt_claims(jwt_claims)\n        user_info = UserInfo(jwt_claims)\n        issuer = user_info.issuer\n        if issuer not in self._issuers_to_provider_ids:\n            raise suppliers.UnauthenticatedException(u\"Unknown issuer: \" + issuer)\n        provider_id = self._issuers_to_provider_ids[issuer]\n        if not auth_info.is_provider_allowed(provider_id):\n            raise suppliers.UnauthenticatedException(u\"The requested method does not \"\n                                                     u\"allow provider id: \" + provider_id)\n        audiences = user_info.audiences\n        has_service_name = service_name in audiences\n        allowed_audiences = auth_info.get_allowed_audiences(provider_id)\n        intersected_audiences = set(allowed_audiences).intersection(audiences)\n        if not has_service_name and not intersected_audiences:\n            raise suppliers.UnauthenticatedException(u\"Audiences not allowed\")\n        return user_info",
    "docstring": "Authenticates the current auth token.\n\n        Args:\n          auth_token: the auth token.\n          auth_info: the auth configurations of the API method being called.\n          service_name: the name of this service.\n\n        Returns:\n          A constructed UserInfo object representing the identity of the caller.\n\n        Raises:\n          UnauthenticatedException: When\n            * the issuer is not allowed;\n            * the audiences are not allowed;\n            * the auth token has already expired."
  },
  {
    "code": "def _recurse_replace(obj, key, new_key, sub, remove):\n    if isinstance(obj, list):\n        return [_recurse_replace(x, key, new_key, sub, remove) for x in obj]\n    if isinstance(obj, dict):\n        for k, v in list(obj.items()):\n            if k == key and v in sub:\n                obj[new_key] = sub[v]\n                if remove:\n                    del obj[key]\n            else:\n                obj[k] = _recurse_replace(v, key, new_key, sub, remove)\n    return obj",
    "docstring": "Recursive helper for `replace_by_key`"
  },
  {
    "code": "def init0(self, dae):\n        if not self.system.pflow.config.flatstart:\n            dae.y[self.a] = self.angle + 1e-10 * uniform(self.n)\n            dae.y[self.v] = self.voltage\n        else:\n            dae.y[self.a] = matrix(0.0,\n                                   (self.n, 1), 'd') + 1e-10 * uniform(self.n)\n            dae.y[self.v] = matrix(1.0, (self.n, 1), 'd')",
    "docstring": "Set bus Va and Vm initial values"
  },
  {
    "code": "def direct_messages(self, delegate, params={}, extra_args=None):\n        return self.__get('/direct_messages.xml', delegate, params,\n                          txml.Direct, extra_args=extra_args)",
    "docstring": "Get direct messages for the authenticating user.\n\n        Search results are returned one message at a time a DirectMessage\n        objects"
  },
  {
    "code": "def median(self):\n        mu = self.mean()\n        ret_val = math.exp(mu)\n        if math.isnan(ret_val):\n            ret_val = float(\"inf\")\n        return ret_val",
    "docstring": "Computes the median of a log-normal distribution built with the stats data."
  },
  {
    "code": "def attention_mask_ignore_padding(inputs, dtype=tf.float32):\n  inputs = rename_length_to_memory_length(inputs)\n  return mtf.cast(mtf.equal(inputs, 0), dtype) * -1e9",
    "docstring": "Bias for encoder-decoder attention.\n\n  Args:\n    inputs: a mtf.Tensor with shape [..., length_dim]\n    dtype: a tf.dtype\n\n  Returns:\n    a mtf.Tensor with shape [..., memory_length_dim]"
  },
  {
    "code": "def fMeasure(self, label, beta=None):\n        if beta is None:\n            return self.call(\"fMeasure\", label)\n        else:\n            return self.call(\"fMeasure\", label, beta)",
    "docstring": "Returns f-measure."
  },
  {
    "code": "def reboot_adb_server():\n    _reboot_count = 0\n    _max_retry = 1\n    def _reboot():\n        nonlocal _reboot_count\n        if _reboot_count >= _max_retry:\n            raise RuntimeError('fail after retry {} times'.format(_max_retry))\n        _reboot_count += 1\n        return_code = subprocess.call(['adb', 'devices'], stdout=subprocess.DEVNULL)\n        if bool(return_code):\n            warnings.warn('return not zero, execute \"adb version\" failed')\n            raise EnvironmentError('adb did not work :(')\n    return _reboot",
    "docstring": "execute 'adb devices' to start adb server"
  },
  {
    "code": "def setup_logging(logfile, print_log_location=True, debug=False):\n    log_dir = os.path.dirname(logfile)\n    make_dir(log_dir)\n    fmt = '[%(levelname)s] %(name)s %(asctime)s %(message)s'\n    if debug:\n        logging.basicConfig(filename=logfile,\n                            filemode='w',\n                            format=fmt,\n                            level=logging.DEBUG)\n    else:\n        logging.basicConfig(filename=logfile,\n                            filemode='w',\n                            format=fmt,\n                            level=logging.INFO)\n    logger = logging.getLogger('log')\n    logger = add_stream_handler(logger)\n    if print_log_location:\n        logger.info('LOG LOCATION: {}'.format(logfile))",
    "docstring": "Set up logging using the built-in ``logging`` package.\n\n    A stream handler is added to all logs, so that logs at or above\n    ``logging.INFO`` level are printed to screen as well as written\n    to the log file.\n\n    Arguments:\n\n        logfile (str): Path to the log file. If the parent directory\n            does not exist, it will be created. Required.\n\n        print_log_location (bool): If ``True``, the log path will be\n            written to the log upon initialization. Default is ``True``.\n\n        debug (bool): If true, the log level will be set to ``logging.DEBUG``.\n            If ``False``, the log level will be set to ``logging.INFO``.\n            Default is ``False``."
  },
  {
    "code": "async def append(self, reply: Reply) \\\n            -> None:\n        result = reply.result\n        identifier = result.get(f.IDENTIFIER.nm)\n        txnId = result.get(TXN_ID)\n        logger.debug(\"Reply being sent {}\".format(reply))\n        if self._isNewTxn(identifier, reply, txnId):\n            self.addToProcessedTxns(identifier, txnId, reply)\n        if identifier not in self.responses:\n            self.responses[identifier] = asyncio.Queue()\n        await self.responses[identifier].put(reply)",
    "docstring": "Add the given Reply to this transaction store's list of responses.\n        Also add to processedRequests if not added previously."
  },
  {
    "code": "def write_tree(self):\n        mdb = MemoryDB()\n        entries = self._entries_sorted()\n        binsha, tree_items = write_tree_from_cache(entries, mdb, slice(0, len(entries)))\n        mdb.stream_copy(mdb.sha_iter(), self.repo.odb)\n        root_tree = Tree(self.repo, binsha, path='')\n        root_tree._cache = tree_items\n        return root_tree",
    "docstring": "Writes this index to a corresponding Tree object into the repository's\n        object database and return it.\n\n        :return: Tree object representing this index\n        :note: The tree will be written even if one or more objects the tree refers to\n            does not yet exist in the object database. This could happen if you added\n            Entries to the index directly.\n        :raise ValueError: if there are no entries in the cache\n        :raise UnmergedEntriesError:"
  },
  {
    "code": "def sky2ang(sky):\n        try:\n            theta_phi = sky.copy()\n        except AttributeError as _:\n            theta_phi = np.array(sky)\n        theta_phi[:, [1, 0]] = theta_phi[:, [0, 1]]\n        theta_phi[:, 0] = np.pi/2 - theta_phi[:, 0]\n        return theta_phi",
    "docstring": "Convert ra,dec coordinates to theta,phi coordinates\n        ra -> phi\n        dec -> theta\n\n        Parameters\n        ----------\n        sky : numpy.array\n            Array of (ra,dec) coordinates.\n            See :func:`AegeanTools.regions.Region.radec2sky`\n\n        Returns\n        -------\n        theta_phi : numpy.array\n            Array of (theta,phi) coordinates."
  },
  {
    "code": "def list_function_versions(FunctionName,\n                           region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        vers = []\n        for ret in __utils__['boto3.paged_call'](conn.list_versions_by_function,\n                                                 FunctionName=FunctionName):\n            vers.extend(ret['Versions'])\n        if not bool(vers):\n            log.warning('No versions found')\n        return {'Versions': vers}\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "List the versions available for the given function.\n\n    Returns list of function versions\n\n    CLI Example:\n\n    .. code-block:: yaml\n\n        versions:\n          - {...}\n          - {...}"
  },
  {
    "code": "def get_otp(hsm, args):\n    if args.no_otp:\n        return None\n    if hsm.version.have_unlock():\n        if args.stdin:\n            otp = sys.stdin.readline()\n            while otp and otp[-1] == '\\n':\n                otp = otp[:-1]\n        else:\n            otp = raw_input('Enter admin YubiKey OTP (press enter to skip) : ')\n        if len(otp) == 44:\n            return otp\n        if otp:\n            sys.stderr.write(\"ERROR: Invalid YubiKey OTP\\n\")\n    return None",
    "docstring": "Get OTP from YubiKey."
  },
  {
    "code": "def sbosrcarsh(self, prgnam, sbo_link, src_link):\n        sources = []\n        name = \"-\".join(prgnam.split(\"-\")[:-1])\n        category = \"{0}/{1}/\".format(sbo_link.split(\"/\")[-2], name)\n        for link in src_link:\n            source = link.split(\"/\")[-1]\n            sources.append(\"{0}{1}{2}\".format(self.meta.sbosrcarch_link,\n                                              category, source))\n        return sources",
    "docstring": "Alternative repository for sbo sources"
  },
  {
    "code": "def __collect_fields(self):\r\n        form = FormData()\r\n        form.add_field(self.__username_field, required=True,\r\n                       error=self.__username_error)\r\n        form.add_field(self.__password_field, required=True,\r\n                       error=self.__password_error)\r\n        form.parse()\r\n        self.username = form.values[self.__username_field]\r\n        self.password = form.values[self.__password_field]\r\n        return",
    "docstring": "Use field values from config.json and collect from request"
  },
  {
    "code": "def get_below_threshold(umi_quals, quality_encoding,  quality_filter_threshold):\n    umi_quals = [x - RANGES[quality_encoding][0] for x in map(ord, umi_quals)]\n    below_threshold = [x < quality_filter_threshold for x in umi_quals]\n    return below_threshold",
    "docstring": "test whether the umi_quals are below the threshold"
  },
  {
    "code": "def result_to_dict(raw_result):\n    result = {}\n    for channel_index, channel in enumerate(raw_result):\n        channel_id, channel_name = channel[0], channel[1]\n        channel_result = {\n            'id': channel_id,\n            'name': channel_name,\n            'movies': []\n        }\n        for movie in channel[2]:\n            channel_result['movies'].append({\n                'title': movie[1],\n                'start_time': datetime.fromtimestamp(movie[2]),\n                'end_time': datetime.fromtimestamp(movie[2] + movie[3]),\n                'inf': True if movie[3] else False,\n            })\n        result[channel_id] = channel_result\n    return result",
    "docstring": "Parse raw result from fetcher into readable dictionary\n\n    Args:\n        raw_result (dict) - raw data from `fetcher`\n\n    Returns:\n        dict - readable dictionary"
  },
  {
    "code": "def create_h5py_with_large_cache(filename, cache_size_mb):\n    propfaid = h5py.h5p.create(h5py.h5p.FILE_ACCESS)\n    settings = list(propfaid.get_cache())\n    settings[2] = 1024 * 1024 * cache_size_mb\n    propfaid.set_cache(*settings)\n    fid = h5py.h5f.create(filename, flags=h5py.h5f.ACC_EXCL, fapl=propfaid)\n    fin = h5py.File(fid)\n    return fin",
    "docstring": "Allows to open the hdf5 file with specified cache size"
  },
  {
    "code": "def save_trajs(trajs, fn, meta, key_to_path=None):\n    if key_to_path is None:\n        key_to_path = default_key_to_path\n    validate_keys(meta.index, key_to_path)\n    backup(fn)\n    os.mkdir(fn)\n    for k in meta.index:\n        v = trajs[k]\n        npy_fn = os.path.join(fn, key_to_path(k))\n        os.makedirs(os.path.dirname(npy_fn), exist_ok=True)\n        np.save(npy_fn, v)",
    "docstring": "Save trajectory-like data\n\n    Data is stored in individual numpy binary files in the\n    directory given by ``fn``.\n\n    This method will automatically back up existing files named ``fn``.\n\n    Parameters\n    ----------\n    trajs : dict of (key, np.ndarray)\n        Dictionary of trajectory-like ndarray's keyed on ``meta.index``\n        values.\n    fn : str\n        Where to save the data. This will be a directory containing\n        one file per trajectory\n    meta : pd.DataFrame\n        The DataFrame of metadata"
  },
  {
    "code": "def xgroup_create(self, stream, group_name, latest_id='$', mkstream=False):\n        args = [b'CREATE', stream, group_name, latest_id]\n        if mkstream:\n            args.append(b'MKSTREAM')\n        fut = self.execute(b'XGROUP', *args)\n        return wait_ok(fut)",
    "docstring": "Create a consumer group"
  },
  {
    "code": "def print_exception(*args, file=None, **kwargs):\n    for line in format_exception(*args, **kwargs):\n        vtml.vtmlprint(line, file=file)",
    "docstring": "Print the formatted output of an exception object."
  },
  {
    "code": "def load_config(name, base='conf'):\n    fname = pjoin(base, name + '.json')\n    if not os.path.exists(fname):\n        return {}\n    try:\n        with open(fname) as f:\n            cfg = json.load(f)\n    except Exception as e:\n        warn(\"Couldn't load %s: %s\" % (fname, e))\n        cfg = {}\n    return cfg",
    "docstring": "Load config dict from JSON"
  },
  {
    "code": "def rename_datastore(datastore_name, new_datastore_name,\n                     service_instance=None):\n    log.trace('Renaming datastore %s to %s', datastore_name, new_datastore_name)\n    target = _get_proxy_target(service_instance)\n    datastores = salt.utils.vmware.get_datastores(\n        service_instance,\n        target,\n        datastore_names=[datastore_name])\n    if not datastores:\n        raise VMwareObjectRetrievalError('Datastore \\'{0}\\' was not found'\n                                         ''.format(datastore_name))\n    ds = datastores[0]\n    salt.utils.vmware.rename_datastore(ds, new_datastore_name)\n    return True",
    "docstring": "Renames a datastore. The datastore needs to be visible to the proxy.\n\n    datastore_name\n        Current datastore name.\n\n    new_datastore_name\n        New datastore name.\n\n    service_instance\n        Service instance (vim.ServiceInstance) of the vCenter/ESXi host.\n        Default is None.\n\n    .. code-block:: bash\n\n        salt '*' vsphere.rename_datastore old_name new_name"
  },
  {
    "code": "def canonical(request, uploaded_at, file_id):\n    filer_file = get_object_or_404(File, pk=file_id, is_public=True)\n    if (uploaded_at != filer_file.uploaded_at.strftime('%s') or\n            not filer_file.file):\n        raise Http404('No %s matches the given query.' %\n                      File._meta.object_name)\n    return redirect(filer_file.url)",
    "docstring": "Redirect to the current url of a public file"
  },
  {
    "code": "def create(cls, scheduled_analysis, tags=None, json_report_objects=None, raw_report_objects=None, additional_metadata=None, analysis_date=None):\n        if tags is None:\n            tags = []\n        if additional_metadata is None:\n            additional_metadata = {}\n        if analysis_date is None:\n            analysis_date = datetime.datetime.now()\n        url = cls._creation_point.format(scheduled_analysis=scheduled_analysis.id)\n        return cls._create(url=url, analysis_date=analysis_date, additional_json_files=json_report_objects,\n                           additional_binary_files=raw_report_objects, tags=tags,\n                           additional_metadata=additional_metadata, force_multipart=True)",
    "docstring": "Create a new report.\n\n        For convenience :func:`~mass_api_client.resources.scheduled_analysis.ScheduledAnalysis.create_report`\n        of class :class:`.ScheduledAnalysis` can be used instead.\n\n        :param scheduled_analysis: The :class:`.ScheduledAnalysis` this report was created for\n        :param tags: A list of strings\n        :param json_report_objects: A dictionary of JSON reports, where the key is the object name.\n        :param raw_report_objects: A dictionary of binary file reports, where the key is the file name.\n        :param analysis_date: A datetime object of the time the report was generated. Defaults to current time.\n        :return: The newly created report object"
  },
  {
    "code": "def Proxy(self, status, headers, exc_info=None):\n    self.call_context['status'] = status\n    self.call_context['headers'] = headers\n    self.call_context['exc_info'] = exc_info\n    return self.body_buffer.write",
    "docstring": "Save args, defer start_response until response body is parsed.\n\n    Create output buffer for body to be written into.\n    Note: this is not quite WSGI compliant: The body should come back as an\n      iterator returned from calling service_app() but instead, StartResponse\n      returns a writer that will be later called to output the body.\n    See google/appengine/ext/webapp/__init__.py::Response.wsgi_write()\n        write = start_response('%d %s' % self.__status, self.__wsgi_headers)\n        write(body)\n\n    Args:\n      status: Http status to be sent with this response\n      headers: Http headers to be sent with this response\n      exc_info: Exception info to be displayed for this response\n    Returns:\n      callable that takes as an argument the body content"
  },
  {
    "code": "def add_filter(self, filter_or_string, *args, **kwargs):\n        self.root_filter.add_filter(filter_or_string, *args, **kwargs)\n        return self",
    "docstring": "Adds a filter to the query builder's filters.\n\n        :return: :class:`~es_fluent.builder.QueryBuilder`"
  },
  {
    "code": "def change_disk_usage(self, usage_change, file_path, st_dev):\n        mount_point = self._mount_point_for_device(st_dev)\n        if mount_point:\n            total_size = mount_point['total_size']\n            if total_size is not None:\n                if total_size - mount_point['used_size'] < usage_change:\n                    self.raise_io_error(errno.ENOSPC, file_path)\n            mount_point['used_size'] += usage_change",
    "docstring": "Change the used disk space by the given amount.\n\n        Args:\n            usage_change: Number of bytes added to the used space.\n                If negative, the used space will be decreased.\n\n            file_path: The path of the object needing the disk space.\n\n            st_dev: The device ID for the respective file system.\n\n        Raises:\n            IOError: if usage_change exceeds the free file system space"
  },
  {
    "code": "def buffer_to_value(self, obj, buffer, offset, default_endianness=DEFAULT_ENDIANNESS):\n        try:\n            value, length = struct.unpack_from(str(self.endianness or default_endianness)\n                                      + self.struct_format, buffer, offset)[0], struct.calcsize(self.struct_format)\n            if self._enum is not None:\n                try:\n                    return self._enum(value), length\n                except ValueError as e:\n                    raise PacketDecodeError(\"{}: {}\".format(self.type, e))\n            else:\n                return value, length\n        except struct.error as e:\n            raise PacketDecodeError(\"{}: {}\".format(self.type, e))",
    "docstring": "Converts the bytes in ``buffer`` at ``offset`` to a native Python value. Returns that value and the number of\n        bytes consumed to create it.\n\n        :param obj: The parent :class:`.PebblePacket` of this field\n        :type obj: .PebblePacket\n        :param buffer: The buffer from which to extract a value.\n        :type buffer: bytes\n        :param offset: The offset in the buffer to start at.\n        :type offset: int\n        :param default_endianness: The default endianness of the value. Used if ``endianness`` was not passed to the\n                                   :class:`Field` constructor.\n        :type default_endianness: str\n        :return: (value, length)\n        :rtype: (:class:`object`, :any:`int`)"
  },
  {
    "code": "def define_noisy_gate(self, name, qubit_indices, kraus_ops):\n        kraus_ops = [np.asarray(k, dtype=np.complex128) for k in kraus_ops]\n        _check_kraus_ops(len(qubit_indices), kraus_ops)\n        return self.inst(_create_kraus_pragmas(name, tuple(qubit_indices), kraus_ops))",
    "docstring": "Overload a static ideal gate with a noisy one defined in terms of a Kraus map.\n\n        .. note::\n\n            The matrix elements along each axis are ordered by bitstring. For two qubits the order\n            is ``00, 01, 10, 11``, where the the bits **are ordered in reverse** by the qubit index,\n            i.e., for qubits 0 and 1 the bitstring ``01`` indicates that qubit 0 is in the state 1.\n            See also :ref:`the related documentation section in the QVM Overview <basis-ordering>`.\n\n\n        :param str name: The name of the gate.\n        :param tuple|list qubit_indices: The qubits it acts on.\n        :param tuple|list kraus_ops: The Kraus operators.\n        :return: The Program instance\n        :rtype: Program"
  },
  {
    "code": "def validate_exported_interfaces(object_class, exported_intfs):\n    if (\n        not exported_intfs\n        or not isinstance(exported_intfs, list)\n        or not exported_intfs\n    ):\n        return False\n    else:\n        for exintf in exported_intfs:\n            if exintf not in object_class:\n                return False\n    return True",
    "docstring": "Validates that the exported interfaces are all provided by the service\n\n    :param object_class: The specifications of a service\n    :param exported_intfs: The exported specifications\n    :return: True if the exported specifications are all provided by the service"
  },
  {
    "code": "def _get_edge_dict(self):\n        edge_dict = collections.defaultdict(lambda: [])\n        if len(self._edges) > 0:\n            for e in self._edges:\n                data = e['data']\n                key = tuple([data['i'], data['source'],\n                            data['target'], data['polarity']])\n                edge_dict[key] = data['id']\n        return edge_dict",
    "docstring": "Return a dict of edges.\n\n        Keyed tuples of (i, source, target, polarity)\n        with lists of edge ids [id1, id2, ...]"
  },
  {
    "code": "def add_sparql_line_nums(sparql):\n    lines = sparql.split(\"\\n\")\n    return \"\\n\".join([\"%s %s\" % (i + 1, line) for i, line in enumerate(lines)])",
    "docstring": "Returns a sparql query with line numbers prepended"
  },
  {
    "code": "def _update_id(record, new_id):\n    old_id = record.id\n    record.id = new_id\n    record.description = re.sub('^' + re.escape(old_id), new_id, record.description)\n    return record",
    "docstring": "Update a record id to new_id, also modifying the ID in record.description"
  },
  {
    "code": "def set_i(self, i, data, field, side):\n        edge = self.get_i(i, side)\n        setattr(edge, field, data[edge.slice])",
    "docstring": "Assigns data on the i'th tile to the data 'field' of the 'side'\n        edge of that tile"
  },
  {
    "code": "def as_lwp_str(self, ignore_discard=True, ignore_expires=True):\n        now = time.time()\n        r = []\n        for cookie in self:\n            if not ignore_discard and cookie.discard:\n                continue\n            if not ignore_expires and cookie.is_expired(now):\n                continue\n            r.append(\"Set-Cookie3: %s\" % lwp_cookie_str(cookie))\n        return \"\\n\".join(r+[\"\"])",
    "docstring": "Return cookies as a string of \"\\\\n\"-separated \"Set-Cookie3\" headers.\n\n        ignore_discard and ignore_expires: see docstring for FileCookieJar.save"
  },
  {
    "code": "def register_tc_plugins(self, plugin_name, plugin_class):\n        if plugin_name in self.registered_plugins:\n            raise PluginException(\"Plugin {} already registered! Duplicate \"\n                                  \"plugins?\".format(plugin_name))\n        self.logger.debug(\"Registering plugin %s\", plugin_name)\n        plugin_class.init(bench=self.bench)\n        if plugin_class.get_bench_api() is not None:\n            register_func = self.plugin_types[PluginTypes.BENCH]\n            register_func(plugin_name, plugin_class)\n        if plugin_class.get_parsers() is not None:\n            register_func = self.plugin_types[PluginTypes.PARSER]\n            register_func(plugin_name, plugin_class)\n        if plugin_class.get_external_services() is not None:\n            register_func = self.plugin_types[PluginTypes.EXTSERVICE]\n            register_func(plugin_name, plugin_class)\n        self.registered_plugins.append(plugin_name)",
    "docstring": "Loads a plugin as a dictionary and attaches needed parts to correct areas for testing\n        parts.\n\n        :param plugin_name: Name of the plugins\n        :param plugin_class: PluginBase\n        :return: Nothing"
  },
  {
    "code": "def nodes_geometry(self):\n        nodes = np.array([\n            n for n in self.transforms.nodes()\n            if 'geometry' in self.transforms.node[n]\n        ])\n        return nodes",
    "docstring": "The nodes in the scene graph with geometry attached.\n\n        Returns\n        ------------\n        nodes_geometry: (m,) array, of node names"
  },
  {
    "code": "def dump_begin(self, selector_id):\n        if self.dump_walker is not None:\n            self.storage.destroy_walker(self.dump_walker)\n        selector = DataStreamSelector.FromEncoded(selector_id)\n        self.dump_walker = self.storage.create_walker(selector, skip_all=False)\n        return Error.NO_ERROR, Error.NO_ERROR, self.dump_walker.count()",
    "docstring": "Start dumping a stream.\n\n        Args:\n            selector_id (int): The buffered stream we want to dump.\n\n        Returns:\n            (int, int, int): Error code, second error code, number of available readings"
  },
  {
    "code": "def TeXLaTeXStrFunction(target = None, source= None, env=None):\n    if env.GetOption(\"no_exec\"):\n        basedir = os.path.split(str(source[0]))[0]\n        abspath = os.path.abspath(basedir)\n        if is_LaTeX(source,env,abspath):\n            result = env.subst('$LATEXCOM',0,target,source)+\" ...\"\n        else:\n            result = env.subst(\"$TEXCOM\",0,target,source)+\" ...\"\n    else:\n        result = ''\n    return result",
    "docstring": "A strfunction for TeX and LaTeX that scans the source file to\n    decide the \"flavor\" of the source and then returns the appropriate\n    command string."
  },
  {
    "code": "def print_gateway():\n    print(\"Printing information about the Gateway\")\n    data = api(gateway.get_gateway_info()).raw\n    print(jsonify(data))",
    "docstring": "Print gateway info as JSON"
  },
  {
    "code": "def _read_single(parser, filepath):\n    from os import path\n    global packages\n    if path.isfile(filepath):\n        parser.readfp(open(filepath))",
    "docstring": "Reads a single config file into the parser, silently failing if the file\n    does not exist.\n\n    Args:\n    parser (ConfigParser): parser to read the file into.\n    filepath (str): full path to the config file."
  },
  {
    "code": "def wait_for(self, timeout):\n        def decorator(function):\n            @wrapt.decorator\n            def wrapper(function, _, args, kwargs):\n                @self.run_in_reactor\n                def run():\n                    return function(*args, **kwargs)\n                eventual_result = run()\n                try:\n                    return eventual_result.wait(timeout)\n                except TimeoutError:\n                    eventual_result.cancel()\n                    raise\n            result = wrapper(function)\n            try:\n                result.wrapped_function = function\n            except AttributeError:\n                pass\n            return result\n        return decorator",
    "docstring": "A decorator factory that ensures the wrapped function runs in the\n        reactor thread.\n\n        When the wrapped function is called, its result is returned or its\n        exception raised. Deferreds are handled transparently. Calls will\n        timeout after the given number of seconds (a float), raising a\n        crochet.TimeoutError, and cancelling the Deferred being waited on."
  },
  {
    "code": "def auth_list():\n    auths = {}\n    with salt.utils.files.fopen('/etc/security/auth_attr', 'r') as auth_attr:\n        for auth in auth_attr:\n            auth = salt.utils.stringutils.to_unicode(auth)\n            auth = auth.split(':')\n            if len(auth) != 6:\n                continue\n            if auth[0][-1:] == '.':\n                auth[0] = '{0}*'.format(auth[0])\n            auths[auth[0]] = auth[3]\n    return auths",
    "docstring": "List all available authorization\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rbac.auth_list"
  },
  {
    "code": "def __assert_less(expected, returned):\n        result = \"Pass\"\n        try:\n            assert (expected < returned), \"{0} not False\".format(returned)\n        except AssertionError as err:\n            result = \"Fail: \" + six.text_type(err)\n        return result",
    "docstring": "Test if a value is less than the returned value"
  },
  {
    "code": "def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts):\n    infoblox = _get_infoblox(**api_opts)\n    host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields)\n    return host",
    "docstring": "Get host information\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt-call infoblox.get_host hostname.domain.ca\n        salt-call infoblox.get_host ipv4addr=123.123.122.12\n        salt-call infoblox.get_host mac=00:50:56:84:6e:ae"
  },
  {
    "code": "def iter_finds(regex_obj, s):\n    if isinstance(regex_obj, str):\n        for m in re.finditer(regex_obj, s):\n            yield m.group()\n    else:\n        for m in regex_obj.finditer(s):\n            yield m.group()",
    "docstring": "Generate all matches found within a string for a regex and yield each match as a string"
  },
  {
    "code": "def _show(self):\n        if not self._icon:\n            self._icon = self._create_statusicon()\n        widget = self._icon\n        widget.set_visible(True)\n        self._conn_left = widget.connect(\"activate\", self._activate)\n        self._conn_right = widget.connect(\"popup-menu\", self._popup_menu)",
    "docstring": "Show the tray icon."
  },
  {
    "code": "def log_level(level):\n    from six import string_types\n    if isinstance(level, int):\n        return level\n    if isinstance(level, string_types):\n        try: return int(level)\n        except ValueError: pass\n        try: return getattr(logging, level.upper())\n        except AttributeError: pass\n    raise ValueError(\"cannot convert '{}' into a log level\".format(level))",
    "docstring": "Attempt to convert the given argument into a log level.\n\n    Log levels are represented as integers, where higher values are more \n    severe.  If the given level is already an integer, it is simply returned.  \n    If the given level is a string that can be converted into an integer, it is \n    converted and that value is returned.  Finally, if the given level is a \n    string naming one of the levels defined in the logging module, return that \n    level.  If none of those conditions are met, raise a ValueError."
  },
  {
    "code": "def post(self, endpoint: str, **kwargs) -> dict:\n        return self._request('POST', endpoint, **kwargs)",
    "docstring": "HTTP POST operation to API endpoint."
  },
  {
    "code": "def get_all_access_keys(user_name, marker=None, max_items=None,\n                        region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    try:\n        return conn.get_all_access_keys(user_name, marker, max_items)\n    except boto.exception.BotoServerError as e:\n        log.debug(e)\n        log.error('Failed to get access keys for IAM user %s.', user_name)\n        return six.text_type(e)",
    "docstring": "Get all access keys from a user.\n\n    .. versionadded:: 2015.8.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_iam.get_all_access_keys myuser"
  },
  {
    "code": "def multi_replace(str_, search_list, repl_list):\n    r\n    if isinstance(repl_list, six.string_types):\n        repl_list_ = [repl_list] * len(search_list)\n    else:\n        repl_list_ = repl_list\n    newstr = str_\n    assert len(search_list) == len(repl_list_), 'bad lens'\n    for search, repl in zip(search_list, repl_list_):\n        newstr = newstr.replace(search, repl)\n    return newstr",
    "docstring": "r\"\"\"\n    Performs multiple replace functions foreach item in search_list and\n    repl_list.\n\n    Args:\n        str_ (str): string to search\n        search_list (list): list of search strings\n        repl_list (list or str): one or multiple replace strings\n\n    Returns:\n        str: str_\n\n    CommandLine:\n        python -m utool.util_str --exec-multi_replace\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_str import *  # NOQA\n        >>> str_ = 'foo. bar: baz; spam-eggs --- eggs+spam'\n        >>> search_list = ['.', ':', '---']\n        >>> repl_list = '@'\n        >>> str_ = multi_replace(str_, search_list, repl_list)\n        >>> result = ('str_ = %s' % (str(str_),))\n        >>> print(result)\n        str_ = foo@ bar@ baz; spam-eggs @ eggs+spam"
  },
  {
    "code": "def decode_for_output(output, target_stream=None, translation_map=None):\n    if not isinstance(output, six.string_types):\n        return output\n    encoding = None\n    if target_stream is not None:\n        encoding = getattr(target_stream, \"encoding\", None)\n    encoding = get_output_encoding(encoding)\n    try:\n        output = _encode(output, encoding=encoding, translation_map=translation_map)\n    except (UnicodeDecodeError, UnicodeEncodeError):\n        output = to_native_string(output)\n        output = _encode(\n            output, encoding=encoding, errors=\"replace\", translation_map=translation_map\n        )\n    return to_text(output, encoding=encoding, errors=\"replace\")",
    "docstring": "Given a string, decode it for output to a terminal\n\n    :param str output: A string to print to a terminal\n    :param target_stream: A stream to write to, we will encode to target this stream if possible.\n    :param dict translation_map: A mapping of unicode character ordinals to replacement strings.\n    :return: A re-encoded string using the preferred encoding\n    :rtype: str"
  },
  {
    "code": "def working2analysis(self,r):\n        \"Transform working space inputs to the analysis color space.\"\n        a = self.colorspace.convert(self.working_space, self.analysis_space, r)\n        return self.swap_polar_HSVorder[self.analysis_space](a)",
    "docstring": "Transform working space inputs to the analysis color space."
  },
  {
    "code": "def setBlockValue(self, block, value):\n        if self._bit_count == 0:\n            raise Exception( \"The margin '\" + self._name +\n                             \"' did not allocate any bits for the values\")\n        if value < 0:\n            raise Exception( \"The margin '\" + self._name +\n                             \"' must be a positive integer\"  )\n        if value >= 2 ** self._bit_count:\n            raise Exception( \"The margin '\" + self._name +\n                             \"' value exceeds the allocated bit range\" )\n        newMarginValue = value << self._bitRange[ 0 ]\n        currentUserState = block.userState()\n        if currentUserState in [ 0, -1 ]:\n            block.setUserState(newMarginValue)\n        else:\n            marginMask = 2 ** self._bit_count - 1\n            otherMarginsValue = currentUserState & ~marginMask\n            block.setUserState(newMarginValue | otherMarginsValue)",
    "docstring": "Sets the required value to the block without damaging the other bits"
  },
  {
    "code": "def find_a_system_python(line):\n    from .vendor.pythonfinder import Finder\n    finder = Finder(system=False, global_search=True)\n    if not line:\n        return next(iter(finder.find_all_python_versions()), None)\n    if (line.startswith(\"py \") or line.startswith(\"py.exe \")) and os.name == \"nt\":\n        line = line.split(\" \", 1)[1].lstrip(\"-\")\n    python_entry = find_python(finder, line)\n    return python_entry",
    "docstring": "Find a Python installation from a given line.\n\n    This tries to parse the line in various of ways:\n\n    * Looks like an absolute path? Use it directly.\n    * Looks like a py.exe call? Use py.exe to get the executable.\n    * Starts with \"py\" something? Looks like a python command. Try to find it\n      in PATH, and use it directly.\n    * Search for \"python\" and \"pythonX.Y\" executables in PATH to find a match.\n    * Nothing fits, return None."
  },
  {
    "code": "def update_time_login(u_name):\n        entry = TabMember.update(\n            time_login=tools.timestamp()\n        ).where(\n            TabMember.user_name == u_name\n        )\n        entry.execute()",
    "docstring": "Update the login time for user."
  },
  {
    "code": "def default_filename_decoder():\n    factory = default_filename_grammar_factory()\n    grammar_old = factory.get_rule('filename_old')\n    grammar_new = factory.get_rule('filename_new')\n    return FileNameDecoder(grammar_old, grammar_new)",
    "docstring": "Creates a decoder which parses CWR filenames following the old or the new\n    convention.\n\n    :return: a CWR filename decoder for the old and the new conventions"
  },
  {
    "code": "def ImportDNS(self, config, token=None):\n        if not token:\n            raise Exception(\"You must have the dns token set first.\")\n        self.dns = CotendoDNS([token, config])\n        return True",
    "docstring": "Import a dns configuration file into the helper\n\n        Note: This requires that you have the latest token.\n        To get the latest token, run the GrabDNS command first."
  },
  {
    "code": "def _get_sortgo(self):\n        if 'sortgo' in self.datobj.kws:\n            return self.datobj.kws['sortgo']\n        return self.datobj.grprdflt.gosubdag.prt_attr['sort'] + \"\\n\"",
    "docstring": "Get function for sorting GO terms in a list of namedtuples."
  },
  {
    "code": "def elimination_order_width(G, order):\n    adj = {v: set(G[v]) for v in G}\n    treewidth = 0\n    for v in order:\n        try:\n            dv = len(adj[v])\n        except KeyError:\n            raise ValueError('{} is in order but not in G'.format(v))\n        if dv > treewidth:\n            treewidth = dv\n        _elim_adj(adj, v)\n    if adj:\n        raise ValueError('not all nodes in G were in order')\n    return treewidth",
    "docstring": "Calculates the width of the tree decomposition induced by a\n    variable elimination order.\n\n    Parameters\n    ----------\n    G : NetworkX graph\n        The graph on which to compute the width of the tree decomposition.\n\n    order : list\n        The elimination order. Must be a list of all of the variables\n        in G.\n\n    Returns\n    -------\n    treewidth : int\n        The width of the tree decomposition induced by  order.\n\n    Examples\n    --------\n    This example computes the width of the tree decomposition for the :math:`K_4`\n    complete graph induced by an elimination order found through the min-width\n    heuristic.\n\n    >>> import dwave_networkx as dnx\n    >>> import networkx as nx\n    >>> K_4 = nx.complete_graph(4)\n    >>> dnx.min_width_heuristic(K_4)\n    (3, [1, 2, 0, 3])\n    >>> dnx.elimination_order_width(K_4, [1, 2, 0, 3])\n    3"
  },
  {
    "code": "def ms_cutlo(self, viewer, event, data_x, data_y):\n        if not self.cancut:\n            return True\n        x, y = self.get_win_xy(viewer)\n        if event.state == 'move':\n            self._cutlow_xy(viewer, x, y)\n        elif event.state == 'down':\n            self._start_x, self._start_y = x, y\n            self._loval, self._hival = viewer.get_cut_levels()\n        else:\n            viewer.onscreen_message(None)\n        return True",
    "docstring": "An interactive way to set the low cut level."
  },
  {
    "code": "def addAPK(self, filename, data):\n        digest = hashlib.sha256(data).hexdigest()\n        log.debug(\"add APK:%s\" % digest)\n        apk = APK(data, True)\n        self.analyzed_apk[digest] = [apk]\n        self.analyzed_files[filename].append(digest)\n        self.analyzed_digest[digest] = filename\n        dx = Analysis()\n        self.analyzed_vms[digest] = dx\n        for dex in apk.get_all_dex():\n            self.addDEX(filename, dex, dx)\n        log.debug(\"added APK:%s\" % digest)\n        return digest, apk",
    "docstring": "Add an APK file to the Session and run analysis on it.\n\n        :param filename: (file)name of APK file\n        :param data: binary data of the APK file\n        :return: a tuple of SHA256 Checksum and APK Object"
  },
  {
    "code": "def deadline(self):\n        if not self._deadline:\n            self._deadline = self.now + timezone.timedelta(days=1)\n        return self._deadline",
    "docstring": "Return next day as deadline if no deadline provided."
  },
  {
    "code": "def _append_number(self, value, _file):\n        _text = value\n        _labs = ' {text}'.format(text=_text)\n        _file.write(_labs)",
    "docstring": "Call this function to write number contents.\n\n        Keyword arguments:\n            * value - dict, content to be dumped\n            * _file - FileIO, output file"
  },
  {
    "code": "def csw_global_dispatch_by_catalog(request, catalog_slug):\n    catalog = get_object_or_404(Catalog, slug=catalog_slug)\n    if catalog:\n        url = settings.SITE_URL.rstrip('/') + request.path.rstrip('/')\n        return csw_global_dispatch(request, url=url, catalog_id=catalog.id)",
    "docstring": "pycsw wrapper for catalogs"
  },
  {
    "code": "def parse_int_string(int_string: str) -> List[int]:\n    cleaned = \" \".join(int_string.strip().split())\n    cleaned = cleaned.replace(\" - \", \"-\")\n    cleaned = cleaned.replace(\",\", \" \")\n    tokens = cleaned.split(\" \")\n    indices: Set[int] = set()\n    for token in tokens:\n        if \"-\" in token:\n            endpoints = token.split(\"-\")\n            if len(endpoints) != 2:\n                LOG.info(f\"Dropping '{token}' as invalid - weird range.\")\n                continue\n            start = int(endpoints[0])\n            end = int(endpoints[1]) + 1\n            indices = indices.union(indices, set(range(start, end)))\n        else:\n            try:\n                indices.add(int(token))\n            except ValueError:\n                LOG.info(f\"Dropping '{token}' as invalid - not an int.\")\n    return list(indices)",
    "docstring": "Given a string like \"1 23 4-8 32 1\", return a unique list of those integers in the string and\n    the integers in the ranges in the string.\n    Non-numbers ignored. Not necessarily sorted"
  },
  {
    "code": "def _validate_example(rh, method, example_type):\n    example = getattr(method, example_type + \"_example\")\n    schema = getattr(method, example_type + \"_schema\")\n    if example is None:\n        return None\n    try:\n        validate(example, schema)\n    except ValidationError as e:\n        raise ValidationError(\n            \"{}_example for {}.{} could not be validated.\\n{}\".format(\n                example_type, rh.__name__, method.__name__, str(e)\n            )\n        )\n    return json.dumps(example, indent=4, sort_keys=True)",
    "docstring": "Validates example against schema\n\n    :returns: Formatted example if example exists and validates, otherwise None\n    :raises ValidationError: If example does not validate against the schema"
  },
  {
    "code": "def register(ctx, model, type, trait, manufacturer, product_name, description,\n             device, nickname, client_type):\n    ctx.obj['SESSION'] = google.auth.transport.requests.AuthorizedSession(\n        ctx.obj['CREDENTIALS']\n    )\n    ctx.invoke(register_model,\n               model=model, type=type, trait=trait,\n               manufacturer=manufacturer,\n               product_name=product_name,\n               description=description)\n    ctx.invoke(register_device, device=device, model=model,\n               nickname=nickname, client_type=client_type)",
    "docstring": "Registers a device model and instance.\n\n    Device model fields can only contain letters, numbers, and the following\n    symbols: period (.), hyphen (-), underscore (_), space ( ) and plus (+).\n    The first character of a field must be a letter or number.\n\n    Device instance fields must start with a letter or number. The device ID\n    can only contain letters, numbers, and the following symbols: period (.),\n    hyphen (-), underscore (_), and plus (+). The device nickname can only\n    contain numbers, letters, and the space ( ) symbol."
  },
  {
    "code": "def ConvertToTemplate(self,visibility,description=None,password=None):\n\t\tif visibility not in ('private','shared'):  raise(clc.CLCException(\"Invalid visibility - must be private or shared\"))\n\t\tif not password: password = self.Credentials()['password']\n\t\tif not description:  description = self.description\n\t\treturn(clc.v2.Requests(clc.v2.API.Call('POST','servers/%s/%s/convertToTemplate' % (self.alias,self.id),\n\t\t\t\t\t\t\t\t\t\t\t   json.dumps({\"description\": description, \"visibility\": visibility, \"password\": password}),\n\t\t\t\t\t\t\t\t\t\t\t   session=self.session),\n\t\t\t\t\t\t\t   alias=self.alias,\n\t\t\t\t\t\t\t   session=self.session))",
    "docstring": "Converts existing server to a template.\n\n\t\tvisibility is one of private or shared.\n\n\t\t>>> d = clc.v2.Datacenter()\n\t\t>>> clc.v2.Server(alias='BTDI',id='WA1BTDIAPI207').ConvertToTemplate(\"private\",\"my template\")\n\t\t0"
  },
  {
    "code": "def cli(patterns, times, json, csv, rst, md, ref, unit, precision, debug):\n    if ref:\n        ref = JSON.load(ref)\n    filenames = []\n    reporters = [CliReporter(ref=ref, debug=debug, unit=unit, precision=precision)]\n    kwargs = {}\n    for pattern in patterns or ['**/*.bench.py']:\n        filenames.extend(resolve_pattern(pattern))\n    if json:\n        reporters.append(JsonReporter(json, precision=precision))\n    if csv:\n        reporters.append(CsvReporter(csv, precision=precision))\n    if rst:\n        reporters.append(RstReporter(rst, precision=precision))\n    if md:\n        reporters.append(MarkdownReporter(md, precision=precision))\n    if times:\n        kwargs['times'] = times\n    runner = BenchmarkRunner(*filenames, reporters=reporters, debug=debug)\n    runner.run(**kwargs)",
    "docstring": "Execute minibench benchmarks"
  },
  {
    "code": "def poll(self):\n        self._returncode = self.process.poll()\n        if self._returncode is not None:\n            self.set_status(self.S_DONE, \"status set to Done\")\n        return self._returncode",
    "docstring": "Check if child process has terminated. Set and return returncode attribute."
  },
  {
    "code": "def get_context_json(self, context):\n        answer = {}\n        answer['meta'] = self.__jcontext_metadata(context)\n        answer['filter'] = self.__jcontext_filter(context)\n        answer['table'] = {}\n        answer['table']['head'] = self.__jcontext_tablehead(context)\n        answer['table']['body'] = None\n        answer['table']['header'] = None\n        answer['table']['summary'] = None\n        return answer",
    "docstring": "Return a base answer for a json answer"
  },
  {
    "code": "def _get_event_id(object_type: str) -> str:\n    key = _keys.event_counter(object_type)\n    DB.watch(key, pipeline=True)\n    count = DB.get_value(key)\n    DB.increment(key)\n    DB.execute()\n    if count is None:\n        count = 0\n    return '{}_event_{:08d}'.format(object_type, int(count))",
    "docstring": "Return an event key for the event on the object type.\n\n    This must be a unique event id for the object.\n\n    Args:\n        object_type (str): Type of object\n\n    Returns:\n        str, event id"
  },
  {
    "code": "def append(self, element):\n        assert element.locus == self.locus, (\n            \"Element locus (%s) != Pileup locus (%s)\"\n            % (element.locus, self.locus))\n        self.elements[element] = None",
    "docstring": "Append a PileupElement to this Pileup. If an identical PileupElement is\n        already part of this Pileup, do nothing."
  },
  {
    "code": "def getWorkingCollisionBoundsInfo(self):\n        fn = self.function_table.getWorkingCollisionBoundsInfo\n        pQuadsBuffer = HmdQuad_t()\n        punQuadsCount = c_uint32()\n        result = fn(byref(pQuadsBuffer), byref(punQuadsCount))\n        return result, pQuadsBuffer, punQuadsCount.value",
    "docstring": "Returns the number of Quads if the buffer points to null. Otherwise it returns Quads \n        into the buffer up to the max specified from the working copy."
  },
  {
    "code": "def get(self, request, *_args, **_kwargs):\n        access_token = self.access_token\n        scope_string = request.GET.get('scope')\n        scope_request = scope_string.split() if scope_string else None\n        claims_string = request.GET.get('claims')\n        claims_request = json.loads(claims_string) if claims_string else None\n        if not provider.scope.check(constants.OPEN_ID_SCOPE, access_token.scope):\n            return self._bad_request('Missing openid scope.')\n        try:\n            claims = self.userinfo_claims(access_token, scope_request, claims_request)\n        except ValueError, exception:\n            return self._bad_request(str(exception))\n        response = JsonResponse(claims)\n        return response",
    "docstring": "Respond to a UserInfo request.\n\n        Two optional query parameters are accepted, scope and claims.\n        See the references above for more details."
  },
  {
    "code": "def unescape(msg, extra_format_dict={}):\n    new_msg = ''\n    extra_format_dict.update(format_dict)\n    while len(msg):\n        char = msg[0]\n        msg = msg[1:]\n        if char == escape_character:\n            escape_key = msg[0]\n            msg = msg[1:]\n            if escape_key == escape_character:\n                new_msg += escape_character\n            elif escape_key == '{':\n                buf = ''\n                new_char = ''\n                while True:\n                    new_char = msg[0]\n                    msg = msg[1:]\n                    if new_char == '}':\n                        break\n                    else:\n                        buf += new_char\n                new_msg += _get_from_format_dict(extra_format_dict, buf)\n            else:\n                new_msg += _get_from_format_dict(extra_format_dict, escape_key)\n            if escape_key == 'c':\n                fill_last = len(msg) and msg[0] in digits\n                colours, msg = extract_girc_colours(msg, fill_last)\n                new_msg += colours\n        else:\n            new_msg += char\n    return new_msg",
    "docstring": "Takes a girc-escaped message and returns a raw IRC message"
  },
  {
    "code": "def voip(self):\n        if self._voip is None:\n            self._voip = VoipList(\n                self._version,\n                account_sid=self._solution['account_sid'],\n                country_code=self._solution['country_code'],\n            )\n        return self._voip",
    "docstring": "Access the voip\n\n        :returns: twilio.rest.api.v2010.account.available_phone_number.voip.VoipList\n        :rtype: twilio.rest.api.v2010.account.available_phone_number.voip.VoipList"
  },
  {
    "code": "def _to_pywintypes(row):\n    def _pywintype(x):\n        if isinstance(x, dt.date):\n            return dt.datetime(x.year, x.month, x.day, tzinfo=dt.timezone.utc)\n        elif isinstance(x, (dt.datetime, pa.Timestamp)):\n            if x.tzinfo is None:\n                return x.replace(tzinfo=dt.timezone.utc)\n        elif isinstance(x, str):\n            if re.match(\"^\\d{4}-\\d{2}-\\d{2}$\", x):\n                return \"'\" + x\n            return x\n        elif isinstance(x, np.integer):\n            return int(x)\n        elif isinstance(x, np.floating):\n            return float(x)\n        elif x is not None and not isinstance(x, (str, int, float, bool)):\n            return str(x)\n        return x\n    return [_pywintype(x) for x in row]",
    "docstring": "convert values in a row to types accepted by excel"
  },
  {
    "code": "def disconnect_all(self):\n        rhs = 'b:' + self.definition['node_class'].__label__\n        rel = _rel_helper(lhs='a', rhs=rhs, ident='r', **self.definition)\n        q = 'MATCH (a) WHERE id(a)={self} MATCH ' + rel + ' DELETE r'\n        self.source.cypher(q)",
    "docstring": "Disconnect all nodes\n\n        :return:"
  },
  {
    "code": "def start(self):\n        with self._lock_send_remaining_time:\n            if self._send_remaining_time <= 0.0:\n                local_send_interval = self._send_interval\n                if self._send_interval < 0.1:\n                    local_send_interval = 0.1\n                self._send_remaining_time = self._send_time\n                if self._send_remaining_time < local_send_interval:\n                    self._send_remaining_time = local_send_interval\n                thread = Thread(target=self._run)\n                thread.daemon = True\n                thread.start()",
    "docstring": "Starts a new sender thread if none is not already there"
  },
  {
    "code": "def run(self, i, o):\n        self.input = i\n        self.output = PoetryStyle(i, o)\n        for logger in self._loggers:\n            self.register_logger(logging.getLogger(logger))\n        return super(BaseCommand, self).run(i, o)",
    "docstring": "Initialize command."
  },
  {
    "code": "def _get_branch_opts(branch, local_branch, all_local_branches,\n                     desired_upstream, git_ver=None):\n    if branch is not None and branch not in all_local_branches:\n        return None\n    if git_ver is None:\n        git_ver = _LooseVersion(__salt__['git.version'](versioninfo=False))\n    ret = []\n    if git_ver >= _LooseVersion('1.8.0'):\n        ret.extend(['--set-upstream-to', desired_upstream])\n    else:\n        ret.append('--set-upstream')\n        ret.append(local_branch if branch is None else branch)\n        ret.append(desired_upstream)\n    return ret",
    "docstring": "DRY helper to build list of opts for git.branch, for the purposes of\n    setting upstream tracking branch"
  },
  {
    "code": "def _get_format_timedelta64(values, nat_rep='NaT', box=False):\n    values_int = values.astype(np.int64)\n    consider_values = values_int != iNaT\n    one_day_nanos = (86400 * 1e9)\n    even_days = np.logical_and(consider_values,\n                               values_int % one_day_nanos != 0).sum() == 0\n    all_sub_day = np.logical_and(\n        consider_values, np.abs(values_int) >= one_day_nanos).sum() == 0\n    if even_days:\n        format = None\n    elif all_sub_day:\n        format = 'sub_day'\n    else:\n        format = 'long'\n    def _formatter(x):\n        if x is None or (is_scalar(x) and isna(x)):\n            return nat_rep\n        if not isinstance(x, Timedelta):\n            x = Timedelta(x)\n        result = x._repr_base(format=format)\n        if box:\n            result = \"'{res}'\".format(res=result)\n        return result\n    return _formatter",
    "docstring": "Return a formatter function for a range of timedeltas.\n    These will all have the same format argument\n\n    If box, then show the return in quotes"
  },
  {
    "code": "def send(self, **kwargs):\n        payload = self.api_payload()\n        payload.update(**kwargs)\n        return self.api_method()(**payload)",
    "docstring": "Combines api_payload and api_method to submit the current object to the API"
  },
  {
    "code": "def _netsh_file(content):\n    with tempfile.NamedTemporaryFile(mode='w',\n                                     prefix='salt-',\n                                     suffix='.netsh',\n                                     delete=False) as fp:\n        fp.write(content)\n    try:\n        log.debug('%s:\\n%s', fp.name, content)\n        return salt.modules.cmdmod.run('netsh -f {0}'.format(fp.name), python_shell=True)\n    finally:\n        os.remove(fp.name)",
    "docstring": "helper function to get the results of ``netsh -f content.txt``\n\n    Running ``netsh`` will drop you into a ``netsh`` prompt where you can issue\n    ``netsh`` commands. You can put a series of commands in an external file and\n    run them as if from a ``netsh`` prompt using the ``-f`` switch. That's what\n    this function does.\n\n    Args:\n\n        content (str):\n            The contents of the file that will be run by the ``netsh -f``\n            command\n\n    Returns:\n        str: The text returned by the netsh command"
  },
  {
    "code": "def get_locale ():\n    try:\n        loc, encoding = locale.getdefaultlocale()\n    except ValueError:\n        loc, encoding = None, None\n    if loc is None:\n        loc = \"C\"\n    else:\n        loc = norm_locale(loc)\n    if encoding is None:\n        encoding = \"ascii\"\n    return (loc, encoding)",
    "docstring": "Search the default platform locale and norm it.\n    @returns (locale, encoding)\n    @rtype (string, string)"
  },
  {
    "code": "def StoreStat(self, responses):\n    index = responses.request_data[\"index\"]\n    if not responses.success:\n      self.Log(\"Failed to stat file: %s\", responses.status)\n      self._FileFetchFailed(index, responses.request_data[\"request_name\"])\n      return\n    tracker = self.state.pending_hashes[index]\n    tracker[\"stat_entry\"] = responses.First()",
    "docstring": "Stores stat entry in the flow's state."
  },
  {
    "code": "def getInstalled():\n    installed = _find_installed()\n    return [os.path.basename(p.pathname)[3:] for p in installed]",
    "docstring": "Returns a list of strings representing the installed wxPython\n    versions that are found on the system."
  },
  {
    "code": "def _get_short_description(self):\n        if self.description is None:\n            return None\n        lines = [x for x in self.description.split('\\n')]\n        if len(lines) == 1:\n            return lines[0]\n        elif len(lines) >= 3 and lines[1] == '':\n            return lines[0]\n        return None",
    "docstring": "Return the first line of a multiline description\n\n        Returns:\n            string: The short description, otherwise None"
  },
  {
    "code": "def _to_ctfile_property_block(self):\n        ctab_properties_data = defaultdict(list)\n        for atom in self.atoms:\n            for ctab_property_key, ctab_property_value in atom._ctab_property_data.items():\n                ctab_properties_data[ctab_property_key].append(OrderedDict(\n                    zip(self.ctab_conf[self.version][ctab_property_key]['values'],\n                        [atom.atom_number, ctab_property_value])))\n        ctab_property_lines = []\n        for ctab_property_key, ctab_property_value in ctab_properties_data.items():\n            for entry in ctab_property_value:\n                ctab_property_line = '{}  {}{}'.format(self.ctab_conf[self.version][ctab_property_key]['fmt'],\n                                                       1, ''.join([str(value).rjust(4) for value in entry.values()]))\n                ctab_property_lines.append(ctab_property_line)\n        if ctab_property_lines:\n            return '{}\\n'.format('\\n'.join(ctab_property_lines))\n        return ''",
    "docstring": "Create ctab properties block in `CTfile` format from atom-specific properties.\n\n        :return: Ctab property block.\n        :rtype: :py:class:`str`"
  },
  {
    "code": "def dumpindented(self, pn, indent=0):\r\n        page = self.readpage(pn)\r\n        print(\"  \" * indent, page)\r\n        if page.isindex():\r\n            print(\"  \" * indent, end=\"\")\r\n            self.dumpindented(page.preceeding, indent + 1)\r\n            for p in range(len(page.index)):\r\n                print(\"  \" * indent, end=\"\")\r\n                self.dumpindented(page.getpage(p), indent + 1)",
    "docstring": "Dump all nodes of the current page with keys indented, showing how the `indent`\r\n        feature works"
  },
  {
    "code": "def _get_or_add_definition(self):\n        if self._has_definition:\n            return self._definition\n        prior_headerfooter = self._prior_headerfooter\n        if prior_headerfooter:\n            return prior_headerfooter._get_or_add_definition()\n        return self._add_definition()",
    "docstring": "Return HeaderPart or FooterPart object for this section.\n\n        If this header/footer inherits its content, the part for the prior header/footer\n        is returned; this process continue recursively until a definition is found. If\n        the definition cannot be inherited (because the header/footer belongs to the\n        first section), a new definition is added for that first section and then\n        returned."
  },
  {
    "code": "def set_position(x, y, stream=STD_OUTPUT_HANDLE):\n    stream = kernel32.GetStdHandle(stream)\n    value = x + (y << 16)\n    kernel32.SetConsoleCursorPosition(stream, c_long(value))",
    "docstring": "Sets current position of the cursor."
  },
  {
    "code": "def _get_reflectance(self, projectables, optional_datasets):\n        _nir, _tb11 = projectables\n        LOG.info('Getting reflective part of %s', _nir.attrs['name'])\n        sun_zenith = None\n        tb13_4 = None\n        for dataset in optional_datasets:\n            wavelengths = dataset.attrs.get('wavelength', [100., 0, 0])\n            if (dataset.attrs.get('units') == 'K' and\n                    wavelengths[0] <= 13.4 <= wavelengths[2]):\n                tb13_4 = dataset\n            elif (\"standard_name\" in dataset.attrs and\n                  dataset.attrs[\"standard_name\"] == \"solar_zenith_angle\"):\n                sun_zenith = dataset\n        if sun_zenith is None:\n            if sun_zenith_angle is None:\n                raise ImportError(\"No module named pyorbital.astronomy\")\n            lons, lats = _nir.attrs[\"area\"].get_lonlats_dask(CHUNK_SIZE)\n            sun_zenith = sun_zenith_angle(_nir.attrs['start_time'], lons, lats)\n        return self._refl3x.reflectance_from_tbs(sun_zenith, _nir, _tb11, tb_ir_co2=tb13_4)",
    "docstring": "Calculate 3.x reflectance with pyspectral."
  },
  {
    "code": "def place_order(self, package_keyname, location, item_keynames, complex_type=None,\n                    hourly=True, preset_keyname=None, extras=None, quantity=1):\n        order = self.generate_order(package_keyname, location, item_keynames,\n                                    complex_type=complex_type, hourly=hourly,\n                                    preset_keyname=preset_keyname,\n                                    extras=extras, quantity=quantity)\n        return self.order_svc.placeOrder(order)",
    "docstring": "Places an order with the given package and prices.\n\n        This function takes in parameters needed for an order and places the order.\n\n        :param str package_keyname: The keyname for the package being ordered\n        :param str location: The datacenter location string for ordering (Ex: DALLAS13)\n        :param list item_keynames: The list of item keyname strings to order. To see list of\n                                   possible keynames for a package, use list_items()\n                                   (or `slcli order item-list`)\n        :param str complex_type: The complex type to send with the order. Typically begins\n                                 with `SoftLayer_Container_Product_Order_`.\n        :param bool hourly: If true, uses hourly billing, otherwise uses monthly billing\n        :param string preset_keyname: If needed, specifies a preset to use for that package.\n                                      To see a list of possible keynames for a package, use\n                                      list_preset() (or `slcli order preset-list`)\n        :param dict extras: The extra data for the order in dictionary format.\n                            Example: A VSI order requires hostname and domain to be set, so\n                            extras will look like the following:\n                            {'virtualGuests': [{'hostname': 'test', domain': 'softlayer.com'}]}\n        :param int quantity: The number of resources to order"
  },
  {
    "code": "def _double_as_bytes(dval):\n    \"Use struct.unpack to decode a double precision float into eight bytes\"\n    tmp = list(struct.unpack('8B',struct.pack('d', dval)))\n    if not _big_endian:\n        tmp.reverse()\n    return tmp",
    "docstring": "Use struct.unpack to decode a double precision float into eight bytes"
  },
  {
    "code": "def get_value(self, subsystem, option):\n        assert subsystem in self, 'Subsystem {} is missing'.format(subsystem)\n        return util.read_file(self.per_subsystem[subsystem], subsystem + '.' + option)",
    "docstring": "Read the given value from the given subsystem.\n        Do not include the subsystem name in the option name.\n        Only call this method if the given subsystem is available."
  },
  {
    "code": "def each(self, callback):\n        items = self.items\n        for item in items:\n            if callback(item) is False:\n                break\n        return self",
    "docstring": "Execute a callback over each item.\n\n        .. code::\n\n            collection = Collection([1, 2, 3])\n            collection.each(lambda x: x + 3)\n\n        .. warning::\n\n            It only applies the callback but does not modify the collection's items.\n            Use the `transform() <#backpack.Collection.transform>`_ method to\n            modify the collection.\n\n        :param callback: The callback to execute\n        :type callback: callable\n\n        :rtype: Collection"
  },
  {
    "code": "def dump_ckan(m):\n    doc = MetapackDoc(cache=m.cache)\n    doc.new_section('Groups',        'Title Description Id Image_url'.split())\n    doc.new_section('Organizations', 'Title Description Id Image_url'.split())\n    c = RemoteCKAN(m.ckan_url, apikey=m.api_key)\n    for g in c.action.group_list(all_fields=True):\n        print(g.keys())\n    for o in c.action.organization_list(all_fields=True):\n        print(g.keys())",
    "docstring": "Create a groups and organization file"
  },
  {
    "code": "def update(self):\n        from ambry.orm.exc import NotFoundError\n        from requests.exceptions import ConnectionError, HTTPError\n        from boto.exception import S3ResponseError\n        d = {}\n        try:\n            for k, v in self.list(full=True):\n                if not v:\n                    continue\n                d[v['vid']] = {\n                    'vid': v['vid'],\n                    'vname': v.get('vname'),\n                    'id': v.get('id'),\n                    'name': v.get('name')\n                }\n            self.data['list'] = d\n        except (NotFoundError, ConnectionError, S3ResponseError, HTTPError) as e:\n            raise RemoteAccessError(\"Failed to update {}: {}\".format(self.short_name, e))",
    "docstring": "Cache the list into the data section of the record"
  },
  {
    "code": "def strengths_und_sign(W):\n    W = W.copy()\n    n = len(W)\n    np.fill_diagonal(W, 0)\n    Spos = np.sum(W * (W > 0), axis=0)\n    Sneg = np.sum(W * (W < 0), axis=0)\n    vpos = np.sum(W[W > 0])\n    vneg = np.sum(W[W < 0])\n    return Spos, Sneg, vpos, vneg",
    "docstring": "Node strength is the sum of weights of links connected to the node.\n\n    Parameters\n    ----------\n    W : NxN np.ndarray\n        undirected connection matrix with positive and negative weights\n\n    Returns\n    -------\n    Spos : Nx1 np.ndarray\n        nodal strength of positive weights\n    Sneg : Nx1 np.ndarray\n        nodal strength of positive weights\n    vpos : float\n        total positive weight\n    vneg : float\n        total negative weight"
  },
  {
    "code": "def inline_inputs(self):\n        self.text = texutils.inline(self.text,\n                                    os.path.dirname(self._filepath))\n        self._children = {}",
    "docstring": "Inline all input latex files references by this document. The\n        inlining is accomplished recursively. The document is modified\n        in place."
  },
  {
    "code": "def del_option(self, section, option):\n        if self.config.has_section(section):\n            if self.config.has_option(section, option):\n                self.config.remove_option(section, option)\n                return (True, self.config.options(section))\n            return (False, 'Option: ' + option + ' does not exist')\n        return (False, 'Section: ' + section + ' does not exist')",
    "docstring": "Deletes an option if the section and option exist"
  },
  {
    "code": "def train_df(self, df):\n        aesthetics = sorted(set(self.aesthetics) & set(df.columns))\n        for ae in aesthetics:\n            self.train(df[ae])",
    "docstring": "Train scale from a dataframe"
  },
  {
    "code": "def _get_frame_result_type(result, objs):\n    if (result.blocks and (\n            any(isinstance(obj, ABCSparseDataFrame) for obj in objs))):\n        from pandas.core.sparse.api import SparseDataFrame\n        return SparseDataFrame\n    else:\n        return next(obj for obj in objs if not isinstance(obj,\n                                                          ABCSparseDataFrame))",
    "docstring": "return appropriate class of DataFrame-like concat\n    if all blocks are sparse, return SparseDataFrame\n    otherwise, return 1st obj"
  },
  {
    "code": "def get(self, key):\n        uri = 'updates/job/{}'.format(key)\n        return self.make_request(method='GET', uri=uri)",
    "docstring": "Return the status from a job.\n\n        :param key: id of job\n        :type document: dict or list\n        :return: message with location of job\n        :rtype: dict\n        :raises Unauthorized: if API returns status 401\n        :raises Forbidden: if API returns status 403\n        :raises NotFound: if API returns status 404\n        :raises ApiError: if API returns other status"
  },
  {
    "code": "def progress_updater(size, total):\n    current_task.update_state(\n        state=state('PROGRESS'),\n        meta=dict(size=size, total=total)\n    )",
    "docstring": "Progress reporter for checksum verification."
  },
  {
    "code": "def list_plugins(self):\n        vals = self.plugins.items()\n        return {x: y for x, y in vals}",
    "docstring": "List all of the plugins that have been registerd for the iotile program on this computer"
  },
  {
    "code": "def calc_paired_insert_stats_save(in_bam, stat_file, nsample=1000000):\n    if utils.file_exists(stat_file):\n        with open(stat_file) as in_handle:\n            return yaml.safe_load(in_handle)\n    else:\n        stats = calc_paired_insert_stats(in_bam, nsample)\n        with open(stat_file, \"w\") as out_handle:\n            yaml.safe_dump(stats, out_handle, default_flow_style=False, allow_unicode=False)\n        return stats",
    "docstring": "Calculate paired stats, saving to a file for re-runs."
  },
  {
    "code": "def indices_within_segments(times, segment_files, ifo=None, segment_name=None):\n    veto_segs = segmentlist([])\n    indices = numpy.array([], dtype=numpy.uint32)\n    for veto_file in segment_files:\n        veto_segs += select_segments_by_definer(veto_file, segment_name, ifo)\n    veto_segs.coalesce()\n    start, end = segments_to_start_end(veto_segs)\n    if len(start) > 0:\n        idx = indices_within_times(times, start, end)\n        indices = numpy.union1d(indices, idx)\n    return indices, veto_segs.coalesce()",
    "docstring": "Return the list of indices that should be vetoed by the segments in the\n    list of veto_files.\n\n    Parameters\n    ----------\n    times: numpy.ndarray of integer type\n        Array of gps start times\n    segment_files: string or list of strings\n        A string or list of strings that contain the path to xml files that\n        contain a segment table\n    ifo: string, optional\n        The ifo to retrieve segments for from the segment files\n    segment_name: str, optional\n        name of segment\n    Returns\n    -------\n    indices: numpy.ndarray\n        The array of index values within the segments\n    segmentlist:\n        The segment list corresponding to the selected time."
  },
  {
    "code": "def get_form(self, request, obj=None, **kwargs):\n        defaults = {}\n        if obj is None:\n            defaults['form'] = self.add_form\n        defaults.update(kwargs)\n        return super(SettingsAdmin, self).get_form(request, obj, **defaults)",
    "docstring": "Use special form during user creation"
  },
  {
    "code": "def matrix_is_equivalent(X, Y):\n    return X is Y or (isinstance(X, Y.__class__) and X.shape == Y.shape and\n                      np.sum((X != Y).sum()) == 0)",
    "docstring": "Checks matrix equivalence with numpy, scipy and pandas"
  },
  {
    "code": "def update_firmware(self, firmware_information, force=False):\n        firmware_uri = \"{}/firmware\".format(self.data[\"uri\"])\n        result = self._helper.update(firmware_information, firmware_uri, force=force)\n        self.refresh()\n        return result",
    "docstring": "Installs firmware to the member interconnects of a SAS Logical Interconnect.\n\n        Args:\n            firmware_information: Options to install firmware to a SAS Logical Interconnect.\n            force: If sets to true, the operation completes despite any problems with the network connectivy\n              or the erros on the resource itself.\n        Returns:\n            dict: SAS Logical Interconnect Firmware."
  },
  {
    "code": "def casperjs_command_kwargs():\n    kwargs = {\n        'stdout': subprocess.PIPE,\n        'stderr': subprocess.PIPE,\n        'universal_newlines': True\n    }\n    phantom_js_cmd = app_settings['PHANTOMJS_CMD']\n    if phantom_js_cmd:\n        path = '{0}:{1}'.format(\n            os.getenv('PATH', ''), os.path.dirname(phantom_js_cmd)\n        )\n        kwargs.update({'env': {'PATH': path}})\n    return kwargs",
    "docstring": "will construct kwargs for cmd"
  },
  {
    "code": "def remap_hotkey(src, dst, suppress=True, trigger_on_release=False):\n    def handler():\n        active_modifiers = sorted(modifier for modifier, state in _listener.modifier_states.items() if state == 'allowed')\n        for modifier in active_modifiers:\n            release(modifier)\n        send(dst)\n        for modifier in reversed(active_modifiers):\n            press(modifier)\n        return False\n    return add_hotkey(src, handler, suppress=suppress, trigger_on_release=trigger_on_release)",
    "docstring": "Whenever the hotkey `src` is pressed, suppress it and send\n    `dst` instead.\n\n    Example:\n\n        remap('alt+w', 'ctrl+up')"
  },
  {
    "code": "def call(self, name, *args, **kwargs):\n        if name in ('getTaskInfo', 'getTaskDescendants'):\n            kwargs['request'] = True\n        if kwargs:\n            kwargs['__starstar'] = True\n            args = args + (kwargs,)\n        payload = {'methodName': name, 'params': args}\n        self.calls.append(payload)",
    "docstring": "Add a new call to the list that we will submit to the server.\n\n        Similar to txkoji.Connection.call(), but this will store the call\n        for later instead of sending it now."
  },
  {
    "code": "def to_representation(self, value):\n        content_type = ContentType.objects.get_for_id(value)\n        return \"_\".join(content_type.natural_key())",
    "docstring": "Convert to natural key."
  },
  {
    "code": "def prettify_xml(xml_root):\n    xml_string = etree.tostring(xml_root, encoding=\"utf-8\", xml_declaration=True, pretty_print=True)\n    return get_unicode_str(xml_string)",
    "docstring": "Returns pretty-printed string representation of element tree."
  },
  {
    "code": "def get_holdings(self, account: SEPAAccount):\n        with self._get_dialog() as dialog:\n            hkwpd = self._find_highest_supported_command(HKWPD5, HKWPD6)\n            responses = self._fetch_with_touchdowns(\n                dialog,\n                lambda touchdown: hkwpd(\n                    account=hkwpd._fields['account'].type.from_sepa_account(account),\n                    touchdown_point=touchdown,\n                ),\n                'HIWPD'\n            )\n        holdings = []\n        for resp in responses:\n            if type(resp.holdings) == bytes:\n                holding_str = resp.holdings.decode()\n            else:\n                holding_str = resp.holdings\n            mt535_lines = str.splitlines(holding_str)\n            del mt535_lines[0]\n            mt535 = MT535_Miniparser()\n            holdings.extend(mt535.parse(mt535_lines))\n        if not holdings:\n            logger.debug('No HIWPD response segment found - maybe account has no holdings?')\n        return holdings",
    "docstring": "Retrieve holdings of an account.\n\n        :param account: SEPAAccount to retrieve holdings for.\n        :return: List of Holding objects"
  },
  {
    "code": "def nextValidComment(self, text, start=0):\n        m = min([self.lineComment(text, start),\n                 self.blockComment(text, start)],\n                key=lambda m: m.start(0) if m else len(text))\n        return m",
    "docstring": "Return the next actual comment."
  },
  {
    "code": "def double_sha256(ba):\n    d1 = hashlib.sha256(ba)\n    d2 = hashlib.sha256()\n    d1.hexdigest()\n    d2.update(d1.digest())\n    return d2.hexdigest()",
    "docstring": "Perform two SHA256 operations on the input.\n\n    Args:\n        ba (bytes): data to hash.\n\n    Returns:\n        str: hash as a double digit hex string."
  },
  {
    "code": "def current_user_was_last_verifier(analysis):\n    verifiers = analysis.getVerificators()\n    return verifiers and verifiers[:-1] == api.get_current_user().getId()",
    "docstring": "Returns whether the current user was the last verifier or not"
  },
  {
    "code": "def item_hist(list_):\n    dict_hist = {}\n    for item in list_:\n        if item not in dict_hist:\n            dict_hist[item] = 0\n        dict_hist[item] += 1\n    return dict_hist",
    "docstring": "counts the number of times each item appears in the dictionary"
  },
  {
    "code": "def create_header(self):\n\t\ttry:\n\t\t\tself.check_valid()\n\t\t\t_header_list = []\n\t\t\tfor k,v in self.inputs.items():\n\t\t\t\tif v is None:\n\t\t\t\t\treturn  {self.__class__.__name__.replace('_','-'):None}\n\t\t\t\telif k == 'value':\n\t\t\t\t\t_header_list.insert(0,str(v))\n\t\t\t\telif isinstance(v,bool):\n\t\t\t\t\tif v is True:\n\t\t\t\t\t\t_header_list.append(k)\n\t\t\t\telse:\n\t\t\t\t\t_header_list.append('%s=%s' % (k,str(v)))\n\t\t\treturn {self.__class__.__name__.replace('_','-'):'; '.join(_header_list)}\n\t\texcept Exception, e:\n\t\t\traise",
    "docstring": "return header dict"
  },
  {
    "code": "def accept(self):\n        socket = Socket(self._llc, None)\n        socket._tco = self.llc.accept(self._tco)\n        return socket",
    "docstring": "Accept a connection. The socket must be bound to an address\n        and listening for connections. The return value is a new\n        socket object usable to send and receive data on the\n        connection."
  },
  {
    "code": "def get_all(self, page=None, per_page=None, include_totals=False):\n        params = {\n            'page': page,\n            'per_page': per_page,\n            'include_totals': str(include_totals).lower()\n        }\n        return self.client.get(self._url(), params=params)",
    "docstring": "Retrieves all resource servers\n\n        Args:\n            page (int, optional): The result's page number (zero based).\n\n            per_page (int, optional): The amount of entries per page.\n\n            include_totals (bool, optional): True if the query summary is\n                to be included in the result, False otherwise.\n\n        See: https://auth0.com/docs/api/management/v2#!/Resource_Servers/get_resource_servers"
  },
  {
    "code": "def get_locale_hints():\n        lang, encoding = locale.getdefaultlocale()\n        if lang and '_' in lang:\n            lang3, _, lang2 = lang.partition('_')\n        else:\n            lang3 = None\n            lang2 = None\n        ll_s = [encoding, lang, lang2, lang3]\n        ll_s_unique = []\n        for ll in ll_s:\n            if ll:\n                ll = ll.lower()\n                if ll not in ll_s_unique:\n                    ll_s_unique.append(ll)\n        return ll_s_unique",
    "docstring": "Get a list of locale hints,\n          guessed according to Python's default locale info."
  },
  {
    "code": "def login(self):\n        response = self.session.get(self.base_url + '/login_sid.lua', timeout=10)\n        xml = ET.fromstring(response.text)\n        if xml.find('SID').text == \"0000000000000000\":\n            challenge = xml.find('Challenge').text\n            url = self.base_url + \"/login_sid.lua\"\n            response = self.session.get(url, params={\n                \"username\": self.username,\n                \"response\": self.calculate_response(challenge, self.password),\n            }, timeout=10)\n            xml = ET.fromstring(response.text)\n            sid = xml.find('SID').text\n            if xml.find('SID').text == \"0000000000000000\":\n                blocktime = int(xml.find('BlockTime').text)\n                exc = Exception(\"Login failed, please wait {} seconds\".format(\n                    blocktime\n                ))\n                exc.blocktime = blocktime\n                raise exc\n            self.sid = sid\n            return sid",
    "docstring": "Try to login and set the internal session id.\n\n        Please note:\n        - Any failed login resets all existing session ids, even of\n          other users.\n        - SIDs expire after some time"
  },
  {
    "code": "def draw_medium(r, R, L, n=1, ax=None):\n    if ax is None:\n        ax = plt.gca()\n    for ru in _unwrap_to_layer(r, L, n):\n        c = plt.Circle(ru, radius=R, alpha=0.2)\n        ax.add_artist(c)",
    "docstring": "Draw circles representing circles in a two-dimensional periodic system.\n    Circles may be tiled up to a number of periods.\n\n    Parameters\n    ----------\n    r: float array, shape (:, 2).\n        Set of points.\n    R: float\n        Circle radius.\n    L: float array, shape (2,)\n        System lengths.\n    n: integer.\n        Period to unwrap up to.\n    ax: matplotlib axes instance or None\n        Axes to draw circles onto. If `None`, use default axes.\n\n    Returns\n    -------\n    None"
  },
  {
    "code": "def get_go_ntsets(self, go_fins):\n        nts = []\n        ntobj = namedtuple('NtGOFiles', 'hdr go_set, go_fin')\n        go_sets = self._init_go_sets(go_fins)\n        hdrs = [os.path.splitext(os.path.basename(f))[0] for f in go_fins]\n        assert len(go_fins) == len(go_sets)\n        assert len(go_fins) == len(hdrs)\n        for hdr, go_set, go_fin in zip(hdrs, go_sets, go_fins):\n            nts.append(ntobj(hdr=hdr, go_set=go_set, go_fin=go_fin))\n        return nts",
    "docstring": "For each file containing GOs, extract GO IDs, store filename and header."
  },
  {
    "code": "def update_attribute_toolbar(self, key=None):\n        if key is None:\n            key = self.actions.cursor\n        post_command_event(self, self.ToolbarUpdateMsg, key=key,\n                           attr=self.code_array.cell_attributes[key])",
    "docstring": "Updates the attribute toolbar\n\n        Parameters\n        ----------\n        key: 3-tuple of Integer, defaults to current cell\n        \\tCell to which attributes the attributes toolbar is updated"
  },
  {
    "code": "def getTaskDescendents(self, task_id, **kwargs):\n        kwargs['request'] = True\n        data = yield self.call('getTaskDescendents', task_id, **kwargs)\n        tasks = []\n        for tdata in data[str(task_id)]:\n            task = Task.fromDict(tdata)\n            task.connection = self\n            tasks.append(task)\n        defer.returnValue(tasks)",
    "docstring": "Load all information about a task's descendents into Task classes.\n\n        Calls \"getTaskDescendents\" XML-RPC (with request=True to get the full\n        information.)\n\n        :param task_id: ``int``, for example 12345, parent task ID\n        :returns: deferred that when fired returns a list of Task (Munch,\n                  dict-like) objects representing Koji tasks."
  },
  {
    "code": "def merge_cameras(self):\n        combined = CaseInsensitiveDict({})\n        for sync in self.sync:\n            combined = merge_dicts(combined, self.sync[sync].cameras)\n        return combined",
    "docstring": "Merge all sync camera dicts into one."
  },
  {
    "code": "def ynticks(self, nticks, index=1):\n        self.layout['yaxis' + str(index)]['nticks'] = nticks\n        return self",
    "docstring": "Set the number of ticks."
  },
  {
    "code": "def generate_subsets(self, sz, overlap=0.8, subsets=2):\n        overlap_sz = int(math.floor(overlap * sz))\n        unique_sz = sz - overlap_sz\n        total_unique_sz = unique_sz * subsets\n        total_sz = overlap_sz + total_unique_sz\n        if total_sz > len(self.names):\n            msg = 'insufficient names for requested size and overlap'\n            raise ValueError(msg)\n        sset = random.sample(self.names, total_sz)\n        sset_overlap, sset_unique = sset[:overlap_sz], sset[overlap_sz:]\n        assert len(sset_unique) == subsets * unique_sz\n        uniques = (sset_unique[p * unique_sz: (p + 1) * unique_sz]\n                   for p in range(subsets))\n        return tuple(sset_overlap + u for u in uniques)",
    "docstring": "Return random subsets with nonempty intersection.\n\n            The random subsets are of specified size. If an element is\n            common to two subsets, then it is common to all subsets.\n            This overlap is controlled by a parameter.\n\n            :param sz: size of subsets to generate\n            :param overlap: size of the intersection, as fraction of the\n                subset length\n            :param subsets: number of subsets to generate\n\n            :raises ValueError: if there aren't sufficiently many names\n                in the list to satisfy the request; more precisely,\n                raises if (1 - subsets) * floor(overlap * sz)\n                              + subsets * sz > len(self.names).\n\n            :return: tuple of subsets"
  },
  {
    "code": "def _find_model(self, constructor, table_name, constraints=None, *, columns=None, order_by=None):\n    data = self.find(table_name, constraints, columns=columns, order_by=order_by)\n    return constructor(data) if data else None",
    "docstring": "Calls DataAccess.find and passes the results to the given constructor."
  },
  {
    "code": "def add(self, *number):\n        return self._format_result(sum(\n            [int(n) for n in number]))",
    "docstring": "Adds all parameters interpreted as integers"
  },
  {
    "code": "def apply(key, value):\n    path = __opts__['conf_file']\n    if os.path.isdir(path):\n        path = os.path.join(path, 'master')\n    data = values()\n    data[key] = value\n    with salt.utils.files.fopen(path, 'w+') as fp_:\n        salt.utils.yaml.safe_dump(data, default_flow_style=False)",
    "docstring": "Set a single key\n\n    .. note::\n\n        This will strip comments from your config file"
  },
  {
    "code": "def dynamodb_autoscaling_policy(tables):\n    return Policy(\n        Statement=[\n            Statement(\n                Effect=Allow,\n                Resource=dynamodb_arns(tables),\n                Action=[\n                    dynamodb.DescribeTable,\n                    dynamodb.UpdateTable,\n                ]\n            ),\n            Statement(\n                Effect=Allow,\n                Resource=['*'],\n                Action=[\n                    cloudwatch.PutMetricAlarm,\n                    cloudwatch.DescribeAlarms,\n                    cloudwatch.GetMetricStatistics,\n                    cloudwatch.SetAlarmState,\n                    cloudwatch.DeleteAlarms,\n                ]\n            ),\n        ]\n    )",
    "docstring": "Policy to allow AutoScaling a list of DynamoDB tables."
  },
  {
    "code": "def list_entrypoints(entry_point):\n    found_entry_points = {}\n    for dist in working_set:\n        entry_map = dist.get_entry_map()\n        for group_name, entry_points in entry_map.items():\n            if entry_point is None and \\\n               not group_name.startswith('invenio'):\n                continue\n            if entry_point is not None and \\\n               entry_point != group_name:\n                continue\n            if group_name not in found_entry_points:\n                found_entry_points[group_name] = []\n            for ep in entry_points.values():\n                found_entry_points[group_name].append(str(ep))\n    for ep_group in sorted(found_entry_points.keys()):\n        click.secho('{0}'.format(ep_group), fg='green')\n        for ep in sorted(found_entry_points[ep_group]):\n            click.echo('  {0}'.format(ep))",
    "docstring": "List defined entry points."
  },
  {
    "code": "def check(cls):\n        attribs = [\n            'app_version',\n            'app_name',\n            'config_file_path',\n            'config_sep_str',\n        ]\n        for attrib in attribs:\n            if getattr(cls, attrib) == 'not_set':\n                raise IncompleteSetupError(f'elib_config setup is incomplete; missing: {attrib}')",
    "docstring": "Verifies that all necessary values for the package to be used have been provided\n\n        :raises: `elib_config._exc.IncompleteSetupError`"
  },
  {
    "code": "def set_cache_token(self, token_data):\n        if self.conn is None:\n            raise CacheException('Redis is not connected')\n        token = token_data['auth_token']\n        token_expires = token_data['expires_at']\n        roles = token_data['roles']\n        try:\n            datetime_object = datetime.strptime(\n                token_expires, '%Y-%m-%dT%H:%M:%S.%fZ')\n        except ValueError:\n            datetime_object = datetime.strptime(\n                token_expires, '%Y-%m-%dT%H:%M:%SZ')\n        ttl = (datetime.utcnow().now() - datetime_object)\n        token_data = json.dumps({\n            'expires_at': token_expires,\n            'roles': roles,\n            'user': token_data['user']\n        })\n        self.conn.set(token, token_data, ex=ttl.seconds)",
    "docstring": "Set Token with data in Redis"
  },
  {
    "code": "def path(self):\n        if len(self.heads) == 1:\n            return _fmt_mfs_path(self.heads.keys()[0], self.heads.values()[0])\n        else:\n            return \"(\" + \"|\".join(\n                _fmt_mfs_path(k, v) for (k, v) in self.heads.items()\n            ) + \")\"",
    "docstring": "The path attribute returns a stringified, concise representation of\n        the MultiFieldSelector.  It can be reversed by the ``from_path``\n        constructor."
  },
  {
    "code": "def create_generic_instances(self, instances):\n        generic_instances = []\n        for instance in instances:\n            transformed_instance = self._create_kube_dns_instance(instance)\n            generic_instances.append(transformed_instance)\n        return generic_instances",
    "docstring": "Transform each Kube DNS instance into a OpenMetricsBaseCheck instance"
  },
  {
    "code": "def get_revocation_time(self):\n        if self.revoked is False:\n            return\n        if timezone.is_aware(self.revoked_date):\n            return timezone.make_naive(self.revoked_date, pytz.utc)\n        return self.revoked_date",
    "docstring": "Get the revocation time as naive datetime.\n\n        Note that this method is only used by cryptography>=2.4."
  },
  {
    "code": "def complex_validates(validate_rule):\n    ref_dict = {\n    }\n    for column_names, predicate_refs in validate_rule.items():\n        for column_name in _to_tuple(column_names):\n            ref_dict[column_name] = \\\n                ref_dict.get(column_name, tuple()) + _normalize_predicate_refs(predicate_refs)\n    return validates(*ref_dict.keys())(\n        lambda self, name, value: _validate_handler(name, value, ref_dict[name]))",
    "docstring": "Quickly setup attributes validation by one-time, based on `sqlalchemy.orm.validates`.\n\n    Don't like `sqlalchemy.orm.validates`, you don't need create many model method,\n    as long as pass formatted validate rule.\n    (Cause of SQLAlchemy's validate mechanism, you need assignment this funciton's return value\n    to a model property.)\n\n    For simplicity, complex_validates don't support `include_removes` and `include_backrefs` parameters\n    that in `sqlalchemy.orm.validates`.\n\n    And we don't recommend you use this function multiple times in one model.\n    Because this will bring many problems, like:\n    1. Multiple complex_validates's execute order was decide by it's model property name, and by reversed order.\n       eg. predicates in `validator1 = complex_validates(...)`\n       will be executed **AFTER** predicates in `validator2 = complex_validates(...)`\n    2. If you try to validate the same attribute in two (or more) complex_validates, only one of complex_validates\n       will be execute. (May be this is a bug of SQLAlchemy?)\n    `complex_validates` was currently based on `sqlalchemy.orm.validates`, so it is difficult to solve these problems.\n    May be we can try to use `AttributeEvents` directly in further, to provide more reliable function.\n\n    Rule Format\n    -----------\n\n    {\n        column_name: predicate                          # basic format\n        (column_name2, column_name3): predicate         # you can specify multiple column_names to given predicates\n        column_name4: (predicate, predicate2)           # you can specify multiple predicates to given column_names\n        column_name5: [(predicate, arg1, ... argN)]     # and you can specify what arguments should pass to predicate\n                                                        # when it doing validate\n        (column_name6, column_name7): [(predicate, arg1, ... argN), predicate2]   # another example\n    }\n\n    Notice: If you want pass arguments to predicate, you must wrap whole command by another list or tuple.\n            Otherwise, we will determine the argument as another predicate.\n            So, this is wrong: { column_name: (predicate, arg) }\n            this is right: { column_name: [(predicate, arg)] }\n\n    Predicate\n    ---------\n\n    There's some `predefined_predicates`, you can just reference its name in validate rule.\n\n        {column_name: ['trans_upper']}\n\n    Or you can pass your own predicate function to the rule, like this:\n\n        def custom_predicate(value):\n            return value_is_legal       # return True or False for valid or invalid value\n\n        {column_name: [custom_predicate]}\n\n    If you want change the value when doing validate, return an `dict(value=new_value)` instead of boolean\n\n        {column_name: lambda value: dict(value = value * 2)}   # And you see, we can use lambda as a predicate.\n\n    And the predicate can receive extra arguments, that passes in rule:\n\n        def multiple(value, target_multiple):\n            return dict(value= value * target_multiple)\n\n        {column_name: (multiple, 10)}\n\n    Complete Example\n    ----------------\n\n    class People(db.Model):\n        name = Column(String(100))\n        age = Column(Integer)\n        IQ = Column(Integer)\n        has_lover = Column(Boolean)\n\n        validator = complex_validates({\n            'name': [('min_length', 1), ('max_length', 100)],\n            ('age', 'IQ'): [('min', 0)],\n            'has_lover': lambda value: return !value    # hate you!\n        })"
  },
  {
    "code": "def subclass(cls, t):\n        t.doc = None\n        t.terms = []\n        t.__class__ = SectionTerm\n        return t",
    "docstring": "Change a term into a Section Term"
  },
  {
    "code": "def calc_one_vert_gauss(one_vert, xyz=None, std=None):\n    trans = empty(xyz.shape[0])\n    for i, one_xyz in enumerate(xyz):\n        trans[i] = gauss(norm(one_vert - one_xyz), std)\n    return trans",
    "docstring": "Calculate how many electrodes influence one vertex, using a Gaussian\n    function.\n\n    Parameters\n    ----------\n    one_vert : ndarray\n        vector of xyz position of a vertex\n    xyz : ndarray\n        nChan X 3 with the position of all the channels\n    std : float\n        distance in mm of the Gaussian kernel\n\n    Returns\n    -------\n    ndarray\n        one vector with values for one vertex"
  },
  {
    "code": "def data(self, data: numpy.ndarray) -> None:\n        self.__data_item.set_data(numpy.copy(data))",
    "docstring": "Set the data.\n\n        :param data: A numpy ndarray.\n\n        .. versionadded:: 1.0\n\n        Scriptable: Yes"
  },
  {
    "code": "def node_scale_root_height(self, treeheight=1):\n        ctree = self._ttree.copy()\n        _height = ctree.treenode.height\n        for node in ctree.treenode.traverse():\n            node.dist = (node.dist / _height) * treeheight\n        ctree._coords.update()\n        return ctree",
    "docstring": "Returns a toytree copy with all nodes scaled so that the root \n        height equals the value entered for treeheight."
  },
  {
    "code": "def random_id(size=8, chars=string.ascii_letters + string.digits):\n\treturn ''.join(random.choice(chars) for _ in range(size))",
    "docstring": "Generates a random string of given size from the given chars.\n\n\t@param size:  The size of the random string.\n\t@param chars: Constituent pool of characters to draw random characters from.\n\t@type size:   number\n\t@type chars:  string\n\t@rtype:       string\n\t@return:      The string of random characters."
  },
  {
    "code": "def arguments(function, extra_arguments=0):\n    if not hasattr(function, '__code__'):\n        return ()\n    return function.__code__.co_varnames[:function.__code__.co_argcount + extra_arguments]",
    "docstring": "Returns the name of all arguments a function takes"
  },
  {
    "code": "def _build_verb_statement_mapping():\n    path_this = os.path.dirname(os.path.abspath(__file__))\n    map_path = os.path.join(path_this, 'isi_verb_to_indra_statement_type.tsv')\n    with open(map_path, 'r') as f:\n        first_line = True\n        verb_to_statement_type = {}\n        for line in f:\n            if not first_line:\n                line = line[:-1]\n                tokens = line.split('\\t')\n                if len(tokens) == 2 and len(tokens[1]) > 0:\n                    verb = tokens[0]\n                    s_type = tokens[1]\n                    try:\n                        statement_class = getattr(ist, s_type)\n                        verb_to_statement_type[verb] = statement_class\n                    except Exception:\n                        pass\n            else:\n                first_line = False\n    return verb_to_statement_type",
    "docstring": "Build the mapping between ISI verb strings and INDRA statement classes.\n\n    Looks up the INDRA statement class name, if any, in a resource file,\n    and resolves this class name to a class.\n\n    Returns\n    -------\n    verb_to_statement_type : dict\n        Dictionary mapping verb name to an INDRA statment class"
  },
  {
    "code": "def decimal_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs):\n        if (min is not None) and (max is not None) and not (max > min):\n            raise ValueError(\"Maximum limit has to be more than the minimum limit.\")\n        def decimal_validator(text):\n            error = None\n            try:\n                value = Decimal(text)\n            except InvalidOperation:\n                return None, \"Please enter a decimal value.\"\n            if (min is not None) and (value < min):\n                return None, \"The minimum allowable value is {0}.\".format(min)\n            if (max is not None) and (value > max):\n                return None, \"The maximum allowable value is {0}.\".format(max)\n            return value, None\n        return self.generic_entry(prompt, decimal_validator, message, rofi_args, **kwargs)",
    "docstring": "Prompt the user to enter a decimal number.\n\n        Parameters\n        ----------\n        prompt: string\n            Prompt to display to the user.\n        message: string, optional\n            Message to display under the entry line.\n        min, max: Decimal, optional\n            Minimum and maximum values to allow. If None, no limit is imposed.\n\n        Returns\n        -------\n        Decimal, or None if the dialog is cancelled."
  },
  {
    "code": "def validate(options):\n        try:\n            if options.backends.index('modelinstance') > options.backends.index('model'):\n                raise Exception(\"Metadata backend 'modelinstance' must come before 'model' backend\")\n        except ValueError:\n            raise Exception(\"Metadata backend 'modelinstance' must be installed in order to use 'model' backend\")",
    "docstring": "Validates the application of this backend to a given metadata"
  },
  {
    "code": "def to_phalf_from_pfull(arr, val_toa=0, val_sfc=0):\n    phalf = np.zeros((arr.shape[0] + 1, arr.shape[1], arr.shape[2]))\n    phalf[0] = val_toa\n    phalf[-1] = val_sfc\n    phalf[1:-1] = 0.5*(arr[:-1] + arr[1:])\n    return phalf",
    "docstring": "Compute data at half pressure levels from values at full levels.\n\n    Could be the pressure array itself, but it could also be any other data\n    defined at pressure levels.  Requires specification of values at surface\n    and top of atmosphere."
  },
  {
    "code": "def alterar(self, id_model, id_brand, name):\n        if not is_valid_int_param(id_model):\n            raise InvalidParameterError(\n                u'The identifier of Model is invalid or was not informed.')\n        model_map = dict()\n        model_map['name'] = name\n        model_map['id_brand'] = id_brand\n        url = 'model/' + str(id_model) + '/'\n        code, xml = self.submit({'model': model_map}, 'PUT', url)\n        return self.response(code, xml)",
    "docstring": "Change Model from by the identifier.\n\n        :param id_model: Identifier of the Model. Integer value and greater than zero.\n        :param id_brand: Identifier of the Brand. Integer value and greater than zero.\n        :param name: Model name. String with a minimum 3 and maximum of 100 characters\n\n        :return: None\n\n        :raise InvalidParameterError: The identifier of Model, Brand or name is null and invalid.\n        :raise MarcaNaoExisteError: Brand not registered.\n        :raise ModeloEquipamentoNaoExisteError: Model not registered.\n        :raise NomeMarcaModeloDuplicadoError: There is already a registered Model with the value of name and brand.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response"
  },
  {
    "code": "def get_residue_mapping(self):\n        if len(self.sequence_ids) == 2:\n            if not self.alignment_output:\n                self.align()\n            assert(self.alignment_output)\n            return self._create_residue_map(self._get_alignment_lines(), self.sequence_ids[1], self.sequence_ids[2])\n        else:\n            return None",
    "docstring": "Returns a mapping between the sequences ONLY IF there are exactly two. This restriction makes the code much simpler."
  },
  {
    "code": "def relpath(self):\n        here = os.path.abspath(os.path.curdir)\n        relpath = os.path.relpath(self.fpath, here)\n        return relpath",
    "docstring": "Determine the relative path to this repository\n\n        Returns:\n            str: relative path to this repository"
  },
  {
    "code": "def configure_root():\n    root_logger = logging.getLogger()\n    for hdlr in root_logger.handlers:\n        if isinstance(hdlr, logging.StreamHandler):\n            root_logger.removeHandler(hdlr)\n    root_logger.setLevel(ROOT_LOG_LEVEL)\n    hdlr = logging.StreamHandler(ROOT_LOG_STREAM) \n    formatter = colorlog.ColoredFormatter(\n                        '%(purple)s%(name)-10s %(log_color)s%(levelname)-8s%(reset)s %(white)s%(message)s',\n                        reset=True,\n                        log_colors={\n                            'DEBUG': 'cyan',\n                            'INFO': 'green',\n                            'WARNING': 'yellow',\n                            'ERROR': 'red',\n                            'CRITICAL': 'red,bg_white',\n                        } \n                                         )   \n    hdlr.setFormatter(formatter)\n    root_logger.addHandler(hdlr)",
    "docstring": "Configure the root logger."
  },
  {
    "code": "def represent_float_as_str(value):\n    if not isinstance(value, float):\n        raise GraphQLInvalidArgumentError(u'Attempting to represent a non-float as a float: '\n                                          u'{}'.format(value))\n    with decimal.localcontext() as ctx:\n        ctx.prec = 20\n        return u'{:f}'.format(decimal.Decimal(value))",
    "docstring": "Represent a float as a string without losing precision."
  },
  {
    "code": "def to_serializable_repr(x):\n    t = type(x)\n    if isinstance(x, list):\n        return list_to_serializable_repr(x)\n    elif t in (set, tuple):\n        return {\n            \"__class__\": class_to_serializable_representation(t),\n            \"__value__\": list_to_serializable_repr(x)\n        }\n    elif isinstance(x, dict):\n        return dict_to_serializable_repr(x)\n    elif isinstance(x, (FunctionType, BuiltinFunctionType)):\n        return function_to_serializable_representation(x)\n    elif type(x) is type:\n        return class_to_serializable_representation(x)\n    else:\n        state_dictionary = to_serializable_repr(to_dict(x))\n        state_dictionary[\"__class__\"] = class_to_serializable_representation(\n            x.__class__)\n        return state_dictionary",
    "docstring": "Convert an instance of Serializable or a primitive collection containing\n    such instances into serializable types."
  },
  {
    "code": "def handle_error(self, error, response):\n        query_params = {\"error\": error.error}\n        query = urlencode(query_params)\n        location = \"%s?%s\" % (self.client.redirect_uri, query)\n        response.status_code = 302\n        response.body = \"\"\n        response.add_header(\"Location\", location)\n        return response",
    "docstring": "Redirects the client in case an error in the auth process occurred."
  },
  {
    "code": "def filter_callbacks(cls, client, event_data):\n        for event in cls.filter_events(client, event_data):\n            for cb in event.callbacks:\n                yield cb",
    "docstring": "Filter registered events and yield all of their callbacks."
  },
  {
    "code": "def readCache(self, filename):\n        with open(filename, 'rb') as f:\n            self.modules = pickle.load(f)",
    "docstring": "Load the graph from a cache file."
  },
  {
    "code": "def upload(self, url, filename, data=None, formname=None,\n               otherfields=()):\n        if data is None:\n            data = open(filename, 'rb')\n        self._upbuffer = StringIO.StringIO(get_upload_form(filename, data,\n                                                           formname,\n                                                           otherfields))\n        ulheaders = self.stdheaders.copy()\n        ulheaders['Content-Type'] = 'multipart/form-data; boundary=' + BND\n        ulheaders['Content-Length'] = len(uploadforms[filename])\n        self.ulsize = len(uploadforms[filename])\n        webclient = self.dupe()\n        webclient.request('POST', url, self._upbuffer, ulheaders)\n        rsp = webclient.getresponse()\n        try:\n            del uploadforms[filename]\n        except KeyError:\n            pass\n        self.rspstatus = rsp.status\n        if rsp.status != 200:\n            raise Exception('Unexpected response in file upload: ' +\n                            rsp.read())\n        return rsp.read()",
    "docstring": "Upload a file to the url\n\n        :param url:\n        :param filename: The name of the file\n        :param data: A file object or data to use rather than reading from\n                     the file.\n        :return:"
  },
  {
    "code": "def _humanize_bytes(num_bytes, precision=1):\n    if num_bytes == 0:\n        return 'no bytes'\n    if num_bytes == 1:\n        return '1 byte'\n    factored_bytes = 0\n    factor_suffix = 'bytes'\n    for factor, suffix in ABBREVS:\n        if num_bytes >= factor:\n            factored_bytes = num_bytes / factor\n            factor_suffix = suffix\n            break\n    if factored_bytes == 1:\n        precision = 0\n    return '{:.{prec}f} {}'.format(factored_bytes, factor_suffix,\n                                   prec=precision)",
    "docstring": "Return a humanized string representation of a number of num_bytes.\n\n    from:\n    http://code.activestate.com/recipes/\n           577081-humanized-representation-of-a-number-of-num_bytes/\n\n    Assumes `from __future__ import division`.\n\n    >>> humanize_bytes(1)\n    '1 byte'\n    >>> humanize_bytes(1024)\n    '1.0 kB'\n    >>> humanize_bytes(1024*123)\n    '123.0 kB'\n    >>> humanize_bytes(1024*12342)\n    '12.1 MB'\n    >>> humanize_bytes(1024*12342,2)\n    '12.05 MB'\n    >>> humanize_bytes(1024*1234,2)\n    '1.21 MB'\n    >>> humanize_bytes(1024*1234*1111,2)\n    '1.31 GB'\n    >>> humanize_bytes(1024*1234*1111,1)\n    '1.3 GB'"
  },
  {
    "code": "def path_helper(self, operations, view, app=None, **kwargs):\n        rule = self._rule_for_view(view, app=app)\n        operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))\n        if hasattr(view, 'view_class') and issubclass(view.view_class, MethodView):\n            for method in view.methods:\n                if method in rule.methods:\n                    method_name = method.lower()\n                    method = getattr(view.view_class, method_name)\n                    operations[method_name] = yaml_utils.load_yaml_from_docstring(method.__doc__)\n        return self.flaskpath2openapi(rule.rule)",
    "docstring": "Path helper that allows passing a Flask view function."
  },
  {
    "code": "def calc_normal_std_he_forward(inmaps, outmaps, kernel=(1, 1)):\n    r\n    return np.sqrt(2. / (np.prod(kernel) * inmaps))",
    "docstring": "r\"\"\"Calculates the standard deviation proposed by He et al.\n\n    .. math::\n        \\sigma = \\sqrt{\\frac{2}{NK}}\n\n    Args:\n        inmaps (int): Map size of an input Variable, :math:`N`.\n        outmaps (int): Map size of an output Variable, :math:`M`.\n        kernel (:obj:`tuple` of :obj:`int`): Convolution kernel spatial shape.\n            In above definition, :math:`K` is the product of shape dimensions.\n            In Affine, the default value should be used.\n\n    Example:\n\n    .. code-block:: python\n\n        import nnabla as nn\n        import nnabla.parametric_functions as PF\n        import nnabla.initializer as I\n\n        x = nn.Variable([60,1,28,28])\n        s = I.calc_normal_std_he_forward(x.shape[1],64)\n        w = I.NormalInitializer(s)\n        b = I.ConstantInitializer(0)\n        h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv')\n\n    References:\n        * `He, et al. Delving Deep into Rectifiers: Surpassing Human-Level\n          Performance on ImageNet Classification.\n          <https://arxiv.org/abs/1502.01852>`_"
  },
  {
    "code": "def get_path(self, i):\n        index = (i - 1) // 2\n        reverse = (i - 1) % 2\n        path = self.paths[index]\n        if reverse:\n            return path.reversed()\n        else:\n            return path",
    "docstring": "Returns the path corresponding to the node i."
  },
  {
    "code": "def from_sample(sample):\n    upload_config = sample.get(\"upload\")\n    if upload_config:\n        approach = _approaches[upload_config.get(\"method\", \"filesystem\")]\n        for finfo in _get_files(sample):\n            approach.update_file(finfo, sample, upload_config)\n    return [[sample]]",
    "docstring": "Upload results of processing from an analysis pipeline sample."
  },
  {
    "code": "def _do_config_proposal_vote(args):\n    signer = _read_signer(args.key)\n    rest_client = RestClient(args.url)\n    proposals = _get_proposals(rest_client)\n    proposal = None\n    for candidate in proposals.candidates:\n        if candidate.proposal_id == args.proposal_id:\n            proposal = candidate\n            break\n    if proposal is None:\n        raise CliException('No proposal exists with the given id')\n    for vote_record in proposal.votes:\n        if vote_record.public_key == signer.get_public_key().as_hex():\n            raise CliException(\n                'A vote has already been recorded with this signing key')\n    txn = _create_vote_txn(\n        signer,\n        args.proposal_id,\n        proposal.proposal.setting,\n        args.vote_value)\n    batch = _create_batch(signer, [txn])\n    batch_list = BatchList(batches=[batch])\n    rest_client.send_batches(batch_list)",
    "docstring": "Executes the 'proposal vote' subcommand.  Given a key file, a proposal\n    id and a vote value, it generates a batch of sawtooth_settings transactions\n    in a BatchList instance.  The BatchList is file or submitted to a\n    validator."
  },
  {
    "code": "def update(accountable, options):\n    issue = accountable.issue_update(options)\n    headers = issue.keys()\n    rows = [headers, [v for k, v in issue.items()]]\n    print_table(SingleTable(rows))",
    "docstring": "Update an existing issue."
  },
  {
    "code": "def is_default(name=None, index=None):\n    if not is_configured():\n        raise JutException('No configurations available, please run `jut config add`')\n    count = 1\n    for configuration in _CONFIG.sections():\n        if index != None:\n            if _CONFIG.has_option(configuration, 'default') and count == index:\n                return True\n        if name != None:\n            if _CONFIG.has_option(configuration, 'default') and configuration == name:\n                return True\n        count += 1\n    return False",
    "docstring": "returns True if the specified configuration is the default one"
  },
  {
    "code": "def __store_other(self, o, method_name, member):\n        self.__store__[ method_name ] = eval( \"o.\" + method_name )\n        self.__store__[ method_name[0].lower() + method_name[1:] ] = eval( \"o.\" + method_name )",
    "docstring": "Stores a reference to an attribute on o\n\n        :param mixed o: Some object\n        :param str method_name: The name of the attribute\n        :param mixed member: The attribute"
  },
  {
    "code": "def files_write(self, path, file, offset=0, create=False, truncate=False,\n                    count=None, **kwargs):\n        opts = {\"offset\": offset, \"create\": create, \"truncate\": truncate}\n        if count is not None:\n            opts[\"count\"] = count\n        kwargs.setdefault(\"opts\", opts)\n        args = (path,)\n        body, headers = multipart.stream_files(file, self.chunk_size)\n        return self._client.request('/files/write', args,\n                                    data=body, headers=headers, **kwargs)",
    "docstring": "Writes to a mutable file in the MFS.\n\n        .. code-block:: python\n\n            >>> c.files_write(\"/test/file\", io.BytesIO(b\"hi\"), create=True)\n            b''\n\n        Parameters\n        ----------\n        path : str\n            Filepath within the MFS\n        file : io.RawIOBase\n            IO stream object with data that should be written\n        offset : int\n            Byte offset at which to begin writing at\n        create : bool\n            Create the file if it does not exist\n        truncate : bool\n            Truncate the file to size zero before writing\n        count : int\n            Maximum number of bytes to read from the source ``file``"
  },
  {
    "code": "def rename(self, arr, new_name=True):\n        name_in_me = arr.psy.arr_name in self.arr_names\n        if not name_in_me:\n            return arr, False\n        elif name_in_me and not self._contains_array(arr):\n            if new_name is False:\n                raise ValueError(\n                    \"Array name %s is already in use! Set the `new_name` \"\n                    \"parameter to None for renaming!\" % arr.psy.arr_name)\n            elif new_name is True:\n                new_name = new_name if isstring(new_name) else 'arr{0}'\n                arr.psy.arr_name = self.next_available_name(new_name)\n                return arr, True\n        return arr, None",
    "docstring": "Rename an array to find a name that isn't already in the list\n\n        Parameters\n        ----------\n        arr: InteractiveBase\n            A :class:`InteractiveArray` or :class:`InteractiveList` instance\n            whose name shall be checked\n        new_name: bool or str\n            If False, and the ``arr_name`` attribute of the new array is\n            already in the list, a ValueError is raised.\n            If True and the ``arr_name`` attribute of the new array is not\n            already in the list, the name is not changed. Otherwise, if the\n            array name is already in use, `new_name` is set to 'arr{0}'.\n            If not True, this will be used for renaming (if the array name of\n            `arr` is in use or not). ``'{0}'`` is replaced by a counter\n\n        Returns\n        -------\n        InteractiveBase\n            `arr` with changed ``arr_name`` attribute\n        bool or None\n            True, if the array has been renamed, False if not and None if the\n            array is already in the list\n\n        Raises\n        ------\n        ValueError\n            If it was impossible to find a name that isn't already  in the list\n        ValueError\n            If `new_name` is False and the array is already in the list"
  },
  {
    "code": "def job(func_or_queue=None, connection=None, *args, **kwargs):\n    if callable(func_or_queue):\n        func = func_or_queue\n        queue = 'default'\n    else:\n        func = None\n        queue = func_or_queue or 'default'\n    if not isinstance(queue, basestring):\n        queue = unicode(queue)\n    try:\n        queue = get_queue(queue)\n        if connection is None:\n            connection = queue.connection\n    except KeyError:\n        pass\n    decorator = _job(queue, connection=connection, *args, **kwargs)\n    if func:\n        return decorator(func)\n    return decorator",
    "docstring": "The same as RQ's job decorator, but it works automatically works out\n    the ``connection`` argument from RQ_QUEUES.\n\n    And also, it allows simplified ``@job`` syntax to put job into\n    default queue."
  },
  {
    "code": "def iter_commit_activity(self, number=-1, etag=None):\n        url = self._build_url('stats', 'commit_activity', base_url=self._api)\n        return self._iter(int(number), url, dict, etag=etag)",
    "docstring": "Iterate over last year of commit activity by week.\n\n        See: http://developer.github.com/v3/repos/statistics/\n\n        :param int number: (optional), number of weeks to return. Default -1\n            will return all of the weeks.\n        :param str etag: (optional), ETag from a previous request to the same\n            endpoint\n        :returns: generator of dictionaries\n\n        .. note:: All statistics methods may return a 202. On those occasions,\n                  you will not receive any objects. You should store your\n                  iterator and check the new ``last_status`` attribute. If it\n                  is a 202 you should wait before re-requesting.\n\n        .. versionadded:: 0.7"
  },
  {
    "code": "def coltype_as_typeengine(coltype: Union[VisitableType,\n                                         TypeEngine]) -> TypeEngine:\n    if isinstance(coltype, TypeEngine):\n        return coltype\n    return coltype()",
    "docstring": "Instances of SQLAlchemy column types are subclasses of ``TypeEngine``.\n    It's possible to specify column types either as such instances, or as the\n    class type. This function ensures that such classes are converted to\n    instances.\n\n    To explain: you can specify columns like\n\n    .. code-block:: python\n\n        a = Column(\"a\", Integer)\n        b = Column(\"b\", Integer())\n        c = Column(\"c\", String(length=50))\n\n        isinstance(Integer, TypeEngine)  # False\n        isinstance(Integer(), TypeEngine)  # True\n        isinstance(String(length=50), TypeEngine)  # True\n\n        type(Integer)  # <class 'sqlalchemy.sql.visitors.VisitableType'>\n        type(Integer())  # <class 'sqlalchemy.sql.sqltypes.Integer'>\n        type(String)  # <class 'sqlalchemy.sql.visitors.VisitableType'>\n        type(String(length=50))  # <class 'sqlalchemy.sql.sqltypes.String'>\n\n    This function coerces things to a :class:`TypeEngine`."
  },
  {
    "code": "def extract(pattern, string, *, assert_equal=False, one=False,\n            condense=False, default=None, default_if_multiple=True,\n            default_if_none=True):\n    if isinstance(pattern, str):\n        output = get_content(pattern, string)\n    else:\n        output = []\n        for p in pattern:\n            output += get_content(p, string)\n    output = process_output(output, one=one, condense=condense,\n                            default=default,\n                            default_if_multiple=default_if_multiple,\n                            default_if_none=default_if_none)\n    if assert_equal:\n        assert_output(output, assert_equal)\n    else:\n        return output",
    "docstring": "Used to extract a given regex pattern from a string, given several options"
  },
  {
    "code": "def write_dag(self):\n    if not self.__nodes_finalized:\n      for node in self.__nodes:\n        node.finalize()\n    self.write_concrete_dag()\n    self.write_abstract_dag()",
    "docstring": "Write either a dag or a dax."
  },
  {
    "code": "def deserialize_durable_record_to_current_model(record, current_model):\n    if record.get(EVENT_TOO_BIG_FLAG):\n        return get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model)\n    new_image = remove_durable_specific_fields(record['dynamodb']['NewImage'])\n    data = {}\n    for item, value in new_image.items():\n        data[item] = DESER.deserialize(value)\n    return current_model(**data)",
    "docstring": "Utility function that will take a Durable Dynamo event record and turn it into the proper Current Dynamo object.\n\n    This will properly deserialize the ugly Dynamo datatypes away.\n    :param record:\n    :param current_model:\n    :return:"
  },
  {
    "code": "def namedb_account_transaction_save(cur, address, token_type, new_credit_value, new_debit_value, block_id, vtxindex, txid, existing_account):\n    if existing_account is None:\n        existing_account = {}\n    accounts_insert = {\n        'address': address,\n        'type': token_type,\n        'credit_value': '{}'.format(new_credit_value),\n        'debit_value': '{}'.format(new_debit_value),\n        'lock_transfer_block_id': existing_account.get('lock_transfer_block_id', 0),\n        'receive_whitelisted': existing_account.get('receive_whitelisted', True),\n        'metadata': existing_account.get('metadata', None),\n        'block_id': block_id,\n        'txid': txid,\n        'vtxindex': vtxindex\n    }\n    try:\n        query, values = namedb_insert_prepare(cur, accounts_insert, 'accounts')\n    except Exception as e:\n        log.exception(e)\n        log.fatal('FATAL: failed to append account history record for {} at ({},{})'.format(address, block_id, vtxindex))\n        os.abort()\n    namedb_query_execute(cur, query, values)\n    return True",
    "docstring": "Insert the new state of an account at a particular point in time.\n\n    The data must be for a never-before-seen (txid,block_id,vtxindex) set in the accounts table, but must\n    correspond to an entry in the history table.\n\n    If existing_account is not None, then copy all other remaining fields from it.\n\n    Return True on success\n    Raise an Exception on error"
  },
  {
    "code": "def last_modified(self) -> Optional[datetime.datetime]:\n        httpdate = self._headers.get(hdrs.LAST_MODIFIED)\n        if httpdate is not None:\n            timetuple = parsedate(httpdate)\n            if timetuple is not None:\n                return datetime.datetime(*timetuple[:6],\n                                         tzinfo=datetime.timezone.utc)\n        return None",
    "docstring": "The value of Last-Modified HTTP header, or None.\n\n        This header is represented as a `datetime` object."
  },
  {
    "code": "def build_body(self):\n        _increase_indent()\n        body_array = [x.build() for x in self.iterable]\n        nl = '\\n' if self.append_extra_newline else ''\n        if len(self.iterable) >= 1:\n            body = self.join_body_on.join(body_array) + nl\n        else:\n            body = ''\n        _decrease_indent()\n        return body",
    "docstring": "Builds the body of a syslog-ng configuration object."
  },
  {
    "code": "def get_criteria(self, sess, model, advx, y, batch_size=BATCH_SIZE):\n    names, factory = self.extra_criteria()\n    factory = _CriteriaFactory(model, factory)\n    results = batch_eval_multi_worker(sess, factory, [advx, y],\n                                      batch_size=batch_size, devices=devices)\n    names = ['correctness', 'confidence'] + names\n    out = dict(safe_zip(names, results))\n    return out",
    "docstring": "Returns a dictionary mapping the name of each criterion to a NumPy\n    array containing the value of that criterion for each adversarial\n    example.\n    Subclasses can add extra criteria by implementing the `extra_criteria`\n    method.\n\n    :param sess: tf.session.Session\n    :param model: cleverhans.model.Model\n    :param adv_x: numpy array containing the adversarial examples made so far\n      by earlier work in the bundling process\n    :param y: numpy array containing true labels\n    :param batch_size: int, batch size"
  },
  {
    "code": "def date_tuple(ovls):\n    day = month = year = 0\n    for o in ovls:\n        if 'day' in o.props:\n            day = o.value\n        if 'month' in o.props:\n            month = o.value\n        if 'year' in o.props:\n            year = o.value\n        if 'date' in o.props:\n            day, month, year = [(o or n) for o, n in zip((day, month,\n                                                          year), o.value)]\n    return (day, month, year)",
    "docstring": "We should have a list of overlays from which to extract day month\n    year."
  },
  {
    "code": "def get_source(self, key, name_spaces=None, default_prefix=''):\n        source = self.source or key\n        prefix = default_prefix\n        if name_spaces and self.name_space and self.name_space in name_spaces:\n            prefix = ''.join([name_spaces[self.name_space], ':'])\n        return ''.join([prefix, source])",
    "docstring": "Generates the dictionary key for the serialized representation\n        based on the instance variable source and a provided key.\n\n        :param str key: name of the field in model\n        :returns: self.source or key"
  },
  {
    "code": "def wrap_xblock(self, block, view, frag, context):\n        if hasattr(self, 'wrap_child'):\n            log.warning(\"wrap_child is deprecated in favor of wrap_xblock and wrap_aside %s\", self.__class__)\n            return self.wrap_child(block, view, frag, context)\n        extra_data = {'name': block.name} if block.name else {}\n        return self._wrap_ele(block, view, frag, extra_data)",
    "docstring": "Creates a div which identifies the xblock and writes out the json_init_args into a script tag.\n\n        If there's a `wrap_child` method, it calls that with a deprecation warning.\n\n        The default implementation creates a frag to wraps frag w/ a div identifying the xblock. If you have\n        javascript, you'll need to override this impl"
  },
  {
    "code": "def asscipy(self):\n        data = self.data.asnumpy()\n        indices = self.indices.asnumpy()\n        indptr = self.indptr.asnumpy()\n        if not spsp:\n            raise ImportError(\"scipy is not available. \\\n                               Please check if the scipy python bindings are installed.\")\n        return spsp.csr_matrix((data, indices, indptr), shape=self.shape, dtype=self.dtype)",
    "docstring": "Returns a ``scipy.sparse.csr.csr_matrix`` object with value copied from this array\n\n        Examples\n        --------\n        >>> x = mx.nd.sparse.zeros('csr', (2,3))\n        >>> y = x.asscipy()\n        >>> type(y)\n        <type 'scipy.sparse.csr.csr_matrix'>\n        >>> y\n        <2x3 sparse matrix of type '<type 'numpy.float32'>'\n        with 0 stored elements in Compressed Sparse Row format>"
  },
  {
    "code": "def rotate(self, rad):\n        s, c = [f(rad) for f in (math.sin, math.cos)]\n        x, y = (c * self.x - s * self.y, s * self.x + c * self.y)\n        return Point(x, y)",
    "docstring": "Rotate counter-clockwise by rad radians.\n\n        Positive y goes *up,* as in traditional mathematics.\n\n        Interestingly, you can use this in y-down computer graphics, if\n        you just remember that it turns clockwise, rather than\n        counter-clockwise.\n\n        The new position is returned as a new Point."
  },
  {
    "code": "def _set_id(self, Id, is_added, index):\n        if is_added:\n            self.selected_ids.add(Id)\n        else:\n            self.selected_ids.remove(Id)\n        self.dataChanged.emit(index, index)",
    "docstring": "Update selected_ids and emit dataChanged"
  },
  {
    "code": "def get_service_display_name(name):\n        with win32.OpenSCManager(\n            dwDesiredAccess = win32.SC_MANAGER_ENUMERATE_SERVICE\n        ) as hSCManager:\n            return win32.GetServiceDisplayName(hSCManager, name)",
    "docstring": "Get the service display name for the given service name.\n\n        @see: L{get_service}\n\n        @type  name: str\n        @param name: Service unique name. You can get this value from the\n            C{ServiceName} member of the service descriptors returned by\n            L{get_services} or L{get_active_services}.\n\n        @rtype:  str\n        @return: Service display name."
  },
  {
    "code": "async def post_data(self, path, data=None, headers=None, timeout=None):\n        url = self.base_url + path\n        _LOGGER.debug('POST URL: %s', url)\n        self._log_data(data, False)\n        resp = None\n        try:\n            resp = await self._session.post(\n                url, headers=headers, data=data,\n                timeout=DEFAULT_TIMEOUT if timeout is None else timeout)\n            if resp.content_length is not None:\n                resp_data = await resp.read()\n            else:\n                resp_data = None\n            self._log_data(resp_data, True)\n            return resp_data, resp.status\n        except Exception as ex:\n            if resp is not None:\n                resp.close()\n            raise ex\n        finally:\n            if resp is not None:\n                await resp.release()",
    "docstring": "Perform a POST request."
  },
  {
    "code": "def json_compat_obj_encode(data_type, obj, caller_permissions=None, alias_validators=None,\n                           old_style=False, for_msgpack=False, should_redact=False):\n    serializer = StoneToPythonPrimitiveSerializer(\n        caller_permissions, alias_validators, for_msgpack, old_style, should_redact)\n    return serializer.encode(data_type, obj)",
    "docstring": "Encodes an object into a JSON-compatible dict based on its type.\n\n    Args:\n        data_type (Validator): Validator for obj.\n        obj (object): Object to be serialized.\n        caller_permissions (list): The list of raw-string caller permissions\n            with which to serialize.\n\n    Returns:\n        An object that when passed to json.dumps() will produce a string\n        giving the JSON-encoded object.\n\n    See json_encode() for additional information about validation."
  },
  {
    "code": "def snapshot_folder():\n    logger.info(\"Snapshot folder\")\n    try:\n        stdout = subprocess.check_output([\"git\", \"show\", \"-s\", \"--format=%cI\", \"HEAD\"])\n    except subprocess.CalledProcessError as e:\n        logger.error(\"Error: {}\".format(e.output.decode('ascii', 'ignore').strip()))\n        sys.exit(2)\n    except FileNotFoundError as e:\n        logger.error(\"Error: {}\".format(e))\n        sys.exit(2)\n    ds = stdout.decode('ascii', 'ignore').strip()\n    dt = datetime.fromisoformat(ds)\n    utc = dt - dt.utcoffset()\n    return utc.strftime(\"%Y%m%d_%H%M%S\")",
    "docstring": "Use the commit date in UTC as folder name"
  },
  {
    "code": "def to_df_CSV(self, tempfile: str=None, tempkeep: bool=False, **kwargs) -> 'pd.DataFrame':\n        return self.to_df(method='CSV', tempfile=tempfile, tempkeep=tempkeep, **kwargs)",
    "docstring": "Export this SAS Data Set to a Pandas Data Frame via CSV file\n\n        :param tempfile: [optional] an OS path for a file to use for the local CSV file; default it a temporary file that's cleaned up\n        :param tempkeep: if you specify your own file to use with tempfile=, this controls whether it's cleaned up after using it\n        :param kwargs:\n        :return: Pandas data frame\n        :rtype: 'pd.DataFrame'"
  },
  {
    "code": "def GetTransPosition(df,field,dic,refCol=\"transcript_id\"):\n    try:\n        gen=str(int(df[field]))\n        transid=df[refCol]\n        bases=dic.get(transid).split(\",\")\n        bases=bases.index(str(gen))+1\n    except:\n        bases=np.nan\n    return bases",
    "docstring": "Maps a genome position to transcript positon\"\n\n    :param df: a Pandas dataframe\n    :param field: the head of the column containing the genomic position\n    :param dic: a dictionary containing for each transcript the respective bases eg. {ENST23923910:'234,235,236,1021,..'}\n    :param refCol: header of the reference column with IDs, eg. 'transcript_id'\n\n    :returns: position on transcript"
  },
  {
    "code": "def set_modifier_mapping(self, keycodes):\n        r = request.SetModifierMapping(display = self.display,\n                                       keycodes = keycodes)\n        return r.status",
    "docstring": "Set the keycodes for the eight modifiers X.Shift, X.Lock,\n        X.Control, X.Mod1, X.Mod2, X.Mod3, X.Mod4 and X.Mod5. keycodes\n        should be a eight-element list where each entry is a list of the\n        keycodes that should be bound to that modifier.\n\n        If any changed\n        key is logically in the down state, X.MappingBusy is returned and\n        the mapping is not changed. If the mapping violates some server\n        restriction, X.MappingFailed is returned. Otherwise the mapping\n        is changed and X.MappingSuccess is returned."
  },
  {
    "code": "def _badlink(info, base):\n    tip = _resolved(os.path.join(base, os.path.dirname(info.name)))\n    return _badpath(info.linkname, base=tip)",
    "docstring": "Links are interpreted relative to the directory containing the link"
  },
  {
    "code": "def default(cls):\n        with enamlnative.imports():\n            for impl in [\n                TornadoEventLoop,\n                TwistedEventLoop,\n                BuiltinEventLoop,\n            ]:\n                if impl.available():\n                    print(\"Using {} event loop!\".format(impl))\n                    return impl()\n        raise RuntimeError(\"No event loop implementation is available. \"\n                           \"Install tornado or twisted.\")",
    "docstring": "Get the first available event loop implementation\n        based on which packages are installed."
  },
  {
    "code": "def connect(self):\n        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        try:\n            self.socket.connect((self.host, self.port))\n        except socket.error as (err, msg):\n            self.connected = False\n            raise ScratchError(\"[Errno %d] %s\" % (err, msg))\n        self.connected = True",
    "docstring": "Connects to Scratch."
  },
  {
    "code": "def recognize_array(self, byte_array):\n        if type(byte_array) != bytes:\n            raise TypeError(\"Expected a byte array (string in Python 2, bytes in Python 3)\")\n        pb = ctypes.cast(byte_array, ctypes.POINTER(ctypes.c_ubyte))\n        ptr = self._recognize_array_func(self.alpr_pointer, pb, len(byte_array))\n        json_data = ctypes.cast(ptr, ctypes.c_char_p).value\n        json_data = _convert_from_charp(json_data)\n        response_obj = json.loads(json_data)\n        self._free_json_mem_func(ctypes.c_void_p(ptr))\n        return response_obj",
    "docstring": "This causes OpenALPR to attempt to recognize an image passed in as a byte array.\n\n        :param byte_array: This should be a string (Python 2) or a bytes object (Python 3)\n        :return: An OpenALPR analysis in the form of a response dictionary"
  },
  {
    "code": "async def _register(self):\n        if self.registered:\n            self.logger.debug(\"skipping cap registration, already registered!\")\n            return\n        await self.rawmsg('CAP', 'LS', '302')\n        await super()._register()",
    "docstring": "Hijack registration to send a CAP LS first."
  },
  {
    "code": "def _update_lock_icon(self):\r\n        icon = ima.icon('lock') if self.locked else ima.icon('lock_open')\r\n        self.locked_button.setIcon(icon)\r\n        tip = _(\"Unlock\") if self.locked else _(\"Lock\")\r\n        self.locked_button.setToolTip(tip)",
    "docstring": "Update locked state icon"
  },
  {
    "code": "def _remove_watch_block(self, wb):\n\t\tif (self._wbslock == None):\n\t\t\tself._wbslock = Lock()\n\t\tself._wbslock.acquire()\n\t\tself._wbs.remove(wb)\n\t\tif len(self._wbs) == 0:\n\t\t\tself._stop_enqueue_thread()\n\t\t\tself._stop_dequeue_thread()\n\t\tself._wbslock.release()",
    "docstring": "Internal method to remove a watch block for stopping event monitoring."
  },
  {
    "code": "def _startMqtt(self):\n        LOGGER.info('Connecting to MQTT... {}:{}'.format(self._server, self._port))\n        try:\n            self._mqttc.connect_async('{}'.format(self._server), int(self._port), 10)\n            self._mqttc.loop_forever()\n        except Exception as ex:\n            template = \"An exception of type {0} occurred. Arguments:\\n{1!r}\"\n            message = template.format(type(ex).__name__, ex.args)\n            LOGGER.error(\"MQTT Connection error: {}\".format(message), exc_info=True)",
    "docstring": "The client start method. Starts the thread for the MQTT Client\n        and publishes the connected message."
  },
  {
    "code": "def _docstring(self):\n        s = '\n' + \"\\n\"\n        return s",
    "docstring": "Generate a docstring for the generated source file.\n\n        :return: new docstring\n        :rtype: str"
  },
  {
    "code": "def load(self, data):\n        branches = defaultdict(list)\n        for row in data:\n            branches[row[-4]].append(row)\n        childbranch = self.db._childbranch\n        branch2do = deque(['trunk'])\n        store = self._store\n        while branch2do:\n            branch = branch2do.popleft()\n            for row in branches[branch]:\n                store(*row, planning=False, loading=True)\n            if branch in childbranch:\n                branch2do.extend(childbranch[branch])",
    "docstring": "Add a bunch of data. Must be in chronological order.\n\n        But it doesn't need to all be from the same branch, as long as\n        each branch is chronological of itself."
  },
  {
    "code": "def on_mode_button(self, my_button, state):\n        if state:\n            self.controller.set_mode(my_button.get_label())",
    "docstring": "Notify the controller of a new mode setting."
  },
  {
    "code": "def highlight(text: str, color_code: int, bold: bool=False) -> str:\n    return '{}\\033[{}m{}\\033[0m'.format(\n        '\\033[1m' if bold else '',\n        color_code,\n        text,)",
    "docstring": "Wraps the given string with terminal color codes.\n\n    Args:\n        text: The content to highlight.\n        color_code: The color to highlight with, e.g. 'shelltools.RED'.\n        bold: Whether to bold the content in addition to coloring.\n\n    Returns:\n        The highlighted string."
  },
  {
    "code": "def motion_sensor(self, enabled):\n        if enabled is True:\n            value = CONST.SETTINGS_MOTION_POLICY_ON\n        elif enabled is False:\n            value = CONST.SETTINGS_MOTION_POLICY_OFF\n        else:\n            raise SkybellException(ERROR.INVALID_SETTING_VALUE,\n                                   (CONST.SETTINGS_MOTION_POLICY, enabled))\n        self._set_setting({CONST.SETTINGS_MOTION_POLICY: value})",
    "docstring": "Set the motion sensor state."
  },
  {
    "code": "def _check_sensor_platform_consistency(self, sensor):\n        ref_sensor = SENSORS.get(self.platform, None)\n        if ref_sensor and not sensor == ref_sensor:\n            logger.error('Sensor-Platform mismatch: {} is not a payload '\n                         'of {}. Did you choose the correct reader?'\n                         .format(sensor, self.platform))",
    "docstring": "Make sure sensor and platform are consistent\n\n        Args:\n            sensor (str) : Sensor name from YAML dataset definition\n\n        Raises:\n            ValueError if they don't match"
  },
  {
    "code": "def appendData(self, xdata, ydata, color='b', legendstr=None):\n        item = self.plot(xdata, ydata, pen=color)\n        if legendstr is not None:\n            self.legend.addItem(item, legendstr)\n        return item",
    "docstring": "Adds the data to the plot\n\n        :param xdata: index values for data, plotted on x-axis\n        :type xdata: numpy.ndarray\n        :param ydata: value data to plot, dimension must match xdata\n        :type ydata: numpy.ndarray"
  },
  {
    "code": "def run(env):\n    os.putenv('CIPR_PACKAGES', env.package_dir)\n    os.putenv('CIPR_PROJECT', env.project_directory)\n    cmd = AND(\n        clom.cd(path.dirname(env.project_directory)),\n        clom[CORONA_SIMULATOR_PATH](path.basename(env.project_directory))\n    )\n    try:\n        cmd.shell.execute()\n    except KeyboardInterrupt:\n        pass",
    "docstring": "Run current project in the Corona Simulator"
  },
  {
    "code": "def get_stripped_file_lines(filename):\n    try:\n        lines = open(filename).readlines()\n    except FileNotFoundError:\n        fatal(\"Could not open file: {!r}\".format(filename))\n    return [line.strip() for line in lines]",
    "docstring": "Return lines of a file with whitespace removed"
  },
  {
    "code": "def many_from_config(config):\n        result = []\n        credentials = config.get_section(\"credentials\")\n        if len(credentials) > 0:\n            sections_names = credentials.get_section_names()\n            for section in sections_names:\n                credential = credentials.get_section(section)\n                result.append(CredentialParams(credential))\n        else:\n            credential = config.get_section(\"credential\")\n            result.append(CredentialParams(credential))\n        return result",
    "docstring": "Retrieves all CredentialParams from configuration parameters\n        from \"credentials\" section. If \"credential\" section is present instead,\n        than it returns a list with only one CredentialParams.\n\n        :param config: a configuration parameters to retrieve credentials\n\n        :return: a list of retrieved CredentialParams"
  },
  {
    "code": "def can_delete_assets(self):\n        url_path = construct_url('authorization',\n                                 bank_id=self._catalog_idstr)\n        return self._get_request(url_path)['assetHints']['canDelete']",
    "docstring": "Tests if this user can delete ``Assets``.\n\n        A return of true does not guarantee successful authorization. A\n        return of false indicates that it is known deleting an ``Asset``\n        will result in a ``PermissionDenied``. This is intended as a\n        hint to an application that may opt not to offer delete\n        operations to an unauthorized user.\n\n        :return: ``false`` if ``Asset`` deletion is not authorized, ``true`` otherwise\n        :rtype: ``boolean``\n\n\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def circle_right(self, radius_m, velocity=VELOCITY, angle_degrees=360.0):\n        distance = 2 * radius_m * math.pi * angle_degrees / 360.0\n        flight_time = distance / velocity\n        self.start_circle_right(radius_m, velocity)\n        time.sleep(flight_time)\n        self.stop()",
    "docstring": "Go in circle, clock wise\n\n        :param radius_m: The radius of the circle (meters)\n        :param velocity: The velocity along the circle (meters/second)\n        :param angle_degrees: How far to go in the circle (degrees)\n        :return:"
  },
  {
    "code": "def fix_jp2_image(image, bit_depth):\n    if bit_depth in [8, 16]:\n        return image\n    if bit_depth == 15:\n        try:\n            return image >> 1\n        except TypeError:\n            raise IOError('Failed to read JPEG 2000 image correctly. Most likely reason is that Pillow did not '\n                          'install OpenJPEG library correctly. Try reinstalling Pillow from a wheel')\n    raise ValueError('Bit depth {} of jp2 image is currently not supported. '\n                     'Please raise an issue on package Github page'.format(bit_depth))",
    "docstring": "Because Pillow library incorrectly reads JPEG 2000 images with 15-bit encoding this function corrects the\n    values in image.\n\n    :param image: image read by opencv library\n    :type image: numpy array\n    :param bit_depth: bit depth of jp2 image encoding\n    :type bit_depth: int\n    :return: corrected image\n    :rtype: numpy array"
  },
  {
    "code": "def update_policy(self):\n        self.demonstration_buffer.update_buffer.shuffle()\n        batch_losses = []\n        num_batches = min(len(self.demonstration_buffer.update_buffer['actions']) //\n                          self.n_sequences, self.batches_per_epoch)\n        for i in range(num_batches):\n            update_buffer = self.demonstration_buffer.update_buffer\n            start = i * self.n_sequences\n            end = (i + 1) * self.n_sequences\n            mini_batch = update_buffer.make_mini_batch(start, end)\n            run_out = self.policy.update(mini_batch, self.n_sequences)\n            loss = run_out['policy_loss']\n            batch_losses.append(loss)\n        if len(batch_losses) > 0:\n            self.stats['Losses/Cloning Loss'].append(np.mean(batch_losses))\n        else:\n            self.stats['Losses/Cloning Loss'].append(0)",
    "docstring": "Updates the policy."
  },
  {
    "code": "def getattribute(model, item):\n    elements = item.split('.')\n    element = elements.pop(0)\n    try:\n        attr = getattr(model, element, None)\n    except:\n        return\n    if attr is None:\n        return\n    if callable(attr):\n        try:\n            attr = attr()\n        except:\n            return\n    if elements:\n        return getattribute(attr, '.'.join(elements))\n    return attr",
    "docstring": "Chained lookup of item on model\n\n    If item has dots (eg: 'foo.bar.baz'), recursively call getattribute():\n    e = getattr(model, 'foo')\n    e = getattr(e, 'bar')\n    e = getattr(e, 'baz')\n    At each step, check if e is a callable, and if so, use e()"
  },
  {
    "code": "def from_int(i):\n        point = ECPointAffine.from_int(bitcoin_curve, i)\n        return PublicKey.from_point(point)",
    "docstring": "Generates a public key object from an integer.\n\n        Note:\n            This assumes that the upper 32 bytes of the integer\n            are the x component of the public key point and the\n            lower 32 bytes are the y component.\n\n        Args:\n            i (Bignum): A 512-bit integer representing the public\n               key point on the secp256k1 curve.\n\n        Returns:\n            PublicKey: A PublicKey object."
  },
  {
    "code": "def get_request_token(self, request):\n        if self.oauth == 'oauth1':\n            oauth = OAuth1Session(self.consumer_key, client_secret=self.consumer_secret)\n            request_token = oauth.fetch_request_token(self.REQ_TOKEN)\n            request.session['oauth_token'] = request_token['oauth_token']\n            request.session['oauth_token_secret'] = request_token['oauth_token_secret']\n            return request_token\n        else:\n            callback_url = self.callback_url(request)\n            oauth = OAuth2Session(client_id=self.consumer_key, redirect_uri=callback_url, scope=self.scope)\n            authorization_url, state = oauth.authorization_url(self.AUTH_URL)\n            return authorization_url",
    "docstring": "request the token to the external service"
  },
  {
    "code": "def fw_update(self, data, fw_name=None):\n        LOG.debug(\"FW Update %s\", data)\n        self._fw_update(fw_name, data)",
    "docstring": "Top level FW update function."
  },
  {
    "code": "def bind(self, sock):\n        if self.context is None:\n            self.context = self.get_context()\n        conn = SSLConnection(self.context, sock)\n        self._environ = self.get_environ()\n        return conn",
    "docstring": "Wrap and return the given socket."
  },
  {
    "code": "def lock(self, lease_time=-1):\n        return self._encode_invoke(lock_lock_codec, invocation_timeout=MAX_SIZE, lease_time=to_millis(lease_time),\n                                   thread_id=thread_id(), reference_id=self.reference_id_generator.get_and_increment())",
    "docstring": "Acquires the lock. If a lease time is specified, lock will be released after this lease time.\n\n        If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies\n        dormant until the lock has been acquired.\n\n        :param lease_time: (long), time to wait before releasing the lock (optional)."
  },
  {
    "code": "def matchSubset(**kwargs):\n        ret = []\n        for m in self.matches:\n            allMatched = True\n            for k,v in iteritems(kwargs):\n                mVal = getattr(m, k)\n                try:\n                    if v == mVal or v in mVal: continue\n                except Exception: pass\n                allMatched = False\n                break\n            if allMatched: ret.append(m)\n        return ret",
    "docstring": "extract matches from player's entire match history given matching criteria kwargs"
  },
  {
    "code": "def get_environment(default=DEVELOPMENT, detectors=None, detectors_opts=None, use_envfiles=True):\n    detectors_opts = detectors_opts or {}\n    if detectors is None:\n        detectors = DETECTORS.keys()\n    env = None\n    for detector in detectors:\n        opts = detectors_opts.get(detector, {})\n        detector = get_detector(detector)\n        detector = detector(**opts)\n        env_name = detector.probe()\n        if env_name:\n            env = get_type(env_name)\n            break\n    if env is None and default is not None:\n        env = get_type(default)\n    if env is not None:\n        env = env()\n        use_envfiles and env.update_from_envfiles()\n    return env",
    "docstring": "Returns current environment type object.\n\n    :param str|Environment|None default: Default environment type or alias.\n\n    :param list[Detector] detectors: List of environment detectors to be used in chain.\n        If not set, default builtin chain is used.\n\n    :param dict detectors_opts: Detectors options dictionary.\n        Where keys are detector names and values are keyword arguments dicts.\n\n    :param bool use_envfiles: Whether to set environment variables (if not already set)\n        using data from .env files.\n\n    :rtype: Environment|None"
  },
  {
    "code": "def _file_name(fname, base_dir):\n        fname = fname.replace(\"\\\\\", \"\\\\\\\\\")\n        if base_dir != '' and fname[0] != ':' and not os.path.isabs(fname):\n            fname = os.path.join(base_dir, fname)\n        return fname",
    "docstring": "Convert a relative filename if we have a base directory."
  },
  {
    "code": "def check_variable_features(self, ds):\n        ret_val = []\n        feature_list = ['point', 'timeSeries', 'trajectory', 'profile', 'timeSeriesProfile', 'trajectoryProfile']\n        feature_type = getattr(ds, 'featureType', None)\n        if feature_type not in feature_list:\n            return []\n        feature_type_map = {\n            'point': [\n                'point'\n            ],\n            'timeSeries': [\n                'timeseries',\n                'multi-timeseries-orthogonal',\n                'multi-timeseries-incomplete',\n            ],\n            'trajectory': [\n                'cf-trajectory',\n                'single-trajectory',\n            ],\n            'profile': [\n                'profile-orthogonal',\n                'profile-incomplete'\n            ],\n            'timeSeriesProfile': [\n                'timeseries-profile-single-station',\n                'timeseries-profile-multi-station',\n                'timeseries-profile-single-ortho-time',\n                'timeseries-profile-multi-ortho-time',\n                'timeseries-profile-ortho-depth',\n                'timeseries-profile-incomplete'\n            ],\n            'trajectoryProfile': [\n                'trajectory-profile-orthogonal',\n                'trajectory-profile-incomplete'\n            ]\n        }\n        for name in self._find_geophysical_vars(ds):\n            variable_feature = cfutil.guess_feature_type(ds, name)\n            if variable_feature is None:\n                continue\n            matching_feature = TestCtx(BaseCheck.MEDIUM,\n                                       self.section_titles['9.1'])\n            matching_feature.assert_true(variable_feature in feature_type_map[feature_type],\n                                         '{} is not a {}, it is detected as a {}'\n                                         ''.format(name, feature_type, variable_feature))\n            ret_val.append(matching_feature.to_result())\n        return ret_val",
    "docstring": "Checks the variable feature types match the dataset featureType attribute\n\n        :param netCDF4.Dataset ds: An open netCDF dataset\n        :rtype: list\n        :return: List of results"
  },
  {
    "code": "def pypi_link(pkg_filename):\n    root = 'https://files.pythonhosted.org/packages/source'\n    name, sep, rest = pkg_filename.partition('-')\n    parts = root, name[0], name, pkg_filename\n    return '/'.join(parts)",
    "docstring": "Given the filename, including md5 fragment, construct the\n    dependency link for PyPI."
  },
  {
    "code": "def show_active_only(self, state):\n        query = self._copy()\n        query.active_only = state\n        return query",
    "docstring": "Set active only to true or false on a copy of this query"
  },
  {
    "code": "def id_unique(dict_id, name, lineno):\n    if dict_id in name_dict:\n        global error_occurred\n        error_occurred = True\n        print(\n            \"ERROR - {0:s} definition {1:s} at line {2:d} conflicts with {3:s}\"\n            .format(name, dict_id, lineno, name_dict[dict_id]))\n        return False\n    else:\n        return True",
    "docstring": "Returns True if dict_id not already used.  Otherwise, invokes error"
  },
  {
    "code": "def find_by_title(self, title):\n        for entry in self.entries:\n            if entry.title == title:\n                return entry\n        raise EntryNotFoundError(\"Entry not found for title: %s\" % title)",
    "docstring": "Find an entry by exact title.\n\n        :raise: EntryNotFoundError"
  },
  {
    "code": "def join_dicts(dicts, delimiter=None, keep_all=False):\n    if not dicts:\n        return {}\n    if keep_all:\n        all_keys = set(chain(*(d.keys() for d in dicts)))\n    else:\n        all_keys = set(dicts[0])\n        for d in dicts[1:]:\n            all_keys.intersection_update(d)\n    ret = {}\n    for key in all_keys:\n        vals = {hashable(d.get(key, None)) for d in dicts} - {None}\n        if len(vals) == 1:\n            ret[key] = next(iter(vals))\n        elif delimiter is None:\n            ret[key] = vals\n        else:\n            ret[key] = delimiter.join(map(str, vals))\n    return ret",
    "docstring": "Join multiple dictionaries into one\n\n    Parameters\n    ----------\n    dicts: list of dict\n        A list of dictionaries\n    delimiter: str\n        The string that shall be used as the delimiter in case that there\n        are multiple values for one attribute in the arrays. If None, they\n        will be returned as sets\n    keep_all: bool\n        If True, all formatoptions are kept. Otherwise only the intersection\n\n    Returns\n    -------\n    dict\n        The combined dictionary"
  },
  {
    "code": "def solve_sparse(self, B):\n        B = B.tocsc()\n        cols = list()\n        for j in xrange(B.shape[1]):\n            col = self.solve(B[:,j])\n            cols.append(csc_matrix(col))\n        return hstack(cols)",
    "docstring": "Solve linear equation of the form A X = B. Where B and X are sparse matrices.\n\n        Parameters\n        ----------\n        B : any scipy.sparse matrix\n            Right-hand side of the matrix equation.\n            Note: it will be converted to csc_matrix via `.tocsc()`.\n\n        Returns\n        -------\n        X : csc_matrix\n            Solution to the matrix equation as a csc_matrix"
  },
  {
    "code": "def clear_deadline(self):\n        if (self.get_deadline_metadata().is_read_only() or\n                self.get_deadline_metadata().is_required()):\n            raise errors.NoAccess()\n        self._my_map['deadline'] = self._deadline_default",
    "docstring": "Clears the deadline.\n\n        raise:  NoAccess - ``Metadata.isRequired()`` or\n                ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def add_association_to_graph(self):\n        Assoc.add_association_to_graph(self)\n        if self.onset is not None and self.onset != '':\n            self.graph.addTriple(self.assoc_id, self.globaltt['onset'], self.onset)\n        if self.frequency is not None and self.frequency != '':\n            self.graph.addTriple(\n                self.assoc_id, self.globaltt['frequency'], self.frequency)\n        return",
    "docstring": "The reified relationship between a disease and a phenotype is decorated\n        with some provenance information.\n        This makes the assumption that both the disease and phenotype\n        are classes.\n\n        :param g:\n\n        :return:"
  },
  {
    "code": "def combine_elem(ind1, ind2):\n    def inner(seq):\n        shift = 2**16\n        if seq[ind1] < 0:\n            seq[ind1] += shift\n        if seq[ind2] < 0:\n            seq[ind2] += shift\n        return (seq[ind1] << 16) | seq[ind2]\n    return inner",
    "docstring": "Create a function to combine two specified product-specific blocks into a single int."
  },
  {
    "code": "def soundexCode(self, char):\n        lang = get_language(char)\n        try:\n            if lang == \"en_US\":\n                return _soundex_map[\"soundex_en\"][charmap[lang].index(char)]\n            else:\n                return _soundex_map[\"soundex\"][charmap[lang].index(char)]\n        except:\n            pass\n        return 0",
    "docstring": "Return the soundex code for given character\n\n           :param char:\n               Character whose soundex code is needed\n           :return:\n               Returns soundex code if character is found in charmap\n               else returns 0"
  },
  {
    "code": "def delete(self, url):\n        logger.debug('Making DELETE request to %s', url)\n        return self.oauth_session.delete(url)",
    "docstring": "Make a HTTP DELETE request to the Readability API.\n\n        :param url: The url to which to send a DELETE request."
  },
  {
    "code": "def mutagen_call(action, path, func, *args, **kwargs):\n    try:\n        return func(*args, **kwargs)\n    except mutagen.MutagenError as exc:\n        log.debug(u'%s failed: %s', action, six.text_type(exc))\n        raise UnreadableFileError(path, six.text_type(exc))\n    except Exception as exc:\n        log.debug(u'%s', traceback.format_exc())\n        log.error(u'uncaught Mutagen exception in %s: %s', action, exc)\n        raise MutagenError(path, exc)",
    "docstring": "Call a Mutagen function with appropriate error handling.\n\n    `action` is a string describing what the function is trying to do,\n    and `path` is the relevant filename. The rest of the arguments\n    describe the callable to invoke.\n\n    We require at least Mutagen 1.33, where `IOError` is *never* used,\n    neither for internal parsing errors *nor* for ordinary IO error\n    conditions such as a bad filename. Mutagen-specific parsing errors and IO\n    errors are reraised as `UnreadableFileError`. Other exceptions\n    raised inside Mutagen---i.e., bugs---are reraised as `MutagenError`."
  },
  {
    "code": "def get_ccle_cna(gene_list, cell_lines):\n    profile_data = get_profile_data(ccle_study, gene_list,\n                                    'COPY_NUMBER_ALTERATION', 'all')\n    profile_data = dict((key, value) for key, value in profile_data.items()\n                        if key in cell_lines)\n    return profile_data",
    "docstring": "Return a dict of CNAs in given genes and cell lines from CCLE.\n\n    CNA values correspond to the following alterations\n\n    -2 = homozygous deletion\n\n    -1 = hemizygous deletion\n\n    0 = neutral / no change\n\n    1 = gain\n\n    2 = high level amplification\n\n    Parameters\n    ----------\n    gene_list : list[str]\n        A list of HGNC gene symbols to get mutations in\n    cell_lines : list[str]\n        A list of CCLE cell line names to get mutations for.\n\n    Returns\n    -------\n    profile_data : dict[dict[int]]\n        A dict keyed to cases containing a dict keyed to genes\n        containing int"
  },
  {
    "code": "def html(self):\n        if self.description:\n            tooltip = 'tooltip=\"{}\"'.format(self.description)\n        else:\n            tooltip = ''\n        return entry_html(\n            title=self.title,\n            thumbnail=self.thumbnail,\n            link=self.html_link,\n            tooltip=tooltip)",
    "docstring": "Return html for a the entry"
  },
  {
    "code": "def get_upstream(self, type_):\n        if isinstance(self, type_):\n            return self\n        elif self.upstream and isinstance(self.upstream, type_):\n            return self.upstream\n        elif self.upstream:\n            return self.upstream.get_upstream(type_)\n        else:\n            return None",
    "docstring": "Return self, or an upstream, that has the given class type.\n        This is typically used to find upstream s that impoement the RemoteInterface"
  },
  {
    "code": "def date_decoder(dic):\n    if '__date__' in dic:\n        try:\n            d = datetime.date(**{c: v for c, v in dic.items() if not c == \"__date__\"})\n        except (TypeError, ValueError):\n            raise json.JSONDecodeError(\"Corrupted date format !\", str(dic), 1)\n    elif '__datetime__' in dic:\n        try:\n            d = datetime.datetime(**{c: v for c, v in dic.items() if not c == \"__datetime__\"})\n        except (TypeError, ValueError):\n            raise json.JSONDecodeError(\"Corrupted datetime format !\", str(dic), 1)\n    else:\n        return dic\n    return d",
    "docstring": "Add python types decoding. See JsonEncoder"
  },
  {
    "code": "def unit(self):\n        unit = ncVarUnit(self._ncVar)\n        fieldNames = self._ncVar.dtype.names\n        if hasattr(unit, '__len__') and len(unit) == len(fieldNames):\n            idx = fieldNames.index(self.nodeName)\n            return unit[idx]\n        else:\n            return unit",
    "docstring": "Returns the unit attribute of the underlying ncdf variable.\n\n            If the units has a length (e.g is a list) and has precisely one element per field,\n            the unit for this field is returned."
  },
  {
    "code": "def extract_journal_reference(line, override_kbs_files=None):\n    kbs = get_kbs(custom_kbs_files=override_kbs_files)\n    references, dummy_m, dummy_c, dummy_co = parse_reference_line(line, kbs)\n    for elements in references:\n        for el in elements:\n            if el['type'] == 'JOURNAL':\n                return el",
    "docstring": "Extract the journal reference from string.\n\n    Extracts the journal reference from string and parses for specific\n    journal information."
  },
  {
    "code": "def get_prime(bits, k=64):\n    if bits % 8 != 0 or bits == 0:\n        raise ValueError(\"bits must be >= 0 and divisible by 8\")\n    while True:\n        n = int.from_bytes(os.urandom(bits // 8), \"big\")\n        if is_prime(n, k):\n            return n",
    "docstring": "Return a random prime up to a certain length.\n\n    This function uses random.SystemRandom."
  },
  {
    "code": "def parse_response(service, response, search_type):\n    _LOG.debug('Parse response \"%s\" from service \"%s\" of type \"%s\"', response,\n               service, search_type)\n    items = []\n    if 'searchResult' in response:\n        response = response['searchResult']\n    elif 'getMetadataResult' in response:\n        response = response['getMetadataResult']\n    else:\n        raise ValueError('\"response\" should contain either the key '\n                         '\"searchResult\" or \"getMetadataResult\"')\n    search_metadata = {\n        'number_returned': response['count'],\n        'total_matches': None,\n        'search_type': search_type,\n        'update_id': None,\n    }\n    for result_type in ('mediaCollection', 'mediaMetadata'):\n        result_type_proper = result_type[0].upper() + result_type[1:]\n        raw_items = response.get(result_type, [])\n        if isinstance(raw_items, OrderedDict):\n            raw_items = [raw_items]\n        for raw_item in raw_items:\n            class_key = result_type_proper + raw_item['itemType'].title()\n            cls = get_class(class_key)\n            items.append(cls.from_music_service(service, raw_item))\n    return SearchResult(items, **search_metadata)",
    "docstring": "Parse the response to a music service query and return a SearchResult\n\n    Args:\n        service (MusicService): The music service that produced the response\n        response (OrderedDict): The response from the soap client call\n        search_type (str): A string that indicates the search type that the\n            response is from\n\n    Returns:\n        SearchResult: A SearchResult object"
  },
  {
    "code": "def poke(self, session, address, width, data):\n        if width == 8:\n            return self.poke_8(session, address, data)\n        elif width == 16:\n            return self.poke_16(session, address, data)\n        elif width == 32:\n            return self.poke_32(session, address, data)\n        elif width == 64:\n            return self.poke_64(session, address, data)\n        raise ValueError('%s is not a valid size. Valid values are 8, 16, 32, or 64' % width)",
    "docstring": "Writes an 8, 16, 32, or 64-bit value from the specified address.\n\n        Corresponds to viPoke* functions of the VISA library.\n\n        :param session: Unique logical identifier to a session.\n        :param address: Source address to read the value.\n        :param width: Number of bits to read.\n        :param data: Data to be written to the bus.\n        :return: return value of the library call.\n        :rtype: :class:`pyvisa.constants.StatusCode`"
  },
  {
    "code": "def close_window(self):\n        if self.undocked_window is not None:\n            self.undocked_window.close()\n            self.undocked_window = None\n            self.undock_action.setDisabled(False)\n            self.close_plugin_action.setDisabled(False)",
    "docstring": "Close QMainWindow instance that contains this plugin."
  },
  {
    "code": "def linkify_s_by_module(self, modules):\n        for i in self:\n            links_list = strip_and_uniq(i.modules)\n            new = []\n            for name in [e for e in links_list if e]:\n                module = modules.find_by_name(name)\n                if module is not None and module.uuid not in new:\n                    new.append(module)\n                else:\n                    i.add_error(\"Error: the module %s is unknown for %s\" % (name, i.get_name()))\n            i.modules = new",
    "docstring": "Link modules to items\n\n        :param modules: Modules object (list of all the modules found in the configuration)\n        :type modules: alignak.objects.module.Modules\n        :return: None"
  },
  {
    "code": "def remove_modifier(self, index, m_type=XenaModifierType.standard):\n        if m_type == XenaModifierType.standard:\n            current_modifiers = OrderedDict(self.modifiers)\n            del current_modifiers[index]\n            self.set_attributes(ps_modifiercount=0)\n            self.del_objects_by_type('modifier')\n        else:\n            current_modifiers = OrderedDict(self.xmodifiers)\n            del current_modifiers[index]\n            self.set_attributes(ps_modifierextcount=0)\n            self.del_objects_by_type('xmodifier')\n        for modifier in current_modifiers.values():\n            self.add_modifier(m_type,\n                              mask=modifier.mask, action=modifier.action, repeat=modifier.repeat,\n                              min_val=modifier.min_val, step=modifier.step, max_val=modifier.max_val)",
    "docstring": "Remove modifier.\n\n        :param m_type: modifier type - standard or extended.\n        :param index: index of modifier to remove."
  },
  {
    "code": "def create_CAG_with_indicators(input, output, filename=\"CAG_with_indicators.pdf\"):\n    with open(input, \"rb\") as f:\n        G = pickle.load(f)\n    G.map_concepts_to_indicators(min_temporal_res=\"month\")\n    G.set_indicator(\"UN/events/weather/precipitation\", \"Historical Average Total Daily Rainfall (Maize)\", \"DSSAT\")\n    G.set_indicator(\"UN/events/human/agriculture/food_production\",\n            \"Historical Production (Maize)\", \"DSSAT\")\n    G.set_indicator(\"UN/entities/human/food/food_security\", \"IPC Phase Classification\", \"FEWSNET\")\n    G.set_indicator(\"UN/entities/food_availability\", \"Production, Meat indigenous, total\", \"FAO\")\n    G.set_indicator(\"UN/entities/human/financial/economic/market\", \"Inflation Rate\", \"ieconomics.com\")\n    G.set_indicator(\"UN/events/human/death\", \"Battle-related deaths\", \"WDI\")\n    with open(output, \"wb\") as f:\n        pickle.dump(G, f)",
    "docstring": "Create a CAG with mapped indicators"
  },
  {
    "code": "def merge(self, other):\n        if not isinstance(other, MetadataRb):\n            raise TypeError(\"MetadataRb to merge should be a 'MetadataRb' \"\n                            \"instance, not %s.\", type(other))\n        current = self.to_dict()\n        new = other.to_dict()\n        meta_writelines = ['%s\\n' % self.depends_statement(cbn, meta)\n                           for cbn, meta in new.get('depends', {}).items()\n                           if cbn not in current.get('depends', {})]\n        self.write_statements(meta_writelines)\n        return self.to_dict()",
    "docstring": "Add requirements from 'other' metadata.rb into this one."
  },
  {
    "code": "def destroy_label(self, label, callback=dummy_progress_cb):\n        current = 0\n        total = self.index.get_nb_docs()\n        self.index.start_destroy_label(label)\n        while True:\n            (op, doc) = self.index.continue_destroy_label()\n            if op == 'end':\n                break\n            callback(current, total, self.LABEL_STEP_DESTROYING, doc)\n            current += 1\n        self.index.end_destroy_label()",
    "docstring": "Remove the label 'label' from all the documents. Takes care of updating\n        the index."
  },
  {
    "code": "def type_inherits_of_type(inheriting_type, base_type):\n    assert isinstance(inheriting_type, type) or isclass(inheriting_type)\n    assert isinstance(base_type, type) or isclass(base_type)\n    if inheriting_type == base_type:\n        return True\n    else:\n        if len(inheriting_type.__bases__) != 1:\n            return False\n        return type_inherits_of_type(inheriting_type.__bases__[0], base_type)",
    "docstring": "Checks whether inheriting_type inherits from base_type\n\n    :param str inheriting_type:\n    :param str base_type:\n    :return: True is base_type is base of inheriting_type"
  },
  {
    "code": "def add(self, host_value):\n        host_obj = self._host_factory(host_value)\n        if self._get_match(host_obj) is not None:\n            return\n        self._add_new(host_obj)",
    "docstring": "Add the given value to the collection.\n\n        :param host: an ip address or a hostname\n        :raises InvalidHostError: raised when the given value\n        is not a valid ip address nor a hostname"
  },
  {
    "code": "def add_item(self, item, field_name=None):\n        field_name = self._choose_field_name(field_name)\n        related_manager = getattr(item, field_name)\n        related_manager.add(self)",
    "docstring": "Add the item to the specified section.\n\n        Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL.\n        Behavior on other items is undefined."
  },
  {
    "code": "def fetchGroupInfo(self, *group_ids):\n        threads = self.fetchThreadInfo(*group_ids)\n        groups = {}\n        for id_, thread in threads.items():\n            if thread.type == ThreadType.GROUP:\n                groups[id_] = thread\n            else:\n                raise FBchatUserError(\"Thread {} was not a group\".format(thread))\n        return groups",
    "docstring": "Get groups' info from IDs, unordered\n\n        :param group_ids: One or more group ID(s) to query\n        :return: :class:`models.Group` objects, labeled by their ID\n        :rtype: dict\n        :raises: FBchatException if request failed"
  },
  {
    "code": "def setting(self, opt, val):\n        opt = opt.encode()\n        if isinstance(val, basestring):\n            fluid_settings_setstr(self.settings, opt, val)\n        elif isinstance(val, int):\n            fluid_settings_setint(self.settings, opt, val)\n        elif isinstance(val, float):\n            fluid_settings_setnum(self.settings, opt, val)",
    "docstring": "change an arbitrary synth setting, type-smart"
  },
  {
    "code": "def _encode_batched_op_msg(\n        operation, command, docs, check_keys, ack, opts, ctx):\n    buf = StringIO()\n    to_send, _ = _batched_op_msg_impl(\n        operation, command, docs, check_keys, ack, opts, ctx, buf)\n    return buf.getvalue(), to_send",
    "docstring": "Encode the next batched insert, update, or delete operation\n    as OP_MSG."
  },
  {
    "code": "def ifaces(cls, name):\n        ifaces = Iface.list({'vlan_id': cls.usable_id(name)})\n        ret = []\n        for iface in ifaces:\n            ret.append(Iface.info(iface['id']))\n        return ret",
    "docstring": "Get vlan attached ifaces."
  },
  {
    "code": "def use_comparative_catalog_view(self):\n        self._catalog_view = COMPARATIVE\n        for session in self._get_provider_sessions():\n            try:\n                session.use_comparative_catalog_view()\n            except AttributeError:\n                pass",
    "docstring": "Pass through to provider CatalogLookupSession.use_comparative_catalog_view"
  },
  {
    "code": "def tags(self, resource_id=None):\n        resource = self.copy()\n        resource._request_entity = 'tag'\n        resource._request_uri = '{}/tags'.format(resource._request_uri)\n        if resource_id is not None:\n            resource._request_uri = '{}/{}'.format(\n                resource._request_uri, self.tcex.safetag(resource_id)\n            )\n        return resource",
    "docstring": "Tag endpoint for this resource with optional tag name.\n\n        This method will set the resource endpoint for working with Tags. The\n        HTTP GET method will return all tags applied to this resource or if a\n        resource id (tag name) is provided it will return the provided tag if\n        it has been applied, which could be useful to verify a tag is applied.\n        The provided resource_id (tag) can be applied to this resource using\n        the HTTP POST method.  The HTTP DELETE method will remove the provided\n        tag from this resource.\n\n        **Example Endpoints URI's**\n\n        +--------------+------------------------------------------------------------+\n        | HTTP Method  | API Endpoint URI's                                         |\n        +==============+============================================================+\n        | GET          | /v2/groups/{resourceType}/{uniqueId}/tags                  |\n        +--------------+------------------------------------------------------------+\n        | GET          | /v2/groups/{resourceType}/{uniqueId}/tags/{resourceId}     |\n        +--------------+------------------------------------------------------------+\n        | GET          | /v2/indicators/{resourceType}/{uniqueId}/tags              |\n        +--------------+------------------------------------------------------------+\n        | GET          | /v2/indicators/{resourceType}/{uniqueId}/tags/{resourceId} |\n        +--------------+------------------------------------------------------------+\n        | DELETE       | /v2/groups/{resourceType}/{uniqueId}/tags/{resourceId}     |\n        +--------------+------------------------------------------------------------+\n        | DELETE       | /v2/indicators/{resourceType}/{uniqueId}/tags/{resourceId} |\n        +--------------+------------------------------------------------------------+\n        | POST         | /v2/groups/{resourceType}/{uniqueId}/tags/{resourceId}     |\n        +--------------+------------------------------------------------------------+\n        | POST         | /v2/indicators/{resourceType}/{uniqueId}/tags/{resourceId} |\n        +--------------+------------------------------------------------------------+\n\n        Args:\n            resource_id (Optional [string]): The resource id (tag name)."
  },
  {
    "code": "def folding_model_gradient(rvec, rcut):\n    r\n    rnorm = np.linalg.norm(rvec)\n    if rnorm == 0.0:\n        return np.zeros(rvec.shape)\n    r = rnorm - rcut\n    if r < 0.0:\n        return -5.0 * r * rvec / rnorm\n    return (1.5 * r - 2.0) * rvec / rnorm",
    "docstring": "r\"\"\"computes the potential's gradient at point rvec"
  },
  {
    "code": "def get_name_DID_info(self, name):\n        db = get_db_state(self.working_dir)\n        did_info = db.get_name_DID_info(name)\n        if did_info is None:\n            return {'error': 'No such name', 'http_status': 404}\n        return did_info",
    "docstring": "Get a name's DID info\n        Returns None if not found"
  },
  {
    "code": "def astype(self, dtype):\n        if dtype not in _supported_dtypes:\n            raise ValueError('Datatype %s not supported. Supported types are %s' % (dtype, _supported_dtypes))\n        pixeltype = _npy_to_itk_map[dtype]\n        return self.clone(pixeltype)",
    "docstring": "Cast & clone an ANTsImage to a given numpy datatype.\n\n        Map:\n            uint8   : unsigned char\n            uint32  : unsigned int\n            float32 : float\n            float64 : double"
  },
  {
    "code": "def execute_java_for_coverage(self, targets, *args, **kwargs):\n    distribution = self.preferred_jvm_distribution_for_targets(targets)\n    actual_executor = SubprocessExecutor(distribution)\n    return distribution.execute_java(*args, executor=actual_executor, **kwargs)",
    "docstring": "Execute java for targets directly and don't use the test mixin.\n\n    This execution won't be wrapped with timeouts and other test mixin code common\n    across test targets. Used for coverage instrumentation."
  },
  {
    "code": "def _readSentence(self):\n        reply_word, words = self.protocol.readSentence()\n        words = dict(parseWord(word) for word in words)\n        return reply_word, words",
    "docstring": "Read one sentence and parse words.\n\n        :returns: Reply word, dict with attribute words."
  },
  {
    "code": "def _sendMsg(self, type, msg):\n        if self.ALERT_STATUS and type in self.ALERT_TYPES:\n            self._configMailer()\n            self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg)",
    "docstring": "Send Alert Message To Emails"
  },
  {
    "code": "def listen(self):\n        while self._listen:\n            key = u''\n            key = self.term.inkey(timeout=0.2)\n            try:\n                if key.code == KEY_ENTER:\n                    self.on_enter(key=key)\n                elif key.code in (KEY_DOWN, KEY_UP):\n                    self.on_key_arrow(key=key)\n                elif key.code == KEY_ESCAPE or key == chr(3):\n                    self.on_exit(key=key)\n                elif key != '':\n                    self.on_key(key=key)\n            except KeyboardInterrupt:\n                self.on_exit(key=key)",
    "docstring": "Blocking call on widgets."
  },
  {
    "code": "def every_match(self, callback, **kwargs):\n        if len(kwargs) == 0:\n            raise ArgumentError(\"You must specify at least one message field to wait on\")\n        spec = MessageSpec(**kwargs)\n        responder = self._add_waiter(spec, callback)\n        return (spec, responder)",
    "docstring": "Invoke callback every time a matching message is received.\n\n        The callback will be invoked directly inside process_message so that\n        you can guarantee that it has been called by the time process_message\n        has returned.\n\n        The callback can be removed by a call to remove_waiter(), passing the\n        handle object returned by this call to identify it.\n\n        Args:\n            callback (callable): A callable function that will be called as\n                callback(message) whenever a matching message is received.\n\n        Returns:\n            object: An opaque handle that can be passed to remove_waiter().\n\n            This handle is the only way to remove this callback if you no\n            longer want it to be called."
  },
  {
    "code": "def end_poll(args):\n    if not args.isadmin:\n        return \"Nope, not gonna do it.\"\n    if not args.msg:\n        return \"Syntax: !vote end <pollnum>\"\n    if not args.msg.isdigit():\n        return \"Not A Valid Positive Integer.\"\n    poll = get_open_poll(args.session, int(args.msg))\n    if poll is None:\n        return \"That poll doesn't exist or has already been deleted!\"\n    if poll.active == 0:\n        return \"Poll already ended!\"\n    poll.active = 0\n    return \"Poll ended!\"",
    "docstring": "Ends a poll."
  },
  {
    "code": "def _update(self, uri, body, **kwargs):\n        self.run_hooks(\"modify_body_for_update\", body, **kwargs)\n        resp, resp_body = self.api.method_put(uri, body=body)\n        return resp_body",
    "docstring": "Handles the communication with the API when updating\n        a specific resource managed by this class."
  },
  {
    "code": "def get_release_id(self, package_name: str, version: str) -> bytes:\n        validate_package_name(package_name)\n        validate_package_version(version)\n        self._validate_set_registry()\n        return self.registry._get_release_id(package_name, version)",
    "docstring": "Returns the 32 byte identifier of a release for the given package name and version,\n        if they are available on the current registry."
  },
  {
    "code": "def collect_ip6table(self, tablename):\n        modname = \"ip6table_\"+tablename\n        if self.check_ext_prog(\"grep -q %s /proc/modules\" % modname):\n            cmd = \"ip6tables -t \"+tablename+\" -nvL\"\n            self.add_cmd_output(cmd)",
    "docstring": "Same as function above, but for ipv6"
  },
  {
    "code": "def validate_known_curve():\n    plt.figure()\n    N = 100\n    x = numpy.linspace(-1, 1, N)\n    y = numpy.sin(4 * x)\n    smoother.DEFAULT_BASIC_SMOOTHER = smoother.BasicFixedSpanSmootherSlowUpdate\n    smooth = smoother.perform_smooth(x, y, smoother_cls=supersmoother.SuperSmoother)\n    plt.plot(x, smooth.smooth_result, label='Slow')\n    smoother.DEFAULT_BASIC_SMOOTHER = smoother.BasicFixedSpanSmoother\n    smooth = smoother.perform_smooth(x, y, smoother_cls=supersmoother.SuperSmoother)\n    plt.plot(x, smooth.smooth_result, label='Fast')\n    plt.plot(x, y, '.', label='data')\n    plt.legend()\n    plt.show()",
    "docstring": "Validate on a sin function."
  },
  {
    "code": "def _micro_service_filter(cls):\n    is_microservice_module = issubclass(cls, MicroService)\n    is_correct_subclass = cls != MicroService and cls != ResponseMicroService and cls != RequestMicroService\n    return is_microservice_module and is_correct_subclass",
    "docstring": "Will only give a find on classes that is a subclass of MicroService, with the exception that\n    the class is not allowed to be a direct ResponseMicroService or RequestMicroService.\n\n    :type cls: type\n    :rtype: bool\n\n    :param cls: A class object\n    :return: True if match, else false"
  },
  {
    "code": "def infos(self, type=None, failed=False):\n        if type is None:\n            type = Info\n        if not issubclass(type, Info):\n            raise TypeError(\n                \"Cannot get infos of type {} \" \"as it is not a valid type.\".format(type)\n            )\n        if failed not in [\"all\", False, True]:\n            raise ValueError(\"{} is not a valid vector failed\".format(failed))\n        if failed == \"all\":\n            return type.query.filter_by(origin_id=self.id).all()\n        else:\n            return type.query.filter_by(origin_id=self.id, failed=failed).all()",
    "docstring": "Get infos that originate from this node.\n\n        Type must be a subclass of :class:`~dallinger.models.Info`, the default is\n        ``Info``. Failed can be True, False or \"all\"."
  },
  {
    "code": "def with_lock(lock, func, *args, **kwargs):\n    d = lock.acquire()\n    def release_lock(result):\n        deferred = lock.release()\n        return deferred.addCallback(lambda x: result)\n    def lock_acquired(lock):\n        return defer.maybeDeferred(func, *args, **kwargs).addBoth(release_lock)\n    d.addCallback(lock_acquired)\n    return d",
    "docstring": "A 'context manager' for performing operations requiring a lock.\n\n    :param lock: A BasicLock instance\n    :type lock: silverberg.lock.BasicLock\n\n    :param func: A callable to execute while the lock is held.\n    :type func: function"
  },
  {
    "code": "def _convert_char_to_type(self, type_char):\n        typecode = type_char\n        if type(type_char) is int:\n            typecode = chr(type_char)\n        if typecode in self.TYPECODES_LIST:\n            return typecode\n        else:\n            raise RuntimeError(\n                \"Typecode {0} ({1}) isn't supported.\".format(type_char, typecode)\n            )",
    "docstring": "Ensures a read character is a typecode.\n\n        :param type_char: Read typecode\n        :return: The typecode as a string (using chr)\n        :raise RuntimeError: Unknown typecode"
  },
  {
    "code": "def bitlist_to_int(bitlist: Sequence[int]) -> int:\n    return int(''.join([str(d) for d in bitlist]), 2)",
    "docstring": "Converts a sequence of bits to an integer.\n\n    >>> from quantumflow.utils import bitlist_to_int\n    >>> bitlist_to_int([1, 0, 0])\n    4"
  },
  {
    "code": "def get_game_id(self, date):\n        df = self.get_game_logs()\n        game_id = df[df.GAME_DATE == date].Game_ID.values[0]\n        return game_id",
    "docstring": "Returns the Game ID associated with the date that is passed in.\n\n        Parameters\n        ----------\n        date : str\n            The date associated with the game whose Game ID. The date that is\n            passed in can take on a numeric format of MM/DD/YY (like \"01/06/16\"\n            or \"01/06/2016\") or the expanded Month Day, Year format (like\n            \"Jan 06, 2016\" or \"January 06, 2016\").\n\n        Returns\n        -------\n        game_id : str\n            The desired Game ID."
  },
  {
    "code": "def phisheye_term_list(self, include_inactive=False, **kwargs):\n        return self._results('phisheye_term_list', '/v1/phisheye/term-list', include_inactive=include_inactive,\n                             items_path=('terms', ), **kwargs)",
    "docstring": "Provides a list of terms that are set up for this account.\n           This call is not charged against your API usage limit.\n\n           NOTE: The terms must be configured in the PhishEye web interface: https://research.domaintools.com/phisheye.\n                 There is no API call to set up the terms."
  },
  {
    "code": "def store_extra_keys(self, d: Dict[str, Any]) -> None:\n        new_dict = dict(self.extra_keys, **d)\n        self.extra_keys = new_dict.copy()",
    "docstring": "Store several extra values in the messaging storage.\n\n        :param d: dictionary entry to merge with current self.extra_keys.\n        :returns: None"
  },
  {
    "code": "def get_edge(self, src_or_list, dst=None):\n        if isinstance( src_or_list, (list, tuple)) and dst is None:\n            edge_points = tuple(src_or_list)\n            edge_points_reverse = (edge_points[1], edge_points[0])\n        else:\n            edge_points = (src_or_list, dst)\n            edge_points_reverse = (dst, src_or_list)\n        match = list()\n        if edge_points in self.obj_dict['edges'] or (\n            self.get_top_graph_type() == 'graph' and\n            edge_points_reverse in self.obj_dict['edges']):\n            edges_obj_dict = self.obj_dict['edges'].get(\n                edge_points,\n                self.obj_dict['edges'].get( edge_points_reverse, None ))\n            for edge_obj_dict in edges_obj_dict:\n                match.append(\n                    Edge(edge_points[0],\n                         edge_points[1],\n                         obj_dict=edge_obj_dict))\n        return match",
    "docstring": "Retrieved an edge from the graph.\n\n        Given an edge's source and destination the corresponding\n        Edge instance(s) will be returned.\n\n        If one or more edges exist with that source and destination\n        a list of Edge instances is returned.\n        An empty list is returned otherwise."
  },
  {
    "code": "def print_search_results(self, search_results, buf=sys.stdout):\n        formatted_lines = self.format_search_results(search_results)\n        pr = Printer(buf)\n        for txt, style in formatted_lines:\n            pr(txt, style)",
    "docstring": "Print formatted search results.\n\n        Args:\n            search_results (list of `ResourceSearchResult`): Search to format."
  },
  {
    "code": "def backend_from_mime(mime):\n    try:\n        mod_name = MIMETYPE_TO_BACKENDS[mime]\n    except KeyError:\n        msg = \"No handler for %r, defaulting to %r\" % (mime, DEFAULT_MIME)\n        if 'FULLTEXT_TESTING' in os.environ:\n            warn(msg)\n        else:\n            LOGGER.debug(msg)\n        mod_name = MIMETYPE_TO_BACKENDS[DEFAULT_MIME]\n    mod = import_mod(mod_name)\n    return mod",
    "docstring": "Determine backend module object from a mime string."
  },
  {
    "code": "def _register_converter(cls, conv_func, conv_type):\n        cls.converters.append(ConverterFunctionInfo(conv_func, conv_type, len(cls.converters)))\n        cls._sort_converters()",
    "docstring": "Triggered by the @converter_function decorator"
  },
  {
    "code": "def get_dict(*keys, **extras):\n    _keys = ('url', 'args', 'form', 'data', 'origin', 'headers', 'files', 'json', 'method')\n    assert all(map(_keys.__contains__, keys))\n    data = request.data\n    form = semiflatten(request.form)\n    try:\n        _json = json.loads(data.decode('utf-8'))\n    except (ValueError, TypeError):\n        _json = None\n    d = dict(\n        url=get_url(request),\n        args=semiflatten(request.args),\n        form=form,\n        data=json_safe(data),\n        origin=request.headers.get('X-Forwarded-For', request.remote_addr),\n        headers=get_headers(),\n        files=get_files(),\n        json=_json,\n        method=request.method,\n    )\n    out_d = dict()\n    for key in keys:\n        out_d[key] = d.get(key)\n    out_d.update(extras)\n    return out_d",
    "docstring": "Returns request dict of given keys."
  },
  {
    "code": "def _reply_json(self, json_payload, status_code=200):\n        self._send_headers(status_code=status_code)\n        json_str = json.dumps(json_payload)\n        self.wfile.write(json_str)",
    "docstring": "Return a JSON-serializable data structure"
  },
  {
    "code": "def get_instance(self, payload):\n        return UserBindingInstance(\n            self._version,\n            payload,\n            service_sid=self._solution['service_sid'],\n            user_sid=self._solution['user_sid'],\n        )",
    "docstring": "Build an instance of UserBindingInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance\n        :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance"
  },
  {
    "code": "def get_authenticated_person(self):\n        try:\n            output = self._get_data()\n            self._logger.debug(output)\n            person = Person([\n                self.email,\n                output[9][1],\n                None,\n                None,\n                None,\n                None,\n                [\n                    None,\n                    None,\n                    self.email,\n                    self.email\n                ],\n                None,\n                None,\n                None,\n                None,\n                None,\n                None,\n                None,\n            ])\n        except (IndexError, TypeError, InvalidData):\n            self._logger.debug('Missing essential info, cannot instantiate authenticated person')\n            return None\n        return person",
    "docstring": "Retrieves the person associated with this account"
  },
  {
    "code": "def user_roles_exists(name, roles, database, user=None, password=None, host=None,\n                      port=None, authdb=None):\n    try:\n        roles = _to_dict(roles)\n    except Exception:\n        return 'Roles provided in wrong format'\n    users = user_list(user, password, host, port, database, authdb)\n    if isinstance(users, six.string_types):\n        return 'Failed to connect to mongo database'\n    for user in users:\n        if name == dict(user).get('user'):\n            for role in roles:\n                if not isinstance(role, dict):\n                    role = {'role': role, 'db': database}\n                if role not in dict(user).get('roles', []):\n                    return False\n            return True\n    return False",
    "docstring": "Checks if a user of a MongoDB database has specified roles\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt '*' mongodb.user_roles_exists johndoe '[\"readWrite\"]' dbname admin adminpwd localhost 27017\n\n    .. code-block:: bash\n\n        salt '*' mongodb.user_roles_exists johndoe '[{\"role\": \"readWrite\", \"db\": \"dbname\" }, {\"role\": \"read\", \"db\": \"otherdb\"}]' dbname admin adminpwd localhost 27017"
  },
  {
    "code": "def _with_env(self, env):\n        res = self._browse(env, self._ids)\n        return res",
    "docstring": "As the `with_env` class method but for recordset."
  },
  {
    "code": "def canonical_query_string(self):\n        results = []\n        for key, values in iteritems(self.query_parameters):\n            if key == _x_amz_signature:\n                continue\n            for value in values:\n                results.append(\"%s=%s\" % (key, value))\n        return \"&\".join(sorted(results))",
    "docstring": "The canonical query string from the query parameters.\n\n        This takes the query string from the request and orders the parameters\n        in"
  },
  {
    "code": "def readCfgJson(cls, working_path):\n        cfg_json_filename = os.path.join(working_path, cls.CFG_JSON_FILENAME)\n        if os.path.isfile(cfg_json_filename):\n            with open(cfg_json_filename) as json_file:\n                cfg = json.load(json_file)\n                return cfg\n        return None",
    "docstring": "Read cmWalk configuration data of a working directory from a json file.\n\n        :param working_path: working path for reading the configuration data.\n        :return: the configuration data represented in a json object, None if the configuration files does not\n                 exist."
  },
  {
    "code": "def GetRandomDatetime():\n  seconds_offset = random.randint(0, 60 * 60 * 24 * 7)\n  dt = datetime.today() + timedelta(seconds=seconds_offset)\n  return dt.replace(second=0, microsecond=0)",
    "docstring": "Return a datetime in the next week."
  },
  {
    "code": "def stats(self, *args):\n        result = self._fetch_cmd(b'stats', args, False)\n        for key, value in six.iteritems(result):\n            converter = STAT_TYPES.get(key, int)\n            try:\n                result[key] = converter(value)\n            except Exception:\n                pass\n        return result",
    "docstring": "The memcached \"stats\" command.\n\n        The returned keys depend on what the \"stats\" command returns.\n        A best effort is made to convert values to appropriate Python\n        types, defaulting to strings when a conversion cannot be made.\n\n        Args:\n          *arg: extra string arguments to the \"stats\" command. See the\n                memcached protocol documentation for more information.\n\n        Returns:\n          A dict of the returned stats."
  },
  {
    "code": "def analyze(self, scratch, **kwargs):\n        results = Counter()\n        for script in self.iter_scripts(scratch):\n            gen = self.iter_blocks(script.blocks)\n            name = 'start'\n            level = None\n            while name != '':\n                if name in self.ANIMATION:\n                    gen, count = self._check_animation(name, level, gen)\n                    results.update(count)\n                name, level, _ = next(gen, ('', 0, ''))\n        return {'animation': results}",
    "docstring": "Run and return the results from the Animation plugin."
  },
  {
    "code": "def parse_top_level(self):\n        contacts = []\n        while not self.eos:\n            contact = self.parse_contact()\n            if not contact:\n                break\n            contacts.append(contact)\n            self.parse_whitespace()\n        output = {}\n        for key, value in contacts:\n            output[key] = value\n        return output",
    "docstring": "The top level parser will do a loop where it looks for a single\n        contact parse and then eats all whitespace until there is no more\n        input left or another contact is found to be parsed and stores them."
  },
  {
    "code": "def is_in_shard(self, s):\n    return self.compute_shard(s, self._nshards) == self._shard",
    "docstring": "Returns True iff the string s is in this shard.\n\n    :param string s: The string to check."
  },
  {
    "code": "def _symlink_remote_lib(self, gopath, go_remote_lib, required_links):\n    def source_iter():\n      remote_lib_source_dir = self.context.products.get_data('go_remote_lib_src')[go_remote_lib]\n      for path in os.listdir(remote_lib_source_dir):\n        remote_src = os.path.join(remote_lib_source_dir, path)\n        if os.path.isfile(remote_src):\n          yield (remote_src, os.path.basename(path))\n    return self._symlink_lib(gopath, go_remote_lib, source_iter(), required_links)",
    "docstring": "Creates symlinks from the given gopath to the source files of the given remote lib.\n\n    Also duplicates directory structure leading to source files of package within\n    gopath, in order to provide isolation to the package.\n\n    Adds the symlinks to the source files to required_links."
  },
  {
    "code": "def get_command_line(instance_type, env, message, data, mode, open_notebook, command_str):\n    floyd_command = [\"floyd\", \"run\"]\n    if instance_type:\n        floyd_command.append('--' + INSTANCE_NAME_MAP[instance_type])\n    if env and not env == DEFAULT_ENV:\n        floyd_command += [\"--env\", env]\n    if message:\n        floyd_command += [\"--message\", shell_quote(message)]\n    if data:\n        for data_item in data:\n            parts = data_item.split(':')\n            if len(parts) > 1:\n                data_item = normalize_data_name(parts[0], use_data_config=False) + ':' + parts[1]\n            floyd_command += [\"--data\", data_item]\n    if mode and mode != \"job\":\n        floyd_command += [\"--mode\", mode]\n        if mode == 'jupyter':\n            if not open_notebook:\n                floyd_command.append(\"--no-open\")\n    else:\n        if command_str:\n            floyd_command.append(shell_quote(command_str))\n    return ' '.join(floyd_command)",
    "docstring": "Return a string representing the full floyd command entered in the command line"
  },
  {
    "code": "def _create_injector(self, injector):\n        if injector == \"block_info\":\n            block_info_injector = importlib.import_module(\n                \"sawtooth_validator.journal.block_info_injector\")\n            return block_info_injector.BlockInfoInjector(\n                self._state_view_factory, self._signer)\n        raise UnknownBatchInjectorError(injector)",
    "docstring": "Returns a new batch injector"
  },
  {
    "code": "def make_avro_schema(i,\n                     loader\n                     ):\n    names = Names()\n    avro = make_avro(i, loader)\n    make_avsc_object(convert_to_dict(avro), names)\n    return names",
    "docstring": "All in one convenience function.\n\n    Call make_avro() and make_avro_schema_from_avro() separately if you need\n    the intermediate result for diagnostic output."
  },
  {
    "code": "def to_positions(self):\n        if self.coords_are_displacement:\n            cumulative_displacements = np.cumsum(self.frac_coords, axis=0)\n            positions = self.base_positions + cumulative_displacements\n            self.frac_coords = positions\n            self.coords_are_displacement = False\n        return",
    "docstring": "Converts fractional coordinates of trajectory into positions"
  },
  {
    "code": "def verify_counter(self, signature, counter):\n        devices = self.__get_u2f_devices()\n        for device in devices:\n            if device['keyHandle'] == signature['keyHandle']:\n                if counter > device['counter']:\n                    device['counter'] = counter\n                    self.__save_u2f_devices(devices)\n                    return True\n                else:\n                    return False",
    "docstring": "Verifies that counter value is greater than previous signature"
  },
  {
    "code": "def use_service(bundle_context, svc_reference):\n    if svc_reference is None:\n        raise TypeError(\"Invalid ServiceReference\")\n    try:\n        yield bundle_context.get_service(svc_reference)\n    finally:\n        try:\n            bundle_context.unget_service(svc_reference)\n        except pelix.constants.BundleException:\n            pass",
    "docstring": "Utility context to safely use a service in a \"with\" block.\n    It looks after the the given service and releases its reference when\n    exiting the context.\n\n    :param bundle_context: The calling bundle context\n    :param svc_reference: The reference of the service to use\n    :return: The requested service\n    :raise BundleException: Service not found\n    :raise TypeError: Invalid service reference"
  },
  {
    "code": "def _remove_dependency(self, dependlist, i, isSubroutine, anexec):\n        if dependlist[i] in anexec.dependencies:\n            all_depends = anexec.dependencies[dependlist[i]]\n            if len(all_depends) > 0:\n                clean_args = all_depends[0].clean(dependlist[i + 1])\n                for idepend in range(len(all_depends)):\n                    if (all_depends[idepend].argslist == clean_args\n                        and all_depends[idepend].isSubroutine == isSubroutine):\n                        del anexec.dependencies[dependlist[i]][idepend]\n                        break",
    "docstring": "Removes the specified dependency from the executable if it exists\n        and matches the call signature."
  },
  {
    "code": "def get_distance_matrix(self):\n        assert self.lons.ndim == 1\n        distances = geodetic.geodetic_distance(\n            self.lons.reshape(self.lons.shape + (1, )),\n            self.lats.reshape(self.lats.shape + (1, )),\n            self.lons,\n            self.lats)\n        return numpy.matrix(distances, copy=False)",
    "docstring": "Compute and return distances between each pairs of points in the mesh.\n\n        This method requires that the coordinate arrays are one-dimensional.\n        NB: the depth of the points is ignored\n\n        .. warning::\n            Because of its quadratic space and time complexity this method\n            is safe to use for meshes of up to several thousand points. For\n            mesh of 10k points it needs ~800 Mb for just the resulting matrix\n            and four times that much for intermediate storage.\n\n        :returns:\n            Two-dimensional numpy array, square matrix of distances. The matrix\n            has zeros on main diagonal and positive distances in kilometers\n            on all other cells. That is, value in cell (3, 5) is the distance\n            between mesh's points 3 and 5 in km, and it is equal to value\n            in cell (5, 3).\n\n        Uses :func:`openquake.hazardlib.geo.geodetic.geodetic_distance`."
  },
  {
    "code": "def get(self, sid):\n        return FieldContext(\n            self._version,\n            assistant_sid=self._solution['assistant_sid'],\n            task_sid=self._solution['task_sid'],\n            sid=sid,\n        )",
    "docstring": "Constructs a FieldContext\n\n        :param sid: The unique string that identifies the resource\n\n        :returns: twilio.rest.autopilot.v1.assistant.task.field.FieldContext\n        :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldContext"
  },
  {
    "code": "def external_answer(self, *sequences):\n        if not getattr(self, 'external', False):\n            return\n        if hasattr(self, 'test_func') and self.test_func is not self._ident:\n            return\n        libs = libraries.get_libs(self.__class__.__name__)\n        for lib in libs:\n            if not lib.check_conditions(self, *sequences):\n                continue\n            if not lib.get_function():\n                continue\n            prepared_sequences = lib.prepare(*sequences)\n            try:\n                return lib.func(*prepared_sequences)\n            except Exception:\n                pass",
    "docstring": "Try to get answer from known external libraries."
  },
  {
    "code": "def _snapshot(self) -> Dict[str, Any]:\n        try:\n            return {name: item._snapshot for name, item in self._nested_items.items()}\n        except Exception as e:\n            raise SnapshotError('Error while creating snapshot for {}'.format(self._name)) from e",
    "docstring": "Implements snapshot for collections by recursively invoking snapshot of all child items"
  },
  {
    "code": "def voronoi(data, line_color=None, line_width=2, f_tooltip=None, cmap=None, max_area=1e4, alpha=220):\n    from geoplotlib.layers import VoronoiLayer\n    _global_config.layers.append(VoronoiLayer(data, line_color, line_width, f_tooltip, cmap, max_area, alpha))",
    "docstring": "Draw the voronoi tesselation of the points\n\n    :param data: data access object\n    :param line_color: line color\n    :param line_width: line width\n    :param f_tooltip: function to generate a tooltip on mouseover\n    :param cmap: color map\n    :param max_area: scaling constant to determine the color of the voronoi areas\n    :param alpha: color alpha"
  },
  {
    "code": "def nvrtcCompileProgram(self, prog, options):\n        options_array = (c_char_p * len(options))()\n        options_array[:] = encode_str_list(options)\n        code = self._lib.nvrtcCompileProgram(prog, len(options), options_array)\n        self._throw_on_error(code)\n        return",
    "docstring": "Compiles the NVRTC program object into PTX, using the provided options\n        array.  See the NVRTC API documentation for accepted options."
  },
  {
    "code": "def make_article_info_correspondences(self, article_info_div):\n        corresps = self.article.root.xpath('./front/article-meta/author-notes/corresp')\n        if corresps:\n            corresp_div = etree.SubElement(article_info_div,\n                                           'div',\n                                           {'id': 'correspondence'})\n        for corresp in corresps:\n            sub_div = etree.SubElement(corresp_div,\n                                       'div',\n                                       {'id': corresp.attrib['id']})\n            append_all_below(sub_div, corresp)",
    "docstring": "Articles generally provide a first contact, typically an email address\n        for one of the authors. This will supply that content."
  },
  {
    "code": "def _check_ubridge_version(self, env=None):\n        try:\n            output = yield from subprocess_check_output(self._path, \"-v\", cwd=self._working_dir, env=env)\n            match = re.search(\"ubridge version ([0-9a-z\\.]+)\", output)\n            if match:\n                self._version = match.group(1)\n                if sys.platform.startswith(\"win\") or sys.platform.startswith(\"darwin\"):\n                    minimum_required_version = \"0.9.12\"\n                else:\n                    minimum_required_version = \"0.9.14\"\n                if parse_version(self._version) < parse_version(minimum_required_version):\n                    raise UbridgeError(\"uBridge executable version must be >= {}\".format(minimum_required_version))\n            else:\n                raise UbridgeError(\"Could not determine uBridge version for {}\".format(self._path))\n        except (OSError, subprocess.SubprocessError) as e:\n            raise UbridgeError(\"Error while looking for uBridge version: {}\".format(e))",
    "docstring": "Checks if the ubridge executable version"
  },
  {
    "code": "def edit_section(self, id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"id\"] = id\r\n        if course_section_name is not None:\r\n            data[\"course_section[name]\"] = course_section_name\r\n        if course_section_sis_section_id is not None:\r\n            data[\"course_section[sis_section_id]\"] = course_section_sis_section_id\r\n        if course_section_start_at is not None:\r\n            data[\"course_section[start_at]\"] = course_section_start_at\r\n        if course_section_end_at is not None:\r\n            data[\"course_section[end_at]\"] = course_section_end_at\r\n        if course_section_restrict_enrollments_to_section_dates is not None:\r\n            data[\"course_section[restrict_enrollments_to_section_dates]\"] = course_section_restrict_enrollments_to_section_dates\r\n        self.logger.debug(\"PUT /api/v1/sections/{id} with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"PUT\", \"/api/v1/sections/{id}\".format(**path), data=data, params=params, single_item=True)",
    "docstring": "Edit a section.\r\n\r\n        Modify an existing section."
  },
  {
    "code": "def _readResponse(self):\n        traps = []\n        reply_word = None\n        while reply_word != '!done':\n            reply_word, words = self._readSentence()\n            if reply_word == '!trap':\n                traps.append(TrapError(**words))\n            elif reply_word in ('!re', '!done') and words:\n                yield words\n        if len(traps) > 1:\n            raise MultiTrapError(*traps)\n        elif len(traps) == 1:\n            raise traps[0]",
    "docstring": "Yield each row of response untill !done is received.\n\n        :throws TrapError: If one !trap is received.\n        :throws MultiTrapError: If > 1 !trap is received."
  },
  {
    "code": "def occurrence(self, file_name=None, path=None, date=None):\n        if self._indicator_data.get('type') != 'File':\n            return None\n        occurrence_obj = FileOccurrence(file_name, path, date)\n        self._occurrences.append(occurrence_obj)\n        return occurrence_obj",
    "docstring": "Add a file Occurrence.\n\n        Args:\n            file_name (str, optional): The file name for this occurrence.\n            path (str, optional): The file path for this occurrence.\n            date (str, optional): The datetime expression for this occurrence.\n\n        Returns:\n            obj: An instance of Occurrence."
  },
  {
    "code": "def get_answer_mdata():\n    return {\n        'item': {\n            'element_label': {\n                'text': 'item',\n                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),\n                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),\n                'formatTypeId': str(DEFAULT_FORMAT_TYPE),\n            },\n            'instructions': {\n                'text': 'accepts an osid.id.Id object',\n                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),\n                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),\n                'formatTypeId': str(DEFAULT_FORMAT_TYPE),\n            },\n            'required': False,\n            'read_only': False,\n            'linked': False,\n            'array': False,\n            'default_id_values': [''],\n            'syntax': 'ID',\n            'id_set': [],\n        },\n    }",
    "docstring": "Return default mdata map for Answer"
  },
  {
    "code": "def get_scheduling_block(sub_array_id, block_id):\n    block_ids = DB.get_sub_array_sbi_ids(sub_array_id)\n    if block_id in block_ids:\n        block = DB.get_block_details([block_id]).__next__()\n        return block, HTTPStatus.OK\n    return dict(error=\"unknown id\"), HTTPStatus.NOT_FOUND",
    "docstring": "Return the list of scheduling blocks instances associated with the sub\n    array"
  },
  {
    "code": "def insert(self, text: str):\n        undoObj = UndoInsert(self, text)\n        self.qteUndoStack.push(undoObj)",
    "docstring": "Undo safe wrapper for the native ``insert`` method.\n\n        |Args|\n\n        * ``text`` (**str**): text to insert at the current position.\n\n        |Returns|\n\n        **None**\n\n        |Raises|\n\n        * **QtmacsArgumentError** if at least one argument has an invalid type."
  },
  {
    "code": "def ratio_to_delta(self, isos_ss, ratio, oneover=False):\n        if type(isos_ss) == float:\n            ss_ratio = isos_ss\n        elif type(isos_ss) == list:\n            ss_ratio = self.inut.isoratio_init(isos_ss)\n        else:\n            print('Check input of isos_ss into ratio_to_delta routine')\n            return None\n        if oneover:\n            ratio = old_div(1,ratio)\n        delta = (old_div(ratio, ss_ratio) - 1.) * 1000.\n        return delta",
    "docstring": "Transforms an isotope ratio into a delta value\n\n        Parameters\n        ----------\n        isos_ss: list or float\n            list w/ isotopes, e.g., ['N-14','N-15'] OR the solar\n            system ratio.\n        ratio : float\n            ratio of the isotopes to transform.\n        oneover : boolean\n            take the inverse of the ratio before transforming (never\n            inverse of delta value!).  The default is False.\n\n        Returns\n        -------\n        float\n            delta value"
  },
  {
    "code": "def union(seq1=(), *seqs):\n    r\n    if not seqs: return list(seq1)\n    res = set(seq1)\n    for seq in seqs:\n        res.update(set(seq))\n    return list(res)",
    "docstring": "r\"\"\"Return the set union of `seq1` and `seqs`, duplicates removed, order random.\n\n    Examples:\n    >>> union()\n    []\n    >>> union([1,2,3])\n    [1, 2, 3]\n    >>> union([1,2,3], {1:2, 5:1})\n    [1, 2, 3, 5]\n    >>> union((1,2,3), ['a'], \"bcd\")\n    ['a', 1, 2, 3, 'd', 'b', 'c']\n    >>> union([1,2,3], iter([0,1,1,1]))\n    [0, 1, 2, 3]"
  },
  {
    "code": "def extra_html_properties(self, prefix=None, postfix=None, template_type=None):\n        prefix = prefix if prefix else \"django-plotly-dash\"\n        post_part = \"-%s\" % postfix if postfix else \"\"\n        template_type = template_type if template_type else \"iframe\"\n        slugified_id = self.slugified_id()\n        return \"%(prefix)s %(prefix)s-%(template_type)s %(prefix)s-app-%(slugified_id)s%(post_part)s\" % {'slugified_id':slugified_id,\n                                                                                                         'post_part':post_part,\n                                                                                                         'template_type':template_type,\n                                                                                                         'prefix':prefix,\n                                                                                                        }",
    "docstring": "Return extra html properties to allow individual apps to be styled separately.\n\n        The content returned from this function is injected unescaped into templates."
  },
  {
    "code": "def merge_variables(variables, **kwargs):\n        var_dict = OrderedDict()\n        for v in variables:\n            if v.name not in var_dict:\n                var_dict[v.name] = []\n            var_dict[v.name].append(v)\n        return [merge_variables(vars_, **kwargs)\n                for vars_ in list(var_dict.values())]",
    "docstring": "Concatenates Variables along row axis.\n\n        Args:\n            variables (list): List of Variables to merge. Variables can have\n                different names (and all Variables that share a name will be\n                concatenated together).\n\n        Returns:\n            A list of Variables."
  },
  {
    "code": "def delete_user_from_group(self, GroupID, UserID):\n        log.info('Delete user %s from group %s' % (UserID, GroupID))\n        self.put('groups/%s/delete_user/%s.json' % (GroupID, UserID))",
    "docstring": "Delete a user from a group."
  },
  {
    "code": "def hour(self, value=None):\n        if value is not None:\n            try:\n                value = int(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type int '\n                                 'for field `hour`'.format(value))\n            if value < 1:\n                raise ValueError('value need to be greater or equal 1 '\n                                 'for field `hour`')\n            if value > 24:\n                raise ValueError('value need to be smaller 24 '\n                                 'for field `hour`')\n        self._hour = value",
    "docstring": "Corresponds to IDD Field `hour`\n\n        Args:\n            value (int): value for IDD Field `hour`\n                value >= 1\n                value <= 24\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def check_staged(filename=None):\n    retcode, _, stdout = git['diff-index', '--quiet', '--cached', 'HEAD',\n                             filename].run(retcode=None)\n    if retcode == 1:\n        return True\n    elif retcode == 0:\n        return False\n    else:\n        raise RuntimeError(stdout)",
    "docstring": "Check if there are 'changes to be committed' in the index."
  },
  {
    "code": "def _update_Prxy_diag(self):\n        for r in range(self.nsites):\n            pr_half = self.prx[r]**0.5\n            pr_neghalf = self.prx[r]**-0.5\n            symm_pr = (pr_half * (self.Prxy[r] * pr_neghalf).transpose()).transpose()\n            (evals, evecs) = scipy.linalg.eigh(symm_pr)\n            self.D[r] = evals\n            self.Ainv[r] = evecs.transpose() * pr_half\n            self.A[r] = (pr_neghalf * evecs.transpose()).transpose()",
    "docstring": "Update `D`, `A`, `Ainv` from `Prxy`, `prx`."
  },
  {
    "code": "def get_face_colors(self, indexed=None):\n        if indexed is None:\n            return self._face_colors\n        elif indexed == 'faces':\n            if (self._face_colors_indexed_by_faces is None and\n                    self._face_colors is not None):\n                Nf = self._face_colors.shape[0]\n                self._face_colors_indexed_by_faces = \\\n                    np.empty((Nf, 3, 4), dtype=self._face_colors.dtype)\n                self._face_colors_indexed_by_faces[:] = \\\n                    self._face_colors.reshape(Nf, 1, 4)\n            return self._face_colors_indexed_by_faces\n        else:\n            raise Exception(\"Invalid indexing mode. Accepts: None, 'faces'\")",
    "docstring": "Get the face colors\n\n        Parameters\n        ----------\n        indexed : str | None\n            If indexed is None, return (Nf, 4) array of face colors.\n            If indexed=='faces', then instead return an indexed array\n            (Nf, 3, 4)  (note this is just the same array with each color\n            repeated three times).\n        \n        Returns\n        -------\n        colors : ndarray\n            The colors."
  },
  {
    "code": "def get_all_children(self):\n        children = self._children[:]\n        oldlen = 0\n        newlen = len(children)\n        while oldlen != newlen:\n            start = oldlen\n            oldlen = len(children)\n            for i in range(start, len(children)):\n                children.extend(children[i]._children)\n            newlen = len(children)\n        return children",
    "docstring": "Get all children including children of children\n\n        :returns: all children including children of children\n        :rtype: list of :class:`Reftrack`\n        :raises: None"
  },
  {
    "code": "def add(self, fact):\n        token = Token.valid(fact)\n        MATCHER.debug(\"<BusNode> added %r\", token)\n        for child in self.children:\n            child.callback(token)",
    "docstring": "Create a VALID token and send it to all children."
  },
  {
    "code": "def stop_sync(self):\n        conn_ids = self.conns.get_connections()\n        for conn in list(conn_ids):\n            try:\n                self.disconnect_sync(conn)\n            except HardwareError:\n                pass\n        self.client.disconnect()\n        self.conns.stop()",
    "docstring": "Synchronously stop this adapter"
  },
  {
    "code": "def _start_check_timer(self):\n        if self.timer:\n            self.timer.cancel()\n        self.timer = threading.Timer(2.5, self.check_complete)\n        self.timer.daemon = True\n        self.timer.start()",
    "docstring": "Periodically checks to see if the task has completed."
  },
  {
    "code": "def under_attack(col, queens):\n        left = right = col\n        for _, column in reversed(queens):\n            left, right = left - 1, right + 1\n            if column in (left, col, right):\n                return True\n        return False",
    "docstring": "Checks if queen is under attack\n\n        :param col: Column number\n        :param queens: list of queens\n        :return: True iff queen is under attack"
  },
  {
    "code": "def transformer_big():\n  hparams = transformer_base()\n  hparams.hidden_size = 1024\n  hparams.filter_size = 4096\n  hparams.batch_size = 2048\n  hparams.num_heads = 16\n  hparams.layer_prepostprocess_dropout = 0.3\n  return hparams",
    "docstring": "HParams for transformer big model on WMT."
  },
  {
    "code": "def roll_mean(input, window):\r\n    nobs, i, j, sum_x = 0,0,0,0.\r\n    N = len(input)\r\n    if window > N:\r\n        raise ValueError('Out of bound')\r\n    output = np.ndarray(N-window+1,dtype=input.dtype)\r\n    for val in input[:window]:\r\n        if val == val:\r\n            nobs += 1\r\n            sum_x += val\r\n    output[j] = NaN if not nobs else sum_x / nobs\r\n    for val in input[window:]:\r\n        prev = input[j]\r\n        if prev == prev:\r\n            sum_x -= prev\r\n            nobs -= 1\r\n        if val == val:\r\n            nobs += 1\r\n            sum_x += val\r\n        j += 1\r\n        output[j] = NaN if not nobs else sum_x / nobs\r\n    return output",
    "docstring": "Apply a rolling mean function to an array.\r\nThis is a simple rolling aggregation."
  },
  {
    "code": "def match_set(self, tokens, item):\n        match, = tokens\n        self.add_check(\"_coconut.isinstance(\" + item + \", _coconut.abc.Set)\")\n        self.add_check(\"_coconut.len(\" + item + \") == \" + str(len(match)))\n        for const in match:\n            self.add_check(const + \" in \" + item)",
    "docstring": "Matches a set."
  },
  {
    "code": "def process_python_symbol_data(oedata):\n    symbol_list = []\n    for key in oedata:\n        val = oedata[key]\n        if val and key != 'found_cell_separators':\n            if val.is_class_or_function():\n                symbol_list.append((key, val.def_name, val.fold_level,\n                                    val.get_token()))\n    return sorted(symbol_list)",
    "docstring": "Returns a list with line number, definition name, fold and token."
  },
  {
    "code": "def chars(self, length, name, value=None, terminator=None):\n        self._add_field(Char(length, name, value, terminator))",
    "docstring": "Add a char array to template.\n\n        `length` is given in bytes and can refer to earlier numeric fields in\n        template. Special value '*' in length means that length is encoded to\n        length of value and decoded as all available bytes.\n\n        `value` is optional.\n        `value` could be either a \"String\" or a \"Regular Expression\" and\n        if it is a Regular Expression it must be prefixed by 'REGEXP:'.\n\n        Examples:\n        | chars | 16 | field | Hello World! |\n\n        | u8 | charLength |\n        | chars | charLength | field |\n\n        | chars | * | field | Hello World! |\n        | chars | * | field | REGEXP:^{[a-zA-Z ]+}$ |"
  },
  {
    "code": "def add_argument(self, dest, nargs=1, obj=None):\n        if obj is None:\n            obj = dest\n        self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))",
    "docstring": "Adds a positional argument named `dest` to the parser.\n\n        The `obj` can be used to identify the option in the order list\n        that is returned from the parser."
  },
  {
    "code": "def set_cover(self, file_name, content, create_page=True):\n        c0 = EpubCover(file_name=file_name)\n        c0.content = content\n        self.add_item(c0)\n        if create_page:\n            c1 = EpubCoverHtml(image_name=file_name)\n            self.add_item(c1)\n        self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))",
    "docstring": "Set cover and create cover document if needed.\n\n        :Args:\n          - file_name: file name of the cover page\n          - content: Content for the cover image\n          - create_page: Should cover page be defined. Defined as bool value (optional). Default value is True."
  },
  {
    "code": "def write(self, fptr):\n        fptr.write(struct.pack('>I4s', 12, b'jP  '))\n        fptr.write(struct.pack('>BBBB', *self.signature))",
    "docstring": "Write a JPEG 2000 Signature box to file."
  },
  {
    "code": "def get_candidate_electoral_votes(self, candidate):\n        candidate_election = CandidateElection.objects.get(\n            candidate=candidate, election=self\n        )\n        return candidate_election.electoral_votes.all()",
    "docstring": "Get all electoral votes for a candidate in this election."
  },
  {
    "code": "def _get_service_connection(self, service, service_command=None, create=True, timeout_ms=None):\n        connection = self._service_connections.get(service, None)\n        if connection:\n            return connection\n        if not connection and not create:\n            return None\n        if service_command:\n            destination_str = b'%s:%s' % (service, service_command)\n        else:\n            destination_str = service\n        connection = self.protocol_handler.Open(\n            self._handle, destination=destination_str, timeout_ms=timeout_ms)\n        self._service_connections.update({service: connection})\n        return connection",
    "docstring": "Based on the service, get the AdbConnection for that service or create one if it doesnt exist\n\n        :param service:\n        :param service_command: Additional service parameters to append\n        :param create: If False, dont create a connection if it does not exist\n        :return:"
  },
  {
    "code": "def hide(self):\n        if self._prev_contrast is None:\n            self._prev_contrast = self._contrast\n            self.contrast(0x00)",
    "docstring": "Simulates switching the display mode OFF; this is achieved by setting\n        the contrast level to zero."
  },
  {
    "code": "def AND(classical_reg1, classical_reg2):\n    left, right = unpack_reg_val_pair(classical_reg1, classical_reg2)\n    return ClassicalAnd(left, right)",
    "docstring": "Produce an AND instruction.\n\n    NOTE: The order of operands was reversed in pyQuil <=1.9 .\n\n    :param classical_reg1: The first classical register, which gets modified.\n    :param classical_reg2: The second classical register or immediate value.\n    :return: A ClassicalAnd instance."
  },
  {
    "code": "def createObjectMachine(machineType, **kwargs):\n  if machineType not in ObjectMachineTypes.getTypes():\n    raise RuntimeError(\"Unknown model type: \" + machineType)\n  return getattr(ObjectMachineTypes, machineType)(**kwargs)",
    "docstring": "Return an object machine of the appropriate type.\n\n  @param machineType (str)  A supported ObjectMachine type\n\n  @param kwargs      (dict) Constructor argument for the class that will be\n                            instantiated. Keyword parameters specific to each\n                            model type should be passed in here."
  },
  {
    "code": "def find_best_matching_node(self, new, old_nodes):\n        name = new.__class__.__name__\n        matches = [c for c in old_nodes if name == c.__class__.__name__]\n        if self.debug:\n            print(\"Found matches for {}: {} \".format(new, matches))\n        return matches[0] if matches else None",
    "docstring": "Find the node that best matches the new node given the old nodes. If no\n            good match exists return `None`."
  },
  {
    "code": "def _call(self, x):\n        if self.prior is None:\n            tmp = self.domain.element((np.exp(x) - 1)).inner(self.domain.one())\n        else:\n            tmp = (self.prior * (np.exp(x) - 1)).inner(self.domain.one())\n        return tmp",
    "docstring": "Return the value in the point ``x``."
  },
  {
    "code": "def periods(ts, phi=0.0):\n    ts = np.squeeze(ts)\n    if ts.ndim <= 1:\n        return np.diff(phase_crossings(ts, phi))\n    else:\n        return np.hstack([ts[...,i].periods(phi) for i in range(ts.shape[-1])])",
    "docstring": "For a single variable timeseries representing the phase of an oscillator,\n    measure the period of each successive oscillation.\n\n    An individual oscillation is defined to start and end when the phase \n    passes phi (by default zero) after completing a full cycle.\n\n    If the timeseries begins (or ends) exactly at phi, then the first\n    (or last) oscillation will be included.\n\n    Arguments: \n      ts: Timeseries (single variable)\n          The timeseries of an angle variable (radians)\n\n      phi (float): A single oscillation starts and ends at phase phi (by \n        default zero)."
  },
  {
    "code": "def get_device_elements(self):\n        plain = self._aha_request('getdevicelistinfos')\n        dom = xml.dom.minidom.parseString(plain)\n        _LOGGER.debug(dom)\n        return dom.getElementsByTagName(\"device\")",
    "docstring": "Get the DOM elements for the device list."
  },
  {
    "code": "def compose_args(self, action_name, in_argdict):\n        for action in self.actions:\n            if action.name == action_name:\n                break\n        else:\n            raise AttributeError('Unknown Action: {0}'.format(action_name))\n        unexpected = set(in_argdict) - \\\n            set(argument.name for argument in action.in_args)\n        if unexpected:\n            raise ValueError(\n                \"Unexpected argument '{0}'. Method signature: {1}\"\n                .format(next(iter(unexpected)), str(action))\n            )\n        composed = []\n        for argument in action.in_args:\n            name = argument.name\n            if name in in_argdict:\n                composed.append((name, in_argdict[name]))\n                continue\n            if name in self.DEFAULT_ARGS:\n                composed.append((name, self.DEFAULT_ARGS[name]))\n                continue\n            if argument.vartype.default is not None:\n                composed.append((name, argument.vartype.default))\n            raise ValueError(\n                \"Missing argument '{0}'. Method signature: {1}\"\n                .format(argument.name, str(action))\n            )\n        return composed",
    "docstring": "Compose the argument list from an argument dictionary, with\n        respect for default values.\n\n        Args:\n            action_name (str): The name of the action to be performed.\n            in_argdict (dict): Arguments as a dict, eg\n                ``{'InstanceID': 0, 'Speed': 1}. The values\n                can be a string or something with a string representation.\n\n        Returns:\n            list: a list of ``(name, value)`` tuples.\n\n        Raises:\n            `AttributeError`: If this service does not support the action.\n            `ValueError`: If the argument lists do not match the action\n                signature."
  },
  {
    "code": "def _current_size(self):\n        deletes, adds, _ = Watch._extract_changes(self.doc_map, self.change_map, None)\n        return len(self.doc_map) + len(adds) - len(deletes)",
    "docstring": "Returns the current count of all documents, including the changes from\n        the current changeMap."
  },
  {
    "code": "def pass_control_back(self, primary, secondary):\n        if secondary is None:\n            self._write(('*PCB', Integer(min=0, max=30)), primary)\n        else:\n            self._write(\n                ('*PCB', [Integer(min=0, max=30), Integer(min=0, max=30)]),\n                primary,\n                secondary\n            )",
    "docstring": "The address to which the controll is to be passed back.\n\n        Tells a potential controller device the address to which the control is\n        to be passed back.\n\n        :param primary: An integer in the range 0 to 30 representing the\n            primary address of the controller sending the command.\n        :param secondary: An integer in the range of 0 to 30 representing the\n            secondary address of the controller sending the command. If it is\n            missing, it indicates that the controller sending this command does\n            not have extended addressing."
  },
  {
    "code": "def return_type(rettype):\n    def wrap(f):\n        @functools.wraps(f)\n        def converter(*pargs, **kwargs):\n            result = f(*pargs, **kwargs)\n            try:\n                result = rettype(result)\n            except ValueError as e:\n                http_status(500, \"Return Value Conversion Failed\")\n                content_type(\"application/json\")\n                return {\"error\": str(e)}\n            return result\n        return converter\n    return wrap",
    "docstring": "Decorate a function to automatically convert its return type to a string\n    using a custom function.\n\n    Web-based service functions must return text to the client.  Tangelo\n    contains default logic to convert many kinds of values into string, but this\n    decorator allows the service writer to specify custom behavior falling\n    outside of the default.  If the conversion fails, an appropriate server\n    error will be raised."
  },
  {
    "code": "def read(self, *, level=0, alignment=1) -> bytes:\n        return self.mglo.read(level, alignment)",
    "docstring": "Read the content of the texture into a buffer.\n\n            Keyword Args:\n                level (int): The mipmap level.\n                alignment (int): The byte alignment of the pixels.\n\n            Returns:\n                bytes"
  },
  {
    "code": "def _get_real_instance_if_mismatch(vpc_info, ipaddr, instance, eni):\n    inst_id = instance.id if instance else \"\"\n    eni_id  = eni.id if eni else \"\"\n    if ipaddr:\n        real_instance, real_eni = \\\n                        find_instance_and_eni_by_ip(vpc_info, ipaddr)\n        if real_instance.id != inst_id  or real_eni.id != eni_id:\n            return real_instance\n    return None",
    "docstring": "Return the real instance for the given IP address, if that instance is\n    different than the passed in instance or has a different eni.\n\n    If the ipaddr belongs to the same instance and eni that was passed in then\n    this returns None."
  },
  {
    "code": "def write(self, face, data, viewport=None, *, alignment=1) -> None:\n        if type(data) is Buffer:\n            data = data.mglo\n        self.mglo.write(face, data, viewport, alignment)",
    "docstring": "Update the content of the texture.\n\n            Args:\n                face (int): The face to update.\n                data (bytes): The pixel data.\n                viewport (tuple): The viewport.\n\n            Keyword Args:\n                alignment (int): The byte alignment of the pixels."
  },
  {
    "code": "def random_ipv4(cidr='10.0.0.0/8'):\n    try:\n        u_cidr = unicode(cidr)\n    except NameError:\n        u_cidr = cidr\n    network = ipaddress.ip_network(u_cidr)\n    start = int(network.network_address) + 1\n    end = int(network.broadcast_address)\n    randint = random.randrange(start, end)\n    return ipaddress.ip_address(randint)",
    "docstring": "Return a random IPv4 address from the given CIDR block.\n\n    :key str cidr: CIDR block\n    :returns: An IPv4 address from the given CIDR block\n    :rtype: ipaddress.IPv4Address"
  },
  {
    "code": "def _WriteOutputValues(self, output_values):\n    for index, value in enumerate(output_values):\n      if not isinstance(value, py2to3.STRING_TYPES):\n        value = ''\n      output_values[index] = value.replace(',', ' ')\n    output_line = ','.join(output_values)\n    output_line = '{0:s}\\n'.format(output_line)\n    self._output_writer.Write(output_line)",
    "docstring": "Writes values to the output.\n\n    Args:\n      output_values (list[str]): output values."
  },
  {
    "code": "def is_valid_sid_for_new_standalone(sysmeta_pyxb):\n    sid = d1_common.xml.get_opt_val(sysmeta_pyxb, 'seriesId')\n    if not d1_gmn.app.did.is_valid_sid_for_new_standalone(sid):\n        raise d1_common.types.exceptions.IdentifierNotUnique(\n            0,\n            'Identifier is already in use as {}. did=\"{}\"'.format(\n                d1_gmn.app.did.classify_identifier(sid), sid\n            ),\n            identifier=sid,\n        )",
    "docstring": "Assert that any SID in ``sysmeta_pyxb`` can be assigned to a new standalone\n    object."
  },
  {
    "code": "def iter_ROOT_classes():\n    class_index = \"http://root.cern.ch/root/html/ClassIndex.html\"\n    for s in minidom.parse(urlopen(class_index)).getElementsByTagName(\"span\"):\n        if (\"class\", \"typename\") in s.attributes.items():\n            class_name = s.childNodes[0].nodeValue\n            try:\n                yield getattr(QROOT, class_name)\n            except AttributeError:\n                pass",
    "docstring": "Iterator over all available ROOT classes"
  },
  {
    "code": "def prune_volumes(self, filters=None):\n        params = {}\n        if filters:\n            params['filters'] = utils.convert_filters(filters)\n        url = self._url('/volumes/prune')\n        return self._result(self._post(url, params=params), True)",
    "docstring": "Delete unused volumes\n\n        Args:\n            filters (dict): Filters to process on the prune list.\n\n        Returns:\n            (dict): A dict containing a list of deleted volume names and\n                the amount of disk space reclaimed in bytes.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def _upload(self, items: Iterable[Tuple[str, str]]) -> None:\n        for src, key in items:\n            logger.info(f'Uploading {src} to {key}')\n            mimetype, _ = mimetypes.guess_type(src)\n            if mimetype is None:\n                logger.warning(f'Could not guess MIME type for {src}')\n                mimetype = 'application/octet-stream'\n            logger.debug(f'Deduced MIME type: {mimetype}')\n            self._bucket.upload_file(src, key, ExtraArgs={\n                    'ContentType': mimetype\n                })",
    "docstring": "Upload a collection of paths to S3.\n\n        :param items: An iterable of pairs containing the local path of the\n                      file to upload, and the remote path to upload it to. The\n                      prefix will be appended to each remote path."
  },
  {
    "code": "def user(self, id, expand=None):\n        user = User(self._options, self._session)\n        params = {}\n        if expand is not None:\n            params['expand'] = expand\n        user.find(id, params=params)\n        return user",
    "docstring": "Get a user Resource from the server.\n\n        :param id: ID of the user to get\n        :param id: str\n        :param expand: Extra information to fetch inside each resource\n        :type expand: Optional[Any]\n\n        :rtype: User"
  },
  {
    "code": "def write_pad_codewords(buff, version, capacity, length):\n    write = buff.extend\n    if version in (consts.VERSION_M1, consts.VERSION_M3):\n        write([0] * (capacity - length))\n    else:\n        pad_codewords = ((1, 1, 1, 0, 1, 1, 0, 0), (0, 0, 0, 1, 0, 0, 0, 1))\n        for i in range(capacity // 8 - length // 8):\n            write(pad_codewords[i % 2])",
    "docstring": "\\\n    Writes the pad codewords iff the data does not fill the capacity of the\n    symbol.\n\n    :param buff: The byte buffer.\n    :param int version: The (Micro) QR Code version.\n    :param int capacity: The total capacity of the symbol (incl. error correction)\n    :param int length: Length of the data bit stream."
  },
  {
    "code": "def _unzip_handle(handle):\n    if isinstance(handle, basestring):\n        handle = _gzip_open_filename(handle)\n    else:\n        handle = _gzip_open_handle(handle)\n    return handle",
    "docstring": "Transparently unzip the file handle"
  },
  {
    "code": "def on_origin(self, *args):\n        if self.origin is None:\n            Clock.schedule_once(self.on_origin, 0)\n            return\n        self.origin.bind(\n            pos=self._trigger_repoint,\n            size=self._trigger_repoint\n        )",
    "docstring": "Make sure to redraw whenever the origin moves."
  },
  {
    "code": "def write_release_version(version):\n    dirname = os.path.abspath(os.path.dirname(__file__))\n    f = open(os.path.join(dirname, \"_version.py\"), \"wt\")\n    f.write(\"__version__ = '%s'\\n\" % version)\n    f.close()",
    "docstring": "Write the release version to ``_version.py``."
  },
  {
    "code": "def _serialize_object(self, response_data, request):\n        if not self.factory:\n            return response_data\n        if isinstance(response_data, (list, tuple)):\n            return map(\n                lambda item: self.factory.serialize(item, request),\n                response_data)\n        else:\n            return self.factory.serialize(response_data, request)",
    "docstring": "Create a python datatype from the given python object.\n\n        This will use ``self.factory`` object's ``serialize()`` function\n        to convert the object into dictionary.\n\n        If no factory is defined, this will simply return the same data\n        that was given.\n\n        :param response_data: data returned by the resource"
  },
  {
    "code": "def _download_file(url, local_filename):\n    response = requests.get(url, stream=True)\n    with open(local_filename, 'wb') as outfile:\n        for chunk in response.iter_content(chunk_size=1024):\n            if chunk:\n                outfile.write(chunk)",
    "docstring": "Utility function that downloads a chunked response from the specified url to a local path.\n    This method is suitable for larger downloads."
  },
  {
    "code": "def validate():\n    if not os.path.exists(os.path.join(ROOT, APP, '__init__.py')):\n        message = ansi.error() + ' Python module not found.'\n        if os.environ.get('LORE_APP') is None:\n            message += ' $LORE_APP is not set. Should it be different than \"%s\"?' % APP\n        else:\n            message += ' $LORE_APP is set to \"%s\". Should it be different?' % APP\n        sys.exit(message)\n    if exists():\n        return\n    if len(sys.argv) > 1:\n        command = sys.argv[1]\n    else:\n        command = 'lore'\n    sys.exit(\n        ansi.error() + ' %s is only available in lore '\n                       'app directories (missing %s)' % (\n            ansi.bold(command),\n            ansi.underline(VERSION_PATH)\n        )\n    )",
    "docstring": "Display error messages and exit if no lore environment can be found."
  },
  {
    "code": "def set_dicts(self, word_dict, char_dict):\n        self.word_dict = word_dict\n        self.char_dict = char_dict",
    "docstring": "Set with custom dictionaries.\n\n        :param word_dict: The word dictionary.\n        :param char_dict: The character dictionary."
  },
  {
    "code": "def check_file_version(notebook, source_path, outputs_path):\n    if not insert_or_test_version_number():\n        return\n    _, ext = os.path.splitext(source_path)\n    if ext.endswith('.ipynb'):\n        return\n    version = notebook.metadata.get('jupytext', {}).get('text_representation', {}).get('format_version')\n    format_name = format_name_for_ext(notebook.metadata, ext)\n    fmt = get_format_implementation(ext, format_name)\n    current = fmt.current_version_number\n    if notebook.metadata and not version:\n        version = current\n    if version == fmt.current_version_number:\n        return\n    if (fmt.min_readable_version_number or current) <= version <= current:\n        return\n    raise JupytextFormatError(\"File {} is in format/version={}/{} (current version is {}). \"\n                              \"It would not be safe to override the source of {} with that file. \"\n                              \"Please remove one or the other file.\"\n                              .format(os.path.basename(source_path),\n                                      format_name, version, current,\n                                      os.path.basename(outputs_path)))",
    "docstring": "Raise if file version in source file would override outputs"
  },
  {
    "code": "def to_df(self, recommended_only=False, include_io=True):\n        od = BMDS._df_ordered_dict(include_io)\n        [\n            session._add_to_to_ordered_dict(od, i, recommended_only)\n            for i, session in enumerate(self)\n        ]\n        return pd.DataFrame(od)",
    "docstring": "Return a pandas DataFrame for each model and dataset.\n\n        Parameters\n        ----------\n        recommended_only : bool, optional\n            If True, only recommended models for each session are included. If\n            no model is recommended, then a row with it's ID will be included,\n            but all fields will be null.\n        include_io :  bool, optional\n            If True, then the input/output files from BMDS will also be\n            included, specifically the (d) input file and the out file.\n\n        Returns\n        -------\n        out : pandas.DataFrame\n            Data frame containing models and outputs"
  },
  {
    "code": "def load_fits(self, filepath):\n        image = AstroImage.AstroImage(logger=self.logger)\n        image.load_file(filepath)\n        self.set_image(image)",
    "docstring": "Load a FITS file into the viewer."
  },
  {
    "code": "def cli(self, *args, **kwargs):\n        kwargs['api'] = self.api\n        return cli(*args, **kwargs)",
    "docstring": "Defines a CLI function that should be routed by this API"
  },
  {
    "code": "def _get_public_ip(name, resource_group):\n    netconn = get_conn(client_type='network')\n    try:\n        pubip_query = netconn.public_ip_addresses.get(\n            resource_group_name=resource_group,\n            public_ip_address_name=name\n        )\n        pubip = pubip_query.as_dict()\n    except CloudError as exc:\n        __utils__['azurearm.log_cloud_error']('network', exc.message)\n        pubip = {'error': exc.message}\n    return pubip",
    "docstring": "Get the public ip address details by name."
  },
  {
    "code": "def normalise(v):\n    vn = np.sqrt(np.sum(v**2, 0))\n    vn[vn == 0] = 1.0\n    return np.asarray(v / vn, dtype=v.dtype)",
    "docstring": "Normalise columns of matrix.\n\n    Parameters\n    ----------\n    v : array_like\n      Array with columns to be normalised\n\n    Returns\n    -------\n    vnrm : ndarray\n      Normalised array"
  },
  {
    "code": "def setDebugActions( self, startAction, successAction, exceptionAction ):\n        self.debugActions = (startAction or _defaultStartDebugAction,\n                             successAction or _defaultSuccessDebugAction,\n                             exceptionAction or _defaultExceptionDebugAction)\n        self.debug = True\n        return self",
    "docstring": "Enable display of debugging messages while doing pattern matching."
  },
  {
    "code": "def generate(env):\n    c_file, cxx_file = SCons.Tool.createCFileBuilders(env)\n    c_file.add_action('.y', YaccAction)\n    c_file.add_emitter('.y', yEmitter)\n    c_file.add_action('.yacc', YaccAction)\n    c_file.add_emitter('.yacc', yEmitter)\n    c_file.add_action('.ym', YaccAction)\n    c_file.add_emitter('.ym', ymEmitter)\n    cxx_file.add_action('.yy', YaccAction)\n    cxx_file.add_emitter('.yy', yyEmitter)\n    env['YACC']      = env.Detect('bison') or 'yacc'\n    env['YACCFLAGS'] = SCons.Util.CLVar('')\n    env['YACCCOM']   = '$YACC $YACCFLAGS -o $TARGET $SOURCES'\n    env['YACCHFILESUFFIX'] = '.h'\n    env['YACCHXXFILESUFFIX'] = '.hpp'\n    env['YACCVCGFILESUFFIX'] = '.vcg'",
    "docstring": "Add Builders and construction variables for yacc to an Environment."
  },
  {
    "code": "def screenshot(self, png_filename=None, format='raw'):\n        value = self.http.get('screenshot').value\n        raw_value = base64.b64decode(value)\n        png_header = b\"\\x89PNG\\r\\n\\x1a\\n\"\n        if not raw_value.startswith(png_header) and png_filename:\n            raise WDAError(-1, \"screenshot png format error\")\n        if png_filename:\n            with open(png_filename, 'wb') as f:\n                f.write(raw_value)\n        if format == 'raw':\n            return raw_value\n        elif format == 'pillow':\n            from PIL import Image\n            buff = io.BytesIO(raw_value)\n            return Image.open(buff)\n        else:\n            raise ValueError(\"unknown format\")",
    "docstring": "Screenshot with PNG format\n\n        Args:\n            png_filename(string): optional, save file name\n            format(string): return format, pillow or raw(default)\n        Returns:\n            raw data or PIL.Image\n        \n        Raises:\n            WDAError"
  },
  {
    "code": "def _calculate_scores(self):\n        scores = {}\n        for node in self.graph.nodes():\n            score = -1 * len([\n                d for d in nx.descendants(self.graph, node)\n                if self._include_in_cost(d)\n            ])\n            scores[node] = score\n        return scores",
    "docstring": "Calculate the 'value' of each node in the graph based on how many\n        blocking descendants it has. We use this score for the internal\n        priority queue's ordering, so the quality of this metric is important.\n\n        The score is stored as a negative number because the internal\n        PriorityQueue picks lowest values first.\n\n        We could do this in one pass over the graph instead of len(self.graph)\n        passes but this is easy. For large graphs this may hurt performance.\n\n        This operates on the graph, so it would require a lock if called from\n        outside __init__.\n\n        :return Dict[str, int]: The score dict, mapping unique IDs to integer\n            scores. Lower scores are higher priority."
  },
  {
    "code": "def query_dict_to_string(query):\n        query_params = []\n        for key, value in query.items():\n            query_params.append(key + \"=\" + value)\n        return \"&\".join(query_params)",
    "docstring": "Convert an OrderedDict to a query string.\n\n        Args:\n            query (obj): The key value object with query params.\n\n        Returns:\n            str: The query string.\n\n        Note:\n            This method does the same as urllib.parse.urlencode except\n            that it doesn't actually encode the values."
  },
  {
    "code": "def removeCurrentItem(self):\n        logger.debug(\"removeCurrentFile\")\n        currentIndex = self.getRowCurrentIndex()\n        if not currentIndex.isValid():\n            return\n        self.model().deleteItemAtIndex(currentIndex)",
    "docstring": "Removes the current item from the repository tree."
  },
  {
    "code": "def ebalance(sdat, tstart=None, tend=None):\n    tseries = sdat.tseries_between(tstart, tend)\n    rbot, rtop = misc.get_rbounds(sdat.steps.last)\n    if rbot != 0:\n        coefsurf = (rtop / rbot)**2\n        volume = rbot * ((rtop / rbot)**3 - 1) / 3\n    else:\n        coefsurf = 1.\n        volume = 1.\n    dtdt, time = dt_dt(sdat, tstart, tend)\n    ftop = tseries['ftop'].values * coefsurf\n    fbot = tseries['fbot'].values\n    radio = tseries['H_int'].values\n    ebal = ftop[1:] - fbot[1:] + volume * (dtdt - radio[1:])\n    return ebal, time",
    "docstring": "Energy balance.\n\n    Compute Nu_t - Nu_b + V*dT/dt as a function of time using an explicit\n    Euler scheme. This should be zero if energy is conserved.\n\n    Args:\n        sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.\n        tstart (float): time at which the computation should start. Use the\n            beginning of the time series data if set to None.\n        tend (float): time at which the computation should end. Use the\n            end of the time series data if set to None.\n    Returns:\n        tuple of :class:`numpy.array`: energy balance and time arrays."
  },
  {
    "code": "def choose(self):\n        if not self.choosed:\n            self.choosed = True\n            self.pos = self.pos + Sep(5, 0)",
    "docstring": "Marks the item as the one the user is in."
  },
  {
    "code": "def RegisterAnyElement(cls):\n        for k,v in cls.types_dict.items():\n            what = Any.serialmap.get(k)\n            if what is None: continue\n            if v in what.__class__.seriallist: continue\n            what.__class__.seriallist.append(v)\n            RegisterType(what.__class__, clobber=1, **what.__dict__)",
    "docstring": "If find registered TypeCode instance, add Wrapper class \n        to TypeCode class serialmap and Re-RegisterType.  Provides\n        Any serialzation of any instances of the Wrapper."
  },
  {
    "code": "def policy(self, args):\n        word = args[0]\n        if word == 'reject':\n            self.accepted_ports = None\n            self.rejected_ports = []\n            target = self.rejected_ports\n        elif word == 'accept':\n            self.accepted_ports = []\n            self.rejected_ports = None\n            target = self.accepted_ports\n        else:\n            raise RuntimeError(\"Don't understand policy word \\\"%s\\\"\" % word)\n        for port in args[1].split(','):\n            if '-' in port:\n                (a, b) = port.split('-')\n                target.append(PortRange(int(a), int(b)))\n            else:\n                target.append(int(port))",
    "docstring": "setter for the policy descriptor"
  },
  {
    "code": "def evaluateQuotes(self, argument):\r\n        r = set()\r\n        search_terms = []\r\n        for item in argument:\r\n            search_terms.append(item[0])\r\n            if len(r) == 0:\r\n                r = self.evaluate(item)\r\n            else:\r\n                r = r.intersection(self.evaluate(item))\r\n        return self.GetQuotes(' '.join(search_terms), r)",
    "docstring": "Evaluate quoted strings\r\n\r\n        First is does an 'and' on the indidual search terms, then it asks the\r\n        function GetQuoted to only return the subset of ID's that contain the\r\n        literal string."
  },
  {
    "code": "def before_event(self, event):\n        if event not in [\"prev_page\", \"next_page\"]:\n            while self.history.position < self.history.size:\n                self.next_page()",
    "docstring": "Ensure a screen is at the bottom of the history buffer.\n\n        :param str event: event name, for example ``\"linefeed\"``."
  },
  {
    "code": "def _batched_write_command(\n        namespace, operation, command, docs, check_keys, opts, ctx):\n    buf = StringIO()\n    buf.write(_ZERO_64)\n    buf.write(b\"\\x00\\x00\\x00\\x00\\xd4\\x07\\x00\\x00\")\n    to_send, length = _batched_write_command_impl(\n        namespace, operation, command, docs, check_keys, opts, ctx, buf)\n    buf.seek(4)\n    request_id = _randint()\n    buf.write(_pack_int(request_id))\n    buf.seek(0)\n    buf.write(_pack_int(length))\n    return request_id, buf.getvalue(), to_send",
    "docstring": "Create the next batched insert, update, or delete command."
  },
  {
    "code": "def get_industry_index(self, index_id,items=None):\n        response = self.select('yahoo.finance.industry',items).where(['id','=',index_id])\n        return response",
    "docstring": "retrieves all symbols that belong to an industry."
  },
  {
    "code": "def sd(d,**kw):\n    r={};\n    r.update(d);\n    r.update(kw);\n    return r;",
    "docstring": "A hack to return a modified dict dynamically. Basically,\n    Does \"classless OOP\" as in js but with dicts, although\n    not really for the \"verb\" parts of OOP but more of the\n    \"subject\" stuff.\n\n    Confused? Here's how it works:\n\n    `d` is a dict. We have that\n\n    sd(d, perfect=42, gf='qt3.14')\n\n    returns a dict like d but with d['perfect']==42 and\n    d['gf']=='qt3.14'. 'sd' stands for \"setdefault\" which is,\n    you know, what we do when we set elements of a dict.\n    \n    I plan to  use this heavily."
  },
  {
    "code": "def addthisbunch(bunchdt, data, commdct, thisbunch, theidf):\n    key = thisbunch.key.upper()\n    obj = copy.copy(thisbunch.obj)\n    abunch = obj2bunch(data, commdct, obj)\n    bunchdt[key].append(abunch)\n    return abunch",
    "docstring": "add a bunch to model.\n    abunch usually comes from another idf file\n    or it can be used to copy within the idf file"
  },
  {
    "code": "def DEFINE_enum(\n    name, default, enum_values, help, flag_values=FLAGS, module_name=None,\n    **args):\n  DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args),\n              flag_values, module_name)",
    "docstring": "Registers a flag whose value can be any string from enum_values.\n\n  Args:\n    name: A string, the flag name.\n    default: The default value of the flag.\n    enum_values: A list of strings with the possible values for the flag.\n    help: A help string.\n    flag_values: FlagValues object with which the flag will be registered.\n    module_name: A string, the name of the Python module declaring this flag.\n        If not provided, it will be computed using the stack trace of this call.\n    **args: Dictionary with extra keyword args that are passed to the\n        Flag __init__."
  },
  {
    "code": "def _GetRowValue(self, query_hash, row, value_name):\n    keys_name_to_index_map = self._keys_per_query.get(query_hash, None)\n    if not keys_name_to_index_map:\n      keys_name_to_index_map = {\n          name: index for index, name in enumerate(row.keys())}\n      self._keys_per_query[query_hash] = keys_name_to_index_map\n    value_index = keys_name_to_index_map.get(value_name)\n    return row[value_index]",
    "docstring": "Retrieves a value from the row.\n\n    Args:\n      query_hash (int): hash of the query, that uniquely identifies the query\n          that produced the row.\n      row (sqlite3.Row): row.\n      value_name (str): name of the value.\n\n    Returns:\n      object: value."
  },
  {
    "code": "def option(value, is_default=False, label=None):\n    _annotate(\"option\", value, is_default=is_default, label=label)",
    "docstring": "Annotates a possible value for IValueOptions,\n    will be validated at instance creation time.\n\n    @param value:      a possible value for the IValueOptions being defined.\n    @type  value:      Any\n    @param is_default: if the option should be the default value.\n    @type  is_default: bool\n    @param label:      option label or None; if none the string representation\n                       of the value will be used as label.\n    @type  label:      str or unicode or None"
  },
  {
    "code": "def except_(self, arguments):\n        if not isinstance(arguments, list):\n            arguments = list(arguments)\n        args = self.request.arguments\n        data = {}\n        for key, value in args.items():\n            if key not in arguments:\n                data[key] = self.get_argument(key)\n        return data",
    "docstring": "returns the arguments passed to the route except that set by user\n\n        Sample Usage\n        ++++++++++++++\n        .. code:: python\n\n            from bast import Controller\n\n            class MyController(Controller):\n                def index(self):\n                    data = self.except_(['arg_name'])\n\n        Returns a dictionary of all arguments except for that provided by as ``arg_name``"
  },
  {
    "code": "def clear_bg(self, which_data=(\"amplitude\", \"phase\"), keys=\"fit\"):\n        which_data = QPImage._conv_which_data(which_data)\n        if isinstance(keys, str):\n            keys = [keys]\n        imdats = []\n        if \"amplitude\" in which_data:\n            imdats.append(self._amp)\n        if \"phase\" in which_data:\n            imdats.append(self._pha)\n        if not imdats:\n            msg = \"`which_data` must contain 'phase' or 'amplitude'!\"\n            raise ValueError(msg)\n        for imdat in imdats:\n            for key in keys:\n                imdat.del_bg(key)",
    "docstring": "Clear background correction\n\n        Parameters\n        ----------\n        which_data: str or list of str\n            From which type of data to remove the background\n            information. The list contains either \"amplitude\",\n            \"phase\", or both.\n        keys: str or list of str\n            Which type of background data to remove. One of:\n\n            - \"fit\": the background data computed with\n              :func:`qpimage.QPImage.compute_bg`\n            - \"data\": the experimentally obtained background image"
  },
  {
    "code": "def userCreate(self, request, tag):\n        userCreator = liveform.LiveForm(\n            self.createUser,\n            [liveform.Parameter(\n                    \"localpart\",\n                    liveform.TEXT_INPUT,\n                    unicode,\n                    \"localpart\"),\n             liveform.Parameter(\n                    \"domain\",\n                    liveform.TEXT_INPUT,\n                    unicode,\n                    \"domain\"),\n             liveform.Parameter(\n                    \"password\",\n                    liveform.PASSWORD_INPUT,\n                    unicode,\n                    \"password\")])\n        userCreator.setFragmentParent(self)\n        return userCreator",
    "docstring": "Render a form for creating new users."
  },
  {
    "code": "def clear(self, timestamp):\n        self.storage.clear()\n        self.push(streams.DATA_CLEARED, timestamp, 1)",
    "docstring": "Clear all data from the RSL.\n\n        This pushes a single reading once we clear everything so that\n        we keep track of the highest ID that we have allocated to date.\n\n        This needs the current timestamp to be able to properly timestamp\n        the cleared storage reading that it pushes.\n\n        Args:\n            timestamp (int): The current timestamp to store with the\n                reading."
  },
  {
    "code": "def build_one_definition_example(self, def_name):\n        if def_name in self.definitions_example.keys():\n            return True\n        elif def_name not in self.specification['definitions'].keys():\n            return False\n        self.definitions_example[def_name] = {}\n        def_spec = self.specification['definitions'][def_name]\n        if def_spec.get('type') == 'array' and 'items' in def_spec:\n            item = self.get_example_from_prop_spec(def_spec['items'])\n            self.definitions_example[def_name] = [item]\n            return True\n        if 'properties' not in def_spec:\n            self.definitions_example[def_name] = self.get_example_from_prop_spec(def_spec)\n            return True\n        for prop_name, prop_spec in def_spec['properties'].items():\n            example = self.get_example_from_prop_spec(prop_spec)\n            if example is None:\n                return False\n            self.definitions_example[def_name][prop_name] = example\n        return True",
    "docstring": "Build the example for the given definition.\n\n        Args:\n            def_name: Name of the definition.\n\n        Returns:\n            True if the example has been created, False if an error occured."
  },
  {
    "code": "def _save(self):\r\n        fname = self.filename()\r\n        def _write_file(fname):\r\n            if PY2:\r\n                with codecs.open(fname, 'w', encoding='utf-8') as configfile:\r\n                    self._write(configfile)\r\n            else:\r\n                with open(fname, 'w', encoding='utf-8') as configfile:\r\n                    self.write(configfile)\r\n        try:\n            _write_file(fname)\r\n        except EnvironmentError:\r\n            try:\n                if osp.isfile(fname):\r\n                    os.remove(fname)\r\n                time.sleep(0.05)\r\n                _write_file(fname)\r\n            except Exception as e:\r\n                print(\"Failed to write user configuration file to disk, with \"\r\n                      \"the exception shown below\")\n                print(e)",
    "docstring": "Save config into the associated .ini file"
  },
  {
    "code": "def _draw_using_figure(self, figure, axs):\n        self = deepcopy(self)\n        self._build()\n        self.theme = self.theme or theme_get()\n        self.figure = figure\n        self.axs = axs\n        try:\n            with mpl.rc_context():\n                self.theme.apply_rcparams()\n                self._setup_parameters()\n                self._draw_layers()\n                self._draw_facet_labels()\n                self._draw_legend()\n                self._apply_theme()\n        except Exception as err:\n            if self.figure is not None:\n                plt.close(self.figure)\n            raise err\n        return self",
    "docstring": "Draw onto already created figure and axes\n\n        This is can be used to draw animation frames,\n        or inset plots. It is intended to be used\n        after the key plot has been drawn.\n\n        Parameters\n        ----------\n        figure : ~matplotlib.figure.Figure\n            Matplotlib figure\n        axs : array_like\n            Array of Axes onto which to draw the plots"
  },
  {
    "code": "def add_in(self, delay: float, fn_process: Callable, *args: Any, **kwargs: Any) -> 'Process':\n        process = Process(self, fn_process, self._gr)\n        if _logger is not None:\n            self._log(INFO, \"add\", __now=self.now(), fn=fn_process, args=args, kwargs=kwargs)\n        self._schedule(delay, process.switch, *args, **kwargs)\n        return process",
    "docstring": "Adds a process to the simulation, which is made to start after the given delay in simulated time.\n\n        See method add() for more details."
  },
  {
    "code": "def cancelPnL(self, account, modelCode: str = ''):\n        key = (account, modelCode)\n        reqId = self.wrapper.pnlKey2ReqId.pop(key, None)\n        if reqId:\n            self.client.cancelPnL(reqId)\n            self.wrapper.pnls.pop(reqId, None)\n        else:\n            self._logger.error(\n                'cancelPnL: No subscription for '\n                f'account {account}, modelCode {modelCode}')",
    "docstring": "Cancel PnL subscription.\n\n        Args:\n            account: Cancel for this account.\n            modelCode: If specified, cancel for this account model."
  },
  {
    "code": "def find(self, *args, **kwargs):\n    \" new query builder on current db\"\n    return Query(*args, db=self, schema=self.schema)",
    "docstring": "new query builder on current db"
  },
  {
    "code": "def lu_decomposition(matrix_a):\n    q = len(matrix_a)\n    for idx, m_a in enumerate(matrix_a):\n        if len(m_a) != q:\n            raise ValueError(\"The input must be a square matrix. \" +\n                             \"Row \" + str(idx + 1) + \" has a size of \" + str(len(m_a)) + \".\")\n    return _linalg.doolittle(matrix_a)",
    "docstring": "LU-Factorization method using Doolittle's Method for solution of linear systems.\n\n    Decomposes the matrix :math:`A` such that :math:`A = LU`.\n\n    The input matrix is represented by a list or a tuple. The input matrix is **2-dimensional**, i.e. list of lists of\n    integers and/or floats.\n\n    :param matrix_a: Input matrix (must be a square matrix)\n    :type matrix_a: list, tuple\n    :return: a tuple containing matrices L and U\n    :rtype: tuple"
  },
  {
    "code": "def load_from_file(self, yamlfile, _override=True, _allow_undeclared=False):\n    self._logger.info('Loading configuration from file: %s', yamlfile)\n    try:\n      parsed_yaml = self._modules['yaml'].safe_load(yamlfile.read())\n    except self._modules['yaml'].YAMLError:\n      self._logger.exception('Problem parsing YAML')\n      raise self.ConfigurationInvalidError(\n          'Failed to load from %s as YAML' % yamlfile)\n    if not isinstance(parsed_yaml, dict):\n      raise self.ConfigurationInvalidError(\n          'YAML parsed, but wrong type, should be dict', parsed_yaml)\n    self._logger.debug('Configuration loaded from file: %s', parsed_yaml)\n    self.load_from_dict(\n        parsed_yaml, _override=_override, _allow_undeclared=_allow_undeclared)",
    "docstring": "Loads the configuration from a file.\n\n    Parsed contents must be a single dict mapping config key to value.\n\n    Args:\n      yamlfile: The opened file object to load configuration from.\n      See load_from_dict() for other args' descriptions.\n\n    Raises:\n      ConfigurationInvalidError: If configuration file can't be read, or can't\n          be parsed as either YAML (or JSON, which is a subset of YAML)."
  },
  {
    "code": "def dealias_image(alias):\n    with Session() as session:\n        try:\n            result = session.Image.dealiasImage(alias)\n        except Exception as e:\n            print_error(e)\n            sys.exit(1)\n        if result['ok']:\n            print(\"alias {0} removed.\".format(alias))\n        else:\n            print(result['msg'])",
    "docstring": "Remove an image alias."
  },
  {
    "code": "def get_ser_val_alt(lat: float, lon: float,\n                    da_alt_x: xr.DataArray,\n                    da_alt: xr.DataArray, da_val: xr.DataArray)->pd.Series:\n    alt_t_1d = da_alt.sel(\n        latitude=lat, longitude=lon, method='nearest')\n    val_t_1d = da_val.sel(\n        latitude=lat, longitude=lon, method='nearest')\n    alt_x = da_alt_x.sel(\n        latitude=lat, longitude=lon, method='nearest')[0]\n    val_alt = np.array(\n        [interp1d(alt_1d, val_1d)(alt_x)\n         for alt_1d, val_1d\n         in zip(alt_t_1d, val_t_1d)])\n    ser_alt = pd.Series(\n        val_alt,\n        index=da_val.time.values,\n        name=da_val.name,\n    )\n    return ser_alt",
    "docstring": "interpolate atmospheric variable to a specified altitude\n\n    Parameters\n    ----------\n    lat : float\n        latitude of specified site\n    lon : float\n        longitude of specified site\n    da_alt_x : xr.DataArray\n        desired altitude to interpolate variable at\n    da_alt : xr.DataArray\n        altitude associated with `da_val`: variable array to interpolate\n    da_val : xr.DataArray\n        atmospheric varialble to interpolate\n\n    Returns\n    -------\n    pd.Series\n        interpolated values at the specified altitude of site positioned by [`lat`, `lon`]"
  },
  {
    "code": "def eval_first_non_none(eval_list: Iterable[Callable[..., Any]], **kwargs: Any) -> Any:\n    Validator.is_real_iterable(raise_ex=True, eval_list=eval_list)\n    for eval_fun in eval_list:\n        res = eval_fun(**kwargs)\n        if res is not None:\n            return res\n    return None",
    "docstring": "Executes a list of functions and returns the first non none result. All kwargs will be passed as\n    kwargs to each individual function. If all functions return None, None is the overall result.\n\n    Examples:\n\n        >>> eval_first_non_none((lambda: None, lambda: None, lambda: 3))\n        3\n        >>> print(eval_first_non_none([lambda: None, lambda: None, lambda: None]))\n        None\n        >>> eval_first_non_none([\n        ...     lambda cnt: cnt if cnt == 1 else None,\n        ...     lambda cnt: cnt if cnt == 2 else None,\n        ...     lambda cnt: cnt if cnt == 3 else None]\n        ... , cnt=2)\n        2"
  },
  {
    "code": "def sheetDeleteEmpty(bookName=None):\n    if bookName is None:\n        bookName = activeBook()\n    if not bookName.lower() in [x.lower() for x in bookNames()]:\n        print(\"can't clean up a book that doesn't exist:\",bookName)\n        return\n    poBook=PyOrigin.WorksheetPages(bookName)\n    namesToKill=[]\n    for i,poSheet in enumerate([poSheet for poSheet in poBook.Layers()]):\n        poFirstCol=poSheet.Columns(0)\n        if poFirstCol.GetLongName()==\"\" and poFirstCol.GetData()==[]:\n            namesToKill.append(poSheet.GetName())\n    for sheetName in namesToKill:\n        print(\"deleting empty sheet\",sheetName)\n        sheetDelete(bookName,sheetName)",
    "docstring": "Delete all sheets which contain no data"
  },
  {
    "code": "def less_than(self, less_than):\n        if hasattr(less_than, 'strftime'):\n            less_than = datetime_as_utc(less_than).strftime('%Y-%m-%d %H:%M:%S')\n        elif isinstance(less_than, six.string_types):\n            raise QueryTypeError('Expected value of type `int` or instance of `datetime`, not %s' % type(less_than))\n        return self._add_condition('<', less_than, types=[int, str])",
    "docstring": "Adds new `<` condition\n\n        :param less_than: str or datetime compatible object (naive UTC datetime or tz-aware datetime)\n        :raise:\n            - QueryTypeError: if `less_than` is of an unexpected type"
  },
  {
    "code": "def set_python(self, value):\n        if not isinstance(value, (list, type(None))):\n            raise ValidationError(\n                self.record,\n                \"Field '{}' must be set to a list, not '{}'\".format(\n                    self.name,\n                    value.__class__\n                )\n            )\n        value = value or []\n        self.cursor._validate_list(value)\n        return super(ListField, self).set_python(value)",
    "docstring": "Validate using cursor for consistency between direct set of values vs modification of cursor values"
  },
  {
    "code": "def get_services_by_explosion(self, servicegroups):\n        self.already_exploded = True\n        if self.rec_tag:\n            logger.error(\"[servicegroup::%s] got a loop in servicegroup definition\",\n                         self.get_name())\n            if hasattr(self, 'members'):\n                return self.members\n            return ''\n        self.rec_tag = True\n        sg_mbrs = self.get_servicegroup_members()\n        for sg_mbr in sg_mbrs:\n            servicegroup = servicegroups.find_by_name(sg_mbr.strip())\n            if servicegroup is not None:\n                value = servicegroup.get_services_by_explosion(servicegroups)\n                if value is not None:\n                    self.add_members(value)\n        if hasattr(self, 'members'):\n            return self.members\n        return ''",
    "docstring": "Get all services of this servicegroup and add it in members container\n\n        :param servicegroups: servicegroups object\n        :type servicegroups: alignak.objects.servicegroup.Servicegroups\n        :return: return empty string or list of members\n        :rtype: str or list"
  },
  {
    "code": "def get_expiration_seconds_v2(expiration):\n    if isinstance(expiration, datetime.timedelta):\n        now = NOW().replace(tzinfo=_helpers.UTC)\n        expiration = now + expiration\n    if isinstance(expiration, datetime.datetime):\n        micros = _helpers._microseconds_from_datetime(expiration)\n        expiration = micros // 10 ** 6\n    if not isinstance(expiration, six.integer_types):\n        raise TypeError(\n            \"Expected an integer timestamp, datetime, or \"\n            \"timedelta. Got %s\" % type(expiration)\n        )\n    return expiration",
    "docstring": "Convert 'expiration' to a number of seconds in the future.\n\n    :type expiration: Union[Integer, datetime.datetime, datetime.timedelta]\n    :param expiration: Point in time when the signed URL should expire.\n\n    :raises: :exc:`TypeError` when expiration is not a valid type.\n\n    :rtype: int\n    :returns: a timestamp as an absolute number of seconds since epoch."
  },
  {
    "code": "def draw_rect(\n        self,\n        x: int,\n        y: int,\n        width: int,\n        height: int,\n        ch: int,\n        fg: Optional[Tuple[int, int, int]] = None,\n        bg: Optional[Tuple[int, int, int]] = None,\n        bg_blend: int = tcod.constants.BKGND_SET,\n    ) -> None:\n        x, y = self._pythonic_index(x, y)\n        lib.draw_rect(\n            self.console_c,\n            x,\n            y,\n            width,\n            height,\n            ch,\n            (fg,) if fg is not None else ffi.NULL,\n            (bg,) if bg is not None else ffi.NULL,\n            bg_blend,\n        )",
    "docstring": "Draw characters and colors over a rectangular region.\n\n        `x` and `y` are the starting tile, with ``0,0`` as the upper-left\n        corner of the console.  You can use negative numbers if you want to\n        start printing relative to the bottom-right corner, but this behavior\n        may change in future versions.\n\n        `width` and `height` determine the size of the rectangle.\n\n        `ch` is a Unicode integer.  You can use 0 to leave the current\n        characters unchanged.\n\n        `fg` and `bg` are the foreground text color and background tile color\n        respectfully.  This is a 3-item tuple with (r, g, b) color values from\n        0 to 255.  These parameters can also be set to `None` to leave the\n        colors unchanged.\n\n        `bg_blend` is the blend type used by libtcod.\n\n        .. versionadded:: 8.5\n\n        .. versionchanged:: 9.0\n            `fg` and `bg` now default to `None` instead of white-on-black."
  },
  {
    "code": "def create_tileset(ctx, dataset, tileset, name):\n    access_token = (ctx.obj and ctx.obj.get('access_token')) or None\n    service = mapbox.Uploader(access_token=access_token)\n    uri = \"mapbox://datasets/{username}/{dataset}\".format(\n        username=tileset.split('.')[0], dataset=dataset)\n    res = service.create(uri, tileset, name)\n    if res.status_code == 201:\n        click.echo(res.text)\n    else:\n        raise MapboxCLIException(res.text.strip())",
    "docstring": "Create a vector tileset from a dataset.\n\n        $ mapbox datasets create-tileset dataset-id username.data\n\n    Note that the tileset must start with your username and the dataset\n    must be one that you own. To view processing status, visit\n    https://www.mapbox.com/data/. You may not generate another tilesets\n    from the same dataset until the first processing job has completed.\n\n    All endpoints require authentication. An access token with\n    `uploads:write` scope is required, see `mapbox --help`."
  },
  {
    "code": "def get_onchain_exchange_rates(deposit_crypto=None, withdraw_crypto=None, **modes):\n    from moneywagon.onchain_exchange import ALL_SERVICES\n    rates = []\n    for Service in ALL_SERVICES:\n        srv = Service(verbose=modes.get('verbose', False))\n        rates.extend(srv.onchain_exchange_rates())\n    if deposit_crypto:\n        rates = [x for x in rates if x['deposit_currency']['code'] == deposit_crypto.upper()]\n    if withdraw_crypto:\n        rates = [x for x in rates if x['withdraw_currency']['code'] == withdraw_crypto.upper()]\n    if modes.get('best', False):\n        return max(rates, key=lambda x: float(x['rate']))\n    return rates",
    "docstring": "Gets exchange rates for all defined on-chain exchange services."
  },
  {
    "code": "def dbg(*objects, file=sys.stderr, flush=True, **kwargs):\n    \"Helper function to print to stderr and flush\"\n    print(*objects, file=file, flush=flush, **kwargs)",
    "docstring": "Helper function to print to stderr and flush"
  },
  {
    "code": "def memory_zones(self):\n        count = self.num_memory_zones()\n        if count == 0:\n            return list()\n        buf = (structs.JLinkMemoryZone * count)()\n        res = self._dll.JLINK_GetMemZones(buf, count)\n        if res < 0:\n            raise errors.JLinkException(res)\n        return list(buf)",
    "docstring": "Gets all memory zones supported by the current target.\n\n        Some targets support multiple memory zones.  This function provides the\n        ability to get a list of all the memory zones to facilate using the\n        memory zone routing functions.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n\n        Returns:\n          A list of all the memory zones as ``JLinkMemoryZone`` structures.\n\n        Raises:\n          JLinkException: on hardware errors."
  },
  {
    "code": "def _get_stddevs(self, dists, mag, dctx, imt, stddev_types):\n        stddevs = []\n        for stddev_type in stddev_types:\n            if stddev_type not in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES:\n                raise ValueError(\"Standard Deviation type %s not supported\"\n                                 % stddev_type)\n            sigma = self._return_tables(mag, imt, stddev_type)\n            interpolator_std = interp1d(dists, sigma,\n                                        bounds_error=False)\n            stddev = interpolator_std(getattr(dctx, self.distance_type))\n            stddev[getattr(dctx, self.distance_type) < dists[0]] = sigma[0]\n            stddev[getattr(dctx, self.distance_type) > dists[-1]] = sigma[-1]\n            stddevs.append(stddev)\n        return stddevs",
    "docstring": "Returns the total standard deviation of the intensity measure level\n        from the tables.\n\n        :param fle:\n            HDF5 data stream as instance of :class:`h5py.File`\n        :param distances:\n            The distance vector for the given magnitude and IMT\n        :param key:\n            The distance type\n        :param mag:\n            The rupture magnitude"
  },
  {
    "code": "def noninjectable(*args):\n    def decorator(function):\n        argspec = inspect.getfullargspec(inspect.unwrap(function))\n        for arg in args:\n            if arg not in argspec.args and arg not in argspec.kwonlyargs:\n                raise UnknownArgument('Unable to mark unknown argument %s ' 'as non-injectable.' % arg)\n        existing = getattr(function, '__noninjectables__', set())\n        merged = existing | set(args)\n        function.__noninjectables__ = merged\n        return function\n    return decorator",
    "docstring": "Mark some parameters as not injectable.\n\n    This serves as documentation for people reading the code and will prevent\n    Injector from ever attempting to provide the parameters.\n\n    For example:\n\n    >>> class Service:\n    ...    pass\n    ...\n    >>> class SomeClass:\n    ...     @inject\n    ...     @noninjectable('user_id')\n    ...     def __init__(self, service: Service, user_id: int):\n    ...         # ...\n    ...         pass\n\n    :func:`noninjectable` decorations can be stacked on top of\n    each other and the order in which a function is decorated with\n    :func:`inject` and :func:`noninjectable`\n    doesn't matter."
  },
  {
    "code": "def set_run_on_node_mask(nodemask):\n    mask = set_to_numa_nodemask(nodemask)\n    tmp = bitmask_t()\n    tmp.maskp = cast(byref(mask), POINTER(c_ulong))\n    tmp.size = sizeof(nodemask_t) * 8\n    if libnuma.numa_run_on_node_mask(byref(tmp)) < 0:\n        raise RuntimeError()",
    "docstring": "Runs the  current thread and its children only on nodes specified in nodemask.\n\n    They will not migrate to CPUs of other nodes until the node affinity is\n    reset with a new call to L{set_run_on_node_mask}.\n\n    @param nodemask: node mask\n    @type nodemask: C{set}"
  },
  {
    "code": "def sync_groups_from_ad(self):\n        ad_list = ADGroupMapping.objects.values_list('ad_group', 'group')\n        mappings = {ad_group: group for ad_group, group in ad_list}\n        user_ad_groups = set(self.ad_groups.filter(groups__isnull=False).values_list(flat=True))\n        all_mapped_groups = set(mappings.values())\n        old_groups = set(self.groups.filter(id__in=all_mapped_groups).values_list(flat=True))\n        new_groups = set([mappings[x] for x in user_ad_groups])\n        groups_to_delete = old_groups - new_groups\n        if groups_to_delete:\n            self.groups.remove(*groups_to_delete)\n        groups_to_add = new_groups - old_groups\n        if groups_to_add:\n            self.groups.add(*groups_to_add)",
    "docstring": "Determine which Django groups to add or remove based on AD groups."
  },
  {
    "code": "def filter_macro(func, *args, **kwargs):\n    filter_partial = partial(func, *args, **kwargs)\n    class FilterMacroMeta(FilterMeta):\n        @staticmethod\n        def __new__(mcs, name, bases, attrs):\n            for attr in WRAPPER_ASSIGNMENTS:\n                if hasattr(func, attr):\n                    attrs[attr] = getattr(func, attr)\n            return super(FilterMacroMeta, mcs)\\\n                .__new__(mcs, func.__name__, bases, attrs)\n        def __call__(cls, *runtime_args, **runtime_kwargs):\n            return filter_partial(*runtime_args, **runtime_kwargs)\n    class FilterMacro(with_metaclass(FilterMacroMeta, FilterMacroType)):\n        def _apply(self, value):\n            return self.__class__()._apply(value)\n    return FilterMacro",
    "docstring": "Promotes a function that returns a filter into its own filter type.\n\n    Example::\n\n        @filter_macro\n        def String():\n            return Unicode | Strip | NotEmpty\n\n        # You can now use `String` anywhere you would use a regular Filter:\n        (String | Split(':')).apply('...')\n\n    You can also use ``filter_macro`` to create partials, allowing you to\n    preset one or more initialization arguments::\n\n        Minor = filter_macro(Max, max_value=18, inclusive=False)\n        Minor(inclusive=True).apply(18)"
  },
  {
    "code": "def create(graph, label_field,\n           threshold=1e-3,\n           weight_field='',\n           self_weight=1.0,\n           undirected=False,\n           max_iterations=None,\n           _single_precision=False,\n           _distributed='auto',\n           verbose=True):\n    from turicreate._cython.cy_server import QuietProgress\n    _raise_error_if_not_of_type(label_field, str)\n    _raise_error_if_not_of_type(weight_field, str)\n    if not isinstance(graph, _SGraph):\n        raise TypeError('graph input must be a SGraph object.')\n    if graph.vertices[label_field].dtype != int:\n        raise TypeError('label_field %s must be integer typed.' % label_field)\n    opts = {'label_field': label_field,\n            'threshold': threshold,\n            'weight_field': weight_field,\n            'self_weight': self_weight,\n            'undirected': undirected,\n            'max_iterations': max_iterations,\n            'single_precision': _single_precision,\n            'graph': graph.__proxy__}\n    with QuietProgress(verbose):\n        params = _tc.extensions._toolkits.graph.label_propagation.create(opts)\n    model = params['model']\n    return LabelPropagationModel(model)",
    "docstring": "Given a weighted graph with observed class labels of a subset of vertices,\n    infer the label probability for the unobserved vertices using the\n    \"label propagation\" algorithm.\n\n    The algorithm iteratively updates the label probability of current vertex\n    as a weighted sum of label probability of self and the neighboring vertices\n    until converge.  See\n    :class:`turicreate.label_propagation.LabelPropagationModel` for the details\n    of the algorithm.\n\n    Notes: label propagation works well with small number of labels, i.e. binary\n    labels, or less than 1000 classes. The toolkit will throw error\n    if the number of classes exceeds the maximum value (1000).\n\n    Parameters\n    ----------\n    graph : SGraph\n        The graph on which to compute the label propagation.\n\n    label_field: str\n        Vertex field storing the initial vertex labels. The values in\n        must be [0, num_classes). None values indicate unobserved vertex labels.\n\n    threshold : float, optional\n        Threshold for convergence, measured in the average L2 norm\n        (the sum of squared values) of the delta of each vertex's\n        label probability vector.\n\n    max_iterations: int, optional\n        The max number of iterations to run. Default is unlimited.\n        If set, the algorithm terminates when either max_iterations\n        or convergence threshold is reached.\n\n    weight_field: str, optional\n        Vertex field for edge weight. If empty, all edges are assumed\n        to have unit weight.\n\n    self_weight: float, optional\n        The weight for self edge.\n\n    undirected: bool, optional\n        If true, treat each edge as undirected, and propagates label in\n        both directions.\n\n    _single_precision : bool, optional\n        If true, running label propagation in single precision. The resulting\n        probability values may less accurate, but should run faster\n        and use less memory.\n\n    _distributed : distributed environment, internal\n\n    verbose : bool, optional\n        If True, print progress updates.\n\n    Returns\n    -------\n    out : LabelPropagationModel\n\n    References\n    ----------\n    - Zhu, X., & Ghahramani, Z. (2002). `Learning from labeled and unlabeled data\n      with label propagation <http://www.cs.cmu.edu/~zhuxj/pub/CMU-CALD-02-107.pdf>`_.\n\n    Examples\n    --------\n    If given an :class:`~turicreate.SGraph` ``g``, we can create\n    a :class:`~turicreate.label_propagation.LabelPropagationModel` as follows:\n\n    >>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/email-Enron.txt.gz',\n    ...                         format='snap')\n    # Initialize random classes for a subset of vertices\n    # Leave the unobserved vertices with None label.\n    >>> import random\n    >>> def init_label(vid):\n    ...     x = random.random()\n    ...     if x < 0.2:\n    ...         return 0\n    ...     elif x > 0.9:\n    ...         return 1\n    ...     else:\n    ...         return None\n    >>> g.vertices['label'] = g.vertices['__id'].apply(init_label, int)\n    >>> m = turicreate.label_propagation.create(g, label_field='label')\n\n    We can obtain for each vertex the predicted label and the probability of\n    each label in the graph ``g`` using:\n\n    >>> labels = m['labels']     # SFrame\n    >>> labels\n    +------+-------+-----------------+-------------------+----------------+\n    | __id | label | predicted_label |         P0        |       P1       |\n    +------+-------+-----------------+-------------------+----------------+\n    |  5   |   1   |        1        |        0.0        |      1.0       |\n    |  7   |  None |        0        |    0.8213214997   |  0.1786785003  |\n    |  8   |  None |        1        | 5.96046447754e-08 | 0.999999940395 |\n    |  10  |  None |        0        |   0.534984718273  | 0.465015281727 |\n    |  27  |  None |        0        |   0.752801638549  | 0.247198361451 |\n    |  29  |  None |        1        | 5.96046447754e-08 | 0.999999940395 |\n    |  33  |  None |        1        | 5.96046447754e-08 | 0.999999940395 |\n    |  47  |   0   |        0        |        1.0        |      0.0       |\n    |  50  |  None |        0        |   0.788279032657  | 0.211720967343 |\n    |  52  |  None |        0        |   0.666666666667  | 0.333333333333 |\n    +------+-------+-----------------+-------------------+----------------+\n    [36692 rows x 5 columns]\n\n    See Also\n    --------\n    LabelPropagationModel"
  },
  {
    "code": "def _self_event(self, event_name, cmd, *pargs, **kwargs):\n        if hasattr(self, event_name):\n            getattr(self, event_name)(cmd, *pargs, **kwargs)",
    "docstring": "Call self event"
  },
  {
    "code": "def recurse(node, *args, **kwargs):\n    fwd = dict()\n    for node_info in _NODE_INFO_TABLE.values():\n        fwd[node_info.handler] = kwargs.get(node_info.handler, None)\n    fwd[\"depth\"] = 0\n    _recurse(node, *args, **fwd)",
    "docstring": "Entry point for AST recursion."
  },
  {
    "code": "def linkify_contactgroups_contacts(self, contacts):\n        for contactgroup in self:\n            mbrs = contactgroup.get_contacts()\n            new_mbrs = []\n            for mbr in mbrs:\n                mbr = mbr.strip()\n                if mbr == '':\n                    continue\n                member = contacts.find_by_name(mbr)\n                if member is not None:\n                    new_mbrs.append(member.uuid)\n                else:\n                    contactgroup.add_unknown_members(mbr)\n            new_mbrs = list(set(new_mbrs))\n            contactgroup.replace_members(new_mbrs)",
    "docstring": "Link the contacts with contactgroups\n\n        :param contacts: realms object to link with\n        :type contacts: alignak.objects.contact.Contacts\n        :return: None"
  },
  {
    "code": "def groups_moderators(self, room_id=None, group=None, **kwargs):\n        if room_id:\n            return self.__call_api_get('groups.moderators', roomId=room_id, kwargs=kwargs)\n        elif group:\n            return self.__call_api_get('groups.moderators', roomName=group, kwargs=kwargs)\n        else:\n            raise RocketMissingParamException('roomId or group required')",
    "docstring": "Lists all moderators of a group."
  },
  {
    "code": "def remove_user(name, profile='github'):\n    client = _get_client(profile)\n    organization = client.get_organization(\n        _get_config_value(profile, 'org_name')\n    )\n    try:\n        git_user = client.get_user(name)\n    except UnknownObjectException:\n        log.exception(\"Resource not found\")\n        return False\n    if organization.has_in_members(git_user):\n        organization.remove_from_members(git_user)\n    return not organization.has_in_members(git_user)",
    "docstring": "Remove a Github user by name.\n\n    name\n        The user for which to obtain information.\n\n    profile\n        The name of the profile configuration to use. Defaults to ``github``.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion github.remove_user github-handle"
  },
  {
    "code": "def finalize_options(self):\n        assert bool(self.fa_version), 'FA version is mandatory for this command.'\n        if self.zip_path:\n            assert os.path.exists(self.zip_path), (\n                'Local zipfile does not exist: %s' % self.zip_path)",
    "docstring": "Validate the command options."
  },
  {
    "code": "def write(self, data):\n    self._check_open()\n    if not isinstance(data, str):\n      raise TypeError('Expected str but got %s.' % type(data))\n    if not data:\n      return\n    self._buffer.append(data)\n    self._buffered += len(data)\n    self._offset += len(data)\n    if self._buffered >= self._flushsize:\n      self._flush()",
    "docstring": "Write some bytes.\n\n    Args:\n      data: data to write. str.\n\n    Raises:\n      TypeError: if data is not of type str."
  },
  {
    "code": "def normalize_release_properties(ensembl_release, species):\n    ensembl_release = check_release_number(ensembl_release)\n    if not isinstance(species, Species):\n        species = find_species_by_name(species)\n    reference_name = species.which_reference(ensembl_release)\n    return ensembl_release, species.latin_name, reference_name",
    "docstring": "Make sure a given release is valid, normalize it to be an integer,\n    normalize the species name, and get its associated reference."
  },
  {
    "code": "def precompute(self, cache_dir=None, swath_usage=0, **kwargs):\n        if kwargs.get('mask') is not None:\n            LOG.warning(\"'mask' parameter has no affect during EWA \"\n                        \"resampling\")\n        del kwargs\n        source_geo_def = self.source_geo_def\n        target_geo_def = self.target_geo_def\n        if cache_dir:\n            LOG.warning(\"'cache_dir' is not used by EWA resampling\")\n        lons, lats = source_geo_def.get_lonlats()\n        if isinstance(lons, xr.DataArray):\n            lons = lons.data\n            lats = lats.data\n        chunks = (2,) + lons.chunks\n        res = da.map_blocks(self._call_ll2cr, lons, lats,\n                            target_geo_def, swath_usage,\n                            dtype=lons.dtype, chunks=chunks, new_axis=[0])\n        cols = res[0]\n        rows = res[1]\n        self.cache = {\n            \"rows\": rows,\n            \"cols\": cols,\n        }\n        return None",
    "docstring": "Generate row and column arrays and store it for later use."
  },
  {
    "code": "def gen_sext(src, dst):\n        assert src.size <= dst.size\n        empty_reg = ReilEmptyOperand()\n        return ReilBuilder.build(ReilMnemonic.SEXT, src, empty_reg, dst)",
    "docstring": "Return a SEXT instruction."
  },
  {
    "code": "def track_purchase(self, user, items, total, purchase_id= None, campaign_id=None, \n\t\t\t\t\t   template_id=None, created_at=None,\n\t\t\t\t\t   data_fields=None):\n\t\tcall=\"/api/commerce/trackPurchase\"\n\t\tpayload ={}\n\t\tif isinstance(user, dict):\n\t\t\tpayload[\"user\"]= user\n\t\telse:\n\t\t\traise TypeError('user key is not in Dictionary format')\n\t\tif isinstance(items, list):\n\t\t\tpayload[\"items\"]= items\n\t\telse:\n\t\t\traise TypeError('items are not in Array format')\n\t\tif isinstance(total, float):\n\t\t\tpayload[\"total\"]= total\n\t\telse:\n\t\t\traise TypeError('total is not in correct format')\n\t\tif purchase_id is not None:\n\t\t\tpayload[\"id\"]= str(purchase_id) \n\t\tif campaign_id is not None:\n\t\t\tpayload[\"campaignId\"]= campaign_id\n\t\tif template_id is not None:\n\t\t\tpayload[\"templateId\"]= template_id\t\t\n\t\tif created_at is not None:\n\t\t\tpayload[\"createdAt\"]= created_at\n\t\tif data_fields is not None:\n\t\t\tpayload[\"data_fields\"]= data_fields\n\t\treturn self.api_call(call=call, method=\"POST\", json=payload)",
    "docstring": "The 'purchase_id' argument maps to 'id' for this API endpoint.\n\t\t\tThis name is used to distinguish it from other instances where\n\t\t\t'id' is a part of the API request with other Iterable endpoints."
  },
  {
    "code": "def _namify_arguments(mapping):\n    result = []\n    for name, parameter in mapping.iteritems():\n        parameter.name = name\n        result.append(parameter)\n    return result",
    "docstring": "Ensure that a mapping of names to parameters has the parameters set to the\n    correct name."
  },
  {
    "code": "def tgread_bool(self):\n        value = self.read_int(signed=False)\n        if value == 0x997275b5:\n            return True\n        elif value == 0xbc799737:\n            return False\n        else:\n            raise RuntimeError('Invalid boolean code {}'.format(hex(value)))",
    "docstring": "Reads a Telegram boolean value."
  },
  {
    "code": "def _get_contents(self):\n        return [\n            str(value) if is_lazy_string(value) else value\n            for value in super(LazyNpmBundle, self)._get_contents()\n        ]",
    "docstring": "Create strings from lazy strings."
  },
  {
    "code": "def get_host(self, use_x_forwarded=True):\n        if use_x_forwarded and ('HTTP_X_FORWARDED_HOST' in self.environ):\n            host = self.environ['HTTP_X_FORWARDED_HOST']\n            port = self.environ.get('HTTP_X_FORWARDED_PORT')\n            if port and port != ('443' if self.is_secure else '80'):\n                host = '%s:%s' % (host, port)\n            return host\n        elif 'HTTP_HOST' in self.environ:\n            host = self.environ['HTTP_HOST']\n        else:\n            host = self.environ['SERVER_NAME']\n            server_port = str(self.environ['SERVER_PORT'])\n            if server_port != ('443' if self.is_secure else '80'):\n                host = '%s:%s' % (host, server_port)\n        return host",
    "docstring": "Returns the HTTP host using the environment or request headers."
  },
  {
    "code": "def tenant_absent(name, profile=None, **connection_args):\n    ret = {'name': name,\n           'changes': {},\n           'result': True,\n           'comment': 'Tenant / project \"{0}\" is already absent'.format(name)}\n    tenant = __salt__['keystone.tenant_get'](name=name,\n                                             profile=profile,\n                                             **connection_args)\n    if 'Error' not in tenant:\n        if __opts__.get('test'):\n            ret['result'] = None\n            ret['comment'] = 'Tenant / project \"{0}\" will be deleted'.format(name)\n            return ret\n        __salt__['keystone.tenant_delete'](name=name, profile=profile,\n                                           **connection_args)\n        ret['comment'] = 'Tenant / project \"{0}\" has been deleted'.format(name)\n        ret['changes']['Tenant/Project'] = 'Deleted'\n    return ret",
    "docstring": "Ensure that the keystone tenant is absent.\n\n    name\n        The name of the tenant that should not exist"
  },
  {
    "code": "def inject_default_call(self, high):\n        for chunk in high:\n            state = high[chunk]\n            if not isinstance(state, collections.Mapping):\n                continue\n            for state_ref in state:\n                needs_default = True\n                if not isinstance(state[state_ref], list):\n                    continue\n                for argset in state[state_ref]:\n                    if isinstance(argset, six.string_types):\n                        needs_default = False\n                        break\n                if needs_default:\n                    state[state_ref].insert(-1, '__call__')",
    "docstring": "Sets .call function to a state, if not there.\n\n        :param high:\n        :return:"
  },
  {
    "code": "def run(self):\n        self._capture_signals()\n        self._start_monitor()\n        try:\n            while True:\n                if not self._run_worker():\n                    self._wait_for_changes()\n                time.sleep(self.reload_interval)\n        except KeyboardInterrupt:\n            pass\n        finally:\n            self._stop_monitor()\n            self._restore_signals()\n        sys.exit(1)",
    "docstring": "Execute the reloader forever, blocking the current thread.\n\n        This will invoke ``sys.exit(1)`` if interrupted."
  },
  {
    "code": "def subtract_afromb(*inputs, **kwargs):\n    try:\n        value_a = inputs[0].pop()\n        value_b = inputs[1].pop()\n        return [IOTileReading(0, 0, value_b.value - value_a.value)]\n    except StreamEmptyError:\n        return []",
    "docstring": "Subtract stream a from stream b.\n\n    Returns:\n        list(IOTileReading)"
  },
  {
    "code": "def ctcp_reply(self, command, dst, message=None):\n        if message is None:\n            raw_cmd = u'\\x01{0}\\x01'.format(command)\n        else:\n            raw_cmd = u'\\x01{0} {1}\\x01'.format(command, message)\n        self.notice(dst, raw_cmd)",
    "docstring": "Sends a reply to a CTCP request.\n\n        :param command: CTCP command to use.\n        :type command: str\n        :param dst: sender of the initial request.\n        :type dst: str\n        :param message: data to attach to the reply.\n        :type message: str"
  },
  {
    "code": "def caesar(shift, data, shift_ranges=('az', 'AZ')):\n    alphabet = dict(\n        (chr(c), chr((c - s + shift) % (e - s + 1) + s))\n        for s, e in map(lambda r: (ord(r[0]), ord(r[-1])), shift_ranges)\n        for c in range(s, e + 1)\n    )\n    return ''.join(alphabet.get(c, c) for c in data)",
    "docstring": "Apply a caesar cipher to a string.\n\n    The caesar cipher is a substition cipher where each letter in the given\n    alphabet is replaced by a letter some fixed number down the alphabet.\n\n    If ``shift`` is ``1``, *A* will become *B*, *B* will become *C*, etc...\n\n    You can define the alphabets that will be shift by specifying one or more\n    shift ranges. The characters will than be shifted within the given ranges.\n\n    Args:\n        shift(int): The shift to apply.\n        data(str): The string to apply the cipher to.\n        shift_ranges(list of str): Which alphabets to shift.\n\n    Returns:\n        str: The string with the caesar cipher applied.\n\n    Examples:\n        >>> caesar(16, 'Pwnypack')\n        'Fmdofqsa'\n        >>> caesar(-16, 'Fmdofqsa')\n        'Pwnypack'\n        >>> caesar(16, 'PWNYpack', shift_ranges=('AZ',))\n        'FMDOpack'\n        >>> caesar(16, 'PWNYpack', shift_ranges=('Az',))\n        '`g^iFqsA'"
  },
  {
    "code": "def data_only_container(name, volumes):\n    info = inspect_container(name)\n    if info:\n        return\n    c = _get_docker().create_container(\n        name=name,\n        image='datacats/postgres',\n        command='true',\n        volumes=volumes,\n        detach=True)\n    return c",
    "docstring": "create \"data-only container\" if it doesn't already exist.\n\n    We'd like to avoid these, but postgres + boot2docker make\n    it difficult, see issue #5"
  },
  {
    "code": "def color_scale(begin_hsl, end_hsl, nb):\n    if nb < 0:\n        raise ValueError(\n            \"Unsupported negative number of colors (nb=%r).\" % nb)\n    step = tuple([float(end_hsl[i] - begin_hsl[i]) / nb for i in range(0, 3)]) \\\n           if nb > 0 else (0, 0, 0)\n    def mul(step, value):\n        return tuple([v * value for v in step])\n    def add_v(step, step2):\n        return tuple([v + step2[i] for i, v in enumerate(step)])\n    return [add_v(begin_hsl, mul(step, r)) for r in range(0, nb + 1)]",
    "docstring": "Returns a list of nb color HSL tuples between begin_hsl and end_hsl\n\n    >>> from colour import color_scale\n\n    >>> [rgb2hex(hsl2rgb(hsl)) for hsl in color_scale((0, 1, 0.5),\n    ...                                               (1, 1, 0.5), 3)]\n    ['#f00', '#0f0', '#00f', '#f00']\n\n    >>> [rgb2hex(hsl2rgb(hsl))\n    ...  for hsl in color_scale((0, 0, 0),\n    ...                         (0, 0, 1),\n    ...                         15)]  # doctest: +ELLIPSIS\n    ['#000', '#111', '#222', ..., '#ccc', '#ddd', '#eee', '#fff']\n\n    Of course, asking for negative values is not supported:\n\n    >>> color_scale((0, 1, 0.5), (1, 1, 0.5), -2)\n    Traceback (most recent call last):\n    ...\n    ValueError: Unsupported negative number of colors (nb=-2)."
  },
  {
    "code": "def pauli_from_char(ch, n=0):\n    ch = ch.upper()\n    if ch == \"I\":\n        return I\n    if ch == \"X\":\n        return X(n)\n    if ch == \"Y\":\n        return Y(n)\n    if ch == \"Z\":\n        return Z(n)\n    raise ValueError(\"ch shall be X, Y, Z or I\")",
    "docstring": "Make Pauli matrix from an character.\n\n    Args:\n        ch (str): \"X\" or \"Y\" or \"Z\" or \"I\".\n        n (int, optional): Make Pauli matrix as n-th qubits.\n\n    Returns:\n        If ch is \"X\" => X, \"Y\" => Y, \"Z\" => Z, \"I\" => I\n\n    Raises:\n        ValueError: When ch is not \"X\", \"Y\", \"Z\" nor \"I\"."
  },
  {
    "code": "def is_writer(self, check_pending=True):\n        me = self._current_thread()\n        if self._writer == me:\n            return True\n        if check_pending:\n            return me in self._pending_writers\n        else:\n            return False",
    "docstring": "Returns if the caller is the active writer or a pending writer."
  },
  {
    "code": "def to_xml(self, tag_name=\"buyer\"):\n        for n, v in {\"name\": self.name, \"address\": self.address}.items():\n            if is_empty_or_none(v):\n                raise ValueError(\"'%s' attribute cannot be empty or None.\" % n)\n        if self.__require_id and is_empty_or_none(self.identifier):\n            raise ValueError(\"identifier attribute cannot be empty or None.\")\n        doc = Document()\n        root = doc.createElement(tag_name)\n        self._create_text_node(root, \"id\", self.identifier)\n        self._create_text_node(root, \"name\", self.name, True)\n        if self.phone:\n            self._create_text_node(root, \"phone\", self.phone, True)\n        root.appendChild(self.address.to_xml())\n        return root",
    "docstring": "Returns an XMLi representation of the object.\n        @param tag_name:str Tag name\n        @return: Element"
  },
  {
    "code": "def add_arguments(self, parser, bootstrap=False):\n        [item.add_argument(parser, bootstrap)\n         for item in self._get_items(bootstrap=False)]",
    "docstring": "Adds all items to the parser passed in.\n\n        Args:\n            parser (argparse.ArgumentParser): The parser to add all items to.\n            bootstrap (bool): Flag to indicate whether you only want to mark\n                bootstrapped items as required on the command-line."
  },
  {
    "code": "def send(self, sender, **named):\n        responses = []\n        if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:\n            return responses\n        for receiver in self._live_receivers(sender):\n            response = receiver(signal=self, sender=sender, **named)\n            responses.append((receiver, response))\n        return responses",
    "docstring": "Send signal from sender to all connected receivers.\n\n        If any receiver raises an error, the error propagates back through send,\n        terminating the dispatch loop. So it's possible that all receivers\n        won't be called if an error is raised.\n\n        Arguments:\n\n            sender\n                The sender of the signal. Either a specific object or None.\n\n            named\n                Named arguments which will be passed to receivers.\n\n        Returns a list of tuple pairs [(receiver, response), ... ]."
  },
  {
    "code": "def fft_freqs(n_fft, fs):\n    return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)",
    "docstring": "Return frequencies for DFT\n\n    Parameters\n    ----------\n    n_fft : int\n        Number of points in the FFT.\n    fs : float\n        The sampling rate."
  },
  {
    "code": "def destroyCluster(self):\n        logger.debug(\"Destroying cluster %s\" % self.clusterName)\n        instancesToTerminate = self._getNodesInCluster()\n        attempts = 0\n        while instancesToTerminate and attempts < 3:\n            self._terminateInstances(instances=instancesToTerminate)\n            instancesToTerminate = self._getNodesInCluster()\n            attempts += 1\n        instanceGroup = self._gceDriver.ex_get_instancegroup(self.clusterName, zone=self._zone)\n        instanceGroup.destroy()",
    "docstring": "Try a few times to terminate all of the instances in the group."
  },
  {
    "code": "def find_by_reference_ids(reference_ids, _connection=None, page_size=100,\n        page_number=0, sort_by=enums.DEFAULT_SORT_BY,\n        sort_order=enums.DEFAULT_SORT_ORDER):\n        if not isinstance(reference_ids, (list, tuple)):\n            err = \"Video.find_by_reference_ids expects an iterable argument\"\n            raise exceptions.PyBrightcoveError(err)\n        ids = ','.join(reference_ids)\n        return connection.ItemResultSet(\n            'find_videos_by_reference_ids', Video, _connection, page_size,\n            page_number, sort_by, sort_order, reference_ids=ids)",
    "docstring": "List all videos identified by a list of reference ids"
  },
  {
    "code": "def _get_serv(ret):\n    _options = _get_options(ret)\n    host = _options.get('host')\n    port = _options.get('port')\n    log.debug('memcache server: %s:%s', host, port)\n    if not host or not port:\n        log.error('Host or port not defined in salt config')\n        return\n    memcacheoptions = (host, port)\n    return memcache.Client(['{0}:{1}'.format(*memcacheoptions)], debug=0)",
    "docstring": "Return a memcache server object"
  },
  {
    "code": "def generation_time(self):\n        entry = self._proto.commandQueueEntry\n        if entry.HasField('generationTimeUTC'):\n            return parse_isostring(entry.generationTimeUTC)\n        return None",
    "docstring": "The generation time as set by Yamcs.\n\n        :type: :class:`~datetime.datetime`"
  },
  {
    "code": "def resolve(self, dependency):\n        if isinstance(dependency, str):\n            name = dependency\n        else:\n            name = dependency._giveme_registered_name\n        return DeferredProperty(\n            partial(self.get, name)\n        )",
    "docstring": "Resolve dependency as instance attribute \n        of given class.\n\n        >>> class Users:\n        ...     db = injector.resolve(user_db)\n        ...\n        ...     def get_by_id(self, user_id):\n        ...         return self.db.get(user_id)\n\n                \n        When the attribute is first accessed, it \n        will be resolved from the corresponding \n        dependency function"
  },
  {
    "code": "def forward_word(event):\n    buff = event.current_buffer\n    pos = buff.document.find_next_word_ending(count=event.arg)\n    if pos:\n        buff.cursor_position += pos",
    "docstring": "Move forward to the end of the next word. Words are composed of letters and\n    digits."
  },
  {
    "code": "def read(self, sensors):\n        payload = {'destDev': [], 'keys': list(set([s.key for s in sensors]))}\n        if self.sma_sid is None:\n            yield from self.new_session()\n            if self.sma_sid is None:\n                return False\n        body = yield from self._fetch_json(URL_VALUES, payload=payload)\n        if body.get('err') == 401:\n            _LOGGER.warning(\"401 error detected, closing session to force \"\n                            \"another login attempt\")\n            self.close_session()\n            return False\n        _LOGGER.debug(json.dumps(body))\n        for sen in sensors:\n            if sen.extract_value(body):\n                _LOGGER.debug(\"%s\\t= %s %s\",\n                              sen.name, sen.value, sen.unit)\n        return True",
    "docstring": "Read a set of keys."
  },
  {
    "code": "def serialize_on_parent(\n            self,\n            parent,\n            value,\n            state\n    ):\n        if value is None and self.required:\n            state.raise_error(MissingValue, self._missing_value_message(parent))\n        if not value and self.omit_empty:\n            return\n        element = _element_get_or_add_from_parent(parent, self.element_path)\n        self._serialize(element, value, state)",
    "docstring": "Serialize the value and add it to the parent element."
  },
  {
    "code": "def on_mouse_release(self, x: int, y: int, button, mods):\r\n        if button in [1, 4]:\r\n            self.example.mouse_release_event(\r\n                x, self.buffer_height - y,\r\n                1 if button == 1 else 2,\r\n            )",
    "docstring": "Handle mouse release events and forward to example window"
  },
  {
    "code": "def _resolve_subkeys(key, separator='.'):\n    subkey = None\n    if separator in key:\n        index = key.index(separator)\n        subkey = key[index + 1:]\n        key = key[:index]\n    return key, subkey",
    "docstring": "Given a key which may actually be a nested key, return the top level\n    key and any nested subkeys as separate values.\n\n    Args:\n        key (str): A string that may or may not contain the separator.\n        separator (str): The namespace separator. Defaults to `.`.\n\n    Returns:\n        Tuple[str, str]: The key and subkey(s)."
  },
  {
    "code": "def push_uci(self, uci: str) -> Move:\n        move = self.parse_uci(uci)\n        self.push(move)\n        return move",
    "docstring": "Parses a move in UCI notation and puts it on the move stack.\n\n        Returns the move.\n\n        :raises: :exc:`ValueError` if the move is invalid or illegal in the\n            current position (but not a null move)."
  },
  {
    "code": "def lemma(lemma_key):\n    if lemma_key in LEMMAS_DICT:\n        return LEMMAS_DICT[lemma_key]\n    split_lemma_key = lemma_key.split('.')\n    synset_key = '.'.join(split_lemma_key[:3])\n    lemma_literal = split_lemma_key[3]\n    lemma_obj = Lemma(synset_key,lemma_literal)\n    LEMMAS_DICT[lemma_key] = lemma_obj\n    return lemma_obj",
    "docstring": "Returns the Lemma object with the given key.\n\n    Parameters\n    ----------\n    lemma_key : str\n      Key of the returned lemma.\n\n    Returns\n    -------\n    Lemma\n      Lemma matching the `lemma_key`."
  },
  {
    "code": "def parent_org_sdo_ids(self):\n        return [sdo.get_owner()._narrow(SDOPackage.SDO).get_sdo_id() \\\n                for sdo in self._obj.get_organizations() if sdo]",
    "docstring": "The SDO IDs of the compositions this RTC belongs to."
  },
  {
    "code": "def _on_shortcut_changed(self, renderer, path, new_shortcuts):\n        action = self.shortcut_list_store[int(path)][self.KEY_STORAGE_ID]\n        old_shortcuts = self.gui_config_model.get_current_config_value(\"SHORTCUTS\", use_preliminary=True)[action]\n        from ast import literal_eval\n        try:\n            new_shortcuts = literal_eval(new_shortcuts)\n            if not isinstance(new_shortcuts, list) and \\\n               not all([isinstance(shortcut, string_types) for shortcut in new_shortcuts]):\n                raise ValueError()\n        except (ValueError, SyntaxError):\n            logger.warning(\"Shortcuts must be a list of strings\")\n            new_shortcuts = old_shortcuts\n        shortcuts = self.gui_config_model.get_current_config_value(\"SHORTCUTS\", use_preliminary=True,  default={})\n        shortcuts[action] = new_shortcuts\n        self.gui_config_model.set_preliminary_config_value(\"SHORTCUTS\", shortcuts)\n        self._select_row_by_column_value(self.view['shortcut_tree_view'], self.shortcut_list_store,\n                                         self.KEY_STORAGE_ID, action)",
    "docstring": "Callback handling a change of a shortcut\n\n        :param Gtk.CellRenderer renderer: Cell renderer showing the shortcut\n        :param path: Path of shortcuts within the list store\n        :param str new_shortcuts: New shortcuts"
  },
  {
    "code": "def mtxvg(m1, v2, ncol1, nr1r2):\n    m1 = stypes.toDoubleMatrix(m1)\n    v2 = stypes.toDoubleVector(v2)\n    ncol1 = ctypes.c_int(ncol1)\n    nr1r2 = ctypes.c_int(nr1r2)\n    vout = stypes.emptyDoubleVector(ncol1.value)\n    libspice.mtxvg_c(m1, v2, ncol1, nr1r2, vout)\n    return stypes.cVectorToPython(vout)",
    "docstring": "Multiply the transpose of a matrix and\n    a vector of arbitrary size.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mtxvg_c.html\n\n    :param m1: Left-hand matrix to be multiplied.\n    :type m1: NxM-Element Array of floats\n    :param v2: Right-hand vector to be multiplied.\n    :type v2: Array of floats\n    :param ncol1: Column dimension of m1 and length of vout.\n    :type ncol1: int\n    :param nr1r2: Row dimension of m1 and length of v2.\n    :type nr1r2: int\n    :return: Product vector m1 transpose * v2.\n    :rtype: Array of floats"
  },
  {
    "code": "def get_model(app_label, model_name):\n    try:\n        from django.apps import apps\n        from django.core.exceptions import AppRegistryNotReady\n    except ImportError:\n        from django.db import models\n        return models.get_model(app_label, model_name)\n    try:\n        return apps.get_model(app_label, model_name)\n    except AppRegistryNotReady:\n        if apps.apps_ready and not apps.models_ready:\n            app_config = apps.get_app_config(app_label)\n            import_module(\"%s.%s\" % (app_config.name, \"models\"))\n            return apps.get_registered_model(app_label, model_name)\n        else:\n            raise",
    "docstring": "Fetches a Django model using the app registry.\n\n    This doesn't require that an app with the given app label exists, which\n    makes it safe to call when the registry is being populated. All other\n    methods to access models might raise an exception about the registry not\n    being ready yet.\n\n    Raises LookupError if model isn't found."
  },
  {
    "code": "def nanstd(values, axis=None, skipna=True, ddof=1, mask=None):\n    result = np.sqrt(nanvar(values, axis=axis, skipna=skipna, ddof=ddof,\n                            mask=mask))\n    return _wrap_results(result, values.dtype)",
    "docstring": "Compute the standard deviation along given axis while ignoring NaNs\n\n    Parameters\n    ----------\n    values : ndarray\n    axis: int, optional\n    skipna : bool, default True\n    ddof : int, default 1\n        Delta Degrees of Freedom. The divisor used in calculations is N - ddof,\n        where N represents the number of elements.\n    mask : ndarray[bool], optional\n        nan-mask if known\n\n    Returns\n    -------\n    result : float\n        Unless input is a float array, in which case use the same\n        precision as the input array.\n\n    Examples\n    --------\n    >>> import pandas.core.nanops as nanops\n    >>> s = pd.Series([1, np.nan, 2, 3])\n    >>> nanops.nanstd(s)\n    1.0"
  },
  {
    "code": "def explode(col):\n    sc = SparkContext._active_spark_context\n    jc = sc._jvm.functions.explode(_to_java_column(col))\n    return Column(jc)",
    "docstring": "Returns a new row for each element in the given array or map.\n    Uses the default column name `col` for elements in the array and\n    `key` and `value` for elements in the map unless specified otherwise.\n\n    >>> from pyspark.sql import Row\n    >>> eDF = spark.createDataFrame([Row(a=1, intlist=[1,2,3], mapfield={\"a\": \"b\"})])\n    >>> eDF.select(explode(eDF.intlist).alias(\"anInt\")).collect()\n    [Row(anInt=1), Row(anInt=2), Row(anInt=3)]\n\n    >>> eDF.select(explode(eDF.mapfield).alias(\"key\", \"value\")).show()\n    +---+-----+\n    |key|value|\n    +---+-----+\n    |  a|    b|\n    +---+-----+"
  },
  {
    "code": "def variable_summaries(vars_, groups=None, scope='weights'):\n  groups = groups or {r'all': r'.*'}\n  grouped = collections.defaultdict(list)\n  for var in vars_:\n    for name, pattern in groups.items():\n      if re.match(pattern, var.name):\n        name = re.sub(pattern, name, var.name)\n        grouped[name].append(var)\n  for name in groups:\n    if name not in grouped:\n      tf.logging.warn(\"No variables matching '{}' group.\".format(name))\n  summaries = []\n  for name, vars_ in grouped.items():\n    vars_ = [tf.reshape(var, [-1]) for var in vars_]\n    vars_ = tf.concat(vars_, 0)\n    summaries.append(tf.summary.histogram(scope + '/' + name, vars_))\n  return tf.summary.merge(summaries)",
    "docstring": "Create histogram summaries for the provided variables.\n\n  Summaries can be grouped via regexes matching variables names.\n\n  Args:\n    vars_: List of variables to summarize.\n    groups: Mapping of name to regex for grouping summaries.\n    scope: Name scope for this operation.\n\n  Returns:\n    Summary tensor."
  },
  {
    "code": "def read_name(source, position):\n    body = source.body\n    body_length = len(body)\n    end = position + 1\n    while end != body_length:\n        code = char_code_at(body, end)\n        if not (\n            code is not None\n            and (\n                code == 95\n                or 48 <= code <= 57\n                or 65 <= code <= 90\n                or 97 <= code <= 122\n            )\n        ):\n            break\n        end += 1\n    return Token(TokenKind.NAME, position, end, body[position:end])",
    "docstring": "Reads an alphanumeric + underscore name from the source.\n\n    [_A-Za-z][_0-9A-Za-z]*"
  },
  {
    "code": "def get_lat_lon_time_from_nmea(nmea_file, local_time=True):\n    with open(nmea_file, \"r\") as f:\n        lines = f.readlines()\n        lines = [l.rstrip(\"\\n\\r\") for l in lines]\n    for l in lines:\n        if \"GPRMC\" in l:\n            data = pynmea2.parse(l)\n            date = data.datetime.date()\n            break\n    points = []\n    for l in lines:\n        if \"GPRMC\" in l:\n            data = pynmea2.parse(l)\n            date = data.datetime.date()\n        if \"$GPGGA\" in l:\n            data = pynmea2.parse(l)\n            timestamp = datetime.datetime.combine(date, data.timestamp)\n            lat, lon, alt = data.latitude, data.longitude, data.altitude\n            points.append((timestamp, lat, lon, alt))\n    points.sort()\n    return points",
    "docstring": "Read location and time stamps from a track in a NMEA file.\n\n    Returns a list of tuples (time, lat, lon).\n\n    GPX stores time in UTC, by default we assume your camera used the local time\n    and convert accordingly."
  },
  {
    "code": "def RebuildHttpConnections(http):\n    if getattr(http, 'connections', None):\n        for conn_key in list(http.connections.keys()):\n            if ':' in conn_key:\n                del http.connections[conn_key]",
    "docstring": "Rebuilds all http connections in the httplib2.Http instance.\n\n    httplib2 overloads the map in http.connections to contain two different\n    types of values:\n    { scheme string:  connection class } and\n    { scheme + authority string : actual http connection }\n    Here we remove all of the entries for actual connections so that on the\n    next request httplib2 will rebuild them from the connection types.\n\n    Args:\n      http: An httplib2.Http instance."
  },
  {
    "code": "def MakeRequest(self, data):\n    stats_collector_instance.Get().IncrementCounter(\"grr_client_sent_bytes\",\n                                                    len(data))\n    response = self.http_manager.OpenServerEndpoint(\n        path=\"control?api=%s\" % config.CONFIG[\"Network.api\"],\n        verify_cb=self.VerifyServerControlResponse,\n        data=data,\n        headers={\"Content-Type\": \"binary/octet-stream\"})\n    if response.code == 406:\n      self.InitiateEnrolment()\n      return response\n    if response.code == 200:\n      stats_collector_instance.Get().IncrementCounter(\n          \"grr_client_received_bytes\", len(response.data))\n      return response\n    return response",
    "docstring": "Make a HTTP Post request to the server 'control' endpoint."
  },
  {
    "code": "def compute_norrec_differences(df, keys_diff):\n    raise Exception('This function is depreciated!')\n    print('computing normal-reciprocal differences')\n    def norrec_diff(x):\n        if x.shape[0] != 2:\n            return np.nan\n        else:\n            return np.abs(x.iloc[1] - x.iloc[0])\n    keys_keep = list(set(df.columns.tolist()) - set(keys_diff))\n    agg_dict = {x: _first for x in keys_keep}\n    agg_dict.update({x: norrec_diff for x in keys_diff})\n    for key in ('id', 'timestep', 'frequency'):\n        if key in agg_dict:\n            del(agg_dict[key])\n    df = df.groupby(('timestep', 'frequency', 'id')).agg(agg_dict)\n    df.reset_index()\n    return df",
    "docstring": "DO NOT USE ANY MORE - DEPRECIATED!"
  },
  {
    "code": "def create(\n            self,\n            order_increment_id,\n            creditmemo_data=None,\n            comment=None,\n            email=False,\n            include_comment=False,\n            refund_to_store_credit_amount=None):\n        if comment is None:\n            comment = ''\n        return self.call(\n            'sales_order_creditmemo.create', [\n                order_increment_id, creditmemo_data, comment, email, include_comment, refund_to_store_credit_amount\n            ]\n        )",
    "docstring": "Create new credit_memo for order\n\n        :param order_increment_id: Order Increment ID\n        :type order_increment_id: str\n        :param creditmemo_data: Sales order credit memo data (optional)\n        :type creditmemo_data: associative array as dict\n\n            {\n                'qtys': [\n                    {\n                        'order_item_id': str,   # Order item ID to be refunded\n                        'qty': int              # Items quantity to be refunded\n                    },\n                    ...\n                ],\n                'shipping_amount': float        # refund shipping amount (optional)\n                'adjustment_positive': float    # adjustment refund amount (optional)\n                'adjustment_negative': float    # adjustment fee amount (optional)\n            }\n\n        :param comment: Credit memo Comment\n        :type comment: str\n        :param email: send e-mail flag (optional)\n        :type email: bool\n        :param include_comment: include comment in e-mail flag (optional)\n        :type include_comment: bool\n        :param refund_to_store_credit_amount: amount to refund to store credit\n        :type refund_to_store_credit_amount: float\n\n        :return str, increment id of credit memo created"
  },
  {
    "code": "def find_d2ifile(flist,detector):\n    d2ifile = None\n    for f in flist:\n        fdet = fits.getval(f, 'detector', memmap=False)\n        if fdet == detector:\n            d2ifile = f\n    return d2ifile",
    "docstring": "Search a list of files for one that matches the detector specified."
  },
  {
    "code": "def get_ride_details(api_client, ride_id):\n    try:\n        ride_details = api_client.get_ride_details(ride_id)\n    except (ClientError, ServerError) as error:\n        fail_print(error)\n    else:\n        success_print(ride_details.json)",
    "docstring": "Use an UberRidesClient to get ride details and print the results.\n\n    Parameters\n        api_client (UberRidesClient)\n            An authorized UberRidesClient with 'request' scope.\n        ride_id (str)\n            Unique ride identifier."
  },
  {
    "code": "def get_python_version(path):\n    version_cmd = [path, \"-c\", \"import sys; print(sys.version.split()[0])\"]\n    try:\n        c = vistir.misc.run(\n            version_cmd,\n            block=True,\n            nospin=True,\n            return_object=True,\n            combine_stderr=False,\n            write_to_stdout=False,\n        )\n    except OSError:\n        raise InvalidPythonVersion(\"%s is not a valid python path\" % path)\n    if not c.out:\n        raise InvalidPythonVersion(\"%s is not a valid python path\" % path)\n    return c.out.strip()",
    "docstring": "Get python version string using subprocess from a given path."
  },
  {
    "code": "def serialise(self, default_endianness=None):\n        endianness = (default_endianness or DEFAULT_ENDIANNESS)\n        if hasattr(self, '_Meta'):\n            endianness = self._Meta.get('endianness', endianness)\n        inferred_fields = set()\n        for k, v in iteritems(self._type_mapping):\n            inferred_fields |= {x._name for x in v.dependent_fields()}\n        for field in inferred_fields:\n            setattr(self, field, None)\n        for k, v in iteritems(self._type_mapping):\n            v.prepare(self, getattr(self, k))\n        message = b''\n        for k, v in iteritems(self._type_mapping):\n            message += v.value_to_bytes(self, getattr(self, k), default_endianness=endianness)\n        return message",
    "docstring": "Serialise a message, without including any framing.\n\n        :param default_endianness: The default endianness, unless overridden by the fields or class metadata.\n                                   Should usually be left at ``None``. Otherwise, use ``'<'`` for little endian and\n                                   ``'>'`` for big endian.\n        :type default_endianness: str\n        :return: The serialised message.\n        :rtype: bytes"
  },
  {
    "code": "def create(self, parameters={}, create_keys=True, **kwargs):\n        cs = self._create_service(parameters=parameters, **kwargs)\n        if create_keys:\n            cfg = parameters\n            cfg.update(self._get_service_config())\n            self.settings.save(cfg)",
    "docstring": "Create the service."
  },
  {
    "code": "def is_filter_tuple(tup):\n    return isinstance(tup, (tuple, list)) and (\n        len(tup) == 3 and\n        isinstance(tup[0], string_types) and\n        callable(tup[1]))",
    "docstring": "Return whether a `tuple` matches the format for a column filter"
  },
  {
    "code": "def _get_path_entry_from_string(self, query_string, first_found=True, full_path=False):\n        iter_matches = gen_dict_key_matches(query_string, self.config_file_contents, full_path=full_path)\n        try:\n            return next(iter_matches) if first_found else iter_matches\n        except (StopIteration, TypeError):\n            raise errors.ResourceNotFoundError('Could not find search string %s in the config file contents %s' %\n                                               (query_string, self.config_file_contents))",
    "docstring": "Parses a string to form a list of strings that represents a possible config entry header\n\n        :param query_string: str, query string we are looking for\n        :param first_found: bool, return first found entry or entire list\n        :param full_path: bool, whether to return each entry with their corresponding config entry path\n        :return: (Generator((list, str, dict, OrderedDict)), config entries that match the query string\n        :raises: exceptions.ResourceNotFoundError"
  },
  {
    "code": "def load_module(self, filename):\n        if not isinstance(filename, string_types):\n            return filename\n        basename = os.path.splitext(os.path.basename(filename))[0]\n        basename = basename.replace('.bench', '')\n        modulename = 'benchmarks.{0}'.format(basename)\n        return load_module(modulename, filename)",
    "docstring": "Load a benchmark module from file"
  },
  {
    "code": "def harvest(self):\n        if self.perform_initialization() is not None:\n            self.process_items()\n            self.finalize()\n        return self.job",
    "docstring": "Start the harvesting process"
  },
  {
    "code": "def fetchText(cls, url, data, textSearch, optional):\n        if cls.css:\n            searchFun = data.cssselect\n        else:\n            searchFun = data.xpath\n        if textSearch:\n            text = ''\n            for match in searchFun(textSearch):\n                try:\n                    text += ' ' + match.text_content()\n                except AttributeError:\n                    text += ' ' + unicode(match)\n            if text.strip() == '':\n                if optional:\n                    return None\n                else:\n                    raise ValueError(\"XPath %s did not match anything at URL %s.\" % (textSearch, url))\n            out.debug(u'Matched text %r with XPath %s' % (text, textSearch))\n            return unescape(text).strip()\n        else:\n            return None",
    "docstring": "Search text entry for given text XPath in a HTML page."
  },
  {
    "code": "def deleteCertificate(self, certName):\n        params = {\"f\" : \"json\"}\n        url = self._url + \"/sslCertificates/{cert}/delete\".format(\n            cert=certName)\n        return self._post(url=url, param_dict=params,\n                          proxy_port=self._proxy_port,\n                          proxy_url=self._proxy_url)",
    "docstring": "This operation deletes an SSL certificate from the key store. Once\n        a certificate is deleted, it cannot be retrieved or used to enable\n        SSL.\n\n        Inputs:\n          certName - name of the cert to delete"
  },
  {
    "code": "def to_networkx(self):\n        return nx_util.to_networkx(self.session.get(self.__url).json())",
    "docstring": "Return this network in NetworkX graph object.\n\n        :return: Network as NetworkX graph object"
  },
  {
    "code": "def main(port=8222):\n    loop = asyncio.get_event_loop()\n    environ = {'hello': 'world'}\n    def create_server():\n        return MySSHServer(lambda: environ)\n    print('Listening on :%i' % port)\n    print('To connect, do \"ssh localhost -p %i\"' % port)\n    loop.run_until_complete(\n        asyncssh.create_server(create_server, '', port,\n                               server_host_keys=['/etc/ssh/ssh_host_dsa_key']))\n    loop.run_forever()",
    "docstring": "Example that starts the REPL through an SSH server."
  },
  {
    "code": "def get_client_class(self, client_class_name):\n        request_url = self._build_url(['ClientClass', client_class_name])\n        return self._do_request('GET', request_url)",
    "docstring": "Returns a specific client class details from CPNR server."
  },
  {
    "code": "def build_strings(self):\n        for idx, dev in enumerate(self.devices):\n            header = 'system.' + dev\n            self.gcalls[idx] = header + '.gcall(system.dae)\\n'\n            self.fcalls[idx] = header + '.fcall(system.dae)\\n'\n            self.gycalls[idx] = header + '.gycall(system.dae)\\n'\n            self.fxcalls[idx] = header + '.fxcall(system.dae)\\n'\n            self.jac0s[idx] = header + '.jac0(system.dae)\\n'",
    "docstring": "build call string for each device"
  },
  {
    "code": "def _cancel_orphan_orders(self, orderId):\n        orders = self.ibConn.orders\n        for order in orders:\n            order = orders[order]\n            if order['parentId'] != orderId:\n                self.ibConn.cancelOrder(order['id'])",
    "docstring": "cancel child orders when parent is gone"
  },
  {
    "code": "def update(self, app_model, forbidden_keys=None, inverse=False):\n        if forbidden_keys is None:\n            forbidden_keys = []\n        update_model(self, app_model, forbidden_keys, inverse)",
    "docstring": "Updates the raw model. Consult `zsl.utils.model_helper.update_model`."
  },
  {
    "code": "def ws_db996(self, value=None):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type float '\n                                 'for field `ws_db996`'.format(value))\n        self._ws_db996 = value",
    "docstring": "Corresponds to IDD Field `ws_db996`\n        Mean wind speed coincident with 99.6% dry-bulb temperature\n\n        Args:\n            value (float): value for IDD Field `ws_db996`\n                Unit: m/s\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def get_first_rec(fastafile):\n    f = list(SeqIO.parse(fastafile, \"fasta\"))\n    if len(f) > 1:\n        logging.debug(\"{0} records found in {1}, using the first one\".\n                      format(len(f), fastafile))\n    return f[0]",
    "docstring": "Returns the first record in the fastafile"
  },
  {
    "code": "def sizeOfOverlap(self, e):\n    if not self.intersects(e):\n      return 0\n    if e.start >= self.start and e.end <= self.end:\n      return len(e)\n    if self.start >= e.start and self.end <= e.end:\n      return len(self)\n    if e.start > self.start:\n      return (self.end - e.start)\n    if self.start > e.start:\n      return (e.end - self.start)",
    "docstring": "Get the size of the overlap between self and e.\n\n    :return: the number of bases that are shared in common between self and e."
  },
  {
    "code": "def buffer(self):\n        if self._buf_in_use:\n            raise RuntimeError(\"nested use of buffer() is not supported\")\n        self._buf_in_use = True\n        old_write = self._write\n        old_flush = self._flush\n        if self._buf is None:\n            self._buf = io.BytesIO()\n        else:\n            try:\n                self._buf.seek(0)\n                self._buf.truncate()\n            except BufferError:\n                self._buf = io.BytesIO()\n        self._write = self._buf.write\n        self._flush = None\n        try:\n            with self._save_state():\n                yield\n            old_write(self._buf.getbuffer())\n            if old_flush:\n                old_flush()\n        finally:\n            self._buf_in_use = False\n            self._write = old_write\n            self._flush = old_flush",
    "docstring": "Context manager to temporarily buffer the output.\n\n        :raise RuntimeError: If two :meth:`buffer` context managers are used\n                             nestedly.\n\n        If the context manager is left without exception, the buffered output\n        is sent to the actual sink. Otherwise, it is discarded.\n\n        In addition to the output being buffered, buffer also captures the\n        entire state of the XML generator and restores it to the previous state\n        if the context manager is left with an exception.\n\n        This can be used to fail-safely attempt to serialise a subtree and\n        return to a well-defined state if serialisation fails.\n\n        :meth:`flush` is not called automatically.\n\n        If :meth:`flush` is called while a :meth:`buffer` context manager is\n        active, no actual flushing happens (but unfinished opening tags are\n        closed as usual, see the `short_empty_arguments` parameter)."
  },
  {
    "code": "def to_internal_value(self, data):\n        model = self.Meta.model\n        if \"id\" in data:\n            author = model.objects.get(id=data[\"id\"])\n        else:\n            if \"username\" not in data:\n                raise ValidationError(\"Authors must include an ID or a username.\")\n            username = data[\"username\"]\n            author = model.objects.get(username=username)\n        return author",
    "docstring": "Basically, each author dict must include either a username or id."
  },
  {
    "code": "def nodes(self, frequency=None):\n        if frequency is None:\n            []\n        elif frequency == 'per_session':\n            return [self]\n        elif frequency in ('per_visit', 'per_subject'):\n            return [self.parent]\n        elif frequency == 'per_study':\n            return [self.parent.parent]",
    "docstring": "Returns all nodes of the specified frequency that are related to\n        the given Session\n\n        Parameters\n        ----------\n        frequency : str | None\n            The frequency of the nodes to return\n\n        Returns\n        -------\n        nodes : iterable[TreeNode]\n            All nodes related to the Session for the specified frequency"
  },
  {
    "code": "def start_virtual_display(self, width=1440, height=900,\n                              colordepth=24, **kwargs):\n        if self._display is None:\n            logger.info(\"Using virtual display: '{0}x{1}x{2}'\".format(\n                        width, height, colordepth))\n            self._display = Xvfb(int(width), int(height),\n                                 int(colordepth), **kwargs)\n            self._display.start()\n            atexit.register(self._display.stop)",
    "docstring": "Starts virtual display which will be\n         destroyed after test execution will be end\n\n        *Arguments:*\n        - width: a width to be set in pixels\n        - height: a height to be set in pixels\n        - color_depth: a color depth to be used\n        - kwargs: extra parameters\n\n        *Example:*\n\n        | Start Virtual Display |\n        | Start Virtual Display | 1920 | 1080 |\n        | Start Virtual Display | ${1920} | ${1080} | ${16} |"
  },
  {
    "code": "def get_rows(self, infer_nrows, skiprows=None):\n        if skiprows is None:\n            skiprows = set()\n        buffer_rows = []\n        detect_rows = []\n        for i, row in enumerate(self.f):\n            if i not in skiprows:\n                detect_rows.append(row)\n            buffer_rows.append(row)\n            if len(detect_rows) >= infer_nrows:\n                break\n        self.buffer = iter(buffer_rows)\n        return detect_rows",
    "docstring": "Read rows from self.f, skipping as specified.\n\n        We distinguish buffer_rows (the first <= infer_nrows\n        lines) from the rows returned to detect_colspecs\n        because it's simpler to leave the other locations\n        with skiprows logic alone than to modify them to\n        deal with the fact we skipped some rows here as\n        well.\n\n        Parameters\n        ----------\n        infer_nrows : int\n            Number of rows to read from self.f, not counting\n            rows that are skipped.\n        skiprows: set, optional\n            Indices of rows to skip.\n\n        Returns\n        -------\n        detect_rows : list of str\n            A list containing the rows to read."
  },
  {
    "code": "def resources_after_reservation(res, constraint):\n    res = res.copy()\n    res[constraint.resource] -= (constraint.reservation.stop -\n                                 constraint.reservation.start)\n    return res",
    "docstring": "Return the resources available after a specified\n    ReserveResourceConstraint has been applied.\n\n    Note: the caller is responsible for testing that the constraint is\n    applicable to the core whose resources are being constrained.\n\n    Note: this function does not pay attention to the specific position of the\n    reserved regieon, only its magnitude."
  },
  {
    "code": "def slot(self, slot_index, marshal=None, unmarshal=None, build=None, cast=None, compress=False):\n        def decorate(o):\n            assert isinstance(o, PersistentMap)\n            name = o.__class__.__name__\n            assert slot_index not in self._index_to_slot\n            assert name not in self._name_to_slot\n            o._zlmdb_slot = slot_index\n            o._zlmdb_marshal = marshal\n            o._zlmdb_unmarshal = unmarshal\n            o._zlmdb_build = build\n            o._zlmdb_cast = cast\n            o._zlmdb_compress = compress\n            _slot = Slot(slot_index, name, o)\n            self._index_to_slot[slot_index] = _slot\n            self._name_to_slot[name] = _slot\n            return o\n        return decorate",
    "docstring": "Decorator for use on classes derived from zlmdb.PersistentMap. The decorator define slots\n        in a LMDB database schema based on persistent maps, and slot configuration.\n\n        :param slot_index:\n        :param marshal:\n        :param unmarshal:\n        :param build:\n        :param cast:\n        :param compress:\n        :return:"
  },
  {
    "code": "def upgrade_defaults(self):\n        self.defaults.upgrade()\n        self.reset_defaults(self.defaults.filename)",
    "docstring": "Upgrade config file and reload."
  },
  {
    "code": "def set_eep(self, data):\n        self._bit_data, self._bit_status = self.eep.set_values(self._profile, self._bit_data, self._bit_status, data)",
    "docstring": "Update packet data based on EEP. Input data is a dictionary with keys corresponding to the EEP."
  },
  {
    "code": "def blue_hour(self, direction=SUN_RISING, date=None, local=True, use_elevation=True):\n        if local and self.timezone is None:\n            raise ValueError(\"Local time requested but Location has no timezone set.\")\n        if self.astral is None:\n            self.astral = Astral()\n        if date is None:\n            date = datetime.date.today()\n        elevation = self.elevation if use_elevation else 0\n        start, end = self.astral.blue_hour_utc(\n            direction, date, self.latitude, self.longitude, elevation\n        )\n        if local:\n            start = start.astimezone(self.tz)\n            end = end.astimezone(self.tz)\n        return start, end",
    "docstring": "Returns the start and end times of the Blue Hour when the sun is traversing\n        in the specified direction.\n\n        This method uses the definition from PhotoPills i.e. the\n        blue hour is when the sun is between 6 and 4 degrees below the horizon.\n\n        :param direction:  Determines whether the time is for the sun rising or setting.\n                           Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``. Default is rising.\n        :type direction:   int\n\n        :param date: The date for which to calculate the times.\n                     If no date is specified then the current date will be used.\n        :type date:  :class:`~datetime.date`\n\n        :param local: True  = Times to be returned in location's time zone;\n                      False = Times to be returned in UTC.\n                      If not specified then the time will be returned in local time\n        :type local:  bool\n\n        :param use_elevation: True  = Return times that allow for the location's elevation;\n                              False = Return times that don't use elevation.\n                              If not specified then times will take elevation into account.\n        :type use_elevation:  bool\n\n        :return: A tuple of the date and time at which the Blue Hour starts and ends.\n        :rtype: (:class:`~datetime.datetime`, :class:`~datetime.datetime`)"
  },
  {
    "code": "def value(self):\n        if isinstance(self.code, Status):\n            code = self.code.value\n        else:\n            code = self.code\n        return {'code': code, 'errors': self.errors}",
    "docstring": "Utility method to retrieve Response Object information"
  },
  {
    "code": "def contains_version(self, version):\n        if len(self.bounds) < 5:\n            for bound in self.bounds:\n                i = bound.version_containment(version)\n                if i == 0:\n                    return True\n                if i == -1:\n                    return False\n        else:\n            _, contains = self._contains_version(version)\n            return contains\n        return False",
    "docstring": "Returns True if version is contained in this range."
  },
  {
    "code": "def _run_cmd(cmds):\n    if not isinstance(cmds, str):\n        cmds = \"\".join(cmds)\n    print(\"Execute \\\"%s\\\"\" % cmds)\n    try:\n        subprocess.check_call(cmds, shell=True)\n    except subprocess.CalledProcessError as err:\n        print(err)\n        raise err",
    "docstring": "Run commands, raise exception if failed"
  },
  {
    "code": "def _checkMissingParamsFromWorkitem(self, copied_from, keep=False,\n                                        **kwargs):\n        parameters = self.listFieldsFromWorkitem(copied_from,\n                                                 keep=keep)\n        self._findMissingParams(parameters, **kwargs)",
    "docstring": "Check the missing parameters for rendering directly from the\n        copied workitem"
  },
  {
    "code": "def get_courses_metadata(self):\n        metadata = dict(self._mdata['courses'])\n        metadata.update({'existing_courses_values': self._my_map['courseIds']})\n        return Metadata(**metadata)",
    "docstring": "Gets the metadata for the courses.\n\n        return: (osid.Metadata) - metadata for the courses\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def portals(self):\n        url = \"%s/portals\" % self.root\n        return _portals.Portals(url=url,\n                                securityHandler=self._securityHandler,\n                                proxy_url=self._proxy_url,\n                                proxy_port=self._proxy_port)",
    "docstring": "returns the Portals class that provides administration access\n        into a given organization"
  },
  {
    "code": "def get_method_docstring(cls, method_name):\n    method = getattr(cls, method_name, None)\n    if method is None:\n        return\n    docstrign = inspect.getdoc(method)\n    if docstrign is None:\n        for base in cls.__bases__:\n            docstrign = get_method_docstring(base, method_name)\n            if docstrign:\n                return docstrign\n        else:\n            return None\n    return docstrign",
    "docstring": "return method  docstring\n    if method docstring is empty we get docstring from parent\n\n    :param method:\n    :type method:\n    :return:\n    :rtype:"
  },
  {
    "code": "def save_inventory(inventory, hosts_file=HOSTS_FILE):\n    with open(hosts_file, 'w') as f:\n        inventory.write(f)",
    "docstring": "Saves Ansible inventory to file.\n\n    Parameters\n    ----------\n    inventory: ConfigParser.SafeConfigParser\n        content of the `hosts_file`\n    hosts_file: str, optional\n        path to Ansible hosts file"
  },
  {
    "code": "def get_collated_content(ident_hash, context_ident_hash, cursor):\n    cursor.execute(SQL['get-collated-content'],\n                   (ident_hash, context_ident_hash,))\n    try:\n        return cursor.fetchone()[0]\n    except TypeError:\n        return",
    "docstring": "Return collated content for ``ident_hash``."
  },
  {
    "code": "def clean_all(self, config_file, region=None, profile_name=None):\n        logging.info('[begin] Cleaning all provisioned artifacts')\n        config = GroupConfigFile(config_file=config_file)\n        if config.is_fresh() is True:\n            raise ValueError(\"Config is already clean.\")\n        if region is None:\n            region = self._region\n        self._delete_group(\n            config_file, region=region, profile_name=profile_name)\n        self.clean_core(config_file, region=region)\n        self.clean_devices(config_file, region=region)\n        self.clean_file(config_file)\n        logging.info('[end] Cleaned all provisioned artifacts')",
    "docstring": "Clean all provisioned artifacts from both the local file and the AWS\n        Greengrass service.\n\n        :param config_file: config file containing the group to clean\n        :param region: the region in which the group should be cleaned.\n            [default: us-west-2]\n        :param profile_name: the name of the `awscli` profile to use.\n            [default: None]"
  },
  {
    "code": "def websafe(s):\r\n    s=s.replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\")\r\n    s=s.replace(r'\\x',r' \\x')\r\n    s=s.replace(\"\\n\",\"<br>\")\r\n    return s",
    "docstring": "return a string with HTML-safe text"
  },
  {
    "code": "def _scons_user_warning(e):\n    etype, value, tb = sys.exc_info()\n    filename, lineno, routine, dummy = find_deepest_user_frame(traceback.extract_tb(tb))\n    sys.stderr.write(\"\\nscons: warning: %s\\n\" % e)\n    sys.stderr.write('File \"%s\", line %d, in %s\\n' % (filename, lineno, routine))",
    "docstring": "Handle user warnings. Print out a message and a description of\n    the warning, along with the line number and routine where it occured.\n    The file and line number will be the deepest stack frame that is\n    not part of SCons itself."
  },
  {
    "code": "def validate_hier_intervals(intervals_hier):\n    label_top = util.generate_labels(intervals_hier[0])\n    boundaries = set(util.intervals_to_boundaries(intervals_hier[0]))\n    for level, intervals in enumerate(intervals_hier[1:], 1):\n        label_current = util.generate_labels(intervals)\n        validate_structure(intervals_hier[0], label_top,\n                           intervals, label_current)\n        new_bounds = set(util.intervals_to_boundaries(intervals))\n        if boundaries - new_bounds:\n            warnings.warn('Segment hierarchy is inconsistent '\n                          'at level {:d}'.format(level))\n        boundaries |= new_bounds",
    "docstring": "Validate a hierarchical segment annotation.\n\n    Parameters\n    ----------\n    intervals_hier : ordered list of segmentations\n\n    Raises\n    ------\n    ValueError\n        If any segmentation does not span the full duration of the top-level\n        segmentation.\n\n        If any segmentation does not start at 0."
  },
  {
    "code": "def _expand_parameters(specification, parameters, original=None):\n    expanded_specification = deepcopy(specification)\n    try:\n        for step_num, step in enumerate(expanded_specification['steps']):\n            current_step = expanded_specification['steps'][step_num]\n            for command_num, command in enumerate(step['commands']):\n                current_step['commands'][command_num] = \\\n                    Template(command).substitute(parameters)\n        if original:\n            return specification\n        else:\n            return expanded_specification\n    except KeyError as e:\n        raise ValidationError('Workflow parameter(s) could not '\n                              'be expanded. Please take a look '\n                              'to {params}'.format(params=str(e)))",
    "docstring": "Expand parameters inside comands for Serial workflow specifications.\n\n    :param specification: Full valid Serial workflow specification.\n    :param parameters: Parameters to be extended on a Serial specification.\n    :param original: Flag which, determins type of specifications to return.\n    :returns: If 'original' parameter is set, a copy of the specification\n        whithout expanded parametrers will be returned. If 'original' is not\n        set, a copy of the specification with expanded parameters (all $varname\n        and ${varname} will be expanded with their value). Otherwise an error\n        will be thrown if the parameters can not be expanded.\n    :raises: jsonschema.ValidationError"
  },
  {
    "code": "def to_binary(self, threshold=0.0):\n        data = BINARY_IM_MAX_VAL * (self._data > threshold)\n        return BinaryImage(data.astype(np.uint8), self._frame)",
    "docstring": "Creates a BinaryImage from the depth image. Points where the depth\n        is greater than threshold are converted to ones, and all other points\n        are zeros.\n\n        Parameters\n        ----------\n        threshold : float\n            The depth threshold.\n\n        Returns\n        -------\n        :obj:`BinaryImage`\n            A BinaryImage where all 1 points had a depth greater than threshold\n            in the DepthImage."
  },
  {
    "code": "def plot_xtb(fignum, XTB, Bs, e, f):\n    plt.figure(num=fignum)\n    plt.xlabel('Temperature (K)')\n    plt.ylabel('Susceptibility (m^3/kg)')\n    k = 0\n    Blab = []\n    for field in XTB:\n        T, X = [], []\n        for xt in field:\n            X.append(xt[0])\n            T.append(xt[1])\n        plt.plot(T, X)\n        plt.text(T[-1], X[-1], '%8.2e' % (Bs[k]) + ' T')\n        k += 1\n    plt.title(e + ': f = ' + '%i' % (int(f)) + ' Hz')",
    "docstring": "function to plot series of chi measurements as a function of temperature, holding frequency constant and varying B"
  },
  {
    "code": "def list_account_admins(self, account_id, user_id=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"account_id\"] = account_id\r\n        if user_id is not None:\r\n            params[\"user_id\"] = user_id\r\n        self.logger.debug(\"GET /api/v1/accounts/{account_id}/admins with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"GET\", \"/api/v1/accounts/{account_id}/admins\".format(**path), data=data, params=params, all_pages=True)",
    "docstring": "List account admins.\r\n\r\n        List the admins in the account"
  },
  {
    "code": "def lstm_init_states(batch_size):\n    hp = Hyperparams()\n    init_shapes = lstm.init_states(batch_size=batch_size, num_lstm_layer=hp.num_lstm_layer, num_hidden=hp.num_hidden)\n    init_names = [s[0] for s in init_shapes]\n    init_arrays = [mx.nd.zeros(x[1]) for x in init_shapes]\n    return init_names, init_arrays",
    "docstring": "Returns a tuple of names and zero arrays for LSTM init states"
  },
  {
    "code": "def index_library_datasets(self, tick_f=None):\n        dataset_n = 0\n        partition_n = 0\n        def tick(d, p):\n            if tick_f:\n                tick_f('datasets: {} partitions: {}'.format(d, p))\n        for dataset in self.library.datasets:\n            if self.backend.dataset_index.index_one(dataset):\n                dataset_n += 1\n                tick(dataset_n, partition_n)\n                for partition in dataset.partitions:\n                    self.backend.partition_index.index_one(partition)\n                    partition_n += 1\n                    tick(dataset_n, partition_n)\n            else:\n                pass",
    "docstring": "Indexes all datasets of the library.\n\n        Args:\n            tick_f (callable, optional): callable of one argument. Gets string with index state."
  },
  {
    "code": "def make_signed_token(self, key):\n        t = JWS(self.claims)\n        t.add_signature(key, protected=self.header)\n        self.token = t",
    "docstring": "Signs the payload.\n\n        Creates a JWS token with the header as the JWS protected header and\n        the claims as the payload. See (:class:`jwcrypto.jws.JWS`) for\n        details on the exceptions that may be reaised.\n\n        :param key: A (:class:`jwcrypto.jwk.JWK`) key."
  },
  {
    "code": "def valid_api_plugin(self, plugin):\n        if (issubclass(plugin, APIPlugin)       and\n            hasattr(plugin, 'plugin_type')      and plugin.plugin_type == 'api' and\n            hasattr(plugin, 'request')          and plugin.request != None and\n            hasattr(plugin, 'request_class')    and plugin.request_class != None and\n            hasattr(plugin, 'response_class')   and plugin.response_class != None):\n            return True\n        return False",
    "docstring": "Validate an API plugin, ensuring it is an API plugin and has the\n        necessary fields present.\n\n        `plugin` is a subclass of scruffy's Plugin class."
  },
  {
    "code": "def compile_bundle_entry(self, spec, entry):\n        modname, source, target, modpath = entry\n        bundled_modpath = {modname: modpath}\n        bundled_target = {modname: target}\n        export_module_name = []\n        if isfile(source):\n            export_module_name.append(modname)\n            copy_target = join(spec[BUILD_DIR], target)\n            if not exists(dirname(copy_target)):\n                makedirs(dirname(copy_target))\n            shutil.copy(source, copy_target)\n        elif isdir(source):\n            copy_target = join(spec[BUILD_DIR], modname)\n            shutil.copytree(source, copy_target)\n        return bundled_modpath, bundled_target, export_module_name",
    "docstring": "Handler for each entry for the bundle method of the compile\n        process.  This copies the source file or directory into the\n        build directory."
  },
  {
    "code": "def register_class(self, instance, name=None):\n        prefix_name = name or instance.__class__.__name__\n        for e in dir(instance):\n            if e[0][0] != \"_\":\n                self.register_function(\n                    getattr(instance, e),\n                    name=\"%s.%s\" % (prefix_name, e)\n                )",
    "docstring": "Add all functions of a class-instance to the RPC-services.\n\n        All entries of the instance which do not begin with '_' are added.\n\n        :Parameters:\n            - myinst: class-instance containing the functions\n            - name:   | hierarchical prefix.\n                      | If omitted, the functions are added directly.\n                      | If given, the functions are added as \"name.function\".\n        :TODO:\n            - only add functions and omit attributes?\n            - improve hierarchy?"
  },
  {
    "code": "def create_from_pybankid_exception(cls, exception):\n        return cls(\n            \"{0}: {1}\".format(exception.__class__.__name__, str(exception)),\n            _exception_class_to_status_code.get(exception.__class__),\n        )",
    "docstring": "Class method for initiating from a `PyBankID` exception.\n\n        :param bankid.exceptions.BankIDError exception:\n        :return: The wrapped exception.\n        :rtype: :py:class:`~FlaskPyBankIDError`"
  },
  {
    "code": "def loads(s, single=False):\n    corpus = etree.fromstring(s)\n    if single:\n        ds = _deserialize_mrs(next(corpus))\n    else:\n        ds = (_deserialize_mrs(mrs_elem) for mrs_elem in corpus)\n    return ds",
    "docstring": "Deserialize MRX string representations\n\n    Args:\n        s (str): a MRX string\n        single (bool): if `True`, only return the first Xmrs object\n    Returns:\n        a generator of Xmrs objects (unless *single* is `True`)"
  },
  {
    "code": "def wait_for(func, timeout=10, step=1, default=None, func_args=(), func_kwargs=None):\n    if func_kwargs is None:\n        func_kwargs = dict()\n    max_time = time.time() + timeout\n    step = min(step or 1, timeout) * BLUR_FACTOR\n    ret = default\n    while time.time() <= max_time:\n        call_ret = func(*func_args, **func_kwargs)\n        if call_ret:\n            ret = call_ret\n            break\n        else:\n            time.sleep(step)\n            step = min(step, max_time - time.time()) * BLUR_FACTOR\n    if time.time() > max_time:\n        log.warning(\"Exceeded waiting time (%s seconds) to exectute %s\", timeout, func)\n    return ret",
    "docstring": "Call `func` at regular intervals and Waits until the given function returns\n    a truthy value within the given timeout and returns that value.\n\n    @param func:\n    @type func: function\n    @param timeout:\n    @type timeout: int | float\n    @param step: Interval at which we should check for the value\n    @type step: int | float\n    @param default: Value that should be returned should `func` not return a truthy value\n    @type default:\n    @param func_args: *args for `func`\n    @type func_args: list | tuple\n    @param func_kwargs: **kwargs for `func`\n    @type func_kwargs: dict\n    @return: `default` or result of `func`"
  },
  {
    "code": "def _match_tags(repex_tags, path_tags):\n    if 'any' in repex_tags or (not repex_tags and not path_tags):\n        return True\n    elif set(repex_tags) & set(path_tags):\n        return True\n    return False",
    "docstring": "Check for matching tags between what the user provided\n    and the tags set in the config.\n\n    If `any` is chosen, match.\n    If no tags are chosen and none are configured, match.\n    If the user provided tags match any of the configured tags, match."
  },
  {
    "code": "def insert_data(self, node, data, start, end):\n        for item in data:\n            self.recursive_insert(node, [item[0], item[1]], item[-1], start, end)",
    "docstring": "loops through all the data and inserts them into the empty tree"
  },
  {
    "code": "def benchmark(self, func, gpu_args, instance, times, verbose):\n        logging.debug('benchmark ' + instance.name)\n        logging.debug('thread block dimensions x,y,z=%d,%d,%d', *instance.threads)\n        logging.debug('grid dimensions x,y,z=%d,%d,%d', *instance.grid)\n        time = None\n        try:\n            time = self.dev.benchmark(func, gpu_args, instance.threads, instance.grid, times)\n        except Exception as e:\n            skippable_exceptions = [\"too many resources requested for launch\", \"OUT_OF_RESOURCES\", \"INVALID_WORK_GROUP_SIZE\"]\n            if any([skip_str in str(e) for skip_str in skippable_exceptions]):\n                logging.debug('benchmark fails due to runtime failure too many resources required')\n                if verbose:\n                    print(\"skipping config\", instance.name, \"reason: too many resources requested for launch\")\n            else:\n                logging.debug('benchmark encountered runtime failure: ' + str(e))\n                print(\"Error while benchmarking:\", instance.name)\n                raise e\n        return time",
    "docstring": "benchmark the kernel instance"
  },
  {
    "code": "def create(self, credentials, friendly_name=values.unset,\n               account_sid=values.unset):\n        data = values.of({\n            'Credentials': credentials,\n            'FriendlyName': friendly_name,\n            'AccountSid': account_sid,\n        })\n        payload = self._version.create(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return AwsInstance(self._version, payload, )",
    "docstring": "Create a new AwsInstance\n\n        :param unicode credentials: A string that contains the AWS access credentials in the format <AWS_ACCESS_KEY_ID>:<AWS_SECRET_ACCESS_KEY>\n        :param unicode friendly_name: A string to describe the resource\n        :param unicode account_sid: The Subaccount this Credential should be associated with.\n\n        :returns: Newly created AwsInstance\n        :rtype: twilio.rest.accounts.v1.credential.aws.AwsInstance"
  },
  {
    "code": "def edterm(trmtyp, source, target, et, fixref, abcorr, obsrvr, npts):\n    trmtyp = stypes.stringToCharP(trmtyp)\n    source = stypes.stringToCharP(source)\n    target = stypes.stringToCharP(target)\n    et = ctypes.c_double(et)\n    fixref = stypes.stringToCharP(fixref)\n    abcorr = stypes.stringToCharP(abcorr)\n    obsrvr = stypes.stringToCharP(obsrvr)\n    trgepc = ctypes.c_double()\n    obspos = stypes.emptyDoubleVector(3)\n    trmpts = stypes.emptyDoubleMatrix(x=3, y=npts)\n    npts = ctypes.c_int(npts)\n    libspice.edterm_c(trmtyp, source, target, et, fixref, abcorr, obsrvr, npts,\n                      ctypes.byref(trgepc), obspos, trmpts)\n    return trgepc.value, stypes.cVectorToPython(obspos), stypes.cMatrixToNumpy(\n            trmpts)",
    "docstring": "Compute a set of points on the umbral or penumbral terminator of\n    a specified target body, where the target shape is modeled as an\n    ellipsoid.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/edterm_c.html\n\n    :param trmtyp: Terminator type.\n    :type trmtyp: str\n    :param source: Light source.\n    :type source: str\n    :param target: Target body.\n    :type target: str\n    :param et: Observation epoch.\n    :type et: str\n    :param fixref: Body-fixed frame associated with target.\n    :type fixref: str\n    :param abcorr: Aberration correction.\n    :type abcorr: str\n    :param obsrvr: Observer.\n    :type obsrvr: str\n    :param npts: Number of points in terminator set.\n    :type npts: int\n    :return:\n            Epoch associated with target center,\n            Position of observer in body-fixed frame,\n            Terminator point set.\n    :rtype: tuple"
  },
  {
    "code": "def timeout(seconds):\n    def _timeout_error(signal, frame):\n        raise TimeoutError(\"Operation did not finish within \\\n        {} seconds\".format(seconds))\n    def timeout_decorator(func):\n        @wraps(func)\n        def timeout_wrapper(*args, **kwargs):\n            signal.signal(signal.SIGALRM, _timeout_error)\n            signal.alarm(seconds)\n            try:\n                return func(*args, **kwargs)\n            finally:\n                signal.alarm(0)\n        return timeout_wrapper\n    return timeout_decorator",
    "docstring": "Raises a TimeoutError if a function does not terminate within\n    specified seconds."
  },
  {
    "code": "def synchronize_resources(self):\n        if not self._rpc.sync_start():\n            LOG.info(\"%(pid)s Failed to grab the sync lock\",\n                     {'pid': os.getpid()})\n            greenthread.sleep(1)\n            return\n        for resource in self._resources_to_update:\n            self.update_neutron_resource(resource)\n        self._resources_to_update = list()\n        for resource_type in reversed(self.sync_order):\n            resource_type.delete_cvx_resources()\n        for resource_type in self.sync_order:\n            resource_type.create_cvx_resources()\n        self._rpc.sync_end()\n        if self._synchronizing_uuid:\n            LOG.info(\"%(pid)s Full sync for cvx uuid %(uuid)s complete\",\n                     {'uuid': self._synchronizing_uuid,\n                      'pid': os.getpid()})\n            self._cvx_uuid = self._synchronizing_uuid\n            self._synchronizing_uuid = None",
    "docstring": "Synchronize worker with CVX\n\n        All database queries must occur while the sync lock is held. This\n        tightly couples reads with writes and ensures that an older read\n        does not result in the last write. Eg:\n\n        Worker 1 reads (P1 created)\n        Worder 2 reads (P1 deleted)\n        Worker 2 writes (Delete P1 from CVX)\n        Worker 1 writes (Create P1 on CVX)\n\n        By ensuring that all reads occur with the sync lock held, we ensure\n        that Worker 1 completes its writes before Worker2 is allowed to read.\n        A failure to write results in a full resync and purges all reads from\n        memory.\n\n        It is also important that we compute resources to sync in reverse sync\n        order in order to avoid missing dependencies on creation. Eg:\n\n        If we query in sync order\n        1. Query Instances -> I1 isn't there\n        2. Query Port table -> Port P1 is there, connected to I1\n        3. We send P1 to CVX without sending I1 -> Error raised\n\n        But if we query P1 first:\n        1. Query Ports P1 -> P1 is not there\n        2. Query Instances -> find I1\n        3. We create I1, not P1 -> harmless, mech driver creates P1\n\n        Missing dependencies on deletion will helpfully result in the\n        dependent resource not being created:\n        1. Query Ports -> P1 is found\n        2. Query Instances -> I1 not found\n        3. Creating P1 fails on CVX"
  },
  {
    "code": "def type(self):\n        return ffi.string(lib.EnvGetDefmessageHandlerType(\n            self._env, self._cls, self._idx)).decode()",
    "docstring": "MessageHandler type."
  },
  {
    "code": "def _cldf2wordlist(dataset, row='parameter_id', col='language_id'):\n    return lingpy.Wordlist(_cldf2wld(dataset), row=row, col=col)",
    "docstring": "Read worldist object from cldf dataset."
  },
  {
    "code": "def trace(fn):\n    def wrapped(*args, **kwargs):\n        msg = []\n        msg.append('Enter {}('.format(fn.__name__))\n        if args:\n            msg.append(', '.join([str(x) for x in args]))\n        if kwargs:\n            kwargs_str = ', '.join(['{}={}'.format(k, v) for k, v in list(kwargs.items())])\n            if args:\n                msg.append(', ')\n            msg.append(kwargs_str)\n        msg.append(')')\n        print(''.join(msg))\n        ret = fn(*args, **kwargs)\n        print('Return {}'.format(ret))\n        return ret\n    return wrapped",
    "docstring": "Prints parameteters and return values of the each call of the wrapped function.\n\n    Usage:\n        decorate appropriate function or method:\n            @trace\n            def myf():\n                ..."
  },
  {
    "code": "def sonos_uri_from_id(self, item_id):\n        item_id = quote_url(item_id.encode('utf-8'))\n        account = self.account\n        result = \"soco://{}?sid={}&sn={}\".format(\n            item_id, self.service_id,\n            account.serial_number\n        )\n        return result",
    "docstring": "Get a uri which can be sent for playing.\n\n        Args:\n            item_id (str): The unique id of a playable item for this music\n                service, such as that returned in the metadata from\n                `get_metadata`, eg ``spotify:track:2qs5ZcLByNTctJKbhAZ9JE``\n\n        Returns:\n            str: A URI of the form: ``soco://spotify%3Atrack\n            %3A2qs5ZcLByNTctJKbhAZ9JE?sid=2311&sn=1`` which encodes the\n            ``item_id``, and relevant data from the account for the music\n            service. This URI can be sent to a Sonos device for playing,\n            and the device itself will retrieve all the necessary metadata\n            such as title, album etc."
  },
  {
    "code": "def from_fptr(cls, label, type_, fptr):\n        return FSEntry(\n            label=label,\n            type=type_,\n            path=fptr.path,\n            use=fptr.use,\n            file_uuid=fptr.file_uuid,\n            derived_from=fptr.derived_from,\n            checksum=fptr.checksum,\n            checksumtype=fptr.checksumtype,\n        )",
    "docstring": "Return ``FSEntry`` object."
  },
  {
    "code": "def select_spread(\n    list_of_elements   = None,\n    number_of_elements = None\n    ):\n    if len(list_of_elements) <= number_of_elements:\n        return list_of_elements\n    if number_of_elements == 0:\n        return []\n    if number_of_elements == 1:\n        return [list_of_elements[int(round((len(list_of_elements) - 1) / 2))]]\n    return \\\n        [list_of_elements[int(round((len(list_of_elements) - 1) /\\\n        (2 * number_of_elements)))]] +\\\n        select_spread(list_of_elements[int(round((len(list_of_elements) - 1) /\\\n        (number_of_elements))):], number_of_elements - 1)",
    "docstring": "This function returns the specified number of elements of a list spread\n    approximately evenly."
  },
  {
    "code": "def js_on_change(self, event, *callbacks):\n        if len(callbacks) == 0:\n            raise ValueError(\"js_on_change takes an event name and one or more callbacks, got only one parameter\")\n        from bokeh.models.callbacks import CustomJS\n        if not all(isinstance(x, CustomJS) for x in callbacks):\n            raise ValueError(\"not all callback values are CustomJS instances\")\n        if event in self.properties():\n            event = \"change:%s\" % event\n        if event not in self.js_property_callbacks:\n            self.js_property_callbacks[event] = []\n        for callback in callbacks:\n            if callback in self.js_property_callbacks[event]:\n                continue\n            self.js_property_callbacks[event].append(callback)",
    "docstring": "Attach a ``CustomJS`` callback to an arbitrary BokehJS model event.\n\n        On the BokehJS side, change events for model properties have the\n        form ``\"change:property_name\"``. As a convenience, if the event name\n        passed to this method is also the name of a property on the model,\n        then it will be prefixed with ``\"change:\"`` automatically:\n\n        .. code:: python\n\n            # these two are equivalent\n            source.js_on_change('data', callback)\n            source.js_on_change('change:data', callback)\n\n        However, there are other kinds of events that can be useful to respond\n        to, in addition to property change events. For example to run a\n        callback whenever data is streamed to a ``ColumnDataSource``, use the\n        ``\"stream\"`` event on the source:\n\n        .. code:: python\n\n            source.js_on_change('streaming', callback)"
  },
  {
    "code": "def run_process(cwd, args):\n    try:\n        process = check_output(args, cwd=cwd, stderr=STDOUT)\n        return process\n    except CalledProcessError as e:\n        log('Uh oh, the teapot broke again! Error:', e, type(e), lvl=verbose, pretty=True)\n        log(e.cmd, e.returncode, e.output, lvl=verbose)\n        return e.output",
    "docstring": "Executes an external process via subprocess.Popen"
  },
  {
    "code": "def append(self, other):\n        if not isinstance(other, (list, tuple)):\n            other = [other]\n        if all((isinstance(o, MultiIndex) and o.nlevels >= self.nlevels)\n               for o in other):\n            arrays = []\n            for i in range(self.nlevels):\n                label = self._get_level_values(i)\n                appended = [o._get_level_values(i) for o in other]\n                arrays.append(label.append(appended))\n            return MultiIndex.from_arrays(arrays, names=self.names)\n        to_concat = (self.values, ) + tuple(k._values for k in other)\n        new_tuples = np.concatenate(to_concat)\n        try:\n            return MultiIndex.from_tuples(new_tuples, names=self.names)\n        except (TypeError, IndexError):\n            return Index(new_tuples)",
    "docstring": "Append a collection of Index options together\n\n        Parameters\n        ----------\n        other : Index or list/tuple of indices\n\n        Returns\n        -------\n        appended : Index"
  },
  {
    "code": "def _in_valid_interval(self, parameter, value):\n        if parameter not in self._parameterIntervals:\n            return True\n        interval = self._parameterIntervals[parameter]\n        if interval[2] and interval[3]:\n            return interval[0] <= value <= interval[1]\n        if not interval[2] and interval[3]:\n            return interval[0] <  value <= interval[1]\n        if interval[2] and not interval[3]:\n            return interval[0] <= value <  interval[1]\n        return interval[0] < value < interval[1]",
    "docstring": "Returns if the parameter is within its valid interval.\n\n        :param string parameter:     Name of the parameter that has to be checked.\n        :param numeric value:     Value of the parameter.\n\n        :return:    Returns :py:const:`True` it the value for the given parameter is valid,\n            :py:const:`False` otherwise.\n        :rtype: boolean"
  },
  {
    "code": "def reset_logformat_timestamped(logger: logging.Logger,\n                                extraname: str = \"\",\n                                level: int = logging.INFO) -> None:\n    namebit = extraname + \":\" if extraname else \"\"\n    fmt = (\"%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s:\" + namebit +\n           \"%(message)s\")\n    reset_logformat(logger, fmt=fmt)\n    logger.setLevel(level)",
    "docstring": "Apply a simple time-stamped log format to an existing logger, and set\n    its loglevel to either ``logging.DEBUG`` or ``logging.INFO``.\n\n    Args:\n        logger: logger to modify\n        extraname: additional name to append to the logger's name\n        level: log level to set"
  },
  {
    "code": "def prune_by_ngram_size(self, minimum=None, maximum=None):\n        self._logger.info('Pruning results by n-gram size')\n        if minimum:\n            self._matches = self._matches[\n                self._matches[constants.SIZE_FIELDNAME] >= minimum]\n        if maximum:\n            self._matches = self._matches[\n                self._matches[constants.SIZE_FIELDNAME] <= maximum]",
    "docstring": "Removes results rows whose n-gram size is outside the\n        range specified by `minimum` and `maximum`.\n\n        :param minimum: minimum n-gram size\n        :type minimum: `int`\n        :param maximum: maximum n-gram size\n        :type maximum: `int`"
  },
  {
    "code": "def _create_fig(\n    *,\n    x_sc=bq.LinearScale,\n    y_sc=bq.LinearScale,\n    x_ax=bq.Axis,\n    y_ax=bq.Axis,\n    fig=bq.Figure,\n    options={},\n    params={}\n):\n    params = _merge_with_defaults(params)\n    x_sc = x_sc(**_call_params(params['x_sc'], options))\n    y_sc = y_sc(**_call_params(params['y_sc'], options))\n    options = tz.merge(options, {'x_sc': x_sc, 'y_sc': y_sc})\n    x_ax = x_ax(**_call_params(params['x_ax'], options))\n    y_ax = y_ax(**_call_params(params['y_ax'], options))\n    options = tz.merge(options, {'x_ax': x_ax, 'y_ax': y_ax, 'marks': []})\n    fig = fig(**_call_params(params['fig'], options))\n    return fig",
    "docstring": "Initializes scales and axes for a bqplot figure and returns the resulting\n    blank figure. Each plot component is passed in as a class. The plot options\n    should be passed into options.\n\n    Any additional parameters to initialize plot components are passed into\n    params as a dict of { plot_component: { trait: value, ... } }\n\n    For example, to change the grid lines of the x-axis:\n    params={ 'x_ax': {'grid_lines' : 'solid'} }\n\n    If the param value is a function, it will be called with the options dict\n    augmented with all previously created plot elements. This permits\n    dependencies on plot elements:\n    params={ 'x_ax': {'scale': lambda opts: opts['x_sc'] } }"
  },
  {
    "code": "def _read_words(filename):\n  with tf.gfile.GFile(filename, \"r\") as f:\n    if sys.version_info[0] >= 3:\n      return f.read().replace(\"\\n\", \" %s \" % EOS).split()\n    else:\n      return f.read().decode(\"utf-8\").replace(\"\\n\", \" %s \" % EOS).split()",
    "docstring": "Reads words from a file."
  },
  {
    "code": "def str2tuple(str_in):\n    tuple_out = safe_eval(str_in)\n    if not isinstance(tuple_out, tuple):\n        tuple_out = None\n    return tuple_out",
    "docstring": "Extracts a tuple from a string.\n\n    Args:\n        str_in (string) that contains python tuple\n    Returns:\n        (dict) or None if no valid tuple was found\n    Raises:\n        -"
  },
  {
    "code": "def pull(rebase=True, refspec=None):\n    options = rebase and '--rebase' or ''\n    output = run('pull %s %s' % (options, refspec or ''))\n    return not re.search('up.to.date', output)",
    "docstring": "Pull refspec from remote repository to local\n\n    If refspec is left as None, then pull current branch\n    The '--rebase' option is used unless rebase is set to false"
  },
  {
    "code": "def _build_instance_group_args(self, instance_group):\n        params = {\n            'InstanceCount' : instance_group.num_instances,\n            'InstanceRole' : instance_group.role,\n            'InstanceType' : instance_group.type,\n            'Name' : instance_group.name,\n            'Market' : instance_group.market\n        }\n        if instance_group.market == 'SPOT':\n            params['BidPrice'] = instance_group.bidprice\n        return params",
    "docstring": "Takes an InstanceGroup; returns a dict that, when its keys are\n        properly prefixed, can be used for describing InstanceGroups in\n        RunJobFlow or AddInstanceGroups requests."
  },
  {
    "code": "def getNorthSouthClone(self, i):\n        north = self.getAdjacentClone(i, south=False)\n        south = self.getAdjacentClone(i)\n        return north, south",
    "docstring": "Returns the adjacent clone name from both sides."
  },
  {
    "code": "def get_meter(self, site, start, end, point_type='Green_Button_Meter',\n                  var=\"meter\", agg='MEAN', window='24h', aligned=True, return_names=True):\n        start = self.convert_to_utc(start)\n        end = self.convert_to_utc(end)\n        request = self.compose_MDAL_dic(point_type=point_type, site=site, start=start, end=end,\n                                        var=var, agg=agg, window=window, aligned=aligned)\n        resp = self.m.query(request)\n        if return_names:\n            resp = self.replace_uuid_w_names(resp)\n        return resp",
    "docstring": "Get meter data from MDAL.\n\n        Parameters\n        ----------\n        site            : str\n            Building name.\n        start           : str\n            Start date - 'YYYY-MM-DDTHH:MM:SSZ'\n        end             : str\n            End date - 'YYYY-MM-DDTHH:MM:SSZ'\n        point_type      : str\n            Type of data, i.e. Green_Button_Meter, Building_Electric_Meter...\n        var             : str\n            Variable - \"meter\", \"weather\"...\n        agg             : str\n            Aggregation - MEAN, SUM, RAW...\n        window          : str\n            Size of the moving window.\n        aligned         : bool\n            ???\n        return_names    : bool\n            ???\n\n        Returns\n        -------\n        (df, mapping, context)\n            ???"
  },
  {
    "code": "def sigma_from_site_prop(self):\n        num_coi = 0\n        if None in self.site_properties['grain_label']:\n            raise RuntimeError('Site were merged, this property do not work')\n        for tag in self.site_properties['grain_label']:\n            if 'incident' in tag:\n                num_coi += 1\n        return int(round(self.num_sites / num_coi))",
    "docstring": "This method returns the sigma value of the gb from site properties.\n        If the GB structure merge some atoms due to the atoms too closer with\n        each other, this property will not work."
  },
  {
    "code": "def bfill(arr, dim=None, limit=None):\n    axis = arr.get_axis_num(dim)\n    _limit = limit if limit is not None else arr.shape[axis]\n    return apply_ufunc(_bfill, arr,\n                       dask='parallelized',\n                       keep_attrs=True,\n                       output_dtypes=[arr.dtype],\n                       kwargs=dict(n=_limit, axis=axis)).transpose(*arr.dims)",
    "docstring": "backfill missing values"
  },
  {
    "code": "def dependencies_of(self, address):\n    assert address in self._target_by_address, (\n      'Cannot retrieve dependencies of {address} because it is not in the BuildGraph.'\n      .format(address=address)\n    )\n    return self._target_dependencies_by_address[address]",
    "docstring": "Returns the dependencies of the Target at `address`.\n\n    This method asserts that the address given is actually in the BuildGraph.\n\n    :API: public"
  },
  {
    "code": "def _send_cli_conf_string(self, nexus_host, cli_str):\n        starttime = time.time()\n        path_snip = snipp.PATH_USER_CMDS\n        body_snip = snipp.BODY_USER_CONF_CMDS % ('1', cli_str)\n        LOG.debug(\"NexusDriver CLI config for host %s: path: %s body: %s\",\n                  nexus_host, path_snip, body_snip)\n        self.nxapi_client.rest_post(path_snip, nexus_host, body_snip)\n        self.capture_and_print_timeshot(\n            starttime, \"send_cliconf\",\n            switch=nexus_host)",
    "docstring": "Sends CLI Config commands to Nexus switch using NXAPI."
  },
  {
    "code": "def add(self, component: Union[Component, Sequence[Component]]) -> None:\n        try:\n            self[Span(*self._available_cell())] = component\n        except NoUnusedCellsError:\n            span = list(self._spans.keys())[-1]\n            self._spans[span] += component",
    "docstring": "Add a widget to the grid in the next available cell.\n\n        Searches over columns then rows for available cells.\n\n        Parameters\n        ----------\n        components : bowtie._Component\n            A Bowtie widget instance."
  },
  {
    "code": "def appdata_roaming_dir():\n    install = arcpy.GetInstallInfo('desktop')\n    app_data = arcpy.GetSystemEnvironment(\"APPDATA\")\n    product_dir = ''.join((install['ProductName'], major_version()))\n    return os.path.join(app_data, 'ESRI', product_dir)",
    "docstring": "Returns the roaming AppData directory for the installed ArcGIS Desktop."
  },
  {
    "code": "def backtrack(self, source):\n        key = self.get_tok(source)\n        s = self[key]()\n        meta = s.metadata['original_source']\n        cls = meta['cls']\n        args = meta['args']\n        kwargs = meta['kwargs']\n        cls = import_name(cls)\n        sout = cls(*args, **kwargs)\n        sout.metadata = s.metadata['original_metadata']\n        sout.name = s.metadata['original_name']\n        return sout",
    "docstring": "Given a unique key in the store, recreate original source"
  },
  {
    "code": "def _get_price_id_for_upgrade(self, package_items, option, value, public=True):\n        warnings.warn(\"use _get_price_id_for_upgrade_option() instead\",\n                      DeprecationWarning)\n        option_category = {\n            'memory': 'ram',\n            'cpus': 'guest_core',\n            'nic_speed': 'port_speed'\n        }\n        category_code = option_category[option]\n        for item in package_items:\n            is_private = (item.get('units') == 'PRIVATE_CORE')\n            for price in item['prices']:\n                if 'locationGroupId' in price and price['locationGroupId']:\n                    continue\n                if 'categories' not in price:\n                    continue\n                categories = price['categories']\n                for category in categories:\n                    if not (category['categoryCode'] == category_code\n                            and str(item['capacity']) == str(value)):\n                        continue\n                    if option == 'cpus':\n                        if public and not is_private:\n                            return price['id']\n                        elif not public and is_private:\n                            return price['id']\n                    elif option == 'nic_speed':\n                        if 'Public' in item['description']:\n                            return price['id']\n                    else:\n                        return price['id']",
    "docstring": "Find the price id for the option and value to upgrade.\n\n        Deprecated in favor of _get_price_id_for_upgrade_option()\n\n        :param list package_items: Contains all the items related to an VS\n        :param string option: Describes type of parameter to be upgraded\n        :param int value: The value of the parameter to be upgraded\n        :param bool public: CPU will be in Private/Public Node."
  },
  {
    "code": "def catch_mon_errors(conn, logger, hostname, cfg, args):\n    monmap = mon_status_check(conn, logger, hostname, args).get('monmap', {})\n    mon_initial_members = get_mon_initial_members(args, _cfg=cfg)\n    public_addr = cfg.safe_get('global', 'public_addr')\n    public_network = cfg.safe_get('global', 'public_network')\n    mon_in_monmap = [\n        mon.get('name')\n        for mon in monmap.get('mons', [{}])\n        if mon.get('name') == hostname\n    ]\n    if mon_initial_members is None or not hostname in mon_initial_members:\n            logger.warning('%s is not defined in `mon initial members`', hostname)\n    if not mon_in_monmap:\n        logger.warning('monitor %s does not exist in monmap', hostname)\n        if not public_addr and not public_network:\n            logger.warning('neither `public_addr` nor `public_network` keys are defined for monitors')\n            logger.warning('monitors may not be able to form quorum')",
    "docstring": "Make sure we are able to catch up common mishaps with monitors\n    and use that state of a monitor to determine what is missing\n    and warn apropriately about it."
  },
  {
    "code": "def get_instance(self, payload):\n        return RoleInstance(self._version, payload, service_sid=self._solution['service_sid'], )",
    "docstring": "Build an instance of RoleInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.chat.v2.service.role.RoleInstance\n        :rtype: twilio.rest.chat.v2.service.role.RoleInstance"
  },
  {
    "code": "def raw_escape(pattern, unix=False):\n    pattern = util.norm_pattern(pattern, False, True)\n    return escape(pattern, unix)",
    "docstring": "Apply raw character transform before applying escape."
  },
  {
    "code": "def _init_credentials(self, oauth_token, oauth_token_secret):\n        \"Depending on the state passed in, get self._oauth up and running\"\n        if oauth_token and oauth_token_secret:\n            if self.verified:\n                self._init_oauth(oauth_token, oauth_token_secret)\n            else:\n                self.oauth_token = oauth_token\n                self.oauth_token_secret = oauth_token_secret\n        else:\n            oauth = OAuth1(\n                self.consumer_key,\n                client_secret=self.consumer_secret,\n                callback_uri=self.callback_uri,\n                rsa_key=self.rsa_key,\n                signature_method=self._signature_method\n            )\n            url = self.base_url + REQUEST_TOKEN_URL\n            headers = {'User-Agent': self.user_agent}\n            response = requests.post(url=url, headers=headers, auth=oauth)\n            self._process_oauth_response(response)",
    "docstring": "Depending on the state passed in, get self._oauth up and running"
  },
  {
    "code": "def _find_keys(self, identity='image'):\n        prefix = add_prefix('', identity)\n        raw_keys = self._find_keys_raw(prefix) or []\n        for raw_key in raw_keys:\n            yield del_prefix(raw_key)",
    "docstring": "Finds and returns all keys for identity,"
  },
  {
    "code": "def read_table(filename, sheetname, index_col=None):\n    if sheetname is None or \\\n            (hasattr(sheetname, '__iter__') \\\n            and not isinstance(sheetname, six.string_types)):\n        raise TypeError(\"sheetname should specify a single sheet\")\n    if packaging.version.parse(pd.__version__) \\\n                < packaging.version.parse('0.21'):\n        table = pd.read_excel(filename,\n                              sheetname=sheetname,\n                              index_col=index_col)\n    else:\n        table = pd.read_excel(filename,\n                              sheet_name=sheetname,\n                              index_col=index_col)\n    if index_col is not None:\n        table = table[pd.notnull(table.index)]\n    if table.index.has_duplicates:\n        raise ValueError(\"sheet {} on file {} contains duplicated values \"\n                         \"for column {}\".format(sheetname, filename, index_col))\n    return table",
    "docstring": "Return the contents of an Excel table as a pandas DataFrame.\n\n    Parameters\n    ----------\n    filename : str\n        Name of the Excel file to read.\n    sheetname : str or int\n        Name or index of the sheet inside the Excel file to read.\n    index_col : str, optional\n        Column name or index to be used as row labels of the DataFrame. If\n        None, default index will be used.\n\n    Returns\n    -------\n    table : DataFrame\n        A DataFrame containing the data in the specified Excel table. If\n        `index_col` is not None, rows in which their `index_col` field\n        is empty will not be present in `table`.\n\n    Raises\n    ------\n    ValueError\n        If `index_col` is specified and two rows contain the same\n        `index_col` field."
  },
  {
    "code": "def map(self, data, layout):\n        msg = \"{} should implement this method.\"\n        raise NotImplementedError(\n            msg.format(self.__class.__name__))",
    "docstring": "Assign a data points to panels\n\n        Parameters\n        ----------\n        data : DataFrame\n            Data for a layer\n        layout : DataFrame\n            As returned by self.compute_layout\n\n        Returns\n        -------\n        data : DataFrame\n            Data with all points mapped to the panels\n            on which they will be plotted."
  },
  {
    "code": "def collect_cases(data_dir):\n    cases = {}\n    for root, dirs, files in os.walk(data_dir):\n        if not dirs:\n            split_case = os.path.relpath(root, data_dir).split(os.path.sep)\n            if split_case[0] not in cases:\n                cases[split_case[0]] = []\n            cases[split_case[0]].append(\"-\".join(split_case[1:]))\n    return cases",
    "docstring": "Find all cases and subcases of a particular run type"
  },
  {
    "code": "def embedManifestDllCheck(target, source, env):\n    if env.get('WINDOWS_EMBED_MANIFEST', 0):\n        manifestSrc = target[0].get_abspath() + '.manifest'\n        if os.path.exists(manifestSrc):\n            ret = (embedManifestDllAction) ([target[0]],None,env)        \n            if ret:\n                raise SCons.Errors.UserError(\"Unable to embed manifest into %s\" % (target[0]))\n            return ret\n        else:\n            print('(embed: no %s.manifest found; not embedding.)'%str(target[0]))\n    return 0",
    "docstring": "Function run by embedManifestDllCheckAction to check for existence of manifest\n    and other conditions, and embed the manifest by calling embedManifestDllAction if so."
  },
  {
    "code": "def args(parsed_args, name=None):\n    strings = parsed_args.arg_strings(name)\n    files = [s for s in strings if os.path.isfile(s)]\n    if files:\n        streams = [open(f) for f in files]\n    else:\n        streams = []\n    if getattr(parsed_args, 'paste', not files):\n        streams.append(clipboard_stream())\n    if getattr(parsed_args, 'stdin', False):\n        streams.append(sys.stdin)\n    elif not streams:\n        streams = [sys.stdin]\n    return streams",
    "docstring": "Interpret parsed args to streams"
  },
  {
    "code": "def make_server(host, port, app=None, threaded=False, processes=1,\n                request_handler=None, passthrough_errors=False,\n                ssl_context=None):\n    if threaded and processes > 1:\n        raise ValueError(\"cannot have a multithreaded and \"\n                         \"multi process server.\")\n    elif threaded:\n        return ThreadedWSGIServer(host, port, app, request_handler,\n                                  passthrough_errors, ssl_context)\n    elif processes > 1:\n        return ForkingWSGIServer(host, port, app, processes, request_handler,\n                                 passthrough_errors, ssl_context)\n    else:\n        return BaseWSGIServer(host, port, app, request_handler,\n                              passthrough_errors, ssl_context)",
    "docstring": "Create a new server instance that is either threaded, or forks\n    or just processes one request after another."
  },
  {
    "code": "def _feature_most_population(self, results):\n        try:\n            populations = [i['population'] for i in results['hits']['hits']]\n            most_pop = results['hits']['hits'][np.array(populations).astype(\"int\").argmax()]\n            return most_pop['country_code3']\n        except Exception as e:\n            return \"\"",
    "docstring": "Find the placename with the largest population and return its country.\n        More population is a rough measure of importance.\n\n        Paramaters\n        ----------\n        results: dict\n            output of `query_geonames`\n\n        Returns\n        -------\n        most_pop: str\n            ISO code of country of place with largest population,\n            or empty string if none"
  },
  {
    "code": "def get_previous_tag(cls, el):\n        sibling = el.previous_sibling\n        while not cls.is_tag(sibling) and sibling is not None:\n            sibling = sibling.previous_sibling\n        return sibling",
    "docstring": "Get previous sibling tag."
  },
  {
    "code": "def events(self, event_id):\n        json = self.request('/events/%s' % event_id, method='GET')\n        status = json.get('status')\n        if status == 'OK':\n            event_json = json.get('event')\n            event = Event.from_json(event_json)\n            return event\n        else:\n            message = json.get('message')\n            raise DOPException('[%s]: %s' % (status, message))",
    "docstring": "This method is primarily used to report on the progress of an event\n        by providing the percentage of completion.\n\n        Required parameters\n\n            event_id:\n                Numeric, this is the id of the event you would like more\n                information about"
  },
  {
    "code": "def env(mounts):\n    f_mounts = [m.strip(\"/\") for m in mounts]\n    root = local.path(\"/\")\n    ld_libs = [root / m / \"lib\" for m in f_mounts]\n    ld_libs.extend([root / m / \"lib64\" for m in f_mounts])\n    paths = [root / m / \"bin\" for m in f_mounts]\n    paths.extend([root / m / \"sbin\" for m in f_mounts])\n    paths.extend([root / m for m in f_mounts])\n    return paths, ld_libs",
    "docstring": "Compute the environment of the change root for the user.\n\n    Args:\n        mounts: The mountpoints of the current user.\n    Return:\n        paths\n        ld_libs"
  },
  {
    "code": "def dinfContributingArea(self,\n                             contributing_area_grid,\n                             flow_dir_grid,\n                             outlet_shapefile=None,\n                             weight_grid=None,\n                             edge_contamination=False,\n                             ):\n        log(\"PROCESS: DinfContributingArea\")\n        cmd = [os.path.join(self.taudem_exe_path, 'areadinf'),\n               '-ang', flow_dir_grid,\n               '-sca', contributing_area_grid,\n               ]\n        if outlet_shapefile:\n            cmd += ['-o', outlet_shapefile]\n        if weight_grid:\n            cmd += ['-wg', weight_grid]\n        if not edge_contamination:\n            cmd = cmd + ['-nc']\n        self._run_mpi_cmd(cmd)\n        self._add_prj_file(flow_dir_grid,\n                           contributing_area_grid)",
    "docstring": "Calculates contributing area with Dinf method."
  },
  {
    "code": "def update(self, other=(), **kwargs):\n        _kwargs = dict(kwargs)\n        _kwargs.update(other)\n        for key, value in _kwargs.items():\n            self[key] = value",
    "docstring": "Just like `dict.update`"
  },
  {
    "code": "def song(self):\n        if self._song is None:\n            self._song = Song(self._song_data)\n        return self._song",
    "docstring": "the song associated with the project"
  },
  {
    "code": "def get_monomers(self, ligands=True, pseudo_group=False):\n        base_filters = dict(ligands=ligands, pseudo_group=pseudo_group)\n        restricted_mol_types = [x[0] for x in base_filters.items() if not x[1]]\n        in_groups = [x for x in self.filter_mol_types(restricted_mol_types)]\n        monomers = itertools.chain(\n            *(p.get_monomers(ligands=ligands) for p in in_groups))\n        return monomers",
    "docstring": "Retrieves all the `Monomers` from the `Assembly` object.\n\n        Parameters\n        ----------\n        ligands : bool, optional\n            If `true`, will include ligand `Monomers`.\n        pseudo_group : bool, optional\n            If `True`, will include pseudo atoms."
  },
  {
    "code": "def is_text_type(text):\n    if isinstance(text, six.text_type) or isinstance(text, six.string_types):\n        return True\n    return False",
    "docstring": "Check if given parameter is a string or not\n\n    Parameters\n    ----------\n    text : *\n        Parameter to be checked for text type\n\n    Returns\n    -------\n    bool\n        Whether parameter is a string or not"
  },
  {
    "code": "def initialize(self, params, repetition):\n    super(TinyCIFARExperiment, self).initialize(params, repetition)\n    self.network_type = params.get(\"network_type\", \"sparse\")",
    "docstring": "Initialize experiment parameters and default values from configuration file.\n    Called at the beginning of each experiment and each repetition."
  },
  {
    "code": "def safe_request(\n    url,\n    method=None,\n    params=None,\n    data=None,\n    json=None,\n    headers=None,\n    allow_redirects=False,\n    timeout=30,\n    verify_ssl=True,\n):\n    session = requests.Session()\n    kwargs = {}\n    if json:\n        kwargs['json'] = json\n        if not headers:\n            headers = {}\n        headers.setdefault('Content-Type', 'application/json')\n    if data:\n        kwargs['data'] = data\n    if params:\n        kwargs['params'] = params\n    if headers:\n        kwargs['headers'] = headers\n    if method is None:\n        method = 'POST' if (data or json) else 'GET'\n    response = session.request(\n        method=method,\n        url=url,\n        allow_redirects=allow_redirects,\n        timeout=timeout,\n        verify=verify_ssl,\n        **kwargs\n    )\n    return response",
    "docstring": "A slightly safer version of `request`."
  },
  {
    "code": "def load(self, path):\n        config = _Config.load(os.path.join(path, 'config.pkl'))\n        config.save_dir = path\n        self._vocab = vocab = ParserVocabulary.load(config.save_vocab_path)\n        with mx.Context(mxnet_prefer_gpu()):\n            self._parser = BiaffineParser(vocab, config.word_dims, config.tag_dims, config.dropout_emb,\n                                          config.lstm_layers,\n                                          config.lstm_hiddens, config.dropout_lstm_input, config.dropout_lstm_hidden,\n                                          config.mlp_arc_size,\n                                          config.mlp_rel_size, config.dropout_mlp, config.debug)\n            self._parser.load(config.save_model_path)\n        return self",
    "docstring": "Load from disk\n\n        Parameters\n        ----------\n        path : str\n            path to the directory which typically contains a config.pkl file and a model.bin file\n\n        Returns\n        -------\n        DepParser\n            parser itself"
  },
  {
    "code": "def stop_listener_thread(self):\n        self.should_listen = False\n        if self.sync_thread:\n            self.sync_thread.kill()\n            self.sync_thread.get()\n        if self._handle_thread is not None:\n            self._handle_thread.get()\n        self.sync_thread = None\n        self._handle_thread = None",
    "docstring": "Kills sync_thread greenlet before joining it"
  },
  {
    "code": "def _dumpNdarrayToFile(filelike, ndarray):\n    bytedata = ndarray.tobytes('C')\n    start = filelike.tell()\n    end = start + len(bytedata)\n    metadata = {'start': start, 'end': end, 'size': ndarray.size,\n                'dtype': ndarray.dtype.name, 'shape': ndarray.shape\n                }\n    filelike.write(bytedata)\n    return metadata",
    "docstring": "Serializes an N-dimensional ``numpy.array`` to bytes, writes the bytes to\n    the filelike object and returns a dictionary with metadata, necessary to\n    restore the ``numpy.array`` from the file.\n\n    :param filelike: can be a file or a file-like object that provides the\n        methods ``.write()`` and ``.tell()``.\n    :param ndarray: a N-dimensional ``numpy.array``\n\n    :returns: a metadata dictionary ::\n        {'start': start position in the file, 'end': end position in the file,\n         'size': size of the array, 'dtype': numpy data type of the array,\n         'shape': description of the array shape\n         }"
  },
  {
    "code": "def clone_with_git(repo_uri, dest_path):\n    log.info('Cloning git repo %s to %s', repo_uri, dest_path)\n    git.Repo.clone_from(repo_uri, dest_path, depth=1)",
    "docstring": "Create a clone by cloning a git repository.\n\n    Args:\n        repo_uri: The URI of the git repository to clone.\n        dest_path: The location to clone to."
  },
  {
    "code": "def delete_network_postcommit(self, context):\n        segments = context.network_segments\n        network_name = context.current['name']\n        for segment in segments:\n            if not self.check_segment(segment):\n                return\n            vlan_id = segment.get(api.SEGMENTATION_ID)\n            if not vlan_id:\n                return\n            port_profile = self.make_profile_name(vlan_id)\n            trunk_vlans = (\n                CONF.sriov_multivlan_trunk.network_vlans.get(network_name, []))\n            self.driver.delete_all_config_for_vlan(vlan_id, port_profile,\n                trunk_vlans)",
    "docstring": "Delete all configuration added to UCS Manager for the vlan_id."
  },
  {
    "code": "def make_full_qualified_url(self, path: str) -> str:\n        return self.application_uri.rstrip('/') + '/' + path.lstrip('/')",
    "docstring": "append application url to path"
  },
  {
    "code": "def aws(product, tile, folder, redownload, info, entire, bands, l2a):\n    band_list = None if bands is None else bands.split(',')\n    data_source = DataSource.SENTINEL2_L2A if l2a else DataSource.SENTINEL2_L1C\n    if info:\n        if product is None:\n            click.echo(get_safe_format(tile=tile, entire_product=entire, data_source=data_source))\n        else:\n            click.echo(get_safe_format(product_id=product))\n    else:\n        if product is None:\n            download_safe_format(tile=tile, folder=folder, redownload=redownload, entire_product=entire,\n                                 bands=band_list, data_source=data_source)\n        else:\n            download_safe_format(product_id=product, folder=folder, redownload=redownload, bands=band_list)",
    "docstring": "Download Sentinel-2 data from Sentinel-2 on AWS to ESA SAFE format. Download uses multiple threads.\n\n    \\b\n    Examples with Sentinel-2 L1C data:\n      sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551\n      sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 -i\n      sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 -f /home/ESA_Products\n      sentinelhub.aws --product S2A_MSIL1C_20170414T003551_N0204_R016_T54HVH_20170414T003551 --bands B08,B11\n      sentinelhub.aws --tile T54HVH 2017-04-14\n      sentinelhub.aws --tile T54HVH 2017-04-14 -e\n\n    \\b\n    Examples with Sentinel-2 L2A data:\n      sentinelhub.aws --product S2A_MSIL2A_20180402T151801_N0207_R068_T33XWJ_20180402T202222\n      sentinelhub.aws --tile T33XWJ 2018-04-02 --l2a"
  },
  {
    "code": "def _pot_month_counts(self, pot_dataset):\n        periods = pot_dataset.continuous_periods()\n        result = [set() for x in range(12)]\n        for period in periods:\n            year = period.start_date.year\n            month = period.start_date.month\n            while True:\n                result[month - 1].add(year)\n                if year == period.end_date.year and month == period.end_date.month:\n                    break\n                month += 1\n                if month == 13:\n                    month = 1\n                    year += 1\n        return result",
    "docstring": "Return a list of 12 sets. Each sets contains the years included in the POT record period.\n\n        :param pot_dataset: POT dataset (records and meta data)\n        :type pot_dataset: :class:`floodestimation.entities.PotDataset`"
  },
  {
    "code": "def check_attr_dimension(attr_id, **kwargs):\n    attr_i = _get_attr(attr_id)\n    datasets = db.DBSession.query(Dataset).filter(Dataset.id == ResourceScenario.dataset_id,\n                        ResourceScenario.resource_attr_id == ResourceAttr.id,\n                        ResourceAttr.attr_id == attr_id).all()\n    bad_datasets = []\n    for d in datasets:\n        if  attr_i.dimension_id is None and d.unit is not None or \\\n            attr_i.dimension_id is not None and d.unit is None or \\\n            units.get_dimension_by_unit_id(d.unit_id) != attr_i.dimension_id:\n                bad_datasets.append(d.id)\n    if len(bad_datasets) > 0:\n        raise HydraError(\"Datasets %s have a different dimension_id to attribute %s\"%(bad_datasets, attr_id))\n    return 'OK'",
    "docstring": "Check that the dimension of the resource attribute data is consistent\n        with the definition of the attribute.\n        If the attribute says 'volume', make sure every dataset connected\n        with this attribute via a resource attribute also has a dimension\n        of 'volume'."
  },
  {
    "code": "def get_columns(self, index, columns=None, as_dict=False):\n        i = sorted_index(self._index, index) if self._sort else self._index.index(index)\n        return self.get_location(i, columns, as_dict)",
    "docstring": "For a single index and list of column names return a DataFrame of the values in that index as either a dict\n        or a DataFrame\n\n        :param index: single index value\n        :param columns: list of column names\n        :param as_dict: if True then return the result as a dictionary\n        :return: DataFrame or dictionary"
  },
  {
    "code": "def validate(self):\n        if self.status_code == 200 and self.data.get(\"ok\", False):\n            self._logger.debug(\"Received the following response: %s\", self.data)\n            return self\n        msg = \"The request to the Slack API failed.\"\n        raise e.SlackApiError(message=msg, response=self.data)",
    "docstring": "Check if the response from Slack was successful.\n\n        Returns:\n            (SlackResponse)\n                This method returns it's own object. e.g. 'self'\n\n        Raises:\n            SlackApiError: The request to the Slack API failed."
  },
  {
    "code": "def _validate_format(req):\n        for key in SLOJSONRPC._min_keys:\n            if not key in req:\n                logging.debug('JSONRPC: Fmt Error: Need key \"%s\"' % key)\n                raise SLOJSONRPCError(-32600)\n        for key in req.keys():\n            if not key in SLOJSONRPC._allowed_keys:\n                logging.debug('JSONRPC: Fmt Error: Not allowed key \"%s\"' % key)\n                raise SLOJSONRPCError(-32600)\n        if req['jsonrpc'] != '2.0':\n            logging.debug('JSONRPC: Fmt Error: \"jsonrpc\" needs to be \"2.0\"')\n            raise SLOJSONRPCError(-32600)",
    "docstring": "Validate jsonrpc compliance of a jsonrpc-dict.\n\n        req - the request as a jsonrpc-dict\n\n        raises SLOJSONRPCError on validation error"
  },
  {
    "code": "def pre_run_hook(self, func, prefix=None):\n        cf = self.capture(func, prefix=prefix)\n        self.pre_run_hooks.append(cf)\n        return cf",
    "docstring": "Decorator to add a pre-run hook to this ingredient.\n\n        Pre-run hooks are captured functions that are run, just before the\n        main function is executed."
  },
  {
    "code": "def to_execution_plan(self,\n                          domain,\n                          default_screen,\n                          start_date,\n                          end_date):\n        if self._domain is not GENERIC and self._domain is not domain:\n            raise AssertionError(\n                \"Attempted to compile Pipeline with domain {} to execution \"\n                \"plan with different domain {}.\".format(self._domain, domain)\n            )\n        return ExecutionPlan(\n            domain=domain,\n            terms=self._prepare_graph_terms(default_screen),\n            start_date=start_date,\n            end_date=end_date,\n        )",
    "docstring": "Compile into an ExecutionPlan.\n\n        Parameters\n        ----------\n        domain : zipline.pipeline.domain.Domain\n            Domain on which the pipeline will be executed.\n        default_screen : zipline.pipeline.term.Term\n            Term to use as a screen if self.screen is None.\n        all_dates : pd.DatetimeIndex\n            A calendar of dates to use to calculate starts and ends for each\n            term.\n        start_date : pd.Timestamp\n            The first date of requested output.\n        end_date : pd.Timestamp\n            The last date of requested output.\n\n        Returns\n        -------\n        graph : zipline.pipeline.graph.ExecutionPlan\n            Graph encoding term dependencies, including metadata about extra\n            row requirements."
  },
  {
    "code": "def update_leads_list(self, leads_list_id, name, team_id=None):\n        params = self.base_params\n        payload = {'name': name}\n        if team_id:\n            payload['team_id'] = team_id\n        endpoint = self.base_endpoint.format('leads_lists/' + str(leads_list_id))\n        return self._query_hunter(endpoint, params, 'put', payload)",
    "docstring": "Update a leads list.\n\n        :param name: Name of the list to update. Must be defined.\n\n        :param team_id: The id of the list to share this list with.\n\n        :return: 204 Response."
  },
  {
    "code": "def list_images(self):\n        r = self.get(self.registry_url + '/v2/_catalog', auth=self.auth)\n        return r.json()['repositories']",
    "docstring": "List images stored in the registry.\n\n        Returns:\n            list[str]: List of image names."
  },
  {
    "code": "def upgradeBatch(self, n):\n        store = self.store\n        def _doBatch(itemType):\n            upgradedAnything = False\n            for theItem in store.query(itemType, limit=n):\n                upgradedAnything = True\n                try:\n                    self.upgradeItem(theItem)\n                except:\n                    f = Failure()\n                    raise ItemUpgradeError(\n                        f, theItem.storeID, itemType,\n                        _typeNameToMostRecentClass[itemType.typeName])\n            return upgradedAnything\n        if self.upgradesPending:\n            didAny = False\n            while self._oldTypesRemaining:\n                t0 = self._oldTypesRemaining[0]\n                upgradedAnything = store.transact(_doBatch, t0)\n                if not upgradedAnything:\n                    self._oldTypesRemaining.pop(0)\n                    if didAny:\n                        msg(\"%s finished upgrading %s\" % (store.dbdir.path, qual(t0)))\n                    continue\n                elif not didAny:\n                    didAny = True\n                    msg(\"%s beginning upgrade...\" % (store.dbdir.path,))\n                yield None\n            if didAny:\n                msg(\"%s completely upgraded.\" % (store.dbdir.path,))",
    "docstring": "Upgrade the entire store in batches, yielding after each batch.\n\n        @param n: Number of upgrades to perform per transaction\n        @type n: C{int}\n\n        @raise axiom.errors.ItemUpgradeError: if an item upgrade failed\n\n        @return: A generator that yields after each batch upgrade. This needs\n            to be consumed for upgrading to actually take place."
  },
  {
    "code": "def _warmup(self, num_updates):\n        assert self.base_lr is not None\n        if not self.warmup:\n            return self.base_lr\n        fraction = (num_updates + 1) * self.base_lr / (self.warmup + 1)\n        if num_updates > self.last_warmup_log and num_updates % self.log_warmup_every_t == 0:\n            self.last_warmup_log = num_updates\n            logger.info(\"Learning rate warmup: %3.0f%%\", fraction / self.base_lr * 100.0)\n        return fraction",
    "docstring": "Returns linearly increasing fraction of base_lr."
  },
  {
    "code": "def list_subnetpools(self, retrieve_all=True, **_params):\n        return self.list('subnetpools', self.subnetpools_path, retrieve_all,\n                         **_params)",
    "docstring": "Fetches a list of all subnetpools for a project."
  },
  {
    "code": "def require_foreign(namespace, symbol=None):\n    try:\n        if symbol is None:\n            get_foreign_module(namespace)\n        else:\n            get_foreign_struct(namespace, symbol)\n    except ForeignError as e:\n        raise ImportError(e)",
    "docstring": "Raises ImportError if the specified foreign module isn't supported or\n    the needed dependencies aren't installed.\n\n    e.g.: check_foreign('cairo', 'Context')"
  },
  {
    "code": "def downloadSessionImages(server, filename=None, height=150, width=150,\n                          opacity=100, saturation=100):\n    info = {}\n    for media in server.sessions():\n        url = None\n        for part in media.iterParts():\n            if media.thumb:\n                url = media.thumb\n            if part.indexes:\n                url = '/library/parts/%s/indexes/%s/%s' % (part.id, part.indexes.lower(), media.viewOffset)\n        if url:\n            if filename is None:\n                prettyname = media._prettyfilename()\n                filename = 'session_transcode_%s_%s_%s' % (media.usernames[0], prettyname, int(time.time()))\n            url = server.transcodeImage(url, height, width, opacity, saturation)\n            filepath = download(url, filename=filename)\n            info['username'] = {'filepath': filepath, 'url': url}\n    return info",
    "docstring": "Helper to download a bif image or thumb.url from plex.server.sessions.\n\n       Parameters:\n           filename (str): default to None,\n           height (int): Height of the image.\n           width (int): width of the image.\n           opacity (int): Opacity of the resulting image (possibly deprecated).\n           saturation (int): Saturating of the resulting image.\n\n       Returns:\n            {'hellowlol': {'filepath': '<filepath>', 'url': 'http://<url>'},\n            {'<username>': {filepath, url}}, ..."
  },
  {
    "code": "async def set_as_default_gateway(self):\n        interface = self._data['interface']\n        await interface._handler.set_default_gateway(\n            system_id=interface.node.system_id, id=interface.id,\n            link_id=self.id)",
    "docstring": "Set this link as the default gateway for the node."
  },
  {
    "code": "def _flush_ndb_puts(self, items, options):\n    assert ndb is not None\n    ndb.put_multi(items, config=self._create_config(options))",
    "docstring": "Flush all NDB puts to datastore."
  },
  {
    "code": "def prefetch_translations(instances, **kwargs):\n    from .mixins import ModelMixin\n    if not isinstance(instances, collections.Iterable):\n        instances = [instances]\n    populate_missing = kwargs.get(\"populate_missing\", True)\n    grouped_translations = utils.get_grouped_translations(instances, **kwargs)\n    if not grouped_translations and populate_missing:\n        for instance in instances:\n            instance.populate_missing_translations()\n    for instance in instances:\n        if (\n            issubclass(instance.__class__, ModelMixin)\n            and instance.pk in grouped_translations\n        ):\n            for translation in grouped_translations[instance.pk]:\n                instance._linguist.set_cache(instance=instance, translation=translation)\n            if populate_missing:\n                instance.populate_missing_translations()",
    "docstring": "Prefetches translations for the given instances.\n    Can be useful for a list of instances."
  },
  {
    "code": "def retry(self):\n        logger.info('Job {0} retrying all failed tasks'.format(self.name))\n        self.initialize_snapshot()\n        failed_task_names = []\n        for task_name, log in self.run_log['tasks'].items():\n            if log.get('success', True) == False:\n                failed_task_names.append(task_name)\n        if len(failed_task_names) == 0:\n            raise DagobahError('no failed tasks to retry')\n        self._set_status('running')\n        self.run_log['last_retry_time'] = datetime.utcnow()\n        logger.debug('Job {0} seeding run logs'.format(self.name))\n        for task_name in failed_task_names:\n            self._put_task_in_run_log(task_name)\n            self.tasks[task_name].start()\n        self._commit_run_log()",
    "docstring": "Restarts failed tasks of a job."
  },
  {
    "code": "def register_entry_points(self):\n        for entrypoint in entrypoints.get_group_all(\"papermill.engine\"):\n            self.register(entrypoint.name, entrypoint.load())",
    "docstring": "Register entrypoints for an engine\n\n        Load handlers provided by other packages"
  },
  {
    "code": "def _promote_solitary_xvowel(self):\n        char_type = self.active_char_type\n        if char_type == VOWEL or char_type == CV or self.active_xvowel is None:\n            return\n        self._set_char(self.active_xvowel, XVOWEL)\n        self.active_xvowel = None\n        self.active_xvowel_info = None",
    "docstring": "\"Promotes\" the current xvowel to a regular vowel, in case\n        it is not otherwise connected to a character.\n        Used to print small vowels that would otherwise get lost;\n        normally small vowels always form a pair, but in case one is\n        by itself it should basically act like a regular vowel."
  },
  {
    "code": "def rule(ctxt, name):\n    if name in ctxt.rule_cache:\n        ctxt.stack.append(ctxt.rule_cache[name])\n        return\n    try:\n        rule = ctxt.policy[name]\n    except KeyError:\n        log = logging.getLogger('policies')\n        log.warn(\"Request to evaluate non-existant rule %r \"\n                 \"while evaluating rule %r\" % (name, ctxt.name))\n        ctxt.stack.append(False)\n        ctxt.rule_cache[name] = False\n        return\n    with ctxt.push_rule(name):\n        rule.instructions(ctxt, True)\n    ctxt.rule_cache[name] = ctxt.stack[-1]",
    "docstring": "Allows evaluation of another rule while evaluating a rule.\n\n    :param ctxt: The evaluation context for the rule.\n    :param name: The name of the rule to evaluate."
  },
  {
    "code": "def catalog(self, table='', column=''):\n        lookup_table = self.lookup_table\n        if lookup_table is not None:\n            if table:\n                if column:\n                    column = column.upper()\n                    return lookup_table[table][column]\n                return lookup_table[table]\n            return self.lookup_methods\n        return None",
    "docstring": "Lookup the values available for querying."
  },
  {
    "code": "def _check_pattern_list(patterns, key, default=None):\n    if not patterns:\n        return default\n    if isinstance(patterns, basestring):\n        return [patterns]\n    if isinstance(patterns, list):\n        if all(isinstance(p, basestring) for p in patterns):\n            return patterns\n    raise ValueError(\"Invalid file patterns in key '{}': must be a string or \"\n                     'list of strings'.format(key))",
    "docstring": "Validates file search patterns from user configuration.\n\n    Acceptable input is a string (which will be converted to a singleton list),\n    a list of strings, or anything falsy (such as None or an empty dictionary).\n    Empty or unset input will be converted to a default.\n\n    Args:\n        patterns: input from user configuration (YAML).\n        key (str): name of the configuration key the input came from,\n            used for error display purposes.\n\n    Keyword Args:\n        default: value to return in case the input is empty or unset.\n\n    Returns:\n        list[str]: validated list of patterns\n\n    Raises:\n        ValueError: if the input is unacceptable."
  },
  {
    "code": "def _sanitize_resources(cls, resources):\n        try:\n            for resource in cls._loop_raw(resources):\n                cls._sanitize_resource(resource)\n        except (KeyError, TypeError):\n            _LOGGER.debug(\"no shade data available\")\n            return None",
    "docstring": "Loops over incoming data looking for base64 encoded data and\n        converts them to a readable format."
  },
  {
    "code": "def make_wcs_data_from_hpx_data(self, hpx_data, wcs, normalize=True):\n        wcs_data = np.zeros(wcs.npix)\n        self.fill_wcs_map_from_hpx_data(hpx_data, wcs_data, normalize)\n        return wcs_data",
    "docstring": "Creates and fills a wcs map from the hpx data using the pre-calculated\n        mappings\n\n        hpx_data  : the input HEALPix data\n        wcs       : the WCS object\n        normalize : True -> perserve integral by splitting HEALPix values between bins"
  },
  {
    "code": "def rouge_1(hypotheses, references):\n    rouge_1 = [\n        rouge_n([hyp], [ref], 1) for hyp, ref in zip(hypotheses, references)\n    ]\n    rouge_1_f, _, _ = map(np.mean, zip(*rouge_1))\n    return rouge_1_f",
    "docstring": "Calculate ROUGE-1 F1, precision, recall scores"
  },
  {
    "code": "def aggregate_data(self, start, end, aggregation, keys=[], tags=[],\n                       attrs={}, rollup=None, period=None, interpolationf=None,\n                       interpolation_period=None, tz=None, limit=1000):\n        url = 'segment'\n        vstart = check_time_param(start)\n        vend = check_time_param(end)\n        params = {\n            'start': vstart,\n            'end': vend,\n            'key': keys,\n            'tag': tags,\n            'attr': attrs,\n            'aggregation.fold': aggregation,\n            'rollup.fold': rollup,\n            'rollup.period': period,\n            'interpolation.function': interpolationf,\n            'interpolation.period': interpolation_period,\n            'tz': tz,\n            'limit': limit\n        }\n        url_args = endpoint.make_url_args(params)\n        url = '?'.join([url, url_args])\n        resp = self.session.get(url)\n        return resp",
    "docstring": "Read data from multiple series according to a filter and apply a\n        function across all the returned series to put the datapoints together\n        into one aggregrate series.\n\n        See the :meth:`list_series` method for a description of how the filter\n        criteria are applied, and the :meth:`read_data` method for how to\n        work with the start, end, and tz parameters.\n\n        Valid aggregation functions are the same as valid rollup functions.\n\n        :param string aggregation: the aggregation to perform\n        :param keys: (optional) filter by one or more series keys\n        :type keys: list or string\n        :param tags: (optional) filter by one or more tags\n        :type tags: list or string\n        :param dict attrs: (optional) filter by one or more key-value\n                           attributes\n        :param start: the start time for the data points\n        :type start: string or Datetime\n        :param end: the end time for the data points\n        :type end: string or Datetime\n        :param string rollup: (optional) the name of a rollup function to use\n        :param string period: (optional) downsampling rate for the data\n        :param string interpolationf: (optional) an interpolation function\n                                      to run over the series\n        :param string interpolation_period: (optional) the period to\n                                            interpolate data into\n        :param string tz: (optional) the timezone to place the data into\n        :rtype: :class:`tempodb.protocol.cursor.DataPointCursor` with an\n                iterator over :class:`tempodb.protocol.objects.DataPoint`\n                objects"
  },
  {
    "code": "def jd_to_datetime(jd):\n    year, month, day = jd_to_date(jd)\n    frac_days,day = math.modf(day)\n    day = int(day)\n    hour,min,sec,micro = days_to_hmsm(frac_days)\n    return datetime(year,month,day,hour,min,sec,micro)",
    "docstring": "Convert a Julian Day to an `jdutil.datetime` object.\n\n    Parameters\n    ----------\n    jd : float\n        Julian day.\n\n    Returns\n    -------\n    dt : `jdutil.datetime` object\n        `jdutil.datetime` equivalent of Julian day.\n\n    Examples\n    --------\n    >>> jd_to_datetime(2446113.75)\n    datetime(1985, 2, 17, 6, 0)"
  },
  {
    "code": "def generate_new_bracket(self):\n        logger.debug(\n            'start to create a new SuccessiveHalving iteration, self.curr_s=%d', self.curr_s)\n        if self.curr_s < 0:\n            logger.info(\"s < 0, Finish this round of Hyperband in BOHB. Generate new round\")\n            self.curr_s = self.s_max\n        self.brackets[self.curr_s] = Bracket(s=self.curr_s, s_max=self.s_max, eta=self.eta,\n                                    max_budget=self.max_budget, optimize_mode=self.optimize_mode)\n        next_n, next_r = self.brackets[self.curr_s].get_n_r()\n        logger.debug(\n            'new SuccessiveHalving iteration, next_n=%d, next_r=%d', next_n, next_r)\n        generated_hyper_configs = self.brackets[self.curr_s].get_hyperparameter_configurations(\n            next_n, next_r, self.cg)\n        self.generated_hyper_configs = generated_hyper_configs.copy()",
    "docstring": "generate a new bracket"
  },
  {
    "code": "def started(name):\n    ret = {'name': name,\n           'changes': {},\n           'comment': '',\n           'result': False}\n    volinfo = __salt__['glusterfs.info']()\n    if name not in volinfo:\n        ret['result'] = False\n        ret['comment'] = 'Volume {0} does not exist'.format(name)\n        return ret\n    if int(volinfo[name]['status']) == 1:\n        ret['comment'] = 'Volume {0} is already started'.format(name)\n        ret['result'] = True\n        return ret\n    elif __opts__['test']:\n        ret['comment'] = 'Volume {0} will be started'.format(name)\n        ret['result'] = None\n        return ret\n    vol_started = __salt__['glusterfs.start_volume'](name)\n    if vol_started:\n        ret['result'] = True\n        ret['comment'] = 'Volume {0} is started'.format(name)\n        ret['change'] = {'new': 'started', 'old': 'stopped'}\n    else:\n        ret['result'] = False\n        ret['comment'] = 'Failed to start volume {0}'.format(name)\n    return ret",
    "docstring": "Check if volume has been started\n\n    name\n        name of the volume\n\n    .. code-block:: yaml\n\n        mycluster:\n          glusterfs.started: []"
  },
  {
    "code": "def get_project(self, project_id):\n        try:\n            result = self._request('/getproject/',\n                                   {'projectid': project_id})\n            return TildaProject(**result)\n        except NetworkError:\n            return []",
    "docstring": "Get project info"
  },
  {
    "code": "def sumlogs(x, axis=None, out=None):\n    maxx = x.max(axis=axis, keepdims=True)\n    xnorm = x - maxx\n    np.exp(xnorm, out=xnorm)\n    out = np.sum(xnorm, axis=axis, out=out)\n    if isinstance(out, np.ndarray):\n        np.log(out, out=out)\n    else:\n        out = np.log(out)\n    out += np.squeeze(maxx)\n    return out",
    "docstring": "Sum of vector where numbers are represented by their logarithms.\n\n    Calculates ``np.log(np.sum(np.exp(x), axis=axis))`` in such a fashion that\n    it works even when elements have large magnitude."
  },
  {
    "code": "def _keep_this(self, name):\n        for keep_name in self.keep:\n            if name == keep_name:\n                return True\n        return False",
    "docstring": "Return True if there are to be no modifications to name."
  },
  {
    "code": "def _find_output_dependencies(self, outputs):\n        dependencies = []\n        for address in outputs:\n            dependencies.extend(\n                self._predecessor_tree.find_write_predecessors(address))\n        return dependencies",
    "docstring": "Use the predecessor tree to find dependencies based on outputs.\n\n        Returns: A list of transaction ids."
  },
  {
    "code": "def enable(self):\n        if not CrashReporter.active:\n            CrashReporter.active = True\n            self._excepthook = sys.excepthook\n            sys.excepthook = self.exception_handler\n            self.logger.info('CrashReporter: Enabled')\n            if self.report_dir:\n                if os.path.exists(self.report_dir):\n                    if self.get_offline_reports():\n                        self.submit_offline_reports()\n                        remaining_reports = len(self.get_offline_reports())\n                        if remaining_reports and self.watcher_enabled:\n                            self.start_watcher()\n                else:\n                    os.makedirs(self.report_dir)",
    "docstring": "Enable the crash reporter. CrashReporter is defaulted to be enabled on creation."
  },
  {
    "code": "def get_state(self, key=None, drop_defaults=False):\n        if key is None:\n            keys = self.keys\n        elif isinstance(key, string_types):\n            keys = [key]\n        elif isinstance(key, collections.Iterable):\n            keys = key\n        else:\n            raise ValueError(\"key must be a string, an iterable of keys, or None\")\n        state = {}\n        traits = self.traits()\n        for k in keys:\n            to_json = self.trait_metadata(k, 'to_json', self._trait_to_json)\n            value = to_json(getattr(self, k), self)\n            if not PY3 and isinstance(traits[k], Bytes) and isinstance(value, bytes):\n                value = memoryview(value)\n            if not drop_defaults or not self._compare(value, traits[k].default_value):\n                state[k] = value\n        return state",
    "docstring": "Gets the widget state, or a piece of it.\n\n        Parameters\n        ----------\n        key : unicode or iterable (optional)\n            A single property's name or iterable of property names to get.\n\n        Returns\n        -------\n        state : dict of states\n        metadata : dict\n            metadata for each field: {key: metadata}"
  },
  {
    "code": "def get_nt_filename (path):\n    unc, rest = os.path.splitunc(path)\n    head, tail = os.path.split(rest)\n    if not tail:\n        return path\n    for fname in os.listdir(unc+head):\n        if fname.lower() == tail.lower():\n            return os.path.join(get_nt_filename(unc+head), fname)\n    log.error(LOG_CHECK, \"could not find %r in %r\", tail, head)\n    return path",
    "docstring": "Return case sensitive filename for NT path."
  },
  {
    "code": "def concat(self, axis, other, **kwargs):\n        return self._append_list_of_managers(other, axis, **kwargs)",
    "docstring": "Concatenates two objects together.\n\n        Args:\n            axis: The axis index object to join (0 for columns, 1 for index).\n            other: The other_index to concat with.\n\n        Returns:\n            Concatenated objects."
  },
  {
    "code": "def get_request(self):\n        request, client_addr = super(BoundedThreadingMixIn, self).get_request()\n        overload = False\n        with self._thread_guard:\n            if self._threads is not None and len(self._threads) + 1 > MAX_RPC_THREADS:\n                overload = True\n        if overload:\n            res = self.overloaded(client_addr)\n            request.sendall(res)\n            sys.stderr.write('{} - - [{}] \"Overloaded\"\\n'.format(client_addr[0], time_str(time.time())))\n            self.shutdown_request(request)\n            return None, None\n        return request, client_addr",
    "docstring": "Accept a request, up to the given number of allowed threads.\n        Defer to self.overloaded if there are already too many pending requests."
  },
  {
    "code": "def new_media_status(self, media_status):\n        casts = self._casts\n        group_members = self._mz.members\n        for member_uuid in group_members:\n            if member_uuid not in casts:\n                continue\n            for listener in list(casts[member_uuid]['listeners']):\n                listener.multizone_new_media_status(\n                    self._group_uuid, media_status)",
    "docstring": "Handle reception of a new MediaStatus."
  },
  {
    "code": "def _generate_energy_edges_single(ene):\n    midene = np.sqrt((ene[1:] * ene[:-1]))\n    elo, ehi = np.zeros(len(ene)) * ene.unit, np.zeros(len(ene)) * ene.unit\n    elo[1:] = ene[1:] - midene\n    ehi[:-1] = midene - ene[:-1]\n    elo[0] = ene[0] * (1 - ene[0] / (ene[0] + ehi[0]))\n    ehi[-1] = elo[-1]\n    return u.Quantity([elo, ehi])",
    "docstring": "Generate energy edges for single group"
  },
  {
    "code": "def on_close(self):\n        if self.id in self.funcserver.websocks:\n            self.funcserver.websocks[self.id] = None\n            ioloop = tornado.ioloop.IOLoop.instance()\n            ioloop.add_callback(lambda: self.funcserver.websocks.pop(self.id, None))\n        psession = self.funcserver.pysessions.get(self.pysession_id, None)\n        if psession:\n            psession['socks'].remove(self.id)\n            if not psession['socks']:\n                del self.funcserver.pysessions[self.pysession_id]",
    "docstring": "Called when client closes this connection. Cleanup\n        is done here."
  },
  {
    "code": "def _clone(self, *args, **kwargs):\n        clone = super(VersionedQuerySet, self)._clone(**kwargs)\n        clone.querytime = self.querytime\n        return clone",
    "docstring": "Overrides the QuerySet._clone method by adding the cloning of the\n        VersionedQuerySet's query_time parameter\n\n        :param kwargs: Same as the original QuerySet._clone params\n        :return: Just as QuerySet._clone, this method returns a clone of the\n            original object"
  },
  {
    "code": "def _init_structures(self, data, subjects):\n        x = []\n        mu = []\n        rho2 = np.zeros(subjects)\n        trace_xtx = np.zeros(subjects)\n        for subject in range(subjects):\n            mu.append(np.mean(data[subject], 1))\n            rho2[subject] = 1\n            trace_xtx[subject] = np.sum(data[subject] ** 2)\n            x.append(data[subject] - mu[subject][:, np.newaxis])\n        return x, mu, rho2, trace_xtx",
    "docstring": "Initializes data structures for SRM and preprocess the data.\n\n\n        Parameters\n        ----------\n        data : list of 2D arrays, element i has shape=[voxels_i, samples]\n            Each element in the list contains the fMRI data of one subject.\n\n        subjects : int\n            The total number of subjects in `data`.\n\n\n        Returns\n        -------\n        x : list of array, element i has shape=[voxels_i, samples]\n            Demeaned data for each subject.\n\n        mu : list of array, element i has shape=[voxels_i]\n            Voxel means over samples, per subject.\n\n        rho2 : array, shape=[subjects]\n            Noise variance :math:`\\\\rho^2` per subject.\n\n        trace_xtx : array, shape=[subjects]\n            The squared Frobenius norm of the demeaned data in `x`."
  },
  {
    "code": "def crossvalidate_model(cls, clusterer, data, num_folds, rnd):\n        return javabridge.static_call(\n            \"Lweka/clusterers/ClusterEvaluation;\", \"crossValidateModel\",\n            \"(Lweka/clusterers/DensityBasedClusterer;Lweka/core/Instances;ILjava/util/Random;)D\",\n            clusterer.jobject, data.jobject, num_folds, rnd.jobject)",
    "docstring": "Cross-validates the clusterer and returns the loglikelihood.\n\n        :param clusterer: the clusterer instance to evaluate\n        :type clusterer: Clusterer\n        :param data: the data to evaluate on\n        :type data: Instances\n        :param num_folds: the number of folds\n        :type num_folds: int\n        :param rnd: the random number generator to use\n        :type rnd: Random\n        :return: the cross-validated loglikelihood\n        :rtype: float"
  },
  {
    "code": "def _clone_block_and_wires(block_in):\n    block_in.sanity_check()\n    block_out = block_in.__class__()\n    temp_wv_map = {}\n    with set_working_block(block_out, no_sanity_check=True):\n        for wirevector in block_in.wirevector_subset():\n            new_wv = clone_wire(wirevector)\n            temp_wv_map[wirevector] = new_wv\n    return block_out, temp_wv_map",
    "docstring": "This is a generic function to copy the WireVectors for another round of\n    synthesis This does not split a WireVector with multiple wires.\n\n    :param block_in: The block to change\n    :param synth_name: a name to prepend to all new copies of a wire\n    :return: the resulting block and a WireVector map"
  },
  {
    "code": "def route(\n        self,\n        uri,\n        methods=frozenset({\"GET\"}),\n        host=None,\n        strict_slashes=None,\n        stream=False,\n        version=None,\n        name=None,\n    ):\n        if strict_slashes is None:\n            strict_slashes = self.strict_slashes\n        def decorator(handler):\n            route = FutureRoute(\n                handler,\n                uri,\n                methods,\n                host,\n                strict_slashes,\n                stream,\n                version,\n                name,\n            )\n            self.routes.append(route)\n            return handler\n        return decorator",
    "docstring": "Create a blueprint route from a decorated function.\n\n        :param uri: endpoint at which the route will be accessible.\n        :param methods: list of acceptable HTTP methods.\n        :param host: IP Address of FQDN for the sanic server to use.\n        :param strict_slashes: Enforce the API urls are requested with a\n            training */*\n        :param stream: If the route should provide a streaming support\n        :param version: Blueprint Version\n        :param name: Unique name to identify the Route\n\n        :return a decorated method that when invoked will return an object\n            of type :class:`FutureRoute`"
  },
  {
    "code": "def parallel_scan(self, scan_id, target):\n        try:\n            ret = self.exec_scan(scan_id, target)\n            if ret == 0:\n                self.add_scan_host_detail(scan_id, name='host_status',\n                                          host=target, value='0')\n            elif ret == 1:\n                self.add_scan_host_detail(scan_id, name='host_status',\n                                          host=target, value='1')\n            elif ret == 2:\n                self.add_scan_host_detail(scan_id, name='host_status',\n                                          host=target, value='2')\n            else:\n                logger.debug('%s: No host status returned', target)\n        except Exception as e:\n            self.add_scan_error(scan_id, name='', host=target,\n                                value='Host process failure (%s).' % e)\n            logger.exception('While scanning %s:', target)\n        else:\n            logger.info(\"%s: Host scan finished.\", target)",
    "docstring": "Starts the scan with scan_id."
  },
  {
    "code": "def _get_access_type(self, mode):\n        access_type = None\n        for char in mode:\n            if char in 'bt':\n                if access_type is not None:\n                    raise IOError('File mode \"%s\" contains contradictory flags' % mode)\n                access_type = char\n            elif char not in 'rbt':\n                raise NotImplementedError(\n                        '%s objects are read-only; unsupported mode \"%s\"'%\n                        (type(self), mode))\n        if access_type is None: access_type = 't'\n        return access_type",
    "docstring": "Make sure mode is appropriate; return 'b' for binary access and 't' for text"
  },
  {
    "code": "def merge(filehandle_1, filehandle_2, output_filehandle):\n    line2 = filehandle_2.readline()\n    for line1 in filehandle_1.readlines():\n        while line2 != '' and line2 <= line1:\n            output_filehandle.write(line2)\n            line2 = filehandle_2.readline()\n        output_filehandle.write(line1)\n    while line2 != '':\n        output_filehandle.write(line2)\n        line2 = filehandle_2.readline()",
    "docstring": "Merges together two files maintaining sorted order."
  },
  {
    "code": "def network(n):\n    tpm(n.tpm)\n    connectivity_matrix(n.cm)\n    if n.cm.shape[0] != n.size:\n        raise ValueError(\"Connectivity matrix must be NxN, where N is the \"\n                         \"number of nodes in the network.\")\n    return True",
    "docstring": "Validate a |Network|.\n\n    Checks the TPM and connectivity matrix."
  },
  {
    "code": "def _connect_hive(self, hive):\n        try:\n            handle = self._remote_hives[hive]\n        except KeyError:\n            handle = win32.RegConnectRegistry(self._machine, hive)\n            self._remote_hives[hive] = handle\n        return handle",
    "docstring": "Connect to the specified hive of a remote Registry.\n\n        @note: The connection will be cached, to close all connections and\n            erase this cache call the L{close} method.\n\n        @type  hive: int\n        @param hive: Hive to connect to.\n\n        @rtype:  L{win32.RegistryKeyHandle}\n        @return: Open handle to the remote Registry hive."
  },
  {
    "code": "def reference(self, tkn: str):\n        return self.grammarelts[tkn] if tkn in self.grammarelts else UndefinedElement(tkn)",
    "docstring": "Return the element that tkn represents"
  },
  {
    "code": "def _create_connection(self):\n        transport = SSL if self.ssl else TCP\n        return transport(self.server, self.port)",
    "docstring": "Creates a transport channel.\n\n        :return: transport channel instance\n        :rtype: :class:`fatbotslim.irc.tcp.TCP` or :class:`fatbotslim.irc.tcp.SSL`"
  },
  {
    "code": "def complete_pool_name(arg):\n    search_string = '^'\n    if arg is not None:\n        search_string += arg\n    res = Pool.search({\n        'operator': 'regex_match',\n        'val1': 'name',\n        'val2': search_string\n    })\n    ret = []\n    for p in res['result']:\n        ret.append(p.name)\n    return ret",
    "docstring": "Returns list of matching pool names"
  },
  {
    "code": "def validate(mcs, bases, attributes):\n        if bases[0] is object:\n            return None\n        mcs.check_model_cls(attributes)\n        mcs.check_include_exclude(attributes)\n        mcs.check_properties(attributes)",
    "docstring": "Check attributes."
  },
  {
    "code": "def array_bytes(array):\n    return np.product(array.shape)*np.dtype(array.dtype).itemsize",
    "docstring": "Estimates the memory of the supplied array in bytes"
  },
  {
    "code": "def search(self, term):\n        r = requests.get(self.apiurl + \"/users\", params={\"filter[name]\": term}, headers=self.header)\n        if r.status_code != 200:\n            raise ServerError\n        jsd = r.json()\n        if jsd['meta']['count']:\n            return SearchWrapper(jsd['data'], jsd['links']['next'] if 'next' in jsd['links'] else None, self.header)\n        else:\n            return None",
    "docstring": "Search for a user by name.\n\n        :param str term: What to search for.\n        :return: The results as a SearchWrapper iterator or None if no results.\n        :rtype: SearchWrapper or None"
  },
  {
    "code": "def _save_json(self, filename):\n        with open(filename, 'w') as file_handle:\n            json.dump(self._sensors, file_handle, cls=MySensorsJSONEncoder,\n                      indent=4)\n            file_handle.flush()\n            os.fsync(file_handle.fileno())",
    "docstring": "Save sensors to json file."
  },
  {
    "code": "def _link(self, base_dir: str, artifact_map: dict, conf: Config):\n        num_linked = 0\n        for dst, src in artifact_map.items():\n            abs_src = join(conf.project_root, src)\n            abs_dest = join(conf.project_root, base_dir, dst)\n            link_node(abs_src, abs_dest)\n            num_linked += 1\n        return num_linked",
    "docstring": "Link all artifacts in `artifact_map` under `base_dir` and return\n           the number of artifacts linked."
  },
  {
    "code": "def get_delimited_message_bytes(byte_stream, nr=4):\n    (length, pos) = decoder._DecodeVarint32(byte_stream.read(nr), 0)\n    if log.getEffectiveLevel() == logging.DEBUG:\n        log.debug(\"Delimited message length (pos %d): %d\" % (pos, length))\n    delimiter_bytes = nr - pos\n    byte_stream.rewind(delimiter_bytes)\n    message_bytes = byte_stream.read(length)\n    if log.getEffectiveLevel() == logging.DEBUG:\n        log.debug(\"Delimited message bytes (%d): %s\" % (len(message_bytes), format_bytes(message_bytes)))\n    total_len = length + pos\n    return (total_len, message_bytes)",
    "docstring": "Parse a delimited protobuf message. This is done by first getting a protobuf varint from\n    the stream that represents the length of the message, then reading that amount of\n    from the message and then parse it.\n    Since the int can be represented as max 4 bytes, first get 4 bytes and try to decode.\n    The decoder returns the value and the position where the value was found, so we need\n    to rewind the buffer to the position, because the remaining bytes belong to the message\n    after."
  },
  {
    "code": "def to_dict(self):\n        as_dict = dict(self.payload or ())\n        as_dict['message'] = self.message\n        return as_dict",
    "docstring": "Return a dictionary representation of the exception."
  },
  {
    "code": "def EmitProto(cls):\n    result = \"message %s {\\n\" % cls.__name__\n    for _, desc in sorted(iteritems(cls.type_infos_by_field_number)):\n      result += desc.Definition()\n    result += \"}\\n\"\n    return result",
    "docstring": "Emits .proto file definitions."
  },
  {
    "code": "def tofile(self, f):\n        f.write(pack(self.FILE_FMT, self.scale, self.ratio,\n                     self.initial_capacity, self.error_rate))\n        f.write(pack(b'<l', len(self.filters)))\n        if len(self.filters) > 0:\n            headerpos = f.tell()\n            headerfmt = b'<' + b'Q'*(len(self.filters))\n            f.write(b'.' * calcsize(headerfmt))\n            filter_sizes = []\n            for filter in self.filters:\n                begin = f.tell()\n                filter.tofile(f)\n                filter_sizes.append(f.tell() - begin)\n            f.seek(headerpos)\n            f.write(pack(headerfmt, *filter_sizes))",
    "docstring": "Serialize this ScalableBloomFilter into the file-object\n        `f'."
  },
  {
    "code": "def mb_filter(fastq, cores):\n    filter_mb = partial(umi_filter)\n    p = multiprocessing.Pool(cores)\n    chunks = tz.partition_all(10000, read_fastq(fastq))\n    bigchunks = tz.partition_all(cores, chunks)\n    for bigchunk in bigchunks:\n        for chunk in p.map(filter_mb, list(bigchunk)):\n            for read in chunk:\n                sys.stdout.write(read)",
    "docstring": "Filters umis with non-ACGT bases\n    Expects formatted fastq files."
  },
  {
    "code": "def ID_colored_tube(color):\n    tubing_data_path = os.path.join(os.path.dirname(__file__), \"data\",\n        \"3_stop_tubing.txt\")\n    df = pd.read_csv(tubing_data_path, delimiter='\\t')\n    idx = df[\"Color\"] == color\n    return df[idx]['Diameter (mm)'].values[0] * u.mm",
    "docstring": "Look up the inner diameter of Ismatec 3-stop tubing given its color code.\n\n    :param color: Color of the 3-stop tubing\n    :type color: string\n\n    :returns: Inner diameter of the 3-stop tubing (mm)\n    :rtype: float\n\n    :Examples:\n\n    >>> from aguaclara.research.peristaltic_pump import ID_colored_tube\n    >>> from aguaclara.core.units import unit_registry as u\n    >>> ID_colored_tube(\"yellow-blue\")\n    <Quantity(1.52, 'millimeter')>\n    >>> ID_colored_tube(\"orange-yellow\")\n    <Quantity(0.51, 'millimeter')>\n    >>> ID_colored_tube(\"purple-white\")\n    <Quantity(2.79, 'millimeter')>"
  },
  {
    "code": "def get_tools(self) -> list:\n        tools = \"flake8,pylint,vulture,pyroma,isort,yapf,safety,dodgy,pytest,pypi\".split(\n            \",\")\n        print(\"Available tools: {0}\".format(\",\".join(tools)))\n        answer = ask_list(\"What tools would you like to use?\",\n                          [\"flake8\", \"pytest\"])\n        if any(tool not in tools for tool in answer):\n            print(\"Invalid answer, retry.\")\n            self.get_tools()\n        return answer",
    "docstring": "Lets the user enter the tools he want to use"
  },
  {
    "code": "def createfork(self, project_id):\n        request = requests.post(\n            '{0}/fork/{1}'.format(self.projects_url, project_id),\n            timeout=self.timeout, verify=self.verify_ssl)\n        if request.status_code == 200:\n            return True\n        else:\n            return False",
    "docstring": "Forks a project into the user namespace of the authenticated user.\n\n        :param project_id: Project ID to fork\n        :return: True if succeed"
  },
  {
    "code": "def notification_factory(code, subcode):\n    notification = BGPNotification(code, subcode)\n    if not notification.reason:\n        raise ValueError('Invalid code/sub-code.')\n    return notification",
    "docstring": "Returns a `Notification` message corresponding to given codes.\n\n    Parameters:\n    - `code`: (int) BGP error code\n    - `subcode`: (int) BGP error sub-code"
  },
  {
    "code": "def ping_connection(dbapi_connection, connection_record, connection_proxy):\n    cursor = dbapi_connection.cursor()\n    try:\n        cursor.execute(\"SELECT 1\")\n    except Exception:\n        raise sa.exc.DisconnectionError()\n    cursor.close()",
    "docstring": "Ensure connections are valid.\n\n    From: `http://docs.sqlalchemy.org/en/rel_0_8/core/pooling.html`\n\n    In case db has been restarted pool may return invalid connections."
  },
  {
    "code": "def observe(self, path, callback, timeout=None, **kwargs):\n        request = self.mk_request(defines.Codes.GET, path)\n        request.observe = 0\n        for k, v in kwargs.items():\n            if hasattr(request, k):\n                setattr(request, k, v)\n        return self.send_request(request, callback, timeout)",
    "docstring": "Perform a GET with observe on a certain path.\n\n        :param path: the path\n        :param callback: the callback function to invoke upon notifications\n        :param timeout: the timeout of the request\n        :return: the response to the observe request"
  },
  {
    "code": "def close_database_session(session):\n    try:\n        session.close()\n    except OperationalError as e:\n        raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])",
    "docstring": "Close connection with the database"
  },
  {
    "code": "def parse_style_decl(style: str, owner: AbstractNode = None\n                     ) -> CSSStyleDeclaration:\n    _style = CSSStyleDeclaration(style, owner=owner)\n    return _style",
    "docstring": "Make CSSStyleDeclaration from style string.\n\n    :arg AbstractNode owner: Owner of the style."
  },
  {
    "code": "def writeFile(filename, data):\n\t\twith open(filename, 'wb') as f:\n\t\t\tf.write(data.encode('utf-8'))",
    "docstring": "Writes data to a file"
  },
  {
    "code": "def pipfaster_download_cacher(index_urls):\n    from pip._internal import download\n    orig = download._download_http_url\n    patched_fn = get_patched_download_http_url(orig, index_urls)\n    return patched(vars(download), {'_download_http_url': patched_fn})",
    "docstring": "vanilla pip stores a cache of the http session in its cache and not the\n    wheel files.  We intercept the download and save those files into our\n    cache"
  },
  {
    "code": "def send_stats(self, start, environ, response_interception, exception=None):\n        if response_interception:\n            key_name = self.get_key_name(environ, response_interception, exception=exception)\n            timer = self.statsd_client.timer(key_name)\n            timer._start_time = start\n            timer.stop()",
    "docstring": "Send the actual timing stats.\n\n        :param start: start time in seconds since the epoch as a floating point number\n        :type start: float\n        :param environ: wsgi environment\n        :type environ: dict\n        :param response_interception: dictionary in form\n            {'status': '<response status>', 'response_headers': [<response headers], 'exc_info': <exc_info>}\n            This is the interception of what was passed to start_response handler.\n        :type response_interception: dict\n        :param exception: optional exception happened during the iteration of the response\n        :type exception: Exception"
  },
  {
    "code": "def status(name, runas=None):\n    return prlctl('status', salt.utils.data.decode(name), runas=runas)",
    "docstring": "Status of a VM\n\n    :param str name:\n        Name/ID of VM whose status will be returned\n\n    :param str runas:\n        The user that the prlctl command will be run as\n\n    Example:\n\n    .. code-block:: bash\n\n        salt '*' parallels.status macvm runas=macdev"
  },
  {
    "code": "def inner(self, isolated=False):\n        if isolated:\n            return Frame(self.eval_ctx, level=self.symbols.level + 1)\n        return Frame(self.eval_ctx, self)",
    "docstring": "Return an inner frame."
  },
  {
    "code": "def put(self, event):\n        self.log(\"Configuration put request \",\n                 event.user)\n        try:\n            component = model_factory(Schema).find_one({\n                'uuid': event.data['uuid']\n            })\n            component.update(event.data)\n            component.save()\n            response = {\n                'component': 'hfos.ui.configurator',\n                'action': 'put',\n                'data': True\n            }\n            self.log('Updated component configuration:',\n                     component.name)\n            self.fireEvent(reload_configuration(component.name))\n        except (KeyError, ValueError, ValidationError, PermissionError) as e:\n            response = {\n                'component': 'hfos.ui.configurator',\n                'action': 'put',\n                'data': False\n            }\n            self.log('Storing component configuration failed: ',\n                     type(e), e, exc=True, lvl=error)\n        self.fireEvent(send(event.client.uuid, response))\n        return",
    "docstring": "Store a given configuration"
  },
  {
    "code": "def update_insight(self, project_key, insight_id, **kwargs):\n        request = self.__build_insight_obj(\n            lambda: _swagger.InsightPatchRequest(), kwargs)\n        project_owner, project_id = parse_dataset_key(project_key)\n        try:\n            self._insights_api.update_insight(project_owner,\n                                              project_id,\n                                              insight_id, body=request)\n        except _swagger.rest.ApiException as e:\n            raise RestApiError(cause=e)",
    "docstring": "Update an insight.\n\n        **Note that only elements included in the request will be updated. All\n        omitted elements will remain untouched.\n        :param project_key: Projrct identifier, in the form of\n        projectOwner/projectid\n        :type project_key: str\n        :param insight_id: Insight unique identifier.\n        :type insight_id: str\n        :param title: Insight title\n        :type title: str\n        :param description: Insight description.\n        :type description: str, optional\n        :param image_url: If image-based, the URL of the image\n        :type image_url: str\n        :param embed_url: If embed-based, the embeddable URL\n        :type embed_url: str\n        :param source_link: Permalink to source code or platform this insight\n        was generated with. Allows others to replicate the steps originally\n        used to produce the insight.\n        :type source_link: str, optional\n        :param data_source_links: One or more permalinks to the data sources\n        used to generate this insight. Allows others to access the data\n        originally used to produce the insight.\n        :type data_source_links: array\n        :returns: message object\n        :rtype: object\n        :raises RestApiException: If a server error occurs\n\n        Examples\n        --------\n        >>> import datadotworld as dw\n        >>> api_client = dw.api_client()\n        >>> api_client.update_insight(\n        ...    'username/test-project', 'insightid'\n        ...    title='demo atadotworld'})  # doctest: +SKIP"
  },
  {
    "code": "def _radix_int_handler_factory(radix_indicators, charset, parse_func):\n    def assertion(c, ctx):\n        return c in radix_indicators and \\\n               ((len(ctx.value) == 1 and ctx.value[0] == _ZERO) or\n                (len(ctx.value) == 2 and ctx.value[0] == _MINUS and ctx.value[1] == _ZERO)) and \\\n               ctx.ion_type == IonType.INT\n    return _numeric_handler_factory(charset, lambda prev, c, ctx, trans: _illegal_character(c, ctx),\n                                    assertion, radix_indicators, parse_func, illegal_at_end=radix_indicators)",
    "docstring": "Generates a handler co-routine which tokenizes a integer of a particular radix.\n\n    Args:\n        radix_indicators (sequence): The set of ordinals of characters that indicate the radix of this int.\n        charset (sequence): Set of ordinals of legal characters for this radix.\n        parse_func (callable): Called upon ending the numeric value. Accepts the current token value and returns a\n            thunk that lazily parses the token."
  },
  {
    "code": "async def log_transaction(self, **params):\n\t\tif params.get(\"message\"):\n\t\t\tparams = json.loads(params.get(\"message\", \"{}\"))\n\t\tif not params:\n\t\t\treturn {\"error\":400, \"reason\":\"Missed required fields\"}\n\t\tcoinid = params.get(\"coinid\")\n\t\tif not coinid in [\"QTUM\", \"PUT\"]:\n\t\t\treturn {\"error\":400, \"reason\": \"Missed or invalid coinid\"}\n\t\tdatabase = client[settings.TXS]\n\t\tsource_collection = database[coinid]\n\t\tawait source_collection.find_one_and_update({\"txid\":params.get(\"txid\")},{\"$set\":{\n\t\t\t\t\"blocknumber\":params.get(\"blocknumber\"),\n\t\t\t\t\"blockhash\":params.get(\"blockhash\"),\n\t\t\t\t\"gasLimit\":params.get(\"gasLimit\"),\n\t\t\t\t\"gasPrice\":params.get(\"gasPrice\"),\n\t\t\t}})\n\t\treturn {\"success\":True}",
    "docstring": "Writing transaction to database"
  },
  {
    "code": "def delete(node_name):\n    result = {}\n    node = nago.core.get_node(node_name)\n    if not node:\n        result['status'] = 'error'\n        result['message'] = \"node not found.\"\n    else:\n        node.delete()\n        result['status'] = 'success'\n        result['message'] = 'node deleted.'\n    return result",
    "docstring": "Delete a specific node"
  },
  {
    "code": "def search_texts(args, parser):\n    store = utils.get_data_store(args)\n    corpus = utils.get_corpus(args)\n    catalogue = utils.get_catalogue(args)\n    store.validate(corpus, catalogue)\n    ngrams = []\n    for ngram_file in args.ngrams:\n        ngrams.extend(utils.get_ngrams(ngram_file))\n    store.search(catalogue, ngrams, sys.stdout)",
    "docstring": "Searches texts for presence of n-grams."
  },
  {
    "code": "def alias_proficiency(self, proficiency_id, alias_id):\n        self._alias_id(primary_id=proficiency_id, equivalent_id=alias_id)",
    "docstring": "Adds an ``Id`` to a ``Proficiency`` for the purpose of creating compatibility.\n\n        The primary ``Id`` of the ``Proficiency`` is determined by the\n        provider. The new ``Id`` performs as an alias to the primary\n        ``Id``. If the alias is a pointer to another proficiency, it is\n        reassigned to the given proficiency ``Id``.\n\n        arg:    proficiency_id (osid.id.Id): the ``Id`` of a\n                ``Proficiency``\n        arg:    alias_id (osid.id.Id): the alias ``Id``\n        raise:  AlreadyExists - ``alias_id`` is already assigned\n        raise:  NotFound - ``proficiency_id`` not found\n        raise:  NullArgument - ``proficiency_id`` or ``alias_id`` is\n                ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def ends(self, layer):\n        ends = []\n        for data in self[layer]:\n            ends.append(data[END])\n        return ends",
    "docstring": "Retrieve end positions of elements if given layer."
  },
  {
    "code": "def apply_defaults(self):\n        self.emit('will_apply_defaults')\n        self.schema.apply_defaults(self)\n        self.emit('did_apply_defaults')",
    "docstring": "Apply schema defaults to this document."
  },
  {
    "code": "def remove(self, field: Field):\n        self._table = [fld for fld in self._table if fld is not field]",
    "docstring": "Removes a `Field` from the table by identity."
  },
  {
    "code": "def networkproperties(self):\n        print('Number of nodes: %d' % len(self.nodes))\n        print('Number of elements: %d' % len(self.elements))\n        print('Number of end nodes: %d' % len(self.endnodes))\n        print('Number of distinct networks: %d' % len(self.numberofnetworks))\n        print('Applied node variables: %s' % ', '.join(self.variables))",
    "docstring": "Print out some properties of the network defined by the |Node| and\n        |Element| objects currently handled by the |HydPy| object."
  },
  {
    "code": "def on_unicode_checkbox(self, w=None, state=False):\n        logging.debug(\"unicode State is %s\", state)\n        self.controller.smooth_graph_mode = state\n        if state:\n            self.hline = urwid.AttrWrap(\n                urwid.SolidFill(u'\\N{LOWER ONE QUARTER BLOCK}'), 'line')\n        else:\n            self.hline = urwid.AttrWrap(urwid.SolidFill(u' '), 'line')\n        for graph in self.graphs.values():\n            graph.set_smooth_colors(state)\n        self.show_graphs()",
    "docstring": "Enable smooth edges if utf-8 is supported"
  },
  {
    "code": "def AddMethod(self, function, name=None):\n        method = MethodWrapper(self, function, name)\n        self.added_methods.append(method)",
    "docstring": "Adds the specified function as a method of this construction\n        environment with the specified name.  If the name is omitted,\n        the default name is the name of the function itself."
  },
  {
    "code": "def _cmp_by_local_pref(path1, path2):\n    lp1 = path1.get_pattr(BGP_ATTR_TYPE_LOCAL_PREF)\n    lp2 = path2.get_pattr(BGP_ATTR_TYPE_LOCAL_PREF)\n    if not (lp1 and lp2):\n        return None\n    lp1 = lp1.value\n    lp2 = lp2.value\n    if lp1 > lp2:\n        return path1\n    elif lp2 > lp1:\n        return path2\n    else:\n        return None",
    "docstring": "Selects a path with highest local-preference.\n\n    Unlike the weight attribute, which is only relevant to the local\n    router, local preference is an attribute that routers exchange in the\n    same AS. Highest local-pref is preferred. If we cannot decide,\n    we return None."
  },
  {
    "code": "def spin_in_system(incl, long_an):\n    return np.dot(Rz(long_an), np.dot(Rx(-incl), np.array([0.,0.,1.])))",
    "docstring": "Spin in the plane of sky of a star given its inclination and \"long_an\"\n\n       incl - inclination of the star in the plane of sky\n       long_an - longitude of ascending node (equator) of the star in the plane of sky\n\n    Return:\n        spin - in plane of sky"
  },
  {
    "code": "def next_moments_operating_on(self,\n                                  qubits: Iterable[ops.Qid],\n                                  start_moment_index: int = 0\n                                  ) -> Dict[ops.Qid, int]:\n        next_moments = {}\n        for q in qubits:\n            next_moment = self.next_moment_operating_on(\n                [q], start_moment_index)\n            next_moments[q] = (len(self._moments) if next_moment is None else\n                               next_moment)\n        return next_moments",
    "docstring": "Finds the index of the next moment that touches each qubit.\n\n        Args:\n            qubits: The qubits to find the next moments acting on.\n            start_moment_index: The starting point of the search.\n\n        Returns:\n            The index of the next moment that touches each qubit. If there\n            is no such moment, the next moment is specified as the number of\n            moments in the circuit. Equivalently, can be characterized as one\n            plus the index of the last moment after start_moment_index\n            (inclusive) that does *not* act on a given qubit."
  },
  {
    "code": "def start_basic_span(self, request):\n        try:\n            if request.tracing.trace_id:\n                context = self.tracer.extract(\n                    format=ZIPKIN_SPAN_FORMAT,\n                    carrier=request.tracing)\n                self.span = self.tracer.start_span(\n                    operation_name=request.endpoint,\n                    child_of=context,\n                    tags={tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER},\n                )\n        except opentracing.UnsupportedFormatException:\n            pass\n        except:\n            log.exception('Cannot extract tracing span from Trace field')",
    "docstring": "Start tracing span from the protocol's `tracing` fields.\n        This will only work if the `tracer` supports Zipkin-style span context.\n\n        :param request: inbound request\n        :type request: tchannel.tornado.request.Request"
  },
  {
    "code": "def _set_cache_(self, attr):\n        if attr in TagObject.__slots__:\n            ostream = self.repo.odb.stream(self.binsha)\n            lines = ostream.read().decode(defenc).splitlines()\n            obj, hexsha = lines[0].split(\" \")\n            type_token, type_name = lines[1].split(\" \")\n            self.object = \\\n                get_object_type_by_name(type_name.encode('ascii'))(self.repo, hex_to_bin(hexsha))\n            self.tag = lines[2][4:]\n            tagger_info = lines[3]\n            self.tagger, self.tagged_date, self.tagger_tz_offset = parse_actor_and_date(tagger_info)\n            if len(lines) > 5:\n                self.message = \"\\n\".join(lines[5:])\n            else:\n                self.message = ''\n        else:\n            super(TagObject, self)._set_cache_(attr)",
    "docstring": "Cache all our attributes at once"
  },
  {
    "code": "def before_insert(mapper, conn, target):\n        if target.sequence_id is None:\n            from ambry.orm.exc import DatabaseError\n            raise DatabaseError('Must have sequence id before insertion')\n        Table.before_update(mapper, conn, target)",
    "docstring": "event.listen method for Sqlalchemy to set the seqience_id for this\n        object and create an ObjectNumber value for the id"
  },
  {
    "code": "def extract_traits(self, entity):\n        traits = getattr(entity, self._characteristic)\n        if traits is not None and isinstance(traits, Hashable):\n            traits = [traits]\n        return Trait(\n            traits,\n            getattr(entity, self._characteristic + '_match', True)\n        )",
    "docstring": "Extract data required to classify entity.\n\n        :param object entity:\n        :return: namedtuple consisting of characteristic traits and match flag\n        :rtype: matchbox.box.Trait"
  },
  {
    "code": "def _learnOnNewSegments(connections, rng, newSegmentCells, growthCandidates,\n                          initialPermanence, sampleSize, maxSynapsesPerSegment):\n    numNewSynapses = len(growthCandidates)\n    if sampleSize != -1:\n      numNewSynapses = min(numNewSynapses, sampleSize)\n    if maxSynapsesPerSegment != -1:\n      numNewSynapses = min(numNewSynapses, maxSynapsesPerSegment)\n    newSegments = connections.createSegments(newSegmentCells)\n    connections.growSynapsesToSample(newSegments, growthCandidates,\n                                     numNewSynapses, initialPermanence,\n                                     rng)",
    "docstring": "Create new segments, and grow synapses on them.\n\n    @param connections (SparseMatrixConnections)\n    @param rng (Random)\n    @param newSegmentCells (numpy array)\n    @param growthCandidates (numpy array)"
  },
  {
    "code": "def pst(self):\n        if self.__pst is None and self.pst_arg is None:\n            raise Exception(\"linear_analysis.pst: can't access self.pst:\" +\n                            \"no pest control argument passed\")\n        elif self.__pst:\n            return self.__pst\n        else:\n            self.__load_pst()\n            return self.__pst",
    "docstring": "get the pyemu.Pst attribute\n\n        Returns\n        -------\n        pst : pyemu.Pst\n\n        Note\n        ----\n        returns a references\n        \n        If LinearAnalysis.__pst is None, then the pst attribute is\n        dynamically loaded before returning"
  },
  {
    "code": "def activate_firmware_and_wait(self, rollback_override=None,\n                                   timeout=2, interval=1):\n        try:\n            self.activate_firmware(rollback_override)\n        except CompletionCodeError as e:\n            if e.cc == CC_LONG_DURATION_CMD_IN_PROGRESS:\n                self.wait_for_long_duration_command(\n                            constants.CMDID_HPM_ACTIVATE_FIRMWARE,\n                            timeout, interval)\n            else:\n                raise HpmError('activate_firmware CC=0x%02x' % e.cc)\n        except IpmiTimeoutError:\n            pass",
    "docstring": "Activate the new uploaded firmware and wait for\n            long running command."
  },
  {
    "code": "def get_declared_enums(metadata, schema, default):\n    types = set(column.type\n                for table in metadata.tables.values()\n                for column in table.columns\n                if (isinstance(column.type, sqlalchemy.Enum) and\n                    schema == (column.type.schema or default)))\n    return {t.name: frozenset(t.enums) for t in types}",
    "docstring": "Return a dict mapping SQLAlchemy enumeration types to the set of their\n    declared values.\n\n    :param metadata:\n        ...\n\n    :param str schema:\n        Schema name (e.g. \"public\").\n\n    :returns dict:\n        {\n            \"my_enum\": frozenset([\"a\", \"b\", \"c\"]),\n        }"
  },
  {
    "code": "def write_line(self, message):\n        self.out.write(message + \"\\n\")\n        self.out.flush()",
    "docstring": "Unbuffered printing to stdout."
  },
  {
    "code": "def get_default_project_id():\n  try:\n    proc = subprocess.Popen(['gcloud', 'config', 'list', '--format', 'value(core.project)'],\n                            stdout=subprocess.PIPE)\n    stdout, _ = proc.communicate()\n    value = stdout.strip()\n    if proc.poll() == 0 and value:\n      if isinstance(value, six.string_types):\n        return value\n      else:\n        return value.decode()\n  except:\n    pass\n  config_file = os.path.join(get_config_dir(), 'config.json')\n  if os.path.exists(config_file):\n    with open(config_file) as f:\n      config = json.loads(f.read())\n      if 'project_id' in config and config['project_id']:\n        return str(config['project_id'])\n  if os.getenv('PROJECT_ID') is not None:\n    return os.getenv('PROJECT_ID')\n  return None",
    "docstring": "Get default project id from config or environment var.\n\n  Returns: the project id if available, or None."
  },
  {
    "code": "def get_node(self, node_id):\n        try:\n            return self._nodes[node_id]\n        except KeyError:\n            raise aiohttp.web.HTTPNotFound(text=\"Node ID {} doesn't exist\".format(node_id))",
    "docstring": "Return the node or raise a 404 if the node is unknown"
  },
  {
    "code": "def scan_and_reimport(mod_type: str) -> List[Tuple[str, str]]:\n    mod_enabled, mod_disabled = get_modules(mod_type)\n    errors = []\n    for mod in mod_enabled + mod_disabled:\n        if mod in sys.modules:\n            msg = safe_reload(sys.modules[mod])\n        else:\n            msg = safe_load(mod)\n        if msg is not None:\n            errors.append((mod, msg))\n    return errors",
    "docstring": "Scans folder for modules."
  },
  {
    "code": "def close(self, clear=False):\n        if clear and not self.leave:\n            self.clear()\n        else:\n            self.refresh()\n        self.manager.remove(self)",
    "docstring": "Do final refresh and remove from manager\n\n        If ``leave`` is True, the default, the effect is the same as :py:meth:`refresh`."
  },
  {
    "code": "def _render_dataframe(dataframe):\n  data = dataframe.to_dict(orient='records')\n  fields = dataframe.columns.tolist()\n  return IPython.core.display.HTML(\n      datalab.utils.commands.HtmlBuilder.render_table(data, fields))",
    "docstring": "Helper to render a dataframe as an HTML table."
  },
  {
    "code": "def _write_bin(self, stream, byte_order):\n        for rec in self.data:\n            for prop in self.properties:\n                prop._write_bin(rec[prop.name], stream, byte_order)",
    "docstring": "Save a PLY element to a binary PLY file.  The element may\n        contain list properties."
  },
  {
    "code": "def _needs_reindex_multi(self, axes, method, level):\n        return ((com.count_not_none(*axes.values()) == self._AXIS_LEN) and\n                method is None and level is None and not self._is_mixed_type)",
    "docstring": "Check if we do need a multi reindex."
  },
  {
    "code": "def list_request_settings(self, service_id, version_number):\n\t\tcontent = self._fetch(\"/service/%s/version/%d/request_settings\" % (service_id, version_number))\n\t\treturn map(lambda x: FastlyRequestSetting(self, x), content)",
    "docstring": "Returns a list of all Request Settings objects for the given service and version."
  },
  {
    "code": "def check_theme(theme):\n        terminal_colors = curses.COLORS if curses.has_colors() else 0\n        if theme.required_colors > terminal_colors:\n            return False\n        elif theme.required_color_pairs > curses.COLOR_PAIRS:\n            return False\n        else:\n            return True",
    "docstring": "Check if the given theme is compatible with the terminal"
  },
  {
    "code": "def is_primary(self):\n        return bool(next(iter(self.selfsig._signature.subpackets['h_PrimaryUserID']), False))",
    "docstring": "If the most recent, valid self-signature specifies this as being primary, this will be True. Otherwise, Faqlse."
  },
  {
    "code": "def is_website(url):\n    if re.match(r\"(http|ftp|https)://([\\w\\-\\.]+)/?\", url):\n        LOGGER.debug(\"> {0}' is matched as website.\".format(url))\n        return True\n    else:\n        LOGGER.debug(\"> {0}' is not matched as website.\".format(url))\n        return False",
    "docstring": "Check if given url string is a website.\n\n    Usage::\n\n        >>> is_website(\"http://www.domain.com\")\n        True\n        >>> is_website(\"domain.com\")\n        False\n\n    :param data: Data to check.\n    :type data: unicode\n    :return: Is website.\n    :rtype: bool"
  },
  {
    "code": "def get_amount_of_tweets(self):\n        if not self.__response:\n            raise TwitterSearchException(1013)\n        return (len(self.__response['content']['statuses'])\n                if self.__order_is_search\n                else len(self.__response['content']))",
    "docstring": "Returns current amount of tweets available within this instance\n\n        :returns: The amount of tweets currently available\n        :raises: TwitterSearchException"
  },
  {
    "code": "def _validate_calibration_params(strategy='accuracy', min_rate=None,\n                                   beta=1.):\n    if strategy not in ('accuracy', 'f_beta', 'max_tpr',\n                        'max_tnr'):\n      raise ValueError('Strategy can either be \"accuracy\", \"f_beta\" or '\n                       '\"max_tpr\" or \"max_tnr\". Got \"{}\" instead.'\n                       .format(strategy))\n    if strategy == 'max_tpr' or strategy == 'max_tnr':\n      if (min_rate is None or not isinstance(min_rate, (int, float)) or\n              not min_rate >= 0 or not min_rate <= 1):\n        raise ValueError('Parameter min_rate must be a number in'\n                         '[0, 1]. '\n                         'Got {} instead.'.format(min_rate))\n    if strategy == 'f_beta':\n      if beta is None or not isinstance(beta, (int, float)):\n        raise ValueError('Parameter beta must be a real number. '\n                         'Got {} instead.'.format(type(beta)))",
    "docstring": "Ensure that calibration parameters have allowed values"
  },
  {
    "code": "def heappush(heap, item):\n    heap.append(item)\n    _siftdown(heap, 0, len(heap)-1)",
    "docstring": "Push item onto heap, maintaining the heap invariant."
  },
  {
    "code": "def list_downloads():\n    outfiles = []\n    for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'):\n        for f in files:\n            outfiles.append(os.path.join(root, f))\n    dist_files = []\n    for f in outfiles:\n        if f.endswith('.dist'):\n            dist_files.append(f)\n    ret = []\n    for update in _get_available():\n        for f in dist_files:\n            with salt.utils.files.fopen(f) as fhr:\n                if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()):\n                    ret.append(update)\n    return ret",
    "docstring": "Return a list of all updates that have been downloaded locally.\n\n    :return: A list of updates that have been downloaded\n    :rtype: list\n\n    CLI Example:\n\n    .. code-block:: bash\n\n       salt '*' softwareupdate.list_downloads"
  },
  {
    "code": "def delete_view(self, request, object_id, extra_context=None):\n        if not extra_context:\n            extra_context = {}\n        extra_context['is_popup'] = request.REQUEST.get('_popup', 0)\n        return super(EnhancedAdminMixin, self).delete_view(request, object_id, extra_context)",
    "docstring": "Sets is_popup context variable to hide admin header."
  },
  {
    "code": "def command_builder(self, string, value=None, default=None, disable=None):\n        if default:\n            return 'default %s' % string\n        elif disable:\n            return 'no %s' % string\n        elif value is True:\n            return string\n        elif value:\n            return '%s %s' % (string, value)\n        else:\n            return 'no %s' % string",
    "docstring": "Builds a command with keywords\n\n        Notes:\n            Negating a command string by overriding 'value' with None or an\n                assigned value that evalutates to false has been deprecated.\n                Please use 'disable' to negate a command.\n\n            Parameters are evaluated in the order 'default', 'disable', 'value'\n\n        Args:\n            string (str): The command string\n            value (str): The configuration setting to subsititue into the\n                command string. If value is a boolean and True, just the\n                command string is used\n            default (bool): Specifies the command should use the default\n                keyword argument. Default preempts disable and value.\n            disable (bool): Specifies the command should use the no\n                keyword argument. Disable preempts value.\n\n        Returns:\n            A command string that can be used to configure the node"
  },
  {
    "code": "def data_to_dict(self, sysbase=False):\n        assert isinstance(sysbase, bool)\n        ret = {}\n        for key in self.data_keys:\n            if (not sysbase) and (key in self._store):\n                val = self._store[key]\n            else:\n                val = self.__dict__[key]\n            ret[key] = val\n        return ret",
    "docstring": "Return the loaded model parameters as one dictionary.\n\n        Each key of the dictionary is a parameter name, and the value is a\n        list of all the parameter values.\n\n        :param sysbase: use system base quantities\n        :type sysbase: bool"
  },
  {
    "code": "def cut_sequences_relative(records, slices, record_id):\n    with _record_buffer(records) as r:\n        try:\n            record = next(i for i in r() if i.id == record_id)\n        except StopIteration:\n            raise ValueError(\"Record with id {0} not found.\".format(record_id))\n        new_slices = _update_slices(record, slices)\n        for record in multi_cut_sequences(r(), new_slices):\n            yield record",
    "docstring": "Cuts records to slices, indexed by non-gap positions in record_id"
  },
  {
    "code": "def checkIPFromAlias(alias=None):\n    headers = {\n    \"Content-type\": \"text/html\",\n    \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n    \"Accept-Encoding\": \" gzip, deflate\",\n    \"Accept-Language\": \" es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3\",\n    \"Connection\": \"keep-alive\",\n    \"DNT\": \"1\",\n    \"Host\": \"www.resolvethem.com\",\n    \"Referer\": \"http://www.resolvethem.com/index.php\",\n    \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; rv:38.0) Gecko/20100101 Firefox/38.0\",\n    \"Content-Length\": \"26\",\n    \"Content-Type\": \"application/x-www-form-urlencoded\",\n    }    \n    req = requests.post(\"http://www.resolvethem.com/index.php\",headers=headers,data={'skypeUsername': alias,'submit':''})\n    data = req.content\n    p = re.compile(\"class='alert alert-success'>([0-9\\.]*)<\")\n    allMatches = p.findall(data)\n    if len(allMatches)> 0:\n        jsonData = {}\n        jsonData[\"type\"]=\"i3visio.ip\"\n        jsonData[\"value\"]=allMatches[0]\n        jsonData[\"attributes\"]=[]     \n        return jsonData\n    return {}",
    "docstring": "Method that checks if the given alias is currently connected to Skype and returns its IP address. \n\n\t\t:param alias:\tAlias to be searched.\n\n\t\t:return:\tPython structure for the Json received. It has the following structure:\n\t        {\n              \"type\": \"i3visio.ip\",\n              \"value\": \"1.1.1.1\",\n              \"attributes\" : []\n            }"
  },
  {
    "code": "def _optimize_A(self, A):\n        right_eigenvectors = self.right_eigenvectors_[:, :self.n_macrostates]\n        flat_map, square_map = get_maps(A)\n        alpha = to_flat(1.0 * A, flat_map)\n        def obj(x):\n            return -1 * self._objective_function(\n                    x, self.transmat_, right_eigenvectors, square_map,\n                    self.populations_\n            )\n        alpha = scipy.optimize.basinhopping(\n                obj, alpha, niter_success=1000,\n        )['x']\n        alpha = scipy.optimize.fmin(\n                obj, alpha, full_output=True, xtol=1E-4, ftol=1E-4,\n                maxfun=5000, maxiter=100000\n        )[0]\n        if np.isneginf(obj(alpha)):\n            raise ValueError(\n                    \"Error: minimization has not located a feasible point.\")\n        A = to_square(alpha, square_map)\n        return A",
    "docstring": "Find optimal transformation matrix A by minimization.\n\n        Parameters\n        ----------\n        A : ndarray\n            The transformation matrix A.\n\n        Returns\n        -------\n        A : ndarray\n            The transformation matrix."
  },
  {
    "code": "def match_rules(tree, rules, fun=None, multi=False):\n    if multi:\n        context = match_rules_context_multi(tree, rules)\n    else:\n        context = match_rules_context(tree, rules)\n        if not context:\n            return None\n    if fun:\n        args = fun.__code__.co_varnames\n        if multi:\n            res = []\n            for c in context:\n                action_context = {}\n                for arg in args:\n                    if arg in c:\n                        action_context[arg] = c[arg]\n                res.append(fun(**action_context))\n            return res\n        else:\n            action_context = {}\n            for arg in args:\n                if arg in context:\n                    action_context[arg] = context[arg]\n            return fun(**action_context)\n    else:\n        return context",
    "docstring": "Matches a Tree structure with the given query rules.\n\n    Query rules are represented as a dictionary of template to action.\n    Action is either a function, or a dictionary of subtemplate parameter to rules::\n\n        rules = { 'template' : { 'key': rules } }\n              | { 'template' : {} }\n\n    Args:\n        tree (Tree): Parsed tree structure\n        rules (dict): A dictionary of query rules\n        fun (function): Function to call with context (set to None if you want to return context)\n        multi (Bool): If True, returns all matched contexts, else returns first matched context\n    Returns:\n        Contexts from matched rules"
  },
  {
    "code": "def wget_files():\n    for f in lamost_id:\n        short = (f.split('-')[2]).split('_')[0]\n        filename = \"%s/%s.gz\" %(short,f)\n        DIR = \"/Users/annaho/Data/Li_Giants/Spectra_APOKASC\"\n        searchfor = \"%s/%s.gz\" %(DIR,f)\n        if glob.glob(searchfor):\n            print(\"done\")\n        else:\n            os.system(\n                    \"wget http://dr2.lamost.org/sas/fits/%s\" %(filename))\n            new_filename = filename.split(\"_\")[0] + \"_\" + filename.split(\"_\")[2]\n            os.system(\n                    \"wget http://dr2.lamost.org/sas/fits/%s\" %(new_filename))",
    "docstring": "Pull the files from the LAMOST archive"
  },
  {
    "code": "def extract_alphabet(alphabet, inputdata, fixed_start = False):\n    if not inputdata:\n        return []\n    base_alphabet = alphabet.alphabet\n    lexer = lexer_factory(alphabet, base_alphabet)\n    totallen = len(inputdata)\n    maxl = totallen\n    minl = 1\n    if fixed_start:\n        max_start = 1\n    else:\n        max_start = totallen\n    result = []\n    for i in range(max_start):\n        for j in range(i+minl, min(i+maxl, totallen) + 1):\n            try:\n                lexed = lexer(inputdata[i:j])\n                if lexed and len(lexed) == 1:\n                    result.append((i,j, inputdata[i:j], lexed[0].gd))\n                elif lexed:\n                    raise Exception\n            except:\n                continue\n    result = filter_subsets(result)\n    return [PositionToken(content, gd, left, right) for (left, right, content, gd) in result]",
    "docstring": "Receives a sequence and an alphabet, \n    returns a list of PositionTokens with all of the parts of the sequence that \n    are a subset of the alphabet"
  },
  {
    "code": "def _merge_outfile_fname(out_file, bam_files, work_dir, batch):\n    if out_file is None:\n        out_file = os.path.join(work_dir, os.path.basename(sorted(bam_files)[0]))\n    if batch is not None:\n        base, ext = os.path.splitext(out_file)\n        out_file = \"%s-b%s%s\" % (base, batch, ext)\n    return out_file",
    "docstring": "Derive correct name of BAM file based on batching."
  },
  {
    "code": "def list_directory(self, path):\n        r\n        _complain_ifclosed(self.closed)\n        return self.fs.list_directory(path)",
    "docstring": "r\"\"\"\n        Get list of files and directories for ``path``\\ .\n\n        :type path: str\n        :param path: the path of the directory\n        :rtype: list\n        :return: list of files and directories in ``path``\n        :raises: :exc:`~exceptions.IOError`"
  },
  {
    "code": "def encode_function_call(self, function_name, args):\n        if function_name not in self.function_data:\n            raise ValueError('Unkown function {}'.format(function_name))\n        description = self.function_data[function_name]\n        function_selector = zpad(encode_int(description['prefix']), 4)\n        arguments = encode_abi(description['encode_types'], args)\n        return function_selector + arguments",
    "docstring": "Return the encoded function call.\n\n        Args:\n            function_name (str): One of the existing functions described in the\n                contract interface.\n            args (List[object]): The function arguments that wll be encoded and\n                used in the contract execution in the vm.\n\n        Return:\n            bin: The encoded function name and arguments so that it can be used\n                 with the evm to execute a funcion call, the binary string follows\n                 the Ethereum Contract ABI."
  },
  {
    "code": "def print_variables(self):\n        print_out = partial(self.print_out, format_options='green')\n        print_out('===== variables =====')\n        for var, hint in self.vars.get_descriptions().items():\n            print_out('    %' + var + ' = ' + var + ' = ' + hint.replace('%', '%%'))\n        print_out('=====================')\n        return self",
    "docstring": "Prints out magic variables available in config files\n        alongside with their values and descriptions.\n        May be useful for debugging.\n\n        http://uwsgi-docs.readthedocs.io/en/latest/Configuration.html#magic-variables"
  },
  {
    "code": "async def on_isupport_maxchannels(self, value):\n        if 'CHANTYPES' in self._isupport and 'CHANLIMIT' not in self._isupport:\n            self._channel_limits = {}\n            prefixes = self._isupport['CHANTYPES']\n            self._channel_limits[frozenset(prefixes)] = int(value)\n            for prefix in prefixes:\n                self._channel_limit_groups[prefix] = frozenset(prefixes)",
    "docstring": "Old version of CHANLIMIT."
  },
  {
    "code": "def log_stack(logger, level=logging.INFO, limit=None, frame=None):\n    if showing_stack.inside:\n        return\n    showing_stack.inside = True\n    try:\n        if frame is None:\n            frame = sys._getframe(1)\n        stack = \"\".join(traceback.format_stack(frame, limit))\n        for line in (l[2:] for l in stack.split(\"\\n\") if l.strip()):\n            logger.log(level, line)\n    finally:\n        showing_stack.inside = False",
    "docstring": "Display the current stack on ``logger``.\n\n    This function is designed to be used during emission of log messages, so it\n    won't call itself."
  },
  {
    "code": "def stop(self, graceful=False):\n        self.stop_flag.set()\n        if graceful:\n            self._logger.info('Shutting down gracefully...')\n            try:\n                for _, worker_process in self.worker_threads:\n                    worker_process.join()\n            except KeyboardInterrupt:\n                self._logger.info('Received request to shut down now.')\n            else:\n                self._logger.info('All workers have stopped.')\n        else:\n            self._logger.info('Shutting down')",
    "docstring": "Set the stop-flag.\n\n        If `graceful=True`, this method blocks until the workers to finish\n        executing any tasks they might be currently working on."
  },
  {
    "code": "def map_pores(self, pores, origin, filtered=True):\n        r\n        ids = origin['pore._id'][pores]\n        return self._map(element='pore', ids=ids, filtered=filtered)",
    "docstring": "r\"\"\"\n        Given a list of pore on a target object, finds indices of those pores\n        on the calling object\n\n        Parameters\n        ----------\n        pores : array_like\n            The indices of the pores on the object specifiedin ``origin``\n\n        origin : OpenPNM Base object\n            The object corresponding to the indices given in ``pores``\n\n        filtered : boolean (default is ``True``)\n            If ``True`` then a ND-array of indices is returned with missing\n            indices removed, otherwise a named-tuple containing both the\n            ``indices`` and a boolean ``mask`` with ``False`` indicating\n            which locations were not found.\n\n        Returns\n        -------\n        Pore indices on the calling object corresponding to the same pores\n        on the ``origin`` object.  Can be an array or a tuple containing an\n        array and a mask, depending on the value of ``filtered``."
  },
  {
    "code": "def remove(self, tag, nth=1):\n        tag = fix_tag(tag)\n        nth = int(nth)\n        for i in range(len(self.pairs)):\n            t, v = self.pairs[i]\n            if t == tag:\n                nth -= 1\n                if nth == 0:\n                    self.pairs.pop(i)\n                    return v\n        return None",
    "docstring": "Remove the n-th occurrence of tag in this message.\n\n        :param tag: FIX field tag number to be removed.\n        :param nth: Index of tag if repeating, first is 1.\n        :returns: Value of the field if removed, None otherwise."
  },
  {
    "code": "def insert_list(self, cards, indice=-1):\n        self_size = len(self.cards)\n        if indice in [0, -1]:\n            if indice == -1:\n                self.cards += cards\n            else:\n                self.cards.extendleft(cards)\n        elif indice != self_size:\n            half_x, half_y = self.split(indice)\n            self.cards = list(half_x.cards) + list(cards) + list(half_y.cards)",
    "docstring": "Insert a list of given cards into the stack at a given indice.\n\n        :arg list cards:\n            The list of cards to insert into the stack.\n        :arg int indice:\n            Where to insert the given cards."
  },
  {
    "code": "def debug(self, *args):\n        if _canShortcutLogging(self.logCategory, DEBUG):\n            return\n        debugObject(self.logObjectName(), self.logCategory,\n            *self.logFunction(*args))",
    "docstring": "Log a debug message.  Used for debugging."
  },
  {
    "code": "def add_argument(self, parser, bootstrap=False):\n        if self.cli_expose:\n            args = self._get_argparse_names(parser.prefix_chars)\n            kwargs = self._get_argparse_kwargs(bootstrap)\n            parser.add_argument(*args, **kwargs)",
    "docstring": "Add this item as an argument to the given parser.\n\n        Args:\n            parser (argparse.ArgumentParser): The parser to add this item to.\n            bootstrap: Flag to indicate whether you only want to mark this\n                item as required or not"
  },
  {
    "code": "def experiments_predictions_create(self, experiment_id, model_id, argument_defs, name, arguments=None, properties=None):\n        if self.experiments_get(experiment_id) is None:\n            return None\n        return self.predictions.create_object(\n            name,\n            experiment_id,\n            model_id,\n            argument_defs,\n            arguments=arguments,\n            properties=properties\n        )",
    "docstring": "Create new model run for given experiment.\n\n        Parameters\n        ----------\n        experiment_id : string\n            Unique experiment identifier\n        model_id : string\n            Unique identifier of model to run\n        name : string\n            User-provided name for the model run\n        argument_defs : list(attribute.AttributeDefinition)\n            Definition of valid arguments for the given model\n        arguments : list(dict('name':...,'value:...')), optional\n            List of attribute instances\n        properties : Dictionary, optional\n            Set of model run properties.\n\n        Returns\n        -------\n        ModelRunHandle\n            Handle for created model run or None if experiment is unknown"
  },
  {
    "code": "def system(command):\n    logger.debug('Running: %r', command)\n    subprocess.check_call(command, shell=isinstance(command, string_types), bufsize=-1)",
    "docstring": "A convenience wrapper around subprocess.check_call that logs the command before passing it\n    on. The command can be either a string or a sequence of strings. If it is a string shell=True\n    will be passed to subprocess.check_call.\n\n    :type command: str | sequence[string]"
  },
  {
    "code": "def outputSimple(self):\n        out = []\n        errors = []\n        successfulResponses = \\\n            len([True for rsp in self.results if rsp['success']])\n        out.append(\"INFO QUERIED {0}\".format(\n            len(self.serverList)))\n        out.append(\"INFO SUCCESS {0}\".format(\n            successfulResponses))\n        out.append(\"INFO ERROR {0}\".format(\n            len(self.serverList) - successfulResponses))\n        for rsp in self.resultsColated:\n            if rsp['success']:\n                out.append(\"RESULT {0} {1}\".format(\n                    len(rsp['servers']),\n                    \"|\".join(rsp['results'])\n                ))\n            else:\n                errors.append(\"ERROR {0} {1}\".format(\n                    len(rsp['servers']),\n                    \"|\".join(rsp['results'])\n                ))\n        out += errors\n        sys.stdout.write(\"\\n\".join(out))\n        sys.stdout.write(\"\\n\")",
    "docstring": "Simple output mode"
  },
  {
    "code": "def parse_compound_file(path, format):\n    context = FilePathContext(path)\n    format = resolve_format(format, context.filepath)\n    if format == 'yaml':\n        logger.debug('Parsing compound file {} as YAML'.format(\n            context.filepath))\n        with context.open('r') as f:\n            for compound in parse_compound_yaml_file(context, f):\n                yield compound\n    elif format == 'modelseed':\n        logger.debug('Parsing compound file {} as ModelSEED TSV'.format(\n            context.filepath))\n        with context.open('r') as f:\n            for compound in modelseed.parse_compound_file(f, context):\n                yield compound\n    elif format == 'tsv':\n        logger.debug('Parsing compound file {} as TSV'.format(\n            context.filepath))\n        with context.open('r') as f:\n            for compound in parse_compound_table_file(context, f):\n                yield compound\n    else:\n        raise ParseError('Unable to detect format of compound file {}'.format(\n            context.filepath))",
    "docstring": "Open and parse reaction file based on file extension or given format\n\n    Path can be given as a string or a context."
  },
  {
    "code": "def get_servo_position(self):\n        data = []\n        data.append(0x09)\n        data.append(self.servoid)\n        data.append(RAM_READ_REQ)\n        data.append(CALIBRATED_POSITION_RAM)\n        data.append(BYTE2)\n        send_data(data)\n        rxdata = []\n        try:\n            rxdata = SERPORT.read(13)\n            if (self.servomodel==0x06) or (self.servomodel == 0x04):\n                return ((ord(rxdata[10])&0xff)<<8) | (ord(rxdata[9])&0xFF)\n            else:\n                return ((ord(rxdata[10])&0x03)<<8) | (ord(rxdata[9])&0xFF)\n        except HerkulexError:\n            print \"Could not read from the servos. Check connection\"",
    "docstring": "Gets the current position of Herkulex\n\n        Args:\n            none\n\n        Returns:\n            int: position of the servo- 0 to 1023\n\n        Raises:\n            SerialException: Error occured while opening serial port"
  },
  {
    "code": "def show_instance(name, session=None, call=None):\n    if call == 'function':\n        raise SaltCloudException(\n            'The show_instnce function must be called with -a or --action.'\n        )\n    log.debug('show_instance-> name: %s session: %s', name, session)\n    if session is None:\n        session = _get_session()\n    vm = _get_vm(name, session=session)\n    record = session.xenapi.VM.get_record(vm)\n    if not record['is_a_template'] and not record['is_control_domain']:\n        try:\n            base_template_name = record['other_config']['base_template_name']\n        except Exception:\n            base_template_name = None\n            log.debug(\n                'VM %s, doesnt have base_template_name attribute',\n                record['name_label']\n            )\n        ret = {'id': record['uuid'],\n               'image': base_template_name,\n               'name': record['name_label'],\n               'size': record['memory_dynamic_max'],\n               'state': record['power_state'],\n               'private_ips': get_vm_ip(name, session),\n               'public_ips': None}\n        __utils__['cloud.cache_node'](\n            ret,\n            __active_provider_name__,\n            __opts__\n        )\n    return ret",
    "docstring": "Show information about a specific VM or template\n\n        .. code-block:: bash\n\n            salt-cloud -a show_instance xenvm01\n\n    .. note:: memory is memory_dynamic_max"
  },
  {
    "code": "def finalize(self):\n        self.library.finalize.argtypes = []\n        self.library.finalize.restype = c_int\n        ierr = wrap(self.library.finalize)()\n        logger.info('cd {}'.format(self.original_dir))\n        os.chdir(self.original_dir)\n        if ierr:\n            errormsg = \"Finalizing model {engine} failed with exit code {code}\"\n            raise RuntimeError(errormsg.format(engine=self.engine, code=ierr))",
    "docstring": "Shutdown the library and clean up the model.\n\n        Note that the Fortran library's cleanup code is not up to snuff yet,\n        so the cleanup is not perfect. Note also that the working directory is\n        changed back to the original one."
  },
  {
    "code": "def _starts_with_drive_letter(self, file_path):\n        colon = self._matching_string(file_path, ':')\n        return (self.is_windows_fs and len(file_path) >= 2 and\n                file_path[:1].isalpha and (file_path[1:2]) == colon)",
    "docstring": "Return True if file_path starts with a drive letter.\n\n        Args:\n            file_path: the full path to be examined.\n\n        Returns:\n            `True` if drive letter support is enabled in the filesystem and\n            the path starts with a drive letter."
  },
  {
    "code": "def max_rain(self):\n        return max(self._purge_none_samples(self.rain_series()),\n                   key=lambda item:item[1])",
    "docstring": "Returns a tuple containing the max value in the rain\n        series preceeded by its timestamp\n\n        :returns: a tuple\n        :raises: ValueError when the measurement series is empty"
  },
  {
    "code": "def on_confirmation(self, frame):\n        delivered = frame.method.NAME.split('.')[1].lower() == 'ack'\n        self.logger.debug('Received publisher confirmation (Delivered: %s)',\n                          delivered)\n        if frame.method.multiple:\n            for index in range(self.last_confirmation + 1,\n                               frame.method.delivery_tag):\n                self.confirm_delivery(index, delivered)\n        self.confirm_delivery(frame.method.delivery_tag, delivered)\n        self.last_confirmation = frame.method.delivery_tag",
    "docstring": "Invoked by pika when RabbitMQ responds to a Basic.Publish RPC\n        command, passing in either a Basic.Ack or Basic.Nack frame with\n        the delivery tag of the message that was published. The delivery tag\n        is an integer counter indicating the message number that was sent\n        on the channel via Basic.Publish.\n\n        :param pika.frame.Method frame: Basic.Ack or Basic.Nack frame"
  },
  {
    "code": "def move_partition_replica(self, under_loaded_rg, eligible_partition):\n        source_broker, dest_broker = self._get_eligible_broker_pair(\n            under_loaded_rg,\n            eligible_partition,\n        )\n        if source_broker and dest_broker:\n            self.log.debug(\n                'Moving partition {p_name} from broker {source_broker} to '\n                'replication-group:broker {rg_dest}:{dest_broker}'.format(\n                    p_name=eligible_partition.name,\n                    source_broker=source_broker.id,\n                    dest_broker=dest_broker.id,\n                    rg_dest=under_loaded_rg.id,\n                ),\n            )\n            source_broker.move_partition(eligible_partition, dest_broker)",
    "docstring": "Move partition to under-loaded replication-group if possible."
  },
  {
    "code": "def scandir_limited(top, limit, deep=0):\n    deep += 1\n    try:\n        scandir_it = Path2(top).scandir()\n    except PermissionError as err:\n        log.error(\"scandir error: %s\" % err)\n        return\n    for entry in scandir_it:\n        if entry.is_dir(follow_symlinks=False):\n            if deep < limit:\n                yield from scandir_limited(entry.path, limit, deep)\n            else:\n                yield entry",
    "docstring": "yields only directories with the given deep limit\n\n    :param top: source path\n    :param limit: how deep should be scanned?\n    :param deep: internal deep number\n    :return: yields os.DirEntry() instances"
  },
  {
    "code": "def assert_keys_exist(self, caller, *keys):\n        assert keys, (\"*keys parameter must be specified.\")\n        for key in keys:\n            self.assert_key_exists(key, caller)",
    "docstring": "Assert that context contains keys.\n\n        Args:\n            keys: validates that these keys exists in context\n            caller: string. calling function or module name - this used to\n                    construct error messages\n\n        Raises:\n            KeyNotInContextError: When key doesn't exist in context."
  },
  {
    "code": "def add_transform_chain(self, tc):\n        for t in tc.gpu_transforms:\n            if isinstance(t, Clip):\n                self.insert_vert('v_temp_pos_tr = temp_pos_tr;')\n                continue\n            self.insert_vert(t.glsl('temp_pos_tr'))\n        clip = tc.get('Clip')\n        if clip:\n            self.insert_frag(clip.glsl('v_temp_pos_tr'), 'before_transforms')",
    "docstring": "Insert the GLSL snippets of a transform chain."
  },
  {
    "code": "def pass_data_on(self, data_setters):\n        data_setters.init_structure(self.num_bonds, len(self.x_coord_list), len(self.group_type_list),\n                                    len(self.chain_id_list), len(self.chains_per_model), self.structure_id)\n        decoder_utils.add_entity_info(self, data_setters)\n        decoder_utils.add_atomic_information(self, data_setters)\n        decoder_utils.add_header_info(self, data_setters)\n        decoder_utils.add_xtalographic_info(self, data_setters)\n        decoder_utils.generate_bio_assembly(self, data_setters)\n        decoder_utils.add_inter_group_bonds(self, data_setters)\n        data_setters.finalize_structure()",
    "docstring": "Write the data from the getters to the setters.\n\n        :param data_setters: a series of functions that can fill a chemical\n        data structure\n        :type data_setters: DataTransferInterface"
  },
  {
    "code": "def from_coordinates(cls,   ra=None, dec=None,\n                                distance=None,\n                                pm_ra_cosdec=None, pm_dec=None,\n                                radial_velocity=None,\n                                obstime=2000.0*u.year,\n                                id=None, mag=None,\n                                **kwargs):\n        N = len(np.atleast_1d(ra))\n        if id is None:\n            id = ['{}'.format(i) for i in range(N)]\n        if mag is None:\n            mag = np.zeros(N)\n        standardized = Table(data=[id, mag], names=['object-id', 'filter-mag'])\n        for k in cls.coordinate_keys:\n            if locals()[k] is not None:\n                standardized[k] = locals()[k]\n        return cls(standardized)",
    "docstring": "Iniitalize a constellation object.\n\n\n        Parameters\n        ----------\n\n        ra, dec, distance, pm_ra_cosdec, pm_dec, radial_velocity\n            These must be able to initialize a SkyCoord.\n        id : list, array\n            Identifications for the entries.\n        mag : list, array\n            Magnitudes for the entries.\n        **kwargs\n            All arguments and keyword arguments are passed along\n            to SkyCoord. They can be coordinates in the first place,\n            or, for example, ra and dec with units, or any other\n            inputs that can initialize a SkyCoord."
  },
  {
    "code": "def connection_open(self) -> None:\n        assert self.state is State.CONNECTING\n        self.state = State.OPEN\n        logger.debug(\"%s - state = OPEN\", self.side)\n        self.transfer_data_task = self.loop.create_task(self.transfer_data())\n        self.keepalive_ping_task = self.loop.create_task(self.keepalive_ping())\n        self.close_connection_task = self.loop.create_task(self.close_connection())",
    "docstring": "Callback when the WebSocket opening handshake completes.\n\n        Enter the OPEN state and start the data transfer phase."
  },
  {
    "code": "def query_keys(self, user_devices, timeout=None, token=None):\n        content = {\"device_keys\": user_devices}\n        if timeout:\n            content[\"timeout\"] = timeout\n        if token:\n            content[\"token\"] = token\n        return self._send(\"POST\", \"/keys/query\", content=content)",
    "docstring": "Query HS for public keys by user and optionally device.\n\n        Args:\n            user_devices (dict): The devices whose keys to download. Should be\n                formatted as <user_id>: [<device_ids>]. No device_ids indicates\n                all devices for the corresponding user.\n            timeout (int): Optional. The time (in milliseconds) to wait when\n                downloading keys from remote servers.\n            token (str): Optional. If the client is fetching keys as a result of\n                a device update received in a sync request, this should be the\n                'since' token of that sync request, or any later sync token."
  },
  {
    "code": "def rnegative_binomial(mu, alpha, size=None):\n    mu = np.asarray(mu, dtype=float)\n    pois_mu = np.random.gamma(alpha, mu / alpha, size)\n    return np.random.poisson(pois_mu, size)",
    "docstring": "Random negative binomial variates."
  },
  {
    "code": "def teams(self, name=None, id=None, is_hidden=False, **kwargs):\n        request_params = {\n            'name': name,\n            'id': id,\n            'is_hidden': is_hidden\n        }\n        if kwargs:\n            request_params.update(**kwargs)\n        r = self._request('GET', self._build_url('teams'), params=request_params)\n        if r.status_code != requests.codes.ok:\n            raise NotFoundError(\"Could not find teams: '{}'\".format(r.json()))\n        data = r.json()\n        return [Team(team, client=self) for team in data['results']]",
    "docstring": "Teams of KE-chain.\n\n        Provide a list of :class:`Team`s of KE-chain. You can filter on teamname or id or any other advanced filter.\n\n        :param name: (optional) teamname to filter\n        :type name: basestring or None\n        :param id: (optional) id of the team to filter\n        :type id: basestring or None\n        :param is_hidden: (optional) boolean to show non-hidden or hidden teams or both (None) (default is non-hidden)\n        :type is_hidden: bool or None\n        :param kwargs: Additional filtering keyword=value arguments\n        :type kwargs: dict or None\n        :return: List of :class:`Teams`\n        :raises NotFoundError: when a team could not be found"
  },
  {
    "code": "def stop(self):\n        self._stop_event.set()\n        if not self.persistence:\n            return\n        if self._cancel_save is not None:\n            self._cancel_save()\n            self._cancel_save = None\n        self.persistence.save_sensors()",
    "docstring": "Stop the background thread."
  },
  {
    "code": "def GetUrnHashEntry(urn, token=None):\n  if data_store.RelationalDBEnabled():\n    client_id, vfs_path = urn.Split(2)\n    path_type, components = rdf_objects.ParseCategorizedPath(vfs_path)\n    path_info = data_store.REL_DB.ReadPathInfo(client_id, path_type, components)\n    return path_info.hash_entry\n  else:\n    with aff4.FACTORY.Open(urn, token=token) as fd:\n      return GetFileHashEntry(fd)",
    "docstring": "Returns an `rdf_crypto.Hash` instance for given URN of an AFF4 file."
  },
  {
    "code": "def send_encoded(self, message, auth_header=None, **kwargs):\n        client_string = 'raven-python/%s' % (raven.VERSION,)\n        if not auth_header:\n            timestamp = time.time()\n            auth_header = get_auth_header(\n                protocol=self.protocol_version,\n                timestamp=timestamp,\n                client=client_string,\n                api_key=self.remote.public_key,\n                api_secret=self.remote.secret_key,\n            )\n        headers = {\n            'User-Agent': client_string,\n            'X-Sentry-Auth': auth_header,\n            'Content-Encoding': self.get_content_encoding(),\n            'Content-Type': 'application/octet-stream',\n        }\n        return self.send_remote(\n            url=self.remote.store_endpoint,\n            data=message,\n            headers=headers,\n            **kwargs\n        )",
    "docstring": "Given an already serialized message, signs the message and passes the\n        payload off to ``send_remote``."
  },
  {
    "code": "def readable_time_delta(seconds):\n    days = seconds // 86400\n    seconds -= days * 86400\n    hours = seconds // 3600\n    seconds -= hours * 3600\n    minutes = seconds // 60\n    m_suffix = 's' if minutes != 1 else ''\n    h_suffix = 's' if hours != 1 else ''\n    d_suffix = 's' if days != 1 else ''\n    retval = u'{0} minute{1}'.format(minutes, m_suffix)\n    if hours != 0:\n        retval = u'{0} hour{1} and {2}'.format(hours, h_suffix, retval)\n    if days != 0:\n        retval = u'{0} day{1}, {2}'.format(days, d_suffix, retval)\n    return retval",
    "docstring": "Convert a number of seconds into readable days, hours, and minutes"
  },
  {
    "code": "def get_plugin_spec(self, name):\n        l_name = name.lower()\n        for spec in self.plugins:\n            name = spec.get('name', spec.get('klass', spec.module))\n            if name.lower() == l_name:\n                return spec\n        raise KeyError(name)",
    "docstring": "Get the specification attributes for plugin with name `name`."
  },
  {
    "code": "def setValidTo(self, value):\n        valid_from = self.getValidFrom()\n        valid_to = DateTime(value)\n        interval = self.getExpirationInterval()\n        if valid_from and interval:\n            valid_to = valid_from + int(interval)\n            self.getField(\"ValidTo\").set(self, valid_to)\n            logger.debug(\"Set ValidTo Date to: %r\" % valid_to)\n        else:\n            self.getField(\"ValidTo\").set(self, valid_to)",
    "docstring": "Custom setter method to calculate a `ValidTo` date based on\n        the `ValidFrom` and `ExpirationInterval` field values."
  },
  {
    "code": "async def send_script(self, conn_id, data):\n        progress_callback = functools.partial(_on_progress, self, 'script', conn_id)\n        resp = await self._execute(self._adapter.send_script_sync, conn_id, data, progress_callback)\n        _raise_error(conn_id, 'send_rpc', resp)",
    "docstring": "Send a a script to a device.\n\n        See :meth:`AbstractDeviceAdapter.send_script`."
  },
  {
    "code": "def set_distributed_assembled(self, irn_loc, jcn_loc, a_loc):\n        self.set_distributed_assembled_rows_cols(irn_loc, jcn_loc)\n        self.set_distributed_assembled_values(a_loc)",
    "docstring": "Set the distributed assembled matrix.\n\n        Distributed assembled matrices require setting icntl(18) != 0."
  },
  {
    "code": "def get_all_runs(self, only_largest_budget=False):\n\t\tall_runs = []\n\t\tfor k in self.data.keys():\n\t\t\truns = self.get_runs_by_id(k)\n\t\t\tif len(runs) > 0:\n\t\t\t\tif only_largest_budget:\n\t\t\t\t\tall_runs.append(runs[-1])\n\t\t\t\telse:\n\t\t\t\t\tall_runs.extend(runs)\n\t\treturn(all_runs)",
    "docstring": "returns all runs performed\n\n\t\tParameters\n\t\t----------\n\t\t\tonly_largest_budget: boolean\n\t\t\t\tif True, only the largest budget for each configuration\n\t\t\t\tis returned. This makes sense if the runs are continued\n\t\t\t\tacross budgets and the info field contains the information\n\t\t\t\tyou care about. If False, all runs of a configuration\n\t\t\t\tare returned"
  },
  {
    "code": "def _adjusted_script_code(self, script):\n        script_code = ByteData()\n        if script[0] == len(script) - 1:\n            return script\n        script_code += VarInt(len(script))\n        script_code += script\n        return script_code",
    "docstring": "Checks if the script code pased in to the sighash function is already\n        length-prepended\n        This will break if there's a redeem script that's just a pushdata\n        That won't happen in practice\n\n        Args:\n            script (bytes): the spend script\n        Returns:\n            (bytes): the length-prepended script (if necessary)"
  },
  {
    "code": "def do_application_actions_plus(parser, token):\n    nodelist = parser.parse(('end_application_actions',))\n    parser.delete_first_token()\n    return ApplicationActionsPlus(nodelist)",
    "docstring": "Render actions available with extra text."
  },
  {
    "code": "def auth_interactive(self, username, handler, submethods=\"\"):\n        if (not self.active) or (not self.initial_kex_done):\n            raise SSHException(\"No existing session\")\n        my_event = threading.Event()\n        self.auth_handler = AuthHandler(self)\n        self.auth_handler.auth_interactive(\n            username, handler, my_event, submethods\n        )\n        return self.auth_handler.wait_for_response(my_event)",
    "docstring": "Authenticate to the server interactively.  A handler is used to answer\n        arbitrary questions from the server.  On many servers, this is just a\n        dumb wrapper around PAM.\n\n        This method will block until the authentication succeeds or fails,\n        peroidically calling the handler asynchronously to get answers to\n        authentication questions.  The handler may be called more than once\n        if the server continues to ask questions.\n\n        The handler is expected to be a callable that will handle calls of the\n        form: ``handler(title, instructions, prompt_list)``.  The ``title`` is\n        meant to be a dialog-window title, and the ``instructions`` are user\n        instructions (both are strings).  ``prompt_list`` will be a list of\n        prompts, each prompt being a tuple of ``(str, bool)``.  The string is\n        the prompt and the boolean indicates whether the user text should be\n        echoed.\n\n        A sample call would thus be:\n        ``handler('title', 'instructions', [('Password:', False)])``.\n\n        The handler should return a list or tuple of answers to the server's\n        questions.\n\n        If the server requires multi-step authentication (which is very rare),\n        this method will return a list of auth types permissible for the next\n        step.  Otherwise, in the normal case, an empty list is returned.\n\n        :param str username: the username to authenticate as\n        :param callable handler: a handler for responding to server questions\n        :param str submethods: a string list of desired submethods (optional)\n        :return:\n            list of auth types permissible for the next stage of\n            authentication (normally empty).\n\n        :raises: `.BadAuthenticationType` -- if public-key authentication isn't\n            allowed by the server for this user\n        :raises: `.AuthenticationException` -- if the authentication failed\n        :raises: `.SSHException` -- if there was a network error\n\n        .. versionadded:: 1.5"
  },
  {
    "code": "def _split_path(self, path):\n        if '\\\\' in path:\n            p = path.find('\\\\')\n            hive = path[:p]\n            path = path[p+1:]\n        else:\n            hive = path\n            path = None\n        handle = self._hives_by_name[ hive.upper() ]\n        return handle, path",
    "docstring": "Splits a Registry path and returns the hive and key.\n\n        @type  path: str\n        @param path: Registry path.\n\n        @rtype:  tuple( int, str )\n        @return: Tuple containing the hive handle and the subkey path.\n            The hive handle is always one of the following integer constants:\n             - L{win32.HKEY_CLASSES_ROOT}\n             - L{win32.HKEY_CURRENT_USER}\n             - L{win32.HKEY_LOCAL_MACHINE}\n             - L{win32.HKEY_USERS}\n             - L{win32.HKEY_PERFORMANCE_DATA}\n             - L{win32.HKEY_CURRENT_CONFIG}"
  },
  {
    "code": "def _setup_transitions(tdef, states, prev=()):\n    trs = list(prev)\n    for transition in tdef:\n        if len(transition) == 3:\n            (name, source, target) = transition\n            if is_string(source) or isinstance(source, State):\n                source = [source]\n            source = [states[src] for src in source]\n            target = states[target]\n            tr = Transition(name, source, target)\n        else:\n            raise TypeError(\n                \"Elements of the 'transition' attribute of a \"\n                \"workflow should be three-tuples; got %r instead.\" % (transition,)\n            )\n        if any(prev_tr.name == tr.name for prev_tr in trs):\n            trs = [tr if prev_tr.name == tr.name else prev_tr for prev_tr in trs]\n        else:\n            trs.append(tr)\n    return TransitionList(trs)",
    "docstring": "Create a TransitionList object from a 'transitions' Workflow attribute.\n\n    Args:\n        tdef: list of transition definitions\n        states (StateList): already parsed state definitions.\n        prev (TransitionList): transition definitions from a parent.\n\n    Returns:\n        TransitionList: the list of transitions defined in the 'tdef' argument."
  },
  {
    "code": "def det_cplx_loglr(self, det):\n        try:\n            return getattr(self._current_stats, '{}_cplx_loglr'.format(det))\n        except AttributeError:\n            self._loglr()\n            return getattr(self._current_stats, '{}_cplx_loglr'.format(det))",
    "docstring": "Returns the complex log likelihood ratio in the given detector.\n\n        Parameters\n        ----------\n        det : str\n            The name of the detector.\n\n        Returns\n        -------\n        complex float :\n            The complex log likelihood ratio."
  },
  {
    "code": "def reflect_left(self, value):\n        if value > self:\n            value = self.reflect(value)\n        return value",
    "docstring": "Only reflects the value if is > self."
  },
  {
    "code": "def _reference_keys(self, reference):\n        if not isinstance(reference, six.string_types):\n            raise TypeError(\n                'When using ~ to reference dynamic attributes ref must be a str. a {0} was provided.'.format(type(reference).__name__)\n            )\n        if '~' in reference:\n            reference = reference[1:]\n            scheme = self._scheme_references.get(reference)\n            if not scheme:\n                raise LookupError(\n                    \"Was unable to find {0} in the scheme references. \"\n                    \"available references {1}\".format(reference, ', '.join(self._scheme_references.keys()))\n                )\n            return scheme['keys']\n        else:\n            raise AttributeError('references must start with ~. Please update {0} and retry.'.format(reference))",
    "docstring": "Returns a list of all of keys for a given reference.\n\n        :param reference: a :string:\n        :rtype: A :list: of reference keys."
  },
  {
    "code": "def ValidateServiceGaps(self,\n                          problems,\n                          validation_start_date,\n                          validation_end_date,\n                          service_gap_interval):\n    if service_gap_interval is None:\n      return\n    departures = self.GenerateDateTripsDeparturesList(validation_start_date,\n                                                      validation_end_date)\n    first_day_without_service = validation_start_date\n    last_day_without_service = validation_start_date\n    consecutive_days_without_service = 0\n    for day_date, day_trips, _ in departures:\n      if day_trips == 0:\n        if consecutive_days_without_service == 0:\n            first_day_without_service = day_date\n        consecutive_days_without_service += 1\n        last_day_without_service = day_date\n      else:\n        if consecutive_days_without_service >= service_gap_interval:\n            problems.TooManyDaysWithoutService(first_day_without_service,\n                                               last_day_without_service,\n                                               consecutive_days_without_service)\n        consecutive_days_without_service = 0\n    if consecutive_days_without_service >= service_gap_interval:\n      problems.TooManyDaysWithoutService(first_day_without_service,\n                                         last_day_without_service,\n                                         consecutive_days_without_service)",
    "docstring": "Validate consecutive dates without service in the feed.\n       Issue a warning if it finds service gaps of at least\n       \"service_gap_interval\" consecutive days in the date range\n       [validation_start_date, last_service_date)\n\n    Args:\n      problems: The problem reporter object\n      validation_start_date: A date object representing the date from which the\n                             validation should take place\n      validation_end_date: A date object representing the first day the feed is\n                        active\n      service_gap_interval: An integer indicating how many consecutive days the\n                            service gaps need to have for a warning to be issued\n\n    Returns:\n      None"
  },
  {
    "code": "def takes_parameters(count):\n    def decorator(f):\n        @wraps(f)\n        def wrapper(filter_operation_info, location, context, parameters, *args, **kwargs):\n            if len(parameters) != count:\n                raise GraphQLCompilationError(u'Incorrect number of parameters, expected {} got '\n                                              u'{}: {}'.format(count, len(parameters), parameters))\n            return f(filter_operation_info, location, context, parameters, *args, **kwargs)\n        return wrapper\n    return decorator",
    "docstring": "Ensure the filter function has \"count\" parameters specified."
  },
  {
    "code": "def OnCellBackgroundColor(self, event):\n        with undo.group(_(\"Background color\")):\n            self.grid.actions.set_attr(\"bgcolor\", event.color)\n        self.grid.ForceRefresh()\n        self.grid.update_attribute_toolbar()\n        event.Skip()",
    "docstring": "Cell background color event handler"
  },
  {
    "code": "def bin(self):\n        bits = self.v == 4 and 32 or 128\n        return bin(self.ip).split('b')[1].rjust(bits, '0')",
    "docstring": "Full-length binary representation of the IP address.\n\n        >>> ip = IP(\"127.0.0.1\")\n        >>> print(ip.bin())\n        01111111000000000000000000000001"
  },
  {
    "code": "def _loadError(ErrorType, thrownError, tracebackString):\n    RemoteException = asRemoteException(ErrorType)\n    return RemoteException(thrownError, tracebackString)",
    "docstring": "constructor of RemoteExceptions"
  },
  {
    "code": "def device_id_partition_keygen(request_envelope):\n    try:\n        device_id = request_envelope.context.system.device.device_id\n        return device_id\n    except AttributeError:\n        raise PersistenceException(\"Couldn't retrieve device id from \"\n                                   \"request envelope, for partition key use\")",
    "docstring": "Retrieve device id from request envelope, to use as partition key.\n\n    :param request_envelope: Request Envelope passed during skill\n        invocation\n    :type request_envelope: ask_sdk_model.RequestEnvelope\n    :return: Device Id retrieved from request envelope\n    :rtype: str\n    :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`"
  },
  {
    "code": "def find_element(self, value, by=By.ID, update=False) -> Elements:\n        if update or not self._nodes:\n            self.uidump()\n        for node in self._nodes:\n            if node.attrib[by] == value:\n                bounds = node.attrib['bounds']\n                coord = list(map(int, re.findall(r'\\d+', bounds)))\n                click_point = (coord[0] + coord[2]) / \\\n                    2, (coord[1] + coord[3]) / 2\n                return self._element_cls(self, node.attrib, by, value, coord, click_point)\n        raise NoSuchElementException(f'No such element: {by}={value!r}.')",
    "docstring": "Find a element or the first element."
  },
  {
    "code": "def inheritance_diagram_directive(name, arguments, options, content, lineno,\n                                  content_offset, block_text, state,\n                                  state_machine):\n    node = inheritance_diagram()\n    class_names = arguments\n    graph = InheritanceGraph(class_names)\n    for name in graph.get_all_class_names():\n        refnodes, x = xfileref_role(\n            'class', ':class:`%s`' % name, name, 0, state)\n        node.extend(refnodes)\n    node['graph'] = graph\n    node['parts'] = options.get('parts', 0)\n    node['content'] = \" \".join(class_names)\n    return [node]",
    "docstring": "Run when the inheritance_diagram directive is first encountered."
  },
  {
    "code": "def parallel_bulk(\n    client,\n    actions,\n    thread_count=4,\n    chunk_size=500,\n    max_chunk_bytes=100 * 1024 * 1024,\n    queue_size=4,\n    expand_action_callback=expand_action,\n    *args,\n    **kwargs\n):\n    from multiprocessing.pool import ThreadPool\n    actions = map(expand_action_callback, actions)\n    class BlockingPool(ThreadPool):\n        def _setup_queues(self):\n            super(BlockingPool, self)._setup_queues()\n            self._inqueue = Queue(max(queue_size, thread_count))\n            self._quick_put = self._inqueue.put\n    pool = BlockingPool(thread_count)\n    try:\n        for result in pool.imap(\n            lambda bulk_chunk: list(\n                _process_bulk_chunk(\n                    client, bulk_chunk[1], bulk_chunk[0], *args, **kwargs\n                )\n            ),\n            _chunk_actions(\n                actions, chunk_size, max_chunk_bytes, client.transport.serializer\n            ),\n        ):\n            for item in result:\n                yield item\n    finally:\n        pool.close()\n        pool.join()",
    "docstring": "Parallel version of the bulk helper run in multiple threads at once.\n\n    :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use\n    :arg actions: iterator containing the actions\n    :arg thread_count: size of the threadpool to use for the bulk requests\n    :arg chunk_size: number of docs in one chunk sent to es (default: 500)\n    :arg max_chunk_bytes: the maximum size of the request in bytes (default: 100MB)\n    :arg raise_on_error: raise ``BulkIndexError`` containing errors (as `.errors`)\n        from the execution of the last chunk when some occur. By default we raise.\n    :arg raise_on_exception: if ``False`` then don't propagate exceptions from\n        call to ``bulk`` and just report the items that failed as failed.\n    :arg expand_action_callback: callback executed on each action passed in,\n        should return a tuple containing the action line and the data line\n        (`None` if data line should be omitted).\n    :arg queue_size: size of the task queue between the main thread (producing\n        chunks to send) and the processing threads."
  },
  {
    "code": "def authorize_download(dataset_name=None):\n    print(('Acquiring resource: ' + dataset_name))\n    print('')\n    dr = data_resources[dataset_name]\n    print('Details of data: ')\n    print((dr['details']))\n    print('')\n    if dr['citation']:\n        print('Please cite:')\n        print((dr['citation']))\n        print('')\n    if dr['size']:\n        print(('After downloading the data will take up ' + str(dr['size']) + ' bytes of space.'))\n        print('')\n    print(('Data will be stored in ' + os.path.join(data_path, dataset_name) + '.'))\n    print('')\n    if overide_manual_authorize:\n        if dr['license']:\n            print('You have agreed to the following license:')\n            print((dr['license']))\n            print('')\n        return True\n    else:\n        if dr['license']:\n            print('You must also agree to the following license:')\n            print((dr['license']))\n            print('')\n        return prompt_user('Do you wish to proceed with the download? [yes/no]')",
    "docstring": "Check with the user that the are happy with terms and conditions for the data set."
  },
  {
    "code": "def _setup_pyudev_monitoring(self):\n        context = pyudev.Context()\n        monitor = pyudev.Monitor.from_netlink(context)\n        self.udev_observer = pyudev.MonitorObserver(monitor, self._udev_event)\n        self.udev_observer.start()\n        self.py3_wrapper.log(\"udev monitoring enabled\")",
    "docstring": "Setup the udev monitor."
  },
  {
    "code": "def process_api_config_response(self, config_json):\n    with self._config_lock:\n      self._add_discovery_config()\n      for config in config_json.get('items', []):\n        lookup_key = config.get('name', ''), config.get('version', '')\n        self._configs[lookup_key] = config\n      for config in self._configs.itervalues():\n        name = config.get('name', '')\n        api_version = config.get('api_version', '')\n        path_version = config.get('path_version', '')\n        sorted_methods = self._get_sorted_methods(config.get('methods', {}))\n        for method_name, method in sorted_methods:\n          self._save_rest_method(method_name, name, path_version, method)",
    "docstring": "Parses a JSON API config and registers methods for dispatch.\n\n    Side effects:\n      Parses method name, etc. for all methods and updates the indexing\n      data structures with the information.\n\n    Args:\n      config_json: A dict, the JSON body of the getApiConfigs response."
  },
  {
    "code": "def allow_unsigned(self, mav, msgId):\n        if self.allow is None:\n            self.allow = {\n                mavutil.mavlink.MAVLINK_MSG_ID_RADIO : True,\n                mavutil.mavlink.MAVLINK_MSG_ID_RADIO_STATUS : True\n                }\n        if msgId in self.allow:\n            return True\n        if self.settings.allow_unsigned:\n            return True\n        return False",
    "docstring": "see if an unsigned packet should be allowed"
  },
  {
    "code": "def read_files(*filenames):\n    output = []\n    for filename in filenames:\n        f = codecs.open(filename, encoding='utf-8')\n        try:\n            output.append(f.read())\n        finally:\n            f.close()\n    return '\\n\\n'.join(output)",
    "docstring": "Output the contents of one or more files to a single concatenated string."
  },
  {
    "code": "def has_image(self, digest, mime_type, index, size=500):\n        cache_key = f\"img:{index}:{size}:{digest}\"\n        return mime_type.startswith(\"image/\") or cache_key in self.cache",
    "docstring": "Tell if there is a preview image."
  },
  {
    "code": "def fetch_user(app_id, token, ticket, url_detail='https://pswdless.appspot.com/rest/detail'):\n    return FetchUserWithValidation(app_id, token, ticket, url_detail)",
    "docstring": "Fetch the user deatil from Passwordless"
  },
  {
    "code": "def render(self):\n        value = self.value\n        if value is None:\n            value = []\n        fmt = [Int.fmt]\n        data = [len(value)]\n        for item_value in value:\n            if issubclass(self.item_class, Primitive):\n                item = self.item_class(item_value)\n            else:\n                item = item_value\n            item_format, item_data = item.render()\n            fmt.extend(item_format)\n            data.extend(item_data)\n        return \"\".join(fmt), data",
    "docstring": "Creates a composite ``struct`` format and the data to render with it.\n\n        The format and data are prefixed with a 32-bit integer denoting the\n        number of elements, after which each of the items in the array value\n        are ``render()``-ed and added to the format and data as well."
  },
  {
    "code": "def get_batch_result_ids(self, job_id, batch_id):\n        response = requests.get(self._get_batch_results_url(job_id, batch_id),\n                                headers=self._get_batch_info_headers())\n        response.raise_for_status()\n        root = ET.fromstring(response.text)\n        result_ids = [r.text for r in root.findall('%sresult' % self.API_NS)]\n        return result_ids",
    "docstring": "Get result IDs of a batch that has completed processing.\n\n        :param job_id: job_id as returned by 'create_operation_job(...)'\n        :param batch_id: batch_id as returned by 'create_batch(...)'\n        :return: list of batch result IDs to be used in 'get_batch_result(...)'"
  },
  {
    "code": "def split_by_idxs(seq, idxs):\n    last = 0\n    for idx in idxs:\n        if not (-len(seq) <= idx < len(seq)):\n          raise KeyError(f'Idx {idx} is out-of-bounds')\n        yield seq[last:idx]\n        last = idx\n    yield seq[last:]",
    "docstring": "A generator that returns sequence pieces, seperated by indexes specified in idxs."
  },
  {
    "code": "def getModule(self, moduleName):\n        if moduleName not in self.moduleCache:\n            modulePath = FilePath(\n                athena.jsDeps.getModuleForName(moduleName)._cache.path)\n            cachedModule = self.moduleCache[moduleName] = CachedJSModule(\n                moduleName, modulePath)\n        else:\n            cachedModule = self.moduleCache[moduleName]\n        return cachedModule",
    "docstring": "Retrieve a JavaScript module cache from the file path cache.\n\n        @returns: Module cache for the named module.\n        @rtype: L{CachedJSModule}"
  },
  {
    "code": "def update_stats_history(self):\n        if self.get_key() is None:\n            item_name = ''\n        else:\n            item_name = self.get_key()\n        if self.get_export() and self.history_enable():\n            for i in self.get_items_history_list():\n                if isinstance(self.get_export(), list):\n                    for l in self.get_export():\n                        self.stats_history.add(\n                            nativestr(l[item_name]) + '_' + nativestr(i['name']),\n                            l[i['name']],\n                            description=i['description'],\n                            history_max_size=self._limits['history_size'])\n                else:\n                    self.stats_history.add(nativestr(i['name']),\n                                           self.get_export()[i['name']],\n                                           description=i['description'],\n                                           history_max_size=self._limits['history_size'])",
    "docstring": "Update stats history."
  },
  {
    "code": "def get_config_dict(self):\n        config_dict = {}\n        for dotted_key, value in self.get_config_values().items():\n            subkeys = dotted_key.split('.')\n            d = config_dict\n            for key in subkeys:\n                d = d.setdefault(key, value if key == subkeys[-1] else {})\n        return config_dict",
    "docstring": "Reconstruct the nested structure of this object's configuration\n        and return it as a dict."
  },
  {
    "code": "def _consume_next(self):\n        response = six.next(self._response_iterator)\n        self._counter += 1\n        if self._metadata is None:\n            metadata = self._metadata = response.metadata\n            source = self._source\n            if source is not None and source._transaction_id is None:\n                source._transaction_id = metadata.transaction.id\n        if response.HasField(\"stats\"):\n            self._stats = response.stats\n        values = list(response.values)\n        if self._pending_chunk is not None:\n            values[0] = self._merge_chunk(values[0])\n        if response.chunked_value:\n            self._pending_chunk = values.pop()\n        self._merge_values(values)",
    "docstring": "Consume the next partial result set from the stream.\n\n        Parse the result set into new/existing rows in :attr:`_rows`"
  },
  {
    "code": "def re_pipe(FlowRate, Diam, Nu):\n    ut.check_range([FlowRate, \">0\", \"Flow rate\"], [Diam, \">0\", \"Diameter\"],\n                   [Nu, \">0\", \"Nu\"])\n    return (4 * FlowRate) / (np.pi * Diam * Nu)",
    "docstring": "Return the Reynolds Number for a pipe."
  },
  {
    "code": "def get(self, sid):\n        return AssignedAddOnContext(\n            self._version,\n            account_sid=self._solution['account_sid'],\n            resource_sid=self._solution['resource_sid'],\n            sid=sid,\n        )",
    "docstring": "Constructs a AssignedAddOnContext\n\n        :param sid: The unique string that identifies the resource\n\n        :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnContext\n        :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.AssignedAddOnContext"
  },
  {
    "code": "def get_repo_url(pypirc, repository):\n    pypirc = os.path.abspath(os.path.expanduser(pypirc))\n    pypi_config = base.PyPIConfig(pypirc)\n    repo_config = pypi_config.get_repo_config(repository)\n    if repo_config:\n        return repo_config.get_clean_url()\n    else:\n        return base.RepositoryURL(repository)",
    "docstring": "Fetch the RepositoryURL for a given repository, reading info from pypirc.\n\n    Will try to find the repository in the .pypirc, including username/password.\n\n    Args:\n        pypirc (str): path to the .pypirc config file\n        repository (str): URL or alias for the repository\n\n    Returns:\n        base.RepositoryURL for the repository"
  },
  {
    "code": "def get_open_spaces(board):\n  open_spaces = []\n  for i in range(3):\n    for j in range(3):\n      if board[i][j] == 0:\n        open_spaces.append(encode_pos(i, j))\n  return open_spaces",
    "docstring": "Given a representation of the board, returns a list of open spaces."
  },
  {
    "code": "def _rebuild_fields(self):\n        new_field_lists = []\n        field_list_len = self.min_elements\n        while not field_list_len > self.max_elements:\n            how_many = self.max_elements + 1 - field_list_len\n            i = 0\n            while i < how_many:\n                current = self.random.sample(self._fields, field_list_len)\n                if current not in new_field_lists:\n                    new_field_lists.append(current)\n                    i += 1\n            field_list_len += 1\n        new_containers = []\n        for i, fields in enumerate(new_field_lists):\n            dup_fields = [field.copy() for field in fields]\n            if self.get_name():\n                name = '%s_sublist_%d' % (self.get_name(), i)\n            else:\n                name = 'sublist_%d' % (i)\n            new_containers.append(Container(fields=dup_fields, encoder=self.subcontainer_encoder, name=name))\n        self.replace_fields(new_containers)",
    "docstring": "We take the original fields and create subsets of them, each subset will be set into a container.\n        all the resulted containers will then replace the original _fields, since we inherit from OneOf each time only one of them will be mutated and used.\n        This is super ugly and dangerous, any idea how to implement it in a better way is welcome."
  },
  {
    "code": "def fromgroups(args):\n    from jcvi.formats.bed import Bed\n    p = OptionParser(fromgroups.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) < 2:\n        sys.exit(not p.print_help())\n    groupsfile = args[0]\n    bedfiles = args[1:]\n    beds = [Bed(x) for x in bedfiles]\n    fp = open(groupsfile)\n    groups = [row.strip().split(\",\") for row in fp]\n    for b1, b2 in product(beds, repeat=2):\n        extract_pairs(b1, b2, groups)",
    "docstring": "%prog fromgroups groupsfile a.bed b.bed ...\n\n    Flatten the gene familes into pairs, the groupsfile is a file with each line\n    containing the members, separated by comma. The commands also require\n    several bed files in order to sort the pairs into different piles (e.g.\n    pairs of species in comparison."
  },
  {
    "code": "def img2ascii(img_path, ascii_path, ascii_char=\"*\", pad=0):\n    if len(ascii_char) != 1:\n        raise Exception(\"ascii_char has to be single character.\")\n    image = Image.open(img_path).convert(\"L\")\n    matrix = np.array(image)\n    matrix[np.where(matrix >= 128)] = 255\n    matrix[np.where(matrix < 128)] = 0\n    lines = list()\n    for vector in matrix:\n        line = list()\n        for i in vector:\n            line.append(\" \" * pad)\n            if i:\n                line.append(\" \")\n            else:\n                line.append(ascii_char)\n        lines.append(\"\".join(line))\n    with open(ascii_path, \"w\") as f:\n        f.write(\"\\n\".join(lines))",
    "docstring": "Convert an image to ascii art text.\n\n    Suppose we have an image like that:\n\n    .. image:: images/rabbit.png\n        :align: left\n\n    Put some codes::\n\n        >>> from weatherlab.math.img2waveform import img2ascii\n        >>> img2ascii(r\"testdata\\img2waveform\\rabbit.png\", \n        ...           r\"testdata\\img2waveform\\asciiart.txt\", pad=0)\n\n    Then you will see this in asciiart.txt::\n\n\n                               ******                                                   \n                              ***  ***                         ****                     \n                             **      **                     *********                   \n                            **        **                   ***     ***                  \n                           **          *                  **         **                 \n                           **          **                **          **                 \n                          **            *               ***           *                 \n                          *             **              **            **                \n                         **              *             **             **                \n                         **              *             **              *                \n                         *               **           **               *                \n                        **               **           *                **               \n                        **                *          **                **               \n                        *                 *          **                **               \n                        *                 **         *                 **               \n                       **                 **        **                 **               \n                       **                  *        **                 **               \n                       **                  *        *                  **               \n                       **                  *       **                   *               \n                       **                  *       **                   *               \n                       *                   **      **                   *               \n                       *                   **      *                    *               \n                       *                   **     **                    *               \n                       *                   **     **                    *               \n                       **                  **     **                   **               \n                       **                   *     **                   **               \n                       **                   *     *                    **               \n                       **                   *     *                    **               \n                       **                   *     *                    **               \n                        *                   *    **                    **               \n                        *                   *    **                    *                \n                        **                  *    **                    *                \n                        **                  *    **                    *                \n                        **                  **   **                   **                \n                         *                  **   **                   **                \n                         *                  **   **                   **                \n                         **                 **   **                   *                 \n                         **                 **   **                  **                 \n                          *                 **   **                  **                 \n                          **                **   **                  *                  \n                          **                *******                  *                  \n                          **                *******                 **                  \n                           **                                       **                  \n                           **                                       *                   \n                           **                                      **                   \n                          ***                                      *                    \n                        ****                                       ***                  \n                      ***                                           ***                 \n                     **                                              ****               \n                    **                                                 ***              \n                   **                                                   ***             \n                  **                                                      **            \n                 **                                                        **           \n                 *                                                          **          \n                **                                                           **         \n               **                                                            **         \n               **                                                             **        \n              **                                                               **       \n              **                                                               **       \n             **                                                                 **      \n             **                                                                 **      \n             *                                                                   **     \n             *                                                                   **     \n            **                                                                    *     \n            **                                                                    **    \n            *                                                                     **    \n            *                                                                     **    \n           **                                                                      *    \n           **                                                                      *    \n           **                                                                      **   \n           **                                                                      **   \n           **                                                                      **   \n           **                                                                      **   \n           **            **                                                        **   \n           **            ***                                      ***              **   \n            *           ****                                      ****             **   \n            *            ***                                      ****             **   \n            **           **                                        **              *    \n            **                                                                     *    \n            **                                                                     *    \n             *                                                                    **    \n             **                                                                   **    \n             **                                                                   *     \n              *                                                                  **     \n              **                                                                 **     \n               **                                                               **      \n               **                                                               *       \n                **                                                             **       \n                **                                                            **        \n                 **                                                          **         \n                  **                        ***  **                         **          \n                   **                        ******                        ***          \n                    ***                     ******                        **            \n                     ***                     *  ***                     ***             \n                       ***                                             ***              \n                        ***                                          ***                \n                          ****                                     ****                 \n                         ********                                *******                \n                        *** **********                       ******** ***               \n                       **   ***  ************         ********** *** * ***              \n                      **  * ****      ***********************   ***  ** ***             \n                     ** *  ** ****  **       ******* *         *** ***** ***            \n                    ****  *  * *****       **********      * **** *  * ** **            \n                   ***  * * ** * ******************************* * ***   * **           \n                   ** ***** * *** ********** **  ** **********   ***   **  ***          \n                  ** * ***** **  *    *****  **  **   *****   * *  ** *     **          \n                 ***  *** ************    ** ****** ** *    * ** ** ** * ** ***         \n                 ** ******* *  * **    **  ** ****    *  ** *  **   * ****   **         \n                ** *** *** ******* ****** * **   * *** ***** *** ** ***** **  **        \n                ** * *  ***** ************************************ * ****  *  **        \n               *** ** ** ***********************************************  *** ***       \n                ***   ** ****************************************** **** ** ** **       \n                ****  ** ** ******************************************** ** *  **       \n               ** ****** ** ******************************************** ** *  ***      \n               **  ***** *********************************************** **  ****       \n               *     *** ****************************** **************** *********      \n              **      **  *************************************** * * *  *****   *      \n              **      ** **********************************************  ***     *      \n               *      ** **  *********************************** ******* **      *      \n               **     **  *****************************************  *** **      *      \n                ***  ** * ********************************************** **     **      \n                 ****** ************************************************ **   ***       \n                   **** *********************************************** ********        \n                     **  *********************************************** ****           \n                     *** **  ******************************************* **             \n                      *** ** ***** ****** * * * * *  ******** *** ** ** ***             \n                       ***  *   * ****   ****  **** * ** **  * *** **  ***              \n                        ****   * * ** **** * *** ********  *  ***   *****               \n                         *****    ** **  ** **  ***  ** ***       *****                 \n                           *******        * * ** * **        ********                   \n                              *************** *   *******************                   \n                               ******************************      ***                  \n                              ***          *********                **                  \n                              **                  *                  **                 \n                             **                   *                  **                 \n                             **                   *                  **                 \n                             **                   *                  **                 \n                             **                   *                  **                 \n                             **                  **                 **                  \n                              **                ****** *  ** *********                  \n                               *************************************                    \n                                  **********    \n\n    :param img_path: the image file path\n    :type img_path: str\n    :param ascii_path: the output ascii text file path\n    :type ascii_path: str\n    :param pad: how many space been filled in between two pixels\n    :type pad: int"
  },
  {
    "code": "def find_typed_function(pytype, prefix, suffix, module=lal):\n    laltype = to_lal_type_str(pytype)\n    return getattr(module, '{0}{1}{2}'.format(prefix, laltype, suffix))",
    "docstring": "Returns the lal method for the correct type\n\n    Parameters\n    ----------\n    pytype : `type`, `numpy.dtype`\n        the python type, or dtype, to map\n\n    prefix : `str`\n        the function name prefix (before the type tag)\n\n    suffix : `str`\n        the function name suffix (after the type tag)\n\n    Raises\n    ------\n    AttributeError\n        if the function is not found\n\n    Examples\n    --------\n    >>> from gwpy.utils.lal import find_typed_function\n    >>> find_typed_function(float, 'Create', 'Sequence')\n    <built-in function CreateREAL8Sequence>"
  },
  {
    "code": "def prepend(self, _, child, name=None):\n        self._insert(child, prepend=True, name=name)\n        return self",
    "docstring": "Adds childs to this tag, starting from the first position."
  },
  {
    "code": "def from_dictionary(cls, dictionary):\n        if not isinstance(dictionary, dict):\n            raise TypeError('dictionary has to be a dict type, got: {}'.format(type(dictionary)))\n        return cls(dictionary)",
    "docstring": "Parse a dictionary representing all command line parameters."
  },
  {
    "code": "def screenshot(filename=\"screenshot.png\"):\n    if not settings.plotter_instance.window:\n        colors.printc('~bomb screenshot(): Rendering window is not present, skip.', c=1)\n        return\n    w2if = vtk.vtkWindowToImageFilter()\n    w2if.ShouldRerenderOff()\n    w2if.SetInput(settings.plotter_instance.window)\n    w2if.ReadFrontBufferOff()\n    w2if.Update()\n    pngwriter = vtk.vtkPNGWriter()\n    pngwriter.SetFileName(filename)\n    pngwriter.SetInputConnection(w2if.GetOutputPort())\n    pngwriter.Write()",
    "docstring": "Save a screenshot of the current rendering window."
  },
  {
    "code": "def upload(config, remote_loc, u_filename):\n    rcode = False\n    try:\n        sftp, transport = get_sftp_conn(config)\n        remote_dir = get_remote_path(remote_loc)\n        for part in ['sha1', 'asc']:\n            local_file = '%s.%s' % (u_filename, part)\n            remote_file = os.path.join(remote_dir, local_file)\n            sftp.put(local_file, remote_file)\n        sftp.put(remote_dir, os.path.join(remote_dir, u_filename))\n        rcode = True\n    except BaseException:\n        pass\n    finally:\n        if 'transport' in locals():\n            transport.close()\n    return rcode",
    "docstring": "Upload the files"
  },
  {
    "code": "def debug_callback(event, *args, **kwds):\n    l = ['event %s' % (event.type,)]\n    if args:\n        l.extend(map(str, args))\n    if kwds:\n        l.extend(sorted('%s=%s' % t for t in kwds.items()))\n    print('Debug callback (%s)' % ', '.join(l))",
    "docstring": "Example callback, useful for debugging."
  },
  {
    "code": "def interm_fluent_variables(self) -> FluentParamsList:\n        fluents = self.domain.intermediate_fluents\n        ordering = self.domain.interm_fluent_ordering\n        return self._fluent_params(fluents, ordering)",
    "docstring": "Returns the instantiated intermediate fluents in canonical order.\n\n        Returns:\n            Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name\n            and a list of instantiated fluents represented as strings."
  },
  {
    "code": "def parse_code(url):\n    result = urlparse(url)\n    query = parse_qs(result.query)\n    return query['code']",
    "docstring": "Parse the code parameter from the a URL\n\n    :param str url: URL to parse\n    :return: code query parameter\n    :rtype: str"
  },
  {
    "code": "def add_action_to(cls, parser, action, subactions, level):\n        p = parser.add_parser(action.name,\n                              description=action.description,\n                              argument_default=argparse.SUPPRESS)\n        for arg in action.args:\n            arg.add_argument_to(p)\n        if subactions:\n            subparsers = cls._add_subparsers_required(p,\n                dest=settings.SUBASSISTANT_N_STRING.format(level),\n                title=cls.subactions_str,\n                description=cls.subactions_desc)\n            for subact, subsubacts in sorted(subactions.items(), key=lambda x: x[0].name):\n                cls.add_action_to(subparsers, subact, subsubacts, level + 1)",
    "docstring": "Adds given action to given parser\n\n        Args:\n            parser: instance of devassistant_argparse.ArgumentParser\n            action: devassistant.actions.Action subclass\n            subactions: dict with subactions - {SubA: {SubB: {}}, SubC: {}}"
  },
  {
    "code": "def save(self, *args, **kwargs):\n        if self.send_html:\n            self.content = get_text_for_html(self.html_content)\n        else:\n            self.html_content = None\n        super(EmailTemplate, self).save(*args, **kwargs)",
    "docstring": "If this is an HTML template, then set the non-HTML content to be the stripped version of the HTML.\n        If this is a plain text template, then set the HTML content to be null."
  },
  {
    "code": "def lr_find(self, start_lr=1e-5, end_lr=10, wds=None, linear=False, **kwargs):\n        self.save('tmp')\n        layer_opt = self.get_layer_opt(start_lr, wds)\n        self.sched = LR_Finder(layer_opt, len(self.data.trn_dl), end_lr, linear=linear)\n        self.fit_gen(self.model, self.data, layer_opt, 1, **kwargs)\n        self.load('tmp')",
    "docstring": "Helps you find an optimal learning rate for a model.\n\n         It uses the technique developed in the 2015 paper\n         `Cyclical Learning Rates for Training Neural Networks`, where\n         we simply keep increasing the learning rate from a very small value,\n         until the loss starts decreasing.\n\n        Args:\n            start_lr (float/numpy array) : Passing in a numpy array allows you\n                to specify learning rates for a learner's layer_groups\n            end_lr (float) : The maximum learning rate to try.\n            wds (iterable/float)\n\n        Examples:\n            As training moves us closer to the optimal weights for a model,\n            the optimal learning rate will be smaller. We can take advantage of\n            that knowledge and provide lr_find() with a starting learning rate\n            1000x smaller than the model's current learning rate as such:\n\n            >> learn.lr_find(lr/1000)\n\n            >> lrs = np.array([ 1e-4, 1e-3, 1e-2 ])\n            >> learn.lr_find(lrs / 1000)\n\n        Notes:\n            lr_find() may finish before going through each batch of examples if\n            the loss decreases enough.\n\n        .. _Cyclical Learning Rates for Training Neural Networks:\n            http://arxiv.org/abs/1506.01186"
  },
  {
    "code": "def _compute_gas_price(probabilities, desired_probability):\n    first = probabilities[0]\n    last = probabilities[-1]\n    if desired_probability >= first.prob:\n        return int(first.gas_price)\n    elif desired_probability <= last.prob:\n        return int(last.gas_price)\n    for left, right in sliding_window(2, probabilities):\n        if desired_probability < right.prob:\n            continue\n        elif desired_probability > left.prob:\n            raise Exception('Invariant')\n        adj_prob = desired_probability - right.prob\n        window_size = left.prob - right.prob\n        position = adj_prob / window_size\n        gas_window_size = left.gas_price - right.gas_price\n        gas_price = int(math.ceil(right.gas_price + gas_window_size * position))\n        return gas_price\n    else:\n        raise Exception('Invariant')",
    "docstring": "Given a sorted range of ``Probability`` named-tuples returns a gas price\n    computed based on where the ``desired_probability`` would fall within the\n    range.\n\n    :param probabilities: An iterable of `Probability` named-tuples sorted in reverse order.\n    :param desired_probability: An floating point representation of the desired\n        probability. (e.g. ``85% -> 0.85``)"
  },
  {
    "code": "def add_exception_handler(self, exception_handler):\n        if exception_handler is None or not isinstance(\n                exception_handler, AbstractExceptionHandler):\n            raise DispatchException(\n                \"Input is not an AbstractExceptionHandler instance\")\n        self._exception_handlers.append(exception_handler)",
    "docstring": "Checks the type before adding it to the exception_handlers\n        instance variable.\n\n        :param exception_handler: Exception Handler instance.\n        :type exception_handler: ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler\n        :raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException` if a\n            null input is provided or if the input is of invalid type"
  },
  {
    "code": "def week(self):\n        self.magnification = 345600\n        self._update(self.baseNumber, self.magnification)\n        return self",
    "docstring": "set unit to week"
  },
  {
    "code": "def make_random_client_id(self):\n        if PY2:\n            return ('py_%s' %\n                    base64.b64encode(str(random.randint(1, 0x40000000))))\n        else:\n            return ('py_%s' %\n                    base64.b64encode(bytes(str(random.randint(1, 0x40000000)),\n                                     'ascii')))",
    "docstring": "Returns a random client identifier"
  },
  {
    "code": "def _get_fct_number_of_arg(self, fct):\n        py_version = sys.version_info[0]\n        if py_version >= 3:\n            return len(inspect.signature(fct).parameters)\n        return len(inspect.getargspec(fct)[0])",
    "docstring": "Get the number of argument of a fuction."
  },
  {
    "code": "def message(blockers):\n    if not blockers:\n        encoding = getattr(sys.stdout, 'encoding', '')\n        if encoding:\n            encoding = encoding.lower()\n        if encoding == 'utf-8':\n            flair = \"\\U0001F389  \"\n        else:\n            flair = ''\n        return [flair +\n                'You have 0 projects blocking you from using Python 3!']\n    flattened_blockers = set()\n    for blocker_reasons in blockers:\n        for blocker in blocker_reasons:\n            flattened_blockers.add(blocker)\n    need = 'You need {0} project{1} to transition to Python 3.'\n    formatted_need = need.format(len(flattened_blockers),\n                      's' if len(flattened_blockers) != 1 else '')\n    can_port = ('Of {0} {1} project{2}, {3} {4} no direct dependencies '\n                'blocking {5} transition:')\n    formatted_can_port = can_port.format(\n            'those' if len(flattened_blockers) != 1 else 'that',\n            len(flattened_blockers),\n            's' if len(flattened_blockers) != 1 else '',\n            len(blockers),\n            'have' if len(blockers) != 1 else 'has',\n            'their' if len(blockers) != 1 else 'its')\n    return formatted_need, formatted_can_port",
    "docstring": "Create a sequence of key messages based on what is blocking."
  },
  {
    "code": "def to_json(self):\n        sets = self.sets()\n        return sorted(sorted(x) for x in sets)",
    "docstring": "Returns the equivalence classes a sorted list of sorted lists."
  },
  {
    "code": "def configure(self, config):\n        self.config = config\n        self.update_monitors()\n        for profile in ('worker', 'result'):\n            for _ in range(config['threads'][profile]['number']):\n                worker = threading.Thread(target=config['threads'][profile]['function'])\n                worker.daemon = True\n                worker.start()\n        self.heartbeat()\n        self.refresh_stopper = set_interval(config['interval']['refresh']*1000,\n                                            self.update_monitors)\n        self.heartbeat_stopper = set_interval(config['interval']['heartbeat']*1000,\n                                              self.heartbeat)\n        self.reporting_stopper = set_interval(config['interval']['reporting']*1000,\n                                              self.reporting)\n        return self",
    "docstring": "Configure Monitor, pull list of what to monitor, initialize threads"
  },
  {
    "code": "def prepare_uuid(data, schema):\n    if isinstance(data, uuid.UUID):\n        return str(data)\n    else:\n        return data",
    "docstring": "Converts uuid.UUID to\n    string formatted UUID xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
  },
  {
    "code": "def profile_add(user, profile):\n    ret = {}\n    profiles = profile.split(',')\n    known_profiles = profile_list().keys()\n    valid_profiles = [p for p in profiles if p in known_profiles]\n    log.debug(\n        'rbac.profile_add - profiles=%s, known_profiles=%s, valid_profiles=%s',\n        profiles,\n        known_profiles,\n        valid_profiles,\n    )\n    if valid_profiles:\n        res = __salt__['cmd.run_all']('usermod -P \"{profiles}\" {login}'.format(\n            login=user,\n            profiles=','.join(set(profile_get(user) + valid_profiles)),\n        ))\n        if res['retcode'] > 0:\n            ret['Error'] = {\n                'retcode': res['retcode'],\n                'message': res['stderr'] if 'stderr' in res else res['stdout']\n            }\n            return ret\n    active_profiles = profile_get(user, False)\n    for p in profiles:\n        if p not in valid_profiles:\n            ret[p] = 'Unknown'\n        elif p in active_profiles:\n            ret[p] = 'Added'\n        else:\n            ret[p] = 'Failed'\n    return ret",
    "docstring": "Add profile to user\n\n    user : string\n        username\n    profile : string\n        profile name\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rbac.profile_add martine 'Primary Administrator'\n        salt '*' rbac.profile_add martine 'User Management,User Security'"
  },
  {
    "code": "def withSize(cls, minimum, maximum):\n        class X(cls):\n            subtypeSpec = cls.subtypeSpec + constraint.ValueSizeConstraint(\n                minimum, maximum)\n        X.__name__ = cls.__name__\n        return X",
    "docstring": "Creates a subclass with value size constraint."
  },
  {
    "code": "def supports_caller(func):\n    def wrap_stackframe(context, *args, **kwargs):\n        context.caller_stack._push_frame()\n        try:\n            return func(context, *args, **kwargs)\n        finally:\n            context.caller_stack._pop_frame()\n    return wrap_stackframe",
    "docstring": "Apply a caller_stack compatibility decorator to a plain\n    Python function.\n\n    See the example in :ref:`namespaces_python_modules`."
  },
  {
    "code": "def ic_pos(self, row1, row2=None):\n        if row2 is None:\n            row2 = [0.25,0.25,0.25,0.25]\n        score = 0\n        for a,b in zip(row1, row2):\n            if a > 0:\n                score += a * log(a / b) / log(2)\n        return score",
    "docstring": "Calculate the information content of one position.\n\n        Returns\n        -------\n        score : float\n            Information content."
  },
  {
    "code": "def get_app_state(device_id, app_id):\n    if not is_valid_app_id(app_id):\n        abort(403)\n    if not is_valid_device_id(device_id):\n        abort(403)\n    if device_id not in devices:\n        abort(404)\n    app_state = devices[device_id].app_state(app_id)\n    return jsonify(state=app_state, status=app_state)",
    "docstring": "Get the state of the requested app"
  },
  {
    "code": "def strip_non_ascii(s):\n    stripped = (c for c in s if 0 < ord(c) < 127)\n    clean_string = u''.join(stripped)\n    return clean_string",
    "docstring": "Returns the string without non-ASCII characters.\n\n    Parameters\n    ----------\n    string : string\n        A string that may contain non-ASCII characters.\n\n    Returns\n    -------\n    clean_string : string\n        A string that does not contain non-ASCII characters."
  },
  {
    "code": "def get_app():\n    from bottle import default_app\n    default_app.push()\n    for module in (\"mongo_orchestration.apps.servers\",\n                   \"mongo_orchestration.apps.replica_sets\",\n                   \"mongo_orchestration.apps.sharded_clusters\"):\n        __import__(module)\n    app = default_app.pop()\n    return app",
    "docstring": "return bottle app that includes all sub-apps"
  },
  {
    "code": "def get_event_string(self, evtype, code):\n        if WIN and evtype == 'Key':\n            try:\n                code = self.codes['wincodes'][code]\n            except KeyError:\n                pass\n        try:\n            return self.codes[evtype][code]\n        except KeyError:\n            raise UnknownEventCode(\"We don't know this event.\", evtype, code)",
    "docstring": "Get the string name of the event."
  },
  {
    "code": "def parse(self, requires_cfg=True):\n        self._parse_default()\n        self._parse_config(requires_cfg)\n        self._parse_env()",
    "docstring": "Parse the configuration sources into `Bison`.\n\n        Args:\n            requires_cfg (bool): Specify whether or not parsing should fail\n                if a config file is not found. (default: True)"
  },
  {
    "code": "def num_fails(self):\n        n = len(self.failed_phase_list)\n        if self.phase_stack[-1].status in (SolverStatus.failed, SolverStatus.cyclic):\n            n += 1\n        return n",
    "docstring": "Return the number of failed solve steps that have been executed.\n        Note that num_solves is inclusive of failures."
  },
  {
    "code": "def download(self):\n        return self._client.download_object(\n            self._instance, self._bucket, self.name)",
    "docstring": "Download this object."
  },
  {
    "code": "def getActiveSegment(self, c, i, timeStep):\n    nSegments = len(self.cells[c][i])\n    bestActivation = self.activationThreshold\n    which = -1\n    for j,s in enumerate(self.cells[c][i]):\n      activity = self.getSegmentActivityLevel(s, self.activeState[timeStep], connectedSynapsesOnly = True)\n      if activity >= bestActivation:\n        bestActivation = activity\n        which = j\n    if which != -1:\n      return self.cells[c][i][which]\n    else:\n      return None",
    "docstring": "For a given cell, return the segment with the strongest _connected_\n    activation, i.e. sum up the activations of the connected synapses of the\n    segments only. That is, a segment is active only if it has enough connected\n    synapses."
  },
  {
    "code": "def replace(self, new):\n        assert self.parent is not None, str(self)\n        assert new is not None\n        if not isinstance(new, list):\n            new = [new]\n        l_children = []\n        found = False\n        for ch in self.parent.children:\n            if ch is self:\n                assert not found, (self.parent.children, self, new)\n                if new is not None:\n                    l_children.extend(new)\n                found = True\n            else:\n                l_children.append(ch)\n        assert found, (self.children, self, new)\n        self.parent.changed()\n        self.parent.children = l_children\n        for x in new:\n            x.parent = self.parent\n        self.parent = None",
    "docstring": "Replace this node with a new one in the parent."
  },
  {
    "code": "def block_offset_bounds(self, namespace):\n        cursor = self.cursor\n        cursor.execute('SELECT MIN(\"offset\"), MAX(\"offset\") '\n                       'FROM gauged_statistics WHERE namespace = %s',\n                       (namespace,))\n        return cursor.fetchone()",
    "docstring": "Get the minimum and maximum block offset for the specified\n        namespace"
  },
  {
    "code": "def PostRegistration(method):\n    if not isinstance(method, types.FunctionType):\n        raise TypeError(\"@PostRegistration can only be applied on functions\")\n    validate_method_arity(method, \"service_reference\")\n    _append_object_entry(\n        method,\n        constants.IPOPO_METHOD_CALLBACKS,\n        constants.IPOPO_CALLBACK_POST_REGISTRATION,\n    )\n    return method",
    "docstring": "The service post-registration callback decorator is called after a service\n    of the component has been registered to the framework.\n\n    The decorated method must accept the\n    :class:`~pelix.framework.ServiceReference` of the registered\n    service as argument::\n\n       @PostRegistration\n       def callback_method(self, service_reference):\n           '''\n           service_reference: The ServiceReference of the provided service\n           '''\n           # ...\n\n    :param method: The decorated method\n    :raise TypeError: The decorated element is not a valid function"
  },
  {
    "code": "def _prepare_statement(sql_statement, parameters):\n        placehoolders = RdbmsConnection._get_placeholders(sql_statement, parameters)\n        for (variable_name, (variable_type, variable_value)) in placehoolders.iteritems():\n            if isinstance(variable_value, (list, set, tuple)):\n                sql_statement = RdbmsConnection._replace_placeholder(sql_statement,\n                        (variable_name, variable_type, variable_value))\n                del parameters[variable_name]\n        return sql_statement",
    "docstring": "Prepare the specified SQL statement, replacing the placeholders by the\n        value of the given parameters\n\n        @param sql_statement: the string expression of a SQL statement.\n\n        @param parameters: a dictionary of parameters where the key represents\n            the name of a parameter and the value represents the value of this\n            parameter to replace in each placeholder of this parameter in the\n            SQL statement.\n\n\n        @return: a string representation of the SQL statement where the\n            placehodlers have been replaced by the value of the corresponding\n            variables, depending on the type of these variables."
  },
  {
    "code": "def rsync_upload():\n    excludes = [\"*.pyc\", \"*.pyo\", \"*.db\", \".DS_Store\", \".coverage\",\n                \"local_settings.py\", \"/static\", \"/.git\", \"/.hg\"]\n    local_dir = os.getcwd() + os.sep\n    return rsync_project(remote_dir=env.proj_path, local_dir=local_dir,\n                         exclude=excludes)",
    "docstring": "Uploads the project with rsync excluding some files and folders."
  },
  {
    "code": "def _dasd_reverse_conversion(cls, val, **kwargs):\n        if val is not None:\n            if val.upper() == 'ADMINISTRATORS':\n                return '0'\n            elif val.upper() == 'ADMINISTRATORS AND POWER USERS':\n                return '1'\n            elif val.upper() == 'ADMINISTRATORS AND INTERACTIVE USERS':\n                return '2'\n            elif val.upper() == 'NOT DEFINED':\n                return '9999'\n            else:\n                return 'Invalid Value'\n        else:\n            return 'Not Defined'",
    "docstring": "converts DASD String values to the reg_sz value"
  },
  {
    "code": "def add_general_report_optgroup(parser):\n    g = parser.add_argument_group(\"Reporting Options\")\n    g.add_argument(\"--report-dir\", action=\"store\", default=None)\n    g.add_argument(\"--report\", action=_opt_cb_report,\n                   help=\"comma-separated list of report formats\")",
    "docstring": "General Reporting Options"
  },
  {
    "code": "def file_list(self, load):\n        if 'env' in load:\n            load.pop('env')\n        ret = set()\n        if 'saltenv' not in load:\n            return []\n        if not isinstance(load['saltenv'], six.string_types):\n            load['saltenv'] = six.text_type(load['saltenv'])\n        for fsb in self.backends(load.pop('fsbackend', None)):\n            fstr = '{0}.file_list'.format(fsb)\n            if fstr in self.servers:\n                ret.update(self.servers[fstr](load))\n        prefix = load.get('prefix', '').strip('/')\n        if prefix != '':\n            ret = [f for f in ret if f.startswith(prefix)]\n        return sorted(ret)",
    "docstring": "Return a list of files from the dominant environment"
  },
  {
    "code": "def syscall_from_number(self, number, allow_unsupported=True, abi=None):\n        abilist = self.syscall_abis if abi is None else [abi]\n        if self.syscall_library is None:\n            if not allow_unsupported:\n                raise AngrUnsupportedSyscallError(\"%s does not have a library of syscalls implemented\" % self.name)\n            proc = P['stubs']['syscall']()\n        elif not allow_unsupported and not self.syscall_library.has_implementation(number, self.arch, abilist):\n            raise AngrUnsupportedSyscallError(\"No implementation for syscall %d\" % number)\n        else:\n            proc = self.syscall_library.get(number, self.arch, abilist)\n        if proc.abi is not None:\n            baseno, minno, _ = self.syscall_abis[proc.abi]\n            mapno = number - minno + baseno\n        else:\n            mapno = self.unknown_syscall_number\n        proc.addr = mapno * self.syscall_addr_alignment + self.kernel_base\n        return proc",
    "docstring": "Get a syscall SimProcedure from its number.\n\n        :param number:              The syscall number\n        :param allow_unsupported:   Whether to return a \"stub\" syscall for unsupported numbers instead of throwing an error\n        :param abi:                 The name of the abi to use. If None, will assume that the abis have disjoint\n                                    numbering schemes and pick the right one.\n        :return: The SimProcedure for the syscall"
  },
  {
    "code": "def on_batch_end(self, train, **kwargs:Any)->None:\n        \"Take one step forward on the annealing schedule for the optim params.\"\n        if train:\n            if self.idx_s >= len(self.lr_scheds): return {'stop_training': True, 'stop_epoch': True}\n            self.opt.lr = self.lr_scheds[self.idx_s].step()\n            self.opt.mom = self.mom_scheds[self.idx_s].step()\n            if self.lr_scheds[self.idx_s].is_done:\n                self.idx_s += 1",
    "docstring": "Take one step forward on the annealing schedule for the optim params."
  },
  {
    "code": "def field_value(key, label, color, padding):\n    if not clr.has_colors and padding > 0:\n        padding = 7\n    if color == \"bright gray\" or color == \"dark gray\":\n        bright_prefix = \"\"\n    else:\n        bright_prefix = \"bright \"\n    field = clr.stringc(key, \"{0}{1}\".format(bright_prefix, color))\n    field_label = clr.stringc(label, color)\n    return \"{0:>{1}} {2}\".format(field, padding, field_label)",
    "docstring": "Print a specific field's stats."
  },
  {
    "code": "def sys_version(version_tuple):\n    old_version = sys.version_info\n    sys.version_info = version_tuple\n    yield\n    sys.version_info = old_version",
    "docstring": "Set a temporary sys.version_info tuple\n\n    :param version_tuple: a fake sys.version_info tuple"
  },
  {
    "code": "def _GenerateSection(self, problem_type):\n    if problem_type == transitfeed.TYPE_WARNING:\n      dataset_problems = self._dataset_warnings\n      heading = 'Warnings'\n    else:\n      dataset_problems = self._dataset_errors\n      heading = 'Errors'\n    if not dataset_problems:\n      return ''\n    prefix = '<h2 class=\"issueHeader\">%s:</h2>' % heading\n    dataset_sections = []\n    for dataset_merger, problems in dataset_problems.items():\n      dataset_sections.append('<h3>%s</h3><ol>%s</ol>' % (\n          dataset_merger.FILE_NAME, '\\n'.join(problems)))\n    body = '\\n'.join(dataset_sections)\n    return prefix + body",
    "docstring": "Generate a listing of the given type of problems.\n\n    Args:\n      problem_type: The type of problem. This is one of the problem type\n                    constants from transitfeed.\n\n    Returns:\n      The generated HTML as a string."
  },
  {
    "code": "def is_link_inline(cls, tag, attribute):\n        if tag in cls.TAG_ATTRIBUTES \\\n           and attribute in cls.TAG_ATTRIBUTES[tag]:\n            attr_flags = cls.TAG_ATTRIBUTES[tag][attribute]\n            return attr_flags & cls.ATTR_INLINE\n        return attribute != 'href'",
    "docstring": "Return whether the link is likely to be inline object."
  },
  {
    "code": "def infer_doy_max(arr):\n    cal = arr.time.encoding.get('calendar', None)\n    if cal in calendars:\n        doy_max = calendars[cal]\n    else:\n        doy_max = arr.time.dt.dayofyear.max().data\n        if len(arr.time) < 360:\n            raise ValueError(\"Cannot infer the calendar from a series less than a year long.\")\n        if doy_max not in [360, 365, 366]:\n            raise ValueError(\"The target array's calendar is not recognized\")\n    return doy_max",
    "docstring": "Return the largest doy allowed by calendar.\n\n    Parameters\n    ----------\n    arr : xarray.DataArray\n      Array with `time` coordinate.\n\n    Returns\n    -------\n    int\n      The largest day of the year found in calendar."
  },
  {
    "code": "def manager(self, value):\n        \"Set the manager object in the global _managers dict.\"\n        pid = current_process().ident\n        if _managers is None:\n            raise RuntimeError(\"Can not set the manager following a system exit.\")\n        if pid not in _managers:\n            _managers[pid] = value\n        else:\n            raise Exception(\"Manager already set for pid %s\" % pid)",
    "docstring": "Set the manager object in the global _managers dict."
  },
  {
    "code": "def read_json(self, xblock):\n        self._warn_deprecated_outside_JSONField()\n        return self.to_json(self.read_from(xblock))",
    "docstring": "Retrieve the serialized value for this field from the specified xblock"
  },
  {
    "code": "def privmsg_many(self, targets, text):\n        target = ','.join(targets)\n        return self.privmsg(target, text)",
    "docstring": "Send a PRIVMSG command to multiple targets."
  },
  {
    "code": "def ncores_allocated(self):\n        return sum(task.manager.num_cores for task in self if task.status in [task.S_SUB, task.S_RUN])",
    "docstring": "Returns the number of CPUs allocated in this moment.\n        A core is allocated if it's running a task or if we have\n        submitted a task to the queue manager but the job is still pending."
  },
  {
    "code": "def search(self, query, pagination, result_field):\n        result = []\n        url = \"/\".join((self.url, query))\n        while url:\n            log.debug(\"Pagure query: {0}\".format(url))\n            try:\n                response = requests.get(url, headers=self.headers)\n                log.data(\"Response headers:\\n{0}\".format(response.headers))\n            except requests.RequestException as error:\n                log.error(error)\n                raise ReportError(\"Pagure search {0} failed.\".format(self.url))\n            data = response.json()\n            objects = data[result_field]\n            log.debug(\"Result: {0} fetched\".format(\n                listed(len(objects), \"item\")))\n            log.data(pretty(data))\n            if not objects:\n                break\n            result.extend(objects)\n            url = data[pagination]['next']\n        return result",
    "docstring": "Perform Pagure query"
  },
  {
    "code": "def get_requires():\n    requirements = open(\"requirements.txt\", \"r\").read()\n    return list(filter(lambda x: x != \"\", requirements.split()))",
    "docstring": "Read requirements.txt."
  },
  {
    "code": "def is_image(file):\n    match = re.match(r'\\.(png|jpe?g)', _get_extension(file), re.IGNORECASE)\n    if match:\n        return True\n    else:\n        return isinstance(resolve_bot_file_id(file), types.Photo)",
    "docstring": "Returns ``True`` if the file extension looks like an image file to Telegram."
  },
  {
    "code": "def profile_list(default_only=False):\n    profiles = {}\n    default_profiles = ['All']\n    with salt.utils.files.fopen('/etc/security/policy.conf', 'r') as policy_conf:\n        for policy in policy_conf:\n            policy = salt.utils.stringutils.to_unicode(policy)\n            policy = policy.split('=')\n            if policy[0].strip() == 'PROFS_GRANTED':\n                default_profiles.extend(policy[1].strip().split(','))\n    with salt.utils.files.fopen('/etc/security/prof_attr', 'r') as prof_attr:\n        for profile in prof_attr:\n            profile = salt.utils.stringutils.to_unicode(profile)\n            profile = profile.split(':')\n            if len(profile) != 5:\n                continue\n            profiles[profile[0]] = profile[3]\n    if default_only:\n        for p in [p for p in profiles if p not in default_profiles]:\n            del profiles[p]\n    return profiles",
    "docstring": "List all available profiles\n\n    default_only : boolean\n        return only default profile\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rbac.profile_list"
  },
  {
    "code": "def connect(self, receiver):\n        if not callable(receiver):\n            raise ValueError('Invalid receiver: %s' % receiver)\n        self.receivers.append(receiver)",
    "docstring": "Append receiver."
  },
  {
    "code": "def compute_grouped_sigma(ungrouped_sigma, group_matrix):\n    group_matrix = np.array(group_matrix, dtype=np.bool)\n    sigma_masked = np.ma.masked_array(ungrouped_sigma * group_matrix.T,\n                                      mask=(group_matrix ^ 1).T)\n    sigma_agg = np.ma.mean(sigma_masked, axis=1)\n    sigma = np.zeros(group_matrix.shape[1], dtype=np.float)\n    np.copyto(sigma, sigma_agg, where=group_matrix.sum(axis=0) == 1)\n    np.copyto(sigma, np.NAN, where=group_matrix.sum(axis=0) != 1)\n    return sigma",
    "docstring": "Returns sigma for the groups of parameter values in the\n    argument ungrouped_metric where the group consists of no more than\n    one parameter"
  },
  {
    "code": "def version_info(self):\r\n        package = pkg.get_distribution('git-up')\r\n        local_version_str = package.version\r\n        local_version = package.parsed_version\r\n        print('GitUp version is: ' + colored('v' + local_version_str, 'green'))\r\n        if not self.settings['updates.check']:\r\n            return\r\n        print('Checking for updates...', end='')\r\n        try:\r\n            reader = codecs.getreader('utf-8')\r\n            details = json.load(reader(urlopen(PYPI_URL)))\r\n            online_version = details['info']['version']\r\n        except (HTTPError, URLError, ValueError):\r\n            recent = True\n        else:\r\n            recent = local_version >= pkg.parse_version(online_version)\r\n        if not recent:\r\n            print(\r\n                '\\rRecent version is: '\r\n                + colored('v' + online_version, color='yellow', attrs=['bold'])\r\n            )\r\n            print('Run \\'pip install -U git-up\\' to get the update.')\r\n        else:\r\n            sys.stdout.write('\\r' + ' ' * 80 + '\\n')",
    "docstring": "Tell, what version we're running at and if it's up to date."
  },
  {
    "code": "def create_environment(self, **kwargs):\n        environment = super().create_environment(**kwargs)\n        environment.tests.update({\n            'type': self.test_type,\n            'kind': self.test_kind,\n            'opposite_before_self': self.test_opposite_before_self,\n        })\n        environment.filters.update({\n            'docstringline': self.filter_docstringline,\n            'pyquotesingle': self.filter_pyquotesingle,\n            'derivedname': self.filter_derived_name,\n            'refqualifiers': self.filter_refqualifiers,\n            'attrqualifiers': self.filter_attrqualifiers,\n            'supertypes': self.filter_supertypes,\n            'all_contents': self.filter_all_contents,\n            'pyfqn': self.filter_pyfqn,\n            're_sub': lambda v, p, r: re.sub(p, r, v),\n            'set': self.filter_set,\n        })\n        from pyecore import ecore\n        environment.globals.update({'ecore': ecore})\n        return environment",
    "docstring": "Return a new Jinja environment.\n\n        Derived classes may override method to pass additional parameters or to change the template\n        loader type."
  },
  {
    "code": "def files_type(fs0, fs1, files):\n    for file_meta in files['deleted_files']:\n        file_meta['type'] = fs0.file(file_meta['path'])\n    for file_meta in files['created_files'] + files['modified_files']:\n        file_meta['type'] = fs1.file(file_meta['path'])\n    return files",
    "docstring": "Inspects the file type of the given files."
  },
  {
    "code": "def supports_gzip(self, context):\n        if 'request' in context and client.supports_gzip():\n            enc = context['request'].META.get('HTTP_ACCEPT_ENCODING', '')\n            return 'gzip' in enc and msettings['SERVE_REMOTE']\n        return False",
    "docstring": "Looks at the RequestContext object and determines if the client\n        supports gzip encoded content. If the client does, we will send them\n        to the gzipped version of files that are allowed to be compressed.\n        Clients without gzip support will be served the original media."
  },
  {
    "code": "def is_user_attempt_whitelisted(request: AxesHttpRequest, credentials: dict = None) -> bool:\n    username_field = getattr(get_user_model(), 'USERNAME_FIELD', 'username')\n    username_value = get_client_username(request, credentials)\n    kwargs = {\n        username_field: username_value\n    }\n    user_model = get_user_model()\n    try:\n        user = user_model.objects.get(**kwargs)\n        return user.nolockout\n    except (user_model.DoesNotExist, AttributeError):\n        pass\n    return False",
    "docstring": "Check if the given request or credentials refer to a whitelisted username.\n\n    A whitelisted user has the magic ``nolockout`` property set.\n\n    If the property is unknown or False or the user can not be found,\n    this implementation fails gracefully and returns True."
  },
  {
    "code": "def get_handler(self, grant_type):\n        if grant_type == 'authorization_code':\n            return self.authorization_code\n        elif grant_type == 'refresh_token':\n            return self.refresh_token\n        elif grant_type == 'password':\n            return self.password\n        return None",
    "docstring": "Return a function or method that is capable handling the ``grant_type``\n        requested by the client or return ``None`` to indicate that this type\n        of grant type is not supported, resulting in an error response."
  },
  {
    "code": "def unzip_file(self, zip_path, output_path):\n        with zipfile.ZipFile(zip_path, 'r') as z:\n            z.extractall(output_path)",
    "docstring": "Unzip a local file into a specified directory."
  },
  {
    "code": "def get_parent_of_type(typ, obj):\n    if type(typ) is not text:\n        typ = typ.__name__\n    while hasattr(obj, 'parent'):\n        obj = obj.parent\n        if obj.__class__.__name__ == typ:\n            return obj",
    "docstring": "Finds first object up the parent chain of the given type.\n    If no parent of the given type exists None is returned.\n\n    Args:\n        typ(str or python class): The type of the model object we are\n            looking for.\n        obj (model object): Python model object which is the start of the\n            search process."
  },
  {
    "code": "def dropEvent(self, event):\r\n        if (event.mimeData().hasFormat(\"text/plain\")):\r\n            text = to_text_string(event.mimeData().text())\r\n            if self.new_input_line:\r\n                self.on_new_line()\r\n            self.insert_text(text, at_end=True)\r\n            self.setFocus()\r\n            event.setDropAction(Qt.MoveAction)\r\n            event.accept()\r\n        else:\r\n            event.ignore()",
    "docstring": "Drag and Drop - Drop event"
  },
  {
    "code": "def filter_paths(d, paths, list_of_dicts=False, deepcopy=True):\n    list_of_dicts = '__list__' if list_of_dicts else None\n    all_keys = [x for y in paths if isinstance(y, tuple) for x in y]\n    all_keys += [x for x in paths if not isinstance(x, tuple)]\n    new_d = filter_keys(d, all_keys, list_of_dicts=list_of_dicts)\n    new_d = flatten(d, list_of_dicts=list_of_dicts)\n    for key in list(new_d.keys()):\n        if not any([\n                set(key).issuperset(path if isinstance(path, tuple) else[path])\n                for path in paths]):\n            new_d.pop(key)\n    return unflatten(new_d, list_of_dicts=list_of_dicts, deepcopy=deepcopy)",
    "docstring": "filter dict by certain paths containing key sets\n\n    Parameters\n    ----------\n    d : dict\n    paths : list[str] or list[tuple]\n    list_of_dicts: bool\n        treat list of dicts as additional branches\n    deepcopy: bool\n        deepcopy values\n\n    Examples\n    --------\n\n    >>> from pprint import pprint\n    >>> d = {'a':{'b':1,'c':{'d':2}},'e':{'c':3}}\n    >>> filter_paths(d,[('c','d')])\n    {'a': {'c': {'d': 2}}}\n\n    >>> d2 = {'a':[{'b':1,'c':3},{'b':1,'c':2}]}\n    >>> pprint(filter_paths(d2,[\"b\"],list_of_dicts=False))\n    {}\n\n    >>> pprint(filter_paths(d2,[\"c\"],list_of_dicts=True))\n    {'a': [{'c': 3}, {'c': 2}]}"
  },
  {
    "code": "def iterate(self):\n        self.counter += 1\n        self.counter0 += 1\n        self.revcounter -= 1\n        self.revcounter0 -= 1\n        self.first = False\n        self.last = (self.revcounter0 == self.len_values - 1)",
    "docstring": "Updates values as if we had iterated over the for"
  },
  {
    "code": "def queue_size(self):\n        response = self._request(\"tasks/list\")\n        tasks = json.loads(response.content.decode('utf-8'))[\"tasks\"]\n        return len([t for t in tasks if t['status'] == 'pending'])",
    "docstring": "Determine Cuckoo sandbox queue length\n\n        There isn't a built in way to do this like with Joe\n\n        :rtype:  int\n        :return: Number of submissions in sandbox queue."
  },
  {
    "code": "def find_peaks(dt, r_max=4, footprint=None):\n    r\n    im = dt > 0\n    if im.ndim != im.squeeze().ndim:\n        warnings.warn('Input image conains a singleton axis:' + str(im.shape) +\n                      ' Reduce dimensionality with np.squeeze(im) to avoid' +\n                      ' unexpected behavior.')\n    if footprint is None:\n        if im.ndim == 2:\n            footprint = disk\n        elif im.ndim == 3:\n            footprint = ball\n        else:\n            raise Exception(\"only 2-d and 3-d images are supported\")\n    mx = spim.maximum_filter(dt + 2*(~im), footprint=footprint(r_max))\n    peaks = (dt == mx)*im\n    return peaks",
    "docstring": "r\"\"\"\n    Returns all local maxima in the distance transform\n\n    Parameters\n    ----------\n    dt : ND-array\n        The distance transform of the pore space.  This may be calculated and\n        filtered using any means desired.\n\n    r_max : scalar\n        The size of the structuring element used in the maximum filter.  This\n        controls the localness of any maxima. The default is 4 voxels.\n\n    footprint : ND-array\n        Specifies the shape of the structuring element used to define the\n        neighborhood when looking for peaks.  If none is specified then a\n        spherical shape is used (or circular in 2D).\n\n    Returns\n    -------\n    image : ND-array\n        An array of booleans with ``True`` values at the location of any\n        local maxima.\n\n    Notes\n    -----\n    It is also possible ot the ``peak_local_max`` function from the\n    ``skimage.feature`` module as follows:\n\n    ``peaks = peak_local_max(image=dt, min_distance=r, exclude_border=0,\n    indices=False)``\n\n    This automatically uses a square structuring element which is significantly\n    faster than using a circular or spherical element."
  },
  {
    "code": "def ordered_expected_layers(self):\n        registry = QgsProject.instance()\n        layers = []\n        count = self.list_layers_in_map_report.count()\n        for i in range(count):\n            layer = self.list_layers_in_map_report.item(i)\n            origin = layer.data(LAYER_ORIGIN_ROLE)\n            if origin == FROM_ANALYSIS['key']:\n                key = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE)\n                parent = layer.data(LAYER_PARENT_ANALYSIS_ROLE)\n                layers.append((\n                    FROM_ANALYSIS['key'],\n                    key,\n                    parent,\n                    None\n                ))\n            else:\n                layer_id = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE)\n                layer = registry.mapLayer(layer_id)\n                style_document = QDomDocument()\n                layer.exportNamedStyle(style_document)\n                layers.append((\n                    FROM_CANVAS['key'],\n                    layer.name(),\n                    full_layer_uri(layer),\n                    style_document.toString()\n                ))\n        return layers",
    "docstring": "Get an ordered list of layers according to users input.\n\n        From top to bottom in the legend:\n        [\n            ('FromCanvas', layer name, full layer URI, QML),\n            ('FromAnalysis', layer purpose, layer group, None),\n            ...\n        ]\n\n        The full layer URI is coming from our helper.\n\n        :return: An ordered list of layers following a structure.\n        :rtype: list"
  },
  {
    "code": "def deactivate_user(self, user):\n        if user.active:\n            user.active = False\n            return True\n        return False",
    "docstring": "Deactivates a specified user. Returns `True` if a change was made.\n\n        :param user: The user to deactivate"
  },
  {
    "code": "def get_list(value):\n    if value is None:\n        return []\n    elif value is NotSet:\n        return NotSet\n    elif isinstance(value, (list, tuple)):\n        return list(value)\n    elif isinstance(value, six.string_types + (lazy_type, )) or uses_type_registry(value):\n        return [value]\n    raise ValueError(\"Invalid type; expected a list, tuple, or string type, found {0}.\".format(\n        type(value).__name__))",
    "docstring": "Wraps the given value in a list. ``None`` returns an empty list. Lists and tuples are returned as lists. Single\n    strings and registered types are wrapped in a list.\n\n    :param value: Value to return as a list.\n    :return: List with the provided value(s).\n    :rtype: list"
  },
  {
    "code": "def childDataReceived(self, childFD, data):\n        protocol = getattr(self, 'protocol', None)\n        if protocol:\n            protocol.dataReceived(data)\n        else:\n            self.data.append((childFD, data))",
    "docstring": "Relay data received on any file descriptor to the process"
  },
  {
    "code": "async def endorsements(self, root):\n        text = root.find('ENDORSEMENTS').text\n        return [Nation(name) for name in text.split(',')] if text else []",
    "docstring": "Regional neighbours endorsing the nation.\n\n        Returns\n        -------\n        an :class:`ApiQuery` of a list of :class:`Nation`"
  },
  {
    "code": "def read_geo(fid, key):\n    dsid = GEO_NAMES[key.name]\n    add_epoch = False\n    if \"time\" in key.name:\n        days = fid[\"/L1C/\" + dsid[\"day\"]].value\n        msecs = fid[\"/L1C/\" + dsid[\"msec\"]].value\n        data = _form_datetimes(days, msecs)\n        add_epoch = True\n        dtype = np.float64\n    else:\n        data = fid[\"/L1C/\" + dsid].value\n        dtype = np.float32\n    data = xr.DataArray(da.from_array(data, chunks=CHUNK_SIZE),\n                        name=key.name, dims=['y', 'x']).astype(dtype)\n    if add_epoch:\n        data.attrs['sensing_time_epoch'] = EPOCH\n    return data",
    "docstring": "Read geolocation and related datasets."
  },
  {
    "code": "def fetch_page(self, title, method='GET'):\n        params = { 'prop': 'revisions',\n                   'format': 'json',\n                   'action': 'query',\n                   'explaintext': '',\n                   'titles': title,\n                   'rvprop': 'content' }\n        r = self.request(method, self.base_url, params=params)\n        r.raise_for_status()\n        pages = r.json()[\"query\"][\"pages\"]\n        pageid = list(pages.keys())[0]\n        if pageid == '-1':\n            raise ArticleNotFound('no matching articles returned')\n        return pages[pageid]",
    "docstring": "Query for page by title"
  },
  {
    "code": "def dist(self, x1, x2):\n        if self.exponent == 2.0:\n            return float(np.sqrt(self.const) * _norm_default(x1 - x2))\n        elif self.exponent == float('inf'):\n            return float(self.const * _pnorm_default(x1 - x2, self.exponent))\n        else:\n            return float((self.const ** (1 / self.exponent) *\n                          _pnorm_default(x1 - x2, self.exponent)))",
    "docstring": "Return the weighted distance between ``x1`` and ``x2``.\n\n        Parameters\n        ----------\n        x1, x2 : `NumpyTensor`\n            Tensors whose mutual distance is calculated.\n\n        Returns\n        -------\n        dist : float\n            The distance between the tensors."
  },
  {
    "code": "def hash(filename, algorithm='sha256'):\n    if incompatible:\n        raise Incompatible\n    if algorithm not in ['sha256', 'sha384', 'sha512']:\n        raise InvalidArguments('Algorithm {} not supported'.format(algorithm))\n    result = call('hash', '--algorithm', algorithm, filename)\n    return result.strip().split(':')[-1]",
    "docstring": "Hash the given filename. Unavailable in `pip<8.0.0`"
  },
  {
    "code": "def report_issue(self, body=None, title=None, open_webpage=False):\r\n        if body is None:\r\n            from spyder.widgets.reporterror import SpyderErrorDialog\r\n            report_dlg = SpyderErrorDialog(self, is_report=True)\r\n            report_dlg.show()\r\n        else:\r\n            if open_webpage:\r\n                if PY3:\r\n                    from urllib.parse import quote\r\n                else:\r\n                    from urllib import quote\n                from qtpy.QtCore import QUrlQuery\r\n                url = QUrl(__project_url__ + '/issues/new')\r\n                query = QUrlQuery()\r\n                query.addQueryItem(\"body\", quote(body))\r\n                if title:\r\n                    query.addQueryItem(\"title\", quote(title))\r\n                url.setQuery(query)\r\n                QDesktopServices.openUrl(url)",
    "docstring": "Report a Spyder issue to github, generating body text if needed."
  },
  {
    "code": "def get_match_history_by_sequence_num(start_at_match_seq_num,\n                                      matches_requested=None, **kwargs):\n    params = {\n        \"start_at_match_seq_num\": start_at_match_seq_num,\n        \"matches_requested\": matches_requested\n    }\n    return make_request(\"GetMatchHistoryBySequenceNum\", params,\n        **kwargs)",
    "docstring": "Most recent matches ordered by sequence number"
  },
  {
    "code": "def __get_job_status(self):\n        job = self.__get_job()\n        if \"succeeded\" in job.obj[\"status\"] and job.obj[\"status\"][\"succeeded\"] > 0:\n            job.scale(replicas=0)\n            if self.print_pod_logs_on_exit:\n                self.__print_pod_logs()\n            if self.delete_on_success:\n                self.__delete_job_cascade(job)\n            return \"SUCCEEDED\"\n        if \"failed\" in job.obj[\"status\"]:\n            failed_cnt = job.obj[\"status\"][\"failed\"]\n            self.__logger.debug(\"Kubernetes job \" + self.uu_name\n                                + \" status.failed: \" + str(failed_cnt))\n            if self.print_pod_logs_on_exit:\n                self.__print_pod_logs()\n            if failed_cnt > self.max_retrials:\n                job.scale(replicas=0)\n                return \"FAILED\"\n        return \"RUNNING\"",
    "docstring": "Return the Kubernetes job status"
  },
  {
    "code": "def get_info(self, key=None, Id=None) -> dict:\n        if key is not None:\n            Id = self[key].Id\n        return self.infos.get(Id,{})",
    "docstring": "Returns information associated with Id or list index"
  },
  {
    "code": "def flatten(list_of_lists):\n    flat_list = []\n    for sublist in list_of_lists:\n        if isinstance(sublist, string_types) or isinstance(sublist, int):\n            flat_list.append(sublist)\n        elif sublist is None:\n            continue\n        elif not isinstance(sublist, string_types) and len(sublist) == 1:\n            flat_list.append(sublist[0])\n        else:\n            flat_list.append(tuple(sublist))\n    return flat_list",
    "docstring": "Flatten a list of lists but maintain strings and ints as entries."
  },
  {
    "code": "def root(self):\n        node = self\n        while node.package is not None:\n            node = node.package\n        return node",
    "docstring": "Property to return the root of this node.\n\n        Returns:\n            Package: this node's root package."
  },
  {
    "code": "def serialize(self, content):\n        worker = JSONSerializer(\n            scheme=self.resource,\n            options=self.resource._meta.emit_options,\n            format=self.resource._meta.emit_format,\n            **self.resource._meta.emit_models\n        )\n        return worker.serialize(content)",
    "docstring": "Serialize to JSON.\n\n        :return string: serializaed JSON"
  },
  {
    "code": "def _get_logical(source_lines, result, logical_start, logical_end):\n    row = result['line'] - 1\n    col = result['column'] - 1\n    ls = None\n    le = None\n    for i in range(0, len(logical_start), 1):\n        assert logical_end\n        x = logical_end[i]\n        if x[0] > row or (x[0] == row and x[1] > col):\n            le = x\n            ls = logical_start[i]\n            break\n    if ls is None:\n        return None\n    original = source_lines[ls[0]:le[0] + 1]\n    return ls, le, original",
    "docstring": "Return the logical line corresponding to the result.\n\n    Assumes input is already E702-clean."
  },
  {
    "code": "def download(self, request, **kwargs):\n        self.method_check(request, allowed=['get'])\n        basic_bundle = self.build_bundle(request=request)\n        tileset = self.cached_obj_get(\n            bundle=basic_bundle,\n            **self.remove_api_resource_names(kwargs))\n        filename = helpers.get_tileset_filename(tileset)\n        filename = os.path.abspath(filename)\n        if os.path.isfile(filename):\n            response = serve(request, os.path.basename(filename), os.path.dirname(filename))\n            response['Content-Disposition'] = 'attachment; filename=\"{}\"'.format(os.path.basename(filename))\n        else:\n            response = self.create_response(request, {'status': 'not generated'})\n        return response",
    "docstring": "proxy for the helpers.tileset_download method"
  },
  {
    "code": "def _find(self, root, tagname, id=None):\n        if id is None:\n            result = root.find('.//%s' % tagname)\n            if result is None:\n                raise LookupError('Cannot find any %s elements' % tagname)\n            else:\n                return result\n        else:\n            result = [\n                elem for elem in root.findall('.//%s' % tagname)\n                if elem.attrib.get('id', '') == id\n            ]\n            if len(result) == 0:\n                raise LookupError('Cannot find a %s element with id %s' % (tagname, id))\n            elif len(result) > 1:\n                raise LookupError('Found multiple %s elements with id %s' % (tagname, id))\n            else:\n                return result[0]",
    "docstring": "Returns the first element with the specified tagname and id"
  },
  {
    "code": "def execute(self):\n        self.start_stemming_process()\n        if self.dictionary.contains(self.current_word):\n            self.result = self.current_word\n        else:\n            self.result = self.original_word",
    "docstring": "Execute stemming process; the result can be retrieved with result"
  },
  {
    "code": "def _pip_cmd(self, name=None, prefix=None):\n        if (name and prefix) or not (name or prefix):\n            raise TypeError(\"conda pip: exactly one of 'name' \"\"or 'prefix' \"\n                            \"required.\")\n        if name and self.environment_exists(name=name):\n            prefix = self.get_prefix_envname(name)\n        if sys.platform == 'win32':\n            python = join(prefix, 'python.exe')\n            pip = join(prefix, 'pip.exe')\n        else:\n            python = join(prefix, 'bin/python')\n            pip = join(prefix, 'bin/pip')\n        cmd_list = [python, pip]\n        return cmd_list",
    "docstring": "Get pip location based on environment `name` or `prefix`."
  },
  {
    "code": "def calinski_harabaz_score(X, labels):\n    X, labels = check_X_y(X, labels)\n    le = LabelEncoder()\n    labels = le.fit_transform(labels)\n    n_samples, _ = X.shape\n    n_labels = len(le.classes_)\n    check_number_of_labels(n_labels, n_samples)\n    extra_disp, intra_disp = 0., 0.\n    mean = np.mean(X, axis=0)\n    for k in range(n_labels):\n        cluster_k = X[labels == k]\n        mean_k = np.mean(cluster_k, axis=0)\n        extra_disp += len(cluster_k) * np.sum((mean_k - mean) ** 2)\n        intra_disp += np.sum((cluster_k - mean_k) ** 2)\n    return (1. if intra_disp == 0. else\n            extra_disp * (n_samples - n_labels) /\n            (intra_disp * (n_labels - 1.)))",
    "docstring": "Compute the Calinski and Harabaz score.\n\n    The score is defined as ratio between the within-cluster dispersion and\n    the between-cluster dispersion.\n\n    Read more in the :ref:`User Guide <calinski_harabaz_index>`.\n\n    Parameters\n    ----------\n    X : array-like, shape (``n_samples``, ``n_features``)\n        List of ``n_features``-dimensional data points. Each row corresponds\n        to a single data point.\n\n    labels : array-like, shape (``n_samples``,)\n        Predicted labels for each sample.\n\n    Returns\n    -------\n    score : float\n        The resulting Calinski-Harabaz score.\n\n    References\n    ----------\n    .. [1] `T. Calinski and J. Harabasz, 1974. \"A dendrite method for cluster\n       analysis\". Communications in Statistics\n       <http://www.tandfonline.com/doi/abs/10.1080/03610927408827101>`_"
  },
  {
    "code": "def split(self, point=None):\n    if point is None:\n      point = len(self) / 2\n    r1 = Sequence(self.name + \".1\", self.sequenceData[:point])\n    r2 = Sequence(self.name + \".2\", self.sequenceData[point:])\n    return r1, r2",
    "docstring": "Split this sequence into two halves and return them. The original\n      sequence remains unmodified.\n\n      :param point: defines the split point, if None then the centre is used\n      :return: two Sequence objects -- one for each side"
  },
  {
    "code": "def read_cz_lsm_info(fd, byte_order, dtype, count):\n    result = numpy.rec.fromfile(fd, CZ_LSM_INFO, 1,\n                                byteorder=byte_order)[0]\n    {50350412: '1.3', 67127628: '2.0'}[result.magic_number]\n    return result",
    "docstring": "Read CS_LSM_INFO tag from file and return as numpy.rec.array."
  },
  {
    "code": "def _redis_notifier(state):\n    tstamp = time.time()\n    state._tstamp = tstamp\n    conf = state.app.config\n    r = redis.client.StrictRedis()\n    r.publish(conf.get('WAFFLE_REDIS_CHANNEL', 'waffleconf'), tstamp)",
    "docstring": "Notify of configuration update through redis.\n\n    Arguments:\n        state (_WaffleState): Object that contains reference to app and its\n            configstore."
  },
  {
    "code": "def write(self,\n              x: int,\n              y: int,\n              text: str,\n              transposed_text: 'Optional[str]' = None):\n        entry = self.entries.get((x, y), _DiagramText('', ''))\n        self.entries[(x, y)] = _DiagramText(\n            entry.text + text,\n            entry.transposed_text + (transposed_text if transposed_text\n                                     else text))",
    "docstring": "Adds text to the given location.\n\n        Args:\n            x: The column in which to write the text.\n            y: The row in which to write the text.\n            text: The text to write at location (x, y).\n            transposed_text: Optional text to write instead, if the text\n                diagram is transposed."
  },
  {
    "code": "def version(self, value):\n        self.bytearray[self._get_slicers(1)] = bytearray(c_uint8(value or 0))",
    "docstring": "Version setter."
  },
  {
    "code": "def _full_diff(merge_result, key, context_lines=3):\n    header_printed = False\n    for group in _split_diff(merge_result, context_lines=context_lines):\n        if not header_printed:\n            header_printed = True\n            yield color.Header('diff a/%s b/%s' % (key, key))\n            yield color.DeletedHeader('--- %s' % key)\n            yield color.AddedHeader('+++ %s' % key)\n        for l in _diff_group(group):\n            yield l",
    "docstring": "Generate a full diff based on a Weave merge result"
  },
  {
    "code": "def _shorten_line_at_tokens_new(tokens, source, indentation,\n                                max_line_length):\n    yield indentation + source\n    parsed_tokens = _parse_tokens(tokens)\n    if parsed_tokens:\n        fixed = _reflow_lines(parsed_tokens, indentation, max_line_length,\n                              start_on_prefix_line=True)\n        if fixed and check_syntax(normalize_multiline(fixed.lstrip())):\n            yield fixed\n        fixed = _reflow_lines(parsed_tokens, indentation, max_line_length,\n                              start_on_prefix_line=False)\n        if fixed and check_syntax(normalize_multiline(fixed.lstrip())):\n            yield fixed",
    "docstring": "Shorten the line taking its length into account.\n\n    The input is expected to be free of newlines except for inside\n    multiline strings and at the end."
  },
  {
    "code": "def export_aliases(export_path=None, exclusions=None):\n    if not export_path:\n        export_path = os.path.abspath(ALIAS_FILE_NAME)\n    alias_table = get_alias_table()\n    for exclusion in exclusions or []:\n        if exclusion not in alias_table.sections():\n            raise CLIError(ALIAS_NOT_FOUND_ERROR.format(exclusion))\n        alias_table.remove_section(exclusion)\n    _commit_change(alias_table, export_path=export_path, post_commit=False)\n    logger.warning(POST_EXPORT_ALIAS_MSG, export_path)",
    "docstring": "Export all registered aliases to a given path, as an INI configuration file.\n\n    Args:\n        export_path: The path of the alias configuration file to export to.\n        exclusions: Space-separated aliases excluded from export."
  },
  {
    "code": "def delete(self, custom_field, params={}, **options): \n        path = \"/custom_fields/%s\" % (custom_field)\n        return self.client.delete(path, params, **options)",
    "docstring": "A specific, existing custom field can be deleted by making a DELETE request on the URL for that custom field.\n        \n        Returns an empty data record.\n\n        Parameters\n        ----------\n        custom_field : {Id} Globally unique identifier for the custom field."
  },
  {
    "code": "def append(self, obj):\n        if isinstance(obj, str):\n            obj = KQMLToken(obj)\n        self.data.append(obj)",
    "docstring": "Append an element to the end of the list.\n\n        Parameters\n        ----------\n        obj : KQMLObject or str\n            If a string is passed, it is instantiated as a\n            KQMLToken before being added to the list."
  },
  {
    "code": "def save(self):\n        if self.id:\n            method = 'put'\n            resource = self.RESOURCE.format(\n                account_id=self.account.id,\n                tailored_audience_id=self.tailored_audience_id,\n                id=self.id)\n        else:\n            method = 'post'\n            resource = self.RESOURCE_COLLECTION.format(\n                account_id=self.account.id,\n                tailored_audience_id=self.tailored_audience_id)\n        response = Request(\n            self.account.client, method,\n            resource, params=self.to_params()).perform()\n        return self.from_response(response.body['data'])",
    "docstring": "Saves or updates the current tailored audience permission."
  },
  {
    "code": "def skew_x(self, x):\n        self.root.set(\"transform\", \"%s skewX(%f)\" %\n                      (self.root.get(\"transform\") or '', x))\n        return self",
    "docstring": "Skew element along the x-axis by the given angle.\n\n        Parameters\n        ----------\n        x : float\n            x-axis skew angle in degrees"
  },
  {
    "code": "def disassemble_instruction(self, instruction):\n        if not util.is_integer(instruction):\n            raise TypeError('Expected instruction to be an integer.')\n        buf_size = self.MAX_BUF_SIZE\n        buf = (ctypes.c_char * buf_size)()\n        res = self._dll.JLINKARM_DisassembleInst(ctypes.byref(buf), buf_size, instruction)\n        if res < 0:\n            raise errors.JLinkException('Failed to disassemble instruction.')\n        return ctypes.string_at(buf).decode()",
    "docstring": "Disassembles and returns the assembly instruction string.\n\n        Args:\n          self (JLink): the ``JLink`` instance.\n          instruction (int): the instruction address.\n\n        Returns:\n          A string corresponding to the assembly instruction string at the\n          given instruction address.\n\n        Raises:\n          JLinkException: on error.\n          TypeError: if ``instruction`` is not a number."
  },
  {
    "code": "def split_demultiplexed_sampledata(data, demultiplexed):\n    datadicts = []\n    samplename = dd.get_sample_name(data)\n    for fastq in demultiplexed:\n        barcode = os.path.basename(fastq).split(\".\")[0]\n        datadict = copy.deepcopy(data)\n        datadict = dd.set_sample_name(datadict, samplename + \"-\" + barcode)\n        datadict = dd.set_description(datadict, samplename + \"-\" + barcode)\n        datadict[\"rgnames\"][\"rg\"] = samplename + \"-\" + barcode\n        datadict[\"name\"]= [\"\", samplename + \"-\" + barcode]\n        datadict[\"files\"] = [fastq]\n        datadicts.append(datadict)\n    return datadicts",
    "docstring": "splits demultiplexed samples into separate entries in the global sample\n    datadict"
  },
  {
    "code": "def printWelcomeMessage(msg, place=10):\n    logging.debug('*' * 30)\n    welcome = ' ' * place\n    welcome+= msg\n    logging.debug(welcome)\n    logging.debug('*' * 30 + '\\n')",
    "docstring": "Print any welcome message"
  },
  {
    "code": "def validate_path(path):\n        if not isinstance(path, six.string_types) or not re.match('^/(?:[._a-zA-Z0-9-]/?)+[^/]$', path):\n            raise InvalidUsage(\n                \"Path validation failed - Expected: '/<component>[/component], got: %s\" % path\n            )\n        return True",
    "docstring": "Validates the provided path\n\n        :param path: path to validate (string)\n        :raise:\n            :InvalidUsage: If validation fails."
  },
  {
    "code": "def get_first_mapping(cls):\n    from .models import Indexable\n    if issubclass(cls, Indexable) and hasattr(cls, \"Mapping\"):\n        return cls.Mapping\n    for base in cls.__bases__:\n        mapping = get_first_mapping(base)\n        if mapping:\n            return mapping\n    return None",
    "docstring": "This allows for Django-like inheritance of mapping configurations"
  },
  {
    "code": "def unfold_file(self, path):\n        yaml_config = self.file_index.unfold_yaml(path)\n        self.unfold_config(path, yaml_config)",
    "docstring": "Parse given file and add it to graph"
  },
  {
    "code": "def getTableCount(verbose=None):\n        response=api(url=self.url+'tables/count', method=\"GET\", verbose=verbose, parse_params=False)\n        return response",
    "docstring": "Returns the number of global tables.\n\n        :param verbose: print more\n\n        :returns: 200: successful operation"
  },
  {
    "code": "def get_string_width(self, s):\n        \"Get width of a string in the current font\"\n        s = self.normalize_text(s)\n        cw=self.current_font['cw']\n        w=0\n        l=len(s)\n        if self.unifontsubset:\n            for char in s:\n                char = ord(char)\n                if len(cw) > char:\n                    w += cw[char]\n                elif (self.current_font['desc']['MissingWidth']) :\n                    w += self.current_font['desc']['MissingWidth']\n                else:\n                    w += 500\n        else:\n            for i in range(0, l):\n                w += cw.get(s[i],0)\n        return w*self.font_size/1000.0",
    "docstring": "Get width of a string in the current font"
  },
  {
    "code": "def to_xml(node, pretty=False):\n    fout = Sio()\n    etree = et.ElementTree(node)\n    etree.write(fout)\n    xml = fout.getvalue()\n    if pretty:\n        xml = pretty_xml(xml, True)\n    return xml",
    "docstring": "convert an etree node to xml"
  },
  {
    "code": "def parse_header_part(self, data):\n        packet_length = data[0]\n        packet_type = data[1]\n        packet_subtype = data[2]\n        sequence_number = data[3]\n        return {\n            'packet_length': packet_length,\n            'packet_type': packet_type,\n            'packet_type_name': self.PACKET_TYPES.get(packet_type),\n            'packet_subtype': packet_subtype,\n            'packet_subtype_name': self.PACKET_SUBTYPES.get(packet_subtype),\n            'sequence_number': sequence_number\n        }",
    "docstring": "Extracts and converts the RFX common header part of all valid\n        packets to a plain dictionary. RFX header part is the 4 bytes prior\n        the sensor vendor specific data part.\n\n        The RFX common header part contains respectively:\n        - packet length\n        - packet type\n        - packet sub-type\n        - sequence number\n\n        :param data: bytearray of received data\n        :type data: bytearray"
  },
  {
    "code": "def parse_signature(cls, function):\n        annotations = function.__annotations__.copy()\n        del annotations['return']\n        result = []\n        for param_name, (param_type, param_obj) in annotations.items():\n            sig_param = function.signature.parameters[param_name]\n            param_description = {\n                'paramType': param_type,\n                'name': param_name,\n                'required': sig_param.default is inspect.Parameter.empty}\n            param_description.update(param_obj.describe())\n            result.append(param_description)\n        return result",
    "docstring": "Parses the signature of a method and its annotations to swagger.\n\n        Return a dictionary {arg_name: info}."
  },
  {
    "code": "def run_command(self, cmd, input_data=None):\n        kwargs = {\n            'stdout': subprocess.PIPE,\n            'stderr': subprocess.PIPE,\n        }\n        if input_data is not None:\n            kwargs['stdin'] = subprocess.PIPE\n        stdout = []\n        stderr = []\n        p = subprocess.Popen(cmd, **kwargs)\n        t1 = Thread(target=self._reader, args=('stdout', p.stdout, stdout))\n        t1.start()\n        t2 = Thread(target=self._reader, args=('stderr', p.stderr, stderr))\n        t2.start()\n        if input_data is not None:\n            p.stdin.write(input_data)\n            p.stdin.close()\n        p.wait()\n        t1.join()\n        t2.join()\n        return p.returncode, stdout, stderr",
    "docstring": "Run a command in a child process , passing it any input data specified.\n\n        :param cmd: The command to run.\n        :param input_data: If specified, this must be a byte string containing\n                           data to be sent to the child process.\n        :return: A tuple consisting of the subprocess' exit code, a list of\n                 lines read from the subprocess' ``stdout``, and a list of\n                 lines read from the subprocess' ``stderr``."
  },
  {
    "code": "def to_record(self):\n        tf_list = [getattr(self, k, None) for k in\n                   [_.value for _ in TLSFileType]]\n        tf_list = filter(lambda x: x, tf_list)\n        files = {tf.file_type.value: tf.file_path for tf in tf_list}\n        self.record['files'] = files\n        return self.record",
    "docstring": "Create a CertStore record from this TLSFileBundle"
  },
  {
    "code": "def overwrite_stage_variables(self, ret, stage_variables):\n        res = __salt__['boto_apigateway.overwrite_api_stage_variables'](restApiId=self.restApiId,\n                                                                        stageName=self._stage_name,\n                                                                        variables=stage_variables,\n                                                                        **self._common_aws_args)\n        if not res.get('overwrite'):\n            ret['result'] = False\n            ret['abort'] = True\n            ret['comment'] = res.get('error')\n        else:\n            ret = _log_changes(ret,\n                               'overwrite_stage_variables',\n                               res.get('stage'))\n        return ret",
    "docstring": "overwrite the given stage_name's stage variables with the given stage_variables"
  },
  {
    "code": "def only_on_master(function):\n    @wraps(function)\n    def inner_function(self, *args, **kwargs):\n        if not self.is_coordinator:\n            message = 'The method or property \"{0}\" can only be called/used '\\\n                'on the coordinator in a group'.format(function.__name__)\n            raise SoCoSlaveException(message)\n        return function(self, *args, **kwargs)\n    return inner_function",
    "docstring": "Decorator that raises SoCoSlaveException on master call on slave."
  },
  {
    "code": "def extract_metrics(self, metrics_files):\n        extension_maps = dict(\n            align_metrics=(self._parse_align_metrics, \"AL\"),\n            dup_metrics=(self._parse_dup_metrics, \"DUP\"),\n            hs_metrics=(self._parse_hybrid_metrics, \"HS\"),\n            insert_metrics=(self._parse_insert_metrics, \"INS\"),\n            rnaseq_metrics=(self._parse_rnaseq_metrics, \"RNA\"))\n        all_metrics = dict()\n        for fname in metrics_files:\n            ext = os.path.splitext(fname)[-1][1:]\n            try:\n                parse_fn, prefix = extension_maps[ext]\n            except KeyError:\n                parse_fn = None\n            if parse_fn:\n                with open(fname) as in_handle:\n                    for key, val in parse_fn(in_handle).items():\n                        if not key.startswith(prefix):\n                            key = \"%s_%s\" % (prefix, key)\n                        all_metrics[key] = val\n        return all_metrics",
    "docstring": "Return summary information for a lane of metrics files."
  },
  {
    "code": "def closer_than(self, mesh, radius):\n        dists = geodetic.distance(self.longitude, self.latitude, self.depth,\n                                  mesh.lons, mesh.lats,\n                                  0 if mesh.depths is None else mesh.depths)\n        return dists <= radius",
    "docstring": "Check for proximity of points in the ``mesh``.\n\n        :param mesh:\n            :class:`openquake.hazardlib.geo.mesh.Mesh` instance.\n        :param radius:\n            Proximity measure in km.\n        :returns:\n            Numpy array of boolean values in the same shape as the mesh\n            coordinate arrays with ``True`` on indexes of points that\n            are not further than ``radius`` km from this point. Function\n            :func:`~openquake.hazardlib.geo.geodetic.distance` is used to\n            calculate distances to points of the mesh. Points of the mesh that\n            lie exactly ``radius`` km away from this point also have\n            ``True`` in their indices."
  },
  {
    "code": "def addCallSetFromName(self, sampleName):\n        callSet = CallSet(self, sampleName)\n        self.addCallSet(callSet)",
    "docstring": "Adds a CallSet for the specified sample name."
  },
  {
    "code": "def write_file(path, content, mode=None, encoding='utf-8'):\n    if not mode:\n        if isinstance(content, bytes):\n            mode = 'wb'\n        else:\n            mode = 'wt'\n    if not path:\n        raise ValueError(\"Output path is invalid\")\n    else:\n        getLogger().debug(\"Writing content to {}\".format(path))\n        if mode in ('w', 'wt') and not isinstance(content, str):\n            content = to_string(content)\n        elif mode == 'wb':\n            if not isinstance(content, str):\n                content = to_string(content).encode(encoding)\n            else:\n                content = content.encode(encoding)\n        if str(path).endswith('.gz'):\n            with gzip.open(path, mode) as outfile:\n                outfile.write(content)\n        else:\n            with open(path, mode=mode) as outfile:\n                outfile.write(content)",
    "docstring": "Write content to a file. If the path ends with .gz, gzip will be used."
  },
  {
    "code": "def protect(self, password=None, read_protect=False, protect_from=0):\n        return super(NTAG203, self).protect(\n            password, read_protect, protect_from)",
    "docstring": "Set lock bits to disable future memory modifications.\n\n        If *password* is None, all memory pages except the 16-bit\n        counter in page 41 are protected by setting the relevant lock\n        bits (note that lock bits can not be reset). If valid NDEF\n        management data is found in page 4, protect() also sets the\n        NDEF write flag to read-only.\n\n        The NTAG203 can not be password protected. If a *password*\n        argument is provided, the protect() method always returns\n        False."
  },
  {
    "code": "def setup(provider=None):\n    site = init(provider)\n    if not site:\n        site = yaml.safe_load(_read_file(DEPLOY_YAML))\n    provider_class = PROVIDERS[site['provider']]\n    provider_class.init(site)",
    "docstring": "Creates the provider config files needed to deploy your project"
  },
  {
    "code": "def is_valid_address (s):\n    try:\n        pairs = s.split (\":\")\n        if len (pairs) != 6: return False\n        if not all(0 <= int(b, 16) <= 255 for b in pairs): return False\n    except:\n        return False\n    return True",
    "docstring": "returns True if address is a valid Bluetooth address\n\n    valid address are always strings of the form XX:XX:XX:XX:XX:XX\n    where X is a hexadecimal character.  For example,\n        01:23:45:67:89:AB is a valid address, but\n        IN:VA:LI:DA:DD:RE is not"
  },
  {
    "code": "def image_gen(normalizer, denorm, sz, tfms=None, max_zoom=None, pad=0, crop_type=None,\n              tfm_y=None, sz_y=None, pad_mode=cv2.BORDER_REFLECT, scale=None):\n    if tfm_y is None: tfm_y=TfmType.NO\n    if tfms is None: tfms=[]\n    elif not isinstance(tfms, collections.Iterable): tfms=[tfms]\n    if sz_y is None: sz_y = sz\n    if scale is None:\n        scale = [RandomScale(sz, max_zoom, tfm_y=tfm_y, sz_y=sz_y) if max_zoom is not None\n                 else Scale(sz, tfm_y, sz_y=sz_y)]\n    elif not is_listy(scale): scale = [scale]\n    if pad: scale.append(AddPadding(pad, mode=pad_mode))\n    if crop_type!=CropType.GOOGLENET: tfms=scale+tfms\n    return Transforms(sz, tfms, normalizer, denorm, crop_type,\n                      tfm_y=tfm_y, sz_y=sz_y)",
    "docstring": "Generate a standard set of transformations\n\n    Arguments\n    ---------\n     normalizer :\n         image normalizing function\n     denorm :\n         image denormalizing function\n     sz :\n         size, sz_y = sz if not specified.\n     tfms :\n         iterable collection of transformation functions\n     max_zoom : float,\n         maximum zoom\n     pad : int,\n         padding on top, left, right and bottom\n     crop_type :\n         crop type\n     tfm_y :\n         y axis specific transformations\n     sz_y :\n         y size, height\n     pad_mode :\n         cv2 padding style: repeat, reflect, etc.\n\n    Returns\n    -------\n     type : ``Transforms``\n         transformer for specified image operations.\n\n    See Also\n    --------\n     Transforms: the transformer object returned by this function"
  },
  {
    "code": "def wrplt(self, fout_dir, plt_ext=\"png\"):\n        basename = self.grprobj.get_fout_base(self.ntplt.hdrgo)\n        plt_pat = self.get_pltpat(plt_ext)\n        fout_basename = plt_pat.format(BASE=basename)\n        fout_plt = os.path.join(fout_dir, fout_basename)\n        self.gosubdagplot.plt_dag(fout_plt)\n        return fout_plt",
    "docstring": "Write png containing plot of GoSubDag."
  },
  {
    "code": "def access_token(self):\n        if self.cache_token:\n            return self.access_token_ or \\\n                   self._resolve_credential('access_token')\n        return self.access_token_",
    "docstring": "Get access_token."
  },
  {
    "code": "def write_crc32(fo, bytes):\n    data = crc32(bytes) & 0xFFFFFFFF\n    fo.write(pack('>I', data))",
    "docstring": "A 4-byte, big-endian CRC32 checksum"
  },
  {
    "code": "def _extract_response_xml(self, domain, response):\n        attributes = {}\n        alexa_keys = {'POPULARITY': 'TEXT', 'REACH': 'RANK', 'RANK': 'DELTA'}\n        try:\n            xml_root = ET.fromstring(response._content)\n            for xml_child in xml_root.findall('SD//'):\n                if xml_child.tag in alexa_keys and \\\n                        alexa_keys[xml_child.tag] in xml_child.attrib:\n                    attributes[xml_child.tag.lower(\n                    )] = xml_child.attrib[alexa_keys[xml_child.tag]]\n        except ParseError:\n            pass\n        attributes['domain'] = domain\n        return {'attributes': attributes}",
    "docstring": "Extract XML content of an HTTP response into dictionary format.\n\n        Args:\n            response: HTML Response objects\n        Returns:\n            A dictionary: {alexa-ranking key : alexa-ranking value}."
  },
  {
    "code": "def make_regex(separator):\n    return re.compile(r'(?:' + re.escape(separator) + r')?((?:[^' +\n                      re.escape(separator) + r'\\\\]|\\\\.)+)')",
    "docstring": "Utility function to create regexp for matching escaped separators\n    in strings."
  },
  {
    "code": "def declalltypes(self):\n        for f in self.body:\n            if (hasattr(f, '_ctype')\n                    and f._ctype._storage == Storages.TYPEDEF):\n                yield f",
    "docstring": "generator on all declaration of type"
  },
  {
    "code": "def pre_save(self, model_instance, add):\n        value = super(\n            LinkedTZDateTimeField,\n            self\n        ).pre_save(\n            model_instance=model_instance,\n            add=add\n        )\n        value = self._convert_value(\n            value=value,\n            model_instance=model_instance,\n            add=add\n        )\n        setattr(model_instance, self.attname, value)\n        return value",
    "docstring": "Converts the value being saved based on `populate_from` and\n        `time_override`"
  },
  {
    "code": "def url_name_for_action(self, action):\n        return \"%s.%s_%s\" % (self.module_name.lower(), self.model_name.lower(), action)",
    "docstring": "Returns the reverse name for this action"
  },
  {
    "code": "def add_internal_subnet(self, context_id, subnet_id):\n        return self.context.addPrivateSubnetToNetworkTunnel(subnet_id,\n                                                            id=context_id)",
    "docstring": "Add an internal subnet to a tunnel context.\n\n        :param int context_id: The id-value representing the context instance.\n        :param int subnet_id: The id-value representing the internal subnet.\n        :return bool: True if internal subnet addition was successful."
  },
  {
    "code": "def absnormpath(self, path):\n        path = self.normcase(path)\n        cwd = self._matching_string(path, self.cwd)\n        if not path:\n            path = self.path_separator\n        elif not self._starts_with_root_path(path):\n            root_name = self._matching_string(path, self.root.name)\n            empty = self._matching_string(path, '')\n            path = self._path_separator(path).join(\n                (cwd != root_name and cwd or empty, path))\n        if path == self._matching_string(path, '.'):\n            path = cwd\n        return self.normpath(path)",
    "docstring": "Absolutize and minimalize the given path.\n\n        Forces all relative paths to be absolute, and normalizes the path to\n        eliminate dot and empty components.\n\n        Args:\n            path:  Path to normalize.\n\n        Returns:\n            The normalized path relative to the current working directory,\n            or the root directory if path is empty."
  },
  {
    "code": "def update_bios_data_by_patch(self, data):\n        bios_settings_data = {\n            'Attributes': data\n        }\n        self._conn.patch(self.path, data=bios_settings_data)",
    "docstring": "Update bios data by patch\n\n        :param data: default bios config data"
  },
  {
    "code": "def split_semicolon(line, maxsplit=None):\n    r\n    split_line = line.split(';')\n    split_line_size = len(split_line)\n    if maxsplit is None or maxsplit < 0:\n        maxsplit = split_line_size\n    i = 0\n    while i < split_line_size - 1:\n        ends = split_line[i].endswith('\\\\')\n        if ends:\n            split_line[i] = split_line[i][:-1]\n        if (ends or i >= maxsplit) and i < split_line_size - 1:\n            split_line[i] = \";\".join([split_line[i], split_line[i + 1]])\n            del split_line[i + 1]\n            split_line_size -= 1\n        else:\n            i += 1\n    return split_line",
    "docstring": "r\"\"\"Split a line on semicolons characters but not on the escaped semicolons\n\n    :param line: line to split\n    :type line: str\n    :param maxsplit: maximal number of split (if None, no limit)\n    :type maxsplit: None | int\n    :return: split line\n    :rtype: list\n\n    >>> split_semicolon('a,b;c;;g')\n    ['a,b', 'c', '', 'g']\n\n    >>> split_semicolon('a,b;c;;g', 2)\n    ['a,b', 'c', ';g']\n\n    >>> split_semicolon(r'a,b;c\\;;g', 2)\n    ['a,b', 'c;', 'g']"
  },
  {
    "code": "def get_parts(self):\n        parts = []\n        start_byte = 0\n        for i in range(1, self.total + 1):\n            end_byte = start_byte + self.part_size\n            if end_byte >= self.file_size - 1:\n                end_byte = self.file_size\n            parts.append({\n                'part': i,\n                'offset': start_byte,\n                'limit': end_byte\n            })\n            start_byte = end_byte\n        return parts",
    "docstring": "Partitions the file and saves the parts to be uploaded\n        in memory."
  },
  {
    "code": "def pkginfo(name, version, arch, repoid, install_date=None, install_date_time_t=None):\n    pkginfo_tuple = collections.namedtuple(\n        'PkgInfo',\n        ('name', 'version', 'arch', 'repoid', 'install_date',\n         'install_date_time_t')\n    )\n    return pkginfo_tuple(name, version, arch, repoid, install_date,\n                         install_date_time_t)",
    "docstring": "Build and return a pkginfo namedtuple"
  },
  {
    "code": "def get_prefix(self):\n        for key, value in self.pages_config.items():\n            if not hasattr(value, '__iter__'):\n                value = (value, )\n            for item in value:\n                if type(self.node) == item\\\n                        or type(self.node) == getattr(item, 'model', None):\n                    return key",
    "docstring": "Each resource defined in config for pages as dict. This method\n        returns key from config where located current resource."
  },
  {
    "code": "def get_assessments_taken_by_ids(self, assessment_taken_ids):\n        collection = JSONClientValidated('assessment',\n                                         collection='AssessmentTaken',\n                                         runtime=self._runtime)\n        object_id_list = []\n        for i in assessment_taken_ids:\n            object_id_list.append(ObjectId(self._get_id(i, 'assessment').get_identifier()))\n        result = collection.find(\n            dict({'_id': {'$in': object_id_list}},\n                 **self._view_filter()))\n        result = list(result)\n        sorted_result = []\n        for object_id in object_id_list:\n            for object_map in result:\n                if object_map['_id'] == object_id:\n                    sorted_result.append(object_map)\n                    break\n        return objects.AssessmentTakenList(sorted_result, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets an ``AssessmentTakenList`` corresponding to the given ``IdList``.\n\n        In plenary mode, the returned list contains all of the\n        assessments specified in the ``Id`` list, in the order of the\n        list, including duplicates, or an error results if an ``Id`` in\n        the supplied list is not found or inaccessible. Otherwise,\n        inaccessible ``AssessmentTaken`` objects may be omitted from the\n        list and may present the elements in any order including\n        returning a unique set.\n\n        arg:    assessment_taken_ids (osid.id.IdList): the list of\n                ``Ids`` to retrieve\n        return: (osid.assessment.AssessmentTakenList) - the returned\n                ``AssessmentTaken list``\n        raise:  NotFound - an ``Id was`` not found\n        raise:  NullArgument - ``assessment_taken_ids`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - assessment failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def toggle_use_font_background_sensitivity(self, chk):\n        self.get_widget('palette_16').set_sensitive(chk.get_active())\n        self.get_widget('palette_17').set_sensitive(chk.get_active())",
    "docstring": "If the user chooses to use the gnome default font\n        configuration it means that he will not be able to use the\n        font selector."
  },
  {
    "code": "async def _async_stop(self):\n        if self.presence:\n            self.presence.set_unavailable()\n        for behav in self.behaviours:\n            behav.kill()\n        if self.web.is_started():\n            await self.web.runner.cleanup()\n        if self.is_alive():\n            self.client.stop()\n            aexit = self.conn_coro.__aexit__(*sys.exc_info())\n            await aexit\n            logger.info(\"Client disconnected.\")\n        self._alive.clear()",
    "docstring": "Stops an agent and kills all its behaviours."
  },
  {
    "code": "def search(self, category = None, cuisine = None, location = (None, None), radius = None, tl_coord = (None, None), \\\n                   br_coord = (None, None), name = None, country = None, locality = None, \\\n                   region = None, postal_code = None, street_address = None,\\\n                   website_url = None, has_menu = None, open_at = None):\n        params = self._get_params(category = category, cuisine = cuisine, location = location, radius = radius, tl_coord = tl_coord, \\\n                                      br_coord = br_coord, name = name, country = country, locality = locality, \\\n                                      region = region, postal_code = postal_code, street_address = street_address, \\\n                                      website_url = website_url, has_menu = has_menu, open_at = open_at)\n        return self._create_query('search', params)",
    "docstring": "Locu Venue Search API Call Wrapper\n\n        \n        Args: \n        *Note that none of the arguments are required\n          category         : List of category types that need to be filtered by: ['restaurant', 'spa', 'beauty salon', 'gym', 'laundry', 'hair care',  'other']\n            type : [string]\n          cuisine          : List of cuisine types that need to be filtered by: ['american', 'italian', ...]\n            type : [string]\n          location          : Tuple that consists of (latitude, longtitude) coordinates\n            type : tuple(float, float)\n          radius            : Radius around the given lat, long\n            type : float\n          tl_coord          : Tuple that consists of (latitude, longtitude) for bounding box top left coordinates  \n            type : tuple(float, float)\n          br_coord          : Tuple that consists of (latitude, longtitude) for bounding box bottom right coordinates  \n            type : tuple(float, float)\n          name              : Name of the venue\n            type : string\n          country           : Country where venue is located\n            type : string\n          locality          : Locality. Ex 'San Francisco'\n            type : string\n          region            : Region/state. Ex. 'CA'\n            type : string\n          postal_code       : Postal code\n            type : string\n          street_address    : Address\n            type : string\n          open_at           : Search for venues open at the specified time\n            type : datetime\n          website_url       : Filter by the a website url\n            type : string\n          has_menu          : Filter venues that have menus in them\n            type : boolean\n        Returns:\n          A dictionary with a data returned by the server\n\n        Raises:\n          HttpException with the error message from the server"
  },
  {
    "code": "def to(self, unit):\n        u = Unit(\"0cm\")\n        u.value = self.value/self.per_inch[self.unit]*self.per_inch[unit]\n        u.unit = unit\n        return u",
    "docstring": "Convert to a given unit.\n\n        Parameters\n        ----------\n        unit : str\n           Name of the unit to convert to.\n\n        Returns\n        -------\n        u : Unit\n            new Unit object with the requested unit and computed value."
  },
  {
    "code": "def spkw17(handle, body, center, inframe, first, last, segid, epoch, eqel,\n           rapol, decpol):\n    handle = ctypes.c_int(handle)\n    body = ctypes.c_int(body)\n    center = ctypes.c_int(center)\n    inframe = stypes.stringToCharP(inframe)\n    first = ctypes.c_double(first)\n    last = ctypes.c_double(last)\n    segid = stypes.stringToCharP(segid)\n    epoch = ctypes.c_double(epoch)\n    eqel = stypes.toDoubleVector(eqel)\n    rapol = ctypes.c_double(rapol)\n    decpol = ctypes.c_double(decpol)\n    libspice.spkw17_c(handle, body, center, inframe, first, last, segid, epoch,\n                      eqel, rapol, decpol)",
    "docstring": "Write an SPK segment of type 17 given a type 17 data record.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw17_c.html\n\n    :param handle: Handle of an SPK file open for writing.\n    :type handle: int\n    :param body: Body code for ephemeris object.\n    :type body: int\n    :param center: Body code for the center of motion of the body.\n    :type center: int\n    :param inframe: The reference frame of the states.\n    :type inframe: str\n    :param first: First valid time for which states can be computed.\n    :type first: float\n    :param last: Last valid time for which states can be computed.\n    :type last: float\n    :param segid: Segment identifier.\n    :type segid: str\n    :param epoch: Epoch of elements in seconds past J2000.\n    :type epoch: float\n    :param eqel: Array of equinoctial elements.\n    :type eqel: 9-Element Array of floats\n    :param rapol: Right Ascension of the pole of the reference plane.\n    :type rapol: float\n    :param decpol: Declination of the pole of the reference plane.\n    :type decpol: float"
  },
  {
    "code": "def html_attributes(self):\n        extra_attributes = ''\n        if self.element_id is not None:\n            extra_attributes = ' id=\"%s\"' % self.element_id\n        if self.style_class is not None:\n            extra_attributes = '%s class=\"%s\"' % (\n                extra_attributes, self.style_class)\n        if self.attributes is not None:\n            extra_attributes = '%s %s' % (extra_attributes, self.attributes)\n        return extra_attributes",
    "docstring": "Get extra html attributes such as id and class."
  },
  {
    "code": "def _module_to_base_modules(s):\n    parts = s.split('.')\n    for i in range(1, len(parts)):\n        yield '.'.join(parts[:i])",
    "docstring": "return all module names that would be imported due to this\n    import-import"
  },
  {
    "code": "def to_pandas(self, wrap=False, **kwargs):\n        try:\n            import pandas as pd\n        except ImportError:\n            raise DependencyNotInstalledError(\n                    'to_pandas requires for `pandas` library')\n        def wrapper(result):\n            df = result.values\n            if wrap:\n                from .. import DataFrame\n                df = DataFrame(df)\n            return df[self.name]\n        return self.execute(wrapper=wrapper, **kwargs)",
    "docstring": "Convert to pandas Series. Execute at once.\n\n        :param wrap: if True, wrap the pandas DataFrame into a PyODPS DataFrame\n        :return: pandas Series"
  },
  {
    "code": "def fetch(self):\n        params = values.of({})\n        payload = self._version.fetch(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return UserChannelInstance(\n            self._version,\n            payload,\n            service_sid=self._solution['service_sid'],\n            user_sid=self._solution['user_sid'],\n            channel_sid=self._solution['channel_sid'],\n        )",
    "docstring": "Fetch a UserChannelInstance\n\n        :returns: Fetched UserChannelInstance\n        :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance"
  },
  {
    "code": "def _load(self, f, layer=None, source=None):\n        if hasattr(f, 'read'):\n            self._loads(f.read(), layer=layer, source=source)\n        else:\n            with open(f) as f:\n                self._loads(f.read(), layer=layer, source=source)",
    "docstring": "Load data from a yaml formatted file.\n\n        Parameters\n        ----------\n        f : str or file like object\n            If f is a string then it is interpreted as a path to the file to load\n            If it is a file like object then data is read directly from it.\n        layer : str\n            layer to load data into. If none is supplied the outermost one is used\n        source : str\n            Source to attribute the values to"
  },
  {
    "code": "def html_entity_decode_char(self, m, defs=htmlentities.entitydefs):\n        try:\n            char = defs[m.group(1)]\n            return \"&{char};\".format(char=char)\n        except ValueError:\n            return m.group(0)\n        except KeyError:\n            return m.group(0)",
    "docstring": "decode html entity into one of the html char"
  },
  {
    "code": "def set_body_s(self, stream):\n        if self.argstreams[2].state == StreamState.init:\n            self.argstreams[2] = stream\n        else:\n            raise TChannelError(\n                \"Unable to change the body since the streaming has started\")",
    "docstring": "Set customized body stream.\n\n        Note: the body stream can only be changed before the stream\n        is consumed.\n\n        :param stream: InMemStream/PipeStream for body\n\n        :except TChannelError:\n            Raise TChannelError if the stream is being sent when you try\n            to change the stream."
  },
  {
    "code": "def get_mapping_variable(variable_name, variables_mapping):\n    try:\n        return variables_mapping[variable_name]\n    except KeyError:\n        raise exceptions.VariableNotFound(\"{} is not found.\".format(variable_name))",
    "docstring": "get variable from variables_mapping.\n\n    Args:\n        variable_name (str): variable name\n        variables_mapping (dict): variables mapping\n\n    Returns:\n        mapping variable value.\n\n    Raises:\n        exceptions.VariableNotFound: variable is not found."
  },
  {
    "code": "def mad(a):\n    a = np.asfarray(a).flatten()\n    return np.median(np.abs(a - np.median(a)))",
    "docstring": "Calculate the median absolute deviation of a sample\n    \n    a - a numpy array-like collection of values\n    \n    returns the median of the deviation of a from its median."
  },
  {
    "code": "def parse_time_division(self, bytes):\n        value = self.bytes_to_int(bytes)\n        if not value & 0x8000:\n            return {'fps': False, 'ticks_per_beat': value & 0x7FFF}\n        else:\n            SMPTE_frames = (value & 0x7F00) >> 2\n            if SMPTE_frames not in [24, 25, 29, 30]:\n                raise TimeDivisionError, \\\n                    \"'%d' is not a valid value for the number of SMPTE frames\"\\\n                     % SMPTE_frames\n            clock_ticks = (value & 0x00FF) >> 2\n            return {'fps': True, 'SMPTE_frames': SMPTE_frames,\n                    'clock_ticks': clock_ticks}",
    "docstring": "Parse the time division found in the header of a MIDI file and\n        return a dictionary with the boolean fps set to indicate whether to\n        use frames per second or ticks per beat.\n\n        If fps is True, the values SMPTE_frames and clock_ticks will also be\n        set. If fps is False, ticks_per_beat will hold the value."
  },
  {
    "code": "def _generate_recommendation(self,\n                                 query_analysis,\n                                 db_name,\n                                 collection_name):\n        index_rec = '{'\n        for query_field in query_analysis['analyzedFields']:\n            if query_field['fieldType'] is EQUIV_TYPE:\n                if len(index_rec) is not 1:\n                    index_rec += ', '\n                index_rec += '\"' + query_field['fieldName'] + '\": 1'\n        for query_field in query_analysis['analyzedFields']:\n            if query_field['fieldType'] is SORT_TYPE:\n                if len(index_rec) is not 1:\n                    index_rec += ', '\n                index_rec += '\"' + query_field['fieldName'] + '\": 1'\n        for query_field in query_analysis['analyzedFields']:\n            if query_field['fieldType'] is RANGE_TYPE:\n                if len(index_rec) is not 1:\n                    index_rec += ', '\n                index_rec += '\"' + query_field['fieldName'] + '\": 1'\n        index_rec += '}'\n        return OrderedDict([('index',index_rec),\n                            ('shellCommand', self.generate_shell_command(collection_name, index_rec))])",
    "docstring": "Generates an ideal query recommendation"
  },
  {
    "code": "def handle_input(self, input_str, place=True, check=False):\n        user = self.get_player()\n        pos = self.validate_input(input_str)\n        if pos[0] == 'u':\n            self.undo(pos[1])\n            return pos\n        if place:\n            result = self.set_pos(pos, check)\n            return result\n        else:\n            return pos",
    "docstring": "Transfer user input to valid chess position"
  },
  {
    "code": "def _asciify_list(data):\n    ret = []\n    for item in data:\n        if isinstance(item, unicode):\n            item = _remove_accents(item)\n            item = item.encode('utf-8')\n        elif isinstance(item, list):\n            item = _asciify_list(item)\n        elif isinstance(item, dict):\n            item = _asciify_dict(item)\n        ret.append(item)\n    return ret",
    "docstring": "Ascii-fies list values"
  },
  {
    "code": "def safeMkdir(p, permissions = permissions755):\n\ttry:\n\t\tos.mkdir(p)\n\texcept OSError:\n\t\tpass\n\tos.chmod(p, permissions)",
    "docstring": "Wrapper around os.mkdir which does not raise an error if the directory exists."
  },
  {
    "code": "def from_cli_single_ifo(opt, ifo, **kwargs):\n    single_det_opt = copy_opts_for_single_ifo(opt, ifo)\n    return from_cli(single_det_opt, **kwargs)",
    "docstring": "Get the strain for a single ifo when using the multi-detector CLI"
  },
  {
    "code": "def get_stddevs(self, C, stddev_shape, stddev_types, sites):\n        stddevs = []\n        tau = C[\"tau_event\"]\n        sigma_s = np.zeros(sites.vs30measured.shape, dtype=float)\n        sigma_s[sites.vs30measured] += C[\"sigma_s_obs\"]\n        sigma_s[np.logical_not(sites.vs30measured)] += C[\"sigma_s_inf\"]\n        phi = np.sqrt(C[\"phi0\"] ** 2.0 + sigma_s ** 2.)\n        for stddev_type in stddev_types:\n            assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n            if stddev_type == const.StdDev.TOTAL:\n                stddevs.append(np.sqrt(tau ** 2. + phi ** 2.) +\n                               np.zeros(stddev_shape))\n            elif stddev_type == const.StdDev.INTRA_EVENT:\n                stddevs.append(phi + np.zeros(stddev_shape))\n            elif stddev_type == const.StdDev.INTER_EVENT:\n                stddevs.append(tau + np.zeros(stddev_shape))\n        return stddevs",
    "docstring": "Returns the standard deviations, with different site standard\n        deviation for inferred vs. observed vs30 sites."
  },
  {
    "code": "def order_error(subtag, got, expected):\n    options = SUBTAG_TYPES[expected:]\n    if len(options) == 1:\n        expect_str = options[0]\n    elif len(options) == 2:\n        expect_str = '%s or %s' % (options[0], options[1])\n    else:\n        expect_str = '%s, or %s' % (', '.join(options[:-1]), options[-1])\n    got_str = SUBTAG_TYPES[got]\n    raise LanguageTagError(\"This %s subtag, %r, is out of place. \"\n                           \"Expected %s.\" % (got_str, subtag, expect_str))",
    "docstring": "Output an error indicating that tags were out of order."
  },
  {
    "code": "def reverse_post_order_sort_nodes(graph, nodes=None):\n        post_order = networkx.dfs_postorder_nodes(graph)\n        if nodes is None:\n            return reversed(list(post_order))\n        addrs_to_index = {}\n        for i, n in enumerate(post_order):\n            addrs_to_index[n.addr] = i\n        return sorted(nodes, key=lambda n: addrs_to_index[n.addr], reverse=True)",
    "docstring": "Sort a given set of nodes in reverse post ordering.\n\n        :param networkx.DiGraph graph: A local transition graph of a function.\n        :param iterable nodes: A collection of nodes to sort.\n        :return: A list of sorted nodes.\n        :rtype: list"
  },
  {
    "code": "def metadata(self):\n        from sqlalchemy import MetaData\n        metadata = MetaData(bind=self.engine, schema=self._schema)\n        metadata.reflect(self.engine)\n        return metadata",
    "docstring": "Return an SqlAlchemy MetaData object, bound to the engine."
  },
  {
    "code": "def _recv(self, line):\n    if line == '':\n      return\n    if line[0] != Lutron.OP_RESPONSE:\n      _LOGGER.debug(\"ignoring %s\" % line)\n      return\n    parts = line[1:].split(',')\n    cmd_type = parts[0]\n    integration_id = int(parts[1])\n    args = parts[2:]\n    if cmd_type not in self._ids:\n      _LOGGER.info(\"Unknown cmd %s (%s)\" % (cmd_type, line))\n      return\n    ids = self._ids[cmd_type]\n    if integration_id not in ids:\n      _LOGGER.warning(\"Unknown id %d (%s)\" % (integration_id, line))\n      return\n    obj = ids[integration_id]\n    handled = obj.handle_update(args)",
    "docstring": "Invoked by the connection manager to process incoming data."
  },
  {
    "code": "def _get_enum_bins(configfile):\n    config = yaml.safe_load(open(configfile))\n    emin = config['selection']['emin']\n    emax = config['selection']['emax']\n    log_emin = np.log10(emin)\n    log_emax = np.log10(emax)\n    ndec = log_emax - log_emin\n    binsperdec = config['binning']['binsperdec']\n    nebins = int(np.round(binsperdec * ndec))\n    return nebins",
    "docstring": "Get the number of energy bin in the SED\n\n    Parameters\n    ----------\n\n    configfile : str\n        Fermipy configuration file.\n\n    Returns\n    -------\n\n    nbins : int\n        The number of energy bins"
  },
  {
    "code": "def holtWintersForecast(requestContext, seriesList):\n    previewSeconds = 7 * 86400\n    newContext = requestContext.copy()\n    newContext['startTime'] = (requestContext['startTime'] -\n                               timedelta(seconds=previewSeconds))\n    previewList = evaluateTokens(newContext, requestContext['args'][0])\n    results = []\n    for series in previewList:\n        analysis = holtWintersAnalysis(series)\n        predictions = analysis['predictions']\n        windowPoints = previewSeconds // predictions.step\n        result = TimeSeries(\"holtWintersForecast(%s)\" % series.name,\n                            predictions.start + previewSeconds,\n                            predictions.end, predictions.step,\n                            predictions[windowPoints:])\n        result.pathExpression = result.name\n        results.append(result)\n    return results",
    "docstring": "Performs a Holt-Winters forecast using the series as input data. Data from\n    one week previous to the series is used to bootstrap the initial forecast."
  },
  {
    "code": "def _get_upload_cmd(self, mirror=False):\n        if mirror:\n            dest_uri = self.s3_mirror_uri\n        else:\n            dest_uri = self.s3_version_uri\n        cmd = 'aws s3 sync {} {} --delete --exact-timestamps --profile {}'.format(self.artifact_path,\n                                                                                  dest_uri, self.env)\n        return cmd",
    "docstring": "Generate the S3 CLI upload command\n\n        Args:\n            mirror (bool): If true, uses a flat directory structure instead of nesting under a version.\n\n        Returns:\n            str: The full CLI command to run."
  },
  {
    "code": "def delete_all_renditions(self):\n        if self.renditions:\n            for r in self.renditions.values():\n                default_storage.delete(r)\n            self.renditions = {}",
    "docstring": "delete all renditions and rendition dict"
  },
  {
    "code": "def rmdir(self, tid):\n        pt = self.PathType.get(tid)\n        if pt is self.PathType.main:\n            raise FuseOSError(errno.EINVAL)\n        elif pt is not self.PathType.subdir:\n            raise FuseOSError(errno.ENOTDIR)\n        try:\n            self.searches[tid[0]].clean()\n            del self.searches[tid[0]]\n        except KeyError:\n            raise FuseOSError(errno.ENOENT)\n        return 0",
    "docstring": "Directory removal. ``YTActions`` object under `tid` is told to clean all data, and then it is deleted.\n\n        Parameters\n        ----------\n        tid : str\n            Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator."
  },
  {
    "code": "def master_primary_name(self) -> Optional[str]:\n        master_primary_name = self.master_replica.primaryName\n        if master_primary_name:\n            return self.master_replica.getNodeName(master_primary_name)\n        return None",
    "docstring": "Return the name of the primary node of the master instance"
  },
  {
    "code": "def build_deps(self):\n        build_requires = self.metadata['setup_requires']\n        if self.has_test_suite:\n            build_requires += self.metadata['tests_require'] + self.metadata[\n                'install_requires']\n        if 'setuptools' not in build_requires:\n            build_requires.append('setuptools')\n        return sorted(self.name_convert_deps_list(deps_from_pyp_format(\n            build_requires, runtime=False)))",
    "docstring": "Same as runtime_deps, but build dependencies. Test and install\n        requires are included if package contains test suite to prevent\n        %check phase crashes because of missing dependencies\n\n        Returns:\n            list of build dependencies of the package"
  },
  {
    "code": "def str_slice(arr, start=None, stop=None, step=None):\n    obj = slice(start, stop, step)\n    f = lambda x: x[obj]\n    return _na_map(f, arr)",
    "docstring": "Slice substrings from each element in the Series or Index.\n\n    Parameters\n    ----------\n    start : int, optional\n        Start position for slice operation.\n    stop : int, optional\n        Stop position for slice operation.\n    step : int, optional\n        Step size for slice operation.\n\n    Returns\n    -------\n    Series or Index of object\n        Series or Index from sliced substring from original string object.\n\n    See Also\n    --------\n    Series.str.slice_replace : Replace a slice with a string.\n    Series.str.get : Return element at position.\n        Equivalent to `Series.str.slice(start=i, stop=i+1)` with `i`\n        being the position.\n\n    Examples\n    --------\n    >>> s = pd.Series([\"koala\", \"fox\", \"chameleon\"])\n    >>> s\n    0        koala\n    1          fox\n    2    chameleon\n    dtype: object\n\n    >>> s.str.slice(start=1)\n    0        oala\n    1          ox\n    2    hameleon\n    dtype: object\n\n    >>> s.str.slice(stop=2)\n    0    ko\n    1    fo\n    2    ch\n    dtype: object\n\n    >>> s.str.slice(step=2)\n    0      kaa\n    1       fx\n    2    caeen\n    dtype: object\n\n    >>> s.str.slice(start=0, stop=5, step=3)\n    0    kl\n    1     f\n    2    cm\n    dtype: object\n\n    Equivalent behaviour to:\n\n    >>> s.str[0:5:3]\n    0    kl\n    1     f\n    2    cm\n    dtype: object"
  },
  {
    "code": "def register_new_edge(edge_id, first_char_index, last_char_index, source_node_id, dest_node_id):\n    event = Edge.Created(\n        originator_id=edge_id,\n        first_char_index=first_char_index,\n        last_char_index=last_char_index,\n        source_node_id=source_node_id,\n        dest_node_id=dest_node_id,\n    )\n    entity = Edge.mutate(event=event)\n    publish(event)\n    return entity",
    "docstring": "Factory method, registers new edge."
  },
  {
    "code": "def register_properties(self, properties):\n        if isinstance(properties, collections.Mapping):\n            properties = properties.itervalues()\n        for prop in properties:\n            self.register_property(**prop)",
    "docstring": "Register properties using a list defining the properties.\n\n        The dictionary should itself contain dictionaries. i.e.\n\n        .. code-block:: python\n\n            D = [\n                { 'name':'ref_wave','dtype':np.float32,\n                    'default':1.41e6 },\n            ]\n\n        Parameters\n        ----------\n        properties : A dictionary or list\n            A dictionary or list of dictionaries\n            describing properties"
  },
  {
    "code": "def check_regularizers(regularizers, keys):\n  if regularizers is None:\n    return {}\n  _assert_is_dictlike(regularizers, valid_keys=keys)\n  keys = set(keys)\n  if not set(regularizers) <= keys:\n    extra_keys = set(regularizers) - keys\n    raise KeyError(\n        \"Invalid regularizer keys {}, regularizers can only \"\n        \"be provided for {}\".format(\n            \", \".join(\"'{}'\".format(key) for key in extra_keys),\n            \", \".join(\"'{}'\".format(key) for key in keys)))\n  _check_nested_callables(regularizers, \"Regularizer\")\n  return dict(regularizers)",
    "docstring": "Checks the given regularizers.\n\n  This checks that `regularizers` is a dictionary that only contains keys in\n  `keys`, and furthermore the entries in `regularizers` are functions or\n  further dictionaries (the latter used, for example, in passing regularizers\n  to modules inside modules) that must satisfy the same constraints.\n\n  Args:\n    regularizers: Dictionary of regularizers (allowing nested dictionaries) or\n      None.\n    keys: Iterable of valid keys for `regularizers`.\n\n  Returns:\n    Copy of checked dictionary of regularizers. If `regularizers=None`, an empty\n    dictionary will be returned.\n\n  Raises:\n    KeyError: If an regularizers is provided for a key not in `keys`.\n    TypeError: If a provided regularizer is not a callable function, or\n      `regularizers` is not a Mapping."
  },
  {
    "code": "def uninstall(plugin_name, *args):\n    if isinstance(plugin_name, types.StringTypes):\n        plugin_name = [plugin_name]\n    available_path = MICRODROP_CONDA_SHARE.joinpath('plugins', 'available')\n    for name_i in plugin_name:\n        plugin_module_i = name_i.split('.')[-1].replace('-', '_')\n        plugin_path_i = available_path.joinpath(plugin_module_i)\n        if not _islinklike(plugin_path_i) and not plugin_path_i.isdir():\n            raise IOError('Plugin `{}` not found in `{}`'\n                          .format(name_i, available_path))\n        else:\n            logging.debug('[uninstall] Found plugin `%s`', plugin_path_i)\n    conda_args = ['uninstall', '--json', '-y'] + list(args) + plugin_name\n    uninstall_log_js = ch.conda_exec(*conda_args, verbose=False)\n    _remove_broken_links()\n    logger.debug('Uninstalled plugins: ```%s```', plugin_name)\n    return json.loads(uninstall_log_js.split('\\x00')[-1])",
    "docstring": "Uninstall plugin packages.\n\n    Plugin packages must have a directory with the same name as the package in\n    the following directory:\n\n        <conda prefix>/share/microdrop/plugins/available/\n\n    Parameters\n    ----------\n    plugin_name : str or list\n        Plugin package(s) to uninstall.\n    *args\n        Extra arguments to pass to Conda ``uninstall`` command.\n\n    Returns\n    -------\n    dict\n        Conda uninstallation log object (from JSON Conda uninstall output)."
  },
  {
    "code": "def _fmadm_action_fmri(action, fmri):\n    ret = {}\n    fmadm = _check_fmadm()\n    cmd = '{cmd} {action} {fmri}'.format(\n        cmd=fmadm,\n        action=action,\n        fmri=fmri\n    )\n    res = __salt__['cmd.run_all'](cmd)\n    retcode = res['retcode']\n    result = {}\n    if retcode != 0:\n        result['Error'] = res['stderr']\n    else:\n        result = True\n    return result",
    "docstring": "Internal function for fmadm.repqired, fmadm.replaced, fmadm.flush"
  },
  {
    "code": "def cdssequencethreads(self):\n        for i in range(self.cpus):\n            threads = Thread(target=self.cdssequence, args=())\n            threads.setDaemon(True)\n            threads.start()\n        for sample in self.metadata.samples:\n            sample[self.analysistype].coresequence = dict()\n            self.sequencequeue.put(sample)\n        self.sequencequeue.join()",
    "docstring": "Extracts the sequence of each gene for each strain"
  },
  {
    "code": "def find_ctrlpts_surface(t_u, t_v, surf, **kwargs):\n    span_func = kwargs.get('find_span_func', helpers.find_span_linear)\n    span_u = span_func(surf.degree_u, surf.knotvector_u, surf.ctrlpts_size_u, t_u)\n    span_v = span_func(surf.degree_v, surf.knotvector_v, surf.ctrlpts_size_v, t_v)\n    idx_u = span_u - surf.degree_u\n    idx_v = span_v - surf.degree_v\n    surf_ctrlpts = [[] for _ in range(surf.degree_u + 1)]\n    for k in range(surf.degree_u + 1):\n        temp = [() for _ in range(surf.degree_v + 1)]\n        for l in range(surf.degree_v + 1):\n            temp[l] = surf.ctrlpts2d[idx_u + k][idx_v + l]\n        surf_ctrlpts[k] = temp\n    return surf_ctrlpts",
    "docstring": "Finds the control points involved in the evaluation of the surface point defined by the input parameter pair.\n\n    This function uses a modified version of the algorithm *A3.5 SurfacePoint* from The NURBS Book by Piegl & Tiller.\n\n    :param t_u: parameter on the u-direction\n    :type t_u: float\n    :param t_v: parameter on the v-direction\n    :type t_v: float\n    :param surf: input surface\n    :type surf: abstract.Surface\n    :return: 2-dimensional control points array\n    :rtype: list"
  },
  {
    "code": "def to_ufo_paths(self, ufo_glyph, layer):\n    pen = ufo_glyph.getPointPen()\n    for path in layer.paths:\n        nodes = list(path.nodes)\n        for node in nodes:\n            self.to_ufo_node_user_data(ufo_glyph, node)\n        pen.beginPath()\n        if not nodes:\n            pen.endPath()\n            continue\n        if not path.closed:\n            node = nodes.pop(0)\n            assert node.type == \"line\", \"Open path starts with off-curve points\"\n            pen.addPoint(tuple(node.position), segmentType=\"move\")\n        else:\n            nodes.insert(0, nodes.pop())\n        for node in nodes:\n            node_type = _to_ufo_node_type(node.type)\n            pen.addPoint(\n                tuple(node.position), segmentType=node_type, smooth=node.smooth\n            )\n        pen.endPath()",
    "docstring": "Draw .glyphs paths onto a pen."
  },
  {
    "code": "def prepare_image(tarpath, outfolder, **kwargs):\n    outfolder = path.Path(outfolder)\n    untar(tarpath, outfolder, **kwargs)\n    resolv_path = outfolder / 'etc' / 'resolv.conf'\n    if resolv_path.islink():\n        resolv_path.remove().write_text('', encoding='ascii')",
    "docstring": "Unpack the OS image stored at tarpath to outfolder.\n\n    Prepare the unpacked image for use as a VR base image."
  },
  {
    "code": "def redirect_to(self, url=None, parameters={}):\n        if url is None and 'RelayState' in self.__request_data['get_data']:\n            url = self.__request_data['get_data']['RelayState']\n        return OneLogin_Saml2_Utils.redirect(url, parameters, request_data=self.__request_data)",
    "docstring": "Redirects the user to the URL passed by parameter or to the URL that we defined in our SSO Request.\n\n        :param url: The target URL to redirect the user\n        :type url: string\n        :param parameters: Extra parameters to be passed as part of the URL\n        :type parameters: dict\n\n        :returns: Redirection URL"
  },
  {
    "code": "def format_diff_pyxb(a_pyxb, b_pyxb):\n    return '\\n'.join(\n        difflib.ndiff(\n            serialize_to_xml_str(a_pyxb).splitlines(),\n            serialize_to_xml_str(b_pyxb).splitlines(),\n        )\n    )",
    "docstring": "Create a diff between two PyXB objects.\n\n    Args:\n      a_pyxb: PyXB object\n      b_pyxb: PyXB object\n\n    Returns:\n      str : `Differ`-style delta"
  },
  {
    "code": "def iter_python_modules(tile):\n    for product_type in tile.PYTHON_PRODUCTS:\n        for product in tile.find_products(product_type):\n            entry_point = ENTRY_POINT_MAP.get(product_type)\n            if entry_point is None:\n                raise BuildError(\"Found an unknown python product (%s) whose entrypoint could not be determined (%s)\" %\n                                 (product_type, product))\n            if ':' in product:\n                module, _, obj_name = product.rpartition(':')\n            else:\n                module = product\n                obj_name = None\n            if not os.path.exists(module):\n                raise BuildError(\"Found a python product whose path did not exist: %s\" % module)\n            product_name = os.path.basename(module)\n            if product_name.endswith(\".py\"):\n                product_name = product_name[:-3]\n            import_string = \"{} = {}.{}\".format(product_name, tile.support_distribution, product_name)\n            if obj_name is not None:\n                import_string += \":{}\".format(obj_name)\n            yield (module, import_string, entry_point)",
    "docstring": "Iterate over all python products in the given tile.\n\n    This will yield tuples where the first entry is the path to the module\n    containing the product the second entry is the appropriate\n    import string to include in an entry point, and the third entry is\n    the entry point name."
  },
  {
    "code": "def _handle(self, nick, target, message, **kwargs):\n        for regex, (func, pattern) in self.routes.items():\n            match = regex.match(message)\n            if match:\n                self.client.loop.create_task(\n                    func(nick, target, message, match, **kwargs))",
    "docstring": "client callback entrance"
  },
  {
    "code": "def gen(skipdirhtml=False):\n    docs_changelog = 'docs/changelog.rst'\n    check_git_unchanged(docs_changelog)\n    pandoc('--from=markdown', '--to=rst', '--output=' + docs_changelog, 'CHANGELOG.md')\n    if not skipdirhtml:\n        sphinx_build['-b', 'dirhtml', '-W', '-E', 'docs', 'docs/_build/dirhtml'] & FG\n    sphinx_build['-b', 'html', '-W', '-E', 'docs', 'docs/_build/html'] & FG",
    "docstring": "Generate html and dirhtml output."
  },
  {
    "code": "def _isnan(self):\n        if self._can_hold_na:\n            return isna(self)\n        else:\n            values = np.empty(len(self), dtype=np.bool_)\n            values.fill(False)\n            return values",
    "docstring": "Return if each value is NaN."
  },
  {
    "code": "def get_domain_smarthost(self, domainid, serverid):\n        return self.api_call(\n            ENDPOINTS['domainsmarthosts']['get'],\n            dict(domainid=domainid, serverid=serverid))",
    "docstring": "Get a domain smarthost"
  },
  {
    "code": "def encode (text):\n    if isinstance(text, unicode):\n        return text.encode(i18n.default_encoding, 'ignore')\n    return text",
    "docstring": "Encode text with default encoding if its Unicode."
  },
  {
    "code": "def row2table(soup, table, row):\n    tr = Tag(soup, name=\"tr\")\n    table.append(tr)\n    for attr in row:\n        td = Tag(soup, name=\"td\")\n        tr.append(td)\n        td.append(attr)",
    "docstring": "ad a row to the table"
  },
  {
    "code": "def set_pin_retries(ctx, pw_attempts, admin_pin, force):\n    controller = ctx.obj['controller']\n    resets_pins = controller.version < (4, 0, 0)\n    if resets_pins:\n        click.echo('WARNING: Setting PIN retries will reset the values for all '\n                   '3 PINs!')\n    force or click.confirm('Set PIN retry counters to: {} {} {}?'.format(\n        *pw_attempts), abort=True, err=True)\n    controller.set_pin_retries(*(pw_attempts + (admin_pin.encode('utf8'),)))\n    click.echo('PIN retries successfully set.')\n    if resets_pins:\n        click.echo('Default PINs are set.')\n        echo_default_pins()",
    "docstring": "Manage pin-retries.\n\n    Sets the number of attempts available before locking for each PIN.\n\n    PW_ATTEMPTS should be three integer values corresponding to the number of\n    attempts for the PIN, Reset Code, and Admin PIN, respectively."
  },
  {
    "code": "def initialize(self, endog, freq_weights):\n        if (endog.ndim > 1 and endog.shape[1] > 1):\n            y = endog[:, 0]\n            self.n = endog.sum(1)\n            return y*1./self.n, self.n\n        else:\n            return endog, np.ones(endog.shape[0])",
    "docstring": "Initialize the response variable.\n\n        Parameters\n        ----------\n        endog : array\n            Endogenous response variable\n\n        Returns\n        --------\n        If `endog` is binary, returns `endog`\n\n        If `endog` is a 2d array, then the input is assumed to be in the format\n        (successes, failures) and\n        successes/(success + failures) is returned.  And n is set to\n        successes + failures."
  },
  {
    "code": "def parsing(**kwargs):\n    from .validators import Object\n    with _VALIDATOR_FACTORIES_LOCK:\n        old_values = {}\n        for key, value in iteritems(kwargs):\n            if value is not None:\n                attr = key.upper()\n                old_values[key] = getattr(Object, attr)\n                setattr(Object, attr, value)\n        try:\n            yield\n        finally:\n            for key, value in iteritems(kwargs):\n                if value is not None:\n                    setattr(Object, key.upper(), old_values[key])",
    "docstring": "Context manager for overriding the default validator parsing rules for the\n    following code block."
  },
  {
    "code": "def case_us2mc(x):\n    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x)",
    "docstring": "underscore to mixed case notation"
  },
  {
    "code": "def _run_raw(self, cmd, ignore_errors=False):\n    result = os.system(cmd)\n    if result != 0:\n      if ignore_errors:\n        self.log(f\"command ({cmd}) failed.\")\n        assert False, \"_run_raw failed\"",
    "docstring": "Runs command directly, skipping tmux interface"
  },
  {
    "code": "def compute_usage_requirements (self, subvariant):\n        assert isinstance(subvariant, virtual_target.Subvariant)\n        rproperties = subvariant.build_properties ()\n        xusage_requirements =self.evaluate_requirements(\n            self.usage_requirements_, rproperties, \"added\")\n        (r1, r2) = self.generate_dependency_properties(xusage_requirements.dependency (), rproperties)\n        extra = r1 + r2\n        result = property_set.create (xusage_requirements.non_dependency () + extra)\n        properties = []\n        for p in subvariant.sources_usage_requirements().all():\n            if p.feature.name not in ('pch-header', 'pch-file'):\n                properties.append(p)\n        if 'shared' in rproperties.get('link'):\n            new_properties = []\n            for p in properties:\n                if p.feature.name != 'library':\n                    new_properties.append(p)\n            properties = new_properties\n        result = result.add_raw(properties)\n        return result",
    "docstring": "Given the set of generated targets, and refined build\n            properties, determines and sets appripriate usage requirements\n            on those targets."
  },
  {
    "code": "def _is_allowed_command(self, command):\n        cmds = self._meta_data['allowed_commands']\n        if command not in self._meta_data['allowed_commands']:\n            error_message = \"The command value {0} does not exist. \" \\\n                            \"Valid commands are {1}\".format(command, cmds)\n            raise InvalidCommand(error_message)",
    "docstring": "Checking if the given command is allowed on a given endpoint."
  },
  {
    "code": "def process_non_raw_string_token(self, prefix, string_body, start_row):\n        if 'u' in prefix:\n            if string_body.find('\\\\0') != -1:\n                self.add_message('null-byte-unicode-literal', line=start_row)",
    "docstring": "check for bad escapes in a non-raw string.\n\n        prefix: lowercase string of eg 'ur' string prefix markers.\n        string_body: the un-parsed body of the string, not including the quote\n        marks.\n        start_row: integer line number in the source."
  },
  {
    "code": "def lee_yeast_ChIP(data_set='lee_yeast_ChIP'):\n    if not data_available(data_set):\n        download_data(data_set)\n    from pandas import read_csv\n    dir_path = os.path.join(data_path, data_set)\n    filename = os.path.join(dir_path, 'binding_by_gene.tsv')\n    S = read_csv(filename, header=1, index_col=0, sep='\\t')\n    transcription_factors = [col for col in S.columns if col[:7] != 'Unnamed']\n    annotations = S[['Unnamed: 1', 'Unnamed: 2', 'Unnamed: 3']]\n    S = S[transcription_factors]\n    return data_details_return({'annotations' : annotations, 'Y' : S, 'transcription_factors': transcription_factors}, data_set)",
    "docstring": "Yeast ChIP data from Lee et al."
  },
  {
    "code": "def isinstance_(x, A_tuple):\n    if is_union(A_tuple):\n        return any(isinstance_(x, t) for t in A_tuple.__args__)\n    elif getattr(A_tuple, '__origin__', None) is not None:\n        return isinstance(x, A_tuple.__origin__)\n    else:\n        return isinstance(x, A_tuple)",
    "docstring": "native isinstance_ with the test for typing.Union overridden"
  },
  {
    "code": "def assure_container(fnc):\n    @wraps(fnc)\n    def _wrapped(self, container, *args, **kwargs):\n        if not isinstance(container, Container):\n            container = self.get(container)\n        return fnc(self, container, *args, **kwargs)\n    return _wrapped",
    "docstring": "Assures that whether a Container or a name of a container is passed, a\n    Container object is available."
  },
  {
    "code": "def add_root_log(self, log_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.add_root_catalog(catalog_id=log_id)\n        return self._hierarchy_session.add_root(id_=log_id)",
    "docstring": "Adds a root log.\n\n        arg:    log_id (osid.id.Id): the ``Id`` of a log\n        raise:  AlreadyExists - ``log_id`` is already in hierarchy\n        raise:  NotFound - ``log_id`` is not found\n        raise:  NullArgument - ``log_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_url(self, url_or_dict):\n        if isinstance(url_or_dict, basestring):\n            url_or_dict = {'viewname': url_or_dict}\n        try:\n            return reverse(**url_or_dict)\n        except NoReverseMatch:\n            if MENU_DEBUG:\n                print >>stderr,'Unable to reverse URL with kwargs %s' % url_or_dict",
    "docstring": "Returns the reversed url given a string or dict and prints errors if MENU_DEBUG is enabled"
  },
  {
    "code": "def get_comments_by_book(self, book_id):\n        mgr = self._get_provider_manager('COMMENTING', local=True)\n        lookup_session = mgr.get_comment_lookup_session_for_book(book_id, proxy=self._proxy)\n        lookup_session.use_isolated_book_view()\n        return lookup_session.get_comments()",
    "docstring": "Gets the list of ``Comments`` associated with a ``Book``.\n\n        arg:    book_id (osid.id.Id): ``Id`` of a ``Book``\n        return: (osid.commenting.CommentList) - list of related comments\n        raise:  NotFound - ``book_id`` is not found\n        raise:  NullArgument - ``book_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def convert_from_ik_angles(self, joints):\n        if len(joints) != len(self.motors) + 2:\n            raise ValueError('Incompatible data, len(joints) should be {}!'.format(len(self.motors) + 2))\n        joints = [rad2deg(j) for j in joints[1:-1]]\n        joints *= self._reversed\n        return [(j * (1 if m.direct else -1)) - m.offset\n                for j, m in zip(joints, self.motors)]",
    "docstring": "Convert from IKPY internal representation to poppy representation."
  },
  {
    "code": "def create_feature_layer(ds, sql, name=\"layer\"):\n    if arcpyFound == False:\n        raise Exception(\"ArcPy is required to use this function\")\n    result = arcpy.MakeFeatureLayer_management(in_features=ds,\n                                               out_layer=name,\n                                               where_clause=sql)\n    return result[0]",
    "docstring": "creates a feature layer object"
  },
  {
    "code": "def list_machines(self):\n        for page in self._request('Machines.List'):\n            for machine in page.get('machines', []):\n                yield Machine(data=machine)",
    "docstring": "Retrieve a list of machines in the fleet cluster\n\n        Yields:\n            Machine: The next machine in the cluster\n\n        Raises:\n            fleet.v1.errors.APIError: Fleet returned a response code >= 400"
  },
  {
    "code": "def _load_all_bookmarks():\n    slots = CONF.get('editor', 'bookmarks', {})\n    for slot_num in list(slots.keys()):\n        if not osp.isfile(slots[slot_num][0]):\n            slots.pop(slot_num)\n    return slots",
    "docstring": "Load all bookmarks from config."
  },
  {
    "code": "def AuthenticatedOrRedirect(invocation):\n    class AuthenticatedOrRedirect(GiottoInputMiddleware):\n        def http(self, request):\n            if request.user:\n                return request\n            return Redirection(invocation)\n        def cmd(self, request):\n            if request.user:\n                return request\n            return Redirection(invocation)\n    return AuthenticatedOrRedirect",
    "docstring": "Middleware class factory that redirects if the user is not logged in.\n    Otherwise, nothing is effected."
  },
  {
    "code": "def hasannotation(self,Class,set=None):\n        return sum( 1 for _ in self.select(Class,set,True,default_ignore_annotations))",
    "docstring": "Returns an integer indicating whether such as annotation exists, and if so, how many.\n\n        See :meth:`AllowTokenAnnotation.annotations`` for a description of the parameters."
  },
  {
    "code": "def _on_io_events(self, fd=None, _events=None):\n        if fd not in self._connections:\n            LOGGER.warning('Received IO event for non-existing connection')\n            return\n        self._poll_connection(fd)",
    "docstring": "Invoked by Tornado's IOLoop when there are events for the fd\n\n        :param int fd: The file descriptor for the event\n        :param int _events: The events raised"
  },
  {
    "code": "def after_this_request(func: Callable) -> Callable:\n    _request_ctx_stack.top._after_request_functions.append(func)\n    return func",
    "docstring": "Schedule the func to be called after the current request.\n\n    This is useful in situations whereby you want an after request\n    function for a specific route or circumstance only, for example,\n\n    .. code-block:: python\n\n        def index():\n            @after_this_request\n            def set_cookie(response):\n                response.set_cookie('special', 'value')\n                return response\n\n            ..."
  },
  {
    "code": "def get_area_info(bbox, date_interval, maxcc=None):\n    result_list = search_iter(bbox=bbox, start_date=date_interval[0], end_date=date_interval[1])\n    if maxcc:\n        return reduce_by_maxcc(result_list, maxcc)\n    return result_list",
    "docstring": "Get information about all images from specified area and time range\n\n    :param bbox: bounding box of requested area\n    :type bbox: geometry.BBox\n    :param date_interval: a pair of time strings in ISO8601 format\n    :type date_interval: tuple(str)\n    :param maxcc: filter images by maximum percentage of cloud coverage\n    :type maxcc: float in range [0, 1] or None\n    :return: list of dictionaries containing info provided by Opensearch REST service\n    :rtype: list(dict)"
  },
  {
    "code": "def unique_event_labels(event_list):\n    if isinstance(event_list, dcase_util.containers.MetaDataContainer):\n        return event_list.unique_event_labels\n    else:\n        labels = []\n        for event in event_list:\n            if 'event_label' in event and event['event_label'] not in labels:\n                labels.append(event['event_label'])\n        labels.sort()\n        return labels",
    "docstring": "Find the unique event labels\n\n    Parameters\n    ----------\n    event_list : list or dcase_util.containers.MetaDataContainer\n        A list containing event dicts\n\n    Returns\n    -------\n    list\n        Unique labels in alphabetical order"
  },
  {
    "code": "def get_sections_by_curriculum_and_term(curriculum, term):\n    url = \"{}?{}\".format(\n        section_res_url_prefix,\n        urlencode([(\"curriculum_abbreviation\", curriculum.label,),\n                   (\"quarter\", term.quarter.lower(),),\n                   (\"year\", term.year,), ]))\n    return _json_to_sectionref(get_resource(url))",
    "docstring": "Returns a list of uw_sws.models.SectionReference objects\n    for the passed curriculum and term."
  },
  {
    "code": "def from_inline(cls: Type[ESUserEndpointType], inline: str) -> ESUserEndpointType:\n        m = ESUserEndpoint.re_inline.match(inline)\n        if m is None:\n            raise MalformedDocumentError(ESUserEndpoint.API)\n        server = m.group(1)\n        port = int(m.group(2))\n        return cls(server, port)",
    "docstring": "Return ESUserEndpoint instance from endpoint string\n\n        :param inline: Endpoint string\n        :return:"
  },
  {
    "code": "def to_json_file(self, path, file_name=None):\n        if bool(path) and os.path.isdir(path):\n            self.write_to_json(path, file_name)\n        else:\n            self.write_to_json(os.getcwd(), file_name)",
    "docstring": "Writes output to a JSON file with the given file name"
  },
  {
    "code": "def session(self) -> SessionT:\n        session = self._session_class()(\n            connection_pool=self._connection_pool,\n        )\n        self.event_dispatcher.notify(self.ClientEvent.new_session, session)\n        return session",
    "docstring": "Return a new session."
  },
  {
    "code": "def currencies(self):\n        return [m.currency.code for m in self.monies() if m.amount]",
    "docstring": "Get all currencies with non-zero values"
  },
  {
    "code": "def get_language(query: str) -> str:\n    query = query.lower()\n    for language in LANGUAGES:\n        if query.endswith(language):\n            return language\n    return ''",
    "docstring": "Tries to work out the highlight.js language of a given file name or\n    shebang. Returns an empty string if none match."
  },
  {
    "code": "def ci_plot(x, arr, conf=0.95, ax=None, line_kwargs=None, fill_kwargs=None):\n    if ax is None:\n        fig = plt.figure()\n        ax = fig.add_subplot(111)\n    line_kwargs = line_kwargs or {}\n    fill_kwargs = fill_kwargs or {}\n    m, lo, hi = ci(arr, conf)\n    ax.plot(x, m, **line_kwargs)\n    ax.fill_between(x, lo, hi, **fill_kwargs)\n    return ax",
    "docstring": "Plots the mean and 95% ci for the given array on the given axes\n\n    Parameters\n    ----------\n    x : 1-D array-like\n        x values for the plot\n\n    arr : 2-D array-like\n        The array to calculate mean and std for\n\n    conf : float [.5 - 1]\n        Confidence interval to use\n\n    ax : matplotlib.Axes\n        The axes object on which to plot\n\n    line_kwargs : dict\n        Additional kwargs passed to Axes.plot\n\n    fill_kwargs : dict\n        Additiona kwargs passed to Axes.fill_between"
  },
  {
    "code": "def sync(self, recursive=False):\r\n        self.syncTree(recursive=recursive)\r\n        self.syncView(recursive=recursive)",
    "docstring": "Syncs the information from this item to the tree and view."
  },
  {
    "code": "def serialize(\n            self,\n            value,\n            state\n    ):\n        start_element, end_element = _element_path_create_new(self.element_path)\n        self._serialize(end_element, value, state)\n        return start_element",
    "docstring": "Serialize the value into a new element object and return the element.\n\n        If the omit_empty option was specified and the value is falsey, then this will return None."
  },
  {
    "code": "def statement(self) -> Statement:\n        pref, kw = self.keyword()\n        pres = self.opt_separator()\n        next = self.peek()\n        if next == \";\":\n            arg = None\n            sub = False\n        elif next == \"{\":\n            arg = None\n            sub = True\n        elif not pres:\n            raise UnexpectedInput(self, \"separator\")\n        else:\n            self._arg = \"\"\n            sub = self.argument()\n            arg = self._arg\n        self.offset += 1\n        res = Statement(kw, arg, pref=pref)\n        if sub:\n            res.substatements = self.substatements()\n            for sub in res.substatements:\n                sub.superstmt = res\n        return res",
    "docstring": "Parse YANG statement.\n\n        Raises:\n            EndOfInput: If past the end of input.\n            UnexpectedInput: If no syntactically correct statement is found."
  },
  {
    "code": "def update_masters(self):\n        if self.master is not None:\n            self.master._medium2long.update(self._medium2long)\n            self.master.update_masters()",
    "docstring": "Update all `master` |Substituter| objects.\n\n        If a |Substituter| object is passed to the constructor of another\n        |Substituter| object, they become `master` and `slave`:\n\n        >>> from hydpy.core.autodoctools import Substituter\n        >>> sub1 = Substituter()\n        >>> from hydpy.core import devicetools\n        >>> sub1.add_module(devicetools)\n        >>> sub2 = Substituter(sub1)\n        >>> sub3 = Substituter(sub2)\n        >>> sub3.master.master is sub1\n        True\n        >>> sub2 in sub1.slaves\n        True\n\n        During initialization, all mappings handled by the master object\n        are passed to its new slave:\n\n        >>> sub3.find('Node|')\n        |Node| :class:`~hydpy.core.devicetools.Node`\n        |devicetools.Node| :class:`~hydpy.core.devicetools.Node`\n\n        Updating a slave, does not affect its master directly:\n\n        >>> from hydpy.core import hydpytools\n        >>> sub3.add_module(hydpytools)\n        >>> sub3.find('HydPy|')\n        |HydPy| :class:`~hydpy.core.hydpytools.HydPy`\n        |hydpytools.HydPy| :class:`~hydpy.core.hydpytools.HydPy`\n        >>> sub2.find('HydPy|')\n\n        Through calling |Substituter.update_masters|, the `medium2long`\n        mappings are passed from the slave to its master:\n\n        >>> sub3.update_masters()\n        >>> sub2.find('HydPy|')\n        |hydpytools.HydPy| :class:`~hydpy.core.hydpytools.HydPy`\n\n        Then each master object updates its own master object also:\n\n        >>> sub1.find('HydPy|')\n        |hydpytools.HydPy| :class:`~hydpy.core.hydpytools.HydPy`\n\n        In reverse, subsequent updates of master objects to not affect\n        their slaves directly:\n\n        >>> from hydpy.core import masktools\n        >>> sub1.add_module(masktools)\n        >>> sub1.find('Masks|')\n        |Masks| :class:`~hydpy.core.masktools.Masks`\n        |masktools.Masks| :class:`~hydpy.core.masktools.Masks`\n        >>> sub2.find('Masks|')\n\n        Through calling |Substituter.update_slaves|, the `medium2long`\n        mappings are passed the master to all of its slaves:\n\n        >>> sub1.update_slaves()\n        >>> sub2.find('Masks|')\n        |masktools.Masks| :class:`~hydpy.core.masktools.Masks`\n        >>> sub3.find('Masks|')\n        |masktools.Masks| :class:`~hydpy.core.masktools.Masks`"
  },
  {
    "code": "def window_size(self, window_size):\n        BasePlotter.window_size.fset(self, window_size)\n        self.app_window.setBaseSize(*window_size)",
    "docstring": "set the render window size"
  },
  {
    "code": "def bounding_polygon(self):\n        lon_left, lat_bottom, lon_right, lat_top = Tile.tile_coords_to_bbox(self.x, self.y, self.zoom)\n        print(lon_left, lat_bottom, lon_right, lat_top)\n        return Polygon([[[lon_left, lat_top],\n                       [lon_right, lat_top],\n                       [lon_right, lat_bottom],\n                       [lon_left, lat_bottom],\n                       [lon_left, lat_top]]])",
    "docstring": "Returns the bounding box polygon for this tile\n\n        :return: `pywom.utils.geo.Polygon` instance"
  },
  {
    "code": "def connection_key(self):\n        return \"{host}:{namespace}:{username}\".format(host=self.host, namespace=self.namespace, username=self.username)",
    "docstring": "Return an index key used to cache the sampler connection."
  },
  {
    "code": "def split_query(qs, keep_blank_values=False):\n    items = []\n    for pair in qs.split('&'):\n        name, delim, value = pair.partition('=')\n        if not delim and keep_blank_values:\n            value = None\n        if keep_blank_values or value:\n            items.append((name, value))\n    return items",
    "docstring": "Split the query string.\n\n    Note for empty values: If an equal sign (``=``) is present, the value\n    will be an empty string (``''``). Otherwise, the value will be ``None``::\n\n        >>> list(split_query('a=&b', keep_blank_values=True))\n        [('a', ''), ('b', None)]\n\n    No processing is done on the actual values."
  },
  {
    "code": "def get_relation_routes(self, viewset):\n        routes = []\n        if not hasattr(viewset, 'serializer_class'):\n            return routes\n        if not hasattr(viewset, 'list_related'):\n            return routes\n        serializer = viewset.serializer_class()\n        fields = getattr(serializer, 'get_link_fields', lambda: [])()\n        route_name = '{basename}-{methodnamehyphen}'\n        for field_name, field in six.iteritems(fields):\n            methodname = 'list_related'\n            url = (\n                r'^{prefix}/{lookup}/(?P<field_name>%s)'\n                '{trailing_slash}$' % field_name\n            )\n            routes.append(Route(\n                url=url,\n                mapping={'get': methodname},\n                name=replace_methodname(route_name, field_name),\n                initkwargs={}\n            ))\n        return routes",
    "docstring": "Generate routes to serve relational objects. This method will add\n        a sub-URL for each relational field.\n\n        e.g.\n        A viewset for the following serializer:\n\n          class UserSerializer(..):\n              events = DynamicRelationField(EventSerializer, many=True)\n              groups = DynamicRelationField(GroupSerializer, many=True)\n              location = DynamicRelationField(LocationSerializer)\n\n        will have the following URLs added:\n\n          /users/<pk>/events/\n          /users/<pk>/groups/\n          /users/<pk>/location/"
  },
  {
    "code": "def interpolate(self, factor, minGlyph, maxGlyph,\n                    round=True, suppressError=True):\n        factor = normalizers.normalizeInterpolationFactor(factor)\n        if not isinstance(minGlyph, BaseGlyph):\n            raise TypeError((\"Interpolation to an instance of %r can not be \"\n                             \"performed from an instance of %r.\")\n                            % (self.__class__.__name__,\n                               minGlyph.__class__.__name__))\n        if not isinstance(maxGlyph, BaseGlyph):\n            raise TypeError((\"Interpolation to an instance of %r can not be \"\n                             \"performed from an instance of %r.\")\n                            % (self.__class__.__name__,\n                               maxGlyph.__class__.__name__))\n        round = normalizers.normalizeBoolean(round)\n        suppressError = normalizers.normalizeBoolean(suppressError)\n        self._interpolate(factor, minGlyph, maxGlyph,\n                          round=round, suppressError=suppressError)",
    "docstring": "Interpolate the contents of this glyph at location ``factor``\n        in a linear interpolation between ``minGlyph`` and ``maxGlyph``.\n\n            >>> glyph.interpolate(0.5, otherGlyph1, otherGlyph2)\n\n        ``factor`` may be a :ref:`type-int-float` or a tuple containing\n        two :ref:`type-int-float` values representing x and y factors.\n\n            >>> glyph.interpolate((0.5, 1.0), otherGlyph1, otherGlyph2)\n\n        ``minGlyph`` must be a :class:`BaseGlyph` and will be located at 0.0\n        in the interpolation range. ``maxGlyph`` must be a :class:`BaseGlyph`\n        and will be located at 1.0 in the interpolation range. If ``round``\n        is ``True``, the contents of the glyph will be rounded to integers\n        after the interpolation is performed.\n\n            >>> glyph.interpolate(0.5, otherGlyph1, otherGlyph2, round=True)\n\n        This method assumes that ``minGlyph`` and ``maxGlyph`` are completely\n        compatible with each other for interpolation. If not, any errors\n        encountered will raise a :class:`FontPartsError`. If ``suppressError``\n        is ``True``, no exception will be raised and errors will be silently\n        ignored."
  },
  {
    "code": "def copy_signal(signal_glob, source_db, target_db):\n    for frame in source_db.frames:\n        for signal in frame.glob_signals(signal_glob):\n            target_db.add_signal(signal)",
    "docstring": "Copy Signals identified by name from source CAN matrix to target CAN matrix.\n    In target CanMatrix the signal is put without frame, just on top level.\n\n    :param signal_glob: Signal glob pattern\n    :param source_db: Source CAN matrix\n    :param target_db: Destination CAN matrix"
  },
  {
    "code": "def to_bool(val):\n    if val is None:\n        return False\n    if isinstance(val, bool):\n        return val\n    if isinstance(val, (six.text_type, six.string_types)):\n        return val.lower() in ('yes', '1', 'true')\n    if isinstance(val, six.integer_types):\n        return val > 0\n    if not isinstance(val, collections.Hashable):\n        return bool(val)\n    return False",
    "docstring": "Returns the logical value.\n\n    .. code-block:: jinja\n\n        {{ 'yes' | to_bool }}\n\n    will be rendered as:\n\n    .. code-block:: text\n\n        True"
  },
  {
    "code": "def visit_Tuple(self, node):\n        if node.elts:\n            elts_aliases = set()\n            for i, elt in enumerate(node.elts):\n                elt_aliases = self.visit(elt)\n                elts_aliases.update(ContainerOf(alias, i)\n                                    for alias in elt_aliases)\n        else:\n            elts_aliases = None\n        return self.add(node, elts_aliases)",
    "docstring": "A tuple is abstracted as an ordered container of its values\n\n        >>> from pythran import passmanager\n        >>> pm = passmanager.PassManager('demo')\n        >>> module = ast.parse('def foo(a, b): return a, b')\n        >>> result = pm.gather(Aliases, module)\n        >>> Aliases.dump(result, filter=ast.Tuple)\n        (a, b) => ['|[0]=a|', '|[1]=b|']\n\n        where the |[i]=id| notation means something that\n        may contain ``id`` at index ``i``."
  },
  {
    "code": "def render_to_string(template_name, context=None, request=None, using=None):\n    if isinstance(template_name, (list, tuple)):\n        template = select_template(template_name, using=using)\n    else:\n        template = get_template(template_name, using=using)\n    return template.render(context, request)",
    "docstring": "Loads a template and renders it with a context. Returns a string.\n    template_name may be a string or a list of strings."
  },
  {
    "code": "def connect(self, address, rack, slot, tcpport=102):\n        logger.info(\"connecting to %s:%s rack %s slot %s\" % (address, tcpport,\n                                                             rack, slot))\n        self.set_param(snap7.snap7types.RemotePort, tcpport)\n        return self.library.Cli_ConnectTo(\n            self.pointer, c_char_p(six.b(address)),\n            c_int(rack), c_int(slot))",
    "docstring": "Connect to a S7 server.\n\n        :param address: IP address of server\n        :param rack: rack on server\n        :param slot: slot on server."
  },
  {
    "code": "def ResolveForCreate(self, document):\n        if document is None:\n            raise ValueError(\"document is None.\")\n        partition_key = self.partition_key_extractor(document)\n        containing_range = self._GetContainingRange(partition_key)\n        if containing_range is None:\n            raise ValueError(\"A containing range for \" + str(partition_key) + \" doesn't exist in the partition map.\")\n        return self.partition_map.get(containing_range)",
    "docstring": "Resolves the collection for creating the document based on the partition key.\n\n        :param dict document:\n            The document to be created.\n\n        :return:\n            Collection Self link or Name based link which should handle the Create operation.\n        :rtype:\n            str"
  },
  {
    "code": "def safe_for_serialization(value):\n    if isinstance(value, six.string_types):\n        return value\n    if isinstance(value, dict):\n        return {\n            safe_for_serialization(key): safe_for_serialization(val)\n            for key, val in six.iteritems(value)\n        }\n    if isinstance(value, collections.Iterable):\n        return list(map(safe_for_serialization, value))\n    try:\n        return six.text_type(value)\n    except Exception:\n        return '[__unicode__ failed]'",
    "docstring": "Transform a value in preparation for serializing as json\n\n    no-op for strings, mappings and iterables have their entries made safe,\n    and all other values are stringified, with a fallback value if that fails"
  },
  {
    "code": "def WriteGraphSeries(graph_series,\n                     label,\n                     token = None):\n  if data_store.RelationalDBEnabled():\n    data_store.REL_DB.WriteClientGraphSeries(graph_series, label)\n  if _ShouldUseLegacyDatastore():\n    aff4_attr = _GetAFF4AttributeForReportType(graph_series.report_type)()\n    if isinstance(aff4_attr, rdf_stats.GraphSeries):\n      for graph in graph_series.graphs:\n        aff4_attr.Append(graph)\n    elif isinstance(aff4_attr, rdf_stats.Graph):\n      for sample in graph_series.graphs[0]:\n        aff4_attr.Append(x_value=sample.x_value, y_value=sample.y_value)\n    else:\n      raise AFF4AttributeTypeError(aff4_attr.__class__)\n    with aff4.FACTORY.Create(\n        GetAFF4ClientReportsURN().Add(label),\n        aff4_type=aff4_stats.ClientFleetStats,\n        mode=\"w\",\n        token=token) as stats_for_label:\n      stats_for_label.AddAttribute(aff4_attr)",
    "docstring": "Writes graph series for a particular client label to the DB.\n\n  Args:\n    graph_series: A series of rdf_stats.Graphs containing aggregated data for a\n      particular report-type.\n    label: Client label by which data in the graph_series was aggregated.\n    token: ACL token to use for writing to the legacy (non-relational)\n      datastore.\n\n  Raises:\n    AFF4AttributeTypeError: If, when writing to the legacy DB, an unexpected\n    report-data type is encountered."
  },
  {
    "code": "def _row_from_frevent(frevent, columns, selection):\n    params = dict(frevent.GetParam())\n    params['time'] = float(LIGOTimeGPS(*frevent.GetGTime()))\n    params['amplitude'] = frevent.GetAmplitude()\n    params['probability'] = frevent.GetProbability()\n    params['timeBefore'] = frevent.GetTimeBefore()\n    params['timeAfter'] = frevent.GetTimeAfter()\n    params['comment'] = frevent.GetComment()\n    if not all(op_(params[c], t) for c, op_, t in selection):\n        return None\n    return [params[c] for c in columns]",
    "docstring": "Generate a table row from an FrEvent\n\n    Filtering (``selection``) is done here, rather than in the table reader,\n    to enable filtering on columns that aren't being returned."
  },
  {
    "code": "def git_ls_remote(self, uri, ref):\n        logger.debug(\"Invoking git to retrieve commit id for repo %s...\", uri)\n        lsremote_output = subprocess.check_output(['git',\n                                                   'ls-remote',\n                                                   uri,\n                                                   ref])\n        if b\"\\t\" in lsremote_output:\n            commit_id = lsremote_output.split(b\"\\t\")[0]\n            logger.debug(\"Matching commit id found: %s\", commit_id)\n            return commit_id\n        else:\n            raise ValueError(\"Ref \\\"%s\\\" not found for repo %s.\" % (ref, uri))",
    "docstring": "Determine the latest commit id for a given ref.\n\n        Args:\n            uri (string): git URI\n            ref (string): git ref\n\n        Returns:\n            str: A commit id"
  },
  {
    "code": "def _aggregations(search, definitions):\n    if definitions:\n        for name, agg in definitions.items():\n            search.aggs[name] = agg if not callable(agg) else agg()\n    return search",
    "docstring": "Add aggregations to query."
  },
  {
    "code": "def init_nvidia(self):\n        if import_error_tag:\n            self.nvml_ready = False\n        try:\n            pynvml.nvmlInit()\n            self.device_handles = get_device_handles()\n            self.nvml_ready = True\n        except Exception:\n            logger.debug(\"pynvml could not be initialized.\")\n            self.nvml_ready = False\n        return self.nvml_ready",
    "docstring": "Init the NVIDIA API."
  },
  {
    "code": "def set_completion(self, completion):\n        if self.get_completion_metadata().is_read_only():\n            raise errors.NoAccess()\n        try:\n            completion = float(completion)\n        except ValueError:\n            raise errors.InvalidArgument()\n        if not self._is_valid_decimal(completion, self.get_completion_metadata()):\n            raise errors.InvalidArgument()\n        self._my_map['completion'] = completion",
    "docstring": "Sets the completion percentage.\n\n        arg:    completion (decimal): the completion percentage\n        raise:  InvalidArgument - ``completion`` is invalid\n        raise:  NoAccess - ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def StartHunt(hunt_id):\n  hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)\n  num_hunt_clients = data_store.REL_DB.CountHuntFlows(hunt_id)\n  if hunt_obj.hunt_state != hunt_obj.HuntState.PAUSED:\n    raise OnlyPausedHuntCanBeStartedError(hunt_obj)\n  data_store.REL_DB.UpdateHuntObject(\n      hunt_id,\n      hunt_state=hunt_obj.HuntState.STARTED,\n      start_time=rdfvalue.RDFDatetime.Now(),\n      num_clients_at_start_time=num_hunt_clients,\n  )\n  hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)\n  if hunt_obj.args.hunt_type == hunt_obj.args.HuntType.STANDARD:\n    _ScheduleGenericHunt(hunt_obj)\n  elif hunt_obj.args.hunt_type == hunt_obj.args.HuntType.VARIABLE:\n    _ScheduleVariableHunt(hunt_obj)\n  else:\n    raise UnknownHuntTypeError(\"Invalid hunt type for hunt %s: %r\" %\n                               (hunt_id, hunt_obj.args.hunt_type))\n  return hunt_obj",
    "docstring": "Starts a hunt with a given id."
  },
  {
    "code": "def as_ul(self, show_leaf=True, current_linkable=False, class_current=\"active_link\"):\n        return self.__do_menu(\"as_ul\", show_leaf, current_linkable, class_current)",
    "docstring": "It returns breadcrumb as ul"
  },
  {
    "code": "def ssh_known_host_key(host, application_name, user=None):\n    cmd = [\n        'ssh-keygen',\n        '-f', known_hosts(application_name, user),\n        '-H',\n        '-F',\n        host]\n    try:\n        output = subprocess.check_output(cmd)\n    except subprocess.CalledProcessError as e:\n        if e.returncode == 1:\n            output = e.output\n        else:\n            raise\n    output = output.strip()\n    if output:\n        lines = output.split('\\n')\n        if len(lines) >= 1:\n            return lines[0]\n    return None",
    "docstring": "Return the first entry in known_hosts for host.\n\n    :param host: hostname to lookup in file.\n    :type host: str\n    :param application_name: Name of application eg nova-compute-something\n    :type application_name: str\n    :param user: The user that the ssh asserts are for.\n    :type user: str\n    :returns: Host key\n    :rtype: str or None"
  },
  {
    "code": "def blockmix_salsa8(BY, Yi, r):\n    start = (2 * r - 1) * 16\n    X = BY[start:start+16]\n    tmp = [0]*16\n    for i in xrange(2 * r):\n        salsa20_8(X, tmp, BY, i * 16, BY, Yi + i*16)\n    for i in xrange(r):\n        BY[i * 16:(i * 16)+(16)] = BY[Yi + (i * 2) * 16:(Yi + (i * 2) * 16)+(16)]\n        BY[(i + r) * 16:((i + r) * 16)+(16)] = BY[Yi + (i*2 + 1) * 16:(Yi + (i*2 + 1) * 16)+(16)]",
    "docstring": "Blockmix; Used by SMix"
  },
  {
    "code": "def count_rows_duplicates(self, table, cols='*'):\n        return self.count_rows(table, '*') - self.count_rows_distinct(table, cols)",
    "docstring": "Get the number of rows that do not contain distinct values."
  },
  {
    "code": "def reverseComplement(self, isRNA=None):\n    isRNA_l = self.isRNA() if isRNA is None else isRNA\n    tmp = \"\"\n    for n in self.sequenceData:\n      if isRNA_l:\n        tmp += RNA_COMPLEMENTS[n]\n      else:\n        tmp += DNA_COMPLEMENTS[n]\n    self.sequenceData = tmp[::-1]",
    "docstring": "Reverse complement this sequence in-place.\n\n      :param isRNA: if True, treat this sequence as RNA. If False, treat it as\n                    DNA. If None (default), inspect the sequence and make a\n                    guess as to whether it is RNA or DNA."
  },
  {
    "code": "def catchable_exceptions(exceptions):\n    if isinstance(exceptions, type) and issubclass(exceptions, BaseException):\n        return True\n    if (\n        isinstance(exceptions, tuple)\n        and exceptions\n        and all(issubclass(it, BaseException) for it in exceptions)\n    ):\n        return True\n    return False",
    "docstring": "Returns True if exceptions can be caught in the except clause.\n\n    The exception can be caught if it is an Exception type or a tuple of\n    exception types."
  },
  {
    "code": "def patch_django_for_autodoc():\n    ManagerDescriptor.__get__ = lambda self, *args, **kwargs: self.manager\n    models.QuerySet.__repr__ = lambda self: self.__class__.__name__",
    "docstring": "Fix the appearance of some classes in autodoc.\n\n    This avoids query evaluation."
  },
  {
    "code": "def listen_for_updates(self):\n        self.toredis.subscribe(self.group_pubsub, callback=self.callback)",
    "docstring": "Attach a callback on the group pubsub"
  },
  {
    "code": "def component_for_entity(self, entity: int, component_type: Type[C]) -> C:\n        return self._entities[entity][component_type]",
    "docstring": "Retrieve a Component instance for a specific Entity.\n\n        Retrieve a Component instance for a specific Entity. In some cases,\n        it may be necessary to access a specific Component instance.\n        For example: directly modifying a Component to handle user input.\n\n        Raises a KeyError if the given Entity and Component do not exist.\n        :param entity: The Entity ID to retrieve the Component for.\n        :param component_type: The Component instance you wish to retrieve.\n        :return: The Component instance requested for the given Entity ID."
  },
  {
    "code": "def _default_logfile(exe_name):\n    if salt.utils.platform.is_windows():\n        tmp_dir = os.path.join(__opts__['cachedir'], 'tmp')\n        if not os.path.isdir(tmp_dir):\n            os.mkdir(tmp_dir)\n        logfile_tmp = tempfile.NamedTemporaryFile(dir=tmp_dir,\n                                                  prefix=exe_name,\n                                                  suffix='.log',\n                                                  delete=False)\n        logfile = logfile_tmp.name\n        logfile_tmp.close()\n    else:\n        logfile = salt.utils.path.join(\n            '/var/log',\n            '{0}.log'.format(exe_name)\n        )\n    return logfile",
    "docstring": "Retrieve the logfile name"
  },
  {
    "code": "def check_webserver_running(url=\"http://localhost:8800\", max_retries=30):\n    retry = 0\n    response = ''\n    success = False\n    while response != requests.codes.ok and retry < max_retries:\n        try:\n            response = requests.head(url, allow_redirects=True).status_code\n            success = True\n        except:\n            sleep(1)\n        retry += 1\n    if not success:\n        logging.warning('Unable to connect to %s within %s retries'\n                     % (url, max_retries))\n    return success",
    "docstring": "Returns True if a given URL is responding within a given timeout."
  },
  {
    "code": "def iter_block_items(self):\n        block_item_tags = (qn('w:p'), qn('w:tbl'), qn('w:sdt'))\n        for child in self:\n            if child.tag in block_item_tags:\n                yield child",
    "docstring": "Generate a reference to each of the block-level content elements in\n        this cell, in the order they appear."
  },
  {
    "code": "def lock(self, resource, label='', expire=60, patience=60):\n        queue = Queue(client=self.client, resource=resource)\n        with queue.draw(label=label, expire=expire) as number:\n            queue.wait(number=number, patience=patience)\n            yield\n        queue.close()",
    "docstring": "Lock a resource.\n\n        :param resource: String corresponding to resource type\n        :param label: String label to attach\n        :param expire: int seconds\n        :param patience: int seconds"
  },
  {
    "code": "def _callUpgradeAgent(self, ev_data, failTimeout) -> None:\n        logger.info(\"{}'s upgrader calling agent for upgrade\".format(self))\n        self._actionLog.append_started(ev_data)\n        self._action_start_callback()\n        self.scheduledAction = None\n        asyncio.ensure_future(\n            self._sendUpgradeRequest(ev_data, failTimeout))",
    "docstring": "Callback which is called when upgrade time come.\n        Writes upgrade record to upgrade log and asks\n        node control service to perform upgrade\n\n        :param when: upgrade time\n        :param version: version to upgrade to"
  },
  {
    "code": "def error_wrapper(error, errorClass):\n    http_status = 0\n    if error.check(TwistedWebError):\n        xml_payload = error.value.response\n        if error.value.status:\n            http_status = int(error.value.status)\n    else:\n        error.raiseException()\n    if http_status >= 400:\n        if not xml_payload:\n            error.raiseException()\n        try:\n            fallback_error = errorClass(\n                xml_payload, error.value.status, str(error.value),\n                error.value.response)\n        except (ParseError, AWSResponseParseError):\n            error_message = http.RESPONSES.get(http_status)\n            fallback_error = TwistedWebError(\n                http_status, error_message, error.value.response)\n        raise fallback_error\n    elif 200 <= http_status < 300:\n        return str(error.value)\n    else:\n        error.raiseException()",
    "docstring": "We want to see all error messages from cloud services. Amazon's EC2 says\n    that their errors are accompanied either by a 400-series or 500-series HTTP\n    response code. As such, the first thing we want to do is check to see if\n    the error is in that range. If it is, we then need to see if the error\n    message is an EC2 one.\n\n    In the event that an error is not a Twisted web error nor an EC2 one, the\n    original exception is raised."
  },
  {
    "code": "def check_is_dataarray(comp):\n    r\n    @wraps(comp)\n    def func(data_array, *args, **kwds):\n        assert isinstance(data_array, xr.DataArray)\n        return comp(data_array, *args, **kwds)\n    return func",
    "docstring": "r\"\"\"Decorator to check that a computation has an instance of xarray.DataArray\n     as first argument."
  },
  {
    "code": "def close(self):\n        handle = self.__handle\n        if handle is None:\n            return\n        weak_transfer_set = self.__transfer_set\n        transfer_set = self.__set()\n        while True:\n            try:\n                transfer = weak_transfer_set.pop()\n            except self.__KeyError:\n                break\n            transfer_set.add(transfer)\n            transfer.doom()\n        inflight = self.__inflight\n        for transfer in inflight:\n            try:\n                transfer.cancel()\n            except (self.__USBErrorNotFound, self.__USBErrorNoDevice):\n                pass\n        while inflight:\n            try:\n                self.__context.handleEvents()\n            except self.__USBErrorInterrupted:\n                pass\n        for transfer in transfer_set:\n            transfer.close()\n        self.__libusb_close(handle)\n        self.__handle = None",
    "docstring": "Close this handle. If not called explicitely, will be called by\n        destructor.\n\n        This method cancels any in-flight transfer when it is called. As\n        cancellation is not immediate, this method needs to let libusb handle\n        events until transfers are actually cancelled.\n        In multi-threaded programs, this can lead to stalls. To avoid this,\n        do not close nor let GC collect a USBDeviceHandle which has in-flight\n        transfers."
  },
  {
    "code": "def log_mel_spectrogram(data,\n                        audio_sample_rate=8000,\n                        log_offset=0.0,\n                        window_length_secs=0.025,\n                        hop_length_secs=0.010,\n                        **kwargs):\n  window_length_samples = int(round(audio_sample_rate * window_length_secs))\n  hop_length_samples = int(round(audio_sample_rate * hop_length_secs))\n  fft_length = 2 ** int(np.ceil(np.log(window_length_samples) / np.log(2.0)))\n  spectrogram = stft_magnitude(\n      data,\n      fft_length=fft_length,\n      hop_length=hop_length_samples,\n      window_length=window_length_samples)\n  mel_spectrogram = np.dot(spectrogram, spectrogram_to_mel_matrix(\n      num_spectrogram_bins=spectrogram.shape[1],\n      audio_sample_rate=audio_sample_rate, **kwargs))\n  return np.log(mel_spectrogram + log_offset)",
    "docstring": "Convert waveform to a log magnitude mel-frequency spectrogram.\n\n  Args:\n    data: 1D np.array of waveform data.\n    audio_sample_rate: The sampling rate of data.\n    log_offset: Add this to values when taking log to avoid -Infs.\n    window_length_secs: Duration of each window to analyze.\n    hop_length_secs: Advance between successive analysis windows.\n    **kwargs: Additional arguments to pass to spectrogram_to_mel_matrix.\n\n  Returns:\n    2D np.array of (num_frames, num_mel_bins) consisting of log mel filterbank\n    magnitudes for successive frames."
  },
  {
    "code": "def _write(self, items):\n        response = self._batch_write_item(items)\n        if 'consumed_capacity' in response:\n            self.consumed_capacity = \\\n                sum(response['consumed_capacity'], self.consumed_capacity)\n        if response.get('UnprocessedItems'):\n            unprocessed = response['UnprocessedItems'].get(self.tablename, [])\n            LOG.info(\"%d items were unprocessed. Storing for later.\",\n                     len(unprocessed))\n            self._unprocessed.extend(unprocessed)\n            self._attempt += 1\n            self.connection.exponential_sleep(self._attempt)\n        else:\n            self._attempt = 0\n        return response",
    "docstring": "Perform a batch write and handle the response"
  },
  {
    "code": "def get_service(self, service_name):\n        service = self.services.get(service_name)\n        if not service:\n            raise KeyError('Service not registered: %s' % service_name)\n        return service",
    "docstring": "Given the name of a registered service, return its service definition."
  },
  {
    "code": "def keyring_refresh(**kwargs):\n    ctx = Context(**kwargs)\n    ctx.execute_action('keyring:refresh', **{\n        'tvm': ctx.repo.create_secure_service('tvm'),\n    })",
    "docstring": "Refresh the keyring in the cocaine-runtime."
  },
  {
    "code": "def embed_seqdiag_sequence(self):\n        test_name = BuiltIn().replace_variables('${TEST NAME}')\n        outputdir = BuiltIn().replace_variables('${OUTPUTDIR}')\n        path = os.path.join(outputdir, test_name + '.seqdiag')\n        SeqdiagGenerator().compile(path, self._message_sequence)",
    "docstring": "Create a message sequence diagram png file to output folder and embed the image to log file.\n\n        You need to have seqdiag installed to create the sequence diagram. See http://blockdiag.com/en/seqdiag/"
  },
  {
    "code": "def get_annotation_entries_by_names(self, url: str, names: Iterable[str]) -> List[NamespaceEntry]:\n        annotation_filter = and_(Namespace.url == url, NamespaceEntry.name.in_(names))\n        return self.session.query(NamespaceEntry).join(Namespace).filter(annotation_filter).all()",
    "docstring": "Get annotation entries by URL and names.\n\n        :param url: The url of the annotation source\n        :param names: The names of the annotation entries from the given url's document"
  },
  {
    "code": "def restore_model(cls, data):\n    obj = cls()\n    for field in data:\n        setattr(obj, field, data[field][Field.VALUE])\n    return obj",
    "docstring": "Returns instance of ``cls`` with attributed loaded\n    from ``data`` dict."
  },
  {
    "code": "def _get_log_model_class(self):\n        if self.log_model_class is not None:\n            return self.log_model_class\n        app_label, model_label = self.log_model.rsplit('.', 1)\n        self.log_model_class = apps.get_model(app_label, model_label)\n        return self.log_model_class",
    "docstring": "Cache for fetching the actual log model object once django is loaded.\n\n        Otherwise, import conflict occur: WorkflowEnabled imports <log_model>\n        which tries to import all models to retrieve the proper model class."
  },
  {
    "code": "def pandas(self):\n        names,prior,posterior = [],[],[]\n        for iname,name in enumerate(self.posterior_parameter.row_names):\n            names.append(name)\n            posterior.append(np.sqrt(float(\n                self.posterior_parameter[iname, iname]. x)))\n            iprior = self.parcov.row_names.index(name)\n            prior.append(np.sqrt(float(self.parcov[iprior, iprior].x)))\n        for pred_name, pred_var in self.posterior_prediction.items():\n            names.append(pred_name)\n            posterior.append(np.sqrt(pred_var))\n            prior.append(self.prior_prediction[pred_name])\n        return pd.DataFrame({\"posterior\": posterior, \"prior\": prior},\n                                index=names)",
    "docstring": "get a pandas dataframe of prior and posterior for all predictions\n\n        Returns:\n            pandas.DataFrame : pandas.DataFrame\n                a dataframe with prior and posterior uncertainty estimates\n                for all forecasts (predictions)"
  },
  {
    "code": "def get_layer(self, class_: Type[L], became: bool=True) -> L:\n        try:\n            return self._index[class_][0]\n        except KeyError:\n            if became:\n                return self._transformed[class_][0]\n            else:\n                raise",
    "docstring": "Return the first layer of a given class. If that layer is not present,\n        then raise a KeyError.\n\n        :param class_: class of the expected layer\n        :param became: Allow transformed layers in results"
  },
  {
    "code": "def open(path, mode='r', host=None, user=None, port=DEFAULT_PORT):\n    if not host:\n        raise ValueError('you must specify the host to connect to')\n    if not user:\n        user = getpass.getuser()\n    conn = _connect(host, user, port)\n    sftp_client = conn.get_transport().open_sftp_client()\n    return sftp_client.open(path, mode)",
    "docstring": "Open a file on a remote machine over SSH.\n\n    Expects authentication to be already set up via existing keys on the local machine.\n\n    Parameters\n    ----------\n    path: str\n        The path to the file to open on the remote machine.\n    mode: str, optional\n        The mode to use for opening the file.\n    host: str, optional\n        The hostname of the remote machine.  May not be None.\n    user: str, optional\n        The username to use to login to the remote machine.\n        If None, defaults to the name of the current user.\n    port: int, optional\n        The port to connect to.\n\n    Returns\n    -------\n    A file-like object.\n\n    Important\n    ---------\n    If you specify a previously unseen host, then its host key will be added to\n    the local ~/.ssh/known_hosts *automatically*."
  },
  {
    "code": "def _condense(self, data):\n    if data:\n      data = filter(None,data.values())\n      if data:\n        return data[-1]\n    return None",
    "docstring": "Condense by returning the last real value of the gauge."
  },
  {
    "code": "def create_project(args):\n    try:\n        __import__(args.project_name)\n    except ImportError:\n        pass\n    else:\n        sys.exit(\"'{}' conflicts with the name of an existing \"\n                 \"Python module and cannot be used as a project \"\n                 \"name. Please try another name.\".format(args.project_name))\n    template_path = path.join(path.dirname(longclaw.__file__), 'project_template')\n    utility = ManagementUtility((\n        'django-admin.py',\n        'startproject',\n        '--template={}'.format(template_path),\n        '--extension=html,css,js,py,txt',\n        args.project_name\n    ))\n    utility.execute()\n    print(\"{} has been created.\".format(args.project_name))",
    "docstring": "Create a new django project using the longclaw template"
  },
  {
    "code": "def onSave(self, event, alert=False, destroy=True):\n        if self.drop_down_menu:\n            self.drop_down_menu.clean_up()\n        self.grid_builder.save_grid_data()\n        if not event and not alert:\n            return\n        wx.MessageBox('Saved!', 'Info',\n                      style=wx.OK | wx.ICON_INFORMATION)\n        if destroy:\n            self.Destroy()",
    "docstring": "Save grid data"
  },
  {
    "code": "def comments(self, update=True):\n        if not self._comments:\n            if self.count == 0:\n                return self._continue_comments(update)\n            children = [x for x in self.children if 't1_{0}'.format(x)\n                        not in self.submission._comments_by_id]\n            if not children:\n                return None\n            data = {'children': ','.join(children),\n                    'link_id': self.submission.fullname,\n                    'r': str(self.submission.subreddit)}\n            if self.submission._comment_sort:\n                data['where'] = self.submission._comment_sort\n            url = self.reddit_session.config['morechildren']\n            response = self.reddit_session.request_json(url, data=data)\n            self._comments = response['data']['things']\n            if update:\n                for comment in self._comments:\n                    comment._update_submission(self.submission)\n        return self._comments",
    "docstring": "Fetch and return the comments for a single MoreComments object."
  },
  {
    "code": "def get_process_definition_start(fname, slug):\n    with open(fname) as file_:\n        for i, line in enumerate(file_):\n            if re.search(r'slug:\\s*{}'.format(slug), line):\n                return i + 1\n    return 1",
    "docstring": "Find the first line of process definition.\n\n    The first line of process definition is the line with a slug.\n\n    :param str fname: Path to filename with processes\n    :param string slug: process slug\n    :return: line where the process definiton starts\n    :rtype: int"
  },
  {
    "code": "def tag_builder(parser, token, cls, flow_type):\n    tokens = token.split_contents()\n    tokens_num = len(tokens)\n    if tokens_num == 1 or (tokens_num == 3 and tokens[1] == 'for'):\n        flow_name = None\n        if tokens_num == 3:\n            flow_name = tokens[2]\n        return cls(flow_name)\n    else:\n        raise template.TemplateSyntaxError(\n            '\"sitegate_%(type)s_form\" tag requires zero or two arguments. '\n            'E.g. {%% sitegate_%(type)s_form %%} or '\n            '{%% sitegate_%(type)s_form for ClassicSignup %%}.' % {'type': flow_type})",
    "docstring": "Helper function handling flow form tags."
  },
  {
    "code": "def get_hash(self, handle):\n        fpath = self._fpath_from_handle(handle)\n        return DiskStorageBroker.hasher(fpath)",
    "docstring": "Return the hash."
  },
  {
    "code": "def aborted(self, exc_info):\n        self.exc_info = exc_info\n        self.did_end = True\n        self.write(format_exception(*self.exc_info))",
    "docstring": "Called by a logger to log an exception."
  },
  {
    "code": "def get_issns_for_journal(nlm_id):\n    params = {'db': 'nlmcatalog',\n              'retmode': 'xml',\n              'id': nlm_id}\n    tree = send_request(pubmed_fetch, params)\n    if tree is None:\n        return None\n    issn_list = tree.findall('.//ISSN')\n    issn_linking = tree.findall('.//ISSNLinking')\n    issns = issn_list + issn_linking\n    if not issns:\n        return None\n    else:\n        return [issn.text for issn in issns]",
    "docstring": "Get a list of the ISSN numbers for a journal given its NLM ID.\n\n    Information on NLM XML DTDs is available at\n    https://www.nlm.nih.gov/databases/dtd/"
  },
  {
    "code": "def scope(self, scope):\n        if scope is None:\n            raise ValueError(\"Invalid value for `scope`, must not be `None`\")\n        allowed_values = [\"CLUSTER\", \"CUSTOMER\", \"USER\"]\n        if scope not in allowed_values:\n            raise ValueError(\n                \"Invalid value for `scope` ({0}), must be one of {1}\"\n                .format(scope, allowed_values)\n            )\n        self._scope = scope",
    "docstring": "Sets the scope of this Message.\n\n        The audience scope that this message should reach  # noqa: E501\n\n        :param scope: The scope of this Message.  # noqa: E501\n        :type: str"
  },
  {
    "code": "def match(tgt, opts=None):\n    if not opts:\n        opts = __opts__\n    if not isinstance(tgt, six.string_types):\n        return False\n    return fnmatch.fnmatch(opts['id'], tgt)",
    "docstring": "Returns true if the passed glob matches the id"
  },
  {
    "code": "def create(cls, path_name=None, name=None, crawlable=True):\n        project = cls(path_name, name, crawlable)\n        db.session.add(project)\n        db.session.commit()\n        return collect_results(project, force=True)",
    "docstring": "initialize an instance and save it to db."
  },
  {
    "code": "def tot_edges(self):\n        all_edges = []\n        for facet in self.facets:\n            edges = []\n            pt = self.get_line_in_facet(facet)\n            lines = []\n            for i, p in enumerate(pt):\n                if i == len(pt) / 2:\n                    break\n                lines.append(tuple(sorted(tuple([tuple(pt[i*2]), tuple(pt[i*2+1])]))))\n            for i, p in enumerate(lines):\n                if p not in all_edges:\n                    edges.append(p)\n            all_edges.extend(edges)\n        return len(all_edges)",
    "docstring": "Returns the number of edges in the convex hull.\n            Useful for identifying catalytically active sites."
  },
  {
    "code": "def add_validate(subparsers):\n    validate_parser = subparsers.add_parser(\n        'validate', help=add_validate.__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n    validate_parser.set_defaults(func=validate_parser.print_help)\n    validate_subparsers = validate_parser.add_subparsers(title='Testers')\n    validate_all_parser = validate_subparsers.add_parser(\n        'all', help=validate.validate_all.__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n    validate_all_parser.set_defaults(func=validate.validate_all)\n    validate_gate_parser = validate_subparsers.add_parser(\n        'gate', help=validate.validate_gate.__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n    validate_gate_parser.set_defaults(func=validate.validate_gate)",
    "docstring": "Validate Spinnaker setup."
  },
  {
    "code": "def register_callbacks(self, on_create, on_modify, on_delete):\n        self.on_create = on_create\n        self.on_modify = on_modify\n        self.on_delete = on_delete",
    "docstring": "Register callbacks for file creation, modification, and deletion"
  },
  {
    "code": "def update_tenant(\n        self,\n        tenant,\n        update_mask=None,\n        retry=google.api_core.gapic_v1.method.DEFAULT,\n        timeout=google.api_core.gapic_v1.method.DEFAULT,\n        metadata=None,\n    ):\n        if \"update_tenant\" not in self._inner_api_calls:\n            self._inner_api_calls[\n                \"update_tenant\"\n            ] = google.api_core.gapic_v1.method.wrap_method(\n                self.transport.update_tenant,\n                default_retry=self._method_configs[\"UpdateTenant\"].retry,\n                default_timeout=self._method_configs[\"UpdateTenant\"].timeout,\n                client_info=self._client_info,\n            )\n        request = tenant_service_pb2.UpdateTenantRequest(\n            tenant=tenant, update_mask=update_mask\n        )\n        return self._inner_api_calls[\"update_tenant\"](\n            request, retry=retry, timeout=timeout, metadata=metadata\n        )",
    "docstring": "Updates specified tenant.\n\n        Example:\n            >>> from google.cloud import talent_v4beta1\n            >>>\n            >>> client = talent_v4beta1.TenantServiceClient()\n            >>>\n            >>> # TODO: Initialize `tenant`:\n            >>> tenant = {}\n            >>>\n            >>> response = client.update_tenant(tenant)\n\n        Args:\n            tenant (Union[dict, ~google.cloud.talent_v4beta1.types.Tenant]): Required.\n\n                The tenant resource to replace the current resource in the system.\n\n                If a dict is provided, it must be of the same form as the protobuf\n                message :class:`~google.cloud.talent_v4beta1.types.Tenant`\n            update_mask (Union[dict, ~google.cloud.talent_v4beta1.types.FieldMask]): Optional but strongly recommended for the best service experience.\n\n                If ``update_mask`` is provided, only the specified fields in ``tenant``\n                are updated. Otherwise all the fields are updated.\n\n                A field mask to specify the tenant fields to be updated. Only top level\n                fields of ``Tenant`` are supported.\n\n                If a dict is provided, it must be of the same form as the protobuf\n                message :class:`~google.cloud.talent_v4beta1.types.FieldMask`\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.talent_v4beta1.types.Tenant` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def view_context(self):\n        url = self.get_selected_item().get('context')\n        if url:\n            self.selected_page = self.open_submission_page(url)",
    "docstring": "View the context surrounding the selected comment."
  },
  {
    "code": "def compat_get_paginated_response(view, page):\n    if DRFVLIST[0] == 3 and DRFVLIST[1] >= 1:\n        from rest_messaging.serializers import ComplexMessageSerializer\n        serializer = ComplexMessageSerializer(page, many=True)\n        return view.get_paginated_response(serializer.data)\n    else:\n        serializer = view.get_pagination_serializer(page)\n        return Response(serializer.data)",
    "docstring": "get_paginated_response is unknown to DRF 3.0"
  },
  {
    "code": "def _build_tag_param_list(params, tags):\n    keys = sorted(tags.keys())\n    i = 1\n    for key in keys:\n        value = tags[key]\n        params['Tags.member.{0}.Key'.format(i)] = key\n        if value is not None:\n            params['Tags.member.{0}.Value'.format(i)] = value\n        i += 1",
    "docstring": "helper function to build a tag parameter list to send"
  },
  {
    "code": "def _emp_extra_options(options):\n    metadata_path = os.path.normpath(os.path.join(options['param_dir'],\n                                                  options['metadata']))\n    if not os.path.isfile(metadata_path):\n        raise IOError, (\"Path to metadata file %s is invalid.\" %\n                        metadata_path)\n    options['metadata_path'] = metadata_path\n    subset = options.get('subset', '')\n    options['patch'] = emp.Patch(metadata_path, subset)\n    if 'cols' not in options.keys():\n        options['cols'] = ''\n    if 'splits' not in options.keys():\n        options['splits'] = ''\n    return options",
    "docstring": "Get special options patch, cols, and splits if analysis in emp module"
  },
  {
    "code": "def create_lockfile(self):\n        process = subprocess.Popen(\n            self.pin_command,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n        )\n        stdout, stderr = process.communicate()\n        if process.returncode == 0:\n            self.fix_lockfile()\n        else:\n            logger.critical(\"ERROR executing %s\", ' '.join(self.pin_command))\n            logger.critical(\"Exit code: %s\", process.returncode)\n            logger.critical(stdout.decode('utf-8'))\n            logger.critical(stderr.decode('utf-8'))\n            raise RuntimeError(\"Failed to pip-compile {0}\".format(self.infile))",
    "docstring": "Write recursive dependencies list to outfile\n        with hard-pinned versions.\n        Then fix it."
  },
  {
    "code": "def put(self, item, *args, **kwargs):\n        if not self.enabled:\n            return\n        timeout = kwargs.pop('timeout', None)\n        if timeout is None:\n            timeout = self.default_timeout\n        cache_key = self.make_key(args, kwargs)\n        with self._cache_lock:\n            self._cache[cache_key] = (time() + timeout, item)",
    "docstring": "Put an item into the cache, for this combination of args and kwargs.\n\n        Args:\n            *args: any arguments.\n            **kwargs: any keyword arguments. If ``timeout`` is specified as one\n                 of the keyword arguments, the item will remain available\n                 for retrieval for ``timeout`` seconds. If ``timeout`` is\n                 `None` or not specified, the ``default_timeout`` for this\n                 cache will be used. Specify a ``timeout`` of 0 (or ensure that\n                 the ``default_timeout`` for this cache is 0) if this item is\n                 not to be cached."
  },
  {
    "code": "def acquire(self, **kwargs):\n        return config.download_data(self.temp_filename, self.url,\n                                    self.sha256)",
    "docstring": "Download the file and return its path\n\n        Returns\n        -------\n        str or None\n            The path of the file in BatchUp's temporary directory or None if\n            the download failed."
  },
  {
    "code": "def clear(self):\n        self._logger.debug(\"Component handlers are cleared\")\n        self._field = None\n        self._name = None\n        self._logger = None",
    "docstring": "Cleans up the handler. The handler can't be used after this method has\n        been called"
  },
  {
    "code": "def can_view(self, user):\n        return user.is_admin or self == user \\\n            or set(self.classes).intersection(user.admin_for)",
    "docstring": "Return whether or not `user` can view information about the user."
  },
  {
    "code": "def ref_context_from_geoloc(geoloc):\n    text = geoloc.get('text')\n    geoid = geoloc.get('geoID')\n    rc = RefContext(name=text, db_refs={'GEOID': geoid})\n    return rc",
    "docstring": "Return a RefContext object given a geoloc entry."
  },
  {
    "code": "async def on_isupport_casemapping(self, value):\n        if value in rfc1459.protocol.CASE_MAPPINGS:\n            self._case_mapping = value\n            self.channels = rfc1459.parsing.NormalizingDict(self.channels, case_mapping=value)\n            self.users = rfc1459.parsing.NormalizingDict(self.users, case_mapping=value)",
    "docstring": "IRC case mapping for nickname and channel name comparisons."
  },
  {
    "code": "async def _execute(self, appt):\n        user = self.core.auth.user(appt.useriden)\n        if user is None:\n            logger.warning('Unknown user %s in stored appointment', appt.useriden)\n            await self._markfailed(appt)\n            return\n        await self.core.boss.execute(self._runJob(user, appt), f'Agenda {appt.iden}', user)",
    "docstring": "Fire off the task to make the storm query"
  },
  {
    "code": "def competition_leaderboard_view(self, competition):\n        result = self.process_response(\n            self.competition_view_leaderboard_with_http_info(competition))\n        return [LeaderboardEntry(e) for e in result['submissions']]",
    "docstring": "view a leaderboard based on a competition name\n\n            Parameters\n            ==========\n            competition: the competition name to view leadboard for"
  },
  {
    "code": "def short_key():\n    firstlast = list(ascii_letters + digits)\n    middle = firstlast + list('-_')\n    return ''.join((\n        choice(firstlast), choice(middle), choice(middle),\n        choice(middle), choice(firstlast),\n    ))",
    "docstring": "Generate a short key.\n\n    >>> key = short_key()\n    >>> len(key)\n    5"
  },
  {
    "code": "def _refresh_nvr(self):\n        rpm_info = juicer.utils.rpm_info(self.path)\n        self.name = rpm_info['name']\n        self.version = rpm_info['version']\n        self.release = rpm_info['release']",
    "docstring": "Refresh our name-version-release attributes."
  },
  {
    "code": "def make_valid_polygon(shape):\n    assert shape.geom_type == 'Polygon'\n    shape = make_valid_pyclipper(shape)\n    assert shape.is_valid\n    return shape",
    "docstring": "Make a polygon valid. Polygons can be invalid in many ways, such as\n    self-intersection, self-touching and degeneracy. This process attempts to\n    make a polygon valid while retaining as much of its extent or area as\n    possible.\n\n    First, we call pyclipper to robustly union the polygon. Using this on its\n    own appears to be good for \"cleaning\" the polygon.\n\n    This might result in polygons which still have degeneracies according to\n    the OCG standard of validity - as pyclipper does not consider these to be\n    invalid. Therefore we follow by using the `buffer(0)` technique to attempt\n    to remove any remaining degeneracies."
  },
  {
    "code": "def is_multidex(self):\n        dexre = re.compile(\"^classes(\\d+)?.dex$\")\n        return len([instance for instance in self.get_files() if dexre.search(instance)]) > 1",
    "docstring": "Test if the APK has multiple DEX files\n\n        :return: True if multiple dex found, otherwise False"
  },
  {
    "code": "def set_ctype(self, ctype, orig_ctype=None):\n        if self.ctype is None:\n            self.ctype = ctype\n            self.orig_ctype = orig_ctype",
    "docstring": "Set the selected content type.  Will not override the value of\n        the content type if that has already been determined.\n\n        :param ctype: The content type string to set.\n\n        :param orig_ctype: The original content type, as found in the\n                           configuration."
  },
  {
    "code": "def printDatawraps() :\n\tl = listDatawraps()\n\tprintf(\"Available datawraps for boostraping\\n\")\n\tfor k, v in l.iteritems() :\n\t\tprintf(k)\n\t\tprintf(\"~\"*len(k) + \"|\")\n\t\tfor vv in v :\n\t\t\tprintf(\" \"*len(k) + \"|\" + \"~~~:> \" + vv)\n\t\tprintf('\\n')",
    "docstring": "print all available datawraps for bootstraping"
  },
  {
    "code": "def include(context, bundle_name, version):\n    store = Store(context.obj['database'], context.obj['root'])\n    if version:\n        version_obj = store.Version.get(version)\n        if version_obj is None:\n            click.echo(click.style('version not found', fg='red'))\n    else:\n        bundle_obj = store.bundle(bundle_name)\n        if bundle_obj is None:\n            click.echo(click.style('bundle not found', fg='red'))\n        version_obj = bundle_obj.versions[0]\n    try:\n        include_version(context.obj['root'], version_obj)\n    except VersionIncludedError as error:\n        click.echo(click.style(error.message, fg='red'))\n        context.abort()\n    version_obj.included_at = dt.datetime.now()\n    store.commit()\n    click.echo(click.style('included all files!', fg='green'))",
    "docstring": "Include a bundle of files into the internal space.\n\n    Use bundle name if you simply want to inlcude the latest version."
  },
  {
    "code": "def OnTool(self, event):\n        msgtype = self.ids_msgs[event.GetId()]\n        post_command_event(self, msgtype)",
    "docstring": "Toolbar event handler"
  },
  {
    "code": "def bus_get(celf, type, private, error = None) :\n        \"returns a Connection to one of the predefined D-Bus buses; type is a BUS_xxx value.\"\n        error, my_error = _get_error(error)\n        result = (dbus.dbus_bus_get, dbus.dbus_bus_get_private)[private](type, error._dbobj)\n        my_error.raise_if_set()\n        if result != None :\n            result = celf(result)\n        return \\\n            result",
    "docstring": "returns a Connection to one of the predefined D-Bus buses; type is a BUS_xxx value."
  },
  {
    "code": "def set_plot_type(self, plot_type):\n        ptypes = [pt[\"type\"] for pt in self.plot_types]\n        self.plot_panel = ptypes.index(plot_type)",
    "docstring": "Sets plot type"
  },
  {
    "code": "def verbose(self_,msg,*args,**kw):\n        self_.__db_print(VERBOSE,msg,*args,**kw)",
    "docstring": "Print msg merged with args as a verbose message.\n\n        See Python's logging module for details of message formatting."
  },
  {
    "code": "def inverse_distance_to_grid(xp, yp, variable, grid_x, grid_y, r, gamma=None, kappa=None,\n                             min_neighbors=3, kind='cressman'):\n    r\n    points_obs = list(zip(xp, yp))\n    points_grid = generate_grid_coords(grid_x, grid_y)\n    img = inverse_distance_to_points(points_obs, variable, points_grid, r, gamma=gamma,\n                                     kappa=kappa, min_neighbors=min_neighbors, kind=kind)\n    return img.reshape(grid_x.shape)",
    "docstring": "r\"\"\"Generate an inverse distance interpolation of the given points to a regular grid.\n\n    Values are assigned to the given grid using inverse distance weighting based on either\n    [Cressman1959]_ or [Barnes1964]_. The Barnes implementation used here based on [Koch1983]_.\n\n    Parameters\n    ----------\n    xp: (N, ) ndarray\n        x-coordinates of observations.\n    yp: (N, ) ndarray\n        y-coordinates of observations.\n    variable: (N, ) ndarray\n        observation values associated with (xp, yp) pairs.\n        IE, variable[i] is a unique observation at (xp[i], yp[i]).\n    grid_x: (M, 2) ndarray\n        Meshgrid associated with x dimension.\n    grid_y: (M, 2) ndarray\n        Meshgrid associated with y dimension.\n    r: float\n        Radius from grid center, within which observations\n        are considered and weighted.\n    gamma: float\n        Adjustable smoothing parameter for the barnes interpolation. Default None.\n    kappa: float\n        Response parameter for barnes interpolation. Default None.\n    min_neighbors: int\n        Minimum number of neighbors needed to perform barnes or cressman interpolation\n        for a point. Default is 3.\n    kind: str\n        Specify what inverse distance weighting interpolation to use.\n        Options: 'cressman' or 'barnes'. Default 'cressman'\n\n    Returns\n    -------\n    img: (M, N) ndarray\n        Interpolated values on a 2-dimensional grid\n\n    See Also\n    --------\n    inverse_distance_to_points"
  },
  {
    "code": "def _get_connection(self):\n        try:\n            if self._ncc_connection and self._ncc_connection.connected:\n                return self._ncc_connection\n            else:\n                self._ncc_connection = manager.connect(\n                    host=self._host_ip, port=self._host_ssh_port,\n                    username=self._username, password=self._password,\n                    device_params={'name': \"csr\"}, timeout=self._timeout)\n                if not self._itfcs_enabled:\n                    self._itfcs_enabled = self._enable_itfcs(\n                        self._ncc_connection)\n            return self._ncc_connection\n        except Exception as e:\n            conn_params = {'host': self._host_ip, 'port': self._host_ssh_port,\n                           'user': self._username,\n                           'timeout': self._timeout, 'reason': e.message}\n            raise cfg_exc.ConnectionException(**conn_params)",
    "docstring": "Make SSH connection to the IOS XE device.\n\n        The external ncclient library is used for creating this connection.\n        This method keeps state of any existing connections and reuses them if\n        already connected. Also interfaces (except management) are typically\n        disabled by default when it is booted. So if connecting for the first\n        time, driver will enable all other interfaces and keep that status in\n        the `_itfcs_enabled` flag."
  },
  {
    "code": "def unset_env():\n        os.environ.pop('COV_CORE_SOURCE', None)\n        os.environ.pop('COV_CORE_DATA_FILE', None)\n        os.environ.pop('COV_CORE_CONFIG', None)",
    "docstring": "Remove coverage info from env."
  },
  {
    "code": "def _GenerateClientInfo(self, client_id, client_fd):\n    summary_dict = client_fd.ToPrimitiveDict(stringify_leaf_fields=True)\n    summary = yaml.Dump(summary_dict).encode(\"utf-8\")\n    client_info_path = os.path.join(self.prefix, client_id, \"client_info.yaml\")\n    st = os.stat_result((0o644, 0, 0, 0, 0, 0, len(summary), 0, 0, 0))\n    yield self.archive_generator.WriteFileHeader(client_info_path, st=st)\n    yield self.archive_generator.WriteFileChunk(summary)\n    yield self.archive_generator.WriteFileFooter()",
    "docstring": "Yields chucks of archive information for given client."
  },
  {
    "code": "def create_feature(self, **kwargs):\n        kwargs['_return_http_data_only'] = True\n        if kwargs.get('callback'):\n            return self.create_feature_with_http_info(**kwargs)\n        else:\n            (data) = self.create_feature_with_http_info(**kwargs)\n            return data",
    "docstring": "Create an enumerated sequence feature\n        \n\n        This method makes a synchronous HTTP request by default. To make an\n        asynchronous HTTP request, please define a `callback` function\n        to be invoked when receiving the response.\n        >>> def callback_function(response):\n        >>>     pprint(response)\n        >>>\n        >>> thread = api.create_feature(callback=callback_function)\n\n        :param callback function: The callback function\n            for asynchronous request. (optional)\n        :param FeatureRequest body: \n        :return: Feature\n                 If the method is called asynchronously,\n                 returns the request thread."
  },
  {
    "code": "def get(self, artifact):\n    coord = self._key(artifact)\n    if coord in self._artifacts_to_versions:\n      return self._artifacts_to_versions[coord]\n    return artifact",
    "docstring": "Gets the coordinate with the correct version for the given artifact coordinate.\n\n    :param M2Coordinate artifact: the coordinate to lookup.\n    :return: a coordinate which is the same as the input, but with the correct pinned version. If\n      this artifact set does not pin a version for the input artifact, this just returns the\n      original coordinate.\n    :rtype: M2Coordinate"
  },
  {
    "code": "def show_analysis_dialog(self):\n        self.analysis_dialog.update_evt_types()\n        self.analysis_dialog.update_groups()\n        self.analysis_dialog.update_cycles()\n        self.analysis_dialog.show()",
    "docstring": "Create the analysis dialog."
  },
  {
    "code": "def add_manager(self, manager):\n        select_action = 'add_manager'\n        self._update_scope_project_team(select_action=select_action, user=manager, user_type='manager')",
    "docstring": "Add a single manager to the scope.\n\n        :param manager: single username to be added to the scope list of managers\n        :type manager: basestring\n        :raises APIError: when unable to update the scope manager"
  },
  {
    "code": "async def resetTriggerToken(self, *args, **kwargs):\n        return await self._makeApiCall(self.funcinfo[\"resetTriggerToken\"], *args, **kwargs)",
    "docstring": "Reset a trigger token\n\n        Reset the token for triggering a given hook. This invalidates token that\n        may have been issued via getTriggerToken with a new token.\n\n        This method gives output: ``v1/trigger-token-response.json#``\n\n        This method is ``stable``"
  },
  {
    "code": "def first_timestamp(self, sid, epoch=False):\n        first_block = self.dbcur.execute(SQL_TMPO_FIRST, (sid,)).fetchone()\n        if first_block is None:\n            return None\n        timestamp = first_block[2]\n        if not epoch:\n            timestamp = pd.Timestamp.utcfromtimestamp(timestamp)\n            timestamp = timestamp.tz_localize('UTC')\n        return timestamp",
    "docstring": "Get the first available timestamp for a sensor\n\n        Parameters\n        ----------\n        sid : str\n            SensorID\n        epoch : bool\n            default False\n            If True return as epoch\n            If False return as pd.Timestamp\n\n        Returns\n        -------\n        pd.Timestamp | int"
  },
  {
    "code": "def dispatch_write(self, buf):\n        self.write_buffer += buf\n        if len(self.write_buffer) > self.MAX_BUFFER_SIZE:\n            console_output('Buffer too big ({:d}) for {}\\n'.format(\n                len(self.write_buffer), str(self)).encode())\n            raise asyncore.ExitNow(1)\n        return True",
    "docstring": "Augment the buffer with stuff to write when possible"
  },
  {
    "code": "def worth(what, level_name):\n    return (logging.NOTSET\n            < globals()[what].level\n            <= getattr(logging, level_name))",
    "docstring": "Returns `True` if the watcher `what` would log under `level_name`."
  },
  {
    "code": "def reload_localzone():\n    global _cache_tz\n    _cache_tz = pytz.timezone(get_localzone_name())\n    utils.assert_tz_offset(_cache_tz)\n    return _cache_tz",
    "docstring": "Reload the cached localzone. You need to call this if the timezone has changed."
  },
  {
    "code": "def get_replay(name, query, config, context=None):\n    endpoint = config.get('replay_endpoints', {}).get(name, None)\n    if not endpoint:\n        raise IOError(\"No appropriate replay endpoint \"\n                      \"found for {0}\".format(name))\n    if not context:\n        context = zmq.Context(config['io_threads'])\n    socket = context.socket(zmq.REQ)\n    try:\n        socket.connect(endpoint)\n    except zmq.ZMQError as e:\n        raise IOError(\"Error when connecting to the \"\n                      \"replay endpoint: '{0}'\".format(str(e)))\n    socket.send(fedmsg.encoding.dumps(query).encode('utf-8'))\n    msgs = socket.recv_multipart()\n    socket.close()\n    for m in msgs:\n        try:\n            yield fedmsg.encoding.loads(m.decode('utf-8'))\n        except ValueError:\n            raise ValueError(m)",
    "docstring": "Query the replay endpoint for missed messages.\n\n    Args:\n        name (str): The replay endpoint name.\n        query (dict): A dictionary used to query the replay endpoint for messages.\n            Queries are dictionaries with the following any of the following keys:\n\n            * 'seq_ids': A ``list`` of ``int``, matching the seq_id attributes\n              of the messages. It should return at most as many messages as the\n              length of the list, assuming no duplicate.\n\n            * 'seq_id': A single ``int`` matching the seq_id attribute of the message.\n              Should return a single message. It is intended as a shorthand for\n              singleton ``seq_ids`` queries.\n\n            * 'seq_id_range': A two-tuple of ``int`` defining a range of seq_id to check.\n\n            * 'msg_ids': A ``list`` of UUIDs matching the msg_id attribute of the messages.\n\n            * 'msg_id': A single UUID for the msg_id attribute.\n\n            * 'time': A tuple of two timestamps. It will return all messages emitted in between.\n        config (dict): A configuration dictionary. This dictionary should contain, at a\n            minimum, two keys. The first key, 'replay_endpoints', should be a dictionary\n            that maps ``name`` to a ZeroMQ socket. The second key, 'io_threads', is an\n            integer used to initialize the ZeroMQ context.\n        context (zmq.Context): The ZeroMQ context to use. If a context is not provided,\n            one will be created.\n\n    Returns:\n        generator: A generator that yields message dictionaries."
  },
  {
    "code": "def add(self, func: Callable, name: Optional[str]=None,\n            queue: Optional[str]=None, max_retries: Optional[Number]=None,\n            periodicity: Optional[timedelta]=None):\n        if not name:\n            raise ValueError('Each Spinach task needs a name')\n        if name in self._tasks:\n            raise ValueError('A task named {} already exists'.format(name))\n        if queue is None:\n            if self.queue:\n                queue = self.queue\n            else:\n                queue = const.DEFAULT_QUEUE\n        if max_retries is None:\n            if self.max_retries:\n                max_retries = self.max_retries\n            else:\n                max_retries = const.DEFAULT_MAX_RETRIES\n        if periodicity is None:\n            periodicity = self.periodicity\n        if queue and queue.startswith('_'):\n            raise ValueError('Queues starting with \"_\" are reserved by '\n                             'Spinach for internal use')\n        self._tasks[name] = Task(func, name, queue, max_retries, periodicity)",
    "docstring": "Register a task function.\n\n        :arg func: a callable to be executed\n        :arg name: name of the task, used later to schedule jobs\n        :arg queue: queue of the task, the default is used if not provided\n        :arg max_retries: maximum number of retries, the default is used if\n             not provided\n        :arg periodicity: for periodic tasks, delay between executions as a\n             timedelta\n\n        >>> tasks = Tasks()\n        >>> tasks.add(lambda x: x, name='do_nothing')"
  },
  {
    "code": "def escape(self, value):\n        value = soft_unicode(value)\n        if self._engine._escape is None:\n            return value\n        return self._engine._escape(value)",
    "docstring": "Escape given value."
  },
  {
    "code": "def check_is_notification(self, participant_id, messages):\n        try:\n            last_check = NotificationCheck.objects.filter(participant__id=participant_id).latest('id').date_check\n        except Exception:\n            for m in messages:\n                m.is_notification = True\n            return messages\n        for m in messages:\n            if m.sent_at > last_check and m.sender.id != participant_id:\n                setattr(m, \"is_notification\", True)\n            else:\n                setattr(m, \"is_notification\", False)\n        return messages",
    "docstring": "Check if each message requires a notification for the specified participant."
  },
  {
    "code": "def request_blocking(self, method, params):\n        response = self._make_request(method, params)\n        if \"error\" in response:\n            raise ValueError(response[\"error\"])\n        return response['result']",
    "docstring": "Make a synchronous request using the provider"
  },
  {
    "code": "def _get_error_generator(type, obj, schema_dir=None, version=DEFAULT_VER, default='core'):\n    if schema_dir is None:\n        schema_dir = os.path.abspath(os.path.dirname(__file__) + '/schemas-'\n                                     + version + '/')\n    try:\n        schema_path = find_schema(schema_dir, type)\n        schema = load_schema(schema_path)\n    except (KeyError, TypeError):\n        try:\n            schema_path = find_schema(schema_dir, default)\n            schema = load_schema(schema_path)\n        except (KeyError, TypeError):\n            if schema_dir is not None:\n                return None\n            raise SchemaInvalidError(\"Cannot locate a schema for the object's \"\n                                     \"type, nor the base schema ({}.json).\".format(default))\n    if type == 'observed-data' and schema_dir is None:\n        schema['allOf'][1]['properties']['objects'] = {\n            \"objects\": {\n                \"type\": \"object\",\n                \"minProperties\": 1\n            }\n        }\n    validator = load_validator(schema_path, schema)\n    try:\n        error_gen = validator.iter_errors(obj)\n    except schema_exceptions.RefResolutionError:\n        raise SchemaInvalidError('Invalid JSON schema: a JSON '\n                                 'reference failed to resolve')\n    return error_gen",
    "docstring": "Get a generator for validating against the schema for the given object type.\n\n    Args:\n        type (str): The object type to find the schema for.\n        obj: The object to be validated.\n        schema_dir (str): The path in which to search for schemas.\n        version (str): The version of the STIX specification to validate\n            against. Only used to find base schemas when schema_dir is None.\n        default (str): If the schema for the given type cannot be found, use\n            the one with this name instead.\n\n    Returns:\n        A generator for errors found when validating the object against the\n        appropriate schema, or None if schema_dir is None and the schema\n        cannot be found."
  },
  {
    "code": "def expr_contains(e, o):\n    if o == e:\n        return True\n    if e.has_args():\n        for a in e.args():\n            if expr_contains(a, o):\n                return True\n    return False",
    "docstring": "Returns true if o is in e"
  },
  {
    "code": "def get_db_filename(impl, working_dir):\n    db_filename = impl.get_virtual_chain_name() + \".db\"\n    return os.path.join(working_dir, db_filename)",
    "docstring": "Get the absolute path to the last-block file."
  },
  {
    "code": "def process_string_tensor_event(event):\n  string_arr = tensor_util.make_ndarray(event.tensor_proto)\n  html = text_array_to_html(string_arr)\n  return {\n      'wall_time': event.wall_time,\n      'step': event.step,\n      'text': html,\n  }",
    "docstring": "Convert a TensorEvent into a JSON-compatible response."
  },
  {
    "code": "def load(self, host, exact_host_match=False):\n        config_string, host_string = ftr_get_config(host, exact_host_match)\n        if config_string is None:\n            LOGGER.error(u'Error while loading configuration.',\n                         extra={'siteconfig': host_string})\n            return\n        self.append(ftr_string_to_instance(config_string))",
    "docstring": "Load a config for a hostname or url.\n\n        This method calls :func:`ftr_get_config` and :meth`append`\n        internally. Refer to their docs for details on parameters."
  },
  {
    "code": "def replace_project(self, project_key, **kwargs):\n        request = self.__build_project_obj(\n            lambda: _swagger.ProjectCreateRequest(\n                title=kwargs.get('title'),\n                visibility=kwargs.get('visibility')\n            ),\n            lambda name, url, description, labels:\n            _swagger.FileCreateRequest(\n                name=name,\n                source=_swagger.FileSourceCreateRequest(url=url),\n                description=description,\n                labels=labels),\n            kwargs)\n        try:\n            project_owner_id, project_id = parse_dataset_key(project_key)\n            self._projects_api.replace_project(project_owner_id,\n                                               project_id,\n                                               body=request)\n        except _swagger.rest.ApiException as e:\n            raise RestApiError(cause=e)",
    "docstring": "Replace an existing Project\n\n        *Create a project with a given id or completely rewrite the project,\n        including any previously added files or linked datasets, if one already\n        exists with the given id.*\n\n        :param project_key: Username and unique identifier of the creator of a\n            project in the form of owner/id.\n        :type project_key: str\n        :param title: Project title\n        :type title: str\n        :param objective: Short project objective.\n        :type objective: str, optional\n        :param summary: Long-form project summary.\n        :type summary: str, optional\n        :param tags: Project tags. Letters numbers and spaces\n        :type tags: list, optional\n        :param license: Project license\n        :type license: {'Public Domain', 'PDDL', 'CC-0', 'CC-BY', 'ODC-BY',\n            'CC-BY-SA', 'ODC-ODbL', 'CC BY-NC', 'CC BY-NC-SA', 'Other'}\n        :param visibility: Project visibility\n        :type visibility: {'OPEN', 'PRIVATE'}\n        :param files: File name as dict, source URLs, description and labels()\n        as properties\n        :type files: dict, optional\n            *Description and labels are optional*\n        :param linked_datasets: Initial set of linked datasets.\n        :type linked_datasets: list of object, optional\n        :returns: project object\n        :rtype: object\n        :raises RestApiException: If a server error occurs\n\n        Examples\n        --------\n        >>> import datadotworld as dw\n        >>> api_client = dw.api_client()\n        >>> api_client.replace_project(\n        ...    'username/test-project',\n        ...    visibility='PRIVATE',\n        ...    objective='A better objective',\n        ...    title='Replace project')  # doctest: +SKIP"
  },
  {
    "code": "def get_monitors(self, condition=None, page_size=1000):\n        req_kwargs = {}\n        if condition:\n            req_kwargs['condition'] = condition.compile()\n        for monitor_data in self._conn.iter_json_pages(\"/ws/Monitor\", **req_kwargs):\n            yield DeviceCloudMonitor.from_json(self._conn, monitor_data, self._tcp_client_manager)",
    "docstring": "Return an iterator over all monitors matching the provided condition\n\n        Get all inactive monitors and print id::\n\n            for mon in dc.monitor.get_monitors(MON_STATUS_ATTR == \"DISABLED\"):\n                print(mon.get_id())\n\n        Get all the HTTP monitors and print id::\n\n            for mon in dc.monitor.get_monitors(MON_TRANSPORT_TYPE_ATTR == \"http\"):\n                print(mon.get_id())\n\n        Many other possibilities exist.  See the :mod:`devicecloud.condition` documention\n        for additional details on building compound expressions.\n\n        :param condition: An :class:`.Expression` which defines the condition\n            which must be matched on the monitor that will be retrieved from\n            Device Cloud. If a condition is unspecified, an iterator over\n            all monitors for this account will be returned.\n        :type condition: :class:`.Expression` or None\n        :param int page_size: The number of results to fetch in a single page.\n        :return: Generator yielding :class:`.DeviceCloudMonitor` instances matching the\n            provided conditions."
  },
  {
    "code": "def manage_brok(self, brok):\n        manage = getattr(self, 'manage_' + brok.type + '_brok', None)\n        if not manage:\n            return False\n        brok.prepare()\n        return manage(brok)",
    "docstring": "Request the module to manage the given brok.\n        There are a lot of different possible broks to manage. The list is defined\n        in the Brok class.\n\n        An internal module may redefine this function or, easier, define only the function\n        for the brok it is interested with. Hence a module interested in the `service_check_result`\n        broks will only need to define a function named as `manage_service_check_result_brok`\n\n        :param brok:\n        :type brok:\n        :return:\n        :rtype:"
  },
  {
    "code": "def email_verifier(self, email, raw=False):\n        params = {'email': email, 'api_key': self.api_key}\n        endpoint = self.base_endpoint.format('email-verifier')\n        return self._query_hunter(endpoint, params, raw=raw)",
    "docstring": "Verify the deliverability of a given email adress.abs\n\n        :param email: The email adress to check.\n\n        :param raw: Gives back the entire response instead of just the 'data'.\n\n        :return: Full payload of the query as a dict."
  },
  {
    "code": "def remove_domain_user_role(request, user, role, domain=None):\n    manager = keystoneclient(request, admin=True).roles\n    return manager.revoke(role, user=user, domain=domain)",
    "docstring": "Removes a given single role for a user from a domain."
  },
  {
    "code": "def load(klass, filename, inject_env=True):\n        p = PipfileParser(filename=filename)\n        pipfile = klass(filename=filename)\n        pipfile.data = p.parse(inject_env=inject_env)\n        return pipfile",
    "docstring": "Load a Pipfile from a given filename."
  },
  {
    "code": "def insert_pattern(self, pattern, index):\n        LOGGER.debug(\"> Inserting '{0}' at '{1}' index.\".format(pattern, index))\n        self.remove_pattern(pattern)\n        self.beginInsertRows(self.get_node_index(self.root_node), index, index)\n        pattern_node = PatternNode(name=pattern)\n        self.root_node.insert_child(pattern_node, index)\n        self.endInsertRows()\n        self.pattern_inserted.emit(pattern_node)\n        return True",
    "docstring": "Inserts given pattern into the Model.\n\n        :param pattern: Pattern.\n        :type pattern: unicode\n        :param index: Insertion index.\n        :type index: int\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def resetStaffCompensationInfo(self, request, queryset):\n    selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)\n    ct = ContentType.objects.get_for_model(queryset.model)\n    return HttpResponseRedirect(reverse('resetCompensationRules') + \"?ct=%s&ids=%s\" % (ct.pk, \",\".join(selected)))",
    "docstring": "This action is added to the list for staff member to permit bulk\n    reseting to category defaults of compensation information for staff members."
  },
  {
    "code": "def _upload_none(self, upload_info, check_result):\n        return UploadResult(\n            action=None,\n            quickkey=check_result['duplicate_quickkey'],\n            hash_=upload_info.hash_info.file,\n            filename=upload_info.name,\n            size=upload_info.size,\n            created=None,\n            revision=None\n        )",
    "docstring": "Dummy upload function for when we don't actually upload"
  },
  {
    "code": "def wait_for_window_focus(self, window, want_focus):\n        _libxdo.xdo_wait_for_window_focus(self._xdo, window, want_focus)",
    "docstring": "Wait for a window to have or lose focus.\n\n        :param window: The window to wait on\n        :param want_focus: If 1, wait for focus. If 0, wait for loss of focus."
  },
  {
    "code": "def perform_exe_expansion(self):\n        if self.has_section('executables'):\n            for option, value in self.items('executables'):\n                newStr = self.interpolate_exe(value)\n                if newStr != value:\n                    self.set('executables', option, newStr)",
    "docstring": "This function will look through the executables section of the\n        ConfigParser object and replace any values using macros with full paths.\n\n        For any values that look like\n\n        ${which:lalapps_tmpltbank}\n\n        will be replaced with the equivalent of which(lalapps_tmpltbank)\n\n        Otherwise values will be unchanged."
  },
  {
    "code": "def get_user(\n        self, identified_with, identifier, req, resp, resource, uri_kwargs\n    ):\n        stored_value = self.kv_store.get(\n            self._get_storage_key(identified_with, identifier)\n        )\n        if stored_value is not None:\n            user = self.serialization.loads(stored_value.decode())\n        else:\n            user = None\n        return user",
    "docstring": "Get user object for given identifier.\n\n        Args:\n            identified_with (object): authentication middleware used\n                to identify the user.\n            identifier: middleware specifix user identifier (string or tuple\n                in case of all built in authentication middleware classes).\n\n        Returns:\n            dict: user object stored in Redis if it exists, otherwise ``None``"
  },
  {
    "code": "def _delete_msg(self, conn, queue_url, receipt_handle):\n        resp = conn.delete_message(QueueUrl=queue_url,\n                                   ReceiptHandle=receipt_handle)\n        if resp['ResponseMetadata']['HTTPStatusCode'] != 200:\n            logger.error('Error: message with receipt handle %s in queue %s '\n                         'was not successfully deleted (HTTP %s)',\n                         receipt_handle, queue_url,\n                         resp['ResponseMetadata']['HTTPStatusCode'])\n            return\n        logger.info('Message with receipt handle %s deleted from queue %s',\n                    receipt_handle, queue_url)",
    "docstring": "Delete the message specified by ``receipt_handle`` in the queue\n        specified by ``queue_url``.\n\n        :param conn: SQS API connection\n        :type conn: :py:class:`botocore:SQS.Client`\n        :param queue_url: queue URL to delete the message from\n        :type queue_url: str\n        :param receipt_handle: message receipt handle\n        :type receipt_handle: str"
  },
  {
    "code": "def set_subject(self, value: Union[Literal, Identifier, str], lang: str= None):\n        return self.metadata.add(key=DC.subject, value=value, lang=lang)",
    "docstring": "Set the DC Subject literal value\n\n        :param value: Value of the subject node\n        :param lang: Language in which the value is"
  },
  {
    "code": "def main():\n    (options, _) = _parse_args()\n    if options.change_password:\n        c.keyring_set_password(c[\"username\"])\n        sys.exit(0)\n    if options.select:\n        courses = client.get_courses()\n        c.selection_dialog(courses)\n        c.save()\n        sys.exit(0)\n    if options.stop:\n        os.system(\"kill -2 `cat ~/.studdp/studdp.pid`\")\n        sys.exit(0)\n    task = _MainLoop(options.daemonize, options.update_courses)\n    if options.daemonize:\n        log.info(\"daemonizing...\")\n        with daemon.DaemonContext(working_directory=\".\", pidfile=PIDLockFile(PID_FILE)):\n            handler = logging.FileHandler(LOG_PATH)\n            handler.setFormatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')\n            log.addHandler(handler)\n            task()\n    else:\n        task()",
    "docstring": "parse command line options and either launch some configuration dialog or start an instance of _MainLoop as a daemon"
  },
  {
    "code": "def get_scenario_data(scenario_id,**kwargs):\n    user_id = kwargs.get('user_id')\n    scenario_data = db.DBSession.query(Dataset).filter(Dataset.id==ResourceScenario.dataset_id, ResourceScenario.scenario_id==scenario_id).options(joinedload_all('metadata')).distinct().all()\n    for sd in scenario_data:\n       if sd.hidden == 'Y':\n           try:\n                sd.check_read_permission(user_id)\n           except:\n               sd.value      = None\n               sd.metadata = []\n    db.DBSession.expunge_all()\n    log.info(\"Retrieved %s datasets\", len(scenario_data))\n    return scenario_data",
    "docstring": "Get all the datasets from the group with the specified name\n        @returns a list of dictionaries"
  },
  {
    "code": "def get_ymal_data(data):\n    try:\n        format_data = yaml.load(data)\n    except yaml.YAMLError, e:\n        msg = \"Yaml format error: {}\".format(\n            unicode(str(e), \"utf-8\")\n        )\n        logging.error(msg)\n        sys.exit(1)\n    if not check_config(format_data):\n        sys.exit(1)\n    return format_data",
    "docstring": "Get metadata and validate them\n\n    :param data: metadata in yaml format"
  },
  {
    "code": "def _eval(self):\n        \"Evaluates a individual using recursion and self._pos as pointer\"\n        pos = self._pos\n        self._pos += 1\n        node = self._ind[pos]\n        if isinstance(node, Function):\n            args = [self._eval() for x in range(node.nargs)]\n            node.eval(args)\n            for x in args:\n                x.hy = None\n                x.hy_test = None\n        else:\n            node.eval(self._X)\n        return node",
    "docstring": "Evaluates a individual using recursion and self._pos as pointer"
  },
  {
    "code": "def numbaGaussian2d(psf, sy, sx):\r\n    ps0, ps1 = psf.shape\r\n    c0,c1 = ps0//2, ps1//2\r\n    ssx = 2*sx**2\r\n    ssy = 2*sy**2\r\n    for i in range(ps0):\r\n        for j in range(ps1):\r\n            psf[i,j]=exp( -( (i-c0)**2/ssy\r\n                            +(j-c1)**2/ssx) )\r\n    psf/=psf.sum()",
    "docstring": "2d Gaussian to be used in numba code"
  },
  {
    "code": "def get_comments_for_reference_on_date(self, reference_id, from_, to):\n        comment_list = []\n        for comment in self.get_comments_for_reference(reference_id):\n            if overlap(from_, to, comment.start_date, comment.end_date):\n                comment_list.append(comment)\n        return objects.CommentList(comment_list, runtime=self._runtime)",
    "docstring": "Gets a list of all comments corresponding to a reference ``Id`` and effective during the entire given date range inclusive but not confined to the date range.\n\n        arg:    reference_id (osid.id.Id): a reference ``Id``\n        arg:    from (osid.calendaring.DateTime): from date\n        arg:    to (osid.calendaring.DateTime): to date\n        return: (osid.commenting.CommentList) - the returned\n                ``CommentList``\n        raise:  InvalidArgument - ``to`` is less than ``from``\n        raise:  NullArgument - ``reference_id, from,`` or ``to`` is\n                ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _add_fragment(cls, syncmap, identifier, lines, begin, end, language=None):\n        syncmap.add_fragment(\n            SyncMapFragment(\n                text_fragment=TextFragment(\n                    identifier=identifier,\n                    lines=lines,\n                    language=language\n                ),\n                begin=begin,\n                end=end\n            )\n        )",
    "docstring": "Add a new fragment to ``syncmap``.\n\n        :param syncmap: the syncmap to append to\n        :type syncmap: :class:`~aeneas.syncmap.SyncMap`\n        :param identifier: the identifier\n        :type identifier: string\n        :param lines: the lines of the text\n        :type lines: list of string\n        :param begin: the begin time\n        :type begin: :class:`~aeneas.exacttiming.TimeValue`\n        :param end: the end time\n        :type end: :class:`~aeneas.exacttiming.TimeValue`\n        :param language: the language\n        :type language: string"
  },
  {
    "code": "def fix_times(self):\n        pointlist = self.get_pointlist()\n        times = [point['time'] for stroke in pointlist for point in stroke]\n        times_min = max(min(times), 0)\n        for i, stroke in enumerate(pointlist):\n            for j, point in enumerate(stroke):\n                if point['time'] is None:\n                    pointlist[i][j]['time'] = times_min\n                else:\n                    times_min = point['time']\n        self.raw_data_json = json.dumps(pointlist)",
    "docstring": "Some recordings have wrong times. Fix them so that nothing after\n        loading a handwritten recording breaks."
  },
  {
    "code": "def _restore_vxlan_entries(self, switch_ip, vlans):\n        count = 1\n        conf_str = ''\n        vnsegment_sent = 0\n        path_str, conf_str = self.driver.start_create_vlan()\n        while vnsegment_sent < const.CREATE_VLAN_BATCH and vlans:\n            vlan_id, vni = vlans.pop(0)\n            conf_str = self.driver.get_create_vlan(\n                switch_ip, vlan_id, vni, conf_str)\n            if (count == const.CREATE_VLAN_SEND_SIZE):\n                conf_str = self.driver.end_create_vlan(conf_str)\n                self.driver.send_edit_string(switch_ip, path_str, conf_str)\n                vnsegment_sent += count\n                conf_str = ''\n                count = 1\n            else:\n                count += 1\n        if conf_str:\n            vnsegment_sent += count\n            conf_str = self.driver.end_create_vlan(conf_str)\n            self.driver.send_edit_string(switch_ip, path_str, conf_str)\n            conf_str = ''\n        LOG.debug(\"Switch %s VLAN vn-segment replay summary: %d\",\n                  switch_ip, vnsegment_sent)",
    "docstring": "Restore vxlan entries on a Nexus switch."
  },
  {
    "code": "def status_color(status):\n        status_color = c.Fore.GREEN\n        if not status:\n            status_color = c.Fore.RED\n        return status_color",
    "docstring": "Return the appropriate status color."
  },
  {
    "code": "def from_yaml_to_list(cls, data: str,\n                          force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TList[T]:\n        return cls.from_dicts(util.load_yaml(data),\n                              force_snake_case=force_snake_case,\n                              force_cast=force_cast,\n                              restrict=restrict)",
    "docstring": "From yaml string to list of instance\n\n        :param data: Yaml string\n        :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True\n        :param force_cast: Cast forcibly if True\n        :param restrict: Prohibit extra parameters if True\n        :return: List of instance\n\n        Usage:\n\n            >>> from owlmixin.samples import Human\n            >>> humans: TList[Human] = Human.from_yaml_to_list('''\n            ... - id: 1\n            ...   name: Tom\n            ...   favorites:\n            ...     - name: Apple\n            ... - id: 2\n            ...   name: John\n            ...   favorites:\n            ...     - name: Orange\n            ... ''')\n            >>> humans[0].name\n            'Tom'\n            >>> humans[1].name\n            'John'\n            >>> humans[0].favorites[0].name\n            'Apple'"
  },
  {
    "code": "def _str(obj):\n    values = []\n    for name in obj._attribs:\n        val = getattr(obj, name)\n        if isinstance(val, str):\n            val = repr(val)\n        val = str(val) if len(str(val)) < 10 else \"(...)\"\n        values.append((name, val))\n    values = \", \".join(\"{}={}\".format(k, v) for k, v in values)\n    return \"{}({})\".format(obj.__class__.__name__, values)",
    "docstring": "Show nicely the generic object received."
  },
  {
    "code": "def poll(poll, msg, server):\n    poll = remove_smart_quotes(poll.replace(u\"\\u2014\", u\"--\"))\n    try:\n        args = ARGPARSE.parse_args(shlex.split(poll)).poll\n    except ValueError:\n        return ERROR_INVALID_FORMAT\n    if not 2 < len(args) < len(POLL_EMOJIS) + 1:\n        return ERROR_WRONG_NUMBER_OF_ARGUMENTS\n    result = [\"Poll: {}\\n\".format(args[0])]\n    for emoji, answer in zip(POLL_EMOJIS, args[1:]):\n        result.append(\":{}: {}\\n\".format(emoji, answer))\n    msg_posted = server.slack.post_message(\n        msg['channel'], \"\".join(result), as_user=server.slack.username)\n    ts = json.loads(msg_posted)[\"ts\"]\n    for i in range(len(args) - 1):\n        server.slack.post_reaction(msg['channel'], ts, POLL_EMOJIS[i])",
    "docstring": "Given a question and answers, present a poll"
  },
  {
    "code": "def unpack(self, struct):\n        v = struct.unpack(self.read(struct.size))\n        return v",
    "docstring": "Read as many bytes as are required to extract struct then\n        unpack and return a tuple of the values.\n\n        Raises\n        ------\n        UnderflowDecodeError\n            Raised when a read failed to extract enough bytes from the\n            underlying stream to extract the bytes.\n\n        Parameters\n        ----------\n        struct: struct.Struct\n\n        Returns\n        -------\n        tuple\n            Tuple of extracted values."
  },
  {
    "code": "def find_behind_subscriptions(self, request):\n        task_id = find_behind_subscriptions.delay()\n        return Response(\n            {\"accepted\": True, \"task_id\": str(task_id)}, status=status.HTTP_202_ACCEPTED\n        )",
    "docstring": "Starts a celery task that looks through active subscriptions to find\n        and subscriptions that are behind where they should be, and adds a\n        BehindSubscription for them."
  },
  {
    "code": "def calculate_length_statistics(source_iterables: Sequence[Iterable[Any]],\n                                target_iterable: Iterable[Any],\n                                max_seq_len_source: int,\n                                max_seq_len_target: int) -> 'LengthStatistics':\n    mean_and_variance = OnlineMeanAndVariance()\n    for sources, target in parallel_iter(source_iterables, target_iterable):\n        source_len = len(sources[0])\n        target_len = len(target)\n        if source_len > max_seq_len_source or target_len > max_seq_len_target:\n            continue\n        length_ratio = target_len / source_len\n        mean_and_variance.update(length_ratio)\n    return LengthStatistics(mean_and_variance.count, mean_and_variance.mean, mean_and_variance.std)",
    "docstring": "Returns mean and standard deviation of target-to-source length ratios of parallel corpus.\n\n    :param source_iterables: Source sequence readers.\n    :param target_iterable: Target sequence reader.\n    :param max_seq_len_source: Maximum source sequence length.\n    :param max_seq_len_target: Maximum target sequence length.\n    :return: The number of sentences as well as the mean and standard deviation of target to source length ratios."
  },
  {
    "code": "def check_error(when='periodic check'):\n    errors = []\n    while True:\n        err = glGetError()\n        if err == GL_NO_ERROR or (errors and err == errors[-1]):\n            break\n        errors.append(err)\n    if errors:\n        msg = ', '.join([repr(ENUM_MAP.get(e, e)) for e in errors])\n        err = RuntimeError('OpenGL got errors (%s): %s' % (when, msg))\n        err.errors = errors\n        err.err = errors[-1]\n        raise err",
    "docstring": "Check this from time to time to detect GL errors.\n\n    Parameters\n    ----------\n    when : str\n        Shown in the exception to help the developer determine when\n        this check was done."
  },
  {
    "code": "def titleize(text):\n    if len(text) == 0:\n        return text\n    else:\n        text = text.lower()\n        chunks = [chunk[0].upper() + chunk[1:] for chunk in text.split(\" \") if len(chunk) >= 1]\n        return \" \".join(chunks)",
    "docstring": "Capitalizes all the words and replaces some characters in the string \n    to create a nicer looking title."
  },
  {
    "code": "def bind(self, queue, exchange, routing_key='', nowait=True, arguments={},\n             ticket=None, cb=None):\n        nowait = nowait and self.allow_nowait() and not cb\n        args = Writer()\n        args.write_short(ticket or self.default_ticket).\\\n            write_shortstr(queue).\\\n            write_shortstr(exchange).\\\n            write_shortstr(routing_key).\\\n            write_bit(nowait).\\\n            write_table(arguments)\n        self.send_frame(MethodFrame(self.channel_id, 50, 20, args))\n        if not nowait:\n            self._bind_cb.append(cb)\n            self.channel.add_synchronous_cb(self._recv_bind_ok)",
    "docstring": "bind to a queue."
  },
  {
    "code": "def set_imap_cb(self, w, index):\n        name = imap.get_names()[index]\n        self.t_.set(intensity_map=name)",
    "docstring": "This callback is invoked when the user selects a new intensity\n        map from the preferences pane."
  },
  {
    "code": "def yaml_parse(yamlstr):\n    try:\n        return json.loads(yamlstr)\n    except ValueError:\n        yaml.SafeLoader.add_multi_constructor(\"!\", intrinsics_multi_constructor)\n        return yaml.safe_load(yamlstr)",
    "docstring": "Parse a yaml string"
  },
  {
    "code": "def _remove_person_from_group(person, group):\n    from karaage.datastores import remove_accounts_from_group\n    from karaage.datastores import remove_accounts_from_project\n    from karaage.datastores import remove_accounts_from_institute\n    a_list = person.account_set\n    remove_accounts_from_group(a_list, group)\n    for project in group.project_set.all():\n        remove_accounts_from_project(a_list, project)\n    for institute in group.institute_set.all():\n        remove_accounts_from_institute(a_list, institute)",
    "docstring": "Call datastores after removing a person from a group."
  },
  {
    "code": "def jsd(p, q):\n    try:\n        _check_prob_dist(p)\n        _check_prob_dist(q)\n    except ValueError:\n        return np.nan\n    weight = 0.5\n    m = weight * (p + q)\n    result = weight * kld(p, m) + (1 - weight) * kld(q, m)\n    return result",
    "docstring": "Finds the per-column JSD between dataframes p and q\n\n    Jensen-Shannon divergence of two probability distrubutions pandas\n    dataframes, p and q. These distributions are usually created by running\n    binify() on the dataframe.\n\n    Parameters\n    ----------\n    p : pandas.DataFrame\n        An nbins x features DataFrame.\n    q : pandas.DataFrame\n        An nbins x features DataFrame.\n\n    Returns\n    -------\n    jsd : pandas.Series\n        Jensen-Shannon divergence of each column with the same names between\n        p and q\n\n    Raises\n    ------\n    ValueError\n        If the data provided is not a probability distribution, i.e. it has\n        negative values or its columns do not sum to 1, raise ValueError"
  },
  {
    "code": "def get_state_and_verify(self):\n        try:\n            state = get_state()\n        except KeyError as ke:\n            class state:\n                name = str(ke.args[0])\n        if state not in self.ALLOWED_STATES:\n            raise ValueError(\n                f\"Run state cherry-picker.state={state.name} in Git config \"\n                \"is not known.\\nPerhaps it has been set by a newer \"\n                \"version of cherry-picker. Try upgrading.\\n\"\n                \"Valid states are: \"\n                f'{\", \".join(s.name for s in self.ALLOWED_STATES)}. '\n                \"If this looks suspicious, raise an issue at \"\n                \"https://github.com/python/core-workflow/issues/new.\\n\"\n                \"As the last resort you can reset the runtime state \"\n                \"stored in Git config using the following command: \"\n                \"`git config --local --remove-section cherry-picker`\"\n            )\n        return state",
    "docstring": "Return the run progress state stored in the Git config.\n\n        Raises ValueError if the retrieved state is not of a form that\n                          cherry_picker would have stored in the config."
  },
  {
    "code": "def entity_tags_form(self, entity, ns=None):\n        if ns is None:\n            ns = self.entity_default_ns(entity)\n        field = TagsField(label=_l(\"Tags\"), ns=ns)\n        cls = type(\"EntityNSTagsForm\", (_TagsForm,), {\"tags\": field})\n        return cls",
    "docstring": "Construct a form class with a field for tags in namespace `ns`."
  },
  {
    "code": "def pawns_at(self, x, y):\n        for pawn in self.pawn.values():\n            if pawn.collide_point(x, y):\n                yield pawn",
    "docstring": "Iterate over pawns that collide the given point."
  },
  {
    "code": "def model_funcpointers(vk, model):\n    model['funcpointers'] = {}\n    funcs = [x for x in vk['registry']['types']['type']\n             if x.get('@category') == 'funcpointer']\n    structs = [x for x in vk['registry']['types']['type']\n               if x.get('@category') == 'struct']\n    for f in funcs:\n        pfn_name = f['name']\n        for s in structs:\n            if 'member' not in s:\n                continue\n            for m in s['member']:\n                if m['type'] == pfn_name:\n                    struct_name = s['@name']\n        model['funcpointers'][pfn_name] = struct_name",
    "docstring": "Fill the model with function pointer\n\n    model['funcpointers'] = {'pfn_name': 'struct_name'}"
  },
  {
    "code": "def get_developer_package(path, format=None):\n    from rez.developer_package import DeveloperPackage\n    return DeveloperPackage.from_path(path, format=format)",
    "docstring": "Create a developer package.\n\n    Args:\n        path (str): Path to dir containing package definition file.\n        format (str): Package definition file format, detected if None.\n\n    Returns:\n        `DeveloperPackage`."
  },
  {
    "code": "def enable_logging(self, bucket_name, object_prefix=\"\"):\n        info = {\"logBucket\": bucket_name, \"logObjectPrefix\": object_prefix}\n        self._patch_property(\"logging\", info)",
    "docstring": "Enable access logging for this bucket.\n\n        See https://cloud.google.com/storage/docs/access-logs\n\n        :type bucket_name: str\n        :param bucket_name: name of bucket in which to store access logs\n\n        :type object_prefix: str\n        :param object_prefix: prefix for access log filenames"
  },
  {
    "code": "def get_assessment_basic_authoring_session_for_bank(self, bank_id, proxy):\n        if not self.supports_assessment_basic_authoring():\n            raise errors.Unimplemented()\n        return sessions.AssessmentBasicAuthoringSession(bank_id, proxy, self._runtime)",
    "docstring": "Gets the ``OsidSession`` associated with the assessment authoring service for the given bank.\n\n        arg:    bank_id (osid.id.Id): the ``Id`` of a bank\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.assessment.AssessmentBasicAuthoringSession) - an\n                ``AssessmentBasicAuthoringSession``\n        raise:  NotFound - ``bank_id`` not found\n        raise:  NullArgument - ``bank_id`` or ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented -\n                ``supports_assessment_basic_authoring()`` or\n                ``supports_visibe_federation()`` is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_assessment_basic_authoring()`` and\n        ``supports_visibe_federation()`` is ``true``.*"
  },
  {
    "code": "def search_location_check(cls, location):\n        if not (isinstance(location, Mapping) and set(location.keys()) == _LOCATION_SEARCH_ARGS):\n            raise ValueError('Search location should be mapping with keys: %s' % _LOCATION_SEARCH_ARGS)\n        cls.location_check(location['lat'], location['long'])\n        radius = location['radius']\n        if not (isinstance(radius, number_types) and 0 < radius <= 20038):\n            raise ValueError(\"Radius: '{radius}' is invalid\".format(radius=radius))",
    "docstring": "Core.Client.request_search location parameter should be a dictionary that contains lat, lon and radius floats"
  },
  {
    "code": "def get_account_holds(self, account_id, **kwargs):\n        endpoint = '/accounts/{}/holds'.format(account_id)\n        return self._send_paginated_message(endpoint, params=kwargs)",
    "docstring": "Get holds on an account.\n\n        This method returns a generator which may make multiple HTTP requests\n        while iterating through it.\n\n        Holds are placed on an account for active orders or\n        pending withdraw requests.\n\n        As an order is filled, the hold amount is updated. If an order\n        is canceled, any remaining hold is removed. For a withdraw, once\n        it is completed, the hold is removed.\n\n        The `type` field will indicate why the hold exists. The hold\n        type is 'order' for holds related to open orders and 'transfer'\n        for holds related to a withdraw.\n\n        The `ref` field contains the id of the order or transfer which\n        created the hold.\n\n        Args:\n            account_id (str): Account id to get holds of.\n            kwargs (dict): Additional HTTP request parameters.\n\n        Returns:\n            generator(list): Hold information for the account. Example::\n                [\n                    {\n                        \"id\": \"82dcd140-c3c7-4507-8de4-2c529cd1a28f\",\n                        \"account_id\": \"e0b3f39a-183d-453e-b754-0c13e5bab0b3\",\n                        \"created_at\": \"2014-11-06T10:34:47.123456Z\",\n                        \"updated_at\": \"2014-11-06T10:40:47.123456Z\",\n                        \"amount\": \"4.23\",\n                        \"type\": \"order\",\n                        \"ref\": \"0a205de4-dd35-4370-a285-fe8fc375a273\",\n                    },\n                    {\n                    ...\n                    }\n                ]"
  },
  {
    "code": "def add_edges(self, from_idx, to_idx, weight=1, symmetric=False, copy=False):\n    raise NotImplementedError()",
    "docstring": "Adds all from->to edges. weight may be a scalar or 1d array.\n    If symmetric=True, also adds to->from edges with the same weights."
  },
  {
    "code": "def volumes(self):\n        return [\n            EBSVolume(res) for res in db.Resource.join(\n                ResourceProperty, Resource.resource_id == ResourceProperty.resource_id\n            ).filter(\n                Resource.resource_type_id == ResourceType.get('aws_ebs_volume').resource_type_id,\n                ResourceProperty.name == 'attachments',\n                func.JSON_CONTAINS(ResourceProperty.value, func.JSON_QUOTE(self.id))\n            ).all()\n        ]",
    "docstring": "Returns a list of the volumes attached to the instance\n\n        Returns:\n            `list` of `EBSVolume`"
  },
  {
    "code": "def get_default_options(self):\n        _, _, internal_usage = self.get_usage()\n        args = docopt(internal_usage, [])\n        return {k: v for k, v in args.items() if k.startswith('--')}",
    "docstring": "Get a dictionary of default options as used with run.\n\n        Returns\n        -------\n        dict\n            A dictionary containing option keys of the form '--beat_interval'.\n            Their values are boolean if the option is a flag, otherwise None or\n            its default value."
  },
  {
    "code": "def is_matching(cls, file_path):\n        if file_path.endswith(\".ndata\") and os.path.exists(file_path):\n            try:\n                with open(file_path, \"r+b\") as fp:\n                    local_files, dir_files, eocd = parse_zip(fp)\n                    contains_data = b\"data.npy\" in dir_files\n                    contains_metadata = b\"metadata.json\" in dir_files\n                    file_count = contains_data + contains_metadata\n                    if len(dir_files) != file_count or file_count == 0:\n                        return False\n                    return True\n            except Exception as e:\n                logging.error(\"Exception parsing ndata file: %s\", file_path)\n                logging.error(str(e))\n        return False",
    "docstring": "Return whether the given absolute file path is an ndata file."
  },
  {
    "code": "async def create_connection(self):\n        connector = self.proxy or self.loop\n        return await connector.create_connection(\n            self.session_factory, self.host, self.port, **self.kwargs)",
    "docstring": "Initiate a connection."
  },
  {
    "code": "def put_request_payment(self, bucket, payer):\n        data = RequestPayment(payer).to_xml()\n        details = self._details(\n            method=b\"PUT\",\n            url_context=self._url_context(bucket=bucket, object_name=\"?requestPayment\"),\n            body=data,\n        )\n        d = self._submit(self._query_factory(details))\n        return d",
    "docstring": "Set request payment configuration on bucket to payer.\n\n        @param bucket: The name of the bucket.\n        @param payer: The name of the payer.\n        @return: A C{Deferred} that will fire with the result of the request."
  },
  {
    "code": "def running(concurrent=False):\n    ret = []\n    if concurrent:\n        return ret\n    active = __salt__['saltutil.is_running']('state.*')\n    for data in active:\n        err = (\n            'The function \"{0}\" is running as PID {1} and was started at '\n            '{2} with jid {3}'\n        ).format(\n            data['fun'],\n            data['pid'],\n            salt.utils.jid.jid_to_time(data['jid']),\n            data['jid'],\n        )\n        ret.append(err)\n    return ret",
    "docstring": "Return a list of strings that contain state return data if a state function\n    is already running. This function is used to prevent multiple state calls\n    from being run at the same time.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' state.running"
  },
  {
    "code": "def check(line, queries):\n    line = line.strip()\n    spLine = line.replace('.', ' ').split()\n    matches = set(spLine).intersection(queries)\n    if len(matches) > 0:\n        return matches, line.split('\\t')\n    return matches, False",
    "docstring": "check that at least one of\n    queries is in list, l"
  },
  {
    "code": "def to_dict(self):\n        return dict(\n            (k, self.__dict__[k]) for k in self.__dict__ if k.find(\"_\") != 0)",
    "docstring": "to_dict will clean all protected and private properties"
  },
  {
    "code": "def set_cpu_status(self, status):\n        assert status in snap7.snap7types.cpu_statuses, 'unknown cpu state %s' % status\n        logger.debug(\"setting cpu status to %s\" % status)\n        return self.library.Srv_SetCpuStatus(self.pointer, status)",
    "docstring": "Sets the Virtual CPU status."
  },
  {
    "code": "def PDBasXMLwithSymwithPolarH(self, id):\n        print _WARNING\n        h_s_xml = urllib.urlopen(\"http://www.cmbi.ru.nl/wiwsd/rest/PDBasXMLwithSymwithPolarH/id/\" + id)\n        self.raw = h_s_xml\n        p = self.parser\n        h_s_smcra = p.read(h_s_xml, 'WHATIF_Output')\n        return h_s_smcra",
    "docstring": "Adds Hydrogen Atoms to a Structure."
  },
  {
    "code": "def keys_to_datetime(obj, *keys):\n    if not keys:\n        return obj\n    for k in keys:\n        if k not in obj:\n            continue\n        v = obj[k]\n        if not isinstance(v, string_types):\n            continue\n        obj[k] = parse_datetime(v)\n    return obj",
    "docstring": "Converts all the keys in an object to DateTime instances.\n\n        Args:\n            obj (dict): the JSON-like ``dict`` object to modify inplace.\n            keys (str): keys of the object being converted into DateTime\n                instances.\n\n        Returns:\n            dict: ``obj`` inplace.\n\n        >>> keys_to_datetime(None) is None\n        True\n        >>> keys_to_datetime({})\n        {}\n        >>> a = {}\n        >>> id(keys_to_datetime(a)) == id(a)\n        True\n        >>> a = {'one': '2016-06-06T19:41:43.039284',\n                 'two': '2016-06-06T19:41:43.039284'}\n        >>> keys_to_datetime(a) == a\n        True\n        >>> keys_to_datetime(a, 'one')['one']\n        datetime.datetime(2016, 6, 6, 19, 41, 43, 39284)\n        >>> keys_to_datetime(a, 'one')['two']\n        '2016-06-06T19:41:43.039284'"
  },
  {
    "code": "def get_crawler_stats(self):\n        self.logger.debug(\"Gathering crawler stats\")\n        the_dict = {}\n        the_dict['spiders'] = self.get_spider_stats()['spiders']\n        the_dict['machines'] = self.get_machine_stats()['machines']\n        the_dict['queue'] = self.get_queue_stats()['queues']\n        return the_dict",
    "docstring": "Gather crawler stats\n\n        @return: A dict of stats"
  },
  {
    "code": "def _assert_validators(self, validators):\n    for validator in sorted(\n        validators, key=lambda validator: validator.insertion_index):\n      try:\n        validator.verify(self)\n      except _exceptions.ValidationError as e:\n        message = validator.print_flags_with_values(self)\n        raise _exceptions.IllegalFlagValueError('%s: %s' % (message, str(e)))",
    "docstring": "Asserts if all validators in the list are satisfied.\n\n    It asserts validators in the order they were created.\n\n    Args:\n      validators: Iterable(validators.Validator), validators to be\n          verified.\n    Raises:\n      AttributeError: Raised if validators work with a non-existing flag.\n      IllegalFlagValueError: Raised if validation fails for at least one\n          validator."
  },
  {
    "code": "def start(st_reg_number):\n    divisor = 11\n    if len(st_reg_number) > 9:\n        return False\n    if len(st_reg_number) < 9:\n        return False\n    sum_total = 0\n    peso = 9\n    for i in range(len(st_reg_number)-1):\n        sum_total = sum_total + int(st_reg_number[i]) * peso\n        peso = peso - 1\n    rest_division = sum_total % divisor\n    digit = divisor - rest_division\n    if digit == 10 or digit == 11:\n        digit = 0\n    return digit == int(st_reg_number[len(st_reg_number)-1])",
    "docstring": "Checks the number valiaty for the Sergipe state"
  },
  {
    "code": "def getvalue(self):\n        if self.strategy == 0:\n            return self._delegate.getvalue()\n        self._delegate.flush()\n        self._delegate.seek(0)\n        value = self._delegate.read()\n        if not isinstance(value, six.binary_type):\n            value = value.encode('utf-8')\n        return value",
    "docstring": "Get value of file. Work around for second strategy.\n        Always returns bytes"
  },
  {
    "code": "def copy(self):\n        other = Version(None)\n        other.tokens = self.tokens[:]\n        other.seps = self.seps[:]\n        return other",
    "docstring": "Returns a copy of the version."
  },
  {
    "code": "def _fix_dynamic_class_lookup(cls, pstfx):\n    extnm = '_' + cls.__name__ + '_' + pstfx\n    mdl = sys.modules[cls.__module__]\n    setattr(mdl, extnm, cls)\n    if hasattr(cls, '__qualname__'):\n        cls.__qualname__ = extnm\n    else:\n        cls.__name__ = extnm",
    "docstring": "Fix name lookup problem that prevents pickling of dynamically\n    defined classes.\n\n    Parameters\n    ----------\n    cls : class\n      Dynamically generated class to which fix is to be applied\n    pstfx : string\n      Postfix that can be used to identify dynamically generated classes\n      that are equivalent by construction"
  },
  {
    "code": "def dump(self, f, indent=''):\n        print((\"%s&%s %s\" % (indent, self.__name, self.section_parameters)).rstrip(), file=f)\n        self.dump_children(f, indent)\n        print(\"%s&END %s\" % (indent, self.__name), file=f)",
    "docstring": "Dump this section and its children to a file-like object"
  },
  {
    "code": "def _build_category_tree(slug, reference=None, items=None):\n    if items is None:\n        items = []\n    for key in reference:\n        category = reference[key]\n        if category[\"parent\"] == slug:\n            children = _build_category_tree(category[\"nicename\"],\n                                            reference=reference)\n            category[\"children\"] = children\n            items.append(category)\n    return items",
    "docstring": "Builds a recursive tree with category relations as children."
  },
  {
    "code": "def _update_display(self, event=None):\n        try:\n            if self._showvalue:\n                self.display_value(self.scale.get())\n            if self._tickinterval:\n                self.place_ticks()\n        except IndexError:\n            pass",
    "docstring": "Redisplay the ticks and the label so that they adapt to the new size of the scale."
  },
  {
    "code": "def apply_obb(self):\n        if len(self.root) == 1:\n            matrix, bounds = polygons.polygon_obb(\n                self.polygons_closed[self.root[0]])\n            self.apply_transform(matrix)\n            return matrix\n        else:\n            raise ValueError('Not implemented for multibody geometry')",
    "docstring": "Transform the current path so that its OBB is axis aligned\n        and OBB center is at the origin."
  },
  {
    "code": "def save_agent_profile(self, profile):\n        request = HTTPRequest(\n            method=\"PUT\",\n            resource=\"agents/profile\",\n            content=profile.content,\n        )\n        if profile.content_type is not None:\n            request.headers[\"Content-Type\"] = profile.content_type\n        else:\n            request.headers[\"Content-Type\"] = \"application/octet-stream\"\n        if profile.etag is not None:\n            request.headers[\"If-Match\"] = profile.etag\n        request.query_params = {\n            \"profileId\": profile.id,\n            \"agent\": profile.agent.to_json(self.version)\n        }\n        lrs_response = self._send_request(request)\n        lrs_response.content = profile\n        return lrs_response",
    "docstring": "Save an agent profile doc to the LRS\n\n        :param profile: Agent profile doc to be saved\n        :type profile: :class:`tincan.documents.agent_profile_document.AgentProfileDocument`\n        :return: LRS Response object with the saved agent profile doc as content\n        :rtype: :class:`tincan.lrs_response.LRSResponse`"
  },
  {
    "code": "def gatherBy(self, func):\n        'Generate only rows for which the given func returns True.'\n        for i in rotate_range(len(self.rows), self.cursorRowIndex):\n            try:\n                r = self.rows[i]\n                if func(r):\n                    yield r\n            except Exception:\n                pass",
    "docstring": "Generate only rows for which the given func returns True."
  },
  {
    "code": "def would_move_be_promotion(self):\n        return (self._end_loc.rank == 0 and not self.color) or \\\n            (self._end_loc.rank == 7 and self.color)",
    "docstring": "Finds if move from current location would be a promotion"
  },
  {
    "code": "def exists(self, key, fresh=False):\n        key = key.upper()\n        if key in self._deleted:\n            return False\n        return self.get(key, fresh=fresh, default=missing) is not missing",
    "docstring": "Check if key exists\n\n        :param key: the name of setting variable\n        :param fresh: if key should be taken from source direclty\n        :return: Boolean"
  },
  {
    "code": "def set_logger(self, log_level=logging.INFO):\n        logging.basicConfig(\n            format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n            level=log_level,\n            stream=sys.stderr)\n        self.logger = logging.getLogger(__name__)\n        logging.getLogger('requests').setLevel(logging.WARNING)",
    "docstring": "Configure the logger with log_level."
  },
  {
    "code": "def asdict(self) -> Dict[str, Union[Dict, Union[str, Dict]]]:\n        return {\n            \"service\": self.service.name,\n            **self.signature.serialize(),\n        }",
    "docstring": "Return a dictionary describing the method.\n\n        This can be used to dump the information into a JSON file."
  },
  {
    "code": "def decode(obj, content_type):\n    try:\n        decoder = _decoders_map[content_type]\n        return decoder(obj)\n    except KeyError:\n        raise _errors.UnsupportedFormatError(content_type)",
    "docstring": "Decode an object ton a one of the default content types to a numpy array.\n\n    Args:\n        obj (object): to be decoded.\n        content_type (str): content type to be used.\n\n    Returns:\n        np.array: decoded object."
  },
  {
    "code": "def AddMonths(start_date, months):\n  current_date = start_date\n  i = 0\n  while i < months:\n    month_days = calendar.monthrange(current_date.year, current_date.month)[1]\n    current_date += timedelta(days=month_days)\n    i += 1\n  return current_date",
    "docstring": "A simple convenience utility for adding months to a given start date.\n\n  This increments the months by adding the number of days in the current month\n  to the current month, for each month.\n\n  Args:\n    start_date: date The date months are being added to.\n    months: int The number of months to add.\n\n  Returns:\n    A date equal to the start date incremented by the given number of months."
  },
  {
    "code": "def _check_uuid_fmt(self):\n        if self.uuid_fmt not in UUIDField.FORMATS:\n            raise FieldValueRangeException(\n                \"Unsupported uuid_fmt ({})\".format(self.uuid_fmt))",
    "docstring": "Checks .uuid_fmt, and raises an exception if it is not valid."
  },
  {
    "code": "def setOverlayRaw(self, ulOverlayHandle, pvBuffer, unWidth, unHeight, unDepth):\n        fn = self.function_table.setOverlayRaw\n        result = fn(ulOverlayHandle, pvBuffer, unWidth, unHeight, unDepth)\n        return result",
    "docstring": "Separate interface for providing the data as a stream of bytes, but there is an upper bound on data \n        that can be sent. This function can only be called by the overlay's renderer process."
  },
  {
    "code": "def mv(hdfs_src, hdfs_dst):\n    cmd = \"hadoop fs -mv %s %s\" % (hdfs_src, hdfs_dst)\n    rcode, stdout, stderr = _checked_hadoop_fs_command(cmd)",
    "docstring": "Move a file on hdfs\n\n    :param hdfs_src: Source (str)\n    :param hdfs_dst: Destination (str)\n    :raises: IOError: If unsuccessful"
  },
  {
    "code": "def make_analogous_scheme(self, angle=30, mode='ryb'):\n    h, s, l = self.__hsl\n    if mode == 'ryb': h = rgb_to_ryb(h)\n    h += 360\n    h1 = (h - angle) % 360\n    h2 = (h + angle) % 360\n    if mode == 'ryb':\n      h1 = ryb_to_rgb(h1)\n      h2 = ryb_to_rgb(h2)\n    return (Color((h1, s,  l), 'hsl', self.__a, self.__wref),\n        Color((h2, s,  l), 'hsl', self.__a, self.__wref))",
    "docstring": "Return two colors analogous to this one.\n\n    Args:\n      :angle:\n        The angle between the hues of the created colors and this one.\n      :mode:\n        Select which color wheel to use for the generation (ryb/rgb).\n\n    Returns:\n      A tuple of grapefruit.Colors analogous to this one.\n\n    >>> c1 = Color.from_hsl(30, 1, 0.5)\n\n    >>> c2, c3 = c1.make_analogous_scheme(angle=60, mode='rgb')\n    >>> c2.hsl\n    (330.0, 1.0, 0.5)\n    >>> c3.hsl\n    (90.0, 1.0, 0.5)\n\n    >>> c2, c3 = c1.make_analogous_scheme(angle=10, mode='rgb')\n    >>> c2.hsl\n    (20.0, 1.0, 0.5)\n    >>> c3.hsl\n    (40.0, 1.0, 0.5)"
  },
  {
    "code": "def get_cust_cols(path):\n    required_keys = [\"title\", \"id\", \"sType\", \"visible\"]\n    with open(path, 'r') as f:\n        try:\n            cust_cols = ast.literal_eval(f.read())\n        except Exception as err:\n            sys.stderr.write(\"Invalid custom columns file: {}\\n\".format(path))\n            sys.stderr.write(\"{}\\n\".format(err))\n            sys.exit(1)\n    for col in cust_cols:\n        for required_key in required_keys:\n            if required_key not in col:\n                sys.stderr.write(\"Missing required key '{}' in custom \"\n                                 \"column {}\\n\".format(required_key, col))\n                sys.exit(1)\n            if \"jsonxs\" not in col and \"tpl\" not in col:\n                sys.stderr.write(\"You need to specify 'jsonxs' or 'tpl' \"\n                                 \"for custom column {}\\n\".format(col))\n                sys.exit(1)\n    return cust_cols",
    "docstring": "Load custom column definitions."
  },
  {
    "code": "def ok(self):\n        rgb, hsv, hexa = self.square.get()\n        if self.alpha_channel:\n            hexa = self.hexa.get()\n            rgb += (self.alpha.get(),)\n        self.color = rgb, hsv, hexa\n        self.destroy()",
    "docstring": "Validate color selection and destroy dialog."
  },
  {
    "code": "def create_config(self, name, data, labels=None):\n        if not isinstance(data, bytes):\n            data = data.encode('utf-8')\n        data = base64.b64encode(data)\n        if six.PY3:\n            data = data.decode('ascii')\n        body = {\n            'Data': data,\n            'Name': name,\n            'Labels': labels\n        }\n        url = self._url('/configs/create')\n        return self._result(\n            self._post_json(url, data=body), True\n        )",
    "docstring": "Create a config\n\n            Args:\n                name (string): Name of the config\n                data (bytes): Config data to be stored\n                labels (dict): A mapping of labels to assign to the config\n\n            Returns (dict): ID of the newly created config"
  },
  {
    "code": "def getClient(self):\n        client = self.Schema().getField('Client').get(self)\n        if client:\n            return client\n        client = self.aq_parent\n        if IClient.providedBy(client):\n            return client",
    "docstring": "Retrieves the Client for which the current Batch is attached to\n           Tries to retrieve the Client from the Schema property, but if not\n           found, searches for linked ARs and retrieve the Client from the\n           first one. If the Batch has no client, returns None."
  },
  {
    "code": "def _get_home():\n    try:\n        if six.PY2 and sys.platform == 'win32':\n            path = os.path.expanduser(b\"~\").decode(sys.getfilesystemencoding())\n        else:\n            path = os.path.expanduser(\"~\")\n    except ImportError:\n        pass\n    else:\n        if os.path.isdir(path):\n            return path\n    for evar in ('HOME', 'USERPROFILE', 'TMP'):\n        path = os.environ.get(evar)\n        if path is not None and os.path.isdir(path):\n            return path\n    return None",
    "docstring": "Find user's home directory if possible.\n    Otherwise, returns None.\n\n    :see:  http://mail.python.org/pipermail/python-list/2005-February/325395.html\n\n    This function is copied from matplotlib version 1.4.3, Jan 2016"
  },
  {
    "code": "def get_mor_by_property(service_instance, object_type, property_value, property_name='name', container_ref=None):\n    object_list = get_mors_with_properties(service_instance, object_type, property_list=[property_name], container_ref=container_ref)\n    for obj in object_list:\n        obj_id = six.text_type(obj.get('object', '')).strip('\\'\"')\n        if obj[property_name] == property_value or property_value == obj_id:\n            return obj['object']\n    return None",
    "docstring": "Returns the first managed object reference having the specified property value.\n\n    service_instance\n        The Service Instance from which to obtain managed object references.\n\n    object_type\n        The type of content for which to obtain managed object references.\n\n    property_value\n        The name of the property for which to obtain the managed object reference.\n\n    property_name\n        An object property used to return the specified object reference results. Defaults to ``name``.\n\n    container_ref\n        An optional reference to the managed object to search under. Can either be an object of type Folder, Datacenter,\n        ComputeResource, Resource Pool or HostSystem. If not specified, default behaviour is to search under the inventory\n        rootFolder."
  },
  {
    "code": "def _unpack(self, content):\n        if self.compressor:\n            try:\n                content = self.compressor.decompress(content)\n            except CompressError:\n                pass\n        if self.serializer:\n            content = self.serializer.deserialize(content)\n        return content",
    "docstring": "unpack cache using serializer and compressor"
  },
  {
    "code": "def clear(self, objtype=[]):\n        r\n        if len(objtype) == 0:\n            super().clear()\n        else:\n            names = [obj.name for obj in self]\n            for name in names:\n                try:\n                    obj = self[name]\n                    for t in objtype:\n                        if obj._isa(t):\n                            self.purge_object(obj)\n                except KeyError:\n                    pass",
    "docstring": "r\"\"\"\n        Clears objects from the project entirely or selectively, depdening on\n        the received arguments.\n\n        Parameters\n        ----------\n        objtype : list of strings\n            A list containing the object type(s) to be removed.  If no types\n            are specified, then all objects are removed.  To clear only objects\n            of a specific type, use *'network'*, *'geometry'*, *'phase'*,\n            *'physics'*, or *'algorithm'*.  It's also possible to use\n            abbreviations, like *'geom'*."
  },
  {
    "code": "def create_user(self, claims):\n        username_claim = settings.USERNAME_CLAIM\n        usermodel = get_user_model()\n        user, created = usermodel.objects.get_or_create(**{\n            usermodel.USERNAME_FIELD: claims[username_claim]\n        })\n        if created or not user.password:\n            user.set_unusable_password()\n            logger.debug(\"User '{}' has been created.\".format(claims[username_claim]))\n        return user",
    "docstring": "Create the user if it doesn't exist yet\n\n        Args:\n            claims (dict): claims from the access token\n\n        Returns:\n            django.contrib.auth.models.User: A Django user"
  },
  {
    "code": "def NewFromJSON(data):\n        s = Shake(\n            id=data.get('id', None),\n            name=data.get('name', None),\n            url=data.get('url', None),\n            thumbnail_url=data.get('thumbnail_url', None),\n            description=data.get('description', None),\n            type=data.get('type', None),\n            created_at=data.get('created_at', None),\n            updated_at=data.get('updated_at', None)\n        )\n        if data.get('owner', None):\n            s.owner = User.NewFromJSON(data.get('owner', None))\n        return s",
    "docstring": "Create a new Shake instance from a JSON dict.\n\n        Args:\n            data (dict): JSON dictionary representing a Shake.\n\n        Returns:\n            A Shake instance."
  },
  {
    "code": "def from_design_day_properties(cls, name, day_type, location, analysis_period,\n                                   dry_bulb_max, dry_bulb_range, humidity_type,\n                                   humidity_value, barometric_p, wind_speed, wind_dir,\n                                   sky_model, sky_properties):\n        dry_bulb_condition = DryBulbCondition(\n            dry_bulb_max, dry_bulb_range)\n        humidity_condition = HumidityCondition(\n            humidity_type, humidity_value, barometric_p)\n        wind_condition = WindCondition(\n            wind_speed, wind_dir)\n        if sky_model == 'ASHRAEClearSky':\n            sky_condition = OriginalClearSkyCondition.from_analysis_period(\n                analysis_period, sky_properties[0])\n        elif sky_model == 'ASHRAETau':\n            sky_condition = RevisedClearSkyCondition.from_analysis_period(\n                analysis_period, sky_properties[0], sky_properties[-1])\n        return cls(name, day_type, location, dry_bulb_condition,\n                   humidity_condition, wind_condition, sky_condition)",
    "docstring": "Create a design day object from various key properties.\n\n        Args:\n            name: A text string to set the name of the design day\n            day_type: Choose from 'SummerDesignDay', 'WinterDesignDay' or other\n                EnergyPlus days\n            location: Location for the design day\n            analysis_period: Analysis period for the design day\n            dry_bulb_max: Maximum dry bulb temperature over the design day (in C).\n            dry_bulb_range: Dry bulb range over the design day (in C).\n            humidity_type: Type of humidity to use. Choose from\n                Wetbulb, Dewpoint, HumidityRatio, Enthalpy\n            humidity_value: The value of the condition above.\n            barometric_p: Barometric pressure in Pa.\n            wind_speed: Wind speed over the design day in m/s.\n            wind_dir: Wind direction over the design day in degrees.\n            sky_model: Type of solar model to use.  Choose from\n                ASHRAEClearSky, ASHRAETau\n            sky_properties: A list of properties describing the sky above.\n                For ASHRAEClearSky this is a single value for clearness\n                For ASHRAETau, this is the tau_beam and tau_diffuse"
  },
  {
    "code": "def get_query(self, query_params=None):\n        if query_params is None:\n            query_params = {}\n        query = ''\n        query_params['idSite'] = self.site_id\n        if self.api_token is not None:\n            query_params['token_auth'] = self.api_token\n        for key, value in query_params.iteritems():\n            if isinstance(value, list):\n                value = ','.join(value)\n            query += '{}={}&'.format(str(key), str(value))\n        return query[:-1]",
    "docstring": "Return a query string"
  },
  {
    "code": "def to_type(cls, typename):\n        NAME_TYPES = {cls.TYPE_NAMES[x]: x for x in cls.TYPE_NAMES}\n        return NAME_TYPES.get(typename, None)",
    "docstring": "Converts a type ID to name. On error returns None"
  },
  {
    "code": "def MAH(z, zi, Mi, **cosmo):\n    z = np.array(z, ndmin=1, dtype=float)\n    dMdt_array = np.empty_like(z)\n    Mz_array = np.empty_like(z)\n    for i_ind, zval in enumerate(z):\n        dMdt, Mz = acc_rate(zval, zi, Mi, **cosmo)\n        dMdt_array[i_ind] = dMdt\n        Mz_array[i_ind] = Mz\n    return(dMdt_array, Mz_array)",
    "docstring": "Calculate mass accretion history by looping function acc_rate\n        over redshift steps 'z' for halo of mass 'Mi' at redshift 'zi'\n\n    Parameters\n    ----------\n    z : float / numpy array\n        Redshift to output MAH over. Note zi<z always\n    zi : float\n        Redshift\n    Mi : float\n        Halo mass at redshift 'zi'\n    cosmo : dict\n        Dictionary of cosmological parameters, similar in format to:\n        {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275,\n         'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0,\n         'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6}\n\n    Returns\n    -------\n    (dMdt, Mz) : float / numpy arrays of equivalent size to 'z'\n        Accretion rate [Msol/yr], halo mass [Msol] at redshift 'z'"
  },
  {
    "code": "def _generic_format(self, raid_config, controller=None):\n        logical_drives = raid_config[\"LogicalDrives\"]\n        logical_disks = []\n        controller = controller\n        for ld in logical_drives:\n            prop = {'size_gb': ld['CapacityGiB'],\n                    'raid_level': ld['Raid'].strip('Raid'),\n                    'root_device_hint': {\n                        'wwn': '0x' + ld['VolumeUniqueIdentifier']},\n                    'controller': controller,\n                    'physical_disks': ld['DataDrives'],\n                    'volume_name': ld['LogicalDriveName']}\n            logical_disks.append(prop)\n        return logical_disks",
    "docstring": "Convert redfish data of current raid config to generic format.\n\n        :param raid_config: Raid configuration dictionary\n        :param controller: Array controller model in post_create read else\n                           None\n        :returns: current raid config."
  },
  {
    "code": "def _hasExplicitOid(store, table):\n    return any(info[1] == 'oid' for info\n               in store.querySchemaSQL(\n                   'PRAGMA *DATABASE*.table_info({})'.format(table)))",
    "docstring": "Does the given table have an explicit oid column?"
  },
  {
    "code": "def do_reset_ids(concatenated_meta_df, data_df, concat_direction):\n    if concat_direction == \"horiz\":\n        assert concatenated_meta_df.index.equals(data_df.columns), (\n            \"cids in concatenated_meta_df do not agree with cids in data_df.\")\n        reset_ids_in_meta_df(concatenated_meta_df)\n        data_df.columns = pd.Index(concatenated_meta_df.index.values)\n    elif concat_direction == \"vert\":\n        assert concatenated_meta_df.index.equals(data_df.index), (\n            \"rids in concatenated_meta_df do not agree with rids in data_df.\")\n        reset_ids_in_meta_df(concatenated_meta_df)\n        data_df.index = pd.Index(concatenated_meta_df.index.values)",
    "docstring": "Reset ids in concatenated metadata and data dfs to unique integers and\n    save the old ids in a metadata column.\n\n    Note that the dataframes are modified in-place.\n\n    Args:\n        concatenated_meta_df (pandas df)\n        data_df (pandas df)\n        concat_direction (string): 'horiz' or 'vert'\n\n    Returns:\n        None (dfs modified in-place)"
  },
  {
    "code": "def send_frame(self, frame):\n        if self.get_mask_key:\n            frame.get_mask_key = self.get_mask_key\n        data = frame.format()\n        length = len(data)\n        trace(\"send: \" + repr(data))\n        with self.lock:\n            while data:\n                l = self._send(data)\n                data = data[l:]\n        return length",
    "docstring": "Send the data frame.\n\n        frame: frame data created  by ABNF.create_frame\n\n        >>> ws = create_connection(\"ws://echo.websocket.org/\")\n        >>> frame = ABNF.create_frame(\"Hello\", ABNF.OPCODE_TEXT)\n        >>> ws.send_frame(frame)\n        >>> cont_frame = ABNF.create_frame(\"My name is \", ABNF.OPCODE_CONT, 0)\n        >>> ws.send_frame(frame)\n        >>> cont_frame = ABNF.create_frame(\"Foo Bar\", ABNF.OPCODE_CONT, 1)\n        >>> ws.send_frame(frame)"
  },
  {
    "code": "def serialize_seeds(seeds, block):\n    for seed_dict in block.seeds:\n        seed = etree.SubElement(seeds, 'seed')\n        seed.set('option', unicode(seed_dict.get('answer', 0) + 1))\n        seed.text = seed_dict.get('rationale', '')",
    "docstring": "Serialize the seeds in peer instruction XBlock to xml\n\n    Args:\n        seeds (lxml.etree.Element): The <seeds> XML element.\n        block (PeerInstructionXBlock): The XBlock with configuration to serialize.\n\n    Returns:\n        None"
  },
  {
    "code": "def keys_to_values(self, keys):\n        \"Return the items in the keystore with keys in `keys`.\"\n        return dict((k, v) for k, v in self.data.items() if k in keys)",
    "docstring": "Return the items in the keystore with keys in `keys`."
  },
  {
    "code": "def copy(self):\n        vs = ValueSet(bits=self.bits)\n        vs._regions = self._regions.copy()\n        vs._region_base_addrs = self._region_base_addrs.copy()\n        vs._reversed = self._reversed\n        vs._si = self._si.copy()\n        return vs",
    "docstring": "Make a copy of self and return.\n\n        :return: A new ValueSet object.\n        :rtype: ValueSet"
  },
  {
    "code": "def visit_BoolOp(self, node):\n        return sum((self.visit(value) for value in node.values), [])",
    "docstring": "Return type may come from any boolop operand."
  },
  {
    "code": "def dimers(primer1, primer2, concentrations=[5e-7, 3e-11]):\n    nupack = coral.analysis.NUPACK([primer1.primer(), primer2.primer(),\n                                    primer1.primer().reverse_complement(),\n                                    primer2.primer().reverse_complement()])\n    primer_concs = [concentrations[0]] * 2\n    template_concs = [concentrations[1]] * 2\n    concs = primer_concs + template_concs\n    nupack_concs = nupack.concentrations(2, conc=concs)\n    dimer_conc = nupack_concs['concentrations'][5]\n    return dimer_conc / concs[0]",
    "docstring": "Calculate expected fraction of primer dimers.\n\n    :param primer1: Forward primer.\n    :type primer1: coral.DNA\n    :param primer2: Reverse primer.\n    :type primer2: coral.DNA\n    :param template: DNA template.\n    :type template: coral.DNA\n    :param concentrations: list of concentrations for primers and the\n                           template. Defaults are those for PCR with 1kb\n                           template.\n    :type concentrations: list\n    :returns: Fraction of dimers versus the total amount of primer added.\n    :rtype: float"
  },
  {
    "code": "def _handle_entity(self, token):\n        token = self._tokens.pop()\n        if isinstance(token, tokens.HTMLEntityNumeric):\n            token = self._tokens.pop()\n            if isinstance(token, tokens.HTMLEntityHex):\n                text = self._tokens.pop()\n                self._tokens.pop()\n                return HTMLEntity(text.text, named=False, hexadecimal=True,\n                                  hex_char=token.char)\n            self._tokens.pop()\n            return HTMLEntity(token.text, named=False, hexadecimal=False)\n        self._tokens.pop()\n        return HTMLEntity(token.text, named=True, hexadecimal=False)",
    "docstring": "Handle a case where an HTML entity is at the head of the tokens."
  },
  {
    "code": "def unlink_parent_dir(path: Path) -> None:\n    logger.info(f\"unlink {str(path)}\")\n    path.unlink()\n    parent_path = path.parent\n    try:\n        parent_path.rmdir()\n        logger.info(f\"rmdir {str(parent_path)}\")\n    except OSError as oe:\n        logger.debug(f\"Did not remove {str(parent_path)}: {str(oe)}\")",
    "docstring": "Remove a file and if the dir is empty remove it"
  },
  {
    "code": "def validate_meta(meta):\n    if not isinstance(meta, (dict,)):\n        raise TypeError('Model Meta \"linguist\" must be a dict')\n    required_keys = (\"identifier\", \"fields\")\n    for key in required_keys:\n        if key not in meta:\n            raise KeyError('Model Meta \"linguist\" dict requires %s to be defined', key)\n    if not isinstance(meta[\"fields\"], (list, tuple)):\n        raise ImproperlyConfigured(\n            \"Linguist Meta's fields attribute must be a list or tuple\"\n        )",
    "docstring": "Validates Linguist Meta attribute."
  },
  {
    "code": "def _consume_add_and_get_tag(self, consume_rpc_result):\n        consumer_tag = consume_rpc_result['consumer_tag']\n        self._channel.add_consumer_tag(consumer_tag)\n        return consumer_tag",
    "docstring": "Add the tag to the channel and return it.\n\n        :param dict consume_rpc_result:\n\n        :rtype: str"
  },
  {
    "code": "def process_post_category(self, bulk_mode, api_category):\n        category = None\n        if bulk_mode:\n            category = self.ref_data_map[\"categories\"].get(api_category[\"ID\"])\n        if not category:\n            category, created = Category.objects.get_or_create(site_id=self.site_id,\n                                                               wp_id=api_category[\"ID\"],\n                                                               defaults=self.api_object_data(\"category\", api_category))\n            if category and not created:\n                self.update_existing_category(category, api_category)\n            if category:\n                self.ref_data_map[\"categories\"][api_category[\"ID\"]] = category\n        return category",
    "docstring": "Create or update a Category related to a post.\n\n        :param bulk_mode: If True, minimize db operations by bulk creating post objects\n        :param api_category: the API data for the Category\n        :return: the Category object"
  },
  {
    "code": "def ij_jlk_to_ilk(A, B):\n    return A.dot(B.reshape(B.shape[0], -1)).reshape(A.shape[0], B.shape[1], B.shape[2])",
    "docstring": "Faster version of einsum 'ij,jlk->ilk'"
  },
  {
    "code": "def get_validator_change(cls, bigchain):\n        latest_block = bigchain.get_latest_block()\n        if latest_block is None:\n            return None\n        return bigchain.get_validator_change(latest_block['height'])",
    "docstring": "Return the validator set from the most recent approved block\n\n        :return: {\n            'height': <block_height>,\n            'validators': <validator_set>\n        }"
  },
  {
    "code": "def empty(self):\n        return any(len(self._get_axis(a)) == 0 for a in self._AXIS_ORDERS)",
    "docstring": "Indicator whether DataFrame is empty.\n\n        True if DataFrame is entirely empty (no items), meaning any of the\n        axes are of length 0.\n\n        Returns\n        -------\n        bool\n            If DataFrame is empty, return True, if not return False.\n\n        See Also\n        --------\n        Series.dropna\n        DataFrame.dropna\n\n        Notes\n        -----\n        If DataFrame contains only NaNs, it is still not considered empty. See\n        the example below.\n\n        Examples\n        --------\n        An example of an actual empty DataFrame. Notice the index is empty:\n\n        >>> df_empty = pd.DataFrame({'A' : []})\n        >>> df_empty\n        Empty DataFrame\n        Columns: [A]\n        Index: []\n        >>> df_empty.empty\n        True\n\n        If we only have NaNs in our DataFrame, it is not considered empty! We\n        will need to drop the NaNs to make the DataFrame empty:\n\n        >>> df = pd.DataFrame({'A' : [np.nan]})\n        >>> df\n            A\n        0 NaN\n        >>> df.empty\n        False\n        >>> df.dropna().empty\n        True"
  },
  {
    "code": "def _model_to_dict(obj):\n        result = _properties_model_to_dict(obj.properties)\n        for attribute in ('metadata', 'snapshot'):\n            try:\n                value = getattr(obj, attribute)\n            except AttributeError:\n                continue\n            if value:\n                result[attribute] = value\n        return result",
    "docstring": "Convert object model to dict.\n\n        Args:\n            obj: Object model.\n\n        Returns:\n            dict: Converted model."
  },
  {
    "code": "def backend_routing(self, context):\n        satosa_logging(logger, logging.DEBUG, \"Routing to backend: %s \" % context.target_backend, context.state)\n        backend = self.backends[context.target_backend][\"instance\"]\n        context.state[STATE_KEY] = context.target_frontend\n        return backend",
    "docstring": "Returns the targeted backend and an updated state\n\n        :type context: satosa.context.Context\n        :rtype satosa.backends.base.BackendModule\n\n        :param context: The request context\n        :return: backend"
  },
  {
    "code": "def get_api_field_data(self):\n        field = self.setup_field()\n        d = {\n            'class': field.__class__.__name__,\n            'widget': {\n                'class': field.widget.__class__.__name__\n            }\n        }\n        try:\n            d['input_type'] = field.widget.input_type\n        except AttributeError:\n            d['input_type'] = None\n        return d",
    "docstring": "Field data to serialize for use on front-end side, for example\n        will include choices available for a choice field"
  },
  {
    "code": "def __update_throughput(table_name, key_name, read_units, write_units):\n    try:\n        current_ru = dynamodb.get_provisioned_table_read_units(table_name)\n        current_wu = dynamodb.get_provisioned_table_write_units(table_name)\n    except JSONResponseError:\n        raise\n    try:\n        table_status = dynamodb.get_table_status(table_name)\n    except JSONResponseError:\n        raise\n    logger.debug('{0} - Table status is {1}'.format(table_name, table_status))\n    if table_status != 'ACTIVE':\n        logger.warning(\n            '{0} - Not performing throughput changes when table '\n            'is {1}'.format(table_name, table_status))\n        return\n    if get_table_option(key_name, 'always_decrease_rw_together'):\n        read_units, write_units = __calculate_always_decrease_rw_values(\n            table_name,\n            read_units,\n            current_ru,\n            write_units,\n            current_wu)\n        if read_units == current_ru and write_units == current_wu:\n            logger.info('{0} - No changes to perform'.format(table_name))\n            return\n    dynamodb.update_table_provisioning(\n        table_name,\n        key_name,\n        int(read_units),\n        int(write_units))",
    "docstring": "Update throughput on the DynamoDB table\n\n    :type table_name: str\n    :param table_name: Name of the DynamoDB table\n    :type key_name: str\n    :param key_name: Configuration option key name\n    :type read_units: int\n    :param read_units: New read unit provisioning\n    :type write_units: int\n    :param write_units: New write unit provisioning"
  },
  {
    "code": "def num_species(self):\n        all_headers = reduce(lambda x, y: set(x) | set(y),\n                             (rec.get_names() for rec in self.records))\n        return len(all_headers)",
    "docstring": "Returns the number of species found over all records"
  },
  {
    "code": "def consumer_partitions_for_topic(consumer, topic):\n    topic_partitions = []\n    partitions = consumer.partitions_for_topic(topic)\n    if partitions is not None:\n        for partition in partitions:\n            topic_partitions.append(TopicPartition(topic, partition))\n    else:\n        logging.error(\n            \"No partitions found for topic {}. Maybe it doesn't exist?\".format(topic),\n        )\n    return topic_partitions",
    "docstring": "Returns a list of all TopicPartitions for a given topic.\n\n    Arguments:\n        consumer: an initialized KafkaConsumer\n        topic: a topic name to fetch TopicPartitions for\n\n    :returns:\n        list(TopicPartition): A list of TopicPartitions that belong to the given topic"
  },
  {
    "code": "def _config():\n    status_url = __salt__['config.get']('nagios.status_url') or \\\n        __salt__['config.get']('nagios:status_url')\n    if not status_url:\n        raise CommandExecutionError('Missing Nagios URL in the configuration.')\n    username = __salt__['config.get']('nagios.username') or \\\n        __salt__['config.get']('nagios:username')\n    password = __salt__['config.get']('nagios.password') or \\\n        __salt__['config.get']('nagios:password')\n    return {\n        'url': status_url,\n        'username': username,\n        'password': password\n    }",
    "docstring": "Get configuration items for URL, Username and Password"
  },
  {
    "code": "def scramble_string(self, length):\n        return fake.text(length) if length > 5 else ''.join([fake.random_letter() for n in range(0, length)])",
    "docstring": "Return random string"
  },
  {
    "code": "def filter_embeddings(embeddings, vocab, dim):\n    if not isinstance(embeddings, dict):\n        return\n    _embeddings = np.zeros([len(vocab), dim])\n    for word in vocab:\n        if word in embeddings:\n            word_idx = vocab[word]\n            _embeddings[word_idx] = embeddings[word]\n    return _embeddings",
    "docstring": "Loads word vectors in numpy array.\n\n    Args:\n        embeddings (dict): a dictionary of numpy array.\n        vocab (dict): word_index lookup table.\n\n    Returns:\n        numpy array: an array of word embeddings."
  },
  {
    "code": "def get_dropout(x, rate=0.0, init=True):\n  if init or rate == 0:\n    return x\n  return tf.layers.dropout(x, rate=rate, training=True)",
    "docstring": "Dropout x with dropout_rate = rate.\n\n  Apply zero dropout during init or prediction time.\n\n  Args:\n    x: 4-D Tensor, shape=(NHWC).\n    rate: Dropout rate.\n    init: Initialization.\n  Returns:\n    x: activations after dropout."
  },
  {
    "code": "def remove_quotes(self, value):\n        if not value:\n            return value\n        if value[0] == value[-1] == '\"':\n            return value[1:-1].replace('\\\\\"', '\"')\n        if value[0] == value[-1] == \"'\":\n            return value[1:-1].replace(\"\\\\'\", \"'\")\n        return value",
    "docstring": "Remove any surrounding quotes from a value and unescape any contained\n        quotes of that type."
  },
  {
    "code": "def insert_json(table=None,\n                bulk_size=1000,\n                concurrency=25,\n                hosts=None,\n                output_fmt=None):\n    if not hosts:\n        return print_only(table)\n    queries = (to_insert(table, d) for d in dicts_from_stdin())\n    bulk_queries = as_bulk_queries(queries, bulk_size)\n    print('Executing inserts: bulk_size={} concurrency={}'.format(\n        bulk_size, concurrency), file=sys.stderr)\n    stats = Stats()\n    with clients.client(hosts, concurrency=concurrency) as client:\n        f = partial(aio.measure, stats, client.execute_many)\n        try:\n            aio.run_many(f, bulk_queries, concurrency)\n        except clients.SqlException as e:\n            raise SystemExit(str(e))\n    try:\n        print(format_stats(stats.get(), output_fmt))\n    except KeyError:\n        if not stats.sampler.values:\n            raise SystemExit('No data received via stdin')\n        raise",
    "docstring": "Insert JSON lines fed into stdin into a Crate cluster.\n\n    If no hosts are specified the statements will be printed.\n\n    Args:\n        table: Target table name.\n        bulk_size: Bulk size of the insert statements.\n        concurrency: Number of operations to run concurrently.\n        hosts: hostname:port pairs of the Crate nodes"
  },
  {
    "code": "def merge_entities(self, from_entity_ids, to_entity_id, force=False, mount_point=DEFAULT_MOUNT_POINT):\n        params = {\n            'from_entity_ids': from_entity_ids,\n            'to_entity_id': to_entity_id,\n            'force': force,\n        }\n        api_path = '/v1/{mount_point}/entity/merge'.format(mount_point=mount_point)\n        return self._adapter.post(\n            url=api_path,\n            json=params,\n        )",
    "docstring": "Merge many entities into one entity.\n\n        Supported methods:\n            POST: /{mount_point}/entity/merge. Produces: 204 (empty body)\n\n        :param from_entity_ids: Entity IDs which needs to get merged.\n        :type from_entity_ids: array\n        :param to_entity_id: Entity ID into which all the other entities need to get merged.\n        :type to_entity_id: str | unicode\n        :param force: Setting this will follow the 'mine' strategy for merging MFA secrets. If there are secrets of the\n            same type both in entities that are merged from and in entity into which all others are getting merged,\n            secrets in the destination will be unaltered. If not set, this API will throw an error containing all the\n            conflicts.\n        :type force: bool\n        :param mount_point: The \"path\" the method/backend was mounted on.\n        :type mount_point: str | unicode\n        :return: The response of the request.\n        :rtype: requests.Response"
  },
  {
    "code": "def delete(self):\n        ret = False\n        q = self.query\n        pk = self.pk\n        if pk:\n            pk_name = self.schema.pk.name\n            self.query.is_field(pk_name, pk).delete()\n            setattr(self, pk_name, None)\n            self.reset_modified()\n            for field_name in self.schema.fields:\n                if getattr(self, field_name, None) != None:\n                    self.modified_fields.add(field_name)\n            ret = True\n        return ret",
    "docstring": "delete the object from the db if pk is set"
  },
  {
    "code": "def parse_xml(self, node):\n        self._set_properties(node)\n        self.name = node.get('name', None)\n        self.opacity = node.get('opacity', self.opacity)\n        self.visible = node.get('visible', self.visible)\n        image_node = node.find('image')\n        self.source = image_node.get('source', None)\n        self.trans = image_node.get('trans', None)\n        return self",
    "docstring": "Parse an Image Layer from ElementTree xml node\n\n        :param node: ElementTree xml node\n        :return: self"
  },
  {
    "code": "def list_packages_in_eups_table(table_text):\n    logger = logging.getLogger(__name__)\n    pattern = re.compile(r'setupRequired\\((?P<name>\\w+)\\)')\n    listed_packages = [m.group('name') for m in pattern.finditer(table_text)]\n    logger.debug('Packages listed in the table file: %r', listed_packages)\n    return listed_packages",
    "docstring": "List the names of packages that are required by an EUPS table file.\n\n    Parameters\n    ----------\n    table_text : `str`\n        The text content of an EUPS table file.\n\n    Returns\n    -------\n    names : `list` [`str`]\n        List of package names that are required byy the EUPS table file."
  },
  {
    "code": "def set_device(cuda, local_rank):\n    if cuda:\n        torch.cuda.set_device(local_rank)\n        device = torch.device('cuda')\n    else:\n        device = torch.device('cpu')\n    return device",
    "docstring": "Sets device based on local_rank and returns instance of torch.device.\n\n    :param cuda: if True: use cuda\n    :param local_rank: local rank of the worker"
  },
  {
    "code": "def announcement_posted_hook(request, obj):\n    logger.debug(\"Announcement posted\")\n    if obj.notify_post:\n        logger.debug(\"Announcement notify on\")\n        announcement_posted_twitter(request, obj)\n        try:\n            notify_all = obj.notify_email_all\n        except AttributeError:\n            notify_all = False\n        try:\n            if notify_all:\n                announcement_posted_email(request, obj, True)\n            else:\n                announcement_posted_email(request, obj)\n        except Exception as e:\n            logger.error(\"Exception when emailing announcement: {}\".format(e))\n            messages.error(request, \"Exception when emailing announcement: {}\".format(e))\n            raise e\n    else:\n        logger.debug(\"Announcement notify off\")",
    "docstring": "Runs whenever a new announcement is created, or a request is approved and posted.\n\n    obj: The Announcement object"
  },
  {
    "code": "def _detect_available_configs():\n        with channels_lock:\n            available_channels = list(channels.keys())\n        get_extra = lambda: \"channel-{}\".format(randint(0, 9999))\n        extra = get_extra()\n        while extra in available_channels:\n            extra = get_extra()\n        available_channels += [extra]\n        return [\n            {'interface': 'virtual', 'channel': channel}\n            for channel in available_channels\n        ]",
    "docstring": "Returns all currently used channels as well as\n        one other currently unused channel.\n\n        .. note::\n\n            This method will run into problems if thousands of\n            autodetected busses are used at once."
  },
  {
    "code": "def stop(self):\n        if self.pid is None:\n            return None\n        try:\n            while True:\n                self.send(signal.SIGTERM)\n                time.sleep(0.1)\n        except RuntimeError as err:\n            if \"No such process\" in str(err):\n                LOG.info(\"Succesfully stopped the process.\")\n                return None\n            LOG.exception(\"Failed to stop the process:\")\n            sys.exit(exit.STOP_FAILED)\n        except TypeError as err:\n            if \"an integer is required\" in str(err):\n                LOG.info(\"Succesfully stopped the process.\")\n                return None\n            LOG.exception(\"Failed to stop the process:\")\n            sys.exit(exit.STOP_FAILED)",
    "docstring": "Stop the daemonized process.\n\n        If the process is already stopped this call should exit successfully.\n        If the process cannot be stopped this call should exit with code\n        STOP_FAILED."
  },
  {
    "code": "def _parse_property(self, node):\n        name = node.attrib[ATTR_NAME]\n        vtype = node.attrib.get(ATTR_VALUE_TYPE, TYPE_STRING)\n        try:\n            value_node = next(iter(node))\n            value = self._parse_value_node(vtype, value_node)\n        except StopIteration:\n            value = self._convert_value(vtype, node.attrib[ATTR_VALUE])\n        return name, value",
    "docstring": "Parses a property node\n\n        :param node: The property node\n        :return: A (name, value) tuple\n        :raise KeyError: Attribute missing"
  },
  {
    "code": "def getRloc16(self):\n        print '%s call getRloc16' % self.port\n        rloc16 = self.__sendCommand('rloc16')[0]\n        return int(rloc16, 16)",
    "docstring": "get rloc16 short address"
  },
  {
    "code": "def is_subdomain(self, other):\n        (nr, o, nl) = self.fullcompare(other)\n        if nr == NAMERELN_SUBDOMAIN or nr == NAMERELN_EQUAL:\n            return True\n        return False",
    "docstring": "Is self a subdomain of other?\n\n        The notion of subdomain includes equality.\n        @rtype: bool"
  },
  {
    "code": "def add_email_address(self, email, hidden=None):\n        existing_emails = get_value(self.obj, 'email_addresses', [])\n        found_email = next(\n            (existing_email for existing_email in existing_emails if existing_email.get('value') == email),\n            None\n        )\n        if found_email is None:\n            new_email = {'value': email}\n            if hidden is not None:\n                new_email['hidden'] = hidden\n            self._append_to('email_addresses', new_email)\n        elif hidden is not None:\n            found_email['hidden'] = hidden",
    "docstring": "Add email address.\n\n        Args:\n            :param email: email of the author.\n            :type email: string\n\n            :param hidden: if email is public or not.\n            :type hidden: boolean"
  },
  {
    "code": "def media_download(self, mxcurl, allow_remote=True):\n        query_params = {}\n        if not allow_remote:\n            query_params[\"allow_remote\"] = False\n        if mxcurl.startswith('mxc://'):\n            return self._send(\n                \"GET\", mxcurl[6:],\n                api_path=\"/_matrix/media/r0/download/\",\n                query_params=query_params,\n                return_json=False\n            )\n        else:\n            raise ValueError(\n                \"MXC URL '%s' did not begin with 'mxc://'\" % mxcurl\n            )",
    "docstring": "Download raw media from provided mxc URL.\n\n        Args:\n            mxcurl (str): mxc media URL.\n            allow_remote (bool): indicates to the server that it should not\n                attempt to fetch the media if it is deemed remote. Defaults\n                to true if not provided."
  },
  {
    "code": "def _call_to(self, from_node, to_func, ret_node, stmt_idx=None, ins_addr=None, return_to_outside=False):\n        self._register_nodes(True, from_node)\n        if to_func.is_syscall:\n            self.transition_graph.add_edge(from_node, to_func, type='syscall', stmt_idx=stmt_idx, ins_addr=ins_addr)\n        else:\n            self.transition_graph.add_edge(from_node, to_func, type='call', stmt_idx=stmt_idx, ins_addr=ins_addr)\n            if ret_node is not None:\n                self._fakeret_to(from_node, ret_node, to_outside=return_to_outside)\n        self._local_transition_graph = None",
    "docstring": "Registers an edge between the caller basic block and callee function.\n\n        :param from_addr:   The basic block that control flow leaves during the transition.\n        :type  from_addr:   angr.knowledge.CodeNode\n        :param to_func:     The function that we are calling\n        :type  to_func:     Function\n        :param ret_node     The basic block that control flow should return to after the\n                            function call.\n        :type  to_func:     angr.knowledge.CodeNode or None\n        :param stmt_idx:    Statement ID of this call.\n        :type  stmt_idx:    int, str or None\n        :param ins_addr:    Instruction address of this call.\n        :type  ins_addr:    int or None"
  },
  {
    "code": "def content(self, value):\n        self._validator.validate_message_dict(value)\n        self._content = value",
    "docstring": "The actual HTML content.\n\n        :param value: The actual HTML content.\n        :type value: string"
  },
  {
    "code": "def transform(self, crs):\n        new_crs = CRS(crs)\n        geometry = self.geometry\n        if new_crs is not self.crs:\n            project = functools.partial(pyproj.transform, self.crs.projection(), new_crs.projection())\n            geometry = shapely.ops.transform(project, geometry)\n        return Geometry(geometry, crs=new_crs)",
    "docstring": "Transforms Geometry from current CRS to target CRS\n\n        :param crs: target CRS\n        :type crs: constants.CRS\n        :return: Geometry in target CRS\n        :rtype: Geometry"
  },
  {
    "code": "def imbalance_check(P):\n    p_list = list(P.values())\n    max_value = max(p_list)\n    min_value = min(p_list)\n    if min_value > 0:\n        balance_ratio = max_value / min_value\n    else:\n        balance_ratio = max_value\n    is_imbalanced = False\n    if balance_ratio > BALANCE_RATIO_THRESHOLD:\n        is_imbalanced = True\n    return is_imbalanced",
    "docstring": "Check if the dataset is imbalanced.\n\n    :param P: condition positive\n    :type P : dict\n    :return: is_imbalanced as bool"
  },
  {
    "code": "def get_object(self, **kwargs):\n        if hasattr(self, 'object') and self.object:\n            return self.object\n        obj = super(CommonSingleObjectViewMixin, self).get_object(**kwargs)\n        self.object = obj\n        return obj",
    "docstring": "Sometimes preprocessing of a view need to happen before the object\n        attribute has been set for a view.  In this case, just return the\n        object if it has already been set when it's called down the road since\n        there's no need to make another query."
  },
  {
    "code": "def get_built_image_info(self):\n        logger.info(\"getting information about built image '%s'\", self.image)\n        image_info = self.tasker.get_image_info_by_image_name(self.image)\n        items_count = len(image_info)\n        if items_count == 1:\n            return image_info[0]\n        elif items_count <= 0:\n            logger.error(\"image '%s' not found\", self.image)\n            raise RuntimeError(\"image '%s' not found\" % self.image)\n        else:\n            logger.error(\"multiple (%d) images found for image '%s'\", items_count, self.image)\n            raise RuntimeError(\"multiple (%d) images found for image '%s'\" % (items_count,\n                                                                              self.image))",
    "docstring": "query docker about built image\n\n        :return dict"
  },
  {
    "code": "def _compile_qt_resources():\n    if config.QT_RES_SRC():\n        epab.utils.ensure_exe('pyrcc5')\n        LOGGER.info('compiling Qt resources')\n        elib_run.run(f'pyrcc5 {config.QT_RES_SRC()} -o {config.QT_RES_TGT()}')",
    "docstring": "Compiles PyQT resources file"
  },
  {
    "code": "def _findroot(self, x):\n        if x.startswith(\".\"):\n            x = x[1:]\n        if not x.endswith(\".\"):\n            x += \".\"\n        max = 0\n        root = \".\"\n        root_key = \"\"\n        for k in six.iterkeys(self):\n            if x.startswith(k + \".\"):\n                if max < len(k):\n                    max = len(k)\n                    root = self[k]\n                    root_key = k\n        return root, root_key, x[max:-1]",
    "docstring": "Internal MIBDict function used to find a partial OID"
  },
  {
    "code": "def _get_or_create_s3_bucket(s3, name):\n    exists = True\n    try:\n        s3.meta.client.head_bucket(Bucket=name)\n    except botocore.exceptions.ClientError as e:\n        error_code = int(e.response[\"Error\"][\"Code\"])\n        if error_code == 404:\n            exists = False\n        else:\n            raise\n    if not exists:\n        s3.create_bucket(Bucket=name)\n    return s3.Bucket(name)",
    "docstring": "Get an S3 bucket resource after making sure it exists"
  },
  {
    "code": "def _update_from_pb(self, instance_pb):\n        if not instance_pb.display_name:\n            raise ValueError(\"Instance protobuf does not contain display_name\")\n        self.display_name = instance_pb.display_name\n        self.configuration_name = instance_pb.config\n        self.node_count = instance_pb.node_count",
    "docstring": "Refresh self from the server-provided protobuf.\n\n        Helper for :meth:`from_pb` and :meth:`reload`."
  },
  {
    "code": "def reset(self):\n    self.L4.reset()\n    for module in self.L6aModules:\n      module.reset()",
    "docstring": "Clear all cell activity."
  },
  {
    "code": "def _subtract(start, stop, intervals):\n    remainder_start = start\n    sub_stop = None\n    for sub_start, sub_stop in _collapse(intervals):\n        if remainder_start < sub_start:\n            yield _Interval(remainder_start, sub_start)\n        remainder_start = sub_stop\n    if sub_stop is not None and sub_stop < stop:\n        yield _Interval(sub_stop, stop)",
    "docstring": "Subtract intervals from a spanning interval."
  },
  {
    "code": "def add_relation(self, url_arr):\n        if MPost.get_by_uid(url_arr[1]):\n            pass\n        else:\n            return False\n        last_post_id = self.get_secure_cookie('last_post_uid')\n        if last_post_id:\n            last_post_id = last_post_id.decode('utf-8')\n        last_app_id = self.get_secure_cookie('use_app_uid')\n        if last_app_id:\n            last_app_id = last_app_id.decode('utf-8')\n        if url_arr[0] == 'info':\n            if last_post_id:\n                MRelation.add_relation(last_post_id, url_arr[1], 2)\n                MRelation.add_relation(url_arr[1], last_post_id, 1)\n        if url_arr[0] == 'post':\n            if last_app_id:\n                MRelation.add_relation(last_app_id, url_arr[1], 2)\n                MRelation.add_relation(url_arr[1], last_app_id, 1)",
    "docstring": "Add relationship."
  },
  {
    "code": "def cast(\n    source: Union[DataType, str], target: Union[DataType, str], **kwargs\n) -> DataType:\n    source, result_target = dtype(source), dtype(target)\n    if not castable(source, result_target, **kwargs):\n        raise com.IbisTypeError(\n            'Datatype {} cannot be implicitly '\n            'casted to {}'.format(source, result_target)\n        )\n    return result_target",
    "docstring": "Attempts to implicitly cast from source dtype to target dtype"
  },
  {
    "code": "def isEquilateral(self):\n        if not nearly_eq(self.a, self.b):\n            return False\n        if not nearly_eq(self.b, self.c):\n            return False\n        return nearly_eq(self.a, self.c)",
    "docstring": "True if all sides of the triangle are the same length.\n\n        All equilateral triangles are also isosceles.\n        All equilateral triangles are also acute."
  },
  {
    "code": "def UninstallDriver(bundle_name):\n  km = objc.KextManager()\n  cf_bundle_name = km.PyStringToCFString(bundle_name)\n  status = km.iokit.KextManagerUnloadKextWithIdentifier(cf_bundle_name)\n  km.dll.CFRelease(cf_bundle_name)\n  return status",
    "docstring": "Calls into the IOKit to unload a kext by its name.\n\n  Args:\n    bundle_name: The bundle identifier of the kernel extension as defined in\n                 Info.plist field CFBundleIdentifier.\n  Returns:\n    The error code from the library call. objc.OS_SUCCESS if successfull."
  },
  {
    "code": "def previous_minute(self, dt):\n        idx = previous_divider_idx(self._trading_minutes_nanos, dt.value)\n        return self.all_minutes[idx]",
    "docstring": "Given a dt, return the previous exchange minute.\n\n        Raises KeyError if the given timestamp is not an exchange minute.\n\n        Parameters\n        ----------\n        dt: pd.Timestamp\n            The dt for which to get the previous exchange minute.\n\n        Returns\n        -------\n        pd.Timestamp\n            The previous exchange minute."
  },
  {
    "code": "def run(self, handler):\n        import eventlet.patcher\n        if not eventlet.patcher.is_monkey_patched(os):\n            msg = (\"%s requires eventlet.monkey_patch() (before \"\n                   \"import)\" % self.__class__.__name__)\n            raise RuntimeError(msg)\n        wsgi_args = {}\n        for arg in ('log', 'environ', 'max_size', 'max_http_version',\n                    'protocol', 'server_event', 'minimum_chunk_size',\n                    'log_x_forwarded_for', 'custom_pool', 'keepalive',\n                    'log_output', 'log_format', 'url_length_limit', 'debug',\n                    'socket_timeout', 'capitalize_response_headers'):\n            try:\n                wsgi_args[arg] = self.options.pop(arg)\n            except KeyError:\n                pass\n        if 'log_output' not in wsgi_args:\n            wsgi_args['log_output'] = not self.quiet\n        import eventlet.wsgi\n        sock = self.options.pop('shared_socket', None) or self.get_socket()\n        eventlet.wsgi.server(sock, handler, **wsgi_args)",
    "docstring": "Start bottle server."
  },
  {
    "code": "def requirements(ctx):\n    echo_info('Freezing check releases')\n    checks = get_valid_checks()\n    checks.remove('datadog_checks_dev')\n    entries = []\n    for check in checks:\n        if check in AGENT_V5_ONLY:\n            echo_info('Check `{}` is only shipped with Agent 5, skipping'.format(check))\n            continue\n        try:\n            version = get_version_string(check)\n            entries.append('{}\\n'.format(get_agent_requirement_line(check, version)))\n        except Exception as e:\n            echo_failure('Error generating line: {}'.format(e))\n            continue\n    lines = sorted(entries)\n    req_file = get_agent_release_requirements()\n    write_file_lines(req_file, lines)\n    echo_success('Successfully wrote to `{}`!'.format(req_file))",
    "docstring": "Write the `requirements-agent-release.txt` file at the root of the repo\n    listing all the Agent-based integrations pinned at the version they currently\n    have in HEAD."
  },
  {
    "code": "def process_jwt(jwt):\n    header, claims, _ = jwt.split('.')\n    parsed_header = json_decode(base64url_decode(header))\n    parsed_claims = json_decode(base64url_decode(claims))\n    return parsed_header, parsed_claims",
    "docstring": "Process a JSON Web Token without verifying it.\n\n    Call this before :func:`verify_jwt` if you need access to the header or claims in the token before verifying it. For example, the claims might identify the issuer such that you can retrieve the appropriate public key.\n\n    :param jwt: The JSON Web Token to verify.\n    :type jwt: str or unicode\n\n    :rtype: tuple\n    :returns: ``(header, claims)``"
  },
  {
    "code": "def oauth2_token_setter(remote, resp, token_type='', extra_data=None):\n    return token_setter(\n        remote,\n        resp['access_token'],\n        secret='',\n        token_type=token_type,\n        extra_data=extra_data,\n    )",
    "docstring": "Set an OAuth2 token.\n\n    The refresh_token can be used to obtain a new access_token after\n    the old one is expired. It is saved in the database for long term use.\n    A refresh_token will be present only if `access_type=offline` is included\n    in the authorization code request.\n\n    :param remote: The remote application.\n    :param resp: The response.\n    :param token_type: The token type. (Default: ``''``)\n    :param extra_data: Extra information. (Default: ``None``)\n    :returns: A :class:`invenio_oauthclient.models.RemoteToken` instance."
  },
  {
    "code": "def main(symbol: str):\n    print(\"Displaying the balance for\", symbol)\n    with BookAggregate() as svc:\n        security = svc.book.get(Commodity, mnemonic=symbol)\n        sec_svc = SecurityAggregate(svc.book, security)\n        shares_no = sec_svc.get_quantity()\n        print(\"Quantity:\", shares_no)\n        avg_price = sec_svc.get_avg_price()\n        print(\"Average price:\", avg_price)",
    "docstring": "Displays the balance for the security symbol."
  },
  {
    "code": "def _validate_config(self):\n        if not self.backend:\n            return\n        if len(self.REQUIRED_CONFIG_KEYS) < 1:\n            return\n        self.config = self.config or {}\n        required_keys_set = set(self.REQUIRED_CONFIG_KEYS)\n        config_keys_set = set(self.config.keys())\n        missing_required_keys = required_keys_set - config_keys_set\n        unrecognized_keys = config_keys_set - required_keys_set\n        if len(missing_required_keys) > 0:\n            missing_keys_string = ', '.join(missing_required_keys)\n            raise ValidationError(_('Missing required config keys: \"%s\"') % missing_keys_string)\n        elif len(unrecognized_keys) > 0:\n            unrecognized_keys_string = ', '.join(unrecognized_keys)\n            raise ValidationError(_('Unrecognized config keys: \"%s\"') % unrecognized_keys_string)",
    "docstring": "ensure REQUIRED_CONFIG_KEYS are filled"
  },
  {
    "code": "async def text(self) -> str:\n        bytes_body = await self.read()\n        encoding = self.charset or 'utf-8'\n        return bytes_body.decode(encoding)",
    "docstring": "Return BODY as text using encoding from .charset."
  },
  {
    "code": "def split_words(line):\n  line = _NORM_REGEX.sub(r'\\1 \\2', line)\n  return [normalize(w) for w in _WORD_REGEX.split(line)]",
    "docstring": "Return the list of words contained in a line."
  },
  {
    "code": "def on_unselect(self, item, action):\n        if not isinstance(item, int):\n            item = self.items.index(item)\n        self._on_unselect[item] = action",
    "docstring": "Add an action to make when an object is unfocused."
  },
  {
    "code": "def spread(self, m: Union[int, pd.Series]) -> Union[int, pd.Series]:\n        return (m * 111_111) % self.TEN_DIGIT_MODULUS",
    "docstring": "Spreads out integer values to give smaller values more weight."
  },
  {
    "code": "def get(self, bus_name, object_path=None, **kwargs):\n\t\tfor kwarg in kwargs:\n\t\t\tif kwarg not in (\"timeout\",):\n\t\t\t\traise TypeError(self.__qualname__ + \" got an unexpected keyword argument '{}'\".format(kwarg))\n\t\ttimeout = kwargs.get(\"timeout\", None)\n\t\tbus_name = auto_bus_name(bus_name)\n\t\tobject_path = auto_object_path(bus_name, object_path)\n\t\tret = self.con.call_sync(\n\t\t\tbus_name, object_path,\n\t\t\t'org.freedesktop.DBus.Introspectable', \"Introspect\", None, GLib.VariantType.new(\"(s)\"),\n\t\t\t0, timeout_to_glib(timeout), None)\n\t\tif not ret:\n\t\t\traise KeyError(\"no such object; you might need to pass object path as the 2nd argument for get()\")\n\t\txml, = ret.unpack()\n\t\ttry:\n\t\t\tintrospection = ET.fromstring(xml)\n\t\texcept:\n\t\t\traise KeyError(\"object provides invalid introspection XML\")\n\t\treturn CompositeInterface(introspection)(self, bus_name, object_path)",
    "docstring": "Get a remote object.\n\n\t\tParameters\n\t\t----------\n\t\tbus_name : string\n\t\t\tName of the service that exposes this object.\n\t\t\tYou may start with \".\" - then org.freedesktop will be automatically prepended.\n\t\tobject_path : string, optional\n\t\t\tPath of the object. If not provided, bus_name translated to path format is used.\n\n\t\tReturns\n\t\t-------\n\t\tProxyObject implementing all the Interfaces exposed by the remote object.\n\t\tNote that it inherits from multiple Interfaces, so the method you want to use\n\t\tmay be shadowed by another one, eg. from a newer version of the interface.\n\t\tTherefore, to interact with only a single interface, use:\n\t\t>>> bus.get(\"org.freedesktop.systemd1\")[\"org.freedesktop.systemd1.Manager\"]\n\t\tor simply\n\t\t>>> bus.get(\".systemd1\")[\".Manager\"]\n\t\twhich will give you access to the one specific interface."
  },
  {
    "code": "def delete_commit(self, commit):\n        req = proto.DeleteCommitRequest(commit=commit_from(commit))\n        self.stub.DeleteCommit(req, metadata=self.metadata)",
    "docstring": "Deletes a commit.\n\n        Params:\n        * commit: A tuple, string, or Commit object representing the commit."
  },
  {
    "code": "def GetBEDnarrowPeakgz(URL_or_PATH_TO_file):\n    if os.path.isfile(URL_or_PATH_TO_file):\n        response=open(URL_or_PATH_TO_file, \"r\")\n        compressedFile = StringIO.StringIO(response.read())\n    else:\n        response = urllib2.urlopen(URL_or_PATH_TO_file)\n        compressedFile = StringIO.StringIO(response.read())\n    decompressedFile = gzip.GzipFile(fileobj=compressedFile)\n    out=decompressedFile.read().split(\"\\n\")\n    out=[ s.split(\"\\t\") for s in out]\n    out=pd.DataFrame(out)\n    out.columns=[\"chrom\",\"chromStart\",\"chromEnd\",\"name\",\"score\",\"strand\",\"signalValue\",\"-log10(pValue)\",\"-log10(qvalue)\",\"peak\"]\n    out[\"name\"]=out.index.tolist()\n    out[\"name\"]=\"Peak_\"+out[\"name\"].astype(str)\n    out=out[:-1]\n    return out",
    "docstring": "Reads a gz compressed BED narrow peak file from a web address or local file\n\n    :param URL_or_PATH_TO_file: web address of path to local file\n\n    :returns: a Pandas dataframe"
  },
  {
    "code": "def watermark(app, env):\n    if app.config.sphinxmark_enable is True:\n        LOG.info('adding watermark...', nonl=True)\n        buildpath, imagefile = getimage(app)\n        cssname = buildcss(app, buildpath, imagefile)\n        app.add_css_file(cssname)\n        LOG.info(' done')",
    "docstring": "Add watermark."
  },
  {
    "code": "def count_consonants(text):\n    count = 0\n    for i in text:\n        if i.lower() in config.AVRO_CONSONANTS:\n            count += 1\n    return count",
    "docstring": "Count number of occurrences of consonants in a given string"
  },
  {
    "code": "def list(self):\n        self._initialize_list()\n        interested = True\n        response = self._cloudFormation.list_stacks()\n        print('Stack(s):')\n        while interested:\n            if 'StackSummaries' in response:\n                for stack in response['StackSummaries']:\n                    stack_status = stack['StackStatus']\n                    if stack_status != 'DELETE_COMPLETE':\n                        print('    [{}] - {}'.format(stack['StackStatus'], stack['StackName']))\n            next_token = response.get('NextToken', None)\n            if next_token:\n                response = self._cloudFormation.list_stacks(NextToken=next_token)\n            else:\n                interested = False\n        return True",
    "docstring": "List the existing stacks in the indicated region\n\n        Args:\n            None\n\n        Returns:\n            True if True\n\n        Todo:\n            Figure out what could go wrong and take steps\n            to hanlde problems."
  },
  {
    "code": "def _deriv_arctan2(y, x):\n    r2 = x*x + y*y\n    df_dy = x / r2\n    df_dx = -y / r2\n    return np.hstack([df_dy, df_dx])",
    "docstring": "Derivative of the arctan2 function"
  },
  {
    "code": "def _match_to_morph_parents(self, type, results):\n        for result in results:\n            if result.get_key() in self._dictionary.get(type, []):\n                for model in self._dictionary[type][result.get_key()]:\n                    model.set_relation(\n                        self._relation, Result(result, self, model, related=result)\n                    )",
    "docstring": "Match the results for a given type to their parent.\n\n        :param type: The parent type\n        :type type: str\n\n        :param results: The results to match to their parent\n        :type results: Collection"
  },
  {
    "code": "def stop(self):\n        yield from self._stop_ubridge()\n        if self.is_running():\n            self._terminate_process()\n            if self._process.returncode is None:\n                try:\n                    yield from wait_for_process_termination(self._process, timeout=3)\n                except asyncio.TimeoutError:\n                    if self._process.returncode is None:\n                        try:\n                            self._process.kill()\n                        except OSError as e:\n                            log.error(\"Cannot stop the VPCS process: {}\".format(e))\n                        if self._process.returncode is None:\n                            log.warn('VPCS VM \"{}\" with PID={} is still running'.format(self._name, self._process.pid))\n        self._process = None\n        self._started = False\n        yield from super().stop()",
    "docstring": "Stops the VPCS process."
  },
  {
    "code": "def _replace_variables(data, variables):\n    formatter = string.Formatter()\n    return [formatter.vformat(item, [], variables) for item in data]",
    "docstring": "Replace the format variables in all items of data."
  },
  {
    "code": "def get_check_result_brok(self):\n        data = {'uuid': self.uuid}\n        self.fill_data_brok_from(data, 'check_result')\n        return Brok({'type': self.my_type + '_check_result', 'data': data})",
    "docstring": "Create check_result brok\n\n        :return: Brok object\n        :rtype: alignak.Brok"
  },
  {
    "code": "def download_image(image_id, url, x1, y1, x2, y2, output_dir):\n  output_filename = os.path.join(output_dir, image_id + '.png')\n  if os.path.exists(output_filename):\n    return True\n  try:\n    url_file = urlopen(url)\n    if url_file.getcode() != 200:\n      return False\n    image_buffer = url_file.read()\n    image = Image.open(BytesIO(image_buffer)).convert('RGB')\n    w = image.size[0]\n    h = image.size[1]\n    image = image.crop((int(x1 * w), int(y1 * h), int(x2 * w),\n                        int(y2 * h)))\n    image = image.resize((299, 299), resample=Image.ANTIALIAS)\n    image.save(output_filename)\n  except IOError:\n    return False\n  return True",
    "docstring": "Downloads one image, crops it, resizes it and saves it locally."
  },
  {
    "code": "def add(modname, features, required_version, installed_version=None,\r\n        optional=False):\r\n    global DEPENDENCIES\r\n    for dependency in DEPENDENCIES:\r\n        if dependency.modname == modname:\r\n            raise ValueError(\"Dependency has already been registered: %s\"\\\r\n                             % modname)\r\n    DEPENDENCIES += [Dependency(modname, features, required_version,\r\n                                installed_version, optional)]",
    "docstring": "Add Spyder dependency"
  },
  {
    "code": "def confirm_or_abort(prompt, exitcode=os.EX_TEMPFAIL, msg=None, **extra_args):\n    if click.confirm(prompt, **extra_args):\n        return True\n    else:\n        if msg:\n            sys.stderr.write(msg)\n            sys.stderr.write('\\n')\n        sys.exit(exitcode)",
    "docstring": "Prompt user for confirmation and exit on negative reply.\n\n    Arguments `prompt` and `extra_args` will be passed unchanged to\n    `click.confirm`:func: (which is used for actual prompting).\n\n    :param str prompt: Prompt string to display.\n    :param int exitcode: Program exit code if negative reply given.\n    :param str msg: Message to display before exiting."
  },
  {
    "code": "def get_questions(self, answered=None, honor_sequential=True, update=True):\n        def update_question_list():\n            latest_question_response = question_map['responses'][0]\n            question_answered = False\n            if 'missingResponse' not in latest_question_response:\n                question_answered = True\n            if answered is None or answered == question_answered:\n                question_list.append(self.get_question(question_map=question_map))\n            return question_answered\n        prev_question_answered = True\n        question_list = []\n        if update:\n            self._update_questions()\n        for question_map in self._my_map['questions']:\n            if self._is_question_sequential(question_map) and honor_sequential:\n                if prev_question_answered:\n                    prev_question_answered = update_question_list()\n            else:\n                update_question_list()\n        if self._my_map['actualStartTime'] is None:\n            self._my_map['actualStartTime'] = DateTime.utcnow()\n        return QuestionList(question_list, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "gets all available questions for this section\n\n        if answered == False: only return next unanswered question\n        if answered == True: only return next answered question\n        if answered in None: return next question whether answered or not\n        if honor_sequential == True: only return questions if section or part\n                                     is set to sequential items"
  },
  {
    "code": "def ident():\n    matrix = stypes.emptyDoubleMatrix()\n    libspice.ident_c(matrix)\n    return stypes.cMatrixToNumpy(matrix)",
    "docstring": "This routine returns the 3x3 identity matrix.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ident_c.html\n\n    :return: The 3x3 identity matrix.\n    :rtype: 3x3-Element Array of floats"
  },
  {
    "code": "def get_dict_repr(self):\n        return dict(\n            phase_name = self.phase_name,\n            phase_type = self.phase_type,\n            actions = self.actions\n            )",
    "docstring": "Return a dictionary representation of this phase.\n        This will be used for checksumming, in order to uniquely compare\n        instance images against their requirements"
  },
  {
    "code": "def _get_dataset(self, dataset, name, color):\n        global palette\n        html = \"{\"\n        html += '\\t\"label\": \"' + name + '\",'\n        if color is not None:\n            html += '\"backgroundColor\": \"' + color + '\",\\n'\n        else:\n            html += '\"backgroundColor\": ' + palette + ',\\n'\n        html += '\"data\": ' + self._format_list(dataset) + ',\\n'\n        html += \"}\"\n        return html",
    "docstring": "Encode a dataset"
  },
  {
    "code": "def remove_default_content(portal):\n    logger.info(\"*** Delete Default Content ***\")\n    object_ids = portal.objectIds()\n    delete_ids = filter(lambda id: id in object_ids, CONTENTS_TO_DELETE)\n    portal.manage_delObjects(ids=delete_ids)",
    "docstring": "Remove default Plone contents"
  },
  {
    "code": "def unlink_reference(self, source, target):\n        target_uid = api.get_uid(target)\n        key = self.get_relationship_key(target)\n        backrefs = get_backreferences(source, relationship=None)\n        if key not in backrefs:\n            logger.warn(\n                \"Referenced object {} has no backreferences for the key {}\"\n                .format(repr(source), key))\n            return False\n        if target_uid not in backrefs[key]:\n            logger.warn(\"Target {} was not linked by {}\"\n                        .format(repr(target), repr(source)))\n            return False\n        backrefs[key].remove(target_uid)\n        return True",
    "docstring": "Unlink the target from the source"
  },
  {
    "code": "def prepare_parser(program):\n    parser = ArgumentParser(\n        description=PROG_DESCRIPTION, prog=program,\n        formatter_class=HelpFormatter,\n        add_help=False)\n    parser.add_argument(\n        \"-h\", \"--help\", action=MinimalHelpAction, help=argparse.SUPPRESS)\n    submodules = (\n        \"nodes\", \"machines\", \"devices\", \"controllers\",\n        \"fabrics\", \"vlans\", \"subnets\", \"spaces\",\n        \"files\", \"tags\", \"users\",\n        \"profiles\", \"shell\",\n    )\n    cmd_help.register(parser)\n    for submodule in submodules:\n        module = import_module(\".\" + submodule, __name__)\n        module.register(parser)\n    parser.add_argument(\n        '--debug', action='store_true', default=False,\n        help=argparse.SUPPRESS)\n    return parser",
    "docstring": "Create and populate an argument parser."
  },
  {
    "code": "def make_operatorsetid(\n        domain,\n        version,\n):\n    operatorsetid = OperatorSetIdProto()\n    operatorsetid.domain = domain\n    operatorsetid.version = version\n    return operatorsetid",
    "docstring": "Construct an OperatorSetIdProto.\n\n    Arguments:\n        domain (string): The domain of the operator set id\n        version (integer): Version of operator set id"
  },
  {
    "code": "def add(self, string: (str, list)):\n        if len(self._entries) == 1:\n            self._entries[0].delete(0, 'end')\n            self._entries[0].insert(0, string)\n        else:\n            if len(string) != len(self._entries):\n                raise ValueError('the \"string\" list must be '\n                                 'equal to the number of entries')\n            for i, e in enumerate(self._entries):\n                self._entries[i].delete(0, 'end')\n                self._entries[i].insert(0, string[i])",
    "docstring": "Clear the contents of the entry field and\n        insert the contents of string.\n\n        :param string: an str containing the text to display\n        :return:"
  },
  {
    "code": "def try_run_inschek(pst):\n    for ins_file,out_file in zip(pst.instruction_files,pst.output_files):\n        df = _try_run_inschek(ins_file,out_file)\n        if df is not None:\n            pst.observation_data.loc[df.index, \"obsval\"] = df.obsval",
    "docstring": "attempt to run INSCHEK for each instruction file, model output\n    file pair in a pyemu.Pst.  If the run is successful, the INSCHEK written\n    .obf file is used to populate the pst.observation_data.obsval attribute\n\n    Parameters\n    ----------\n    pst : (pyemu.Pst)"
  },
  {
    "code": "def process_keystroke(self, inp, idx, offset):\n        if inp.lower() in (u'q', u'Q'):\n            return (-1, -1)\n        self._process_keystroke_commands(inp)\n        idx, offset = self._process_keystroke_movement(inp, idx, offset)\n        return idx, offset",
    "docstring": "Process keystroke ``inp``, adjusting screen parameters.\n\n        :param inp: return value of Terminal.inkey().\n        :type inp: blessed.keyboard.Keystroke\n        :param idx: page index.\n        :type idx: int\n        :param offset: scrolling region offset of current page.\n        :type offset: int\n        :returns: tuple of next (idx, offset).\n        :rtype: (int, int)"
  },
  {
    "code": "def balance(self, account_id=None):\n        if not account_id:\n            if len(self.accounts()) == 1:\n                account_id = self.accounts()[0].id\n            else:\n                raise ValueError(\"You need to pass account ID\")\n        endpoint = '/balance'\n        response = self._get_response(\n            method='get', endpoint=endpoint,\n            params={\n                'account_id': account_id,\n            },\n        )\n        return MonzoBalance(data=response.json())",
    "docstring": "Returns balance information for a specific account.\n\n        Official docs:\n            https://monzo.com/docs/#read-balance\n\n        :param account_id: Monzo account ID\n        :type account_id: str\n        :raises: ValueError\n        :returns: Monzo balance instance\n        :rtype: MonzoBalance"
  },
  {
    "code": "def hexdigest(self, data=None):\n        from base64 import b16encode\n        if pyver == 2:\n            return b16encode(self.digest(data))\n        else:\n            return b16encode(self.digest(data)).decode('us-ascii')",
    "docstring": "Returns digest in the hexadecimal form. For compatibility\n            with hashlib"
  },
  {
    "code": "def start(self):\n        if self.stream is None:\n            from pyaudio import PyAudio, paInt16\n            self.pa = PyAudio()\n            self.stream = self.pa.open(\n                16000, 1, paInt16, True, frames_per_buffer=self.chunk_size\n            )\n        self._wrap_stream_read(self.stream)\n        self.engine.start()\n        self.running = True\n        self.is_paused = False\n        self.thread = Thread(target=self._handle_predictions)\n        self.thread.daemon = True\n        self.thread.start()",
    "docstring": "Start listening from stream"
  },
  {
    "code": "def add_location_reminder(self, service, name, lat, long, trigger, radius):\n        args = {\n            'item_id': self.id,\n            'service': service,\n            'type': 'location',\n            'name': name,\n            'loc_lat': str(lat),\n            'loc_long': str(long),\n            'loc_trigger': trigger,\n            'radius': radius\n        }\n        _perform_command(self.project.owner, 'reminder_add', args)",
    "docstring": "Add a reminder to the task which activates on at a given location.\n\n        .. warning:: Requires Todoist premium.\n\n        :param service: ```email```, ```sms``` or ```push``` for mobile.\n        :type service: str\n        :param name: An alias for the location.\n        :type name: str\n        :param lat: The location latitude.\n        :type lat: float\n        :param long: The location longitude.\n        :type long: float\n        :param trigger: ```on_enter``` or ```on_leave```.\n        :type trigger: str\n        :param radius: The radius around the location that is still considered\n            the location.\n        :type radius: float\n\n        >>> from pytodoist import todoist\n        >>> user = todoist.login('john.doe@gmail.com', 'password')\n        >>> project = user.get_project('PyTodoist')\n        >>> task = project.add_task('Install PyTodoist')\n        >>> task.add_location_reminder('email', 'Leave Glasgow',\n        ...                            55.8580, 4.2590, 'on_leave', 100)"
  },
  {
    "code": "def _convert_method_settings_into_operations(method_settings=None):\n    operations = []\n    if method_settings:\n        for method in method_settings.keys():\n            for key, value in method_settings[method].items():\n                if isinstance(value, bool):\n                    if value:\n                        value = 'true'\n                    else:\n                        value = 'false'\n                operations.append({\n                    'op': 'replace',\n                    'path': method + _resolve_key(key),\n                    'value': value\n                })\n    return operations",
    "docstring": "Helper to handle the conversion of method_settings to operations\n\n    :param method_settings:\n    :return: list of operations"
  },
  {
    "code": "def tzname_in_python2(myfunc):\n    def inner_func(*args, **kwargs):\n        if PY3:\n            return myfunc(*args, **kwargs)\n        else:\n            return myfunc(*args, **kwargs).encode()\n    return inner_func",
    "docstring": "Change unicode output into bytestrings in Python 2\n\n    tzname() API changed in Python 3. It used to return bytes, but was changed\n    to unicode strings"
  },
  {
    "code": "def avatar(self, size: int = 256) -> str:\n        url = 'https://api.adorable.io/avatars/{0}/{1}.png'\n        return url.format(size, self.password(hashed=True))",
    "docstring": "Generate a random avatar..\n\n        :param size: Size of avatar.\n        :return: Link to avatar."
  },
  {
    "code": "def _generate_processing_blocks(start_id, min_blocks=0, max_blocks=4):\n    processing_blocks = []\n    num_blocks = random.randint(min_blocks, max_blocks)\n    for i in range(start_id, start_id + num_blocks):\n        _id = 'sip-pb{:03d}'.format(i)\n        block = dict(id=_id, resources_requirement={}, workflow={})\n        processing_blocks.append(block)\n    return processing_blocks",
    "docstring": "Generate a number of Processing Blocks"
  },
  {
    "code": "def _set_led_value(self, group, val):\n        new_bitmask = set_bit(self._value, group, bool(val))\n        self._set_led_bitmask(new_bitmask)",
    "docstring": "Set the LED value and confirm with a status check."
  },
  {
    "code": "def _get_videos_for_filter(video_filter, sort_field=None, sort_dir=SortDirection.asc, pagination_conf=None):\n    videos = Video.objects.filter(**video_filter)\n    paginator_context = {}\n    if sort_field:\n        videos = videos.order_by(sort_field.value, \"edx_video_id\")\n        if sort_dir == SortDirection.desc:\n            videos = videos.reverse()\n    if pagination_conf:\n        videos_per_page = pagination_conf.get('videos_per_page')\n        paginator = Paginator(videos, videos_per_page)\n        videos = paginator.page(pagination_conf.get('page_number'))\n        paginator_context = {\n            'current_page':   videos.number,\n            'total_pages': videos.paginator.num_pages,\n            'items_on_one_page':videos_per_page\n        }\n    return (VideoSerializer(video).data for video in videos), paginator_context",
    "docstring": "Returns a generator expression that contains the videos found, sorted by\n    the given field and direction, with ties broken by edx_video_id to ensure a\n    total order."
  },
  {
    "code": "def paintEvent(self, event):\n        if not self.toPlainText() and not self.hasFocus() and self._placeholder:\n            p = QtGui.QPainter(self.viewport())\n            p.setClipping(False)\n            col = self.palette().text().color()\n            col.setAlpha(128)\n            oldpen = p.pen()\n            p.setPen(col)\n            p.drawText(self.viewport().geometry(), QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop, self._placeholder)\n            p.setPen(oldpen)\n        else:\n            return super(JB_PlainTextEdit, self).paintEvent(event)",
    "docstring": "Paint the widget\n\n        :param event:\n        :type event:\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def add_note(self, note, octave=None, dynamics={}):\n        if type(note) == str:\n            if octave is not None:\n                note = Note(note, octave, dynamics)\n            elif len(self.notes) == 0:\n                note = Note(note, 4, dynamics)\n            else:\n                if Note(note, self.notes[-1].octave) < self.notes[-1]:\n                    note = Note(note, self.notes[-1].octave + 1, dynamics)\n                else:\n                    note = Note(note, self.notes[-1].octave, dynamics)\n        if not hasattr(note, 'name'):\n            raise UnexpectedObjectError(\"Object '%s' was not expected. \"\n                    \"Expecting a mingus.containers.Note object.\" % note)\n        if note not in self.notes:\n            self.notes.append(note)\n            self.notes.sort()\n        return self.notes",
    "docstring": "Add a note to the container and sorts the notes from low to high.\n\n        The note can either be a string, in which case you could also use\n        the octave and dynamics arguments, or a Note object."
  },
  {
    "code": "def exec_request(endpoint, func, raise_for_status=False, **kwargs):\n        try:\n            endpoint = '{0}/api/v1/{1}'.format(settings.SEAT_URL, endpoint)\n            headers = {'X-Token': settings.SEAT_XTOKEN, 'Accept': 'application/json'}\n            logger.debug(headers)\n            logger.debug(endpoint)\n            ret = getattr(requests, func)(endpoint, headers=headers, data=kwargs)\n            ret.raise_for_status()\n            return ret.json()\n        except requests.HTTPError as e:\n            if raise_for_status:\n                raise e\n            logger.exception(\"Error encountered while performing API request to SeAT with url {}\".format(endpoint))\n            return {}",
    "docstring": "Send an https api request"
  },
  {
    "code": "def extract(body, sender):\n    try:\n        delimiter = get_delimiter(body)\n        body = body.strip()\n        if has_signature(body, sender):\n            lines = body.splitlines()\n            markers = _mark_lines(lines, sender)\n            text, signature = _process_marked_lines(lines, markers)\n            if signature:\n                text = delimiter.join(text)\n                if text.strip():\n                    return (text, delimiter.join(signature))\n    except Exception as e:\n        log.exception('ERROR when extracting signature with classifiers')\n    return (body, None)",
    "docstring": "Strips signature from the body of the message.\n\n    Returns stripped body and signature as a tuple.\n    If no signature is found the corresponding returned value is None."
  },
  {
    "code": "def pool_create(hypervisor, identifier, pool_path):\n    path = os.path.join(pool_path, identifier)\n    if not os.path.exists(path):\n        os.makedirs(path)\n    xml = POOL_DEFAULT_CONFIG.format(identifier, path)\n    return hypervisor.storagePoolCreateXML(xml, 0)",
    "docstring": "Storage pool creation.\n\n    The following values are set in the XML configuration:\n      * name\n      * target/path\n      * target/permission/label"
  },
  {
    "code": "def _GenerateStopTimesTuples(self):\n    stoptimes = self.GetStopTimes()\n    for i, st in enumerate(stoptimes):\n      yield st.GetFieldValuesTuple(self.trip_id)",
    "docstring": "Generator for rows of the stop_times file"
  },
  {
    "code": "def null_slice(slice_):\n    try:\n        slice_ = as_slice(slice_)\n    except TypeError:\n        return False\n    if isinstance(slice_, numpy.ndarray) and numpy.all(slice_):\n        return True\n    if isinstance(slice_, slice) and slice_ in (\n            slice(None, None, None), slice(0, None, 1)\n    ):\n        return True",
    "docstring": "Returns True if a slice will have no affect"
  },
  {
    "code": "def is_valid_ipv6 (ip):\n    if not (_ipv6_re.match(ip) or _ipv6_ipv4_re.match(ip) or\n            _ipv6_abbr_re.match(ip) or _ipv6_ipv4_abbr_re.match(ip)):\n        return False\n    return True",
    "docstring": "Return True if given ip is a valid IPv6 address."
  },
  {
    "code": "def split(self, granularity_after_split, exclude_partial=True):\n        if granularity_after_split == Granularity.DAY:\n            return self.get_days()\n        elif granularity_after_split == Granularity.WEEK:\n            return self.get_weeks(exclude_partial)\n        elif granularity_after_split == Granularity.MONTH:\n            return self.get_months(exclude_partial)\n        elif granularity_after_split == Granularity.QUARTER:\n            return self.get_quarters(exclude_partial)\n        elif granularity_after_split == Granularity.HALF_YEAR:\n            return self.get_half_years(exclude_partial)\n        elif granularity_after_split == Granularity.YEAR:\n            return self.get_years(exclude_partial)\n        else:\n            raise Exception(\"Invalid granularity: %s\" % granularity_after_split)",
    "docstring": "Split a period into a given granularity. Optionally include partial\n        periods at the start and end of the period."
  },
  {
    "code": "def _update_params_on_kvstore_nccl(param_arrays, grad_arrays, kvstore, param_names):\n    valid_indices = [index for index, grad_list in\n                     enumerate(grad_arrays) if grad_list[0] is not None]\n    valid_grad_arrays = [grad_arrays[i] for i in valid_indices]\n    valid_param_arrays = [param_arrays[i] for i in valid_indices]\n    valid_param_names = [param_names[i] for i in valid_indices]\n    size = len(valid_grad_arrays)\n    start = 0\n    default_batch = '16'\n    batch = int(os.getenv('MXNET_UPDATE_AGGREGATION_SIZE', default_batch))\n    while start < size:\n        end = start + batch if start + batch < size else size\n        kvstore.push(valid_param_names[start:end], valid_grad_arrays[start:end], priority=-start)\n        kvstore.pull(valid_param_names[start:end], valid_param_arrays[start:end], priority=-start)\n        start = end",
    "docstring": "Perform update of param_arrays from grad_arrays on NCCL kvstore."
  },
  {
    "code": "def infer_ml_task(y):\n    if y.dtype.kind in np.typecodes['AllInteger'] or y.dtype == np.object:\n        ml_task = 'classification'\n    else:\n        ml_task = 'regression'\n    _logger.warning('Infered {} as machine learning task'.format(ml_task))\n    return ml_task",
    "docstring": "Infer the machine learning task to select for.\n    The result will be either `'regression'` or `'classification'`.\n    If the target vector only consists of integer typed values or objects, we assume the task is `'classification'`.\n    Else `'regression'`.\n\n    :param y: The target vector y.\n    :type y: pandas.Series\n    :return: 'classification' or 'regression'\n    :rtype: str"
  },
  {
    "code": "def get_version_text(self):\n        show_version_brief_not_supported = False\n        version_text = None\n        try:\n            version_text = self.device.send(\"show version brief\", timeout=120)\n        except CommandError:\n            show_version_brief_not_supported = True\n        if show_version_brief_not_supported:\n            try:\n                version_text = self.device.send(\"show version\", timeout=120)\n            except CommandError as exc:\n                exc.command = 'show version'\n                raise exc\n        return version_text",
    "docstring": "Return the version information from the device."
  },
  {
    "code": "def get_gpubsub_publisher(config, metrics, changes_channel, **kw):\n    builder = gpubsub_publisher.GPubsubPublisherBuilder(\n        config, metrics, changes_channel, **kw)\n    return builder.build_publisher()",
    "docstring": "Get a GPubsubPublisher client.\n\n    A factory function that validates configuration, creates an auth\n    and pubsub API client, and returns a Google Pub/Sub Publisher\n    provider.\n\n    Args:\n        config (dict): Google Cloud Pub/Sub-related configuration.\n        metrics (obj): :interface:`IMetricRelay` implementation.\n        changes_channel (asyncio.Queue): Queue to publish message to\n            make corrections to Cloud DNS.\n        kw (dict): Additional keyword arguments to pass to the\n            Publisher.\n    Returns:\n        A :class:`GPubsubPublisher` instance."
  },
  {
    "code": "def get_hub():\n    try:\n        hub = _local.hub\n    except AttributeError:\n        assert fibers.current().parent is None\n        hub = _local.hub = Hub()\n    return hub",
    "docstring": "Return the instance of the hub."
  },
  {
    "code": "def computational_form(data):\n    if isinstance(data.iloc[0], DataFrame):\n        dslice = Panel.from_dict(dict([(i,data.iloc[i])\n                                       for i in xrange(len(data))]))\n    elif isinstance(data.iloc[0], Series):\n        dslice = DataFrame(data.tolist())\n        dslice.index = data.index\n    else:\n        dslice = data\n    return dslice",
    "docstring": "Input Series of numbers, Series, or DataFrames repackaged\n    for calculation.\n\n    Parameters\n    ----------\n    data : pandas.Series\n        Series of numbers, Series, DataFrames\n\n    Returns\n    -------\n    pandas.Series, DataFrame, or Panel\n        repacked data, aligned by indices, ready for calculation"
  },
  {
    "code": "def gen_outputs(self, riskinput, monitor, epspath=None, hazard=None):\n        self.monitor = monitor\n        hazard_getter = riskinput.hazard_getter\n        if hazard is None:\n            with monitor('getting hazard'):\n                hazard_getter.init()\n                hazard = hazard_getter.get_hazard()\n        sids = hazard_getter.sids\n        assert len(sids) == 1\n        with monitor('computing risk', measuremem=False):\n            assets_by_taxo = get_assets_by_taxo(riskinput.assets, epspath)\n            for rlzi, haz in sorted(hazard[sids[0]].items()):\n                out = self.get_output(assets_by_taxo, haz, rlzi)\n                yield out",
    "docstring": "Group the assets per taxonomy and compute the outputs by using the\n        underlying riskmodels. Yield one output per realization.\n\n        :param riskinput: a RiskInput instance\n        :param monitor: a monitor object used to measure the performance"
  },
  {
    "code": "def serialize_date(attr, **kwargs):\n        if isinstance(attr, str):\n            attr = isodate.parse_date(attr)\n        t = \"{:04}-{:02}-{:02}\".format(attr.year, attr.month, attr.day)\n        return t",
    "docstring": "Serialize Date object into ISO-8601 formatted string.\n\n        :param Date attr: Object to be serialized.\n        :rtype: str"
  },
  {
    "code": "def auto_consume(func):\n    def inner(*args, **kwargs):\n        func(*args, **kwargs)\n        args[0].consume_line()\n    return inner",
    "docstring": "Decorator for auto consuming lines when leaving the function"
  },
  {
    "code": "def this(obj, **kwargs):\n    verbose = kwargs.get(\"verbose\", True)\n    if verbose:\n        print('{:=^30}'.format(\" whatis.this? \"))\n    for func in pipeline:\n        s = func(obj, **kwargs)\n        if s is not None:\n            print(s)\n    if verbose:\n        print('{:=^30}\\n'.format(\" whatis.this? \"))",
    "docstring": "Prints series of debugging steps to user.\n\n    Runs through pipeline of functions and print results of each."
  },
  {
    "code": "def add_section(self, alias, section):\n        if not isinstance(alias, six.string_types):\n            raise TypeError('Section name must be a string, got a {!r}'.format(type(alias)))\n        self._tree[alias] = section\n        if self.settings.str_path_separator in alias:\n            raise ValueError(\n                'Section alias must not contain str_path_separator which is configured for this Config -- {!r} -- '\n                'but {!r} does.'.format(self.settings.str_path_separator, alias)\n            )\n        section._section = self\n        section._section_alias = alias\n        self.dispatch_event(self.hooks.section_added_to_section, alias=alias, section=self, subject=section)",
    "docstring": "Add a sub-section to this section."
  },
  {
    "code": "def update(self):\n        con = self.subpars.pars.control\n        self(con.relwb*con.nfk)",
    "docstring": "Update |WB| based on |RelWB| and |NFk|.\n\n        >>> from hydpy.models.lland import *\n        >>> parameterstep('1d')\n        >>> nhru(2)\n        >>> lnk(ACKER)\n        >>> relwb(0.2)\n        >>> nfk(100.0, 200.0)\n        >>> derived.wb.update()\n        >>> derived.wb\n        wb(20.0, 40.0)"
  },
  {
    "code": "def setup_pathing(self):\n        self.s3_version_uri = self._path_formatter(self.version)\n        self.s3_latest_uri = self._path_formatter(\"LATEST\")\n        self.s3_canary_uri = self._path_formatter(\"CANARY\")\n        self.s3_alpha_uri = self._path_formatter(\"ALPHA\")\n        self.s3_mirror_uri = self._path_formatter(\"MIRROR\")",
    "docstring": "Format pathing for S3 deployments."
  },
  {
    "code": "def usn_v4_record(header, record):\n    length, major_version, minor_version = header\n    fields = V4_RECORD.unpack_from(record, RECORD_HEADER.size)\n    raise NotImplementedError('Not implemented')",
    "docstring": "Extracts USN V4 record information."
  },
  {
    "code": "def urlencode(txt):\n    if isinstance(txt, unicode):\n        txt = txt.encode('utf-8')\n    return urllib.quote_plus(txt)",
    "docstring": "Url encode a path."
  },
  {
    "code": "def saveComicStrip(self, strip):\n        allskipped = True\n        for image in strip.getImages():\n            try:\n                if self.options.dry_run:\n                    filename, saved = \"\", False\n                else:\n                    filename, saved = image.save(self.options.basepath)\n                if saved:\n                    allskipped = False\n                if self.stopped:\n                    break\n            except Exception as msg:\n                out.exception('Could not save image at %s to %s: %r' % (image.referrer, image.filename, msg))\n                self.errors += 1\n        return allskipped",
    "docstring": "Save a comic strip which can consist of multiple images."
  },
  {
    "code": "def _get_ssl_sock(self):\n        assert self.scheme == u\"https\", self\n        raw_connection = self.url_connection.raw._connection\n        if raw_connection.sock is None:\n            raw_connection.connect()\n        return raw_connection.sock",
    "docstring": "Get raw SSL socket."
  },
  {
    "code": "def _get_formatting_template(self, number_pattern, number_format):\n        longest_phone_number = unicod(\"999999999999999\")\n        number_re = re.compile(number_pattern)\n        m = number_re.search(longest_phone_number)\n        a_phone_number = m.group(0)\n        if len(a_phone_number) < len(self._national_number):\n            return U_EMPTY_STRING\n        template = re.sub(number_pattern, number_format, a_phone_number)\n        template = re.sub(\"9\", _DIGIT_PLACEHOLDER, template)\n        return template",
    "docstring": "Gets a formatting template which can be used to efficiently\n        format a partial number where digits are added one by one."
  },
  {
    "code": "def _build_zmat(self, construction_table):\n        c_table = construction_table\n        default_cols = ['atom', 'b', 'bond', 'a', 'angle', 'd', 'dihedral']\n        optional_cols = list(set(self.columns) - {'atom', 'x', 'y', 'z'})\n        zmat_frame = pd.DataFrame(columns=default_cols + optional_cols,\n                                  dtype='float', index=c_table.index)\n        zmat_frame.loc[:, optional_cols] = self.loc[c_table.index,\n                                                    optional_cols]\n        zmat_frame.loc[:, 'atom'] = self.loc[c_table.index, 'atom']\n        zmat_frame.loc[:, ['b', 'a', 'd']] = c_table\n        zmat_values = self._calculate_zmat_values(c_table)\n        zmat_frame.loc[:, ['bond', 'angle', 'dihedral']] = zmat_values\n        zmatrix = Zmat(zmat_frame, metadata=self.metadata,\n                       _metadata={'last_valid_cartesian': self.copy()})\n        return zmatrix",
    "docstring": "Create the Zmatrix from a construction table.\n\n        Args:\n            Construction table (pd.DataFrame):\n\n        Returns:\n            Zmat: A new instance of :class:`Zmat`."
  },
  {
    "code": "def cached_property(func):\n    name = func.__name__\n    doc = func.__doc__\n    def getter(self, name=name):\n        try:\n            return self.__dict__[name]\n        except KeyError:\n            self.__dict__[name] = value = func(self)\n            return value\n    getter.func_name = name\n    return property(getter, doc=doc)",
    "docstring": "Special property decorator that caches the computed\n    property value in the object's instance dict the first\n    time it is accessed."
  },
  {
    "code": "def ints(l, ifilter=lambda x: x, idescr=None):\n    if isinstance(l, string_types):\n        if l[0] == '[' and l[-1] == ']':\n            l = l[1:-1]\n        l = list(map(lambda x: x.strip(), l.split(',')))\n    try:\n        l = list(map(ifilter, list(map(int, l))))\n    except:\n        raise ValueError(\"Bad list of {}integers\"\n                         .format(\"\" if idescr is None else idescr + \" \"))\n    return l",
    "docstring": "Parses a comma-separated list of ints."
  },
  {
    "code": "def triangle_plots(self, basename=None, format='png',\n                       **kwargs):\n        if self.fit_for_distance:\n            fig1 = self.triangle(plot_datapoints=False,\n                                 params=['mass','radius','Teff','logg','feh','age',\n                                         'distance','AV'],\n                                 **kwargs)\n        else:\n            fig1 = self.triangle(plot_datapoints=False,\n                                 params=['mass','radius','Teff','feh','age'],\n                                 **kwargs)\n        if basename is not None:\n            plt.savefig('{}_physical.{}'.format(basename,format))\n            plt.close()\n        fig2 = self.prop_triangle(**kwargs)\n        if basename is not None:\n            plt.savefig('{}_observed.{}'.format(basename,format))\n            plt.close()\n        return fig1, fig2",
    "docstring": "Returns two triangle plots, one with physical params, one observational\n\n        :param basename:\n            If basename is provided, then plots will be saved as\n            \"[basename]_physical.[format]\" and \"[basename]_observed.[format]\"\n\n        :param format:\n            Format in which to save figures (e.g., 'png' or 'pdf')\n\n        :param **kwargs:\n            Additional keyword arguments passed to :func:`StarModel.triangle`\n            and :func:`StarModel.prop_triangle`\n\n        :return:\n             * Physical parameters triangle plot (mass, radius, Teff, feh, age, distance)\n             * Observed properties triangle plot."
  },
  {
    "code": "def get_descendants(self, include_self=False, depth=None):\n        params = {\"%s__parent\" % self._closure_childref():self.pk}\n        if depth is not None:\n            params[\"%s__depth__lte\" % self._closure_childref()] = depth\n        descendants = self._toplevel().objects.filter(**params)\n        if not include_self:\n            descendants = descendants.exclude(pk=self.pk)\n        return descendants.order_by(\"%s__depth\" % self._closure_childref())",
    "docstring": "Return all the descendants of this object."
  },
  {
    "code": "def _handle_wikilink_separator(self):\n        self._context ^= contexts.WIKILINK_TITLE\n        self._context |= contexts.WIKILINK_TEXT\n        self._emit(tokens.WikilinkSeparator())",
    "docstring": "Handle the separator between a wikilink's title and its text."
  },
  {
    "code": "def on_binlog(event, stream):\n    rows, meta = _rows_event_to_dict(event, stream)\n    table_name = '%s.%s' % (meta['schema'], meta['table'])\n    if meta['action'] == 'insert':\n        sig = signals.rows_inserted\n    elif meta['action'] == 'update':\n        sig = signals.rows_updated\n    elif meta['action'] == 'delete':\n        sig = signals.rows_deleted\n    else:\n        raise RuntimeError('Invalid action \"%s\"' % meta['action'])\n    sig.send(table_name, rows=rows, meta=meta)",
    "docstring": "Process on a binlog event\n\n    1. Convert event instance into a dict\n    2. Send corresponding schema/table/signals\n\n    Args:\n        event (pymysqlreplication.row_event.RowsEvent): the event"
  },
  {
    "code": "def exception(self, *exceptions):\n        def response(handler):\n            for exception in exceptions:\n                if isinstance(exception, (tuple, list)):\n                    for e in exception:\n                        self.error_handler.add(e, handler)\n                else:\n                    self.error_handler.add(exception, handler)\n            return handler\n        return response",
    "docstring": "Decorate a function to be registered as a handler for exceptions\n\n        :param exceptions: exceptions\n        :return: decorated function"
  },
  {
    "code": "def dump(obj, file_path, prettify=False):\n    with open(file_path, 'w') as fp:\n        fp.write(dumps(obj))",
    "docstring": "Dumps a data structure to the filesystem as TOML.\n\n    The given value must be either a dict of dict values, a dict, or a TOML file constructed by this module."
  },
  {
    "code": "def detect_stream_mode(stream):\n    if hasattr(stream, 'mode'):\n        if 'b' in stream.mode:\n            return bytes\n        elif 't' in stream.mode:\n            return str\n    if hasattr(stream, 'read'):\n        zeroStr = stream.read(0)\n        if type(zeroStr) is str:\n            return str\n        return bytes\n    elif hasattr(stream, 'recv'):\n        zeroStr = stream.recv(0)\n        if type(zeroStr) is str:\n            return str\n        return bytes\n    return bytes",
    "docstring": "detect_stream_mode - Detect the mode on a given stream\n\n            @param stream <object> - A stream object\n\n            If \"mode\" is present, that will be used.\n\n        @return <type> - \"Bytes\" type or \"str\" type"
  },
  {
    "code": "def counts(args):\n    p = OptionParser(counts.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(not p.print_help())\n    vcffile, = args\n    vcf_reader = vcf.Reader(open(vcffile))\n    for r in vcf_reader:\n        v = CPRA(r)\n        if not v.is_valid:\n            continue\n        for sample in r.samples:\n            ro = sample[\"RO\"]\n            ao = sample[\"AO\"]\n            print(\"\\t\".join(str(x) for x in (v, ro, ao)))",
    "docstring": "%prog counts vcffile\n\n    Collect allele counts from RO and AO fields."
  },
  {
    "code": "def endpoint_get(auth=None, **kwargs):\n    cloud = get_operator_cloud(auth)\n    kwargs = _clean_kwargs(**kwargs)\n    return cloud.get_endpoint(**kwargs)",
    "docstring": "Get a single endpoint\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' keystoneng.endpoint_get id=02cffaa173b2460f98e40eda3748dae5"
  },
  {
    "code": "def set_time(time):\n    time_format = _get_date_time_format(time)\n    dt_obj = datetime.strptime(time, time_format)\n    cmd = 'systemsetup -settime {0}'.format(dt_obj.strftime('%H:%M:%S'))\n    return salt.utils.mac_utils.execute_return_success(cmd)",
    "docstring": "Sets the current time. Must be in 24 hour format.\n\n    :param str time: The time to set in 24 hour format.  The value must be\n        double quoted. ie: '\"17:46\"'\n\n    :return: True if successful, False if not\n    :rtype: bool\n\n    :raises: SaltInvocationError on Invalid Time format\n    :raises: CommandExecutionError on failure\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' timezone.set_time '\"17:34\"'"
  },
  {
    "code": "def user_delete(users, **kwargs):\n    conn_args = _login(**kwargs)\n    ret = {}\n    try:\n        if conn_args:\n            method = 'user.delete'\n            if not isinstance(users, list):\n                params = [users]\n            else:\n                params = users\n            ret = _query(method, params, conn_args['url'], conn_args['auth'])\n            return ret['result']['userids']\n        else:\n            raise KeyError\n    except KeyError:\n        return ret",
    "docstring": "Delete zabbix users.\n\n    .. versionadded:: 2016.3.0\n\n    :param users: array of users (userids) to delete\n    :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n    :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n    :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n    :return: On success array with userids of deleted users.\n\n    CLI Example:\n    .. code-block:: bash\n\n        salt '*' zabbix.user_delete 15"
  },
  {
    "code": "def zip_namedtuple(nt_list):\n    if not nt_list:\n        return dict()\n    if not isinstance(nt_list, list):\n        nt_list = [nt_list]\n    for nt in nt_list:\n        assert type(nt) == type(nt_list[0])\n    ret = {k : [v] for k, v in nt_list[0]._asdict().items()}\n    for nt in nt_list[1:]:\n        for k, v in nt._asdict().items():\n            ret[k].append(v)\n    return ret",
    "docstring": "accept list of namedtuple, return a dict of zipped fields"
  },
  {
    "code": "def get_context_data(self, *args, **kwargs):\n\t\tcontext = super().get_context_data(**kwargs)\n\t\tcontext[\"is_plans_plural\"] = Plan.objects.count() > 1\n\t\tcontext[\"customer\"], _created = Customer.get_or_create(\n\t\t\tsubscriber=djstripe_settings.subscriber_request_callback(self.request)\n\t\t)\n\t\tcontext[\"subscription\"] = context[\"customer\"].subscription\n\t\treturn context",
    "docstring": "Inject is_plans_plural and customer into context_data."
  },
  {
    "code": "def rotate_scale(im, angle, scale, borderValue=0, interp=cv2.INTER_CUBIC):\n    im = np.asarray(im, dtype=np.float32)\n    rows, cols = im.shape\n    M = cv2.getRotationMatrix2D(\n        (cols / 2, rows / 2), -angle * 180 / np.pi, 1 / scale)\n    im = cv2.warpAffine(im, M, (cols, rows),\n                        borderMode=cv2.BORDER_CONSTANT,\n                        flags=interp,\n                        borderValue=borderValue)\n    return im",
    "docstring": "Rotates and scales the image\n\n    Parameters\n    ----------\n    im: 2d array\n        The image\n    angle: number\n        The angle, in radians, to rotate\n    scale: positive number\n        The scale factor\n    borderValue: number, default 0\n        The value for the pixels outside the border (default 0)\n\n    Returns\n    -------\n    im: 2d array\n        the rotated and scaled image\n\n    Notes\n    -----\n    The output image has the same size as the input.\n    Therefore the image may be cropped in the process."
  },
  {
    "code": "def removeByIndex(self, index):\n        if index < len(self._invites) -1 and \\\n           index >=0:\n            self._invites.remove(index)",
    "docstring": "removes a user from the invitation list by position"
  },
  {
    "code": "def vars_to_array(self):\n        logger.warn('This function is deprecated. You can inspect `self.np_vars` directly as NumPy arrays '\n                    'without conversion.')\n        if not self.vars:\n            return None\n        vars_matrix = matrix(self.vars, size=(self.vars[0].size[0],\n                                              len(self.vars))).trans()\n        self.vars_array = np.array(vars_matrix)\n        return self.vars_array",
    "docstring": "Convert `self.vars` to a numpy array\n\n        Returns\n        -------\n        numpy.array"
  },
  {
    "code": "def get_channels_by_sln_year_quarter(\n            self, channel_type, sln, year, quarter):\n        return self.search_channels(\n            type=channel_type, tag_sln=sln, tag_year=year, tag_quarter=quarter)",
    "docstring": "Search for all channels by sln, year and quarter"
  },
  {
    "code": "async def queryone(self, stmt, *args):\n        results = await self.query(stmt, *args)\n        if len(results) == 0:\n            raise NoResultError()\n        elif len(results) > 1:\n            raise ValueError(\"Expected 1 result, got %d\" % len(results))\n        return results[0]",
    "docstring": "Query for exactly one result.\n\n        Raises NoResultError if there are no results, or ValueError if\n        there are more than one."
  },
  {
    "code": "def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:\n        return self._query(f'guilds/{guild_id}/roles', 'GET')",
    "docstring": "Gets all the roles for the specified guild\n\n        Args:\n            guild_id: snowflake id of the guild\n\n        Returns:\n            List of dictionary objects of roles in the guild.\n\n            Example:\n                [\n                    {\n                        \"id\": \"41771983423143936\",\n                        \"name\": \"WE DEM BOYZZ!!!!!!\",\n                        \"color\": 3447003,\n                        \"hoist\": true,\n                        \"position\": 1,\n                        \"permissions\": 66321471,\n                        \"managed\": false,\n                        \"mentionable\": false\n                    },\n                    {\n                        \"hoist\": false,\n                        \"name\": \"Admin\",\n                        \"mentionable\": false,\n                        \"color\": 15158332,\n                        \"position\": 2,\n                        \"id\": \"151107620239966208\",\n                        \"managed\": false,\n                        \"permissions\": 66583679\n                      },\n                      {\n                        \"hoist\": false,\n                        \"name\": \"@everyone\",\n                        \"mentionable\": false,\n                        \"color\": 0,\n                        \"position\": 0,\n                        \"id\": \"151106790233210882\",\n                        \"managed\": false,\n                        \"permissions\": 37215297\n                      }\n                ]"
  },
  {
    "code": "def block_icmp(zone, icmp, permanent=True):\n    if icmp not in get_icmp_types(permanent):\n        log.error('Invalid ICMP type')\n        return False\n    if icmp in list_icmp_block(zone, permanent):\n        log.info('ICMP block already exists')\n        return 'success'\n    cmd = '--zone={0} --add-icmp-block={1}'.format(zone, icmp)\n    if permanent:\n        cmd += ' --permanent'\n    return __firewall_cmd(cmd)",
    "docstring": "Block a specific ICMP type on a zone\n\n    .. versionadded:: 2015.8.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' firewalld.block_icmp zone echo-reply"
  },
  {
    "code": "def update_single_grading_period(self, id, course_id, grading_periods_end_date, grading_periods_start_date, grading_periods_weight=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"course_id\"] = course_id\r\n        path[\"id\"] = id\r\n        data[\"grading_periods[start_date]\"] = grading_periods_start_date\r\n        data[\"grading_periods[end_date]\"] = grading_periods_end_date\r\n        if grading_periods_weight is not None:\r\n            data[\"grading_periods[weight]\"] = grading_periods_weight\r\n        self.logger.debug(\"PUT /api/v1/courses/{course_id}/grading_periods/{id} with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"PUT\", \"/api/v1/courses/{course_id}/grading_periods/{id}\".format(**path), data=data, params=params, no_data=True)",
    "docstring": "Update a single grading period.\r\n\r\n        Update an existing grading period."
  },
  {
    "code": "def _get_key_file_path():\n        if os.getenv(USER_HOME) is not None and os.access(os.getenv(USER_HOME),\n                                                          os.W_OK):\n            return os.path.join(os.getenv(USER_HOME), KEY_FILE_NAME)\n        return os.path.join(os.getcwd(), KEY_FILE_NAME)",
    "docstring": "Return the key file path."
  },
  {
    "code": "def print_time(self, message=\"Time is now: \", print_frame_info=True):\n        if print_frame_info:\n            frame_info = inspect.getouterframes(inspect.currentframe())[1]\n            print(message, (datetime.now() - self.start_time), frame_info)\n        else:\n            print(message, (datetime.now() - self.start_time))",
    "docstring": "Print the current elapsed time.\n\n        Kwargs:\n            message (str) : Message to prefix the time stamp.\n            print_frame_info (bool) : Add frame info to the print message."
  },
  {
    "code": "def create_event(service_key=None, description=None, details=None,\n                 incident_key=None, profile=None):\n    trigger_url = 'https://events.pagerduty.com/generic/2010-04-15/create_event.json'\n    if isinstance(details, six.string_types):\n        details = salt.utils.yaml.safe_load(details)\n        if isinstance(details, six.string_types):\n            details = {'details': details}\n    ret = salt.utils.json.loads(salt.utils.pagerduty.query(\n        method='POST',\n        profile_dict=__salt__['config.option'](profile),\n        api_key=service_key,\n        data={\n            'service_key': service_key,\n            'incident_key': incident_key,\n            'event_type': 'trigger',\n            'description': description,\n            'details': details,\n        },\n        url=trigger_url,\n        opts=__opts__\n    ))\n    return ret",
    "docstring": "Create an event in PagerDuty. Designed for use in states.\n\n    CLI Example:\n\n    .. code-block:: yaml\n\n        salt myminion pagerduty.create_event <service_key> <description> <details> \\\n        profile=my-pagerduty-account\n\n    The following parameters are required:\n\n    service_key\n        This key can be found by using pagerduty.list_services.\n\n    description\n        This is a short description of the event.\n\n    details\n        This can be a more detailed description of the event.\n\n    profile\n        This refers to the configuration profile to use to connect to the\n        PagerDuty service."
  },
  {
    "code": "def add(self, error):\n        if not self._path_of_(error):\n            self.errors.append(error)\n            self.errors.sort()\n        else:\n            super(ErrorTree, self).add(error)",
    "docstring": "Add an error to the tree.\n\n        :param error: :class:`~cerberus.errors.ValidationError`"
  },
  {
    "code": "def command_load(ctx, config, socket_name, socket_path, answer_yes, detached, colors):\n    util.oh_my_zsh_auto_title()\n    tmux_options = {\n        'socket_name': socket_name,\n        'socket_path': socket_path,\n        'answer_yes': answer_yes,\n        'colors': colors,\n        'detached': detached,\n    }\n    if not config:\n        click.echo(\"Enter at least one CONFIG\")\n        click.echo(ctx.get_help(), color=ctx.color)\n        ctx.exit()\n    if isinstance(config, string_types):\n        load_workspace(config, **tmux_options)\n    elif isinstance(config, tuple):\n        config = list(config)\n        for cfg in config[:-1]:\n            opt = tmux_options.copy()\n            opt.update({'detached': True})\n            load_workspace(cfg, **opt)\n        load_workspace(config[-1], **tmux_options)",
    "docstring": "Load a tmux workspace from each CONFIG.\n\n    CONFIG is a specifier for a configuration file.\n\n    If CONFIG is a path to a directory, tmuxp will search it for\n    \".tmuxp.{yaml,yml,json}\".\n\n    If CONFIG is has no directory component and only a filename, e.g.\n    \"myconfig.yaml\", tmuxp will search the users's config directory for that\n    file.\n\n    If CONFIG has no directory component, and only a name with no extension,\n    e.g. \"myconfig\", tmuxp will search the users's config directory for any\n    file with the extension \".yaml\", \".yml\", or \".json\" that matches that name.\n\n    If multiple configuration files that match a given CONFIG are found, tmuxp\n    will warn and pick the first one found.\n\n    If multiple CONFIGs are provided, workspaces will be created for all of\n    them. The last one provided will be attached. The others will be created in\n    detached mode."
  },
  {
    "code": "def make_dataset(self, dataset, raise_if_exists=False, body=None):\n        if body is None:\n            body = {}\n        try:\n            body['datasetReference'] = {\n                'projectId': dataset.project_id,\n                'datasetId': dataset.dataset_id\n            }\n            if dataset.location is not None:\n                body['location'] = dataset.location\n            self.client.datasets().insert(projectId=dataset.project_id, body=body).execute()\n        except http.HttpError as ex:\n            if ex.resp.status == 409:\n                if raise_if_exists:\n                    raise luigi.target.FileAlreadyExists()\n            else:\n                raise",
    "docstring": "Creates a new dataset with the default permissions.\n\n           :param dataset:\n           :type dataset: BQDataset\n           :param raise_if_exists: whether to raise an exception if the dataset already exists.\n           :raises luigi.target.FileAlreadyExists: if raise_if_exists=True and the dataset exists"
  },
  {
    "code": "def legal_edge_coords():\n    edges = set()\n    for tile_id in legal_tile_ids():\n        for edge in edges_touching_tile(tile_id):\n            edges.add(edge)\n    logging.debug('Legal edge coords({})={}'.format(len(edges), edges))\n    return edges",
    "docstring": "Return all legal edge coordinates on the grid."
  },
  {
    "code": "def get_data(self):\n        \"Get SNMP values from host\"\n        alarm_oids = [netsnmp.Varbind(alarms[alarm_id]['oid']) for alarm_id in self.models[self.modem_type]['alarms']]\n        metric_oids = [netsnmp.Varbind(metrics[metric_id]['oid']) for metric_id in self.models[self.modem_type]['metrics']]\n        response = self.snmp_session.get(netsnmp.VarList(*alarm_oids + metric_oids))\n        return (\n            response[0:len(alarm_oids)],\n            response[len(alarm_oids):]\n        )",
    "docstring": "Get SNMP values from host"
  },
  {
    "code": "def run_per_switch_cmds(self, switch_cmds):\n        for switch_ip, cmds in switch_cmds.items():\n            switch = self._switches.get(switch_ip)\n            self.run_openstack_sg_cmds(cmds, switch)",
    "docstring": "Applies cmds to appropriate switches\n\n        This takes in a switch->cmds mapping and runs only the set of cmds\n        specified for a switch on that switch. This helper is used for\n        applying/removing ACLs to/from interfaces as this config will vary\n        from switch to switch."
  },
  {
    "code": "def recover_all_handler(self):\n        for handler in self._handler_cache:\n            self.logger.addHandler(handler)\n        self._handler_cache = list()",
    "docstring": "Relink the file handler association you just removed."
  },
  {
    "code": "def location(hexgrid_type, coord):\n    if hexgrid_type == TILE:\n        return str(coord)\n    elif hexgrid_type == NODE:\n        tile_id = nearest_tile_to_node(coord)\n        dirn = tile_node_offset_to_direction(coord - tile_id_to_coord(tile_id))\n        return '({} {})'.format(tile_id, dirn)\n    elif hexgrid_type == EDGE:\n        tile_id = nearest_tile_to_edge(coord)\n        dirn = tile_edge_offset_to_direction(coord - tile_id_to_coord(tile_id))\n        return '({} {})'.format(tile_id, dirn)\n    else:\n        logging.warning('unsupported hexgrid_type={}'.format(hexgrid_type))\n        return None",
    "docstring": "Returns a formatted string representing the coordinate. The format depends on the\n    coordinate type.\n\n    Tiles look like: 1, 12\n    Nodes look like: (1 NW), (12 S)\n    Edges look like: (1 NW), (12 SE)\n\n    :param hexgrid_type: hexgrid.TILE, hexgrid.NODE, hexgrid.EDGE\n    :param coord: integer coordinate in this module's hexadecimal coordinate system\n    :return: formatted string for display"
  },
  {
    "code": "def GetArtifactParserDependencies(rdf_artifact):\n  deps = set()\n  processors = parser.Parser.GetClassesByArtifact(rdf_artifact.name)\n  for p in processors:\n    deps.update(p.knowledgebase_dependencies)\n  return deps",
    "docstring": "Return the set of knowledgebase path dependencies required by the parser.\n\n  Args:\n    rdf_artifact: RDF artifact object.\n\n  Returns:\n    A set of strings for the required kb objects e.g.\n    [\"users.appdata\", \"systemroot\"]"
  },
  {
    "code": "def get_scenenode(self, nodes):\n        scenenodes = cmds.ls(nodes, type='jb_sceneNode')\n        assert scenenodes, \"Found no scene nodes!\"\n        return sorted(scenenodes)[0]",
    "docstring": "Get the scenenode in the given nodes\n\n        There should only be one scenenode in nodes!\n\n        :param nodes:\n        :type nodes:\n        :returns: None\n        :rtype: None\n        :raises: AssertionError"
  },
  {
    "code": "def _can_connect(ip, port):\n    cs = socket.socket()\n    try:\n        cs.connect((ip, port))\n        cs.close()\n        return True\n    except socket.error:\n        return False",
    "docstring": "Checks if a TCP port at IP address is possible to connect to"
  },
  {
    "code": "def raise_figure_window(f=0):\n    if _fun.is_a_number(f): f = _pylab.figure(f)\n    f.canvas.manager.window.raise_()",
    "docstring": "Raises the supplied figure number or figure window."
  },
  {
    "code": "def experiments_predictions_update_state_success(self, experiment_id, run_id, result_file):\n        model_run = self.experiments_predictions_get(experiment_id, run_id)\n        if model_run is None:\n            return None\n        funcdata = self.funcdata.create_object(result_file)\n        return self.predictions.update_state(\n            run_id,\n            modelrun.ModelRunSuccess(funcdata.identifier)\n        )",
    "docstring": "Update state of given prediction to success. Create a function data\n        resource for the given result file and associate it with the model run.\n\n        Parameters\n        ----------\n        experiment_id : string\n            Unique experiment identifier\n        run_id : string\n            Unique model run identifier\n        result_file : string\n            Path to model run result file\n\n        Returns\n        -------\n        ModelRunHandle\n            Handle for updated model run or None is prediction is undefined"
  },
  {
    "code": "def _build_deployments_object(\n    contract_type: str,\n    deployment_bytecode: Dict[str, Any],\n    runtime_bytecode: Dict[str, Any],\n    compiler: Dict[str, Any],\n    address: HexStr,\n    tx: HexStr,\n    block: HexStr,\n    manifest: Dict[str, Any],\n) -> Iterable[Tuple[str, Any]]:\n    yield \"contract_type\", contract_type\n    yield \"address\", to_hex(address)\n    if deployment_bytecode:\n        yield \"deployment_bytecode\", deployment_bytecode\n    if compiler:\n        yield \"compiler\", compiler\n    if tx:\n        yield \"transaction\", tx\n    if block:\n        yield \"block\", block\n    if runtime_bytecode:\n        yield \"runtime_bytecode\", runtime_bytecode",
    "docstring": "Returns a dict with properly formatted deployment data."
  },
  {
    "code": "def serialize(self):\n        expects = [exp.serialize() for exp in self.expects]\n        converted_dict = {\n            'id': self.id,\n            'name': self.pretty_name,\n            'raw_name': self.name,\n            'doc': self.doc,\n            'error': self.error,\n            'skipped': self.skipped,\n            'skip_reason': self.skip_reason,\n            'execute_kwargs': self.safe_execute_kwargs,\n            'metadata': self.metadata,\n            'start': self.start_time,\n            'end': self.end_time,\n            'expects': expects,\n            'success': self.success\n        }\n        return remove_empty_entries_from_dict(converted_dict)",
    "docstring": "Serializes the CaseWrapper object for collection.\n\n        Warning, this will only grab the available information.\n        It is strongly that you only call this once all specs and\n        tests have completed."
  },
  {
    "code": "def docker(gandi, vm, args):\n    if not [basedir for basedir in os.getenv('PATH', '.:/usr/bin').split(':')\n            if os.path.exists('%s/docker' % basedir)]:\n        gandi.echo(\n)\n        return\n    if vm:\n        gandi.configure(True, 'dockervm', vm)\n    else:\n        vm = gandi.get('dockervm')\n    if not vm:\n        gandi.echo(\n)\n        return\n    return gandi.docker.handle(vm, args)",
    "docstring": "Manage docker instance"
  },
  {
    "code": "def set_element_dt(self, el_name, dt, tz=None, el_idx=0):\n        dt = d1_common.date_time.cast_naive_datetime_to_tz(dt, tz)\n        self.get_element_by_name(el_name, el_idx).text = dt.isoformat()",
    "docstring": "Set the text of the selected element to an ISO8601 formatted datetime.\n\n        Args:\n          el_name : str\n            Name of element to update.\n\n          dt : datetime.datetime\n            Date and time to set\n\n          tz : datetime.tzinfo\n            Timezone to set\n\n            - Without a timezone, other contextual information is required in order to\n              determine the exact represented time.\n            - If dt has timezone: The ``tz`` parameter is ignored.\n            - If dt is naive (without timezone): The timezone is set to ``tz``.\n            - ``tz=None``: Prevent naive dt from being set to a timezone. Without a\n              timezone, other contextual information is required in order to determine\n              the exact represented time.\n            - ``tz=d1_common.date_time.UTC()``: Set naive dt to UTC.\n\n          el_idx : int\n            Index of element to use in the event that there are multiple sibling\n            elements with the same name."
  },
  {
    "code": "def generate_age(issue_time):\n    td = datetime.datetime.now() - issue_time\n    age = (td.microseconds + (td.seconds + td.days * 24 * 3600)\n           * 10 ** 6) / 10 ** 6\n    return unicode_type(age)",
    "docstring": "Generate a age parameter for MAC authentication draft 00."
  },
  {
    "code": "def generate(basename, xml_list):\n    generate_shared(basename, xml_list)\n    for xml in xml_list:\n        generate_message_definitions(basename, xml)",
    "docstring": "generate complete MAVLink Objective-C implemenation"
  },
  {
    "code": "def __CheckAndUnifyQueryFormat(self, query_body):\n        if (self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.Default or\n               self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.Query):\n            if not isinstance(query_body, dict) and not isinstance(query_body, six.string_types):\n                raise TypeError('query body must be a dict or string.')\n            if isinstance(query_body, dict) and not query_body.get('query'):\n                raise ValueError('query body must have valid query text with key \"query\".')\n            if isinstance(query_body, six.string_types):\n                return {'query': query_body}\n        elif (self._query_compatibility_mode == CosmosClient._QueryCompatibilityMode.SqlQuery and\n              not isinstance(query_body, six.string_types)):\n            raise TypeError('query body must be a string.')\n        else:\n            raise SystemError('Unexpected query compatibility mode.')\n        return query_body",
    "docstring": "Checks and unifies the format of the query body.\n\n        :raises TypeError: If query_body is not of expected type (depending on the query compatibility mode).\n        :raises ValueError: If query_body is a dict but doesn\\'t have valid query text.\n        :raises SystemError: If the query compatibility mode is undefined.\n\n        :param (str or dict) query_body:\n\n        :return:\n            The formatted query body.\n        :rtype:\n            dict or string"
  },
  {
    "code": "def _fracRoiSparse(self):\n        self.frac_roi_sparse = np.min([self.mask_1.frac_roi_sparse,self.mask_2.frac_roi_sparse],axis=0)\n        return self.frac_roi_sparse",
    "docstring": "Calculate an approximate pixel coverage fraction from the two masks.\n\n        We have no way to know a priori how much the coverage of the\n        two masks overlap in a give pixel. For example, masks that each\n        have frac = 0.5 could have a combined frac = [0.0 to 0.5]. \n        The limits will be: \n          max:  min(frac1,frac2)\n          min:  max((frac1+frac2)-1, 0.0)\n\n        Sometimes we are lucky and our fracdet is actually already\n        calculated for the two masks combined, so that the max\n        condition is satisfied. That is what we will assume..."
  },
  {
    "code": "def solve(graph, debug=False, anim=None):\n    specs = ding0_graph_to_routing_specs(graph)\n    RoutingGraph = Graph(specs)\n    timeout = 30000\n    savings_solver = savings.ClarkeWrightSolver()\n    local_search_solver = local_search.LocalSearchSolver()\n    start = time.time()\n    savings_solution = savings_solver.solve(RoutingGraph, timeout, debug, anim)\n    if debug:\n        logger.debug('ClarkeWrightSolver solution:')\n        util.print_solution(savings_solution)\n        logger.debug('Elapsed time (seconds): {}'.format(time.time() - start))\n    local_search_solution = local_search_solver.solve(RoutingGraph, savings_solution, timeout, debug, anim)\n    if debug:\n        logger.debug('Local Search solution:')\n        util.print_solution(local_search_solution)\n        logger.debug('Elapsed time (seconds): {}'.format(time.time() - start))\n    return routing_solution_to_ding0_graph(graph, local_search_solution)",
    "docstring": "Do MV routing for given nodes in `graph`.\n    \n    Translate data from node objects to appropriate format before.\n\n    Args\n    ----\n    graph: :networkx:`NetworkX Graph Obj< >`\n        NetworkX graph object with nodes\n    debug: bool, defaults to False\n        If True, information is printed while routing\n    anim: AnimationDing0\n        AnimationDing0 object\n\n    Returns\n    -------\n    :networkx:`NetworkX Graph Obj< >`\n        NetworkX graph object with nodes and edges\n        \n    See Also\n    --------\n    ding0.tools.animation.AnimationDing0 : for a more detailed description on anim parameter."
  },
  {
    "code": "def softmax_cross_entropy_one_hot(logits, labels, weights_fn=None):\n  with tf.variable_scope(\"softmax_cross_entropy_one_hot\",\n                         values=[logits, labels]):\n    del weights_fn\n    cross_entropy = tf.losses.softmax_cross_entropy(\n        onehot_labels=labels, logits=logits)\n    return cross_entropy, tf.constant(1.0)",
    "docstring": "Calculate softmax cross entropy given one-hot labels and logits.\n\n  Args:\n    logits: Tensor of size [batch-size, o=1, p=1, num-classes]\n    labels: Tensor of size [batch-size, o=1, p=1, num-classes]\n    weights_fn: Function that takes in labels and weighs examples (unused)\n  Returns:\n    cross-entropy (scalar), weights"
  },
  {
    "code": "def cleanup(first_I, first_Z):\n    cont = 0\n    Nmin = len(first_I)\n    if len(first_Z) < Nmin:\n        Nmin = len(first_Z)\n    for kk in range(Nmin):\n        if first_I[kk][0] != first_Z[kk][0]:\n            print(\"\\n WARNING: \")\n            if first_I[kk] < first_Z[kk]:\n                del first_I[kk]\n            else:\n                del first_Z[kk]\n            print(\"Unmatched step number: \", kk + 1, '  ignored')\n            cont = 1\n        if cont == 1:\n            return first_I, first_Z, cont\n    return first_I, first_Z, cont",
    "docstring": "cleans up unbalanced steps\n     failure can be from unbalanced final step, or from missing steps,\n     this takes care of  missing steps"
  },
  {
    "code": "def coerce_to_list(val):\n    if val:\n        if not isinstance(val, (list, tuple)):\n            val = [val]\n    else:\n        val = []\n    return val",
    "docstring": "For parameters that can take either a single string or a list of strings,\n    this function will ensure that the result is a list containing the passed\n    values."
  },
  {
    "code": "def deletegitlabciservice(self, project_id, token, project_url):\n        request = requests.delete(\n            '{0}/{1}/services/gitlab-ci'.format(self.projects_url, project_id),\n            headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)\n        return request.status_code == 200",
    "docstring": "Delete GitLab CI service settings\n\n        :param project_id: Project ID\n        :param token: Token\n        :param project_url: Project URL\n        :return: true if success, false if not"
  },
  {
    "code": "def _get_socket(self, sid):\n        try:\n            s = self.sockets[sid]\n        except KeyError:\n            raise KeyError('Session not found')\n        if s.closed:\n            del self.sockets[sid]\n            raise KeyError('Session is disconnected')\n        return s",
    "docstring": "Return the socket object for a given session."
  },
  {
    "code": "def get_class(classname):\n    parts = classname.split('.')\n    module = \".\".join(parts[:-1])\n    m = __import__(module)\n    for comp in parts[1:]:\n        m = getattr(m, comp)\n    return m",
    "docstring": "Returns the class object associated with the dot-notation classname.\n\n    Taken from here: http://stackoverflow.com/a/452981\n\n    :param classname: the classname\n    :type classname: str\n    :return: the class object\n    :rtype: object"
  },
  {
    "code": "def from_soup(self,soup):\n\t\tif soup is None or soup is '':\n\t\t\treturn None\n\t\telse:\t\n\t\t\tauthor_name = soup.find('em').contents[0].strip() if soup.find('em') else ''\n\t\t\tauthor_image = soup.find('img').get('src') if soup.find('img') else ''\n\t\t\tauthor_contact = Contact.from_soup(self,soup)\n\t\t\treturn Author(author_name,author_image,author_contact)",
    "docstring": "Factory Pattern. Fetches author data from given soup and builds the object"
  },
  {
    "code": "def minimum(attrs, inputs, proto_obj):\n    if len(inputs) > 1:\n        mxnet_op = symbol.minimum(inputs[0], inputs[1])\n        for op_input in inputs[2:]:\n            mxnet_op = symbol.minimum(mxnet_op, op_input)\n    else:\n        mxnet_op = symbol.minimum(inputs[0], inputs[0])\n    return mxnet_op, attrs, inputs",
    "docstring": "Elementwise minimum of arrays."
  },
  {
    "code": "def cliques(self, reordered = True):\n        if reordered:\n            return [list(self.snrowidx[self.sncolptr[k]:self.sncolptr[k+1]]) for k in range(self.Nsn)]\n        else:\n            return [list(self.__p[self.snrowidx[self.sncolptr[k]:self.sncolptr[k+1]]]) for k in range(self.Nsn)]",
    "docstring": "Returns a list of cliques"
  },
  {
    "code": "def overlap(listA, listB):\n    if (listA is None) or (listB is None):\n        return []\n    else:\n        return list(set(listA) & set(listB))",
    "docstring": "Return list of objects shared by listA, listB."
  },
  {
    "code": "def cursor_to_line(self, line=None):\n        self.cursor.y = (line or 1) - 1\n        if mo.DECOM in self.mode:\n            self.cursor.y += self.margins.top\n        self.ensure_vbounds()",
    "docstring": "Move cursor to a specific line in the current column.\n\n        :param int line: line number to move the cursor to."
  },
  {
    "code": "def create_notification_channel(self, callback_url, calendar_ids=()):\n        data = {'callback_url': callback_url}\n        if calendar_ids:\n            data['filters'] = {'calendar_ids': calendar_ids}\n        return self.request_handler.post('channels', data=data).json()['channel']",
    "docstring": "Create a new channel for receiving push notifications.\n\n        :param string callback_url: The url that will receive push notifications.\n        Must not be longer than 128 characters and should be HTTPS.\n        :param tuple calendar_ids: List of calendar ids to create notification channels for. (Optional. Default empty tuple)\n        :return: Channel id and channel callback\n        :rtype: ``dict``"
  },
  {
    "code": "def execute_r(prog, quiet):\n    FNULL = open(os.devnull, 'w') if quiet else None\n    try:\n        input_proc = subprocess.Popen([\"echo\", prog], stdout=subprocess.PIPE)\n        status = subprocess.call(\"R --no-save --quiet\",\n                                 stdin=input_proc.stdout,\n                                 stdout=FNULL,\n                                 stderr=subprocess.STDOUT,\n                                 shell=True)\n        if status != 0:\n            raise ValueError(\"ggplot2 bridge failed for program: {}.\"\n                             \" Check for an error\".format(prog))\n    finally:\n        if FNULL is not None:\n            FNULL.close()",
    "docstring": "Run the R code prog an R subprocess\n\n    @raises ValueError if the subprocess exits with non-zero status"
  },
  {
    "code": "def bin_number(datapoint, intervals):\n  index = numpy.searchsorted(intervals, datapoint)\n  return [0 if index != i else 1 for i in range(len(intervals) + 1)]",
    "docstring": "Given a datapoint and intervals representing bins, returns the number\n  represented in binned form, where the bin including the value is\n  set to 1 and all others are 0."
  },
  {
    "code": "def save(self):\n\t\twith open(self.configuration_file, 'w') as file_h:\n\t\t\tfile_h.write(self._serializer('dumps', self._storage))",
    "docstring": "Save the current configuration to disk."
  },
  {
    "code": "def get_intercom_data(self):\n        return {\n            \"user_id\": self.intercom_id,\n            \"email\": self.email,\n            \"name\": self.get_full_name(),\n            \"last_request_at\": self.last_login.strftime(\"%s\") if self.last_login else \"\",\n            \"created_at\": self.date_joined.strftime(\"%s\"),\n            \"custom_attributes\": {\n                \"is_admin\": self.is_superuser\n            }\n        }",
    "docstring": "Specify the user data sent to Intercom API"
  },
  {
    "code": "def search_phenotype(\n            self, phenotype_association_set_id=None, phenotype_id=None,\n            description=None, type_=None, age_of_onset=None):\n        request = protocol.SearchPhenotypesRequest()\n        request.phenotype_association_set_id = phenotype_association_set_id\n        if phenotype_id:\n            request.id = phenotype_id\n        if description:\n            request.description = description\n        if type_:\n            request.type.mergeFrom(type_)\n        if age_of_onset:\n            request.age_of_onset = age_of_onset\n        request.page_size = pb.int(self._page_size)\n        return self._run_search_request(\n            request, \"phenotypes\",\n            protocol.SearchPhenotypesResponse)",
    "docstring": "Returns an iterator over the Phenotypes from the server"
  },
  {
    "code": "def texture_map_to_plane(dataset, origin=None, point_u=None, point_v=None,\n                             inplace=False, name='Texture Coordinates'):\n        alg = vtk.vtkTextureMapToPlane()\n        if origin is None or point_u is None or point_v is None:\n            alg.SetAutomaticPlaneGeneration(True)\n        else:\n            alg.SetOrigin(origin)\n            alg.SetPoint1(point_u)\n            alg.SetPoint2(point_v)\n        alg.SetInputDataObject(dataset)\n        alg.Update()\n        output = _get_output(alg)\n        if not inplace:\n            return output\n        t_coords = output.GetPointData().GetTCoords()\n        t_coords.SetName(name)\n        otc = dataset.GetPointData().GetTCoords()\n        dataset.GetPointData().SetTCoords(t_coords)\n        dataset.GetPointData().AddArray(t_coords)\n        dataset.GetPointData().AddArray(otc)\n        return",
    "docstring": "Texture map this dataset to a user defined plane. This is often used\n        to define a plane to texture map an image to this dataset. The plane\n        defines the spatial reference and extent of that image.\n\n        Parameters\n        ----------\n        origin : tuple(float)\n            Length 3 iterable of floats defining the XYZ coordinates of the\n            BOTTOM LEFT CORNER of the plane\n\n        point_u : tuple(float)\n            Length 3 iterable of floats defining the XYZ coordinates of the\n            BOTTOM RIGHT CORNER of the plane\n\n        point_v : tuple(float)\n            Length 3 iterable of floats defining the XYZ coordinates of the\n            TOP LEFT CORNER of the plane\n\n        inplace : bool, optional\n            If True, the new texture coordinates will be added to the dataset\n            inplace. If False (default), a new dataset is returned with the\n            textures coordinates\n\n        name : str, optional\n            The string name to give the new texture coordinates if applying\n            the filter inplace."
  },
  {
    "code": "def construct_parameter_pattern(parameter):\n    name = parameter['name']\n    type = parameter['type']\n    repeated = '[^/]'\n    if type == 'integer':\n        repeated = '\\d'\n    return \"(?P<{name}>{repeated}+)\".format(name=name, repeated=repeated)",
    "docstring": "Given a parameter definition returns a regex pattern that will match that\n    part of the path."
  },
  {
    "code": "def moothedata(data, key=None):\n    if not key:\n        key = choice(list(data.keys()))\n        logger.debug(\"Using randomly chosen key: %s\", key)\n    msg = cow.Moose().milk(\"{0}: {1}\".format(key.capitalize(), data[key]))\n    return msg",
    "docstring": "Return an amusing picture containing an item from a dict.\n\n    Parameters\n    ----------\n    data: mapping\n        A mapping, such as a raster dataset's ``meta`` or ``profile``\n        property.\n    key:\n        A key of the ``data`` mapping."
  },
  {
    "code": "def get_logging_tensor_hook(every_n_iter=100, tensors_to_log=None, **kwargs):\n  if tensors_to_log is None:\n    tensors_to_log = _TENSORS_TO_LOG\n  return tf.train.LoggingTensorHook(\n      tensors=tensors_to_log,\n      every_n_iter=every_n_iter)",
    "docstring": "Function to get LoggingTensorHook.\n\n  Args:\n    every_n_iter: `int`, print the values of `tensors` once every N local\n      steps taken on the current worker.\n    tensors_to_log: List of tensor names or dictionary mapping labels to tensor\n      names. If not set, log _TENSORS_TO_LOG by default.\n    **kwargs: a dictionary of arguments to LoggingTensorHook.\n\n  Returns:\n    Returns a LoggingTensorHook with a standard set of tensors that will be\n    printed to stdout."
  },
  {
    "code": "def textContent(self, text: str) -> None:\n        self._set_text_content(text)\n        if self.connected:\n            self._set_text_content_web(text)",
    "docstring": "Set textContent both on this node and related browser node."
  },
  {
    "code": "def update_module_file(redbaron_tree, module_path, show_diff=False, dry_run=False):\n    with tempfile.NamedTemporaryFile() as tmp_file:\n        tmp_file.write(redbaron_tree_to_module_str(redbaron_tree))\n        tmp_file.seek(0)\n        if are_files_equal(module_path, tmp_file.name):\n            logging.debug('Source unchanged')\n            return False\n        logging.debug('Source modified')\n        tmp_file.seek(0)\n        diff_update_file(module_path, tmp_file.read(), show_diff, dry_run)",
    "docstring": "Set show_diff to False to overwrite module_path with a new file generated from\n    ``redbaron_tree``.\n\n    Returns True if tree is different from source."
  },
  {
    "code": "def intervals_to_samples(intervals, labels, offset=0, sample_size=0.1,\n                         fill_value=None):\n    num_samples = int(np.floor(intervals.max() / sample_size))\n    sample_indices = np.arange(num_samples, dtype=np.float32)\n    sample_times = (sample_indices*sample_size + offset).tolist()\n    sampled_labels = interpolate_intervals(\n        intervals, labels, sample_times, fill_value)\n    return sample_times, sampled_labels",
    "docstring": "Convert an array of labeled time intervals to annotated samples.\n\n    Parameters\n    ----------\n    intervals : np.ndarray, shape=(n, d)\n        An array of time intervals, as returned by\n        :func:`mir_eval.io.load_intervals()` or\n        :func:`mir_eval.io.load_labeled_intervals()`.\n        The ``i`` th interval spans time ``intervals[i, 0]`` to\n        ``intervals[i, 1]``.\n\n    labels : list, shape=(n,)\n        The annotation for each interval\n\n    offset : float > 0\n        Phase offset of the sampled time grid (in seconds)\n        (Default value = 0)\n\n    sample_size : float > 0\n        duration of each sample to be generated (in seconds)\n        (Default value = 0.1)\n\n    fill_value : type(labels[0])\n        Object to use for the label with out-of-range time points.\n        (Default value = None)\n\n    Returns\n    -------\n    sample_times : list\n        list of sample times\n\n    sample_labels : list\n        array of labels for each generated sample\n\n    Notes\n    -----\n        Intervals will be rounded down to the nearest multiple\n        of ``sample_size``."
  },
  {
    "code": "def option(self, opt):\n        if 'config.merge' in self.functions:\n            return self.functions['config.merge'](opt, {}, omit_master=True)\n        return self.opts.get(opt, {})",
    "docstring": "Return options merged from config and pillar"
  },
  {
    "code": "def extensionResponse(self, namespace_uri, require_signed):\n        if require_signed:\n            return self.getSignedNS(namespace_uri)\n        else:\n            return self.message.getArgs(namespace_uri)",
    "docstring": "Return response arguments in the specified namespace.\n\n        @param namespace_uri: The namespace URI of the arguments to be\n        returned.\n\n        @param require_signed: True if the arguments should be among\n        those signed in the response, False if you don't care.\n\n        If require_signed is True and the arguments are not signed,\n        return None."
  },
  {
    "code": "def _render_with_context(self, parsed_node, config):\n        context = dbt.context.parser.generate(\n            parsed_node,\n            self.root_project_config,\n            self.macro_manifest,\n            config)\n        dbt.clients.jinja.get_rendered(\n            parsed_node.raw_sql, context, parsed_node.to_shallow_dict(),\n            capture_macros=True)",
    "docstring": "Given the parsed node and a SourceConfig to use during parsing,\n        render the node's sql wtih macro capture enabled.\n\n        Note: this mutates the config object when config() calls are rendered."
  },
  {
    "code": "def submit(cls, job_config, in_xg_transaction=False):\n    cls.__validate_job_config(job_config)\n    mapper_spec = job_config._get_mapper_spec()\n    mapreduce_params = job_config._get_mr_params()\n    mapreduce_spec = model.MapreduceSpec(\n        job_config.job_name,\n        job_config.job_id,\n        mapper_spec.to_json(),\n        mapreduce_params,\n        util._obj_to_path(job_config._hooks_cls))\n    if in_xg_transaction:\n      propagation = db.MANDATORY\n    else:\n      propagation = db.INDEPENDENT\n    state = None\n    @db.transactional(propagation=propagation)\n    def _txn():\n      state = cls.__create_and_save_state(job_config, mapreduce_spec)\n      cls.__add_kickoff_task(job_config, mapreduce_spec)\n      return state\n    state = _txn()\n    return cls(state)",
    "docstring": "Submit the job to run.\n\n    Args:\n      job_config: an instance of map_job.MapJobConfig.\n      in_xg_transaction: controls what transaction scope to use to start this MR\n        job. If True, there has to be an already opened cross-group transaction\n        scope. MR will use one entity group from it.\n        If False, MR will create an independent transaction to start the job\n        regardless of any existing transaction scopes.\n\n    Returns:\n      a Job instance representing the submitted job."
  },
  {
    "code": "def reverse_reference(self):\n        self.ref_start = self.ref_length - self.ref_start - 1\n        self.ref_end = self.ref_length - self.ref_end - 1",
    "docstring": "Changes the coordinates as if the reference sequence has been reverse complemented"
  },
  {
    "code": "def add(self, name, arcname=None, **kwargs):\n        if os.path.isdir(name):\n            exclusions = get_exclusions(name)\n            if exclusions:\n                target_prefix = os.path.abspath(arcname or name)\n                kwargs.setdefault('filter', get_filter_func(exclusions, target_prefix))\n        self.tarfile.add(name, arcname=arcname, **kwargs)",
    "docstring": "Add a file or directory to the context tarball.\n\n        :param name: File or directory path.\n        :type name: unicode | str\n        :param args: Additional args for :meth:`tarfile.TarFile.add`.\n        :param kwargs: Additional kwargs for :meth:`tarfile.TarFile.add`."
  },
  {
    "code": "def CallMethod(self, method, controller, request, response_class, done):\n        try:\n            self.validate_request(request)\n            if not self.sock:\n                self.get_connection(self.host, self.port)\n            self.send_rpc_message(method, request)\n            byte_stream = self.recv_rpc_message()\n            return self.parse_response(byte_stream, response_class)\n        except RequestError:\n            raise\n        except Exception:\n            self.close_socket()\n            raise",
    "docstring": "Call the RPC method. The naming doesn't confirm PEP8, since it's\n        a method called by protobuf"
  },
  {
    "code": "def apply_to(self, A):\n        if A.ndim == 1:\n            A = np.expand_dims(A, axis=0)\n        rows, cols = A.shape\n        A_new = np.hstack([A, np.ones((rows, 1))])\n        A_new = np.transpose(self.T.dot(np.transpose(A_new)))\n        return A_new[:, 0:cols]",
    "docstring": "Apply the coordinate transformation to points in A."
  },
  {
    "code": "def unlock_area(self, code, index):\n        logger.debug(\"unlocking area code %s index %s\" % (code, index))\n        return self.library.Srv_UnlockArea(self.pointer, code, index)",
    "docstring": "Unlocks a previously locked shared memory area."
  },
  {
    "code": "def get_authors(repo_path, from_commit):\n    repo = dulwich.repo.Repo(repo_path)\n    refs = get_refs(repo)\n    start_including = False\n    authors = set()\n    if from_commit is None:\n        start_including = True\n    for commit_sha, children in reversed(\n        get_children_per_first_parent(repo_path).items()\n    ):\n        commit = get_repo_object(repo, commit_sha)\n        if (\n            start_including or commit_sha.startswith(from_commit) or\n            fuzzy_matches_refs(from_commit, refs.get(commit_sha, []))\n        ):\n            authors.add(commit.author.decode())\n            for child in children:\n                authors.add(child.author.decode())\n            start_including = True\n    return '\\n'.join(sorted(authors))",
    "docstring": "Given a repo and optionally a base revision to start from, will return\n    the list of authors."
  },
  {
    "code": "async def identify(self, duration_s: int = 5):\n        count = duration_s * 4\n        on = False\n        for sec in range(count):\n            then = self._loop.time()\n            self.set_lights(button=on)\n            on = not on\n            now = self._loop.time()\n            await asyncio.sleep(max(0, 0.25-(now-then)))\n        self.set_lights(button=True)",
    "docstring": "Blink the button light to identify the robot.\n\n        :param int duration_s: The duration to blink for, in seconds."
  },
  {
    "code": "def _needs_base64_encoding(self, attr_type, attr_value):\n        return attr_type.lower() in self._base64_attrs or \\\n            isinstance(attr_value, bytes) or \\\n            UNSAFE_STRING_RE.search(attr_value) is not None",
    "docstring": "Return True if attr_value has to be base-64 encoded.\n\n        This is the case because of special chars or because attr_type is in\n        self._base64_attrs"
  },
  {
    "code": "def zeroed_observation(observation):\n    if hasattr(observation, 'shape'):\n        return np.zeros(observation.shape)\n    elif hasattr(observation, '__iter__'):\n        out = []\n        for x in observation:\n            out.append(zeroed_observation(x))\n        return out\n    else:\n        return 0.",
    "docstring": "Return an array of zeros with same shape as given observation\n\n    # Argument\n        observation (list): List of observation\n    \n    # Return\n        A np.ndarray of zeros with observation.shape"
  },
  {
    "code": "def EXTRA_LOGGING(self):\n        input_text = get('EXTRA_LOGGING', '')\n        modules = input_text.split(',')\n        if input_text:\n            modules = input_text.split(',')\n            modules = [x.split(':') for x in modules]\n        else:\n            modules = []\n        return modules",
    "docstring": "lista modulos con los distintos niveles a logear y su\n        nivel de debug\n\n        Por ejemplo:\n\n            [Logs]\n            EXTRA_LOGGING = oscar.paypal:DEBUG, django.db:INFO"
  },
  {
    "code": "def _add_single_session_to_to_ordered_dict(self, d, dataset_index, recommended_only):\n        for model_index, model in enumerate(self.models):\n            show_null = False\n            if recommended_only:\n                if self.recommendation_enabled:\n                    if self.recommended_model is None:\n                        if model_index == 0:\n                            show_null = True\n                        else:\n                            continue\n                    elif self.recommended_model == model:\n                        pass\n                    else:\n                        continue\n                else:\n                    if model_index == 0:\n                        show_null = True\n                    else:\n                        continue\n            d[\"dataset_index\"].append(dataset_index)\n            d[\"doses_dropped\"].append(self.doses_dropped)\n            model._to_df(d, model_index, show_null)",
    "docstring": "Save a single session to an ordered dictionary."
  },
  {
    "code": "def merge(file, feature_layers):\n    tile = VectorTile(extents)\n    for layer in feature_layers:\n        tile.addFeatures(layer['features'], layer['name'])\n    tile.complete()\n    data = tile.out.SerializeToString()\n    file.write(struct.pack(\">I\", len(data)))\n    file.write(data)",
    "docstring": "Retrieve a list of OSciMap4 tile responses and merge them into one.\n\n        get_tiles() retrieves data and performs basic integrity checks."
  },
  {
    "code": "def format_name(subject):\n    if isinstance(subject, x509.Name):\n        subject = [(OID_NAME_MAPPINGS[s.oid], s.value) for s in subject]\n    return '/%s' % ('/'.join(['%s=%s' % (force_text(k), force_text(v)) for k, v in subject]))",
    "docstring": "Convert a subject into the canonical form for distinguished names.\n\n    This function does not take care of sorting the subject in any meaningful order.\n\n    Examples::\n\n        >>> format_name([('CN', 'example.com'), ])\n        '/CN=example.com'\n        >>> format_name([('CN', 'example.com'), ('O', \"My Organization\"), ])\n        '/CN=example.com/O=My Organization'"
  },
  {
    "code": "def draw(self):\r\n        if not self.visible:\r\n            return\r\n        self.window.blit(self.textImage, self.loc)",
    "docstring": "Draws the current text in the window"
  },
  {
    "code": "def _parse_args(func, variables, annotations=None):\n    arg_read_var = []\n    for arg_name, anno in (annotations or func.__annotations__).items():\n        if arg_name == 'return':\n            continue\n        var, read = _parse_arg(func, variables, arg_name, anno)\n        arg = Argument(name=arg_name, read=read)\n        arg_read_var.append((arg, var))\n    return arg_read_var",
    "docstring": "Return a list of arguments with the variable it reads.\n\n    NOTE: Multiple arguments may read the same variable."
  },
  {
    "code": "def fix_reference_url(url):\n    new_url = url\n    new_url = fix_url_bars_instead_of_slashes(new_url)\n    new_url = fix_url_add_http_if_missing(new_url)\n    new_url = fix_url_replace_tilde(new_url)\n    try:\n        rfc3987.parse(new_url, rule=\"URI\")\n        return new_url\n    except ValueError:\n        return url",
    "docstring": "Used to parse an incorect url to try to fix it with the most common ocurrences for errors.\n    If the fixed url is still incorrect, it returns ``None``.\n\n    Returns:\n        String containing the fixed url or the original one if it could not be fixed."
  },
  {
    "code": "def proxy(self, request, original_target_route, presenter_name, **kwargs):\n\t\taction_kwargs = kwargs.copy()\n\t\taction_name = 'index'\n\t\tif 'action' in action_kwargs:\n\t\t\taction_name = action_kwargs['action']\n\t\t\taction_kwargs.pop('action')\n\t\toriginal_route = original_target_route.route()\n\t\toriginal_route_map = original_target_route.route_map()\n\t\ttarget_route = WWebTargetRoute(\n\t\t\tpresenter_name, action_name, original_route, original_route_map, **action_kwargs\n\t\t)\n\t\treturn self.execute(request, target_route)",
    "docstring": "Execute the given presenter as a target for the given client request\n\n\t\t:param request: original client request\n\t\t:param original_target_route: previous target route\n\t\t:param presenter_name: target presenter name\n\t\t:param kwargs: presenter arguments\n\t\t:return: WWebResponseProto"
  },
  {
    "code": "def get_list_columns(self):\n        url = self.build_url(self._endpoints.get('get_list_columns'))\n        response = self.con.get(url)\n        if not response:\n            return []\n        data = response.json()\n        return [self.list_column_constructor(parent=self, **{self._cloud_data_key: column})\n                for column in data.get('value', [])]",
    "docstring": "Returns the sharepoint list columns"
  },
  {
    "code": "def pop(self):\n        method_frame, header, body = self.server.basic_get(queue=self.key)\n        if body:\n            return self._decode_request(body)",
    "docstring": "Pop a request"
  },
  {
    "code": "def should_exclude(self, filename) -> bool:\n        for skip_glob in self.skip_globs:\n            if self.filename_matches_glob(filename, skip_glob):\n                return True\n        return False",
    "docstring": "Should we exclude this file from consideration?"
  },
  {
    "code": "def get_forces(self):\n        forces = []\n        for f in self.service.request('GET', 'forces'):\n            forces.append(Force(self, id=f['id'], name=f['name']))\n        return forces",
    "docstring": "Get a list of all police forces. Uses the forces_ API call.\n\n        .. _forces: https://data.police.uk/docs/method/forces/\n\n        :rtype: list\n        :return: A list of :class:`forces.Force` objects (one for each police\n                 force represented in the API)"
  },
  {
    "code": "def get_geostationary_mask(area):\n    h = area.proj_dict['h']\n    xmax, ymax = get_geostationary_angle_extent(area)\n    xmax *= h\n    ymax *= h\n    x, y = area.get_proj_coords_dask()\n    return ((x / xmax) ** 2 + (y / ymax) ** 2) <= 1",
    "docstring": "Compute a mask of the earth's shape as seen by a geostationary satellite\n\n    Args:\n        area (pyresample.geometry.AreaDefinition) : Corresponding area\n                                                    definition\n\n    Returns:\n        Boolean mask, True inside the earth's shape, False outside."
  },
  {
    "code": "def bool_from_string(value):\n    if isinstance(value, six.string_types):\n        value = six.text_type(value)\n    else:\n        msg = \"Unable to interpret non-string value '%s' as boolean\" % (value)\n        raise ValueError(msg)\n    value = value.strip().lower()\n    if value in ['y', 'yes', 'true', 't', 'on']:\n        return True\n    elif value in ['n', 'no', 'false', 'f', 'off']:\n        return False\n    msg = \"Unable to interpret string value '%s' as boolean\" % (value)\n    raise ValueError(msg)",
    "docstring": "Interpret string value as boolean.\n\n    Returns True if value translates to True otherwise False."
  },
  {
    "code": "def multiget(self, keys, r=None, pr=None, timeout=None,\n                 basic_quorum=None, notfound_ok=None,\n                 head_only=False):\n        bkeys = [(self.bucket_type.name, self.name, key) for key in keys]\n        return self._client.multiget(bkeys, r=r, pr=pr, timeout=timeout,\n                                     basic_quorum=basic_quorum,\n                                     notfound_ok=notfound_ok,\n                                     head_only=head_only)",
    "docstring": "Retrieves a list of keys belonging to this bucket in parallel.\n\n        :param keys: the keys to fetch\n        :type keys: list\n        :param r: R-Value for the requests (defaults to bucket's R)\n        :type r: integer\n        :param pr: PR-Value for the requests (defaults to bucket's PR)\n        :type pr: integer\n        :param timeout: a timeout value in milliseconds\n        :type timeout: int\n        :param basic_quorum: whether to use the \"basic quorum\" policy\n           for not-founds\n        :type basic_quorum: bool\n        :param notfound_ok: whether to treat not-found responses as successful\n        :type notfound_ok: bool\n        :param head_only: whether to fetch without value, so only metadata\n           (only available on PB transport)\n        :type head_only: bool\n        :rtype: list of :class:`RiakObjects <riak.riak_object.RiakObject>`,\n            :class:`Datatypes <riak.datatypes.Datatype>`, or tuples of\n            bucket_type, bucket, key, and the exception raised on fetch"
  },
  {
    "code": "def colorize(string, stack):\n  codes = optimize(stack)\n  if len(codes):\n    prefix = SEQ % ';'.join(map(str, codes))\n    suffix = SEQ % STYLE.reset\n    return prefix + string + suffix\n  else:\n    return string",
    "docstring": "Apply optimal ANSI escape sequences to the string."
  },
  {
    "code": "def get_missing_languages(self, field_name, db_table):\n        db_table_fields = self.get_table_fields(db_table)\n        for lang_code in AVAILABLE_LANGUAGES:\n            if build_localized_fieldname(field_name, lang_code) not in db_table_fields:\n                yield lang_code",
    "docstring": "Gets only missings fields."
  },
  {
    "code": "def safe_cast_to_index(array: Any) -> pd.Index:\n    if isinstance(array, pd.Index):\n        index = array\n    elif hasattr(array, 'to_index'):\n        index = array.to_index()\n    else:\n        kwargs = {}\n        if hasattr(array, 'dtype') and array.dtype.kind == 'O':\n            kwargs['dtype'] = object\n        index = pd.Index(np.asarray(array), **kwargs)\n    return _maybe_cast_to_cftimeindex(index)",
    "docstring": "Given an array, safely cast it to a pandas.Index.\n\n    If it is already a pandas.Index, return it unchanged.\n\n    Unlike pandas.Index, if the array has dtype=object or dtype=timedelta64,\n    this function will not attempt to do automatic type conversion but will\n    always return an index with dtype=object."
  },
  {
    "code": "def _to_key(d):\n        as_str = json.dumps(d, sort_keys=True)\n        return as_str.replace('\"{{', '{{').replace('}}\"', '}}')",
    "docstring": "Convert dict to str and enable Jinja2 template syntax."
  },
  {
    "code": "def encode(value, encoding='utf-8', encoding_errors='strict'):\n    if isinstance(value, bytes):\n        return value\n    if not isinstance(value, basestring):\n        value = str(value)\n    if isinstance(value, unicode):\n        value = value.encode(encoding, encoding_errors)\n    return value",
    "docstring": "Return a bytestring representation of the value."
  },
  {
    "code": "def validate(self, *args, **kwargs):\n        return super(ParameterValidator, self)._validate(*args, **kwargs)",
    "docstring": "Validate a parameter dict against a parameter schema from an ocrd-tool.json\n\n        Args:\n            obj (dict):\n            schema (dict):"
  },
  {
    "code": "def add_val(self, val):\n        if not isinstance(val, type({})):\n            raise ValueError(type({}))\n        self.read()\n        self.config.update(val)\n        self.save()",
    "docstring": "add value in form of dict"
  },
  {
    "code": "def set_log_type_flags(self, logType, stdoutFlag, fileFlag):\n        assert logType in self.__logTypeStdoutFlags.keys(), \"logType '%s' not defined\" %logType\n        assert isinstance(stdoutFlag, bool), \"stdoutFlag must be boolean\"\n        assert isinstance(fileFlag, bool), \"fileFlag must be boolean\"\n        self.__logTypeStdoutFlags[logType] = stdoutFlag\n        self.__logTypeFileFlags[logType]   = fileFlag",
    "docstring": "Set a defined log type flags.\n\n        :Parameters:\n           #. logType (string): A defined logging type.\n           #. stdoutFlag (boolean): Whether to log to the standard output stream.\n           #. fileFlag (boolean): Whether to log to to file."
  },
  {
    "code": "def get_attribute(json, attr):\n    res = [json[entry][attr] for entry, _ in enumerate(json)]\n    logger.debug('{0}s (from JSON):\\n{1}'.format(attr, res))\n    return res",
    "docstring": "Gets the values of an attribute from JSON\n\n    Args:\n        json: JSON data as a list of dict dates, where the keys are\n            the raw market statistics.\n        attr: String of attribute in JSON file to collect.\n\n    Returns:\n        List of values of specified attribute from JSON"
  },
  {
    "code": "def new_children(self, **kwargs):\n        for k, v in kwargs.items():\n            self.new_child(k, v)\n        return self",
    "docstring": "Create new children from kwargs"
  },
  {
    "code": "def query(self, query_data, k=10, queue_size=5.0):\n        query_data = np.asarray(query_data).astype(np.float32)\n        init = initialise_search(\n            self._rp_forest,\n            self._raw_data,\n            query_data,\n            int(k * queue_size),\n            self._random_init,\n            self._tree_init,\n            self.rng_state,\n        )\n        result = self._search(\n            self._raw_data,\n            self._search_graph.indptr,\n            self._search_graph.indices,\n            init,\n            query_data,\n        )\n        indices, dists = deheap_sort(result)\n        return indices[:, :k], dists[:, :k]",
    "docstring": "Query the training data for the k nearest neighbors\n\n        Parameters\n        ----------\n        query_data: array-like, last dimension self.dim\n            An array of points to query\n\n        k: integer (default = 10)\n            The number of nearest neighbors to return\n\n        queue_size: float (default 5.0)\n            The multiplier of the internal search queue. This controls the\n            speed/accuracy tradeoff. Low values will search faster but with\n            more approximate results. High values will search more\n            accurately, but will require more computation to do so. Values\n            should generally be in the range 1.0 to 10.0.\n\n        Returns\n        -------\n        indices, distances: array (n_query_points, k), array (n_query_points, k)\n            The first array, ``indices``, provides the indices of the data\n            points in the training set that are the nearest neighbors of\n            each query point. Thus ``indices[i, j]`` is the index into the\n            training data of the jth nearest neighbor of the ith query points.\n\n            Similarly ``distances`` provides the distances to the neighbors\n            of the query points such that ``distances[i, j]`` is the distance\n            from the ith query point to its jth nearest neighbor in the\n            training data."
  },
  {
    "code": "def register_interaction(key=None):\n    def wrap(interaction):\n        name = key if key is not None else interaction.__module__ + \\\n            interaction.__name__\n        interaction.types[name] = interaction\n        return interaction\n    return wrap",
    "docstring": "Decorator registering an interaction class in the registry.\n\n    If no key is provided, the class name is used as a key. A key is provided\n    for each core bqplot interaction type so that the frontend can use this\n    key regardless of the kernal language."
  },
  {
    "code": "def value(self):\n        try:\n            res = self.properties.device.properties.network.read(\n                \"{} {} {} presentValue\".format(\n                    self.properties.device.properties.address,\n                    self.properties.type,\n                    str(self.properties.address),\n                )\n            )\n            self._trend(res)\n        except Exception:\n            raise Exception(\"Problem reading : {}\".format(self.properties.name))\n        if res == \"inactive\":\n            self._key = 0\n            self._boolKey = False\n        else:\n            self._key = 1\n            self._boolKey = True\n        return res",
    "docstring": "Read the value from BACnet network"
  },
  {
    "code": "def opendocs(where='index', how='default'):\n    import webbrowser\n    docs_dir = os.path.join(\n        os.path.dirname(os.path.abspath(__file__)),\n        'docs')\n    index = os.path.join(docs_dir, '_build/html/%s.html' % where)\n    builddocs('html')\n    url = 'file://%s' % os.path.abspath(index)\n    if how in ('d', 'default'):\n        webbrowser.open(url)\n    elif how in ('t', 'tab'):\n        webbrowser.open_new_tab(url)\n    elif how in ('n', 'w', 'window'):\n        webbrowser.open_new(url)",
    "docstring": "Rebuild documentation and opens it in your browser.\n\n    Use the first argument to specify how it should be opened:\n\n        `d` or `default`: Open in new tab or new window, using the default\n        method of your browser.\n\n        `t` or `tab`: Open documentation in new tab.\n\n        `n`, `w` or `window`: Open documentation in new window."
  },
  {
    "code": "def _get_title(self, prop, main_infos, info_dict):\n        result = main_infos.get('label')\n        if result is None:\n            result = info_dict.get('colanderalchemy', {}).get('title')\n        if result is None:\n            result = prop.key\n        return result",
    "docstring": "Return the title configured as in colanderalchemy"
  },
  {
    "code": "def _ReferenceFromSerialized(serialized):\n  if not isinstance(serialized, basestring):\n    raise TypeError('serialized must be a string; received %r' % serialized)\n  elif isinstance(serialized, unicode):\n    serialized = serialized.encode('utf8')\n  return entity_pb.Reference(serialized)",
    "docstring": "Construct a Reference from a serialized Reference."
  },
  {
    "code": "def set_text(self, text=\"YEAH.\"):\n        s = str(text)\n        if not s == self.get_text(): self._widget.setText(str(text))\n        return self",
    "docstring": "Sets the current value of the text box."
  },
  {
    "code": "def set_computer_name(name):\n    if six.PY2:\n        name = _to_unicode(name)\n    if windll.kernel32.SetComputerNameExW(\n            win32con.ComputerNamePhysicalDnsHostname, name):\n        ret = {'Computer Name': {'Current': get_computer_name()}}\n        pending = get_pending_computer_name()\n        if pending not in (None, False):\n            ret['Computer Name']['Pending'] = pending\n        return ret\n    return False",
    "docstring": "Set the Windows computer name\n\n    Args:\n\n        name (str):\n            The new name to give the computer. Requires a reboot to take effect.\n\n    Returns:\n        dict:\n            Returns a dictionary containing the old and new names if successful.\n            ``False`` if not.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'minion-id' system.set_computer_name 'DavesComputer'"
  },
  {
    "code": "async def delete(\n        self, name: str, *, force: bool = False, noprune: bool = False\n    ) -> List:\n        params = {\"force\": force, \"noprune\": noprune}\n        response = await self.docker._query_json(\n            \"images/{name}\".format(name=name), \"DELETE\", params=params\n        )\n        return response",
    "docstring": "Remove an image along with any untagged parent\n        images that were referenced by that image\n\n        Args:\n            name: name/id of the image to delete\n            force: remove the image even if it is being used\n                   by stopped containers or has other tags\n            noprune: don't delete untagged parent images\n\n        Returns:\n            List of deleted images"
  },
  {
    "code": "def rename_db_ref(stmts_in, ns_from, ns_to, **kwargs):\n    logger.info('Remapping \"%s\" to \"%s\" in db_refs on %d statements...' %\n                (ns_from, ns_to, len(stmts_in)))\n    stmts_out = [deepcopy(st) for st in stmts_in]\n    for stmt in stmts_out:\n        for agent in stmt.agent_list():\n            if agent is not None and ns_from in agent.db_refs:\n                agent.db_refs[ns_to] = agent.db_refs.pop(ns_from)\n    dump_pkl = kwargs.get('save')\n    if dump_pkl:\n        dump_statements(stmts_out, dump_pkl)\n    return stmts_out",
    "docstring": "Rename an entry in the db_refs of each Agent.\n\n    This is particularly useful when old Statements in pickle files\n    need to be updated after a namespace was changed such as\n    'BE' to 'FPLX'.\n\n    Parameters\n    ----------\n    stmts_in : list[indra.statements.Statement]\n        A list of statements whose Agents' db_refs need to be changed\n    ns_from : str\n        The namespace identifier to replace\n    ns_to : str\n        The namespace identifier to replace to\n    save : Optional[str]\n        The name of a pickle file to save the results (stmts_out) into.\n\n    Returns\n    -------\n    stmts_out : list[indra.statements.Statement]\n        A list of Statements with Agents' db_refs changed."
  },
  {
    "code": "def page_should_contain_element(self, locator, loglevel='INFO'):\r\n        if not self._is_element_present(locator):\r\n            self.log_source(loglevel)\r\n            raise AssertionError(\"Page should have contained element '%s' \"\r\n                                 \"but did not\" % locator)\r\n        self._info(\"Current page contains element '%s'.\" % locator)",
    "docstring": "Verifies that current page contains `locator` element.\r\n\r\n        If this keyword fails, it automatically logs the page source\r\n        using the log level specified with the optional `loglevel` argument.\r\n        Giving `NONE` as level disables logging."
  },
  {
    "code": "def transform_using_this_method(original_sample):\n    new_sample = original_sample.copy()\n    new_data = new_sample.data\n    new_data['Y2-A'] = log(new_data['Y2-A'])\n    new_data = new_data.dropna()\n    new_sample.data = new_data\n    return new_sample",
    "docstring": "This function implements a log transformation on the data."
  },
  {
    "code": "def snapshot_agents(self, force=False):\n        for agent in self._agents:\n            agent.check_if_should_snapshot(force)",
    "docstring": "snapshot agents if number of entries from last snapshot if greater\n        than 1000. Use force=True to override."
  },
  {
    "code": "def react_to_event(self, event):\n        if not react_to_event(self.view, self.view.editor, event):\n            return False\n        if not rafcon.gui.singleton.state_machine_manager_model.selected_state_machine_id == \\\n                self.model.state_machine.state_machine_id:\n            return False\n        return True",
    "docstring": "Check whether the given event should be handled\n\n        Checks, whether the editor widget has the focus and whether the selected state machine corresponds to the\n        state machine of this editor.\n\n        :param event: GTK event object\n        :return: True if the event should be handled, else False\n        :rtype: bool"
  },
  {
    "code": "def _pidExists(pid):\n        assert pid > 0\n        try:\n            os.kill(pid, 0)\n        except OSError as err:\n            if err.errno == errno.ESRCH:\n                return False\n            else:\n                raise\n        else:\n            return True",
    "docstring": "This will return True if the process associated with pid is still running on the machine.\n        This is based on stackoverflow question 568271.\n\n        :param int pid: ID of the process to check for\n        :return: True/False\n        :rtype: bool"
  },
  {
    "code": "def get_user_subadmin_groups(self, user_name):\n        res = self._make_ocs_request(\n            'GET',\n            self.OCS_SERVICE_CLOUD,\n            'users/' + user_name + '/subadmins',\n        )\n        if res.status_code == 200:\n            tree = ET.fromstring(res.content)\n            self._check_ocs_status(tree, [100])\n            groups = tree.find('data')\n            return groups\n        raise HTTPResponseError(res)",
    "docstring": "Get a list of subadmin groups associated to a user.\n\n        :param user_name:  name of user\n        :returns: list of subadmin groups\n        :raises: HTTPResponseError in case an HTTP error status was returned"
  },
  {
    "code": "def set(self, varname, value, idx=0, units=None):\n        if not varname in self.mapping.vars:\n            raise fgFDMError('Unknown variable %s' % varname)\n        if idx >= self.mapping.vars[varname].arraylength:\n            raise fgFDMError('index of %s beyond end of array idx=%u arraylength=%u' % (\n                varname, idx, self.mapping.vars[varname].arraylength))\n        if units:\n            value = self.convert(value, units, self.mapping.vars[varname].units)\n        if math.isinf(value) or math.isnan(value) or math.fabs(value) > 3.4e38:\n            value = 0\n        self.values[self.mapping.vars[varname].index + idx] = value",
    "docstring": "set a variable value"
  },
  {
    "code": "def scan(self, t, dt=None, aggfunc=None):\n        idx = (np.abs(self.index - t)).argmin()\n        if dt is None:\n            mz_abn = self.values[idx, :].copy()\n        else:\n            en_idx = (np.abs(self.index - t - dt)).argmin()\n            idx, en_idx = min(idx, en_idx), max(idx, en_idx)\n            if aggfunc is None:\n                mz_abn = self.values[idx:en_idx + 1, :].copy().sum(axis=0)\n            else:\n                mz_abn = aggfunc(self.values[idx:en_idx + 1, :].copy())\n        if isinstance(mz_abn, scipy.sparse.spmatrix):\n            mz_abn = mz_abn.toarray()[0]\n        return Scan(self.columns, mz_abn)",
    "docstring": "Returns the spectrum from a specific time.\n\n        Parameters\n        ----------\n        t : float\n        dt : float"
  },
  {
    "code": "def scrape(url, params=None, user_agent=None):\n    headers = {}\n    if user_agent:\n        headers['User-Agent'] = user_agent\n    data = params and six.moves.urllib.parse.urlencode(params) or None\n    req = six.moves.urllib.request.Request(url, data=data, headers=headers)\n    f = six.moves.urllib.request.urlopen(req)\n    text = f.read()\n    f.close()\n    return text",
    "docstring": "Scrape a URL optionally with parameters.\n    This is effectively a wrapper around urllib2.urlopen."
  },
  {
    "code": "async def workerType(self, *args, **kwargs):\n        return await self._makeApiCall(self.funcinfo[\"workerType\"], *args, **kwargs)",
    "docstring": "Get Worker Type\n\n        Retrieve a copy of the requested worker type definition.\n        This copy contains a lastModified field as well as the worker\n        type name.  As such, it will require manipulation to be able to\n        use the results of this method to submit date to the update\n        method.\n\n        This method gives output: ``http://schemas.taskcluster.net/aws-provisioner/v1/get-worker-type-response.json#``\n\n        This method is ``stable``"
  },
  {
    "code": "def register(self, name, asymmetric=False):\n        def register_func(func):\n            if asymmetric:\n                self._asymmetric.append(name)\n            self.store[name] = func\n            return func\n        return register_func",
    "docstring": "Decorator for registering a measure with PyPhi.\n\n        Args:\n            name (string): The name of the measure.\n\n        Keyword Args:\n            asymmetric (boolean): ``True`` if the measure is asymmetric."
  },
  {
    "code": "def stop(self):\n        res = self.send_request('manager/stop', post=True)\n        if res.status_code != 200:\n            raise UnexpectedResponse(\n                'Attempted to stop manager. {res_code}: {res_text}'.format(\n                    res_code=res.status_code,\n                    res_text=res.text,\n                )\n            )\n        if settings.VERBOSITY >= verbosity.PROCESS_STOP:\n            print('Stopped {}'.format(self.get_name()))\n        time.sleep(0.05)",
    "docstring": "If the manager is running, tell it to stop its process"
  },
  {
    "code": "def _extractErrorString(request):\n        errorStr = \"\"\n        tag = None\n        try:\n            root = ET.fromstring(request.text.encode('utf-8'))\n            tag = root[0][0]\n        except:\n            return errorStr\n        for element in tag.getiterator():\n            tagName = element.tag.lower()\n            if tagName.endswith(\"string\"):\n                errorStr += element.text + \" \"\n            elif tagName.endswith(\"description\"):\n                errorStr += element.text + \" \"\n        return errorStr",
    "docstring": "Extract error string from a failed UPnP call.\n\n        :param request: the failed request result\n        :type request: requests.Response\n        :return: an extracted error text or empty str\n        :rtype: str"
  },
  {
    "code": "def getEmailTemplate(request):\r\n    if request.method != 'POST':\r\n        return HttpResponse(_('Error, no POST data.'))\r\n    if not hasattr(request,'user'):\r\n        return HttpResponse(_('Error, not authenticated.'))\r\n    template_id = request.POST.get('template')\r\n    if not template_id:\r\n        return HttpResponse(_(\"Error, no template ID provided.\"))\r\n    try:\r\n        this_template = EmailTemplate.objects.get(id=template_id)\r\n    except ObjectDoesNotExist:\r\n        return HttpResponse(_(\"Error getting template.\"))\r\n    if this_template.groupRequired and this_template.groupRequired not in request.user.groups.all():\r\n        return HttpResponse(_(\"Error, no permission to access this template.\"))\r\n    if this_template.hideFromForm:\r\n        return HttpResponse(_(\"Error, no permission to access this template.\"))\r\n    return JsonResponse({\r\n        'subject': this_template.subject,\r\n        'content': this_template.content,\r\n        'html_content': this_template.html_content,\r\n        'richTextChoice': this_template.richTextChoice,\r\n    })",
    "docstring": "This function handles the Ajax call made when a user wants a specific email template"
  },
  {
    "code": "def update_text(self, mapping):\n        found = False\n        for node in self._page.iter(\"*\"):\n            if node.text or node.tail:\n                for old, new in mapping.items():\n                    if node.text and old in node.text:\n                        node.text = node.text.replace(old, new)\n                        found = True\n                    if node.tail and old in node.tail:\n                        node.tail = node.tail.replace(old, new)\n                        found = True\n        if not found:\n            raise KeyError(\"Updating text failed with mapping:{}\".format(mapping))",
    "docstring": "Iterate over nodes, replace text with mapping"
  },
  {
    "code": "def style(theme=None, context='paper', grid=True, gridlines=u'-', ticks=False, spines=True, fscale=1.2, figsize=(8., 7.)):\n    rcdict = set_context(context=context, fscale=fscale, figsize=figsize)\n    if theme is None:\n        theme = infer_theme()\n    set_style(rcdict, theme=theme, grid=grid, gridlines=gridlines, ticks=ticks, spines=spines)",
    "docstring": "main function for styling matplotlib according to theme\n\n    ::Arguments::\n        theme (str): 'oceans16', 'grade3', 'chesterish', 'onedork', 'monokai', 'solarizedl', 'solarizedd'. If no theme name supplied the currently installed notebook theme will be used.\n\n        context (str): 'paper' (Default), 'notebook', 'talk', or 'poster'\n\n        grid (bool): removes axis grid lines if False\n\n        gridlines (str): set grid linestyle (e.g., '--' for dashed grid)\n\n        ticks (bool): make major x and y ticks visible\n\n        spines (bool): removes x (bottom) and y (left) axis spines if False\n\n        fscale (float): scale font size for axes labels, legend, etc.\n\n        figsize (tuple): default figure size of matplotlib figures"
  },
  {
    "code": "def is_subdir(a, b):\n    a, b = map(os.path.abspath, [a, b])\n    return os.path.commonpath([a, b]) == b",
    "docstring": "Return true if a is a subdirectory of b"
  },
  {
    "code": "def _state_invalid(self):\n        for statemanager, conditions in self.statetransition.transitions.items():\n            current_state = getattr(self.obj, statemanager.propname)\n            if conditions['from'] is None:\n                state_valid = True\n            else:\n                mstate = conditions['from'].get(current_state)\n                state_valid = mstate and mstate(self.obj)\n            if state_valid and conditions['if']:\n                state_valid = all(v(self.obj) for v in conditions['if'])\n            if not state_valid:\n                return statemanager, current_state, statemanager.lenum.get(current_state)",
    "docstring": "If the state is invalid for the transition, return details on what didn't match\n\n        :return: Tuple of (state manager, current state, label for current state)"
  },
  {
    "code": "def getfieldindex(data, commdct, objkey, fname):\n    objindex = data.dtls.index(objkey)\n    objcomm = commdct[objindex]\n    for i_index, item in enumerate(objcomm):\n        try:\n            if item['field'] == [fname]:\n                break\n        except KeyError as err:\n            pass\n    return i_index",
    "docstring": "given objkey and fieldname, return its index"
  },
  {
    "code": "def __parseParameters(self):\n        self.__parameters = []\n        for parameter in self.__data['parameters']:\n            self.__parameters.append(Parameter(parameter))",
    "docstring": "Parses the parameters of data."
  },
  {
    "code": "def validate(self):\n        msg = list()\n        previously_seen = set()\n        currently_seen = set([1])\n        problemset = set()\n        while currently_seen:\n            node = currently_seen.pop()\n            if node in previously_seen:\n                problemset.add(node)\n            else:\n                previously_seen.add(node)\n                self.add_descendants(node, currently_seen)\n        unreachable = self.all_nodes - previously_seen\n        if unreachable:\n            msg.append(\"%d unreachable nodes: \"%len(unreachable))\n            for node in unreachable:\n                msg.append(str(node))\n        if problemset:\n            msg.append(\"Loop involving %d nodes\"%len(problemset))\n            for node in problemset:\n                msg.append(str(node))\n        if msg:\n            return msg\n        else:\n            return True",
    "docstring": "Simulataneously checks for loops and unreachable nodes"
  },
  {
    "code": "def _cast_to_pod(val):\n  bools = {\"True\": True, \"False\": False}\n  if val in bools:\n    return bools[val]\n  try:\n    return int(val)\n  except ValueError:\n    try:\n      return float(val)\n    except ValueError:\n      return tf.compat.as_text(val)",
    "docstring": "Try cast to int, float, bool, str, in that order."
  },
  {
    "code": "def add_model(self, model):\n        if model.identity not in self._models.keys():\n            self._models[model.identity] = model\n        else:\n            raise ValueError(\"{} has already been defined\".format(model.identity))",
    "docstring": "Add a model to the document"
  },
  {
    "code": "def get_full_url(self, url):\n        request = Request('GET', url)\n        preparedrequest = self.session.prepare_request(request)\n        return preparedrequest.url",
    "docstring": "Get full url including any additional parameters\n\n        Args:\n            url (str): URL for which to get full url\n\n        Returns:\n            str: Full url including any additional parameters"
  },
  {
    "code": "def os_info():\n    stype = \"\"\n    slack, ver = slack_ver()\n    mir = mirror()\n    if mir:\n        if \"current\" in mir:\n            stype = \"Current\"\n        else:\n            stype = \"Stable\"\n    info = (\n        \"User: {0}\\n\"\n        \"OS: {1}\\n\"\n        \"Version: {2}\\n\"\n        \"Type: {3}\\n\"\n        \"Arch: {4}\\n\"\n        \"Kernel: {5}\\n\"\n        \"Packages: {6}\".format(getpass.getuser(), slack, ver, stype,\n                               os.uname()[4], os.uname()[2], ins_packages()))\n    return info",
    "docstring": "Get OS info"
  },
  {
    "code": "def downsample_with_striding(array, factor):\n    return array[tuple(np.s_[::f] for f in factor)]",
    "docstring": "Downsample x by factor using striding.\n\n    @return: The downsampled array, of the same type as x."
  },
  {
    "code": "def search_text(self, text, encoding = \"utf-16le\",\n                                caseSensitive = False,\n                                minAddr = None,\n                                maxAddr = None):\n        pattern = TextPattern(text, encoding, caseSensitive)\n        matches = Search.search_process(self, pattern, minAddr, maxAddr)\n        for addr, size, data in matches:\n            yield addr, data",
    "docstring": "Search for the given text within the process memory.\n\n        @type  text: str or compat.unicode\n        @param text: Text to search for.\n\n        @type  encoding: str\n        @param encoding: (Optional) Encoding for the text parameter.\n            Only used when the text to search for is a Unicode string.\n            Don't change unless you know what you're doing!\n\n        @type  caseSensitive: bool\n        @param caseSensitive: C{True} of the search is case sensitive,\n            C{False} otherwise.\n\n        @type  minAddr: int\n        @param minAddr: (Optional) Start the search at this memory address.\n\n        @type  maxAddr: int\n        @param maxAddr: (Optional) Stop the search at this memory address.\n\n        @rtype:  iterator of tuple( int, str )\n        @return: An iterator of tuples. Each tuple contains the following:\n             - The memory address where the pattern was found.\n             - The text that matches the pattern.\n\n        @raise WindowsError: An error occurred when querying or reading the\n            process memory."
  },
  {
    "code": "def join(self, *args):\n        call_args = list(args)\n        joiner = call_args.pop(0)\n        self.random.shuffle(call_args)\n        return joiner.join(call_args)",
    "docstring": "Returns the arguments in the list joined by STR.\n            FIRST,JOIN_BY,ARG_1,...,ARG_N\n\n        %{JOIN: ,A,...,F} -> 'A B C ... F'"
  },
  {
    "code": "def is_processed(self, db_versions):\n        return self.number in (v.number for v in db_versions if v.date_done)",
    "docstring": "Check if version is already applied in the database.\n\n        :param db_versions:"
  },
  {
    "code": "def load():\n    plugins = []\n    for filename in os.listdir(PLUGINS_PATH):\n        if not filename.endswith(\".py\") or filename.startswith(\"_\"):\n            continue\n        if not os.path.isfile(os.path.join(PLUGINS_PATH, filename)):\n            continue\n        plugin = filename[:-3]\n        if plugin in FAILED_PLUGINS:\n            continue\n        try:\n            __import__(PLUGINS.__name__, {}, {}, [plugin])\n            plugins.append(plugin)\n            log.debug(\"Successfully imported {0} plugin\".format(plugin))\n        except (ImportError, SyntaxError) as error:\n            message = \"Failed to import {0} plugin ({1})\".format(plugin, error)\n            if Config().sections(kind=plugin):\n                log.warn(message)\n            else:\n                log.debug(message)\n            FAILED_PLUGINS.append(plugin)\n    return plugins",
    "docstring": "Check available plugins and attempt to import them"
  },
  {
    "code": "def get_prefix_envname(self, name, log=False):\n        prefix = None\n        if name == 'root':\n            prefix = self.ROOT_PREFIX\n        envs = self.get_envs()\n        for p in envs:\n            if basename(p) == name:\n                prefix = p\n        return prefix",
    "docstring": "Return full prefix path of environment defined by `name`."
  },
  {
    "code": "def check_config(config):\n    essential_keys = ['number_earthquakes']\n    for key in essential_keys:\n        if key not in config:\n            raise ValueError('For Kijko Nonparametric Gaussian the key %s '\n                             'needs to be set in the configuation' % key)\n    if config.get('tolerance', 0.0) <= 0.0:\n        config['tolerance'] = 0.05\n    if config.get('maximum_iterations', 0) < 1:\n        config['maximum_iterations'] = 100\n    if config.get('number_samples', 0) < 2:\n        config['number_samples'] = 51\n    return config",
    "docstring": "Check config file inputs and overwrite bad values with the defaults"
  },
  {
    "code": "def get(self, key):\n        upload = None\n        files_states = self.backend.get(key)\n        files = MultiValueDict()\n        if files_states:\n            for name, state in files_states.items():\n                f = BytesIO()\n                f.write(state['content'])\n                if state['size'] > settings.FILE_UPLOAD_MAX_MEMORY_SIZE:\n                    upload = TemporaryUploadedFile(\n                        state['name'],\n                        state['content_type'],\n                        state['size'],\n                        state['charset'],\n                    )\n                    upload.file = f\n                else:\n                    f = BytesIO()\n                    f.write(state['content'])\n                    upload = InMemoryUploadedFile(\n                        file=f,\n                        field_name=name,\n                        name=state['name'],\n                        content_type=state['content_type'],\n                        size=state['size'],\n                        charset=state['charset'],\n                    )\n                files[name] = upload\n                upload.file.seek(0)\n        return files",
    "docstring": "Regenerates a MultiValueDict instance containing the files related to all file states\n            stored for the given key."
  },
  {
    "code": "def rename_tabs_after_change(self, given_name):\r\n        client = self.get_current_client()\r\n        repeated = False\r\n        for cl in self.get_clients():\r\n            if id(client) != id(cl) and given_name == cl.given_name:\r\n                repeated = True\r\n                break\r\n        if client.allow_rename and not u'/' in given_name and not repeated:\r\n            self.rename_client_tab(client, given_name)\r\n        else:\r\n            self.rename_client_tab(client, None)\r\n        if client.allow_rename and not u'/' in given_name and not repeated:\r\n            for cl in self.get_related_clients(client):\r\n                self.rename_client_tab(cl, given_name)",
    "docstring": "Rename tabs after a change in name."
  },
  {
    "code": "def longest_run(da, dim='time'):\n    d = rle(da, dim=dim)\n    rl_long = d.max(dim=dim)\n    return rl_long",
    "docstring": "Return the length of the longest consecutive run of True values.\n\n        Parameters\n        ----------\n        arr : N-dimensional array (boolean)\n          Input array\n        dim : Xarray dimension (default = 'time')\n          Dimension along which to calculate consecutive run\n\n        Returns\n        -------\n        N-dimensional array (int)\n          Length of longest run of True values along dimension"
  },
  {
    "code": "def get_piis(query_str):\n    dates = range(1960, datetime.datetime.now().year)\n    all_piis = flatten([get_piis_for_date(query_str, date) for date in dates])\n    return all_piis",
    "docstring": "Search ScienceDirect through the API for articles and return PIIs.\n\n    Note that ScienceDirect has a limitation in which a maximum of 6,000\n    PIIs can be retrieved for a given search and therefore this call is\n    internally broken up into multiple queries by a range of years and the\n    results are combined.\n\n    Parameters\n    ----------\n    query_str : str\n        The query string to search with\n\n    Returns\n    -------\n    piis : list[str]\n        The list of PIIs identifying the papers returned by the search"
  },
  {
    "code": "def _get_string_match_value(self, string, string_match_type):\n        if string_match_type == Type(**get_type_data('EXACT')):\n            return string\n        elif string_match_type == Type(**get_type_data('IGNORECASE')):\n            return re.compile('^' + string, re.I)\n        elif string_match_type == Type(**get_type_data('WORD')):\n            return re.compile('.*' + string + '.*')\n        elif string_match_type == Type(**get_type_data('WORDIGNORECASE')):\n            return re.compile('.*' + string + '.*', re.I)",
    "docstring": "Gets the match value"
  },
  {
    "code": "def validate_json(f):\n    @wraps(f)\n    def wrapper(*args, **kw):\n        instance = args[0]\n        try:\n            if request.get_json() is None:\n                ret_dict = instance._create_ret_object(instance.FAILURE,\n                                                       None, True,\n                                                       instance.MUST_JSON)\n                instance.logger.error(instance.MUST_JSON)\n                return jsonify(ret_dict), 400\n        except BadRequest:\n            ret_dict = instance._create_ret_object(instance.FAILURE, None,\n                                                   True,\n                                                   instance.MUST_JSON)\n            instance.logger.error(instance.MUST_JSON)\n            return jsonify(ret_dict), 400\n        instance.logger.debug(\"JSON is valid\")\n        return f(*args, **kw)\n    return wrapper",
    "docstring": "Validate that the call is JSON."
  },
  {
    "code": "def _parse_ipmi_nic_capacity(nic_out):\n    if ((\"Device not present\" in nic_out)\n       or (\"Unknown FRU header\" in nic_out) or not nic_out):\n        return None\n    capacity = None\n    product_name = None\n    data = nic_out.split('\\n')\n    for item in data:\n        fields = item.split(':')\n        if len(fields) > 1:\n            first_field = fields[0].strip()\n            if first_field == \"Product Name\":\n                product_name = ':'.join(fields[1:])\n                break\n    if product_name:\n        product_name_array = product_name.split(' ')\n        for item in product_name_array:\n            if 'Gb' in item:\n                capacity_int = item.strip('Gb')\n                if capacity_int.isdigit():\n                    capacity = item\n    return capacity",
    "docstring": "Parse the FRU output for NIC capacity\n\n    Parses the FRU output. Seraches for the key \"Product Name\"\n    in FRU output and greps for maximum speed supported by the\n    NIC adapter.\n\n    :param nic_out: the FRU output for NIC adapter.\n    :returns: the max capacity supported by the NIC adapter."
  },
  {
    "code": "def make_hash_id():\n    today = datetime.datetime.now().strftime(DATETIME_FORMAT)\n    return hashlib.sha1(today.encode('utf-8')).hexdigest()",
    "docstring": "Compute the `datetime.now` based SHA-1 hash of a string.\n\n    :return: Returns the sha1 hash as a string.\n    :rtype: str"
  },
  {
    "code": "def replace_model(refwcs, newcoeffs):\n    print('WARNING:')\n    print('    Replacing existing distortion model with one')\n    print('    not necessarily matched to the observation!')\n    wcslin = stwcs.distortion.utils.undistortWCS(refwcs)\n    outwcs = refwcs.deepcopy()\n    outwcs.wcs.cd = wcslin.wcs.cd\n    outwcs.wcs.set()\n    outwcs.setOrient()\n    outwcs.setPscale()\n    add_model(outwcs,newcoeffs)\n    apply_model(outwcs)\n    refwcs = outwcs.deepcopy()",
    "docstring": "Replace the distortion model in a current WCS with a new model\n        Start by creating linear WCS, then run"
  },
  {
    "code": "def disablingBuidCache(self):\n        self.buidcache = s_cache.LruDict(0)\n        yield\n        self.buidcache = s_cache.LruDict(BUID_CACHE_SIZE)",
    "docstring": "Disable and invalidate the layer buid cache for migration"
  },
  {
    "code": "def _fold_line(self, line):\n        if len(line) <= self._cols:\n            self._output_file.write(line)\n            self._output_file.write(self._line_sep)\n        else:\n            pos = self._cols\n            self._output_file.write(line[0:self._cols])\n            self._output_file.write(self._line_sep)\n            while pos < len(line):\n                self._output_file.write(b' ')\n                end = min(len(line), pos + self._cols - 1)\n                self._output_file.write(line[pos:end])\n                self._output_file.write(self._line_sep)\n                pos = end",
    "docstring": "Write string line as one or more folded lines."
  },
  {
    "code": "def event_return(events):\n    conn = _get_conn()\n    if conn is None:\n        return None\n    cur = conn.cursor()\n    for event in events:\n        tag = event.get('tag', '')\n        data = event.get('data', '')\n        sql =\n        cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id']))\n    _close_conn(conn)",
    "docstring": "Return event to a postgres server\n\n    Require that configuration be enabled via 'event_return'\n    option in master config."
  },
  {
    "code": "def get_snippet_content(snippet_name, **format_kwargs):\n    filename = snippet_name + '.snippet'\n    snippet_file = os.path.join(SNIPPETS_ROOT, filename)\n    if not os.path.isfile(snippet_file):\n        raise ValueError('could not find snippet with name ' + filename)\n    ret = helpers.get_file_content(snippet_file)\n    if format_kwargs:\n        ret = ret.format(**format_kwargs)\n    return ret",
    "docstring": "Load the content from a snippet file which exists in SNIPPETS_ROOT"
  },
  {
    "code": "def from_array(array):\n        if array is None or not array:\n            return None\n        assert_type_or_raise(array, dict, parameter_name=\"array\")\n        from ..receivable.media import Location\n        from ..receivable.peer import User\n        data = {}\n        data['result_id'] = u(array.get('result_id'))\n        data['from_peer'] = User.from_array(array.get('from'))\n        data['query'] = u(array.get('query'))\n        data['location'] = Location.from_array(array.get('location')) if array.get('location') is not None else None\n        data['inline_message_id'] = u(array.get('inline_message_id')) if array.get('inline_message_id') is not None else None\n        data['_raw'] = array\n        return ChosenInlineResult(**data)",
    "docstring": "Deserialize a new ChosenInlineResult from a given dictionary.\n\n        :return: new ChosenInlineResult instance.\n        :rtype: ChosenInlineResult"
  },
  {
    "code": "def get_files(dirname=None, pattern='*.*', recursive=True):\n    if dirname is None:\n        from FlowCytometryTools.gui import dialogs\n        dirname = dialogs.select_directory_dialog('Select a directory')\n    if recursive:\n        matches = []\n        for root, dirnames, filenames in os.walk(dirname):\n            for filename in fnmatch.filter(filenames, pattern):\n                matches.append(os.path.join(root, filename))\n    else:\n        matches = glob.glob(os.path.join(dirname, pattern))\n    return matches",
    "docstring": "Get all file names within a given directory those names match a\n    given pattern.\n\n    Parameters\n    ----------\n    dirname : str | None\n        Directory containing the datafiles.\n        If None is given, open a dialog box.\n    pattern : str\n        Return only files whose names match the specified pattern.\n    recursive : bool\n        True : Search recursively within all sub-directories.\n        False : Search only in given directory.\n\n    Returns\n    -------\n    matches: list\n       List of file names (including full path)."
  },
  {
    "code": "def printAllElements(self):\n        cnt = 1\n        print(\"{id:<3s}: {name:<12s} {type:<10s} {classname:<10s}\"\n              .format(id='ID', name='Name', type='Type', classname='Class Name'))\n        for e in self._lattice_eleobjlist:\n            print(\"{cnt:>03d}: {name:<12s} {type:<10s} {classname:<10s}\"\n                  .format(cnt=cnt, name=e.name, type=e.typename, classname=e.__class__.__name__))\n            cnt += 1",
    "docstring": "print out all modeled elements"
  },
  {
    "code": "def find_nearest(self, hex_code, system, filter_set=None):\n        if system not in self._colors_by_system_hex:\n            raise ValueError(\n                \"%r is not a registered color system. Try one of %r\"\n                % (system, self._colors_by_system_hex.keys())\n            )\n        hex_code = hex_code.lower().strip()\n        if hex_code in self._colors_by_system_hex[system]:\n            color_name = self._colors_by_system_hex[system][hex_code]\n            if filter_set is None or color_name in filter_set:\n                return FindResult(color_name, 0)\n        colors = self._colors_by_system_lab[system]\n        if filter_set is not None:\n            colors = (pair for pair in colors if pair[1] in set(filter_set))\n        lab_color = _hex_to_lab(hex_code)\n        min_distance = sys.float_info.max\n        min_color_name = None\n        for current_lab_color, current_color_name in colors:\n            distance = colormath.color_diff.delta_e_cie2000(lab_color, current_lab_color)\n            if distance < min_distance:\n                min_distance = distance\n                min_color_name = current_color_name\n        return FindResult(min_color_name, min_distance)",
    "docstring": "Find a color name that's most similar to a given sRGB hex code.\n\n        In normalization terms, this method implements \"normalize an arbitrary sRGB value\n        to a well-defined color name\".\n\n        Args:\n          system (string): The color system. Currently, `\"en\"`` is the only default\n            system.\n          filter_set (iterable of string, optional): Limits the output choices\n            to fewer color names. The names (e.g. ``[\"black\", \"white\"]``) must be\n            present in the given system.\n            If omitted, all color names of the system are considered. Defaults to None.\n\n        Returns:\n          A named tuple with the members `color_name` and `distance`.\n\n        Raises:\n          ValueError: If argument `system` is not a registered color system.\n\n        Examples:\n          >>> tint_registry = TintRegistry()\n          >>> tint_registry.find_nearest(\"54e6e4\", system=\"en\")\n          FindResult(color_name=u'bright turquoise', distance=3.730288645055483)\n          >>> tint_registry.find_nearest(\"54e6e4\", \"en\", filter_set=(\"white\", \"black\"))\n          FindResult(color_name=u'white', distance=25.709952192116894)"
  },
  {
    "code": "def filter(self, filter_fn=None, desc=None, **kwargs):\n        if filter_fn is not None and kwargs:\n            raise TypeError('Must supply either a filter_fn or attribute filter parameters to filter(), but not both.')\n        if filter_fn is None and not kwargs:\n            raise TypeError('Must supply one of filter_fn or one or more attribute filter parameters to filter().')\n        if desc is None:\n            if filter_fn is not None:\n                desc = getattr(filter_fn, '__name__', '')\n            elif kwargs:\n                desc = u\", \".join([u\"{}={!r}\".format(key, value) for key, value in kwargs.items()])\n        desc = u\"filter({})\".format(desc)\n        if kwargs:\n            def filter_fn(elem):\n                return all(\n                    getattr(elem, filter_key) == filter_value\n                    for filter_key, filter_value\n                    in kwargs.items()\n                )\n        return self.transform(lambda xs: (x for x in xs if filter_fn(x)), desc=desc)",
    "docstring": "Return a copy of this query, with some values removed.\n\n        Example usages:\n\n        .. code:: python\n\n            # Returns a query that matches even numbers\n            q.filter(filter_fn=lambda x: x % 2)\n\n            # Returns a query that matches elements with el.description == \"foo\"\n            q.filter(description=\"foo\")\n\n        Keyword Args:\n            filter_fn (callable): If specified, a function that accepts one argument (the element)\n                    and returns a boolean indicating whether to include that element in the results.\n\n            kwargs: Specify attribute values that an element must have to be included in the results.\n\n            desc (str): A description of the filter, for use in log messages.\n                Defaults to the name of the filter function or attribute.\n\n        Raises:\n            TypeError: neither or both of `filter_fn` and `kwargs` are provided."
  },
  {
    "code": "def _update_transforms(self):\n        if len(self._fb_stack) == 0:\n            fb_size = fb_rect = None\n        else:\n            fb, origin, fb_size = self._fb_stack[-1]\n            fb_rect = origin + fb_size\n        if len(self._vp_stack) == 0:\n            viewport = None\n        else:\n            viewport = self._vp_stack[-1]\n        self.transforms.configure(viewport=viewport, fbo_size=fb_size,\n                                  fbo_rect=fb_rect)",
    "docstring": "Update the canvas's TransformSystem to correct for the current \n        canvas size, framebuffer, and viewport."
  },
  {
    "code": "def _get_v4_signed_headers(self):\n        if self.aws_session is None:\n            boto_session = session.Session()\n            creds = boto_session.get_credentials()\n        else:\n            creds = self.aws_session.get_credentials()\n        if creds is None:\n            raise CerberusClientException(\"Unable to locate AWS credentials\")\n        readonly_credentials = creds.get_frozen_credentials()\n        data = OrderedDict((('Action','GetCallerIdentity'), ('Version', '2011-06-15')))\n        url = 'https://sts.{}.amazonaws.com/'.format(self.region)\n        request_object = awsrequest.AWSRequest(method='POST', url=url, data=data)\n        signer = auth.SigV4Auth(readonly_credentials, 'sts', self.region)\n        signer.add_auth(request_object)\n        return request_object.headers",
    "docstring": "Returns V4 signed get-caller-identity request headers"
  },
  {
    "code": "def quoteattrs(data):\n    items = []\n    for key, value in data.items():\n        items.append('{}={}'.format(key, quoteattr(value)))\n    return ' '.join(items)",
    "docstring": "Takes dict of attributes and returns their HTML representation"
  },
  {
    "code": "def send(self, filenames=None):\n        try:\n            with self.ssh_client.connect() as ssh_conn:\n                with self.sftp_client.connect(ssh_conn) as sftp_conn:\n                    for filename in filenames:\n                        sftp_conn.copy(filename=filename)\n                        self.archive(filename=filename)\n                        if self.update_history_model:\n                            self.update_history(filename=filename)\n        except SSHClientError as e:\n            raise TransactionFileSenderError(e) from e\n        except SFTPClientError as e:\n            raise TransactionFileSenderError(e) from e\n        return filenames",
    "docstring": "Sends the file to the remote host and archives\n        the sent file locally."
  },
  {
    "code": "def edit(self, pk):\n        resp = super(TableModelView, self).edit(pk)\n        if isinstance(resp, str):\n            return resp\n        return redirect('/superset/explore/table/{}/'.format(pk))",
    "docstring": "Simple hack to redirect to explore view after saving"
  },
  {
    "code": "def display_upstream_structure(structure_dict):\n    graph = _create_graph(structure_dict)\n    plt = Image(graph.create_png())\n    display(plt)",
    "docstring": "Displays pipeline structure in the jupyter notebook.\n\n    Args:\n        structure_dict (dict): dict returned by\n            :func:`~steppy.base.Step.upstream_structure`."
  },
  {
    "code": "def get_ticket(self, ticket_id):\n        url = 'tickets/%d' % ticket_id\n        ticket = self._api._get(url)\n        return Ticket(**ticket)",
    "docstring": "Fetches the ticket for the given ticket ID"
  },
  {
    "code": "def schedule(identifier, **kwargs):\n    source = actions.schedule(identifier, **kwargs)\n    msg = 'Scheduled {source.name} with the following crontab: {cron}'\n    log.info(msg.format(source=source, cron=source.periodic_task.crontab))",
    "docstring": "Schedule a harvest job to run periodically"
  },
  {
    "code": "def get_word_under_cursor(self):\n        if not re.match(r\"^\\w+$\", foundations.strings.to_string(self.get_previous_character())):\n            return QString()\n        cursor = self.textCursor()\n        cursor.movePosition(QTextCursor.PreviousWord, QTextCursor.MoveAnchor)\n        cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor)\n        return cursor.selectedText()",
    "docstring": "Returns the document word under cursor.\n\n        :return: Word under cursor.\n        :rtype: QString"
  },
  {
    "code": "def instances(cls):\n        l = [i for i in cls.allinstances() if isinstance(i, cls)]\n        return l",
    "docstring": "Return all instances of this class and subclasses\n\n        :returns: all instances of the current class and subclasses\n        :rtype: list\n        :raises: None"
  },
  {
    "code": "def get_dock_json(self):\n        env_json = self.build_json['spec']['strategy']['customStrategy']['env']\n        try:\n            p = [env for env in env_json if env[\"name\"] == \"ATOMIC_REACTOR_PLUGINS\"]\n        except TypeError:\n            raise RuntimeError(\"\\\"env\\\" is not iterable\")\n        if len(p) <= 0:\n            raise RuntimeError(\"\\\"env\\\" misses key ATOMIC_REACTOR_PLUGINS\")\n        dock_json_str = p[0]['value']\n        dock_json = json.loads(dock_json_str)\n        return dock_json",
    "docstring": "return dock json from existing build json"
  },
  {
    "code": "def run_migration_list(self, path, migrations, pretend=False):\n        if not migrations:\n            self._note(\"<info>Nothing to migrate</info>\")\n            return\n        batch = self._repository.get_next_batch_number()\n        for f in migrations:\n            self._run_up(path, f, batch, pretend)",
    "docstring": "Run a list of migrations.\n\n        :type migrations: list\n\n        :type pretend: bool"
  },
  {
    "code": "def lookupByName(self, name):\n        res = yield queue.executeInThread(self.connection.lookupByName, name)\n        return self.DomainClass(self, res)",
    "docstring": "I lookup an existing predefined domain"
  },
  {
    "code": "def clipandmerge_general_stats_table(self):\n        headers = OrderedDict()\n        headers['percentage'] = {\n            'title': '% Merged',\n            'description': 'Percentage of reads merged',\n            'min': 0,\n            'max': 100,\n            'suffix': '%',\n            'scale': 'Greens',\n            'format': '{:,.2f}',\n        }\n        self.general_stats_addcols(self.clipandmerge_data, headers)",
    "docstring": "Take the parsed stats from the ClipAndMerge report and add it to the\n        basic stats table at the top of the report"
  },
  {
    "code": "def keep_everything_scorer(checked_ids):\n    result = checked_ids.keys()\n    for i in checked_ids.values():\n        result.extend(i.keys())\n    return dict.fromkeys(result).keys()",
    "docstring": "Returns every query and every match in checked_ids, with best score."
  },
  {
    "code": "def trailing_stop_loss(self, accountID, **kwargs):\n        return self.create(\n            accountID,\n            order=TrailingStopLossOrderRequest(**kwargs)\n        )",
    "docstring": "Shortcut to create a Trailing Stop Loss Order in an Account\n\n        Args:\n            accountID : The ID of the Account\n            kwargs : The arguments to create a TrailingStopLossOrderRequest\n\n        Returns:\n            v20.response.Response containing the results from submitting\n            the request"
  },
  {
    "code": "def mouse_button_callback(self, window, button, action, mods):\r\n        button += 1\r\n        if button not in [1, 2]:\r\n            return\r\n        xpos, ypos = glfw.get_cursor_pos(self.window)\r\n        if action == glfw.PRESS:\r\n            self.example.mouse_press_event(xpos, ypos, button)\r\n        else:\r\n            self.example.mouse_release_event(xpos, ypos, button)",
    "docstring": "Handle mouse button events and forward them to the example"
  },
  {
    "code": "def readPhenoFile(pfile,idx=None):\n    usecols = None\n    if idx!=None:\n        usecols = [int(x) for x in idx.split(',')]\n    phenoFile = pfile+'.phe'\n    assert os.path.exists(phenoFile), '%s is missing.'%phenoFile\n    Y = SP.loadtxt(phenoFile,usecols=usecols)\n    if (usecols is not None) and (len(usecols)==1): Y = Y[:,SP.newaxis]\n    Y -= Y.mean(0); Y /= Y.std(0)\n    return Y",
    "docstring": "reading in phenotype file\n\n    pfile   root of the file containing the phenotypes as NxP matrix\n            (N=number of samples, P=number of traits)"
  },
  {
    "code": "def static_filename(self, repo: str, branch: str, relative_path: Union[str, Path], *,\n                        depth: DepthDefinitionType=1,\n                        reference: ReferenceDefinitionType=None\n                        ) -> Path:\n        self.validate_repo_url(repo)\n        depth = self.validate_depth(depth)\n        reference = self.validate_reference(reference)\n        if not isinstance(relative_path, Path):\n            relative_path = Path(relative_path)\n        _, repo_path = self.get_files(repo, branch, depth=depth, reference=reference)\n        result = repo_path / relative_path\n        result = result.resolve()\n        if repo_path not in result.parents:\n            raise FileOutOfRangeError(f\"{relative_path} is not inside the repository.\")\n        if not result.exists():\n            raise FileNotFoundError(f\"{relative_path} does not exist in the repository.\")\n        logger.info(\"Static path for %s is %s\", relative_path, result)\n        return result",
    "docstring": "Returns an absolute path to where a file from the repo was cloned to.\n\n        :param repo: Repo URL\n        :param branch: Branch name\n        :param relative_path: Relative path to the requested file\n        :param depth: See :meth:`run`\n        :param reference: See :meth:`run`\n\n        :return: Absolute path to the file in the target repository\n\n        :raise FileOutOfRangeError: If the relative path leads out of the repository path\n        :raise FileNotFoundError: If the file doesn't exist in the repository."
  },
  {
    "code": "def recent_update_frequencies(self):\n        return list(reversed([(1.0 / p) for p in numpy.diff(self._recent_updates)]))",
    "docstring": "Returns the 10 most recent update frequencies.\n\n        The given frequencies are computed as short-term frequencies!\n        The 0th element of the list corresponds to the most recent frequency."
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'section_titles' in _dict:\n            args['section_titles'] = [\n                SectionTitles._from_dict(x)\n                for x in (_dict.get('section_titles'))\n            ]\n        if 'leading_sentences' in _dict:\n            args['leading_sentences'] = [\n                LeadingSentence._from_dict(x)\n                for x in (_dict.get('leading_sentences'))\n            ]\n        return cls(**args)",
    "docstring": "Initialize a DocStructure object from a json dictionary."
  },
  {
    "code": "def tasks(self):\n        tasks_response = self.get_request('tasks/')\n        return [Task(self, tjson['task']) for tjson in tasks_response]",
    "docstring": "Generates a list of all Tasks."
  },
  {
    "code": "def ensure_default_namespace(self) -> Namespace:\n        namespace = self.get_namespace_by_keyword_version(BEL_DEFAULT_NAMESPACE, BEL_DEFAULT_NAMESPACE_VERSION)\n        if namespace is None:\n            namespace = Namespace(\n                name='BEL Default Namespace',\n                contact='charles.hoyt@scai.fraunhofer.de',\n                keyword=BEL_DEFAULT_NAMESPACE,\n                version=BEL_DEFAULT_NAMESPACE_VERSION,\n                url=BEL_DEFAULT_NAMESPACE_URL,\n            )\n            for name in set(chain(pmod_mappings, gmod_mappings, activity_mapping, compartment_mapping)):\n                entry = NamespaceEntry(name=name, namespace=namespace)\n                self.session.add(entry)\n            self.session.add(namespace)\n            self.session.commit()\n        return namespace",
    "docstring": "Get or create the BEL default namespace."
  },
  {
    "code": "def address(self) -> str:\n        fmt = self._data['address_fmt']\n        st_num = self.street_number()\n        st_name = self.street_name()\n        if self.locale in SHORTENED_ADDRESS_FMT:\n            return fmt.format(\n                st_num=st_num,\n                st_name=st_name,\n            )\n        if self.locale == 'ja':\n            return fmt.format(\n                self.random.choice(self._data['city']),\n                *self.random.randints(amount=3, a=1, b=100),\n            )\n        return fmt.format(\n            st_num=st_num,\n            st_name=st_name,\n            st_sfx=self.street_suffix(),\n        )",
    "docstring": "Generate a random full address.\n\n        :return: Full address."
  },
  {
    "code": "def peers(**kwargs):\n    ntp_peers = salt.utils.napalm.call(\n        napalm_device,\n        'get_ntp_peers',\n        **{\n        }\n    )\n    if not ntp_peers.get('result'):\n        return ntp_peers\n    ntp_peers_list = list(ntp_peers.get('out', {}).keys())\n    ntp_peers['out'] = ntp_peers_list\n    return ntp_peers",
    "docstring": "Returns a list the NTP peers configured on the network device.\n\n    :return: configured NTP peers as list.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' ntp.peers\n\n    Example output:\n\n    .. code-block:: python\n\n        [\n            '192.168.0.1',\n            '172.17.17.1',\n            '172.17.17.2',\n            '2400:cb00:6:1024::c71b:840a'\n        ]"
  },
  {
    "code": "def transform(self, data, centers=None):\n        centers = centers or self.centers_\n        hypercubes = [\n            self.transform_single(data, cube, i) for i, cube in enumerate(centers)\n        ]\n        hypercubes = [cube for cube in hypercubes if len(cube)]\n        return hypercubes",
    "docstring": "Find entries of all hypercubes. If `centers=None`, then use `self.centers_` as computed in `self.fit`.\n            \n            Empty hypercubes are removed from the result\n\n        Parameters\n        ===========\n\n        data: array-like\n            Data to find in entries in cube. Warning: first column must be index column.\n        centers: list of array-like\n            Center points for all cubes as returned by `self.fit`. Default is to use `self.centers_`.\n\n        Returns\n        =========\n        hypercubes: list of array-like\n            list of entries in each hypercobe in `data`."
  },
  {
    "code": "def set_color(self, ipaddr, hue, sat, bri, kel, fade):\n        cmd = {\"payloadtype\": PayloadType.SETCOLOR,\n               \"target\": ipaddr,\n               \"hue\": hue,\n               \"sat\": sat,\n               \"bri\": bri,\n               \"kel\": kel,\n               \"fade\": fade}\n        self._send_command(cmd)",
    "docstring": "Send SETCOLOR message."
  },
  {
    "code": "def validate_model(self):\n        model: AssetAllocationModel = self.get_asset_allocation_model()\n        model.logger = self.logger\n        valid = model.validate()\n        if valid:\n            print(f\"The model is valid. Congratulations\")\n        else:\n            print(f\"The model is invalid.\")",
    "docstring": "Validate the model"
  },
  {
    "code": "def capture_heroku_database(self):\n        self.print_message(\"Capturing database backup for app '%s'\" % self.args.source_app)\n        args = [\n            \"heroku\",\n            \"pg:backups:capture\",\n            \"--app=%s\" % self.args.source_app,\n        ]\n        if self.args.use_pgbackups:\n            args = [\n                \"heroku\",\n                \"pgbackups:capture\",\n                \"--app=%s\" % self.args.source_app,\n                \"--expire\",\n            ]\n        subprocess.check_call(args)",
    "docstring": "Capture Heroku database backup."
  },
  {
    "code": "def clone(self, parent=None):\n        a = Attribute(self.qname(), self.value)\n        a.parent = parent\n        return a",
    "docstring": "Clone this object.\n        @param parent: The parent for the clone.\n        @type parent: L{element.Element}\n        @return: A copy of this object assigned to the new parent.\n        @rtype: L{Attribute}"
  },
  {
    "code": "def _get_at_from_session(self):\n        try:\n            return self.request.session['oauth_%s_access_token'\n                                        % get_token_prefix(\n                                            self.request_token_url)]\n        except KeyError:\n            raise OAuthError(\n                _('No access token saved for \"%s\".')\n                % get_token_prefix(self.request_token_url))",
    "docstring": "Get the saved access token for private resources from the session."
  },
  {
    "code": "def GenerateDSP(dspfile, source, env):\n    version_num = 6.0\n    if 'MSVS_VERSION' in env:\n        version_num, suite = msvs_parse_version(env['MSVS_VERSION'])\n    if version_num >= 10.0:\n        g = _GenerateV10DSP(dspfile, source, env)\n        g.Build()\n    elif version_num >= 7.0:\n        g = _GenerateV7DSP(dspfile, source, env)\n        g.Build()\n    else:\n        g = _GenerateV6DSP(dspfile, source, env)\n        g.Build()",
    "docstring": "Generates a Project file based on the version of MSVS that is being used"
  },
  {
    "code": "def estimate_sub_second_time(files, interval=0.0):\n    if interval <= 0.0:\n        return [exif_time(f) for f in tqdm(files, desc=\"Reading image capture time\")]\n    onesecond = datetime.timedelta(seconds=1.0)\n    T = datetime.timedelta(seconds=interval)\n    for i, f in tqdm(enumerate(files), desc=\"Estimating subsecond time\"):\n        m = exif_time(f)\n        if not m:\n            pass\n        if i == 0:\n            smin = m\n            smax = m + onesecond\n        else:\n            m0 = m - T * i\n            smin = max(smin, m0)\n            smax = min(smax, m0 + onesecond)\n    if not smin or not smax:\n        return None\n    if smin > smax:\n        print('Interval not compatible with EXIF times')\n        return None\n    else:\n        s = smin + (smax - smin) / 2\n        return [s + T * i for i in range(len(files))]",
    "docstring": "Estimate the capture time of a sequence with sub-second precision\n    EXIF times are only given up to a second of precision. This function\n    uses the given interval between shots to estimate the time inside that\n    second that each picture was taken."
  },
  {
    "code": "def delete(self):\n        response = self.session.request(\"delete:Message\", [ self.message_id ])\n        self.data = response\n        return self",
    "docstring": "Delete the draft."
  },
  {
    "code": "def is_manifest_valid(self, manifest_id):\n        response = self.get_manifest_validation_result(manifest_id)\n        if response.status_code != 200:\n            raise Exception(response.status_code)\n        content = json.loads(response.content)\n        if not content['processed']:\n            return None\n        if content['valid']:\n            return True\n        return content['validation']",
    "docstring": "Check validation shortcut\n\n        :param: manifest_id (string) id received in :method:`validate_manifest`\n        :returns:\n            * True if manifest was valid\n            * None if manifest wasn't checked yet\n            * validation dict if not valid"
  },
  {
    "code": "def verify_token(self, token, **kwargs):\n        nonce = kwargs.get('nonce')\n        token = force_bytes(token)\n        if self.OIDC_RP_SIGN_ALGO.startswith('RS'):\n            if self.OIDC_RP_IDP_SIGN_KEY is not None:\n                key = self.OIDC_RP_IDP_SIGN_KEY\n            else:\n                key = self.retrieve_matching_jwk(token)\n        else:\n            key = self.OIDC_RP_CLIENT_SECRET\n        payload_data = self.get_payload_data(token, key)\n        payload = json.loads(payload_data.decode('utf-8'))\n        token_nonce = payload.get('nonce')\n        if self.get_settings('OIDC_USE_NONCE', True) and nonce != token_nonce:\n            msg = 'JWT Nonce verification failed.'\n            raise SuspiciousOperation(msg)\n        return payload",
    "docstring": "Validate the token signature."
  },
  {
    "code": "def from_cif_file(cif_file, source='', comment=''):\n        r = CifParser(cif_file)\n        structure = r.get_structures()[0]\n        return Header(structure, source, comment)",
    "docstring": "Static method to create Header object from cif_file\n\n        Args:\n            cif_file: cif_file path and name\n            source: User supplied identifier, i.e. for Materials Project this\n                would be the material ID number\n            comment: User comment that goes in header\n\n        Returns:\n            Header Object"
  },
  {
    "code": "def _output_format(self, out, fmt_j=None, fmt_p=None):\r\n        if self.output_format == 'pandas':\r\n            if fmt_p is not None:\r\n                return fmt_p(out)\r\n            else:\r\n                return self._convert_output(out)\r\n        if fmt_j:\r\n            return fmt_j(out)\r\n        return out",
    "docstring": "Output formatting handler"
  },
  {
    "code": "def to_api_repr(self):\n        resource = {self.entity_type: self.entity_id}\n        if self.role is not None:\n            resource[\"role\"] = self.role\n        return resource",
    "docstring": "Construct the API resource representation of this access entry\n\n        Returns:\n            Dict[str, object]: Access entry represented as an API resource"
  },
  {
    "code": "def save_cert(domain, master):\n    result = __salt__['cmd.run_all']([\"icinga2\", \"pki\", \"save-cert\", \"--key\", \"{0}{1}.key\".format(get_certs_path(), domain), \"--cert\", \"{0}{1}.cert\".format(get_certs_path(), domain), \"--trustedcert\",\n                                      \"{0}trusted-master.crt\".format(get_certs_path()), \"--host\", master], python_shell=False)\n    return result",
    "docstring": "Save the certificate for master icinga2 node.\n\n    Returns::\n        icinga2 pki save-cert --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert /etc/icinga2/pki/trusted-master.crt --host master.domain.tld\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' icinga2.save_cert domain.tld master.domain.tld"
  },
  {
    "code": "def validate_attribute(attr, name, expected_type=None, required=False):\n    if expected_type:\n        if type(expected_type) == list:\n            if not _check_type(attr, expected_type):\n                raise InvalidTypeError(name, type(attr), expected_type)\n        else:\n            if not _check_type(attr, [expected_type]):\n                raise InvalidTypeError(name, type(attr), expected_type)\n    if required and not attr:\n        raise RequiredAttributeError(name)",
    "docstring": "Validates that an attribute meets expectations.\n\n    This function will check if the given attribute value matches a necessary\n    type and/or is not None, an empty string, an empty list, etc. It will raise\n    suitable exceptions on validation failure.\n\n    @param attr The value to validate.\n    @param name The attribute name to use in exceptions.\n    @param expected_type The type the value must be. If None, no check is\n    performed. If a list, attr must match one type in the list.\n    @param required If the value must not be empty, e.g. not an empty string.\n    @raises InvalidTypeError\n    @raises RequiredAttributeError"
  },
  {
    "code": "def _flush(self):\n        if not self.enabled:\n            return\n        try:\n            try:\n                self.lock.acquire()\n                self.flush()\n            except Exception:\n                self.log.error(traceback.format_exc())\n        finally:\n            if self.lock.locked():\n                self.lock.release()",
    "docstring": "Decorator for flushing handlers with an lock, catching exceptions"
  },
  {
    "code": "async def get_available_abilities(self, units: Union[List[Unit], Units], ignore_resource_requirements=False) -> List[List[AbilityId]]:\n        return await self._client.query_available_abilities(units, ignore_resource_requirements)",
    "docstring": "Returns available abilities of one or more units."
  },
  {
    "code": "def remove_whitespace(s):\n    ignores = {}\n    for ignore in html_ignore_whitespace_re.finditer(s):\n        name = \"{}{}{}\".format(r\"{}\", uuid.uuid4(), r\"{}\")\n        ignores[name] = ignore.group()\n        s = s.replace(ignore.group(), name)\n    s = whitespace_re(r' ', s).strip()\n    for name, val in ignores.items():\n        s = s.replace(name, val)\n    return s",
    "docstring": "Unsafely attempts to remove HTML whitespace. This is not an HTML parser\n        which is why its considered 'unsafe', but it should work for most\n        implementations. Just use on at your own risk.\n\n        @s: #str\n\n        -> HTML with whitespace removed, ignoring <pre>, script, textarea and code\n            tags"
  },
  {
    "code": "def _check_if_ins_is_dup(self, start, insertion):\n        is_dup = False\n        variant_start = None\n        dup_candidate_start = start - len(insertion) - 1\n        dup_candidate = self._ref_seq[dup_candidate_start:dup_candidate_start + len(insertion)]\n        if insertion == dup_candidate:\n            is_dup = True\n            variant_start = dup_candidate_start + 1\n        return is_dup, variant_start",
    "docstring": "Helper to identify an insertion as a duplicate\n\n        :param start: 1-based insertion start\n        :type start: int\n        :param insertion: sequence\n        :type insertion: str\n        :return (is duplicate, variant start)\n        :rtype (bool, int)"
  },
  {
    "code": "def relpath(self, start='.'):\n        cwd = self._next_class(start)\n        return cwd.relpathto(self)",
    "docstring": "Return this path as a relative path,\n        based from `start`, which defaults to the current working directory."
  },
  {
    "code": "def makeaddress(self, label):\n        addr = address.new(label)\n        if not addr.repo:\n            addr.repo = self.address.repo\n            if not addr.path:\n                addr.path = self.address.path\n        return addr",
    "docstring": "Turn a label into an Address with current context.\n\n        Adds repo and path if given a label that only has a :target part."
  },
  {
    "code": "def create_hook(self, auth, repo_name, hook_type, config, events=None, organization=None, active=False):\n        if events is None:\n            events = [\"push\"]\n        data = {\n            \"type\": hook_type,\n            \"config\": config,\n            \"events\": events,\n            \"active\": active\n        }\n        url = \"/repos/{o}/{r}/hooks\".format(o=organization, r=repo_name) if organization is not None \\\n            else \"/repos/{r}/hooks\".format(r=repo_name)\n        response = self.post(url, auth=auth, data=data)\n        return GogsRepo.Hook.from_json(response.json())",
    "docstring": "Creates a new hook, and returns the created hook.\n\n        :param auth.Authentication auth: authentication object, must be admin-level\n        :param str repo_name: the name of the repo for which we create the hook\n        :param str hook_type: The type of webhook, either \"gogs\" or \"slack\"\n        :param dict config: Settings for this hook (possible keys are\n                            ``\"url\"``, ``\"content_type\"``, ``\"secret\"``)\n        :param list events: Determines what events the hook is triggered for. Default: [\"push\"]\n        :param str organization: Organization of the repo\n        :param bool active: Determines whether the hook is actually triggered on pushes. Default is false\n        :return: a representation of the created hook\n        :rtype: GogsRepo.Hook\n        :raises NetworkFailure: if there is an error communicating with the server\n        :raises ApiFailure: if the request cannot be serviced"
  },
  {
    "code": "def set_line_width(self, width):\n        \"Set line width\"\n        self.line_width=width\n        if(self.page>0):\n            self._out(sprintf('%.2f w',width*self.k))",
    "docstring": "Set line width"
  },
  {
    "code": "def apply_with_summary(input_layer, operation, *op_args, **op_kwargs):\n  return layers.apply_activation(input_layer.bookkeeper,\n                                 input_layer.tensor,\n                                 operation,\n                                 activation_args=op_args,\n                                 activation_kwargs=op_kwargs)",
    "docstring": "Applies the given operation to `input_layer` and create a summary.\n\n  Args:\n    input_layer: The input layer for this op.\n    operation: An operation that takes a tensor and the supplied args.\n    *op_args: Extra arguments for operation.\n    **op_kwargs: Keyword arguments for the operation.\n  Returns:\n    A new layer with operation applied."
  },
  {
    "code": "def is_merged(sheet, row, column):\n    for cell_range in sheet.merged_cells:\n        row_low, row_high, column_low, column_high = cell_range\n        if (row in range(row_low, row_high)) and \\\n                (column in range(column_low, column_high)):\n            if ((column_high - column_low) < sheet.ncols - 1) and \\\n                    ((row_high - row_low) < sheet.nrows - 1):\n                return (True, cell_range)\n    return False",
    "docstring": "Check if a row, column cell is a merged cell"
  },
  {
    "code": "def _acronym_lic(self, license_statement):\n        pat = re.compile(r'\\(([\\w+\\W?\\s?]+)\\)')\n        if pat.search(license_statement):\n            lic = pat.search(license_statement).group(1)\n            if lic.startswith('CNRI'):\n                acronym_licence = lic[:4]\n            else:\n                acronym_licence = lic.replace(' ', '')\n        else:\n            acronym_licence = ''.join(\n                [w[0]\n                 for w in license_statement.split(self.prefix_lic)[1].split()])\n        return acronym_licence",
    "docstring": "Convert license acronym."
  },
  {
    "code": "def setup(self, helper=None, **create_kwargs):\n        if self.created:\n            return\n        self.set_helper(helper)\n        self.create(**create_kwargs)\n        return self",
    "docstring": "Setup this resource so that is ready to be used in a test. If the\n        resource has already been created, this call does nothing.\n\n        For most resources, this just involves creating the resource in Docker.\n\n        :param helper:\n            The resource helper to use, if one was not provided when this\n            resource definition was created.\n        :param **create_kwargs: Keyword arguments passed to :meth:`.create`.\n\n        :returns:\n            This definition instance. Useful for creating and setting up a\n            resource in a single step::\n\n                volume = VolumeDefinition('volly').setup(helper=docker_helper)"
  },
  {
    "code": "def import_(zone, path):\n    ret = {'status': True}\n    _dump_cfg(path)\n    res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {path}'.format(\n        zone=zone,\n        path=path,\n    ))\n    ret['status'] = res['retcode'] == 0\n    ret['message'] = res['stdout'] if ret['status'] else res['stderr']\n    if ret['message'] == '':\n        del ret['message']\n    else:\n        ret['message'] = _clean_message(ret['message'])\n    return ret",
    "docstring": "Import the configuration to memory from stable storage.\n\n    zone : string\n        name of zone\n    path : string\n        path of file to export to\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' zonecfg.import epyon /zones/epyon.cfg"
  },
  {
    "code": "def create_window(size=None, samples=16, *, fullscreen=False, title=None, threaded=True) -> Window:\n    if size is None:\n        width, height = 1280, 720\n    else:\n        width, height = size\n    if samples < 0 or (samples & (samples - 1)) != 0:\n        raise Exception('Invalid number of samples: %d' % samples)\n    window = Window.__new__(Window)\n    window.wnd = glwnd.create_window(width, height, samples, fullscreen, title, threaded)\n    return window",
    "docstring": "Create the main window.\n\n        Args:\n            size (tuple): The width and height of the window.\n            samples (int): The number of samples.\n\n        Keyword Args:\n            fullscreen (bool): Fullscreen?\n            title (bool): The title of the window.\n            threaded (bool): Threaded?\n\n        Returns:\n            Window: The main window."
  },
  {
    "code": "def dump(*args, **kwargs):\n    kwargs.update(dict(cls=NumpyEncoder,\n                       sort_keys=True,\n                       indent=4,\n                       separators=(',', ': ')))\n    return _json.dump(*args, **kwargs)",
    "docstring": "Dump a numpy.ndarray to file stream.\n\n    This works exactly like the usual `json.dump()` function,\n    but it uses our custom serializer."
  },
  {
    "code": "def wildcard_allowed_actions(self, pattern=None):\n        wildcard_allowed = []\n        for statement in self.statements:\n            if statement.wildcard_actions(pattern) and statement.effect == \"Allow\":\n                wildcard_allowed.append(statement)\n        return wildcard_allowed",
    "docstring": "Find statements which allow wildcard actions.\n\n        A pattern can be specified for the wildcard action"
  },
  {
    "code": "def NegateQueryFilter(es_query):\n    query = es_query.to_dict().get(\"query\", {})\n    filtered = query.get(\"filtered\", {})\n    negated_filter = filtered.get(\"filter\", {})\n    return Not(**negated_filter)",
    "docstring": "Return a filter removing the contents of the provided query."
  },
  {
    "code": "def _pause(self):\n        if self._input_func in self._netaudio_func_list:\n            body = {\"cmd0\": \"PutNetAudioCommand/CurEnter\",\n                    \"cmd1\": \"aspMainZone_WebUpdateStatus/\",\n                    \"ZoneName\": \"MAIN ZONE\"}\n            try:\n                if self.send_post_command(\n                        self._urls.command_netaudio_post, body):\n                    self._state = STATE_PAUSED\n                    return True\n                else:\n                    return False\n            except requests.exceptions.RequestException:\n                _LOGGER.error(\"Connection error: pause command not sent.\")\n                return False",
    "docstring": "Send pause command to receiver command via HTTP post."
  },
  {
    "code": "def _create_batches(self, X, batch_size, shuffle_data=True):\n        if shuffle_data:\n            X = shuffle(X)\n        if batch_size > X.shape[0]:\n            batch_size = X.shape[0]\n        max_x = int(np.ceil(X.shape[0] / batch_size))\n        X = np.resize(X, (max_x, batch_size, X.shape[-1]))\n        return X",
    "docstring": "Create batches out of a sequence of data.\n\n        This function will append zeros to the end of your data to ensure that\n        all batches are even-sized. These are masked out during training."
  },
  {
    "code": "def _bubbleP(cls, T):\n        c = cls._blend[\"bubble\"]\n        Tj = cls._blend[\"Tj\"]\n        Pj = cls._blend[\"Pj\"]\n        Tita = 1-T/Tj\n        suma = 0\n        for i, n in zip(c[\"i\"], c[\"n\"]):\n            suma += n*Tita**(i/2.)\n        P = Pj*exp(Tj/T*suma)\n        return P",
    "docstring": "Using ancillary equation return the pressure of bubble point"
  },
  {
    "code": "def fetchThreads(self, thread_location, before=None, after=None, limit=None):\n        threads = []\n        last_thread_timestamp = None\n        while True:\n            if limit and len(threads) >= limit:\n                break\n            candidates = self.fetchThreadList(\n                before=last_thread_timestamp, thread_location=thread_location\n            )\n            if len(candidates) > 1:\n                threads += candidates[1:]\n            else:\n                break\n            last_thread_timestamp = threads[-1].last_message_timestamp\n            if (before is not None and int(last_thread_timestamp) > before) or (\n                after is not None and int(last_thread_timestamp) < after\n            ):\n                break\n        if before is not None or after is not None:\n            for t in threads:\n                last_message_timestamp = int(t.last_message_timestamp)\n                if (before is not None and last_message_timestamp > before) or (\n                    after is not None and last_message_timestamp < after\n                ):\n                    threads.remove(t)\n        if limit and len(threads) > limit:\n            return threads[:limit]\n        return threads",
    "docstring": "Get all threads in thread_location.\n        Threads will be sorted from newest to oldest.\n\n        :param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER\n        :param before: Fetch only thread before this epoch (in ms) (default all threads)\n        :param after: Fetch only thread after this epoch (in ms) (default all threads)\n        :param limit: The max. amount of threads to fetch (default all threads)\n        :return: :class:`models.Thread` objects\n        :rtype: list\n        :raises: FBchatException if request failed"
  },
  {
    "code": "def output(output_id, name, value_class=NumberValue):\n        def _init():\n            return value_class(\n                name,\n                input_id=output_id,\n                is_input=False,\n                index=-1\n            )\n        def _decorator(cls):\n            setattr(cls, output_id, _init())\n            return cls\n        return _decorator",
    "docstring": "Add output to controller"
  },
  {
    "code": "def create_attributes(klass, attributes, previous_object=None):\n        if previous_object is not None:\n            return {'name': attributes.get('name', previous_object.name)}\n        return {\n            'name': attributes.get('name', ''),\n            'defaultLocale': attributes['default_locale']\n        }",
    "docstring": "Attributes for space creation."
  },
  {
    "code": "def convert_random_normal(node, **kwargs):\n    name, input_nodes, attrs = get_inputs(node, kwargs)\n    mean = float(attrs.get(\"loc\", 0))\n    scale = float(attrs.get(\"scale\", 1.0))\n    shape = convert_string_to_list(attrs.get('shape', '[]'))\n    dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(attrs.get('dtype', 'float32'))]\n    node = onnx.helper.make_node(\n        'RandomNormal',\n        input_nodes,\n        [name],\n        mean=mean,\n        scale=scale,\n        dtype=dtype,\n        shape=shape,\n        name=name\n    )\n    return [node]",
    "docstring": "Map MXNet's random_normal operator attributes to onnx's RandomNormal\n    operator and return the created node."
  },
  {
    "code": "def include(self):\n        include_param = self.qs.get('include', [])\n        if current_app.config.get('MAX_INCLUDE_DEPTH') is not None:\n            for include_path in include_param:\n                if len(include_path.split('.')) > current_app.config['MAX_INCLUDE_DEPTH']:\n                    raise InvalidInclude(\"You can't use include through more than {} relationships\"\n                                         .format(current_app.config['MAX_INCLUDE_DEPTH']))\n        return include_param.split(',') if include_param else []",
    "docstring": "Return fields to include\n\n        :return list: a list of include information"
  },
  {
    "code": "def change_keys(obj, convert):\n    if isinstance(obj, (str, int, float)):\n        return obj\n    if isinstance(obj, dict):\n        new = obj.__class__()\n        for k, v in obj.items():\n            new[convert(k)] = change_keys(v, convert)\n    elif isinstance(obj, (list, set, tuple)):\n        new = obj.__class__(change_keys(v, convert) for v in obj)\n    else:\n        return obj\n    return new",
    "docstring": "Recursively goes through the dictionary obj and replaces keys with the convert function."
  },
  {
    "code": "def iter_nautilus(method):\n    solution = None\n    while method.current_iter:\n        preference_class = init_nautilus(method)\n        pref = preference_class(method, None)\n        default = \",\".join(map(str, pref.default_input()))\n        while method.current_iter:\n            method.print_current_iteration()\n            pref_input = _prompt_wrapper(\n                u\"Preferences: \",\n                default=default,\n                validator=VectorValidator(method, pref),\n            )\n            cmd = _check_cmd(pref_input)\n            if cmd:\n                solution = method.zh\n                break\n            pref = preference_class(\n                method, np.fromstring(pref_input, dtype=np.float, sep=\",\")\n            )\n            default = \",\".join(map(str, pref.pref_input))\n            solution, _ = method.next_iteration(pref)\n        if cmd and list(cmd)[0] == \"c\":\n            break\n    return solution",
    "docstring": "Iterate NAUTILUS method either interactively, or using given preferences if given\n\n    Parameters\n    ----------\n\n    method : instance of NAUTILUS subclass\n       Fully initialized NAUTILUS method instance"
  },
  {
    "code": "def upcoming_shabbat(self):\n        if self.is_shabbat:\n            return self\n        saturday = self.gdate + datetime.timedelta(\n            (12 - self.gdate.weekday()) % 7)\n        return HDate(saturday, diaspora=self.diaspora, hebrew=self.hebrew)",
    "docstring": "Return the HDate for either the upcoming or current Shabbat.\n\n        If it is currently Shabbat, returns the HDate of the Saturday."
  },
  {
    "code": "def compute_layers(elements: List[Keccak256]) -> List[List[Keccak256]]:\n    elements = list(elements)\n    assert elements, 'Use make_empty_merkle_tree if there are no elements'\n    if not all(isinstance(item, bytes) for item in elements):\n        raise ValueError('all elements must be bytes')\n    if any(len(item) != 32 for item in elements):\n        raise HashLengthNot32()\n    if len(elements) != len(set(elements)):\n        raise ValueError('Duplicated element')\n    leaves = sorted(item for item in elements)\n    tree = [leaves]\n    layer = leaves\n    while len(layer) > 1:\n        paired_items = split_in_pairs(layer)\n        layer = [hash_pair(a, b) for a, b in paired_items]\n        tree.append(layer)\n    return tree",
    "docstring": "Computes the layers of the merkletree.\n\n    First layer is the list of elements and the last layer is a list with a\n    single entry, the merkleroot."
  },
  {
    "code": "def fill_in_by_selector(self, selector, value):\n    elem = find_element_by_jquery(world.browser, selector)\n    elem.clear()\n    elem.send_keys(value)",
    "docstring": "Fill in the form element matching the CSS selector."
  },
  {
    "code": "def ffPDC(self):\n        A = self.A()\n        return np.abs(A * self.nfft / np.sqrt(np.sum(A.conj() * A, axis=(0, 2),\n                                                     keepdims=True)))",
    "docstring": "Full frequency partial directed coherence.\n\n        .. math:: \\mathrm{ffPDC}_{ij}(f) =\n           \\\\frac{A_{ij}(f)}{\\sqrt{\\sum_f A_{:j}'(f) A_{:j}(f)}}"
  },
  {
    "code": "def get_example_extractions(fname):\n    \"Get extractions from one of the examples in `cag_examples`.\"\n    with open(fname, 'r') as f:\n        sentences = f.read().splitlines()\n    rdf_xml_dict = {}\n    for sentence in sentences:\n        logger.info(\"Reading \\\"%s\\\"...\" % sentence)\n        html = tc.send_query(sentence, 'cwms')\n        try:\n            rdf_xml_dict[sentence] = tc.get_xml(html, 'rdf:RDF',\n                                                fail_if_empty=True)\n        except AssertionError as e:\n            logger.error(\"Got error for %s.\" % sentence)\n            logger.exception(e)\n    return rdf_xml_dict",
    "docstring": "Get extractions from one of the examples in `cag_examples`."
  },
  {
    "code": "def _check_smart_storage_message(self):\n        ssc_mesg = self.smart_storage_config_message\n        result = True\n        raid_message = \"\"\n        for element in ssc_mesg:\n            if \"Success\" not in element['MessageId']:\n                result = False\n                raid_message = element['MessageId']\n        return result, raid_message",
    "docstring": "Check for smart storage message.\n\n        :returns: result, raid_message"
  },
  {
    "code": "def ip2hex(ip):\n    parts = ip.split(\".\")\n    if len(parts) != 4: return None\n    ipv = 0\n    for part in parts:\n        try:\n            p = int(part)\n            if p < 0 or p > 255: return None\n            ipv = (ipv << 8) + p\n        except:\n            return None\n    return ipv",
    "docstring": "Converts an ip to a hex value that can be used with a hex bit mask"
  },
  {
    "code": "def get_locations_from_coords(self, longitude, latitude, levels=None):\n        resp = requests.get(SETTINGS['url'] + '/point/4326/%s,%s?generation=%s' % (longitude, latitude, SETTINGS['generation']))\n        resp.raise_for_status()\n        geos = []\n        for feature in resp.json().itervalues():\n            try:\n                geo = self.get_geography(feature['codes']['MDB'],\n                                         feature['type_name'].lower())\n                if not levels or geo.geo_level in levels:\n                    geos.append(geo)\n            except LocationNotFound as e:\n                log.warn(\"Couldn't find geo that Mapit gave us: %s\" % feature, exc_info=e)\n        return geos",
    "docstring": "Returns a list of geographies containing this point."
  },
  {
    "code": "def content_create(self, key, model, contentid, meta, protected=False):\n        params = {'id': contentid, 'meta': meta}\n        if protected is not False:\n            params['protected'] = 'true'\n        data = urlencode(params)\n        path = PROVISION_MANAGE_CONTENT + model + '/'\n        return self._request(path,\n                             key, data, 'POST', self._manage_by_cik)",
    "docstring": "Creates a content entity bucket with the given `contentid`.\n\n        This method maps to\n        https://github.com/exosite/docs/tree/master/provision#post---create-content-entity.\n\n        Args:\n            key: The CIK or Token for the device\n            model:\n            contentid: The ID used to name the entity bucket\n            meta:\n            protected: Whether or not this is restricted to certain device serial numbers only."
  },
  {
    "code": "def add(self, operator):\n        if not isinstance(operator, Scope):\n            raise ParameterError('Operator {} must be a TaskTransformer '\n                                 'or FeatureExtractor'.format(operator))\n        for key in operator.fields:\n            self._time[key] = []\n            for tdim, idx in enumerate(operator.fields[key].shape, 1):\n                if idx is None:\n                    self._time[key].append(tdim)",
    "docstring": "Add an operator to the Slicer\n\n        Parameters\n        ----------\n        operator : Scope (TaskTransformer or FeatureExtractor)\n            The new operator to add"
  },
  {
    "code": "def configure():\n    log_levels = {\n        5: logging.NOTSET,\n        4: logging.DEBUG,\n        3: logging.INFO,\n        2: logging.WARNING,\n        1: logging.ERROR,\n        0: logging.CRITICAL\n    }\n    logging.captureWarnings(True)\n    root_logger = logging.getLogger()\n    if settings.CFG[\"debug\"]:\n        details_format = logging.Formatter(\n            '%(name)s (%(filename)s:%(lineno)s) [%(levelname)s] %(message)s')\n        details_hdl = logging.StreamHandler()\n        details_hdl.setFormatter(details_format)\n        root_logger.addHandler(details_hdl)\n    else:\n        brief_format = logging.Formatter('%(message)s')\n        console_hdl = logging.StreamHandler()\n        console_hdl.setFormatter(brief_format)\n        root_logger.addHandler(console_hdl)\n    root_logger.setLevel(log_levels[int(settings.CFG[\"verbosity\"])])\n    configure_plumbum_log()\n    configure_migrate_log()\n    configure_parse_log()",
    "docstring": "Load logging configuration from our own defaults."
  },
  {
    "code": "def precision_score(y_true, y_pred, average='micro', suffix=False):\n    true_entities = set(get_entities(y_true, suffix))\n    pred_entities = set(get_entities(y_pred, suffix))\n    nb_correct = len(true_entities & pred_entities)\n    nb_pred = len(pred_entities)\n    score = nb_correct / nb_pred if nb_pred > 0 else 0\n    return score",
    "docstring": "Compute the precision.\n\n    The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of\n    true positives and ``fp`` the number of false positives. The precision is\n    intuitively the ability of the classifier not to label as positive a sample.\n\n    The best value is 1 and the worst value is 0.\n\n    Args:\n        y_true : 2d array. Ground truth (correct) target values.\n        y_pred : 2d array. Estimated targets as returned by a tagger.\n\n    Returns:\n        score : float.\n\n    Example:\n        >>> from seqeval.metrics import precision_score\n        >>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]\n        >>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]\n        >>> precision_score(y_true, y_pred)\n        0.50"
  },
  {
    "code": "def get_status(self):\n        result = ''\n        if self._data_struct is not None:\n            result = self._data_struct[KEY_STATUS]\n        return result",
    "docstring": "Return the status embedded in the JSON error response body,\n        or an empty string if the JSON couldn't be parsed."
  },
  {
    "code": "def _service_by_name(name):\n    services = _available_services()\n    name = name.lower()\n    if name in services:\n        return services[name]\n    for service in six.itervalues(services):\n        if service['file_path'].lower() == name:\n            return service\n        basename, ext = os.path.splitext(service['filename'])\n        if basename.lower() == name:\n            return service\n    return False",
    "docstring": "Return the service info for a service by label, filename or path"
  },
  {
    "code": "def tasks_all_replaced_predicate(\n        service_name,\n        old_task_ids,\n        task_predicate=None\n):\n    try:\n        task_ids = get_service_task_ids(service_name, task_predicate)\n    except DCOSHTTPException:\n        print('failed to get task ids for service {}'.format(service_name))\n        task_ids = []\n    print('waiting for all task ids in \"{}\" to change:\\n- old tasks: {}\\n- current tasks: {}'.format(\n        service_name, old_task_ids, task_ids))\n    for id in task_ids:\n        if id in old_task_ids:\n            return False\n    if len(task_ids) < len(old_task_ids):\n        return False\n    return True",
    "docstring": "Returns whether ALL of old_task_ids have been replaced with new tasks\n\n        :param service_name: the service name\n        :type service_name: str\n        :param old_task_ids: list of original task ids as returned by get_service_task_ids\n        :type old_task_ids: [str]\n        :param task_predicate: filter to use when searching for tasks\n        :type task_predicate: func\n\n        :return: True if none of old_task_ids are still present in the service\n        :rtype: bool"
  },
  {
    "code": "def import_graph(self, t_input=None, scope='import', forget_xy_shape=True):\n    graph = tf.get_default_graph()\n    assert graph.unique_name(scope, False) == scope, (\n        'Scope \"%s\" already exists. Provide explicit scope names when '\n        'importing multiple instances of the model.') % scope\n    t_input, t_prep_input = self.create_input(t_input, forget_xy_shape)\n    tf.import_graph_def(\n        self.graph_def, {self.input_name: t_prep_input}, name=scope)\n    self.post_import(scope)",
    "docstring": "Import model GraphDef into the current graph."
  },
  {
    "code": "def fileMD5(filename, partial=True):\n    filesize = os.path.getsize(filename)\n    md5 = hash_md5()\n    block_size = 2**20\n    try:\n        if (not partial) or filesize < 2**24:\n            with open(filename, 'rb') as f:\n                while True:\n                    data = f.read(block_size)\n                    if not data:\n                        break\n                    md5.update(data)\n        else:\n            count = 16\n            with open(filename, 'rb') as f:\n                while True:\n                    data = f.read(block_size)\n                    count -= 1\n                    if count == 8:\n                        f.seek(-2**23, 2)\n                    if not data or count == 0:\n                        break\n                    md5.update(data)\n    except IOError as e:\n        sys.exit(f'Failed to read {filename}: {e}')\n    return md5.hexdigest()",
    "docstring": "Calculate partial MD5, basically the first and last 8M\n    of the file for large files. This should signicicantly reduce\n    the time spent on the creation and comparison of file signature\n    when dealing with large bioinformat ics datasets."
  },
  {
    "code": "def _find_file_meta(metadata, bucket_name, saltenv, path):\n    env_meta = metadata[saltenv] if saltenv in metadata else {}\n    bucket_meta = {}\n    for bucket in env_meta:\n        if bucket_name in bucket:\n            bucket_meta = bucket[bucket_name]\n    files_meta = list(list(filter((lambda k: 'Key' in k), bucket_meta)))\n    for item_meta in files_meta:\n        if 'Key' in item_meta and item_meta['Key'] == path:\n            try:\n                item_meta['ETag'] = item_meta['ETag'].strip('\"')\n            except KeyError:\n                pass\n            return item_meta",
    "docstring": "Looks for a file's metadata in the S3 bucket cache file"
  },
  {
    "code": "def copymode(self, target):\n        shutil.copymode(self.path, self._to_backend(target))",
    "docstring": "Copies the mode of this file on the `target` file.\n\n        The owner is not copied."
  },
  {
    "code": "def _add_example_helper(self, example):\n        for label, example_field in example.fields.items():\n            if not any(label == f.name for f in self.all_fields):\n                raise InvalidSpec(\n                    \"Example for '%s' has unknown field '%s'.\" %\n                    (self.name, label),\n                    example_field.lineno, example_field.path,\n                )\n        for field in self.all_fields:\n            if field.name in example.fields:\n                example_field = example.fields[field.name]\n                try:\n                    field.data_type.check_example(example_field)\n                except InvalidSpec as e:\n                    e.msg = \"Bad example for field '{}': {}\".format(\n                        field.name, e.msg)\n                    raise\n            elif field.has_default or isinstance(field.data_type, Nullable):\n                pass\n            else:\n                raise InvalidSpec(\n                    \"Missing field '%s' in example.\" % field.name,\n                    example.lineno, example.path)\n        self._raw_examples[example.label] = example",
    "docstring": "Validates examples for structs without enumerated subtypes."
  },
  {
    "code": "def rowsum_stdev(x, beta):\n    r\n    n = x.size\n    betabar = (1.0/n) * np.dot(x, beta)\n    stdev = np.sqrt((1.0/n) *\n                    np.sum(np.power(np.multiply(x, beta) - betabar, 2)))\n    return stdev/betabar",
    "docstring": "r\"\"\"Compute row sum standard deviation.\n\n    Compute for approximation x, the std dev of the row sums\n    s(x) = ( 1/n \\sum_k  (x_k beta_k - betabar)^2 )^(1/2)\n    with betabar = 1/n dot(beta,x)\n\n    Parameters\n    ----------\n    x : array\n    beta : array\n\n    Returns\n    -------\n    s(x)/betabar : float\n\n    Notes\n    -----\n    equation (7) in Livne/Golub"
  },
  {
    "code": "def extract_references_from_string(source,\n                                   is_only_references=True,\n                                   recid=None,\n                                   reference_format=\"{title} {volume} ({year}) {page}\",\n                                   linker_callback=None,\n                                   override_kbs_files=None):\n    docbody = source.split('\\n')\n    if not is_only_references:\n        reflines, dummy, dummy = extract_references_from_fulltext(docbody)\n    else:\n        refs_info = get_reference_section_beginning(docbody)\n        if not refs_info:\n            refs_info, dummy = find_numeration_in_body(docbody)\n            refs_info['start_line'] = 0\n            refs_info['end_line'] = len(docbody) - 1,\n        reflines = rebuild_reference_lines(\n            docbody, refs_info['marker_pattern'])\n    parsed_refs, stats = parse_references(\n        reflines,\n        recid=recid,\n        reference_format=reference_format,\n        linker_callback=linker_callback,\n        override_kbs_files=override_kbs_files,\n    )\n    return parsed_refs",
    "docstring": "Extract references from a raw string.\n\n    The first parameter is the path to the file.\n    It returns a tuple (references, stats).\n\n    If the string does not only contain references, improve accuracy by\n    specifing ``is_only_references=False``.\n\n    The standard reference format is: {title} {volume} ({year}) {page}.\n\n    E.g. you can change that by passing the reference_format:\n\n    >>> extract_references_from_string(path, reference_format=\"{title},{volume},{page}\")\n\n    If you want to also link each reference to some other resource (like a record),\n    you can provide a linker_callback function to be executed for every reference\n    element found.\n\n    To override KBs for journal names etc., use ``override_kbs_files``:\n\n    >>> extract_references_from_string(path, override_kbs_files={'journals': 'my/path/to.kb'})"
  },
  {
    "code": "def markers(self, values):\n        if not isinstance(values, list):\n            raise TypeError(\"Markers must be a list of objects\")\n        self.options[\"markers\"] = values",
    "docstring": "Set the markers.\n\n            Args:\n                values (list): list of marker objects.\n\n            Raises:\n                ValueError: Markers must be a list of objects."
  },
  {
    "code": "def getOPOrUserServices(openid_services):\n    op_services = arrangeByType(openid_services, [OPENID_IDP_2_0_TYPE])\n    openid_services = arrangeByType(openid_services,\n                                    OpenIDServiceEndpoint.openid_type_uris)\n    return op_services or openid_services",
    "docstring": "Extract OP Identifier services.  If none found, return the\n    rest, sorted with most preferred first according to\n    OpenIDServiceEndpoint.openid_type_uris.\n\n    openid_services is a list of OpenIDServiceEndpoint objects.\n\n    Returns a list of OpenIDServiceEndpoint objects."
  },
  {
    "code": "def _filter_sources(self, sources):\n        filtered, hosts = [], []\n        for source in sources:\n            if 'error' in source:\n                continue\n            filtered.append(source)\n            hosts.append(source['host_name'])\n        return sorted(filtered, key=lambda s:\n                      self._hosts_by_success(hosts).index(s['host_name']))",
    "docstring": "Remove sources with errors and return ordered by host success.\n\n        :param sources: List of potential sources to connect to.\n        :type sources: list\n        :returns: Sorted list of potential sources without errors.\n        :rtype: list"
  },
  {
    "code": "def verify_month(self, now):\n        return self.month == \"*\" or str(now.month) in self.month.split(\" \")",
    "docstring": "Verify the month"
  },
  {
    "code": "def _peek(tokens, n=0):\n    return tokens.peek(n=n, skip=_is_comment, drop=True)",
    "docstring": "peek and drop comments"
  },
  {
    "code": "def __set_name(self, value):\n        if not value or not len(value):\n            raise ValueError(\"Invalid name.\")\n        self.__name = value",
    "docstring": "Sets the name of the treatment.\n        @param value:str"
  },
  {
    "code": "def setbpf(self, bpf):\n        self._bpf = min(bpf, self.BPF)\n        self._rng_n = int((self._bpf + self.RNG_RANGE_BITS - 1) / self.RNG_RANGE_BITS)",
    "docstring": "Set number of bits per float output"
  },
  {
    "code": "def OpenFileObject(cls, path_spec_object, resolver_context=None):\n    if not isinstance(path_spec_object, path_spec.PathSpec):\n      raise TypeError('Unsupported path specification type.')\n    if resolver_context is None:\n      resolver_context = cls._resolver_context\n    if path_spec_object.type_indicator == definitions.TYPE_INDICATOR_MOUNT:\n      if path_spec_object.HasParent():\n        raise errors.PathSpecError(\n            'Unsupported mount path specification with parent.')\n      mount_point = getattr(path_spec_object, 'identifier', None)\n      if not mount_point:\n        raise errors.PathSpecError(\n            'Unsupported path specification without mount point identifier.')\n      path_spec_object = mount_manager.MountPointManager.GetMountPoint(\n          mount_point)\n      if not path_spec_object:\n        raise errors.MountPointError(\n            'No such mount point: {0:s}'.format(mount_point))\n    file_object = resolver_context.GetFileObject(path_spec_object)\n    if not file_object:\n      resolver_helper = cls._GetResolverHelper(path_spec_object.type_indicator)\n      file_object = resolver_helper.NewFileObject(resolver_context)\n    file_object.open(path_spec=path_spec_object)\n    return file_object",
    "docstring": "Opens a file-like object defined by path specification.\n\n    Args:\n      path_spec_object (PathSpec): path specification.\n      resolver_context (Optional[Context]): resolver context, where None\n          represents the built in context which is not multi process safe.\n\n    Returns:\n      FileIO: file-like object or None if the path specification could not\n          be resolved.\n\n    Raises:\n      PathSpecError: if the path specification is incorrect.\n      TypeError: if the path specification type is unsupported."
  },
  {
    "code": "def comment_set(self):\n        ct = ContentType.objects.get_for_model(self.__class__)\n        qs = Comment.objects.filter(\n            content_type=ct,\n            object_pk=self.pk)\n        qs = qs.exclude(is_removed=True)\n        qs = qs.order_by('-submit_date')\n        return qs",
    "docstring": "Get the comments that have been submitted for the chat"
  },
  {
    "code": "def mosaic_info(name, pretty):\n    cl = clientv1()\n    echo_json_response(call_and_wrap(cl.get_mosaic_by_name, name), pretty)",
    "docstring": "Get information for a specific mosaic"
  },
  {
    "code": "def get_tags_of_recurring_per_page(self, recurring_id, per_page=1000, page=1):\n        return self._get_resource_per_page(\n            resource=RECURRING_TAGS,\n            per_page=per_page,\n            page=page,\n            params={'recurring_id': recurring_id},\n        )",
    "docstring": "Get tags of recurring per page\n\n        :param recurring_id: the recurring id\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :return: list"
  },
  {
    "code": "def clean_already_reported(self, comments, file_name, position,\n                               message):\n        for comment in comments:\n            if ((comment['path'] == file_name and\n                 comment['position'] == position and\n                 comment['user']['login'] == self.requester.username)):\n                return [m for m in message if m not in comment['body']]\n        return message",
    "docstring": "message is potentially a list of messages to post. This is later\n        converted into a string."
  },
  {
    "code": "def process_queue(queue=None, **kwargs):\n    while True:\n        item = queue.get()\n        if item is None:\n            queue.task_done()\n            logger.info(f\"{queue}: exiting process queue.\")\n            break\n        filename = os.path.basename(item)\n        try:\n            queue.next_task(item, **kwargs)\n        except Exception as e:\n            queue.task_done()\n            logger.warn(f\"{queue}: item={filename}. {e}\\n\")\n            logger.exception(e)\n            sys.stdout.write(\n                style.ERROR(\n                    f\"{queue}. item={filename}. {e}. Exception has been logged.\\n\"\n                )\n            )\n            sys.stdout.flush()\n            break\n        else:\n            logger.info(f\"{queue}: Successfully processed {filename}.\\n\")\n        queue.task_done()",
    "docstring": "Loops and waits on queue calling queue's `next_task` method.\n\n    If an exception occurs, log the error, log the exception,\n    and break."
  },
  {
    "code": "def set(self, key, value):\n        changed = super().set(key=key, value=value)\n        if not changed:\n            return False\n        self._log.info('Saving configuration to \"%s\"...', self._filename)\n        with open(self._filename, 'w') as stream:\n            stream.write(self.content)\n            self._log.info('Saved configuration to \"%s\".', self._filename)\n        return True",
    "docstring": "Updates the value of the given key in the file.\n\n        Args:\n            key (str): Key of the property to update.\n            value (str): New value of the property.\n\n        Return:\n            bool: Indicates whether or not a change was made."
  },
  {
    "code": "def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]:\n    if unit.lower() not in units:\n        raise ValueError(\n            \"Unknown unit.  Must be one of {0}\".format(\"/\".join(units.keys()))\n        )\n    if number == 0:\n        return 0\n    if number < MIN_WEI or number > MAX_WEI:\n        raise ValueError(\"value must be between 1 and 2**256 - 1\")\n    unit_value = units[unit.lower()]\n    with localcontext() as ctx:\n        ctx.prec = 999\n        d_number = decimal.Decimal(value=number, context=ctx)\n        result_value = d_number / unit_value\n    return result_value",
    "docstring": "Takes a number of wei and converts it to any other ether unit."
  },
  {
    "code": "def get_anki_phrases_english(limit=None):\n    texts = set()\n    for lang in ANKI_LANGUAGES:\n        df = get_data(lang)\n        phrases = df.eng.str.strip().values\n        texts = texts.union(set(phrases))\n        if limit and len(texts) >= limit:\n            break\n    return sorted(texts)",
    "docstring": "Return all the English phrases in the Anki translation flashcards \n\n    >>> len(get_anki_phrases_english(limit=100)) > 700\n    True"
  },
  {
    "code": "def get_ssl(self, host_and_port=None):\n        if not host_and_port:\n            host_and_port = self.current_host_and_port\n        return self.__ssl_params.get(host_and_port)",
    "docstring": "Get SSL params for the given host.\n\n        :param (str,int) host_and_port: the host/port pair we want SSL params for, default current_host_and_port"
  },
  {
    "code": "def search(self):\n        for cb in SearchUrl.search_callbacks:\n            try:\n                v = cb(self)\n                if v is not None:\n                    return v\n            except Exception as e:\n                raise",
    "docstring": "Search for a url by returning the value from the first callback that\n        returns a non-None value"
  },
  {
    "code": "def wait_for_signal(self, timeout=None):\n\t\ttimeout_ms = int(timeout * 1000) if timeout else win32event.INFINITE\n\t\twin32event.WaitForSingleObject(self.signal_event, timeout_ms)",
    "docstring": "wait for the signal; return after the signal has occurred or the\n\t\ttimeout in seconds elapses."
  },
  {
    "code": "def publish(self, artifact):\n        self.env.add_artifact(artifact)\n        self._log(logging.DEBUG, \"Published {} to domain.\".format(artifact))",
    "docstring": "Publish artifact to agent's environment.\n\n        :param artifact: artifact to be published\n        :type artifact: :py:class:`~creamas.core.artifact.Artifact`"
  },
  {
    "code": "def entity_to_protobuf(entity):\n    entity_pb = entity_pb2.Entity()\n    if entity.key is not None:\n        key_pb = entity.key.to_protobuf()\n        entity_pb.key.CopyFrom(key_pb)\n    for name, value in entity.items():\n        value_is_list = isinstance(value, list)\n        value_pb = _new_value_pb(entity_pb, name)\n        _set_protobuf_value(value_pb, value)\n        if name in entity.exclude_from_indexes:\n            if not value_is_list:\n                value_pb.exclude_from_indexes = True\n            for sub_value in value_pb.array_value.values:\n                sub_value.exclude_from_indexes = True\n        _set_pb_meaning_from_entity(\n            entity, name, value, value_pb, is_list=value_is_list\n        )\n    return entity_pb",
    "docstring": "Converts an entity into a protobuf.\n\n    :type entity: :class:`google.cloud.datastore.entity.Entity`\n    :param entity: The entity to be turned into a protobuf.\n\n    :rtype: :class:`.entity_pb2.Entity`\n    :returns: The protobuf representing the entity."
  },
  {
    "code": "def extract_followups(task):\n    callbacks = task.request.callbacks\n    errbacks = task.request.errbacks\n    task.request.callbacks = None\n    return {'link': callbacks, 'link_error': errbacks}",
    "docstring": "Retrieve callbacks and errbacks from provided task instance, disables\n    tasks callbacks."
  },
  {
    "code": "def to_ufo_family_user_data(self, ufo):\n    if not self.use_designspace:\n        ufo.lib[FONT_USER_DATA_KEY] = dict(self.font.userData)",
    "docstring": "Set family-wide user data as Glyphs does."
  },
  {
    "code": "def read_electrodes(self, electrodes):\n        for nr, electrode in enumerate(electrodes):\n            index = self.get_point_id(\n                electrode, self.char_lengths['electrode'])\n            self.Electrodes.append(index)",
    "docstring": "Read in electrodes, check if points already exist"
  },
  {
    "code": "def read_json_flag(fobj):\n    if isinstance(fobj, string_types):\n        with open(fobj, 'r') as fobj2:\n            return read_json_flag(fobj2)\n    txt = fobj.read()\n    if isinstance(txt, bytes):\n        txt = txt.decode('utf-8')\n    data = json.loads(txt)\n    name = '{ifo}:{name}:{version}'.format(**data)\n    out = DataQualityFlag(name, active=data['active'],\n                          known=data['known'])\n    try:\n        out.description = data['metadata'].get('flag_description', None)\n    except KeyError:\n        pass\n    else:\n        out.isgood = not data['metadata'].get(\n            'active_indicates_ifo_badness', False)\n    return out",
    "docstring": "Read a `DataQualityFlag` from a segments-web.ligo.org JSON file"
  },
  {
    "code": "def get_lyrics_letssingit(song_name):\n    lyrics = \"\"\n    url = \"http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=\" + \\\n        quote(song_name.encode('utf-8'))\n    html = urlopen(url).read()\n    soup = BeautifulSoup(html, \"html.parser\")\n    link = soup.find('a', {'class': 'high_profile'})\n    try:\n        link = link.get('href')\n        link = urlopen(link).read()\n        soup = BeautifulSoup(link, \"html.parser\")\n        try:\n            lyrics = soup.find('div', {'id': 'lyrics'}).text\n            lyrics = lyrics[3:]\n        except AttributeError:\n            lyrics = \"\"\n    except:\n        lyrics = \"\"\n    return lyrics",
    "docstring": "Scrapes the lyrics of a song since spotify does not provide lyrics\n    takes song title as arguement"
  },
  {
    "code": "def _construct_request(self):\n        if self.parsed_endpoint.scheme == 'https':\n            conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc)\n        else:\n            conn = httplib.HTTPConnection(self.parsed_endpoint.netloc)\n        head = {\n            \"Accept\": \"application/json\",\n            \"User-Agent\": USER_AGENT,\n            API_TOKEN_HEADER_NAME: self.api_token,\n        }\n        if self.api_version in ['0.1', '0.01a']:\n            head[API_VERSION_HEADER_NAME] = self.api_version\n        return conn, head",
    "docstring": "Utility for constructing the request header and connection"
  },
  {
    "code": "def create_map(self, pix):\n        k0 = self._m0.shift_to_coords(pix)\n        k1 = self._m1.shift_to_coords(pix)\n        k0[np.isfinite(k1)] = k1[np.isfinite(k1)]\n        k0[~np.isfinite(k0)] = 0\n        return k0",
    "docstring": "Create a new map with reference pixel coordinates shifted\n        to the pixel coordinates ``pix``.\n\n        Parameters\n        ----------\n        pix : `~numpy.ndarray`\n            Reference pixel of new map.\n\n        Returns\n        -------\n        out_map : `~numpy.ndarray`\n            The shifted map."
  },
  {
    "code": "def topics(self, exclude_internal_topics=True):\n        topics = set(self._partitions.keys())\n        if exclude_internal_topics:\n            return topics - self.internal_topics\n        else:\n            return topics",
    "docstring": "Get set of known topics.\n\n        Arguments:\n            exclude_internal_topics (bool): Whether records from internal topics\n                (such as offsets) should be exposed to the consumer. If set to\n                True the only way to receive records from an internal topic is\n                subscribing to it. Default True\n\n        Returns:\n            set: {topic (str), ...}"
  },
  {
    "code": "def show_popup(self, *args, **kwargs):\n        self.mw = JB_MainWindow(parent=self, flags=QtCore.Qt.Dialog)\n        self.mw.setWindowTitle(self.popuptitle)\n        self.mw.setWindowModality(QtCore.Qt.ApplicationModal)\n        w = QtGui.QWidget()\n        self.mw.setCentralWidget(w)\n        vbox = QtGui.QVBoxLayout(w)\n        pte = QtGui.QPlainTextEdit()\n        pte.setPlainText(self.get_popup_text())\n        vbox.addWidget(pte)\n        d = self.cursor().pos() - self.mw.mapToGlobal(self.mw.pos())\n        self.mw.move(d)\n        self.mw.show()",
    "docstring": "Show a popup with a textedit\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def _get_op_name(op, special):\n    opname = op.__name__.strip('_')\n    if special:\n        opname = '__{opname}__'.format(opname=opname)\n    return opname",
    "docstring": "Find the name to attach to this method according to conventions\n    for special and non-special methods.\n\n    Parameters\n    ----------\n    op : binary operator\n    special : bool\n\n    Returns\n    -------\n    op_name : str"
  },
  {
    "code": "def get_word(byte_iterator):\n    byte_values = list(itertools.islice(byte_iterator, 2))\n    try:\n        word = (byte_values[0] << 8) | byte_values[1]\n    except TypeError, err:\n        raise TypeError(\"Can't build word from %s: %s\" % (repr(byte_values), err))\n    return word",
    "docstring": "return a uint16 value\n\n    >>> g=iter([0x1e, 0x12])\n    >>> v=get_word(g)\n    >>> v\n    7698\n    >>> hex(v)\n    '0x1e12'"
  },
  {
    "code": "def _openResources(self):\n        arr = self._fun()\n        check_is_an_array(arr)\n        self._array = arr",
    "docstring": "Evaluates the function to result an array"
  },
  {
    "code": "def get_setting_with_envfallback(setting, default=None, typecast=None):\n    try:\n        from django.conf import settings\n    except ImportError:\n        return default\n    else:\n        fallback = getattr(settings, setting, default)\n        value = os.environ.get(setting, fallback)\n        if typecast:\n            value = typecast(value)\n        return value",
    "docstring": "Get the given setting and fall back to the default of not found in\n    ``django.conf.settings`` or ``os.environ``.\n\n    :param settings: The setting as a string.\n    :param default: The fallback if ``setting`` is not found.\n    :param typecast:\n        A function that converts the given value from string to another type.\n        E.g.: Use ``typecast=int`` to convert the value to int before returning."
  },
  {
    "code": "def _print_fields(self, fields):\n        longest_name = max(fields, key=lambda f: len(f[1]))[1]\n        longest_type = max(fields, key=lambda f: len(f[2]))[2]\n        field_format = '%s%-{}s %-{}s %s'.format(\n            len(longest_name) + self._padding_after_name,\n            len(longest_type) + self._padding_after_type)\n        for field in fields:\n            self._print(field_format % field)",
    "docstring": "Print the fields, padding the names as necessary to align them."
  },
  {
    "code": "def mark_fit_good(self, fit, spec=None):\n        if spec == None:\n            for spec, fits in list(self.pmag_results_data['specimens'].items()):\n                if fit in fits:\n                    break\n        samp = self.Data_hierarchy['sample_of_specimen'][spec]\n        if 'sample_orientation_flag' not in self.Data_info['er_samples'][samp]:\n            self.Data_info['er_samples'][samp]['sample_orientation_flag'] = 'g'\n        samp_flag = self.Data_info['er_samples'][samp]['sample_orientation_flag']\n        if samp_flag == 'g':\n            self.bad_fits.remove(fit)\n            return True\n        else:\n            self.user_warning(\n                \"Cannot mark this interpretation good its sample orientation has been marked bad\")\n            return False",
    "docstring": "Marks fit good so it is used in high level means\n\n        Parameters\n        ----------\n        fit : fit to mark good\n        spec : specimen of fit to mark good (optional though runtime will\n            increase if not provided)"
  },
  {
    "code": "def mean_by_panel(self, length):\n        self._check_panel(length)\n        func = lambda v: v.reshape(-1, length).mean(axis=0)\n        newindex = arange(length)\n        return self.map(func, index=newindex)",
    "docstring": "Compute the mean across fixed sized panels of each record.\n\n        Splits each record into panels of size `length`,\n        and then computes the mean across panels.\n        Panel length must subdivide record exactly.\n\n        Parameters\n        ----------\n        length : int\n            Fixed length with which to subdivide."
  },
  {
    "code": "def process_object(obj):\n    \"Hook to process the object currently being displayed.\"\n    invalid_options = OptsMagic.process_element(obj)\n    if invalid_options: return invalid_options\n    OutputMagic.info(obj)",
    "docstring": "Hook to process the object currently being displayed."
  },
  {
    "code": "def creditusage(cls):\n        rating = cls.call('hosting.rating.list')\n        if not rating:\n            return 0\n        rating = rating.pop()\n        usage = [sum(resource.values())\n                 for resource in rating.values()\n                 if isinstance(resource, dict)]\n        return sum(usage)",
    "docstring": "Get credit usage per hour"
  },
  {
    "code": "def update_subject_identifier_on_save(self):\n        if not self.subject_identifier:\n            self.subject_identifier = self.subject_identifier_as_pk.hex\n        elif re.match(UUID_PATTERN, self.subject_identifier):\n            pass\n        return self.subject_identifier",
    "docstring": "Overridden to not set the subject identifier on save."
  },
  {
    "code": "def main():\n    parser = argparse.ArgumentParser(\n        description='Tool for testing caffe to mxnet conversion layer by layer')\n    parser.add_argument('--image_url', type=str,\n                        default='https://github.com/dmlc/web-data/raw/master/mxnet/doc/'\\\n                                'tutorials/python/predict_image/cat.jpg',\n                        help='input image to test inference, can be either file path or url')\n    parser.add_argument('--caffe_prototxt_path', type=str,\n                        default='./model.prototxt',\n                        help='path to caffe prototxt')\n    parser.add_argument('--caffe_model_path', type=str,\n                        default='./model.caffemodel',\n                        help='path to caffe weights')\n    parser.add_argument('--caffe_mean', type=str,\n                        default='./model_mean.binaryproto',\n                        help='path to caffe mean file')\n    parser.add_argument('--mean_diff_allowed', type=int, default=1e-03,\n                        help='mean difference allowed between caffe blob and mxnet blob')\n    parser.add_argument('--max_diff_allowed', type=int, default=1e-01,\n                        help='max difference allowed between caffe blob and mxnet blob')\n    parser.add_argument('--gpu', type=int, default=-1, help='the gpu id used for predict')\n    args = parser.parse_args()\n    convert_and_compare_caffe_to_mxnet(args.image_url, args.gpu, args.caffe_prototxt_path,\n                                       args.caffe_model_path, args.caffe_mean,\n                                       args.mean_diff_allowed, args.max_diff_allowed)",
    "docstring": "Entrypoint for compare_layers"
  },
  {
    "code": "def export_to_directory_crtomo(self, directory, norrec='norrec'):\n        exporter_crtomo.write_files_to_directory(\n            self.data, directory, norrec=norrec\n        )",
    "docstring": "Export the sEIT data into data files that can be read by CRTomo.\n\n        Parameters\n        ----------\n        directory : string\n            output directory. will be created if required\n        norrec : string (nor|rec|norrec)\n            Which data to export. Default: norrec"
  },
  {
    "code": "def _validateSetting(value, policy):\n    log.debug('validating %s for policy %s', value, policy)\n    if 'Settings' in policy:\n        if policy['Settings']:\n            if isinstance(policy['Settings'], list):\n                if value not in policy['Settings']:\n                    return False\n            elif isinstance(policy['Settings'], dict):\n                _policydata = _policy_info()\n                if not getattr(_policydata, policy['Settings']['Function'])(value, **policy['Settings']['Args']):\n                    return False\n    else:\n        return True\n    return True",
    "docstring": "helper function to validate specified value is appropriate for the policy\n    if the 'Settings' key is a list, the value will check that it is in the list\n    if the 'Settings' key is a dict we will try to execute the function name\n        from the 'Function' key, passing the value and additional arguments from\n        the 'Args' dict\n    if the 'Settings' key is None, we won't do any validation and just return\n        True\n    if the Policy has 'Children', we'll validate their settings too"
  },
  {
    "code": "def _maybe_add_conditions_to_implicit_api_paths(self, template):\n        for api_id, api in template.iterate(SamResourceType.Api.value):\n            if not api.properties.get('__MANAGE_SWAGGER'):\n                continue\n            swagger = api.properties.get(\"DefinitionBody\")\n            editor = SwaggerEditor(swagger)\n            for path in editor.iter_on_path():\n                all_method_conditions = set(\n                    [condition for method, condition in self.api_conditions[api_id][path].items()]\n                )\n                at_least_one_method = len(all_method_conditions) > 0\n                all_methods_contain_conditions = None not in all_method_conditions\n                if at_least_one_method and all_methods_contain_conditions:\n                    if len(all_method_conditions) == 1:\n                        editor.make_path_conditional(path, all_method_conditions.pop())\n                    else:\n                        path_condition_name = self._path_condition_name(api_id, path)\n                        self._add_combined_condition_to_template(\n                            template.template_dict, path_condition_name, all_method_conditions)\n                        editor.make_path_conditional(path, path_condition_name)\n            api.properties[\"DefinitionBody\"] = editor.swagger\n            template.set(api_id, api)",
    "docstring": "Add conditions to implicit API paths if necessary.\n\n        Implicit API resource methods are constructed from API events on individual serverless functions within the SAM\n        template. Since serverless functions can have conditions on them, it's possible to have a case where all methods\n        under a resource path have conditions on them. If all of these conditions evaluate to false, the entire resource\n        path should not be defined either. This method checks all resource paths' methods and if all methods under a\n        given path contain a condition, a composite condition is added to the overall template Conditions section and\n        that composite condition is added to the resource path."
  },
  {
    "code": "def salt_run():\n    import salt.cli.run\n    if '' in sys.path:\n        sys.path.remove('')\n    client = salt.cli.run.SaltRun()\n    _install_signal_handlers(client)\n    client.run()",
    "docstring": "Execute a salt convenience routine."
  },
  {
    "code": "def load_library_handle(libname, path):\n    if path is None or path in ['None', 'none']:\n        return None\n    try:\n        if os.name == \"nt\":\n            opj_lib = ctypes.windll.LoadLibrary(path)\n        else:\n            opj_lib = ctypes.CDLL(path)\n    except (TypeError, OSError):\n        msg = 'The {libname} library at {path} could not be loaded.'\n        msg = msg.format(path=path, libname=libname)\n        warnings.warn(msg, UserWarning)\n        opj_lib = None\n    return opj_lib",
    "docstring": "Load the library, return the ctypes handle."
  },
  {
    "code": "def _frame_generator(self, frame_duration_ms, audio, sample_rate):\n        n = int(sample_rate * (frame_duration_ms / 1000.0) * 2)\n        offset = 0\n        timestamp = 0.0\n        duration = (float(n) / sample_rate) / 2.0\n        while offset + n < len(audio):\n            yield self.Frame(audio[offset:offset + n], timestamp, duration)\n            timestamp += duration\n            offset += n",
    "docstring": "Generates audio frames from PCM audio data.\n        Takes the desired frame duration in milliseconds, the PCM data, and\n        the sample rate.\n        Yields Frames of the requested duration."
  },
  {
    "code": "def round_to_nearest(number, nearest=1):\n    result = nearest * round(number / nearest)\n    if result % 1 == 0:\n        return int(result)\n    if nearest % 1 == 0:\n        return round(result)\n    if nearest % 0.1 == 0:\n        return round(result, 1)\n    if nearest % 0.01 == 0:\n        return round(result, 2)\n    return result",
    "docstring": "Round 'number' to the nearest multiple of 'nearest'.\n\n    Parameters\n    ----------\n    number\n        A real number to round.\n    nearest\n        Number to round to closes multiple of.\n\n    Returns\n    -------\n    rounded\n        A rounded number.\n\n\n    Examples\n    -------\n    >>> round_to_nearest(6.8, nearest = 2.5)\n    7.5"
  },
  {
    "code": "def read_pid_stat(pid):\n    return {\n        \"utime\": random.randint(0, 999999999),\n        \"stime\": random.randint(0, 999999999),\n        \"cutime\": random.randint(0, 999999999),\n        \"cstime\": random.randint(0, 999999999),\n    }",
    "docstring": "Mocks read_pid_stat as this is a Linux-specific operation."
  },
  {
    "code": "def run(self):\n        with util.timed_block() as t:\n            files = self._collect_files()\n        log.info(\"Collected <33>{} <32>files in <33>{}s\".format(\n            len(files), t.elapsed_s\n        ))\n        if self.verbose:\n            for p in files:\n                log.info(\"  <0>{}\", p)\n        if not files:\n            return self.allow_empty\n        with util.timed_block() as t:\n            results = self._run_checks(files)\n        log.info(\"Code checked in <33>{}s\", t.elapsed_s)\n        success = True\n        for name, retcodes in results.items():\n            if any(x != 0 for x in retcodes):\n                success = False\n                log.err(\"<35>{} <31>failed with: <33>{}\".format(\n                    name, retcodes\n                ))\n        return success",
    "docstring": "Run all linters and report results.\n\n        Returns:\n            bool: **True** if all checks were successful, **False** otherwise."
  },
  {
    "code": "def download_file_with_progress_bar(url):\n    request = requests.get(url, stream=True)\n    if request.status_code == 404:\n        msg = ('there was a 404 error trying to reach {} \\nThis probably '\n               'means the requested version does not exist.'.format(url))\n        logger.error(msg)\n        sys.exit()\n    total_size = int(request.headers[\"Content-Length\"])\n    chunk_size = 1024\n    bars = int(total_size / chunk_size)\n    bytes_io = io.BytesIO()\n    pbar = tqdm(request.iter_content(chunk_size=chunk_size), total=bars,\n                unit=\"kb\", leave=False)\n    for chunk in pbar:\n        bytes_io.write(chunk)\n    return bytes_io",
    "docstring": "Downloads a file from the given url, displays \n    a progress bar.\n    Returns a io.BytesIO object"
  },
  {
    "code": "def focus0(self):\n        f = Point(self.center)\n        if self.xAxisIsMajor:\n            f.x -= self.linearEccentricity\n        else:\n            f.y -= self.linearEccentricity\n        return f",
    "docstring": "First focus of the ellipse, Point class."
  },
  {
    "code": "def increment_name(self, name, i):\n        if i == 0:\n            return name\n        if '.' in name:\n            split = name.split('.')\n            split[-2] = split[-2] + str(i)\n            return '.'.join(split)\n        else:\n            return name + str(i)",
    "docstring": "takes something like\n            test.txt\n        and returns\n            test1.txt"
  },
  {
    "code": "def children(self) -> NodeList:\n        return NodeList([e for e in self.childNodes\n                         if e.nodeType == Node.ELEMENT_NODE])",
    "docstring": "Return list of child nodes.\n\n        Currently this is not a live object."
  },
  {
    "code": "def name_to_int(name):\n    if not name:\n        return float('nan')\n    lower = name.lower()\n    cga_names = {s: i for i, s in enumerate(colour_names.cga())}\n    return cga_names.get(lower) or html_to_small_ansi(lower)",
    "docstring": "Get a number for that colour name\n\n    if not a name, then not a number"
  },
  {
    "code": "def twitter_credential(name):\n    credential_name = 'TWITTER_' + name.upper()\n    if hasattr(settings, credential_name):\n        return getattr(settings, credential_name)\n    else:\n        raise AttributeError('Missing twitter credential in settings: ' + credential_name)",
    "docstring": "Grab twitter credential from settings"
  },
  {
    "code": "def parse(self, filelike, filename):\n        self.log = log\n        self.source = filelike.readlines()\n        src = ''.join(self.source)\n        try:\n            compile(src, filename, 'exec')\n        except SyntaxError as error:\n            raise ParseError() from error\n        self.stream = TokenStream(StringIO(src))\n        self.filename = filename\n        self.dunder_all = None\n        self.dunder_all_error = None\n        self.future_imports = set()\n        self._accumulated_decorators = []\n        return self.parse_module()",
    "docstring": "Parse the given file-like object and return its Module object."
  },
  {
    "code": "def validate_link(link_data):\n    from django.apps import apps\n    try:\n        Model = apps.get_model(*link_data['model'].split('.'))\n        Model.objects.get(pk=link_data['pk'])\n    except Model.DoesNotExist:\n        raise ValidationError(_(\"Unable to link onto '{0}'.\").format(Model.__name__))",
    "docstring": "Check if the given model exists, otherwise raise a Validation error"
  },
  {
    "code": "def list_build_records(page_size=200, page_index=0, sort=\"\", q=\"\"):\n    data = list_build_records_raw(page_size, page_index, sort, q)\n    if data:\n        return utils.format_json_list(data)",
    "docstring": "List all BuildRecords"
  },
  {
    "code": "def vote(self, candidates):\n        ranks = [(c, self.evaluate(c)[0]) for c in candidates]\n        ranks.sort(key=operator.itemgetter(1), reverse=True)\n        return ranks",
    "docstring": "Rank artifact candidates.\n\n        The voting is needed for the agents living in societies using\n        social decision making. The function should return a sorted list\n        of (candidate, evaluation)-tuples. Depending on the social choice\n        function used, the evaluation might be omitted from the actual decision\n        making, or only a number of (the highest ranking) candidates may be\n        used.\n\n        This basic implementation ranks candidates based on\n        :meth:`~creamas.core.agent.CreativeAgent.evaluate`.\n\n        :param candidates:\n            list of :py:class:`~creamas.core.artifact.Artifact` objects to be\n            ranked\n\n        :returns:\n            Ordered list of (candidate, evaluation)-tuples"
  },
  {
    "code": "def service_response(body, headers, status_code):\n        response = Response(body)\n        response.headers = headers\n        response.status_code = status_code\n        return response",
    "docstring": "Constructs a Flask Response from the body, headers, and status_code.\n\n        :param str body: Response body as a string\n        :param dict headers: headers for the response\n        :param int status_code: status_code for response\n        :return: Flask Response"
  },
  {
    "code": "def set_refresh_rate(self, fps):\n        self.rf_fps = fps\n        self.rf_rate = 1.0 / self.rf_fps\n        self.logger.info(\"set a refresh rate of %.2f fps\" % (self.rf_fps))",
    "docstring": "Set the refresh rate for redrawing the canvas at a timed interval.\n\n        Parameters\n        ----------\n        fps : float\n            Desired rate in frames per second."
  },
  {
    "code": "def merge_from(self, other):\n        if other.pattern is not None:\n            self.pattern = other.pattern\n        if other.format is not None:\n            self.format = other.format\n        self.leading_digits_pattern.extend(other.leading_digits_pattern)\n        if other.national_prefix_formatting_rule is not None:\n            self.national_prefix_formatting_rule = other.national_prefix_formatting_rule\n        if other.national_prefix_optional_when_formatting is not None:\n            self.national_prefix_optional_when_formatting = other.national_prefix_optional_when_formatting\n        if other.domestic_carrier_code_formatting_rule is not None:\n            self.domestic_carrier_code_formatting_rule = other.domestic_carrier_code_formatting_rule",
    "docstring": "Merge information from another NumberFormat object into this one."
  },
  {
    "code": "def _handle_tag_csmtextsettings(self):\n        obj = _make_object(\"CSMTextSettings\")\n        obj.TextId = unpack_ui16(self._src)\n        bc = BitConsumer(self._src)\n        obj.UseFlashType = bc.u_get(2)\n        obj.GridFit = bc.u_get(3)\n        obj.Reserved1 = bc.u_get(3)\n        obj.Thickness = unpack_float(self._src)\n        obj.Sharpness = unpack_float(self._src)\n        obj.Reserved2 = unpack_ui8(self._src)\n        return obj",
    "docstring": "Handle the CSMTextSettings tag."
  },
  {
    "code": "def get_logs(self, jobs, log_file=None):\n        if not (jobs and self.log_url):\n            return\n        for job in jobs:\n            url = \"{}?jobId={}\".format(self.log_url, job.get(\"id\"))\n            if log_file:\n                self._download_log(\"{}&download\".format(url), log_file)\n            else:\n                logger.info(\"Submit log for job %s: %s\", job.get(\"id\"), url)",
    "docstring": "Get log or log url of the jobs."
  },
  {
    "code": "def indicator_pivot(self, indicator_resource):\n        resource = self.copy()\n        resource._request_uri = '{}/{}'.format(\n            indicator_resource.request_uri, resource._request_uri\n        )\n        return resource",
    "docstring": "Pivot point on indicators for this resource.\n\n        This method will return all *resources* (groups, tasks, victims, etc)\n        for this resource that are associated with the provided resource id\n        (indicator value).\n\n        **Example Endpoints URI's**\n\n        +--------+---------------------------------------------------------------------------------+\n        | Method | API Endpoint URI's                                                              |\n        +========+=================================================================================+\n        | GET    | /v2/indicators/{resourceType}/{resourceId}/groups/{resourceType}                |\n        +--------+---------------------------------------------------------------------------------+\n        | GET    | /v2/indicators/{resourceType}/{resourceId}/groups/{resourceType}/{uniqueId}     |\n        +--------+---------------------------------------------------------------------------------+\n        | GET    | /v2/indicators/{resourceType}/{resourceId}/tasks/                               |\n        +--------+---------------------------------------------------------------------------------+\n        | GET    | /v2/indicators/{resourceType}/{resourceId}/tasks/{uniqueId}                     |\n        +--------+---------------------------------------------------------------------------------+\n        | GET    | /v2/indicators/{resourceType}/{resourceId}/victims/                             |\n        +--------+---------------------------------------------------------------------------------+\n        | GET    | /v2/indicators/{resourceType}/{resourceId}/victims/{uniqueId}                   |\n        +--------+---------------------------------------------------------------------------------+\n\n        Args:\n            resource_type (string): The resource pivot resource type (indicator type).\n            resource_id (integer): The resource pivot id (indicator value)."
  },
  {
    "code": "def travis(branch: str):\n    assert os.environ.get('TRAVIS_BRANCH') == branch\n    assert os.environ.get('TRAVIS_PULL_REQUEST') == 'false'",
    "docstring": "Performs necessary checks to ensure that the travis build is one\n    that should create releases.\n\n    :param branch: The branch the environment should be running against."
  },
  {
    "code": "def publish(self, message, tag=b''):\n        self.send(tag + b'\\0' + message)",
    "docstring": "Publish `message` with specified `tag`.\n\n        :param message: message data\n        :type message: str\n        :param tag: message tag\n        :type tag: str"
  },
  {
    "code": "def writeSampleIndex(self, fp):\n        print('\\n'.join(\n            '%d %s' % (index, name) for (index, name) in\n            sorted((index, name) for (name, index) in self._samples.items())\n        ), file=fp)",
    "docstring": "Write a file of sample indices and names, sorted by index.\n\n        @param fp: A file-like object, opened for writing."
  },
  {
    "code": "def replayOne(self, r):\n        'Replay the command in one given row.'\n        CommandLog.currentReplayRow = r\n        longname = getattr(r, 'longname', None)\n        if longname == 'set-option':\n            try:\n                options.set(r.row, r.input, options._opts.getobj(r.col))\n                escaped = False\n            except Exception as e:\n                exceptionCaught(e)\n                escaped = True\n        else:\n            vs = self.moveToReplayContext(r)\n            vd().keystrokes = r.keystrokes\n            escaped = vs.exec_command(vs.getCommand(longname if longname else r.keystrokes), keystrokes=r.keystrokes)\n        CommandLog.currentReplayRow = None\n        if escaped:\n            warning('replay aborted')\n        return escaped",
    "docstring": "Replay the command in one given row."
  },
  {
    "code": "def extract(self, pbf, output):\n        logging.info(\"Extracting POI nodes from {0} to {1}\".format(pbf, output))\n        with open(output, 'w') as f:\n            def nodes_callback(nodes):\n                for node in nodes:\n                    node_id, tags, coordinates = node\n                    if any([t in tags for t in POI_TAGS]):\n                        f.write(json.dumps(dict(tags=tags, coordinates=coordinates)))\n                        f.write('\\n')\n            parser = OSMParser(concurrency=4, nodes_callback=nodes_callback)\n            parser.parse(pbf)\n        return output",
    "docstring": "extract POI nodes from osm pbf extract"
  },
  {
    "code": "def _read24(self, register):\n        ret = 0.0\n        for b in self._read_register(register, 3):\n            ret *= 256.0\n            ret += float(b & 0xFF)\n        return ret",
    "docstring": "Read an unsigned 24-bit value as a floating point and return it."
  },
  {
    "code": "def clearText(self, keepFocus=False):\r\n        self.text = ''\r\n        self.focus = keepFocus\r\n        self._updateImage()",
    "docstring": "Clear the text in the field"
  },
  {
    "code": "def page_revisions(request, page_id, template_name='wagtailrollbacks/edit_handlers/revisions.html'):\n    page        = get_object_or_404(Page, pk=page_id)\n    page_perms  = page.permissions_for_user(request.user)\n    if not page_perms.can_edit():\n        raise PermissionDenied\n    page_num    = request.GET.get('p', 1)\n    revisions   = get_revisions(page, page_num)\n    return render(\n        request,\n        template_name,\n        {\n            'page':         page,\n            'revisions':    revisions,\n            'p':            page_num,\n        }\n    )",
    "docstring": "Returns GET response for specified page revisions.\n\n    :param request: the request instance.\n    :param page_id: the page ID.\n    :param template_name: the template name.\n    :rtype: django.http.HttpResponse."
  },
  {
    "code": "def get_model_home():\n    d = os.path.join(get_data_home(), 'nnp_models')\n    if not os.path.isdir(d):\n        os.makedirs(d)\n    return d",
    "docstring": "Returns a root folder path for downloading models."
  },
  {
    "code": "def _reuse_pre_installed_setuptools(env, installer):\r\n    if not env.setuptools_version:\r\n        return\n    reuse_old = config.reuse_old_setuptools\r\n    reuse_best = config.reuse_best_setuptools\r\n    reuse_future = config.reuse_future_setuptools\r\n    reuse_comment = None\r\n    if reuse_old or reuse_best or reuse_future:\r\n        pv_old = parse_version(env.setuptools_version)\r\n        pv_new = parse_version(installer.setuptools_version())\r\n        if pv_old < pv_new:\r\n            if reuse_old:\r\n                reuse_comment = \"%s+ recommended\" % (\r\n                    installer.setuptools_version(),)\r\n        elif pv_old > pv_new:\r\n            if reuse_future:\r\n                reuse_comment = \"%s+ required\" % (\r\n                    installer.setuptools_version(),)\r\n        elif reuse_best:\r\n            reuse_comment = \"\"\r\n    if reuse_comment is None:\r\n        return\n    if reuse_comment:\r\n        reuse_comment = \" (%s)\" % (reuse_comment,)\r\n    print(\"Reusing pre-installed setuptools %s distribution%s.\" % (\r\n        env.setuptools_version, reuse_comment))\r\n    return True",
    "docstring": "Return whether a pre-installed setuptools distribution should be reused."
  },
  {
    "code": "def stats(self):\n        import ns1.rest.stats\n        return ns1.rest.stats.Stats(self.config)",
    "docstring": "Return a new raw REST interface to stats resources\n\n        :rtype: :py:class:`ns1.rest.stats.Stats`"
  },
  {
    "code": "def _compress(self):\n        rank = 0.0\n        current = self._head\n        while current and current._successor:\n            if current._rank + current._successor._rank + current._successor._delta <= self._invariant(rank, self._observations):\n                removed = current._successor\n                current._value = removed._value\n                current._rank += removed._rank\n                current._delta = removed._delta\n                current._successor = removed._successor\n            rank += current._rank\n            current = current._successor",
    "docstring": "Prunes the cataloged observations."
  },
  {
    "code": "def short_repr(obj, max_len=40):\n  obj_repr = repr(obj)\n  if len(obj_repr) <= max_len:\n    return obj_repr\n  return '<{} of length {}>'.format(type(obj).__name__, len(obj_repr))",
    "docstring": "Returns a short, term-friendly string representation of the object.\n\n  Args:\n    obj: An object for which to return a string representation.\n    max_len: Maximum length of the returned string. Longer reprs will be turned\n        into a brief descriptive string giving the type and length of obj."
  },
  {
    "code": "def hdf5_storable(type_or_storable, *args, **kwargs):\n    if not isinstance(type_or_storable, Storable):\n        type_or_storable = default_storable(type_or_storable)\n    hdf5_service.registerStorable(type_or_storable, *args, **kwargs)",
    "docstring": "Registers a `Storable` instance in the global service."
  },
  {
    "code": "def get_default_voices(self):\n        voices = []\n        for app in self.app_list:\n            children = []\n            for model in app.get('models', []):\n                child = {\n                    'type': 'model',\n                    'label': model.get('name', ''),\n                    'url': model.get('admin_url', '')\n                }\n                children.append(child)\n            voice = {\n                'type': 'app',\n                'label': app.get('name', ''),\n                'url': app.get('app_url', ''),\n                'children': children\n            }\n            voices.append(voice)\n        return voices",
    "docstring": "When no custom menu is defined in settings\n            Retrieves a js menu ready dict from the django admin app list"
  },
  {
    "code": "def prj_resolution_data(project, role):\n    if role == QtCore.Qt.DisplayRole:\n        return '%s x %s' % (project.resx, project.resy)",
    "docstring": "Return the data for resolution\n\n    :param project: the project that holds the data\n    :type project: :class:`jukeboxcore.djadapter.models.Project`\n    :param role: item data role\n    :type role: QtCore.Qt.ItemDataRole\n    :returns: data for the resolution\n    :rtype: depending on role\n    :raises: None"
  },
  {
    "code": "def create(self):\n        column_family = self.to_pb()\n        modification = table_admin_v2_pb2.ModifyColumnFamiliesRequest.Modification(\n            id=self.column_family_id, create=column_family\n        )\n        client = self._table._instance._client\n        client.table_admin_client.modify_column_families(\n            self._table.name, [modification]\n        )",
    "docstring": "Create this column family.\n\n        For example:\n\n        .. literalinclude:: snippets_table.py\n            :start-after: [START bigtable_create_column_family]\n            :end-before: [END bigtable_create_column_family]"
  },
  {
    "code": "def check_ten_percent_voltage_deviation(network):\n    v_mag_pu_pfa = network.results.v_res()\n    if (v_mag_pu_pfa > 1.1).any().any() or (v_mag_pu_pfa < 0.9).any().any():\n        message = \"Maximum allowed voltage deviation of 10% exceeded.\"\n        raise ValueError(message)",
    "docstring": "Checks if 10% criteria is exceeded.\n\n    Parameters\n    ----------\n    network : :class:`~.grid.network.Network`"
  },
  {
    "code": "def get_inventory(self):\n        self.oem_init()\n        yield (\"System\", self._get_zero_fru())\n        self.init_sdr()\n        for fruid in sorted(self._sdr.fru):\n            fruinf = fru.FRU(\n                ipmicmd=self, fruid=fruid, sdr=self._sdr.fru[fruid]).info\n            if fruinf is not None:\n                fruinf = self._oem.process_fru(fruinf,\n                                               self._sdr.fru[fruid].fru_name)\n            yield (self._sdr.fru[fruid].fru_name, fruinf)\n        for componentpair in self._oem.get_oem_inventory():\n            yield componentpair",
    "docstring": "Retrieve inventory of system\n\n        Retrieve inventory of the targeted system.  This frequently includes\n        serial numbers, sometimes hardware addresses, sometimes memory modules\n        This function will retrieve whatever the underlying platform provides\n        and apply some structure.  Iterating over the return yields tuples\n        of a name for the inventoried item and dictionary of descriptions\n        or None for items not present."
  },
  {
    "code": "def name2rgb(name):\n    try:\n        import colour\n    except ImportError:\n        raise ImportError('You need colour to be installed: pip install colour')\n    c = colour.Color(name)\n    color = int(c.red * 255), int(c.green * 255), int(c.blue * 255)\n    return color",
    "docstring": "Convert the name of a color into its RGB value"
  },
  {
    "code": "def relabel(self, change):\n        \"Relabel images by moving from parent dir with old label `class_old` to parent dir with new label `class_new`.\"\n        class_new,class_old,file_path = change.new,change.old,change.owner.file_path\n        fp = Path(file_path)\n        parent = fp.parents[1]\n        self._csv_dict[fp] = class_new",
    "docstring": "Relabel images by moving from parent dir with old label `class_old` to parent dir with new label `class_new`."
  },
  {
    "code": "def write_training_data(self, features, targets):\n        assert len(features) == len(targets)\n        data = dict(zip(features, targets))\n        with open(os.path.join(self.repopath, 'training.pkl'), 'w') as fp:\n            pickle.dump(data, fp)",
    "docstring": "Writes data dictionary to filename"
  },
  {
    "code": "def app_authenticate(self, account=None, flush=True, bailout=False):\n        with self._get_account(account) as account:\n            user = account.get_name()\n            password = account.get_password()\n            self._dbg(1, \"Attempting to app-authenticate %s.\" % user)\n            self._app_authenticate(account, password, flush, bailout)\n        self.app_authenticated = True",
    "docstring": "Attempt to perform application-level authentication. Application\n        level authentication is needed on devices where the username and\n        password are requested from the user after the connection was\n        already accepted by the remote device.\n\n        The difference between app-level authentication and protocol-level\n        authentication is that in the latter case, the prompting is handled\n        by the client, whereas app-level authentication is handled by the\n        remote device.\n\n        App-level authentication comes in a large variety of forms, and\n        while this method tries hard to support them all, there is no\n        guarantee that it will always work.\n\n        We attempt to smartly recognize the user and password prompts;\n        for a list of supported operating systems please check the\n        Exscript.protocols.drivers module.\n\n        Returns upon finding the first command line prompt. Depending\n        on whether the flush argument is True, it also removes the\n        prompt from the incoming buffer.\n\n        :type  account: Account\n        :param account: An account object, like login().\n        :type  flush: bool\n        :param flush: Whether to flush the last prompt from the buffer.\n        :type  bailout: bool\n        :param bailout: Whether to wait for a prompt after sending the password."
  },
  {
    "code": "def copy_file(source, destination, unique=False, sort=False, case_sensitive=True, create_path=False):\n    _File.copy(source, destination, unique, sort, case_sensitive, create_path)",
    "docstring": "Python utility to create file\n\n    Args:\n        source: absolute/relative path of source file\n        destination: absolute/relative path of destination file.\n                     Use same as source for replacing the content of existing file.\n        unique: Copy only unique lines from file\n        sort: Sort the content of file\n        case_sensitive: unique/sort operations to be performed case-sensitive string\n        create_path: Recursively create the path to destination directory in case not found\n\n    Returns: None"
  },
  {
    "code": "def selected(self, new):\n        def preprocess(item):\n            if isinstance(item, str):\n                return self.options[item]\n            return item\n        items = coerce_to_list(new, preprocess)\n        self.widget.value = items",
    "docstring": "Set selected from list or instance of object or name.\n\n        Over-writes existing selection"
  },
  {
    "code": "def snapshot(self):\n        snap = connState(connection_end=self.connection_end,\n                         read_or_write=self.row,\n                         seq_num=self.seq_num,\n                         compression_alg=type(self.compression),\n                         ciphersuite=type(self.ciphersuite),\n                         tls_version=self.tls_version)\n        snap.cipher = self.cipher.snapshot()\n        if self.hmac:\n            snap.hmac.key = self.hmac.key\n        return snap",
    "docstring": "This is used mostly as a way to keep the cipher state and the seq_num."
  },
  {
    "code": "def summarizeResults(expName, suite):\n  print(\"\\n================\",expName,\"=====================\")\n  try:\n    values, params = suite.get_values_fix_params(\n      expName, 0, \"totalCorrect\", \"last\")\n    v = np.array(values)\n    sortedIndices = v.argsort()\n    for i in sortedIndices[::-1]:\n      print(v[i], params[i][\"name\"])\n    print()\n  except:\n    print(\"Couldn't analyze experiment\",expName)\n  try:\n    values, params = suite.get_values_fix_params(\n      expName, 0, \"testerror\", \"last\")\n    v = np.array(values)\n    sortedIndices = v.argsort()\n    for i in sortedIndices[::-1]:\n      print(v[i], params[i][\"name\"])\n    print()\n  except:\n    print(\"Couldn't analyze experiment\",expName)",
    "docstring": "Summarize the totalCorrect value from the last iteration for each experiment\n  in the directory tree."
  },
  {
    "code": "def describe_guest(userid):\n    guest_list_info = client.send_request('guest_list')\n    userid_1 = (unicode(userid, \"utf-8\") if sys.version[0] == '2' else userid)\n    if userid_1 not in guest_list_info['output']:\n        raise RuntimeError(\"Guest %s does not exist!\" % userid)\n    guest_describe_info = client.send_request('guest_get_definition_info', userid)\n    print(\"\\nThe created guest %s's info are: \\n%s\\n\" % (userid, guest_describe_info))",
    "docstring": "Get the basic information of virtual machine.\n\n    Input parameters:\n    :userid:    USERID of the guest, last 8 if length > 8"
  },
  {
    "code": "def evalMetric(self, x, method=None):\n        if self.verbose:\n            print('----------')\n            print('At design: ' + str(x))\n        q_samples, grad_samples = self.evalSamples(x)\n        if self.verbose:\n            print('Evaluating metric')\n        return self.evalMetricFromSamples(q_samples, grad_samples, method)",
    "docstring": "Evaluates the horsetail matching metric at given values of the\n        design variables.\n\n        :param iterable x: values of the design variables, this is passed as\n            the first argument to the function fqoi\n        :param str method: method to use to evaluate the metric ('empirical' or\n            'kernel')\n\n        :return: metric_value - value of the metric evaluated at the design\n            point given by x\n\n        :rtype: float\n\n        *Example Usage*::\n\n            >>> def myFunc(x, u): return x[0]*x[1] + u\n            >>> u1 = UniformParameter()\n            >>> theHM = HorsetailMatching(myFunc, u)\n            >>> x0 = [1, 2]\n            >>> theHM.evalMetric(x0)"
  },
  {
    "code": "def set_mode(self, mode):\n        if mode not in [self.TERMINATE, self.RUN, self.IDLE]:\n            raise ProgrammerError('mode=%r is not recognized' % mode)\n        with self.registry.lock(identifier=self.worker_id) as session:\n            session.set('modes', 'mode', mode)\n        logger.info('set mode to %s', mode)",
    "docstring": "Set the global mode of the rejester system.\n\n        This must be one of the constants :attr:`TERMINATE`,\n        :attr:`RUN`, or :attr:`IDLE`.  :attr:`TERMINATE` instructs any\n        running workers to do an orderly shutdown, completing current\n        jobs then exiting.  :attr:`IDLE` instructs workers to stay\n        running but not start new jobs.  :attr:`RUN` tells workers to\n        do actual work.\n\n        :param str mode: new rejester mode\n        :raise rejester.exceptions.ProgrammerError: on invalid `mode`"
  },
  {
    "code": "def LAMBDA(self, node):\n        self.handleNode, self.deferHandleNode = self.deferHandleNode, self.handleNode\n        super().LAMBDA(node)\n        self.handleNode, self.deferHandleNode = self.deferHandleNode, self.handleNode",
    "docstring": "This is likely very brittle, currently works for pyflakes 1.3.0.\n\n        Deferring annotation handling depends on the fact that during calls\n        to LAMBDA visiting the function's body is already deferred and the\n        only eager calls to `handleNode` are for annotations."
  },
  {
    "code": "def copy_directory(src, dest, force=False):\n    if os.path.exists(dest) and force is True:\n        shutil.rmtree(dest)\n    try:\n        shutil.copytree(src, dest)\n    except OSError as e:\n        if e.errno == errno.ENOTDIR:\n            shutil.copy(src, dest)\n        else:\n            bot.error('Directory not copied. Error: %s' % e)\n            sys.exit(1)",
    "docstring": "Copy an entire directory recursively"
  },
  {
    "code": "def resize(widthWindow, heightWindow):\n\tglEnable(GL_BLEND)\n\tglEnable(GL_POINT_SMOOTH)\n\tglShadeModel(GL_SMOOTH)\n\tglBlendFunc(GL_SRC_ALPHA,GL_ONE)\n\tglHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);\n\tglHint(GL_POINT_SMOOTH_HINT,GL_NICEST);\n\tglDisable(GL_DEPTH_TEST)",
    "docstring": "Initial settings for the OpenGL state machine, clear color, window size, etc"
  },
  {
    "code": "def mchirp_sampler_imf(**kwargs):\n    m1, m2 = draw_imf_samples(**kwargs)\n    mchirp_astro = mchirp_from_mass1_mass2(m1, m2)\n    return mchirp_astro",
    "docstring": "Draw chirp mass samples for power-law model\n\n        Parameters\n        ----------\n        **kwargs: string\n           Keyword arguments as model parameters and number of samples\n\n        Returns\n        -------\n        mchirp-astro: array\n           The chirp mass samples for the population"
  },
  {
    "code": "def get (self, feature):\n        if type(feature) == type([]):\n            feature = feature[0]\n        if not isinstance(feature, b2.build.feature.Feature):\n            feature = b2.build.feature.get(feature)\n        assert isinstance(feature, b2.build.feature.Feature)\n        if self.feature_map_ is None:\n            self.feature_map_ = {}\n            for v in self.all_:\n                if v.feature not in self.feature_map_:\n                    self.feature_map_[v.feature] = []\n                self.feature_map_[v.feature].append(v.value)\n        return self.feature_map_.get(feature, [])",
    "docstring": "Returns all values of 'feature'."
  },
  {
    "code": "def respond(self, result):\n        if self.one_way or self.unique_id is None:\n            return None\n        response = JSONRPCSuccessResponse()\n        response.result = result\n        response.unique_id = self.unique_id\n        return response",
    "docstring": "Create a response to this request.\n\n        When processing the request completed successfully this method can be used to\n        create a response object.\n\n        :param result: The result of the invoked method.\n        :type result: Anything that can be encoded by JSON.\n        :returns: A response object that can be serialized and sent to the client.\n        :rtype: :py:class:`JSONRPCSuccessResponse`"
  },
  {
    "code": "def request_examples(self, attack_config, criteria, run_counts, batch_size):\n    raise NotImplementedError(str(type(self)) +\n                              \"needs to implement request_examples\")",
    "docstring": "Returns a numpy array of integer example indices to run in the next batch."
  },
  {
    "code": "def from_time(cls, source):\n        return cls(hours=source.hour, minutes=source.minute,\n            seconds=source.second, milliseconds=source.microsecond // 1000)",
    "docstring": "datetime.time -> SubRipTime corresponding to time object"
  },
  {
    "code": "def rollapply(data, window, fn):\n    res = data.copy()\n    res[:] = np.nan\n    n = len(data)\n    if window > n:\n        return res\n    for i in range(window - 1, n):\n        res.iloc[i] = fn(data.iloc[i - window + 1:i + 1])\n    return res",
    "docstring": "Apply a function fn over a rolling window of size window.\n\n    Args:\n        * data (Series or DataFrame): Series or DataFrame\n        * window (int): Window size\n        * fn (function): Function to apply over the rolling window.\n            For a series, the return value is expected to be a single\n            number. For a DataFrame, it shuold return a new row.\n\n    Returns:\n        * Object of same dimensions as data"
  },
  {
    "code": "async def self_check(self):\n        platforms = set()\n        for platform in get_platform_settings():\n            try:\n                name = platform['class']\n                cls: Type[Platform] = import_class(name)\n            except KeyError:\n                yield HealthCheckFail(\n                    '00004',\n                    'Missing platform `class` name in configuration.'\n                )\n            except (AttributeError, ImportError, ValueError):\n                yield HealthCheckFail(\n                    '00003',\n                    f'Platform \"{name}\" cannot be imported.'\n                )\n            else:\n                if cls in platforms:\n                    yield HealthCheckFail(\n                        '00002',\n                        f'Platform \"{name}\" is imported more than once.'\n                    )\n                platforms.add(cls)\n                async for check in cls.self_check():\n                    yield check",
    "docstring": "Checks that the platforms configuration is all right."
  },
  {
    "code": "def _get_default_mr_params(cls):\n    cfg = cls(_lenient=True)\n    mr_params = cfg._get_mr_params()\n    mr_params[\"api_version\"] = 0\n    return mr_params",
    "docstring": "Gets default values for old API."
  },
  {
    "code": "def config(self):\n        config = {}\n        if self.config_file.exists():\n            with open(self.config_file.as_posix(), 'rt') as f:\n                config = {k:self._override[k] if\n                        k in self._override else\n                        v for k, v in yaml.safe_load(f).items()}\n        return config",
    "docstring": "Allows changing the config on the fly"
  },
  {
    "code": "def prerequisites():\n    url = \"http://home.gna.org/gaupol/download.html\"\n    debian = \"sudo apt-get install python3-aeidon\"\n    other = \"python3 setup.py --user --without-gaupol clean install\"\n    LOGGER.error(\n        \"The aeidon module is missing!\\n\\n\"\n        \"Try '{0}' or the appropriate command for your package manager.\\n\\n\"\n        \"You can also download the tarball for gaupol (which includes \"\n        \"aeidon) at {1}. After downloading, unpack and run '{2}'.\"\n        .format(debian, url, other))",
    "docstring": "Display information about obtaining the aeidon module."
  },
  {
    "code": "def parse_diff_filenames(diff_files):\n        files = []\n        for line in diff_files.splitlines():\n            line = line.strip()\n            fn = re.findall('[^ ]+\\s+(.*.py)', line)\n            if fn and not line.startswith('?'):\n                files.append(fn[0])\n        return files",
    "docstring": "Parse the output of filenames_diff_cmd."
  },
  {
    "code": "def compile_theme(theme_id=None):\n    from engineer.processors import convert_less\n    from engineer.themes import ThemeManager\n    if theme_id is None:\n        themes = ThemeManager.themes().values()\n    else:\n        themes = [ThemeManager.theme(theme_id)]\n    with(indent(2)):\n        puts(colored.yellow(\"Compiling %s themes.\" % len(themes)))\n        for theme in themes:\n            theme_output_path = (theme.static_root / ('stylesheets/%s_precompiled.css' % theme.id)).normpath()\n            puts(colored.cyan(\"Compiling theme %s to %s\" % (theme.id, theme_output_path)))\n            with indent(4):\n                puts(\"Compiling...\")\n                convert_less(theme.static_root / ('stylesheets/%s.less' % theme.id),\n                             theme_output_path,\n                             minify=True)\n                puts(colored.green(\"Done.\", bold=True))",
    "docstring": "Compiles a theme."
  },
  {
    "code": "def alter(self, function):\n        check_not_none(function, \"function can't be None\")\n        return self._encode_invoke(atomic_long_alter_codec, function=self._to_data(function))",
    "docstring": "Alters the currently stored value by applying a function on it.\n\n        :param function: (Function), A stateful serializable object which represents the Function defined on\n            server side.\n            This object must have a serializable Function counter part registered on server side with the actual\n            ``org.hazelcast.core.IFunction`` implementation."
  },
  {
    "code": "def parse_deckspawn_metainfo(protobuf: bytes, version: int) -> dict:\n    deck = DeckSpawnProto()\n    deck.ParseFromString(protobuf)\n    error = {\"error\": \"Deck ({deck}) metainfo incomplete, deck must have a name.\".format(deck=deck.name)}\n    if deck.name == \"\":\n        raise InvalidDeckMetainfo(error)\n    if deck.version != version:\n        raise InvalidDeckVersion({\"error\", \"Deck version mismatch.\"})\n    return {\n        \"version\": deck.version,\n        \"name\": deck.name,\n        \"issue_mode\": deck.issue_mode,\n        \"number_of_decimals\": deck.number_of_decimals,\n        \"asset_specific_data\": deck.asset_specific_data\n        }",
    "docstring": "Decode deck_spawn tx op_return protobuf message and validate it,\n       Raise error if deck_spawn metainfo incomplete or version mistmatch."
  },
  {
    "code": "def _check_read(self, fd, nbytes):\n        result = fd.read(nbytes)\n        if (not result and nbytes > 0) or len(result) != nbytes:\n            raise InvalidZoneinfoFile(\n                \"Expected {} bytes reading {}, \"\n                \"but got {}\".format(nbytes, fd.name, len(result) if result else 0)\n            )\n        if PY2:\n            return bytearray(result)\n        return result",
    "docstring": "Reads the given number of bytes from the given file\n        and checks that the correct number of bytes could be read."
  },
  {
    "code": "def pt_scale(pt=(0.0, 0.0), f=1.0):\n    assert isinstance(pt, tuple)\n    l_pt = len(pt)\n    assert l_pt > 1\n    for i in pt:\n        assert isinstance(i, float)\n    assert isinstance(f, float)\n    return tuple([pt[i]*f for i in range(l_pt)])",
    "docstring": "Return given point scaled by factor f from origin."
  },
  {
    "code": "def fromdelta(args):\n    p = OptionParser(fromdelta.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(not p.print_help())\n    deltafile, = args\n    coordsfile = deltafile.rsplit(\".\", 1)[0] + \".coords\"\n    cmd = \"show-coords -rclH {0}\".format(deltafile)\n    sh(cmd, outfile=coordsfile)\n    return coordsfile",
    "docstring": "%prog fromdelta deltafile\n\n    Convert deltafile to coordsfile."
  },
  {
    "code": "def __definitions_descriptor(self):\n    result = {}\n    for def_key, def_value in self.__parser.schemas().iteritems():\n      if 'properties' in def_value or 'type' in def_value:\n        key_result = {}\n        required_keys = set()\n        if 'type' in def_value:\n          key_result['type'] = def_value['type']\n        if 'properties' in def_value:\n          for prop_key, prop_value in def_value['properties'].items():\n            if isinstance(prop_value, dict) and 'required' in prop_value:\n              required_keys.add(prop_key)\n              del prop_value['required']\n          key_result['properties'] = def_value['properties']\n        if required_keys:\n          key_result['required'] = sorted(required_keys)\n        result[def_key] = key_result\n    for def_value in result.itervalues():\n      for prop_value in def_value.itervalues():\n        if isinstance(prop_value, dict):\n          if '$ref' in prop_value:\n            prop_value['type'] = 'object'\n          self._add_def_paths(prop_value)\n    return result",
    "docstring": "Describes the definitions section of the OpenAPI spec.\n\n    Returns:\n      Dictionary describing the definitions of the spec."
  },
  {
    "code": "def tag_torsion_angles(self, force=False):\n        tagged = ['omega' in x.tags.keys() for x in self._monomers]\n        if (not all(tagged)) or force:\n            tas = measure_torsion_angles(self._monomers)\n            for monomer, (omega, phi, psi) in zip(self._monomers, tas):\n                monomer.tags['omega'] = omega\n                monomer.tags['phi'] = phi\n                monomer.tags['psi'] = psi\n                monomer.tags['tas'] = (omega, phi, psi)\n        return",
    "docstring": "Tags each Monomer of the Polymer with its omega, phi and psi torsion angle.\n\n        Parameters\n        ----------\n        force : bool, optional\n            If `True` the tag will be run even if `Residues` are\n            already tagged."
  },
  {
    "code": "def __remove_pyc_pyo(fname):\r\n    if osp.splitext(fname)[1] == '.py':\r\n        for ending in ('c', 'o'):\r\n            if osp.exists(fname+ending):\r\n                os.remove(fname+ending)",
    "docstring": "Eventually remove .pyc and .pyo files associated to a Python script"
  },
  {
    "code": "def write_json(self, **kwargs):\n        self.stdout.write(json.dumps(kwargs) + \"\\n\")\n        self.stdout.flush()",
    "docstring": "Write an JSON object on a single line.\n\n        The keyword arguments are interpreted as a single JSON object.\n        It's not possible with this method to write non-objects."
  },
  {
    "code": "def do_reload(module: types.ModuleType, newer_than: int) -> bool:\n    path = getattr(module, '__file__')\n    directory = getattr(module, '__path__', [None])[0]\n    if path is None and directory:\n        path = os.path.join(directory, '__init__.py')\n    last_modified = os.path.getmtime(path)\n    if last_modified < newer_than:\n        return False\n    try:\n        importlib.reload(module)\n        return True\n    except ImportError:\n        return False",
    "docstring": "Executes the reload of the specified module if the source file that it was\n    loaded from was updated more recently than the specified time\n\n    :param module:\n        A module object to be reloaded\n    :param newer_than:\n        The time in seconds since epoch that should be used to determine if\n        the module needs to be reloaded. If the module source was modified\n        more recently than this time, the module will be refreshed.\n    :return:\n        Whether or not the module was reloaded"
  },
  {
    "code": "def GetRelativePath(self, path_spec):\n    location = getattr(path_spec, 'location', None)\n    if location is None:\n      raise errors.PathSpecError('Path specification missing location.')\n    if path_spec_factory.Factory.IsSystemLevelTypeIndicator(\n        self._file_system.type_indicator):\n      if not location.startswith(self._mount_point.location):\n        raise errors.PathSpecError(\n            'Path specification does not contain mount point.')\n    else:\n      if not hasattr(path_spec, 'parent'):\n        raise errors.PathSpecError('Path specification missing parent.')\n      if path_spec.parent != self._mount_point:\n        raise errors.PathSpecError(\n            'Path specification does not contain mount point.')\n    path_segments = self._file_system.SplitPath(location)\n    if path_spec_factory.Factory.IsSystemLevelTypeIndicator(\n        self._file_system.type_indicator):\n      mount_point_path_segments = self._file_system.SplitPath(\n          self._mount_point.location)\n      path_segments = path_segments[len(mount_point_path_segments):]\n    return '{0:s}{1:s}'.format(\n        self._file_system.PATH_SEPARATOR,\n        self._file_system.PATH_SEPARATOR.join(path_segments))",
    "docstring": "Returns the relative path based on a resolved path specification.\n\n    The relative path is the location of the upper most path specification.\n    The the location of the mount point is stripped off if relevant.\n\n    Args:\n      path_spec (PathSpec): path specification.\n\n    Returns:\n      str: corresponding relative path or None if the relative path could not\n          be determined.\n\n    Raises:\n      PathSpecError: if the path specification is incorrect."
  },
  {
    "code": "def encode_request(self, fields, files):\n        parts = []\n        boundary = self.boundary\n        for k, values in fields:\n            if not isinstance(values, (list, tuple)):\n                values = [values]\n            for v in values:\n                parts.extend((\n                    b'--' + boundary,\n                    ('Content-Disposition: form-data; name=\"%s\"' %\n                     k).encode('utf-8'),\n                    b'',\n                    v.encode('utf-8')))\n        for key, filename, value in files:\n            parts.extend((\n                b'--' + boundary,\n                ('Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"' %\n                 (key, filename)).encode('utf-8'),\n                b'',\n                value))\n        parts.extend((b'--' + boundary + b'--', b''))\n        body = b'\\r\\n'.join(parts)\n        ct = b'multipart/form-data; boundary=' + boundary\n        headers = {\n            'Content-type': ct,\n            'Content-length': str(len(body))\n        }\n        return Request(self.url, body, headers)",
    "docstring": "Encode fields and files for posting to an HTTP server.\n\n        :param fields: The fields to send as a list of (fieldname, value)\n                       tuples.\n        :param files: The files to send as a list of (fieldname, filename,\n                      file_bytes) tuple."
  },
  {
    "code": "def validate_connector(self, connector):\n        if not 'connector' in connector:\n            raise ValueError('missing connector name')\n        elif connector['connector'] != CONNECTOR_RABBITMQ:\n            raise ValueError('unknown connector: ' + str(connector['connector']))\n        RabbitMQConnector.validate(connector)",
    "docstring": "Validate a given connector. Raises ValueError if the connector is not\n        valid.\n\n        Parameters\n        ----------\n        connector : dict\n            Connection information"
  },
  {
    "code": "def denormalize(x:TensorImage, mean:FloatTensor,std:FloatTensor, do_x:bool=True)->TensorImage:\n    \"Denormalize `x` with `mean` and `std`.\"\n    return x.cpu().float()*std[...,None,None] + mean[...,None,None] if do_x else x.cpu()",
    "docstring": "Denormalize `x` with `mean` and `std`."
  },
  {
    "code": "def newNodeEatName(self, name):\n        ret = libxml2mod.xmlNewNodeEatName(self._o, name)\n        if ret is None:raise treeError('xmlNewNodeEatName() failed')\n        __tmp = xmlNode(_obj=ret)\n        return __tmp",
    "docstring": "Creation of a new node element. @ns is optional (None)."
  },
  {
    "code": "def form_valid(self, form):\n        form_valid_from_parent = super(HostCreate, self).form_valid(form)\n        messages.success(self.request, 'Host {} Successfully Created'.format(self.object))\n        return form_valid_from_parent",
    "docstring": "First call the parent's form valid then let the user know it worked."
  },
  {
    "code": "def clearAdvancedActions( self ):\n        self._advancedMap.clear()\n        margins     = list(self.getContentsMargins())\n        margins[2]  = 0\n        self.setContentsMargins(*margins)",
    "docstring": "Clears out the advanced action map."
  },
  {
    "code": "def remove_read_more_sep(self, raw_content):\n        if self._read_more_exp is None:\n            return raw_content\n        sp = self._read_more_exp.split(raw_content, maxsplit=1)\n        if len(sp) == 2 and sp[0]:\n            result = '\\n\\n'.join((sp[0].rstrip(), sp[1].lstrip()))\n        else:\n            result = raw_content\n        return result",
    "docstring": "Removes the first read_more_sep that occurs in raw_content.\n        Subclasses should call this method to preprocess raw_content."
  },
  {
    "code": "def getVerifiers(self):\n        contacts = list()\n        for verifier in self.getVerifiersIDs():\n            user = api.get_user(verifier)\n            contact = api.get_user_contact(user, [\"LabContact\"])\n            if contact:\n                contacts.append(contact)\n        return contacts",
    "docstring": "Returns the list of lab contacts that have verified at least one\n        analysis from this Analysis Request"
  },
  {
    "code": "def add_user(username,\n             deployment_name,\n             token_manager=None,\n             app_url=defaults.APP_URL):\n    deployment_id = get_deployment_id(deployment_name,\n                                      token_manager=token_manager,\n                                      app_url=app_url)\n    account_id = accounts.get_account_id(username,\n                                         token_manager=token_manager,\n                                         app_url=app_url)\n    headers = token_manager.get_access_token_headers()\n    deployment_url = environment.get_deployment_url(app_url=app_url)\n    response = requests.put('%s/api/v1/deployments/%s/accounts/%s' %\n                            (deployment_url, deployment_id, account_id),\n                            headers=headers)\n    if response.status_code == 204:\n        return response.text\n    else:\n        raise JutException('Error %s: %s' % (response.status_code, response.text))",
    "docstring": "add user to deployment"
  },
  {
    "code": "def write_result(self, result):\n        assert not self.finished, \"Already sent a response\"\n        if not self.result.thrift_spec:\n            self.finished = True\n            return\n        spec = self.result.thrift_spec[0]\n        if result is not None:\n            assert spec, \"Tried to return a result for a void method.\"\n            setattr(self.result, spec[2], result)\n        self.finished = True",
    "docstring": "Send back the result of this call.\n\n        Only one of this and `write_exc_info` may be called.\n\n        :param result:\n            Return value of the call"
  },
  {
    "code": "def user_photo_url(user, size):\n    endpoint, kwargs = user_url_args(user, size)\n    return url_for(endpoint, **kwargs)",
    "docstring": "Return url to use for this user."
  },
  {
    "code": "def serve_assets(path):\n    res = os.path.join(app.config['NIKOLA_ROOT'],\n                       _site.config[\"OUTPUT_FOLDER\"], 'assets')\n    return send_from_directory(res, path)",
    "docstring": "Serve Nikola assets.\n\n    This is meant to be used ONLY by the internal dev server.\n    Please configure your web server to handle requests to this URL::\n\n        /assets/ => output/assets"
  },
  {
    "code": "def view_contents(token, dstore):\n    try:\n        desc = dstore['oqparam'].description\n    except KeyError:\n        desc = ''\n    data = sorted((dstore.getsize(key), key) for key in dstore)\n    rows = [(key, humansize(nbytes)) for nbytes, key in data]\n    total = '\\n%s : %s' % (\n        dstore.filename, humansize(os.path.getsize(dstore.filename)))\n    return rst_table(rows, header=(desc, '')) + total",
    "docstring": "Returns the size of the contents of the datastore and its total size"
  },
  {
    "code": "def list_instance_profiles(path_prefix='/', region=None, key=None,\n                           keyid=None, profile=None):\n    p = get_all_instance_profiles(path_prefix, region, key, keyid, profile)\n    return [i['instance_profile_name'] for i in p]",
    "docstring": "List all IAM instance profiles, starting at the optional path.\n\n    .. versionadded:: 2016.11.0\n\n    CLI Example:\n\n        salt-call boto_iam.list_instance_profiles"
  },
  {
    "code": "def wait_for_responses(self):\n        self.thread.join(self.COMMAND_RESPONSE_TIMEOUT_S)\n        self.running = False\n        return self.responses",
    "docstring": "Block the thread and wait for the response to the given request to\n        arrive from the VI. If no matching response is received in\n        COMMAND_RESPONSE_TIMEOUT_S seconds, returns anyway."
  },
  {
    "code": "def _is_valid_string(self, inpt, metadata):\n        if not is_string(inpt):\n            return False\n        if metadata.get_minimum_string_length() and len(inpt) < metadata.get_minimum_string_length():\n            return False\n        elif metadata.get_maximum_string_length() and len(inpt) > metadata.get_maximum_string_length():\n            return False\n        if metadata.get_string_set() and inpt not in metadata.get_string_set():\n            return False\n        else:\n            return True",
    "docstring": "Checks if input is a valid string"
  },
  {
    "code": "def up_threshold(x, s, p):\n    if 1.0 * x/s >= p:\n        return True\n    elif stat.binom_test(x, s, p) > 0.01:\n        return True\n    return False",
    "docstring": "function to decide if similarity is\n    below cutoff"
  },
  {
    "code": "def re_enqueue(self, item):\n        if 'retries' in item:\n            retries = item['retries']\n            if retries >= self.MAX_RETRIES:\n                log.warn(\"Failed to execute {} after {} retries, give it \"\n                         \" up.\".format(item['method'], retries))\n            else:\n                retries += 1\n                item['retries'] = retries\n                self._q.put_nowait(item)\n        else:\n            item['retries'] = 1\n            self._q.put_nowait(item)",
    "docstring": "Re-enqueue till reach max retries."
  },
  {
    "code": "def renames(from_path, to_path, user=None):\n    to_dir = path.dirname(to_path)\n    if to_dir:\n        mkdir(to_dir, user=user)\n    rename(from_path, to_path, user=user)",
    "docstring": "Rename ``from_path`` to ``to_path``, creating parents as needed."
  },
  {
    "code": "def prune_cached(values):\n    import os\n    config_path = os.path.expanduser('~/.config/blockade')\n    file_path = os.path.join(config_path, 'cache.txt')\n    if not os.path.isfile(file_path):\n        return values\n    cached = [x.strip() for x in open(file_path, 'r').readlines()]\n    output = list()\n    for item in values:\n        hashed = hash_values(item)\n        if hashed in cached:\n            continue\n        output.append(item)\n    return output",
    "docstring": "Remove the items that have already been cached."
  },
  {
    "code": "def msquared(self, benchmark, rf=0.02, ddof=0):\n        rf = self._validate_rf(rf)\n        scaling = benchmark.anlzd_stdev(ddof) / self.anlzd_stdev(ddof)\n        diff = self.anlzd_ret() - rf\n        return rf + diff * scaling",
    "docstring": "M-squared, return scaled by relative total risk.\n\n        A measure of what a portfolio would have returned if it had\n        taken on the same *total* risk as the market index.\n        [Source: CFA Institute]\n\n        Parameters\n        ----------\n        benchmark : {pd.Series, TSeries, 1d np.ndarray}\n            The benchmark security to which `self` is compared.\n        rf : {float, TSeries, pd.Series}, default 0.02\n            If float, this represents an *compounded annualized*\n            risk-free rate; 2.0% is the default.\n            If a TSeries or pd.Series, this represents a time series\n            of periodic returns to a risk-free security.\n\n            To download a risk-free rate return series using\n            3-month US T-bill yields, see:`pyfinance.datasets.load_rf`.\n        ddof : int, default 0\n            Degrees of freedom, passed to pd.Series.std().\n\n        Returns\n        -------\n        float"
  },
  {
    "code": "def build_timeout_circuit(tor_state, reactor, path, timeout, using_guards=False):\n    timed_circuit = []\n    d = tor_state.build_circuit(routers=path, using_guards=using_guards)\n    def get_circuit(c):\n        timed_circuit.append(c)\n        return c\n    def trap_cancel(f):\n        f.trap(defer.CancelledError)\n        if timed_circuit:\n            d2 = timed_circuit[0].close()\n        else:\n            d2 = defer.succeed(None)\n        d2.addCallback(lambda _: Failure(CircuitBuildTimedOutError(\"circuit build timed out\")))\n        return d2\n    d.addCallback(get_circuit)\n    d.addCallback(lambda circ: circ.when_built())\n    d.addErrback(trap_cancel)\n    reactor.callLater(timeout, d.cancel)\n    return d",
    "docstring": "Build a new circuit within a timeout.\n\n    CircuitBuildTimedOutError will be raised unless we receive a\n    circuit build result (success or failure) within the `timeout`\n    duration.\n\n    :returns: a Deferred which fires when the circuit build succeeds (or\n        fails to build)."
  },
  {
    "code": "def _set_combobox(self, attrname, vals, default=0):\n        combobox = getattr(self.w, attrname)\n        for val in vals:\n            combobox.append_text(val)\n        if default > len(vals):\n            default = 0\n        val = vals[default]\n        combobox.show_text(val)\n        return val",
    "docstring": "Populate combobox with given list."
  },
  {
    "code": "def destroy(self):\n        while True:\n            try:\n                client = self.__pool.popleft()\n                if isinstance(client, Client):\n                    client.disconnect()\n            except IndexError:\n                break",
    "docstring": "Disconnects all pooled client objects."
  },
  {
    "code": "def shuffle(self, overwrite=False):\n        if overwrite:\n            shuffled = self.path\n        else:\n            shuffled = FileAPI.add_ext_name(self.path, \"_shuffled\")\n        lines = open(self.path).readlines()\n        random.shuffle(lines)\n        open(shuffled, \"w\").writelines(lines)\n        self.path = shuffled",
    "docstring": "This method creates new shuffled file."
  },
  {
    "code": "def get_templatetype(type_id,**kwargs):\n    templatetype = db.DBSession.query(TemplateType).filter(\n                        TemplateType.id==type_id).options(\n                        joinedload_all(\"typeattrs\")).one()\n    return templatetype",
    "docstring": "Get a specific resource type by ID."
  },
  {
    "code": "def _unpack_episode_title(element: ET.Element):\n    return EpisodeTitle(title=element.text,\n                        lang=element.get(f'{XML}lang'))",
    "docstring": "Unpack EpisodeTitle from title XML element."
  },
  {
    "code": "def read_ma_array(self, infile, var_name):\n        file_obj = self.read_cdf(infile)\n        data = file_obj.variables[var_name][:]\n        try:\n            import numpy as np\n        except Exception:\n            raise ImportError(\"numpy is required to return masked arrays.\")\n        if hasattr(file_obj.variables[var_name], \"_FillValue\"):\n            fill_val = file_obj.variables[var_name]._FillValue\n            retval = np.ma.masked_where(data == fill_val, data)\n        else:\n            retval = np.ma.array(data)\n        return retval",
    "docstring": "Create a masked array based on cdf's FillValue"
  },
  {
    "code": "def _find_files(dirpath: str) -> 'Iterable[str]':\n    for dirpath, dirnames, filenames in os.walk(dirpath, topdown=True,\n                                                followlinks=True):\n        if os.path.basename(dirpath).startswith('.'):\n            del dirnames[:]\n        for filename in filenames:\n            yield os.path.join(dirpath, filename)",
    "docstring": "Find files recursively.\n\n    Returns a generator that yields paths in no particular order."
  },
  {
    "code": "def date_to_jd(year,month,day):\n    if month == 1 or month == 2:\n        yearp = year - 1\n        monthp = month + 12\n    else:\n        yearp = year\n        monthp = month\n    if ((year < 1582) or\n        (year == 1582 and month < 10) or\n        (year == 1582 and month == 10 and day < 15)):\n        B = 0\n    else:\n        A = math.trunc(yearp / 100.)\n        B = 2 - A + math.trunc(A / 4.)\n    if yearp < 0:\n        C = math.trunc((365.25 * yearp) - 0.75)\n    else:\n        C = math.trunc(365.25 * yearp)\n    D = math.trunc(30.6001 * (monthp + 1))\n    jd = B + C + D + day + 1720994.5\n    return jd",
    "docstring": "Convert a date to Julian Day.\n\n    Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet', \n        4th ed., Duffet-Smith and Zwart, 2011.\n\n    Parameters\n    ----------\n    year : int\n        Year as integer. Years preceding 1 A.D. should be 0 or negative.\n        The year before 1 A.D. is 0, 10 B.C. is year -9.\n\n    month : int\n        Month as integer, Jan = 1, Feb. = 2, etc.\n\n    day : float\n        Day, may contain fractional part.\n\n    Returns\n    -------\n    jd : float\n        Julian Day\n\n    Examples\n    --------\n    Convert 6 a.m., February 17, 1985 to Julian Day\n\n    >>> date_to_jd(1985,2,17.25)\n    2446113.75"
  },
  {
    "code": "def lex_document(self, document):\n        location = self.editor_buffer.location\n        if location:\n            if self.editor_buffer.in_file_explorer_mode:\n                return PygmentsLexer(DirectoryListingLexer, sync_from_start=False).lex_document(document)\n            return PygmentsLexer.from_filename(location, sync_from_start=False).lex_document(document)\n        return SimpleLexer().lex_document(document)",
    "docstring": "Call the lexer and return a get_tokens_for_line function."
  },
  {
    "code": "def _assemble_regulate_amount(stmt):\n    obj_str = _assemble_agent_str(stmt.obj)\n    if stmt.subj is not None:\n        subj_str = _assemble_agent_str(stmt.subj)\n        if isinstance(stmt, ist.IncreaseAmount):\n            rel_str = ' increases the amount of '\n        elif isinstance(stmt, ist.DecreaseAmount):\n            rel_str = ' decreases the amount of '\n        stmt_str = subj_str + rel_str + obj_str\n    else:\n        if isinstance(stmt, ist.IncreaseAmount):\n            stmt_str = obj_str + ' is produced'\n        elif isinstance(stmt, ist.DecreaseAmount):\n            stmt_str = obj_str + ' is degraded'\n    return _make_sentence(stmt_str)",
    "docstring": "Assemble RegulateAmount statements into text."
  },
  {
    "code": "def _read_hdf_columns(path_or_buf, columns, num_splits, kwargs):\n    df = pandas.read_hdf(path_or_buf, columns=columns, **kwargs)\n    return _split_result_for_readers(0, num_splits, df) + [len(df.index)]",
    "docstring": "Use a Ray task to read columns from HDF5 into a Pandas DataFrame.\n\n    Note: Ray functions are not detected by codecov (thus pragma: no cover)\n\n    Args:\n        path_or_buf: The path of the HDF5 file.\n        columns: The list of column names to read.\n        num_splits: The number of partitions to split the column into.\n\n    Returns:\n         A list containing the split Pandas DataFrames and the Index as the last\n            element. If there is not `index_col` set, then we just return the length.\n            This is used to determine the total length of the DataFrame to build a\n            default Index."
  },
  {
    "code": "def move(self, auth, resource, destinationresource, options={\"aliases\": True}, defer=False):\n        return self._call('move', auth, [resource, destinationresource, options], defer)",
    "docstring": "Moves a resource from one parent client to another.\n\n        Args:\n            auth: <cik>\n            resource: Identifed resource to be moved.\n            destinationresource: resource of client resource is being moved to."
  },
  {
    "code": "def _len_lcs(x, y):\n  table = _lcs(x, y)\n  n, m = len(x), len(y)\n  return table[n, m]",
    "docstring": "Returns the length of the Longest Common Subsequence between two seqs.\n\n  Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence\n\n  Args:\n    x: sequence of words\n    y: sequence of words\n\n  Returns\n    integer: Length of LCS between x and y"
  },
  {
    "code": "def error(self, id, errorCode, errorString):\n        if errorCode == 165:\n            sys.stderr.write(\"TWS INFO - %s: %s\\n\" % (errorCode, errorString))\n        elif errorCode >= 501 and errorCode < 600:\n            sys.stderr.write(\"TWS CLIENT-ERROR - %s: %s\\n\" % (errorCode, errorString))\n        elif errorCode >= 100 and errorCode < 1100:\n            sys.stderr.write(\"TWS ERROR - %s: %s\\n\" % (errorCode, errorString))\n        elif errorCode >= 1100 and errorCode < 2100:\n            sys.stderr.write(\"TWS SYSTEM-ERROR - %s: %s\\n\" % (errorCode, errorString))\n        elif errorCode in (2104, 2106, 2108):\n            sys.stderr.write(\"TWS INFO - %s: %s\\n\" % (errorCode, errorString))\n        elif errorCode >= 2100 and errorCode <= 2110:\n            sys.stderr.write(\"TWS WARNING - %s: %s\\n\" % (errorCode, errorString))\n        else:\n            sys.stderr.write(\"TWS ERROR - %s: %s\\n\" % (errorCode, errorString))",
    "docstring": "Error during communication with TWS"
  },
  {
    "code": "def html(self):\n        output = self.html_preamble\n        output += self._repr_html_()\n        output += self.html_post\n        return output",
    "docstring": "Gives an html representation of the assessment."
  },
  {
    "code": "def pair_list(args):\n    if args.entity_type and args.entity:\n        if args.entity_type == 'pair':\n            return [ args.entity.strip() ]\n        elif args.entity_type == 'participant':\n            entities = _entity_paginator(args.project, args.workspace,\n                                     'pair', page_size=2000)\n            return [ e['name'] for e in entities if\n                     e['attributes']['participant']['entityName'] == args.entity]\n        r = fapi.get_entity(args.project, args.workspace, args.entity_type, args.entity)\n        fapi._check_response_code(r, 200)\n        pairs = r.json()['attributes'][\"pairs\"]['items']\n        return [ pair['entityName'] for pair in pairs]\n    return __get_entities(args, \"pair\", page_size=2000)",
    "docstring": "List pairs within a container."
  },
  {
    "code": "def rank(items, sequence=string.ascii_lowercase):\n    items = set(items)\n    return sum(1 << i for i, s in enumerate(sequence) if s in items)",
    "docstring": "Rank items from sequence in colexicographical order.\n\n    >>> [rank(i) for i in ('', 'a', 'b', 'ab', 'c')]\n    [0, 1, 2, 3, 4]\n\n    >>> rank('spam')\n    299009"
  },
  {
    "code": "def _decode_image(fobj, session, filename):\n  buf = fobj.read()\n  image = tfds.core.lazy_imports.cv2.imdecode(\n      np.fromstring(buf, dtype=np.uint8), flags=3)\n  if image is None:\n    logging.warning(\n        \"Image %s could not be decoded by OpenCV, falling back to TF\", filename)\n    try:\n      image = tf.image.decode_image(buf, channels=3)\n      image = session.run(image)\n    except tf.errors.InvalidArgumentError:\n      logging.fatal(\"Image %s could not be decoded by Tensorflow\", filename)\n  if len(image.shape) == 4:\n    image = image.reshape(image.shape[1:])\n  return image",
    "docstring": "Reads and decodes an image from a file object as a Numpy array.\n\n  The SUN dataset contains images in several formats (despite the fact that\n  all of them have .jpg extension). Some of them are:\n    - BMP (RGB)\n    - PNG (grayscale, RGBA, RGB interlaced)\n    - JPEG (RGB)\n    - GIF (1-frame RGB)\n  Since TFDS assumes that all images have the same number of channels, we\n  convert all of them to RGB.\n\n  Args:\n    fobj: File object to read from.\n    session: TF session used to decode the images.\n    filename: Filename of the original image in the archive.\n\n  Returns:\n    Numpy array with shape (height, width, channels)."
  },
  {
    "code": "def create_perm(self, using=None, *args, **kwargs):\n        from django.conf import settings\n        from django.contrib.auth.models import Permission\n        from django.contrib.contenttypes.models import ContentType\n        constance_dbs = getattr(settings, 'CONSTANCE_DBS', None)\n        if constance_dbs is not None and using not in constance_dbs:\n            return\n        if ContentType._meta.installed and Permission._meta.installed:\n            content_type, created = ContentType.objects.using(using).get_or_create(\n                app_label='constance',\n                model='config',\n            )\n            permission, created = Permission.objects.using(using).get_or_create(\n                content_type=content_type,\n                codename='change_config',\n                defaults={'name': 'Can change config'})",
    "docstring": "Creates a fake content type and permission\n        to be able to check for permissions"
  },
  {
    "code": "def _match(self, struct1, struct2, fu, s1_supercell=True, use_rms=False,\n               break_on_match=False):\n        ratio = fu if s1_supercell else 1/fu\n        if len(struct1) * ratio >= len(struct2):\n            return self._strict_match(\n                struct1, struct2, fu, s1_supercell=s1_supercell,\n                break_on_match=break_on_match, use_rms=use_rms)\n        else:\n            return self._strict_match(\n                struct2, struct1, fu, s1_supercell=(not s1_supercell),\n                break_on_match=break_on_match, use_rms=use_rms)",
    "docstring": "Matches one struct onto the other"
  },
  {
    "code": "def get_oldest_commit_date(self):\n        oldest_commit = self.get_oldest_commit()\n        return self.git.get_commit_date(oldest_commit, self.tz_name)",
    "docstring": "Get datetime of oldest commit involving this file\n\n        :returns: Datetime of oldest commit"
  },
  {
    "code": "def generate_method_deprecation_message(to_be_removed_in_version, old_method_name, method_name=None, module_name=None):\n    message = \"Call to deprecated function '{old_method_name}'. This method will be removed in version '{version}'\".format(\n        old_method_name=old_method_name,\n        version=to_be_removed_in_version,\n    )\n    if method_name is not None and module_name is not None:\n        message += \" Please use the '{method_name}' method on the '{module_name}' class moving forward.\".format(\n            method_name=method_name,\n            module_name=module_name,\n        )\n    return message",
    "docstring": "Generate a message to be used when warning about the use of deprecated methods.\n\n    :param to_be_removed_in_version: Version of this module the deprecated method will be removed in.\n    :type to_be_removed_in_version: str\n    :param old_method_name: Deprecated method name.\n    :type old_method_name:  str\n    :param method_name:  Method intended to replace the deprecated method indicated. This method's docstrings are\n        included in the decorated method's docstring.\n    :type method_name: str\n    :param module_name: Name of the module containing the new method to use.\n    :type module_name: str\n    :return: Full deprecation warning message for the indicated method.\n    :rtype: str"
  },
  {
    "code": "def _assign_values_to_unbound_vars(unbound_vars, unbound_var_values):\n  context = {}\n  for key, value in six.iteritems(unbound_var_values):\n    if key not in unbound_vars:\n      raise ValueError('unexpected key: %s. Legal values are: %s' %\n                       (key, list(six.iterkeys(unbound_vars))))\n    context[unbound_vars[key]] = value\n  unspecified = []\n  for unbound_var in six.itervalues(unbound_vars):\n    if unbound_var not in context:\n      if unbound_var.has_default():\n        context[unbound_var] = unbound_var.default\n      else:\n        unspecified.append(unbound_var.key)\n  if unspecified:\n    raise ValueError('Unspecified keys: %s' % unspecified)\n  return context",
    "docstring": "Assigns values to the vars and raises ValueError if one is missing."
  },
  {
    "code": "def _load_config(configfile, section=None):\n    if os.path.exists(configfile):\n        config = read_config(configfile)\n        if section is not None:\n            if section in config:\n                return config._sections[section]\n            else:\n                bot.warning('%s not found in %s' %(section, configfile))\n        return config",
    "docstring": "general function to load and return a configuration given a helper\n       name. This function is used for both the user config and global help me\n       config files."
  },
  {
    "code": "def make_valid_string(self, string=''):\n        if not self.is_valid_str(string):\n            if string in self.val_map and not self.allow_dups:\n                raise IndexError(\"Value {} has already been given to the sanitizer\".format(string))\n            internal_name = super(_NameSanitizer, self).make_valid_string()\n            self.val_map[string] = internal_name\n            return internal_name\n        else:\n            if self.map_valid:\n                self.val_map[string] = string\n            return string",
    "docstring": "Inputting a value for the first time"
  },
  {
    "code": "def unpack_types(types, args, argnames, major):\n    if len(types) > 0:\n        multiple = types[-1]._multiple\n    else:\n        multiple = False\n    if len(types) < len(args) and not multiple:\n        raise FailReply(\"Too many parameters given.\")\n    params = []\n    for i, kattype in enumerate(types):\n        name = \"\"\n        if i < len(argnames):\n            name = argnames[i]\n        params.append(Parameter(i+1, name, kattype, major))\n    if len(args) > len(types) and multiple:\n        for i in range(len(types), len(args)):\n            params.append(Parameter(i+1, name, kattype, major))\n    return map(lambda param, arg: param.unpack(arg), params, args)",
    "docstring": "Parse arguments according to types list.\n\n    Parameters\n    ----------\n    types : list of kattypes\n        The types of the arguments (in order).\n    args : list of strings\n        The arguments to parse.\n    argnames : list of strings\n        The names of the arguments.\n    major : integer\n        Major version of KATCP to use when packing types"
  },
  {
    "code": "def get_match_details(self, match_id=None, **kwargs):\n        if 'match_id' not in kwargs:\n            kwargs['match_id'] = match_id\n        url = self.__build_url(urls.GET_MATCH_DETAILS, **kwargs)\n        req = self.executor(url)\n        if self.logger:\n            self.logger.info('URL: {0}'.format(url))\n        if not self.__check_http_err(req.status_code):\n            return response.build(req, url, self.raw_mode)",
    "docstring": "Returns a dictionary containing the details for a Dota 2 match\n\n        :param match_id: (int, optional)\n        :return: dictionary of matches, see :doc:`responses </responses>`"
  },
  {
    "code": "def get_client_ip(self):\n        if self.client_ip:\n            return self.client_ip\n        try:\n            client = os.environ.get('SSH_CONNECTION',\n                                    os.environ.get('SSH_CLIENT'))\n            self.client_ip = client.split()[0]\n            self.logdebug('client_ip: %s\\n' % self.client_ip)\n            return self.client_ip\n        except:\n            raise SSHEnvironmentError('cannot identify the ssh client '\n                                      'IP address')",
    "docstring": "Return the client IP from the environment."
  },
  {
    "code": "def apply_child_computation(self, child_msg: Message) -> 'BaseComputation':\n        child_computation = self.generate_child_computation(child_msg)\n        self.add_child_computation(child_computation)\n        return child_computation",
    "docstring": "Apply the vm message ``child_msg`` as a child computation."
  },
  {
    "code": "def check(self, check_url=None):\n        if check_url is not None:\n            self.check_url = self._normalize_check_url(check_url)\n        response = None\n        sleeped = 0.0\n        t = datetime.now()\n        while not response:\n            try:\n                response = requests.get(self.check_url, verify=False)\n            except requests.exceptions.ConnectionError:\n                if sleeped > self.timeout:\n                    self._kill()\n                    raise LiveAndLetDieError(\n                        '{0} server {1} didn\\'t start in specified timeout {2} '\n                        'seconds!\\ncommand: {3}'.format(\n                            self.__class__.__name__,\n                            self.check_url,\n                            self.timeout,\n                            ' '.join(self.create_command())\n                        )\n                    )\n                time.sleep(1)\n                sleeped = _get_total_seconds(datetime.now() - t)\n        return _get_total_seconds(datetime.now() - t)",
    "docstring": "Checks whether a server is running.\n\n        :param str check_url:\n            URL where to check whether the server is running.\n            Default is ``\"http://{self.host}:{self.port}\"``."
  },
  {
    "code": "def to_ufo_components(self, ufo_glyph, layer):\n    pen = ufo_glyph.getPointPen()\n    for index, component in enumerate(layer.components):\n        pen.addComponent(component.name, component.transform)\n        if component.anchor:\n            if COMPONENT_INFO_KEY not in ufo_glyph.lib:\n                ufo_glyph.lib[COMPONENT_INFO_KEY] = []\n            ufo_glyph.lib[COMPONENT_INFO_KEY].append(\n                {\"name\": component.name, \"index\": index, \"anchor\": component.anchor}\n            )\n    for key in [\"alignment\", \"locked\", \"smartComponentValues\"]:\n        values = [getattr(c, key) for c in layer.components]\n        if any(values):\n            ufo_glyph.lib[_lib_key(key)] = values",
    "docstring": "Draw .glyphs components onto a pen, adding them to the parent glyph."
  },
  {
    "code": "def lock(self, atime=30, ltime=5, identifier=None):\n        if identifier is None:\n            identifier = nice_identifier()\n        if self._acquire_lock(identifier, atime, ltime) != identifier:\n            raise LockError(\"could not acquire lock\")\n        try:\n            self._session_lock_identifier = identifier\n            yield self\n        finally:\n            self._release_lock(identifier)\n            self._session_lock_identifier = None",
    "docstring": "Context manager to acquire the namespace global lock.\n\n        This is typically used for multi-step registry operations,\n        such as a read-modify-write sequence::\n\n            with registry.lock() as session:\n                d = session.get('dict', 'key')\n                del d['traceback']\n                session.set('dict', 'key', d)\n\n        Callers may provide their own `identifier`; if they do, they\n        must ensure that it is reasonably unique (e.g., a UUID).\n        Using a stored worker ID that is traceable back to the lock\n        holder is a good practice.\n\n        :param int atime: maximum time (in seconds) to acquire lock\n        :param int ltime: maximum time (in seconds) to own lock\n        :param str identifier: worker-unique identifier for the lock"
  },
  {
    "code": "def projection_to_raster_coords(self, lat, lon):\n        r_px_py = np.array([1, lon, lat])\n        tg = inv(np.array([[1, 0, 0], self.geotransform[0:3], self.geotransform[3:6]]))\n        return np.inner(tg, r_px_py)[1:]",
    "docstring": "Returns pixel centers.\n        See documentation for the GDAL function GetGeoTransform for details."
  },
  {
    "code": "def get_api_docs(routes):\n    routes = map(_get_tuple_from_route, routes)\n    documentation = []\n    for url, rh, methods in sorted(routes, key=lambda a: a[0]):\n        if issubclass(rh, APIHandler):\n            documentation.append(_get_route_doc(url, rh, methods))\n    documentation = (\n        \"**This documentation is automatically generated.**\\n\\n\" +\n        \"**Output schemas only represent `data` and not the full output; \" +\n        \"see output examples and the JSend specification.**\\n\" +\n        \"\\n<br>\\n<br>\\n\".join(documentation)\n    )\n    return documentation",
    "docstring": "Generates GitHub Markdown formatted API documentation using\n    provided schemas in RequestHandler methods and their docstrings.\n\n    :type  routes: [(url, RequestHandler), ...]\n    :param routes: List of routes (this is ideally all possible routes of the\n        app)\n    :rtype: str\n    :returns: generated GFM-formatted documentation"
  },
  {
    "code": "def create_contact(self, email=None, first_name=None, last_name=None, phone_number=None):\n        result = {}\n        if email:\n            result['email'] = email\n        if first_name is not None:\n            result['first_name'] = first_name\n        if last_name is not None:\n            result['last_name'] = last_name\n        if phone_number is not None:\n            result['phone_number'] = phone_number\n        return result if len(result) > 0 else None",
    "docstring": "Create a contant which is later passed to payment."
  },
  {
    "code": "def error(self, correlation_id, error, message, *args, **kwargs):\n        self._format_and_write(LogLevel.Error, correlation_id, error, message, args, kwargs)",
    "docstring": "Logs recoverable application error.\n\n        :param correlation_id: (optional) transaction id to trace execution through call chain.\n\n        :param error: an error object associated with this message.\n\n        :param message: a human-readable message to log.\n\n        :param args: arguments to parameterize the message.\n\n        :param kwargs: arguments to parameterize the message."
  },
  {
    "code": "def _check_db_exists(self, instance):\n        dsn, host, username, password, database, driver = self._get_access_info(instance, self.DEFAULT_DB_KEY)\n        context = \"{} - {}\".format(host, database)\n        if self.existing_databases is None:\n            cursor = self.get_cursor(instance, None, self.DEFAULT_DATABASE)\n            try:\n                self.existing_databases = {}\n                cursor.execute(DATABASE_EXISTS_QUERY)\n                for row in cursor:\n                    self.existing_databases[row.name] = True\n            except Exception as e:\n                self.log.error(\"Failed to check if database {} exists: {}\".format(database, e))\n                return False, context\n            finally:\n                self.close_cursor(cursor)\n        return database in self.existing_databases, context",
    "docstring": "Check if the database we're targeting actually exists\n        If not then we won't do any checks\n        This allows the same config to be installed on many servers but fail gracefully"
  },
  {
    "code": "def _flip_lr(x):\n    \"Flip `x` horizontally.\"\n    if isinstance(x, ImagePoints):\n        x.flow.flow[...,0] *= -1\n        return x\n    return tensor(np.ascontiguousarray(np.array(x)[...,::-1]))",
    "docstring": "Flip `x` horizontally."
  },
  {
    "code": "def CopyAttributesFromSessionCompletion(self, session_completion):\n    if self.identifier != session_completion.identifier:\n      raise ValueError('Session identifier mismatch.')\n    self.aborted = session_completion.aborted\n    if session_completion.analysis_reports_counter:\n      self.analysis_reports_counter = (\n          session_completion.analysis_reports_counter)\n    self.completion_time = session_completion.timestamp\n    if session_completion.event_labels_counter:\n      self.event_labels_counter = session_completion.event_labels_counter\n    if session_completion.parsers_counter:\n      self.parsers_counter = session_completion.parsers_counter",
    "docstring": "Copies attributes from a session completion.\n\n    Args:\n      session_completion (SessionCompletion): session completion attribute\n          container.\n\n    Raises:\n      ValueError: if the identifier of the session completion does not match\n          that of the session."
  },
  {
    "code": "def get(name, function=None):\n        if function is not None:\n            if hasattr(function, Settings.FUNCTION_SETTINGS_NAME):\n                if name in getattr(function, Settings.FUNCTION_SETTINGS_NAME):\n                    return getattr(function, Settings.FUNCTION_SETTINGS_NAME)[name]\n        return Settings.__global_setting_values[name]",
    "docstring": "Get a setting.\n\n        `name` should be the name of the setting to look for.  If the\n        optional argument `function` is passed, this will look for a\n        value local to the function before retrieving the global\n        value."
  },
  {
    "code": "def identity(self):\n        if self.dataset is None:\n            s = object_session(self)\n            ds = s.query(Dataset).filter(Dataset.id_ == self.d_id).one()\n        else:\n            ds = self.dataset\n        d = {\n            'id': self.id,\n            'vid': self.vid,\n            'name': self.name,\n            'vname': self.vname,\n            'ref': self.ref,\n            'space': self.space,\n            'time': self.time,\n            'table': self.table_name,\n            'grain': self.grain,\n            'variant': self.variant,\n            'segment': self.segment,\n            'format': self.format if self.format else 'db'\n        }\n        return PartitionIdentity.from_dict(dict(list(ds.dict.items()) + list(d.items())))",
    "docstring": "Return this partition information as a PartitionId."
  },
  {
    "code": "def list_registered_stateful_ops_without_inputs():\n  return set([\n      name\n      for name, op in op_def_registry.get_registered_ops().items()\n      if op.is_stateful and not op.input_arg\n  ])",
    "docstring": "Returns set of registered stateful ops that do not expect inputs.\n\n  This list is used to identify the ops to be included in the state-graph and\n  that are subsequently fed into the apply-graphs.\n\n  Returns:\n    A set of strings."
  },
  {
    "code": "def upgradeUpload(self, file):\n        files = {'upfile': open(file, 'rb')}\n        return self.__post_files('/upgrade/upload',\n                                 files=files)",
    "docstring": "Upgrade the firmware of the miner."
  },
  {
    "code": "def write_config(self):\n        template = util.render_template(\n            self._get_config_template(), config_options=self.config_options)\n        util.write_file(self.config_file, template)",
    "docstring": "Writes the provisioner's config file to disk and returns None.\n\n        :return: None"
  },
  {
    "code": "def add_field_with_label(self, key, label_description, field):\n        self.inputs[key] = field\n        label = Label(label_description)\n        label.style['margin'] = '0px 5px'\n        label.style['min-width'] = '30%'\n        container = HBox()\n        container.style.update({'justify-content':'space-between', 'overflow':'auto', 'padding':'3px'})\n        container.append(label, key='lbl' + key)\n        container.append(self.inputs[key], key=key)\n        self.container.append(container, key=key)",
    "docstring": "Adds a field to the dialog together with a descriptive label and a unique identifier.\n\n        Note: You can access to the fields content calling the function GenericDialog.get_field(key).\n\n        Args:\n            key (str): The unique identifier for the field.\n            label_description (str): The string content of the description label.\n            field (Widget): The instance of the field Widget. It can be for example a TextInput or maybe\n            a custom widget."
  },
  {
    "code": "def describe_api_integration(restApiId, resourcePath, httpMethod, region=None, key=None, keyid=None, profile=None):\n    try:\n        resource = describe_api_resource(restApiId, resourcePath, region=region,\n                                         key=key, keyid=keyid, profile=profile).get('resource')\n        if resource:\n            conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n            integration = conn.get_integration(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod)\n            return {'integration': _convert_datetime_str(integration)}\n        return {'error': 'no such resource'}\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Get an integration for a given method in a given API\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_apigateway.describe_api_integration restApiId resourcePath httpMethod"
  },
  {
    "code": "def stop_tracing_process(self, pid):\n        for thread in self.system.get_process(pid).iter_threads():\n            self.__stop_tracing(thread)",
    "docstring": "Stop tracing mode for all threads in the given process.\n\n        @type  pid: int\n        @param pid: Global ID of process to stop tracing."
  },
  {
    "code": "def create(self, public_key, friendly_name=values.unset,\n               account_sid=values.unset):\n        data = values.of({\n            'PublicKey': public_key,\n            'FriendlyName': friendly_name,\n            'AccountSid': account_sid,\n        })\n        payload = self._version.create(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return PublicKeyInstance(self._version, payload, )",
    "docstring": "Create a new PublicKeyInstance\n\n        :param unicode public_key: A URL encoded representation of the public key\n        :param unicode friendly_name: A string to describe the resource\n        :param unicode account_sid: The Subaccount this Credential should be associated with.\n\n        :returns: Newly created PublicKeyInstance\n        :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyInstance"
  },
  {
    "code": "def select_device_by_load(wproc=0.5, wmem=0.5):\n    ids = device_by_load(wproc=wproc, wmem=wmem)\n    cp.cuda.Device(ids[0]).use()\n    return ids[0]",
    "docstring": "Set the current device for cupy as the device with the lowest\n    weighted average of processor and memory load."
  },
  {
    "code": "def render(self):\n        \"Re-render Jupyter cell for batch of images.\"\n        clear_output()\n        self.write_csv()\n        if self.empty() and self._skipped>0:\n            return display(f'No images to show :). {self._skipped} pairs were '\n                    f'skipped since at least one of the images was deleted by the user.')\n        elif self.empty():\n            return display('No images to show :)')\n        if self.batch_contains_deleted():\n            self.next_batch(None)\n            self._skipped += 1\n        else:\n            display(self.make_horizontal_box(self.get_widgets(self._duplicates)))\n            display(self.make_button_widget('Next Batch', handler=self.next_batch, style=\"primary\"))",
    "docstring": "Re-render Jupyter cell for batch of images."
  },
  {
    "code": "def concatenate(self, other):\n        other = as_shape(other)\n        if self._dims is None or other.dims is None:\n            return unknown_shape()\n        else:\n            return TensorShape(self._dims + other.dims)",
    "docstring": "Returns the concatenation of the dimension in `self` and `other`.\n\n        *N.B.* If either `self` or `other` is completely unknown,\n        concatenation will discard information about the other shape. In\n        future, we might support concatenation that preserves this\n        information for use with slicing.\n\n        Args:\n          other: Another `TensorShape`.\n\n        Returns:\n          A `TensorShape` whose dimensions are the concatenation of the\n          dimensions in `self` and `other`."
  },
  {
    "code": "def splitlines(self, keepends=False):\n        lines = self.split('\\n')\n        return [line+'\\n' for line in lines] if keepends else (\n               lines if lines[-1] else lines[:-1])",
    "docstring": "Return a list of lines, split on newline characters,\n        include line boundaries, if keepends is true."
  },
  {
    "code": "def output_files(self):\n        outs = [os.path.join(self.address.repo, self.address.path, x)\n                for x in self.params['outs']]\n        return outs",
    "docstring": "Returns list of output files from this rule, relative to buildroot.\n\n        In this case it's simple (for now) - the output files are enumerated in\n        the rule definition."
  },
  {
    "code": "def check_complicance(self):\n        if(any([ma for ma in vars(self)\n                if ma.startswith('media_') and getattr(self, ma)])\n           and not self.media_group\n           and not self.media_content\n           and not self.media_player\n           and not self.media_peerLink\n           and not self.media_location\n           ):\n            raise AttributeError(\n                \"Using media elements requires the specification of at least \"\n                \"one of the following elements: 'media_group', \"\n                \"'media_content', 'media_player', 'media_peerLink' or \"\n                \"'media_location'.\")\n        if not self.media_player:\n            if self.media_content:\n                if isinstance(self.media_content, list):\n                    if not all([False for mc in self.media_content if\n                                'url' not in mc.element_attrs]):\n                        raise AttributeError(\n                            \"MediaRSSItems require a media_player attribute \"\n                            \"if a media_content has no url set.\")\n                else:\n                    if not self.media_content.element_attrs['url']:\n                        raise AttributeError(\n                            \"MediaRSSItems require a media_player attribute \"\n                            \"if a media_content has no url set.\")\n                pass\n            elif self.media_group:\n                raise NotImplementedError(\n                    \"MediaRSSItem: media_group check not implemented yet.\")",
    "docstring": "Check compliance with Media RSS Specification, Version 1.5.1.\n\n        see http://www.rssboard.org/media-rss\n        Raises AttributeError on error."
  },
  {
    "code": "def user_remove(user,\n                host='localhost',\n                **connection_args):\n    dbc = _connect(**connection_args)\n    if dbc is None:\n        return False\n    cur = dbc.cursor()\n    qry = 'DROP USER %(user)s@%(host)s'\n    args = {}\n    args['user'] = user\n    args['host'] = host\n    try:\n        _execute(cur, qry, args)\n    except MySQLdb.OperationalError as exc:\n        err = 'MySQL Error {0}: {1}'.format(*exc.args)\n        __context__['mysql.error'] = err\n        log.error(err)\n        return False\n    if not user_exists(user, host, **connection_args):\n        log.info('User \\'%s\\'@\\'%s\\' has been removed', user, host)\n        return True\n    log.info('User \\'%s\\'@\\'%s\\' has NOT been removed', user, host)\n    return False",
    "docstring": "Delete MySQL user\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' mysql.user_remove frank localhost"
  },
  {
    "code": "def time_to_seconds(x):\n    if isinstance(x, time):\n        return ((((x.hour * 60) + x.minute) * 60 + x.second) * 10**6 +\n                x.microsecond) / 10**6\n    if is_str(x):\n        return x\n    return x and max(0, min(x, 24 * 3600 - 10**-6))",
    "docstring": "Convert a time in a seconds sum"
  },
  {
    "code": "def process_prefix(self, prefix: str) -> Union[Namespace, None]:\n        if self.namespaces.get(prefix):\n            return self.namespaces[prefix]\n        iri: str = common_namespaces.get(prefix)\n        if iri:\n            return self.add_namespace(prefix, iri)",
    "docstring": "Add namespace to graph if it has a local match\n\n        This allows qnames to be used without adding their respected namespaces if they are in\n        the common_namespaces local dict. This is is to save a butt-ton of time trying to see what\n        the ontology has as far as uris go.\n\n        Args: prefix: prefix of the uri in the rdflib namespace to be checked if it exists in\n            the local dict of common_namespaces.\n\n        Returns: Namespace of uri if add or already exists; else None"
  },
  {
    "code": "def done(self):\n        try:\n            scoop._control.execQueue.remove(self)\n            scoop._control.execQueue.socket.sendFuture(self)\n        except ValueError as e:\n            pass\n        scoop._control.execQueue.updateQueue()\n        return self._ended()",
    "docstring": "Returns True if the call was successfully cancelled or finished\n           running, False otherwise. This function updates the executionQueue\n           so it receives all the awaiting message."
  },
  {
    "code": "def add_personalization(self, personalization, index=0):\n        self._personalizations = self._ensure_append(\n            personalization, self._personalizations, index)",
    "docstring": "Add a Personaliztion object\n\n        :param personalizations: Add a Personalization object\n        :type personalizations: Personalization\n        :param index: The index where to add the Personalization\n        :type index: int"
  },
  {
    "code": "def generate_report(book_url):\n    shares_no = None\n    avg_price = None\n    stock_template = templates.load_jinja_template(\"stock_template.html\")\n    stock_rows = \"\"\n    with piecash.open_book(book_url, readonly=True, open_if_lock=True) as book:\n        all_stocks = portfoliovalue.get_all_stocks(book)\n        for stock in all_stocks:\n            for_date = datetime.today().date\n            model = portfoliovalue.get_stock_model_from(book, stock, for_date)\n            stock_rows += stock_template.render(model)\n    template = templates.load_jinja_template(\"template.html\")\n    result = template.render(**locals())\n    return result",
    "docstring": "Generates an HTML report content."
  },
  {
    "code": "def _all(self, *args, **kwargs):\n        data = dict()\n        data['software'] = self._software(**kwargs)\n        data['system'] = self._system(**kwargs)\n        data['services'] = self._services(**kwargs)\n        try:\n            data['configuration'] = self._configuration(**kwargs)\n        except InspectorQueryException as ex:\n            data['configuration'] = 'N/A'\n            log.error(ex)\n        data['payload'] = self._payload(**kwargs) or 'N/A'\n        return data",
    "docstring": "Return all the summary of the particular system."
  },
  {
    "code": "def build_from_yamlstr(cls, yamlstr):\n        top_dict = yaml.safe_load(yamlstr)\n        coordsys = top_dict.pop('coordsys')\n        output_list = []\n        for e_key, e_dict in sorted(top_dict.items()):\n            if e_key == 'coordsys':\n                continue\n            e_dict = top_dict[e_key]\n            e_dict['coordsys'] = coordsys\n            output_list += cls.build_from_energy_dict(e_key, e_dict)\n        return output_list",
    "docstring": "Build a list of components from a yaml string"
  },
  {
    "code": "def beam_splitter(ax, p0, size=2.54, alpha=0, format=None, **kwds):\r\n    r\r\n    if format is None: format = 'k-'\r\n    a = size/2\r\n    x0 = [a, -a, -a, a, a, -a]\r\n    y0 = [a, a, -a, -a, a, -a]\r\n    cur_list = [(x0, y0)]\r\n    cur_list = rotate_and_traslate(cur_list, alpha, p0)\r\n    for curi in cur_list: ax.plot(curi[0], curi[1], format, **kwds)",
    "docstring": "r\"\"\"Draw a beam splitter."
  },
  {
    "code": "def time_stats(self, **kwargs):\n        if 'time_stats' in self.attributes:\n            return self.attributes['time_stats']\n        path = '%s/%s/time_stats' % (self.manager.path, self.get_id())\n        return self.manager.gitlab.http_get(path, **kwargs)",
    "docstring": "Get time stats for the object.\n\n        Args:\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabTimeTrackingError: If the time tracking update cannot be done"
  },
  {
    "code": "def to_dict(self):\r\n        d = {}\r\n        d['start'] = date_to_str(self.start)\r\n        d['end'] = date_to_str(self.end)\r\n        return d",
    "docstring": "Transform the date-range to a dict."
  },
  {
    "code": "def from_file(cls, fp, is_outlook=False):\n        log.debug(\"Parsing email from file {!r}\".format(fp))\n        with ported_open(fp) as f:\n            message = email.message_from_file(f)\n        if is_outlook:\n            log.debug(\"Removing temp converted Outlook email {!r}\".format(fp))\n            os.remove(fp)\n        return cls(message)",
    "docstring": "Init a new object from a file path.\n\n        Args:\n            fp (string): file path of raw email\n            is_outlook (boolean): if True is an Outlook email\n\n        Returns:\n            Instance of MailParser"
  },
  {
    "code": "def query(self, query, max_results=None, timeout=0, dry_run=False, use_legacy_sql=None, external_udf_uris=None):\n        logger.debug('Executing query: %s' % query)\n        query_data = {\n            'query': query,\n            'timeoutMs': timeout * 1000,\n            'dryRun': dry_run,\n            'maxResults': max_results\n        }\n        if use_legacy_sql is not None:\n            query_data['useLegacySql'] = use_legacy_sql\n        if external_udf_uris:\n            query_data['userDefinedFunctionResources'] = \\\n                [ {'resourceUri': u} for u in external_udf_uris ]\n        return self._submit_query_job(query_data)",
    "docstring": "Submit a query to BigQuery.\n\n        Parameters\n        ----------\n        query : str\n            BigQuery query string\n        max_results : int, optional\n            The maximum number of rows to return per page of results.\n        timeout : float, optional\n            How long to wait for the query to complete, in seconds before\n            the request times out and returns.\n        dry_run : bool, optional\n            If True, the query isn't actually run. A valid query will return an\n            empty response, while an invalid one will return the same error\n            message it would if it wasn't a dry run.\n        use_legacy_sql : bool, optional. Default True.\n            If False, the query will use BigQuery's standard SQL (https://cloud.google.com/bigquery/sql-reference/)\n        external_udf_uris : list, optional\n            Contains external UDF URIs. If given, URIs must be Google Cloud\n            Storage and have .js extensions.\n\n\n        Returns\n        -------\n        tuple\n            (job id, query results) if the query completed. If dry_run is True,\n            job id will be None and results will be empty if the query is valid\n            or a ``dict`` containing the response if invalid.\n\n        Raises\n        ------\n        BigQueryTimeoutException\n            on timeout"
  },
  {
    "code": "def from_xml(self, doc):\n        import xml.sax\n        handler = DomainDumpParser(self)\n        xml.sax.parse(doc, handler)\n        return handler",
    "docstring": "Load this domain based on an XML document"
  },
  {
    "code": "def download(self):\n\t\tself.page = requests.get(self.url)\n\t\tself.tree = html.fromstring(self.page.text)",
    "docstring": "Downloads HTML from url."
  },
  {
    "code": "def notimplemented (func):\n    def newfunc (*args, **kwargs):\n        co = func.func_code\n        attrs = (co.co_name, co.co_filename, co.co_firstlineno)\n        raise NotImplementedError(\"function %s at %s:%d is not implemented\" % attrs)\n    return update_func_meta(newfunc, func)",
    "docstring": "Raises a NotImplementedError if the function is called."
  },
  {
    "code": "def _read_routes_c_v1():\n    def _extract_ip(obj):\n        return inet_ntop(socket.AF_INET, struct.pack(\"<I\", obj))\n    routes = []\n    for route in GetIpForwardTable():\n        ifIndex = route['ForwardIfIndex']\n        dest = route['ForwardDest']\n        netmask = route['ForwardMask']\n        nexthop = _extract_ip(route['ForwardNextHop'])\n        metric = route['ForwardMetric1']\n        try:\n            iface = dev_from_index(ifIndex)\n            if iface.ip == \"0.0.0.0\":\n                continue\n        except ValueError:\n            continue\n        ip = iface.ip\n        metric = metric + iface.ipv4_metric\n        routes.append((dest, netmask, nexthop, iface, ip, metric))\n    return routes",
    "docstring": "Retrieve Windows routes through a GetIpForwardTable call.\n\n    This is compatible with XP but won't get IPv6 routes."
  },
  {
    "code": "def zincr(self, name, key, amount=1):\n        amount = get_integer('amount', amount)        \n        return self.execute_command('zincr', name, key, amount)",
    "docstring": "Increase the score of ``key`` in zset ``name`` by ``amount``. If no key\n        exists, the value will be initialized as ``amount``\n\n        Like **Redis.ZINCR**\n\n        :param string name: the zset name\n        :param string key: the key name        \n        :param int amount: increments\n        :return: the integer value of ``key`` in zset ``name``\n        :rtype: int\n\n        >>> ssdb.zincr('zset_2', 'key1', 7)\n        49\n        >>> ssdb.zincr('zset_2', 'key2', 3)\n        317\n        >>> ssdb.zincr('zset_2', 'key_not_exists', 101)\n        101\n        >>> ssdb.zincr('zset_not_exists', 'key_not_exists', 8848)\n        8848"
  },
  {
    "code": "def get_table(self, name='Meta', h5loc='/meta'):\n        if not self.meta:\n            return None\n        data = defaultdict(list)\n        for entry in self.meta:\n            for key, value in entry.items():\n                data[key].append(value)\n        dtypes = []\n        for key, values in data.items():\n            max_len = max(map(len, values))\n            dtype = 'S{}'.format(max_len)\n            dtypes.append((key, dtype))\n        tab = Table(\n            data, dtype=dtypes, h5loc=h5loc, name='Meta', h5singleton=True\n        )\n        return tab",
    "docstring": "Convert metadata to a KM3Pipe Table.\n\n        Returns `None` if there is no data.\n\n        Each column's dtype will be set to a fixed size string (numpy.string_)\n        with the length of the longest entry, since writing variable length\n        strings does not fit the current scheme."
  },
  {
    "code": "def create_snmp_manager(self, manager, host, **kwargs):\n        data = {\"host\": host}\n        data.update(kwargs)\n        return self._request(\"POST\", \"snmp/{0}\".format(manager), data)",
    "docstring": "Create an SNMP manager.\n\n        :param manager: Name of manager to be created.\n        :type manager: str\n        :param host: IP address or DNS name of SNMP server to be used.\n        :type host: str\n        :param \\*\\*kwargs: See the REST API Guide on your array for the\n                           documentation on the request:\n                           **POST snmp/:manager**\n        :type \\*\\*kwargs: optional\n\n        :returns: A dictionary describing the created SNMP manager.\n        :rtype: ResponseDict"
  },
  {
    "code": "def GetGroups(r, bulk=False):\n    if bulk:\n        return r.request(\"get\", \"/2/groups\", query={\"bulk\": 1})\n    else:\n        groups = r.request(\"get\", \"/2/groups\")\n        return r.applier(itemgetters(\"name\"), groups)",
    "docstring": "Gets all node groups in the cluster.\n\n    @type bulk: bool\n    @param bulk: whether to return all information about the groups\n\n    @rtype: list of dict or str\n    @return: if bulk is true, a list of dictionaries with info about all node\n            groups in the cluster, else a list of names of those node groups"
  },
  {
    "code": "def fetch_identifier_component(self, endpoint_name, identifier_data, query_params=None):\n        if query_params is None:\n            query_params = {}\n        identifier_input = self.get_identifier_input(identifier_data)\n        return self._api_client.fetch(endpoint_name, identifier_input, query_params)",
    "docstring": "Common method for handling parameters before passing to api_client"
  },
  {
    "code": "def timethis(func):\n    func_module, func_name = func.__module__, func.__name__\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        start = _time_perf_counter()\n        r = func(*args, **kwargs)\n        end = _time_perf_counter()\n        print('timethis : <{}.{}> : {}'.format(func_module, func_name, end - start))\n        return r\n    return wrapper",
    "docstring": "A wrapper use for timeit."
  },
  {
    "code": "def find_needed_formatter(input_format, output_format):\n    selected_registry = [re.cls for re in registry if re.category==RegistryCategories.formatters]\n    needed_formatters = []\n    for formatter in selected_registry:\n        formatter_inst = formatter()\n        if input_format in formatter_inst.input_formats and output_format in formatter_inst.output_formats:\n            needed_formatters.append(formatter)\n    if len(needed_formatters)>0:\n        return needed_formatters[0]\n    return None",
    "docstring": "Find a data formatter given an input and output format\n    input_format - needed input format.  see utils.input.dataformats\n    output_format - needed output format.  see utils.input.dataformats"
  },
  {
    "code": "def check_with_pep8(source_code, filename=None):\r\n    try:\r\n        args = get_checker_executable('pycodestyle')\r\n        results = check(args, source_code, filename=filename, options=['-r'])\r\n    except Exception:\r\n        results = []\r\n        if DEBUG_EDITOR:\r\n            traceback.print_exc()\n    return results",
    "docstring": "Check source code with pycodestyle"
  },
  {
    "code": "def get_git_root(index=3):\n    path = get_current_path(index=index)\n    while True:\n        git_path = os.path.join(path, '.git')\n        if os.path.isdir(git_path):\n            return path\n        if os.path.dirname(path) == path:\n            raise RuntimeError(\"Cannot find git root\")\n        path = os.path.split(path)[0]",
    "docstring": "Get the path of the git root directory of the caller's file\n    Raises a RuntimeError if a git repository cannot be found"
  },
  {
    "code": "def create(self, table_id, schema):\n        from google.cloud.bigquery import SchemaField\n        from google.cloud.bigquery import Table\n        if self.exists(table_id):\n            raise TableCreationError(\n                \"Table {0} already \" \"exists\".format(table_id)\n            )\n        if not _Dataset(self.project_id, credentials=self.credentials).exists(\n            self.dataset_id\n        ):\n            _Dataset(\n                self.project_id,\n                credentials=self.credentials,\n                location=self.location,\n            ).create(self.dataset_id)\n        table_ref = self.client.dataset(self.dataset_id).table(table_id)\n        table = Table(table_ref)\n        for field in schema[\"fields\"]:\n            if \"mode\" not in field:\n                field[\"mode\"] = \"NULLABLE\"\n        table.schema = [\n            SchemaField.from_api_repr(field) for field in schema[\"fields\"]\n        ]\n        try:\n            self.client.create_table(table)\n        except self.http_error as ex:\n            self.process_http_error(ex)",
    "docstring": "Create a table in Google BigQuery given a table and schema\n\n        Parameters\n        ----------\n        table : str\n            Name of table to be written\n        schema : str\n            Use the generate_bq_schema to generate your table schema from a\n            dataframe."
  },
  {
    "code": "def print_details(self):\n\t\tprint(\"Title:\", self.title)\n\t\tprint(\"Category:\", self.category)\n\t\tprint(\"Page: \", self.page)\n\t\tprint(\"Size: \", self.size)\n\t\tprint(\"Files: \", self.files)\n\t\tprint(\"Age: \", self.age)\n\t\tprint(\"Seeds:\", self.seeders)\n\t\tprint(\"Leechers: \", self.leechers)\n\t\tprint(\"Magnet: \", self.magnet)\n\t\tprint(\"Download: \", self.download)\n\t\tprint(\"Verified:\", self.isVerified)",
    "docstring": "Print torrent details"
  },
  {
    "code": "def undo(self, key_value, modifier_mask):\n        for key, tab in gui_singletons.main_window_controller.get_controller('states_editor_ctrl').tabs.items():\n            if tab['controller'].get_controller('source_ctrl') is not None and \\\n                    react_to_event(self.view, tab['controller'].get_controller('source_ctrl').view.textview,\n                                   (key_value, modifier_mask)) or \\\n                tab['controller'].get_controller('description_ctrl') is not None and \\\n                    react_to_event(self.view, tab['controller'].get_controller('description_ctrl').view.textview,\n                                   (key_value, modifier_mask)):\n                return False\n        if self._selected_sm_model is not None:\n            self._selected_sm_model.history.undo()\n            return True\n        else:\n            logger.debug(\"Undo is not possible now as long as no state_machine is selected.\")",
    "docstring": "Undo for selected state-machine if no state-source-editor is open and focused in states-editor-controller.\n\n        :return: True if a undo was performed, False if focus on source-editor.\n        :rtype: bool"
  },
  {
    "code": "def run_ps(self, script):\n        encoded_ps = b64encode(script.encode('utf_16_le')).decode('ascii')\n        rs = self.run_cmd('powershell -encodedcommand {0}'.format(encoded_ps))\n        if len(rs.std_err):\n            rs.std_err = self._clean_error_msg(rs.std_err)\n        return rs",
    "docstring": "base64 encodes a Powershell script and executes the powershell\n        encoded script command"
  },
  {
    "code": "def exists(self, filename):\n        result = False\n        if is_package(filename):\n            packages = self.connection[\"jss\"].Package().retrieve_all()\n            for package in packages:\n                if package.findtext(\"filename\") == filename:\n                    result = True\n                    break\n        else:\n            scripts = self.connection[\"jss\"].Script().retrieve_all()\n            for script in scripts:\n                if script.findtext(\"filename\") == filename:\n                    result = True\n                    break\n        return result",
    "docstring": "Check for the existence of a package or script.\n\n        Unlike other DistributionPoint types, JDS and CDP types have no\n        documented interface for checking whether the server and its\n        children have a complete copy of a file. The best we can do is\n        check for an object using the API /packages URL--JSS.Package()\n        or /scripts and look for matches on the filename.\n\n        If this is not enough, please use the alternate\n        exists_with_casper method.  For example, it's possible to create\n        a Package object but never upload a package file, and this\n        method will still return \"True\".\n\n        Also, this may be slow, as it needs to retrieve the complete\n        list of packages from the server."
  },
  {
    "code": "def set_index(self, index):\n        self.setCurrentIndex(index)\n        self.new_root.emit(index)\n        self.scrollTo(index)",
    "docstring": "Set the current index to the row of the given index\n\n        :param index: the index to set the level to\n        :type index: QtCore.QModelIndex\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def _load_type_counts(self):\r\n\t\trel_path = os.path.join(CLTK_DATA_DIR,\r\n                                'old_english',\r\n                                'model',\r\n                                'old_english_models_cltk',\r\n                                'data',\r\n                                'oe.counts')\r\n\t\tpath = os.path.expanduser(rel_path)\r\n\t\tself.type_counts = {}\r\n\t\twith open(path, 'r') as infile:\r\n\t\t\tlines = infile.read().splitlines()\r\n\t\t\tfor line in lines:\r\n\t\t\t\tcount, word = line.split()\r\n\t\t\t\tself.type_counts[word] = int(count)",
    "docstring": "Load the table of frequency counts of word forms."
  },
  {
    "code": "def _vector_pattern_uniform_op_left(func):\r\n        @wraps(func)\r\n        def verif(self, patt):\r\n            if isinstance(patt, TransversePatternUniform):\r\n                if self._tdsphere.shape == patt._tdsphere.shape:\r\n                    return TransversePatternUniform(func(self, self._tdsphere,\r\n                                                     patt._tdsphere),\r\n                                                func(self, self._pdsphere,\r\n                                                     patt._pdsphere),\r\n                                                doublesphere=True)\r\n                else:\r\n                    raise ValueError(err_msg['VP_sz_msmtch'] % \\\r\n                                            (self.nrows, self.ncols,\r\n                                            patt.nrows, patt.ncols))\r\n            elif isinstance(patt, numbers.Number):\r\n                return TransversePatternUniform(func(self, self._tdsphere, patt),\r\n                                            func(self, self._pdsphere, patt),\r\n                                            doublesphere=True)\r\n            else:\r\n                raise TypeError(err_msg['no_combi_VP'])\r\n        return verif",
    "docstring": "decorator for operator overloading when VectorPatternUniform is on \r\n        the left"
  },
  {
    "code": "def run_sls_remove(sls_cmd, env_vars):\n    sls_process = subprocess.Popen(sls_cmd,\n                                   stdout=subprocess.PIPE,\n                                   env=env_vars)\n    stdoutdata, _stderrdata = sls_process.communicate()\n    sls_return = sls_process.wait()\n    print(stdoutdata)\n    if sls_return != 0 and (sls_return == 1 and not (\n            re.search(r\"Stack '.*' does not exist\", stdoutdata))):\n        sys.exit(sls_return)",
    "docstring": "Run sls remove command."
  },
  {
    "code": "def list(self, full=False):\n        if self.is_api:\n            return self._list_api(full=full)\n        else:\n            return self._list_fs(full=full)",
    "docstring": "List all of the bundles in the remote"
  },
  {
    "code": "def is_canonical_address(address: Any) -> bool:\n    if not is_bytes(address) or len(address) != 20:\n        return False\n    return address == to_canonical_address(address)",
    "docstring": "Returns `True` if the `value` is an address in its canonical form."
  },
  {
    "code": "def irfftn(a, s=None, axes=None, norm=None):\n    output = mkl_fft.irfftn_numpy(a, s, axes)\n    if _unitary(norm):\n        output *= sqrt(_tot_size(output, axes))\n    return output",
    "docstring": "Compute the inverse of the N-dimensional FFT of real input.\n\n    This function computes the inverse of the N-dimensional discrete\n    Fourier Transform for real input over any number of axes in an\n    M-dimensional array by means of the Fast Fourier Transform (FFT).  In\n    other words, ``irfftn(rfftn(a), a.shape) == a`` to within numerical\n    accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`,\n    and for the same reason.)\n\n    The input should be ordered in the same way as is returned by `rfftn`,\n    i.e. as for `irfft` for the final transformation axis, and as for `ifftn`\n    along all the other axes.\n\n    Parameters\n    ----------\n    a : array_like\n        Input array.\n    s : sequence of ints, optional\n        Shape (length of each transformed axis) of the output\n        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the\n        number of input points used along this axis, except for the last axis,\n        where ``s[-1]//2+1`` points of the input are used.\n        Along any axis, if the shape indicated by `s` is smaller than that of\n        the input, the input is cropped.  If it is larger, the input is padded\n        with zeros. If `s` is not given, the shape of the input along the\n        axes specified by `axes` is used.\n    axes : sequence of ints, optional\n        Axes over which to compute the inverse FFT. If not given, the last\n        `len(s)` axes are used, or all axes if `s` is also not specified.\n        Repeated indices in `axes` means that the inverse transform over that\n        axis is performed multiple times.\n    norm : {None, \"ortho\"}, optional\n        .. versionadded:: 1.10.0\n        Normalization mode (see `numpy.fft`). Default is None.\n\n    Returns\n    -------\n    out : ndarray\n        The truncated or zero-padded input, transformed along the axes\n        indicated by `axes`, or by a combination of `s` or `a`,\n        as explained in the parameters section above.\n        The length of each transformed axis is as given by the corresponding\n        element of `s`, or the length of the input in every axis except for the\n        last one if `s` is not given.  In the final transformed axis the length\n        of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the\n        length of the final transformed axis of the input.  To get an odd\n        number of output points in the final axis, `s` must be specified.\n\n    Raises\n    ------\n    ValueError\n        If `s` and `axes` have different length.\n    IndexError\n        If an element of `axes` is larger than than the number of axes of `a`.\n\n    See Also\n    --------\n    rfftn : The forward n-dimensional FFT of real input,\n            of which `ifftn` is the inverse.\n    fft : The one-dimensional FFT, with definitions and conventions used.\n    irfft : The inverse of the one-dimensional FFT of real input.\n    irfft2 : The inverse of the two-dimensional FFT of real input.\n\n    Notes\n    -----\n    See `fft` for definitions and conventions used.\n\n    See `rfft` for definitions and conventions used for real input.\n\n    Examples\n    --------\n    >>> a = np.zeros((3, 2, 2))\n    >>> a[0, 0, 0] = 3 * 2 * 2\n    >>> np.fft.irfftn(a)\n    array([[[ 1.,  1.],\n            [ 1.,  1.]],\n           [[ 1.,  1.],\n            [ 1.,  1.]],\n           [[ 1.,  1.],\n            [ 1.,  1.]]])"
  },
  {
    "code": "def get_examples(examples_dir=\"examples/\"):\n    all_files = os.listdir(examples_dir)\n    python_files = [f for f in all_files if is_python_file(f)]\n    basenames = [remove_suffix(f) for f in python_files]\n    modules = [import_module(module) for module in pathify(basenames)]\n    return [\n        module for module in modules\n        if getattr(module, 'app', None) is not None\n    ]",
    "docstring": "All example modules"
  },
  {
    "code": "def gdbgui():\n    interpreter = \"lldb\" if app.config[\"LLDB\"] else \"gdb\"\n    gdbpid = request.args.get(\"gdbpid\", 0)\n    initial_gdb_user_command = request.args.get(\"initial_gdb_user_command\", \"\")\n    add_csrf_token_to_session()\n    THEMES = [\"monokai\", \"light\"]\n    initial_data = {\n        \"csrf_token\": session[\"csrf_token\"],\n        \"gdbgui_version\": __version__,\n        \"gdbpid\": gdbpid,\n        \"initial_gdb_user_command\": initial_gdb_user_command,\n        \"interpreter\": interpreter,\n        \"initial_binary_and_args\": app.config[\"initial_binary_and_args\"],\n        \"p\": pbkdf2_hex(str(app.config.get(\"l\")), \"Feo8CJol\")\n        if app.config.get(\"l\")\n        else \"\",\n        \"project_home\": app.config[\"project_home\"],\n        \"remap_sources\": app.config[\"remap_sources\"],\n        \"rr\": app.config[\"rr\"],\n        \"show_gdbgui_upgrades\": app.config[\"show_gdbgui_upgrades\"],\n        \"themes\": THEMES,\n        \"signals\": SIGNAL_NAME_TO_OBJ,\n        \"using_windows\": USING_WINDOWS,\n    }\n    return render_template(\n        \"gdbgui.html\",\n        version=__version__,\n        debug=app.debug,\n        interpreter=interpreter,\n        initial_data=initial_data,\n        themes=THEMES,\n    )",
    "docstring": "Render the main gdbgui interface"
  },
  {
    "code": "def anchored_pairs(self, anchor):\n        pairs = OrderedDict()\n        for term in self.keys:\n            score = self.get_pair(anchor, term)\n            if score: pairs[term] = score\n        return utils.sort_dict(pairs)",
    "docstring": "Get distances between an anchor term and all other terms.\n\n        Args:\n            anchor (str): The anchor term.\n\n        Returns:\n            OrderedDict: The distances, in descending order."
  },
  {
    "code": "def zscore(self, key, member):\n        fut = self.execute(b'ZSCORE', key, member)\n        return wait_convert(fut, optional_int_or_float)",
    "docstring": "Get the score associated with the given member in a sorted set."
  },
  {
    "code": "def output(self, result):\n        if self.returns:\n            errors = None\n            try:\n                return self._adapt_result(result)\n            except AdaptErrors as e:\n                errors = e.errors\n            except AdaptError as e:\n                errors = [e]\n            raise AnticipateErrors(\n                message='Return value %r does not match anticipated type %r'\n                    % (type(result), self.returns),\n                errors=errors)\n        elif self.strict:\n            if result is not None:\n                raise AnticipateErrors(\n                    message='Return value %r does not match anticipated value '\n                    'of None' % type(result),\n                    errors=None)\n            return None\n        else:\n            return result",
    "docstring": "Adapts the result of a function based on the returns definition."
  },
  {
    "code": "def stop_patching(name=None):\n    global _patchers, _mocks\n    if not _patchers:\n        warnings.warn('stop_patching() called again, already stopped')\n    if name is not None:\n        items = [(name, _patchers[name])]\n    else:\n        items = list(_patchers.items())\n    for name, patcher in items:\n        patcher.stop()\n        del _patchers[name]\n        del _mocks[name]",
    "docstring": "Finish the mocking initiated by `start_patching`\n\n    Kwargs:\n        name (Optional[str]): if given, only unpatch the specified path, else all\n            defined default mocks"
  },
  {
    "code": "def lists_submissions(self, date, course_id, grader_id, assignment_id):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"course_id\"] = course_id\r\n        path[\"date\"] = date\r\n        path[\"grader_id\"] = grader_id\r\n        path[\"assignment_id\"] = assignment_id\r\n        self.logger.debug(\"GET /api/v1/courses/{course_id}/gradebook_history/{date}/graders/{grader_id}/assignments/{assignment_id}/submissions with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"GET\", \"/api/v1/courses/{course_id}/gradebook_history/{date}/graders/{grader_id}/assignments/{assignment_id}/submissions\".format(**path), data=data, params=params, all_pages=True)",
    "docstring": "Lists submissions.\r\n\r\n        Gives a nested list of submission versions"
  },
  {
    "code": "def poisson(lam=1, shape=_Null, dtype=_Null, **kwargs):\n    return _random_helper(_internal._random_poisson, _internal._sample_poisson,\n                          [lam], shape, dtype, kwargs)",
    "docstring": "Draw random samples from a Poisson distribution.\n\n    Samples are distributed according to a Poisson distribution parametrized\n    by *lambda* (rate). Samples will always be returned as a floating point data type.\n\n    Parameters\n    ----------\n    lam : float or Symbol, optional\n        Expectation of interval, should be >= 0.\n    shape : int or tuple of ints, optional\n        The number of samples to draw. If shape is, e.g., `(m, n)` and `lam` is\n        a scalar, output shape will be `(m, n)`. If `lam`\n        is an Symbol with shape, e.g., `(x, y)`, then output will have shape\n        `(x, y, m, n)`, where `m*n` samples are drawn for each entry in `lam`.\n    dtype : {'float16', 'float32', 'float64'}, optional\n        Data type of output samples. Default is 'float32'\n\n    Returns\n    -------\n    Symbol\n        If input `shape` has dimensions, e.g., `(m, n)`, and `lam` is\n        a scalar, output shape will be `(m, n)`. If `lam`\n        is an Symbol with shape, e.g., `(x, y)`, then output will have shape\n        `(x, y, m, n)`, where `m*n` samples are drawn for each entry in `lam`."
  },
  {
    "code": "def _propagate_options(self, change):\n        \"Set the values and labels, and select the first option if we aren't initializing\"\n        options = self._options_full\n        self.set_trait('_options_labels', tuple(i[0] for i in options))\n        self._options_values = tuple(i[1] for i in options)\n        if self._initializing_traits_ is not True:\n            if len(options) > 0:\n                if self.index == 0:\n                    self._notify_trait('index', 0, 0)\n                else:\n                    self.index = 0\n            else:\n                self.index = None",
    "docstring": "Set the values and labels, and select the first option if we aren't initializing"
  },
  {
    "code": "def list_append(self, key, value, create=False, **kwargs):\n        op = SD.array_append('', value)\n        sdres = self.mutate_in(key, op, **kwargs)\n        return self._wrap_dsop(sdres)",
    "docstring": "Add an item to the end of a list.\n\n        :param str key: The document ID of the list\n        :param value: The value to append\n        :param create: Whether the list should be created if it does not\n               exist. Note that this option only works on servers >= 4.6\n        :param kwargs: Additional arguments to :meth:`mutate_in`\n        :return: :class:`~.OperationResult`.\n        :raise: :cb_exc:`NotFoundError` if the document does not exist.\n            and `create` was not specified.\n\n        example::\n\n            cb.list_append('a_list', 'hello')\n            cb.list_append('a_list', 'world')\n\n        .. seealso:: :meth:`map_add`"
  },
  {
    "code": "def buildCliString(self):\r\n        config = self.navbar.getActiveConfig()\r\n        group = self.buildSpec['widgets'][self.navbar.getSelectedGroup()]\r\n        positional = config.getPositionalArgs()\r\n        optional = config.getOptionalArgs()\r\n        print(cli.buildCliString(\r\n            self.buildSpec['target'],\r\n            group['command'],\r\n            positional,\r\n            optional\r\n        ))\r\n        return cli.buildCliString(\r\n            self.buildSpec['target'],\r\n            group['command'],\r\n            positional,\r\n            optional\r\n        )",
    "docstring": "Collect all of the required information from the config screen and\r\n        build a CLI string which can be used to invoke the client program"
  },
  {
    "code": "def set_template(path, template, context, defaults, saltenv='base', **kwargs):\n    path = __salt__['cp.get_template'](\n        path=path,\n        dest=None,\n        template=template,\n        saltenv=saltenv,\n        context=context,\n        defaults=defaults,\n        **kwargs)\n    return set_file(path, saltenv, **kwargs)",
    "docstring": "Set answers to debconf questions from a template.\n\n    path\n        location of the file containing the package selections\n\n    template\n        template format\n\n    context\n        variables to add to the template environment\n\n    default\n        default values for the template environment\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' debconf.set_template salt://pathto/pkg.selections.jinja jinja None None"
  },
  {
    "code": "def Validate(self, type_names):\n    errs = [n for n in self._RDFTypes(type_names) if not self._GetClass(n)]\n    if errs:\n      raise DefinitionError(\"Undefined RDF Types: %s\" % \",\".join(errs))",
    "docstring": "Filtered types need to be RDFValues."
  },
  {
    "code": "def get_view_url(self, view_name, user,\n                     url_kwargs=None, context_kwargs=None,\n                     follow_parent=True, check_permissions=True):\n        view, url_name = self.get_initialized_view_and_name(view_name,\n                                            follow_parent=follow_parent)\n        if isinstance(view, URLAlias):\n            view_name = view.get_view_name(view_name)\n            bundle = view.get_bundle(self, url_kwargs, context_kwargs)\n            if bundle and isinstance(bundle, Bundle):\n                return bundle.get_view_url(view_name, user,\n                                           url_kwargs=url_kwargs,\n                                           context_kwargs=context_kwargs,\n                                           follow_parent=follow_parent,\n                                           check_permissions=check_permissions)\n        elif view:\n            if not url_kwargs:\n                url_kwargs = {}\n            url_kwargs = view.get_url_kwargs(context_kwargs, **url_kwargs)\n            view.kwargs = url_kwargs\n            if check_permissions and not view.can_view(user):\n                return None\n            url = reverse(\"admin:%s\" % url_name, kwargs=url_kwargs)\n            return url",
    "docstring": "Returns the url for a given view_name. If the view isn't\n        found or the user does not have permission None is returned.\n        A NoReverseMatch error may be raised if the view was unable\n        to find the correct keyword arguments for the reverse function\n        from the given url_kwargs and context_kwargs.\n\n        :param view_name: The name of the view that you want.\n        :param user: The user who is requesting the view\n        :param url_kwargs: The url keyword arguments that came \\\n        with the request object. The view itself is responsible \\\n        to remove arguments that would not be part of a normal match \\\n        for that view. This is done by calling  the `get_url_kwargs` \\\n        method on the view.\n        :param context_kwargs: Extra arguments that will be passed \\\n        to the view for consideration in the final keyword arguments \\\n        for reverse.\n        :param follow_parent: If we encounter a parent reference should \\\n        we follow it. Defaults to True.\n        :param check_permisions: Run permissions checks. Defaults to True."
  },
  {
    "code": "def construct_formatdb_cmd(filename, outdir, blastdb_exe=pyani_config.FORMATDB_DEFAULT):\n    title = os.path.splitext(os.path.split(filename)[-1])[0]\n    newfilename = os.path.join(outdir, os.path.split(filename)[-1])\n    shutil.copy(filename, newfilename)\n    return (\n        \"{0} -p F -i {1} -t {2}\".format(blastdb_exe, newfilename, title),\n        newfilename,\n    )",
    "docstring": "Returns a single formatdb command.\n\n    - filename - input filename\n    - blastdb_exe - path to the formatdb executable"
  },
  {
    "code": "def output_deployment_status(awsclient, deployment_id, iterations=100):\n    counter = 0\n    steady_states = ['Succeeded', 'Failed', 'Stopped']\n    client_codedeploy = awsclient.get_client('codedeploy')\n    while counter <= iterations:\n        response = client_codedeploy.get_deployment(deploymentId=deployment_id)\n        status = response['deploymentInfo']['status']\n        if status not in steady_states:\n            log.info('Deployment: %s - State: %s' % (deployment_id, status))\n            time.sleep(10)\n        elif status == 'Failed':\n            log.info(\n                colored.red('Deployment: {} failed: {}'.format(\n                    deployment_id,\n                    json.dumps(response['deploymentInfo']['errorInformation'],\n                               indent=2)\n                ))\n            )\n            return 1\n        else:\n            log.info('Deployment: %s - State: %s' % (deployment_id, status))\n            break\n    return 0",
    "docstring": "Wait until an deployment is in an steady state and output information.\n\n    :param deployment_id:\n    :param iterations:\n    :return: exit_code"
  },
  {
    "code": "def compile(self, **kwargs):\n        code = compile(str(self), \"<string>\", \"exec\")\n        global_dict = dict(self._deps)\n        global_dict.update(kwargs)\n        _compat.exec_(code, global_dict)\n        return global_dict",
    "docstring": "Execute the python code and returns the global dict.\n        kwargs can contain extra dependencies that get only used\n        at compile time."
  },
  {
    "code": "def add_gripper(self, arm_name, gripper):\n        if arm_name in self.grippers:\n            raise ValueError(\"Attempts to add multiple grippers to one body\")\n        arm_subtree = self.worldbody.find(\".//body[@name='{}']\".format(arm_name))\n        for actuator in gripper.actuator:\n            if actuator.get(\"name\") is None:\n                raise XMLError(\"Actuator has no name\")\n            if not actuator.get(\"name\").startswith(\"gripper\"):\n                raise XMLError(\n                    \"Actuator name {} does not have prefix 'gripper'\".format(\n                        actuator.get(\"name\")\n                    )\n                )\n        for body in gripper.worldbody:\n            arm_subtree.append(body)\n        self.merge(gripper, merge_body=False)\n        self.grippers[arm_name] = gripper",
    "docstring": "Mounts gripper to arm.\n\n        Throws error if robot already has a gripper or gripper type is incorrect.\n\n        Args:\n            arm_name (str): name of arm mount\n            gripper (MujocoGripper instance): gripper MJCF model"
  },
  {
    "code": "def run_parser_plugins(self, url_data, pagetype):\n        run_plugins(self.parser_plugins, url_data, stop_after_match=True, pagetype=pagetype)",
    "docstring": "Run parser plugins for given pagetype."
  },
  {
    "code": "def executemany(self, sql, *params):\n        fut = self._run_operation(self._impl.executemany, sql, *params)\n        return fut",
    "docstring": "Prepare a database query or command and then execute it against\n        all parameter sequences  found in the sequence seq_of_params.\n\n        :param sql: the SQL statement to execute with optional ? parameters\n        :param params: sequence parameters for the markers in the SQL."
  },
  {
    "code": "def pack_and_batch(dataset, batch_size, length, pack=True):\n  if pack:\n    dataset = pack_dataset(dataset, length=length)\n  dataset = dataset.map(\n      functools.partial(trim_and_pad_all_features, length=length),\n      num_parallel_calls=tf.data.experimental.AUTOTUNE\n  )\n  dataset = dataset.batch(batch_size, drop_remainder=False)\n  dataset = dataset.map(\n      functools.partial(trim_and_pad_all_features, length=batch_size),\n      num_parallel_calls=tf.data.experimental.AUTOTUNE\n  )\n  dataset = dataset.map(\n      lambda x: {k: tf.reshape(v, (batch_size, length)) for k, v in x.items()},\n      num_parallel_calls=tf.data.experimental.AUTOTUNE\n  )\n  dataset = dataset.prefetch(100)\n  return dataset",
    "docstring": "Create a tf.data.Dataset which emits training batches.\n\n  The input dataset emits feature-dictionaries where each feature is a vector\n  of integers ending in EOS=1\n\n  The tensors in the returned tf.data.Dataset have shape\n  [batch_size, length].  Zeros indicate padding.\n\n  length indicates the length of the emitted examples.  Examples with\n  inputs/targets longer than length get truncated.\n\n  TODO(noam): for text2self problems, we should just chop too-long\n  sequences into multiple parts and train on all of them.\n\n  If pack=False, then each emitted example will contain one\n  example emitted by load_internal().\n\n  If pack=True, then multiple examples emitted by load_internal() are\n  concatenated to form one combined example with the given length.\n  See comments in the function pack_dataset().\n\n  batch_size indicates the number of (combined) examples per batch,\n  across all cores.\n\n  Args:\n    dataset: a tf.data.Dataset\n    batch_size: an integer\n    length: an integer\n    pack: a boolean\n  Returns:\n    a tf.data.Dataset where all features have fixed shape [batch, length]."
  },
  {
    "code": "def flo(string):\n    callers_locals = {}\n    frame = inspect.currentframe()\n    try:\n        outerframe = frame.f_back\n        callers_locals = outerframe.f_locals\n    finally:\n        del frame\n    return string.format(**callers_locals)",
    "docstring": "Return the string given by param formatted with the callers locals."
  },
  {
    "code": "def as_set(self, decode=False):\n        items = self.database.smembers(self.key)\n        return set(_decode(item) for item in items) if decode else items",
    "docstring": "Return a Python set containing all the items in the collection."
  },
  {
    "code": "def SvcStop(self) -> None:\n        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n        win32event.SetEvent(self.h_stop_event)",
    "docstring": "Called when the service is being shut down."
  },
  {
    "code": "def cub200_iterator(data_path, batch_k, batch_size, data_shape):\n    return (CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=True),\n            CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=False))",
    "docstring": "Return training and testing iterator for the CUB200-2011 dataset."
  },
  {
    "code": "def save(self):\n        d = dict(self)\n        old_dict = d.copy()\n        _id = self.collection.save(d)\n        self._id = _id\n        self.on_save(old_dict)\n        return self._id",
    "docstring": "Save model object to database."
  },
  {
    "code": "def assert_numbers_almost_equal(self, actual_val, expected_val, allowed_delta=0.0001,\n                                    failure_message='Expected numbers to be within {} of each other: \"{}\" and \"{}\"'):\n        assertion = lambda: abs(expected_val - actual_val) <= allowed_delta\n        self.webdriver_assert(assertion, unicode(failure_message).format(allowed_delta, actual_val, expected_val))",
    "docstring": "Asserts that two numbers are within an allowed delta of each other"
  },
  {
    "code": "def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True):\n    if regex:\n        if not case:\n            flags |= re.IGNORECASE\n        regex = re.compile(pat, flags=flags)\n        if regex.groups > 0:\n            warnings.warn(\"This pattern has match groups. To actually get the\"\n                          \" groups, use str.extract.\", UserWarning,\n                          stacklevel=3)\n        f = lambda x: bool(regex.search(x))\n    else:\n        if case:\n            f = lambda x: pat in x\n        else:\n            upper_pat = pat.upper()\n            f = lambda x: upper_pat in x\n            uppered = _na_map(lambda x: x.upper(), arr)\n            return _na_map(f, uppered, na, dtype=bool)\n    return _na_map(f, arr, na, dtype=bool)",
    "docstring": "Test if pattern or regex is contained within a string of a Series or Index.\n\n    Return boolean Series or Index based on whether a given pattern or regex is\n    contained within a string of a Series or Index.\n\n    Parameters\n    ----------\n    pat : str\n        Character sequence or regular expression.\n    case : bool, default True\n        If True, case sensitive.\n    flags : int, default 0 (no flags)\n        Flags to pass through to the re module, e.g. re.IGNORECASE.\n    na : default NaN\n        Fill value for missing values.\n    regex : bool, default True\n        If True, assumes the pat is a regular expression.\n\n        If False, treats the pat as a literal string.\n\n    Returns\n    -------\n    Series or Index of boolean values\n        A Series or Index of boolean values indicating whether the\n        given pattern is contained within the string of each element\n        of the Series or Index.\n\n    See Also\n    --------\n    match : Analogous, but stricter, relying on re.match instead of re.search.\n    Series.str.startswith : Test if the start of each string element matches a\n        pattern.\n    Series.str.endswith : Same as startswith, but tests the end of string.\n\n    Examples\n    --------\n\n    Returning a Series of booleans using only a literal pattern.\n\n    >>> s1 = pd.Series(['Mouse', 'dog', 'house and parrot', '23', np.NaN])\n    >>> s1.str.contains('og', regex=False)\n    0    False\n    1     True\n    2    False\n    3    False\n    4      NaN\n    dtype: object\n\n    Returning an Index of booleans using only a literal pattern.\n\n    >>> ind = pd.Index(['Mouse', 'dog', 'house and parrot', '23.0', np.NaN])\n    >>> ind.str.contains('23', regex=False)\n    Index([False, False, False, True, nan], dtype='object')\n\n    Specifying case sensitivity using `case`.\n\n    >>> s1.str.contains('oG', case=True, regex=True)\n    0    False\n    1    False\n    2    False\n    3    False\n    4      NaN\n    dtype: object\n\n    Specifying `na` to be `False` instead of `NaN` replaces NaN values\n    with `False`. If Series or Index does not contain NaN values\n    the resultant dtype will be `bool`, otherwise, an `object` dtype.\n\n    >>> s1.str.contains('og', na=False, regex=True)\n    0    False\n    1     True\n    2    False\n    3    False\n    4    False\n    dtype: bool\n\n    Returning 'house' or 'dog' when either expression occurs in a string.\n\n    >>> s1.str.contains('house|dog', regex=True)\n    0    False\n    1     True\n    2     True\n    3    False\n    4      NaN\n    dtype: object\n\n    Ignoring case sensitivity using `flags` with regex.\n\n    >>> import re\n    >>> s1.str.contains('PARROT', flags=re.IGNORECASE, regex=True)\n    0    False\n    1    False\n    2     True\n    3    False\n    4      NaN\n    dtype: object\n\n    Returning any digit using regular expression.\n\n    >>> s1.str.contains('\\\\d', regex=True)\n    0    False\n    1    False\n    2    False\n    3     True\n    4      NaN\n    dtype: object\n\n    Ensure `pat` is a not a literal pattern when `regex` is set to True.\n    Note in the following example one might expect only `s2[1]` and `s2[3]` to\n    return `True`. However, '.0' as a regex matches any character\n    followed by a 0.\n\n    >>> s2 = pd.Series(['40', '40.0', '41', '41.0', '35'])\n    >>> s2.str.contains('.0', regex=True)\n    0     True\n    1     True\n    2    False\n    3     True\n    4    False\n    dtype: bool"
  },
  {
    "code": "def disconnect_async(self, conn_id, callback):\n        future = self._loop.launch_coroutine(self._adapter.disconnect(conn_id))\n        future.add_done_callback(lambda x: self._callback_future(conn_id, x, callback))",
    "docstring": "Asynchronously disconnect from a device."
  },
  {
    "code": "def digest_chunks(chunks, algorithms=(hashlib.md5, hashlib.sha1)):\n    hashes = [algorithm() for algorithm in algorithms]\n    for chunk in chunks:\n        for h in hashes:\n            h.update(chunk)\n    return [_b64encode_to_str(h.digest()) for h in hashes]",
    "docstring": "returns a base64 rep of the given digest algorithms from the\n    chunks of data"
  },
  {
    "code": "def getCompleteFile(self, basepath):\n        dirname = getDirname(self.getName())\n        return os.path.join(basepath, dirname, \"complete.txt\")",
    "docstring": "Get filename indicating all comics are downloaded."
  },
  {
    "code": "def update_url(url, params):\n    if not isinstance(url, bytes):\n        url = url.encode('utf-8')\n    for key, value in list(params.items()):\n        if not isinstance(key, bytes):\n            del params[key]\n            key = key.encode('utf-8')\n        if not isinstance(value, bytes):\n            value = value.encode('utf-8')\n        params[key] = value\n    url_parts = list(urlparse(url))\n    query = dict(parse_qsl(url_parts[4]))\n    query.update(params)\n    query = list(query.items())\n    query.sort()\n    url_query = urlencode(query)\n    if not isinstance(url_query, bytes):\n        url_query = url_query.encode(\"utf-8\")\n    url_parts[4] = url_query\n    return urlunparse(url_parts).decode('utf-8')",
    "docstring": "update parameters using ``params`` in the ``url`` query string\n\n        :param url: An URL possibily with a querystring\n        :type url: :obj:`unicode` or :obj:`str`\n        :param dict params: A dictionary of parameters for updating the url querystring\n        :return: The URL with an updated querystring\n        :rtype: unicode"
  },
  {
    "code": "def set_names(self, names, level=None, inplace=False):\n        if level is not None and not isinstance(self, ABCMultiIndex):\n            raise ValueError('Level must be None for non-MultiIndex')\n        if level is not None and not is_list_like(level) and is_list_like(\n                names):\n            msg = \"Names must be a string when a single level is provided.\"\n            raise TypeError(msg)\n        if not is_list_like(names) and level is None and self.nlevels > 1:\n            raise TypeError(\"Must pass list-like as `names`.\")\n        if not is_list_like(names):\n            names = [names]\n        if level is not None and not is_list_like(level):\n            level = [level]\n        if inplace:\n            idx = self\n        else:\n            idx = self._shallow_copy()\n        idx._set_names(names, level=level)\n        if not inplace:\n            return idx",
    "docstring": "Set Index or MultiIndex name.\n\n        Able to set new names partially and by level.\n\n        Parameters\n        ----------\n        names : label or list of label\n            Name(s) to set.\n        level : int, label or list of int or label, optional\n            If the index is a MultiIndex, level(s) to set (None for all\n            levels). Otherwise level must be None.\n        inplace : bool, default False\n            Modifies the object directly, instead of creating a new Index or\n            MultiIndex.\n\n        Returns\n        -------\n        Index\n            The same type as the caller or None if inplace is True.\n\n        See Also\n        --------\n        Index.rename : Able to set new names without level.\n\n        Examples\n        --------\n        >>> idx = pd.Index([1, 2, 3, 4])\n        >>> idx\n        Int64Index([1, 2, 3, 4], dtype='int64')\n        >>> idx.set_names('quarter')\n        Int64Index([1, 2, 3, 4], dtype='int64', name='quarter')\n\n        >>> idx = pd.MultiIndex.from_product([['python', 'cobra'],\n        ...                                   [2018, 2019]])\n        >>> idx\n        MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n                   codes=[[1, 1, 0, 0], [0, 1, 0, 1]])\n        >>> idx.set_names(['kind', 'year'], inplace=True)\n        >>> idx\n        MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n                   codes=[[1, 1, 0, 0], [0, 1, 0, 1]],\n                   names=['kind', 'year'])\n        >>> idx.set_names('species', level=0)\n        MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n                   codes=[[1, 1, 0, 0], [0, 1, 0, 1]],\n                   names=['species', 'year'])"
  },
  {
    "code": "def guests_get_nic_info(self, userid=None, nic_id=None, vswitch=None):\n        action = \"get nic information\"\n        with zvmutils.log_and_reraise_sdkbase_error(action):\n            return self._networkops.get_nic_info(userid=userid, nic_id=nic_id,\n                                                 vswitch=vswitch)",
    "docstring": "Retrieve nic information in the network database according to\n            the requirements, the nic information will include the guest\n            name, nic device number, vswitch name that the nic is coupled\n            to, nic identifier and the comments.\n\n        :param str userid: the user id of the vm\n        :param str nic_id: nic identifier\n        :param str vswitch: the name of the vswitch\n\n        :returns: list describing nic information, format is\n                  [\n                  (userid, interface, vswitch, nic_id, comments),\n                  (userid, interface, vswitch, nic_id, comments)\n                  ], such as\n                  [\n                  ('VM01', '1000', 'xcatvsw2', '1111-2222', None),\n                  ('VM02', '2000', 'xcatvsw3', None, None)\n                  ]\n        :rtype: list"
  },
  {
    "code": "def info_string(self, size=None, message='', frame=-1):\n        info = []\n        if size is not None:\n            info.append('Size: {1}x{0}'.format(*size))\n        elif self.size is not None:\n            info.append('Size: {1}x{0}'.format(*self.size))\n        if frame >= 0:\n            info.append('Frame: {}'.format(frame))\n        if message != '':\n            info.append('{}'.format(message))\n        return ' '.join(info)",
    "docstring": "Returns information about the stream.\n\n        Generates a string containing size, frame number, and info messages.\n        Omits unnecessary information (e.g. empty messages and frame -1).\n\n        This method is primarily used to update the suptitle of the plot\n        figure.\n\n        Returns:\n            An info string."
  },
  {
    "code": "def _factory(importname, base_class_type, path=None, *args, **kargs):\n    def is_base_class(item):\n        return isclass(item) and item.__module__ == importname\n    if path:\n        sys.path.append(path)\n        absolute_path = os.path.join(path, importname) + '.py'\n        module = imp.load_source(importname, absolute_path)\n    else:\n        module = import_module(importname)\n    clsmembers = getmembers(module, is_base_class)\n    if not len(clsmembers):\n        raise ValueError('Found no matching class in %s.' % importname)\n    else:\n        cls = clsmembers[0][1]\n    return cls(*args, **kargs)",
    "docstring": "Load a module of a given base class type\n\n        Parameter\n        --------\n        importname: string\n            Name of the module, etc. converter\n        base_class_type: class type\n            E.g converter\n        path: Absoulte path of the module\n            Neede for extensions. If not given module is in online_monitor\n            package\n        *args, **kargs:\n            Arguments to pass to the object init\n\n        Return\n        ------\n        Object of given base class type"
  },
  {
    "code": "def _clone(self):\n        instance = super(Bungiesearch, self)._clone()\n        instance._raw_results_only = self._raw_results_only\n        return instance",
    "docstring": "Must clone additional fields to those cloned by elasticsearch-dsl-py."
  },
  {
    "code": "def _update_label(self, label, array):\n        maximum = float(numpy.max(array))\n        mean = float(numpy.mean(array))\n        median = float(numpy.median(array))\n        minimum = float(numpy.min(array))\n        stdev = float(numpy.std(array, ddof=1))\n        encoder = pvl.encoder.PDSLabelEncoder\n        serial_label = pvl.dumps(label, cls=encoder)\n        label_sz = len(serial_label)\n        image_pointer = int(label_sz / label['RECORD_BYTES']) + 1\n        label['^IMAGE'] = image_pointer + 1\n        label['LABEL_RECORDS'] = image_pointer\n        label['IMAGE']['MEAN'] = mean\n        label['IMAGE']['MAXIMUM'] = maximum\n        label['IMAGE']['MEDIAN'] = median\n        label['IMAGE']['MINIMUM'] = minimum\n        label['IMAGE']['STANDARD_DEVIATION'] = stdev\n        return label",
    "docstring": "Update PDS3 label for NumPy Array.\n        It is called by '_create_label' to update label values\n        such as,\n        - ^IMAGE, RECORD_BYTES\n        - STANDARD_DEVIATION\n        - MAXIMUM, MINIMUM\n        - MEDIAN, MEAN\n\n        Returns\n        -------\n        Update label module for the NumPy array.\n\n        Usage: self.label = self._update_label(label, array)"
  },
  {
    "code": "def gen_opt_str(ser_rec: pd.Series)->str:\n    name = ser_rec.name\n    indent = r'    '\n    str_opt = f'.. option:: {name}'+'\\n\\n'\n    for spec in ser_rec.sort_index().index:\n        str_opt += indent+f':{spec}:'+'\\n'\n        spec_content = ser_rec[spec]\n        str_opt += indent+indent+f'{spec_content}'+'\\n'\n    return str_opt",
    "docstring": "generate rst option string\n\n    Parameters\n    ----------\n    ser_rec : pd.Series\n        record for specifications\n\n    Returns\n    -------\n    str\n        rst string"
  },
  {
    "code": "def get(self, name, default=_MISSING):\n        name = self._convert_name(name)\n        if name not in self._fields:\n            if default is _MISSING:\n                default = self._default_value(name)\n            return default\n        if name in _UNICODEFIELDS:\n            value = self._fields[name]\n            return value\n        elif name in _LISTFIELDS:\n            value = self._fields[name]\n            if value is None:\n                return []\n            res = []\n            for val in value:\n                if name not in _LISTTUPLEFIELDS:\n                    res.append(val)\n                else:\n                    res.append((val[0], val[1]))\n            return res\n        elif name in _ELEMENTSFIELD:\n            value = self._fields[name]\n            if isinstance(value, string_types):\n                return value.split(',')\n        return self._fields[name]",
    "docstring": "Get a metadata field."
  },
  {
    "code": "def detect_port(port):\n    socket_test = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n    try:\n        socket_test.connect(('127.0.0.1', int(port)))\n        socket_test.close()\n        return True\n    except:\n        return False",
    "docstring": "Detect if the port is used"
  },
  {
    "code": "def contribute_to_class(self, cls, name, virtual_only=False):\n        super(RegexField, self).contribute_to_class(cls, name, virtual_only)\n        setattr(cls, name, CastOnAssignDescriptor(self))",
    "docstring": "Cast to the correct value every"
  },
  {
    "code": "def get_data(self):\n        url = self.build_url()\n        self.locationApiData = requests.get(url)\n        if not self.locationApiData.status_code == 200:\n            raise self.locationApiData.raise_for_status()",
    "docstring": "Gets data from the built url"
  },
  {
    "code": "def migrateProvPre010(self, newslab):\n        did_migrate = self._migrate_db_pre010('prov', newslab)\n        if not did_migrate:\n            return\n        self._migrate_db_pre010('provs', newslab)",
    "docstring": "Check for any pre-010 provstacks and migrate those to the new slab."
  },
  {
    "code": "def parse(source, remove_comments=True, **kw):\n    return ElementTree.parse(source, SourceLineParser(), **kw)",
    "docstring": "Thin wrapper around ElementTree.parse"
  },
  {
    "code": "def _set_cell_attr(self, selection, table, attr):\n        post_command_event(self.main_window, self.ContentChangedMsg)\n        if selection is not None:\n            self.code_array.cell_attributes.append((selection, table, attr))",
    "docstring": "Sets cell attr for key cell and mark grid content as changed\n\n        Parameters\n        ----------\n\n        attr: dict\n        \\tContains cell attribute keys\n        \\tkeys in [\"borderwidth_bottom\", \"borderwidth_right\",\n        \\t\"bordercolor_bottom\", \"bordercolor_right\",\n        \\t\"bgcolor\", \"textfont\",\n        \\t\"pointsize\", \"fontweight\", \"fontstyle\", \"textcolor\", \"underline\",\n        \\t\"strikethrough\", \"angle\", \"column-width\", \"row-height\",\n        \\t\"vertical_align\", \"justification\", \"frozen\", \"merge_area\"]"
  },
  {
    "code": "def memmap_array(self, dtype, shape, offset=0, mode='r', order='C'):\n        if not self.is_file:\n            raise ValueError('Cannot memory-map file without fileno')\n        return numpy.memmap(self._fh, dtype=dtype, mode=mode,\n                            offset=self._offset + offset,\n                            shape=shape, order=order)",
    "docstring": "Return numpy.memmap of data stored in file."
  },
  {
    "code": "def _piecewise_learning_rate(step, boundaries, values):\n  values = [1.0] + values\n  boundaries = [float(x) for x in boundaries]\n  return tf.train.piecewise_constant(\n      step, boundaries, values, name=\"piecewise_lr\")",
    "docstring": "Scale learning rate according to the given schedule.\n\n  Multipliers are not cumulative.\n\n  Args:\n    step: global step\n    boundaries: List of steps to transition on.\n    values: Multiplier to apply at each boundary transition.\n\n  Returns:\n    Scaled value for the learning rate."
  },
  {
    "code": "def parse_pgurl(self, url):\n        parsed = urlsplit(url)\n        return {\n            'user': parsed.username,\n            'password': parsed.password,\n            'database': parsed.path.lstrip('/'),\n            'host': parsed.hostname,\n            'port': parsed.port or 5432,\n        }",
    "docstring": "Given a Postgres url, return a dict with keys for user, password,\n        host, port, and database."
  },
  {
    "code": "def S_isothermal_pipe_eccentric_to_isothermal_pipe(D1, D2, Z, L=1.):\n    r\n    return 2.*pi*L/acosh((D2**2 + D1**2 - 4.*Z**2)/(2.*D1*D2))",
    "docstring": "r'''Returns the Shape factor `S` of a pipe of constant outer temperature\n    and of outer diameter `D1` which is `Z` distance from the center of another\n    pipe of outer diameter`D2`. Length `L` must be provided, but can be set to\n    1 to obtain a dimensionless shape factor used in some sources.\n\n    .. math::\n        S = \\frac{2\\pi L}{\\cosh^{-1}\n        \\left(\\frac{D_2^2 + D_1^2 - 4Z^2}{2D_1D_2}\\right)}\n\n    Parameters\n    ----------\n    D1 : float\n        Diameter of inner pipe, [m]\n    D2 : float\n        Diameter of outer pipe, [m]\n    Z : float\n        Distance from the middle of inner pipe to the center of the other, [m]\n    L : float, optional\n        Length of the pipe, [m]\n\n    Returns\n    -------\n    S : float\n        Shape factor [m]\n\n    Examples\n    --------\n    >>> S_isothermal_pipe_eccentric_to_isothermal_pipe(.1, .4, .05, 10)\n    47.709841915608976\n\n    Notes\n    -----\n    L should be much larger than both diameters. D2 should be larger than D1.\n\n    .. math::\n        Q = Sk(T_1 - T_2) \\\\ R_{\\text{shape}}=\\frac{1}{Sk}\n\n    References\n    ----------\n    .. [1] Kreith, Frank, Raj Manglik, and Mark Bohn. Principles of Heat\n       Transfer. Cengage, 2010.\n    .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n       David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n       Wiley, 2011."
  },
  {
    "code": "def parse(cls, s, **kwargs):\n        pb2_obj = cls._get_cmsg()\n        pb2_obj.ParseFromString(s)\n        return cls.parse_from_cmessage(pb2_obj, **kwargs)",
    "docstring": "Parse a bytes object and create a class object.\n\n        :param bytes s: A bytes object.\n        :return:        A class object.\n        :rtype:         cls"
  },
  {
    "code": "def mac_address(ip):\n    mac = ''\n    for line in os.popen('/sbin/ifconfig'):\n        s = line.split()\n        if len(s) > 3:\n            if s[3] == 'HWaddr':\n                mac = s[4]\n            elif s[2] == ip:\n                break\n    return {'MAC': mac}",
    "docstring": "Get the MAC address"
  },
  {
    "code": "def usage(text):\n    def decorator(func):\n        adaptor = ScriptAdaptor._get_adaptor(func)\n        adaptor.usage = text\n        return func\n    return decorator",
    "docstring": "Decorator used to specify a usage string for the console script\n    help message.\n\n    :param text: The text to use for the usage."
  },
  {
    "code": "def project_drawn(cb, msg):\n    stream = cb.streams[0]\n    old_data = stream.data\n    stream.update(data=msg['data'])\n    element = stream.element\n    stream.update(data=old_data)\n    proj = cb.plot.projection\n    if not isinstance(element, _Element) or element.crs == proj:\n        return None\n    crs = element.crs\n    element.crs = proj\n    return project(element, projection=crs)",
    "docstring": "Projects a drawn element to the declared coordinate system"
  },
  {
    "code": "def start_external_service(self, service_name, conf=None):\n        if service_name in self._external_services:\n            ser = self._external_services[service_name]\n            service = ser(service_name, conf=conf, bench=self.bench)\n            try:\n                service.start()\n            except PluginException:\n                self.logger.exception(\"Starting service %s caused an exception!\", service_name)\n                raise PluginException(\"Failed to start external service {}\".format(service_name))\n            self._started_services.append(service)\n            setattr(self.bench, service_name, service)\n        else:\n            self.logger.warning(\"Service %s not found. Check your plugins.\", service_name)",
    "docstring": "Start external service service_name with configuration conf.\n\n        :param service_name: Name of service to start\n        :param conf:\n        :return: nothing"
  },
  {
    "code": "def remove_channel(self, channel, *, verbose=True):\n        channel_index = wt_kit.get_index(self.channel_names, channel)\n        new = list(self.channel_names)\n        name = new.pop(channel_index)\n        del self[name]\n        self.channel_names = new\n        if verbose:\n            print(\"channel {0} removed\".format(name))",
    "docstring": "Remove channel from data.\n\n        Parameters\n        ----------\n        channel : int or str\n            Channel index or name to remove.\n        verbose : boolean (optional)\n            Toggle talkback. Default is True."
  },
  {
    "code": "def log(self, ctx='all'):\n    path = '%s/%s.log' % (self.path, ctx)\n    if os.path.exists(path) is True:\n      with open(path, 'r') as f:\n        print(f.read())\n      return\n    validate_path = '%s/validate.log' % self.path\n    build_path = '%s/build.log' % self.path\n    out = []\n    with open(validate_path) as validate_log, open(build_path) as build_log:\n      for line in validate_log.readlines():\n        out.append(line)\n      for line in build_log.readlines():\n        out.append(line)\n    print(''.join(out))",
    "docstring": "Gets the build log output.\n\n    :param ctx: specifies which log message to show, it can be 'validate', 'build' or 'all'."
  },
  {
    "code": "def read_config():\n    if not os.path.isfile(CONFIG):\n        with open(CONFIG, \"w\"):\n            pass\n    parser = ConfigParser()\n    parser.read(CONFIG)\n    return parser",
    "docstring": "Read the configuration file and parse the different environments.\n\n        Returns: ConfigParser object"
  },
  {
    "code": "def _parse_optional_params(self, oauth_params, req_kwargs):\n        params = req_kwargs.get('params', {})\n        data = req_kwargs.get('data') or {}\n        for oauth_param in OPTIONAL_OAUTH_PARAMS:\n            if oauth_param in params:\n                oauth_params[oauth_param] = params.pop(oauth_param)\n            if oauth_param in data:\n                oauth_params[oauth_param] = data.pop(oauth_param)\n            if params:\n                req_kwargs['params'] = params\n            if data:\n                req_kwargs['data'] = data",
    "docstring": "Parses and sets optional OAuth parameters on a request.\n\n        :param oauth_param: The OAuth parameter to parse.\n        :type oauth_param: str\n        :param req_kwargs: The keyworded arguments passed to the request\n            method.\n        :type req_kwargs: dict"
  },
  {
    "code": "def include_library(libname):\n    if exclude_list:\n        if exclude_list.search(libname) and not include_list.search(libname):\n            return False\n        else:\n            return True\n    else:\n        return True",
    "docstring": "Check if a dynamic library should be included with application or not."
  },
  {
    "code": "def mod(x, y, context=None):\n    return _apply_function_in_current_context(\n        BigFloat,\n        mpfr_mod,\n        (\n            BigFloat._implicit_convert(x),\n            BigFloat._implicit_convert(y),\n        ),\n        context,\n    )",
    "docstring": "Return the remainder of x divided by y, with sign matching that of y."
  },
  {
    "code": "def runSearchContinuousSets(self, request):\n        return self.runSearchRequest(\n            request, protocol.SearchContinuousSetsRequest,\n            protocol.SearchContinuousSetsResponse,\n            self.continuousSetsGenerator)",
    "docstring": "Returns a SearchContinuousSetsResponse for the specified\n        SearchContinuousSetsRequest object."
  },
  {
    "code": "def add(self, child):\n        if isinstance(child, Run):\n            self.add_run(child)\n        elif isinstance(child, Record):\n            self.add_record(child)\n        elif isinstance(child, EventRecord):\n            self.add_event_record(child)\n        elif isinstance(child, DataDisplay):\n            self.add_data_display(child)\n        elif isinstance(child, DataWriter):\n            self.add_data_writer(child)\n        elif isinstance(child, EventWriter):\n            self.add_event_writer(child)\n        else:\n            raise ModelError('Unsupported child element')",
    "docstring": "Adds a typed child object to the simulation spec.\n\n        @param child: Child object to be added."
  },
  {
    "code": "def between(self, start, end):\n        if hasattr(start, 'strftime') and hasattr(end, 'strftime'):\n            dt_between = (\n              'javascript:gs.dateGenerate(\"%(start)s\")'\n              \"@\"\n              'javascript:gs.dateGenerate(\"%(end)s\")'\n            ) % {\n              'start': start.strftime('%Y-%m-%d %H:%M:%S'),\n              'end': end.strftime('%Y-%m-%d %H:%M:%S')\n            }\n        elif isinstance(start, int) and isinstance(end, int):\n            dt_between = '%d@%d' % (start, end)\n        else:\n            raise QueryTypeError(\"Expected `start` and `end` of type `int` \"\n                                 \"or instance of `datetime`, not %s and %s\" % (type(start), type(end)))\n        return self._add_condition('BETWEEN', dt_between, types=[str])",
    "docstring": "Adds new `BETWEEN` condition\n\n        :param start: int or datetime  compatible object (in SNOW user's timezone)\n        :param end: int or datetime compatible object (in SNOW user's timezone)\n        :raise:\n            - QueryTypeError: if start or end arguments is of an invalid type"
  },
  {
    "code": "def enable_global_typechecked_decorator(flag = True, retrospective = True):\n    global global_typechecked_decorator\n    global_typechecked_decorator = flag\n    if import_hook_enabled:\n        _install_import_hook()\n    if global_typechecked_decorator and retrospective:\n        _catch_up_global_typechecked_decorator()\n    return global_typechecked_decorator",
    "docstring": "Enables or disables global typechecking mode via decorators.\n    See flag global_typechecked_decorator.\n    In contrast to setting the flag directly, this function provides\n    a retrospective option. If retrospective is true, this will also\n    affect already imported modules, not only future imports.\n    Does not work if checking_enabled is false.\n    Does not work reliably if checking_enabled has ever been set to\n    false during current run."
  },
  {
    "code": "def create_query_engine(config, clazz):\n    try:\n        qe = clazz(**config.settings)\n    except Exception as err:\n        raise CreateQueryEngineError(clazz, config.settings, err)\n    return qe",
    "docstring": "Create and return new query engine object from the\n    given `DBConfig` object.\n\n    :param config: Database configuration\n    :type config: dbconfig.DBConfig\n    :param clazz: Class to use for creating query engine. Should\n                  act like query_engine.QueryEngine.\n    :type clazz: class\n    :return: New query engine"
  },
  {
    "code": "def send(self, data):\n        log.debug('Sending %s' % data)\n        if not self._socket:\n            log.warn('No connection')\n            return\n        self._socket.send_bytes(data.encode('utf-8'))",
    "docstring": "Send data through websocket"
  },
  {
    "code": "def parse_command_line() -> Namespace:\n    import tornado.options\n    parser.parse_known_args(namespace=config)\n    set_loglevel()\n    for k, v in vars(config).items():\n        if k.startswith('log'):\n            tornado.options.options.__setattr__(k, v)\n    return config",
    "docstring": "Parse command line options and set them to ``config``.\n\n    This function skips unknown command line options. After parsing options,\n    set log level and set options in ``tornado.options``."
  },
  {
    "code": "def unpack(cls, msg):\n        flags, first_payload_type, first_payload_size = cls.UNPACK_FROM(msg)\n        if flags != 0:\n            raise ProtocolError(\"Unsupported OP_MSG flags (%r)\" % (flags,))\n        if first_payload_type != 0:\n            raise ProtocolError(\n                \"Unsupported OP_MSG payload type (%r)\" % (first_payload_type,))\n        if len(msg) != first_payload_size + 5:\n            raise ProtocolError(\"Unsupported OP_MSG reply: >1 section\")\n        payload_document = bytes(msg[5:])\n        return cls(flags, payload_document)",
    "docstring": "Construct an _OpMsg from raw bytes."
  },
  {
    "code": "def makeSocket(self, timeout=1):\n        plain_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        if hasattr(plain_socket, 'settimeout'):\n            plain_socket.settimeout(timeout)\n        wrapped_socket = ssl.wrap_socket(\n            plain_socket,\n            ca_certs=self.ca_certs,\n            cert_reqs=self.reqs,\n            keyfile=self.keyfile,\n            certfile=self.certfile\n        )\n        wrapped_socket.connect((self.host, self.port))\n        return wrapped_socket",
    "docstring": "Override SocketHandler.makeSocket, to allow creating wrapped\n        TLS sockets"
  },
  {
    "code": "def enable_receiving(self, loop=None):\n        self.receive_task = asyncio.ensure_future(self._receive_loop(), loop=loop)\n        def do_if_done(fut):\n            try:\n                fut.result()\n            except asyncio.CancelledError:\n                pass\n            except Exception as ex:\n                self.receive_task_exception = ex\n            self.receive_task = None\n        self.receive_task.add_done_callback(do_if_done)",
    "docstring": "Schedules the receive loop to run on the given loop."
  },
  {
    "code": "def main(model_folder):\n    model_description_file = os.path.join(model_folder, \"info.yml\")\n    with open(model_description_file, 'r') as ymlfile:\n        model_description = yaml.load(ymlfile)\n    logging.info(model_description['model'])\n    data = {}\n    data['training'] = os.path.join(model_folder, \"traindata.hdf5\")\n    data['testing'] = os.path.join(model_folder, \"testdata.hdf5\")\n    data['validating'] = os.path.join(model_folder, \"validdata.hdf5\")\n    train_model(model_folder)",
    "docstring": "Main part of the training script."
  },
  {
    "code": "def clean_series_name(seriesname):\n    if not seriesname:\n        return seriesname\n    seriesname = re.sub(r'(\\D)[.](\\D)', '\\\\1 \\\\2', seriesname)\n    seriesname = re.sub(r'(\\D)[.]', '\\\\1 ', seriesname)\n    seriesname = re.sub(r'[.](\\D)', ' \\\\1', seriesname)\n    seriesname = seriesname.replace('_', ' ')\n    seriesname = re.sub('-$', '', seriesname)\n    return _replace_series_name(seriesname.strip(),\n                                cfg.CONF.input_series_replacements)",
    "docstring": "Cleans up series name.\n\n    By removing any . and _ characters, along with any trailing hyphens.\n\n    Is basically equivalent to replacing all _ and . with a\n    space, but handles decimal numbers in string, for example:\n\n    >>> _clean_series_name(\"an.example.1.0.test\")\n    'an example 1.0 test'\n    >>> _clean_series_name(\"an_example_1.0_test\")\n    'an example 1.0 test'"
  },
  {
    "code": "def set_options(self, option_type, option_dict, force_options=False):\n        if force_options:\n            self.options[option_type].update(option_dict)\n        elif (option_type == 'yAxis' or option_type == 'xAxis') and isinstance(option_dict, list):\n            self.options[option_type] = MultiAxis(option_type)\n            for each_dict in option_dict:\n                self.options[option_type].update(**each_dict)\n        elif option_type == 'colors':\n            self.options[\"colors\"].set_colors(option_dict)\n        elif option_type in [\"global\" , \"lang\"]:\n            self.setOptions[option_type].update_dict(**option_dict)\n        else:\n            self.options[option_type].update_dict(**option_dict)",
    "docstring": "set plot options"
  },
  {
    "code": "def ffill_across_cols(df, columns, name_map):\n    df.ffill(inplace=True)\n    for column in columns:\n        column_name = name_map[column.name]\n        if column.dtype == categorical_dtype:\n            df[column_name] = df[\n                column.name\n            ].where(pd.notnull(df[column_name]),\n                    column.missing_value)\n        else:\n            df[column_name] = df[\n                column_name\n            ].fillna(column.missing_value).astype(column.dtype)",
    "docstring": "Forward fill values in a DataFrame with special logic to handle cases\n    that pd.DataFrame.ffill cannot and cast columns to appropriate types.\n\n    Parameters\n    ----------\n    df : pd.DataFrame\n        The DataFrame to do forward-filling on.\n    columns : list of BoundColumn\n        The BoundColumns that correspond to columns in the DataFrame to which\n        special filling and/or casting logic should be applied.\n    name_map: map of string -> string\n        Mapping from the name of each BoundColumn to the associated column\n        name in `df`."
  },
  {
    "code": "def get_vip_request(self, vip_request_id):\n        uri = 'api/v3/vip-request/%s/' % vip_request_id\n        return super(ApiVipRequest, self).get(uri)",
    "docstring": "Method to get vip request\n\n        param vip_request_id: vip_request id"
  },
  {
    "code": "def iter(self, pages=None):\n        i = self._pages()\n        if pages is not None:\n            i = itertools.islice(i, pages)\n        return i",
    "docstring": "Get an iterator of pages.\n\n        :param int pages: optional limit to number of pages\n        :return: iter of this and subsequent pages"
  },
  {
    "code": "def get_token():\n    token = os.environ.get(\"GH_TOKEN\", None)\n    if not token:\n        token = \"GH_TOKEN environment variable not set\"\n    token = token.encode('utf-8')\n    return token",
    "docstring": "Get the encrypted GitHub token in Travis.\n\n    Make sure the contents this variable do not leak. The ``run()`` function\n    will remove this from the output, so always use it."
  },
  {
    "code": "def install(directory,\n            composer=None,\n            php=None,\n            runas=None,\n            prefer_source=None,\n            prefer_dist=None,\n            no_scripts=None,\n            no_plugins=None,\n            optimize=None,\n            no_dev=None,\n            quiet=False,\n            composer_home='/root',\n            env=None):\n    result = _run_composer('install',\n                           directory=directory,\n                           composer=composer,\n                           php=php,\n                           runas=runas,\n                           prefer_source=prefer_source,\n                           prefer_dist=prefer_dist,\n                           no_scripts=no_scripts,\n                           no_plugins=no_plugins,\n                           optimize=optimize,\n                           no_dev=no_dev,\n                           quiet=quiet,\n                           composer_home=composer_home,\n                           env=env)\n    return result",
    "docstring": "Install composer dependencies for a directory.\n\n    If composer has not been installed globally making it available in the\n    system PATH & making it executable, the ``composer`` and ``php`` parameters\n    will need to be set to the location of the executables.\n\n    directory\n        Directory location of the composer.json file.\n\n    composer\n        Location of the composer.phar file. If not set composer will\n        just execute \"composer\" as if it is installed globally.\n        (i.e. /path/to/composer.phar)\n\n    php\n        Location of the php executable to use with composer.\n        (i.e. /usr/bin/php)\n\n    runas\n        Which system user to run composer as.\n\n    prefer_source\n        --prefer-source option of composer.\n\n    prefer_dist\n        --prefer-dist option of composer.\n\n    no_scripts\n        --no-scripts option of composer.\n\n    no_plugins\n        --no-plugins option of composer.\n\n    optimize\n        --optimize-autoloader option of composer. Recommended for production.\n\n    no_dev\n        --no-dev option for composer. Recommended for production.\n\n    quiet\n        --quiet option for composer. Whether or not to return output from composer.\n\n    composer_home\n        $COMPOSER_HOME environment variable\n\n    env\n        A list of environment variables to be set prior to execution.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' composer.install /var/www/application\n\n        salt '*' composer.install /var/www/application \\\n            no_dev=True optimize=True"
  },
  {
    "code": "def get_rel_sciobj_file_path(pid):\n    hash_str = hashlib.sha1(pid.encode('utf-8')).hexdigest()\n    return os.path.join(hash_str[:2], hash_str[2:4], hash_str)",
    "docstring": "Get the relative local path to the file holding an object's bytes.\n\n    - The path is relative to settings.OBJECT_STORE_PATH\n    - There is a one-to-one mapping between pid and path\n    - The path is based on a SHA1 hash. It's now possible to craft SHA1 collisions, but\n      it's so unlikely that we ignore it for now\n    - The path may or may not exist (yet)."
  },
  {
    "code": "def hybrid_forward(self, F, inputs):\n        outputs = self.ffn_1(inputs)\n        if self.activation:\n            outputs = self.activation(outputs)\n        outputs = self.ffn_2(outputs)\n        if self._dropout:\n            outputs = self.dropout_layer(outputs)\n        if self._use_residual:\n            outputs = outputs + inputs\n        outputs = self.layer_norm(outputs)\n        return outputs",
    "docstring": "Position-wise encoding of the inputs.\n\n        Parameters\n        ----------\n        inputs : Symbol or NDArray\n            Input sequence. Shape (batch_size, length, C_in)\n\n        Returns\n        -------\n        outputs : Symbol or NDArray\n            Shape (batch_size, length, C_out)"
  },
  {
    "code": "def load(filename):\n    try:\n        with open(filename, 'rb') as f:\n            return pickle.load(f)\n    except Exception as e1:\n        try:\n            return jl_load(filename)\n        except Exception as e2:\n            raise IOError(\n                \"Unable to load {} using the pickle or joblib protocol.\\n\"\n                \"Pickle: {}\\n\"\n                \"Joblib: {}\".format(filename, e1, e2)\n            )",
    "docstring": "Load an object that has been saved with dump.\n\n    We try to open it using the pickle protocol. As a fallback, we\n    use joblib.load. Joblib was the default prior to msmbuilder v3.2\n\n    Parameters\n    ----------\n    filename : string\n        The name of the file to load."
  },
  {
    "code": "def variablename(var):\n    s=[tpl[0] for tpl in itertools.ifilter(lambda x: var is x[1], globals().items())]\n    s=s[0].upper()\n    return s",
    "docstring": "Returns the string of a variable name."
  },
  {
    "code": "def execute_with_style_LEGACY(template, style, data, callback, body_subtree='body'):\n    try:\n        body_data = data[body_subtree]\n    except KeyError:\n        raise EvaluationError('Data dictionary has no subtree %r' % body_subtree)\n    tokens_body = []\n    template.execute(body_data, tokens_body.append)\n    data[body_subtree] = tokens_body\n    tokens = []\n    style.execute(data, tokens.append)\n    _FlattenToCallback(tokens, callback)",
    "docstring": "OBSOLETE old API."
  },
  {
    "code": "def bk_blue(cls):\n        \"Make the text background color blue.\"\n        wAttributes = cls._get_text_attributes()\n        wAttributes &= ~win32.BACKGROUND_MASK\n        wAttributes |=  win32.BACKGROUND_BLUE\n        cls._set_text_attributes(wAttributes)",
    "docstring": "Make the text background color blue."
  },
  {
    "code": "def default_spec(self, manager):\n        specstr = \"\"\n        stable_families = manager.stable_families\n        if manager.config.releases_unstable_prehistory and stable_families:\n            specstr = \">={}\".format(min(stable_families))\n        if self.is_featurelike:\n            if True:\n                specstr = \">={}\".format(max(manager.keys()))\n        else:\n            buckets = self.minor_releases(manager)\n            if buckets:\n                specstr = \">={}\".format(max(buckets))\n        return Spec(specstr) if specstr else Spec()",
    "docstring": "Given the current release-lines structure, return a default Spec.\n\n        Specifics:\n\n        * For feature-like issues, only the highest major release is used, so\n          given a ``manager`` with top level keys of ``[1, 2]``, this would\n          return ``Spec(\">=2\")``.\n\n            * When ``releases_always_forwardport_features`` is ``True``, that\n              behavior is nullified, and this function always returns the empty\n              ``Spec`` (which matches any and all versions/lines).\n\n        * For bugfix-like issues, we only consider major release families which\n          have actual releases already.\n\n            * Thus the core difference here is that features are 'consumed' by\n              upcoming major releases, and bugfixes are not.\n\n        * When the ``unstable_prehistory`` setting is ``True``, the default\n          spec starts at the oldest non-zero release line. (Otherwise, issues\n          posted after prehistory ends would try being added to the 0.x part of\n          the tree, which makes no sense in unstable-prehistory mode.)"
  },
  {
    "code": "def _get_id(self):\n        return ''.join(map(str,\n                           filter(is_not_None,\n                                  [self.Prefix, self.Name])))",
    "docstring": "Construct and return the identifier"
  },
  {
    "code": "def send_pgrp(cls, sock, pgrp):\n    assert(isinstance(pgrp, IntegerForPid) and pgrp < 0)\n    encoded_int = cls.encode_int(pgrp)\n    cls.write_chunk(sock, ChunkType.PGRP, encoded_int)",
    "docstring": "Send the PGRP chunk over the specified socket."
  },
  {
    "code": "def get_current_key(self, resource_name):\n        url = ENCRYPTION_CURRENT_KEY_URL.format(resource_name)\n        return self._key_from_json(self._get_resource(url))",
    "docstring": "Returns a restclients.Key object for the given resource.  If the\n        resource isn't found, or if there is an error communicating with the\n        KWS, a DataFailureException will be thrown."
  },
  {
    "code": "def headers(self):\n        return {\n            \"Content-Type\": (\"multipart/form-data; boundary={}\".format(self.boundary)),\n            \"Content-Length\": str(self.len),\n            \"Content-Encoding\": self.encoding,\n        }",
    "docstring": "All headers needed to make a request"
  },
  {
    "code": "def _guessunit(self):\n        if not self.days % 1:\n            return 'd'\n        elif not self.hours % 1:\n            return 'h'\n        elif not self.minutes % 1:\n            return 'm'\n        elif not self.seconds % 1:\n            return 's'\n        else:\n            raise ValueError(\n                'The stepsize is not a multiple of one '\n                'second, which is not allowed.')",
    "docstring": "Guess the unit of the period as the largest one, which results in\n        an integer duration."
  },
  {
    "code": "def from_response(response):\n        http_response = response.raw._original_response\n        status_line = \"HTTP/1.1 %d %s\" % (http_response.status, http_response.reason)\n        headers = str(http_response.msg)\n        body = http_response.read()\n        response.raw._fp = StringIO(body)\n        payload = status_line + \"\\r\\n\" + headers + \"\\r\\n\" + body\n        headers = {\n            \"WARC-Type\": \"response\",\n            \"WARC-Target-URI\": response.request.full_url.encode('utf-8')\n        }\n        return WARCRecord(payload=payload, headers=headers)",
    "docstring": "Creates a WARCRecord from given response object.\n\n        This must be called before reading the response. The response can be \n        read after this method is called.\n        \n        :param response: An instance of :class:`requests.models.Response`."
  },
  {
    "code": "def getlist(self, section, option):\n        value = self.get(section, option)\n        if value:\n            return value.split(',')\n        else:\n            return None",
    "docstring": "returns the named option as a list, splitting the original value\n            by ','"
  },
  {
    "code": "def setKeySequenceCounter(self, iKeySequenceValue):\n        print '%s call setKeySequenceCounter' % self.port\n        print iKeySequenceValue\n        try:\n            cmd = WPANCTL_CMD + 'setprop Network:KeyIndex %s' % str(iKeySequenceValue)\n            if self.__sendCommand(cmd)[0] != 'Fail':\n                time.sleep(1)\n                return True\n            else:\n                return False\n        except Exception, e:\n            ModuleHelper.WriteIntoDebugLogger('setKeySequenceCounter() Error: ' + str(e))",
    "docstring": "set the Key sequence counter corresponding to Thread Network master key\n\n        Args:\n            iKeySequenceValue: key sequence value\n\n        Returns:\n            True: successful to set the key sequence\n            False: fail to set the key sequence"
  },
  {
    "code": "def vertical_velocity(omega, pressure, temperature, mixing=0):\n    r\n    rho = density(pressure, temperature, mixing)\n    return (omega / (- mpconsts.g * rho)).to('m/s')",
    "docstring": "r\"\"\"Calculate w from omega assuming hydrostatic conditions.\n\n    This function converts vertical velocity with respect to pressure\n    :math:`\\left(\\omega = \\frac{Dp}{Dt}\\right)` to that with respect to height\n    :math:`\\left(w = \\frac{Dz}{Dt}\\right)` assuming hydrostatic conditions on\n    the synoptic scale. By Equation 7.33 in [Hobbs2006]_,\n\n    .. math: \\omega \\simeq -\\rho g w\n\n    so that\n\n    .. math w \\simeq \\frac{- \\omega}{\\rho g}\n\n    Density (:math:`\\rho`) is calculated using the :func:`density` function,\n    from the given pressure and temperature. If `mixing` is given, the virtual\n    temperature correction is used, otherwise, dry air is assumed.\n\n    Parameters\n    ----------\n    omega: `pint.Quantity`\n        Vertical velocity in terms of pressure\n    pressure: `pint.Quantity`\n        Total atmospheric pressure\n    temperature: `pint.Quantity`\n        Air temperature\n    mixing: `pint.Quantity`, optional\n        Mixing ratio of air\n\n    Returns\n    -------\n    `pint.Quantity`\n        Vertical velocity in terms of height (in meters / second)\n\n    See Also\n    --------\n    density, vertical_velocity_pressure"
  },
  {
    "code": "def _reconnect_handler(self):\n        for channel_name, channel in self.channels.items():\n            data = {'channel': channel_name}\n            if channel.auth:\n                data['auth'] = channel.auth\n            self.connection.send_event('pusher:subscribe', data)",
    "docstring": "Handle a reconnect."
  },
  {
    "code": "def get(self, preview_id):\n        return self.request.get('get', params=dict(id=preview_id))",
    "docstring": "Retrieve a Historics preview job.\n\n            Warning: previews expire after 24 hours.\n\n            Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/previewget\n\n            :param preview_id: historics preview job hash of the job to retrieve\n            :type preview_id: str\n            :return: dict of REST API output with headers attached\n            :rtype: :class:`~datasift.request.DictResponse`\n            :raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`"
  },
  {
    "code": "def _logger(self):\n        level = logging.INFO\n        self.log.setLevel(level)\n        self.log.handlers = []\n        if self.default_args.logging is not None:\n            level = self._logger_levels[self.default_args.logging]\n        elif self.default_args.tc_log_level is not None:\n            level = self._logger_levels[self.default_args.tc_log_level]\n        self.log.setLevel(level)\n        if self.default_args.tc_log_path:\n            self._logger_fh()\n        if self.default_args.tc_token is not None and self.default_args.tc_log_to_api:\n            self._logger_api()\n        self.log.info('Logging Level: {}'.format(logging.getLevelName(level)))",
    "docstring": "Create TcEx app logger instance.\n\n        The logger is accessible via the ``tc.log.<level>`` call.\n\n        **Logging examples**\n\n        .. code-block:: python\n            :linenos:\n            :lineno-start: 1\n\n            tcex.log.debug('logging debug')\n            tcex.log.info('logging info')\n            tcex.log.warning('logging warning')\n            tcex.log.error('logging error')\n\n        Args:\n            stream_only (bool, default:False): If True only the Stream handler will be enabled.\n\n        Returns:\n            logger: An instance of logging"
  },
  {
    "code": "def _load_data(self):\n        if self.raw_data is None and self.data_format is not FormatType.PYTHON:\n            if self.file_path is None:\n                raise ArgumentInvalid('One of \"raw_data\" or \"file_path\" should be set!')\n            if not os.path.isfile(self.file_path) or not os.access(self.file_path, os.R_OK):\n                raise ArgumentInvalid('\"file_path\" should be a valid path to an exist file with read permission!')\n            with open(self.file_path) as f:\n                self.raw_data = f.read()",
    "docstring": "Load data from raw_data or file_path"
  },
  {
    "code": "def get_doc(additional_doc=False,\n            field_prefix='$',\n            field_suffix=':',\n            indent=4):\n    if additional_doc:\n        f = fields.copy()\n        f.update(additional_doc)\n    else:\n        f = fields\n    field_length = get_max_field_length(f)\n    field_length = field_length + len(field_prefix) + len(field_suffix) + 4\n    description_indent = ' ' * (indent + field_length)\n    output = ''\n    for field, description in sorted(f.items()):\n        description = description['description']\n        field = ' ' * indent + field_prefix + field + ':'\n        output += field.ljust(field_length) + \\\n            textwrap.fill(\n                description,\n                width=78,\n                initial_indent=description_indent,\n                subsequent_indent=description_indent\n            )[field_length:] + '\\n\\n\\n'\n    return output",
    "docstring": "Return a formated string containing documentation about the audio\n    fields."
  },
  {
    "code": "def find_module_path():\n    master_modname = __name__.split(\".\", 1)[0]\n    master_module = sys.modules[master_modname]\n    path = os.path.dirname(inspect.getsourcefile(master_module))\n    return path",
    "docstring": "find where the master module is located"
  },
  {
    "code": "def mousePressEvent(self, event):\n        if self.scene is not None:\n            x_in_scene = self.mapToScene(event.pos()).x()\n            window_length = self.parent.value('window_length')\n            window_start = int(floor(x_in_scene / window_length) *\n                               window_length)\n            if self.parent.notes.annot is not None:\n                window_start = self.parent.notes.annot.get_epoch_start(\n                        window_start)\n            self.update_position(window_start)",
    "docstring": "Jump to window when user clicks on overview.\n\n        Parameters\n        ----------\n        event : instance of QtCore.QEvent\n            it contains the position that was clicked."
  },
  {
    "code": "def is_bool(tg_type, inc_array=False):\n    global _scalar_bool_types, _array_bool_types\n    if tg_type in _scalar_bool_types:\n        return True\n    if not inc_array:\n        return False\n    return tg_type in _array_bool_types",
    "docstring": "Tells if the given tango type is boolean\n\n    :param tg_type: tango type\n    :type tg_type: :class:`tango.CmdArgType`\n    :param inc_array: (optional, default is False) determines if include array\n                      in the list of checked types\n    :type inc_array: :py:obj:`bool`\n\n    :return: True if the given tango type is boolean or False otherwise\n    :rtype: :py:obj:`bool`"
  },
  {
    "code": "def listscripts(self):\n        code, data, listing = self.__send_command(\n            \"LISTSCRIPTS\", withcontent=True)\n        if code == \"NO\":\n            return None\n        ret = []\n        active_script = None\n        for l in listing.splitlines():\n            if self.__size_expr.match(l):\n                continue\n            m = re.match(br'\"([^\"]+)\"\\s*(.+)', l)\n            if m is None:\n                ret += [l.strip(b'\"').decode(\"utf-8\")]\n                continue\n            script = m.group(1).decode(\"utf-8\")\n            if self.__active_expr.match(m.group(2)):\n                active_script = script\n                continue\n            ret += [script]\n        self.__dprint(ret)\n        return (active_script, ret)",
    "docstring": "List available scripts.\n\n        See MANAGESIEVE specifications, section 2.7\n\n        :returns: a 2-uple (active script, [script1, ...])"
  },
  {
    "code": "def list_app(self):\n        kwd = {\n            'pager': '',\n            'title': ''\n        }\n        self.render('user/info_list/list_app.html', kwd=kwd,\n                    userinfo=self.userinfo)",
    "docstring": "List the apps."
  },
  {
    "code": "def remove_network_profile(self, obj, params):\n        self._logger.debug(\"delete profile: %s\", params.ssid)\n        str_buf = create_unicode_buffer(params.ssid)\n        ret = self._wlan_delete_profile(self._handle, obj['guid'], str_buf)\n        self._logger.debug(\"delete result %d\", ret)",
    "docstring": "Remove the specified AP profile."
  },
  {
    "code": "def reset_modified(self):\n        self.modified_fields = set()\n        for field_name, field in self.schema.normal_fields.items():\n            if isinstance(field, ObjectField):\n                self.modified_fields.add(field_name)",
    "docstring": "reset field modification tracking\n\n        this is handy for when you are loading a new Orm with the results from a query and\n        you don't want set() to do anything, you can Orm(**fields) and then orm.reset_modified() to\n        clear all the passed in fields from the modified list"
  },
  {
    "code": "def variant_overlaps_interval(\n        variant_start,\n        n_ref_bases,\n        interval_start,\n        interval_end):\n    if n_ref_bases == 0:\n        return interval_start <= variant_start and interval_end >= variant_start\n    variant_end = variant_start + n_ref_bases\n    return interval_start <= variant_end and interval_end >= variant_start",
    "docstring": "Does a variant overlap a given interval on the same chromosome?\n\n    Parameters\n    ----------\n    variant_start : int\n        Inclusive base-1 position of variant's starting location\n        (or location before an insertion)\n\n    n_ref_bases : int\n        Number of reference bases affect by variant (used to compute\n        end coordinate or determine whether variant is an insertion)\n\n    interval_start : int\n        Interval's inclusive base-1 start position\n\n    interval_end : int\n        Interval's inclusive base-1 end position"
  },
  {
    "code": "def deploy(self, pathobj, fobj, md5=None, sha1=None, parameters=None):\n        if isinstance(fobj, urllib3.response.HTTPResponse):\n            fobj = HTTPResponseWrapper(fobj)\n        url = str(pathobj)\n        if parameters:\n            url += \";%s\" % encode_matrix_parameters(parameters)\n        headers = {}\n        if md5:\n            headers['X-Checksum-Md5'] = md5\n        if sha1:\n            headers['X-Checksum-Sha1'] = sha1\n        text, code = self.rest_put_stream(url,\n                                          fobj,\n                                          headers=headers,\n                                          auth=pathobj.auth,\n                                          verify=pathobj.verify,\n                                          cert=pathobj.cert)\n        if code not in [200, 201]:\n            raise RuntimeError(\"%s\" % text)",
    "docstring": "Uploads a given file-like object\n        HTTP chunked encoding will be attempted"
  },
  {
    "code": "def zero_missing_data(data1, data2):\n    nans = xu.logical_and(xu.isnan(data1), xu.logical_not(xu.isnan(data2)))\n    return data1.where(~nans, 0)",
    "docstring": "Replace NaN values with zeros in data1 if the data is valid in data2."
  },
  {
    "code": "def get_closest(self, sma):\n        index = (np.abs(self.sma - sma)).argmin()\n        return self._list[index]",
    "docstring": "Return the `~photutils.isophote.Isophote` instance that has the\n        closest semimajor axis length to the input semimajor axis.\n\n        Parameters\n        ----------\n        sma : float\n            The semimajor axis length.\n\n        Returns\n        -------\n        isophote : `~photutils.isophote.Isophote` instance\n            The isophote with the closest semimajor axis value."
  },
  {
    "code": "def get_unique_directives(ast):\n    if not ast.directives:\n        return dict()\n    result = dict()\n    for directive_obj in ast.directives:\n        directive_name = directive_obj.name.value\n        if directive_name in ALLOWED_DUPLICATED_DIRECTIVES:\n            pass\n        elif directive_name in result:\n            raise GraphQLCompilationError(u'Directive was unexpectedly applied twice in the same '\n                                          u'location: {} {}'.format(directive_name, ast.directives))\n        else:\n            result[directive_name] = directive_obj\n    return result",
    "docstring": "Return a dict of directive name to directive object for the given AST node.\n\n    Any directives that are allowed to exist more than once on any AST node are ignored.\n    For any directives that can only exist up to once, we verify that they are not duplicated\n    raising GraphQLCompilationError in case we find them more than once on the AST node.\n\n    Args:\n        ast: GraphQL AST node, obtained from the graphql library\n\n    Returns:\n        dict of string to directive object"
  },
  {
    "code": "def _list_existing(filesystem, glob, paths):\n    globs = _constrain_glob(glob, paths)\n    time_start = time.time()\n    listing = []\n    for g in sorted(globs):\n        logger.debug('Listing %s', g)\n        if filesystem.exists(g):\n            listing.extend(filesystem.listdir(g))\n    logger.debug('%d %s listings took %f s to return %d items',\n                 len(globs), filesystem.__class__.__name__, time.time() - time_start, len(listing))\n    return set(listing)",
    "docstring": "Get all the paths that do in fact exist. Returns a set of all existing paths.\n\n    Takes a luigi.target.FileSystem object, a str which represents a glob and\n    a list of strings representing paths."
  },
  {
    "code": "def build(path: str) -> dict:\n    update_base_image(path)\n    match = file_pattern.search(os.path.basename(path))\n    build_id = match.group('id')\n    tags = [\n        '{}:{}-{}'.format(HUB_PREFIX, version, build_id),\n        '{}:latest-{}'.format(HUB_PREFIX, build_id),\n        '{}:current-{}'.format(HUB_PREFIX, build_id)\n    ]\n    if build_id == 'standard':\n        tags.append('{}:latest'.format(HUB_PREFIX))\n    command = 'docker build --file \"{}\" {} .'.format(\n        path,\n        ' '.join(['-t {}'.format(t) for t in tags])\n    )\n    print('[BUILDING]:', build_id)\n    os.system(command)\n    return dict(\n        id=build_id,\n        path=path,\n        command=command,\n        tags=tags\n    )",
    "docstring": "Builds the container from the specified docker file path"
  },
  {
    "code": "def expect_column_values_to_be_of_type(\n        self,\n        column,\n        type_,\n        mostly=None,\n        result_format=None, include_config=False, catch_exceptions=None, meta=None\n    ):\n        raise NotImplementedError",
    "docstring": "Expect each column entry to be a specified data type.\n\n        expect_column_values_to_be_of_type is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`.\n\n        Args:\n            column (str): \\\n                The column name.\n            type\\_ (str): \\\n                A string representing the data type that each column should have as entries.\n                For example, \"double integer\" refers to an integer with double precision.\n\n        Keyword Args:\n            mostly (None or a float between 0 and 1): \\\n                Return `\"success\": True` if at least mostly percent of values match the expectation. \\\n                For more detail, see :ref:`mostly`.\n\n        Other Parameters:\n            result_format (str or None): \\\n                Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.\n                For more detail, see :ref:`result_format <result_format>`.\n            include_config (boolean): \\\n                If True, then include the expectation config as part of the result object. \\\n                For more detail, see :ref:`include_config`.\n            catch_exceptions (boolean or None): \\\n                If True, then catch exceptions and include them as part of the result object. \\\n                For more detail, see :ref:`catch_exceptions`.\n            meta (dict or None): \\\n                A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \\\n                For more detail, see :ref:`meta`.\n\n        Returns:\n            A JSON-serializable expectation result object.\n\n            Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and\n            :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.\n\n        Warning:\n            expect_column_values_to_be_of_type is slated for major changes in future versions of great_expectations.\n\n            As of v0.3, great_expectations is exclusively based on pandas, which handles typing in its own peculiar way.\n            Future versions of great_expectations will allow for Datasets in SQL, spark, etc.\n            When we make that change, we expect some breaking changes in parts of the codebase that are based strongly on pandas notions of typing.\n\n        See also:\n            expect_column_values_to_be_in_type_list"
  },
  {
    "code": "def create_element(tag: str, name: str = None, base: type = None,\n                   attr: dict = None) -> Node:\n    from wdom.web_node import WdomElement\n    from wdom.tag import Tag\n    from wdom.window import customElements\n    if attr is None:\n        attr = {}\n    if name:\n        base_class = customElements.get((name, tag))\n    else:\n        base_class = customElements.get((tag, None))\n    if base_class is None:\n        attr['_registered'] = False\n        base_class = base or WdomElement\n    if issubclass(base_class, Tag):\n        return base_class(**attr)\n    return base_class(tag, **attr)",
    "docstring": "Create element with a tag of ``name``.\n\n    :arg str name: html tag.\n    :arg type base: Base class of the created element\n                       (defatlt: ``WdomElement``)\n    :arg dict attr: Attributes (key-value pairs dict) of the new element."
  },
  {
    "code": "def object_data(self, multihash, **kwargs):\n        r\n        args = (multihash,)\n        return self._client.request('/object/data', args, **kwargs)",
    "docstring": "r\"\"\"Returns the raw bytes in an IPFS object.\n\n        .. code-block:: python\n\n            >>> c.object_data('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')\n            b'\\x08\\x01'\n\n        Parameters\n        ----------\n        multihash : str\n            Key of the object to retrieve, in base58-encoded multihash format\n\n        Returns\n        -------\n            str : Raw object data"
  },
  {
    "code": "def get_remove_security_group_commands(self, sg_id, profile):\n        return self._get_interface_commands(sg_id, profile, delete=True)",
    "docstring": "Commands for removing ACL from interface"
  },
  {
    "code": "def _hook(self, hook_name, doc_uri=None, **kwargs):\n        doc = self.workspace.get_document(doc_uri) if doc_uri else None\n        hook_handlers = self.config.plugin_manager.subset_hook_caller(hook_name, self.config.disabled_plugins)\n        return hook_handlers(config=self.config, workspace=self.workspace, document=doc, **kwargs)",
    "docstring": "Calls hook_name and returns a list of results from all registered handlers"
  },
  {
    "code": "def repmi(instr, marker, value, lenout=None):\n    if lenout is None:\n        lenout = ctypes.c_int(len(instr) + len(marker) + 15)\n    instr = stypes.stringToCharP(instr)\n    marker = stypes.stringToCharP(marker)\n    value = ctypes.c_int(value)\n    out = stypes.stringToCharP(lenout)\n    libspice.repmi_c(instr, marker, value, lenout, out)\n    return stypes.toPythonString(out)",
    "docstring": "Replace a marker with an integer.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmi_c.html\n\n    :param instr: Input string.\n    :type instr: str\n    :param marker: Marker to be replaced.\n    :type marker: str\n    :param value: Replacement value.\n    :type value: int\n    :param lenout: Optional available space in output string.\n    :type lenout: int\n    :return: Output string.\n    :rtype: str"
  },
  {
    "code": "def reset_default(verbose=False):\n    paths = [jupyter_custom, jupyter_nbext]\n    for fpath in paths:\n        custom = '{0}{1}{2}.css'.format(fpath, os.sep, 'custom')\n        try:\n            os.remove(custom)\n        except Exception:\n            pass\n    try:\n        delete_font_files()\n    except Exception:\n        check_directories()\n        delete_font_files()\n    copyfile(defaultCSS, jupyter_customcss)\n    copyfile(defaultJS, jupyter_customjs)\n    if os.path.exists(theme_name_file):\n        os.remove(theme_name_file)\n    if verbose:\n        print(\"Reset css and font defaults in:\\n{} &\\n{}\".format(*paths))",
    "docstring": "Remove custom.css and custom fonts"
  },
  {
    "code": "def userinfo(self, access_token):\n        return self.get(\n            url='https://{}/userinfo'.format(self.domain),\n            headers={'Authorization': 'Bearer {}'.format(access_token)}\n        )",
    "docstring": "Returns the user information based on the Auth0 access token.\n        This endpoint will work only if openid was granted as a scope for the access_token.\n\n        Args:\n            access_token (str): Auth0 access token (obtained during login).\n\n        Returns:\n            The user profile."
  },
  {
    "code": "def parse_xml_string(self, xml, id_generator=None):\n        if id_generator is not None:\n            warnings.warn(\n                \"Passing an id_generator directly is deprecated \"\n                \"in favor of constructing the Runtime with the id_generator\",\n                DeprecationWarning,\n                stacklevel=2,\n            )\n        id_generator = id_generator or self.id_generator\n        if isinstance(xml, six.binary_type):\n            io_type = BytesIO\n        else:\n            io_type = StringIO\n        return self.parse_xml_file(io_type(xml), id_generator)",
    "docstring": "Parse a string of XML, returning a usage id."
  },
  {
    "code": "def train_agent_real_env(env, learner, hparams, epoch):\n  base_algo_str = hparams.base_algo\n  train_hparams = trainer_lib.create_hparams(hparams.base_algo_params)\n  rl_utils.update_hparams_from_hparams(\n      train_hparams, hparams, \"real_\" + base_algo_str + \"_\"\n  )\n  if hparams.wm_policy_param_sharing:\n    train_hparams.optimizer_zero_grads = True\n  env_fn = rl.make_real_env_fn(env)\n  num_env_steps = real_env_step_increment(hparams)\n  learner.train(\n      env_fn,\n      train_hparams,\n      simulated=False,\n      save_continuously=False,\n      epoch=epoch,\n      sampling_temp=hparams.real_sampling_temp,\n      num_env_steps=num_env_steps,\n  )\n  env.reset()",
    "docstring": "Train the PPO agent in the real environment."
  },
  {
    "code": "def execute(self, context):\n        for ware in self.middleware:\n            ware.premessage(context)\n            context = ware.bind(context)\n            ware.postmessage(context)\n        return context",
    "docstring": "Execute the strategies on the given context"
  },
  {
    "code": "def get_url(url, data=None, cached=True, cache_key=None, crawler='urllib'):\n    if cache_key is None:\n        cache_key = url\n    cache_path = cache_path_for_url(cache_key)\n    if cached and os.path.exists(cache_path):\n        with open(cache_path) as f:\n            html = f.read().decode('utf-8')\n    else:\n        if FAIL_IF_NOT_CACHED:\n            raise BaseException(\"URL is not in cache and FAIL_IF_NOT_CACHED is True: %s\" % url)\n        crawler_fn = CRAWLERS[crawler]\n        status, html = crawler_fn(url, data)\n        if status != 200: \n            raise HttpNotFound(url)\n        _ensure_directory(CACHE_DIRECTORY)\n        with open(cache_path, 'w') as f:\n            f.write(html.encode('utf-8'))\n    return html",
    "docstring": "Retrieves the HTML code for a given URL.\n     If a cached version is not available, uses phantom_retrieve to fetch the page.\n\n    data - Additional data that gets passed onto the crawler.\n    cached - If True, retrieves the URL from the cache if it is available. If False, will still store the page in cache.\n    cache_key - If set, will be used instead of the URL to lookup the cached version of the page.\n    crawler - A string referencing one of the builtin crawlers.\n\n    Returns the HTML as a unicode string.\n    Raises a HttpNotFound exception if the page could not be found."
  },
  {
    "code": "def qteRemoveHighlighting(self, widgetObj):\n        data = self.qteMacroData(widgetObj)\n        if not data:\n            return\n        if not data.matchingPositions:\n            return\n        self.highlightCharacters(widgetObj, data.matchingPositions,\n                                 QtCore.Qt.black, 50, data.oldCharFormats)\n        data.matchingPositions = None\n        data.oldCharFormats = None\n        self.qteSaveMacroData(data, widgetObj)",
    "docstring": "Remove the highlighting from previously highlighted characters.\n\n        The method access instance variables to determine which\n        characters are currently highlighted and have to be converted\n        to non-highlighted ones.\n\n        |Args|\n\n        * ``widgetObj`` (**QWidget**): the ``QTextEdit`` to use.\n\n        |Returns|\n\n        * **None**\n\n        |Raises|\n\n        * **None**"
  },
  {
    "code": "def any_text_to_fernet_key(self, text):\n        md5 = fingerprint.fingerprint.of_text(text)\n        fernet_key = base64.b64encode(md5.encode(\"utf-8\"))\n        return fernet_key",
    "docstring": "Convert any text to a fernet key for encryption."
  },
  {
    "code": "def _get_error_values(self, startingPercentage, endPercentage, startDate, endDate):\n        if startDate is not None:\n            possibleDates = filter(lambda date: date >= startDate, self._errorDates)\n            if 0 == len(possibleDates):\n                raise ValueError(\"%s does not represent a valid startDate.\" % startDate)\n            startIdx = self._errorDates.index(min(possibleDates))\n        else:\n            startIdx = int((startingPercentage * len(self._errorValues)) / 100.0)\n        if endDate is not None:\n            possibleDates = filter(lambda date: date <= endDate, self._errorDates)\n            if 0 == len(possibleDates):\n                raise ValueError(\"%s does not represent a valid endDate.\" % endDate)\n            endIdx = self._errorDates.index(max(possibleDates)) + 1\n        else:\n            endIdx = int((endPercentage * len(self._errorValues)) / 100.0)\n        return self._errorValues[startIdx:endIdx]",
    "docstring": "Gets the defined subset of self._errorValues.\n\n        Both parameters will be correct at this time.\n\n        :param float startingPercentage: Defines the start of the interval. This has to be a value in [0.0, 100.0].\n            It represents the value, where the error calculation should be started.\n            25.0 for example means that the first 25% of all calculated errors will be ignored.\n        :param float endPercentage:    Defines the end of the interval. This has to be a value in [0.0, 100.0].\n            It represents the value, after which all error values will be ignored. 90.0 for example means that\n            the last 10% of all local errors will be ignored.\n        :param float startDate: Epoch representing the start date used for error calculation.\n        :param float endDate: Epoch representing the end date used in the error calculation.\n\n        :return:    Returns a list with the defined error values.\n        :rtype: list\n\n        :raise:    Raises a ValueError if startDate or endDate do not represent correct boundaries for error calculation."
  },
  {
    "code": "def get_feature_penalty(self):\n        if self.feature_penalty is None:\n            self.feature_penalty = self.get_field('feature_penalty')\n        return self.feature_penalty",
    "docstring": "Get the feature penalty of the Dataset.\n\n        Returns\n        -------\n        feature_penalty : numpy array or None\n            Feature penalty for each feature in the Dataset."
  },
  {
    "code": "def _extract_conjuction_elements_from_expression(expression):\n    if isinstance(expression, BinaryComposition) and expression.operator == u'&&':\n        for element in _extract_conjuction_elements_from_expression(expression.left):\n            yield element\n        for element in _extract_conjuction_elements_from_expression(expression.right):\n            yield element\n    else:\n        yield expression",
    "docstring": "Return a generator for expressions that are connected by `&&`s in the given expression."
  },
  {
    "code": "def register_optionables(self, optionables):\n    if not isinstance(optionables, Iterable):\n      raise TypeError('The optionables must be an iterable, given {}'.format(optionables))\n    optionables = tuple(optionables)\n    if not optionables:\n      return\n    invalid_optionables = [s\n                           for s in optionables\n                           if not isinstance(s, type) or not issubclass(s, Optionable)]\n    if invalid_optionables:\n      raise TypeError('The following items from the given optionables are not Optionable '\n                      'subclasses:\\n\\t{}'.format('\\n\\t'.join(str(i) for i in invalid_optionables)))\n    self._optionables.update(optionables)",
    "docstring": "Registers the given subsystem types.\n\n    :param optionables: The Optionable types to register.\n    :type optionables: :class:`collections.Iterable` containing\n                       :class:`pants.option.optionable.Optionable` subclasses."
  },
  {
    "code": "def ensurearray(*args):\n    input_is_array = any(isinstance(arg, numpy.ndarray) for arg in args)\n    args = numpy.broadcast_arrays(*args)\n    args.append(input_is_array)\n    return args",
    "docstring": "Apply numpy's broadcast rules to the given arguments.\n\n    This will ensure that all of the arguments are numpy arrays and that they\n    all have the same shape. See ``numpy.broadcast_arrays`` for more details.\n\n    It also returns a boolean indicating whether any of the inputs were\n    originally arrays.\n\n    Parameters\n    ----------\n    *args :\n        The arguments to check.\n\n    Returns\n    -------\n    list :\n        A list with length ``N+1`` where ``N`` is the number of given\n        arguments. The first N values are the input arguments as ``ndarrays``s.\n        The last value is a boolean indicating whether any of the\n        inputs was an array."
  },
  {
    "code": "def apply_translation(self, translation):\n        translation = np.asanyarray(translation, dtype=np.float64)\n        if translation.shape != (3,):\n            raise ValueError('Translation must be (3,)!')\n        matrix = np.eye(4)\n        matrix[:3, 3] = translation\n        self.apply_transform(matrix)",
    "docstring": "Translate the current mesh.\n\n        Parameters\n        ----------\n        translation : (3,) float\n          Translation in XYZ"
  },
  {
    "code": "def remove_nio(self, port_number):\n        if port_number not in self._nios:\n            raise NodeError(\"Port {} is not allocated\".format(port_number))\n        nio = self._nios[port_number]\n        if isinstance(nio, NIOUDP):\n            self.manager.port_manager.release_udp_port(nio.lport, self._project)\n        log.info('Cloud \"{name}\" [{id}]: NIO {nio} removed from port {port}'.format(name=self._name,\n                                                                                    id=self._id,\n                                                                                    nio=nio,\n                                                                                    port=port_number))\n        del self._nios[port_number]\n        if self._ubridge_hypervisor and self._ubridge_hypervisor.is_running():\n            yield from self._delete_ubridge_connection(port_number)\n        yield from self.start()\n        return nio",
    "docstring": "Removes the specified NIO as member of cloud.\n\n        :param port_number: allocated port number\n\n        :returns: the NIO that was bound to the allocated port"
  },
  {
    "code": "def leave_group(self, group_id, timeout=None):\n        self._post(\n            '/v2/bot/group/{group_id}/leave'.format(group_id=group_id),\n            timeout=timeout\n        )",
    "docstring": "Call leave group API.\n\n        https://devdocs.line.me/en/#leave\n\n        Leave a group.\n\n        :param str group_id: Group ID\n        :param timeout: (optional) How long to wait for the server\n            to send data before giving up, as a float,\n            or a (connect timeout, read timeout) float tuple.\n            Default is self.http_client.timeout\n        :type timeout: float | tuple(float, float)"
  },
  {
    "code": "def add_variable(self, key, value, system_wide=False):\n        if system_wide:\n            javabridge.call(self.jobject, \"addVariableSystemWide\", \"(Ljava/lang/String;Ljava/lang/String;)V\", key, value)\n        else:\n            javabridge.call(self.jobject, \"addVariable\", \"(Ljava/lang/String;Ljava/lang/String;)V\", key, value)",
    "docstring": "Adds the environment variable.\n\n        :param key: the name of the variable\n        :type key: str\n        :param value: the value\n        :type value: str\n        :param system_wide: whether to add the variable system wide\n        :type system_wide: bool"
  },
  {
    "code": "def connect(self, broker, port=1883, client_id=\"\", clean_session=True):\n        logger.info('Connecting to %s at port %s' % (broker, port))\n        self._connected = False\n        self._unexpected_disconnect = False\n        self._mqttc = mqtt.Client(client_id, clean_session)\n        self._mqttc.on_connect = self._on_connect\n        self._mqttc.on_disconnect = self._on_disconnect\n        if self._username:\n            self._mqttc.username_pw_set(self._username, self._password)\n        self._mqttc.connect(broker, int(port))\n        timer_start = time.time()\n        while time.time() < timer_start + self._loop_timeout:\n            if self._connected or self._unexpected_disconnect:\n                break;\n            self._mqttc.loop()\n        if self._unexpected_disconnect:\n            raise RuntimeError(\"The client disconnected unexpectedly\")\n        logger.debug('client_id: %s' % self._mqttc._client_id)\n        return self._mqttc",
    "docstring": "Connect to an MQTT broker. This is a pre-requisite step for publish\n        and subscribe keywords.\n\n        `broker` MQTT broker host\n\n        `port` broker port (default 1883)\n\n        `client_id` if not specified, a random id is generated\n\n        `clean_session` specifies the clean session flag for the connection\n\n        Examples:\n\n        Connect to a broker with default port and client id\n        | Connect | 127.0.0.1 |\n\n        Connect to a broker by specifying the port and client id explicitly\n        | Connect | 127.0.0.1 | 1883 | test.client |\n\n        Connect to a broker with clean session flag set to false\n        | Connect | 127.0.0.1 | clean_session=${false} |"
  },
  {
    "code": "def remove_arg(self, arg):\n        self.args = [arg_.strip() for arg_ in self.args if arg_.strip()]\n        for arg_ in list(self.args):\n            if arg_.lower() == arg.lower():\n                self.args.remove(arg_)",
    "docstring": "Remove an arg to the arg list"
  },
  {
    "code": "def archive(class_obj: type) -> type:\n    assert isinstance(class_obj, type), \"class_obj is not a Class\"\n    global _archive_resource_type\n    _archive_resource_type = class_obj\n    return class_obj",
    "docstring": "Decorator to annotate the Archive class. Registers the decorated class\n    as the Archive known type."
  },
  {
    "code": "def report_error_event(self, error_report):\n        project_name = self._gapic_api.project_path(self._project)\n        error_report_payload = report_errors_service_pb2.ReportedErrorEvent()\n        ParseDict(error_report, error_report_payload)\n        self._gapic_api.report_error_event(project_name, error_report_payload)",
    "docstring": "Uses the gapic client to report the error.\n\n        :type error_report: dict\n        :param error_report:\n            payload of the error report formatted according to\n            https://cloud.google.com/error-reporting/docs/formatting-error-messages\n            This object should be built using\n            Use\n            :meth:~`google.cloud.error_reporting.client._build_error_report`"
  },
  {
    "code": "def _s3_path_split(s3_path):\n    if not s3_path.startswith('s3://'):\n        raise ValueError('s3_path is expected to start with \\'s3://\\', '\n                         'but was {}'.format(s3_path))\n    bucket_key = s3_path[len('s3://'):]\n    bucket_name, key = bucket_key.split('/', 1)\n    return S3Path(bucket_name, key)",
    "docstring": "Split an S3 path into bucket and key.\n\n    Parameters\n    ----------\n    s3_path : str\n\n    Returns\n    -------\n    splitted : (str, str)\n        (bucket, key)\n\n    Examples\n    --------\n    >>> _s3_path_split('s3://my-bucket/foo/bar.jpg')\n    S3Path(bucket_name='my-bucket', key='foo/bar.jpg')"
  },
  {
    "code": "def anti_clobber_dir_path(dir_path, suffix='.d'):\n    dir_path = os.path.normpath(dir_path)\n    parts = dir_path.split(os.sep)\n    for index in range(len(parts)):\n        test_path = os.sep.join(parts[:index + 1])\n        if os.path.isfile(test_path):\n            parts[index] += suffix\n            return os.sep.join(parts)\n    return dir_path",
    "docstring": "Return a directory path free of filenames.\n\n    Args:\n        dir_path (str): A directory path.\n        suffix (str): The suffix to append to the part of the path that is\n             a file.\n\n    Returns:\n        str"
  },
  {
    "code": "def create_vnet(access_token, subscription_id, resource_group, name, location,\n                address_prefix='10.0.0.0/16', subnet_prefix='10.0.0.0/16', nsg_id=None):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/resourceGroups/', resource_group,\n                        '/providers/Microsoft.Network/virtualNetworks/', name,\n                        '?api-version=', NETWORK_API])\n    vnet_body = {'location': location}\n    properties = {'addressSpace': {'addressPrefixes': [address_prefix]}}\n    subnet = {'name': 'subnet'}\n    subnet['properties'] = {'addressPrefix': subnet_prefix}\n    if nsg_id is not None:\n        subnet['properties']['networkSecurityGroup'] = {'id': nsg_id}\n    properties['subnets'] = [subnet]\n    vnet_body['properties'] = properties\n    body = json.dumps(vnet_body)\n    return do_put(endpoint, body, access_token)",
    "docstring": "Create a VNet with specified name and location. Optional subnet address prefix..\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n        resource_group (str): Azure resource group name.\n        name (str): Name of the new VNet.\n        location (str): Azure data center location. E.g. westus.\n        address_prefix (str): Optional VNet address prefix. Default '10.0.0.0/16'.\n        subnet_prefix (str): Optional subnet address prefix. Default '10.0.0.0/16'.\n        nsg_id (str): Optional Netwrok Security Group resource Id. Default None.\n\n    Returns:\n        HTTP response. VNet JSON body."
  },
  {
    "code": "def transform_around(matrix, point):\n    point = np.asanyarray(point)\n    matrix = np.asanyarray(matrix)\n    dim = len(point)\n    if matrix.shape != (dim + 1,\n                        dim + 1):\n        raise ValueError('matrix must be (d+1, d+1)')\n    translate = np.eye(dim + 1)\n    translate[:dim, dim] = -point\n    result = np.dot(matrix, translate)\n    translate[:dim, dim] = point\n    result = np.dot(translate, result)\n    return result",
    "docstring": "Given a transformation matrix, apply its rotation\n    around a point in space.\n\n    Parameters\n    ----------\n    matrix: (4,4) or (3, 3) float, transformation matrix\n    point:  (3,) or (2,)  float, point in space\n\n    Returns\n    ---------\n    result: (4,4) transformation matrix"
  },
  {
    "code": "def _render_our_module_key_flags(self, module, output_lines, prefix=''):\n    key_flags = self.get_key_flags_for_module(module)\n    if key_flags:\n      self._render_module_flags(module, key_flags, output_lines, prefix)",
    "docstring": "Returns a help string for the key flags of a given module.\n\n    Args:\n      module: module|str, the module to render key flags for.\n      output_lines: [str], a list of strings.  The generated help message\n          lines will be appended to this list.\n      prefix: str, a string that is prepended to each generated help line."
  },
  {
    "code": "def set_value(self, obj, value):\n        if value:\n            obj.set_field_value(self.name, value)\n        else:\n            self.delete_value(obj)",
    "docstring": "Sets value to model if not empty"
  },
  {
    "code": "def getrawpartid(self, msgid, partid, stream=sys.stdout):\n        parts = [part for hdr,part in self._get(msgid)]\n        part = parts[int(partid)]\n        pl = part.get_payload(decode=True)\n        if pl != None:\n            print(pl, file=stream)",
    "docstring": "Get a specific part from the message and print it raw."
  },
  {
    "code": "def Concat(*args: Union[BitVec, List[BitVec]]) -> BitVec:\n    if len(args) == 1 and isinstance(args[0], list):\n        bvs = args[0]\n    else:\n        bvs = cast(List[BitVec], args)\n    nraw = z3.Concat([a.raw for a in bvs])\n    annotations = []\n    bitvecfunc = False\n    for bv in bvs:\n        annotations += bv.annotations\n        if isinstance(bv, BitVecFunc):\n            bitvecfunc = True\n    if bitvecfunc:\n        return BitVecFunc(\n            raw=nraw, func_name=None, input_=None, annotations=annotations\n        )\n    return BitVec(nraw, annotations)",
    "docstring": "Create a concatenation expression.\n\n    :param args:\n    :return:"
  },
  {
    "code": "def remove(self, container, instances=None, map_name=None, **kwargs):\n        return self.run_actions('remove', container, instances=instances, map_name=map_name, **kwargs)",
    "docstring": "Remove instances from a container configuration.\n\n        :param container: Container name.\n        :type container: unicode | str\n        :param instances: Instance names to remove. If not specified, will remove all instances as specified in the\n         configuration (or just one default instance).\n        :type instances: collections.Iterable[unicode | str | NoneType]\n        :param map_name: Container map name. Optional - if not provided the default map is used.\n        :type map_name: unicode | str\n        :param kwargs: Additional kwargs. If multiple actions are resulting from this, they will only be applied to\n          the main container removal.\n        :return: Return values of removed containers.\n        :rtype: list[dockermap.map.runner.ActionOutput]"
  },
  {
    "code": "def decode(self, value, value_type):\n        if value_type == 'i':\n            return int(value)\n        if value_type == 'z':\n            value = zlib.decompress(value)\n            value_type = 'p'\n        if value_type == 'p':\n            return pickle.loads(force_bytes(value))\n        raise ValueError(\n            \"Unknown value_type '{}' read from the cache table.\"\n            .format(value_type),\n        )",
    "docstring": "Take a value blob and its value_type one-char code and convert it back\n        to a python object"
  },
  {
    "code": "def validate_required(self, value):\n        if self.required and (value is None or value==''):\n            raise MissingFieldError(self.name)",
    "docstring": "Validates the given value agains this field's 'required' property"
  },
  {
    "code": "def new_worker(self, name: str):\n        if not self.running:\n            return self.immediate_worker\n        worker = self._new_worker(name)\n        self._start_worker(worker)\n        return worker",
    "docstring": "Creates a new Worker and start a new Thread with it. Returns the Worker."
  },
  {
    "code": "def create_module(clear_target, target):\n    if os.path.exists(target):\n        if clear_target:\n            shutil.rmtree(target)\n        else:\n            log(\"Target exists! Use --clear to delete it first.\",\n                emitter='MANAGE')\n            sys.exit(2)\n    done = False\n    info = None\n    while not done:\n        info = _ask_questionnaire()\n        pprint(info)\n        done = _ask('Is the above correct', default='y', data_type='bool')\n    augmented_info = _augment_info(info)\n    log(\"Constructing module %(plugin_name)s\" % info)\n    _construct_module(augmented_info, target)",
    "docstring": "Creates a new template HFOS plugin module"
  },
  {
    "code": "def _lambda_add_s3_event_source(awsclient, arn, event, bucket, prefix,\n                                suffix):\n    json_data = {\n        'LambdaFunctionConfigurations': [{\n            'LambdaFunctionArn': arn,\n            'Id': str(uuid.uuid1()),\n            'Events': [event]\n        }]\n    }\n    filter_rules = build_filter_rules(prefix, suffix)\n    json_data['LambdaFunctionConfigurations'][0].update({\n        'Filter': {\n            'Key': {\n                'FilterRules': filter_rules\n            }\n        }\n    })\n    client_s3 = awsclient.get_client('s3')\n    bucket_configurations = client_s3.get_bucket_notification_configuration(\n        Bucket=bucket)\n    bucket_configurations.pop('ResponseMetadata')\n    if 'LambdaFunctionConfigurations' in bucket_configurations:\n        bucket_configurations['LambdaFunctionConfigurations'].append(\n            json_data['LambdaFunctionConfigurations'][0]\n        )\n    else:\n        bucket_configurations['LambdaFunctionConfigurations'] = json_data[\n            'LambdaFunctionConfigurations']\n    response = client_s3.put_bucket_notification_configuration(\n        Bucket=bucket,\n        NotificationConfiguration=bucket_configurations\n    )\n    return json2table(response)",
    "docstring": "Use only prefix OR suffix\n\n    :param arn:\n    :param event:\n    :param bucket:\n    :param prefix:\n    :param suffix:\n    :return:"
  },
  {
    "code": "def get_init(self):\n        suffix = self._separator + \"%s\" % str(self._counter_init)\n        return self._base_name + suffix",
    "docstring": "Return initial name."
  },
  {
    "code": "def app_to_object(self):\n        if self.tagClass != Tag.applicationTagClass:\n            raise ValueError(\"application tag required\")\n        klass = self._app_tag_class[self.tagNumber]\n        if not klass:\n            return None\n        return klass(self)",
    "docstring": "Return the application object encoded by the tag."
  },
  {
    "code": "def markdownify(markdown_content):\n    try:\n        return markdown.markdown(\n            markdown_content,\n            safe_mode=MARTOR_MARKDOWN_SAFE_MODE,\n            extensions=MARTOR_MARKDOWN_EXTENSIONS,\n            extension_configs=MARTOR_MARKDOWN_EXTENSION_CONFIGS\n        )\n    except Exception:\n        raise VersionNotCompatible(\"The markdown isn't compatible, please reinstall \"\n                                   \"your python markdown into Markdown>=3.0\")",
    "docstring": "Render the markdown content to HTML.\n\n    Basic:\n        >>> from martor.utils import markdownify\n        >>> content = \"![awesome](http://i.imgur.com/hvguiSn.jpg)\"\n        >>> markdownify(content)\n        '<p><img alt=\"awesome\" src=\"http://i.imgur.com/hvguiSn.jpg\" /></p>'\n        >>>"
  },
  {
    "code": "def _set_logger(self):\n        self.logger.propagate = False\n        hdl = logging.StreamHandler()\n        fmt_str = '[querier][%(levelname)s] %(message)s'\n        hdl.setFormatter(logging.Formatter(fmt_str))\n        self.logger.addHandler(hdl)",
    "docstring": "change log format."
  },
  {
    "code": "def process(self):\n    if not self.timesketch_api.session:\n      message = 'Could not connect to Timesketch server'\n      self.state.add_error(message, critical=True)\n    named_timelines = []\n    for description, path in self.state.input:\n      if not description:\n        description = 'untitled timeline for '+path\n      named_timelines.append((description, path))\n    try:\n      self.timesketch_api.export_artifacts(named_timelines, self.sketch_id)\n    except RuntimeError as e:\n      self.state.add_error(\n          'Error occurred while working with Timesketch: {0:s}'.format(str(e)),\n          critical=True)\n      return\n    sketch_url = self.timesketch_api.get_sketch_url(self.sketch_id)\n    print('Your Timesketch URL is: {0:s}'.format(sketch_url))\n    self.state.output = sketch_url",
    "docstring": "Executes a Timesketch export."
  },
  {
    "code": "def Import(context, request):\n    errors = []\n    logs = []\n    logs.append(\"Generic XML Import is not available\")\n    results = {'errors': errors, 'log': logs}\n    return json.dumps(results)",
    "docstring": "Read analysis results from an XML string"
  },
  {
    "code": "async def jsk_vc_join(self, ctx: commands.Context, *,\n                          destination: typing.Union[discord.VoiceChannel, discord.Member] = None):\n        destination = destination or ctx.author\n        if isinstance(destination, discord.Member):\n            if destination.voice and destination.voice.channel:\n                destination = destination.voice.channel\n            else:\n                return await ctx.send(\"Member has no voice channel.\")\n        voice = ctx.guild.voice_client\n        if voice:\n            await voice.move_to(destination)\n        else:\n            await destination.connect(reconnect=True)\n        await ctx.send(f\"Connected to {destination.name}.\")",
    "docstring": "Joins a voice channel, or moves to it if already connected.\n\n        Passing a voice channel uses that voice channel.\n        Passing a member will use that member's current voice channel.\n        Passing nothing will use the author's voice channel."
  },
  {
    "code": "def check_layout_json(self):\n        layout_json_file = 'layout.json'\n        if self.layout_json_schema is None or not os.path.isfile(layout_json_file):\n            return\n        error = None\n        status = True\n        try:\n            with open(layout_json_file) as fh:\n                data = json.loads(fh.read())\n            validate(data, self.layout_json_schema)\n        except SchemaError as e:\n            status = False\n            error = e\n        except ValidationError as e:\n            status = False\n            error = e.message\n        except ValueError:\n            return\n        self.validation_data['schema'].append({'filename': layout_json_file, 'status': status})\n        if error:\n            self.validation_data['errors'].append(\n                'Schema validation failed for {} ({}).'.format(layout_json_file, error)\n            )\n        else:\n            self.check_layout_params()",
    "docstring": "Check all layout.json files for valid schema."
  },
  {
    "code": "async def throttle_update_all_heaters(self):\n        if (self._throttle_all_time is not None\n                and dt.datetime.now() - self._throttle_all_time\n                < MIN_TIME_BETWEEN_UPDATES):\n            return\n        self._throttle_all_time = dt.datetime.now()\n        await self.find_all_heaters()",
    "docstring": "Throttle update all devices and rooms."
  },
  {
    "code": "def _set_extensions(self):\n        self._critical_extensions = set()\n        for extension in self['single_extensions']:\n            name = extension['extn_id'].native\n            attribute_name = '_%s_value' % name\n            if hasattr(self, attribute_name):\n                setattr(self, attribute_name, extension['extn_value'].parsed)\n            if extension['critical'].native:\n                self._critical_extensions.add(name)\n        self._processed_extensions = True",
    "docstring": "Sets common named extensions to private attributes and creates a list\n        of critical extensions"
  },
  {
    "code": "def on_action_end(self, action, logs={}):\n        for callback in self.callbacks:\n            if callable(getattr(callback, 'on_action_end', None)):\n                callback.on_action_end(action, logs=logs)",
    "docstring": "Called at end of each action for each callback in callbackList"
  },
  {
    "code": "def V(x, requires_grad=False, volatile=False):\n    return map_over(x, lambda o: V_(o, requires_grad, volatile))",
    "docstring": "creates a single or a list of pytorch tensors, depending on input x."
  },
  {
    "code": "def choose_type(cls, content_type):\n        return cls.type_cls.SUBDIR if content_type in cls.subdir_types \\\n            else cls.type_cls.FILE",
    "docstring": "Choose object type from content type."
  },
  {
    "code": "def pkg_not_found(self, bol, pkg, message, eol):\n        print(\"{0}No such package {1}: {2}{3}\".format(bol, pkg, message, eol))",
    "docstring": "Print message when package not found"
  },
  {
    "code": "def get_state_actions(self, state, **kwargs):\n        config_type = state.config_id.config_type\n        if config_type == ItemType.CONTAINER:\n            extra_data = kwargs\n        else:\n            extra_data = None\n        if state.base_state == State.PRESENT:\n            if ((config_type == ItemType.VOLUME and self.remove_attached) or\n                    (config_type == ItemType.CONTAINER and\n                     self.remove_persistent or not state.state_flags & StateFlags.PERSISTENT)):\n                return [ItemAction(state, Action.REMOVE, extra_data=extra_data)]\n            elif config_type == ItemType.NETWORK:\n                connected_containers = state.extra_data.get('containers')\n                if connected_containers:\n                    actions = [ItemAction(state, NetworkUtilAction.DISCONNECT_ALL, {'containers': connected_containers})]\n                else:\n                    actions = []\n                actions.append(ItemAction(state, Action.REMOVE, extra_data=kwargs))\n                return actions",
    "docstring": "Removes containers that are stopped. Optionally skips persistent containers. Attached containers are skipped\n        by default from removal but can optionally be included.\n\n        :param state: Configuration state.\n        :type state: dockermap.map.state.ConfigState\n        :param kwargs: Additional keyword arguments.\n        :return: Actions on the client, map, and configurations.\n        :rtype: list[dockermap.map.action.ItemAction]"
  },
  {
    "code": "def parse_text_block(text: str) -> Tuple[str, str]:\n    body, footer = '', ''\n    if text:\n        body = text.split('\\n\\n')[0]\n        if len(text.split('\\n\\n')) == 2:\n            footer = text.split('\\n\\n')[1]\n    return body.replace('\\n', ' '), footer.replace('\\n', ' ')",
    "docstring": "This will take a text block and return a tuple with body and footer,\n    where footer is defined as the last paragraph.\n\n    :param text: The text string to be divided.\n    :return: A tuple with body and footer,\n    where footer is defined as the last paragraph."
  },
  {
    "code": "def bsp_new_with_size(x: int, y: int, w: int, h: int) -> tcod.bsp.BSP:\n    return Bsp(x, y, w, h)",
    "docstring": "Create a new BSP instance with the given rectangle.\n\n    Args:\n        x (int): Rectangle left coordinate.\n        y (int): Rectangle top coordinate.\n        w (int): Rectangle width.\n        h (int): Rectangle height.\n\n    Returns:\n        BSP: A new BSP instance.\n\n    .. deprecated:: 2.0\n       Call the :any:`BSP` class instead."
  },
  {
    "code": "def pack(self, value=None):\n        if value is None:\n            output = self.header.pack()\n            output += self.value.pack()\n            return output\n        elif isinstance(value, type(self)):\n            return value.pack()\n        else:\n            msg = \"{} is not an instance of {}\".format(value,\n                                                       type(self).__name__)\n            raise PackException(msg)",
    "docstring": "Pack the TLV in a binary representation.\n\n        Returns:\n            bytes: Binary representation of the struct object.\n\n        Raises:\n            :exc:`~.exceptions.ValidationError`: If validation fails."
  },
  {
    "code": "def restore_sampler_state(self):\n        state = self.db.getstate() or {}\n        sampler_state = state.get('sampler', {})\n        self.__dict__.update(sampler_state)\n        stoch_state = state.get('stochastics', {})\n        for sm in self.stochastics:\n            try:\n                sm.value = stoch_state[sm.__name__]\n            except:\n                warnings.warn(\n                    'Failed to restore state of stochastic %s from %s backend' %\n                    (sm.__name__, self.db.__name__))",
    "docstring": "Restore the state of the sampler and to\n        the state stored in the database."
  },
  {
    "code": "def __prepare_dataset_parameter(self, dataset):\n        if not isinstance(dataset, _SFrame):\n            def raise_dataset_type_exception():\n                raise TypeError(\"The dataset parameter must be either an SFrame, \"\n                                \"or a dictionary of (str : list) or (str : value).\")\n            if type(dataset) is dict:\n                if not all(type(k) is str for k in _six.iterkeys(dataset)):\n                    raise_dataset_type_exception()\n                if all(type(v) in (list, tuple, _array.array) for v in _six.itervalues(dataset)):\n                    dataset = _SFrame(dataset)\n                else:\n                    dataset = _SFrame({k : [v] for k, v in _six.iteritems(dataset)})\n            else:\n                raise_dataset_type_exception()\n        return dataset",
    "docstring": "Processes the dataset parameter for type correctness.\n        Returns it as an SFrame."
  },
  {
    "code": "def _add_members(self, catmembers):\n        members = [x for x in catmembers if x['ns'] == 0]\n        subcats = [x for x in catmembers if x['ns'] == 14]\n        if 'members' in self.data:\n            self.data['members'].extend(members)\n        else:\n            self.data.update({'members': members})\n        if subcats:\n            if 'subcategories' in self.data:\n                self.data['subcategories'].extend(subcats)\n            else:\n                self.data.update({'subcategories': subcats})",
    "docstring": "Adds category members and subcategories to data"
  },
  {
    "code": "def get_provides(self, ignored=tuple()):\n        if self._provides is None:\n            self._collect_requires_provides()\n        d = self._provides\n        if ignored:\n            d = dict((k, v) for k, v in d.items()\n                     if not fnmatches(k, *ignored))\n        return d",
    "docstring": "a map of provided classes and class members, and what\n        provides them. ignored is an optional list of globbed patterns\n        indicating packages, classes, etc that shouldn't be included\n        in the provides map"
  },
  {
    "code": "def __execute_bsh(self, instr):\n        op0_val = self.read_operand(instr.operands[0])\n        op1_val = self.read_operand(instr.operands[1])\n        op1_size = instr.operands[1].size\n        if extract_sign_bit(op1_val, op1_size) == 0:\n            op2_val = op0_val << op1_val\n        else:\n            op2_val = op0_val >> twos_complement(op1_val, op1_size)\n        self.write_operand(instr.operands[2], op2_val)\n        return None",
    "docstring": "Execute BSH instruction."
  },
  {
    "code": "def reduce(self, func, *initial):\n        if len(initial) == 0:\n            return _wrap(reduce(func, self))\n        elif len(initial) == 1:\n            return _wrap(reduce(func, self, initial[0]))\n        else:\n            raise ValueError('reduce takes exactly one optional parameter for initial value')",
    "docstring": "Reduce sequence of elements using func. API mirrors functools.reduce\n\n        >>> seq([1, 2, 3]).reduce(lambda x, y: x + y)\n        6\n\n        :param func: two parameter, associative reduce function\n        :param initial: single optional argument acting as initial value\n        :return: reduced value using func"
  },
  {
    "code": "def import_numpy():\n    try:\n        imp.find_module('numpy')\n        numpy_exists = True\n    except ImportError:\n        numpy_exists = False\n    if numpy_exists:\n        import numpy as np\n    else:\n        np = None\n    return np",
    "docstring": "Returns the numpy module if it exists on the system,\n    otherwise returns None."
  },
  {
    "code": "def parse_for(self):\n        lineno = self.stream.expect('name:for').lineno\n        target = self.parse_assign_target(extra_end_rules=('name:in',))\n        self.stream.expect('name:in')\n        iter = self.parse_tuple(with_condexpr=False,\n                                extra_end_rules=('name:recursive',))\n        test = None\n        if self.stream.skip_if('name:if'):\n            test = self.parse_expression()\n        recursive = self.stream.skip_if('name:recursive')\n        body = self.parse_statements(('name:endfor', 'name:else'))\n        if next(self.stream).value == 'endfor':\n            else_ = []\n        else:\n            else_ = self.parse_statements(('name:endfor',), drop_needle=True)\n        return nodes.For(target, iter, body, else_, test,\n                         recursive, lineno=lineno)",
    "docstring": "Parse a for loop."
  },
  {
    "code": "def prog(self):\n        if not self._prog:\n            self._prog = self._parser.prog\n        return self._prog",
    "docstring": "Program name."
  },
  {
    "code": "def init_ui(self, ):\n        self.mm = MenuManager.get()\n        p = self.mm.menus['Jukebox']\n        self.menu = self.mm.create_menu(\"Preferences\", p, command=self.run)",
    "docstring": "Create the menu \\\"Preferences\\\" under \\\"Jukebox\\\" to start the plugin\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def team_profiles(self, team):\n        return [Profile(raw) for raw in self._get('team/%s/social_media' % self.team_key(team))]",
    "docstring": "Get team's social media profiles linked on their TBA page.\n\n        :param team: Team to get data on.\n        :return: List of Profile objects."
  },
  {
    "code": "def clean(self, argslist):\n        result = []\n        for arg in argslist:\n            if type(arg) == type([]):\n                if len(result) > 0:\n                    result[-1] = result[-1] + \"(*{})\".format(len(self.clean(arg)))\n                elif \"/\" not in arg[0]:\n                    msg.warn(\"argument to function call unrecognized. {}\".format(arg))\n            else:\n                cleaner = re.sub(\"[:,]+\", \"\", arg).strip()\n                if len(cleaner) > 0:\n                    result.append(cleaner)\n        return result",
    "docstring": "Cleans the argslist."
  },
  {
    "code": "def update(cls, **kwargs):\n        q = cls._get_instance(**{'id': kwargs['id']})\n        if q:\n            for k, v in kwargs.items():\n                setattr(q, k, v)\n            _action_and_commit(q, session.add)\n        else:\n            cls.get_or_create(**kwargs)",
    "docstring": "If a record matching the instance id already exists in the database, \n        update it. If a record matching the instance id does not already exist,\n        create a new record."
  },
  {
    "code": "def extract_length(self, lower_bound=None, upper_bound=None, new_path=None):\n        if new_path is None: fraction = self.__class__(new_temp_path())\n        elif isinstance(new_path, FASTA): fraction = new_path\n        else:                fraction = self.__class__(new_path)\n        if lower_bound is None: lower_bound = 0\n        if upper_bound is None: upper_bound = sys.maxint\n        def fraction_iterator():\n            for read in self:\n                if lower_bound <= len(read) <= upper_bound:\n                    yield read\n        fraction.write(fraction_iterator())\n        fraction.close()\n        return fraction",
    "docstring": "Extract a certain length fraction and place them in a new file."
  },
  {
    "code": "def build(self):\n\t\tif self._clf is None:\n\t\t\traise NeedToTrainExceptionBeforeDeployingException()\n\t\treturn DeployedClassifier(self._category,\n\t\t                          self._term_doc_matrix._category_idx_store,\n\t\t                          self._term_doc_matrix._term_idx_store,\n\t\t                          self._term_doc_matrix_factory)",
    "docstring": "Builds Depoyed Classifier"
  },
  {
    "code": "def holtWintersConfidenceArea(requestContext, seriesList, delta=3):\n    bands = holtWintersConfidenceBands(requestContext, seriesList, delta)\n    results = areaBetween(requestContext, bands)\n    for series in results:\n        series.name = series.name.replace('areaBetween',\n                                          'holtWintersConfidenceArea')\n    return results",
    "docstring": "Performs a Holt-Winters forecast using the series as input data and plots\n    the area between the upper and lower bands of the predicted forecast\n    deviations."
  },
  {
    "code": "def _migrate(data: Mapping[str, Any]) -> SettingsData:\n    next = dict(data)\n    version = next.pop('_version', 0)\n    target_version = len(_MIGRATIONS)\n    migrations = _MIGRATIONS[version:]\n    if len(migrations) > 0:\n        log.info(\n            \"Migrating advanced settings from version {} to {}\"\n            .format(version, target_version))\n    for m in migrations:\n        next = m(next)\n    return next, target_version",
    "docstring": "Check the version integer of the JSON file data a run any necessary\n    migrations to get us to the latest file format. Returns dictionary of\n    settings and version migrated to"
  },
  {
    "code": "def accuracy_helper(egg, match='exact', distance='euclidean',\n                    features=None):\n    def acc(lst):\n        return len([i for i in np.unique(lst) if i>=0])/(egg.list_length)\n    opts = dict(match=match, distance=distance, features=features)\n    if match is 'exact':\n        opts.update({'features' : 'item'})\n    recmat = recall_matrix(egg, **opts)\n    if match in ['exact', 'best']:\n        result = [acc(lst) for lst in recmat]\n    elif match is 'smooth':\n        result = np.mean(recmat, axis=1)\n    else:\n        raise ValueError('Match must be set to exact, best or smooth.')\n    return np.nanmean(result, axis=0)",
    "docstring": "Computes proportion of words recalled\n\n    Parameters\n    ----------\n    egg : quail.Egg\n        Data to analyze\n\n    match : str (exact, best or smooth)\n        Matching approach to compute recall matrix.  If exact, the presented and\n        recalled items must be identical (default).  If best, the recalled item\n        that is most similar to the presented items will be selected. If smooth,\n        a weighted average of all presented items will be used, where the\n        weights are derived from the similarity between the recalled item and\n        each presented item.\n\n    distance : str\n        The distance function used to compare presented and recalled items.\n        Applies only to 'best' and 'smooth' matching approaches.  Can be any\n        distance function supported by numpy.spatial.distance.cdist.\n\n    Returns\n    ----------\n    prop_recalled : numpy array\n      proportion of words recalled"
  },
  {
    "code": "def merge(self, *args):\n        for data in args:\n            if isinstance(data, str):\n                to_merge = load_string(data, self.context)\n                if not to_merge:\n                    continue\n            else:\n                to_merge = data\n            if not self.can_merge(to_merge):\n                raise TypeError(\n                    'Cannot merge myself:%s with %s. data: %s' \\\n                    % (type(self), type(data), data)\n                )\n            self._merge(to_merge)",
    "docstring": "Merges this instance with new instances, in-place.\n\n        :param \\\\*args: Configuration values to merge with current instance.\n        :type \\\\*args: iterable"
  },
  {
    "code": "def _connect_temporarily(self, port_v, target=True):\n        if target:\n            handle = self._connection_v.to_handle()\n        else:\n            handle = self._connection_v.from_handle()\n        port_v.add_connected_handle(handle, self._connection_v, moving=True)\n        port_v.tmp_connect(handle, self._connection_v)\n        self._connection_v.set_port_for_handle(port_v, handle)\n        self._redraw_port(port_v)",
    "docstring": "Set a connection between the current connection and the given port\n\n        :param rafcon.gui.mygaphas.items.ports.PortView port_v: The port to be connected\n        :param bool target: Whether the connection origin or target should be connected"
  },
  {
    "code": "def read(self, file):\n        content = self._read_content(file)\n        self._validate(content)\n        self._parse(content)\n        return self",
    "docstring": "Reads the captions file."
  },
  {
    "code": "def set_trace(self, frame=None):\n        if hasattr(local, '_pdbpp_completing'):\n            return\n        if frame is None:\n            frame = sys._getframe().f_back\n        self._via_set_trace_frame = frame\n        return super(Pdb, self).set_trace(frame)",
    "docstring": "Remember starting frame.\n\n        This is used with pytest, which does not use pdb.set_trace()."
  },
  {
    "code": "def get_labels(input_dir):\n  data_dir = _get_latest_data_dir(input_dir)\n  labels_file = os.path.join(data_dir, 'labels')\n  with file_io.FileIO(labels_file, 'r') as f:\n    labels = f.read().rstrip().split('\\n')\n  return labels",
    "docstring": "Get a list of labels from preprocessed output dir."
  },
  {
    "code": "def set_high_water_mark(socket, config):\n    if config['high_water_mark']:\n        if hasattr(zmq, 'HWM'):\n            socket.setsockopt(zmq.HWM, config['high_water_mark'])\n        else:\n            socket.setsockopt(zmq.SNDHWM, config['high_water_mark'])\n            socket.setsockopt(zmq.RCVHWM, config['high_water_mark'])",
    "docstring": "Set a high water mark on the zmq socket.  Do so in a way that is\n    cross-compatible with zeromq2 and zeromq3."
  },
  {
    "code": "def coords_intersect(self):\n        return set.intersection(*map(\n            set, (getattr(arr, 'coords_intersect', arr.coords) for arr in self)\n            ))",
    "docstring": "Coordinates of the arrays in this list that are used in all arrays"
  },
  {
    "code": "def provide_label(self):\n        return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.label]",
    "docstring": "The name and shape of label provided by this iterator"
  },
  {
    "code": "def cli_reload(self, event):\n        self.log('Reloading all components.')\n        self.update_components(forcereload=True)\n        initialize()\n        from hfos.debugger import cli_compgraph\n        self.fireEvent(cli_compgraph())",
    "docstring": "Experimental call to reload the component tree"
  },
  {
    "code": "def get_records_with_attachments(attachment_table, rel_object_field=\"REL_OBJECTID\"):\n    if arcpyFound == False:\n        raise Exception(\"ArcPy is required to use this function\")\n    OIDs = []\n    with arcpy.da.SearchCursor(attachment_table,\n                               [rel_object_field]) as rows:\n        for row in rows:\n            if not str(row[0]) in OIDs:\n                OIDs.append(\"%s\" % str(row[0]))\n            del row\n    del rows\n    return OIDs",
    "docstring": "returns a list of ObjectIDs for rows in the attachment table"
  },
  {
    "code": "def create_objective_bank(self, *args, **kwargs):\n        return ObjectiveBank(\n            self._provider_manager,\n            self._get_provider_session('objective_bank_admin_session').create_objective_bank(*args, **kwargs),\n            self._runtime,\n            self._proxy)",
    "docstring": "Pass through to provider ObjectiveBankAdminSession.create_objective_bank"
  },
  {
    "code": "def iterintervals(self, n=2):\n        streams = tee(iter(self), n)\n        for stream_index, stream in enumerate(streams):\n            for i in range(stream_index):\n                next(stream)\n        for intervals in zip(*streams):\n            yield intervals",
    "docstring": "Iterate over groups of `n` consecutive measurement points in the\n        time series."
  },
  {
    "code": "def filter_create(self, phrase, context, irreversible = False, whole_word = True, expires_in = None):\n        params = self.__generate_params(locals())\n        for context_val in context:\n            if not context_val in ['home', 'notifications', 'public', 'thread']:\n                raise MastodonIllegalArgumentError('Invalid filter context.')\n        return self.__api_request('POST', '/api/v1/filters', params)",
    "docstring": "Creates a new keyword filter. `phrase` is the phrase that should be\n        filtered out, `context` specifies from where to filter the keywords.\n        Valid contexts are 'home', 'notifications', 'public' and 'thread'.\n        \n        Set `irreversible` to True if you want the filter to just delete statuses\n        server side. This works only for the 'home' and 'notifications' contexts.\n        \n        Set `whole_word` to False if you want to allow filter matches to\n        start or end within a word, not only at word boundaries.\n        \n        Set `expires_in` to specify for how many seconds the filter should be\n        kept around.\n        \n        Returns the `filter dict`_ of the newly created filter."
  },
  {
    "code": "def parse(self, type, data):\n        try:\n            return self.registered_formats[type]['parser'](data)\n        except KeyError:\n            raise NotImplementedError(\"No parser found for \"\n                                      \"type '{type}'\".format(type=type))",
    "docstring": "Parse text as a format.\n\n        :param type: The unique name of the format\n        :param data: The text to parse as the format"
  },
  {
    "code": "def add_view(self, *args, **kwargs):\n        try:\n            singleton = self.model.objects.get()\n        except (self.model.DoesNotExist, self.model.MultipleObjectsReturned):\n            kwargs.setdefault(\"extra_context\", {})\n            kwargs[\"extra_context\"][\"singleton\"] = True\n            response = super(SingletonAdmin, self).add_view(*args, **kwargs)\n            return self.handle_save(args[0], response)\n        return redirect(admin_url(self.model, \"change\", singleton.id))",
    "docstring": "Redirect to the change view if the singleton instance exists."
  },
  {
    "code": "def imageFields(self):\n        if self._imageFields is None:\n            ctx = SparkContext._active_spark_context\n            self._imageFields = list(ctx._jvm.org.apache.spark.ml.image.ImageSchema.imageFields())\n        return self._imageFields",
    "docstring": "Returns field names of image columns.\n\n        :return: a list of field names.\n\n        .. versionadded:: 2.3.0"
  },
  {
    "code": "def get_tensor_num_entries(self, tensor_name, partial_layout=None,\n                             mesh_dimension_to_size=None):\n    shape = self.get_tensor_shape(tensor_name)\n    num_entries = 1\n    for dim in shape.dims:\n      num_entries = num_entries * dim.value\n    if not partial_layout:\n      return num_entries\n    for mtf_dimension_name in self.get_tensor_mtf_dimension_names(tensor_name):\n      if mtf_dimension_name not in partial_layout:\n        continue\n      mesh_dimension_name = partial_layout[mtf_dimension_name]\n      mesh_dimension_size = mesh_dimension_to_size[mesh_dimension_name]\n      num_entries = int(math.ceil(num_entries / mesh_dimension_size))\n    return num_entries",
    "docstring": "The number of entries in a tensor.\n\n    If partial_layout is specified, then mesh_dimension_to_size must also be. In\n    this case, the number of entries on a single device is returned.\n\n    Args:\n      tensor_name: a string, name of a tensor in the graph.\n      partial_layout: an optional {string: string}, from MTF dimension name to\n          mesh dimension name.\n      mesh_dimension_to_size: an optional {string: int}, from mesh dimension\n          name to size.\n\n    Returns:\n      an integer"
  },
  {
    "code": "def _get_folds(n_rows, n_folds, use_stored):\n        if use_stored is not None:\n            with open(os.path.expanduser(use_stored)) as json_file:\n                json_data = json.load(json_file)\n            if json_data['N_rows'] != n_rows:\n                raise Exception('N_rows from folds doesnt match the number of rows of X_seq, X_feat, y')\n            if json_data['N_folds'] != n_folds:\n                raise Exception('n_folds dont match', json_data['N_folds'], n_folds)\n            kf = [(np.array(train), np.array(test)) for (train, test) in json_data['folds']]\n        else:\n            kf = KFold(n_splits=n_folds).split(np.zeros((n_rows, 1)))\n        i = 1\n        folds = []\n        for train, test in kf:\n            fold = \"fold_\" + str(i)\n            folds.append((fold, train, test))\n            i = i + 1\n        return folds",
    "docstring": "Get the used CV folds"
  },
  {
    "code": "def cpu_count(logical=True):\n    if logical:\n        from multiprocessing import cpu_count\n        ncpu=cpu_count()\n    else:\n        import psutil\n        ncpu=psutil.cpu_count(logical=False)\n    return ncpu",
    "docstring": "Return system CPU count"
  },
  {
    "code": "def set_codes(self, codes, reject=False):\n        self.codes = set(codes)\n        self.reject = reject",
    "docstring": "Set the accepted or rejected codes codes list.\n\n        :param codes: A list of the response codes.\n        :param reject: If True, the listed codes will be rejected, and\n                       the conversion will format as \"-\"; if False,\n                       only the listed codes will be accepted, and the\n                       conversion will format as \"-\" for all the\n                       others."
  },
  {
    "code": "def initialize_unbounded(obj, dimensions, key):\n    select = dict(zip([d.name for d in dimensions], key))\n    try:\n        obj.select([DynamicMap], **select)\n    except KeyError:\n        pass",
    "docstring": "Initializes any DynamicMaps in unbounded mode."
  },
  {
    "code": "def runcmds_plus_hooks(self, cmds: List[str]) -> bool:\n        stop = False\n        self.cmdqueue = list(cmds) + self.cmdqueue\n        try:\n            while self.cmdqueue and not stop:\n                line = self.cmdqueue.pop(0)\n                if self.echo and line != 'eos':\n                    self.poutput('{}{}'.format(self.prompt, line))\n                stop = self.onecmd_plus_hooks(line)\n        finally:\n            self.cmdqueue = []\n            self._script_dir = []\n            return stop",
    "docstring": "Convenience method to run multiple commands by onecmd_plus_hooks.\n\n        This method adds the given cmds to the command queue and processes the\n        queue until completion or an error causes it to abort. Scripts that are\n        loaded will have their commands added to the queue. Scripts may even\n        load other scripts recursively. This means, however, that you should not\n        use this method if there is a running cmdloop or some other event-loop.\n        This method is only intended to be used in \"one-off\" scenarios.\n\n        NOTE: You may need this method even if you only have one command. If\n        that command is a load, then you will need this command to fully process\n        all the subsequent commands that are loaded from the script file. This\n        is an improvement over onecmd_plus_hooks, which expects to be used\n        inside of a command loop which does the processing of loaded commands.\n\n        Example: cmd_obj.runcmds_plus_hooks(['load myscript.txt'])\n\n        :param cmds: command strings suitable for onecmd_plus_hooks.\n        :return: True implies the entire application should exit."
  },
  {
    "code": "def args(self):\n        return (self.base, self.item, self.leng, self.refs,\n                self.both, self.kind, self.type)",
    "docstring": "Return all attributes as arguments tuple."
  },
  {
    "code": "def energy_upperbound(self, spins):\n        subtheta = self.theta.copy()\n        subtheta.fix_variables(spins)\n        trees = self._trees\n        if not trees:\n            assert not subtheta.linear and not subtheta.quadratic\n            return subtheta.offset\n        energy = Plus(self.message_upperbound(trees, {}, subtheta), subtheta.offset)\n        return energy",
    "docstring": "A formula for an upper bound on the energy of Theta with spins fixed.\n\n        Args:\n            spins (dict): Spin values for a subset of the variables in Theta.\n\n        Returns:\n            Formula that upper bounds the energy with spins fixed."
  },
  {
    "code": "def load_emacs_open_in_editor_bindings():\n    registry = Registry()\n    registry.add_binding(Keys.ControlX, Keys.ControlE,\n                         filter=EmacsMode() & ~HasSelection())(\n         get_by_name('edit-and-execute-command'))\n    return registry",
    "docstring": "Pressing C-X C-E will open the buffer in an external editor."
  },
  {
    "code": "def sync_focus(self, *_):\n        if self.display_popup:\n            self.app.layout.focus(self.layout_manager.popup_dialog)\n            return\n        if self.confirm_text:\n            return\n        if self.prompt_command:\n            return\n        if self.command_mode:\n            return\n        if not self.pymux.arrangement.windows:\n            return\n        pane = self.pymux.arrangement.get_active_pane()\n        self.app.layout.focus(pane.terminal)",
    "docstring": "Focus the focused window from the pymux arrangement."
  },
  {
    "code": "def describe_db_subnet_groups(name=None, filters=None, jmespath='DBSubnetGroups',\n                              region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    pag = conn.get_paginator('describe_db_subnet_groups')\n    args = {}\n    args.update({'DBSubnetGroupName': name}) if name else None\n    args.update({'Filters': filters}) if filters else None\n    pit = pag.paginate(**args)\n    pit = pit.search(jmespath) if jmespath else pit\n    return [p for p in pit]",
    "docstring": "Return a detailed listing of some, or all, DB Subnet Groups visible in the\n    current scope.  Arbitrary subelements or subsections of the returned dataset\n    can be selected by passing in a valid JMSEPath filter as well.\n\n    CLI example::\n\n        salt myminion boto_rds.describe_db_subnet_groups"
  },
  {
    "code": "def get_link(self, task_id):\n        links = [x for x in self.links if x.task_id == task_id]\n        if len(links) != 1:\n            raise CoTError(\"No single Link matches task_id {}!\\n{}\".format(task_id, self.dependent_task_ids()))\n        return links[0]",
    "docstring": "Get a ``LinkOfTrust`` by task id.\n\n        Args:\n            task_id (str): the task id to find.\n\n        Returns:\n            LinkOfTrust: the link matching the task id.\n\n        Raises:\n            CoTError: if no ``LinkOfTrust`` matches."
  },
  {
    "code": "def is_ready(self):\n        response = self.get()\n        if response.status == 204:\n            return False\n        self._state = self.read(response)\n        ready = self._state.content['dispatchState'] not in ['QUEUED', 'PARSING']\n        return ready",
    "docstring": "Indicates whether this job is ready for querying.\n\n        :return: ``True`` if the job is ready, ``False`` if not.\n        :rtype: ``boolean``"
  },
  {
    "code": "def to_trip(\n            self,\n            smooth,\n            smooth_strategy,\n            smooth_noise,\n            seg,\n            seg_eps,\n            seg_min_time,\n            simplify,\n            simplify_max_dist_error,\n            simplify_max_speed_error\n        ):\n        self.compute_metrics()\n        self.remove_noise()\n        print (smooth, seg, simplify)\n        if smooth:\n            self.compute_metrics()\n            self.smooth(smooth_strategy, smooth_noise)\n        if seg:\n            self.compute_metrics()\n            self.segment(seg_eps, seg_min_time)\n        if simplify:\n            self.compute_metrics()\n            self.simplify(0, simplify_max_dist_error, simplify_max_speed_error)\n        self.compute_metrics()\n        return self",
    "docstring": "In-place, transformation of a track into a trip\n\n        A trip is a more accurate depiction of reality than a\n        track.\n        For a track to become a trip it need to go through the\n        following steps:\n            + noise removal\n            + smoothing\n            + spatio-temporal segmentation\n            + simplification\n        At the end of these steps we have a less noisy, track\n        that has less points, but that holds the same information.\n        It's required that each segment has their metrics calculated\n        or has been preprocessed.\n\n        Args:\n            name: An optional string with the name of the trip. If\n                none is given, one will be generated by generateName\n        Returns:\n            This Track instance"
  },
  {
    "code": "def coerce(value):\n        if isinstance(value, ListCell):\n            return value\n        elif isinstance(value, (list)):\n            return ListCell(value)\n        else:\n            return ListCell([value])",
    "docstring": "Turns a value into a list"
  },
  {
    "code": "def relpath_to_site(lang, target_lang):\n    path = _SITES_RELPATH_DB.get((lang, target_lang), None)\n    if path is None:\n        siteurl = _SITE_DB.get(lang, _MAIN_SITEURL)\n        target_siteurl = _SITE_DB.get(target_lang, _MAIN_SITEURL)\n        path = posixpath.relpath(get_site_path(target_siteurl),\n                                 get_site_path(siteurl))\n        _SITES_RELPATH_DB[(lang, target_lang)] = path\n    return path",
    "docstring": "Get relative path from siteurl of lang to siteurl of base_lang\n\n    the output is cached in _SITES_RELPATH_DB"
  },
  {
    "code": "def command(cls, command, stdin=None, shell=False):\n        if not shell and isinstance(command, str):\n            command = cls.shlex.split(command)\n        collate_original = None\n        try:\n            collate_original = cls.os.environ['LC_ALL']\n        except KeyError:\n            pass\n        cls.os.environ['LC_ALL'] = \"C\"\n        try:\n            process = cls.subprocess.Popen(command,\n                                           stdout=cls.subprocess.PIPE,\n                                           stderr=cls.subprocess.PIPE,\n                                           stdin=cls.subprocess.PIPE,\n                                           shell=shell)\n            (stdout, stderr) = process.communicate(stdin)\n        finally:\n            if collate_original:\n                cls.os.environ['LC_ALL'] = collate_original\n            else:\n                del cls.os.environ['LC_ALL']\n        return cls(stdout, stderr, stdin, process.returncode, command)",
    "docstring": "Runs specified command.\n\n        The command can be fed with data on stdin with parameter ``stdin``.\n        The command can also be treated as a shell command with parameter ``shell``.\n        Please refer to subprocess.Popen on how does this stuff work\n\n        :returns: Run() instance with resulting data"
  },
  {
    "code": "def activate_boost_by_name(self,\n                               zone_name,\n                               target_temperature,\n                               num_hours=1):\n        zone = self.get_zone(zone_name)\n        if zone is None:\n            raise RuntimeError(\"Unknown zone\")\n        return self.activate_boost_by_id(zone[\"zoneId\"],\n                                         target_temperature, num_hours)",
    "docstring": "Activate boost by the name of the zone"
  },
  {
    "code": "def _check_arg_length(fname, args, max_fname_arg_count, compat_args):\n    if max_fname_arg_count < 0:\n        raise ValueError(\"'max_fname_arg_count' must be non-negative\")\n    if len(args) > len(compat_args):\n        max_arg_count = len(compat_args) + max_fname_arg_count\n        actual_arg_count = len(args) + max_fname_arg_count\n        argument = 'argument' if max_arg_count == 1 else 'arguments'\n        raise TypeError(\n            \"{fname}() takes at most {max_arg} {argument} \"\n            \"({given_arg} given)\".format(\n                fname=fname, max_arg=max_arg_count,\n                argument=argument, given_arg=actual_arg_count))",
    "docstring": "Checks whether 'args' has length of at most 'compat_args'. Raises\n    a TypeError if that is not the case, similar to in Python when a\n    function is called with too many arguments."
  },
  {
    "code": "def getPos(position, pagesize):\n    position = str(position).split()\n    if len(position) != 2:\n        raise Exception(\"position not defined right way\")\n    x, y = [getSize(pos) for pos in position]\n    return getCoords(x, y, None, None, pagesize)",
    "docstring": "Pair of coordinates"
  },
  {
    "code": "def run_job(self, job=None):\n        if job is None:\n            if not self.queue:\n                return None\n            job = self.queue.popleft()\n        start = timer()\n        func, args = job\n        reply = func(*args)\n        end = timer()\n        if end - start > 0.1:\n            _LOGGER.debug(\n                'Handle queue with call %s(%s) took %.3f seconds',\n                func, args, end - start)\n        return reply",
    "docstring": "Run a job, either passed in or from the queue.\n\n        A job is a tuple of function and optional args. Keyword arguments\n        can be passed via use of functools.partial. The job should return a\n        string that should be sent by the gateway protocol. The function will\n        be called with the arguments and the result will be returned."
  },
  {
    "code": "def hvenvup(package, directory):\n    pip = Command(DIR.gen.joinpath(\"hvenv\", \"bin\", \"pip\"))\n    pip(\"uninstall\", package, \"-y\").run()\n    pip(\"install\", DIR.project.joinpath(directory).abspath()).run()",
    "docstring": "Install a new version of a package in the hitch venv."
  },
  {
    "code": "def save(self):\n        with open(self.filename, 'w') as plist_file:\n            plist_file.write(str(self.soup))",
    "docstring": "Save current property list representation to the original file."
  },
  {
    "code": "def split(self):\n        self._annotate_groups()\n        index = 0\n        for group in range(self._max_group):\n            subgraph = copy(self)\n            subgraph.metadata = self.metadata[:]\n            subgraph.edges = self.edges.copy()\n            if subgraph._filter_group(group):\n                subgraph.total_size = sum([x.size for x in subgraph.metadata])\n                subgraph.index = index\n                index += 1\n                yield subgraph",
    "docstring": "Split the graph into sub-graphs. Only connected objects belong to the\n        same graph. `split` yields copies of the Graph object. Shallow copies\n        are used that only replicate the meta-information, but share the same\n        object list ``self.objects``.\n\n        >>> from pympler.refgraph import ReferenceGraph\n        >>> a = 42\n        >>> b = 'spam'\n        >>> c = {a: b}\n        >>> t = (1,2,3)\n        >>> rg = ReferenceGraph([a,b,c,t])\n        >>> for subgraph in rg.split():\n        ...   print subgraph.index\n        0\n        1"
  },
  {
    "code": "def delete_row(self, index):\n        body = {\n            \"requests\": [{\n                \"deleteDimension\": {\n                    \"range\": {\n                      \"sheetId\": self.id,\n                      \"dimension\": \"ROWS\",\n                      \"startIndex\": index - 1,\n                      \"endIndex\": index\n                    }\n                }\n            }]\n        }\n        return self.spreadsheet.batch_update(body)",
    "docstring": "Deletes the row from the worksheet at the specified index.\n\n        :param index: Index of a row for deletion.\n        :type index: int"
  },
  {
    "code": "def get_other_keys(self, key, including_current=False):\r\n        other_keys = []\r\n        if key in self:\r\n            other_keys.extend(self.__dict__[str(type(key))][key])\r\n            if not including_current:\r\n                other_keys.remove(key)\r\n        return other_keys",
    "docstring": "Returns list of other keys that are mapped to the same value as specified key. \r\n            @param key - key for which other keys should be returned.\r\n            @param including_current if set to True - key will also appear on this list."
  },
  {
    "code": "def get_secret_registration_block_by_secrethash(\n            self,\n            secrethash: SecretHash,\n            block_identifier: BlockSpecification,\n    ) -> Optional[BlockNumber]:\n        result = self.proxy.contract.functions.getSecretRevealBlockHeight(\n            secrethash,\n        ).call(block_identifier=block_identifier)\n        if result == 0:\n            return None\n        return result",
    "docstring": "Return the block number at which the secret for `secrethash` was\n        registered, None if the secret was never registered."
  },
  {
    "code": "def im_detect(self, im_list, root_dir=None, extension=None, show_timer=False):\n        test_db = TestDB(im_list, root_dir=root_dir, extension=extension)\n        test_iter = DetIter(test_db, 1, self.data_shape, self.mean_pixels,\n                            is_train=False)\n        return self.detect_iter(test_iter, show_timer)",
    "docstring": "wrapper for detecting multiple images\n\n        Parameters:\n        ----------\n        im_list : list of str\n            image path or list of image paths\n        root_dir : str\n            directory of input images, optional if image path already\n            has full directory information\n        extension : str\n            image extension, eg. \".jpg\", optional\n\n        Returns:\n        ----------\n        list of detection results in format [det0, det1...], det is in\n        format np.array([id, score, xmin, ymin, xmax, ymax]...)"
  },
  {
    "code": "def arbitrary_object_to_string(a_thing):\n    if a_thing is None:\n        return ''\n    if isinstance(a_thing, six.string_types):\n        return a_thing\n    if six.PY3 and isinstance(a_thing, six.binary_type):\n        try:\n            return a_thing.decode('utf-8')\n        except UnicodeDecodeError:\n            pass\n    try:\n        return a_thing.to_str()\n    except (AttributeError, KeyError, TypeError):\n        pass\n    try:\n        return arbitrary_object_to_string(a_thing.a_type)\n    except (AttributeError, KeyError, TypeError):\n        pass\n    try:\n        return known_mapping_type_to_str[a_thing]\n    except (KeyError, TypeError):\n        pass\n    try:\n        if a_thing.__module__ not in ('__builtin__', 'builtins', 'exceptions'):\n            if a_thing.__module__ == \"__main__\":\n                module_name = (\n                    sys.modules['__main__']\n                    .__file__[:-3]\n                    .replace('/', '.')\n                    .strip('.')\n                )\n            else:\n                module_name = a_thing.__module__\n            return \"%s.%s\" % (module_name, a_thing.__name__)\n    except AttributeError:\n        pass\n    try:\n        return a_thing.__name__\n    except AttributeError:\n        pass\n    return str(a_thing)",
    "docstring": "take a python object of some sort, and convert it into a human readable\n    string.  this function is used extensively to convert things like \"subject\"\n    into \"subject_key, function -> function_key, etc."
  },
  {
    "code": "def chdir(new_dir):\n    cur_dir = os.getcwd()\n    _mkdir(new_dir)\n    os.chdir(new_dir)\n    try:\n        yield\n    finally:\n        os.chdir(cur_dir)",
    "docstring": "stolen from bcbio.\n    Context manager to temporarily change to a new directory.\n\n    http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/"
  },
  {
    "code": "def check_if_not(x, *checks, **params):\n    for p in params:\n        if params[p] is not x and params[p] != x:\n            [check(**{p: params[p]}) for check in checks]",
    "docstring": "Run checks only if parameters are not equal to a specified value\n\n    Parameters\n    ----------\n\n    x : excepted value\n        Checks not run if parameters equal x\n\n    checks : function\n        Unnamed arguments, check functions to be run\n\n    params : object\n        Named arguments, parameters to be checked\n\n    Raises\n    ------\n    ValueError : unacceptable choice of parameters"
  },
  {
    "code": "def spin_gen_op(oper, gauge):\n    slaves = len(gauge)\n    oper['O'] = np.array([spin_gen(slaves, i, c) for i, c in enumerate(gauge)])\n    oper['O_d'] = np.transpose(oper['O'], (0, 2, 1))\n    oper['O_dO'] = np.einsum('...ij,...jk->...ik', oper['O_d'], oper['O'])\n    oper['Sfliphop'] = spinflipandhop(slaves)",
    "docstring": "Generates the generic spin matrices for the system"
  },
  {
    "code": "def circulation(self):\n        L = self.angular_momentum()\n        if L.ndim == 2:\n            single_orbit = True\n            L = L[...,None]\n        else:\n            single_orbit = False\n        ndim,ntimes,norbits = L.shape\n        L0 = L[:,0]\n        circ = np.ones((ndim,norbits))\n        for ii in range(ndim):\n            cnd = (np.sign(L0[ii]) != np.sign(L[ii,1:])) | \\\n                  (np.abs(L[ii,1:]).value < 1E-13)\n            ix = np.atleast_1d(np.any(cnd, axis=0))\n            circ[ii,ix] = 0\n        circ = circ.astype(int)\n        if single_orbit:\n            return circ.reshape((ndim,))\n        else:\n            return circ",
    "docstring": "Determine which axes the Orbit circulates around by checking\n        whether there is a change of sign of the angular momentum\n        about an axis. Returns a 2D array with ``ndim`` integers per orbit\n        point. If a box orbit, all integers will be 0. A 1 indicates\n        circulation about the corresponding axis.\n\n        TODO: clockwise / counterclockwise?\n\n        For example, for a single 3D orbit:\n\n        - Box and boxlet = [0,0,0]\n        - z-axis (short-axis) tube = [0,0,1]\n        - x-axis (long-axis) tube = [1,0,0]\n\n        Returns\n        -------\n        circulation : :class:`numpy.ndarray`\n            An array that specifies whether there is circulation about any of\n            the axes of the input orbit. For a single orbit, will return a\n            1D array, but for multiple orbits, the shape will be\n            ``(3, norbits)``."
  },
  {
    "code": "def getSampleTypeTitles(self):\n        sample_types = self.getSampleTypes()\n        sample_type_titles = map(lambda obj: obj.Title(), sample_types)\n        if not sample_type_titles:\n            return [\"\"]\n        return sample_type_titles",
    "docstring": "Returns a list of sample type titles"
  },
  {
    "code": "def get_by_id(self, reply_id):\n        reply = MReply.get_by_uid(reply_id)\n        logger.info('get_reply: {0}'.format(reply_id))\n        self.render('misc/reply/show_reply.html',\n                    reply=reply,\n                    username=reply.user_name,\n                    date=reply.date,\n                    vote=reply.vote,\n                    uid=reply.uid,\n                    userinfo=self.userinfo,\n                    kwd={})",
    "docstring": "Get the reply by id."
  },
  {
    "code": "def linreg_mle(y, X, algorithm='Nelder-Mead', debug=False):\n    import numpy as np\n    import scipy.stats as sstat\n    import scipy.optimize as sopt\n    def objective_nll_linreg(theta, y, X):\n        yhat = np.dot(X, theta[:-1])\n        return -1.0 * sstat.norm.logpdf(y, loc=yhat, scale=theta[-1]).sum()\n    if algorithm not in ('Nelder-Mead', 'CG', 'BFGS'):\n        raise Exception('Optimization Algorithm not supported.')\n    theta0 = np.ones((X.shape[1] + 1, ))\n    results = sopt.minimize(\n        objective_nll_linreg,\n        theta0,\n        args=(y, X),\n        method=algorithm,\n        options={'disp': False})\n    if debug:\n        return results\n    return results.x[:-1]",
    "docstring": "MLE for Linear Regression Model\n\n    Parameters:\n    -----------\n    y : ndarray\n        target variable with N observations\n\n    X : ndarray\n        The <N x C> design matrix with C independent\n        variables, features, factors, etc.\n\n    algorithm : str\n        Optional. Default 'Nelder-Mead' (Simplex).\n        The algorithm used in scipy.optimize.minimize\n\n    debug : bool\n        Optional.\n\n    Returns:\n    --------\n    beta : ndarray\n        Estimated regression coefficients.\n\n    results : scipy.optimize.optimize.OptimizeResult\n        Optional. If debug=True then only scipy's\n        optimization result variable is returned."
  },
  {
    "code": "def _load_lib():\n    lib_path = find_lib_path()\n    if len(lib_path) == 0:\n        return None\n    lib = ctypes.cdll.LoadLibrary(lib_path[0])\n    lib.LGBM_GetLastError.restype = ctypes.c_char_p\n    return lib",
    "docstring": "Load LightGBM library."
  },
  {
    "code": "def to_numpy(self):\n        assert HAS_NUMPY, 'numpy is not installed.'\n        import numpy\n        return numpy.transpose(numpy.asarray([self[x] for x in self.column_names()]))",
    "docstring": "Converts this SFrame to a numpy array\n\n        This operation will construct a numpy array in memory. Care must\n        be taken when size of the returned object is big.\n\n        Returns\n        -------\n        out : numpy.ndarray\n            A Numpy Array containing all the values of the SFrame"
  },
  {
    "code": "def project_hidden(x, projection_tensors, hidden_size, num_blocks):\n  batch_size, latent_dim, _ = common_layers.shape_list(x)\n  x = tf.reshape(x, shape=[1, -1, hidden_size])\n  x_tiled = tf.reshape(\n      tf.tile(x, multiples=[num_blocks, 1, 1]),\n      shape=[num_blocks, -1, hidden_size])\n  x_projected = tf.matmul(x_tiled, projection_tensors)\n  x_projected = tf.transpose(x_projected, perm=[1, 0, 2])\n  x_4d = tf.reshape(x_projected, [batch_size, latent_dim, num_blocks, -1])\n  return x_4d",
    "docstring": "Project encoder hidden state under num_blocks using projection tensors.\n\n  Args:\n    x: Encoder hidden state of shape [batch_size, latent_dim,  hidden_size].\n    projection_tensors: Projection tensors used to project the hidden state.\n    hidden_size: Dimension of the latent space.\n    num_blocks: Number of blocks in DVQ.\n\n  Returns:\n    x_projected: Projected states of shape [batch_size, latent_dim, num_blocks,\n      hidden_size / num_blocks]."
  },
  {
    "code": "def insert_table(self, label = None, name = None, **kwargs):\n        data_frame = kwargs.pop('data_frame', None)\n        if data_frame is None:\n            data_frame = kwargs.pop('dataframe', None)\n        to_hdf_kwargs = kwargs.pop('to_hdf_kwargs', dict())\n        if data_frame is not None:\n            assert isinstance(data_frame, pandas.DataFrame)\n        if data_frame is not None:\n            if label is None:\n                label = name\n            table = Table(label = label, name = name, survey = self)\n            assert table.survey.hdf5_file_path is not None\n            log.debug(\"Saving table {} in {}\".format(name, table.survey.hdf5_file_path))\n            table.save_data_frame(data_frame, **to_hdf_kwargs)\n        if name not in self.tables:\n            self.tables[name] = dict()\n        for key, val in kwargs.items():\n            self.tables[name][key] = val",
    "docstring": "Insert a table in the Survey object"
  },
  {
    "code": "def iters(cls, batch_size=32, device=0, root='.data',\n              vectors=None, trees=False, **kwargs):\n        if trees:\n            TEXT = ParsedTextField()\n            TRANSITIONS = ShiftReduceField()\n        else:\n            TEXT = data.Field(tokenize='spacy')\n            TRANSITIONS = None\n        LABEL = data.Field(sequential=False)\n        train, val, test = cls.splits(\n            TEXT, LABEL, TRANSITIONS, root=root, **kwargs)\n        TEXT.build_vocab(train, vectors=vectors)\n        LABEL.build_vocab(train)\n        return data.BucketIterator.splits(\n            (train, val, test), batch_size=batch_size, device=device)",
    "docstring": "Create iterator objects for splits of the SNLI dataset.\n\n        This is the simplest way to use the dataset, and assumes common\n        defaults for field, vocabulary, and iterator parameters.\n\n        Arguments:\n            batch_size: Batch size.\n            device: Device to create batches on. Use -1 for CPU and None for\n                the currently active GPU device.\n            root: The root directory that the dataset's zip archive will be\n                expanded into; therefore the directory in whose wikitext-2\n                subdirectory the data files will be stored.\n            vectors: one of the available pretrained vectors or a list with each\n                element one of the available pretrained vectors (see Vocab.load_vectors)\n            trees: Whether to include shift-reduce parser transitions.\n                Default: False.\n            Remaining keyword arguments: Passed to the splits method."
  },
  {
    "code": "def train_all(ctx, output):\n    click.echo('chemdataextractor.pos.train_all')\n    click.echo('Output: %s' % output)\n    ctx.invoke(train, output='%s_wsj_nocluster.pickle' % output, corpus='wsj', clusters=False)\n    ctx.invoke(train, output='%s_wsj.pickle' % output, corpus='wsj', clusters=True)\n    ctx.invoke(train, output='%s_genia_nocluster.pickle' % output, corpus='genia', clusters=False)\n    ctx.invoke(train, output='%s_genia.pickle' % output, corpus='genia', clusters=True)\n    ctx.invoke(train, output='%s_wsj_genia_nocluster.pickle' % output, corpus='wsj+genia', clusters=False)\n    ctx.invoke(train, output='%s_wsj_genia.pickle' % output, corpus='wsj+genia', clusters=True)",
    "docstring": "Train POS tagger on WSJ, GENIA, and both. With and without cluster features."
  },
  {
    "code": "def open(self):\n        self._connection = \\\n          amqp.Connection(host='%s:%s' % (self.hostname, self.port),\n                          userid=self.username, password=self.password,\n                          virtual_host=self.virtual_host, insist=False)\n        self.channel = self._connection.channel()",
    "docstring": "Open a connection to the AMQP compliant broker."
  },
  {
    "code": "def _interleave(self):\n        from pandas.core.dtypes.common import is_sparse\n        dtype = _interleaved_dtype(self.blocks)\n        if is_sparse(dtype):\n            dtype = dtype.subtype\n        elif is_extension_array_dtype(dtype):\n            dtype = 'object'\n        result = np.empty(self.shape, dtype=dtype)\n        itemmask = np.zeros(self.shape[0])\n        for blk in self.blocks:\n            rl = blk.mgr_locs\n            result[rl.indexer] = blk.get_values(dtype)\n            itemmask[rl.indexer] = 1\n        if not itemmask.all():\n            raise AssertionError('Some items were not contained in blocks')\n        return result",
    "docstring": "Return ndarray from blocks with specified item order\n        Items must be contained in the blocks"
  },
  {
    "code": "def remove_this_tlink(self,tlink_id):\n        for tlink in self.get_tlinks():\n            if tlink.get_id() == tlink_id:\n                self.node.remove(tlink.get_node())\n                break",
    "docstring": "Removes the tlink for the given tlink identifier\n        @type tlink_id: string\n        @param tlink_id: the tlink identifier to be removed"
  },
  {
    "code": "def to_multidimensional(tpm):\n    tpm = np.array(tpm)\n    N = tpm.shape[-1]\n    return tpm.reshape([2] * N + [N], order=\"F\").astype(float)",
    "docstring": "Reshape a state-by-node TPM to the multidimensional form.\n\n    See documentation for the |Network| object for more information on TPM\n    formats."
  },
  {
    "code": "def synchronise(func):\n    def inner(request, *args):\n        lock_id = '%s-%s-built-%s' % (\n            datetime.date.today(), func.__name__,\n            \",\".join([str(a) for a in args]))\n        if cache.add(lock_id, 'true', LOCK_EXPIRE):\n            result = func(request, *args)\n            cache.set(lock_id, result.task_id)\n        else:\n            task_id = cache.get(lock_id)\n            if not task_id:\n                return None\n            cache.set(lock_id, \"\")\n            result = Task.AsyncResult(task_id)\n            if result.ready():\n                result.forget()\n                return None\n        return result\n    return inner",
    "docstring": "If task already queued, running, or finished, don't restart."
  },
  {
    "code": "def apply(self, builder, model):\n        builder.where_null(model.get_qualified_deleted_at_column())\n        self.extend(builder)",
    "docstring": "Apply the scope to a given query builder.\n\n        :param builder: The query builder\n        :type builder: orator.orm.builder.Builder\n\n        :param model: The model\n        :type model: orator.orm.Model"
  },
  {
    "code": "def gfpa(target, illmin, abcorr, obsrvr, relate, refval, adjust, step, nintvals,\n         cnfine, result=None):\n    assert isinstance(cnfine, stypes.SpiceCell)\n    assert cnfine.is_double()\n    if result is None:\n        result = stypes.SPICEDOUBLE_CELL(2000)\n    else:\n        assert isinstance(result, stypes.SpiceCell)\n        assert result.is_double()\n    target = stypes.stringToCharP(target)\n    illmin = stypes.stringToCharP(illmin)\n    abcorr = stypes.stringToCharP(abcorr)\n    obsrvr = stypes.stringToCharP(obsrvr)\n    relate = stypes.stringToCharP(relate)\n    refval = ctypes.c_double(refval)\n    adjust = ctypes.c_double(adjust)\n    step = ctypes.c_double(step)\n    nintvals = ctypes.c_int(nintvals)\n    libspice.gfpa_c(target, illmin, abcorr, obsrvr, relate, refval,\n                    adjust, step, nintvals, ctypes.byref(cnfine),\n                    ctypes.byref(result))\n    return result",
    "docstring": "Determine time intervals for which a specified constraint\n    on the phase angle between an illumination source, a target,\n    and observer body centers is met.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfpa_c.html\n\n    :param target: Name of the target body.\n    :type target: str\n    :param illmin: Name of the illuminating body.\n    :type illmin: str\n    :param abcorr: Aberration correction flag.\n    :type abcorr: str\n    :param obsrvr: Name of the observing body.\n    :type obsrvr: str\n    :param relate: Relational operator.\n    :type relate: str\n    :param refval: Reference value.\n    :type refval: float\n    :param adjust: Adjustment value for absolute extrema searches.\n    :type adjust: float\n    :param step: Step size used for locating extrema and roots.\n    :type step: float\n    :param nintvals: Workspace window interval count.\n    :type nintvals: int\n    :param cnfine: SPICE window to which the search is restricted.\n    :type cnfine: spiceypy.utils.support_types.SpiceCell\n    :param result: Optional SPICE window containing results.\n    :type result: spiceypy.utils.support_types.SpiceCell"
  },
  {
    "code": "def get_details(self, jobname, jobkey):\n        fullkey = JobDetails.make_fullkey(jobname, jobkey)\n        return self._cache[fullkey]",
    "docstring": "Get the `JobDetails` associated to a particular job instance"
  },
  {
    "code": "def get_missing_deps(self, obj):\n        deps = self.get_deps(obj)\n        ret = []\n        for key in deps:\n            provider = self._providers.get(key)\n            if provider and provider.providable:\n                continue\n            ret.append(key)\n        return ret",
    "docstring": "Returns missing dependencies for provider key.\n        Missing meaning no instance can be provided at this time.\n\n        :param key: Provider key\n        :type key: object\n        :return: Missing dependencies\n        :rtype: list"
  },
  {
    "code": "def db_dp010(self, value=None):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type float '\n                                 'for field `db_dp010`'.format(value))\n        self._db_dp010 = value",
    "docstring": "Corresponds to IDD Field `db_dp010`\n        mean coincident dry-bulb temperature to\n        Dew-point temperature corresponding to 1.0% annual cumulative frequency of occurrence\n\n        Args:\n            value (float): value for IDD Field `db_dp010`\n                Unit: C\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def rolling(self, window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None):\n        kwds = {\n            \"window\": window,\n            \"min_periods\": min_periods,\n            \"center\": center,\n            \"win_type\": win_type,\n            \"on\": on,\n            \"axis\": axis,\n            \"closed\": closed,\n        }\n        return Rolling(self._obj, self._npartitions, self._dask_threshold, self._scheduler, self._progress_bar, **kwds)",
    "docstring": "Create a swifter rolling object"
  },
  {
    "code": "def find_coord_vars(ncds):\n    coord_vars = []\n    for d in ncds.dimensions:\n        if d in ncds.variables and ncds.variables[d].dimensions == (d,):\n            coord_vars.append(ncds.variables[d])\n    return coord_vars",
    "docstring": "Finds all coordinate variables in a dataset.\n\n    A variable with the same name as a dimension is called a coordinate variable."
  },
  {
    "code": "def owner_search_fields(self):\n        try:\n            from django.contrib.auth import get_user_model\n        except ImportError:\n            from django.contrib.auth.models import User\n        else:\n            User = get_user_model()\n        return [\n            field.name for field in User._meta.fields\n            if isinstance(field, models.CharField) and field.name != 'password'\n        ]",
    "docstring": "Returns all the fields that are CharFields except for password from the\n        User model.  For the built-in User model, that means username,\n        first_name, last_name, and email."
  },
  {
    "code": "def get_all_chains(self):\n        return [self.get_chain(i) for i in range(len(self.leaves))]",
    "docstring": "Assemble and return a list of all chains for all leaf nodes to the merkle root."
  },
  {
    "code": "def notice(self, target, msg):\n        self.cmd(u'NOTICE', u'{0} :{1}'.format(target, msg))",
    "docstring": "Sends a NOTICE to an user or channel.\n\n        :param target: user or channel to send to.\n        :type target: str\n        :param msg: message to send.\n        :type msg: basestring"
  },
  {
    "code": "def dcc_send(self, mask, filepath):\n        return self.dcc.create('send', mask, filepath=filepath).ready",
    "docstring": "DCC SEND a file to mask. filepath must be an absolute path to\n        existing file"
  },
  {
    "code": "def _check_valid_translation(self, translation):\n        if not isinstance(translation, np.ndarray) or not np.issubdtype(translation.dtype, np.number):\n            raise ValueError('Translation must be specified as numeric numpy array')\n        t = translation.squeeze()\n        if len(t.shape) != 1 or t.shape[0] != 3:\n            raise ValueError('Translation must be specified as a 3-vector, 3x1 ndarray, or 1x3 ndarray')",
    "docstring": "Checks that the translation vector is valid."
  },
  {
    "code": "def sync_to(self):\n        device_group_collection = self._meta_data['container']\n        cm = device_group_collection._meta_data['container']\n        sync_cmd = 'config-sync to-group %s' % self.name\n        cm.exec_cmd('run', utilCmdArgs=sync_cmd)",
    "docstring": "Wrapper method that synchronizes configuration to DG.\n\n\n        Executes the containing object's cm :meth:`~f5.bigip.cm.Cm.exec_cmd`\n        method to sync the configuration TO the device-group.\n\n        :note:: Both sync_to, and sync_from methods are convenience\n                methods which usually are not what this SDK offers.\n                It is best to execute config-sync with the use of\n                exec_cmd() method on the cm endpoint."
  },
  {
    "code": "def plot(self, save_path=None, close=False, bbox_inches=\"tight\", pad_inches=1):\n        for plot in self.subplots.flatten():\n            plot.set_xlim(-0.1, 1.1)\n            plot.set_ylim(-0.1, 1.1)\n            plot.axis(\"off\")\n        if save_path:\n            plt.savefig(\n                save_path,\n                transparent=True,\n                dpi=300,\n                bbox_inches=bbox_inches,\n                pad_inches=pad_inches,\n            )\n        if close:\n            plt.close()",
    "docstring": "Plot figure.\n\n        Parameters\n        ----------\n        save_path : string (optional)\n            Save path. Default is None.\n        close : boolean (optional)\n            Toggle automatic figure closure after plotting.\n            Default is False.\n        bbox_inches : number (optional)\n            Bounding box size, in inches. Default is 'tight'.\n        pad_inches : number (optional)\n            Pad inches. Default is 1."
  },
  {
    "code": "def _valid_baremetal_port(port):\n        if port.get(portbindings.VNIC_TYPE) != portbindings.VNIC_BAREMETAL:\n            return False\n        sgs = port.get('security_groups', [])\n        if len(sgs) == 0:\n            return False\n        if len(port.get('security_groups', [])) > 1:\n            LOG.warning('SG provisioning failed for %(port)s. Only one '\n                        'SG may be applied per port.',\n                        {'port': port['id']})\n            return False\n        return True",
    "docstring": "Check if port is a baremetal port with exactly one security group"
  },
  {
    "code": "def load_module(name):\n    spec = importlib.util.find_spec(name)\n    mod = importlib.util.module_from_spec(spec)\n    mod.__spec__ = spec\n    mod.__loader__ = spec.loader\n    spec.loader.exec_module(mod)\n    return mod",
    "docstring": "Load the named module without registering it in ``sys.modules``.\n\n    Parameters\n    ----------\n    name : string\n      Module name\n\n    Returns\n    -------\n    mod : module\n      Loaded module"
  },
  {
    "code": "def random(magnitude=1):\n        theta = random.uniform(0, 2 * math.pi)\n        return magnitude * Vector(math.cos(theta), math.sin(theta))",
    "docstring": "Create a unit vector pointing in a random direction."
  },
  {
    "code": "def signal_handler(sig, frame):\n    print('\\nYou pressed Ctrl+C')\n    if board is not None:\n        board.send_reset()\n        board.shutdown()\n    sys.exit(0)",
    "docstring": "Helper method to shutdown the RedBot if Ctrl-c is pressed"
  },
  {
    "code": "def get_available_hashes():\n    if sys.version_info >= (3,2):\n        return hashlib.algorithms_available\n    elif sys.version_info >= (2,7) and sys.version_info < (3,0):\n        return hashlib.algorithms\n    else:\n        return 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'",
    "docstring": "Returns a tuple of the available hashes"
  },
  {
    "code": "def _have_conf(self, magic_hash=None):\n        self.app.have_conf = getattr(self.app, 'cur_conf', None) not in [None, {}]\n        if magic_hash is not None:\n            magic_hash = int(magic_hash)\n            return self.app.have_conf and self.app.cur_conf.magic_hash == magic_hash\n        return self.app.have_conf",
    "docstring": "Get the daemon current configuration state\n\n        If the daemon has received a configuration from its arbiter, this will\n        return True\n\n        If a `magic_hash` is provided it is compared with the one included in the\n        daemon configuration and this function returns True only if they match!\n\n        :return: boolean indicating if the daemon has a configuration\n        :rtype: bool"
  },
  {
    "code": "def is_pdf(document):\n    if not executable_exists('pdftotext'):\n        current_app.logger.warning(\n            \"GNU file was not found on the system. \"\n            \"Switching to a weak file extension test.\"\n        )\n        if document.lower().endswith(\".pdf\"):\n            return True\n        return False\n    file_output = os.popen('file ' + re.escape(document)).read()\n    try:\n        filetype = file_output.split(\":\")[-1]\n    except IndexError:\n        current_app.logger.error(\n            \"Your version of the 'file' utility seems to be unsupported.\"\n        )\n        raise IncompatiblePDF2Text('Incompatible pdftotext')\n    pdf = filetype.find(\"PDF\") > -1\n    return pdf",
    "docstring": "Check if a document is a PDF file and return True if is is."
  },
  {
    "code": "def exit_if_path_exists(self):\n        if os.path.exists(self.output_path):\n            ui.error(c.MESSAGES[\"path_exists\"], self.output_path)\n            sys.exit(1)",
    "docstring": "Exit early if the path cannot be found."
  },
  {
    "code": "def purge_items(app, env, docname):\n    keys = list(env.traceability_all_items.keys())\n    for key in keys:\n        if env.traceability_all_items[key]['docname'] == docname:\n            del env.traceability_all_items[key]",
    "docstring": "Clean, if existing, ``item`` entries in ``traceability_all_items``\n    environment variable, for all the source docs being purged.\n\n    This function should be triggered upon ``env-purge-doc`` event."
  },
  {
    "code": "def on_nicknameinuse(self, connection, event):\n        digits = \"\"\n        while self.nickname[-1].isdigit():\n            digits = self.nickname[-1] + digits\n            self.nickname = self.nickname[:-1]\n        digits = 1 if not digits else int(digits) + 1\n        self.nickname += str(digits)\n        self.connect(self.host, self.port, self.nickname)",
    "docstring": "Increment a digit on the nickname if it's in use, and\n        re-connect."
  },
  {
    "code": "def logit(self, msg, pid, user, cname, priority=None):\n        if self.stream:\n            print(msg, file=self.stream)\n        elif priority == logging.WARNING:\n            self.logger.warning(\"{0}[pid:{1}] user:{2}: WARNING - {3}\".format(cname, pid, user, msg))\n        elif priority == logging.ERROR:\n            self.logger.error(\"{0}[pid:{1}] user:{2}: ERROR - {3}\".format(cname, pid, user, msg))\n        else:\n            self.logger.info(\"{0}[pid:{1}] user:{2}: INFO - {3}\".format(cname, pid, user, msg))",
    "docstring": "Function for formatting content and logging to syslog"
  },
  {
    "code": "def answered_by(self, rec):\n        return self.clazz == rec.clazz and \\\n                (self.type == rec.type or self.type == _TYPE_ANY) and \\\n                self.name == rec.name",
    "docstring": "Returns true if the question is answered by the record"
  },
  {
    "code": "def transform_incoming(self, son, collection):\n        def transform_value(value):\n            if isinstance(value, collections.MutableMapping):\n                if \"_id\" in value and \"_ns\" in value:\n                    return DBRef(value[\"_ns\"], transform_value(value[\"_id\"]))\n                else:\n                    return transform_dict(SON(value))\n            elif isinstance(value, list):\n                return [transform_value(v) for v in value]\n            return value\n        def transform_dict(object):\n            for (key, value) in object.items():\n                object[key] = transform_value(value)\n            return object\n        return transform_dict(SON(son))",
    "docstring": "Replace embedded documents with DBRefs."
  },
  {
    "code": "def transformToNative(obj):\n        if obj.isNative:\n            return obj\n        obj.isNative = True\n        if obj.value == '':\n            return obj\n        obj.value=obj.value\n        obj.value=parseDtstart(obj, allowSignatureMismatch=True)\n        if getattr(obj, 'value_param', 'DATE-TIME').upper() == 'DATE-TIME':\n            if hasattr(obj, 'tzid_param'):\n                obj.params['X-VOBJ-ORIGINAL-TZID'] = [obj.tzid_param]\n                del obj.tzid_param\n        return obj",
    "docstring": "Turn obj.value into a date or datetime."
  },
  {
    "code": "def sorensen(seq1, seq2):\n\tset1, set2 = set(seq1), set(seq2)\n\treturn 1 - (2 * len(set1 & set2) / float(len(set1) + len(set2)))",
    "docstring": "Compute the Sorensen distance between the two sequences `seq1` and `seq2`.\n\tThey should contain hashable items.\n\t\n\tThe return value is a float between 0 and 1, where 0 means equal, and 1 totally different."
  },
  {
    "code": "def set_credentials(self, client_id=None, client_secret=None):\n        self._client_id = client_id\n        self._client_secret = client_secret\n        self._session = None",
    "docstring": "set given credentials and reset the session"
  },
  {
    "code": "def merge_extends(self, target, extends, inherit_key=\"inherit\", inherit=False):\n        if isinstance(target, dict):\n            if inherit and inherit_key in target and not to_boolean(target[inherit_key]):\n                return\n            if not isinstance(extends, dict):\n                raise ValueError(\"Unable to merge: Dictionnary expected\")\n            for key in extends:\n                if key not in target:\n                    target[str(key)] = extends[key]\n                else:\n                    self.merge_extends(target[key], extends[key], inherit_key, True)\n        elif isinstance(target, list):\n            if not isinstance(extends, list):\n                raise ValueError(\"Unable to merge: List expected\")\n            target += extends",
    "docstring": "Merge extended dicts"
  },
  {
    "code": "def set_permitted_ip(address=None, deploy=False):\n    if not address:\n        raise CommandExecutionError(\"Address option must not be empty.\")\n    ret = {}\n    query = {'type': 'config',\n             'action': 'set',\n             'xpath': '/config/devices/entry[@name=\\'localhost.localdomain\\']/deviceconfig/system/permitted-ip',\n             'element': '<entry name=\\'{0}\\'></entry>'.format(address)}\n    ret.update(__proxy__['panos.call'](query))\n    if deploy is True:\n        ret.update(commit())\n    return ret",
    "docstring": "Add an IPv4 address or network to the permitted IP list.\n\n    CLI Example:\n\n    Args:\n        address (str): The IPv4 address or network to allow access to add to the Palo Alto device.\n\n        deploy (bool): If true then commit the full candidate configuration, if false only set pending change.\n\n    .. code-block:: bash\n\n        salt '*' panos.set_permitted_ip 10.0.0.1\n        salt '*' panos.set_permitted_ip 10.0.0.0/24\n        salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True"
  },
  {
    "code": "def set_user_presence(self, userid, presence):\n        response, status_code = self.__pod__.Presence.post_v2_user_uid_presence(\n            sessionToken=self.__session__,\n            uid=userid,\n            presence=presence\n        ).result()\n        self.logger.debug('%s: %s' % (status_code, response))\n        return status_code, response",
    "docstring": "set presence of user"
  },
  {
    "code": "def build_url_request(self):\n        params = {}\n        headers = {}\n        self._authenticator(params, headers)\n        self._grant(params)\n        return Request(self._endpoint, urlencode(params), headers)",
    "docstring": "Consults the authenticator and grant for HTTP request parameters and\n        headers to send with the access token request, builds the request using\n        the stored endpoint and returns it."
  },
  {
    "code": "def choices(self):\n        model_parent_part = self.part.model()\n        property_model = model_parent_part.property(self.name)\n        referenced_model = self._client.model(pk=property_model._value['id'])\n        possible_choices = self._client.parts(model=referenced_model)\n        return possible_choices",
    "docstring": "Retrieve the parts that you can reference for this `ReferenceProperty`.\n\n        This method makes 2 API calls: 1) to retrieve the referenced model, and 2) to retrieve the instances of\n        that model.\n\n        :return: the :class:`Part`'s that can be referenced as a :class:`~pykechain.model.PartSet`.\n        :raises APIError: When unable to load and provide the choices\n\n        Example\n        -------\n\n        >>> property = project.part('Bike').property('RefTest')\n        >>> reference_part_choices = property.choices()"
  },
  {
    "code": "def encrypt(message, modN, e, blockSize):\n    numList = string2numList(message)\n    numBlocks = numList2blocks(numList, blockSize)\n    message = numBlocks[0]\n    return modExp(message, e, modN)",
    "docstring": "given a string message, public keys and blockSize, encrypt using\n    RSA algorithms."
  },
  {
    "code": "def assert_variable_type(variable, expected_type, raise_exception=True):\n    if not isinstance(expected_type, list):\n        expected_type = [expected_type]\n    for t in expected_type:\n        if not isinstance(t, type):\n            raise ValueError('expected_type argument \"%s\" is not a type' %str(t))\n    if not isinstance(raise_exception, bool):\n        raise ValueError('raise_exception argument \"%s\" is not a bool' %str(raise_exception))\n    if not len([(t) for t in expected_type if isinstance(variable, t)]):\n        error_message = '\"%s\" is not an instance of type %s. It is of type %s' %(str(variable),' or '.join([str(t) for t in expected_type]), str(type(variable)))\n        if raise_exception:\n            raise ValueError(error_message)\n        else:\n            return False, error_message\n    return True, None",
    "docstring": "Return True if a variable is of a certain type or types.\n    Otherwise raise a ValueError exception.\n\n    Positional arguments:\n    variable -- the variable to be checked\n    expected_type -- the expected type or types of the variable\n    raise_exception -- whether to raise an exception or just return\n                        False on failure, with error message"
  },
  {
    "code": "def cmd(name,\n        tgt,\n        func,\n        arg=(),\n        tgt_type='glob',\n        ret='',\n        kwarg=None,\n        **kwargs):\n    ret = {'name': name,\n           'changes': {},\n           'comment': '',\n           'result': True}\n    local = salt.client.get_local_client(mopts=__opts__)\n    jid = local.cmd_async(tgt,\n                          func,\n                          arg,\n                          tgt_type=tgt_type,\n                          ret=ret,\n                          kwarg=kwarg,\n                          **kwargs)\n    ret['changes']['jid'] = jid\n    return ret",
    "docstring": "Execute a remote execution command\n\n    USAGE:\n\n    .. code-block:: yaml\n\n        run_remote_ex:\n          local.cmd:\n            - tgt: '*'\n            - func: test.ping\n\n        run_remote_ex:\n          local.cmd:\n            - tgt: '*'\n            - func: test.sleep\n            - arg:\n              - 30\n\n        run_remote_ex:\n          local.cmd:\n            - tgt: '*'\n            - func: test.sleep\n            - kwarg:\n              length: 30"
  },
  {
    "code": "def move_by_offset(self, xoffset, yoffset):\n        if self._driver.w3c:\n            self.w3c_actions.pointer_action.move_by(xoffset, yoffset)\n            self.w3c_actions.key_action.pause()\n        else:\n            self._actions.append(lambda: self._driver.execute(\n                Command.MOVE_TO, {\n                    'xoffset': int(xoffset),\n                    'yoffset': int(yoffset)}))\n        return self",
    "docstring": "Moving the mouse to an offset from current mouse position.\n\n        :Args:\n         - xoffset: X offset to move to, as a positive or negative integer.\n         - yoffset: Y offset to move to, as a positive or negative integer."
  },
  {
    "code": "def set_mode_label_to_ifcw(self):\n        self.setWindowTitle(self.ifcw_name)\n        self.lblSubtitle.setText(tr(\n            'Use this wizard to run a guided impact assessment'))",
    "docstring": "Set the mode label to the IFCW."
  },
  {
    "code": "def process_shells(self, shells):\n        result = {'success': True, 'output': []}\n        if self.parallel and len(shells) > 1:\n            result = self.process_shells_parallel(shells)\n        elif len(shells) > 0:\n            result = self.process_shells_ordered(shells)\n        return result",
    "docstring": "Processing a list of shells."
  },
  {
    "code": "async def set_password(self, password):\n        await self.controller.change_user_password(self.username, password)\n        self._user_info.password = password",
    "docstring": "Update this user's password."
  },
  {
    "code": "def cltext(fname):\n    fnameP    = stypes.stringToCharP(fname)\n    fname_len = ctypes.c_int(len(fname))\n    libspice.cltext_(fnameP, fname_len)",
    "docstring": "Internal undocumented command for closing a text file opened by RDTEXT.\n\n    No URL available; relevant lines from SPICE source:\n\n    FORTRAN SPICE, rdtext.f::\n\n        C$Procedure  CLTEXT ( Close a text file opened by RDTEXT)\n              ENTRY  CLTEXT ( FILE )\n              CHARACTER*(*)       FILE\n        C     VARIABLE  I/O  DESCRIPTION\n        C     --------  ---  --------------------------------------------------\n        C     FILE       I   Text file to be closed.\n\n    CSPICE, rdtext.c::\n\n        /* $Procedure  CLTEXT ( Close a text file opened by RDTEXT) */\n        /* Subroutine */ int cltext_(char *file, ftnlen file_len)\n\n\n    :param fname: Text file to be closed.\n    :type fname: str"
  },
  {
    "code": "def ndims(self):\n        if self._dims is None:\n            return None\n        else:\n            if self._ndims is None:\n                self._ndims = len(self._dims)\n            return self._ndims",
    "docstring": "Returns the rank of this shape, or None if it is unspecified."
  },
  {
    "code": "def langids(self):\n        if self._langids is None:\n            try:\n                self._langids = util.get_langids(self)\n            except USBError:\n                self._langids = ()\n        return self._langids",
    "docstring": "Return the USB device's supported language ID codes.\n\n        These are 16-bit codes familiar to Windows developers, where for\n        example instead of en-US you say 0x0409. USB_LANGIDS.pdf on the usb.org\n        developer site for more info. String requests using a LANGID not\n        in this array should not be sent to the device.\n\n        This property will cause some USB traffic the first time it is accessed\n        and cache the resulting value for future use."
  },
  {
    "code": "def go_env(self, gopath=None):\n    no_gopath = os.devnull\n    return OrderedDict(GOROOT=self.goroot, GOPATH=gopath or no_gopath)",
    "docstring": "Return an env dict that represents a proper Go environment mapping for this distribution."
  },
  {
    "code": "def volume_delete(name, profile=None, **kwargs):\n    conn = _auth(profile, **kwargs)\n    return conn.volume_delete(name)",
    "docstring": "Destroy the volume\n\n    name\n        Name of the volume\n\n    profile\n        Profile to build on\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' nova.volume_delete myblock profile=openstack"
  },
  {
    "code": "def recv(self, timeout=None):\n        try:\n            return self.rx_queue.get(timeout is None or timeout > 0, timeout)\n        except queue.Empty:\n            return None",
    "docstring": "Receive an ISOTP frame, blocking if none is available in the buffer\n        for at most 'timeout' seconds."
  },
  {
    "code": "def mask_umi(umi, umi_quals, quality_encoding,  quality_filter_threshold):\n    below_threshold = get_below_threshold(\n        umi_quals, quality_encoding, quality_filter_threshold)\n    new_umi = \"\"\n    for base, test in zip(umi, below_threshold):\n        if test:\n            new_umi += \"N\"\n        else:\n            new_umi += base\n    return new_umi",
    "docstring": "Mask all positions where quals < threshold with \"N\""
  },
  {
    "code": "def resource(\n        self,\n        token: dict = None,\n        id_resource: str = None,\n        subresource=None,\n        include: list = [],\n        prot: str = \"https\",\n    ) -> dict:\n        if isinstance(subresource, str):\n            subresource = \"/{}\".format(checker._check_subresource(subresource))\n        else:\n            subresource = \"\"\n            include = checker._check_filter_includes(include)\n        payload = {\"id\": id_resource, \"_include\": include}\n        md_url = \"{}://v1.{}.isogeo.com/resources/{}{}\".format(\n            prot, self.api_url, id_resource, subresource\n        )\n        resource_req = self.get(\n            md_url,\n            headers=self.header,\n            params=payload,\n            proxies=self.proxies,\n            verify=self.ssl,\n        )\n        checker.check_api_response(resource_req)\n        return resource_req.json()",
    "docstring": "Get complete or partial metadata about one specific resource.\n\n        :param str token: API auth token\n        :param str id_resource: metadata UUID to get\n        :param list include: subresources that should be included.\n         Must be a list of strings. Available values: 'isogeo.SUBRESOURCES'\n        :param str prot: https [DEFAULT] or http\n         (use it only for dev and tracking needs)."
  },
  {
    "code": "def request_withdrawal(self, amount: Number, address: str, subtract_fee: bool=False, **params) -> Withdrawal:\n        self.log.debug(f'Requesting {self.currency} withdrawal from {self.name} to {address}')\n        amount = self._parse_money(amount)\n        if self.dry_run:\n            withdrawal = Withdrawal.create_default(TxType.WITHDRAWAL, self.currency, amount, address)\n            self.log.warning(f'DRY RUN: Withdrawal requested on {self.name}: {withdrawal}')\n            return withdrawal\n        try:\n            withdrawal = self._withdraw(amount, address, subtract_fee, **params)\n        except Exception as e:\n            msg = f'Failed requesting withdrawal on {self.name}!: amount={amount}, address={address}'\n            raise self.exception(InvalidWithdrawal, msg, e) from e\n        self.log.info(f'Withdrawal requested on {self.name}: {withdrawal}')\n        return withdrawal",
    "docstring": "Request a withdrawal."
  },
  {
    "code": "def restore_defaults(self):\n        for key in self.default_values:\n            self.restore_default(key)\n        for section in self.sections:\n            self[section].restore_defaults()",
    "docstring": "Recursively restore default values to all members\n        that have them.\n\n        This method will only work for a ConfigObj that was created\n        with a configspec and has been validated.\n\n        It doesn't delete or modify entries without default values."
  },
  {
    "code": "def label_total_duration(self):\n        durations = collections.defaultdict(float)\n        for label in self:\n            durations[label.value] += label.duration\n        return durations",
    "docstring": "Return for each distinct label value the total duration of all occurrences.\n\n        Returns:\n            dict: A dictionary containing for every label-value (key)\n                  the total duration in seconds (value).\n\n        Example:\n            >>> ll = LabelList(labels=[\n            >>>     Label('a', 3, 5),\n            >>>     Label('b', 5, 8),\n            >>>     Label('a', 8, 10),\n            >>>     Label('b', 10, 14),\n            >>>     Label('a', 15, 18.5)\n            >>> ])\n            >>> ll.label_total_duration()\n            {'a': 7.5 'b': 7.0}"
  },
  {
    "code": "def xyzlabel(labelx, labely, labelz):\n    xlabel(labelx)\n    ylabel(labely)\n    zlabel(labelz)",
    "docstring": "Set all labels at once."
  },
  {
    "code": "def _parseTagName(self):\n        for el in self._element.split():\n            el = el.replace(\"/\", \"\").replace(\"<\", \"\").replace(\">\", \"\")\n            if el.strip():\n                self._tagname = el.rstrip()\n                return",
    "docstring": "Parse name of the tag.\n\n        Result is saved to the :attr:`_tagname` property."
  },
  {
    "code": "async def release_cursor(self, cursor, in_transaction=False):\n        conn = cursor.connection\n        await cursor.close()\n        if not in_transaction:\n            self.release(conn)",
    "docstring": "Release cursor coroutine. Unless in transaction,\n        the connection is also released back to the pool."
  },
  {
    "code": "def _slugify_title(self):\n        self.slug = slugify(self.title)\n        while len(self.slug) > 255:\n            self.slug = '-'.join(self.slug.split('-')[:-1])\n        if Entry.objects.filter(slug=self.slug).exclude(id=self.id).exists():\n            self.slug = self._insert_timestamp(self.slug)",
    "docstring": "Slugify the Entry title, but ensure it's less than the maximum\n        number of characters. This method also ensures that a slug is unique by\n        appending a timestamp to any duplicate slugs."
  },
  {
    "code": "def parse_request(self, request, parameters=None, fake_method=None):\n        return (request.method,\n                request.url,\n                request.headers,\n                request.form.copy())",
    "docstring": "Parse Flask request"
  },
  {
    "code": "def before_update(mapper, conn, target):\n        target.name = Table.mangle_name(target.name)\n        if isinstance(target, Column):\n            raise TypeError('Got a column instead of a table')\n        target.update_id(target.sequence_id, False)",
    "docstring": "Set the Table ID based on the dataset number and the sequence number\n        for the table."
  },
  {
    "code": "def _blocked_connection(self, frame_in):\n        self.is_blocked = True\n        LOGGER.warning(\n            'Connection is blocked by remote server: %s',\n            try_utf8_decode(frame_in.reason)\n        )",
    "docstring": "Connection is Blocked.\n\n        :param frame_in:\n        :return:"
  },
  {
    "code": "def tag_and_push(context):\n    tag_option = '--annotate'\n    if probe.has_signing_key(context):\n        tag_option = '--sign'\n    shell.dry_run(\n        TAG_TEMPLATE % (tag_option, context.new_version, context.new_version),\n        context.dry_run,\n    )\n    shell.dry_run('git push --tags', context.dry_run)",
    "docstring": "Tags your git repo with the new version number"
  },
  {
    "code": "def pic_inflow_v2(self):\n    flu = self.sequences.fluxes.fastaccess\n    inl = self.sequences.inlets.fastaccess\n    flu.inflow = inl.q[0]+inl.s[0]+inl.r[0]",
    "docstring": "Update the inlet link sequences.\n\n    Required inlet sequences:\n      |dam_inlets.Q|\n      |dam_inlets.S|\n      |dam_inlets.R|\n\n    Calculated flux sequence:\n      |Inflow|\n\n    Basic equation:\n      :math:`Inflow = Q + S + R`"
  },
  {
    "code": "def set_permissions(self, object, replace=False):\n        if isinstance(self.config.origin, S3Origin):\n            if self.config.origin.origin_access_identity:\n                id = self.config.origin.origin_access_identity.split('/')[-1]\n                oai = self.connection.get_origin_access_identity_info(id)\n                policy = object.get_acl()\n                if replace:\n                    policy.acl = ACL()\n                policy.acl.add_user_grant('READ', oai.s3_user_id)\n                object.set_acl(policy)\n            else:\n                object.set_canned_acl('public-read')",
    "docstring": "Sets the S3 ACL grants for the given object to the appropriate\n        value based on the type of Distribution.  If the Distribution\n        is serving private content the ACL will be set to include the\n        Origin Access Identity associated with the Distribution.  If\n        the Distribution is serving public content the content will\n        be set up with \"public-read\".\n\n        :type object: :class:`boto.cloudfront.object.Object`\n        :param enabled: The Object whose ACL is being set\n\n        :type replace: bool\n        :param replace: If False, the Origin Access Identity will be\n                        appended to the existing ACL for the object.\n                        If True, the ACL for the object will be\n                        completely replaced with one that grants\n                        READ permission to the Origin Access Identity."
  },
  {
    "code": "def get_category_by_id(self, cid):\n        self._cache_init()\n        return self._cache_get_entry(self.CACHE_NAME_IDS, cid)",
    "docstring": "Returns Category object by its id.\n\n        :param str cid:\n        :rtype: Category\n        :return: category object"
  },
  {
    "code": "def is_primary_vehicle(self, msg):\n        sysid = msg.get_srcSystem()\n        if self.target_system == 0 or self.target_system == sysid:\n            return True\n        return False",
    "docstring": "see if a msg is from our primary vehicle"
  },
  {
    "code": "def watched_file_handler(name, logname, filename, mode='a', encoding=None,\n                         delay=False):\n    return wrap_log_handler(logging.handlers.WatchedFileHandler(\n        filename, mode=mode, encoding=encoding, delay=delay))",
    "docstring": "A Bark logging handler logging output to a named file.  If the\n    file has changed since the last log message was written, it will\n    be closed and reopened.\n\n    Similar to logging.handlers.WatchedFileHandler."
  },
  {
    "code": "def read(self, size=None):\n    if size is None:\n      return self.buf.read() + self.open_file.read()\n    contents = self.buf.read(size)\n    if len(contents) < size:\n      contents += self.open_file.read(size - len(contents))\n    return contents",
    "docstring": "Read `size` of bytes."
  },
  {
    "code": "def parse_file(self, f):\n        if type(f) is str:\n            self.f = open(f, 'rb')\n        else:\n            self.f = f\n        self._parse_header(self.f.read(64))",
    "docstring": "Parse an ELF file and fill the class' properties.\n\n        Arguments:\n            f(file or str): The (path to) the ELF file to read."
  },
  {
    "code": "def get_parameters_by_location(self, locations=None, excludes=None):\n        result = self.parameters\n        if locations:\n            result = filter(lambda x: x.location_in in locations, result)\n        if excludes:\n            result = filter(lambda x: x.location_in not in excludes, result)\n        return list(result)",
    "docstring": "Get parameters list by location\n\n        :param locations: list of locations\n        :type locations: list or None\n        :param excludes: list of excludes locations\n        :type excludes: list or None\n        :return: list of Parameter\n        :rtype: list"
  },
  {
    "code": "def eval_function(value):\n    name, args = value[0], value[1:]\n    if name == \"NOW\":\n        return datetime.utcnow().replace(tzinfo=tzutc())\n    elif name in [\"TIMESTAMP\", \"TS\"]:\n        return parse(unwrap(args[0])).replace(tzinfo=tzlocal())\n    elif name in [\"UTCTIMESTAMP\", \"UTCTS\"]:\n        return parse(unwrap(args[0])).replace(tzinfo=tzutc())\n    elif name == \"MS\":\n        return 1000 * resolve(args[0])\n    else:\n        raise SyntaxError(\"Unrecognized function %r\" % name)",
    "docstring": "Evaluate a timestamp function"
  },
  {
    "code": "def num_rewards(self):\n    if not self.is_reward_range_finite:\n      tf.logging.error(\"Infinite reward range, `num_rewards returning None`\")\n      return None\n    if not self.is_processed_rewards_discrete:\n      tf.logging.error(\n          \"Processed rewards are not discrete, `num_rewards` returning None\")\n      return None\n    min_reward, max_reward = self.reward_range\n    return max_reward - min_reward + 1",
    "docstring": "Returns the number of distinct rewards.\n\n    Returns:\n      Returns None if the reward range is infinite or the processed rewards\n      aren't discrete, otherwise returns the number of distinct rewards."
  },
  {
    "code": "def libvlc_video_set_deinterlace(p_mi, psz_mode):\n    f = _Cfunctions.get('libvlc_video_set_deinterlace', None) or \\\n        _Cfunction('libvlc_video_set_deinterlace', ((1,), (1,),), None,\n                    None, MediaPlayer, ctypes.c_char_p)\n    return f(p_mi, psz_mode)",
    "docstring": "Enable or disable deinterlace filter.\n    @param p_mi: libvlc media player.\n    @param psz_mode: type of deinterlace filter, NULL to disable."
  },
  {
    "code": "def exclude(self, minimum_address, maximum_address):\n        if maximum_address < minimum_address:\n            raise Error('bad address range')\n        minimum_address *= self.word_size_bytes\n        maximum_address *= self.word_size_bytes\n        self._segments.remove(minimum_address, maximum_address)",
    "docstring": "Exclude given range and keep the rest.\n\n        `minimum_address` is the first word address to exclude\n        (including).\n\n        `maximum_address` is the last word address to exclude\n        (excluding)."
  },
  {
    "code": "def index(value, array):\n    i = array.searchsorted(value)\n    if i == len(array): return -1\n    else:               return i",
    "docstring": "Array search that behaves like I want it to. Totally dumb, I know."
  },
  {
    "code": "def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None,\n            region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    r = {}\n    try:\n        ciphertext = conn.encrypt(\n            key_id,\n            plaintext,\n            encryption_context=encryption_context,\n            grant_tokens=grant_tokens\n        )\n        r['ciphertext'] = ciphertext['CiphertextBlob']\n    except boto.exception.BotoServerError as e:\n        r['error'] = __utils__['boto.get_error'](e)\n    return r",
    "docstring": "Encrypt plaintext into cipher text using specified key.\n\n    CLI example::\n\n        salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{\"aws:username\":\"myuser\"}'"
  },
  {
    "code": "def rm_prefix(name):\n    if name.startswith('nova_'):\n        return name[5:]\n    elif name.startswith('novaclient_'):\n        return name[11:]\n    elif name.startswith('os_'):\n        return name[3:]\n    else:\n        return name",
    "docstring": "Removes nova_ os_ novaclient_ prefix from string."
  },
  {
    "code": "def _support_op(*args):\n        def inner(func):\n            for one_arg in args:\n                _op_mapping_[one_arg] = func\n            return func\n        return inner",
    "docstring": "Internal decorator to define an criteria compare operations."
  },
  {
    "code": "def last_modified(self):\n        last_modified = time.strftime(\n            \"%a, %d %b %Y %H:%M:%S GMT\",\n            time.gmtime(time.time()))\n        return last_modified",
    "docstring": "Get the HTTP-datetime of when the collection was modified."
  },
  {
    "code": "def _cwlvar_to_wdl(var):\n    if isinstance(var, (list, tuple)):\n        return [_cwlvar_to_wdl(x) for x in var]\n    elif isinstance(var, dict):\n        assert var.get(\"class\") == \"File\", var\n        return var.get(\"path\") or var[\"value\"]\n    else:\n        return var",
    "docstring": "Convert a CWL output object into a WDL output.\n\n    This flattens files and other special CWL outputs that are\n    plain strings in WDL."
  },
  {
    "code": "def reloadFileOfCurrentItem(self, rtiRegItem=None):\n        logger.debug(\"reloadFileOfCurrentItem, rtiClass={}\".format(rtiRegItem))\n        currentIndex = self.getRowCurrentIndex()\n        if not currentIndex.isValid():\n            return\n        currentItem, _ = self.getCurrentItem()\n        oldPath = currentItem.nodePath\n        fileRtiIndex = self.model().findFileRtiIndex(currentIndex)\n        isExpanded = self.isExpanded(fileRtiIndex)\n        if rtiRegItem is None:\n            rtiClass = None\n        else:\n            rtiRegItem.tryImportClass()\n            rtiClass = rtiRegItem.cls\n        newRtiIndex = self.model().reloadFileAtIndex(fileRtiIndex, rtiClass=rtiClass)\n        try:\n            _lastItem, lastIndex = self.expandPath(oldPath)\n            self.setCurrentIndex(lastIndex)\n            return lastIndex\n        except Exception as ex:\n            logger.warning(\"Unable to select {!r} beause of: {}\".format(oldPath, ex))\n            self.setExpanded(newRtiIndex, isExpanded)\n            self.setCurrentIndex(newRtiIndex)\n            return newRtiIndex",
    "docstring": "Finds the repo tree item that holds the file of the current item and reloads it.\n            Reloading is done by removing the repo tree item and inserting a new one.\n\n            The new item will have by of type rtiRegItem.cls. If rtiRegItem is None (the default),\n            the new rtiClass will be the same as the old one.\n            The rtiRegItem.cls will be imported. If this fails the old class will be used, and a\n            warning will be logged."
  },
  {
    "code": "def show_partitioning(rdd, show=True):\n    if show:\n        partitionCount = rdd.getNumPartitions()\n        try:\n            valueCount = rdd.countApprox(1000, confidence=0.50)\n        except:\n            valueCount = -1\n        try:\n            name = rdd.name() or None\n        except:\n            pass\n        name = name or \"anonymous\"\n        logging.info(\"For RDD %s, there are %d partitions with on average %s values\" % \n                     (name, partitionCount, int(valueCount/float(partitionCount))))",
    "docstring": "Seems to be significantly more expensive on cluster than locally"
  },
  {
    "code": "def on_show_mainframe(self, event):\n        self.parent.Enable()\n        self.parent.Show()\n        self.parent.Raise()",
    "docstring": "Show mainframe window"
  },
  {
    "code": "def patch_sys(self, inherit_path):\n    def patch_dict(old_value, new_value):\n      old_value.clear()\n      old_value.update(new_value)\n    def patch_all(path, path_importer_cache, modules):\n      sys.path[:] = path\n      patch_dict(sys.path_importer_cache, path_importer_cache)\n      patch_dict(sys.modules, modules)\n    new_sys_path, new_sys_path_importer_cache, new_sys_modules = self.minimum_sys(inherit_path)\n    new_sys_path.extend(merge_split(self._pex_info.pex_path, self._vars.PEX_PATH))\n    patch_all(new_sys_path, new_sys_path_importer_cache, new_sys_modules)",
    "docstring": "Patch sys with all site scrubbed."
  },
  {
    "code": "def draw_polygon(\n            self,\n            *pts,\n            close_path:bool=True,\n            stroke:Color=None,\n            stroke_width:float=1,\n            stroke_dash:typing.Sequence=None,\n            fill:Color=None\n            ) -> None:\n        pass",
    "docstring": "Draws the given linear path."
  },
  {
    "code": "def delete_security_group_rule(self, sec_grp_rule_id):\n        ret = self.network_conn.delete_security_group_rule(\n            security_group_rule=sec_grp_rule_id)\n        return ret if ret else True",
    "docstring": "Deletes the specified security group rule"
  },
  {
    "code": "def list_submissions():\n    submissions = []\n    try:\n        submissions = session.query(Submission).all()\n    except SQLAlchemyError as e:\n        session.rollback()\n    return render_template('list_submissions.html', submissions=submissions)",
    "docstring": "List the past submissions with information about them"
  },
  {
    "code": "def bytes(num, check_result=False):\n    if num <= 0:\n        raise ValueError(\"'num' should be > 0\")\n    buf = create_string_buffer(num)\n    result = libcrypto.RAND_bytes(buf, num)\n    if check_result and result == 0:\n        raise RandError(\"Random Number Generator not seeded sufficiently\")\n    return buf.raw[:num]",
    "docstring": "Returns num bytes of cryptographically strong pseudo-random\n    bytes. If checkc_result is True, raises error if PRNG is not\n    seeded enough"
  },
  {
    "code": "def export_chat_invite_link(\n        self,\n        chat_id: Union[int, str]\n    ) -> str:\n        peer = self.resolve_peer(chat_id)\n        if isinstance(peer, types.InputPeerChat):\n            return self.send(\n                functions.messages.ExportChatInvite(\n                    peer=peer.chat_id\n                )\n            ).link\n        elif isinstance(peer, types.InputPeerChannel):\n            return self.send(\n                functions.channels.ExportInvite(\n                    channel=peer\n                )\n            ).link",
    "docstring": "Use this method to generate a new invite link for a chat; any previously generated link is revoked.\n\n        You must be an administrator in the chat for this to work and have the appropriate admin rights.\n\n        Args:\n            chat_id (``int`` | ``str``):\n                Unique identifier for the target chat or username of the target channel/supergroup\n                (in the format @username).\n\n        Returns:\n            On success, the exported invite link as string is returned.\n\n        Raises:\n            :class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error."
  },
  {
    "code": "def to_dict(self):\n        def is_non_native_sc(ty, encoded):\n            return (ty == 'StringCounter'\n                    and not is_native_string_counter(encoded))\n        fc = {}\n        native = ('StringCounter', 'Unicode')\n        for name, feat in self._features.iteritems():\n            if name.startswith(self.EPHEMERAL_PREFIX):\n                continue\n            if not isinstance(name, unicode):\n                name = name.decode('utf-8')\n            tyname = registry.feature_type_name(name, feat)\n            encoded = registry.get(tyname).dumps(feat)\n            if tyname not in native or is_non_native_sc(tyname, encoded):\n                encoded = cbor.Tag(cbor_names_to_tags[tyname], encoded)\n            fc[name] = encoded\n        return fc",
    "docstring": "Dump a feature collection's features to a dictionary.\n\n        This does not include additional data, such as whether\n        or not the collection is read-only.  The returned dictionary\n        is suitable for serialization into JSON, CBOR, or similar\n        data formats."
  },
  {
    "code": "def slugify(s, delimiter='-'):\n    s = unicodedata.normalize('NFKD', to_unicode(s)).encode('ascii', 'ignore').decode('ascii')\n    return RE_SLUG.sub(delimiter, s).strip(delimiter).lower()",
    "docstring": "Normalize `s` into ASCII and replace non-word characters with `delimiter`."
  },
  {
    "code": "def pack(self, value, nocheck=False, major=DEFAULT_KATCP_MAJOR):\n        if value is None:\n            value = self.get_default()\n        if value is None:\n            raise ValueError(\"Cannot pack a None value.\")\n        if not nocheck:\n            self.check(value, major)\n        return self.encode(value, major)",
    "docstring": "Return the value formatted as a KATCP parameter.\n\n        Parameters\n        ----------\n        value : object\n            The value to pack.\n        nocheck : bool, optional\n            Whether to check that the value is valid before\n            packing it.\n        major : int, optional\n            Major version of KATCP to use when interpreting types.\n            Defaults to latest implemented KATCP version.\n\n        Returns\n        -------\n        packed_value : str\n            The unescaped KATCP string representing the value."
  },
  {
    "code": "def AddValue(self, name, number, aliases=None, description=None):\n    if name in self.values_per_name:\n      raise KeyError('Value with name: {0:s} already exists.'.format(name))\n    if number in self.values_per_number:\n      raise KeyError('Value with number: {0!s} already exists.'.format(number))\n    for alias in aliases or []:\n      if alias in self.values_per_alias:\n        raise KeyError('Value with alias: {0:s} already exists.'.format(alias))\n    enumeration_value = EnumerationValue(\n        name, number, aliases=aliases, description=description)\n    self.values.append(enumeration_value)\n    self.values_per_name[name] = enumeration_value\n    self.values_per_number[number] = enumeration_value\n    for alias in aliases or []:\n      self.values_per_alias[alias] = enumeration_value",
    "docstring": "Adds an enumeration value.\n\n    Args:\n      name (str): name.\n      number (int): number.\n      aliases (Optional[list[str]]): aliases.\n      description (Optional[str]): description.\n\n    Raises:\n      KeyError: if the enumeration value already exists."
  },
  {
    "code": "def flatten(self):\n    ls = [self.output]\n    ls.extend(self.state)\n    return ls",
    "docstring": "Create a flattened version by putting output first and then states."
  },
  {
    "code": "def genealogic_types(self):\n        types = []\n        parent = self\n        while parent:\n            types.append(parent.rest_name)\n            parent = parent.parent_object\n        return types",
    "docstring": "Get genealogic types\n\n            Returns:\n                Returns a list of all parent types"
  },
  {
    "code": "def _check_message_valid(msg):\n    try:\n        if int(msg[:2], 16) != (len(msg) - 2):\n            raise ValueError(\"Elk message length incorrect\")\n        _check_checksum(msg)\n    except IndexError:\n        raise ValueError(\"Elk message length incorrect\")",
    "docstring": "Check packet length valid and that checksum is good."
  },
  {
    "code": "def from_json(cls, data, result=None):\n        if data.get(\"type\") != cls._type_value:\n            raise exception.ElementDataWrongType(\n                type_expected=cls._type_value,\n                type_provided=data.get(\"type\")\n            )\n        ref = data.get(\"ref\")\n        role = data.get(\"role\")\n        attributes = {}\n        ignore = [\"geometry\", \"type\", \"ref\", \"role\"]\n        for n, v in data.items():\n            if n in ignore:\n                continue\n            attributes[n] = v\n        geometry = data.get(\"geometry\")\n        if isinstance(geometry, list):\n            geometry_orig = geometry\n            geometry = []\n            for v in geometry_orig:\n                geometry.append(\n                    RelationWayGeometryValue(\n                        lat=v.get(\"lat\"),\n                        lon=v.get(\"lon\")\n                    )\n                )\n        else:\n            geometry = None\n        return cls(\n            attributes=attributes,\n            geometry=geometry,\n            ref=ref,\n            role=role,\n            result=result\n        )",
    "docstring": "Create new RelationMember element from JSON data\n\n        :param child: Element data from JSON\n        :type child: Dict\n        :param result: The result this element belongs to\n        :type result: overpy.Result\n        :return: New instance of RelationMember\n        :rtype: overpy.RelationMember\n        :raises overpy.exception.ElementDataWrongType: If type value of the passed JSON data does not match."
  },
  {
    "code": "def clone(module: torch.nn.Module, num_copies: int) -> torch.nn.ModuleList:\n    return torch.nn.ModuleList([copy.deepcopy(module) for _ in range(num_copies)])",
    "docstring": "Produce N identical layers."
  },
  {
    "code": "def exponentialRDD(sc, mean, size, numPartitions=None, seed=None):\n        return callMLlibFunc(\"exponentialRDD\", sc._jsc, float(mean), size, numPartitions, seed)",
    "docstring": "Generates an RDD comprised of i.i.d. samples from the Exponential\n        distribution with the input mean.\n\n        :param sc: SparkContext used to create the RDD.\n        :param mean: Mean, or 1 / lambda, for the Exponential distribution.\n        :param size: Size of the RDD.\n        :param numPartitions: Number of partitions in the RDD (default: `sc.defaultParallelism`).\n        :param seed: Random seed (default: a random long integer).\n        :return: RDD of float comprised of i.i.d. samples ~ Exp(mean).\n\n        >>> mean = 2.0\n        >>> x = RandomRDDs.exponentialRDD(sc, mean, 1000, seed=2)\n        >>> stats = x.stats()\n        >>> stats.count()\n        1000\n        >>> abs(stats.mean() - mean) < 0.5\n        True\n        >>> from math import sqrt\n        >>> abs(stats.stdev() - sqrt(mean)) < 0.5\n        True"
  },
  {
    "code": "def mesh_axis_to_tensor_axis(self, mesh_ndims):\n    ta2ma = self._tensor_axis_to_mesh_axis\n    return tuple(\n        [ta2ma.index(mesh_axis) if mesh_axis in ta2ma else None\n         for mesh_axis in xrange(mesh_ndims)])",
    "docstring": "For each mesh axis, which Tensor axis maps to it.\n\n    Args:\n      mesh_ndims: int.\n\n    Returns:\n      Tuple of optional integers, with length mesh_ndims."
  },
  {
    "code": "def decrypt(self, data, oaep_hash_fn_name=None, mgf1_hash_fn_name=None):\n\t\tif self.__private_key is None:\n\t\t\traise ValueError('Unable to call this method. Private key must be set')\n\t\tif oaep_hash_fn_name is None:\n\t\t\toaep_hash_fn_name = self.__class__.__default_oaep_hash_function_name__\n\t\tif mgf1_hash_fn_name is None:\n\t\t\tmgf1_hash_fn_name = self.__class__.__default_mgf1_hash_function_name__\n\t\toaep_hash_cls = getattr(hashes, oaep_hash_fn_name)\n\t\tmgf1_hash_cls = getattr(hashes, mgf1_hash_fn_name)\n\t\treturn self.__private_key.decrypt(\n\t\t\tdata,\n\t\t\tpadding.OAEP(\n\t\t\t\tmgf=padding.MGF1(algorithm=mgf1_hash_cls()),\n\t\t\t\talgorithm=oaep_hash_cls(),\n\t\t\t\tlabel=None\n\t\t\t)\n\t\t)",
    "docstring": "Decrypt a data that used PKCS1 OAEP protocol\n\n\t\t:param data: data to decrypt\n\t\t:param oaep_hash_fn_name: hash function name to use with OAEP\n\t\t:param mgf1_hash_fn_name: hash function name to use with MGF1 padding\n\t\t:return: bytes"
  },
  {
    "code": "def process_response(self, request, response):\n        if self._is_enabled():\n            log_prefix = self._log_prefix(u\"After\", request)\n            new_memory_data = self._memory_data(log_prefix)\n            log_prefix = self._log_prefix(u\"Diff\", request)\n            cached_memory_data_response = self._cache.get_cached_response(self.memory_data_key)\n            old_memory_data = cached_memory_data_response.get_value_or_default(None)\n            self._log_diff_memory_data(log_prefix, new_memory_data, old_memory_data)\n        return response",
    "docstring": "Logs memory data after processing response."
  },
  {
    "code": "def _build_instruction_ds(instructions):\n  tensor_inputs = {\n      k: np.array(vals, dtype=np.int64) if k == \"mask_offset\" else list(vals)\n      for k, vals in utils.zip_dict(*instructions)\n  }\n  return tf.data.Dataset.from_tensor_slices(tensor_inputs)",
    "docstring": "Create a dataset containing individual instruction for each shard.\n\n  Each instruction is a dict:\n  ```\n  {\n      \"filepath\": tf.Tensor(shape=(), dtype=tf.string),\n      \"mask_offset\": tf.Tensor(shape=(), dtype=tf.int64),\n      \"mask\": tf.Tensor(shape=(100,), dtype=tf.bool),\n  }\n  ```\n\n  Args:\n    instructions: `list[dict]`, the list of instruction dict\n\n  Returns:\n    instruction_ds: The dataset containing the instruction. The dataset size is\n      the number of shard."
  },
  {
    "code": "def fuzzy_search(self, *filters):\n        matches = []\n        logger.verbose(\n            \"Performing fuzzy search on %s (%s) ..\", pluralize(len(filters), \"pattern\"), concatenate(map(repr, filters))\n        )\n        patterns = list(map(create_fuzzy_pattern, filters))\n        for entry in self.filtered_entries:\n            if all(p.search(entry.name) for p in patterns):\n                matches.append(entry)\n        logger.log(\n            logging.INFO if matches else logging.VERBOSE,\n            \"Matched %s using fuzzy search.\",\n            pluralize(len(matches), \"password\"),\n        )\n        return matches",
    "docstring": "Perform a \"fuzzy\" search that matches the given characters in the given order.\n\n        :param filters: The pattern(s) to search for.\n        :returns: The matched password names (a list of strings)."
  },
  {
    "code": "def format(self, record):\n        out = dict(\n            Timestamp=int(record.created * 1e9),\n            Type=record.name,\n            Logger=self.logger_name,\n            Hostname=self.hostname,\n            EnvVersion=self.LOGGING_FORMAT_VERSION,\n            Severity=self.SYSLOG_LEVEL_MAP.get(record.levelno,\n                                               self.DEFAULT_SYSLOG_LEVEL),\n            Pid=record.process,\n        )\n        fields = dict()\n        for key, value in record.__dict__.items():\n            if key not in self.EXCLUDED_LOGRECORD_ATTRS:\n                fields[key] = value\n        message = record.getMessage()\n        if message:\n            if not message.startswith(\"{\") and not message.endswith(\"}\"):\n                fields[\"msg\"] = message\n        if record.exc_info is not None:\n            fields[\"error\"] = repr(record.exc_info[1])\n            fields[\"traceback\"] = safer_format_traceback(*record.exc_info)\n        out['Fields'] = fields\n        return json.dumps(out)",
    "docstring": "Map from Python LogRecord attributes to JSON log format fields\n\n        * from - https://docs.python.org/3/library/logging.html#logrecord-attributes\n        * to - https://mana.mozilla.org/wiki/pages/viewpage.action?pageId=42895640"
  },
  {
    "code": "def buff_interaction_eval(cls, specification, sequences, parameters,\n                              **kwargs):\n        instance = cls(specification,\n                       sequences,\n                       parameters,\n                       build_fn=default_build,\n                       eval_fn=buff_interaction_eval,\n                       **kwargs)\n        return instance",
    "docstring": "Creates optimizer with default build and BUFF interaction eval.\n\n        Notes\n        -----\n        Any keyword arguments will be propagated down to BaseOptimizer.\n\n        Parameters\n        ----------\n        specification : ampal.assembly.specification\n            Any assembly level specification.\n        sequences : [str]\n            A list of sequences, one for each polymer.\n        parameters : [base_ev_opt.Parameter]\n            A list of `Parameter` objects in the same order as the\n            function signature expects."
  },
  {
    "code": "def LockedRead(self):\n        file_contents = None\n        with self._thread_lock:\n            if not self._EnsureFileExists():\n                return None\n            with self._process_lock_getter() as acquired_plock:\n                if not acquired_plock:\n                    return None\n                with open(self._filename, 'rb') as f:\n                    file_contents = f.read().decode(encoding=self._encoding)\n        return file_contents",
    "docstring": "Acquire an interprocess lock and dump cache contents.\n\n        This method safely acquires the locks then reads a string\n        from the cache file. If the file does not exist and cannot\n        be created, it will return None. If the locks cannot be\n        acquired, this will also return None.\n\n        Returns:\n          cache data - string if present, None on failure."
  },
  {
    "code": "def read_character_string(self):\n        length = ord(self.data[self.offset])\n        self.offset += 1\n        return self.read_string(length)",
    "docstring": "Reads a character string from the packet"
  },
  {
    "code": "def dumps(self, o):\n        f = io.BytesIO()\n        VaultPickler(self, f).dump(o)\n        f.seek(0)\n        return f.read()",
    "docstring": "Returns a serialized string representing the object, post-deduplication.\n\n        :param o: the object"
  },
  {
    "code": "def log_request_end_send(self, target_system, target_component, force_mavlink1=False):\n                return self.send(self.log_request_end_encode(target_system, target_component), force_mavlink1=force_mavlink1)",
    "docstring": "Stop log transfer and resume normal logging\n\n                target_system             : System ID (uint8_t)\n                target_component          : Component ID (uint8_t)"
  },
  {
    "code": "def flatten_dict(d,\n                 parent_key='', sep='.',\n                 ignore_under_prefixed=True,\n                 mark_value=True):\n    items = {}\n    for k in d:\n        if ignore_under_prefixed and k.startswith('__'): continue\n        v = d[k]\n        if mark_value and k.startswith('_') and not k.startswith('__'):\n            v = MarkValue(repr(v))\n        new_key = sep.join((parent_key, k)) if parent_key else k\n        if isinstance(v, collections.MutableMapping):\n            items.update(flatten_dict(v, new_key, sep=sep,\n                                        ignore_under_prefixed=True,\n                                        mark_value=True)\n                            )\n        else:\n            items[new_key] = v\n    return items",
    "docstring": "Flattens a nested dictionary\n\n    >>> from pprint import pprint\n    >>> d = {\"a\": {\"b\": {\"c\": 1, \"b\": 2, \"__d\": 'ignore', \"_e\": \"mark\"} } }\n    >>> fd = flatten_dict(d)\n    >>> pprint(fd)\n    {'a.b._e': \"'mark'\", 'a.b.b': 2, 'a.b.c': 1}"
  },
  {
    "code": "def set_environ(env_name, value):\n    value_changed = value is not None\n    if value_changed:\n        old_value = os.environ.get(env_name)\n        os.environ[env_name] = value\n    try:\n        yield\n    finally:\n        if value_changed:\n            if old_value is None:\n                del os.environ[env_name]\n            else:\n                os.environ[env_name] = old_value",
    "docstring": "Set the environment variable 'env_name' to 'value'\n\n    Save previous value, yield, and then restore the previous value stored in\n    the environment variable 'env_name'.\n\n    If 'value' is None, do nothing"
  },
  {
    "code": "def sign(self, msg, key):\n        hasher = hashes.Hash(self.hash_algorithm(), backend=default_backend())\n        hasher.update(msg)\n        digest = hasher.finalize()\n        sig = key.sign(\n            digest,\n            padding.PSS(\n                mgf=padding.MGF1(self.hash_algorithm()),\n                salt_length=padding.PSS.MAX_LENGTH),\n            utils.Prehashed(self.hash_algorithm()))\n        return sig",
    "docstring": "Create a signature over a message\n\n        :param msg: The message\n        :param key: The key\n        :return: A signature"
  },
  {
    "code": "def save_x509s(self, x509s):\n        for file_type in TLSFileType:\n            if file_type.value in x509s:\n                x509 = x509s[file_type.value]\n                if file_type is not TLSFileType.CA:\n                    tlsfile = getattr(self, file_type.value)\n                    if tlsfile:\n                        tlsfile.save(x509)",
    "docstring": "Saves the x509 objects to the paths known by this bundle"
  },
  {
    "code": "def hourly(dt=datetime.datetime.utcnow(), fmt=None):\n    date = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, 1, 1, 0, dt.tzinfo)\n    if fmt is not None:\n        return date.strftime(fmt)\n    return date",
    "docstring": "Get a new datetime object every hour."
  },
  {
    "code": "def read_group(self, group_id, mount_point=DEFAULT_MOUNT_POINT):\n        api_path = '/v1/{mount_point}/group/id/{id}'.format(\n            mount_point=mount_point,\n            id=group_id,\n        )\n        response = self._adapter.get(\n            url=api_path,\n        )\n        return response.json()",
    "docstring": "Query the group by its identifier.\n\n        Supported methods:\n            GET: /{mount_point}/group/id/{id}. Produces: 200 application/json\n\n        :param group_id: Identifier of the group.\n        :type group_id: str | unicode\n        :param mount_point: The \"path\" the method/backend was mounted on.\n        :type mount_point: str | unicode\n        :return: The JSON response of the request.\n        :rtype: requests.Response"
  },
  {
    "code": "def register(self, cls, instance):\n        if not issubclass(cls, DropletInterface):\n            raise TypeError('Given class is not a NAZInterface subclass: %s'\n                            % cls)\n        if not isinstance(instance, cls):\n            raise TypeError('Given instance does not implement the class: %s'\n                            % instance)\n        if instance.name in self.INSTANCES_BY_NAME:\n            if self.INSTANCES_BY_NAME[instance.name] != instance:\n                raise ValueError('Given name is registered '\n                                 'by other instance: %s' % instance.name)\n        self.INSTANCES_BY_INTERFACE[cls].add(instance)\n        self.INSTANCES_BY_NAME[instance.name] = instance",
    "docstring": "Register the given instance as implementation for a class interface"
  },
  {
    "code": "def get_user(self, userPk):\n        r = self._request('user/' + str(userPk))\n        if r:\n            u = User()\n            u.pk = u.id = userPk\n            u.__dict__.update(r.json())\n            return u\n        return None",
    "docstring": "Returns the user specified with the user's Pk or UUID"
  },
  {
    "code": "def create_api_network_ipv6(self):\n        return ApiNetworkIPv6(\n            self.networkapi_url,\n            self.user,\n            self.password,\n            self.user_ldap)",
    "docstring": "Get an instance of Api Networkv6 services facade."
  },
  {
    "code": "def batch(iterable, size):\n    item = iter(iterable)\n    while True:\n        batch_iterator = islice(item, size)\n        try:\n            yield chain([next(batch_iterator)], batch_iterator)\n        except StopIteration:\n            return",
    "docstring": "Get items from a sequence a batch at a time.\n\n    .. note:\n\n        Adapted from\n        https://code.activestate.com/recipes/303279-getting-items-in-batches/.\n\n\n    .. note:\n\n        All batches must be exhausted immediately.\n\n    :params iterable: An iterable to get batches from.\n    :params size: Size of the batches.\n    :returns: A new batch of the given size at each time.\n\n    >>> [list(i) for i in batch([1, 2, 3, 4, 5], 2)]\n    [[1, 2], [3, 4], [5]]"
  },
  {
    "code": "def cors_setup(self, request):\n        def cors_headers(request, response):\n            if request.method.lower() == 'options':\n                response.headers.update({\n                    '-'.join([p.capitalize() for p in k.split('_')]): v\n                    for k, v in self.cors_options.items()\n                })\n            else:\n                origin = self.cors_options.get('access_control_allow_origin', '*')\n                expose_headers = self.cors_options.get('access_control_expose_headers', '')\n                response.headers['Access-Control-Allow-Origin'] = origin\n                if expose_headers:\n                    response.headers['Access-Control-Expose-Headers'] = expose_headers\n        request.add_response_callback(cors_headers)",
    "docstring": "Sets up the CORS headers response based on the settings used for the API.\n\n        :param request: <pyramid.request.Request>"
  },
  {
    "code": "def load_handler(self):\n        handler_path = self.handler_name.split(\".\")\n        handler_module = __import__(\".\".join(handler_path[:-1]), {}, {}, str(handler_path[-1]))\n        self.handler = getattr(handler_module, handler_path[-1])()",
    "docstring": "Load the detected handler."
  },
  {
    "code": "def check_extracted_paths(namelist, subdir=None):\n    def relpath(p):\n        q = os.path.relpath(p)\n        if p.endswith(os.path.sep) or p.endswith('/'):\n            q += os.path.sep\n        return q\n    parent = os.path.abspath('.')\n    if subdir:\n        if os.path.isabs(subdir):\n            raise FileException('subdir must be a relative path', subdir)\n        subdir = relpath(subdir + os.path.sep)\n    for name in namelist:\n        if os.path.commonprefix([parent, os.path.abspath(name)]) != parent:\n            raise FileException('Insecure path in zipfile', name)\n        if subdir and os.path.commonprefix(\n                [subdir, relpath(name)]) != subdir:\n            raise FileException(\n                'Path in zipfile is not in required subdir', name)",
    "docstring": "Check whether zip file paths are all relative, and optionally in a\n    specified subdirectory, raises an exception if not\n\n    namelist: A list of paths from the zip file\n    subdir: If specified then check whether all paths in the zip file are\n      under this subdirectory\n\n    Python docs are unclear about the security of extract/extractall:\n    https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.extractall\n    https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.extract"
  },
  {
    "code": "def add_custom_feature(self, feature):\n        if feature.dimension <= 0:\n            raise ValueError(\"Dimension has to be positive. \"\n                             \"Please override dimension attribute in feature!\")\n        if not hasattr(feature, 'transform'):\n            raise ValueError(\"no 'transform' method in given feature\")\n        elif not callable(getattr(feature, 'transform')):\n            raise ValueError(\"'transform' attribute exists but is not a method\")\n        self.__add_feature(feature)",
    "docstring": "Adds a custom feature to the feature list.\n\n        Parameters\n        ----------\n        feature : object\n            an object with interface like CustomFeature (map, describe methods)"
  },
  {
    "code": "def get_nth_unique_value(self, keypath, n, distance_from, open_interval=True):\n        unique_values = self.get_ordered_values(keypath, distance_from, open_interval)\n        if 0 <= n < len(unique_values):\n            return unique_values[n]\n        else:\n            raise Contradiction(\"n-th Unique value out of range: \" + str(n))",
    "docstring": "Returns the `n-1`th unique value, or raises\n        a contradiction if that is out of bounds"
  },
  {
    "code": "def content(self, name, attrs=None, characters=None):\n    with self.no_inner_space(outer=True):\n      with self.element(name, attrs):\n        if characters:\n          self.characters(characters)",
    "docstring": "Writes an element, some content for the element, and then closes the element, all without\n    indentation.\n\n    :name: the name of the element\n    :attrs: a dict of attributes\n    :characters: the characters to write"
  },
  {
    "code": "def set_widgets(self):\n        self.tvBrowserExposure_selection_changed()\n        exposure = self.parent.step_fc_functions1.selected_value(\n            layer_purpose_exposure['key'])\n        icon_path = get_image_path(exposure)\n        self.lblIconIFCWExposureFromBrowser.setPixmap(QPixmap(icon_path))",
    "docstring": "Set widgets on the Exposure Layer From Browser tab."
  },
  {
    "code": "def _add_data_to_general_stats(self, data):\n    headers = _get_general_stats_headers()\n    self.general_stats_headers.update(headers)\n    header_names = ('ERROR_count', 'WARNING_count', 'file_validation_status')\n    general_data = dict()\n    for sample in data:\n        general_data[sample] = {column: data[sample][column] for column in header_names}\n        if sample not in self.general_stats_data:\n            self.general_stats_data[sample] = dict()\n        if data[sample]['file_validation_status'] != 'pass':\n            headers['file_validation_status']['hidden'] = False\n        self.general_stats_data[sample].update(general_data[sample])",
    "docstring": "Add data for the general stats in a Picard-module specific manner"
  },
  {
    "code": "def set_value(self, visual_property, value):\n        if visual_property is None or value is None:\n            raise ValueError('Both VP and value are required.')\n        new_value = [\n            {\n                'visualProperty': visual_property,\n                \"value\": value\n            }\n        ]\n        requests.put(self.url, data=json.dumps(new_value), headers=HEADERS)",
    "docstring": "Set a single Visual Property Value\n\n        :param visual_property: Visual Property ID\n        :param value: New value for the VP\n        :return: None"
  },
  {
    "code": "def build(self):\n        for cmd in self.build_cmds:\n            log.info('building command: {}'.format(cmd))\n            full_cmd = 'cd {}; {}'.format(self.analyses_path, cmd)\n            log.debug('full command: {}'.format(full_cmd))\n            subprocess.call(full_cmd, shell=True)\n            log.info('build done')",
    "docstring": "Run the build command specified in index.yaml."
  },
  {
    "code": "def _dict_factory(cursor, row):\n        d = {}\n        for idx, col in enumerate(cursor.description):\n            if col[0] == 'rowid':\n                d['_id'] = row[idx]\n            else:\n                d[col[0]] = row[idx]\n        return d",
    "docstring": "factory for sqlite3 to return results as dict"
  },
  {
    "code": "def get_art(cache_dir, size, client):\n    song = client.currentsong()\n    if len(song) < 2:\n        print(\"album: Nothing currently playing.\")\n        return\n    file_name = f\"{song['artist']}_{song['album']}_{size}.jpg\".replace(\"/\", \"\")\n    file_name = cache_dir / file_name\n    if file_name.is_file():\n        shutil.copy(file_name, cache_dir / \"current.jpg\")\n        print(\"album: Found cached art.\")\n    else:\n        print(\"album: Downloading album art...\")\n        brainz.init()\n        album_art = brainz.get_cover(song, size)\n        if album_art:\n            util.bytes_to_file(album_art, cache_dir / file_name)\n            util.bytes_to_file(album_art, cache_dir / \"current.jpg\")\n            print(f\"album: Swapped art to {song['artist']}, {song['album']}.\")",
    "docstring": "Get the album art."
  },
  {
    "code": "def absent(name, domain, user=None):\n    ret = {'name': name,\n           'result': True,\n           'comment': '',\n           'changes': {}}\n    out = __salt__['macdefaults.delete'](domain, name, user)\n    if out['retcode'] != 0:\n        ret['comment'] += \"{0} {1} is already absent\".format(domain, name)\n    else:\n        ret['changes']['absent'] = \"{0} {1} is now absent\".format(domain, name)\n    return ret",
    "docstring": "Make sure the defaults value is absent\n\n    name\n        The key of the given domain to remove\n\n    domain\n        The name of the domain to remove from\n\n    user\n        The user to write the defaults to"
  },
  {
    "code": "def username(self, default=None):\n        if self.lis_person_name_given:\n            return self.lis_person_name_given\n        elif self.lis_person_name_family:\n            return self.lis_person_name_family\n        elif self.lis_person_name_full:\n            return self.lis_person_name_full\n        else:\n            return default",
    "docstring": "Return the full, given, or family name if set."
  },
  {
    "code": "def set_args(self, **kwargs):\n        try:\n            kwargs_items = kwargs.iteritems()\n        except AttributeError:\n            kwargs_items = kwargs.items()\n        for key, val in kwargs_items:\n            self.args[key] = val",
    "docstring": "Set more arguments to self.args\n\n        args:\n            **kwargs:\n                key and value represents dictionary key and value"
  },
  {
    "code": "def json_encoder_default(obj):\n    if isinstance(obj, numbers.Integral) and (obj < min_safe_integer or obj > max_safe_integer):\n        return str(obj)\n    if isinstance(obj, np.integer):\n        return str(obj)\n    elif isinstance(obj, np.floating):\n        return float(obj)\n    elif isinstance(obj, np.ndarray):\n        return list(obj)\n    elif isinstance(obj, (set, frozenset)):\n        return list(obj)\n    raise TypeError",
    "docstring": "JSON encoder function that handles some numpy types."
  },
  {
    "code": "def dump(self):\n        f = h5py.File(self.h5file, 'w')\n        for i, k in enumerate(self.kwslist):\n            v = self.h5data[:, i]\n            dset = f.create_dataset(k, shape=v.shape, dtype=v.dtype)\n            dset[...] = v\n        f.close()",
    "docstring": "dump extracted data into a single hdf5file,\n\n        :return: None\n        :Example:\n\n\n        >>> # dump data into an hdf5 formated file\n        >>> datafields = ['s', 'Sx', 'Sy', 'enx', 'eny']\n        >>> datascript = 'sddsprintdata.sh'\n        >>> datapath   = './tests/tracking'\n        >>> hdf5file   = './tests/tracking/test.h5'\n        >>> A = DataExtracter('test.sig', *datafields)\n        >>> A.setDataScript(datascript)\n        >>> A.setDataPath  (datapath)\n        >>> A.setH5file    (hdf5file)\n        >>> A.extractData().dump()\n        >>>\n        >>> # read dumped file\n        >>> fd = h5py.File(hdf5file, 'r')\n        >>> d_s  = fd['s'][:]\n        >>> d_sx = fd['Sx'][:]\n        >>>\n        >>> # plot dumped data\n        >>> import matplotlib.pyplot as plt\n        >>> plt.figure(1)\n        >>> plt.plot(d_s, d_sx, 'r-')\n        >>> plt.xlabel('$s$')\n        >>> plt.ylabel('$\\sigma_x$')\n        >>> plt.show()\n\n        Just like the following figure shows:\n\n        .. image:: ../../images/test_DataExtracter.png\n            :width: 400px"
  },
  {
    "code": "def corpusindex():\n        corpora = []\n        for f in glob.glob(settings.ROOT + \"corpora/*\"):\n            if os.path.isdir(f):\n                corpora.append(os.path.basename(f))\n        return corpora",
    "docstring": "Get list of pre-installed corpora"
  },
  {
    "code": "def fast_combine_pairs(files, force_single, full_name, separators):\n    files = sort_filenames(files)\n    chunks = tz.sliding_window(10, files)\n    pairs = [combine_pairs(chunk, force_single, full_name, separators) for chunk in chunks]\n    pairs = [y for x in pairs for y in x]\n    longest = defaultdict(list)\n    for pair in pairs:\n        for file in pair:\n            if len(longest[file]) < len(pair):\n                longest[file] = pair\n    longest = {tuple(sort_filenames(x)) for x in longest.values()}\n    return [sort_filenames(list(x)) for x in longest]",
    "docstring": "assume files that need to be paired are within 10 entries of each other, once the list is sorted"
  },
  {
    "code": "def OnTableListToggle(self, event):\n        table_list_panel_info = \\\n            self.main_window._mgr.GetPane(\"table_list_panel\")\n        self._toggle_pane(table_list_panel_info)\n        event.Skip()",
    "docstring": "Table list toggle event handler"
  },
  {
    "code": "def _add_string_to_commastring(self, field, string):\n        if string in self._get_stringlist_from_commastring(field):\n            return False\n        strings = '%s,%s' % (self.data.get(field, ''), string)\n        if strings[0] == ',':\n            strings = strings[1:]\n        self.data[field] = strings\n        return True",
    "docstring": "Add a string to a comma separated list of strings\n\n        Args:\n            field (str): Field containing comma separated list\n            string (str): String to add\n\n        Returns:\n            bool: True if string added or False if string already present"
  },
  {
    "code": "def set_ignores(self, folder, *patterns):\n        if not patterns:\n            return {}\n        data = {'ignore': list(patterns)}\n        return self.post('ignores', params={'folder': folder}, data=data)",
    "docstring": "Applies ``patterns`` to ``folder``'s ``.stignore`` file.\n\n            Args:\n                folder (str):\n                patterns (str):\n\n            Returns:\n                dict"
  },
  {
    "code": "def expanduser(path):\n    if path[:1] != '~':\n        return path\n    i, n = 1, len(path)\n    while i < n and path[i] not in '/\\\\':\n        i = i + 1\n    if 'HOME' in os.environ:\n        userhome = os.environ['HOME']\n    elif 'USERPROFILE' in os.environ:\n        userhome = os.environ['USERPROFILE']\n    elif not 'HOMEPATH' in os.environ:\n        return path\n    else:\n        try:\n            drive = os.environ['HOMEDRIVE']\n        except KeyError:\n            drive = ''\n        userhome = join(drive, os.environ['HOMEPATH'])\n    if i != 1:\n        userhome = join(dirname(userhome), path[1:i])\n    return userhome + path[i:]",
    "docstring": "Expand ~ and ~user constructs.\n\n    If user or $HOME is unknown, do nothing."
  },
  {
    "code": "def loudest_time(self, start=0, duration=0):\n        if duration == 0:\n            duration = self.sound.nframes\n        self.current_frame = start\n        arr = self.read_frames(duration)\n        max_amp_sample = int(np.floor(arr.argmax()/2)) + start\n        return max_amp_sample",
    "docstring": "Find the loudest time in the window given by start and duration\n        Returns frame number in context of entire track, not just the window.\n\n        :param integer start: Start frame\n        :param integer duration: Number of frames to consider from start\n        :returns: Frame number of loudest frame\n        :rtype: integer"
  },
  {
    "code": "def parse_fallback(self):\n        if self.strict:\n            raise PywavefrontException(\"Unimplemented OBJ format statement '%s' on line '%s'\"\n                                       % (self.values[0], self.line.rstrip()))\n        else:\n            logger.warning(\"Unimplemented OBJ format statement '%s' on line '%s'\"\n                            % (self.values[0], self.line.rstrip()))",
    "docstring": "Fallback method when parser doesn't know the statement"
  },
  {
    "code": "def raw(self):\n        try:\n            return urlopen(str(self.url))\n        except HTTPError as error:\n            try:\n                parsed = self._parsejson(error)\n                exc = RequestError(parsed['message'])\n                exc.__cause__ = None\n                raise exc\n            except ValueError:\n                exc = StatbankError()\n                exc.__cause__ = None\n                raise exc",
    "docstring": "Make request to url and return the raw response object."
  },
  {
    "code": "def _set_raise_on_bulk_item_failure(self, raise_on_bulk_item_failure):\n        self._raise_on_bulk_item_failure = raise_on_bulk_item_failure\n        self.bulker.raise_on_bulk_item_failure = raise_on_bulk_item_failure",
    "docstring": "Set the raise_on_bulk_item_failure parameter\n\n        :param raise_on_bulk_item_failure a bool the status of the raise_on_bulk_item_failure"
  },
  {
    "code": "def _get_next_trial(self):\n        trials_done = all(trial.is_finished() for trial in self._trials)\n        wait_for_trial = trials_done and not self._search_alg.is_finished()\n        self._update_trial_queue(blocking=wait_for_trial)\n        with warn_if_slow(\"choose_trial_to_run\"):\n            trial = self._scheduler_alg.choose_trial_to_run(self)\n        return trial",
    "docstring": "Replenishes queue.\n\n        Blocks if all trials queued have finished, but search algorithm is\n        still not finished."
  },
  {
    "code": "def json_data(self):\n        return {\n            \"info_in_id\": self.info_in_id,\n            \"info_out_id\": self.info_out_id,\n            \"node_id\": self.node_id,\n            \"network_id\": self.network_id,\n        }",
    "docstring": "The json representation of a transformation."
  },
  {
    "code": "def scale_app(self, app_id, instances=None, delta=None, force=False):\n        if instances is None and delta is None:\n            marathon.log.error('instances or delta must be passed')\n            return\n        try:\n            app = self.get_app(app_id)\n        except NotFoundError:\n            marathon.log.error('App \"{app}\" not found'.format(app=app_id))\n            return\n        desired = instances if instances is not None else (\n            app.instances + delta)\n        return self.update_app(app.id, MarathonApp(instances=desired), force=force)",
    "docstring": "Scale an app.\n\n        Scale an app to a target number of instances (with `instances`), or scale the number of\n        instances up or down by some delta (`delta`). If the resulting number of instances would be negative,\n        desired instances will be set to zero.\n\n        If both `instances` and `delta` are passed, use `instances`.\n\n        :param str app_id: application ID\n        :param int instances: [optional] the number of instances to scale to\n        :param int delta: [optional] the number of instances to scale up or down by\n        :param bool force: apply even if a deployment is in progress\n\n        :returns: a dict containing the deployment id and version\n        :rtype: dict"
  },
  {
    "code": "def parse_limit(limit_def):\n    lower, upper = get_limits(limit_def)\n    reaction = limit_def.get('reaction')\n    return reaction, lower, upper",
    "docstring": "Parse a structured flux limit definition as obtained from a YAML file\n\n    Returns a tuple of reaction, lower and upper bound."
  },
  {
    "code": "def _title(self):\n        return (\n            'Overall, proteins from %d pathogen%s were found in %d sample%s.' %\n            (len(self.pathogenNames),\n             '' if len(self.pathogenNames) == 1 else 's',\n             len(self.sampleNames),\n             '' if len(self.sampleNames) == 1 else 's'))",
    "docstring": "Create a title summarizing the pathogens and samples.\n\n        @return: A C{str} title."
  },
  {
    "code": "def delete_scan(self, scan_id):\n        if self.get_scan_status(scan_id) == ScanStatus.RUNNING:\n            return 0\n        try:\n            del self.scan_processes[scan_id]\n        except KeyError:\n            logger.debug('Scan process for %s not found', scan_id)\n        return self.scan_collection.delete_scan(scan_id)",
    "docstring": "Deletes scan_id scan from collection.\n\n        @return: 1 if scan deleted, 0 otherwise."
  },
  {
    "code": "def exit_config_mode(self, exit_config=\"exit\", pattern=\"\"):\n        if not pattern:\n            pattern = re.escape(self.base_prompt)\n        return super(CiscoWlcSSH, self).exit_config_mode(exit_config, pattern)",
    "docstring": "Exit config_mode."
  },
  {
    "code": "def absolutize(self, region_id, relative_address):\n        if region_id == 'global':\n            return relative_address\n        if region_id not in self._region_id_to_address:\n            raise SimRegionMapError('Non-existent region ID \"%s\"' % region_id)\n        base_address = self._region_id_to_address[region_id].base_address\n        return base_address + relative_address",
    "docstring": "Convert a relative address in some memory region to an absolute address.\n\n        :param region_id:           The memory region ID\n        :param relative_address:    The relative memory offset in that memory region\n        :return:                    An absolute address if converted, or an exception is raised when region id does not\n                                    exist."
  },
  {
    "code": "def lookup_host_host(self, mac):\n\t\tres = self.lookup_by_host(mac=mac)\n\t\ttry:\n\t\t\treturn dict(ip=res[\"ip-address\"], mac=res[\"hardware-address\"], name=res[\"name\"].decode('utf-8'))\n\t\texcept KeyError:\n\t\t\traise OmapiErrorAttributeNotFound()",
    "docstring": "Look for a host object with given mac address and return the\n\t\tname, mac, and ip address\n\n\t\t@type mac: str\n\t\t@rtype: dict or None\n\t\t@raises ValueError:\n\t\t@raises OmapiError:\n\t\t@raises OmapiErrorNotFound: if no host object with the given mac address could be found\n\t\t@raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks ip, mac or name\n\t\t@raises socket.error:"
  },
  {
    "code": "def ip_v4(self, with_port: bool = False) -> str:\n        ip = '.'.join(str(self.random.randint(0, 255)) for _ in range(4))\n        if with_port:\n            ip += ':{}'.format(self.port())\n        return ip",
    "docstring": "Generate a random IPv4 address.\n\n        :param with_port: Add port to IP.\n        :return: Random IPv4 address.\n\n        :Example:\n            19.121.223.58"
  },
  {
    "code": "def _image_of_size(image_size):\n  return np.random.uniform(0, 256, [image_size, image_size, 3]).astype(np.uint8)",
    "docstring": "Generate a square RGB test image of the given side length."
  },
  {
    "code": "def is_authenticated(self):\n        if not self.token:\n            return False\n        try:\n            self.lookup_token()\n            return True\n        except exceptions.Forbidden:\n            return False\n        except exceptions.InvalidPath:\n            return False\n        except exceptions.InvalidRequest:\n            return False",
    "docstring": "Helper method which returns the authentication status of the client\n\n        :return:\n        :rtype:"
  },
  {
    "code": "def bin1d(x, bins):\n    left = [-float(\"inf\")]\n    left.extend(bins[0:-1])\n    right = bins\n    cuts = list(zip(left, right))\n    k = len(bins)\n    binIds = np.zeros(x.shape, dtype='int')\n    while cuts:\n        k -= 1\n        l, r = cuts.pop(-1)\n        binIds += (x > l) * (x <= r) * k\n    counts = np.bincount(binIds, minlength=len(bins))\n    return (binIds, counts)",
    "docstring": "Place values of a 1-d array into bins and determine counts of values in\n    each bin\n\n    Parameters\n    ----------\n    x : array\n        (n, 1), values to bin\n    bins : array\n           (k,1), upper bounds of each bin (monotonic)\n\n    Returns\n    -------\n    binIds : array\n             1-d array of integer bin Ids\n\n    counts : int\n            number of elements of x falling in each bin\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> import mapclassify as mc\n    >>> x = np.arange(100, dtype = 'float')\n    >>> bins = [25, 74, 100]\n    >>> binIds, counts = mc.classifiers.bin1d(x, bins)\n    >>> binIds\n    array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n           0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n           1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n           2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])\n    >>> counts\n    array([26, 49, 25])"
  },
  {
    "code": "def addbr(name):\n    fcntl.ioctl(ifconfig.sockfd, SIOCBRADDBR, name)\n    return Bridge(name)",
    "docstring": "Create new bridge with the given name"
  },
  {
    "code": "def uid(self):\n        exp = datetime.datetime.utcnow() + self.expDelay\n        claims = {\n            'user_info': self.user_info,\n            'exp': calendar.timegm(datetime.datetime.timetuple(exp))}\n        return jwt.encode(claims, self.site.session_secret, algorithm=SESSION_SECRET_ALGORITHM)",
    "docstring": "uid is now generated automatically according to the claims.\n\n        This should actually only be used for cookie generation"
  },
  {
    "code": "def analyse_topology(self,topology, cutoff=3.5):\n        self.define_residues_for_plotting_topology(cutoff)\n        self.find_the_closest_atoms(topology)",
    "docstring": "In case user wants to analyse only a single topology file, this process will determine the residues\n        that should be plotted and find the ligand atoms closest to these residues."
  },
  {
    "code": "def _group(self, rdd):\n        return rdd.reduceByKey(lambda x, y: x.append(y))",
    "docstring": "Group together the values with the same key."
  },
  {
    "code": "def assert_stmt(self):\n        module_globals = vars(sys.modules[self.module])\n        line_range, lineno = self._find_assert_stmt(\n            self.filename, self.linenumber, module_globals=module_globals)\n        source = [linecache.getline(self.filename, x,\n                                    module_globals=module_globals)\n                  for x in line_range]\n        dedented_lines = textwrap.dedent(''.join(source)).split('\\n')[:-1]\n        formatted_lines = []\n        for i, line in zip(line_range, dedented_lines):\n            prefix = '>' if i == lineno else ' '\n            formatted_lines.append(' {0} {1:4d} {2}'.format(prefix, i, line))\n        return '\\n'.join(formatted_lines)",
    "docstring": "Returns a string displaying the whole statement that failed,\n        with a '>' indicator on the line starting the expression."
  },
  {
    "code": "def to_routing_header(params):\n    if sys.version_info[0] < 3:\n        return urlencode(params).replace(\"%2F\", \"/\")\n    return urlencode(\n        params,\n        safe=\"/\",\n    )",
    "docstring": "Returns a routing header string for the given request parameters.\n\n    Args:\n        params (Mapping[str, Any]): A dictionary containing the request\n            parameters used for routing.\n\n    Returns:\n        str: The routing header string."
  },
  {
    "code": "def _set_value(self, new_value):\n        if self.min_value is not None and new_value < self.min_value:\n            raise SettingOutOfBounds(\n                \"Trying to set parameter {0} = {1}, which is less than the minimum allowed {2}\".format(\n                    self.name, new_value, self.min_value))\n        if self.max_value is not None and new_value > self.max_value:\n            raise SettingOutOfBounds(\n                \"Trying to set parameter {0} = {1}, which is more than the maximum allowed {2}\".format(\n                    self.name, new_value, self.max_value))\n        if self.has_auxiliary_variable():\n            with warnings.catch_warnings():\n                warnings.simplefilter(\"always\", RuntimeWarning)\n                warnings.warn(\"You are trying to assign to a parameter which is either linked or \"\n                              \"has auxiliary variables. The assignment has no effect.\", RuntimeWarning)\n        if self._transformation is None:\n            new_internal_value = new_value\n        else:\n            new_internal_value = self._transformation.forward(new_value)\n        if new_internal_value != self._internal_value:\n            self._internal_value = new_internal_value\n            for callback in self._callbacks:\n                try:\n                    callback(self)\n                except:\n                    raise NotCallableOrErrorInCall(\"Could not call callback for parameter %s\" % self.name)",
    "docstring": "Sets the current value of the parameter, ensuring that it is within the allowed range."
  },
  {
    "code": "def _create_query_string(params):\n        parameters = params or {}\n        for param, value in parameters.items():\n            param_value = str(value).lower() if isinstance(value, bool) else value\n            parameters[param] = param_value\n        return urlencode(parameters)",
    "docstring": "Support Elasticsearch 5.X"
  },
  {
    "code": "def set_sorting(self, flag):\r\n        self.sorting['status'] = flag\r\n        self.header().setSectionsClickable(flag == ON)",
    "docstring": "Enable result sorting after search is complete."
  },
  {
    "code": "def get_layout(name, *args, **kwargs):\n    if name not in _layout_map:\n        raise KeyError(\"Graph layout '%s' not found. Should be one of %s\"\n                       % (name, AVAILABLE_LAYOUTS))\n    layout = _layout_map[name]\n    if inspect.isclass(layout):\n        layout = layout(*args, **kwargs)\n    return layout",
    "docstring": "Retrieve a graph layout\n\n    Some graph layouts accept extra options. Please refer to their\n    documentation for more information.\n\n    Parameters\n    ----------\n    name : string\n        The name of the layout. The variable `AVAILABLE_LAYOUTS`\n        contains all available layouts.\n    *args\n        Positional arguments which are passed to the layout.\n    **kwargs\n        Keyword arguments which are passed to the layout.\n\n    Returns\n    -------\n    layout : callable\n        The callable generator which will calculate the graph layout"
  },
  {
    "code": "def flatten(list_to_flatten):\n    def genflatten(lst):\n        for elem in lst:\n            if isinstance(elem, (list, tuple)):\n                for x in flatten(elem):\n                    yield x\n            else:\n                yield elem\n    return list(genflatten(list_to_flatten))",
    "docstring": "Flatten out a list."
  },
  {
    "code": "def enable_gpid(self):\n        if self.is_ncb:\n            self.run_lldptool([\"-T\", \"-i\", self.port_name, \"-g\", \"ncb\",\n                               \"-V\", \"evb\", \"-c\", \"evbgpid=yes\"])\n            return True\n        else:\n            LOG.error(\"GPID cannot be set on NB\")\n            return False",
    "docstring": "Function to enable Group ID on the interface.\n\n        This is needed to use the MAC, GID, VID Filter."
  },
  {
    "code": "def get_catalogs_by_query(self, catalog_query):\n        if self._catalog_session is not None:\n            return self._catalog_session.get_catalogs_by_query(catalog_query)\n        query_terms = dict(catalog_query._query_terms)\n        collection = JSONClientValidated('cataloging',\n                                         collection='Catalog',\n                                         runtime=self._runtime)\n        result = collection.find(query_terms).sort('_id', DESCENDING)\n        return objects.CatalogList(result, runtime=self._runtime)",
    "docstring": "Gets a list of ``Catalogs`` matching the given catalog query.\n\n        arg:    catalog_query (osid.cataloging.CatalogQuery): the\n                catalog query\n        return: (osid.cataloging.CatalogList) - the returned\n                ``CatalogList``\n        raise:  NullArgument - ``catalog_query`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        raise:  Unsupported - ``catalog_query`` is not of this service\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def set(self, group, **kwargs):\n        if not self.leds:\n            return\n        assert group in self.led_groups, \\\n            \"%s is an invalid LED group, valid choices are %s\" % \\\n            (group, ', '.join(self.led_groups.keys()))\n        for led in self.led_groups[group]:\n            for k in kwargs:\n                setattr(led, k, kwargs[k])",
    "docstring": "Set attributes for each LED in group.\n\n        Example::\n\n            my_leds = Leds()\n            my_leds.set_color('LEFT', brightness_pct=0.5, trigger='timer')"
  },
  {
    "code": "def on_mouse_move(self, event):\n        if event.modifiers:\n            return\n        if event.is_dragging:\n            x0, y0 = self._normalize(event.press_event.pos)\n            x1, y1 = self._normalize(event.last_event.pos)\n            x, y = self._normalize(event.pos)\n            dx, dy = x - x1, y - y1\n            if event.button == 1:\n                self.pan_delta((dx, dy))\n            elif event.button == 2:\n                c = np.sqrt(self.size[0]) * .03\n                self.zoom_delta((dx, dy), (x0, y0), c=c)",
    "docstring": "Pan and zoom with the mouse."
  },
  {
    "code": "def exclude(self, d, item):\n        try:\n            md = d.__metadata__\n            pmd = getattr(md, '__print__', None)\n            if pmd is None:\n                return False\n            excludes = getattr(pmd, 'excludes', [])\n            return ( item[0] in excludes ) \n        except:\n            pass\n        return False",
    "docstring": "check metadata for excluded items"
  },
  {
    "code": "def extract_meta(cls, serializer, resource):\n        if hasattr(serializer, 'child'):\n            meta = getattr(serializer.child, 'Meta', None)\n        else:\n            meta = getattr(serializer, 'Meta', None)\n        meta_fields = getattr(meta, 'meta_fields', [])\n        data = OrderedDict()\n        for field_name in meta_fields:\n            data.update({\n                field_name: resource.get(field_name)\n            })\n        return data",
    "docstring": "Gathers the data from serializer fields specified in meta_fields and adds it to\n        the meta object."
  },
  {
    "code": "def handle_server_filter(self, request, table=None):\n        if not table:\n            table = self.get_table()\n        filter_info = self.get_server_filter_info(request, table)\n        if filter_info is None:\n            return False\n        request.session[filter_info['value_param']] = filter_info['value']\n        if filter_info['field_param']:\n            request.session[filter_info['field_param']] = filter_info['field']\n        return filter_info['changed']",
    "docstring": "Update the table server filter information in the session.\n\n        Returns True if the filter has been changed."
  },
  {
    "code": "def get(self, name):\n        name = str(name)\n        if name not in self._properties:\n            raise ArgumentError(\"Unknown property in DeviceModel\", name=name)\n        return self._properties[name]",
    "docstring": "Get a device model property.\n\n        Args:\n            name (str): The name of the property to get"
  },
  {
    "code": "def _find_base_tds_url(catalog_url):\n    url_components = urlparse(catalog_url)\n    if url_components.path:\n        return catalog_url.split(url_components.path)[0]\n    else:\n        return catalog_url",
    "docstring": "Identify the base URL of the THREDDS server from the catalog URL.\n\n    Will retain URL scheme, host, port and username/password when present."
  },
  {
    "code": "def manifest_parse(self, path):\n        print(\"fw: parsing manifests\")\n        content = open(path).read()\n        return json.loads(content)",
    "docstring": "parse manifest at path, return JSON object"
  },
  {
    "code": "def find(self, title):\n        files = backend.iterfiles(self._drive, name=title)\n        try:\n            return next(self[id] for id, _ in files)\n        except StopIteration:\n            raise KeyError(title)",
    "docstring": "Fetch and return the first spreadsheet with the given title.\n\n        Args:\n            title(str): title/name of the spreadsheet to return\n        Returns:\n            SpreadSheet: new SpreadSheet instance\n        Raises:\n            KeyError: if no spreadsheet with the given ``title`` is found"
  },
  {
    "code": "def get_indexes_from_base(self):\n        if self.is_indexed:\n            return np.copy(self.order[i])\n        if self.data.base is None:\n            i = 0\n        else:\n            i = self.get_raw_index(0)\n        return np.arange(i, i + len(self), dtype=np.uint32)",
    "docstring": "Get array of indexes from the base array, as if this raw data were\n        indexed."
  },
  {
    "code": "def main():\n    args = _parse_args()\n    _init_logging(args.verbose)\n    client = _from_args(args)\n    client.submit_error(args.description, args.extra,\n                        default_message=args.default_message)",
    "docstring": "Create a new instance and publish an error from command line args.\n\n    There is a console script for invoking this function from the command\n    line directly."
  },
  {
    "code": "async def viewers_js(request):\n    response = singletons.server.response\n    viewers_resource = singletons.viewers.get_resource()\n    url_string = viewers_resource.url_string\n    target_ts = TypeString('min.js')\n    target_resource = TypedResource(url_string, target_ts)\n    if target_resource.cache_exists():\n        return await response.file(target_resource.cache_path, headers={\n            'Content-Type': 'application/javascript',\n        })\n    if not viewers_resource.cache_exists():\n        viewers_resource.save()\n    await singletons.workers.async_enqueue_sync(\n        enqueue_conversion_path,\n        url_string,\n        str(target_ts),\n        singletons.workers.enqueue_convert\n    )\n    return response.text(NOT_LOADED_JS, headers={\n        'Content-Type': 'application/javascript',\n    })",
    "docstring": "Viewers determines the viewers installed based on settings, then uses the\n    conversion infrastructure to convert all these JS files into a single JS\n    bundle, that is then served. As with media, it will simply serve a cached\n    version if necessary."
  },
  {
    "code": "def group_factory(bridge, number, name, led_type):\n    if led_type in [RGBW, BRIDGE_LED]:\n        return RgbwGroup(bridge, number, name, led_type)\n    elif led_type == RGBWW:\n        return RgbwwGroup(bridge, number, name)\n    elif led_type == WHITE:\n        return WhiteGroup(bridge, number, name)\n    elif led_type == DIMMER:\n        return DimmerGroup(bridge, number, name)\n    elif led_type == WRGB:\n        return WrgbGroup(bridge, number, name)\n    else:\n        raise ValueError('Invalid LED type: %s', led_type)",
    "docstring": "Make a group.\n\n    :param bridge: Member of this bridge.\n    :param number: Group number (1-4).\n    :param name: Name of group.\n    :param led_type: Either `RGBW`, `WRGB`, `RGBWW`, `WHITE`, `DIMMER` or `BRIDGE_LED`.\n    :returns: New group."
  },
  {
    "code": "def substitute(self, var_map):\n        if self in var_map:\n            return var_map[self]\n        return self._substitute(var_map)",
    "docstring": "Substitute sub-expressions\n\n        Args:\n            var_map (dict): Dictionary with entries of the form\n                ``{expr: substitution}``"
  },
  {
    "code": "def has_object_error(self):\n        if self._has_object_error is None:\n            self._has_object_error = next(\n                (True for o in self.objects()\n                 if o.has_error()),\n                False)\n        return self._has_object_error",
    "docstring": "Returns true if any requested object had a business logic error,\n        otherwise returns false\n\n        Returns:\n            boolean"
  },
  {
    "code": "def _rx_timer_handler(self):\n        with self.rx_mutex:\n            if self.rx_state == ISOTP_WAIT_DATA:\n                self.rx_state = ISOTP_IDLE\n                warning(\"RX state was reset due to timeout\")",
    "docstring": "Method called every time the rx_timer times out, due to the peer not\n        sending a consecutive frame within the expected time window"
  },
  {
    "code": "def replace(self, episodes, length, rows=None):\n    rows = tf.range(self._capacity) if rows is None else rows\n    assert rows.shape.ndims == 1\n    assert_capacity = tf.assert_less(\n        rows, self._capacity, message='capacity exceeded')\n    with tf.control_dependencies([assert_capacity]):\n      assert_max_length = tf.assert_less_equal(\n          length, self._max_length, message='max length exceeded')\n    with tf.control_dependencies([assert_max_length]):\n      replace_ops = tools.nested.map(\n          lambda var, val: tf.scatter_update(var, rows, val),\n          self._buffers, episodes, flatten=True)\n    with tf.control_dependencies(replace_ops):\n      return tf.scatter_update(self._length, rows, length)",
    "docstring": "Replace full episodes.\n\n    Args:\n      episodes: Tuple of transition quantities with batch and time dimensions.\n      length: Batch of sequence lengths.\n      rows: Episodes to replace, defaults to all.\n\n    Returns:\n      Operation."
  },
  {
    "code": "def dot_v2(vec1, vec2):\n    return vec1.x * vec2.x + vec1.y * vec2.y",
    "docstring": "Return the dot product of two vectors"
  },
  {
    "code": "def niggli_reduce(lattice, eps=1e-5):\n    _set_no_error()\n    niggli_lattice = np.array(np.transpose(lattice), dtype='double', order='C')\n    result = spg.niggli_reduce(niggli_lattice, float(eps))\n    _set_error_message()\n    if result == 0:\n        return None\n    else:\n        return np.array(np.transpose(niggli_lattice),\n                        dtype='double', order='C')",
    "docstring": "Run Niggli reduction\n\n    Args:\n        lattice: Lattice parameters in the form of\n            [[a_x, a_y, a_z],\n             [b_x, b_y, b_z],\n             [c_x, c_y, c_z]]\n        eps:\n            float: Tolerance to check if difference of norms of two basis\n                   vectors is close to zero or not and if two basis vectors are\n                   orthogonal by the value of dot product being close to zero or\n                   not. The detail is shown at\n                   https://atztogo.github.io/niggli/.\n\n    Returns:\n        if the Niggli reduction succeeded:\n            Reduced lattice parameters are given as a numpy 'double' array:\n            [[a_x, a_y, a_z],\n             [b_x, b_y, b_z],\n             [c_x, c_y, c_z]]\n        otherwise None is returned."
  },
  {
    "code": "def view(self, rec):\n        out_json = {\n            'uid': rec.uid,\n            'time_update': rec.time_update,\n            'title': rec.title,\n            'cnt_html': tornado.escape.xhtml_unescape(rec.cnt_html),\n        }\n        self.write(json.dumps(out_json))",
    "docstring": "view the post."
  },
  {
    "code": "def dest_fpath(self, source_fpath: str) -> str:\n        relative_fpath = os.path.join(*source_fpath.split(os.sep)[1:])\n        relative_dirpath = os.path.dirname(relative_fpath)\n        source_fname = relative_fpath.split(os.sep)[-1]\n        base_fname = source_fname.split('.')[0]\n        dest_fname = f'{base_fname}.json'\n        return os.path.join(self.dest_dir, relative_dirpath, dest_fname)",
    "docstring": "Calculates full path for end json-api file from source file full\n        path."
  },
  {
    "code": "def _multi_take(self, tup):\n        o = self.obj\n        d = {axis: self._get_listlike_indexer(key, axis)\n             for (key, axis) in zip(tup, o._AXIS_ORDERS)}\n        return o._reindex_with_indexers(d, copy=True, allow_dups=True)",
    "docstring": "Create the indexers for the passed tuple of keys, and execute the take\n        operation. This allows the take operation to be executed all at once -\n        rather than once for each dimension - improving efficiency.\n\n        Parameters\n        ----------\n        tup : tuple\n            Tuple of indexers, one per axis\n\n        Returns\n        -------\n        values: same type as the object being indexed"
  },
  {
    "code": "def set_metrics(self, key, name, metrics):\n        with self._mor_lock:\n            mor = self._mor[key].get(name)\n            if mor is None:\n                raise MorNotFoundError(\"Mor object '{}' is not in the cache.\".format(name))\n            mor['metrics'] = metrics",
    "docstring": "Store a list of metric identifiers for the given instance key and Mor\n        object name.\n        If the key is not in the cache, raises a KeyError.\n        If the Mor object is not in the cache, raises a MorNotFoundError"
  },
  {
    "code": "def prepare_module(self):\n        if self.has_post_config_hook:\n            try:\n                self.module_class.post_config_hook()\n            except Exception as e:\n                self.terminated = True\n                self.error_index = 0\n                self.error_messages = [\n                    self.module_nice_name,\n                    u\"{}: {}\".format(\n                        self.module_nice_name, str(e) or e.__class__.__name__\n                    ),\n                ]\n                self.error_output(self.error_messages[0])\n                msg = \"Exception in `%s` post_config_hook()\" % self.module_full_name\n                self._py3_wrapper.report_exception(msg, notify_user=False)\n                self._py3_wrapper.log(\"terminating module %s\" % self.module_full_name)\n        self.enabled = True",
    "docstring": "Ready the module to get it ready to start."
  },
  {
    "code": "def residueCounts(self, convertCaseTo='upper'):\n        if convertCaseTo == 'none':\n            def convert(x):\n                return x\n        elif convertCaseTo == 'lower':\n            convert = str.lower\n        elif convertCaseTo == 'upper':\n            convert = str.upper\n        else:\n            raise ValueError(\n                \"convertCaseTo must be one of 'none', 'lower', or 'upper'\")\n        counts = defaultdict(Counter)\n        for titleAlignment in self:\n            read = titleAlignment.read\n            for hsp in titleAlignment.hsps:\n                for (subjectOffset, residue, inMatch) in read.walkHSP(hsp):\n                    counts[subjectOffset][convert(residue)] += 1\n        return counts",
    "docstring": "Count residue frequencies at all sequence locations matched by reads.\n\n        @param convertCaseTo: A C{str}, 'upper', 'lower', or 'none'.\n            If 'none', case will not be converted (both the upper and lower\n            case string of a residue will be present in the result if they are\n            present in the read - usually due to low complexity masking).\n        @return: A C{dict} whose keys are C{int} offsets into the title\n            sequence and whose values are C{Counters} with the residue as keys\n            and the count of that residue at that location as values."
  },
  {
    "code": "def scene_to_collision(scene):\n    manager = CollisionManager()\n    objects = {}\n    for node in scene.graph.nodes_geometry:\n        T, geometry = scene.graph[node]\n        objects[node] = manager.add_object(name=node,\n                                           mesh=scene.geometry[geometry],\n                                           transform=T)\n    return manager, objects",
    "docstring": "Create collision objects from a trimesh.Scene object.\n\n    Parameters\n    ------------\n    scene : trimesh.Scene\n      Scene to create collision objects for\n\n    Returns\n    ------------\n    manager : CollisionManager\n      CollisionManager for objects in scene\n    objects: {node name: CollisionObject}\n      Collision objects for nodes in scene"
  },
  {
    "code": "def _is_pid_running_on_windows(pid):\r\n    pid = str(pid)\r\n    startupinfo = subprocess.STARTUPINFO()\r\n    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\r\n    process = subprocess.Popen(r'tasklist /fi \"PID eq {0}\"'.format(pid),\r\n                               stdout=subprocess.PIPE,\r\n                               stderr=subprocess.STDOUT,\r\n                               startupinfo=startupinfo)\r\n    stdoutdata, stderrdata = process.communicate()\r\n    stdoutdata = to_text_string(stdoutdata)\r\n    process.kill()\r\n    check = pid in stdoutdata\r\n    return check",
    "docstring": "Check if a process is running on windows systems based on the pid."
  },
  {
    "code": "def update_object(self, container, obj, metadata, **kwargs):\n        try:\n            LOG.debug('update_object() with %s is success.', self.driver)\n            return self.driver.update_object(container, obj,\n                                             metadata, **kwargs)\n        except DriverException as e:\n            LOG.exception('copy_object() with %s raised\\\n                            an exception %s.', self.driver, e)",
    "docstring": "Update object metadata\n\n        :param container: container name (Container is equivalent to\n                          Bucket term in Amazon).\n        :param obj: object name (Object is equivalent to\n                    Key term in Amazon).\n        :param metadata(dict): additional metadata to include in the request."
  },
  {
    "code": "def retry_handler(retries=0, delay=timedelta(), conditions=[]):\n    delay_in_seconds = delay.total_seconds()\n    return partial(retry_loop, retries, delay_in_seconds, conditions)",
    "docstring": "A simple wrapper function that creates a handler function by using\n    on the retry_loop function.\n\n    Args:\n        retries (Integral): The number of times to retry if a failure occurs.\n        delay (timedelta, optional, 0 seconds): A timedelta representing\n            the amount time to delay between retries.\n        conditions (list): A list of retry conditions.\n    Returns:\n        function: The retry_loop function partialed."
  },
  {
    "code": "def refresh(self, refresh_token):\n        r = requests.post(self.apiurl + \"/token\", params={\"grant_type\": \"refresh_token\", \"client_id\": self.cid,\n                                                          \"client_secret\": self.csecret,\n                                                          \"refresh_token\": refresh_token})\n        if r.status_code != 200:\n            raise ServerError\n        jsd = r.json()\n        return jsd['access_token'], int(jsd['expires_in']) + int(jsd['created_at'])",
    "docstring": "Renew an oauth token given an appropriate refresh token.\n\n        :param refresh_token: The Refresh Token\n        :return: A tuple of (token, expiration time in unix time stamp)"
  },
  {
    "code": "def on_select(self, item, action):\n        if not isinstance(item, int):\n            item = self.items.index(item)\n        self._on_select[item] = action",
    "docstring": "Add an action to make when an object is selected.\n        Only one action can be stored this way."
  },
  {
    "code": "def is_supported(value, check_all=False, filters=None, iterate=False):\n    assert filters is not None\n    if value is None:\n        return True\n    if not is_editable_type(value):\n        return False\n    elif not isinstance(value, filters):\n        return False\n    elif iterate:\n        if isinstance(value, (list, tuple, set)):\n            valid_count = 0\n            for val in value:\n                if is_supported(val, filters=filters, iterate=check_all):\n                    valid_count += 1\n                if not check_all:\n                    break\n            return valid_count > 0\n        elif isinstance(value, dict):\n            for key, val in list(value.items()):\n                if not is_supported(key, filters=filters, iterate=check_all) \\\n                   or not is_supported(val, filters=filters,\n                                       iterate=check_all):\n                    return False\n                if not check_all:\n                    break\n    return True",
    "docstring": "Return True if the value is supported, False otherwise"
  },
  {
    "code": "def _get_dominant_angle(lines, domination_type=MEDIAN):\n    if domination_type == MEDIAN:\n        return _get_median_angle(lines)\n    elif domination_type == MEAN:\n        return _get_mean_angle(lines)\n    else:\n        raise ValueError('Unknown domination type provided: %s' % (\n            domination_type))",
    "docstring": "Picks dominant angle of a set of lines.\n\n    Args:\n        lines: iterable of (x1, y1, x2, y2) tuples that define lines.\n        domination_type: either MEDIAN or MEAN.\n\n    Returns:\n        Dominant angle value in radians.\n\n    Raises:\n        ValueError: on unknown domination_type."
  },
  {
    "code": "def default_chunksize(self):\n        if self._default_chunksize is None:\n            try:\n                self.dimension()\n                self.output_type()\n            except:\n                self._default_chunksize = Iterable._FALLBACK_CHUNKSIZE\n            else:\n                self._default_chunksize = Iterable._compute_default_cs(self.dimension(),\n                                                                       self.output_type().itemsize, self.logger)\n        return self._default_chunksize",
    "docstring": "How much data will be processed at once, in case no chunksize has been provided.\n\n        Notes\n        -----\n        This variable respects your setting for maximum memory in pyemma.config.default_chunksize"
  },
  {
    "code": "def from_tuples(cls, tups):\n        ivs = [Interval(*t) for t in tups]\n        return IntervalTree(ivs)",
    "docstring": "Create a new IntervalTree from an iterable of 2- or 3-tuples,\n         where the tuple lists begin, end, and optionally data."
  },
  {
    "code": "def get_intermediate_dirs(fs, dir_path):\n    intermediates = []\n    with fs.lock():\n        for path in recursepath(abspath(dir_path), reverse=True):\n            try:\n                resource = fs.getinfo(path)\n            except ResourceNotFound:\n                intermediates.append(abspath(path))\n            else:\n                if resource.is_dir:\n                    break\n                raise errors.DirectoryExpected(dir_path)\n    return intermediates[::-1][:-1]",
    "docstring": "Get a list of non-existing intermediate directories.\n\n    Arguments:\n        fs (FS): A filesystem instance.\n        dir_path (str): A path to a new directory on the filesystem.\n\n    Returns:\n        list: A list of non-existing paths.\n\n    Raises:\n        ~fs.errors.DirectoryExpected: If a path component\n            references a file and not a directory."
  },
  {
    "code": "def schedule(self, cron_schedule, base_datetime=None):\n        logger.debug('Scheduling job {0} with cron schedule {1}'.format(self.name, cron_schedule))\n        if not self.state.allow_change_schedule:\n            raise DagobahError(\"job's schedule cannot be changed in state: %s\"\n                               % self.state.status)\n        if cron_schedule is None:\n            self.cron_schedule = None\n            self.cron_iter = None\n            self.next_run = None\n        else:\n            if base_datetime is None:\n                base_datetime = datetime.utcnow()\n            self.cron_schedule = cron_schedule\n            self.cron_iter = croniter(cron_schedule, base_datetime)\n            self.next_run = self.cron_iter.get_next(datetime)\n        logger.debug('Determined job {0} next run of {1}'.format(self.name, self.next_run))\n        self.commit()",
    "docstring": "Schedules the job to run periodically using Cron syntax."
  },
  {
    "code": "def get_directory(self, identifier):\n        return os.path.join(\n            os.path.join(self.directory, identifier[:2]),\n            identifier\n        )",
    "docstring": "Implements the policy for naming directories for image objects. Image\n        object directories are name by their identifier. In addition, these\n        directories are grouped in parent directories named by the first two\n        characters of the identifier. The aim is to avoid having too many\n        sub-folders in a single directory.\n\n        Parameters\n        ----------\n        identifier : string\n            Unique object identifier\n\n        Returns\n        -------\n        string\n            Path to image objects data directory"
  },
  {
    "code": "def memory_read16(self, addr, num_halfwords, zone=None):\n        return self.memory_read(addr, num_halfwords, zone=zone, nbits=16)",
    "docstring": "Reads memory from the target system in units of 16-bits.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          addr (int): start address to read from\n          num_halfwords (int): number of half words to read\n          zone (str): memory zone to read from\n\n        Returns:\n          List of halfwords read from the target system.\n\n        Raises:\n          JLinkException: if memory could not be read"
  },
  {
    "code": "def gen_binder_url(fpath, binder_conf, gallery_conf):\n    fpath_prefix = binder_conf.get('filepath_prefix')\n    link_base = binder_conf.get('notebooks_dir')\n    relative_link = os.path.relpath(fpath, gallery_conf['src_dir'])\n    path_link = os.path.join(\n        link_base, replace_py_ipynb(relative_link))\n    if fpath_prefix is not None:\n        path_link = '/'.join([fpath_prefix.strip('/'), path_link])\n    path_link = path_link.replace(os.path.sep, '/')\n    binder_url = binder_conf['binderhub_url']\n    binder_url = '/'.join([binder_conf['binderhub_url'],\n                           'v2', 'gh',\n                           binder_conf['org'],\n                           binder_conf['repo'],\n                           binder_conf['branch']])\n    if binder_conf.get('use_jupyter_lab', False) is True:\n        binder_url += '?urlpath=lab/tree/{}'.format(path_link)\n    else:\n        binder_url += '?filepath={}'.format(path_link)\n    return binder_url",
    "docstring": "Generate a Binder URL according to the configuration in conf.py.\n\n    Parameters\n    ----------\n    fpath: str\n        The path to the `.py` file for which a Binder badge will be generated.\n    binder_conf: dict or None\n        The Binder configuration dictionary. See `gen_binder_rst` for details.\n\n    Returns\n    -------\n    binder_url : str\n        A URL that can be used to direct the user to the live Binder\n        environment."
  },
  {
    "code": "def seconds_left(self):\n        return int((self._ENDDATE.datetime -\n                    Date(self).datetime).total_seconds())",
    "docstring": "Remaining part of the year in seconds.\n\n        In the first example, only one minute and thirty seconds of the year\n        remain:\n\n        >>> from hydpy.core.timetools import TOY\n        >>> TOY('12_31_23_58_30').seconds_left\n        90\n\n        The second example shows that the 29th February is generally included:\n\n        >>> TOY('2').seconds_left\n        28944000"
  },
  {
    "code": "def reset(self):\n        self.at(ardrone.at.ref, False, True)\n        time.sleep(0.1)\n        self.at(ardrone.at.ref, False, False)",
    "docstring": "Toggle the drone's emergency state."
  },
  {
    "code": "def set_xlim(self, xlim):\n        if self.xlim_pipe is not None and self.xlim != xlim:\n            try:\n                self.xlim_pipe[0].send(xlim)\n            except IOError:\n                return False\n            self.xlim = xlim\n        return True",
    "docstring": "set new X bounds"
  },
  {
    "code": "def unsigned_big_integer(self, column, auto_increment=False):\n        return self.big_integer(column, auto_increment, True)",
    "docstring": "Create a new unsigned big integer column on the table.\n\n        :param column: The column\n        :type column: str\n\n        :type auto_increment: bool\n\n        :rtype: Fluent"
  },
  {
    "code": "def _nowaveform_loglr(self):\n        for det in self._data:\n            setattr(self._current_stats, 'loglikelihood', -numpy.inf)\n            setattr(self._current_stats, '{}_cplx_loglr'.format(det),\n                    -numpy.inf)\n            setattr(self._current_stats, '{}_optimal_snrsq'.format(det), 0.)\n        return -numpy.inf",
    "docstring": "Convenience function to set loglr values if no waveform generated."
  },
  {
    "code": "def _retrieve_device_cache(proxy=None):\n    global DEVICE_CACHE\n    if not DEVICE_CACHE:\n        if proxy and salt.utils.napalm.is_proxy(__opts__):\n            if 'napalm.get_device' in proxy:\n                DEVICE_CACHE = proxy['napalm.get_device']()\n        elif not proxy and salt.utils.napalm.is_minion(__opts__):\n            DEVICE_CACHE = salt.utils.napalm.get_device(__opts__)\n    return DEVICE_CACHE",
    "docstring": "Loads the network device details if not cached already."
  },
  {
    "code": "def set_amino_acid(self, aa):\n        aa = aa.upper()\n        aa = aa[2:] if aa.startswith('P.') else aa\n        self.__set_mutation_status()\n        self.__parse_hgvs_syntax(aa)",
    "docstring": "Set amino acid change and position."
  },
  {
    "code": "def get_methods_names(public_properties):\n        if public_properties:\n            prefix = ipopo_constants.IPOPO_PROPERTY_PREFIX\n        else:\n            prefix = ipopo_constants.IPOPO_HIDDEN_PROPERTY_PREFIX\n        return (\n            \"{0}{1}\".format(prefix, ipopo_constants.IPOPO_GETTER_SUFFIX),\n            \"{0}{1}\".format(prefix, ipopo_constants.IPOPO_SETTER_SUFFIX),\n        )",
    "docstring": "Generates the names of the fields where to inject the getter and setter\n        methods\n\n        :param public_properties: If True, returns the names of public property\n                                  accessors, else of hidden property ones\n        :return: getter and a setter field names"
  },
  {
    "code": "def notify_completed(self, participant):\n        if participant.status == \"overrecruited\" or not self.qualification_active:\n            return\n        worker_id = participant.worker_id\n        for name in self.qualifications:\n            try:\n                self.mturkservice.increment_qualification_score(name, worker_id)\n            except QualificationNotFoundException as ex:\n                logger.exception(ex)",
    "docstring": "Assign a Qualification to the Participant for the experiment ID,\n        and for the configured group_name, if it's been set.\n\n        Overrecruited participants don't receive qualifications, since they\n        haven't actually completed the experiment. This allows them to remain\n        eligible for future runs."
  },
  {
    "code": "def text(self, text, stylename=None):\n        assert self._containers\n        container = self._containers[-1]\n        if stylename is not None:\n            stylename = self._get_style_name(stylename)\n            container.addElement(Span(stylename=stylename, text=text))\n        else:\n            container.addElement(Span(text=text))",
    "docstring": "Add text within the current container."
  },
  {
    "code": "def SVG_path(path, transform=None, simplify=False):\n    if transform is not None:\n        path = path.transformed(transform)\n    vc_tuples = [(vertices if path_code != Path.CLOSEPOLY else [],\n                  PATH_DICT[path_code])\n                 for (vertices, path_code)\n                 in path.iter_segments(simplify=simplify)]\n    if not vc_tuples:\n        return np.zeros((0, 2)), []\n    else:\n        vertices, codes = zip(*vc_tuples)\n        vertices = np.array(list(itertools.chain(*vertices))).reshape(-1, 2)\n        return vertices, list(codes)",
    "docstring": "Construct the vertices and SVG codes for the path\n\n    Parameters\n    ----------\n    path : matplotlib.Path object\n\n    transform : matplotlib transform (optional)\n        if specified, the path will be transformed before computing the output.\n\n    Returns\n    -------\n    vertices : array\n        The shape (M, 2) array of vertices of the Path. Note that some Path\n        codes require multiple vertices, so the length of these vertices may\n        be longer than the list of path codes.\n    path_codes : list\n        A length N list of single-character path codes, N <= M. Each code is\n        a single character, in ['L','M','S','C','Z']. See the standard SVG\n        path specification for a description of these."
  },
  {
    "code": "def watch(cams, path=None, delay=10):\n    while True:\n        for c in cams:\n            c.snap(path)\n        time.sleep(delay)",
    "docstring": "Get screenshots from all cams at defined intervall."
  },
  {
    "code": "def _requested_name(self, name, action=None, func=None):\n        if name is not None:\n            if name in self._used_names:\n                n = 2\n                while True:\n                    pn = name + '_' + str(n)\n                    if pn not in self._used_names:\n                        self._used_names.add(pn)\n                        return pn\n                    n += 1\n            else:\n                self._used_names.add(name)\n                return name\n        if func is not None:\n            if hasattr(func, '__name__'):\n                name = func.__name__\n                if name == '<lambda>':\n                    name = action + '_lambda'\n            elif hasattr(func, '__class__'):\n                name = func.__class__.__name__\n        if name is None:\n            if action is not None:\n                name = action\n            else:\n                name = self.name\n        return self._requested_name(name)",
    "docstring": "Create a unique name for an operator or a stream."
  },
  {
    "code": "def fit_transform(self, X, y=None, **fit_params):\n        self._validate_transformers()\n        with Pool(self.n_jobs) as pool:\n            result = pool.starmap(_fit_transform_one,\n                         ((trans, weight, X[trans['col_pick']] if hasattr(trans, 'col_pick') else X, y)\n                          for name, trans, weight in self._iter()))\n        if not result:\n            return np.zeros((X.shape[0], 0))\n        Xs, transformers = zip(*result)\n        self._update_transformer_list(transformers)\n        if self.concatenate:\n            if any(sparse.issparse(f) for f in Xs):\n                Xs = sparse.hstack(Xs).tocsr()\n            else:\n                Xs = np.hstack(Xs)\n        return Xs",
    "docstring": "Fit all transformers, transform the data and concatenate results.\n\n        Parameters\n        ----------\n        X : iterable or array-like, depending on transformers\n            Input data to be transformed.\n\n        y : array-like, shape (n_samples, ...), optional\n            Targets for supervised learning.\n\n        Returns\n        -------\n        X_t : array-like or sparse matrix, shape (n_samples, sum_n_components)\n            hstack of results of transformers. sum_n_components is the\n            sum of n_components (output dimension) over transformers."
  },
  {
    "code": "def verify_convention_version(self, ds):\n        try:\n            for convention in getattr(ds, \"Conventions\", '').replace(' ', '').split(','):\n                if convention == 'ACDD-' + self._cc_spec_version:\n                    return ratable_result((2, 2), None, [])\n            m = [\"Conventions does not contain 'ACDD-{}'\".format(self._cc_spec_version)]\n            return ratable_result((1, 2), \"Global Attributes\", m)\n        except AttributeError:\n            m = [\"No Conventions attribute present; must contain ACDD-{}\".format(self._cc_spec_version)]\n            return ratable_result((0, 2), \"Global Attributes\", m)",
    "docstring": "Verify that the version in the Conventions field is correct"
  },
  {
    "code": "def cmd_cminv(self, ch=None):\n        viewer = self.get_viewer(ch)\n        if viewer is None:\n            self.log(\"No current viewer/channel.\")\n            return\n        viewer.invert_cmap()",
    "docstring": "cminv ch=chname\n\n        Invert the color map in the channel/viewer"
  },
  {
    "code": "def commit(self):\n        if not self.consumer_group:\n            return fail(Failure(InvalidConsumerGroupError(\n                \"Bad Group_id:{0!r}\".format(self.consumer_group))))\n        if ((self._last_processed_offset is None) or\n                (self._last_processed_offset == self._last_committed_offset)):\n            return succeed(self._last_committed_offset)\n        if self._commit_ds:\n            d = Deferred()\n            self._commit_ds.append(d)\n            return fail(OperationInProgress(d))\n        d = Deferred()\n        self._commit_ds.append(d)\n        self._send_commit_request()\n        if self._commit_looper is not None:\n            self._commit_looper.reset()\n        return d",
    "docstring": "Commit the offset of the message we last processed if it is different\n        from what we believe is the last offset committed to Kafka.\n\n        .. note::\n\n            It is possible to commit a smaller offset than Kafka has stored.\n            This is by design, so we can reprocess a Kafka message stream if\n            desired.\n\n        On error, will retry according to :attr:`request_retry_max_attempts`\n        (by default, forever).\n\n        If called while a commit operation is in progress, and new messages\n        have been processed since the last request was sent then the commit\n        will fail with :exc:`OperationInProgress`.  The\n        :exc:`OperationInProgress` exception wraps\n        a :class:`~twisted.internet.defer.Deferred` which fires when the\n        outstanding commit operation completes.\n\n        :returns:\n            A :class:`~twisted.internet.defer.Deferred` which resolves with the\n            committed offset when the operation has completed.  It will resolve\n            immediately if the current offset and the last committed offset do\n            not differ."
  },
  {
    "code": "def on_quit(self, connection, event):\n        nickname = self.get_nickname(event)\n        nickname_color = self.nicknames[nickname]\n        del self.nicknames[nickname]\n        self.namespace.emit(\"message\", nickname, \"leaves\", nickname_color)\n        self.emit_nicknames()",
    "docstring": "Someone left the channel - send the nicknames list to the\n        WebSocket."
  },
  {
    "code": "def load_data(train_path='./data/regression.train', test_path='./data/regression.test'):\n    print('Load data...')\n    df_train = pd.read_csv(train_path, header=None, sep='\\t')\n    df_test = pd.read_csv(test_path, header=None, sep='\\t')\n    num = len(df_train)\n    split_num = int(0.9 * num)\n    y_train = df_train[0].values\n    y_test = df_test[0].values\n    y_eval = y_train[split_num:]\n    y_train = y_train[:split_num]\n    X_train = df_train.drop(0, axis=1).values\n    X_test = df_test.drop(0, axis=1).values\n    X_eval = X_train[split_num:, :]\n    X_train = X_train[:split_num, :]\n    lgb_train = lgb.Dataset(X_train, y_train)\n    lgb_eval = lgb.Dataset(X_eval, y_eval, reference=lgb_train)\n    return lgb_train, lgb_eval, X_test, y_test",
    "docstring": "Load or create dataset"
  },
  {
    "code": "def read_buffer(io, print_output=False, print_func=None):\n    def _print(line):\n        if print_output:\n            if print_func:\n                formatted_line = print_func(line)\n            else:\n                formatted_line = line\n            encoded_line = unicode(formatted_line).encode('utf-8')\n            print(encoded_line)\n    out = []\n    for line in io:\n        if not isinstance(line, six.text_type):\n            line = line.decode('utf-8')\n        line = line.strip()\n        out.append(line)\n        _print(line)\n    return out",
    "docstring": "Reads a file-like buffer object into lines and optionally prints the output."
  },
  {
    "code": "def Extract(high: int, low: int, bv: BitVec) -> BitVec:\n    raw = z3.Extract(high, low, bv.raw)\n    if isinstance(bv, BitVecFunc):\n        return BitVecFunc(\n            raw=raw, func_name=None, input_=None, annotations=bv.annotations\n        )\n    return BitVec(raw, annotations=bv.annotations)",
    "docstring": "Create an extract expression.\n\n    :param high:\n    :param low:\n    :param bv:\n    :return:"
  },
  {
    "code": "def list_hosting_devices_hosting_routers(self, client, router_id,\n                                             **_params):\n        return client.get((client.router_path + L3_ROUTER_DEVICES) %\n                          router_id, params=_params)",
    "docstring": "Fetches a list of hosting devices hosting a router."
  },
  {
    "code": "def _writeImage(dataArray=None, inputHeader=None):\n    prihdu = fits.PrimaryHDU(data=dataArray, header=inputHeader)\n    pf = fits.HDUList()\n    pf.append(prihdu)\n    return pf",
    "docstring": "Writes out the result of the combination step.\n        The header of the first 'outsingle' file in the\n        association parlist is used as the header of the\n        new image.\n\n        Parameters\n        ----------\n        dataArray : arr\n            Array of data to be written to a fits.PrimaryHDU object\n\n        inputHeader : obj\n            fits.header.Header object to use as basis for the PrimaryHDU header"
  },
  {
    "code": "def service(self, *args, **kwargs):\n        return self._client.service(*args, scope=self.id, **kwargs)",
    "docstring": "Retrieve a single service belonging to this scope.\n\n        See :class:`pykechain.Client.service` for available parameters.\n\n        .. versionadded:: 1.13"
  },
  {
    "code": "def _process_response(response):\n    try:\n        data = response.json()\n    except ValueError:\n        _log_and_raise_exception('Invalid response', response.text)\n    if response.status_code == 200:\n        return { 'headers': response.headers, 'data': data }\n    return _raise_error_from_response(data)",
    "docstring": "Make the request and handle exception processing"
  },
  {
    "code": "def get_hit_count_from_obj_variable(context, obj_variable, tag_name):\n    error_to_raise = template.TemplateSyntaxError(\n        \"'%(a)s' requires a valid individual model variable \"\n        \"in the form of '%(a)s for [model_obj]'.\\n\"\n        \"Got: %(b)s\" % {'a': tag_name, 'b': obj_variable}\n    )\n    try:\n        obj = obj_variable.resolve(context)\n    except template.VariableDoesNotExist:\n        raise error_to_raise\n    try:\n        ctype = ContentType.objects.get_for_model(obj)\n    except AttributeError:\n        raise error_to_raise\n    hit_count, created = HitCount.objects.get_or_create(\n        content_type=ctype, object_pk=obj.pk)\n    return hit_count",
    "docstring": "Helper function to return a HitCount for a given template object variable.\n\n    Raises TemplateSyntaxError if the passed object variable cannot be parsed."
  },
  {
    "code": "def params_dict(self):\n        location_code = 'US'\n        language_code = 'en'\n        if len(self.location):\n            location_code = locationMap[process.extractOne(self.location, self.locations)[0]]\n        if len(self.language):\n            language_code = langMap[process.extractOne(self.language, self.languages)[0]]\n        params = {\n            'hl': language_code,\n            'gl': location_code,\n            'ceid': '{}:{}'.format(location_code, language_code)\n        }\n        return params",
    "docstring": "function to get params dict for HTTP request"
  },
  {
    "code": "def delete_table_records(self, table, query_column, ids_to_delete):\n        table = table.get_soap_object(self.client)\n        result = self.call('deleteTableRecords', table, query_column, ids_to_delete)\n        if hasattr(result, '__iter__'):\n            return [DeleteResult(delete_result) for delete_result in result]\n        return [DeleteResult(result)]",
    "docstring": "Responsys.deleteTableRecords call\n\n        Accepts:\n            InteractObject table\n            string query_column\n                possible values: 'RIID'|'EMAIL_ADDRESS'|'CUSTOMER_ID'|'MOBILE_NUMBER'\n            list ids_to_delete\n\n        Returns a list of DeleteResult instances"
  },
  {
    "code": "def describe_autocomplete(self, service, operation, param):\n        service_index = self._index[service]\n        LOG.debug(service_index)\n        if param not in service_index.get('operations', {}).get(operation, {}):\n            LOG.debug(\"param not in index: %s\", param)\n            return None\n        p = service_index['operations'][operation][param]\n        resource_name = p['resourceName']\n        resource_identifier = p['resourceIdentifier']\n        resource_index = service_index['resources'][resource_name]\n        completion_operation = resource_index['operation']\n        path = resource_index['resourceIdentifier'][resource_identifier]\n        return ServerCompletion(service=service, operation=completion_operation,\n                                params={}, path=path)",
    "docstring": "Describe operation and args needed for server side completion.\n\n        :type service: str\n        :param service: The AWS service name.\n\n        :type operation: str\n        :param operation: The AWS operation name.\n\n        :type param: str\n        :param param: The name of the parameter being completed.  This must\n            match the casing in the service model (e.g. InstanceIds, not\n            --instance-ids).\n\n        :rtype: ServerCompletion\n        :return: A ServerCompletion object that describes what API call to make\n            in order to complete the response."
  },
  {
    "code": "def all_finite(self,X):\n        if (X.dtype.char in np.typecodes['AllFloat']\n            and not np.isfinite(np.asarray(X,dtype='float32').sum())\n            and not np.isfinite(np.asarray(X,dtype='float32')).all()):\n            return False\n        return True",
    "docstring": "returns true if X is finite, false, otherwise"
  },
  {
    "code": "def prepare(self):\n        super(Syndic, self).prepare()\n        try:\n            if self.config['verify_env']:\n                verify_env(\n                    [\n                        self.config['pki_dir'],\n                        self.config['cachedir'],\n                        self.config['sock_dir'],\n                        self.config['extension_modules'],\n                    ],\n                    self.config['user'],\n                    permissive=self.config['permissive_pki_access'],\n                    root_dir=self.config['root_dir'],\n                    pki_dir=self.config['pki_dir'],\n                )\n        except OSError as error:\n            self.environment_failure(error)\n        self.setup_logfile_logger()\n        verify_log(self.config)\n        self.action_log_info('Setting up \"{0}\"'.format(self.config['id']))\n        import salt.minion\n        self.daemonize_if_required()\n        self.syndic = salt.minion.SyndicManager(self.config)\n        self.set_pidfile()",
    "docstring": "Run the preparation sequence required to start a salt syndic minion.\n\n        If sub-classed, don't **ever** forget to run:\n\n            super(YourSubClass, self).prepare()"
  },
  {
    "code": "def noise_covariance(fit, dof=2, **kw):\n    ev = fit.eigenvalues\n    measurement_noise = ev[-1]/(fit.n-dof)\n    return 4*ev*measurement_noise",
    "docstring": "Covariance taking into account the 'noise covariance' of the data.\n    This is technically more realistic for continuously sampled data.\n    From Faber, 1993"
  },
  {
    "code": "def ensure_has_same_campaigns(self):\n        lhs_yaml = osp.join(self.lhs, 'campaign.yaml')\n        rhs_yaml = osp.join(self.rhs, 'campaign.yaml')\n        assert osp.isfile(lhs_yaml)\n        assert osp.isfile(rhs_yaml)\n        assert filecmp.cmp(lhs_yaml, rhs_yaml)",
    "docstring": "Ensure that the 2 campaigns to merge have been generated\n        from the same campaign.yaml"
  },
  {
    "code": "def ports_mapping(self, ports):\n        if ports != self._ports_mapping:\n            if len(self._nios) > 0:\n                raise NodeError(\"Can't modify a cloud already connected.\")\n            port_number = 0\n            for port in ports:\n                port[\"port_number\"] = port_number\n                port_number += 1\n            self._ports_mapping = ports",
    "docstring": "Set the ports on this cloud.\n\n        :param ports: ports info"
  },
  {
    "code": "def to_snake(camel):\n    if not camel:\n        return camel\n    return ''.join('_' + x if 'A' <= x <= 'Z' else x for x in camel).lower()[camel[0].isupper():]",
    "docstring": "TimeSkill -> time_skill"
  },
  {
    "code": "def create(self, period: int, limit: int):\n        self.period = period\n        self.limit = limit",
    "docstring": "Creates a rate limiting rule with rate limiting period and attempt limit\n\n        :param period: Rate limiting period in seconds\n        :type period: int\n\n        :param limit: Number of attempts permitted by rate limiting within a given period\n        :type limit: int"
  },
  {
    "code": "def call_operation(self, operation, **kwargs):\n        data = {'operation': operation}\n        data.update(kwargs)\n        return self.invoke(data)",
    "docstring": "A generic method to call any operation supported by the Lambda handler"
  },
  {
    "code": "def skip_common_stack_elements(stacktrace, base_case):\n  for i, (trace, base) in enumerate(zip(stacktrace, base_case)):\n    if trace != base:\n      return stacktrace[i:]\n  return stacktrace[-1:]",
    "docstring": "Skips items that the target stacktrace shares with the base stacktrace."
  },
  {
    "code": "def term_width():\n    if fcntl and termios:\n        try:\n            winsize = fcntl.ioctl(0, termios.TIOCGWINSZ, '    ')\n            _, width = struct.unpack('hh', winsize)\n            return width\n        except IOError:\n            pass\n    elif windll and create_string_buffer:\n        stderr_handle, struct_size = -12, 22\n        handle = windll.kernel32.GetStdHandle(stderr_handle)\n        csbi = create_string_buffer(struct_size)\n        res = windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)\n        if res:\n            (_, _, _, _, _, left, _, right, _,\n             _, _) = struct.unpack('hhhhHhhhhhh', csbi.raw)\n            return right - left + 1\n        else:\n            return 0",
    "docstring": "Return the column width of the terminal, or ``None`` if it can't be\n    determined."
  },
  {
    "code": "def add_device(self, path):\n\t\thdevice = self._libinput.libinput_path_add_device(\n\t\t\tself._li, path.encode())\n\t\tif hdevice:\n\t\t\treturn Device(hdevice, self._libinput)\n\t\treturn None",
    "docstring": "Add a device to a libinput context.\n\n\t\tIf successful, the device will be added to the internal list and\n\t\tre-opened on :meth:`~libinput.LibInput.resume`. The device can be\n\t\tremoved with :meth:`remove_device`.\n\t\tIf the device was successfully initialized, it is returned.\n\n\t\tArgs:\n\t\t\tpath (str): Path to an input device.\n\t\tReturns:\n\t\t\t~libinput.define.Device: A device object or :obj:`None`."
  },
  {
    "code": "def edit_content(self, original_lines, file_name):\n        lines = [self.edit_line(line) for line in original_lines]\n        for function in self._functions:\n            try:\n                lines = list(function(lines, file_name))\n            except UnicodeDecodeError as err:\n                log.error('failed to process %s: %s', file_name, err)\n                return lines\n            except Exception as err:\n                log.error(\"failed to process %s with code %s: %s\",\n                          file_name, function, err)\n                raise\n        return lines",
    "docstring": "Processes a file contents.\n\n        First processes the contents line by line applying the registered\n        expressions, then process the resulting contents using the\n        registered functions.\n\n        Arguments:\n          original_lines (list of str): file content.\n          file_name (str): name of the file."
  },
  {
    "code": "def delete(name, region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    if not exists(name, region, key, keyid, profile):\n        return True\n    try:\n        conn.delete_load_balancer(name)\n        log.info('Deleted ELB %s.', name)\n        return True\n    except boto.exception.BotoServerError as error:\n        log.error('Failed to delete ELB %s', name,\n                  exc_info_on_loglevel=logging.DEBUG)\n        return False",
    "docstring": "Delete an ELB.\n\n    CLI example to delete an ELB:\n\n    .. code-block:: bash\n\n        salt myminion boto_elb.delete myelb region=us-east-1"
  },
  {
    "code": "def _add_linux_ethernet(self, port_info, bridge_name):\n        interface = port_info[\"interface\"]\n        if gns3server.utils.interfaces.is_interface_bridge(interface):\n            network_interfaces = [interface[\"name\"] for interface in self._interfaces()]\n            i = 0\n            while True:\n                tap = \"gns3tap{}-{}\".format(i, port_info[\"port_number\"])\n                if tap not in network_interfaces:\n                    break\n                i += 1\n            yield from self._ubridge_send('bridge add_nio_tap \"{name}\" \"{interface}\"'.format(name=bridge_name, interface=tap))\n            yield from self._ubridge_send('brctl addif \"{interface}\" \"{tap}\"'.format(tap=tap, interface=interface))\n        else:\n            yield from self._ubridge_send('bridge add_nio_linux_raw {name} \"{interface}\"'.format(name=bridge_name, interface=interface))",
    "docstring": "Use raw sockets on Linux.\n\n        If interface is a bridge we connect a tap to it"
  },
  {
    "code": "def build_rotation(vec3):\n        if not isinstance(vec3, Vector3):\n            raise ValueError(\"rotAmt must be a Vector3\")\n        return Matrix4.x_rotate(vec3.x) * Matrix4.y_rotate(vec3.y) * Matrix4.z_rotate(vec3.z)",
    "docstring": "Build a rotation matrix.\n        vec3 is a Vector3 defining the axis about which to rotate the object."
  },
  {
    "code": "def get_deposit_address(self, currency):\n        data = {\n            'currency': currency\n        }\n        return self._get('deposit-addresses', True, data=data)",
    "docstring": "Get deposit address for a currency\n\n        https://docs.kucoin.com/#get-deposit-address\n\n        :param currency: Name of currency\n        :type currency: string\n\n        .. code:: python\n\n            address = client.get_deposit_address('NEO')\n\n        :returns: ApiResponse\n\n        .. code:: python\n\n            {\n                \"address\": \"0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1\",\n                \"memo\": \"5c247c8a03aa677cea2a251d\"\n            }\n\n        :raises: KucoinResponseException, KucoinAPIException"
  },
  {
    "code": "def prune(self, filter_func=None, from_stash='active', to_stash='pruned'):\n        def _prune_filter(state):\n            to_prune = not filter_func or filter_func(state)\n            if to_prune and not state.satisfiable():\n                if self._hierarchy:\n                    self._hierarchy.unreachable_state(state)\n                    self._hierarchy.simplify()\n                return True\n            return False\n        self.move(from_stash, to_stash, _prune_filter)\n        return self",
    "docstring": "Prune unsatisfiable states from a stash.\n\n        This function will move all unsatisfiable states in the given stash into a different stash.\n\n        :param filter_func: Only prune states that match this filter.\n        :param from_stash:  Prune states from this stash. (default: 'active')\n        :param to_stash:    Put pruned states in this stash. (default: 'pruned')\n\n        :returns:           The simulation manager, for chaining.\n        :rtype:             SimulationManager"
  },
  {
    "code": "def send_message(ctx, scheduler_rpc, project, message):\n    if isinstance(scheduler_rpc, six.string_types):\n        scheduler_rpc = connect_rpc(ctx, None, scheduler_rpc)\n    if scheduler_rpc is None and os.environ.get('SCHEDULER_NAME'):\n        scheduler_rpc = connect_rpc(ctx, None, 'http://%s/' % (\n            os.environ['SCHEDULER_PORT_23333_TCP'][len('tcp://'):]))\n    if scheduler_rpc is None:\n        scheduler_rpc = connect_rpc(ctx, None, 'http://127.0.0.1:23333/')\n    return scheduler_rpc.send_task({\n        'taskid': utils.md5string('data:,on_message'),\n        'project': project,\n        'url': 'data:,on_message',\n        'fetch': {\n            'save': ('__command__', message),\n        },\n        'process': {\n            'callback': '_on_message',\n        }\n    })",
    "docstring": "Send Message to project from command line"
  },
  {
    "code": "def show_dbs():\n    l = []\n    mc = client_connector()\n    if not mc:\n        return ()\n    dbs = mc.database_names()\n    for d in dbs:\n        dbc = mc[d]\n        collections = dbc.collection_names()\n        collections = remove_values_from_list(collections, \"system.indexes\")\n        l.append({\"name\": d, \"collections\": collections})\n    return tuple(l)",
    "docstring": "return a list of all dbs and related collections.\n    Return an empty list on error."
  },
  {
    "code": "def set_main_fan(self, main_fan):\n        if type(main_fan) != int and main_fan not in range(0, 11):\n            raise InvalidInput(\"Main fan value must be int between 0-10\")\n        self._config['main_fan'] = main_fan\n        self._q.put(self._config)",
    "docstring": "Set the main fan config.\n\n        :param main_fan: Value to set the main fan\n        :type main_fan: int [0-10]\n        :returns: None\n        :raises: InvalidInput"
  },
  {
    "code": "def togpx(self):\n        element = create_elem(self.__class__._elem_name,\n                              {'lat': str(self.latitude),\n                               'lon': str(self.longitude)})\n        if self.name:\n            element.append(create_elem('name', text=self.name))\n        if self.description:\n            element.append(create_elem('desc', text=self.description))\n        if self.elevation:\n            element.append(create_elem('ele', text=str(self.elevation)))\n        if self.time:\n            element.append(create_elem('time', text=self.time.isoformat()))\n        return element",
    "docstring": "Generate a GPX waypoint element subtree.\n\n        Returns:\n            etree.Element: GPX element"
  },
  {
    "code": "def get_connection_id(self, conn_or_int_id):\n        key = conn_or_int_id\n        if isinstance(key, str):\n            table = self._int_connections\n        elif isinstance(key, int):\n            table = self._connections\n        else:\n            raise ArgumentError(\"You must supply either an int connection id or a string internal id to _get_connection_state\", id=key)\n        try:\n            data = table[key]\n        except KeyError:\n            raise ArgumentError(\"Could not find connection by id\", id=key)\n        return data['conn_id']",
    "docstring": "Get the connection id.\n\n        Args:\n            conn_or_int_id (int, string): The external integer connection id or\n                and internal string connection id\n\n        Returns:\n            dict: The context data associated with that connection or None if it cannot\n                be found.\n\n        Raises:\n            ArgumentError: When the key is not found in the list of active connections\n                or is invalid."
  },
  {
    "code": "def _loadChildRules(context, xmlElement, attributeToFormatMap):\n    rules = []\n    for ruleElement in xmlElement.getchildren():\n        if not ruleElement.tag in _ruleClassDict:\n            raise ValueError(\"Not supported rule '%s'\" % ruleElement.tag)\n        rule = _ruleClassDict[ruleElement.tag](context, ruleElement, attributeToFormatMap)\n        rules.append(rule)\n    return rules",
    "docstring": "Extract rules from Context or Rule xml element"
  },
  {
    "code": "def __join_connections(self):\n        interval_s = nsq.config.client.CONNECTION_CLOSE_AUDIT_WAIT_S\n        graceful_wait_s = nsq.config.client.CONNECTION_QUIT_CLOSE_TIMEOUT_S\n        graceful = False\n        while graceful_wait_s > 0:\n            if not self.__connections:\n                break\n            connected_list = [c.is_connected for (n, c, g) in self.__connections]\n            if any(connected_list) is False:\n                graceful = True\n                break\n            gevent.sleep(interval_s)\n            graceful_wait_s -= interval_s\n        if graceful is False:\n            connected_list = [c for (n, c, g) in self.__connections if c.is_connected]\n            _logger.error(\"We were told to terminate, but not all \"\n                          \"connections were stopped: [%s]\", connected_list)",
    "docstring": "Wait for all connections to close. There are no side-effects here. \n        We just want to try and leave -after- everything has closed, in \n        general."
  },
  {
    "code": "def _do_authorize(self):\n        if self.auth_data is None:\n            raise ApiwatcherClientException(\"You must provide authorization data.\")\n        r = requests.post(\n            \"{0}/api/token\".format(self.base_url), json=self.auth_data,\n            verify=self.verify_certificate, timeout=self.timeout\n        )\n        if r.status_code == 401:\n            raise ApiwatcherClientException(\"Wrong credentials supplied: {0}\".format(\n                r.json()[\"message\"]\n            ))\n        elif r.status_code != 201:\n            try:\n                reason = r.json()[\"message\"]\n            except:\n                reason = r.text\n            raise ApiwatcherClientException(\n                \"Authorization failed. Reason {0} {1}\".format(\n                    r.status_code, reason)\n                )\n        else:\n            data = r.json()[\"data\"]\n            self.token = data[\"access_token\"]\n            if \"refresh_token\" in data:\n                self.auth_data = {\n                    \"grant_type\": \"refresh_token\",\n                    \"refresh_token\": data[\"refresh_token\"],\n                    \"client_id\": self.auth_data[\"client_id\"]\n                }",
    "docstring": "Perform the authorization"
  },
  {
    "code": "def create_db(self):\n        self.add_role(self.auth_role_admin)\n        self.add_role(self.auth_role_public)\n        if self.count_users() == 0:\n            log.warning(LOGMSG_WAR_SEC_NO_USER)",
    "docstring": "Setups the DB, creates admin and public roles if they don't exist."
  },
  {
    "code": "def get_ss_class(pdb_file, dssp_file, chain):\n    prag = pr.parsePDB(pdb_file)\n    pr.parseDSSP(dssp_file, prag)\n    alpha, threeTen, beta = get_dssp_ss_content_multiplechains(prag, chain)\n    if alpha == 0 and beta > 0:\n        classification = 'all-beta'\n    elif beta == 0 and alpha > 0:\n        classification = 'all-alpha'\n    elif beta == 0 and alpha == 0:\n        classification = 'mixed'\n    elif float(alpha) / beta >= 20:\n        classification = 'all-alpha'\n    else:\n        classification = 'mixed'\n    return classification",
    "docstring": "Define the secondary structure class of a PDB file at the specific chain\n\n    Args:\n        pdb_file:\n        dssp_file:\n        chain:\n\n    Returns:"
  },
  {
    "code": "def _compute(self):\n        tendencies = {}\n        for name, value in self.state.items():\n            tendencies[name] = value * 0.\n        return tendencies",
    "docstring": "Where the tendencies are actually computed...\n\n        Needs to be implemented for each daughter class\n\n        Returns a dictionary with same keys as self.state"
  },
  {
    "code": "def pprint_ast(node,\n               include_attributes=INCLUDE_ATTRIBUTES_DEFAULT,\n               indent=INDENT_DEFAULT,\n               file=None):\n    if file is None:\n        file = sys.stdout\n    print(\n        pformat_ast(\n            node,\n            include_attributes=include_attributes,\n            indent=indent\n        ),\n        file=file,\n    )",
    "docstring": "Pretty-print an AST tree.\n\n    Parameters\n    ----------\n    node : ast.AST\n       Top-level node to render.\n    include_attributes : bool, optional\n        Whether to include node attributes.  Default False.\n    indent : str, optional.\n        Indentation string for nested expressions.  Default is two spaces.\n    file : None or file-like object, optional\n        File to use to print output.  If the default of `None` is passed, we\n        use sys.stdout."
  },
  {
    "code": "def from_pubkey_line(cls, line):\n        options, key_without_options = cls._extract_options(line)\n        if key_without_options == '':\n            raise ValueError(\"Empty key\")\n        fields = key_without_options.strip().split(None, 2)\n        if len(fields) == 3:\n            type_str, data64, comment = fields\n        elif len(fields) == 2:\n            type_str, data64 = fields\n            comment = None\n        else:\n            raise ValueError(\"Key has insufficient number of fields\")\n        try:\n            data = b64decode(data64)\n        except (binascii.Error, TypeError):\n            raise ValueError(\"Key contains invalid data\")\n        key_type = next(iter_prefixed(data))\n        if key_type == b'ssh-rsa':\n            key_class = RSAKey\n        elif key_type == b'ssh-dss':\n            key_class = DSAKey\n        elif key_type.startswith(b'ecdsa-'):\n            key_class = ECDSAKey\n        else:\n            raise ValueError('Unknown key type {}'.format(key_type))\n        return key_class(b64decode(data64), comment, options=options)",
    "docstring": "Generate Key instance from a a string. Raise ValueError if string is\n        malformed"
  },
  {
    "code": "def infos_on_basis_set(self):\n        o = []\n        o.append(\"=========================================\")\n        o.append(\"Reading basis set:\")\n        o.append(\"\")\n        o.append(\" Basis set for {} atom \".format(str(self.filename)))\n        o.append(\" Maximum angular momentum = {}\".format(self.data['lmax']))\n        o.append(\" Number of atomics orbitals = {}\".format(self.data['n_nlo']))\n        o.append(\" Number of nlm orbitals = {}\".format(self.data['n_nlmo']))\n        o.append(\"=========================================\")\n        return str(0)",
    "docstring": "infos on the basis set as in Fiesta log"
  },
  {
    "code": "def UpdateSet(self, dataset):\n        for data in dataset:\n            for hypo in self.Values():\n                like = self.Likelihood(data, hypo)\n                self.Mult(hypo, like)\n        return self.Normalize()",
    "docstring": "Updates each hypothesis based on the dataset.\n\n        This is more efficient than calling Update repeatedly because\n        it waits until the end to Normalize.\n\n        Modifies the suite directly; if you want to keep the original, make\n        a copy.\n\n        dataset: a sequence of data\n\n        returns: the normalizing constant"
  },
  {
    "code": "def python_to_ucn(uni_char, as_bytes=False):\n    ucn = uni_char.encode('unicode_escape').decode('latin1')\n    ucn = text_type(ucn).replace('\\\\', '').upper().lstrip('U')\n    if len(ucn) > int(4):\n        ucn = ucn.lstrip(\"0\")\n    ucn = \"U+\" + ucn.upper()\n    if as_bytes:\n        ucn = ucn.encode('latin1')\n    return ucn",
    "docstring": "Return UCN character from Python Unicode character.\n\n    Converts a one character Python unicode string (e.g. u'\\\\u4e00') to the\n    corresponding Unicode UCN ('U+4E00')."
  },
  {
    "code": "def start():\n        action_set('meta.start', time.strftime('%Y-%m-%dT%H:%M:%SZ'))\n        COLLECT_PROFILE_DATA = '/usr/local/bin/collect-profile-data'\n        if os.path.exists(COLLECT_PROFILE_DATA):\n            subprocess.check_output([COLLECT_PROFILE_DATA])",
    "docstring": "If the collectd charm is also installed, tell it to send a snapshot\n        of the current profile data."
  },
  {
    "code": "def get_format(self):\n        url = self.build_url(self._endpoints.get('get_format'))\n        response = self.session.get(url)\n        if not response:\n            return None\n        return self.range_format_constructor(parent=self, **{self._cloud_data_key: response.json()})",
    "docstring": "Returns a RangeFormat instance with the format of this range"
  },
  {
    "code": "def _parse(self, stream, context, path):\n        length = self.length(context)\n        new_stream = BytesIO(construct.core._read_stream(stream, length))\n        return self.subcon._parse(new_stream, context, path)",
    "docstring": "Parse tunnel."
  },
  {
    "code": "def _AnyMessageToJsonObject(self, message):\n    if not message.ListFields():\n      return {}\n    js = OrderedDict()\n    type_url = message.type_url\n    js['@type'] = type_url\n    sub_message = _CreateMessageFromTypeUrl(type_url)\n    sub_message.ParseFromString(message.value)\n    message_descriptor = sub_message.DESCRIPTOR\n    full_name = message_descriptor.full_name\n    if _IsWrapperMessage(message_descriptor):\n      js['value'] = self._WrapperMessageToJsonObject(sub_message)\n      return js\n    if full_name in _WKTJSONMETHODS:\n      js['value'] = methodcaller(_WKTJSONMETHODS[full_name][0],\n                                 sub_message)(self)\n      return js\n    return self._RegularMessageToJsonObject(sub_message, js)",
    "docstring": "Converts Any message according to Proto3 JSON Specification."
  },
  {
    "code": "def init(name, *args, **kwargs):\n    if name in _PLUGIN_CATALOG:\n        if rapport.config.get_int(\"rapport\", \"verbosity\") >= 2:\n            print(\"Initialize plugin {0}: {1} {2}\".format(name, args, kwargs))\n        try:\n            return _PLUGIN_CATALOG[name](*args, **kwargs)\n        except (ValueError, TypeError) as e:\n            print(\"Failed to initialize plugin {0}: {1}!\".format(name, e), file=sys.stderr)\n    else:\n        print(\"Failed to initialize plugin {0}: Not in catalog!\".format(name), file=sys.stderr)",
    "docstring": "Instantiate a plugin from the catalog."
  },
  {
    "code": "def substitute_symbol_table(table, version, max_id):\n    if not table.table_type.is_shared:\n        raise ValueError('Symbol table to substitute from must be a shared table')\n    if version <= 0:\n        raise ValueError('Version must be grater than or equal to 1: %s' % version)\n    if max_id < 0:\n        raise ValueError('Max ID must be zero or positive: %s' % max_id)\n    if max_id <= table.max_id:\n        symbols = (token.text for token in islice(table, max_id))\n    else:\n        symbols = chain(\n            (token.text for token in table),\n            repeat(None, max_id - table.max_id)\n        )\n    return SymbolTable(\n        table_type=SHARED_TABLE_TYPE,\n        symbols=symbols,\n        name=table.name,\n        version=version,\n        is_substitute=True\n    )",
    "docstring": "Substitutes a given shared symbol table for another version.\n\n    * If the given table has **more** symbols than the requested substitute, then the generated\n      symbol table will be a subset of the given table.\n    * If the given table has **less** symbols than the requested substitute, then the generated\n      symbol table will have symbols with unknown text generated for the difference.\n\n    Args:\n        table (SymbolTable): The shared table to derive from.\n        version (int): The version to target.\n        max_id (int): The maximum ID allocated by the substitute, must be ``>= 0``.\n\n    Returns:\n        SymbolTable: The synthesized table."
  },
  {
    "code": "def fit(self, X, y=None, categorical=None):\n        if categorical is not None:\n            assert isinstance(categorical, (int, list, tuple)), \"The 'categorical' \\\n                argument needs to be an integer with the index of the categorical \\\n                column in your data, or a list or tuple of several of them, \\\n                but it is a {}.\".format(type(categorical))\n        X = pandas_to_numpy(X)\n        random_state = check_random_state(self.random_state)\n        self._enc_cluster_centroids, self._enc_map, self.labels_, self.cost_,\\\n            self.n_iter_, self.gamma = k_prototypes(X,\n                                                    categorical,\n                                                    self.n_clusters,\n                                                    self.max_iter,\n                                                    self.num_dissim,\n                                                    self.cat_dissim,\n                                                    self.gamma,\n                                                    self.init,\n                                                    self.n_init,\n                                                    self.verbose,\n                                                    random_state,\n                                                    self.n_jobs)\n        return self",
    "docstring": "Compute k-prototypes clustering.\n\n        Parameters\n        ----------\n        X : array-like, shape=[n_samples, n_features]\n        categorical : Index of columns that contain categorical data"
  },
  {
    "code": "def nextChild(hotmap, index):\n        nextChildIndex = min(index + 1, len(hotmap) - 1)\n        return hotmap[nextChildIndex][1]",
    "docstring": "Return the next sibling of the node indicated by index."
  },
  {
    "code": "def _deserialize_dict(data, boxed_type):\n    return {k: _deserialize(v, boxed_type)\n            for k, v in six.iteritems(data)}",
    "docstring": "Deserializes a dict and its elements.\n\n    :param data: dict to deserialize.\n    :type data: dict\n    :param boxed_type: class literal.\n\n    :return: deserialized dict.\n    :rtype: dict"
  },
  {
    "code": "def _process_messages(self, messages, ignore_unknown_message_types=False):\n        with self.before_after_send_handling():\n            for message_id, message_data in messages.items():\n                message_model, dispatch_models = message_data\n                try:\n                    message_cls = get_registered_message_type(message_model.cls)\n                except UnknownMessageTypeError:\n                    if ignore_unknown_message_types:\n                        continue\n                    raise\n                message_type_cache = None\n                for dispatch in dispatch_models:\n                    if not dispatch.message_cache:\n                        try:\n                            if message_type_cache is None and not message_cls.has_dynamic_context:\n                                message_type_cache = message_cls.compile(message_model, self, dispatch=dispatch)\n                            dispatch.message_cache = message_type_cache or message_cls.compile(\n                                message_model, self, dispatch=dispatch)\n                        except Exception as e:\n                            self.mark_error(dispatch, e, message_cls)\n                self.send(message_cls, message_model, dispatch_models)",
    "docstring": "Performs message processing.\n\n        :param dict messages: indexed by message id dict with messages data\n        :param bool ignore_unknown_message_types: whether to silence exceptions\n        :raises UnknownMessageTypeError:"
  },
  {
    "code": "def _retrieve_and_validate_certificate_chain(self, cert_url):\n        self._validate_certificate_url(cert_url)\n        cert_chain = self._load_cert_chain(cert_url)\n        self._validate_cert_chain(cert_chain)\n        return cert_chain",
    "docstring": "Retrieve and validate certificate chain.\n\n        This method validates if the URL is valid and loads and\n        validates the certificate chain, before returning it.\n\n        :param cert_url: URL for retrieving certificate chain\n        :type cert_url: str\n        :return The certificate chain loaded from the URL\n        :rtype cryptography.x509.Certificate\n        :raises: :py:class:`VerificationException` if the URL is invalid,\n            if the loaded certificate chain is invalid"
  },
  {
    "code": "def filter(self):\n        logging.info('Filtering contigs')\n        for i in range(self.cpus):\n            threads = Thread(target=self.filterthreads, args=())\n            threads.setDaemon(True)\n            threads.start()\n        with progressbar(self.metadata) as bar:\n            for sample in bar:\n                if sample.general.bestassemblyfile != 'NA':\n                    sample.general.contigsfile = sample.general.assemblyfile\n                    self.filterqueue.put(sample)\n        self.filterqueue.join()",
    "docstring": "Filter contigs based on depth"
  },
  {
    "code": "def bootstrap_stat(arr, stat=np.mean, n_iters=1000, alpha=0.05):\n    stat_orig = stat(arr, 0)\n    boot_arr = np.empty((arr.shape[-1] , n_iters))\n    for ii in xrange(n_iters):\n        this_arr=arr[np.random.random_integers(0, arr.shape[0]-1, arr.shape[0])]\n        boot_arr[:, ii] = stat(this_arr, 0)\n    eb = np.array([stats.scoreatpercentile(boot_arr[xx], 1-(alpha/2)) -\n                   stats.scoreatpercentile(boot_arr[xx], alpha/2)\n                   for xx in range(boot_arr.shape[0])])\n    return stat_orig, eb",
    "docstring": "Produce a boot-strap distribution of the mean of an array on axis 0\n\n    Parameters\n    ---------\n    arr : ndarray\n       The array with data to be bootstrapped\n\n    stat : callable\n        The statistical function to call. will be called as `stat(arr, 0)`, so\n        needs to accept that call signature.\n\n    n_iters : int\n        The number of bootstrap iterations to sample\n\n    alpha : float\n       The confidence interval size will be 1-alpha"
  },
  {
    "code": "def style_defs(cls):\n        formatter = HtmlFormatter()\n        formatter.style.highlight_color = cls.VIOLATION_COLOR\n        return formatter.get_style_defs()",
    "docstring": "Return the CSS style definitions required\n        by the formatted snippet."
  },
  {
    "code": "def descriptions(self):\n        return {key: val[2] for key, val in six.iteritems(self.defaultParams)\n                if len(val) >= 3}",
    "docstring": "The description of each keyword in the rcParams dictionary"
  },
  {
    "code": "def list_policies(self, filters=None):\n        _, policy_list = self.handler.streamed_request(\"list-policies\",\n                                                       \"list-policy\", filters)\n        return policy_list",
    "docstring": "Retrieve installed trap, drop and bypass policies.\n\n        :param filters: retrieve only matching policies (optional)\n        :type filters: dict\n        :return: list of installed trap, drop and bypass policies\n        :rtype: list"
  },
  {
    "code": "def get_hash(self, shallow=True, refresh=False):\n        if shallow:\n            if not hasattr(self, '_shallow_hash') or self._shallow_hash is None\\\n                    or refresh:\n                self._shallow_hash = make_hash(self.matches_key(), 14)\n            ret = self._shallow_hash\n        else:\n            if not hasattr(self, '_full_hash') or self._full_hash is None \\\n                    or refresh:\n                ev_mk_list = sorted([ev.matches_key() for ev in self.evidence])\n                self._full_hash = \\\n                    make_hash(self.matches_key() + str(ev_mk_list), 16)\n            ret = self._full_hash\n        return ret",
    "docstring": "Get a hash for this Statement.\n\n        There are two types of hash, \"shallow\" and \"full\". A shallow hash is\n        as unique as the information carried by the statement, i.e. it is a hash\n        of the `matches_key`. This means that differences in source, evidence,\n        and so on are not included. As such, it is a shorter hash (14 nibbles).\n        The odds of a collision among all the statements we expect to encounter\n        (well under 10^8) is ~10^-9 (1 in a billion). Checks for collisions can\n        be done by using the matches keys.\n\n        A full hash includes, in addition to the matches key, information from\n        the evidence of the statement. These hashes will be equal if the two\n        Statements came from the same sentences, extracted by the same reader,\n        from the same source. These hashes are correspondingly longer (16\n        nibbles). The odds of a collision for an expected less than 10^10\n        extractions is ~10^-9 (1 in a billion).\n\n        Note that a hash of the Python object will also include the `uuid`, so\n        it will always be unique for every object.\n\n        Parameters\n        ----------\n        shallow : bool\n            Choose between the shallow and full hashes described above. Default\n            is true (e.g. a shallow hash).\n        refresh : bool\n            Used to get a new copy of the hash. Default is false, so the hash,\n            if it has been already created, will be read from the attribute.\n            This is primarily used for speed testing.\n\n        Returns\n        -------\n        hash : int\n            A long integer hash."
  },
  {
    "code": "def blend_color(color, color2):\n    r1, g1, b1 = hex_to_rgb(color)\n    r2, g2, b2 = hex_to_rgb(color2)\n    r3 = int(0.5 * r1 + 0.5 * r2)\n    g3 = int(0.5 * g1 + 0.5 * g2)\n    b3 = int(0.5 * b1 + 0.5 * b2)\n    return rgb_to_hex((r3, g3, b3))",
    "docstring": "Blend two colors together."
  },
  {
    "code": "def _get_xml_dom(self):\n        if self.site_control == SITE_CONTROL_NONE and \\\n           any((self.domains, self.header_domains, self.identities)):\n            raise TypeError(BAD_POLICY)\n        policy_type = minidom.createDocumentType(\n            qualifiedName='cross-domain-policy',\n            publicId=None,\n            systemId='http://www.adobe.com/xml/dtds/cross-domain-policy.dtd'\n        )\n        policy = minidom.createDocument(\n            None,\n            'cross-domain-policy',\n            policy_type\n        )\n        if self.site_control is not None:\n            control_element = policy.createElement('site-control')\n            control_element.setAttribute(\n                'permitted-cross-domain-policies',\n                self.site_control\n            )\n            policy.documentElement.appendChild(control_element)\n        for elem_type in ('domains', 'header_domains', 'identities'):\n            getattr(self, '_add_{}_xml'.format(elem_type))(policy)\n        return policy",
    "docstring": "Collects all options set so far, and produce and return an\n        ``xml.dom.minidom.Document`` representing the corresponding\n        XML."
  },
  {
    "code": "def all_ports(self):\n        from mbuild.port import Port\n        return [successor for successor in self.successors()\n                if isinstance(successor, Port)]",
    "docstring": "Return all Ports referenced by this Compound and its successors\n\n        Returns\n        -------\n        list of mb.Compound\n            A list of all Ports referenced by this Compound and its successors"
  },
  {
    "code": "def get_system_bck_color():\n        def merged_colors(colorA, colorB, factor):\n            maxFactor = 100\n            colorA = QtGui.QColor(colorA)\n            colorB = QtGui.QColor(colorB)\n            tmp = colorA\n            tmp.setRed((tmp.red() * factor) / maxFactor +\n                       (colorB.red() * (maxFactor - factor)) / maxFactor)\n            tmp.setGreen((tmp.green() * factor) / maxFactor +\n                         (colorB.green() * (maxFactor - factor)) / maxFactor)\n            tmp.setBlue((tmp.blue() * factor) / maxFactor +\n                        (colorB.blue() * (maxFactor - factor)) / maxFactor)\n            return tmp\n        pal = QtWidgets.QApplication.instance().palette()\n        b = pal.window().color()\n        h = pal.highlight().color()\n        return merged_colors(b, h, 50)",
    "docstring": "Gets a system color for drawing the fold scope background."
  },
  {
    "code": "def ExamineEvent(self, mediator, event):\n    self._EnsureRequesterStarted()\n    path_spec = event.pathspec\n    event_identifiers = self._event_identifiers_by_pathspec[path_spec]\n    event_identifier = event.GetIdentifier()\n    event_identifiers.append(event_identifier)\n    if event.data_type not in self.DATA_TYPES or not self._analyzer.lookup_hash:\n      return\n    lookup_hash = '{0:s}_hash'.format(self._analyzer.lookup_hash)\n    lookup_hash = getattr(event, lookup_hash, None)\n    if not lookup_hash:\n      display_name = mediator.GetDisplayNameForPathSpec(path_spec)\n      logger.warning((\n          'Lookup hash attribute: {0:s}_hash missing from event that '\n          'originated from: {1:s}.').format(\n              self._analyzer.lookup_hash, display_name))\n      return\n    path_specs = self._hash_pathspecs[lookup_hash]\n    path_specs.append(path_spec)\n    if len(path_specs) == 1:\n      self.hash_queue.put(lookup_hash)",
    "docstring": "Evaluates whether an event contains the right data for a hash lookup.\n\n    Args:\n      mediator (AnalysisMediator): mediates interactions between\n          analysis plugins and other components, such as storage and dfvfs.\n      event (EventObject): event."
  },
  {
    "code": "def unwrap(self, value, session=None):\n        self.validate_unwrap(value)\n        value = self.item_type.unwrap(value, session=session)\n        for val in self.values:\n            if val == value:\n                return val\n        self._fail_validation(value, 'Value was not in the enum values')",
    "docstring": "Unwrap value using the unwrap function from ``EnumField.item_type``.\n            Since unwrap validation could not happen in is_valid_wrap, it\n            happens in this function."
  },
  {
    "code": "def auth_with_token(self, token, tenant_id=None, tenant_name=None):\n        main_resp, main_body = self._call_token_auth(token, tenant_id,\n                tenant_name)\n        roles = main_body[\"access\"][\"user\"][\"roles\"]\n        ostore = [role for role in roles\n                if role[\"name\"] == \"object-store:default\"]\n        if ostore:\n            ostore_tenant_id = ostore[0][\"tenantId\"]\n            ostore_resp, ostore_body = self._call_token_auth(token,\n                    ostore_tenant_id, None)\n            ostore_cat = ostore_body[\"access\"][\"serviceCatalog\"]\n            main_cat = main_body[\"access\"][\"serviceCatalog\"]\n            main_cat.extend(ostore_cat)\n        self._parse_response(main_body)\n        self.authenticated = True",
    "docstring": "If a valid token is already known, this call will use it to generate\n        the service catalog."
  },
  {
    "code": "def register_namespace(self, namespace, module):\n        if namespace in self._namespaces:\n            raise AlreadyRegisteredError(\"Namespace '{0}' is already registered on loader.\".format(namespace))\n        self._namespaces[namespace] = module",
    "docstring": "Register a namespace.\n\n        :param namespace: Namespace tag.\n        :type namespace: str\n        :param module: must be a string or a module object to register.\n        :type module: str"
  },
  {
    "code": "def csv_row_to_transaction(index, row, source_encoding=\"latin1\",\n            date_format=\"%d-%m-%Y\", thousand_sep=\".\", decimal_sep=\",\"):\n        xfer, posted, message, amount, total = row\n        xfer = Parse.date(xfer)\n        posted = Parse.date(posted)\n        message = Parse.to_utf8(message, source_encoding)\n        amount = Parse.money(amount)\n        total = Parse.money(total)\n        return Transaction(index, xfer, posted, message, amount, total)",
    "docstring": "Parses a row of strings to a ``Transaction`` object.\n\n        Args:\n            index: The index of this row in the original CSV file. Used for\n            sorting ``Transaction``s by their order of appearance.\n\n            row: The row containing strings for [transfer_date, posted_date,\n            message, money_amount, money_total].\n\n            source_encoding: The encoding that will be used to decode strings\n            to UTF-8.\n\n            date_format: The format of dates in this row.\n\n            thousand_sep: The thousand separator in money amounts.\n\n            decimal_sep: The decimal separator in money amounts.\n\n        Returns:\n            A ``Transaction`` object."
  },
  {
    "code": "def push(self, record, shard):\n        heapq.heappush(self.heap, heap_item(self.clock, record, shard))",
    "docstring": "Push a new record into the buffer\n\n        :param dict record: new record\n        :param shard: Shard the record came from\n        :type shard: :class:`~bloop.stream.shard.Shard`"
  },
  {
    "code": "def _finish_pending_requests(self) -> None:\n        while True:\n            num_q, ok_list, err_list = self._multi.info_read()\n            for curl in ok_list:\n                self._finish(curl)\n            for curl, errnum, errmsg in err_list:\n                self._finish(curl, errnum, errmsg)\n            if num_q == 0:\n                break\n        self._process_queue()",
    "docstring": "Process any requests that were completed by the last\n        call to multi.socket_action."
  },
  {
    "code": "def spi_ss_polarity(self, polarity):\n        ret = api.py_aa_spi_master_ss_polarity(self.handle, polarity)\n        _raise_error_if_negative(ret)",
    "docstring": "Change the ouput polarity on the SS line.\n\n        Please note, that this only affects the master functions."
  },
  {
    "code": "def title(cls, message=None):\n        if message == None:\n            return getproctitle()\n        else:\n            setproctitle('qless-py-worker %s' % message)\n            logger.info(message)",
    "docstring": "Set the title of the process"
  },
  {
    "code": "def summary_plot(data):\n        cats = OrderedDict()\n        cats = {\n            'inniepairs': {\n                'name': 'Combined innie pairs',\n                'color': '\n            },\n            'outiepairs': {\n                'name': 'Combined outie pairs',\n                'color': '\n            },\n            'uncombopairs': {\n                'name': 'Uncombined pairs',\n                'color': '\n            },\n            'discardpairs': {\n                'name': 'Discarded pairs',\n                'color': '\n            }\n        }\n        splotconfig = {'id': 'flash_combo_stats_plot',\n                       'title': 'FLASh: Read combination statistics',\n                       'ylab': 'Number of read pairs',\n                       'hide_zero_cats': False }\n        return bargraph.plot(data, cats, splotconfig)",
    "docstring": "Barplot of combined pairs"
  },
  {
    "code": "def parsed(self):\n        if not self._parsed:\n            self._parsed = ConfigParser()\n            self._parsed.readfp(io.StringIO(self.content))\n        return self._parsed",
    "docstring": "Get the ConfigParser object which represents the content.\n\n        This property is cached and only parses the content once."
  },
  {
    "code": "def array_to_json(array_like):\n    def default(_array_like):\n        if hasattr(_array_like, 'tolist'):\n            return _array_like.tolist()\n        return json.JSONEncoder().default(_array_like)\n    return json.dumps(array_like, default=default)",
    "docstring": "Convert an array like object to JSON.\n\n    To understand better what an array like object is see:\n    https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays\n\n    Args:\n        array_like (np.array or Iterable or int or float): array like object to be converted to JSON.\n\n    Returns:\n        (str): object serialized to JSON"
  },
  {
    "code": "def check_type_and_size_of_param_list(param_list, expected_length):\n    try:\n        assert isinstance(param_list, list)\n        assert len(param_list) == expected_length\n    except AssertionError:\n        msg = \"param_list must be a list containing {} elements.\"\n        raise ValueError(msg.format(expected_length))\n    return None",
    "docstring": "Ensure that param_list is a list with the expected length. Raises a helpful\n    ValueError if this is not the case."
  },
  {
    "code": "def read_archive(archive, fname):\n    zfile = zipfile.ZipFile(archive)\n    contents = zfile.open(fname, 'r')\n    fobj = io.TextIOWrapper(contents)\n    seen = set()\n    for line in fobj:\n        line = line.rstrip('\\t|\\n')\n        if line not in seen:\n            yield line.split('\\t|\\t')\n            seen.add(line)",
    "docstring": "Return an iterator of unique rows from a zip archive.\n\n    * archive - path to the zip archive.\n    * fname - name of the compressed file within the archive."
  },
  {
    "code": "def _load_ssh_files(self):\n        if self._runtime_ssh_path is not None:\n            path = self._runtime_ssh_path\n            if not os.path.exists(path):\n                msg = \"No such file or directory: {!r}\".format(path)\n                raise IOError(errno.ENOENT, msg)\n            self._load_ssh_file(os.path.expanduser(path))\n        elif self.load_ssh_configs:\n            for path in (self._user_ssh_path, self._system_ssh_path):\n                self._load_ssh_file(os.path.expanduser(path))",
    "docstring": "Trigger loading of configured SSH config file paths.\n\n        Expects that ``base_ssh_config`` has already been set to an\n        `~paramiko.config.SSHConfig` object.\n\n        :returns: ``None``."
  },
  {
    "code": "def get_route_streams(self, route_id):\n        result_fetcher = functools.partial(self.protocol.get,\n                                           '/routes/{id}/streams/'.format(id=route_id))\n        streams = BatchedResultsIterator(entity=model.Stream,\n                                         bind_client=self,\n                                         result_fetcher=result_fetcher)\n        return {i.type: i for i in streams}",
    "docstring": "Returns streams for a route.\n\n        http://strava.github.io/api/v3/streams/#routes\n\n        Streams represent the raw data of the saved route. External\n        applications may access this information for all public routes and for\n        the private routes of the authenticated athlete.\n\n        The 3 available route stream types `distance`, `altitude` and `latlng`\n        are always returned.\n\n        http://strava.github.io/api/v3/streams/#routes\n\n        :param activity_id: The ID of activity.\n        :type activity_id: int\n\n        :return: A dictionary of :class:`stravalib.model.Stream`from the route.\n        :rtype: :py:class:`dict`"
  },
  {
    "code": "def get_catalog_query_session(self):\n        if not self.supports_catalog_query():\n            raise errors.Unimplemented()\n        return sessions.CatalogQuerySession(runtime=self._runtime)",
    "docstring": "Gets the catalog query session.\n\n        return: (osid.cataloging.CatalogQuerySession) - a\n                ``CatalogQuerySession``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_catalog_query()`` is\n                ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_catalog_query()`` is ``true``.*"
  },
  {
    "code": "def compile(self):\n        self.context.set_query(self)\n        with_frag = self.format_subqueries()\n        select_frag = self.format_select_set()\n        from_frag = self.format_table_set()\n        where_frag = self.format_where()\n        groupby_frag = self.format_group_by()\n        order_frag = self.format_order_by()\n        limit_frag = self.format_limit()\n        query = '\\n'.join(\n            filter(\n                None,\n                [\n                    with_frag,\n                    select_frag,\n                    from_frag,\n                    where_frag,\n                    groupby_frag,\n                    order_frag,\n                    limit_frag,\n                ],\n            )\n        )\n        return query",
    "docstring": "This method isn't yet idempotent; calling multiple times may yield\n        unexpected results"
  },
  {
    "code": "def _appendstore(self, store):\n        if not store.bitlength:\n            return\n        store = offsetcopy(store, (self.offset + self.bitlength) % 8)\n        if store.offset:\n            joinval = (self._rawarray.pop() & (255 ^ (255 >> store.offset)) |\n                       (store.getbyte(0) & (255 >> store.offset)))\n            self._rawarray.append(joinval)\n            self._rawarray.extend(store._rawarray[1:])\n        else:\n            self._rawarray.extend(store._rawarray)\n        self.bitlength += store.bitlength",
    "docstring": "Join another store on to the end of this one."
  },
  {
    "code": "def write_bibtex_dict(stream, entries):\n    from bibtexparser.bwriter import BibTexWriter\n    writer = BibTexWriter()\n    writer.indent = '  '\n    writer.entry_separator = ''\n    first = True\n    for rec in entries:\n        if first:\n            first = False\n        else:\n            stream.write(b'\\n')\n        stream.write(writer._entry_to_bibtex(rec).encode('utf8'))",
    "docstring": "bibtexparser.write converts the entire database to one big string and\n    writes it out in one go. I'm sure it will always all fit in RAM but some\n    things just will not stand."
  },
  {
    "code": "def symmetrically_add_atom(self, specie, point, coords_are_cartesian=False):\n        point2 = self.get_symmetric_site(point, cartesian=coords_are_cartesian)\n        self.append(specie, point, coords_are_cartesian=coords_are_cartesian)\n        self.append(specie, point2, coords_are_cartesian=coords_are_cartesian)",
    "docstring": "Class method for adding a site at a specified point in a slab.\n            Will add the corresponding site on the other side of the\n            slab to maintain equivalent surfaces.\n\n        Arg:\n            specie (str): The specie to add\n            point (coords): The coordinate of the site in the slab to add.\n            coords_are_cartesian (bool): Is the point in cartesian coordinates\n\n        Returns:\n            (Slab): The modified slab"
  },
  {
    "code": "def created(self):\n        if 'id_perms' not in self:\n            self.fetch()\n        created = self['id_perms']['created']\n        return datetime.strptime(created, '%Y-%m-%dT%H:%M:%S.%f')",
    "docstring": "Return creation date\n\n        :rtype: datetime\n        :raises ResourceNotFound: resource not found on the API"
  },
  {
    "code": "def replace_missing_value(self, str_in):\n        if self.missing_value is None:\n            return str_in\n        elif self.missing_value.sentinel == str_in:\n            return self.missing_value.replace_with\n        else:\n            return str_in",
    "docstring": "returns 'str_in' if it is not equals to the 'sentinel' as\n        defined in the missingValue section of\n        the schema. Else it will return the 'replaceWith' value.\n\n        :param str_in:\n        :return: str_in or the missingValue replacement value"
  },
  {
    "code": "def setXr(self, Xr):\n        self.Xr = Xr\n        self.gp_block.covar.G = Xr",
    "docstring": "set genotype data of the set component"
  },
  {
    "code": "def documentation(self, level='first'):\n        docs = (t.docstring for t in list(self.conjunction.terms) + [self]\n                if t.docstring is not None)\n        if level.lower() == 'first':\n            doc = next(docs, None)\n        elif level.lower() == 'top':\n            doc = list(docs)\n        return doc",
    "docstring": "Return the documentation of the type.\n\n        By default, this is the first docstring on a top-level term.\n        By setting *level* to `\"top\"`, the list of all docstrings on\n        top-level terms is returned, including the type's `docstring`\n        value, if not `None`, as the last item. The docstring for the\n        type itself is available via :attr:`TypeDefinition.docstring`.\n\n        Args:\n            level (str): `\"first\"` or `\"top\"`\n        Returns:\n            a single docstring or a list of docstrings"
  },
  {
    "code": "def transpose(self, semitone):\n        for track in self.tracks:\n            if not track.is_drum:\n                track.transpose(semitone)",
    "docstring": "Transpose the pianorolls of all tracks by a number of semitones, where\n        positive values are for higher key, while negative values are for lower\n        key. The drum tracks are ignored.\n\n        Parameters\n        ----------\n        semitone : int\n            The number of semitones to transpose the pianorolls."
  },
  {
    "code": "def deletecols(X, cols):\n    if isinstance(cols, str):\n        cols = cols.split(',')\n    retain = [n for n in X.dtype.names if n not in cols]\n    if len(retain) > 0:\n        return X[retain]\n    else:\n        return None",
    "docstring": "Delete columns from a numpy ndarry or recarray.\n\n    Can take a string giving a column name or comma-separated list of column \n    names, or a list of string column names.\n\n    Implemented by the tabarray method \n    :func:`tabular.tab.tabarray.deletecols`.\n\n    **Parameters**\n\n            **X** :  numpy recarray or ndarray with structured dtype\n\n                    The numpy array from which to delete columns.\n\n            **cols** :  string or list of strings\n\n                    Name or list of names of columns in `X`.  This can be\n                    a string giving a column name or comma-separated list of \n                    column names, or a list of string column names.\n\n    **Returns**\n\n            **out** :  numpy ndarray with structured dtype\n\n                    New numpy ndarray with structured dtype\n                    given by `X`, excluding the columns named in `cols`."
  },
  {
    "code": "def from_client(catalog, client_id, lowcut, highcut, samp_rate, filt_order,\n                length, prepick, swin, process_len=86400, data_pad=90,\n                all_horiz=False, delayed=True, plot=False, debug=0,\n                return_event=False, min_snr=None):\n    EQcorrscanDeprecationWarning(\n        \"Function is depreciated and will be removed soon. Use \"\n        \"template_gen.template_gen instead.\")\n    temp_list = template_gen(\n        method=\"from_client\", catalog=catalog, client_id=client_id,\n        lowcut=lowcut, highcut=highcut, samp_rate=samp_rate,\n        filt_order=filt_order, length=length, prepick=prepick,\n        swin=swin, process_len=process_len, data_pad=data_pad,\n        all_horiz=all_horiz, delayed=delayed, plot=plot, debug=debug,\n        return_event=return_event, min_snr=min_snr)\n    return temp_list",
    "docstring": "Generate multiplexed template from FDSN client.\n\n    Function to generate templates from an FDSN client. Must be given \\\n    an obspy.Catalog class and the client_id as input. The function returns \\\n    a list of obspy.Stream classes containing steams for each desired \\\n    template.\n\n    :type catalog: obspy.core.event.Catalog\n    :param catalog: Catalog class containing desired template events\n    :type client_id: str\n    :param client_id: Name of the client, either url, or Obspy \\\n        mappable (see the :mod:`obspy.clients.fdsn` documentation).\n    :type lowcut: float\n    :param lowcut: Low cut (Hz), if set to None will not apply a lowcut.\n    :type highcut: float\n    :param highcut: High cut (Hz), if set to None will not apply a highcut.\n    :type samp_rate: float\n    :param samp_rate: New sampling rate in Hz.\n    :type filt_order: int\n    :param filt_order: Filter level (number of corners).\n    :type length: float\n    :param length: Extract length in seconds.\n    :type prepick: float\n    :param prepick: Pre-pick time in seconds\n    :type swin: str\n    :param swin:\n        P, S, P_all, S_all or all, defaults to all: see note in\n        :func:`eqcorrscan.core.template_gen.template_gen`\n    :type process_len: int\n    :param process_len: Length of data in seconds to download and process.\n    :param data_pad: Length of data (in seconds) required before and after \\\n        any event for processing, use to reduce edge-effects of filtering on \\\n        the templates.\n    :type data_pad: int\n    :type all_horiz: bool\n    :param all_horiz: To use both horizontal channels even if there is only \\\n        a pick on one of them.  Defaults to False.\n    :type delayed: bool\n    :param delayed: If True, each channel will begin relative to it's own \\\n        pick-time, if set to False, each channel will begin at the same time.\n    :type plot: bool\n    :param plot: Plot templates or not.\n    :type debug: int\n    :param debug: Level of debugging output, higher=more\n    :type return_event: bool\n    :param return_event: Whether to return the event and process length or not.\n    :type min_snr: float\n    :param min_snr:\n        Minimum signal-to-noise ratio for a channel to be included in the\n        template, where signal-to-noise ratio is calculated as the ratio of\n        the maximum amplitude in the template window to the rms amplitude in\n        the whole window given.\n\n    :returns: List of :class:`obspy.core.stream.Stream` Templates\n    :rtype: list\n\n    .. warning::\n        This function is depreciated and will be removed in a forthcoming\n        release. Please use `template_gen` instead.\n\n    .. note::\n        process_len should be set to the same length as used when computing\n        detections using match_filter.match_filter, e.g. if you read\n        in day-long data for match_filter, process_len should be 86400.\n\n    .. rubric:: Example\n\n    >>> from obspy.clients.fdsn import Client\n    >>> from eqcorrscan.core.template_gen import from_client\n    >>> client = Client('NCEDC')\n    >>> catalog = client.get_events(eventid='72572665', includearrivals=True)\n    >>> # We are only taking two picks for this example to speed up the\n    >>> # example, note that you don't have to!\n    >>> catalog[0].picks = catalog[0].picks[0:2]\n    >>> templates = from_client(catalog=catalog, client_id='NCEDC',\n    ...                         lowcut=2.0, highcut=9.0, samp_rate=20.0,\n    ...                         filt_order=4, length=3.0, prepick=0.15,\n    ...                         swin='all', process_len=300,\n    ...                         all_horiz=True)\n    >>> templates[0].plot(equal_scale=False, size=(800,600)) # doctest: +SKIP\n\n    .. figure:: ../../plots/template_gen.from_client.png"
  },
  {
    "code": "def is_hash(fhash):\n    if re.match(re_md5, fhash):\n        return True\n    elif re.match(re_sha1, fhash):\n        return True\n    elif re.match(re_sha256, fhash):\n        return True\n    elif re.match(re_sha512, fhash):\n        return True\n    elif re.match(re_ssdeep, fhash):\n        return True\n    else:\n        return False",
    "docstring": "Returns true for valid hashes, false for invalid."
  },
  {
    "code": "def forbid_web_access(f):\n    @wraps(f)\n    def wrapper_fn(*args, **kwargs):\n        if isinstance(JobContext.get_current_context(), WebJobContext):\n            raise ForbiddenError('Access forbidden from web.')\n        return f(*args, **kwargs)\n    return wrapper_fn",
    "docstring": "Forbids running task using http request.\n\n    :param f: Callable\n    :return Callable"
  },
  {
    "code": "def x_11paths_authorization(app_id, secret, context, utc=None):\n    utc = utc or context.headers[X_11PATHS_DATE_HEADER_NAME]\n    url_path = ensure_url_path_starts_with_slash(context.url_path)\n    url_path_query = url_path\n    if context.query_params:\n        url_path_query += \"?%s\" % (url_encode(context.query_params, sort=True))\n    string_to_sign = (context.method.upper().strip() + \"\\n\" +\n                      utc + \"\\n\" +\n                      _get_11paths_serialized_headers(context.headers) + \"\\n\" +\n                      url_path_query.strip())\n    if context.body_params and isinstance(context.renderer, FormRenderer):\n        string_to_sign = string_to_sign + \"\\n\" + url_encode(context.body_params, sort=True).replace(\"&\", \"\")\n    authorization_header_value = (AUTHORIZATION_METHOD + AUTHORIZATION_HEADER_FIELD_SEPARATOR + app_id +\n                                  AUTHORIZATION_HEADER_FIELD_SEPARATOR + _sign_data(secret, string_to_sign))\n    return authorization_header_value",
    "docstring": "Calculate the authentication headers to be sent with a request to the API.\n\n    :param app_id:\n    :param secret:\n    :param context\n    :param utc:\n    :return: array a map with the Authorization and Date headers needed to sign a Latch API request"
  },
  {
    "code": "def bulk_update(self, request):\r\n        bid = utils.destroy_basket(request)\r\n        for item_data in request.data:\r\n            item = BasketItem(basket_id=bid, **item_data)\r\n            item.save()\r\n        serializer = BasketItemSerializer(self.get_queryset(request), many=True)\r\n        response = Response(data=serializer.data,\r\n                            status=status.HTTP_200_OK)\r\n        return response",
    "docstring": "Put multiple items in the basket,\r\n        removing anything that already exists"
  },
  {
    "code": "def _encode_key(self, obj):\n        if obj.__class__ is str:\n            return self._encode_str(obj)\n        if obj.__class__ is UUID:\n            return '\"' + str(obj) + '\"'\n        try:\n            sx_encoder = obj.__mm_serialize__\n        except AttributeError:\n            pass\n        else:\n            try:\n                data = sx_encoder()\n            except NotImplementedError:\n                pass\n            else:\n                return self._encode_key(data)\n        if isinstance(obj, UUID):\n            return '\"' + str(obj) + '\"'\n        if isinstance(obj, str):\n            return self._encode_str(obj)\n        try:\n            value = self.default(obj)\n        except TypeError:\n            raise TypeError('{!r} is not a valid dictionary key'.format(obj))\n        return self._encode_key(value)",
    "docstring": "Encodes a dictionary key - a key can only be a string in std JSON"
  },
  {
    "code": "def tci_path(self):\n        tci_paths = [\n            path for path in self.dataset._product_metadata.xpath(\n                \".//Granule[@granuleIdentifier='%s']/IMAGE_FILE/text()\"\n                % self.granule_identifier\n            ) if path.endswith('TCI')\n        ]\n        try:\n            tci_path = tci_paths[0]\n        except IndexError:\n            return None\n        return os.path.join(\n            self.dataset._zip_root if self.dataset.is_zip else self.dataset.path,\n            tci_path\n        ) + '.jp2'",
    "docstring": "Return the path to the granules TrueColorImage."
  },
  {
    "code": "def _set_sequence(cls, val):\n        if db.engine.dialect.name == 'postgresql':\n            db.session.execute(\n                \"SELECT setval(pg_get_serial_sequence(\"\n                \"'{0}', 'recid'), :newval)\".format(\n                    cls.__tablename__), dict(newval=val))",
    "docstring": "Internal function to reset sequence to specific value.\n\n        Note: this function is for PostgreSQL compatibility.\n\n        :param val: The value to be set."
  },
  {
    "code": "def jieba_tokenize(text, external_wordlist=False):\n    global jieba_tokenizer, jieba_orig_tokenizer\n    if external_wordlist:\n        if jieba_orig_tokenizer is None:\n            jieba_orig_tokenizer = jieba.Tokenizer(dictionary=ORIG_DICT_FILENAME)\n        return jieba_orig_tokenizer.lcut(text)\n    else:\n        if jieba_tokenizer is None:\n            jieba_tokenizer = jieba.Tokenizer(dictionary=DICT_FILENAME)\n        tokens = []\n        for _token, start, end in jieba_tokenizer.tokenize(simplify_chinese(text), HMM=False):\n            tokens.append(text[start:end])\n        return tokens",
    "docstring": "Tokenize the given text into tokens whose word frequencies can probably\n    be looked up. This uses Jieba, a word-frequency-based tokenizer.\n\n    If `external_wordlist` is False, we tell Jieba to default to using\n    wordfreq's own Chinese wordlist, and not to infer unknown words using a\n    hidden Markov model. This ensures that the multi-character tokens that it\n    outputs will be ones whose word frequencies we can look up.\n\n    If `external_wordlist` is True, this will use the largest version of\n    Jieba's original dictionary, with HMM enabled, so its results will be\n    independent of the data in wordfreq. These results will be better optimized\n    for purposes that aren't looking up word frequencies, such as general-\n    purpose tokenization, or collecting word frequencies in the first place."
  },
  {
    "code": "def stop_db_session(exc=None):\n    if has_db_session():\n        exc_type = None\n        tb = None\n        if exc:\n            exc_type, exc, tb = get_exc_info(exc)\n        db_session.__exit__(exc_type, exc, tb)",
    "docstring": "Stops the last db_session"
  },
  {
    "code": "def get_monitor_physical_size(monitor):\n    width_value = ctypes.c_int(0)\n    width = ctypes.pointer(width_value)\n    height_value = ctypes.c_int(0)\n    height = ctypes.pointer(height_value)\n    _glfw.glfwGetMonitorPhysicalSize(monitor, width, height)\n    return width_value.value, height_value.value",
    "docstring": "Returns the physical size of the monitor.\n\n    Wrapper for:\n        void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* width, int* height);"
  },
  {
    "code": "def aggregate(table, metrics=None, by=None, having=None, **kwds):\n    if metrics is None:\n        metrics = []\n    for k, v in sorted(kwds.items()):\n        v = table._ensure_expr(v)\n        metrics.append(v.name(k))\n    op = table.op().aggregate(table, metrics, by=by, having=having)\n    return op.to_expr()",
    "docstring": "Aggregate a table with a given set of reductions, with grouping\n    expressions, and post-aggregation filters.\n\n    Parameters\n    ----------\n    table : table expression\n    metrics : expression or expression list\n    by : optional, default None\n      Grouping expressions\n    having : optional, default None\n      Post-aggregation filters\n\n    Returns\n    -------\n    agg_expr : TableExpr"
  },
  {
    "code": "def str_search(self, search: str) -> List[HistoryItem]:\n        def isin(history_item):\n            sloppy = utils.norm_fold(search)\n            return sloppy in utils.norm_fold(history_item) or sloppy in utils.norm_fold(history_item.expanded)\n        return [item for item in self if isin(item)]",
    "docstring": "Find history items which contain a given string\n\n        :param search: the string to search for\n        :return: a list of history items, or an empty list if the string was not found"
  },
  {
    "code": "def _is_number_match_OO(numobj1_in, numobj2_in):\n    numobj1 = _copy_core_fields_only(numobj1_in)\n    numobj2 = _copy_core_fields_only(numobj2_in)\n    if (numobj1.extension is not None and\n        numobj2.extension is not None and\n        numobj1.extension != numobj2.extension):\n        return MatchType.NO_MATCH\n    country_code1 = numobj1.country_code\n    country_code2 = numobj2.country_code\n    if country_code1 != 0 and country_code2 != 0:\n        if numobj1 == numobj2:\n            return MatchType.EXACT_MATCH\n        elif (country_code1 == country_code2 and\n              _is_national_number_suffix_of_other(numobj1, numobj2)):\n            return MatchType.SHORT_NSN_MATCH\n        return MatchType.NO_MATCH\n    numobj1.country_code = country_code2\n    if numobj1 == numobj2:\n        return MatchType.NSN_MATCH\n    if _is_national_number_suffix_of_other(numobj1, numobj2):\n        return MatchType.SHORT_NSN_MATCH\n    return MatchType.NO_MATCH",
    "docstring": "Takes two phone number objects and compares them for equality."
  },
  {
    "code": "def logout(self):\n        if self.cache(CONST.ACCESS_TOKEN):\n            self._session = requests.session()\n            self._devices = None\n            self.update_cache({CONST.ACCESS_TOKEN: None})\n        return True",
    "docstring": "Explicit Skybell logout."
  },
  {
    "code": "def validate(self):\n        if not self.principals:\n            raise InvalidApplicationPolicyError(error_message='principals not provided')\n        if not self.actions:\n            raise InvalidApplicationPolicyError(error_message='actions not provided')\n        if any(not self._PRINCIPAL_PATTERN.match(p) for p in self.principals):\n            raise InvalidApplicationPolicyError(\n                error_message='principal should be 12-digit AWS account ID or \"*\"')\n        unsupported_actions = sorted(set(self.actions) - set(self.SUPPORTED_ACTIONS))\n        if unsupported_actions:\n            raise InvalidApplicationPolicyError(\n                error_message='{} not supported'.format(', '.join(unsupported_actions)))\n        return True",
    "docstring": "Check if the formats of principals and actions are valid.\n\n        :return: True, if the policy is valid\n        :raises: InvalidApplicationPolicyError"
  },
  {
    "code": "def convert(self, json, fout):\n        self.build_markdown_body(json)\n        self.build_header(json['name'])\n        self.build_output(fout)",
    "docstring": "Convert json to markdown.\n\n        Takes in a .json file as input and convert it to Markdown format,\n        saving the generated .png images into ./images."
  },
  {
    "code": "def FindUnspentCoinsByAssetAndTotal(self, asset_id, amount, from_addr=None, use_standard=False, watch_only_val=0, reverse=False):\n        coins = self.FindUnspentCoinsByAsset(asset_id, from_addr=from_addr,\n                                             use_standard=use_standard, watch_only_val=watch_only_val)\n        sum = Fixed8(0)\n        for coin in coins:\n            sum = sum + coin.Output.Value\n        if sum < amount:\n            return None\n        coins = sorted(coins, key=lambda coin: coin.Output.Value.value)\n        if reverse:\n            coins.reverse()\n        total = Fixed8(0)\n        for coin in coins:\n            if coin.Output.Value == amount:\n                return [coin]\n        to_ret = []\n        for coin in coins:\n            total = total + coin.Output.Value\n            to_ret.append(coin)\n            if total >= amount:\n                break\n        return to_ret",
    "docstring": "Finds unspent coin objects totalling a requested value in the wallet limited to those of a certain asset type.\n\n        Args:\n            asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain.\n            amount (int): the amount of unspent coins that are being requested.\n            from_addr (UInt160): a bytearray (len 20) representing an address.\n            use_standard (bool): whether or not to only include standard contracts ( i.e not a smart contract addr ).\n            watch_only_val (int): a flag ( 0 or 64 ) indicating whether or not to find coins that are in 'watch only' addresses.\n\n        Returns:\n            list: a list of ``neo.Wallet.Coin`` in the wallet that are not spent. this list is empty if there are not enough coins to satisfy the request."
  },
  {
    "code": "def get_ptrms_angle(ptrms_best_fit_vector, B_lab_vector):\n    ptrms_angle = math.degrees(math.acos(old_div(numpy.dot(ptrms_best_fit_vector,B_lab_vector),(numpy.sqrt(sum(ptrms_best_fit_vector**2)) * numpy.sqrt(sum(B_lab_vector**2))))))\n    return ptrms_angle",
    "docstring": "gives angle between principal direction of the ptrm data and the b_lab vector.  this is NOT in SPD, but taken from Ron Shaar's old thellier_gui.py code.  see PmagPy on github"
  },
  {
    "code": "def get_lambda_runtime_info(context):\n    runtime_info = {\n        'remaining_time': context.get_remaining_time_in_millis(),\n        'function_name': context.function_name,\n        'function_version': context.function_version,\n        'invoked_function_arn': context.invoked_function_arn,\n        'memory_limit': context.memory_limit_in_mb,\n        'aws_request_id': context.aws_request_id,\n        'log_group_name': context.log_group_name,\n        'log_stream_name': context.log_stream_name\n    }\n    return runtime_info",
    "docstring": "Returns a dictionary of information about the AWS Lambda function invocation\n\n    Arguments\n\n    context: The context object from AWS Lambda."
  },
  {
    "code": "def request(self, method, url, **kwargs):\n        if not self.cache_storage:\n            resp = super(CachingSession, self).request(method, url, **kwargs)\n            resp.fromcache = False\n            return resp\n        resp = None\n        method = method.lower()\n        request_key = self.key_for_request(method, url, **kwargs)\n        if request_key and not self.cache_write_only:\n            resp = self.cache_storage.get(request_key)\n        if resp:\n            resp.fromcache = True\n        else:\n            resp = super(CachingSession, self).request(method, url, **kwargs)\n            if request_key and self.should_cache_response(resp):\n                self.cache_storage.set(request_key, resp)\n            resp.fromcache = False\n        return resp",
    "docstring": "Override, wraps Session.request in caching.\n\n            Cache is only used if key_for_request returns a valid key\n            and should_cache_response was true as well."
  },
  {
    "code": "def main(testfiles=None, action=printer):\r\n    testfiles = get_filename_list(testfiles)\r\n    print(testfiles)\r\n    if action:\r\n        for i in (simple_identifier, value, item_list):\r\n            i.setParseAction(action)\r\n    success = 0\r\n    failures = []\r\n    retval = {}\r\n    for f in testfiles:\r\n        try:\r\n            retval[f] = object_definition.parseFile(f)\r\n            success += 1\r\n        except Exception:\r\n            failures.append(f)\r\n    if failures:\r\n        print('\\nfailed while processing %s' % ', '.join(failures))\r\n    print('\\nsucceeded on %d of %d files' %(success, len(testfiles)))\r\n    if len(retval) == 1 and len(testfiles) == 1:\r\n        return retval[list(retval.keys())[0]]\r\n    return retval",
    "docstring": "testfiles can be None, in which case the command line arguments are used as filenames.\r\n    testfiles can be a string, in which case that file is parsed.\r\n    testfiles can be a list.\r\n    In all cases, the filenames will be globbed.\r\n    If more than one file is parsed successfully, a dictionary of ParseResults is returned.\r\n    Otherwise, a simple ParseResults is returned."
  },
  {
    "code": "def has_overflow(self, params):\n        is_not_finite = 0\n        for param in params:\n            if param.grad_req != 'null':\n                grad = param.list_grad()[0]\n                is_not_finite += mx.nd.contrib.isnan(grad).sum()\n                is_not_finite += mx.nd.contrib.isinf(grad).sum()\n        if is_not_finite == 0:\n            return False\n        else:\n            return True",
    "docstring": "detect inf and nan"
  },
  {
    "code": "def get_decoded_tile(codec, stream, imagep, tile_index):\n    OPENJP2.opj_get_decoded_tile.argtypes = [CODEC_TYPE,\n                                             STREAM_TYPE_P,\n                                             ctypes.POINTER(ImageType),\n                                             ctypes.c_uint32]\n    OPENJP2.opj_get_decoded_tile.restype = check_error\n    OPENJP2.opj_get_decoded_tile(codec, stream, imagep, tile_index)",
    "docstring": "get the decoded tile from the codec\n\n    Wraps the openjp2 library function opj_get_decoded_tile.\n\n    Parameters\n    ----------\n    codec : CODEC_TYPE\n        The jpeg2000 codec.\n    stream : STREAM_TYPE_P\n        The input stream.\n    image : ImageType\n        Output image structure.\n    tiler_index : int\n        Index of the tile which will be decoded.\n\n    Raises\n    ------\n    RuntimeError\n        If the OpenJPEG library routine opj_get_decoded_tile fails."
  },
  {
    "code": "def json(self):\n        return json.dumps(self.dict_rules,\n                          sort_keys=True,\n                          indent=2,\n                          separators=(',', ': '))",
    "docstring": "Output the security rules as a json string.\n\n        Return:\n            str"
  },
  {
    "code": "def _parse_args(self, args):\n        parser = ArgumentParser(description=\"Runs pylint recursively on a directory\")\n        parser.add_argument(\n            \"-v\",\n            \"--verbose\",\n            dest=\"verbose\",\n            action=\"store_true\",\n            default=False,\n            help=\"Verbose mode (report which files were found for testing).\",\n        )\n        parser.add_argument(\n            \"--rcfile\",\n            dest=\"rcfile\",\n            action=\"store\",\n            default=\".pylintrc\",\n            help=\"A relative or absolute path to your pylint rcfile. Defaults to\\\n                            `.pylintrc` at the current working directory\",\n        )\n        parser.add_argument(\n            \"-V\",\n            \"--version\",\n            action=\"version\",\n            version=\"%(prog)s ({0}) for Python {1}\".format(__version__, PYTHON_VERSION),\n        )\n        options, _ = parser.parse_known_args(args)\n        self.verbose = options.verbose\n        if options.rcfile:\n            if not os.path.isfile(options.rcfile):\n                options.rcfile = os.getcwd() + \"/\" + options.rcfile\n            self.rcfile = options.rcfile\n        return options",
    "docstring": "Parses any supplied command-line args and provides help text."
  },
  {
    "code": "def calc_dihedral(point1, point2, point3, point4):\n    points = np.array([point1, point2, point3, point4])\n    x = np.cross(points[1] - points[0], points[2] - points[1])\n    y = np.cross(points[2] - points[1], points[3] - points[2])\n    return angle(x, y)",
    "docstring": "Calculates a dihedral angle\n\n    Here, two planes are defined by (point1, point2, point3) and\n    (point2, point3, point4). The angle between them is returned.\n\n    Parameters\n    ----------\n    point1, point2, point3, point4 : array-like, shape=(3,), dtype=float\n        Four points that define two planes\n\n    Returns\n    -------\n    float\n        The dihedral angle between the two planes defined by the four\n        points."
  },
  {
    "code": "def _exec(**kwargs):\n    if 'ignore_retcode' not in kwargs:\n        kwargs['ignore_retcode'] = True\n    if 'output_loglevel' not in kwargs:\n        kwargs['output_loglevel'] = 'quiet'\n    return salt.modules.cmdmod.run_all(**kwargs)",
    "docstring": "Simple internal wrapper for cmdmod.run"
  },
  {
    "code": "def binned_entropy(x, max_bins):\n    if not isinstance(x, (np.ndarray, pd.Series)):\n        x = np.asarray(x)\n    hist, bin_edges = np.histogram(x, bins=max_bins)\n    probs = hist / x.size\n    return - np.sum(p * np.math.log(p) for p in probs if p != 0)",
    "docstring": "First bins the values of x into max_bins equidistant bins.\n    Then calculates the value of\n\n    .. math::\n\n        - \\\\sum_{k=0}^{min(max\\\\_bins, len(x))} p_k log(p_k) \\\\cdot \\\\mathbf{1}_{(p_k > 0)}\n\n    where :math:`p_k` is the percentage of samples in bin :math:`k`.\n\n    :param x: the time series to calculate the feature of\n    :type x: numpy.ndarray\n    :param max_bins: the maximal number of bins\n    :type max_bins: int\n    :return: the value of this feature\n    :return type: float"
  },
  {
    "code": "def validate(self):\n        if not self.file.exists():\n            raise ValueError(\"File \\\"%s\\\" doesn't exists\")\n        if not self.search:\n            raise ValueError(\"Search cannot be empty\")\n        if not self.replace:\n            raise ValueError(\"Replace cannot be empty\")\n        if self.match not in ('file', 'line'):\n            raise ValueError(\"Match must be one of: file, line\")\n        try:\n            codecs.lookup(self.encoding)\n        except LookupError:\n            raise ValueError(\"Unknown encoding: \\\"%s\\\"\" % self.encoding)",
    "docstring": "Validate current file configuration\n\n        :raise ValueError:"
  },
  {
    "code": "def write_file(self, filename, file_format=\"xyz\"):\n        mol = pb.Molecule(self._obmol)\n        return mol.write(file_format, filename, overwrite=True)",
    "docstring": "Uses OpenBabel to output all supported formats.\n\n        Args:\n            filename: Filename of file to output\n            file_format: String specifying any OpenBabel supported formats."
  },
  {
    "code": "def service_restart(service_name):\n    if host.service_available(service_name):\n        if host.service_running(service_name):\n            host.service_restart(service_name)\n        else:\n            host.service_start(service_name)",
    "docstring": "Wrapper around host.service_restart to prevent spurious \"unknown service\"\n    messages in the logs."
  },
  {
    "code": "def sign(self, key, network_id=None):\n        if network_id is None:\n            rawhash = utils.sha3(rlp.encode(unsigned_tx_from_tx(self), UnsignedTransaction))\n        else:\n            assert 1 <= network_id < 2**63 - 18\n            rlpdata = rlp.encode(rlp.infer_sedes(self).serialize(self)[\n                                 :-3] + [network_id, b'', b''])\n            rawhash = utils.sha3(rlpdata)\n        key = normalize_key(key)\n        v, r, s = ecsign(rawhash, key)\n        if network_id is not None:\n            v += 8 + network_id * 2\n        ret = self.copy(\n            v=v, r=r, s=s\n        )\n        ret._sender = utils.privtoaddr(key)\n        return ret",
    "docstring": "Sign this transaction with a private key.\n\n        A potentially already existing signature would be overridden."
  },
  {
    "code": "def check_pow(block_number, header_hash, mixhash, nonce, difficulty):\n    log.debug('checking pow', block_number=block_number)\n    if len(mixhash) != 32 or len(header_hash) != 32 or len(nonce) != 8:\n        return False\n    cache = get_cache(block_number)\n    mining_output = hashimoto_light(block_number, cache, header_hash, nonce)\n    if mining_output[b'mix digest'] != mixhash:\n        return False\n    return utils.big_endian_to_int(\n        mining_output[b'result']) <= 2**256 // (difficulty or 1)",
    "docstring": "Check if the proof-of-work of the block is valid.\n\n    :param nonce: if given the proof of work function will be evaluated\n                  with this nonce instead of the one already present in\n                  the header\n    :returns: `True` or `False`"
  },
  {
    "code": "def register(cls, package_type):\n    if not issubclass(package_type, cls):\n      raise TypeError('package_type must be a subclass of Package.')\n    cls._REGISTRY.add(package_type)",
    "docstring": "Register a concrete implementation of a Package to be recognized by pex."
  },
  {
    "code": "def lmx_base():\n  hparams = transformer.transformer_tpu()\n  hparams.shared_embedding_and_softmax_weights = False\n  hparams.label_smoothing = 0.0\n  hparams.max_length = 256\n  hparams.batch_size = 4096\n  hparams.activation_dtype = \"bfloat16\"\n  return hparams",
    "docstring": "Transformer on languagemodel_lm1b32k_packed.  50M Params."
  },
  {
    "code": "def create_audio_mp3_profile(apps, schema_editor):\n    Profile = apps.get_model('edxval', 'Profile')\n    Profile.objects.get_or_create(profile_name=AUDIO_MP3_PROFILE)",
    "docstring": "Create audio_mp3 profile"
  },
  {
    "code": "def claim_watches(user):\n    Watch.objects.filter(email=user.email).update(email=None, user=user)",
    "docstring": "Attach any anonymous watches having a user's email to that user.\n\n    Call this from your user registration process if you like."
  },
  {
    "code": "def is_human(data, builds=None):\n    def has_build37_contigs(data):\n        for contig in ref.file_contigs(dd.get_ref_file(data)):\n            if contig.name.startswith(\"GL\") or contig.name.find(\"_gl\") >= 0:\n                if contig.name in naming.GMAP[\"hg19\"] or contig.name in naming.GMAP[\"GRCh37\"]:\n                    return True\n        return False\n    if not builds and tz.get_in([\"genome_resources\", \"aliases\", \"human\"], data):\n        return True\n    if not builds or \"37\" in builds:\n        target_builds = [\"hg19\", \"GRCh37\"]\n        if any([dd.get_genome_build(data).startswith(b) for b in target_builds]):\n            return True\n        elif has_build37_contigs(data):\n            return True\n    if not builds or \"38\" in builds:\n        target_builds = [\"hg38\"]\n        if any([dd.get_genome_build(data).startswith(b) for b in target_builds]):\n            return True\n    return False",
    "docstring": "Check if human, optionally with build number, search by name or extra GL contigs."
  },
  {
    "code": "def add_cut(problem, indicators, bound, Constraint):\n    cut = Constraint(sympy.Add(*indicators), ub=bound)\n    problem.add(cut)\n    return cut",
    "docstring": "Add an integer cut to the problem.\n\n    Ensure that the same solution involving these indicator variables cannot be\n    found by enforcing their sum to be less than before.\n\n    Parameters\n    ----------\n    problem : optlang.Model\n        Specific optlang interface Model instance.\n    indicators : iterable\n        Binary indicator `optlang.Variable`s.\n    bound : int\n        Should be one less than the sum of indicators. Corresponds to P - 1 in\n        equation (14) in [1]_.\n    Constraint : optlang.Constraint\n        Constraint class for a specific optlang interface.\n\n    References\n    ----------\n    .. [1] Gevorgyan, A., M. G Poolman, and D. A Fell.\n           \"Detection of Stoichiometric Inconsistencies in Biomolecular\n           Models.\"\n           Bioinformatics 24, no. 19 (2008): 2245."
  },
  {
    "code": "def trimpath(attributes):\n    if 'pathdepth' in attributes:\n        if attributes['pathdepth'] != 'full':\n            pathelements = []\n            remainder = attributes['file']\n            limit = int(attributes['pathdepth'])\n            while len(pathelements) < limit and remainder:\n                remainder, pe = os.path.split(remainder)\n                pathelements.insert(0, pe)\n            return os.path.join(*pathelements)\n        return attributes['file']\n    return os.path.basename(attributes['file'])",
    "docstring": "Simplifies the given path.\n\n    If pathdepth is in attributes, the last pathdepth elements will be\n    returned. If pathdepth is \"full\", the full path will be returned.\n    Otherwise the filename only will be returned.\n\n    Args:\n        attributes: The element attributes.\n\n    Returns:\n        The trimmed path."
  },
  {
    "code": "def search(table: LdapObjectClass, query: Optional[Q] = None,\n           database: Optional[Database] = None, base_dn: Optional[str] = None) -> Iterator[LdapObject]:\n    fields = table.get_fields()\n    db_fields = {\n        name: field\n        for name, field in fields.items()\n        if field.db_field\n    }\n    database = get_database(database)\n    connection = database.connection\n    search_options = table.get_search_options(database)\n    iterator = tldap.query.search(\n        connection=connection,\n        query=query,\n        fields=db_fields,\n        base_dn=base_dn or search_options.base_dn,\n        object_classes=search_options.object_class,\n        pk=search_options.pk_field,\n    )\n    for dn, data in iterator:\n        python_data = _db_to_python(data, table, dn)\n        python_data = table.on_load(python_data, database)\n        yield python_data",
    "docstring": "Search for a object of given type in the database."
  },
  {
    "code": "def _hash_of_file(path, algorithm):\n    with open(path, 'rb') as archive:\n        hash = hashlib.new(algorithm)\n        for chunk in read_chunks(archive):\n            hash.update(chunk)\n    return hash.hexdigest()",
    "docstring": "Return the hash digest of a file."
  },
  {
    "code": "def add_custom_fields(cls, *args, **kw):\n        for factory in config.custom_field_factories:\n            for field in factory():\n                setattr(cls, field.name, field)",
    "docstring": "Add any custom fields defined in the configuration."
  },
  {
    "code": "def percentile(self, percent):\n        if percent >= 100:\n            percent = 100\n        target = len(self) - len(self) * (percent / 100)\n        for k in reversed(sorted(self._data.keys())):\n            target -= self._data[k]\n            if target < 0:\n                return k\n        return 10",
    "docstring": "Return the value that is the Nth precentile in the histogram.\n\n        Args:\n            percent (Union[int, float]): The precentile being sought. The\n                default consumer implementations use consistently use ``99``.\n\n        Returns:\n            int: The value corresponding to the requested percentile."
  },
  {
    "code": "def colorize(text, messageType=None):\n    formattedText = str(text)\n    if \"ERROR\" in messageType:\n        formattedText = colorama.Fore.RED + formattedText\n    elif \"WARNING\" in messageType:\n        formattedText = colorama.Fore.YELLOW + formattedText\n    elif \"SUCCESS\" in messageType:\n        formattedText = colorama.Fore.GREEN + formattedText\n    elif \"INFO\" in messageType:\n        formattedText = colorama.Fore.BLUE + formattedText\n    if \"BOLD\" in messageType:\n        formattedText = colorama.Style.BRIGHT + formattedText\n    return formattedText + colorama.Style.RESET_ALL",
    "docstring": "Function that colorizes a message.\n\n    Args:\n    -----\n        text: The string to be colorized.\n        messageType: Possible options include \"ERROR\", \"WARNING\", \"SUCCESS\",\n            \"INFO\" or \"BOLD\".\n\n    Returns:\n    --------\n        string: Colorized if the option is correct, including a tag at the end\n            to reset the formatting."
  },
  {
    "code": "def append_responder(self, matcher, *args, **kwargs):\n        return self._insert_responder(\"bottom\", matcher, *args, **kwargs)",
    "docstring": "Add a responder of last resort.\n\n        Like `.autoresponds`, but instead of adding a responder to the top of\n        the stack, add it to the bottom. This responder will be called if no\n        others match."
  },
  {
    "code": "def generate_timeline(usnjrnl, filesystem_content):\n    journal_content = defaultdict(list)\n    for event in usnjrnl:\n        journal_content[event.inode].append(event)\n    for event in usnjrnl:\n        try:\n            dirent = lookup_dirent(event, filesystem_content, journal_content)\n            yield UsnJrnlEvent(\n                dirent.inode, dirent.path, dirent.size, dirent.allocated,\n                event.timestamp, event.changes, event.attributes)\n        except LookupError as error:\n            LOGGER.debug(error)",
    "docstring": "Aggregates the data collected from the USN journal\n    and the filesystem content."
  },
  {
    "code": "def get_link_domain(link, dist):\n    domain = np.array([-np.inf, -1, 0, 1, np.inf])\n    domain = domain[~np.isnan(link.link(domain, dist))]\n    return [domain[0], domain[-1]]",
    "docstring": "tool to identify the domain of a given monotonic link function\n\n    Parameters\n    ----------\n    link : Link object\n    dist : Distribution object\n\n    Returns\n    -------\n    domain : list of length 2, representing the interval of the domain."
  },
  {
    "code": "def add(self, synchronous=True, **kwargs):\n        kwargs = kwargs.copy()\n        if 'data' not in kwargs:\n            kwargs['data'] = dict()\n        if 'component_ids' not in kwargs['data']:\n            kwargs['data']['components'] = [_payload(self.get_fields(), self.get_values())]\n        kwargs.update(self._server_config.get_client_kwargs())\n        response = client.put(self.path('add'), **kwargs)\n        return _handle_response(response, self._server_config, synchronous)",
    "docstring": "Add provided Content View Component.\n\n        :param synchronous: What should happen if the server returns an HTTP\n            202 (accepted) status code? Wait for the task to complete if\n            ``True``. Immediately return the server's response otherwise.\n        :param kwargs: Arguments to pass to requests.\n        :returns: The server's response, with all JSON decoded.\n        :raises: ``requests.exceptions.HTTPError`` If the server responds with\n            an HTTP 4XX or 5XX message."
  },
  {
    "code": "def to_satoshis(input_quantity, input_type):\n    assert input_type in UNIT_CHOICES, input_type\n    if input_type in ('btc', 'mbtc', 'bit'):\n        satoshis = float(input_quantity) * float(UNIT_MAPPINGS[input_type]['satoshis_per'])\n    elif input_type == 'satoshi':\n        satoshis = input_quantity\n    else:\n        raise Exception('Invalid Unit Choice: %s' % input_type)\n    return int(satoshis)",
    "docstring": "convert to satoshis, no rounding"
  },
  {
    "code": "def complete(text, state):\n    for cmd in COMMANDS:\n        if cmd.startswith(text):\n            if not state:\n                return cmd\n            else:\n                state -= 1",
    "docstring": "Auto complete scss constructions in interactive mode."
  },
  {
    "code": "def close(self):\n        if not self._closed:\n            self._closed = True\n            if self._pool is not None:\n                self._pool.close()\n                self._pool = None",
    "docstring": "Shut down, closing any open connections in the pool."
  },
  {
    "code": "def contribute_to_class(self, model, name):\n        super(SearchableManager, self).contribute_to_class(model, name)\n        setattr(model, name, ManagerDescriptor(self))",
    "docstring": "Newer versions of Django explicitly prevent managers being\n        accessed from abstract classes, which is behaviour the search\n        API has always relied on. Here we reinstate it."
  },
  {
    "code": "def replace_url_query_values(url, replace_vals):\n    if '?' not in url:\n        return url\n    parsed_url = urlparse(url)\n    query = dict(parse_qsl(parsed_url.query))\n    query.update(replace_vals)\n    return '{0}?{1}'.format(url.split('?')[0], urlencode(query))",
    "docstring": "Replace querystring values in a url string.\n\n    >>> url = 'http://helloworld.com/some/path?test=5'\n    >>> replace_vals = {'test': 10}\n    >>> replace_url_query_values(url=url, replace_vals=replace_vals)\n    'http://helloworld.com/some/path?test=10'"
  },
  {
    "code": "def get_num_shares(self) -> Decimal:\n        from pydatum import Datum\n        today = Datum().today()\n        return self.get_num_shares_on(today)",
    "docstring": "Returns the number of shares at this time"
  },
  {
    "code": "def sort_file_tabs_alphabetically(self):\r\n        while self.sorted() is False:\r\n            for i in range(0, self.tabs.tabBar().count()):\r\n                if(self.tabs.tabBar().tabText(i) >\r\n                        self.tabs.tabBar().tabText(i + 1)):\r\n                    self.tabs.tabBar().moveTab(i, i + 1)",
    "docstring": "Sort open tabs alphabetically."
  },
  {
    "code": "def filter_queryset(self, request, queryset, view):\n        applicable_filters, applicable_exclusions = self.build_filters(view, filters=self.get_request_filters(request))\n        return self.apply_filters(\n            queryset=queryset,\n            applicable_filters=self.process_filters(applicable_filters, queryset, view),\n            applicable_exclusions=self.process_filters(applicable_exclusions, queryset, view)\n        )",
    "docstring": "Return the filtered queryset."
  },
  {
    "code": "def create_comment(self, body, sha, path=None, position=None, line=1):\n        json = None\n        if body and sha and (line and int(line) > 0):\n            data = {'body': body, 'line': line, 'path': path,\n                    'position': position}\n            self._remove_none(data)\n            url = self._build_url('commits', sha, 'comments',\n                                  base_url=self._api)\n            json = self._json(self._post(url, data=data), 201)\n        return RepoComment(json, self) if json else None",
    "docstring": "Create a comment on a commit.\n\n        :param str body: (required), body of the message\n        :param str sha: (required), commit id\n        :param str path: (optional), relative path of the file to comment\n            on\n        :param str position: (optional), line index in the diff to comment on\n        :param int line: (optional), line number of the file to comment on,\n            default: 1\n        :returns: :class:`RepoComment <github3.repos.comment.RepoComment>` if\n            successful, otherwise None"
  },
  {
    "code": "def hooks_factory(identifier, configuration, context):\n    manager = HookManager(identifier, configuration)\n    manager.load_hooks(context)\n    return manager",
    "docstring": "Returns the initialized hooks."
  },
  {
    "code": "def _try_close_dirty_tabs(self, exept=None):\n        widgets, filenames = self._collect_dirty_tabs(exept=exept)\n        if not len(filenames):\n            return True\n        dlg = DlgUnsavedFiles(self, files=filenames)\n        if dlg.exec_() == dlg.Accepted:\n            if not dlg.discarded:\n                for item in dlg.listWidget.selectedItems():\n                    filename = item.text()\n                    widget = None\n                    for widget in widgets:\n                        if widget.file.path == filename:\n                            break\n                    if widget != exept:\n                        self._save_editor(widget)\n                        self.removeTab(self.indexOf(widget))\n            return True\n        return False",
    "docstring": "Tries to close dirty tabs. Uses DlgUnsavedFiles to ask the user\n        what he wants to do."
  },
  {
    "code": "def _process_data(self, obj):\n        assert len(self._waiters) > 0, (type(obj), obj)\n        waiter, encoding, cb = self._waiters.popleft()\n        if isinstance(obj, RedisError):\n            if isinstance(obj, ReplyError):\n                if obj.args[0].startswith('READONLY'):\n                    obj = ReadOnlyError(obj.args[0])\n            _set_exception(waiter, obj)\n            if self._in_transaction is not None:\n                self._transaction_error = obj\n        else:\n            if encoding is not None:\n                try:\n                    obj = decode(obj, encoding)\n                except Exception as exc:\n                    _set_exception(waiter, exc)\n                    return\n            if cb is not None:\n                try:\n                    obj = cb(obj)\n                except Exception as exc:\n                    _set_exception(waiter, exc)\n                    return\n            _set_result(waiter, obj)\n            if self._in_transaction is not None:\n                self._in_transaction.append((encoding, cb))",
    "docstring": "Processes command results."
  },
  {
    "code": "def get_max_recv_data_size(self, target):\n        fname = \"get_max_recv_data_size\"\n        cname = self.__class__.__module__ + '.' + self.__class__.__name__\n        raise NotImplementedError(\"%s.%s() is required\" % (cname, fname))",
    "docstring": "Returns the maximum number of data bytes for receiving.\n\n        The maximum number of data bytes acceptable for receiving with\n        either :meth:`send_cmd_recv_rsp` or :meth:`send_rsp_recv_cmd`.\n        The value reflects the local device capabilities for receiving\n        in the mode determined by *target*. It does not relate to any\n        protocol capabilities and negotiations.\n\n        Arguments:\n\n          target (nfc.clf.Target): The current local or remote\n            communication target.\n\n        Returns:\n\n          int: Maximum number of data bytes supported for receiving."
  },
  {
    "code": "def generate(self, id_or_uri):\n        uri = self._client.build_uri(id_or_uri) + \"/generate\"\n        return self._client.get(uri)",
    "docstring": "Generates and returns a random range.\n\n        Args:\n            id_or_uri:\n                ID or URI of range.\n\n        Returns:\n            dict: A dict containing a list with IDs."
  },
  {
    "code": "def addcommenttomergerequest(self, project_id, mergerequest_id, note):\n        request = requests.post(\n            '{0}/{1}/merge_request/{2}/comments'.format(self.projects_url, project_id, mergerequest_id),\n            data={'note': note}, headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)\n        return request.status_code == 201",
    "docstring": "Add a comment to a merge request.\n\n        :param project_id: ID of the project originating the merge request\n        :param mergerequest_id: ID of the merge request to comment on\n        :param note: Text of comment\n        :return: True if success"
  },
  {
    "code": "def connect(self, address, **kws):\r\n        return yield_(Connect(self, address, timeout=self._timeout, **kws))",
    "docstring": "Connect to a remote socket at _address_."
  },
  {
    "code": "def _silence():\n    old_stdout = sys.stdout\n    old_stderr = sys.stderr\n    sys.stdout = _DummyFile()\n    sys.stderr = _DummyFile()\n    exception_occurred = False\n    try:\n        yield\n    except:\n        exception_occurred = True\n        sys.stdout = old_stdout\n        sys.stderr = old_stderr\n        raise\n    if not exception_occurred:\n        sys.stdout = old_stdout\n        sys.stderr = old_stderr",
    "docstring": "A context manager that silences sys.stdout and sys.stderr."
  },
  {
    "code": "def selected_objects(self):\n        return [\n            obj\n            for obj in self.text_objects\n            if contains_or_overlap(self.table_bbox, obj.bbox)\n        ]",
    "docstring": "Filter out objects outside table boundaries"
  },
  {
    "code": "def put(self, key, value):\n    key = self._service_key(key)\n    self._service_ops['put'](key, value)",
    "docstring": "Stores the object `value` named by `key` in `service`.\n\n    Args:\n      key: Key naming `value`.\n      value: the object to store."
  },
  {
    "code": "def pan_delta(self, d):\n        dx, dy = d\n        pan_x, pan_y = self.pan\n        zoom_x, zoom_y = self._zoom_aspect(self._zoom)\n        self.pan = (pan_x + dx / zoom_x, pan_y + dy / zoom_y)\n        self.update()",
    "docstring": "Pan the view by a given amount."
  },
  {
    "code": "def get_host_template(resource_root, name, cluster_name):\n  return call(resource_root.get,\n      HOST_TEMPLATE_PATH % (cluster_name, name),\n      ApiHostTemplate, api_version=3)",
    "docstring": "Lookup a host template by name in the specified cluster.\n  @param resource_root: The root Resource object.\n  @param name: Host template name.\n  @param cluster_name: Cluster name.\n  @return: An ApiHostTemplate object.\n  @since: API v3"
  },
  {
    "code": "def tournament(self, negative=False):\n        if self.generation <= self._random_generations and not negative:\n            return self.random_selection()\n        if not self._negative_selection and negative:\n            return self.random_selection(negative=negative)\n        vars = self.random()\n        fit = [(k, self.population[x].fitness) for k, x in enumerate(vars)]\n        if negative:\n            fit = min(fit, key=lambda x: x[1])\n        else:\n            fit = max(fit, key=lambda x: x[1])\n        index = fit[0]\n        return vars[index]",
    "docstring": "Tournament selection and when negative is True it performs negative\n        tournament selection"
  },
  {
    "code": "def parse_timers(self):\n        filenames = list(filter(os.path.exists, [task.output_file.path for task in self]))\n        parser = AbinitTimerParser()\n        parser.parse(filenames)\n        return parser",
    "docstring": "Parse the TIMER section reported in the ABINIT output files.\n\n        Returns:\n            :class:`AbinitTimerParser` object"
  },
  {
    "code": "def _request(method, url, content_type=None, _data=None, user=None, passwd=None):\n    opener = _build_opener(_HTTPHandler)\n    request = _Request(url, data=_data)\n    if content_type:\n        request.add_header('Content-Type', content_type)\n    if user and passwd:\n        auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1]\n        auth_basic = \"Basic {0}\".format(auth_encode)\n        request.add_header('Authorization', auth_basic)\n        request.add_header('Accept', 'application/json')\n    request.get_method = lambda: method\n    try:\n        handler = opener.open(request)\n    except HTTPError as exc:\n        return {'error': '{0}'.format(exc)}\n    return salt.utils.json.loads(handler.read())",
    "docstring": "Makes a HTTP request. Returns the JSON parse, or an obj with an error."
  },
  {
    "code": "def breakpoint_set(self, addr, thumb=False, arm=False):\n        flags = enums.JLinkBreakpoint.ANY\n        if thumb:\n            flags = flags | enums.JLinkBreakpoint.THUMB\n        elif arm:\n            flags = flags | enums.JLinkBreakpoint.ARM\n        handle = self._dll.JLINKARM_SetBPEx(int(addr), flags)\n        if handle <= 0:\n            raise errors.JLinkException('Breakpoint could not be set.')\n        return handle",
    "docstring": "Sets a breakpoint at the specified address.\n\n        If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if\n        ``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a\n        normal breakpoint is set.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          addr (int): the address where the breakpoint will be set\n          thumb (bool): boolean indicating to set the breakpoint in THUMB mode\n          arm (bool): boolean indicating to set the breakpoint in ARM mode\n\n        Returns:\n          An integer specifying the breakpoint handle.  This handle should be\n          retained for future breakpoint operations.\n\n        Raises:\n          TypeError: if the given address is not an integer.\n          JLinkException: if the breakpoint could not be set."
  },
  {
    "code": "def lat_from_pole(ref_loc_lon, ref_loc_lat, pole_plon, pole_plat):\n    ref_loc = (ref_loc_lon, ref_loc_lat)\n    pole = (pole_plon, pole_plat)\n    paleo_lat = 90 - pmag.angle(pole, ref_loc)\n    return float(paleo_lat)",
    "docstring": "Calculate paleolatitude for a reference location based on a paleomagnetic pole\n\n    Required Parameters\n    ----------\n    ref_loc_lon: longitude of reference location in degrees\n    ref_loc_lat: latitude of reference location\n    pole_plon: paleopole longitude in degrees\n    pole_plat: paleopole latitude in degrees"
  },
  {
    "code": "def base_url(klass, space_id, resource_id=None, public=False, environment_id=None, **kwargs):\n        if public:\n            environment_slug = \"\"\n            if environment_id is not None:\n                environment_slug = \"/environments/{0}\".format(environment_id)\n            return \"spaces/{0}{1}/public/content_types\".format(space_id, environment_slug)\n        return super(ContentType, klass).base_url(\n            space_id,\n            resource_id=resource_id,\n            environment_id=environment_id,\n            **kwargs\n        )",
    "docstring": "Returns the URI for the content type."
  },
  {
    "code": "def get_child_files(path):\n        path = FileHelper.abspath(path)\n        return [filename for filename in os.listdir(path) if os.path.isfile(os.path.join(path, filename))]",
    "docstring": "Get all child files of a folder"
  },
  {
    "code": "def draw_variable_local(self, size): \n        return ss.norm.rvs(loc=self.mu0, scale=self.sigma0, size=size)",
    "docstring": "Simulate from the Normal distribution using instance values\n\n        Parameters\n        ----------\n        size : int\n            How many simulations to perform\n\n        Returns\n        ----------\n        np.ndarray of Normal random variable"
  },
  {
    "code": "def clean_dict(d0, clean_item_fn=None):\n    clean_item_fn = clean_item_fn if clean_item_fn else clean_item\n    d = dict()\n    for key in d0:\n        cleaned_item = clean_item_fn(d0[key])\n        if cleaned_item is not None:\n            d[key] = cleaned_item\n    return d",
    "docstring": "Return a json-clean dict. Will log info message for failures."
  },
  {
    "code": "def attempt(self, *kinds):\n        if self._error:\n            raise self._error\n        token = self.next_token\n        if not token:\n            return None\n        if kinds and token.kind not in kinds:\n            return None\n        self._advance()\n        return token",
    "docstring": "Try to get the next token if it matches one of the kinds given,\n        otherwise returning None. If no kinds are given, any kind is\n        accepted."
  },
  {
    "code": "def DbExportEvent(self, argin):\n        self._log.debug(\"In DbExportEvent()\")\n        if len(argin) < 5:\n            self.warn_stream(\"DataBase::db_export_event(): insufficient export info for event \")\n            th_exc(DB_IncorrectArguments,\n                   \"insufficient export info for event\",\n                   \"DataBase::ExportEvent()\")\n        event, IOR, host, pid, version = argin[:5]\n        event = replace_wildcard(event.lower())\n        self.db.export_event(event, IOR, host, pid, version)",
    "docstring": "Export Event channel to database\n\n        :param argin: Str[0] = event channel name (or factory name)\n        Str[1] = CORBA IOR\n        Str[2] = Notifd host name\n        Str[3] = Notifd pid\n        Str[4] = Notifd version\n        :type: tango.DevVarStringArray\n        :return:\n        :rtype: tango.DevVoid"
  },
  {
    "code": "def set_extractor_processor_inputs(self, extractor_processors,\n                                       sub_output=None):\n        if not (isinstance(extractor_processors, ExtractorProcessor) or\n                isinstance(extractor_processors, types.ListType)):\n            raise ValueError(\n                \"extractor_processors must be an ExtractorProcessor or a list\")\n        if isinstance(extractor_processors, ExtractorProcessor):\n            extractor_processor = extractor_processors\n            self.input_fields = self.__get_jp(extractor_processor, sub_output)\n        elif isinstance(extractor_processors, types.ListType):\n            self.input_fields = list()\n            for extractor_processor in extractor_processors:\n                if isinstance(extractor_processor, ExtractorProcessor):\n                    self.input_fields.append(\n                        self.__get_jp(extractor_processor, sub_output))\n                elif isinstance(extractor_processor, list):\n                    self.input_fields.append(\n                        reduce(lambda a, b: \"{}|{}\".format(a, b),\n                               [\"({})\".format(self.__get_jp(x, sub_output))\n                                for x in extractor_processor]))\n        self.generate_json_paths()\n        return self",
    "docstring": "Instead of specifying fields in the source document to rename\n        for the extractor, allows the user to specify ExtractorProcessors that\n        are executed earlier in the chain and generate json paths from\n        their output fields"
  },
  {
    "code": "def _build(self, inputs_list):\n    outputs = []\n    for idx, tensor in enumerate(inputs_list):\n      outputs.append(\n          Linear(\n              self._output_size,\n              initializers=self._initializers,\n              partitioners=self._partitioners,\n              regularizers=self._regularizers,\n              use_bias=(idx == 0 and self._use_bias))(tensor))\n    return tf.add_n(outputs)",
    "docstring": "Connects the module into the graph.\n\n    If this is not the first time the module has been connected to the graph,\n    the Tensors provided here must have the same final dimensions as when called\n    the first time, in order for the existing variables to be the correct size\n    for the multiplication. The batch size may differ for each connection.\n\n    Args:\n      inputs_list: A list of 2D Tensors of rank 2, with leading batch dimension.\n\n    Returns:\n      A 2D Tensor of size [batch_size, output_size]."
  },
  {
    "code": "def fix_repeat_dt(dt_list, offset_s=0.001):\n    idx = (np.diff(dt_list) == timedelta(0))\n    while np.any(idx):\n        dt_list[idx.nonzero()[0] + 1] += timedelta(seconds=offset_s)\n        idx = (np.diff(dt_list) == timedelta(0))\n    return dt_list",
    "docstring": "Add some small offset to remove duplicate times\n    Needed for xarray interp, which expects monotonically increasing times"
  },
  {
    "code": "def _SetHeader(self, values):\n    if self._values and len(values) != len(self._values):\n      raise ValueError('Header values not equal to existing data width.')\n    if not self._values:\n      for _ in range(len(values)):\n        self._values.append(None)\n    self._keys = list(values)\n    self._BuildIndex()",
    "docstring": "Set the row's header from a list."
  },
  {
    "code": "def start_listener_thread(self, timeout_ms=30000, exception_handler=None):\n        try:\n            thread = Thread(target=self.listen_forever,\n                            args=(timeout_ms, exception_handler))\n            thread.daemon = True\n            self.sync_thread = thread\n            self.should_listen = True\n            thread.start()\n        except RuntimeError:\n            e = sys.exc_info()[0]\n            logger.error(\"Error: unable to start thread. %s\", str(e))",
    "docstring": "Start a listener thread to listen for events in the background.\n\n        Args:\n            timeout (int): How long to poll the Home Server for before\n               retrying.\n            exception_handler (func(exception)): Optional exception handler\n               function which can be used to handle exceptions in the caller\n               thread."
  },
  {
    "code": "def is_event_of_key_string(event, key_string):\n    return len(event) >= 2 and not isinstance(event[1], Gdk.ModifierType) and event[0] == Gtk.accelerator_parse(key_string)[0]",
    "docstring": "Condition check if key string represent the key value of handed event and whether the event is of right type\n\n    The function checks for constructed event tuple that are generated by the rafcon.gui.shortcut_manager.ShortcutManager.\n    :param tuple event: Event tuple generated by the ShortcutManager\n    :param str key_string: Key string parsed to a key value and for condition check"
  },
  {
    "code": "def bdd_common_after_scenario(context_or_world, scenario, status):\n    if status == 'skipped':\n        return\n    elif status == 'passed':\n        test_status = 'Pass'\n        test_comment = None\n        context_or_world.logger.info(\"The scenario '%s' has passed\", scenario.name)\n    else:\n        test_status = 'Fail'\n        test_comment = \"The scenario '%s' has failed\" % scenario.name\n        context_or_world.logger.error(\"The scenario '%s' has failed\", scenario.name)\n        context_or_world.global_status['test_passed'] = False\n    DriverWrappersPool.close_drivers(scope='function', test_name=scenario.name, test_passed=status == 'passed',\n                                     context=context_or_world)\n    add_jira_status(get_jira_key_from_scenario(scenario), test_status, test_comment)",
    "docstring": "Clean method that will be executed after each scenario in behave or lettuce\n\n    :param context_or_world: behave context or lettuce world\n    :param scenario: running scenario\n    :param status: scenario status (passed, failed or skipped)"
  },
  {
    "code": "def configure(self, kubernetes_host, kubernetes_ca_cert='', token_reviewer_jwt='', pem_keys=None,\n                  mount_point=DEFAULT_MOUNT_POINT):\n        if pem_keys is None:\n            pem_keys = []\n        list_of_pem_params = {\n            'kubernetes_ca_cert': kubernetes_ca_cert,\n            'pem_keys': pem_keys\n        }\n        for param_name, param_argument in list_of_pem_params.items():\n            validate_pem_format(\n                param_name=param_name,\n                param_argument=param_argument,\n            )\n        params = {\n            'kubernetes_host': kubernetes_host,\n            'kubernetes_ca_cert': kubernetes_ca_cert,\n            'token_reviewer_jwt': token_reviewer_jwt,\n            'pem_keys': pem_keys,\n        }\n        api_path = '/v1/auth/{mount_point}/config'.format(\n            mount_point=mount_point\n        )\n        return self._adapter.post(\n            url=api_path,\n            json=params,\n        )",
    "docstring": "Configure the connection parameters for Kubernetes.\n\n        This path honors the distinction between the create and update capabilities inside ACL policies.\n\n        Supported methods:\n            POST: /auth/{mount_point}/config. Produces: 204 (empty body)\n\n        :param kubernetes_host: Host must be a host string, a host:port pair, or a URL to the base of the\n            Kubernetes API server. Example: https://k8s.example.com:443\n        :type kubernetes_host: str | unicode\n        :param kubernetes_ca_cert: PEM encoded CA cert for use by the TLS client used to talk with the Kubernetes API.\n            NOTE: Every line must end with a newline: \\n\n        :type kubernetes_ca_cert: str | unicode\n        :param token_reviewer_jwt: A service account JWT used to access the TokenReview API to validate other\n            JWTs during login. If not set the JWT used for login will be used to access the API.\n        :type token_reviewer_jwt: str | unicode\n        :param pem_keys: Optional list of PEM-formatted public keys or certificates used to verify the signatures of\n            Kubernetes service account JWTs. If a certificate is given, its public key will be extracted. Not every\n            installation of Kubernetes exposes these keys.\n        :type pem_keys: list\n        :param mount_point: The \"path\" the method/backend was mounted on.\n        :type mount_point: str | unicode\n        :return: The response of the configure_method request.\n        :rtype: requests.Response"
  },
  {
    "code": "def assemble(self):\n        first_block = ray.get(self.objectids[(0, ) * self.ndim])\n        dtype = first_block.dtype\n        result = np.zeros(self.shape, dtype=dtype)\n        for index in np.ndindex(*self.num_blocks):\n            lower = DistArray.compute_block_lower(index, self.shape)\n            upper = DistArray.compute_block_upper(index, self.shape)\n            result[[slice(l, u) for (l, u) in zip(lower, upper)]] = ray.get(\n                self.objectids[index])\n        return result",
    "docstring": "Assemble an array from a distributed array of object IDs."
  },
  {
    "code": "def _msToString(self, ms):\n        hr, ms = divmod(ms, 3600000)\n        mins, ms = divmod(ms, 60000)\n        secs, mill = divmod(ms, 1000)\n        return \"%ihr %imin %isecs %ims\" % (hr, mins, secs, mill)",
    "docstring": "Change milliseconds to hours min sec ms format."
  },
  {
    "code": "def _compile_fragment_ast(schema, current_schema_type, ast, location, context):\n    query_metadata_table = context['metadata']\n    coerces_to_type_name = ast.type_condition.name.value\n    coerces_to_type_obj = schema.get_type(coerces_to_type_name)\n    basic_blocks = []\n    is_same_type_as_scope = current_schema_type.is_same_type(coerces_to_type_obj)\n    equivalent_union_type = context['type_equivalence_hints'].get(coerces_to_type_obj, None)\n    is_base_type_of_union = (\n        isinstance(current_schema_type, GraphQLUnionType) and\n        current_schema_type.is_same_type(equivalent_union_type)\n    )\n    if not (is_same_type_as_scope or is_base_type_of_union):\n        query_metadata_table.record_coercion_at_location(location, coerces_to_type_obj)\n        basic_blocks.append(blocks.CoerceType({coerces_to_type_name}))\n    inner_basic_blocks = _compile_ast_node_to_ir(\n        schema, coerces_to_type_obj, ast, location, context)\n    basic_blocks.extend(inner_basic_blocks)\n    return basic_blocks",
    "docstring": "Return a list of basic blocks corresponding to the inline fragment at this AST node.\n\n    Args:\n        schema: GraphQL schema object, obtained from the graphql library\n        current_schema_type: GraphQLType, the schema type at the current location\n        ast: GraphQL AST node, obtained from the graphql library.\n        location: Location object representing the current location in the query\n        context: dict, various per-compilation data (e.g. declared tags, whether the current block\n                 is optional, etc.). May be mutated in-place in this function!\n\n    Returns:\n        list of basic blocks, the compiled output of the vertex AST node"
  },
  {
    "code": "def extract_geometry(self):\n        gf = vtk.vtkCompositeDataGeometryFilter()\n        gf.SetInputData(self)\n        gf.Update()\n        return wrap(gf.GetOutputDataObject(0))",
    "docstring": "Combines the geomertry of all blocks into a single ``PolyData``\n        object. Place this filter at the end of a pipeline before a polydata\n        consumer such as a polydata mapper to extract geometry from all blocks\n        and append them to one polydata object."
  },
  {
    "code": "def _get_files(file_patterns, top=HERE):\n    if not isinstance(file_patterns, (list, tuple)):\n        file_patterns = [file_patterns]\n    for i, p in enumerate(file_patterns):\n        if os.path.isabs(p):\n            file_patterns[i] = os.path.relpath(p, top)\n    matchers = [_compile_pattern(p) for p in file_patterns]\n    files = set()\n    for root, dirnames, filenames in os.walk(top):\n        if 'node_modules' in dirnames:\n            dirnames.remove('node_modules')\n        for m in matchers:\n            for filename in filenames:\n                fn = os.path.relpath(_glob_pjoin(root, filename), top)\n                fn = fn.replace(os.sep, '/')\n                if m(fn):\n                    files.add(fn.replace(os.sep, '/'))\n    return list(files)",
    "docstring": "Expand file patterns to a list of paths.\n\n    Parameters\n    -----------\n    file_patterns: list or str\n        A list of glob patterns for the data file locations.\n        The globs can be recursive if they include a `**`.\n        They should be relative paths from the top directory or\n        absolute paths.\n    top: str\n        the directory to consider for data files\n\n    Note:\n    Files in `node_modules` are ignored."
  },
  {
    "code": "def get_grades(self, login=None, promotion=None, **kwargs):\n        _login = kwargs.get(\n            'login',\n            login or self._login\n        )\n        _promotion_id = kwargs.get('promotion', promotion)\n        _grades_url = GRADES_URL.format(login=_login, promo_id=_promotion_id)\n        return self._request_api(url=_grades_url).json()",
    "docstring": "Get a user's grades on a single promotion based on his login.\n\n        Either use the `login` param, or the client's login if unset.\n        :return: JSON"
  },
  {
    "code": "def register(self, plugin):\n        if not plugin or not isinstance(plugin, BasePlugin):\n            raise ValueError(\"Plugin must be implemented as a subclass of BasePlugin class\")\n        if self.is_registered(plugin.name):\n            raise ValueError(\"Plugin with name {} is already registered\".format(plugin.name))\n        self._plugins.append(plugin)",
    "docstring": "Register a plugin. New plugins are added to the end of the plugins list.\n\n        :param samtranslator.plugins.BasePlugin plugin: Instance/subclass of BasePlugin class that implements hooks\n        :raises ValueError: If plugin is not an instance of samtranslator.plugins.BasePlugin or if it is already\n            registered\n        :return: None"
  },
  {
    "code": "def load_psd():\n    psd = np.loadtxt(\"ZERO_DET_high_P_PSD.txt\")[:,1]\n    down_factor = 3\n    pad_size = int(np.ceil(float(psd.size)/down_factor)*down_factor - psd.size)\n    psd_padded = np.append(psd, np.zeros(pad_size)*np.NaN)\n    psd = sp.nanmean(psd_padded.reshape(-1,down_factor), axis=1)\n    return psd",
    "docstring": "Resamples advLIGO noise PSD to 4096 Hz"
  },
  {
    "code": "def all_entity_classes():\n    persistent_classes = Entity._decl_class_registry.values()\n    return [\n        cls for cls in persistent_classes if isclass(cls) and issubclass(cls, Entity)\n    ]",
    "docstring": "Return the list of all concrete persistent classes that are subclasses\n    of Entity."
  },
  {
    "code": "def is_valid(self):\n        if not self.total:\n            return False\n        if not self.contributor.freelanceprofile.is_freelance:\n            return False\n        return True",
    "docstring": "returns `True` if the report should be sent."
  },
  {
    "code": "def get_collection(self, request, **resources):\n        if self._meta.queryset is None:\n            return []\n        filters = self.get_filters(request, **resources)\n        filters.update(self.get_default_filters(**resources))\n        qs = self._meta.queryset\n        for key, (value, exclude) in filters.items():\n            try:\n                if exclude:\n                    qs = qs.exclude(**{key: value})\n                else:\n                    qs = qs.filter(**{key: value})\n            except FieldError, e:\n                logger.warning(e)\n        sorting = self.get_sorting(request, **resources)\n        if sorting:\n            qs = qs.order_by(*sorting)\n        return qs",
    "docstring": "Get filters and return filtered result.\n\n        :return collection: collection of related resources."
  },
  {
    "code": "def load_servers_from_env(self, filter=[], dynamic=None):\n        if dynamic == None:\n            dynamic = self._dynamic\n        if NAMESERVERS_ENV_VAR in os.environ:\n            servers = [s for s in os.environ[NAMESERVERS_ENV_VAR].split(';') \\\n                         if s]\n            self._parse_name_servers(servers, filter, dynamic)",
    "docstring": "Load the name servers environment variable and parse each server in\n        the list.\n\n        @param filter Restrict the parsed objects to only those in this\n                      path. For example, setting filter to [['/',\n                      'localhost', 'host.cxt', 'comp1.rtc']] will\n                      prevent 'comp2.rtc' in the same naming context\n                      from being parsed.\n        @param dynamic Override the tree-wide dynamic setting. If not provided,\n                       the value given when the tree was created will be used."
  },
  {
    "code": "def _start_server(self, *args):\n        self.log(\"Starting server\", args)\n        secure = self.certificate is not None\n        if secure:\n            self.log(\"Running SSL server with cert:\", self.certificate)\n        else:\n            self.log(\"Running insecure server without SSL. Do not use without SSL proxy in production!\", lvl=warn)\n        try:\n            self.server = Server(\n                (self.host, self.port),\n                secure=secure,\n                certfile=self.certificate\n            ).register(self)\n        except PermissionError:\n            self.log('Could not open (privileged?) port, check '\n                     'permissions!', lvl=critical)",
    "docstring": "Run the node local server"
  },
  {
    "code": "def cores(self):\n        if self._cores is not None:\n            return self._cores\n        elif self._config is not None:\n            return self._config.defaultCores\n        else:\n            raise AttributeError(\"Default value for 'cores' cannot be determined\")",
    "docstring": "The number of CPU cores required."
  },
  {
    "code": "def _update_recording(self, frame, config):\n    should_record = config['is_recording']\n    if should_record:\n      if not self.is_recording:\n        self.is_recording = True\n        logger.info(\n            'Starting recording using %s',\n            self.video_writer.current_output().name())\n      self.video_writer.write_frame(frame)\n    elif self.is_recording:\n      self.is_recording = False\n      self.video_writer.finish()\n      logger.info('Finished recording')",
    "docstring": "Adds a frame to the current video output."
  },
  {
    "code": "def get(self):\n        key = self.get_key_from_request()\n        result = self.get_storage().get(key)\n        return result if result else None",
    "docstring": "Get the item from redis."
  },
  {
    "code": "def request(self, apdu):\n        if _debug: ClientSSM._debug(\"request %r\", apdu)\n        apdu.pduSource = None\n        apdu.pduDestination = self.pdu_address\n        self.ssmSAP.request(apdu)",
    "docstring": "This function is called by client transaction functions when it wants\n        to send a message to the device."
  },
  {
    "code": "def partial_fit(self, X):\n        opt, cost = self.sess.run((self.optimizer, self.cost), \n                                  feed_dict={self.x: X})\n        return cost",
    "docstring": "Train model based on mini-batch of input data.\n        \n        Return cost of mini-batch."
  },
  {
    "code": "def AAAA(host, nameserver=None):\n    dig = ['dig', '+short', six.text_type(host), 'AAAA']\n    if nameserver is not None:\n        dig.append('@{0}'.format(nameserver))\n    cmd = __salt__['cmd.run_all'](dig, python_shell=False)\n    if cmd['retcode'] != 0:\n        log.warning(\n            'dig returned exit code \\'%s\\'. Returning empty list as fallback.',\n            cmd['retcode']\n        )\n        return []\n    return [x for x in cmd['stdout'].split('\\n') if check_ip(x)]",
    "docstring": "Return the AAAA record for ``host``.\n\n    Always returns a list.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt ns1 dig.AAAA www.google.com"
  },
  {
    "code": "def on_view_not_found(\n            self, _,\n            start_response: Callable[[str, List[Tuple[str, str]]], None],\n    ) -> Iterable[bytes]:\n        start_response(\n            \"405 Method Not Allowed\",\n            [('Content-type', 'text/plain')])\n        return [b\"Method Not Allowed\"]",
    "docstring": "called when valid view is not found"
  },
  {
    "code": "def insert(self, schema, fields, **kwargs):\n        r = 0\n        with self.connection(**kwargs) as connection:\n            kwargs['connection'] = connection\n            try:\n                with self.transaction(**kwargs):\n                    r = self._insert(schema, fields, **kwargs)\n            except Exception as e:\n                exc_info = sys.exc_info()\n                if self.handle_error(schema, e, **kwargs):\n                    r = self._insert(schema, fields, **kwargs)\n                else:\n                    self.raise_error(e, exc_info)\n        return r",
    "docstring": "Persist d into the db\n\n        schema -- Schema()\n        fields -- dict -- the values to persist\n\n        return -- int -- the primary key of the row just inserted"
  },
  {
    "code": "def find_span_binsearch(degree, knot_vector, num_ctrlpts, knot, **kwargs):\n    tol = kwargs.get('tol', 10e-6)\n    n = num_ctrlpts - 1\n    if abs(knot_vector[n + 1] - knot) <= tol:\n        return n\n    low = degree\n    high = num_ctrlpts\n    mid = (low + high) / 2\n    mid = int(round(mid + tol))\n    while (knot < knot_vector[mid]) or (knot >= knot_vector[mid + 1]):\n        if knot < knot_vector[mid]:\n            high = mid\n        else:\n            low = mid\n        mid = int((low + high) / 2)\n    return mid",
    "docstring": "Finds the span of the knot over the input knot vector using binary search.\n\n    Implementation of Algorithm A2.1 from The NURBS Book by Piegl & Tiller.\n\n    The NURBS Book states that the knot span index always starts from zero, i.e. for a knot vector [0, 0, 1, 1];\n    if FindSpan returns 1, then the knot is between the interval [0, 1).\n\n    :param degree: degree, :math:`p`\n    :type degree: int\n    :param knot_vector: knot vector, :math:`U`\n    :type knot_vector: list, tuple\n    :param num_ctrlpts: number of control points, :math:`n + 1`\n    :type num_ctrlpts: int\n    :param knot: knot or parameter, :math:`u`\n    :type knot: float\n    :return: knot span\n    :rtype: int"
  },
  {
    "code": "def name(self):\n        return self._meta.name if self._meta.name else \\\n            'Rule @%s' % self.tag",
    "docstring": "Name attribute of rule element"
  },
  {
    "code": "def reset(self):\n        self.resetRNG()\n        sNow = np.zeros(self.pop_size)\n        Shk  = self.RNG.rand(self.pop_size)\n        sNow[Shk < self.p_init] = 1\n        self.sNow = sNow",
    "docstring": "Resets this agent type to prepare it for a new simulation run.  This\n        includes resetting the random number generator and initializing the style\n        of each agent of this type."
  },
  {
    "code": "def get_token(code, token_service, client_id, client_secret, redirect_uri,\n              grant_type):\n  data = {\n      'code': code,\n      'client_id': client_id,\n      'client_secret': client_secret,\n      'redirect_uri': redirect_uri,\n      'grant_type': grant_type,\n  }\n  resp = requests.post(token_service, data, verify=False)\n  return resp.json()",
    "docstring": "Fetches an OAuth 2 token."
  },
  {
    "code": "def set_val(self, key:str, val:Any, bn_groups:bool=True)->Any:\n        \"Set `val` inside the optimizer dictionary at `key`.\"\n        if is_tuple(val): val = [(v1,v2) for v1,v2 in zip(*val)]\n        for v,pg1,pg2 in zip(val,self.opt.param_groups[::2],self.opt.param_groups[1::2]):\n            pg1[key] = v\n            if bn_groups: pg2[key] = v\n        return val",
    "docstring": "Set `val` inside the optimizer dictionary at `key`."
  },
  {
    "code": "def is_valid_delta_name(file):\n        filename = basename(file)\n        pattern = re.compile(Delta.FILENAME_PATTERN)\n        if re.match(pattern, filename):\n            return True\n        return False",
    "docstring": "Return if a file has a valid name\n\n        A delta file name can be:\n        - pre-all.py\n        - pre-all.sql\n        - delta_x.x.x_ddmmyyyy.pre.py\n        - delta_x.x.x_ddmmyyyy.pre.sql\n        - delta_x.x.x_ddmmyyyy.py\n        - delta_x.x.x_ddmmyyyy.sql\n        - delta_x.x.x_ddmmyyyy.post.py\n        - delta_x.x.x_ddmmyyyy.post.sql\n        - post-all.py\n        - post-all.sql\n\n        where x.x.x is the version number and _ddmmyyyy is an optional\n        description, usually representing the date of the delta file"
  },
  {
    "code": "def update(self, test_path, number):\n        GRAPH_WIDTH = 14\n        num_filled = int(round(min(1.0, float(number) / self.max) * GRAPH_WIDTH))\n        graph = ''.join([self._fill_cap(' ' * num_filled),\n                         self._empty_cap(self._empty_char * (GRAPH_WIDTH - num_filled))])\n        cols_for_path = self.cols - GRAPH_WIDTH - 2\n        if len(test_path) > cols_for_path:\n            test_path = test_path[len(test_path) - cols_for_path:]\n        else:\n            test_path += ' ' * (cols_for_path - len(test_path))\n        self.last = self._term.bold(test_path) + '  ' + graph\n        with self._at_last_line():\n            self.stream.write(self.last)\n        self.stream.flush()",
    "docstring": "Draw an updated progress bar.\n\n        At the moment, the graph takes a fixed width, and the test identifier\n        takes the rest of the row, truncated from the left to fit.\n\n        test_path -- the selector of the test being run\n        number -- how many tests have been run so far, including this one"
  },
  {
    "code": "def dump(self, fh, value, context=None):\n\t\tvalue = self.dumps(value)\n\t\tfh.write(value)\n\t\treturn len(value)",
    "docstring": "Attempt to transform and write a string-based foreign value to the given file-like object.\n\t\t\n\t\tReturns the length written."
  },
  {
    "code": "def add_density_option_group(parser):\n    density_group = parser.add_argument_group(\"Options for configuring the \"\n                                              \"contours and density color map\")\n    density_group.add_argument(\n        \"--density-cmap\", type=str, default='viridis',\n        help=\"Specify the colormap to use for the density. \"\n             \"Default is viridis.\")\n    density_group.add_argument(\n        \"--contour-color\", type=str, default=None,\n        help=\"Specify the color to use for the contour lines. Default is \"\n             \"white for density plots and black for scatter plots.\")\n    density_group.add_argument(\n        '--use-kombine-kde', default=False, action=\"store_true\",\n        help=\"Use kombine's KDE for determining contours. \"\n             \"Default is to use scipy's gaussian_kde.\")\n    return density_group",
    "docstring": "Adds the options needed to configure contours and density colour map.\n\n    Parameters\n    ----------\n    parser : object\n        ArgumentParser instance."
  },
  {
    "code": "def instruction_ROR_register(self, opcode, register):\n        a = register.value\n        r = self.ROR(a)\n        register.set(r)",
    "docstring": "Rotate accumulator right"
  },
  {
    "code": "def export_public_keys(self, identities):\n        public_keys = []\n        with self.device:\n            for i in identities:\n                pubkey = self.device.pubkey(identity=i)\n                vk = formats.decompress_pubkey(pubkey=pubkey,\n                                               curve_name=i.curve_name)\n                public_key = formats.export_public_key(vk=vk,\n                                                       label=i.to_string())\n                public_keys.append(public_key)\n        return public_keys",
    "docstring": "Export SSH public keys from the device."
  },
  {
    "code": "def empty_over_span(self, time, duration):\n        for seg in self.segments:\n            if seg.comp_location_in_seconds >= time and\\\n                seg.comp_location_in_seconds < time + duration:\n                return False\n            elif seg.comp_location_in_seconds + seg.duration_in_seconds >= time and\\\n                seg.comp_location_in_seconds + seg.duration_in_seconds < time + duration:\n                return False\n            elif seg.comp_location_in_seconds < time and\\\n                seg.comp_location_in_seconds + seg.duration_in_seconds >= time + duration:\n                return False\n        return True",
    "docstring": "Helper method that tests whether composition contains any segments\n        at a given time for a given duration. \n\n        :param time: Time (in seconds) to start span\n        :param duration: Duration (in seconds) of span\n        :returns: `True` if there are no segments in the composition that overlap the span starting at `time` and lasting for `duration` seconds. `False` otherwise."
  },
  {
    "code": "def write(self, auth, resource, value, options={}, defer=False):\n        return self._call('write', auth, [resource, value, options], defer)",
    "docstring": "Writes a single value to the resource specified.\n\n        Args:\n            auth: cik for authentication.\n            resource: resource to write to.\n            value: value to write\n            options: options."
  },
  {
    "code": "def now(tzinfo=True):\n    if dj_now:\n        return dj_now()\n    if tzinfo:\n        return datetime.utcnow().replace(tzinfo=utc)\n    return datetime.now()",
    "docstring": "Return an aware or naive datetime.datetime, depending on settings.USE_TZ."
  },
  {
    "code": "def detect_encoding(value):\n    if six.PY2:\n        null_pattern = tuple(bool(ord(char)) for char in value[:4])\n    else:\n        null_pattern = tuple(bool(char) for char in value[:4])\n    encodings = {\n        (0, 0, 0, 1): 'utf-32-be',\n        (0, 1, 0, 1): 'utf-16-be',\n        (1, 0, 0, 0): 'utf-32-le',\n        (1, 0, 1, 0): 'utf-16-le',\n    }\n    return encodings.get(null_pattern, 'utf-8')",
    "docstring": "Returns the character encoding for a JSON string."
  },
  {
    "code": "def _create_training_directories():\n    logger.info('Creating a new training folder under %s .' % base_dir)\n    os.makedirs(model_dir)\n    os.makedirs(input_config_dir)\n    os.makedirs(output_data_dir)\n    _write_json({}, hyperparameters_file_dir)\n    _write_json({}, input_data_config_file_dir)\n    host_name = socket.gethostname()\n    resources_dict = {\n        \"current_host\": host_name,\n        \"hosts\": [host_name]\n    }\n    _write_json(resources_dict, resource_config_file_dir)",
    "docstring": "Creates the directory structure and files necessary for training under the base path"
  },
  {
    "code": "def get_institution(self, **kwargs):\n        qualifier = kwargs.get('qualifier', '')\n        content = kwargs.get('content', '')\n        if qualifier == 'grantor':\n            return content\n        return None",
    "docstring": "Get the dissertation institution."
  },
  {
    "code": "def list_proxy(root_package = 'vlcp'):\n    proxy_dict = OrderedDict()\n    pkg = __import__(root_package, fromlist=['_'])\n    for imp, module, _ in walk_packages(pkg.__path__, root_package + '.'):\n        m = __import__(module, fromlist = ['_'])\n        for _, v in vars(m).items():\n            if v is not None and isinstance(v, type) and issubclass(v, _ProxyModule) \\\n                    and v is not _ProxyModule \\\n                    and v.__module__ == module \\\n                    and hasattr(v, '_default'):\n                name = v.__name__.lower()\n                if name not in proxy_dict:\n                    proxy_dict[name] = {'defaultmodule': v._default.__name__.lower(),\n                                        'class': repr(v._default.__module__ + '.' + v._default.__name__)}\n    return proxy_dict",
    "docstring": "Walk through all the sub modules, find subclasses of vlcp.server.module._ProxyModule,\n    list their default values"
  },
  {
    "code": "def copy_figure_to_clipboard(figure='gcf'):\n    try:\n        import pyqtgraph as _p\n        if figure is 'gcf': figure = _s.pylab.gcf() \n        path = _os.path.join(_s.settings.path_home, \"clipboard.png\")\n        figure.savefig(path)\n        _p.QtGui.QApplication.instance().clipboard().setImage(_p.QtGui.QImage(path))\n    except:         \n        print(\"This function currently requires pyqtgraph to be installed.\")",
    "docstring": "Copies the specified figure to the system clipboard. Specifying 'gcf'\n    will use the current figure."
  },
  {
    "code": "def add(self, recipients):\n        if recipients:\n            if isinstance(recipients, str):\n                self._recipients.append(\n                    Recipient(address=recipients, parent=self._parent,\n                              field=self._field))\n            elif isinstance(recipients, Recipient):\n                self._recipients.append(recipients)\n            elif isinstance(recipients, tuple):\n                name, address = recipients\n                if address:\n                    self._recipients.append(\n                        Recipient(address=address, name=name,\n                                  parent=self._parent, field=self._field))\n            elif isinstance(recipients, list):\n                for recipient in recipients:\n                    self.add(recipient)\n            else:\n                raise ValueError('Recipients must be an address string, a '\n                                 'Recipient instance, a (name, address) '\n                                 'tuple or a list')\n            self._track_changes()",
    "docstring": "Add the supplied recipients to the exiting list\n\n        :param recipients: list of either address strings or\n         tuples (name, address) or dictionary elements\n        :type recipients: list[str] or list[tuple] or list[dict]"
  },
  {
    "code": "def create_highlight(self, artist):\n        highlight = copy.copy(artist)\n        highlight.set(color=self.highlight_color, mec=self.highlight_color,\n                      lw=self.highlight_width, mew=self.highlight_width)\n        artist.axes.add_artist(highlight)\n        return highlight",
    "docstring": "Create a new highlight for the given artist."
  },
  {
    "code": "def showEvent(self, event):\n        super(CodeEdit, self).showEvent(event)\n        self.panels.refresh()",
    "docstring": "Overrides showEvent to update the viewport margins"
  },
  {
    "code": "def browsers(self, browser=None, browser_version=None, device=None, os=None, os_version=None):\n        response = self.execute('GET', '/screenshots/browsers.json')\n        for key, value in list(locals().items()):\n            if key in ('self', 'response') or not value:\n                continue\n            response = [item for item in response if match_item(key, value, item)]\n        return response",
    "docstring": "Returns list of available browsers & OS."
  },
  {
    "code": "def get_bounce(bounce_id, api_key=None, secure=None, test=None,\n               **request_args):\n    return _default_bounce.get(bounce_id, api_key=api_key, secure=secure,\n                               test=test, **request_args)",
    "docstring": "Get a single bounce.\n\n    :param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.\n    :param api_key: Your Postmark API key. Required, if `test` is not `True`.\n    :param secure: Use the https scheme for the Postmark API.\n        Defaults to `True`\n    :param test: Use the Postmark Test API. Defaults to `False`.\n    :param \\*\\*request_args: Keyword arguments to pass to\n        :func:`requests.request`.\n    :rtype: :class:`BounceResponse`"
  },
  {
    "code": "def selectisnot(table, field, value, complement=False):\n    return selectop(table, field, value, operator.is_not, complement=complement)",
    "docstring": "Select rows where the given field `is not` the given value."
  },
  {
    "code": "def match(self, row):\n        for condition in self._conditions:\n            if condition.match(row):\n                return True\n        return False",
    "docstring": "Returns True if the row matches one or more child conditions. Returns False otherwise.\n\n        :param dict row: The row.\n\n        :rtype: bool"
  },
  {
    "code": "def as_set(self, include_weak=False):\n        rv = set(self._strong)\n        if include_weak:\n            rv.update(self._weak)\n        return rv",
    "docstring": "Convert the `ETags` object into a python set.  Per default all the\n        weak etags are not part of this set."
  },
  {
    "code": "def copy(self):\n        model = self.__class__(self._database)\n        model._limits_lower = dict(self._limits_lower)\n        model._limits_upper = dict(self._limits_upper)\n        model._reaction_set = set(self._reaction_set)\n        model._compound_set = set(self._compound_set)\n        return model",
    "docstring": "Return copy of model"
  },
  {
    "code": "def spit(path, txt, encoding='UTF-8', append=False):\n    mode = 'a' if append else 'w'\n    with io.open(path, mode, encoding=encoding) as f:\n        f.write(txt)\n        return txt",
    "docstring": "Write a unicode string `txt` to file `path`.\n\n    By default encoded as UTF-8 and truncates the file prior to writing\n\n    Parameters\n    ----------\n\n    path : str\n        File path to file on disk\n    txt : unicode\n        Text content to write to file\n    encoding : str, default `UTF-8`, optional\n        Encoding of the file\n    append : Boolean, default False\n        Append to file instead of truncating before writing\n\n    Returns\n    -------\n\n    The txt written to the file as a unicode string"
  },
  {
    "code": "def get_name(self, tag):\n        name = super(functionTagProcessor, self).get_name(tag)\n        if self.include_function_signatures:\n            func_args = tag.findChild('arglist')\n            if func_args and len(func_args.contents):\n                name += func_args.contents[0]\n            ret_type = tag.findChild('type')\n            if ret_type and len(ret_type.contents):\n                name += ' -> ' + ret_type.contents[0]\n        return name",
    "docstring": "Override. Extract a representative \"name\" from a function tag.\n\n        get_name's output can be controlled through keyword arguments that are\n        provided when initializing a functionTagProcessor. For instance,\n        function arguments and return types can be included by passing\n        include_function_signatures=True to __init__().\n\n        Args:\n            tag: A BeautifulSoup Tag for a function.\n\n        Returns:\n            A string that would be appropriate to use as an entry name for a\n            function in a Zeal database."
  },
  {
    "code": "def create_element(self, ns, name):\n        elem = self._node.makeelement('{%s}%s' % (SLDNode._nsmap[ns], name), nsmap=SLDNode._nsmap)\n        self._node.append(elem)\n        return getattr(self, name)",
    "docstring": "Create an element as a child of this SLDNode.\n\n        @type    ns: string\n        @param   ns: The namespace of the new element.\n        @type  name: string\n        @param name: The name of the new element.\n        @rtype: L{SLDNode}\n        @return: The wrapped node, in the parent's property class. This will\n                 always be a descendent of SLDNode."
  },
  {
    "code": "def write_yaml(filename, content):\n    y = _yaml.dump(content, indent=4, default_flow_style=False)\n    if y:\n        return write_file(filename, y)",
    "docstring": "Writes YAML files\n\n    :param filename:\n        The full path to the YAML file\n    :param content:\n        The content to dump\n    :returns:\n        The size written"
  },
  {
    "code": "def subscribe(self, topic=b''):\n        self.sockets[zmq.SUB].setsockopt(zmq.SUBSCRIBE, topic)\n        poller = self.pollers[zmq.SUB]\n        return poller",
    "docstring": "subscribe to the SUB socket, to listen for incomming variables, return a stream that can be listened to."
  },
  {
    "code": "def get_context_data(self, **kwargs):\n        context = super(ScheduleXmlView, self).get_context_data(**kwargs)\n        if self.request.GET.get('render_description', None) == '1':\n            context['render_description'] = True\n        else:\n            context['render_description'] = False\n        return context",
    "docstring": "Allow adding a 'render_description' parameter"
  },
  {
    "code": "def get_article(self, url=None, article_id=None, max_pages=25):\n        query_params = {}\n        if url is not None:\n            query_params['url'] = url\n        if article_id is not None:\n            query_params['article_id'] = article_id\n        query_params['max_pages'] = max_pages\n        url = self._generate_url('parser', query_params=query_params)\n        return self.get(url)",
    "docstring": "Send a GET request to the `parser` endpoint of the parser API to get\n        back the representation of an article.\n\n        The article can be identified by either a URL or an id that exists\n        in Readability.\n\n        Note that either the `url` or `article_id` param should be passed.\n\n        :param url (optional): The url of an article whose content is wanted.\n        :param article_id (optional): The id of an article in the Readability\n            system whose content is wanted.\n        :param max_pages: The maximum number of pages to parse and combine.\n            The default is 25."
  },
  {
    "code": "def _init_training(self):\n        if self.check:\n            self.backprop = CheckedBackprop(self.network, self.problem.cost)\n        else:\n            self.backprop = BatchBackprop(self.network, self.problem.cost)\n        self.momentum = Momentum()\n        self.decent = GradientDecent()\n        self.decay = WeightDecay()\n        self.tying = WeightTying(*self.problem.weight_tying)\n        self.weights = self.tying(self.weights)",
    "docstring": "Classes needed during training."
  },
  {
    "code": "def setup_request_sessions(self):\n        self.req_session = requests.Session()\n        self.req_session.headers.update(self.headers)",
    "docstring": "Sets up a requests.Session object for sharing headers across API requests."
  },
  {
    "code": "def peek(self, length):\n        return self.string[self.pos:self.pos + length]",
    "docstring": "Get a number of characters without advancing the scan pointer.\n\n            >>> s = Scanner(\"test string\")\n            >>> s.peek(7)\n            'test st'\n            >>> s.peek(7)\n            'test st'"
  },
  {
    "code": "def read_csv(self, dtype=False, parse_dates=True, *args, **kwargs):\n        import pandas\n        t = self.resolved_url.get_resource().get_target()\n        kwargs = self._update_pandas_kwargs(dtype, parse_dates, kwargs)\n        return pandas.read_csv(t.fspath, *args, **kwargs)",
    "docstring": "Fetch the target and pass through to pandas.read_csv\n\n        Don't provide the first argument of read_csv(); it is supplied internally."
  },
  {
    "code": "def AddHeadwayPeriodObject(self, headway_period, problem_reporter):\n    warnings.warn(\"No longer supported. The HeadwayPeriod class was renamed to \"\n                  \"Frequency, and all related functions were renamed \"\n                  \"accordingly.\", DeprecationWarning)\n    self.AddFrequencyObject(frequency, problem_reporter)",
    "docstring": "Deprecated. Please use AddFrequencyObject instead."
  },
  {
    "code": "def make_fake_data(g, fac=1.0):\n    if hasattr(g, 'keys'):\n        if not isinstance(g, BufferDict):\n            g = BufferDict(g)\n        return BufferDict(g, buf=make_fake_data(g.buf, fac))\n    else:\n        g_shape = numpy.shape(g)\n        g_flat = numpy.array(g).flat\n        zero = numpy.zeros(len(g_flat), float)\n        dg = (2. ** -0.5) * gvar(zero, evalcov(g_flat))\n        dg *= fac\n        noise = gvar(zero, sdev(dg))\n        g_flat = mean(g_flat) + dg + noise + next(raniter(dg + noise))\n        return g_flat[0] if g_shape == () else g_flat.reshape(g_shape)",
    "docstring": "Make fake data based on ``g``.\n\n    This function replaces the |GVar|\\s in ``g`` by  new |GVar|\\s with similar\n    means and a similar covariance matrix, but multiplied by ``fac**2`` (so\n    standard deviations are ``fac`` times smaller). The changes are random.\n    The function was designed to create fake data for testing fitting\n    routines, where ``g`` is set equal to ``fitfcn(x, prior)`` and ``fac<1``\n    (e.g.,  set ``fac=0.1`` to get fit parameters whose standard deviations\n    are  10x smaller than those of the corresponding priors).\n\n    Args:\n        g (dict, array or gvar.GVar): The |GVar| or array of |GVar|\\s,\n            or dictionary whose values are |GVar|\\s or arrays of |GVar|\\s that\n            from which the fake data is generated.\n\n        fac (float): Uncertainties are rescaled by ``fac`` in the fake data.\n\n    Returns:\n        A collection of |GVar|\\s with the same layout as ``g`` but with\n        somewhat different means, and standard deviations rescaled by ``fac``."
  },
  {
    "code": "def _must_be_deleted(local_path, r_st):\n        if not os.path.lexists(local_path):\n            return True\n        l_st = os.lstat(local_path)\n        if S_IFMT(r_st.st_mode) != S_IFMT(l_st.st_mode):\n            return True\n        return False",
    "docstring": "Return True if the remote correspondent of local_path has to be deleted.\n\n        i.e. if it doesn't exists locally or if it has a different type from the remote one."
  },
  {
    "code": "def parse_broken_json(json_text: str) -> dict:\n    json_text = json_text.replace(\":\", \": \")\n    json_dict = yaml.load(json_text)\n    return json_dict",
    "docstring": "Parses broken JSON that the standard Python JSON module cannot parse.\n\n    Ex: {success:true}\n\n    Keys do not contain quotes and the JSON cannot be parsed using the regular json encoder.\n    YAML happens to be a superset of JSON and can parse json without quotes."
  },
  {
    "code": "def methods(self) -> 'PrettyDir':\n        return PrettyDir(\n            self.obj,\n            [\n                pattr\n                for pattr in self.pattrs\n                if category_match(pattr.category, AttrCategory.FUNCTION)\n            ],\n        )",
    "docstring": "Returns all methods of the inspected object.\n\n        Note that \"methods\" can mean \"functions\" when inspecting a module."
  },
  {
    "code": "def unique(lst):\n    seen = set()\n    def make_seen(x):\n        seen.add(x)\n        return x\n    return [make_seen(x) for x in lst if x not in seen]",
    "docstring": "Return unique elements\n\n    :class:`pandas.unique` and :class:`numpy.unique` cast\n    mixed type lists to the same type. They are faster, but\n    some times we want to maintain the type.\n\n    Parameters\n    ----------\n    lst : list-like\n        List of items\n\n    Returns\n    -------\n    out : list\n        Unique items in the order that they appear in the\n        input.\n\n    Examples\n    --------\n    >>> import pandas as pd\n    >>> import numpy as np\n    >>> lst = ['one', 'two', 123, 'three']\n    >>> pd.unique(lst)\n    array(['one', 'two', '123', 'three'], dtype=object)\n    >>> np.unique(lst)\n    array(['123', 'one', 'three', 'two'],\n          dtype='<U5')\n    >>> unique(lst)\n    ['one', 'two', 123, 'three']\n\n    pandas and numpy cast 123 to a string!, and numpy does not\n    even maintain the order."
  },
  {
    "code": "def draw_identity_line(ax=None, dynamic=True, **kwargs):\n    ax = ax or plt.gca()\n    if 'c' not in kwargs and 'color' not in kwargs:\n        kwargs['color'] = LINE_COLOR\n    if 'alpha' not in kwargs:\n        kwargs['alpha'] = 0.5\n    identity, = ax.plot([],[], **kwargs)\n    def callback(ax):\n        xlim = ax.get_xlim()\n        ylim = ax.get_ylim()\n        data = (\n            max(xlim[0], ylim[0]), min(xlim[1], ylim[1])\n        )\n        identity.set_data(data, data)\n    callback(ax)\n    if dynamic:\n        ax.callbacks.connect('xlim_changed', callback)\n        ax.callbacks.connect('ylim_changed', callback)\n    return ax",
    "docstring": "Draws a 45 degree identity line such that y=x for all points within the\n    given axes x and y limits. This function also registeres a callback so\n    that as the figure is modified, the axes are updated and the line remains\n    drawn correctly.\n\n    Parameters\n    ----------\n\n    ax : matplotlib Axes, default: None\n        The axes to plot the figure on. If None is passed in the current axes\n        will be used (or generated if required).\n\n    dynamic : bool, default : True\n        If the plot is dynamic, callbacks will be registered to update the\n        identiy line as axes are changed.\n\n    kwargs : dict\n        Keyword arguments to pass to the matplotlib plot function to style the\n        identity line.\n\n\n    Returns\n    -------\n\n    ax : matplotlib Axes\n        The axes with the line drawn on it.\n\n    Notes\n    -----\n\n    .. seealso:: `StackOverflow discussion: Does matplotlib have a function for drawing diagonal lines in axis coordinates? <https://stackoverflow.com/questions/22104256/does-matplotlib-have-a-function-for-drawing-diagonal-lines-in-axis-coordinates>`_"
  },
  {
    "code": "def _proc_dihedral(self):\n        main_axis, rot = max(self.rot_sym, key=lambda v: v[1])\n        self.sch_symbol = \"D{}\".format(rot)\n        mirror_type = self._find_mirror(main_axis)\n        if mirror_type == \"h\":\n            self.sch_symbol += \"h\"\n        elif not mirror_type == \"\":\n            self.sch_symbol += \"d\"",
    "docstring": "Handles dihedral group molecules, i.e those with intersecting R2 axes\n        and a main axis."
  },
  {
    "code": "def peak_generation_per_technology_and_weather_cell(self):\n        peak_generation = defaultdict(float)\n        for gen in self.generators:\n            if hasattr(gen, 'weather_cell_id'):\n                if (gen.type, gen.weather_cell_id) in peak_generation.keys():\n                    peak_generation[gen.type, gen.weather_cell_id] += gen.nominal_capacity\n                else:\n                    peak_generation[gen.type, gen.weather_cell_id] = gen.nominal_capacity\n            else:\n                message = 'No weather cell ID found for ' \\\n                          'generator {}.'.format(repr(gen))\n                raise KeyError(message)\n        series_index = pd.MultiIndex.from_tuples(list(peak_generation.keys()),\n                                                 names=['type', 'weather_cell_id'])\n        return pd.Series(peak_generation, index=series_index)",
    "docstring": "Peak generation of each technology and the \n        corresponding weather cell in the grid \n\n        Returns\n        -------\n        :pandas:`pandas.Series<series>`\n            Peak generation index by technology"
  },
  {
    "code": "def parse_substitution_from_list(list_rep):\n    if type(list_rep) is not list:\n        raise SyntaxError('Substitution must be a list')\n    if len(list_rep) < 2:\n        raise SyntaxError('Substitution must be a list of size 2')\n    pattern = list_rep[0]\n    replacement = list_rep[1]\n    is_multiline = False\n    if (len(list_rep) > 2):\n        is_multiline = list_rep[2]\n        if type(is_multiline) is not bool:\n            raise SyntaxError('is_multiline must be a boolean')\n    result = substitute.Substitution(pattern, replacement, is_multiline)\n    return result",
    "docstring": "Parse a substitution from the list representation in the config file."
  },
  {
    "code": "def symmetry_reduce(tensors, structure, tol=1e-8, **kwargs):\n    sga = SpacegroupAnalyzer(structure, **kwargs)\n    symmops = sga.get_symmetry_operations(cartesian=True)\n    unique_mapping = TensorMapping([tensors[0]], [[]], tol=tol)\n    for tensor in tensors[1:]:\n        is_unique = True\n        for unique_tensor, symmop in itertools.product(unique_mapping, symmops):\n            if np.allclose(unique_tensor.transform(symmop), tensor, atol=tol):\n                unique_mapping[unique_tensor].append(symmop)\n                is_unique = False\n                break\n        if is_unique:\n            unique_mapping[tensor] = []\n    return unique_mapping",
    "docstring": "Function that converts a list of tensors corresponding to a structure\n    and returns a dictionary consisting of unique tensor keys with symmop\n    values corresponding to transformations that will result in derivative\n    tensors from the original list\n\n    Args:\n        tensors (list of tensors): list of Tensor objects to test for\n            symmetrically-equivalent duplicates\n        structure (Structure): structure from which to get symmetry\n        tol (float): tolerance for tensor equivalence\n        kwargs: keyword arguments for the SpacegroupAnalyzer\n\n    returns:\n        dictionary consisting of unique tensors with symmetry operations\n        corresponding to those which will reconstruct the remaining\n        tensors as values"
  },
  {
    "code": "def create_comment(self, text):\n        return DashboardComment.get_or_create(self._issue_or_pr, self._header, text)",
    "docstring": "Mimic issue API, so we can use it everywhere.\n        Return dashboard comment."
  },
  {
    "code": "def extract_cpio (archive, compression, cmd, verbosity, interactive, outdir):\n    cmdlist = [util.shell_quote(cmd), '--extract', '--make-directories',\n        '--preserve-modification-time']\n    if sys.platform.startswith('linux') and not cmd.endswith('bsdcpio'):\n        cmdlist.extend(['--no-absolute-filenames',\n        '--force-local', '--nonmatching', r'\"*\\.\\.*\"'])\n    if verbosity > 1:\n        cmdlist.append('-v')\n    cmdlist.extend(['<', util.shell_quote(os.path.abspath(archive))])\n    return (cmdlist, {'cwd': outdir, 'shell': True})",
    "docstring": "Extract a CPIO archive."
  },
  {
    "code": "def enumerate_spans(sentence: List[T],\n                    offset: int = 0,\n                    max_span_width: int = None,\n                    min_span_width: int = 1,\n                    filter_function: Callable[[List[T]], bool] = None) -> List[Tuple[int, int]]:\n    max_span_width = max_span_width or len(sentence)\n    filter_function = filter_function or (lambda x: True)\n    spans: List[Tuple[int, int]] = []\n    for start_index in range(len(sentence)):\n        last_end_index = min(start_index + max_span_width, len(sentence))\n        first_end_index = min(start_index + min_span_width - 1, len(sentence))\n        for end_index in range(first_end_index, last_end_index):\n            start = offset + start_index\n            end = offset + end_index\n            if filter_function(sentence[slice(start_index, end_index + 1)]):\n                spans.append((start, end))\n    return spans",
    "docstring": "Given a sentence, return all token spans within the sentence. Spans are `inclusive`.\n    Additionally, you can provide a maximum and minimum span width, which will be used\n    to exclude spans outside of this range.\n\n    Finally, you can provide a function mapping ``List[T] -> bool``, which will\n    be applied to every span to decide whether that span should be included. This\n    allows filtering by length, regex matches, pos tags or any Spacy ``Token``\n    attributes, for example.\n\n    Parameters\n    ----------\n    sentence : ``List[T]``, required.\n        The sentence to generate spans for. The type is generic, as this function\n        can be used with strings, or Spacy ``Tokens`` or other sequences.\n    offset : ``int``, optional (default = 0)\n        A numeric offset to add to all span start and end indices. This is helpful\n        if the sentence is part of a larger structure, such as a document, which\n        the indices need to respect.\n    max_span_width : ``int``, optional (default = None)\n        The maximum length of spans which should be included. Defaults to len(sentence).\n    min_span_width : ``int``, optional (default = 1)\n        The minimum length of spans which should be included. Defaults to 1.\n    filter_function : ``Callable[[List[T]], bool]``, optional (default = None)\n        A function mapping sequences of the passed type T to a boolean value.\n        If ``True``, the span is included in the returned spans from the\n        sentence, otherwise it is excluded.."
  },
  {
    "code": "def __decode_timehex(self, timehex):\n        year, month, day, hour, minute, second = unpack(\"6B\", timehex)\n        year += 2000\n        d = datetime(year, month, day, hour, minute, second)\n        return d",
    "docstring": "timehex string of six bytes"
  },
  {
    "code": "def paths(self):\n        paths = traversal.closed_paths(self.entities,\n                                       self.vertices)\n        return paths",
    "docstring": "Sequence of closed paths, encoded by entity index.\n\n        Returns\n        ---------\n        paths: (n,) sequence of (*,) int referencing self.entities"
  },
  {
    "code": "def fork(executable, args=(), env={}, path=None, timeout=3600):\n    d = defer.Deferred()\n    p = ProcessProtocol(d, timeout)\n    reactor.spawnProcess(p, executable, (executable,)+tuple(args), env, path)\n    return d",
    "docstring": "fork\n    Provides a deferred wrapper function with a timeout function\n\n    :param executable: Executable\n    :type executable: str.\n    :param args: Tupple of arguments\n    :type args: tupple.\n    :param env: Environment dictionary\n    :type env: dict.\n    :param timeout: Kill the child process if timeout is exceeded\n    :type timeout: int."
  },
  {
    "code": "def add_to_linestring(position_data, kml_linestring):\n    global kml\n    position_data[2] += float(args.aoff)\n    kml_linestring.coords.addcoordinates([position_data])",
    "docstring": "add a point to the kml file"
  },
  {
    "code": "def reset(self):\n        self._variables_shim = {}\n        self._executable = None\n        self._bitstrings = None\n        self.status = 'connected'",
    "docstring": "Reset the Quantum Abstract Machine to its initial state, which is particularly useful\n        when it has gotten into an unwanted state. This can happen, for example, if the QAM\n        is interrupted in the middle of a run."
  },
  {
    "code": "def human_repr(self):\n        return urlunsplit(\n            SplitResult(\n                self.scheme,\n                self._make_netloc(\n                    self.user, self.password, self.host, self._val.port, encode=False\n                ),\n                self.path,\n                self.query_string,\n                self.fragment,\n            )\n        )",
    "docstring": "Return decoded human readable string for URL representation."
  },
  {
    "code": "def CheckHeader(context, header, include_quotes = '<>', language = None):\n    prog_prefix, hdr_to_check = \\\n                 createIncludesFromHeaders(header, 1, include_quotes)\n    res = SCons.Conftest.CheckHeader(context, hdr_to_check, prog_prefix,\n                                     language = language,\n                                     include_quotes = include_quotes)\n    context.did_show_result = 1\n    return not res",
    "docstring": "A test for a C or C++ header file."
  },
  {
    "code": "def on_btn_add_fit(self, event):\n        if self.auto_save.GetValue():\n            self.current_fit = self.add_fit(self.s, None, None, None, saved=True)\n        else:\n            self.current_fit = self.add_fit(self.s, None, None, None, saved=False)\n        self.generate_warning_text()\n        self.update_warning_box()\n        if self.ie_open:\n            self.ie.update_editor()\n        self.update_fit_boxes(True)\n        self.get_new_PCA_parameters(event)",
    "docstring": "add a new interpretation to the current specimen\n\n        Parameters\n        ----------\n        event : the wx.ButtonEvent that triggered this function\n\n        Alters\n        ------\n        pmag_results_data"
  },
  {
    "code": "def mark_module_skipped(self, module_name):\n        try:\n            del self.modules[module_name]\n        except KeyError:\n            pass\n        self.skip_modules[module_name] = True",
    "docstring": "Skip reloading the named module in the future"
  },
  {
    "code": "def DeleteInstanceTags(r, instance, tags, dry_run=False):\n    query = {\n        \"tag\": tags,\n        \"dry-run\": dry_run,\n    }\n    return r.request(\"delete\", \"/2/instances/%s/tags\" % instance, query=query)",
    "docstring": "Deletes tags from an instance.\n\n    @type instance: str\n    @param instance: instance to delete tags from\n    @type tags: list of str\n    @param tags: tags to delete\n    @type dry_run: bool\n    @param dry_run: whether to perform a dry run"
  },
  {
    "code": "def price_oscillator(data, short_period, long_period):\n    catch_errors.check_for_period_error(data, short_period)\n    catch_errors.check_for_period_error(data, long_period)\n    ema_short = ema(data, short_period)\n    ema_long = ema(data, long_period)\n    po = ((ema_short - ema_long) / ema_long) * 100\n    return po",
    "docstring": "Price Oscillator.\n\n    Formula:\n    (short EMA - long EMA / long EMA) * 100"
  },
  {
    "code": "def get_remote_port(self, tlv_data):\n        ret, parsed_val = self._check_common_tlv_format(\n            tlv_data, \"\\n\", \"Port Description TLV\")\n        if not ret:\n            return None\n        return parsed_val[1].strip()",
    "docstring": "Returns Remote Port from the TLV."
  },
  {
    "code": "def symlink_exists(self, symlink):\n        if not isinstance(symlink, basestring):\n            raise TypeError(\"symlink can only be an instance of type basestring\")\n        exists = self._call(\"symlinkExists\",\n                     in_p=[symlink])\n        return exists",
    "docstring": "Checks whether a symbolic link exists in the guest.\n\n        in symlink of type str\n            Path to the alleged symbolic link.  Guest path style.\n\n        return exists of type bool\n            Returns @c true if the symbolic link exists.  Returns @c false if it\n            does not exist, if the file system object identified by the path is\n            not a symbolic link, or if the object type is inaccessible to the\n            user, or if the @a symlink argument is empty.\n\n        raises :class:`OleErrorNotimpl`\n            The method is not implemented yet."
  },
  {
    "code": "def end_subsegment(self, end_time=None):\n        subsegment = self.get_trace_entity()\n        if self._is_subsegment(subsegment):\n            subsegment.close(end_time)\n            self._local.entities.pop()\n            return True\n        else:\n            log.warning(\"No subsegment to end.\")\n            return False",
    "docstring": "End the current active segment. Return False if there is no\n        subsegment to end.\n\n        :param int end_time: epoch in seconds. If not specified the current\n            system time will be used."
  },
  {
    "code": "def respond(self):\n        response = self.req.server.wsgi_app(self.env, self.start_response)\n        try:\n            for chunk in filter(None, response):\n                if not isinstance(chunk, six.binary_type):\n                    raise ValueError('WSGI Applications must yield bytes')\n                self.write(chunk)\n        finally:\n            self.req.ensure_headers_sent()\n            if hasattr(response, 'close'):\n                response.close()",
    "docstring": "Process the current request.\n\n        From :pep:`333`:\n\n            The start_response callable must not actually transmit\n            the response headers. Instead, it must store them for the\n            server or gateway to transmit only after the first\n            iteration of the application return value that yields\n            a NON-EMPTY string, or upon the application's first\n            invocation of the write() callable."
  },
  {
    "code": "def find_matching_bracket_position(self, start_pos=None, end_pos=None):\n        for A, B in '()', '[]', '{}', '<>':\n            if self.current_char == A:\n                return self.find_enclosing_bracket_right(A, B, end_pos=end_pos) or 0\n            elif self.current_char == B:\n                return self.find_enclosing_bracket_left(A, B, start_pos=start_pos) or 0\n        return 0",
    "docstring": "Return relative cursor position of matching [, (, { or < bracket.\n\n        When `start_pos` or `end_pos` are given. Don't look past the positions."
  },
  {
    "code": "def _lengstr(obj):\n    n = leng(obj)\n    if n is None:\n       r = ''\n    elif n > _len(obj):\n       r = ' leng %d!' % n\n    else:\n       r = ' leng %d' % n\n    return r",
    "docstring": "Object length as a string."
  },
  {
    "code": "def modify_parameters(self, modifier_function):\n        baseline_parameters = self.baseline.parameters\n        baseline_parameters_copy = copy.deepcopy(baseline_parameters)\n        reform_parameters = modifier_function(baseline_parameters_copy)\n        if not isinstance(reform_parameters, ParameterNode):\n            return ValueError(\n                'modifier_function {} in module {} must return a ParameterNode'\n                .format(modifier_function.__name__, modifier_function.__module__,)\n                )\n        self.parameters = reform_parameters\n        self._parameters_at_instant_cache = {}",
    "docstring": "Make modifications on the parameters of the legislation\n\n        Call this function in `apply()` if the reform asks for legislation parameter modifications.\n\n        :param modifier_function: A function that takes an object of type :any:`ParameterNode` and should return an object of the same type."
  },
  {
    "code": "def update_task_redundancy(config, task_id, redundancy):\n    if task_id is None:\n        msg = (\"Are you sure you want to update all the tasks redundancy?\")\n        if click.confirm(msg):\n            res = _update_tasks_redundancy(config, task_id, redundancy)\n            click.echo(res)\n        else:\n            click.echo(\"Aborting.\")\n    else:\n        res = _update_tasks_redundancy(config, task_id, redundancy)\n        click.echo(res)",
    "docstring": "Update task redudancy for a project."
  },
  {
    "code": "def update_orders(self, market_id, instructions, customer_ref=None):\n        return self.make_api_request(\n            'Sports',\n            'updateOrders',\n            utils.get_kwargs(locals()),\n            model=models.UpdateExecutionReport,\n        )",
    "docstring": "Update non-exposure changing fields.\n\n        :param str market_id: The market id these orders are to be placed on\n        :param list instructions: List of `UpdateInstruction` objects\n        :param str customer_ref: Optional order identifier string"
  },
  {
    "code": "def invalidate(self, key):\n        if key not in self.data:\n            return\n        del self.data[key]\n        for cname in self.components:\n            if key in self.depends[cname]:\n                for downstream_key in self.provides[cname]:\n                    self.invalidate(downstream_key)",
    "docstring": "Remove the given data item along with all items that depend on it in the graph."
  },
  {
    "code": "def get_job_asset_url(self, job_id, filename):\n        return 'https://saucelabs.com/rest/v1/{}/jobs/{}/assets/{}'.format(\n            self.client.sauce_username, job_id, filename)",
    "docstring": "Get details about the static assets collected for a specific job."
  },
  {
    "code": "def _wrap_stream_errors(callable_):\n    _patch_callable_name(callable_)\n    @general_helpers.wraps(callable_)\n    def error_remapped_callable(*args, **kwargs):\n        try:\n            result = callable_(*args, **kwargs)\n            return _StreamingResponseIterator(result)\n        except grpc.RpcError as exc:\n            six.raise_from(exceptions.from_grpc_error(exc), exc)\n    return error_remapped_callable",
    "docstring": "Wrap errors for Unary-Stream and Stream-Stream gRPC callables.\n\n    The callables that return iterators require a bit more logic to re-map\n    errors when iterating. This wraps both the initial invocation and the\n    iterator of the return value to re-map errors."
  },
  {
    "code": "def from_json(cls, json_obj):\n        if isinstance(json_obj, str):\n            json_obj = json.loads(json_obj)\n        time = None\n        value = None\n        if cls.TIME_FIELD_NAME in json_obj:\n            time = json_obj[cls.TIME_FIELD_NAME]\n        else:\n            raise InvalidMetricError(\"{field} must be present!\".format(\n                field=cls.TIME_FIELD_NAME))\n        if cls.VALUE_FIELD_NAME in json_obj:\n            value = json_obj[cls.VALUE_FIELD_NAME]\n        return cls(time, value)",
    "docstring": "Build a MetricResponse from JSON.\n\n        :param json_obj: JSON data representing a Cube Metric.\n        :type json_obj: `String` or `json`\n        :throws: `InvalidMetricError` when any of {type,time,data} fields are\n        not present in json_obj."
  },
  {
    "code": "def make_image(location, size, fmt):\n    if not os.path.isabs(location):\n        return ''\n    if not os.path.isdir(os.path.dirname(location)):\n        return ''\n    if not __salt__['cmd.retcode'](\n            'qemu-img create -f {0} {1} {2}M'.format(\n                fmt,\n                location,\n                size),\n                python_shell=False):\n        return location\n    return ''",
    "docstring": "Create a blank virtual machine image file of the specified size in\n    megabytes. The image can be created in any format supported by qemu\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' qemu_img.make_image /tmp/image.qcow 2048 qcow2\n        salt '*' qemu_img.make_image /tmp/image.raw 10240 raw"
  },
  {
    "code": "def blur(dset,fwhm,prefix=None):\n    if prefix==None:\n        prefix = nl.suffix(dset,'_blur%.1fmm'%fwhm)\n    return available_method('blur')(dset,fwhm,prefix)",
    "docstring": "blurs ``dset`` with given ``fwhm`` runs 3dmerge to blur dataset to given ``fwhm``\n    default ``prefix`` is to suffix ``dset`` with ``_blur%.1fmm``"
  },
  {
    "code": "def artifact2destination(self, artifact, descriptor):\n        _art = base64.b64decode(artifact)\n        assert _art[:2] == ARTIFACT_TYPECODE\n        try:\n            endpoint_index = str(int(_art[2:4]))\n        except ValueError:\n            endpoint_index = str(int(hexlify(_art[2:4])))\n        entity = self.sourceid[_art[4:24]]\n        destination = None\n        for desc in entity[\"%s_descriptor\" % descriptor]:\n            for srv in desc[\"artifact_resolution_service\"]:\n                if srv[\"index\"] == endpoint_index:\n                    destination = srv[\"location\"]\n                    break\n        return destination",
    "docstring": "Translate an artifact into a receiver location\n\n        :param artifact: The Base64 encoded SAML artifact\n        :return:"
  },
  {
    "code": "def extract_geometry(dataset):\n        alg = vtk.vtkGeometryFilter()\n        alg.SetInputDataObject(dataset)\n        alg.Update()\n        return _get_output(alg)",
    "docstring": "Extract the outer surface of a volume or structured grid dataset as\n        PolyData. This will extract all 0D, 1D, and 2D cells producing the\n        boundary faces of the dataset."
  },
  {
    "code": "def lpop(self, key, *, encoding=_NOTSET):\n        return self.execute(b'LPOP', key, encoding=encoding)",
    "docstring": "Removes and returns the first element of the list stored at key."
  },
  {
    "code": "def copy_current_websocket_context(func: Callable) -> Callable:\n    if not has_websocket_context():\n        raise RuntimeError('Attempt to copy websocket context outside of a websocket context')\n    websocket_context = _websocket_ctx_stack.top.copy()\n    @wraps(func)\n    async def wrapper(*args: Any, **kwargs: Any) -> Any:\n        async with websocket_context:\n            return await func(*args, **kwargs)\n    return wrapper",
    "docstring": "Share the current websocket context with the function decorated.\n\n    The websocket context is local per task and hence will not be\n    available in any other task. This decorator can be used to make\n    the context available,\n\n    .. code-block:: python\n\n        @copy_current_websocket_context\n        async def within_context() -> None:\n            method = websocket.method\n            ..."
  },
  {
    "code": "def _memory_usage(func, gallery_conf):\n    if gallery_conf['show_memory']:\n        from memory_profiler import memory_usage\n        assert callable(func)\n        mem, out = memory_usage(func, max_usage=True, retval=True,\n                                multiprocess=True)\n        mem = mem[0]\n    else:\n        out = func()\n        mem = 0\n    return out, mem",
    "docstring": "Get memory usage of a function call."
  },
  {
    "code": "def end_compress(codec, stream):\n    OPENJP2.opj_end_compress.argtypes = [CODEC_TYPE, STREAM_TYPE_P]\n    OPENJP2.opj_end_compress.restype = check_error\n    OPENJP2.opj_end_compress(codec, stream)",
    "docstring": "End of compressing the current image.\n\n    Wraps the openjp2 library function opj_end_compress.\n\n    Parameters\n    ----------\n    codec : CODEC_TYPE\n        Compressor handle.\n    stream : STREAM_TYPE_P\n        Output stream buffer.\n\n    Raises\n    ------\n    RuntimeError\n        If the OpenJPEG library routine opj_end_compress fails."
  },
  {
    "code": "def read_moc_fits(moc, filename, include_meta=False, **kwargs):\n    hl = fits.open(filename, mode='readonly', **kwargs)\n    read_moc_fits_hdu(moc, hl[1], include_meta)",
    "docstring": "Read data from a FITS file into a MOC.\n\n    Any additional keyword arguments are passed to the\n    astropy.io.fits.open method."
  },
  {
    "code": "def _configobj_factory(self,\n                           infile,\n                           raise_errors=True,\n                           list_values=True,\n                           file_error=True,\n                           interpolation=False,\n                           configspec=None,\n                           stringify=True,\n                           _inspec=False\n                           ):\n        return configobj.ConfigObj(infile=infile,\n                                   raise_errors=raise_errors,\n                                   list_values=list_values,\n                                   file_error=file_error,\n                                   interpolation=interpolation,\n                                   configspec=configspec,\n                                   stringify=stringify,\n                                   _inspec=_inspec\n                                   )",
    "docstring": "Factory Method.\n        Create Configobj instance and register it to self.config.\n        This method also is used to create configspec instance.\n        Because configspec instance also is ConfigObj instance."
  },
  {
    "code": "def knt2mlt(t):\n    t = np.atleast_1d(t)\n    if t.ndim > 1:\n        raise ValueError(\"t must be a list or a rank-1 array\")\n    out   = []\n    e     = None\n    for k in range(t.shape[0]):\n        if t[k] != e:\n            e     = t[k]\n            count = 0\n        else:\n            count += 1\n        out.append(count)\n    return np.array( out )",
    "docstring": "Count multiplicities of elements in a sorted list or rank-1 array.\n\nMinimal emulation of MATLAB's ``knt2mlt``.\n\nParameters:\n    t:\n        Python list or rank-1 array. Must be sorted!\n\nReturns:\n    out\n        rank-1 array such that\n        out[k] = #{ t[i] == t[k] for i < k }\n\nExample:\n    If ``t = [1, 1, 2, 3, 3, 3]``, then ``out = [0, 1, 0, 0, 1, 2]``.\n\nCaveat:\n    Requires input to be already sorted (this is not checked)."
  },
  {
    "code": "def list_themes(dark=True):\n    dark = \"dark\" if dark else \"light\"\n    themes = os.scandir(os.path.join(MODULE_DIR, \"colorschemes\", dark))\n    return [t for t in themes if os.path.isfile(t.path)]",
    "docstring": "List all installed theme files."
  },
  {
    "code": "def _match_real(filename, include, exclude, follow, symlinks):\n    sep = '\\\\' if util.platform() == \"windows\" else '/'\n    if isinstance(filename, bytes):\n        sep = os.fsencode(sep)\n    if not filename.endswith(sep) and os.path.isdir(filename):\n        filename += sep\n    matched = False\n    for pattern in include:\n        if _fs_match(pattern, filename, sep, follow, symlinks):\n            matched = True\n            break\n    if matched:\n        matched = True\n        if exclude:\n            for pattern in exclude:\n                if _fs_match(pattern, filename, sep, follow, symlinks):\n                    matched = False\n                    break\n    return matched",
    "docstring": "Match real filename includes and excludes."
  },
  {
    "code": "def get_converter(self, parameter):\n        if parameter not in self._converters:\n            param = self.get_parameter(parameter)\n            try:\n                scale = float(param['Scale'])\n            except KeyError:\n                scale = 1\n            def convert(value):\n                return value * scale\n            return convert",
    "docstring": "Generate unit conversion function for given parameter"
  },
  {
    "code": "def shuffle_step(entries, step):\n    answer = []\n    for i in range(0, len(entries), step):\n        sub = entries[i:i+step]\n        shuffle(sub)\n        answer += sub\n    return answer",
    "docstring": "Shuffle the step"
  },
  {
    "code": "def getIndices(self):\n        for indexName in self.neograph.nodes.indexes.keys():\n            indexObject = self.neograph.nodes.indexes.get(indexName)\n            yield Index(indexName, \"vertex\", \"manual\", indexObject)\n        for indexName in self.neograph.relationships.indexes.keys():\n            indexObject = self.neograph.relationships.indexes.get(indexName)\n            yield Index(indexName, \"edge\", \"manual\", indexObject)",
    "docstring": "Returns a generator function over all the existing indexes\n\n        @returns A generator function over all rhe Index objects"
  },
  {
    "code": "def delete_object_in_seconds(self, obj, seconds, extra_info=None):\n        return self.manager.delete_object_in_seconds(self, obj, seconds)",
    "docstring": "Sets the object in this container to be deleted after the specified\n        number of seconds.\n\n        The 'extra_info' parameter is included for backwards compatibility. It\n        is no longer used at all, and will not be modified with swiftclient\n        info, since swiftclient is not used any more."
  },
  {
    "code": "def CallDhclient(\n    interfaces, logger, dhclient_script=None):\n  logger.info('Enabling the Ethernet interfaces %s.', interfaces)\n  dhclient_command = ['dhclient']\n  if dhclient_script and os.path.exists(dhclient_script):\n    dhclient_command += ['-sf', dhclient_script]\n  try:\n    subprocess.check_call(dhclient_command + ['-x'] + interfaces)\n    subprocess.check_call(dhclient_command + interfaces)\n  except subprocess.CalledProcessError:\n    logger.warning('Could not enable interfaces %s.', interfaces)",
    "docstring": "Configure the network interfaces using dhclient.\n\n  Args:\n    interfaces: list of string, the output device names to enable.\n    logger: logger object, used to write to SysLog and serial port.\n    dhclient_script: string, the path to a dhclient script used by dhclient."
  },
  {
    "code": "def scale_down(self, workers, pods=None):\n        pods = pods or self._cleanup_terminated_pods(self.pods())\n        ips = set(urlparse(worker).hostname for worker in workers)\n        to_delete = [p for p in pods if p.status.pod_ip in ips]\n        if not to_delete:\n            return\n        self._delete_pods(to_delete)",
    "docstring": "Remove the pods for the requested list of workers\n\n        When scale_down is called by the _adapt async loop, the workers are\n        assumed to have been cleanly closed first and in-memory data has been\n        migrated to the remaining workers.\n\n        Note that when the worker process exits, Kubernetes leaves the pods in\n        a 'Succeeded' state that we collect here.\n\n        If some workers have not been closed, we just delete the pods with\n        matching ip addresses.\n\n        Parameters\n        ----------\n        workers: List[str] List of addresses of workers to close"
  },
  {
    "code": "def compute_mask_offsets(shard_id2num_examples):\n  total_num_examples = sum(shard_id2num_examples)\n  mask_offsets = []\n  total_num_examples = 0\n  for num_examples_in_shard in shard_id2num_examples:\n    mask_offsets.append(total_num_examples % 100)\n    total_num_examples += num_examples_in_shard\n  return mask_offsets",
    "docstring": "Return the list of offsets associated with each shards.\n\n  Args:\n    shard_id2num_examples: `list[int]`, mapping shard_id=>num_examples\n\n  Returns:\n    mask_offsets: `list[int]`, offset to skip for each of the shard"
  },
  {
    "code": "def dijkstra(graph, start, end=None):\n    D = {}\n    P = {}\n    Q = _priorityDictionary()\n    Q[start] = 0\n    for v in Q:\n        D[v] = Q[v]\n        if v == end: break\n        for w in graph.out_nbrs(v):\n            edge_id  = graph.edge_by_node(v,w)\n            vwLength = D[v] + graph.edge_data(edge_id)\n            if w in D:\n                if vwLength < D[w]:\n                    raise GraphError(\"Dijkstra: found better path to already-final vertex\")\n            elif w not in Q or vwLength < Q[w]:\n                Q[w] = vwLength\n                P[w] = v\n    return (D,P)",
    "docstring": "Dijkstra's algorithm for shortest paths\n\n    `David Eppstein, UC Irvine, 4 April 2002 <http://www.ics.uci.edu/~eppstein/161/python/>`_\n\n    `Python Cookbook Recipe <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466>`_\n\n    Find shortest paths from the  start node to all nodes nearer than or equal to the end node.\n\n    Dijkstra's algorithm is only guaranteed to work correctly when all edge lengths are positive.\n    This code does not verify this property for all edges (only the edges examined until the end\n    vertex is reached), but will correctly compute shortest paths even for some graphs with negative\n    edges, and will raise an exception if it discovers that a negative edge has caused it to make a mistake.\n\n    *Adapted to altgraph by Istvan Albert, Pennsylvania State University - June, 9 2004*"
  },
  {
    "code": "def user(session, uid, ladder_ids=None):\n    data = get_user(session, uid)\n    resp = dict(data)\n    if not ladder_ids:\n        return resp\n    resp['ladders'] = {}\n    for ladder_id in ladder_ids:\n        if isinstance(ladder_id, str):\n            ladder_id = lookup_ladder_id(ladder_id)\n        try:\n            ladder_data = dict(get_ladder(session, ladder_id, user_id=uid))\n            resp['ladders'][ladder_id] = ladder_data\n        except VooblyError:\n            pass\n    return resp",
    "docstring": "Get all possible user info by name."
  },
  {
    "code": "def get_range(self, i):\n        try:\n            m = i.match(RE_INT_ITER)\n            if m:\n                return self.get_int_range(*m.groups())\n            m = i.match(RE_CHR_ITER)\n            if m:\n                return self.get_char_range(*m.groups())\n        except Exception:\n            pass\n        return None",
    "docstring": "Check and retrieve range if value is a valid range.\n\n        Here we are looking to see if the value is series or range.\n        We look for `{1..2[..inc]}` or `{a..z[..inc]}` (negative numbers are fine)."
  },
  {
    "code": "def get_image_command(image):\n    info = docker_inspect_or_pull(image)\n    try:\n        return info['Config']['Cmd']\n    except KeyError as ke:\n        raise DockerError('Failed to inspect image: JSON result missing key {}'.format(ke))",
    "docstring": "Gets the default command for an image"
  },
  {
    "code": "def __getTemplate(template_file_name):\n        with open(template_file_name) as template_file:\n            template_raw = template_file.read()\n        template = parse(template_raw)\n        return template",
    "docstring": "Get temaplte to save the ranking.\n\n        :param template_file_name: path to the template.\n        :type template_file_name: str.\n\n        :return: template for the file.\n        :rtype: pystache's template."
  },
  {
    "code": "def getContainerName(job):\n    return '--'.join([str(job),\n                      base64.b64encode(os.urandom(9), b'-_').decode('utf-8')])\\\n                      .replace(\"'\", '').replace('\"', '').replace('_', '')",
    "docstring": "Create a random string including the job name, and return it."
  },
  {
    "code": "def _right(self):\n        left, _, width, _ = self._extents\n        return left + width",
    "docstring": "Index of column following the last column in range"
  },
  {
    "code": "def put_settings(self, using=None, **kwargs):\n        return self._get_connection(using).indices.put_settings(index=self._name, **kwargs)",
    "docstring": "Change specific index level settings in real time.\n\n        Any additional keyword arguments will be passed to\n        ``Elasticsearch.indices.put_settings`` unchanged."
  },
  {
    "code": "def add_instance(self, name, properties):\n        if name in self.__instances:\n            raise NameError(name)\n        self.__instances[name] = properties",
    "docstring": "Stores the description of a component instance. The given properties\n        are stored as is.\n\n        :param name: Instance name\n        :param properties: Instance properties\n        :raise NameError: Already known instance name"
  },
  {
    "code": "def bytes_to_int(b, order='big'):\n        if six.PY2:\n            _b = b.__class__()\n            if order != 'little':\n                b = reversed(b)\n            if not isinstance(_b, bytearray):\n                b = six.iterbytes(b)\n            return sum(c << (i * 8) for i, c in enumerate(b))\n        return int.from_bytes(b, order)",
    "docstring": "convert bytes to integer"
  },
  {
    "code": "def open_fastq(in_file):\n    if objectstore.is_remote(in_file):\n        return objectstore.open_file(in_file)\n    else:\n        return utils.open_gzipsafe(in_file)",
    "docstring": "open a fastq file, using gzip if it is gzipped"
  },
  {
    "code": "def as_string(self):\n        if type(self.instruction) is str:\n            return self.instruction\n        if self.action == \"FROM\" and not isinstance(self.command, six.string_types):\n            extra = \"\" if self.extra is NotSpecified else \" {0}\".format(self.extra)\n            return \"{0} {1}{2}\".format(self.action, self.command.from_name, extra)\n        else:\n            return \"{0} {1}\".format(self.action, self.command)",
    "docstring": "Return the command as a single string for the docker file"
  },
  {
    "code": "def update_meta_data_for_state_view(graphical_editor_view, state_v, affects_children=False, publish=True):\n    from gaphas.item import NW\n    update_meta_data_for_port(graphical_editor_view, state_v, None)\n    if affects_children:\n        update_meta_data_for_name_view(graphical_editor_view, state_v.name_view, publish=False)\n        for transition_v in state_v.get_transitions():\n            update_meta_data_for_transition_waypoints(graphical_editor_view, transition_v, None, publish=False)\n        for child_state_v in state_v.child_state_views():\n            update_meta_data_for_state_view(graphical_editor_view, child_state_v, True, publish=False)\n    rel_pos = calc_rel_pos_to_parent(graphical_editor_view.editor.canvas, state_v, state_v.handles()[NW])\n    state_v.model.set_meta_data_editor('size', (state_v.width, state_v.height))\n    state_v.model.set_meta_data_editor('rel_pos', rel_pos)\n    if publish:\n        graphical_editor_view.emit('meta_data_changed', state_v.model, \"size\", affects_children)",
    "docstring": "This method updates the meta data of a state view\n\n    :param graphical_editor_view: Graphical Editor view the change occurred in\n    :param state_v: The state view which has been changed/moved\n    :param affects_children: Whether the children of the state view have been resized or not\n    :param publish: Whether to publish the changes of the meta data"
  },
  {
    "code": "def lotus_root_geometry():\n    a_offset = np.pi / 2\n    apart = uniform_partition(a_offset,\n                              a_offset + 2 * np.pi * 366. / 360.,\n                              366)\n    d_offset = 0.35\n    dpart = uniform_partition(d_offset - 60, d_offset + 60, 2240)\n    geometry = FanBeamGeometry(apart, dpart,\n                               src_radius=540, det_radius=90)\n    return geometry",
    "docstring": "Tomographic geometry for the lotus root dataset.\n\n    Notes\n    -----\n    See the article `Tomographic X-ray data of a lotus root filled with\n    attenuating objects`_ for further information.\n\n    See Also\n    --------\n    lotus_root_geometry\n\n    References\n    ----------\n    .. _Tomographic X-ray data of a lotus root filled with attenuating objects:\n       https://arxiv.org/abs/1609.07299"
  },
  {
    "code": "def clean_up(self):\n        self.socket.close()\n        for h in self.capture_handlers:\n            h['logger'].close()",
    "docstring": "Clean up the socket and log file handles."
  },
  {
    "code": "def updateSquareFees(paymentRecord):\r\n    fees = paymentRecord.netFees\r\n    invoice = paymentRecord.invoice\r\n    invoice.fees = fees\r\n    invoice.save()\r\n    invoice.allocateFees()\r\n    return fees",
    "docstring": "The Square Checkout API does not calculate fees immediately, so this task is\r\n    called to be asynchronously run 1 minute after the initial transaction, so that\r\n    any Invoice or ExpenseItem associated with this transaction also remains accurate."
  },
  {
    "code": "def get_http_rtt(\n        url: str,\n        samples: int = 3,\n        method: str = 'head',\n        timeout: int = 1,\n) -> Optional[float]:\n    durations = []\n    for _ in range(samples):\n        try:\n            durations.append(\n                requests.request(method, url, timeout=timeout).elapsed.total_seconds(),\n            )\n        except (RequestException, OSError):\n            return None\n        except Exception as ex:\n            print(ex)\n            return None\n        sleep(.125)\n    return sum(durations) / samples",
    "docstring": "Determine the average HTTP RTT to `url` over the number of `samples`.\n    Returns `None` if the server is unreachable."
  },
  {
    "code": "def mk_dx_dy_from_geotif_layer(geotif):\n    ELLIPSOID_MAP = {'WGS84': 'WGS-84'}\n    ellipsoid = ELLIPSOID_MAP[geotif.grid_coordinates.wkt]\n    d = distance(ellipsoid=ellipsoid)\n    dx = geotif.grid_coordinates.x_axis\n    dy = geotif.grid_coordinates.y_axis\n    dX = np.zeros((dy.shape[0]-1))\n    for j in xrange(len(dX)):\n        dX[j] = d.measure((dy[j+1], dx[1]), (dy[j+1], dx[0])) * 1000\n    dY = np.zeros((dy.shape[0]-1))\n    for i in xrange(len(dY)):\n        dY[i] = d.measure((dy[i], 0), (dy[i+1], 0)) * 1000\n    return dX, dY",
    "docstring": "Extracts the change in x and y coordinates from the geotiff file. Presently\n    only supports WGS-84 files."
  },
  {
    "code": "def _set_request_auth_type_metric(self, request):\n        if 'HTTP_AUTHORIZATION' in request.META and request.META['HTTP_AUTHORIZATION']:\n            token_parts = request.META['HTTP_AUTHORIZATION'].split()\n            if len(token_parts) == 2:\n                auth_type = token_parts[0].lower()\n            else:\n                auth_type = 'other-token-type'\n        elif not hasattr(request, 'user') or not request.user:\n            auth_type = 'no-user'\n        elif not request.user.is_authenticated:\n            auth_type = 'unauthenticated'\n        else:\n            auth_type = 'session-or-unknown'\n        monitoring.set_custom_metric('request_auth_type', auth_type)",
    "docstring": "Add metric 'request_auth_type' for the authentication type used.\n\n        NOTE: This is a best guess at this point.  Possible values include:\n            no-user\n            unauthenticated\n            jwt/bearer/other-token-type\n            session-or-unknown (catch all)"
  },
  {
    "code": "def server_console_output(request, instance_id, tail_length=None):\n    nc = _nova.novaclient(request)\n    return nc.servers.get_console_output(instance_id, length=tail_length)",
    "docstring": "Gets console output of an instance."
  },
  {
    "code": "def list_from_metadata(cls, url, metadata):\n        key = cls._get_key(url)\n        metadata = Metadata(**metadata)\n        ct = cls._get_create_time(key)\n        time_buckets = cls.get_time_buckets_from_metadata(metadata)\n        return [cls(url, metadata, t, ct, key.size) for t in time_buckets]",
    "docstring": "return a list of DatalakeRecords for the url and metadata"
  },
  {
    "code": "def format_percent_field(__, prec, number, locale):\n    prec = PERCENT_DECIMAL_DIGITS if prec is None else int(prec)\n    locale = Locale.parse(locale)\n    pattern = locale.percent_formats.get(None)\n    return pattern.apply(number, locale, force_frac=(prec, prec))",
    "docstring": "Formats a percent field."
  },
  {
    "code": "def get_name(principal):\n    if isinstance(principal, pywintypes.SIDType):\n        sid_obj = principal\n    else:\n        if principal is None:\n            principal = 'S-1-0-0'\n        try:\n            sid_obj = win32security.ConvertStringSidToSid(principal)\n        except pywintypes.error:\n            try:\n                sid_obj = win32security.LookupAccountName(None, principal)[0]\n            except pywintypes.error:\n                sid_obj = principal\n    try:\n        return win32security.LookupAccountSid(None, sid_obj)[0]\n    except (pywintypes.error, TypeError) as exc:\n        message = 'Error resolving \"{0}\"'.format(principal)\n        if type(exc) == pywintypes.error:\n            win_error = win32api.FormatMessage(exc.winerror).rstrip('\\n')\n            message = '{0}: {1}'.format(message, win_error)\n        log.exception(message)\n        raise CommandExecutionError(message, exc)",
    "docstring": "Gets the name from the specified principal.\n\n    Args:\n\n        principal (str):\n            Find the Normalized name based on this. Can be a PySID object, a SID\n            string, or a user name in any capitalization.\n\n            .. note::\n                Searching based on the user name can be slow on hosts connected\n                to large Active Directory domains.\n\n    Returns:\n        str: The name that corresponds to the passed principal\n\n    Usage:\n\n    .. code-block:: python\n\n        salt.utils.win_dacl.get_name('S-1-5-32-544')\n        salt.utils.win_dacl.get_name('adminisTrators')"
  },
  {
    "code": "def areBackupsDegraded(self):\n        slow_instances = []\n        if self.acc_monitor:\n            for instance in self.instances.backupIds:\n                if self.acc_monitor.is_instance_degraded(instance):\n                    slow_instances.append(instance)\n        else:\n            for instance in self.instances.backupIds:\n                if self.is_instance_throughput_too_low(instance):\n                    slow_instances.append(instance)\n        return slow_instances",
    "docstring": "Return slow instance."
  },
  {
    "code": "async def update(self, **kwargs):\n        try:\n            self.data[self.pk] = self.pk_type(kwargs['pk'])\n            updated_obj = await self._meta.object_class().update(self.db, data=self.data)\n            if updated_obj is None:\n                raise NotFound('Object matching the given {} was not found'.format(self.pk))\n            return await updated_obj.serialize()\n        except Exception as ex:\n            logger.exception(ex)\n            raise BadRequest(ex)",
    "docstring": "Corresponds to PUT request with a resource identifier, updating a single document in the database"
  },
  {
    "code": "def replace_nones(list_, repl=-1):\n    r\n    repl_list = [\n        repl if item is None else (\n            replace_nones(item, repl) if isinstance(item, list) else item\n        )\n        for item in list_\n    ]\n    return repl_list",
    "docstring": "r\"\"\"\n    Recursively removes Nones in all lists and sublists and replaces them with\n    the repl variable\n\n    Args:\n        list_ (list):\n        repl (obj): replacement value\n\n    Returns:\n        list\n\n    CommandLine:\n        python -m utool.util_list --test-replace_nones\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_list import *  # NOQA\n        >>> # build test data\n        >>> list_ = [None, 0, 1, 2]\n        >>> repl = -1\n        >>> # execute function\n        >>> repl_list = replace_nones(list_, repl)\n        >>> # verify results\n        >>> result = str(repl_list)\n        >>> print(result)\n        [-1, 0, 1, 2]"
  },
  {
    "code": "def executable(self):\n        if not hasattr(self.local, 'conn'):\n            self.local.conn = self.engine.connect()\n        return self.local.conn",
    "docstring": "Connection against which statements will be executed."
  },
  {
    "code": "def commit(using=None):\n    if using is None:\n        for using in tldap.backend.connections:\n            connection = tldap.backend.connections[using]\n            connection.commit()\n        return\n    connection = tldap.backend.connections[using]\n    connection.commit()",
    "docstring": "Does the commit itself and resets the dirty flag."
  },
  {
    "code": "def access_view(name, **kwargs):\n    ctx = Context(**kwargs)\n    ctx.execute_action('access:view', **{\n        'unicorn': ctx.repo.create_secure_service('unicorn'),\n        'service': name,\n    })",
    "docstring": "Shows ACL for the specified service."
  },
  {
    "code": "def cudnnSetStream(handle, id):\n    status = _libcudnn.cudnnSetStream(handle, id)\n    cudnnCheckStatus(status)",
    "docstring": "Set current cuDNN library stream.\n\n    Parameters\n    ----------\n    handle : cudnnHandle\n        cuDNN context.\n    id : cudaStream\n        Stream Id."
  },
  {
    "code": "def truncate(text, length=50, ellipsis='...'):\n    text = nativestring(text)\n    return text[:length] + (text[length:] and ellipsis)",
    "docstring": "Returns a truncated version of the inputted text.\n\n    :param      text | <str>\n                length | <int>\n                ellipsis | <str>\n\n    :return     <str>"
  },
  {
    "code": "def _prepare_record(record, index, doc_type):\n        if current_app.config['INDEXER_REPLACE_REFS']:\n            data = copy.deepcopy(record.replace_refs())\n        else:\n            data = record.dumps()\n        data['_created'] = pytz.utc.localize(record.created).isoformat() \\\n            if record.created else None\n        data['_updated'] = pytz.utc.localize(record.updated).isoformat() \\\n            if record.updated else None\n        before_record_index.send(\n            current_app._get_current_object(),\n            json=data,\n            record=record,\n            index=index,\n            doc_type=doc_type,\n        )\n        return data",
    "docstring": "Prepare record data for indexing.\n\n        :param record: The record to prepare.\n        :param index: The Elasticsearch index.\n        :param doc_type: The Elasticsearch document type.\n        :returns: The record metadata."
  },
  {
    "code": "def catch_error(func):\n    import amqp\n    try:\n        import pika.exceptions\n        connect_exceptions = (\n            pika.exceptions.ConnectionClosed,\n            pika.exceptions.AMQPConnectionError,\n        )\n    except ImportError:\n        connect_exceptions = ()\n    connect_exceptions += (\n        select.error,\n        socket.error,\n        amqp.ConnectionError\n    )\n    def wrap(self, *args, **kwargs):\n        try:\n            return func(self, *args, **kwargs)\n        except connect_exceptions as e:\n            logging.error('RabbitMQ error: %r, reconnect.', e)\n            self.reconnect()\n            return func(self, *args, **kwargs)\n    return wrap",
    "docstring": "Catch errors of rabbitmq then reconnect"
  },
  {
    "code": "def _check_segment_cohesion(self):\n        if self.n_seg != len(self.segments):\n            raise ValueError(\"Length of segments must match the 'n_seg' field\")\n        for i in range(n_seg):\n            s = self.segments[i]\n            if i == 0 and self.seg_len[0] == 0:\n                for file_name in s.file_name:\n                    if file_name != '~':\n                        raise ValueError(\"Layout specification records must have all file_names named '~'\")\n            if s.fs != self.fs:\n                raise ValueError(\"The 'fs' in each segment must match the overall record's 'fs'\")\n            if s.sig_len != self.seg_len[i]:\n                raise ValueError('The signal length of segment '+str(i)+' does not match the corresponding segment length')\n            totalsig_len = totalsig_len + getattr(s, 'sig_len')",
    "docstring": "Check the cohesion of the segments field with other fields used\n        to write the record"
  },
  {
    "code": "def is_type(obj,\n            type_,\n            **kwargs):\n    if not is_iterable(type_):\n        type_ = [type_]\n    return_value = False\n    for check_for_type in type_:\n        if isinstance(check_for_type, type):\n            return_value = isinstance(obj, check_for_type)\n        elif obj.__class__.__name__ == check_for_type:\n            return_value = True\n        else:\n            return_value = _check_base_classes(obj.__class__.__bases__,\n                                               check_for_type)\n        if return_value is True:\n            break\n    return return_value",
    "docstring": "Indicate if ``obj`` is a type in ``type_``.\n\n    .. hint::\n\n      This checker is particularly useful when you want to evaluate whether\n      ``obj`` is of a particular type, but importing that type directly to use\n      in :func:`isinstance() <python:isinstance>` would cause a circular import\n      error.\n\n      To use this checker in that kind of situation, you can instead pass the\n      *name* of the type you want to check as a string in ``type_``. The checker\n      will evaluate it and see whether ``obj`` is of a type or inherits from a\n      type whose name matches the string you passed.\n\n    :param obj: The object whose type should be checked.\n    :type obj: :class:`object <python:object>`\n\n    :param type_: The type(s) to check against.\n    :type type_: :class:`type <python:type>` / iterable of :class:`type <python:type>` /\n      :class:`str <python:str>` with type name / iterable of :class:`str <python:str>`\n      with type name\n\n    :returns: ``True`` if ``obj`` is a type in ``type_``. Otherwise, ``False``.\n    :rtype: :class:`bool <python:bool>`\n\n    :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates\n      keyword parameters passed to the underlying validator"
  },
  {
    "code": "def configure_app(**kwargs):\n    sys_args = sys.argv\n    args, command, command_args = parse_args(sys_args[1:])\n    parser = OptionParser()\n    parser.add_option('--config', metavar='CONFIG')\n    (options, logan_args) = parser.parse_args(args)\n    config_path = options.config\n    logan_configure(config_path=config_path, **kwargs)",
    "docstring": "Builds up the settings using the same method as logan"
  },
  {
    "code": "def skip(self):\n        for pos, element in self.element_iter:\n            tag, class_attr = _tag_and_class_attr(element)\n            if tag == \"div\" and \"thread\" in class_attr and pos == \"end\":\n                break",
    "docstring": "Eats through the input iterator without recording the content."
  },
  {
    "code": "def set_scenario_hosts_file(self, network_name='user-net', domain_name=None):\n        log = logging.getLogger(self.cls_logger + '.set_scenario_hosts_file')\n        log.info('Scanning scenario hosts to make entries in the hosts file for network: {n}'.format(n=network_name))\n        for scenario_host in self.scenario_network_info:\n            if domain_name:\n                host_file_entry = '{r}.{d} {r}'.format(r=scenario_host['scenario_role_name'], d=domain_name)\n            else:\n                host_file_entry = scenario_host['scenario_role_name']\n            for host_network_info in scenario_host['network_info']:\n                if host_network_info['network_name'] == network_name:\n                    self.update_hosts_file(ip=host_network_info['internal_ip'], entry=host_file_entry)",
    "docstring": "Adds hosts file entries for each system in the scenario\n        for the specified network_name provided\n\n        :param network_name: (str) Name of the network to add to the hosts file\n        :param domain_name: (str) Domain name to include in the hosts file entries if provided\n        :return: None"
  },
  {
    "code": "def mark_flags_as_mutual_exclusive(flag_names, required=False,\n                                   flag_values=_flagvalues.FLAGS):\n  for flag_name in flag_names:\n    if flag_values[flag_name].default is not None:\n      warnings.warn(\n          'Flag --{} has a non-None default value. That does not make sense '\n          'with mark_flags_as_mutual_exclusive, which checks whether the '\n          'listed flags have a value other than None.'.format(flag_name))\n  def validate_mutual_exclusion(flags_dict):\n    flag_count = sum(1 for val in flags_dict.values() if val is not None)\n    if flag_count == 1 or (not required and flag_count == 0):\n      return True\n    raise _exceptions.ValidationError(\n        '{} one of ({}) must have a value other than None.'.format(\n            'Exactly' if required else 'At most', ', '.join(flag_names)))\n  register_multi_flags_validator(\n      flag_names, validate_mutual_exclusion, flag_values=flag_values)",
    "docstring": "Ensures that only one flag among flag_names is not None.\n\n  Important note: This validator checks if flag values are None, and it does not\n  distinguish between default and explicit values. Therefore, this validator\n  does not make sense when applied to flags with default values other than None,\n  including other false values (e.g. False, 0, '', []). That includes multi\n  flags with a default value of [] instead of None.\n\n  Args:\n    flag_names: [str], names of the flags.\n    required: bool. If true, exactly one of the flags must have a value other\n        than None. Otherwise, at most one of the flags can have a value other\n        than None, and it is valid for all of the flags to be None.\n    flag_values: flags.FlagValues, optional FlagValues instance where the flags\n        are defined."
  },
  {
    "code": "def _eval_target_brutal(state, ip, limit):\n        addrs = state.solver.eval_upto(ip, limit)\n        return [ (ip == addr, addr) for addr in addrs ]",
    "docstring": "The traditional way of evaluating symbolic jump targets.\n\n        :param state:   A SimState instance.\n        :param ip:      The AST of the instruction pointer to evaluate.\n        :param limit:   The maximum number of concrete IPs.\n        :return:        A list of conditions and the corresponding concrete IPs.\n        :rtype:         list"
  },
  {
    "code": "def get_extended(self, config):\n        if not config.extends or self._extended:\n            return config\n        extended_config = ContainerConfiguration()\n        for ext_name in config.extends:\n            ext_cfg_base = self._containers.get(ext_name)\n            if not ext_cfg_base:\n                raise KeyError(ext_name)\n            ext_cfg = self.get_extended(ext_cfg_base)\n            extended_config.merge_from_obj(ext_cfg)\n        extended_config.merge_from_obj(config)\n        return extended_config",
    "docstring": "Generates a configuration that includes all inherited values.\n\n        :param config: Container configuration.\n        :type config: ContainerConfiguration\n        :return: A merged (shallow) copy of all inherited configurations merged with the container configuration.\n        :rtype: ContainerConfiguration"
  },
  {
    "code": "def set_title(self, title, subtitle=''):\n        self.title = title\n        self.subtitle = subtitle",
    "docstring": "Set the title and the subtitle of the suite."
  },
  {
    "code": "def _mudraw(buffer, fmt):\n    with NamedTemporaryFile(suffix='.pdf') as tmp_in:\n        tmp_in.write(buffer)\n        tmp_in.seek(0)\n        tmp_in.flush()\n        proc = run(\n            ['mudraw', '-F', fmt, '-o', '-', tmp_in.name], stdout=PIPE, stderr=PIPE\n        )\n        if proc.stderr:\n            raise RuntimeError(proc.stderr.decode())\n        return proc.stdout",
    "docstring": "Use mupdf draw to rasterize the PDF in the memory buffer"
  },
  {
    "code": "def find_next_character(code, position, char):\n    end = LineCol(code, *position)\n    while not end.eof and end.char() in WHITESPACE:\n        end.inc()\n    if not end.eof and end.char() == char:\n        return end.tuple(), inc_tuple(end.tuple())\n    return None, None",
    "docstring": "Find next char and return its first and last positions"
  },
  {
    "code": "def list_exchanges_for_vhost(self, vhost):\n        return self._api_get('/api/exchanges/{0}'.format(\n            urllib.parse.quote_plus(vhost)\n        ))",
    "docstring": "A list of all exchanges in a given virtual host.\n\n        :param vhost: The vhost name\n        :type vhost: str"
  },
  {
    "code": "def get_project(self, name):\n        if self._cache is None:\n            result = self._get_project(name)\n        elif name in self._cache:\n            result = self._cache[name]\n        else:\n            self.clear_errors()\n            result = self._get_project(name)\n            self._cache[name] = result\n        return result",
    "docstring": "For a given project, get a dictionary mapping available versions to Distribution\n        instances.\n\n        This calls _get_project to do all the work, and just implements a caching layer on top."
  },
  {
    "code": "def open_fileswitcher(self, symbol=False):\r\n        if self.fileswitcher is not None and \\\r\n          self.fileswitcher.is_visible:\r\n            self.fileswitcher.hide()\r\n            self.fileswitcher.is_visible = False\r\n            return\r\n        if symbol:\r\n            self.fileswitcher.plugin = self.editor\r\n            self.fileswitcher.set_search_text('@')\r\n        else:\r\n            self.fileswitcher.set_search_text('')\r\n        self.fileswitcher.show()\r\n        self.fileswitcher.is_visible = True",
    "docstring": "Open file list management dialog box."
  },
  {
    "code": "def _make_ssh_forward_handler_class(self, remote_address_):\n        class Handler(_ForwardHandler):\n            remote_address = remote_address_\n            ssh_transport = self._transport\n            logger = self.logger\n        return Handler",
    "docstring": "Make SSH Handler class"
  },
  {
    "code": "def author_id_normalize_and_schema(uid, schema=None):\n    def _get_uid_normalized_in_schema(_uid, _schema):\n        regex, template = _RE_AUTHORS_UID[_schema]\n        match = regex.match(_uid)\n        if match:\n            return template.format(match.group('uid'))\n    if idutils.is_orcid(uid) and schema in (None, 'ORCID'):\n        return idutils.normalize_orcid(uid), 'ORCID'\n    if schema and schema not in _RE_AUTHORS_UID:\n        raise UnknownUIDSchema(uid)\n    if schema:\n        normalized_uid = _get_uid_normalized_in_schema(uid, schema)\n        if normalized_uid:\n            return normalized_uid, schema\n        else:\n            raise SchemaUIDConflict(schema, uid)\n    match_schema, normalized_uid = None, None\n    for candidate_schema in _RE_AUTHORS_UID:\n        candidate_uid = _get_uid_normalized_in_schema(uid, candidate_schema)\n        if candidate_uid:\n            if match_schema:\n                raise UnknownUIDSchema(uid)\n            match_schema = candidate_schema\n            normalized_uid = candidate_uid\n    if match_schema:\n        return normalized_uid, match_schema\n    raise UnknownUIDSchema(uid)",
    "docstring": "Detect and normalize an author UID schema.\n\n    Args:\n        uid (string): a UID string\n        schema (string): try to resolve to schema\n\n    Returns:\n        Tuple[string, string]: a tuple (uid, schema) where:\n        - uid: the UID normalized to comply with the id.json schema\n        - schema: a schema of the UID or *None* if not recognised\n\n    Raise:\n        UnknownUIDSchema: if UID is too little to definitively guess the schema\n        SchemaUIDConflict: if specified schema is not matching the given UID"
  },
  {
    "code": "def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None):\n        if type(rdata) is not list:\n            rdata = [rdata]\n        rrset = {\"rdata\": rdata}\n        method = \"patch\"\n        if profile:\n            rrset[\"profile\"] = profile\n            method = \"put\"\n        uri = \"/v1/zones/\" + zone_name + \"/rrsets/\" + rtype + \"/\" + owner_name\n        return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset))",
    "docstring": "Updates an existing RRSet's Rdata in the specified zone.\n\n        Arguments:\n        zone_name -- The zone that contains the RRSet.  The trailing dot is optional.\n        rtype -- The type of the RRSet.  This can be numeric (1) or\n                 if a well-known name is defined for the type (A), you can use it instead.\n        owner_name -- The owner name for the RRSet.\n                      If no trailing dot is supplied, the owner_name is assumed to be relative (foo).\n                      If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.)\n        rdata -- The updated BIND data for the RRSet as a string.\n                 If there is a single resource record in the RRSet, you can pass in the single string.\n                 If there are multiple resource records  in this RRSet, pass in a list of strings.\n        profile -- The profile info if this is updating a resource pool"
  },
  {
    "code": "def normal_distribution(mean, variance,\n                        minimum=None, maximum=None, weight_count=23):\n    standard_deviation = math.sqrt(variance)\n    min_x = (standard_deviation * -5) + mean\n    max_x = (standard_deviation * 5) + mean\n    step = (max_x - min_x) / weight_count\n    current_x = min_x\n    weights = []\n    while current_x < max_x:\n        weights.append(\n            (current_x, _normal_function(current_x, mean, variance))\n        )\n        current_x += step\n    if minimum is not None or maximum is not None:\n        return bound_weights(weights, minimum, maximum)\n    else:\n        return weights",
    "docstring": "Return a list of weights approximating a normal distribution.\n\n    Args:\n        mean (float): The mean of the distribution\n        variance (float): The variance of the distribution\n        minimum (float): The minimum outcome possible to\n            bound the output distribution to\n        maximum (float): The maximum outcome possible to\n            bound the output distribution to\n        weight_count (int): The number of weights that will\n            be used to approximate the distribution\n\n    Returns:\n        list: a list of ``(float, float)`` weight tuples\n        approximating a normal distribution.\n\n    Raises:\n        ValueError: ``if maximum < minimum``\n        TypeError: if both ``minimum`` and ``maximum`` are ``None``\n\n    Example:\n        >>> weights = normal_distribution(10, 3,\n        ...                               minimum=0, maximum=20,\n        ...                               weight_count=5)\n        >>> rounded_weights = [(round(value, 2), round(strength, 2))\n        ...                    for value, strength in weights]\n        >>> rounded_weights\n        [(1.34, 0.0), (4.8, 0.0), (8.27, 0.14), (11.73, 0.14), (15.2, 0.0)]"
  },
  {
    "code": "def resource_name(cls):\n        if cls.__name__ == \"NURESTRootObject\" or cls.__name__ == \"NURESTObject\":\n            return \"Not Implemented\"\n        if cls.__resource_name__ is None:\n            raise NotImplementedError('%s has no defined resource name. Implement resource_name property first.' % cls)\n        return cls.__resource_name__",
    "docstring": "Represents the resource name"
  },
  {
    "code": "def subnet_distance(self):\n        return [(Element.from_href(entry.get('subnet')), entry.get('distance'))\n                for entry in self.data.get('distance_entry')]",
    "docstring": "Specific subnet administrative distances\n\n        :return: list of tuple (subnet, distance)"
  },
  {
    "code": "def _move_mount(robot, mount, point):\n    carriage = robot._actuators[mount]['carriage']\n    robot.poses = carriage.home(robot.poses)\n    other_mount = 'left' if mount == 'right' else 'right'\n    robot.poses = robot._actuators[other_mount]['carriage'].home(robot.poses)\n    robot.gantry.move(\n        robot.poses, x=point[0], y=point[1])\n    robot.poses = carriage.move(\n        robot.poses, z=point[2])\n    x, y, _ = tuple(\n        pose_tracker.absolute(\n            robot.poses, robot._actuators[mount]['carriage']))\n    _, _, z = tuple(\n        pose_tracker.absolute(\n            robot.poses, robot.gantry))\n    new_position = (x, y, z)\n    return \"Move complete. New position: {}\".format(new_position)",
    "docstring": "The carriage moves the mount in the Z axis, and the gantry moves in X and Y\n\n    Mount movements do not have the same protections calculated in to an\n    existing `move` command like Pipette does, so the safest thing is to home\n    the Z axis, then move in X and Y, then move down to the specified Z height"
  },
  {
    "code": "def set_network_settings(self, mtu, sock_snd, sock_rcv, tcp_wnd_snd, tcp_wnd_rcv):\n        if not isinstance(mtu, baseinteger):\n            raise TypeError(\"mtu can only be an instance of type baseinteger\")\n        if not isinstance(sock_snd, baseinteger):\n            raise TypeError(\"sock_snd can only be an instance of type baseinteger\")\n        if not isinstance(sock_rcv, baseinteger):\n            raise TypeError(\"sock_rcv can only be an instance of type baseinteger\")\n        if not isinstance(tcp_wnd_snd, baseinteger):\n            raise TypeError(\"tcp_wnd_snd can only be an instance of type baseinteger\")\n        if not isinstance(tcp_wnd_rcv, baseinteger):\n            raise TypeError(\"tcp_wnd_rcv can only be an instance of type baseinteger\")\n        self._call(\"setNetworkSettings\",\n                     in_p=[mtu, sock_snd, sock_rcv, tcp_wnd_snd, tcp_wnd_rcv])",
    "docstring": "Sets network configuration of the NAT engine.\n\n        in mtu of type int\n            MTU (maximum transmission unit) of the NAT engine in bytes.\n\n        in sock_snd of type int\n            Capacity of the socket send buffer in bytes when creating a new socket.\n\n        in sock_rcv of type int\n            Capacity of the socket receive buffer in bytes when creating a new socket.\n\n        in tcp_wnd_snd of type int\n            Initial size of the NAT engine's sending TCP window in bytes when\n            establishing a new TCP connection.\n\n        in tcp_wnd_rcv of type int\n            Initial size of the NAT engine's receiving TCP window in bytes when\n            establishing a new TCP connection."
  },
  {
    "code": "def operator_driven(drain_timeout=_DEFAULT_DRAIN, reset_timeout=_DEFAULT_RESET, max_consecutive_attempts=_DEFAULT_ATTEMPTS):\n        return ConsistentRegionConfig(trigger=ConsistentRegionConfig.Trigger.OPERATOR_DRIVEN, drain_timeout=drain_timeout, reset_timeout=reset_timeout, max_consecutive_attempts=max_consecutive_attempts)",
    "docstring": "Define an operator-driven consistent region configuration.  \n        The source operator triggers drain and checkpoint cycles for the region.\n\n        Args:\n          drain_timeout: The drain timeout, as either a :py:class:`datetime.timedelta` value or the number of seconds as a `float`.  If not specified, the default value is 180 seconds.\n          reset_timeout: The reset timeout, as either a :py:class:`datetime.timedelta` value or the number of seconds as a `float`.  If not specified, the default value is 180 seconds.\n          max_consecutive_attempts(int): The maximum number of consecutive attempts to reset the region.  This must be an integer value between 1 and 2147483647, inclusive.  If not specified, the default value is 5.\n\n        Returns:\n          ConsistentRegionConfig: the configuration."
  },
  {
    "code": "def get_field_label(self, trans, field):\n        try:\n            object_field_label = trans._meta.get_field_by_name(field)[0].verbose_name\n        except Exception:\n            try:\n                object_field_label = self.sender._meta.get_field_by_name(field)[0].verbose_name\n            except Exception:\n                object_field_label = field\n        return object_field_label",
    "docstring": "Get the field label from the _meta api of the model\n\n        :param trans:\n        :param field:\n        :return:"
  },
  {
    "code": "def availableRoles(self):\n        if not hasattr(self.instructor,'instructorprivatelessondetails'):\n            return []\n        return [\n            [x.id,x.name] for x in\n            self.instructor.instructorprivatelessondetails.roles.all()\n        ]",
    "docstring": "Some instructors only offer private lessons for certain roles, so we should only allow booking\n        for the roles that have been selected for the instructor."
  },
  {
    "code": "def addPhenotypeAssociationSet(self, phenotypeAssociationSet):\n        id_ = phenotypeAssociationSet.getId()\n        self._phenotypeAssociationSetIdMap[id_] = phenotypeAssociationSet\n        self._phenotypeAssociationSetNameMap[\n            phenotypeAssociationSet.getLocalId()] = phenotypeAssociationSet\n        self._phenotypeAssociationSetIds.append(id_)",
    "docstring": "Adds the specified g2p association set to this backend."
  },
  {
    "code": "def sar(self, count):\n        count = operator.index(count)\n        if count < 0:\n            raise ValueError('negative shift')\n        if count > self._width:\n            count = self._width\n        return BinWord(self._width, self.to_sint() >> count, trunc=True)",
    "docstring": "Performs an arithmetic right-shift of a BinWord by the given number\n        of bits.  Bits shifted out of the word are lost.  The word is\n        filled on the left with copies of the top bit.\n\n        The shift count can be an arbitrary non-negative number, including\n        counts larger than the word (a word filled with copies of the sign bit\n        is returned in this case)."
  },
  {
    "code": "def markov_blanket(self, beta, alpha):\n        likelihood_blanket = self.likelihood_markov_blanket(beta)\n        state_blanket = self.state_likelihood_markov_blanket(beta,alpha,0)\n        for i in range(self.state_no-1):\n            likelihood_blanket = np.append(likelihood_blanket,self.likelihood_markov_blanket(beta))\n            state_blanket = np.append(state_blanket,self.state_likelihood_markov_blanket(beta,alpha,i+1))\n        return likelihood_blanket + state_blanket",
    "docstring": "Creates total Markov blanket for states\n\n        Parameters\n        ----------\n        beta : np.array\n            Contains untransformed starting values for latent variables\n\n        alpha : np.array\n            A vector of states\n\n        Returns\n        ----------\n        Markov blanket for states"
  },
  {
    "code": "def add_watch_callback(self, *args, **kwargs):\n        try:\n            return self.watcher.add_callback(*args, **kwargs)\n        except queue.Empty:\n            raise exceptions.WatchTimedOut()",
    "docstring": "Watch a key or range of keys and call a callback on every event.\n\n        If timeout was declared during the client initialization and\n        the watch cannot be created during that time the method raises\n        a ``WatchTimedOut`` exception.\n\n        :param key: key to watch\n        :param callback: callback function\n\n        :returns: watch_id. Later it could be used for cancelling watch."
  },
  {
    "code": "def extract_scalar_reward(value, scalar_key='default'):\n    if isinstance(value, float) or isinstance(value, int):\n        reward = value\n    elif isinstance(value, dict) and scalar_key in value and isinstance(value[scalar_key], (float, int)):\n        reward = value[scalar_key]\n    else:\n        raise RuntimeError('Incorrect final result: the final result should be float/int, or a dict which has a key named \"default\" whose value is float/int.')\n    return reward",
    "docstring": "Extract scalar reward from trial result.\n\n    Raises\n    ------\n    RuntimeError\n        Incorrect final result: the final result should be float/int,\n        or a dict which has a key named \"default\" whose value is float/int."
  },
  {
    "code": "def package_info(pkg_name):\n    indent = \"  \"\n    for config, _ in _iter_packages():\n        if pkg_name == config[\"name\"]:\n            print(\"Package:\", pkg_name)\n            print(indent, \"Platform:\", config[\"platform\"])\n            print(indent, \"Version:\", config[\"version\"])\n            print(indent, \"Path:\", config[\"path\"])\n            print(indent, \"Worlds:\")\n            for world in config[\"maps\"]:\n                world_info(world[\"name\"], world_config=world, initial_indent=\"    \")",
    "docstring": "Prints the information of a package.\n\n    Args:\n        pkg_name (str): The name of the desired package to get information"
  },
  {
    "code": "def resolve_label_conflict(mapping, old_labels=None, new_labels=None):\n    if old_labels is None:\n        old_labels = set(mapping)\n    if new_labels is None:\n        new_labels = set(itervalues(mapping))\n    counter = itertools.count(2 * len(mapping))\n    old_to_intermediate = {}\n    intermediate_to_new = {}\n    for old, new in iteritems(mapping):\n        if old == new:\n            continue\n        if old in new_labels or new in old_labels:\n            lbl = next(counter)\n            while lbl in new_labels or lbl in old_labels:\n                lbl = next(counter)\n            old_to_intermediate[old] = lbl\n            intermediate_to_new[lbl] = new\n        else:\n            old_to_intermediate[old] = new\n    return old_to_intermediate, intermediate_to_new",
    "docstring": "Resolve a self-labeling conflict by creating an intermediate labeling.\n\n    Args:\n        mapping (dict):\n            A dict mapping the current variable labels to new ones.\n\n        old_labels (set, optional, default=None):\n            The keys of mapping. Can be passed in for performance reasons. These are not checked.\n\n        new_labels (set, optional, default=None):\n            The values of mapping. Can be passed in for performance reasons. These are not checked.\n\n    Returns:\n        tuple: A 2-tuple containing:\n\n            dict: A map from the keys of mapping to an intermediate labeling\n\n            dict: A map from the intermediate labeling to the values of mapping."
  },
  {
    "code": "def create_admin(app, appbuilder, username, firstname, lastname, email, password):\n    auth_type = {\n        c.AUTH_DB: \"Database Authentications\",\n        c.AUTH_OID: \"OpenID Authentication\",\n        c.AUTH_LDAP: \"LDAP Authentication\",\n        c.AUTH_REMOTE_USER: \"WebServer REMOTE_USER Authentication\",\n        c.AUTH_OAUTH: \"OAuth Authentication\",\n    }\n    _appbuilder = import_application(app, appbuilder)\n    click.echo(\n        click.style(\n            \"Recognized {0}.\".format(\n                auth_type.get(_appbuilder.sm.auth_type, \"No Auth method\")\n            ),\n            fg=\"green\",\n        )\n    )\n    role_admin = _appbuilder.sm.find_role(_appbuilder.sm.auth_role_admin)\n    user = _appbuilder.sm.add_user(\n        username, firstname, lastname, email, role_admin, password\n    )\n    if user:\n        click.echo(click.style(\"Admin User {0} created.\".format(username), fg=\"green\"))\n    else:\n        click.echo(click.style(\"No user created an error occured\", fg=\"red\"))",
    "docstring": "Creates an admin user"
  },
  {
    "code": "def add(parent, idx, value):\n  if isinstance(parent, dict):\n    if idx in parent:\n      raise JSONPatchError(\"Item already exists\")\n    parent[idx] = value\n  elif isinstance(parent, list):\n    if idx == \"\" or idx == \"~\":\n      parent.append(value)\n    else:\n      parent.insert(int(idx), value)\n  else:\n    raise JSONPathError(\"Invalid path for operation\")",
    "docstring": "Add a value to a dict."
  },
  {
    "code": "def get_resources_by_search(self, resource_query, resource_search):\n        if not self._can('search'):\n            raise PermissionDenied()\n        return self._provider_session.get_resources_by_search(resource_query, resource_search)",
    "docstring": "Pass through to provider ResourceSearchSession.get_resources_by_search"
  },
  {
    "code": "def copy_plan(modeladmin, request, queryset):\n    for plan in queryset:\n        plan_copy = deepcopy(plan)\n        plan_copy.id = None\n        plan_copy.available = False\n        plan_copy.default = False\n        plan_copy.created = None\n        plan_copy.save(force_insert=True)\n        for pricing in plan.planpricing_set.all():\n            pricing.id = None\n            pricing.plan = plan_copy\n            pricing.save(force_insert=True)\n        for quota in plan.planquota_set.all():\n            quota.id = None\n            quota.plan = plan_copy\n            quota.save(force_insert=True)",
    "docstring": "Admin command for duplicating plans preserving quotas and pricings."
  },
  {
    "code": "def neg_int(i):\n    try:\n        if isinstance(i, string_types):\n            i = int(i)\n        if not isinstance(i, int) or i > 0:\n            raise Exception()\n    except:\n        raise ValueError(\"Not a negative integer\")\n    return i",
    "docstring": "Simple negative integer validation."
  },
  {
    "code": "def default(cls):\n        \"Make the current foreground color the default.\"\n        wAttributes = cls._get_text_attributes()\n        wAttributes &= ~win32.FOREGROUND_MASK\n        wAttributes |=  win32.FOREGROUND_GREY\n        wAttributes &= ~win32.FOREGROUND_INTENSITY\n        cls._set_text_attributes(wAttributes)",
    "docstring": "Make the current foreground color the default."
  },
  {
    "code": "def _norm(self, x):\n    return tf.sqrt(tf.reduce_sum(tf.square(x), keepdims=True, axis=-1) + 1e-7)",
    "docstring": "Compute the safe norm."
  },
  {
    "code": "def copyHiddenToContext(self):\n        for item in list(self.contextLayers.items()):\n            if self.verbosity > 2: print('Hidden layer: ', self.getLayer(item[0]).activation)\n            if self.verbosity > 2: print('Context layer before copy: ', item[1].activation)\n            item[1].copyActivations(self.getLayer(item[0]).activation)\n            if self.verbosity > 2: print('Context layer after copy: ', item[1].activation)",
    "docstring": "Uses key to identify the hidden layer associated with each\n        layer in the self.contextLayers dictionary."
  },
  {
    "code": "async def on_raw_cap_ls(self, params):\n        to_request = set()\n        for capab in params[0].split():\n            capab, value = self._capability_normalize(capab)\n            if capab in self._capabilities:\n                continue\n            attr = 'on_capability_' + pydle.protocol.identifierify(capab) + '_available'\n            supported = (await getattr(self, attr)(value)) if hasattr(self, attr) else False\n            if supported:\n                if isinstance(supported, str):\n                    to_request.add(capab + CAPABILITY_VALUE_DIVIDER + supported)\n                else:\n                    to_request.add(capab)\n            else:\n                self._capabilities[capab] = False\n        if to_request:\n            self._capabilities_requested.update(x.split(CAPABILITY_VALUE_DIVIDER, 1)[0] for x in to_request)\n            await self.rawmsg('CAP', 'REQ', ' '.join(to_request))\n        else:\n            await self.rawmsg('CAP', 'END')",
    "docstring": "Update capability mapping. Request capabilities."
  },
  {
    "code": "def app1(self):\n        for m in self._markers:\n            if m.marker_code == JPEG_MARKER_CODE.APP1:\n                return m\n        raise KeyError('no APP1 marker in image')",
    "docstring": "First APP1 marker in image markers."
  },
  {
    "code": "def bool(name, execute_bool=True, default=None):\n    def wrapped(func):\n        @functools.wraps(func)\n        def _decorator(*args, **kwargs):\n            if core.isset(name) and core.bool(name) == execute_bool:\n                return func(*args, **kwargs)\n            elif default is not None and default == execute_bool:\n                return func(*args, **kwargs)\n        return _decorator\n    return wrapped",
    "docstring": "Only execute the function if the boolean variable is set.\n\n    Args:\n        name: The name of the environment variable\n        execute_bool: The boolean value to execute the function on\n        default: The default value if the environment variable is not set (respects `execute_bool`)\n\n    Returns:\n        The function return value or `None` if the function was skipped."
  },
  {
    "code": "def remove_pointer(type_):\n    nake_type = remove_alias(type_)\n    if not is_pointer(nake_type):\n        return type_\n    elif isinstance(nake_type, cpptypes.volatile_t) and \\\n            isinstance(nake_type.base, cpptypes.pointer_t):\n        return cpptypes.volatile_t(nake_type.base.base)\n    elif isinstance(nake_type, cpptypes.const_t) and \\\n            isinstance(nake_type.base, cpptypes.pointer_t):\n        return cpptypes.const_t(nake_type.base.base)\n    elif isinstance(nake_type, cpptypes.volatile_t) \\\n            and isinstance(nake_type.base, cpptypes.const_t) \\\n            and isinstance(nake_type.base.base, cpptypes.pointer_t):\n        return (\n            cpptypes.volatile_t(cpptypes.const_t(nake_type.base.base.base))\n        )\n    return nake_type.base",
    "docstring": "removes pointer from the type definition\n\n    If type is not pointer type, it will be returned as is."
  },
  {
    "code": "def get(self, run_id):\n        config = _read_json(_path_to_config(self.directory, run_id))\n        run = _read_json(_path_to_run(self.directory, run_id))\n        try:\n            info = _read_json(_path_to_info(self.directory, run_id))\n        except IOError:\n            info = {}\n        return _create_run(run_id, run, config, info)",
    "docstring": "Return the run associated with a particular `run_id`.\n\n        :param run_id:\n        :return: dict\n        :raises FileNotFoundError"
  },
  {
    "code": "def total_weight(self):\n        weights = self._raw_weights()\n        if weights.shape[1] == 0:\n            return 0.0\n        elif weights.shape[1] < self._ntaps:\n            return np.sum(np.mean(weights, axis=1))\n        else:\n            return self._filter_coeffs.dot(np.sum(weights, axis=0))",
    "docstring": "Read a weight from the sensor in grams.\n\n        Returns\n        -------\n        weight : float\n            The sensor weight in grams."
  },
  {
    "code": "def derivative(self, point):\n        r\n        point = self.domain.element(point)\n        diff = point - self.vector\n        dist = self.vector.dist(point)\n        if dist == 0:\n            raise ValueError('not differentiable at the reference vector {!r}'\n                             ''.format(self.vector))\n        return InnerProductOperator(diff / dist)",
    "docstring": "r\"\"\"The derivative operator.\n\n            ``DistOperator(y).derivative(z)(x) ==\n            ((y - z) / y.dist(z)).inner(x)``\n\n        This is only applicable in inner product spaces.\n\n        Parameters\n        ----------\n        x : `domain` `element-like`\n            Point in which to take the derivative.\n\n        Returns\n        -------\n        derivative : `InnerProductOperator`\n\n        Raises\n        ------\n        ValueError\n            If ``point == self.vector``, in which case the derivative is not\n            well defined in the Frechet sense.\n\n        Notes\n        -----\n        The derivative cannot be written in a general sense except in Hilbert\n        spaces, in which case it is given by\n\n        .. math::\n            (D d(\\cdot, y))(z)(x) = \\langle (y-z) / d(y, z), x \\rangle\n\n        Examples\n        --------\n        >>> r2 = odl.rn(2)\n        >>> x = r2.element([1, 1])\n        >>> op = DistOperator(x)\n        >>> derivative = op.derivative([2, 1])\n        >>> derivative([1, 0])\n        1.0"
  },
  {
    "code": "def insert_fft_option_group(parser):\n    fft_group = parser.add_argument_group(\"Options for selecting the\"\n                                          \" FFT backend and controlling its performance\"\n                                          \" in this program.\")\n    fft_group.add_argument(\"--fft-backends\",\n                      help=\"Preference list of the FFT backends. \"\n                           \"Choices are: \\n\" + str(get_backend_names()),\n                      nargs='*', default=[])\n    for backend in get_backend_modules():\n        try:\n            backend.insert_fft_options(fft_group)\n        except AttributeError:\n            pass",
    "docstring": "Adds the options used to choose an FFT backend. This should be used\n    if your program supports the ability to select the FFT backend; otherwise\n    you may simply call the fft and ifft functions and rely on default\n    choices.  This function will also attempt to add any options exported\n    by available backends through a function called insert_fft_options.\n    These submodule functions should take the fft_group object as argument.\n\n    Parameters\n    ----------\n    parser : object\n        OptionParser instance"
  },
  {
    "code": "def get_id(self, details=False):\n        res = {\n            \"alignak\": getattr(self, 'alignak_name', 'unknown'),\n            \"type\": getattr(self, 'type', 'unknown'),\n            \"name\": getattr(self, 'name', 'unknown'),\n            \"version\": VERSION\n        }\n        return res",
    "docstring": "Get daemon identification information\n\n        :return: A dict with the following structure\n        ::\n            {\n                \"alignak\": selfAlignak instance name\n                \"type\": daemon type\n                \"name\": daemon name\n                \"version\": Alignak version\n            }\n\n        :rtype: dict"
  },
  {
    "code": "def parse_s2bs(s2bs):\n    s2b = {}\n    for s in s2bs:\n        for line in open(s):\n            line = line.strip().split('\\t')\n            s, b = line[0], line[1]\n            s2b[s] = b\n    return s2b",
    "docstring": "convert s2b files to dictionary"
  },
  {
    "code": "def options(self, group, target=None, defaults=True):\n        if target is None:\n            target = self.path\n        if self.groups.get(group, None) is None:\n            return None\n        if self.parent is None and target and (self is not Store.options()) and defaults:\n            root_name = self.__class__.__name__\n            replacement = root_name + ('' if len(target) == len(root_name) else '.')\n            option_key = target.replace(replacement,'')\n            match = Store.options().find(option_key)\n            if match is not Store.options():\n                return match.options(group)\n            else:\n                return Options()\n        elif self.parent is None:\n            return self.groups[group]\n        parent_opts = self.parent.options(group,target, defaults)\n        return Options(**dict(parent_opts.kwargs, **self.groups[group].kwargs))",
    "docstring": "Using inheritance up to the root, get the complete Options\n        object for the given node and the specified group."
  },
  {
    "code": "def set_add(self, key, value, create=False, **kwargs):\n        op = SD.array_addunique('', value)\n        try:\n            sdres = self.mutate_in(key, op, **kwargs)\n            return self._wrap_dsop(sdres)\n        except E.SubdocPathExistsError:\n            pass",
    "docstring": "Add an item to a set if the item does not yet exist.\n\n        :param key: The document ID\n        :param value: Value to add\n        :param create: Create the set if it does not exist\n        :param kwargs: Arguments to :meth:`mutate_in`\n        :return: A :class:`~.OperationResult` if the item was added,\n        :raise: :cb_exc:`NotFoundError` if the document does not exist\n            and `create` was not specified.\n\n        .. seealso:: :meth:`map_add`"
  },
  {
    "code": "def _format_ret(self, full_ret):\n        ret = {}\n        out = ''\n        retcode = 0\n        for key, data in six.iteritems(full_ret):\n            ret[key] = data['ret']\n            if 'out' in data:\n                out = data['out']\n            ret_retcode = self._get_retcode(data)\n            if ret_retcode > retcode:\n                retcode = ret_retcode\n        return ret, out, retcode",
    "docstring": "Take the full return data and format it to simple output"
  },
  {
    "code": "def _add_column(self, label, field):\n        assert self.headers is not None\n        cols = 0\n        if len(self._headers) > 0:\n            cols = max([int(c.cell.col) for c in self._headers])\n        new_col = cols + 1\n        if int(self._ws.col_count.text) < new_col:\n            self._ws.col_count.text = str(new_col)\n            self._update_metadata()\n        cell = self._service.UpdateCell(1, new_col, label,\n                                        self._ss.id, self.id)\n        self._headers.append(cell)",
    "docstring": "Add a new column to the table. It will have the header\n        text ``label``, but for data inserts and queries, the\n        ``field`` name must be used. If necessary, this will expand\n        the size of the sheet itself to allow for the new column."
  },
  {
    "code": "def set_debug(self, debug=1):\n        self._check_if_ready()\n        self.debug = debug\n        self.main_loop.debug = debug",
    "docstring": "Set the debug level.\n\n        :type  debug: int\n        :param debug: The debug level."
  },
  {
    "code": "def add_codedValue(self, name, code):\n        if self._codedValues is None:\n            self._codedValues = []\n        self._codedValues.append(\n            {\"name\": name, \"code\": code}\n        )",
    "docstring": "adds a value to the coded value list"
  },
  {
    "code": "def parse_strike_dip(strike, dip):\n    strike = parse_azimuth(strike)\n    dip, direction = split_trailing_letters(dip)\n    if direction is not None:\n        expected_direc = strike + 90\n        if opposite_end(expected_direc, direction):\n            strike += 180\n    if strike > 360:\n        strike -= 360\n    return strike, dip",
    "docstring": "Parses strings of strike and dip and returns strike and dip measurements\n    following the right-hand-rule.\n\n    Dip directions are parsed, and if the measurement does not follow the\n    right-hand-rule, the opposite end of the strike measurement is returned.\n\n    Accepts either quadrant-formatted or azimuth-formatted strikes.\n\n    For example, this would convert a strike of \"N30E\" and a dip of \"45NW\" to\n    a strike of 210 and a dip of 45.\n\n    Parameters\n    ----------\n    strike : string\n        A strike measurement. May be in azimuth or quadrant format.\n    dip : string\n        The dip angle and direction of a plane.\n\n    Returns\n    -------\n    azi : float\n        Azimuth in degrees of the strike of the plane with dip direction\n        indicated following the right-hand-rule.\n    dip : float\n        Dip of the plane in degrees."
  },
  {
    "code": "def get_data_by_slug(model, slug, kind='', **kwargs):\n    instance = get_instance_by_slug(model, slug, **kwargs)\n    if not instance:\n        return\n    return ins2dict(instance, kind)",
    "docstring": "Get instance data by slug and kind. Raise 404 Not Found if there is no data.\n\n    This function requires model has a `slug` column.\n\n    :param model: a string, model name in rio.models\n    :param slug: a string used to query by `slug`. This requires there is a\n                 slug field in model definition.\n    :param kind: a string specified which kind of dict tranformer should be called.\n    :return: a dict or None."
  },
  {
    "code": "def tee2(process, filter):\n    while True:\n        line = process.stderr.readline()\n        if line:\n            if sys.version_info[0] >= 3:\n                line = decode(line)\n            stripped_line = line.rstrip()\n            if filter(stripped_line):\n                sys.stderr.write(line)\n        elif process.returncode is not None:\n            process.stderr.close()\n            break",
    "docstring": "Read lines from process.stderr and echo them to sys.stderr.\n\n    The 'filter' is a callable which is invoked for every line,\n    receiving the line as argument. If the filter returns True, the\n    line is echoed to sys.stderr."
  },
  {
    "code": "def get_symmetry_from_database(hall_number):\n    _set_no_error()\n    rotations = np.zeros((192, 3, 3), dtype='intc')\n    translations = np.zeros((192, 3), dtype='double')\n    num_sym = spg.symmetry_from_database(rotations, translations, hall_number)\n    _set_error_message()\n    if num_sym is None:\n        return None\n    else:\n        return {'rotations':\n                np.array(rotations[:num_sym], dtype='intc', order='C'),\n                'translations':\n                np.array(translations[:num_sym], dtype='double', order='C')}",
    "docstring": "Return symmetry operations corresponding to a Hall symbol.\n\n    The Hall symbol is given by the serial number in between 1 and 530.\n    The symmetry operations are given by a dictionary whose keys are\n    'rotations' and 'translations'.\n    If it fails, None is returned."
  },
  {
    "code": "def _phi_node_contains(self, phi_variable, variable):\n        if self.variable_manager[self.function.addr].is_phi_variable(phi_variable):\n            return variable in self.variable_manager[self.function.addr].get_phi_subvariables(phi_variable)\n        return False",
    "docstring": "Checks if `phi_variable` is a phi variable, and if it contains `variable` as a sub-variable.\n\n        :param phi_variable:\n        :param variable:\n        :return:"
  },
  {
    "code": "def save_workspace(self, filename=''):\n        r\n        if filename == '':\n            filename = 'workspace' + '_' + time.strftime('%Y%b%d_%H%M%p')\n        filename = self._parse_filename(filename=filename, ext='pnm')\n        d = {}\n        for sim in self.values():\n            d[sim.name] = sim\n        with open(filename, 'wb') as f:\n            pickle.dump(d, f)",
    "docstring": "r\"\"\"\n        Saves all the current Projects to a 'pnm' file\n\n        Parameters\n        ----------\n        filename : string, optional\n            If no filename is given, a name is genrated using the current\n            time and date. See Notes for more information on valid file names.\n\n        See Also\n        --------\n        save_project\n\n        Notes\n        -----\n        The filename can be a string such as 'saved_file.pnm'.  The string can\n        include absolute path such as 'C:\\networks\\saved_file.pnm', or can\n        be a relative path such as '..\\..\\saved_file.pnm', which will look\n        2 directories above the current working directory.  It can also be a\n        path object object such as that produced by ``pathlib`` or\n        ``os.path`` in the Python standard library."
  },
  {
    "code": "def _output_validators(self):\n        if self._walk_for_type('Boolean'):\n            print(\"from .validators import boolean\")\n        if self._walk_for_type('Integer'):\n            print(\"from .validators import integer\")\n        vlist = self.override.get_validator_list()\n        for override in vlist:\n            if override.startswith('common/'):\n                override = override.lstrip('common/')\n                filename = \"validators\"\n            else:\n                filename = \"%s_validators\" % self.filename\n            print(\"from .%s import %s\" % (filename, override))",
    "docstring": "Output common validator types based on usage."
  },
  {
    "code": "def create_working_dir(config, prefix):\n    basepath = config.get(\"Execution\", \"directory\")\n    if not prefix:\n        prefix = 'opensubmit'\n    finalpath = tempfile.mkdtemp(prefix=prefix + '_', dir=basepath)\n    if not finalpath.endswith(os.sep):\n        finalpath += os.sep\n    logger.debug(\"Created fresh working directory at {0}.\".format(finalpath))\n    return finalpath",
    "docstring": "Create a fresh temporary directory, based on the fiven prefix.\n        Returns the new path."
  },
  {
    "code": "def ball_pick(n, d, rng=None):\n    def valid(r):\n        return vector_mag_sq(r) < 1.0\n    return rejection_pick(L=2.0, n=n, d=d, valid=valid, rng=rng)",
    "docstring": "Return cartesian vectors uniformly picked on the unit ball in an\n    arbitrary number of dimensions.\n\n    The unit ball is the space enclosed by the unit sphere.\n\n    The picking is done by rejection sampling in the unit cube.\n\n    In 3-dimensional space, the fraction `\\pi / 6 \\sim 0.52` points are valid.\n\n    Parameters\n    ----------\n    n: integer\n        Number of points to return.\n    d: integer\n        Number of dimensions of the space in which the ball lives\n\n    Returns\n    -------\n    r: array, shape (n, d)\n        Sample cartesian vectors."
  },
  {
    "code": "def update_colors(self, colors):\n        colors = np.array(colors, dtype=np.uint8)\n        self._vbo_c.set_data(colors)\n        self._vbo_c.unbind()",
    "docstring": "Update the colors"
  },
  {
    "code": "def run(self):\n        log.debug(\"Starting Kafka producer I/O thread.\")\n        while self._running:\n            try:\n                self.run_once()\n            except Exception:\n                log.exception(\"Uncaught error in kafka producer I/O thread\")\n        log.debug(\"Beginning shutdown of Kafka producer I/O thread, sending\"\n                  \" remaining records.\")\n        while (not self._force_close\n               and (self._accumulator.has_unsent()\n                    or self._client.in_flight_request_count() > 0)):\n            try:\n                self.run_once()\n            except Exception:\n                log.exception(\"Uncaught error in kafka producer I/O thread\")\n        if self._force_close:\n            self._accumulator.abort_incomplete_batches()\n        try:\n            self._client.close()\n        except Exception:\n            log.exception(\"Failed to close network client\")\n        log.debug(\"Shutdown of Kafka producer I/O thread has completed.\")",
    "docstring": "The main run loop for the sender thread."
  },
  {
    "code": "def arg_bool(name, default=False):\n    v = request.args.get(name, '')\n    if not len(v):\n        return default\n    return v in BOOL_TRUISH",
    "docstring": "Fetch a query argument, as a boolean."
  },
  {
    "code": "def files_in_dir(dirpath, wildcard=\"*\", startpath=None):\n    import glob\n    filelist = []\n    if startpath is not None:\n        completedirpath = os.path.join(startpath, dirpath)\n    else:\n        completedirpath = dirpath\n    if os.path.exists(completedirpath):\n        logger.info('completedirpath = ' + completedirpath)\n    else:\n        logger.error('Wrong path: ' + completedirpath)\n        raise Exception('Wrong path : ' + completedirpath)\n    for infile in glob.glob(os.path.join(completedirpath, wildcard)):\n        filelist.append(infile)\n    if len(filelist) == 0:\n        logger.error('No required files in path: ' + completedirpath)\n        raise Exception('No required file in path: ' + completedirpath)\n    return filelist",
    "docstring": "Function generates list of files from specific dir\n\n    files_in_dir(dirpath, wildcard=\"*.*\", startpath=None)\n\n    dirpath: required directory\n    wilcard: mask for files\n    startpath: start for relative path\n\n    Example\n    files_in_dir('medical/jatra-kiv','*.dcm', '~/data/')"
  },
  {
    "code": "def delete_kb(kb_name):\n    db.session.delete(models.KnwKB.query.filter_by(\n        name=kb_name).one())",
    "docstring": "Delete given kb from database.\n\n    :param kb_name: knowledge base name"
  },
  {
    "code": "def _generate_author_query(self, author_name):\n        name_variations = [name_variation.lower()\n                           for name_variation\n                           in generate_minimal_name_variations(author_name)]\n        if author_name_contains_fullnames(author_name):\n            specialized_author_filter = [\n                {\n                    'bool': {\n                        'must': [\n                            {\n                                'term': {ElasticSearchVisitor.AUTHORS_NAME_VARIATIONS_FIELD: names_variation[0]}\n                            },\n                            generate_match_query(\n                                ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'],\n                                names_variation[1],\n                                with_operator_and=True\n                            )\n                        ]\n                    }\n                } for names_variation\n                in product(name_variations, name_variations)\n            ]\n        else:\n            specialized_author_filter = [\n                {'term': {ElasticSearchVisitor.AUTHORS_NAME_VARIATIONS_FIELD: name_variation}}\n                for name_variation in name_variations\n            ]\n        query = {\n            'bool': {\n                'filter': {\n                    'bool': {\n                        'should': specialized_author_filter\n                    }\n                },\n                'must': {\n                    'match': {\n                        ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author']: author_name\n                    }\n                }\n            }\n        }\n        return generate_nested_query(ElasticSearchVisitor.AUTHORS_NESTED_QUERY_PATH, query)",
    "docstring": "Generates a query handling specifically authors.\n\n        Notes:\n            The match query is generic enough to return many results. Then, using the filter clause we truncate these\n            so that we imitate legacy's behaviour on returning more \"exact\" results. E.g. Searching for `Smith, John`\n            shouldn't return papers of 'Smith, Bob'.\n\n            Additionally, doing a ``match`` with ``\"operator\": \"and\"`` in order to be even more exact in our search, by\n            requiring that ``full_name`` field contains both"
  },
  {
    "code": "def parse_file(infile, exit_on_error=True):\n    try:\n        a, b, mag = np.atleast_2d(\n                            np.genfromtxt(\n                                        infile,\n                                        usecols=[0, 1, 2],\n                                        delimiter=','\n                                        )\n                    ).T\n    except IOError as e:\n        if exit_on_error:\n            logger.error(\"There seems to be a problem with the input file, \"\n                         \"the format should be: RA_degrees (J2000), Dec_degrees (J2000), \"\n                         \"Magnitude. There should be no header, columns should be \"\n                         \"separated by a comma\")\n            sys.exit(1)\n        else:\n            raise e\n    return a, b, mag",
    "docstring": "Parse a comma-separated file with columns \"ra,dec,magnitude\"."
  },
  {
    "code": "def get_candidate_election(self, election):\n        return CandidateElection.objects.get(candidate=self, election=election)",
    "docstring": "Get a CandidateElection."
  },
  {
    "code": "def unused_keys(self):\n        unused = set()\n        for k, c in self._children.items():\n            if isinstance(c, ConfigNode):\n                if not c.has_been_accessed():\n                    unused.add(k)\n            else:\n                for ck in c.unused_keys():\n                    unused.add(k+'.'+ck)\n        return unused",
    "docstring": "Lists all keys which are present in the ConfigTree but which have not been accessed."
  },
  {
    "code": "def getApplicationsErrorNameFromEnum(self, error):\n        fn = self.function_table.getApplicationsErrorNameFromEnum\n        result = fn(error)\n        return result",
    "docstring": "Returns a string for an applications error"
  },
  {
    "code": "def each(iterable = None, *, name = None, metric = call_default):\n    if iterable is None:\n        return _each_decorator(name, metric)\n    else:\n        return _do_each(iterable, name, metric)",
    "docstring": "Measure time elapsed to produce each item of an iterable\n\n    :arg iterable: any iterable\n    :arg function metric: f(name, 1, time)\n    :arg str name: name for the metric"
  },
  {
    "code": "def decipher(self,string):\n        string = string.upper()\n        mapping = dict(zip(self.key,self.table))\n        ptext = \"\"\n        for i in string:\n            ptext += mapping[i]\n        return self.demorse(ptext)",
    "docstring": "Decipher string using FracMorse cipher according to initialised key. \n\n        Example::\n\n            plaintext = FracMorse('ROUNDTABLECFGHIJKMPQSVWXYZ').decipher(ciphertext)     \n\n        :param string: The string to decipher.\n        :returns: The enciphered string."
  },
  {
    "code": "def map(self, mapper: Callable[[Any], Any]) -> 'List':\n        try:\n            ret = List.from_iterable([mapper(x) for x in self])\n        except TypeError:\n            ret = List.from_iterable([partial(mapper, x) for x in self])\n        return ret",
    "docstring": "Map a function over a List."
  },
  {
    "code": "def constraint(self, n=-1, fid=0):\n        c = self._getval(\"constr\", fid)\n        if n < 0 or n > self.deficiency(fid):\n            return c\n        else:\n            raise RuntimeError(\"Not yet implemented\")",
    "docstring": "Obtain the set of orthogonal equations that make the solution of\n        the rank deficient normal equations possible.\n\n        :param fid: the id of the sub-fitter (numerical)"
  },
  {
    "code": "def parse_name(cls, name: str, default: T = None) -> T:\n        if not name:\n            return default\n        name = name.lower()\n        return next((item for item in cls if name == item.name.lower()), default)",
    "docstring": "Parse specified name for IntEnum; return default if not found."
  },
  {
    "code": "def getWeb(url, isFeed):\n    socket.setdefaulttimeout(300)\n    loadedWeb = urllib2.build_opener()\n    loadedWeb.addheaders = getHeaders()\n    if isFeed:\n        web = etree.parse(loadedWeb.open(url))\n    else:\n        web = html.parse(loadedWeb.open(url))\n    return web",
    "docstring": "Download url and parse it with lxml.\n    If \"isFeed\" is True returns lxml.etree\n    else, returns lxml.html"
  },
  {
    "code": "def create_video_transcript(video_id, language_code, file_format, content, provider=TranscriptProviderType.CUSTOM):\n    transcript_serializer = TranscriptSerializer(\n        data=dict(provider=provider, language_code=language_code, file_format=file_format),\n        context=dict(video_id=video_id),\n    )\n    if transcript_serializer.is_valid():\n        transcript_serializer.save(content=content)\n        return transcript_serializer.data\n    else:\n        raise ValCannotCreateError(transcript_serializer.errors)",
    "docstring": "Create a video transcript.\n\n    Arguments:\n        video_id(unicode): An Id identifying the Video data model object.\n        language_code(unicode): A language code.\n        file_format(unicode): Transcript file format.\n        content(InMemoryUploadedFile): Transcript content.\n        provider(unicode): Transcript provider (it will be 'custom' by default if not selected)."
  },
  {
    "code": "def submit(self):\n        u = urlparse(self.url)\n        if not self.action:\n            self.action = self.url\n        elif self.action == u.path:\n            self.action = self.url\n        else:\n            if not u.netloc in self.action:\n                path = \"/\".join(u.path.split(\"/\")[1:-1])\n                if self.action.startswith(\"/\"):\n                    path = path + self.action\n                else:\n                    path = path + \"/\" + self.action\n                self.action = \"http://\" + u.netloc + \"/\" + path\n        return self.usr.getPage(self.action, self.items, {'Referer': self.url}, self.usePin)",
    "docstring": "Posts the form's data and returns the resulting Page\n           \n        Returns\n           Page - The resulting page"
  },
  {
    "code": "def mdownload(args):\n    from jcvi.apps.grid import Jobs\n    p = OptionParser(mdownload.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(not p.print_help())\n    linksfile, = args\n    links = [(x.strip(),) for x in open(linksfile)]\n    j = Jobs(download, links)\n    j.run()",
    "docstring": "%prog mdownload links.txt\n\n    Multiple download a list of files. Use formats.html.links() to extract the\n    links file."
  },
  {
    "code": "def load_file(self, filename):\n        with open(filename, 'r') as sourcefile:\n            self.set_string(sourcefile.read())",
    "docstring": "Read in file contents and set the current string."
  },
  {
    "code": "def delete_params_s(s, params):\n        patt = '(?s)' + '|'.join(\n            '(?<=\\n)' + s + '\\s*:.+?\\n(?=\\S+|$)' for s in params)\n        return re.sub(patt, '', '\\n' + s.strip() + '\\n').strip()",
    "docstring": "Delete the given parameters from a string\n\n        Same as :meth:`delete_params` but does not use the :attr:`params`\n        dictionary\n\n        Parameters\n        ----------\n        s: str\n            The string of the parameters section\n        params: list of str\n            The names of the parameters to delete\n\n        Returns\n        -------\n        str\n            The modified string `s` without the descriptions of `params`"
  },
  {
    "code": "def iterkeys(self):\n        def _iterkeys(bin):\n            for item in bin:\n                yield item.key\n        for bin in self.bins:\n            yield _iterkeys(bin)",
    "docstring": "An iterator over the keys of each bin."
  },
  {
    "code": "def removeOntology(self, ontology):\n        q = models.Ontology.delete().where(id == ontology.getId())\n        q.execute()",
    "docstring": "Removes the specified ontology term map from this repository."
  },
  {
    "code": "def get_job_info(current_job):\n    trials = TrialRecord.objects.filter(job_id=current_job.job_id)\n    total_num = len(trials)\n    running_num = sum(t.trial_status == Trial.RUNNING for t in trials)\n    success_num = sum(t.trial_status == Trial.TERMINATED for t in trials)\n    failed_num = sum(t.trial_status == Trial.ERROR for t in trials)\n    if total_num == 0:\n        progress = 0\n    else:\n        progress = int(float(success_num) / total_num * 100)\n    winner = get_winner(trials)\n    job_info = {\n        \"job_id\": current_job.job_id,\n        \"job_name\": current_job.name,\n        \"user\": current_job.user,\n        \"type\": current_job.type,\n        \"start_time\": current_job.start_time,\n        \"end_time\": current_job.end_time,\n        \"total_num\": total_num,\n        \"running_num\": running_num,\n        \"success_num\": success_num,\n        \"failed_num\": failed_num,\n        \"best_trial_id\": current_job.best_trial_id,\n        \"progress\": progress,\n        \"winner\": winner\n    }\n    return job_info",
    "docstring": "Get job information for current job."
  },
  {
    "code": "def get_decomp_and_e_above_hull(self, entry, allow_negative=False):\n        if entry in self.stable_entries:\n            return {entry: 1}, 0\n        comp = entry.composition\n        facet, simplex = self._get_facet_and_simplex(comp)\n        decomp_amts = simplex.bary_coords(self.pd_coords(comp))\n        decomp = {self.qhull_entries[f]: amt\n                  for f, amt in zip(facet, decomp_amts)\n                  if abs(amt) > PhaseDiagram.numerical_tol}\n        energies = [self.qhull_entries[i].energy_per_atom for i in facet]\n        ehull = entry.energy_per_atom - np.dot(decomp_amts, energies)\n        if allow_negative or ehull >= -PhaseDiagram.numerical_tol:\n            return decomp, ehull\n        raise ValueError(\"No valid decomp found!\")",
    "docstring": "Provides the decomposition and energy above convex hull for an entry.\n        Due to caching, can be much faster if entries with the same composition\n        are processed together.\n\n        Args:\n            entry: A PDEntry like object\n            allow_negative: Whether to allow negative e_above_hulls. Used to\n                calculate equilibrium reaction energies. Defaults to False.\n\n        Returns:\n            (decomp, energy above convex hull)  Stable entries should have\n            energy above hull of 0. The decomposition is provided as a dict of\n            {Entry: amount}."
  },
  {
    "code": "def upload_object(self, instance, bucket_name, object_name, file_obj,\n                      content_type=None):\n        url = '/buckets/{}/{}/{}'.format(instance, bucket_name, object_name)\n        with open(file_obj, 'rb') as f:\n            if content_type:\n                files = {object_name: (object_name, f, content_type)}\n            else:\n                files = {object_name: (object_name, f)}\n            self._client.request(path=url, method='post', files=files)",
    "docstring": "Upload an object to a bucket.\n\n        :param str instance: A Yamcs instance name.\n        :param str bucket_name: The name of the bucket.\n        :param str object_name: The target name of the object.\n        :param file file_obj: The file (or file-like object) to upload.\n        :param str content_type: The content type associated to this object.\n                                 This is mainly useful when accessing an object\n                                 directly via a web browser. If unspecified, a\n                                 content type *may* be automatically derived\n                                 from the specified ``file_obj``."
  },
  {
    "code": "def odometry2Pose3D(odom):\n    pose = Pose3d()\n    ori = odom.pose.pose.orientation\n    pose.x = odom.pose.pose.position.x\n    pose.y = odom.pose.pose.position.y\n    pose.z = odom.pose.pose.position.z\n    pose.yaw = quat2Yaw(ori.w, ori.x, ori.y, ori.z)\n    pose.pitch = quat2Pitch(ori.w, ori.x, ori.y, ori.z)\n    pose.roll = quat2Roll(ori.w, ori.x, ori.y, ori.z)\n    pose.q = [ori.w, ori.x, ori.y, ori.z]\n    pose.timeStamp = odom.header.stamp.secs + (odom.header.stamp.nsecs *1e-9)\n    return pose",
    "docstring": "Translates from ROS Odometry to JderobotTypes Pose3d. \n\n    @param odom: ROS Odometry to translate\n\n    @type odom: Odometry\n\n    @return a Pose3d translated from odom"
  },
  {
    "code": "def _parse_nodes_section(f, current_section, nodes):\n    section = {}\n    dimensions = None\n    if current_section == 'NODE_COORD_SECTION':\n        dimensions = 3\n    elif current_section == 'DEMAND_SECTION':\n        dimensions = 2\n    else:\n        raise ParseException('Invalid section {}'.format(current_section))\n    n = 0\n    for line in f:\n        line = strip(line)\n        definitions = re.split(r'\\s*', line)\n        if len(definitions) != dimensions:\n            raise ParseException('Invalid dimensions from section {}. Expected: {}'.format(current_section, dimensions))\n        node = int(definitions[0])\n        values = [int(v) for v in definitions[1:]]\n        if len(values) == 1:\n            values = values[0]\n        section[node] = values\n        n = n + 1\n        if n == nodes:\n            break\n    if n != nodes:\n        raise ParseException('Missing {} nodes definition from section {}'.format(nodes - n, current_section))\n    return section",
    "docstring": "Parse TSPLIB NODE_COORD_SECTION or DEMAND_SECTION from file descript f\n\n    Returns a dict containing the node as key"
  },
  {
    "code": "def raster_to_projection_coords(self, pixel_x, pixel_y):\n        h_px_py = np.array([1, pixel_x, pixel_y])\n        gt = np.array([[1, 0, 0], self.geotransform[0:3], self.geotransform[3:6]])\n        arr = np.inner(gt, h_px_py)\n        return arr[2], arr[1]",
    "docstring": "Use pixel centers when appropriate.\n        See documentation for the GDAL function GetGeoTransform for details."
  },
  {
    "code": "def _j9SaveCurrent(sDir = '.'):\n    dname = os.path.normpath(sDir + '/' +  datetime.datetime.now().strftime(\"%Y-%m-%d_J9_AbbreviationDocs\"))\n    if not os.path.isdir(dname):\n        os.mkdir(dname)\n        os.chdir(dname)\n    else:\n        os.chdir(dname)\n    for urlID, urlString in j9urlGenerator(nameDict = True).items():\n        fname = \"{}_abrvjt.html\".format(urlID)\n        f = open(fname, 'wb')\n        f.write(urllib.request.urlopen(urlString).read())",
    "docstring": "Downloads and saves all the webpages\n\n    For Backend"
  },
  {
    "code": "def get_series_episodes(self, id, page=1):\n        params = {'page': page}\n        r = self.session.get(self.base_url + '/series/{}/episodes'.format(id), params=params)\n        if r.status_code == 404:\n            return None\n        r.raise_for_status()\n        return r.json()",
    "docstring": "Get series episodes"
  },
  {
    "code": "def info(self, abspath=True):\n        logger.debug(str(''))\n        return self._call_and_parse(['info', '--json'], abspath=abspath)",
    "docstring": "Return a dictionary with configuration information.\n\n        No guarantee is made about which keys exist.  Therefore this function\n        should only be used for testing and debugging."
  },
  {
    "code": "def usearch_cluster_error_correction(\n        fasta_filepath,\n        output_filepath=None,\n        output_uc_filepath=None,\n        percent_id_err=0.97,\n        sizein=True,\n        sizeout=True,\n        w=64,\n        slots=16769023,\n        maxrejects=64,\n        log_name=\"usearch_cluster_err_corrected.log\",\n        usersort=False,\n        HALT_EXEC=False,\n        save_intermediate_files=False,\n        remove_usearch_logs=False,\n        working_dir=None):\n    if not output_filepath:\n        _, output_filepath = mkstemp(prefix='usearch_cluster_err_corrected',\n                                     suffix='.fasta')\n    log_filepath = join(working_dir, log_name)\n    params = {'--sizein': sizein,\n              '--sizeout': sizeout,\n              '--id': percent_id_err,\n              '--w': w,\n              '--slots': slots,\n              '--maxrejects': maxrejects}\n    app = Usearch(params, WorkingDir=working_dir, HALT_EXEC=HALT_EXEC)\n    if usersort:\n        app.Parameters['--usersort'].on()\n    data = {'--cluster': fasta_filepath,\n            '--consout': output_filepath\n            }\n    if not remove_usearch_logs:\n        data['--log'] = log_filepath\n    if output_uc_filepath:\n        data['--uc'] = output_uc_filepath\n    app_result = app(data)\n    return app_result, output_filepath",
    "docstring": "Cluster for err. correction at percent_id_err, output consensus fasta\n\n    fasta_filepath = input fasta file, generally a dereplicated fasta\n    output_filepath = output error corrected fasta filepath\n    percent_id_err = minimum identity percent.\n    sizein = not defined in usearch helpstring\n    sizeout = not defined in usearch helpstring\n    w = Word length for U-sorting\n    slots = Size of compressed index table. Should be prime, e.g. 40000003.\n     Should also specify --w, typical is --w 16 or --w 32.\n    maxrejects = Max rejected targets, 0=ignore, default 32.\n    log_name = string specifying output log name\n    usersort = Enable if input fasta not sorted by length purposefully, lest\n     usearch will raise an error.\n    HALT_EXEC: Used for debugging app controller\n    save_intermediate_files: Preserve all intermediate files created."
  },
  {
    "code": "def render_to_response(self, template_name, __data,\n                           content_type=\"text/html\"):\n        resp = self.render(template_name, __data)\n        return Response(resp,\n                        content_type=content_type)",
    "docstring": "Given a template name and template data.\n        Renders a template and returns `webob.Response` object"
  },
  {
    "code": "def get_comments_of_confirmation_per_page(self, confirmation_id, per_page=1000, page=1):\n        return self._get_resource_per_page(\n            resource=CONFIRMATION_COMMENTS,\n            per_page=per_page,\n            page=page,\n            params={'confirmation_id': confirmation_id},\n        )",
    "docstring": "Get comments of confirmation per page\n\n        :param confirmation_id: the confirmation id\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :return: list"
  },
  {
    "code": "def on_new_line(self):\r\n        self.set_cursor_position('eof')\r\n        self.current_prompt_pos = self.get_position('cursor')\r\n        self.new_input_line = False",
    "docstring": "On new input line"
  },
  {
    "code": "def compute_ecc_hash(ecc_manager, hasher, buf, max_block_size, rate, message_size=None, as_string=False):\n    result = []\n    if not message_size:\n        ecc_params = compute_ecc_params(max_block_size, rate, hasher)\n        message_size = ecc_params[\"message_size\"]\n    for i in xrange(0, len(buf), message_size):\n        mes = buf[i:i+message_size]\n        ecc = ecc_manager.encode(mes)\n        hash = hasher.hash(mes)\n        if as_string:\n            result.append(\"%s%s\" % (str(hash),str(ecc)))\n        else:\n            result.append([hash, ecc])\n    return result",
    "docstring": "Split a string in blocks given max_block_size and compute the hash and ecc for each block, and then return a nice list with both for easy processing."
  },
  {
    "code": "def context_list_users(zap_helper, context_name):\n    with zap_error_handler():\n        info = zap_helper.get_context_info(context_name)\n    users = zap_helper.zap.users.users_list(info['id'])\n    if len(users):\n        user_list = ', '.join([user['name'] for user in users])\n        console.info('Available users for the context {0}: {1}'.format(context_name, user_list))\n    else:\n        console.info('No users configured for the context {}'.format(context_name))",
    "docstring": "List the users available for a given context."
  },
  {
    "code": "def add_job_from_json(self, job_json, destructive=False):\n        logger.debug('Importing job from JSON document: {0}'.format(job_json))\n        rec = self.backend.decode_import_json(job_json)\n        if destructive:\n            try:\n                self.delete_job(rec['name'])\n            except DagobahError:\n                pass\n        self._add_job_from_spec(rec, use_job_id=False)\n        self.commit(cascade=True)",
    "docstring": "Construct a new Job from an imported JSON spec."
  },
  {
    "code": "def get_last_lineno(node):\n    max_lineno = 0\n    if hasattr(node, \"lineno\"):\n        max_lineno = node.lineno\n    for _, field in ast.iter_fields(node):\n        if isinstance(field, list):\n            for value in field:\n                if isinstance(value, ast.AST):\n                    max_lineno = max(max_lineno, get_last_lineno(value))\n        elif isinstance(field, ast.AST):\n            max_lineno = max(max_lineno, get_last_lineno(field))\n    return max_lineno",
    "docstring": "Recursively find the last line number of the ast node."
  },
  {
    "code": "def drain(iterable):\n    if getattr(iterable, \"popleft\", False):\n        def next_item(coll):\n            return coll.popleft()\n    elif getattr(iterable, \"popitem\", False):\n        def next_item(coll):\n            return coll.popitem()\n    else:\n        def next_item(coll):\n            return coll.pop()\n    while True:\n        try:\n            yield next_item(iterable)\n        except (IndexError, KeyError):\n            raise StopIteration",
    "docstring": "Helper method that empties an iterable as it is iterated over.\n\n    Works for:\n\n    * ``dict``\n    * ``collections.deque``\n    * ``list``\n    * ``set``"
  },
  {
    "code": "def has_changed (filename):\n    key = os.path.abspath(filename)\n    mtime = get_mtime(key)\n    if key not in _mtime_cache:\n        _mtime_cache[key] = mtime\n        return True\n    return mtime > _mtime_cache[key]",
    "docstring": "Check if filename has changed since the last check. If this\n    is the first check, assume the file is changed."
  },
  {
    "code": "def load_entry_points(self):\n        if self.entry_point_group:\n            task_packages = {}\n            for item in pkg_resources.iter_entry_points(\n                    group=self.entry_point_group):\n                try:\n                    pkg, related_name = item.module_name.rsplit('.', 1)\n                except ValueError:\n                    warnings.warn(\n                        'The celery task module \"{}\" was not loaded. '\n                        'Defining modules in bare Python modules is no longer '\n                        'supported due to Celery v4.2 constraints. Please '\n                        'move the module into a Python package.'.format(\n                            item.module_name\n                        ),\n                        RuntimeWarning\n                    )\n                    continue\n                if related_name not in task_packages:\n                    task_packages[related_name] = []\n                task_packages[related_name].append(pkg)\n            if task_packages:\n                for related_name, packages in task_packages.items():\n                    self.celery.autodiscover_tasks(\n                        packages, related_name=related_name, force=True\n                    )",
    "docstring": "Load tasks from entry points."
  },
  {
    "code": "def _get_jvm_opts(out_file, data):\n    resources = config_utils.get_resources(\"purple\", data[\"config\"])\n    jvm_opts = resources.get(\"jvm_opts\", [\"-Xms750m\", \"-Xmx3500m\"])\n    jvm_opts = config_utils.adjust_opts(jvm_opts, {\"algorithm\": {\"memory_adjust\":\n                                                                 {\"direction\": \"increase\",\n                                                                  \"maximum\": \"30000M\",\n                                                                  \"magnitude\": dd.get_cores(data)}}})\n    jvm_opts += broad.get_default_jvm_opts(os.path.dirname(out_file))\n    return jvm_opts",
    "docstring": "Retrieve Java options, adjusting memory for available cores."
  },
  {
    "code": "def __json(self):\r\n        if self.exclude_list is None:\r\n            self.exclude_list = []\r\n        fields = {}\r\n        for key, item in vars(self).items():\r\n            if hasattr(self, '_sa_instance_state'):\r\n                if len(orm.attributes.instance_state(self).unloaded) > 0:\r\n                    mapper = inspect(self)\r\n                    for column in mapper.attrs:\r\n                        column.key\r\n                        column.value\r\n            if str(key).startswith('_') or key in self.exclude_list:\r\n                continue\r\n            fields[key] = item\r\n        obj = Json.safe_object(fields)\r\n        return str(obj)",
    "docstring": "Using the exclude lists, convert fields to a string."
  },
  {
    "code": "def _TemplateExists(unused_value, context, args):\n    try:\n        name = args[0]\n    except IndexError:\n        raise EvaluationError('The \"template\" predicate requires an argument.')\n    return context.HasTemplate(name)",
    "docstring": "Returns whether the given name is in the current Template's template group."
  },
  {
    "code": "def read_comment(self, start: int, line: int, col: int, prev: Token) -> Token:\n        body = self.source.body\n        body_length = len(body)\n        position = start\n        while True:\n            position += 1\n            if position > body_length:\n                break\n            char = body[position]\n            if char < \" \" and char != \"\\t\":\n                break\n        return Token(\n            TokenKind.COMMENT,\n            start,\n            position,\n            line,\n            col,\n            prev,\n            body[start + 1 : position],\n        )",
    "docstring": "Read a comment token from the source file."
  },
  {
    "code": "def create(**data):\n        http_client = HttpClient()\n        response, _ = http_client.post(routes.url(routes.PAYMENT_RESOURCE), data)\n        return resources.Payment(**response)",
    "docstring": "Create a Payment request.\n\n        :param data: data required to create the payment\n\n        :return: The payment resource\n        :rtype resources.Payment"
  },
  {
    "code": "def related_obj_to_dict(obj, **kwargs):\n    kwargs.pop('formatter', None)\n    suppress_private_attr = kwargs.get(\"suppress_private_attr\", False)\n    suppress_empty_values = kwargs.get(\"suppress_empty_values\", False)\n    attrs = fields(obj.__class__)\n    return_dict = kwargs.get(\"dict_factory\", OrderedDict)()\n    for a in attrs:\n        if suppress_private_attr and a.name.startswith(\"_\"):\n            continue\n        metadata = a.metadata or {}\n        formatter = metadata.get('formatter')\n        value = getattr(obj, a.name)\n        value = to_dict(value, formatter=formatter, **kwargs)\n        if suppress_empty_values and value is None:\n            continue\n        key_name = a.metadata.get('key') or a.name\n        return_dict[key_name] = value\n    return return_dict",
    "docstring": "Covert a known related object to a dictionary."
  },
  {
    "code": "def protocol_str(protocol):\n    if protocol == const.PROTOCOL_MRP:\n        return 'MRP'\n    if protocol == const.PROTOCOL_DMAP:\n        return 'DMAP'\n    if protocol == const.PROTOCOL_AIRPLAY:\n        return 'AirPlay'\n    return 'Unknown'",
    "docstring": "Convert internal API protocol to string."
  },
  {
    "code": "def _cellrepr(value, allow_formulas):\n    if pd.isnull(value) is True:\n        return \"\"\n    if isinstance(value, float):\n        value = repr(value)\n    else:\n        value = str(value)\n    if (not allow_formulas) and value.startswith('='):\n        value = \"'%s\" % value\n    return value",
    "docstring": "Get a string representation of dataframe value.\n\n    :param :value: the value to represent\n    :param :allow_formulas: if True, allow values starting with '='\n            to be interpreted as formulas; otherwise, escape\n            them with an apostrophe to avoid formula interpretation."
  },
  {
    "code": "def clean_title(title):\n    date_pattern = re.compile(r'\\W*'\n                              r'\\d{1,2}'\n                              r'[/\\-.]'\n                              r'\\d{1,2}'\n                              r'[/\\-.]'\n                              r'(?=\\d*)(?:.{4}|.{2})'\n                              r'\\W*')\n    title = date_pattern.sub(' ', title)\n    title = re.sub(r'\\s{2,}', ' ', title)\n    title = title.strip()\n    return title",
    "docstring": "Clean title -> remove dates, remove duplicated spaces and strip title.\n\n    Args:\n        title (str): Title.\n\n    Returns:\n        str: Clean title without dates, duplicated, trailing and leading spaces."
  },
  {
    "code": "def _secret_yaml(loader, node):\n    fname = os.path.join(os.path.dirname(loader.name), \"secrets.yaml\")\n    try:\n        with open(fname, encoding=\"utf-8\") as secret_file:\n            secrets = YAML(typ=\"safe\").load(secret_file)\n    except FileNotFoundError:\n        raise ValueError(\"Secrets file {} not found\".format(fname)) from None\n    try:\n        return secrets[node.value]\n    except KeyError:\n        raise ValueError(\"Secret {} not found\".format(node.value)) from None",
    "docstring": "Load secrets and embed it into the configuration YAML."
  },
  {
    "code": "def decimal(self, var, default=NOTSET, force=True):\n        return self._get(var, default=default, cast=Decimal, force=force)",
    "docstring": "Convenience method for casting to a decimal.Decimal\n\n        Note:\n            Casting"
  },
  {
    "code": "def error(self, reason=None):\n        self.set_status(Report.ERROR)\n        if reason:\n            self.add('reason', reason)",
    "docstring": "Set the test status to Report.ERROR, and set the error reason\n\n        :param reason: error reason (default: None)"
  },
  {
    "code": "def authenticate(self, username=None, password=None):\n        u = self.username\n        p = self.password\n        if username and password:\n            u = username\n            p = password\n        client = self.client()\n        query = client.authenticated_query(username=u, password=p)\n        res = client.post(query)\n        ofx = BeautifulSoup(res, 'lxml')\n        sonrs = ofx.find('sonrs')\n        code = int(sonrs.find('code').contents[0].strip())\n        try:\n            status = sonrs.find('message').contents[0].strip()\n        except Exception:\n            status = ''\n        if code == 0:\n            return 1\n        raise ValueError(status)",
    "docstring": "Test the authentication credentials\n\n        Raises a ``ValueError`` if there is a problem authenticating\n        with the human readable reason given by the institution.\n\n        :param username: optional username (use self.username by default)\n        :type username: string or None\n        :param password: optional password (use self.password by default)\n        :type password: string or None"
  },
  {
    "code": "def slices(src_path):\n  pages = list_slices(src_path)\n  slices = []\n  for page in pages:\n    slices.extend(page.slices)\n  return slices",
    "docstring": "Return slices as a flat list"
  },
  {
    "code": "def _get_all_policy_ids(zap_helper):\n    policies = zap_helper.zap.ascan.policies()\n    return [p['id'] for p in policies]",
    "docstring": "Get all policy IDs."
  },
  {
    "code": "def set_defaults(self):\n        for key, val in self.c_default.items():\n            self._dict[key] = val",
    "docstring": "Based on specification set a parameters value to the default value."
  },
  {
    "code": "def _format_method_nodes(self, task_method, modulename, classname):\n        methodname = task_method.__name__\n        fullname = '.'.join((modulename, classname, methodname))\n        signature = Signature(task_method, bound_method=True)\n        desc_sig_node = self._format_signature(\n            signature, modulename, classname, fullname, 'py:meth')\n        content_node = desc_content()\n        content_node += self._create_doc_summary(task_method, fullname,\n                                                 'py:meth')\n        desc_node = desc()\n        desc_node['noindex'] = True\n        desc_node['domain'] = 'py'\n        desc_node['objtype'] = 'method'\n        desc_node += desc_sig_node\n        desc_node += content_node\n        return desc_node",
    "docstring": "Create a ``desc`` node summarizing a method docstring."
  },
  {
    "code": "def sortByColumn(self, index):\r\n        if self.sort_old == [None]:\r\n            self.header_class.setSortIndicatorShown(True)\r\n        sort_order = self.header_class.sortIndicatorOrder()\r\n        self.sig_sort_by_column.emit()\r\n        if not self.model().sort(index, sort_order):\r\n            if len(self.sort_old) != 2:\r\n                self.header_class.setSortIndicatorShown(False)\r\n            else:\r\n                self.header_class.setSortIndicator(self.sort_old[0],\r\n                                                   self.sort_old[1])\r\n            return\r\n        self.sort_old = [index, self.header_class.sortIndicatorOrder()]",
    "docstring": "Implement a column sort."
  },
  {
    "code": "def buildASNList(rootnames, asnname, check_for_duplicates=True):\n    filelist, duplicates = checkForDuplicateInputs(rootnames)\n    if check_for_duplicates and duplicates:\n        origasn = changeSuffixinASN(asnname, 'flt')\n        dupasn = changeSuffixinASN(asnname, 'flc')\n        errstr = 'ERROR:\\nMultiple valid input files found:\\n'\n        for fname, dname in zip(filelist, duplicates):\n            errstr += '    %s    %s\\n' % (fname, dname)\n        errstr += ('\\nNew association files have been generated for each '\n                   'version of these files.\\n    %s\\n    %s\\n\\nPlease '\n                   're-start astrodrizzle using of these new ASN files or '\n                   'use widlcards for the input to only select one type of '\n                   'input file.' % (dupasn, origasn))\n        print(textutil.textbox(errstr), file=sys.stderr)\n        raise ValueError\n    return filelist",
    "docstring": "Return the list of filenames for a given set of rootnames"
  },
  {
    "code": "def spearmanr(self, target, correlation_length, mask=NotSpecified):\n        from .statistical import RollingSpearman\n        return RollingSpearman(\n            base_factor=self,\n            target=target,\n            correlation_length=correlation_length,\n            mask=mask,\n        )",
    "docstring": "Construct a new Factor that computes rolling spearman rank correlation\n        coefficients between `target` and the columns of `self`.\n\n        This method can only be called on factors which are deemed safe for use\n        as inputs to other factors. This includes `Returns` and any factors\n        created from `Factor.rank` or `Factor.zscore`.\n\n        Parameters\n        ----------\n        target : zipline.pipeline.Term with a numeric dtype\n            The term used to compute correlations against each column of data\n            produced by `self`. This may be a Factor, a BoundColumn or a Slice.\n            If `target` is two-dimensional, correlations are computed\n            asset-wise.\n        correlation_length : int\n            Length of the lookback window over which to compute each\n            correlation coefficient.\n        mask : zipline.pipeline.Filter, optional\n            A Filter describing which assets should have their correlation with\n            the target slice computed each day.\n\n        Returns\n        -------\n        correlations : zipline.pipeline.factors.RollingSpearman\n            A new Factor that will compute correlations between `target` and\n            the columns of `self`.\n\n        Examples\n        --------\n        Suppose we want to create a factor that computes the correlation\n        between AAPL's 10-day returns and the 10-day returns of all other\n        assets, computing each correlation over 30 days. This can be achieved\n        by doing the following::\n\n            returns = Returns(window_length=10)\n            returns_slice = returns[sid(24)]\n            aapl_correlations = returns.spearmanr(\n                target=returns_slice, correlation_length=30,\n            )\n\n        This is equivalent to doing::\n\n            aapl_correlations = RollingSpearmanOfReturns(\n                target=sid(24), returns_length=10, correlation_length=30,\n            )\n\n        See Also\n        --------\n        :func:`scipy.stats.spearmanr`\n        :class:`zipline.pipeline.factors.RollingSpearmanOfReturns`\n        :meth:`Factor.pearsonr`"
  },
  {
    "code": "def chain(*steps):\n    if not steps:\n        return\n    def on_done(sprite=None):\n        chain(*steps[2:])\n    obj, params = steps[:2]\n    if len(steps) > 2:\n        params['on_complete'] = on_done\n    if callable(obj):\n        obj(**params)\n    else:\n        obj.animate(**params)",
    "docstring": "chains the given list of functions and object animations into a callback string.\n\n        Expects an interlaced list of object and params, something like:\n            object, {params},\n            callable, {params},\n            object, {},\n            object, {params}\n    Assumes that all callees accept on_complete named param.\n    The last item in the list can omit that.\n    XXX - figure out where to place these guys as they are quite useful"
  },
  {
    "code": "def find(self, name, current_location):\n        assert isinstance(name, basestring)\n        assert isinstance(current_location, basestring)\n        project_module = None\n        if name[0] == '/':\n            project_module = self.id2module.get(name)\n        if not project_module:\n            location = os.path.join(current_location, name)\n            project_module = self.module_name(location)\n            if not project_module in self.jamfile_modules:\n                if b2.util.path.glob([location], self.JAMROOT + self.JAMFILE):\n                    project_module = self.load(location)\n                else:\n                    project_module = None\n        return project_module",
    "docstring": "Given 'name' which can be project-id or plain directory name,\n        return project module corresponding to that id or directory.\n        Returns nothing of project is not found."
  },
  {
    "code": "def vn(x):\n\tif x == []:\n\t\treturn None\n\tif isinstance(x, list):\n\t\treturn '|'.join(x)\n\tif isinstance(x, datetime):\n\t\treturn x.isoformat()\n\treturn x",
    "docstring": "value or none, returns none if x is an empty list"
  },
  {
    "code": "async def popen_uci(command: Union[str, List[str]], *, setpgrp: bool = False, loop=None, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, UciProtocol]:\n    transport, protocol = await UciProtocol.popen(command, setpgrp=setpgrp, loop=loop, **popen_args)\n    try:\n        await protocol.initialize()\n    except:\n        transport.close()\n        raise\n    return transport, protocol",
    "docstring": "Spawns and initializes an UCI engine.\n\n    :param command: Path of the engine executable, or a list including the\n        path and arguments.\n    :param setpgrp: Open the engine process in a new process group. This will\n        stop signals (such as keyboard interrupts) from propagating from the\n        parent process. Defaults to ``False``.\n    :param popen_args: Additional arguments for\n        `popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.\n        Do not set ``stdin``, ``stdout``, ``bufsize`` or\n        ``universal_newlines``.\n\n    Returns a subprocess transport and engine protocol pair."
  },
  {
    "code": "def insert_row(self, index, row):\n        row = self._validate_row(row)\n        row_obj = RowData(self, row)\n        self._table.insert(index, row_obj)",
    "docstring": "Insert a row before index in the table.\n\n        Parameters\n        ----------\n        index : int\n            List index rules apply\n\n        row : iterable\n            Any iterable of appropriate length.\n\n        Raises\n        ------\n        TypeError:\n            If `row` is not an iterable.\n\n        ValueError:\n            If size of `row` is inconsistent with the current number\n            of columns."
  },
  {
    "code": "def no_auth(self):\n        old_basic_auth, self.auth = self.auth, None\n        old_token_auth = self.headers.pop('Authorization', None)\n        yield\n        self.auth = old_basic_auth\n        if old_token_auth:\n            self.headers['Authorization'] = old_token_auth",
    "docstring": "Unset authentication temporarily as a context manager."
  },
  {
    "code": "def evolve(self, years):\n        world_file = fldr + os.sep + self.name + '.txt'\n        self.build_base()\n        self.world.add_mountains()\n        self.add_life()\n        self.world.grd.save(world_file)\n        print('TODO - run ' + str(years) + ' years')",
    "docstring": "run the evolution of the planet to see how it looks \n        after 'years'"
  },
  {
    "code": "def _dump_multipoint(obj, big_endian, meta):\n    coords = obj['coordinates']\n    vertex = coords[0]\n    num_dims = len(vertex)\n    wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder(\n        'MultiPoint', num_dims, big_endian, meta\n    )\n    point_type = _WKB[_INT_TO_DIM_LABEL.get(num_dims)]['Point']\n    if big_endian:\n        point_type = BIG_ENDIAN + point_type\n    else:\n        point_type = LITTLE_ENDIAN + point_type[::-1]\n    wkb_string += struct.pack('%sl' % byte_order, len(coords))\n    for vertex in coords:\n        wkb_string += point_type\n        wkb_string += struct.pack(byte_fmt, *vertex)\n    return wkb_string",
    "docstring": "Dump a GeoJSON-like `dict` to a multipoint WKB string.\n\n    Input parameters and output are similar to :funct:`_dump_point`."
  },
  {
    "code": "def find_paths_breadth_first(from_target, to_target, log):\n  log.debug('Looking for all paths from {} to {}'.format(from_target.address.reference(),\n                                                         to_target.address.reference()))\n  if from_target == to_target:\n    yield [from_target]\n    return\n  visited_edges = set()\n  to_walk_paths = deque([[from_target]])\n  while len(to_walk_paths) > 0:\n    cur_path = to_walk_paths.popleft()\n    target = cur_path[-1]\n    if len(cur_path) > 1:\n      prev_target = cur_path[-2]\n    else:\n      prev_target = None\n    current_edge = (prev_target, target)\n    if current_edge not in visited_edges:\n      for dep in target.dependencies:\n        dep_path = cur_path + [dep]\n        if dep == to_target:\n          yield dep_path\n        else:\n          to_walk_paths.append(dep_path)\n      visited_edges.add(current_edge)",
    "docstring": "Yields the paths between from_target to to_target if they exist.\n\n  The paths are returned ordered by length, shortest first.\n  If there are cycles, it checks visited edges to prevent recrossing them."
  },
  {
    "code": "def list_entitlements(owner, repo, page, page_size, show_tokens):\n    client = get_entitlements_api()\n    with catch_raise_api_exception():\n        data, _, headers = client.entitlements_list_with_http_info(\n            owner=owner,\n            repo=repo,\n            page=page,\n            page_size=page_size,\n            show_tokens=show_tokens,\n        )\n    ratelimits.maybe_rate_limit(client, headers)\n    page_info = PageInfo.from_headers(headers)\n    entitlements = [ent.to_dict() for ent in data]\n    return entitlements, page_info",
    "docstring": "Get a list of entitlements on a repository."
  },
  {
    "code": "def basename(path: Optional[str]) -> Optional[str]:\n    if path is not None:\n        return os.path.basename(path)",
    "docstring": "Returns the final component of a pathname and None if the argument is None"
  },
  {
    "code": "def get_new_session(self):\n        session = Session()\n        session.headers = self.headers\n        session.proxies = self._get_request_proxies()\n        return session",
    "docstring": "Returns a new session using the object's proxies and headers"
  },
  {
    "code": "def get_registration_fields(xmlstream,\n                            timeout=60,\n                            ):\n    iq = aioxmpp.IQ(\n        to=aioxmpp.JID.fromstr(xmlstream._to),\n        type_=aioxmpp.IQType.GET,\n        payload=xso.Query()\n    )\n    iq.autoset_id()\n    reply = yield from aioxmpp.protocol.send_and_wait_for(xmlstream,\n                                                          [iq],\n                                                          [aioxmpp.IQ],\n                                                          timeout=timeout)\n    return reply.payload",
    "docstring": "A query is sent to the server to obtain the fields that need to be\n    filled to register with the server.\n\n    :param xmlstream: Specifies the stream connected to the server where\n                      the account will be created.\n    :type xmlstream: :class:`aioxmpp.protocol.XMLStream`\n\n    :param timeout: Maximum time in seconds to wait for an IQ response, or\n                    :data:`None` to disable the timeout.\n    :type timeout: :class:`~numbers.Real` or :data:`None`\n\n    :return: :attr:`list`"
  },
  {
    "code": "def _update_frozencell(self, frozen):\n        toggle_state = frozen is not False\n        self.ToggleTool(wx.FONTFLAG_MASK, toggle_state)",
    "docstring": "Updates frozen cell widget\n\n        Parameters\n        ----------\n\n        frozen: Bool or string\n        \\tUntoggled iif False"
  },
  {
    "code": "def read_magic_file(self, path, sort_by_this_name):\n        DATA = {}\n        try:\n            with open(path, 'r') as finput:\n                lines = list(finput.readlines()[1:])\n        except FileNotFoundError:\n            return []\n        line = lines[0]\n        header = line.strip('\\n').split('\\t')\n        error_strings = []\n        for line in lines[1:]:\n            tmp_data = {}\n            tmp_line = line.strip('\\n').split('\\t')\n            for i in range(len(tmp_line)):\n                tmp_data[header[i]] = tmp_line[i]\n            if tmp_data[sort_by_this_name] in list(DATA.keys()):\n                error_string = \"-E- ERROR: magic file %s has more than one line for %s %s\" % (\n                    path, sort_by_this_name, tmp_data[sort_by_this_name])\n                if error_string not in error_strings:\n                    print(error_string)\n                    error_strings.append(error_string)\n            DATA[tmp_data[sort_by_this_name]] = tmp_data\n        finput.close()\n        return(DATA)",
    "docstring": "reads a magic formated data file from path and sorts the keys\n        according to sort_by_this_name\n\n        Parameters\n        ----------\n        path : path to file to read\n        sort_by_this_name : variable to sort data by"
  },
  {
    "code": "def remove_template(self, tpl):\n        try:\n            del self.templates[tpl.uuid]\n        except KeyError:\n            pass\n        self.unindex_template(tpl)",
    "docstring": "Removes and un-index a template from the `templates` container.\n\n        :param tpl: The template to remove\n        :type tpl: alignak.objects.item.Item\n        :return: None"
  },
  {
    "code": "def open_netcdf_reader(self, flatten=False, isolate=False, timeaxis=1):\n        self._netcdf_reader = netcdftools.NetCDFInterface(\n            flatten=bool(flatten),\n            isolate=bool(isolate),\n            timeaxis=int(timeaxis))",
    "docstring": "Prepare a new |NetCDFInterface| object for reading data."
  },
  {
    "code": "def wirevector_subset(self, cls=None, exclude=tuple()):\n        if cls is None:\n            initial_set = self.wirevector_set\n        else:\n            initial_set = (x for x in self.wirevector_set if isinstance(x, cls))\n        if exclude == tuple():\n            return set(initial_set)\n        else:\n            return set(x for x in initial_set if not isinstance(x, exclude))",
    "docstring": "Return set of wirevectors, filtered by the type or tuple of types provided as cls.\n\n        If no cls is specified, the full set of wirevectors associated with the Block are\n        returned.  If cls is a single type, or a tuple of types, only those wirevectors of\n        the matching types will be returned.  This is helpful for getting all inputs, outputs,\n        or registers of a block for example."
  },
  {
    "code": "def process(self, checksum, revision=None):\n        revert = None\n        if checksum in self:\n            reverteds = list(self.up_to(checksum))\n            if len(reverteds) > 0:\n                revert = Revert(revision, reverteds, self[checksum])\n        self.insert(checksum, revision)\n        return revert",
    "docstring": "Process a new revision and detect a revert if it occurred.  Note that\n        you can pass whatever you like as `revision` and it will be returned in\n        the case that a revert occurs.\n\n        :Parameters:\n            checksum : str\n                Any identity-machable string-based hash of revision content\n            revision : `mixed`\n                Revision metadata.  Note that any data will just be returned\n                in the case of a revert.\n\n        :Returns:\n            a :class:`~mwreverts.Revert` if one occured or `None`"
  },
  {
    "code": "def get_monkeypatched_pathset(self):\n        from pip_shims.shims import InstallRequirement\n        uninstall_path = InstallRequirement.__module__.replace(\n            \"req_install\", \"req_uninstall\"\n        )\n        req_uninstall = self.safe_import(uninstall_path)\n        self.recursive_monkey_patch.monkey_patch(\n            PatchedUninstaller, req_uninstall.UninstallPathSet\n        )\n        return req_uninstall.UninstallPathSet",
    "docstring": "Returns a monkeypatched `UninstallPathset` for using to uninstall packages from the virtualenv\n\n        :return: A patched `UninstallPathset` which enables uninstallation of venv packages\n        :rtype: :class:`pip._internal.req.req_uninstall.UninstallPathset`"
  },
  {
    "code": "def add_current_user_is_applied_representation(func):\n  @wraps(func)\n  def _impl(self, instance):\n    ret = func(self, instance)\n    user = self.context[\"request\"].user\n    applied = False\n    if not user.is_anonymous():\n      try:\n        applied = models.Apply.objects.filter(user=user, project=instance).count() > 0\n      except:\n        pass\n    ret[\"current_user_is_applied\"] = applied\n    return ret\n  return _impl",
    "docstring": "Used to decorate Serializer.to_representation method.\n      It sets the field \"current_user_is_applied\" if the user is applied to the project"
  },
  {
    "code": "def __set_log_file_name(self):\n        dir, _ = os.path.split(self.__logFileBasename)\n        if len(dir) and not os.path.exists(dir):\n            os.makedirs(dir)\n        self.__logFileName = self.__logFileBasename+\".\"+self.__logFileExtension\n        number = 0\n        while os.path.isfile(self.__logFileName):\n            if os.stat(self.__logFileName).st_size/1e6 < self.__maxlogFileSize:\n                break\n            number += 1\n            self.__logFileName = self.__logFileBasename+\"_\"+str(number)+\".\"+self.__logFileExtension\n        self.__logFileStream = None",
    "docstring": "Automatically set logFileName attribute"
  },
  {
    "code": "def _seconds_to_days(cls, val, **kwargs):\n        zero_value = kwargs.get('zero_value', 0)\n        if val is not None:\n            if val == zero_value:\n                return 0\n            return val / 86400\n        else:\n            return 'Not Defined'",
    "docstring": "converts a number of seconds to days"
  },
  {
    "code": "def bind(self, name, filterset):\n        if self.name is not None:\n            name = self.name\n        self.field.bind(name, self)",
    "docstring": "attach filter to filterset\n\n        gives a name to use to extract arguments from querydict"
  },
  {
    "code": "def fetch(self):\n        params = values.of({})\n        payload = self._version.fetch(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return ExportInstance(self._version, payload, resource_type=self._solution['resource_type'], )",
    "docstring": "Fetch a ExportInstance\n\n        :returns: Fetched ExportInstance\n        :rtype: twilio.rest.preview.bulk_exports.export.ExportInstance"
  },
  {
    "code": "def hide(self, _unhide=False):\n        return self.reddit_session.hide(self.fullname, _unhide=_unhide)",
    "docstring": "Hide object in the context of the logged in user.\n\n        :param _unhide: If True, unhide the item instead.  Use\n            :meth:`~praw.objects.Hideable.unhide` instead of setting this\n            manually.\n\n        :returns: The json response from the server."
  },
  {
    "code": "def merge(self, paths):\n        topojson_binary = 'node_modules/bin/topojson'\n        if not os.path.exists(topojson_binary):\n            topojson_binary = 'topojson'\n        merge_cmd = '%(binary)s -o %(output_path)s --bbox -p -- %(paths)s' % {\n            'output_path': self.args.output_path,\n            'paths': ' '.join(paths),\n            'binary': topojson_binary\n        }\n        sys.stdout.write('Merging layers\\n')\n        if self.args.verbose:\n            sys.stdout.write('  %s\\n' % merge_cmd)\n        r = envoy.run(merge_cmd)\n        if r.status_code != 0:\n            sys.stderr.write(r.std_err)",
    "docstring": "Merge data layers into a single topojson file."
  },
  {
    "code": "def load_projects(self):\n        server_config = Config.instance().get_section_config(\"Server\")\n        projects_path = os.path.expanduser(server_config.get(\"projects_path\", \"~/GNS3/projects\"))\n        os.makedirs(projects_path, exist_ok=True)\n        try:\n            for project_path in os.listdir(projects_path):\n                project_dir = os.path.join(projects_path, project_path)\n                if os.path.isdir(project_dir):\n                    for file in os.listdir(project_dir):\n                        if file.endswith(\".gns3\"):\n                            try:\n                                yield from self.load_project(os.path.join(project_dir, file), load=False)\n                            except (aiohttp.web_exceptions.HTTPConflict, NotImplementedError):\n                                pass\n        except OSError as e:\n            log.error(str(e))",
    "docstring": "Preload the list of projects from disk"
  },
  {
    "code": "def name(self) -> Optional[str]:\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params, 'name')",
    "docstring": "Returns name specified in Content-Disposition header or None\n        if missed or header is malformed."
  },
  {
    "code": "def router_id(self, **kwargs):\n        router_id = kwargs.pop('router_id')\n        rbridge_id = kwargs.pop('rbridge_id', '1')\n        callback = kwargs.pop('callback', self._callback)\n        rid_args = dict(rbridge_id=rbridge_id, router_id=router_id)\n        config = self._rbridge.rbridge_id_ip_rtm_config_router_id(**rid_args)\n        return callback(config)",
    "docstring": "Configures device's Router ID.\n\n        Args:\n            router_id (str): Router ID for the device.\n            rbridge_id (str): The rbridge ID of the device on which BGP will be\n                configured in a VCS fabric.\n            callback (function): A function executed upon completion of the\n                method.  The only parameter passed to `callback` will be the\n                ``ElementTree`` `config`.\n\n        Returns:\n            Return value of `callback`.\n\n        Raises:\n            KeyError: if `router_id` is not specified.\n\n        Examples:\n            >>> import pynos.device\n            >>> conn = ('10.24.39.211', '22')\n            >>> auth = ('admin', 'password')\n            >>> with pynos.device.Device(conn=conn, auth=auth) as dev:\n            ...     output = dev.system.router_id(router_id='10.24.39.211',\n            ...     rbridge_id='225')\n            ...     dev.system.router_id() # doctest: +IGNORE_EXCEPTION_DETAIL\n            Traceback (most recent call last):\n            KeyError"
  },
  {
    "code": "def title_line(text):\n    columns = shutil.get_terminal_size()[0]\n    start = columns // 2 - len(text) // 2\n    output = '='*columns + '\\n\\n' + \\\n            ' ' * start + str(text) + \"\\n\\n\" + \\\n            '='*columns + '\\n'\n    return output",
    "docstring": "Returns a string that represents the\n    text as a title blurb"
  },
  {
    "code": "def compress(samples, run_parallel):\n    to_cram = []\n    finished = []\n    for data in [x[0] for x in samples]:\n        if \"cram\" in dd.get_archive(data) or \"cram-lossless\" in dd.get_archive(data):\n            to_cram.append([data])\n        else:\n            finished.append([data])\n    crammed = run_parallel(\"archive_to_cram\", to_cram)\n    return finished + crammed",
    "docstring": "Perform compression of output files for long term storage."
  },
  {
    "code": "def groups_setPurpose(self, *, channel: str, purpose: str, **kwargs) -> SlackResponse:\n        kwargs.update({\"channel\": channel, \"purpose\": purpose})\n        return self.api_call(\"groups.setPurpose\", json=kwargs)",
    "docstring": "Sets the purpose for a private channel.\n\n        Args:\n            channel (str): The channel id. e.g. 'G1234567890'\n            purpose (str): The new purpose for the channel. e.g. 'My Purpose'"
  },
  {
    "code": "def calc_login_v1(self):\n    der = self.parameters.derived.fastaccess\n    flu = self.sequences.fluxes.fastaccess\n    log = self.sequences.logs.fastaccess\n    for idx in range(der.nmb):\n        for jdx in range(der.ma_order[idx]-2, -1, -1):\n            log.login[idx, jdx+1] = log.login[idx, jdx]\n    for idx in range(der.nmb):\n        log.login[idx, 0] = flu.qpin[idx]",
    "docstring": "Refresh the input log sequence for the different MA processes.\n\n    Required derived parameters:\n      |Nmb|\n      |MA_Order|\n\n    Required flux sequence:\n      |QPIn|\n\n    Updated log sequence:\n      |LogIn|\n\n    Example:\n\n        Assume there are three response functions, involving one, two and\n        three MA coefficients respectively:\n\n        >>> from hydpy.models.arma import *\n        >>> parameterstep()\n        >>> derived.nmb(3)\n        >>> derived.ma_order.shape = 3\n        >>> derived.ma_order = 1, 2, 3\n        >>> fluxes.qpin.shape = 3\n        >>> logs.login.shape = (3, 3)\n\n        The \"memory values\" of the different MA processes are defined as\n        follows (one row for each process):\n\n        >>> logs.login = ((1.0, nan, nan),\n        ...               (2.0, 3.0, nan),\n        ...               (4.0, 5.0, 6.0))\n\n        These are the new inflow discharge portions to be included into\n        the memories of the different processes:\n\n        >>> fluxes.qpin = 7.0, 8.0, 9.0\n\n        Through applying method |calc_login_v1| all values already\n        existing are shifted to the right (\"into the past\").  Values,\n        which are no longer required due to the limited order or the\n        different MA processes, are discarded.  The new values are\n        inserted in the first column:\n\n        >>> model.calc_login_v1()\n        >>> logs.login\n        login([[7.0, nan, nan],\n               [8.0, 2.0, nan],\n               [9.0, 4.0, 5.0]])"
  },
  {
    "code": "def aroon_down(data, period):\n    catch_errors.check_for_period_error(data, period)\n    period = int(period)\n    a_down = [((period -\n            list(reversed(data[idx+1-period:idx+1])).index(np.min(data[idx+1-period:idx+1]))) /\n            float(period)) * 100 for idx in range(period-1, len(data))]\n    a_down = fill_for_noncomputable_vals(data, a_down)\n    return a_down",
    "docstring": "Aroon Down.\n\n    Formula:\n    AROONDWN = (((PERIOD) - (PERIODS SINCE PERIOD LOW)) / (PERIOD)) * 100"
  },
  {
    "code": "def update(self):\n        if not os.path.isdir(os.path.join(self.path)):\n            os.makedirs(self.path)\n        if not os.path.isdir(os.path.join(self.path, 'refs')):\n            subprocess.check_output([\n                'git', 'clone', '--bare', self.repo_git, self.path\n            ])\n        self.run(['gc', '--auto', '--prune=all'])\n        self.run(['fetch', '-p', 'origin', '+refs/heads/*:refs/heads/*'])\n        self.run(['fetch', 'origin', '+refs/pull/*/head:refs/pull/*'])\n        self.run([\n            'fetch', 'origin', '+refs/merge-requests/*/head:refs/pull/*'])",
    "docstring": "Get a repository git or update it"
  },
  {
    "code": "def _format_pair_with_equals(explode, separator, escape, key, value):\n    if not value:\n        return key + '='\n    return _format_pair(explode, separator, escape, key, value)",
    "docstring": "Format a key, value pair including the equals sign\n    when there is no value"
  },
  {
    "code": "def rastrigin(self, x):\n        if not isscalar(x[0]):\n            N = len(x[0])\n            return [10 * N + sum(xi**2 - 10 * np.cos(2 * np.pi * xi)) for xi in x]\n        N = len(x)\n        return 10 * N + sum(x**2 - 10 * np.cos(2 * np.pi * x))",
    "docstring": "Rastrigin test objective function"
  },
  {
    "code": "def fix_attr_encoding(ds):\n    def _maybe_del_attr(da, attr):\n        if attr in da.attrs:\n            del da.attrs[attr]\n        return da\n    def _maybe_decode_attr(da, attr):\n        if (attr in da.attrs) and (type(da.attrs[attr] == bool)):\n            da.attrs[attr] = int(da.attrs[attr])\n        return da\n    for v in ds.data_vars:\n        da = ds[v]\n        da = _maybe_del_attr(da, 'scale_factor')\n        da = _maybe_del_attr(da, 'units')\n        da = _maybe_decode_attr(da, 'hydrocarbon')\n        da = _maybe_decode_attr(da, 'chemical')\n    if hasattr(ds, 'time'):\n        times = ds.time\n        times = _maybe_del_attr(times, 'units')\n    return ds",
    "docstring": "This is a temporary hot-fix to handle the way metadata is encoded\n    when we read data directly from bpch files. It removes the 'scale_factor'\n    and 'units' attributes we encode with the data we ingest, converts the\n    'hydrocarbon' and 'chemical' attribute to a binary integer instead of a\n    boolean, and removes the 'units' attribute from the \"time\" dimension since\n    that too is implicitly encoded.\n\n    In future versions of this library, when upstream issues in decoding\n    data wrapped in dask arrays is fixed, this won't be necessary and will be\n    removed."
  },
  {
    "code": "def prune(self):\n        target_user_ids = self.get_queryset().values_list('id', flat=True)\n        exclude_user_ids = SentDrip.objects.filter(date__lt=conditional_now(),\n                                                   drip=self.drip_model,\n                                                   user__id__in=target_user_ids)\\\n                                           .values_list('user_id', flat=True)\n        self._queryset = self.get_queryset().exclude(id__in=exclude_user_ids)",
    "docstring": "Do an exclude for all Users who have a SentDrip already."
  },
  {
    "code": "def get_data_by_hex_uuid_or_404(model, hex_uuid, kind=''):\n    uuid = UUID(hex_uuid)\n    bin_uuid = uuid.get_bytes()\n    instance = get_instance_by_bin_uuid(model, bin_uuid)\n    if not instance:\n        return abort(404)\n    return ins2dict(instance, kind)",
    "docstring": "Get instance data by uuid and kind. Raise 404 Not Found if there is no data.\n\n    This requires model has a `bin_uuid` column.\n\n    :param model: a string, model name in rio.models\n    :param hex_uuid: a hex uuid string in 24-bytes human-readable representation.\n    :return: a dict."
  },
  {
    "code": "def _to_numpy(nd4j_array):\n    buff = nd4j_array.data()\n    address = buff.pointer().address()\n    dtype = get_context_dtype()\n    mapping = {\n        'double': ctypes.c_double,\n        'float': ctypes.c_float\n    }\n    Pointer = ctypes.POINTER(mapping[dtype])\n    pointer = ctypes.cast(address, Pointer)\n    np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape()))\n    return np_array",
    "docstring": "Convert nd4j array to numpy array"
  },
  {
    "code": "def delete(self):\n        params = {\"email\": self.email_address}\n        response = self._delete(\"/admins.json\", params=params)",
    "docstring": "Deletes the administrator from the account."
  },
  {
    "code": "def exit_frames(self):\n        if self._exit_frames is None:\n            exit_frames = []\n            for frame in self.frames:\n                if any(c.group != self for c in frame.children):\n                    exit_frames.append(frame)\n            self._exit_frames = exit_frames\n        return self._exit_frames",
    "docstring": "Returns a list of frames whose children include a frame outside of the group"
  },
  {
    "code": "def get_new_locations(self, urls):\n        seen = set(urls)\n        for i in urls:\n            for k in self.get_locations(i):\n                if k not in seen:\n                    seen.add(k)\n                    yield k",
    "docstring": "Get valid location header values for all given URLs.\n\n        The returned values are new, that is: they do not repeat any\n        value contained in the original input. Only unique values\n        are yielded.\n\n        :param urls: a list of URL addresses\n        :returns: valid location header values from responses\n        to the URLs"
  },
  {
    "code": "def service(self):\n        if not self._service:\n            self._service = self._client.service(id=self.service_id)\n        return self._service",
    "docstring": "Retrieve the `Service` object to which this execution is associated."
  },
  {
    "code": "def dataset_format_to_extension(ds_format):\n    try:\n        return DATASET_FORMATS[ds_format]\n    except KeyError:\n        raise ValueError(\n            \"dataset_format is expected to be one of %s. '%s' is not valid\"\n            % (\", \".join(DATASET_FORMATS.keys()), ds_format)\n        )",
    "docstring": "Get the preferred Dataset format extension\n\n    :param str ds_format: Format of the Dataset (expected to be one of `csv` or `xml`)\n    :rtype: str"
  },
  {
    "code": "def fai_from_bam(ref_file, bam_file, out_file, data):\n    contigs = set([x.contig for x in idxstats(bam_file, data)])\n    if not utils.file_uptodate(out_file, bam_file):\n        with open(ref.fasta_idx(ref_file, data[\"config\"])) as in_handle:\n            with file_transaction(data, out_file) as tx_out_file:\n                with open(tx_out_file, \"w\") as out_handle:\n                    for line in (l for l in in_handle if l.strip()):\n                        if line.split()[0] in contigs:\n                            out_handle.write(line)\n    return out_file",
    "docstring": "Create a fai index with only contigs in the input BAM file."
  },
  {
    "code": "def package_manager_owns(self, dist):\n        if dist.location.lower() == get_python_lib().lower():\n            filename = os.path.join(dist.location, dist.egg_name() + \".egg-info\")\n        else:\n            filename = dist.location\n        status, output = getstatusoutput(\"/usr/bin/acmefile -q %s\" % filename)\n        if status == 0:\n            return self.name\n        else:\n            return \"\"",
    "docstring": "Returns True if package manager 'owns' file\n        Returns False if package manager does not 'own' file\n\n        There is currently no way to determine if distutils or\n        setuptools installed a package. A future feature of setuptools\n        will make a package manifest which can be checked.\n           \n        'filename' must be the full path to file"
  },
  {
    "code": "def generate_routes(config):\n    routes = []\n    for name, config in iteritems(config):\n        pattern = r'^%s(?P<url>.*)$' % re.escape(config['prefix'].lstrip('/'))\n        proxy = generate_proxy(\n            prefix=config['prefix'], base_url=config['base_url'],\n            verify_ssl=config.get('verify_ssl', True),\n            middleware=config.get('middleware'),\n            append_middleware=config.get('append_middleware'),\n            cert=config.get('cert'),\n            timeout=config.get('timeout'))\n        proxy_view_function = proxy.as_view()\n        proxy_view_function.csrf_exempt = config.get('csrf_exempt', True)\n        routes.append(url(pattern, proxy_view_function, name=name))\n    return routes",
    "docstring": "Generate a list of urls that map to generated proxy views.\n\n    generate_routes({\n        'test_proxy': {\n            'base_url': 'https://google.com/',\n            'prefix': '/test_prefix/',\n            'verify_ssl': False,\n            'csrf_exempt: False',\n            'middleware': ['djproxy.proxy_middleware.AddXFF'],\n            'append_middleware': ['djproxy.proxy_middleware.AddXFF'],\n            'timeout': 3.0,\n            'cert': None\n        }\n    })\n\n    Required configuration keys:\n\n    * `base_url`\n    * `prefix`\n\n    Optional configuration keys:\n\n    * `verify_ssl`: defaults to `True`.\n    * `csrf_exempt`: defaults to `True`.\n    * `cert`: defaults to `None`.\n    * `timeout`: defaults to `None`.\n    * `middleware`: Defaults to `None`. Specifying `None` causes djproxy to use\n      the default middleware set. If a list is passed, the default middleware\n      list specified by the HttpProxy definition will be replaced with the\n      provided list.\n    * `append_middleware`: Defaults to `None`. `None` results in no changes to\n      the default middleware set. If a list is specified, the list will be\n      appended to the default middleware list specified in the HttpProxy\n      definition or, if provided, the middleware key specificed in the config\n      dict.\n\n    Returns:\n\n    [\n        url(r'^test_prefix/', GeneratedProxy.as_view(), name='test_proxy')),\n    ]"
  },
  {
    "code": "def AssertType(value, expected_type):\n  if not isinstance(value, expected_type):\n    message = \"Expected type `%r`, but got value `%r` of type `%s`\"\n    message %= (expected_type, value, type(value))\n    raise TypeError(message)",
    "docstring": "Ensures that given value has certain type.\n\n  Args:\n    value: A value to assert the type for.\n    expected_type: An expected type for the given value.\n\n  Raises:\n    TypeError: If given value does not have the expected type."
  },
  {
    "code": "def infer_len(node, context=None):\n    call = arguments.CallSite.from_call(node)\n    if call.keyword_arguments:\n        raise UseInferenceDefault(\"TypeError: len() must take no keyword arguments\")\n    if len(call.positional_arguments) != 1:\n        raise UseInferenceDefault(\n            \"TypeError: len() must take exactly one argument \"\n            \"({len}) given\".format(len=len(call.positional_arguments))\n        )\n    [argument_node] = call.positional_arguments\n    try:\n        return nodes.Const(helpers.object_len(argument_node, context=context))\n    except (AstroidTypeError, InferenceError) as exc:\n        raise UseInferenceDefault(str(exc)) from exc",
    "docstring": "Infer length calls\n\n    :param nodes.Call node: len call to infer\n    :param context.InferenceContext: node context\n    :rtype nodes.Const: a Const node with the inferred length, if possible"
  },
  {
    "code": "def count(self):\n        return (\n            self\n            .mapPartitions(lambda p: [sum(1 for _ in p)])\n            .reduce(operator.add)\n        )",
    "docstring": "Count elements per RDD.\n\n        Creates a new RDD stream where each RDD has a single entry that\n        is the count of the elements.\n\n        :rtype: DStream"
  },
  {
    "code": "def merge_values(values1,values2):\n    array1 = values_to_array(values1)\n    array2 = values_to_array(values2)\n    if array1.size == 0:\n        return array2\n    if array2.size == 0:\n        return array1\n    merged_array = []\n    for row_array1 in array1:\n        for row_array2 in array2:\n            merged_row = np.hstack((row_array1,row_array2))\n            merged_array.append(merged_row)\n    return np.atleast_2d(merged_array)",
    "docstring": "Merges two numpy arrays by calculating all possible combinations of rows"
  },
  {
    "code": "def read_mac(self):\n        mac0 = self.read_reg(self.ESP_OTP_MAC0)\n        mac1 = self.read_reg(self.ESP_OTP_MAC1)\n        mac3 = self.read_reg(self.ESP_OTP_MAC3)\n        if (mac3 != 0):\n            oui = ((mac3 >> 16) & 0xff, (mac3 >> 8) & 0xff, mac3 & 0xff)\n        elif ((mac1 >> 16) & 0xff) == 0:\n            oui = (0x18, 0xfe, 0x34)\n        elif ((mac1 >> 16) & 0xff) == 1:\n            oui = (0xac, 0xd0, 0x74)\n        else:\n            raise FatalError(\"Unknown OUI\")\n        return oui + ((mac1 >> 8) & 0xff, mac1 & 0xff, (mac0 >> 24) & 0xff)",
    "docstring": "Read MAC from OTP ROM"
  },
  {
    "code": "def assign_literal(element, value):\n        u\n        helper = helpers.CAST_DICT.get(type(value), str)\n        element.clear()\n        element.text = helper(value)",
    "docstring": "u\"\"\"Assigns a literal.\n\n        If a given node doesn't exist, it will be created.\n\n        :param etree.Element element: element to which we assign.\n        :param value: the value to assign"
  },
  {
    "code": "def return_on_initial_capital(capital, period_pl, leverage=None):\n    if capital <= 0:\n        raise ValueError('cost must be a positive number not %s' % capital)\n    leverage = leverage or 1.\n    eod = capital + (leverage * period_pl.cumsum())\n    ltd_rets = (eod / capital) - 1.\n    dly_rets = ltd_rets\n    dly_rets.iloc[1:] = (1. + ltd_rets).pct_change().iloc[1:]\n    return dly_rets",
    "docstring": "Return the daily return series based on the capital"
  },
  {
    "code": "def types_(self, col: str) -> pd.DataFrame:\n        cols = self.df.columns.values\n        all_types = {}\n        for col in cols:\n            local_types = []\n            for i, val in self.df[col].iteritems():\n                t = type(val).__name__\n                if t not in local_types:\n                    local_types.append(t)\n            all_types[col] = (local_types, i)\n        df = pd.DataFrame(all_types, index=[\"type\", \"num\"])\n        return df",
    "docstring": "Display types of values in a column\n\n        :param col: column name\n        :type col: str\n        :return: a pandas dataframe\n        :rtype: pd.DataFrame\n\n        :example: ``ds.types_(\"Col 1\")``"
  },
  {
    "code": "def transform(self, data):\n        if not self._get(\"fitted\"):\n            raise RuntimeError(\"`transform` called before `fit` or `fit_transform`.\")\n        data = data.copy()\n        output_column_prefix = self._get(\"output_column_prefix\")\n        if output_column_prefix is None:\n            prefix = \"\"\n        else:\n            prefix = output_column_prefix + '.'\n        transform_function = self._get(\"transform_function\")\n        feature_columns = self._get(\"features\")\n        feature_columns = _internal_utils.select_feature_subset(data, feature_columns)\n        for f in feature_columns:\n            data[prefix + f] = transform_function(data[f])\n        return data",
    "docstring": "Transforms the data."
  },
  {
    "code": "def create_tag(self, tag_name):\n        self.create()\n        self.ensure_working_tree()\n        logger.info(\"Creating tag '%s' in %s ..\", tag_name, format_path(self.local))\n        self.context.execute(*self.get_create_tag_command(tag_name))",
    "docstring": "Create a new tag based on the working tree's revision.\n\n        :param tag_name: The name of the tag to create (a string)."
  },
  {
    "code": "def get_race(self, row, division):\n        office = self.get_office(row, division)\n        try:\n            return election.Race.objects.get(\n                office=office,\n                cycle__name=row[\"electiondate\"].split(\"-\")[0],\n                special=(\n                    (row[\"seatnum\"] == (\"2\") and office.body.slug == \"senate\")\n                    or (\n                        \"Class II\" in row.get(\"description\", \"\")\n                        and office.body.slug == \"senate\"\n                    )\n                    or (row[\"racetype\"].startswith(\"Special\"))\n                ),\n            )\n        except ObjectDoesNotExist:\n            print(\n                \"Could not find race for {} {}\".format(\n                    row[\"electiondate\"].split(\"-\")[0], office.label\n                )\n            )",
    "docstring": "Gets the Race object for the given row of election results.\n\n        In order to get the race, we must know the office. This function\n        will get the office as well.\n\n        The only way to know if a Race is a special is based on the string\n        of the `racetype` field from the AP data."
  },
  {
    "code": "def is_vert_aligned(c):\n    return all(\n        [\n            _to_span(c[i]).sentence.is_visual()\n            and bbox_vert_aligned(\n                bbox_from_span(_to_span(c[i])), bbox_from_span(_to_span(c[0]))\n            )\n            for i in range(len(c))\n        ]\n    )",
    "docstring": "Return true if all the components of c are vertically aligned.\n\n    Vertical alignment means that the bounding boxes of each Mention of c\n    shares a similar x-axis value in the visual rendering of the document.\n\n    :param c: The candidate to evaluate\n    :rtype: boolean"
  },
  {
    "code": "def _send_pub(self, load):\n        for transport, opts in iter_transport_opts(self.opts):\n            chan = salt.transport.server.PubServerChannel.factory(opts)\n            chan.publish(load)",
    "docstring": "Take a load and send it across the network to connected minions"
  },
  {
    "code": "def render(self):\n        engine = Engine()\n        return engine.from_string(SUMMARY_TEMPLATE).render(Context(self.__dict__))",
    "docstring": "Render the summary."
  },
  {
    "code": "def describe_table(self, tablename):\n        try:\n            response = self.call(\n                'describe_table', TableName=tablename)['Table']\n            return Table.from_response(response)\n        except DynamoDBError as e:\n            if e.kwargs['Code'] == 'ResourceNotFoundException':\n                return None\n            else:\n                raise",
    "docstring": "Get the details about a table\n\n        Parameters\n        ----------\n        tablename : str\n            Name of the table\n\n        Returns\n        -------\n        table : :class:`~dynamo3.fields.Table`"
  },
  {
    "code": "def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,\n                group_keys=True, squeeze=False, observed=False, **kwargs):\n        from pandas.core.groupby.groupby import groupby\n        if level is None and by is None:\n            raise TypeError(\"You have to supply one of 'by' and 'level'\")\n        axis = self._get_axis_number(axis)\n        return groupby(self, by=by, axis=axis, level=level, as_index=as_index,\n                       sort=sort, group_keys=group_keys, squeeze=squeeze,\n                       observed=observed, **kwargs)",
    "docstring": "Group DataFrame or Series using a mapper or by a Series of columns.\n\n        A groupby operation involves some combination of splitting the\n        object, applying a function, and combining the results. This can be\n        used to group large amounts of data and compute operations on these\n        groups.\n\n        Parameters\n        ----------\n        by : mapping, function, label, or list of labels\n            Used to determine the groups for the groupby.\n            If ``by`` is a function, it's called on each value of the object's\n            index. If a dict or Series is passed, the Series or dict VALUES\n            will be used to determine the groups (the Series' values are first\n            aligned; see ``.align()`` method). If an ndarray is passed, the\n            values are used as-is determine the groups. A label or list of\n            labels may be passed to group by the columns in ``self``. Notice\n            that a tuple is interpreted a (single) key.\n        axis : {0 or 'index', 1 or 'columns'}, default 0\n            Split along rows (0) or columns (1).\n        level : int, level name, or sequence of such, default None\n            If the axis is a MultiIndex (hierarchical), group by a particular\n            level or levels.\n        as_index : bool, default True\n            For aggregated output, return object with group labels as the\n            index. Only relevant for DataFrame input. as_index=False is\n            effectively \"SQL-style\" grouped output.\n        sort : bool, default True\n            Sort group keys. Get better performance by turning this off.\n            Note this does not influence the order of observations within each\n            group. Groupby preserves the order of rows within each group.\n        group_keys : bool, default True\n            When calling apply, add group keys to index to identify pieces.\n        squeeze : bool, default False\n            Reduce the dimensionality of the return type if possible,\n            otherwise return a consistent type.\n        observed : bool, default False\n            This only applies if any of the groupers are Categoricals.\n            If True: only show observed values for categorical groupers.\n            If False: show all values for categorical groupers.\n\n            .. versionadded:: 0.23.0\n\n        **kwargs\n            Optional, only accepts keyword argument 'mutated' and is passed\n            to groupby.\n\n        Returns\n        -------\n        DataFrameGroupBy or SeriesGroupBy\n            Depends on the calling object and returns groupby object that\n            contains information about the groups.\n\n        See Also\n        --------\n        resample : Convenience method for frequency conversion and resampling\n            of time series.\n\n        Notes\n        -----\n        See the `user guide\n        <http://pandas.pydata.org/pandas-docs/stable/groupby.html>`_ for more.\n\n        Examples\n        --------\n        >>> df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',\n        ...                               'Parrot', 'Parrot'],\n        ...                    'Max Speed': [380., 370., 24., 26.]})\n        >>> df\n           Animal  Max Speed\n        0  Falcon      380.0\n        1  Falcon      370.0\n        2  Parrot       24.0\n        3  Parrot       26.0\n        >>> df.groupby(['Animal']).mean()\n                Max Speed\n        Animal\n        Falcon      375.0\n        Parrot       25.0\n\n        **Hierarchical Indexes**\n\n        We can groupby different levels of a hierarchical index\n        using the `level` parameter:\n\n        >>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],\n        ...           ['Captive', 'Wild', 'Captive', 'Wild']]\n        >>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))\n        >>> df = pd.DataFrame({'Max Speed': [390., 350., 30., 20.]},\n        ...                   index=index)\n        >>> df\n                        Max Speed\n        Animal Type\n        Falcon Captive      390.0\n               Wild         350.0\n        Parrot Captive       30.0\n               Wild          20.0\n        >>> df.groupby(level=0).mean()\n                Max Speed\n        Animal\n        Falcon      370.0\n        Parrot       25.0\n        >>> df.groupby(level=1).mean()\n                 Max Speed\n        Type\n        Captive      210.0\n        Wild         185.0"
  },
  {
    "code": "def update(self, docs=None, split=0, parallelism=None, progress_bar=True):\n        self.apply(\n            docs=docs,\n            split=split,\n            train=True,\n            clear=False,\n            parallelism=parallelism,\n            progress_bar=progress_bar,\n        )",
    "docstring": "Update the features of the specified candidates.\n\n        :param docs: If provided, apply features to all the candidates in these\n            documents.\n        :param split: If docs is None, apply features to the candidates in this\n            particular split.\n        :type split: int\n        :param parallelism: How many threads to use for extraction. This will\n            override the parallelism value used to initialize the Featurizer if\n            it is provided.\n        :type parallelism: int\n        :param progress_bar: Whether or not to display a progress bar. The\n            progress bar is measured per document.\n        :type progress_bar: bool"
  },
  {
    "code": "def start_in_oneshot_processes(obj, nb_process):\n    processes = []\n    for i in range(nb_process):\n        p = Process(target=oneshot_in_process, args=(obj,))\n        p.start()\n        processes.append(p)\n    for process in processes:\n        process.join()",
    "docstring": "Start nb_process processes to do the job. Then process finish the job they die."
  },
  {
    "code": "def change_state_id(self, state_id=None):\n        old_state_id = self.state_id\n        super(ContainerState, self).change_state_id(state_id)\n        for transition in self.transitions.values():\n            if transition.from_state == old_state_id:\n                transition._from_state = self.state_id\n            if transition.to_state == old_state_id:\n                transition._to_state = self.state_id\n        for data_flow in self.data_flows.values():\n            if data_flow.from_state == old_state_id:\n                data_flow._from_state = self.state_id\n            if data_flow.to_state == old_state_id:\n                data_flow._to_state = self.state_id",
    "docstring": "Changes the id of the state to a new id. This functions replaces the old state_id with the new state_id in all\n        data flows and transitions.\n\n        :param state_id: The new state if of the state"
  },
  {
    "code": "def _convert_status(self, msg):\n        code = msg.get_int()\n        text = msg.get_text()\n        if code == SFTP_OK:\n            return\n        elif code == SFTP_EOF:\n            raise EOFError(text)\n        elif code == SFTP_NO_SUCH_FILE:\n            raise IOError(errno.ENOENT, text)\n        elif code == SFTP_PERMISSION_DENIED:\n            raise IOError(errno.EACCES, text)\n        else:\n            raise IOError(text)",
    "docstring": "Raises EOFError or IOError on error status; otherwise does nothing."
  },
  {
    "code": "def wait(self):\n        while True:\n            if not self.greenlet_watch:\n                break\n            if self.stopping:\n                gevent.sleep(0.1)\n            else:\n                gevent.sleep(1)",
    "docstring": "Waits for the pool to be fully stopped"
  },
  {
    "code": "def add_usb_device_source(self, backend, id_p, address, property_names, property_values):\n        if not isinstance(backend, basestring):\n            raise TypeError(\"backend can only be an instance of type basestring\")\n        if not isinstance(id_p, basestring):\n            raise TypeError(\"id_p can only be an instance of type basestring\")\n        if not isinstance(address, basestring):\n            raise TypeError(\"address can only be an instance of type basestring\")\n        if not isinstance(property_names, list):\n            raise TypeError(\"property_names can only be an instance of type list\")\n        for a in property_names[:10]:\n            if not isinstance(a, basestring):\n                raise TypeError(\n                        \"array can only contain objects of type basestring\")\n        if not isinstance(property_values, list):\n            raise TypeError(\"property_values can only be an instance of type list\")\n        for a in property_values[:10]:\n            if not isinstance(a, basestring):\n                raise TypeError(\n                        \"array can only contain objects of type basestring\")\n        self._call(\"addUSBDeviceSource\",\n                     in_p=[backend, id_p, address, property_names, property_values])",
    "docstring": "Adds a new USB device source.\n\n        in backend of type str\n            The backend to use as the new device source.\n\n        in id_p of type str\n            Unique ID to identify the source.\n\n        in address of type str\n            Address to use, the format is dependent on the backend.\n            For USB/IP backends for example the notation is host[:port].\n\n        in property_names of type str\n            Array of property names for more detailed configuration. Not used at the moment.\n\n        in property_values of type str\n            Array of property values for more detailed configuration. Not used at the moment."
  },
  {
    "code": "def groupBy(self, f, numPartitions=None, partitionFunc=portable_hash):\n        return self.map(lambda x: (f(x), x)).groupByKey(numPartitions, partitionFunc)",
    "docstring": "Return an RDD of grouped items.\n\n        >>> rdd = sc.parallelize([1, 1, 2, 3, 5, 8])\n        >>> result = rdd.groupBy(lambda x: x % 2).collect()\n        >>> sorted([(x, sorted(y)) for (x, y) in result])\n        [(0, [2, 8]), (1, [1, 1, 3, 5])]"
  },
  {
    "code": "def get_route(self):\n        session = OAuth1Session(self.consumer_key,\n                                self.consumer_secret,\n                                access_token=self.session_token,\n                                access_token_secret=self.session_secret)\n        r = session.get(self.test_rest_url)\n        if r.status_code == 200 or r.status_code == 201:\n            if re.search('json', r.headers['content-type'], flags=0):\n                decoded = r.json()\n            else:\n                decoded = r.text\n            self.loci = decoded['loci']\n            self.profile = decoded['schemes']",
    "docstring": "Creates a session to find the URL for the loci and schemes"
  },
  {
    "code": "def put_file(self,\n                 name,\n                 filename,\n                 to_local_store=True,\n                 to_remote_store=True,\n                 compress_hint=True):\n        if not to_local_store and not to_remote_store:\n            raise ValueError(\"Neither to_local_store nor to_remote_store set \"\n                             \"in a call to filetracker.Client.put_file\")\n        check_name(name)\n        lock = None\n        if self.local_store:\n            lock = self.lock_manager.lock_for(name)\n            lock.lock_exclusive()\n        try:\n            if (to_local_store or not self.remote_store) and self.local_store:\n                versioned_name = self.local_store.add_file(name, filename)\n            if (to_remote_store or not self.local_store) and self.remote_store:\n                versioned_name = self.remote_store.add_file(\n                        name, filename, compress_hint=compress_hint)\n        finally:\n            if lock:\n                lock.close()\n        return versioned_name",
    "docstring": "Adds file ``filename`` to the filetracker under the name ``name``.\n\n           If the file already exists, a new version is created. In practice\n           if the store does not support versioning, the file is overwritten.\n\n           The file may be added to local store only (if ``to_remote_store`` is\n           ``False``), to remote store only (if ``to_local_store`` is\n           ``False``) or both. If only one store is configured, the values of\n           ``to_local_store`` and ``to_remote_store`` are ignored.\n\n           Local data store implemented in :class:`LocalDataStore` tries to not\n           directly copy the data to the final cache destination, but uses\n           hardlinking. Therefore you should not modify the file in-place\n           later as this would be disastrous.\n\n           If ``compress_hint`` is set to False, file is compressed on\n           the server, instead of the client. This is generally not\n           recommended, unless you know what you're doing."
  },
  {
    "code": "def data_chunk(data, chunk, with_overlap=False):\n    assert isinstance(chunk, tuple)\n    if len(chunk) == 2:\n        i, j = chunk\n    elif len(chunk) == 4:\n        if with_overlap:\n            i, j = chunk[:2]\n        else:\n            i, j = chunk[2:]\n    else:\n        raise ValueError(\"'chunk' should have 2 or 4 elements, \"\n                         \"not {0:d}\".format(len(chunk)))\n    return data[i:j, ...]",
    "docstring": "Get a data chunk."
  },
  {
    "code": "def _numbered_vowel_to_accented(vowel, tone):\n    if isinstance(tone, int):\n        tone = str(tone)\n    return _PINYIN_TONES[vowel + tone]",
    "docstring": "Convert a numbered Pinyin vowel to an accented Pinyin vowel."
  },
  {
    "code": "def data_size(self, live_data=None):\n        if live_data is not None:\n            warnings.warn(\"The 'live_data' keyword argument is deprecated.\",\n                          DeprecationWarning)\n        output = self.nodetool('info')[0]\n        return _get_load_from_info_output(output)",
    "docstring": "Uses `nodetool info` to get the size of a node's data in KB."
  },
  {
    "code": "def parse_href(href):\n    url = urlparse(href)\n    path = url.path.split('/')\n    collection_name = path[1]\n    id_ = path[2]\n    return collection_name, id_",
    "docstring": "Parses an Analyze Re href into collection name and ID"
  },
  {
    "code": "def pre_dispatch(self):\n        middleware = sort_by_priority(self)\n        return tuple(m.pre_dispatch for m in middleware if hasattr(m, 'pre_dispatch'))",
    "docstring": "List of pre-dispatch methods from registered middleware."
  },
  {
    "code": "def is_output(self, stream):\n        for streamer in self.streamers:\n            if streamer.selector.matches(stream):\n                return True\n        return False",
    "docstring": "Check if a stream is a sensor graph output.\n\n        Return:\n            bool"
  },
  {
    "code": "def _get_queue_types(fed_arrays, data_sources):\n    try:\n        return [data_sources[n].dtype for n in fed_arrays]\n    except KeyError as e:\n        raise ValueError(\"Array '{k}' has no data source!\"\n            .format(k=e.message)), None, sys.exc_info()[2]",
    "docstring": "Given a list of arrays to feed in fed_arrays, return\n    a list of associated queue types, obtained from tuples\n    in the data_sources dictionary"
  },
  {
    "code": "def find_results_gen(search_term, field='title'):\n    scan_params = make_query(search_term, querytype='AdvancedKeywordQuery')\n    search_result_ids = do_search(scan_params)\n    all_titles = []\n    for pdb_result in search_result_ids:\n        result= describe_pdb(pdb_result)\n        if field in result.keys():\n            yield result[field]",
    "docstring": "Return a generator of the results returned by a search of\n    the protein data bank. This generator is used internally.\n\n    Parameters\n    ----------\n\n    search_term : str\n        The search keyword\n\n    field : str\n        The type of information to record about each entry\n\n    Examples\n    --------\n\n    >>> result_gen = find_results_gen('bleb')\n    >>> pprint.pprint([item for item in result_gen][:5])\n    ['MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456Y BOUND WITH MGADP-BEFX',\n     'MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456Y BOUND WITH MGADP-ALF4',\n     'DICTYOSTELIUM DISCOIDEUM MYOSIN II MOTOR DOMAIN S456E WITH BOUND MGADP-BEFX',\n     'MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456E BOUND WITH MGADP-ALF4',\n     'The structural basis of blebbistatin inhibition and specificity for myosin '\n     'II']"
  },
  {
    "code": "def read_galaxy_amqp_config(galaxy_config, base_dir):\n    galaxy_config = add_full_path(galaxy_config, base_dir)\n    config = six.moves.configparser.ConfigParser()\n    config.read(galaxy_config)\n    amqp_config = {}\n    for option in config.options(\"galaxy_amqp\"):\n        amqp_config[option] = config.get(\"galaxy_amqp\", option)\n    return amqp_config",
    "docstring": "Read connection information on the RabbitMQ server from Galaxy config."
  },
  {
    "code": "def minutes(start, end=None):\n    return iterate.between(start, datetime.timedelta(minutes=1), end)",
    "docstring": "Iterate over the minutes between the given datetime_tzs.\n\n    Args:\n      start: datetime_tz to start from.\n      end: (Optional) Date to end at, if not given the iterator will never\n           terminate.\n\n    Returns:\n      An iterator which generates datetime_tz objects a minute apart."
  },
  {
    "code": "def tob(data, enc='utf8'):\n    return data.encode(enc) if isinstance(data, six.text_type) else bytes(data)",
    "docstring": "Convert anything to bytes"
  },
  {
    "code": "def wind_bft(ms):\n    \"Convert wind from metres per second to Beaufort scale\"\n    if ms is None:\n        return None\n    for bft in range(len(_bft_threshold)):\n        if ms < _bft_threshold[bft]:\n            return bft\n    return len(_bft_threshold)",
    "docstring": "Convert wind from metres per second to Beaufort scale"
  },
  {
    "code": "def save_csv(self, fd):\n        from pylon.io.excel import CSVWriter\n        CSVWriter(self).write(fd)",
    "docstring": "Saves the case as a series of Comma-Separated Values."
  },
  {
    "code": "def update_progress(self, progress, prefix=''):\n        total_length = 40\n        if progress == 1.:\n            sys.stderr.write('\\r' + ' ' * (total_length + len(prefix) + 50))\n            sys.stderr.write('\\n')\n            sys.stderr.flush()\n        else:\n            bar_length = int(round(total_length * progress))\n            sys.stderr.write('\\r%s [%s%s] %.1f %% '\n                             % (prefix, '=' * bar_length,\n                                ' ' * (total_length - bar_length),\n                                progress * 100))\n            sys.stderr.flush()",
    "docstring": "Print a progress bar for longer-running scripts.\n\n        The progress value is a value between 0.0 and 1.0. If a prefix is\n        present, it will be printed before the progress bar."
  },
  {
    "code": "def on_success(self, inv_plugin, emit_set_slot):\n        self.dirty = set()\n        self.apply(inv_plugin)\n        for changed_slot in self.dirty:\n            emit_set_slot(changed_slot)",
    "docstring": "Called when the click was successful\n        and should be applied to the inventory.\n\n        Args:\n            inv_plugin (InventoryPlugin): inventory plugin instance\n            emit_set_slot (func): function to signal a slot change,\n                should be InventoryPlugin().emit_set_slot"
  },
  {
    "code": "def create_cities_csv(filename=\"places2k.txt\", output=\"cities.csv\"):\n    with open(filename, 'r') as city_file:\n        with open(output, 'w') as out:\n            for line in city_file:\n                if line[0:2] == \"PR\":\n                    continue\n                out.write(\" \".join(line[9:72].split()[:-1]) + '\\n')",
    "docstring": "Takes the places2k.txt from USPS and creates a simple file of all cities."
  },
  {
    "code": "def _add_filters(self, **filters):\n        string_filters = filters.copy()\n        for key, value in filters.items():\n            is_extended = False\n            if isinstance(value, RedisField):\n                if (not isinstance(value, SingleValueField)\n                    or getattr(value, '_instance', None) is None):\n                    raise ValueError('If a field is used as a filter value, it '\n                                     'must be a simple value field attached to '\n                                     'an instance')\n                is_extended = True\n            elif isinstance(value, RedisModel):\n                is_extended = True\n            if is_extended:\n                if self._field_is_pk(key):\n                    raw_filter = RawFilter(key, value)\n                    self._lazy_collection['pks'].add(raw_filter)\n                else:\n                    index, suffix, extra_field_parts = self._parse_filter_key(key)\n                    parsed_filter = ParsedFilter(index, suffix, extra_field_parts, value)\n                    self._lazy_collection['sets'].append(parsed_filter)\n                string_filters.pop(key)\n        super(ExtendedCollectionManager, self)._add_filters(**string_filters)\n        return self",
    "docstring": "In addition to the normal _add_filters, this one accept RedisField objects\n        on the right part of a filter. The value will be fetched from redis when\n        calling the collection.\n        The filter value can also be a model instance, in which case its PK will\n        be fetched when calling the collection, too."
  },
  {
    "code": "def descend(self, remote, force=False):\n        remote_dirs = remote.split('/')\n        for directory in remote_dirs:\n            try:\n                self.conn.cwd(directory)\n            except Exception:\n                if force:\n                    self.conn.mkd(directory)\n                    self.conn.cwd(directory)\n        return self.conn.pwd()",
    "docstring": "Descend, possibly creating directories as needed"
  },
  {
    "code": "def cleanup_images(remove_old=False, **kwargs):\n    keep_tags = env.get('docker_keep_tags')\n    if keep_tags is not None:\n        kwargs.setdefault('keep_tags', keep_tags)\n    removed_images = docker_fabric().cleanup_images(remove_old=remove_old, **kwargs)\n    if kwargs.get('list_only'):\n        puts('Unused images:')\n        for image_name in removed_images:\n            fastprint(image_name, end='\\n')",
    "docstring": "Removes all images that have no name, and that are not references as dependency by any other named image. Similar\n    to the ``prune`` functionality in newer Docker versions, but supports more filters.\n\n    :param remove_old: Also remove images that do have a name, but no `latest` tag.\n    :type remove_old: bool"
  },
  {
    "code": "def channel_is_opened(\n            self,\n            participant1: Address,\n            participant2: Address,\n            block_identifier: BlockSpecification,\n            channel_identifier: ChannelID,\n    ) -> bool:\n        try:\n            channel_state = self._get_channel_state(\n                participant1=participant1,\n                participant2=participant2,\n                block_identifier=block_identifier,\n                channel_identifier=channel_identifier,\n            )\n        except RaidenRecoverableError:\n            return False\n        return channel_state == ChannelState.OPENED",
    "docstring": "Returns true if the channel is in an open state, false otherwise."
  },
  {
    "code": "def __list_uniques(self, date_range, field_name):\n        s = Search(using=self._es_conn, index=self._es_index)\n        s = s.filter('range', **date_range)\n        s = s[0:0]\n        s.aggs.bucket('uniques', 'terms', field=field_name, size=1000)\n        response = s.execute()\n        uniques_list = []\n        for item in response.aggregations.uniques.buckets:\n            uniques_list.append(item.key)\n        return uniques_list",
    "docstring": "Retrieve a list of unique values in a given field within a date range.\n\n        :param date_range:\n        :param field_name:\n        :return: list  of unique values."
  },
  {
    "code": "def prepare_hmet_lsm(self, lsm_data_var_map_array,\n                         hmet_ascii_output_folder=None,\n                         netcdf_file_path=None):\n        if self.l2g is None:\n            raise ValueError(\"LSM converter not loaded ...\")\n        with tmp_chdir(self.project_manager.project_directory):\n            self._update_simulation_end_from_lsm()\n            if netcdf_file_path is not None:\n                self.l2g.lsm_data_to_subset_netcdf(netcdf_file_path, lsm_data_var_map_array)\n                self._update_card(\"HMET_NETCDF\", netcdf_file_path, True)\n                self.project_manager.deleteCard('HMET_ASCII', self.db_session)\n            else:\n                if \"{0}\" in hmet_ascii_output_folder and \"{1}\" in hmet_ascii_output_folder:\n                    hmet_ascii_output_folder = hmet_ascii_output_folder.format(self.simulation_start.strftime(\"%Y%m%d%H%M\"),\n                                                                               self.simulation_end.strftime(\"%Y%m%d%H%M\"))\n                self.l2g.lsm_data_to_arc_ascii(lsm_data_var_map_array,\n                                               main_output_folder=os.path.join(self.gssha_directory,\n                                                                          hmet_ascii_output_folder))\n                self._update_card(\"HMET_ASCII\", os.path.join(hmet_ascii_output_folder, 'hmet_file_list.txt'), True)\n                self.project_manager.deleteCard('HMET_NETCDF', self.db_session)\n            self._update_gmt()",
    "docstring": "Prepares HMET data for GSSHA simulation from land surface model data.\n\n        Parameters:\n            lsm_data_var_map_array(str): Array with connections for LSM output and GSSHA input. See: :func:`~gsshapy.grid.GRIDtoGSSHA.`\n            hmet_ascii_output_folder(Optional[str]): Path to diretory to output HMET ASCII files. Mutually exclusice with netcdf_file_path. Default is None.\n            netcdf_file_path(Optional[str]): If you want the HMET data output as a NetCDF4 file for input to GSSHA. Mutually exclusice with hmet_ascii_output_folder. Default is None."
  },
  {
    "code": "def write_alias_config_hash(alias_config_hash='', empty_hash=False):\n        with open(GLOBAL_ALIAS_HASH_PATH, 'w') as alias_config_hash_file:\n            alias_config_hash_file.write('' if empty_hash else alias_config_hash)",
    "docstring": "Write self.alias_config_hash to the alias hash file.\n\n        Args:\n            empty_hash: True if we want to write an empty string into the file. Empty string in the alias hash file\n                means that we have to perform a full load of the command table in the next run."
  },
  {
    "code": "def decode(self, codes):\n        assert codes.ndim == 2\n        N, M = codes.shape\n        assert M == self.M\n        assert codes.dtype == self.code_dtype\n        vecs = np.empty((N, self.Ds * self.M), dtype=np.float32)\n        for m in range(self.M):\n            vecs[:, m * self.Ds : (m+1) * self.Ds] = self.codewords[m][codes[:, m], :]\n        return vecs",
    "docstring": "Given PQ-codes, reconstruct original D-dimensional vectors\n        approximately by fetching the codewords.\n\n        Args:\n            codes (np.ndarray): PQ-cdoes with shape=(N, M) and dtype=self.code_dtype.\n                Each row is a PQ-code\n\n        Returns:\n            np.ndarray: Reconstructed vectors with shape=(N, D) and dtype=np.float32"
  },
  {
    "code": "def remove_pending_work_units(self, work_spec_name, work_unit_names):\n        return self._remove_some_work_units(\n            work_spec_name, work_unit_names, priority_min=time.time())",
    "docstring": "Remove some work units in the pending list.\n\n        If `work_unit_names` is :const:`None` (which must be passed\n        explicitly), all pending work units in `work_spec_name` are\n        removed; otherwise only the specific named work units will be.\n\n        Note that this function has the potential to confuse workers\n        if they are actually working on the work units in question.  If\n        you have ensured that the workers are dead and you would be\n        otherwise waiting for the leases to expire before calling\n        :meth:`remove_available_work_units`, then this is a useful\n        shortcut.\n\n        :param str work_spec_name: name of the work spec\n        :param list work_unit_names: names of the work units, or\n          :const:`None` for all in `work_spec_name`\n        :return: number of work units removed"
  },
  {
    "code": "def do_unmute(self, sender, body, args):\n        if sender.get('MUTED'):\n            sender['MUTED'] = False\n            self.broadcast('%s has unmuted this chatroom' % (sender['NICK'],))\n            for msg in sender.get('QUEUED_MESSAGES', []):\n                self.send_message(msg, sender)\n            sender['QUEUED_MESSAGES'] = []\n        else:\n            self.send_message('you were not muted', sender)",
    "docstring": "Unmutes the chatroom for a user"
  },
  {
    "code": "def sparsify(dirname, output_every):\n    fnames = get_filenames(dirname)\n    output_every_old = get_output_every(dirname)\n    if output_every % output_every_old != 0:\n        raise ValueError('Directory with output_every={} cannot be coerced to'\n                         'desired new value.'.format(output_every_old))\n    keep_every = output_every // output_every_old\n    fnames_to_keep = fnames[::keep_every]\n    fnames_to_delete = set(fnames) - set(fnames_to_keep)\n    for fname in fnames_to_delete:\n        os.remove(fname)",
    "docstring": "Remove files from an output directory at regular interval, so as to\n    make it as if there had been more iterations between outputs. Can be used\n    to reduce the storage size of a directory.\n\n    If the new number of iterations between outputs is not an integer multiple\n    of the old number, then raise an exception.\n\n    Parameters\n    ----------\n    dirname: str\n        A path to a directory.\n    output_every: int\n        Desired new number of iterations between outputs.\n\n    Raises\n    ------\n    ValueError\n        The directory cannot be coerced into representing `output_every`."
  },
  {
    "code": "def _add_trustee(self, device):\n        device_name = get_device_info(device).name\n        if device_name in self.domain:\n            msg = 'Device: %r is already in this trust domain.' % device_name\n            raise DeviceAlreadyInTrustDomain(msg)\n        self._modify_trust(self.devices[0], self._get_add_trustee_cmd, device)",
    "docstring": "Add a single trusted device to the trust domain.\n\n        :param device: ManagementRoot object -- device to add to trust domain"
  },
  {
    "code": "def _setGroupNames(classes, classRename):\n    groups = {}\n    for groupName, glyphList in classes.items():\n        groupName = classRename.get(groupName, groupName)\n        if len(glyphList) == 1:\n            continue\n        groups[groupName] = glyphList\n    return groups",
    "docstring": "Set the final names into the groups."
  },
  {
    "code": "def _visible_in_diff(merge_result, context_lines=3):\n    i = old_line = new_line = 0\n    while i < len(merge_result):\n        line_or_conflict = merge_result[i]\n        if isinstance(line_or_conflict, tuple):\n            yield old_line, new_line, line_or_conflict\n            old_line += len(line_or_conflict[0])\n            new_line += len(line_or_conflict[1])\n        else:\n            for j in (list(range(max(0, i-context_lines), i                                        )) +\n                      list(range(i+1                    , min(len(merge_result), i+1+context_lines)))):\n                if isinstance(merge_result[j], tuple):\n                    yield old_line, new_line, line_or_conflict\n                    break\n            else:\n                yield None\n            old_line += 1\n            new_line += 1\n        i += 1\n    yield None",
    "docstring": "Collects the set of lines that should be visible in a diff with a certain number of context lines"
  },
  {
    "code": "def datetimes(self):\n        if self._timestamps_data is None:\n            self._calculate_timestamps()\n        return tuple(DateTime.from_moy(moy, self.is_leap_year)\n                     for moy in self._timestamps_data)",
    "docstring": "A sorted list of datetimes in this analysis period."
  },
  {
    "code": "def on_close(self, ws):\n        log.debug(\"Closing WebSocket connection with {}\".format(self.url))\n        if self.keepalive and self.keepalive.is_alive():\n            self.keepalive.do_run = False\n            self.keepalive.join()",
    "docstring": "Called when websocket connection is closed"
  },
  {
    "code": "def parsyfiles_global_config(multiple_errors_tb_limit: int = None, full_paths_in_logs: bool = None, \n                             dict_to_object_subclass_limit: int = None):\n    if multiple_errors_tb_limit is not None:\n        GLOBAL_CONFIG.multiple_errors_tb_limit = multiple_errors_tb_limit\n    if full_paths_in_logs is not None:\n        GLOBAL_CONFIG.full_paths_in_logs = full_paths_in_logs\n    if dict_to_object_subclass_limit is not None:\n        GLOBAL_CONFIG.dict_to_object_subclass_limit = dict_to_object_subclass_limit",
    "docstring": "This is the method you should use to configure the parsyfiles library\n\n    :param multiple_errors_tb_limit: the traceback size (default is 3) of individual parsers exceptions displayed when\n    parsyfiles tries several parsing chains and all of them fail.\n    :param full_paths_in_logs: if True, full file paths will be displayed in logs. Otherwise only the parent path will\n    be displayed and children paths will be indented (default is False)\n    :param dict_to_object_subclass_limit: the number of subclasses that the <dict_to_object> converter will try, when \n    instantiating an object from a dictionary. Default is 50\n    :return:"
  },
  {
    "code": "def pop_stream(cache, user_id):\n    stack = cache.get(user_id)\n    if stack is None:\n        return None\n    result = stack.pop()\n    if len(stack) == 0:\n        cache.delete(user_id)\n    else:\n        cache.set(user_id, stack)\n    return result",
    "docstring": "Pop an item off the stack in the cache. If stack\n    is empty after pop, it deletes the stack.\n\n    :param cache: werkzeug BasicCache-like object\n    :param user_id: id of user, used as key in cache\n\n    :return: top item from stack, otherwise None"
  },
  {
    "code": "def remove_tenant_user(request, project=None, user=None, domain=None):\n    client = keystoneclient(request, admin=True)\n    roles = client.roles.roles_for_user(user, project)\n    for role in roles:\n        remove_tenant_user_role(request, user=user, role=role.id,\n                                project=project, domain=domain)",
    "docstring": "Removes all roles from a user on a tenant, removing them from it."
  },
  {
    "code": "def is_dynamo_value(value):\n    if not isinstance(value, dict) or len(value) != 1:\n        return False\n    subkey = six.next(six.iterkeys(value))\n    return subkey in TYPES_REV",
    "docstring": "Returns True if the value is a Dynamo-formatted value"
  },
  {
    "code": "def get_message_plain_text(msg: Message):\n    if msg.body:\n        return msg.body\n    if BeautifulSoup is None or not msg.html:\n        return msg.html\n    plain_text = '\\n'.join(line.strip() for line in\n                           BeautifulSoup(msg.html, 'lxml').text.splitlines())\n    return re.sub(r'\\n\\n+', '\\n\\n', plain_text).strip()",
    "docstring": "Converts an HTML message to plain text.\n\n    :param msg: A :class:`~flask_mail.Message`\n    :return: The plain text message."
  },
  {
    "code": "def add_to_package_package_tree(self, root, node_path, pkgnode):\n        if node_path:\n            ptr = root\n            for node in node_path[:-1]:\n                ptr = ptr.children.setdefault(node, GroupNode(dict()))\n            ptr.children[node_path[-1]] = pkgnode\n        else:\n            if root.children:\n                raise PackageException(\"Attempting to overwrite root node of a non-empty package.\")\n            root.children = pkgnode.children.copy()",
    "docstring": "Adds a package or sub-package tree from an existing package to this package's\n        contents."
  },
  {
    "code": "def My_TreeTable(self, table, heads, heads2=None):\n        self.Define_TreeTable(heads, heads2)\n        self.Display_TreeTable(table)",
    "docstring": "Define and display a table\n            in which the values in first column form one or more trees."
  },
  {
    "code": "def exec_module(self, module):\n        global MAIN_MODULE_NAME\n        if module.__name__ == MAIN_MODULE_NAME:\n            module.__name__ = \"__main__\"\n            MAIN_MODULE_NAME = None\n        with open(self.filename) as f:\n            source = f.read()\n        if transforms.transformers:\n            source = transforms.transform(source)\n        else:\n            for line in source.split('\\n'):\n                if transforms.FROM_EXPERIMENTAL.match(line):\n                    source = transforms.transform(source)\n                    break\n        exec(source, vars(module))",
    "docstring": "import the source code, transforma it before executing it so that\n           it is known to Python."
  },
  {
    "code": "def modify_karma(self, words):\n        k = defaultdict(int)\n        if words:\n            for word_tuple in words:\n                word = word_tuple[0]\n                ending = word[-1]\n                change = -1 if ending == '-' else 1\n                if '-' in ending:\n                    word = word.rstrip('-')\n                elif '+' in ending:\n                    word = word.rstrip('+')\n                if word.startswith('(') and word.endswith(')'):\n                    word = word[1:-1]\n                word = word.strip()\n                if word:\n                    k[word] += change\n        return k",
    "docstring": "Given a regex object, look through the groups and modify karma\n        as necessary"
  },
  {
    "code": "def _convert_units(self):\n        self.m1 = self.m1*M_sun*ct.G/ct.c**2\n        self.m2 = self.m2*M_sun*ct.G/ct.c**2\n        initial_cond_type_conversion = {\n            'time': ct.c*ct.Julian_year,\n            'frequency': 1./ct.c,\n            'separation': ct.parsec,\n        }\n        self.initial_point = self.initial_point*initial_cond_type_conversion[self.initial_cond_type]\n        self.t_obs = self.t_obs*ct.c*ct.Julian_year\n        return",
    "docstring": "Convert units to geometrized units.\n\n        Change to G=c=1 (geometrized) units for ease in calculations."
  },
  {
    "code": "def childFactory(self, ctx, name):\n        try:\n            o = self.webapp.fromWebID(name)\n        except _WebIDFormatException:\n            return None\n        if o is None:\n            return None\n        return self.webViewer.wrapModel(o)",
    "docstring": "Return a shell page wrapped around the Item model described by the\n        webID, or return None if no such item can be found."
  },
  {
    "code": "def get_proc_name(cmd):\n    if isinstance(cmd, Iterable) and not isinstance(cmd, str):\n        cmd = \" \".join(cmd)\n    return cmd.split()[0].replace('(', '').replace(')', '')",
    "docstring": "Get the representative process name from complex command\n\n    :param str | list[str] cmd: a command to be processed\n    :return str: the basename representative command"
  },
  {
    "code": "def cudaMemcpy_htod(dst, src, count):\n    status = _libcudart.cudaMemcpy(dst, src,\n                                   ctypes.c_size_t(count),\n                                   cudaMemcpyHostToDevice)\n    cudaCheckStatus(status)",
    "docstring": "Copy memory from host to device.\n\n    Copy data from host memory to device memory.\n\n    Parameters\n    ----------\n    dst : ctypes pointer\n        Device memory pointer.\n    src : ctypes pointer\n        Host memory pointer.\n    count : int\n        Number of bytes to copy."
  },
  {
    "code": "def _setup_phantomjs(self, capabilities):\n        phantomjs_driver = self.config.get('Driver', 'phantomjs_driver_path')\n        self.logger.debug(\"Phantom driver path given in properties: %s\", phantomjs_driver)\n        return webdriver.PhantomJS(executable_path=phantomjs_driver, desired_capabilities=capabilities)",
    "docstring": "Setup phantomjs webdriver\n\n        :param capabilities: capabilities object\n        :returns: a new local phantomjs driver"
  },
  {
    "code": "def from_py_func(cls, func):\n        from bokeh.util.deprecation import deprecated\n        deprecated(\"'from_py_func' is deprecated and will be removed in an eventual 2.0 release. \"\n                   \"Use CustomJSFilter directly instead.\")\n        if not isinstance(func, FunctionType):\n            raise ValueError('CustomJSFilter.from_py_func only accepts function objects.')\n        pscript = import_required(\n            'pscript',\n            dedent(\n)\n            )\n        argspec = inspect.getargspec(func)\n        default_names = argspec.args\n        default_values = argspec.defaults or []\n        if len(default_names) - len(default_values) != 0:\n            raise ValueError(\"Function may only contain keyword arguments.\")\n        if default_values and not any(isinstance(value, Model) for value in default_values):\n            raise ValueError(\"Default value must be a plot object.\")\n        func_kwargs = dict(zip(default_names, default_values))\n        code = pscript.py2js(func, 'filter') + 'return filter(%s);\\n' % ', '.join(default_names)\n        return cls(code=code, args=func_kwargs)",
    "docstring": "Create a ``CustomJSFilter`` instance from a Python function. The\n        function is translated to JavaScript using PScript.\n\n        The ``func`` function namespace will contain the variable ``source``\n        at render time. This will be the data source associated with the ``CDSView``\n        that this filter is added to."
  },
  {
    "code": "def write(self, data):\n    block_remaining = _BLOCK_SIZE - self.__position % _BLOCK_SIZE\n    if block_remaining < _HEADER_LENGTH:\n      self.__writer.write('\\x00' * block_remaining)\n      self.__position += block_remaining\n      block_remaining = _BLOCK_SIZE\n    if block_remaining < len(data) + _HEADER_LENGTH:\n      first_chunk = data[:block_remaining - _HEADER_LENGTH]\n      self.__write_record(_RECORD_TYPE_FIRST, first_chunk)\n      data = data[len(first_chunk):]\n      while True:\n        block_remaining = _BLOCK_SIZE - self.__position % _BLOCK_SIZE\n        if block_remaining >= len(data) + _HEADER_LENGTH:\n          self.__write_record(_RECORD_TYPE_LAST, data)\n          break\n        else:\n          chunk = data[:block_remaining - _HEADER_LENGTH]\n          self.__write_record(_RECORD_TYPE_MIDDLE, chunk)\n          data = data[len(chunk):]\n    else:\n      self.__write_record(_RECORD_TYPE_FULL, data)",
    "docstring": "Write single record.\n\n    Args:\n      data: record data to write as string, byte array or byte sequence."
  },
  {
    "code": "def update(self, back=None):\n        back = self.backends(back)\n        for fsb in back:\n            fstr = '{0}.update'.format(fsb)\n            if fstr in self.servers:\n                log.debug('Updating %s fileserver cache', fsb)\n                self.servers[fstr]()",
    "docstring": "Update all of the enabled fileserver backends which support the update\n        function, or"
  },
  {
    "code": "def raise_thread_exception(thread_id, exception):\n    if current_platform == \"CPython\":\n        _raise_thread_exception_cpython(thread_id, exception)\n    else:\n        message = \"Setting thread exceptions (%s) is not supported for your current platform (%r).\"\n        exctype = (exception if inspect.isclass(exception) else type(exception)).__name__\n        logger.critical(message, exctype, current_platform)",
    "docstring": "Raise an exception in a thread.\n\n    Currently, this is only available on CPython.\n\n    Note:\n      This works by setting an async exception in the thread.  This means\n      that the exception will only get called the next time that thread\n      acquires the GIL.  Concretely, this means that this middleware can't\n      cancel system calls."
  },
  {
    "code": "def get_schema_descendant(\n            self, route: SchemaRoute) -> Optional[SchemaNode]:\n        node = self\n        for p in route:\n            node = node.get_child(*p)\n            if node is None:\n                return None\n        return node",
    "docstring": "Return descendant schema node or ``None`` if not found.\n\n        Args:\n            route: Schema route to the descendant node\n                   (relative to the receiver)."
  },
  {
    "code": "def _create_scsi_devices(scsi_devices):\n    keys = range(-1000, -1050, -1)\n    scsi_specs = []\n    if scsi_devices:\n        devs = [scsi['adapter'] for scsi in scsi_devices]\n        log.trace('Creating SCSI devices %s', devs)\n        for (key, scsi_controller) in zip(keys, scsi_devices):\n            scsi_spec = _apply_scsi_controller(scsi_controller['adapter'],\n                                               scsi_controller['type'],\n                                               scsi_controller['bus_sharing'],\n                                               key,\n                                               scsi_controller['bus_number'],\n                                               'add')\n            scsi_specs.append(scsi_spec)\n    return scsi_specs",
    "docstring": "Returns a list of vim.vm.device.VirtualDeviceSpec objects representing\n    SCSI controllers\n\n    scsi_devices:\n        List of SCSI device properties"
  },
  {
    "code": "def pct_negative(self, threshold=0.0):\n        return np.count_nonzero(self[self < threshold]) / self.count()",
    "docstring": "Pct. of periods in which `self` is less than `threshold.`\n\n        Parameters\n        ----------\n        threshold : {float, TSeries, pd.Series}, default 0.\n\n        Returns\n        -------\n        float"
  },
  {
    "code": "def astype(value, types=None):\n    if types is None:\n        types = int, float, asbool, bytes2str\n    for typ in types:\n        try:\n            return typ(value)\n        except (ValueError, AttributeError, TypeError, UnicodeEncodeError):\n            pass\n    return value",
    "docstring": "Return argument as one of types if possible.\n\n    >>> astype('42')\n    42\n    >>> astype('3.14')\n    3.14\n    >>> astype('True')\n    True\n    >>> astype(b'Neee-Wom')\n    'Neee-Wom'"
  },
  {
    "code": "def strip_tags(cls, html):\n        s = cls()\n        s.feed(html)\n        return s.get_data()",
    "docstring": "This function may be used to remove HTML tags from data."
  },
  {
    "code": "def cache_dest(self, url, saltenv='base', cachedir=None):\n        proto = urlparse(url).scheme\n        if proto == '':\n            return url\n        if proto == 'salt':\n            url, senv = salt.utils.url.parse(url)\n            if senv:\n                saltenv = senv\n            return salt.utils.path.join(\n                self.opts['cachedir'],\n                'files',\n                saltenv,\n                url.lstrip('|/'))\n        return self._extrn_path(url, saltenv, cachedir=cachedir)",
    "docstring": "Return the expected cache location for the specified URL and\n        environment."
  },
  {
    "code": "def _package_exists(path):\n    while path:\n        if os.path.exists(path):\n            return True\n        else:\n            path = os.path.dirname(path)\n    return False",
    "docstring": "Checks if the given Python path matches a valid file or a valid container\n    file\n\n    :param path: A Python path\n    :return: True if the module or its container exists"
  },
  {
    "code": "def index_template_absent(name):\n    ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}\n    try:\n        index_template = __salt__['elasticsearch.index_template_get'](name=name)\n        if index_template and name in index_template:\n            if __opts__['test']:\n                ret['comment'] = 'Index template {0} will be removed'.format(name)\n                ret['changes']['old'] = index_template[name]\n                ret['result'] = None\n            else:\n                ret['result'] = __salt__['elasticsearch.index_template_delete'](name=name)\n                if ret['result']:\n                    ret['comment'] = 'Successfully removed index template {0}'.format(name)\n                    ret['changes']['old'] = index_template[name]\n                else:\n                    ret['comment'] = 'Failed to remove index template {0} for unknown reasons'.format(name)\n        else:\n            ret['comment'] = 'Index template {0} is already absent'.format(name)\n    except Exception as err:\n        ret['result'] = False\n        ret['comment'] = six.text_type(err)\n    return ret",
    "docstring": "Ensure that the named index template is absent.\n\n    name\n        Name of the index to remove"
  },
  {
    "code": "def reverse_transform(self, tables, table_metas=None, missing=None):\n        if missing is None:\n            missing = self.missing\n        else:\n            self.missing = missing\n            warnings.warn(DEPRECATION_MESSAGE.format('reverse_transform'), DeprecationWarning)\n        reverse = {}\n        for table_name in tables:\n            table = tables[table_name]\n            if table_metas is None:\n                table_meta = self.table_dict[table_name][1]\n            else:\n                table_meta = table_metas[table_name]\n            reverse[table_name] = self.reverse_transform_table(table, table_meta)\n        return reverse",
    "docstring": "Transform data back to its original format.\n\n        Args:\n            tables(dict):   mapping of table names to `tuple` where each tuple is on the form\n                            (`pandas.DataFrame`, `dict`). The `DataFrame` contains the transformed\n                            data and the `dict` the corresponding meta information.\n                            If not specified, the tables will be retrieved using the meta_file.\n\n            table_metas(dict):  Full metadata file for the dataset.\n\n            missing(bool):      Wheter or not use NullTransformer to handle missing values.\n\n        Returns:\n            dict: Map from `str` (table_names) to `pandas.DataFrame` (transformed data)."
  },
  {
    "code": "def draw(self):\n        self.ax.plot(self.k_values_, self.k_scores_, marker=\"D\")\n        if self.locate_elbow and self.elbow_value_!=None:\n            elbow_label = \"$elbow\\ at\\ k={}, score={:0.3f}$\".format(self.elbow_value_, self.elbow_score_)\n            self.ax.axvline(self.elbow_value_, c=LINE_COLOR, linestyle=\"--\", label=elbow_label)\n        if self.timings:\n            self.axes = [self.ax, self.ax.twinx()]\n            self.axes[1].plot(\n                self.k_values_, self.k_timers_, label=\"fit time\",\n                c='g', marker=\"o\", linestyle=\"--\", alpha=0.75,\n            )\n        return self.ax",
    "docstring": "Draw the elbow curve for the specified scores and values of K."
  },
  {
    "code": "def exec_cmd(self, cmdstr):\n        parts = cmdstr.split()\n        if len(parts):\n            cmd, args = parts[0], parts[1:]\n            self._dispatch(cmd, args)\n        else:\n            pass",
    "docstring": "Parse line from CLI read loop and execute provided command"
  },
  {
    "code": "def _unpack(self, data):\n        msg_magic, msg_length, msg_type = self._unpack_header(data)\n        msg_size = self._struct_header_size + msg_length\n        payload = data[self._struct_header_size:msg_size]\n        return payload.decode('utf-8', 'replace')",
    "docstring": "Unpacks the given byte string and parses the result from JSON.\n        Returns None on failure and saves data into \"self.buffer\"."
  },
  {
    "code": "def ParseMultiple(self, result_dicts):\n    for result_dict in result_dicts:\n      kb_user = rdf_client.User()\n      for wmi_key, kb_key in iteritems(self.account_mapping):\n        try:\n          kb_user.Set(kb_key, result_dict[wmi_key])\n        except KeyError:\n          pass\n      if kb_user.sid or kb_user.username:\n        yield kb_user",
    "docstring": "Parse the WMI Win32_UserAccount output."
  },
  {
    "code": "def get_subscriptions(self, fetch=False):\n        return Subscriptions(\n            self.resource.subscriptions, self.client, populate=fetch)",
    "docstring": "Return this Wallet's subscriptions object, populating it if fetch is True."
  },
  {
    "code": "def create_symlink_job(directory, checksums, filetype, symlink_path):\n    pattern = NgdConfig.get_fileending(filetype)\n    filename, _ = get_name_and_checksum(checksums, pattern)\n    local_file = os.path.join(directory, filename)\n    full_symlink = os.path.join(symlink_path, filename)\n    return DownloadJob(None, local_file, None, full_symlink)",
    "docstring": "Create a symlink-creating DownloadJob for an already downloaded file."
  },
  {
    "code": "def _check_pcre_minions(self, expr, greedy):\n        reg = re.compile(expr)\n        return {'minions': [m for m in self._pki_minions() if reg.match(m)],\n                'missing': []}",
    "docstring": "Return the minions found by looking via regular expressions"
  },
  {
    "code": "def _handle_response_error(self, response, retries, **kwargs):\n        r\n        error = self._convert_response_to_error(response)\n        if error is None:\n            return response\n        max_retries = self._max_retries_for_error(error)\n        if max_retries is None or retries >= max_retries:\n            return response\n        backoff = min(0.0625 * 2 ** retries, 1.0)\n        self.logger.warning(\"Sleeping for %r before retrying failed request...\", backoff)\n        time.sleep(backoff)\n        retries += 1\n        self.logger.warning(\"Retrying failed request. Attempt %d/%d.\", retries, max_retries)\n        return self.request(retries=retries, **kwargs)",
    "docstring": "r\"\"\"Provides a way for each connection wrapper to handle error\n        responses.\n\n        Parameters:\n          response(Response): An instance of :class:`.requests.Response`.\n          retries(int): The number of times :meth:`.request` has been\n            called so far.\n          \\**kwargs: The parameters with which :meth:`.request` was\n            called.  The `retries` parameter is excluded from `kwargs`\n            intentionally.\n\n        Returns:\n          requests.Response"
  },
  {
    "code": "def random_uniform(mesh, shape, **kwargs):\n  shape = convert_to_shape(shape)\n  return RandomOperation(mesh, shape, tf.random.uniform, **kwargs).outputs[0]",
    "docstring": "Random uniform.\n\n  Args:\n    mesh: a Mesh\n    shape: a Shape\n    **kwargs: keyword args for tf.random.uniform, except seed\n\n  Returns:\n    a Tensor"
  },
  {
    "code": "def omit_wells(self, uwis=None):\n        if uwis is None:\n            raise ValueError('Must specify at least one uwi')\n        return Project([w for w in self if w.uwi not in uwis])",
    "docstring": "Returns a new project where wells with specified uwis have been omitted\n\n        Args: \n            uwis (list): list or tuple of UWI strings.\n\n        Returns: \n            project"
  },
  {
    "code": "def buscar(self, id_vlan):\n        if not is_valid_int_param(id_vlan):\n            raise InvalidParameterError(\n                u'Vlan id is invalid or was not informed.')\n        url = 'vlan/' + str(id_vlan) + '/'\n        code, xml = self.submit(None, 'GET', url)\n        return self.response(code, xml)",
    "docstring": "Get VLAN by its identifier.\n\n        :param id_vlan: VLAN identifier.\n\n        :return: Following dictionary:\n\n        ::\n\n          {'vlan': {'id': < id_vlan >,\n          'nome': < nome_vlan >,\n          'num_vlan': < num_vlan >,\n          'id_ambiente': < id_ambiente >,\n          'id_tipo_rede': < id_tipo_rede >,\n          'rede_oct1': < rede_oct1 >,\n          'rede_oct2': < rede_oct2 >,\n          'rede_oct3': < rede_oct3 >,\n          'rede_oct4': < rede_oct4 >,\n          'bloco': < bloco >,\n          'mascara_oct1': < mascara_oct1 >,\n          'mascara_oct2': < mascara_oct2 >,\n          'mascara_oct3': < mascara_oct3 >,\n          'mascara_oct4': < mascara_oct4 >,\n          'broadcast': < broadcast >,\n          'descricao': < descricao >,\n          'acl_file_name': < acl_file_name >,\n          'acl_valida': < acl_valida >,\n          'ativada': < ativada >}\n          OR {'id': < id_vlan >,\n          'nome': < nome_vlan >,\n          'num_vlan': < num_vlan >,\n          'id_tipo_rede': < id_tipo_rede >,\n          'id_ambiente': < id_ambiente >,\n          'bloco1': < bloco1 >,\n          'bloco2': < bloco2 >,\n          'bloco3': < bloco3 >,\n          'bloco4': < bloco4 >,\n          'bloco5': < bloco5 >,\n          'bloco6': < bloco6 >,\n          'bloco7': < bloco7 >,\n          'bloco8': < bloco8 >,\n          'bloco': < bloco >,\n          'mask_bloco1': < mask_bloco1 >,\n          'mask_bloco2': < mask_bloco2 >,\n          'mask_bloco3': < mask_bloco3 >,\n          'mask_bloco4': < mask_bloco4 >,\n          'mask_bloco5': < mask_bloco5 >,\n          'mask_bloco6': < mask_bloco6 >,\n          'mask_bloco7': < mask_bloco7 >,\n          'mask_bloco8': < mask_bloco8 >,\n          'broadcast': < broadcast >,\n          'descricao': < descricao >,\n          'acl_file_name': < acl_file_name >,\n          'acl_valida': < acl_valida >,\n          'acl_file_name_v6': < acl_file_name_v6 >,\n          'acl_valida_v6': < acl_valida_v6 >,\n          'ativada': < ativada >}}\n\n        :raise VlanNaoExisteError: VLAN does not exist.\n        :raise InvalidParameterError: VLAN id is none or invalid.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def serialize(v, known_modules=[]):\n    tname = name(v, known_modules=known_modules)\n    func = serializer(tname)\n    return func(v), tname",
    "docstring": "Get a text representation of an object."
  },
  {
    "code": "def dispatch_hook(cls, _pkt, _underlayer=None, *args, **kargs):\n        for klass in cls._payload_class:\n            if hasattr(klass, \"can_handle\") and \\\n                    klass.can_handle(_pkt, _underlayer):\n                return klass\n        print(\"DCE/RPC payload class not found or undefined (using Raw)\")\n        return Raw",
    "docstring": "dispatch_hook to choose among different registered payloads"
  },
  {
    "code": "def config_args(self, section='default'):\n        if sys.version_info >= (2, 7, 0):\n            parser = ConfigParser.SafeConfigParser(allow_no_value=True)\n        else:\n            parser = ConfigParser.SafeConfigParser()\n        parser.optionxform = str\n        args = {}\n        try:\n            parser.read(self.config_file)\n            for name, value in parser.items(section):\n                if any([value == 'False', value == 'false']):\n                    value = False\n                elif any([value == 'True', value == 'true']):\n                    value = True\n                else:\n                    value = utils.is_int(value=value)\n                args[name] = value\n        except Exception as exp:\n            self.log.warn('Section: [ %s ] Message: \"%s\"', section, exp)\n            return {}\n        else:\n            return args",
    "docstring": "Loop through the configuration file and set all of our values.\n\n        Note:\n          that anything can be set as a \"section\" in the argument file. If a\n          section does not exist an empty dict will be returned.\n\n\n        :param section: ``str``\n        :return: ``dict``"
  },
  {
    "code": "def nmltostring(nml):\n    if not isinstance(nml,dict):\n      raise ValueError(\"nml should be a dict !\")\n    curstr = \"\"\n    for key,group in nml.items():\n       namelist = [\"&\" + key]\n       for k, v in group.items():\n         if isinstance(v, list) or isinstance(v, tuple):\n           namelist.append(k + \" = \" + \",\".join(map(str, v)) + \",\")\n         elif is_string(v):\n           namelist.append(k + \" = '\" + str(v) + \"',\")\n         else:\n           namelist.append(k + \" = \" + str(v) + \",\")\n       namelist.append(\"/\")\n       curstr = curstr + \"\\n\".join(namelist) + \"\\n\"\n    return curstr",
    "docstring": "Convert a dictionary representing a Fortran namelist into a string."
  },
  {
    "code": "def _rollback_handle(cls, connection):\n        try:\n            connection.handle.rollback()\n        except snowflake.connector.errors.ProgrammingError as e:\n            msg = dbt.compat.to_string(e)\n            if 'Session no longer exists' not in msg:\n                raise",
    "docstring": "On snowflake, rolling back the handle of an aborted session raises\n        an exception."
  },
  {
    "code": "def OnLinkBitmap(self, event):\n        wildcard = \"*\"\n        message = _(\"Select bitmap for current cell\")\n        style = wx.OPEN | wx.CHANGE_DIR\n        filepath, __ = \\\n            self.grid.interfaces.get_filepath_findex_from_user(wildcard,\n                                                               message, style)\n        try:\n            bmp = wx.Bitmap(filepath)\n        except TypeError:\n            return\n        if bmp.Size == (-1, -1):\n            return\n        code = \"wx.Bitmap(r'{filepath}')\".format(filepath=filepath)\n        key = self.grid.actions.cursor\n        self.grid.actions.set_code(key, code)",
    "docstring": "Link bitmap event handler"
  },
  {
    "code": "def _wait_and_except_if_failed(self, event, timeout=None):\n        event.wait(timeout or self.__sync_timeout)\n        self._except_if_failed(event)",
    "docstring": "Combines waiting for event and call to `_except_if_failed`. If timeout is not specified the configured\n        sync_timeout is used."
  },
  {
    "code": "def create_group(self, group):\n        data = group.to_json()\n        response = self._do_request('POST', '/v2/groups', data=data)\n        return response.json()",
    "docstring": "Create and start a group.\n\n        :param :class:`marathon.models.group.MarathonGroup` group: the group to create\n\n        :returns: success\n        :rtype: dict containing the version ID"
  },
  {
    "code": "def __update_layer_density(self):\n        _stack = self.stack\n        _density_lock = self.density_lock\n        list_compound = _stack.keys()\n        for _key in list_compound:\n            if _density_lock[_key]:\n                continue\n            _list_ratio = _stack[_key]['stoichiometric_ratio']\n            _list_density = []\n            for _element in _stack[_key]['elements']:\n                _list_density.append(_stack[_key][_element]['density']['value'])\n                _compound_density = _utilities.get_compound_density(list_density=_list_density,\n                                                                    list_ratio=_list_ratio)\n            _stack[_key]['density']['value'] = _compound_density\n        self.stack = _stack",
    "docstring": "calculate or update the layer density"
  },
  {
    "code": "def _extract_features(self):\n        for parsed_line in self.parsed_lines:\n            if parsed_line.get('program') == 'sshd':\n                result = self._parse_auth_message(parsed_line['message'])\n                if 'ip' in result:\n                    self.features['ips'].append(result['ip'])\n                    if result['ip'] not in self.ips_to_pids:\n                        self.ips_to_pids[result['ip']] = [parsed_line['processid']]\n                    else:\n                        if parsed_line['processid'] not in self.ips_to_pids[result['ip']]:\n                            self.ips_to_pids[result['ip']].append(parsed_line['processid'])",
    "docstring": "Extracts and sets the feature data from the log file necessary for a reduction"
  },
  {
    "code": "def update(self, m_ag, reset=True, log=True):\n        if reset:\n            self.reset()\n        if len(array(m_ag).shape) == 1:\n            s = self.one_update(m_ag, log)\n        else:\n            s = []\n            for m in m_ag:\n                s.append(self.one_update(m, log))\n            s = array(s)\n        return s",
    "docstring": "Computes sensorimotor values from motor orders.\n\n        :param numpy.array m_ag: a motor command with shape (self.conf.m_ndims, ) or a set of n motor commands of shape (n, self.conf.m_ndims)\n\n        :param bool log: emit the motor and sensory values for logging purpose (default: True).\n\n        :returns: an array of shape (self.conf.ndims, ) or (n, self.conf.ndims) according to the shape of the m_ag parameter, containing the motor values (which can be different from m_ag, e.g. bounded according to self.conf.m_bounds) and the corresponding sensory values.\n\n        .. note:: self.conf.ndims = self.conf.m_ndims + self.conf.s_ndims is the dimensionality of the sensorimotor space (dim of the motor space + dim of the sensory space)."
  },
  {
    "code": "def orthogonal(*args) -> bool:\n    for i, arg in enumerate(args):\n        if hasattr(arg, \"shape\"):\n            args[i] = arg.shape\n    for s in zip(*args):\n        if np.product(s) != max(s):\n            return False\n    return True",
    "docstring": "Determine if a set of arrays are orthogonal.\n\n    Parameters\n    ----------\n    args : array-likes or array shapes\n\n    Returns\n    -------\n    bool\n        Array orthogonality condition."
  },
  {
    "code": "def db_remove(name, user=None, password=None, host=None, port=None, authdb=None):\n    conn = _connect(user, password, host, port, authdb=authdb)\n    if not conn:\n        return 'Failed to connect to mongo database'\n    try:\n        log.info('Removing database %s', name)\n        conn.drop_database(name)\n    except pymongo.errors.PyMongoError as err:\n        log.error('Removing database %s failed with error: %s', name, err)\n        return six.text_type(err)\n    return True",
    "docstring": "Remove a MongoDB database\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' mongodb.db_remove <name> <user> <password> <host> <port>"
  },
  {
    "code": "def is_valid(self, value):\n        if not self.is_array:\n            return self._valid(value)\n        if isinstance(value, (list, set, tuple)):\n            return all([self._valid(item) for item in value])\n        return self._valid(value)",
    "docstring": "Validate value before actual instance setting based on type.\n\n        Args:\n            value (object): The value object for validation.\n\n        Returns:\n            True if value validation succeeds else False."
  },
  {
    "code": "def default_number_converter(number_str):\n    is_int = (number_str.startswith('-') and number_str[1:].isdigit()) or number_str.isdigit()\n    return int(number_str) if is_int else float(number_str)",
    "docstring": "Converts the string representation of a json number into its python object equivalent, an\n    int, long, float or whatever type suits."
  },
  {
    "code": "def get_feeds_url(blog_page, root_page):\n    if root_page == blog_page:\n        return reverse('blog_page_feed')\n    else:\n        blog_path = strip_prefix_and_ending_slash(blog_page.specific.last_url_part)\n        return reverse('blog_page_feed_slug', kwargs={'blog_path': blog_path})",
    "docstring": "Get the feeds urls a blog page instance.\n    It will use an url or another depending if blog_page is the root page."
  },
  {
    "code": "def pks_from_objects(self, objects):\n        return {o.pk if isinstance(o, Model) else o for o in objects}",
    "docstring": "Extract all the primary key strings from the given objects.\n        Objects may be Versionables, or bare primary keys.\n\n        :rtype : set"
  },
  {
    "code": "def full_keywords(soup):\n    \"author keywords list including inline tags, such as italic\"\n    if not raw_parser.author_keywords(soup):\n        return []\n    return list(map(node_contents_str, raw_parser.author_keywords(soup)))",
    "docstring": "author keywords list including inline tags, such as italic"
  },
  {
    "code": "def clear(self):\n        for ax in self.flat_grid:\n            for im_h in ax.findobj(AxesImage):\n                im_h.remove()",
    "docstring": "Clears all the axes to start fresh."
  },
  {
    "code": "def last_year():\n        since, until = Date.this_year()\n        since = since.date - delta(years=1)\n        until = until.date - delta(years=1)\n        return Date(since), Date(until)",
    "docstring": "Return start and end date of the last fiscal year"
  },
  {
    "code": "def run(self):\n        self.info_log(\"The test batch is ready.\")\n        self.executed_tests = []\n        for test in self.tests:\n            localhost_instance = LocalhostInstance(\n                runner=self,\n                browser_config=self.browser_config,\n                test_name=test.Test.name\n            )\n            localhost_instance.startup()\n            with DbSessionContext(BROME_CONFIG['database']['mongo_database_name']) as session:\n                test_batch = session.query(Testbatch)\\\n                    .filter(Testbatch.mongo_id == self.test_batch_id).one()\n                test_batch.total_executing_tests = 1\n                session.save(test_batch, safe=True)\n            test_ = test.Test(\n                runner=self,\n                browser_config=self.browser_config,\n                name=test.Test.name,\n                test_batch_id=self.test_batch_id,\n                localhost_instance=localhost_instance,\n                index=1\n            )\n            test_.execute()\n            self.executed_tests.append(test_)\n            localhost_instance.tear_down()",
    "docstring": "Run the test batch"
  },
  {
    "code": "def _format_return_timestamps(self, return_timestamps=None):\n        if return_timestamps is None:\n            return_timestamps_array = np.arange(\n                self.components.initial_time(),\n                self.components.final_time() + self.components.saveper(),\n                self.components.saveper(), dtype=np.float64\n            )\n        elif inspect.isclass(range) and isinstance(return_timestamps, range):\n            return_timestamps_array = np.array(return_timestamps, ndmin=1)\n        elif isinstance(return_timestamps, (list, int, float, np.ndarray)):\n            return_timestamps_array = np.array(return_timestamps, ndmin=1)\n        elif isinstance(return_timestamps, _pd.Series):\n            return_timestamps_array = return_timestamps.as_matrix()\n        else:\n            raise TypeError('`return_timestamps` expects a list, array, pandas Series, '\n                            'or numeric value')\n        return return_timestamps_array",
    "docstring": "Format the passed in return timestamps value as a numpy array.\n        If no value is passed, build up array of timestamps based upon\n        model start and end times, and the 'saveper' value."
  },
  {
    "code": "def _gcd(a=None, b=None, terms=None):\n    if terms:\n        return reduce(lambda a, b: _gcd(a, b), terms)\n    else:\n        while b:\n            (a, b) = (b, a % b)\n        return a",
    "docstring": "Return greatest common divisor using Euclid's Algorithm."
  },
  {
    "code": "def decorate(self, record):\n        attachments = {}\n        if record.levelno >= logging.ERROR:\n            attachments['color'] = 'warning'\n        if record.levelno >= logging.CRITICAL:\n            attachments['color'] = 'danger'\n        attach_text = '{levelname}: {name} {module}.{funcName}:{lineno}'.format(\n            levelname=record.levelname,\n            name=record.name,\n            module=record.module,\n            funcName=record.funcName,\n            lineno=record.lineno\n        )\n        attachments['text'] = attach_text\n        attachments['fallback'] = attach_text\n        return attachments",
    "docstring": "add slack-specific flourishes to responses\n\n        https://api.slack.com/docs/message-attachments\n\n        Args:\n            record (:obj:`logging.record`): message to log\n\n        Returns:\n            (:obj:`dict`): attachments object for reporting"
  },
  {
    "code": "def _get_formatted_error(self, error):\n        def bits(n):\n            while n:\n                b = n & (~n+1)\n                yield b\n                n ^= b\n        stsReturn = self.m_objPCANBasic.GetErrorText(error, 0)\n        if stsReturn[0] != PCAN_ERROR_OK:\n            strings = []\n            for b in bits(error):\n                stsReturn = self.m_objPCANBasic.GetErrorText(b, 0)\n                if stsReturn[0] != PCAN_ERROR_OK:\n                    text = \"An error occurred. Error-code's text ({0:X}h) couldn't be retrieved\".format(error)\n                else:\n                    text = stsReturn[1].decode('utf-8', errors='replace')\n                strings.append(text)\n            complete_text = '\\n'.join(strings)\n        else:\n            complete_text = stsReturn[1].decode('utf-8', errors='replace')\n        return complete_text",
    "docstring": "Gets the text using the GetErrorText API function.\n        If the function call succeeds, the translated error is returned. If it fails,\n        a text describing the current error is returned. Multiple errors may\n        be present in which case their individual messages are included in the\n        return string, one line per error."
  },
  {
    "code": "def _convert_option(self):\n        if sys.byteorder == 'little' and self._endian() == 'big-endian':\n            order = '>'\n        elif sys.byteorder == 'big' and self._endian() == 'little-endian':\n            order = '<'\n        else:\n            order = '='\n        return order",
    "docstring": "Determines how to convert CDF byte ordering to the system\n        byte ordering."
  },
  {
    "code": "def validate(policy):\n    for param, value in policy.items():\n        if param not in ACCEPTED_SECURITY_TYPES.keys():\n            raise SecurityError('Invalid Security Parameter: {}'.format(param))\n        if type(value) != ACCEPTED_SECURITY_TYPES[param]:\n            raise SecurityError('Invalid Parameter Data Type for {}, '\n                                'Expecting: {} Received: {}'.format(\n                                    param, ACCEPTED_SECURITY_TYPES[param],\n                                    type(value)))",
    "docstring": "Validates a policy and its parameters and raises an error if invalid"
  },
  {
    "code": "def stop_replication(self, repl_id):\n        try:\n            repl_doc = self.database[repl_id]\n        except KeyError:\n            raise CloudantReplicatorException(404, repl_id)\n        repl_doc.fetch()\n        repl_doc.delete()",
    "docstring": "Stops a replication based on the provided replication id by deleting\n        the replication document from the replication database.  The\n        replication can only be stopped if it has not yet completed.  If it has\n        already completed then the replication document is still deleted from\n        replication database.\n\n        :param str repl_id: Replication id used to identify the replication to\n            stop."
  },
  {
    "code": "def instances(exp=\".*\"):\n    \"Filter list of machines matching an expression\"\n    expression = re.compile(exp)\n    instances = []\n    for node in ec2_instances():\n        if node.tags and ip(node):\n            try:\n                if expression.match(node.tags.get(\"Name\")):\n                    instances.append(node)\n            except TypeError:\n                pass\n    return instances",
    "docstring": "Filter list of machines matching an expression"
  },
  {
    "code": "def find_library_windows(cls):\n        dll = cls.get_appropriate_windows_sdk_name() + '.dll'\n        root = 'C:\\\\'\n        for d in os.listdir(root):\n            dir_path = os.path.join(root, d)\n            if d.startswith('Program Files') and os.path.isdir(dir_path):\n                dir_path = os.path.join(dir_path, 'SEGGER')\n                if not os.path.isdir(dir_path):\n                    continue\n                ds = filter(lambda x: x.startswith('JLink'), os.listdir(dir_path))\n                for jlink_dir in ds:\n                    lib_path = os.path.join(dir_path, jlink_dir, dll)\n                    if os.path.isfile(lib_path):\n                        yield lib_path",
    "docstring": "Loads the SEGGER DLL from the windows installation directory.\n\n        On Windows, these are found either under:\n          - ``C:\\\\Program Files\\\\SEGGER\\\\JLink``\n          - ``C:\\\\Program Files (x86)\\\\SEGGER\\\\JLink``.\n\n        Args:\n          cls (Library): the ``Library`` class\n\n        Returns:\n          The paths to the J-Link library files in the order that they are\n          found."
  },
  {
    "code": "def select(self, *cluster_ids):\n        if cluster_ids and isinstance(cluster_ids[0], (tuple, list)):\n            cluster_ids = list(cluster_ids[0]) + list(cluster_ids[1:])\n        cluster_ids = self._keep_existing_clusters(cluster_ids)\n        self.cluster_view.select(cluster_ids)",
    "docstring": "Select a list of clusters."
  },
  {
    "code": "def analysis_title_header_element(feature, parent):\n    _ = feature, parent\n    header = analysis_title_header['string_format']\n    return header.capitalize()",
    "docstring": "Retrieve analysis title header string from definitions."
  },
  {
    "code": "def subtract(self, number1, number2):\n        return self._format_result(int(number1) - int(number2))",
    "docstring": "Subtracts number2 from number1"
  },
  {
    "code": "def create_package(project, name, sourcefolder=None):\n    if sourcefolder is None:\n        sourcefolder = project.root\n    packages = name.split('.')\n    parent = sourcefolder\n    for package in packages[:-1]:\n        parent = parent.get_child(package)\n    made_packages = parent.create_folder(packages[-1])\n    made_packages.create_file('__init__.py')\n    return made_packages",
    "docstring": "Creates a package and returns a `rope.base.resources.Folder`"
  },
  {
    "code": "def versioned_static(file_path):\n    full_path = find(file_path)\n    url = static(file_path)\n    if type(full_path) is list and len(full_path) > 0:\n        full_path = full_path[0]\n    if not full_path:\n        msg = 'Could not find static file: {0}'.format(file_path)\n        logger.warning(msg)\n        return url\n    file_hash = md5()\n    with open(full_path, \"rb\") as file_contents:\n        for chunk in iter(lambda: file_contents.read(4096), b\"\"):\n            file_hash.update(chunk)\n    return url + '?v=' + file_hash.hexdigest()[:7]",
    "docstring": "Given the path for a static file\n    Output a url path with a hex has query string for versioning"
  },
  {
    "code": "def _write_min_norm(self, norms:[])->None:\n        \"Writes the minimum norm of the gradients to Tensorboard.\"\n        min_norm = min(norms)\n        self._add_gradient_scalar('min_norm', scalar_value=min_norm)",
    "docstring": "Writes the minimum norm of the gradients to Tensorboard."
  },
  {
    "code": "def write_terminator(buff, capacity, ver, length):\n    buff.extend([0] * min(capacity - length, consts.TERMINATOR_LENGTH[ver]))",
    "docstring": "\\\n    Writes the terminator.\n\n    :param buff: The byte buffer.\n    :param capacity: Symbol capacity.\n    :param ver: ``None`` if a QR Code is written, \"M1\", \"M2\", \"M3\", or \"M4\" if a\n            Micro QR Code is written.\n    :param length: Length of the data bit stream."
  },
  {
    "code": "def signature_required(secret_key_func):\n    def actual_decorator(obj):\n        def test_func(request, *args, **kwargs):\n            secret_key = secret_key_func(request, *args, **kwargs)\n            return validate_signature(request, secret_key)\n        decorator = request_passes_test(test_func)\n        return wrap_object(obj, decorator)\n    return actual_decorator",
    "docstring": "Requires that the request contain a valid signature to gain access\n    to a specified resource."
  },
  {
    "code": "def convert(self, argument):\n    if _is_integer_type(argument):\n      return argument\n    elif isinstance(argument, six.string_types):\n      base = 10\n      if len(argument) > 2 and argument[0] == '0':\n        if argument[1] == 'o':\n          base = 8\n        elif argument[1] == 'x':\n          base = 16\n      return int(argument, base)\n    else:\n      raise TypeError('Expect argument to be a string or int, found {}'.format(\n          type(argument)))",
    "docstring": "Returns the int value of argument."
  },
  {
    "code": "def get_grade_entry_lookup_session_for_gradebook(self, gradebook_id, proxy):\n        if not self.supports_grade_entry_lookup():\n            raise errors.Unimplemented()\n        return sessions.GradeEntryLookupSession(gradebook_id, proxy, self._runtime)",
    "docstring": "Gets the ``OsidSession`` associated with the grade entry lookup service for the given gradebook.\n\n        arg:    gradebook_id (osid.id.Id): the ``Id`` of the gradebook\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.grading.GradeEntryLookupSession) - ``a\n                GradeEntryLookupSession``\n        raise:  NotFound - ``gradebook_id`` not found\n        raise:  NullArgument - ``gradebook_id`` or ``proxy`` is ``null``\n        raise:  OperationFailed - ``unable to complete request``\n        raise:  Unimplemented - ``supports_grade_entry_lookup()`` or\n                ``supports_visible_federation()`` is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_grade_entry_lookup()`` and\n        ``supports_visible_federation()`` are ``true``.*"
  },
  {
    "code": "def measure_string(self, text, fontname, fontsize, encoding=0):\n        return _fitz.Tools_measure_string(self, text, fontname, fontsize, encoding)",
    "docstring": "Measure length of a string for a Base14 font."
  },
  {
    "code": "def show_prediction_labels_on_image(img_path, predictions):\n    pil_image = Image.open(img_path).convert(\"RGB\")\n    draw = ImageDraw.Draw(pil_image)\n    for name, (top, right, bottom, left) in predictions:\n        draw.rectangle(((left, top), (right, bottom)), outline=(0, 0, 255))\n        name = name.encode(\"UTF-8\")\n        text_width, text_height = draw.textsize(name)\n        draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=(0, 0, 255), outline=(0, 0, 255))\n        draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 255))\n    del draw\n    pil_image.show()",
    "docstring": "Shows the face recognition results visually.\n\n    :param img_path: path to image to be recognized\n    :param predictions: results of the predict function\n    :return:"
  },
  {
    "code": "def get_grade_system_lookup_session_for_gradebook(self, gradebook_id, proxy):\n        if not self.supports_grade_system_lookup():\n            raise errors.Unimplemented()\n        return sessions.GradeSystemLookupSession(gradebook_id, proxy, self._runtime)",
    "docstring": "Gets the ``OsidSession`` associated with the grade system lookup service for the given gradebook.\n\n        arg:    gradebook_id (osid.id.Id): the ``Id`` of the gradebook\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.grading.GradeSystemLookupSession) - ``a\n                GradeSystemLookupSession``\n        raise:  NotFound - ``gradebook_id`` not found\n        raise:  NullArgument - ``gradebook_id`` or ``proxy`` is ``null``\n        raise:  OperationFailed - ``unable to complete request``\n        raise:  Unimplemented - ``supports_grade_system_lookup()`` or\n                ``supports_visible_federation()`` is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_grade_system_lookup()`` and\n        ``supports_visible_federation()`` are ``true``.*"
  },
  {
    "code": "def get_editor_query(sql):\n    sql = sql.strip()\n    pattern = re.compile('(^\\\\\\e|\\\\\\e$)')\n    while pattern.search(sql):\n        sql = pattern.sub('', sql)\n    return sql",
    "docstring": "Get the query part of an editor command."
  },
  {
    "code": "def chk_goids(goids, msg=None, raise_except=True):\n    for goid in goids:\n        if not goid_is_valid(goid):\n            if raise_except:\n                raise RuntimeError(\"BAD GO({GO}): {MSG}\".format(GO=goid, MSG=msg))\n            else:\n                return goid",
    "docstring": "check that all GO IDs have the proper format."
  },
  {
    "code": "def logon():\n    content = {}\n    payload = \"<aaaLogin inName='{0}' inPassword='{1}'></aaaLogin>\".format(DETAILS['username'], DETAILS['password'])\n    r = __utils__['http.query'](DETAILS['url'],\n                                data=payload,\n                                method='POST',\n                                decode_type='plain',\n                                decode=True,\n                                verify_ssl=False,\n                                raise_error=False,\n                                status=True,\n                                headers=DETAILS['headers'])\n    _validate_response_code(r['status'])\n    answer = re.findall(r'(<[\\s\\S.]*>)', r['text'])[0]\n    items = ET.fromstring(answer)\n    for item in items.attrib:\n        content[item] = items.attrib[item]\n    if 'outCookie' not in content:\n        raise salt.exceptions.CommandExecutionError(\"Unable to log into proxy device.\")\n    return content['outCookie']",
    "docstring": "Logs into the cimc device and returns the session cookie."
  },
  {
    "code": "def hull_points(obj, qhull_options='QbB Pp'):\n    if hasattr(obj, 'convex_hull'):\n        return obj.convex_hull.vertices\n    initial = np.asanyarray(obj, dtype=np.float64)\n    if len(initial.shape) != 2:\n        raise ValueError('points must be (n, dimension)!')\n    hull = spatial.ConvexHull(initial, qhull_options=qhull_options)\n    points = hull.points[hull.vertices]\n    return points",
    "docstring": "Try to extract a convex set of points from multiple input formats.\n\n    Parameters\n    ---------\n    obj: Trimesh object\n         (n,d) points\n         (m,) Trimesh objects\n\n    Returns\n    --------\n    points: (o,d) convex set of points"
  },
  {
    "code": "def locateChild(self, context, segments):\n        shortcut = getattr(self, 'child_' + segments[0], None)\n        if shortcut:\n            res = shortcut(context)\n            if res is not None:\n                return res, segments[1:]\n        req = IRequest(context)\n        for plg in self.siteStore.powerupsFor(ISessionlessSiteRootPlugin):\n            spr = getattr(plg, 'sessionlessProduceResource', None)\n            if spr is not None:\n                childAndSegments = spr(req, segments)\n            else:\n                childAndSegments = plg.resourceFactory(segments)\n            if childAndSegments is not None:\n                return childAndSegments\n        return self.guardedRoot.locateChild(context, segments)",
    "docstring": "Return a statically defined child or a child defined by a sessionless\n        site root plugin or an avatar from guard."
  },
  {
    "code": "def print_stamp(self):\n        from . import VERSION\n        print_out = partial(self.print_out, format_options='red')\n        print_out('This configuration was automatically generated using')\n        print_out('uwsgiconf v%s on %s' % ('.'.join(map(str, VERSION)), datetime.now().isoformat(' ')))\n        return self",
    "docstring": "Prints out a stamp containing useful information,\n        such as what and when has generated this configuration."
  },
  {
    "code": "def get_object(self, queryset=None):\n        obj = super(EntryPreviewMixin, self).get_object(queryset)\n        if obj.is_visible:\n            return obj\n        if (self.request.user.has_perm('zinnia.can_view_all') or\n                self.request.user.pk in [\n                author.pk for author in obj.authors.all()]):\n            return obj\n        raise Http404(_('No entry found matching the query'))",
    "docstring": "If the status of the entry is not PUBLISHED,\n        a preview is requested, so we check if the user\n        has the 'zinnia.can_view_all' permission or if\n        it's an author of the entry."
  },
  {
    "code": "def calculate_partial_digest(username, realm, password):\n    return md5.md5(\"%s:%s:%s\" % (username.encode('utf-8'), realm, password.encode('utf-8'))).hexdigest()",
    "docstring": "Calculate a partial digest that may be stored and used to authenticate future\n    HTTP Digest sessions."
  },
  {
    "code": "def set_gpio_pin(self, pin_number, setting, dest_addr_long=None):\n        assert setting in const.GPIO_SETTINGS.values()\n        self._send_and_wait(\n            command=const.IO_PIN_COMMANDS[pin_number],\n            parameter=setting.value,\n            dest_addr_long=dest_addr_long)",
    "docstring": "Set a gpio pin setting."
  },
  {
    "code": "def get_summaryf(self, *args, **kwargs):\n        def func(f):\n            doc = f.__doc__\n            self.get_summary(doc or '', *args, **kwargs)\n            return f\n        return func",
    "docstring": "Extract the summary from a function docstring\n\n        Parameters\n        ----------\n        ``*args`` and ``**kwargs``\n            See the :meth:`get_summary` method. Note, that the first argument\n            will be the docstring of the specified function\n\n        Returns\n        -------\n        function\n            Wrapper that takes a function as input and registers its summary\n            via the :meth:`get_summary` method"
  },
  {
    "code": "def has_calmjs_artifact_declarations(cmd, registry_name='calmjs.artifacts'):\n    return any(get(registry_name).iter_records_for(\n        cmd.distribution.get_name()))",
    "docstring": "For a distutils command to verify that the artifact build step is\n    possible."
  },
  {
    "code": "def Sample(self, n):\n        size = n,\n        return numpy.random.beta(self.alpha, self.beta, size)",
    "docstring": "Generates a random sample from this distribution.\n\n        n: int sample size"
  },
  {
    "code": "def set_foreign_key(self, parent_table, parent_column, child_table, child_column):\n        self.execute('ALTER TABLE {0} ADD FOREIGN KEY ({1}) REFERENCES {2}({3})'.format(parent_table, parent_column,\n                                                                                        child_table, child_column))",
    "docstring": "Create a Foreign Key constraint on a column from a table."
  },
  {
    "code": "def process(self):\n        \"Process the inner datasets.\"\n        xp,yp = self.get_processors()\n        for ds,n in zip(self.lists, ['train','valid','test']): ds.process(xp, yp, name=n)\n        for ds in self.lists:\n            if getattr(ds, 'warn', False): warn(ds.warn)\n        return self",
    "docstring": "Process the inner datasets."
  },
  {
    "code": "def _send_trace(self, chunk=None):\n        self._trace_sm_running = True\n        if chunk is None:\n            chunk = self._next_tracing_chunk(20)\n        if chunk is None or len(chunk) == 0:\n            self._trace_sm_running = False\n            return\n        try:\n            self._send_notification(TracingChar.value_handle, chunk)\n            self._defer(self._send_trace)\n        except bable_interface.BaBLEException as err:\n            if err.packet.status == 'Rejected':\n                time.sleep(0.05)\n                self._defer(self._send_trace, [chunk])\n            else:\n                self._audit('ErrorStreamingTrace')\n                self._logger.exception(\"Error while tracing data\")",
    "docstring": "Stream tracing data to the ble client in 20 byte chunks\n\n        Args:\n            chunk (bytearray): A chunk that should be sent instead of requesting a\n                new chunk from the pending reports."
  },
  {
    "code": "def set_errors(self, result):\n        errors = result.get_messages()\n        for property_name in errors:\n            if not hasattr(self, property_name):\n                continue\n            prop_errors = errors[property_name]\n            if type(prop_errors) is not list:\n                prop_errors = ['<Nested schema result following...>']\n            if property_name in self.errors:\n                self.errors[property_name].extend(prop_errors)\n            else:\n                self.errors[property_name] = prop_errors",
    "docstring": "Populate field errors with errors from schema validation"
  },
  {
    "code": "def loadavg():\n    if __grains__['kernel'] == 'AIX':\n        return _aix_loadavg()\n    try:\n        load_avg = os.getloadavg()\n    except AttributeError:\n        raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform')\n    return {'1-min': load_avg[0],\n            '5-min': load_avg[1],\n            '15-min': load_avg[2]}",
    "docstring": "Return the load averages for this minion\n\n    .. versionchanged:: 2016.11.4\n        Added support for AIX\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' status.loadavg\n\n        :raises CommandExecutionError: If the system cannot report loadaverages to Python"
  },
  {
    "code": "def Get(self, attribute, default=None):\n    if attribute is None:\n      return default\n    elif isinstance(attribute, str):\n      attribute = Attribute.GetAttributeByName(attribute)\n    if \"r\" not in self.mode and (attribute not in self.new_attributes and\n                                 attribute not in self.synced_attributes):\n      raise IOError(\"Fetching %s from object not opened for reading.\" %\n                    attribute)\n    for result in self.GetValuesForAttribute(attribute, only_one=True):\n      try:\n        result.attribute_instance = attribute\n      except AttributeError:\n        pass\n      return result\n    return attribute.GetDefault(self, default)",
    "docstring": "Gets the attribute from this object."
  },
  {
    "code": "def _cobalt_ratio_file(paired, work_dir):\n    cobalt_dir = utils.safe_makedir(os.path.join(work_dir, \"cobalt\"))\n    out_file = os.path.join(cobalt_dir, \"%s.cobalt\" % dd.get_sample_name(paired.tumor_data))\n    if not utils.file_exists(out_file):\n        cnr_file = tz.get_in([\"depth\", \"bins\", \"normalized\"], paired.tumor_data)\n        with file_transaction(paired.tumor_data, out_file) as tx_out_file:\n            with open(tx_out_file, \"w\") as out_handle:\n                writer = csv.writer(out_handle, delimiter=\"\\t\")\n                writer.writerow([\"Chromosome\", \"Position\", \"ReferenceReadCount\", \"TumorReadCount\",\n                                 \"ReferenceGCRatio\", \"TumorGCRatio\", \"ReferenceGCDiploidRatio\"])\n        raise NotImplementedError\n    return out_file",
    "docstring": "Convert CNVkit binning counts into cobalt ratio output.\n\n    This contains read counts plus normalization for GC, from section 7.2\n    \"Determine read depth ratios for tumor and reference genomes\"\n\n    https://www.biorxiv.org/content/biorxiv/early/2018/09/20/415133.full.pdf\n\n    Since CNVkit cnr files already have GC bias correction, we re-center\n    the existing log2 ratios to be around 1, rather than zero, which matches\n    the cobalt expectations.\n\n    XXX This doesn't appear to be a worthwhile direction since PURPLE requires\n    1000bp even binning. We'll leave this here as a starting point for future\n    work but work on using cobalt directly."
  },
  {
    "code": "def new(self, text):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('This File or Text identifier is already initialized')\n        if len(text) != 128:\n            raise pycdlibexception.PyCdlibInvalidInput('Length of text must be 128')\n        self.text = text\n        self._initialized = True",
    "docstring": "Create a new file or text identifier.\n\n        Parameters:\n          text   - The text to store into the identifier.\n        Returns:\n          Nothing."
  },
  {
    "code": "def tenure(self):\n        if self.end_date:\n            return round((date.end_date - self.start_date).days / 365., 2)\n        else:\n            return round((date.today() - self.start_date).days / 365., 2)",
    "docstring": "Calculates board tenure in years"
  },
  {
    "code": "def get_min_col_num(mention):\n    span = _to_span(mention)\n    if span.sentence.is_tabular():\n        return span.sentence.cell.col_start\n    else:\n        return None",
    "docstring": "Return the lowest column number that a Mention occupies.\n\n    :param mention: The Mention to evaluate. If a candidate is given, default\n        to its first Mention.\n    :rtype: integer or None"
  },
  {
    "code": "def get_recently_played_games(self, steamID, count=0, format=None):\n        parameters = {'steamid' : steamID, 'count' : count}\n        if format is not None:\n            parameters['format'] = format\n        url = self.create_request_url(self.interface, 'GetRecentlyPlayedGames', 1,\n            parameters)\n        data = self.retrieve_request(url)\n        return self.return_data(data, format=format)",
    "docstring": "Request a list of recently played games by a given steam id.\n\n        steamID: The users ID\n        count: Number of games to return. (0 is all recent games.)\n        format: Return format. None defaults to json. (json, xml, vdf)"
  },
  {
    "code": "def add_behaviour(self, behaviour, template=None):\n        behaviour.set_agent(self)\n        if issubclass(type(behaviour), FSMBehaviour):\n            for _, state in behaviour.get_states().items():\n                state.set_agent(self)\n        behaviour.set_template(template)\n        self.behaviours.append(behaviour)\n        if self.is_alive():\n            behaviour.start()",
    "docstring": "Adds and starts a behaviour to the agent.\n        If template is not None it is used to match\n        new messages and deliver them to the behaviour.\n\n        Args:\n          behaviour (spade.behaviour.CyclicBehaviour): the behaviour to be started\n          template (spade.template.Template, optional): the template to match messages with (Default value = None)"
  },
  {
    "code": "def progress_all(self):\n        return self.progress_idxs(range(np.shape(self.get_data_x())[0] - self.progress_win_size, \n                                        np.shape(self.get_data_x())[0]))",
    "docstring": "Competence progress of the overall tree."
  },
  {
    "code": "def in_constraints(self):\n        expressions = []\n        for uniqueid in self._in_constraints:\n            expressions.append(self._bundle.get_parameter(context='constraint', uniqueid=uniqueid))\n        return expressions",
    "docstring": "returns a list of the expressions in which this parameter constrains another"
  },
  {
    "code": "def delete_model(self):\n        request_failed = False\n        failed_models = []\n        for model_name in self._model_names:\n            try:\n                self.sagemaker_session.delete_model(model_name)\n            except Exception:\n                request_failed = True\n                failed_models.append(model_name)\n        if request_failed:\n            raise Exception('One or more models cannot be deleted, please retry. \\n'\n                            'Failed models: {}'.format(', '.join(failed_models)))",
    "docstring": "Deletes the Amazon SageMaker models backing this predictor."
  },
  {
    "code": "def apply_inheritance(self):\n        self.apply_partial_inheritance('exclude')\n        for i in self:\n            self.get_customs_properties_by_inheritance(i)\n        for timeperiod in self:\n            self.get_unresolved_properties_by_inheritance(timeperiod)",
    "docstring": "The only interesting property to inherit is exclude\n\n        :return: None"
  },
  {
    "code": "def create_dirs(path):\n    fname = os.path.basename(path)\n    if fname.__contains__('.'):\n        path = os.path.dirname(path)\n    if not os.path.exists(path):\n        os.makedirs(path)",
    "docstring": "Creates all directories mentioned in the given path.\n        Useful to write a new file with the specified path.\n        It carefully skips the file-name in the given path.\n\n    :param path: Path of a file or directory"
  },
  {
    "code": "def update(self, res, pk, depth=1, since=None):\n        fetch = lambda: self._fetcher.fetch_latest(res, pk, 1, since=since)\n        self._update(res, fetch, depth)",
    "docstring": "Try to sync an object to the local database, in case of failure\n        where a referenced object is not found, attempt to fetch said\n        object from the REST api"
  },
  {
    "code": "def set_reprompt_text(self, text):\n        self.response.reprompt.outputSpeech.type = 'PlainText'\n        self.response.reprompt.outputSpeech.text = text",
    "docstring": "Set response reprompt output speech as plain text type.\n\n        Args:\n            text: str. Response speech used when type is 'PlainText'. Cannot\n                exceed 8,000 characters."
  },
  {
    "code": "def merge_lists(*args):\n    out = {}\n    for contacts in filter(None, args):\n        for contact in contacts:\n            out[contact.value] = contact\n    return list(out.values())",
    "docstring": "Merge an arbitrary number of lists into a single list and dedupe it\n\n    Args:\n        *args: Two or more lists\n\n    Returns:\n        A deduped merged list of all the provided lists as a single list"
  },
  {
    "code": "def add_time_stamp(self, db_id, name):\n        with self.lock:\n            self.cur.execute(\n                'insert into \"timestamps\" (\"job\", \"what\")'\n                'values (?, ?);', (db_id, name))",
    "docstring": "Add a timestamp to the database."
  },
  {
    "code": "def _abort(self) -> None:\n        self.client_terminated = True\n        self.server_terminated = True\n        if self.stream is not None:\n            self.stream.close()\n        self.close()",
    "docstring": "Instantly aborts the WebSocket connection by closing the socket"
  },
  {
    "code": "def post(self):\n        resource = self.__model__.query.filter_by(**request.json).first()\n        if resource:\n            error_message = is_valid_method(self.__model__, resource)\n            if error_message:\n                raise BadRequestException(error_message)\n            return self._no_content_response()\n        resource = self.__model__(**request.json)\n        error_message = is_valid_method(self.__model__, resource)\n        if error_message:\n            raise BadRequestException(error_message)\n        db.session().add(resource)\n        db.session().commit()\n        return self._created_response(resource)",
    "docstring": "Return the JSON representation of a new resource created through\n        an HTTP POST call.\n\n        :returns: ``HTTP 201`` if a resource is properly created\n        :returns: ``HTTP 204`` if the resource already exists\n        :returns: ``HTTP 400`` if the request is malformed or missing data"
  },
  {
    "code": "def feature_importances_(self):\n        if getattr(self, 'booster', None) is not None and self.booster != 'gbtree':\n            raise AttributeError('Feature importance is not defined for Booster type {}'\n                                 .format(self.booster))\n        b = self.get_booster()\n        score = b.get_score(importance_type=self.importance_type)\n        all_features = [score.get(f, 0.) for f in b.feature_names]\n        all_features = np.array(all_features, dtype=np.float32)\n        return all_features / all_features.sum()",
    "docstring": "Feature importances property\n\n        .. note:: Feature importance is defined only for tree boosters\n\n            Feature importance is only defined when the decision tree model is chosen as base\n            learner (`booster=gbtree`). It is not defined for other base learner types, such\n            as linear learners (`booster=gblinear`).\n\n        Returns\n        -------\n        feature_importances_ : array of shape ``[n_features]``"
  },
  {
    "code": "def is_in_intervall(value, min_value, max_value, name='variable'):\n    if not (min_value <= value <= max_value):\n        raise ValueError('{}={} is not in [{}, {}]'\n                         .format(name, value, min_value, max_value))",
    "docstring": "Raise an exception if value is not in an interval.\n\n    Parameters\n    ----------\n    value : orderable\n    min_value : orderable\n    max_value : orderable\n    name : str\n        Name of the variable to print in exception."
  },
  {
    "code": "def save_dash(self, dashboard_id):\n        session = db.session()\n        dash = (session\n                .query(models.Dashboard)\n                .filter_by(id=dashboard_id).first())\n        check_ownership(dash, raise_if_false=True)\n        data = json.loads(request.form.get('data'))\n        self._set_dash_metadata(dash, data)\n        session.merge(dash)\n        session.commit()\n        session.close()\n        return json_success(json.dumps({'status': 'SUCCESS'}))",
    "docstring": "Save a dashboard's metadata"
  },
  {
    "code": "def _id_or_key(list_item):\n    if isinstance(list_item, dict):\n        if 'id' in list_item:\n            return list_item['id']\n        if 'key' in list_item:\n            return list_item['key']\n    return list_item",
    "docstring": "Return the value at key 'id' or 'key'."
  },
  {
    "code": "def device_not_active(self, addr):\n        self.aldb_device_handled(addr)\n        for callback in self._cb_device_not_active:\n            callback(addr)",
    "docstring": "Handle inactive devices."
  },
  {
    "code": "def trainable_params(m:nn.Module)->ParamList:\n    \"Return list of trainable params in `m`.\"\n    res = filter(lambda p: p.requires_grad, m.parameters())\n    return res",
    "docstring": "Return list of trainable params in `m`."
  },
  {
    "code": "def namedtuple_row_strategy(column_names):\n    import collections\n    column_names = [name if is_valid_identifier(name) else 'col%s_' % idx for idx, name in enumerate(column_names)]\n    row_class = collections.namedtuple('Row', column_names)\n    def row_factory(row):\n        return row_class(*row)\n    return row_factory",
    "docstring": "Namedtuple row strategy, rows returned as named tuples\n\n    Column names that are not valid Python identifiers will be replaced\n    with col<number>_"
  },
  {
    "code": "def _render_content(self):\n        if self.content_format == \"rst\" and docutils_publish is not None:\n            doc_parts = docutils_publish(\n                source=self.raw_content,\n                writer_name=\"html4css1\"\n            )\n            self.rendered_content = doc_parts['fragment']\n        elif self.content_format == \"rs\" and docutils_publish is None:\n            raise RuntimeError(\"Install docutils to pubilsh reStructuredText\")\n        elif self.content_format == \"md\" and markdown is not None:\n            self.rendered_content = markdown(self.raw_content)\n        elif self.content_format == \"md\" and markdown is None:\n            raise RuntimeError(\"Install Markdown to pubilsh markdown\")\n        else:\n            self.rendered_content = self.raw_content",
    "docstring": "Renders the content according to the ``content_format``."
  },
  {
    "code": "def _validate_args(self, args):\n        assert(args.bucket)\n        if args.subscribers:\n            for _subscriber in args.subscribers:\n                assert(isinstance(_subscriber, AsperaBaseSubscriber))\n        if (args.transfer_config):\n            assert(isinstance(args.transfer_config, AsperaConfig))\n            if args.transfer_config.multi_session > self._config.ascp_max_concurrent:\n                raise ValueError(\"Max sessions is %d\" % self._config.ascp_max_concurrent)\n        for _pair in args.file_pair_list:\n            if not _pair.key or not _pair.fileobj:\n                raise ValueError(\"Invalid file pair\")",
    "docstring": "validate the user arguments"
  },
  {
    "code": "def by_sql(cls, sql, engine_or_session):\n        ses, auto_close = ensure_session(engine_or_session)\n        result = ses.query(cls).from_statement(sql).all()\n        if auto_close:\n            ses.close()\n        return result",
    "docstring": "Query with sql statement or texture sql."
  },
  {
    "code": "def jtag_enable(self):\n        status, _ = self.bulkCommand(_BMSG_ENABLE_JTAG)\n        if status == 0:\n            self._jtagon = True\n        elif status == 3:\n            self._jtagon = True\n            raise JTAGAlreadyEnabledError()\n        else:\n            raise JTAGEnableFailedError(\"Error enabling JTAG. Error code: %s.\" %status)",
    "docstring": "Enables JTAG output on the controller. JTAG operations executed\n        before this function is called will return useless data or fail.\n\n        Usage:\n            >>> from proteusisc import getAttachedControllers, bitarray\n            >>> c = getAttachedControllers()[0]\n            >>> c.jtag_enable()\n            >>> c.write_tms_bits(bitarray(\"001011111\"), return_tdo=True)\n            >>> c.jtag_disable()"
  },
  {
    "code": "def refresh(self, client_name, refresh_token, **params):\n        client = self.client(client_name, logger=self.app.logger)\n        return client.get_access_token(refresh_token, grant_type='refresh_token', **params)",
    "docstring": "Get refresh token.\n\n        :param client_name: A name one of configured clients\n        :param redirect_uri: An URI for authorization redirect\n        :returns: a coroutine"
  },
  {
    "code": "def sub(a, b):\n    if a is None:\n        if b is None:\n            return None\n        else:\n            return -1 * b\n    elif b is None:\n        return a\n    return a - b",
    "docstring": "Subtract two values, ignoring None"
  },
  {
    "code": "def make_heartbeat(port, path, peer_uid, node_uid, app_id):\n    packet = struct.pack(\"<BBH\", PACKET_FORMAT_VERSION, PACKET_TYPE_HEARTBEAT, port)\n    for string in (path, peer_uid, node_uid, app_id):\n        string_bytes = to_bytes(string)\n        packet += struct.pack(\"<H\", len(string_bytes))\n        packet += string_bytes\n    return packet",
    "docstring": "Prepares the heart beat UDP packet\n\n    Format : Little endian\n    * Kind of beat (1 byte)\n    * Herald HTTP server port (2 bytes)\n    * Herald HTTP servlet path length (2 bytes)\n    * Herald HTTP servlet path (variable, UTF-8)\n    * Peer UID length (2 bytes)\n    * Peer UID (variable, UTF-8)\n    * Node UID length (2 bytes)\n    * Node UID (variable, UTF-8)\n    * Application ID length (2 bytes)\n    * Application ID (variable, UTF-8)\n\n    :param port: The port to access the Herald HTTP server\n    :param path: The path to the Herald HTTP servlet\n    :param peer_uid: The UID of the peer\n    :param node_uid: The UID of the node\n    :param app_id: Application ID\n    :return: The heart beat packet content (byte array)"
  },
  {
    "code": "def validate_language_key(obj, key):\n    backend = bigchaindb.config['database']['backend']\n    if backend == 'localmongodb':\n        data = obj.get(key, {})\n        if isinstance(data, dict):\n            validate_all_values_for_key_in_obj(data, 'language', validate_language)\n        elif isinstance(data, list):\n            validate_all_values_for_key_in_list(data, 'language', validate_language)",
    "docstring": "Validate all nested \"language\" key in `obj`.\n\n       Args:\n           obj (dict): dictionary whose \"language\" key is to be validated.\n\n       Returns:\n           None: validation successful\n\n        Raises:\n            ValidationError: will raise exception in case language is not valid."
  },
  {
    "code": "def _build_keys(self, slug, date=None, granularity='all'):\n        slug = slugify(slug)\n        if date is None:\n            date = datetime.utcnow()\n        patts = self._build_key_patterns(slug, date)\n        if granularity == \"all\":\n            return list(patts.values())\n        return [patts[granularity]]",
    "docstring": "Builds redis keys used to store metrics.\n\n        * ``slug`` -- a slug used for a metric, e.g. \"user-signups\"\n        * ``date`` -- (optional) A ``datetime.datetime`` object used to\n          generate the time period for the metric. If omitted, the current date\n          and time (in UTC) will be used.\n        * ``granularity`` -- Must be one of: \"all\" (default), \"yearly\",\n        \"monthly\", \"weekly\", \"daily\", \"hourly\", \"minutes\", or \"seconds\".\n\n        Returns a list of strings."
  },
  {
    "code": "def delay(self, dl=0):\n        if dl is None:\n            time.sleep(self.dl)\n        elif dl < 0:\n            sys.stderr.write(\n                \"delay cannot less than zero, this takes no effects.\\n\")\n        else:\n            time.sleep(dl)",
    "docstring": "Delay for ``dl`` seconds."
  },
  {
    "code": "def rebase(self):\n        if self.standalone:\n            rebase_msg = 'Merging layered image with base'\n        else:\n            rebase_msg = 'Rebase'\n        with LogTask(rebase_msg):\n            if len(self.src_qemu_info) == 1:\n                return\n            if self.standalone:\n                utils.qemu_rebase(target=self.dst, backing_file=\"\")\n            else:\n                if len(self.src_qemu_info) > 2:\n                    raise utils.LagoUserException(\n                        'Layered export is currently supported for one '\n                        'layer only.  You can try to use Standalone export.'\n                    )\n                parent = self.src_qemu_info[0]['backing-filename']\n                parent = os.path.basename(parent)\n                try:\n                    parent = parent.split(':', 1)[1]\n                except IndexError:\n                    pass\n                parent = './{}'.format(parent)\n                utils.qemu_rebase(\n                    target=self.dst, backing_file=parent, safe=False\n                )",
    "docstring": "Change the backing-file entry of the exported disk.\n        Please refer to 'qemu-img rebase' manual for more info."
  },
  {
    "code": "def has_chess960_castling_rights(self) -> bool:\n        chess960 = self.chess960\n        self.chess960 = True\n        castling_rights = self.clean_castling_rights()\n        self.chess960 = chess960\n        if castling_rights & ~BB_CORNERS:\n            return True\n        if castling_rights & BB_RANK_1 and not self.occupied_co[WHITE] & self.kings & BB_E1:\n            return True\n        if castling_rights & BB_RANK_8 and not self.occupied_co[BLACK] & self.kings & BB_E8:\n            return True\n        return False",
    "docstring": "Checks if there are castling rights that are only possible in Chess960."
  },
  {
    "code": "def _api_wrapper(fn):\n    def _convert(value):\n        if isinstance(value, _datetime.date):\n            return value.strftime('%s')\n        return value\n    @_six.wraps(fn)\n    def _fn(self, command, **params):\n        with self.startup_lock:\n            if self.timer.ident is None:\n                self.timer.setDaemon(True)\n                self.timer.start()\n        params = dict((key, _convert(value))\n                      for key, value in _six.iteritems(params)\n                      if value is not None)\n        self.semaphore.acquire()\n        resp = fn(self, command, **params)\n        try:\n            respdata = resp.json(object_hook=_AutoCastDict)\n        except:\n            resp.raise_for_status()\n            raise Exception('No JSON object could be decoded')\n        if 'error' in respdata:\n            raise PoloniexCommandException(respdata['error'])\n        resp.raise_for_status()\n        return respdata\n    return _fn",
    "docstring": "API function decorator that performs rate limiting and error checking."
  },
  {
    "code": "def line(h1: Histogram1D, **kwargs) -> dict:\n    lw = kwargs.pop(\"lw\", DEFAULT_STROKE_WIDTH)\n    mark_template = [{\n        \"type\": \"line\",\n        \"encode\": {\n            \"enter\": {\n                \"x\": {\"scale\": \"xscale\", \"field\": \"x\"},\n                \"y\": {\"scale\": \"yscale\", \"field\": \"y\"},\n                \"stroke\": {\"scale\": \"series\", \"field\": \"c\"},\n                \"strokeWidth\": {\"value\": lw}\n            }\n        },\n        \"from\": {\"data\": \"series\"},\n    }]\n    vega = _scatter_or_line(h1, mark_template=mark_template, kwargs=kwargs)\n    return vega",
    "docstring": "Line plot of 1D histogram values.\n\n    Points are horizontally placed in bin centers.\n\n    Parameters\n    ----------\n    h1 : physt.histogram1d.Histogram1D\n        Dimensionality of histogram for which it is applicable"
  },
  {
    "code": "def get_paths(path_tokens):\n    if len(path_tokens) == 0:\n        return []\n    token = path_tokens.pop()\n    path = PathToken(token.alias, token.path)\n    return [path] + get_paths(path_tokens)",
    "docstring": "Given a list of parser path tokens, return a list of path objects\n    for them."
  },
  {
    "code": "def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys,\n                               timeout=0):\n        set_mods = pygame.key.get_mods()\n        return frozenset.union(\n            frozenset([self.wait_for_keys(*keys, timeout=timeout)]),\n            EventListener._contained_modifiers(set_mods, modifiers_to_check))",
    "docstring": "The same as wait_for_keys, but returns a frozen_set which contains \n        the pressed key, and the modifier keys.\n\n        :param modifiers_to_check: iterable of modifiers for which the function\n            will check whether they are pressed\n\n        :type modifiers: Iterable[int]"
  },
  {
    "code": "def rslv(self, interface: str, name: str=None) -> Tuple[str, int, Optional[str]]:\n\t\tif name is None:\n\t\t\tname = self.name\n\t\tkey = '{}-{}'.format(name, interface)\n\t\thost = None\n\t\tif 'host' in self.interfaces[key]:\n\t\t\thost = self.interfaces[key]['host']\n\t\treturn self.interfaces[key]['ip'], self.interfaces[key]['port'], host",
    "docstring": "Return the IP address, port and optionally host IP for one of this Nodes interfaces."
  },
  {
    "code": "def date_time_this_month(\n            self,\n            before_now=True,\n            after_now=False,\n            tzinfo=None):\n        now = datetime.now(tzinfo)\n        this_month_start = now.replace(\n            day=1, hour=0, minute=0, second=0, microsecond=0)\n        next_month_start = this_month_start + \\\n            relativedelta.relativedelta(months=1)\n        if before_now and after_now:\n            return self.date_time_between_dates(\n                this_month_start, next_month_start, tzinfo)\n        elif not before_now and after_now:\n            return self.date_time_between_dates(now, next_month_start, tzinfo)\n        elif not after_now and before_now:\n            return self.date_time_between_dates(this_month_start, now, tzinfo)\n        else:\n            return now",
    "docstring": "Gets a DateTime object for the current month.\n\n        :param before_now: include days in current month before today\n        :param after_now: include days in current month after today\n        :param tzinfo: timezone, instance of datetime.tzinfo subclass\n        :example DateTime('2012-04-04 11:02:02')\n        :return DateTime"
  },
  {
    "code": "def _setBitOn(x, bitNum):\n    _checkInt(x, minvalue=0, description='input value')\n    _checkInt(bitNum, minvalue=0, description='bitnumber')\n    return x | (1 << bitNum)",
    "docstring": "Set bit 'bitNum' to True.\n\n    Args:\n        * x (int): The value before.\n        * bitNum (int): The bit number that should be set to True.\n\n    Returns:\n        The value after setting the bit. This is an integer.\n\n    For example:\n        For x = 4 (dec) = 0100 (bin), setting bit number 0 results in 0101 (bin) = 5 (dec)."
  },
  {
    "code": "def _get_query_uri(self):\n        if 'VCAP_SERVICES' in os.environ:\n            services = json.loads(os.getenv('VCAP_SERVICES'))\n            predix_timeseries = services['predix-timeseries'][0]['credentials']\n            return predix_timeseries['query']['uri'].partition('/v1')[0]\n        else:\n            return predix.config.get_env_value(self, 'query_uri')",
    "docstring": "Returns the URI endpoint for performing queries of a\n        Predix Time Series instance from environment inspection."
  },
  {
    "code": "def list_create(self, title):\n        params = self.__generate_params(locals())\n        return self.__api_request('POST', '/api/v1/lists', params)",
    "docstring": "Create a new list with the given `title`.\n        \n        Returns the `list dict`_ of the created list."
  },
  {
    "code": "def iter_cofactors(self, vs=None):\n        r\n        vs = self._expect_vars(vs)\n        for point in iter_points(vs):\n            yield self.restrict(point)",
    "docstring": "r\"\"\"Iterate through the cofactors of a function over N variables.\n\n        The *vs* argument is a sequence of :math:`N` Boolean variables.\n\n        The *cofactor* of :math:`f(x_1, x_2, \\dots, x_i, \\dots, x_n)`\n        with respect to variable :math:`x_i` is:\n        :math:`f_{x_i} = f(x_1, x_2, \\dots, 1, \\dots, x_n)`\n\n        The *cofactor* of :math:`f(x_1, x_2, \\dots, x_i, \\dots, x_n)`\n        with respect to variable :math:`x_i'` is:\n        :math:`f_{x_i'} = f(x_1, x_2, \\dots, 0, \\dots, x_n)`"
  },
  {
    "code": "def open(cls, filename):\n        file_info = cls.parse_remote(filename)\n        blob_service = cls.connect(filename)\n        return BlobHandle(blob_service=blob_service,\n                          container=file_info.container,\n                          blob=file_info.blob,\n                          chunk_size=cls._BLOB_CHUNK_DATA_SIZE)",
    "docstring": "Provide a handle-like object for streaming."
  },
  {
    "code": "def calc_L(A):\n    I = np.eye(A.shape[0])\n    if type(A) is pd.DataFrame:\n        return pd.DataFrame(np.linalg.inv(I-A),\n                            index=A.index, columns=A.columns)\n    else:\n        return np.linalg.inv(I-A)",
    "docstring": "Calculate the Leontief L from A\n\n    Parameters\n    ----------\n    A : pandas.DataFrame or numpy.array\n        Symmetric input output table (coefficients)\n\n    Returns\n    -------\n    pandas.DataFrame or numpy.array\n        Leontief input output table L\n        The type is determined by the type of A.\n        If DataFrame index/columns as A"
  },
  {
    "code": "def by_owner(cls, session, owner_name):\n        return cls.find(session,\n                        join=(cls.owners),\n                        where=(User.login == owner_name,),\n                        order_by=cls.name)",
    "docstring": "Get packages from a given owner username.\n\n        :param session: SQLAlchemy session\n        :type session: :class:`sqlalchemy.Session`\n\n        :param owner_name: owner username\n        :type owner_name: unicode\n\n        :return: package instances\n        :rtype: generator of :class:`pyshop.models.Package`"
  },
  {
    "code": "def _write(self, data):\n        stream = yaml.dump(data, default_flow_style=False)\n        self.path.write_text(stream)",
    "docstring": "Write data to config file."
  },
  {
    "code": "def import_transformer(name):\n    if name in transformers:\n        return transformers[name]\n    hook = sys.meta_path[0]\n    sys.meta_path = sys.meta_path[1:]\n    try:\n        transformers[name] = __import__(name)\n        if CONSOLE_ACTIVE:\n            if hasattr(transformers[name], \"NO_CONSOLE\"):\n                print(transformers[name].NO_CONSOLE)\n                transformers[name] = NullTransformer()\n    except ImportError:\n        sys.stderr.write(\"Warning: Import Error in add_transformers: %s not found\\n\" % name)\n        transformers[name] = NullTransformer()\n    except Exception as e:\n        sys.stderr.write(\"Unexpected exception in transforms.import_transformer%s\\n \" %\n                         e.__class__.__name__)\n    finally:\n        sys.meta_path.insert(0, hook)\n    return transformers[name]",
    "docstring": "If needed, import a transformer, and adds it to the globally known dict\n       The code inside a module where a transformer is defined should be\n       standard Python code, which does not need any transformation.\n       So, we disable the import hook, and let the normal module import\n       do its job - which is faster and likely more reliable than our\n       custom method."
  },
  {
    "code": "def destroy(\n            self, request, pk=None, parent_lookup_seedteam=None,\n            parent_lookup_seedteam__organization=None):\n        self.check_team_permissions(\n            request, parent_lookup_seedteam,\n            parent_lookup_seedteam__organization)\n        return super(TeamPermissionViewSet, self).destroy(\n            request, pk, parent_lookup_seedteam,\n            parent_lookup_seedteam__organization)",
    "docstring": "Remove a permission from a team."
  },
  {
    "code": "def reload(self, **params):\n        if not self.bucket:\n            raise ValueError('bucket property not assigned')\n        if not self.key:\n            raise ValueError('key property not assigned')\n        dtype, value, context = self.bucket._client._fetch_datatype(\n            self.bucket, self.key, **params)\n        if not dtype == self.type_name:\n            raise TypeError(\"Expected datatype {} but \"\n                            \"got datatype {}\".format(self.__class__,\n                                                     TYPES[dtype]))\n        self.clear()\n        self._context = context\n        self._set_value(value)\n        return self",
    "docstring": "Reloads the datatype from Riak.\n\n        .. warning: This clears any local modifications you might have\n           made.\n\n        :param r: the read quorum\n        :type r: integer, string, None\n        :param pr: the primary read quorum\n        :type pr: integer, string, None\n        :param basic_quorum: whether to use the \"basic quorum\" policy\n           for not-founds\n        :type basic_quorum: bool\n        :param notfound_ok: whether to treat not-found responses as successful\n        :type notfound_ok: bool\n        :param timeout: a timeout value in milliseconds\n        :type timeout: int\n        :param include_context: whether to return the opaque context\n          as well as the value, which is useful for removal operations\n          on sets and maps\n        :type include_context: bool\n        :rtype: :class:`Datatype`"
  },
  {
    "code": "def applications(self):\n        if self._applications is None:\n            self._applications = ApplicationList(self._version, account_sid=self._solution['sid'], )\n        return self._applications",
    "docstring": "Access the applications\n\n        :returns: twilio.rest.api.v2010.account.application.ApplicationList\n        :rtype: twilio.rest.api.v2010.account.application.ApplicationList"
  },
  {
    "code": "def copy(self):\n        c = matrix()\n        c.tt = self.tt.copy()\n        c.n = self.n.copy()\n        c.m = self.m.copy()\n        return c",
    "docstring": "Creates a copy of the TT-matrix"
  },
  {
    "code": "def complete_upload(self):\n        xml = self.to_xml()\n        return self.bucket.complete_multipart_upload(self.key_name,\n                                                     self.id, xml)",
    "docstring": "Complete the MultiPart Upload operation.  This method should\n        be called when all parts of the file have been successfully\n        uploaded to S3.\n\n        :rtype: :class:`boto.s3.multipart.CompletedMultiPartUpload`\n        :returns: An object representing the completed upload."
  },
  {
    "code": "def parse_region(self, include, region_type, region_end, line):\n        if self.coordsys is None:\n            raise DS9RegionParserError(\"No coordinate system specified and a\"\n                                       \" region has been found.\")\n        else:\n            helper = DS9RegionParser(coordsys=self.coordsys,\n                                     include=include,\n                                     region_type=region_type,\n                                     region_end=region_end,\n                                     global_meta=self.global_meta,\n                                     line=line)\n            helper.parse()\n            self.shapes.append(helper.shape)",
    "docstring": "Extract a Shape from a region string"
  },
  {
    "code": "def selfcheck(tools):\n    msg = []\n    for tool_name, check_cli in collections.OrderedDict(tools).items():\n        try:\n            subprocess.check_output(check_cli, shell=True, stderr=subprocess.STDOUT)\n        except subprocess.CalledProcessError:\n            msg.append('%r not found or not usable.' % tool_name)\n    return '\\n'.join(msg) if msg else 'Your system is ready.'",
    "docstring": "Audit the system for issues.\n\n    :param tools: Tools description. Use elevation.TOOLS to test elevation."
  },
  {
    "code": "def _short_ts_regexp():\n\tts_re = ['^']\n\tfor k in it.chain(_short_ts_days, _short_ts_s):\n\t\tts_re.append(r'(?P<{0}>\\d+{0}\\s*)?'.format(k))\n\treturn re.compile(''.join(ts_re), re.I | re.U)",
    "docstring": "Generates regexp for parsing of\n\t\tshortened relative timestamps, as shown in the table."
  },
  {
    "code": "def add_connection_throttle(self, loadbalancer, maxConnectionRate=None,\n            maxConnections=None, minConnections=None, rateInterval=None):\n        settings = {}\n        if maxConnectionRate:\n            settings[\"maxConnectionRate\"] = maxConnectionRate\n        if maxConnections:\n            settings[\"maxConnections\"] = maxConnections\n        if minConnections:\n            settings[\"minConnections\"] = minConnections\n        if rateInterval:\n            settings[\"rateInterval\"] = rateInterval\n        req_body = {\"connectionThrottle\": settings}\n        uri = \"/loadbalancers/%s/connectionthrottle\" % utils.get_id(loadbalancer)\n        resp, body = self.api.method_put(uri, body=req_body)\n        return body",
    "docstring": "Creates or updates the connection throttling information for the load\n        balancer. When first creating the connection throttle, all 4 parameters\n        must be supplied. When updating an existing connection throttle, at\n        least one of the parameters must be supplied."
  },
  {
    "code": "def install_unicast_keys(self, client_nonce):\n        pmk = self.pmk\n        anonce = self.anonce\n        snonce = client_nonce\n        amac = mac2str(self.mac)\n        smac = mac2str(self.client)\n        self.ptk = customPRF512(pmk, amac, smac, anonce, snonce)\n        self.kck = self.ptk[:16]\n        self.kek = self.ptk[16:32]\n        self.tk = self.ptk[32:48]\n        self.mic_ap_to_sta = self.ptk[48:56]\n        self.mic_sta_to_ap = self.ptk[56:64]\n        self.client_iv = count()",
    "docstring": "Use the client nonce @client_nonce to compute and install\n        PTK, KCK, KEK, TK, MIC (AP -> STA), MIC (STA -> AP)"
  },
  {
    "code": "def remove(self, attendees):\n        if isinstance(attendees, (list, tuple)):\n            attendees = {\n                attendee.address if isinstance(attendee, Attendee) else attendee\n                for\n                attendee in attendees}\n        elif isinstance(attendees, str):\n            attendees = {attendees}\n        elif isinstance(attendees, Attendee):\n            attendees = {attendees.address}\n        else:\n            raise ValueError('Incorrect parameter type for attendees')\n        new_attendees = []\n        for attendee in self.__attendees:\n            if attendee.address not in attendees:\n                new_attendees.append(attendee)\n        self.__attendees = new_attendees\n        self._track_changes()",
    "docstring": "Remove the provided attendees from the event\n\n        :param attendees: list of attendees to add\n        :type attendees: str or tuple(str, str) or Attendee or list[str] or\n         list[tuple(str,str)] or list[Attendee]"
  },
  {
    "code": "def header_proc(self, inputstring, header=\"file\", initial=\"initial\", use_hash=None, **kwargs):\n        pre_header = self.getheader(initial, use_hash=use_hash, polish=False)\n        main_header = self.getheader(header, polish=False)\n        if self.minify:\n            main_header = minify(main_header)\n        return pre_header + self.docstring + main_header + inputstring",
    "docstring": "Add the header."
  },
  {
    "code": "def reset(self):\n        r\n        self._ctx.managed_open()\n        self._ctx.dispose(self, False)\n        self._ctx.backend.reset_device(self._ctx.handle)\n        self._ctx.dispose(self, True)",
    "docstring": "r\"\"\"Reset the device."
  },
  {
    "code": "def browse_podcasts(self, podcast_genre_id='JZCpodcasttopchartall'):\n\t\tresponse = self._call(\n\t\t\tmc_calls.PodcastBrowse,\n\t\t\tpodcast_genre_id=podcast_genre_id\n\t\t)\n\t\tpodcast_series_list = response.body.get('series', [])\n\t\treturn podcast_series_list",
    "docstring": "Get the podcasts for a genre from the Podcasts browse tab.\n\n\t\tParameters:\n\t\t\tpodcast_genre_id (str, Optional): A podcast genre ID as found\n\t\t\t\tin :meth:`browse_podcasts_genres`.\n\t\t\t\tDefault: ``'JZCpodcasttopchartall'``.\n\n\t\tReturns:\n\t\t\tlist: Podcast dicts."
  },
  {
    "code": "def register(filename):\n    if not os.path.isfile(filename):\n        raise CommandExecutionError(\n            'The specified filename ({0}) does not exist.'.format(filename)\n        )\n    cmd = '{0} registervm {1}'.format(vboxcmd(), filename)\n    ret = salt.modules.cmdmod.run_all(cmd)\n    if ret['retcode'] == 0:\n        return True\n    return ret['stderr']",
    "docstring": "Register a VM\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' vboxmanage.register my_vm_filename"
  },
  {
    "code": "def astensor(array: TensorLike) -> BKTensor:\n    tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n    return tensor",
    "docstring": "Covert numpy array to tensorflow tensor"
  },
  {
    "code": "def resolve_rva(self, rva):\n        containing_section = self.get_section_of_rva(rva)\n        in_section_offset = containing_section.PointerToRawData -\\\n            containing_section.VirtualAddress\n        return in_section_offset + rva",
    "docstring": "RVAs are supposed to be used with the image of the file in memory.\n            There's no direct algorithm to calculate the offset of an RVA in\n            the file.\n\n            What we do here is to find the section that contains the RVA and\n            then we calculate the offset between the RVA of the section\n            and the offset of the section in the file. With this offset, we can\n            compute the position of the RVA in the file"
  },
  {
    "code": "def reshuffle_batches(self, indices, rng):\n        indices = indices.view(-1, self.global_batch_size)\n        num_batches = indices.shape[0]\n        order = torch.randperm(num_batches, generator=rng)\n        indices = indices[order, :]\n        indices = indices.view(-1)\n        return indices",
    "docstring": "Permutes global batches\n\n        :param indices: torch.tensor with batch indices\n        :param rng: instance of torch.Generator"
  },
  {
    "code": "def sollen(tex, command):\n    r\n    return sum(len(a.string) for a in TexSoup(tex).find_all(command))",
    "docstring": "r\"\"\"Measure solution length\n\n    :param Union[str,buffer] tex: the LaTeX source as a string or file buffer\n    :param str command: the command denoting a solution i.e., if the tex file\n        uses '\\answer{<answer here>}', then the command is 'answer'.\n    :return int: the solution length"
  },
  {
    "code": "def _setup_profiles(self, conversion_profiles):\n        for key, path in conversion_profiles.items():\n            if isinstance(path, str):\n                path = (path, )\n            for left, right in pair_looper(path):\n                pair = (_format(left), _format(right))\n                if pair not in self.converters:\n                    msg = 'Invalid conversion profile %s, unknown step %s'\n                    log.warning(msg % (repr(key), repr(pair)))\n                    break\n            else:\n                self.conversion_profiles[key] = path",
    "docstring": "Add given conversion profiles checking for invalid profiles"
  },
  {
    "code": "def get_signature_request_file(self, signature_request_id, path_or_file=None, file_type=None, filename=None):\n        request = self._get_request()\n        url = self.SIGNATURE_REQUEST_DOWNLOAD_PDF_URL + signature_request_id\n        if file_type:\n            url += '?file_type=%s' % file_type\n        return request.get_file(url, path_or_file or filename)",
    "docstring": "Download the PDF copy of the current documents\n\n        Args:\n\n            signature_request_id (str): Id of the signature request\n\n            path_or_file (str or file): A writable File-like object or a full path to save the PDF file to.\n\n            filename (str):             [DEPRECATED] Filename to save the PDF file to. This should be a full path.\n\n            file_type (str):            Type of file to return. Either \"pdf\" for a single merged document or \"zip\" for a collection of individual documents. Defaults to \"pdf\" if not specified.\n\n        Returns:\n            True if file is downloaded and successfully written, False otherwise."
  },
  {
    "code": "def all_balances(currency, services=None, verbose=False, timeout=None):\n    balances = {}\n    if not services:\n        services = [\n            x(verbose=verbose, timeout=timeout)\n            for x in ExchangeUniverse.get_authenticated_services()\n        ]\n    for e in services:\n        try:\n            balances[e] = e.get_exchange_balance(currency)\n        except NotImplementedError:\n            if verbose:\n                print(e.name, \"balance not implemented\")\n        except Exception as exc:\n            if verbose:\n                print(e.name, \"failed:\", exc.__class__.__name__, str(exc))\n    return balances",
    "docstring": "Get balances for passed in currency for all exchanges."
  },
  {
    "code": "def get_smooth_step_function(min_val, max_val, switch_point, smooth_factor):\n    dif = max_val - min_val\n    def _smooth_step(x):\n        return min_val + dif * tanh((x - switch_point) / smooth_factor)\n    return _smooth_step",
    "docstring": "Returns a function that moves smoothly between a minimal value and a\n    maximal one when its value increases from a given witch point to infinity.\n\n    Arguments\n    ---------\n    min_val: float\n        max_val value the function will return when x=switch_point.\n    min_val: float\n        The value the function will converge to when x -> infinity.\n    switch_point: float\n        The point in which the function's value will become min_val. Smaller\n        x values will return values smaller than min_val.\n    smooth_factor: float\n        The bigger the smoother, and less cliff-like, is the function.\n\n    Returns\n    -------\n    function\n        The desired smooth function."
  },
  {
    "code": "def minimum(self):\n        return min([(x, energy) for _, x, energy, _, _ in self.get_kinks()],\n                   key=lambda i: i[1])",
    "docstring": "Finds the minimum reaction energy E_min and corresponding\n        mixing ratio x_min.\n\n        Returns:\n            Tuple (x_min, E_min)."
  },
  {
    "code": "def _output_function_label(self):\n        if self.asm_code:\n            return True\n        if not self.blocks:\n            return True\n        the_block = next((b for b in self.blocks if b.addr == self.addr), None)\n        if the_block is None:\n            return True\n        if not the_block.instructions:\n            return True\n        if not the_block.instructions[0].labels:\n            return True\n        return False",
    "docstring": "Determines if we want to output the function label in assembly. We output the function label only when the\n        original instruction does not output the function label.\n\n        :return: True if we should output the function label, False otherwise.\n        :rtype: bool"
  },
  {
    "code": "def import_lsdinst(self, struct_data):\n        self.name = struct_data['name']\n        self.automate = struct_data['data']['automate']\n        self.pan = struct_data['data']['pan']\n        if self.table is not None:\n            self.table.import_lsdinst(struct_data)",
    "docstring": "import from an lsdinst struct"
  },
  {
    "code": "def search_track(self, artist, album=None, track=None,\n                     full_album_art_uri=False):\n        subcategories = [artist]\n        subcategories.append(album or '')\n        result = self.get_album_artists(\n            full_album_art_uri=full_album_art_uri,\n            subcategories=subcategories, search_term=track,\n            complete_result=True)\n        result._metadata['search_type'] = 'search_track'\n        return result",
    "docstring": "Search for an artist, an artist's albums, or specific track.\n\n        Args:\n            artist (str): an artist's name.\n            album (str, optional): an album name. Default `None`.\n            track (str, optional): a track name. Default `None`.\n            full_album_art_uri (bool): whether the album art URI should be\n                absolute (i.e. including the IP address). Default `False`.\n\n        Returns:\n            A `SearchResult` instance."
  },
  {
    "code": "def delete_datastore(self):\n        success, result = self._read_from_hdx('datastore', self.data['id'], 'resource_id',\n                                              self.actions()['datastore_delete'],\n                                              force=True)\n        if not success:\n            logger.debug(result)",
    "docstring": "Delete a resource from the HDX datastore\n\n        Returns:\n            None"
  },
  {
    "code": "def resend_welcome_message(self, user, base_url):\n        user.require_email_confirmation()\n        self.save(user)\n        self.send_welcome_message(user, base_url)",
    "docstring": "Regenerate email link and resend welcome"
  },
  {
    "code": "def _set_rc(self):\n        base_str = self._get_rc_strings()\n        pattern_base = map(lambda s: s.replace('.', '\\.'), base_str)\n        pattern = '(%s)(?=$)' % '|'.join(self._get_formatoptions())\n        self._rc = rcParams.find_and_replace(base_str, pattern=pattern,\n                                             pattern_base=pattern_base)\n        user_rc = SubDict(rcParams['plotter.user'], base_str, pattern=pattern,\n                          pattern_base=pattern_base)\n        self._rc.update(user_rc.data)\n        self._defaultParams = SubDict(rcParams.defaultParams, base_str,\n                                      pattern=pattern,\n                                      pattern_base=pattern_base)",
    "docstring": "Method to set the rcparams and defaultParams for this plotter"
  },
  {
    "code": "def auto_generate_missing_tabs(self):\n        for config in models_config.get_all_configs():\n            model_alias = '{}.{}'.format(config.app_label, config.model_name)\n            if model_alias not in self.tabs:\n                @self.register(model_alias)\n                def general_layout(obj):\n                    return Layout(\n                        Column12(\n                            Panel(\n                                'info',\n                                DescriptionList(*[f.name for f in obj.get_fields()])\n                            )\n                        )\n                    )",
    "docstring": "Auto generate tabs for models with no tabs"
  },
  {
    "code": "def dmxData(self, data: tuple):\n        newData = [0]*512\n        for i in range(0, min(len(data), 512)):\n            newData[i] = data[i]\n        self._dmxData = tuple(newData)\n        self.length = 126 + len(self._dmxData)",
    "docstring": "For legacy devices and to prevent errors, the length of the DMX data is normalized to 512"
  },
  {
    "code": "def hexdump(stream):\n    if isinstance(stream, six.string_types):\n        stream = BytesIO(stream)\n    row = 0\n    while True:\n        data = stream.read(16)\n        if not data:\n            break\n        hextets = data.encode('hex').ljust(32)\n        canonical = printable(data)\n        print('%08x %s  %s  |%s|' % (\n            row * 16,\n            ' '.join(hextets[x:x + 2] for x in range(0x00, 0x10, 2)),\n            ' '.join(hextets[x:x + 2] for x in range(0x10, 0x20, 2)),\n            canonical,\n        ))\n        row += 1",
    "docstring": "Display stream contents in hexadecimal and ASCII format. The ``stream``\n    specified must either be a file-like object that supports the ``read``\n    method to receive bytes, or it can be a string.\n\n    To dump a file::\n\n        >>> hexdump(file(filename))     # doctest: +SKIP\n\n    Or to dump stdin::\n\n        >>> import sys\n        >>> hexdump(sys.stdin)          # doctest: +SKIP\n\n    :param stream: stream input"
  },
  {
    "code": "def _get_gpu_pci_devices(self):\n        pci_device_list = self._get_pci_devices()\n        gpu_list = []\n        items = pci_device_list['Items']\n        for item in items:\n            if item['ClassCode'] in CLASSCODE_FOR_GPU_DEVICES:\n                if item['SubclassCode'] in SUBCLASSCODE_FOR_GPU_DEVICES:\n                    gpu_list.append(item)\n        return gpu_list",
    "docstring": "Returns the list of gpu devices."
  },
  {
    "code": "def get_filtering_contenthandler(element):\n    from ligo.lw.ligolw import FilteringLIGOLWContentHandler\n    from ligo.lw.table import Table\n    if issubclass(element, Table):\n        def _element_filter(name, attrs):\n            return ~element.CheckProperties(name, attrs)\n    else:\n        def _element_filter(name, _):\n            return name != element.tagName\n    return build_content_handler(FilteringLIGOLWContentHandler,\n                                 _element_filter)",
    "docstring": "Build a `FilteringLIGOLWContentHandler` to exclude this element\n\n    Parameters\n    ----------\n    element : `type`, subclass of :class:`~ligo.lw.ligolw.Element`\n        the element to exclude (and its children)\n\n    Returns\n    -------\n    contenthandler : `type`\n        a subclass of\n        :class:`~ligo.lw.ligolw.FilteringLIGOLWContentHandler` to\n        exclude an element and its children"
  },
  {
    "code": "def update(self, **kwargs):\n        return self.__class__(self.resource.update(kwargs),\n                              self.client,\n                              wallet=self.wallet)",
    "docstring": "Update the Account resource with specified content.\n\n        Args:\n          name (str): Human-readable name for the account\n\n        Returns: the updated Account object."
  },
  {
    "code": "def search(self):\n        safeEnvDict = {\n            'freeSearch': self.freeSearch,\n            'extentSearch': self.extentSearch,\n            'indexSearch': self.indexSearch\n        }\n        for col in self._dataFrame.columns:\n            safeEnvDict[col] = self._dataFrame[col]\n        try:\n            searchIndex = eval(self._filterString, {\n                               '__builtins__': None}, safeEnvDict)\n        except NameError:\n            return [], False\n        except SyntaxError:\n            return [], False\n        except ValueError:\n            return [], False\n        except TypeError:\n            return [], False\n        return searchIndex, True",
    "docstring": "Applies the filter to the stored dataframe.\n\n        A safe environment dictionary will be created, which stores all allowed\n        functions and attributes, which may be used for the filter.\n        If any object in the given `filterString` could not be found in the\n        dictionary, the filter does not apply and returns `False`.\n\n        Returns:\n            tuple: A (indexes, success)-tuple, which indicates identified objects\n                by applying the filter and if the operation was successful in\n                general."
  },
  {
    "code": "def name(self, address):\n        reversed_domain = address_to_reverse_domain(address)\n        return self.resolve(reversed_domain, get='name')",
    "docstring": "Look up the name that the address points to, using a\n        reverse lookup. Reverse lookup is opt-in for name owners.\n\n        :param address:\n        :type address: hex-string"
  },
  {
    "code": "def delivery_note_pdf(self, delivery_note_id):\n        return self._create_get_request(resource=DELIVERY_NOTES, billomat_id=delivery_note_id, command=PDF)",
    "docstring": "Opens a pdf of a delivery note\n\n        :param delivery_note_id: the delivery note id\n        :return: dict"
  },
  {
    "code": "def sigma_clip(data, sigma=3, sigma_lower=None, sigma_upper=None, maxiters=5,\n               cenfunc='median', stdfunc='std', axis=None, masked=True,\n               return_bounds=False, copy=True):\n    sigclip = SigmaClip(sigma=sigma, sigma_lower=sigma_lower,\n                        sigma_upper=sigma_upper, maxiters=maxiters,\n                        cenfunc=cenfunc, stdfunc=stdfunc)\n    return sigclip(data, axis=axis, masked=masked,\n                   return_bounds=return_bounds, copy=copy)",
    "docstring": "Perform sigma-clipping on the provided data.\n\n    The data will be iterated over, each time rejecting values that are\n    less or more than a specified number of standard deviations from a\n    center value.\n\n    Clipped (rejected) pixels are those where::\n\n        data < cenfunc(data [,axis=int]) - (sigma_lower * stdfunc(data [,axis=int]))\n        data > cenfunc(data [,axis=int]) + (sigma_upper * stdfunc(data [,axis=int]))\n\n    Invalid data values (i.e. NaN or inf) are automatically clipped.\n\n    For an object-oriented interface to sigma clipping, see\n    :class:`SigmaClip`.\n\n    .. note::\n        `scipy.stats.sigmaclip\n        <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.sigmaclip.html>`_\n        provides a subset of the functionality in this class.  Also, its\n        input data cannot be a masked array and it does not handle data\n        that contains invalid values (i.e.  NaN or inf).  Also note that\n        it uses the mean as the centering function.\n\n        If your data is a `~numpy.ndarray` with no invalid values and\n        you want to use the mean as the centering function with\n        ``axis=None`` and iterate to convergence, then\n        `scipy.stats.sigmaclip` is ~25-30% faster than the equivalent\n        settings here (``sigma_clip(data, cenfunc='mean', maxiters=None,\n        axis=None)``).\n\n    Parameters\n    ----------\n    data : array-like or `~numpy.ma.MaskedArray`\n        The data to be sigma clipped.\n\n    sigma : float, optional\n        The number of standard deviations to use for both the lower and\n        upper clipping limit.  These limits are overridden by\n        ``sigma_lower`` and ``sigma_upper``, if input.  The default is\n        3.\n\n    sigma_lower : float or `None`, optional\n        The number of standard deviations to use as the lower bound for\n        the clipping limit.  If `None` then the value of ``sigma`` is\n        used.  The default is `None`.\n\n    sigma_upper : float or `None`, optional\n        The number of standard deviations to use as the upper bound for\n        the clipping limit.  If `None` then the value of ``sigma`` is\n        used.  The default is `None`.\n\n    maxiters : int or `None`, optional\n        The maximum number of sigma-clipping iterations to perform or\n        `None` to clip until convergence is achieved (i.e., iterate\n        until the last iteration clips nothing).  If convergence is\n        achieved prior to ``maxiters`` iterations, the clipping\n        iterations will stop.  The default is 5.\n\n    cenfunc : {'median', 'mean'} or callable, optional\n        The statistic or callable function/object used to compute the\n        center value for the clipping.  If set to ``'median'`` or\n        ``'mean'`` then having the optional `bottleneck`_ package\n        installed will result in the best performance.  If using a\n        callable function/object and the ``axis`` keyword is used, then\n        it must be callable that can ignore NaNs (e.g. `numpy.nanmean`)\n        and has an ``axis`` keyword to return an array with axis\n        dimension(s) removed.  The default is ``'median'``.\n\n        .. _bottleneck:  https://github.com/kwgoodman/bottleneck\n\n    stdfunc : {'std'} or callable, optional\n        The statistic or callable function/object used to compute the\n        standard deviation about the center value.  If set to ``'std'``\n        then having the optional `bottleneck`_ package installed will\n        result in the best performance.  If using a callable\n        function/object and the ``axis`` keyword is used, then it must\n        be callable that can ignore NaNs (e.g. `numpy.nanstd`) and has\n        an ``axis`` keyword to return an array with axis dimension(s)\n        removed.  The default is ``'std'``.\n\n    axis : `None` or int or tuple of int, optional\n        The axis or axes along which to sigma clip the data.  If `None`,\n        then the flattened data will be used.  ``axis`` is passed to the\n        ``cenfunc`` and ``stdfunc``.  The default is `None`.\n\n    masked : bool, optional\n        If `True`, then a `~numpy.ma.MaskedArray` is returned, where the\n        mask is `True` for clipped values.  If `False`, then a\n        `~numpy.ndarray` and the minimum and maximum clipping thresholds\n        are returned.  The default is `True`.\n\n    return_bounds : bool, optional\n        If `True`, then the minimum and maximum clipping bounds are also\n        returned.\n\n    copy : bool, optional\n        If `True`, then the ``data`` array will be copied.  If `False`\n        and ``masked=True``, then the returned masked array data will\n        contain the same array as the input ``data`` (if ``data`` is a\n        `~numpy.ndarray` or `~numpy.ma.MaskedArray`).  The default is\n        `True`.\n\n    Returns\n    -------\n    result : flexible\n        If ``masked=True``, then a `~numpy.ma.MaskedArray` is returned,\n        where the mask is `True` for clipped values.  If\n        ``masked=False``, then a `~numpy.ndarray` is returned.\n\n        If ``return_bounds=True``, then in addition to the (masked)\n        array above, the minimum and maximum clipping bounds are\n        returned.\n\n        If ``masked=False`` and ``axis=None``, then the output array is\n        a flattened 1D `~numpy.ndarray` where the clipped values have\n        been removed.  If ``return_bounds=True`` then the returned\n        minimum and maximum thresholds are scalars.\n\n        If ``masked=False`` and ``axis`` is specified, then the output\n        `~numpy.ndarray` will have the same shape as the input ``data``\n        and contain ``np.nan`` where values were clipped.  If\n        ``return_bounds=True`` then the returned minimum and maximum\n        clipping thresholds will be be `~numpy.ndarray`\\\\s.\n\n    See Also\n    --------\n    SigmaClip, sigma_clipped_stats\n\n    Examples\n    --------\n    This example uses a data array of random variates from a Gaussian\n    distribution.  We clip all points that are more than 2 sample\n    standard deviations from the median.  The result is a masked array,\n    where the mask is `True` for clipped data::\n\n        >>> from astropy.stats import sigma_clip\n        >>> from numpy.random import randn\n        >>> randvar = randn(10000)\n        >>> filtered_data = sigma_clip(randvar, sigma=2, maxiters=5)\n\n    This example clips all points that are more than 3 sigma relative to\n    the sample *mean*, clips until convergence, returns an unmasked\n    `~numpy.ndarray`, and does not copy the data::\n\n        >>> from astropy.stats import sigma_clip\n        >>> from numpy.random import randn\n        >>> from numpy import mean\n        >>> randvar = randn(10000)\n        >>> filtered_data = sigma_clip(randvar, sigma=3, maxiters=None,\n        ...                            cenfunc=mean, masked=False, copy=False)\n\n    This example sigma clips along one axis::\n\n        >>> from astropy.stats import sigma_clip\n        >>> from numpy.random import normal\n        >>> from numpy import arange, diag, ones\n        >>> data = arange(5) + normal(0., 0.05, (5, 5)) + diag(ones(5))\n        >>> filtered_data = sigma_clip(data, sigma=2.3, axis=0)\n\n    Note that along the other axis, no points would be clipped, as the\n    standard deviation is higher."
  },
  {
    "code": "def basename(self, suffix=''):\n\t\treturn os.path.basename(self._file, suffix) if self._file else None",
    "docstring": "The basename of the template file."
  },
  {
    "code": "def get_my_subscribed_partitions(self, groupid, topic):\n        path = \"/consumers/{group_id}/offsets/{topic}\".format(\n            group_id=groupid,\n            topic=topic,\n        )\n        return self.get_children(path)",
    "docstring": "Get the list of partitions of a topic\n        that a consumer is subscribed to\n\n        :param: groupid: The consumer group ID for the consumer\n        :param: topic: The topic name\n        :returns list of partitions\n        :rtype: list"
  },
  {
    "code": "def pick_event_handler(self, event):\n        info = {'options': self.get_available_channels(),\n                'guiEvent': event.mouseevent.guiEvent,\n                }\n        if hasattr(self, 'xlabel_artist') and (event.artist == self.xlabel_artist):\n            info['axis_num'] = 0\n            self.callback(Event('axis_click', info))\n        if hasattr(self, 'ylabel_artist') and (event.artist == self.ylabel_artist):\n            info['axis_num'] = 1\n            self.callback(Event('axis_click', info))",
    "docstring": "Handles pick events"
  },
  {
    "code": "def rooms(request, template=\"rooms.html\"):\n    context = {\"rooms\": ChatRoom.objects.all()}\n    return render(request, template, context)",
    "docstring": "Homepage - lists all rooms."
  },
  {
    "code": "def get_pycons3rt_home_dir():\n    if platform.system() == 'Linux':\n        return os.path.join(os.path.sep, 'etc', 'pycons3rt')\n    elif platform.system() == 'Windows':\n        return os.path.join('C:', os.path.sep, 'pycons3rt')\n    elif platform.system() == 'Darwin':\n        return os.path.join(os.path.expanduser('~'), '.pycons3rt')\n    else:\n        raise OSError('Unsupported Operating System')",
    "docstring": "Returns the pycons3rt home directory based on OS\n\n    :return: (str) Full path to pycons3rt home\n    :raises: OSError"
  },
  {
    "code": "def _unpickle_collection(self, collection):\n        for mkey in collection:\n            if isinstance(collection[mkey], list):\n                for item in collection[mkey]:\n                    item.unpickle(self)\n            else:\n                collection[mkey].unpickle(self)",
    "docstring": "Unpickles all members of the specified dictionary."
  },
  {
    "code": "def _to_ned(self):\n        if self.ref_frame is 'USE':\n            return utils.use_to_ned(self.tensor), \\\n                utils.use_to_ned(self.tensor_sigma)\n        elif self.ref_frame is 'NED':\n            return self.tensor, self.tensor_sigma\n        else:\n            raise ValueError('Reference frame %s not recognised - cannot '\n                             'transform to NED!' % self.ref_frame)",
    "docstring": "Switches the reference frame to NED"
  },
  {
    "code": "def get_available_references(self, datas):\n        names = []\n        for k, v in datas.items():\n            if k.startswith(RULE_REFERENCE):\n                names.append(k[len(RULE_REFERENCE)+1:])\n        return names",
    "docstring": "Get available manifest reference names.\n\n        Every rules starting with prefix from ``nomenclature.RULE_REFERENCE``\n        are available references.\n\n        Only name validation is performed on these references.\n\n        Arguments:\n            datas (dict): Data where to search for reference declarations.\n\n        Returns:\n            list: List of every available reference names. This is the real\n                name unprefixed."
  },
  {
    "code": "def metadata(self):\n        if self._metadata is None:\n            try:\n                with open(self.paths.metadata()) as metadata_fd:\n                    self._metadata = json.load(metadata_fd)\n            except IOError:\n                self._metadata = {}\n        return self._metadata",
    "docstring": "Retrieve the metadata info for this prefix\n\n        Returns:\n            dict: metadata info"
  },
  {
    "code": "def CreateGallery():\n    url = 'http://min.us/api/CreateGallery'\n    response = _dopost(url)\n    _editor_id = response[\"editor_id\"]\n    _reader_id = response[\"reader_id\"]\n    return Gallery(_reader_id, editor_id=_editor_id)",
    "docstring": "Creates a Gallery on the server. Returns a Gallery object with the\n    editor_id and reader_id."
  },
  {
    "code": "def get_indelcaller(d_or_c):\n    config = d_or_c if isinstance(d_or_c, dict) and \"config\" in d_or_c else d_or_c\n    indelcaller = config[\"algorithm\"].get(\"indelcaller\", \"\")\n    if not indelcaller:\n        indelcaller = \"\"\n    if isinstance(indelcaller, (list, tuple)):\n        indelcaller = indelcaller[0] if (len(indelcaller) > 0) else \"\"\n    return indelcaller",
    "docstring": "Retrieve string for indelcaller to use, or empty string if not specified."
  },
  {
    "code": "def to_header(self):\n        if self.star_tag:\n            return \"*\"\n        return \", \".join(\n            ['\"%s\"' % x for x in self._strong] + ['W/\"%s\"' % x for x in self._weak]\n        )",
    "docstring": "Convert the etags set into a HTTP header string."
  },
  {
    "code": "def populate_csv_headers(rows,\n                         partial_headers,\n                         column_headers_count=1):\n    result = [''] * (len(rows) - column_headers_count)\n    for i_index in range(0, len(partial_headers)):\n        for k_index in range(0, len(partial_headers[i_index])):\n            if not partial_headers[i_index][k_index] and i_index - 1 >= 0:\n                for t_index in range(i_index - 1, -1, -1):\n                    partial_value = partial_headers[t_index][k_index]\n                    if partial_value:\n                        partial_headers[i_index][k_index] = partial_value\n                        break\n        result[i_index] = \" \".join(map(str, partial_headers[i_index]))\n    return result",
    "docstring": "Populate csv rows headers when are empty, extending the superior or\n    upper headers."
  },
  {
    "code": "def LogHttpFrontendAccess(self, request, source=None, message_count=None):\n    event_id = self.GetNewEventId()\n    log_msg = \"%s-%s [%s]: %s %s %s %s (%d)\" % (\n        event_id, request.source_ip, source or \"<unknown>\", request.method,\n        request.url, request.user_agent, request.user, message_count or 0)\n    logging.info(log_msg)",
    "docstring": "Write a log entry for a Frontend or UI Request.\n\n    Args:\n      request: A HttpRequest protobuf.\n      source: Client id of the client initiating the request. Optional.\n      message_count: Number of messages received from the client. Optional."
  },
  {
    "code": "def use_plenary_repository_view(self):\n        self._repository_view = PLENARY\n        for session in self._get_provider_sessions():\n            try:\n                session.use_plenary_repository_view()\n            except AttributeError:\n                pass",
    "docstring": "Pass through to provider AssetRepositorySession.use_plenary_repository_view"
  },
  {
    "code": "def transcriptions(self):\n        if self._transcriptions is None:\n            self._transcriptions = TranscriptionList(self._version, account_sid=self._solution['sid'], )\n        return self._transcriptions",
    "docstring": "Access the transcriptions\n\n        :returns: twilio.rest.api.v2010.account.transcription.TranscriptionList\n        :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionList"
  },
  {
    "code": "def set_rows(self, ids):\n        assert all(isinstance(i, int) for i in ids)\n        sort_col, sort_dir = self.current_sort\n        default_sort_col, default_sort_dir = self.default_sort\n        sort_col = sort_col or default_sort_col\n        sort_dir = sort_dir or default_sort_dir or 'desc'\n        logger.log(5, \"Set %d rows in the table.\", len(ids))\n        items = [self._get_row(id) for id in ids]\n        data = _create_json_dict(items=items,\n                                 cols=self.column_names,\n                                 )\n        self.eval_js('table.setData({});'.format(data))\n        if sort_col:\n            self.sort_by(sort_col, sort_dir)",
    "docstring": "Set the rows of the table."
  },
  {
    "code": "def _history_buffer_pos_changed(self, _):\n        if self.app.current_buffer == self.history_buffer:\n            line_no = self.history_buffer.document.cursor_position_row\n            if line_no in self.history_mapping.selected_lines:\n                default_lineno = sorted(self.history_mapping.selected_lines).index(line_no) + \\\n                    self.history_mapping.result_line_offset\n                self.default_buffer.cursor_position = \\\n                    self.default_buffer.document.translate_row_col_to_index(default_lineno, 0)",
    "docstring": "When the cursor changes in the history buffer. Synchronize."
  },
  {
    "code": "def generate_schema_file(config_file):\n    config = utils.load_config_from_ini_file(config_file)\n    schema = {}\n    for section_name in config:\n        for option_name in config[section_name]:\n            schema.setdefault(section_name, {}).setdefault(option_name, {})\n            schema[section_name][option_name]['description'] = 'No description provided.'\n    return utils.dump_schema_file(schema)",
    "docstring": "Generates a basic confirm schema file from a configuration file."
  },
  {
    "code": "def tickets(self, extra_params=None):\n        params = {\n            'per_page': settings.MAX_PER_PAGE,\n            'report': 0,\n        }\n        if extra_params:\n            params.update(extra_params)\n        return self.api._get_json(\n            Ticket,\n            space=self,\n            rel_path=self._build_rel_path('tickets'),\n            extra_params=params,\n            get_all=True,\n        )",
    "docstring": "All Tickets in this Space"
  },
  {
    "code": "def get_version():\n    if all([VERSION, UPDATED, any([isinstance(UPDATED, date), isinstance(UPDATED, datetime), ]), ]):\n        return FORMAT_STRING.format(**{\"version\": VERSION, \"updated\": UPDATED, })\n    elif VERSION:\n        return VERSION\n    elif UPDATED:\n        return localize(UPDATED) if any([isinstance(UPDATED, date), isinstance(UPDATED, datetime), ]) else \"\"\n    else:\n        return \"\"",
    "docstring": "Return formatted version string.\n\n    Returns:\n        str: string with project version or empty string."
  },
  {
    "code": "def _initVirtualOutputs(self):\n        self.virtualOutputs = {}\n        for product in self.outputNames:\n            self.virtualOutputs[product] = None",
    "docstring": "Sets up the structure to hold all the output data arrays for\n        this image in memory."
  },
  {
    "code": "def update_vlan(self, name, vid, vni):\n        cmd = 'vxlan vlan %s vni %s' % (vid, vni)\n        return self.configure_interface(name, cmd)",
    "docstring": "Adds a new vlan to vni mapping for the interface\n\n        EosVersion:\n            4.13.7M\n\n        Args:\n            vlan (str, int): The vlan id to map to the vni\n            vni (str, int): The vni value to use\n\n        Returns:\n            True if the command completes successfully"
  },
  {
    "code": "def initialize(self, app: Flask, app_config):\n        debug = app_config[\"debug\"]\n        port = app_config[\"http.port\"]\n        if debug:\n            self.started_on_port = port\n            app.run(host=\"0.0.0.0\", debug=True, port=port)\n        else:\n            for port in range(port, port + 50):\n                self.http_server = WSGIServer(('0.0.0.0', port), app)\n                try:\n                    self.http_server.start()\n                except OSError:\n                    continue\n                self.started_on_port = port\n                break",
    "docstring": "Prepare the server to run and determine the port.\n\n        :param app: The Flask Application.\n        :param app_config: Configuration dictionary. This module uses the `debug`\n        (`True`/`False`) and `http.port` attributes."
  },
  {
    "code": "def count_protein_group_hits(lineproteins, groups):\n    hits = []\n    for group in groups:\n        hits.append(0)\n        for protein in lineproteins:\n            if protein in group:\n                hits[-1] += 1\n    return [str(x) for x in hits]",
    "docstring": "Takes a list of protein accessions and a list of protein groups\n    content from DB. Counts for each group in list how many proteins\n    are found in lineproteins. Returns list of str amounts."
  },
  {
    "code": "def set_monitoring_transaction_name(name, group=None, priority=None):\n    if not newrelic:\n        return\n    newrelic.agent.set_transaction_name(name, group, priority)",
    "docstring": "Sets the transaction name for monitoring.\n\n    This is not cached, and only support reporting to New Relic."
  },
  {
    "code": "def parse_list_objects_v2(data, bucket_name):\n    root = S3Element.fromstring('ListObjectV2Result', data)\n    is_truncated = root.get_child_text('IsTruncated').lower() == 'true'\n    continuation_token = root.get_child_text('NextContinuationToken',\n                                             strict=False)\n    objects, object_dirs = _parse_objects_from_xml_elts(\n        bucket_name,\n        root.findall('Contents'),\n        root.findall('CommonPrefixes')\n    )\n    return objects + object_dirs, is_truncated, continuation_token",
    "docstring": "Parser for list objects version 2 response.\n\n    :param data: Response data for list objects.\n    :param bucket_name: Response for the bucket.\n    :return: Returns three distinct components:\n       - List of :class:`Object <Object>`\n       - True if list is truncated, False otherwise.\n       - Continuation Token for the next request."
  },
  {
    "code": "def verify(ctx):\n    oks = run_configurations(\n        skipper(verify_environments),\n        read_sections,\n    )\n    ctx.exit(0\n             if False not in oks\n             else 1)",
    "docstring": "Upgrade locked dependency versions"
  },
  {
    "code": "def line_intersects_itself(lons, lats, closed_shape=False):\n    assert len(lons) == len(lats)\n    if len(lons) <= 3:\n        return False\n    west, east, north, south = get_spherical_bounding_box(lons, lats)\n    proj = OrthographicProjection(west, east, north, south)\n    xx, yy = proj(lons, lats)\n    if not shapely.geometry.LineString(list(zip(xx, yy))).is_simple:\n        return True\n    if closed_shape:\n        xx, yy = proj(numpy.roll(lons, 1), numpy.roll(lats, 1))\n        if not shapely.geometry.LineString(list(zip(xx, yy))).is_simple:\n            return True\n    return False",
    "docstring": "Return ``True`` if line of points intersects itself.\n    Line with the last point repeating the first one considered\n    intersecting itself.\n\n    The line is defined by lists (or numpy arrays) of points'\n    longitudes and latitudes (depth is not taken into account).\n\n    :param closed_shape:\n        If ``True`` the line will be checked twice: first time with\n        its original shape and second time with the points sequence\n        being shifted by one point (the last point becomes first,\n        the first turns second and so on). This is useful for\n        checking that the sequence of points defines a valid\n        :class:`~openquake.hazardlib.geo.polygon.Polygon`."
  },
  {
    "code": "def set_approvers(self, approver_ids=[], approver_group_ids=[], **kwargs):\n        path = '%s/%s/approvers' % (self._parent.manager.path,\n                                    self._parent.get_id())\n        data = {'approver_ids': approver_ids,\n                'approver_group_ids': approver_group_ids}\n        self.gitlab.http_put(path, post_data=data, **kwargs)",
    "docstring": "Change MR-level allowed approvers and approver groups.\n\n        Args:\n            approver_ids (list): User IDs that can approve MRs\n            approver_group_ids (list): Group IDs whose members can approve MRs\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabUpdateError: If the server failed to perform the request"
  },
  {
    "code": "def get_type(type_name):\n    parts = type_name.split('.')\n    if len(parts) < 2:\n        raise SphinxError(\n            'Type must be fully-qualified, '\n            'of the form ``module.MyClass``. Got: {}'.format(type_name)\n        )\n    module_name = \".\".join(parts[0:-1])\n    name = parts[-1]\n    return getattr(import_module(module_name), name)",
    "docstring": "Get a type given its importable name.\n\n    Parameters\n    ----------\n    task_name : `str`\n        Name of the Python type, such as ``mypackage.MyClass``.\n\n    Returns\n    -------\n    object\n        The object."
  },
  {
    "code": "def ignore_reports(self):\n        url = self.reddit_session.config['ignore_reports']\n        data = {'id': self.fullname}\n        return self.reddit_session.request_json(url, data=data)",
    "docstring": "Ignore future reports on this object.\n\n        This prevents future reports from causing notifications or appearing\n        in the various moderation listing. The report count will still\n        increment."
  },
  {
    "code": "def _check_tagmode_and_tmos_version(self, **kwargs):\n        tmos_version = self._meta_data['bigip']._meta_data['tmos_version']\n        if LooseVersion(tmos_version) < LooseVersion('11.6.0'):\n            msg = \"The parameter, 'tagMode', is not allowed against the \" \\\n                \"following version of TMOS: %s\" % (tmos_version)\n            if 'tagMode' in kwargs or hasattr(self, 'tagMode'):\n                raise TagModeDisallowedForTMOSVersion(msg)",
    "docstring": "Raise an exception if tagMode in kwargs and tmos version < 11.6.0\n\n        :param kwargs: dict -- keyword arguments for request\n        :raises: TagModeDisallowedForTMOSVersion"
  },
  {
    "code": "def create_domain(self, domain_name):\n        params = {'DomainName':domain_name}\n        d = self.get_object('CreateDomain', params, Domain)\n        d.name = domain_name\n        return d",
    "docstring": "Create a SimpleDB domain.\n\n        :type domain_name: string\n        :param domain_name: The name of the new domain\n\n        :rtype: :class:`boto.sdb.domain.Domain` object\n        :return: The newly created domain"
  },
  {
    "code": "def add_predicate(self, key, value, predicate_type='equals'):\n        if predicate_type not in operators:\n            predicate_type = operator_lkup.get(predicate_type)\n        if predicate_type:\n            self.predicates.append({'type': predicate_type,\n                                    'key': key,\n                                    'value': value\n                                    })\n        else:\n            raise Exception(\"predicate type not a valid operator\")",
    "docstring": "add key, value, type combination of a predicate\n\n        :param key: query KEY parameter\n        :param value: the value used in the predicate\n        :param predicate_type: the type of predicate (e.g. ``equals``)"
  },
  {
    "code": "def positional(max_positional_args):\n    def positional_decorator(wrapped):\n        @functools.wraps(wrapped)\n        def positional_wrapper(*args, **kwargs):\n            if len(args) > max_positional_args:\n                plural_s = ''\n                if max_positional_args != 1:\n                    plural_s = 's'\n                raise TypeError('%s() takes at most %d positional argument%s '\n                                '(%d given)' % (wrapped.__name__,\n                                                max_positional_args,\n                                                plural_s, len(args)))\n            return wrapped(*args, **kwargs)\n        return positional_wrapper\n    if isinstance(max_positional_args, six.integer_types):\n        return positional_decorator\n    else:\n        args, _, _, defaults = inspect.getargspec(max_positional_args)\n        if defaults is None:\n            raise ValueError(\n                'Functions with no keyword arguments must specify '\n                'max_positional_args')\n        return positional(len(args) - len(defaults))(max_positional_args)",
    "docstring": "A decorator that declares only the first N arguments may be positional.\n\n    This decorator makes it easy to support Python 3 style keyword-only\n    parameters. For example, in Python 3 it is possible to write:\n\n      def fn(pos1, *, kwonly1=None, kwonly1=None):\n        ...\n\n    All named parameters after * must be a keyword:\n\n      fn(10, 'kw1', 'kw2')  # Raises exception.\n      fn(10, kwonly1='kw1')  # Ok.\n\n    Example:\n      To define a function like above, do:\n\n        @positional(1)\n        def fn(pos1, kwonly1=None, kwonly2=None):\n          ...\n\n      If no default value is provided to a keyword argument, it\n      becomes a required keyword argument:\n\n        @positional(0)\n        def fn(required_kw):\n          ...\n\n      This must be called with the keyword parameter:\n\n        fn()  # Raises exception.\n        fn(10)  # Raises exception.\n        fn(required_kw=10)  # Ok.\n\n      When defining instance or class methods always remember to account for\n      'self' and 'cls':\n\n        class MyClass(object):\n\n          @positional(2)\n          def my_method(self, pos1, kwonly1=None):\n            ...\n\n          @classmethod\n          @positional(2)\n          def my_method(cls, pos1, kwonly1=None):\n            ...\n\n      One can omit the argument to 'positional' altogether, and then no\n      arguments with default values may be passed positionally. This\n      would be equivalent to placing a '*' before the first argument\n      with a default value in Python 3. If there are no arguments with\n      default values, and no argument is given to 'positional', an error\n      is raised.\n\n        @positional\n        def fn(arg1, arg2, required_kw1=None, required_kw2=0):\n          ...\n\n        fn(1, 3, 5)  # Raises exception.\n        fn(1, 3)  # Ok.\n        fn(1, 3, required_kw1=5)  # Ok.\n\n    Args:\n      max_positional_arguments: Maximum number of positional arguments.  All\n        parameters after the this index must be keyword only.\n\n    Returns:\n      A decorator that prevents using arguments after max_positional_args from\n      being used as positional parameters.\n\n    Raises:\n      TypeError if a keyword-only argument is provided as a positional\n        parameter.\n      ValueError if no maximum number of arguments is provided and the function\n        has no arguments with default values."
  },
  {
    "code": "def _validate(self, data, owner=None):\n        if isinstance(data, DynamicValue):\n            data = data()\n        if data is None and not self.nullable:\n            raise ValueError('Value can not be null')\n        elif data is not None:\n            isdict = isinstance(data, dict)\n            for name, schema in iteritems(self.getschemas()):\n                if name == 'default':\n                    continue\n                if name in self.required:\n                    if (\n                        (isdict and name not in data) or\n                        (not isdict and not hasattr(data, name))\n                    ):\n                        part1 = (\n                            'Mandatory property {0} by {1} is missing in {2}.'.\n                            format(name, self, data)\n                        )\n                        part2 = '{0} expected.'.format(schema)\n                        error = '{0} {1}'.format(part1, part2)\n                        raise ValueError(error)\n                elif (isdict and name in data) or hasattr(data, name):\n                    value = data[name] if isdict else getattr(data, name)\n                    schema._validate(data=value, owner=self)",
    "docstring": "Validate input data in returning an empty list if true.\n\n        :param data: data to validate with this schema.\n        :param Schema owner: schema owner.\n        :raises: Exception if the data is not validated."
  },
  {
    "code": "def add_entry_point(self, destination):\n        self.routes.setdefault('__entry_point', set()).add(destination)\n        return self.routes['__entry_point']",
    "docstring": "\\\n        Add an entry point\n\n        :param destination: node to route to initially\n        :type destination: str"
  },
  {
    "code": "def write(self, session, directory, name, maskMap):\n        name_split = name.split('.')\n        name = name_split[0]\n        extension = ''\n        if len(name_split) >= 2:\n            extension = name_split[-1]\n        try:\n            name = self._namePreprocessor(name)\n        except:\n            'DO NOTHING'\n        if extension == '':\n            filename = '{0}.{1}'.format(name, self.fileExtension)\n        else:\n            filename = '{0}.{1}'.format(name, extension)\n        filePath = os.path.join(directory, filename)\n        with open(filePath, 'w') as openFile:\n            self._write(session=session,\n                        openFile=openFile,\n                        maskMap=maskMap)",
    "docstring": "Write from database to file.\n\n        *session* = SQLAlchemy session object\\n\n        *directory* = to which directory will the files be written (e.g.: '/example/path')\\n\n        *name* = name of file that will be written (e.g.: 'my_project.ext')\\n"
  },
  {
    "code": "async def start(self) -> None:\n        if self._is_running:\n            raise SublemonRuntimeError(\n                'Attempted to start an already-running `Sublemon` instance')\n        self._poll_task = asyncio.ensure_future(self._poll())\n        self._is_running = True",
    "docstring": "Coroutine to run this server."
  },
  {
    "code": "def sca_xsect(scatterer, h_pol=True):\n    if scatterer.psd_integrator is not None:\n        return scatterer.psd_integrator.get_angular_integrated(\n            scatterer.psd, scatterer.get_geometry(), \"sca_xsect\")\n    old_geom = scatterer.get_geometry()    \n    def d_xsect(thet, phi):\n        (scatterer.phi, scatterer.thet) = (phi*rad_to_deg, thet*rad_to_deg)        \n        Z = scatterer.get_Z()        \n        I = sca_intensity(scatterer, h_pol)\n        return I * np.sin(thet)\n    try:\n        xsect = dblquad(d_xsect, 0.0, 2*np.pi, lambda x: 0.0, \n            lambda x: np.pi)[0]\n    finally:\n        scatterer.set_geometry(old_geom)\n    return xsect",
    "docstring": "Scattering cross section for the current setup, with polarization.    \n\n    Args:\n        scatterer: a Scatterer instance.\n        h_pol: If True (default), use horizontal polarization.\n        If False, use vertical polarization.\n\n    Returns:\n        The scattering cross section."
  },
  {
    "code": "def init(cls, path):\n        if not os.path.exists( path ):\n            block_header_serializer = BlockHeaderSerializer()\n            genesis_block_header = BlockHeader()\n            if USE_MAINNET:\n                genesis_block_header.version = 1\n                genesis_block_header.prev_block = 0\n                genesis_block_header.merkle_root = int(GENESIS_BLOCK_MERKLE_ROOT, 16 )\n                genesis_block_header.timestamp = 1231006505\n                genesis_block_header.bits = int( \"1d00ffff\", 16 )\n                genesis_block_header.nonce = 2083236893\n                genesis_block_header.txns_count = 0\n                with open(path, \"wb\") as f:\n                    bin_data = block_header_serializer.serialize( genesis_block_header )\n                    f.write( bin_data )",
    "docstring": "Set up an SPV client.\n        If the locally-stored headers do not exist, then \n        create a stub headers file with the genesis block information."
  },
  {
    "code": "def find_syslog_address():\n    if sys.platform == 'darwin' and os.path.exists(LOG_DEVICE_MACOSX):\n        return LOG_DEVICE_MACOSX\n    elif os.path.exists(LOG_DEVICE_UNIX):\n        return LOG_DEVICE_UNIX\n    else:\n        return 'localhost', logging.handlers.SYSLOG_UDP_PORT",
    "docstring": "Find the most suitable destination for system log messages.\n\n    :returns: The pathname of a log device (a string) or an address/port tuple as\n              supported by :class:`~logging.handlers.SysLogHandler`.\n\n    On Mac OS X this prefers :data:`LOG_DEVICE_MACOSX`, after that :data:`LOG_DEVICE_UNIX`\n    is checked for existence. If both of these device files don't exist the default used\n    by :class:`~logging.handlers.SysLogHandler` is returned."
  },
  {
    "code": "def string2identifier(s):\n    if len(s) == 0:\n        return \"_\"\n    if s[0] not in string.ascii_letters:\n        s = \"_\" + s\n    valids = string.ascii_letters + string.digits + \"_\"\n    out = \"\"\n    for i, char in enumerate(s):\n        if char in valids:\n            out += char\n        else:\n            out += \"_\"\n    return out",
    "docstring": "Turn a string into a valid python identifier.\n\n    Currently only allows ASCII letters and underscore. Illegal characters\n    are replaced with underscore. This is slightly more opinionated than\n    python 3 itself, and may be refactored in future (see PEP 3131).\n\n    Parameters\n    ----------\n    s : string\n        string to convert\n\n    Returns\n    -------\n    str\n        valid python identifier."
  },
  {
    "code": "def samples(self):\n        names = self.series.dimensions\n        for n, offset in enumerate(self.series.offsets):\n            dt = datetime.timedelta(microseconds=offset * 1000)\n            d = {\"ts\": self.ts + dt}\n            for name in names:\n                d[name] = getattr(self.series, name)[n]\n            yield d",
    "docstring": "Yield samples as dictionaries, keyed by dimensions."
  },
  {
    "code": "def parse_date(table_data):\n        text = table_data.text.split('Added on ')\n        if len(text) < 2:\n            return date.today()\n        return datetime.strptime(text[1], Parser.DATE_STRPTIME_FORMAT).date()",
    "docstring": "Static method that parses a given table data element with `Url.DATE_STRPTIME_FORMAT` and creates a `date` object from td's text contnet.\n\n        :param lxml.HtmlElement table_data: table_data tag to parse\n        :return: date object from td's text date\n        :rtype: datetime.date"
  },
  {
    "code": "def end_segment(self, end_time=None):\n        entity = self.get_trace_entity()\n        if not entity:\n            log.warning(\"No segment to end\")\n            return\n        if self._is_subsegment(entity):\n            entity.parent_segment.close(end_time)\n        else:\n            entity.close(end_time)",
    "docstring": "End the current active segment.\n\n        :param int end_time: epoch in seconds. If not specified the current\n            system time will be used."
  },
  {
    "code": "def make_action_list(self, item_list, **kwargs):\r\n        action_list = []\r\n        es_index = get2(kwargs, \"es_index\", self.es_index)\r\n        action_type = kwargs.get(\"action_type\",\"index\")\r\n        action_settings = {'_op_type': action_type,\r\n                           '_index': es_index}\r\n        doc_type = kwargs.get(\"doc_type\", self.doc_type)\r\n        if not doc_type:\r\n            doc_type = \"unk\"\r\n        id_field = kwargs.get(\"id_field\")\r\n        for item in item_list:\r\n            action = get_es_action_item(item,\r\n                                        action_settings,\r\n                                        doc_type,\r\n                                        id_field)\r\n            action_list.append(action)\r\n        return action_list",
    "docstring": "Generates a list of actions for sending to Elasticsearch"
  },
  {
    "code": "def position(self):\n        return {k.upper(): v for k, v in self._position.items()}",
    "docstring": "Instead of sending M114.2 we are storing target values in\n        self._position since movement and home commands are blocking and\n        assumed to go the correct place.\n\n        Cases where Smoothie would not be in the correct place (such as if a\n        belt slips) would not be corrected by getting position with M114.2\n        because Smoothie would also not be aware of slippage."
  },
  {
    "code": "def send(self, data):\n        _vv and IOLOG.debug('%r.send(%r..)', self, repr(data)[:100])\n        self.context.send(Message.pickled(data, handle=self.dst_handle))",
    "docstring": "Send `data` to the remote end."
  },
  {
    "code": "def write_multi(self, frames, encoded_frames=None):\n    if encoded_frames is None:\n      encoded_frames = iter(lambda: None, 1)\n    for (frame, encoded_frame) in zip(frames, encoded_frames):\n      self.write(frame, encoded_frame)",
    "docstring": "Writes multiple video frames."
  },
  {
    "code": "def serialize(self):\n        commands = []\n        for cmd in self.commands:\n            commands.append(cmd.serialize())\n        out = {'commands': commands, 'deviceURL': self.__device_url}\n        return out",
    "docstring": "Serialize action."
  },
  {
    "code": "def build_flags(library, type_, path):\n    pkg_config_path = [path]\n    if \"PKG_CONFIG_PATH\" in os.environ:\n        pkg_config_path.append(os.environ['PKG_CONFIG_PATH'])\n    if \"LIB_DIR\" in os.environ:\n        pkg_config_path.append(os.environ['LIB_DIR'])\n        pkg_config_path.append(os.path.join(os.environ['LIB_DIR'], \"pkgconfig\"))\n    options = [\n        \"--static\",\n        {\n            'I': \"--cflags-only-I\",\n            'L': \"--libs-only-L\",\n            'l': \"--libs-only-l\"\n        }[type_]\n    ]\n    return [\n        flag.strip(\"-{}\".format(type_))\n        for flag\n        in subprocess.check_output(\n            [\"pkg-config\"] + options + [library],\n            env=dict(os.environ, PKG_CONFIG_PATH=\":\".join(pkg_config_path))\n        ).decode(\"UTF-8\").split()\n    ]",
    "docstring": "Return separated build flags from pkg-config output"
  },
  {
    "code": "def update(self):\n        step = self.geometry.astep\n        s = self.extract()\n        self.mean = np.mean(s[2])\n        gradient, gradient_error = self._get_gradient(step)\n        previous_gradient = self.gradient\n        if not previous_gradient:\n            previous_gradient = -0.05\n        if gradient >= (previous_gradient / 3.):\n            gradient, gradient_error = self._get_gradient(2 * step)\n        if gradient >= (previous_gradient / 3.):\n            gradient = previous_gradient * 0.8\n            gradient_error = None\n        self.gradient = gradient\n        self.gradient_error = gradient_error\n        if gradient_error:\n            self.gradient_relative_error = gradient_error / np.abs(gradient)\n        else:\n            self.gradient_relative_error = None",
    "docstring": "Update this `~photutils.isophote.EllipseSample` instance.\n\n        This method calls the\n        :meth:`~photutils.isophote.EllipseSample.extract` method to get\n        the values that match the current ``geometry`` attribute, and\n        then computes the the mean intensity, local gradient, and other\n        associated quantities."
  },
  {
    "code": "def list(self):\n        backups = []\n        for d in glob(join(self.backup_directory, '*')):\n            backups.append(WorkspaceBackup.from_path(d))\n        backups.sort(key=lambda b: b.lastmod, reverse=True)\n        return backups",
    "docstring": "List all backups as WorkspaceBackup objects, sorted descending by lastmod."
  },
  {
    "code": "def cases(arg, case_result_pairs, default=None):\n    builder = arg.case()\n    for case, result in case_result_pairs:\n        builder = builder.when(case, result)\n    if default is not None:\n        builder = builder.else_(default)\n    return builder.end()",
    "docstring": "Create a case expression in one shot.\n\n    Returns\n    -------\n    case_expr : SimpleCase"
  },
  {
    "code": "def _set_dict_translations(instance, dict_translations):\n\tif not hasattr(instance._meta, \"translatable_fields\"):\n\t\treturn False\n\tif site_is_monolingual():\n\t\treturn False\n\ttranslatable_fields = instance._meta.translatable_fields\n\tfor field in translatable_fields:\n\t\tfor lang in settings.LANGUAGES:\n\t\t\tlang = lang[0]\n\t\t\tif lang != settings.LANGUAGE_CODE:\n\t\t\t\ttrans_field = trans_attr(field,lang)\n\t\t\t\tif dict_translations.has_key(trans_field):\n\t\t\t\t\tsetattr(instance,trans_field,dict_translations[trans_field])\n\t\t\t\ttrans_isfuzzy = trans_is_fuzzy_attr(field,lang)\n\t\t\t\tif dict_translations.has_key(trans_isfuzzy):\n\t\t\t\t\tis_fuzzy_value = (dict_translations[trans_isfuzzy]==\"1\") or (dict_translations[trans_isfuzzy]==1)\n\t\t\t\t\tsetattr(instance,trans_isfuzzy, is_fuzzy_value)",
    "docstring": "Establece los atributos de traducciones a partir de una dict que\n\tcontiene todas las traducciones."
  },
  {
    "code": "def escape_string(string):\n    result = string\n    result = result.replace('\\\\', '\\\\\\\\')\n    result = result.replace('\"', '\\\\\"')\n    return '\"' + result + '\"'",
    "docstring": "Escape a string for use in Gerrit commands.\n\n    :arg str string: The string to escape.\n\n    :returns: The string with necessary escapes and surrounding double quotes\n        so that it can be passed to any of the Gerrit commands that require\n        double-quoted strings."
  },
  {
    "code": "def _request_process_json_standard(self, response_data):\n        data = response_data.get('data', {}).get(self.request_entity, [])\n        status = response_data.get('status', 'Failure')\n        return data, status",
    "docstring": "Handle JSON response\n\n        This should be the most common response from the ThreatConnect API.\n\n        Return:\n            (string): The response data\n            (string): The response status"
  },
  {
    "code": "def any_contains_any(strings, candidates):\r\n    for string in strings:\r\n        for c in candidates:\r\n            if c in string:\r\n                return True",
    "docstring": "Whether any of the strings contains any of the candidates."
  },
  {
    "code": "def media_type_str(mediatype):\n    if mediatype == const.MEDIA_TYPE_UNKNOWN:\n        return 'Unknown'\n    if mediatype == const.MEDIA_TYPE_VIDEO:\n        return 'Video'\n    if mediatype == const.MEDIA_TYPE_MUSIC:\n        return 'Music'\n    if mediatype == const.MEDIA_TYPE_TV:\n        return 'TV'\n    return 'Unsupported'",
    "docstring": "Convert internal API media type to string."
  },
  {
    "code": "def _set_comment(self, section, comment, key=None):\n        if '\\n' in comment:\n            comment = '\\n\n        comment = '\n        if key:\n            self._comments[(section, key)] = comment\n        else:\n            self._comments[section] = comment",
    "docstring": "Set a comment for section or key\n\n        :param str section: Section to add comment to\n        :param str comment: Comment to add\n        :param str key: Key to add comment to"
  },
  {
    "code": "def get_canonical_headers(headers):\n    if headers is None:\n        headers = []\n    elif isinstance(headers, dict):\n        headers = list(headers.items())\n    if not headers:\n        return [], []\n    normalized = collections.defaultdict(list)\n    for key, val in headers:\n        key = key.lower().strip()\n        val = MULTIPLE_SPACES.sub(\" \", val.strip())\n        normalized[key].append(val)\n    ordered_headers = sorted((key, \",\".join(val)) for key, val in normalized.items())\n    canonical_headers = [\"{}:{}\".format(*item) for item in ordered_headers]\n    return canonical_headers, ordered_headers",
    "docstring": "Canonicalize headers for signing.\n\n    See:\n    https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers\n\n    :type headers: Union[dict|List(Tuple(str,str))]\n    :param headers:\n        (Optional) Additional HTTP headers to be included as part of the\n        signed URLs.  See:\n        https://cloud.google.com/storage/docs/xml-api/reference-headers\n        Requests using the signed URL *must* pass the specified header\n        (name and value) with each request for the URL.\n\n    :rtype: str\n    :returns: List of headers, normalized / sortted per the URL refernced above."
  },
  {
    "code": "def write_bytes(out_data, encoding=\"ascii\"):\n    if sys.version_info[0] >= 3:\n        if isinstance(out_data, type(\"\")):\n            if encoding == \"utf-8\":\n                return out_data.encode(\"utf-8\")\n            else:\n                return out_data.encode(\"ascii\", \"ignore\")\n        elif isinstance(out_data, type(b\"\")):\n            return out_data\n    else:\n        if isinstance(out_data, type(\"\")):\n            if encoding == \"utf-8\":\n                return out_data.encode(\"utf-8\")\n            else:\n                return out_data.encode(\"ascii\", \"ignore\")\n        elif isinstance(out_data, type(str(\"\"))):\n            return out_data\n    msg = \"Invalid value for out_data neither unicode nor byte string: {}\".format(\n        out_data\n    )\n    raise ValueError(msg)",
    "docstring": "Write Python2 and Python3 compatible byte stream."
  },
  {
    "code": "def materialize(datasets):\n    from .. import GMQLDataset\n    if isinstance(datasets, dict):\n        result = dict()\n        for output_path in datasets.keys():\n            dataset = datasets[output_path]\n            if not isinstance(dataset, GMQLDataset.GMQLDataset):\n                raise TypeError(\"The values of the dictionary must be GMQLDataset.\"\n                                \" {} was given\".format(type(dataset)))\n            gframe = dataset.materialize(output_path)\n            result[output_path] = gframe\n    elif isinstance(datasets, list):\n        result = []\n        for dataset in datasets:\n            if not isinstance(dataset, GMQLDataset.GMQLDataset):\n                raise TypeError(\"The values of the list must be GMQLDataset.\"\n                                \" {} was given\".format(type(dataset)))\n            gframe = dataset.materialize()\n            result.append(gframe)\n    else:\n        raise TypeError(\"The input must be a dictionary of a list. \"\n                        \"{} was given\".format(type(datasets)))\n    return result",
    "docstring": "Multiple materializations. Enables the user to specify a set of GMQLDataset to be materialized.\n    The engine will perform all the materializations at the same time, if an output path is provided,\n    while will perform each operation separately if the output_path is not specified.\n\n    :param datasets: it can be a list of GMQLDataset or a dictionary {'output_path' : GMQLDataset}\n    :return: a list of GDataframe or a dictionary {'output_path' : GDataframe}"
  },
  {
    "code": "def _has_method(arg, method):\n    return hasattr(arg, method) and callable(getattr(arg, method))",
    "docstring": "Returns true if the given object has a method with the given name.\n\n    :param arg: the object\n\n    :param method: the method name\n    :type method: string\n\n    :rtype: bool"
  },
  {
    "code": "def covariance(self, param_1, param_2):\n        param_1_number = self.model.params.index(param_1)\n        param_2_number = self.model.params.index(param_2)\n        return self.covariance_matrix[param_1_number, param_2_number]",
    "docstring": "Return the covariance between param_1 and param_2.\n\n        :param param_1: ``Parameter`` Instance.\n        :param param_2: ``Parameter`` Instance.\n        :return: Covariance of the two params."
  },
  {
    "code": "def non_existing_path(path_, dpath=None, offset=0, suffix=None,\n                            force_fmt=False):\n    r\n    import utool as ut\n    from os.path import basename, dirname\n    if dpath is None:\n        dpath = dirname(path_)\n    base_fmtstr = basename(path_)\n    if suffix is not None:\n        base_fmtstr = ut.augpath(base_fmtstr, suffix)\n    if '%' not in base_fmtstr:\n        if not force_fmt:\n            first_choice = join(dpath, base_fmtstr)\n            if not exists(first_choice):\n                return first_choice\n        base_fmtstr = ut.augpath(base_fmtstr, '%d')\n    dname_list = ut.glob(dpath, pattern='*', recursive=False, with_files=True,\n                         with_dirs=True)\n    conflict_set = set(basename(dname) for dname in dname_list)\n    newname = ut.get_nonconflicting_string(base_fmtstr, conflict_set,\n                                           offset=offset)\n    newpath = join(dpath, newname)\n    return newpath",
    "docstring": "r\"\"\"\n    Searches for and finds a path garuenteed to not exist.\n\n    Args:\n        path_ (str):  path string. If may include a \"%\" formatstr.\n        dpath (str):  directory path(default = None)\n        offset (int): (default = 0)\n        suffix (None): (default = None)\n\n    Returns:\n        str: path_ - path string\n\n    CommandLine:\n        python -m utool.util_path non_existing_path\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_path import *  # NOQA\n        >>> import utool as ut\n        >>> base = ut.ensure_app_resource_dir('utool', 'tmp')\n        >>> ut.touch(base + '/tmp.txt')\n        >>> ut.touch(base + '/tmp0.txt')\n        >>> ut.delete(base + '/tmp1.txt')\n        >>> path_ = base + '/tmp.txt'\n        >>> newpath = ut.non_existing_path(path_)\n        >>> assert basename(newpath) == 'tmp1.txt'\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_path import *  # NOQA\n        >>> import utool as ut\n        >>> base = ut.ensure_app_resource_dir('utool', 'tmp')\n        >>> ut.ensurepath(base + '/dir_old')\n        >>> ut.ensurepath(base + '/dir_old0')\n        >>> ut.ensurepath(base + '/dir_old1')\n        >>> ut.delete(base + '/dir_old2')\n        >>> path_ = base + '/dir'\n        >>> suffix = '_old'\n        >>> newpath = ut.non_existing_path(path_, suffix=suffix)\n        >>> ut.assert_eq(basename(newpath), 'dir_old2')"
  },
  {
    "code": "def libvlc_media_list_player_event_manager(p_mlp):\n    f = _Cfunctions.get('libvlc_media_list_player_event_manager', None) or \\\n        _Cfunction('libvlc_media_list_player_event_manager', ((1,),), class_result(EventManager),\n                    ctypes.c_void_p, MediaListPlayer)\n    return f(p_mlp)",
    "docstring": "Return the event manager of this media_list_player.\n    @param p_mlp: media list player instance.\n    @return: the event manager."
  },
  {
    "code": "def _expand_place_ids(self, terms):\n        place_vids = []\n        first_type = None\n        for result in self.backend.identifier_index.search(terms):\n            if not first_type:\n                first_type = result.type\n            if result.type != first_type:\n                continue\n            place_vids.append(result.vid)\n        if place_vids:\n            all_set = set(itertools.chain.from_iterable(iallval(GVid.parse(x)) for x in place_vids))\n            place_vids += list(str(x) for x in all_set)\n            return place_vids\n        else:\n            return terms",
    "docstring": "Lookups all of the place identifiers to get gvids\n\n        Args:\n            terms (str or unicode): terms to lookup\n\n        Returns:\n            str or list: given terms if no identifiers found, otherwise list of identifiers."
  },
  {
    "code": "def extract_arguments(args, defaults):\n    out_dict = convert_option_dict_to_dict(defaults)\n    for key in defaults.keys():\n        mapped_val = args.get(key, None)\n        if mapped_val is None:\n            pass\n        else:\n            out_dict[key] = mapped_val\n    return out_dict",
    "docstring": "Extract a set of arguments from a large dictionary\n\n    Parameters\n    ----------\n\n    args : dict\n        Dictionary with the arguments values to use\n\n    defaults : dict\n        Dictionary with all the argument to extract, and default values for each\n\n    Returns\n    -------\n\n    out_dict : dict\n        A dictionary with only the extracted arguments"
  },
  {
    "code": "def restore_image_options(cli, image, options):\n    dockerfile = io.StringIO()\n    dockerfile.write(u'FROM {image}\\nCMD {cmd}'.format(\n        image=image, cmd=json.dumps(options['cmd'])))\n    if options['entrypoint']:\n        dockerfile.write(\n            '\\nENTRYPOINT {}'.format(json.dumps(options['entrypoint'])))\n    cli.build(tag=image, fileobj=dockerfile)",
    "docstring": "Restores CMD and ENTRYPOINT values of the image\n\n    This is needed because we force the overwrite of ENTRYPOINT and CMD in the\n    `run_code_in_container` function, to be able to run the code in the\n    container, through /bin/bash."
  },
  {
    "code": "def fetch_defense_data(self):\n    if self.defenses_data_initialized:\n      return\n    logging.info('Fetching defense data from datastore')\n    self.submissions.init_from_datastore()\n    self.dataset_batches.init_from_datastore()\n    self.adv_batches.init_from_datastore()\n    self.read_dataset_metadata()\n    self.defenses_data_initialized = True",
    "docstring": "Lazy initialization of data necessary to execute defenses."
  },
  {
    "code": "def _pad(self, text):\n        top_bottom = (\"\\n\" * self._padding) + \" \"\n        right_left = \" \" * self._padding * self.PAD_WIDTH\n        return top_bottom + right_left + text + right_left + top_bottom",
    "docstring": "Pad the text."
  },
  {
    "code": "def rule_match(component, cmd):\n    if component == cmd:\n        return True\n    expanded = rule_expand(component, cmd)\n    if cmd in expanded:\n        return True\n    return False",
    "docstring": "see if one rule component matches"
  },
  {
    "code": "def generic_path_not_found(*args):\n        exception_tuple = LambdaErrorResponses.PathNotFoundException\n        return BaseLocalService.service_response(\n            LambdaErrorResponses._construct_error_response_body(\n                LambdaErrorResponses.LOCAL_SERVICE_ERROR, \"PathNotFoundException\"),\n            LambdaErrorResponses._construct_headers(exception_tuple[0]),\n            exception_tuple[1]\n        )",
    "docstring": "Creates a Lambda Service Generic PathNotFound Response\n\n        Parameters\n        ----------\n        args list\n            List of arguments Flask passes to the method\n\n        Returns\n        -------\n        Flask.Response\n            A response object representing the GenericPathNotFound Error"
  },
  {
    "code": "def build(self):\n        if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None):\n            return self.dutinformation.get(0).build.name\n        return None",
    "docstring": "get build name.\n\n        :return: build name. None if not found"
  },
  {
    "code": "def epoch_cb(self):\n        metrics = {}\n        metrics['elapsed'] = self.elapsed()\n        now = datetime.datetime.now()\n        metrics['epoch_time'] = now - self.last_epoch_time\n        self.append_metrics(metrics, 'epoch')\n        self.last_epoch_time = now",
    "docstring": "Callback function after each epoch. Now it records each epoch time\n        and append it to epoch dataframe."
  },
  {
    "code": "def get_js(self):\n        js_file = os.path.join(self.theme_dir, 'js', 'slides.js')\n        if not os.path.exists(js_file):\n            js_file = os.path.join(THEMES_DIR, 'default', 'js', 'slides.js')\n            if not os.path.exists(js_file):\n                raise IOError(u\"Cannot find slides.js in default theme\")\n        with codecs.open(js_file, encoding=self.encoding) as js_file_obj:\n            return {\n                'path_url': utils.get_path_url(js_file, self.relative),\n                'contents': js_file_obj.read(),\n            }",
    "docstring": "Fetches and returns javascript file path or contents, depending if\n            we want a standalone presentation or not."
  },
  {
    "code": "def _get_index_class_name(self, index_cls):\n        cls_name = index_cls.__name__\n        aliases = self.Meta.index_aliases\n        return aliases.get(cls_name, cls_name.split('.')[-1])",
    "docstring": "Converts in index model class to a name suitable for use as a field name prefix. A user\n        may optionally specify custom aliases via an 'index_aliases' attribute on the Meta class"
  },
  {
    "code": "def _urlnorm(cls, uri):\n        (scheme, authority, path, query, fragment) = parse_uri(uri)\n        if not scheme or not authority:\n            raise Exception(\"Only absolute URIs are allowed. uri = %s\" % uri)\n        scheme = scheme.lower()\n        authority = authority.lower()\n        if not path:\n            path = \"/\"\n        request_uri = query and \"?\".join([path, query]) or path\n        defrag_uri = scheme + \"://\" + authority + request_uri\n        return defrag_uri",
    "docstring": "Normalize the URL to create a safe key for the cache"
  },
  {
    "code": "def get_options(self):\n        query = 'SET'\n        return dict(row[:2] for row in self.con.fetchall(query))",
    "docstring": "Return current query options for the Impala session"
  },
  {
    "code": "def cyclic(self):\n        \"Returns True if the options cycle, otherwise False\"\n        return any(isinstance(val, Cycle) for val in self.kwargs.values())",
    "docstring": "Returns True if the options cycle, otherwise False"
  },
  {
    "code": "def set(self, name, msg) :\n        \"fills in the error name and message.\"\n        dbus.dbus_set_error(self._dbobj, name.encode(), b\"%s\", msg.encode())",
    "docstring": "fills in the error name and message."
  },
  {
    "code": "def logo_element():\n    path = os.path.join(resources_path(), 'img', 'logos', 'inasafe-logo.png')\n    url = urllib.parse.urljoin('file:', urllib.request.pathname2url(path))\n    return url",
    "docstring": "Create a sanitised local url to the logo for insertion into html.\n\n    :returns: A sanitised local url to the logo prefixed with file://.\n    :rtype: str\n\n    ..note:: We are not using QUrl here because on Windows 10 it returns\n        an empty path if using QUrl.toLocalPath"
  },
  {
    "code": "def download_dataset(self, dataset_name, local_path, how=\"stream\"):\n        if not os.path.isdir(local_path):\n            os.makedirs(local_path)\n        else:\n            raise ValueError(\"Path {} already exists!\".format(local_path))\n        local_path = os.path.join(local_path, FILES_FOLDER)\n        os.makedirs(local_path)\n        if how == 'zip':\n            return self.download_as_zip(dataset_name, local_path)\n        elif how == 'stream':\n            return self.download_as_stream(dataset_name, local_path)\n        else:\n            raise ValueError(\"how must be {'zip', 'stream'}\")",
    "docstring": "It downloads from the repository the specified dataset and puts it\n        in the specified local folder\n\n        :param dataset_name: the name the dataset has in the repository\n        :param local_path: where you want to save the dataset\n        :param how: 'zip' downloads the whole dataset as a zip file and decompress it; 'stream'\n               downloads the dataset sample by sample\n        :return: None"
  },
  {
    "code": "async def volume(dev: Device, volume, output):\n    vol = None\n    vol_controls = await dev.get_volume_information()\n    if output is not None:\n        click.echo(\"Using output: %s\" % output)\n        output_uri = (await dev.get_zone(output)).uri\n        for v in vol_controls:\n            if v.output == output_uri:\n                vol = v\n                break\n    else:\n        vol = vol_controls[0]\n    if vol is None:\n        err(\"Unable to find volume controller: %s\" % output)\n        return\n    if volume and volume == \"mute\":\n        click.echo(\"Muting\")\n        await vol.set_mute(True)\n    elif volume and volume == \"unmute\":\n        click.echo(\"Unmuting\")\n        await vol.set_mute(False)\n    elif volume:\n        click.echo(\"Setting volume to %s\" % volume)\n        await vol.set_volume(volume)\n    if output is not None:\n        click.echo(vol)\n    else:\n        [click.echo(x) for x in vol_controls]",
    "docstring": "Get and set the volume settings.\n\n    Passing 'mute' as new volume will mute the volume,\n    'unmute' removes it."
  },
  {
    "code": "def query_band(self, value):\n        self._query_band = value\n        if value is None:\n            try:\n                del self._connectionXML.attrib['query-band-spec']\n            except KeyError:\n                pass\n        else:\n            self._connectionXML.set('query-band-spec', value)",
    "docstring": "Set the connection's query_band property.\n\n        Args:\n            value:  New query_band value. String.\n\n        Returns:\n            Nothing."
  },
  {
    "code": "def signup(remote_app):\n    if remote_app not in current_oauthclient.signup_handlers:\n        return abort(404)\n    res = current_oauthclient.signup_handlers[remote_app]['view']()\n    return abort(404) if res is None else res",
    "docstring": "Extra signup step."
  },
  {
    "code": "def CreateFromDOM(node, default_namespace=None):\n    if default_namespace is None:\n        default_namespace = Namespace.fallbackNamespace()\n    return pyxb.binding.basis.element.AnyCreateFromDOM(node, default_namespace)",
    "docstring": "Create a Python instance from the given DOM node. The node tag must correspond to\n    an element declaration in this module.\n\n    @deprecated: Forcing use of DOM interface is unnecessary; use L{CreateFromDocument}."
  },
  {
    "code": "def expect_column_values_to_be_in_set(self,\n                                          column,\n                                          value_set,\n                                          mostly=None,\n                                          parse_strings_as_datetimes=None,\n                                          result_format=None, include_config=False, catch_exceptions=None, meta=None\n                                          ):\n        raise NotImplementedError",
    "docstring": "Expect each column value to be in a given set.\n\n        For example:\n        ::\n\n            # my_df.my_col = [1,2,2,3,3,3]\n            >>> my_df.expect_column_values_to_be_in_set(\n                \"my_col\",\n                [2,3]\n            )\n            {\n              \"success\": false\n              \"result\": {\n                \"unexpected_count\": 1\n                \"unexpected_percent\": 0.16666666666666666,\n                \"unexpected_percent_nonmissing\": 0.16666666666666666,\n                \"partial_unexpected_list\": [\n                  1\n                ],\n              },\n            }\n\n        expect_column_values_to_be_in_set is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`.\n\n\n        Args:\n            column (str): \\\n                The column name.\n            value_set (set-like): \\\n                A set of objects used for comparison.\n\n        Keyword Args:\n            mostly (None or a float between 0 and 1): \\\n                Return `\"success\": True` if at least mostly percent of values match the expectation. \\\n                For more detail, see :ref:`mostly`.\n            parse_strings_as_datetimes (boolean or None) : If True values provided in value_set will be parsed as \\\n                datetimes before making comparisons.\n\n        Other Parameters:\n            result_format (str or None): \\\n                Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.\n                For more detail, see :ref:`result_format <result_format>`.\n            include_config (boolean): \\\n                If True, then include the expectation config as part of the result object. \\\n                For more detail, see :ref:`include_config`.\n            catch_exceptions (boolean or None): \\\n                If True, then catch exceptions and include them as part of the result object. \\\n                For more detail, see :ref:`catch_exceptions`.\n            meta (dict or None): \\\n                A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \\\n                For more detail, see :ref:`meta`.\n\n        Returns:\n            A JSON-serializable expectation result object.\n\n            Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and\n            :ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.\n\n        See Also:\n            expect_column_values_to_not_be_in_set"
  },
  {
    "code": "def add_line(self, line='', *, empty=False):\n        max_page_size = self.max_size - self._prefix_len - 2\n        if len(line) > max_page_size:\n            raise RuntimeError('Line exceeds maximum page size %s' % (max_page_size))\n        if self._count + len(line) + 1 > self.max_size:\n            self.close_page()\n        self._count += len(line) + 1\n        self._current_page.append(line)\n        if empty:\n            self._current_page.append('')\n            self._count += 1",
    "docstring": "Adds a line to the current page.\n\n        If the line exceeds the :attr:`max_size` then an exception\n        is raised.\n\n        Parameters\n        -----------\n        line: :class:`str`\n            The line to add.\n        empty: :class:`bool`\n            Indicates if another empty line should be added.\n\n        Raises\n        ------\n        RuntimeError\n            The line was too big for the current :attr:`max_size`."
  },
  {
    "code": "def render(data, saltenv='base', sls='', argline='', **kwargs):\n    translate_newlines = kwargs.get('translate_newlines', False)\n    return _decrypt_object(data, translate_newlines=translate_newlines)",
    "docstring": "Decrypt the data to be rendered that was encrypted using AWS KMS envelope encryption."
  },
  {
    "code": "def toggle_rules(self, *args):\n        if self.app.manager.current != 'rules' and not isinstance(self.app.selected_proxy, CharStatProxy):\n            self.app.rules.entity = self.app.selected_proxy\n            self.app.rules.rulebook = self.app.selected_proxy.rulebook\n        if isinstance(self.app.selected_proxy, CharStatProxy):\n            self.app.charrules.character = self.app.selected_proxy\n            self.app.charrules.toggle()\n        else:\n            self.app.rules.toggle()",
    "docstring": "Display or hide the view for constructing rules out of cards."
  },
  {
    "code": "def _summary_matching_gos(prt, pattern, matching_gos, all_gos):\n        msg = 'Found {N} GO(s) out of {M} matching pattern(\"{P}\")\\n'\n        num_gos = len(matching_gos)\n        num_all = len(all_gos)\n        prt.write(msg.format(N=num_gos, M=num_all, P=pattern))",
    "docstring": "Print summary for get_matching_gos."
  },
  {
    "code": "def set_scan_parameters(self, scan_type=ScanType.ACTIVE, interval_ms=10, window_ms=10,\n                            address_type=BluetoothAddressType.RANDOM, filter_type=ScanFilter.ALL):\n        interval_fractions = interval_ms / MS_FRACTION_DIVIDER\n        if interval_fractions < 0x0004 or interval_fractions > 0x4000:\n            raise ValueError(\n                \"Invalid interval given {}, must be in range of 2.5ms to 10240ms!\".format(\n                    interval_fractions))\n        window_fractions = window_ms / MS_FRACTION_DIVIDER\n        if window_fractions < 0x0004 or window_fractions > 0x4000:\n            raise ValueError(\n                \"Invalid window given {}, must be in range of 2.5ms to 10240ms!\".format(\n                    window_fractions))\n        interval_fractions, window_fractions = int(interval_fractions), int(window_fractions)\n        scan_parameter_pkg = struct.pack(\n            \">BHHBB\",\n            scan_type,\n            interval_fractions,\n            window_fractions,\n            address_type,\n            filter_type)\n        self.bluez.hci_send_cmd(self.socket, OGF_LE_CTL, OCF_LE_SET_SCAN_PARAMETERS,\n                                scan_parameter_pkg)",
    "docstring": "sets the le scan parameters\n\n        Args:\n            scan_type: ScanType.(PASSIVE|ACTIVE)\n            interval: ms (as float) between scans (valid range 2.5ms - 10240ms)\n                ..note:: when interval and window are equal, the scan\n                    runs continuos\n            window: ms (as float) scan duration (valid range 2.5ms - 10240ms)\n            address_type: Bluetooth address type BluetoothAddressType.(PUBLIC|RANDOM)\n                * PUBLIC = use device MAC address\n                * RANDOM = generate a random MAC address and use that\n            filter: ScanFilter.(ALL|WHITELIST_ONLY) only ALL is supported, which will\n                return all fetched bluetooth packets (WHITELIST_ONLY is not supported,\n                because OCF_LE_ADD_DEVICE_TO_WHITE_LIST command is not implemented)\n\n        Raises:\n            ValueError: A value had an unexpected format or was not in range"
  },
  {
    "code": "def _extend_data(self, datapoint, new_data):\n        if new_data:\n            try:\n                self.data[datapoint].extend(new_data)\n            except KeyError:\n                self.data[datapoint] = new_data",
    "docstring": "extend or assign new data to datapoint"
  },
  {
    "code": "def apply_conditions(self, value):\n        retval = value\n        if self._cyclic:\n            retval = apply_cyclic(value, self)\n        retval = self._reflect(retval)\n        if isinstance(retval, numpy.ndarray) and retval.size == 1:\n            try:\n                retval = retval[0]\n            except IndexError:\n                retval = float(retval)\n        return retval",
    "docstring": "Applies any boundary conditions to the given value.\n\n        The value is manipulated according based on the following conditions:\n\n         * If `self.cyclic` is True then `value` is wrapped around to the\n           minimum (maximum) bound if `value` is `>= self.max` (`< self.min`)\n           bound. For example, if the minimum and maximum bounds are `0, 2*pi`\n           and `value = 5*pi`, then the returned value will be `pi`.\n         * If `self.min` is a reflected boundary then `value` will be\n           reflected to the right if it is `< self.min`. For example, if\n           `self.min = 10` and `value = 3`, then the returned value will be\n           17.\n         * If `self.max` is a reflected boundary then `value` will be\n           reflected to the left if it is `> self.max`. For example, if\n           `self.max = 20` and `value = 27`, then the returned value will be\n           13.\n         * If `self.min` and `self.max` are both reflected boundaries, then\n           `value` will be reflected between the two boundaries until it\n           falls within the bounds. The first reflection occurs off of the\n           maximum boundary. For example, if `self.min = 10`, `self.max =\n           20`, and `value = 42`, the returned value will be 18 ( the first\n           reflection yields -2, the second 22, and the last 18).\n         * If neither bounds are reflected and cyclic is False, then the\n           value is just returned as-is.\n\n        Parameters\n        ----------\n        value : float\n            The value to apply the conditions to.\n\n        Returns\n        -------\n        float\n            The value after the conditions are applied; see above for details."
  },
  {
    "code": "def get_or_create(self, db_name):\n        if not db_name in self:\n            res = self.resource.put(db_name)\n            if not res[0] == 201:\n                raise RuntimeError(\n                    'Failed to create database \"{}\"'.format(db_name)\n                )\n        return self[db_name]",
    "docstring": "Creates the database named `db_name` if it doesn't already exist and\n        return it"
  },
  {
    "code": "def clear(self):\n        if hasattr(self.stdout, 'isatty') and self.stdout.isatty() or self.term_type == 'mintty':\n            cmd, shell = {\n                'posix': ('clear', False),\n                'nt': ('cls', True),\n                'cygwin': (['echo', '-en', r'\\ec'], False),\n                'mintty': (r'echo -en \"\\ec', False),\n            }[self.term_type]\n            subprocess.call(cmd, shell=shell, stdin=self.stdin, stdout=self.stdout, stderr=self.stderr)",
    "docstring": "Clear the terminal screen."
  },
  {
    "code": "def getlist(self, event):\n        try:\n            componentlist = model_factory(Schema).find({})\n            data = []\n            for comp in componentlist:\n                try:\n                    data.append({\n                        'name': comp.name,\n                        'uuid': comp.uuid,\n                        'class': comp.componentclass,\n                        'active': comp.active\n                    })\n                except AttributeError:\n                    self.log('Bad component without component class encountered:', lvl=warn)\n                    self.log(comp.serializablefields(), pretty=True, lvl=warn)\n            data = sorted(data, key=lambda x: x['name'])\n            response = {\n                'component': 'hfos.ui.configurator',\n                'action': 'getlist',\n                'data': data\n            }\n            self.fireEvent(send(event.client.uuid, response))\n            return\n        except Exception as e:\n            self.log(\"List error: \", e, type(e), lvl=error, exc=True)",
    "docstring": "Processes configuration list requests\n\n        :param event:"
  },
  {
    "code": "def prt_goids(self, prt):\n        fmt = self.gosubdag.prt_attr['fmta']\n        nts = sorted(self.gosubdag.go2nt.values(), key=lambda nt: [nt.NS, nt.depth, nt.alt])\n        _get_color = self.pydotnodego.go2color.get\n        for ntgo in nts:\n            gostr = fmt.format(**ntgo._asdict())\n            col = _get_color(ntgo.GO, \"\")\n            prt.write(\"{COLOR:7} {GO}\\n\".format(COLOR=col, GO=gostr))",
    "docstring": "Print all GO IDs in the plot, plus their color."
  },
  {
    "code": "def _get_preferred_cipher_suite(\n            cls,\n            server_connectivity_info: ServerConnectivityInfo,\n            ssl_version: OpenSslVersionEnum,\n            accepted_cipher_list: List['AcceptedCipherSuite']\n    ) -> Optional['AcceptedCipherSuite']:\n        if len(accepted_cipher_list) < 2:\n            return None\n        accepted_cipher_names = [cipher.openssl_name for cipher in accepted_cipher_list]\n        should_use_legacy_openssl = None\n        if ssl_version == OpenSslVersionEnum.TLSV1_2:\n            should_use_legacy_openssl = True\n            for cipher_name in accepted_cipher_names:\n                modern_supported_cipher_count = 0\n                if not WorkaroundForTls12ForCipherSuites.requires_legacy_openssl(cipher_name):\n                    modern_supported_cipher_count += 1\n                if modern_supported_cipher_count > 1:\n                    should_use_legacy_openssl = False\n                    break\n        first_cipher_str = ', '.join(accepted_cipher_names)\n        second_cipher_str = ', '.join([accepted_cipher_names[1], accepted_cipher_names[0]] + accepted_cipher_names[2:])\n        try:\n            first_cipher = cls._get_selected_cipher_suite(\n                server_connectivity_info, ssl_version, first_cipher_str, should_use_legacy_openssl\n            )\n            second_cipher = cls._get_selected_cipher_suite(\n                server_connectivity_info, ssl_version, second_cipher_str, should_use_legacy_openssl\n            )\n        except (SslHandshakeRejected, ConnectionError):\n            return None\n        if first_cipher.name == second_cipher.name:\n            return first_cipher\n        else:\n            return None",
    "docstring": "Try to detect the server's preferred cipher suite among all cipher suites supported by SSLyze."
  },
  {
    "code": "def add_ihex(self, records, overwrite=False):\n        extended_segment_address = 0\n        extended_linear_address = 0\n        for record in StringIO(records):\n            type_, address, size, data = unpack_ihex(record.strip())\n            if type_ == IHEX_DATA:\n                address = (address\n                           + extended_segment_address\n                           + extended_linear_address)\n                address *= self.word_size_bytes\n                self._segments.add(_Segment(address,\n                                            address + size,\n                                            bytearray(data),\n                                            self.word_size_bytes),\n                                   overwrite)\n            elif type_ == IHEX_END_OF_FILE:\n                pass\n            elif type_ == IHEX_EXTENDED_SEGMENT_ADDRESS:\n                extended_segment_address = int(binascii.hexlify(data), 16)\n                extended_segment_address *= 16\n            elif type_ == IHEX_EXTENDED_LINEAR_ADDRESS:\n                extended_linear_address = int(binascii.hexlify(data), 16)\n                extended_linear_address <<= 16\n            elif type_ in [IHEX_START_SEGMENT_ADDRESS, IHEX_START_LINEAR_ADDRESS]:\n                self.execution_start_address = int(binascii.hexlify(data), 16)\n            else:\n                raise Error(\"expected type 1..5 in record {}, but got {}\".format(\n                    record,\n                    type_))",
    "docstring": "Add given Intel HEX records string. Set `overwrite` to ``True`` to\n        allow already added data to be overwritten."
  },
  {
    "code": "def _url_params(size:str='>400*300', format:str='jpg') -> str:\n    \"Build Google Images Search Url params and return them as a string.\"\n    _fmts = {'jpg':'ift:jpg','gif':'ift:gif','png':'ift:png','bmp':'ift:bmp', 'svg':'ift:svg','webp':'webp','ico':'ift:ico'}\n    if size not in _img_sizes: \n        raise RuntimeError(f\n) \n    if format not in _fmts: \n        raise RuntimeError(f\"Unexpected image file format: {format}. Use jpg, gif, png, bmp, svg, webp, or ico.\")\n    return \"&tbs=\" + _img_sizes[size] + \",\" + _fmts[format]",
    "docstring": "Build Google Images Search Url params and return them as a string."
  },
  {
    "code": "def signature(self, name, file_name, file_type, file_content, owner=None, **kwargs):\n        return Signature(self.tcex, name, file_name, file_type, file_content, owner=owner, **kwargs)",
    "docstring": "Create the Signature TI object.\n\n        Args:\n            owner:\n            file_content:\n            file_name:\n            file_type:\n            name:\n            **kwargs:\n\n        Return:"
  },
  {
    "code": "def get_value(self, class_name, attr, default_value=None,\n                  state='normal', base_name='View'):\n        styles = self.get_dict_for_class(class_name, state, base_name)\n        try:\n            return styles[attr]\n        except KeyError:\n            return default_value",
    "docstring": "Get a single style attribute value for the given class."
  },
  {
    "code": "def update(self, dt=None):\n        dt = dt if (dt is not None and dt > 0) else self.dt\n        tspan = [0, dt]\n        res = self.sim.run(tspan=tspan, initials=self.state)\n        self.state  = res.species[-1]\n        self.time += dt\n        if self.time > self.stop_time:\n            self.DONE = True\n        print((self.time, self.state))\n        self.time_course.append((self.time.copy(), self.state.copy()))",
    "docstring": "Simulate the model for a given time interval.\n\n        Parameters\n        ----------\n        dt : Optional[float]\n            The time step to simulate, if None, the default built-in time step\n            is used."
  },
  {
    "code": "def task_add_user(self, *args, **kwargs):\n        if not self.cur_task:\n            return\n        dialog = UserAdderDialog(task=self.cur_task)\n        dialog.exec_()\n        users = dialog.users\n        for user in users:\n            userdata = djitemdata.UserItemData(user)\n            treemodel.TreeItem(userdata, self.task_user_model.root)",
    "docstring": "Add users to the current task\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def run_sphinx():\n    old_dir = here_directory()\n    os.chdir(str(doc_directory()))\n    doc_status = subprocess.check_call(['make', 'html'], shell=True)\n    os.chdir(str(old_dir))\n    if doc_status is not 0:\n        exit(Fore.RED + 'Something broke generating your documentation...')",
    "docstring": "Runs Sphinx via it's `make html` command"
  },
  {
    "code": "def add_text(self, tag, text, global_step=None):\n        self._file_writer.add_summary(text_summary(tag, text), global_step)\n        if tag not in self._text_tags:\n            self._text_tags.append(tag)\n            extension_dir = self.get_logdir() + '/plugins/tensorboard_text/'\n            if not os.path.exists(extension_dir):\n                os.makedirs(extension_dir)\n            with open(extension_dir + 'tensors.json', 'w') as fp:\n                json.dump(self._text_tags, fp)",
    "docstring": "Add text data to the event file.\n\n        Parameters\n        ----------\n            tag : str\n                Name for the `text`.\n            text : str\n                Text to be saved to the event file.\n            global_step : int\n                Global step value to record."
  },
  {
    "code": "def profile_update(request, template=\"accounts/account_profile_update.html\",\n                   extra_context=None):\n    profile_form = get_profile_form()\n    form = profile_form(request.POST or None, request.FILES or None,\n                        instance=request.user)\n    if request.method == \"POST\" and form.is_valid():\n        user = form.save()\n        info(request, _(\"Profile updated\"))\n        try:\n            return redirect(\"profile\", username=user.username)\n        except NoReverseMatch:\n            return redirect(\"profile_update\")\n    context = {\"form\": form, \"title\": _(\"Update Profile\")}\n    context.update(extra_context or {})\n    return TemplateResponse(request, template, context)",
    "docstring": "Profile update form."
  },
  {
    "code": "def _build_processor(cls, session: AppSession):\n        web_processor = cls._build_web_processor(session)\n        ftp_processor = cls._build_ftp_processor(session)\n        delegate_processor = session.factory.new('Processor')\n        delegate_processor.register('http', web_processor)\n        delegate_processor.register('https', web_processor)\n        delegate_processor.register('ftp', ftp_processor)",
    "docstring": "Create the Processor\n\n        Returns:\n            Processor: An instance of :class:`.processor.BaseProcessor`."
  },
  {
    "code": "def analyze_async(output_dir, dataset, cloud=False, project_id=None):\n  import google.datalab.utils as du\n  with warnings.catch_warnings():\n    warnings.simplefilter(\"ignore\")\n    fn = lambda: _analyze(output_dir, dataset, cloud, project_id)\n    return du.LambdaJob(fn, job_id=None)",
    "docstring": "Analyze data locally or in the cloud with BigQuery.\n\n  Produce analysis used by training. This can take a while, even for small\n  datasets. For small datasets, it may be faster to use local_analysis.\n\n  Args:\n    output_dir: The output directory to use.\n    dataset: only CsvDataSet is supported currently.\n    cloud: If False, runs analysis locally with Pandas. If Ture, runs analysis\n        in the cloud with BigQuery.\n    project_id: Uses BigQuery with this project id. Default is datalab's\n        default project id.\n\n  Returns:\n    A google.datalab.utils.Job object that can be used to query state from or wait."
  },
  {
    "code": "def create_router(self, context, router):\n        if router:\n            router_name = self._arista_router_name(router['id'],\n                                                   router['name'])\n            hashed = hashlib.sha256(router_name.encode('utf-8'))\n            rdm = str(int(hashed.hexdigest(), 16) % 65536)\n            mlag_peer_failed = False\n            for s in self._servers:\n                try:\n                    self.create_router_on_eos(router_name, rdm, s)\n                    mlag_peer_failed = False\n                except Exception:\n                    if self._mlag_configured and not mlag_peer_failed:\n                        mlag_peer_failed = True\n                    else:\n                        msg = (_('Failed to create router %s on EOS') %\n                               router_name)\n                        LOG.exception(msg)\n                        raise arista_exc.AristaServicePluginRpcError(msg=msg)",
    "docstring": "Creates a router on Arista Switch.\n\n        Deals with multiple configurations - such as Router per VRF,\n        a router in default VRF, Virtual Router in MLAG configurations"
  },
  {
    "code": "def ls(ctx, name, list_formatted):\n    session = create_session(ctx.obj['AWS_PROFILE_NAME'])\n    client = session.client('autoscaling')\n    if name == \"*\":\n        groups = client.describe_auto_scaling_groups()\n    else:\n        groups = client.describe_auto_scaling_groups(\n            AutoScalingGroupNames=[\n                name,\n            ]\n        )\n    out = format_output(groups, list_formatted)\n    click.echo('\\n'.join(out))",
    "docstring": "List AutoScaling groups"
  },
  {
    "code": "def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record):\n        rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl)\n        return self.rest_api_connection.post(\"/v1/zones/\" + zone_name + \"/rrsets/A/\" + owner_name, json.dumps(rrset))",
    "docstring": "Creates a new TC Pool.\n\n        Arguments:\n        zone_name -- The zone that contains the RRSet.  The trailing dot is optional.\n        owner_name -- The owner name for the RRSet.\n                      If no trailing dot is supplied, the owner_name is assumed to be relative (foo).\n                      If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.)\n        ttl -- The updated TTL value for the RRSet.\n        pool_info -- dict of information about the pool\n        rdata_info -- dict of information about the records in the pool.\n                      The keys in the dict are the A and CNAME records that make up the pool.\n                      The values are the rdataInfo for each of the records\n        backup_record -- dict of information about the backup (all-fail) records in the pool.\n                        There are two key/value in the dict:\n                            rdata - the A or CNAME for the backup record\n                            failoverDelay - the time to wait to fail over (optional, defaults to 0)"
  },
  {
    "code": "def exception_to_unicode(e, traceback=False):\n    message = '%s: %s' % (e.__class__.__name__, to_unicode(e))\n    if traceback:\n        from docido_sdk.toolbox import get_last_traceback\n        traceback_only = get_last_traceback().split('\\n')[:-2]\n        message = '\\n%s\\n%s' % (to_unicode('\\n'.join(traceback_only)), message)\n    return message",
    "docstring": "Convert an `Exception` to an `unicode` object.\n\n    In addition to `to_unicode`, this representation of the exception\n    also contains the class name and optionally the traceback."
  },
  {
    "code": "def from_settings(settings):\n    connection_type = settings.get('RABBITMQ_CONNECTION_TYPE', RABBITMQ_CONNECTION_TYPE)\n    queue_name = settings.get('RABBITMQ_QUEUE_NAME', RABBITMQ_QUEUE_NAME)\n    connection_parameters = settings.get('RABBITMQ_CONNECTION_PARAMETERS', RABBITMQ_CONNECTION_PARAMETERS)\n    connection = {\n        'blocking': pika.BlockingConnection,\n        'libev': pika.LibevConnection,\n        'select': pika.SelectConnection,\n        'tornado': pika.TornadoConnection,\n        'twisted': pika.TwistedConnection\n    }[connection_type](pika.ConnectionParameters(**connection_parameters))\n    channel = connection.channel()\n    channel.queue_declare(queue=queue_name, durable=True)\n    return channel",
    "docstring": "Factory method that returns an instance of channel\n\n        :param str connection_type: This field can be `blocking`\n            `asyncore`, `libev`, `select`, `tornado`, or `twisted`\n\n        See pika documentation for more details:\n            TODO: put pika url regarding connection type\n\n        Parameters is a dictionary that can\n        include the following values:\n\n            :param str host: Hostname or IP Address to connect to\n            :param int port: TCP port to connect to\n            :param str virtual_host: RabbitMQ virtual host to use\n            :param pika.credentials.Credentials credentials: auth credentials\n            :param int channel_max: Maximum number of channels to allow\n            :param int frame_max: The maximum byte size for an AMQP frame\n            :param int heartbeat_interval: How often to send heartbeats\n            :param bool ssl: Enable SSL\n            :param dict ssl_options: Arguments passed to ssl.wrap_socket as\n            :param int connection_attempts: Maximum number of retry attempts\n            :param int|float retry_delay: Time to wait in seconds, before the next\n            :param int|float socket_timeout: Use for high latency networks\n            :param str locale: Set the locale value\n            :param bool backpressure_detection: Toggle backpressure detection\n\n        :return: Channel object"
  },
  {
    "code": "def state(self, states=None):\n        if states is None or not states:\n            return self\n        nodes = []\n        for node in self.nodes:\n            if any(state.lower() == node.state.lower() for state in states):\n                nodes.append(node)\n        self.nodes = nodes\n        return self",
    "docstring": "Filter by state.\n\n        :param  tags: States to filter.\n        :type   tags: ``list``\n\n        :return: A list of Node objects.\n        :rtype:  ``list`` of :class:`Node`"
  },
  {
    "code": "def equal(list1, list2):\n    return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]",
    "docstring": "takes flags returns indexes of True values"
  },
  {
    "code": "def _newline_tokenize(self, data):\n        parts = data.split('\\n')\n        tokens = []\n        for num, part in enumerate(parts):\n            if part:\n                tokens.append((self.TOKEN_DATA, None, None, part))\n            if num < (len(parts) - 1):\n                tokens.append((self.TOKEN_NEWLINE, None, None, '\\n'))\n        return tokens",
    "docstring": "Given a string that does not contain any tags, this function will\n        return a list of NEWLINE and DATA tokens such that if you concatenate\n        their data, you will have the original string."
  },
  {
    "code": "def set_dwelling_current(self, settings):\n        self._dwelling_current_settings['now'].update(settings)\n        dwelling_axes_to_update = {\n            axis: amps\n            for axis, amps in self._dwelling_current_settings['now'].items()\n            if self._active_axes.get(axis) is False\n            if self.current[axis] != amps\n        }\n        if dwelling_axes_to_update:\n            self._save_current(dwelling_axes_to_update, axes_active=False)",
    "docstring": "Sets the amperage of each motor for when it is dwelling.\n        Values are initialized from the `robot_config.log_current` values,\n        and can then be changed through this method by other parts of the API.\n\n        For example, `Pipette` setting the dwelling-current of it's pipette,\n        depending on what model pipette it is.\n\n        settings\n            Dict with axes as valies (e.g.: 'X', 'Y', 'Z', 'A', 'B', or 'C')\n            and floating point number for current (generally between 0.1 and 2)"
  },
  {
    "code": "def create_delete_model(record):\n    arn = f\"arn:aws:s3:::{cloudwatch.filter_request_parameters('bucketName', record)}\"\n    LOG.debug(f'[-] Deleting Dynamodb Records. Hash Key: {arn}')\n    data = {\n        'arn': arn,\n        'principalId': cloudwatch.get_principal(record),\n        'userIdentity': cloudwatch.get_user_identity(record),\n        'accountId': record['account'],\n        'eventTime': record['detail']['eventTime'],\n        'BucketName': cloudwatch.filter_request_parameters('bucketName', record),\n        'Region': cloudwatch.get_region(record),\n        'Tags': {},\n        'configuration': {},\n        'eventSource': record['detail']['eventSource'],\n        'version': VERSION\n    }\n    return CurrentS3Model(**data)",
    "docstring": "Create an S3 model from a record."
  },
  {
    "code": "def get_total_ram():\n    with open('/proc/meminfo', 'r') as f:\n        for line in f.readlines():\n            if line:\n                key, value, unit = line.split()\n                if key == 'MemTotal:':\n                    assert unit == 'kB', 'Unknown unit'\n                    return int(value) * 1024\n        raise NotImplementedError()",
    "docstring": "The total amount of system RAM in bytes.\n\n    This is what is reported by the OS, and may be overcommitted when\n    there are multiple containers hosted on the same machine."
  },
  {
    "code": "def read_byte_data(self, i2c_addr, register, force=None):\n        self._set_address(i2c_addr, force=force)\n        msg = i2c_smbus_ioctl_data.create(\n            read_write=I2C_SMBUS_READ, command=register, size=I2C_SMBUS_BYTE_DATA\n        )\n        ioctl(self.fd, I2C_SMBUS, msg)\n        return msg.data.contents.byte",
    "docstring": "Read a single byte from a designated register.\n\n        :param i2c_addr: i2c address\n        :type i2c_addr: int\n        :param register: Register to read\n        :type register: int\n        :param force:\n        :type force: Boolean\n        :return: Read byte value\n        :rtype: int"
  },
  {
    "code": "def update_nodes(nodes,**kwargs):\n    user_id = kwargs.get('user_id')\n    updated_nodes = []\n    for n in nodes:\n        updated_node_i = update_node(n, flush=False, user_id=user_id)\n        updated_nodes.append(updated_node_i)\n    db.DBSession.flush()\n    return updated_nodes",
    "docstring": "Update multiple nodes.\n    If new attributes are present, they will be added to the node.\n    The non-presence of attributes does not remove them.\n\n    %TODO:merge this with the 'update_nodes' functionality in the 'update_netework'\n    function, so we're not duplicating functionality. D.R.Y!\n\n    returns: a list of updated nodes"
  },
  {
    "code": "def fit_transform(self, *args, **kwargs):\n        self.fit(*args, **kwargs)\n        return self.transform(*args, **kwargs)",
    "docstring": "Performs fit followed by transform.\n\n        This method simply combines fit and transform.\n\n        Args:\n            args: positional arguments (can be anything)\n            kwargs: keyword arguments (can be anything)\n\n        Returns:\n            dict: output"
  },
  {
    "code": "def _has_fr_route(self):\n        if self._should_use_fr_error_handler():\n            return True\n        if not request.url_rule:\n            return False\n        return self.owns_endpoint(request.url_rule.endpoint)",
    "docstring": "Encapsulating the rules for whether the request was to a Flask endpoint"
  },
  {
    "code": "def dirty_fields(self):\n        dirty_fields = []\n        for field in self.all_fields:\n            if field not in self._original:\n                dirty_fields.append(field)\n            elif self._original[field] != getattr(self, field):\n                dirty_fields.append(field)\n        return dirty_fields",
    "docstring": "Return an array of field names that are dirty\n\n        Dirty means if a model was hydrated first from the\n        store & then had field values changed they are now\n        considered dirty.\n\n        For new models all fields are considered dirty.\n\n        :return: list"
  },
  {
    "code": "def get_known_topics(self, lang):\n        return [topic['title']\n                for topic in self.user_data.language_data[lang]['skills']\n                if topic['learned']]",
    "docstring": "Return the topics learned by a user in a language."
  },
  {
    "code": "def set_duration(self, duration):\n        if self.get_duration_metadata().is_read_only():\n            raise errors.NoAccess()\n        if not self._is_valid_duration(\n                duration,\n                self.get_duration_metadata()):\n            raise errors.InvalidArgument()\n        map = dict()\n        map['days'] = duration.days\n        map['seconds'] = duration.seconds\n        map['microseconds'] = duration.microseconds\n        self._my_map['duration'] = map",
    "docstring": "Sets the assessment duration.\n\n        arg:    duration (osid.calendaring.Duration): assessment\n                duration\n        raise:  InvalidArgument - ``duration`` is invalid\n        raise:  NoAccess - ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def authGenders(self, countsOnly = False, fractionsMode = False, _countsTuple = False):\n        authDict = recordGenders(self)\n        if _countsTuple or countsOnly or fractionsMode:\n            rawList = list(authDict.values())\n            countsList = []\n            for k in ('Male','Female','Unknown'):\n                countsList.append(rawList.count(k))\n            if fractionsMode:\n                tot = sum(countsList)\n                for i in range(3):\n                    countsList.append(countsList.pop(0) / tot)\n            if _countsTuple:\n                return tuple(countsList)\n            else:\n                return {'Male' : countsList[0], 'Female' : countsList[1], 'Unknown' : countsList[2]}\n        else:\n            return authDict",
    "docstring": "Creates a dict mapping `'Male'`, `'Female'` and `'Unknown'` to lists of the names of all the authors.\n\n        # Parameters\n\n        _countsOnly_ : `optional bool`\n\n        > Default `False`, if `True` the counts (lengths of the lists) will be given instead of the lists of names\n\n        _fractionsMode_ : `optional bool`\n\n        > Default `False`, if `True` the fraction counts (lengths of the lists divided by the total  number of authors) will be given instead of the lists of names. This supersedes _countsOnly_\n\n        # Returns\n\n        `dict[str:str or int]`\n\n        > The mapping of genders to author's names or counts"
  },
  {
    "code": "def translate_gitlab_exception(func):\n    @functools.wraps(func)\n    def _wrapper(*args, **kwargs):\n        try:\n            return func(*args, **kwargs)\n        except gitlab.GitlabError as e:\n            status_to_exception = {\n                401: UnauthorizedError,\n                404: NotFoundError,\n            }\n            exc_class = status_to_exception.get(e.response_code, GitClientError)\n            raise exc_class(str(e), status_code=e.response_code)\n    return _wrapper",
    "docstring": "Decorator to catch GitLab-specific exceptions and raise them as GitClientError exceptions."
  },
  {
    "code": "def _get_color_from_config(config, option):\n    if not config.has_option(COLOR_SECTION, option):\n        return None\n    else:\n        return ast.literal_eval(config.get(COLOR_SECTION, option))",
    "docstring": "Helper method to uet an option from the COLOR_SECTION of the config.\n\n    Returns None if the value is not present. If the value is present, it tries\n    to parse the value as a raw string literal, allowing escape sequences in\n    the egrc."
  },
  {
    "code": "def append(self, clause):\n        self.nv = max([abs(l) for l in clause] + [self.nv])\n        self.clauses.append(clause)",
    "docstring": "Add one more clause to CNF formula. This method additionally\n            updates the number of variables, i.e. variable ``self.nv``, used in\n            the formula.\n\n            :param clause: a new clause to add.\n            :type clause: list(int)\n\n            .. code-block:: python\n\n                >>> from pysat.formula import CNF\n                >>> cnf = CNF(from_clauses=[[-1, 2], [3]])\n                >>> cnf.append([-3, 4])\n                >>> print cnf.clauses\n                [[-1, 2], [3], [-3, 4]]"
  },
  {
    "code": "def update_unit(self, unit_id, unit_dict):\n        return self._create_put_request(resource=UNITS, billomat_id=unit_id, send_data=unit_dict)",
    "docstring": "Updates an unit\n\n        :param unit_id: the unit id\n        :param unit_dict: dict\n        :return: dict"
  },
  {
    "code": "def save_vip_request(self, vip_request):\n        uri = 'api/v3/vip-request/'\n        data = dict()\n        data['vips'] = list()\n        data['vips'].append(vip_request)\n        return super(ApiVipRequest, self).post(uri, data)",
    "docstring": "Method to save vip request\n\n        param vip_request: vip_request object"
  },
  {
    "code": "def hardware_info(self, mask=0xFFFFFFFF):\n        buf = (ctypes.c_uint32 * 32)()\n        res = self._dll.JLINKARM_GetHWInfo(mask, ctypes.byref(buf))\n        if res != 0:\n            raise errors.JLinkException(res)\n        return list(buf)",
    "docstring": "Returns a list of 32 integer values corresponding to the bitfields\n        specifying the power consumption of the target.\n\n        The values returned by this function only have significance if the\n        J-Link is powering the target.\n\n        The words, indexed, have the following significance:\n          0. If ``1``, target is powered via J-Link.\n          1. Overcurrent bitfield:\n             0: No overcurrent.\n             1: Overcurrent happened.  2ms @ 3000mA\n             2: Overcurrent happened.  10ms @ 1000mA\n             3: Overcurrent happened.  40ms @ 400mA\n          2. Power consumption of target (mA).\n          3. Peak of target power consumption (mA).\n          4. Peak of target power consumption during J-Link operation (mA).\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          mask (int): bit mask to decide which hardware information words are\n            returned (defaults to all the words).\n\n        Returns:\n          List of bitfields specifying different states based on their index\n          within the list and their value.\n\n        Raises:\n          JLinkException: on hardware error."
  },
  {
    "code": "def unregister(self, id):\n        result = self.rr.table(self.table).get(id).delete().run()\n        if result != {\n                'deleted':1, 'errors':0,'inserted':0,\n                'replaced':0,'skipped':0,'unchanged':0}:\n            self.logger.warn(\n                    'unexpected result attempting to delete id=%s from '\n                    'rethinkdb services table: %s', id, result)",
    "docstring": "Remove the service with id `id` from the service registry."
  },
  {
    "code": "def common_update_sys(self):\n        try:\n            sudo('apt-get update -y --fix-missing')\n        except Exception as e:\n            print(e)\n        print(green('System package is up to date.'))\n        print()",
    "docstring": "update system package"
  },
  {
    "code": "def _stamp_and_update_hook(method,\n                           dependencies,\n                           stampfile,\n                           func,\n                           *args,\n                           **kwargs):\n    result = _stamp(stampfile, func, *args, **kwargs)\n    method.update_stampfile_hook(dependencies)\n    return result",
    "docstring": "Write stamp and call update_stampfile_hook on method."
  },
  {
    "code": "def install(self, opener):\n        _opener = opener if isinstance(opener, Opener) else opener()\n        assert isinstance(_opener, Opener), \"Opener instance required\"\n        assert _opener.protocols, \"must list one or more protocols\"\n        for protocol in _opener.protocols:\n            self._protocols[protocol] = _opener\n        return opener",
    "docstring": "Install an opener.\n\n        Arguments:\n            opener (`Opener`): an `Opener` instance, or a callable that\n                returns an opener instance.\n\n        Note:\n            May be used as a class decorator. For example::\n                registry = Registry()\n                @registry.install\n                class ArchiveOpener(Opener):\n                    protocols = ['zip', 'tar']"
  },
  {
    "code": "def install_from_pypi(context):\n    tmp_dir = venv.create_venv()\n    install_cmd = '%s/bin/pip install %s' % (tmp_dir, context.module_name)\n    package_index = 'pypi'\n    if context.pypi:\n        install_cmd += '-i %s' % context.pypi\n        package_index = context.pypi\n    try:\n        result = shell.dry_run(install_cmd, context.dry_run)\n        if not context.dry_run and not result:\n            log.error(\n                'Failed to install %s from %s', context.module_name, package_index\n            )\n        else:\n            log.info(\n                'Successfully installed %s from %s', context.module_name, package_index\n            )\n    except Exception as e:\n        error_msg = 'Error installing %s from %s' % (context.module_name, package_index)\n        log.exception(error_msg)\n        raise Exception(error_msg, e)",
    "docstring": "Attempts to install your package from pypi."
  },
  {
    "code": "def run_git_shell(cls, cmd, cwd=None):\n        p = Popen(cmd, shell=True, stdout=PIPE, cwd=cwd)\n        output, _ = p.communicate()\n        output = cls.decode_git_output(output)\n        if p.returncode:\n            if sys.version_info > (2, 6):\n                raise CalledProcessError(returncode=p.returncode, cmd=cmd, output=output)\n            else:\n                raise CalledProcessError(returncode=p.returncode, cmd=cmd)\n        return output",
    "docstring": "Runs git shell command, reads output and decodes it into unicode string.\n\n        @param cmd: Command to be executed.\n        @type cmd: str\n\n        @type cwd: str\n        @param cwd: Working directory.\n\n        @rtype: str\n        @return: Output of the command.\n\n        @raise CalledProcessError:  Raises exception if return code of the command is non-zero."
  },
  {
    "code": "def write_sample(binary, payload, path, filename):\n    if not os.path.exists(path):\n        os.makedirs(path)\n    sample = os.path.join(path, filename)\n    if binary:\n        with open(sample, \"wb\") as f:\n            f.write(base64.b64decode(payload))\n    else:\n        with open(sample, \"w\") as f:\n            f.write(payload)",
    "docstring": "This function writes a sample on file system.\n\n    Args:\n        binary (bool): True if it's a binary file\n        payload: payload of sample, in base64 if it's a binary\n        path (string): path of file\n        filename (string): name of file\n        hash_ (string): file hash"
  },
  {
    "code": "def canonical_uri_path(self):\n        result = getattr(self, \"_canonical_uri_path\", None)\n        if result is None:\n            result = self._canonical_uri_path = get_canonical_uri_path(\n                self.uri_path)\n        return result",
    "docstring": "The canonicalized URI path from the request."
  },
  {
    "code": "def u2handlers(self):\n        handlers = []\n        handlers.append(u2.ProxyHandler(self.proxy))\n        return handlers",
    "docstring": "Get a collection of urllib handlers.\n        @return: A list of handlers to be installed in the opener.\n        @rtype: [Handler,...]"
  },
  {
    "code": "def _calc_adu(self):\n        res = super()._calc_adu()\n        self.ensure_one()\n        dafs_to_apply = self.env['ddmrp.adjustment'].search(\n            self._daf_to_apply_domain())\n        if dafs_to_apply:\n            daf = 1\n            values = dafs_to_apply.mapped('value')\n            for val in values:\n                daf *= val\n            prev = self.adu\n            self.adu *= daf\n            _logger.debug(\n                \"DAF=%s applied to %s. ADU: %s -> %s\" %\n                (daf, self.name, prev, self.adu))\n        dafs_to_explode = self.env['ddmrp.adjustment'].search(\n            self._daf_to_apply_domain(False))\n        for daf in dafs_to_explode:\n            prev = self.adu\n            increased_demand = prev * daf.value - prev\n            self.explode_demand_to_components(\n                daf, increased_demand, self.product_uom)\n        return res",
    "docstring": "Apply DAFs if existing for the buffer."
  },
  {
    "code": "def human_time(seconds):\n    units = [\n        ('y', 60 * 60 * 24 * 7 * 52),\n        ('w', 60 * 60 * 24 * 7),\n        ('d', 60 * 60 * 24),\n        ('h', 60 * 60),\n        ('m', 60),\n        ('s', 1),\n    ]\n    seconds = int(seconds)\n    if seconds < 60:\n        return '   {0:2d}s'.format(seconds)\n    for i in range(len(units) - 1):\n        unit1, limit1 = units[i]\n        unit2, limit2 = units[i + 1]\n        if seconds >= limit1:\n            return '{0:2d}{1}{2:2d}{3}'.format(\n                seconds // limit1, unit1,\n                (seconds % limit1) // limit2, unit2)\n    return '  ~inf'",
    "docstring": "Returns a human-friendly time string that is always exactly 6\n    characters long.\n\n    Depending on the number of seconds given, can be one of::\n\n        1w 3d\n        2d 4h\n        1h 5m\n        1m 4s\n          15s\n\n    Will be in color if console coloring is turned on.\n\n    Parameters\n    ----------\n    seconds : int\n        The number of seconds to represent\n\n    Returns\n    -------\n    time : str\n        A human-friendly representation of the given number of seconds\n        that is always exactly 6 characters."
  },
  {
    "code": "def save_id_to_path_mapping(self):\n    if not self.id_to_path_mapping:\n      return\n    with open(self.local_id_to_path_mapping_file, 'w') as f:\n      writer = csv.writer(f)\n      writer.writerow(['id', 'path'])\n      for k, v in sorted(iteritems(self.id_to_path_mapping)):\n        writer.writerow([k, v])\n    cmd = ['gsutil', 'cp', self.local_id_to_path_mapping_file,\n           os.path.join(self.target_dir, 'id_to_path_mapping.csv')]\n    if subprocess.call(cmd) != 0:\n      logging.error('Can\\'t copy id_to_path_mapping.csv to target directory')",
    "docstring": "Saves mapping from submission IDs to original filenames.\n\n    This mapping is saved as CSV file into target directory."
  },
  {
    "code": "def send_raw_email(self, raw_message, source=None, destinations=None):\n        params = {\n            'RawMessage.Data': base64.b64encode(raw_message),\n        }\n        if source:\n            params['Source'] = source\n        if destinations:\n            self._build_list_params(params, destinations,\n                                   'Destinations.member')\n        return self._make_request('SendRawEmail', params)",
    "docstring": "Sends an email message, with header and content specified by the\n        client. The SendRawEmail action is useful for sending multipart MIME\n        emails, with attachments or inline content. The raw text of the message\n        must comply with Internet email standards; otherwise, the message\n        cannot be sent.\n\n        :type source: string\n        :param source: The sender's email address. Amazon's docs say:\n\n          If you specify the Source parameter, then bounce notifications and\n          complaints will be sent to this email address. This takes precedence\n          over any Return-Path header that you might include in the raw text of\n          the message.\n\n        :type raw_message: string\n        :param raw_message: The raw text of the message. The client is\n          responsible for ensuring the following:\n\n          - Message must contain a header and a body, separated by a blank line.\n          - All required header fields must be present.\n          - Each part of a multipart MIME message must be formatted properly.\n          - MIME content types must be among those supported by Amazon SES.\n            Refer to the Amazon SES Developer Guide for more details.\n          - Content must be base64-encoded, if MIME requires it.\n\n        :type destinations: list of strings or string\n        :param destinations: A list of destinations for the message."
  },
  {
    "code": "def resolve_alias(self, path_str):\n        if path_str in self.aliases:\n            return self.aliases[path_str]\n        return path_str",
    "docstring": "Returns the actual command name. Uses the alias mapping."
  },
  {
    "code": "def _bottom(self):\n        _, top, _, height = self._extents\n        return top + height",
    "docstring": "Index of row following last row of range"
  },
  {
    "code": "def decrypt(key, ciphertext, shift_function=shift_case_english):\n    return [shift_function(key, symbol) for symbol in ciphertext]",
    "docstring": "Decrypt Shift enciphered ``ciphertext`` using ``key``.\n\n    Examples:\n        >>> ''.join(decrypt(3, \"KHOOR\"))\n        HELLO\n\n        >> decrypt(15, [0xcf, 0x9e, 0xaf, 0xe0], shift_bytes)\n        [0xde, 0xad, 0xbe, 0xef]\n\n    Args:\n        key (int): The shift to use\n        ciphertext (iterable): The symbols to decrypt\n        shift_function (function (shift, symbol)): Shift function to apply to symbols in the ciphertext\n\n    Returns:\n        Decrypted ciphertext, list of plaintext symbols"
  },
  {
    "code": "def search_indicators_page(self, search_term=None,\n                               enclave_ids=None,\n                               from_time=None,\n                               to_time=None,\n                               indicator_types=None,\n                               tags=None,\n                               excluded_tags=None,\n                               page_size=None,\n                               page_number=None):\n        body = {\n            'searchTerm': search_term\n        }\n        params = {\n            'enclaveIds': enclave_ids,\n            'from': from_time,\n            'to': to_time,\n            'entityTypes': indicator_types,\n            'tags': tags,\n            'excludedTags': excluded_tags,\n            'pageSize': page_size,\n            'pageNumber': page_number\n        }\n        resp = self._client.post(\"indicators/search\", params=params, data=json.dumps(body))\n        return Page.from_dict(resp.json(), content_type=Indicator)",
    "docstring": "Search for indicators containing a search term.\n\n        :param str search_term: The term to search for.  If empty, no search term will be applied.  Otherwise, must\n            be at least 3 characters.\n        :param list(str) enclave_ids: list of enclave ids used to restrict to indicators found in reports in specific\n            enclaves (optional - by default reports from all of the user's enclaves are used)\n        :param int from_time: start of time window in milliseconds since epoch (optional)\n        :param int to_time: end of time window in milliseconds since epoch (optional)\n        :param list(str) indicator_types: a list of indicator types to filter by (optional)\n        :param list(str) tags: Name (or list of names) of tag(s) to filter indicators by.  Only indicators containing\n            ALL of these tags will be returned. (optional)\n        :param list(str) excluded_tags: Indicators containing ANY of these tags will be excluded from the results.\n        :param int page_number: the page number to get.\n        :param int page_size: the size of the page to be returned.\n        :return: a |Page| of |Indicator| objects."
  },
  {
    "code": "def is_zero(self):\n        for o in self.matrix.ravel():\n            try:\n                if not o.is_zero:\n                    return False\n            except AttributeError:\n                if not o == 0:\n                    return False\n        return True",
    "docstring": "Are all elements of the matrix zero?"
  },
  {
    "code": "def load_template(self, path):\n        if not path.startswith('/'):\n            for folder in self.options['template_folders']:\n                fullpath = op.join(folder, path)\n                if op.exists(fullpath):\n                    path = fullpath\n                    break\n            else:\n                raise JadeException('Template doesnt exist: %s' % path)\n        with open(path, 'rb') as f:\n            source = f.read().decode(self.options['encoding'])\n        return ExtendCompiler(\n            pyjade.parser.Parser(source).parse(), pretty=self.options['pretty'],\n            env=self, compileDebug=True\n        )",
    "docstring": "Load and compile a template."
  },
  {
    "code": "def make_scrape_request(session, url, mode='get', data=None):\n    try:\n        html = session.request(mode, url, data=data)\n    except RequestException:\n        raise VooblyError('failed to connect')\n    if SCRAPE_FETCH_ERROR in html.text:\n        raise VooblyError('not logged in')\n    if html.status_code != 200 or SCRAPE_PAGE_NOT_FOUND in html.text:\n        raise VooblyError('page not found')\n    return bs4.BeautifulSoup(html.text, features='lxml')",
    "docstring": "Make a request to URL."
  },
  {
    "code": "def getName(self, innerFlag=False):\n        if self._currentIdx is None:\n            raise error.PyAsn1Error('Component not chosen')\n        else:\n            if innerFlag:\n                c = self._componentValues[self._currentIdx]\n                if isinstance(c, Choice):\n                    return c.getName(innerFlag)\n            return self.componentType.getNameByPosition(self._currentIdx)",
    "docstring": "Return the name of currently assigned component of the |ASN.1| object.\n\n        Returns\n        -------\n        : :py:class:`str`\n            |ASN.1| component name"
  },
  {
    "code": "def filter_belief(stmts_in, belief_cutoff, **kwargs):\n    dump_pkl = kwargs.get('save')\n    logger.info('Filtering %d statements to above %f belief' %\n                (len(stmts_in), belief_cutoff))\n    stmts_out = []\n    for stmt in stmts_in:\n        if stmt.belief < belief_cutoff:\n            continue\n        stmts_out.append(stmt)\n        supp_by = []\n        supp = []\n        for st in stmt.supports:\n            if st.belief >= belief_cutoff:\n                supp.append(st)\n        for st in stmt.supported_by:\n            if st.belief >= belief_cutoff:\n                supp_by.append(st)\n        stmt.supports = supp\n        stmt.supported_by = supp_by\n    logger.info('%d statements after filter...' % len(stmts_out))\n    if dump_pkl:\n        dump_statements(stmts_out, dump_pkl)\n    return stmts_out",
    "docstring": "Filter to statements with belief above a given cutoff.\n\n    Parameters\n    ----------\n    stmts_in : list[indra.statements.Statement]\n        A list of statements to filter.\n    belief_cutoff : float\n        Only statements with belief above the belief_cutoff will be returned.\n        Here 0 < belief_cutoff < 1.\n    save : Optional[str]\n        The name of a pickle file to save the results (stmts_out) into.\n\n    Returns\n    -------\n    stmts_out : list[indra.statements.Statement]\n        A list of filtered statements."
  },
  {
    "code": "def get(search=\"unsigned\"):\n    plugins = []\n    for i in os.walk('/usr/lib/nagios/plugins'):\n        for f in i[2]:\n            plugins.append(f)\n    return plugins",
    "docstring": "List all available plugins"
  },
  {
    "code": "def _draw_binary(self):\n        self._draw_pr_curve(self.recall_, self.precision_, label=\"binary PR curve\")\n        self._draw_ap_score(self.score_)",
    "docstring": "Draw the precision-recall curves in the binary case"
  },
  {
    "code": "def range(cls, collection, attribute, left, right, closed, index_id, skip=None, limit=None):\n        kwargs = {\n            'index': index_id,\n            'attribute': attribute,\n            'left': left,\n            'right': right,\n            'closed': closed,\n            'skip': skip,\n            'limit': limit,\n        }\n        return cls._construct_query(name='range',\n                                    collection=collection, multiple=True,\n                                    **kwargs)",
    "docstring": "This will find all documents within a given range. In order to execute a range query, a\n            skip-list index on the queried attribute must be present.\n\n            :param collection Collection instance\n            :param attribute The attribute path to check\n            :param left The lower bound\n            :param right The upper bound\n            :param closed  If true, use interval including left and right, otherwise exclude right, but include left\n            :param index_id ID of the index which should be used for the query\n            :param skip  The number of documents to skip in the query\n            :param limit The maximal amount of documents to return. The skip is applied before the limit restriction.\n\n            :returns Document list"
  },
  {
    "code": "def calc_dist(lamost_point, training_points, coeffs):\n    diff2 = (training_points - lamost_point)**2\n    dist = np.sqrt(np.sum(diff2*coeffs, axis=1))\n    return np.mean(dist[dist.argsort()][0:10])",
    "docstring": "avg dist from one lamost point to nearest 10 training points"
  },
  {
    "code": "def p_debug(self, message):\n        \"Format and print debug messages\"\n        print(\"{}{} `{}`\".format(self._debug_indent * \" \",\n                                 message, repr(self.p_suffix(10))))",
    "docstring": "Format and print debug messages"
  },
  {
    "code": "def attention_lm_moe_24b_diet():\n  hparams = attention_lm_moe_large_diet()\n  hparams.moe_hidden_sizes = \"12288\"\n  hparams.moe_num_experts = 1024\n  hparams.batch_size = 4096\n  return hparams",
    "docstring": "Unnecessarily large model with 24B params - because we can."
  },
  {
    "code": "def convex_conj(self):\n        r\n        if self.quadratic_coeff == 0:\n            cconj = self.functional.convex_conj.translated(self.linear_term)\n            if self.constant != 0:\n                cconj = cconj - self.constant\n            return cconj\n        else:\n            return super(FunctionalQuadraticPerturb, self).convex_conj",
    "docstring": "r\"\"\"Convex conjugate functional of the functional.\n\n        Notes\n        -----\n        Given a functional :math:`f`, the convex conjugate of a linearly\n        perturbed version :math:`f(x) + <y, x>` is given by a translation of\n        the convex conjugate of :math:`f`:\n\n        .. math::\n            (f + \\langle y, \\cdot \\rangle)^* (x^*) = f^*(x^* - y).\n\n        For reference on the identity used, see `[KP2015]`_. Moreover, the\n        convex conjugate of :math:`f + c` is by definition\n\n        .. math::\n            (f + c)^* (x^*) = f^*(x^*) - c.\n\n\n        References\n        ----------\n        [KP2015] Komodakis, N, and Pesquet, J-C. *Playing with Duality: An\n        overview of recent primal-dual approaches for solving large-scale\n        optimization problems*. IEEE Signal Processing Magazine, 32.6 (2015),\n        pp 31--54.\n\n        .. _[KP2015]:  https://arxiv.org/abs/1406.5429"
  },
  {
    "code": "def remove_custom_css(destdir, resource=PKGNAME ):\n    if not os.path.isdir( destdir ):\n        return False\n    custom = os.path.join( destdir, 'custom.css' )\n    copy = True\n    found = False\n    prefix = css_frame_prefix(resource)\n    with io.open(custom + '-new', 'wt') as fout:\n        with io.open(custom) as fin:\n            for line in fin:\n                if line.startswith( prefix + 'START' ):\n                    copy = False\n                    found = True\n                elif line.startswith( prefix + 'END' ):\n                    copy = True\n                elif copy:\n                    fout.write( line )\n    if found:\n        os.rename( custom+'-new',custom)\n    else:\n        os.unlink( custom+'-new')\n    return found",
    "docstring": "Remove the kernel CSS from custom.css"
  },
  {
    "code": "def restart(self, all=False):\n        if all:\n            data = {'type': self.type}\n        else:\n            data = {'ps': self.process}\n        r = self._h._http_resource(\n            method='POST',\n            resource=('apps', self.app.name, 'ps', 'restart'),\n            data=data\n        )\n        r.raise_for_status()",
    "docstring": "Restarts the given process."
  },
  {
    "code": "def make_tarball(src_dir):\n    if type(src_dir) != str:\n        raise TypeError('src_dir must be str')\n    output_file = src_dir + \".tar.gz\"\n    log.msg(\"Wrapping tarball '{out}' ...\".format(out=output_file))\n    if not _dry_run:\n        with tarfile.open(output_file, \"w:gz\") as tar:\n            tar.add(src_dir, arcname=os.path.basename(src_dir))\n    return output_file",
    "docstring": "Make gzipped tarball from a source directory\n\n    :param src_dir: source directory\n    :raises TypeError: if src_dir is not str"
  },
  {
    "code": "def get_sentence_break_property(value, is_bytes=False):\n    obj = unidata.ascii_sentence_break if is_bytes else unidata.unicode_sentence_break\n    if value.startswith('^'):\n        negated = value[1:]\n        value = '^' + unidata.unicode_alias['sentencebreak'].get(negated, negated)\n    else:\n        value = unidata.unicode_alias['sentencebreak'].get(value, value)\n    return obj[value]",
    "docstring": "Get `SENTENCE BREAK` property."
  },
  {
    "code": "def show_function_centric_wizard(self):\n        from safe.gui.tools.wizard.wizard_dialog import WizardDialog\n        if self.wizard and self.wizard.isVisible():\n            return\n        if not self.wizard:\n            self.wizard = WizardDialog(\n                self.iface.mainWindow(),\n                self.iface,\n                self.dock_widget)\n        self.wizard.set_function_centric_mode()\n        self.wizard.show()",
    "docstring": "Show the function centric wizard."
  },
  {
    "code": "def get_system(self, identity):\n        return system.HPESystem(self._conn, identity,\n                                redfish_version=self.redfish_version)",
    "docstring": "Given the identity return a HPESystem object\n\n        :param identity: The identity of the System resource\n        :returns: The System object"
  },
  {
    "code": "def get_android_id(self) -> str:\n        output, _ = self._execute(\n            '-s', self.device_sn, 'shell', 'settings', 'get', 'secure', 'android_id')\n        return output.strip()",
    "docstring": "Show Android ID."
  },
  {
    "code": "def parse(self, text, layers=None):\n        params = {\n            \"text\": text,\n            \"key\": self.key,\n        }\n        if layers is not None:\n            if isinstance(layers, six.string_types):\n                params[\"layers\"] = layers\n            elif isinstance(layers, collections.Iterable):\n                params[\"layers\"] = \",\".join(layers)\n        req = requests.get(self.NLU_URL, params=params)\n        return req.json()",
    "docstring": "Parsing passed text to json.\n\n        Args:\n            text: Text to parse.\n            layers (optional): Special fields. Only one string\n                or iterable object (e.g \"Data\", (\"Data\", \"Fio\")).\n                Only these fields will be returned.\n\n\n        Returns:\n            The parsed text into a json object."
  },
  {
    "code": "def gen_file_lines(path, mode='rUb', strip_eol=True, ascii=True, eol='\\n'):\n    if isinstance(path, str):\n        path = open(path, mode)\n    with path:\n        for line in path:\n            if ascii:\n                line = str(line)\n            if strip_eol:\n                line = line.rstrip('\\n')\n            yield line",
    "docstring": "Generate a sequence of \"documents\" from the lines in a file\n\n    Arguments:\n      path (file or str): path to a file or an open file_obj ready to be read\n      mode (str): file mode to open a file in\n      strip_eol (bool): whether to strip the EOL char from lines as they are read/generated/yielded\n      ascii (bool): whether to use the stringify and to_ascii functions on each line\n      eol (str): UNUSED character delimitting lines in the file\n\n    TODO:\n      Use `eol` to split lines (currently ignored because use `file.readline` doesn't have EOL arg)"
  },
  {
    "code": "def raw_query(self, query, query_parameters=None):\n        self.assert_no_raw_query()\n        if len(self._where_tokens) != 0 or len(self._select_tokens) != 0 or len(\n                self._order_by_tokens) != 0 or len(self._group_by_tokens) != 0:\n            raise InvalidOperationException(\n                \"You can only use raw_query on a new query, without applying any operations \"\n                \"(such as where, select, order_by, group_by, etc)\")\n        if query_parameters:\n            self.query_parameters = query_parameters\n        self._query = query\n        return self",
    "docstring": "To get all the document that equal to the query\n\n        @param str query: The rql query\n        @param dict query_parameters: Add query parameters to the query {key : value}"
  },
  {
    "code": "def _message_received(self, message):\n        with self.lock:\n            self._state.receive_message(message)\n            for callable in chain(self._on_message_received, self._on_message):\n                callable(message)",
    "docstring": "Notify the observers about the received message."
  },
  {
    "code": "def update(self, egg, permute=False, nperms=1000,\n                 parallel=False):\n        self.n+=1\n        next_weights = np.nanmean(_analyze_chunk(egg,\n                          analysis=fingerprint_helper,\n                          analysis_type='fingerprint',\n                          pass_features=True,\n                          permute=permute,\n                          n_perms=nperms,\n                          parallel=parallel).values, 0)\n        if self.state is not None:\n            c = self.state*self.n\n            self.state = np.nansum(np.array([c, next_weights]), axis=0)/(self.n+1)\n        else:\n            self.state = next_weights\n        self.history.append(next_weights)",
    "docstring": "In-place method that updates fingerprint with new data\n\n        Parameters\n        ----------\n        egg : quail.Egg\n            Data to update fingerprint\n        Returns\n        ----------\n        None"
  },
  {
    "code": "def origin(self):\n        with self.selenium.context(self.selenium.CONTEXT_CHROME):\n            return self.root.get_attribute(\"origin\")",
    "docstring": "Provide access to the notification origin.\n\n        Returns:\n            str: The notification origin."
  },
  {
    "code": "def plot_loss(self, n_skip=10, n_skip_end=5):\n        if not in_ipynb(): plt.switch_backend('agg')\n        plt.plot(self.iterations[n_skip:-n_skip_end], self.losses[n_skip:-n_skip_end])\n        if not in_ipynb():\n            plt.savefig(os.path.join(self.save_path, 'loss_plot.png'))\n            np.save(os.path.join(self.save_path, 'losses.npy'), self.losses[10:])",
    "docstring": "plots loss function as function of iterations. \n        When used in Jupyternotebook, plot will be displayed in notebook. Else, plot will be displayed in console and both plot and loss are saved in save_path."
  },
  {
    "code": "def get_key():\n    character_name = chr\n    codes = _get_keycodes()\n    if len(codes) == 1:\n        code = codes[0]\n        if code >= 32:\n            return character_name(code)\n        return control_key_name(code)\n    return get_extended_key_name(codes)",
    "docstring": "Get a key from the keyboard as a string\n\n    A 'key' will be a single char, or the name of an extended key"
  },
  {
    "code": "def get_quoted_local_columns(self, platform):\n        columns = []\n        for column in self._local_column_names.values():\n            columns.append(column.get_quoted_name(platform))\n        return columns",
    "docstring": "Returns the quoted representation of the referencing table column names\n        the foreign key constraint is associated with.\n\n        But only if they were defined with one or the referencing table column name\n        is a keyword reserved by the platform.\n        Otherwise the plain unquoted value as inserted is returned.\n\n        :param platform: The platform to use for quotation.\n        :type platform: Platform\n\n        :rtype: list"
  },
  {
    "code": "def render_html(self, *args, **kwargs):\n        static_url = '%s://%s%s' % (self.request.scheme, self.request.get_host(), settings.STATIC_URL)\n        media_url = '%s://%s%s' % (self.request.scheme, self.request.get_host(), settings.MEDIA_URL)\n        with override_settings(STATIC_URL=static_url, MEDIA_URL=media_url):\n            template = loader.get_template(self.template_name)\n            context = self.get_context_data(*args, **kwargs)\n            html = template.render(context)\n            return html",
    "docstring": "Renders the template.\n\n        :rtype: str"
  },
  {
    "code": "def serialize(self, data):\n        with open(self.dest, 'wb') as fh:\n            root = et.Element('nrml')\n            self.add_hazard_curves(root, self.metadata, data)\n            nrml.write(list(root), fh)",
    "docstring": "Write a sequence of hazard curves to the specified file.\n\n        :param data:\n            Iterable of hazard curve data. Each datum must be an object with\n            the following attributes:\n\n            * poes: A list of probability of exceedence values (floats).\n            * location: An object representing the location of the curve; must\n              have `x` and `y` to represent lon and lat, respectively."
  },
  {
    "code": "def render(self, template_name: str, **ctx):\n        if '.' not in template_name:\n            template_file_extension = (self.Meta.template_file_extension\n                                       or app.config.TEMPLATE_FILE_EXTENSION)\n            template_name = f'{template_name}{template_file_extension}'\n        if self.Meta.template_folder_name and os.sep not in template_name:\n            template_name = os.path.join(self.Meta.template_folder_name,\n                                         template_name)\n        return render_template(template_name, **ctx)",
    "docstring": "Convenience method for rendering a template.\n\n        :param template_name: The template's name. Can either be a full path,\n                              or a filename in the controller's template folder.\n        :param ctx: Context variables to pass into the template."
  },
  {
    "code": "def get_admins_from_django(homedir):\n    return [\"root@localhost\"]\n    path = homedir + \"/settings/basic.py\"\n    if not os.path.exists(path):\n        path = homedir + \"/settings.py\"\n    if not os.path.exists(path):\n        return\n    mod = compiler.parseFile(path)\n    for node in mod.node.nodes:\n        try:\n            if node.asList()[0].name == \"ADMINS\":\n                return [it.nodes[1].value for it in node.asList()[1].asList()]\n        except:\n            pass",
    "docstring": "Get admin's emails from django settings"
  },
  {
    "code": "def pos(self):\n        pos = self._pos\n        if pos is None:\n            return self.p0\n        pos = {param: self._pos[..., k]\n               for (k, param) in enumerate(self.sampling_params)}\n        return pos",
    "docstring": "A dictionary of the current walker positions.\n\n        If the sampler hasn't been run yet, returns p0."
  },
  {
    "code": "def get_writable_metadata(self, file_format):\n        if file_format == 'json':\n            metadata = self.json\n        elif file_format == 'xml':\n            metadata = self.xml\n        else:\n            raise TypeError('The requested file type (%s) is not yet supported'\n                            % file_format)\n        return metadata",
    "docstring": "Convert the metadata to a writable form.\n\n        :param file_format: the needed format can be json or xml\n        :type file_format: str\n        :return: the dupled metadata\n        :rtype: str"
  },
  {
    "code": "def cli(self):\n        if self._cli is None:\n            self._cli = self.create_interface()\n        return self._cli",
    "docstring": "Makes the interface or refreshes it"
  },
  {
    "code": "def get_rand_string(length=12, allowed_chars='0123456789abcdef'):\n    if not using_sysrandom:\n        random.seed(\n            hashlib.sha256(\n                (\"%s%s\" % (\n                    random.getstate(),\n                    time.time())).encode('utf-8')\n            ).digest())\n    return ''.join([random.choice(allowed_chars) for i in range(length)])",
    "docstring": "Returns a securely generated random string. Taken from the Django project\n\n    The default length of 12 with the a-z, A-Z, 0-9 character set returns\n    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits"
  },
  {
    "code": "def _request(self, url, params={}):\n        r = self._session.get(url=url, params=params, headers=DEFAULT_ORIGIN)\n        return r",
    "docstring": "Makes a request using the currently open session.\n\n        :param url: A url fragment to use in the creation of the master url"
  },
  {
    "code": "def focus_next(self, count=1):\n        \" Focus the next pane. \"\n        panes = self.panes\n        if panes:\n            self.active_pane = panes[(panes.index(self.active_pane) + count) % len(panes)]\n        else:\n            self.active_pane = None",
    "docstring": "Focus the next pane."
  },
  {
    "code": "def get(self, *args, **kwargs):\n        self.before_get(args, kwargs)\n        relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()\n        obj, data = self._data_layer.get_relationship(model_relationship_field,\n                                                      related_type_,\n                                                      related_id_field,\n                                                      kwargs)\n        result = {'links': {'self': request.path,\n                            'related': self.schema._declared_fields[relationship_field].get_related_url(obj)},\n                  'data': data}\n        qs = QSManager(request.args, self.schema)\n        if qs.include:\n            schema = compute_schema(self.schema, dict(), qs, qs.include)\n            serialized_obj = schema.dump(obj)\n            result['included'] = serialized_obj.data.get('included', dict())\n        final_result = self.after_get(result)\n        return final_result",
    "docstring": "Get a relationship details"
  },
  {
    "code": "def SCISetStyling(self, line: int, col: int,\n                      numChar: int, style: bytearray):\n        if not self.isPositionValid(line, col):\n            return\n        pos = self.positionFromLineIndex(line, col)\n        self.SendScintilla(self.SCI_STARTSTYLING, pos, 0xFF)\n        self.SendScintilla(self.SCI_SETSTYLING, numChar, style)",
    "docstring": "Pythonic wrapper for the SCI_SETSTYLING command.\n\n        For example, the following code applies style #3\n        to the first five characters in the second line\n        of the widget:\n\n            SCISetStyling((0, 1), 5, 3)\n\n        |Args|\n\n        * ``line`` (**int**): line number where to start styling.\n        * ``col`` (**int**): column number where to start styling.\n        * ``numChar`` (**int**): number of characters to style.\n        * ``style`` (**int**): Scintilla style number.\n\n        |Returns|\n\n        **None**\n\n        |Raises|\n\n        * **QtmacsArgumentError** if at least one argument has an invalid type."
  },
  {
    "code": "def browserify_libs(lib_dirs, output_file, babelify=False):\n    from .modules import browserify\n    if not isinstance(lib_dirs, (list, tuple)):\n        raise RuntimeError('Browserify Libs compiler takes a list of library directories as input.')\n    return {\n        'dependencies_fn': browserify.browserify_deps_libs,\n        'compiler_fn': browserify.browserify_compile_libs,\n        'input': lib_dirs,\n        'output': output_file,\n        'kwargs': {\n            'babelify': babelify,\n        },\n    }",
    "docstring": "Browserify one or more library directories into a single\n    javascript file. Generates source maps in debug mode. Minifies the\n    output in release mode.\n\n    The final directory name in each of lib_dirs is the library name\n    for importing. Eg.::\n\n        lib_dirs = ['cordova_libs/jskit']\n\n        var MyClass = require('jskit/MyClass');"
  },
  {
    "code": "def stringc(text, color):\n    if has_colors:\n        text = str(text)\n        return \"\\033[\"+codeCodes[color]+\"m\"+text+\"\\033[0m\"\n    else:\n        return text",
    "docstring": "Return a string with terminal colors."
  },
  {
    "code": "def _get_jmx_data(self, instance, jmx_address, tags):\n        response = self._rest_request_to_json(\n            instance, jmx_address, self.JMX_PATH, {'qry': self.HDFS_DATANODE_BEAN_NAME}, tags=tags\n        )\n        beans = response.get('beans', [])\n        return beans",
    "docstring": "Get namenode beans data from JMX endpoint"
  },
  {
    "code": "def is_circumpolar(self, var):\n        xcoord = self.get_x(var)\n        return xcoord is not None and xcoord.ndim == 2",
    "docstring": "Test if a variable is on a circumpolar grid\n\n        Parameters\n        ----------\n        %(CFDecoder.is_triangular.parameters)s\n\n        Returns\n        -------\n        %(CFDecoder.is_triangular.returns)s"
  },
  {
    "code": "def on_pumprequest(self, event):\n        self.log(\"Updating pump status: \", event.controlvalue)\n        self._set_digital_pin(self._pump_channel, event.controlvalue)",
    "docstring": "Activates or deactivates a connected pump.\n\n        :param event:"
  },
  {
    "code": "def all_tamil( word_in ):\n    if isinstance(word_in,list):\n        word = word_in\n    else:\n        word = get_letters( word_in )\n    return all( [(letter in tamil_letters) for letter in word] )",
    "docstring": "predicate checks if all letters of the input word are Tamil letters"
  },
  {
    "code": "def _itertuples(df):\n    cols = [df.iloc[:, k] for k in range(len(df.columns))]\n    return zip(df.index, *cols)",
    "docstring": "Custom implementation of ``DataFrame.itertuples`` that\n    returns plain tuples instead of namedtuples. About 50% faster."
  },
  {
    "code": "def _get_protocol_tuple(data: Dict[str, Any]) -> Tuple[str, List, Dict]:\n    return data['function'], data.get('args', []), data.get('kwargs', {})",
    "docstring": "Convert a dictionary to a tuple."
  },
  {
    "code": "def html_encode(path):\n    if sys.version_info > (3, 2, 0):\n        return urllib.parse.quote(utils.ensure_string(path))\n    else:\n        return urllib.quote(utils.ensure_string(path))",
    "docstring": "Return an HTML encoded Path.\n\n    :param path: ``str``\n    :return: ``str``"
  },
  {
    "code": "def timer(fun, *a, **k):\n    @wraps(fun)\n    def timer(*a, **k):\n        start = arrow.now()\n        ret = fun(*a, **k)\n        end = arrow.now()\n        print('timer:fun: %s\\n start:%s,end:%s, took [%s]' % (\n            str(fun), str(start), str(end), str(end - start)))\n        return ret\n    return timer",
    "docstring": "define a timer for a rule function\n    for log and statistic purposes"
  },
  {
    "code": "def to_datetimeindex(self, unsafe=False):\n        nptimes = cftime_to_nptime(self)\n        calendar = infer_calendar_name(self)\n        if calendar not in _STANDARD_CALENDARS and not unsafe:\n            warnings.warn(\n                'Converting a CFTimeIndex with dates from a non-standard '\n                'calendar, {!r}, to a pandas.DatetimeIndex, which uses dates '\n                'from the standard calendar.  This may lead to subtle errors '\n                'in operations that depend on the length of time between '\n                'dates.'.format(calendar), RuntimeWarning, stacklevel=2)\n        return pd.DatetimeIndex(nptimes)",
    "docstring": "If possible, convert this index to a pandas.DatetimeIndex.\n\n        Parameters\n        ----------\n        unsafe : bool\n            Flag to turn off warning when converting from a CFTimeIndex with\n            a non-standard calendar to a DatetimeIndex (default ``False``).\n\n        Returns\n        -------\n        pandas.DatetimeIndex\n\n        Raises\n        ------\n        ValueError\n            If the CFTimeIndex contains dates that are not possible in the\n            standard calendar or outside the pandas.Timestamp-valid range.\n\n        Warns\n        -----\n        RuntimeWarning\n            If converting from a non-standard calendar to a DatetimeIndex.\n\n        Warnings\n        --------\n        Note that for non-standard calendars, this will change the calendar\n        type of the index.  In that case the result of this method should be\n        used with caution.\n\n        Examples\n        --------\n        >>> import xarray as xr\n        >>> times = xr.cftime_range('2000', periods=2, calendar='gregorian')\n        >>> times\n        CFTimeIndex([2000-01-01 00:00:00, 2000-01-02 00:00:00], dtype='object')\n        >>> times.to_datetimeindex()\n        DatetimeIndex(['2000-01-01', '2000-01-02'], dtype='datetime64[ns]', freq=None)"
  },
  {
    "code": "def pull(args):\n    p = OptionParser(pull.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 3:\n        sys.exit(not p.print_help())\n    prefix = get_prefix()\n    version, partID, unitigID = args\n    s = \".\".join(args)\n    cmd = \"tigStore\"\n    cmd += \" -g ../{0}.gkpStore -t ../{0}.tigStore\".format(prefix)\n    cmd += \" {0} -up {1} -d layout -u {2}\".format(version, partID, unitigID)\n    unitigfile = \"unitig\" + s\n    sh(cmd, outfile=unitigfile)\n    return unitigfile",
    "docstring": "%prog pull version partID unitigID\n\n    For example, `%prog pull 5 530` will pull the utg530 from partition 5\n    The layout is written to `unitig530`"
  },
  {
    "code": "def div(self, y):\n        r\n        y = np.asanyarray(y)\n        if y.shape[0] != self.Ne:\n            raise ValueError('First dimension must be the number of edges '\n                             'G.Ne = {}, got {}.'.format(self.Ne, y.shape))\n        return self.D.dot(y)",
    "docstring": "r\"\"\"Compute the divergence of a signal defined on the edges.\n\n        The divergence :math:`z` of a signal :math:`y` is defined as\n\n        .. math:: z = \\operatorname{div}_\\mathcal{G} y = D y,\n\n        where :math:`D` is the differential operator :attr:`D`.\n\n        The value of the divergence on the vertex :math:`v_i` is\n\n        .. math:: z[i] = \\sum_k D[i, k] y[k]\n            = \\sum_{\\{k,j | e_k=(v_j, v_i) \\in \\mathcal{E}\\}}\n                \\sqrt{\\frac{W[j, i]}{2}} y[k]\n            - \\sum_{\\{k,j | e_k=(v_i, v_j) \\in \\mathcal{E}\\}}\n                \\sqrt{\\frac{W[i, j]}{2}} y[k]\n\n        for the combinatorial Laplacian, and\n\n        .. math:: z[i] = \\sum_k D[i, k] y[k]\n            = \\sum_{\\{k,j | e_k=(v_j, v_i) \\in \\mathcal{E}\\}}\n                \\sqrt{\\frac{W[j, i]}{2 d[i]}} y[k]\n            - \\sum_{\\{k,j | e_k=(v_i, v_j) \\in \\mathcal{E}\\}}\n                \\sqrt{\\frac{W[i, j]}{2 d[i]}} y[k]\n\n        for the normalized Laplacian.\n\n        For undirected graphs, only half the edges are kept and the\n        :math:`1/\\sqrt{2}` factor disappears from the above equations. See\n        :meth:`compute_differential_operator` for details.\n\n        Parameters\n        ----------\n        y : array_like\n            Signal of length :attr:`n_edges` living on the edges.\n\n        Returns\n        -------\n        z : ndarray\n            Divergence signal of length :attr:`n_vertices` living on the\n            vertices.\n\n        See Also\n        --------\n        compute_differential_operator\n        grad : compute the gradient of a vertex signal\n\n        Examples\n        --------\n\n        Non-directed graph and combinatorial Laplacian:\n\n        >>> graph = graphs.Path(4, directed=False, lap_type='combinatorial')\n        >>> graph.compute_differential_operator()\n        >>> graph.div([2, -2, 0])\n        array([-2.,  4., -2.,  0.])\n\n        Directed graph and combinatorial Laplacian:\n\n        >>> graph = graphs.Path(4, directed=True, lap_type='combinatorial')\n        >>> graph.compute_differential_operator()\n        >>> graph.div([2, -2, 0])\n        array([-1.41421356,  2.82842712, -1.41421356,  0.        ])\n\n        Non-directed graph and normalized Laplacian:\n\n        >>> graph = graphs.Path(4, directed=False, lap_type='normalized')\n        >>> graph.compute_differential_operator()\n        >>> graph.div([2, -2, 0])\n        array([-2.        ,  2.82842712, -1.41421356,  0.        ])\n\n        Directed graph and normalized Laplacian:\n\n        >>> graph = graphs.Path(4, directed=True, lap_type='normalized')\n        >>> graph.compute_differential_operator()\n        >>> graph.div([2, -2, 0])\n        array([-2.        ,  2.82842712, -1.41421356,  0.        ])"
  },
  {
    "code": "def load_scheduler_plugins(self):\n        if not self.scheduler_plugins:\n            for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.schedulers']['plugins']:\n                cls = entry_point.load()\n                self.scheduler_plugins[cls.__name__] = cls\n                if cls.__name__ == self.active_scheduler:\n                    self.log.debug('Scheduler loaded: {} in module {}'.format(cls.__name__, cls.__module__))\n                else:\n                    self.log.debug('Scheduler disabled: {} in module {}'.format(cls.__name__, cls.__module__))",
    "docstring": "Refresh the list of available schedulers\n\n        Returns:\n            `list` of :obj:`BaseScheduler`"
  },
  {
    "code": "def coherence_spectrogram(self, other, stride, fftlength=None,\n                              overlap=None, window='hann', nproc=1):\n        from ..spectrogram.coherence import from_timeseries\n        return from_timeseries(self, other, stride, fftlength=fftlength,\n                               overlap=overlap, window=window,\n                               nproc=nproc)",
    "docstring": "Calculate the coherence spectrogram between this `TimeSeries`\n        and other.\n\n        Parameters\n        ----------\n        other : `TimeSeries`\n            the second `TimeSeries` in this CSD calculation\n\n        stride : `float`\n            number of seconds in single PSD (column of spectrogram)\n\n        fftlength : `float`\n            number of seconds in single FFT\n\n        overlap : `float`, optional\n            number of seconds of overlap between FFTs, defaults to the\n            recommended overlap for the given window (if given), or 0\n\n        window : `str`, `numpy.ndarray`, optional\n            window function to apply to timeseries prior to FFT,\n            see :func:`scipy.signal.get_window` for details on acceptable\n            formats\n\n        nproc : `int`\n            number of parallel processes to use when calculating\n            individual coherence spectra.\n\n        Returns\n        -------\n        spectrogram : `~gwpy.spectrogram.Spectrogram`\n            time-frequency coherence spectrogram as generated from the\n            input time-series."
  },
  {
    "code": "def _state_connecting(self):\n        def responseReceived(protocol):\n            self.makeConnection(protocol)\n            if self._state == 'aborting':\n                self._toState('disconnecting')\n            else:\n                self._toState('connected')\n        def trapError(failure):\n            self._toState('error', failure)\n        def onEntry(entry):\n            if self.delegate:\n                try:\n                    self.delegate(entry)\n                except:\n                    log.err()\n            else:\n                pass\n        d = self.api(onEntry, self.args)\n        d.addCallback(responseReceived)\n        d.addErrback(trapError)",
    "docstring": "A connection is being started.\n\n        A succesful attempt results in the state C{'connected'} when the\n        first response from Twitter has been received. Transitioning\n        to the state C{'aborting'} will cause an immediate disconnect instead,\n        by transitioning to C{'disconnecting'}.\n\n        Errors will cause a transition to the C{'error'} state."
  },
  {
    "code": "def explain_prediction_sklearn(estimator, doc,\n                               vec=None,\n                               top=None,\n                               top_targets=None,\n                               target_names=None,\n                               targets=None,\n                               feature_names=None,\n                               feature_re=None,\n                               feature_filter=None,\n                               vectorized=False):\n    return explain_prediction_sklearn_not_supported(estimator, doc)",
    "docstring": "Return an explanation of a scikit-learn estimator"
  },
  {
    "code": "def _conn(commit=False):\n    defaults = {'host': 'localhost',\n                'user': 'salt',\n                'password': 'salt',\n                'dbname': 'salt',\n                'port': 5432}\n    conn_kwargs = {}\n    for key, value in defaults.items():\n        conn_kwargs[key] = __opts__.get('queue.{0}.{1}'.format(__virtualname__, key), value)\n    try:\n        conn = psycopg2.connect(**conn_kwargs)\n    except psycopg2.OperationalError as exc:\n        raise SaltMasterError('pgjsonb returner could not connect to database: {exc}'.format(exc=exc))\n    cursor = conn.cursor()\n    try:\n        yield cursor\n    except psycopg2.DatabaseError as err:\n        error = err.args\n        sys.stderr.write(six.text_type(error))\n        cursor.execute(\"ROLLBACK\")\n        raise err\n    else:\n        if commit:\n            cursor.execute(\"COMMIT\")\n        else:\n            cursor.execute(\"ROLLBACK\")\n    finally:\n        conn.close()",
    "docstring": "Return an postgres cursor"
  },
  {
    "code": "def cli(env, identifier):\n    vsi = SoftLayer.VSManager(env.client)\n    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')\n    instance = vsi.get_instance(vs_id)\n    table = formatting.Table(['username', 'password'])\n    for item in instance['operatingSystem']['passwords']:\n        table.add_row([item['username'], item['password']])\n    env.fout(table)",
    "docstring": "List virtual server credentials."
  },
  {
    "code": "def get_model_class(self):\n        if getattr(self, 'model', None):\n            return self.model\n        elif getattr(self, 'object', None):\n            return self.object.__class__\n        elif 'app' in self.kwargs and 'model' in self.kwargs:\n            return apps.get_model(self.kwargs.get('app'), self.kwargs.get('model'))\n        elif hasattr(self, 'get_queryset'):\n            return self.get_queryset().model\n        else:\n            return None",
    "docstring": "Get model class"
  },
  {
    "code": "def _validate_json_for_regular_workflow(json_spec, args):\n    validated = {}\n    override_project_id, override_folder, override_workflow_name = \\\n        dxpy.executable_builder.get_parsed_destination(args.destination)\n    validated['project'] = _get_destination_project(json_spec, args, override_project_id)\n    validated['folder'] = _get_destination_folder(json_spec, override_folder)\n    workflow_name = _get_workflow_name(json_spec, override_workflow_name)\n    if not workflow_name:\n        print('Warning: workflow name is not specified')\n    else:\n        validated['name'] = workflow_name\n    return validated",
    "docstring": "Validates fields used only for building a regular, project-based workflow."
  },
  {
    "code": "def extend_dict_key_value(\n        in_dict,\n        keys,\n        value,\n        delimiter=DEFAULT_TARGET_DELIM,\n        ordered_dict=False):\n    dict_pointer, last_key = _dict_rpartition(\n        in_dict,\n        keys,\n        delimiter=delimiter,\n        ordered_dict=ordered_dict)\n    if last_key not in dict_pointer or dict_pointer[last_key] is None:\n        dict_pointer[last_key] = []\n    try:\n        dict_pointer[last_key].extend(value)\n    except AttributeError:\n        raise SaltInvocationError('The last key contains a {}, which cannot extend.'\n                                  ''.format(type(dict_pointer[last_key])))\n    except TypeError:\n        raise SaltInvocationError('Cannot extend {} with a {}.'\n                                  ''.format(type(dict_pointer[last_key]), type(value)))\n    return in_dict",
    "docstring": "Ensures that in_dict contains the series of recursive keys defined in keys.\n    Also extends the list, that is at the end of `in_dict` traversed with `keys`,\n    with `value`.\n\n    :param dict in_dict: The dictionary to work with\n    :param str keys: The delimited string with one or more keys.\n    :param any value: The value to extend the nested dict-key with.\n    :param str delimiter: The delimiter to use in `keys`. Defaults to ':'.\n    :param bool ordered_dict: Create OrderedDicts if keys are missing.\n                              Default: create regular dicts.\n\n    :return dict: Though it updates in_dict in-place."
  },
  {
    "code": "def two_way_portal(self, other, **stats):\n        return self.character.new_portal(\n            self, other, symmetrical=True, **stats\n        )",
    "docstring": "Connect these nodes with a two-way portal and return it."
  },
  {
    "code": "def readCovarianceMatrixFile(cfile,readCov=True,readEig=True):\n    covFile = cfile+'.cov'\n    evalFile = cfile+'.cov.eval'\n    evecFile = cfile+'.cov.evec'\n    RV = {}\n    if readCov:\n        assert os.path.exists(covFile), '%s is missing.'%covFile\n        RV['K'] = SP.loadtxt(covFile)\n    if readEig:\n        assert os.path.exists(evalFile), '%s is missing.'%evalFile\n        assert os.path.exists(evecFile), '%s is missing.'%evecFile\n        RV['eval'] = SP.loadtxt(evalFile)\n        RV['evec'] = SP.loadtxt(evecFile)\n    return RV",
    "docstring": "reading in similarity matrix\n\n    cfile   File containing the covariance matrix. The corresponding ID file must be specified in cfile.id)"
  },
  {
    "code": "def parse_args(args=None):\r\n    parser = argparse.ArgumentParser()\r\n    parser.add_argument(\r\n        '-w', '--window',\r\n        default=\"pyqt5\",\r\n        choices=find_window_classes(),\r\n        help='Name for the window type to use',\r\n    )\r\n    parser.add_argument(\r\n        '-fs', '--fullscreen',\r\n        action=\"store_true\",\r\n        help='Open the window in fullscreen mode',\r\n    )\r\n    parser.add_argument(\r\n        '-vs', '--vsync',\r\n        type=str2bool,\r\n        default=\"1\",\r\n        help=\"Enable or disable vsync\",\r\n    )\r\n    parser.add_argument(\r\n        '-s', '--samples',\r\n        type=int,\r\n        default=4,\r\n        help=\"Specify the desired number of samples to use for multisampling\",\r\n    )\r\n    parser.add_argument(\r\n        '-c', '--cursor',\r\n        type=str2bool,\r\n        default=\"true\",\r\n        help=\"Enable or disable displaying the mouse cursor\",\r\n    )\r\n    return parser.parse_args(args or sys.argv[1:])",
    "docstring": "Parse arguments from sys.argv"
  },
  {
    "code": "def copy(self):\n        df = super(Ensemble,self).copy()\n        return type(self).from_dataframe(df=df)",
    "docstring": "make a deep copy of self\n\n        Returns\n        -------\n        Ensemble : Ensemble"
  },
  {
    "code": "def _expected_condition_value_in_element_attribute(self, element_attribute_value):\n        element, attribute, value = element_attribute_value\n        web_element = self._expected_condition_find_element(element)\n        try:\n            return web_element if web_element and web_element.get_attribute(attribute) == value else False\n        except StaleElementReferenceException:\n            return False",
    "docstring": "Tries to find the element and checks that it contains the requested attribute with the expected value,\n           but does not thrown an exception if the element is not found\n\n        :param element_attribute_value: Tuple with 3 items where:\n            [0] element: PageElement or element locator as a tuple (locator_type, locator_value) to be found\n            [1] attribute: element's attribute where to check its value\n            [2] value: expected value for the element's attribute\n        :returns: the web element if it contains the expected value for the requested attribute or False\n        :rtype: selenium.webdriver.remote.webelement.WebElement or appium.webdriver.webelement.WebElement"
  },
  {
    "code": "def horiz_rows(labels, data, normal_dat, args, colors):\n    val_min = find_min(data)\n    for i in range(len(labels)):\n        if args['no_labels']:\n            label = ''\n        else:\n            label = \"{:<{x}}: \".format(labels[i],\n                                       x=find_max_label_length(labels))\n        values = data[i]\n        num_blocks = normal_dat[i]\n        for j in range(len(values)):\n            if j > 0:\n                len_label = len(label)\n                label = ' ' * len_label\n            tail = ' {}{}'.format(args['format'].format(values[j]),\n                                  args['suffix'])\n            if colors:\n                color = colors[j]\n            else:\n                color = None\n            if not args['vertical']:\n                print(label, end=\"\")\n            yield(values[j], int(num_blocks[j]), val_min, color)\n            if not args['vertical']:\n                print(tail)",
    "docstring": "Prepare the horizontal graph.\n       Each row is printed through the print_row function."
  },
  {
    "code": "def formfield_for_foreignkey_helper(inline, *args, **kwargs):\n    db_field = args[0]\n    if db_field.name != \"related_type\":\n        return args, kwargs\n    initial_filter = getattr(settings, RELATED_TYPE_INITIAL_FILTER,\n            False)\n    if \"initial\" not in kwargs and initial_filter:\n        initial = RelatedType.objects.get(**initial_filter).pk\n        kwargs[\"initial\"] = initial\n    return args, kwargs",
    "docstring": "The implementation for ``RelatedContentInline.formfield_for_foreignkey``\n\n    This takes the takes all of the ``args`` and ``kwargs`` from the call to\n    ``formfield_for_foreignkey`` and operates on this.  It returns the updated\n    ``args`` and ``kwargs`` to be passed on to ``super``.\n\n    This is solely an implementation detail as it's easier to test a function\n    than to provide all of the expectations that the ``GenericTabularInline``\n    has."
  },
  {
    "code": "def update_entitlement(owner, repo, identifier, name, token, show_tokens):\n    client = get_entitlements_api()\n    data = {}\n    if name is not None:\n        data[\"name\"] = name\n    if token is not None:\n        data[\"token\"] = token\n    with catch_raise_api_exception():\n        data, _, headers = client.entitlements_partial_update_with_http_info(\n            owner=owner,\n            repo=repo,\n            identifier=identifier,\n            data=data,\n            show_tokens=show_tokens,\n        )\n    ratelimits.maybe_rate_limit(client, headers)\n    return data.to_dict()",
    "docstring": "Update an entitlement in a repository."
  },
  {
    "code": "def has_edge(self, edge):\n        u, v = edge\n        return (u, v) in self.edge_properties",
    "docstring": "Return whether an edge exists.\n\n        @type  edge: tuple\n        @param edge: Edge.\n\n        @rtype:  boolean\n        @return: Truth-value for edge existence."
  },
  {
    "code": "def decode(decoder, data, length, frame_size, decode_fec, channels=2):\n    pcm_size = frame_size * channels * ctypes.sizeof(ctypes.c_int16)\n    pcm = (ctypes.c_int16 * pcm_size)()\n    pcm_pointer = ctypes.cast(pcm, c_int16_pointer)\n    decode_fec = int(bool(decode_fec))\n    result = _decode(decoder, data, length, pcm_pointer, frame_size, decode_fec)\n    if result < 0:\n        raise OpusError(result)\n    return array.array('h', pcm).tostring()",
    "docstring": "Decode an Opus frame\n\n    Unlike the `opus_decode` function , this function takes an additional parameter `channels`,\n    which indicates the number of channels in the frame"
  },
  {
    "code": "def get_stats_display_width(self, curse_msg, without_option=False):\n        try:\n            if without_option:\n                c = len(max(''.join([(u(u(nativestr(i['msg'])).encode('ascii', 'replace')) if not i['optional'] else \"\")\n                                     for i in curse_msg['msgdict']]).split('\\n'), key=len))\n            else:\n                c = len(max(''.join([u(u(nativestr(i['msg'])).encode('ascii', 'replace'))\n                                     for i in curse_msg['msgdict']]).split('\\n'), key=len))\n        except Exception as e:\n            logger.debug('ERROR: Can not compute plugin width ({})'.format(e))\n            return 0\n        else:\n            return c",
    "docstring": "Return the width of the formatted curses message."
  },
  {
    "code": "def generate_additional_context(self, matching_datasets):\n        dataset_ids = [upload.id for upload in matching_datasets]\n        tags = Tag.objects.filter(\n            dataset__in=dataset_ids\n        ).distinct().annotate(\n            Count('word')\n        ).order_by('-word__count')[:5]\n        hubs = matching_datasets.values(\"hub_slug\").annotate(\n            Count('hub_slug')\n        ).order_by('-hub_slug__count')\n        if hubs:\n            most_used_hub = get_hub_name_from_slug(hubs[0]['hub_slug'])\n            hub_slug = hubs[0]['hub_slug']\n        else:\n            most_used_hub = None\n            hub_slug = None\n        return {\n            'tags': tags,\n            'hub': most_used_hub,\n            'hub_slug': hub_slug,\n        }",
    "docstring": "Return additional information about matching datasets.\n\n        Includes upload counts, related hubs, related tags."
  },
  {
    "code": "def dirname(self, path):\n        if self.is_ssh(path):\n            remotepath = self._get_remote(path)\n            remotedir = os.path.dirname(remotepath)\n            return self._get_tramp_path(remotedir)\n        else:\n            return os.path.dirname(path)",
    "docstring": "Returns the full path to the parent directory of the specified\n        file path."
  },
  {
    "code": "def save_region(region, filename):\n    region.save(filename)\n    logging.info(\"Wrote {0}\".format(filename))\n    return",
    "docstring": "Save the given region to a file\n\n    Parameters\n    ----------\n    region : :class:`AegeanTools.regions.Region`\n        A region.\n\n    filename : str\n        Output file name."
  },
  {
    "code": "def _writeOptionalXsecCards(self, fileObject, xSec, replaceParamFile):\n        if xSec.erode:\n            fileObject.write('ERODE\\n')\n        if xSec.maxErosion != None:\n            fileObject.write('MAX_EROSION    %.6f\\n' % xSec.maxErosion)\n        if xSec.subsurface:\n            fileObject.write('SUBSURFACE\\n')\n        if xSec.mRiver != None:\n            mRiver = vwp(xSec.mRiver, replaceParamFile)\n            try:\n                fileObject.write('M_RIVER        %.6f\\n' % mRiver)\n            except:\n                fileObject.write('M_RIVER        %s\\n' % mRiver)\n        if xSec.kRiver != None:\n            kRiver = vwp(xSec.kRiver, replaceParamFile)\n            try:\n                fileObject.write('K_RIVER        %.6f\\n' % kRiver)\n            except:\n                fileObject.write('K_RIVER        %s\\n' % kRiver)",
    "docstring": "Write Optional Cross Section Cards to File Method"
  },
  {
    "code": "def serialize_cert_to_der(cert_obj):\n    return cert_obj.public_bytes(\n        cryptography.hazmat.primitives.serialization.Encoding.DER\n    )",
    "docstring": "Serialize certificate to DER.\n\n    Args:\n      cert_obj: cryptography.Certificate\n\n    Returns:\n      bytes: DER encoded certificate"
  },
  {
    "code": "def update(self, new_keys: Index):\n        if not self._map.index.intersection(new_keys).empty:\n            raise KeyError(\"Non-unique keys in index.\")\n        mapping_update = self.hash_(new_keys)\n        if self._map.empty:\n            self._map = mapping_update.drop_duplicates()\n        else:\n            self._map = self._map.append(mapping_update).drop_duplicates()\n        collisions = mapping_update.index.difference(self._map.index)\n        salt = 1\n        while not collisions.empty:\n            mapping_update = self.hash_(collisions, salt)\n            self._map = self._map.append(mapping_update).drop_duplicates()\n            collisions = mapping_update.index.difference(self._map.index)\n            salt += 1",
    "docstring": "Adds the new keys to the mapping.\n\n        Parameters\n        ----------\n        new_keys :\n            The new index to hash."
  },
  {
    "code": "def generate(self, overwrite=False):\n        super(Upstart, self).generate(overwrite=overwrite)\n        svc_file_template = self.template_prefix + '.conf'\n        self.svc_file_path = self.generate_into_prefix + '.conf'\n        self.generate_file_from_template(svc_file_template, self.svc_file_path)\n        return self.files",
    "docstring": "Generate a config file for an upstart service."
  },
  {
    "code": "def _example_short_number(region_code):\n    metadata = PhoneMetadata.short_metadata_for_region(region_code)\n    if metadata is None:\n        return U_EMPTY_STRING\n    desc = metadata.short_code\n    if desc.example_number is not None:\n        return desc.example_number\n    return U_EMPTY_STRING",
    "docstring": "Gets a valid short number for the specified region.\n\n    Arguments:\n    region_code -- the region for which an example short number is needed.\n\n    Returns a valid short number for the specified region. Returns an empty\n    string when the metadata does not contain such information."
  },
  {
    "code": "def get_final_path(path):\n\tr\n\tdesired_access = api.NULL\n\tshare_mode = (\n\t\tapi.FILE_SHARE_READ | api.FILE_SHARE_WRITE | api.FILE_SHARE_DELETE\n\t)\n\tsecurity_attributes = api.LPSECURITY_ATTRIBUTES()\n\thFile = api.CreateFile(\n\t\tpath,\n\t\tdesired_access,\n\t\tshare_mode,\n\t\tsecurity_attributes,\n\t\tapi.OPEN_EXISTING,\n\t\tapi.FILE_FLAG_BACKUP_SEMANTICS,\n\t\tapi.NULL,\n\t)\n\tif hFile == api.INVALID_HANDLE_VALUE:\n\t\traise WindowsError()\n\tbuf_size = api.GetFinalPathNameByHandle(\n\t\thFile, LPWSTR(), 0, api.VOLUME_NAME_DOS)\n\thandle_nonzero_success(buf_size)\n\tbuf = create_unicode_buffer(buf_size)\n\tresult_length = api.GetFinalPathNameByHandle(\n\t\thFile, buf, len(buf), api.VOLUME_NAME_DOS)\n\tassert result_length < len(buf)\n\thandle_nonzero_success(result_length)\n\thandle_nonzero_success(api.CloseHandle(hFile))\n\treturn buf[:result_length]",
    "docstring": "r\"\"\"\n\tFor a given path, determine the ultimate location of that path.\n\tUseful for resolving symlink targets.\n\tThis functions wraps the GetFinalPathNameByHandle from the Windows\n\tSDK.\n\n\tNote, this function fails if a handle cannot be obtained (such as\n\tfor C:\\Pagefile.sys on a stock windows system). Consider using\n\ttrace_symlink_target instead."
  },
  {
    "code": "def dump(self):\n    return json.dumps(\n        self.primitive,\n        sort_keys=True,\n        ensure_ascii=False,\n        separators=(',', ':'))",
    "docstring": "Item as a JSON representation."
  },
  {
    "code": "def delete(self, template_name):\n        template = db.Template.find_one(template_name=template_name)\n        if not template:\n            return self.make_response('No such template found', HTTP.NOT_FOUND)\n        db.session.delete(template)\n        db.session.commit()\n        auditlog(event='template.delete', actor=session['user'].username, data={'template_name': template_name})\n        return self.make_response({\n            'message': 'Template has been deleted',\n            'templateName': template_name\n        })",
    "docstring": "Delete a template"
  },
  {
    "code": "def pi (self, data):\n        data = data.encode(self.encoding, \"ignore\")\n        self.fd.write(\"<?%s?>\" % data)",
    "docstring": "Print HTML pi.\n\n        @param data: the tag data\n        @type data: string\n        @return: None"
  },
  {
    "code": "def _get_animation_frames(self, all_datasets, shape, fill_value=None,\n                              ignore_missing=False):\n        for idx, ds in enumerate(all_datasets):\n            if ds is None and ignore_missing:\n                continue\n            elif ds is None:\n                log.debug(\"Missing frame: %d\", idx)\n                data = da.zeros(shape, dtype=np.uint8, chunks=shape)\n                data = xr.DataArray(data)\n            else:\n                img = get_enhanced_image(ds)\n                data, mode = img.finalize(fill_value=fill_value)\n                if data.ndim == 3:\n                    data = data.transpose('y', 'x', 'bands')\n            yield data.data",
    "docstring": "Create enhanced image frames to save to a file."
  },
  {
    "code": "def _emiss_ep(self, Eph):\n        if self.weight_ep == 0.0:\n            return np.zeros_like(Eph)\n        gam = np.vstack(self._gam)\n        eps = (Eph / mec2).decompose().value\n        emiss = c.cgs * trapz_loglog(\n            np.vstack(self._nelec) * self._sigma_ep(gam, eps),\n            self._gam,\n            axis=0,\n        ).to(u.cm ** 2 / Eph.unit)\n        return emiss",
    "docstring": "Electron-proton bremsstrahlung emissivity per unit photon energy"
  },
  {
    "code": "def get_from_ident(self, ident):\n        model_repr, job_pk = ident.split(':', 1)\n        klass = import_class(model_repr)\n        return klass.get(job_pk)",
    "docstring": "Take a string as returned by get_ident and return a job,\n        based on the class representation and the job's pk from the ident"
  },
  {
    "code": "def _idx_table_by_name(tables, crumbs):\n    _tables = OrderedDict()\n    try:\n        for _idx, _table in enumerate(tables):\n            _name = \"{}{}\".format(crumbs, _idx)\n            _tmp = _idx_col_by_name(_table)\n            if _name in _tables:\n                _name = \"{}_{}\".format(_name, _idx)\n            _tmp[\"tableName\"] = _name\n            _tables[_name] = _tmp\n    except Exception as e:\n        logger_jsons.error(\"idx_table_by_name: {}\".format(e))\n        print(\"Error: idx_table_by_name: {}\".format(e))\n    return _tables",
    "docstring": "Import summary, ensemble, or distribution data.\n\n    :param list tables: Metadata\n    :return dict _tables: Metadata"
  },
  {
    "code": "def avail_images(call=None):\n    all_servers = list_nodes_full()\n    templates = {}\n    for server in all_servers:\n        if server[\"IsTemplate\"]:\n            templates.update({\"Template Name\": server[\"Name\"]})\n    return templates",
    "docstring": "returns a list of images available to you"
  },
  {
    "code": "def urls(self):\n        for base_url, mapping in self.routes.items():\n            for url, _ in mapping.items():\n                yield base_url + url",
    "docstring": "Returns a generator of all URLs attached to this API"
  },
  {
    "code": "def _valid_headerline(l):\n    if not l:\n        return False\n    headers = l.split('\\t')\n    first_col = headers[0]\n    tsplit = first_col.split(':')\n    if len(tsplit) != 2:\n        return False\n    if tsplit[0] in ('entity', 'update'):\n        return tsplit[1] in ('participant_id', 'participant_set_id',\n                             'sample_id', 'sample_set_id',\n                             'pair_id', 'pair_set_id')\n    elif tsplit[0] == 'membership':\n        if len(headers) < 2:\n            return False\n        return tsplit[1].replace('set_', '') == headers[1]\n    else:\n        return False",
    "docstring": "return true if the given string is a valid loadfile header"
  },
  {
    "code": "def remove_interface_router(self, router, body=None):\n        return self.put((self.router_path % router) +\n                        \"/remove_router_interface\", body=body)",
    "docstring": "Removes an internal network interface from the specified router."
  },
  {
    "code": "def scan_on_disk(node, env, path=()):\n    try:\n        flist = node.fs.listdir(node.get_abspath())\n    except (IOError, OSError):\n        return []\n    e = node.Entry\n    for f in  filter(do_not_scan, flist):\n        e('./' + f)\n    return scan_in_memory(node, env, path)",
    "docstring": "Scans a directory for on-disk files and directories therein.\n\n    Looking up the entries will add these to the in-memory Node tree\n    representation of the file system, so all we have to do is just\n    that and then call the in-memory scanning function."
  },
  {
    "code": "def add_sidebar(self, component: Component) -> None:\n        if not self.sidebar:\n            raise NoSidebarError('Set `sidebar=True` if you want to use the sidebar.')\n        if not isinstance(component, Component):\n            raise ValueError('component must be Component type, found {}'.format(component))\n        self._controllers.append(component)",
    "docstring": "Add a widget to the sidebar.\n\n        Parameters\n        ----------\n        component : bowtie._Component\n            Add this component to the sidebar, it will be appended to the end."
  },
  {
    "code": "def network_get(auth=None, **kwargs):\n    cloud = get_operator_cloud(auth)\n    kwargs = _clean_kwargs(**kwargs)\n    return cloud.get_network(**kwargs)",
    "docstring": "Get a single network\n\n    filters\n        A Python dictionary of filter conditions to push down\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' neutronng.network_get name=XLB4"
  },
  {
    "code": "def notes(self):\n        return tuple(self._get_note_data(note) for note in self.root.iter('note'))",
    "docstring": "Tuple of notes.."
  },
  {
    "code": "def store_job(self):\n        try:\n            class_name = self.__class__.__name__.lower()\n        except AttributeError:\n            log.warning(\n                'Unable to determine class name',\n                exc_info_on_loglevel=logging.DEBUG\n            )\n            return True\n        try:\n            return self.opts['{0}_returns'.format(class_name)]\n        except KeyError:\n            return True",
    "docstring": "Helper that allows us to turn off storing jobs for different classes\n        that may incorporate this mixin."
  },
  {
    "code": "def size(self, key, resource_type):\n        with self._objects_queue_lock:\n            return len(self._objects_queue[key].get(resource_type, []))",
    "docstring": "Return the size of the queue for a given key and resource type.\n        If the key is not in the cache, this will raise a KeyError."
  },
  {
    "code": "def get_consumer_info(self, instance, cursor):\n        cursor.execute(self.CONSUMER_INFO_STATEMENT)\n        for queue_name, consumer_name, lag, pending_events, last_seen in cursor:\n            yield queue_name, consumer_name, {\n                'lag': lag,\n                'pending_events': pending_events,\n                'last_seen': last_seen,\n            }",
    "docstring": "Collects metrics for all consumers on the connected database."
  },
  {
    "code": "def get_request(self, model_run, run_url):\n        return ModelRunRequest(\n            model_run.identifier,\n            model_run.experiment_id,\n            run_url\n        )",
    "docstring": "Create request object to run model. Requests are handled by SCO\n        worker implementations.\n\n        Parameters\n        ----------\n        model_run : ModelRunHandle\n            Handle to model run\n        run_url : string\n            URL for model run information\n\n        Returns\n        -------\n        ModelRunRequest\n            Object representing model run request"
  },
  {
    "code": "def _skip_remove(self):\n        if \"--checklist\" not in self.extra:\n            self.msg.template(78)\n            print(\"| Insert packages to exception remove:\")\n            self.msg.template(78)\n            try:\n                self.skip = raw_input(\" > \").split()\n            except EOFError:\n                print(\"\")\n                raise SystemExit()\n        for s in self.skip:\n            if s in self.removed:\n                self.removed.remove(s)",
    "docstring": "Skip packages from remove"
  },
  {
    "code": "def ls_dir(dirname):\n    ls = os.listdir(dirname)\n    files = [p for p in ls if os.path.isfile(os.path.join(dirname, p))]\n    dirs = [p for p in ls if os.path.isdir(os.path.join(dirname, p))]\n    return files, dirs",
    "docstring": "Returns files and subdirectories within a given directory.\n\n    Returns a pair of lists, containing the names of directories and files\n    in ``dirname``.\n\n    Raises\n    ------\n    OSError : Accessing the given directory path failed\n\n    Parameters\n    ----------\n    dirname : str\n        The path of the directory to be listed"
  },
  {
    "code": "def list_ape (archive, compression, cmd, verbosity, interactive):\n    return stripext(cmd, archive, verbosity, extension=\".wav\")",
    "docstring": "List an APE archive."
  },
  {
    "code": "def enable_global_annotations_decorator(flag = True, retrospective = True):\n    global global_annotations_decorator\n    global_annotations_decorator = flag\n    if import_hook_enabled:\n        _install_import_hook()\n    if global_annotations_decorator and retrospective:\n        _catch_up_global_annotations_decorator()\n    return global_annotations_decorator",
    "docstring": "Enables or disables global annotation mode via decorators.\n    See flag global_annotations_decorator.\n    In contrast to setting the flag directly, this function provides\n    a retrospective option. If retrospective is true, this will also\n    affect already imported modules, not only future imports."
  },
  {
    "code": "def _normalize(self):\n        \"Normalize basis function. From THO eq. 2.2\"\n        l,m,n = self.powers\n        self.norm = np.sqrt(pow(2,2*(l+m+n)+1.5)*\n                            pow(self.exponent,l+m+n+1.5)/\n                            fact2(2*l-1)/fact2(2*m-1)/\n                            fact2(2*n-1)/pow(np.pi,1.5))\n        return",
    "docstring": "Normalize basis function. From THO eq. 2.2"
  },
  {
    "code": "def copy(self, props=None, value=None):\n        return Overlay(self.text,\n                       (self.start, self.end),\n                       props=props or self.props,\n                       value=value or self.value)",
    "docstring": "Copy the Overlay possibly overriding props."
  },
  {
    "code": "def latitude(self, dms: bool = False) -> Union[str, float]:\n        return self._get_fs('lt', dms)",
    "docstring": "Generate a random value of latitude.\n\n        :param dms: DMS format.\n        :return: Value of longitude."
  },
  {
    "code": "def _get_site(self):\n        import mwclient\n        parts = self.server.settings.wiki.replace(\"http\", \"\").replace(\"://\", \"\").split(\"/\")\n        self.url = parts[0]\n        if len(parts) > 1 and parts[1].strip() != \"\":\n            self.relpath = '/' + '/'.join(parts[1:len(parts)])\n            if self.relpath[-1] != \"/\":\n                self.relpath += \"/\"\n            if not self.testmode:\n                self.site = mwclient.Site(self.url, path=self.relpath)\n        else:\n            if not self.testmode:\n                self.site = mwclient.Site(self.url)",
    "docstring": "Returns the mwclient.Site for accessing and editing the wiki pages."
  },
  {
    "code": "def _bind_variables(self, instance, space):\n        instance.api = self\n        if space:\n            instance.space = space\n        return instance",
    "docstring": "Bind related variables to the instance"
  },
  {
    "code": "def is_in_bounds(self, x):\n        if self.bounds is None:\n            return True\n        for ib in [0, 1]:\n            if self.bounds[ib] is None:\n                continue\n            for i in rglen(x):\n                idx = min([i, len(self.bounds[ib]) - 1])\n                if self.bounds[ib][idx] is not None and \\\n                        (-1)**ib * x[i] < (-1)**ib * self.bounds[ib][idx]:\n                    return False\n        return True",
    "docstring": "not yet tested"
  },
  {
    "code": "def with_img_type_and_preset(self, image_type, preset):\n        assert isinstance(image_type, ImageType)\n        assert isinstance(preset, str)\n        return list(filter(lambda x: x.image_type == image_type and x.preset == preset, self.metaimages))",
    "docstring": "Returns the search results having both the specified image type and preset\n\n        :param image_type: the desired image type (valid values are provided by the\n            `pyowm.commons.enums.ImageTypeEnum` enum)\n        :type image_type: `pyowm.commons.databoxes.ImageType` instance\n        :param preset: the desired image preset (valid values are provided by the\n            `pyowm.agroapi10.enums.PresetEnum` enum)\n        :type preset: str\n        :returns: a list of `pyowm.agroapi10.imagery.MetaImage` instances"
  },
  {
    "code": "def insert_runner(fun, args=None, kwargs=None, queue=None, backend=None):\n    if args is None:\n        args = []\n    elif isinstance(args, six.string_types):\n        args = args.split(',')\n    if kwargs is None:\n        kwargs = {}\n    queue_kwargs = __get_queue_opts(queue=queue, backend=backend)\n    data = {'fun': fun, 'args': args, 'kwargs': kwargs}\n    return insert(items=data, **queue_kwargs)",
    "docstring": "Insert a reference to a runner into the queue so that it can be run later.\n\n    fun\n        The runner function that is going to be run\n\n    args\n        list or comma-seperated string of args to send to fun\n\n    kwargs\n        dictionary of keyword arguments to send to fun\n\n    queue\n        queue to insert the runner reference into\n\n    backend\n        backend that to use for the queue\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-run queue.insert_runner test.stdout_print\n        salt-run queue.insert_runner event.send test_insert_runner kwargs='{\"data\": {\"foo\": \"bar\"}}'"
  },
  {
    "code": "def _isFollowedByComma( wordID, clauseTokens ):\r\n    koma = WordTemplate({ROOT:'^,+$', POSTAG:'Z'})\r\n    for i in range(len(clauseTokens)):\r\n        token = clauseTokens[i]\r\n        if token[WORD_ID] == wordID:\r\n            if re.match('^.*,$', token[TEXT]):\r\n                return True\r\n            elif i+1 < len(clauseTokens) and koma.matches(clauseTokens[i+1]):\r\n                return True\r\n            break\r\n    return False",
    "docstring": "Teeb kindlaks, kas etteantud ID-ga s6nale j2rgneb vahetult koma;\r\n        Tagastab True, kui eeltoodud tingimus on t2idetud, vastasel juhul False;"
  },
  {
    "code": "def workflow_script_cancel(self):\n        if skip(self, \"cancel\"):\n            return\n        self.reindexObject(idxs=[\"is_active\", ])\n        analysis_requests = self.getAnalysisRequests()\n        for ar in analysis_requests:\n            ar_obj = ar.getObject()\n            workflow = getToolByName(self, 'portal_workflow')\n            if workflow.getInfoFor(ar_obj, 'review_state') != 'cancelled':\n                doActionFor(ar.getObject(), 'cancel')",
    "docstring": "When the round is cancelled, all its associated Samples and ARs are cancelled by the system."
  },
  {
    "code": "def initialize_constraint_table(cfg_list):\n    for cfg in cfg_list:\n        constraint_table.update(dict.fromkeys(cfg.nodes, 0))",
    "docstring": "Collects all given cfg nodes and initializes the table with value 0."
  },
  {
    "code": "def disconnect(self):\n        self.log(\"Disconnecting broker %r.\", self)\n        d = defer.succeed(None)\n        if self.is_master():\n            if self.listener is not None:\n                d.addCallback(defer.drop_param, self.listener.stopListening)\n                d.addCallback(defer.drop_param, self.factory.disconnect)\n        elif self.is_slave():\n            d = defer.maybeDeferred(self.factory.disconnect)\n        elif self._cmp_state(BrokerRole.disconnected):\n            return defer.succeed(None)\n        d.addCallback(defer.drop_param, self.become_disconnected)\n        return d",
    "docstring": "This is called as part of the agency shutdown."
  },
  {
    "code": "def parse(link):\n    html = get_html(link)\n    data = {'rating': get_rating(html),\n            'name': get_name_date(html)[0]}\n    div = html.find(id=\"title-episode-widget\")\n    season_tags = get_a(div, find=\"season=\")\n    episodes = {}\n    for slink in season_tags:\n        for e in episode_list(slink):\n            season, d = parse_episode(e)\n            if season in episodes:\n                episodes[season].append(d)\n            else:\n                episodes[season] = [d]\n    data['episodes'] = episodes\n    return data",
    "docstring": "Parses a Tv Series\n    returns the dataset as a dictionary"
  },
  {
    "code": "def get_profile(self, user_id, timeout=None):\n        response = self._get(\n            '/v2/bot/profile/{user_id}'.format(user_id=user_id),\n            timeout=timeout\n        )\n        return Profile.new_from_json_dict(response.json)",
    "docstring": "Call get profile API.\n\n        https://devdocs.line.me/en/#bot-api-get-profile\n\n        Get user profile information.\n\n        :param str user_id: User ID\n        :param timeout: (optional) How long to wait for the server\n            to send data before giving up, as a float,\n            or a (connect timeout, read timeout) float tuple.\n            Default is self.http_client.timeout\n        :type timeout: float | tuple(float, float)\n        :rtype: :py:class:`linebot.models.responses.Profile`\n        :return: Profile instance"
  },
  {
    "code": "def register_mapper(self, mapper, content_type, shortname=None):\n        self._check_mapper(mapper)\n        cont_type_names = self._get_content_type_names(content_type, shortname)\n        self._datamappers.update(dict([(name, mapper) for name in cont_type_names]))",
    "docstring": "Register new mapper.\n\n        :param mapper: mapper object needs to implement ``parse()`` and\n        ``format()`` functions."
  },
  {
    "code": "def readTraining(self, training_file):\n        logger.info('reading training from file')\n        training_pairs = json.load(training_file,\n                                   cls=serializer.dedupe_decoder)\n        self.markPairs(training_pairs)",
    "docstring": "Read training from previously built training data file object\n\n        Arguments:\n\n        training_file -- file object containing the training data"
  },
  {
    "code": "def _cleanup(self):\n        if self.todolist.exists():\n            try:\n                saved_todo = iter(open(self.todolist, encoding=\"utf-8\"))\n                int(next(saved_todo).strip())\n                for line in saved_todo:\n                    _, serial = line.strip().split()\n                    int(serial)\n            except (StopIteration, ValueError):\n                logger.info(\"Removing inconsistent todo list.\")\n                self.todolist.unlink()",
    "docstring": "Does a couple of cleanup tasks to ensure consistent data for later\n        processing."
  },
  {
    "code": "def status(self):\n        status_request = etcdrpc.StatusRequest()\n        status_response = self.maintenancestub.Status(\n            status_request,\n            self.timeout,\n            credentials=self.call_credentials,\n            metadata=self.metadata\n        )\n        for m in self.members:\n            if m.id == status_response.leader:\n                leader = m\n                break\n        else:\n            leader = None\n        return Status(status_response.version,\n                      status_response.dbSize,\n                      leader,\n                      status_response.raftIndex,\n                      status_response.raftTerm)",
    "docstring": "Get the status of the responding member."
  },
  {
    "code": "def count_partitions(self, topic):\n        return sum(1 for p in topic.partitions if p in self.partitions)",
    "docstring": "Return count of partitions for given topic."
  },
  {
    "code": "def is_promisc(ip, fake_bcast=\"ff:ff:00:00:00:00\", **kargs):\n    responses = srp1(Ether(dst=fake_bcast) / ARP(op=\"who-has\", pdst=ip), type=ETH_P_ARP, iface_hint=ip, timeout=1, verbose=0, **kargs)\n    return responses is not None",
    "docstring": "Try to guess if target is in Promisc mode. The target is provided by its ip."
  },
  {
    "code": "def set_mt_wcs(self, image):\n        for chip in range(1,self._numchips+1,1):\n            sci_chip = self._image[self.scienceExt,chip]\n            ref_chip = image._image[image.scienceExt,chip]\n            sci_chip.wcs = ref_chip.wcs.copy()",
    "docstring": "Reset the WCS for this image based on the WCS information from\n            another imageObject."
  },
  {
    "code": "def interact(banner=None, readfunc=None, local=None):\n    console = InteractiveConsole(local)\n    if readfunc is not None:\n        console.raw_input = readfunc\n    else:\n        try:\n            import readline\n        except ImportError:\n            pass\n    console.interact(banner)",
    "docstring": "Closely emulate the interactive Python interpreter.\n\n    This is a backwards compatible interface to the InteractiveConsole\n    class.  When readfunc is not specified, it attempts to import the\n    readline module to enable GNU readline if it is available.\n\n    Arguments (all optional, all default to None):\n\n    banner -- passed to InteractiveConsole.interact()\n    readfunc -- if not None, replaces InteractiveConsole.raw_input()\n    local -- passed to InteractiveInterpreter.__init__()"
  },
  {
    "code": "def canCommit(self, prepare: Prepare) -> (bool, str):\n        quorum = self.quorums.prepare.value\n        if not self.prepares.hasQuorum(prepare, quorum):\n            return False, 'does not have prepare quorum for {}'.format(prepare)\n        if self.hasCommitted(prepare):\n            return False, 'has already sent COMMIT for {}'.format(prepare)\n        return True, ''",
    "docstring": "Return whether the specified PREPARE can proceed to the Commit\n        step.\n\n        Decision criteria:\n\n        - If this replica has got just n-f-1 PREPARE requests then commit request.\n        - If less than n-f-1 PREPARE requests then probably there's no consensus on\n            the request; don't commit\n        - If more than n-f-1 then already sent COMMIT; don't commit\n\n        :param prepare: the PREPARE"
  },
  {
    "code": "def close(self):\n        try:\n            self.connection.close()\n            self.connection = None\n        except Exception:\n            if not self.fail_silently:\n                raise",
    "docstring": "Close any open HTTP connections to the API server."
  },
  {
    "code": "def stub():\n    form = cgi.FieldStorage()\n    userid = form['userid'].value\n    password = form['passwd'].value\n    group = form['group'].value",
    "docstring": "Just some left over code"
  },
  {
    "code": "def updateRPYLocations(self):\n        self.rollText.set_position((self.leftPos+(self.vertSize/10.0),-0.97+(2*self.vertSize)-(self.vertSize/10.0)))\n        self.pitchText.set_position((self.leftPos+(self.vertSize/10.0),-0.97+self.vertSize-(0.5*self.vertSize/10.0)))\n        self.yawText.set_position((self.leftPos+(self.vertSize/10.0),-0.97))\n        self.rollText.set_size(self.fontSize)\n        self.pitchText.set_size(self.fontSize)\n        self.yawText.set_size(self.fontSize)",
    "docstring": "Update the locations of roll, pitch, yaw text."
  },
  {
    "code": "def _total_rectangles(tree):\n    return sum(len(sec.children) + sec.points.shape[0] - 1\n               for sec in tree.iter_sections())",
    "docstring": "Calculate the total number of segments that are required\n    for the dendrogram. There is a vertical line for each segment\n    and two horizontal line at each branching point"
  },
  {
    "code": "def returner(ret):\n    _options = _get_options(ret)\n    from_jid = _options.get('from_jid')\n    password = _options.get('password')\n    recipient_jid = _options.get('recipient_jid')\n    if not from_jid:\n        log.error('xmpp.jid not defined in salt config')\n        return\n    if not password:\n        log.error('xmpp.password not defined in salt config')\n        return\n    if not recipient_jid:\n        log.error('xmpp.recipient not defined in salt config')\n        return\n    message = ('id: {0}\\r\\n'\n               'function: {1}\\r\\n'\n               'function args: {2}\\r\\n'\n               'jid: {3}\\r\\n'\n               'return: {4}\\r\\n').format(\n                    ret.get('id'),\n                    ret.get('fun'),\n                    ret.get('fun_args'),\n                    ret.get('jid'),\n                    pprint.pformat(ret.get('return')))\n    xmpp = SendMsgBot(from_jid, password, recipient_jid, message)\n    xmpp.register_plugin('xep_0030')\n    xmpp.register_plugin('xep_0199')\n    if xmpp.connect():\n        xmpp.process(block=True)\n        return True\n    return False",
    "docstring": "Send an xmpp message with the data"
  },
  {
    "code": "def rooms_info(self, room_id=None, room_name=None):\n        if room_id is not None:\n            return self.__call_api_get('rooms.info', roomId=room_id)\n        elif room_name is not None:\n            return self.__call_api_get('rooms.info', roomName=room_name)\n        else:\n            raise RocketMissingParamException('roomId or roomName required')",
    "docstring": "Retrieves the information about the room."
  },
  {
    "code": "def get_install_names(filename):\n    lines = _cmd_out_err(['otool', '-L', filename])\n    if not _line0_says_object(lines[0], filename):\n        return ()\n    names = tuple(parse_install_name(line)[0] for line in lines[1:])\n    install_id = get_install_id(filename)\n    if not install_id is None:\n        assert names[0] == install_id\n        return names[1:]\n    return names",
    "docstring": "Return install names from library named in `filename`\n\n    Returns tuple of install names\n\n    tuple will be empty if no install names, or if this is not an object file.\n\n    Parameters\n    ----------\n    filename : str\n        filename of library\n\n    Returns\n    -------\n    install_names : tuple\n        tuple of install names for library `filename`"
  },
  {
    "code": "def _compute_all_files(self):\n        self._all_files = any(pat.all_files() for pat in self.patterns)",
    "docstring": "Handles lazy evaluation of self.all_files"
  },
  {
    "code": "def eof_received(self) -> bool:\n        logger.debug(\"%s - event = eof_received()\", self.side)\n        super().eof_received()\n        return False",
    "docstring": "Close the transport after receiving EOF.\n\n        Since Python 3.5, `:meth:~StreamReaderProtocol.eof_received` returns\n        ``True`` on non-TLS connections.\n\n        See http://bugs.python.org/issue24539 for more information.\n\n        This is inappropriate for websockets for at least three reasons:\n\n        1. The use case is to read data until EOF with self.reader.read(-1).\n           Since websockets is a TLV protocol, this never happens.\n\n        2. It doesn't work on TLS connections. A falsy value must be\n           returned to have the same behavior on TLS and plain connections.\n\n        3. The websockets protocol has its own closing handshake. Endpoints\n           close the TCP connection after sending a close frame.\n\n        As a consequence we revert to the previous, more useful behavior."
  },
  {
    "code": "def get_rendition_url(self, width=0, height=0):\n        if width == 0 and height == 0:\n            return self.get_master_url()\n        target_width, target_height = self.get_rendition_size(width, height)\n        key = '%sx%s' % (target_width, target_height)\n        if not self.renditions:\n            self.renditions = {}\n        rendition_name = self.renditions.get(key, False)\n        if not rendition_name:\n            rendition_name = self.make_rendition(target_width, target_height)\n        return default_storage.url(rendition_name)",
    "docstring": "get the rendition URL for a specified size\n\n        if the renditions does not exists it will be created"
  },
  {
    "code": "def rl_get_point() -> int:\n    if rl_type == RlType.GNU:\n        return ctypes.c_int.in_dll(readline_lib, \"rl_point\").value\n    elif rl_type == RlType.PYREADLINE:\n        return readline.rl.mode.l_buffer.point\n    else:\n        return 0",
    "docstring": "Returns the offset of the current cursor position in rl_line_buffer"
  },
  {
    "code": "def validate(self, value):\n        if value is None:\n            if self.required:\n                raise ValidationError('{} - None values are not allowed'.format(self.column_name or self.db_field))\n        return value",
    "docstring": "Returns a cleaned and validated value. Raises a ValidationError\n        if there's a problem"
  },
  {
    "code": "def dump(self):\n        results = []\n        for data in self.data():\n            results.append(data)\n        return results",
    "docstring": "Dump raw JSON output of matching queryset objects.\n\n        Returns:\n            List of dicts."
  },
  {
    "code": "def raise_not_found(self, environ, msg):\n        raise NotFound(response=self.rewriterapp._error_response(environ, msg))",
    "docstring": "Utility function for raising a werkzeug.exceptions.NotFound execption with the supplied WSGI environment\n        and message.\n\n        :param dict environ: The WSGI environment dictionary for the request\n        :param str msg: The error message"
  },
  {
    "code": "def _convert_units(obj, desired, guess=False):\n    if obj.units is None:\n        obj.units = units_from_metadata(obj, guess=guess)\n    log.info('converting units from %s to %s', obj.units, desired)\n    conversion = unit_conversion(obj.units, desired)\n    obj.apply_scale(conversion)\n    obj.units = desired",
    "docstring": "Given an object with scale and units try to scale\n    to different units via the object's `apply_scale`.\n\n    Parameters\n    ---------\n    obj :  object\n        With apply_scale method (i.e. Trimesh, Path2D, etc)\n    desired : str\n        Units desired (eg 'inches')\n    guess:   bool\n        Whether we are allowed to guess the units\n        if they are not specified."
  },
  {
    "code": "def nsmap(self):\n        NSMAP = dict()\n        for k, v in set(self.namespaces):\n            s_prefix = self.sb[k]\n            s_uri = self.sb[v]\n            if s_uri != \"\" and s_prefix != \"\":\n                NSMAP[s_prefix] = s_uri\n        return NSMAP",
    "docstring": "Returns the current namespace mapping as a dictionary\n\n        there are several problems with the map and we try to guess a few\n        things here:\n\n        1) a URI can be mapped by many prefixes, so it is to decide which one to take\n        2) a prefix might map to an empty string (some packers)\n        3) uri+prefix mappings might be included several times\n        4) prefix might be empty"
  },
  {
    "code": "def get_correlated_reports_page(self, indicators, enclave_ids=None, is_enclave=True,\n                                    page_size=None, page_number=None):\n        if is_enclave:\n            distribution_type = DistributionType.ENCLAVE\n        else:\n            distribution_type = DistributionType.COMMUNITY\n        params = {\n            'indicators': indicators,\n            'enclaveIds': enclave_ids,\n            'distributionType': distribution_type,\n            'pageNumber': page_number,\n            'pageSize': page_size\n        }\n        resp = self._client.get(\"reports/correlated\", params=params)\n        return Page.from_dict(resp.json(), content_type=Report)",
    "docstring": "Retrieves a page of all TruSTAR reports that contain the searched indicators.\n\n        :param indicators: A list of indicator values to retrieve correlated reports for.\n        :param enclave_ids: The enclaves to search in.\n        :param is_enclave: Whether to search enclave reports or community reports.\n        :param int page_number: the page number to get.\n        :param int page_size: the size of the page to be returned.\n        :return: The list of IDs of reports that correlated.\n\n        Example:\n\n        >>> reports = ts.get_correlated_reports_page([\"wannacry\", \"www.evil.com\"]).items\n        >>> print([report.id for report in reports])\n        [\"e3bc6921-e2c8-42eb-829e-eea8da2d3f36\", \"4d04804f-ff82-4a0b-8586-c42aef2f6f73\"]"
  },
  {
    "code": "def ncores_used(self):\n        return sum(task.manager.num_cores for task in self if task.status == task.S_RUN)",
    "docstring": "Returns the number of cores used in this moment.\n        A core is used if there's a job that is running on it."
  },
  {
    "code": "def convert_http_request(request, referrer_host=None):\n    new_request = urllib.request.Request(\n        request.url_info.url,\n        origin_req_host=referrer_host,\n    )\n    for name, value in request.fields.get_all():\n        new_request.add_header(name, value)\n    return new_request",
    "docstring": "Convert a HTTP request.\n\n    Args:\n        request: An instance of :class:`.http.request.Request`.\n        referrer_host (str): The referrering hostname or IP address.\n\n    Returns:\n        Request: An instance of :class:`urllib.request.Request`"
  },
  {
    "code": "def param_fetch_one(self, name):\n        try:\n            idx = int(name)\n            self.mav.param_request_read_send(self.target_system, self.target_component, \"\", idx)\n        except Exception:\n            self.mav.param_request_read_send(self.target_system, self.target_component, name, -1)",
    "docstring": "initiate fetch of one parameter"
  },
  {
    "code": "def interfacesFor(self, powerup):\n        pc = _PowerupConnector\n        for iface in self.store.query(pc,\n                                      AND(pc.item == self,\n                                          pc.powerup == powerup)).getColumn('interface'):\n            yield namedAny(iface)",
    "docstring": "Return an iterator of the interfaces for which the given powerup is\n        installed on this object.\n\n        This is not implemented for in-memory powerups.  It will probably fail\n        in an unpredictable, implementation-dependent way if used on one."
  },
  {
    "code": "def capture_moves(self, position):\n        try:\n            right_diagonal = self.square_in_front(self.location.shift_right())\n            for move in self._one_diagonal_capture_square(right_diagonal, position):\n                yield move\n        except IndexError:\n            pass\n        try:\n            left_diagonal = self.square_in_front(self.location.shift_left())\n            for move in self._one_diagonal_capture_square(left_diagonal, position):\n                yield move\n        except IndexError:\n            pass",
    "docstring": "Finds out all possible capture moves\n\n        :rtype: list"
  },
  {
    "code": "def bind_license(self, license_item_id=None):\n        params = {'license_item_id': license_item_id}\n        self.make_request(\n            LicenseError,\n            method='create',\n            resource='bind',\n            params=params)",
    "docstring": "Auto bind license, uses dynamic if POS is not found\n\n        :param str license_item_id: license id\n        :raises LicenseError: binding license failed, possibly no licenses\n        :return: None"
  },
  {
    "code": "def _collect_peers_of_interest(self, new_best_path):\n        path_rts = new_best_path.get_rts()\n        qualified_peers = set(self._peers.values())\n        qualified_peers = self._rt_manager.filter_by_origin_as(\n            new_best_path, qualified_peers\n        )\n        if path_rts:\n            path_rts.append(RouteTargetMembershipNLRI.DEFAULT_RT)\n            qualified_peers = set(self._get_non_rtc_peers())\n            peer_to_rtfilter_map = self._peer_to_rtfilter_map\n            for peer, rt_filter in peer_to_rtfilter_map.items():\n                if peer is None:\n                    continue\n                if rt_filter is None:\n                    qualified_peers.add(peer)\n                elif rt_filter.intersection(path_rts):\n                    qualified_peers.add(peer)\n        return qualified_peers",
    "docstring": "Collect all peers that qualify for sharing a path with given RTs."
  },
  {
    "code": "def layer_norm_compute(x, epsilon, scale, bias, layer_collection=None):\n  params = (scale, bias)\n  epsilon, scale, bias = [cast_like(t, x) for t in [epsilon, scale, bias]]\n  mean = tf.reduce_mean(x, axis=[-1], keepdims=True)\n  variance = tf.reduce_mean(\n      tf.squared_difference(x, mean), axis=[-1], keepdims=True)\n  norm_x = (x - mean) * tf.rsqrt(variance + epsilon)\n  output = norm_x * scale + bias\n  return output",
    "docstring": "Layer norm raw computation."
  },
  {
    "code": "def disable_pow_check(chain_class: Type[BaseChain]) -> Type[BaseChain]:\n    if not chain_class.vm_configuration:\n        raise ValidationError(\"Chain class has no vm_configuration\")\n    if issubclass(chain_class, NoChainSealValidationMixin):\n        chain_class_without_seal_validation = chain_class\n    else:\n        chain_class_without_seal_validation = type(\n            chain_class.__name__,\n            (chain_class, NoChainSealValidationMixin),\n            {},\n        )\n    return chain_class_without_seal_validation.configure(\n        vm_configuration=_mix_in_disable_seal_validation(\n            chain_class_without_seal_validation.vm_configuration\n        ),\n    )",
    "docstring": "Disable the proof of work validation check for each of the chain's vms.\n    This allows for block mining without generation of the proof of work seal.\n\n    .. note::\n\n        blocks mined this way will not be importable on any chain that does not\n        have proof of work disabled."
  },
  {
    "code": "def plot(self):\n\t\tpl.plot(self.x, self.y, '.')\n\t\tpl.plot(self.x_int, self.y_int)\n\t\tpl.grid(True)\n\t\tpl.show()",
    "docstring": "Plot the individual and the gene"
  },
  {
    "code": "def _set_folium_map(self):\n        m = Map(features=[self], width=self._width, height=self._height)\n        self._folium_map = m.draw()",
    "docstring": "A map containing only the feature."
  },
  {
    "code": "def _from_java(cls, java_stage):\n        featuresCol = java_stage.getFeaturesCol()\n        labelCol = java_stage.getLabelCol()\n        predictionCol = java_stage.getPredictionCol()\n        classifier = JavaParams._from_java(java_stage.getClassifier())\n        models = [JavaParams._from_java(model) for model in java_stage.models()]\n        py_stage = cls(models=models).setPredictionCol(predictionCol).setLabelCol(labelCol)\\\n            .setFeaturesCol(featuresCol).setClassifier(classifier)\n        py_stage._resetUid(java_stage.uid())\n        return py_stage",
    "docstring": "Given a Java OneVsRestModel, create and return a Python wrapper of it.\n        Used for ML persistence."
  },
  {
    "code": "def _decode_telegram_base64(string):\n    try:\n        return base64.urlsafe_b64decode(string + '=' * (len(string) % 4))\n    except (binascii.Error, ValueError, TypeError):\n        return None",
    "docstring": "Decodes an url-safe base64-encoded string into its bytes\n    by first adding the stripped necessary padding characters.\n\n    This is the way Telegram shares binary data as strings,\n    such as Bot API-style file IDs or invite links.\n\n    Returns ``None`` if the input string was not valid."
  },
  {
    "code": "def dens_alum_nanocluster(coag):\n    density = (coag.PrecipDensity * MOLEC_WEIGHT_ALUMINUM\n               * coag.PrecipAluminumMPM / coag.PrecipMolecWeight)\n    return density",
    "docstring": "Return the density of the aluminum in the nanocluster.\n\n    This is useful for determining the volume of nanoclusters\n    given a concentration of aluminum."
  },
  {
    "code": "def clear_expired_cookies(self):\n        self._cookies_lock.acquire()\n        try:\n            now = time.time()\n            for cookie in self:\n                if cookie.is_expired(now):\n                    self.clear(cookie.domain, cookie.path, cookie.name)\n        finally:\n            self._cookies_lock.release()",
    "docstring": "Discard all expired cookies.\n\n        You probably don't need to call this method: expired cookies are never\n        sent back to the server (provided you're using DefaultCookiePolicy),\n        this method is called by CookieJar itself every so often, and the\n        .save() method won't save expired cookies anyway (unless you ask\n        otherwise by passing a true ignore_expires argument)."
  },
  {
    "code": "def has_key(self, key):\n        if key in self._dict:\n            try: \n                self[key]\n                return True\n            except ValueError:\n                return False\n            except KeyError:\n                return False\n        return False",
    "docstring": "Does the key exist?\n        This method will check to see if it has expired too."
  },
  {
    "code": "def cancel(self) :\n        \"tells libdbus you no longer care about the pending incoming message.\"\n        dbus.dbus_pending_call_cancel(self._dbobj)\n        if self._awaiting != None :\n            self._awaiting.cancel()",
    "docstring": "tells libdbus you no longer care about the pending incoming message."
  },
  {
    "code": "def build_git_url(self):\n        if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None):\n            return self.dutinformation.get(0).build.giturl\n        return None",
    "docstring": "get build git url.\n\n        :return: build git url or None if not found"
  },
  {
    "code": "def to_json(self):\n        result = super(UIExtension, self).to_json()\n        result.update({\n            'extension': self.extension\n        })\n        return result",
    "docstring": "Returns the JSON Representation of the UI extension."
  },
  {
    "code": "def md5sum(fname, block_size=1048576):\n    md5 = hashlib.md5()\n    with open(fname, 'rb') as fid:\n        while True:\n            data = fid.read(block_size)\n            if not data:\n                break\n            md5.update(data)\n    return md5.hexdigest()",
    "docstring": "Calculate the md5sum for a file.\n\n    Parameters\n    ----------\n    fname : str\n        Filename.\n    block_size : int\n        Block size to use when reading.\n\n    Returns\n    -------\n    hash_ : str\n        The hexadecimal digest of the hash."
  },
  {
    "code": "def pile(args):\n    from jcvi.utils.grouper import Grouper\n    p = OptionParser(pile.__doc__)\n    p.add_option(\"--minOverlap\", default=0, type=\"int\",\n                 help=\"Minimum overlap required [default: %default]\")\n    opts, args = p.parse_args(args)\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n    abedfile, bbedfile = args\n    iw = intersectBed_wao(abedfile, bbedfile, minOverlap=opts.minOverlap)\n    groups = Grouper()\n    for a, b in iw:\n        groups.join(a.accn, b.accn)\n    ngroups = 0\n    for group in groups:\n        if len(group) > 1:\n            ngroups += 1\n            print(\"|\".join(group))\n    logging.debug(\"A total of {0} piles (>= 2 members)\".format(ngroups))",
    "docstring": "%prog pile abedfile bbedfile > piles\n\n    Call intersectBed on two bedfiles."
  },
  {
    "code": "def write(self, obj: BioCDocument or BioCPassage or BioCSentence):\n        if self.level == DOCUMENT and not isinstance(obj, BioCDocument):\n            raise ValueError\n        if self.level == PASSAGE and not isinstance(obj, BioCPassage):\n            raise ValueError\n        if self.level == SENTENCE and not isinstance(obj, BioCSentence):\n            raise ValueError\n        self.writer.write(BioCJSONEncoder().default(obj))",
    "docstring": "Encode and write a single object.\n\n        Args:\n            obj: an instance of BioCDocument, BioCPassage, or BioCSentence\n\n        Returns:"
  },
  {
    "code": "def load_window_opener(self, item):\n        window = Window.from_config(self.pyvlx, item)\n        self.add(window)",
    "docstring": "Load window opener from JSON."
  },
  {
    "code": "def get_contact(self, msisdn):\n        response = self.session.post(\n            urllib_parse.urljoin(self.api_url, \"/v1/contacts\"),\n            json={\"blocking\": \"wait\", \"contacts\": [msisdn]},\n        )\n        response.raise_for_status()\n        whatsapp_id = response.json()[\"contacts\"][0].get(\"wa_id\")\n        if not whatsapp_id:\n            self.fire_failed_contact_lookup(msisdn)\n        return whatsapp_id",
    "docstring": "Returns the WhatsApp ID for the given MSISDN"
  },
  {
    "code": "def fetch(self, minutes=values.unset, start_date=values.unset,\n              end_date=values.unset, task_channel=values.unset):\n        return self._proxy.fetch(\n            minutes=minutes,\n            start_date=start_date,\n            end_date=end_date,\n            task_channel=task_channel,\n        )",
    "docstring": "Fetch a WorkerStatisticsInstance\n\n        :param unicode minutes: Filter cumulative statistics by up to 'x' minutes in the past.\n        :param datetime start_date: Filter cumulative statistics by a start date.\n        :param datetime end_date: Filter cumulative statistics by a end date.\n        :param unicode task_channel: Filter cumulative statistics by TaskChannel.\n\n        :returns: Fetched WorkerStatisticsInstance\n        :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsInstance"
  },
  {
    "code": "def beep(self, duration, frequency):\n        cmd = 'BEEP', [Float(min=0.1, max=5.0), Integer(min=500, max=5000)]\n        self._write(cmd, duration, frequency)",
    "docstring": "Generates a beep.\n\n        :param duration: The duration in seconds, in the range 0.1 to 5.\n        :param frequency: The frequency in Hz, in the range 500 to 5000."
  },
  {
    "code": "def _handle_signal_gracefully(cls, signum, signame, traceback_lines):\n    formatted_traceback = cls._format_traceback(traceback_lines=traceback_lines,\n                                                should_print_backtrace=True)\n    signal_error_log_entry = cls._CATCHABLE_SIGNAL_ERROR_LOG_FORMAT.format(\n      signum=signum,\n      signame=signame,\n      formatted_traceback=formatted_traceback)\n    cls.log_exception(signal_error_log_entry)\n    formatted_traceback_for_terminal = cls._format_traceback(\n      traceback_lines=traceback_lines,\n      should_print_backtrace=cls._should_print_backtrace_to_terminal)\n    terminal_log_entry = cls._CATCHABLE_SIGNAL_ERROR_LOG_FORMAT.format(\n      signum=signum,\n      signame=signame,\n      formatted_traceback=formatted_traceback_for_terminal)\n    cls._exit_with_failure(terminal_log_entry)",
    "docstring": "Signal handler for non-fatal signals which raises or logs an error and exits with failure."
  },
  {
    "code": "def _get_bucket(self, client_kwargs):\n        return _oss.Bucket(self.client, endpoint=self._endpoint,\n                           bucket_name=client_kwargs['bucket_name'])",
    "docstring": "Get bucket object.\n\n        Returns:\n            oss2.Bucket"
  },
  {
    "code": "def _hdfs_namenode_metrics(self, beans, metrics, tags):\n        bean = next(iter(beans))\n        bean_name = bean.get('name')\n        if bean_name != bean_name:\n            raise Exception(\"Unexpected bean name {}\".format(bean_name))\n        for metric, (metric_name, metric_type) in iteritems(metrics):\n            metric_value = bean.get(metric)\n            if metric_value is not None:\n                self._set_metric(metric_name, metric_type, metric_value, tags)\n        if 'CapacityUsed' in bean and 'CapacityTotal' in bean:\n            self._set_metric(\n                'hdfs.namenode.capacity_in_use',\n                self.GAUGE,\n                float(bean['CapacityUsed']) / float(bean['CapacityTotal']),\n                tags,\n            )",
    "docstring": "Get HDFS namenode metrics from JMX"
  },
  {
    "code": "def _param_toc_updated_cb(self):\n        logger.info('Param TOC finished updating')\n        self.connected_ts = datetime.datetime.now()\n        self.connected.call(self.link_uri)\n        self.param.request_update_of_all_params()",
    "docstring": "Called when the param TOC has been fully updated"
  },
  {
    "code": "def _alert_malformed(self, msg, row_num):\n        if self.error_bad_lines:\n            raise ParserError(msg)\n        elif self.warn_bad_lines:\n            base = 'Skipping line {row_num}: '.format(row_num=row_num)\n            sys.stderr.write(base + msg + '\\n')",
    "docstring": "Alert a user about a malformed row.\n\n        If `self.error_bad_lines` is True, the alert will be `ParserError`.\n        If `self.warn_bad_lines` is True, the alert will be printed out.\n\n        Parameters\n        ----------\n        msg : The error message to display.\n        row_num : The row number where the parsing error occurred.\n                  Because this row number is displayed, we 1-index,\n                  even though we 0-index internally."
  },
  {
    "code": "def login(self, came_from=lurl('/')):\n        login_counter = request.environ.get('repoze.who.logins', 0)\n        if login_counter > 0:\n            flash(_('Wrong credentials'), 'warning')\n        return dict(page='login', login_counter=str(login_counter),\n                    came_from=came_from)",
    "docstring": "Start the user login."
  },
  {
    "code": "def _calculate(self, field):\n        encloser = field.enclosing\n        if encloser:\n            rendered = encloser.get_rendered_fields(RenderContext(self))\n            if field not in rendered:\n                value = len(rendered)\n            else:\n                value = rendered.index(field)\n        else:\n            value = 0\n        return value",
    "docstring": "We want to avoid trouble, so if the field is not enclosed by any other field,\n        we just return 0."
  },
  {
    "code": "def create(self, resource):\n        uri = self.URI + self.RESOURCES_PATH\n        return self._client.create(resource=resource, uri=uri)",
    "docstring": "Set all the labels for a resource.\n\n        Args:\n            resource: The object containing the resource URI and a list of labels\n\n        Returns:\n            dict: Resource Labels"
  },
  {
    "code": "def down(force):\n    try:\n        cloud_config = CloudConfig()\n        cloud_controller = CloudController(cloud_config)\n        cloud_controller.down(force)\n    except CloudComposeException as ex:\n        print(ex)",
    "docstring": "destroys an existing cluster"
  },
  {
    "code": "def autodoc_event_handlers(stream=sys.stdout):\n    lines = []\n    for cls in all_subclasses(EventHandler):\n        if cls in _ABC_EVHANDLER_CLASSES: continue\n        event_class = cls.event_class\n        lines.extend(cls.cls2str().split(\"\\n\"))\n        if not hasattr(cls, \"can_change_physics\"):\n            raise RuntimeError(\"%s: can_change_physics must be defined\" % cls)\n    stream.write(\"\\n\".join(lines) + \"\\n\")",
    "docstring": "Print to the given string, the documentation for the events\n    and the associated handlers."
  },
  {
    "code": "def _parsecsv(x):\n        for line in x:\n            yield line.decode('utf-8').strip().split(config.DELIMITER)",
    "docstring": "Deserialize file-like object containing csv to a Python generator."
  },
  {
    "code": "def _decode_symbols(symbols):\n    for symbol in symbols:\n        data = string_at(zbar_symbol_get_data(symbol))\n        symbol_type = ZBarSymbol(symbol.contents.type).name\n        polygon = convex_hull(\n            (\n                zbar_symbol_get_loc_x(symbol, index),\n                zbar_symbol_get_loc_y(symbol, index)\n            )\n            for index in _RANGEFN(zbar_symbol_get_loc_size(symbol))\n        )\n        yield Decoded(\n            data=data,\n            type=symbol_type,\n            rect=bounding_box(polygon),\n            polygon=polygon\n        )",
    "docstring": "Generator of decoded symbol information.\n\n    Args:\n        symbols: iterable of instances of `POINTER(zbar_symbol)`\n\n    Yields:\n        Decoded: decoded symbol"
  },
  {
    "code": "def get_array_shape(self, key):\r\n        data = self.model.get_data()\r\n        return data[key].shape",
    "docstring": "Return array's shape"
  },
  {
    "code": "def resizeToContents(self):\r\n        if self.count():\r\n            item = self.item(self.count() - 1)\r\n            rect = self.visualItemRect(item)\r\n            height = rect.bottom() + 8\r\n            height = max(28, height)\r\n            self.setFixedHeight(height)\r\n        else:\r\n            self.setFixedHeight(self.minimumHeight())",
    "docstring": "Resizes the list widget to fit its contents vertically."
  },
  {
    "code": "def tojson(self) -> str:\n        return json.dumps({\n            'event_id': str(self.id),\n            'event_type': self.type,\n            'schema_name': self.schema_name,\n            'table_name': self.table_name,\n            'row_id': self.row_id\n        })",
    "docstring": "Serialize an Event into JSON.\n\n        Returns\n        -------\n        str\n            JSON-serialized Event."
  },
  {
    "code": "def get_prep_value(self, value: LocalizedIntegerValue) -> dict:\n        default_values = LocalizedIntegerValue(self.default)\n        if isinstance(value, LocalizedIntegerValue):\n            for lang_code, _ in settings.LANGUAGES:\n                local_value = value.get(lang_code)\n                if local_value is None:\n                    value.set(lang_code, default_values.get(lang_code, None))\n        prepped_value = super().get_prep_value(value)\n        if prepped_value is None:\n            return None\n        for lang_code, _ in settings.LANGUAGES:\n            local_value = prepped_value[lang_code]\n            try:\n                if local_value is not None:\n                    int(local_value)\n            except (TypeError, ValueError):\n                raise IntegrityError('non-integer value in column \"%s.%s\" violates '\n                                     'integer constraint' % (self.name, lang_code))\n            prepped_value[lang_code] = str(local_value) if local_value is not None else None\n        return prepped_value",
    "docstring": "Gets the value in a format to store into the database."
  },
  {
    "code": "def stderrHandler(level, object, category, file, line, message):\n    o = \"\"\n    if object:\n        o = '\"' + object + '\"'\n    where = \"(%s:%d)\" % (file, line)\n    safeprintf(sys.stderr, '%s [%5d] %-32s %-17s %-15s ',\n               getFormattedLevelName(level), os.getpid(), o, category,\n               time.strftime(\"%b %d %H:%M:%S\"))\n    try:\n        safeprintf(sys.stderr, '%-4s %s %s\\n', \"\", message, where)\n    except UnicodeEncodeError:\n        message = message.encode('UTF-8')\n        safeprintf(sys.stderr, '%-4s %s %s\\n', \"\", message, where)\n    sys.stderr.flush()",
    "docstring": "A log handler that writes to stderr.\n\n    @type level:    string\n    @type object:   string (or None)\n    @type category: string\n    @type message:  string"
  },
  {
    "code": "def space_references(document):\n    for ref in document.xpath('.//a/sup/span[@class=\"sup_ref\"]'):\n        a = ref.getparent().getparent()\n        if a is not None:\n            atail = a.tail or ''\n            if not atail.startswith(')') and not atail.startswith(',') and not atail.startswith(' '):\n                a.tail = ' ' + atail\n    return document",
    "docstring": "Ensure a space around reference links, so there's a gap when they are removed."
  },
  {
    "code": "def get_sigma(imt):\n    if imt.period < 0.2:\n        return np.log(10**0.23)\n    elif imt.period > 1.0:\n        return np.log(10**0.27)\n    else:\n        return np.log(10**(0.23 + (imt.period - 0.2)/0.8 * 0.04))",
    "docstring": "Return the value of the total sigma\n\n    :param float imt:\n        An :class:`openquake.hazardlib.imt.IMT` instance\n    :returns:\n        A float representing the total sigma value"
  },
  {
    "code": "def get_dividend_sum_for_symbol(book: Book, symbol: str):\n    svc = SecuritiesAggregate(book)\n    security = svc.get_by_symbol(symbol)\n    sec_svc = SecurityAggregate(book, security)\n    accounts = sec_svc.get_income_accounts()\n    total = Decimal(0)\n    for account in accounts:\n        income = get_dividend_sum(book, account)\n        total += income\n    return total",
    "docstring": "Calculates all income for a symbol"
  },
  {
    "code": "def _build_hash_string(self):\n        if self.site_name in SITE_LIST or self.hash_string:\n            if self.username and self.password:\n                try:\n                    hash_string = self.hash_string.format(self.password)\n                except TypeError:\n                    raise PybooruError(\"Pybooru can't add 'password' \"\n                                       \"to 'hash_string'\")\n                self.password_hash = hashlib.sha1(\n                    hash_string.encode('utf-8')).hexdigest()\n            else:\n                raise PybooruError(\"Specify the 'username' and 'password' \"\n                                   \"parameters of the Pybooru object, for \"\n                                   \"setting 'password_hash' attribute.\")\n        else:\n            raise PybooruError(\n                \"Specify the 'hash_string' parameter of the Pybooru\"\n                \" object, for the functions that requires login.\")",
    "docstring": "Function for build password hash string.\n\n        Raises:\n            PybooruError: When isn't provide hash string.\n            PybooruError: When aren't provide username or password.\n            PybooruError: When Pybooru can't add password to hash strring."
  },
  {
    "code": "def get_instance(self, payload):\n        return TaskQueueStatisticsInstance(\n            self._version,\n            payload,\n            workspace_sid=self._solution['workspace_sid'],\n            task_queue_sid=self._solution['task_queue_sid'],\n        )",
    "docstring": "Build an instance of TaskQueueStatisticsInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsInstance\n        :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsInstance"
  },
  {
    "code": "def divide(self, layer=WORDS, by=SENTENCES):\n        if not self.is_tagged(layer):\n            self.tag(layer)\n        if not self.is_tagged(by):\n            self.tag(by)\n        return divide(self[layer], self[by])",
    "docstring": "Divide the Text into pieces by keeping references to original elements, when possible.\n        This is not possible only, if the _element_ is a multispan.\n\n        Parameters\n        ----------\n\n        element: str\n            The element to collect and distribute in resulting bins.\n        by: str\n            Each resulting bin is defined by spans of this element.\n\n        Returns\n        -------\n        list of (list of dict)"
  },
  {
    "code": "def get(self, *, no_ack=False):\n        if self.deleted:\n            raise Deleted(\"Queue {} was deleted\".format(self.name))\n        self.sender.send_BasicGet(self.name, no_ack)\n        tag_msg = yield from self.synchroniser.wait(spec.BasicGetOK, spec.BasicGetEmpty)\n        if tag_msg is not None:\n            consumer_tag, msg = tag_msg\n            assert consumer_tag is None\n        else:\n            msg = None\n        self.reader.ready()\n        return msg",
    "docstring": "Synchronously get a message from the queue.\n\n        This method is a :ref:`coroutine <coroutine>`.\n\n        :keyword bool no_ack: if true, the broker does not require acknowledgement of receipt of the message.\n\n        :return: an :class:`~asynqp.message.IncomingMessage`,\n            or ``None`` if there were no messages on the queue."
  },
  {
    "code": "def _get_tnames(self):\n        tnames = set()\n        for arr in self:\n            if isinstance(arr, InteractiveList):\n                tnames.update(arr.get_tnames())\n            else:\n                tnames.add(arr.psy.decoder.get_tname(\n                    next(arr.psy.iter_base_variables), arr.coords))\n        return tnames - {None}",
    "docstring": "Get the name of the time coordinate of the objects in this list"
  },
  {
    "code": "def get_ancestor_processes():\n    if not _ANCESTOR_PROCESSES and psutil is not None:\n        proc = psutil.Process(os.getpid())\n        while proc.parent() is not None:\n            try:\n                _ANCESTOR_PROCESSES.append(proc.parent().exe())\n                proc = proc.parent()\n            except psutil.Error:\n                break\n    return _ANCESTOR_PROCESSES",
    "docstring": "Get a list of the executables of all ancestor processes."
  },
  {
    "code": "def insert(self, key, value, data={}):\n        if value < self.min_value or value > self.max_value:\n            raise BoundsError('item value out of bounds')\n        item = self.Item(key, value, data)\n        index = self.get_bin_index(value)\n        self.bins[index].append(item)",
    "docstring": "Insert the `key` into a bin based on the given `value`.\n\n        Optionally, `data` dictionary may be provided to attach arbitrary data\n        to the key."
  },
  {
    "code": "def _update_config(self,directory,filename):\n        basefilename=os.path.splitext(filename)[0]\n        ext=os.path.splitext(filename)[1].lower()\n        if filename==SET_FILE:\n            print(\"%s - Moving photos to album\"%(filename))\n            return self._upload_media(directory,movealbum_request=True)\n        elif filename==MEGAPIXEL_FILE:\n            print(\"%s - Resizing photos\"%(filename))\n            return self._upload_media(directory,resize_request=True)\n        elif ext in self.FB_META_EXTENSIONS:\n            print(\"%s - Changing photo title\"%(basefilename))\n            return self._upload_media(directory,basefilename,changetitle_request=True)\n        return False",
    "docstring": "Manages FB config files"
  },
  {
    "code": "def get_fallback_languages(self):\n        lang_dict = get_language_settings(self._current_language)\n        fallbacks = [lang for lang in lang_dict['fallbacks'] if lang != self._current_language]\n        return fallbacks or []",
    "docstring": "Return the fallback language codes,\n        which are used in case there is no translation for the currently active language."
  },
  {
    "code": "def hash(self):\n        return u''.join([\n            self.alias,\n            self.description,\n            str(self.ignored),\n            str(self.flags),\n        ])",
    "docstring": "Return a value that's used to uniquely identify an entry in a date so we can regroup all entries that share the\n        same hash."
  },
  {
    "code": "def run_task_class(self, class_path, **options):\n        logger.console(\"\\n\")\n        task_class, task_config = self._init_task(class_path, options, TaskConfig())\n        return self._run_task(task_class, task_config)",
    "docstring": "Runs a CumulusCI task class with task options via kwargs.\n\n            Use this keyword to run logic from CumulusCI tasks which have not\n            been configured in the project's cumulusci.yml file.  This is\n            most useful in cases where a test needs to use task logic for\n            logic unique to the test and thus not worth making into a named\n            task for the project\n\n            Examples:\n            | =Keyword=      | =task_class=                     | =task_options=                            |\n            | Run Task Class | cumulusci.task.utils.DownloadZip | url=http://test.com/test.zip dir=test_zip |"
  },
  {
    "code": "def stop():\n    global _active\n    if not _active:\n        msg = 'lazarus is not active'\n        raise RuntimeWarning(msg)\n    _observer.stop()\n    _observer.join()\n    _deactivate()",
    "docstring": "Stops lazarus, regardless of which mode it was started in.\n\n    For example:\n\n        >>> import lazarus\n        >>> lazarus.default()\n        >>> lazarus.stop()"
  },
  {
    "code": "def hash_file(path, hashobj, conn=None):\n    if os.path.isdir(path):\n        return ''\n    with salt.utils.files.fopen(path, 'r') as f:\n        hashobj.update(salt.utils.stringutils.to_bytes(f.read()))\n        return hashobj.hexdigest()",
    "docstring": "Get the hexdigest hash value of a file"
  },
  {
    "code": "def _write_iterate(self, values):\n        result = []\n        for key in self.order:\n            result.append(self.lines[key].write(values))\n        if len(result) > 1:\n            return result\n        else:\n            return result[0]",
    "docstring": "Generates the lines for a single pass through the group."
  },
  {
    "code": "def datapoint(self, ind, field_names=None):\n        if self._has_unsaved_data:\n            self.flush()\n        if ind >= self._num_datapoints:\n            raise ValueError('Index %d larger than the number of datapoints in the dataset (%d)' %(ind, self._num_datapoints))\n        if field_names is None:\n            field_names = self.field_names\n        datapoint = TensorDatapoint(field_names)\n        file_num = self._index_to_file_num[ind]\n        for field_name in field_names:\n            tensor = self.tensor(field_name, file_num)\n            tensor_index = ind % self._datapoints_per_file\n            datapoint[field_name] = tensor.datapoint(tensor_index)\n        return datapoint",
    "docstring": "Loads a tensor datapoint for a given global index.\n\n        Parameters\n        ----------\n        ind : int\n            global index in the tensor\n        field_names : :obj:`list` of str\n            field names to load\n\n        Returns\n        -------\n        :obj:`TensorDatapoint`\n            the desired tensor datapoint"
  },
  {
    "code": "def write_raw(path, raw):\n    log.debug('Writing vault secrets for %s at %s', __grains__['id'], path)\n    try:\n        url = 'v1/{0}'.format(path)\n        response = __utils__['vault.make_request']('POST', url, json=raw)\n        if response.status_code == 200:\n            return response.json()['data']\n        elif response.status_code != 204:\n            response.raise_for_status()\n        return True\n    except Exception as err:\n        log.error('Failed to write secret! %s: %s', type(err).__name__, err)\n        return False",
    "docstring": "Set raw data at the path in vault. The vault policy used must allow this.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n            salt '*' vault.write_raw \"secret/my/secret\" '{\"user\":\"foo\",\"password\": \"bar\"}'"
  },
  {
    "code": "def add_clause(self, clause, no_return=True):\n        if self.solver:\n            res = self.solver.add_clause(clause, no_return)\n            if not no_return:\n                return res",
    "docstring": "This method is used to add a single clause to the solver. An\n            optional argument ``no_return`` controls whether or not to check\n            the formula's satisfiability after adding the new clause.\n\n            :param clause: an iterable over literals.\n            :param no_return: check solver's internal formula and return the\n                result, if set to ``False``.\n\n            :type clause: iterable(int)\n            :type no_return: bool\n\n            :rtype: bool if ``no_return`` is set to ``False``.\n\n            Note that a clause can be either a ``list`` of integers or another\n            iterable type over integers, e.g. ``tuple`` or ``set`` among\n            others.\n\n            A usage example is the following:\n\n            .. code-block:: python\n\n                >>> s = Solver(bootstrap_with=[[-1, 2], [-1, -2]])\n                >>> s.add_clause([1], no_return=False)\n                False"
  },
  {
    "code": "def sql(self, input_string, *args):\n        psycopg2 = importlib.import_module('psycopg2')\n        importlib.import_module('psycopg2.extensions')\n        connection = psycopg2.connect(\n            user=self.user, host=self.host,\n            port=self.port, database=self.db_name)\n        connection.set_isolation_level(\n            psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)\n        try:\n            cursor = connection.cursor()\n            cursor.execute(input_string, args)\n            try:\n                return cursor.fetchall()\n            except psycopg2.ProgrammingError:\n                return None\n        finally:\n            connection.close()",
    "docstring": "Execute a SQL command using the Python DBI directly.\n\n        Connection parameters are taken from self.  Autocommit is in effect.\n\n        Example: .sql('SELECT %s FROM %s WHERE age > %s', 'name', 'table1',\n            '45')\n\n        @param input_string: A string of SQL.  May contain %s or %(name)s\n        format specifiers; they are replaced with corresponding values taken\n        from args.\n\n        @param args: zero or more parameters to interpolate into the string.\n        Note that they're passed individually, not as a single tuple.\n\n        @return: Whatever .fetchall() returns."
  },
  {
    "code": "def distance(latitude_1, longitude_1, latitude_2, longitude_2):\n    coef = mod_math.cos(latitude_1 / 180. * mod_math.pi)\n    x = latitude_1 - latitude_2\n    y = (longitude_1 - longitude_2) * coef\n    return mod_math.sqrt(x * x + y * y) * ONE_DEGREE",
    "docstring": "Distance between two points."
  },
  {
    "code": "def set_config(self, payload):\n        self.config['default'][payload['option']] = str(payload['value'])\n        if payload['option'] == 'maxProcesses':\n            self.process_handler.set_max(payload['value'])\n        if payload['option'] == 'customShell':\n            path = payload['value']\n            if os.path.isfile(path) and os.access(path, os.X_OK):\n                self.process_handler.set_shell(path)\n            elif path == 'default':\n                self.process_handler.set_shell()\n            else:\n                return {'message': \"File in path doesn't exist or is not executable.\",\n                        'status': 'error'}\n        self.write_config()\n        return {'message': 'Configuration successfully updated.',\n                'status': 'success'}",
    "docstring": "Update the current config depending on the payload and save it."
  },
  {
    "code": "def split_every(n, iterable):\n    items = iter(iterable)\n    return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))",
    "docstring": "Returns a generator that spits an iteratable into n-sized chunks. The last chunk may have\n    less than n elements.\n\n    See http://stackoverflow.com/a/22919323/503377."
  },
  {
    "code": "def git_available(func):\n    def inner(*args):\n        os.chdir(APISettings.GIT_DIR)\n        if call(['git', 'rev-parse']) == 0:\n            return func(*args)\n        Shell.fail('There is no git repository!')\n        return exit(1)\n    return inner",
    "docstring": "Check, if a git repository exists in the given folder."
  },
  {
    "code": "def get_version(module='spyder_notebook'):\n    with open(os.path.join(HERE, module, '_version.py'), 'r') as f:\n        data = f.read()\n    lines = data.split('\\n')\n    for line in lines:\n        if line.startswith('VERSION_INFO'):\n            version_tuple = ast.literal_eval(line.split('=')[-1].strip())\n            version = '.'.join(map(str, version_tuple))\n            break\n    return version",
    "docstring": "Get version."
  },
  {
    "code": "async def wait_stream(aiterable):\n    async with streamcontext(aiterable) as streamer:\n        async for item in streamer:\n            item\n        try:\n            return item\n        except NameError:\n            raise StreamEmpty()",
    "docstring": "Wait for an asynchronous iterable to finish and return the last item.\n\n    The iterable is executed within a safe stream context.\n    A StreamEmpty exception is raised if the sequence is empty."
  },
  {
    "code": "def _get_sub_package_provider_session(self, sub_package, session_name, proxy=None):\n        agent_key = self._get_agent_key()\n        if session_name in self._provider_sessions[agent_key]:\n            return self._provider_sessions[agent_key][session_name]\n        else:\n            manager = self._get_sub_package_provider_manager(sub_package)\n            session = self._instantiate_session('get_' + session_name + '_for_bank',\n                                                proxy=self._proxy,\n                                                manager=manager)\n            self._set_bank_view(session)\n            self._set_object_view(session)\n            self._set_operable_view(session)\n            self._set_containable_view(session)\n            if self._session_management != DISABLED:\n                self._provider_sessions[agent_key][session_name] = session\n            return session",
    "docstring": "Gets the session from a sub-package"
  },
  {
    "code": "def correct_word(word_string):\n    if word_string is None:\n        return \"\"\n    elif isinstance(word_string, str):\n        return max(find_candidates(word_string), key=find_word_prob)\n    else:\n        raise InputError(\"string or none type variable not passed as argument to correct_word\")",
    "docstring": "Finds all valid one and two letter corrections for word_string, returning the word\n    with the highest relative probability as type str."
  },
  {
    "code": "def ArtifactsFromYaml(self, yaml_content):\n    raw_list = yaml.ParseMany(yaml_content)\n    if (isinstance(raw_list, list) and len(raw_list) == 1 and\n        isinstance(raw_list[0], list)):\n      raw_list = raw_list[0]\n    valid_artifacts = []\n    for artifact_dict in raw_list:\n      try:\n        artifact_value = rdf_artifacts.Artifact(**artifact_dict)\n        valid_artifacts.append(artifact_value)\n      except (TypeError, AttributeError, type_info.TypeValueError) as e:\n        name = artifact_dict.get(\"name\")\n        raise rdf_artifacts.ArtifactDefinitionError(\n            name, \"invalid definition\", cause=e)\n    return valid_artifacts",
    "docstring": "Get a list of Artifacts from yaml."
  },
  {
    "code": "def _fwhm_side_lineal(uu, vv):\n    res1, = np.nonzero(vv < 0)\n    if len(res1) == 0:\n        return 0, 1\n    else:\n        i2 = res1[0]\n        i1 = i2 - 1\n        dx = uu[i2] - uu[i1]\n        dy = vv[i2] - vv[i1]\n        r12 = uu[i1] - vv[i1] * dx / dy\n        return r12, 0",
    "docstring": "Compute r12 using linear interpolation."
  },
  {
    "code": "def make_request(self, data, is_json=True):\n        if is_json:\n            self.headers['Content-Type'] = 'application/json'\n        if not is_json:\n            data = urlencode_utf8(data)\n        response = requests.post(\n            self.url, data=data, headers=self.headers,\n            proxies=self.proxy\n        )\n        if response.status_code == 200:\n            if is_json:\n                response = response.json()\n            else:\n                response = response.content\n            return response\n        if response.status_code == 400:\n            raise GCMMalformedJsonException(\n                \"The request could not be parsed as JSON\")\n        elif response.status_code == 401:\n            raise GCMAuthenticationException(\n                \"There was an error authenticating the sender account\")\n        elif response.status_code == 503:\n            raise GCMUnavailableException(\"GCM service is unavailable\")\n        else:\n            error = \"GCM service error: %d\" % response.status_code\n            raise GCMUnavailableException(error)",
    "docstring": "Makes a HTTP request to GCM servers with the constructed payload\n\n        :param data: return value from construct_payload method\n        :raises GCMMalformedJsonException: if malformed JSON request found\n        :raises GCMAuthenticationException: if there was a problem with authentication, invalid api key\n        :raises GCMConnectionException: if GCM is screwed"
  },
  {
    "code": "def get_object(self, queryset=None):\n        if settings.PODCAST_SINGULAR:\n            show = get_object_or_404(Show, id=settings.PODCAST_ID)\n        else:\n            show = get_object_or_404(Show, slug=self.kwargs['show_slug'])\n        obj = get_object_or_404(Episode, show=show, slug=self.kwargs['slug'])\n        index = Episode.objects.is_public_or_secret().filter(show=show, pub_date__lt=obj.pub_date).count()\n        obj.index = index + 1\n        obj.index_next = obj.index + 1\n        obj.index_previous = obj.index - 1\n        return obj",
    "docstring": "Return object with episode number attached to episode."
  },
  {
    "code": "def _evaluate(self, message):\n        return eval(\n            self.code,\n            globals(), {\n                \"J\": message,\n                \"timedelta\": timedelta,\n                \"datetime\": datetime,\n                \"SKIP\": self._SKIP})",
    "docstring": "Evaluate the expression with the given Python object in its locals.\n\n        @param message: A decoded JSON input.\n\n        @return: The resulting object."
  },
  {
    "code": "def makefile(self, mode='r', bufsize=-1):\n        'return a file-like object that operates on the ssl connection'\n        sockfile = gsock.SocketFile.__new__(gsock.SocketFile)\n        gfiles.FileBase.__init__(sockfile)\n        sockfile._sock = self\n        sockfile.mode = mode\n        if bufsize > 0:\n            sockfile.CHUNKSIZE = bufsize\n        return sockfile",
    "docstring": "return a file-like object that operates on the ssl connection"
  },
  {
    "code": "def __add_document_structure(self, docgraph,\n                                 remove_redundant_layers=True):\n        E = self.E\n        root = self.__create_document_header()\n        body = E('basic-body')\n        timeline = E('common-timeline')\n        for i in xrange(len(docgraph.tokens)+1):\n            idx = str(i)\n            timeline.append(E('tli', {'id': 'T'+idx, 'time': idx}))\n        body.append(timeline)\n        body = self.__add_token_tiers(docgraph, body)\n        annotation_layers = get_annotation_layers(docgraph)\n        for layer in annotation_layers:\n            if not remove_redundant_layers:\n                self.__add_annotation_tier(docgraph, body, layer)\n            elif is_informative(layer):\n                self.__add_annotation_tier(docgraph, body, layer)\n        self.__add_coreference_chain_tiers(docgraph, body)\n        root.append(body)\n        return root",
    "docstring": "return an Exmaralda XML etree representation a docgraph"
  },
  {
    "code": "def _set_virtual(self, key, value):\n        if key in self and key not in self._virtual_keys:\n            return\n        self._virtual_keys.add(key)\n        if key in self and self[key] is not value:\n            self._on_change(key, value)\n        dict.__setitem__(self, key, value)\n        for overlay in self._iter_overlays():\n            overlay._set_virtual(key, value)",
    "docstring": "Recursively set or update virtual keys. Do nothing if non-virtual\n            value is present."
  },
  {
    "code": "def find_collection_ids(self, search_pattern=\"\", identifier=\"\", fetched=0, page=1):\n        params = {\"page\": page, \"q\": \"primary_type:resource\"}\n        if search_pattern != \"\":\n            search_pattern = self._escape_solr_query(search_pattern, field=\"title\")\n            params[\"q\"] = params[\"q\"] + \" AND title:{}\".format(search_pattern)\n        if identifier != \"\":\n            identifier = self._escape_solr_query(identifier, field=\"identifier\")\n            params[\"q\"] = params[\"q\"] + \" AND identifier:{}\".format(identifier)\n        response = self._get(self.repository + \"/search\", params=params)\n        hits = response.json()\n        results = [r[\"uri\"] for r in hits[\"results\"]]\n        results_so_far = fetched + hits[\"this_page\"]\n        if hits[\"total_hits\"] > results_so_far:\n            results.extend(\n                self.find_collection_ids(fetched=results_so_far, page=page + 1)\n            )\n        return results",
    "docstring": "Fetches a list of resource URLs for every resource in the database.\n\n        :param string search_pattern: A search pattern to use in looking up resources by title or resourceid.\n            The search will match any title containing this string;\n            for example, \"text\" will match \"this title has this text in it\".\n            If omitted, then all resources will be fetched.\n        :param string identifier: Only records containing this identifier will be returned.\n            Substring matching will not be performed; however, wildcards are supported.\n            For example, searching \"F1\" will only return records with the identifier \"F1\", while searching \"F*\" will return \"F1\", \"F2\", etc.\n\n        :return: A list containing every matched resource's URL.\n        :rtype list:"
  },
  {
    "code": "def to_text(self, name, **kw):\n        s = StringIO.StringIO()\n        for rds in self.rdatasets:\n            print >> s, rds.to_text(name, **kw)\n        return s.getvalue()[:-1]",
    "docstring": "Convert a node to text format.\n\n        Each rdataset at the node is printed.  Any keyword arguments\n        to this method are passed on to the rdataset's to_text() method.\n        @param name: the owner name of the rdatasets\n        @type name: dns.name.Name object\n        @rtype: string"
  },
  {
    "code": "def find(name, path=(), parent=None):\n    assert isinstance(path, tuple)\n    head, _, tail = name.partition('.')\n    try:\n        tup = imp.find_module(head, list(path))\n    except ImportError:\n        return parent\n    fp, modpath, (suffix, mode, kind) = tup\n    if fp:\n        fp.close()\n    if parent and modpath == parent.path:\n        return None\n    if kind == imp.PKG_DIRECTORY:\n        modpath = os.path.join(modpath, '__init__.py')\n    module = Module(head, modpath, kind, parent)\n    if tail and kind == imp.PKG_DIRECTORY:\n        return find_relative(module, tail, path)\n    return module",
    "docstring": "Return a Module instance describing the first matching module found on the\n    search path.\n\n    :param str name:\n        Module name.\n    :param list path:\n        List of directory names to search for the module.\n    :param Module parent:\n        Optional module parent."
  },
  {
    "code": "def _compose_custom_getters(getter_a, getter_b):\n  if not getter_a:\n    return getter_b\n  if not getter_b:\n    return getter_a\n  def getter_fn(getter, *args, **kwargs):\n    return getter_b(functools.partial(getter_a, getter), *args, **kwargs)\n  return getter_fn",
    "docstring": "Compose two custom getters.\n\n  Example use:\n  tf.get_variable_scope().set_custom_getter(\n    compose_custom_getters(tf.get_variable_scope().custom_getter, new_getter))\n\n  This composes getters in the same way as creating a new variable scope with\n  the new_getter, but it does not actually create a new variable scope.\n\n  Args:\n    getter_a: a custom getter - generally from the existing variable scope.\n    getter_b: a custom getter\n\n  Returns:\n    a custom getter"
  },
  {
    "code": "def __unset_binding(self, dependency, service, reference):\n        self.__safe_field_callback(\n            dependency.get_field(),\n            constants.IPOPO_CALLBACK_UNBIND_FIELD,\n            service,\n            reference,\n        )\n        self.safe_callback(constants.IPOPO_CALLBACK_UNBIND, service, reference)\n        setattr(self.instance, dependency.get_field(), dependency.get_value())\n        self.bundle_context.unget_service(reference)",
    "docstring": "Removes a service from the component\n\n        :param dependency: The dependency handler\n        :param service: The injected service\n        :param reference: The reference of the injected service"
  },
  {
    "code": "def start_batch(job, input_args):\n    samples = parse_sra(input_args['sra'])\n    job.addChildJobFn(download_and_transfer_sample, input_args, samples, cores=1, disk='30')",
    "docstring": "This function will administer 5 jobs at a time then recursively call itself until subset is empty"
  },
  {
    "code": "def from_file(xmu_dat_file=\"xmu.dat\", feff_inp_file=\"feff.inp\"):\n        data = np.loadtxt(xmu_dat_file)\n        header = Header.from_file(feff_inp_file)\n        parameters = Tags.from_file(feff_inp_file)\n        pots = Potential.pot_string_from_file(feff_inp_file)\n        if \"RECIPROCAL\" in parameters:\n            absorbing_atom = parameters[\"TARGET\"]\n        else:\n            absorbing_atom = pots.splitlines()[3].split()[2]\n        return Xmu(header, parameters, absorbing_atom, data)",
    "docstring": "Get Xmu from file.\n\n        Args:\n            xmu_dat_file (str): filename and path for xmu.dat\n            feff_inp_file (str): filename and path of feff.inp input file\n\n        Returns:\n             Xmu object"
  },
  {
    "code": "def merge_xml(first_doc, second_doc):\n    if isinstance(first_doc, lxml.etree._Element):\n        first_doc = ET.fromstring(lxml.etree.tostring(first_doc))\n    if isinstance(second_doc, lxml.etree._Element):\n        second_doc = ET.fromstring(lxml.etree.tostring(second_doc))\n    mapping = {element.tag: element for element in first_doc}\n    for element in second_doc:\n        if not len(element):\n            try:\n                mapping[element.tag].text = element.text\n            except KeyError:\n                mapping[element.tag] = element\n                first_doc.append(element)\n        else:\n            try:\n                merge_xml(mapping[element.tag], element)\n            except KeyError:\n                mapping[element.tag] = element\n                first_doc.append(element)\n    return lxml.etree.fromstring(ET.tostring(first_doc))",
    "docstring": "Merges two XML documents.\n\n    Args:\n        first_doc (str): First XML document.  `second_doc` is merged into this\n            document.\n        second_doc (str): Second XML document.  It is merged into the first.\n\n    Returns:\n        XML Document: The merged document.\n\n    Raises:\n        None\n\n    Example:\n        >>> import pynos.utilities\n        >>> import lxml\n        >>> import xml\n        >>> x = xml.etree.ElementTree.fromstring('<config />')\n        >>> y = lxml.etree.fromstring('<config><hello /></config>')\n        >>> x = pynos.utilities.merge_xml(x, y)"
  },
  {
    "code": "def keep_types_s(s, types):\n        patt = '|'.join('(?<=\\n)' + s + '\\n(?s).+?\\n(?=\\S+|$)' for s in types)\n        return ''.join(re.findall(patt, '\\n' + s.strip() + '\\n')).rstrip()",
    "docstring": "Keep the given types from a string\n\n        Same as :meth:`keep_types` but does not use the :attr:`params`\n        dictionary\n\n        Parameters\n        ----------\n        s: str\n            The string of the returns like section\n        types: list of str\n            The type identifiers to keep\n\n        Returns\n        -------\n        str\n            The modified string `s` with only the descriptions of `types`"
  },
  {
    "code": "def get_chr2idx(self):\n        return {chr(ascii_int):idx for idx, ascii_int in enumerate(self.all_chrints)}",
    "docstring": "Return a dict with the ASCII art character as key and its index as value."
  },
  {
    "code": "def name(self):\n        alias = getattr(self, 'alias', None)\n        if alias:\n            return alias\n        caption = getattr(self, 'caption', None)\n        if caption:\n            return caption\n        return self.id",
    "docstring": "Provides a nice name for the field which is derived from the alias, caption, or the id.\n\n        The name resolves as either the alias if it's defined, or the caption if alias is not defined,\n        and finally the id which is the underlying name if neither of the fields exist."
  },
  {
    "code": "def _set_frequency_spacing(self, min_freq, max_freq):\n        self.frequency_spacing = np.linspace(min_freq, max_freq, num=self._sheet_dimensions[0]+1, endpoint=True)",
    "docstring": "Frequency spacing to use, i.e. how to map the available\n        frequency range to the discrete sheet rows.\n\n        NOTE: We're calculating the spacing of a range between the\n        highest and lowest frequencies, the actual segmentation and\n        averaging of the frequencies to fit this spacing occurs in\n        _getAmplitudes().\n\n        This method is here solely to provide a minimal overload if\n        custom spacing is required."
  },
  {
    "code": "def has_parent_families(self, family_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.has_parent_catalogs(catalog_id=family_id)\n        return self._hierarchy_session.has_parents(id_=family_id)",
    "docstring": "Tests if the ``Family`` has any parents.\n\n        arg:    family_id (osid.id.Id): the ``Id`` of a family\n        return: (boolean) - ``true`` if the family has parents,\n                ``false`` otherwise\n        raise:  NotFound - ``family_id`` is not found\n        raise:  NullArgument - ``family_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_syllabus(self, site):\n        tools = self.get_tools(site)\n        syllabus_filter = [x.href for x in tools if x.name == 'syllabus']\n        if not syllabus_filter:\n            return ''\n        response = self._session.get(syllabus_filter[0])\n        response.raise_for_status()\n        iframes = self._html_iface.get_iframes(response.text)\n        iframe_url = ''\n        for frame in iframes:\n            if frame['title'] == 'Syllabus ':\n                iframe_url = frame['src']\n        if iframe_url == '':\n            print \"WARHING: NO SYLLABUS IFRAME FOUND\"\n        response = self._session.get(iframe_url)\n        response.raise_for_status()\n        syllabus_html = self._html_iface.get_syllabus(response.text)\n        return syllabus_html",
    "docstring": "Gets the syllabus for a course. The syllabus may or may not\n        contain HTML, depending on the site. TSquare does not enforce\n        whether or not pages are allowed to have HTML, so it is impossible\n        to tell."
  },
  {
    "code": "def _assign_entity_to_pb(entity_pb, entity):\n    bare_entity_pb = helpers.entity_to_protobuf(entity)\n    bare_entity_pb.key.CopyFrom(bare_entity_pb.key)\n    entity_pb.CopyFrom(bare_entity_pb)",
    "docstring": "Copy ``entity`` into ``entity_pb``.\n\n    Helper method for ``Batch.put``.\n\n    :type entity_pb: :class:`.entity_pb2.Entity`\n    :param entity_pb: The entity owned by a mutation.\n\n    :type entity: :class:`google.cloud.datastore.entity.Entity`\n    :param entity: The entity being updated within the batch / transaction."
  },
  {
    "code": "def _log_statistics(self):\n        rows_per_second_trans = self._count_total / (self._time1 - self._time0)\n        rows_per_second_load = self._count_transform / (self._time2 - self._time1)\n        rows_per_second_overall = self._count_total / (self._time3 - self._time0)\n        self._log('Number of rows processed            : {0:d}'.format(self._count_total))\n        self._log('Number of rows transformed          : {0:d}'.format(self._count_transform))\n        self._log('Number of rows ignored              : {0:d}'.format(self._count_ignore))\n        self._log('Number of rows parked               : {0:d}'.format(self._count_park))\n        self._log('Number of errors                    : {0:d}'.format(self._count_error))\n        self._log('Number of rows per second processed : {0:d}'.format(int(rows_per_second_trans)))\n        self._log('Number of rows per second loaded    : {0:d}'.format(int(rows_per_second_load)))\n        self._log('Number of rows per second overall   : {0:d}'.format(int(rows_per_second_overall)))",
    "docstring": "Log statistics about the number of rows and number of rows per second."
  },
  {
    "code": "def _find_min_start(text, max_width, unicode_aware=True, at_end=False):\n    if 2 * len(text) < max_width:\n        return 0\n    result = 0\n    string_len = wcswidth if unicode_aware else len\n    char_len = wcwidth if unicode_aware else lambda x: 1\n    display_end = string_len(text)\n    while display_end > max_width:\n        result += 1\n        display_end -= char_len(text[0])\n        text = text[1:]\n    if at_end and display_end == max_width:\n        result += 1\n    return result",
    "docstring": "Find the starting point in the string that will reduce it to be less than or equal to the\n    specified width when displayed on screen.\n\n    :param text: The text to analyze.\n    :param max_width: The required maximum width\n    :param at_end: At the end of the editable line, so allow spaced for cursor.\n\n    :return: The offset within `text` to start at to reduce it to the required length."
  },
  {
    "code": "def remove(self, child):\n        if isinstance(child, Element):\n            return child.detach()\n        if isinstance(child, Attribute):\n            self.attributes.remove(child)\n        return None",
    "docstring": "Remove the specified child element or attribute.\n        @param child: A child to remove.\n        @type child: L{Element}|L{Attribute}\n        @return: The detached I{child} when I{child} is an element, else None.\n        @rtype: L{Element}|None"
  },
  {
    "code": "def get_version(package_name, ignore_cache=False):\n    if ignore_cache:\n        with microcache.temporarily_disabled():\n            found = helpers.regex_in_package_file(\n                VERSION_SET_REGEX, '_version.py', package_name, return_match=True\n            )\n    else:\n        found = helpers.regex_in_package_file(\n            VERSION_SET_REGEX, '_version.py', package_name, return_match=True\n        )\n    if found is None:\n        raise ProjectError('found {}, but __version__ is not defined')\n    current_version = found['version']\n    return current_version",
    "docstring": "Get the version which is currently configured by the package"
  },
  {
    "code": "def origin_north_africa(origin):\n    return origin_egypt(origin) or origin_algeria(origin) \\\n           or origin_libya(origin) or origin_morocco(origin) \\\n           or origin_sudan(origin) or origin_tunisia(origin)",
    "docstring": "\\\n    Returns if the origin is located in North Africa.\n\n    Holds true for the following countries:\n        * Algeria\n        * Egypt\n        * Libya\n        * Morocco\n        * Sudan\n        * Tunisia\n\n    `origin`\n        The origin to check."
  },
  {
    "code": "def main(self):\n        for m in self.methods:\n            if m.name in ['Main', 'main']:\n                return m\n        if len(self.methods):\n            return self.methods[0]\n        return None",
    "docstring": "Return the default method in this module.\n\n        :return: the default method in this module\n        :rtype: ``boa.code.method.Method``"
  },
  {
    "code": "def sg_regularizer_loss(scale=1.0):\n    r\n    return scale * tf.reduce_mean(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))",
    "docstring": "r\"\"\" Get regularizer losss\n\n    Args:\n      scale: A scalar. A weight applied to regularizer loss"
  },
  {
    "code": "def contains_parent_dir(fpath, dirs):\n    return bool([x for x in dirs if _f(fpath, x)])",
    "docstring": "Returns true if paths in dirs start with fpath.\n\n    Precondition: dirs and fpath should be normalized before calling\n    this function."
  },
  {
    "code": "def Sum(*args: BitVec) -> BitVec:\n    raw = z3.Sum([a.raw for a in args])\n    annotations = []\n    bitvecfuncs = []\n    for bv in args:\n        annotations += bv.annotations\n        if isinstance(bv, BitVecFunc):\n            bitvecfuncs.append(bv)\n    if len(bitvecfuncs) >= 2:\n        return BitVecFunc(raw=raw, func_name=None, input_=None, annotations=annotations)\n    elif len(bitvecfuncs) == 1:\n        return BitVecFunc(\n            raw=raw,\n            func_name=bitvecfuncs[0].func_name,\n            input_=bitvecfuncs[0].input_,\n            annotations=annotations,\n        )\n    return BitVec(raw, annotations)",
    "docstring": "Create sum expression.\n\n    :return:"
  },
  {
    "code": "def permissions(self, course_id, permissions=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"course_id\"] = course_id\r\n        if permissions is not None:\r\n            params[\"permissions\"] = permissions\r\n        self.logger.debug(\"GET /api/v1/courses/{course_id}/permissions with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"GET\", \"/api/v1/courses/{course_id}/permissions\".format(**path), data=data, params=params, no_data=True)",
    "docstring": "Permissions.\r\n\r\n        Returns permission information for provided course & current_user"
  },
  {
    "code": "def _update(self, data):\n        for k, v in six.iteritems(data):\n            new_value = v\n            if isinstance(v, dict):\n                new_value = type(self)(v)\n            elif isinstance(v, list):\n                new_value = [(type(self)(e) if isinstance(e, dict) else e)\n                             for e in v]\n            setattr(self, k, new_value)",
    "docstring": "Update the object with new data."
  },
  {
    "code": "def roster(team_id):\n    data = mlbgame.info.roster(team_id)\n    return mlbgame.info.Roster(data)",
    "docstring": "Return Roster object that contains roster info for a team"
  },
  {
    "code": "def _find_errors_param(self):\n        if hasattr(self.estimator, 'mse_path_'):\n            return self.estimator.mse_path_.mean(1)\n        if hasattr(self.estimator, 'cv_values_'):\n            return self.estimator.cv_values_.mean(0)\n        raise YellowbrickValueError(\n            \"could not find errors param on {} estimator\".format(\n                self.estimator.__class__.__name__\n            )\n        )",
    "docstring": "Searches for the parameter on the estimator that contains the array of\n        errors that was used to determine the optimal alpha. If it cannot find\n        the parameter then a YellowbrickValueError is raised."
  },
  {
    "code": "def intersect_sites_method(form):\n    if settings.PAGE_USE_SITE_ID:\n        if settings.PAGE_HIDE_SITES:\n            site_ids = [global_settings.SITE_ID]\n        else:\n            site_ids = [int(x) for x in form.data.getlist('sites')]\n        def intersects_sites(sibling):\n            return sibling.sites.filter(id__in=site_ids).count() > 0\n    else:\n        def intersects_sites(sibling):\n            return True\n    return intersects_sites",
    "docstring": "Return a method to intersect sites."
  },
  {
    "code": "def _command(self, event, command, *args, **kwargs):\n        self._assert_transition(event)\n        self.trigger('pre_%s' % event, **kwargs)\n        self._execute_command(command, *args)\n        self.trigger('post_%s' % event, **kwargs)",
    "docstring": "Context state controller.\n\n        Check whether the transition is possible or not, it executes it and\n        triggers the Hooks with the pre_* and post_* events.\n\n        @param event: (str) event generated by the command.\n        @param command: (virDomain.method) state transition to impose.\n        @raise: RuntimeError."
  },
  {
    "code": "def image_format(value):\n    if value.image.format.upper() not in constants.ALLOWED_IMAGE_FORMATS:\n        raise ValidationError(MESSAGE_INVALID_IMAGE_FORMAT)",
    "docstring": "Confirms that the uploaded image is of supported format.\n\n    Args:\n        value (File): The file with an `image` property containing the image\n\n    Raises:\n        django.forms.ValidationError"
  },
  {
    "code": "def tag_torsion_angles(self, force=False):\n        for polymer in self._molecules:\n            if polymer.molecule_type == 'protein':\n                polymer.tag_torsion_angles(force=force)\n        return",
    "docstring": "Tags each `Monomer` in the `Assembly` with its torsion angles.\n\n        Parameters\n        ----------\n        force : bool, optional\n            If `True`, the tag will be run even if `Monomers` are already\n            tagged."
  },
  {
    "code": "def process_response(self, request, response, spider):\n        return response.replace(body=str(BeautifulSoup(response.body, self.parser)))",
    "docstring": "Overridden process_response would \"pipe\" response.body through BeautifulSoup."
  },
  {
    "code": "def search_traceback(self, tb):\n        new_paths = []\n        with self.lock:\n            for filename, line, funcname, txt in traceback.extract_tb(tb):\n                path = os.path.abspath(filename)\n                if path not in self.paths:\n                    self.paths.add(path)\n                    new_paths.append(path)\n        if new_paths:\n            self.watch_paths(new_paths)",
    "docstring": "Inspect a traceback for new paths to add to our path set."
  },
  {
    "code": "def main():\n    if len(sys.argv) != 3:\n        print('Usage: {} <file1> <file2>'.format(sys.argv[0]))\n        exit(-1)\n    file1 = sys.argv[1]\n    file2 = sys.argv[2]\n    with open(file1) as f1, open(file2) as f2:\n        for line1, line2 in zip(f1, f2):\n            print(\"Line 1: {}\".format(line1.strip()))\n            print(\"Line 2: {}\".format(line2.strip()))\n            dist, _, _ = edit_distance_backpointer(line1.split(), line2.split())\n            print('Distance: {}'.format(dist))\n            print('=' * 80)",
    "docstring": "Read two files line-by-line and print edit distances between each pair\n    of lines. Will terminate at the end of the shorter of the two files."
  },
  {
    "code": "def parse_MML(self, mml):\n        hashes_c = []\n        mentions_c = []\n        soup = BeautifulSoup(mml, \"lxml\")\n        hashes = soup.find_all('hash', {\"tag\": True})\n        for hashe in hashes:\n            hashes_c.append(hashe['tag'])\n        mentions = soup.find_all('mention', {\"uid\": True})\n        for mention in mentions:\n            mentions_c.append(mention['uid'])\n        msg_string = soup.messageml.text.strip()\n        self.logger.debug('%s : %s : %s' % (hashes_c, mentions_c, msg_string))\n        return hashes_c, mentions_c, msg_string",
    "docstring": "parse the MML structure"
  },
  {
    "code": "def _make_attr_tuple_class(cls_name, attr_names):\n    attr_class_name = \"{}Attributes\".format(cls_name)\n    attr_class_template = [\n        \"class {}(tuple):\".format(attr_class_name),\n        \"    __slots__ = ()\",\n    ]\n    if attr_names:\n        for i, attr_name in enumerate(attr_names):\n            attr_class_template.append(\n                _tuple_property_pat.format(index=i, attr_name=attr_name)\n            )\n    else:\n        attr_class_template.append(\"    pass\")\n    globs = {\"_attrs_itemgetter\": itemgetter, \"_attrs_property\": property}\n    eval(compile(\"\\n\".join(attr_class_template), \"\", \"exec\"), globs)\n    return globs[attr_class_name]",
    "docstring": "Create a tuple subclass to hold `Attribute`s for an `attrs` class.\n\n    The subclass is a bare tuple with properties for names.\n\n    class MyClassAttributes(tuple):\n        __slots__ = ()\n        x = property(itemgetter(0))"
  },
  {
    "code": "def attr_dict(self):\n        size = mx_uint()\n        pairs = ctypes.POINTER(ctypes.c_char_p)()\n        f_handle = _LIB.MXSymbolListAttr\n        check_call(f_handle(self.handle, ctypes.byref(size), ctypes.byref(pairs)))\n        ret = {}\n        for i in range(size.value):\n            name, key = py_str(pairs[i * 2]).split('$')\n            val = py_str(pairs[i * 2 + 1])\n            if name not in ret:\n                ret[name] = {}\n            ret[name][key] = val\n        return ret",
    "docstring": "Recursively gets all attributes from the symbol and its children.\n\n        Example\n        -------\n        >>> a = mx.sym.Variable('a', attr={'a1':'a2'})\n        >>> b = mx.sym.Variable('b', attr={'b1':'b2'})\n        >>> c = a+b\n        >>> c.attr_dict()\n        {'a': {'a1': 'a2'}, 'b': {'b1': 'b2'}}\n\n        Returns\n        -------\n        ret : Dict of str to dict\n            There is a key in the returned dict for every child with non-empty attribute set.\n            For each symbol, the name of the symbol is its key in the dict\n            and the correspond value is that symbol's attribute list (itself a dictionary)."
  },
  {
    "code": "def _embedPayload(slaveaddress, mode, functioncode, payloaddata):\n    _checkSlaveaddress(slaveaddress)\n    _checkMode(mode)\n    _checkFunctioncode(functioncode, None)\n    _checkString(payloaddata, description='payload')\n    firstPart = _numToOneByteString(slaveaddress) + _numToOneByteString(functioncode) + payloaddata\n    if mode == MODE_ASCII:\n        request = _ASCII_HEADER + \\\n                _hexencode(firstPart) + \\\n                _hexencode(_calculateLrcString(firstPart)) + \\\n                _ASCII_FOOTER\n    else:\n        request = firstPart + _calculateCrcString(firstPart)\n    return request",
    "docstring": "Build a request from the slaveaddress, the function code and the payload data.\n\n    Args:\n        * slaveaddress (int): The address of the slave.\n        * mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII)\n        * functioncode (int): The function code for the command to be performed. Can for example be 16 (Write register).\n        * payloaddata (str): The byte string to be sent to the slave.\n\n    Returns:\n        The built (raw) request string for sending to the slave (including CRC etc).\n\n    Raises:\n        ValueError, TypeError.\n\n    The resulting request has the format:\n     * RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes).\n     * ASCII Mode: header (:) + slaveaddress (2 characters) + functioncode (2 characters) + payloaddata + LRC (which is two characters) + footer (CRLF)\n\n    The LRC or CRC is calculated from the byte string made up of slaveaddress + functioncode + payloaddata.\n    The header, LRC/CRC, and footer are excluded from the calculation."
  },
  {
    "code": "def dpsi2_dmuS(self, dL_dpsi2, Z, mu, S, target_mu, target_S):\n        self._psi_computations(Z, mu, S)\n        tmp = (self.inv_lengthscale2 * self._psi2[:, :, :, None]) / self._psi2_denom\n        target_mu += -2.*(dL_dpsi2[:, :, :, None] * tmp * self._psi2_mudist).sum(1).sum(1)\n        target_S += (dL_dpsi2[:, :, :, None] * tmp * (2.*self._psi2_mudist_sq - 1)).sum(1).sum(1)",
    "docstring": "Think N,num_inducing,num_inducing,input_dim"
  },
  {
    "code": "def extract_twin_values(triples, traits, gender=None):\n    traitValuesAbsent = 0\n    nanValues = 0\n    genderSkipped = 0\n    twinValues = []\n    for a, b, t in triples:\n        if gender is not None and t != gender:\n            genderSkipped += 1\n            continue\n        if not (a in traits and b in traits):\n            traitValuesAbsent += 1\n            continue\n        if np.isnan(traits[a]) or np.isnan(traits[b]):\n            nanValues += 1\n            continue\n        twinValues.append((traits[a], traits[b]))\n    print(\"A total of {} pairs extracted ({} absent; {} nan; {} genderSkipped)\"\\\n        .format(len(twinValues), traitValuesAbsent, nanValues, genderSkipped))\n    return twinValues",
    "docstring": "Calculate the heritability of certain traits in triplets.\n\n    Parameters\n    ==========\n    triples: (a, b, \"Female/Male\") triples. The sample IDs are then used to query\n             the traits dictionary.\n    traits: sample_id => value dictionary\n\n    Returns\n    =======\n    tuples of size 2, that contain paired trait values of the twins"
  },
  {
    "code": "def cli(env, sortby, datacenter):\n    file_manager = SoftLayer.FileStorageManager(env.client)\n    mask = \"mask[serviceResource[datacenter[name]],\"\\\n           \"replicationPartners[serviceResource[datacenter[name]]]]\"\n    file_volumes = file_manager.list_file_volumes(datacenter=datacenter,\n                                                  mask=mask)\n    datacenters = dict()\n    for volume in file_volumes:\n        service_resource = volume['serviceResource']\n        if 'datacenter' in service_resource:\n            datacenter_name = service_resource['datacenter']['name']\n            if datacenter_name not in datacenters.keys():\n                datacenters[datacenter_name] = 1\n            else:\n                datacenters[datacenter_name] += 1\n    table = formatting.KeyValueTable(DEFAULT_COLUMNS)\n    table.sortby = sortby\n    for datacenter_name in datacenters:\n        table.add_row([datacenter_name, datacenters[datacenter_name]])\n    env.fout(table)",
    "docstring": "List number of file storage volumes per datacenter."
  },
  {
    "code": "def _remove_zeros(votes, fpl, cl, ranking):\n    for v in votes:\n        for r in v:\n            if r not in fpl:\n                v.remove(r)\n    for c in cl:\n        if c not in fpl:\n            if c not in ranking:\n                ranking.append((c, 0))",
    "docstring": "Remove zeros in IRV voting."
  },
  {
    "code": "def ExtractCredentialsFromPathSpec(self, path_spec):\n    credentials = manager.CredentialsManager.GetCredentials(path_spec)\n    for identifier in credentials.CREDENTIALS:\n      value = getattr(path_spec, identifier, None)\n      if value is None:\n        continue\n      self.SetCredential(path_spec, identifier, value)",
    "docstring": "Extracts credentials from a path specification.\n\n    Args:\n      path_spec (PathSpec): path specification to extract credentials from."
  },
  {
    "code": "def get_constant(self, const_name, context):\n        const = self._constants[const_name]\n        if isinstance(const, ast.AnnAssign):\n            if context:\n                expr = Expr(const.value, context).lll_node\n                return expr\n            else:\n                raise VariableDeclarationException(\n                    \"ByteArray: Can not be used outside of a function context: %s\" % const_name\n                )\n        return self._constants[const_name]",
    "docstring": "Return unrolled const"
  },
  {
    "code": "def delete(self, *args, **kwargs):\n        return self.session.delete(*args, **self.get_kwargs(**kwargs))",
    "docstring": "Executes an HTTP DELETE.\n\n        :Parameters:\n           - `args`: Non-keyword arguments\n           - `kwargs`: Keyword arguments"
  },
  {
    "code": "def assign_to(self, obj):\n    obj.x = self.x\n    obj.y = self.y",
    "docstring": "Assign `x` and `y` to an object that has properties `x` and `y`."
  },
  {
    "code": "def get(self, **kwargs):\n        for chain in self.chains:\n            for key in kwargs:\n                getter_name = \"get_\"+key\n                if (hasattr(chain, getter_name)):\n                    getter = getattr(chain, getter_name)\n                    if (getter() == kwargs[key]):\n                        return chain\n        return None",
    "docstring": "Find correct filterchain based on generic variables"
  },
  {
    "code": "def findSensor(self, sensors, sensor_name, device_type = None):\r\n        if device_type == None:\r\n            for sensor in sensors:\r\n                if sensor['name'] == sensor_name:\r\n                    return sensor['id']\r\n        else:\r\n            for sensor in sensors:\r\n                if sensor['name'] == sensor_name and sensor['device_type'] == device_type:\r\n                    return sensor['id']\r\n        return None",
    "docstring": "Find a sensor in the provided list of sensors\r\n            \r\n            @param sensors (list) - List of sensors to search in\r\n            @param sensor_name (string) - Name of sensor to find\r\n            @param device_type (string) - Device type of sensor to find, can be None\r\n            \r\n            @return (string) - sensor_id of sensor or None if not found"
  },
  {
    "code": "def register_auth_system(self, auth_system):\n        auth_system_settings = dbconfig.get('auth_system')\n        if auth_system.name not in auth_system_settings['available']:\n            auth_system_settings['available'].append(auth_system.name)\n            dbconfig.set('default', 'auth_system', DBCChoice(auth_system_settings))\n        if auth_system.name == auth_system_settings['enabled'][0]:\n            self.active_auth_system = auth_system\n            auth_system().bootstrap()\n            logger.debug('Registered {} as the active auth system'.format(auth_system.name))\n            return True\n        else:\n            logger.debug('Not trying to load the {} auth system as it is disabled by config'.format(auth_system.name))\n            return False",
    "docstring": "Register a given authentication system with the framework. Returns `True` if the `auth_system` is registered\n        as the active auth system, else `False`\n\n        Args:\n            auth_system (:obj:`BaseAuthPlugin`): A subclass of the `BaseAuthPlugin` class to register\n\n        Returns:\n            `bool`"
  },
  {
    "code": "def _update_with_csrf_disabled(d=None):\n    if d is None:\n        d = {}\n    import flask_wtf\n    from pkg_resources import parse_version\n    supports_meta = parse_version(flask_wtf.__version__) >= parse_version(\n        \"0.14.0\")\n    if supports_meta:\n        d.setdefault('meta', {})\n        d['meta'].update({'csrf': False})\n    else:\n        d['csrf_enabled'] = False\n    return d",
    "docstring": "Update the input dict with CSRF disabled depending on WTF-Form version.\n\n    From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of\n    `meta={csrf: True/False}`."
  },
  {
    "code": "def _rshift_logical(self, shift_amount):\n        if self.is_empty:\n            return self\n        ssplit = self._ssplit()\n        if len(ssplit) == 1:\n            l = self.lower_bound >> shift_amount\n            u = self.upper_bound >> shift_amount\n            stride = max(self.stride >> shift_amount, 1)\n            return StridedInterval(bits=self.bits,\n                                   lower_bound=l,\n                                   upper_bound=u,\n                                   stride=stride,\n                                   uninitialized=self.uninitialized\n                                   )\n        else:\n            a = ssplit[0]._rshift_logical(shift_amount)\n            b = ssplit[1]._rshift_logical(shift_amount)\n            return a.union(b)",
    "docstring": "Logical shift right with a concrete shift amount\n\n        :param int shift_amount: Number of bits to shift right.\n        :return: The new StridedInterval after right shifting\n        :rtype: StridedInterval"
  },
  {
    "code": "def port_pair(self):\n        if self.transport is NotSpecified:\n            return (self.port, \"tcp\")\n        else:\n            return (self.port, self.transport)",
    "docstring": "The port and it's transport as a pair"
  },
  {
    "code": "def collect_all_bucket_keys(self):\n        if len(self.childs) == 0:\n            return [self.bucket_key]\n        result = []\n        for child in self.childs.values():\n            result = result + child.collect_all_bucket_keys()\n        return result",
    "docstring": "Just collects all buckets keys from subtree"
  },
  {
    "code": "def remove_tree(self, dirname):\r\n        while osp.exists(dirname):\r\n            try:\r\n                shutil.rmtree(dirname, onerror=misc.onerror)\r\n            except Exception as e:\r\n                if type(e).__name__ == \"OSError\":\r\n                    error_path = to_text_string(e.filename)\r\n                    shutil.rmtree(error_path, ignore_errors=True)",
    "docstring": "Remove whole directory tree\r\n        Reimplemented in project explorer widget"
  },
  {
    "code": "def remove(self, value):\n\t\ttry:\n\t\t\tindex = self._dict[value]\n\t\texcept KeyError:\n\t\t\traise ValueError('Value \"%s\" is not present.')\n\t\telse:\n\t\t\tdel self[index]",
    "docstring": "Remove value from self.\n\n\t\tArgs:\n\t\t\tvalue: Element to remove from self\n\t\tRaises:\n\t\t\tValueError: if element is already present"
  },
  {
    "code": "def find_related(self, fullname):\n        stack = [fullname]\n        found = set()\n        while stack:\n            name = stack.pop(0)\n            names = self.find_related_imports(name)\n            stack.extend(set(names).difference(set(found).union(stack)))\n            found.update(names)\n        found.discard(fullname)\n        return sorted(found)",
    "docstring": "Return a list of non-stdlib modules that are imported directly or\n        indirectly by `fullname`, plus their parents.\n\n        This method is like :py:meth:`find_related_imports`, but also\n        recursively searches any modules which are imported by `fullname`.\n\n        :param fullname: Fully qualified name of an _already imported_ module\n            for which source code can be retrieved\n        :type fullname: str"
  },
  {
    "code": "def merge_dictionaries(base_dict, extra_dict):\n    new_dict = base_dict.copy()\n    new_dict.update(extra_dict)\n    return new_dict",
    "docstring": "merge two dictionaries.\n\n    if both have a same key, the one from extra_dict is taken\n\n    :param base_dict: first dictionary\n    :type base_dict: dict\n    :param extra_dict: second dictionary\n    :type extra_dict: dict\n    :return: a merge of the two dictionaries\n    :rtype: dicts"
  },
  {
    "code": "def softplus(attrs, inputs, proto_obj):\n    new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type' : 'softrelu'})\n    return 'Activation', new_attrs, inputs",
    "docstring": "Applies the sofplus activation function element-wise to the input."
  },
  {
    "code": "def image_show(self, image_id):\n        nt_ks = self.compute_conn\n        image = nt_ks.images.get(image_id)\n        links = {}\n        for link in image.links:\n            links[link['rel']] = link['href']\n        ret = {\n            'name': image.name,\n            'id': image.id,\n            'status': image.status,\n            'progress': image.progress,\n            'created': image.created,\n            'updated': image.updated,\n            'metadata': image.metadata,\n            'links': links,\n        }\n        if hasattr(image, 'minDisk'):\n            ret['minDisk'] = image.minDisk\n        if hasattr(image, 'minRam'):\n            ret['minRam'] = image.minRam\n        return ret",
    "docstring": "Show image details and metadata"
  },
  {
    "code": "def bcr(eal_original, eal_retrofitted, interest_rate,\n        asset_life_expectancy, asset_value, retrofitting_cost):\n    return ((eal_original - eal_retrofitted) * asset_value *\n            (1 - numpy.exp(- interest_rate * asset_life_expectancy)) /\n            (interest_rate * retrofitting_cost))",
    "docstring": "Compute the Benefit-Cost Ratio.\n\n    BCR = (EALo - EALr)(1-exp(-r*t))/(r*C)\n\n    Where:\n\n    * BCR -- Benefit cost ratio\n    * EALo -- Expected annual loss for original asset\n    * EALr -- Expected annual loss for retrofitted asset\n    * r -- Interest rate\n    * t -- Life expectancy of the asset\n    * C -- Retrofitting cost"
  },
  {
    "code": "def inputAnalyzeCallback(self, *args, **kwargs):\n        b_status            = False\n        filesRead           = 0\n        filesAnalyzed       = 0\n        for k, v in kwargs.items():\n            if k == 'filesRead':    d_DCMRead   = v\n            if k == 'path':         str_path    = v\n        if len(args):\n            at_data         = args[0]\n            str_path        = at_data[0]\n            d_read          = at_data[1]\n        b_status        = True\n        self.dp.qprint(\"analyzing:\\n%s\" % \n                                self.pp.pformat(d_read['l_file']), \n                                level = 5)\n        if int(self.f_sleepLength):\n            self.dp.qprint(\"sleeping for: %f\" % self.f_sleepLength, level = 5)\n            time.sleep(self.f_sleepLength)\n        filesAnalyzed   = len(d_read['l_file'])\n        return {\n            'status':           b_status,\n            'filesAnalyzed':    filesAnalyzed,\n            'l_file':           d_read['l_file']\n        }",
    "docstring": "Test method for inputAnalzeCallback\n\n        This method loops over the passed number of files, \n        and optionally \"delays\" in each loop to simulate\n        some analysis. The delay length is specified by\n        the '--test <delay>' flag."
  },
  {
    "code": "def setup_shiny():\n    name = 'shiny'\n    def _get_shiny_cmd(port):\n        conf = dedent(\n).format(\n            user=getpass.getuser(),\n            port=str(port),\n            site_dir=os.getcwd()\n        )\n        f = tempfile.NamedTemporaryFile(mode='w', delete=False)\n        f.write(conf)\n        f.close()\n        return ['shiny-server', f.name]\n    return {\n        'command': _get_shiny_cmd,\n        'launcher_entry': {\n            'title': 'Shiny',\n            'icon_path': os.path.join(os.path.dirname(os.path.abspath(__file__)), 'icons', 'shiny.svg')\n        }\n    }",
    "docstring": "Manage a Shiny instance."
  },
  {
    "code": "def re_flags_str(flags, custom_flags):\n    res = ''\n    for flag in RE_FLAGS:\n        if flags & getattr(re, flag):\n            res += flag\n    for flag in RE_CUSTOM_FLAGS:\n        if custom_flags & getattr(ReFlags, flag):\n            res += flag\n    return res",
    "docstring": "Convert regexp flags to string.\n\n    Parameters\n    ----------\n    flags : `int`\n        Flags.\n    custom_flags : `int`\n        Custom flags.\n\n    Returns\n    -------\n    `str`\n        Flag string."
  },
  {
    "code": "def merge(self, other_roc):\n        if other_roc.thresholds.size == self.thresholds.size and np.all(other_roc.thresholds == self.thresholds):\n            self.contingency_tables += other_roc.contingency_tables\n        else:\n            print(\"Input table thresholds do not match.\")",
    "docstring": "Ingest the values of another DistributedROC object into this one and update the statistics inplace.\n\n        Args:\n            other_roc: another DistributedROC object."
  },
  {
    "code": "def reapply_sampling_strategies(self):\n        check_sensor = self._inspecting_client.future_check_sensor\n        for sensor_name, strategy in list(self._strategy_cache.items()):\n            try:\n                sensor_exists = yield check_sensor(sensor_name)\n                if not sensor_exists:\n                    self._logger.warn('Did not set strategy for non-existing sensor {}'\n                                      .format(sensor_name))\n                    continue\n                result = yield self.set_sampling_strategy(sensor_name, strategy)\n            except KATCPSensorError as e:\n                self._logger.error('Error reapplying strategy for sensor {0}: {1!s}'\n                                   .format(sensor_name, e))\n            except Exception:\n                self._logger.exception('Unhandled exception reapplying strategy for '\n                                       'sensor {}'.format(sensor_name), exc_info=True)",
    "docstring": "Reapply all sensor strategies using cached values"
  },
  {
    "code": "def segment_radial_dist(seg, pos):\n    return point_dist(pos, np.divide(np.add(seg[0], seg[1]), 2.0))",
    "docstring": "Return the radial distance of a tree segment to a given point\n\n    The radial distance is the euclidian distance between the mid-point of\n    the segment and the point in question.\n\n    Parameters:\n        seg: tree segment\n\n        pos: origin to which distances are measured. It must have at lease 3\n        components. The first 3 components are (x, y, z)."
  },
  {
    "code": "def is_in_team(self, team_id):\n        if self.is_super_admin():\n            return True\n        team_id = uuid.UUID(str(team_id))\n        return team_id in self.teams or team_id in self.child_teams_ids",
    "docstring": "Test if user is in team"
  },
  {
    "code": "def slugify(text, length_limit=0, delimiter=u'-'):\n    result = []\n    for word in _punctuation_regex.split(text.lower()):\n        word = _available_unicode_handlers[0](word)\n        if word:\n            result.append(word)\n    slug = delimiter.join(result)\n    if length_limit > 0:\n        return slug[0:length_limit]\n    return slug",
    "docstring": "Generates an ASCII-only slug of a string."
  },
  {
    "code": "def parse_cookies(self, req: Request, name: str, field: Field) -> typing.Any:\n        return core.get_value(req.cookies, name, field)",
    "docstring": "Pull a value from the cookiejar."
  },
  {
    "code": "def invite_by_email(self, email, sender=None, request=None, **kwargs):\n        try:\n            user = self.user_model.objects.get(email=email)\n        except self.user_model.DoesNotExist:\n            if \"username\" in inspect.getargspec(\n                self.user_model.objects.create_user\n            ).args:\n                user = self.user_model.objects.create(\n                    username=self.get_username(),\n                    email=email,\n                    password=self.user_model.objects.make_random_password(),\n                )\n            else:\n                user = self.user_model.objects.create(\n                    email=email, password=self.user_model.objects.make_random_password()\n                )\n            user.is_active = False\n            user.save()\n        self.send_invitation(user, sender, **kwargs)\n        return user",
    "docstring": "Creates an inactive user with the information we know and then sends\n        an invitation email for that user to complete registration.\n\n        If your project uses email in a different way then you should make to\n        extend this method as it only checks the `email` attribute for Users."
  },
  {
    "code": "def ibis_schema_apply_to(schema, df):\n    for column, dtype in schema.items():\n        pandas_dtype = dtype.to_pandas()\n        col = df[column]\n        col_dtype = col.dtype\n        try:\n            not_equal = pandas_dtype != col_dtype\n        except TypeError:\n            not_equal = True\n        if not_equal or dtype == dt.string:\n            df[column] = convert(col_dtype, dtype, col)\n    return df",
    "docstring": "Applies the Ibis schema to a pandas DataFrame\n\n    Parameters\n    ----------\n    schema : ibis.schema.Schema\n    df : pandas.DataFrame\n\n    Returns\n    -------\n    df : pandas.DataFrame\n\n    Notes\n    -----\n    Mutates `df`"
  },
  {
    "code": "def _raveled_index_for(self, param):\n        from ..param import ParamConcatenation\n        if isinstance(param, ParamConcatenation):\n            return np.hstack((self._raveled_index_for(p) for p in param.params))\n        return param._raveled_index() + self._offset_for(param)",
    "docstring": "get the raveled index for a param\n        that is an int array, containing the indexes for the flattened\n        param inside this parameterized logic.\n\n        !Warning! be sure to call this method on the highest parent of a hierarchy,\n        as it uses the fixes to do its work"
  },
  {
    "code": "def is_of_genus_type(self, genus_type=None):\n        if genus_type is None:\n            raise NullArgument()\n        else:\n            my_genus_type = self.get_genus_type()\n            return (genus_type.get_authority() == my_genus_type.get_authority() and\n                    genus_type.get_identifier_namespace() == my_genus_type.get_identifier_namespace() and\n                    genus_type.get_identifier() == my_genus_type.get_identifier())",
    "docstring": "Tests if this object is of the given genus Type.\n\n        The given genus type may be supported by the object through the\n        type hierarchy.\n\n        | arg:    ``genus_type`` (``osid.type.Type``): a genus type\n        | return: (``boolean``) - true if this object is of the given genus\n                Type,  false otherwise\n        | raise:  ``NullArgument`` - ``genus_type`` is null\n        | *compliance: mandatory - This method must be implemented.*"
  },
  {
    "code": "def on_touch_move(self, touch):\n        if touch is not self._touch:\n            return False\n        self.pos = (\n            touch.x + self.x_down,\n            touch.y + self.y_down\n        )\n        return True",
    "docstring": "Follow the touch"
  },
  {
    "code": "def load_config(fname: str) -> ModelConfig:\n        config = ModelConfig.load(fname)\n        logger.info('ModelConfig loaded from \"%s\"', fname)\n        return cast(ModelConfig, config)",
    "docstring": "Loads model configuration.\n\n        :param fname: Path to load model configuration from.\n        :return: Model configuration."
  },
  {
    "code": "def parse_connection_string(self, connection):\n        if connection == 'c2s_tls':\n            return CONNECTION_XMPP, True, False\n        elif connection == 'c2s_compressed_tls':\n            return CONNECTION_XMPP, True, True\n        elif connection == 'http_bind':\n            return CONNECTION_HTTP_BINDING, None, None\n        elif connection == 'c2s':\n            return CONNECTION_XMPP, False, False\n        log.warn('Could not parse connection string \"%s\"', connection)\n        return CONNECTION_UNKNOWN, True, True",
    "docstring": "Parse string as returned by the ``connected_users_info`` or ``user_sessions_info`` API calls.\n\n        >>> EjabberdBackendBase().parse_connection_string('c2s_tls')\n        (0, True, False)\n        >>> EjabberdBackendBase().parse_connection_string('c2s_compressed_tls')\n        (0, True, True)\n        >>> EjabberdBackendBase().parse_connection_string('http_bind')\n        (2, None, None)\n\n        :param connection: The connection string as returned by the ejabberd APIs.\n        :type  connection: str\n        :return: A tuple representing the conntion type, if it is encrypted and if it uses XMPP stream\n            compression.\n        :rtype: tuple"
  },
  {
    "code": "def _str(self, name, val):\n        s = ''\n        v = Value(val)\n        if name:\n            logger.debug(\"{} is type {}\".format(name, v.typename))\n            try:\n                count = len(val)\n                s = \"{} ({}) = {}\".format(name, count, v.string_value())\n            except (TypeError, KeyError, AttributeError) as e:\n                logger.info(e, exc_info=True)\n                s = \"{} = {}\".format(name, v.string_value())\n        else:\n            s = v.string_value()\n        return s",
    "docstring": "return a string version of name = val that can be printed\n\n        example -- \n            _str('foo', 'bar') # foo = bar\n\n        name -- string -- the variable name that was passed into one of the public methods\n        val -- mixed -- the variable at name's value\n\n        return -- string"
  },
  {
    "code": "def get_creation_date_tags(url, domain, as_dicts=False):\n    creation_date_tags = [\n        mementoweb_api_tags(url),\n        get_whois_tags(domain),\n    ]\n    creation_date_tags = sorted(\n        sum(creation_date_tags, []),\n        key=lambda x: x.date\n    )\n    if not as_dicts:\n        return creation_date_tags\n    return [\n        item._as_dict()\n        for item in creation_date_tags\n    ]",
    "docstring": "Put together all data sources in this module and return it's output.\n\n    Args:\n        url (str): URL of the web. With relative paths and so on.\n        domain (str): Just the domain of the web.\n        as_dicts (bool, default False): Convert output to dictionaries\n            compatible with :class:`.SourceString`?\n\n    Returns:\n        list: Sorted list of :class:`TimeResource` objects or dicts."
  },
  {
    "code": "def _write_migration(self, creator, name, table, create, path):\n        file_ = os.path.basename(creator.create(name, path, table, create))\n        return file_",
    "docstring": "Write the migration file to disk."
  },
  {
    "code": "def is_subfeature_of (parent_property, f):\n    if __debug__:\n        from .property import Property\n        assert isinstance(parent_property, Property)\n        assert isinstance(f, Feature)\n    if not f.subfeature:\n        return False\n    p = f.parent\n    if not p:\n        return False\n    parent_feature = p[0]\n    parent_value = p[1]\n    if parent_feature != parent_property.feature:\n        return False\n    if parent_value and parent_value != parent_property.value:\n        return False\n    return True",
    "docstring": "Return true iff f is an ordinary subfeature of the parent_property's\n        feature, or if f is a subfeature of the parent_property's feature\n        specific to the parent_property's value."
  },
  {
    "code": "def prepare_allseries(self, ramflag: bool = True) -> None:\n        for element in printtools.progressbar(self):\n            element.prepare_allseries(ramflag)",
    "docstring": "Call method |Element.prepare_allseries| of all handled\n        |Element| objects."
  },
  {
    "code": "def format_image(path, options):\n    image = Image.open(path)\n    image_pipeline_results = __pipeline_image(image, options)\n    return image_pipeline_results",
    "docstring": "Formats an image.\n\n    Args:\n        path (str): Path to the image file.\n        options (dict): Options to apply to the image.\n\n    Returns:\n        (list) A list of PIL images. The list will always be of length\n        1 unless resolutions for resizing are provided in the options."
  },
  {
    "code": "def format_assistants_lines(cls, assistants):\n        lines = cls._format_files(assistants, 'assistants')\n        if assistants:\n            lines.append('')\n            assistant = strip_prefix(random.choice(assistants), 'assistants').replace(os.path.sep, ' ').strip()\n            if len(assistants) == 1:\n                strings = ['After you install this DAP, you can find help about the Assistant',\n                           'by running \"da {a} -h\" .']\n            else:\n                strings = ['After you install this DAP, you can find help, for example about the Assistant',\n                           '\"{a}\", by running \"da {a} -h\".']\n            lines.extend([l.format(a=assistant) for l in strings])\n        return lines",
    "docstring": "Return formatted assistants from the given list in human readable form."
  },
  {
    "code": "def _setup_params(self_,**params):\n        self = self_.param.self\n        params_to_instantiate = {}\n        for class_ in classlist(type(self)):\n            if not issubclass(class_, Parameterized):\n                continue\n            for (k,v) in class_.__dict__.items():\n                if isinstance(v,Parameter) and v.instantiate and k!=\"name\":\n                    params_to_instantiate[k]=v\n        for p in params_to_instantiate.values():\n            self.param._instantiate_param(p)\n        for name,val in params.items():\n            desc = self.__class__.get_param_descriptor(name)[0]\n            if not desc:\n                self.param.warning(\"Setting non-parameter attribute %s=%s using a mechanism intended only for parameters\",name,val)\n            setattr(self,name,val)",
    "docstring": "Initialize default and keyword parameter values.\n\n        First, ensures that all Parameters with 'instantiate=True'\n        (typically used for mutable Parameters) are copied directly\n        into each object, to ensure that there is an independent copy\n        (to avoid suprising aliasing errors).  Then sets each of the\n        keyword arguments, warning when any of them are not defined as\n        parameters.\n\n        Constant Parameters can be set during calls to this method."
  },
  {
    "code": "def parse_json(self, page):\n        if not isinstance(page, basestring):\n            page = util.decode_page(page)\n        self.doc = json.loads(page)\n        results = self.doc.get(self.result_name, [])\n        if not results:\n            self.check_status(self.doc.get('status'))\n            return None\n        return results",
    "docstring": "Returns json feed."
  },
  {
    "code": "def identify_datafiles(root,\n                       extensions_to_ignore=None,\n                       directories_to_ignore=None,\n                       files_to_ignore=None):\n    for dirpath, dirnames, filenames in walk(root):\n        for ignore in directories_to_ignore:\n            if ignore in dirnames:\n                dirnames.remove(ignore)\n        for filename in filenames:\n            ignore = False\n            for ext in extensions_to_ignore:\n                if filename.endswith(ext):\n                    ignore = True\n            if filename in files_to_ignore:\n                ignore = True\n            if ignore is False:\n                yield dirpath, filename",
    "docstring": "Identify files that might contain data\n\n    See function IP_verified() for details about optinoal parmeters"
  },
  {
    "code": "def transform(fields, function, *tables):\n    \"Return a new table based on other tables and a transformation function\"\n    new_table = Table(fields=fields)\n    for table in tables:\n        for row in filter(bool, map(lambda row: function(row, table), table)):\n            new_table.append(row)\n    return new_table",
    "docstring": "Return a new table based on other tables and a transformation function"
  },
  {
    "code": "def service_executions(self, name=None, pk=None, scope=None, service=None, **kwargs):\n        request_params = {\n            'name': name,\n            'id': pk,\n            'service': service,\n            'scope': scope\n        }\n        if kwargs:\n            request_params.update(**kwargs)\n        r = self._request('GET', self._build_url('service_executions'), params=request_params)\n        if r.status_code != requests.codes.ok:\n            raise NotFoundError(\"Could not retrieve service executions\")\n        data = r.json()\n        return [ServiceExecution(service_exeuction, client=self) for service_exeuction in data['results']]",
    "docstring": "Retrieve Service Executions.\n\n        If additional `keyword=value` arguments are provided, these are added to the request parameters. Please\n        refer to the documentation of the KE-chain API for additional query parameters.\n\n        :param name: (optional) name to limit the search for\n        :type name: basestring or None\n        :param pk: (optional) primary key or id (UUID) of the service to search for\n        :type pk: basestring or None\n        :param scope: (optional) id (UUID) of the scope to search in\n        :type scope: basestring or None\n        :param service: (optional) service UUID to filter on\n        :type service: basestring or None\n        :param kwargs: (optional) additional search keyword arguments\n        :type kwargs: dict or None\n        :return: a single :class:`models.ServiceExecution` object\n        :raises NotFoundError: When no `ServiceExecution` object is found"
  },
  {
    "code": "def _parse_references(xml):\n    references = []\n    ref_finder = HTMLReferenceFinder(xml)\n    for elm, uri_attr in ref_finder:\n        type_ = _discover_uri_type(elm.get(uri_attr))\n        references.append(Reference(elm, type_, uri_attr))\n    return references",
    "docstring": "Parse the references to ``Reference`` instances."
  },
  {
    "code": "def unoptimize_scope(self, frame):\n        if frame.identifiers.declared:\n            self.writeline('%sdummy(%s)' % (\n                unoptimize_before_dead_code and 'if 0: ' or '',\n                ', '.join('l_' + name for name in frame.identifiers.declared)\n            ))",
    "docstring": "Disable Python optimizations for the frame."
  },
  {
    "code": "def _is_autonomous(indep, exprs):\n    if indep is None:\n        return True\n    for expr in exprs:\n        try:\n            in_there = indep in expr.free_symbols\n        except:\n            in_there = expr.has(indep)\n        if in_there:\n            return False\n    return True",
    "docstring": "Whether the expressions for the dependent variables are autonomous.\n\n    Note that the system may still behave as an autonomous system on the interface\n    of :meth:`integrate` due to use of pre-/post-processors."
  },
  {
    "code": "def _encode_params(kw):\n    args = []\n    for k, v in kw.items():\n        try:\n            qv = v.encode('utf-8') if isinstance(v, unicode) else str(v)\n        except:\n            qv = v\n        args.append('%s=%s' % (k, urlquote(qv)))\n    return '&'.join(args)",
    "docstring": "Encode parameters."
  },
  {
    "code": "def buildingname(ddtt):\n    idf = ddtt.theidf\n    building = idf.idfobjects['building'.upper()][0]\n    return building.Name",
    "docstring": "return building name"
  },
  {
    "code": "def shorten_type(typ):\n    offset = 0\n    for prefix in SHORTEN_TYPE_PREFIXES:\n        if typ.startswith(prefix):\n            if len(prefix) > offset:\n                offset = len(prefix)\n    return typ[offset:]",
    "docstring": "Shorten a type. E.g. drops 'System.'"
  },
  {
    "code": "def _fetch_all(self):\n        if self._result_cache is None:\n            self._result_cache = list(self.iterator())\n            if self._iterable_class == ModelIterable:\n                for x in self._result_cache:\n                    self._set_item_querytime(x)\n        if self._prefetch_related_lookups and not self._prefetch_done:\n            self._prefetch_related_objects()",
    "docstring": "Completely overrides the QuerySet._fetch_all method by adding the\n        timestamp to all objects\n\n        :return: See django.db.models.query.QuerySet._fetch_all for return\n            values"
  },
  {
    "code": "def _split_lines(self):\n        parsed_lines = {}\n        for rt in all_record_types:\n            parsed_lines[rt] = []\n        parsed_lines[0] = []\n        for line in self.lines:\n            linetype = line[0:6]\n            if linetype in all_record_types:\n                parsed_lines[linetype].append(line)\n            else:\n                parsed_lines[0].append(line)\n        self.parsed_lines = parsed_lines\n        self._update_structure_lines()",
    "docstring": "Creates the parsed_lines dict which keeps all record data in document order indexed by the record type."
  },
  {
    "code": "def _expand_sequence(self, seq: List[GridQubit]) -> List[GridQubit]:\n        i = 1\n        while i < len(seq):\n            path = self._find_path_between(seq[i - 1], seq[i], set(seq))\n            if path:\n                seq = seq[:i] + path + seq[i:]\n            else:\n                i += 1\n        return seq",
    "docstring": "Tries to expand given sequence with more qubits.\n\n        Args:\n            seq: Linear sequence of qubits.\n\n        Returns:\n            New continuous linear sequence which contains all the qubits from\n            seq and possibly new qubits inserted in between."
  },
  {
    "code": "def bounds(self, thr=0):\n        min_lat = float(\"inf\")\n        min_lon = float(\"inf\")\n        max_lat = -float(\"inf\")\n        max_lon = -float(\"inf\")\n        for segment in self.segments:\n            milat, milon, malat, malon = segment.bounds(thr=thr)\n            min_lat = min(milat, min_lat)\n            min_lon = min(milon, min_lon)\n            max_lat = max(malat, max_lat)\n            max_lon = max(malon, max_lon)\n        return min_lat, min_lon, max_lat, max_lon",
    "docstring": "Gets the bounds of this segment\n\n        Returns:\n            (float, float, float, float): Bounds, with min latitude, min longitude,\n                max latitude and max longitude"
  },
  {
    "code": "def load_configuration(self):\n        filename = os.path.join(os.path.dirname(__file__), 'templates/spline-loc.yml.j2')\n        with open(filename) as handle:\n            return Adapter(safe_load(handle)).configuration",
    "docstring": "Loading configuration."
  },
  {
    "code": "def events(self, year, simple=False, keys=False):\n        if keys:\n            return self._get('events/%s/keys' % year)\n        else:\n            return [Event(raw) for raw in self._get('events/%s%s' % (year, '/simple' if simple else ''))]",
    "docstring": "Get a list of events in a given year.\n\n        :param year: Year to get events from.\n        :param keys: Get only keys of the events rather than full data.\n        :param simple: Get only vital data.\n        :return: List of string event keys or Event objects."
  },
  {
    "code": "def cublasZherk(handle, uplo, trans, n, k, alpha, A, lda, beta, C, ldc):\n    status = _libcublas.cublasZherk_v2(handle,\n                                       _CUBLAS_FILL_MODE[uplo], \n                                       _CUBLAS_OP[trans],\n                                       n, k, ctypes.byref(ctypes.c_double(alpha)),\n                                       int(A), lda, \n                                       ctypes.byref(ctypes.c_double(beta)),\n                                       int(C), ldc)\n    cublasCheckStatus(status)",
    "docstring": "Rank-k operation on Hermitian matrix."
  },
  {
    "code": "def _prepare_tmp_directory(self, tmp_dir):\n        if tmp_dir:\n            if os.path.exists(tmp_dir):\n                raise SquashError(\n                    \"The '%s' directory already exists, please remove it before you proceed\" % tmp_dir)\n            os.makedirs(tmp_dir)\n        else:\n            tmp_dir = tempfile.mkdtemp(prefix=\"docker-squash-\")\n        self.log.debug(\"Using %s as the temporary directory\" % tmp_dir)\n        return tmp_dir",
    "docstring": "Creates temporary directory that is used to work on layers"
  },
  {
    "code": "def strip_spaces(value, sep=None, join=True):\n    value = value.strip()\n    value = [v.strip() for v in value.split(sep)]\n    join_sep = sep or ' '\n    return join_sep.join(value) if join else value",
    "docstring": "Cleans trailing whitespaces and replaces also multiple whitespaces with a single space."
  },
  {
    "code": "def parse_first_row(row, url_instance):\n        tags = row.xpath(Parser.FIRST_ROW_XPATH)\n        category_url = url_instance.combine(tags[0].get('href'))\n        title = unicode(tags[1].text)\n        torrent_url = tags[1].get('href')\n        str_id = torrent_url.split('details/')[1]\n        str_id = str_id[:-1] if str_id.endswith('/') else str_id\n        torrent_url = url_instance.combine(torrent_url)\n        if len(tags) == 3:\n            category_url += '&external=1'\n            tracked_by = '(external)'\n        else:\n            tracked_by = 'Demonoid'\n        return [str_id, title, tracked_by, category_url, torrent_url]",
    "docstring": "Static method that parses a given table row element by executing `Parser.FIRST_ROW_XPATH` and scrapping torrent's\n        id, title, tracked by status, category url and torrent url. Used specifically with a torrent's first table row.\n\n        :param lxml.HtmlElement row: row to parse\n        :param urls.Url url_instance: Url used to combine base url's with scrapped links from tr\n        :return: scrapped id, title, tracked by status, category url and torrent url\n        :rtype: list"
  },
  {
    "code": "def count(self, stats, value, sample_rate=1):\n        self.update_stats(stats, value, self.SC_COUNT, sample_rate)",
    "docstring": "Updates one or more stats counters by arbitrary value\n\n        >>> client = StatsdClient()\n        >>> client.count('example.counter', 17)"
  },
  {
    "code": "def remove_tar_files(file_list):\n    for f in file_list:\n        if file_exists(f) and f.endswith('.tar'):\n            os.remove(f)",
    "docstring": "Public function that removes temporary tar archive files in a local directory"
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'authors' in _dict:\n            args['authors'] = [\n                Author._from_dict(x) for x in (_dict.get('authors'))\n            ]\n        if 'publication_date' in _dict:\n            args['publication_date'] = _dict.get('publication_date')\n        if 'title' in _dict:\n            args['title'] = _dict.get('title')\n        if 'image' in _dict:\n            args['image'] = _dict.get('image')\n        if 'feeds' in _dict:\n            args['feeds'] = [Feed._from_dict(x) for x in (_dict.get('feeds'))]\n        return cls(**args)",
    "docstring": "Initialize a AnalysisResultsMetadata object from a json dictionary."
  },
  {
    "code": "def handle(self, args):\n        salutation = {\n            'french': 'Bonjour',\n            'spanish': 'Hola',\n            'english': 'Hello',\n        }[args.lang.lower()]\n        output = []\n        for name in args.name:\n            output.append(\"{} {}!\".format(salutation, name))\n        return \"\\n\".join(output)",
    "docstring": "Greet each person by name."
  },
  {
    "code": "def _one_q_state_prep(oneq_state: _OneQState):\n    label = oneq_state.label\n    if label == 'SIC':\n        return _one_q_sic_prep(oneq_state.index, oneq_state.qubit)\n    elif label in ['X', 'Y', 'Z']:\n        return _one_q_pauli_prep(label, oneq_state.index, oneq_state.qubit)\n    else:\n        raise ValueError(f\"Bad state label: {label}\")",
    "docstring": "Prepare a one qubit state.\n\n    Either SIC[0-3], X[0-1], Y[0-1], or Z[0-1]."
  },
  {
    "code": "def process_dataset(dataset, models, **kargs):\n        dset = collections.OrderedDict()\n        for m in MultiFitter.flatten_models(models):\n            dset[m.datatag] = (\n                m.builddataset(dataset) if m.ncg <= 1 else\n                MultiFitter.coarse_grain(m.builddataset(dataset), ncg=m.ncg)\n                )\n        return gvar.dataset.avg_data(dset, **kargs)",
    "docstring": "Convert ``dataset`` to processed data using ``models``.\n\n        :class:`gvar.dataset.Dataset` (or similar dictionary) object\n        ``dataset`` is processed by each model in list ``models``,\n        and the results collected into a new dictionary ``pdata`` for use in\n        :meth:`MultiFitter.lsqfit` and :meth:`MultiFitter.chained_lsqft`.\n        Assumes that the models have defined method\n        :meth:`MultiFitterModel.builddataset`. Keyword arguments\n        ``kargs`` are passed on to :func:`gvar.dataset.avg_data` when\n        averaging the data."
  },
  {
    "code": "def _get_version():\n    version_string = __salt__['cmd.run'](\n        [_check_xbps(), '--version'],\n        output_loglevel='trace')\n    if version_string is None:\n        return False\n    VERSION_MATCH = re.compile(r'(?:XBPS:[\\s]+)([\\d.]+)(?:[\\s]+.*)')\n    version_match = VERSION_MATCH.search(version_string)\n    if not version_match:\n        return False\n    return version_match.group(1).split('.')",
    "docstring": "Get the xbps version"
  },
  {
    "code": "def compliance_report(filepath=None,\n                      string=None,\n                      renderer='jinja|yaml',\n                      **kwargs):\n    validation_string = __salt__['slsutil.renderer'](path=filepath,\n                                                     string=string,\n                                                     default_renderer=renderer,\n                                                     **kwargs)\n    return salt.utils.napalm.call(\n        napalm_device,\n        'compliance_report',\n        validation_source=validation_string\n    )",
    "docstring": "Return the compliance report.\n\n    filepath\n        The absolute path to the validation file.\n\n        .. versionchanged:: 2019.2.0\n\n        Beginning with release codename ``2019.2.0``, this function has been\n        enhanced, to be able to leverage the multi-engine template rendering\n        of Salt, besides the possibility to retrieve the file source from\n        remote systems, the URL schemes supported being:\n\n        - ``salt://``\n        - ``http://`` and ``https://``\n        - ``ftp://``\n        - ``s3://``\n        - ``swift:/``\n\n        Or on the local file system (on the Minion).\n\n        .. note::\n\n            The rendering result does not necessarily need to be YAML, instead\n            it can be any format interpreted by Salt's rendering pipeline\n            (including pure Python).\n\n    string\n        .. versionadded:: 2019.2.0\n\n        The compliance report send as inline string, to be used as the file to\n        send through the renderer system. Note, not all renderer modules can\n        work with strings; the 'py' renderer requires a file, for example.\n\n    renderer: ``jinja|yaml``\n        .. versionadded:: 2019.2.0\n\n        The renderer pipe to send the file through; this is overridden by a\n        \"she-bang\" at the top of the file.\n\n    kwargs\n        .. versionchanged:: 2019.2.0\n\n        Keyword args to pass to Salt's compile_template() function.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' napalm.compliance_report ~/validate.yml\n        salt '*' napalm.compliance_report salt://path/to/validator.sls\n\n    Validation File Example (pure YAML):\n\n    .. code-block:: yaml\n\n        - get_facts:\n            os_version: 4.17\n\n        - get_interfaces_ip:\n            Management1:\n              ipv4:\n                10.0.2.14:\n                  prefix_length: 24\n                _mode: strict\n\n    Validation File Example (as Jinja + YAML):\n\n    .. code-block:: yaml\n\n        - get_facts:\n            os_version: {{ grains.version }}\n        - get_interfaces_ip:\n            Loopback0:\n              ipv4:\n                {{ grains.lo0.ipv4 }}:\n                  prefix_length: 24\n                _mode: strict\n        - get_bgp_neighbors: {{ pillar.bgp.neighbors }}\n\n    Output Example:\n\n    .. code-block:: yaml\n\n        device1:\n            ----------\n            comment:\n            out:\n                ----------\n                complies:\n                    False\n                get_facts:\n                    ----------\n                    complies:\n                        False\n                    extra:\n                    missing:\n                    present:\n                        ----------\n                        os_version:\n                            ----------\n                            actual_value:\n                                15.1F6-S1.4\n                            complies:\n                                False\n                            nested:\n                                False\n                get_interfaces_ip:\n                    ----------\n                    complies:\n                        False\n                    extra:\n                    missing:\n                        - Management1\n                    present:\n                        ----------\n                skipped:\n            result:\n                True"
  },
  {
    "code": "def op_at_on(operation: ops.Operation,\n                 time: Timestamp,\n                 device: Device):\n        return ScheduledOperation(time,\n                                  device.duration_of(operation),\n                                  operation)",
    "docstring": "Creates a scheduled operation with a device-determined duration."
  },
  {
    "code": "def add_coreference(self, coreference):\n        if self.coreference_layer is None:\n            self.coreference_layer = Ccoreferences(type=self.type)\n            self.root.append(self.coreference_layer.get_node())\n        self.coreference_layer.add_coreference(coreference)",
    "docstring": "Adds an coreference to the coreference layer\n        @type coreference: L{Ccoreference}\n        @param coreference: the coreference object"
  },
  {
    "code": "def number(self):\n        return int(math.ceil(self.total_size / float(self.size)))",
    "docstring": "Returns the number of batches the batched sequence contains.\n\n        :rtype: integer."
  },
  {
    "code": "def get_single_keywords(skw_db, fulltext):\n    timer_start = time.clock()\n    records = []\n    for single_keyword in skw_db.values():\n        for regex in single_keyword.regex:\n            for match in regex.finditer(fulltext):\n                span = (match.span()[0], match.span()[1] - 1)\n                records = [record for record in records\n                           if not _contains_span(span, record[0])]\n                add = True\n                for previous_record in records:\n                    if ((span, single_keyword) == previous_record or\n                            _contains_span(previous_record[0], span)):\n                        add = False\n                        break\n                if add:\n                    records.append((span, single_keyword))\n    single_keywords = {}\n    for span, single_keyword in records:\n        single_keywords.setdefault(single_keyword, [[]])\n        single_keywords[single_keyword][0].append(span)\n    current_app.logger.info(\n        \"Matching single keywords... %d keywords found \"\n        \"in %.1f sec.\" % (len(single_keywords), time.clock() - timer_start),\n    )\n    return single_keywords",
    "docstring": "Find single keywords in the fulltext.\n\n    :param skw_db: list of KeywordToken objects\n    :param fulltext: string, which will be searched\n\n    :return : dictionary of matches in a format {\n        <keyword object>, [[position, position...], ],\n        ..\n    }"
  },
  {
    "code": "def create(dataset, target, features=None, validation_set = 'auto',\n        verbose=True):\n    dataset, validation_set = _validate_data(dataset, target, features,\n                                             validation_set)\n    if validation_set is None:\n        validation_set = _turicreate.SFrame()\n    model_proxy = _turicreate.extensions.create_automatic_regression_model(\n        dataset, target, validation_set, {})\n    return _sl.wrap_model_proxy(model_proxy)",
    "docstring": "Automatically create a suitable regression model based on the provided\n    training data.\n\n    To use specific options of a desired model, use the ``create`` function\n    of the corresponding model.\n\n    Parameters\n    ----------\n    dataset : SFrame\n        Dataset for training the model.\n\n    target : str\n        The name of the column in ``dataset`` that is the prediction target.\n        This column must have a numeric type (int/float).\n\n    features : list[string], optional\n        Names of the columns containing features. 'None' (the default) indicates\n        that all columns except the target variable should be used as features.\n\n        The features are columns in the input SFrame that can be of the\n        following types:\n\n        - *Numeric*: values of numeric type integer or float.\n\n        - *Categorical*: values of type string.\n\n        - *Array*: list of numeric (integer or float) values. Each list element\n          is treated as a separate feature in the model.\n\n        - *Dictionary*: key-value pairs with numeric (integer or float) values\n          Each key of a dictionary is treated as a separate feature and the\n          value in the dictionary corresponds to the value of the feature.\n          Dictionaries are ideal for representing sparse data.\n\n        Columns of type *list* are not supported. Convert such feature\n        columns to type array if all entries in the list are of numeric\n        types. If the lists contain data of mixed types, separate\n        them out into different columns.\n\n    validation_set : SFrame, optional\n        A dataset for monitoring the model's generalization performance.  For\n        each row of the progress table, the chosen metrics are computed for\n        both the provided training dataset and the validation_set. The format\n        of this SFrame must be the same as the training set.  By default this\n        argument is set to 'auto' and a validation set is automatically sampled\n        and used for progress printing. If validation_set is set to None, then\n        no additional metrics are computed. The default value is 'auto'.\n\n\n    verbose : boolean, optional\n        If True, print progress information during training.\n\n    Returns\n    -------\n      out : A trained regression model.\n\n    See Also\n    --------\n    turicreate.linear_regression.LinearRegression,\n    turicreate.boosted_trees_regression.BoostedTreesRegression\n\n    Examples\n    --------\n    .. sourcecode:: python\n\n      # Setup the data\n      >>> import turicreate as tc\n      >>> data =  tc.SFrame('https://static.turi.com/datasets/regression/houses.csv')\n\n      # Selects the best model based on your data.\n      >>> model = tc.regression.create(data, target='price',\n      ...                                  features=['bath', 'bedroom', 'size'])\n\n      # Make predictions and evaluate results.\n      >>> predictions = model.predict(data)\n      >>> results = model.evaluate(data)\n\n      # Setup the data\n      >>> import turicreate as tc\n      >>> data =  tc.SFrame('https://static.turi.com/datasets/regression/houses.csv')\n\n      # Selects the best model based on your data.\n      >>> model = tc.regression.create(data, target='price',\n      ...                                  features=['bath', 'bedroom', 'size'])\n\n      # Make predictions and evaluate results.\n      >>> predictions = model.predict(data)\n      >>> results = model.evaluate(data)"
  },
  {
    "code": "def snappy_encode(payload, xerial_compatible=False, xerial_blocksize=32 * 1024):\n    if not has_snappy():\n        raise NotImplementedError(\"Snappy codec is not available\")\n    if xerial_compatible:\n        def _chunker():\n            for i in xrange(0, len(payload), xerial_blocksize):\n                yield payload[i:i + xerial_blocksize]\n        out = BytesIO()\n        header = b''.join([struct.pack('!' + fmt, dat) for fmt, dat\n                           in zip(_XERIAL_V1_FORMAT, _XERIAL_V1_HEADER)])\n        out.write(header)\n        for chunk in _chunker():\n            block = snappy.compress(chunk)\n            block_size = len(block)\n            out.write(struct.pack('!i', block_size))\n            out.write(block)\n        out.seek(0)\n        return out.read()\n    else:\n        return snappy.compress(payload)",
    "docstring": "Encodes the given data with snappy if xerial_compatible is set then the\n       stream is encoded in a fashion compatible with the xerial snappy library\n\n       The block size (xerial_blocksize) controls how frequent the blocking\n       occurs 32k is the default in the xerial library.\n\n       The format winds up being\n        +-------------+------------+--------------+------------+--------------+\n        |   Header    | Block1 len | Block1 data  | Blockn len | Blockn data  |\n        |-------------+------------+--------------+------------+--------------|\n        |  16 bytes   |  BE int32  | snappy bytes |  BE int32  | snappy bytes |\n        +-------------+------------+--------------+------------+--------------+\n\n        It is important to not that the blocksize is the amount of uncompressed\n        data presented to snappy at each block, whereas the blocklen is the\n        number of bytes that will be present in the stream, that is the\n        length will always be <= blocksize."
  },
  {
    "code": "def _get_pdb_id(self, elem, **kwargs):\n        id = elem.attrib['ID']\n        if self.restrict_to_transmembrane_proteins:\n            tmp = elem.attrib['TMP']\n            assert(tmp == 'no' or tmp == 'yes' or tmp == 'not')\n            if tmp == 'yes':\n                self.ids[id] = PDBTM._get_tm_type(elem)\n        else:\n            self.ids[id] = self.ids.get(id, 0) + 1",
    "docstring": "If self.restrict_to_transmembrane_proteins is False then this adds all ids to self.ids. Otherwise, only transmembrane protein ids are added."
  },
  {
    "code": "def create_redis_client(self):\n        return ray.services.create_redis_client(\n            self._redis_address, self._ray_params.redis_password)",
    "docstring": "Create a redis client."
  },
  {
    "code": "def do_authenticate_account(self, authc_token):\n        try:\n            realms = self.token_realm_resolver[authc_token.__class__]\n        except KeyError:\n            raise KeyError('Unsupported Token Type Provided: ', authc_token.__class__.__name__)\n        if (len(self.realms) == 1):\n            account = self.authenticate_single_realm_account(realms[0], authc_token)\n        else:\n            account = self.authenticate_multi_realm_account(self.realms, authc_token)\n        cred_type = authc_token.token_info['cred_type']\n        attempts = account['authc_info'][cred_type].get('failed_attempts', [])\n        self.validate_locked(authc_token, attempts)\n        if len(account['authc_info']) > authc_token.token_info['tier']:\n            if self.mfa_dispatcher:\n                realm = self.token_realm_resolver[TOTPToken][0]\n                totp_token = realm.generate_totp_token(account)\n                mfa_info = account['authc_info']['totp_key']['2fa_info']\n                self.mfa_dispatcher.dispatch(authc_token.identifier,\n                                             mfa_info,\n                                             totp_token)\n            raise AdditionalAuthenticationRequired(account['account_id'])\n        return account",
    "docstring": "Returns an account object only when the current token authenticates AND\n        the authentication process is complete, raising otherwise\n\n        :returns:  Account\n        :raises AdditionalAuthenticationRequired: when additional tokens are required,\n                                                  passing the account object"
  },
  {
    "code": "def connect_reftrack_scenenode(self, refobj, scenenode):\n        conns = [(\"%s.scenenode\" % refobj, \"%s.reftrack\" % scenenode),\n                 (\"%s.taskfile_id\" % scenenode, \"%s.taskfile_id\" % refobj)]\n        for src, dst in conns:\n            if not cmds.isConnected(src, dst):\n                cmds.connectAttr(src, dst, force=True)",
    "docstring": "Connect the given reftrack node with the given scene node\n\n        :param refobj: the reftrack node to connect\n        :type refobj: str\n        :param scenenode: the jb_sceneNode to connect\n        :type scenenode: str\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def download_and_extract_to_mkdtemp(bucket, key, session=None):\n    if session:\n        s3_client = session.client('s3')\n    else:\n        s3_client = boto3.client('s3')\n    transfer = S3Transfer(s3_client)\n    filedes, temp_file = tempfile.mkstemp()\n    os.close(filedes)\n    transfer.download_file(bucket, key, temp_file)\n    output_dir = tempfile.mkdtemp()\n    zip_ref = zipfile.ZipFile(temp_file, 'r')\n    zip_ref.extractall(output_dir)\n    zip_ref.close()\n    os.remove(temp_file)\n    return output_dir",
    "docstring": "Download zip archive and extract it to temporary directory."
  },
  {
    "code": "def _speak_as_spell_out_inherit(self, element):\n        self._reverse_speak_as(element, 'spell-out')\n        self._isolate_text_node(element)\n        self._visit(element, self._speak_as_spell_out)",
    "docstring": "Speak one letter at a time for each word for elements and descendants.\n\n        :param element: The element.\n        :type element: hatemile.util.html.htmldomelement.HTMLDOMElement"
  },
  {
    "code": "def plot_soma3d(ax, soma, color=None, alpha=_ALPHA):\n    color = _get_color(color, tree_type=NeuriteType.soma)\n    if isinstance(soma, SomaCylinders):\n        for start, end in zip(soma.points, soma.points[1:]):\n            common.plot_cylinder(ax,\n                                 start=start[COLS.XYZ], end=end[COLS.XYZ],\n                                 start_radius=start[COLS.R], end_radius=end[COLS.R],\n                                 color=color, alpha=alpha)\n    else:\n        common.plot_sphere(ax, center=soma.center[COLS.XYZ], radius=soma.radius,\n                           color=color, alpha=alpha)\n    _update_3d_datalim(ax, soma)",
    "docstring": "Generates a 3d figure of the soma.\n\n    Args:\n        ax(matplotlib axes): on what to plot\n        soma(neurom.core.Soma): plotted soma\n        color(str or None): Color of plotted values, None corresponds to default choice\n        alpha(float): Transparency of plotted values"
  },
  {
    "code": "def convert_value(value, source_currency, target_currency):\n    if source_currency == target_currency:\n        return value\n    rate = get_rate(source_currency, target_currency)\n    return value * rate",
    "docstring": "Converts the price of a currency to another one using exchange rates\n\n    :param price: the price value\n    :param type: decimal\n\n    :param source_currency: source ISO-4217 currency code\n    :param type: str\n\n    :param target_currency: target ISO-4217 currency code\n    :param type: str\n\n    :returns: converted price instance\n    :rtype: ``Price``"
  },
  {
    "code": "def gsr_path(self):\n        try:\n            return self._gsr_path\n        except AttributeError:\n            path = self.outdir.has_abiext(\"GSR\")\n            if path: self._gsr_path = path\n            return path",
    "docstring": "Absolute path of the GSR file. Empty string if file is not present."
  },
  {
    "code": "def bind_download_buttons(cls):\n        def on_click(ev):\n            button_el = ev.target\n            form_el = button_el.parent.parent.parent\n            content = form_el.get(selector=\"textarea\")[0].text\n            suffix = form_el.name\n            download_path = \"as_file/%s.%s\" % (cls.filename, suffix)\n            form_el.action = join(settings.API_PATH, download_path)\n            input_el = form_el.get(selector=\"input\")[0]\n            input_el.value = content\n        for el in document.get(selector=\"button.output_download_button\"):\n            el.bind(\"click\", on_click)",
    "docstring": "Bind buttons to callbacks."
  },
  {
    "code": "def namedtuple_storable(namedtuple, *args, **kwargs):\n    return default_storable(namedtuple, namedtuple._fields, *args, **kwargs)",
    "docstring": "Storable factory for named tuples."
  },
  {
    "code": "def get_total_time(self):\n        first_step = self.steps[0]\n        last_step = self.steps[-1]\n        seconds = self.history[last_step][\"__timestamp__\"] \\\n                  - self.history[first_step][\"__timestamp__\"]\n        return datetime.timedelta(seconds=seconds)",
    "docstring": "Returns the total period between when the first and last steps\n        where logged. This usually correspnods to the total training time\n        if there were no gaps in the training."
  },
  {
    "code": "def _py3_crc16(value):\n    crc = 0\n    for byte in value:\n        crc = ((crc << 8) & 0xffff) ^ _CRC16_LOOKUP[((crc >> 8) ^ byte) & 0xff]\n    return crc",
    "docstring": "Calculate the CRC for the value in Python 3\n\n    :param bytes value: The value to return for the CRC Checksum\n    :rtype: int"
  },
  {
    "code": "def rename_keys(record: Mapping, key_map: Mapping) -> dict:\n    new_record = dict()\n    for k, v in record.items():\n        key = key_map[k] if k in key_map else k\n        new_record[key] = v\n    return new_record",
    "docstring": "New record with same keys or renamed keys if key found in key_map."
  },
  {
    "code": "def blob(self, sha):\n        url = self._build_url('git', 'blobs', sha, base_url=self._api)\n        json = self._json(self._get(url), 200)\n        return Blob(json) if json else None",
    "docstring": "Get the blob indicated by ``sha``.\n\n        :param str sha: (required), sha of the blob\n        :returns: :class:`Blob <github3.git.Blob>` if successful, otherwise\n            None"
  },
  {
    "code": "def merge_chunk_data(output_file=\"merged_idx_contig_hit_size_cov.txt\", *files):\n    chunks = dict()\n    for chunk_file in files:\n        with open(chunk_file) as chunk_file_handle:\n            for line in chunk_file_handle:\n                chunk_id, chunk_name, hit, size, cov = line.split(\"\\t\")\n                try:\n                    chunks[chunk_id][\"hit\"] += hit\n                    chunks[chunk_id][\"cov\"] += cov\n                except KeyError:\n                    chunks[chunk_id] = {\n                        \"name\": chunk_name,\n                        \"hit\": hit,\n                        \"size\": size,\n                        \"cov\": cov,\n                    }\n    sorted_chunks = sorted(chunks)\n    with open(output_file, \"w\") as output_handle:\n        for chunk_id in sorted_chunks:\n            my_chunk = chunks[chunk_id]\n            name, hit, size, cov = (\n                my_chunk[\"name\"],\n                my_chunk[\"hit\"],\n                my_chunk[\"size\"],\n                my_chunk[\"cov\"],\n            )\n            my_line = \"{}\\t{}\\t{}\\t{}\\t{}\".format(\n                chunk_id, name, hit, size, cov\n            )\n            output_handle.write(my_line)",
    "docstring": "Merge chunk data from different networks\n\n    Similarly to merge_network, this merges any number of chunk data files.\n\n    Parameters\n    ---------\n    output_file : file, str, or pathlib.Path, optional\n        The output file to write the merged chunk data files into. Default is\n        merged_idx_contig_hit_size_cov.txt\n    `*files` : file, str or pathlib.Path\n        The chunk data files to merge."
  },
  {
    "code": "def delete_intf_router(self, name, tenant_id, rout_id, subnet_lst):\n        try:\n            for subnet_id in subnet_lst:\n                body = {'subnet_id': subnet_id}\n                intf = self.neutronclient.remove_interface_router(rout_id,\n                                                                  body=body)\n                intf.get('id')\n        except Exception as exc:\n            LOG.error(\"Failed to delete router interface %(name)s, \"\n                      \" Exc %(exc)s\", {'name': name, 'exc': str(exc)})\n            return False\n        return True",
    "docstring": "Delete the openstack router and remove the interfaces attached."
  },
  {
    "code": "def convert_ascii_field(string):\n    values = []\n    for codepoint in [s for s in string.split(DATA_FILE_CODEPOINT_SEPARATOR) if (s != DATA_FILE_VALUE_NOT_AVAILABLE) and (len(s) > 0)]:\n        if (codepoint.startswith(DATA_FILE_ASCII_NUMERICAL_CODEPOINT_START)) or (codepoint.startswith(DATA_FILE_ASCII_UNICODE_CODEPOINT_START)):\n            values.append(hex_to_unichr(codepoint))\n        else:\n            values.append(codepoint)\n    return values",
    "docstring": "Convert an ASCII field into the corresponding list of Unicode strings.\n\n    The (input) ASCII field is a Unicode string containing\n    one or more ASCII codepoints (``00xx`` or ``U+00xx`` or\n    an ASCII string not starting with ``00`` or ``U+``),\n    separated by a space.\n\n    :param str string: the (input) ASCII field\n    :rtype: list of Unicode strings"
  },
  {
    "code": "def get_service_types(self):\n    resp = self._get_resource_root().get(self._path() + '/serviceTypes')\n    return resp[ApiList.LIST_KEY]",
    "docstring": "Get all service types supported by this cluster.\n\n    @return: A list of service types (strings)"
  },
  {
    "code": "def body_kwargs(self):\n        body_kwargs = {}\n        ct = self.get_header(\"content-type\")\n        if ct:\n            ct = ct.lower()\n            if ct.rfind(\"json\") >= 0:\n                body = self.body\n                if body:\n                    body_kwargs = json.loads(body)\n            else:\n                if self.body_input:\n                    body = RequestBody(\n                        fp=self.body_input,\n                        headers=self.headers,\n                        environ=self.environ\n                    )\n                    body_kwargs = dict(body)\n                else:\n                    body = self.body\n                    if body:\n                        body_kwargs = self._parse_query_str(body)\n        return body_kwargs",
    "docstring": "the request body, if this is a POST request\n\n        this tries to do the right thing with the body, so if you have set the body and\n        the content type is json, then it will return the body json decoded, if you need\n        the original string body, use body\n\n        example --\n\n            self.body = '{\"foo\":{\"name\":\"bar\"}}'\n            b = self.body_kwargs # dict with: {\"foo\": { \"name\": \"bar\"}}\n            print self.body # string with: '{\"foo\":{\"name\":\"bar\"}}'"
  },
  {
    "code": "def set_cursor_pos_callback(window, cbfun):\n    window_addr = ctypes.cast(ctypes.pointer(window),\n                              ctypes.POINTER(ctypes.c_long)).contents.value\n    if window_addr in _cursor_pos_callback_repository:\n        previous_callback = _cursor_pos_callback_repository[window_addr]\n    else:\n        previous_callback = None\n    if cbfun is None:\n        cbfun = 0\n    c_cbfun = _GLFWcursorposfun(cbfun)\n    _cursor_pos_callback_repository[window_addr] = (cbfun, c_cbfun)\n    cbfun = c_cbfun\n    _glfw.glfwSetCursorPosCallback(window, cbfun)\n    if previous_callback is not None and previous_callback[0] != 0:\n        return previous_callback[0]",
    "docstring": "Sets the cursor position callback.\n\n    Wrapper for:\n        GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun);"
  },
  {
    "code": "def substitute_values(self, vect):\n        try:\n            unique = np.unique(vect)\n        except:\n            unique = set(vect)\n        unique = [\n            x for x in unique if not isinstance(x, float) or not isnan(x)\n        ]\n        arr = np.copy(vect)\n        for new_id, value in enumerate(unique):\n            np.place(arr, arr==value, new_id)\n            self.metadata[new_id] = value\n        arr = arr.astype(np.float)\n        np.place(arr, np.isnan(arr), -1)\n        self.arr = arr\n        if -1 in arr:\n            self.metadata[-1] = self._missing_id",
    "docstring": "Internal method to substitute integers into the vector, and construct\n        metadata to convert back to the original vector.\n\n        np.nan is always given -1, all other objects are given integers in\n        order of apperence.\n\n        Parameters\n        ----------\n        vect : np.array\n            the vector in which to substitute values in"
  },
  {
    "code": "def reconstitute_path(drive, folders):\n    reconstituted = os.path.join(drive, os.path.sep, *folders)\n    return reconstituted",
    "docstring": "Reverts a tuple from `get_path_components` into a path.\n\n    :param drive: A drive (eg 'c:'). Only applicable for NT systems\n    :param folders: A list of folder names\n    :return: A path comprising the drive and list of folder names. The path terminate\n             with a `os.path.sep` *only* if it is a root directory"
  },
  {
    "code": "def select(self, limit=0):\n        if limit < 1:\n            limit = None\n        for child in self.get_descendants(self.tag):\n            if self.match(child):\n                yield child\n                if limit is not None:\n                    limit -= 1\n                    if limit < 1:\n                        break",
    "docstring": "Match all tags under the targeted tag."
  },
  {
    "code": "def crypto_sign(msg, sk):\n    if len(sk) != SECRETKEYBYTES:\n        raise ValueError(\"Bad signing key length %d\" % len(sk))\n    vkbytes = sk[PUBLICKEYBYTES:]\n    skbytes = sk[:PUBLICKEYBYTES]\n    sig = djbec.signature(msg, skbytes, vkbytes)\n    return sig + msg",
    "docstring": "Return signature+message given message and secret key.\n    The signature is the first SIGNATUREBYTES bytes of the return value.\n    A copy of msg is in the remainder."
  },
  {
    "code": "def format(self, *args, **kwargs):\n        return self.__class__(super(ColorStr, self).format(*args, **kwargs), keep_tags=True)",
    "docstring": "Return a formatted version, using substitutions from args and kwargs.\n\n        The substitutions are identified by braces ('{' and '}')."
  },
  {
    "code": "def parse_rule(name, rule_text, do_raise=False):\n    try:\n        return rule.parseString(rule_text, parseAll=True)[0]\n    except pyparsing.ParseException as exc:\n        if do_raise:\n            raise\n        log = logging.getLogger('policies')\n        log.warn(\"Failed to parse rule %r: %s\" % (name, exc))\n        log.warn(\"Rule line: %s\" % exc.line)\n        log.warn(\"Location : %s^\" % (\" \" * (exc.col - 1)))\n        return Instructions([Constant(False), set_authz])",
    "docstring": "Parses the given rule text.\n\n    :param name: The name of the rule.  Used when emitting log\n                 messages regarding a failure to parse the rule.\n    :param rule_text: The text of the rule to parse.\n    :param do_raise: If ``False`` and the rule fails to parse, a log\n                     message is emitted to the \"policies\" logger at\n                     level WARN, and a rule that always evaluates to\n                     ``False`` will be returned.  If ``True``, a\n                     ``pyparsing.ParseException`` will be raised.\n\n    :returns: An instance of ``policies.instructions.Instructions``,\n              containing the instructions necessary to evaluate the\n              authorization rule."
  },
  {
    "code": "def get_relationship(self, attribute):\n        rel = self.__relationships.get(attribute.entity_attr)\n        if rel is None:\n            rel = LazyDomainRelationship(self, attribute,\n                                         direction=\n                                            self.relationship_direction)\n            self.__relationships[attribute.entity_attr] = rel\n        return rel",
    "docstring": "Returns the domain relationship object for the given resource\n        attribute."
  },
  {
    "code": "def wrap(start: str, string: str, end: str = \"\") -> str:\n    return f\"{start}{string}{end}\" if string else \"\"",
    "docstring": "Wrap string inside other strings at start and end.\n\n    If the string is not None or empty, then wrap with start and end, otherwise return\n    an empty string."
  },
  {
    "code": "def send_msg(app, msg, reply_cls=None, reply_multi=False):\n    return app.send_request(event.SendMsgRequest(msg=msg,\n                                                 reply_cls=reply_cls,\n                                                 reply_multi=reply_multi))()",
    "docstring": "Send an OpenFlow message and wait for reply messages.\n\n    :param app: Client RyuApp instance\n    :param msg: An OpenFlow controller-to-switch message to send\n    :param reply_cls: OpenFlow message class for expected replies.\n        None means no replies are expected.  The default is None.\n    :param reply_multi: True if multipart replies are expected.\n        The default is False.\n\n    If no replies, returns None.\n    If reply_multi=False, returns OpenFlow switch-to-controller message.\n    If reply_multi=True, returns a list of OpenFlow switch-to-controller\n    messages.\n\n    Raise an exception on error.\n\n    Example::\n\n        # ...(snip)...\n        import ryu.app.ofctl.api as ofctl_api\n\n\n        class MyApp(app_manager.RyuApp):\n\n            def _my_handler(self, ev):\n                # ...(snip)...\n                msg = parser.OFPPortDescStatsRequest(datapath=datapath)\n                result = ofctl_api.send_msg(\n                    self, msg,\n                    reply_cls=parser.OFPPortDescStatsReply,\n                    reply_multi=True)"
  },
  {
    "code": "def is_castable(src, dst):\n    if ((src in [int, bool]) or rdltypes.is_user_enum(src)) and (dst in [int, bool]):\n        return True\n    elif (src == rdltypes.ArrayPlaceholder) and (dst == rdltypes.ArrayPlaceholder):\n        if src.element_type is None:\n            return True\n        elif src.element_type == dst.element_type:\n            return True\n        else:\n            return False\n    elif rdltypes.is_user_struct(dst):\n        return issubclass(src, dst)\n    elif dst == rdltypes.PropertyReference:\n        return issubclass(src, rdltypes.PropertyReference)\n    elif src == dst:\n        return True\n    else:\n        return False",
    "docstring": "Check if src type can be cast to dst type"
  },
  {
    "code": "async def finish_authentication(self, username, password):\n        self.srp.step1(username, password)\n        data = await self._send_plist(\n            'step1', method='pin', user=username)\n        resp = plistlib.loads(data)\n        pub_key, key_proof = self.srp.step2(resp['pk'], resp['salt'])\n        await self._send_plist(\n            'step2',\n            pk=binascii.unhexlify(pub_key),\n            proof=binascii.unhexlify(key_proof))\n        epk, tag = self.srp.step3()\n        await self._send_plist('step3', epk=epk, authTag=tag)\n        return True",
    "docstring": "Finish authentication process.\n\n        A username (generated by new_credentials) and the PIN code shown on\n        screen must be provided."
  },
  {
    "code": "def _get_section(self, name, create=True):\n        try:\n            return self.sections[name]\n        except KeyError:\n            if not create:\n                raise\n            section = Section(name)\n            self.sections[name] = section\n            return section",
    "docstring": "Retrieve a section by name. Create it on first access."
  },
  {
    "code": "def get_iso2_from_iso3(cls, iso3, use_live=True, exception=None):\n        countriesdata = cls.countriesdata(use_live=use_live)\n        iso2 = countriesdata['iso2iso3'].get(iso3.upper())\n        if iso2 is not None:\n            return iso2\n        if exception is not None:\n            raise exception\n        return None",
    "docstring": "Get ISO2 from ISO3 code\n\n        Args:\n            iso3 (str): ISO3 code for which to get ISO2 code\n            use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.\n            exception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults to None.\n\n        Returns:\n            Optional[str]: ISO2 code"
  },
  {
    "code": "def get_service_id_list() -> List[tuple]:\n    keys = DB.get_keys('states*')\n    services = []\n    for key in keys:\n        values = key.split(':')\n        if len(values) == 4:\n            services.append(':'.join(values[1:]))\n    return services",
    "docstring": "Return list of Services."
  },
  {
    "code": "def get_plural_name(cls):\n        if not hasattr(cls.Meta, 'plural_name'):\n            setattr(\n                cls.Meta,\n                'plural_name',\n                inflection.pluralize(cls.get_name())\n            )\n        return cls.Meta.plural_name",
    "docstring": "Get the serializer's plural name.\n\n        The plural name may be defined on the Meta class.\n        If the plural name is not defined,\n        the pluralized form of the name will be returned."
  },
  {
    "code": "def get_all_published_ships_basic(db_connection):\n    if not hasattr(get_all_published_ships_basic, '_results'):\n        sql = 'CALL get_all_published_ships_basic();'\n        results = execute_sql(sql, db_connection)\n        get_all_published_ships_basic._results = results\n    return get_all_published_ships_basic._results",
    "docstring": "Gets a list of all published ships and their basic information.\n\n    :return: Each result has a tuple of (typeID, typeName, groupID, groupName, categoryID, and categoryName).\n    :rtype: list"
  },
  {
    "code": "def _resample_residuals(self, stars, epsf):\n        shape = (stars.n_good_stars, epsf.shape[0], epsf.shape[1])\n        star_imgs = np.zeros(shape)\n        for i, star in enumerate(stars.all_good_stars):\n            star_imgs[i, :, :] = self._resample_residual(star, epsf)\n        return star_imgs",
    "docstring": "Compute normalized residual images for all the input stars.\n\n        Parameters\n        ----------\n        stars : `EPSFStars` object\n            The stars used to build the ePSF.\n\n        epsf : `EPSFModel` object\n            The ePSF model.\n\n        Returns\n        -------\n        star_imgs : 3D `~numpy.ndarray`\n            A 3D cube containing the resampled residual images."
  },
  {
    "code": "def resource_create_ticket(self, token, id, scopes, **kwargs):\n        data = dict(resource_id=id, resource_scopes=scopes, **kwargs)\n        return self._realm.client.post(\n            self.well_known['permission_endpoint'],\n            data=self._dumps([data]),\n            headers=self.get_headers(token)\n        )",
    "docstring": "Create a ticket form permission to resource.\n\n        https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_protection_permission_api_papi\n\n        :param str token: user access token\n        :param str id: resource id\n        :param list scopes: scopes access is wanted\n        :param dict claims: (optional)\n        :rtype: dict"
  },
  {
    "code": "def prebuild_arch(self, arch):\n        path = self.get_build_dir(arch.arch)\n        if not exists(path):\n            info(\"creating {}\".format(path))\n            shprint(sh.mkdir, '-p', path)",
    "docstring": "Make the build and target directories"
  },
  {
    "code": "def do_propset(self, subcmd, opts, *args):\n        print \"'svn %s' opts: %s\" % (subcmd, opts)\n        print \"'svn %s' args: %s\" % (subcmd, args)",
    "docstring": "Set PROPNAME to PROPVAL on files, dirs, or revisions.\n\n        usage:\n            1. propset PROPNAME [PROPVAL | -F VALFILE] PATH...\n            2. propset PROPNAME --revprop -r REV [PROPVAL | -F VALFILE] [URL]\n        \n        1. Creates a versioned, local propchange in working copy.\n        2. Creates an unversioned, remote propchange on repos revision.\n        \n        Note: svn recognizes the following special versioned properties\n        but will store any arbitrary properties set:\n          svn:ignore     - A newline separated list of file patterns to ignore.\n          svn:keywords   - Keywords to be expanded.  Valid keywords are:\n            URL, HeadURL             - The URL for the head version of the object.\n            Author, LastChangedBy    - The last person to modify the file.\n            Date, LastChangedDate    - The date/time the object was last modified.\n            Rev, Revision,           - The last revision the object changed.\n            LastChangedRevision\n            Id                       - A compressed summary of the previous\n                                         4 keywords.\n          svn:executable - If present, make the file executable. This\n            property cannot be set on a directory.  A non-recursive attempt\n            will fail, and a recursive attempt will set the property only\n            on the file children of the directory.\n          svn:eol-style  - One of 'native', 'LF', 'CR', 'CRLF'.\n          svn:mime-type  - The mimetype of the file.  Used to determine\n            whether to merge the file, and how to serve it from Apache.\n            A mimetype beginning with 'text/' (or an absent mimetype) is\n            treated as text.  Anything else is treated as binary.\n          svn:externals  - A newline separated list of module specifiers,\n            each of which consists of a relative directory path, optional\n            revision flags, and an URL.  For example\n              foo             http://example.com/repos/zig\n              foo/bar -r 1234 http://example.com/repos/zag\n\n        ${cmd_option_list}"
  },
  {
    "code": "def delete(self, story, params={}, **options): \n        path = \"/stories/%s\" % (story)\n        return self.client.delete(path, params, **options)",
    "docstring": "Deletes a story. A user can only delete stories they have created. Returns an empty data record.\n\n        Parameters\n        ----------\n        story : {Id} Globally unique identifier for the story."
  },
  {
    "code": "def _createMagConversionDict():\n    magnitude_conversion_filepath = resource_stream(__name__, 'data/magnitude_conversion.dat')\n    raw_table = np.loadtxt(magnitude_conversion_filepath, '|S5')\n    magDict = {}\n    for row in raw_table:\n        if sys.hexversion >= 0x03000000:\n            starClass = row[1].decode(\"utf-8\")\n            tableData = [x.decode(\"utf-8\") for x in row[3:]]\n        else:\n            starClass = row[1]\n            tableData = row[3:]\n        magDict[starClass] = tableData\n    return magDict",
    "docstring": "loads magnitude_conversion.dat which is table A% 1995ApJS..101..117K"
  },
  {
    "code": "def poll_events(self):\n        while self.started:\n            event_obj = None\n            event_name = None\n            try:\n                event_obj = self._sl4a.eventWait(50000)\n            except:\n                if self.started:\n                    print(\"Exception happened during polling.\")\n                    print(traceback.format_exc())\n                    raise\n            if not event_obj:\n                continue\n            elif 'name' not in event_obj:\n                print(\"Received Malformed event {}\".format(event_obj))\n                continue\n            else:\n                event_name = event_obj['name']\n            if event_name in self.handlers:\n                self.handle_subscribed_event(event_obj, event_name)\n            if event_name == \"EventDispatcherShutdown\":\n                self._sl4a.closeSl4aSession()\n                break\n            else:\n                self.lock.acquire()\n                if event_name in self.event_dict:\n                    self.event_dict[event_name].put(event_obj)\n                else:\n                    q = queue.Queue()\n                    q.put(event_obj)\n                    self.event_dict[event_name] = q\n                self.lock.release()",
    "docstring": "Continuously polls all types of events from sl4a.\n\n        Events are sorted by name and store in separate queues.\n        If there are registered handlers, the handlers will be called with\n        corresponding event immediately upon event discovery, and the event\n        won't be stored. If exceptions occur, stop the dispatcher and return"
  },
  {
    "code": "def pop(self):\n        if self._length == 0:\n            raise IndexError()\n        newvec = ImmutableVector()\n        newvec.tree = self.tree.remove(self._length-1)\n        newvec._length = self._length-1\n        return newvec",
    "docstring": "Return a new ImmutableVector with the last item removed."
  },
  {
    "code": "def dpotri(A, lower=1):\n    A = force_F_ordered(A)\n    R, info = lapack.dpotri(A, lower=lower)\n    symmetrify(R)\n    return R, info",
    "docstring": "Wrapper for lapack dpotri function\n\n    DPOTRI - compute the inverse of a real symmetric positive\n      definite matrix A using the Cholesky factorization A =\n      U**T*U or A = L*L**T computed by DPOTRF\n\n    :param A: Matrix A\n    :param lower: is matrix lower (true) or upper (false)\n    :returns: A inverse"
  },
  {
    "code": "def required(cls):\n        columns = []\n        for column in cls.__table__.columns:\n            is_autoincrement = 'int' in str(column.type).lower() and column.autoincrement\n            if (not column.nullable and not column.primary_key) or (column.primary_key and not is_autoincrement):\n                columns.append(column.name)\n        return columns",
    "docstring": "Return a list of all columns required by the database to create the\n        resource.\n\n        :param cls: The Model class to gather attributes from\n        :rtype: list"
  },
  {
    "code": "def GetDataStream(self, name, case_sensitive=True):\n    if not isinstance(name, py2to3.STRING_TYPES):\n      raise ValueError('Name is not a string.')\n    name_lower = name.lower()\n    matching_data_stream = None\n    for data_stream in self._GetDataStreams():\n      if data_stream.name == name:\n        return data_stream\n      if not case_sensitive and data_stream.name.lower() == name_lower:\n        if not matching_data_stream:\n          matching_data_stream = data_stream\n    return matching_data_stream",
    "docstring": "Retrieves a data stream by name.\n\n    Args:\n      name (str): name of the data stream.\n      case_sensitive (Optional[bool]): True if the name is case sensitive.\n\n    Returns:\n      DataStream: a data stream or None if not available.\n\n    Raises:\n      ValueError: if the name is not string."
  },
  {
    "code": "async def scan(self):\n        atvs = await pyatv.scan_for_apple_tvs(\n            self.loop, timeout=self.args.scan_timeout, only_usable=False)\n        _print_found_apple_tvs(atvs)\n        return 0",
    "docstring": "Scan for Apple TVs on the network."
  },
  {
    "code": "def getIRThreshold(self):\n    command = '$GO'\n    threshold = self.sendCommand(command)\n    if threshold[0] == 'NK':\n      return 0\n    else:\n      return float(threshold[2])/10",
    "docstring": "Returns the IR temperature threshold in degrees Celcius, or 0 if no Threshold is set"
  },
  {
    "code": "def removeReliableListener(self, listener):\n        self.store.query(_ReliableListener,\n                         attributes.AND(_ReliableListener.processor == self,\n                                        _ReliableListener.listener == listener)).deleteFromStore()\n        self.store.query(BatchProcessingError,\n                         attributes.AND(BatchProcessingError.processor == self,\n                                        BatchProcessingError.listener == listener)).deleteFromStore()",
    "docstring": "Remove a previously added listener."
  },
  {
    "code": "def exp2(x, context=None):\n    return _apply_function_in_current_context(\n        BigFloat,\n        mpfr.mpfr_exp2,\n        (BigFloat._implicit_convert(x),),\n        context,\n    )",
    "docstring": "Return two raised to the power x."
  },
  {
    "code": "def __edge_weight(edge_id, dfs_data):\n    graph = dfs_data['graph']\n    edge_lookup = dfs_data['edge_lookup']\n    edge = graph.get_edge(edge_id)\n    u, v = edge['vertices']\n    d_u = D(u, dfs_data)\n    d_v = D(v, dfs_data)\n    lp_1 = L1(v, dfs_data)\n    d_lp_1 = D(lp_1, dfs_data)\n    if edge_lookup[edge_id] == 'backedge' and d_v < d_u:\n        return 2*d_v\n    elif is_type_I_branch(u, v, dfs_data):\n        return 2*d_lp_1\n    elif is_type_II_branch(u, v, dfs_data):\n        return 2*d_lp_1 + 1\n    else:\n        return 2*graph.num_nodes() + 1",
    "docstring": "Calculates the edge weight used to sort edges."
  },
  {
    "code": "def make_summaries(self):\n        self.summary_df = save_summaries(self.frames, self.keys,\n                                         self.selected_summaries,\n                                         self.batch_dir, self.name)\n        logger.debug(\"made and saved summaries\")",
    "docstring": "Make and save summary csv files,\n        each containing values from all cells"
  },
  {
    "code": "async def fetch_api_description(\n        url: typing.Union[str, ParseResult, SplitResult],\n        insecure: bool = False):\n    url_describe = urljoin(_ensure_url_string(url), \"describe/\")\n    connector = aiohttp.TCPConnector(verify_ssl=(not insecure))\n    session = aiohttp.ClientSession(connector=connector)\n    async with session, session.get(url_describe) as response:\n        if response.status != HTTPStatus.OK:\n            raise RemoteError(\n                \"{0} -> {1.status} {1.reason}\".format(\n                    url, response))\n        elif response.content_type != \"application/json\":\n            raise RemoteError(\n                \"Expected application/json, got: %s\"\n                % response.content_type)\n        else:\n            return await response.json()",
    "docstring": "Fetch the API description from the remote MAAS instance."
  },
  {
    "code": "def _connect(self, key, spec, via=None):\n        try:\n            method = getattr(self.router, spec['method'])\n        except AttributeError:\n            raise Error('unsupported method: %(transport)s' % spec)\n        context = method(via=via, unidirectional=True, **spec['kwargs'])\n        if via and spec.get('enable_lru'):\n            self._update_lru(context, spec, via)\n        mitogen.core.listen(context, 'disconnect',\n            lambda: self._on_context_disconnect(context))\n        self._send_module_forwards(context)\n        init_child_result = context.call(\n            ansible_mitogen.target.init_child,\n            log_level=LOG.getEffectiveLevel(),\n            candidate_temp_dirs=self._get_candidate_temp_dirs(),\n        )\n        if os.environ.get('MITOGEN_DUMP_THREAD_STACKS'):\n            from mitogen import debug\n            context.call(debug.dump_to_logger)\n        self._key_by_context[context] = key\n        self._refs_by_context[context] = 0\n        return {\n            'context': context,\n            'via': via,\n            'init_child_result': init_child_result,\n            'msg': None,\n        }",
    "docstring": "Actual connect implementation. Arranges for the Mitogen connection to\n        be created and enqueues an asynchronous call to start the forked task\n        parent in the remote context.\n\n        :param key:\n            Deduplication key representing the connection configuration.\n        :param spec:\n            Connection specification.\n        :returns:\n            Dict like::\n\n                {\n                    'context': mitogen.core.Context or None,\n                    'via': mitogen.core.Context or None,\n                    'init_child_result': {\n                        'fork_context': mitogen.core.Context,\n                        'home_dir': str or None,\n                    },\n                    'msg': str or None\n                }\n\n            Where `context` is a reference to the newly constructed context,\n            `init_child_result` is the result of executing\n            :func:`ansible_mitogen.target.init_child` in that context, `msg` is\n            an error message and the remaining fields are :data:`None`, or\n            `msg` is :data:`None` and the remaining fields are set."
  },
  {
    "code": "def corr(sim=None, obs=None, node=None, skip_nan=False):\n    sim, obs = prepare_arrays(sim, obs, node, skip_nan)\n    return numpy.corrcoef(sim, obs)[0, 1]",
    "docstring": "Calculate the product-moment correlation coefficient after Pearson.\n\n    >>> from hydpy import round_\n    >>> from hydpy import corr\n    >>> round_(corr(sim=[0.5, 1.0, 1.5], obs=[1.0, 2.0, 3.0]))\n    1.0\n    >>> round_(corr(sim=[4.0, 2.0, 0.0], obs=[1.0, 2.0, 3.0]))\n    -1.0\n    >>> round_(corr(sim=[1.0, 2.0, 1.0], obs=[1.0, 2.0, 3.0]))\n    0.0\n\n    See the documentation on function |prepare_arrays| for some\n    additional instructions for use of function |corr|."
  },
  {
    "code": "def set_state(self, updater=None, **kwargs):\n        if callable(updater):\n            state_change = updater(self)\n        elif updater is not None:\n            state_change = updater\n        else:\n            state_change = kwargs\n        return [callback_result\n                for k, v in state_change.items()\n                for callback_result in self.set(k, v)]",
    "docstring": "Update the datastore.\n\n        :param func|dict updater: (state) => state_change or dict state_change\n        :rtype: Iterable[tornado.concurrent.Future]"
  },
  {
    "code": "def validateURL(self, url):\n        url_parts = _parseURL(url)\n        if url_parts is None:\n            return False\n        proto, host, port, path = url_parts\n        if proto != self.proto:\n            return False\n        if port != self.port:\n            return False\n        if '*' in host:\n            return False\n        if not self.wildcard:\n            if host != self.host:\n                return False\n        elif ((not host.endswith(self.host)) and\n              ('.' + host) != self.host):\n            return False\n        if path != self.path:\n            path_len = len(self.path)\n            trust_prefix = self.path[:path_len]\n            url_prefix = path[:path_len]\n            if trust_prefix != url_prefix:\n                return False\n            if '?' in self.path:\n                allowed = '&'\n            else:\n                allowed = '?/'\n            return (self.path[-1] in allowed or\n                path[path_len] in allowed)\n        return True",
    "docstring": "Validates a URL against this trust root.\n\n\n        @param url: The URL to check\n\n        @type url: C{str}\n\n\n        @return: Whether the given URL is within this trust root.\n\n        @rtype: C{bool}"
  },
  {
    "code": "def _set_tk_config(self, keys, value):\n        if isinstance(keys, str):\n            keys = [keys]\n        for key in keys:\n            if key in self.tk.keys():\n                if value is None:\n                    self.tk[key] = self._tk_defaults[key]\n                else:\n                    self.tk[key] = value",
    "docstring": "Gets the config from the widget's tk object\n\n        :param string/List keys:\n            The tk config key or a list of tk keys.\n\n        :param variable value:\n            The value to set. If the value is `None`, the config value will be\n            reset to its default."
  },
  {
    "code": "def get_deep_features(audio_data, verbose=True):\n    from ._audio_feature_extractor import _get_feature_extractor\n    if not _is_audio_data_sarray(audio_data):\n        raise TypeError(\"Input must be audio data\")\n    feature_extractor_name = 'VGGish'\n    feature_extractor = _get_feature_extractor(feature_extractor_name)\n    return feature_extractor.get_deep_features(audio_data, verbose=verbose)",
    "docstring": "Calculates the deep features used by the Sound Classifier.\n\n    Internally the Sound Classifier calculates deep features for both model\n    creation and predictions. If the same data will be used multiple times,\n    calculating the deep features just once will result in a significant speed\n    up.\n\n    Parameters\n    ----------\n    audio_data : SArray\n        Audio data is represented as dicts with key 'data' and 'sample_rate',\n        see `turicreate.load_audio(...)`.\n\n    Examples\n    --------\n    >>> my_audio_data['deep_features'] = get_deep_features(my_audio_data['audio'])\n    >>> train, test = my_audio_data.random_split(.8)\n    >>> model = tc.sound_classifier.create(train, 'label', 'deep_features')\n    >>> predictions = model.predict(test)"
  },
  {
    "code": "def enable_vt_mode(filehandle=None):\n    if filehandle is None:\n        filehandle = msvcrt.get_osfhandle(sys.__stdout__.fileno())\n    current_mode = wintypes.DWORD()\n    KERNEL32.GetConsoleMode(filehandle, ctypes.byref(current_mode))\n    new_mode = 0x0004 | current_mode.value\n    KERNEL32.SetConsoleMode(filehandle, new_mode)",
    "docstring": "Enables virtual terminal processing mode for the given console or stdout"
  },
  {
    "code": "def check_function_semantics(self, line: str, position: int, tokens: ParseResults) -> ParseResults:\n        if not self._namespace_dict or NAMESPACE not in tokens:\n            return tokens\n        namespace, name = tokens[NAMESPACE], tokens[NAME]\n        if namespace in self.identifier_parser.namespace_to_pattern:\n            return tokens\n        if self._allow_naked_names and tokens[NAMESPACE] == DIRTY:\n            return tokens\n        valid_functions = set(itt.chain.from_iterable(\n            belns_encodings.get(k, set())\n            for k in self._namespace_dict[namespace][name]\n        ))\n        if not valid_functions:\n            raise InvalidEntity(self.get_line_number(), line, position, namespace, name)\n        if tokens[FUNCTION] not in valid_functions:\n            raise InvalidFunctionSemantic(self.get_line_number(), line, position, tokens[FUNCTION], namespace, name,\n                                          valid_functions)\n        return tokens",
    "docstring": "Raise an exception if the function used on the tokens is wrong.\n\n        :raises: InvalidFunctionSemantic"
  },
  {
    "code": "def nodes_with_recipe(recipename):\n    nodes = [n['name'] for n in\n             lib.get_nodes_with_recipe(recipename, env.chef_environment)]\n    if not len(nodes):\n        print(\"No nodes found with recipe '{0}'\".format(recipename))\n        sys.exit(0)\n    return node(*nodes)",
    "docstring": "Configures a list of nodes that have the given recipe in their run list"
  },
  {
    "code": "def content_id(self) -> Optional[UnstructuredHeader]:\n        try:\n            return cast(UnstructuredHeader, self[b'content-id'][0])\n        except (KeyError, IndexError):\n            return None",
    "docstring": "The ``Content-Id`` header."
  },
  {
    "code": "def ToResponse(self, columns_order=None, order_by=(), tqx=\"\"):\n    tqx_dict = {}\n    if tqx:\n      tqx_dict = dict(opt.split(\":\") for opt in tqx.split(\";\"))\n    if tqx_dict.get(\"version\", \"0.6\") != \"0.6\":\n      raise DataTableException(\n          \"Version (%s) passed by request is not supported.\"\n          % tqx_dict[\"version\"])\n    if tqx_dict.get(\"out\", \"json\") == \"json\":\n      response_handler = tqx_dict.get(\"responseHandler\",\n                                      \"google.visualization.Query.setResponse\")\n      return self.ToJSonResponse(columns_order, order_by,\n                                 req_id=tqx_dict.get(\"reqId\", 0),\n                                 response_handler=response_handler)\n    elif tqx_dict[\"out\"] == \"html\":\n      return self.ToHtml(columns_order, order_by)\n    elif tqx_dict[\"out\"] == \"csv\":\n      return self.ToCsv(columns_order, order_by)\n    elif tqx_dict[\"out\"] == \"tsv-excel\":\n      return self.ToTsvExcel(columns_order, order_by)\n    else:\n      raise DataTableException(\n          \"'out' parameter: '%s' is not supported\" % tqx_dict[\"out\"])",
    "docstring": "Writes the right response according to the request string passed in tqx.\n\n    This method parses the tqx request string (format of which is defined in\n    the documentation for implementing a data source of Google Visualization),\n    and returns the right response according to the request.\n    It parses out the \"out\" parameter of tqx, calls the relevant response\n    (ToJSonResponse() for \"json\", ToCsv() for \"csv\", ToHtml() for \"html\",\n    ToTsvExcel() for \"tsv-excel\") and passes the response function the rest of\n    the relevant request keys.\n\n    Args:\n      columns_order: Optional. Passed as is to the relevant response function.\n      order_by: Optional. Passed as is to the relevant response function.\n      tqx: Optional. The request string as received by HTTP GET. Should be in\n           the format \"key1:value1;key2:value2...\". All keys have a default\n           value, so an empty string will just do the default (which is calling\n           ToJSonResponse() with no extra parameters).\n\n    Returns:\n      A response string, as returned by the relevant response function.\n\n    Raises:\n      DataTableException: One of the parameters passed in tqx is not supported."
  },
  {
    "code": "def dst_to_src(self, dst_file):\n        m = re.match(self.dst_path + \"/(.*)$\", dst_file)\n        if (m is None):\n            return(None)\n        rel_path = m.group(1)\n        return(self.src_uri + '/' + rel_path)",
    "docstring": "Return the src URI from the dst filepath.\n\n        This does not rely on the destination filepath actually\n        existing on the local filesystem, just on pattern matching.\n        Return source URI on success, None on failure."
  },
  {
    "code": "def height_max(self, height_max):\n        if height_max is None:\n            self._height_limits[1] = None\n            return\n        height_max = float(height_max)\n        assert(0 <= self.height_min <= height_max)\n        self._height_limits[1] = height_max\n        self._update_layout()",
    "docstring": "Set the maximum height of the widget.\n\n        Parameters\n        ----------\n        height_max: None | float\n            the maximum height of the widget. if None, maximum height\n            is unbounded"
  },
  {
    "code": "def build_conflict_dict(key_list, val_list):\n    key_to_vals = defaultdict(list)\n    for key, val in zip(key_list, val_list):\n        key_to_vals[key].append(val)\n    return key_to_vals",
    "docstring": "Builds dict where a list of values is associated with more than one key\n\n    Args:\n        key_list (list):\n        val_list (list):\n\n    Returns:\n        dict: key_to_vals\n\n    CommandLine:\n        python -m utool.util_dict --test-build_conflict_dict\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_dict import *  # NOQA\n        >>> import utool as ut\n        >>> key_list = [  1,   2,   2,   3,   1]\n        >>> val_list = ['a', 'b', 'c', 'd', 'e']\n        >>> key_to_vals = build_conflict_dict(key_list, val_list)\n        >>> result = ut.repr4(key_to_vals)\n        >>> print(result)\n        {\n            1: ['a', 'e'],\n            2: ['b', 'c'],\n            3: ['d'],\n        }"
  },
  {
    "code": "def get_instance_type(self, port):\n        if port[portbindings.VNIC_TYPE] == portbindings.VNIC_BAREMETAL:\n            return a_const.BAREMETAL_RESOURCE\n        owner_to_type = {\n            n_const.DEVICE_OWNER_DHCP: a_const.DHCP_RESOURCE,\n            n_const.DEVICE_OWNER_DVR_INTERFACE: a_const.ROUTER_RESOURCE,\n            trunk_consts.TRUNK_SUBPORT_OWNER: a_const.VM_RESOURCE}\n        if port['device_owner'] in owner_to_type.keys():\n            return owner_to_type[port['device_owner']]\n        elif port['device_owner'].startswith(\n                n_const.DEVICE_OWNER_COMPUTE_PREFIX):\n            return a_const.VM_RESOURCE\n        return None",
    "docstring": "Determine the port type based on device owner and vnic type"
  },
  {
    "code": "def add_param(self, param_name, layer_index, blob_index):\n        blobs = self.layers[layer_index].blobs\n        self.dict_param[param_name] = mx.nd.array(caffe.io.blobproto_to_array(blobs[blob_index]))",
    "docstring": "Add a param to the .params file"
  },
  {
    "code": "def get_taf_remarks(txt: str) -> (str, str):\n    remarks_start = find_first_in_list(txt, TAF_RMK)\n    if remarks_start == -1:\n        return txt, ''\n    remarks = txt[remarks_start:]\n    txt = txt[:remarks_start].strip()\n    return txt, remarks",
    "docstring": "Returns report and remarks separated if found"
  },
  {
    "code": "def raw_connection_from(engine_or_conn):\n    if hasattr(engine_or_conn, 'cursor'):\n        return engine_or_conn, False\n    if hasattr(engine_or_conn, 'connection'):\n        return engine_or_conn.connection, False\n    return engine_or_conn.raw_connection(), True",
    "docstring": "Extract a raw_connection and determine if it should be automatically closed.\n\n    Only connections opened by this package will be closed automatically."
  },
  {
    "code": "def _update_log_record(self, record):\n    if not hasattr(record, 'hostname'):\n        record.hostname = '-'\n    if not hasattr(record, 'job_id'):\n        record.job_id = self.job_id",
    "docstring": "Massage a log record before emitting it. Intended to be used by the\n    custom log handlers defined in this module."
  },
  {
    "code": "def __add_recent_file(self, fname):\r\n        if fname is None:\r\n            return\r\n        if fname in self.recent_files:\r\n            self.recent_files.remove(fname)\r\n        self.recent_files.insert(0, fname)\r\n        if len(self.recent_files) > self.get_option('max_recent_files'):\r\n            self.recent_files.pop(-1)",
    "docstring": "Add to recent file list"
  },
  {
    "code": "def download_safe_format(product_id=None, tile=None, folder='.', redownload=False, entire_product=False, bands=None,\n                         data_source=DataSource.SENTINEL2_L1C):\n    entire_product = entire_product and product_id is None\n    if tile is not None:\n        safe_request = AwsTileRequest(tile=tile[0], time=tile[1], data_folder=folder, bands=bands,\n                                      safe_format=True, data_source=data_source)\n        if entire_product:\n            safe_tile = safe_request.get_aws_service()\n            product_id = safe_tile.get_product_id()\n    if product_id is not None:\n        safe_request = AwsProductRequest(product_id, tile_list=[tile[0]], data_folder=folder, bands=bands,\n                                         safe_format=True) if entire_product else \\\n            AwsProductRequest(product_id, data_folder=folder, bands=bands, safe_format=True)\n    safe_request.save_data(redownload=redownload)",
    "docstring": "Downloads .SAFE format structure in form of nested dictionaries. Either ``product_id`` or ``tile`` must\n    be specified.\n\n    :param product_id: original ESA product identification string. Default is ``None``\n    :type product_id: str\n    :param tile: tuple containing tile name and sensing time/date. Default is ``None``\n    :type tile: (str, str)\n    :param folder: location of the directory where the fetched data will be saved. Default is ``'.'``\n    :type folder: str\n    :param redownload: if ``True``, download again the requested data even though it's already saved to disk. If\n                       ``False``, do not download if data is already available on disk. Default is ``False``\n    :type redownload: bool\n    :param entire_product: in case tile is specified this flag determines if it will be place inside a .SAFE structure\n                           of the product. Default is ``False``\n    :type entire_product: bool\n    :param bands: list of bands to download. If ``None`` all bands will be downloaded. Default is ``None``\n    :type bands: list(str) or None\n    :param data_source: In case of tile request the source of satellite data has to be specified. Default is Sentinel-2\n                        L1C data.\n    :type data_source: constants.DataSource\n    :return: Nested dictionaries representing .SAFE structure.\n    :rtype: dict"
  },
  {
    "code": "def _check_choices_attribute(self):\n        if self.choices:\n            warning_params = {\n                'msg': (\n                    \"'choices' contains an invalid time zone value '{value}' \"\n                    \"which was not found as a supported time zone by pytz \"\n                    \"{version}.\"\n                ),\n                'hint': \"Values must be found in pytz.all_timezones.\",\n                'obj': self,\n            }\n            for option_key, option_value in self.choices:\n                if isinstance(option_value, (list, tuple)):\n                    for optgroup_key in map(lambda x: x[0], option_value):\n                        if optgroup_key not in pytz.all_timezones:\n                            if optgroup_key not in self.empty_values:\n                                warning_params.update({\n                                    'msg': warning_params['msg'].format(\n                                        value=optgroup_key,\n                                        version=pytz.VERSION\n                                    )\n                                })\n                                return [\n                                    checks.Warning(**warning_params)\n                                ]\n                elif option_key not in pytz.all_timezones:\n                    if option_key not in self.empty_values:\n                        warning_params.update({\n                            'msg': warning_params['msg'].format(\n                                value=option_key,\n                                version=pytz.VERSION\n                            )\n                        })\n                        return [\n                            checks.Warning(**warning_params)\n                        ]\n        return []",
    "docstring": "Checks to make sure that choices contains valid timezone choices."
  },
  {
    "code": "def cookie(\n        url,\n        name,\n        value,\n        expires=None):\n    u = urlparse(url)\n    domain = u.hostname\n    if '.' not in domain and not _is_ip_addr(domain):\n        domain += \".local\"\n    port = str(u.port) if u.port is not None else None\n    secure = u.scheme == 'https'\n    if expires is not None:\n        if expires.tzinfo is not None:\n            raise ValueError('Cookie expiration must be a naive datetime')\n        expires = (expires - datetime(1970, 1, 1)).total_seconds()\n    return http_cookiejar.Cookie(\n        version=0,\n        name=name,\n        value=value,\n        port=port,\n        port_specified=port is not None,\n        domain=domain,\n        domain_specified=True,\n        domain_initial_dot=False,\n        path=u.path,\n        path_specified=True,\n        secure=secure,\n        expires=expires,\n        discard=False,\n        comment=None,\n        comment_url=None,\n        rest=None,\n        rfc2109=False,\n    )",
    "docstring": "Return a new Cookie using a slightly more\n    friendly API than that provided by six.moves.http_cookiejar\n\n    @param name The cookie name {str}\n    @param value The cookie value {str}\n    @param url The URL path of the cookie {str}\n    @param expires The expiry time of the cookie {datetime}. If provided,\n        it must be a naive timestamp in UTC."
  },
  {
    "code": "def convert_tensor_float_to_float16(tensor):\n    if not isinstance(tensor, onnx_proto.TensorProto):\n        raise ValueError('Expected input type is an ONNX TensorProto but got %s' % type(tensor))\n    if tensor.data_type == onnx_proto.TensorProto.FLOAT:\n        tensor.data_type = onnx_proto.TensorProto.FLOAT16\n        if tensor.float_data:\n            int_list = _npfloat16_to_int(np.float16(tensor.float_data))\n            tensor.int32_data[:] = int_list\n            tensor.float_data[:] = []\n        if tensor.raw_data:\n            float32_list = np.fromstring(tensor.raw_data, dtype='float32')\n            float16_list = np.float16(float32_list)\n            tensor.raw_data = float16_list.tostring()\n    return tensor",
    "docstring": "Convert tensor float to float16.\n\n    :param tensor: TensorProto object\n    :return tensor_float16: converted TensorProto object\n\n    Example:\n\n    ::\n\n        from onnxmltools.utils.float16_converter import convert_tensor_float_to_float16\n        new_tensor = convert_tensor_float_to_float16(tensor)"
  },
  {
    "code": "def get_distance(self, node):\n        delta = (node.pos[0]-self.pos[0], node.pos[1]-self.pos[1])\n        return sqrt(delta[0]**2+delta[1]**2)",
    "docstring": "Get the distance beetween 2 nodes\n\n        Args:\n            node (object): The other node."
  },
  {
    "code": "def portfolio(self) -> List[PortfolioItem]:\n        account = self.wrapper.accounts[0]\n        return [v for v in self.wrapper.portfolio[account].values()]",
    "docstring": "List of portfolio items of the default account."
  },
  {
    "code": "def _is_homogeneous_type(self):\n        if self._data.any_extension_types:\n            return len({block.dtype for block in self._data.blocks}) == 1\n        else:\n            return not self._data.is_mixed_type",
    "docstring": "Whether all the columns in a DataFrame have the same type.\n\n        Returns\n        -------\n        bool\n\n        Examples\n        --------\n        >>> DataFrame({\"A\": [1, 2], \"B\": [3, 4]})._is_homogeneous_type\n        True\n        >>> DataFrame({\"A\": [1, 2], \"B\": [3.0, 4.0]})._is_homogeneous_type\n        False\n\n        Items with the same type but different sizes are considered\n        different types.\n\n        >>> DataFrame({\n        ...    \"A\": np.array([1, 2], dtype=np.int32),\n        ...    \"B\": np.array([1, 2], dtype=np.int64)})._is_homogeneous_type\n        False"
  },
  {
    "code": "async def jsk_retain(self, ctx: commands.Context, *, toggle: bool = None):\n        if toggle is None:\n            if self.retain:\n                return await ctx.send(\"Variable retention is set to ON.\")\n            return await ctx.send(\"Variable retention is set to OFF.\")\n        if toggle:\n            if self.retain:\n                return await ctx.send(\"Variable retention is already set to ON.\")\n            self.retain = True\n            self._scope = Scope()\n            return await ctx.send(\"Variable retention is ON. Future REPL sessions will retain their scope.\")\n        if not self.retain:\n            return await ctx.send(\"Variable retention is already set to OFF.\")\n        self.retain = False\n        return await ctx.send(\"Variable retention is OFF. Future REPL sessions will dispose their scope when done.\")",
    "docstring": "Turn variable retention for REPL on or off.\n\n        Provide no argument for current status."
  },
  {
    "code": "def load_json(file, new_root_dir=None, decompression=False):\n    if decompression:\n        with open(file, 'rb') as f:\n            my_object = load(f, decompression=decompression)\n    else:\n        with open(file, 'r') as f:\n            my_object = load(f, decompression=decompression)\n    if new_root_dir:\n        my_object.root_dir = new_root_dir\n    return my_object",
    "docstring": "Load a JSON file using json_tricks"
  },
  {
    "code": "def _os_dispatch(func, *args, **kwargs):\n    if __grains__['kernel'] in SUPPORTED_BSD_LIKE:\n        kernel = 'bsd'\n    else:\n        kernel = __grains__['kernel'].lower()\n    _os_func = getattr(sys.modules[__name__], '_{0}_{1}'.format(kernel, func))\n    if callable(_os_func):\n        return _os_func(*args, **kwargs)",
    "docstring": "Internal, dispatches functions by operating system"
  },
  {
    "code": "def unpack(d):\n    p = SBP._parser.parse(d)\n    assert p.preamble == SBP_PREAMBLE, \"Invalid preamble 0x%x.\" % p.preamble\n    return SBP(p.msg_type, p.sender, p.length, p.payload, p.crc)",
    "docstring": "Unpack and return a framed binary message."
  },
  {
    "code": "def create_permissao_administrativa(self):\n        return PermissaoAdministrativa(\n            self.networkapi_url,\n            self.user,\n            self.password,\n            self.user_ldap)",
    "docstring": "Get an instance of permissao_administrativa services facade."
  },
  {
    "code": "def dependencies_order_of_build(target_contract, dependencies_map):\n    if not dependencies_map:\n        return [target_contract]\n    if target_contract not in dependencies_map:\n        raise ValueError('no dependencies defined for {}'.format(target_contract))\n    order = [target_contract]\n    todo = list(dependencies_map[target_contract])\n    while todo:\n        target_contract = todo.pop(0)\n        target_pos = len(order)\n        for dependency in dependencies_map[target_contract]:\n            if dependency in order:\n                target_pos = order.index(dependency)\n            else:\n                todo.append(dependency)\n        order.insert(target_pos, target_contract)\n    order.reverse()\n    return order",
    "docstring": "Return an ordered list of contracts that is sufficient to successfully\n    deploy the target contract.\n\n    Note:\n        This function assumes that the `dependencies_map` is an acyclic graph."
  },
  {
    "code": "def get_nexusport_binding(port_id, vlan_id, switch_ip, instance_id):\n    LOG.debug(\"get_nexusport_binding() called\")\n    return _lookup_all_nexus_bindings(port_id=port_id,\n                                      vlan_id=vlan_id,\n                                      switch_ip=switch_ip,\n                                      instance_id=instance_id)",
    "docstring": "Lists a nexusport binding."
  },
  {
    "code": "def pubsub_pub(self, topic, payload, **kwargs):\n        args = (topic, payload)\n        return self._client.request('/pubsub/pub', args,\n                                    decoder='json', **kwargs)",
    "docstring": "Publish a message to a given pubsub topic\n\n        Publishing will publish the given payload (string) to\n        everyone currently subscribed to the given topic.\n\n        All data (including the id of the publisher) is automatically\n        base64 encoded when published.\n\n        .. code-block:: python\n\n            # publishes the message 'message' to the topic 'hello'\n            >>> c.pubsub_pub('hello', 'message')\n            []\n\n        Parameters\n        ----------\n        topic : str\n            Topic to publish to\n        payload : Data to be published to the given topic\n\n        Returns\n        -------\n            list : empty list"
  },
  {
    "code": "def add_config_paths(**kwargs):\n    for k, path in kwargs.items():\n        if not os.path.exists(path):\n            raise ValueError(\n                'Configuration file \"{}\" does not exist'.format(k))\n        if k in cf.get_option('config_paths'):\n            raise ValueError('Configuration {!r} already exists'.format(k))\n    kwargs.update(**cf.get_option('config_paths'))\n    cf.set_option('config_paths', kwargs)",
    "docstring": "Add to the pool of available configuration files for BIDSLayout.\n\n    Args:\n        kwargs: dictionary specifying where to find additional config files.\n            Keys are names, values are paths to the corresponding .json file.\n\n    Example:\n        > add_config_paths(my_config='/path/to/config')\n        > layout = BIDSLayout('/path/to/bids', config=['bids', 'my_config'])"
  },
  {
    "code": "def _write_to_command_buffer(self, to_write):\n        np.copyto(self._command_bool_ptr, True)\n        to_write += '0'\n        input_bytes = str.encode(to_write)\n        for index, val in enumerate(input_bytes):\n            self._command_buffer_ptr[index] = val",
    "docstring": "Write input to the command buffer.  Reformat input string to the correct format.\n\n        Args:\n            to_write (str): The string to write to the command buffer."
  },
  {
    "code": "def _is_replacement_allowed(self, s):\n        if any(tag in s.parent_tags for tag in self.skipped_tags):\n            return False\n        if any(tag not in self.textflow_tags for tag in s.involved_tags):\n            return False\n        return True",
    "docstring": "Tests whether replacement is allowed on given piece of HTML text."
  },
  {
    "code": "def clean_global_runtime_state(reset_subsystem=False):\n  if reset_subsystem:\n    Subsystem.reset()\n  Goal.clear()\n  BuildConfigInitializer.reset()",
    "docstring": "Resets the global runtime state of a pants runtime for cleaner forking.\n\n  :param bool reset_subsystem: Whether or not to clean Subsystem global state."
  },
  {
    "code": "def register_logger(self, logger):\n        handler = CommandHandler(self)\n        handler.setFormatter(CommandFormatter())\n        logger.handlers = [handler]\n        logger.propagate = False\n        output = self.output\n        level = logging.WARNING\n        if output.is_debug():\n            level = logging.DEBUG\n        elif output.is_very_verbose() or output.is_verbose():\n            level = logging.INFO\n        logger.setLevel(level)",
    "docstring": "Register a new logger."
  },
  {
    "code": "def handle_routine(self, que, opts, host, target, mine=False):\n        opts = copy.deepcopy(opts)\n        single = Single(\n                opts,\n                opts['argv'],\n                host,\n                mods=self.mods,\n                fsclient=self.fsclient,\n                thin=self.thin,\n                mine=mine,\n                **target)\n        ret = {'id': single.id}\n        stdout, stderr, retcode = single.run()\n        try:\n            data = salt.utils.json.find_json(stdout)\n            if len(data) < 2 and 'local' in data:\n                ret['ret'] = data['local']\n            else:\n                ret['ret'] = {\n                    'stdout': stdout,\n                    'stderr': stderr,\n                    'retcode': retcode,\n                }\n        except Exception:\n            ret['ret'] = {\n                'stdout': stdout,\n                'stderr': stderr,\n                'retcode': retcode,\n            }\n        que.put(ret)",
    "docstring": "Run the routine in a \"Thread\", put a dict on the queue"
  },
  {
    "code": "def main():\n    parser = argparse.ArgumentParser(description='Run SSOIS and return the available images in a particular filter.')\n    parser.add_argument(\"--filter\",\n                        action=\"store\",\n                        default='r',\n                        dest=\"filter\",\n                        choices=['r', 'u'],\n                        help=\"Passband: default is r.\")\n    parser.add_argument(\"--family\", '-f',\n                        action=\"store\",\n                        default=None,\n                        help='List of objects to query.')\n    parser.add_argument(\"--member\", '-m',\n                        action=\"store\",\n                        default=None,\n                        help='Member object of family to query.')\n    args = parser.parse_args()\n    if args.family != None and args.member == None:\n        get_family_info(str(args.family), args.filter)\n    elif args.family == None and args.member != None:\n        get_member_info(str(args.member), args.filter)\n    else:\n        print \"Please input either a family or single member name\"",
    "docstring": "Input asteroid family, filter type, and image type to query SSOIS"
  },
  {
    "code": "def parse(self, rrstr):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('CL record already initialized!')\n        (su_len, su_entry_version_unused, child_log_block_num_le, child_log_block_num_be) = struct.unpack_from('=BBLL', rrstr[:12], 2)\n        if su_len != RRCLRecord.length():\n            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on rock ridge extension')\n        if child_log_block_num_le != utils.swab_32bit(child_log_block_num_be):\n            raise pycdlibexception.PyCdlibInvalidISO('Little endian block num does not equal big endian; corrupt ISO')\n        self.child_log_block_num = child_log_block_num_le\n        self._initialized = True",
    "docstring": "Parse a Rock Ridge Child Link record out of a string.\n\n        Parameters:\n         rrstr - The string to parse the record out of.\n        Returns:\n         Nothing."
  },
  {
    "code": "def list_ptr_records(self, device):\n        device_type = self._resolve_device_type(device)\n        href, svc_name = self._get_ptr_details(device, device_type)\n        uri = \"/rdns/%s?href=%s\" % (svc_name, href)\n        try:\n            resp, resp_body = self._retry_get(uri)\n        except exc.NotFound:\n            return []\n        records = [CloudDNSPTRRecord(rec, device)\n                for rec in resp_body.get(\"records\", [])]\n        return records",
    "docstring": "Returns a list of all PTR records configured for this device."
  },
  {
    "code": "def serialize(self, sw):\n        detail = None\n        if self.detail is not None: \n            detail = Detail()\n            detail.any = self.detail\n        pyobj = FaultType(self.code, self.string, self.actor, detail)\n        sw.serialize(pyobj, typed=False)",
    "docstring": "Serialize the object."
  },
  {
    "code": "def kwargs(self):\n        keywords = self.keywords or []\n        return [keyword for keyword in keywords if keyword.arg is None]",
    "docstring": "The keyword arguments that unpack something.\n\n        :type: list(Keyword)"
  },
  {
    "code": "def _apply_base_theme(app):\n    if QT_VERSION < (5,):\n        app.setStyle('plastique')\n    else:\n        app.setStyle('Fusion')\n    with open(_STYLESHEET) as stylesheet:\n        app.setStyleSheet(stylesheet.read())",
    "docstring": "Apply base theme to the application.\n\n        Args:\n            app (QApplication): QApplication instance."
  },
  {
    "code": "def add_dataset(self, dataset, datasets_to_check=None):\n        showcase_dataset = self._get_showcase_dataset_dict(dataset)\n        if datasets_to_check is None:\n            datasets_to_check = self.get_datasets()\n        for dataset in datasets_to_check:\n            if showcase_dataset['package_id'] == dataset['id']:\n                return False\n        self._write_to_hdx('associate', showcase_dataset, 'package_id')\n        return True",
    "docstring": "Add a dataset\n\n        Args:\n            dataset (Union[Dataset,Dict,str]): Either a dataset id or dataset metadata either from a Dataset object or a dictionary\n            datasets_to_check (List[Dataset]): List of datasets against which to check existence of dataset. Defaults to datasets in showcase.\n\n        Returns:\n            bool: True if the dataset was added, False if already present"
  },
  {
    "code": "def requiredUnless(col_name, arg, dm, df, *args):\n    if col_name in df.columns:\n        return None\n    arg_list = arg.split(\",\")\n    arg_list = [argument.strip('\"') for argument in arg_list]\n    msg = \"\"\n    for a in arg_list:\n        if \".\" in a:\n            continue\n        if a not in df.columns:\n            msg += \"{} column is required unless {} is present.  \".format(col_name, a)\n    if msg:\n        return msg\n    else:\n        return None\n    return None",
    "docstring": "Arg is a string in the format \"str1, str2, ...\"\n    Each string will be a column name.\n    Col_name is required in df unless each column from arg is present."
  },
  {
    "code": "def mold_id_to_path(self, mold_id, default=_marker):\n        def handle_default(debug_msg=None):\n            if debug_msg:\n                logger.debug('mold_id_to_path:' + debug_msg, mold_id)\n            if default is _marker:\n                raise KeyError(\n                    'Failed to lookup mold_id %s to a path' % mold_id)\n            return default\n        result = self.molds.get(mold_id)\n        if result:\n            return result\n        if not self.tracked_entry_points:\n            return handle_default()\n        try:\n            prefix, mold_basename = mold_id.split('/')\n        except ValueError:\n            return handle_default(\n                'mold_id %s not found and not in standard format')\n        entry_point = self.tracked_entry_points.get(prefix)\n        if entry_point is None:\n            return handle_default()\n        return join(self._entry_point_to_path(entry_point), mold_basename)",
    "docstring": "Lookup the filesystem path of a mold identifier."
  },
  {
    "code": "def convert_coord_object(coord):\n    assert isinstance(coord, Coordinate)\n    coord = coord.container()\n    return Tile(int(coord.zoom), int(coord.column), int(coord.row))",
    "docstring": "Convert ModestMaps.Core.Coordinate -> raw_tiles.tile.Tile"
  },
  {
    "code": "def add_loghandler (handler):\n    format = \"%(levelname)s %(name)s %(asctime)s %(threadName)s %(message)s\"\n    handler.setFormatter(logging.Formatter(format))\n    logging.getLogger(LOG_ROOT).addHandler(handler)\n    logging.getLogger().addHandler(handler)",
    "docstring": "Add log handler to root logger and LOG_ROOT and set formatting."
  },
  {
    "code": "def outputs_of(self, idx, create=False):\n        if create and not idx in self.edges:\n            self.edges[idx] = set()\n        return self.edges[idx]",
    "docstring": "Get a set of the outputs for a given node index."
  },
  {
    "code": "def localortho(lon, lat):\n    local_srs = osr.SpatialReference()\n    local_proj = '+proj=ortho +lat_0=%0.7f +lon_0=%0.7f +datum=WGS84 +units=m +no_defs ' % (lat, lon)\n    local_srs.ImportFromProj4(local_proj)\n    return local_srs",
    "docstring": "Create srs for local orthographic projection centered at lat, lon"
  },
  {
    "code": "def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True):\n        return (not matchTags or\n                (self.tagSet.isSuperTagSetOf(other.tagSet)) and\n                 (not matchConstraints or self.subtypeSpec.isSuperTypeOf(other.subtypeSpec)))",
    "docstring": "Examine |ASN.1| type for subtype relationship with other ASN.1 type.\n\n        ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints\n        (:py:mod:`~pyasn1.type.constraint`) are examined when carrying\n        out ASN.1 types comparison.\n\n        Python class inheritance relationship is NOT considered.\n\n        Parameters\n        ----------\n            other: a pyasn1 type object\n                Class instance representing ASN.1 type.\n\n        Returns\n        -------\n            : :class:`bool`\n                :class:`True` if *other* is a subtype of |ASN.1| type,\n                :class:`False` otherwise."
  },
  {
    "code": "def group_theta(node_length, node_idx):\n    theta = -np.pi + node_idx * 2 * np.pi / node_length\n    return theta",
    "docstring": "Returns an angle corresponding to a node of interest.\n\n    Intended to be used for placing node group labels at the correct spot.\n\n    :param float node_length: total number of nodes in the graph.\n    :param int node_idx: the index of the node of interest.\n    :returns: theta -- the angle of the node of interest in radians."
  },
  {
    "code": "def copy_path_flat(self):\n        path = cairo.cairo_copy_path_flat(self._pointer)\n        result = list(_iter_path(path))\n        cairo.cairo_path_destroy(path)\n        return result",
    "docstring": "Return a flattened copy of the current path\n\n        This method is like :meth:`copy_path`\n        except that any curves in the path will be approximated\n        with piecewise-linear approximations,\n        (accurate to within the current tolerance value,\n        see :meth:`set_tolerance`).\n        That is,\n        the result is guaranteed to not have any elements\n        of type :obj:`CURVE_TO <PATH_CURVE_TO>`\n        which will instead be replaced by\n        a series of :obj:`LINE_TO <PATH_LINE_TO>` elements.\n\n        :returns:\n            A list of ``(path_operation, coordinates)`` tuples.\n            See :meth:`copy_path` for the data structure."
  },
  {
    "code": "def end_coordsys(self):\n        coordsys = copy(self.location)\n        coordsys.origin = self.end_point\n        return coordsys",
    "docstring": "Coordinate system at end of effect.\n\n        All axes are parallel to the original vector evaluation location, with\n        the origin moved to this effect's end point.\n\n        :return: coordinate system at end of effect\n        :rtype: :class:`CoordSys`"
  },
  {
    "code": "def is_model_admin_subclass(node):\n    if node.name[-5:] != 'Admin' or isinstance(node.parent, ClassDef):\n        return False\n    return node_is_subclass(node, 'django.contrib.admin.options.ModelAdmin')",
    "docstring": "Checks that node is derivative of ModelAdmin class."
  },
  {
    "code": "def cache_as_field(cache_name):\n    def cache_wrapper(func):\n        @functools.wraps(func)\n        def inner_wrapper(self, *args, **kwargs):\n            value = getattr(self, cache_name, UndefToken)\n            if value != UndefToken:\n                return value\n            ret = func(self, *args, **kwargs)\n            setattr(self, cache_name, ret)\n            return ret\n        return inner_wrapper\n    return cache_wrapper",
    "docstring": "Cache a functions return value as the field 'cache_name'."
  },
  {
    "code": "async def stop(self, wait_for_completion=True):\n        await self.set_position(\n            position=CurrentPosition(),\n            wait_for_completion=wait_for_completion)",
    "docstring": "Stop window.\n\n        Parameters:\n            * wait_for_completion: If set, function will return\n                after device has reached target position."
  },
  {
    "code": "def range(self, axis=None):\n        return (self.min(axis=axis), self.max(axis=axis))",
    "docstring": "Return range tuple along specified axis"
  },
  {
    "code": "def single_download_photos(photos):\n    global counter\n    counter = len(photos)\n    for photo in photos:\n        download_photo(photo)",
    "docstring": "Use single process to download photos\n\n    :param photos: The photos to be downloaded\n    :type photos: list of dicts"
  },
  {
    "code": "def execute(self):\n        logging.info('Requesting view metadata for project %s' % self.project_name)\n        project_csv_meta = self.rws_connection.send_request(ProjectMetaDataRequest(self.project_name))\n        self.db_adapter.processMetaData(project_csv_meta)\n        for dataset_name in self.db_adapter.datasets.keys():\n            logging.info('Requesting data from dataset %s' % dataset_name)\n            form_name, _type = self.name_type_from_viewname(dataset_name)\n            form_data = self.rws_connection.send_request(\n                FormDataRequest(self.project_name, self.environment, _type, form_name))\n            logging.info('Populating dataset %s' % dataset_name)\n            self.db_adapter.processFormData(form_data, dataset_name)\n        logging.info('Process complete')",
    "docstring": "Generate local DB, pulling metadata and data from RWSConnection"
  },
  {
    "code": "def cci(series, window=14):\n    price = typical_price(series)\n    typical_mean = rolling_mean(price, window)\n    res = (price - typical_mean) / (.015 * np.std(typical_mean))\n    return pd.Series(index=series.index, data=res)",
    "docstring": "compute commodity channel index"
  },
  {
    "code": "def listFunctions(self, dbName=None):\n        if dbName is None:\n            dbName = self.currentDatabase()\n        iter = self._jcatalog.listFunctions(dbName).toLocalIterator()\n        functions = []\n        while iter.hasNext():\n            jfunction = iter.next()\n            functions.append(Function(\n                name=jfunction.name(),\n                description=jfunction.description(),\n                className=jfunction.className(),\n                isTemporary=jfunction.isTemporary()))\n        return functions",
    "docstring": "Returns a list of functions registered in the specified database.\n\n        If no database is specified, the current database is used.\n        This includes all temporary functions."
  },
  {
    "code": "def enable_mac(self, app=None):\n        def inputhook_mac(app=None):\n            if self.pyplot_imported:\n                pyplot = sys.modules['matplotlib.pyplot']\n                try:\n                    pyplot.pause(0.01)\n                except:\n                    pass\n            else:\n                if 'matplotlib.pyplot' in sys.modules:\n                    self.pyplot_imported = True\n        self.set_inputhook(inputhook_mac)\n        self._current_gui = GUI_OSX",
    "docstring": "Enable event loop integration with MacOSX.\n\n        We call function pyplot.pause, which updates and displays active\n        figure during pause. It's not MacOSX-specific, but it enables to\n        avoid inputhooks in native MacOSX backend.\n        Also we shouldn't import pyplot, until user does it. Cause it's\n        possible to choose backend before importing pyplot for the first\n        time only."
  },
  {
    "code": "def remove_transcript_preferences(course_id):\n    try:\n        transcript_preference = TranscriptPreference.objects.get(course_id=course_id)\n        transcript_preference.delete()\n    except TranscriptPreference.DoesNotExist:\n        pass",
    "docstring": "Deletes course-wide transcript preferences.\n\n    Arguments:\n        course_id(str): course id"
  },
  {
    "code": "def fixed_terms(self):\n        return {k: v for (k, v) in self.terms.items() if not v.random}",
    "docstring": "Return dict of all and only fixed effects in model."
  },
  {
    "code": "def get_list_from_xml(elem, tag=\"option\", attributes=[\"name\"]):\n    return flatten(([option.get(attr) for attr in attributes] + [option.text] for option in elem.findall(tag)), exclude=[None])",
    "docstring": "This function searches for all \"option\"-tags and returns a list with all attributes and texts."
  },
  {
    "code": "def require_openid(f):\n    @wraps(f)\n    def decorator(*args, **kwargs):\n        if g.user is None:\n            next_url = url_for(\"login\") + \"?next=\" + request.url\n            return redirect(next_url)\n        else:\n            return f(*args, **kwargs)\n    return decorator",
    "docstring": "Require user to be logged in."
  },
  {
    "code": "def serialize(self, entity, request=None):\n        def should_we_insert(value, field_spec):\n            return value not in self.missing or field_spec.required\n        errors = {}\n        ret = {}\n        for field_name, field_spec in self.spec.fields.items():\n            value = self._get_value_for_serialization(entity, field_name, field_spec)\n            func = self._get_serialize_func(field_name, self.spec)\n            try:\n                value = func(value, entity, request)\n                if should_we_insert(value, field_spec):\n                    ret[field_name] = value\n            except ValidationError, e:\n                if hasattr(e, 'message_dict'):\n                    errors.update(dict(zip(\n                        [field_name + '.' + key for key in e.message_dict.keys()],\n                        e.message_dict.values())))\n                else:\n                    errors[field_name] = e.messages\n        if errors:\n            raise ValidationError(errors)\n        return None if ret == {} else ret",
    "docstring": "Serialize entity into dictionary.\n\n        The spec can affect how individual fields will be serialized by\n        implementing ``serialize()`` for the fields needing customization.\n\n        :returns: dictionary"
  },
  {
    "code": "def get_node_parent_class(node):\n    while node.parent:\n        if isinstance(node, ClassDef):\n            return node\n        node = node.parent",
    "docstring": "Supposes that node is a mongoengine field in a class and tries to\n    get its parent class"
  },
  {
    "code": "def on_train_begin(self, **kwargs:Any)->None:\n        \"Initialize inner arguments.\"\n        self.wait, self.opt = 0, self.learn.opt\n        super().on_train_begin(**kwargs)",
    "docstring": "Initialize inner arguments."
  },
  {
    "code": "def remove_blank_dirs(self):\n        if self.is_blank():\n            try:\n                os.rmdir(self.path)\n            except OSError as e:\n                print(e)\n        else:\n            remove_empty_dir(self.path)",
    "docstring": "Remove blank dir and all blank subdirectories"
  },
  {
    "code": "def run_mypy(self, paths=(), code=None):\n        if self.mypy:\n            set_mypy_path(stub_dir)\n            from coconut.command.mypy import mypy_run\n            args = list(paths) + self.mypy_args\n            if code is not None:\n                args += [\"-c\", code]\n            for line, is_err in mypy_run(args):\n                if code is None or line not in self.mypy_errs:\n                    printerr(line)\n                if line not in self.mypy_errs:\n                    self.mypy_errs.append(line)\n                self.register_error(errmsg=\"MyPy error\")",
    "docstring": "Run MyPy with arguments."
  },
  {
    "code": "async def _run_server_task(self, started_signal):\n        try:\n            server = await websockets.serve(self._manage_connection, self.host, self.port)\n            port = server.sockets[0].getsockname()[1]\n            started_signal.set_result(port)\n        except Exception as err:\n            self._logger.exception(\"Error starting server on host %s, port %s\", self.host, self.port)\n            started_signal.set_exception(err)\n            return\n        try:\n            while True:\n                await asyncio.sleep(1)\n        except asyncio.CancelledError:\n            self._logger.info(\"Stopping server due to stop() command\")\n        finally:\n            server.close()\n            await server.wait_closed()\n        self._logger.debug(\"Server stopped, exiting task\")",
    "docstring": "Create a BackgroundTask to manage the server.\n\n        This allows subclasess to attach their server related tasks as\n        subtasks that are properly cleaned up when this parent task is\n        stopped and not require them all to overload start() and stop()\n        to perform this action."
  },
  {
    "code": "def make_usage_key_from_deprecated_string(self, location_url):\n        warnings.warn(\n            \"make_usage_key_from_deprecated_string is deprecated! Please use make_usage_key\",\n            DeprecationWarning,\n            stacklevel=2\n        )\n        return BlockUsageLocator.from_string(location_url).replace(run=self.run)",
    "docstring": "Deprecated mechanism for creating a UsageKey given a CourseKey and a serialized Location.\n\n        NOTE: this prejudicially takes the tag, org, and course from the url not self.\n\n        Raises:\n            InvalidKeyError: if the url does not parse"
  },
  {
    "code": "def func(self, volume):\n        return self._func(np.array(volume), self.eos_params)",
    "docstring": "The equation of state function with the paramters other than volume set\n        to the ones obtained from fitting.\n\n        Args:\n             volume (list/numpy.array)\n\n        Returns:\n            numpy.array"
  },
  {
    "code": "def pbmc68k_reduced() -> AnnData:\n    filename = os.path.dirname(__file__) + '/10x_pbmc68k_reduced.h5ad'\n    return sc.read(filename)",
    "docstring": "Subsampled and processed 68k PBMCs.\n\n    10x PBMC 68k dataset from\n    https://support.10xgenomics.com/single-cell-gene-expression/datasets\n\n    The original PBMC 68k dataset was preprocessed using scanpy and was saved\n    keeping only 724 cells and 221 highly variable genes.\n\n    The saved file contains the annotation of cell types (key: 'bulk_labels'), UMAP coordinates,\n    louvain clustering and gene rankings based on the bulk_labels.\n\n    Returns\n    -------\n    Annotated data matrix."
  },
  {
    "code": "def get_roles_for_permission(permission, brain_or_object):\n    obj = api.get_object(brain_or_object)\n    valid_roles = get_valid_roles_for(obj)\n    for item in obj.ac_inherited_permissions(1):\n        name, value = item[:2]\n        if name == permission:\n            permission = Permission(name, value, obj)\n            roles = permission.getRoles()\n            return filter(lambda r: r in valid_roles, roles)\n    raise ValueError(\"The permission {} is invalid.\".format(permission))",
    "docstring": "Return the roles of the permission that is granted on the object\n\n    Code extracted from `IRoleManager.rolesOfPermission`\n\n    :param permission: The permission to get the roles\n    :param brain_or_object: Catalog brain or object\n    :returns: List of roles having the permission"
  },
  {
    "code": "def _reader(self, name, stream, outbuf):\n        while True:\n            s = stream.readline()\n            if not s:\n                break\n            s = s.decode('utf-8').rstrip()\n            outbuf.append(s)\n            logger.debug('%s: %s' % (name, s))\n        stream.close()",
    "docstring": "Thread runner for reading lines of from a subprocess into a buffer.\n\n        :param name: The logical name of the stream (used for logging only).\n        :param stream: The stream to read from. This will typically a pipe\n                       connected to the output stream of a subprocess.\n        :param outbuf: The list to append the read lines to."
  },
  {
    "code": "def copy(self, h5file=None):\n        h5 = copyh5(self.h5, h5file)\n        return QPImage(h5file=h5, h5dtype=self.h5dtype)",
    "docstring": "Create a copy of the current instance\n\n        This is done by recursively copying the underlying hdf5 data.\n\n        Parameters\n        ----------\n        h5file: str, h5py.File, h5py.Group, or None\n            see `QPImage.__init__`"
  },
  {
    "code": "def json2xml(json_data, factory=ET.Element):\n    if not isinstance(json_data, dict):\n        json_data = json.loads(json_data)\n    elem = internal_to_elem(json_data, factory)\n    return ET.tostring(elem)",
    "docstring": "Convert a JSON string into an XML string.\n\n    Whatever Element implementation we could import will be used by\n    default; if you want to use something else, pass the Element class\n    as the factory parameter."
  },
  {
    "code": "def check_sections(config):\n        default_sections = ['global', 'auth', 'napps', 'kytos']\n        for section in default_sections:\n            if not config.has_section(section):\n                config.add_section(section)",
    "docstring": "Create a empty config file."
  },
  {
    "code": "def colored_map(text, cmap):\n    if not __ISON: return text\n    for key, v in cmap.items():\n        if isinstance(v, dict):\n            text = text.replace(key, colored(key, **v))\n        else:\n            text = text.replace(key, colored(key, color=v))\n    return text",
    "docstring": "Return colorized text. cmap is a dict mapping tokens to color options.\n\n    .. Example:\n\n        colored_key(\"foo bar\", {bar: \"green\"})\n        colored_key(\"foo bar\", {bar: {\"color\": \"green\", \"on_color\": \"on_red\"}})"
  },
  {
    "code": "def display(self):\n        from IPython.core.display import display, HTML\n        display(HTML(self._repr_html_()))",
    "docstring": "Display the visualization inline in the IPython notebook.\n\n        This is deprecated, use the following instead::\n\n            from IPython.display import display\n            display(viz)"
  },
  {
    "code": "def set_name(self, name):\n        if not name:\n            name = ''\n        self._client['config']['name'] = name\n        yield from self._server.client_name(self.identifier, name)",
    "docstring": "Set a client name."
  },
  {
    "code": "def centers(self):\n        w_cen = np.nanmean(self.wave.value, axis=1)\n        f_cen = np.nanmean(self.throughput, axis=1)\n        return np.asarray([w_cen, f_cen])",
    "docstring": "A getter for the wavelength bin centers and average fluxes"
  },
  {
    "code": "def loop_once(self):\n        while 1:\n            if not self._active_nodes:\n                self.triggershutdown()\n                raise RuntimeError(\"Unexpectedly no active workers available\")\n            try:\n                eventcall = self.queue.get(timeout=2.0)\n                break\n            except Empty:\n                continue\n        callname, kwargs = eventcall\n        assert callname, kwargs\n        method = \"worker_\" + callname\n        call = getattr(self, method)\n        self.log(\"calling method\", method, kwargs)\n        call(**kwargs)\n        if self.sched.tests_finished:\n            self.triggershutdown()",
    "docstring": "Process one callback from one of the workers."
  },
  {
    "code": "def run_async(self, time_limit):\n        self.background = time_limit\n        results = self.run()\n        return results, poller.AsyncPoller(results, self)",
    "docstring": "Run this module asynchronously and return a poller."
  },
  {
    "code": "def create(self, uri, buffer=\"queue\", interval=10):\n        return self._http_client.put_json(\"subscriptions/{}\".format(self.short_name), {\n            \"subscription\": {\n                \"uri\": uri,\n                \"buffer\": buffer,\n                \"interval\": interval,\n            }\n        })",
    "docstring": "Create a subscription with this short name and the provided parameters\n\n        For more information on what the parameters required here mean, please\n        refer to the `WVA Documentation <http://goo.gl/DRcOQf>`_.\n\n        :raises WVAError: If there is a problem creating the new subscription"
  },
  {
    "code": "def visit_Subscript(self, node: ast.Subscript) -> Any:\n        value = self.visit(node=node.value)\n        a_slice = self.visit(node=node.slice)\n        result = value[a_slice]\n        self.recomputed_values[node] = result\n        return result",
    "docstring": "Visit the ``slice`` and a ``value`` and get the element."
  },
  {
    "code": "def should_checkpoint(self):\n        result = self.last_result or {}\n        if result.get(DONE) and self.checkpoint_at_end:\n            return True\n        if self.checkpoint_freq:\n            return result.get(TRAINING_ITERATION,\n                              0) % self.checkpoint_freq == 0\n        else:\n            return False",
    "docstring": "Whether this trial is due for checkpointing."
  },
  {
    "code": "def evecs(self):\n        if self._evecs is None:\n            errMsg = \"The metric eigenvectors have not been set in the \"\n            errMsg += \"metricParameters instance.\"\n            raise ValueError(errMsg)\n        return self._evecs",
    "docstring": "The eigenvectors of the parameter space.\n        This is a Dictionary of numpy.matrix\n        Each entry in the dictionary is as described under evals.\n        Each numpy.matrix contains the eigenvectors which, with the eigenvalues\n        in evals, are needed to rotate the\n        coordinate system to one in which the metric is the identity matrix."
  },
  {
    "code": "def run(self):\n        (task_id, tasks) = self.server.get_task()\n        self.task_store.from_dict(tasks)\n        for (index, task) in self.task_store:\n            result = self.compute(index, task)\n            self.results.append(result)\n        self.server.task_done((task_id, self.results))",
    "docstring": "This function needs to be called to start the computation."
  },
  {
    "code": "def same_intersection(intersection1, intersection2, wiggle=0.5 ** 40):\n    if intersection1.index_first != intersection2.index_first:\n        return False\n    if intersection1.index_second != intersection2.index_second:\n        return False\n    return np.allclose(\n        [intersection1.s, intersection1.t],\n        [intersection2.s, intersection2.t],\n        atol=0.0,\n        rtol=wiggle,\n    )",
    "docstring": "Check if two intersections are close to machine precision.\n\n    .. note::\n\n       This is a helper used only by :func:`verify_duplicates`, which in turn\n       is only used by :func:`generic_intersect`.\n\n    Args:\n        intersection1 (.Intersection): The first intersection.\n        intersection2 (.Intersection): The second intersection.\n        wiggle (Optional[float]): The amount of relative error allowed\n            in parameter values.\n\n    Returns:\n        bool: Indicates if the two intersections are the same to\n        machine precision."
  },
  {
    "code": "def postprocess_monograph(marc_xml, mods, uuid, counter, url):\n    dom = double_linked_dom(mods)\n    if not isinstance(marc_xml, MARCXMLRecord):\n        marc_xml = MARCXMLRecord(marc_xml)\n    add_missing_xml_attributes(dom, counter)\n    fix_invalid_type_parameter(dom)\n    if uuid:\n        add_uuid(dom, uuid)\n    add_marccountry_tag(dom)\n    add_genre(dom)\n    remove_hairs_from_tags(dom)\n    fix_issuance(dom)\n    fix_location_tag(dom)\n    fix_related_item_tag(dom)\n    fix_missing_electronic_locator_tag(dom, url)\n    fix_missing_lang_tags(marc_xml, dom)\n    return dom.prettify()",
    "docstring": "Fix bugs in `mods` produced by XSLT template.\n\n    Args:\n        marc_xml (str): Original Aleph record.\n        mods (str): XML string generated by XSLT template.\n        uuid (str): UUID of the package.\n        counter (int): Number of record, is added to XML headers.\n        url (str): URL of the publication (public or not).\n\n    Returns:\n        str: Updated XML."
  },
  {
    "code": "def install():\n    sudo(\"apt-get update -y -q\")\n    apt(\"nginx libjpeg-dev python-dev python-setuptools git-core \"\n        \"postgresql libpq-dev memcached supervisor python-pip\")\n    run(\"mkdir -p /home/%s/logs\" % env.user)\n    sudo(\"pip install -U pip virtualenv virtualenvwrapper mercurial\")\n    run(\"mkdir -p %s\" % env.venv_home)\n    run(\"echo 'export WORKON_HOME=%s' >> /home/%s/.bashrc\" % (env.venv_home,\n                                                              env.user))\n    run(\"echo 'source /usr/local/bin/virtualenvwrapper.sh' >> \"\n        \"/home/%s/.bashrc\" % env.user)\n    print(green(\"Successfully set up git, mercurial, pip, virtualenv, \"\n                \"supervisor, memcached.\", bold=True))",
    "docstring": "Installs the base system and Python requirements for the entire server."
  },
  {
    "code": "def search_weekday(weekday, jd, direction, offset):\n    return weekday_before(weekday, jd + (direction * offset))",
    "docstring": "Determine the Julian date for the next or previous weekday"
  },
  {
    "code": "def create(self, friendly_name=None, description=None):\n    if not self.exists():\n      try:\n        response = self._api.datasets_insert(self._name_parts,\n                                             friendly_name=friendly_name,\n                                             description=description)\n      except Exception as e:\n        raise e\n      if 'selfLink' not in response:\n        raise Exception(\"Could not create dataset %s\" % self._full_name)\n    return self",
    "docstring": "Creates the Dataset with the specified friendly name and description.\n\n    Args:\n      friendly_name: (optional) the friendly name for the dataset if it is being created.\n      description: (optional) a description for the dataset if it is being created.\n    Returns:\n      The Dataset.\n    Raises:\n      Exception if the Dataset could not be created."
  },
  {
    "code": "def create_gist(self, description, files, public=True):\n        new_gist = {'description': description, 'public': public,\n                    'files': files}\n        url = self._build_url('gists')\n        json = self._json(self._post(url, data=new_gist), 201)\n        return Gist(json, self) if json else None",
    "docstring": "Create a new gist.\n\n        If no login was provided, it will be anonymous.\n\n        :param str description: (required), description of gist\n        :param dict files: (required), file names with associated dictionaries\n            for content, e.g. ``{'spam.txt': {'content': 'File contents\n            ...'}}``\n        :param bool public: (optional), make the gist public if True\n        :returns: :class:`Gist <github3.gists.Gist>`"
  },
  {
    "code": "def _makeButtons(self):\n        self.button = button = urwid.Button(u\"OK\")\n        urwid.connect_signal(button, \"click\", self._completed)\n        return [self.button]",
    "docstring": "Makes buttons and wires them up."
  },
  {
    "code": "def normalise(self, to_currency):\n        out = Money(currency=to_currency)\n        for money in self._money_obs:\n            out += converter.convert(money, to_currency)\n        return Balance([out])",
    "docstring": "Normalise this balance into a single currency\n\n        Args:\n            to_currency (str): Destination currency\n\n        Returns:\n            (Balance): A new balance object containing a single Money value in the specified currency"
  },
  {
    "code": "def random(args):\n    from random import sample\n    p = OptionParser(random.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n    fastafile, N = args\n    N = int(N)\n    assert N > 0\n    f = Fasta(fastafile)\n    fw = must_open(\"stdout\", \"w\")\n    for key in sample(f.keys(), N):\n        rec = f[key]\n        SeqIO.write([rec], fw, \"fasta\")\n    fw.close()",
    "docstring": "%prog random fasta 100 > random100.fasta\n\n    Take number of records randomly from fasta"
  },
  {
    "code": "def create_zone(domain, profile, type='master', ttl=None):\n    conn = _get_driver(profile=profile)\n    zone = conn.create_record(domain, type=type, ttl=ttl)\n    return _simple_zone(zone)",
    "docstring": "Create a new zone.\n\n    :param domain: Zone domain name (e.g. example.com)\n    :type domain: ``str``\n\n    :param profile: The profile key\n    :type  profile: ``str``\n\n    :param type: Zone type (master / slave).\n    :type  type: ``str``\n\n    :param ttl: TTL for new records. (optional)\n    :type  ttl: ``int``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion libcloud_dns.create_zone google.com profile1"
  },
  {
    "code": "def GetClientStates(self, client_list, client_chunk=50):\n    for client_group in collection.Batch(client_list, client_chunk):\n      for fd in aff4.FACTORY.MultiOpen(\n          client_group,\n          mode=\"r\",\n          aff4_type=aff4_grr.VFSGRRClient,\n          token=self.token):\n        result = {}\n        result[\"age\"] = fd.Get(fd.Schema.PING)\n        result[\"hostname\"] = fd.Get(fd.Schema.HOSTNAME)\n        yield (fd.urn, result)",
    "docstring": "Take in a client list and return dicts with their age and hostname."
  },
  {
    "code": "def minimize_dihedrals(self):\n        r\n        new = self.copy()\n        def convert_d(d):\n            r = d % 360\n            return r - (r // 180) * 360\n        new.unsafe_loc[:, 'dihedral'] = convert_d(new.loc[:, 'dihedral'])\n        return new",
    "docstring": "r\"\"\"Give a representation of the dihedral with minimized absolute value.\n\n        Mathematically speaking the angles in a zmatrix are\n        representations of an equivalence class.\n        We will denote an equivalence relation with :math:`\\sim`\n        and use :math:`\\alpha` for an angle and :math:`\\delta` for a dihedral\n        angle. Then the following equations hold true.\n\n        .. math::\n\n           (\\alpha, \\delta) &\\sim (-\\alpha, \\delta + \\pi) \\\\\n           \\alpha &\\sim \\alpha \\mod 2\\pi \\\\\n           \\delta &\\sim \\delta \\mod 2\\pi\n\n        This function asserts:\n\n        .. math::\n\n           -\\pi \\leq \\delta \\leq \\pi\n\n        The main application of this function is the construction of\n        a transforming movement from ``zmat1`` to ``zmat2``.\n        This is under the assumption that ``zmat1`` and ``zmat2`` are the same\n        molecules (regarding their topology) and have the same\n        construction table (:meth:`~Cartesian.get_construction_table`)::\n\n          with cc.TestOperators(False):\n              D = zm2 - zm1\n              zmats1 = [zm1 + D * i / n for i in range(n)]\n              zmats2 = [zm1 + D.minimize_dihedrals() * i / n for i in range(n)]\n\n        The movement described by ``zmats1`` might be too large,\n        because going from :math:`5^\\circ` to :math:`355^\\circ` is\n        :math:`350^\\circ` in this case and not :math:`-10^\\circ` as\n        in ``zmats2`` which is the desired :math:`\\Delta` in most cases.\n\n        Args:\n            None\n\n        Returns:\n            Zmat: Zmatrix with accordingly changed angles and dihedrals."
  },
  {
    "code": "def _load_data_flow_models(self):\n        self.data_flows = []\n        for data_flow in self.state.data_flows.values():\n            self._add_model(self.data_flows, data_flow, DataFlowModel)",
    "docstring": "Adds models for each data flow of the state"
  },
  {
    "code": "def check_key(user,\n              key,\n              enc,\n              comment,\n              options,\n              config='.ssh/authorized_keys',\n              cache_keys=None,\n              fingerprint_hash_type=None):\n    if cache_keys is None:\n        cache_keys = []\n    enc = _refine_enc(enc)\n    current = auth_keys(user,\n                        config=config,\n                        fingerprint_hash_type=fingerprint_hash_type)\n    nline = _format_auth_line(key, enc, comment, options)\n    if key in current:\n        cline = _format_auth_line(key,\n                                  current[key]['enc'],\n                                  current[key]['comment'],\n                                  current[key]['options'])\n        if cline != nline:\n            return 'update'\n    else:\n        return 'add'\n    return 'exists'",
    "docstring": "Check to see if a key needs updating, returns \"update\", \"add\" or \"exists\"\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' ssh.check_key <user> <key> <enc> <comment> <options>"
  },
  {
    "code": "def save_notebook(self, body):\n        directory = os.path.dirname(self.output_path)\n        full_path = os.path.join(directory, self.notebook_name)\n        try:\n            with open(full_path, 'w') as fh:\n                fh.write(json.dumps(body, indent=2))\n        except ValueError:\n            print('ERROR: Could not save executed notebook to path: ' +\n                  self.output_path +\n                  ' -- Please provide a valid absolute path.')",
    "docstring": "Save notebook depending on user provided output path."
  },
  {
    "code": "def assets_set_asset(self, asset_name, file, **kwargs):\n        content_type = mimetypes.MimeTypes().guess_type(file)\n        files = {\n            asset_name: (file, open(file, 'rb'), content_type[0], {'Expires': '0'}),\n        }\n        return self.__call_api_post('assets.setAsset', kwargs=kwargs, use_json=False, files=files)",
    "docstring": "Set an asset image by name."
  },
  {
    "code": "def feed(self, json_item):\n        @MethodTimer.timeout(self.settings['KAFKA_FEED_TIMEOUT'], False)\n        def _feed(json_item):\n            producer = self._create_producer()\n            topic = self.settings['KAFKA_INCOMING_TOPIC']\n            if not self.logger.json:\n                self.logger.info('Feeding JSON into {0}\\n{1}'.format(\n                    topic, json.dumps(json_item, indent=4)))\n            else:\n                self.logger.info('Feeding JSON into {0}\\n'.format(topic),\n                                 extra={'value': json_item})\n            if producer is not None:\n                producer.send(topic, json_item)\n                producer.flush()\n                producer.close(timeout=10)\n                return True\n            else:\n                return False\n        result = _feed(json_item)\n        if result:\n            self.logger.info(\"Successfully fed item to Kafka\")\n        else:\n            self.logger.error(\"Failed to feed item into Kafka\")",
    "docstring": "Feeds a json item into the Kafka topic\n\n        @param json_item: The loaded json object"
  },
  {
    "code": "def filter_matching(self, urls):\n        for url in urls:\n            if urlparse(url).hostname in self:\n                yield url",
    "docstring": "Get URLs with hosts matching any listed ones.\n\n        :param urls: an iterable containing URLs to filter\n        :returns: a generator yielding matching URLs\n        :raises InvalidURLError: if there are any invalid URLs in\n        the sequence"
  },
  {
    "code": "def from_parameter(cls: Type[UnlockParameterType], parameter: str) -> Optional[Union[SIGParameter, XHXParameter]]:\n        sig_param = SIGParameter.from_parameter(parameter)\n        if sig_param:\n            return sig_param\n        else:\n            xhx_param = XHXParameter.from_parameter(parameter)\n            if xhx_param:\n                return xhx_param\n        return None",
    "docstring": "Return UnlockParameter instance from parameter string\n\n        :param parameter: Parameter string\n        :return:"
  },
  {
    "code": "def getblockhash(self, index: int) -> str:\n        return cast(str, self.api_fetch('getblockhash?index=' + str(index)))",
    "docstring": "Returns the hash of the block at ; index 0 is the genesis block."
  },
  {
    "code": "def _generate_full_recipe_message(self, destination, message, add_path_step):\n        if add_path_step and self.recipe_pointer:\n            recipe_path = self.recipe_path + [self.recipe_pointer]\n        else:\n            recipe_path = self.recipe_path\n        return {\n            \"environment\": self.environment,\n            \"payload\": message,\n            \"recipe\": self.recipe.recipe,\n            \"recipe-path\": recipe_path,\n            \"recipe-pointer\": destination,\n        }",
    "docstring": "Factory function to generate independent message objects for\n        downstream recipients with different destinations."
  },
  {
    "code": "def is_empty(self):\n        if(((self.channels == []) and (not self.shape == (0, 0))) or\n           ((not self.channels == []) and (self.shape == (0, 0)))):\n            raise RuntimeError(\"Channels-shape mismatch.\")\n        return self.channels == [] and self.shape == (0, 0)",
    "docstring": "Checks for an empty image."
  },
  {
    "code": "def stringify_seconds(seconds=0):\n    seconds = int(seconds)\n    minutes = seconds / 60\n    ti = {'h': 0, 'm': 0, 's': 0}\n    if seconds > 0:\n        ti['s'] = seconds % 60\n        ti['m'] = minutes % 60\n        ti['h'] = minutes / 60\n    return \"%dh %dm %ds\" % (ti['h'], ti['m'], ti['s'])",
    "docstring": "Takes time as a value of seconds and deduces the delta in human-readable\n    HHh MMm SSs format."
  },
  {
    "code": "def _log_task_info(headers, extra_task_info=None):\n    ran_at = time.time()\n    task_eta = float(headers.get('X-Appengine-Tasketa', 0.0))\n    task_info = {\n        'retry_count': headers.get('X-Appengine-Taskretrycount', ''),\n        'execution_count': headers.get('X-Appengine-Taskexecutioncount', ''),\n        'task_eta': task_eta,\n        'ran': ran_at,\n        'gae_latency_seconds': ran_at - task_eta\n    }\n    if extra_task_info:\n        task_info['extra'] = extra_task_info\n    logging.debug('TASK-INFO: %s', json.dumps(task_info))",
    "docstring": "Processes the header from task requests to log analytical data."
  },
  {
    "code": "def intinlist(lst):\n    for item in lst:\n        try:\n            item = int(item)\n            return True\n        except ValueError:\n            pass\n    return False",
    "docstring": "test if int in list"
  },
  {
    "code": "def get_changed_devices(self, timestamp):\n        if timestamp is None:\n            payload = {}\n        else:\n            payload = {\n                'timeout': SUBSCRIPTION_WAIT,\n                'minimumdelay': SUBSCRIPTION_MIN_WAIT\n            }\n            payload.update(timestamp)\n        payload.update({\n            'id': 'lu_sdata',\n        })\n        logger.debug(\"get_changed_devices() requesting payload %s\", str(payload))\n        r = self.data_request(payload, TIMEOUT*2)\n        r.raise_for_status()\n        if r.text == \"\":\n            raise PyveraError(\"Empty response from Vera\")\n        try:\n            result = r.json()\n        except ValueError as ex:\n            raise PyveraError(\"JSON decode error: \" + str(ex))\n        if not ( type(result) is dict\n                 and 'loadtime' in result and 'dataversion' in result ):\n            raise PyveraError(\"Unexpected/garbled response from Vera\")\n        device_data = result.get('devices')\n        timestamp = {\n            'loadtime': result.get('loadtime'),\n            'dataversion': result.get('dataversion')\n        }\n        return [device_data, timestamp]",
    "docstring": "Get data since last timestamp.\n\n        This is done via a blocking call, pass NONE for initial state."
  },
  {
    "code": "def get_wharton_gsrs_formatted(self, sessionid, date=None):\n        gsrs = self.get_wharton_gsrs(sessionid, date)\n        return self.switch_format(gsrs)",
    "docstring": "Return the wharton GSR listing formatted in studyspaces format."
  },
  {
    "code": "def _safe_type(value):\n    if type(value) is str: dtype = 'string'\n    if type(value) is unicode: dtype = 'string'\n    if type(value) is int: dtype = 'integer'\n    if type(value) is float: dtype = 'real'\n    return dtype",
    "docstring": "Converts Python type names to XGMML-safe type names."
  },
  {
    "code": "def version_msg():\n    python_version = sys.version[:3]\n    location = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n    message = u'Cookiecutter %(version)s from {} (Python {})'\n    return message.format(location, python_version)",
    "docstring": "Return the Cookiecutter version, location and Python powering it."
  },
  {
    "code": "def get_start_of_line_position(self, after_whitespace=False):\n        if after_whitespace:\n            current_line = self.current_line\n            return len(current_line) - len(current_line.lstrip()) - self.cursor_position_col\n        else:\n            return - len(self.current_line_before_cursor)",
    "docstring": "Relative position for the start of this line."
  },
  {
    "code": "def unpack(self, unpacker):\n        (a, b, c) = unpacker.unpack_struct(_HHI)\n        self.max_stack = a\n        self.max_locals = b\n        self.code = unpacker.read(c)\n        uobjs = unpacker.unpack_objects\n        self.exceptions = tuple(uobjs(JavaExceptionInfo, self))\n        self.attribs.unpack(unpacker)",
    "docstring": "unpacks a code block from a buffer. Updates the internal structure\n        of this instance"
  },
  {
    "code": "def append(self, item):\n        try:\n            self._data[self._position] = item\n        except IndexError:\n            self._grow()\n            self._data[self._position] = item\n        self._position += 1\n        return self",
    "docstring": "append a single item to the array, growing the wrapped numpy array\n        if necessary"
  },
  {
    "code": "def is_valid_resource_name(rname, exception_type=None):\n    match = _ARMNAME_RE.match(rname)\n    if match:\n        return True\n    if exception_type:\n        raise exception_type()\n    return False",
    "docstring": "Validates the given resource name to ARM guidelines, individual services may be more restrictive.\n\n    :param rname: The resource name being validated.\n    :type rname: str\n    :param exception_type: Raises this Exception if invalid.\n    :type exception_type: :class:`Exception`\n    :returns: A boolean describing whether the name is valid.\n    :rtype: bool"
  },
  {
    "code": "def to_versions(self):\n        versions = []\n        for bound in self.bounds:\n            if bound.lower.inclusive and bound.upper.inclusive \\\n                    and (bound.lower.version == bound.upper.version):\n                versions.append(bound.lower.version)\n        return versions or None",
    "docstring": "Returns exact version ranges as Version objects, or None if there\n        are no exact version ranges present."
  },
  {
    "code": "def get_object_position(self, object_name, relative_to_object=None):\n        h = self.get_object_handle(object_name)\n        relative_handle = (-1 if relative_to_object is None\n                           else self.get_object_handle(relative_to_object))\n        return self.call_remote_api('simxGetObjectPosition',\n                                    h, relative_handle,\n                                    streaming=True)",
    "docstring": "Gets the object position."
  },
  {
    "code": "def _nat_rules_for_internet_access(self, acl_no, network, netmask,\n                                       inner_itfc, outer_itfc, vrf_name):\n        acl_present = self._check_acl(acl_no, network, netmask)\n        if not acl_present:\n            conf_str = snippets.CREATE_ACL % (acl_no, network, netmask)\n            self._edit_running_config(conf_str, 'CREATE_ACL')\n        pool_name = \"%s_nat_pool\" % vrf_name\n        conf_str = asr1k_snippets.SET_DYN_SRC_TRL_POOL % (acl_no, pool_name,\n                                                          vrf_name)\n        try:\n            self._edit_running_config(conf_str, 'SET_DYN_SRC_TRL_POOL')\n        except Exception as dyn_nat_e:\n            LOG.info(\"Ignore exception for SET_DYN_SRC_TRL_POOL: %s. \"\n                     \"The config seems to be applied properly but netconf \"\n                     \"seems to report an error.\", dyn_nat_e)\n        conf_str = snippets.SET_NAT % (inner_itfc, 'inside')\n        self._edit_running_config(conf_str, 'SET_NAT')\n        conf_str = snippets.SET_NAT % (outer_itfc, 'outside')\n        self._edit_running_config(conf_str, 'SET_NAT')",
    "docstring": "Configure the NAT rules for an internal network.\n\n        Configuring NAT rules in the ASR1k is a three step process. First\n        create an ACL for the IP range of the internal network. Then enable\n        dynamic source NATing on the external interface of the ASR1k for this\n        ACL and VRF of the neutron router. Finally enable NAT on the interfaces\n        of the ASR1k where the internal and external networks are connected.\n\n        :param acl_no: ACL number of the internal network.\n        :param network: internal network\n        :param netmask: netmask of the internal network.\n        :param inner_itfc: (name of) interface connected to the internal\n        network\n        :param outer_itfc: (name of) interface connected to the external\n        network\n        :param vrf_name: VRF corresponding to this virtual router\n        :return: True if configuration succeeded\n        :raises: networking_cisco.plugins.cisco.cfg_agent.cfg_exceptions.\n        IOSXEConfigException"
  },
  {
    "code": "def _get_average_time_stamp(action_set):\n        total_time_stamps = sum(rule.time_stamp * rule.numerosity\n                                for rule in action_set)\n        total_numerosity = sum(rule.numerosity for rule in action_set)\n        return total_time_stamps / (total_numerosity or 1)",
    "docstring": "Return the average time stamp for the rules in this action\n        set."
  },
  {
    "code": "def param_remove(self, param: 'str') -> None:\n        for attr in self._param_attr_dicts:\n            if param in self.__dict__[attr]:\n                self.__dict__[attr].pop(param)\n        for attr in self._param_attr_lists:\n            if param in self.__dict__[attr]:\n                self.__dict__[attr].remove(param)",
    "docstring": "Remove a param from this model\n\n        :param param: name of the parameter to be removed\n        :type param: str"
  },
  {
    "code": "def convert_json_object(obographdoc, **args):\n    digraph = networkx.MultiDiGraph()\n    xref_graph = networkx.MultiGraph()\n    logical_definitions = []\n    property_chain_axioms = []\n    context = obographdoc.get('@context',{})\n    logging.info(\"CONTEXT: {}\".format(context))\n    mapper = OboJsonMapper(digraph=digraph, context=context)\n    ogs = obographdoc['graphs']\n    base_og = ogs[0]\n    for og in ogs:\n        mapper.add_obograph_digraph(og, xref_graph=xref_graph,\n                                    logical_definitions=logical_definitions,\n                                    property_chain_axioms=property_chain_axioms, **args)\n    return {\n        'id': base_og.get('id'),\n        'meta': base_og.get('meta'),\n        'graph': mapper.digraph,\n        'xref_graph': xref_graph,\n        'graphdoc': obographdoc,\n        'logical_definitions': logical_definitions,\n        'property_chain_axioms': property_chain_axioms\n        }",
    "docstring": "Return a networkx MultiDiGraph of the ontologies\n    serialized as a json object"
  },
  {
    "code": "def get_build_file_path(self, build_module) -> str:\n        project_root = Path(self.project_root)\n        build_module = norm_proj_path(build_module, '')\n        return str(project_root / build_module /\n                   (BUILD_PROJ_FILE if '' == build_module\n                    else self.build_file_name))",
    "docstring": "Return a full path to the build file of `build_module`.\n\n        The returned path will always be OS-native, regardless of the format\n        of project_root (native) and build_module (with '/')."
  },
  {
    "code": "def submit_ham(self, params):\n        for required in ['blog', 'user_ip', 'user_agent']:\n            if required not in params:\n                raise MissingParams(required) \n        response = self._request('submit-ham', params)\n        if response.status is 200:\n            return response.read() == \"true\"\n        return False",
    "docstring": "For submitting a ham comment to Akismet."
  },
  {
    "code": "def _encode_resp(self, value):\n        if isinstance(value, bytes):\n            return b''.join(\n                [b'$',\n                 ascii(len(value)).encode('ascii'), CRLF, value, CRLF])\n        elif isinstance(value, str):\n            return self._encode_resp(value.encode('utf-8'))\n        elif isinstance(value, int):\n            return self._encode_resp(ascii(value).encode('ascii'))\n        elif isinstance(value, float):\n            return self._encode_resp(ascii(value).encode('ascii'))\n        elif isinstance(value, list):\n            output = [b'*', ascii(len(value)).encode('ascii'), CRLF]\n            for item in value:\n                output.append(self._encode_resp(item))\n            return b''.join(output)\n        else:\n            raise ValueError('Unsupported type: {0}'.format(type(value)))",
    "docstring": "Dynamically build the RESP payload based upon the list provided.\n\n        :param mixed value: The list of command parts to encode\n        :rtype: bytes"
  },
  {
    "code": "def before(self, *nodes: Union[AbstractNode, str]) -> None:\n        if self.parentNode:\n            node = _to_node_list(nodes)\n            self.parentNode.insertBefore(node, self)",
    "docstring": "Insert nodes before this node.\n\n        If nodes contains ``str``, it will be converted to Text node."
  },
  {
    "code": "def rnumlistwithreplacement(howmany, max, min=0):\n    if checkquota() < 1:\n        raise Exception(\"Your www.random.org quota has already run out.\")\n    requestparam = build_request_parameterWR(howmany, min, max)\n    request = urllib.request.Request(requestparam)\n    request.add_header('User-Agent', 'randomwrapy/0.1 very alpha')\n    opener = urllib.request.build_opener()\n    numlist = opener.open(request).read()\n    return numlist.split()",
    "docstring": "Returns a list of howmany integers with a maximum value = max.\n    The minimum value defaults to zero."
  },
  {
    "code": "def update_count(cat_id):\n        entry2 = TabTag.update(\n            count=TabPost2Tag.select().where(\n                TabPost2Tag.tag_id == cat_id\n            ).count()\n        ).where(TabTag.uid == cat_id)\n        entry2.execute()",
    "docstring": "Update the count of certain category."
  },
  {
    "code": "def get_script(self):\n        uri = \"{}/script\".format(self.data[\"uri\"])\n        return self._helper.do_get(uri)",
    "docstring": "Gets the configuration script of the logical enclosure by ID or URI.\n\n        Return:\n            str: Configuration script."
  },
  {
    "code": "def compute(chart, date, fixedObjects=False):\n    sun = chart.getObject(const.SUN)\n    prevSr = ephem.prevSolarReturn(date, sun.lon)\n    nextSr = ephem.nextSolarReturn(date, sun.lon)\n    rotation = 30 * (date.jd - prevSr.jd) / (nextSr.jd - prevSr.jd)\n    age = math.floor((date.jd - chart.date.jd) / 365.25)\n    rotation = 30 * age + rotation\n    pChart = chart.copy()\n    for obj in pChart.objects:\n        if not fixedObjects:\n            obj.relocate(obj.lon + rotation)\n    for house in pChart.houses:\n        house.relocate(house.lon + rotation)\n    for angle in pChart.angles:\n        angle.relocate(angle.lon + rotation)\n    return pChart",
    "docstring": "Returns a profection chart for a given\n    date. Receives argument 'fixedObjects' to\n    fix chart objects in their natal locations."
  },
  {
    "code": "def u16(self, name, value=None, align=None):\n        self.uint(2, name, value, align)",
    "docstring": "Add an unsigned 2 byte integer field to template.\n\n        This is an convenience method that simply calls `Uint` keyword with predefined length."
  },
  {
    "code": "def reload(self, schedule):\n        self.intervals = {}\n        if 'schedule' in schedule:\n            schedule = schedule['schedule']\n        self.opts.setdefault('schedule', {}).update(schedule)",
    "docstring": "Reload the schedule from saved schedule file."
  },
  {
    "code": "def editpermissions_anonymous_user_view(self, request, forum_id=None):\n        forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None\n        context = self.get_forum_perms_base_context(request, forum)\n        context['forum'] = forum\n        context['title'] = '{} - {}'.format(_('Forum permissions'), _('Anonymous user'))\n        context['form'] = self._get_permissions_form(\n            request, UserForumPermission, {'forum': forum, 'anonymous_user': True},\n        )\n        return render(request, self.editpermissions_anonymous_user_view_template_name, context)",
    "docstring": "Allows to edit anonymous user permissions for the considered forum.\n\n        The view displays a form to define which permissions are granted for the anonymous user for\n        the considered forum."
  },
  {
    "code": "def insert_sequences_into_tree(aln, moltype, params={}):\n    new_aln=get_align_for_phylip(StringIO(aln))\n    aln2 = Alignment(new_aln)\n    seqs = aln2.toFasta()\n    parsinsert_app = ParsInsert(params=params)\n    result = parsinsert_app(seqs)\n    tree = DndParser(result['Tree'].read(), constructor=PhyloNode)\n    result.cleanUp()\n    return tree",
    "docstring": "Returns a tree from placement of sequences"
  },
  {
    "code": "def info_community(self,teamid):\n        headers = {\"Content-type\": \"application/x-www-form-urlencoded\",\"Accept\": \"text/plain\",'Referer': 'http://'+self.domain+'/standings.phtml',\"User-Agent\": user_agent}\n        req = self.session.get('http://'+self.domain+'/teamInfo.phtml?tid='+teamid,headers=headers).content\n        soup = BeautifulSoup(req)\n        info = []\n        for i in soup.find('table',cellpadding=2).find_all('tr')[1:]:\n            info.append('%s\\t%s\\t%s\\t%s\\t%s'%(i.find('td').text,i.find('a')['href'].split('pid=')[1],i.a.text,i.find_all('td')[2].text,i.find_all('td')[3].text))\n        return info",
    "docstring": "Get comunity info using a ID"
  },
  {
    "code": "def set_last_build_date(self):\n        try:\n            self.last_build_date = self.soup.find('lastbuilddate').string\n        except AttributeError:\n            self.last_build_date = None",
    "docstring": "Parses last build date and set value"
  },
  {
    "code": "def sort_set(s):\n    if not isinstance(s, Set):\n        raise TypeError(\"sets only\")\n    s = frozenset(s)\n    if s not in _sort_set_memo:\n        _sort_set_memo[s] = sorted(s, key=_sort_set_key)\n    return _sort_set_memo[s]",
    "docstring": "Return a sorted list of the contents of a set\n\n    This is intended to be used to iterate over world state, where you just need keys\n    to be in some deterministic order, but the sort order should be obvious from the key.\n\n    Non-strings come before strings and then tuples. Tuples compare element-wise as normal.\n    But ultimately all comparisons are between values' ``repr``.\n\n    This is memoized."
  },
  {
    "code": "def map_output(self, node_id, node_output_name, parameter_name):\n        self.output_mapping[parameter_name] = (node_id, node_output_name)\n        dependents = self.dependents_by_node_id.get(node_id, set())\n        dependents.add('output_{}'.format(parameter_name))\n        self.dependents_by_node_id[node_id] = dependents",
    "docstring": "Maps the output from a node to a workflow output.\n\n        :param node_id: The id of the node to map from.\n        :param node_output_name: The output parameter name for the node task to map to the workflow output.\n        :param parameter_name: The workflow output parameter name."
  },
  {
    "code": "def get_possible_actions(self):\n        possible_actions = self.wrapped.get_possible_actions()\n        if len(possible_actions) <= 20:\n            try:\n                possible_actions = list(set(possible_actions))\n            except TypeError:\n                possible_actions = list(possible_actions)\n            try:\n                possible_actions.sort()\n            except TypeError:\n                pass\n            self.logger.info('Possible actions:')\n            for action in possible_actions:\n                self.logger.info('    %s', action)\n        else:\n            self.logger.info(\"%d possible actions.\", len(possible_actions))\n        return possible_actions",
    "docstring": "Return a sequence containing the possible actions that can be\n        executed within the environment.\n\n        Usage:\n            possible_actions = scenario.get_possible_actions()\n\n        Arguments: None\n        Return:\n            A sequence containing the possible actions which can be\n            executed within this scenario."
  },
  {
    "code": "def generic_distribution(target, seeds, func):\n    r\n    seeds = target[seeds]\n    value = func.ppf(seeds)\n    return value",
    "docstring": "r\"\"\"\n    Accepts an 'rv_frozen' object from the Scipy.stats submodule and returns\n    values from the distribution for the given seeds\n\n    This uses the ``ppf`` method of the stats object\n\n    Parameters\n    ----------\n    target : OpenPNM Object\n        The object which this model is associated with. This controls the\n        length of the calculated array, and also provides access to other\n        necessary properties.\n\n    seeds : string, optional\n        The dictionary key on the Geometry object containing random seed values\n        (between 0 and 1) to use in the statistical distribution.\n\n    func : object\n        An 'rv_frozen' object from the Scipy.stats library with all of the\n        parameters pre-specified.\n\n    Examples\n    --------\n    The following code illustrates the process of obtaining a 'frozen' Scipy\n    stats object and adding it as a model:\n\n    >>> import scipy\n    >>> import openpnm as op\n    >>> pn = op.network.Cubic(shape=[3, 3, 3])\n    >>> geo = op.geometry.GenericGeometry(network=pn, pores=pn.Ps, throats=pn.Ts)\n    >>> geo.add_model(propname='pore.seed',\n    ...               model=op.models.geometry.pore_seed.random)\n\n    Now retrieve the stats distribution and add to ``geo`` as a model:\n\n    >>> stats_obj = scipy.stats.weibull_min(c=2, scale=.0001, loc=0)\n    >>> geo.add_model(propname='pore.size',\n    ...               model=op.models.geometry.pore_size.generic_distribution,\n    ...               seeds='pore.seed',\n    ...               func=stats_obj)\n\n\n    >>> import matplotlib.pyplot as plt\n    >>> fig = plt.hist(stats_obj.ppf(q=scipy.rand(1000)), bins=50)"
  },
  {
    "code": "def crashlog_cleanrange(from_day, up_to_day, **kwargs):\n    ctx = Context(**kwargs)\n    ctx.execute_action('crashlog:cleanwhen', **{\n        'storage': ctx.repo.create_secure_service('storage'),\n        'from_day': from_day,\n        'to_day': up_to_day,\n    })",
    "docstring": "Remove all crashlogs from one date up to another.\n\n    The date can be specified as DAY-[MONTH-[YEAR]].\n\n    Example:\n        today, yesterday, 10, 10-09, 10-09-2015"
  },
  {
    "code": "def sort(self, request, reverse=False):\n        field = self.model._meta.fields.get(self.columns_sort)\n        if not field:\n            return self.collection\n        if reverse:\n            field = field.desc()\n        return self.collection.order_by(field)",
    "docstring": "Sort current collection."
  },
  {
    "code": "def main():\n    t, kf, t0, major, minor, prod, beta = sympy.symbols(\n        't k_f t0 Y Z X beta', negative=False)\n    for f in funcs:\n        args = [t, kf, prod, major, minor]\n        if f in (pseudo_rev, binary_rev):\n            args.insert(2, kf/beta)\n        expr = f(*args, backend='sympy')\n        with open(f.__name__ + '.png', 'wb') as ofh:\n            sympy.printing.preview(expr, output='png', filename='out.png',\n                                   viewer='BytesIO', outputbuffer=ofh)\n        with open(f.__name__ + '_diff.png', 'wb') as ofh:\n            sympy.printing.preview(expr.diff(t).subs({t0: 0}).simplify(),\n                                   output='png', filename='out.png',\n                                   viewer='BytesIO', outputbuffer=ofh)",
    "docstring": "This example demonstrates how to generate pretty equations from the analytic\n    expressions found in ``chempy.kinetics.integrated``."
  },
  {
    "code": "def get_tree_from_sha(self, ref):\n        try:\n            return self.repo.revparse_single(ref).tree\n        except (KeyError, TypeError, ValueError, AttributeError):\n            return None",
    "docstring": "Return a pygit2.Tree object matching a SHA"
  },
  {
    "code": "def should_run(self):\n        if self.is_orchestrator():\n            self.log.warning(\"%s plugin set to run on orchestrator. Skipping\", self.key)\n            return False\n        if self.operator_manifests_extract_platform != self.platform:\n            self.log.info(\"Only platform [%s] will upload operators metadata. Skipping\",\n                          self.operator_manifests_extract_platform)\n            return False\n        if is_scratch_build():\n            self.log.info(\"Scratch build. Skipping\")\n            return False\n        if not self.has_operator_manifest():\n            self.log.info(\"Operator manifests label not set in Dockerfile. Skipping\")\n            return False\n        return True",
    "docstring": "Check if the plugin should run or skip execution.\n\n        :return: bool, False if plugin should skip execution"
  },
  {
    "code": "def _build_b(self, force=False):\n        r\n        if force:\n            self._pure_b = None\n        if self._pure_b is None:\n            b = np.zeros(shape=(self.Np, ), dtype=float)\n            self._pure_b = b\n        self.b = self._pure_b.copy()",
    "docstring": "r\"\"\"\n        Builds the RHS matrix, without applying any boundary conditions or\n        source terms. This method is trivial an basically creates a column\n        vector of 0's.\n\n        Parameters\n        ----------\n        force : Boolean (default is ``False``)\n            If set to ``True`` then the b matrix is built from new.  If\n            ``False`` (the default), a cached version of b is returned.  The\n            cached version is *clean* in the sense that no boundary conditions\n            or sources terms have been added to it."
  },
  {
    "code": "def mangle_volume(citation_elements):\n    volume_re = re.compile(ur\"(\\d+)([A-Z])\", re.U | re.I)\n    for el in citation_elements:\n        if el['type'] == 'JOURNAL':\n            matches = volume_re.match(el['volume'])\n            if matches:\n                el['volume'] = matches.group(2) + matches.group(1)\n    return citation_elements",
    "docstring": "Make sure the volume letter is before the volume number\n\n    e.g. transforms 100B to B100"
  },
  {
    "code": "def load_code_info(self):\n    return PhaseGroup(\n        setup=load_code_info(self.setup),\n        main=load_code_info(self.main),\n        teardown=load_code_info(self.teardown),\n        name=self.name)",
    "docstring": "Load coded info for all contained phases."
  },
  {
    "code": "def aesthetics(cls):\n        main = cls.DEFAULT_AES.keys() | cls.REQUIRED_AES\n        other = {'group'}\n        if 'color' in main:\n            other.add('colour')\n        if 'outlier_color' in main:\n            other.add('outlier_colour')\n        return main | other",
    "docstring": "Return all the aesthetics for this geom\n\n        geoms should not override this method."
  },
  {
    "code": "def page_crawled(self, page_resp):\n        page_text = utils.parse_text(page_resp)\n        page_hash = utils.hash_text(''.join(page_text))\n        if page_hash not in self.page_cache:\n            utils.cache_page(self.page_cache, page_hash, self.args['cache_size'])\n            return False\n        return True",
    "docstring": "Check if page has been crawled by hashing its text content.\n\n        Add new pages to the page cache.\n        Return whether page was found in cache."
  },
  {
    "code": "def run_pty(self, command):\n        boto.log.debug('running:%s on %s' % (command, self.server.instance_id))\n        channel = self._ssh_client.get_transport().open_session()\n        channel.get_pty()\n        channel.exec_command(command)\n        return channel.recv(1024)",
    "docstring": "Execute a command on the remote host with a pseudo-terminal.\n        Returns a string containing the output of the command."
  },
  {
    "code": "def collect_dashboard_js(collector):\n    dashmat = collector.configuration[\"dashmat\"]\n    modules = collector.configuration[\"__active_modules__\"]\n    compiled_static_prep = dashmat.compiled_static_prep\n    compiled_static_folder = dashmat.compiled_static_folder\n    npm_deps = list_npm_modules(collector, no_print=True)\n    react_server = ReactServer()\n    react_server.prepare(npm_deps, compiled_static_folder)\n    for dashboard in collector.configuration[\"dashboards\"].values():\n        log.info(\"Generating compiled javascript for dashboard:{0}\".format(dashboard.path))\n        filename = dashboard.path.replace(\"_\", \"__\").replace(\"/\", \"_\")\n        location = os.path.join(compiled_static_folder, \"dashboards\", \"{0}.js\".format(filename))\n        if os.path.exists(location):\n            os.remove(location)\n        generate_dashboard_js(dashboard, react_server, compiled_static_folder, compiled_static_prep, modules)",
    "docstring": "Generate dashboard javascript for each dashboard"
  },
  {
    "code": "def view(A, offset=0):\n    from numpy.lib.stride_tricks import as_strided\n    assert A.ndim == 2, \"only implemented for 2 dimensions\"\n    assert A.shape[0] == A.shape[1], \"attempting to get the view of non-square matrix?!\"\n    if offset > 0:\n        return as_strided(A[0, offset:], shape=(A.shape[0] - offset, ), strides=((A.shape[0]+1)*A.itemsize, ))\n    elif offset < 0:\n        return as_strided(A[-offset:, 0], shape=(A.shape[0] + offset, ), strides=((A.shape[0]+1)*A.itemsize, ))\n    else:\n        return as_strided(A, shape=(A.shape[0], ), strides=((A.shape[0]+1)*A.itemsize, ))",
    "docstring": "Get a view on the diagonal elements of a 2D array.\n\n    This is actually a view (!) on the diagonal of the array, so you can\n    in-place adjust the view.\n\n    :param :class:`ndarray` A: 2 dimensional numpy array\n    :param int offset: view offset to give back (negative entries allowed)\n    :rtype: :class:`ndarray` view of diag(A)\n\n    >>> import numpy as np\n    >>> X = np.arange(9).reshape(3,3)\n    >>> view(X)\n    array([0, 4, 8])\n    >>> d = view(X)\n    >>> d += 2\n    >>> view(X)\n    array([ 2,  6, 10])\n    >>> view(X, offset=-1)\n    array([3, 7])\n    >>> subtract(X, 3, offset=-1)\n    array([[ 2,  1,  2],\n           [ 0,  6,  5],\n           [ 6,  4, 10]])"
  },
  {
    "code": "def console_set_alignment(con: tcod.console.Console, alignment: int) -> None:\n    lib.TCOD_console_set_alignment(_console(con), alignment)",
    "docstring": "Change this consoles current alignment mode.\n\n    * tcod.LEFT\n    * tcod.CENTER\n    * tcod.RIGHT\n\n    Args:\n        con (Console): Any Console instance.\n        alignment (int):\n\n    .. deprecated:: 8.5\n        Set :any:`Console.default_alignment` instead."
  },
  {
    "code": "def compatible_api_version(server_version):\n    try:\n        semver = server_version.split('.')\n        if semver[0] != '1':\n            logger.error(\n                'Server API version (%s) is too new for us. Please update the executor installation.' % server_version)\n            return False\n        else:\n            return True\n    except Exception:\n        logger.error(\n            'Cannot understand the server API version (%s). Please update the executor installation.' % server_version)\n        return False",
    "docstring": "Check if this server API version is compatible to us."
  },
  {
    "code": "def get_tab(self, tab_name, allow_disabled=False):\n        tab = self._tabs.get(tab_name, None)\n        if tab and tab._allowed and (tab._enabled or allow_disabled):\n            return tab\n        return None",
    "docstring": "Returns a specific tab from this tab group.\n\n        If the tab is not allowed or not enabled this method returns ``None``.\n\n        If the tab is disabled but you wish to return it anyway, you can pass\n        ``True`` to the allow_disabled argument."
  },
  {
    "code": "def _call_setnx(self, command, value):\n        result = self._traverse_command(command, value)\n        if self.indexable and value is not None and result:\n            self.index(value)\n        return result",
    "docstring": "Index only if value has been set."
  },
  {
    "code": "def _selectedRepoRow(self):\n        selectedModelIndexes = \\\n            self.reposTableWidget.selectionModel().selectedRows()\n        for index in selectedModelIndexes:\n            return index.row()",
    "docstring": "Return the currently select repo"
  },
  {
    "code": "def conformPadding(cls, chars):\n        pad = chars\n        if pad and pad[0] not in PAD_MAP:\n            pad = cls.getPaddingChars(cls.getPaddingNum(pad))\n        return pad",
    "docstring": "Ensure alternate input padding formats are conformed\n        to formats defined in PAD_MAP\n\n        If chars is already a format defined in PAD_MAP, then\n        it is returned unmodified.\n\n        Example::\n            '#'    -> '#'\n            '@@@@' -> '@@@@'\n            '%04d' -> '#'\n\n        Args:\n            chars (str): input padding chars\n\n        Returns:\n            str: conformed padding chars\n\n        Raises:\n            ValueError: If chars contains invalid padding characters"
  },
  {
    "code": "def new_issuer(self, issuer_idx, info=None):\n        new_issuer_idx = issuer_idx\n        if new_issuer_idx in self._issuers.keys():\n            new_issuer_idx = naming.index_name_if_in_list(new_issuer_idx, self._issuers.keys())\n        new_issuer = issuers.Issuer(new_issuer_idx, info=info)\n        self._issuers[new_issuer_idx] = new_issuer\n        return new_issuer",
    "docstring": "Add a new issuer to the dataset with the given data.\n\n        Parameters:\n            issuer_idx (str): The id to associate the issuer with. If None or already exists, one is\n                              generated.\n            info (dict, list): Additional info of the issuer.\n\n        Returns:\n            Issuer: The newly added issuer."
  },
  {
    "code": "def predict(self, X):\n        self._check_method(\"predict\")\n        X = self._check_array(X)\n        if isinstance(X, da.Array):\n            result = X.map_blocks(\n                _predict, dtype=\"int\", estimator=self._postfit_estimator, drop_axis=1\n            )\n            return result\n        elif isinstance(X, dd._Frame):\n            return X.map_partitions(\n                _predict, estimator=self._postfit_estimator, meta=np.array([1])\n            )\n        else:\n            return _predict(X, estimator=self._postfit_estimator)",
    "docstring": "Predict for X.\n\n        For dask inputs, a dask array or dataframe is returned. For other\n        inputs (NumPy array, pandas dataframe, scipy sparse matrix), the\n        regular return value is returned.\n\n        Parameters\n        ----------\n        X : array-like\n\n        Returns\n        -------\n        y : array-like"
  },
  {
    "code": "def getControllerRoleForTrackedDeviceIndex(self, unDeviceIndex):\n        fn = self.function_table.getControllerRoleForTrackedDeviceIndex\n        result = fn(unDeviceIndex)\n        return result",
    "docstring": "Returns the controller type associated with a device index. This function is deprecated in favor of the new IVRInput system."
  },
  {
    "code": "def _memcache_key(self, timestamped=False):\n        request = tuple(map(str, self.package_requests))\n        repo_ids = []\n        for path in self.package_paths:\n            repo = package_repository_manager.get_repository(path)\n            repo_ids.append(repo.uid)\n        t = [\"resolve\",\n             request,\n             tuple(repo_ids),\n             self.package_filter_hash,\n             self.package_orderers_hash,\n             self.building,\n             config.prune_failed_graph]\n        if timestamped and self.timestamp:\n            t.append(self.timestamp)\n        return str(tuple(t))",
    "docstring": "Makes a key suitable as a memcache entry."
  },
  {
    "code": "def send_request(cls, sock, working_dir, command, *arguments, **environment):\n    for argument in arguments:\n      cls.write_chunk(sock, ChunkType.ARGUMENT, argument)\n    for item_tuple in environment.items():\n      cls.write_chunk(sock,\n                      ChunkType.ENVIRONMENT,\n                      cls.ENVIRON_SEP.join(cls._decode_unicode_seq(item_tuple)))\n    cls.write_chunk(sock, ChunkType.WORKING_DIR, working_dir)\n    cls.write_chunk(sock, ChunkType.COMMAND, command)",
    "docstring": "Send the initial Nailgun request over the specified socket."
  },
  {
    "code": "def labels(self, qids):\n        if len(qids) > 50:\n            raise ValueError(\"The limit is 50.\")\n        self.domain = 'www.wikidata.org'\n        self.uri = self.wiki_uri(self.domain)\n        query = self.WIKIDATA.substitute(\n            WIKI=self.uri,\n            ENDPOINT=self.endpoint,\n            LANG=self.variant or self.lang,\n            PROPS='labels')\n        qids = '|'.join(qids)\n        query += \"&ids=%s\" % qids\n        self.set_status('labels', qids)\n        return query",
    "docstring": "Returns Wikidata labels query string"
  },
  {
    "code": "def parse_datetime(date_str):\n    is_common_era = True\n    date_str_parts = date_str.split(\"-\")\n    if date_str_parts and date_str_parts[0] == '':\n        is_common_era = False\n        if len(date_str_parts) == 2:\n            date_str = date_str + \"-01-01T00:00:00Z\"\n    parsed_datetime = {\n        'is_common_era': is_common_era,\n        'parsed_datetime': None\n    }\n    if is_common_era:\n        if date_str == '*':\n            return parsed_datetime\n        default = datetime.datetime.now().replace(\n            hour=0, minute=0, second=0, microsecond=0,\n            day=1, month=1\n        )\n        parsed_datetime['parsed_datetime'] = parse(date_str, default=default)\n        return parsed_datetime\n    parsed_datetime['parsed_datetime'] = date_str\n    return parsed_datetime",
    "docstring": "Parses a date string to date object.\n    for BCE dates, only supports the year part."
  },
  {
    "code": "def trigger(self, when=1):\n        tw = Window(self.stream, self._config['type'])\n        tw._config['evictPolicy'] = self._config['evictPolicy']\n        tw._config['evictConfig'] = self._config['evictConfig']\n        if self._config['evictPolicy'] == 'TIME':\n            tw._config['evictTimeUnit'] = 'MILLISECONDS'\n        if isinstance(when, datetime.timedelta):\n            tw._config['triggerPolicy'] = 'TIME'\n            tw._config['triggerConfig'] = int(when.total_seconds() * 1000.0)\n            tw._config['triggerTimeUnit'] = 'MILLISECONDS'\n        elif isinstance(when, int):\n            tw._config['triggerPolicy'] = 'COUNT'\n            tw._config['triggerConfig'] = when\n        else:\n            raise ValueError(when)\n        return tw",
    "docstring": "Declare a window with this window's size and a trigger policy.\n\n        When the window is triggered is defined by `when`.\n\n        If `when` is an `int` then the window is triggered every\n        `when` tuples.  For example, with ``when=5`` the window\n        will be triggered every five tuples.\n\n        If `when` is an `datetime.timedelta` then it is the period\n        of the trigger. With a `timedelta` representing one minute\n        then the window is triggered every minute.\n\n        By default, when `trigger` has not been called on a `Window`\n        it triggers for every tuple inserted into the window\n        (equivalent to ``when=1``).\n\n        Args:\n            when: The size of the window, either an `int` to define the\n                number of tuples or `datetime.timedelta` to define the\n                duration of the window.\n\n        Returns:\n            Window: Window that will be triggered.\n\n        .. warning:: A trigger is only supported for a sliding window\n            such as one created by :py:meth:`last`."
  },
  {
    "code": "def base_url(self, value):\n        logger.debug('StackInABox({0}): Updating URL from {1} to {2}'\n                     .format(self.__id, self.__base_url, value))\n        self.__base_url = value\n        for k, v in six.iteritems(self.services):\n            matcher, service = v\n            service.base_url = StackInABox.__get_service_url(value,\n                                                             service.name)\n            logger.debug('StackInABox({0}): Service {1} has url {2}'\n                         .format(self.__id, service.name, service.base_url))",
    "docstring": "Set the Base URL property, updating all associated services."
  },
  {
    "code": "def exclusively(f):\n    @wraps(f)\n    def exclusively_f(self, *a, **kw):\n        with self._lock:\n            return f(self, *a, **kw)\n    return exclusively_f",
    "docstring": "Decorate a function to make it thread-safe by serializing invocations\n    using a per-instance lock."
  },
  {
    "code": "def colorize(text, color, background=False):\n    if color in _styles:\n        c = Color(text)\n        c.styles = [_styles.index(color) + 1]\n        return c\n    c = Color(text)\n    if background:\n        c.bgcolor = _color2ansi(color)\n    else:\n        c.fgcolor = _color2ansi(color)\n    return c",
    "docstring": "Colorize text with hex code.\n\n    :param text: the text you want to paint\n    :param color: a hex color or rgb color\n    :param background: decide to colorize background\n\n    ::\n\n        colorize('hello', 'ff0000')\n        colorize('hello', '#ff0000')\n        colorize('hello', (255, 0, 0))"
  },
  {
    "code": "def validate(instance):\n    jsonschema.validate(\n        to_dict(instance, dict_type=dict), build_schema(instance.__class__)\n    )",
    "docstring": "Validates a given ``instance``.\n\n    :param object instance: The instance to validate\n    :raises jsonschema.exceptions.ValidationError: On failed validation"
  },
  {
    "code": "def get_grapheme_cluster_break_property(value, is_bytes=False):\n    obj = unidata.ascii_grapheme_cluster_break if is_bytes else unidata.unicode_grapheme_cluster_break\n    if value.startswith('^'):\n        negated = value[1:]\n        value = '^' + unidata.unicode_alias['graphemeclusterbreak'].get(negated, negated)\n    else:\n        value = unidata.unicode_alias['graphemeclusterbreak'].get(value, value)\n    return obj[value]",
    "docstring": "Get `GRAPHEME CLUSTER BREAK` property."
  },
  {
    "code": "def get_uvi_history(self, params_dict):\n        lat = str(params_dict['lat'])\n        lon = str(params_dict['lon'])\n        start = str(params_dict['start'])\n        end = str(params_dict['end'])\n        params = dict(lat=lat, lon=lon, start=start, end=end)\n        uri = http_client.HttpClient.to_url(UV_INDEX_HISTORY_URL,\n                                            self._API_key,\n                                            None)\n        _, json_data = self._client.cacheable_get_json(uri, params=params)\n        return json_data",
    "docstring": "Invokes the UV Index History endpoint\n\n        :param params_dict: dict of parameters\n        :returns: a string containing raw JSON data\n        :raises: *ValueError*, *APICallError*"
  },
  {
    "code": "def get(self) -> Union[Event, None]:\n        message = self._queue.get_message()\n        if message and message['type'] == 'message':\n            event_id = DB.get_event(self._pub_key, self._processed_key)\n            event_data_str = DB.get_hash_value(self._data_key, event_id)\n            event_dict = ast.literal_eval(event_data_str)\n            event_dict['id'] = event_id\n            event_dict['subscriber'] = self._subscriber\n            return Event.from_config(event_dict)\n        return None",
    "docstring": "Get the latest event from the queue.\n\n        Call this method to query the queue for the latest event.\n\n        If no event has been published None is returned.\n\n        Returns:\n              Event or None"
  },
  {
    "code": "def set_field_value(self, name, value):\n        name = self.get_real_name(name)\n        if not name or not self._can_write_field(name):\n            return\n        if name in self.__deleted_fields__:\n            self.__deleted_fields__.remove(name)\n        if self.__original_data__.get(name) == value:\n            try:\n                self.__modified_data__.pop(name)\n            except KeyError:\n                pass\n        else:\n            self.__modified_data__[name] = value\n            self._prepare_child(value)\n            if name not in self.__structure__ or not self.__structure__[name].read_only:\n                return\n            try:\n                value.set_read_only(True)\n            except AttributeError:\n                pass",
    "docstring": "Set the value to the field modified_data"
  },
  {
    "code": "def cmd_work(self, connection, sender, target, payload):\n        connection.action(target, \"is doing something...\")\n        time.sleep(int(payload or \"5\"))\n        connection.action(target, \"has finished !\")\n        connection.privmsg(target, \"My answer is: 42.\")",
    "docstring": "Does some job"
  },
  {
    "code": "def class_instance_as_index(node):\n    context = contextmod.InferenceContext()\n    context.callcontext = contextmod.CallContext(args=[node])\n    try:\n        for inferred in node.igetattr(\"__index__\", context=context):\n            if not isinstance(inferred, bases.BoundMethod):\n                continue\n            for result in inferred.infer_call_result(node, context=context):\n                if isinstance(result, nodes.Const) and isinstance(result.value, int):\n                    return result\n    except exceptions.InferenceError:\n        pass\n    return None",
    "docstring": "Get the value as an index for the given instance.\n\n    If an instance provides an __index__ method, then it can\n    be used in some scenarios where an integer is expected,\n    for instance when multiplying or subscripting a list."
  },
  {
    "code": "def xpathNewContext(self):\n        ret = libxml2mod.xmlXPathNewContext(self._o)\n        if ret is None:raise xpathError('xmlXPathNewContext() failed')\n        __tmp = xpathContext(_obj=ret)\n        return __tmp",
    "docstring": "Create a new xmlXPathContext"
  },
  {
    "code": "def score(self):\n        if not self.scoreProperties:\n            self.scoreProperties = self.getScoreProperties()\n        return sum(self.scoreProperties.values())",
    "docstring": "Returns the sum of the accidental dignities\n        score."
  },
  {
    "code": "def save_screenshot(driver, name):\n    if hasattr(driver, 'save_screenshot'):\n        screenshot_dir = os.environ.get('SCREENSHOT_DIR')\n        if not screenshot_dir:\n            LOGGER.warning('The SCREENSHOT_DIR environment variable was not set; not saving a screenshot')\n            return\n        elif not os.path.exists(screenshot_dir):\n            os.makedirs(screenshot_dir)\n        image_name = os.path.join(screenshot_dir, name + '.png')\n        driver.save_screenshot(image_name)\n    else:\n        msg = (\n            u\"Browser does not support screenshots. \"\n            u\"Could not save screenshot '{name}'\"\n        ).format(name=name)\n        LOGGER.warning(msg)",
    "docstring": "Save a screenshot of the browser.\n\n    The location of the screenshot can be configured\n    by the environment variable `SCREENSHOT_DIR`.  If not set,\n    this defaults to the current working directory.\n\n    Args:\n        driver (selenium.webdriver): The Selenium-controlled browser.\n        name (str): A name for the screenshot, which will be used in the output file name.\n\n    Returns:\n        None"
  },
  {
    "code": "def get_contact(self, jid):\n        try:\n            return self.get_contacts()[jid.bare()]\n        except KeyError:\n            raise ContactNotFound\n        except AttributeError:\n            raise AttributeError(\"jid must be an aioxmpp.JID object\")",
    "docstring": "Returns a contact\n\n        Args:\n          jid (aioxmpp.JID): jid of the contact\n\n        Returns:\n          dict: the roster of contacts"
  },
  {
    "code": "def forecast(self,parensemble=None):\n        if parensemble is None:\n            parensemble = self.parensemble\n        self.logger.log(\"evaluating ensemble\")\n        failed_runs, obsensemble = self._calc_obs(parensemble)\n        if failed_runs is not None:\n            self.logger.warn(\"dropping failed realizations\")\n            parensemble.loc[failed_runs, :] = np.NaN\n            parensemble = parensemble.dropna()\n            obsensemble.loc[failed_runs, :] = np.NaN\n            obsensemble = obsensemble.dropna()\n        self.logger.log(\"evaluating ensemble\")\n        return obsensemble",
    "docstring": "for the enkf formulation, this simply moves the ensemble forward by running the model\n        once for each realization"
  },
  {
    "code": "def compute_default_choice(self):\n        choices = self.choices\n        if len(choices) == 0:\n            return None\n        high_choice = max(choices, key=lambda choice: choice.performance)\n        self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, \"default-choice\", high_choice.name)\n        self.refresh()\n        return high_choice",
    "docstring": "Computes and sets the default choice"
  },
  {
    "code": "def get_sessions(self, app_path):\n        if app_path not in self._applications:\n            raise ValueError(\"Application %s does not exist on this server\" % app_path)\n        return list(self._applications[app_path].sessions)",
    "docstring": "Gets all currently active sessions for an application.\n\n        Args:\n            app_path (str) :\n                The configured application path for the application to return\n                sessions for.\n\n        Returns:\n            list[ServerSession]"
  },
  {
    "code": "def value_from_message(self, message):\n        message = super(DateTimeField, self).value_from_message(message)\n        if message.time_zone_offset is None:\n            return datetime.datetime.utcfromtimestamp(\n                message.milliseconds / 1000.0)\n        milliseconds = (message.milliseconds -\n                        60000 * message.time_zone_offset)\n        timezone = util.TimeZoneOffset(message.time_zone_offset)\n        return datetime.datetime.fromtimestamp(milliseconds / 1000.0,\n                                               tz=timezone)",
    "docstring": "Convert DateTimeMessage to a datetime.\n\n        Args:\n          A DateTimeMessage instance.\n\n        Returns:\n          A datetime instance."
  },
  {
    "code": "def overrides(method):\n    for super_class in _get_base_classes(sys._getframe(2), method.__globals__):\n        if hasattr(super_class, method.__name__):\n            super_method = getattr(super_class, method.__name__)\n            if hasattr(super_method, \"__finalized__\"):\n                finalized = getattr(super_method, \"__finalized__\")\n                if finalized:\n                    raise AssertionError('Method \"%s\" is finalized' %\n                                         method.__name__)\n            if not method.__doc__:\n                method.__doc__ = super_method.__doc__\n            return method\n    raise AssertionError('No super class method found for \"%s\"' %\n                         method.__name__)",
    "docstring": "Decorator to indicate that the decorated method overrides a method in\n    superclass.\n    The decorator code is executed while loading class. Using this method\n    should have minimal runtime performance implications.\n\n    This is based on my idea about how to do this and fwc:s highly improved\n    algorithm for the implementation fwc:s\n    algorithm : http://stackoverflow.com/a/14631397/308189\n    my answer : http://stackoverflow.com/a/8313042/308189\n\n    How to use:\n    from overrides import overrides\n\n    class SuperClass(object):\n        def method(self):\n          return 2\n\n    class SubClass(SuperClass):\n\n        @overrides\n        def method(self):\n            return 1\n\n    :raises  AssertionError if no match in super classes for the method name\n    :return  method with possibly added (if the method doesn't have one)\n        docstring from super class"
  },
  {
    "code": "def finish_review(self, success=True, error=False):\n        if self.set_status:\n            if error:\n                self.github_repo.create_status(\n                    state=\"error\",\n                    description=\"Static analysis error! inline-plz failed to run.\",\n                    context=\"inline-plz\",\n                    sha=self.last_sha,\n                )\n            elif success:\n                self.github_repo.create_status(\n                    state=\"success\",\n                    description=\"Static analysis complete! No errors found in your PR.\",\n                    context=\"inline-plz\",\n                    sha=self.last_sha,\n                )\n            else:\n                self.github_repo.create_status(\n                    state=\"failure\",\n                    description=\"Static analysis complete! Found errors in your PR.\",\n                    context=\"inline-plz\",\n                    sha=self.last_sha,\n                )",
    "docstring": "Mark our review as finished."
  },
  {
    "code": "def GPIO_config(self, gpio_enable, gpio_config):\n        'Enable or disable slave-select pins as gpio.'\n        self.bus.write_byte_data(self.address, 0xF6, gpio_enable)\n        self.bus.write_byte_data(self.address, 0xF7, gpio_config)\n        return",
    "docstring": "Enable or disable slave-select pins as gpio."
  },
  {
    "code": "def connect(self, callback=None, timeout=None):\n        if hasattr(self, '_connecting_future') and not self._connecting_future.done():\n            future = self._connecting_future\n        else:\n            if hasattr(self, '_connecting_future'):\n                self._connecting_future.exception()\n            future = tornado.concurrent.Future()\n            self._connecting_future = future\n            self._connect(timeout=timeout)\n        if callback is not None:\n            def handle_future(future):\n                response = future.result()\n                self.io_loop.add_callback(callback, response)\n            future.add_done_callback(handle_future)\n        return future",
    "docstring": "Connect to the IPC socket"
  },
  {
    "code": "def _prep_sample_cnvs(cnv_file, data):\n    import pybedtools\n    sample_name = tz.get_in([\"rgnames\", \"sample\"], data)\n    def make_names(name):\n        return re.sub(\"[^\\w.]\", '.', name)\n    def matches_sample_name(feat):\n        return (feat.name == sample_name or feat.name == \"X%s\" % sample_name or\n                feat.name == make_names(sample_name))\n    def update_sample_name(feat):\n        feat.name = sample_name\n        return feat\n    sample_file = os.path.join(os.path.dirname(cnv_file), \"%s-cnv.bed\" % sample_name)\n    if not utils.file_exists(sample_file):\n        with file_transaction(data, sample_file) as tx_out_file:\n            with shared.bedtools_tmpdir(data):\n                pybedtools.BedTool(cnv_file).filter(matches_sample_name).each(update_sample_name).saveas(tx_out_file)\n    return sample_file",
    "docstring": "Convert a multiple sample CNV file into a single BED file for a sample.\n\n    Handles matching and fixing names where R converts numerical IDs (1234) into\n    strings by adding an X (X1234), and converts other characters into '.'s.\n    http://stat.ethz.ch/R-manual/R-devel/library/base/html/make.names.html"
  },
  {
    "code": "def stem(self, form, tag):\n        key = (form, tag)\n        if key not in self.lemma_cache:\n            lemma = self.stemmer(*key).word()\n            self.lemma_cache[key] = lemma\n        return self.lemma_cache[key]",
    "docstring": "Returns the stem of word with specific form and part-of-speech\n        tag according to the Stanford lemmatizer. Lemmas are cached."
  },
  {
    "code": "def _map_purchase_request_to_func(self, purchase_request_type):\n        if purchase_request_type in self._intent_view_funcs:\n            view_func = self._intent_view_funcs[purchase_request_type]\n        else:\n            raise NotImplementedError('Request type \"{}\" not found and no default view specified.'.format(purchase_request_type)) \n        argspec = inspect.getargspec(view_func)\n        arg_names = argspec.args\n        arg_values = self._map_params_to_view_args(purchase_request_type, arg_names)\n        print('_map_purchase_request_to_func', arg_names, arg_values, view_func, purchase_request_type)\n        return partial(view_func, *arg_values)",
    "docstring": "Provides appropriate parameters to the on_purchase functions."
  },
  {
    "code": "def get_default_vpc():\n  ec2 = get_ec2_resource()\n  for vpc in ec2.vpcs.all():\n    if vpc.is_default:\n      return vpc",
    "docstring": "Return default VPC or none if not present"
  },
  {
    "code": "def from_key_bytes(cls, algorithm, key_bytes):\n        return cls(\n            algorithm=algorithm, key=serialization.load_der_public_key(data=key_bytes, backend=default_backend())\n        )",
    "docstring": "Creates a `Verifier` object based on the supplied algorithm and raw verification key.\n\n        :param algorithm: Algorithm on which to base verifier\n        :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n        :param bytes encoded_point: Raw verification key\n        :returns: Instance of Verifier generated from encoded point\n        :rtype: aws_encryption_sdk.internal.crypto.Verifier"
  },
  {
    "code": "def authenticate(self, request):\n        authenticators = self._meta.authenticators\n        if request.method == 'OPTIONS' and ADREST_ALLOW_OPTIONS:\n            self.auth = AnonimousAuthenticator(self)\n            return True\n        error_message = \"Authorization required.\"\n        for authenticator in authenticators:\n            auth = authenticator(self)\n            try:\n                if not auth.authenticate(request):\n                    raise AssertionError(error_message)\n                self.auth = auth\n                auth.configure(request)\n                return True\n            except AssertionError, e:\n                error_message = str(e)\n        raise HttpError(error_message, status=status.HTTP_401_UNAUTHORIZED)",
    "docstring": "Attempt to authenticate the request.\n\n        :param request: django.http.Request instance\n\n        :return bool: True if success else raises HTTP_401"
  },
  {
    "code": "def change_password(username, password, uid=None, host=None,\n                    admin_username=None, admin_password=None,\n                    module=None):\n    if len(password) > 20:\n        raise CommandExecutionError('Supplied password should be 20 characters or less')\n    if uid is None:\n        user = list_users(host=host, admin_username=admin_username,\n                          admin_password=admin_password, module=module)\n        uid = user[username]['index']\n    if uid:\n        return __execute_cmd('config -g cfgUserAdmin -o '\n                             'cfgUserAdminPassword -i {0} {1}'\n                             .format(uid, password),\n                             host=host, admin_username=admin_username,\n                             admin_password=admin_password, module=module)\n    else:\n        log.warning('racadm: user \\'%s\\' does not exist', username)\n        return False",
    "docstring": "Change user's password\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt dell dracr.change_password [USERNAME] [PASSWORD] uid=[OPTIONAL]\n            host=<remote DRAC> admin_username=<DRAC user>\n            admin_password=<DRAC PW>\n        salt dell dracr.change_password diana secret\n\n    Note that if only a username is specified then this module will look up\n    details for all 16 possible DRAC users.  This is time consuming, but might\n    be necessary if one is not sure which user slot contains the one you want.\n    Many late-model Dell chassis have 'root' as UID 1, so if you can depend\n    on that then setting the password is much quicker.\n    Raises an error if the supplied password is greater than 20 chars."
  },
  {
    "code": "def seek(self, value, target=\"offset\"):\n        if target not in (u'offset', u'id'):\n            raise ArgumentError(\"You must specify target as either offset or id\", target=target)\n        if target == u'offset':\n            self._verify_offset(value)\n            self.offset = value\n        else:\n            self.offset = self._find_id(value)\n        self._count = self.engine.count_matching(self.selector, offset=self.offset)\n        curr = self.engine.get(self.storage_type, self.offset)\n        return self.matches(DataStream.FromEncoded(curr.stream))",
    "docstring": "Seek this stream to a specific offset or reading id.\n\n        There are two modes of use.  You can seek to a specific reading id,\n        which means the walker will be positioned exactly at the reading\n        pointed to by the reading ID.  If the reading id cannot be found\n        an exception will be raised.  The reading id can be found but corresponds\n        to a reading that is not selected by this walker, the walker will\n        be moved to point at the first reading after that reading and False\n        will be returned.\n\n        If target==\"offset\", the walker will be positioned at the specified\n        offset in the sensor log. It will also update the count of available\n        readings based on that new location so that the count remains correct.\n\n        The offset does not need to correspond to a reading selected by this\n        walker.  If offset does not point to a selected reading, the effective\n        behavior will be as if the walker pointed to the next selected reading\n        after `offset`.\n\n        Args:\n            value (int): The identifier to seek, either an offset or a\n                reading id.\n            target (str): The type of thing to seek.  Can be offset or id.\n                If id is given, then a reading with the given ID will be\n                searched for.  If offset is given then the walker will\n                be positioned at the given offset.\n\n        Returns:\n            bool: True if an exact match was found, False otherwise.\n\n            An exact match means that the offset or reading ID existed and\n            corresponded to a reading selected by this walker.\n\n            An inexact match means that the offset or reading ID existed but\n            corresponded to reading that was not selected by this walker.\n\n            If the offset or reading ID could not be found an Exception is\n            thrown instead.\n\n        Raises:\n            ArgumentError: target is an invalid string, must be offset or\n                id.\n            UnresolvedIdentifierError: the desired offset or reading id\n                could not be found."
  },
  {
    "code": "def main():\n    setup_main_logger(console=True, file_logging=False)\n    params = argparse.ArgumentParser(description='Quick usage: python3 -m sockeye.init_embedding '\n                                                 '-w embed-in-src.npy embed-in-tgt.npy '\n                                                 '-i vocab-in-src.json vocab-in-tgt.json '\n                                                 '-o vocab-out-src.json vocab-out-tgt.json '\n                                                 '-n source_embed_weight target_embed_weight '\n                                                 '-f params.init')\n    arguments.add_init_embedding_args(params)\n    args = params.parse_args()\n    init_embeddings(args)",
    "docstring": "Commandline interface to initialize Sockeye embedding weights with pretrained word representations."
  },
  {
    "code": "def right_axis_label(self, label, position=None, rotation=-60, offset=0.08,\n                         **kwargs):\n        if not position:\n            position = (2. / 5 + offset, 3. / 5, 0)\n        self._labels[\"right\"] = (label, position, rotation, kwargs)",
    "docstring": "Sets the label on the right axis.\n\n        Parameters\n        ----------\n        label: String\n            The axis label\n        position: 3-Tuple of floats, None\n            The position of the text label\n        rotation: float, -60\n            The angle of rotation of the label\n        offset: float,\n            Used to compute the distance of the label from the axis\n        kwargs:\n            Any kwargs to pass through to matplotlib."
  },
  {
    "code": "def ToDebugString(self):\n    text_parts = ['Path segment index\\tWeight']\n    for path_segment_index, weight in self._weight_per_index.items():\n      text_parts.append('{0:d}\\t\\t\\t{1:d}'.format(\n          path_segment_index, weight))\n    text_parts.append('')\n    text_parts.append('Weight\\t\\t\\tPath segment index(es)')\n    for weight, path_segment_indexes in self._indexes_per_weight.items():\n      text_parts.append('{0:d}\\t\\t\\t{1!s}'.format(\n          weight, path_segment_indexes))\n    text_parts.append('')\n    return '\\n'.join(text_parts)",
    "docstring": "Converts the path segment weights into a debug string."
  },
  {
    "code": "def has_started(self):\n        assessment_offered = self.get_assessment_offered()\n        if assessment_offered.has_start_time():\n            return DateTime.utcnow() >= assessment_offered.get_start_time()\n        else:\n            return True",
    "docstring": "Tests if this assessment has begun.\n\n        return: (boolean) - ``true`` if the assessment has begun,\n                ``false`` otherwise\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def dict_snake_to_camel_case(snake_dict, convert_keys=True, convert_subkeys=False):\n    converted = {}\n    for key, value in snake_dict.items():\n        if isinstance(value, dict):\n            new_value = dict_snake_to_camel_case(value, convert_keys=convert_subkeys,\n                                                 convert_subkeys=True)\n        elif isinstance(value, list):\n            new_value = []\n            for subvalue in value:\n                new_subvalue = dict_snake_to_camel_case(subvalue, convert_keys=convert_subkeys,\n                                                        convert_subkeys=True) \\\n                    if isinstance(subvalue, dict) else subvalue\n                new_value.append(new_subvalue)\n        else:\n            new_value = value\n        new_key = to_camel_case(key) if convert_keys else key\n        converted[new_key] = new_value\n    return converted",
    "docstring": "Recursively convert a snake_cased dict into a camelCased dict\n\n    :param snake_dict: Dictionary to convert\n    :param convert_keys: Whether the key should be converted\n    :param convert_subkeys: Whether to also convert the subkeys, in case they are named properties of the dict\n    :return:"
  },
  {
    "code": "def handleSync(self, msg: Any) -> Any:\n        if isinstance(msg, tuple) and len(\n                msg) == 2 and not hasattr(msg, '_field_types'):\n            return self.getFunc(msg[0])(*msg)\n        else:\n            return self.getFunc(msg)(msg)",
    "docstring": "Pass the message as an argument to the function defined in `routes`.\n        If the msg is a tuple, pass the values as multiple arguments to the function.\n\n        :param msg: tuple of object and callable"
  },
  {
    "code": "def home_slug():\n    prefix = get_script_prefix()\n    slug = reverse(\"home\")\n    if slug.startswith(prefix):\n        slug = '/' + slug[len(prefix):]\n    try:\n        return resolve(slug).kwargs[\"slug\"]\n    except KeyError:\n        return slug",
    "docstring": "Returns the slug arg defined for the ``home`` urlpattern, which\n    is the definitive source of the ``url`` field defined for an\n    editable homepage object."
  },
  {
    "code": "def sky_dist(src1, src2):\n    if np.all(src1 == src2):\n        return 0\n    return gcd(src1.ra, src1.dec, src2.ra, src2.dec)",
    "docstring": "Great circle distance between two sources.\n    A check is made to determine if the two sources are the same object, in this case\n    the distance is zero.\n\n    Parameters\n    ----------\n    src1, src2 : object\n        Two sources to check. Objects must have parameters (ra,dec) in degrees.\n\n    Returns\n    -------\n    distance : float\n        The distance between the two sources.\n\n    See Also\n    --------\n    :func:`AegeanTools.angle_tools.gcd`"
  },
  {
    "code": "def execute(self):\n        if not self.cmd.is_conn_available():\n            return\n        if self.cmd.connection.lowest_server_version >= SYSINFO_MIN_VERSION:\n            success, rows = self._sys_info()\n            self.cmd.exit_code = self.cmd.exit_code or int(not success)\n            if success:\n                for result in rows:\n                    self.cmd.pprint(result.rows, result.cols)\n                self.cmd.logger.info(\n                    \"For debugging purposes you can send above listed information to support@crate.io\")\n        else:\n            tmpl = 'Crate {version} does not support the cluster \"sysinfo\" command'\n            self.cmd.logger.warn(tmpl\n                                 .format(version=self.cmd.connection.lowest_server_version))",
    "docstring": "print system and cluster info"
  },
  {
    "code": "def _create_worker(self, worker):\n        worker.sig_started.connect(self._start)\n        self._workers.append(worker)",
    "docstring": "Common worker setup."
  },
  {
    "code": "def get_token(self, code, headers=None, **kwargs):\n        self._check_configuration(\"site\", \"token_url\", \"redirect_uri\",\n                                  \"client_id\", \"client_secret\")\n        url = \"%s%s\" % (self.site, quote(self.token_url))\n        data = {\n            'redirect_uri': self.redirect_uri,\n            'client_id': self.client_id,\n            'client_secret': self.client_secret,\n            'code': code,\n        }\n        data.update(kwargs)\n        return self._make_request(url, data=data, headers=headers)",
    "docstring": "Requests an access token"
  },
  {
    "code": "def calculate_row_format(columns, keys=None):\n    row_format = ''\n    if keys is None:\n        keys = columns.keys()\n    else:\n        keys = [key for key in keys if key in columns]\n    for key in keys:\n        if len(row_format) > 0:\n            row_format += \"|\"\n        row_format += \"%%(%s)-%ds\" % (key, columns[key])\n    return '|' + row_format + '|'",
    "docstring": "Calculate row format.\n\n    Args:\n        columns (dict): the keys are the column name and the value the max length.\n        keys (list): optional list of keys to order columns as well as to filter for them.\n\n    Returns:\n        str: format for table row"
  },
  {
    "code": "def rms(x):\n    try:\n        return (np.array(x) ** 2).mean() ** 0.5\n    except:\n        x = np.array(dropna(x))\n        invN = 1.0 / len(x)\n        return (sum(invN * (x_i ** 2) for x_i in x)) ** .5",
    "docstring": "Root Mean Square\"\n\n    Arguments:\n        x (seq of float): A sequence of numerical values\n\n    Returns:\n        The square root of the average of the squares of the values\n\n        math.sqrt(sum(x_i**2 for x_i in x) / len(x))\n\n        or\n\n        return (np.array(x) ** 2).mean() ** 0.5\n\n    >>> rms([0, 2, 4, 4])\n    3.0"
  },
  {
    "code": "def _repr(obj):\n    vals = \", \".join(\"{}={!r}\".format(\n        name, getattr(obj, name)) for name in obj._attribs)\n    if vals:\n        t = \"{}(name={}, {})\".format(obj.__class__.__name__, obj.name, vals)\n    else:\n        t = \"{}(name={})\".format(obj.__class__.__name__, obj.name)\n    return t",
    "docstring": "Show the received object as precise as possible."
  },
  {
    "code": "def updateMesh(self, polydata):\n        self.poly = polydata\n        self.mapper.SetInputData(polydata)\n        self.mapper.Modified()\n        return self",
    "docstring": "Overwrite the polygonal mesh of the actor with a new one."
  },
  {
    "code": "def seek(self, offset, whence=0, mode='rw'):\n        try:\n            st = self._sndfile.seek(offset, whence, mode)\n        except IOError, e:\n            raise PyaudioIOError(str(e))\n        return st",
    "docstring": "similar to python seek function, taking only in account audio data.\n\n        :Parameters:\n            offset : int\n                the number of frames (eg two samples for stereo files) to move\n                relatively to position set by whence.\n            whence : int\n                only 0 (beginning), 1 (current) and 2 (end of the file) are\n                valid.\n            mode : string\n                If set to 'rw', both read and write pointers are updated. If\n                'r' is given, only read pointer is updated, if 'w', only the\n                write one is (this may of course make sense only if you open\n                the file in a certain mode).\n\n        Notes\n        -----\n\n        - one only takes into accound audio data.\n        - if an invalid seek is given (beyond or before the file), a\n          PyaudioIOError is launched."
  },
  {
    "code": "def set_acl(self, role, users):\n        acl_updates = [{\"user\": user, \"role\": role} for user in users]\n        r = fapi.update_repository_method_acl(\n            self.namespace, self.name, self.snapshot_id,\n            acl_updates, self.api_url\n        )\n        fapi._check_response_code(r, 200)",
    "docstring": "Set permissions for this method.\n\n        Args:\n            role (str): Access level\n                one of {one of \"OWNER\", \"READER\", \"WRITER\", \"NO ACCESS\"}\n            users (list(str)): List of users to give role to"
  },
  {
    "code": "def clean(self, list_article_candidates):\n        results = []\n        for article_candidate in list_article_candidates:\n            article_candidate.title = self.do_cleaning(article_candidate.title)\n            article_candidate.description = self.do_cleaning(article_candidate.description)\n            article_candidate.text = self.do_cleaning(article_candidate.text)\n            article_candidate.topimage = self.do_cleaning(article_candidate.topimage)\n            article_candidate.author = self.do_cleaning(article_candidate.author)\n            article_candidate.publish_date = self.do_cleaning(article_candidate.publish_date)\n            results.append(article_candidate)\n        return results",
    "docstring": "Iterates over each article_candidate and cleans every extracted data.\n\n        :param list_article_candidates: A list, the list of ArticleCandidate-Objects which have been extracted\n        :return: A list, the list with the cleaned ArticleCandidate-Objects"
  },
  {
    "code": "def delete(ctx, componentname):\n    col = ctx.obj['col']\n    if col.count({'name': componentname}) > 1:\n        log('More than one component configuration of this name! Try '\n            'one of the uuids as argument. Get a list with \"config '\n            'list\"')\n        return\n    log('Deleting component configuration', componentname,\n        emitter='MANAGE')\n    configuration = col.find_one({'name': componentname})\n    if configuration is None:\n        configuration = col.find_one({'uuid': componentname})\n    if configuration is None:\n        log('Component configuration not found:', componentname,\n            emitter='MANAGE')\n        return\n    configuration.delete()\n    log('Done')",
    "docstring": "Delete an existing component configuration. This will trigger\n    the creation of its default configuration upon next restart."
  },
  {
    "code": "def alterar(\n            self,\n            id_interface,\n            nome,\n            protegida,\n            descricao,\n            id_ligacao_front,\n            id_ligacao_back,\n            tipo=None,\n            vlan=None):\n        if not is_valid_int_param(id_interface):\n            raise InvalidParameterError(\n                u'Interface id is invalid or was not informed.')\n        url = 'interface/' + str(id_interface) + '/'\n        interface_map = dict()\n        interface_map['nome'] = nome\n        interface_map['protegida'] = protegida\n        interface_map['descricao'] = descricao\n        interface_map['id_ligacao_front'] = id_ligacao_front\n        interface_map['id_ligacao_back'] = id_ligacao_back\n        interface_map['tipo'] = tipo\n        interface_map['vlan'] = vlan\n        code, xml = self.submit({'interface': interface_map}, 'PUT', url)\n        return self.response(code, xml)",
    "docstring": "Edit an interface by its identifier.\n\n        Equipment identifier is not changed.\n\n        :param nome: Interface name.\n        :param protegida: Indication of protected ('0' or '1').\n        :param descricao: Interface description.\n        :param id_ligacao_front: Front end link interface identifier.\n        :param id_ligacao_back: Back end link interface identifier.\n        :param id_interface: Interface identifier.\n\n        :return: None\n\n        :raise InvalidParameterError: The parameters interface id, nome and protegida are none or invalid.\n        :raise NomeInterfaceDuplicadoParaEquipamentoError: There is already an interface with this name for this equipment.\n        :raise InterfaceNaoExisteError: Front link interface and/or back link interface doesn't exist.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def float(cls, name, description=None, unit='', params=None,\n              default=None, initial_status=None):\n        return cls(cls.FLOAT, name, description, unit, params,\n                   default, initial_status)",
    "docstring": "Instantiate a new float sensor object.\n\n        Parameters\n        ----------\n        name : str\n            The name of the sensor.\n        description : str\n            A short description of the sensor.\n        units : str\n            The units of the sensor value. May be the empty string\n            if there are no applicable units.\n        params : list\n            [min, max] -- miniumum and maximum values of the sensor\n        default : float\n            An initial value for the sensor. Defaults to 0.0.\n        initial_status : int enum or None\n            An initial status for the sensor. If None, defaults to\n            Sensor.UNKNOWN. `initial_status` must be one of the keys in\n            Sensor.STATUSES"
  },
  {
    "code": "def norm(x, encoding=\"latin1\"):\n    \"Convertir acentos codificados en ISO 8859-1 u otro, a ASCII regular\"\n    if not isinstance(x, basestring):\n        x = unicode(x)\n    elif isinstance(x, str):\n        x = x.decode(encoding, 'ignore')\n    return unicodedata.normalize('NFKD', x).encode('ASCII', 'ignore')",
    "docstring": "Convertir acentos codificados en ISO 8859-1 u otro, a ASCII regular"
  },
  {
    "code": "def fetchExternalUpdates(self):\r\n        seeds = seeder.fetchDynamicProperties(\r\n            self.buildSpec['target'],\r\n            self.buildSpec['encoding']\r\n        )\r\n        for config in self.configs:\r\n            config.seedUI(seeds)",
    "docstring": "!Experimental!\r\n        Calls out to the client code requesting seed values to use in the UI\r\n        !Experimental!"
  },
  {
    "code": "def _get_ids_from_hostname(self, hostname):\n        results = self.list_instances(hostname=hostname, mask=\"id\")\n        return [result['id'] for result in results]",
    "docstring": "List VS ids which match the given hostname."
  },
  {
    "code": "def request_args(self):\n        kwargs = {}\n        kwargs.update(self.request.match_info.items())\n        kwargs.update(self.request.query.items())\n        return kwargs",
    "docstring": "Returns the arguments passed with the request in a dictionary.\n        Returns both URL resolved arguments and query string arguments."
  },
  {
    "code": "def iter_pages_builds(self, number=-1, etag=None):\n        url = self._build_url('pages', 'builds', base_url=self._api)\n        return self._iter(int(number), url, PagesBuild, etag=etag)",
    "docstring": "Iterate over pages builds of this repository.\n\n        :returns: generator of :class:`PagesBuild\n            <github3.repos.pages.PagesBuild>`"
  },
  {
    "code": "def regret(self):\n        return (sum(self.pulls)*np.max(np.nan_to_num(self.wins/self.pulls)) -\n                sum(self.wins)) / sum(self.pulls)",
    "docstring": "Calculate expected regret, where expected regret is\n        maximum optimal reward - sum of collected rewards, i.e.\n\n        expected regret = T*max_k(mean_k) - sum_(t=1-->T) (reward_t)\n\n        Returns\n        -------\n        float"
  },
  {
    "code": "def download(ui, repo, clname, **opts):\n\tif codereview_disabled:\n\t\traise hg_util.Abort(codereview_disabled)\n\tcl, vers, patch, err = DownloadCL(ui, repo, clname)\n\tif err != \"\":\n\t\treturn err\n\tui.write(cl.EditorText() + \"\\n\")\n\tui.write(patch + \"\\n\")\n\treturn",
    "docstring": "download a change from the code review server\n\n\tDownload prints a description of the given change list\n\tfollowed by its diff, downloaded from the code review server."
  },
  {
    "code": "def respond(request, code):\n    redirect = request.GET.get('next', request.POST.get('next'))\n    if redirect:\n        return HttpResponseRedirect(redirect)\n    return type('Response%d' % code, (HttpResponse, ), {'status_code': code})()",
    "docstring": "Responds to the request with the given response code.\n    If ``next`` is in the form, it will redirect instead."
  },
  {
    "code": "def write_csv(data, file_name, encoding='utf-8'):\n    name_extension = len(data) > 1\n    root, ext = os.path.splitext(file_name)\n    for i, sheet in enumerate(data):\n        fname = file_name if not name_extension else root+\"_\"+str(i)+ext\n        with open(fname, 'wb') as date_file:\n            csv_file = csv.writer(date_file, encoding=encoding)\n            for line in sheet:\n                csv_file.writerow(line)",
    "docstring": "Writes out to csv format.\n\n    Args:\n        data: 2D list of tables/worksheets.\n        file_name: Name of the output file."
  },
  {
    "code": "def update(self, obj_id, is_public=NotUpdated, is_protected=NotUpdated):\n        data = {}\n        self._copy_if_updated(data, is_public=is_public,\n                              is_protected=is_protected)\n        return self._patch('/job-executions/%s' % obj_id, data)",
    "docstring": "Update a Job Execution."
  },
  {
    "code": "def get_attribute_option(self, attribute, option_name):\n        self.__validate_attribute_option_name(option_name)\n        attribute_key = self.__make_key(attribute)\n        return self.__attribute_options[attribute_key].get(option_name)",
    "docstring": "Returns the value of the given attribute option for the specified\n        attribute."
  },
  {
    "code": "def write_file(self, filename, distance=6, velocity=8, charge=3):\n        with open(filename, \"w\") as f:\n            f.write(self.get_string(distance=distance, velocity=velocity,\n                                    charge=charge))",
    "docstring": "Writes LammpsData to file.\n\n        Args:\n            filename (str): Filename.\n            distance (int): No. of significant figures to output for\n                box settings (bounds and tilt) and atomic coordinates.\n                Default to 6.\n            velocity (int): No. of significant figures to output for\n                velocities. Default to 8.\n            charge (int): No. of significant figures to output for\n                charges. Default to 3."
  },
  {
    "code": "def write(self, text):\n        'Uses curses to print in the fanciest way possible.'\n        if not self.no_color:\n            text = self.colorize_text(text)\n        else:\n            pattern = re.compile('\\<\\<[A-Z]*?\\>\\>')\n            text = pattern.sub('', text)\n        text += '\\n'\n        self.buffer.write(text)\n        return self",
    "docstring": "Uses curses to print in the fanciest way possible."
  },
  {
    "code": "def _jws_header(keyid, algorithm):\n    data = {\n        'typ': 'JWT',\n        'alg': algorithm.name,\n        'kid': keyid\n    }\n    datajson = json.dumps(data, sort_keys=True).encode('utf8')\n    return base64url_encode(datajson)",
    "docstring": "Produce a base64-encoded JWS header."
  },
  {
    "code": "def _parse_reassign_label(cls, args):\n        argparser = ArgumentParser(prog=\"cluster reassign_label\")\n        argparser.add_argument(\"destination_cluster\",\n                metavar=\"destination_cluster_id_label\",\n                help=\"id/label of the cluster to move the label to\")\n        argparser.add_argument(\"label\",\n                help=\"label to be moved from the source cluster\")\n        arguments = argparser.parse_args(args)\n        return arguments",
    "docstring": "Parse command line arguments for reassigning label."
  },
  {
    "code": "def get_summary_page_link(ifo, utc_time):\n    search_form = search_form_string\n    data = {'H1': data_h1_string, 'L1': data_l1_string}\n    if ifo not in data:\n        return ifo\n    else:\n        alog_utc = '%02d-%02d-%4d' % (utc_time[2], utc_time[1], utc_time[0])\n        ext = '%4d%02d%02d' % (utc_time[0], utc_time[1], utc_time[2])\n        return_string = search_form % (ifo.lower(), ifo.lower(), alog_utc, alog_utc)\n        return return_string + data[ifo] % ext",
    "docstring": "Return a string that links to the summary page and aLOG for this ifo\n\n    Parameters\n    ----------\n    ifo : string\n        The detector name\n    utc_time : sequence\n        First three elements must be strings giving year, month, day resp.\n\n    Returns\n    -------\n    return_string : string\n        String containing HTML for links to summary page and aLOG search"
  },
  {
    "code": "def postorder(self, skip_seed=False):\n        for node in self._tree.postorder_node_iter():\n            if skip_seed and node is self._tree.seed_node:\n                continue\n            yield node",
    "docstring": "Return a generator that yields the nodes of the tree in postorder.\n        If skip_seed=True then the root node is not included."
  },
  {
    "code": "def inserir(self, name):\n        brand_map = dict()\n        brand_map['name'] = name\n        code, xml = self.submit({'brand': brand_map}, 'POST', 'brand/')\n        return self.response(code, xml)",
    "docstring": "Inserts a new Brand and returns its identifier\n\n        :param name: Brand name. String with a minimum 3 and maximum of 100 characters\n\n        :return: Dictionary with the following structure:\n\n        ::\n\n            {'marca': {'id': < id_brand >}}\n\n        :raise InvalidParameterError: Name is null and invalid.\n        :raise NomeMarcaDuplicadoError: There is already a registered Brand with the value of name.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def make_retrigger_request(repo_name, request_id, auth, count=DEFAULT_COUNT_NUM,\n                           priority=DEFAULT_PRIORITY, dry_run=True):\n    url = '{}/{}/request'.format(SELF_SERVE, repo_name)\n    payload = {'request_id': request_id}\n    if count != DEFAULT_COUNT_NUM or priority != DEFAULT_PRIORITY:\n        payload.update({'count': count,\n                        'priority': priority})\n    if dry_run:\n        LOG.info('We would make a POST request to %s with the payload: %s' % (url, str(payload)))\n        return None\n    LOG.info(\"We're going to re-trigger an existing completed job with request_id: %s %i time(s).\"\n             % (request_id, count))\n    req = requests.post(\n        url,\n        headers={'Accept': 'application/json'},\n        data=payload,\n        auth=auth,\n        timeout=TCP_TIMEOUT,\n    )\n    return req",
    "docstring": "Retrigger a request using buildapi self-serve. Returns a request.\n\n    Buildapi documentation:\n    POST  /self-serve/{branch}/request\n    Rebuild `request_id`, which must be passed in as a POST parameter.\n    `priority` and `count` are also accepted as optional\n    parameters. `count` defaults to 1, and represents the number\n    of times this build  will be rebuilt."
  },
  {
    "code": "def do_hdr(self, line, hdrs_usr):\n        if self.hdr_ex is None:\n            self._init_hdr(line, hdrs_usr)\n            return True\n        elif self.hdr_ex in line:\n            self._init_hdr(line, hdrs_usr)\n            return True\n        return False",
    "docstring": "Initialize self.h2i."
  },
  {
    "code": "def trim(self):\n        for key, value in list(iteritems(self.counters)):\n            if value.empty():\n                del self.counters[key]",
    "docstring": "Clear not used counters"
  },
  {
    "code": "def _onClassAttribute(self, name, line, pos, absPosition, level):\n        attributes = self.objectsStack[level].classAttributes\n        for item in attributes:\n            if item.name == name:\n                return\n        attributes.append(ClassAttribute(name, line, pos, absPosition))",
    "docstring": "Memorizes a class attribute"
  },
  {
    "code": "def make_filter(self, fieldname, query_func, expct_value):\n        def actual_filter(item):\n            value = getattr(item, fieldname)\n            if query_func in NULL_AFFECTED_FILTERS and value is None:\n                return False\n            if query_func == 'eq':\n                return value == expct_value\n            elif query_func == 'ne':\n                return value != expct_value\n            elif query_func == 'lt':\n                return value < expct_value\n            elif query_func == 'lte':\n                return value <= expct_value\n            elif query_func == 'gt':\n                return value > expct_value\n            elif query_func == 'gte':\n                return value >= expct_value\n            elif query_func == 'startswith':\n                return value.startswith(expct_value)\n            elif query_func == 'endswith':\n                return value.endswith(expct_value)\n        actual_filter.__doc__ = '{} {} {}'.format('val', query_func, expct_value)\n        return actual_filter",
    "docstring": "makes a filter that will be appliead to an object's property based\n        on query_func"
  },
  {
    "code": "def create_assignment_group(self, course_id, group_weight=None, integration_data=None, name=None, position=None, rules=None, sis_source_id=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"course_id\"] = course_id\r\n        if name is not None:\r\n            data[\"name\"] = name\r\n        if position is not None:\r\n            data[\"position\"] = position\r\n        if group_weight is not None:\r\n            data[\"group_weight\"] = group_weight\r\n        if sis_source_id is not None:\r\n            data[\"sis_source_id\"] = sis_source_id\r\n        if integration_data is not None:\r\n            data[\"integration_data\"] = integration_data\r\n        if rules is not None:\r\n            data[\"rules\"] = rules\r\n        self.logger.debug(\"POST /api/v1/courses/{course_id}/assignment_groups with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"POST\", \"/api/v1/courses/{course_id}/assignment_groups\".format(**path), data=data, params=params, single_item=True)",
    "docstring": "Create an Assignment Group.\r\n\r\n        Create a new assignment group for this course."
  },
  {
    "code": "async def unpack(self, ciphertext: bytes) -> (str, str, str):\n        LOGGER.debug('Wallet.unpack >>> ciphertext: %s', ciphertext)\n        if not ciphertext:\n            LOGGER.debug('Wallet.pack <!< No ciphertext to unpack')\n            raise AbsentMessage('No ciphertext to unpack')\n        try:\n            unpacked = json.loads(await crypto.unpack_message(self.handle, ciphertext))\n        except IndyError as x_indy:\n            if x_indy.error_code == ErrorCode.WalletItemNotFound:\n                LOGGER.debug('Wallet.unpack <!< Wallet %s has no local key to unpack ciphertext', self.name)\n                raise AbsentRecord('Wallet {} has no local key to unpack ciphertext'.format(self.name))\n            LOGGER.debug('Wallet.unpack <!< Wallet %s unpack() raised indy error code {}', x_indy.error_code)\n            raise\n        rv = (unpacked['message'], unpacked.get('sender_verkey', None), unpacked.get('recipient_verkey', None))\n        LOGGER.debug('Wallet.unpack <<< %s', rv)\n        return rv",
    "docstring": "Unpack a message. Return triple with cleartext, sender verification key, and recipient verification key.\n        Raise AbsentMessage for missing ciphertext, or WalletState if wallet is closed. Raise AbsentRecord\n        if wallet has no key to unpack ciphertext.\n\n        :param ciphertext: JWE-like formatted message as pack() produces\n        :return: cleartext, sender verification key, recipient verification key"
  },
  {
    "code": "def packet_write(self):\n        bytes_written = 0\n        if self.sock == NC.INVALID_SOCKET:\n            return NC.ERR_NO_CONN, bytes_written\n        while len(self.out_packet) > 0:\n            pkt = self.out_packet[0]\n            write_length, status = nyamuk_net.write(self.sock, pkt.payload)\n            if write_length > 0:\n                pkt.to_process -= write_length\n                pkt.pos += write_length\n                bytes_written += write_length\n                if pkt.to_process > 0:\n                    return NC.ERR_SUCCESS, bytes_written\n            else:\n                if status == errno.EAGAIN or status == errno.EWOULDBLOCK:\n                    return NC.ERR_SUCCESS, bytes_written\n                elif status == errno.ECONNRESET:\n                    return NC.ERR_CONN_LOST, bytes_written\n                else:\n                    return NC.ERR_UNKNOWN, bytes_written\n            del self.out_packet[0]\n            self.last_msg_out = time.time()\n        return NC.ERR_SUCCESS, bytes_written",
    "docstring": "Write packet to network."
  },
  {
    "code": "def eliminate_sequential_children(paths):\n  \"helper for infer_columns. removes paths that are direct children of the n-1 or n-2 path\"\n  return [p for i,p in enumerate(paths) if not ((i>0 and paths[i-1]==p[:-1]) or (i>1 and paths[i-2]==p[:-1]))]",
    "docstring": "helper for infer_columns. removes paths that are direct children of the n-1 or n-2 path"
  },
  {
    "code": "def extract_col_name(string):\n    prefixes = [\"presence_pass_\", \"value_pass_\", \"type_pass_\"]\n    end = string.rfind(\"_\")\n    for prefix in prefixes:\n        if string.startswith(prefix):\n            return prefix[:-6], string[len(prefix):end]\n    return string, string",
    "docstring": "Take a string and split it.\n    String will be a format like \"presence_pass_azimuth\",\n    where \"azimuth\" is the MagIC column name and \"presence_pass\"\n    is the validation.\n    Return \"presence\", \"azimuth\"."
  },
  {
    "code": "def setattr(self, req, ino, attr, to_set, fi):\n        self.reply_err(req, errno.EROFS)",
    "docstring": "Set file attributes\n\n        Valid replies:\n            reply_attr\n            reply_err"
  },
  {
    "code": "def from_desmond(cls, path, **kwargs):\n        dms = DesmondDMSFile(path)\n        pos = kwargs.pop('positions', dms.getPositions())\n        return cls(master=dms, topology=dms.getTopology(), positions=pos, path=path,\n                   **kwargs)",
    "docstring": "Loads a topology from a Desmond DMS file located at `path`.\n\n        Arguments\n        ---------\n        path : str\n            Path to a Desmond DMS file"
  },
  {
    "code": "def proc_decorator(req_set):\n        def decorator(func):\n            @wraps(func)\n            def inner(self, *args, **kwargs):\n                proc = func.__name__.lower()\n                inner.proc_decorator = kwargs\n                self.logger.debug(\"processing proc:{}\".format(func.__name__))\n                self.logger.debug(req_set)\n                self.logger.debug(\"kwargs type: \" + str(type(kwargs)))\n                if proc in ['hplogistic', 'hpreg']:\n                    kwargs['ODSGraphics'] = kwargs.get('ODSGraphics', False)\n                if proc == 'hpcluster':\n                    proc = 'hpclus'\n                legal_set = set(kwargs.keys())\n                self.logger.debug(legal_set)\n                return SASProcCommons._run_proc(self, proc, req_set, legal_set, **kwargs)\n            return inner\n        return decorator",
    "docstring": "Decorator that provides the wrapped function with an attribute 'actual_kwargs'\n        containing just those keyword arguments actually passed in to the function."
  },
  {
    "code": "def email_users(users, subject, text_body, html_body=None, sender=None, configuration=None, **kwargs):\n        if not users:\n            raise ValueError('No users supplied')\n        recipients = list()\n        for user in users:\n            recipients.append(user.data['email'])\n        if configuration is None:\n            configuration = users[0].configuration\n        configuration.emailer().send(recipients, subject, text_body, html_body=html_body, sender=sender, **kwargs)",
    "docstring": "Email a list of users\n\n        Args:\n            users (List[User]): List of users\n            subject (str): Email subject\n            text_body (str): Plain text email body\n            html_body (str): HTML email body\n            sender (Optional[str]): Email sender. Defaults to SMTP username.\n            configuration (Optional[Configuration]): HDX configuration. Defaults to configuration of first user in list.\n            **kwargs: See below\n            mail_options (List): Mail options (see smtplib documentation)\n            rcpt_options (List): Recipient options (see smtplib documentation)\n\n        Returns:\n            None"
  },
  {
    "code": "def has_ops_before(self, ts):\n        spec = {'ts': {'$lt': ts}}\n        return bool(self.coll.find_one(spec))",
    "docstring": "Determine if there are any ops before ts"
  },
  {
    "code": "def get_font(self, font):\n        font = {'a': 0, 'b': 1}.get(font, font)\n        if not six.text_type(font) in self.fonts:\n            raise NotSupported(\n                '\"{}\" is not a valid font in the current profile'.format(font))\n        return font",
    "docstring": "Return the escpos index for `font`. Makes sure that\n        the requested `font` is valid."
  },
  {
    "code": "def add(x, y, context=None):\n    return _apply_function_in_current_context(\n        BigFloat,\n        mpfr.mpfr_add,\n        (\n            BigFloat._implicit_convert(x),\n            BigFloat._implicit_convert(y),\n        ),\n        context,\n    )",
    "docstring": "Return ``x`` + ``y``."
  },
  {
    "code": "def save(self, heads, console=True):\n        self._save_junit()\n        self._save_html_report(heads)\n        if console:\n            self._print_console_summary()",
    "docstring": "Create reports in different formats.\n\n        :param heads: html table extra values in title rows\n        :param console: Boolean, default is True. If set, also print out the console log."
  },
  {
    "code": "def has_value_of_type(self, var_type):\n        if self.has_value() and self.has_type(var_type):\n            return True\n        return False",
    "docstring": "Does the variable both have the given type and\n        have a variable value we can use?"
  },
  {
    "code": "def call(self, method, *args, **kw):\n        if args and kw:\n            raise ValueError(\"JSON-RPC method calls allow only either named or positional arguments.\")\n        if not method:\n            raise ValueError(\"JSON-RPC method call requires a method name.\")\n        request = self._data_serializer.assemble_request(\n            method, args or kw or None\n        )\n        if self._in_batch_mode:\n            self._requests.append(request)\n            return request.get('id')\n        else:\n            return request",
    "docstring": "In context of a batch we return the request's ID\n        else we return the actual json"
  },
  {
    "code": "def naive_grouped_rowwise_apply(data,\n                                group_labels,\n                                func,\n                                func_args=(),\n                                out=None):\n    if out is None:\n        out = np.empty_like(data)\n    for (row, label_row, out_row) in zip(data, group_labels, out):\n        for label in np.unique(label_row):\n            locs = (label_row == label)\n            out_row[locs] = func(row[locs], *func_args)\n    return out",
    "docstring": "Simple implementation of grouped row-wise function application.\n\n    Parameters\n    ----------\n    data : ndarray[ndim=2]\n        Input array over which to apply a grouped function.\n    group_labels : ndarray[ndim=2, dtype=int64]\n        Labels to use to bucket inputs from array.\n        Should be the same shape as array.\n    func : function[ndarray[ndim=1]] -> function[ndarray[ndim=1]]\n        Function to apply to pieces of each row in array.\n    func_args : tuple\n        Additional positional arguments to provide to each row in array.\n    out : ndarray, optional\n        Array into which to write output.  If not supplied, a new array of the\n        same shape as ``data`` is allocated and returned.\n\n    Examples\n    --------\n    >>> data = np.array([[1., 2., 3.],\n    ...                  [2., 3., 4.],\n    ...                  [5., 6., 7.]])\n    >>> labels = np.array([[0, 0, 1],\n    ...                    [0, 1, 0],\n    ...                    [1, 0, 2]])\n    >>> naive_grouped_rowwise_apply(data, labels, lambda row: row - row.min())\n    array([[ 0.,  1.,  0.],\n           [ 0.,  0.,  2.],\n           [ 0.,  0.,  0.]])\n    >>> naive_grouped_rowwise_apply(data, labels, lambda row: row / row.sum())\n    array([[ 0.33333333,  0.66666667,  1.        ],\n           [ 0.33333333,  1.        ,  0.66666667],\n           [ 1.        ,  1.        ,  1.        ]])"
  },
  {
    "code": "def create_key(self, master_secret=b\"\"):\n        master_secret = deserialize.bytes_str(master_secret)\n        bip32node = control.create_wallet(self.testnet,\n                                          master_secret=master_secret)\n        return bip32node.wif()",
    "docstring": "Create new private key and return in wif format.\n\n        @param: master_secret Create from master secret, otherwise random."
  },
  {
    "code": "def extract_forward_and_reverse_complement(\n            self, forward_reads_to_extract, reverse_reads_to_extract, database_fasta_file,\n            output_file):\n        self.extract(forward_reads_to_extract, database_fasta_file, output_file)\n        cmd_rev = \"fxtract -XH -f /dev/stdin '%s'\" % database_fasta_file\n        output = extern.run(cmd_rev, stdin='\\n'.join(reverse_reads_to_extract))\n        with open(output_file, 'a') as f:\n            for record in SeqIO.parse(StringIO(output), 'fasta'):\n                record.seq = record.reverse_complement().seq\n                SeqIO.write(record, f, 'fasta')",
    "docstring": "As per extract except also reverse complement the sequences."
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'name' in _dict:\n            args['name'] = _dict.get('name')\n        else:\n            raise ValueError(\n                'Required property \\'name\\' not present in ClassifierResult JSON'\n            )\n        if 'classifier_id' in _dict:\n            args['classifier_id'] = _dict.get('classifier_id')\n        else:\n            raise ValueError(\n                'Required property \\'classifier_id\\' not present in ClassifierResult JSON'\n            )\n        if 'classes' in _dict:\n            args['classes'] = [\n                ClassResult._from_dict(x) for x in (_dict.get('classes'))\n            ]\n        else:\n            raise ValueError(\n                'Required property \\'classes\\' not present in ClassifierResult JSON'\n            )\n        return cls(**args)",
    "docstring": "Initialize a ClassifierResult object from a json dictionary."
  },
  {
    "code": "def conditional_probability_alive(self, frequency, recency, T):\n        r, alpha, a, b = self._unload_params(\"r\", \"alpha\", \"a\", \"b\")\n        log_div = (r + frequency) * np.log((alpha + T) / (alpha + recency)) + np.log(\n            a / (b + np.maximum(frequency, 1) - 1)\n        )\n        return np.atleast_1d(np.where(frequency == 0, 1.0, expit(-log_div)))",
    "docstring": "Compute conditional probability alive.\n\n        Compute the probability that a customer with history\n        (frequency, recency, T) is currently alive.\n\n        From http://www.brucehardie.com/notes/021/palive_for_BGNBD.pdf\n\n        Parameters\n        ----------\n        frequency: array or scalar\n            historical frequency of customer.\n        recency: array or scalar\n            historical recency of customer.\n        T: array or scalar\n            age of the customer.\n\n        Returns\n        -------\n        array\n            value representing a probability"
  },
  {
    "code": "def get_curl_command_line(self, method, url, **kwargs):\n        if kwargs.get(\"query\"):\n            url = \"{}?{}\".format(url, d1_common.url.urlencode(kwargs[\"query\"]))\n        curl_list = [\"curl\"]\n        if method.lower() == \"head\":\n            curl_list.append(\"--head\")\n        else:\n            curl_list.append(\"-X {}\".format(method))\n        for k, v in sorted(list(kwargs[\"headers\"].items())):\n            curl_list.append('-H \"{}: {}\"'.format(k, v))\n        curl_list.append(\"{}\".format(url))\n        return \" \".join(curl_list)",
    "docstring": "Get request as cURL command line for debugging."
  },
  {
    "code": "def percent_pareto_interactions(records, percentage=0.8):\n    if len(records) == 0:\n        return None\n    user_count = Counter(r.correspondent_id for r in records)\n    target = int(math.ceil(sum(user_count.values()) * percentage))\n    user_sort = sorted(user_count.keys(), key=lambda x: user_count[x])\n    while target > 0 and len(user_sort) > 0:\n        user_id = user_sort.pop()\n        target -= user_count[user_id]\n    return (len(user_count) - len(user_sort)) / len(records)",
    "docstring": "The percentage of user's contacts that account for 80% of its interactions."
  },
  {
    "code": "def _create_rubber_bands_action(self):\n        icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg')\n        self.action_toggle_rubberbands = QAction(\n            QIcon(icon),\n            self.tr('Toggle Scenario Outlines'), self.iface.mainWindow())\n        message = self.tr('Toggle rubber bands showing scenario extents.')\n        self.action_toggle_rubberbands.setStatusTip(message)\n        self.action_toggle_rubberbands.setWhatsThis(message)\n        self.action_toggle_rubberbands.setCheckable(True)\n        flag = setting('showRubberBands', False, expected_type=bool)\n        self.action_toggle_rubberbands.setChecked(flag)\n        self.action_toggle_rubberbands.triggered.connect(\n            self.dock_widget.toggle_rubber_bands)\n        self.add_action(self.action_toggle_rubberbands)",
    "docstring": "Create action for toggling rubber bands."
  },
  {
    "code": "def render_value_for_node(node_id):\n    value = None\n    result = []\n    try:\n        result = db.execute(text(fetch_query_string('select_node_from_id.sql')), node_id=node_id).fetchall()\n    except DatabaseError as err:\n        current_app.logger.error(\"DatabaseError: %s\", err)\n    if result:\n        kw = dict(zip(result[0].keys(), result[0].values()))\n        value = render_node(node_id, noderequest={'_no_template':True}, **kw)\n    return value",
    "docstring": "Wrap render_node for usage in operate scripts.  Returns without template\n    rendered."
  },
  {
    "code": "def hardware_version(self):\n        res = self.rpc(0x00, 0x02, result_type=(0, True))\n        binary_version = res['buffer']\n        ver = \"\"\n        for x in binary_version:\n            if x != 0:\n                ver += chr(x)\n        return ver",
    "docstring": "Return the embedded hardware version string for this tile.\n\n        The hardware version is an up to 10 byte user readable string that is\n        meant to encode any necessary information about the specific hardware\n        that this tile is running on.  For example, if you have multiple\n        assembly variants of a given tile, you could encode that information\n        here.\n\n        Returns:\n            str: The hardware version read from the tile."
  },
  {
    "code": "def _calcidxs(func):\n        timegrids = hydpy.pub.get('timegrids')\n        if timegrids is None:\n            raise RuntimeError(\n                'An Indexer object has been asked for an %s array.  Such an '\n                'array has neither been determined yet nor can it be '\n                'determined automatically at the moment.   Either define an '\n                '%s array manually and pass it to the Indexer object, or make '\n                'a proper Timegrids object available within the pub module.  '\n                'In usual HydPy applications, the latter is done '\n                'automatically.'\n                % (func.__name__, func.__name__))\n        idxs = numpy.empty(len(timegrids.init), dtype=int)\n        for jdx, date in enumerate(hydpy.pub.timegrids.init):\n            idxs[jdx] = func(date)\n        return idxs",
    "docstring": "Return the required indexes based on the given lambda function\n        and the |Timegrids| object handled by module |pub|.  Raise a\n        |RuntimeError| if the latter is not available."
  },
  {
    "code": "def verbose(self):\n        enabled = self.lib.iperf_get_verbose(self._test)\n        if enabled:\n            self._verbose = True\n        else:\n            self._verbose = False\n        return self._verbose",
    "docstring": "Toggles verbose output for the iperf3 instance\n\n        :rtype: bool"
  },
  {
    "code": "def score_n1(matrix, matrix_size):\n    score = 0\n    for i in range(matrix_size):\n        prev_bit_row, prev_bit_col = -1, -1\n        row_counter, col_counter = 0, 0\n        for j in range(matrix_size):\n            bit = matrix[i][j]\n            if bit == prev_bit_row:\n                row_counter += 1\n            else:\n                if row_counter >= 5:\n                    score += row_counter - 2\n                row_counter = 1\n                prev_bit_row = bit\n            bit = matrix[j][i]\n            if bit == prev_bit_col:\n                col_counter += 1\n            else:\n                if col_counter >= 5:\n                    score += col_counter - 2\n                col_counter = 1\n                prev_bit_col = bit\n        if row_counter >= 5:\n            score += row_counter - 2\n        if col_counter >= 5:\n            score += col_counter - 2\n    return score",
    "docstring": "\\\n    Implements the penalty score feature 1.\n\n    ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)\n\n    ============================================   ========================    ======\n    Feature                                        Evaluation condition        Points\n    ============================================   ========================    ======\n    Adjacent modules in row/column in same color   No. of modules = (5 + i)    N1 + i\n    ============================================   ========================    ======\n\n    N1 = 3\n\n    :param matrix: The matrix to evaluate\n    :param matrix_size: The width (or height) of the matrix.\n    :return int: The penalty score (feature 1) of the matrix."
  },
  {
    "code": "def _jitter(c, magnitude:uniform):\n    \"Replace pixels by random neighbors at `magnitude`.\"\n    c.flow.add_((torch.rand_like(c.flow)-0.5)*magnitude*2)\n    return c",
    "docstring": "Replace pixels by random neighbors at `magnitude`."
  },
  {
    "code": "def _create_user(self, email, password, is_superuser, **extra_fields):\n        now = timezone.now()\n        if not email:\n            raise ValueError('The given email must be set')\n        email = self.normalize_email(email)\n        user = self.model(\n            email=email,\n            password=password,\n            is_active=True,\n            is_superuser=is_superuser, last_login=now,\n            date_joined=now,\n            **extra_fields)\n        user.set_password(password)\n        user.save(using=self._db)\n        return user",
    "docstring": "Create new user"
  },
  {
    "code": "def get_appliance_event_after_time(self, location_id, since, per_page=None, page=None, min_power=None):\n    url = \"https://api.neur.io/v1/appliances/events\"\n    headers = self.__gen_headers()\n    headers[\"Content-Type\"] = \"application/json\"\n    params = {\n      \"locationId\": location_id,\n      \"since\": since\n    }\n    if min_power:\n      params[\"minPower\"] = min_power\n    if per_page:\n      params[\"perPage\"] = per_page\n    if page:\n      params[\"page\"] = page\n    url = self.__append_url_params(url, params)\n    r = requests.get(url, headers=headers)\n    return r.json()",
    "docstring": "Get appliance events by location Id after defined time.\n\n    Args:\n      location_id (string): hexadecimal id of the sensor to query, e.g.\n                          ``0x0013A20040B65FAD``\n      since (string): ISO 8601 start time for getting the events that are created or updated after it.\n        Maxiumim value allowed is 1 day from the current time.\n      min_power (string): The minimum average power (in watts) for filtering.\n        Only events with an average power above this value will be returned.\n        (default: 400)\n      per_page (string, optional): the number of returned results per page\n        (min 1, max 500) (default: 10)\n      page (string, optional): the page number to return (min 1, max 100000)\n        (default: 1)\n\n    Returns:\n      list: dictionary objects containing appliance events meeting specified criteria"
  },
  {
    "code": "def get_term(self,term_id):\n        if term_id in self.idx:\n            return Cterm(self.idx[term_id],self.type)\n        else:\n            return None",
    "docstring": "Returns the term object for the supplied identifier\n        @type term_id: string\n        @param term_id: term identifier"
  },
  {
    "code": "def remove_prohibited_element(tag_name, document_element):\n    elements = document_element.getElementsByTagName(tag_name)\n    for element in elements:\n        p = element.parentNode\n        p.removeChild(element)",
    "docstring": "To fit the Evernote DTD need, drop this tag name"
  },
  {
    "code": "def Process(\n      self, parser_mediator, cache=None, database=None, **unused_kwargs):\n    if cache is None:\n      raise ValueError('Missing cache value.')\n    if database is None:\n      raise ValueError('Missing database value.')\n    super(SQLitePlugin, self).Process(parser_mediator)\n    for query, callback_method in self.QUERIES:\n      if parser_mediator.abort:\n        break\n      callback = getattr(self, callback_method, None)\n      if callback is None:\n        logger.warning(\n            '[{0:s}] missing callback method: {1:s} for query: {2:s}'.format(\n                self.NAME, callback_method, query))\n        continue\n      self._ParseQuery(parser_mediator, database, query, callback, cache)",
    "docstring": "Determine if this is the right plugin for this database.\n\n    This function takes a SQLiteDatabase object and compares the list\n    of required tables against the available tables in the database.\n    If all the tables defined in REQUIRED_TABLES are present in the\n    database then this plugin is considered to be the correct plugin\n    and the function will return back a generator that yields event\n    objects.\n\n    Args:\n      parser_mediator (ParserMediator): parser mediator.\n      cache (Optional[SQLiteCache]): cache.\n      database (Optional[SQLiteDatabase]): database.\n\n    Raises:\n      ValueError: If the database or cache value are missing."
  },
  {
    "code": "def initialize_from_bucket(self):\n    tmp_dir = tempfile.mkdtemp(\"tfds\")\n    data_files = gcs_utils.gcs_dataset_info_files(self.full_name)\n    if not data_files:\n      return\n    logging.info(\"Loading info from GCS for %s\", self.full_name)\n    for fname in data_files:\n      out_fname = os.path.join(tmp_dir, os.path.basename(fname))\n      gcs_utils.download_gcs_file(fname, out_fname)\n    self.read_from_directory(tmp_dir)",
    "docstring": "Initialize DatasetInfo from GCS bucket info files."
  },
  {
    "code": "def _handle_response(response):\n        if not str(response.status_code).startswith('2'):\n            raise KucoinAPIException(response)\n        try:\n            res = response.json()\n            if 'code' in res and res['code'] != \"200000\":\n                raise KucoinAPIException(response)\n            if 'success' in res and not res['success']:\n                raise KucoinAPIException(response)\n            if 'data' in res:\n                res = res['data']\n            return res\n        except ValueError:\n            raise KucoinRequestException('Invalid Response: %s' % response.text)",
    "docstring": "Internal helper for handling API responses from the Quoine server.\n        Raises the appropriate exceptions when necessary; otherwise, returns the\n        response."
  },
  {
    "code": "def reset(self):\n        self.indchar = None\n        self.comments = {}\n        self.refs = []\n        self.set_skips([])\n        self.docstring = \"\"\n        self.ichain_count = 0\n        self.tre_store_count = 0\n        self.case_check_count = 0\n        self.stmt_lambdas = []\n        if self.strict:\n            self.unused_imports = set()\n        self.bind()",
    "docstring": "Resets references."
  },
  {
    "code": "def heptad_register(self):\n        base_reg = 'abcdefg'\n        exp_base = base_reg * (self.cc_len//7+2)\n        ave_ca_layers = self.calc_average_parameters(self.ca_layers)[0][:-1]\n        reg_fit = fit_heptad_register(ave_ca_layers)\n        hep_pos = reg_fit[0][0]\n        return exp_base[hep_pos:hep_pos+self.cc_len], reg_fit[0][1:]",
    "docstring": "Returns the calculated register of the coiled coil and the fit quality."
  },
  {
    "code": "def set_exception(self, exception):\n        was_handled = self._finish(self.errbacks, exception)\n        if not was_handled:\n            traceback.print_exception(\n                type(exception), exception, exception.__traceback__)",
    "docstring": "Signal unsuccessful completion."
  },
  {
    "code": "def save_veto_definer(cp, out_dir, tags=None):\n    if tags is None:\n        tags = []\n    make_analysis_dir(out_dir)\n    veto_def_url = cp.get_opt_tags(\"workflow-segments\",\n                                 \"segments-veto-definer-url\", tags)\n    veto_def_base_name = os.path.basename(veto_def_url)\n    veto_def_new_path = os.path.abspath(os.path.join(out_dir,\n                                        veto_def_base_name))\n    resolve_url(veto_def_url,out_dir)\n    cp.set(\"workflow-segments\", \"segments-veto-definer-file\", veto_def_new_path)\n    return veto_def_new_path",
    "docstring": "Retrieve the veto definer file and save it locally\n\n    Parameters\n    -----------\n    cp : ConfigParser instance\n    out_dir : path\n    tags : list of strings\n        Used to retrieve subsections of the ini file for\n        configuration options."
  },
  {
    "code": "def print_label(self, package_num=None):\n        if package_num:\n            packages = [\n                self.shipment.response.CompletedShipmentDetail.CompletedPackageDetails[package_num]\n            ]\n        else:\n            packages = self.shipment.response.CompletedShipmentDetail.CompletedPackageDetails\n        for package in packages:\n            label_binary = binascii.a2b_base64(package.Label.Parts[0].Image)\n            self._print_base64(label_binary)",
    "docstring": "Prints all of a shipment's labels, or optionally just one.\n        \n        @type package_num: L{int}\n        @param package_num: 0-based index of the package to print. This is\n                            only useful for shipments with more than one package."
  },
  {
    "code": "def execute_cross_join(op, left, right, **kwargs):\n    key = \"cross_join_{}\".format(ibis.util.guid())\n    join_key = {key: True}\n    new_left = left.assign(**join_key)\n    new_right = right.assign(**join_key)\n    result = pd.merge(\n        new_left,\n        new_right,\n        how='inner',\n        on=key,\n        copy=False,\n        suffixes=constants.JOIN_SUFFIXES,\n    )\n    del result[key]\n    return result",
    "docstring": "Execute a cross join in pandas.\n\n    Notes\n    -----\n    We create a dummy column of all :data:`True` instances and use that as the\n    join key. This results in the desired Cartesian product behavior guaranteed\n    by cross join."
  },
  {
    "code": "def charge_transfer_to_string(self):\n        ch = self.charge_transfer\n        chts = ['\\nCharge Transfer\\n\\nabsorbing atom']\n        for i in range(len(ch)):\n            for atom, v2 in ch[str(i)].items():\n                a = ['\\n', atom, '\\n', 's   ', str(v2['s']), '\\n',\n                     'p   ', str(v2['p']), '\\n',\n                     'd   ', str(v2['d']), '\\n',\n                     'f   ', str(v2['f']), '\\n',\n                     'tot ', str(v2['tot']), '\\n']\n                chts.extend(a)\n        return ''.join(chts)",
    "docstring": "returns shrage transfer as string"
  },
  {
    "code": "def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs):\n        if grouper is None:\n            self._set_binner()\n            grouper = self.grouper\n        obj = self._selected_obj\n        grouped = groupby(obj, by=None, grouper=grouper, axis=self.axis)\n        try:\n            if isinstance(obj, ABCDataFrame) and callable(how):\n                result = grouped._aggregate_item_by_item(how, *args, **kwargs)\n            else:\n                result = grouped.aggregate(how, *args, **kwargs)\n        except Exception:\n            result = grouped.apply(how, *args, **kwargs)\n        result = self._apply_loffset(result)\n        return self._wrap_result(result)",
    "docstring": "Re-evaluate the obj with a groupby aggregation."
  },
  {
    "code": "def prog(text):\n    def decorator(func):\n        adaptor = ScriptAdaptor._get_adaptor(func)\n        adaptor.prog = text\n        return func\n    return decorator",
    "docstring": "Decorator used to specify the program name for the console script\n    help message.\n\n    :param text: The text to use for the program name."
  },
  {
    "code": "def get_relationships_for_idents(self, cid, idents):\n        keys = [(cid, ident,) for ident in idents]\n        key_ranges = zip(keys, keys)\n        mapping = {}\n        for k, v in self.kvl.scan(self.TABLE, *key_ranges):\n            label = self._label_from_kvlayer(k, v)\n            ident = label.other(cid)\n            rel_strength = label.rel_strength\n            mapping[ident] = label.rel_strength\n        return mapping",
    "docstring": "Get relationships between ``idents`` and a ``cid``.\n\n        Returns a dictionary mapping the identifiers in ``idents``\n        to either None, if no relationship label is found between\n        the identifier and ``cid``, or a RelationshipType classifying\n        the strength of the relationship between the identifier and\n        ``cid``."
  },
  {
    "code": "def compose_item_handle(tokens):\n    if len(tokens) < 1:\n        raise CoconutInternalException(\"invalid function composition tokens\", tokens)\n    elif len(tokens) == 1:\n        return tokens[0]\n    else:\n        return \"_coconut_forward_compose(\" + \", \".join(reversed(tokens)) + \")\"",
    "docstring": "Process function composition."
  },
  {
    "code": "def load_pem(cls, private_key, password=None):\n        maybe_path = normpath(private_key)\n        if os.path.isfile(maybe_path):\n            with open(maybe_path, 'rb') as pkf:\n                private_key = pkf.read()\n        if not isinstance(private_key, six.binary_type):\n            private_key = private_key.encode('utf-8')\n        pkey = serialization.load_pem_private_key(\n            private_key,\n            password=password,\n            backend=crypto_backends.default_backend())\n        return cls(pkey)",
    "docstring": "Return a PrivateKey instance.\n\n        :param private_key: Private key string (PEM format) or the path\n                            to a local private key file."
  },
  {
    "code": "def _get_metadata_from_ndk_string(self, gcmt, ndk_string):\n        gcmt.identifier = ndk_string[:16]\n        inversion_data = re.split('[A-Z:]+', ndk_string[17:61])\n        gcmt.metadata['BODY'] = [float(x) for x in inversion_data[1].split()]\n        gcmt.metadata['SURFACE'] = [\n            float(x) for x in inversion_data[2].split()]\n        gcmt.metadata['MANTLE'] = [float(x) for x in inversion_data[3].split()]\n        further_meta = re.split('[: ]+', ndk_string[62:])\n        gcmt.metadata['CMT'] = int(further_meta[1])\n        gcmt.metadata['FUNCTION'] = {'TYPE': further_meta[2],\n                                     'DURATION': float(further_meta[3])}\n        return gcmt",
    "docstring": "Reads the GCMT metadata from line 2 of the ndk batch"
  },
  {
    "code": "def configure_replacefor(self, ns, definition):\n        @self.add_route(ns.relation_path, Operation.ReplaceFor, ns)\n        @request(definition.request_schema)\n        @response(definition.response_schema)\n        @wraps(definition.func)\n        def replace(**path_data):\n            headers = dict()\n            request_data = load_request_data(definition.request_schema)\n            response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))\n            definition.header_func(headers, response_data)\n            response_format = self.negotiate_response_content(definition.response_formats)\n            return dump_response_data(\n                definition.response_schema,\n                response_data,\n                status_code=Operation.ReplaceFor.value.default_code,\n                headers=headers,\n                response_format=response_format,\n            )\n        replace.__doc__ = \"Replace a {} relative to a {}\".format(pluralize(ns.object_name), ns.subject_name)",
    "docstring": "Register a replace-for relation endpoint.\n\n        For typical usage, this relation is not strictly required; once an object exists and has its own ID,\n        it is better to operate on it directly via dedicated CRUD routes.\n        However, in some cases, the composite key of (subject_id, object_id) is required to look up the object.\n        This happens, for example, when using DynamoDB where an object which maintains both a hash key and a range key\n        requires specifying them both for access.\n\n        The definition's func should be a replace function, which must:\n\n        - accept kwargs for the new instance replacement parameters\n        - return the instance\n\n        :param ns: the namespace\n        :param definition: the endpoint definition"
  },
  {
    "code": "def add_hyperedge(self, nodes, attr_dict=None, **attr):\n        attr_dict = self._combine_attribute_arguments(attr_dict, attr)\n        if not nodes:\n            raise ValueError(\"nodes argument cannot be empty.\")\n        frozen_nodes = frozenset(nodes)\n        is_new_hyperedge = not self.has_hyperedge(frozen_nodes)\n        if is_new_hyperedge:\n            self.add_nodes(frozen_nodes)\n            hyperedge_id = self._assign_next_hyperedge_id()\n            for node in frozen_nodes:\n                self._star[node].add(hyperedge_id)\n            self._node_set_to_hyperedge[frozen_nodes] = hyperedge_id\n            self._hyperedge_attributes[hyperedge_id] = \\\n                {\"nodes\": nodes, \"__frozen_nodes\": frozen_nodes, \"weight\": 1}\n        else:\n            hyperedge_id = self._node_set_to_hyperedge[frozen_nodes]\n        self._hyperedge_attributes[hyperedge_id].update(attr_dict)\n        return hyperedge_id",
    "docstring": "Adds a hyperedge to the hypergraph, along with any related\n            attributes of the hyperedge.\n            This method will automatically add any node from the node set\n            that was not in the hypergraph.\n            A hyperedge without a \"weight\" attribute specified will be\n            assigned the default value of 1.\n\n        :param nodes: iterable container of references to nodes in the\n                    hyperedge to be added.\n        :param attr_dict: dictionary of attributes of the hyperedge being\n                        added.\n        :param attr: keyword arguments of attributes of the hyperedge;\n                    attr's values will override attr_dict's values\n                    if both are provided.\n        :returns: str -- the ID of the hyperedge that was added.\n        :raises: ValueError -- nodes arguments cannot be empty.\n\n        Examples:\n        ::\n\n            >>> H = UndirectedHypergraph()\n            >>> x = H.add_hyperedge([\"A\", \"B\", \"C\"])\n            >>> y = H.add_hyperedge((\"A\", \"D\"), weight=2)\n            >>> z = H.add_hyperedge(set([\"B\", \"D\"]), {color: \"red\"})"
  },
  {
    "code": "def split_by_connected_component(self, idents):\n        idents_remaining = set(idents)\n        connected_components = []\n        for ident in idents:\n            if ident not in idents_remaining:\n                continue\n            idents_remaining.remove(ident)\n            connected_component = [ident]\n            for label in self.connected_component(ident):\n                cids = label.content_id1, label.content_id2\n                for cid in cids:\n                    if cid in idents_remaining:\n                        connected_component.append(cid)\n                        idents_remaining.remove(cid)\n            connected_components.append(sorted(connected_component))\n        return connected_components",
    "docstring": "Split idents into equivalence classes based on connected\n        components."
  },
  {
    "code": "def rename(self, name=None, sourceNetwork=None, verbose=False):\n        sourceNetwork=check_network(self,sourceNetwork,verbose=verbose)\n        PARAMS=set_param([\"name\",\"sourceNetwork\"],[name,sourceNetwork])\n        response=api(url=self.__url+\"/rename\", PARAMS=PARAMS, method=\"POST\", verbose=verbose)\n        return response",
    "docstring": "Rename an existing network. The SUID of the network is returned\n\n        :param name (string): Enter a new title for the network\n        :param sourceNetwork (string): Specifies a network by name, or by SUID\n            if the prefix SUID: is used. The keyword CURRENT, or a blank value\n            can also be used to specify the current network.\n        :param verbose: print more\n\n        :returns: SUID of the network is returned"
  },
  {
    "code": "def load_data_file(path_of_file):\n    if os.path.exists(path_of_file):\n        return storage_utils.load_objects_from_json(path_of_file)\n    raise ValueError(\"Data file not found: {0}\".format(path_of_file))",
    "docstring": "Loads the content of a file by using json.load.\n\n    :param path_of_file: the path of the file to load\n    :return: the file content as a string\n    :raises exceptions.ValueError: if the file was not found"
  },
  {
    "code": "def concat(attrs, inputs, proto_obj):\n    new_attrs = translation_utils._fix_attribute_names(attrs, {'axis': 'dim'})\n    return 'concat', new_attrs, inputs",
    "docstring": "Joins input arrays along a given axis."
  },
  {
    "code": "def set_per_page(self, entries=100):\n        if isinstance(entries, int) and entries <= 200:\n            self.per_page = int(entries)\n            return self\n        else:\n            raise SalesKingException(\"PERPAGE_ONLYINT\", \"Please set an integer <200 for the per-page limit\");",
    "docstring": "set entries per page max 200"
  },
  {
    "code": "def get_barycenter(self):\n        try:\n            mass = self['mass'].values\n        except KeyError:\n            mass = self.add_data('mass')['mass'].values\n        pos = self.loc[:, ['x', 'y', 'z']].values\n        return (pos * mass[:, None]).sum(axis=0) / self.get_total_mass()",
    "docstring": "Return the mass weighted average location.\n\n        Args:\n            None\n\n        Returns:\n            :class:`numpy.ndarray`:"
  },
  {
    "code": "def get_bin_hierarchy_design_session(self):\n        if not self.supports_bin_hierarchy_design():\n            raise errors.Unimplemented()\n        return sessions.BinHierarchyDesignSession(runtime=self._runtime)",
    "docstring": "Gets the bin hierarchy design session.\n\n        return: (osid.resource.BinHierarchyDesignSession) - a\n                ``BinHierarchyDesignSession``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_bin_hierarchy_design()`` is\n                ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_bin_hierarchy_design()`` is ``true``.*"
  },
  {
    "code": "def serialize_math(ctx, document, elem, root):\n    _div = etree.SubElement(root, 'span')\n    if ctx.options['embed_styles']:\n        _div.set('style', 'border: 1px solid red')\n    _div.text = 'We do not support Math blocks at the moment.'\n    fire_hooks(ctx, document, elem, _div, ctx.get_hook('math'))\n    return root",
    "docstring": "Serialize math element.\n\n    Math objects are not supported at the moment. This is wht we only show error message."
  },
  {
    "code": "def smart_content_encoding(self):\n        encoding = self.content_encoding\n        if not encoding:\n            base_list = self.basename.split('.')\n            while (not encoding) and len(base_list) > 1:\n                _, encoding = mimetypes.guess_type('.'.join(base_list))\n                base_list.pop()\n        return encoding",
    "docstring": "Smart content encoding."
  },
  {
    "code": "def reversed_dotted_parts(s):\n    idx = -1\n    if s:\n        yield s\n    while s:\n        idx = s.rfind('.', 0, idx)\n        if idx == -1:\n            break\n        yield s[:idx]",
    "docstring": "For a string \"a.b.c\", yields \"a.b.c\", \"a.b\", \"a\"."
  },
  {
    "code": "def read_block_epb(self, block, size):\n        intid, tshigh, tslow, caplen, wirelen = struct.unpack(\n            self.endian + \"5I\",\n            block[:20],\n        )\n        return (block[20:20 + caplen][:size],\n                RawPcapNgReader.PacketMetadata(linktype=self.interfaces[intid][0],\n                                               tsresol=self.interfaces[intid][2],\n                                               tshigh=tshigh,\n                                               tslow=tslow,\n                                               wirelen=wirelen))",
    "docstring": "Enhanced Packet Block"
  },
  {
    "code": "def _align_sequences_to_hmm(self, hmm_file, sequences_file, output_alignment_file):\n        ss = SequenceSearcher(hmm_file)\n        with tempfile.NamedTemporaryFile(prefix='graftm', suffix='.aln.fasta') as tempalign:\n            ss.hmmalign_sequences(hmm_file, sequences_file, tempalign.name)\n            ss.alignment_correcter([tempalign.name], output_alignment_file)",
    "docstring": "Align sequences to an HMM, and write an alignment of\n        these proteins after cleanup so that they can be used for tree-making\n\n        Parameters\n        ----------\n        sequences_file: str\n            path to file of unaligned protein sequences\n        hmm_file: str\n            path to hmm file\n        output_alignment_file: str\n            write alignment to this file\n\n        Returns\n        -------\n        nothing"
  },
  {
    "code": "def alpha2(self, code):\n        code = force_text(code).upper()\n        if code.isdigit():\n            lookup_code = int(code)\n            def find(alt_codes):\n                return alt_codes[1] == lookup_code\n        elif len(code) == 3:\n            lookup_code = code\n            def find(alt_codes):\n                return alt_codes[0] == lookup_code\n        else:\n            find = None\n        if find:\n            code = None\n            for alpha2, alt_codes in self.alt_codes.items():\n                if find(alt_codes):\n                    code = alpha2\n                    break\n        if code in self.countries:\n            return code\n        return \"\"",
    "docstring": "Return the two letter country code when passed any type of ISO 3166-1\n        country code.\n\n        If no match is found, returns an empty string."
  },
  {
    "code": "def install(self):\n        items = []\n        for typeName in self.types:\n            it = self.store.findOrCreate(namedAny(typeName))\n            installOn(it, self.store)\n            items.append(str(it.storeID).decode('ascii'))\n        self._items = items",
    "docstring": "Called when installed on the user store. Installs my powerups."
  },
  {
    "code": "def bpoints(self):\n        return self.start, self.control1, self.control2, self.end",
    "docstring": "returns the Bezier control points of the segment."
  },
  {
    "code": "def available_dataset_names(self, reader_name=None, composites=False):\n        return sorted(set(x.name for x in self.available_dataset_ids(\n            reader_name=reader_name, composites=composites)))",
    "docstring": "Get the list of the names of the available datasets."
  },
  {
    "code": "def from_file(cls, file, charset='utf-8', errors='strict',\n                  unicode_mode=True):\n        close = False\n        f = file\n        if isinstance(file, basestring):\n            f = open(file, 'r')\n            close = True\n        try:\n            data = _decode_unicode(f.read(), charset, errors)\n        finally:\n            if close:\n                f.close()\n        return cls(data, getattr(f, 'name', '<template>'), charset,\n                   errors, unicode_mode)",
    "docstring": "Load a template from a file.\n\n        .. versionchanged:: 0.5\n            The encoding parameter was renamed to charset.\n\n        :param file: a filename or file object to load the template from.\n        :param charset: the charset of the template to load.\n        :param errors: the error behavior of the charset decoding.\n        :param unicode_mode: set to `False` to disable unicode mode.\n        :return: a template"
  },
  {
    "code": "def addVariantAnnotationSet(self, variantAnnotationSet):\n        id_ = variantAnnotationSet.getId()\n        self._variantAnnotationSetIdMap[id_] = variantAnnotationSet\n        self._variantAnnotationSetIds.append(id_)",
    "docstring": "Adds the specified variantAnnotationSet to this dataset."
  },
  {
    "code": "def remove_node(self, node):\n        if not self.has_node(node):\n            raise ValueError(\"No such node exists.\")\n        for hyperedge_id in self._star[node]:\n            frozen_nodes = \\\n                self._hyperedge_attributes[hyperedge_id][\"__frozen_nodes\"]\n            del self._node_set_to_hyperedge[frozen_nodes]\n            del self._hyperedge_attributes[hyperedge_id]\n        del self._star[node]\n        del self._node_attributes[node]",
    "docstring": "Removes a node and its attributes from the hypergraph. Removes\n        every hyperedge that contains this node.\n\n        :param node: reference to the node being added.\n        :raises: ValueError -- No such node exists.\n\n        Examples:\n        ::\n\n            >>> H = UndirectedHypergraph()\n            >>> H.add_node(\"A\", label=\"positive\")\n            >>> H.remove_node(\"A\")"
  },
  {
    "code": "def _do_analysis(options):\n    module = _function_location(options)\n    core_results = _call_analysis_function(options, module)\n    if module == 'emp' and ('models' in options.keys()):\n        fit_results = _fit_models(options, core_results)\n    else:\n        fit_results = None\n    _save_results(options, module, core_results, fit_results)",
    "docstring": "Do analysis for a single run, as specified by options.\n\n    Parameters\n    ----------\n    options : dict\n        Option names and values for analysis"
  },
  {
    "code": "def process_request(self, request):\n        global _urlconf_pages\n        page_list = list(\n            Page.objects.exclude(glitter_app_name='').values_list('id', 'url').order_by('id')\n        )\n        with _urlconf_lock:\n            if page_list != _urlconf_pages:\n                glitter_urls = 'glitter.urls'\n                if glitter_urls in sys.modules:\n                    importlib.reload(sys.modules[glitter_urls])\n                _urlconf_pages = page_list",
    "docstring": "Reloads glitter URL patterns if page URLs change.\n\n        Avoids having to restart the server to recreate the glitter URLs being used by Django."
  },
  {
    "code": "def _bounds_to_array(bounds):\n    elements = []\n    for value in bounds:\n        if all_elements_equal(value):\n            elements.append(Scalar(get_single_value(value), ctype='mot_float_type'))\n        else:\n            elements.append(Array(value, ctype='mot_float_type', as_scalar=True))\n    return CompositeArray(elements, 'mot_float_type', address_space='local')",
    "docstring": "Create a CompositeArray to hold the bounds."
  },
  {
    "code": "def reset_state(self, reset_state):\n        if isinstance(reset_state, int):\n            self._pool.map(_reset_state,\n                           self._shard_num_args({'reset_state': reset_state}))\n        elif isinstance(reset_state, np.ndarray):\n            sim.validate_normalized_state(reset_state, self._num_qubits)\n            args = []\n            for kwargs in self._shard_num_args():\n                shard_num = kwargs['shard_num']\n                shard_size = 1 << kwargs['num_shard_qubits']\n                start = shard_num * shard_size\n                end = start + shard_size\n                kwargs['reset_state'] = reset_state[start:end]\n                args.append(kwargs)\n            self._pool.map(_reset_state, args)",
    "docstring": "Reset the state to the given initial state.\n\n        Args:\n            reset_state: If this is an int, then this is the state to reset\n                the stepper to, expressed as an integer of the computational\n                basis. Integer to bitwise indices is little endian. Otherwise\n                if this is a np.ndarray this must be the correct size, be\n                normalized (L2 norm of 1), and have dtype of np.complex64.\n\n        Raises:\n            ValueError if the state is incorrectly sized or not of the correct\n            dtype."
  },
  {
    "code": "def get_parts(self):\n        parts = []\n        start_b = 0\n        end_byte = start_b + PartSize.DOWNLOAD_MINIMUM_PART_SIZE - 1\n        for i in range(self.total):\n            parts.append([start_b, end_byte])\n            start_b = end_byte + 1\n            end_byte = start_b + PartSize.DOWNLOAD_MINIMUM_PART_SIZE - 1\n        return parts",
    "docstring": "Partitions the file and saves the part information in memory."
  },
  {
    "code": "def process_dut(dut):\n        if dut.finished():\n            return\n        Dut._signalled_duts.appendleft(dut)\n        Dut._sem.release()",
    "docstring": "Signal worker thread that specified Dut needs processing"
  },
  {
    "code": "def _format_coord(self, x, limits):\n        if x is None:\n            return None\n        formatter = self._mplformatter\n        formatter.locs = np.linspace(limits[0], limits[1], 7)\n        formatter._set_format(*limits)\n        formatter._set_orderOfMagnitude(abs(np.diff(limits)))\n        return formatter.pprint_val(x)",
    "docstring": "Handles display-range-specific formatting for the x and y coords.\n\n        Parameters\n        ----------\n        x : number\n            The number to be formatted\n        limits : 2-item sequence\n            The min and max of the current display limits for the axis."
  },
  {
    "code": "def __update_offsets(self, fileobj, atoms, delta, offset):\n        if delta == 0:\n            return\n        moov = atoms[b\"moov\"]\n        for atom in moov.findall(b'stco', True):\n            self.__update_offset_table(fileobj, \">%dI\", atom, delta, offset)\n        for atom in moov.findall(b'co64', True):\n            self.__update_offset_table(fileobj, \">%dQ\", atom, delta, offset)\n        try:\n            for atom in atoms[b\"moof\"].findall(b'tfhd', True):\n                self.__update_tfhd(fileobj, atom, delta, offset)\n        except KeyError:\n            pass",
    "docstring": "Update offset tables in all 'stco' and 'co64' atoms."
  },
  {
    "code": "def from_json_to_list(cls, data: str,\n                          force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> TList[T]:\n        return cls.from_dicts(util.load_json(data),\n                              force_snake_case=force_snake_case,\n                              force_cast=force_cast,\n                              restrict=restrict)",
    "docstring": "From json string to list of instance\n\n        :param data: Json string\n        :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True\n        :param force_cast: Cast forcibly if True\n        :param restrict: Prohibit extra parameters if True\n        :return: List of instance\n\n        Usage:\n\n            >>> from owlmixin.samples import Human\n            >>> humans: TList[Human] = Human.from_json_to_list('''[\n            ...    {\"id\": 1, \"name\": \"Tom\",  \"favorites\": [{\"name\": \"Apple\"}]},\n            ...    {\"id\": 2, \"name\": \"John\", \"favorites\": [{\"name\": \"Orange\"}]}\n            ... ]''')\n            >>> humans[0].name\n            'Tom'\n            >>> humans[1].name\n            'John'"
  },
  {
    "code": "def default_suse_tr(mod):\n    pkg = 'python-%s' % mod\n    py2pkg = 'python2-%s' % mod\n    py3pkg = 'python3-%s' % mod\n    return (pkg, py2pkg, py3pkg)",
    "docstring": "Default translation function for openSUSE, SLES, and other\n    SUSE based systems\n\n    Returns a tuple of 3 elements - the unversioned name, the python2 versioned\n    name and the python3 versioned name."
  },
  {
    "code": "def convert_size(size_bytes):\n    if size_bytes == 0:\n        return \"0B\"\n    size_name = (\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\")\n    i = int(math.floor(math.log(size_bytes, 1024)))\n    p = math.pow(1024, i)\n    s = round(size_bytes / p, 2)\n    return \"%s %s\" % (s, size_name[i])",
    "docstring": "Transform bytesize to a human readable filesize\n\n    :param size_bytes: bytesize\n    :return: human readable filesize"
  },
  {
    "code": "def previous_theme(self):\n        theme = self.term.theme_list.previous(self.term.theme)\n        while not self.term.check_theme(theme):\n            theme = self.term.theme_list.previous(theme)\n        self.term.set_theme(theme)\n        self.draw()\n        message = self.term.theme.display_string\n        self.term.show_notification(message, timeout=1)",
    "docstring": "Cycle to preview the previous theme from the internal list of themes."
  },
  {
    "code": "def system_add_keyspace(self, ks_def):\n    self._seqid += 1\n    d = self._reqs[self._seqid] = defer.Deferred()\n    self.send_system_add_keyspace(ks_def)\n    return d",
    "docstring": "adds a keyspace and any column families that are part of it. returns the new schema id.\n\n    Parameters:\n     - ks_def"
  },
  {
    "code": "def label_from_bin(buf):\n    mpls_label = type_desc.Int3.to_user(six.binary_type(buf))\n    return mpls_label >> 4, mpls_label & 1",
    "docstring": "Converts binary representation label to integer.\n\n    :param buf: Binary representation of label.\n    :return: MPLS Label and BoS bit."
  },
  {
    "code": "def can_fetch_pool(self, request: Request):\n        url_info = request.url_info\n        user_agent = request.fields.get('User-agent', '')\n        if self._robots_txt_pool.has_parser(url_info):\n            return self._robots_txt_pool.can_fetch(url_info, user_agent)\n        else:\n            raise NotInPoolError()",
    "docstring": "Return whether the request can be fetched based on the pool."
  },
  {
    "code": "def verify_login(request):\n    verifier = request.registry['persona.verifier']\n    try:\n        data = verifier.verify(request.POST['assertion'])\n    except (ValueError, browserid.errors.TrustError) as e:\n        logger.info('Failed persona login: %s (%s)', e, type(e).__name__)\n        raise HTTPBadRequest('Invalid assertion')\n    return data['email']",
    "docstring": "Verifies the assertion and the csrf token in the given request.\n\n    Returns the email of the user if everything is valid, otherwise raises\n    a HTTPBadRequest"
  },
  {
    "code": "def delta_nu(self, *args):\n        return 134.88 * np.sqrt(self.mass(*args) / self.radius(*args)**3)",
    "docstring": "Returns asteroseismic delta_nu in uHz\n\n        reference: https://arxiv.org/pdf/1312.3853v1.pdf, Eq (2)"
  },
  {
    "code": "def AddFareObject(self, fare, problem_reporter=None):\n    warnings.warn(\"No longer supported. The Fare class was renamed to \"\n                  \"FareAttribute, and all related functions were renamed \"\n                  \"accordingly.\", DeprecationWarning)\n    self.AddFareAttributeObject(fare, problem_reporter)",
    "docstring": "Deprecated. Please use AddFareAttributeObject."
  },
  {
    "code": "def get_attached_message(self, key, message_type, tags=None, required=False):\n    attached_bytes = self._get_attached_bytes(key, tags)\n    if attached_bytes is None:\n      if required:\n        raise KeyError(\"No attached message for key '%s' in graph version %s \"\n                       \"of Hub Module\" % (key, sorted(tags or [])))\n      else:\n        return None\n    message = message_type()\n    message.ParseFromString(attached_bytes)\n    return message",
    "docstring": "Returns the message attached to the module under the given key, or None.\n\n    Module publishers can attach protocol messages to modules at creation time\n    to provide module consumers with additional information, e.g., on module\n    usage or provenance (see see hub.attach_message()). A typical use would be\n    to store a small set of named values with modules of a certain type so\n    that a support library for consumers of such modules can be parametric\n    in those values.\n\n    This method can also be called on a Module instantiated from a ModuleSpec,\n    then `tags` are set to those used in module instatiation.\n\n    Args:\n      key: A string with the key of an attached message.\n      message_type: A concrete protocol message class (*not* object) used\n        to parse the attached message from its serialized representation.\n        The message type for a particular key must be advertised with the key.\n      tags: Optional set of strings, specifying the graph variant from which\n        to read the attached message.\n      required: An optional boolean. Setting it true changes the effect of\n        an unknown `key` from returning None to raising a KeyError with text\n        about attached messages.\n\n    Returns:\n      An instance of `message_type` with the message contents attached to the\n      module, or `None` if `key` is unknown and `required` is False.\n\n    Raises:\n      KeyError: if `key` is unknown and `required` is True."
  },
  {
    "code": "def train_epoch(model:nn.Module, dl:DataLoader, opt:optim.Optimizer, loss_func:LossFunction)->None:\n    \"Simple training of `model` for 1 epoch of `dl` using optim `opt` and loss function `loss_func`.\"\n    model.train()\n    for xb,yb in dl:\n        loss = loss_func(model(xb), yb)\n        loss.backward()\n        opt.step()\n        opt.zero_grad()",
    "docstring": "Simple training of `model` for 1 epoch of `dl` using optim `opt` and loss function `loss_func`."
  },
  {
    "code": "def set_info_handler(codec, handler, data=None):\n    OPENJP2.opj_set_info_handler.argtypes = [CODEC_TYPE,\n                                             ctypes.c_void_p,\n                                             ctypes.c_void_p]\n    OPENJP2.opj_set_info_handler.restype = check_error\n    OPENJP2.opj_set_info_handler(codec, handler, data)",
    "docstring": "Wraps openjp2 library function opj_set_info_handler.\n\n    Set the info handler use by openjpeg.\n\n    Parameters\n    ----------\n    codec : CODEC_TYPE\n        Codec initialized by create_compress function.\n    handler : python function\n        The callback function to be used.\n    user_data : anything\n        User/client data.\n\n    Raises\n    ------\n    RuntimeError\n        If the OpenJPEG library routine opj_set_info_handler fails."
  },
  {
    "code": "def as_rational(self):\n        (denominator, numerator) = \\\n           NatDivision.undivision(\n              self.integer_part,\n              self.non_repeating_part,\n              self.repeating_part,\n              self.base\n           )\n        result = Fraction(\n           Nats.convert_to_int(numerator, self.base),\n           Nats.convert_to_int(denominator, self.base)\n        )\n        return result * self.sign",
    "docstring": "Return this value as a Rational.\n\n        :returns: this radix as a rational\n        :rtype: Rational"
  },
  {
    "code": "def get_conn(opts, profile=None, host=None, port=None):\n    if not (host and port):\n        opts_pillar = opts.get('pillar', {})\n        opts_master = opts_pillar.get('master', {})\n        opts_merged = {}\n        opts_merged.update(opts_master)\n        opts_merged.update(opts_pillar)\n        opts_merged.update(opts)\n        if profile:\n            conf = opts_merged.get(profile, {})\n        else:\n            conf = opts_merged\n        host = conf.get('memcached.host', DEFAULT_HOST)\n        port = conf.get('memcached.port', DEFAULT_PORT)\n    if not six.text_type(port).isdigit():\n        raise SaltInvocationError('port must be an integer')\n    if HAS_LIBS:\n        return memcache.Client(['{0}:{1}'.format(host, port)])\n    else:\n        raise CommandExecutionError(\n            '(unable to import memcache, '\n            'module most likely not installed)'\n        )",
    "docstring": "Return a conn object for accessing memcached"
  },
  {
    "code": "def setnx(self, name, value):\n        with self.pipe as pipe:\n            return pipe.setnx(self.redis_key(name),\n                              self.valueparse.encode(value))",
    "docstring": "Set the value as a string in the key only if the key doesn't exist.\n\n        :param name: str     the name of the redis key\n        :param value:\n        :return: Future()"
  },
  {
    "code": "def encode(self, s):\n    return [int(w) + self._num_reserved_ids for w in s.split()]",
    "docstring": "Transform a human-readable string into a sequence of int ids.\n\n    The ids should be in the range [num_reserved_ids, vocab_size). Ids [0,\n    num_reserved_ids) are reserved.\n\n    EOS is not appended.\n\n    Args:\n      s: human-readable string to be converted.\n\n    Returns:\n      ids: list of integers"
  },
  {
    "code": "def get_catalog(self, query):\n        try:\n            url = self._base[:-1] if self._base[-1] == '/' else self._base\n            url += '?' + str(query)\n            return TDSCatalog(url)\n        except ET.ParseError:\n            raise BadQueryError(self.get_catalog_raw(query))",
    "docstring": "Fetch a parsed THREDDS catalog from the radar server.\n\n        Requests a catalog of radar data files data from the radar server given the\n        parameters in `query` and returns a :class:`~siphon.catalog.TDSCatalog` instance.\n\n        Parameters\n        ----------\n        query : RadarQuery\n            The parameters to send to the radar server\n\n        Returns\n        -------\n        catalog : TDSCatalog\n            The catalog of matching data files\n\n        Raises\n        ------\n        :class:`~siphon.http_util.BadQueryError`\n            When the query cannot be handled by the server\n\n        See Also\n        --------\n        get_catalog_raw"
  },
  {
    "code": "def generate_cloudformation_args(stack_name, parameters, tags, template,\n                                 capabilities=DEFAULT_CAPABILITIES,\n                                 change_set_type=None,\n                                 service_role=None,\n                                 stack_policy=None,\n                                 change_set_name=None):\n    args = {\n        \"StackName\": stack_name,\n        \"Parameters\": parameters,\n        \"Tags\": tags,\n        \"Capabilities\": capabilities,\n    }\n    if service_role:\n        args[\"RoleARN\"] = service_role\n    if change_set_name:\n        args[\"ChangeSetName\"] = change_set_name\n    if change_set_type:\n        args[\"ChangeSetType\"] = change_set_type\n    if template.url:\n        args[\"TemplateURL\"] = template.url\n    else:\n        args[\"TemplateBody\"] = template.body\n    if not change_set_name:\n        args.update(generate_stack_policy_args(stack_policy))\n    return args",
    "docstring": "Used to generate the args for common cloudformation API interactions.\n\n    This is used for create_stack/update_stack/create_change_set calls in\n    cloudformation.\n\n    Args:\n        stack_name (str): The fully qualified stack name in Cloudformation.\n        parameters (list): A list of dictionaries that defines the\n            parameter list to be applied to the Cloudformation stack.\n        tags (list): A list of dictionaries that defines the tags\n            that should be applied to the Cloudformation stack.\n        template (:class:`stacker.provider.base.Template`): The template\n            object.\n        capabilities (list, optional): A list of capabilities to use when\n            updating Cloudformation.\n        change_set_type (str, optional): An optional change set type to use\n            with create_change_set.\n        service_role (str, optional): An optional service role to use when\n            interacting with Cloudformation.\n        stack_policy (:class:`stacker.providers.base.Template`): A template\n            object representing a stack policy.\n        change_set_name (str, optional): An optional change set name to use\n            with create_change_set.\n\n    Returns:\n        dict: A dictionary of arguments to be used in the Cloudformation API\n            call."
  },
  {
    "code": "def _select_parent(action_set):\n        total_fitness = sum(rule.fitness for rule in action_set)\n        selector = random.uniform(0, total_fitness)\n        for rule in action_set:\n            selector -= rule.fitness\n            if selector <= 0:\n                return rule\n        return random.choice(list(action_set))",
    "docstring": "Select a rule from this action set, with probability\n        proportionate to its fitness, to act as a parent for a new rule in\n        the classifier set. Return the selected rule."
  },
  {
    "code": "def assertType(var, *allowedTypes):\n    if not isinstance(var, *allowedTypes):\n        raise NotImplementedError(\"This operation is only supported for {}. \"\\\n            \"Instead found {}\".format(str(*allowedTypes), type(var)))",
    "docstring": "Asserts that a variable @var is of an @expectedType. Raises a TypeError\n    if the assertion fails."
  },
  {
    "code": "def spawn_agent(self, agent_definition, location):\n        self._should_write_to_command_buffer = True\n        self._add_agents(agent_definition)\n        command_to_send = SpawnAgentCommand(location, agent_definition.name, agent_definition.type)\n        self._commands.add_command(command_to_send)",
    "docstring": "Queues a spawn agent command. It will be applied when `tick` or `step` is called next.\n        The agent won't be able to be used until the next frame.\n\n        Args:\n            agent_definition (:obj:`AgentDefinition`): The definition of the agent to spawn.\n            location (np.ndarray or list): The position to spawn the agent in the world, in XYZ coordinates (in meters)."
  },
  {
    "code": "def parse(self):\n        if self.rorg in [RORG.RPS, RORG.BS1, RORG.BS4]:\n            self.status = self.data[-1]\n        if self.rorg == RORG.VLD:\n            self.status = self.optional[-1]\n        if self.rorg in [RORG.RPS, RORG.BS1, RORG.BS4]:\n            self.repeater_count = enocean.utils.from_bitarray(self._bit_status[4:])\n        return self.parsed",
    "docstring": "Parse data from Packet"
  },
  {
    "code": "def delete(self):\n        \" Delete the record.\"\n        response = self.dyn.delete(self.url)\n        return response.content['job_id']",
    "docstring": "Delete the record."
  },
  {
    "code": "def run(self, service_id, **kwargs):\n        log = self.get_logger(**kwargs)\n        log.info(\"Loading Service for metric sync\")\n        try:\n            service = Service.objects.get(id=service_id)\n            log.info(\"Getting metrics for <%s>\" % (service.name))\n            metrics = self.get_metrics(service.url, service.token)\n            result = metrics.json()\n            if \"metrics_available\" in result:\n                for key in result[\"metrics_available\"]:\n                    check = WidgetData.objects.filter(service=service, key=key)\n                    if not check.exists():\n                        WidgetData.objects.create(\n                            service=service,\n                            key=key,\n                            title=\"TEMP - Pending update\"\n                        )\n                        log.info(\"Add WidgetData for <%s>\" % (key,))\n            return \"Completed metric sync for <%s>\" % (service.name)\n        except ObjectDoesNotExist:\n            logger.error('Missing Service', exc_info=True)\n        except SoftTimeLimitExceeded:\n            logger.error(\n                'Soft time limit exceed processing pull of service metrics \\\n                 via Celery.',\n                exc_info=True)",
    "docstring": "Retrieve a list of metrics. Ensure they are set as metric data sources."
  },
  {
    "code": "def _find_workflows(mcs, attrs):\n        workflows = {}\n        for attribute, value in attrs.items():\n            if isinstance(value, Workflow):\n                workflows[attribute] = StateField(value)\n        return workflows",
    "docstring": "Finds all occurrences of a workflow in the attributes definitions.\n\n        Returns:\n            dict(str => StateField): maps an attribute name to a StateField\n                describing the related Workflow."
  },
  {
    "code": "def css(self, *props, **kwprops):\n        self._stable = False\n        styles = {}\n        if props:\n            if len(props) == 1 and isinstance(props[0], Mapping):\n                styles = props[0]\n            else:\n                raise WrongContentError(self, props, \"Arguments not valid\")\n        elif kwprops:\n            styles = kwprops\n        else:\n            raise WrongContentError(self, None, \"args OR wkargs are needed\")\n        return self.attr(style=styles)",
    "docstring": "Adds css properties to this element."
  },
  {
    "code": "def _meta_schema_factory(self, columns, model, class_mixin):\n        _model = model\n        if columns:\n            class MetaSchema(ModelSchema, class_mixin):\n                class Meta:\n                    model = _model\n                    fields = columns\n                    strict = True\n                    sqla_session = self.datamodel.session\n        else:\n            class MetaSchema(ModelSchema, class_mixin):\n                class Meta:\n                    model = _model\n                    strict = True\n                    sqla_session = self.datamodel.session\n        return MetaSchema",
    "docstring": "Creates ModelSchema marshmallow-sqlalchemy\n\n        :param columns: a list of columns to mix\n        :param model: Model\n        :param class_mixin: a marshamallow Schema to mix\n        :return: ModelSchema"
  },
  {
    "code": "async def create(self, config: dict = None, access: str = None, replace: bool = False) -> Wallet:\n        LOGGER.debug('WalletManager.create >>> config %s, access %s, replace %s', config, access, replace)\n        assert {'name', 'id'} & {k for k in config}\n        wallet_name = config.get('name', config.get('id'))\n        if replace:\n            von_wallet = self.get(config, access)\n            if not await von_wallet.remove():\n                LOGGER.debug('WalletManager.create <!< Failed to remove wallet %s for replacement', wallet_name)\n                raise ExtantWallet('Failed to remove wallet {} for replacement'.format(wallet_name))\n        indy_config = self._config2indy(config)\n        von_config = self._config2von(config, access)\n        rv = Wallet(indy_config, von_config)\n        await rv.create()\n        LOGGER.debug('WalletManager.create <<< %s', rv)\n        return rv",
    "docstring": "Create wallet on input name with given configuration and access credential value.\n\n        Raise ExtantWallet if wallet on input name exists already and replace parameter is False.\n        Raise BadAccess on replacement for bad access credentials value.\n\n        FAIR WARNING: specifying replace=True attempts to remove any matching wallet before proceeding; to\n        succeed, the existing wallet must use the same access credentials that the input configuration has.\n\n        :param config: configuration data for both indy-sdk and VON anchor wallet:\n\n            - 'name' or 'id': wallet name\n            - 'storage_type': storage type\n            - 'freshness_time': freshness time\n            - 'did': (optional) DID to use\n            - 'seed': (optional) seed to use\n            - 'auto_create': whether to create the wallet on first open (persists past close, can work with auto_remove)\n            - 'auto_remove': whether to remove the wallet on next close\n            - 'link_secret_label': (optional) link secret label to use to create link secret\n\n        :param access: indy wallet access credential ('key') value, if different than default\n        :param replace: whether to replace old wallet if it exists\n        :return: wallet created"
  },
  {
    "code": "def cmd_loadfile(args):\n    if len(args) != 1:\n        fileargs = \" \".join(args)\n    else:\n        fileargs = args[0]\n    if not os.path.exists(fileargs):\n        print(\"Error loading file \", fileargs);\n        return\n    if os.name == 'nt':\n        fileargs = fileargs.replace(\"\\\\\", \"/\")\n    loadfile(fileargs.strip('\"'))",
    "docstring": "callback from menu to load a log file"
  },
  {
    "code": "def config_extensions(app):\n    \" Init application with extensions. \"\n    cache.init_app(app)\n    db.init_app(app)\n    main.init_app(app)\n    collect.init_app(app)\n    config_babel(app)",
    "docstring": "Init application with extensions."
  },
  {
    "code": "async def register_callback(self, cb):\n        self._callbacks.add(cb)\n        def unregister():\n            self._callbacks.remove(cb)\n        return unregister",
    "docstring": "Allows the caller to register a callback, and returns a closure\n        that can be used to unregister the provided callback"
  },
  {
    "code": "def parse_value(self, value):\n        parsed = super(BoolField, self).parse_value(value)\n        return bool(parsed) if parsed is not None else None",
    "docstring": "Cast value to `bool`."
  },
  {
    "code": "def authenticate(json_path=None):\n  msg = ('budou.authentication() is deprecated. '\n         'Please use budou.get_parser() to obtain a parser instead.')\n  warnings.warn(msg, DeprecationWarning)\n  parser = get_parser('nlapi', credentials_path=json_path)\n  return parser",
    "docstring": "Gets a Natural Language API parser by authenticating the API.\n\n  **This method is deprecated.** Please use :obj:`budou.get_parser` to obtain a\n  parser instead.\n\n  Args:\n    json_path (:obj:`str`, optional): The file path to the service account's\n        credentials.\n\n  Returns:\n    Parser. (:obj:`budou.parser.NLAPIParser`)"
  },
  {
    "code": "def set_todo_results(self, filename, todo_results):\r\n        index = self.has_filename(filename)\r\n        if index is None:\r\n            return\r\n        self.data[index].set_todo_results(todo_results)",
    "docstring": "Synchronize todo results between editorstacks"
  },
  {
    "code": "def _raise_last_error(bulk_write_result):\n    write_errors = bulk_write_result.get(\"writeErrors\")\n    if write_errors:\n        _raise_last_write_error(write_errors)\n    _raise_write_concern_error(bulk_write_result[\"writeConcernErrors\"][-1])",
    "docstring": "Backward compatibility helper for insert error handling."
  },
  {
    "code": "def survey_loader(sur_dir=SUR_DIR, sur_file=SUR_FILE):\n    survey_path = os.path.join(sur_dir, sur_file)\n    survey = None\n    with open(survey_path) as survey_file:\n        survey = Survey(survey_file.read())\n    return survey",
    "docstring": "Loads up the given survey in the given dir."
  },
  {
    "code": "def get_swagger_versions(settings):\n    swagger_versions = set(aslist(settings.get(\n        'pyramid_swagger.swagger_versions', DEFAULT_SWAGGER_VERSIONS)))\n    if len(swagger_versions) == 0:\n        raise ValueError('pyramid_swagger.swagger_versions is empty')\n    for swagger_version in swagger_versions:\n        if swagger_version not in SUPPORTED_SWAGGER_VERSIONS:\n            raise ValueError('Swagger version {0} is not supported.'\n                             .format(swagger_version))\n    return swagger_versions",
    "docstring": "Validates and returns the versions of the Swagger Spec that this pyramid\n    application supports.\n\n    :type settings: dict\n    :return: list of strings. eg ['1.2', '2.0']\n    :raises: ValueError when an unsupported Swagger version is encountered."
  },
  {
    "code": "def create(controller_id, name):\n        def _decorator(cls):\n            class _ControllerClass(cls, Controller):\n                def __init__(self):\n                    Controller.__init__(self, controller_id, name)\n                    for key in cls.__dict__.keys():\n                        prop = cls.__dict__[key]\n                        if isinstance(prop, KerviValue):\n                            if prop.is_input:\n                                self.inputs._add_internal(key, prop)\n                            else:\n                                self.outputs._add_internal(key, prop)\n                    cls.__init__(self)\n            return _ControllerClass\n        return _decorator",
    "docstring": "Turn class into a kervi controller"
  },
  {
    "code": "def export_data(self):\n        result = {}\n        data = self.__original_data__.copy()\n        data.update(self.__modified_data__)\n        for key, value in data.items():\n            if key in self.__deleted_fields__:\n                continue\n            try:\n                result[key] = value.export_data()\n            except AttributeError:\n                result[key] = value\n        return result",
    "docstring": "Get the results with the modified_data"
  },
  {
    "code": "def read_csr(csr):\n    csr = _get_request_obj(csr)\n    ret = {\n        'Version': csr.get_version() + 1,\n        'Subject': _parse_subject(csr.get_subject()),\n        'Subject Hash': _dec2hex(csr.get_subject().as_hash()),\n        'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),\n        'X509v3 Extensions': _get_csr_extensions(csr),\n    }\n    return ret",
    "docstring": "Returns a dict containing details of a certificate request.\n\n    :depends:   - OpenSSL command line tool\n\n    csr:\n        A path or PEM encoded string containing the CSR to read.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' x509.read_csr /etc/pki/mycert.csr"
  },
  {
    "code": "def make_check(exc_type, template, pred, actual, funcname):\n    if isinstance(funcname, str):\n        def get_funcname(_):\n            return funcname\n    else:\n        get_funcname = funcname\n    def _check(func, argname, argvalue):\n        if pred(argvalue):\n            raise exc_type(\n                template % {\n                    'funcname': get_funcname(func),\n                    'argname': argname,\n                    'actual': actual(argvalue),\n                },\n            )\n        return argvalue\n    return _check",
    "docstring": "Factory for making preprocessing functions that check a predicate on the\n    input value.\n\n    Parameters\n    ----------\n    exc_type : Exception\n        The exception type to raise if the predicate fails.\n    template : str\n        A template string to use to create error messages.\n        Should have %-style named template parameters for 'funcname',\n        'argname', and 'actual'.\n    pred : function[object -> bool]\n        A function to call on the argument being preprocessed.  If the\n        predicate returns `True`, we raise an instance of `exc_type`.\n    actual : function[object -> object]\n        A function to call on bad values to produce the value to display in the\n        error message.\n    funcname : str or callable\n        Name to use in error messages, or function to call on decorated\n        functions to produce a name.  Passing an explicit name is useful when\n        creating checks for __init__ or __new__ methods when you want the error\n        to refer to the class name instead of the method name."
  },
  {
    "code": "def ellipse(center,covariance_matrix,level=1, n=1000):\n    U, s, rotation_matrix = N.linalg.svd(covariance_matrix)\n    saxes = N.sqrt(s)*level\n    u = N.linspace(0, 2*N.pi, n)\n    data = N.column_stack((saxes[0]*N.cos(u), saxes[1]*N.sin(u)))\n    return N.dot(data, rotation_matrix)+ center",
    "docstring": "Returns error ellipse in slope-azimuth space"
  },
  {
    "code": "def parse_authentication_request(self, request_body, http_headers=None):\n        auth_req = AuthorizationRequest().deserialize(request_body)\n        for validator in self.authentication_request_validators:\n            validator(auth_req)\n        logger.debug('parsed authentication_request: %s', auth_req)\n        return auth_req",
    "docstring": "Parses and verifies an authentication request.\n\n        :param request_body: urlencoded authentication request\n        :param http_headers: http headers"
  },
  {
    "code": "def _base_placeholder(self):\n        base_ph_type = {\n            PP_PLACEHOLDER.BODY:         PP_PLACEHOLDER.BODY,\n            PP_PLACEHOLDER.CHART:        PP_PLACEHOLDER.BODY,\n            PP_PLACEHOLDER.BITMAP:       PP_PLACEHOLDER.BODY,\n            PP_PLACEHOLDER.CENTER_TITLE: PP_PLACEHOLDER.TITLE,\n            PP_PLACEHOLDER.ORG_CHART:    PP_PLACEHOLDER.BODY,\n            PP_PLACEHOLDER.DATE:         PP_PLACEHOLDER.DATE,\n            PP_PLACEHOLDER.FOOTER:       PP_PLACEHOLDER.FOOTER,\n            PP_PLACEHOLDER.MEDIA_CLIP:   PP_PLACEHOLDER.BODY,\n            PP_PLACEHOLDER.OBJECT:       PP_PLACEHOLDER.BODY,\n            PP_PLACEHOLDER.PICTURE:      PP_PLACEHOLDER.BODY,\n            PP_PLACEHOLDER.SLIDE_NUMBER: PP_PLACEHOLDER.SLIDE_NUMBER,\n            PP_PLACEHOLDER.SUBTITLE:     PP_PLACEHOLDER.BODY,\n            PP_PLACEHOLDER.TABLE:        PP_PLACEHOLDER.BODY,\n            PP_PLACEHOLDER.TITLE:        PP_PLACEHOLDER.TITLE,\n        }[self._element.ph_type]\n        slide_master = self.part.slide_master\n        return slide_master.placeholders.get(base_ph_type, None)",
    "docstring": "Return the master placeholder this layout placeholder inherits from."
  },
  {
    "code": "def rename_item_list(self, item_list_url, new_name):\n        data = json.dumps({'name': new_name})\n        resp = self.api_request(str(item_list_url), data, method=\"PUT\")\n        try:\n            return ItemList(resp['items'], self, item_list_url, resp['name'])\n        except KeyError:\n            try:\n                raise APIError('200', 'Rename operation failed', resp['error'])\n            except KeyError:\n                raise APIError('200', 'Rename operation failed', resp)",
    "docstring": "Rename an Item List on the server\n\n        :type item_list_url: String or ItemList\n        :param item_list_url: the URL of the list to which to add the items,\n            or an ItemList object\n        :type new_name: String\n        :param new_name: the new name to give the Item List\n\n        :rtype: ItemList\n        :returns: the item list, if successful\n\n        :raises: APIError if the request was not successful"
  },
  {
    "code": "def port_is_open():\n    with settings(hide('aborts'), warn_only=True ):\n        try:\n            if env.verbosity:\n                print \"Testing node for previous installation on port %s:\"% env.port\n            distribution = lsb_release()\n        except KeyboardInterrupt:\n            if env.verbosity:\n                print >> sys.stderr, \"\\nStopped.\"\n            sys.exit(1)\n        except:\n            return False\n        if distribution.distributor_id <> 'Ubuntu':\n            print env.host, 'WARNING: Woven has only been tested on Ubuntu >= 10.04. It may not work as expected on',distribution.description\n    return True",
    "docstring": "Determine if the default port and user is open for business."
  },
  {
    "code": "def block_user(self, username, domain):\n        self.set_password(username, domain, self.get_random_password())",
    "docstring": "Block the specified user.\n\n        The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` with a\n        random password.\n\n        :param username: The username of the user.\n        :type  username: str\n        :param   domain: The domain of the user.\n        :type    domain: str"
  },
  {
    "code": "def generate_seeds(num, root_seed, secret):\n        if num < 0:\n            raise HeartbeatError('%s is not greater than 0' % num)\n        if secret is None:\n            raise HeartbeatError('secret can not be of type NoneType')\n        seeds = []\n        try:\n            tmp_seed = hashlib.sha256(root_seed).digest()\n        except TypeError:\n            tmp_seed = hashlib.sha256(str(root_seed).encode()).digest()\n        for x in range(num):\n            seeds.append(tmp_seed)\n            h = hashlib.sha256(tmp_seed)\n            h.update(secret)\n            tmp_seed = h.digest()\n        return seeds",
    "docstring": "Deterministically generate list of seeds from a root seed.\n\n        :param num: Numbers of seeds to generate as int\n        :param root_seed: Seed to start off with.\n        :return: seed values as a list of length num"
  },
  {
    "code": "def set_input_container(_container, cfg):\n    if not _container:\n        return False\n    if _container.exists():\n        cfg[\"container\"][\"input\"] = str(_container)\n        return True\n    return False",
    "docstring": "Save the input for the container in the configurations."
  },
  {
    "code": "def is_zipstream(data):\n    if isinstance(data, (str, buffer)):\n        data = BytesIO(data)\n    if hasattr(data, \"read\"):\n        tell = 0\n        if hasattr(data, \"tell\"):\n            tell = data.tell()\n        try:\n            result = bool(_EndRecData(data))\n        except IOError:\n            result = False\n        if hasattr(data, \"seek\"):\n            data.seek(tell)\n    else:\n        raise TypeError(\"requies str, buffer, or stream-like object\")\n    return result",
    "docstring": "just like zipfile.is_zipfile, but works upon buffers and streams\n    rather than filenames.\n\n    If data supports the read method, it will be treated as a stream\n    and read from to test whether it is a valid ZipFile.\n\n    If data also supports the tell and seek methods, it will be\n    rewound after being tested."
  },
  {
    "code": "def assign(self, experiment):\n        self.experiments.append(experiment)\n        self.farms.append(empty_farm)",
    "docstring": "Assign an experiment."
  },
  {
    "code": "def update_lbaas_l7policy(self, l7policy, body=None):\n        return self.put(self.lbaas_l7policy_path % l7policy,\n                        body=body)",
    "docstring": "Updates L7 policy."
  },
  {
    "code": "def all(self):\n        return {\n            key: value\n            for key, value in chain(self.entry_points.items(), self.factories.items())\n        }",
    "docstring": "Return a synthetic dictionary of all factories."
  },
  {
    "code": "def rename(self, newname):\n    dic = self.to_json_dict()\n    if self._get_resource_root().version < 6:\n      dic['name'] = newname\n    else:\n      dic['displayName'] = newname\n    return self._put_cluster(dic)",
    "docstring": "Rename a cluster.\n\n    @param newname: New cluster name\n    @return: An ApiCluster object\n    @since: API v2"
  },
  {
    "code": "async def fetchmany(self, size: int = None) -> Iterable[sqlite3.Row]:\n        args = ()\n        if size is not None:\n            args = (size,)\n        return await self._execute(self._cursor.fetchmany, *args)",
    "docstring": "Fetch up to `cursor.arraysize` number of rows."
  },
  {
    "code": "def visualize_learning_result(self, state_key):\n        x, y = state_key\n        map_arr = copy.deepcopy(self.__map_arr)\n        goal_point_tuple = np.where(map_arr == self.__end_point_label)\n        goal_x, goal_y = goal_point_tuple\n        map_arr[y][x] = \"@\"\n        self.__map_arr_list.append(map_arr)\n        if goal_x == x and goal_y == y:\n            for i in range(10):\n                key = len(self.__map_arr_list) - (10 - i)\n                print(\"Number of searches: \" + str(key))\n                print(self.__map_arr_list[key])\n            print(\"Total number of searches: \" + str(self.t))\n            print(self.__map_arr_list[-1])\n            print(\"Goal !!\")",
    "docstring": "Visualize learning result."
  },
  {
    "code": "def to_bytes(instance, encoding='utf-8', error='strict'):\n    if isinstance(instance, bytes):\n        return instance\n    elif hasattr(instance, 'encode'):\n        return instance.encode(encoding, error)\n    elif isinstance(instance, list):\n        return list([to_bytes(item, encoding, error) for item in instance])\n    elif isinstance(instance, tuple):\n        return tuple([to_bytes(item, encoding, error) for item in instance])\n    elif isinstance(instance, dict):\n        return dict(\n            [(to_bytes(key, encoding, error), to_bytes(value, encoding, error))\n                for key, value in instance.items()])\n    else:\n        return instance",
    "docstring": "Convert an instance recursively to bytes."
  },
  {
    "code": "def dropout_no_scaling(x, keep_prob):\n  if keep_prob == 1.0:\n    return x\n  mask = tf.less(tf.random_uniform(tf.shape(x)), keep_prob)\n  return x * cast_like(mask, x)",
    "docstring": "Like tf.nn.dropout, but does not scale up.  Works on integers also.\n\n  Args:\n    x: a Tensor\n    keep_prob: a floating point number\n\n  Returns:\n    Tensor of the same shape as x."
  },
  {
    "code": "def blur(self):\n        scene = self.get_scene()\n        if scene and scene._focus_sprite == self:\n            scene._focus_sprite = None",
    "docstring": "removes focus from the current element if it has it"
  },
  {
    "code": "def raw_sensor_strings(self):\n        try:\n            with open(self.sensorpath, \"r\") as f:\n                data = f.readlines()\n        except IOError:\n            raise NoSensorFoundError(self.type_name, self.id)\n        if data[0].strip()[-3:] != \"YES\":\n            raise SensorNotReadyError(self)\n        return data",
    "docstring": "Reads the raw strings from the kernel module sysfs interface\n\n            :returns: raw strings containing all bytes from the sensor memory\n            :rtype: str\n\n            :raises NoSensorFoundError: if the sensor could not be found\n            :raises SensorNotReadyError: if the sensor is not ready yet"
  },
  {
    "code": "def decode(self, json_string):\n        default_obj = super(JSONPDecoder, self).decode(json_string)\n        return list(self._iterdecode(default_obj))[0]",
    "docstring": "json_string is basicly string that you give to json.loads method"
  },
  {
    "code": "def set_limit_override(self, service_name, limit_name,\n                           value, override_ta=True):\n        self.services[service_name].set_limit_override(\n            limit_name,\n            value,\n            override_ta=override_ta\n        )",
    "docstring": "Set a manual override on an AWS service limits, i.e. if you\n        had limits increased by AWS support.\n\n        This method calls :py:meth:`._AwsService.set_limit_override`\n        on the corresponding _AwsService instance.\n\n        Explicitly set limit overrides using this method will take\n        precedence over default limits. They will also take precedence over\n        limit information obtained via Trusted Advisor, unless ``override_ta``\n        is set to ``False``.\n\n        :param service_name: the name of the service to override limit for\n        :type service_name: str\n        :param limit_name: the name of the limit to override:\n        :type limit_name: str\n        :param value: the new (overridden) limit value)\n        :type value: int\n        :param override_ta: whether or not to use this value even if Trusted\n          Advisor supplies limit information\n        :type override_ta: bool\n        :raises: :py:exc:`ValueError` if limit_name is not known to the\n          service instance"
  },
  {
    "code": "def get_pull_request_number(task, source_env_prefix):\n    pull_request = _extract_from_env_in_payload(task, source_env_prefix + '_PULL_REQUEST_NUMBER')\n    if pull_request is not None:\n        pull_request = int(pull_request)\n    return pull_request",
    "docstring": "Get what Github pull request created the graph.\n\n    Args:\n        obj (ChainOfTrust or LinkOfTrust): the trust object to inspect\n        source_env_prefix (str): The environment variable prefix that is used\n            to get repository information.\n\n    Returns:\n        int: the pull request number.\n        None: if not defined for this task."
  },
  {
    "code": "def _update(self, resource, update_dict=None, params=None, **kwargs):\n        url = self._client._build_url(resource, **kwargs)\n        response = self._client._request('PUT', url, json=update_dict, params=params)\n        if response.status_code != requests.codes.ok:\n            raise APIError(\"Could not update {} ({})\".format(self.__class__.__name__, response.json().get('results')))\n        else:\n            self.refresh()",
    "docstring": "Update the object."
  },
  {
    "code": "def listen(self):\n        while True:\n            message = self.pull.recv()\n            logger.debug(\"received message of length %d\" % len(message))\n            uuid, message = message[:32], message[32:]\n            response = uuid + self.handle(message)\n            self.push.send(response)",
    "docstring": "Listen forever on the zmq.PULL socket."
  },
  {
    "code": "def _write_script(self, script_name, ref, qry, outfile):\n        f = pyfastaq.utils.open_file_write(script_name)\n        print(self._nucmer_command(ref, qry, 'p'), file=f)\n        print(self._delta_filter_command('p.delta', 'p.delta.filter'), file=f)\n        print(self._show_coords_command('p.delta.filter', outfile), file=f)\n        if self.show_snps:\n            print(self._show_snps_command('p.delta.filter', outfile + '.snps'), file=f)\n        pyfastaq.utils.close(f)",
    "docstring": "Write commands into a bash script"
  },
  {
    "code": "def ProgramScanner(**kw):\n    kw['path_function'] = SCons.Scanner.FindPathDirs('LIBPATH')\n    ps = SCons.Scanner.Base(scan, \"ProgramScanner\", **kw)\n    return ps",
    "docstring": "Return a prototype Scanner instance for scanning executable\n    files for static-lib dependencies"
  },
  {
    "code": "def to_pretty_json(self, ignore_none: bool=True, ignore_empty: bool=False) -> str:\n        return self.to_json(4, ignore_none, ignore_empty)",
    "docstring": "From instance to pretty json string\n\n        :param ignore_none: Properties which is None are excluded if True\n        :param ignore_empty: Properties which is empty are excluded if True\n        :return: Json string\n\n        Usage:\n\n            >>> from owlmixin.samples import Human\n            >>> human = Human.from_dict({\n            ...     \"id\": 1,\n            ...     \"name\": \"Tom\",\n            ...     \"favorites\": [\n            ...         {\"name\": \"Apple\", \"names_by_lang\": {\"en\": \"Apple\", \"de\": \"Apfel\"}},\n            ...         {\"name\": \"Orange\"}\n            ...     ]\n            ... })\n            >>> print(human.to_pretty_json())\n            {\n                \"favorites\": [\n                    {\n                        \"name\": \"Apple\",\n                        \"names_by_lang\": {\n                            \"de\": \"Apfel\",\n                            \"en\": \"Apple\"\n                        }\n                    },\n                    {\n                        \"name\": \"Orange\"\n                    }\n                ],\n                \"id\": 1,\n                \"name\": \"Tom\"\n            }"
  },
  {
    "code": "def get_unique_connection_configs(config=None):\n    if config is None:\n        from .settings import QUEUES\n        config = QUEUES\n    connection_configs = []\n    for key, value in config.items():\n        value = filter_connection_params(value)\n        if value not in connection_configs:\n            connection_configs.append(value)\n    return connection_configs",
    "docstring": "Returns a list of unique Redis connections from config"
  },
  {
    "code": "def DropTables(self):\n    rows, _ = self.ExecuteQuery(\n        \"SELECT table_name FROM information_schema.tables \"\n        \"WHERE table_schema='%s'\" % self.database_name)\n    for row in rows:\n      self.ExecuteQuery(\"DROP TABLE `%s`\" % row[\"table_name\"])",
    "docstring": "Drop all existing tables."
  },
  {
    "code": "async def addFeedData(self, name, items, seqn=None):\n        return await self.core.addFeedData(name, items, seqn)",
    "docstring": "Add feed data to the cortex."
  },
  {
    "code": "def plot_wigner_seitz(lattice, ax=None, **kwargs):\n    ax, fig, plt = get_ax3d_fig_plt(ax)\n    if \"color\" not in kwargs:\n        kwargs[\"color\"] = \"k\"\n    if \"linewidth\" not in kwargs:\n        kwargs[\"linewidth\"] = 1\n    bz = lattice.get_wigner_seitz_cell()\n    ax, fig, plt = get_ax3d_fig_plt(ax)\n    for iface in range(len(bz)):\n        for line in itertools.combinations(bz[iface], 2):\n            for jface in range(len(bz)):\n                if iface < jface and any(\n                        np.all(line[0] == x) for x in bz[jface]) \\\n                        and any(np.all(line[1] == x) for x in bz[jface]):\n                    ax.plot(*zip(line[0], line[1]), **kwargs)\n    return fig, ax",
    "docstring": "Adds the skeleton of the Wigner-Seitz cell of the lattice to a matplotlib Axes\n\n    Args:\n        lattice: Lattice object\n        ax: matplotlib :class:`Axes` or None if a new figure should be created.\n        kwargs: kwargs passed to the matplotlib function 'plot'. Color defaults to black\n            and linewidth to 1.\n\n    Returns:\n        matplotlib figure and matplotlib ax"
  },
  {
    "code": "def start_all_linking(self, mode, group):\n        msg = StartAllLinking(mode, group)\n        self.send_msg(msg)",
    "docstring": "Put the IM into All-Linking mode.\n\n        Puts the IM into All-Linking mode for 4 minutes.\n\n        Parameters:\n            mode: 0 | 1 | 3 | 255\n                  0 - PLM is responder\n                  1 - PLM is controller\n                  3 - Device that initiated All-Linking is Controller\n                255 = Delete All-Link\n            group: All-Link group number (0 - 255)"
  },
  {
    "code": "def check_output(*args, **kwargs):\n    if hasattr(subprocess, 'check_output'):\n        return subprocess.check_output(stderr=subprocess.STDOUT, universal_newlines=True,\n                                       *args, **kwargs)\n    else:\n        process = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,\n                                   universal_newlines=True, **kwargs)\n        output, _ = process.communicate()\n        retcode = process.poll()\n        if retcode:\n            error = subprocess.CalledProcessError(retcode, args[0])\n            error.output = output\n            raise error\n        return output",
    "docstring": "Compatibility wrapper for Python 2.6 missin g subprocess.check_output"
  },
  {
    "code": "def update_state(url, state_obj):\n        try:\n            req = urllib2.Request(url)\n            req.add_header('Content-Type', 'application/json')\n            response = urllib2.urlopen(req, json.dumps(state_obj))\n        except urllib2.URLError as ex:\n            raise ValueError(str(ex))\n        if response.code == 400:\n            raise ValueError(response.message)\n        elif response.code == 404:\n            raise ValueError('unknown model run')",
    "docstring": "Update the state of a given model run. The state object is a Json\n        representation of the state as created by the SCO-Server.\n\n        Throws a ValueError if the resource is unknown or the update state\n        request failed.\n\n        Parameters\n        ----------\n        url : string\n            Url to POST model run create model run request\n        state_obj : Json object\n            State object serialization as expected by the API."
  },
  {
    "code": "def perform(self):\n        last_value = None\n        last_step = None\n        while self.items.qsize():\n            item = self.items.get()\n            if item.flag == self.do:\n                last_value = item.item(*item.args, **item.kwargs)\n                last_step = item.message\n            elif item.flag == self.expect:\n                message = item.message\n                local = {'value': last_value, 'expectation': item.item}\n                expression = 'value {operator} expectation'.format(operator=item.operator)\n                result = eval(expression, local)\n                format_vars = {\n                    'actual': last_value,\n                    'expected': item.item,\n                    'step': last_step,\n                    'operator': item.operator\n                }\n                for var, val in format_vars.iteritems():\n                    message = message.replace('{' + str(var) + '}', str(val))\n                assert result, message\n        return last_value",
    "docstring": "Runs through all of the steps in the chain and runs each of them in sequence.\n\n        :return: The value from the lat \"do\" step performed"
  },
  {
    "code": "def create_page_from_template(template_file, output_path):\n    mkdir_p(os.path.dirname(output_path))\n    shutil.copy(os.path.join(livvkit.resource_dir, template_file), output_path)",
    "docstring": "Copy the correct html template file to the output directory"
  },
  {
    "code": "def _render_after(self, element):\n        if element.inline_content:\n            return \"</%s>%s\" % (element.tag, self.render_newlines())\n        elif element.self_close:\n            return self.render_newlines()\n        elif self.children:\n            return \"%s</%s>\\n\" % (self.spaces, element.tag)\n        else:\n            return \"</%s>\\n\" % (element.tag)",
    "docstring": "Render closing tag"
  },
  {
    "code": "def add_comes_from(self, basic_block):\n        if basic_block is None:\n            return\n        if self.lock:\n            return\n        if basic_block in self.comes_from:\n            return\n        self.lock = True\n        self.comes_from.add(basic_block)\n        basic_block.add_goes_to(self)\n        self.lock = False",
    "docstring": "This simulates a set. Adds the basic_block to the comes_from\n        list if not done already."
  },
  {
    "code": "def get_backup_blocks(cls, impl, working_dir):\n        ret = []\n        backup_dir = config.get_backups_directory(impl, working_dir)\n        if not os.path.exists(backup_dir):\n            return []\n        for name in os.listdir( backup_dir ):\n            if \".bak.\" not in name:\n                continue \n            suffix = name.split(\".bak.\")[-1]\n            try:\n                block_id = int(suffix)\n            except:\n                continue \n            backup_paths = cls.get_backup_paths(block_id, impl, working_dir)\n            for p in backup_paths:\n                if not os.path.exists(p):\n                    block_id = None\n                    continue\n            if block_id is not None:\n                ret.append(block_id)\n        return ret",
    "docstring": "Get the set of block IDs that were backed up"
  },
  {
    "code": "def _finalize(self):\n        \"Computes _fobj, the completed hash.\"\n        hobj = self._hobj\n        for hashname in self._algorithms[1:]:\n            fobj = hashlib.new(hashname)\n            fobj.update(hobj.digest())\n            hobj = fobj\n        self._fobj = hobj",
    "docstring": "Computes _fobj, the completed hash."
  },
  {
    "code": "def _get_shareinfo(self, data_el):\n        if (data_el is None) or not (isinstance(data_el, ET.Element)):\n            return None\n        return ShareInfo(self._xml_to_dict(data_el))",
    "docstring": "Simple helper which returns instance of ShareInfo class\n\n        :param data_el: 'data' element extracted from _make_ocs_request\n        :returns: instance of ShareInfo class"
  },
  {
    "code": "def extract(self, item):\n        doc = Document(deepcopy(item['spider_response'].body))\n        description = doc.summary()\n        article_candidate = ArticleCandidate()\n        article_candidate.extractor = self._name\n        article_candidate.title = doc.short_title()\n        article_candidate.description = description\n        article_candidate.text = self._text(item)\n        article_candidate.topimage = self._topimage(item)\n        article_candidate.author = self._author(item)\n        article_candidate.publish_date = self._publish_date(item)\n        article_candidate.language = self._language(item)\n        return article_candidate",
    "docstring": "Creates an readability document and returns an ArticleCandidate containing article title and text.\n\n        :param item: A NewscrawlerItem to parse.\n        :return: ArticleCandidate containing the recovered article data."
  },
  {
    "code": "def stats(syslog_ng_sbin_dir=None):\n    try:\n        ret = _run_command_in_extended_path(syslog_ng_sbin_dir,\n                                            'syslog-ng-ctl',\n                                            ('stats',))\n    except CommandExecutionError as err:\n        return _format_return_data(retcode=-1, stderr=six.text_type(err))\n    return _format_return_data(ret['retcode'],\n                               ret.get('stdout'),\n                               ret.get('stderr'))",
    "docstring": "Returns statistics from the running syslog-ng instance. If\n    syslog_ng_sbin_dir is specified, it is added to the PATH during the\n    execution of the command syslog-ng-ctl.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' syslog_ng.stats\n        salt '*' syslog_ng.stats /home/user/install/syslog-ng/sbin"
  },
  {
    "code": "def __add_dependency(self, word_instance, sent_id):\n        head = word_instance.__getattribute__(self.head_attr)\n        deprel = word_instance.__getattribute__(self.deprel_attr)\n        if head == '0':\n            source_id = sent_id\n        else:\n            source_id = '{0}_t{1}'.format(sent_id, head)\n            if source_id not in self.node:\n                self.add_node(source_id, layers={self.ns})\n        target_id = '{0}_t{1}'.format(sent_id, word_instance.word_id)\n        try:\n            self.add_edge(source_id, target_id,\n                          layers={self.ns, self.ns+':dependency'},\n                          relation_type=deprel,\n                          label=deprel,\n                          edge_type=EdgeTypes.dominance_relation)\n        except AssertionError:\n            print \"source: {0}, target: {1}\".format(source_id, target_id)",
    "docstring": "adds an ingoing dependency relation from the projected head of a token\n        to the token itself."
  },
  {
    "code": "def copy(self):\n        return Poly(self.A.copy(), self.dim, self.shape,\n            self.dtype)",
    "docstring": "Return a copy of the polynomial."
  },
  {
    "code": "def lower_camel(string, prefix='', suffix=''):\n    return require_valid(append_underscore_if_keyword(''.join(\n        word.lower() if index == 0 else upper_case_first_char(word)\n        for index, word in enumerate(en.words(' '.join([prefix, string, suffix]))))\n    ))",
    "docstring": "Generate a camel-case identifier.\n    Useful for unit test methods.\n\n    Takes a string, prefix, and optional suffix.\n\n    `prefix` can be set to `''`, though be careful - without a prefix, the\n    function will throw `InvalidIdentifier` when your string starts with a\n    number.\n\n    Example:\n        >>> lower_camel(\"User can login\", prefix='test')\n        'testUserCanLogin'"
  },
  {
    "code": "def item_related_name(self):\n        if not hasattr(self, '_item_related_name'):\n            many_to_many_rels = \\\n                get_section_many_to_many_relations(self.__class__)\n            if len(many_to_many_rels) != 1:\n                self._item_related_name = None\n            else:\n                self._item_related_name = many_to_many_rels[0].field.name\n        return self._item_related_name",
    "docstring": "The ManyToMany field on the item class pointing to this class.\n\n        If there is more than one field, this value will be None."
  },
  {
    "code": "def facter_info():\n    with suppress(FileNotFoundError):\n        proc = subprocess.Popen(['facter', '--yaml'],\n                                stdout=subprocess.PIPE,\n                                stderr=subprocess.PIPE)\n        stdout, stderr = proc.communicate()\n        if not proc.returncode:\n            data = serializer.load(stdout)\n            return {'facter': data}",
    "docstring": "Returns data from facter."
  },
  {
    "code": "def _regex_strings(self):\n        domain = 0\n        if domain not in self.domains:\n            self.register_domain(domain=domain)\n        return self.domains[domain]._regex_strings",
    "docstring": "A property to link into IntentEngine's _regex_strings.\n\n        Warning: this is only for backwards compatiblility and should not be used if you\n            intend on using domains.\n\n        Returns: the domains _regex_strings from its IntentEngine"
  },
  {
    "code": "def _linux_disks():\n    ret = {'disks': [], 'SSDs': []}\n    for entry in glob.glob('/sys/block/*/queue/rotational'):\n        try:\n            with salt.utils.files.fopen(entry) as entry_fp:\n                device = entry.split('/')[3]\n                flag = entry_fp.read(1)\n                if flag == '0':\n                    ret['SSDs'].append(device)\n                    log.trace('Device %s reports itself as an SSD', device)\n                elif flag == '1':\n                    ret['disks'].append(device)\n                    log.trace('Device %s reports itself as an HDD', device)\n                else:\n                    log.trace(\n                        'Unable to identify device %s as an SSD or HDD. It does '\n                        'not report 0 or 1', device\n                    )\n        except IOError:\n            pass\n    return ret",
    "docstring": "Return list of disk devices and work out if they are SSD or HDD."
  },
  {
    "code": "def describe_thing_type(thingTypeName,\n    region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        res = conn.describe_thing_type(thingTypeName=thingTypeName)\n        if res:\n            res.pop('ResponseMetadata', None)\n            thingTypeMetadata = res.get('thingTypeMetadata')\n            if thingTypeMetadata:\n                for dtype in ('creationDate', 'deprecationDate'):\n                    dval = thingTypeMetadata.get(dtype)\n                    if dval and isinstance(dval, datetime.date):\n                        thingTypeMetadata[dtype] = '{0}'.format(dval)\n            return {'thing_type': res}\n        else:\n            return {'thing_type': None}\n    except ClientError as e:\n        err = __utils__['boto3.get_error'](e)\n        if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':\n            return {'thing_type': None}\n        return {'error': err}",
    "docstring": "Given a thing type name describe its properties.\n\n    Returns a dictionary of interesting properties.\n\n    .. versionadded:: 2016.11.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_iot.describe_thing_type mythingtype"
  },
  {
    "code": "def set(self, time):\n        self._time = time\n        self._pb.sec = int(self._time)\n        self._pb.nsec = int((self._time - self._pb.sec) * 10 ** 9)",
    "docstring": "Sets time in seconds since Epoch\n\n        Args:\n            time (:obj:`float`): time in seconds since Epoch (see time.time())\n\n        Returns:\n            None"
  },
  {
    "code": "def get_correctness(self, question_id):\n        response = self.get_response(question_id)\n        if response.is_answered():\n            item = self._get_item(response.get_item_id())\n            return item.get_correctness_for_response(response)\n        raise errors.IllegalState()",
    "docstring": "get measure of correctness for the question"
  },
  {
    "code": "def set_windows_permissions(filename):\n    if os.name == 'nt':\n        try:\n            everyone, domain, type = win32security.LookupAccountName(\n            \"\", \"Everyone\")\n        except Exception:\n            everyone, domain, type = win32security.LookupAccountName (\"\", win32api.GetUserName())\n        sd = win32security.GetFileSecurity(\n            filename,\n            win32security.DACL_SECURITY_INFORMATION)\n        dacl = sd.GetSecurityDescriptorDacl()\n        dacl.AddAccessAllowedAce(\n            win32security.ACL_REVISION,\n            con.FILE_ALL_ACCESS,\n            everyone)\n        sd.SetSecurityDescriptorDacl(1, dacl, 0)\n        win32security.SetFileSecurity(\n            filename,\n            win32security.DACL_SECURITY_INFORMATION,\n            sd)",
    "docstring": "At least on windows 7 if a file is created on an Admin account,\n    Other users will not be given execute or full control.\n    However if a user creates the file himself it will work...\n    So just always change permissions after creating a file on windows\n\n    Change the permissions for Allusers of the application\n    The Everyone Group\n    Full access\n\n    http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html"
  },
  {
    "code": "def _should_proxy(self, attr):\n        if attr in type(self).__notproxied__:\n            return False\n        if _oga(self, \"__notproxied__\") is True:\n            return False\n        return True",
    "docstring": "Determines whether `attr` should be looked up on the proxied object, or\n        the proxy itself."
  },
  {
    "code": "def slugify(field_name, slug_field_name=None, mutable=False):\n    slug_field_name = slug_field_name or 'slug'\n    def _set_slug(target, value, old_value, _, mutable=False):\n        existing_slug = getattr(target, slug_field_name)\n        if existing_slug and not mutable:\n            return\n        if value and (not existing_slug or value != old_value):\n            setattr(target, slug_field_name, _slugify(value))\n    def wrapper(cls):\n        event.listen(getattr(cls, field_name), 'set',\n                     partial(_set_slug, mutable=mutable))\n        return cls\n    return wrapper",
    "docstring": "Class decorator to specify a field to slugify. Slugs are immutable by\n    default unless mutable=True is passed.\n\n    Usage::\n\n        @slugify('title')\n        def Post(Model):\n            title = Column(String(100))\n            slug = Column(String(100))\n\n        # pass a second argument to specify the slug attribute field:\n        @slugify('title', 'title_slug')\n        def Post(Model)\n            title = Column(String(100))\n            title_slug = Column(String(100))\n\n        # optionally set mutable to True for a slug that changes every time\n        # the slugified field changes:\n        @slugify('title', mutable=True)\n        def Post(Model):\n            title = Column(String(100))\n            slug = Column(String(100))"
  },
  {
    "code": "def raw_incron(user):\n    if __grains__['os_family'] == 'Solaris':\n        cmd = 'incrontab -l {0}'.format(user)\n    else:\n        cmd = 'incrontab -l -u {0}'.format(user)\n    return __salt__['cmd.run_stdout'](cmd, rstrip=False, runas=user, python_shell=False)",
    "docstring": "Return the contents of the user's incrontab\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' incron.raw_incron root"
  },
  {
    "code": "def execute_callback(self, *args, **kwargs):\n        response = self._sijax.execute_callback(*args, **kwargs)\n        return _make_response(response)",
    "docstring": "Executes a callback and returns the proper response.\n\n        Refer to :meth:`sijax.Sijax.execute_callback` for more details."
  },
  {
    "code": "def from_xml(cls, xml_bytes):\n        root = XML(xml_bytes)\n        return cls(root.findtext('Bucket'),\n                   root.findtext('Key'),\n                   root.findtext('UploadId'))",
    "docstring": "Create an instance of this from XML bytes.\n\n        @param xml_bytes: C{str} bytes of XML to parse\n        @return: an instance of L{MultipartInitiationResponse}"
  },
  {
    "code": "def mac_addresses(self):\n        mac_addresses = [self.findtext(\"general/mac_address\")]\n        if self.findtext(\"general/alt_mac_address\"):\n            mac_addresses.append(self.findtext(\"general/alt_mac_address\"))\n            return mac_addresses",
    "docstring": "Return a list of mac addresses for this device.\n\n        Computers don't tell you which network device is which."
  },
  {
    "code": "def add(self, key, metric, **dims):\n        return super(MetricsRegistry, self).add(\n            self.metadata.register(key, **dims), metric)",
    "docstring": "Adds custom metric instances to the registry with dimensions\n        which are not created with their constructors default arguments"
  },
  {
    "code": "def set_weights(params, new_params):\n        for param, new_param in zip(params, new_params):\n            param.data.copy_(new_param.data)",
    "docstring": "Copies parameters from new_params to params\n\n        :param params: dst parameters\n        :param new_params: src parameters"
  },
  {
    "code": "def run_toy_HMC(gpu_id=None):\n    X, Y, X_test, Y_test = load_toy()\n    minibatch_size = Y.shape[0]\n    noise_precision = 1 / 9.0\n    net = get_toy_sym(True, noise_precision)\n    data_shape = (minibatch_size,) + X.shape[1::]\n    data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id)),\n                   'teacher_output_label': nd.zeros((minibatch_size, 1), ctx=dev(gpu_id))}\n    initializer = mx.init.Uniform(0.07)\n    sample_pool = HMC(net, data_inputs=data_inputs, X=X, Y=Y, X_test=X_test, Y_test=Y_test,\n                      sample_num=300000, initializer=initializer, prior_precision=1.0,\n                      learning_rate=1E-3, L=10, dev=dev(gpu_id))",
    "docstring": "Run HMC on toy dataset"
  },
  {
    "code": "def mkdir(self, target_folder):\n        self.printv(\"Making directory: %s\" % target_folder)\n        self.k.key = re.sub(r\"^/|/$\", \"\", target_folder) + \"/\"\n        self.k.set_contents_from_string('')\n        self.k.close()",
    "docstring": "Create a folder on S3.\n\n        Examples\n        --------\n            >>> s3utils.mkdir(\"path/to/my_folder\")\n            Making directory: path/to/my_folder"
  },
  {
    "code": "def _hijack_target(self):\n        if self._target.is_class_or_module():\n            setattr(self._target.obj, self._method_name, self)\n        elif self._attr.kind == 'property':\n            proxy_property = ProxyProperty(\n                double_name(self._method_name),\n                self._original_method,\n            )\n            setattr(self._target.obj.__class__, self._method_name, proxy_property)\n            self._target.obj.__dict__[double_name(self._method_name)] = self\n        else:\n            self._target.obj.__dict__[self._method_name] = self\n        if self._method_name in ['__call__', '__enter__', '__exit__']:\n            self._target.hijack_attr(self._method_name)",
    "docstring": "Replaces the target method on the target object with the proxy method."
  },
  {
    "code": "def edges(self):\n        canonical_edges = set()\n        for v1, neighbours in self._vertices.items():\n            for v2 in neighbours:\n                edge = self.canonical_order((v1, v2))\n                canonical_edges.add(edge)\n        return canonical_edges",
    "docstring": "Edges of this graph, in canonical order."
  },
  {
    "code": "def find_data_files(self, package, src_dir):\n        patterns = self._get_platform_patterns(\n            self.package_data,\n            package,\n            src_dir,\n        )\n        globs_expanded = map(glob, patterns)\n        globs_matches = itertools.chain.from_iterable(globs_expanded)\n        glob_files = filter(os.path.isfile, globs_matches)\n        files = itertools.chain(\n            self.manifest_files.get(package, []),\n            glob_files,\n        )\n        return self.exclude_data_files(package, src_dir, files)",
    "docstring": "Return filenames for package's data files in 'src_dir"
  },
  {
    "code": "def points(self, include_hidden=False):\n        return sum(x.points for x in self.testable_results\n                   if include_hidden or not x.testable.is_hidden)",
    "docstring": "Return the number of points awarded to this submission."
  },
  {
    "code": "def union(*sets, **kwargs):\n    sets = _set_preprocess(sets, **kwargs)\n    return as_index( _set_concatenate(sets), axis=0, base=True).unique",
    "docstring": "all unique items which occur in any one of the sets\n\n    Parameters\n    ----------\n    sets : tuple of indexable objects\n\n    Returns\n    -------\n    union of all items in all sets"
  },
  {
    "code": "def Forget(self, obj):\n        obj = _get_idstr(obj)\n        try:\n            self.memo.remove(obj)\n        except ValueError:\n            pass",
    "docstring": "Forget we've seen this object."
  },
  {
    "code": "def set_sleep(minutes):\n    value = _validate_sleep(minutes)\n    cmd = 'systemsetup -setsleep {0}'.format(value)\n    salt.utils.mac_utils.execute_return_success(cmd)\n    state = []\n    for check in (get_computer_sleep, get_display_sleep, get_harddisk_sleep):\n        state.append(salt.utils.mac_utils.confirm_updated(\n            value,\n            check,\n        ))\n    return all(state)",
    "docstring": "Sets the amount of idle time until the machine sleeps. Sets the same value\n    for Computer, Display, and Hard Disk. Pass \"Never\" or \"Off\" for computers\n    that should never sleep.\n\n    :param minutes: Can be an integer between 1 and 180 or \"Never\" or \"Off\"\n    :ptype: int, str\n\n    :return: True if successful, False if not\n    :rtype: bool\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' power.set_sleep 120\n        salt '*' power.set_sleep never"
  },
  {
    "code": "def get_host(self):\n        host = self.get_as_nullable_string(\"host\")\n        host = host if host != None else self.get_as_nullable_string(\"ip\")\n        return host",
    "docstring": "Gets the host name or IP address.\n\n        :return: the host name or IP address."
  },
  {
    "code": "def login(self) -> bool:\n        user_check = isinstance(self.username, str) and len(self.username) > 0\n        pass_check = isinstance(self.password, str) and len(self.password) > 0\n        if user_check and pass_check:\n            response, _ = helpers.call_api(\n                '/cloud/v1/user/login',\n                'post',\n                json=helpers.req_body(self, 'login')\n            )\n            if response and helpers.check_response(response, 'login'):\n                self.token = response['result']['token']\n                self.account_id = response['result']['accountID']\n                self.enabled = True\n                return True\n            else:\n                logger.error('Error logging in with username and password')\n                return False\n        else:\n            if user_check is False:\n                logger.error('Username invalid')\n            if pass_check is False:\n                logger.error('Password invalid')\n        return False",
    "docstring": "Return True if log in request succeeds"
  },
  {
    "code": "def _call(self, x, out=None):\n        def per_axis_interp(arg, out=None):\n            if is_valid_input_meshgrid(arg, self.grid.ndim):\n                input_type = 'meshgrid'\n            else:\n                input_type = 'array'\n            interpolator = _PerAxisInterpolator(\n                self.grid.coord_vectors, x,\n                schemes=self.schemes, nn_variants=self.nn_variants,\n                input_type=input_type)\n            return interpolator(arg, out=out)\n        return self.range.element(per_axis_interp, vectorized=True)",
    "docstring": "Create an interpolator from grid values ``x``.\n\n        Parameters\n        ----------\n        x : `Tensor`\n            The array of values to be interpolated\n        out : `FunctionSpaceElement`, optional\n            Element in which to store the interpolator\n\n        Returns\n        -------\n        out : `FunctionSpaceElement`\n            Per-axis interpolator for the grid of this operator. If\n            ``out`` was provided, the returned object is a reference\n            to it."
  },
  {
    "code": "def GetDecrypter(cls, encryption_method, **kwargs):\n    encryption_method = encryption_method.lower()\n    decrypter = cls._decrypters.get(encryption_method, None)\n    if not decrypter:\n      return None\n    return decrypter(**kwargs)",
    "docstring": "Retrieves the decrypter object for a specific encryption method.\n\n    Args:\n      encryption_method (str): encryption method identifier.\n      kwargs (dict): keyword arguments depending on the decrypter.\n\n    Returns:\n      Decrypter: decrypter or None if the encryption method does not exists.\n\n    Raises:\n      CredentialError: if the necessary credentials are missing."
  },
  {
    "code": "def remove_each(text, items, count=None, strip=False):\n    for item in items:\n        text = remove(text, item, count=count, strip=strip)\n    return text",
    "docstring": "Like ``remove``, where each occurrence in ``items`` is ``what`` to remove."
  },
  {
    "code": "def delete_library(self, library):\n        lib = ArcticLibraryBinding(self, library)\n        colname = lib.get_top_level_collection().name\n        if not [c for c in lib._db.list_collection_names(False) if re.match(r\"^{}([\\.].*)?$\".format(colname), c)]:\n            logger.info('Nothing to delete. Arctic library %s does not exist.' % colname)\n        logger.info('Dropping collection: %s' % colname)\n        lib._db.drop_collection(colname)\n        for coll in lib._db.list_collection_names():\n            if coll.startswith(colname + '.'):\n                logger.info('Dropping collection: %s' % coll)\n                lib._db.drop_collection(coll)\n        if library in self._library_cache:\n            del self._library_cache[library]\n            del self._library_cache[lib.get_name()]\n        self._cache.delete_item_from_key('list_libraries', self._sanitize_lib_name(library))",
    "docstring": "Delete an Arctic Library, and all associated collections in the MongoDB.\n\n        Parameters\n        ----------\n        library : `str`\n            The name of the library. e.g. 'library' or 'user.library'"
  },
  {
    "code": "def percent_chance(self, pct):\n        if pct <= 0:\n            return False\n        if pct >= 100:\n            return True\n        return pct / 100 < self.random()",
    "docstring": "Given a ``pct``% chance of something happening right now, decide at\n        random whether it actually happens, and return ``True`` or\n        ``False`` as appropriate.\n\n        Values not between 0 and 100 are treated as though they\n        were 0 or 100, whichever is nearer."
  },
  {
    "code": "def fix_multiclass_predict_proba(y_proba,\n                                 seen_classes,\n                                 complete_classes\n                                 ):\n    assert set(complete_classes) >= set(seen_classes)\n    y_proba_fixed = np.zeros(\n        shape=(y_proba.shape[0], len(complete_classes)),\n        dtype=y_proba.dtype,\n    )\n    class_mapping = np.searchsorted(complete_classes, seen_classes)\n    y_proba_fixed[:, class_mapping] = y_proba\n    return y_proba_fixed",
    "docstring": "Add missing columns to predict_proba result.\n\n    When a multiclass classifier is fit on a dataset which only contains\n    a subset of possible classes its predict_proba result only has columns\n    corresponding to seen classes. This function adds missing columns."
  },
  {
    "code": "def admin_tools_render_menu(context, menu=None):\n    if menu is None:\n        menu = get_admin_menu(context)\n    menu.init_with_context(context)\n    has_bookmark_item = False\n    bookmark = None\n    if len([c for c in menu.children if isinstance(c, items.Bookmarks)]) > 0:\n        has_bookmark_item = True\n        url = context['request'].get_full_path()\n        try:\n            bookmark = Bookmark.objects.filter(\n                user=context['request'].user, url=url\n            )[0]\n        except:\n            pass\n    context.update({\n        'template': menu.template,\n        'menu': menu,\n        'has_bookmark_item': has_bookmark_item,\n        'bookmark': bookmark,\n        'admin_url': reverse('%s:index' % get_admin_site_name(context)),\n    })\n    return context",
    "docstring": "Template tag that renders the menu, it takes an optional ``Menu`` instance\n    as unique argument, if not given, the menu will be retrieved with the\n    ``get_admin_menu`` function."
  },
  {
    "code": "def __attr_index(self, attribute: str) -> Optional[int]:\n        attr_index = None\n        for i, (key_node, _) in enumerate(self.yaml_node.value):\n            if key_node.value == attribute:\n                attr_index = i\n                break\n        return attr_index",
    "docstring": "Finds an attribute's index in the yaml_node.value list."
  },
  {
    "code": "def get_proc_return_status(self):\n        if self._session is None:\n            return None\n        if not self._session.has_status:\n            self._session.find_return_status()\n        return self._session.ret_status if self._session.has_status else None",
    "docstring": "Last stored proc result"
  },
  {
    "code": "def upload_log_data(url, stream_or_file, config):\n    try:\n        logger.debug(\"Uploading log data to IOpipe\")\n        if isinstance(stream_or_file, StringIO):\n            stream_or_file.seek(0)\n            response = requests.put(\n                url, data=stream_or_file, timeout=config[\"network_timeout\"]\n            )\n        else:\n            with open(stream_or_file, \"rb\") as data:\n                response = requests.put(\n                    url, data=data, timeout=config[\"network_timeout\"]\n                )\n        response.raise_for_status()\n    except Exception as e:\n        logger.debug(\"Error while uploading log data: %s\", e)\n        logger.exception(e)\n        if hasattr(e, \"response\") and hasattr(e.response, \"content\"):\n            logger.debug(e.response.content)\n    else:\n        logger.debug(\"Log data uploaded successfully\")\n    finally:\n        if isinstance(stream_or_file, str) and os.path.exists(stream_or_file):\n            os.remove(stream_or_file)",
    "docstring": "Uploads log data to IOpipe.\n\n    :param url: The signed URL\n    :param stream_or_file: The log data stream or file\n    :param config: The IOpipe config"
  },
  {
    "code": "def simplify(self):\n        node = self.node.simplify()\n        if node is self.node:\n            return self\n        else:\n            return _expr(node)",
    "docstring": "Return a simplified expression."
  },
  {
    "code": "def generate_nonce_timestamp():\n    global count\n    rng = botan.rng().get(30)\n    uuid4 = uuid.uuid4().bytes\n    tmpnonce = (bytes(str(count).encode('utf-8'))) + uuid4 + rng\n    nonce = tmpnonce[:41]\n    count += 1\n    return nonce",
    "docstring": "Generate unique nonce with counter, uuid and rng."
  },
  {
    "code": "def _new_theme_part(cls, package):\n        partname = package.next_partname('/ppt/theme/theme%d.xml')\n        content_type = CT.OFC_THEME\n        theme = CT_OfficeStyleSheet.new_default()\n        return XmlPart(partname, content_type, theme, package)",
    "docstring": "Create and return a default theme part suitable for use with a notes\n        master."
  },
  {
    "code": "def instance():\n    start_time = time.time()\n    print(_green(\"Started...\"))\n    env.host_string = _create_ec2_instance()\n    print(_green(\"Waiting 30 seconds for server to boot...\"))\n    time.sleep(30)\n    for item in tasks.configure_instance:\n        try:\n            print(_yellow(item['message']))\n        except KeyError:\n            pass\n        globals()[\"_\" + item['action']](item['params'])\n    end_time = time.time()\n    print(_green(\"Runtime: %f minutes\" % ((end_time - start_time) / 60)))\n    print(_green(\"\\nPLEASE ADD ADDRESS THIS TO YOUR \")),\n    print(_yellow(\"project_conf.py\")),\n    print(_green(\" FILE UNDER \")),\n    print(_yellow(\"fabconf['EC2_INSTANCES'] : \")),\n    print(_green(env.host_string))",
    "docstring": "Creates an EC2 instance from an Ubuntu AMI and configures it as a Django server\n    with nginx + gunicorn"
  },
  {
    "code": "def treeWidgetChanged(self):\n        ParameterItem.treeWidgetChanged(self)\n        if self.widget is not None:\n            tree = self.treeWidget()\n            if tree is None:\n                return\n            tree.setItemWidget(self, 1, self.layoutWidget)\n            self.displayLabel.hide()\n            self.selected(False)",
    "docstring": "Called when this item is added or removed from a tree."
  },
  {
    "code": "def remove_output_data_port(self, data_port_id, force=False, destroy=True):\n        if data_port_id in self._output_data_ports:\n            if destroy:\n                self.remove_data_flows_with_data_port_id(data_port_id)\n            self._output_data_ports[data_port_id].parent = None\n            return self._output_data_ports.pop(data_port_id)\n        else:\n            raise AttributeError(\"output data port with name %s does not exit\", data_port_id)",
    "docstring": "Remove an output data port from the state\n\n        :param int data_port_id: the id of the output data port to remove\n        :raises exceptions.AttributeError: if the specified input data port does not exist"
  },
  {
    "code": "def forward(self, X):\n        return self.W(X).sum(dim=1) + self.b",
    "docstring": "Execute sparse linear layer\n\n        Args:\n            X: an [n, h] torch.LongTensor containing up to h indices of features\n                whose weights should be looked up and used in a sparse linear\n                multiplication."
  },
  {
    "code": "def create_consumer(self):\n        with self.connection_pool.acquire(block=True) as conn:\n            yield self.consumer(conn)",
    "docstring": "Context manager that yields an instance of ``Consumer``."
  },
  {
    "code": "async def verify_chain_of_trust(chain):\n    log_path = os.path.join(chain.context.config[\"task_log_dir\"], \"chain_of_trust.log\")\n    scriptworker_log = logging.getLogger('scriptworker')\n    with contextual_log_handler(\n        chain.context, path=log_path, log_obj=scriptworker_log,\n        formatter=AuditLogFormatter(\n            fmt=chain.context.config['log_fmt'],\n            datefmt=chain.context.config['log_datefmt'],\n        )\n    ):\n        try:\n            await build_task_dependencies(chain, chain.task, chain.name, chain.task_id)\n            await download_cot(chain)\n            verify_cot_signatures(chain)\n            await download_cot_artifacts(chain)\n            task_count = await verify_task_types(chain)\n            check_num_tasks(chain, task_count)\n            await verify_worker_impls(chain)\n            await trace_back_to_tree(chain)\n        except (BaseDownloadError, KeyError, AttributeError) as exc:\n            log.critical(\"Chain of Trust verification error!\", exc_info=True)\n            if isinstance(exc, CoTError):\n                raise\n            else:\n                raise CoTError(str(exc))\n        log.info(\"Good.\")",
    "docstring": "Build and verify the chain of trust.\n\n    Args:\n        chain (ChainOfTrust): the chain we're operating on\n\n    Raises:\n        CoTError: on failure"
  },
  {
    "code": "def add_route(self, handler, uri, methods=frozenset({'GET'}), host=None,\n                  strict_slashes=False):\n        stream = False\n        if hasattr(handler, 'view_class'):\n            http_methods = (\n                'GET', 'POST', 'PUT', 'HEAD', 'OPTIONS', 'PATCH', 'DELETE')\n            methods = set()\n            for method in http_methods:\n                _handler = getattr(handler.view_class, method.lower(), None)\n                if _handler:\n                    methods.add(method)\n                    if hasattr(_handler, 'is_stream'):\n                        stream = True\n        if isinstance(handler, self.composition_view_class):\n            methods = handler.handlers.keys()\n            for _handler in handler.handlers.values():\n                if hasattr(_handler, 'is_stream'):\n                    stream = True\n                    break\n        self.route(uri=uri, methods=methods, host=host,\n                   strict_slashes=strict_slashes, stream=stream)(handler)\n        return handler",
    "docstring": "A helper method to register class instance or\n        functions as a handler to the application url\n        routes.\n\n        :param handler: function or class instance\n        :param uri: path of the URL\n        :param methods: list or tuple of methods allowed, these are overridden\n                        if using a HTTPMethodView\n        :param host:\n        :return: function or class instance"
  },
  {
    "code": "def confirm_user(query):\n    user = _query_to_user(query)\n    if click.confirm(f'Are you sure you want to confirm {user!r}?'):\n        if security_service.confirm_user(user):\n            click.echo(f'Successfully confirmed {user!r} at '\n                       f'{user.confirmed_at.strftime(\"%Y-%m-%d %H:%M:%S%z\")}')\n            user_manager.save(user, commit=True)\n        else:\n            click.echo(f'{user!r} has already been confirmed.')\n    else:\n        click.echo('Cancelled.')",
    "docstring": "Confirm a user account."
  },
  {
    "code": "def parse_cl_args(arg_vector):\n  parser = argparse.ArgumentParser(description='Compiles markdown files into html files for remark.js')\n  parser.add_argument('source', metavar='source', help='the source to compile. If a directory is provided, all markdown files in that directory are compiled. Output is saved in the current working directory under a md2remark_build subdirectory.')\n  return parser.parse_args(arg_vector)",
    "docstring": "Parses the command line arguments"
  },
  {
    "code": "def values_for_column(self,\n                          column_name,\n                          limit=10000):\n        logging.info(\n            'Getting values for columns [{}] limited to [{}]'\n            .format(column_name, limit))\n        if self.fetch_values_from:\n            from_dttm = utils.parse_human_datetime(self.fetch_values_from)\n        else:\n            from_dttm = datetime(1970, 1, 1)\n        qry = dict(\n            datasource=self.datasource_name,\n            granularity='all',\n            intervals=from_dttm.isoformat() + '/' + datetime.now().isoformat(),\n            aggregations=dict(count=count('count')),\n            dimension=column_name,\n            metric='count',\n            threshold=limit,\n        )\n        client = self.cluster.get_pydruid_client()\n        client.topn(**qry)\n        df = client.export_pandas()\n        return [row[column_name] for row in df.to_records(index=False)]",
    "docstring": "Retrieve some values for the given column"
  },
  {
    "code": "async def write_register(self, address, value, skip_encode=False):\n        await self._request('write_registers', address, value, skip_encode=skip_encode)",
    "docstring": "Write a modbus register."
  },
  {
    "code": "def ParsePath(path,\n              opts = None):\n  precondition.AssertType(path, Text)\n  rcount = 0\n  normalized_path = path.replace(os.path.sep, \"/\")\n  for item in normalized_path.split(\"/\"):\n    component = ParsePathItem(item, opts=opts)\n    if isinstance(component, RecursiveComponent):\n      rcount += 1\n      if rcount > 1:\n        raise ValueError(\"path cannot have more than one recursive component\")\n    yield component",
    "docstring": "Parses given path into a stream of `PathComponent` instances.\n\n  Args:\n    path: A path to be parsed.\n    opts: An `PathOpts` object.\n\n  Yields:\n    `PathComponent` instances corresponding to the components of the given path.\n\n  Raises:\n    ValueError: If path contains more than one recursive component."
  },
  {
    "code": "def VcardFieldsEqual(field1, field2):\n    field1_vals = set([ str(f.value) for f in field1 ])\n    field2_vals = set([ str(f.value) for f in field2 ])\n    if field1_vals == field2_vals:\n        return True\n    else:\n        return False",
    "docstring": "Handle comparing vCard fields where inputs are lists of components.\n\n    Handle parameters?  Are any used aside from 'TYPE'?\n    Note: force cast to string to compare sub-objects like Name and Address"
  },
  {
    "code": "async def unformat(self):\n        self._data = await self._handler.unformat(\n            system_id=self.node.system_id, id=self.id)",
    "docstring": "Unformat this block device."
  },
  {
    "code": "def register_prefix(self, path):\n        if path not in self._prefixes:\n            LOG.debug('%r: registering prefix %r', self, path)\n            self._prefixes.add(path)",
    "docstring": "Authorize a path and any subpaths for access by children. Repeat calls\n        with the same path has no effect.\n\n        :param str path:\n            File path."
  },
  {
    "code": "def editor_example():\n    sensors = [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR]\n    agent = AgentDefinition(\"uav0\", agents.UavAgent, sensors)\n    env = HolodeckEnvironment(agent, start_world=False)\n    env.agents[\"uav0\"].set_control_scheme(1)\n    command = [0, 0, 10, 50]\n    for i in range(10):\n        env.reset()\n        for _ in range(1000):\n            state, reward, terminal, _ = env.step(command)",
    "docstring": "This editor example shows how to interact with holodeck worlds while they are being built\n    in the Unreal Engine. Most people that use holodeck will not need this."
  },
  {
    "code": "def disconnect(self):\n    if self.sock is not None:\n      try:\n        self.sock.close()\n      except socket.error:\n        pass\n      finally:\n        self.sock = None",
    "docstring": "Disconnect from the Graphite server if connected."
  },
  {
    "code": "def set_up_log(filename, verbose=True):\n    filename += '.log'\n    if verbose:\n        print('Preparing log file:', filename)\n    logging.captureWarnings(True)\n    formatter = logging.Formatter(fmt='%(asctime)s %(message)s',\n                                  datefmt='%d/%m/%Y %H:%M:%S')\n    fh = logging.FileHandler(filename=filename, mode='w')\n    fh.setLevel(logging.DEBUG)\n    fh.setFormatter(formatter)\n    log = logging.getLogger(filename)\n    log.setLevel(logging.DEBUG)\n    log.addHandler(fh)\n    log.info('The log file has been set-up.')\n    return log",
    "docstring": "Set up log\n\n    This method sets up a basic log.\n\n    Parameters\n    ----------\n    filename : str\n        Log file name\n\n    Returns\n    -------\n    logging.Logger instance"
  },
  {
    "code": "def generate_search_subparser(subparsers):\n    parser = subparsers.add_parser(\n        'search', description=constants.SEARCH_DESCRIPTION,\n        epilog=constants.SEARCH_EPILOG, formatter_class=ParagraphFormatter,\n        help=constants.SEARCH_HELP)\n    parser.set_defaults(func=search_texts)\n    utils.add_common_arguments(parser)\n    utils.add_db_arguments(parser)\n    utils.add_corpus_arguments(parser)\n    utils.add_query_arguments(parser)\n    parser.add_argument('ngrams', help=constants.SEARCH_NGRAMS_HELP,\n                        nargs='*', metavar='NGRAMS')",
    "docstring": "Adds a sub-command parser to `subparsers` to generate search\n    results for a set of n-grams."
  },
  {
    "code": "def can_create_assets(self):\n        url_path = construct_url('authorization',\n                                 bank_id=self._catalog_idstr)\n        return self._get_request(url_path)['assetHints']['canCreate']",
    "docstring": "Tests if this user can create ``Assets``.\n\n        A return of true does not guarantee successful authorization. A\n        return of false indicates that it is known creating an ``Asset``\n        will result in a ``PermissionDenied``. This is intended as a\n        hint to an application that may opt not to offer create\n        operations to an unauthorized user.\n\n        :return: ``false`` if ``Asset`` creation is not authorized, ``true`` otherwise\n        :rtype: ``boolean``\n\n\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def Parse(self, stat, file_object, knowledge_base):\n    _, _ = stat, knowledge_base\n    field_parser = NtpdFieldParser()\n    for line in field_parser.ParseEntries(\n        utils.ReadFileBytesAsUnicode(file_object)):\n      field_parser.ParseLine(line)\n    yield rdf_config_file.NtpConfig(\n        config=field_parser.config,\n        server=field_parser.keyed.get(\"server\"),\n        restrict=field_parser.keyed.get(\"restrict\"),\n        fudge=field_parser.keyed.get(\"fudge\"),\n        trap=field_parser.keyed.get(\"trap\"),\n        peer=field_parser.keyed.get(\"peer\"),\n        broadcast=field_parser.keyed.get(\"broadcast\"),\n        manycastclient=field_parser.keyed.get(\"manycastclient\"))",
    "docstring": "Parse a ntp config into rdf."
  },
  {
    "code": "def expected_part_size(self, part_number):\n        last_part = self.multipart.last_part_number\n        if part_number == last_part:\n            return self.multipart.last_part_size\n        elif part_number >= 0 and part_number < last_part:\n            return self.multipart.chunk_size\n        else:\n            raise MultipartInvalidPartNumber()",
    "docstring": "Get expected part size for a particular part number."
  },
  {
    "code": "def _parse_odata_timestamp(in_date):\n    timestamp = int(in_date.replace('/Date(', '').replace(')/', ''))\n    seconds = timestamp // 1000\n    ms = timestamp % 1000\n    return datetime.utcfromtimestamp(seconds) + timedelta(milliseconds=ms)",
    "docstring": "Convert the timestamp received from OData JSON API to a datetime object."
  },
  {
    "code": "def _run_and_measure(self, quil_program, qubits, trials, random_seed) -> np.ndarray:\n        payload = run_and_measure_payload(quil_program, qubits, trials, random_seed)\n        response = post_json(self.session, self.sync_endpoint + \"/qvm\", payload)\n        return np.asarray(response.json())",
    "docstring": "Run a Forest ``run_and_measure`` job.\n\n        Users should use :py:func:`WavefunctionSimulator.run_and_measure` instead of calling\n        this directly."
  },
  {
    "code": "def mount(self, prefix, adapter):\n        self.adapters[prefix] = adapter\n        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n        for key in keys_to_move:\n            self.adapters[key] = self.adapters.pop(key)",
    "docstring": "Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length."
  },
  {
    "code": "def hincrbyfloat(self, hashkey, attribute, increment=1.0):\n        return self._hincrby(hashkey, attribute, 'HINCRBYFLOAT', float, increment)",
    "docstring": "Emulate hincrbyfloat."
  },
  {
    "code": "def add_route(self, handler, uri, methods=frozenset({'GET'}), host=None,\n                  strict_slashes=False):\n        if hasattr(handler, 'view_class'):\n            http_methods = (\n                'GET', 'POST', 'PUT', 'HEAD', 'OPTIONS', 'PATCH', 'DELETE')\n            methods = set()\n            for method in http_methods:\n                if getattr(handler.view_class, method.lower(), None):\n                    methods.add(method)\n        if isinstance(handler, self._composition_view_class):\n            methods = handler.handlers.keys()\n        self.route(uri=uri, methods=methods, host=host,\n                   strict_slashes=strict_slashes)(handler)\n        return handler",
    "docstring": "Create a blueprint route from a function.\n\n        :param handler: function for handling uri requests. Accepts function,\n                        or class instance with a view_class method.\n        :param uri: endpoint at which the route will be accessible.\n        :param methods: list of acceptable HTTP methods.\n        :return: function or class instance"
  },
  {
    "code": "def check_perms(perms, user, slug, raise_exception=False):\n    if isinstance(perms, string_types):\n        perms = {perms}\n    else:\n        perms = set(perms)\n    allowed_users = ACLRule.get_users_for(perms, slug)\n    if allowed_users:\n        return user in allowed_users\n    if perms.issubset(set(WALIKI_ANONYMOUS_USER_PERMISSIONS)):\n        return True\n    if is_authenticated(user) and perms.issubset(set(WALIKI_LOGGED_USER_PERMISSIONS)):\n        return True\n    if user.has_perms(['waliki.%s' % p for p in perms]):\n        return True\n    if raise_exception:\n        raise PermissionDenied\n    return False",
    "docstring": "a helper user to check if a user has the permissions\n    for a given slug"
  },
  {
    "code": "def set_permutation_symmetry(force_constants):\n    fc_copy = force_constants.copy()\n    for i in range(force_constants.shape[0]):\n        for j in range(force_constants.shape[1]):\n            force_constants[i, j] = (force_constants[i, j] +\n                                     fc_copy[j, i].T) / 2",
    "docstring": "Enforce permutation symmetry to force cosntants by\n\n    Phi_ij_ab = Phi_ji_ba\n\n    i, j: atom index\n    a, b: Cartesian axis index\n\n    This is not necessary for harmonic phonon calculation because this\n    condition is imposed when making dynamical matrix Hermite in\n    dynamical_matrix.py."
  },
  {
    "code": "def export_gpg_key(key):\n    cmd = flatten([gnupg_bin(), gnupg_verbose(), gnupg_home(),\n                   \"--export\", key])\n    handle, gpg_stderr = stderr_handle()\n    try:\n        gpg_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n                                    stderr=gpg_stderr)\n        output, _err = gpg_proc.communicate()\n        if handle:\n            handle.close()\n        return portable_b64encode(output)\n    except subprocess.CalledProcessError as exception:\n        LOGGER.debug(\"GPG Command %s\", ' '.join(exception.cmd))\n        LOGGER.debug(\"GPG Output %s\", exception.output)\n        raise CryptoritoError('GPG encryption error')",
    "docstring": "Exports a GPG key and returns it"
  },
  {
    "code": "def _check_dedup(data):\n    if dd.get_analysis(data).lower() in [\"rna-seq\", \"smallrna-seq\"] or not dd.get_aligner(data):\n        dup_param = utils.get_in(data, (\"config\", \"algorithm\", \"mark_duplicates\"), False)\n    else:\n        dup_param = utils.get_in(data, (\"config\", \"algorithm\", \"mark_duplicates\"), True)\n    if dup_param and isinstance(dup_param, six.string_types):\n        logger.info(\"Warning: bcbio no longer support explicit setting of mark_duplicate algorithm. \"\n                    \"Using best-practice choice based on input data.\")\n        dup_param = True\n    return dup_param",
    "docstring": "Check configuration for de-duplication.\n\n    Defaults to no de-duplication for RNA-seq and small RNA, the\n    back compatible default. Allow overwriting with explicit\n    `mark_duplicates: true` setting.\n    Also defaults to false for no alignment inputs."
  },
  {
    "code": "def taylor(fun, z0=0, n=1, r=0.0061, num_extrap=3, step_ratio=1.6, **kwds):\n    return Taylor(fun, n=n, r=r, num_extrap=num_extrap, step_ratio=step_ratio, **kwds)(z0)",
    "docstring": "Return Taylor coefficients of complex analytic function using FFT\n\n    Parameters\n    ----------\n    fun : callable\n        function to differentiate\n    z0 : real or complex scalar at which to evaluate the derivatives\n    n : scalar integer, default 1\n        Number of taylor coefficents to compute. Maximum number is 100.\n    r : real scalar, default 0.0061\n        Initial radius at which to evaluate. For well-behaved functions,\n        the computation should be insensitive to the initial radius to within\n        about four orders of magnitude.\n    num_extrap : scalar integer, default 3\n        number of extrapolation steps used in the calculation\n    step_ratio : real scalar, default 1.6\n        Initial grow/shrinking factor for finding the best radius.\n    max_iter : scalar integer, default 30\n        Maximum number of iterations\n    min_iter : scalar integer, default max_iter // 2\n        Minimum number of iterations before the solution may be deemed\n        degenerate.  A larger number allows the algorithm to correct a bad\n        initial radius.\n    full_output : bool, optional\n        If `full_output` is False, only the coefficents is returned (default).\n        If `full_output` is True, then (coefs, status) is returned\n\n    Returns\n    -------\n    coefs : ndarray\n       array of taylor coefficents\n    status: Optional object into which output information is written:\n        degenerate: True if the algorithm was unable to bound the error\n        iterations: Number of iterations executed\n        function_count: Number of function calls\n        final_radius: Ending radius of the algorithm\n        failed: True if the maximum number of iterations was reached\n        error_estimate: approximate bounds of the rounding error.\n\n    Notes\n    -----\n    This module uses the method of Fornberg to compute the Taylor series\n    coefficents of a complex analytic function along with error bounds. The\n    method uses a Fast Fourier Transform to invert function evaluations around\n    a circle into Taylor series coefficients and uses Richardson Extrapolation\n    to improve and bound the estimate. Unlike real-valued finite differences,\n    the method searches for a desirable radius and so is reasonably\n    insensitive to the initial radius-to within a number of orders of\n    magnitude at least. For most cases, the default configuration is likely to\n    succeed.\n\n    Restrictions\n\n    The method uses the coefficients themselves to control the truncation\n    error, so the error will not be properly bounded for functions like\n    low-order polynomials whose Taylor series coefficients are nearly zero.\n    If the error cannot be bounded, degenerate flag will be set to true, and\n    an answer will still be computed and returned but should be used with\n    caution.\n\n    Examples\n    --------\n\n    Compute the first 6 taylor coefficients 1 / (1 - z) expanded round  z0 = 0:\n    >>> import numdifftools.fornberg as ndf\n    >>> import numpy as np\n    >>> c, info = ndf.taylor(lambda x: 1./(1-x), z0=0, n=6, full_output=True)\n    >>> np.allclose(c, np.ones(8))\n    True\n    >>> np.all(info.error_estimate < 1e-9)\n    True\n    >>> (info.function_count, info.iterations, info.failed) == (144, 18, False)\n    True\n\n\n    References\n    ----------\n    [1] Fornberg, B. (1981).\n        Numerical Differentiation of Analytic Functions.\n        ACM Transactions on Mathematical Software (TOMS),\n        7(4), 512-526. http://doi.org/10.1145/355972.355979"
  },
  {
    "code": "def cli(env, identifier):\n    mgr = SoftLayer.ObjectStorageManager(env.client)\n    credential_limit = mgr.limit_credential(identifier)\n    table = formatting.Table(['limit'])\n    table.add_row([\n        credential_limit,\n    ])\n    env.fout(table)",
    "docstring": "Credential limits for this IBM Cloud Object Storage account."
  },
  {
    "code": "def _chunks(iterable, n):\n    iterable = iter(iterable)\n    while True:\n        yield chain([next(iterable)], islice(iterable, n-1))",
    "docstring": "Splits an iterable into chunks of size n."
  },
  {
    "code": "def transform(self, trans):\n        _data = deepcopy(self._data)\n        _data.data_block[:, 0:3] = trans(_data.data_block[:, 0:3])\n        return FstNeuron(_data, self.name)",
    "docstring": "Return a copy of this neuron with a 3D transformation applied"
  },
  {
    "code": "def get_bar_data_from_undetermined(self, flowcells):\n        bar_data = defaultdict(dict)\n        for lane_id, lane in flowcells.items():\n            try:\n                for barcode, count in islice(lane['unknown_barcodes'].items(), 20):\n                    bar_data[barcode][lane_id] = count\n            except AttributeError:\n                pass\n        bar_data = OrderedDict(sorted(\n            bar_data.items(),\n            key=lambda x: sum(x[1].values()),\n            reverse=True\n        ))\n        return OrderedDict(\n            (key, value) for key, value in islice(bar_data.items(), 20)\n        )",
    "docstring": "Get data to plot for undetermined barcodes."
  },
  {
    "code": "def _get_input_args(bam_file, data, out_base, background):\n    if dd.get_genome_build(data) in [\"hg19\"]:\n        return [\"--PileupFile\", _create_pileup(bam_file, data, out_base, background)]\n    else:\n        return [\"--BamFile\", bam_file]",
    "docstring": "Retrieve input args, depending on genome build.\n\n    VerifyBamID2 only handles GRCh37 (1, 2, 3) not hg19, so need to generate\n    a pileup for hg19 and fix chromosome naming."
  },
  {
    "code": "def update_ostree_summary(self, release):\n        self.log.info('Updating the ostree summary for %s', release['name'])\n        self.mock_chroot(release, release['ostree_summary'])\n        return os.path.join(release['output_dir'], 'summary')",
    "docstring": "Update the ostree summary file and return a path to it"
  },
  {
    "code": "def reset(self):\n        self._attempts = 0\n        self._cur_delay = self.delay\n        self._cur_stoptime = None",
    "docstring": "Reset the attempt counter"
  },
  {
    "code": "def value_from_person(self, array, role, default = 0):\n        self.entity.check_role_validity(role)\n        if role.max != 1:\n            raise Exception(\n                'You can only use value_from_person with a role that is unique in {}. Role {} is not unique.'\n                .format(self.key, role.key)\n                )\n        self.members.check_array_compatible_with_entity(array)\n        members_map = self.ordered_members_map\n        result = self.filled_array(default, dtype = array.dtype)\n        if isinstance(array, EnumArray):\n            result = EnumArray(result, array.possible_values)\n        role_filter = self.members.has_role(role)\n        entity_filter = self.any(role_filter)\n        result[entity_filter] = array[members_map][role_filter[members_map]]\n        return result",
    "docstring": "Get the value of ``array`` for the person with the unique role ``role``.\n\n            ``array`` must have the dimension of the number of persons in the simulation\n\n            If such a person does not exist, return ``default`` instead\n\n            The result is a vector which dimension is the number of entities"
  },
  {
    "code": "def write_json(self, chunk, code=None, headers=None):\n        assert chunk is not None, 'None cound not be written in write_json'\n        self.set_header(\"Content-Type\", \"application/json; charset=UTF-8\")\n        if isinstance(chunk, dict) or isinstance(chunk, list):\n            chunk = self.json_encode(chunk)\n        try:\n            chunk = utf8(chunk)\n        except Exception:\n            app_log.error('chunk encoding error, repr: %s' % repr(chunk))\n            raise_exc_info(sys.exc_info())\n        self.write(chunk)\n        if code:\n            self.set_status(code)\n        if headers:\n            for k, v in headers.items():\n                self.set_header(k, v)",
    "docstring": "A convenient method that binds `chunk`, `code`, `headers` together\n\n        chunk could be any type of (str, dict, list)"
  },
  {
    "code": "def change(self, inpt, hashfun=DEFAULT_HASHFUN):\n        self.img = self.__create_image(inpt, hashfun)",
    "docstring": "Change the avatar by providing a new input.\n        Uses the standard hash function if no one is given."
  },
  {
    "code": "def enable_step_on_branch_mode(cls):\n        cls.write_msr(DebugRegister.DebugCtlMSR,\n                DebugRegister.BranchTrapFlag | DebugRegister.LastBranchRecord)",
    "docstring": "When tracing, call this on every single step event\n        for step on branch mode.\n\n        @raise WindowsError:\n            Raises C{ERROR_DEBUGGER_INACTIVE} if the debugger is not attached\n            to least one process.\n\n        @raise NotImplementedError:\n            Current architecture is not C{i386} or C{amd64}.\n\n        @warning:\n            This method uses the processor's machine specific registers (MSR).\n            It could potentially brick your machine.\n            It works on my machine, but your mileage may vary.\n\n        @note:\n            It doesn't seem to work in VMWare or VirtualBox machines.\n            Maybe it fails in other virtualization/emulation environments,\n            no extensive testing was made so far."
  },
  {
    "code": "def _assign(self, values):\n        LOGGER.debug('Assigning values: %r', values)\n        if not values:\n            return\n        keys = self.keys()\n        if not self._ref:\n            keys.append('_ref')\n        if isinstance(values, dict):\n            for key in keys:\n                if values.get(key):\n                    if isinstance(values.get(key), list):\n                        items = list()\n                        for item in values[key]:\n                            if isinstance(item, dict):\n                                if '_ref' in item:\n                                    obj_class = get_class(item['_ref'])\n                                    if obj_class:\n                                        items.append(obj_class(self._session,\n                                                               **item))\n                            else:\n                                items.append(item)\n                        setattr(self, key, items)\n                    else:\n                        setattr(self, key, values[key])\n        elif isinstance(values, list):\n            self._assign(values[0])\n        else:\n            LOGGER.critical('Unhandled return type: %r', values)",
    "docstring": "Assign the values passed as either a dict or list to the object if\n        the key for each value matches an available attribute on the object.\n\n        :param dict values: The values to assign"
  },
  {
    "code": "def detect_extracellular_compartment(model):\n    extracellular_key = Counter()\n    for reaction in model.reactions:\n        equation = reaction.equation\n        if equation is None:\n            continue\n        if len(equation.compounds) == 1:\n            compound, _ = equation.compounds[0]\n            compartment = compound.compartment\n            extracellular_key[compartment] += 1\n    if len(extracellular_key) == 0:\n        return None\n    else:\n        best_key, _ = extracellular_key.most_common(1)[0]\n    logger.info('{} is extracellular compartment'.format(best_key))\n    return best_key",
    "docstring": "Detect the identifier for equations with extracellular compartments.\n\n    Args:\n        model: :class:`NativeModel`."
  },
  {
    "code": "def get_rnn_cells(self) -> List[mx.rnn.BaseRNNCell]:\n        return self.forward_rnn.get_rnn_cells() + self.reverse_rnn.get_rnn_cells()",
    "docstring": "Returns a list of RNNCells used by this encoder."
  },
  {
    "code": "def global_permission_set(self):\n        only_admins_create_admins = Or(\n            AllowAdmin,\n            And(\n                ObjAttrTrue(\n                    lambda r, _: r.data.get('admin') is not True),\n                Or(\n                    AllowPermission('org:admin')\n                )\n            )\n        )\n        return And(\n            AllowOnlyAuthenticated,\n            Or(\n                Not(AllowCreate),\n                only_admins_create_admins\n            )\n        )",
    "docstring": "All users must be authenticated. Only admins can create other admin\n        users."
  },
  {
    "code": "def get_record_collections(record, matcher):\n    collections = current_collections.collections\n    if collections is None:\n        collections = current_collections.collections = dict(_build_cache())\n    output = set()\n    for collections in matcher(collections, record):\n        output |= collections\n    return list(output)",
    "docstring": "Return list of collections to which record belongs to.\n\n    :param record: Record instance.\n    :param matcher: Function used to check if a record belongs to a collection.\n    :return: list of collection names."
  },
  {
    "code": "def _build_netengine_arguments(self):\n        arguments = {\n            \"host\": self.host\n        }\n        if self.config is not None:\n            for key, value in self.config.iteritems():\n                arguments[key] = value\n        if self.port:\n            arguments[\"port\"] = self.port\n        return arguments",
    "docstring": "returns a python dictionary representing arguments\n        that will be passed to a netengine backend\n        for internal use only"
  },
  {
    "code": "def file_match_any(self, filename):\n        if filename.startswith('.' + os.sep):\n            filename = filename[len(os.sep) + 1:]\n        if os.sep != '/':\n            filename = filename.replace(os.sep, '/')\n        for selector in self.file_selectors:\n            if (selector.pattern.endswith('/') and\n                    filename.startswith(selector.pattern)):\n                return True\n            if fnmatch.fnmatch(filename, selector.pattern):\n                return True\n        return False",
    "docstring": "Match any filename."
  },
  {
    "code": "def _convert_url_to_downloadable(url):\n    if 'drive.google.com' in url:\n        file_id = url.split('d/')[1].split('/')[0]\n        base_url = 'https://drive.google.com/uc?export=download&id='\n        out = '{}{}'.format(base_url, file_id)\n    elif 'dropbox.com' in url:\n        if url.endswith('.png'):\n            out = url + '?dl=1'\n        else:\n            out = url.replace('dl=0', 'dl=1')\n    elif 'github.com' in url:\n        out = url.replace('github.com', 'raw.githubusercontent.com')\n        out = out.replace('blob/', '')\n    else:\n        out = url\n    return out",
    "docstring": "Convert a url to the proper style depending on its website."
  },
  {
    "code": "def resolve_pname(self, pname: PrefName,\n                      mid: ModuleId) -> Tuple[YangIdentifier, ModuleId]:\n        p, s, loc = pname.partition(\":\")\n        try:\n            mdata = self.modules[mid]\n        except KeyError:\n            raise ModuleNotRegistered(*mid) from None\n        try:\n            return (loc, mdata.prefix_map[p]) if s else (p, mdata.main_module)\n        except KeyError:\n            raise UnknownPrefix(p, mid) from None",
    "docstring": "Return the name and module identifier in which the name is defined.\n\n        Args:\n            pname: Name with an optional prefix.\n            mid: Identifier of the module in which `pname` appears.\n\n        Raises:\n            ModuleNotRegistered: If `mid` is not registered in the data model.\n            UnknownPrefix: If the prefix specified in `pname` is not declared."
  },
  {
    "code": "def retry(func, exception_type, quit_event):\n    while True:\n        if quit_event.is_set():\n            raise StopIteration\n        try:\n            return func()\n        except exception_type:\n            pass",
    "docstring": "Run the function, retrying when the specified exception_type occurs.\n\n    Poll quit_event on each iteration, to be responsive to an external\n    exit request."
  },
  {
    "code": "def execute(self, view, include=None):\n        return self._get(self._build_url(self.endpoint.execute(id=view, include=include)))",
    "docstring": "Execute a view.\n\n        :param include: list of objects to sideload. `Side-loading API Docs \n            <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.\n        :param view: View or view id"
  },
  {
    "code": "def setup_logging(handler, exclude=(\"gunicorn\", \"south\", \"elasticapm.errors\")):\n    logger = logging.getLogger()\n    if handler.__class__ in map(type, logger.handlers):\n        return False\n    logger.addHandler(handler)\n    return True",
    "docstring": "Configures logging to pipe to Elastic APM.\n\n    - ``exclude`` is a list of loggers that shouldn't go to ElasticAPM.\n\n    For a typical Python install:\n\n    >>> from elasticapm.handlers.logging import LoggingHandler\n    >>> client = ElasticAPM(...)\n    >>> setup_logging(LoggingHandler(client))\n\n    Within Django:\n\n    >>> from elasticapm.contrib.django.handlers import LoggingHandler\n    >>> setup_logging(LoggingHandler())\n\n    Returns a boolean based on if logging was configured or not."
  },
  {
    "code": "def get_checks(self, argument_name):\n        checks = []\n        for check, attrs in _checks[argument_name].items():\n            (codes, args) = attrs\n            if any(not (code and self.ignore_code(code)) for code in codes):\n                checks.append((check.__name__, check, args))\n        return sorted(checks)",
    "docstring": "Get all the checks for this category.\n\n        Find all globally visible functions where the first argument name\n        starts with argument_name and which contain selected tests."
  },
  {
    "code": "def new_station(self, _id, callSign, name, affiliate, fccChannelNumber):\n        if self.__v_station:\n            print(\"[Station: %s, %s, %s, %s, %s]\" % \n                  (_id, callSign, name, affiliate, fccChannelNumber))",
    "docstring": "Callback run for each new station"
  },
  {
    "code": "def resize(self, newsize, zeros=True):\n        if not self.can_resize:\n            raise ValueError(\"Segment %s can't be resized\" % str(self))\n        if not self.rawdata.is_base:\n            raise ValueError(\"Only container segments can be resized\")\n        origsize = len(self)\n        self.rawdata.resize(newsize)\n        self.set_raw(self.rawdata)\n        newsize = len(self)\n        if zeros:\n            if newsize > origsize:\n                self.data[origsize:] = 0\n                self.style[origsize:] = 0\n        return origsize, newsize",
    "docstring": "Resize the data arrays.\n\n        This can only be performed on the container segment. Child segments\n        must adjust their rawdata to point to the correct place.\n\n        Since segments don't keep references to other segments, it is the\n        user's responsibility to update any child segments that point to this\n        segment's data.\n\n        Numpy can't do an in-place resize on an array that has a view, so the\n        data must be replaced and all segments that point to that raw data must\n        also be changed. This has to happen outside this method because it\n        doesn't know the segment list of segments using itself as a base."
  },
  {
    "code": "def delete(name, dry_run, verbose):\n    collection = Collection.query.filter_by(name=name).one()\n    if verbose:\n        tr = LeftAligned(traverse=AttributeTraversal())\n        click.secho(tr(collection), fg='red')\n    db.session.delete(collection)",
    "docstring": "Delete a collection."
  },
  {
    "code": "def _stop_processes(paths):\n    def cache_checksum(path):\n        if not path:\n            return None\n        if not path in _process_checksums:\n            checksum = _get_checksum(path)\n            _process_checksums[path] = checksum\n        return _process_checksums[path]\n    if not paths:\n        return\n    target_checksums = dict((cache_checksum(p), 1) for p in paths)\n    if not target_checksums:\n        return\n    for proc, path in _get_user_processes():\n        if cache_checksum(path) in target_checksums:\n            try:\n                proc.terminate()\n            except (psutil.AccessDenied, psutil.NoSuchProcess):\n                pass",
    "docstring": "Scans process list trying to terminate processes matching paths\n        specified. Uses checksums to identify processes that are duplicates of\n        those specified to terminate.\n\n        `paths`\n            List of full paths to executables for processes to terminate."
  },
  {
    "code": "def update(xCqNck7t, **kwargs):\r\n        def dict_list_val(inlist):\r\n            l = []\r\n            for i in inlist:\r\n                if type(i)==dict:\r\n                    l.append(Dict(**i))\r\n                elif type(i)==list:\r\n                    l.append(make_list(i))\r\n                elif type(i)==bytes:\r\n                    l.append(i.decode('UTF-8'))\r\n                else:\r\n                    l.append(i)\r\n            return l\r\n        for k in list(kwargs.keys()):\r\n            if type(kwargs[k])==dict:\r\n                xCqNck7t[k] = Dict(**kwargs[k])\r\n            elif type(kwargs[k])==list:\r\n                xCqNck7t[k] = dict_list_val(kwargs[k])\r\n            else:\r\n                xCqNck7t[k] = kwargs[k]",
    "docstring": "Updates the Dict with the given values. Turns internal dicts into Dicts."
  },
  {
    "code": "def underlying_likelihood(self, binary_outcomes, modelparams, expparams):\n        original_mps = modelparams[..., self._orig_mps_slice]\n        return self.underlying_model.likelihood(binary_outcomes, original_mps, expparams)",
    "docstring": "Given outcomes hypothesized for the underlying model, returns the likelihood\n        which which those outcomes occur."
  },
  {
    "code": "def _login(self, environ, start_response):\n        response = HTTPUnauthorized()\n        response.www_authenticate = ('Basic', {'realm': self._realm})\n        return response(environ, start_response)",
    "docstring": "Send a login response back to the client."
  },
  {
    "code": "def get_assessment_taken(self, assessment_taken_id):\n        collection = JSONClientValidated('assessment',\n                                         collection='AssessmentTaken',\n                                         runtime=self._runtime)\n        result = collection.find_one(\n            dict({'_id': ObjectId(self._get_id(assessment_taken_id, 'assessment').get_identifier())},\n                 **self._view_filter()))\n        return objects.AssessmentTaken(osid_object_map=result, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets the ``AssessmentTaken`` specified by its ``Id``.\n\n        In plenary mode, the exact ``Id`` is found or a ``NotFound``\n        results. Otherwise, the returned ``AssessmentTaken`` may have a\n        different ``Id`` than requested, such as the case where a\n        duplicate ``Id`` was assigned to an ``AssessmentTaken`` and\n        retained for compatibility.\n\n        arg:    assessment_taken_id (osid.id.Id): ``Id`` of the\n                ``AssessmentTaken``\n        return: (osid.assessment.AssessmentTaken) - the assessment taken\n        raise:  NotFound - ``assessment_taken_id`` not found\n        raise:  NullArgument - ``assessment_taken_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method is must be implemented.*"
  },
  {
    "code": "def run_subprocess(command: str, verbose: bool = True, blocking: bool = True) \\\n        -> Optional[subprocess.Popen]:\n    if blocking:\n        result1 = subprocess.run(\n            command,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n            encoding='utf-8',\n            shell=True)\n        if verbose:\n            for output in (result1.stdout, result1.stderr):\n                output = output.strip()\n                if output:\n                    print(output)\n        return None\n    stdouterr = None if verbose else subprocess.DEVNULL\n    result2 = subprocess.Popen(\n        command,\n        stdout=stdouterr,\n        stderr=stdouterr,\n        encoding='utf-8',\n        shell=True)\n    return result2",
    "docstring": "Execute the given command in a new process.\n\n    Only when both `verbose` and `blocking` are |True|, |run_subprocess|\n    prints all responses to the current value of |sys.stdout|:\n\n    >>> from hydpy import run_subprocess\n    >>> import platform\n    >>> esc = '' if 'windows' in platform.platform().lower() else '\\\\\\\\'\n    >>> run_subprocess(f'python -c print{esc}(1+1{esc})')\n    2\n\n    With verbose being |False|, |run_subprocess| does never print out\n    anything:\n\n    >>> run_subprocess(f'python -c print{esc}(1+1{esc})', verbose=False)\n\n    >>> process = run_subprocess('python', blocking=False, verbose=False)\n    >>> process.kill()\n    >>> _ = process.communicate()\n\n    When `verbose` is |True| and `blocking` is |False|, |run_subprocess|\n    prints all responses to the console (\"invisible\" for doctests):\n\n    >>> process = run_subprocess('python', blocking=False)\n    >>> process.kill()\n    >>> _ = process.communicate()"
  },
  {
    "code": "def integral_scale(u, t, tau1=0.0, tau2=1.0):\r\n    tau, rho = autocorr_coeff(u, t, tau1, tau2)\r\n    zero_cross_ind = np.where(np.diff(np.sign(rho)))[0][0]\r\n    int_scale = np.trapz(rho[:zero_cross_ind], tau[:zero_cross_ind])\r\n    return int_scale",
    "docstring": "Calculate the integral scale of a time series by integrating up to\r\n    the first zero crossing."
  },
  {
    "code": "def bbox(self):\n        mn = amin(self.coordinates, axis=0)\n        mx = amax(self.coordinates, axis=0)\n        return concatenate((mn, mx))",
    "docstring": "Bounding box as minimum and maximum coordinates."
  },
  {
    "code": "def _trigger_params_changed(self, trigger_parent=True):\n        [p._trigger_params_changed(trigger_parent=False) for p in self.parameters if not p.is_fixed]\n        self.notify_observers(None, None if trigger_parent else -np.inf)",
    "docstring": "First tell all children to update,\n        then update yourself.\n\n        If trigger_parent is True, we will tell the parent, otherwise not."
  },
  {
    "code": "def tags(norm):\n    parts = norm.split('.')\n    return ['.'.join(parts[:i]) for i in range(1, len(parts) + 1)]",
    "docstring": "Divide a normalized tag string into hierarchical layers."
  },
  {
    "code": "def solve_semi_dual_entropic(a, b, M, reg, method, numItermax=10000, lr=None,\n                                log=False):\n    if method.lower() == \"sag\":\n        opt_beta = sag_entropic_transport(a, b, M, reg, numItermax, lr)\n    elif method.lower() == \"asgd\":\n        opt_beta = averaged_sgd_entropic_transport(a, b, M, reg, numItermax, lr)\n    else:\n        print(\"Please, select your method between SAG and ASGD\")\n        return None\n    opt_alpha = c_transform_entropic(b, M, reg, opt_beta)\n    pi = (np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg) *\n          a[:, None] * b[None, :])\n    if log:\n        log = {}\n        log['alpha'] = opt_alpha\n        log['beta'] = opt_beta\n        return pi, log\n    else:\n        return pi",
    "docstring": "Compute the transportation matrix to solve the regularized discrete\n        measures optimal transport max problem\n\n    The function solves the following optimization problem:\n\n    .. math::\n        \\gamma = arg\\min_\\gamma <\\gamma,M>_F + reg\\cdot\\Omega(\\gamma)\n\n        s.t. \\gamma 1 = a\n\n             \\gamma^T 1= b\n\n             \\gamma \\geq 0\n\n    Where :\n\n    - M is the (ns,nt) metric cost matrix\n    - :math:`\\Omega` is the entropic regularization term with :math:`\\Omega(\\gamma)=\\sum_{i,j} \\gamma_{i,j}\\log(\\gamma_{i,j})`\n    - a and b are source and target weights (sum to 1)\n    The algorithm used for solving the problem is the SAG or ASGD algorithms\n    as proposed in [18]_\n\n\n    Parameters\n    ----------\n\n    a : np.ndarray(ns,)\n        source measure\n    b : np.ndarray(nt,)\n        target measure\n    M : np.ndarray(ns, nt)\n        cost matrix\n    reg : float number\n        Regularization term > 0\n    methode : str\n        used method (SAG or ASGD)\n    numItermax : int number\n        number of iteration\n    lr : float number\n        learning rate\n    n_source : int number\n        size of the source measure\n    n_target : int number\n        size of the target measure\n    log : bool, optional\n        record log if True\n\n    Returns\n    -------\n\n    pi : np.ndarray(ns, nt)\n        transportation matrix\n    log : dict\n        log dictionary return only if log==True in parameters\n\n    Examples\n    --------\n\n    >>> n_source = 7\n    >>> n_target = 4\n    >>> reg = 1\n    >>> numItermax = 300000\n    >>> a = ot.utils.unif(n_source)\n    >>> b = ot.utils.unif(n_target)\n    >>> rng = np.random.RandomState(0)\n    >>> X_source = rng.randn(n_source, 2)\n    >>> Y_target = rng.randn(n_target, 2)\n    >>> M = ot.dist(X_source, Y_target)\n    >>> method = \"ASGD\"\n    >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,\n                                                      method, numItermax)\n    >>> print(asgd_pi)\n\n    References\n    ----------\n\n    [Genevay et al., 2016] :\n                    Stochastic Optimization for Large-scale Optimal Transport,\n                     Advances in Neural Information Processing Systems (2016),\n                      arXiv preprint arxiv:1605.08527."
  },
  {
    "code": "def boolean(\n        element_name,\n        attribute=None,\n        required=True,\n        alias=None,\n        default=False,\n        omit_empty=False,\n        hooks=None\n):\n    return _PrimitiveValue(\n        element_name,\n        _parse_boolean,\n        attribute,\n        required,\n        alias,\n        default,\n        omit_empty,\n        hooks\n    )",
    "docstring": "Create a processor for boolean values.\n\n    :param element_name: Name of the XML element containing the value. Can also be specified\n        using supported XPath syntax.\n    :param attribute: If specified, then the value is searched for under the\n        attribute within the element specified by element_name. If not specified,\n        then the value is searched for as the contents of the element specified by\n        element_name.\n    :param required: Indicates whether the value is required when parsing and serializing.\n    :param alias: If specified, then this is used as the name of the value when read from\n        XML. If not specified, then the element_name is used as the name of the value.\n    :param default: Default value to use if the element is not present. This option is only\n        valid if required is specified as False.\n    :param omit_empty: If True, then Falsey values will be omitted when serializing to XML. Note\n        that Falsey values are never omitted when they are elements of an array. Falsey values can\n        be omitted only when they are standalone elements.\n    :param hooks: A Hooks object.\n\n    :return: A declxml processor object."
  },
  {
    "code": "def to_match(self):\n        self.validate()\n        translation_table = {\n            u'size': u'size()',\n        }\n        match_operator = translation_table.get(self.operator)\n        if not match_operator:\n            raise AssertionError(u'Unrecognized operator used: '\n                                 u'{} {}'.format(self.operator, self))\n        template = u'%(inner)s.%(operator)s'\n        args = {\n            'inner': self.inner_expression.to_match(),\n            'operator': match_operator,\n        }\n        return template % args",
    "docstring": "Return a unicode object with the MATCH representation of this UnaryTransformation."
  },
  {
    "code": "async def iter_lines(\n            self,\n            *cmds: str,\n            stream: str='both') -> AsyncGenerator[str, None]:\n        sps = self.spawn(*cmds)\n        if stream == 'both':\n            agen = amerge(\n                amerge(*[sp.stdout for sp in sps]),\n                amerge(*[sp.stderr for sp in sps]))\n        elif stream == 'stdout':\n            agen = amerge(*[sp.stdout for sp in sps])\n        elif stream == 'stderr':\n            agen = amerge(*[sp.stderr for sp in sps])\n        else:\n            raise SublemonRuntimeError(\n                'Invalid `stream` kwarg received: `' + str(stream) + '`')\n        async for line in agen:\n            yield line.decode('utf-8').rstrip()",
    "docstring": "Coroutine to spawn commands and yield text lines from stdout."
  },
  {
    "code": "def as_requirement(self):\n        if isinstance(self.parsed_version, packaging.version.Version):\n            spec = \"%s==%s\" % (self.project_name, self.parsed_version)\n        else:\n            spec = \"%s===%s\" % (self.project_name, self.parsed_version)\n        return Requirement.parse(spec)",
    "docstring": "Return a ``Requirement`` that matches this distribution exactly"
  },
  {
    "code": "def sys_check_for_event(\n    mask: int, k: Optional[Key], m: Optional[Mouse]\n) -> int:\n    return int(\n        lib.TCOD_sys_check_for_event(\n            mask, k.key_p if k else ffi.NULL, m.mouse_p if m else ffi.NULL\n        )\n    )",
    "docstring": "Check for and return an event.\n\n    Args:\n        mask (int): :any:`Event types` to wait for.\n        k (Optional[Key]): A tcod.Key instance which might be updated with\n                           an event.  Can be None.\n        m (Optional[Mouse]): A tcod.Mouse instance which might be updated\n                             with an event.  Can be None.\n\n    .. deprecated:: 9.3\n        Use the :any:`tcod.event.get` function to check for events."
  },
  {
    "code": "def commit_config(self, label=None, comment=None, confirmed=None):\n        rpc_command = '<Commit'\n        if label:\n            rpc_command += ' Label=\"%s\"' % label\n        if comment:\n            rpc_command += ' Comment=\"%s\"' % comment[:60]\n        if confirmed:\n            if 30 <= int(confirmed) <= 300:\n                rpc_command += ' Confirmed=\"%d\"' % int(confirmed)\n            else:\n                raise InvalidInputError('confirmed needs to be between 30 and 300 seconds', self)\n        rpc_command += '/>'\n        self._execute_rpc(rpc_command)",
    "docstring": "Commit the candidate config.\n\n        :param label:     Commit comment, displayed in the commit entry on the device.\n        :param comment:   Commit label, displayed instead of the commit ID on the device. (Max 60 characters)\n        :param confirmed: Commit with auto-rollback if new commit is not made in 30 to 300 sec"
  },
  {
    "code": "def get_active_clients():\n    global drivers\n    if not drivers:\n        return jsonify([])\n    result = {client: get_client_info(client) for client in drivers}\n    return jsonify(result)",
    "docstring": "Get a list of all active clients and their status"
  },
  {
    "code": "def performAction(self, action):\n        self.t += 1\n        Task.performAction(self, action)\n        self.samples += 1",
    "docstring": "Execute one action."
  },
  {
    "code": "def clampings_iter(self, cues=None):\n        s = cues or list(self.stimuli + self.inhibitors)\n        clampings = it.chain.from_iterable(it.combinations(s, r) for r in xrange(len(s) + 1))\n        literals_tpl = {}\n        for stimulus in self.stimuli:\n            literals_tpl[stimulus] = -1\n        for c in clampings:\n            literals = literals_tpl.copy()\n            for cues in c:\n                if cues in self.stimuli:\n                    literals[cues] = 1\n                else:\n                    literals[cues] = -1\n            yield Clamping(literals.iteritems())",
    "docstring": "Iterates over all possible clampings of this experimental setup\n\n        Parameters\n        ----------\n        cues : Optional[iterable]\n            If given, restricts clampings over given species names\n\n\n        Yields\n        ------\n        caspo.core.clamping.Clamping\n            The next clamping with respect to the experimental setup"
  },
  {
    "code": "def _perturbation(self):\n        if self.P>1:\n            scales = []\n            for term_i in range(self.n_terms):\n                _scales = SP.randn(self.diag[term_i].shape[0])\n                if self.offset[term_i]>0:\n                    _scales  = SP.concatenate((_scales,SP.zeros(1)))\n                scales.append(_scales)\n            scales = SP.concatenate(scales)\n        else:\n            scales = SP.randn(self.vd.getNumberScales())\n        return scales",
    "docstring": "Returns Gaussian perturbation"
  },
  {
    "code": "def date_range(start_date, end_date, increment, period):\n    next = start_date\n    delta = relativedelta.relativedelta(**{period:increment})\n    while next <= end_date:\n        yield next\n        next += delta",
    "docstring": "Generate `date` objects between `start_date` and `end_date` in `increment`\n    `period` intervals."
  },
  {
    "code": "def complete(self):\n        if self._possible is None:\n            self._possible = []\n            for possible in self.names:\n                c = Completion(self.context, self.names[possible], len(self.context.symbol))\n                self._possible.append(c)\n        return self._possible",
    "docstring": "Gets a list of completion objects for the symbol under the cursor."
  },
  {
    "code": "def ulogin_response(self, token, host):\n        response = requests.get(\n            settings.TOKEN_URL,\n            params={\n                'token': token,\n                'host': host\n            })\n        content = response.content\n        if sys.version_info >= (3, 0):\n            content = content.decode('utf8')\n        return json.loads(content)",
    "docstring": "Makes a request to ULOGIN"
  },
  {
    "code": "def _get_cifar(directory, url):\n  filename = os.path.basename(url)\n  path = generator_utils.maybe_download(directory, filename, url)\n  tarfile.open(path, \"r:gz\").extractall(directory)",
    "docstring": "Download and extract CIFAR to directory unless it is there."
  },
  {
    "code": "def _load_config(self):\n        config = import_module('config')\n        variables = [var for var in dir(config) if not var.startswith('_')]\n        return {var: getattr(config, var) for var in variables}",
    "docstring": "Load project's config and return dict.\n\n        TODO: Convert the original dotted representation to hierarchical."
  },
  {
    "code": "def ordered_load(self, stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):\n        class OrderedLoader(Loader):\n            pass\n        def construct_mapping(loader, node):\n            loader.flatten_mapping(node)\n            return object_pairs_hook(loader.construct_pairs(node))\n        OrderedLoader.add_constructor(\n            yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,\n            construct_mapping)\n        try:\n            try:\n                result = yaml.load(stream, OrderedLoader)\n            except yaml.scanner.ScannerError:\n                if type(stream) == str:\n                    result = json.loads(stream, object_pairs_hook=object_pairs_hook)\n                else:\n                    stream.seek(0)\n                    result = json.load(stream, object_pairs_hook=object_pairs_hook)\n        except Exception as e:\n            self.error(e)\n            result = {}\n        return result",
    "docstring": "Allows you to use `pyyaml` to load as OrderedDict.\n\n        Taken from https://stackoverflow.com/a/21912744/1927102"
  },
  {
    "code": "def get_help(self, prefix='', include_special_flags=True):\n    flags_by_module = self.flags_by_module_dict()\n    if flags_by_module:\n      modules = sorted(flags_by_module)\n      main_module = sys.argv[0]\n      if main_module in modules:\n        modules.remove(main_module)\n        modules = [main_module] + modules\n      return self._get_help_for_modules(modules, prefix, include_special_flags)\n    else:\n      output_lines = []\n      values = six.itervalues(self._flags())\n      if include_special_flags:\n        values = itertools.chain(\n            values, six.itervalues(_helpers.SPECIAL_FLAGS._flags()))\n      self._render_flag_list(values, output_lines, prefix)\n      return '\\n'.join(output_lines)",
    "docstring": "Returns a help string for all known flags.\n\n    Args:\n      prefix: str, per-line output prefix.\n      include_special_flags: bool, whether to include description of\n        SPECIAL_FLAGS, i.e. --flagfile and --undefok.\n\n    Returns:\n      str, formatted help message."
  },
  {
    "code": "def zoom_pinch_cb(self, fitsimage, event):\n        chviewer = self.fv.getfocus_viewer()\n        bd = chviewer.get_bindings()\n        if hasattr(bd, 'pi_zoom'):\n            return bd.pi_zoom(chviewer, event)\n        return False",
    "docstring": "Pinch event in the pan window.  Just zoom the channel viewer."
  },
  {
    "code": "def _metaclass_lookup_attribute(self, name, context):\n        attrs = set()\n        implicit_meta = self.implicit_metaclass()\n        metaclass = self.metaclass()\n        for cls in {implicit_meta, metaclass}:\n            if cls and cls != self and isinstance(cls, ClassDef):\n                cls_attributes = self._get_attribute_from_metaclass(cls, name, context)\n                attrs.update(set(cls_attributes))\n        return attrs",
    "docstring": "Search the given name in the implicit and the explicit metaclass."
  },
  {
    "code": "def neighbors(self, n, t=None):\n        try:\n            if t is None:\n                return list(self._adj[n])\n            else:\n                return [i for i in self._adj[n] if self.__presence_test(n, i, t)]\n        except KeyError:\n            raise nx.NetworkXError(\"The node %s is not in the graph.\" % (n,))",
    "docstring": "Return a list of the nodes connected to the node n at time t.\n\n        Parameters\n        ----------\n        n : node\n           A node in the graph\n        t : snapshot id (default=None)\n            If None will be returned the neighbors of the node on the flattened graph.\n\n\n        Returns\n        -------\n        nlist : list\n            A list of nodes that are adjacent to n.\n\n        Raises\n        ------\n        NetworkXError\n            If the node n is not in the graph.\n\n        Examples\n        --------\n        >>> G = dn.DynGraph()\n        >>> G.add_path([0,1,2,3], t=0)\n        >>> G.neighbors(0, t=0)\n        [1]\n        >>> G.neighbors(0, t=1)\n        []"
  },
  {
    "code": "def fillna(self, value):\n        if not is_scalar(value):\n            raise TypeError('Value to replace with is not a valid scalar')\n        return Index(weld_replace(self.weld_expr,\n                                  self.weld_type,\n                                  default_missing_data_literal(self.weld_type),\n                                  value),\n                     self.dtype,\n                     self.name)",
    "docstring": "Returns Index with missing values replaced with value.\n\n        Parameters\n        ----------\n        value : {int, float, bytes, bool}\n            Scalar value to replace missing values with.\n\n        Returns\n        -------\n        Index\n            With missing values replaced."
  },
  {
    "code": "def find_service_by_id(self, service_id):\n        service_id_key = 'serviceDefinitionId'\n        service_id = str(service_id)\n        for service in self._services:\n            if service_id_key in service.values and str(\n                    service.values[service_id_key]) == service_id:\n                return service\n        try:\n            int(service_id)\n            return None\n        except ValueError:\n            pass\n        return self.find_service_by_type(service_id)",
    "docstring": "Get service for a given service_id.\n\n        :param service_id: Service id, str\n        :return: Service"
  },
  {
    "code": "def reads(args):\n    p = OptionParser(reads.__doc__)\n    p.add_option(\"-p\", dest=\"prefix_length\", default=4, type=\"int\",\n            help=\"group the reads based on the first N chars [default: %default]\")\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(p.print_help())\n    frgscffile, = args\n    prefix_length = opts.prefix_length\n    fp = open(frgscffile)\n    keyfn = lambda: defaultdict(int)\n    counts = defaultdict(keyfn)\n    for row in fp:\n        f = FrgScfLine(row)\n        fi = f.fragmentID[:prefix_length]\n        counts[f.scaffoldID][fi] += 1\n    for scf, count in sorted(counts.items()):\n        print(\"{0}\\t{1}\".format(scf,\n                \", \".join(\"{0}:{1}\".format(*x) for x in sorted(count.items()))))",
    "docstring": "%prog reads frgscffile\n\n    Report read counts per scaffold (based on frgscf)."
  },
  {
    "code": "def using(self, alias):\n        clone = self._clone()\n        clone._index = alias\n        return clone",
    "docstring": "Selects which database this QuerySet should excecute its query against."
  },
  {
    "code": "def spectrum_loglike(self, specType, params, scale=1E3):\n        sfn = self.create_functor(specType, scale)[0]\n        return self.__call__(sfn(params))",
    "docstring": "return the log-likelihood for a particular spectrum\n\n        Parameters\n        ----------\n        specTypes  : str\n            The type of spectrum to try\n\n        params : array-like\n            The spectral parameters\n\n        scale : float\n            The energy scale or 'pivot' energy"
  },
  {
    "code": "def _prev_month(self):\n        self._canvas.place_forget()\n        self._date = self._date - self.timedelta(days=1)\n        self._date = self.datetime(self._date.year, self._date.month, 1)\n        self._build_calendar()",
    "docstring": "Updated calendar to show the previous month."
  },
  {
    "code": "def pept_diff(p1, p2):\n    if len(p1) != len(p2):\n        return -1\n    else:\n        return sum([p1[i] != p2[i] for i in range(len(p1))])",
    "docstring": "Return the number of differences betweeen 2 peptides\n\n    :param str p1: Peptide 1\n    :param str p2: Peptide 2\n    :return: The number of differences between the pepetides\n    :rtype: int\n\n    >>> pept_diff('ABCDE', 'ABCDF')\n    1\n    >>> pept_diff('ABCDE', 'ABDFE')\n    2\n    >>> pept_diff('ABCDE', 'EDCBA')\n    4\n    >>> pept_diff('ABCDE', 'ABCDE')\n    0"
  },
  {
    "code": "def set_log_type_name(self, logType, name):\n        assert logType in self.__logTypeStdoutFlags.keys(), \"logType '%s' not defined\" %logType\n        assert isinstance(name, basestring), \"name must be a string\"\n        name = str(name)\n        self.__logTypeNames[logType] = name",
    "docstring": "Set a logtype name.\n\n        :Parameters:\n           #. logType (string): A defined logging type.\n           #. name (string): The logtype new name."
  },
  {
    "code": "def create_binary_descriptor(streamer):\n    trigger = 0\n    if streamer.automatic:\n        trigger = 1\n    elif streamer.with_other is not None:\n        trigger = (1 << 7) | streamer.with_other\n    return struct.pack(\"<8sHBBBx\", streamer.dest.encode(), streamer.selector.encode(), trigger, streamer.KnownFormats[streamer.format], streamer.KnownTypes[streamer.report_type])",
    "docstring": "Create a packed binary descriptor of a DataStreamer object.\n\n    Args:\n        streamer (DataStreamer): The streamer to create a packed descriptor for\n\n    Returns:\n        bytes: A packed 14-byte streamer descriptor."
  },
  {
    "code": "def fmap(self, f: 'WrappedFunction') -> 'WrappedFunction':\n        if not isinstance(f, WrappedFunction):\n            f = WrappedFunction(f)\n        return WrappedFunction(lambda *args, **kwargs: self(f(*args, **kwargs)), nargs=f.nargs, nouts=self.nouts)",
    "docstring": "function map for Wrapped Function. A forced transfermation to WrappedFunction would be applied.async def \n\n            fmap(self, f: 'WrappedFunction') -> 'WrappedFunction'"
  },
  {
    "code": "def dashes(phone):\n    if isinstance(phone, str):\n        if phone.startswith(\"+1\"):\n            return \"1-\" + \"-\".join((phone[2:5], phone[5:8], phone[8:]))\n        elif len(phone) == 10:\n            return \"-\".join((phone[:3], phone[3:6], phone[6:]))\n        else:\n            return phone\n    else:\n        return phone",
    "docstring": "Returns the phone number formatted with dashes."
  },
  {
    "code": "def _get_movie_raw_metadata():\n    path = _get_movielens_path()\n    if not os.path.isfile(path):\n        _download_movielens(path)\n    with zipfile.ZipFile(path) as datafile:\n        return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\\n')",
    "docstring": "Get raw lines of the genre file."
  },
  {
    "code": "def get_level_methods(self, level):\n        try:\n            return set(self.__levels[level])\n        except KeyError:\n            result = set()\n            for sub_level in self.__aliases[level]:\n                result.update(self.get_level_methods(sub_level))\n            return result",
    "docstring": "Returns the methods to call for the given level of report\n\n        :param level: The level of report\n        :return: The set of methods to call to fill the report\n        :raise KeyError: Unknown level or alias"
  },
  {
    "code": "def _log_board_ports(self, ports):\n        ports = sorted(ports, key=lambda port: (port.tile_id, port.direction))\n        self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction)\n                                                for p in ports)))",
    "docstring": "A board with no ports is allowed.\n\n        In the logfile, ports must be sorted\n        - ascending by tile identifier (primary)\n        - alphabetical by edge direction (secondary)\n\n        :param ports: list of catan.board.Port objects"
  },
  {
    "code": "def flip_motion(self, value):\r\n        if value:\r\n            self.cam.enable_motion_detection()\r\n        else:\r\n            self.cam.disable_motion_detection()",
    "docstring": "Toggle motion detection"
  },
  {
    "code": "def slice(self, items):\n        if self.limit:\n            if self.page>self.pages_count:\n                return []\n            if self.page == self.pages_count:\n                return items[self.limit*(self.page-1):]\n            return items[self.limit*(self.page-1):self.limit*self.page]\n        else:\n            return items[:]",
    "docstring": "Slice the sequence of all items to obtain them for current page."
  },
  {
    "code": "def by_name(self, name, archived=False, limit=None, page=None):\n        return super(Projects, self).by_name(name, archived=archived,\n                                             limit=limit, page=page)",
    "docstring": "return a project by it's name.\n        this only works with the exact name of the project."
  },
  {
    "code": "def with_optimizer_tensor(self, tensor: Union[tf.Tensor, tf.Operation]) -> 'Optimization':\n        self._optimizer_tensor = tensor\n        return self",
    "docstring": "Replace optimizer tensor.\n\n            :param model: Tensorflow tensor.\n            :return: Optimization instance self reference."
  },
  {
    "code": "def _update_phi(self):\n        etaprod = 1.0\n        for w in range(N_NT - 1):\n            self.phi[w] = etaprod * (1 - self.eta[w])\n            etaprod *= self.eta[w]\n        self.phi[N_NT - 1] = etaprod",
    "docstring": "Update `phi` using current `eta`."
  },
  {
    "code": "def view_links(obj):\n    result=format_html('')\n    result+=format_html('<a href=\"%s\" style=\"white-space: nowrap\">Show duplicates</a><br/>'%reverse('duplicates', args=(obj.pk,)))\n    result+=format_html('<a href=\"%s\" style=\"white-space: nowrap\">Show submissions</a><br/>'%obj.grading_url())\n    result+=format_html('<a href=\"%s\" style=\"white-space: nowrap\">Download submissions</a>'%reverse('assarchive', args=(obj.pk,)))\n    return result",
    "docstring": "Link to performance data and duplicate overview."
  },
  {
    "code": "def put(self, fn):\n    self._inserted += 1\n    self._queue.put(fn, block=True)\n    return self",
    "docstring": "Enqueue a task function for processing.\n\n    Requires:\n      fn: a function object that takes one argument\n        that is the interface associated with each\n        thread.\n\n        e.g. def download(api):\n               results.append(api.download())\n\n             self.put(download)\n\n    Returns: self"
  },
  {
    "code": "def clone(self, into=None):\n    into = into or safe_mkdtemp()\n    new_chroot = Chroot(into)\n    for label, fileset in self.filesets.items():\n      for fn in fileset:\n        new_chroot.link(os.path.join(self.chroot, fn), fn, label=label)\n    return new_chroot",
    "docstring": "Clone this chroot.\n\n    :keyword into: (optional) An optional destination directory to clone the\n      Chroot into.  If not specified, a temporary directory will be created.\n\n    .. versionchanged:: 0.8\n      The temporary directory created when ``into`` is not specified is now garbage collected on\n      interpreter exit."
  },
  {
    "code": "def detag_string(self, string):\n        counter = itertools.count(0)\n        count = lambda m: '<%s>' % next(counter)\n        tags = self.tag_pattern.findall(string)\n        tags = [''.join(tag) for tag in tags]\n        (new, nfound) = self.tag_pattern.subn(count, string)\n        if len(tags) != nfound:\n            raise Exception('tags dont match:' + string)\n        return (new, tags)",
    "docstring": "Extracts tags from string.\n\n           returns (string, list) where\n           string: string has tags replaced by indices (<BR>... => <0>, <1>, <2>, etc.)\n           list: list of the removed tags ('<BR>', '<I>', '</I>')"
  },
  {
    "code": "def seen_tasks(self):\n        print('\\n'.join(self._stub.seen_tasks(clearly_pb2.Empty()).task_types))",
    "docstring": "Shows a list of seen task types."
  },
  {
    "code": "def changeThreadTitle(self, title, thread_id=None, thread_type=ThreadType.USER):\n        thread_id, thread_type = self._getThread(thread_id, thread_type)\n        if thread_type == ThreadType.USER:\n            return self.changeNickname(\n                title, thread_id, thread_id=thread_id, thread_type=thread_type\n            )\n        data = {\"thread_name\": title, \"thread_id\": thread_id}\n        j = self._post(self.req_url.THREAD_NAME, data, fix_request=True, as_json=True)",
    "docstring": "Changes title of a thread.\n        If this is executed on a user thread, this will change the nickname of that user, effectively changing the title\n\n        :param title: New group thread title\n        :param thread_id: Group ID to change title of. See :ref:`intro_threads`\n        :param thread_type: See :ref:`intro_threads`\n        :type thread_type: models.ThreadType\n        :raises: FBchatException if request failed"
  },
  {
    "code": "def update(self, n=1):\n    with self._lock:\n      self._pbar.update(n)\n      self.refresh()",
    "docstring": "Increment current value."
  },
  {
    "code": "def make_unique_name(name, existing_names, name_format=\"{name}_{index}\", start=2):\n    index = start\n    new_name = name\n    while new_name in existing_names:\n        new_name = name_format.format(name=name, index=index)\n        index += 1\n    return new_name",
    "docstring": "Return a unique name based on `name_format` and `name`."
  },
  {
    "code": "def explode_line(argument_line: str) -> typing.Tuple[str, str]:\n    parts = tuple(argument_line.split(' ', 1)[-1].split(':', 1))\n    return parts if len(parts) > 1 else (parts[0], '')",
    "docstring": "Returns a tuple containing the parameter name and the description parsed\n    from the given argument line"
  },
  {
    "code": "def _attach_to_model(self, model):\n        super(RelatedFieldMixin, self)._attach_to_model(model)\n        if model.abstract:\n            return\n        self.related_name = self._get_related_name()\n        self.related_to = self._get_related_model_name()\n        if not hasattr(self.database, '_relations'):\n            self.database._relations = {}\n        self.database._relations.setdefault(self.related_to, [])\n        self._assert_relation_does_not_exists()\n        relation = (self._model._name, self.name, self.related_name)\n        self.database._relations[self.related_to].append(relation)",
    "docstring": "When we have a model, save the relation in the database, to later create\n        RelatedCollection objects in the related model"
  },
  {
    "code": "def __destroyLockedView(self):\r\n        if self._lockedView:\r\n            self._lockedView.close()\r\n            self._lockedView.deleteLater()\r\n            self._lockedView = None",
    "docstring": "Destroys the locked view from this widget."
  },
  {
    "code": "def parse_config(self):\n        tree = ElementTree.parse(self.file_xml)\n        root = tree.getroot()\n        for server in root.findall('server'):\n            destination = server.text\n            name = server.get(\"name\")\n            self.discover_remote(destination, name)",
    "docstring": "Parse the xml file with remote servers and discover resources on each found server."
  },
  {
    "code": "def chunker(l, n):\n    for i in ranger(0, len(l), n):\n        yield l[i:i + n]",
    "docstring": "Generates n-sized chunks from the list l"
  },
  {
    "code": "def extract_rows(data, *rows):\n    try:\n        out = []\n        for r in rows:\n            out.append(data[r])\n        return out\n    except IndexError:\n        raise IndexError(\"data=%s rows=%s\" % (data, rows))\n    return out",
    "docstring": "Extract rows specified in the argument list.\n\n>>> chart_data.extract_rows([[10,20], [30,40], [50,60]], 1, 2)\n[[30,40],[50,60]]"
  },
  {
    "code": "def uniqued(iterable):\n    seen = set()\n    return [item for item in iterable if item not in seen and not seen.add(item)]",
    "docstring": "Return unique list of ``iterable`` items preserving order.\n\n    >>> uniqued('spameggs')\n    ['s', 'p', 'a', 'm', 'e', 'g']"
  },
  {
    "code": "def get_checksum(self):\n        arr = [ ]\n        for elem in self.parsed:\n            s = elem_checksum(elem)\n            if s:\n                arr.append(s)\n        arr.sort()\n        return md5(json.dumps(arr))",
    "docstring": "Returns a checksum based on the IDL that ignores comments and \n        ordering, but detects changes to types, parameter order, \n        and enum values."
  },
  {
    "code": "def matrix(self, angle):\n        _rot_mat = {\n            'x': self._x_rot,\n            'y': self._y_rot,\n            'z': self._z_rot\n        }\n        return _rot_mat[self.axis](angle)",
    "docstring": "Return rotation matrix in homogeneous coordinates."
  },
  {
    "code": "def get_room_member_ids(self, room_id, start=None, timeout=None):\n        params = None if start is None else {'start': start}\n        response = self._get(\n            '/v2/bot/room/{room_id}/members/ids'.format(room_id=room_id),\n            params=params,\n            timeout=timeout\n        )\n        return MemberIds.new_from_json_dict(response.json)",
    "docstring": "Call get room member IDs API.\n\n        https://devdocs.line.me/en/#get-group-room-member-ids\n\n        Gets the user IDs of the members of a group that the bot is in.\n        This includes the user IDs of users who have not added the bot as a friend\n        or has blocked the bot.\n\n        :param str room_id: Room ID\n        :param str start: continuationToken\n        :param timeout: (optional) How long to wait for the server\n            to send data before giving up, as a float,\n            or a (connect timeout, read timeout) float tuple.\n            Default is self.http_client.timeout\n        :type timeout: float | tuple(float, float)\n        :rtype: :py:class:`linebot.models.responses.MemberIds`\n        :return: MemberIds instance"
  },
  {
    "code": "def sampling(self, ufunc, **kwargs):\n        self.space.sampling(ufunc, out=self.tensor, **kwargs)",
    "docstring": "Sample a continuous function and assign to this element.\n\n        Parameters\n        ----------\n        ufunc : ``self.space.fspace`` element\n            The continuous function that should be samplingicted.\n        kwargs :\n            Additional arugments for the sampling operator implementation\n\n        Examples\n        --------\n        >>> space = odl.uniform_discr(0, 1, 5)\n        >>> x = space.element()\n\n        Assign x according to a continuous function:\n\n        >>> x.sampling(lambda t: t)\n        >>> x  # Print values at grid points (which are centered)\n        uniform_discr(0.0, 1.0, 5).element([ 0.1,  0.3,  0.5,  0.7,  0.9])\n\n        See Also\n        --------\n        DiscretizedSpace.sampling : For full description"
  },
  {
    "code": "def get_field(self, offset, length, format):\n        return struct.unpack(format, self.data[offset:offset + length])[0]",
    "docstring": "Returns unpacked Python struct array.\n\n        Args:\n            offset (int): offset to byte array within structure\n            length (int): how many bytes to unpack\n            format (str): Python struct format string for unpacking\n\n        See Also:\n            https://docs.python.org/2/library/struct.html#format-characters"
  },
  {
    "code": "def get_version(svn=False, limit=3):\n    \"Returns the version as a human-format string.\"\n    v = '.'.join([str(i) for i in VERSION[:limit]])\n    if svn and limit >= 3:\n        from django.utils.version import get_svn_revision\n        import os\n        svn_rev = get_svn_revision(os.path.dirname(__file__))\n        if svn_rev:\n            v = '%s.%s' % (v, svn_rev)\n    return v",
    "docstring": "Returns the version as a human-format string."
  },
  {
    "code": "def tuple_to_datetime(self, date_tuple):\n    year, month, day, hour, minute, second = date_tuple\n    if year == month == day == 0:\n      return time(hour, minute, second)\n    elif hour == minute == second == 0:\n      return date(year, month, day)\n    else:\n      return datetime(year, month, day, hour, minute, second)",
    "docstring": "Converts a tuple to a either a date, time or datetime object.\n\n    If the Y, M and D parts of the tuple are all 0, then a time object is returned.\n    If the h, m and s aprts of the tuple are all 0, then a date object is returned.\n    Otherwise a datetime object is returned."
  },
  {
    "code": "def contains(self, key):\n    return self.cache_datastore.contains(key) \\\n        or self.child_datastore.contains(key)",
    "docstring": "Returns whether the object named by `key` exists.\n       First checks ``cache_datastore``."
  },
  {
    "code": "def run(self, user_kw=None, build_kw=None):\n        user_kw = {} if user_kw is None else user_kw\n        build_kw = {} if build_kw is None else build_kw\n        n = self._build(self.get_items(**user_kw), **build_kw)\n        finalized = self.finalize(self._status.has_failures())\n        if not finalized:\n            _log.error(\"Finalization failed\")\n        return n",
    "docstring": "Run the builder.\n\n        :param user_kw: keywords from user\n        :type user_kw: dict\n        :param build_kw: internal settings\n        :type build_kw: dict\n        :return: Number of items processed\n        :rtype: int"
  },
  {
    "code": "def get_subgraph(self, name):\n        match = list()\n        if name in self.obj_dict['subgraphs']:\n            sgraphs_obj_dict = self.obj_dict['subgraphs'].get( name )\n            for obj_dict_list in sgraphs_obj_dict:\n                match.append( Subgraph( obj_dict = obj_dict_list ) )\n        return match",
    "docstring": "Retrieved a subgraph from the graph.\n\n        Given a subgraph's name the corresponding\n        Subgraph instance will be returned.\n\n        If one or more subgraphs exist with the same name, a list of\n        Subgraph instances is returned.\n        An empty list is returned otherwise."
  },
  {
    "code": "def closeEvent(self, event):\n        if self.inimodel.get_edited():\n            r = self.doc_modified_prompt()\n            if r == QtGui.QMessageBox.Yes:\n                event.accept()\n            else:\n                event.ignore()\n        else:\n            event.accept()",
    "docstring": "Handles closing of the window. If configs were edited, ask user to continue.\n\n        :param event: the close event\n        :type event: QCloseEvent\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def _tokenize(cls, sentence):\n        while True:\n            match = cls._regex_tag.search(sentence)\n            if not match:\n                yield from cls._split(sentence)\n                return\n            chunk = sentence[:match.start()]\n            yield from cls._split(chunk)\n            tag = match.group(0)\n            yield tag\n            sentence = sentence[(len(chunk) + len(tag)):]",
    "docstring": "Split a sentence while preserving tags."
  },
  {
    "code": "def _GetFlowArgsHelpAsString(self, flow_cls):\n    output = [\n        \"  Call Spec:\",\n        \"    %s\" % self._GetCallingPrototypeAsString(flow_cls), \"\"\n    ]\n    arg_list = sorted(\n        iteritems(self._GetArgsDescription(flow_cls.args_type)),\n        key=lambda x: x[0])\n    if not arg_list:\n      output.append(\"  Args: None\")\n    else:\n      output.append(\"  Args:\")\n      for arg, val in arg_list:\n        output.append(\"    %s\" % arg)\n        output.append(\"      description: %s\" % val[\"description\"])\n        output.append(\"      type: %s\" % val[\"type\"])\n        output.append(\"      default: %s\" % val[\"default\"])\n        output.append(\"\")\n    return \"\\n\".join(output)",
    "docstring": "Get a string description of the calling prototype for this flow."
  },
  {
    "code": "def get_forced_variation(self, experiment, user_id):\n    forced_variations = experiment.forcedVariations\n    if forced_variations and user_id in forced_variations:\n      variation_key = forced_variations.get(user_id)\n      variation = self.config.get_variation_from_key(experiment.key, variation_key)\n      if variation:\n        self.logger.info('User \"%s\" is forced in variation \"%s\".' % (user_id, variation_key))\n      return variation\n    return None",
    "docstring": "Determine if a user is forced into a variation for the given experiment and return that variation.\n\n    Args:\n      experiment: Object representing the experiment for which user is to be bucketed.\n      user_id: ID for the user.\n\n    Returns:\n      Variation in which the user with ID user_id is forced into. None if no variation."
  },
  {
    "code": "def metadata(abbr, __metadata=__metadata):\n    abbr = abbr.lower()\n    if abbr in __metadata:\n        return __metadata[abbr]\n    rv = db.metadata.find_one({'_id': abbr})\n    __metadata[abbr] = rv\n    return rv",
    "docstring": "Grab the metadata for the given two-letter abbreviation."
  },
  {
    "code": "def owner(self, owner):\n        if owner is None:\n            raise ValueError(\"Invalid value for `owner`, must not be `None`\")\n        if owner is not None and len(owner) > 31:\n            raise ValueError(\"Invalid value for `owner`, length must be less than or equal to `31`\")\n        if owner is not None and len(owner) < 3:\n            raise ValueError(\"Invalid value for `owner`, length must be greater than or equal to `3`\")\n        if owner is not None and not re.search('[a-z0-9](?:-(?!-)|[a-z0-9])+[a-z0-9]', owner):\n            raise ValueError(\"Invalid value for `owner`, must be a follow pattern or equal to `/[a-z0-9](?:-(?!-)|[a-z0-9])+[a-z0-9]/`\")\n        self._owner = owner",
    "docstring": "Sets the owner of this OauthTokenReference.\n        User name of the owner of the OAuth token within data.world.\n\n        :param owner: The owner of this OauthTokenReference.\n        :type: str"
  },
  {
    "code": "def grant_bonus(self, assignment_id, amount, reason):\n        assignment = self.get_assignment(assignment_id)\n        worker_id = assignment[\"worker_id\"]\n        amount_str = \"{:.2f}\".format(amount)\n        try:\n            return self._is_ok(\n                self.mturk.send_bonus(\n                    WorkerId=worker_id,\n                    BonusAmount=amount_str,\n                    AssignmentId=assignment_id,\n                    Reason=reason,\n                    UniqueRequestToken=self._request_token(),\n                )\n            )\n        except ClientError as ex:\n            error = \"Failed to pay assignment {} bonus of {}: {}\".format(\n                assignment_id, amount_str, str(ex)\n            )\n            raise MTurkServiceException(error)",
    "docstring": "Grant a bonus to the MTurk Worker.\n        Issues a payment of money from your account to a Worker.  To\n        be eligible for a bonus, the Worker must have submitted\n        results for one of your HITs, and have had those results\n        approved or rejected. This payment happens separately from the\n        reward you pay to the Worker when you approve the Worker's\n        assignment."
  },
  {
    "code": "def is_parent_of_catalog(self, id_, catalog_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.is_parent_of_catalog(id_=id_, catalog_id=catalog_id)\n        return self._hierarchy_session.is_parent(id_=catalog_id, parent_id=id_)",
    "docstring": "Tests if an ``Id`` is a direct parent of a catalog.\n\n        arg:    id (osid.id.Id): an ``Id``\n        arg:    catalog_id (osid.id.Id): the ``Id`` of a catalog\n        return: (boolean) - ``true`` if this ``id`` is a parent of\n                ``catalog_id,``  ``false`` otherwise\n        raise:  NotFound - ``catalog_id`` is not found\n        raise:  NullArgument - ``id`` or ``catalog_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*\n        *implementation notes*: If ``id`` not found return ``false``."
  },
  {
    "code": "def filter_data(data, filter_name, filter_file, bits, filterbank_off=False,\n                    swstat_channel_name=None):\n    if filterbank_off:\n        return numpy.zeros(len(data))\n    for i in range(10):\n        filter = Filter(filter_file[filter_name][i])\n        bit = int(bits[-(i+1)])\n        if bit:\n            logging.info('filtering with filter module %d', i)\n            if len(filter.sections):\n                data = filter.apply(data)\n            else:\n                coeffs = iir2z(filter_file[filter_name][i])\n                if len(coeffs) > 1:\n                    logging.info('Gain-only filter module return more than one number')\n                    sys.exit()\n                gain = coeffs[0]\n                data = gain * data\n    return  data",
    "docstring": "A naive function to determine if the filter was on at the time\n    and then filter the data."
  },
  {
    "code": "def list_directories(dir_pathname,\n                     recursive=True,\n                     topdown=True,\n                     followlinks=False):\n    for root, dirnames, filenames\\\n    in walk(dir_pathname, recursive, topdown, followlinks):\n        for dirname in dirnames:\n            yield absolute_path(os.path.join(root, dirname))",
    "docstring": "Enlists all the directories using their absolute paths within the specified\n    directory, optionally recursively.\n\n    :param dir_pathname:\n        The directory to traverse.\n    :param recursive:\n        ``True`` for walking recursively through the directory tree;\n        ``False`` otherwise.\n    :param topdown:\n        Please see the documentation for :func:`os.walk`\n    :param followlinks:\n        Please see the documentation for :func:`os.walk`"
  },
  {
    "code": "def server_enabled(s_name, **connection_args):\n    server = _server_get(s_name, **connection_args)\n    return server is not None and server.get_state() == 'ENABLED'",
    "docstring": "Check if a server is enabled globally\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' netscaler.server_enabled 'serverName'"
  },
  {
    "code": "def EnableEditingOnService(self, url, definition = None):\n        adminFS = AdminFeatureService(url=url, securityHandler=self._securityHandler)\n        if definition is None:\n            definition = collections.OrderedDict()\n            definition['hasStaticData'] = False\n            definition['allowGeometryUpdates'] = True\n            definition['editorTrackingInfo'] = {}\n            definition['editorTrackingInfo']['enableEditorTracking'] = False\n            definition['editorTrackingInfo']['enableOwnershipAccessControl'] = False\n            definition['editorTrackingInfo']['allowOthersToUpdate'] = True\n            definition['editorTrackingInfo']['allowOthersToDelete'] = True\n            definition['capabilities'] = \"Query,Editing,Create,Update,Delete\"\n        existingDef = {}\n        existingDef['capabilities']  = adminFS.capabilities\n        existingDef['allowGeometryUpdates'] = adminFS.allowGeometryUpdates\n        enableResults = adminFS.updateDefinition(json_dict=definition)\n        if 'error' in enableResults:\n            return enableResults['error']\n        adminFS = None\n        del adminFS\n        print (enableResults)\n        return existingDef",
    "docstring": "Enables editing capabilities on a feature service.\n\n        Args:\n            url (str): The URL of the feature service.\n            definition (dict): A dictionary containing valid definition values. Defaults to ``None``.\n        Returns:\n            dict: The existing feature service definition capabilities.\n\n        When ``definition`` is not provided (``None``), the following values are used by default:\n\n        +------------------------------+------------------------------------------+\n        |              Key             |                   Value                  |\n        +------------------------------+------------------------------------------+\n        | hasStaticData                | ``False``                                |\n        +------------------------------+------------------------------------------+\n        | allowGeometryUpdates         | ``True``                                 |\n        +------------------------------+------------------------------------------+\n        | enableEditorTracking         | ``False``                                |\n        +------------------------------+------------------------------------------+\n        | enableOwnershipAccessControl | ``False``                                |\n        +------------------------------+------------------------------------------+\n        | allowOthersToUpdate          | ``True``                                 |\n        +------------------------------+------------------------------------------+\n        | allowOthersToDelete          | ``True``                                 |\n        +------------------------------+------------------------------------------+\n        | capabilities                 | ``\"Query,Editing,Create,Update,Delete\"`` |\n        +------------------------------+------------------------------------------+"
  },
  {
    "code": "def get_resource(self, resource, **kwargs):\n        return resource(request=self.request, response=self.response,\n            path_params=self.path_params, application=self.application,\n            **kwargs)",
    "docstring": "Returns a new instance of the resource class passed in as resource.\n        This is a helper to make future-compatibility easier when new\n        arguments get added to the constructor.\n\n        :param resource: Resource class to instantiate. Gets called with the\n                         named arguments as required for the constructor.\n        :type resource: :class:`Resource`\n        :param kwargs: Additional named arguments to pass to the constructor\n                       function.\n        :type kwargs: dict"
  },
  {
    "code": "def describe_alias(FunctionName, Name, region=None, key=None,\n                   keyid=None, profile=None):\n    try:\n        alias = _find_alias(FunctionName, Name,\n                            region=region, key=key, keyid=keyid, profile=profile)\n        if alias:\n            keys = ('AliasArn', 'Name', 'FunctionVersion', 'Description')\n            return {'alias': dict([(k, alias.get(k)) for k in keys])}\n        else:\n            return {'alias': None}\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Given a function name and alias name describe the properties of the alias.\n\n    Returns a dictionary of interesting properties.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_lambda.describe_alias myalias"
  },
  {
    "code": "def zero_pad(matrix, to_length):\n    assert matrix.shape[0] <= to_length\n    if not matrix.shape[0] <= to_length:\n        logger.error(\"zero_pad cannot be performed on matrix with shape {}\"\n                     \" to length {}\".format(matrix.shape[0], to_length))\n        raise ValueError\n    result = np.zeros((to_length,) + matrix.shape[1:])\n    result[:matrix.shape[0]] = matrix\n    return result",
    "docstring": "Zero pads along the 0th dimension to make sure the utterance array\n    x is of length to_length."
  },
  {
    "code": "def Parse(text):\n  precondition.AssertType(text, Text)\n  if compatibility.PY2:\n    text = text.encode(\"utf-8\")\n  return yaml.safe_load(text)",
    "docstring": "Parses a YAML source into a Python object.\n\n  Args:\n    text: A YAML source to parse.\n\n  Returns:\n    A Python data structure corresponding to the YAML source."
  },
  {
    "code": "def get_interfaces(zone, permanent=True):\n    cmd = '--zone={0} --list-interfaces'.format(zone)\n    if permanent:\n        cmd += ' --permanent'\n    return __firewall_cmd(cmd).split()",
    "docstring": "List interfaces bound to a zone\n\n    .. versionadded:: 2016.3.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' firewalld.get_interfaces zone"
  },
  {
    "code": "def Delete(self):\n\t\tdisk_set = [{'diskId': o.id, 'sizeGB': o.size} for o in self.parent.disks if o!=self]\n\t\tself.parent.disks = [o for o in self.parent.disks if o!=self]\n\t\tself.parent.server.dirty = True\n\t\treturn(clc.v2.Requests(clc.v2.API.Call('PATCH','servers/%s/%s' % (self.parent.server.alias,self.parent.server.id),\n\t\t                                       json.dumps([{\"op\": \"set\", \"member\": \"disks\", \"value\": disk_set}]),\n\t\t\t\t\t\t\t\t\t\t\t   session=self.session),\n\t\t\t\t\t\t\t   alias=self.parent.server.alias,\n\t\t\t\t\t\t\t   session=self.session))",
    "docstring": "Delete disk.\n\n\t\tThis request will error if disk is protected and cannot be removed (e.g. a system disk)\n\n\t\t>>> clc.v2.Server(\"WA1BTDIX01\").Disks().disks[2].Delete().WaitUntilComplete()\n\t\t0"
  },
  {
    "code": "def user_link_history(self, created_before=None, created_after=None,\n                          limit=100, **kwargs):\n        limit = int(limit)\n        created_after = int(created_after)\n        created_before = int(created_before)\n        hist = self.api.user_link_history(\n            limit=limit, created_before=created_before,\n            created_after=created_after)\n        record = \"{0} - {1}\"\n        links = []\n        for r in hist:\n            link = r.get('keyword_link') or r['link']\n            title = r['title'] or '<< NO TITLE >>'\n            links.append(record.format(link, title))\n        log.debug(\"First 3 Links fetched:\")\n        log.debug(pretty(hist[0:3], indent=4))\n        return links",
    "docstring": "Bit.ly API - user_link_history wrapper"
  },
  {
    "code": "def update_assume_role_policy(role_name, policy_document, region=None,\n                              key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    if isinstance(policy_document, six.string_types):\n        policy_document = salt.utils.json.loads(policy_document,\n                                     object_pairs_hook=odict.OrderedDict)\n    try:\n        _policy_document = salt.utils.json.dumps(policy_document)\n        conn.update_assume_role_policy(role_name, _policy_document)\n        log.info('Successfully updated assume role policy for IAM role %s.', role_name)\n        return True\n    except boto.exception.BotoServerError as e:\n        log.error(e)\n        log.error('Failed to update assume role policy for IAM role %s.', role_name)\n        return False",
    "docstring": "Update an assume role policy for a role.\n\n    .. versionadded:: 2015.8.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_iam.update_assume_role_policy myrole '{\"Statement\":\"...\"}'"
  },
  {
    "code": "def system_status(self):\n        flag, timestamp, status = self._query(('GETDAT? 1', (Integer, Float, Integer)))\n        return {\n            'timestamp': datetime.datetime.fromtimestamp(timestamp),\n            'temperature': STATUS_TEMPERATURE[status & 0xf],\n            'magnet': STATUS_MAGNET[(status >> 4) & 0xf],\n            'chamber': STATUS_CHAMBER[(status >> 8) & 0xf],\n            'sample_position': STATUS_SAMPLE_POSITION[(status >> 12) & 0xf],\n        }",
    "docstring": "The system status codes."
  },
  {
    "code": "def is_float_like(value):\n    try:\n        if isinstance(value, float): return True\n        return float(value) == value and not str(value).isdigit()\n    except:\n        return False",
    "docstring": "Returns whether the value acts like a standard float.\n\n        >>> is_float_like(4.0)\n        True\n        >>> is_float_like(numpy.float32(4.0))\n        True\n        >>> is_float_like(numpy.int32(4.0))\n        False\n        >>> is_float_like(4)\n        False"
  },
  {
    "code": "def _validator(key, val, env):\n    if not env[key] in (True, False):\n        raise SCons.Errors.UserError(\n            'Invalid value for boolean option %s: %s' % (key, env[key]))",
    "docstring": "Validates the given value to be either '0' or '1'.\n    \n    This is usable as 'validator' for SCons' Variables."
  },
  {
    "code": "def conv_layer(x,\n               hidden_size,\n               kernel_size,\n               stride,\n               pooling_window,\n               dropout_rate,\n               dilation_rate,\n               name=\"conv\"):\n  with tf.variable_scope(name):\n    out = x\n    out = common_layers.conv1d_block(\n        out,\n        hidden_size, [(dilation_rate, kernel_size)],\n        strides=stride,\n        first_relu=False,\n        padding=\"same\")\n    out = tf.nn.relu(out)\n    if pooling_window:\n      out = tf.layers.max_pooling1d(\n          out, pooling_window, pooling_window, padding=\"same\")\n    out = tf.layers.dropout(out, dropout_rate)\n    return out",
    "docstring": "Single conv layer with relu, optional pooling, and dropout."
  },
  {
    "code": "def _is_subspan(self, m, span):\n        return (\n            m.sentence.id == span[0]\n            and m.char_start >= span[1]\n            and m.char_end <= span[2]\n        )",
    "docstring": "Tests if mention m is subspan of span, where span is defined\n        specific to mention type."
  },
  {
    "code": "def print_table(lines, separate_head=True):\n\twidths = []\n\tfor line in lines:\n\t\t\tfor i,size in enumerate([len(x) for x in line]):\n\t\t\t\t\twhile i >= len(widths):\n\t\t\t\t\t\t\twidths.append(0)\n\t\t\t\t\tif size > widths[i]:\n\t\t\t\t\t\t\twidths[i] = size\n\tprint_string = \"\"\n\tfor i,width in enumerate(widths):\n\t\t\tprint_string += \"{\" + str(i) + \":\" + str(width) + \"} | \"\n\tif (len(print_string) == 0):\n\t\t\treturn\n\tprint_string = print_string[:-3]\n\tfor i,line in enumerate(lines):\n\t\t\tprint(print_string.format(*line))\n\t\t\tif (i == 0 and separate_head):\n\t\t\t\t\tprint(\"-\"*(sum(widths)+3*(len(widths)-1)))",
    "docstring": "Prints a formatted table given a 2 dimensional array"
  },
  {
    "code": "def _createGsshaPyObjects(self, cell):\n        gridCell = GridStreamCell(cellI=cell['i'],\n                                  cellJ=cell['j'],\n                                  numNodes=cell['numNodes'])\n        gridCell.gridStreamFile = self\n        for linkNode in cell['linkNodes']:\n            gridNode = GridStreamNode(linkNumber=linkNode['linkNumber'],\n                                      nodeNumber=linkNode['nodeNumber'],\n                                      nodePercentGrid=linkNode['percent'])\n            gridNode.gridStreamCell = gridCell",
    "docstring": "Create GSSHAPY PipeGridCell and PipeGridNode Objects Method"
  },
  {
    "code": "def fetch(args: List[str], env: Dict[str, str] = None,\n          encoding: str = sys.getdefaultencoding()) -> str:\n    stdout, _ = run(args, env=env, capture_stdout=True,\n                    echo_stdout=False, encoding=encoding)\n    log.debug(stdout)\n    return stdout",
    "docstring": "Run a command and returns its stdout.\n\n    Args:\n        args: the command-line arguments\n        env: the operating system environment to use\n        encoding: the encoding to use for ``stdout``\n\n    Returns:\n        the command's ``stdout`` output"
  },
  {
    "code": "def check_no_element_by_selector(self, selector):\n    elems = find_elements_by_jquery(world.browser, selector)\n    if elems:\n        raise AssertionError(\"Expected no matching elements, found {}.\".format(\n            len(elems)))",
    "docstring": "Assert an element does not exist matching the given selector."
  },
  {
    "code": "def type(self):\n        properties = {self.is_code: \"code\",\n                      self.is_data: \"data\",\n                      self.is_string: \"string\",\n                      self.is_tail: \"tail\",\n                      self.is_unknown: \"unknown\"}\n        for k, v in properties.items():\n            if k: return v",
    "docstring": "return the type of the Line"
  },
  {
    "code": "def getExistingFile(name, max_suffix=1000):\n    num = 1\n    stem, ext = os.path.splitext(name)\n    filename = name\n    while not os.path.exists(filename):\n        suffix = \"-%d\" % num\n        filename = stem + suffix + ext\n        num += 1\n        if num >= max_suffix:\n            raise ValueError(\"No file %r found\" % name)\n    return filename",
    "docstring": "Add filename suffix until file exists\n    @return: filename if file is found\n    @raise: ValueError if maximum suffix number is reached while searching"
  },
  {
    "code": "def __version_capture_slp(self, pkg_id, version_binary, version_display, display_name):\n        if self.__pkg_obj and hasattr(self.__pkg_obj, 'version_capture'):\n            version_str, src, version_user_str = \\\n                self.__pkg_obj.version_capture(pkg_id, version_binary, version_display, display_name)\n            if src != 'use-default' and version_str and src:\n                return version_str, src, version_user_str\n            elif src != 'use-default':\n                raise ValueError(\n                    'version capture within object \\'{0}\\' failed '\n                    'for pkg id: \\'{1}\\' it returned \\'{2}\\' \\'{3}\\' '\n                    '\\'{4}\\''.format(six.text_type(self.__pkg_obj), pkg_id, version_str, src, version_user_str)\n                    )\n        if version_display and re.match(r'\\d+', version_display, flags=re.IGNORECASE + re.UNICODE) is not None:\n            version_str = version_display\n            src = 'display-version'\n        elif version_binary and re.match(r'\\d+', version_binary, flags=re.IGNORECASE + re.UNICODE) is not None:\n            version_str = version_binary\n            src = 'version-binary'\n        else:\n            src = 'none'\n            version_str = '0.0.0.0.0'\n        return version_str, src, version_str",
    "docstring": "This returns the version and where the version string came from, based on instructions\n        under ``version_capture``, if ``version_capture`` is missing, it defaults to\n        value of display-version.\n\n        Args:\n            pkg_id (str): Publisher of the software/component.\n            version_binary (str): Name of the software.\n            version_display (str): True if package is a component.\n            display_name (str): True if the software/component is 32bit architecture.\n\n        Returns:\n            str: Package Id"
  },
  {
    "code": "def log(self, level, *msg_elements):\n    self.report.log(self._threadlocal.current_workunit, level, *msg_elements)",
    "docstring": "Log a message against the current workunit."
  },
  {
    "code": "def call_later(fn, args=(), delay=0.001):\n    thread = _Thread(target=lambda: (_time.sleep(delay), fn(*args)))\n    thread.start()",
    "docstring": "Calls the provided function in a new thread after waiting some time.\n    Useful for giving the system some time to process an event, without blocking\n    the current execution flow."
  },
  {
    "code": "def overall():\n        return ZeroOrMore(Grammar.comment) + Dict(ZeroOrMore(Group(\n            Grammar._section + ZeroOrMore(Group(Grammar.line)))\n            ))",
    "docstring": "The overall grammer for pulling apart the main input files."
  },
  {
    "code": "def _add_slide_footer(self, slide_no):\n        if self.builder.config.slide_footer:\n            self.body.append(\n                '\\n<div class=\"slide-footer\">%s</div>\\n' % (\n                    self.builder.config.slide_footer,\n                ),\n            )",
    "docstring": "Add the slide footer to the output if enabled."
  },
  {
    "code": "def createTable(dbconn, pd):\n    cols = ('%s %s' % (defn.name, getTypename(defn)) for defn in pd.fields)\n    sql  = 'CREATE TABLE IF NOT EXISTS %s (%s)' % (pd.name, ', '.join(cols))\n    dbconn.execute(sql)\n    dbconn.commit()",
    "docstring": "Creates a database table for the given PacketDefinition."
  },
  {
    "code": "def run(argv=None):\n    cli = InfrascopeCLI()\n    return cli.run(sys.argv[1:] if argv is None else argv)",
    "docstring": "Main CLI entry point."
  },
  {
    "code": "def train_epoch(self, epoch_info, source: 'vel.api.Source', interactive=True):\n        self.train()\n        if interactive:\n            iterator = tqdm.tqdm(source.train_loader(), desc=\"Training\", unit=\"iter\", file=sys.stdout)\n        else:\n            iterator = source.train_loader()\n        for batch_idx, (data, target) in enumerate(iterator):\n            batch_info = BatchInfo(epoch_info, batch_idx)\n            batch_info.on_batch_begin()\n            self.train_batch(batch_info, data, target)\n            batch_info.on_batch_end()\n            iterator.set_postfix(loss=epoch_info.result_accumulator.intermediate_value('loss'))",
    "docstring": "Run a single training epoch"
  },
  {
    "code": "def load_tabs(self):\n        tab_group = self.get_tabs(self.request, **self.kwargs)\n        tabs = tab_group.get_tabs()\n        for tab in [t for t in tabs if issubclass(t.__class__, TableTab)]:\n            self.table_classes.extend(tab.table_classes)\n            for table in tab._tables.values():\n                self._table_dict[table._meta.name] = {'table': table,\n                                                      'tab': tab}",
    "docstring": "Loads the tab group.\n\n        It compiles the table instances for each table attached to\n        any :class:`horizon.tabs.TableTab` instances on the tab group.\n        This step is necessary before processing any tab or table actions."
  },
  {
    "code": "def _to_full_dict(xmltree):\n    xmldict = {}\n    for attrName, attrValue in xmltree.attrib.items():\n        xmldict[attrName] = attrValue\n    if not xmltree.getchildren():\n        if not xmldict:\n            return xmltree.text\n        elif xmltree.text:\n            xmldict[_conv_name(xmltree.tag)] = xmltree.text\n    for item in xmltree:\n        name = _conv_name(item.tag)\n        if name not in xmldict:\n            xmldict[name] = _to_full_dict(item)\n        else:\n            if not isinstance(xmldict[name], list):\n                xmldict[name] = [xmldict[name]]\n            xmldict[name].append(_to_full_dict(item))\n    return xmldict",
    "docstring": "Returns the full XML dictionary including attributes."
  },
  {
    "code": "def is_namespace_preordered( self, namespace_id_hash ):\n        namespace_preorder = self.get_namespace_preorder(namespace_id_hash)\n        if namespace_preorder is None:\n            return False \n        else:\n            return True",
    "docstring": "Given a namespace preorder hash, determine if it is preordered\n        at the current block."
  },
  {
    "code": "def color_pack2rgb(packed):\n    r = packed & 255\n    g = (packed & (255 << 8)) >> 8\n    b = (packed & (255 << 16)) >> 16\n    return r, g, b",
    "docstring": "Returns r, g, b tuple from packed wx.ColourGetRGB value"
  },
  {
    "code": "def spread(iterable):\n    if len(iterable) == 1:\n        return 0\n    iterable = iterable.copy()\n    iterable.sort()\n    max_diff = max(abs(i - j) for (i, j) in zip(iterable[1:], iterable[:-1]))\n    return max_diff",
    "docstring": "Returns the maximal spread of a sorted list of numbers.\n\n    Parameters\n    ----------\n    iterable\n        A list of numbers.\n\n    Returns\n    -------\n    max_diff\n        The maximal difference when the iterable is sorted.\n\n\n    Examples\n    -------\n    >>> spread([1, 11, 13, 15])\n    10\n    \n    >>> spread([1, 15, 11, 13])\n    10"
  },
  {
    "code": "def objects_to_record(self, preference=None):\n        from ambry.orm.file import File\n        raise NotImplementedError(\"Still uses obsolete file_info_map\")\n        for file_const, (file_name, clz) in iteritems(file_info_map):\n            f = self.file(file_const)\n            pref = preference if preference else f.record.preference\n            if pref in (File.PREFERENCE.MERGE, File.PREFERENCE.OBJECT):\n                self._bundle.logger.debug('   otr {}'.format(file_const))\n                f.objects_to_record()",
    "docstring": "Create file records from objects."
  },
  {
    "code": "def clear(self):\r\n        for item in self.traverseItems():\r\n            if isinstance(item, XTreeWidgetItem):\r\n                item.destroy()\r\n        super(XTreeWidget, self).clear()",
    "docstring": "Removes all the items from this tree widget.  This will go through\r\n        and also destroy any XTreeWidgetItems prior to the model clearing\r\n        its references."
  },
  {
    "code": "def _weight_opacity(weight, weight_range):\n    min_opacity = 0.8\n    if np.isclose(weight, 0) and np.isclose(weight_range, 0):\n        rel_weight = 0.0\n    else:\n        rel_weight = abs(weight) / weight_range\n    return '{:.2f}'.format(min_opacity + (1 - min_opacity) * rel_weight)",
    "docstring": "Return opacity value for given weight as a string."
  },
  {
    "code": "def generate_order_template(self, quote_id, extra, quantity=1):\n        if not isinstance(extra, dict):\n            raise ValueError(\"extra is not formatted properly\")\n        container = self.get_order_container(quote_id)\n        container['quantity'] = quantity\n        for key in extra.keys():\n            container[key] = extra[key]\n        return container",
    "docstring": "Generate a complete order template.\n\n        :param int quote_id: ID of target quote\n        :param dictionary extra: Overrides for the defaults of SoftLayer_Container_Product_Order\n        :param int quantity: Number of items to order."
  },
  {
    "code": "def directionaldiff(f, x0, vec, **options):\n    x0 = np.asarray(x0)\n    vec = np.asarray(vec)\n    if x0.size != vec.size:\n        raise ValueError('vec and x0 must be the same shapes')\n    vec = np.reshape(vec/np.linalg.norm(vec.ravel()), x0.shape)\n    return Derivative(lambda t: f(x0+t*vec), **options)(0)",
    "docstring": "Return directional derivative of a function of n variables\n\n    Parameters\n    ----------\n    fun: callable\n        analytical function to differentiate.\n    x0: array\n        vector location at which to differentiate fun. If x0 is an nxm array,\n        then fun is assumed to be a function of n*m variables.\n    vec: array\n        vector defining the line along which to take the derivative. It should\n        be the same size as x0, but need not be a vector of unit length.\n    **options:\n        optional arguments to pass on to Derivative.\n\n    Returns\n    -------\n    dder:  scalar\n        estimate of the first derivative of fun in the specified direction.\n\n    Examples\n    --------\n    At the global minimizer (1,1) of the Rosenbrock function,\n    compute the directional derivative in the direction [1 2]\n\n    >>> import numpy as np\n    >>> import numdifftools as nd\n    >>> vec = np.r_[1, 2]\n    >>> rosen = lambda x: (1-x[0])**2 + 105*(x[1]-x[0]**2)**2\n    >>> dd, info = nd.directionaldiff(rosen, [1, 1], vec, full_output=True)\n    >>> np.allclose(dd, 0)\n    True\n    >>> np.abs(info.error_estimate)<1e-14\n    True\n\n    See also\n    --------\n    Derivative,\n    Gradient"
  },
  {
    "code": "def has_permission(self, request):\n        if not self.object and not self.permission:\n            return True\n        if not self.permission:\n            return request.user.has_perm('{}_{}'.format(\n                self.model_permission,\n                self.object.__class__.__name__.lower()), self.object\n            )\n        return request.user.has_perm(self.permission)",
    "docstring": "Check if user has permission"
  },
  {
    "code": "def bacpypes_debugging(obj):\n    logger = logging.getLogger(obj.__module__ + '.' + obj.__name__)\n    obj._logger = logger\n    obj._debug = logger.debug\n    obj._info = logger.info\n    obj._warning = logger.warning\n    obj._error = logger.error\n    obj._exception = logger.exception\n    obj._fatal = logger.fatal\n    return obj",
    "docstring": "Function for attaching a debugging logger to a class or function."
  },
  {
    "code": "def handle_starttag(self, tag, attrs):\n        if not tag == 'a':\n            return\n        for attr in attrs:\n            if attr[0] == 'href':\n                url = urllib.unquote(attr[1])\n                self.active_url = url.rstrip('/').split('/')[-1]\n                return",
    "docstring": "Callback for when a tag gets opened."
  },
  {
    "code": "def set_dimmer(self, dimmer, transition_time=None):\n        values = {\n            ATTR_LIGHT_DIMMER: dimmer,\n        }\n        if transition_time is not None:\n            values[ATTR_TRANSITION_TIME] = transition_time\n        return self.set_values(values)",
    "docstring": "Set dimmer value of a group.\n\n        dimmer: Integer between 0..255\n        transition_time: Integer representing tenth of a second (default None)"
  },
  {
    "code": "def plotants(vis, figfile):\n    from .scripting import CasapyScript\n    script = os.path.join(os.path.dirname(__file__), 'cscript_plotants.py')\n    with CasapyScript(script, vis=vis, figfile=figfile) as cs:\n        pass",
    "docstring": "Plot the physical layout of the antennas described in the MS.\n\n    vis (str)\n      Path to the input dataset\n    figfile (str)\n      Path to the output image file.\n\n    The output image format will be inferred from the extension of *figfile*.\n    Example::\n\n      from pwkit.environments.casa import tasks\n      tasks.plotants('dataset.ms', 'antennas.png')"
  },
  {
    "code": "def getKey(self, key):\n\t\tdata = self.getDictionary()\n\t\tif key in data:\n\t\t\treturn data[key]\n\t\telse:\n\t\t\treturn None",
    "docstring": "Retrieves the value for the specified dictionary key"
  },
  {
    "code": "def _update_shared_response(X, S, W, features):\n        subjs = len(X)\n        TRs = X[0].shape[1]\n        R = np.zeros((features, TRs))\n        for i in range(subjs):\n            R += W[i].T.dot(X[i]-S[i])\n        R /= subjs\n        return R",
    "docstring": "Update the shared response `R`.\n\n        Parameters\n        ----------\n\n        X : list of 2D arrays, element i has shape=[voxels_i, timepoints]\n            Each element in the list contains the fMRI data for alignment of\n            one subject.\n\n        S : list of array, element i has shape=[voxels_i, timepoints]\n            The individual component :math:`S_i` for each subject.\n\n        W : list of array, element i has shape=[voxels_i, features]\n            The orthogonal transforms (mappings) :math:`W_i` for each subject.\n\n        features : int\n            The number of features in the model.\n\n        Returns\n        -------\n\n        R : array, shape=[features, timepoints]\n            The updated shared response."
  },
  {
    "code": "def detect_config(self):\n        default_files = (\"config.json\", \"config.yml\")\n        for file_ in default_files:\n            if os.path.exists(file_):\n                return file_",
    "docstring": "check in the current working directory for configuration files"
  },
  {
    "code": "def GetUcsPropertyMetaAttributeList(classId):\n\t\tif classId in _ManagedObjectMeta:\n\t\t\tattrList = _ManagedObjectMeta[classId].keys()\n\t\t\tattrList.remove(\"Meta\")\n\t\t\treturn attrList\n\t\tif classId in _MethodFactoryMeta:\n\t\t\tattrList = _MethodFactoryMeta[classId].keys()\n\t\t\tattrList.remove(\"Meta\")\n\t\t\treturn attrList\n\t\tnci = UcsUtils.FindClassIdInMoMetaIgnoreCase(classId)\n\t\tif (nci != None):\n\t\t\tattrList = _ManagedObjectMeta[nci].keys()\n\t\t\tattrList.remove(\"Meta\")\n\t\t\treturn attrList\n\t\tnci = UcsUtils.FindClassIdInMethodMetaIgnoreCase(classId)\n\t\tif (nci != None):\n\t\t\tattrList = _MethodFactoryMeta[nci].keys()\n\t\t\tattrList.remove(\"Meta\")\n\t\t\treturn attrList\n\t\treturn None",
    "docstring": "Methods returns the class meta."
  },
  {
    "code": "def _getStore(self):\n        storeDir = self.store.newDirectory(self.indexDirectory)\n        if not storeDir.exists():\n            store = Store(storeDir)\n            self._initStore(store)\n            return store\n        else:\n            return Store(storeDir)",
    "docstring": "Get the Store used for FTS.\n\n        If it does not exist, it is created and initialised."
  },
  {
    "code": "def instruction_ADD8(self, opcode, m, register):\n        assert register.WIDTH == 8\n        old = register.value\n        r = old + m\n        register.set(r)\n        self.clear_HNZVC()\n        self.update_HNZVC_8(old, m, r)",
    "docstring": "Adds the memory byte into an 8-bit accumulator.\n\n        source code forms: ADDA P; ADDB P\n\n        CC bits \"HNZVC\": aaaaa"
  },
  {
    "code": "def create_html_from_fragment(tag):\n    try:\n        assert isinstance(tag, bs4.element.Tag)\n    except AssertionError:\n        raise TypeError\n    try:\n        assert tag.find_all('body') == []\n    except AssertionError:\n        raise ValueError\n    soup = BeautifulSoup('<html><head></head><body></body></html>', 'html.parser')\n    soup.body.append(tag)\n    return soup",
    "docstring": "Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not\n\n    Args:\n        tag: a bs4.element.Tag\n\n    Returns:\"\n        bs4.element.Tag: A bs4 tag representing a full html document"
  },
  {
    "code": "def _handle_component(sourcekey, comp_dict):\n        if comp_dict.comp_key is None:\n            fullkey = sourcekey\n        else:\n            fullkey = \"%s_%s\" % (sourcekey, comp_dict.comp_key)\n        srcdict = make_sources(fullkey, comp_dict)\n        if comp_dict.model_type == 'IsoSource':\n            print(\"Writing xml for %s to %s: %s %s\" % (fullkey,\n                                                       comp_dict.srcmdl_name,\n                                                       comp_dict.model_type,\n                                                       comp_dict.Spectral_Filename))\n        elif comp_dict.model_type == 'MapCubeSource':\n            print(\"Writing xml for %s to %s: %s %s\" % (fullkey,\n                                                       comp_dict.srcmdl_name,\n                                                       comp_dict.model_type,\n                                                       comp_dict.Spatial_Filename))\n        SrcmapsDiffuse_SG._write_xml(comp_dict.srcmdl_name, srcdict.values())",
    "docstring": "Make the source objects and write the xml for a component"
  },
  {
    "code": "def entry_archive_year_url():\n    entry = Entry.objects.filter(published=True).latest()\n    arg_list = [entry.published_on.strftime(\"%Y\")]\n    return reverse('blargg:entry_archive_year', args=arg_list)",
    "docstring": "Renders the ``entry_archive_year`` URL for the latest ``Entry``."
  },
  {
    "code": "def id_source(source, full=False):\n    if source not in source_ids:\n        return ''\n    if full:\n        return source_ids[source][1]\n    else:\n        return source_ids[source][0]",
    "docstring": "Returns the name of a website-scrapping function."
  },
  {
    "code": "def init_running_properties(self):\n        for prop, entry in list(self.__class__.running_properties.items()):\n            val = entry.default\n            setattr(self, prop, copy(val) if isinstance(val, (set, list, dict)) else val)",
    "docstring": "Initialize the running_properties.\n        Each instance have own property.\n\n        :return: None"
  },
  {
    "code": "def _scope_lookup(self, node, name, offset=0):\n        try:\n            stmts = node._filter_stmts(self.locals[name], self, offset)\n        except KeyError:\n            stmts = ()\n        if stmts:\n            return self, stmts\n        if self.parent:\n            pscope = self.parent.scope()\n            if not pscope.is_function:\n                pscope = pscope.root()\n            return pscope.scope_lookup(node, name)\n        return builtin_lookup(name)",
    "docstring": "XXX method for interfacing the scope lookup"
  },
  {
    "code": "def merge_configurations(configurations):\n    configuration = {}\n    for c in configurations:\n        for k, v in c.iteritems():\n            if k in configuration:\n                raise ValueError('%s already in a previous base configuration' % k)\n            configuration[k] = v\n    return configuration",
    "docstring": "Merge configurations together and raise error if a conflict is detected\n\n    :param configurations: configurations to merge together\n    :type configurations: list of :attr:`~pyextdirect.configuration.Base.configuration` dicts\n    :return: merged configurations as a single one\n    :rtype: dict"
  },
  {
    "code": "def find_parents(self):\n        for i in range(len(self.vertices)):\n            self.vertices[i].parents = []\n        for i in range(len(self.vertices)):\n            for child in self.vertices[i].children:\n                if i not in self.vertices[child].parents:\n                    self.vertices[child].parents.append(i)",
    "docstring": "Take a tree and set the parents according to the children\n\n        Takes a tree structure which lists the children of each vertex\n        and computes the parents for each vertex and places them in."
  },
  {
    "code": "def all(self):\n    \" execute query, get all list of lists\"\n    query,inputs = self._toedn()\n    return self.db.q(query,\n      inputs  = inputs,\n      limit   = self._limit,\n      offset  = self._offset,\n      history = self._history)",
    "docstring": "execute query, get all list of lists"
  },
  {
    "code": "def dirs(self, paths, access=None):\n        self.failures = [path for path in paths if not\n                         isvalid(path, access, filetype='dir')]\n        return not self.failures",
    "docstring": "Verify list of directories"
  },
  {
    "code": "def patch_python_logging_handlers():\n    logging.StreamHandler = StreamHandler\n    logging.FileHandler = FileHandler\n    logging.handlers.SysLogHandler = SysLogHandler\n    logging.handlers.WatchedFileHandler = WatchedFileHandler\n    logging.handlers.RotatingFileHandler = RotatingFileHandler\n    if sys.version_info >= (3, 2):\n        logging.handlers.QueueHandler = QueueHandler",
    "docstring": "Patch the python logging handlers with out mixed-in classes"
  },
  {
    "code": "def create_source(\n        self,\n        parent,\n        source,\n        retry=google.api_core.gapic_v1.method.DEFAULT,\n        timeout=google.api_core.gapic_v1.method.DEFAULT,\n        metadata=None,\n    ):\n        if \"create_source\" not in self._inner_api_calls:\n            self._inner_api_calls[\n                \"create_source\"\n            ] = google.api_core.gapic_v1.method.wrap_method(\n                self.transport.create_source,\n                default_retry=self._method_configs[\"CreateSource\"].retry,\n                default_timeout=self._method_configs[\"CreateSource\"].timeout,\n                client_info=self._client_info,\n            )\n        request = securitycenter_service_pb2.CreateSourceRequest(\n            parent=parent, source=source\n        )\n        if metadata is None:\n            metadata = []\n        metadata = list(metadata)\n        try:\n            routing_header = [(\"parent\", parent)]\n        except AttributeError:\n            pass\n        else:\n            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(\n                routing_header\n            )\n            metadata.append(routing_metadata)\n        return self._inner_api_calls[\"create_source\"](\n            request, retry=retry, timeout=timeout, metadata=metadata\n        )",
    "docstring": "Creates a source.\n\n        Example:\n            >>> from google.cloud import securitycenter_v1\n            >>>\n            >>> client = securitycenter_v1.SecurityCenterClient()\n            >>>\n            >>> parent = client.organization_path('[ORGANIZATION]')\n            >>>\n            >>> # TODO: Initialize `source`:\n            >>> source = {}\n            >>>\n            >>> response = client.create_source(parent, source)\n\n        Args:\n            parent (str): Resource name of the new source's parent. Its format should be\n                \"organizations/[organization\\_id]\".\n            source (Union[dict, ~google.cloud.securitycenter_v1.types.Source]): The Source being created, only the display\\_name and description will be\n                used. All other fields will be ignored.\n\n                If a dict is provided, it must be of the same form as the protobuf\n                message :class:`~google.cloud.securitycenter_v1.types.Source`\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.securitycenter_v1.types.Source` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def Softmax(a):\n    e = np.exp(a)\n    return np.divide(e, np.sum(e, axis=-1, keepdims=True)),",
    "docstring": "Softmax op."
  },
  {
    "code": "def _sigma_inel(self, Tp):\n        L = np.log(Tp / self._Tth)\n        sigma = 30.7 - 0.96 * L + 0.18 * L ** 2\n        sigma *= (1 - (self._Tth / Tp) ** 1.9) ** 3\n        return sigma * 1e-27",
    "docstring": "Inelastic cross-section for p-p interaction. KATV14 Eq. 1\n\n        Parameters\n        ----------\n        Tp : float\n            Kinetic energy of proton (i.e. Ep - m_p*c**2) [GeV]\n\n        Returns\n        -------\n        sigma_inel : float\n            Inelastic cross-section for p-p interaction [1/cm2]."
  },
  {
    "code": "def _export_graph(self):\n        for brain_name in self.trainers.keys():\n            self.trainers[brain_name].export_model()",
    "docstring": "Exports latest saved models to .nn format for Unity embedding."
  },
  {
    "code": "def generate_signature_class(cls):\n    return type(\"%sSigs\" % cls.__name__, (Base,),\n                {'__tablename__': \"%s_sigs\" % cls.__tablename__,\n                 'id': sa.Column(sa.Integer,\n                                 sa.Sequence('%s_id_seq' % cls.__tablename__),\n                                 primary_key=True,\n                                 doc=\"primary key\"),\n                 'data': sa.Column(sa.Text(), nullable=False,\n                                   doc=\"The signed data\"),\n                 '%s_id' % cls.__tablename__: sa.Column(sa.Integer,\n                                                        sa.ForeignKey(\"%s.id\" % cls.__tablename__),\n                                                        nullable=False)})",
    "docstring": "Generate a declarative model for storing signatures related to the given\n    cls parameter.\n\n    :param class cls: The declarative model to generate a signature class for.\n    :return: The signature class, as a declarative derived from Base."
  },
  {
    "code": "def disable(self):\n        self.ticker_text_label.hide()\n        if self.current_observed_sm_m:\n            self.stop_sm_m_observation(self.current_observed_sm_m)",
    "docstring": "Relieve all state machines that have no active execution and hide the widget"
  },
  {
    "code": "def inventory(uri, format):\n    base_uri = dtoolcore.utils.sanitise_uri(uri)\n    info = _base_uri_info(base_uri)\n    if format is None:\n        _cmd_line_report(info)\n    elif format == \"csv\":\n        _csv_tsv_report(info, \",\")\n    elif format == \"tsv\":\n        _csv_tsv_report(info, \"\\t\")\n    elif format == \"html\":\n        _html_report(info)",
    "docstring": "Generate an inventory of datasets in a base URI."
  },
  {
    "code": "def dispose_qualification_type(self, qualification_id):\n        return self._is_ok(\n            self.mturk.delete_qualification_type(QualificationTypeId=qualification_id)\n        )",
    "docstring": "Remove a qualification type we created"
  },
  {
    "code": "def from_dict(self, document):\n        identifier = str(document['_id'])\n        active = document['active']\n        directory = os.path.join(self.directory, identifier)\n        timestamp = datetime.datetime.strptime(document['timestamp'], '%Y-%m-%dT%H:%M:%S.%f')\n        properties = document['properties']\n        return FunctionalDataHandle(identifier, properties, directory, timestamp=timestamp, is_active=active)",
    "docstring": "Create functional data object from JSON document retrieved from\n        database.\n\n        Parameters\n        ----------\n        document : JSON\n            Json document in database\n\n        Returns\n        -------\n        FunctionalDataHandle\n            Handle for functional data object"
  },
  {
    "code": "def max_ver(ver1, ver2):\n    cmp_res = compare(ver1, ver2)\n    if cmp_res == 0 or cmp_res == 1:\n        return ver1\n    else:\n        return ver2",
    "docstring": "Returns the greater version of two versions\n\n    :param ver1: version string 1\n    :param ver2: version string 2\n    :return: the greater version of the two\n    :rtype: :class:`VersionInfo`\n\n    >>> import semver\n    >>> semver.max_ver(\"1.0.0\", \"2.0.0\")\n    '2.0.0'"
  },
  {
    "code": "def get_rotated(self, angle):\n        ca = math.cos(angle)\n        sa = math.sin(angle)\n        return Point(self.x*ca-self.y*sa, self.x*sa+self.y*ca)",
    "docstring": "Rotates this vector through the given anti-clockwise angle\n        in radians."
  },
  {
    "code": "def _getDetails(self, uriRef, associations_details):\n        associationDetail = {}\n        for detail in associations_details:\n            if detail['subject'] == uriRef:\n                associationDetail[detail['predicate']] = detail['object']\n            associationDetail['id'] = uriRef\n        return associationDetail",
    "docstring": "Given a uriRef, return a dict of all the details for that Ref\n        use the uriRef as the 'id' of the dict"
  },
  {
    "code": "def reload(self):\n        self.buf = self.fetch(buf = self.buf)\n        return self",
    "docstring": "This object will read header when it is constructed, which means it\n        might be out-of-date if the file is updated through some other handle.\n\n        It's rarely required to call this method, and it's a symptom of fragile\n        code. However, if you have multiple handles to the same header, it\n        might be necessary. Consider the following example::\n\n            >>> x = f.header[10]\n            >>> y = f.header[10]\n            >>> x[1, 5]\n            { 1: 5, 5: 10 }\n            >>> y[1, 5]\n            { 1: 5, 5: 10 }\n            >>> x[1] = 6\n            >>> x[1], y[1] # write to x[1] is invisible to y\n            6, 5\n            >>> y.reload()\n            >>> x[1], y[1]\n            6, 6\n            >>> x[1] = 5\n            >>> x[1], y[1]\n            5, 6\n            >>> y[5] = 1\n            >>> x.reload()\n            >>> x[1], y[1, 5] # the write to x[1] is lost\n            6, { 1: 6; 5: 1 }\n\n        In segyio, headers writes are atomic, and the write to disk writes the\n        full cache. If this cache is out of date, some writes might get lost,\n        even though the updates are compatible.\n\n        The fix to this issue is either to use ``reload`` and maintain buffer\n        consistency, or simply don't let header handles alias and overlap in\n        lifetime.\n\n        Notes\n        -----\n        .. versionadded:: 1.6"
  },
  {
    "code": "def prepare_model_data(self, packages, linked, pip=None,\n                           private_packages=None):\n        logger.debug('')\n        return self._prepare_model_data(packages, linked, pip=pip,\n                                        private_packages=private_packages)",
    "docstring": "Prepare downloaded package info along with pip pacakges info."
  },
  {
    "code": "def cutoff(s, length=120):\n    if length < 5:\n        raise ValueError('length must be >= 5')\n    if len(s) <= length:\n        return s\n    else:\n        i = (length - 2) / 2\n        j = (length - 3) / 2\n        return s[:i] + '...' + s[-j:]",
    "docstring": "Cuts a given string if it is longer than a given length."
  },
  {
    "code": "def get_output(src):\n    output = ''\n    lines = open(src.path, 'rU').readlines()\n    for line in lines:\n        m = re.match(config.import_regex,line)\n        if m:\n            include_path = os.path.abspath(src.dir + '/' + m.group('script'));\n            if include_path not in config.sources:\n                script = Script(include_path)\n                script.parents.append(src)\n                config.sources[script.path] = script\n            include_file = config.sources[include_path]\n            if include_file not in config.stack or m.group('command') == 'import':\n                config.stack.append(include_file)\n                output += get_output(include_file)\n        else:\n            output += line\n    return output",
    "docstring": "parse lines looking for commands"
  },
  {
    "code": "def items_at(self, depth):\n        if depth < 1:\n            yield ROOT, self\n        elif depth == 1:\n            for key, value in self.items():\n                yield key, value\n        else:\n            for dict_tree in self.values():\n                for key, value in dict_tree.items_at(depth - 1):\n                    yield key, value",
    "docstring": "Iterate items at specified depth."
  },
  {
    "code": "def to_dict(self):\n        return {\n            'body': self._body,\n            'method': self._method,\n            'properties': self._properties,\n            'channel': self._channel\n        }",
    "docstring": "Message to Dictionary.\n\n        :rtype: dict"
  },
  {
    "code": "def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False):\n        for segment in self.segments:\n            segment.simplify(eps, max_dist_error, max_speed_error, topology_only)\n        return self",
    "docstring": "In-place simplification of segments\n\n        Args:\n            max_dist_error (float): Min distance error, in meters\n            max_speed_error (float): Min speed error, in km/h\n            topology_only: Boolean, optional. True to keep\n                the topology, neglecting velocity and time\n                accuracy (use common Douglas-Ramen-Peucker).\n                False (default) to simplify segments keeping\n                the velocity between points.\n        Returns:\n            This track"
  },
  {
    "code": "def align_options(options):\n    l = 0\n    for opt in options:\n        if len(opt[0]) > l:\n            l = len(opt[0])\n    s = []\n    for opt in options:\n        s.append('  {0}{1}  {2}'.format(opt[0], ' ' * (l - len(opt[0])), opt[1]))\n    return '\\n'.join(s)",
    "docstring": "Indents flags and aligns help texts."
  },
  {
    "code": "def get_default_plugin(cls):\n        from importlib import import_module\n        from django.conf import settings\n        default_plugin = getattr(settings, 'ACCESS_DEFAULT_PLUGIN', \"access.plugins.DjangoAccessPlugin\")\n        if default_plugin not in cls.default_plugins:\n            logger.info(\"Creating a default plugin: %s\", default_plugin)\n            path = default_plugin.split('.')\n            plugin_path = '.'.join(path[:-1])\n            plugin_name = path[-1]\n            DefaultPlugin = getattr(import_module(plugin_path), plugin_name)\n            cls.default_plugins[default_plugin] = DefaultPlugin()\n        return cls.default_plugins[default_plugin]",
    "docstring": "Return a default plugin."
  },
  {
    "code": "def ParseFileObject(self, parser_mediator, file_object):\n    file_object.seek(0, os.SEEK_SET)\n    header = file_object.read(2)\n    if not self.BENCODE_RE.match(header):\n      raise errors.UnableToParseFile('Not a valid Bencoded file.')\n    file_object.seek(0, os.SEEK_SET)\n    try:\n      data_object = bencode.bdecode(file_object.read())\n    except (IOError, bencode.BTFailure) as exception:\n      raise errors.UnableToParseFile(\n          '[{0:s}] unable to parse file: {1:s} with error: {2!s}'.format(\n              self.NAME, parser_mediator.GetDisplayName(), exception))\n    if not data_object:\n      raise errors.UnableToParseFile(\n          '[{0:s}] missing decoded data for file: {1:s}'.format(\n              self.NAME, parser_mediator.GetDisplayName()))\n    for plugin in self._plugins:\n      try:\n        plugin.UpdateChainAndProcess(parser_mediator, data=data_object)\n      except errors.WrongBencodePlugin as exception:\n        logger.debug('[{0:s}] wrong plugin: {1!s}'.format(\n            self.NAME, exception))",
    "docstring": "Parses a bencoded file-like object.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      file_object (dfvfs.FileIO): a file-like object.\n\n    Raises:\n      UnableToParseFile: when the file cannot be parsed."
  },
  {
    "code": "def _set_state(self, new_state, response=None):\n        if self._closed:\n            raise RuntimeError(\"message tracker is closed\")\n        if (self._state == MessageState.ABORTED or\n                new_state == MessageState.IN_TRANSIT or\n                (self._state == MessageState.ERROR and\n                 new_state == MessageState.DELIVERED_TO_SERVER) or\n                (self._state == MessageState.ERROR and\n                 new_state == MessageState.ABORTED) or\n                (self._state == MessageState.DELIVERED_TO_RECIPIENT and\n                 new_state == MessageState.DELIVERED_TO_SERVER) or\n                (self._state == MessageState.SEEN_BY_RECIPIENT and\n                 new_state == MessageState.DELIVERED_TO_SERVER) or\n                (self._state == MessageState.SEEN_BY_RECIPIENT and\n                 new_state == MessageState.DELIVERED_TO_RECIPIENT)):\n            raise ValueError(\n                \"message tracker transition from {} to {} not allowed\".format(\n                    self._state,\n                    new_state\n                )\n            )\n        self._state = new_state\n        self._response = response\n        self.on_state_changed(self._state, self._response)",
    "docstring": "Set the state of the tracker.\n\n        :param new_state: The new state of the tracker.\n        :type new_state: :class:`~.MessageState` member\n        :param response: A stanza related to the new state.\n        :type response: :class:`~.StanzaBase` or :data:`None`\n        :raise ValueError: if a forbidden state transition is attempted.\n        :raise RuntimeError: if the tracker is closed.\n\n        The state of the tracker is set to the `new_state`. The\n        :attr:`response` is also overriden with the new value, no matter if the\n        new or old value is :data:`None` or not. The :meth:`on_state_changed`\n        event is emitted.\n\n        The following transitions are forbidden and attempting to perform them\n        will raise :class:`ValueError`:\n\n        * any state -> :attr:`~.MessageState.IN_TRANSIT`\n        * :attr:`~.MessageState.DELIVERED_TO_RECIPIENT` ->\n          :attr:`~.MessageState.DELIVERED_TO_SERVER`\n        * :attr:`~.MessageState.SEEN_BY_RECIPIENT` ->\n          :attr:`~.MessageState.DELIVERED_TO_RECIPIENT`\n        * :attr:`~.MessageState.SEEN_BY_RECIPIENT` ->\n          :attr:`~.MessageState.DELIVERED_TO_SERVER`\n        * :attr:`~.MessageState.ABORTED` -> any state\n        * :attr:`~.MessageState.ERROR` -> any state\n\n        If the tracker is already :meth:`close`\\\\ -d, :class:`RuntimeError` is\n        raised. This check happens *before* a test is made whether the\n        transition is valid.\n\n        This method is part of the \"protected\" interface."
  },
  {
    "code": "def annotate_with_XMLNS(tree, prefix, URI):\n    if not ET.iselement(tree):\n        tree = tree.getroot()\n    tree.attrib['xmlns:' + prefix] = URI\n    iterator = tree.iter()\n    next(iterator)\n    for e in iterator:\n        e.tag = prefix + \":\" + e.tag",
    "docstring": "Annotates the provided DOM tree with XMLNS attributes and adds XMLNS\n    prefixes to the tags of the tree nodes.\n\n    :param tree: the input DOM tree\n    :type tree: an ``xml.etree.ElementTree.ElementTree`` or\n        ``xml.etree.ElementTree.Element`` object\n    :param prefix: XMLNS prefix for tree nodes' tags\n    :type prefix: str\n    :param URI: the URI for the XMLNS definition file\n    :type URI: str"
  },
  {
    "code": "def __get_container_path(self, host_path):\n    libname = os.path.split(host_path)[1]\n    return os.path.join(_container_lib_location, libname)",
    "docstring": "A simple helper function to determine the path of a host library\n    inside the container\n\n    :param host_path: The path of the library on the host\n    :type host_path: str"
  },
  {
    "code": "def reset(self):\n        if self.running:\n            raise RuntimeError('paco: executor is still running')\n        self.pool.clear()\n        self.observer.clear()\n        self.semaphore = asyncio.Semaphore(self.limit, loop=self.loop)",
    "docstring": "Resets the executer scheduler internal state.\n\n        Raises:\n            RuntimeError: is the executor is still running."
  },
  {
    "code": "def create(\n        project: 'projects.Project',\n        destination_directory,\n        destination_filename: str = None\n) -> file_io.FILE_WRITE_ENTRY:\n    template_path = environ.paths.resources('web', 'project.html')\n    with open(template_path, 'r') as f:\n        dom = f.read()\n    dom = dom.replace(\n        '<!-- CAULDRON:EXPORT -->',\n        templating.render_template(\n            'notebook-script-header.html',\n            uuid=project.uuid,\n            version=environ.version\n        )\n    )\n    filename = (\n        destination_filename\n        if destination_filename else\n        '{}.html'.format(project.uuid)\n    )\n    html_out_path = os.path.join(destination_directory, filename)\n    return file_io.FILE_WRITE_ENTRY(\n        path=html_out_path,\n        contents=dom\n    )",
    "docstring": "Creates a FILE_WRITE_ENTRY for the rendered HTML file for the given\n    project that will be saved in the destination directory with the given\n    filename.\n\n    :param project:\n        The project for which the rendered HTML file will be created\n    :param destination_directory:\n        The absolute path to the folder where the HTML file will be saved\n    :param destination_filename:\n        The name of the HTML file to be written in the destination directory.\n        Defaults to the project uuid.\n    :return:\n        A FILE_WRITE_ENTRY for the project's HTML file output"
  },
  {
    "code": "def get_cache_key(request, page, lang, site_id, title):\n    from cms.cache import _get_cache_key\n    from cms.templatetags.cms_tags import _get_page_by_untyped_arg\n    from cms.models import Page\n    if not isinstance(page, Page):\n        page = _get_page_by_untyped_arg(page, request, site_id)\n    if not site_id:\n        try:\n            site_id = page.node.site_id\n        except AttributeError:\n            site_id = page.site_id\n    if not title:\n        return _get_cache_key('page_tags', page, '', site_id) + '_type:tags_list'\n    else:\n        return _get_cache_key('title_tags', page, lang, site_id) + '_type:tags_list'",
    "docstring": "Create the cache key for the current page and tag type"
  },
  {
    "code": "def project_activity(index, start, end):\n    results = {\n        \"metrics\": [OpenedIssues(index, start, end),\n                    ClosedIssues(index, start, end)]\n    }\n    return results",
    "docstring": "Compute the metrics for the project activity section of the enriched\n    github issues index.\n\n    Returns a dictionary containing a \"metric\" key. This key contains the\n    metrics for this section.\n\n    :param index: index object\n    :param start: start date to get the data from\n    :param end: end date to get the data upto\n    :return: dictionary with the value of the metrics"
  },
  {
    "code": "def print_param_values(self_):\n        self = self_.self\n        for name,val in self.param.get_param_values():\n            print('%s.%s = %s' % (self.name,name,val))",
    "docstring": "Print the values of all this object's Parameters."
  },
  {
    "code": "def allow_capability(self, ctx, ops):\n        nops = 0\n        for op in ops:\n            if op != LOGIN_OP:\n                nops += 1\n        if nops == 0:\n            raise ValueError('no non-login operations required in capability')\n        _, used = self._allow_any(ctx, ops)\n        squasher = _CaveatSquasher()\n        for i, is_used in enumerate(used):\n            if not is_used:\n                continue\n            for cond in self._conditions[i]:\n                squasher.add(cond)\n        return squasher.final()",
    "docstring": "Checks that the user is allowed to perform all the\n        given operations. If not, a discharge error will be raised.\n        If allow_capability succeeds, it returns a list of first party caveat\n        conditions that must be applied to any macaroon granting capability\n        to execute the operations. Those caveat conditions will not\n        include any declarations contained in login macaroons - the\n        caller must be careful not to mint a macaroon associated\n        with the LOGIN_OP operation unless they add the expected\n        declaration caveat too - in general, clients should not create\n        capabilities that grant LOGIN_OP rights.\n\n        The operations must include at least one non-LOGIN_OP operation."
  },
  {
    "code": "def destroy(self):\r\n        sdl2.SDL_GL_DeleteContext(self.context)\r\n        sdl2.SDL_DestroyWindow(self.window)\r\n        sdl2.SDL_Quit()",
    "docstring": "Gracefully close the window"
  },
  {
    "code": "def configInputQueue():\n    def captureInput(iqueue):\n        while True:\n            c = getch()\n            if c == '\\x03' or c == '\\x04':\n                log.debug(\"Break received (\\\\x{0:02X})\".format(ord(c)))\n                iqueue.put(c)\n                break\n            log.debug(\n                \"Input Char '{}' received\".format(\n                    c if c != '\\r' else '\\\\r'))\n            iqueue.put(c)\n    input_queue = queue.Queue()\n    input_thread = threading.Thread(target=lambda: captureInput(input_queue))\n    input_thread.daemon = True\n    input_thread.start()\n    return input_queue, input_thread",
    "docstring": "configure a queue for accepting characters and return the queue"
  },
  {
    "code": "def set_tcp_reconnect(socket, config):\n    reconnect_options = {\n        'zmq_reconnect_ivl': 'RECONNECT_IVL',\n        'zmq_reconnect_ivl_max': 'RECONNECT_IVL_MAX',\n    }\n    for key, const in reconnect_options.items():\n        if key in config:\n            attr = getattr(zmq, const, None)\n            if attr:\n                socket.setsockopt(attr, config[key])",
    "docstring": "Set a series of TCP reconnect options on the socket if\n    and only if\n      1) they are specified explicitly in the config and\n      2) the version of pyzmq has been compiled with support\n\n    Once our fedmsg bus grew to include many hundreds of endpoints, we started\n    notices a *lot* of SYN-ACKs in the logs.  By default, if an endpoint is\n    unavailable, zeromq will attempt to reconnect every 100ms until it gets a\n    connection.  With this code, you can reconfigure that to back off\n    exponentially to some max delay (like 1000ms) to reduce reconnect storm\n    spam.\n\n    See the following\n      - http://api.zeromq.org/3-2:zmq-setsockopt"
  },
  {
    "code": "def is_allowed(self, subject_id, action, resource_id, policy_sets=[]):\n        body = {\n            \"action\": action,\n            \"subjectIdentifier\": subject_id,\n            \"resourceIdentifier\": resource_id,\n        }\n        if policy_sets:\n            body['policySetsEvaluationOrder'] = policy_sets\n        uri = self.uri + '/v1/policy-evaluation'\n        logging.debug(\"URI=\" + str(uri))\n        logging.debug(\"BODY=\" + str(body))\n        response = self.service._post(uri, body)\n        if 'effect' in response:\n            if response['effect'] in ['NOT_APPLICABLE', 'PERMIT']:\n                return True\n        return False",
    "docstring": "Evaluate a policy-set against a subject and resource.\n\n        example/\n\n            is_allowed('/user/j12y', 'GET', '/asset/12')"
  },
  {
    "code": "def optimization_loop(self, timeSeries, forecastingMethod, remainingParameters, currentParameterValues=None):\n        if currentParameterValues is None:\n            currentParameterValues = {}\n        if 0 == len(remainingParameters):\n            for parameter in currentParameterValues:\n                forecastingMethod.set_parameter(parameter, currentParameterValues[parameter])\n            forecast = timeSeries.apply(forecastingMethod)\n            error = self._errorClass(**self._errorMeasureKWArgs)\n            if not error.initialize(timeSeries, forecast):\n                return []\n            return [[error, dict(currentParameterValues)]]\n        localParameter       = remainingParameters[-1]\n        localParameterName   = localParameter[0]\n        localParameterValues = localParameter[1]\n        results = []\n        for value in localParameterValues:\n            currentParameterValues[localParameterName] = value\n            remainingParameters = remainingParameters[:-1]\n            results += self.optimization_loop(timeSeries, forecastingMethod, remainingParameters, currentParameterValues)\n        return results",
    "docstring": "The optimization loop.\n\n        This function is called recursively, until all parameter values were evaluated.\n\n        :param TimeSeries timeSeries:    TimeSeries instance that requires an optimized forecast.\n        :param BaseForecastingMethod forecastingMethod:    ForecastingMethod that is used to optimize the parameters.\n        :param list remainingParameters:    List containing all parameters with their corresponding values that still\n            need to be evaluated.\n            When this list is empty, the most inner optimization loop is reached.\n        :param dictionary currentParameterValues:    The currently evaluated forecast parameter combination.\n\n        :return: Returns a list containing a BaseErrorMeasure instance as defined in\n            :py:meth:`BaseOptimizationMethod.__init__` and the forecastingMethods parameter.\n        :rtype: list"
  },
  {
    "code": "def get(self, key):\n        try:\n            layers = key.split('.')\n            value = self.registrar\n            for key in layers:\n                value = value[key]\n            return value\n        except:\n            return None",
    "docstring": "Function deeply gets the key with \".\" notation\n\n        Args\n        ----\n          key (string): A key with the \".\" notation.\n\n        Returns\n        -------\n          reg (unknown type): Returns a dict or a primitive\n            type."
  },
  {
    "code": "def set_timestamp(self,timestamp=None):\n        if timestamp is None:\n            import time\n            timestamp = time.strftime('%Y-%m-%dT%H:%M:%S%Z')\n        self.node.set('timestamp',timestamp)",
    "docstring": "Set the timestamp of the linguistic processor, set to None for the current time\n        @type timestamp:string\n        @param timestamp: version of the linguistic processor"
  },
  {
    "code": "def upload(self, local_path):\n        camerafile_p = ffi.new(\"CameraFile**\")\n        with open(local_path, 'rb') as fp:\n            lib.gp_file_new_from_fd(camerafile_p, fp.fileno())\n            lib.gp_camera_folder_put_file(\n                self._cam._cam, self.path.encode() + b\"/\",\n                os.path.basename(local_path).encode(),\n                backend.FILE_TYPES['normal'], camerafile_p[0],\n                self._cam.ctx)",
    "docstring": "Upload a file to the camera's permanent storage.\n\n        :param local_path: Path to file to copy\n        :type local_path:  str/unicode"
  },
  {
    "code": "def mcscanx(args):\n    p = OptionParser(mcscanx.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) < 2:\n        sys.exit(not p.print_help())\n    blastfile = args[0]\n    bedfiles = args[1:]\n    prefix = \"_\".join(op.basename(x)[:2] for x in bedfiles)\n    symlink(blastfile, prefix + \".blast\")\n    allbedfile = prefix + \".gff\"\n    fw = open(allbedfile, \"w\")\n    for i, bedfile in enumerate(bedfiles):\n        prefix = chr(ord('A') + i)\n        make_gff(bedfile, prefix, fw)\n    fw.close()",
    "docstring": "%prog mcscanx athaliana.athaliana.last athaliana.bed\n\n    Wrap around MCScanX."
  },
  {
    "code": "def parse_line(self, line):\n        prefix = \"\"\n        if line.startswith(\",\"):\n            line, prefix = line[1:], \",\"\n        j = json.loads(line)\n        yield j\n        self.io.write_line(prefix + json.dumps(j))",
    "docstring": "Parse a single line of JSON and write modified JSON back."
  },
  {
    "code": "def singularize(word, pos=NOUN, gender=MALE, role=SUBJECT, custom={}):\n    w = word.lower().capitalize()\n    if word in custom:\n        return custom[word]\n    if word in singular:\n        return singular[word]\n    if pos == NOUN:\n        for a, b in singular_inflections:\n            if w.endswith(a):\n                return w[:-len(a)] + b\n        for suffix in (\"nen\", \"en\", \"n\", \"e\", \"er\", \"s\"):\n            if w.endswith(suffix):\n                w = w[:-len(suffix)]\n                break\n        if w.endswith((\"rr\", \"rv\", \"nz\")):\n            return w + \"e\"\n        return w\n    return w",
    "docstring": "Returns the singular of a given word.\n        The inflection is based on probability rather than gender and role."
  },
  {
    "code": "def record(self):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('SF record not yet initialized!')\n        length = 12\n        if self.virtual_file_size_high is not None:\n            length = 21\n        ret = b'SF' + struct.pack('=BB', length, SU_ENTRY_VERSION)\n        if self.virtual_file_size_high is not None and self.table_depth is not None:\n            ret += struct.pack('=LLLLB', self.virtual_file_size_high, utils.swab_32bit(self.virtual_file_size_high), self.virtual_file_size_low, utils.swab_32bit(self.virtual_file_size_low), self.table_depth)\n        else:\n            ret += struct.pack('=LL', self.virtual_file_size_low, utils.swab_32bit(self.virtual_file_size_low))\n        return ret",
    "docstring": "Generate a string representing the Rock Ridge Sparse File record.\n\n        Parameters:\n         None.\n        Returns:\n         String containing the Rock Ridge record."
  },
  {
    "code": "def _load_history_from_file(path, size=-1):\n        if size == 0:\n            return []\n        if os.path.exists(path):\n            with codecs.open(path, 'r', encoding='utf-8') as histfile:\n                lines = [line.rstrip('\\n') for line in histfile]\n            if size > 0:\n                lines = lines[-size:]\n            return lines\n        else:\n            return []",
    "docstring": "Load a history list from a file and split it into lines.\n\n        :param path: the path to the file that should be loaded\n        :type path: str\n        :param size: the number of lines to load (0 means no lines, < 0 means\n            all lines)\n        :type size: int\n        :returns: a list of history items (the lines of the file)\n        :rtype: list(str)"
  },
  {
    "code": "def _is_num_param(names, values, to_float=False):\n    fun = to_float and float or int\n    out_params = []\n    for (name, val) in zip(names, values):\n        if val is None:\n            out_params.append(val)\n        elif isinstance(val, number_or_string_types):\n            try:\n                out_params.append(fun(val))\n            except ValueError:\n                raise VdtParamError(name, val)\n        else:\n            raise VdtParamError(name, val)\n    return out_params",
    "docstring": "Return numbers from inputs or raise VdtParamError.\n\n    Lets ``None`` pass through.\n    Pass in keyword argument ``to_float=True`` to\n    use float for the conversion rather than int.\n\n    >>> _is_num_param(('', ''), (0, 1.0))\n    [0, 1]\n    >>> _is_num_param(('', ''), (0, 1.0), to_float=True)\n    [0.0, 1.0]\n    >>> _is_num_param(('a'), ('a'))  # doctest: +SKIP\n    Traceback (most recent call last):\n    VdtParamError: passed an incorrect value \"a\" for parameter \"a\"."
  },
  {
    "code": "def cmd_gimbal_mode(self, args):\n        if len(args) != 1:\n            print(\"usage: gimbal mode <GPS|MAVLink>\")\n            return\n        if args[0].upper() == 'GPS':\n            mode = mavutil.mavlink.MAV_MOUNT_MODE_GPS_POINT\n        elif args[0].upper() == 'MAVLINK':\n            mode = mavutil.mavlink.MAV_MOUNT_MODE_MAVLINK_TARGETING\n        elif args[0].upper() == 'RC':\n            mode = mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING\n        else:\n            print(\"Unsupported mode %s\" % args[0])\n        self.master.mav.mount_configure_send(self.target_system,\n                                             self.target_component,\n                                             mode,\n                                             1, 1, 1)",
    "docstring": "control gimbal mode"
  },
  {
    "code": "def match(self, location):\n        if self.ssh_alias != location.ssh_alias:\n            return False\n        elif self.have_wildcards:\n            return fnmatch.fnmatch(location.directory, self.directory)\n        else:\n            self = os.path.normpath(self.directory)\n            other = os.path.normpath(location.directory)\n            return self == other",
    "docstring": "Check if the given location \"matches\".\n\n        :param location: The :class:`Location` object to try to match.\n        :returns: :data:`True` if the two locations are on the same system and\n                  the :attr:`directory` can be matched as a filename pattern or\n                  a literal match on the normalized pathname."
  },
  {
    "code": "def memory_read_bytes(self, start_position: int, size: int) -> bytes:\n        return self._memory.read_bytes(start_position, size)",
    "docstring": "Read and return ``size`` bytes from memory starting at ``start_position``."
  },
  {
    "code": "async def build_get_revoc_reg_request(submitter_did: Optional[str],\n                                      revoc_reg_def_id: str,\n                                      timestamp: int) -> str:\n    logger = logging.getLogger(__name__)\n    logger.debug(\"build_get_revoc_reg_request: >>> submitter_did: %r, revoc_reg_def_id: %r, timestamp: %r\",\n                 submitter_did, revoc_reg_def_id, timestamp)\n    if not hasattr(build_get_revoc_reg_request, \"cb\"):\n        logger.debug(\"build_get_revoc_reg_request: Creating callback\")\n        build_get_revoc_reg_request.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_char_p))\n    c_submitter_did = c_char_p(submitter_did.encode('utf-8')) if submitter_did is not None else None\n    c_revoc_reg_def_id = c_char_p(revoc_reg_def_id.encode('utf-8'))\n    c_timestamp = c_int64(timestamp)\n    request_json = await do_call('indy_build_get_revoc_reg_request',\n                                 c_submitter_did,\n                                 c_revoc_reg_def_id,\n                                 c_timestamp,\n                                 build_get_revoc_reg_request.cb)\n    res = request_json.decode()\n    logger.debug(\"build_get_revoc_reg_request: <<< res: %r\", res)\n    return res",
    "docstring": "Builds a GET_REVOC_REG request. Request to get the accumulated state of the Revocation Registry\n    by ID. The state is defined by the given timestamp.\n\n    :param submitter_did: (Optional) DID of the read request sender (if not provided then default Libindy DID will be used).\n    :param revoc_reg_def_id:  ID of the corresponding Revocation Registry Definition in ledger.\n    :param timestamp: Requested time represented as a total number of seconds from Unix Epoch\n    :return: Request result as json."
  },
  {
    "code": "def assign_operation_ids(spec, operids):\n    empty_dict = {}\n    for path_name, path_data in six.iteritems(spec['paths']):\n        for method, method_data in six.iteritems(path_data):\n            oper_id = operids.get(path_name, empty_dict).get(method)\n            if oper_id:\n                method_data['operationId'] = oper_id",
    "docstring": "used to assign caller provided operationId values into a spec"
  },
  {
    "code": "def kernel():\n\tprint('================================')\n\tprint('  WARNING: upgrading the kernel')\n\tprint('================================')\n\ttime.sleep(5)\n\tprint('-[kernel]----------')\n\tcmd('rpi-update', True)\n\tprint(' >> You MUST reboot to load the new kernel <<')",
    "docstring": "Handle linux kernel update"
  },
  {
    "code": "def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        if conn.disassociate_route_table(association_id):\n            log.info('Route table with association id %s has been disassociated.', association_id)\n            return {'disassociated': True}\n        else:\n            log.warning('Route table with association id %s has not been disassociated.', association_id)\n            return {'disassociated': False}\n    except BotoServerError as e:\n        return {'disassociated': False, 'error': __utils__['boto.get_error'](e)}",
    "docstring": "Dissassociates a route table.\n\n    association_id\n        The Route Table Association ID to disassociate\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba'"
  },
  {
    "code": "def wrapper(cls, func, height=None, catch_interrupt=False, arguments=None,\n                unicode_aware=None):\n        screen = Screen.open(height,\n                             catch_interrupt=catch_interrupt,\n                             unicode_aware=unicode_aware)\n        restore = True\n        try:\n            try:\n                if arguments:\n                    return func(screen, *arguments)\n                else:\n                    return func(screen)\n            except ResizeScreenError:\n                restore = False\n                raise\n        finally:\n            screen.close(restore)",
    "docstring": "Construct a new Screen for any platform.  This will initialize the\n        Screen, call the specified function and then tidy up the system as\n        required when the function exits.\n\n        :param func: The function to call once the Screen has been created.\n        :param height: The buffer height for this Screen (only for test purposes).\n        :param catch_interrupt: Whether to catch and prevent keyboard\n            interrupts.  Defaults to False to maintain backwards compatibility.\n        :param arguments: Optional arguments list to pass to func (after the\n            Screen object).\n        :param unicode_aware: Whether the application can use unicode or not.\n            If None, try to detect from the environment if UTF-8 is enabled."
  },
  {
    "code": "def map_(input_layer, fn):\n  if not input_layer.is_sequence():\n    raise ValueError('Can only map a sequence.')\n  return [fn(x) for x in input_layer]",
    "docstring": "Maps the given function across this sequence.\n\n  To map an entire template across the sequence, use the `as_fn` method on the\n  template.\n\n  Args:\n    input_layer: The input tensor.\n    fn: A function of 1 argument that is applied to each item in the sequence.\n  Returns:\n    A new sequence Pretty Tensor.\n  Raises:\n    ValueError: If the input_layer does not hold a sequence."
  },
  {
    "code": "def _get_auth_challenge(self, exc):\n        response = HttpResponse(content=exc.content, status=exc.get_code_num())\n        response['WWW-Authenticate'] = 'Basic realm=\"%s\"' % REALM\n        return response",
    "docstring": "Returns HttpResponse for the client."
  },
  {
    "code": "def get_saver(scope, collections=(tf.GraphKeys.GLOBAL_VARIABLES,),\n              context=None, **kwargs):\n  variable_map = {}\n  for collection in collections:\n    variable_map.update(get_normalized_variable_map(scope, collection, context))\n  return tf.train.Saver(var_list=variable_map, **kwargs)",
    "docstring": "Builds a `tf.train.Saver` for the scope or module, with normalized names.\n\n  The names of the variables are normalized to remove the scope prefix.\n  This allows the same variables to be restored into another similar scope or\n  module using a complementary `tf.train.Saver` object.\n\n  Args:\n    scope: Scope or module. Variables within will be saved or restored.\n    collections: Sequence of collections of variables to restrict\n        `tf.train.Saver` to. By default this is `tf.GraphKeys.GLOBAL_VARIABLES`\n        which includes moving averages variables as well as trainable variables.\n    context: Scope or module, identical to or parent of `scope`. If given, this\n        will be used as the stripped prefix.\n    **kwargs: Extra keyword arguments to pass to tf.train.Saver.\n\n  Returns:\n    A `tf.train.Saver` object for Variables in the scope or module."
  },
  {
    "code": "def disenriched(self, thresh=0.05, idx=True):\n        return self.downregulated(thresh=thresh, idx=idx)",
    "docstring": "Disenriched features.\n\n        {threshdoc}"
  },
  {
    "code": "def get_installed_packages(site_packages, site_packages_64):\n        import pkg_resources\n        package_to_keep = []\n        if os.path.isdir(site_packages):\n            package_to_keep += os.listdir(site_packages)\n        if os.path.isdir(site_packages_64):\n            package_to_keep += os.listdir(site_packages_64)\n        package_to_keep = [x.lower() for x in package_to_keep]\n        installed_packages = {package.project_name.lower(): package.version for package in\n                              pkg_resources.WorkingSet()\n                              if package.project_name.lower() in package_to_keep\n                              or package.location.lower() in [site_packages.lower(), site_packages_64.lower()]}\n        return installed_packages",
    "docstring": "Returns a dict of installed packages that Zappa cares about."
  },
  {
    "code": "def pretty_objname(self, obj=None, maxlen=50, color=\"boldcyan\"):\n        parent_name = lambda_sub(\"\", get_parent_name(obj) or \"\")\n        objname = get_obj_name(obj)\n        if color:\n            objname += colorize(\"<{}>\".format(parent_name), color, close=False)\n        else:\n            objname += \"<{}>\".format(parent_name)\n        objname = objname if len(objname) < maxlen else \\\n            objname[:(maxlen-1)]+\"…>\"\n        if color:\n            objname += colors.RESET\n        return objname",
    "docstring": "Pretty prints object name\n\n            @obj: the object whose name you want to pretty print\n            @maxlen: #int maximum length of an object name to print\n            @color: your choice of :mod:colors or |None|\n\n            -> #str pretty object name\n            ..\n                from vital.debug import Look\n                print(Look.pretty_objname(dict))\n                # -> 'dict\\x1b[1;36m<builtins>\\x1b[1;m'\n            .."
  },
  {
    "code": "def get_path_matching(name):\n    p = os.path.join(os.path.expanduser(\"~\"), name)\n    if not os.path.isdir(p):\n        p = None\n        drive, folders = os.path.splitdrive(os.getcwd())\n        folders = folders.split(os.sep)\n        folders.insert(0, os.sep)\n        if name in folders:\n            p = os.path.join(drive, *folders[: folders.index(name) + 1])\n    return p",
    "docstring": "Get path matching a name.\n\n    Parameters\n    ----------\n    name : string\n        Name to search for.\n\n    Returns\n    -------\n    string\n        Full filepath."
  },
  {
    "code": "def _get_domain(conn, *vms, **kwargs):\n    ret = list()\n    lookup_vms = list()\n    all_vms = []\n    if kwargs.get('active', True):\n        for id_ in conn.listDomainsID():\n            all_vms.append(conn.lookupByID(id_).name())\n    if kwargs.get('inactive', True):\n        for id_ in conn.listDefinedDomains():\n            all_vms.append(id_)\n    if not all_vms:\n        raise CommandExecutionError('No virtual machines found.')\n    if vms:\n        for name in vms:\n            if name not in all_vms:\n                raise CommandExecutionError('The VM \"{name}\" is not present'.format(name=name))\n            else:\n                lookup_vms.append(name)\n    else:\n        lookup_vms = list(all_vms)\n    for name in lookup_vms:\n        ret.append(conn.lookupByName(name))\n    return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret",
    "docstring": "Return a domain object for the named VM or return domain object for all VMs.\n\n    :params conn: libvirt connection object\n    :param vms: list of domain names to look for\n    :param iterable: True to return an array in all cases"
  },
  {
    "code": "def create_model_package_from_algorithm(self, name, description, algorithm_arn, model_data):\n        request = {\n            'ModelPackageName': name,\n            'ModelPackageDescription': description,\n            'SourceAlgorithmSpecification': {\n                'SourceAlgorithms': [\n                    {\n                        'AlgorithmName': algorithm_arn,\n                        'ModelDataUrl': model_data\n                    }\n                ]\n            }\n        }\n        try:\n            LOGGER.info('Creating model package with name: {}'.format(name))\n            self.sagemaker_client.create_model_package(**request)\n        except ClientError as e:\n            error_code = e.response['Error']['Code']\n            message = e.response['Error']['Message']\n            if (\n                    error_code == 'ValidationException'\n                    and 'ModelPackage already exists' in message\n            ):\n                LOGGER.warning('Using already existing model package: {}'.format(name))\n            else:\n                raise",
    "docstring": "Create a SageMaker Model Package from the results of training with an Algorithm Package\n\n        Args:\n            name (str): ModelPackage name\n            description (str): Model Package description\n            algorithm_arn (str): arn or name of the algorithm used for training.\n            model_data (str): s3 URI to the model artifacts produced by training"
  },
  {
    "code": "def get_host(self, hostname):\n        if hostname in self.get_hosts():\n            return self.load_ssh_conf().lookup(hostname)\n        logger.warn('Tried to find host with name {0}, but host not found'.format(hostname))\n        return None",
    "docstring": "Returns a Host dict with config options, or None if none exists"
  },
  {
    "code": "def get_contract_by_hash(self, contract_hash):\n        contract_address = self.db.reader._get_address_by_hash(contract_hash)\n        if contract_address is not None:\n            return contract_address\n        else:\n            raise AddressNotFoundError",
    "docstring": "get mapped contract_address by its hash, if not found try\n        indexing."
  },
  {
    "code": "def _write_field(self, value):\n        class_name = str(value.__class__)\n        if class_name not in self.handlers:\n            raise ValueError('No handler has been registered for class: {0!s}'.format(class_name))\n        handler = self.handlers[class_name]\n        handler(value, self._file)",
    "docstring": "Write a single field to the destination file.\n\n        :param T value: The value of the field."
  },
  {
    "code": "def _do_merge(orig_files, out_file, config, region):\n    if not utils.file_exists(out_file):\n        with file_transaction(config, out_file) as tx_out_file:\n            _check_samples_nodups(orig_files)\n            prep_files = run_multicore(p_bgzip_and_index, [[x, config] for x in orig_files], config)\n            input_vcf_file = \"%s-files.txt\" % utils.splitext_plus(out_file)[0]\n            with open(input_vcf_file, \"w\") as out_handle:\n                for fname in prep_files:\n                    out_handle.write(fname + \"\\n\")\n            bcftools = config_utils.get_program(\"bcftools\", config)\n            output_type = \"z\" if out_file.endswith(\".gz\") else \"v\"\n            region_str = \"-r {}\".format(region) if region else \"\"\n            cmd = \"{bcftools} merge -O {output_type} {region_str} `cat {input_vcf_file}` > {tx_out_file}\"\n            do.run(cmd.format(**locals()), \"Merge variants\")\n    if out_file.endswith(\".gz\"):\n        bgzip_and_index(out_file, config)\n    return out_file",
    "docstring": "Do the actual work of merging with bcftools merge."
  },
  {
    "code": "def _run_module_code(code, init_globals=None,\n                    mod_name=None, mod_fname=None,\n                    mod_loader=None, pkg_name=None):\n    with _ModifiedArgv0(mod_fname):\n        with _TempModule(mod_name) as temp_module:\n            mod_globals = temp_module.module.__dict__\n            _run_code(code, mod_globals, init_globals,\n                      mod_name, mod_fname, mod_loader, pkg_name)\n    return mod_globals.copy()",
    "docstring": "Helper to run code in new namespace with sys modified"
  },
  {
    "code": "def _run_node_distribution_command(self, command, workunit):\n    process = command.run(stdout=workunit.output('stdout'),\n                          stderr=workunit.output('stderr'))\n    return process.wait()",
    "docstring": "Runs a NodeDistribution.Command for _execute_command and returns its return code.\n\n    Passes any additional kwargs to command.run (which passes them, modified, to subprocess.Popen).\n    Override this in a Task subclass to do something more complicated than just calling\n    command.run() and returning the result of wait().\n\n    :param NodeDistribution.Command command: The command to run.\n    :param WorkUnit workunit: The WorkUnit the command is running under.\n    :returns: returncode\n    :rtype: int"
  },
  {
    "code": "def deleteICM(uuid: str):\n    _metadata = ICMMetadata.query.filter_by(id=uuid).first()\n    db.session.delete(_metadata)\n    db.session.commit()\n    return (\"\", 204)",
    "docstring": "Deletes an ICM"
  },
  {
    "code": "def marketPrice(self) -> float:\n        price = self.last if (\n            self.hasBidAsk() and self.bid <= self.last <= self.ask) else \\\n            self.midpoint()\n        if isNan(price):\n            price = self.close\n        return price",
    "docstring": "Return the first available one of\n\n        * last price if within current bid/ask;\n        * average of bid and ask (midpoint);\n        * close price."
  },
  {
    "code": "def get_tags():\n    tags = getattr(flask.g, 'bukudb', get_bukudb()).get_tag_all()\n    result = {\n        'tags': tags[0]\n    }\n    if request.path.startswith('/api/'):\n        res = jsonify(result)\n    else:\n        res = render_template('bukuserver/tags.html', result=result)\n    return res",
    "docstring": "get tags."
  },
  {
    "code": "def _read_nowait(self, n: int) -> bytes:\n        chunks = []\n        while self._buffer:\n            chunk = self._read_nowait_chunk(n)\n            chunks.append(chunk)\n            if n != -1:\n                n -= len(chunk)\n                if n == 0:\n                    break\n        return b''.join(chunks) if chunks else b''",
    "docstring": "Read not more than n bytes, or whole buffer is n == -1"
  },
  {
    "code": "def firstAttr(self, *attrs):\n        for attr in attrs:\n            value = self.__dict__.get(attr)\n            if value is not None:\n                return value",
    "docstring": "Return the first attribute in attrs that is not None."
  },
  {
    "code": "def fixchars(self, text):\n        keys = ''.join(Config.CHARFIXES.keys())\n        values = ''.join(Config.CHARFIXES.values())\n        fixed = text.translate(str.maketrans(keys, values))\n        if fixed != text:\n            self.modified = True\n        return fixed",
    "docstring": "Find and replace problematic characters."
  },
  {
    "code": "def get_logger(name):\n    logger = logging.getLogger(name)\n    logger.setLevel(logging.INFO)\n    file_handler = logging.FileHandler(log_path)\n    file_handler.setLevel(logging.INFO)\n    formatter = logging.Formatter(\n        '%(asctime)s %(name)12s %(levelname)8s %(lineno)s %(message)s',\n        datefmt='%m/%d/%Y %I:%M:%S %p')\n    file_handler.setFormatter(formatter)\n    logger.addHandler(file_handler)\n    return logger",
    "docstring": "Return a logger with a file handler."
  },
  {
    "code": "def on_right_click_listctrl(self, event):\n        g_index = event.GetIndex()\n        if self.Data[self.s]['measurement_flag'][g_index] == 'g':\n            self.mark_meas_bad(g_index)\n        else:\n            self.mark_meas_good(g_index)\n        if self.data_model == 3.0:\n            self.con.tables['measurements'].write_magic_file(dir_path=self.WD)\n        else:\n            pmag.magic_write(os.path.join(\n                self.WD, \"magic_measurements.txt\"), self.mag_meas_data, \"magic_measurements\")\n        self.recalculate_current_specimen_interpreatations()\n        if self.ie_open:\n            self.ie.update_current_fit_data()\n        self.calculate_high_levels_data()\n        self.update_selection()",
    "docstring": "right click on the listctrl toggles measurement bad"
  },
  {
    "code": "def delete_service(resource_root, name, cluster_name=\"default\"):\n  return call(resource_root.delete,\n      \"%s/%s\" % (SERVICES_PATH % (cluster_name,), name),\n      ApiService)",
    "docstring": "Delete a service by name\n  @param resource_root: The root Resource object.\n  @param name: Service name\n  @param cluster_name: Cluster name\n  @return: The deleted ApiService object"
  },
  {
    "code": "def _read_and_batch_from_files(\n    file_pattern, batch_size, max_length, num_cpu_cores, shuffle, repeat):\n  dataset = tf.data.Dataset.list_files(file_pattern)\n  if shuffle:\n    mlperf_log.transformer_print(key=mlperf_log.INPUT_ORDER)\n    dataset = dataset.shuffle(buffer_size=_FILE_SHUFFLE_BUFFER)\n  dataset = dataset.apply(\n      tf.contrib.data.parallel_interleave(\n          _load_records, sloppy=shuffle, cycle_length=num_cpu_cores))\n  dataset = dataset.map(_parse_example,\n                        num_parallel_calls=num_cpu_cores)\n  dataset = dataset.filter(lambda x, y: _filter_max_length((x, y), max_length))\n  mlperf_log.transformer_print(key=mlperf_log.INPUT_BATCH_SIZE,\n                               value=batch_size)\n  mlperf_log.transformer_print(key=mlperf_log.INPUT_MAX_LENGTH,\n                               value=max_length)\n  dataset = _batch_examples(dataset, batch_size, max_length)\n  dataset = dataset.repeat(repeat)\n  dataset = dataset.prefetch(1)\n  return dataset",
    "docstring": "Create dataset where each item is a dict of \"inputs\" and \"targets\".\n\n  Args:\n    file_pattern: String used to match the input TFRecord files.\n    batch_size: Maximum number of tokens per batch of examples\n    max_length: Maximum number of tokens per example\n    num_cpu_cores: Number of cpu cores for parallel input processing.\n    shuffle: If true, randomizes order of elements.\n    repeat: Number of times to repeat the dataset. If None, the dataset is\n      repeated forever.\n\n  Returns:\n    tf.data.Dataset object containing examples loaded from the files."
  },
  {
    "code": "def add_leaves(self, values_array, do_hash=False):\n        self.tree['is_ready'] = False\n        [self._add_leaf(value, do_hash) for value in values_array]",
    "docstring": "Add leaves to the tree.\n\n        Similar to chainpoint merkle tree library, this accepts hash values as an array of Buffers or hex strings.\n        :param values_array: array of values to add\n        :param do_hash: whether to hash the values before inserting"
  },
  {
    "code": "def get_default_config(self):\n        config = super(XFSCollector, self).get_default_config()\n        config.update({\n            'path': 'xfs'\n        })\n        return config",
    "docstring": "Returns the xfs collector settings"
  },
  {
    "code": "def push_reindex_to_actions_pool(obj, idxs=None):\n    indexes = idxs and idxs or []\n    pool = ActionHandlerPool.get_instance()\n    pool.push(obj, \"reindex\", success=True, idxs=indexes)",
    "docstring": "Push a reindex job to the actions handler pool"
  },
  {
    "code": "def map_sequence(stmts_in, **kwargs):\n    from indra.preassembler.sitemapper import SiteMapper, default_site_map\n    logger.info('Mapping sites on %d statements...' % len(stmts_in))\n    kwarg_list = ['do_methionine_offset', 'do_orthology_mapping',\n                  'do_isoform_mapping']\n    sm = SiteMapper(default_site_map,\n                    use_cache=kwargs.pop('use_cache', False),\n                    **_filter(kwargs, kwarg_list))\n    valid, mapped = sm.map_sites(stmts_in)\n    correctly_mapped_stmts = []\n    for ms in mapped:\n        correctly_mapped = all([mm.has_mapping() for mm in ms.mapped_mods])\n        if correctly_mapped:\n            correctly_mapped_stmts.append(ms.mapped_stmt)\n    stmts_out = valid + correctly_mapped_stmts\n    logger.info('%d statements with valid sites' % len(stmts_out))\n    dump_pkl = kwargs.get('save')\n    if dump_pkl:\n        dump_statements(stmts_out, dump_pkl)\n    del sm\n    return stmts_out",
    "docstring": "Map sequences using the SiteMapper.\n\n    Parameters\n    ----------\n    stmts_in : list[indra.statements.Statement]\n        A list of statements to map.\n    do_methionine_offset : boolean\n        Whether to check for off-by-one errors in site position (possibly)\n        attributable to site numbering from mature proteins after\n        cleavage of the initial methionine. If True, checks the reference\n        sequence for a known modification at 1 site position greater\n        than the given one; if there exists such a site, creates the\n        mapping. Default is True.\n    do_orthology_mapping : boolean\n        Whether to check sequence positions for known modification sites\n        in mouse or rat sequences (based on PhosphoSitePlus data). If a\n        mouse/rat site is found that is linked to a site in the human\n        reference sequence, a mapping is created. Default is True.\n    do_isoform_mapping : boolean\n        Whether to check sequence positions for known modifications\n        in other human isoforms of the protein (based on PhosphoSitePlus\n        data). If a site is found that is linked to a site in the human\n        reference sequence, a mapping is created. Default is True.\n    use_cache : boolean\n        If True, a cache will be created/used from the laction specified by\n        SITEMAPPER_CACHE_PATH, defined in your INDRA config or the environment.\n        If False, no cache is used. For more details on the cache, see the\n        SiteMapper class definition.\n    save : Optional[str]\n        The name of a pickle file to save the results (stmts_out) into.\n\n    Returns\n    -------\n    stmts_out : list[indra.statements.Statement]\n        A list of mapped statements."
  },
  {
    "code": "def load(path, use_nep8=True):\n        Compiler.__instance = None\n        compiler = Compiler.instance()\n        compiler.nep8 = use_nep8\n        compiler.entry_module = Module(path)\n        return compiler",
    "docstring": "Call `load` to load a Python file to be compiled but not to write to .avm\n\n        :param path: the path of the Python file to compile\n        :return: The instance of the compiler\n\n        The following returns the compiler object for inspection.\n\n        .. code-block:: python\n\n            from boa.compiler import Compiler\n\n            compiler = Compiler.load('path/to/your/file.py')"
  },
  {
    "code": "def _update_context_field_binary_composition(present_locations, expression):\n    if not any((isinstance(expression.left, ContextField),\n                isinstance(expression.right, ContextField))):\n        raise AssertionError(u'Received a BinaryComposition {} without any ContextField '\n                             u'operands. This should never happen.'.format(expression))\n    if isinstance(expression.left, ContextField):\n        context_field = expression.left\n        location_name, _ = context_field.location.get_location_name()\n        if location_name not in present_locations:\n            return TrueLiteral\n    if isinstance(expression.right, ContextField):\n        context_field = expression.right\n        location_name, _ = context_field.location.get_location_name()\n        if location_name not in present_locations:\n            return TrueLiteral\n    return expression",
    "docstring": "Lower BinaryCompositions involving non-existent ContextFields to True.\n\n    Args:\n        present_locations: set of all locations in the current MatchQuery that have not been pruned\n        expression: BinaryComposition with at least one ContextField operand\n\n    Returns:\n        TrueLiteral iff either ContextField operand is not in `present_locations`,\n        and the original expression otherwise"
  },
  {
    "code": "def find(self, header, list_type=None):\n        for chunk in self:\n            if chunk.header == header and (list_type is None or (header in\n                    list_headers and chunk.type == list_type)):\n                return chunk\n            elif chunk.header in list_headers:\n                try:\n                    result = chunk.find(header, list_type)\n                    return result\n                except chunk.NotFound:\n                    pass\n        if list_type is None:\n            raise self.NotFound('Chunk \\'{0}\\' not found.'.format(header))\n        else:\n            raise self.NotFound('List \\'{0} {1}\\' not found.'.format(header,\n                list_type))",
    "docstring": "Find the first chunk with specified header and optional list type."
  },
  {
    "code": "def summary(app):\n    r = requests.get('https://{}.herokuapp.com/summary'.format(app))\n    summary = r.json()['summary']\n    click.echo(\"\\nstatus \\t| count\")\n    click.echo(\"----------------\")\n    for s in summary:\n        click.echo(\"{}\\t| {}\".format(s[0], s[1]))\n    num_101s = sum([s[1] for s in summary if s[0] == 101])\n    num_10xs = sum([s[1] for s in summary if s[0] >= 100])\n    if num_10xs > 0:\n        click.echo(\"\\nYield: {:.2%}\".format(1.0 * num_101s / num_10xs))",
    "docstring": "Print a summary of a deployed app's status."
  },
  {
    "code": "def to_array(self):\n        array = super(WebhookInfo, self).to_array()\n        array['url'] = u(self.url)\n        array['has_custom_certificate'] = bool(self.has_custom_certificate)\n        array['pending_update_count'] = int(self.pending_update_count)\n        if self.last_error_date is not None:\n            array['last_error_date'] = int(self.last_error_date)\n        if self.last_error_message is not None:\n            array['last_error_message'] = u(self.last_error_message)\n        if self.max_connections is not None:\n            array['max_connections'] = int(self.max_connections)\n        if self.allowed_updates is not None:\n            array['allowed_updates'] = self._as_array(self.allowed_updates)\n        return array",
    "docstring": "Serializes this WebhookInfo to a dictionary.\n\n        :return: dictionary representation of this object.\n        :rtype: dict"
  },
  {
    "code": "def is_stalemate(self) -> bool:\n        if self.is_check():\n            return False\n        if self.is_variant_end():\n            return False\n        return not any(self.generate_legal_moves())",
    "docstring": "Checks if the current position is a stalemate."
  },
  {
    "code": "async def listen(self):\n        \"Listen for messages on channels this client has been subscribed to\"\n        if self.subscribed:\n            return self.handle_message(await self.parse_response(block=True))",
    "docstring": "Listen for messages on channels this client has been subscribed to"
  },
  {
    "code": "def _symbol_bars(\n            self,\n            symbols,\n            size,\n            _from=None,\n            to=None,\n            limit=None):\n        assert size in ('day', 'minute')\n        query_limit = limit\n        if query_limit is not None:\n            query_limit *= 2\n        @skip_http_error((404, 504))\n        def fetch(symbol):\n            df = self._api.polygon.historic_agg(\n                size, symbol, _from, to, query_limit).df\n            if size == 'minute':\n                df.index += pd.Timedelta('1min')\n                mask = self._cal.minutes_in_range(\n                    df.index[0], df.index[-1],\n                ).tz_convert(NY)\n                df = df.reindex(mask)\n            if limit is not None:\n                df = df.iloc[-limit:]\n            return df\n        return parallelize(fetch)(symbols)",
    "docstring": "Query historic_agg either minute or day in parallel\n        for multiple symbols, and return in dict.\n\n        symbols: list[str]\n        size:    str ('day', 'minute')\n        _from:   str or pd.Timestamp\n        to:      str or pd.Timestamp\n        limit:   str or int\n\n        return: dict[str -> pd.DataFrame]"
  },
  {
    "code": "def encode_task(task):\n    task = task.copy()\n    if 'tags' in task:\n        task['tags'] = ','.join(task['tags'])\n    for k in task:\n        for unsafe, safe in six.iteritems(encode_replacements):\n            if isinstance(task[k], six.string_types):\n                task[k] = task[k].replace(unsafe, safe)\n        if isinstance(task[k], datetime.datetime):\n            task[k] = task[k].strftime(\"%Y%m%dT%M%H%SZ\")\n    return \"[%s]\\n\" % \" \".join([\n        \"%s:\\\"%s\\\"\" % (k, v)\n        for k, v in sorted(task.items(), key=itemgetter(0))\n    ])",
    "docstring": "Convert a dict-like task to its string representation"
  },
  {
    "code": "def from_columns(columns):\n        data = [\n            [\n                column[i]\n                for i in range(len(column))\n            ]\n            for column in columns\n        ]\n        return Matrix(data)",
    "docstring": "Parses raw columns\n\n        :param columns: matrix divided into columns\n        :return: Matrix: Merge the columns to form a matrix"
  },
  {
    "code": "def alphabetical_sort(list_to_sort: Iterable[str]) -> List[str]:\n    return sorted(list_to_sort, key=norm_fold)",
    "docstring": "Sorts a list of strings alphabetically.\n\n    For example: ['a1', 'A11', 'A2', 'a22', 'a3']\n\n    To sort a list in place, don't call this method, which makes a copy. Instead, do this:\n\n    my_list.sort(key=norm_fold)\n\n    :param list_to_sort: the list being sorted\n    :return: the sorted list"
  },
  {
    "code": "def select(self, field_paths):\n        query = query_mod.Query(self)\n        return query.select(field_paths)",
    "docstring": "Create a \"select\" query with this collection as parent.\n\n        See\n        :meth:`~.firestore_v1beta1.query.Query.select` for\n        more information on this method.\n\n        Args:\n            field_paths (Iterable[str, ...]): An iterable of field paths\n                (``.``-delimited list of field names) to use as a projection\n                of document fields in the query results.\n\n        Returns:\n            ~.firestore_v1beta1.query.Query: A \"projected\" query."
  },
  {
    "code": "def to_text(path):\n    import subprocess\n    from distutils import spawn\n    if spawn.find_executable(\"pdftotext\"):\n        out, err = subprocess.Popen(\n            [\"pdftotext\", '-layout', '-enc', 'UTF-8', path, '-'], stdout=subprocess.PIPE\n        ).communicate()\n        return out\n    else:\n        raise EnvironmentError(\n            'pdftotext not installed. Can be downloaded from https://poppler.freedesktop.org/'\n        )",
    "docstring": "Wrapper around Poppler pdftotext.\n\n    Parameters\n    ----------\n    path : str\n        path of electronic invoice in PDF\n\n    Returns\n    -------\n    out : str\n        returns extracted text from pdf\n\n    Raises\n    ------\n    EnvironmentError:\n        If pdftotext library is not found"
  },
  {
    "code": "def _link_replace(self, match, **context):\n        url = match.group(0)\n        if self.linker:\n            if self.linker_takes_context:\n                return self.linker(url, context)\n            else:\n                return self.linker(url)\n        else:\n            href = url\n            if '://' not in href:\n                href = 'http://' + href\n            return self.url_template.format(href=href.replace('\"', '%22'), text=url)",
    "docstring": "Callback for re.sub to replace link text with markup. Turns out using a callback function\n        is actually faster than using backrefs, plus this lets us provide a hook for user customization.\n        linker_takes_context=True means that the linker gets passed context like a standard format function."
  },
  {
    "code": "def transform_annotation(self, ann, duration):\n        intervals = np.asarray([[0, 1]])\n        values = list([obs.value for obs in ann])\n        intervals = np.tile(intervals, [len(values), 1])\n        tags = [v for v in values if v in self._classes]\n        if len(tags):\n            target = self.encoder.transform([tags]).astype(np.bool).max(axis=0)\n        else:\n            target = np.zeros(len(self._classes), dtype=np.bool)\n        return {'tags': target}",
    "docstring": "Transform an annotation to static label encoding.\n\n        Parameters\n        ----------\n        ann : jams.Annotation\n            The annotation to convert\n\n        duration : number > 0\n            The duration of the track\n\n        Returns\n        -------\n        data : dict\n            data['tags'] : np.ndarray, shape=(n_labels,)\n                A static binary encoding of the labels"
  },
  {
    "code": "def start(self, execution_history, backward_execution=False, generate_run_id=True):\n        self.execution_history = execution_history\n        if generate_run_id:\n            self._run_id = run_id_generator()\n        self.backward_execution = copy.copy(backward_execution)\n        self.thread = threading.Thread(target=self.run)\n        self.thread.start()",
    "docstring": "Starts the execution of the state in a new thread.\n\n        :return:"
  },
  {
    "code": "def vote_choice_address(self) -> List[str]:\n        if self.vote_id is None:\n            raise Exception(\"vote_id is required\")\n        addresses = []\n        vote_init_txid = unhexlify(self.vote_id)\n        for choice in self.choices:\n            vote_cast_privkey = sha256(vote_init_txid + bytes(\n                                    list(self.choices).index(choice))\n                                    ).hexdigest()\n            addresses.append(Kutil(network=self.deck.network,\n                                   privkey=bytearray.fromhex(vote_cast_privkey)).address)\n        return addresses",
    "docstring": "calculate the addresses on which the vote is casted."
  },
  {
    "code": "def requires_public_key(func):\n    def func_wrapper(self, *args, **kwargs):\n        if hasattr(self, \"public_key\"):\n            func(self, *args, **kwargs)\n        else:\n            self.generate_public_key()\n            func(self, *args, **kwargs)\n    return func_wrapper",
    "docstring": "Decorator for functions that require the public key to be defined. By definition, this includes the private key, as such, it's enough to use this to effect definition of both public and private key."
  },
  {
    "code": "def calculate_error(self):\n        self.numvars.error = 0.\n        fluxes = self.sequences.fluxes\n        for flux in fluxes.numerics:\n            results = getattr(fluxes.fastaccess, '_%s_results' % flux.name)\n            diff = (results[self.numvars.idx_method] -\n                    results[self.numvars.idx_method-1])\n            self.numvars.error = max(self.numvars.error,\n                                     numpy.max(numpy.abs(diff)))",
    "docstring": "Estimate the numerical error based on the fluxes calculated\n        by the current and the last method.\n\n        >>> from hydpy.models.test_v1 import *\n        >>> parameterstep()\n        >>> model.numvars.idx_method = 2\n        >>> results = numpy.asarray(fluxes.fastaccess._q_results)\n        >>> results[:4] = 0., 3., 4., 0.\n        >>> model.calculate_error()\n        >>> from hydpy import round_\n        >>> round_(model.numvars.error)\n        1.0"
  },
  {
    "code": "def mlt2mlon(self, mlt, datetime, ssheight=50*6371):\n        ssglat, ssglon = helpers.subsol(datetime)\n        ssalat, ssalon = self.geo2apex(ssglat, ssglon, ssheight)\n        return (15*np.float64(mlt) - 180 + ssalon + 360) % 360",
    "docstring": "Computes the magnetic longitude at the specified magnetic local time\n        and UT.\n\n        Parameters\n        ==========\n        mlt : array_like\n            Magnetic local time\n        datetime : :class:`datetime.datetime`\n            Date and time\n        ssheight : float, optional\n            Altitude in km to use for converting the subsolar point from\n            geographic to magnetic coordinates. A high altitude is used\n            to ensure the subsolar point is mapped to high latitudes, which\n            prevents the South-Atlantic Anomaly (SAA) from influencing the MLT.\n\n        Returns\n        =======\n        mlon : ndarray or float\n            Magnetic longitude [0, 360) (apex and quasi-dipole longitude are\n            always equal)\n\n        Notes\n        =====\n        To compute the magnetic longitude, we find the apex longitude of the\n        subsolar point at the given time. Then the magnetic longitude of the\n        given point will be computed from the separation in magnetic local time\n        from this point (1 hour = 15 degrees)."
  },
  {
    "code": "def flatten_dir_tree(self, tree):\n        result = {}\n        def helper(tree, leading_path = ''):\n            dirs  = tree['dirs']; files = tree['files']\n            for name, file_info in files.iteritems():\n                file_info['path'] = leading_path + '/'  + name\n                result[file_info['path']] = file_info\n            for name, contents in dirs.iteritems():\n                helper(contents, leading_path +'/'+ name)\n        helper(tree); return result",
    "docstring": "Convert a file tree back into a flat dict"
  },
  {
    "code": "def load_weights(self):\n        if self.network_weights_loader:\n            self.network_weights = self.network_weights_loader()\n            self.network_weights_loader = None",
    "docstring": "Load weights by evaluating self.network_weights_loader, if needed.\n\n        After calling this, self.network_weights_loader will be None and\n        self.network_weights will be the weights list, if available."
  },
  {
    "code": "def get_serializer(self, node):\n        return self.options['serializers'].get(type(node), None)\n        if type(node) in self.options['serializers']:\n            return self.options['serializers'][type(node)]\n        return None",
    "docstring": "Returns serializer for specific element.\n\n        :Args:\n          - node (:class:`ooxml.doc.Element`): Element object \n\n        :Returns:\n          Returns reference to a function which will be used for serialization."
  },
  {
    "code": "def make_initial_frame_chooser(\n    real_env, frame_stack_size, simulation_random_starts,\n    simulation_flip_first_random_for_beginning,\n    split=tf.estimator.ModeKeys.TRAIN,\n):\n  initial_frame_rollouts = real_env.current_epoch_rollouts(\n      split=split, minimal_rollout_frames=frame_stack_size,\n  )\n  def initial_frame_chooser(batch_size):\n    deterministic_initial_frames =\\\n        initial_frame_rollouts[0][:frame_stack_size]\n    if not simulation_random_starts:\n      initial_frames = [deterministic_initial_frames] * batch_size\n    else:\n      initial_frames = random_rollout_subsequences(\n          initial_frame_rollouts, batch_size, frame_stack_size\n      )\n      if simulation_flip_first_random_for_beginning:\n        initial_frames[0] = deterministic_initial_frames\n    return np.stack([\n        [frame.observation.decode() for frame in initial_frame_stack]\n        for initial_frame_stack in initial_frames\n    ])\n  return initial_frame_chooser",
    "docstring": "Make frame chooser.\n\n  Args:\n    real_env: T2TEnv to take initial frames from.\n    frame_stack_size (int): Number of consecutive frames to extract.\n    simulation_random_starts (bool): Whether to choose frames at random.\n    simulation_flip_first_random_for_beginning (bool): Whether to flip the first\n      frame stack in every batch for the frames at the beginning.\n    split (tf.estimator.ModeKeys or None): Data split to take the frames from,\n      None means use all frames.\n\n  Returns:\n    Function batch_size -> initial_frames."
  },
  {
    "code": "def _read_from_sql(self, request, db_name):\n        with contextlib.closing(sqlite3.connect(\"{}.db\".format(db_name))) as con:\n            return sql.read_sql(sql=request, con=con)",
    "docstring": "Using the contextlib, I hope to close the connection to database when\n        not in use"
  },
  {
    "code": "def protect(self, password=None, read_protect=False, protect_from=0):\n        return super(FelicaLite, self).protect(\n            password, read_protect, protect_from)",
    "docstring": "Protect a FeliCa Lite Tag.\n\n        A FeliCa Lite Tag can be provisioned with a custom password\n        (or the default manufacturer key if the password is an empty\n        string or bytearray) to ensure that data retrieved by future\n        read operations, after authentication, is genuine. Read\n        protection is not supported.\n\n        A non-empty *password* must provide at least 128 bit key\n        material, in other words it must be a string or bytearray of\n        length 16 or more.\n\n        The memory unit for the value of *protect_from* is 16 byte,\n        thus with ``protect_from=2`` bytes 0 to 31 are not protected.\n        If *protect_from* is zero (the default value) and the Tag has\n        valid NDEF management data, the NDEF RW Flag is set to read\n        only."
  },
  {
    "code": "def ParseApplicationUsageRow(\n      self, parser_mediator, query, row, **unused_kwargs):\n    query_hash = hash(query)\n    application_name = self._GetRowValue(query_hash, row, 'event')\n    usage = 'Application {0:s}'.format(application_name)\n    event_data = MacOSApplicationUsageEventData()\n    event_data.application = self._GetRowValue(query_hash, row, 'app_path')\n    event_data.app_version = self._GetRowValue(query_hash, row, 'app_version')\n    event_data.bundle_id = self._GetRowValue(query_hash, row, 'bundle_id')\n    event_data.count = self._GetRowValue(query_hash, row, 'number_times')\n    event_data.query = query\n    timestamp = self._GetRowValue(query_hash, row, 'last_time')\n    date_time = dfdatetime_posix_time.PosixTime(timestamp=timestamp)\n    event = time_events.DateTimeValuesEvent(date_time, usage)\n    parser_mediator.ProduceEventWithEventData(event, event_data)",
    "docstring": "Parses an application usage row.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      query (str): query that created the row.\n      row (sqlite3.Row): row."
  },
  {
    "code": "def get_max_dim(self, obj):\n        try:\n            iter(obj)\n        except TypeError:\n            return 0\n        try:\n            for o in obj:\n                iter(o)\n                break\n        except TypeError:\n            return 1\n        return 2",
    "docstring": "Returns maximum dimensionality over which obj is iterable <= 2"
  },
  {
    "code": "def from_isodatetime(value, strict=False):\n    if value or strict:\n        return arrow.get(value).datetime",
    "docstring": "Convert an ISO formatted datetime into a Date object.\n\n    :param value: The ISO formatted datetime.\n    :param strict: If value is ``None``, then if strict is ``True`` it returns\n        the Date object of today, otherwise it returns ``None``.\n        (Default: ``False``)\n    :returns: The Date object or ``None``."
  },
  {
    "code": "def from_gene_ids_and_names(cls, gene_names: Dict[str, str]):\n        genes = [ExpGene(id_, name=name) for id_, name in gene_names.items()]\n        return cls.from_genes(genes)",
    "docstring": "Initialize instance from gene IDs and names."
  },
  {
    "code": "def put(self, endpoint, **kwargs):\n        kwargs.update(self.kwargs.copy())\n        if \"data\" in kwargs:\n            kwargs[\"headers\"].update(\n                {\"Content-Type\": \"application/json;charset=UTF-8\"})\n        response = requests.put(self.make_url(endpoint), **kwargs)\n        return _decode_response(response)",
    "docstring": "Send HTTP PUT to the endpoint.\n\n        :arg str endpoint: The endpoint to send to.\n\n        :returns:\n            JSON decoded result.\n\n        :raises:\n            requests.RequestException on timeout or connection error."
  },
  {
    "code": "def parse_task_rawcommand(self, rawcommand_subAST):\n        command_array = []\n        for code_snippet in rawcommand_subAST.attributes[\"parts\"]:\n            if isinstance(code_snippet, wdl_parser.Terminal):\n                command_var = \"r\"\n            if isinstance(code_snippet, wdl_parser.Ast):\n                if code_snippet.name == 'CommandParameter':\n                    code_expr = self.parse_declaration_expressn(code_snippet.attr('expr'), es='')\n                    code_attributes = self.parse_task_rawcommand_attributes(code_snippet.attr('attributes'))\n                    command_var = self.modify_cmd_expr_w_attributes(code_expr, code_attributes)\n            if isinstance(code_snippet, wdl_parser.AstList):\n                raise NotImplementedError\n            command_array.append(command_var)\n        return command_array",
    "docstring": "Parses the rawcommand section of the WDL task AST subtree.\n\n        Task \"rawcommands\" are divided into many parts.  There are 2 types of\n        parts: normal strings, & variables that can serve as changeable inputs.\n\n        The following example command:\n            'echo ${variable1} ${variable2} > output_file.txt'\n\n        Has 5 parts:\n                     Normal  String: 'echo '\n                     Variable Input: variable1\n                     Normal  String: ' '\n                     Variable Input: variable2\n                     Normal  String: ' > output_file.txt'\n\n        Variables can also have additional conditions, like 'sep', which is like\n        the python ''.join() function and in WDL looks like: ${sep=\" -V \" GVCFs}\n        and would be translated as: ' -V '.join(GVCFs).\n\n        :param rawcommand_subAST: A subAST representing some bash command.\n        :return: A list=[] of tuples=() representing the parts of the command:\n             e.g. [(command_var, command_type, additional_conditions_list), ...]\n                  Where: command_var = 'GVCFs'\n                         command_type = 'variable'\n                         command_actions = {'sep': ' -V '}"
  },
  {
    "code": "def process_message_notification(request, messages_path):\n    if not messages_path:\n        return\n    global _MESSAGES_CACHE\n    global _MESSAGES_MTIME\n    if (_MESSAGES_CACHE is None or\n            _MESSAGES_MTIME != os.path.getmtime(messages_path)):\n        _MESSAGES_CACHE = _get_processed_messages(messages_path)\n        _MESSAGES_MTIME = os.path.getmtime(messages_path)\n    for msg in _MESSAGES_CACHE:\n        msg.send_message(request)",
    "docstring": "Process all the msg file found in the message directory"
  },
  {
    "code": "def getHeader(self):\n        return {\"technician\": self.getTechnician(), \"recording_additional\": self.getRecordingAdditional(),\n                \"patientname\": self.getPatientName(), \"patient_additional\": self.getPatientAdditional(),\n                \"patientcode\": self.getPatientCode(), \"equipment\": self.getEquipment(),\n                \"admincode\": self.getAdmincode(), \"gender\": self.getGender(), \"startdate\": self.getStartdatetime(),\n                \"birthdate\": self.getBirthdate()}",
    "docstring": "Returns the file header as dict\n\n        Parameters\n        ----------\n        None"
  },
  {
    "code": "def dot(self, w):\n        return sum([x * y for x, y in zip(self, w)])",
    "docstring": "Return the dotproduct between self and another vector."
  },
  {
    "code": "def open_handle(self, dwDesiredAccess = win32.THREAD_ALL_ACCESS):\n        hThread = win32.OpenThread(dwDesiredAccess, win32.FALSE, self.dwThreadId)\n        if not hasattr(self.hThread, '__del__'):\n            self.close_handle()\n        self.hThread = hThread",
    "docstring": "Opens a new handle to the thread, closing the previous one.\n\n        The new handle is stored in the L{hThread} property.\n\n        @warn: Normally you should call L{get_handle} instead, since it's much\n            \"smarter\" and tries to reuse handles and merge access rights.\n\n        @type  dwDesiredAccess: int\n        @param dwDesiredAccess: Desired access rights.\n            Defaults to L{win32.THREAD_ALL_ACCESS}.\n            See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms686769(v=vs.85).aspx}\n\n        @raise WindowsError: It's not possible to open a handle to the thread\n            with the requested access rights. This tipically happens because\n            the target thread belongs to system process and the debugger is not\n            runnning with administrative rights."
  },
  {
    "code": "def read_10x_h5(filename, genome=None, gex_only=True) -> AnnData:\n    logg.info('reading', filename, r=True, end=' ')\n    with tables.open_file(str(filename), 'r') as f:\n        v3 = '/matrix' in f\n    if v3:\n        adata = _read_v3_10x_h5(filename)\n        if genome:\n            if genome not in adata.var['genome'].values:\n                raise ValueError(\n                    \"Could not find data corresponding to genome '{genome}' in '{filename}'. \"\n                    \"Available genomes are: {avail}.\"\n                    .format(\n                        genome=genome, filename=filename,\n                        avail=list(adata.var[\"genome\"].unique()),\n                    )\n                )\n            adata = adata[:, list(map(lambda x: x == str(genome), adata.var['genome']))]\n        if gex_only:\n            adata = adata[:, list(map(lambda x: x == 'Gene Expression', adata.var['feature_types']))]\n        return adata\n    else:\n        return _read_legacy_10x_h5(filename, genome=genome)",
    "docstring": "Read 10x-Genomics-formatted hdf5 file.\n\n    Parameters\n    ----------\n    filename : `str` | :class:`~pathlib.Path`\n        Filename.\n    genome : `str`, optional (default: ``None``)\n        Filter expression to this genes within this genome. For legacy 10x h5\n        files, this must be provided if the data contains more than one genome.\n    gex_only : `bool`, optional (default: `True`)\n        Only keep 'Gene Expression' data and ignore other feature types,\n        e.g. 'Antibody Capture', 'CRISPR Guide Capture', or 'Custom'\n\n    Returns\n    -------\n    Annotated data matrix, where obsevations/cells are named by their\n    barcode and variables/genes by gene name. The data matrix is stored in\n    `adata.X`, cell names in `adata.obs_names` and gene names in\n    `adata.var_names`. The gene IDs are stored in `adata.var['gene_ids']`.\n    The feature types are stored in `adata.var['feature_types']`"
  },
  {
    "code": "def getsubtables(self):\n        keyset = self.getkeywords()\n        names = []\n        for key, value in keyset.items():\n            if isinstance(value, str) and value.find('Table: ') == 0:\n                names.append(_do_remove_prefix(value))\n        return names",
    "docstring": "Get the names of all subtables."
  },
  {
    "code": "def tabSeparatedSummary(self, sortOn=None):\n        result = []\n        for titleSummary in self.summary(sortOn):\n            result.append('\\t'.join([\n                '%(coverage)f',\n                '%(medianScore)f',\n                '%(bestScore)f',\n                '%(readCount)d',\n                '%(hspCount)d',\n                '%(subjectLength)d',\n                '%(subjectTitle)s',\n            ]) % titleSummary)\n        return '\\n'.join(result)",
    "docstring": "Summarize all the alignments for this title as multi-line string with\n        TAB-separated values on each line.\n\n        @param sortOn: A C{str} attribute to sort titles on. One of 'length',\n            'maxScore', 'medianScore', 'readCount', or 'title'.\n        @raise ValueError: If an unknown C{sortOn} value is given.\n        @return: A newline-separated C{str}, each line with a summary of a\n            title. Each summary line is TAB-separated."
  },
  {
    "code": "def get_object(self, request, object_id, *args, **kwargs):\n        obj = super(TranslatableAdmin, self).get_object(request, object_id, *args, **kwargs)\n        if obj is not None and self._has_translatable_model():\n            obj.set_current_language(self._language(request, obj), initialize=True)\n        return obj",
    "docstring": "Make sure the object is fetched in the correct language."
  },
  {
    "code": "def _ParseLastRunTime(self, parser_mediator, fixed_length_section):\n    systemtime_struct = fixed_length_section.last_run_time\n    system_time_tuple = (\n        systemtime_struct.year, systemtime_struct.month,\n        systemtime_struct.weekday, systemtime_struct.day_of_month,\n        systemtime_struct.hours, systemtime_struct.minutes,\n        systemtime_struct.seconds, systemtime_struct.milliseconds)\n    date_time = None\n    if system_time_tuple != self._EMPTY_SYSTEM_TIME_TUPLE:\n      try:\n        date_time = dfdatetime_systemtime.Systemtime(\n            system_time_tuple=system_time_tuple)\n      except ValueError:\n        parser_mediator.ProduceExtractionWarning(\n            'invalid last run time: {0!s}'.format(system_time_tuple))\n    return date_time",
    "docstring": "Parses the last run time from a fixed-length data section.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      fixed_length_section (job_fixed_length_data_section): a Windows\n          Scheduled Task job fixed-length data section.\n\n    Returns:\n      dfdatetime.DateTimeValues: last run date and time or None if not\n          available."
  },
  {
    "code": "def default(self, node):\n        if hasattr(node, 'linestart'):\n            if node.linestart:\n                self.source_linemap[self.current_line_number] = node.linestart\n        return super(LineMapWalker, self).default(node)",
    "docstring": "Augment write default routine to record line number changes"
  },
  {
    "code": "def get_details(cls, node, as_model=False):\n        rest_job = RestJob(\n            process_name=node.process_name,\n            timeperiod=node.timeperiod,\n            time_qualifier=node.time_qualifier,\n            number_of_children=len(node.children),\n            number_of_failures='NA' if not node.job_record else node.job_record.number_of_failures,\n            state='NA' if not node.job_record else node.job_record.state,\n            event_log=[] if not node.job_record else node.job_record.event_log)\n        if as_model:\n            return rest_job\n        else:\n            return rest_job.document",
    "docstring": "method returns either RestJob instance or corresponding document, depending on the as_model argument"
  },
  {
    "code": "def AddTableColumn(self, table, column):\n    if column not in self._table_columns[table]:\n      self._table_columns[table].append(column)",
    "docstring": "Add column to table if it is not already there."
  },
  {
    "code": "def update(self):\n        con = self.subpars.pars.control\n        self(con.eqd1*con.tind)",
    "docstring": "Update |KD1| based on |EQD1| and |TInd|.\n\n        >>> from hydpy.models.lland import *\n        >>> parameterstep('1d')\n        >>> eqd1(0.5)\n        >>> tind.value = 10.0\n        >>> derived.kd1.update()\n        >>> derived.kd1\n        kd1(5.0)"
  },
  {
    "code": "def FetchCompletedRequests(self, session_id, timestamp=None):\n    if timestamp is None:\n      timestamp = (0, self.frozen_timestamp or rdfvalue.RDFDatetime.Now())\n    for request, status in self.data_store.ReadCompletedRequests(\n        session_id, timestamp=timestamp, limit=self.request_limit):\n      yield request, status",
    "docstring": "Fetch all the requests with a status message queued for them."
  },
  {
    "code": "def split(string, callback=None, sep=None):\n    if callback is not None:\n        return [callback(i) for i in string.split(sep)]\n    else:\n        return string.split(sep)",
    "docstring": "Split the string and execute the callback function on each part.\n\n    >>> string = \"1 2 3 4\"\n    >>> parts = split(string, int)\n    >>> parts\n    [1, 2, 3, 4]"
  },
  {
    "code": "def import_submodules(package, recursive=True):\n    if isinstance(package, str):\n        package = importlib.import_module(package)\n    results = {}\n    for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):\n        full_name = package.__name__ + \".\" + name\n        results[name] = importlib.import_module(full_name)\n        if recursive and is_pkg:\n            results.update(import_submodules(full_name))\n    return results",
    "docstring": "Import all submodules of a module, recursively, including subpackages\n\n    :param package: package (name or actual module)\n    :type package: str | module\n    :rtype: dict[str, types.ModuleType]"
  },
  {
    "code": "def pad(self, pad_length):\n        self.pianoroll = np.pad(\n            self.pianoroll, ((0, pad_length), (0, 0)), 'constant')",
    "docstring": "Pad the pianoroll with zeros at the end along the time axis.\n\n        Parameters\n        ----------\n        pad_length : int\n            The length to pad with zeros along the time axis."
  },
  {
    "code": "def delete_set(self, x):\n        if x not in self._parents:\n            return\n        members = list(self.members(x))\n        for v in members:\n            del self._parents[v]\n            del self._weights[v]\n            del self._prev_next[v]\n            del self._min_values[v]",
    "docstring": "Removes the equivalence class containing `x`."
  },
  {
    "code": "def copy_r(src, dst):\n    abssrc = os.path.abspath(src)\n    absdst = os.path.abspath(dst)\n    try:\n        os.makedirs(absdst)\n    except OSError:\n        pass\n    for f in os.listdir(abssrc):\n        fpath = os.path.join(abssrc, f)\n        if os.path.isfile(fpath):\n            shutil.copy(fpath, absdst)\n        elif not absdst.startswith(fpath):\n            copy_r(fpath, os.path.join(absdst, f))\n        else:\n            warnings.warn(\"Cannot copy %s to itself\" % fpath)",
    "docstring": "Implements a recursive copy function similar to Unix's \"cp -r\" command.\n    Surprisingly, python does not have a real equivalent. shutil.copytree\n    only works if the destination directory is not present.\n\n    Args:\n        src (str): Source folder to copy.\n        dst (str): Destination folder."
  },
  {
    "code": "def rdf(self, rdf: Optional[Union[str, Graph]]) -> None:\n        if isinstance(rdf, Graph):\n            self.g = rdf\n        else:\n            self.g = Graph()\n            if isinstance(rdf, str):\n                if '\\n' in rdf or '\\r' in rdf:\n                    self.g.parse(data=rdf, format=self.rdf_format)\n                elif ':' in rdf:\n                    self.g.parse(location=rdf, format=self.rdf_format)\n                else:\n                    self.g.parse(source=rdf, format=self.rdf_format)",
    "docstring": "Set the RDF DataSet to be evaulated.  If ``rdf`` is a string, the presence of a return is the\n        indicator that it is text instead of a location.\n\n        :param rdf: File name, URL, representation of rdflib Graph"
  },
  {
    "code": "def serve_protected_thumbnail(request, path):\n    source_path = thumbnail_to_original_filename(path)\n    if not source_path:\n        raise Http404('File not found')\n    try:\n        file_obj = File.objects.get(file=source_path)\n    except File.DoesNotExist:\n        raise Http404('File not found %s' % path)\n    if not file_obj.has_read_permission(request):\n        if settings.DEBUG:\n            raise PermissionDenied\n        else:\n            raise Http404('File not found %s' % path)\n    try:\n        thumbnail = ThumbnailFile(name=path, storage=file_obj.file.thumbnail_storage)\n        return thumbnail_server.serve(request, thumbnail, save_as=False)\n    except Exception:\n        raise Http404('File not found %s' % path)",
    "docstring": "Serve protected thumbnails to authenticated users.\n    If the user doesn't have read permissions, redirect to a static image."
  },
  {
    "code": "def _compute_global_interested_rts(self):\n        interested_rts = set()\n        for rtfilter in self._peer_to_rtfilter_map.values():\n            interested_rts.update(rtfilter)\n        interested_rts.update(self._vrfs_conf.vrf_interested_rts)\n        interested_rts.add(RouteTargetMembershipNLRI.DEFAULT_RT)\n        interested_rts.remove(RouteTargetMembershipNLRI.DEFAULT_RT)\n        return interested_rts",
    "docstring": "Computes current global interested RTs for global tables.\n\n        Computes interested RTs based on current RT filters for peers. This\n        filter should be used to check if for RTs on a path that is installed\n        in any global table (expect RT Table)."
  },
  {
    "code": "def average(sequence, key):\n    return sum(map(key, sequence)) / float(len(sequence))",
    "docstring": "Averages a sequence based on a key."
  },
  {
    "code": "def custom_scale_mixture_prior_builder(getter, name, *args, **kwargs):\n  del getter\n  del name\n  del args\n  del kwargs\n  return CustomScaleMixture(\n      FLAGS.prior_pi, FLAGS.prior_sigma1, FLAGS.prior_sigma2)",
    "docstring": "A builder for the gaussian scale-mixture prior of Fortunato et al.\n\n  Please see https://arxiv.org/abs/1704.02798, section 7.1\n\n  Args:\n    getter: The `getter` passed to a `custom_getter`. Please see the\n      documentation for `tf.get_variable`.\n    name: The `name` argument passed to `tf.get_variable`.\n    *args: Positional arguments forwarded by `tf.get_variable`.\n    **kwargs: Keyword arguments forwarded by `tf.get_variable`.\n\n  Returns:\n    An instance of `tfp.distributions.Distribution` representing the\n    prior distribution over the variable in question."
  },
  {
    "code": "def upper_camel(string, prefix='', suffix=''):\n    return require_valid(append_underscore_if_keyword(''.join(\n        upper_case_first_char(word)\n        for word in en.words(' '.join([prefix, string, suffix])))\n    ))",
    "docstring": "Generate a camel-case identifier with the first word capitalised.\n    Useful for class names.\n\n    Takes a string, prefix, and optional suffix.\n\n    `prefix` can be set to `''`, though be careful - without a prefix, the\n    function will throw `InvalidIdentifier` when your string starts with a\n    number.\n\n    Example:\n        >>> upper_camel(\"I'm a class\", prefix='')\n        'IAmAClass'"
  },
  {
    "code": "def map_hmms(input_model, mapping):\n    output_model = copy.copy(input_model)\n    o_hmms = []\n    for i_hmm in input_model['hmms']:\n        i_hmm_name = i_hmm['name']\n        o_hmm_names = mapping.get(i_hmm_name, [i_hmm_name])\n        for o_hmm_name in o_hmm_names:\n            o_hmm = copy.copy(i_hmm)\n            o_hmm['name'] = o_hmm_name\n            o_hmms.append(o_hmm)\n    output_model['hmms'] = o_hmms\n    return output_model",
    "docstring": "Create a new HTK HMM model given a model and a mapping dictionary.\n\n    :param input_model: The model to transform of type dict\n    :param mapping: A dictionary from string -> list(string)\n    :return: The transformed model of type dict"
  },
  {
    "code": "def escape(str):\n    out = ''\n    for char in str:\n        if char in '\\\\ ':\n            out += '\\\\'\n        out += char\n    return out",
    "docstring": "Precede all special characters with a backslash."
  },
  {
    "code": "def graph_to_dot(graph, node_renderer=None, edge_renderer=None):\n    node_pairs = list(graph.nodes.items())\n    edge_pairs = list(graph.edges.items())\n    if node_renderer is None:\n        node_renderer_wrapper = lambda nid: ''\n    else:\n        node_renderer_wrapper = lambda nid: ' [%s]' % ','.join(\n            ['%s=%s' % tpl for tpl in list(node_renderer(graph, nid).items())])\n    graph_string = 'digraph G {\\n'\n    graph_string += 'overlap=scale;\\n'\n    for node_id, node in node_pairs:\n        graph_string += '%i%s;\\n' % (node_id, node_renderer_wrapper(node_id))\n    for edge_id, edge in edge_pairs:\n        node_a = edge['vertices'][0]\n        node_b = edge['vertices'][1]\n        graph_string += '%i -> %i;\\n' % (node_a, node_b)\n    graph_string += '}'\n    return graph_string",
    "docstring": "Produces a DOT specification string from the provided graph."
  },
  {
    "code": "def ks_significance(fg_pos, bg_pos=None):\n    p = ks_pvalue(fg_pos, max(fg_pos))\n    if p > 0:\n        return -np.log10(p)\n    else:\n        return np.inf",
    "docstring": "Computes the -log10 of Kolmogorov-Smirnov p-value of position distribution.\n\n    Parameters\n    ----------\n    fg_pos : array_like\n        The list of values for the positive set.\n\n    bg_pos : array_like, optional\n        The list of values for the negative set.\n    \n    Returns\n    -------\n    p : float\n        -log10(KS p-value)."
  },
  {
    "code": "def instantiate_client(_unused_client, _unused_to_delete):\n    from google.cloud import logging\n    client = logging.Client()\n    credentials = object()\n    from google.cloud import logging\n    client = logging.Client(project=\"my-project\", credentials=credentials)",
    "docstring": "Instantiate client."
  },
  {
    "code": "def create_rflink_connection(port=None, host=None, baud=57600, protocol=RflinkProtocol,\n                             packet_callback=None, event_callback=None,\n                             disconnect_callback=None, ignore=None, loop=None):\n    protocol = partial(\n        protocol,\n        loop=loop if loop else asyncio.get_event_loop(),\n        packet_callback=packet_callback,\n        event_callback=event_callback,\n        disconnect_callback=disconnect_callback,\n        ignore=ignore if ignore else [],\n    )\n    if host:\n        conn = loop.create_connection(protocol, host, port)\n    else:\n        baud = baud\n        conn = create_serial_connection(loop, protocol, port, baud)\n    return conn",
    "docstring": "Create Rflink manager class, returns transport coroutine."
  },
  {
    "code": "def new_type(type_name: str, prefix: str or None = None) -> str:\n        if Naming.TYPE_PREFIX in type_name:\n            raise TypeError('Cannot create new type: type {} is already prefixed.'.format(type_name))\n        prefix = (prefix + Naming.TYPE_PREFIX) if prefix is not None else ''\n        return prefix + type_name",
    "docstring": "Creates a resource type with optionally a prefix.\n\n            Using the rules of JSON-LD, we use prefixes to disambiguate between different types with the same name:\n            one can Accept a device or a project. In eReuse.org there are different events with the same names, in\n            linked-data terms they have different URI. In eReuse.org, we solve this with the following:\n\n                \"@type\": \"devices:Accept\" // the URI for these events is 'devices/events/accept'\n                \"@type\": \"projects:Accept\"  // the URI for these events is 'projects/events/accept\n                ...\n\n            Type is only used in events, when there are ambiguities. The rest of\n\n                \"@type\": \"devices:Accept\"\n                \"@type\": \"Accept\"\n\n            But these not:\n\n                \"@type\": \"projects:Accept\"  // it is an event from a project\n                \"@type\": \"Accept\"  // it is an event from a device"
  },
  {
    "code": "def right_shift_blockwise(x, query_shape, name=None):\n  with tf.variable_scope(\n      name, default_name=\"right_shift_blockwise\", values=[x]):\n    x_list_shape = x.get_shape().as_list()\n    x_shape = common_layers.shape_list(x)\n    x = tf.expand_dims(x, axis=1)\n    x = pad_to_multiple_2d(x, query_shape)\n    padded_x_shape = common_layers.shape_list(x)\n    x_indices = gather_indices_2d(x, query_shape, query_shape)\n    x_new = get_shifted_center_blocks(x, x_indices)\n    output = scatter_blocks_2d(x_new, x_indices, padded_x_shape)\n    output = tf.squeeze(output, axis=1)\n    output = tf.slice(output, [0, 0, 0, 0], [-1, x_shape[1], x_shape[2], -1])\n    output.set_shape(x_list_shape)\n    return output",
    "docstring": "Right shifts once in every block.\n\n  Args:\n    x: a tensor of shape [batch, height, width, depth]\n    query_shape: A 2d tuple of ints\n    name: a string\n\n  Returns:\n    output: a tensor of the same shape as x"
  },
  {
    "code": "def get_price(item):\n    the_price = \"No Default Pricing\"\n    for price in item.get('prices', []):\n        if not price.get('locationGroupId'):\n            the_price = \"%0.4f\" % float(price['hourlyRecurringFee'])\n    return the_price",
    "docstring": "Finds the price with the default locationGroupId"
  },
  {
    "code": "def _list_records(self, rtype=None, name=None, content=None):\n        records = [\n            {\n                'id': record['id'],\n                'type': record['type'],\n                'name': self._full_name(record['hostname']),\n                'content': record['destination'],\n                'priority': record['priority'],\n                'ttl': self.zone_ttl,\n            }\n            for record in self._raw_records(None, rtype, name, content)\n        ]\n        LOGGER.debug('list_records: %s', records)\n        return records",
    "docstring": "List all records. Return an empty list if no records found.\n        ``rtype``, ``name`` and ``content`` are used to filter records."
  },
  {
    "code": "def connect(\n    uri=None,\n    user=None,\n    password=None,\n    host=None,\n    port=9091,\n    database=None,\n    protocol='binary',\n    execution_type=EXECUTION_TYPE_CURSOR,\n):\n    client = MapDClient(\n        uri=uri,\n        user=user,\n        password=password,\n        host=host,\n        port=port,\n        database=database,\n        protocol=protocol,\n        execution_type=execution_type,\n    )\n    if options.default_backend is None:\n        options.default_backend = client\n    return client",
    "docstring": "Create a MapDClient for use with Ibis\n\n    Parameters could be\n\n    :param uri: str\n    :param user: str\n    :param password: str\n    :param host: str\n    :param port: int\n    :param database: str\n    :param protocol: str\n    :param execution_type: int\n    Returns\n    -------\n    MapDClient"
  },
  {
    "code": "def get_grade_system_lookup_session(self, proxy):\n        if not self.supports_grade_system_lookup():\n            raise errors.Unimplemented()\n        return sessions.GradeSystemLookupSession(proxy=proxy, runtime=self._runtime)",
    "docstring": "Gets the ``OsidSession`` associated with the grade system lookup service.\n\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.grading.GradeSystemLookupSession) - a\n                ``GradeSystemLookupSession``\n        raise:  NullArgument - ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_grade_system_lookup()`` is\n                ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_grade_system_lookup()`` is ``true``.*"
  },
  {
    "code": "def _parse_result(self, result):\n        u\n        if result is not True:\n            for section, errors in result.iteritems():\n                for key, value in errors.iteritems():\n                    if value is not True:\n                        message = (\n                            '\"{0}\" option in [{1}] is invalid value. {2}'\n                            ''.format(key, section, value)\n                        )\n                        print(message)\n            err_message = (\n                'Some options are invalid!!! Please see the log!!!'\n            )\n            raise validate.ValidateError(err_message)\n        else:\n            return True",
    "docstring": "u\"\"\"\n        This method parses validation results.\n        If result is True, then do nothing.\n        if include even one false to result,\n        this method parse result and raise Exception."
  },
  {
    "code": "def print_lamps():\n    print(\"Printing information about all lamps paired to the Gateway\")\n    lights = [dev for dev in devices if dev.has_light_control]\n    if len(lights) == 0:\n        exit(bold(\"No lamps paired\"))\n    container = []\n    for l in lights:\n        container.append(l.raw)\n    print(jsonify(container))",
    "docstring": "Print all lamp devices as JSON"
  },
  {
    "code": "def text_assert(self, anchor, byte=False):\n        if not self.text_search(anchor, byte=byte):\n            raise DataNotFound(u'Substring not found: %s' % anchor)",
    "docstring": "If `anchor` is not found then raise `DataNotFound` exception."
  },
  {
    "code": "def all_lemmas(self):\n        for lemma_dict in self._mongo_db.lexunits.find():\n            yield Lemma(self, lemma_dict)",
    "docstring": "A generator over all the lemmas in the GermaNet database."
  },
  {
    "code": "def by_geopoint(self, lat, long):\n        header, content = self._http_request(self.BASE_URL, lat=lat, long=long)\t\t\n        return json.loads(content)",
    "docstring": "Perform a Yelp Neighborhood API Search based on a geopoint.\n\n        Args:\n          lat      - geopoint latitude \n          long     - geopoint longitude"
  },
  {
    "code": "def read_ip_ranges(filename, local_file = True, ip_only = False, conditions = []):\n    targets = []\n    data = load_data(filename, local_file = local_file)\n    if 'source' in data:\n        conditions = data['conditions']\n        local_file = data['local_file'] if 'local_file' in data else False\n        data = load_data(data['source'], local_file = local_file, key_name = 'prefixes')\n    else:\n        data = data['prefixes']\n    for d in data:\n        condition_passed = True\n        for condition in conditions:\n            if type(condition) != list or len(condition) < 3:\n                continue\n            condition_passed = pass_condition(d[condition[0]], condition[1], condition[2])\n            if not condition_passed:\n                break\n        if condition_passed:\n            targets.append(d)\n    if ip_only:\n        ips = []\n        for t in targets:\n            ips.append(t['ip_prefix'])\n        return ips\n    else:\n        return targets",
    "docstring": "Returns the list of IP prefixes from an ip-ranges file\n\n    :param filename:\n    :param local_file:\n    :param conditions:\n    :param ip_only:\n    :return:"
  },
  {
    "code": "def do_filter(qs, qdata, quick_query_fields=[], int_quick_query_fields=[]):\n    try:\n        qs = qs.filter(\n            __gen_quick_query_params(\n                qdata.get('q_quick_search_kw'), quick_query_fields,\n                int_quick_query_fields)\n        )\n        q, kw_query_params = __gen_query_params(qdata)\n        qs = qs.filter(q, **kw_query_params)\n    except:\n        import traceback\n        traceback.print_exc()\n    return qs",
    "docstring": "auto filter queryset by dict.\n\n    qs: queryset need to filter.\n    qdata:\n    quick_query_fields:\n    int_quick_query_fields:"
  },
  {
    "code": "def parseRangeString(s, convertToZeroBased=False):\n    result = set()\n    for _range in s.split(','):\n        match = _rangeRegex.match(_range)\n        if match:\n            start, end = match.groups()\n            start = int(start)\n            if end is None:\n                end = start\n            else:\n                end = int(end)\n            if start > end:\n                start, end = end, start\n            if convertToZeroBased:\n                result.update(range(start - 1, end))\n            else:\n                result.update(range(start, end + 1))\n        else:\n            raise ValueError(\n                'Illegal range %r. Ranges must single numbers or '\n                'number-number.' % _range)\n    return result",
    "docstring": "Parse a range string of the form 1-5,12,100-200.\n\n    @param s: A C{str} specifiying a set of numbers, given in the form of\n        comma separated numeric ranges or individual indices.\n    @param convertToZeroBased: If C{True} all indices will have one\n        subtracted from them.\n    @return: A C{set} of all C{int}s in the specified set."
  },
  {
    "code": "def cos(cls, x: 'TensorFluent') -> 'TensorFluent':\n        return cls._unary_op(x, tf.cos, tf.float32)",
    "docstring": "Returns a TensorFluent for the cos function.\n\n        Args:\n            x: The input fluent.\n\n        Returns:\n            A TensorFluent wrapping the cos function."
  },
  {
    "code": "def _downgrade_v1(op):\n    op.drop_index('ix_futures_contracts_root_symbol')\n    op.drop_index('ix_futures_contracts_symbol')\n    with op.batch_alter_table('futures_contracts') as batch_op:\n        batch_op.alter_column(column_name='multiplier',\n                              new_column_name='contract_multiplier')\n        batch_op.drop_column('tick_size')\n    op.create_index('ix_futures_contracts_root_symbol',\n                    table_name='futures_contracts',\n                    columns=['root_symbol'])\n    op.create_index('ix_futures_contracts_symbol',\n                    table_name='futures_contracts',\n                    columns=['symbol'],\n                    unique=True)",
    "docstring": "Downgrade assets db by removing the 'tick_size' column and renaming the\n    'multiplier' column."
  },
  {
    "code": "def contribute_to_class(model_class, name='slots', descriptor=None):\n    rel_obj = descriptor or PlaceholderDescriptor()\n    rel_obj.contribute_to_class(model_class, name)\n    setattr(model_class, name, rel_obj)\n    return True",
    "docstring": "Function that adds a description to a model Class.\n\n    :param model_class: The model class the descriptor is to be added\n    to.\n    :param name: The attribute name the descriptor will be assigned to.\n    :param descriptor: The descriptor instance to be used. If none is\n    specified it will default to\n    ``icekit.plugins.descriptors.PlaceholderDescriptor``.\n    :return: True"
  },
  {
    "code": "def measure(*qubits: raw_types.Qid,\n            key: Optional[str] = None,\n            invert_mask: Tuple[bool, ...] = ()\n            ) -> gate_operation.GateOperation:\n    for qubit in qubits:\n        if isinstance(qubit, np.ndarray):\n            raise ValueError(\n                    'measure() was called a numpy ndarray. Perhaps you meant '\n                    'to call measure_state_vector on numpy array?'\n            )\n        elif not isinstance(qubit, raw_types.Qid):\n            raise ValueError(\n                    'measure() was called with type different than Qid.')\n    if key is None:\n        key = _default_measurement_key(qubits)\n    return MeasurementGate(len(qubits), key, invert_mask).on(*qubits)",
    "docstring": "Returns a single MeasurementGate applied to all the given qubits.\n\n    The qubits are measured in the computational basis.\n\n    Args:\n        *qubits: The qubits that the measurement gate should measure.\n        key: The string key of the measurement. If this is None, it defaults\n            to a comma-separated list of the target qubits' str values.\n        invert_mask: A list of Truthy or Falsey values indicating whether\n            the corresponding qubits should be flipped. None indicates no\n            inverting should be done.\n\n    Returns:\n        An operation targeting the given qubits with a measurement.\n\n    Raises:\n        ValueError if the qubits are not instances of Qid."
  },
  {
    "code": "def commit(self, cont = False):\n        self.journal.close()\n        self.journal = None\n        os.remove(self.j_file)\n        for itm in os.listdir(self.tmp_dir): os.remove(cpjoin(self.tmp_dir, itm))\n        if cont is True: self.begin()",
    "docstring": "Finish a transaction"
  },
  {
    "code": "def to_OrderedDict(self, include_null=True):\n        if include_null:\n            return OrderedDict(self.items())\n        else:\n            items = list()\n            for c in self.__table__._columns:\n                try:\n                    items.append((c.name, self.__dict__[c.name]))\n                except KeyError:\n                    pass\n            return OrderedDict(items)",
    "docstring": "Convert to OrderedDict."
  },
  {
    "code": "def post(self, *args, **kwargs):\n        try:\n            resp = self.session.post(*args, **kwargs)\n            if resp.status_code in _EXCEPTIONS_BY_CODE:\n                raise _EXCEPTIONS_BY_CODE[resp.status_code](resp.reason)\n            if resp.status_code != requests.codes['ok']:\n                raise exceptions.Etcd3Exception(resp.reason)\n        except requests.exceptions.Timeout as ex:\n            raise exceptions.ConnectionTimeoutError(six.text_type(ex))\n        except requests.exceptions.ConnectionError as ex:\n            raise exceptions.ConnectionFailedError(six.text_type(ex))\n        return resp.json()",
    "docstring": "helper method for HTTP POST\n\n        :param args:\n        :param kwargs:\n        :return: json response"
  },
  {
    "code": "def _get_symbol_by_slope(\n        self,\n        slope,\n        default_symbol\n        ):\n        if slope > math.tan(3 * math.pi / 8):\n            draw_symbol = \"|\"\n        elif math.tan(math.pi / 8) < slope < math.tan(3 * math.pi / 8):\n            draw_symbol = u\"\\u27cb\"\n        elif abs(slope) < math.tan(math.pi / 8):\n            draw_symbol = \"-\"\n        elif slope < math.tan(-math.pi / 8) and\\\n            slope > math.tan(-3 * math.pi / 8):\n            draw_symbol = u\"\\u27CD\"\n        elif slope < math.tan(-3 * math.pi / 8):\n            draw_symbol = \"|\"\n        else:\n            draw_symbol = default_symbol\n        return draw_symbol",
    "docstring": "return line oriented approximatively along the slope value"
  },
  {
    "code": "def memory_read8(self, addr, num_bytes, zone=None):\n        return self.memory_read(addr, num_bytes, zone=zone, nbits=8)",
    "docstring": "Reads memory from the target system in units of bytes.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          addr (int): start address to read from\n          num_bytes (int): number of bytes to read\n          zone (str): memory zone to read from\n\n        Returns:\n          List of bytes read from the target system.\n\n        Raises:\n          JLinkException: if memory could not be read."
  },
  {
    "code": "def get_driver_config(driver):\n    response = errorIfUnauthorized(role='admin')\n    if response:\n        return response\n    else:\n        response = ApitaxResponse()\n    return Response(status=200, body=response.getResponseBody())",
    "docstring": "Retrieve the config of a loaded driver\n\n    Retrieve the config of a loaded driver # noqa: E501\n\n    :param driver: The driver to use for the request. ie. github\n    :type driver: str\n\n    :rtype: Response"
  },
  {
    "code": "def validate(self, value, redis):\n        value = super().validate(value, redis)\n        if is_hashed(value):\n            return value\n        return make_password(value)",
    "docstring": "hash passwords given via http"
  },
  {
    "code": "def sync(self):\n        xbin = self.xbin.value()\n        ybin = self.ybin.value()\n        n = 0\n        for xsl, xsr, ys, nx, ny in self:\n            if xbin > 1:\n                xsl = xbin*((xsl-1)//xbin)+1\n                self.xsl[n].set(xsl)\n                xsr = xbin*((xsr-1025)//xbin)+1025\n                self.xsr[n].set(xsr)\n            if ybin > 1:\n                ys = ybin*((ys-1)//ybin)+1\n                self.ys[n].set(ys)\n            n += 1\n        g = get_root(self).globals\n        self.sbutt.config(bg=g.COL['main'])\n        self.sbutt.config(state='disable')",
    "docstring": "Synchronise the settings. This means that the pixel start\n        values are shifted downwards so that they are synchronised\n        with a full-frame binned version. This does nothing if the\n        binning factors == 1."
  },
  {
    "code": "def download_all(self, urls, dir_path):\n        filenames = []\n        try:\n            for url in urls:\n                filenames.append(self.download(url, dir_path))\n        except DownloadError as e:\n            for filename in filenames:\n                os.remove(filename)\n            raise e\n        return filenames",
    "docstring": "Download all the resources specified by urls into dir_path. The resulting\n            file paths is returned.\n\n            DownloadError is raised if at least one of the resources cannot be downloaded.\n            In the case already downloaded resources are erased."
  },
  {
    "code": "def from_array(array):\n        if array is None or not array:\n            return None\n        assert_type_or_raise(array, dict, parameter_name=\"array\")\n        data = {}\n        data['file_id'] = u(array.get('file_id'))\n        data['length'] = int(array.get('length'))\n        data['duration'] = int(array.get('duration'))\n        data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None\n        data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None\n        data['_raw'] = array\n        return VideoNote(**data)",
    "docstring": "Deserialize a new VideoNote from a given dictionary.\n\n        :return: new VideoNote instance.\n        :rtype: VideoNote"
  },
  {
    "code": "def is_type_sub_type_of(\n    schema: GraphQLSchema, maybe_subtype: GraphQLType, super_type: GraphQLType\n) -> bool:\n    if maybe_subtype is super_type:\n        return True\n    if is_non_null_type(super_type):\n        if is_non_null_type(maybe_subtype):\n            return is_type_sub_type_of(\n                schema,\n                cast(GraphQLNonNull, maybe_subtype).of_type,\n                cast(GraphQLNonNull, super_type).of_type,\n            )\n        return False\n    elif is_non_null_type(maybe_subtype):\n        return is_type_sub_type_of(\n            schema, cast(GraphQLNonNull, maybe_subtype).of_type, super_type\n        )\n    if is_list_type(super_type):\n        if is_list_type(maybe_subtype):\n            return is_type_sub_type_of(\n                schema,\n                cast(GraphQLList, maybe_subtype).of_type,\n                cast(GraphQLList, super_type).of_type,\n            )\n        return False\n    elif is_list_type(maybe_subtype):\n        return False\n    if (\n        is_abstract_type(super_type)\n        and is_object_type(maybe_subtype)\n        and schema.is_possible_type(\n            cast(GraphQLAbstractType, super_type),\n            cast(GraphQLObjectType, maybe_subtype),\n        )\n    ):\n        return True\n    return False",
    "docstring": "Check whether a type is subtype of another type in a given schema.\n\n    Provided a type and a super type, return true if the first type is either equal or\n    a subset of the second super type (covariant)."
  },
  {
    "code": "def age(self):\n        if self.exists:\n            return datetime.utcnow() - datetime.utcfromtimestamp(os.path.getmtime(self.name))\n        return timedelta()",
    "docstring": "Age of the video"
  },
  {
    "code": "def create_module(module, target):\n    module_x = module.split('.')\n    cur_path = ''\n    for path in module_x:\n        cur_path = os.path.join(cur_path, path)\n        if not os.path.isdir(os.path.join(target, cur_path)):\n            os.mkdir(os.path.join(target, cur_path))\n        if not os.path.exists(os.path.join(target, cur_path, '__init__.py')):\n            touch(os.path.join(target, cur_path, '__init__.py'))\n    return cur_path",
    "docstring": "Create a module directory structure into the target directory."
  },
  {
    "code": "def chunks(seq, size):\n    return (seq[pos:pos + size] for pos in range(0, len(seq), size))",
    "docstring": "simple two-line alternative to `ubelt.chunks`"
  },
  {
    "code": "def _get_all_relationships(self):\n        relationships_all = set()\n        for goterm in self.go2obj.values():\n            if goterm.relationship:\n                relationships_all.update(goterm.relationship)\n            if goterm.relationship_rev:\n                relationships_all.update(goterm.relationship_rev)\n        return relationships_all",
    "docstring": "Return all relationships seen in GO Dag subset."
  },
  {
    "code": "def consumer_commit_for_times(consumer, partition_to_offset, atomic=False):\n    no_offsets = set()\n    for tp, offset in six.iteritems(partition_to_offset):\n        if offset is None:\n            logging.error(\n                \"No offsets found for topic-partition {tp}. Either timestamps not supported\"\n                \" for the topic {tp}, or no offsets found after timestamp specified, or there is no\"\n                \" data in the topic-partition.\".format(tp=tp),\n            )\n            no_offsets.add(tp)\n    if atomic and len(no_offsets) > 0:\n        logging.error(\n            \"Commit aborted; offsets were not found for timestamps in\"\n            \" topics {}\".format(\",\".join([str(tp) for tp in no_offsets])),\n        )\n        return\n    offsets_metadata = {\n        tp: OffsetAndMetadata(partition_to_offset[tp].offset, metadata=None)\n        for tp in six.iterkeys(partition_to_offset) if tp not in no_offsets\n    }\n    if len(offsets_metadata) != 0:\n        consumer.commit(offsets_metadata)",
    "docstring": "Commits offsets to Kafka using the given KafkaConsumer and offsets, a mapping\n    of TopicPartition to Unix Epoch milliseconds timestamps.\n\n    Arguments:\n        consumer (KafkaConsumer): an initialized kafka-python consumer.\n        partitions_to_offset (dict TopicPartition: OffsetAndTimestamp): Map of TopicPartition to OffsetAndTimestamp. Return value of offsets_for_times.\n        atomic (bool): Flag to specify whether the commit should fail if offsets are not found for some\n            TopicPartition: timestamp pairs."
  },
  {
    "code": "def post_file(self, url, filename, file_stream, *args, **kwargs):\n        res = self._conn.post(url, files={filename: file_stream},\n                              headers=self._prepare_headers(**kwargs))\n        if res.status_code == 200 or res.status_code == 201:\n            return res.text\n        else:\n            return None",
    "docstring": "Uploads file to provided url.\n\n        Returns contents as text\n\n        Args:\n            **url**: address where to upload file\n\n            **filename**: Name of the uploaded file\n\n            **file_stream**: file like object to upload\n\n            .. versionadded:: 0.3.2\n                **additional_headers**: (optional) Additional headers\n                to be used with request\n\n        Returns:\n            string"
  },
  {
    "code": "def guess_github_repo():\n    p = subprocess.run(['git', 'ls-remote', '--get-url', 'origin'],\n        stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)\n    if p.stderr or p.returncode:\n        return False\n    url = p.stdout.decode('utf-8').strip()\n    m = GIT_URL.fullmatch(url)\n    if not m:\n        return False\n    return m.group(1)",
    "docstring": "Guesses the github repo for the current directory\n\n    Returns False if no guess can be made."
  },
  {
    "code": "def create_entry(self, group, **kwargs):\n        if group not in self.groups:\n            raise ValueError(\"Group doesn't exist / is not bound to this database.\")\n        uuid = binascii.hexlify(get_random_bytes(16))\n        entry = Entry(uuid=uuid,\n                      group_id=group.id,\n                      created=util.now(),\n                      modified=util.now(),\n                      accessed=util.now(),\n                      **kwargs)\n        self.entries.append(entry)\n        group.entries.append(entry)\n        return entry",
    "docstring": "Create a new Entry object.\n        \n        The group which should hold the entry is needed.\n\n        image must be an unsigned int >0, group a Group.\n        \n        :param group: The associated group.\n        :keyword title: \n        :keyword icon:\n        :keyword url:\n        :keyword username:\n        :keyword password:\n        :keyword notes:\n        :keyword expires: Expiration date (if None, entry will never expire). \n        :type expires: datetime\n         \n        :return: The new entry.\n        :rtype: :class:`keepassdb.model.Entry`"
  },
  {
    "code": "def intersection(self, *others, **kwargs):\n        return self._combine_variant_collections(\n            combine_fn=set.intersection,\n            variant_collections=(self,) + others,\n            kwargs=kwargs)",
    "docstring": "Returns the intersection of variants in several VariantCollection objects."
  },
  {
    "code": "def get_services_health(self) -> dict:\n        services_health = {}\n        services_ids = self._get_services()\n        for service_id in services_ids:\n            service_name = DC.get_service_name(service_id)\n            if DC.get_replicas(service_id) != \\\n                    DC.get_actual_replica(service_id):\n                services_health[service_name] = \"Unhealthy\"\n            else:\n                services_health[service_name] = \"Healthy\"\n        return services_health",
    "docstring": "Get the health of all services.\n\n        Returns:\n            dict, services id and health status"
  },
  {
    "code": "def text(self, selector):\n        result = self.__bs4.select(selector)\n        return [r.get_text() for r in result] \\\n            if result.__len__() > 1 else \\\n            result[0].get_text() if result.__len__() > 0 else None",
    "docstring": "Return text result that executed by given css selector\n\n        :param selector: `str` css selector\n        :return: `list` or `None`"
  },
  {
    "code": "def get_readable_time_string(seconds):\n    seconds = int(seconds)\n    minutes = seconds // 60\n    seconds = seconds % 60\n    hours = minutes // 60\n    minutes = minutes % 60\n    days = hours // 24\n    hours = hours % 24\n    result = \"\"\n    if days > 0:\n        result += \"%d %s \" % (days, \"Day\" if (days == 1) else \"Days\")\n    if hours > 0:\n        result += \"%d %s \" % (hours, \"Hour\" if (hours == 1) else \"Hours\")\n    if minutes > 0:\n        result += \"%d %s \" % (minutes, \"Minute\" if (minutes == 1) else \"Minutes\")\n    if seconds > 0:\n        result += \"%d %s \" % (seconds, \"Second\" if (seconds == 1) else \"Seconds\")\n    return result.strip()",
    "docstring": "Returns human readable string from number of seconds"
  },
  {
    "code": "def walk_nodes(self, node, original):\n        try:\n            nodelist = self.parser.get_nodelist(node, original=original)\n        except TypeError:\n            nodelist = self.parser.get_nodelist(node, original=original, context=None)\n        for node in nodelist:\n            if isinstance(node, SassSrcNode):\n                if node.is_sass:\n                    yield node\n            else:\n                for node in self.walk_nodes(node, original=original):\n                    yield node",
    "docstring": "Iterate over the nodes recursively yielding the templatetag 'sass_src'"
  },
  {
    "code": "def get(self, id, **options):\n        if not self._item_path:\n            raise AttributeError('get is not available for %s' % self._item_name)\n        target = self._item_path % id\n        json_data = self._redmine.get(target, **options)\n        data = self._redmine.unwrap_json(self._item_type, json_data)\n        data['_source_path'] = target\n        return self._objectify(data=data)",
    "docstring": "Get a single item with the given ID"
  },
  {
    "code": "def check(text):\n    err = \"misc.suddenly\"\n    msg = u\"Suddenly is nondescript, slows the action, and warns your reader.\"\n    regex = \"Suddenly,\"\n    return existence_check(text, [regex], err, msg, max_errors=3,\n                           require_padding=False, offset=-1, ignore_case=False)",
    "docstring": "Advice on sudden vs suddenly."
  },
  {
    "code": "def get_cloud_from_metadata_endpoint(arm_endpoint, name=None, session=None):\n    cloud = Cloud(name or arm_endpoint)\n    cloud.endpoints.management = arm_endpoint\n    cloud.endpoints.resource_manager = arm_endpoint\n    _populate_from_metadata_endpoint(cloud, arm_endpoint, session)\n    return cloud",
    "docstring": "Get a Cloud object from an ARM endpoint.\n\n    .. versionadded:: 0.4.11\n\n    :Example:\n\n    .. code:: python\n\n        get_cloud_from_metadata_endpoint(https://management.azure.com/, \"Public Azure\")\n\n    :param str arm_endpoint: The ARM management endpoint\n    :param str name: An optional name for the Cloud object. Otherwise it's the ARM endpoint\n    :params requests.Session session: A requests session object if you need to configure proxy, cert, etc.\n    :rtype Cloud:\n    :returns: a Cloud object\n    :raises: MetadataEndpointError if unable to build the Cloud object"
  },
  {
    "code": "def process_part(self, char):\n        if char in self.whitespace or char == self.eol_char:\n            self.parts.append( ''.join(self.part) )\n            self.part = []\n            self.process_char = self.process_delimiter\n            if char == self.eol_char:\n                self.complete = True\n            return\n        if char in self.quote_chars:\n            self.inquote = char\n            self.process_char = self.process_quote\n            return\n        self.part.append(char)",
    "docstring": "Process chars while in a part"
  },
  {
    "code": "def reverse(self, lon, lat, types=None, limit=None):\n        uri = URITemplate(self.baseuri + '/{dataset}/{lon},{lat}.json').expand(\n            dataset=self.name,\n            lon=str(round(float(lon), self.precision.get('reverse', 5))),\n            lat=str(round(float(lat), self.precision.get('reverse', 5))))\n        params = {}\n        if types:\n            types = list(types)\n            params.update(self._validate_place_types(types))\n        if limit is not None:\n            if not types or len(types) != 1:\n                raise InvalidPlaceTypeError(\n                    'Specify a single type when using limit with reverse geocoding')\n            params.update(limit='{0}'.format(limit))\n        resp = self.session.get(uri, params=params)\n        self.handle_http_error(resp)\n        def geojson():\n            return resp.json()\n        resp.geojson = geojson\n        return resp",
    "docstring": "Returns a Requests response object that contains a GeoJSON\n        collection of places near the given longitude and latitude.\n\n        `response.geojson()` returns the geocoding result as GeoJSON.\n        `response.status_code` returns the HTTP API status code.\n\n        See: https://www.mapbox.com/api-documentation/search/#reverse-geocoding."
  },
  {
    "code": "def _setuintbe(self, uintbe, length=None):\n        if length is not None and length % 8 != 0:\n            raise CreationError(\"Big-endian integers must be whole-byte. \"\n                                \"Length = {0} bits.\", length)\n        self._setuint(uintbe, length)",
    "docstring": "Set the bitstring to a big-endian unsigned int interpretation."
  },
  {
    "code": "def output(id, url):\n    try:\n        experiment = ExperimentClient().get(normalize_job_name(id))\n    except FloydException:\n        experiment = ExperimentClient().get(id)\n    output_dir_url = \"%s/%s/files\" % (floyd.floyd_web_host, experiment.name)\n    if url:\n        floyd_logger.info(output_dir_url)\n    else:\n        floyd_logger.info(\"Opening output path in your browser ...\")\n        webbrowser.open(output_dir_url)",
    "docstring": "View the files from a job."
  },
  {
    "code": "def getFeatureById(self, featureId):\n        sql = \"SELECT * FROM FEATURE WHERE id = ?\"\n        query = self._dbconn.execute(sql, (featureId,))\n        ret = query.fetchone()\n        if ret is None:\n            return None\n        return sqlite_backend.sqliteRowToDict(ret)",
    "docstring": "Fetch feature by featureID.\n\n        :param featureId: the FeatureID as found in GFF3 records\n        :return: dictionary representing a feature object,\n            or None if no match is found."
  },
  {
    "code": "def op_match_funcdef_handle(self, original, loc, tokens):\n        if len(tokens) == 3:\n            func, args = get_infix_items(tokens)\n            cond = None\n        elif len(tokens) == 4:\n            func, args = get_infix_items(tokens[:-1])\n            cond = tokens[-1]\n        else:\n            raise CoconutInternalException(\"invalid infix match function definition tokens\", tokens)\n        name_tokens = [func, args]\n        if cond is not None:\n            name_tokens.append(cond)\n        return self.name_match_funcdef_handle(original, loc, name_tokens)",
    "docstring": "Process infix match defs. Result must be passed to insert_docstring_handle."
  },
  {
    "code": "def _get_timezone(self, root):\n        tz_str = root.xpath('//div[@class=\"smallfont\" and @align=\"center\"]')[0].text\n        hours = int(self._tz_re.search(tz_str).group(1))\n        return tzoffset(tz_str, hours * 60)",
    "docstring": "Find timezone informatation on bottom of the page."
  },
  {
    "code": "def from_coo(cls, obj, vartype=None):\n        import dimod.serialization.coo as coo\n        if isinstance(obj, str):\n            return coo.loads(obj, cls=cls, vartype=vartype)\n        return coo.load(obj, cls=cls, vartype=vartype)",
    "docstring": "Deserialize a binary quadratic model from a COOrdinate_ format encoding.\n\n        .. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO)\n\n        Args:\n            obj: (str/file):\n                Either a string or a `.read()`-supporting `file object`_ that represents\n                linear and quadratic biases for a binary quadratic model. This data\n                is stored as a list of 3-tuples, (i, j, bias), where :math:`i=j`\n                for linear biases.\n\n            vartype (:class:`.Vartype`/str/set, optional):\n                Variable type for the binary quadratic model. Accepted input values:\n\n                * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n                * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n                If not provided, the vartype must be specified with a header in the\n                file.\n\n        .. _file object: https://docs.python.org/3/glossary.html#term-file-object\n\n        .. note:: Variables must use index lables (numeric lables). Binary quadratic\n            models created from COOrdinate format encoding have offsets set to\n            zero.\n\n        Examples:\n            An example of a binary quadratic model encoded in COOrdinate format.\n\n            .. code-block:: none\n\n                0 0 0.50000\n                0 1 0.50000\n                1 1 -1.50000\n\n            The Coordinate format with a header\n\n            .. code-block:: none\n\n                # vartype=SPIN\n                0 0 0.50000\n                0 1 0.50000\n                1 1 -1.50000\n\n            This example saves a binary quadratic model to a COOrdinate-format file\n            and creates a new model by reading the saved file.\n\n            >>> import dimod\n            >>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.BINARY)\n            >>> with open('tmp.qubo', 'w') as file:      # doctest: +SKIP\n            ...     bqm.to_coo(file)\n            >>> with open('tmp.qubo', 'r') as file:      # doctest: +SKIP\n            ...     new_bqm = dimod.BinaryQuadraticModel.from_coo(file, dimod.BINARY)\n            >>> any(new_bqm)        # doctest: +SKIP\n            True"
  },
  {
    "code": "def hide_object(self, key, hide=True):\n        self.object_queue.put(SlipHideObject(key, hide))",
    "docstring": "hide an object on the map by key"
  },
  {
    "code": "def get_task(config):\n    path = os.path.join(config['work_dir'], \"task.json\")\n    message = \"Can't read task from {}!\\n%(exc)s\".format(path)\n    contents = load_json_or_yaml(path, is_path=True, message=message)\n    return contents",
    "docstring": "Read the task.json from work_dir.\n\n    Args:\n        config (dict): the running config, to find work_dir.\n\n    Returns:\n        dict: the contents of task.json\n\n    Raises:\n        ScriptWorkerTaskException: on error."
  },
  {
    "code": "def get_airport_metars_hist(self, iata):\n        url = AIRPORT_BASE.format(iata) + \"/weather\"\n        return self._fr24.get_airport_metars_hist(url)",
    "docstring": "Retrieve the metar data for past 72 hours. The data will not be parsed to readable format.\n\n        Given the IATA code of an airport, this method returns the metar information for last 72 hours.\n\n        Args:\n            iata (str): The IATA code for an airport, e.g. HYD\n\n        Returns:\n            The metar data for the airport\n\n        Example::\n\n            from pyflightdata import FlightData\n            f=FlightData()\n            #optional login\n            f.login(myemail,mypassword)\n            f.get_airport_metars_hist('HYD')"
  },
  {
    "code": "def report_open_file(self, options):\r\n        filename = options['filename']\r\n        logger.debug('Call LSP for %s' % filename)\r\n        language = options['language']\r\n        callback = options['codeeditor']\r\n        stat = self.main.lspmanager.start_client(language.lower())\r\n        self.main.lspmanager.register_file(\r\n            language.lower(), filename, callback)\r\n        if stat:\r\n            if language.lower() in self.lsp_editor_settings:\r\n                self.lsp_server_ready(\r\n                    language.lower(), self.lsp_editor_settings[\r\n                        language.lower()])\r\n            else:\r\n                editor = self.get_current_editor()\r\n                editor.lsp_ready = False",
    "docstring": "Request to start a LSP server to attend a language."
  },
  {
    "code": "def to_string(mnemonic):\n        strings = {\n            ReilMnemonic.ADD: \"add\",\n            ReilMnemonic.SUB: \"sub\",\n            ReilMnemonic.MUL: \"mul\",\n            ReilMnemonic.DIV: \"div\",\n            ReilMnemonic.MOD: \"mod\",\n            ReilMnemonic.BSH: \"bsh\",\n            ReilMnemonic.AND: \"and\",\n            ReilMnemonic.OR:  \"or\",\n            ReilMnemonic.XOR: \"xor\",\n            ReilMnemonic.LDM: \"ldm\",\n            ReilMnemonic.STM: \"stm\",\n            ReilMnemonic.STR: \"str\",\n            ReilMnemonic.BISZ: \"bisz\",\n            ReilMnemonic.JCC:  \"jcc\",\n            ReilMnemonic.UNKN:  \"unkn\",\n            ReilMnemonic.UNDEF: \"undef\",\n            ReilMnemonic.NOP:   \"nop\",\n            ReilMnemonic.SEXT: \"sext\",\n            ReilMnemonic.SDIV: \"sdiv\",\n            ReilMnemonic.SMOD: \"smod\",\n            ReilMnemonic.SMUL: \"smul\",\n        }\n        return strings[mnemonic]",
    "docstring": "Return the string representation of the given mnemonic."
  },
  {
    "code": "def vcard(self, qs):\n        try:\n            import vobject\n        except ImportError:\n            print(self.style.ERROR(\"Please install vobject to use the vcard export format.\"))\n            sys.exit(1)\n        out = sys.stdout\n        for ent in qs:\n            card = vobject.vCard()\n            card.add('fn').value = full_name(**ent)\n            if not ent['last_name'] and not ent['first_name']:\n                card.add('n').value = vobject.vcard.Name(full_name(**ent))\n            else:\n                card.add('n').value = vobject.vcard.Name(ent['last_name'], ent['first_name'])\n            emailpart = card.add('email')\n            emailpart.value = ent['email']\n            emailpart.type_param = 'INTERNET'\n            out.write(card.serialize())",
    "docstring": "VCARD format."
  },
  {
    "code": "def build_act(cls: Type[_Block], node: ast.stmt, test_func_node: ast.FunctionDef) -> _Block:\n        add_node_parents(test_func_node)\n        act_block_node = node\n        while act_block_node.parent != test_func_node:\n            act_block_node = act_block_node.parent\n        return cls([act_block_node], LineType.act)",
    "docstring": "Act block is a single node - either the act node itself, or the node\n        that wraps the act node."
  },
  {
    "code": "def _parse_row(row):\n        data = []\n        labels = HtmlTable._get_row_tag(row, \"th\")\n        if labels:\n            data += labels\n        columns = HtmlTable._get_row_tag(row, \"td\")\n        if columns:\n            data += columns\n        return data",
    "docstring": "Parses HTML row\n\n        :param row: HTML row\n        :return: list of values in row"
  },
  {
    "code": "def HandlePeerInfoReceived(self, payload):\n        addrs = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.AddrPayload.AddrPayload')\n        if not addrs:\n            return\n        for nawt in addrs.NetworkAddressesWithTime:\n            self.leader.RemoteNodePeerReceived(nawt.Address, nawt.Port, self.prefix)",
    "docstring": "Process response of `self.RequestPeerInfo`."
  },
  {
    "code": "def update(self, notification_level):\n        data = values.of({'NotificationLevel': notification_level, })\n        payload = self._version.update(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return UserChannelInstance(\n            self._version,\n            payload,\n            service_sid=self._solution['service_sid'],\n            user_sid=self._solution['user_sid'],\n            channel_sid=self._solution['channel_sid'],\n        )",
    "docstring": "Update the UserChannelInstance\n\n        :param UserChannelInstance.NotificationLevel notification_level: The push notification level to assign to the User Channel\n\n        :returns: Updated UserChannelInstance\n        :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance"
  },
  {
    "code": "def octaves(freq, fmin=20., fmax=2e4):\n  if any(f <= 0 for f in (freq, fmin, fmax)):\n    raise ValueError(\"Frequencies have to be positive\")\n  while freq < fmin:\n    freq *= 2\n  while freq > fmax:\n    freq /= 2\n  if freq < fmin:\n    return []\n  return list(it.takewhile(lambda x: x > fmin,\n                           (freq * 2 ** harm for harm in it.count(0, -1))\n                          ))[::-1] \\\n       + list(it.takewhile(lambda x: x < fmax,\n                           (freq * 2 ** harm for harm in it.count(1))\n                          ))",
    "docstring": "Given a frequency and a frequency range, returns all frequencies in that\n  range that is an integer number of octaves related to the given frequency.\n\n  Parameters\n  ----------\n  freq :\n    Frequency, in any (linear) unit.\n  fmin, fmax :\n    Frequency range, in the same unit of ``freq``. Defaults to 20.0 and\n    20,000.0, respectively.\n\n  Returns\n  -------\n  A list of frequencies, in the same unit of ``freq`` and in ascending order.\n\n  Examples\n  --------\n  >>> from audiolazy import octaves, sHz\n  >>> octaves(440.)\n  [27.5, 55.0, 110.0, 220.0, 440.0, 880.0, 1760.0, 3520.0, 7040.0, 14080.0]\n  >>> octaves(440., fmin=3000)\n  [3520.0, 7040.0, 14080.0]\n  >>> Hz = sHz(44100)[1] # Conversion unit from sample rate\n  >>> freqs = octaves(440 * Hz, fmin=300 * Hz, fmax = 1000 * Hz) # rad/sample\n  >>> len(freqs) # Number of octaves\n  2\n  >>> [round(f, 6) for f in freqs] # Values in rad/sample\n  [0.062689, 0.125379]\n  >>> [round(f / Hz, 6) for f in freqs] # Values in Hz\n  [440.0, 880.0]"
  },
  {
    "code": "def getPhysicalAddress(self, length=512):\n        name = ctypes.create_string_buffer(length)\n        self._ioctl(_HIDIOCGRAWPHYS(length), name, True)\n        return name.value",
    "docstring": "Returns device physical address as a string.\n        See hidraw documentation for value signification, as it depends on\n        device's bus type."
  },
  {
    "code": "def head(self, *args, **kwargs):\n        self.model = self.get_model(kwargs.get('id'))\n        result = yield self.model.fetch()\n        if not result:\n            self.not_found()\n            return\n        if not self.has_read_permission():\n            self.permission_denied()\n            return\n        self.add_headers()\n        self.set_status(200)\n        self.finish()",
    "docstring": "Handle HEAD requests for the item\n\n        :param args:\n        :param kwargs:"
  },
  {
    "code": "def save_image(image, local_filename):\n    r_name, __, i_name = image.rpartition('/')\n    i_name, __, __ = i_name.partition(':')\n    with temp_dir() as remote_tmp:\n        archive = posixpath.join(remote_tmp, 'image_{0}.tar.gz'.format(i_name))\n        run('docker save {0} | gzip --stdout > {1}'.format(image, archive), shell=False)\n        get(archive, local_filename)",
    "docstring": "Saves a Docker image as a compressed tarball. This command line client method is a suitable alternative, if the\n    Remove API method is too slow.\n\n    :param image: Image id or tag.\n    :type image: unicode\n    :param local_filename: Local file name to store the image into. If this is a directory, the image will be stored\n      there as a file named ``image_<Image name>.tar.gz``."
  },
  {
    "code": "def df2list(df):\n    subjects = df.index.levels[0].values.tolist()\n    lists = df.index.levels[1].values.tolist()\n    idx = pd.IndexSlice\n    df = df.loc[idx[subjects,lists],df.columns]\n    lst = [df.loc[sub,:].values.tolist() for sub in subjects]\n    return lst",
    "docstring": "Convert a MultiIndex df to list\n\n    Parameters\n    ----------\n\n    df : pandas.DataFrame\n        A MultiIndex DataFrame where the first level is subjects and the second\n        level is lists (e.g. egg.pres)\n\n    Returns\n    ----------\n\n    lst : a list of lists of lists of values\n        The input df reformatted as a list"
  },
  {
    "code": "def pickle_loads(cls, s):\n        strio = StringIO()\n        strio.write(s)\n        strio.seek(0)\n        flow = pmg_pickle_load(strio)\n        return flow",
    "docstring": "Reconstruct the flow from a string."
  },
  {
    "code": "def _getInstrumentsVoc(self):\n        cfilter = {'portal_type': 'Instrument', 'is_active': True}\n        if self.getMethod():\n            cfilter['getMethodUIDs'] = {\"query\": self.getMethod().UID(),\n                                        \"operator\": \"or\"}\n        bsc = getToolByName(self, 'bika_setup_catalog')\n        items = [('', 'No instrument')] + [\n            (o.UID, o.Title) for o in\n            bsc(cfilter)]\n        o = self.getInstrument()\n        if o and o.UID() not in [i[0] for i in items]:\n            items.append((o.UID(), o.Title()))\n        items.sort(lambda x, y: cmp(x[1], y[1]))\n        return DisplayList(list(items))",
    "docstring": "This function returns the registered instruments in the system as a\n        vocabulary. The instruments are filtered by the selected method."
  },
  {
    "code": "def on_helpButton(self, event, page=None):\n        path = find_pmag_dir.get_pmag_dir()\n        help_page = os.path.join(path, 'dialogs', 'help_files', page)\n        if not os.path.exists(help_page):\n            help_page = os.path.join(path, 'help_files', page)\n        html_frame = pw.HtmlFrame(self, page=help_page)\n        html_frame.Show()",
    "docstring": "shows html help page"
  },
  {
    "code": "def save_hash(self, location, basedir, ext=None):\n        if isinstance(location, six.text_type):\n            location = location.encode('utf-8')\n        rel_path = hashed_path(location, ext=ext)\n        path = os.path.join(basedir, rel_path)\n        if not os.path.exists(path):\n            path_dir, _ = os.path.split(path)\n            try:\n                os.makedirs(path_dir)\n            except OSError:\n                pass\n            with open(path, 'wb') as out:\n                out.write(self._bytes_body)\n        return rel_path",
    "docstring": "Save response body into file with special path\n        builded from hash. That allows to lower number of files\n        per directory.\n\n        :param location: URL of file or something else. It is\n            used to build the SHA1 hash.\n        :param basedir: base directory to save the file. Note that\n            file will not be saved directly to this directory but to\n            some sub-directory of `basedir`\n        :param ext: extension which should be appended to file name. The\n            dot is inserted automatically between filename and extension.\n        :returns: path to saved file relative to `basedir`\n\n        Example::\n\n            >>> url = 'http://yandex.ru/logo.png'\n            >>> g.go(url)\n            >>> g.response.save_hash(url, 'some_dir', ext='png')\n            'e8/dc/f2918108788296df1facadc975d32b361a6a.png'\n            # the file was saved to $PWD/some_dir/e8/dc/...\n\n        TODO: replace `basedir` with two options: root and save_to. And\n        returns save_to + path"
  },
  {
    "code": "def bar(self, x=None, y=None, **kwds):\n        return self(kind='bar', x=x, y=y, **kwds)",
    "docstring": "Vertical bar plot.\n\n        A bar plot is a plot that presents categorical data with\n        rectangular bars with lengths proportional to the values that they\n        represent. A bar plot shows comparisons among discrete categories. One\n        axis of the plot shows the specific categories being compared, and the\n        other axis represents a measured value.\n\n        Parameters\n        ----------\n        x : label or position, optional\n            Allows plotting of one column versus another. If not specified,\n            the index of the DataFrame is used.\n        y : label or position, optional\n            Allows plotting of one column versus another. If not specified,\n            all numerical columns are used.\n        **kwds\n            Additional keyword arguments are documented in\n            :meth:`DataFrame.plot`.\n\n        Returns\n        -------\n        matplotlib.axes.Axes or np.ndarray of them\n            An ndarray is returned with one :class:`matplotlib.axes.Axes`\n            per column when ``subplots=True``.\n\n        See Also\n        --------\n        DataFrame.plot.barh : Horizontal bar plot.\n        DataFrame.plot : Make plots of a DataFrame.\n        matplotlib.pyplot.bar : Make a bar plot with matplotlib.\n\n        Examples\n        --------\n        Basic plot.\n\n        .. plot::\n            :context: close-figs\n\n            >>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})\n            >>> ax = df.plot.bar(x='lab', y='val', rot=0)\n\n        Plot a whole dataframe to a bar plot. Each column is assigned a\n        distinct color, and each row is nested in a group along the\n        horizontal axis.\n\n        .. plot::\n            :context: close-figs\n\n            >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]\n            >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]\n            >>> index = ['snail', 'pig', 'elephant',\n            ...          'rabbit', 'giraffe', 'coyote', 'horse']\n            >>> df = pd.DataFrame({'speed': speed,\n            ...                    'lifespan': lifespan}, index=index)\n            >>> ax = df.plot.bar(rot=0)\n\n        Instead of nesting, the figure can be split by column with\n        ``subplots=True``. In this case, a :class:`numpy.ndarray` of\n        :class:`matplotlib.axes.Axes` are returned.\n\n        .. plot::\n            :context: close-figs\n\n            >>> axes = df.plot.bar(rot=0, subplots=True)\n            >>> axes[1].legend(loc=2)  # doctest: +SKIP\n\n        Plot a single column.\n\n        .. plot::\n            :context: close-figs\n\n            >>> ax = df.plot.bar(y='speed', rot=0)\n\n        Plot only selected categories for the DataFrame.\n\n        .. plot::\n            :context: close-figs\n\n            >>> ax = df.plot.bar(x='lifespan', rot=0)"
  },
  {
    "code": "def wait_for_task_property(service, task, prop, timeout_sec=120):\n    return time_wait(lambda: task_property_present_predicate(service, task, prop), timeout_seconds=timeout_sec)",
    "docstring": "Waits for a task to have the specified property"
  },
  {
    "code": "def check_ns_run_logls(run, dup_assert=False, dup_warn=False):\n    assert np.array_equal(run['logl'], run['logl'][np.argsort(run['logl'])])\n    if dup_assert or dup_warn:\n        unique_logls, counts = np.unique(run['logl'], return_counts=True)\n        repeat_logls = run['logl'].shape[0] - unique_logls.shape[0]\n        msg = ('{} duplicate logl values (out of a total of {}). This may be '\n               'caused by limited numerical precision in the output files.'\n               '\\nrepeated logls = {}\\ncounts = {}\\npositions in list of {}'\n               ' unique logls = {}').format(\n                   repeat_logls, run['logl'].shape[0],\n                   unique_logls[counts != 1], counts[counts != 1],\n                   unique_logls.shape[0], np.where(counts != 1)[0])\n        if dup_assert:\n            assert repeat_logls == 0, msg\n        elif dup_warn:\n            if repeat_logls != 0:\n                warnings.warn(msg, UserWarning)",
    "docstring": "Check run logls are unique and in the correct order.\n\n    Parameters\n    ----------\n    run: dict\n        nested sampling run to check.\n    dup_assert: bool, optional\n        Whether to raise and AssertionError if there are duplicate logl values.\n    dup_warn: bool, optional\n        Whether to give a UserWarning if there are duplicate logl values (only\n        used if dup_assert is False).\n\n    Raises\n    ------\n    AssertionError\n        if run does not have expected properties."
  },
  {
    "code": "def new_transaction(self, timeout, durability, transaction_type):\n        connection = self._connect()\n        return Transaction(self._client, connection, timeout, durability, transaction_type)",
    "docstring": "Creates a Transaction object with given timeout, durability and transaction type.\n\n        :param timeout: (long), the timeout in seconds determines the maximum lifespan of a transaction.\n        :param durability: (int), the durability is the number of machines that can take over if a member fails during a\n            transaction commit or rollback\n        :param transaction_type: (Transaction Type), the transaction type which can be :const:`~hazelcast.transaction.TWO_PHASE` or :const:`~hazelcast.transaction.ONE_PHASE`\n        :return: (:class:`~hazelcast.transaction.Transaction`), new created Transaction."
  },
  {
    "code": "def _extract_auth_config(self):\n        service = self._service\n        if not service.authentication:\n            return {}\n        auth_infos = {}\n        for auth_rule in service.authentication.rules:\n            selector = auth_rule.selector\n            provider_ids_to_audiences = {}\n            for requirement in auth_rule.requirements:\n                provider_id = requirement.providerId\n                if provider_id and requirement.audiences:\n                    audiences = requirement.audiences.split(u\",\")\n                    provider_ids_to_audiences[provider_id] = audiences\n            auth_infos[selector] = AuthInfo(provider_ids_to_audiences)\n        return auth_infos",
    "docstring": "Obtains the authentication configurations."
  },
  {
    "code": "def unsubscribe(self, ssid, max_msgs=0):\n        if self.is_closed:\n            raise ErrConnectionClosed\n        sub = None\n        try:\n            sub = self._subs[ssid]\n        except KeyError:\n            return\n        if max_msgs == 0 or sub.received >= max_msgs:\n            self._subs.pop(ssid, None)\n            self._remove_subscription(sub)\n        if not self.is_reconnecting:\n            yield self.auto_unsubscribe(ssid, max_msgs)",
    "docstring": "Takes a subscription sequence id and removes the subscription\n        from the client, optionally after receiving more than max_msgs,\n        and unsubscribes immediatedly."
  },
  {
    "code": "def set_module_version(self, major, minor, patch):\n        if not (self._is_byte(major) and self._is_byte(minor) and self._is_byte(patch)):\n            raise ArgumentError(\"Invalid module version number with component that does not fit in 1 byte\",\n                                major=major, minor=minor, patch=patch)\n        self.module_version = (major, minor, patch)",
    "docstring": "Set the module version for this module.\n\n        Each module must declare a semantic version number in the form:\n        major.minor.patch\n\n        where each component is a 1 byte number between 0 and 255."
  },
  {
    "code": "def throttle(coro, limit=1, timeframe=1,\n             return_value=None, raise_exception=False):\n    assert_corofunction(coro=coro)\n    limit = max(int(limit), 1)\n    remaning = limit\n    timeframe = timeframe * 1000\n    last_call = now()\n    result = None\n    def stop():\n        if raise_exception:\n            raise RuntimeError('paco: coroutine throttle limit exceeded')\n        if return_value:\n            return return_value\n        return result\n    def elapsed():\n        return now() - last_call\n    @asyncio.coroutine\n    def wrapper(*args, **kw):\n        nonlocal result\n        nonlocal remaning\n        nonlocal last_call\n        if elapsed() > timeframe:\n            remaning = limit\n            last_call = now()\n        elif elapsed() < timeframe and remaning <= 0:\n            return stop()\n        remaning -= 1\n        result = yield from coro(*args, **kw)\n        return result\n    return wrapper",
    "docstring": "Creates a throttled coroutine function that only invokes\n    ``coro`` at most once per every time frame of seconds or milliseconds.\n\n    Provide options to indicate whether func should be invoked on the\n    leading and/or trailing edge of the wait timeout.\n\n    Subsequent calls to the throttled coroutine\n    return the result of the last coroutine invocation.\n\n    This function can be used as decorator.\n\n    Arguments:\n        coro (coroutinefunction):\n            coroutine function to wrap with throttle strategy.\n        limit (int):\n            number of coroutine allowed execution in the given time frame.\n        timeframe (int|float):\n            throttle limit time frame in seconds.\n        return_value (mixed):\n            optional return if the throttle limit is reached.\n            Returns the latest returned value by default.\n        raise_exception (bool):\n            raise exception if throttle limit is reached.\n\n    Raises:\n        RuntimeError: if cannot throttle limit reached (optional).\n\n    Returns:\n        coroutinefunction\n\n    Usage::\n\n        async def mul_2(num):\n            return num * 2\n\n        # Use as simple wrapper\n        throttled = paco.throttle(mul_2, limit=1, timeframe=2)\n        await throttled(2)\n        # => 4\n        await throttled(3)  # ignored!\n        # => 4\n        await asyncio.sleep(2)\n        await throttled(3)  # executed!\n        # => 6\n\n        # Use as decorator\n        @paco.throttle(limit=1, timeframe=2)\n        async def mul_2(num):\n            return num * 2\n\n        await mul_2(2)\n        # => 4\n        await mul_2(3)  # ignored!\n        # => 4\n        await asyncio.sleep(2)\n        await mul_2(3)  # executed!\n        # => 6"
  },
  {
    "code": "def _add_index(self, index):\n        index_name = index.get_name()\n        index_name = self._normalize_identifier(index_name)\n        replaced_implicit_indexes = []\n        for name, implicit_index in self._implicit_indexes.items():\n            if implicit_index.is_fullfilled_by(index) and name in self._indexes:\n                replaced_implicit_indexes.append(name)\n        already_exists = (\n            index_name in self._indexes\n            and index_name not in replaced_implicit_indexes\n            or self._primary_key_name is not False\n            and index.is_primary()\n        )\n        if already_exists:\n            raise IndexAlreadyExists(index_name, self._name)\n        for name in replaced_implicit_indexes:\n            del self._indexes[name]\n            del self._implicit_indexes[name]\n        if index.is_primary():\n            self._primary_key_name = index_name\n        self._indexes[index_name] = index\n        return self",
    "docstring": "Adds an index to the table.\n\n        :param index: The index to add\n        :type index: Index\n\n        :rtype: Table"
  },
  {
    "code": "def sphinx(self):\n        try:\n            assert __IPYTHON__\n            classdoc = ''\n        except (NameError, AssertionError):\n            scls = self.sphinx_class()\n            classdoc = ' ({})'.format(scls) if scls else ''\n        prop_doc = '**{name}**{cls}: {doc}{info}'.format(\n            name=self.name,\n            cls=classdoc,\n            doc=self.doc,\n            info=', {}'.format(self.info) if self.info else '',\n        )\n        return prop_doc",
    "docstring": "Generate Sphinx-formatted documentation for the Property"
  },
  {
    "code": "def os_requires_version(ostack_release, pkg):\n    def wrap(f):\n        @wraps(f)\n        def wrapped_f(*args):\n            if os_release(pkg) < ostack_release:\n                raise Exception(\"This hook is not supported on releases\"\n                                \" before %s\" % ostack_release)\n            f(*args)\n        return wrapped_f\n    return wrap",
    "docstring": "Decorator for hook to specify minimum supported release"
  },
  {
    "code": "def is_ready(self):\n        ready = len(self.get(self.name, [])) > 0\n        if not ready:\n            hookenv.log('Incomplete relation: {}'.format(self.__class__.__name__), hookenv.DEBUG)\n        return ready",
    "docstring": "Returns True if all of the `required_keys` are available from any units."
  },
  {
    "code": "def current_version():\n    filepath = os.path.abspath(\n        project_root / \"directory_components\" / \"version.py\")\n    version_py = get_file_string(filepath)\n    regex = re.compile(Utils.get_version)\n    if regex.search(version_py) is not None:\n        current_version = regex.search(version_py).group(0)\n        print(color(\n            \"Current directory-components version: {}\".format(current_version),\n            fg='blue', style='bold'))\n        get_update_info()\n    else:\n        print(color(\n            'Error finding directory-components version.',\n            fg='red', style='bold'))",
    "docstring": "Get current version of directory-components."
  },
  {
    "code": "def get_agent_sock_path(env=None, sp=subprocess):\n    args = [util.which('gpgconf'), '--list-dirs']\n    output = check_output(args=args, env=env, sp=sp)\n    lines = output.strip().split(b'\\n')\n    dirs = dict(line.split(b':', 1) for line in lines)\n    log.debug('%s: %s', args, dirs)\n    return dirs[b'agent-socket']",
    "docstring": "Parse gpgconf output to find out GPG agent UNIX socket path."
  },
  {
    "code": "def read(filename, loader=None, implicit_tuple=True, allow_errors=False):\n  with open(filename, 'r') as f:\n    return reads(f.read(),\n                 filename=filename,\n                 loader=loader,\n                 implicit_tuple=implicit_tuple,\n                 allow_errors=allow_errors)",
    "docstring": "Load but don't evaluate a GCL expression from a file."
  },
  {
    "code": "def cmd(send, msg, _):\n    coin = ['heads', 'tails']\n    if not msg:\n        send('The coin lands on... %s' % choice(coin))\n    elif not msg.lstrip('-').isdigit():\n        send(\"Not A Valid Positive Integer.\")\n    else:\n        msg = int(msg)\n        if msg < 0:\n            send(\"Negative Flipping requires the (optional) quantum coprocessor.\")\n            return\n        headflips = randint(0, msg)\n        tailflips = msg - headflips\n        send('The coins land on heads %g times and on tails %g times.' % (headflips, tailflips))",
    "docstring": "Flips a coin a number of times.\n\n    Syntax: {command} [number]"
  },
  {
    "code": "def _get_client_and_key(url, user, password, verbose=0):\n    session = {}\n    session['client'] = six.moves.xmlrpc_client.Server(url, verbose=verbose, use_datetime=True)\n    session['key'] = session['client'].auth.login(user, password)\n    return session",
    "docstring": "Return the client object and session key for the client"
  },
  {
    "code": "def _default_url(self):\n        host = 'localhost' if self.mode == 'remote' else self.host\n        return 'ws://{}:{}/dev'.format(host, self.port)",
    "docstring": "Websocket URL to connect to and listen for reload requests"
  },
  {
    "code": "def fit(self, X, y=None):\n        if self.metric != 'precomputed':\n            X = check_array(X, accept_sparse='csr')\n            self._raw_data = X\n        elif issparse(X):\n            X = check_array(X, accept_sparse='csr')\n        else:\n            check_precomputed_distance_matrix(X)\n        kwargs = self.get_params()\n        kwargs.pop('prediction_data', None)\n        kwargs.update(self._metric_kwargs)\n        (self.labels_,\n         self.probabilities_,\n         self.cluster_persistence_,\n         self._condensed_tree,\n         self._single_linkage_tree,\n         self._min_spanning_tree) = hdbscan(X, **kwargs)\n        if self.prediction_data:\n            self.generate_prediction_data()\n        return self",
    "docstring": "Perform HDBSCAN clustering from features or distance matrix.\n\n        Parameters\n        ----------\n        X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \\\n                array of shape (n_samples, n_samples)\n            A feature array, or array of distances between samples if\n            ``metric='precomputed'``.\n\n        Returns\n        -------\n        self : object\n            Returns self"
  },
  {
    "code": "def action(act, config):\n    if not config:\n        pass\n    elif act is \"list\":\n        do_list()\n    else:\n        config_dir = os.path.join(CONFIG_ROOT, config)\n        globals()[\"do_\" + act](config, config_dir)",
    "docstring": "CLI action preprocessor"
  },
  {
    "code": "def iterativeFetch(query, batchSize=default_batch_size):\n    while True:\n        rows = query.fetchmany(batchSize)\n        if not rows:\n            break\n        rowDicts = sqliteRowsToDicts(rows)\n        for rowDict in rowDicts:\n            yield rowDict",
    "docstring": "Returns rows of a sql fetch query on demand"
  },
  {
    "code": "def from_environ(cls, environ=os.environ):\n    base_path, unused = (environ['PATH_INFO'].rsplit('/', 1) + [''])[:2]\n    return cls(\n        environ['HTTP_X_APPENGINE_TASKNAME'],\n        environ['HTTP_X_APPENGINE_QUEUENAME'],\n        base_path)",
    "docstring": "Constructs a _PipelineContext from the task queue environment."
  },
  {
    "code": "def source_get(method_name):\n    def source_get(_value, context, **_params):\n        method = getattr(context[\"model\"].source, method_name)\n        return _get(method, context[\"key\"], (), {})\n    return source_get",
    "docstring": "Creates a getter that will drop the current value,\n    and call the source's method with specified name\n    using the context's key as first argument.\n    @param method_name: the name of a method belonging to the source.\n    @type method_name: str"
  },
  {
    "code": "def load_configuration(yaml: yaml.ruamel.yaml.YAML, filename: str) -> DictLike:\n    with open(filename, \"r\") as f:\n        config = yaml.load(f)\n    return config",
    "docstring": "Load an analysis configuration from a file.\n\n    Args:\n        yaml: YAML object to use in loading the configuration.\n        filename: Filename of the YAML configuration file.\n    Returns:\n        dict-like object containing the loaded configuration"
  },
  {
    "code": "def size(self):\n        if not self._size:\n            self._size = os.path.getsize(self._path)\n        return self._size",
    "docstring": "size in bytes"
  },
  {
    "code": "def get_review_sh(self, revision, item):\n        identity = self.get_sh_identity(revision)\n        update = parser.parse(item[self.get_field_date()])\n        erevision = self.get_item_sh_fields(identity, update)\n        return erevision",
    "docstring": "Add sorting hat enrichment fields for the author of the revision"
  },
  {
    "code": "def attach_db(self, db):\n        if db is not None:\n            if isinstance(db, basestring):\n                db = gffutils.FeatureDB(db)\n            if not isinstance(db, gffutils.FeatureDB):\n                raise ValueError(\n                    \"`db` must be a filename or a gffutils.FeatureDB\")\n        self._kwargs['db'] = db\n        self.db = db",
    "docstring": "Attach a gffutils.FeatureDB for access to features.\n\n        Useful if you want to attach a db after this instance has already been\n        created.\n\n        Parameters\n        ----------\n        db : gffutils.FeatureDB"
  },
  {
    "code": "def quote_xml(text):\n    text = _coerce_unicode(text)\n    if text.startswith(CDATA_START):\n        return text\n    return saxutils.escape(text)",
    "docstring": "Format a value for display as an XML text node.\n\n    Returns:\n        Unicode string (str on Python 3, unicode on Python 2)"
  },
  {
    "code": "def get_url(self, cmd, **args):\n        return self.http.base_url + self._mkurl(cmd, *args)",
    "docstring": "Expand the request URL for a request."
  },
  {
    "code": "def log_to(logger):\n    logger_id = id(logger)\n    def decorator(function):\n        func = add_label(function, 'log_to', logger_id=logger_id)\n        return func\n    return decorator",
    "docstring": "Wraps a function that has a connection passed such that everything that\n    happens on the connection is logged using the given logger.\n\n    :type  logger: Logger\n    :param logger: The logger that handles the logging."
  },
  {
    "code": "def inserir(self, name):\n        logical_environment_map = dict()\n        logical_environment_map['name'] = name\n        code, xml = self.submit(\n            {'logical_environment': logical_environment_map}, 'POST', 'logicalenvironment/')\n        return self.response(code, xml)",
    "docstring": "Inserts a new Logical Environment and returns its identifier.\n\n        :param name: Logical Environment name. String with a minimum 2 and maximum of 80 characters\n\n        :return: Dictionary with the following structure:\n\n        ::\n\n            {'logical_environment': {'id': < id_logical_environment >}}\n\n        :raise InvalidParameterError: Name is null and invalid.\n        :raise NomeAmbienteLogicoDuplicadoError: There is already a registered Logical Environment with the value of name.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def cap(self):\n        to_cap = (self._inputnodes, self._outputnodes, self._prov)\n        if to_cap == (None, None, None):\n            self._inputnodes = {\n                f: self._make_inputnode(f) for f in self.input_frequencies}\n            self._outputnodes = {\n                f: self._make_outputnode(f) for f in self.output_frequencies}\n            self._prov = self._gen_prov()\n        elif None in to_cap:\n            raise ArcanaError(\n                \"If one of _inputnodes, _outputnodes or _prov is not None then\"\n                \" they all should be in {}\".format(self))",
    "docstring": "\"Caps\" the construction of the pipeline, signifying that no more inputs\n        and outputs are expected to be added and therefore the input and output\n        nodes can be created along with the provenance."
  },
  {
    "code": "def local_bind_ports(self):\n        self._check_is_started()\n        return [_server.local_port for _server in self._server_list if\n                _server.local_port is not None]",
    "docstring": "Return a list containing the ports of local side of the TCP tunnels"
  },
  {
    "code": "def get_t_factor(t1, t2):\n    t_factor = None\n    if t1 is not None and t2 is not None and t1 != t2:  \n        dt = t2 - t1\n        year = timedelta(days=365.25)\n        t_factor = abs(dt.total_seconds() / year.total_seconds()) \n    return t_factor",
    "docstring": "Time difference between two datetimes, expressed as decimal year"
  },
  {
    "code": "def _get_next_buffered_row(self):\n        if self._iter_row == self._iter_nrows:\n            raise StopIteration\n        if self._row_buffer_index >= self._iter_row_buffer:\n            self._buffer_iter_rows(self._iter_row)\n        data = self._row_buffer[self._row_buffer_index]\n        self._iter_row += 1\n        self._row_buffer_index += 1\n        return data",
    "docstring": "Get the next row for iteration."
  },
  {
    "code": "def disconnect(remote_app):\n    if remote_app not in current_oauthclient.disconnect_handlers:\n        return abort(404)\n    ret = current_oauthclient.disconnect_handlers[remote_app]()\n    db.session.commit()\n    return ret",
    "docstring": "Disconnect user from remote application.\n\n    Removes application as well as associated information."
  },
  {
    "code": "def get_drill_bits_d_metric():\n    return np.concatenate((np.arange(1.0, 10.0, 0.1),\n                           np.arange(10.0, 18.0, 0.5),\n                           np.arange(18.0, 36.0, 1.0),\n                           np.arange(40.0, 55.0, 5.0))) * u.mm",
    "docstring": "Return array of possible drill diameters in metric."
  },
  {
    "code": "def apply_rows(applicators, rows):\n    for row in rows:\n        for (cols, function) in applicators:\n            for col in (cols or []):\n                value = row.get(col, '')\n                row[col] = function(row, value)\n        yield row",
    "docstring": "Yield rows after applying the applicator functions to them.\n\n    Applicators are simple unary functions that return a value, and that\n    value is stored in the yielded row. E.g.\n    `row[col] = applicator(row[col])`. These are useful to, e.g., cast\n    strings to numeric datatypes, to convert formats stored in a cell,\n    extract features for machine learning, and so on.\n\n    Args:\n        applicators: a tuple of (cols, applicator) where the applicator\n            will be applied to each col in cols\n        rows: an iterable of rows for applicators to be called on\n    Yields:\n        Rows with specified column values replaced with the results of\n        the applicators\n\n    .. deprecated:: v0.7.0"
  },
  {
    "code": "def _combine_core_aux_specs(self):\n        all_specs = []\n        for core_dict in self._permute_core_specs():\n            for aux_dict in self._permute_aux_specs():\n                all_specs.append(_merge_dicts(core_dict, aux_dict))\n        return all_specs",
    "docstring": "Combine permutations over core and auxilliary Calc specs."
  },
  {
    "code": "def execute(self):\n        self._collect_garbage()\n        upstream_channels = {}\n        for node in nx.topological_sort(self.logical_topo):\n            operator = self.operators[node]\n            downstream_channels = self._generate_channels(operator)\n            handles = self.__generate_actors(operator, upstream_channels,\n                                             downstream_channels)\n            if handles:\n                self.actor_handles.extend(handles)\n            upstream_channels.update(downstream_channels)\n        logger.debug(\"Running...\")\n        return self.actor_handles",
    "docstring": "Deploys and executes the physical dataflow."
  },
  {
    "code": "def _func_router(self, msg, fname, **config):\n        FNAME = 'handle_%s_autocloud_%s'\n        if ('compose_id' in msg['msg'] or 'compose_job_id' in msg['msg'] or\n                'autocloud.compose' in msg['topic']):\n            return getattr(self, FNAME % ('v2', fname))(msg, **config)\n        else:\n            return getattr(self, FNAME % ('v1', fname))(msg, **config)",
    "docstring": "This method routes the messages based on the params and calls the\n        appropriate method to process the message. The utility of the method is\n        to cope up with the major message change during different releases."
  },
  {
    "code": "def get_job_amounts(agent, project_name, spider_name=None):\n    job_list = agent.get_job_list(project_name)\n    pending_job_list = job_list['pending']\n    running_job_list = job_list['running']\n    finished_job_list = job_list['finished']\n    job_amounts = {}\n    if spider_name is None:\n        job_amounts['pending'] = len(pending_job_list)\n        job_amounts['running'] = len(running_job_list)\n        job_amounts['finished'] = len(finished_job_list)\n    else:\n        job_amounts['pending'] = len([j for j in pending_job_list if j['spider'] == spider_name])\n        job_amounts['running'] = len([j for j in running_job_list if j['spider'] == spider_name])\n        job_amounts['finished'] = len([j for j in finished_job_list if j['spider'] == spider_name])\n    return job_amounts",
    "docstring": "Get amounts that pending job amount, running job amount, finished job amount."
  },
  {
    "code": "def _process_table_cells(self, table):\n        rows = []\n        for i, tr in enumerate(table.find_all('tr')):\n            row = []\n            for c in tr.contents:\n                cell_type = getattr(c, 'name', None)\n                if cell_type not in ('td', 'th'):\n                    continue\n                rowspan = int(c.attrs.get('rowspan', 1))\n                colspan = int(c.attrs.get('colspan', 1))\n                contents = self._process_children(c).strip()\n                if cell_type == 'th' and i > 0:\n                    contents = self._inline('**', contents)\n                row.append(Cell(cell_type, rowspan, colspan, contents))\n            rows.append(row)\n        return rows",
    "docstring": "Compile all the table cells.\n\n        Returns a list of rows. The rows may have different lengths because of\n        column spans."
  },
  {
    "code": "def imshow_interact(self, canvas, plot_function, extent=None, label=None, vmin=None, vmax=None, **kwargs):\n        raise NotImplementedError(\"Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library\")",
    "docstring": "This function is optional!\n\n        Create an imshow controller to stream \n        the image returned by the plot_function. There is an imshow controller written for \n        mmatplotlib, which updates the imshow on changes in axis.\n                \n        The origin of the image show is (0,0), such that X[0,0] gets plotted at [0,0] of the image!\n        \n        the kwargs are plotting library specific kwargs!"
  },
  {
    "code": "def _partial_extraction_fixed(self, idx, extra_idx=0):\r\n        myarray = np.array([])\r\n        with open(self.abspath) as fobj:\r\n            contents = fobj.readlines()[idx+extra_idx:]\r\n            for line in contents:\r\n                try:\r\n                    vals = re.findall(r' *[\\w\\-\\+\\.]*', line)\r\n                    temp = np.array([float(val) for val in vals\r\n                                     if val not in ('', '     ')])\r\n                    myarray = np.hstack((myarray, temp))\r\n                except ValueError:\r\n                    break\r\n        return myarray",
    "docstring": "Private method for a single extraction on a fixed-type tab file"
  },
  {
    "code": "def add(self, item):\n        with self.lock:\n            if item in self.set:\n                return False\n            self.set.add(item)\n            return True",
    "docstring": "Add an item to the set, and return whether it was newly added"
  },
  {
    "code": "def _render_border_line(self, t, settings):\n        s = self._es(settings, self.SETTING_WIDTH, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT)\n        w = self.calculate_width_widget(**s)\n        s = self._es(settings, self.SETTING_BORDER_STYLE, self.SETTING_BORDER_FORMATING)\n        border_line = self.fmt_border(w, t, **s)\n        s = self._es(settings, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT, self.SETTING_MARGIN_CHAR)\n        border_line = self.fmt_margin(border_line, **s)\n        return border_line",
    "docstring": "Render box border line."
  },
  {
    "code": "def peek(self, offset=0):\n        pos = self.pos + offset\n        if pos >= self.end:\n            return None\n        return self.text[pos]",
    "docstring": "Looking forward in the input text without actually stepping the current position.\n        returns None if the current position is at the end of the input."
  },
  {
    "code": "def _CheckStorageFile(self, storage_file_path):\n    if os.path.exists(storage_file_path):\n      if not os.path.isfile(storage_file_path):\n        raise errors.BadConfigOption(\n            'Storage file: {0:s} already exists and is not a file.'.format(\n                storage_file_path))\n      logger.warning('Appending to an already existing storage file.')\n    dirname = os.path.dirname(storage_file_path)\n    if not dirname:\n      dirname = '.'\n    if not os.access(dirname, os.W_OK):\n      raise errors.BadConfigOption(\n          'Unable to write to storage file: {0:s}'.format(storage_file_path))",
    "docstring": "Checks if the storage file path is valid.\n\n    Args:\n      storage_file_path (str): path of the storage file.\n\n    Raises:\n      BadConfigOption: if the storage file path is invalid."
  },
  {
    "code": "def createuser(self, email, name='', password=''):\n        self._proxy.User.create(email, name, password)\n        return self.getuser(email)",
    "docstring": "Return a bugzilla User for the given username\n\n        :arg email: The email address to use in bugzilla\n        :kwarg name: Real name to associate with the account\n        :kwarg password: Password to set for the bugzilla account\n        :raises XMLRPC Fault: Code 501 if the username already exists\n            Code 500 if the email address isn't valid\n            Code 502 if the password is too short\n            Code 503 if the password is too long\n        :return: User record for the username"
  },
  {
    "code": "def arrays2wcxf(C):\n    d = {}\n    for k, v in C.items():\n        if np.shape(v) == () or np.shape(v) == (1,):\n            d[k] = v\n        else:\n            ind = np.indices(v.shape).reshape(v.ndim, v.size).T\n            for i in ind:\n                name = k + '_' + ''.join([str(int(j) + 1) for j in i])\n                d[name] = v[tuple(i)]\n    return d",
    "docstring": "Convert a dictionary with Wilson coefficient names as keys and\n    numbers or numpy arrays as values to a dictionary with a Wilson coefficient\n    name followed by underscore and numeric indices as keys and numbers as\n    values. This is needed for the output in WCxf format."
  },
  {
    "code": "def extend(self, **kwargs):\n    props = self.copy()\n    props.update(kwargs)\n    return TemplateData(**props)",
    "docstring": "Returns a new instance with this instance's data overlayed by the key-value args."
  },
  {
    "code": "def wait_for_contract(self, contract_address_hex, timeout=None):\n        contract_address = decode_hex(contract_address_hex)\n        start_time = time.time()\n        result = self._raiden.chain.client.web3.eth.getCode(\n            to_checksum_address(contract_address),\n        )\n        current_time = time.time()\n        while not result:\n            if timeout and start_time + timeout > current_time:\n                return False\n            result = self._raiden.chain.client.web3.eth.getCode(\n                to_checksum_address(contract_address),\n            )\n            gevent.sleep(0.5)\n            current_time = time.time()\n        return len(result) > 0",
    "docstring": "Wait until a contract is mined\n\n        Args:\n            contract_address_hex (string): hex encoded address of the contract\n            timeout (int): time to wait for the contract to get mined\n\n        Returns:\n            True if the contract got mined, false otherwise"
  },
  {
    "code": "def _locate_file(f, base_dir):\n    if base_dir == None:\n        return f\n    file_name = os.path.join(base_dir, f)\n    real = os.path.realpath(file_name)\n    return real",
    "docstring": "Utility method for finding full path to a filename as string"
  },
  {
    "code": "def force_encoding(self, encoding):\n        if not encoding:\n            self.disabled = False\n        else:\n            self.write_with_encoding(encoding, None)\n            self.disabled = True",
    "docstring": "Sets a fixed encoding. The change is emitted right away.\n\n        From now one, this buffer will switch the code page anymore.\n        However, it will still keep track of the current code page."
  },
  {
    "code": "def setup_dictionary(self, task):\n        dictionary_options = task.get('dictionary', {})\n        output = os.path.abspath(dictionary_options.get('output', self.dict_bin))\n        lang = dictionary_options.get('lang', 'en_US')\n        wordlists = dictionary_options.get('wordlists', [])\n        if lang and wordlists:\n            self.compile_dictionary(lang, dictionary_options.get('wordlists', []), None, output)\n        else:\n            output = None\n        return output",
    "docstring": "Setup dictionary."
  },
  {
    "code": "def T_i(v_vars: List[fl.Var], mass: np.ndarray, i: int):\n    assert len(v_vars) == 3 * len(mass)\n    m = mass[i]\n    T = (0.5 * m) * flux_v2(v_vars, i)\n    return T",
    "docstring": "Make Fluxion with the kinetic energy of body i"
  },
  {
    "code": "def _dataset_line(args):\n  if args['command'] == 'list':\n    filter_ = args['filter'] if args['filter'] else '*'\n    context = google.datalab.Context.default()\n    if args['project']:\n      context = google.datalab.Context(args['project'], context.credentials)\n    return _render_list([str(dataset) for dataset in bigquery.Datasets(context)\n                         if fnmatch.fnmatch(str(dataset), filter_)])\n  elif args['command'] == 'create':\n    try:\n      bigquery.Dataset(args['name']).create(friendly_name=args['friendly'])\n    except Exception as e:\n      print('Failed to create dataset %s: %s' % (args['name'], e))\n  elif args['command'] == 'delete':\n    try:\n      bigquery.Dataset(args['name']).delete()\n    except Exception as e:\n      print('Failed to delete dataset %s: %s' % (args['name'], e))",
    "docstring": "Implements the BigQuery dataset magic subcommand used to operate on datasets\n\n   The supported syntax is:\n   %bq datasets <command> <args>\n\n  Commands:\n    {list, create, delete}\n\n  Args:\n    args: the optional arguments following '%bq datasets command'."
  },
  {
    "code": "def get_in_net_id(cls, tenant_id):\n        if 'in' not in cls.ip_db_obj:\n            LOG.error(\"Fabric not prepared for tenant %s\", tenant_id)\n            return None\n        db_obj = cls.ip_db_obj.get('in')\n        in_subnet_dict = cls.get_in_ip_addr(tenant_id)\n        sub = db_obj.get_subnet(in_subnet_dict.get('subnet'))\n        return sub.network_id",
    "docstring": "Retrieve the network ID of IN network."
  },
  {
    "code": "def save_object(filename, obj):\n    logging.info('saving {}...'.format(filename))\n    try:\n        with gzip.GzipFile(filename, 'wb') as f:\n            f.write(pickle.dumps(obj, 1))\n    except Exception as e:\n        logging.error('save failure: {}'.format(e))\n        raise",
    "docstring": "Compresses and pickles given object to the given filename."
  },
  {
    "code": "def _on_change(self):\n        font = self.__generate_font_tuple()\n        self._example_label.configure(font=font)",
    "docstring": "Callback if any of the values are changed."
  },
  {
    "code": "def log(self, sequence, infoarray) -> None:\n        aggregated = ((infoarray is not None) and\n                      (infoarray.info['type'] != 'unmodified'))\n        descr = sequence.descr_sequence\n        if aggregated:\n            descr = '_'.join([descr, infoarray.info['type']])\n        if descr in self.variables:\n            var_ = self.variables[descr]\n        else:\n            if aggregated:\n                cls = NetCDFVariableAgg\n            elif self._flatten:\n                cls = NetCDFVariableFlat\n            else:\n                cls = NetCDFVariableDeep\n            var_ = cls(name=descr,\n                       isolate=self._isolate,\n                       timeaxis=self._timeaxis)\n            self.variables[descr] = var_\n        var_.log(sequence, infoarray)",
    "docstring": "Pass the given |IoSequence| to a suitable instance of\n        a |NetCDFVariableBase| subclass.\n\n        When writing data, the second argument should be an |InfoArray|.\n        When reading data, this argument is ignored. Simply pass |None|.\n\n        (1) We prepare some devices handling some sequences by applying\n        function |prepare_io_example_1|.  We limit our attention to the\n        returned elements, which handle the more diverse sequences:\n\n        >>> from hydpy.core.examples import prepare_io_example_1\n        >>> nodes, (element1, element2, element3) = prepare_io_example_1()\n\n        (2) We define some shortcuts for the sequences used in the\n        following examples:\n\n        >>> nied1 = element1.model.sequences.inputs.nied\n        >>> nied2 = element2.model.sequences.inputs.nied\n        >>> nkor2 = element2.model.sequences.fluxes.nkor\n        >>> nkor3 = element3.model.sequences.fluxes.nkor\n\n        (3) We define a function that logs these example sequences\n        to a given |NetCDFFile| object and prints some information\n        about the resulting object structure.  Note that sequence\n        `nkor2` is logged twice, the first time with its original\n        time series data, the second time with averaged values:\n\n        >>> from hydpy import classname\n        >>> def test(ncfile):\n        ...     ncfile.log(nied1, nied1.series)\n        ...     ncfile.log(nied2, nied2.series)\n        ...     ncfile.log(nkor2, nkor2.series)\n        ...     ncfile.log(nkor2, nkor2.average_series())\n        ...     ncfile.log(nkor3, nkor3.average_series())\n        ...     for name, variable in ncfile.variables.items():\n        ...         print(name, classname(variable), variable.subdevicenames)\n\n        (4) We prepare a |NetCDFFile| object with both options\n        `flatten` and `isolate` being disabled:\n\n        >>> from hydpy.core.netcdftools import NetCDFFile\n        >>> ncfile = NetCDFFile(\n        ...     'model', flatten=False, isolate=False, timeaxis=1, dirpath='')\n\n        (5) We log all test sequences results in two |NetCDFVariableDeep|\n        and one |NetCDFVariableAgg| objects.  To keep both NetCDF variables\n        related to |lland_fluxes.NKor| distinguishable, the name\n        `flux_nkor_mean` includes information about the kind of aggregation\n        performed:\n\n        >>> test(ncfile)\n        input_nied NetCDFVariableDeep ('element1', 'element2')\n        flux_nkor NetCDFVariableDeep ('element2',)\n        flux_nkor_mean NetCDFVariableAgg ('element2', 'element3')\n\n        (6) We confirm that the |NetCDFVariableBase| objects received\n        the required information:\n\n        >>> ncfile.flux_nkor.element2.sequence.descr_device\n        'element2'\n        >>> ncfile.flux_nkor.element2.array\n        InfoArray([[ 16.,  17.],\n                   [ 18.,  19.],\n                   [ 20.,  21.],\n                   [ 22.,  23.]])\n        >>> ncfile.flux_nkor_mean.element2.sequence.descr_device\n        'element2'\n        >>> ncfile.flux_nkor_mean.element2.array\n        InfoArray([ 16.5,  18.5,  20.5,  22.5])\n\n        (7) We again prepare a |NetCDFFile| object, but now with both\n        options `flatten` and `isolate` being enabled.  To log test\n        sequences with their original time series data does now trigger\n        the initialisation of class |NetCDFVariableFlat|.  When passing\n        aggregated data, nothing changes:\n\n        >>> ncfile = NetCDFFile(\n        ...     'model', flatten=True, isolate=True, timeaxis=1, dirpath='')\n        >>> test(ncfile)\n        input_nied NetCDFVariableFlat ('element1', 'element2')\n        flux_nkor NetCDFVariableFlat ('element2_0', 'element2_1')\n        flux_nkor_mean NetCDFVariableAgg ('element2', 'element3')\n        >>> ncfile.flux_nkor.element2.sequence.descr_device\n        'element2'\n        >>> ncfile.flux_nkor.element2.array\n        InfoArray([[ 16.,  17.],\n                   [ 18.,  19.],\n                   [ 20.,  21.],\n                   [ 22.,  23.]])\n        >>> ncfile.flux_nkor_mean.element2.sequence.descr_device\n        'element2'\n        >>> ncfile.flux_nkor_mean.element2.array\n        InfoArray([ 16.5,  18.5,  20.5,  22.5])\n\n        (8) We technically confirm that the `isolate` argument is passed\n        to the constructor of subclasses of |NetCDFVariableBase| correctly:\n\n        >>> from unittest.mock import patch\n        >>> with patch('hydpy.core.netcdftools.NetCDFVariableFlat') as mock:\n        ...     ncfile = NetCDFFile(\n        ...         'model', flatten=True, isolate=False, timeaxis=0,\n        ...         dirpath='')\n        ...     ncfile.log(nied1, nied1.series)\n        ...     mock.assert_called_once_with(\n        ...         name='input_nied', timeaxis=0, isolate=False)"
  },
  {
    "code": "def get_included_resources(request, serializer=None):\n    include_resources_param = request.query_params.get('include') if request else None\n    if include_resources_param:\n        return include_resources_param.split(',')\n    else:\n        return get_default_included_resources_from_serializer(serializer)",
    "docstring": "Build a list of included resources."
  },
  {
    "code": "def latinize_text(text, ascii=False):\n    if text is None or not isinstance(text, six.string_types) or not len(text):\n        return text\n    if ascii:\n        if not hasattr(latinize_text, '_ascii'):\n            latinize_text._ascii = Transliterator.createInstance('Any-Latin; NFKD; [:Symbol:] Remove; [:Nonspacing Mark:] Remove; NFKC; Accents-Any; Latin-ASCII')\n        return latinize_text._ascii.transliterate(text)\n    if not hasattr(latinize_text, '_tr'):\n        latinize_text._tr = Transliterator.createInstance('Any-Latin')\n    return latinize_text._tr.transliterate(text)",
    "docstring": "Transliterate the given text to the latin script.\n\n    This attempts to convert a given text to latin script using the\n    closest match of characters vis a vis the original script."
  },
  {
    "code": "def fetch_state_data(self, states):\n        print(\"Fetching census data\")\n        for table in CensusTable.objects.all():\n            api = self.get_series(table.series)\n            for variable in table.variables.all():\n                estimate = \"{}_{}\".format(table.code, variable.code)\n                print(\n                    \">> Fetching {} {} {}\".format(\n                        table.year, table.series, estimate\n                    )\n                )\n                for state in tqdm(states):\n                    self.get_state_estimates_by_state(\n                        api=api,\n                        table=table,\n                        variable=variable,\n                        estimate=estimate,\n                        state=state,\n                    )\n                    self.get_county_estimates_by_state(\n                        api=api,\n                        table=table,\n                        variable=variable,\n                        estimate=estimate,\n                        state=state,\n                    )\n                    self.get_district_estimates_by_state(\n                        api=api,\n                        table=table,\n                        variable=variable,\n                        estimate=estimate,\n                        state=state,\n                    )",
    "docstring": "Fetch census estimates from table."
  },
  {
    "code": "def cc(project, detect_project=False):\n    from benchbuild.utils import cmd\n    cc_name = str(CFG[\"compiler\"][\"c\"])\n    wrap_cc(cc_name, compiler(cc_name), project, detect_project=detect_project)\n    return cmd[\"./{}\".format(cc_name)]",
    "docstring": "Return a clang that hides CFLAGS and LDFLAGS.\n\n    This will generate a wrapper script in the current directory\n    and return a complete plumbum command to it.\n\n    Args:\n        cflags: The CFLAGS we want to hide.\n        ldflags: The LDFLAGS we want to hide.\n        func (optional): A function that will be pickled alongside the compiler.\n            It will be called before the actual compilation took place. This\n            way you can intercept the compilation process with arbitrary python\n            code.\n\n    Returns (benchbuild.utils.cmd):\n        Path to the new clang command."
  },
  {
    "code": "def to_bytes(self):\n        return struct.pack(Ethernet._PACKFMT, self._dst.packed, \n            self._src.packed, self._ethertype.value)",
    "docstring": "Return packed byte representation of the Ethernet header."
  },
  {
    "code": "def fill_predictive_missing_parameters(self):\n        if hasattr(self, 'host_name') and not hasattr(self, 'address'):\n            self.address = self.host_name\n        if hasattr(self, 'host_name') and not hasattr(self, 'alias'):\n            self.alias = self.host_name\n        if self.initial_state == 'd':\n            self.state = 'DOWN'\n        elif self.initial_state == 'x':\n            self.state = 'UNREACHABLE'",
    "docstring": "Fill address with host_name if not already set\n        and define state with initial_state\n\n        :return: None"
  },
  {
    "code": "def get_storage_info(self, human=False):\n        res = self._req_get_storage_info()\n        if human:\n            res['total'] = humanize.naturalsize(res['total'], binary=True)\n            res['used'] = humanize.naturalsize(res['used'], binary=True)\n        return res",
    "docstring": "Get storage info\n\n        :param bool human: whether return human-readable size\n        :return: total and used storage\n        :rtype: dict"
  },
  {
    "code": "def raise_for_error(self):\n        if self.ok:\n            return self\n        tip = \"running {0} @<{1}> error, return code {2}\".format(\n            \" \".join(self.cmd), self.cwd, self.return_code\n        )\n        logger.error(\"{0}\\nstdout:{1}\\nstderr:{2}\\n\".format(\n            tip, self._stdout.decode(\"utf8\"), self._stderr.decode(\"utf8\")\n        ))\n        raise ShCmdError(self)",
    "docstring": "raise `ShCmdError` if the proc's return_code is not 0\n        otherwise return self\n\n        ..Usage::\n\n            >>> proc = shcmd.run(\"ls\").raise_for_error()\n            >>> proc.return_code == 0\n            True"
  },
  {
    "code": "def add_view(self, *args, **kwargs):\n        new_view = View(*args, **kwargs)\n        for view in self.views:\n            if view.uid == new_view.uid:\n                raise ValueError(\"View with this uid already exists\")\n        self.views += [new_view]\n        return new_view",
    "docstring": "Add a new view\n\n        Parameters\n        ----------\n        uid: string\n            The uid of new view\n        width: int\n            The width of this of view on a 12 unit grid\n        height: int\n            The height of the this view. The height is proportional\n            to the height of all the views present.\n        x: int\n            The position of this view on the grid\n        y: int\n            The position of this view on the grid\n        initialXDoamin: [int, int]\n            The initial x range of the view\n        initialYDomain: [int, int]\n            The initial y range of the view"
  },
  {
    "code": "def _get_class_handlers(cls, signal_name, instance):\n        handlers = cls._signal_handlers_sorted[signal_name]\n        return [getattr(instance, hname) for hname in handlers]",
    "docstring": "Returns the handlers registered at class level."
  },
  {
    "code": "def run_manage_command(self, command, venv_path, verbose=True):\n        self.logger.debug('Running manage command `%s` for `%s` ...' % (command, venv_path))\n        self._run_shell_command(\n            '. %s/bin/activate && python %s %s' % (venv_path, self._get_manage_py_path(), command),\n            pipe_it=(not verbose))",
    "docstring": "Runs a given Django manage command in a given virtual environment.\n\n        :param str command:\n        :param str venv_path:\n        :param bool verbose:"
  },
  {
    "code": "def get_current_clementine():\n    try:\n        return get_info_mpris2('clementine')\n    except DBusErrorResponse:\n        bus_name = 'org.mpris.clementine'\n        path = '/Player'\n        interface = 'org.freedesktop.MediaPlayer'\n        return dbus_get_metadata(path, bus_name, interface)",
    "docstring": "Get the current song from clementine."
  },
  {
    "code": "def unpack_message(buffer):\n    hdr_size = Header().get_size()\n    hdr_buff, msg_buff = buffer[:hdr_size], buffer[hdr_size:]\n    header = Header()\n    header.unpack(hdr_buff)\n    message = new_message_from_header(header)\n    message.unpack(msg_buff)\n    return message",
    "docstring": "Unpack the whole buffer, including header pack.\n\n    Args:\n        buffer (bytes): Bytes representation of a openflow message.\n\n    Returns:\n        object: Instance of openflow message."
  },
  {
    "code": "def is_authenticated(user):\n    if not hasattr(user, 'is_authenticated'):\n       return False\n    if callable(user.is_authenticated):\n        return user.is_authenticated()\n    else:\n        return user.is_authenticated",
    "docstring": "Return whether or not a User is authenticated.\n\n    Function provides compatibility following deprecation of method call to\n    `is_authenticated()` in Django 2.0.\n\n    This is *only* required to support Django < v1.10 (i.e. v1.9 and earlier),\n    as `is_authenticated` was introduced as a property in v1.10.s"
  },
  {
    "code": "async def inspect(self, *, node_id: str) -> Mapping[str, Any]:\n        response = await self.docker._query_json(\n            \"nodes/{node_id}\".format(node_id=node_id), method=\"GET\"\n        )\n        return response",
    "docstring": "Inspect a node\n\n        Args:\n            node_id: The ID or name of the node"
  },
  {
    "code": "def validate_receiver(self, key, value):\n        if value not in current_webhooks.receivers:\n            raise ReceiverDoesNotExist(self.receiver_id)\n        return value",
    "docstring": "Validate receiver identifier."
  },
  {
    "code": "def _ConvertInteger(value):\n  if isinstance(value, float) and not value.is_integer():\n    raise ParseError('Couldn\\'t parse integer: {0}.'.format(value))\n  if isinstance(value, six.text_type) and value.find(' ') != -1:\n    raise ParseError('Couldn\\'t parse integer: \"{0}\".'.format(value))\n  return int(value)",
    "docstring": "Convert an integer.\n\n  Args:\n    value: A scalar value to convert.\n\n  Returns:\n    The integer value.\n\n  Raises:\n    ParseError: If an integer couldn't be consumed."
  },
  {
    "code": "def raw(self, from_, to, body):\n        if isinstance(to, string_types):\n            raise TypeError('\"to\" parameter must be enumerable')\n        return self._session.post('{}/raw'.format(self._url), json={\n            'from': from_,\n            'to': to,\n            'body': body,\n        }).json()",
    "docstring": "Send a raw MIME message."
  },
  {
    "code": "def LL(n):\n    if (n<=0):return Context('0')\n    else:\n        LL1=LL(n-1)\n        r1 = C1(3**(n-1),2**(n-1)) - LL1 - LL1\n        r2 = LL1 - LL1 - LL1\n        return r1 + r2",
    "docstring": "constructs the LL context"
  },
  {
    "code": "def decision_function(self, X):\n        predictions = self.predict_proba(X)\n        out = np.zeros((predictions.shape[0], 1))\n        out[:, 0] = 1 - predictions[:, -1]\n        return out",
    "docstring": "Generate an inlier score for each test data example.\n\n        Parameters\n        ----------\n        X : array\n            Test data, of dimension N times d (rows are examples, columns\n            are data dimensions)\n\n        Returns:\n        -------\n        scores : array\n            A vector of length N, where each element contains an inlier\n            score in the range 0-1 (outliers have values close to zero,\n            inliers have values close to one)."
  },
  {
    "code": "def oidc_to_user_data(payload):\n    payload = payload.copy()\n    field_map = {\n        'given_name': 'first_name',\n        'family_name': 'last_name',\n        'email': 'email',\n    }\n    ret = {}\n    for token_attr, user_attr in field_map.items():\n        if token_attr not in payload:\n            continue\n        ret[user_attr] = payload.pop(token_attr)\n    ret.update(payload)\n    return ret",
    "docstring": "Map OIDC claims to Django user fields."
  },
  {
    "code": "def split_flanks(self, _, result):\n        if not result.strip():\n            self.left, self.right = \"\", \"\"\n            return result\n        match = self.flank_re.match(result)\n        assert match, \"This regexp should always match\"\n        self.left, self.right = match.group(1), match.group(3)\n        return match.group(2)",
    "docstring": "Return `result` without flanking whitespace."
  },
  {
    "code": "def choose(items, title_text, question_text):\n    print(title_text)\n    for i, item in enumerate(items, start=1):\n        print('%d) %s' % (i, item))\n    print('%d) Abort' % (i + 1))\n    selected = input(question_text)\n    try:\n        index = int(selected)\n    except ValueError:\n        index = -1\n    if not (index - 1) in range(len(items)):\n        print('Aborting.')\n        return None\n    return items[index - 1]",
    "docstring": "Interactively choose one of the items."
  },
  {
    "code": "def dumpfile(item, path):\n    with io.open(path, 'wb') as fd:\n        fd.write(en(item))",
    "docstring": "Dump an object to a file by path.\n\n    Args:\n        item (object): The object to serialize.\n        path (str): The file path to save.\n\n    Returns:\n        None"
  },
  {
    "code": "def gauge(self, *args, **kwargs):\n        orig_gauge = super(Nagios, self).gauge\n        if 'timestamp' in kwargs and 'timestamp' not in getargspec(orig_gauge).args:\n            del kwargs['timestamp']\n        orig_gauge(*args, **kwargs)",
    "docstring": "Compatability wrapper for Agents that do not submit gauge metrics with custom timestamps"
  },
  {
    "code": "def match_rank (self, ps):\n        assert isinstance(ps, property_set.PropertySet)\n        all_requirements = self.requirements ()\n        property_requirements = []\n        feature_requirements = []\n        for r in all_requirements:\n            if get_value (r):\n                property_requirements.append (r)\n            else:\n                feature_requirements.append (r)\n        return all(ps.get(get_grist(s)) == [get_value(s)] for s in property_requirements) \\\n               and all(ps.get(get_grist(s)) for s in feature_requirements)",
    "docstring": "Returns true if the generator can be run with the specified\n            properties."
  },
  {
    "code": "def get_num_primal_variables(self):\n        if self.x is not None:\n            return self.x.size\n        if self.gphi is not None:\n            return self.gphi.size\n        if self.Hphi is not None:\n            return self.Hphi.shape[0]\n        if self.A is not None:\n            return self.A.shape[1]\n        if self.J is not None:\n            return self.J.shape[1]\n        if self.u is not None:\n            return self.u.size\n        if self.l is not None:\n            return self.l.size\n        return 0",
    "docstring": "Gets number of primal variables.\n\n        Returns\n        -------\n        num : int"
  },
  {
    "code": "def pop_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]:\n        if changeset_id not in self.journal_data:\n            raise KeyError(changeset_id, \"Unknown changeset in JournalDB\")\n        all_ids = tuple(self.journal_data.keys())\n        changeset_idx = all_ids.index(changeset_id)\n        changesets_to_pop = all_ids[changeset_idx:]\n        popped_clears = tuple(idx for idx in changesets_to_pop if idx in self._clears_at)\n        if popped_clears:\n            last_clear_idx = changesets_to_pop.index(popped_clears[-1])\n            changesets_to_drop = changesets_to_pop[:last_clear_idx]\n            changesets_to_merge = changesets_to_pop[last_clear_idx:]\n        else:\n            changesets_to_drop = ()\n            changesets_to_merge = changesets_to_pop\n        changeset_data = merge(*(\n            self.journal_data.pop(c_id)\n            for c_id\n            in changesets_to_merge\n        ))\n        for changeset_id in changesets_to_drop:\n            self.journal_data.pop(changeset_id)\n        self._clears_at.difference_update(popped_clears)\n        return changeset_data",
    "docstring": "Returns all changes from the given changeset.  This includes all of\n        the changes from any subsequent changeset, giving precidence to\n        later changesets."
  },
  {
    "code": "def nsmallest(self, n, columns, keep='first'):\n        return algorithms.SelectNFrame(self,\n                                       n=n,\n                                       keep=keep,\n                                       columns=columns).nsmallest()",
    "docstring": "Return the first `n` rows ordered by `columns` in ascending order.\n\n        Return the first `n` rows with the smallest values in `columns`, in\n        ascending order. The columns that are not specified are returned as\n        well, but not used for ordering.\n\n        This method is equivalent to\n        ``df.sort_values(columns, ascending=True).head(n)``, but more\n        performant.\n\n        Parameters\n        ----------\n        n : int\n            Number of items to retrieve.\n        columns : list or str\n            Column name or names to order by.\n        keep : {'first', 'last', 'all'}, default 'first'\n            Where there are duplicate values:\n\n            - ``first`` : take the first occurrence.\n            - ``last`` : take the last occurrence.\n            - ``all`` : do not drop any duplicates, even it means\n              selecting more than `n` items.\n\n            .. versionadded:: 0.24.0\n\n        Returns\n        -------\n        DataFrame\n\n        See Also\n        --------\n        DataFrame.nlargest : Return the first `n` rows ordered by `columns` in\n            descending order.\n        DataFrame.sort_values : Sort DataFrame by the values.\n        DataFrame.head : Return the first `n` rows without re-ordering.\n\n        Examples\n        --------\n        >>> df = pd.DataFrame({'population': [59000000, 65000000, 434000,\n        ...                                   434000, 434000, 337000, 11300,\n        ...                                   11300, 11300],\n        ...                    'GDP': [1937894, 2583560 , 12011, 4520, 12128,\n        ...                            17036, 182, 38, 311],\n        ...                    'alpha-2': [\"IT\", \"FR\", \"MT\", \"MV\", \"BN\",\n        ...                                \"IS\", \"NR\", \"TV\", \"AI\"]},\n        ...                   index=[\"Italy\", \"France\", \"Malta\",\n        ...                          \"Maldives\", \"Brunei\", \"Iceland\",\n        ...                          \"Nauru\", \"Tuvalu\", \"Anguilla\"])\n        >>> df\n                  population      GDP alpha-2\n        Italy       59000000  1937894      IT\n        France      65000000  2583560      FR\n        Malta         434000    12011      MT\n        Maldives      434000     4520      MV\n        Brunei        434000    12128      BN\n        Iceland       337000    17036      IS\n        Nauru          11300      182      NR\n        Tuvalu         11300       38      TV\n        Anguilla       11300      311      AI\n\n        In the following example, we will use ``nsmallest`` to select the\n        three rows having the smallest values in column \"a\".\n\n        >>> df.nsmallest(3, 'population')\n                  population  GDP alpha-2\n        Nauru          11300  182      NR\n        Tuvalu         11300   38      TV\n        Anguilla       11300  311      AI\n\n        When using ``keep='last'``, ties are resolved in reverse order:\n\n        >>> df.nsmallest(3, 'population', keep='last')\n                  population  GDP alpha-2\n        Anguilla       11300  311      AI\n        Tuvalu         11300   38      TV\n        Nauru          11300  182      NR\n\n        When using ``keep='all'``, all duplicate items are maintained:\n\n        >>> df.nsmallest(3, 'population', keep='all')\n                  population  GDP alpha-2\n        Nauru          11300  182      NR\n        Tuvalu         11300   38      TV\n        Anguilla       11300  311      AI\n\n        To order by the largest values in column \"a\" and then \"c\", we can\n        specify multiple columns like in the next example.\n\n        >>> df.nsmallest(3, ['population', 'GDP'])\n                  population  GDP alpha-2\n        Tuvalu         11300   38      TV\n        Nauru          11300  182      NR\n        Anguilla       11300  311      AI"
  },
  {
    "code": "def _fusion_range_to_dsl(tokens) -> FusionRangeBase:\n    if FUSION_MISSING in tokens:\n        return missing_fusion_range()\n    return fusion_range(\n        reference=tokens[FUSION_REFERENCE],\n        start=tokens[FUSION_START],\n        stop=tokens[FUSION_STOP]\n    )",
    "docstring": "Convert a PyParsing data dictionary into a PyBEL.\n\n    :type tokens: ParseResult"
  },
  {
    "code": "def element_data_from_sym(sym):\n    sym_lower = sym.lower()\n    if sym_lower not in _element_sym_map:\n        raise KeyError('No element data for symbol \\'{}\\''.format(sym))\n    return _element_sym_map[sym_lower]",
    "docstring": "Obtain elemental data given an elemental symbol\n\n    The given symbol is not case sensitive\n\n    An exception is thrown if the symbol is not found"
  },
  {
    "code": "def can_map_ipa_string(self, ipa_string):\n        canonical = [(c.canonical_representation, ) for c in ipa_string]\n        split = split_using_dictionary(canonical, self, self.max_key_length, single_char_parsing=False)\n        for sub in split:\n            if not sub in self.ipa_canonical_representation_to_mapped_str:\n                return False\n        return True",
    "docstring": "Return ``True`` if the mapper can map all the IPA characters\n        in the given IPA string.\n\n        :param IPAString ipa_string: the IPAString to be parsed\n        :rtype: bool"
  },
  {
    "code": "def gen_bisz(src, dst):\n        return ReilBuilder.build(ReilMnemonic.BISZ, src, ReilEmptyOperand(), dst)",
    "docstring": "Return a BISZ instruction."
  },
  {
    "code": "def create_env(self, interpreter, is_current, options):\n        if is_current:\n            pyvenv_options = options['pyvenv_options']\n            if \"--system-site-packages\" in pyvenv_options:\n                self.system_site_packages = True\n            logger.debug(\"Creating virtualenv with pyvenv. options=%s\", pyvenv_options)\n            self.create(self.env_path)\n        else:\n            virtualenv_options = options['virtualenv_options']\n            logger.debug(\"Creating virtualenv with virtualenv\")\n            self.create_with_virtualenv(interpreter, virtualenv_options)\n        logger.debug(\"env_bin_path: %s\", self.env_bin_path)\n        pip_bin = os.path.join(self.env_bin_path, \"pip\")\n        pip_exe = os.path.join(self.env_bin_path, \"pip.exe\")\n        if not (os.path.exists(pip_bin) or os.path.exists(pip_exe)):\n            logger.debug(\"pip isn't installed in the venv, setting pip_installed=False\")\n            self.pip_installed = False\n        return self.env_path, self.env_bin_path, self.pip_installed",
    "docstring": "Create the virtualenv and return its info."
  },
  {
    "code": "def storepage(self, page):\n    try:\n      return self._api_entrypoint.storePage(self._session_token, page)\n    except XMLRPCError as e:\n      log.error('Failed to store page %s: %s' % (page.get('title', '[unknown title]'), e))\n      return None",
    "docstring": "Stores a page object, updating the page if it already exists.\n    returns the stored page, or None if the page could not be stored."
  },
  {
    "code": "def parse_response(self, response, header=None):\n        response = response.decode(self.encoding)\n        if header:\n            header = \"\".join((self.resp_prefix, header, self.resp_header_sep))\n            if not response.startswith(header):\n                raise IEC60488.ParsingError('Response header mismatch')\n            response = response[len(header):]\n        return response.split(self.resp_data_sep)",
    "docstring": "Parses the response message.\n\n        The following graph shows the structure of response messages.\n\n        ::\n\n                                                        +----------+\n                                                     +--+ data sep +<-+\n                                                     |  +----------+  |\n                                                     |                |\n                  +--------+        +------------+   |    +------+    |\n              +-->| header +------->+ header sep +---+--->+ data +----+----+\n              |   +--------+        +------------+        +------+         |\n              |                                                            |\n            --+                                         +----------+       +-->\n              |                                      +--+ data sep +<-+    |\n              |                                      |  +----------+  |    |\n              |                                      |                |    |\n              |                                      |    +------+    |    |\n              +--------------------------------------+--->+ data +----+----+\n                                                          +------+"
  },
  {
    "code": "def verify_fun(lazy_obj, fun):\n    if not fun:\n        raise salt.exceptions.SaltInvocationError(\n            'Must specify a function to run!\\n'\n            'ex: manage.up'\n        )\n    if fun not in lazy_obj:\n        raise salt.exceptions.CommandExecutionError(lazy_obj.missing_fun_string(fun))",
    "docstring": "Check that the function passed really exists"
  },
  {
    "code": "def _getMethodNamePrefix(self, node):\n        targetName = node.name\n        for sibling in node.parent.nodes_of_class(type(node)):\n            if sibling is node:\n                continue\n            prefix = self._getCommonStart(targetName, sibling.name)\n            if not prefix.rstrip('_'):\n                continue\n            return prefix\n        return ''",
    "docstring": "Return the prefix of this method based on sibling methods.\n\n        @param node: the current node"
  },
  {
    "code": "def getTmpFilename(self, tmp_dir=None, prefix='tmp', suffix='.txt',\n                       include_class_id=False, result_constructor=FilePath):\n        if not tmp_dir:\n            tmp_dir = self.TmpDir\n        elif not tmp_dir.endswith(\"/\"):\n            tmp_dir += \"/\"\n        if include_class_id:\n            class_id = str(self.__class__())\n            prefix = ''.join([prefix,\n                              class_id[class_id.rindex('.') + 1:\n                                       class_id.index(' ')]])\n        try:\n            mkdir(tmp_dir)\n        except OSError:\n            pass\n        return result_constructor(tmp_dir) + result_constructor(prefix) + \\\n            result_constructor(''.join([choice(_all_chars)\n                                        for i in range(self.TmpNameLen)])) +\\\n            result_constructor(suffix)",
    "docstring": "Return a temp filename\n\n            tmp_dir: directory where temporary files will be stored\n            prefix: text to append to start of file name\n            suffix: text to append to end of file name\n            include_class_id: if True, will append a class identifier (built\n             from the class name) to the filename following prefix. This is\n             False by default b/c there is some string processing overhead\n             in getting the class name. This will probably be most useful for\n             testing: if temp files are being left behind by tests, you can\n             turn this on in here (temporarily) to find out which tests are\n             leaving the temp files.\n            result_constructor: the constructor used to build the result\n             (default: cogent.app.parameters.FilePath). Note that joining\n             FilePath objects with one another or with strings, you must use\n             the + operator. If this causes trouble, you can pass str as the\n             the result_constructor."
  },
  {
    "code": "def _find_address_range(addresses):\n    first = last = addresses[0]\n    last_index = 0\n    for ip in addresses[1:]:\n        if ip._ip == last._ip + 1:\n            last = ip\n            last_index += 1\n        else:\n            break\n    return (first, last, last_index)",
    "docstring": "Find a sequence of addresses.\n\n    Args:\n        addresses: a list of IPv4 or IPv6 addresses.\n\n    Returns:\n        A tuple containing the first and last IP addresses in the sequence,\n        and the index of the last IP address in the sequence."
  },
  {
    "code": "def annotation(args):\n    from jcvi.formats.base import DictFile\n    p = OptionParser(annotation.__doc__)\n    p.add_option(\"--queryids\", help=\"Query IDS file to switch [default: %default]\")\n    p.add_option(\"--subjectids\", help=\"Subject IDS file to switch [default: %default]\")\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(not p.print_help())\n    blastfile, = args\n    d = \"\\t\"\n    qids = DictFile(opts.queryids, delimiter=d) if opts.queryids else None\n    sids = DictFile(opts.subjectids, delimiter=d) if opts.subjectids else None\n    blast = Blast(blastfile)\n    for b in blast:\n        query, subject = b.query, b.subject\n        if qids:\n            query = qids[query]\n        if sids:\n            subject = sids[subject]\n        print(\"\\t\".join((query, subject)))",
    "docstring": "%prog annotation blastfile > annotations\n\n    Create simple two column files from the first two coluns in blastfile. Use\n    --queryids and --subjectids to switch IDs or descriptions."
  },
  {
    "code": "def maximum_address(self):\n        maximum_address = self._segments.maximum_address\n        if maximum_address is not None:\n            maximum_address //= self.word_size_bytes\n        return maximum_address",
    "docstring": "The maximum address of the data, or ``None`` if the file is empty."
  },
  {
    "code": "def set_setting(key, value, qsettings=None):\n    full_key = '%s/%s' % (APPLICATION_NAME, key)\n    set_general_setting(full_key, value, qsettings)",
    "docstring": "Set value to QSettings based on key in InaSAFE scope.\n\n    :param key: Unique key for setting.\n    :type key: basestring\n\n    :param value: Value to be saved.\n    :type value: QVariant\n\n    :param qsettings: A custom QSettings to use. If it's not defined, it will\n        use the default one.\n    :type qsettings: qgis.PyQt.QtCore.QSettings"
  },
  {
    "code": "def count_dimensions(entry):\n    result = 0\n    for e in entry:\n        if isinstance(e, str):\n            sliced = e.strip(\",\").split(\",\")\n            result += 0 if len(sliced) == 1 and sliced[0] == \"\" else len(sliced)\n    return result",
    "docstring": "Counts the number of dimensions from a nested list of dimension assignments\n    that may include function calls."
  },
  {
    "code": "def sponsor_tagged_image(sponsor, tag):\n    if sponsor.files.filter(tag_name=tag).exists():\n        return sponsor.files.filter(tag_name=tag).first().tagged_file.item.url\n    return ''",
    "docstring": "returns the corresponding url from the tagged image list."
  },
  {
    "code": "def add_callback(self, name, callback, echo_old=False, priority=0):\n        if self.is_callback_property(name):\n            prop = getattr(type(self), name)\n            prop.add_callback(self, callback, echo_old=echo_old, priority=priority)\n        else:\n            raise TypeError(\"attribute '{0}' is not a callback property\".format(name))",
    "docstring": "Add a callback that gets triggered when a callback property of the\n        class changes.\n\n        Parameters\n        ----------\n        name : str\n            The instance to add the callback to.\n        callback : func\n            The callback function to add\n        echo_old : bool, optional\n            If `True`, the callback function will be invoked with both the old\n            and new values of the property, as ``callback(old, new)``. If `False`\n            (the default), will be invoked as ``callback(new)``\n        priority : int, optional\n            This can optionally be used to force a certain order of execution of\n            callbacks (larger values indicate a higher priority)."
  },
  {
    "code": "def get_tags(self, rev=None):\n\t\trev = rev or 'HEAD'\n\t\treturn set(self._invoke('tag', '--points-at', rev).splitlines())",
    "docstring": "Return the tags for the current revision as a set"
  },
  {
    "code": "def _get_script_args(cls, type_, name, header, script_text):\n        if type_ == 'gui':\n            launcher_type = 'gui'\n            ext = '-script.pyw'\n            old = ['.pyw']\n        else:\n            launcher_type = 'cli'\n            ext = '-script.py'\n            old = ['.py', '.pyc', '.pyo']\n        hdr = cls._adjust_header(type_, header)\n        blockers = [name + x for x in old]\n        yield (name + ext, hdr + script_text, 't', blockers)\n        yield (\n            name + '.exe', get_win_launcher(launcher_type),\n            'b'\n        )\n        if not is_64bit():\n            m_name = name + '.exe.manifest'\n            yield (m_name, load_launcher_manifest(name), 't')",
    "docstring": "For Windows, add a .py extension and an .exe launcher"
  },
  {
    "code": "def get_payment_request(self, cart, request):\n        try:\n            self.charge(cart, request)\n            thank_you_url = OrderModel.objects.get_latest_url()\n            js_expression = 'window.location.href=\"{}\";'.format(thank_you_url)\n            return js_expression\n        except (KeyError, stripe.error.StripeError) as err:\n            raise ValidationError(err)",
    "docstring": "From the given request, add a snippet to the page."
  },
  {
    "code": "def hydra_parser(in_file, options=None):\n    if options is None: options = {}\n    BedPe = namedtuple('BedPe', [\"chrom1\", \"start1\", \"end1\",\n                                 \"chrom2\", \"start2\", \"end2\",\n                                 \"name\", \"strand1\", \"strand2\",\n                                 \"support\"])\n    with open(in_file) as in_handle:\n        reader = csv.reader(in_handle, dialect=\"excel-tab\")\n        for line in reader:\n            cur = BedPe(line[0], int(line[1]), int(line[2]),\n                        line[3], int(line[4]), int(line[5]),\n                        line[6], line[8], line[9],\n                        float(line[18]))\n            if cur.support >= options.get(\"min_support\", 0):\n                yield cur",
    "docstring": "Parse hydra input file into namedtuple of values."
  },
  {
    "code": "def objname(self, obj=None):\n        obj = obj or self.obj\n        _objname = self.pretty_objname(obj, color=None)\n        _objname = \"'{}'\".format(colorize(_objname, \"blue\"))\n        return _objname",
    "docstring": "Formats object names in a pretty fashion"
  },
  {
    "code": "def _energy_evaluation(self, operator):\n        if self._quantum_state is not None:\n            input_circuit = self._quantum_state\n        else:\n            input_circuit = [self.opt_circuit]\n        if operator._paulis:\n            mean_energy, std_energy = operator.evaluate_with_result(self._operator_mode, input_circuit,\n                                                                    self._quantum_instance.backend, self.ret)\n        else:\n            mean_energy = 0.0\n            std_energy = 0.0\n        operator.disable_summarize_circuits()\n        logger.debug('Energy evaluation {} returned {}'.format(self._eval_count, np.real(mean_energy)))\n        return np.real(mean_energy), np.real(std_energy)",
    "docstring": "Evaluate the energy of the current input circuit with respect to the given operator.\n\n        :param operator: Hamiltonian of the system\n\n        :return: Energy of the Hamiltonian"
  },
  {
    "code": "def get_expr_summ_id(self, experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id = None):\n\t\tfor row in self:\n\t\t\tif (row.experiment_id, row.time_slide_id, row.veto_def_name, row.datatype, row.sim_proc_id) == (experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id):\n\t\t\t\treturn row.experiment_summ_id\n\t\treturn None",
    "docstring": "Return the expr_summ_id for the row in the table whose experiment_id, \n\t\ttime_slide_id, veto_def_name, and datatype match the given. If sim_proc_id,\n\t\twill retrieve the injection run matching that sim_proc_id.\n\t\tIf a matching row is not found, returns None."
  },
  {
    "code": "def figs(self):\n        ret = utils.DefaultOrderedDict(lambda: self[1:0])\n        for arr in self:\n            if arr.psy.plotter is not None:\n                ret[arr.psy.plotter.ax.get_figure()].append(arr)\n        return OrderedDict(ret)",
    "docstring": "A mapping from figures to data objects with the plotter in this\n        figure"
  },
  {
    "code": "def create_response(version, status, headers):\n    message = []\n    message.append('HTTP/{} {}\\r\\n'.format(version, status))\n    for name, value in headers:\n        message.append(name)\n        message.append(': ')\n        message.append(value)\n        message.append('\\r\\n')\n    message.append('\\r\\n')\n    return s2b(''.join(message))",
    "docstring": "Create a HTTP response header."
  },
  {
    "code": "def create_channels(chan_name=None, n_chan=None):\n    if chan_name is not None:\n        n_chan = len(chan_name)\n    elif n_chan is not None:\n        chan_name = _make_chan_name(n_chan)\n    else:\n        raise TypeError('You need to specify either the channel names (chan_name) or the number of channels (n_chan)')\n    xyz = round(random.randn(n_chan, 3) * 10, decimals=2)\n    return Channels(chan_name, xyz)",
    "docstring": "Create instance of Channels with random xyz coordinates\n\n    Parameters\n    ----------\n    chan_name : list of str\n        names of the channels\n    n_chan : int\n        if chan_name is not specified, this defines the number of channels\n\n    Returns\n    -------\n    instance of Channels\n        where the location of the channels is random"
  },
  {
    "code": "def _array2cstr(arr):\n    out = StringIO()\n    np.save(out, arr)\n    return b64encode(out.getvalue())",
    "docstring": "Serializes a numpy array to a compressed base64 string"
  },
  {
    "code": "def signalize_extensions():\n    warnings.warn(\"DB-API extension cursor.rownumber used\", SalesforceWarning)\n    warnings.warn(\"DB-API extension connection.<exception> used\", SalesforceWarning)\n    warnings.warn(\"DB-API extension cursor.connection used\", SalesforceWarning)\n    warnings.warn(\"DB-API extension cursor.messages used\", SalesforceWarning)\n    warnings.warn(\"DB-API extension connection.messages used\", SalesforceWarning)\n    warnings.warn(\"DB-API extension cursor.next(, SalesforceWarning) used\")\n    warnings.warn(\"DB-API extension cursor.__iter__(, SalesforceWarning) used\")\n    warnings.warn(\"DB-API extension cursor.lastrowid used\", SalesforceWarning)\n    warnings.warn(\"DB-API extension .errorhandler used\", SalesforceWarning)",
    "docstring": "DB API 2.0 extension are reported by warnings at run-time."
  },
  {
    "code": "def extend(self, delta):\n\t\tif delta.total_seconds() < 0:\n\t\t\traise ValueError(\"delta must be a positive timedelta.\")\n\t\tif self.trial_end is not None and self.trial_end > timezone.now():\n\t\t\tperiod_end = self.trial_end\n\t\telse:\n\t\t\tperiod_end = self.current_period_end\n\t\tperiod_end += delta\n\t\treturn self.update(prorate=False, trial_end=period_end)",
    "docstring": "Extends this subscription by the provided delta.\n\n\t\t:param delta: The timedelta by which to extend this subscription.\n\t\t:type delta: timedelta"
  },
  {
    "code": "def _set_channel_gain(self, num):\n        if not 1 <= num <= 3:\n            raise AttributeError(\n            )\n        for _ in range(num):\n            logging.debug(\"_set_channel_gain called\")\n            start_counter = time.perf_counter()\n            GPIO.output(self._pd_sck, True)\n            GPIO.output(self._pd_sck, False)\n            end_counter = time.perf_counter()\n            time_elapsed = float(end_counter - start_counter)\n            if time_elapsed >= 0.00006:\n                logging.warning(\n                    'setting gain and channel took more than 60µs. '\n                    'Time elapsed: {:0.8f}'.format(time_elapsed)\n                )\n                result = self.get_raw_data(times=6)\n                if result is False:\n                    raise GenericHX711Exception(\"channel was not set properly\")\n        return True",
    "docstring": "Finish data transmission from HX711 by setting\n        next required gain and channel\n\n        Only called from the _read function.\n        :param num: how often so do the set (1...3)\n        :type num: int\n        :return True on success\n        :rtype bool"
  },
  {
    "code": "def _add_item(self, cls, *args, **kwargs):\n        box_index = kwargs.pop('box_index', self._default_box_index)\n        data = cls.validate(*args, **kwargs)\n        n = cls.vertex_count(**data)\n        if not isinstance(box_index, np.ndarray):\n            k = len(self._default_box_index)\n            box_index = _get_array(box_index, (n, k))\n        data['box_index'] = box_index\n        if cls not in self._items:\n            self._items[cls] = []\n        self._items[cls].append(data)\n        return data",
    "docstring": "Add a plot item."
  },
  {
    "code": "def _write_plan(self, stream):\n        if self.plan is not None:\n            if not self._plan_written:\n                print(\"1..{0}\".format(self.plan), file=stream)\n            self._plan_written = True",
    "docstring": "Write the plan line to the stream.\n\n        If we have a plan and have not yet written it out, write it to\n        the given stream."
  },
  {
    "code": "def transform(self, X, y=None, copy=None):\n        check_is_fitted(self, 'scale_')\n        copy = copy if copy is not None else self.copy\n        X = check_array(X, accept_sparse='csr', copy=copy, warn_on_dtype=True,\n                        estimator=self, dtype=FLOAT_DTYPES)\n        if sparse.issparse(X):\n            if self.with_mean:\n                raise ValueError(\n                    \"Cannot center sparse matrices: pass `with_mean=False` \"\n                    \"instead. See docstring for motivation and alternatives.\")\n            if self.scale_ is not None:\n                inplace_column_scale(X, 1 / self.scale_)\n        else:\n            if self.with_mean:\n                X -= self.mean_\n            if self.with_std:\n                X /= self.scale_\n        return X",
    "docstring": "Perform standardization by centering and scaling using the parameters.\n\n        :param X: Data matrix to scale.\n        :type X: numpy.ndarray, shape [n_samples, n_features]\n        :param y: Passthrough for scikit-learn ``Pipeline`` compatibility.\n        :type y: None\n        :param bool copy: Copy the X matrix.\n        :return: Scaled version of the X data matrix.\n        :rtype: numpy.ndarray, shape [n_samples, n_features]"
  },
  {
    "code": "def get_offset(cls, info):\n        assert info.layer == 3\n        if info.version == 1:\n            if info.mode != 3:\n                return 36\n            else:\n                return 21\n        else:\n            if info.mode != 3:\n                return 21\n            else:\n                return 13",
    "docstring": "Calculate the offset to the Xing header from the start of the\n        MPEG header including sync based on the MPEG header's content."
  },
  {
    "code": "def get_password(self):\n        if self.password is None:\n            if os.environ.get(self.username+'password'):\n                self.password = os.environ.get(self.username+'password')\n            else:\n                raise PasswordError(self.username)",
    "docstring": "If password is not provided will look in environment variables\n        for username+'password'."
  },
  {
    "code": "def faces_unique_edges(self):\n        populate = self.edges_unique\n        result = self._cache['edges_unique_inverse'].reshape((-1, 3))\n        return result",
    "docstring": "For each face return which indexes in mesh.unique_edges constructs\n        that face.\n\n        Returns\n        ---------\n        faces_unique_edges : (len(self.faces), 3) int\n          Indexes of self.edges_unique that\n          construct self.faces\n\n        Examples\n        ---------\n        In [0]: mesh.faces[0:2]\n        Out[0]:\n        TrackedArray([[    1,  6946, 24224],\n                      [ 6946,  1727, 24225]])\n\n        In [1]: mesh.edges_unique[mesh.faces_unique_edges[0:2]]\n        Out[1]:\n        array([[[    1,  6946],\n                [ 6946, 24224],\n                [    1, 24224]],\n               [[ 1727,  6946],\n                [ 1727, 24225],\n                [ 6946, 24225]]])"
  },
  {
    "code": "def _init_go_sources(self, go_sources_arg, go2obj_arg):\n        gos_user = set(go_sources_arg)\n        if 'children' in self.kws and self.kws['children']:\n            gos_user |= get_leaf_children(gos_user, go2obj_arg)\n        gos_godag = set(go2obj_arg)\n        gos_source = gos_user.intersection(gos_godag)\n        gos_missing = gos_user.difference(gos_godag)\n        if not gos_missing:\n            return gos_source\n        sys.stdout.write(\"{N} GO IDs NOT FOUND IN GO DAG: {GOs}\\n\".format(\n            N=len(gos_missing), GOs=\" \".join([str(e) for e in gos_missing])))\n        return gos_source",
    "docstring": "Return GO sources which are present in GODag."
  },
  {
    "code": "def connect_db(config):\n    rv = sqlite3.connect(config[\"database\"][\"uri\"])\n    rv.row_factory = sqlite3.Row\n    return rv",
    "docstring": "Connects to the specific database."
  },
  {
    "code": "def _get_ctypes(self):\n        ctypes = []\n        for related_object in self.model._meta.get_all_related_objects():\n            model = getattr(related_object, 'related_model', related_object.model)\n            ctypes.append(ContentType.objects.get_for_model(model).pk)\n            if model.__subclasses__():\n                for child in model.__subclasses__():\n                    ctypes.append(ContentType.objects.get_for_model(child).pk)\n        return ctypes",
    "docstring": "Returns all related objects for this model."
  },
  {
    "code": "def argsize(self):\n        argsize = sum(arg.nbytes for arg in self.argdefns)\n        return argsize if len(self.argdefns) > 0 else 0",
    "docstring": "The total size in bytes of all the command arguments."
  },
  {
    "code": "def validate(self, value):\n        errors = []\n        self._used_validator = []\n        for val in self._validators:\n            try:\n                val.validate(value)\n                self._used_validator.append(val)\n            except ValidatorException as e:\n                errors.append(e)\n            except Exception as e:\n                errors.append(ValidatorException(\"Unknown Error\", e))\n        if len(errors) > 0:\n            raise ValidatorException.from_list(errors)\n        return value",
    "docstring": "validate function form OrValidator\n\n        Returns:\n            True if at least one of the validators\n            validate function return True"
  },
  {
    "code": "def render(self, data, accepted_media_type=None, renderer_context=None):\n        assert yaml, 'YAMLRenderer requires pyyaml to be installed'\n        if data is None:\n            return ''\n        return yaml.dump(\n            data,\n            stream=None,\n            encoding=self.charset,\n            Dumper=self.encoder,\n            allow_unicode=not self.ensure_ascii,\n            default_flow_style=self.default_flow_style\n        )",
    "docstring": "Renders `data` into serialized YAML."
  },
  {
    "code": "def set_exception(self, exception):\n        self._exception = exception\n        self._result_set = True\n        self._invoke_callbacks(self)",
    "docstring": "Set the Future's exception."
  },
  {
    "code": "def tune_scale(acceptance, scale):\n        if acceptance > 0.8:\n            scale *= 2.0\n        elif acceptance <= 0.8 and acceptance > 0.4:\n            scale *= 1.3            \n        elif acceptance < 0.234 and acceptance > 0.1:\n            scale *= (1/1.3)\n        elif acceptance <= 0.1 and acceptance > 0.05:\n            scale *= 0.4\n        elif acceptance <= 0.05 and acceptance > 0.01:\n            scale *= 0.2\n        elif acceptance <= 0.01:\n            scale *= 0.1\n        return scale",
    "docstring": "Tunes scale for M-H algorithm\n\n        Parameters\n        ----------\n        acceptance : float\n            The most recent acceptance rate\n\n        scale : float\n            The current scale parameter\n\n        Returns\n        ----------\n        scale : float\n            An adjusted scale parameter\n\n        Notes\n        ----------\n        Ross : Initially did this by trial and error, then refined by looking at other\n        implementations, so some credit here to PyMC3 which became a guideline for this."
  },
  {
    "code": "def mesh_surface_area(mesh=None, verts=None, faces=None):\n    r\n    if mesh:\n        verts = mesh.verts\n        faces = mesh.faces\n    else:\n        if (verts is None) or (faces is None):\n            raise Exception('Either mesh or verts and faces must be given')\n    surface_area = measure.mesh_surface_area(verts, faces)\n    return surface_area",
    "docstring": "r\"\"\"\n    Calculates the surface area of a meshed region\n\n    Parameters\n    ----------\n    mesh : tuple\n        The tuple returned from the ``mesh_region`` function\n    verts : array\n        An N-by-ND array containing the coordinates of each mesh vertex\n    faces : array\n        An N-by-ND array indicating which elements in ``verts`` form a mesh\n        element.\n\n    Returns\n    -------\n    surface_area : float\n        The surface area of the mesh, calculated by\n        ``skimage.measure.mesh_surface_area``\n\n    Notes\n    -----\n    This function simply calls ``scikit-image.measure.mesh_surface_area``, but\n    it allows for the passing of the ``mesh`` tuple returned by the\n    ``mesh_region`` function, entirely for convenience."
  },
  {
    "code": "def split(mesh,\n          only_watertight=True,\n          adjacency=None,\n          engine=None):\n    if adjacency is None:\n        adjacency = mesh.face_adjacency\n    if only_watertight:\n        min_len = 3\n    else:\n        min_len = 1\n    components = connected_components(edges=adjacency,\n                                      nodes=np.arange(len(mesh.faces)),\n                                      min_len=min_len,\n                                      engine=engine)\n    meshes = mesh.submesh(components,\n                          only_watertight=only_watertight)\n    return meshes",
    "docstring": "Split a mesh into multiple meshes from face connectivity.\n\n    If only_watertight is true, it will only return watertight meshes\n    and will attempt single triangle/quad repairs.\n\n    Parameters\n    ----------\n    mesh: Trimesh\n    only_watertight: if True, only return watertight components\n    adjacency: (n,2) list of face adjacency to override using the plain\n               adjacency calculated automatically.\n    engine: str, which engine to use. ('networkx', 'scipy', or 'graphtool')\n\n    Returns\n    ----------\n    meshes: list of Trimesh objects"
  },
  {
    "code": "def expand(self, line, do_expand, force=False, vislevels=0, level=-1):\n        lastchild = self.GetLastChild(line, level)\n        line += 1\n        while line <= lastchild:\n            if force:\n                if vislevels > 0:\n                    self.ShowLines(line, line)\n                else:\n                    self.HideLines(line, line)\n            elif do_expand:\n                self.ShowLines(line, line)\n            if level == -1:\n                level = self.GetFoldLevel(line)\n            if level & stc.STC_FOLDLEVELHEADERFLAG:\n                if force:\n                    self.SetFoldExpanded(line, vislevels - 1)\n                    line = self.expand(line, do_expand, force, vislevels - 1)\n                else:\n                    expandsub = do_expand and self.GetFoldExpanded(line)\n                    line = self.expand(line, expandsub, force, vislevels - 1)\n            else:\n                line += 1\n        return line",
    "docstring": "Multi-purpose expand method from original STC class"
  },
  {
    "code": "def uncomment_lines(lines):\n    ret = []\n    for line in lines:\n        ws_prefix, rest, ignore = RE_LINE_SPLITTER_UNCOMMENT.match(line).groups()\n        ret.append(ws_prefix + rest)\n    return ''.join(ret)",
    "docstring": "Uncomment the given list of lines and return them.  The first hash mark\n    following any amount of whitespace will be removed on each line."
  },
  {
    "code": "def remove_file(self):\n        if not self.fullpath or not self.archived:\n            raise RuntimeError()\n        try:\n            os.remove(self.fullpath)\n        except:\n            print(\"Error removing %s: %s\" % (self.fullpath, sys.exc_info()[1]))",
    "docstring": "Removes archived file associated with this DP"
  },
  {
    "code": "def _reset_bbox(self):\n        scale_x, scale_y = self.get_scale_xy()\n        pan_x, pan_y = self.get_pan(coord='data')[:2]\n        win_wd, win_ht = self.get_window_size()\n        win_wd, win_ht = max(1, win_wd), max(1, win_ht)\n        self._calc_bg_dimensions(scale_x, scale_y,\n                                 pan_x, pan_y, win_wd, win_ht)",
    "docstring": "This function should only be called internally.  It resets\n        the viewers bounding box based on changes to pan or scale."
  },
  {
    "code": "def _imm_default_init(self, *args, **kwargs):\n    for (k,v) in six.iteritems({k:v for dct in (args + (kwargs,)) for (k,v) in dct}):\n        setattr(self, k, v)",
    "docstring": "An immutable's defalt initialization function is to accept any number of dictionaries followed\n    by any number of keyword args and to turn them all into the parameters of the immutable that is\n    being created."
  },
  {
    "code": "def _thumbnail_div(target_dir, src_dir, fname, snippet, is_backref=False,\n                   check=True):\n    thumb, _ = _find_image_ext(\n        os.path.join(target_dir, 'images', 'thumb',\n                     'sphx_glr_%s_thumb.png' % fname[:-3]))\n    if check and not os.path.isfile(thumb):\n        raise RuntimeError('Could not find internal sphinx-gallery thumbnail '\n                           'file:\\n%s' % (thumb,))\n    thumb = os.path.relpath(thumb, src_dir)\n    full_dir = os.path.relpath(target_dir, src_dir)\n    thumb = thumb.replace(os.sep, \"/\")\n    ref_name = os.path.join(full_dir, fname).replace(os.path.sep, '_')\n    template = BACKREF_THUMBNAIL_TEMPLATE if is_backref else THUMBNAIL_TEMPLATE\n    return template.format(snippet=escape(snippet),\n                           thumbnail=thumb, ref_name=ref_name)",
    "docstring": "Generates RST to place a thumbnail in a gallery"
  },
  {
    "code": "def ping_interval(self, value):\n        if not isinstance(value, int):\n            raise TypeError(\"ping interval must be int\")\n        if value < 0:\n            raise ValueError(\"ping interval must be greater then 0\")\n        self._ping_interval = value",
    "docstring": "Setter for ping_interval property.\n\n        :param int value: interval in sec between two ping values."
  },
  {
    "code": "def get_webhook(self):\n        api = self._get_api(mds.NotificationsApi)\n        return Webhook(api.get_webhook())",
    "docstring": "Get the current callback URL if it exists.\n\n        :return: The currently set webhook"
  },
  {
    "code": "def parse_excel(file_path: str,\n                entrez_id_header,\n                log_fold_change_header,\n                adjusted_p_value_header,\n                entrez_delimiter,\n                base_mean_header=None) -> List[Gene]:\n    logger.info(\"In parse_excel()\")\n    df = pd.read_excel(file_path)\n    return handle_dataframe(\n        df,\n        entrez_id_name=entrez_id_header,\n        log2_fold_change_name=log_fold_change_header,\n        adjusted_p_value_name=adjusted_p_value_header,\n        entrez_delimiter=entrez_delimiter,\n        base_mean=base_mean_header,\n    )",
    "docstring": "Read an excel file on differential expression values as Gene objects.\n\n    :param str file_path: The path to the differential expression file to be parsed.\n    :param config.Params params: An object that includes paths, cutoffs and other information.\n    :return list: A list of Gene objects."
  },
  {
    "code": "def role_get(auth=None, **kwargs):\n    cloud = get_operator_cloud(auth)\n    kwargs = _clean_kwargs(**kwargs)\n    return cloud.get_role(**kwargs)",
    "docstring": "Get a single role\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' keystoneng.role_get name=role1\n        salt '*' keystoneng.role_get name=role1 domain_id=b62e76fbeeff4e8fb77073f591cf211e\n        salt '*' keystoneng.role_get name=1eb6edd5525e4ac39af571adee673559"
  },
  {
    "code": "def selectNumber(self):\n        le = self.lineEdit()\n        text = asUnicode(le.text())\n        if self.opts['suffix'] == '':\n            le.setSelection(0, len(text))\n        else:\n            try:\n                index = text.index(' ')\n            except ValueError:\n                return\n            le.setSelection(0, index)",
    "docstring": "Select the numerical portion of the text to allow quick editing by the user."
  },
  {
    "code": "def __threshold(self, ymx_i):\n        return ymx_i - (self.S * np.diff(self.xsn).mean())",
    "docstring": "Calculates the difference threshold for a\n        given difference local maximum.\n\n        Parameters\n        -----------\n        ymx_i : float \n           The normalized y value of a local maximum."
  },
  {
    "code": "def cont_r(self, percent=0.9, N=None):\n\t\tif not hasattr(self, 'F'):\n\t\t\tself.fs_r(N=self.rank)\n\t\treturn apply_along_axis(lambda _: _/self.L[:N], 1,\n\t\t\t   apply_along_axis(lambda _: _*self.r, 0, self.F[:, :N]**2))",
    "docstring": "Return the contribution of each row."
  },
  {
    "code": "def get_cod_ids(self, formula):\n        sql = 'select file from data where formula=\"- %s -\"' % \\\n            Composition(formula).hill_formula\n        text = self.query(sql).split(\"\\n\")\n        cod_ids = []\n        for l in text:\n            m = re.search(r\"(\\d+)\", l)\n            if m:\n                cod_ids.append(int(m.group(1)))\n        return cod_ids",
    "docstring": "Queries the COD for all cod ids associated with a formula. Requires\n        mysql executable to be in the path.\n\n        Args:\n            formula (str): Formula.\n\n        Returns:\n            List of cod ids."
  },
  {
    "code": "def dumps():\n    d = {}\n    for k, v in FILTERS.items():\n        d[dr.get_name(k)] = list(v)\n    return _dumps(d)",
    "docstring": "Returns a string representation of the FILTERS dictionary."
  },
  {
    "code": "def from_lt(rsize, ltm, ltv):\n    dbinx = rsize / ltm[0]\n    dbiny = rsize / ltm[1]\n    dxcorner = (dbinx - rsize) - dbinx * ltv[0]\n    dycorner = (dbiny - rsize) - dbiny * ltv[1]\n    bin = (_nint(dbinx), _nint(dbiny))\n    corner = (_nint(dxcorner), _nint(dycorner))\n    return bin, corner",
    "docstring": "Compute the corner location and pixel size in units\n    of unbinned pixels.\n\n    .. note:: Translated from ``calacs/lib/fromlt.c``.\n\n    Parameters\n    ----------\n    rsize : int\n        Reference pixel size. Usually 1.\n\n    ltm, ltv : tuple of float\n        See :func:`get_lt`.\n\n    Returns\n    -------\n    bin : tuple of int\n        Pixel size in X and Y.\n\n    corner : tuple of int\n        Corner of subarray in X and Y."
  },
  {
    "code": "def dec2dec(dec):\n    d = dec.replace(':', ' ').split()\n    if len(d) == 2:\n        d.append(0.0)\n    if d[0].startswith('-') or float(d[0]) < 0:\n        return float(d[0]) - float(d[1]) / 60.0 - float(d[2]) / 3600.0\n    return float(d[0]) + float(d[1]) / 60.0 + float(d[2]) / 3600.0",
    "docstring": "Convert sexegessimal RA string into a float in degrees.\n\n    Parameters\n    ----------\n    dec : string\n        A string separated representing the Dec.\n        Expected format is `[+- ]hh:mm[:ss.s]`\n        Colons can be replaced with any whit space character.\n\n    Returns\n    -------\n    dec : float\n        The Dec in degrees."
  },
  {
    "code": "def get_current(self):\n        now = dt.now().timestamp()\n        url = build_url(self.api_key, self.spot_id, self.fields,\n                        self.unit, now, now)\n        return get_msw(url)",
    "docstring": "Get current forecast."
  },
  {
    "code": "def get_uniprot_evidence_level(header):\n    header = header.split()\n    for item in header:\n        item = item.split('=')\n        try:\n            if item[0] == 'PE':\n                return 5 - int(item[1])\n        except IndexError:\n            continue\n    return -1",
    "docstring": "Returns uniprot protein existence evidence level for a fasta header.\n    Evidence levels are 1-5, but we return 5 - x since sorting still demands\n    that higher is better."
  },
  {
    "code": "def get_entity_type(self,\n                        name,\n                        language_code=None,\n                        retry=google.api_core.gapic_v1.method.DEFAULT,\n                        timeout=google.api_core.gapic_v1.method.DEFAULT,\n                        metadata=None):\n        if 'get_entity_type' not in self._inner_api_calls:\n            self._inner_api_calls[\n                'get_entity_type'] = google.api_core.gapic_v1.method.wrap_method(\n                    self.transport.get_entity_type,\n                    default_retry=self._method_configs['GetEntityType'].retry,\n                    default_timeout=self._method_configs['GetEntityType']\n                    .timeout,\n                    client_info=self._client_info,\n                )\n        request = entity_type_pb2.GetEntityTypeRequest(\n            name=name,\n            language_code=language_code,\n        )\n        return self._inner_api_calls['get_entity_type'](\n            request, retry=retry, timeout=timeout, metadata=metadata)",
    "docstring": "Retrieves the specified entity type.\n\n        Example:\n            >>> import dialogflow_v2\n            >>>\n            >>> client = dialogflow_v2.EntityTypesClient()\n            >>>\n            >>> name = client.entity_type_path('[PROJECT]', '[ENTITY_TYPE]')\n            >>>\n            >>> response = client.get_entity_type(name)\n\n        Args:\n            name (str): Required. The name of the entity type.\n                Format: ``projects/<Project ID>/agent/entityTypes/<EntityType ID>``.\n            language_code (str): Optional. The language to retrieve entity synonyms for. If not specified,\n                the agent's default language is used.\n                [More than a dozen\n                languages](https://dialogflow.com/docs/reference/language) are supported.\n                Note: languages must be enabled in the agent, before they can be used.\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def get_arg_names(target) -> typing.List[str]:\n    code = getattr(target, '__code__')\n    if code is None:\n        return []\n    arg_count = code.co_argcount\n    kwarg_count = code.co_kwonlyargcount\n    args_index = get_args_index(target)\n    kwargs_index = get_kwargs_index(target)\n    arg_names = list(code.co_varnames[:arg_count])\n    if args_index != -1:\n        arg_names.append(code.co_varnames[args_index])\n    arg_names += list(code.co_varnames[arg_count:(arg_count + kwarg_count)])\n    if kwargs_index != -1:\n        arg_names.append(code.co_varnames[kwargs_index])\n    if len(arg_names) > 0 and arg_names[0] in ['self', 'cls']:\n        arg_count -= 1\n        arg_names.pop(0)\n    return arg_names",
    "docstring": "Gets the list of named arguments for the target function\n\n    :param target:\n        Function for which the argument names will be retrieved"
  },
  {
    "code": "def load(uid=None):\n    app.logger.info(\"GET /sync route with id: %s\" % uid)\n    try:\n        user = Participant.query.\\\n            filter(Participant.uniqueid == uid).\\\n            one()\n    except exc.SQLAlchemyError:\n        app.logger.error(\"DB error: Unique user not found.\")\n    try:\n        resp = json.loads(user.datastring)\n    except:\n        resp = {\n            \"condition\": user.cond,\n            \"counterbalance\": user.counterbalance,\n            \"assignmentId\": user.assignmentid,\n            \"workerId\": user.workerid,\n            \"hitId\": user.hitid,\n            \"bonus\": user.bonus\n        }\n    return jsonify(**resp)",
    "docstring": "Load experiment data, which should be a JSON object and will be stored\n    after converting to string."
  },
  {
    "code": "def value_to_datum(self, instance, value):\n        if value is None:\n            return None\n        bound = getattr(instance._origin, self.cls)\n        if type(value) is bound:\n            if self.use_data_setter:\n                return value._data\n            else:\n                descriptors, alt_descriptors = get_pk_descriptors(bound)\n                if len(descriptors) == 1:\n                    return getattr(value, descriptors[0][0])\n                elif len(descriptors) > 1:\n                    return tuple(\n                        getattr(value, name)\n                        for name, _ in descriptors\n                    )\n                else:\n                    raise AttributeError(\n                        \"unable to perform set object no primary key \"\n                        \"fields defined for %s\" % self.cls)\n        else:\n            raise TypeError(\n                \"must be %s, not %s\" % (self.cls, type(value).__name__))",
    "docstring": "Convert a given Python-side value to a MAAS-side datum.\n\n        :param instance: The `Object` instance on which this field is\n            currently operating. This method should treat it as read-only, for\n            example to perform validation with regards to other fields.\n        :param datum: The Python-side value to validate and convert into a\n            MAAS-side datum.\n        :return: A datum derived from the given value."
  },
  {
    "code": "def create_open_msg(self):\n        asnum = self.local_as\n        if not is_valid_old_asn(asnum):\n            asnum = bgp.AS_TRANS\n        bgpid = self._common_conf.router_id\n        holdtime = self._neigh_conf.hold_time\n        def flatten(L):\n            if isinstance(L, list):\n                for i in range(len(L)):\n                    for e in flatten(L[i]):\n                        yield e\n            else:\n                yield L\n        opts = list(flatten(\n            list(self._neigh_conf.get_configured_capabilities().values())))\n        open_msg = BGPOpen(\n            my_as=asnum,\n            bgp_identifier=bgpid,\n            version=const.BGP_VERSION_NUM,\n            hold_time=holdtime,\n            opt_param=opts\n        )\n        return open_msg",
    "docstring": "Create `Open` message using current settings.\n\n        Current setting include capabilities, timers and ids."
  },
  {
    "code": "def create(cls, name, members=None, comment=None):\n        element = [] if members is None else element_resolver(members)\n        json = {'name': name,\n                'element': element,\n                'comment': comment}\n        return ElementCreator(cls, json)",
    "docstring": "Create the TCP Service group\n\n        :param str name: name of tcp service group\n        :param list element: tcp services by element or href\n        :type element: list(str,Element)\n        :raises CreateElementFailed: element creation failed with reason\n        :return: instance with meta\n        :rtype: TCPServiceGroup"
  },
  {
    "code": "def satisfiesExternal(cntxt: Context, n: Node, se: ShExJ.ShapeExternal, c: DebugContext) -> bool:\n    if c.debug:\n        print(f\"id: {se.id}\")\n    extern_shape = cntxt.external_shape_for(se.id)\n    if extern_shape:\n        return satisfies(cntxt, n, extern_shape)\n    cntxt.fail_reason = f\"{se.id}: Shape is not in Schema\"\n    return False",
    "docstring": "Se is a ShapeExternal and implementation-specific mechansims not defined in this specification indicate\n     success."
  },
  {
    "code": "def _get_key_redis_key(bank, key):\n    opts = _get_redis_keys_opts()\n    return '{prefix}{separator}{bank}/{key}'.format(\n        prefix=opts['key_prefix'],\n        separator=opts['separator'],\n        bank=bank,\n        key=key\n    )",
    "docstring": "Return the Redis key given the bank name and the key name."
  },
  {
    "code": "def update(self, title=None, description=None, images=None, cover=None,\n               layout=None, privacy=None):\n        url = (self._imgur._base_url + \"/3/album/\"\n               \"{0}\".format(self._delete_or_id_hash))\n        is_updated = self._imgur._send_request(url, params=locals(),\n                                               method='POST')\n        if is_updated:\n            self.title = title or self.title\n            self.description = description or self.description\n            self.layout = layout or self.layout\n            self.privacy = privacy or self.privacy\n            if cover is not None:\n                self.cover = (cover if isinstance(cover, Image)\n                              else Image({'id': cover}, self._imgur,\n                                         has_fetched=False))\n            if images:\n                self.images = [img if isinstance(img, Image) else\n                               Image({'id': img}, self._imgur, False)\n                               for img in images]\n        return is_updated",
    "docstring": "Update the album's information.\n\n        Arguments with the value None will retain their old values.\n\n        :param title: The title of the album.\n        :param description: A description of the album.\n        :param images: A list of the images we want the album to contain.\n            Can be Image objects, ids or a combination of the two. Images that\n            images that you cannot set (non-existing or not owned by you) will\n            not cause exceptions, but fail silently.\n        :param privacy: The albums privacy level, can be public, hidden or\n            secret.\n        :param cover: The id of the cover image.\n        :param layout: The way the album is displayed, can be blog, grid,\n            horizontal or vertical."
  },
  {
    "code": "def show_plot_methods(self):\n        print_func = PlotterInterface._print_func\n        if print_func is None:\n            print_func = six.print_\n        s = \"\\n\".join(\n            \"%s\\n    %s\" % t for t in six.iteritems(self._plot_methods))\n        return print_func(s)",
    "docstring": "Print the plotmethods of this instance"
  },
  {
    "code": "def close(self):\n        _LOGGER.debug(\"Joining submission queue\")\n        self._submission_queue.join()\n        _LOGGER.debug(\"Joining cancel queue\")\n        self._cancel_queue.join()\n        _LOGGER.debug(\"Joining poll queue\")\n        self._poll_queue.join()\n        _LOGGER.debug(\"Joining load queue\")\n        self._load_queue.join()\n        for _ in self._submission_workers:\n            self._submission_queue.put(None)\n        for _ in self._cancel_workers:\n            self._cancel_queue.put(None)\n        for _ in self._poll_workers:\n            self._poll_queue.put((-1, None))\n        for _ in self._load_workers:\n            self._load_queue.put(None)\n        for worker in chain(self._submission_workers, self._cancel_workers,\n                            self._poll_workers, self._load_workers):\n            worker.join()\n        self.session.close()",
    "docstring": "Perform a clean shutdown.\n\n        Waits for all the currently scheduled work to finish, kills the workers,\n        and closes the connection pool.\n\n        .. note:: Ensure your code does not submit new work while the connection is closing.\n\n        Where possible, it is recommended you use a context manager (a :code:`with Client.from_config(...) as`\n        construct) to ensure your code properly closes all resources.\n\n        Examples:\n            This example creates a client (based on an auto-detected configuration file), executes\n            some code (represented by a placeholder comment), and then closes the client.\n\n            >>> from dwave.cloud import Client\n            >>> client = Client.from_config()\n            >>> # code that uses client\n            >>> client.close()"
  },
  {
    "code": "def is_causal_sink(graph: BELGraph, node: BaseEntity) -> bool:\n    return has_causal_in_edges(graph, node) and not has_causal_out_edges(graph, node)",
    "docstring": "Return true if the node is a causal sink.\n\n    - Does have causal in edge(s)\n    - Doesn't have any causal out edge(s)"
  },
  {
    "code": "def verify_signature(public_key, signature, hash, hash_algo):\n    hash_algo = _hash_algorithms[hash_algo]\n    try:\n        return get_publickey(public_key).verify(\n            signature,\n            hash,\n            padding.PKCS1v15(),\n            utils.Prehashed(hash_algo),\n        ) is None\n    except InvalidSignature:\n        return False",
    "docstring": "Verify the given signature is correct for the given hash and public key.\n\n    Args:\n        public_key (str): PEM encoded public key\n        signature (bytes): signature to verify\n        hash (bytes): hash of data\n        hash_algo (str): hash algorithm used\n\n    Returns:\n        True if the signature is valid, False otherwise"
  },
  {
    "code": "def method2jpg(output, mx, raw=False):\n    buff = raw\n    if not raw:\n        buff = method2dot(mx)\n    method2format(output, \"jpg\", mx, buff)",
    "docstring": "Export method to a jpg file format\n\n    :param output: output filename\n    :type output: string\n    :param mx: specify the MethodAnalysis object\n    :type mx: :class:`MethodAnalysis` object\n    :param raw: use directly a dot raw buffer (optional)\n    :type raw: string"
  },
  {
    "code": "def compute_search_volume_in_bins(found, total, ndbins, sim_to_bins_function):\n    eff, err = compute_search_efficiency_in_bins(\n                                    found, total, ndbins, sim_to_bins_function)\n    dx = ndbins[0].upper() - ndbins[0].lower()\n    r = ndbins[0].centres()\n    vol = bin_utils.BinnedArray(bin_utils.NDBins(ndbins[1:]))\n    errors = bin_utils.BinnedArray(bin_utils.NDBins(ndbins[1:]))\n    vol.array = numpy.trapz(eff.array.T * 4. * numpy.pi * r**2, r, dx)\n    errors.array = numpy.sqrt(\n        ((4 * numpy.pi * r**2 * err.array.T * dx)**2).sum(axis=-1)\n    )\n    return vol, errors",
    "docstring": "Calculate search sensitive volume by integrating efficiency in distance bins\n\n    No cosmological corrections are applied: flat space is assumed.\n    The first dimension of ndbins must be bins over injected distance.\n    sim_to_bins_function must maps an object to a tuple indexing the ndbins."
  },
  {
    "code": "def reset_index(self, level=None, drop=False, name=None, inplace=False):\n        inplace = validate_bool_kwarg(inplace, 'inplace')\n        if drop:\n            new_index = ibase.default_index(len(self))\n            if level is not None:\n                if not isinstance(level, (tuple, list)):\n                    level = [level]\n                level = [self.index._get_level_number(lev) for lev in level]\n                if len(level) < self.index.nlevels:\n                    new_index = self.index.droplevel(level)\n            if inplace:\n                self.index = new_index\n                self.name = name or self.name\n            else:\n                return self._constructor(self._values.copy(),\n                                         index=new_index).__finalize__(self)\n        elif inplace:\n            raise TypeError('Cannot reset_index inplace on a Series '\n                            'to create a DataFrame')\n        else:\n            df = self.to_frame(name)\n            return df.reset_index(level=level, drop=drop)",
    "docstring": "Generate a new DataFrame or Series with the index reset.\n\n        This is useful when the index needs to be treated as a column, or\n        when the index is meaningless and needs to be reset to the default\n        before another operation.\n\n        Parameters\n        ----------\n        level : int, str, tuple, or list, default optional\n            For a Series with a MultiIndex, only remove the specified levels\n            from the index. Removes all levels by default.\n        drop : bool, default False\n            Just reset the index, without inserting it as a column in\n            the new DataFrame.\n        name : object, optional\n            The name to use for the column containing the original Series\n            values. Uses ``self.name`` by default. This argument is ignored\n            when `drop` is True.\n        inplace : bool, default False\n            Modify the Series in place (do not create a new object).\n\n        Returns\n        -------\n        Series or DataFrame\n            When `drop` is False (the default), a DataFrame is returned.\n            The newly created columns will come first in the DataFrame,\n            followed by the original Series values.\n            When `drop` is True, a `Series` is returned.\n            In either case, if ``inplace=True``, no value is returned.\n\n        See Also\n        --------\n        DataFrame.reset_index: Analogous function for DataFrame.\n\n        Examples\n        --------\n        >>> s = pd.Series([1, 2, 3, 4], name='foo',\n        ...               index=pd.Index(['a', 'b', 'c', 'd'], name='idx'))\n\n        Generate a DataFrame with default index.\n\n        >>> s.reset_index()\n          idx  foo\n        0   a    1\n        1   b    2\n        2   c    3\n        3   d    4\n\n        To specify the name of the new column use `name`.\n\n        >>> s.reset_index(name='values')\n          idx  values\n        0   a       1\n        1   b       2\n        2   c       3\n        3   d       4\n\n        To generate a new Series with the default set `drop` to True.\n\n        >>> s.reset_index(drop=True)\n        0    1\n        1    2\n        2    3\n        3    4\n        Name: foo, dtype: int64\n\n        To update the Series in place, without generating a new one\n        set `inplace` to True. Note that it also requires ``drop=True``.\n\n        >>> s.reset_index(inplace=True, drop=True)\n        >>> s\n        0    1\n        1    2\n        2    3\n        3    4\n        Name: foo, dtype: int64\n\n        The `level` parameter is interesting for Series with a multi-level\n        index.\n\n        >>> arrays = [np.array(['bar', 'bar', 'baz', 'baz']),\n        ...           np.array(['one', 'two', 'one', 'two'])]\n        >>> s2 = pd.Series(\n        ...     range(4), name='foo',\n        ...     index=pd.MultiIndex.from_arrays(arrays,\n        ...                                     names=['a', 'b']))\n\n        To remove a specific level from the Index, use `level`.\n\n        >>> s2.reset_index(level='a')\n               a  foo\n        b\n        one  bar    0\n        two  bar    1\n        one  baz    2\n        two  baz    3\n\n        If `level` is not set, all levels are removed from the Index.\n\n        >>> s2.reset_index()\n             a    b  foo\n        0  bar  one    0\n        1  bar  two    1\n        2  baz  one    2\n        3  baz  two    3"
  },
  {
    "code": "def _setup_metric_group_definitions(self):\n        metric_group_definitions = dict()\n        for mg_info in self.properties['metric-group-infos']:\n            mg_name = mg_info['group-name']\n            mg_def = MetricGroupDefinition(\n                name=mg_name,\n                resource_class=_resource_class_from_group(mg_name),\n                metric_definitions=dict())\n            for i, m_info in enumerate(mg_info['metric-infos']):\n                m_name = m_info['metric-name']\n                m_def = MetricDefinition(\n                    index=i,\n                    name=m_name,\n                    type=_metric_type(m_info['metric-type']),\n                    unit=_metric_unit_from_name(m_name))\n                mg_def.metric_definitions[m_name] = m_def\n            metric_group_definitions[mg_name] = mg_def\n        return metric_group_definitions",
    "docstring": "Return the dict of MetricGroupDefinition objects for this metrics\n        context, by processing its 'metric-group-infos' property."
  },
  {
    "code": "def _ValidateValue(value, type_check):\n  if inspect.isclass(type_check):\n    return isinstance(value, type_check)\n  if isinstance(type_check, tuple):\n    return _ValidateTuple(value, type_check)\n  elif callable(type_check):\n    return type_check(value)\n  else:\n    raise TypeError(\"Invalid type check '%s'\" % repr(type_check))",
    "docstring": "Validate a single value with type_check."
  },
  {
    "code": "def getAspect(obj1, obj2, aspList):\n    ap = _getActivePassive(obj1, obj2)\n    aspDict = _aspectDict(ap['active'], ap['passive'], aspList)\n    if not aspDict:\n        aspDict = {\n            'type': const.NO_ASPECT,\n            'orb': 0,\n            'separation': 0,\n        } \n    aspProp = _aspectProperties(ap['active'], ap['passive'], aspDict)\n    return Aspect(aspProp)",
    "docstring": "Returns an Aspect object for the aspect between two\n    objects considering a list of possible aspect types."
  },
  {
    "code": "def get_formset(self, request, obj=None, **kwargs):\n        FormSet = super(TranslatableInlineModelAdmin, self).get_formset(request, obj, **kwargs)\n        FormSet.language_code = self.get_form_language(request, obj)\n        if self.inline_tabs:\n            available_languages = self.get_available_languages(obj, FormSet)\n            FormSet.language_tabs = self.get_language_tabs(request, obj, available_languages, css_class='parler-inline-language-tabs')\n            FormSet.language_tabs.allow_deletion = self._has_translatable_parent_model()\n        return FormSet",
    "docstring": "Return the formset, and provide the language information to the formset."
  },
  {
    "code": "def cmd(self, cmd, verbose=False):\n        command = cmd.format(maildir=self.directory)\n        if verbose:\n            print(command)\n        p = Popen([\n                \"ssh\",\n                \"-T\",\n                self.host,\n                command\n                ], stdin=PIPE, stdout=PIPE, stderr=PIPE)\n        stdout,stderr = p.communicate()\n        return stdout",
    "docstring": "Executes the specified command on the remote host.\n\n        The cmd must be format safe, this means { and } must be doubled, thusly:\n\n          echo /var/local/maildir/{{cur,new}}\n\n        the cmd can include the format word 'maildir' to be replaced\n        by self.directory. eg:\n\n          echo {maildir}/{{cur,new}}"
  },
  {
    "code": "def put_pipeline_definition(pipeline_id, pipeline_objects, parameter_objects=None,\n                            parameter_values=None, region=None, key=None, keyid=None, profile=None):\n    parameter_objects = parameter_objects or []\n    parameter_values = parameter_values or []\n    client = _get_client(region, key, keyid, profile)\n    r = {}\n    try:\n        response = client.put_pipeline_definition(\n            pipelineId=pipeline_id,\n            pipelineObjects=pipeline_objects,\n            parameterObjects=parameter_objects,\n            parameterValues=parameter_values,\n        )\n        if response['errored']:\n            r['error'] = response['validationErrors']\n        else:\n            r['result'] = response\n    except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:\n        r['error'] = six.text_type(e)\n    return r",
    "docstring": "Add tasks, schedules, and preconditions to the specified pipeline. This function is\n    idempotent and will replace an existing definition.\n\n    CLI example:\n\n    .. code-block:: bash\n\n        salt myminion boto_datapipeline.put_pipeline_definition my_pipeline_id my_pipeline_objects"
  },
  {
    "code": "def add_query_params(url, params):\n    def encode(s):\n        return force_bytes(s, settings.DEFAULT_CHARSET)\n    params = dict([(encode(k), encode(v)) for k, v in params.items() if v])\n    parts = list(urlparse(url))\n    query = dict(parse_qsl(parts[4]))\n    query.update(params)\n    parts[4] = urlencode(query)\n    return urlunparse(parts)",
    "docstring": "Inject additional query parameters into an existing URL. If\n    parameters already exist with the same name, they will be\n    overwritten. Parameters with empty values are ignored. Return\n    the modified URL as a string."
  },
  {
    "code": "def request(uri, method, data, token=''):\n    socket.setdefaulttimeout(__timeout__)\n    obj = urllib.build_opener(urllib.HTTPHandler)\n    encoded = json.JSONEncoder(object).encode(data)\n    data_utf8 = encoded.encode('utf-8')\n    req = urllib.Request(uri, data=data_utf8)\n    if encoded:\n        req.add_header('Content-Type', 'application/json')\n    if token:\n        req.add_header('x-authentication-token', token)\n    req.get_method = lambda: method\n    try:\n        res = obj.open(req)\n        return res\n    except urllib.URLError as e:\n        sys.stderr.write(\"ERROR: %s\\n\" % e)\n        exit(1)\n    except urllib.HTTPError as e:\n        sys.stderr.write(\"ERROR: %s\\n\" % e)\n        exit(1)",
    "docstring": "Request to TonicDNS API.\n\n    Arguments:\n\n        uri:     TonicDNS API URI\n        method:  TonicDNS API request method\n        data:    Post data to TonicDNS API\n        token:   TonicDNS API authentication token"
  },
  {
    "code": "def stem_leaf_plot(data, vmin, vmax, bins, digit=1, title=None):\n    assert bins > 0\n    range = vmax - vmin\n    step = range * 1. / bins\n    if isinstance(range, int):\n        step = int(ceil(step))\n    step = step or 1\n    bins = np.arange(vmin, vmax + step, step)\n    hist, bin_edges = np.histogram(data, bins=bins)\n    bin_edges = bin_edges[:len(hist)]\n    asciiplot(bin_edges, hist, digit=digit, title=title)\n    print(\"Last bin ends in {0}, inclusive.\".format(vmax), file=sys.stderr)\n    return bin_edges, hist",
    "docstring": "Generate stem and leaf plot given a collection of numbers"
  },
  {
    "code": "def requiredGPU_MB(self, n):\n        from darknet.core import darknet_with_cuda\n        if (darknet_with_cuda()):\n            free = getFreeGPU_MB()\n            print(\"Yolo: requiredGPU_MB: required, free\", n, free)\n            if (free == -1):\n                return True\n            return (free>=n)\n        else:\n            return True",
    "docstring": "Required GPU memory in MBytes"
  },
  {
    "code": "def snippets(self):\n        return [strip_suffix(f, '.yaml') for f in self._stripped_files if self._snippets_pattern.match(f)]",
    "docstring": "Get all snippets in this DAP"
  },
  {
    "code": "def covariance(self):\n        mu = self.moments_central\n        if mu[0, 0] != 0:\n            m = mu / mu[0, 0]\n            covariance = self._check_covariance(\n                np.array([[m[0, 2], m[1, 1]], [m[1, 1], m[2, 0]]]))\n            return covariance * u.pix**2\n        else:\n            return np.empty((2, 2)) * np.nan * u.pix**2",
    "docstring": "The covariance matrix of the 2D Gaussian function that has the\n        same second-order moments as the source."
  },
  {
    "code": "def _init_sub_dsp(self, dsp, fringe, outputs, no_call, initial_dist, index,\n                      full_name):\n        sol = self.__class__(\n            dsp, {}, outputs, False, None, None, no_call, False,\n            wait_in=self._wait_in.get(dsp, None), index=self.index + index,\n            full_name=full_name\n        )\n        sol.sub_sol = self.sub_sol\n        for f in sol.fringe:\n            item = (initial_dist + f[0], (2,) + f[1][1:], f[-1])\n            heapq.heappush(fringe, item)\n        return sol",
    "docstring": "Initialize the dispatcher as sub-dispatcher and update the fringe.\n\n        :param fringe:\n            Heapq of closest available nodes.\n        :type fringe: list[(float | int, bool, (str, Dispatcher)]\n\n        :param outputs:\n            Ending data nodes.\n        :type outputs: list[str], iterable\n\n        :param no_call:\n            If True data node estimation function is not used.\n        :type no_call: bool"
  },
  {
    "code": "def node_from_nid(self, nid):\n        for node in self.iflat_nodes():\n            if node.node_id == nid: return node\n        raise ValueError(\"Cannot find node with node id: %s\" % nid)",
    "docstring": "Return the node in the `Flow` with the given `nid` identifier"
  },
  {
    "code": "def showLicense():\n    print(\"Trying to recover the contents of the license...\\n\")\n    try:\n        text = urllib.urlopen(LICENSE_URL).read()\n        print(\"License retrieved from \" + emphasis(LICENSE_URL) + \".\")\n        raw_input(\"\\n\\tPress \" + emphasis(\"<ENTER>\") + \" to print it.\\n\")\n        print(text)\n    except:\n        print(warning(\"The license could not be downloaded and printed.\"))",
    "docstring": "Method that prints the license if requested.\n\n    It tries to find the license online and manually download it. This method\n    only prints its contents in plain text."
  },
  {
    "code": "def _get_user_agent(self):\n        user_agent = request.headers.get('User-Agent')\n        if user_agent:\n            user_agent = user_agent.encode('utf-8')\n        return user_agent or ''",
    "docstring": "Retrieve the request's User-Agent, if available.\n\n        Taken from Flask Login utils.py."
  },
  {
    "code": "def add_errors(self, *errors: Union[BaseSchemaError, SchemaErrorCollection]) -> None:\n        for error in errors:\n            self._error_cache.add(error)",
    "docstring": "Adds errors to the error store for the schema"
  },
  {
    "code": "def get_forum(self):\n        pk = self.kwargs.get(self.forum_pk_url_kwarg, None)\n        if not pk:\n            return\n        if not hasattr(self, '_forum'):\n            self._forum = get_object_or_404(Forum, pk=pk)\n        return self._forum",
    "docstring": "Returns the considered forum."
  },
  {
    "code": "def _compute_inter_event_std(self, C, C_PGA, pga1100, mag, vs30):\n        tau_0 = self._compute_std_0(C['s3'], C['s4'], mag)\n        tau_b_pga = self._compute_std_0(C_PGA['s3'], C_PGA['s4'], mag)\n        delta_amp = self._compute_partial_derivative_site_amp(C, pga1100, vs30)\n        std_inter = np.sqrt(tau_0 ** 2 + (delta_amp ** 2) * (tau_b_pga ** 2) +\n                            2 * delta_amp * tau_0 * tau_b_pga * C['rho'])\n        return std_inter",
    "docstring": "Compute inter event standard deviation, equation 25, page 82."
  },
  {
    "code": "def init_backends():\n    global _BACKENDS, _ACTIVE_BACKENDS\n    try:\n        from .cffi_backend import CFFIBackend\n    except ImportError:\n        pass\n    else:\n        _BACKENDS.append(CFFIBackend)\n    from .ctypes_backend import CTypesBackend\n    from .null_backend import NullBackend\n    _BACKENDS.append(CTypesBackend)\n    _ACTIVE_BACKENDS = _BACKENDS[:]\n    _BACKENDS.append(NullBackend)",
    "docstring": "Loads all backends"
  },
  {
    "code": "def babel_extract(config, input, output, target, keywords):\n    click.echo(\n        click.style(\n            \"Starting Extractions config:{0} input:{1} output:{2} keywords:{3}\".format(\n                config, input, output, keywords\n            ),\n            fg=\"green\",\n        )\n    )\n    keywords = \" -k \".join(keywords)\n    os.popen(\n        \"pybabel extract -F {0} -k {1} -o {2} {3}\".format(\n            config, keywords, output, input\n        )\n    )\n    click.echo(click.style(\"Starting Update target:{0}\".format(target), fg=\"green\"))\n    os.popen(\"pybabel update -N -i {0} -d {1}\".format(output, target))\n    click.echo(click.style(\"Finish, you can start your translations\", fg=\"green\"))",
    "docstring": "Babel, Extracts and updates all messages marked for translation"
  },
  {
    "code": "def _restore_counts_maps(self):\n        for c in self.components:\n            c.restore_counts_maps()\n        if hasattr(self.like.components[0].logLike, 'setCountsMap'):\n            self._init_roi_model()\n        else:\n            self.write_xml('tmp')\n            self._like = SummedLikelihood()\n            for i, c in enumerate(self._components):\n                c._create_binned_analysis()\n                self._like.addComponent(c.like)\n            self._init_roi_model()\n            self.load_xml('tmp')",
    "docstring": "Revert counts maps to their state prior to injecting any simulated\n        components."
  },
  {
    "code": "def getConfig(self):\n        config = {}\n        config[\"name\"] = self.city\n        config[\"intervals\"] = self.__intervals\n        config[\"last_date\"] = self.__lastDay\n        config[\"excludedUsers\"] = []\n        config[\"excludedLocations\"] = []\n        for e in self.__excludedUsers:\n            config[\"excludedUsers\"].append(e)\n        for e in self.__excludedLocations:\n            config[\"excludedLocations\"].append(e)\n        config[\"locations\"] = self.__locations\n        return config",
    "docstring": "Return the configuration of the city.\n\n        :return: configuration of the city.\n        :rtype: dict."
  },
  {
    "code": "def compute_texptime(imageObjectList):\n    expnames = []\n    exptimes = []\n    start = []\n    end = []\n    for img in imageObjectList:\n        expnames += img.getKeywordList('_expname')\n        exptimes += img.getKeywordList('_exptime')\n        start += img.getKeywordList('_expstart')\n        end += img.getKeywordList('_expend')\n    exptime = 0.\n    expstart = min(start)\n    expend = max(end)\n    exposure = None\n    for n in range(len(expnames)):\n        if expnames[n] != exposure:\n            exposure = expnames[n]\n            exptime += exptimes[n]\n    return (exptime,expstart,expend)",
    "docstring": "Add up the exposure time for all the members in\n    the pattern, since 'drizzle' doesn't have the necessary\n    information to correctly set this itself."
  },
  {
    "code": "def _readintle(self, length, start):\n        ui = self._readuintle(length, start)\n        if not ui >> (length - 1):\n            return ui\n        tmp = (~(ui - 1)) & ((1 << length) - 1)\n        return -tmp",
    "docstring": "Read bits and interpret as a little-endian signed int."
  },
  {
    "code": "def load_robots_txt(self, url_info: URLInfo, text: str):\n        key = self.url_info_key(url_info)\n        parser = robotexclusionrulesparser.RobotExclusionRulesParser()\n        parser.parse(text)\n        self._parsers[key] = parser",
    "docstring": "Load the robot.txt file."
  },
  {
    "code": "def _list(self, foldername=\"INBOX\", reverse=False, since=None):\n        folder = self.folder \\\n            if foldername == \"INBOX\" \\\n            else self._getfolder(foldername)\n        def sortcmp(d):\n            try:\n                return d[1].date\n            except:\n                return -1\n        lst = folder.items() if not since else folder.items_since(since)\n        sorted_lst = sorted(lst, key=sortcmp, reverse=1 if reverse else 0)\n        itemlist = [(folder, key, msg) for key,msg in sorted_lst]\n        return itemlist",
    "docstring": "Do structured list output.\n\n        Sorts the list by date, possibly reversed, filtered from 'since'.\n\n        The returned list is: foldername, message key, message object"
  },
  {
    "code": "def edge_val_set(self, graph, orig, dest, idx, key, branch, turn, tick, value):\n        if (branch, turn, tick) in self._btts:\n            raise TimeError\n        self._btts.add((branch, turn, tick))\n        graph, orig, dest, key, value = map(self.pack, (graph, orig, dest, key, value))\n        self._edgevals2set.append(\n            (graph, orig, dest, idx, key, branch, turn, tick, value)\n        )",
    "docstring": "Set this key of this edge to this value."
  },
  {
    "code": "def _render(template, callable_, args, data, as_unicode=False):\n    if as_unicode:\n        buf = util.FastEncodingBuffer(as_unicode=True)\n    elif template.bytestring_passthrough:\n        buf = compat.StringIO()\n    else:\n        buf = util.FastEncodingBuffer(\n                        as_unicode=as_unicode,\n                        encoding=template.output_encoding,\n                        errors=template.encoding_errors)\n    context = Context(buf, **data)\n    context._outputting_as_unicode = as_unicode\n    context._set_with_template(template)\n    _render_context(template, callable_, context, *args,\n                            **_kwargs_for_callable(callable_, data))\n    return context._pop_buffer().getvalue()",
    "docstring": "create a Context and return the string\n    output of the given template and template callable."
  },
  {
    "code": "def children(self, vertex):\n        return [self.head(edge) for edge in self.out_edges(vertex)]",
    "docstring": "Return the list of immediate children of the given vertex."
  },
  {
    "code": "def help_cli_search(self):\n        help =  '%sSearch: %s returns sample_sets, a sample_set is a set/list of md5s.' % (color.Yellow, color.Green)\n        help += '\\n\\n\\t%sSearch for all samples in the database that are known bad pe files,'  % (color.Green)\n        help += '\\n\\t%sthis command returns the sample_set containing the matching items'% (color.Green)\n        help += '\\n\\t%s> my_bad_exes = search([\\'bad\\', \\'exe\\'])' % (color.LightBlue)\n        help += '\\n\\n\\t%sRun workers on this sample_set:'  % (color.Green)\n        help += '\\n\\t%s> pe_outputs = pe_features(my_bad_exes) %s' % (color.LightBlue, color.Normal)\n        help += '\\n\\n\\t%sLoop on the generator (or make a DataFrame see >help dataframe)'  % (color.Green)\n        help += '\\n\\t%s> for output in pe_outputs: %s' % (color.LightBlue, color.Normal)\n        help += '\\n\\t\\t%s print output %s' % (color.LightBlue, color.Normal)\n        return help",
    "docstring": "Help for Workbench CLI Search"
  },
  {
    "code": "def serialize_for_transport(obj_pyxb, pretty=False, strip_prolog=False, xslt_url=None):\n    return serialize_gen(obj_pyxb, 'utf-8', pretty, strip_prolog, xslt_url)",
    "docstring": "Serialize PyXB object to XML ``bytes`` with UTF-8 encoding for transport over the\n    network, filesystem storage and other machine usage.\n\n    Args:\n      obj_pyxb: PyXB object\n        PyXB object to serialize.\n\n      pretty: bool\n        True: Use pretty print formatting for human readability.\n\n      strip_prolog:\n        True: remove any XML prolog (e.g., ``<?xml version=\"1.0\" encoding=\"utf-8\"?>``),\n        from the resulting XML doc.\n\n      xslt_url: str\n        If specified, add a processing instruction to the XML doc that specifies the\n        download location for an XSLT stylesheet.\n\n    Returns:\n      bytes: UTF-8 encoded XML document\n\n    See Also:\n      ``serialize_for_display()``"
  },
  {
    "code": "def rounder(input_number, digit=5):\n    if isinstance(input_number, tuple):\n        tuple_list = list(input_number)\n        tuple_str = []\n        for i in tuple_list:\n            if isfloat(i):\n                tuple_str.append(str(numpy.around(i, digit)))\n            else:\n                tuple_str.append(str(i))\n        return \"(\" + \",\".join(tuple_str) + \")\"\n    if isfloat(input_number):\n        return str(numpy.around(input_number, digit))\n    return str(input_number)",
    "docstring": "Round input number and convert to str.\n\n    :param input_number: input number\n    :type input_number : anything\n    :param digit: scale (the number of digits to the right of the decimal point in a number.)\n    :type digit : int\n    :return: round number as str"
  },
  {
    "code": "def all_sharded_cluster_links(cluster_id, shard_id=None,\n                              router_id=None, rel_to=None):\n    return [\n        sharded_cluster_link(rel, cluster_id, shard_id, router_id,\n                             self_rel=(rel == rel_to))\n        for rel in (\n            'get-sharded-clusters', 'get-sharded-cluster-info',\n            'sharded-cluster-command', 'delete-sharded-cluster',\n            'add-shard', 'get-shards', 'get-configsvrs',\n            'get-routers', 'add-router'\n        )\n    ]",
    "docstring": "Get a list of all links to be included with ShardedClusters."
  },
  {
    "code": "def AllTypes():\n        return [AssetType.CreditFlag, AssetType.DutyFlag, AssetType.GoverningToken,\n                AssetType.UtilityToken, AssetType.Currency, AssetType.Share,\n                AssetType.Invoice, AssetType.Token]",
    "docstring": "Get a list of all available asset types.\n\n        Returns:\n            list: of AssetType items."
  },
  {
    "code": "def choose_form(self, number=None, xpath=None, name=None, **kwargs):\n        id_ = kwargs.pop('id', None)\n        if id_ is not None:\n            try:\n                self._lxml_form = self.select('//form[@id=\"%s\"]' % id_).node()\n            except IndexError:\n                raise DataNotFound(\"There is no form with id: %s\" % id_)\n        elif name is not None:\n            try:\n                self._lxml_form = self.select(\n                    '//form[@name=\"%s\"]' % name).node()\n            except IndexError:\n                raise DataNotFound('There is no form with name: %s' % name)\n        elif number is not None:\n            try:\n                self._lxml_form = self.tree.forms[number]\n            except IndexError:\n                raise DataNotFound('There is no form with number: %s' % number)\n        elif xpath is not None:\n            try:\n                self._lxml_form = self.select(xpath).node()\n            except IndexError:\n                raise DataNotFound(\n                    'Could not find form with xpath: %s' % xpath)\n        else:\n            raise GrabMisuseError('choose_form methods requires one of '\n                                  '[number, id, name, xpath] arguments')",
    "docstring": "Set the default form.\n\n        :param number: number of form (starting from zero)\n        :param id: value of \"id\" attribute\n        :param name: value of \"name\" attribute\n        :param xpath: XPath query\n        :raises: :class:`DataNotFound` if form not found\n        :raises: :class:`GrabMisuseError`\n            if method is called without parameters\n\n        Selected form will be available via `form` attribute of `Grab`\n        instance. All form methods will work with default form.\n\n        Examples::\n\n            # Select second form\n            g.choose_form(1)\n\n            # Select by id\n            g.choose_form(id=\"register\")\n\n            # Select by name\n            g.choose_form(name=\"signup\")\n\n            # Select by xpath\n            g.choose_form(xpath='//form[contains(@action, \"/submit\")]')"
  },
  {
    "code": "def _init_deferred_buffers(self):\n        self._transfer_list = collections.deque()\n        self._crnt_cmd = _Command(self._packet_size)\n        self._commands_to_read = collections.deque()\n        self._command_response_buf = bytearray()",
    "docstring": "Initialize or reinitalize all the deferred transfer buffers\n\n        Calling this method will drop all pending transactions\n        so use with care."
  },
  {
    "code": "def validate(self, value):\n        if isinstance(value, (str, unicode)) and not re.match(self.__pattern, value):\n            raise orb.errors.ColumnValidationError(self, 'The email provided is not valid.')\n        else:\n            return super(EmailColumn, self).validate(value)",
    "docstring": "Validates the value provided is a valid email address,\n        at least, on paper.\n\n        :param value: <str>\n\n        :return: <bool>"
  },
  {
    "code": "def publish(self, topic, message=None, qos=0, retain=False):\n        logger.info('Publish topic: %s, message: %s, qos: %s, retain: %s'\n            % (topic, message, qos, retain))\n        self._mid = -1\n        self._mqttc.on_publish = self._on_publish\n        result, mid = self._mqttc.publish(topic, message, int(qos), retain)\n        if result != 0:\n            raise RuntimeError('Error publishing: %s' % result)\n        timer_start = time.time()\n        while time.time() < timer_start + self._loop_timeout:\n            if mid == self._mid:\n                break;\n            self._mqttc.loop()\n        if mid != self._mid:\n            logger.warn('mid wasn\\'t matched: %s' % mid)",
    "docstring": "Publish a message to a topic with specified qos and retained flag.\n        It is required that a connection has been established using `Connect`\n        keyword before using this keyword.\n\n        `topic` topic to which the message will be published\n\n        `message` message payload to publish\n\n        `qos` qos of the message\n\n        `retain` retained flag\n\n        Examples:\n\n        | Publish | test/test | test message | 1 | ${false} |"
  },
  {
    "code": "def iterate(self, train=None, valid=None, max_updates=None, **kwargs):\n        r\n        self._compile(**kwargs)\n        if valid is None:\n            valid = train\n        iteration = 0\n        training = validation = None\n        while max_updates is None or iteration < max_updates:\n            if not iteration % self.validate_every:\n                try:\n                    validation = self.evaluate(valid)\n                except KeyboardInterrupt:\n                    util.log('interrupted!')\n                    break\n                if self._test_patience(validation):\n                    util.log('patience elapsed!')\n                    break\n            try:\n                training = self._step(train)\n            except KeyboardInterrupt:\n                util.log('interrupted!')\n                break\n            iteration += 1\n            self._log(training, iteration)\n            yield training, validation\n        self.set_params('best')",
    "docstring": "r'''Optimize a loss iteratively using a training and validation dataset.\n\n        This method yields a series of monitor values to the caller. After every\n        optimization epoch, a pair of monitor dictionaries is generated: one\n        evaluated on the training dataset during the epoch, and another\n        evaluated on the validation dataset at the most recent validation epoch.\n\n        The validation monitors might not be updated during every optimization\n        iteration; in this case, the most recent validation monitors will be\n        yielded along with the training monitors.\n\n        Additional keyword arguments supplied here will set the global\n        optimizer attributes.\n\n        Parameters\n        ----------\n        train : sequence or :class:`Dataset <downhill.dataset.Dataset>`\n            A set of training data for computing updates to model parameters.\n        valid : sequence or :class:`Dataset <downhill.dataset.Dataset>`\n            A set of validation data for computing monitor values and\n            determining when the loss has stopped improving. Defaults to the\n            training data.\n        max_updates : int, optional\n            If specified, halt optimization after this many gradient updates\n            have been processed. If not provided, uses early stopping to decide\n            when to halt.\n\n        Yields\n        ------\n        train_monitors : dict\n            A dictionary mapping monitor names to values, evaluated on the\n            training dataset.\n        valid_monitors : dict\n            A dictionary containing monitor values evaluated on the validation\n            dataset."
  },
  {
    "code": "def _fill_untouched(idx, ret, fill_value):\n    untouched = np.ones_like(ret, dtype=bool)\n    untouched[idx] = False\n    ret[untouched] = fill_value",
    "docstring": "any elements of ret not indexed by idx are set to fill_value."
  },
  {
    "code": "def GetAnalyzersInformation(cls):\n    analyzer_information = []\n    for _, analyzer_class in cls.GetAnalyzers():\n      description = getattr(analyzer_class, 'DESCRIPTION', '')\n      analyzer_information.append((analyzer_class.NAME, description))\n    return analyzer_information",
    "docstring": "Retrieves the analyzers information.\n\n    Returns:\n      list[tuple]: containing:\n\n        str: analyzer name.\n        str: analyzer description."
  },
  {
    "code": "def _handle_tag_definetext2(self):\n        obj = _make_object(\"DefineText2\")\n        self._generic_definetext_parser(obj, self._get_struct_rgba)\n        return obj",
    "docstring": "Handle the DefineText2 tag."
  },
  {
    "code": "def _update_length(self):\n        action_length = 4 + len(self.field.pack())\n        overflow = action_length % 8\n        self.length = action_length\n        if overflow:\n            self.length = action_length + 8 - overflow",
    "docstring": "Update the length field of the struct."
  },
  {
    "code": "def parse_properties(node):\n    d = dict()\n    for child in node.findall('properties'):\n        for subnode in child.findall('property'):\n            cls = None\n            try:\n                if \"type\" in subnode.keys():\n                    module = importlib.import_module('builtins')\n                    cls = getattr(module, subnode.get(\"type\"))\n            except AttributeError:\n                logger.info(\"Type [} Not a built-in type. Defaulting to string-cast.\")\n            d[subnode.get('name')] = cls(subnode.get('value')) if cls is not None else subnode.get('value')\n    return d",
    "docstring": "Parse a Tiled xml node and return a dict that represents a tiled \"property\"\n\n    :param node: etree element\n    :return: dict"
  },
  {
    "code": "def imports():\n    from .core.import_hooks import ExtensionImporter\n    importer = ExtensionImporter()\n    sys.meta_path.append(importer)\n    yield\n    sys.meta_path.remove(importer)",
    "docstring": "Install the import hook to load python extensions from app's lib folder\n        during the context of this block.\n\n        This method is preferred as it's faster than using install."
  },
  {
    "code": "def sync_objects_in(self):\n        self.dstate = self.STATES.BUILDING\n        self.build_source_files.record_to_objects()",
    "docstring": "Synchronize from records to objects"
  },
  {
    "code": "def serve(application, host='127.0.0.1', port=8080):\n\tWSGIServer((host, int(port)), application).serve_forever()",
    "docstring": "Gevent-based WSGI-HTTP server."
  },
  {
    "code": "def subtype(self, **kwargs):\n        initializers = self.readOnly.copy()\n        cloneValueFlag = kwargs.pop('cloneValueFlag', False)\n        implicitTag = kwargs.pop('implicitTag', None)\n        if implicitTag is not None:\n            initializers['tagSet'] = self.tagSet.tagImplicitly(implicitTag)\n        explicitTag = kwargs.pop('explicitTag', None)\n        if explicitTag is not None:\n            initializers['tagSet'] = self.tagSet.tagExplicitly(explicitTag)\n        for arg, option in kwargs.items():\n            initializers[arg] += option\n        clone = self.__class__(**initializers)\n        if cloneValueFlag:\n            self._cloneComponentValues(clone, cloneValueFlag)\n        return clone",
    "docstring": "Create a specialization of |ASN.1| schema object.\n\n        The `subtype()` method accepts the same set arguments as |ASN.1|\n        class takes on instantiation except that all parameters\n        of the `subtype()` method are optional.\n\n        With the exception of the arguments described below, the rest of\n        supplied arguments they are used to create a copy of `self` taking\n        precedence over the ones used to instantiate `self`.\n\n        The following arguments to `subtype()` create a ASN.1 subtype out of\n        |ASN.1| type.\n\n        Other Parameters\n        ----------------\n        implicitTag: :py:class:`~pyasn1.type.tag.Tag`\n            Implicitly apply given ASN.1 tag object to `self`'s\n            :py:class:`~pyasn1.type.tag.TagSet`, then use the result as\n            new object's ASN.1 tag(s).\n\n        explicitTag: :py:class:`~pyasn1.type.tag.Tag`\n            Explicitly apply given ASN.1 tag object to `self`'s\n            :py:class:`~pyasn1.type.tag.TagSet`, then use the result as\n            new object's ASN.1 tag(s).\n\n        subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`\n            Add ASN.1 constraints object to one of the `self`'s, then\n            use the result as new object's ASN.1 constraints.\n\n\n        Returns\n        -------\n        :\n            new instance of |ASN.1| type/value\n\n        Note\n        ----\n        Due to the immutable nature of the |ASN.1| object, if no arguments\n        are supplied, no new |ASN.1| object will be created and `self` will\n        be returned instead."
  },
  {
    "code": "def write_configs(self):\n        utils.banner(\"Generating Configs\")\n        if not self.runway_dir:\n            app_configs = configs.process_git_configs(git_short=self.git_short)\n        else:\n            app_configs = configs.process_runway_configs(runway_dir=self.runway_dir)\n        self.configs = configs.write_variables(\n            app_configs=app_configs, out_file=self.raw_path, git_short=self.git_short)",
    "docstring": "Generate the configurations needed for pipes."
  },
  {
    "code": "def pesn(number, separator=u''):\n    number = re.sub(r'[\\s-]', '', meid(number))\n    serial = hashlib.sha1(unhexlify(number[:14]))\n    return separator.join(['80', serial.hexdigest()[-6:].upper()])",
    "docstring": "Printable Pseudo Electronic Serial Number.\n\n    :param number: hexadecimal string\n\n    >>> print(pesn('1B69B4BA630F34E'))\n    805F9EF7"
  },
  {
    "code": "def post_url(self, url, form):\n        _r = self.br.open(url, form.click_request_data()[1])\n        if self.br.geturl().startswith(self.AUTH_URL):\n            raise AuthRequiredException\n        elif self.br.geturl().startswith(self.ERROR_URL):\n            raise RequestErrorException\n        else:\n            return _r.read()",
    "docstring": "Internally used to retrieve the contents of a URL using\n        the POST request method.\n        The `form` parameter is a mechanize.HTMLForm object\n        This method will use a POST request type regardless of the method\n        used in the `form`."
  },
  {
    "code": "def set_register(self, register, value):\n        context = self.get_context()\n        context[register] = value\n        self.set_context(context)",
    "docstring": "Sets the value of a specific register.\n\n        @type  register: str\n        @param register: Register name.\n\n        @rtype:  int\n        @return: Register value."
  },
  {
    "code": "def validate_custom_interpreters_list(self):\r\n        custom_list = self.get_option('custom_interpreters_list')\r\n        valid_custom_list = []\r\n        for value in custom_list:\r\n            if (osp.isfile(value) and programs.is_python_interpreter(value)\r\n                    and value != get_python_executable()):\r\n                valid_custom_list.append(value)\r\n        self.set_option('custom_interpreters_list', valid_custom_list)",
    "docstring": "Check that the used custom interpreters are still valid."
  },
  {
    "code": "def validate_version(self, service_id, version_number):\n\t\tcontent = self._fetch(\"/service/%s/version/%d/validate\" % (service_id, version_number))\n\t\treturn self._status(content)",
    "docstring": "Validate the version for a particular service and version."
  },
  {
    "code": "def meta_manager_view(request):\n    managers = Manager.objects.all()\n    return render_to_response('meta_manager.html', {\n        'page_name': \"Admin - Meta-Manager\",\n        'managerset': managers,\n        }, context_instance=RequestContext(request))",
    "docstring": "A manager of managers.  Display a list of current managers, with links to modify them.\n    Also display a link to add a new manager.  Restricted to presidents and superadmins."
  },
  {
    "code": "def percent_of_the_time(p):\n    def decorator(fn):\n        def wrapped(*args, **kwargs):\n            if in_percentage(p):\n                fn(*args, **kwargs)\n        return wrapped\n    return decorator",
    "docstring": "Function has a X percentage chance of running"
  },
  {
    "code": "async def cancel(self, task: asyncio.Task, wait_for: bool = True) -> Any:\n        if task is None:\n            return\n        task.cancel()\n        with suppress(KeyError):\n            self._tasks.remove(task)\n        with suppress(Exception):\n            return (await task) if wait_for else None",
    "docstring": "Cancels and waits for an `asyncio.Task` to finish.\n        Removes it from the collection of managed tasks.\n\n        Args:\n            task (asyncio.Task):\n                The to be cancelled task.\n                It is not required that the task was was created with `TaskScheduler.create_task()`.\n\n            wait_for (bool, optional):\n                Whether to wait for the task to finish execution.\n                If falsey, this function returns immediately after cancelling the task.\n\n        Returns:\n            Any: The return value of `task`. None if `wait_for` is falsey."
  },
  {
    "code": "def used_by(self, bundle):\n        if bundle is None or bundle is self.__bundle:\n            return\n        with self.__usage_lock:\n            self.__using_bundles.setdefault(bundle, _UsageCounter()).inc()",
    "docstring": "Indicates that this reference is being used by the given bundle.\n        This method should only be used by the framework.\n\n        :param bundle: A bundle using this reference"
  },
  {
    "code": "def limit_spec(self, spec):\n        if list(spec.keys()) == ['name']:\n            return ((Q(name=spec['name']) | Q(other_names__name=spec['name'])) &\n                    Q(memberships__organization__jurisdiction_id=self.jurisdiction_id))\n        spec['memberships__organization__jurisdiction_id'] = self.jurisdiction_id\n        return spec",
    "docstring": "Whenever we do a Pseudo ID lookup from the database, we need to limit\n        based on the memberships -> organization -> jurisdiction, so we scope\n        the resolution."
  },
  {
    "code": "def node_slider(self, seed=None):\n        prop = 0.999\n        assert isinstance(prop, float), \"prop must be a float\"\n        assert prop < 1, \"prop must be a proportion >0 and < 1.\"\n        random.seed(seed)\n        ctree = self._ttree.copy()\n        for node in ctree.treenode.traverse():\n            if node.up and node.children:\n                minjit = max([i.dist for i in node.children]) * prop\n                maxjit = (node.up.height * prop) - node.height\n                newheight = random.uniform(-minjit, maxjit)\n                for child in node.children:\n                    child.dist += newheight\n                node.dist -= newheight\n        ctree._coords.update()\n        return ctree",
    "docstring": "Returns a toytree copy with node heights modified while retaining \n        the same topology but not necessarily node branching order. \n        Node heights are moved up or down uniformly between their parent \n        and highest child node heights in 'levelorder' from root to tips.\n        The total tree height is retained at 1.0, only relative edge\n        lengths change."
  },
  {
    "code": "def get_file(self, file, **kwargs):\n        file_id = obj_or_id(file, \"file\", (File,))\n        response = self.__requester.request(\n            'GET',\n            'files/{}'.format(file_id),\n            _kwargs=combine_kwargs(**kwargs)\n        )\n        return File(self.__requester, response.json())",
    "docstring": "Return the standard attachment json object for a file.\n\n        :calls: `GET /api/v1/files/:id \\\n        <https://canvas.instructure.com/doc/api/files.html#method.files.api_show>`_\n\n        :param file: The object or ID of the file to retrieve.\n        :type file: :class:`canvasapi.file.File` or int\n\n        :rtype: :class:`canvasapi.file.File`"
  },
  {
    "code": "def _analyse(self, table=''):\n        self._logger.info('Starting analysis of database')\n        self._conn.execute(constants.ANALYSE_SQL.format(table))\n        self._logger.info('Analysis of database complete')",
    "docstring": "Analyses the database, or `table` if it is supplied.\n\n        :param table: optional name of table to analyse\n        :type table: `str`"
  },
  {
    "code": "def dms_to_decimal(degrees, minutes, seconds, hemisphere):\n    dms = float(degrees) + float(minutes) / 60 + float(seconds) / 3600\n    if hemisphere in \"WwSs\":\n        dms = -1 * dms\n    return dms",
    "docstring": "Convert from degrees, minutes, seconds to decimal degrees.\n    @author: mprins"
  },
  {
    "code": "def endswith(self, suffix):\n        return ArrayPredicate(\n            term=self,\n            op=LabelArray.endswith,\n            opargs=(suffix,),\n        )",
    "docstring": "Construct a Filter matching values ending with ``suffix``.\n\n        Parameters\n        ----------\n        suffix : str\n            String suffix against which to compare values produced by ``self``.\n\n        Returns\n        -------\n        matches : Filter\n            Filter returning True for all sid/date pairs for which ``self``\n            produces a string ending with ``prefix``."
  },
  {
    "code": "def mxvg(m1, v2, nrow1, nc1r2):\n    m1 = stypes.toDoubleMatrix(m1)\n    v2 = stypes.toDoubleVector(v2)\n    nrow1 = ctypes.c_int(nrow1)\n    nc1r2 = ctypes.c_int(nc1r2)\n    vout = stypes.emptyDoubleVector(nrow1.value)\n    libspice.mxvg_c(m1, v2, nrow1, nc1r2, vout)\n    return stypes.cVectorToPython(vout)",
    "docstring": "Multiply a matrix and a vector of arbitrary size.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxvg_c.html\n\n    :param m1: Left-hand matrix to be multiplied.\n    :type m1: NxM-Element Array of floats\n    :param v2: Right-hand vector to be multiplied.\n    :type v2: Array of floats\n    :param nrow1: Row dimension of m1 and length of vout.\n    :type nrow1: int\n    :param nc1r2: Column dimension of m1 and length of v2.\n    :type nc1r2: int\n    :return: Product vector m1*v2\n    :rtype: Array of floats"
  },
  {
    "code": "def configure_logger(self, name, config, incremental=False):\n        logger = logging.getLogger(name)\n        self.common_logger_config(logger, config, incremental)\n        propagate = config.get('propagate', None)\n        if propagate is not None:\n            logger.propagate = propagate",
    "docstring": "Configure a non-root logger from a dictionary."
  },
  {
    "code": "def get_assessment_taken_admin_session(self, proxy):\n        if not self.supports_assessment_taken_admin():\n            raise errors.Unimplemented()\n        return sessions.AssessmentTakenAdminSession(proxy=proxy, runtime=self._runtime)",
    "docstring": "Gets the ``OsidSession`` associated with the assessment taken administration service.\n\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.assessment.AssessmentTakenAdminSession) - an\n                ``AssessmentTakenAdminSession``\n        raise:  NullArgument - ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_assessment_taken_admin()`` is\n                ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_assessment_taken_admin()`` is ``true``.*"
  },
  {
    "code": "def locate_file(start_path, file_name):\n    if os.path.isfile(start_path):\n        start_dir_path = os.path.dirname(start_path)\n    elif os.path.isdir(start_path):\n        start_dir_path = start_path\n    else:\n        raise exceptions.FileNotFound(\"invalid path: {}\".format(start_path))\n    file_path = os.path.join(start_dir_path, file_name)\n    if os.path.isfile(file_path):\n        return os.path.abspath(file_path)\n    if os.path.abspath(start_dir_path) in [os.getcwd(), os.path.abspath(os.sep)]:\n        raise exceptions.FileNotFound(\"{} not found in {}\".format(file_name, start_path))\n    return locate_file(os.path.dirname(start_dir_path), file_name)",
    "docstring": "locate filename and return absolute file path.\n        searching will be recursive upward until current working directory.\n\n    Args:\n        start_path (str): start locating path, maybe file path or directory path\n\n    Returns:\n        str: located file path. None if file not found.\n\n    Raises:\n        exceptions.FileNotFound: If failed to locate file."
  },
  {
    "code": "def autocrop(im, bgcolor):\n    \"Crop away a border of the given background color.\"\n    if im.mode != \"RGB\":\n        im = im.convert(\"RGB\")\n    bg = Image.new(\"RGB\", im.size, bgcolor)\n    diff = ImageChops.difference(im, bg)\n    bbox = diff.getbbox()\n    if bbox:\n        return im.crop(bbox)\n    return im",
    "docstring": "Crop away a border of the given background color."
  },
  {
    "code": "def _readline_echo(self, char, echo):\n        if self._readline_do_echo(echo):\n            self.write(char)",
    "docstring": "Echo a recieved character, move cursor etc..."
  },
  {
    "code": "def as_block_string(txt):\n    import json\n    lines = []\n    for line in txt.split('\\n'):\n        line_ = json.dumps(line)\n        line_ = line_[1:-1].rstrip()\n        lines.append(line_)\n    return '' % '\\n'.join(lines)",
    "docstring": "Return a string formatted as a python block comment string, like the one\n    you're currently reading. Special characters are escaped if necessary."
  },
  {
    "code": "def adev(self, tau0, tau):\n        prefactor = self.adev_from_qd(tau0=tau0, tau=tau)\n        c = self.c_avar()\n        avar = pow(prefactor, 2)*pow(tau, c)\n        return np.sqrt(avar)",
    "docstring": "return predicted ADEV of noise-type at given tau"
  },
  {
    "code": "def remove_grad_hooks(module, input):\n    for hook in list(module.param_hooks.keys()):\n        module.param_hooks[hook].remove()\n        module.param_hooks.pop(hook)\n    for hook in list(module.var_hooks.keys()):\n        module.var_hooks[hook].remove()\n        module.var_hooks.pop(hook)",
    "docstring": "Remove gradient hooks to all of the parameters and monitored vars"
  },
  {
    "code": "def subset(self, used_indices, params=None):\n        if params is None:\n            params = self.params\n        ret = Dataset(None, reference=self, feature_name=self.feature_name,\n                      categorical_feature=self.categorical_feature, params=params,\n                      free_raw_data=self.free_raw_data)\n        ret._predictor = self._predictor\n        ret.pandas_categorical = self.pandas_categorical\n        ret.used_indices = used_indices\n        return ret",
    "docstring": "Get subset of current Dataset.\n\n        Parameters\n        ----------\n        used_indices : list of int\n            Indices used to create the subset.\n        params : dict or None, optional (default=None)\n            These parameters will be passed to Dataset constructor.\n\n        Returns\n        -------\n        subset : Dataset\n            Subset of the current Dataset."
  },
  {
    "code": "def has(self, block, name):\n        try:\n            self.get(block, name)\n            return True\n        except KeyError:\n            return False",
    "docstring": "Return whether or not the field named `name` has a non-default value for the XBlock `block`.\n\n        :param block: block to check\n        :type block: :class:`~xblock.core.XBlock`\n        :param name: field name\n        :type name: str"
  },
  {
    "code": "def set_password(url, ownerToken, password):\n    service, fileId, key = sendclient.common.splitkeyurl(url)\n    rawKey = sendclient.common.unpadded_urlsafe_b64decode(key)\n    keys = sendclient.common.secretKeys(rawKey, password, url)\n    return api_password(service, fileId, ownerToken, keys.newAuthKey)",
    "docstring": "set or change the password required to download a file hosted on a send server."
  },
  {
    "code": "def stats_tube(self, tube_name):\n        with self._sock_ctx() as socket:\n            self._send_message('stats-tube {0}'.format(tube_name), socket)\n            body = self._receive_data_with_prefix(b'OK', socket)\n            return yaml_load(body)",
    "docstring": "Fetch statistics about a single tube\n\n        :param tube_name: Tube to fetch stats about\n        :rtype: dict"
  },
  {
    "code": "def rev(self, i):\n        on = copy(self)\n        on.revision = i\n        return on",
    "docstring": "Return a clone with a different revision."
  },
  {
    "code": "def _dump_multilinestring(obj, big_endian, meta):\n    coords = obj['coordinates']\n    vertex = coords[0][0]\n    num_dims = len(vertex)\n    wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder(\n        'MultiLineString', num_dims, big_endian, meta\n    )\n    ls_type = _WKB[_INT_TO_DIM_LABEL.get(num_dims)]['LineString']\n    if big_endian:\n        ls_type = BIG_ENDIAN + ls_type\n    else:\n        ls_type = LITTLE_ENDIAN + ls_type[::-1]\n    wkb_string += struct.pack('%sl' % byte_order, len(coords))\n    for linestring in coords:\n        wkb_string += ls_type\n        wkb_string += struct.pack('%sl' % byte_order, len(linestring))\n        for vertex in linestring:\n            wkb_string += struct.pack(byte_fmt, *vertex)\n    return wkb_string",
    "docstring": "Dump a GeoJSON-like `dict` to a multilinestring WKB string.\n\n    Input parameters and output are similar to :funct:`_dump_point`."
  },
  {
    "code": "def delete_object(self, container, obj, **kwargs):\n        try:\n            LOG.debug('delete_object() with %s is success.', self.driver)\n            return self.driver.delete_object(container, obj, **kwargs)\n        except DriverException as e:\n            LOG.exception('download_object() with %s raised\\\n                            an exception %s.', self.driver, e)",
    "docstring": "Delete object in container\n\n        :param container: container name (Container is equivalent to\n                          Bucket term in Amazon).\n        :param obj: object name (Object is equivalent to\n                    Key term in Amazon)."
  },
  {
    "code": "def validate (self):\n    if not os.path.isfile(self.pathname):\n      self.message.append('Filename \"%s\" does not exist.')\n    else:\n      try:\n        with open(self.pathname, 'r') as stream:\n          pass\n      except IOError:\n        self.messages.append('Could not open \"%s\" for reading.' % self.pathname)\n    for line in self.commands:\n      messages = [ ]\n      if line.cmd and not line.cmd.validate(messages):\n        msg = 'error: %s: %s' % (line.cmd.name, \" \".join(messages))\n        self.log.messages.append(msg)\n    return len(self.log.messages) == 0",
    "docstring": "Returns True if this Sequence is valid, False otherwise.\n    Validation error messages are stored in self.messages."
  },
  {
    "code": "def get_standard_package(self, server_id, is_virt=True):\n        firewall_port_speed = self._get_fwl_port_speed(server_id, is_virt)\n        _value = \"%s%s\" % (firewall_port_speed, \"Mbps Hardware Firewall\")\n        _filter = {'items': {'description': utils.query_filter(_value)}}\n        return self.prod_pkg.getItems(id=0, filter=_filter)",
    "docstring": "Retrieves the standard firewall package for the virtual server.\n\n        :param int server_id: The ID of the server to create the firewall for\n        :param bool is_virt: True if the ID provided is for a virtual server,\n                             False for a server\n        :returns: A dictionary containing the standard virtual server firewall\n                  package"
  },
  {
    "code": "def str_brief(obj, lim=20, dots='...', use_repr=True):\n    if isinstance(obj, basestring) or not use_repr:\n        full = str(obj)\n    else:\n        full = repr(obj)\n    postfix = []\n    CLOSERS = {'(': ')', '{': '}', '[': ']', '\"': '\"', \"'\": \"'\", '<': '>'}\n    for i, c in enumerate(full):\n        if i >= lim + len(postfix):\n            return full[:i] + dots + ''.join(reversed(postfix))\n        if postfix and postfix[-1] == c:\n            postfix.pop(-1)\n            continue\n        closer = CLOSERS.get(c, None)\n        if closer is not None:\n            postfix.append(closer)\n    return full",
    "docstring": "Truncates a string, starting from 'lim' chars. The given object\n    can be a string, or something that can be casted to a string.\n\n    >>> import string\n    >>> str_brief(string.uppercase)\n    'ABCDEFGHIJKLMNOPQRST...'\n    >>> str_brief(2 ** 50, lim=10, dots='0')\n    '11258999060'"
  },
  {
    "code": "def load_csv(filename, dialect='excel', encoding='utf-8'):\n    return Context.fromfile(filename, 'csv', encoding, dialect=dialect)",
    "docstring": "Load and return formal context from CSV file.\n\n    Args:\n        filename: Path to the CSV file to load the context from.\n        dialect: Syntax variant of the CSV file (``'excel'``, ``'excel-tab'``).\n        encoding (str): Encoding of the file (``'utf-8'``, ``'latin1'``, ``'ascii'``, ...).\n\n    Example:\n        >>> load_csv('examples/vowels.csv')  # doctest: +ELLIPSIS\n        <Context object mapping 12 objects to 8 properties [a717eee4] at 0x...>"
  },
  {
    "code": "def RGB_to_HSL(cobj, *args, **kwargs):\n    var_R = cobj.rgb_r\n    var_G = cobj.rgb_g\n    var_B = cobj.rgb_b\n    var_max = max(var_R, var_G, var_B)\n    var_min = min(var_R, var_G, var_B)\n    var_H = __RGB_to_Hue(var_R, var_G, var_B, var_min, var_max)\n    var_L = 0.5 * (var_max + var_min)\n    if var_max == var_min:\n        var_S = 0\n    elif var_L <= 0.5:\n        var_S = (var_max - var_min) / (2.0 * var_L)\n    else:\n        var_S = (var_max - var_min) / (2.0 - (2.0 * var_L))\n    return HSLColor(\n        var_H, var_S, var_L)",
    "docstring": "Converts from RGB to HSL.\n\n    H values are in degrees and are 0 to 360.\n    S values are a percentage, 0.0 to 1.0.\n    L values are a percentage, 0.0 to 1.0."
  },
  {
    "code": "def clean(self, force: bool=False):\n        assert not self._closed\n        with (yield from self._host_pools_lock):\n            for key, pool in tuple(self._host_pools.items()):\n                yield from pool.clean(force=force)\n                if not self._host_pool_waiters[key] and pool.empty():\n                    del self._host_pools[key]\n                    del self._host_pool_waiters[key]",
    "docstring": "Clean all closed connections.\n\n        Args:\n            force: Clean connected and idle connections too.\n\n        Coroutine."
  },
  {
    "code": "async def send_files_preconf(filepaths, config_path=CONFIG_PATH):\n    config = read_config(config_path)\n    subject = \"PDF files from pdfebc\"\n    message = \"\"\n    await send_with_attachments(subject, message, filepaths, config)",
    "docstring": "Send files using the config.ini settings.\n\n    Args:\n        filepaths (list(str)): A list of filepaths."
  },
  {
    "code": "def get_n_header(f, header_char='\"'):\n    n_header = 0\n    reading_headers = True\n    while reading_headers:\n        line = f.readline()\n        if line.startswith(header_char):\n            n_header += 1\n        else:\n            reading_headers = False\n    return n_header",
    "docstring": "Get the nummber of header rows in a Little Leonardo data file\n\n    Args\n    ----\n    f : file stream\n        File handle for the file from which header rows will be read\n    header_char: str\n        Character array at beginning of each header line\n\n    Returns\n    -------\n    n_header: int\n        Number of header rows in Little Leonardo data file"
  },
  {
    "code": "def cms_identify(self, url, timeout=15, headers={}):\n        self.out.debug(\"cms_identify\")\n        if isinstance(self.regular_file_url, str):\n            rfu = [self.regular_file_url]\n        else:\n            rfu = self.regular_file_url\n        is_cms = False\n        for regular_file_url in rfu:\n            try:\n                hash = self.enumerate_file_hash(url, regular_file_url, timeout,\n                        headers)\n            except RuntimeError:\n                continue\n            hash_exists = self.vf.has_hash(hash)\n            if hash_exists:\n                is_cms = True\n                break\n        return is_cms",
    "docstring": "Function called when attempting to determine if a URL is identified\n        as being this particular CMS.\n        @param url: the URL to attempt to identify.\n        @param timeout: number of seconds before a timeout occurs on a http\n            connection.\n        @param headers: custom HTTP headers as expected by requests.\n        @return: a boolean value indiciating whether this CMS is identified\n            as being this particular CMS."
  },
  {
    "code": "def _index_classes(self) -> Dict[Text, Type[Platform]]:\n        out = {}\n        for p in get_platform_settings():\n            cls: Type[Platform] = import_class(p['class'])\n            if 'name' in p:\n                out[p['name']] = cls\n            else:\n                out[cls.NAME] = cls\n        return out",
    "docstring": "Build a name index for all platform classes"
  },
  {
    "code": "def to_index(self, index_type, index_name, includes=None):\n        return IndexField(self.name, self.data_type, index_type, index_name, includes)",
    "docstring": "Create an index field from this field"
  },
  {
    "code": "def is_encrypted_account(self, id):\n        for key in self.secured_field_names:\n            if not self.parser.is_secure_option(id, key):\n                return False\n        return True",
    "docstring": "Are all fields for the account id encrypted?"
  },
  {
    "code": "def invite_others_to_group(self, group_id, invitees):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"group_id\"] = group_id\r\n        data[\"invitees\"] = invitees\r\n        self.logger.debug(\"POST /api/v1/groups/{group_id}/invite with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"POST\", \"/api/v1/groups/{group_id}/invite\".format(**path), data=data, params=params, no_data=True)",
    "docstring": "Invite others to a group.\r\n\r\n        Sends an invitation to all supplied email addresses which will allow the\r\n        receivers to join the group."
  },
  {
    "code": "def factory(self, request, parent=None, name=None):\n        traverse = request.matchdict['traverse']\n        if not traverse:\n            return {}\n        else:\n            service = {}\n            name = name or traverse[0]\n            traversed = '/' + '/'.join(traverse)\n            service_type = None\n            service_object = None\n            for route, endpoint in self.routes:\n                result = route.match(traversed)\n                if result is not None:\n                    request.matchdict = result\n                    request.endpoint = endpoint\n                    break\n            else:\n                try:\n                    service_type, service_object = self.services[name]\n                except KeyError:\n                    raise HTTPNotFound()\n            if service_type:\n                if isinstance(service_type, Endpoint):\n                    service[name] = service_type\n                elif service_object is None:\n                    service[name] = service_type(request)\n                else:\n                    service[name] = service_type(request, service_object)\n            request.api_service = service\n            return service",
    "docstring": "Returns a new service for the given request.\n\n        :param      request | <pyramid.request.Request>\n\n        :return     <pyramid_restful.services.AbstractService>"
  },
  {
    "code": "def get_string_plus_property_value(value):\n    if value:\n        if isinstance(value, str):\n            return [value]\n        if isinstance(value, list):\n            return value\n        if isinstance(value, tuple):\n            return list(value)\n    return None",
    "docstring": "Converts a string or list of string into a list of strings\n\n    :param value: A string or a list of strings\n    :return: A list of strings or None"
  },
  {
    "code": "def _pnorm_diagweight(x, p, w):\n    order = 'F' if all(a.flags.f_contiguous for a in (x.data, w)) else 'C'\n    xp = np.abs(x.data.ravel(order))\n    if p == float('inf'):\n        xp *= w.ravel(order)\n        return np.max(xp)\n    else:\n        xp = np.power(xp, p, out=xp)\n        xp *= w.ravel(order)\n        return np.sum(xp) ** (1 / p)",
    "docstring": "Diagonally weighted p-norm implementation."
  },
  {
    "code": "def compute_hash(attributes, ignored_attributes=None):\n    ignored_attributes = list(ignored_attributes) if ignored_attributes else []\n    tuple_attributes = _convert(attributes.copy(), ignored_attributes)\n    hasher = hashlib.sha256(str(tuple_attributes).encode('utf-8', errors='ignore'))\n    return hasher.hexdigest()",
    "docstring": "Computes a hash code for the given dictionary that is safe for persistence round trips"
  },
  {
    "code": "def uninstall_handler(self, event_type, handler, user_handle=None):\n        self.visalib.uninstall_visa_handler(self.session, event_type, handler, user_handle)",
    "docstring": "Uninstalls handlers for events in this resource.\n\n        :param event_type: Logical event identifier.\n        :param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application.\n        :param user_handle: The user handle (ctypes object or None) returned by install_handler."
  },
  {
    "code": "def create_team(self, name, repo_names=[], permission=''):\n        data = {'name': name, 'repo_names': repo_names,\n                'permission': permission}\n        url = self._build_url('teams', base_url=self._api)\n        json = self._json(self._post(url, data), 201)\n        return Team(json, self._session) if json else None",
    "docstring": "Assuming the authenticated user owns this organization,\n        create and return a new team.\n\n        :param str name: (required), name to be given to the team\n        :param list repo_names: (optional) repositories, e.g.\n            ['github/dotfiles']\n        :param str permission: (optional), options:\n\n            - ``pull`` -- (default) members can not push or administer\n                repositories accessible by this team\n            - ``push`` -- members can push and pull but not administer\n                repositories accessible by this team\n            - ``admin`` -- members can push, pull and administer\n                repositories accessible by this team\n\n        :returns: :class:`Team <Team>`"
  },
  {
    "code": "def angles(triangles):\n    u = triangles[:, 1] - triangles[:, 0]\n    v = triangles[:, 2] - triangles[:, 0]\n    w = triangles[:, 2] - triangles[:, 1]\n    u /= np.linalg.norm(u, axis=1, keepdims=True)\n    v /= np.linalg.norm(v, axis=1, keepdims=True)\n    w /= np.linalg.norm(w, axis=1, keepdims=True)\n    a = np.arccos(np.clip(np.einsum('ij, ij->i', u, v), -1, 1))\n    b = np.arccos(np.clip(np.einsum('ij, ij->i', -u, w), -1, 1))\n    c = np.pi - a - b\n    return np.column_stack([a, b, c])",
    "docstring": "Calculates the angles of input triangles.\n\n    Parameters\n    ------------\n    triangles : (n, 3, 3) float\n      Vertex positions\n\n    Returns\n    ------------\n    angles : (n, 3) float\n      Angles at vertex positions, in radians"
  },
  {
    "code": "def hexbin(x, y, size, orientation=\"pointytop\", aspect_scale=1):\n    pd = import_required('pandas','hexbin requires pandas to be installed')\n    q, r = cartesian_to_axial(x, y, size, orientation, aspect_scale=aspect_scale)\n    df = pd.DataFrame(dict(r=r, q=q))\n    return df.groupby(['q', 'r']).size().reset_index(name='counts')",
    "docstring": "Perform an equal-weight binning of data points into hexagonal tiles.\n\n    For more sophisticated use cases, e.g. weighted binning or scaling\n    individual tiles proportional to some other quantity, consider using\n    HoloViews.\n\n    Args:\n        x (array[float]) :\n            A NumPy array of x-coordinates for binning\n\n        y (array[float]) :\n            A NumPy array of y-coordinates for binning\n\n        size (float) :\n            The size of the hexagonal tiling.\n\n            The size is defined as the distance from the center of a hexagon\n            to the top corner for \"pointytop\" orientation, or from the center\n            to a side corner for \"flattop\" orientation.\n\n        orientation (str, optional) :\n            Whether the hex tile orientation should be \"pointytop\" or\n            \"flattop\". (default: \"pointytop\")\n\n        aspect_scale (float, optional) :\n            Match a plot's aspect ratio scaling.\n\n            When working with a plot with ``aspect_scale != 1``, this\n            parameter can be set to match the plot, in order to draw\n            regular hexagons (instead of \"stretched\" ones).\n\n            This is roughly equivalent to binning in \"screen space\", and\n            it may be better to use axis-aligned rectangular bins when\n            plot aspect scales are not one.\n\n    Returns:\n        DataFrame\n\n        The resulting DataFrame will have columns *q* and *r* that specify\n        hexagon tile locations in axial coordinates, and a column *counts* that\n        provides the count for each tile.\n\n    .. warning::\n        Hex binning only functions on linear scales, i.e. not on log plots."
  },
  {
    "code": "def flipGenotype(genotype):\n    newGenotype = set()\n    for allele in genotype:\n        if allele == \"A\":\n            newGenotype.add(\"T\")\n        elif allele == \"C\":\n            newGenotype.add(\"G\")\n        elif allele == \"T\":\n            newGenotype.add(\"A\")\n        elif allele == \"G\":\n            newGenotype.add(\"C\")\n        else:\n            msg = \"%(allele)s: unknown allele\" % locals()\n            raise ProgramError(msg)\n    return newGenotype",
    "docstring": "Flips a genotype.\n\n    :param genotype: the genotype to flip.\n\n    :type genotype: set\n\n    :returns: the new flipped genotype (as a :py:class:`set`)\n\n    .. testsetup::\n\n        from pyGenClean.DupSNPs.duplicated_snps import flipGenotype\n\n    .. doctest::\n\n        >>> flipGenotype({\"A\", \"T\"})\n        set(['A', 'T'])\n        >>> flipGenotype({\"C\", \"T\"})\n        set(['A', 'G'])\n        >>> flipGenotype({\"T\", \"G\"})\n        set(['A', 'C'])\n        >>> flipGenotype({\"0\", \"0\"})\n        Traceback (most recent call last):\n            ...\n        ProgramError: 0: unkown allele\n        >>> flipGenotype({\"A\", \"N\"})\n        Traceback (most recent call last):\n            ...\n        ProgramError: N: unkown allele"
  },
  {
    "code": "def clean(self, force: bool=False):\n        with (yield from self._lock):\n            for connection in tuple(self.ready):\n                if force or connection.closed():\n                    connection.close()\n                    self.ready.remove(connection)",
    "docstring": "Clean closed connections.\n\n        Args:\n            force: Clean connected and idle connections too.\n\n        Coroutine."
  },
  {
    "code": "def coerce(val: t.Any,\n               coerce_type: t.Optional[t.Type] = None,\n               coercer: t.Optional[t.Callable] = None) -> t.Any:\n        if not coerce_type and not coercer:\n            return val\n        if coerce_type and type(val) is coerce_type:\n            return val\n        if coerce_type and coerce_type is bool and not coercer:\n            coercer = coerce_str_to_bool\n        if coercer is None:\n            coercer = coerce_type\n        return coercer(val)",
    "docstring": "Casts a type of ``val`` to ``coerce_type`` with ``coercer``.\n\n        If ``coerce_type`` is bool and no ``coercer`` specified it uses\n        :func:`~django_docker_helpers.utils.coerce_str_to_bool` by default.\n\n        :param val: a value of any type\n        :param coerce_type: any type\n        :param coercer: provide a callback that takes ``val`` and returns a value with desired type\n        :return: type casted value"
  },
  {
    "code": "def force_string(val=None):\n    if val is None:\n        return ''\n    if isinstance(val, list):\n        newval = [str(x) for x in val]\n        return ';'.join(newval)\n    if isinstance(val, str):\n        return val\n    else:\n        return str(val)",
    "docstring": "Force a string representation of an object\n\n    Args:\n        val: object to parse into a string\n\n    Returns:\n        str: String representation"
  },
  {
    "code": "def remove_from_queue(self, series):\n        result = self._android_api.remove_from_queue(series_id=series.series_id)\n        return result",
    "docstring": "Remove a series from the queue\n\n        @param crunchyroll.models.Series series\n        @return bool"
  },
  {
    "code": "def unarmor(pem_bytes, multiple=False):\n    generator = _unarmor(pem_bytes)\n    if not multiple:\n        return next(generator)\n    return generator",
    "docstring": "Convert a PEM-encoded byte string into a DER-encoded byte string\n\n    :param pem_bytes:\n        A byte string of the PEM-encoded data\n\n    :param multiple:\n        If True, function will return a generator\n\n    :raises:\n        ValueError - when the pem_bytes do not appear to be PEM-encoded bytes\n\n    :return:\n        A 3-element tuple (object_name, headers, der_bytes). The object_name is\n        a unicode string of what is between \"-----BEGIN \" and \"-----\". Examples\n        include: \"CERTIFICATE\", \"PUBLIC KEY\", \"PRIVATE KEY\". The headers is a\n        dict containing any lines in the form \"Name: Value\" that are right\n        after the begin line."
  },
  {
    "code": "def _thread_worker(self):\n        while self._running:\n            packet = self._queue.get(True)\n            if isinstance(packet, dict) and QS_CMD in packet:\n                try:\n                    self._callback_listen(packet)\n                except Exception as err:\n                    _LOGGER.error(\"Exception in callback\\nType: %s: %s\",\n                                  type(err), err)\n            self._queue.task_done()",
    "docstring": "Process callbacks from the queue populated by &listen."
  },
  {
    "code": "def exchange_reference(root_url, service, version):\n    root_url = root_url.rstrip('/')\n    if root_url == OLD_ROOT_URL:\n        return 'https://references.taskcluster.net/{}/{}/exchanges.json'.format(service, version)\n    else:\n        return '{}/references/{}/{}/exchanges.json'.format(root_url, service, version)",
    "docstring": "Generate URL for a Taskcluster exchange reference."
  },
  {
    "code": "def main():\n    try:\n        pkg_version = Update()\n        if pkg_version.updatable():\n            pkg_version.show_message()\n        metadata = control.retreive_metadata()\n        parser = parse_options(metadata)\n        argvs = sys.argv\n        if len(argvs) <= 1:\n            parser.print_help()\n            sys.exit(1)\n        args = parser.parse_args()\n        control.print_licences(args, metadata)\n        control.check_repository_existence(args)\n        control.check_package_existence(args)\n        control.generate_package(args)\n    except (RuntimeError, BackendFailure, Conflict) as exc:\n        sys.stderr.write('{0}\\n'.format(exc))\n        sys.exit(1)",
    "docstring": "Execute main processes."
  },
  {
    "code": "def get_token(self):\n    if self.__token is not None:\n      return self.__token\n    url = \"https://api.neur.io/v1/oauth2/token\"\n    creds = b64encode(\":\".join([self.__key,self.__secret]).encode()).decode()\n    headers = {\n      \"Authorization\": \" \".join([\"Basic\", creds]),\n    }\n    payload = {\n      \"grant_type\": \"client_credentials\"\n    }\n    r = requests.post(url, data=payload, headers=headers)\n    self.__token = r.json()[\"access_token\"]\n    return self.__token",
    "docstring": "Performs Neurio API token authentication using provided key and secret.\n\n    Note:\n      This method is generally not called by hand; rather it is usually\n      called as-needed by a Neurio Client object.\n\n    Returns:\n      string: the access token"
  },
  {
    "code": "def _add_task(self, task):\n        if hasattr(task, '_task_group'):\n            raise RuntimeError('task is already part of a group')\n        if self._closed:\n            raise RuntimeError('task group is closed')\n        task._task_group = self\n        if task.done():\n            self._done.append(task)\n        else:\n            self._pending.add(task)\n            task.add_done_callback(self._on_done)",
    "docstring": "Add an already existing task to the task group."
  },
  {
    "code": "def _write(self, session, openFile, replaceParamFile):\n        openFile.write(text(self.projection))",
    "docstring": "Projection File Write to File Method"
  },
  {
    "code": "def _is_valid_netmask(self, netmask):\n        mask = netmask.split('.')\n        if len(mask) == 4:\n            try:\n                for x in mask:\n                    if int(x) not in self._valid_mask_octets:\n                        return False\n            except ValueError:\n                return False\n            for idx, y in enumerate(mask):\n                if idx > 0 and y > mask[idx - 1]:\n                    return False\n            return True\n        try:\n            netmask = int(netmask)\n        except ValueError:\n            return False\n        return 0 <= netmask <= self._max_prefixlen",
    "docstring": "Verify that the netmask is valid.\n\n        Args:\n            netmask: A string, either a prefix or dotted decimal\n              netmask.\n\n        Returns:\n            A boolean, True if the prefix represents a valid IPv4\n            netmask."
  },
  {
    "code": "def _load_single_patient_cufflinks(self, patient, filter_ok):\n        data = pd.read_csv(patient.tumor_sample.cufflinks_path, sep=\"\\t\")\n        data[\"patient_id\"] = patient.id\n        if filter_ok:\n            data = data[data[\"FPKM_status\"] == \"OK\"]\n        return data",
    "docstring": "Load Cufflinks gene quantification given a patient\n\n        Parameters\n        ----------\n        patient : Patient\n        filter_ok : bool, optional\n            If true, filter Cufflinks data to row with FPKM_status == \"OK\"\n\n        Returns\n        -------\n        data: Pandas dataframe\n            Pandas dataframe of sample's Cufflinks data\n            columns include patient_id, gene_id, gene_short_name, FPKM, FPKM_conf_lo, FPKM_conf_hi"
  },
  {
    "code": "def _action_get(self, ids):\n        if not ids:\n            ids = self.jobs\n        result = []\n        ids = set(ids)\n        while ids:\n            id_ = ids.pop()\n            if id_ is None:\n                continue\n            try:\n                payload = r_client.get(id_)\n            except ResponseError:\n                continue\n            try:\n                payload = self._decode(payload)\n            except ValueError:\n                continue\n            else:\n                result.append(payload)\n            if payload['type'] == 'group':\n                for obj in self.traverse(id_):\n                    ids.add(obj['id'])\n        return result",
    "docstring": "Get the details for ids\n\n        Parameters\n        ----------\n        ids : {list, set, tuple, generator} of str\n            The IDs to get\n\n        Notes\n        -----\n        If ids is empty, then all IDs are returned.\n\n        Returns\n        -------\n        list of dict\n            The details of the jobs"
  },
  {
    "code": "def parse_document(xmlcontent):\n    document = etree.fromstring(xmlcontent)\n    body = document.xpath('.//w:body', namespaces=NAMESPACES)[0]\n    document = doc.Document()\n    for elem in body:\n        if elem.tag == _name('{{{w}}}p'):\n            document.elements.append(parse_paragraph(document, elem))\n        if elem.tag == _name('{{{w}}}tbl'):\n            document.elements.append(parse_table(document, elem))\n        if elem.tag == _name('{{{w}}}sdt'):\n            document.elements.append(doc.TOC())\n    return document",
    "docstring": "Parse document with content.\n\n    Content is placed in file 'document.xml'."
  },
  {
    "code": "def populateFromRow(self, ontologyRecord):\n        self._id = ontologyRecord.id\n        self._dataUrl = ontologyRecord.dataurl\n        self._readFile()",
    "docstring": "Populates this Ontology using values in the specified DB row."
  },
  {
    "code": "def lambert_xticks(ax, ticks):\n    te = lambda xy: xy[0]\n    lc = lambda t, n, b: np.vstack((np.zeros(n) + t, np.linspace(b[2], b[3], n))).T\n    xticks, xticklabels = _lambert_ticks(ax, ticks, 'bottom', lc, te)\n    ax.xaxis.tick_bottom()\n    ax.set_xticks(xticks)\n    ax.set_xticklabels([ax.xaxis.get_major_formatter()(xtick) for xtick in xticklabels])",
    "docstring": "Draw ticks on the bottom x-axis of a Lambert Conformal projection."
  },
  {
    "code": "def get_label(self, code):\n        for style in self.styles:\n            if style[1] == code:\n                return style[0]\n        msg = _(\"Code {code} is invalid.\").format(code=code)\n        raise ValueError(msg)",
    "docstring": "Returns string label for given code string\n\n        Inverse of get_code\n\n        Parameters\n        ----------\n        code: String\n        \\tCode string, field 1 of style tuple"
  },
  {
    "code": "def images(self):\n        for ds_id, projectable in self.datasets.items():\n            if ds_id in self.wishlist:\n                yield projectable.to_image()",
    "docstring": "Generate images for all the datasets from the scene."
  },
  {
    "code": "def walknset_vars(self, task_class=None, *args, **kwargs):\n        def change_task(task):\n            if task_class is not None and task.__class__ is not task_class: return False\n            return True\n        if self.is_work:\n            for task in self:\n                if not change_task(task): continue\n                task.set_vars(*args, **kwargs)\n        elif self.is_flow:\n            for task in self.iflat_tasks():\n                if not change_task(task): continue\n                task.set_vars(*args, **kwargs)\n        else:\n            raise TypeError(\"Don't know how to set variables for object class %s\"  % self.__class__.__name__)",
    "docstring": "Set the values of the ABINIT variables in the input files of the nodes\n\n        Args:\n            task_class: If not None, only the input files of the tasks belonging\n                to class `task_class` are modified.\n\n        Example:\n\n            flow.walknset_vars(ecut=10, kptopt=4)"
  },
  {
    "code": "def CallApiHandler(handler, args, token=None):\n    result = handler.Handle(args, token=token)\n    expected_type = handler.result_type\n    if expected_type is None:\n      expected_type = None.__class__\n    if result.__class__ != expected_type:\n      raise UnexpectedResultTypeError(\n          \"Expected %s, but got %s.\" %\n          (expected_type.__name__, result.__class__.__name__))\n    return result",
    "docstring": "Handles API call to a given handler with given args and token."
  },
  {
    "code": "def assert_is_not_substring(substring, subject, message=None, extra=None):\n    assert (\n        (subject is not None)\n        and (substring is not None)\n        and (subject.find(substring) == -1)\n    ), _assert_fail_message(message, substring, subject, \"is in\", extra)",
    "docstring": "Raises an AssertionError if substring is a substring of subject."
  },
  {
    "code": "def getChildrenInfo(self):\n        print '%s call getChildrenInfo' % self.port\n        try:\n            childrenInfoAll = []\n            childrenInfo = {'EUI': 0, 'Rloc16': 0, 'MLEID': ''}\n            childrenList = self.__sendCommand('child list')[0].split()\n            print childrenList\n            if 'Done' in childrenList:\n                print 'no children'\n                return None\n            for index in childrenList:\n                cmd = 'child %s' % index\n                child = []\n                child = self.__sendCommand(cmd)\n                for line in child:\n                    if 'Done' in line:\n                        break\n                    elif 'Rloc' in line:\n                        rloc16 = line.split()[1]\n                    elif 'Ext Addr' in line:\n                        eui = line.split()[2]\n                    else:\n                        pass\n                childrenInfo['EUI'] = int(eui, 16)\n                childrenInfo['Rloc16'] = int(rloc16, 16)\n                childrenInfoAll.append(childrenInfo['EUI'])\n            print childrenInfoAll\n            return childrenInfoAll\n        except Exception, e:\n            ModuleHelper.WriteIntoDebugLogger(\"getChildrenInfo() Error: \" + str(e))",
    "docstring": "get all children information\n\n        Returns:\n            children's extended address"
  },
  {
    "code": "def validateaddress(self, address: str) -> bool:\n        \"Returns True if the passed address is valid, False otherwise.\"\n        try:\n            Address.from_string(address, self.network_properties)\n        except InvalidAddress:\n            return False\n        return True",
    "docstring": "Returns True if the passed address is valid, False otherwise."
  },
  {
    "code": "def cfgGetBool(theObj, name, dflt):\n    strval = theObj.get(name, None)\n    if strval is None:\n        return dflt\n    return strval.lower().strip() == 'true'",
    "docstring": "Get a stringified val from a ConfigObj obj and return it as bool"
  },
  {
    "code": "def from_google(cls, google_x, google_y, zoom):\n        max_tile = (2 ** zoom) - 1\n        assert 0 <= google_x <= max_tile, 'Google X needs to be a value between 0 and (2^zoom) -1.'\n        assert 0 <= google_y <= max_tile, 'Google Y needs to be a value between 0 and (2^zoom) -1.'\n        return cls(tms_x=google_x, tms_y=(2 ** zoom - 1) - google_y, zoom=zoom)",
    "docstring": "Creates a tile from Google format X Y and zoom"
  },
  {
    "code": "def submit_by_selector(self, selector):\n    elem = find_element_by_jquery(world.browser, selector)\n    elem.submit()",
    "docstring": "Submit the form matching the CSS selector."
  },
  {
    "code": "def _nodedev_event_update_cb(conn, dev, opaque):\n    _salt_send_event(opaque, conn, {\n        'nodedev': {\n            'name': dev.name()\n        },\n        'event': opaque['event']\n    })",
    "docstring": "Node device update events handler"
  },
  {
    "code": "def make_reader_task(self, stream, callback):\n        return self.loop.create_task(self.executor_wrapper(background_reader, stream, self.loop, callback))",
    "docstring": "Create a reader executor task for a stream."
  },
  {
    "code": "def grant_user_access(self, user, db_names, strict=True):\n        user = utils.get_name(user)\n        uri = \"/%s/%s/databases\" % (self.uri_base, user)\n        db_names = self._get_db_names(db_names, strict=strict)\n        dbs = [{\"name\": db_name} for db_name in db_names]\n        body = {\"databases\": dbs}\n        try:\n            resp, resp_body = self.api.method_put(uri, body=body)\n        except exc.NotFound as e:\n            raise exc.NoSuchDatabaseUser(\"User '%s' does not exist.\" % user)",
    "docstring": "Gives access to the databases listed in `db_names` to the user. You may\n        pass in either a single db or a list of dbs.\n\n        If any of the databases do not exist, a NoSuchDatabase exception will\n        be raised, unless you specify `strict=False` in the call."
  },
  {
    "code": "def add_redistribution(self, protocol, route_map_name=None):\n        protocols = ['bgp', 'rip', 'static', 'connected']\n        if protocol not in protocols:\n            raise ValueError('redistributed protocol must be'\n                             'bgp, connected, rip or static')\n        if route_map_name is None:\n            cmd = 'redistribute {}'.format(protocol)\n        else:\n            cmd = 'redistribute {} route-map {}'.format(protocol,\n                                                        route_map_name)\n        return self.configure_ospf(cmd)",
    "docstring": "Adds a protocol redistribution to OSPF\n\n           Args:\n               protocol (str):  protocol to redistribute\n               route_map_name (str): route-map to be used to\n                                     filter the protocols\n           Returns:\n               bool: True if the command completes successfully\n           Exception:\n               ValueError:  This will be raised if the protocol pass is not one\n                            of the following: [rip, bgp, static, connected]"
  },
  {
    "code": "def evaluate(self, dataset):\n        if dataset is None:\n            values = [self.f_eval()]\n        else:\n            values = [self.f_eval(*x) for x in dataset]\n        monitors = zip(self._monitor_names, np.mean(values, axis=0))\n        return collections.OrderedDict(monitors)",
    "docstring": "Evaluate the current model parameters on a dataset.\n\n        Parameters\n        ----------\n        dataset : :class:`Dataset <downhill.dataset.Dataset>`\n            A set of data to use for evaluating the model.\n\n        Returns\n        -------\n        monitors : OrderedDict\n            A dictionary mapping monitor names to values. Monitors are\n            quantities of interest during optimization---for example, loss\n            function, accuracy, or whatever the optimization task requires."
  },
  {
    "code": "def find(cls, dtype):\n        try:\n            return cls._member_map_[dtype]\n        except KeyError:\n            try:\n                dtype = numpy.dtype(dtype).type\n            except TypeError:\n                for ndstype in cls._member_map_.values():\n                    if ndstype.value is dtype:\n                        return ndstype\n            else:\n                for ndstype in cls._member_map_.values():\n                    if ndstype.value and ndstype.numpy_dtype is dtype:\n                        return ndstype\n            raise ValueError('%s is not a valid %s' % (dtype, cls.__name__))",
    "docstring": "Returns the NDS2 type corresponding to the given python type"
  },
  {
    "code": "def _process_info(self):\n        if not self._process:\n            return []\n        output, error = self._process.communicate(timeout=5)\n        if error is None:\n            error = b\"\"\n        output = output.decode(\"utf-8\").strip()\n        error = error.decode(\"utf-8\").strip()\n        info = (u\"returncode: %r\\n\"\n                u\"output:\\n%s\\n\"\n                u\"error:\\n%s\\n\" % (self._process.returncode, output, error))\n        return [info.encode(\"utf-8\")]",
    "docstring": "Return details about the fake process."
  },
  {
    "code": "def loadACatalog(filename):\n    ret = libxml2mod.xmlLoadACatalog(filename)\n    if ret is None:raise treeError('xmlLoadACatalog() failed')\n    return catalog(_obj=ret)",
    "docstring": "Load the catalog and build the associated data structures.\n      This can be either an XML Catalog or an SGML Catalog It\n      will recurse in SGML CATALOG entries. On the other hand XML\n       Catalogs are not handled recursively."
  },
  {
    "code": "def highlightBlock(self, text):\r\n        if self._allow_highlight:\r\n            start = self.previousBlockState() + 1\r\n            end = start + len(text)\r\n            for i, (fmt, letter) in enumerate(self._charlist[start:end]):\r\n                self.setFormat(i, 1, fmt)\r\n            self.setCurrentBlockState(end)\r\n            self.highlight_spaces(text)",
    "docstring": "Actually highlight the block"
  },
  {
    "code": "def login(self, email, password):\n        response = FlightData.session.post(\n            url=LOGIN_URL,\n            data={\n                'email': email,\n                'password': password,\n                'remember': 'true',\n                'type': 'web'\n            },\n            headers={\n                'Origin': 'https://www.flightradar24.com',\n                'Referer': 'https://www.flightradar24.com',\n                'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'\n            }\n        )\n        response = self._fr24.json_loads_byteified(\n            response.content) if response.status_code == 200 else None\n        if response:\n            token = response['userData']['subscriptionKey']\n            self.AUTH_TOKEN = token",
    "docstring": "Login to the flightradar24 session\n\n        The API currently uses flightradar24 as the primary data source. The site provides different levels of data based on user plans.\n        For users who have signed up for a plan, this method allows to login with the credentials from flightradar24. The API obtains\n        a token that will be passed on all the requests; this obtains the data as per the plan limits.\n\n        Args:\n            email (str): The email ID which is used to login to flightradar24\n            password (str): The password for the user ID\n\n        Example::\n\n            from pyflightdata import FlightData\n            f=FlightData()\n            f.login(myemail,mypassword)"
  },
  {
    "code": "def terminate(self, instances, count=0):\n        if not instances:\n            return\n        if count > 0:\n            instances = self._scale_down(instances, count)\n        self.ec2.terminate_instances([i.id for i in instances])",
    "docstring": "Terminate each provided running or stopped instance.\n\n        :param count:\n        :param instances: A list of instances.\n        :type instances: list"
  },
  {
    "code": "def check(self,\n            targets,\n            topological_order=False):\n    all_vts = self.wrap_targets(targets, topological_order=topological_order)\n    invalid_vts = [vt for vt in all_vts if not vt.valid]\n    return InvalidationCheck(all_vts, invalid_vts)",
    "docstring": "Checks whether each of the targets has changed and invalidates it if so.\n\n    Returns a list of VersionedTargetSet objects (either valid or invalid). The returned sets\n    'cover' the input targets, with one caveat: if the FingerprintStrategy\n    opted out of fingerprinting a target because it doesn't contribute to invalidation, then that\n    target will be excluded from all_vts and invalid_vts.\n\n    Callers can inspect these vts and rebuild the invalid ones, for example."
  },
  {
    "code": "def most_frequent_terms(self, depth):\n        counts = self.term_counts()\n        top_terms = set(list(counts.keys())[:depth])\n        end_count = list(counts.values())[:depth][-1]\n        bucket = self.term_count_buckets()[end_count]\n        return top_terms.union(set(bucket))",
    "docstring": "Get the X most frequent terms in the text, and then probe down to get\n        any other terms that have the same count as the last term.\n\n        Args:\n            depth (int): The number of terms.\n\n        Returns:\n            set: The set of frequent terms."
  },
  {
    "code": "def to_char(token):\n    if ord(token) in _range(9216, 9229 + 1):\n        token = _unichr(ord(token) - 9216)\n    return token",
    "docstring": "Transforms the ASCII control character symbols to their real char.\n\n    Note: If the token is not an ASCII control character symbol, just\n    return the token.\n\n    Keyword arguments:\n    token -- the token to transform"
  },
  {
    "code": "def fast_exit(code):\n    sys.stdout.flush()\n    sys.stderr.flush()\n    os._exit(code)",
    "docstring": "Exit without garbage collection, this speeds up exit by about 10ms for\n    things like bash completion."
  },
  {
    "code": "def link_text(cls):\n        link = cls.__name__\n        if link.endswith('View'):\n            link = link[:-4]\n        return link",
    "docstring": "Return link text for this view."
  },
  {
    "code": "def _set_session_cookie(self):\n        LOGGER.debug('Setting session cookie for %s', self.session.id)\n        self.set_secure_cookie(name=self._session_cookie_name,\n                               value=self.session.id,\n                               expires=self._cookie_expiration)",
    "docstring": "Set the session data cookie."
  },
  {
    "code": "def _resolve_attribute(self, attribute):\n        value = self.attributes[attribute]\n        if not value:\n            return None\n        resolved_value = re.sub('\\$\\((.*?)\\)',self._resolve_attribute_match, value)\n        return resolved_value",
    "docstring": "Recursively replaces references to other attributes with their value.\n\n        Args:\n            attribute (str): The name of the attribute to resolve.\n\n        Returns:\n            str: The resolved value of 'attribute'."
  },
  {
    "code": "def get_help_width():\n  if not sys.stdout.isatty() or termios is None or fcntl is None:\n    return _DEFAULT_HELP_WIDTH\n  try:\n    data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234')\n    columns = struct.unpack('hh', data)[1]\n    if columns >= _MIN_HELP_WIDTH:\n      return columns\n    return int(os.getenv('COLUMNS', _DEFAULT_HELP_WIDTH))\n  except (TypeError, IOError, struct.error):\n    return _DEFAULT_HELP_WIDTH",
    "docstring": "Returns the integer width of help lines that is used in TextWrap."
  },
  {
    "code": "def parse_column_filters(*definitions):\n    fltrs = []\n    for def_ in _flatten(definitions):\n        if is_filter_tuple(def_):\n            fltrs.append(def_)\n        else:\n            for splitdef in DELIM_REGEX.split(def_)[::2]:\n                fltrs.extend(parse_column_filter(splitdef))\n    return fltrs",
    "docstring": "Parse multiple compound column filter definitions\n\n    Examples\n    --------\n    >>> parse_column_filters('snr > 10', 'frequency < 1000')\n    [('snr', <function operator.gt>, 10.), ('frequency', <function operator.lt>, 1000.)]\n    >>> parse_column_filters('snr > 10 && frequency < 1000')\n    [('snr', <function operator.gt>, 10.), ('frequency', <function operator.lt>, 1000.)]"
  },
  {
    "code": "def _attach_new(self, records, current, touch=True):\n        changes = {\n            'attached': [],\n            'updated': []\n        }\n        for id, attributes in records.items():\n            if id not in current:\n                self.attach(id, attributes, touch)\n                changes['attached'].append(id)\n            elif len(attributes) > 0 and self.update_existing_pivot(id, attributes, touch):\n                changes['updated'].append(id)\n        return changes",
    "docstring": "Attach all of the IDs that aren't in the current dict."
  },
  {
    "code": "def match_host (host, domainlist):\n    if not host:\n        return False\n    for domain in domainlist:\n        if domain.startswith('.'):\n            if host.endswith(domain):\n                return True\n        elif host == domain:\n            return True\n    return False",
    "docstring": "Return True if host matches an entry in given domain list."
  },
  {
    "code": "def restart_user(self, subid):\n    if os.path.exists(self.data_base):\n        data_base = \"%s/%s\" %(self.data_base, subid)\n        for ext in ['revoked','finished']:\n            folder = \"%s_%s\" % (data_base, ext)\n            if os.path.exists(folder):\n                os.rename(folder, data_base)\n                self.logger.info('Restarting %s, folder is %s.' % (subid, data_base))\n        self.logger.warning('%s does not have revoked or finished folder, no changes necessary.' % (subid))\n        return data_base    \n    self.logger.warning('%s does not exist, cannot restart. %s' % (self.database, subid))",
    "docstring": "restart user will remove any \"finished\" or \"revoked\" extensions from \n    the user folder to restart the session. This command always comes from\n    the client users function, so we know subid does not start with the\n    study identifer first"
  },
  {
    "code": "def get_me(self):\n        response = self.request_json(self.config['me'])\n        user = objects.Redditor(self, response['name'], response)\n        user.__class__ = objects.LoggedInRedditor\n        return user",
    "docstring": "Return a LoggedInRedditor object.\n\n        Note: This function is only intended to be used with an 'identity'\n        providing OAuth2 grant."
  },
  {
    "code": "def license_name(self, license_name):\n        allowed_values = [\"CC0-1.0\", \"CC-BY-SA-4.0\", \"GPL-2.0\", \"ODbL-1.0\", \"CC-BY-NC-SA-4.0\", \"unknown\", \"DbCL-1.0\", \"CC-BY-SA-3.0\", \"copyright-authors\", \"other\", \"reddit-api\", \"world-bank\"]\n        if license_name not in allowed_values:\n            raise ValueError(\n                \"Invalid value for `license_name` ({0}), must be one of {1}\"\n                .format(license_name, allowed_values)\n            )\n        self._license_name = license_name",
    "docstring": "Sets the license_name of this DatasetNewRequest.\n\n        The license that should be associated with the dataset  # noqa: E501\n\n        :param license_name: The license_name of this DatasetNewRequest.  # noqa: E501\n        :type: str"
  },
  {
    "code": "def plot_eeg_erp_topo(all_epochs, colors=None):\n    all_evokeds = eeg_to_all_evokeds(all_epochs)\n    data = {}\n    for participant, epochs in all_evokeds.items():\n        for cond, epoch in epochs.items():\n            data[cond] = []\n    for participant, epochs in all_evokeds.items():\n        for cond, epoch in epochs.items():\n            data[cond].append(epoch)\n    if colors is not None:\n        color_list = []\n    else:\n        color_list = None\n    evokeds = []\n    for condition, evoked in data.items():\n        grand_average = mne.grand_average(evoked)\n        grand_average.comment = condition\n        evokeds += [grand_average]\n        if colors is not None:\n            color_list.append(colors[condition])\n    plot = mne.viz.plot_evoked_topo(evokeds, background_color=\"w\", color=color_list)\n    return(plot)",
    "docstring": "Plot butterfly plot.\n\n    DOCS INCOMPLETE :("
  },
  {
    "code": "def cl_mutect(self, params, tmp_dir):\n        gatk_jar = self._get_jar(\"muTect\", [\"mutect\"])\n        jvm_opts = config_utils.adjust_opts(self._jvm_opts,\n                                            {\"algorithm\": {\"memory_adjust\":\n                                                           {\"magnitude\": 1.1, \"direction\": \"decrease\"}}})\n        return [\"java\"] + jvm_opts + get_default_jvm_opts(tmp_dir) + \\\n               [\"-jar\", gatk_jar] + [str(x) for x in params]",
    "docstring": "Define parameters to run the mutect paired algorithm."
  },
  {
    "code": "def _post_analysis(self):\n        self._make_completed_functions()\n        new_changes = self._iteratively_analyze_function_features()\n        functions_do_not_return = new_changes['functions_do_not_return']\n        self._update_function_callsites(functions_do_not_return)\n        for _, edges in self._pending_edges.items():\n            for src_node, dst_node, data in edges:\n                self._graph_add_edge(src_node, dst_node, **data)\n        self._remove_non_return_edges()\n        CFGBase._post_analysis(self)",
    "docstring": "Post-CFG-construction.\n\n        :return: None"
  },
  {
    "code": "def scale_rc(self, servo, min, max, param):\n        min_pwm  = self.get_mav_param('%s_MIN'  % param, 0)\n        max_pwm  = self.get_mav_param('%s_MAX'  % param, 0)\n        if min_pwm == 0 or max_pwm == 0:\n            return 0\n        if max_pwm == min_pwm:\n            p = 0.0\n        else:\n            p = (servo-min_pwm) / float(max_pwm-min_pwm)\n        v = min + p*(max-min)\n        if v < min:\n            v = min\n        if v > max:\n            v = max\n        return v",
    "docstring": "scale a PWM value"
  },
  {
    "code": "def is_instance_throughput_too_low(self, inst_id):\n        r = self.instance_throughput_ratio(inst_id)\n        if r is None:\n            logger.debug(\"{} instance {} throughput is not \"\n                         \"measurable.\".format(self, inst_id))\n            return None\n        too_low = r < self.Delta\n        if too_low:\n            logger.display(\"{}{} instance {} throughput ratio {} is lower than Delta {}.\".\n                           format(MONITORING_PREFIX, self, inst_id, r, self.Delta))\n        else:\n            logger.trace(\"{} instance {} throughput ratio {} is acceptable.\".\n                         format(self, inst_id, r))\n        return too_low",
    "docstring": "Return whether the throughput of the master instance is greater than the\n        acceptable threshold"
  },
  {
    "code": "def simplices(self):\n        return [Simplex([self.points[i] for i in v]) for v in self.vertices]",
    "docstring": "Returns the simplices of the triangulation."
  },
  {
    "code": "def run_tasks(tasks, max_workers=None, use_processes=False):\n    futures = set()\n    if use_processes:\n        get_executor = concurrent.futures.ProcessPoolExecutor\n    else:\n        get_executor = concurrent.futures.ThreadPoolExecutor\n    with get_executor(max_workers) as executor:\n        def execute(function, name):\n            future = executor.submit(function)\n            future.name = name\n            futures.add(future)\n        def wait():\n            results = []\n            waited = concurrent.futures.wait(\n                futures, return_when=concurrent.futures.FIRST_COMPLETED\n            )\n            for future in waited.done:\n                exc = future.exception()\n                if exc is None:\n                    results.append(\n                        TaskResult(\n                            future.name,\n                            True,\n                            None,\n                            future.result()\n                        )\n                    )\n                else:\n                    results.append(TaskResult(future.name, False, exc, None))\n                futures.remove(future)\n            return results\n        return task_loop(tasks, execute, wait)",
    "docstring": "Run an iterable of tasks.\n\n    tasks: The iterable of tasks\n    max_workers: (optional, None) The maximum number of workers to use.\n        As of Python 3.5, if None is passed to the thread executor will\n        default to 5 * the number of processors and the process executor\n        will default to the number of processors. If you are running an\n        older version, consider this a non-optional value.\n    use_processes: (optional, False) use a process pool instead of a\n        thread pool."
  },
  {
    "code": "def get_topic_keyword_dictionary():\n    topic_keyword_dictionary = dict()\n    file_row_gen = get_file_row_generator(get_package_path() + \"/twitter/res/topics/topic_keyword_mapping\" + \".txt\",\n                                          \",\",\n                                          \"utf-8\")\n    for file_row in file_row_gen:\n        topic_keyword_dictionary[file_row[0]] = set([keyword for keyword in file_row[1:]])\n    return topic_keyword_dictionary",
    "docstring": "Opens the topic-keyword map resource file and returns the corresponding python dictionary.\n\n    - Input:  - file_path: The path pointing to the topic-keyword map resource file.\n\n    - Output: - topic_set: A topic to keyword python dictionary."
  },
  {
    "code": "def _overlap_slices(self, shape):\n        if len(shape) != 2:\n            raise ValueError('input shape must have 2 elements.')\n        xmin = self.bbox.ixmin\n        xmax = self.bbox.ixmax\n        ymin = self.bbox.iymin\n        ymax = self.bbox.iymax\n        if xmin >= shape[1] or ymin >= shape[0] or xmax <= 0 or ymax <= 0:\n            return None, None\n        slices_large = (slice(max(ymin, 0), min(ymax, shape[0])),\n                        slice(max(xmin, 0), min(xmax, shape[1])))\n        slices_small = (slice(max(-ymin, 0),\n                              min(ymax - ymin, shape[0] - ymin)),\n                        slice(max(-xmin, 0),\n                              min(xmax - xmin, shape[1] - xmin)))\n        return slices_large, slices_small",
    "docstring": "Calculate the slices for the overlapping part of the bounding\n        box and an array of the given shape.\n\n        Parameters\n        ----------\n        shape : tuple of int\n            The ``(ny, nx)`` shape of array where the slices are to be\n            applied.\n\n        Returns\n        -------\n        slices_large : tuple of slices\n            A tuple of slice objects for each axis of the large array,\n            such that ``large_array[slices_large]`` extracts the region\n            of the large array that overlaps with the small array.\n\n        slices_small : slice\n            A tuple of slice objects for each axis of the small array,\n            such that ``small_array[slices_small]`` extracts the region\n            of the small array that is inside the large array."
  },
  {
    "code": "def get_project_endpoint_from_env(project_id=None, host=None):\n  project_id = project_id or os.getenv(_DATASTORE_PROJECT_ID_ENV)\n  if not project_id:\n    raise ValueError('project_id was not provided. Either pass it in '\n                     'directly or set DATASTORE_PROJECT_ID.')\n  if os.getenv(_DATASTORE_HOST_ENV):\n    logging.warning('Ignoring value of environment variable DATASTORE_HOST. '\n                    'To point datastore to a host running locally, use the '\n                    'environment variable DATASTORE_EMULATOR_HOST')\n  url_override = os.getenv(_DATASTORE_URL_OVERRIDE_ENV)\n  if url_override:\n    return '%s/projects/%s' % (url_override, project_id)\n  localhost = os.getenv(_DATASTORE_EMULATOR_HOST_ENV)\n  if localhost:\n    return ('http://%s/%s/projects/%s'\n            % (localhost, API_VERSION, project_id))\n  host = host or GOOGLEAPIS_HOST\n  return 'https://%s/%s/projects/%s' % (host, API_VERSION, project_id)",
    "docstring": "Get Datastore project endpoint from environment variables.\n\n  Args:\n    project_id: The Cloud project, defaults to the environment\n        variable DATASTORE_PROJECT_ID.\n    host: The Cloud Datastore API host to use.\n\n  Returns:\n    the endpoint to use, for example\n    https://datastore.googleapis.com/v1/projects/my-project\n\n  Raises:\n    ValueError: if the wrong environment variable was set or a project_id was\n        not provided."
  },
  {
    "code": "def view(self, dtype=None):\n        return self._constructor(self._values.view(dtype),\n                                 index=self.index).__finalize__(self)",
    "docstring": "Create a new view of the Series.\n\n        This function will return a new Series with a view of the same\n        underlying values in memory, optionally reinterpreted with a new data\n        type. The new data type must preserve the same size in bytes as to not\n        cause index misalignment.\n\n        Parameters\n        ----------\n        dtype : data type\n            Data type object or one of their string representations.\n\n        Returns\n        -------\n        Series\n            A new Series object as a view of the same data in memory.\n\n        See Also\n        --------\n        numpy.ndarray.view : Equivalent numpy function to create a new view of\n            the same data in memory.\n\n        Notes\n        -----\n        Series are instantiated with ``dtype=float64`` by default. While\n        ``numpy.ndarray.view()`` will return a view with the same data type as\n        the original array, ``Series.view()`` (without specified dtype)\n        will try using ``float64`` and may fail if the original data type size\n        in bytes is not the same.\n\n        Examples\n        --------\n        >>> s = pd.Series([-2, -1, 0, 1, 2], dtype='int8')\n        >>> s\n        0   -2\n        1   -1\n        2    0\n        3    1\n        4    2\n        dtype: int8\n\n        The 8 bit signed integer representation of `-1` is `0b11111111`, but\n        the same bytes represent 255 if read as an 8 bit unsigned integer:\n\n        >>> us = s.view('uint8')\n        >>> us\n        0    254\n        1    255\n        2      0\n        3      1\n        4      2\n        dtype: uint8\n\n        The views share the same underlying values:\n\n        >>> us[0] = 128\n        >>> s\n        0   -128\n        1     -1\n        2      0\n        3      1\n        4      2\n        dtype: int8"
  },
  {
    "code": "def normalized(a, axis=-1, order=2):\n    import numpy\n    l2 = numpy.atleast_1d(numpy.linalg.norm(a, order, axis))\n    l2[l2==0] = 1\n    return a / numpy.expand_dims(l2, axis)",
    "docstring": "Return normalized vector for arbitrary axis\n\n    Args\n    ----\n    a: ndarray (n,3)\n        Tri-axial vector data\n    axis: int\n        Axis index to overwhich to normalize\n    order: int\n        Order of nomalization to calculate\n\n    Notes\n    -----\n    This function was adapted from the following StackOverflow answer:\n    http://stackoverflow.com/a/21032099/943773"
  },
  {
    "code": "def _sample_weight(kappa, dim):\n    dim = dim - 1\n    b = dim / (np.sqrt(4. * kappa ** 2 + dim ** 2) + 2 * kappa)\n    x = (1. - b) / (1. + b)\n    c = kappa * x + dim * np.log(1 - x ** 2)\n    while True:\n        z = np.random.beta(dim / 2., dim / 2.)\n        w = (1. - (1. + b) * z) / (1. - (1. - b) * z)\n        u = np.random.uniform(low=0, high=1)\n        if kappa * w + dim * np.log(1. - x * w) - c >= np.log(u):\n            return w",
    "docstring": "Rejection sampling scheme for sampling distance from center on\n    surface of the sphere."
  },
  {
    "code": "def request_vms_info(self, payload):\n        agent = payload.get('agent')\n        LOG.debug('request_vms_info: Getting VMs info for %s', agent)\n        req = dict(host=payload.get('agent'))\n        instances = self.get_vms_for_this_req(**req)\n        vm_info = []\n        for vm in instances:\n            vm_info.append(dict(status=vm.status,\n                           vm_mac=vm.mac,\n                           segmentation_id=vm.segmentation_id,\n                           host=vm.host,\n                           port_uuid=vm.port_id,\n                           net_uuid=vm.network_id,\n                           oui=dict(ip_addr=vm.ip,\n                                    vm_name=vm.name,\n                                    vm_uuid=vm.instance_id,\n                                    gw_mac=vm.gw_mac,\n                                    fwd_mod=vm.fwd_mod,\n                                    oui_id='cisco')))\n        try:\n            self.neutron_event.send_vm_info(agent, str(vm_info))\n        except (rpc.MessagingTimeout, rpc.RPCException, rpc.RemoteError):\n            LOG.error('Failed to send VM info to agent.')",
    "docstring": "Get the VMs from the database and send the info to the agent."
  },
  {
    "code": "def insert_option_group(self, idx, *args, **kwargs):\n        group = self.add_option_group(*args, **kwargs)\n        self.option_groups.pop()\n        self.option_groups.insert(idx, group)\n        return group",
    "docstring": "Insert an OptionGroup at a given position."
  },
  {
    "code": "def NormalizeRelativePath(path):\n        path_components = path.split('/')\n        normalized_components = []\n        for component in path_components:\n            if re.match(r'{[A-Za-z0-9_]+}$', component):\n                normalized_components.append(\n                    '{%s}' % Names.CleanName(component[1:-1]))\n            else:\n                normalized_components.append(component)\n        return '/'.join(normalized_components)",
    "docstring": "Normalize camelCase entries in path."
  },
  {
    "code": "def GetAll(self, interface_name, *args, **kwargs):\n        self.log('GetAll ' + interface_name)\n        if not interface_name:\n            interface_name = self.interface\n        try:\n            return self.props[interface_name]\n        except KeyError:\n            raise dbus.exceptions.DBusException(\n                'no such interface ' + interface_name,\n                name=self.interface + '.UnknownInterface')",
    "docstring": "Standard D-Bus API for getting all property values"
  },
  {
    "code": "def add(self, text, name, field, type='term', size=None, params=None):\n        func = None\n        if type == 'completion':\n            func = self.add_completion\n        elif type == 'phrase':\n            func = self.add_phrase\n        elif type == 'term':\n            func = self.add_term\n        else:\n            raise InvalidQuery('Invalid type')\n        func(text=text, name=name, field=field, size=size, params=params)",
    "docstring": "Set the suggester of given type.\n\n        :param text: text\n        :param name: name of suggest\n        :param field: field to be used\n        :param type: type of suggester to add, available types are: completion,\n                     phrase, term\n        :param size: number of phrases\n        :param params: dict of additional parameters to pass to the suggester\n        :return: None"
  },
  {
    "code": "def optimizer_tensor(self) -> Union[tf.Tensor, tf.Operation]:\n        return _get_attr(self, _optimizer_tensor=None)",
    "docstring": "The `optimizer_tensor` is an attribute for getting optimization's\n        optimizer tensor."
  },
  {
    "code": "def recv(self, timeout=None):\n        start = time()\n        time_left = timeout\n        while True:\n            msg, already_filtered = self._recv_internal(timeout=time_left)\n            if msg and (already_filtered or self._matches_filters(msg)):\n                LOG.log(self.RECV_LOGGING_LEVEL, 'Received: %s', msg)\n                return msg\n            elif timeout is None:\n                continue\n            else:\n                time_left = timeout - (time() - start)\n                if time_left > 0:\n                    continue\n                else:\n                    return None",
    "docstring": "Block waiting for a message from the Bus.\n\n        :type timeout: float or None\n        :param timeout:\n            seconds to wait for a message or None to wait indefinitely\n\n        :rtype: can.Message or None\n        :return:\n            None on timeout or a :class:`can.Message` object.\n        :raises can.CanError:\n            if an error occurred while reading"
  },
  {
    "code": "def parse(self):\n        self.tokenize()\n        if self.debug: print(\"Tokens found: %s\"%self.token_list)\n        try:\n            parse_tree = self.parse2()\n        except Exception as e:\n                raise e\n        return parse_tree",
    "docstring": "Tokenizes and parses an arithmetic expression into a parse tree.\n\n        @return: Returns a token string.\n        @rtype: lems.parser.expr.ExprNode"
  },
  {
    "code": "def FromFile(cls, filename, mime_type=None, auto_transfer=True,\n                 gzip_encoded=False, **kwds):\n        path = os.path.expanduser(filename)\n        if not os.path.exists(path):\n            raise exceptions.NotFoundError('Could not find file %s' % path)\n        if not mime_type:\n            mime_type, _ = mimetypes.guess_type(path)\n            if mime_type is None:\n                raise exceptions.InvalidUserInputError(\n                    'Could not guess mime type for %s' % path)\n        size = os.stat(path).st_size\n        return cls(open(path, 'rb'), mime_type, total_size=size,\n                   close_stream=True, auto_transfer=auto_transfer,\n                   gzip_encoded=gzip_encoded, **kwds)",
    "docstring": "Create a new Upload object from a filename."
  },
  {
    "code": "def got_scheduler_module_type_defined(self, module_type):\n        for scheduler_link in self.schedulers:\n            for module in scheduler_link.modules:\n                if module.is_a_module(module_type):\n                    return True\n        return False",
    "docstring": "Check if a module type is defined in one of the schedulers\n\n        :param module_type: module type to search for\n        :type module_type: str\n        :return: True if mod_type is found else False\n        :rtype: bool\n        TODO: Factorize it with got_broker_module_type_defined"
  },
  {
    "code": "def height_to_geopotential(height):\n    r\n    geopot = mpconsts.G * mpconsts.me * ((1 / mpconsts.Re) - (1 / (mpconsts.Re + height)))\n    return geopot",
    "docstring": "r\"\"\"Compute geopotential for a given height.\n\n    Parameters\n    ----------\n    height : `pint.Quantity`\n        Height above sea level (array_like)\n\n    Returns\n    -------\n    `pint.Quantity`\n        The corresponding geopotential value(s)\n\n    Examples\n    --------\n    >>> from metpy.constants import g, G, me, Re\n    >>> import metpy.calc\n    >>> from metpy.units import units\n    >>> height = np.linspace(0,10000, num = 11) * units.m\n    >>> geopot = metpy.calc.height_to_geopotential(height)\n    >>> geopot\n    <Quantity([     0.           9817.46806283  19631.85526579  29443.16305888\n    39251.39289118  49056.54621087  58858.62446525  68657.62910064\n    78453.56156253  88246.42329545  98036.21574306], 'meter ** 2 / second ** 2')>\n\n    Notes\n    -----\n    Derived from definition of geopotential in [Hobbs2006]_ pg.14 Eq.1.8."
  },
  {
    "code": "def remove(self, position):\n        if position <= 0:\n            return self.remove_first()\n        if position >= self.length() - 1:\n            return self.remove_last()\n        counter = 0\n        last_node = self.head\n        current_node = self.head\n        while current_node is not None and counter <= position:\n            if counter == position:\n                last_node.next_node = current_node.next_node\n                return True\n            last_node = current_node\n            current_node = current_node.next_node\n            counter += 1\n        return False",
    "docstring": "Removes at index\n\n        :param position: Index of removal\n        :return: bool: True iff removal completed successfully"
  },
  {
    "code": "def _find_update_fields(cls, field, doc):\n        def find_partial_matches():\n            for key in doc:\n                if len(key) > len(field):\n                    if key.startswith(field) and key[len(field)] == \".\":\n                        yield [key], doc[key]\n                elif len(key) < len(field):\n                    if field.startswith(key) and field[len(key)] == \".\":\n                        matched = cls._find_field(field[len(key) + 1 :], doc[key])\n                        if matched:\n                            match = matched[0]\n                            match[0].insert(0, key)\n                            yield match\n                        return\n        try:\n            return [([field], doc[field])]\n        except KeyError:\n            return list(find_partial_matches())",
    "docstring": "Find the fields in the update document which match the given field.\n\n        Both the field and the top level keys in the doc may be in dot\n        notation, eg \"a.b.c\". Returns a list of tuples (path, field_value) or\n        the empty list if the field is not present."
  },
  {
    "code": "def _obtain_lock_or_raise(self):\n        if self._has_lock():\n            return\n        lock_file = self._lock_file_path()\n        if os.path.isfile(lock_file):\n            raise IOError(\"Lock for file %r did already exist, delete %r in case the lock is illegal\" % (self._file_path, lock_file))\n        try:\n            fd = os.open(lock_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0)\n            os.close(fd)\n        except OSError,e:\n            raise IOError(str(e))\n        self._owns_lock = True",
    "docstring": "Create a lock file as flag for other instances, mark our instance as lock-holder\n\n        :raise IOError: if a lock was already present or a lock file could not be written"
  },
  {
    "code": "def search(self, dsl, params):\n        query_parameters = []\n        for key, value in params:\n            query_parameters.append(self.CITEDBY_THRIFT.kwargs(str(key), str(value)))\n        try:\n            result = self.client.search(dsl, query_parameters)\n        except self.CITEDBY_THRIFT.ServerError:\n            raise ServerError('you may trying to run a bad DSL Query')\n        try:\n            return json.loads(result)\n        except:\n            return None",
    "docstring": "Free queries to ES index.\n\n        dsl (string): with DSL query\n        params (list): [(key, value), (key, value)]\n            where key is a query parameter, and value is the value required for parameter, ex: [('size', '0'), ('search_type', 'count')]"
  },
  {
    "code": "def line(x_fn, y_fn, *, options={}, **interact_params):\n    fig = options.get('_fig', False) or _create_fig(options=options)\n    [line] = (_create_marks(fig=fig, marks=[bq.Lines], options=options))\n    _add_marks(fig, [line])\n    def wrapped(**interact_params):\n        x_data = util.maybe_call(x_fn, interact_params, prefix='x')\n        line.x = x_data\n        y_bound = util.maybe_curry(y_fn, x_data)\n        line.y = util.maybe_call(y_bound, interact_params, prefix='y')\n    controls = widgets.interactive(wrapped, **interact_params)\n    return widgets.VBox([controls, fig])",
    "docstring": "Generates an interactive line chart that allows users to change the\n    parameters of the inputs x_fn and y_fn.\n\n    Args:\n        x_fn (Array | (*args -> Array str | Array int | Array float)):\n            If array, uses array values for x-coordinates.\n\n            If function, must take parameters to interact with and return an\n            array of strings or numbers. These will become the x-coordinates\n            of the line plot.\n\n        y_fn (Array | (Array, *args -> Array int | Array float)):\n            If array, uses array values for y-coordinates.\n\n            If function, must take in the output of x_fn as its first parameter\n            and optionally other parameters to interact with. Must return an\n            array of numbers. These will become the y-coordinates of the line\n            plot.\n\n    Kwargs:\n        {options}\n\n        interact_params (dict): Keyword arguments in the same format as\n            `ipywidgets.interact`. One argument is required for each argument\n            of both `x_fn` and `y_fn`. If `x_fn` and `y_fn` have conflicting\n            parameter names, prefix the corresponding kwargs with `x__` and\n            `y__`.\n\n    Returns:\n        VBox with two children: the interactive controls and the figure.\n\n    >>> line([1, 2, 3], [4, 7, 10])\n    VBox(...)\n\n    >>> def x_values(max): return np.arange(0, max)\n    >>> def y_values(xs, sd):\n    ...     return xs + np.random.normal(len(xs), scale=sd)\n    >>> line(x_values, y_values, max=(10, 50), sd=(1, 10))\n    VBox(...)"
  },
  {
    "code": "def serialized(self, prepend_date=True):\n        name = self.serialized_name()\n        datetime = self.serialized_time(prepend_date)\n        return \"%s %s\" % (datetime, name)",
    "docstring": "Return a string fully representing the fact."
  },
  {
    "code": "def eeg_name_frequencies(freqs):\n    freqs = list(freqs)\n    freqs_names = []\n    for freq in freqs:\n        if freq < 1:\n            freqs_names.append(\"UltraLow\")\n        elif freq <= 3:\n            freqs_names.append(\"Delta\")\n        elif freq <= 7:\n            freqs_names.append(\"Theta\")\n        elif freq <= 9:\n            freqs_names.append(\"Alpha1/Mu\")\n        elif freq <= 12:\n            freqs_names.append(\"Alpha2/Mu\")\n        elif freq <= 13:\n            freqs_names.append(\"Beta1/Mu\")\n        elif freq <= 17:\n            freqs_names.append(\"Beta1\")\n        elif freq <= 30:\n            freqs_names.append(\"Beta2\")\n        elif freq <= 40:\n            freqs_names.append(\"Gamma1\")\n        elif freq <= 50:\n            freqs_names.append(\"Gamma2\")\n        else:\n            freqs_names.append(\"UltraHigh\")\n    return(freqs_names)",
    "docstring": "Name frequencies according to standart classifications.\n\n    Parameters\n    ----------\n    freqs : list or numpy.array\n        list of floats containing frequencies to classify.\n\n    Returns\n    ----------\n    freqs_names : list\n        Named frequencies\n\n    Example\n    ----------\n    >>> import neurokit as nk\n    >>>\n    >>> nk.eeg_name_frequencies([0.5, 1.5, 3, 5, 7, 15])\n\n    Notes\n    ----------\n    *Details*\n\n    - Delta: 1-3Hz\n    - Theta: 4-7Hz\n    - Alpha1: 8-9Hz\n    - Alpha2: 10-12Hz\n    - Beta1: 13-17Hz\n    - Beta2: 18-30Hz\n    - Gamma1: 31-40Hz\n    - Gamma2: 41-50Hz\n    - Mu: 8-13Hz\n\n    *Authors*\n\n    - Dominique Makowski (https://github.com/DominiqueMakowski)\n\n    References\n    ------------\n    - None"
  },
  {
    "code": "def csv_to_pickle(path=ROOT / \"raw\", clean=False):\n    for file in os.listdir(path):\n        base, ext = os.path.splitext(file)\n        if ext != \".csv\":\n            continue\n        LOG(f\"converting {file} to pickle\")\n        df = pd.read_csv(path / file, low_memory=True)\n        WRITE_DF(df, path / (base + \".\" + FILE_EXTENSION), **WRITE_DF_OPTS)\n        if clean:\n            os.remove(path / file)\n            LOG(f\"removed {file}\")",
    "docstring": "Convert all CSV files in path to pickle."
  },
  {
    "code": "def angle_to_cartesian(lon, lat):\n    theta = np.array(np.pi / 2. - lat)\n    return np.vstack((np.sin(theta) * np.cos(lon),\n                      np.sin(theta) * np.sin(lon),\n                      np.cos(theta))).T",
    "docstring": "Convert spherical coordinates to cartesian unit vectors."
  },
  {
    "code": "def settings(cls):\n        from bernard.platforms.management import get_platform_settings\n        for platform in get_platform_settings():\n            candidate = import_class(platform['class'])\n            if candidate == cls:\n                return platform.get('settings', {})",
    "docstring": "Find the settings for the current class inside the platforms\n        configuration."
  },
  {
    "code": "def complete_from_dir(directory):\n    global currDirModule\n    if currDirModule is not None:\n        if len(sys.path) > 0 and sys.path[0] == currDirModule:\n            del sys.path[0]\n    currDirModule = directory\n    sys.path.insert(0, directory)",
    "docstring": "This is necessary so that we get the imports from the same directory where the file\n    we are completing is located."
  },
  {
    "code": "def _extract_when(body):\n        when = body.get('timestamp', body.get('_context_timestamp'))\n        if when:\n            return Datatype.datetime.convert(when)\n        return utcnow()",
    "docstring": "Extract the generated datetime from the notification."
  },
  {
    "code": "def fqname_to_id(self, fq_name, type):\n        data = {\n            \"type\": type,\n            \"fq_name\": list(fq_name)\n        }\n        return self.post_json(self.make_url(\"/fqname-to-id\"), data)[\"uuid\"]",
    "docstring": "Return uuid for fq_name\n\n        :param fq_name: resource fq name\n        :type fq_name: FQName\n        :param type: resource type\n        :type type: str\n\n        :rtype: UUIDv4 str\n        :raises HttpError: fq_name not found"
  },
  {
    "code": "def get_option_columns(self, typ, element):\n        inter = self.get_typ_interface(typ)\n        return inter.get_option_columns(element)",
    "docstring": "Return the column of the model to show for each level\n\n        Because each level might be displayed in a combobox. So you might want to provide the column\n        to show.\n\n        :param typ: the typ of options. E.g. Asset, Alembic, Camera etc\n        :type typ: str\n        :param element: The element for wich the options should be fetched.\n        :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot`\n        :returns: a list of columns\n        :rtype: list\n        :raises: None"
  },
  {
    "code": "def junk_folder(self):\n        return self.folder_constructor(parent=self, name='Junk',\n                                       folder_id=OutlookWellKnowFolderNames\n                                       .JUNK.value)",
    "docstring": "Shortcut to get Junk Folder instance\n\n        :rtype: mailbox.Folder"
  },
  {
    "code": "def right_click_high_equalarea(self, event):\n        if event.LeftIsDown():\n            return\n        elif self.high_EA_setting == \"Zoom\":\n            self.high_EA_setting = \"Pan\"\n            try:\n                self.toolbar4.pan('off')\n            except TypeError:\n                pass\n        elif self.high_EA_setting == \"Pan\":\n            self.high_EA_setting = \"Zoom\"\n            try:\n                self.toolbar4.zoom()\n            except TypeError:\n                pass",
    "docstring": "toggles between zoom and pan effects for the high equal area on\n        right click\n\n        Parameters\n        ----------\n        event : the wx.MouseEvent that triggered the call of this function\n\n        Alters\n        ------\n        high_EA_setting, toolbar4 setting"
  },
  {
    "code": "def plot(x, y, units='absolute', axis=None, **kwargs):\n  r\n  if axis is None:\n    axis = plt.gca()\n  if units.lower() == 'relative':\n    x = rel2abs_x(x, axis)\n    y = rel2abs_y(y, axis)\n  return axis.plot(x, y, **kwargs)",
    "docstring": "r'''\nPlot.\n\n:arguments:\n\n  **x, y** (``list``)\n    Coordinates.\n\n:options:\n\n  **units** ([``'absolute'``] | ``'relative'``)\n    The type of units in which the coordinates are specified. Relative coordinates correspond to a\n    fraction of the relevant axis. If you use relative coordinates, be sure to set the limits and\n    scale before calling this function!\n\n  ...\n    Any ``plt.plot(...)`` option.\n\n:returns:\n\n  The handle of the ``plt.plot(...)`` command."
  },
  {
    "code": "def set_id_format(portal, format):\n    bs = portal.bika_setup\n    if 'portal_type' not in format:\n        return\n    logger.info(\"Applying format {} for {}\".format(format.get('form', ''),\n                                                   format.get(\n                                                       'portal_type')))\n    portal_type = format['portal_type']\n    ids = list()\n    id_map = bs.getIDFormatting()\n    for record in id_map:\n        if record.get('portal_type', '') == portal_type:\n            continue\n        ids.append(record)\n    ids.append(format)\n    bs.setIDFormatting(ids)",
    "docstring": "Sets the id formatting in setup for the format provided"
  },
  {
    "code": "def get_int_from_user(self, title=\"Enter integer value\",\n                          cond_func=lambda i: i is not None):\n        is_integer = False\n        while not is_integer:\n            dlg = wx.TextEntryDialog(None, title, title)\n            if dlg.ShowModal() == wx.ID_OK:\n                result = dlg.GetValue()\n            else:\n                return None\n            dlg.Destroy()\n            try:\n                integer = int(result)\n                if cond_func(integer):\n                    is_integer = True\n            except ValueError:\n                pass\n        return integer",
    "docstring": "Opens an integer entry dialog and returns integer\n\n        Parameters\n        ----------\n        title: String\n        \\tDialog title\n        cond_func: Function\n        \\tIf cond_func of int(<entry_value> then result is returned.\n        \\tOtherwise the dialog pops up again."
  },
  {
    "code": "def _get_rh_methods(rh):\n    for k, v in vars(rh).items():\n        if all([\n            k in HTTP_METHODS,\n            is_method(v),\n            hasattr(v, \"input_schema\")\n        ]):\n            yield (k, v)",
    "docstring": "Yield all HTTP methods in ``rh`` that are decorated\n    with schema.validate"
  },
  {
    "code": "def generate(env):\n    global GhostscriptAction\n    try:\n        if GhostscriptAction is None:\n            GhostscriptAction = SCons.Action.Action('$GSCOM', '$GSCOMSTR')\n        from SCons.Tool import pdf\n        pdf.generate(env)\n        bld = env['BUILDERS']['PDF']\n        bld.add_action('.ps', GhostscriptAction)\n    except ImportError as e:\n        pass\n    gsbuilder = SCons.Builder.Builder(action = SCons.Action.Action('$GSCOM', '$GSCOMSTR'))\n    env['BUILDERS']['Gs'] = gsbuilder\n    env['GS']      = gs\n    env['GSFLAGS'] = SCons.Util.CLVar('-dNOPAUSE -dBATCH -sDEVICE=pdfwrite')\n    env['GSCOM']   = '$GS $GSFLAGS -sOutputFile=$TARGET $SOURCES'",
    "docstring": "Add Builders and construction variables for Ghostscript to an\n    Environment."
  },
  {
    "code": "def list_users_in_group_category(self, group_category_id, search_term=None, unassigned=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"group_category_id\"] = group_category_id\r\n        if search_term is not None:\r\n            params[\"search_term\"] = search_term\r\n        if unassigned is not None:\r\n            params[\"unassigned\"] = unassigned\r\n        self.logger.debug(\"GET /api/v1/group_categories/{group_category_id}/users with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"GET\", \"/api/v1/group_categories/{group_category_id}/users\".format(**path), data=data, params=params, all_pages=True)",
    "docstring": "List users in group category.\r\n\r\n        Returns a list of users in the group category."
  },
  {
    "code": "def remote_get(cwd,\n               remote='origin',\n               user=None,\n               password=None,\n               redact_auth=True,\n               ignore_retcode=False,\n               output_encoding=None):\n    cwd = _expand_path(cwd, user)\n    all_remotes = remotes(cwd,\n                          user=user,\n                          password=password,\n                          redact_auth=redact_auth,\n                          ignore_retcode=ignore_retcode,\n                          output_encoding=output_encoding)\n    if remote not in all_remotes:\n        raise CommandExecutionError(\n            'Remote \\'{0}\\' not present in git checkout located at {1}'\n            .format(remote, cwd)\n        )\n    return all_remotes[remote]",
    "docstring": "Get the fetch and push URL for a specific remote\n\n    cwd\n        The path to the git checkout\n\n    remote : origin\n        Name of the remote to query\n\n    user\n        User under which to run the git command. By default, the command is run\n        by the user under which the minion is running.\n\n    password\n        Windows only. Required when specifying ``user``. This parameter will be\n        ignored on non-Windows platforms.\n\n      .. versionadded:: 2016.3.4\n\n    redact_auth : True\n        Set to ``False`` to include the username/password if the remote uses\n        HTTPS Basic Auth. Otherwise, this information will be redacted.\n\n        .. warning::\n            Setting this to ``False`` will not only reveal any HTTPS Basic Auth\n            that is configured, but the return data will also be written to the\n            job cache. When possible, it is recommended to use SSH for\n            authentication.\n\n        .. versionadded:: 2015.5.6\n\n    ignore_retcode : False\n        If ``True``, do not log an error to the minion log if the git command\n        returns a nonzero exit status.\n\n        .. versionadded:: 2015.8.0\n\n    output_encoding\n        Use this option to specify which encoding to use to decode the output\n        from any git commands which are run. This should not be needed in most\n        cases.\n\n        .. note::\n            This should only be needed if the files in the repository were\n            created with filenames using an encoding other than UTF-8 to handle\n            Unicode characters.\n\n        .. versionadded:: 2018.3.1\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt myminion git.remote_get /path/to/repo\n        salt myminion git.remote_get /path/to/repo upstream"
  },
  {
    "code": "def solve(self, value, filter_):\n        try:\n            return value[filter_.slice or filter_.index]\n        except IndexError:\n            return None",
    "docstring": "Get slice or entry defined by an index from the given value.\n\n        Arguments\n        ---------\n        value : ?\n            A value to solve in combination with the given filter.\n        filter_ : dataql.resource.SliceFilter\n            An instance of ``SliceFilter``to solve with the given value.\n\n        Example\n        -------\n\n        >>> from dataql.solvers.registry import Registry\n        >>> registry = Registry()\n        >>> solver = SliceSolver(registry)\n        >>> solver.solve([1, 2, 3], SliceFilter(1))\n        2\n        >>> solver.solve([1, 2, 3], SliceFilter(slice(1, None, None)))\n        [2, 3]\n        >>> solver.solve([1, 2, 3], SliceFilter(slice(0, 2, 2)))\n        [1]\n        >>> solver.solve([1, 2, 3], SliceFilter(4))"
  },
  {
    "code": "def tag(self, image, repository, tag=None, force=False):\n        params = {\n            'tag': tag,\n            'repo': repository,\n            'force': 1 if force else 0\n        }\n        url = self._url(\"/images/{0}/tag\", image)\n        res = self._post(url, params=params)\n        self._raise_for_status(res)\n        return res.status_code == 201",
    "docstring": "Tag an image into a repository. Similar to the ``docker tag`` command.\n\n        Args:\n            image (str): The image to tag\n            repository (str): The repository to set for the tag\n            tag (str): The tag name\n            force (bool): Force\n\n        Returns:\n            (bool): ``True`` if successful\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error.\n\n        Example:\n\n            >>> client.tag('ubuntu', 'localhost:5000/ubuntu', 'latest',\n                           force=True)"
  },
  {
    "code": "def name_without_zeroes(name):\n    first_zero = name.find(b'\\0')\n    if first_zero == -1:\n        return name\n    else:\n        return str(name[:first_zero])",
    "docstring": "Return a human-readable name without LSDJ's trailing zeroes.\n\n    :param name: the name from which to strip zeroes\n    :rtype: the name, without trailing zeroes"
  },
  {
    "code": "def bisect(func, a, b, xtol=1e-12, maxiter=100):\n    fa = func(a)\n    if fa == 0.:\n        return a\n    fb = func(b)\n    if fb == 0.:\n        return b\n    assert sign(fa) != sign(fb)\n    for i in xrange(maxiter):\n        c = (a + b) / 2.\n        fc = func(c)\n        if fc == 0. or abs(b - a) / 2. < xtol:\n            return c\n        if sign(fc) == sign(func(a)):\n            a = c\n        else:\n            b = c\n    else:\n        raise RuntimeError('Failed to converge after %d iterations.' % maxiter)",
    "docstring": "Finds the root of `func` using the bisection method.\n\n    Requirements\n    ------------\n    - func must be continuous function that accepts a single number input\n      and returns a single number\n    - `func(a)` and `func(b)` must have opposite sign\n\n    Parameters\n    ----------\n    func : function\n        the function that we want to find the root of\n    a : number\n        one of the bounds on the input\n    b : number\n        the other bound on the input\n    xtol : number, optional\n        the solution tolerance of the input value. The algorithm is\n        considered converged if `abs(b-a)2. < xtol`\n    maxiter : number, optional\n        the maximum number of iterations allowed for convergence"
  },
  {
    "code": "def setup_block_and_grid(problem_size, grid_div, params, block_size_names=None):\n    threads = get_thread_block_dimensions(params, block_size_names)\n    current_problem_size = get_problem_size(problem_size, params)\n    grid = get_grid_dimensions(current_problem_size, params, grid_div, block_size_names)\n    return threads, grid",
    "docstring": "compute problem size, thread block and grid dimensions for this kernel"
  },
  {
    "code": "async def print_what_is_playing(loop):\n    print('Discovering devices on network...')\n    atvs = await pyatv.scan_for_apple_tvs(loop, timeout=5)\n    if not atvs:\n        print('no device found', file=sys.stderr)\n        return\n    print('Connecting to {0}'.format(atvs[0].address))\n    atv = pyatv.connect_to_apple_tv(atvs[0], loop)\n    try:\n        playing = await atv.metadata.playing()\n        print('Currently playing:')\n        print(playing)\n    finally:\n        await atv.logout()",
    "docstring": "Find a device and print what is playing."
  },
  {
    "code": "def generate_docs(app):\n    config = app.config\n    config_dir = app.env.srcdir\n    source_root = os.path.join(config_dir, config.apidoc_source_root)\n    output_root = os.path.join(config_dir, config.apidoc_output_root)\n    execution_dir = os.path.join(config_dir, '..')\n    cleanup(output_root)\n    command = ['sphinx-apidoc', '-f', '-o', output_root, source_root]\n    for exclude in config.apidoc_exclude:\n        command.append(os.path.join(source_root, exclude))\n    process = Popen(command, cwd=execution_dir)\n    process.wait()",
    "docstring": "Run sphinx-apidoc to generate Python API documentation for the project."
  },
  {
    "code": "def get_frame(self, in_data, frame_count, time_info, status):\n\t\twhile self.keep_listening:\n\t\t\ttry:\n\t\t\t\tframe = self.queue.get(False, timeout=queue_timeout)\n\t\t\t\treturn (frame, pyaudio.paContinue)\n\t\t\texcept Empty:\n\t\t\t\tpass\n\t\treturn (None, pyaudio.paComplete)",
    "docstring": "Callback function for the pyaudio stream. Don't use directly."
  },
  {
    "code": "def _ExtractContentFromDataStream(\n      self, mediator, file_entry, data_stream_name):\n    self.processing_status = definitions.STATUS_INDICATOR_EXTRACTING\n    if self._processing_profiler:\n      self._processing_profiler.StartTiming('extracting')\n    self._event_extractor.ParseDataStream(\n        mediator, file_entry, data_stream_name)\n    if self._processing_profiler:\n      self._processing_profiler.StopTiming('extracting')\n    self.processing_status = definitions.STATUS_INDICATOR_RUNNING\n    self.last_activity_timestamp = time.time()",
    "docstring": "Extracts content from a data stream.\n\n    Args:\n      mediator (ParserMediator): mediates the interactions between\n          parsers and other components, such as storage and abort signals.\n      file_entry (dfvfs.FileEntry): file entry to extract its content.\n      data_stream_name (str): name of the data stream whose content is to be\n          extracted."
  },
  {
    "code": "def commit_signal(data_id):\n    if not getattr(settings, 'FLOW_MANAGER_DISABLE_AUTO_CALLS', False):\n        immediate = getattr(settings, 'FLOW_MANAGER_SYNC_AUTO_CALLS', False)\n        async_to_sync(manager.communicate)(data_id=data_id, save_settings=False, run_sync=immediate)",
    "docstring": "Nudge manager at the end of every Data object save event."
  },
  {
    "code": "def is_git_repo():\n    cmd = \"git\", \"rev-parse\", \"--git-dir\"\n    try:\n        subprocess.run(cmd, stdout=subprocess.DEVNULL, check=True)\n        return True\n    except subprocess.CalledProcessError:\n        return False",
    "docstring": "Check whether the current folder is a Git repo."
  },
  {
    "code": "def set_value(*args, **kwargs):\n    global _config\n    if _config is None:\n        raise ValueError('configuration not set; must run figgypy.set_config first')\n    return _config.set_value(*args, **kwargs)",
    "docstring": "Set value in the global Config object."
  },
  {
    "code": "async def send(self, payload='', action_type='', channel=None, **kwds):\n        channel = channel or self.producer_channel\n        message = serialize_action(action_type=action_type, payload=payload, **kwds)\n        return await self._producer.send(channel, message.encode())",
    "docstring": "This method sends a message over the kafka stream."
  },
  {
    "code": "def from_dict(cls, data: Dict[str, Union[str, int]]):\n        assert isinstance(data, dict)\n        if 'ensembl_id' not in data:\n            raise ValueError('An \"ensembl_id\" key is missing!')\n        data = dict(data)\n        for attr in ['name', 'chromosome', 'position', 'length',\n                     'type', 'source']:\n            if attr in data and data[attr] == '':\n                data[attr] = None            \n        data['type_'] = data['type']\n        del data['type']\n        return cls(**data)",
    "docstring": "Generate an `ExpGene` object from a dictionary.\n\n        Parameters\n        ----------\n        data : dict\n            A dictionary with keys corresponding to attribute names.\n            Attributes with missing keys will be assigned `None`.\n\n        Returns\n        -------\n        `ExpGene`\n            The gene."
  },
  {
    "code": "def with_args(self, **kwargs):\n    new_info = mutablerecords.CopyRecord(self)\n    new_info.options = new_info.options.format_strings(**kwargs)\n    new_info.extra_kwargs.update(kwargs)\n    new_info.measurements = [m.with_args(**kwargs) for m in self.measurements]\n    return new_info",
    "docstring": "Send these keyword-arguments to the phase when called."
  },
  {
    "code": "def fit(self, x, fudge=1e-18):\n        assert x.ndim == 2\n        ns, nc = x.shape\n        x_cov = np.cov(x, rowvar=0)\n        assert x_cov.shape == (nc, nc)\n        d, v = np.linalg.eigh(x_cov)\n        d = np.diag(1. / np.sqrt(d + fudge))\n        w = np.dot(np.dot(v, d), v.T)\n        self._matrix = w\n        return w",
    "docstring": "Compute the whitening matrix.\n\n        Parameters\n        ----------\n\n        x : array\n            An `(n_samples, n_channels)` array."
  },
  {
    "code": "def add_sub_directory(self, key, path):\n        sub_dir_path = os.path.join(self.results_root, path)\n        os.makedirs(sub_dir_path, exist_ok=True)\n        self._directories[key] = sub_dir_path\n        return sub_dir_path",
    "docstring": "Adds a sub-directory to the results directory.\n\n        Parameters\n        ----------\n        key: str\n            A look-up key for the directory path.\n        path: str\n            The relative path from the root of the results directory to the sub-directory.\n\n        Returns\n        -------\n        str:\n            The absolute path to the sub-directory."
  },
  {
    "code": "def list(self, prefix='', delimiter='', marker='', headers=None):\n        return BucketListResultSet(self, prefix, delimiter, marker, headers)",
    "docstring": "List key objects within a bucket.  This returns an instance of an\n        BucketListResultSet that automatically handles all of the result\n        paging, etc. from S3.  You just need to keep iterating until\n        there are no more results.\n        \n        Called with no arguments, this will return an iterator object across\n        all keys within the bucket.\n\n        The Key objects returned by the iterator are obtained by parsing\n        the results of a GET on the bucket, also known as the List Objects\n        request.  The XML returned by this request contains only a subset\n        of the information about each key.  Certain metadata fields such\n        as Content-Type and user metadata are not available in the XML.\n        Therefore, if you want these additional metadata fields you will\n        have to do a HEAD request on the Key in the bucket.\n        \n        :type prefix: string\n        :param prefix: allows you to limit the listing to a particular\n                        prefix.  For example, if you call the method with\n                        prefix='/foo/' then the iterator will only cycle\n                        through the keys that begin with the string '/foo/'.\n                        \n        :type delimiter: string\n        :param delimiter: can be used in conjunction with the prefix\n                        to allow you to organize and browse your keys\n                        hierarchically. See:\n                        http://docs.amazonwebservices.com/AmazonS3/2006-03-01/\n                        for more details.\n                        \n        :type marker: string\n        :param marker: The \"marker\" of where you are in the result set\n        \n        :rtype: :class:`boto.s3.bucketlistresultset.BucketListResultSet`\n        :return: an instance of a BucketListResultSet that handles paging, etc"
  },
  {
    "code": "def get_app_state():\n    if not hasattr(g, 'app_state'):\n        model = get_model()\n        g.app_state = {\n            'app_title': APP_TITLE,\n            'model_name': type(model).__name__,\n            'latest_ckpt_name': model.latest_ckpt_name,\n            'latest_ckpt_time': model.latest_ckpt_time\n        }\n    return g.app_state",
    "docstring": "Get current status of application in context\n\n    Returns:\n        :obj:`dict` of application status"
  },
  {
    "code": "def running(opts):\n    ret = []\n    proc_dir = os.path.join(opts['cachedir'], 'proc')\n    if not os.path.isdir(proc_dir):\n        return ret\n    for fn_ in os.listdir(proc_dir):\n        path = os.path.join(proc_dir, fn_)\n        try:\n            data = _read_proc_file(path, opts)\n            if data is not None:\n                ret.append(data)\n        except (IOError, OSError):\n            pass\n    return ret",
    "docstring": "Return the running jobs on this minion"
  },
  {
    "code": "def setImembPtr(self): \n        jseg = 0\n        for sec in list(self.secs.values()):\n            hSec = sec['hObj']\n            for iseg, seg in enumerate(hSec):\n                self.imembPtr.pset(jseg, seg._ref_i_membrane_)\n                jseg += 1",
    "docstring": "Set PtrVector to point to the i_membrane_"
  },
  {
    "code": "def parse_xml_to_obj(self, xml_file, check_version=True, check_root=True,\n                         encoding=None):\n        root = get_etree_root(xml_file, encoding=encoding)\n        if check_root:\n            self._check_root_tag(root)\n        if check_version:\n            self._check_version(root)\n        entity_class = self.get_entity_class(root.tag)\n        entity_obj = entity_class._binding_class.factory()\n        entity_obj.build(root)\n        return entity_obj",
    "docstring": "Creates a STIX binding object from the supplied xml file.\n\n        Args:\n            xml_file: A filename/path or a file-like object representing a STIX\n                instance document\n            check_version: Inspect the version before parsing.\n            check_root: Inspect the root element before parsing.\n            encoding: The character encoding of the input `xml_file`.\n\n        Raises:\n            .UnknownVersionError: If `check_version` is ``True`` and `xml_file`\n                does not contain STIX version information.\n            .UnsupportedVersionError: If `check_version` is ``False`` and\n                `xml_file` contains an unsupported STIX version.\n            .UnsupportedRootElement: If `check_root` is ``True`` and `xml_file`\n                contains an invalid root element."
  },
  {
    "code": "def pct_positive(self, threshold=0.0):\n        return np.count_nonzero(self[self > threshold]) / self.count()",
    "docstring": "Pct. of periods in which `self` is greater than `threshold.`\n\n        Parameters\n        ----------\n        threshold : {float, TSeries, pd.Series}, default 0.\n\n        Returns\n        -------\n        float"
  },
  {
    "code": "def html_error_template():\n    import mako.template\n    return mako.template.Template(r\n, output_encoding=sys.getdefaultencoding(),\n        encoding_errors='htmlentityreplace')",
    "docstring": "Provides a template that renders a stack trace in an HTML format,\n    providing an excerpt of code as well as substituting source template\n    filenames, line numbers and code for that of the originating source\n    template, as applicable.\n\n    The template's default ``encoding_errors`` value is\n    ``'htmlentityreplace'``. The template has two options. With the\n    ``full`` option disabled, only a section of an HTML document is\n    returned. With the ``css`` option disabled, the default stylesheet\n    won't be included."
  },
  {
    "code": "def trim_join_unit(join_unit, length):\n    if 0 not in join_unit.indexers:\n        extra_indexers = join_unit.indexers\n        if join_unit.block is None:\n            extra_block = None\n        else:\n            extra_block = join_unit.block.getitem_block(slice(length, None))\n            join_unit.block = join_unit.block.getitem_block(slice(length))\n    else:\n        extra_block = join_unit.block\n        extra_indexers = copy.copy(join_unit.indexers)\n        extra_indexers[0] = extra_indexers[0][length:]\n        join_unit.indexers[0] = join_unit.indexers[0][:length]\n    extra_shape = (join_unit.shape[0] - length,) + join_unit.shape[1:]\n    join_unit.shape = (length,) + join_unit.shape[1:]\n    return JoinUnit(block=extra_block, indexers=extra_indexers,\n                    shape=extra_shape)",
    "docstring": "Reduce join_unit's shape along item axis to length.\n\n    Extra items that didn't fit are returned as a separate block."
  },
  {
    "code": "def info(self, section='default'):\n        if not section:\n            raise ValueError(\"invalid section\")\n        fut = self.execute(b'INFO', section, encoding='utf-8')\n        return wait_convert(fut, parse_info)",
    "docstring": "Get information and statistics about the server.\n\n        If called without argument will return default set of sections.\n        For available sections, see http://redis.io/commands/INFO\n\n        :raises ValueError: if section is invalid"
  },
  {
    "code": "def auto_slug(self):\n        slug = self.name\n        if slug is not None:\n            slug = slugify(slug, separator=self.SLUG_SEPARATOR)\n            session = sa.orm.object_session(self)\n            if not session:\n                return None\n            query = session.query(Entity.slug).filter(\n                Entity._entity_type == self.object_type\n            )\n            if self.id is not None:\n                query = query.filter(Entity.id != self.id)\n            slug_re = re.compile(re.escape(slug) + r\"-?(-\\d+)?\")\n            results = [\n                int(m.group(1) or 0)\n                for m in (slug_re.match(s.slug) for s in query.all() if s.slug)\n                if m\n            ]\n            max_id = max(-1, -1, *results) + 1\n            if max_id:\n                slug = f\"{slug}-{max_id}\"\n        return slug",
    "docstring": "This property is used to auto-generate a slug from the name\n        attribute.\n\n        It can be customized by subclasses."
  },
  {
    "code": "def socket_monitor_loop(self):\n        try:\n            while True:\n                gevent.socket.wait_read(self.socket.fileno())\n                self._handle_log_rotations()\n                self.capture_packet()\n        finally:\n            self.clean_up()",
    "docstring": "Monitor the socket and log captured data."
  },
  {
    "code": "def get(self, sid):\n        return ApplicationContext(self._version, account_sid=self._solution['account_sid'], sid=sid, )",
    "docstring": "Constructs a ApplicationContext\n\n        :param sid: The unique string that identifies the resource\n\n        :returns: twilio.rest.api.v2010.account.application.ApplicationContext\n        :rtype: twilio.rest.api.v2010.account.application.ApplicationContext"
  },
  {
    "code": "def encode_constructor_arguments(self, args):\n        if self.constructor_data is None:\n            raise ValueError(\n                \"The contract interface didn't have a constructor\")\n        return encode_abi(self.constructor_data['encode_types'], args)",
    "docstring": "Return the encoded constructor call."
  },
  {
    "code": "def _get_geom_type(type_bytes):\n    high_byte = type_bytes[0]\n    if six.PY3:\n        high_byte = bytes([high_byte])\n    has_srid = high_byte == b'\\x20'\n    if has_srid:\n        type_bytes = as_bin_str(b'\\x00' + type_bytes[1:])\n    else:\n        type_bytes = as_bin_str(type_bytes)\n    geom_type = _BINARY_TO_GEOM_TYPE.get(type_bytes)\n    return geom_type, type_bytes, has_srid",
    "docstring": "Get the GeoJSON geometry type label from a WKB type byte string.\n\n    :param type_bytes:\n        4 byte string in big endian byte order containing a WKB type number.\n        It may also contain a \"has SRID\" flag in the high byte (the first type,\n        since this is big endian byte order), indicated as 0x20. If the SRID\n        flag is not set, the high byte will always be null (0x00).\n    :returns:\n        3-tuple ofGeoJSON geometry type label, the bytes resprenting the\n        geometry type, and a separate \"has SRID\" flag. If the input\n        `type_bytes` contains an SRID flag, it will be removed.\n\n        >>> # Z Point, with SRID flag\n        >>> _get_geom_type(b'\\\\x20\\\\x00\\\\x03\\\\xe9') == (\n        ... 'Point', b'\\\\x00\\\\x00\\\\x03\\\\xe9', True)\n        True\n\n        >>> # 2D MultiLineString, without SRID flag\n        >>> _get_geom_type(b'\\\\x00\\\\x00\\\\x00\\\\x05') == (\n        ... 'MultiLineString', b'\\\\x00\\\\x00\\\\x00\\\\x05', False)\n        True"
  },
  {
    "code": "def to_sky(self, wcs, origin=_DEFAULT_WCS_ORIGIN, mode=_DEFAULT_WCS_MODE):\n        return SkyCoord.from_pixel(\n            xp=self.x, yp=self.y, wcs=wcs,\n            origin=origin, mode=mode,\n        )",
    "docstring": "Convert this `PixCoord` to `~astropy.coordinates.SkyCoord`.\n\n        Calls :meth:`astropy.coordinates.SkyCoord.from_pixel`.\n        See parameter description there."
  },
  {
    "code": "def _normalize_numpy_indices(i):\n    if isinstance(i, np.ndarray):\n        if i.dtype == bool:\n            i = tuple(j.tolist() for j in i.nonzero())\n        elif i.dtype == int:\n            i = i.tolist()\n    return i",
    "docstring": "Normalize the index in case it is a numpy integer or boolean\n    array."
  },
  {
    "code": "def choose(n, k):\n    import scipy.misc\n    return scipy.misc.comb(n, k, exact=True, repetition=False)",
    "docstring": "N choose k\n\n    binomial combination (without replacement)\n    scipy.special.binom"
  },
  {
    "code": "def docx_table_from_xml_node(table_node: ElementTree.Element,\n                             level: int,\n                             config: TextProcessingConfig) -> str:\n    table = CustomDocxTable()\n    for row_node in table_node:\n        if row_node.tag != DOCX_TABLE_ROW:\n            continue\n        table.new_row()\n        for cell_node in row_node:\n            if cell_node.tag != DOCX_TABLE_CELL:\n                continue\n            table.new_cell()\n            for para_node in cell_node:\n                text = docx_text_from_xml_node(para_node, level, config)\n                if text:\n                    table.add_paragraph(text)\n    return docx_process_table(table, config)",
    "docstring": "Converts an XML node representing a DOCX table into a textual\n    representation.\n\n    Args:\n        table_node: XML node\n        level: current level in XML hierarchy (used for recursion; start level\n            is 0)\n        config: :class:`TextProcessingConfig` control object\n\n    Returns:\n        string representation"
  },
  {
    "code": "def resize(self, size):\n        result = self._client.post('{}/resize'.format(Volume.api_endpoint, model=self,\n            data={ \"size\": size }))\n        self._populate(result.json)\n        return True",
    "docstring": "Resizes this Volume"
  },
  {
    "code": "def get_client_settings_config_file(**kwargs):\n    config_files = ['/etc/softlayer.conf', '~/.softlayer']\n    if kwargs.get('config_file'):\n        config_files.append(kwargs.get('config_file'))\n    config_files = [os.path.expanduser(f) for f in config_files]\n    config = utils.configparser.RawConfigParser({\n        'username': '',\n        'api_key': '',\n        'endpoint_url': '',\n        'timeout': '0',\n        'proxy': '',\n    })\n    config.read(config_files)\n    if config.has_section('softlayer'):\n        return {\n            'endpoint_url': config.get('softlayer', 'endpoint_url'),\n            'timeout': config.getfloat('softlayer', 'timeout'),\n            'proxy': config.get('softlayer', 'proxy'),\n            'username': config.get('softlayer', 'username'),\n            'api_key': config.get('softlayer', 'api_key'),\n        }",
    "docstring": "Retrieve client settings from the possible config file locations.\n\n        :param \\\\*\\\\*kwargs: Arguments that are passed into the client instance"
  },
  {
    "code": "def get(cls, bucket, key, version_id=None):\n        filters = [\n            cls.bucket_id == as_bucket_id(bucket),\n            cls.key == key,\n        ]\n        if version_id:\n            filters.append(cls.version_id == version_id)\n        else:\n            filters.append(cls.is_head.is_(True))\n            filters.append(cls.file_id.isnot(None))\n        return cls.query.filter(*filters).one_or_none()",
    "docstring": "Fetch a specific object.\n\n        By default the latest object version is returned, if\n        ``version_id`` is not set.\n\n        :param bucket: The bucket (instance or id) to get the object from.\n        :param key: Key of object.\n        :param version_id: Specific version of an object."
  },
  {
    "code": "def tvdb_login(api_key):\n    url = \"https://api.thetvdb.com/login\"\n    body = {\"apikey\": api_key}\n    status, content = _request_json(url, body=body, cache=False)\n    if status == 401:\n        raise MapiProviderException(\"invalid api key\")\n    elif status != 200 or not content.get(\"token\"):\n        raise MapiNetworkException(\"TVDb down or unavailable?\")\n    return content[\"token\"]",
    "docstring": "Logs into TVDb using the provided api key\n\n    Note: You can register for a free TVDb key at thetvdb.com/?tab=apiregister\n    Online docs: api.thetvdb.com/swagger#!/Authentication/post_login="
  },
  {
    "code": "def ValidateChildren(self, problems):\n    assert self._schedule, \"Trip must be in a schedule to ValidateChildren\"\n    self.ValidateNoDuplicateStopSequences(problems)\n    stoptimes = self.GetStopTimes(problems)\n    stoptimes.sort(key=lambda x: x.stop_sequence)\n    self.ValidateTripStartAndEndTimes(problems, stoptimes)\n    self.ValidateStopTimesSequenceHasIncreasingTimeAndDistance(problems,\n                                                               stoptimes)\n    self.ValidateShapeDistTraveledSmallerThanMaxShapeDistance(problems,\n                                                              stoptimes)\n    self.ValidateDistanceFromStopToShape(problems, stoptimes)\n    self.ValidateFrequencies(problems)",
    "docstring": "Validate StopTimes and headways of this trip."
  },
  {
    "code": "def serve_forever(self, poll_interval=0.5):\n        self.serial_port.timeout = poll_interval\n        while not self._shutdown_request:\n            try:\n                self.serve_once()\n            except (CRCError, struct.error) as e:\n                log.error('Can\\'t handle request: {0}'.format(e))\n            except (SerialTimeoutException, ValueError):\n                pass",
    "docstring": "Wait for incomming requests."
  },
  {
    "code": "def trunc(text, length):\n    if length < 1:\n        raise ValueError(\"length should be 1 or larger\")\n    text = text.strip()\n    text_length = wcswidth(text)\n    if text_length <= length:\n        return text\n    chars_to_truncate = 0\n    trunc_length = 0\n    for char in reversed(text):\n        chars_to_truncate += 1\n        trunc_length += wcwidth(char)\n        if text_length - trunc_length <= length:\n            break\n    n = chars_to_truncate + 1\n    return text[:-n].strip() + '…'",
    "docstring": "Truncates text to given length, taking into account wide characters.\n\n    If truncated, the last char is replaced by an elipsis."
  },
  {
    "code": "def replace_ext(filename, ext):\n    if ext.startswith('.'):\n        ext = ext[1:]\n    stem, _ = os.path.splitext(filename)\n    return (stem + '.' + ext)",
    "docstring": "Return new pathname formed by replacing extension in `filename` with `ext`."
  },
  {
    "code": "def get_accuracy(targets, outputs, k=1, ignore_index=None):\n    n_correct = 0.0\n    for target, output in zip(targets, outputs):\n        if not torch.is_tensor(target) or is_scalar(target):\n            target = torch.LongTensor([target])\n        if not torch.is_tensor(output) or is_scalar(output):\n            output = torch.LongTensor([[output]])\n        predictions = output.topk(k=min(k, len(output)), dim=0)[0]\n        for prediction in predictions:\n            if torch_equals_ignore_index(\n                    target.squeeze(), prediction.squeeze(), ignore_index=ignore_index):\n                n_correct += 1\n                break\n    return n_correct / len(targets), int(n_correct), len(targets)",
    "docstring": "Get the accuracy top-k accuracy between two tensors.\n\n    Args:\n      targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure\n          saccuracy\n      outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector\n      ignore_index (int, optional): Specifies a target index that is ignored\n\n    Returns:\n      :class:`tuple` consisting of accuracy (:class:`float`), number correct (:class:`int`) and\n      total (:class:`int`)\n\n    Example:\n\n        >>> import torch\n        >>> from torchnlp.metrics import get_accuracy\n        >>> targets = torch.LongTensor([1, 2, 3, 4, 5])\n        >>> outputs = torch.LongTensor([1, 2, 2, 3, 5])\n        >>> accuracy, n_correct, n_total = get_accuracy(targets, outputs, ignore_index=3)\n        >>> accuracy\n        0.8\n        >>> n_correct\n        4\n        >>> n_total\n        5"
  },
  {
    "code": "def _start_of_century(self):\n        year = self.year - 1 - (self.year - 1) % YEARS_PER_CENTURY + 1\n        return self.set(year, 1, 1)",
    "docstring": "Reset the date to the first day of the century.\n\n        :rtype: Date"
  },
  {
    "code": "def get_item(self, item_id):\n        if self.object_id:\n            url = self.build_url(\n                self._endpoints.get('get_item').format(id=self.object_id,\n                                                       item_id=item_id))\n        else:\n            url = self.build_url(\n                self._endpoints.get('get_item_default').format(item_id=item_id))\n        response = self.con.get(url)\n        if not response:\n            return None\n        data = response.json()\n        return self._classifier(data)(parent=self,\n                                      **{self._cloud_data_key: data})",
    "docstring": "Returns a DriveItem by it's Id\n\n        :return: one item\n        :rtype: DriveItem"
  },
  {
    "code": "def _poll_loop(self):\n        next_poll = time.time()\n        while True:\n            next_poll += self._poll_period\n            timeout = next_poll - time.time()\n            if timeout < 0:\n                timeout = 0\n            try:\n                return self._stop_queue.get(timeout=timeout)\n            except TimeoutError:\n                pass\n            try:\n                self.handle_changes(self.client.get_changes())\n            except Exception:\n                self.log.exception(\"Error while getting changes\")",
    "docstring": "At self.poll_period poll for changes"
  },
  {
    "code": "def _get_request_body_bytes_only(param_name, param_value):\n    if param_value is None:\n        return b''\n    if isinstance(param_value, bytes):\n        return param_value\n    raise TypeError(_ERROR_VALUE_SHOULD_BE_BYTES.format(param_name))",
    "docstring": "Validates the request body passed in and converts it to bytes\n    if our policy allows it."
  },
  {
    "code": "def viewbox(self):\n        return self.left, self.top, self.right, self.bottom",
    "docstring": "Return bounding box of the viewport.\n\n        :return: (left, top, right, bottom) `tuple`."
  },
  {
    "code": "def watch(self, resource, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None):\n        watcher = watch.Watch()\n        for event in watcher.stream(\n            resource.get,\n            namespace=namespace,\n            name=name,\n            field_selector=field_selector,\n            label_selector=label_selector,\n            resource_version=resource_version,\n            serialize=False,\n            timeout_seconds=timeout\n        ):\n            event['object'] = ResourceInstance(resource, event['object'])\n            yield event",
    "docstring": "Stream events for a resource from the Kubernetes API\n\n        :param resource: The API resource object that will be used to query the API\n        :param namespace: The namespace to query\n        :param name: The name of the resource instance to query\n        :param label_selector: The label selector with which to filter results\n        :param field_selector: The field selector with which to filter results\n        :param resource_version: The version with which to filter results. Only events with\n                                 a resource_version greater than this value will be returned\n        :param timeout: The amount of time in seconds to wait before terminating the stream\n\n        :return: Event object with these keys:\n                   'type': The type of event such as \"ADDED\", \"DELETED\", etc.\n                   'raw_object': a dict representing the watched object.\n                   'object': A ResourceInstance wrapping raw_object.\n\n        Example:\n            client = DynamicClient(k8s_client)\n            v1_pods = client.resources.get(api_version='v1', kind='Pod')\n\n            for e in v1_pods.watch(resource_version=0, namespace=default, timeout=5):\n                print(e['type'])\n                print(e['object'].metadata)"
  },
  {
    "code": "def nlmsg_reserve(n, len_, pad):\n    nlmsg_len_ = n.nm_nlh.nlmsg_len\n    tlen = len_ if not pad else ((len_ + (pad - 1)) & ~(pad - 1))\n    if tlen + nlmsg_len_ > n.nm_size:\n        return None\n    buf = bytearray_ptr(n.nm_nlh.bytearray, nlmsg_len_)\n    n.nm_nlh.nlmsg_len += tlen\n    if tlen > len_:\n        bytearray_ptr(buf, len_, tlen)[:] = bytearray(b'\\0') * (tlen - len_)\n    _LOGGER.debug('msg 0x%x: Reserved %d (%d) bytes, pad=%d, nlmsg_len=%d', id(n), tlen, len_, pad, n.nm_nlh.nlmsg_len)\n    return buf",
    "docstring": "Reserve room for additional data in a Netlink message.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L407\n\n    Reserves room for additional data at the tail of the an existing netlink message. Eventual padding required will be\n    zeroed out.\n\n    bytearray_ptr() at the start of additional data or None."
  },
  {
    "code": "def all_nets(transform_func):\n    @functools.wraps(transform_func)\n    def t_res(**kwargs):\n        net_transform(transform_func, **kwargs)\n    return t_res",
    "docstring": "Decorator that wraps a net transform function"
  },
  {
    "code": "def _narrow_states(node, old_state, new_state, previously_widened_state):\n        l.debug('Narrowing state at IP %s', previously_widened_state.ip)\n        s = previously_widened_state.copy()\n        narrowing_occurred = False\n        return s, narrowing_occurred",
    "docstring": "Try to narrow the state!\n\n        :param old_state:\n        :param new_state:\n        :param previously_widened_state:\n        :returns: The narrowed state, and whether a narrowing has occurred"
  },
  {
    "code": "def write_requirements(reqs_linenum, req_file):\n    with open(req_file, 'r') as input:\n        lines = input.readlines()\n    for req in reqs_linenum:\n        line_num = int(req[1])\n        if hasattr(req[0], 'link'):\n            lines[line_num - 1] = '{}\\n'.format(req[0].link)\n        else:\n            lines[line_num - 1] = '{}\\n'.format(req[0])\n    with open(req_file, 'w') as output:\n        output.writelines(lines)",
    "docstring": "Writes a list of req objects out to a given file."
  },
  {
    "code": "def get_access_flags_string(value):\n    buff = \"\"\n    for i in ACCESS_FLAGS:\n        if (i[0] & value) == i[0]:\n            buff += i[1] + \" \"\n    if buff != \"\":\n        return buff[:-1]\n    return buff",
    "docstring": "Transform an access flags to the corresponding string\n\n      :param value: the value of the access flags\n      :type value: int\n\n      :rtype: string"
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'batches' in _dict:\n            args['batches'] = [\n                BatchStatus._from_dict(x) for x in (_dict.get('batches'))\n            ]\n        return cls(**args)",
    "docstring": "Initialize a Batches object from a json dictionary."
  },
  {
    "code": "def search_for_devices_by_serial_number(self, sn):\n        import re\n        sn_search = re.compile(sn)\n        matches = []\n        for dev_o in self.get_all_devices_in_portal():\n            try:\n                if sn_search.match(dev_o['sn']):\n                    matches.append(dev_o)\n            except TypeError as err:\n                print(\"Problem checking device {!r}: {!r}\".format(\n                                    dev_o['info']['description']['name'],\n                                    str(err)))\n        return matches",
    "docstring": "Returns a list of device objects that match the serial number\n            in param 'sn'.\n\n            This will match partial serial numbers."
  },
  {
    "code": "async def jsk_vc_play(self, ctx: commands.Context, *, uri: str):\n        voice = ctx.guild.voice_client\n        if voice.is_playing():\n            voice.stop()\n        uri = uri.lstrip(\"<\").rstrip(\">\")\n        voice.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(uri)))\n        await ctx.send(f\"Playing in {voice.channel.name}.\")",
    "docstring": "Plays audio direct from a URI.\n\n        Can be either a local file or an audio resource on the internet."
  },
  {
    "code": "def _draw_score_box(self, label, score, position, size):\n        x1, y1 = position\n        width, height = size\n        pygame.draw.rect(self.screen, (187, 173, 160), (x1, y1, width, height))\n        w, h = label.get_size()\n        self.screen.blit(label, (x1 + (width - w) / 2, y1 + 8))\n        score = self.score_font.render(str(score), True, (255, 255, 255))\n        w, h = score.get_size()\n        self.screen.blit(score, (x1 + (width - w) / 2, y1 + (height + label.get_height() - h) / 2))",
    "docstring": "Draw a score box, whether current or best."
  },
  {
    "code": "def cfset_to_set(cfset):\n    count = cf.CFSetGetCount(cfset)\n    buffer = (c_void_p * count)()\n    cf.CFSetGetValues(cfset, byref(buffer))\n    return set([cftype_to_value(c_void_p(buffer[i])) for i in range(count)])",
    "docstring": "Convert CFSet to python set."
  },
  {
    "code": "def parse(self, rrstr):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('SF record already initialized!')\n        (su_len, su_entry_version_unused,) = struct.unpack_from('=BB', rrstr[:4], 2)\n        if su_len == 12:\n            (virtual_file_size_le, virtual_file_size_be) = struct.unpack_from('=LL', rrstr[:12], 4)\n            if virtual_file_size_le != utils.swab_32bit(virtual_file_size_be):\n                raise pycdlibexception.PyCdlibInvalidISO('Virtual file size little-endian does not match big-endian')\n            self.virtual_file_size_low = virtual_file_size_le\n        elif su_len == 21:\n            (virtual_file_size_high_le, virtual_file_size_high_be, virtual_file_size_low_le,\n             virtual_file_size_low_be, self.table_depth) = struct.unpack_from('=LLLLB', rrstr[:21], 4)\n            if virtual_file_size_high_le != utils.swab_32bit(virtual_file_size_high_be):\n                raise pycdlibexception.PyCdlibInvalidISO('Virtual file size high little-endian does not match big-endian')\n            if virtual_file_size_low_le != utils.swab_32bit(virtual_file_size_low_be):\n                raise pycdlibexception.PyCdlibInvalidISO('Virtual file size low little-endian does not match big-endian')\n            self.virtual_file_size_low = virtual_file_size_low_le\n            self.virtual_file_size_high = virtual_file_size_high_le\n        else:\n            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on Rock Ridge SF record (expected 12 or 21)')\n        self._initialized = True",
    "docstring": "Parse a Rock Ridge Sparse File record out of a string.\n\n        Parameters:\n         rrstr - The string to parse the record out of.\n        Returns:\n         Nothing."
  },
  {
    "code": "def concatenate_join_units(join_units, concat_axis, copy):\n    if concat_axis == 0 and len(join_units) > 1:\n        raise AssertionError(\"Concatenating join units along axis0\")\n    empty_dtype, upcasted_na = get_empty_dtype_and_na(join_units)\n    to_concat = [ju.get_reindexed_values(empty_dtype=empty_dtype,\n                                         upcasted_na=upcasted_na)\n                 for ju in join_units]\n    if len(to_concat) == 1:\n        concat_values = to_concat[0]\n        if copy:\n            if isinstance(concat_values, np.ndarray):\n                if concat_values.base is not None:\n                    concat_values = concat_values.copy()\n            else:\n                concat_values = concat_values.copy()\n    else:\n        concat_values = _concat._concat_compat(to_concat, axis=concat_axis)\n    return concat_values",
    "docstring": "Concatenate values from several join units along selected axis."
  },
  {
    "code": "def post(self, url, data=None, files=None, headers=None, raw=False,\n             send_as_json=True, content_type=None, **request_kwargs):\n        return self._secure_request(\n            url, 'post', data=data, files=files, headers=headers, raw=raw,\n            send_as_json=send_as_json, content_type=content_type,\n            **request_kwargs\n        )",
    "docstring": "POST request to AmigoCloud endpoint."
  },
  {
    "code": "def output(self, attrs=None, header=\"Set-Cookie:\", sep=\"\\015\\012\"):\n        result = []\n        items = sorted(self.items())\n        for key, value in items:\n            result.append(value.output(attrs, header))\n        return sep.join(result)",
    "docstring": "Return a string suitable for HTTP."
  },
  {
    "code": "def _locked_refresh_doc_ids(self):\n        d = {}\n        for s in self._shards:\n            for k in s.doc_index.keys():\n                if k in d:\n                    raise KeyError('doc \"{i}\" found in multiple repos'.format(i=k))\n                d[k] = s\n        self._doc2shard_map = d",
    "docstring": "Assumes that the caller has the _index_lock !"
  },
  {
    "code": "def namespace(self, name=None, function=None, recursive=None):\n        return (\n            self._find_single(\n                scopedef.scopedef_t._impl_matchers[namespace_t.namespace],\n                name=name,\n                function=function,\n                recursive=recursive)\n        )",
    "docstring": "Returns reference to namespace declaration that matches\n        a defined criteria."
  },
  {
    "code": "def get_schema_from_list(table_name, frum):\n    columns = UniqueIndex(keys=(\"name\",))\n    _get_schema_from_list(frum, \".\", parent=\".\", nested_path=ROOT_PATH, columns=columns)\n    return Schema(table_name=table_name, columns=list(columns))",
    "docstring": "SCAN THE LIST FOR COLUMN TYPES"
  },
  {
    "code": "def insert_uniques(self, table, columns, values):\n        existing_rows = self.select(table, columns)\n        unique = diff(existing_rows, values, y_only=True)\n        keys = self.get_primary_key_vals(table)\n        pk_col = self.get_primary_key(table)\n        pk_index = columns.index(pk_col)\n        to_insert, to_update = [], []\n        for index, row in enumerate(unique):\n            if row[pk_index] not in keys:\n                to_insert.append(unique[index])\n            elif row[pk_index] in keys:\n                to_update.append(unique[index])\n        if len(to_insert) > 0:\n            self.insert_many(table, columns, to_insert)\n        if len(to_update) > 0:\n            self.update_many(table, columns, to_update, pk_col, 0)\n        if len(to_insert) < 1 and len(to_update) < 0:\n            self._printer('No rows added to', table)",
    "docstring": "Insert multiple rows into a table that do not already exist.\n\n        If the rows primary key already exists, the rows values will be updated.\n        If the rows primary key does not exists, a new row will be inserted"
  },
  {
    "code": "def get_history(self, i=None):\n        ps = self.filter(context='history')\n        if i is not None:\n            return ps.to_list()[i]\n        else:\n            return ps",
    "docstring": "Get a history item by index.\n\n        You can toggle whether history is recorded using\n            * :meth:`enable_history`\n            * :meth:`disable_history`\n\n        :parameter int i: integer for indexing (can be positive or\n            negative).  If i is None or not provided, the entire list\n            of history items will be returned\n        :return: :class:`phoebe.parameters.parameters.Parameter` if i is\n            an int, or :class:`phoebe.parameters.parameters.ParameterSet` if i\n            is not provided\n        :raises ValueError: if no history items have been recorded."
  },
  {
    "code": "def check(self, item_id):\n        response = self._request(\"tasks/view/{id}\".format(id=item_id))\n        if response.status_code == 404:\n            return False\n        try:\n            content = json.loads(response.content.decode('utf-8'))\n            status = content['task'][\"status\"]\n            if status == 'completed' or status == \"reported\":\n                return True\n        except ValueError as e:\n            raise sandboxapi.SandboxError(e)\n        return False",
    "docstring": "Check if an analysis is complete\n\n        :type  item_id: int\n        :param item_id: task_id to check.\n\n        :rtype:  bool\n        :return: Boolean indicating if a report is done or not."
  },
  {
    "code": "def is_active(self):\n        if self._queue.exhausted:\n            return False\n        return any(ch.is_active for ch in self._refs.values())",
    "docstring": "Returns True if listener has any active subscription."
  },
  {
    "code": "def run_field_scan(ModelClass, model_kwargs, t_output_every, t_upto, field,\n                   vals, force_resume=True, parallel=False):\n    model_kwarg_sets = [dict(model_kwargs, field=val) for val in vals]\n    run_kwarg_scan(ModelClass, model_kwarg_sets,\n                   t_output_every, t_upto, force_resume, parallel)",
    "docstring": "Run many models with a range of parameter sets.\n\n    Parameters\n    ----------\n    ModelClass: callable\n        A class or factory function that returns a model object by\n        calling `ModelClass(model_kwargs)`\n    model_kwargs: dict\n        See `ModelClass` explanation.\n    t_output_every: float\n        see :class:`Runner`.\n    t_upto: float\n        Run each model until the time is equal to this\n    field: str\n        The name of the field to be varied, whose values are in `vals`.\n    vals: array_like\n        Iterable of values to use to instantiate each Model object.\n    parallel: bool\n        Whether or not to run the models in parallel, using the Multiprocessing\n        library. If `True`, the number of concurrent tasks will be equal to\n        one less than the number of available cores detected."
  },
  {
    "code": "def prlsrvctl(sub_cmd, args=None, runas=None):\n    if not salt.utils.path.which('prlsrvctl'):\n        raise CommandExecutionError('prlsrvctl utility not available')\n    cmd = ['prlsrvctl', sub_cmd]\n    if args:\n        cmd.extend(_normalize_args(args))\n    return __salt__['cmd.run'](cmd, runas=runas)",
    "docstring": "Execute a prlsrvctl command\n\n    .. versionadded:: 2016.11.0\n\n    :param str sub_cmd:\n        prlsrvctl subcommand to execute\n\n    :param str args:\n        The arguments supplied to ``prlsrvctl <sub_cmd>``\n\n    :param str runas:\n        The user that the prlsrvctl command will be run as\n\n    Example:\n\n    .. code-block:: bash\n\n        salt '*' parallels.prlsrvctl info runas=macdev\n        salt '*' parallels.prlsrvctl usb list runas=macdev\n        salt -- '*' parallels.prlsrvctl set '--mem-limit auto' runas=macdev"
  },
  {
    "code": "def _hz_to_semitones(self, hz):\n        return np.log(hz / self._a440) / np.log(self._a)",
    "docstring": "Convert hertz into a number of semitones above or below some reference\n        value, in this case, A440"
  },
  {
    "code": "def _get_national_number_groups_without_pattern(numobj):\n    rfc3966_format = format_number(numobj, PhoneNumberFormat.RFC3966)\n    end_index = rfc3966_format.find(U_SEMICOLON)\n    if end_index < 0:\n        end_index = len(rfc3966_format)\n    start_index = rfc3966_format.find(U_DASH) + 1\n    return rfc3966_format[start_index:end_index].split(U_DASH)",
    "docstring": "Helper method to get the national-number part of a number, formatted without any national\n    prefix, and return it as a set of digit blocks that would be formatted together following\n    standard formatting rules."
  },
  {
    "code": "def drop_it(title, filters, blacklist):\n    title = title.lower()\n    matched = False\n    for f in filters:\n        if re.match(f, title):\n            matched = True\n    if not matched:\n        return True\n    for b in blacklist:\n        if re.match(b, title):\n            return True\n    return False",
    "docstring": "The found torrents should be in filters list and shouldn't be in blacklist."
  },
  {
    "code": "def create_trial_from_spec(spec, output_path, parser, **trial_kwargs):\n    try:\n        args = parser.parse_args(to_argv(spec))\n    except SystemExit:\n        raise TuneError(\"Error parsing args, see above message\", spec)\n    if \"resources_per_trial\" in spec:\n        trial_kwargs[\"resources\"] = json_to_resources(\n            spec[\"resources_per_trial\"])\n    return Trial(\n        trainable_name=spec[\"run\"],\n        config=spec.get(\"config\", {}),\n        local_dir=os.path.join(args.local_dir, output_path),\n        stopping_criterion=spec.get(\"stop\", {}),\n        checkpoint_freq=args.checkpoint_freq,\n        checkpoint_at_end=args.checkpoint_at_end,\n        keep_checkpoints_num=args.keep_checkpoints_num,\n        checkpoint_score_attr=args.checkpoint_score_attr,\n        export_formats=spec.get(\"export_formats\", []),\n        restore_path=spec.get(\"restore\"),\n        upload_dir=args.upload_dir,\n        trial_name_creator=spec.get(\"trial_name_creator\"),\n        loggers=spec.get(\"loggers\"),\n        sync_function=spec.get(\"sync_function\"),\n        max_failures=args.max_failures,\n        **trial_kwargs)",
    "docstring": "Creates a Trial object from parsing the spec.\n\n    Arguments:\n        spec (dict): A resolved experiment specification. Arguments should\n            The args here should correspond to the command line flags\n            in ray.tune.config_parser.\n        output_path (str); A specific output path within the local_dir.\n            Typically the name of the experiment.\n        parser (ArgumentParser): An argument parser object from\n            make_parser.\n        trial_kwargs: Extra keyword arguments used in instantiating the Trial.\n\n    Returns:\n        A trial object with corresponding parameters to the specification."
  },
  {
    "code": "def randomArray2(size, bound):\n    if type(size) == type(1):\n        size = (size,)\n    temp = Numeric.array( ndim(*size), thunk=lambda: random.gauss(0, 1)) * (2.0 * bound)\n    return temp - bound",
    "docstring": "Returns an array initialized to random values between -bound and\n    bound distributed in a gaussian probability distribution more\n    appropriate for a Tanh activation function."
  },
  {
    "code": "def get_pipeline(self, *args, **kwargs):\n        return getattr(missions, self.mission).pipelines.get(self.ID, *args,\n                                                             **kwargs)",
    "docstring": "Returns the `time` and `flux` arrays for the target obtained by a given\n        pipeline.\n\n        Options :py:obj:`args` and :py:obj:`kwargs` are passed directly to\n        the :py:func:`pipelines.get` function of the mission."
  },
  {
    "code": "def regex_match_list(line, patterns):\n    m = None\n    for ptn in patterns:\n        m = ptn.match(line)\n        if m is not None:\n            break\n    return m",
    "docstring": "Given a list of COMPILED regex patters, perform the \"re.match\" operation\n       on the line for every pattern.\n       Break from searching at the first match, returning the match object.\n       In the case that no patterns match, the None type will be returned.\n       @param line: (unicode string) to be searched in.\n       @param patterns: (list) of compiled regex patterns to search  \"line\"\n        with.\n       @return: (None or an re.match object), depending upon whether one of\n        the patterns matched within line or not."
  },
  {
    "code": "def template_file(\n    task: Task,\n    template: str,\n    path: str,\n    jinja_filters: FiltersDict = None,\n    **kwargs: Any\n) -> Result:\n    jinja_filters = jinja_filters or {} or task.nornir.config.jinja2.filters\n    text = jinja_helper.render_from_file(\n        template=template,\n        path=path,\n        host=task.host,\n        jinja_filters=jinja_filters,\n        **kwargs\n    )\n    return Result(host=task.host, result=text)",
    "docstring": "Renders contants of a file with jinja2. All the host data is available in the template\n\n    Arguments:\n        template: filename\n        path: path to dir with templates\n        jinja_filters: jinja filters to enable. Defaults to nornir.config.jinja2.filters\n        **kwargs: additional data to pass to the template\n\n    Returns:\n        Result object with the following attributes set:\n          * result (``string``): rendered string"
  },
  {
    "code": "def nvlist_to_dict(nvlist):\r\n    result = {}\r\n    for item in nvlist :\r\n        result[item.name] = item.value.value()\r\n    return result",
    "docstring": "Convert a CORBA namevalue list into a dictionary."
  },
  {
    "code": "def match(self, fsys_view):\n        evalue_dict = fsys_view[1]\n        for key, value in six.viewitems(self.criteria):\n            if key in evalue_dict:\n                if evalue_dict[key] != value:\n                    return False\n            else:\n                return False\n        return True",
    "docstring": "Compare potentially partial criteria against built filesystems entry dictionary"
  },
  {
    "code": "def updateSession(self, request):\n        secure = request.isSecure()\n        if not secure:\n            cookieString = b\"TWISTED_SESSION\"\n        else:\n            cookieString = b\"TWISTED_SECURE_SESSION\"\n        cookiename = b\"_\".join([cookieString] + request.sitepath)\n        request.addCookie(cookiename, self.uid, path=b\"/\",\n                          secure=secure)",
    "docstring": "Update the cookie after session object was modified\n        @param request: the request object which should get a new cookie"
  },
  {
    "code": "def build(self):\n        assert not self.final, 'Trying to mutate a final graph.'\n        for scc in sorted(nx.kosaraju_strongly_connected_components(self.graph),\n                          key=len, reverse=True):\n            if len(scc) == 1:\n                break\n            self.shrink_to_node(NodeSet(scc))\n        self.final = True",
    "docstring": "Finalise the graph, after adding all input files to it."
  },
  {
    "code": "def libvlc_event_attach(p_event_manager, i_event_type, f_callback, user_data):\n    f = _Cfunctions.get('libvlc_event_attach', None) or \\\n        _Cfunction('libvlc_event_attach', ((1,), (1,), (1,), (1,),), None,\n                    ctypes.c_int, EventManager, ctypes.c_uint, Callback, ctypes.c_void_p)\n    return f(p_event_manager, i_event_type, f_callback, user_data)",
    "docstring": "Register for an event notification.\n    @param p_event_manager: the event manager to which you want to attach to. Generally it is obtained by vlc_my_object_event_manager() where my_object is the object you want to listen to.\n    @param i_event_type: the desired event to which we want to listen.\n    @param f_callback: the function to call when i_event_type occurs.\n    @param user_data: user provided data to carry with the event.\n    @return: 0 on success, ENOMEM on error."
  },
  {
    "code": "def create(self, item, dry_run=None):\n        logger.debug('Creating new item. Item: {item} Path: {data_file}'.format(\n            item=item,\n            data_file=self.data_file\n        ))\n        items = load_file(self.client, self.bucket_name, self.data_file)\n        items = append_item(self.namespace, self.version, item, items)\n        save_file(self.client, self.bucket_name, self.data_file, items, dry_run=dry_run)\n        return item",
    "docstring": "Creates a new item in file."
  },
  {
    "code": "def clean(ctx):\n    os.chdir(PROJECT_DIR)\n    patterns = ['.cache',\n                '.coverage',\n                '.eggs',\n                'build',\n                'dist']\n    ctx.run('rm -vrf {0}'.format(' '.join(patterns)))\n    ctx.run(\n            )",
    "docstring": "clean generated project files"
  },
  {
    "code": "def _get_table_cells(table):\n    sent_map = defaultdict(list)\n    for sent in table.sentences:\n        if sent.is_tabular():\n            sent_map[sent.cell].append(sent)\n    return sent_map",
    "docstring": "Helper function with caching for table cells and the cells' sentences.\n\n    This function significantly improves the speed of `get_row_ngrams`\n    primarily by reducing the number of queries that are made (which were\n    previously the bottleneck. Rather than taking a single mention, then its\n    sentence, then its table, then all the cells in the table, then all the\n    sentences in each cell, and performing operations on that series of\n    queries, this performs a single query for all the sentences in a table and\n    returns all of the cells and the cells sentences directly.\n\n    :param table: the Table object to cache.\n    :return: an iterator of (Cell, [Sentence._asdict(), ...]) tuples."
  },
  {
    "code": "def get_state(self):\n        battery = self.player.stats['battery']/100\n        if len(self.mode['items']) > 0:\n            observation = []\n            for sensor in self.player.sensors:\n                col = []\n                col.append(sensor.proximity_norm())\n                for item_type in self.mode['items']:\n                    if sensor.sensed_type == item_type:\n                        col.append(sensor.proximity_norm())\n                    else:\n                        col.append(1)\n                observation.append(col)\n            if 'battery' in self.mode:\n                observation.append([battery,1,1])\n        else:\n            observation = [o.proximity_norm() for o in self.player.sensors]\n            if 'battery' in self.mode:\n                observation.append(battery)\n        return observation",
    "docstring": "Create state from sensors and battery"
  },
  {
    "code": "def execute_proc(self, procname, args):\n        self.logger(procname, args)\n        with self.cursor() as cursor:\n            cursor.callproc(procname, args)\n            return cursor",
    "docstring": "Execute a stored procedure, returning a cursor. For internal use\n        only."
  },
  {
    "code": "def childgroup(self, field):\n        grid = getattr(self, \"grid\", None)\n        named_grid = getattr(self, \"named_grid\", None)\n        if grid is not None:\n            childgroup = self._childgroup(field.children, grid)\n        elif named_grid is not None:\n            childgroup = self._childgroup_by_name(field.children, named_grid)\n        else:\n            raise AttributeError(u\"Missing the grid or named_grid argument\")\n        return childgroup",
    "docstring": "Return a list of fields stored by row regarding the configured grid\n\n        :param field: The original field this widget is attached to"
  },
  {
    "code": "def refreshThumbnails( self ):\r\n        widget = self.thumbnailWidget()\r\n        widget.setUpdatesEnabled(False)\r\n        widget.blockSignals(True)\r\n        widget.clear()\r\n        widget.setIconSize(self.thumbnailSize())\r\n        factory = self.factory()\r\n        if ( self.isGroupingActive() ):\r\n            grouping = self.records().grouped()\r\n            for groupName, records in sorted(grouping.items()):\r\n                self._loadThumbnailGroup(groupName, records)\r\n        else:\r\n            for record in self.records():\r\n                thumbnail = factory.thumbnail(record)\r\n                text      = factory.thumbnailText(record)\r\n                RecordListWidgetItem(thumbnail, text, record, widget)\r\n        widget.setUpdatesEnabled(True)\r\n        widget.blockSignals(False)",
    "docstring": "Refreshes the thumbnails view of the browser."
  },
  {
    "code": "def triggered(self):\n        if self.stop is not None and not self.stop_reached:\n            return False\n        if self.limit is not None and not self.limit_reached:\n            return False\n        return True",
    "docstring": "For a market order, True.\n        For a stop order, True IFF stop_reached.\n        For a limit order, True IFF limit_reached."
  },
  {
    "code": "def on_batch_begin(self, last_input, last_target, **kwargs):\n        \"accumulate samples and batches\"\n        self.acc_samples += last_input.shape[0]\n        self.acc_batches += 1",
    "docstring": "accumulate samples and batches"
  },
  {
    "code": "def format_ring_double_bond(mol):\n    mol.require(\"Topology\")\n    mol.require(\"ScaleAndCenter\")\n    for r in sorted(mol.rings, key=len, reverse=True):\n        vertices = [mol.atom(n).coords for n in r]\n        try:\n            if geometry.is_clockwise(vertices):\n                cpath = iterator.consecutive(itertools.cycle(r), 2)\n            else:\n                cpath = iterator.consecutive(itertools.cycle(reversed(r)), 2)\n        except ValueError:\n            continue\n        for _ in r:\n            u, v = next(cpath)\n            b = mol.bond(u, v)\n            if b.order == 2:\n                b.type = int((u > v) == b.is_lower_first)",
    "docstring": "Set double bonds around the ring."
  },
  {
    "code": "def add_task(self, task, func=None, **kwargs):\n        if not self.__tasks:\n            raise Exception(\"Tasks subparsers is disabled\")\n        if 'help' not in kwargs:\n            if func.__doc__:\n                kwargs['help'] = func.__doc__\n        task_parser = self.__tasks.add_parser(task, **kwargs)\n        if self.__add_vq:\n            self.add_vq(task_parser)\n        if func is not None:\n            task_parser.set_defaults(func=func)\n        return task_parser",
    "docstring": "Add a task parser"
  },
  {
    "code": "def cbpdn_setdict():\n    global mp_DSf\n    mp_Df[:] = sl.rfftn(mp_D_Y, mp_cri.Nv, mp_cri.axisN)\n    if mp_cri.Cd == 1:\n        mp_DSf[:] = np.conj(mp_Df) * mp_Sf\n    else:\n        mp_DSf[:] = sl.inner(np.conj(mp_Df[np.newaxis, ...]), mp_Sf,\n                              axis=mp_cri.axisC+1)",
    "docstring": "Set the dictionary for the cbpdn stage. There are no parameters\n    or return values because all inputs and outputs are from and to\n    global variables."
  },
  {
    "code": "def step_processing(self, warning=True):\n        if not self.__is_processing:\n            warning and LOGGER.warning(\n                \"!> {0} | Engine is not processing, 'step_processing' request has been ignored!\".format(\n                    self.__class__.__name__))\n            return False\n        LOGGER.debug(\"> Stepping processing operation!\")\n        self.Application_Progress_Status_processing.Processing_progressBar.setValue(\n            self.Application_Progress_Status_processing.Processing_progressBar.value() + 1)\n        self.process_events()\n        return True",
    "docstring": "Steps the processing operation progress indicator.\n\n        :param warning: Emit warning message.\n        :type warning: int\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def _grab_version(self):\n        original_version = self.vcs.version\n        logger.debug(\"Extracted version: %s\", original_version)\n        if original_version is None:\n            logger.critical('No version found.')\n            sys.exit(1)\n        suggestion = utils.cleanup_version(original_version)\n        new_version = utils.ask_version(\"Enter version\", default=suggestion)\n        if not new_version:\n            new_version = suggestion\n        self.data['original_version'] = original_version\n        self.data['new_version'] = new_version",
    "docstring": "Set the version to a non-development version."
  },
  {
    "code": "def set_payload(self,val):\n    self._options = self._options._replace(payload = val)",
    "docstring": "Set a payload for this object\n\n    :param val: payload to be stored\n    :type val: Anything that can be put in a list"
  },
  {
    "code": "def _check_kafka_disconnect(self):\n        for node_id in self.consumer._client._conns:\n            conn = self.consumer._client._conns[node_id]\n            if conn.state == ConnectionStates.DISCONNECTED or \\\n                    conn.state == ConnectionStates.DISCONNECTING:\n                self._spawn_kafka_connection_thread()\n                break",
    "docstring": "Checks the kafka connection is still valid"
  },
  {
    "code": "def generate_image(self, chars):\n        background = random_color(238, 255)\n        color = random_color(10, 200, random.randint(220, 255))\n        im = self.create_captcha_image(chars, color, background)\n        self.create_noise_dots(im, color)\n        self.create_noise_curve(im, color)\n        im = im.filter(ImageFilter.SMOOTH)\n        return im",
    "docstring": "Generate the image of the given characters.\n\n        :param chars: text to be generated."
  },
  {
    "code": "def do_help(self, args: argparse.Namespace) -> None:\n        if not args.command or args.verbose:\n            self._help_menu(args.verbose)\n        else:\n            func = self.cmd_func(args.command)\n            help_func = getattr(self, HELP_FUNC_PREFIX + args.command, None)\n            if func and hasattr(func, 'argparser'):\n                completer = AutoCompleter(getattr(func, 'argparser'), self)\n                tokens = [args.command] + args.subcommand\n                self.poutput(completer.format_help(tokens))\n            elif help_func is None and (func is None or not func.__doc__):\n                err_msg = self.help_error.format(args.command)\n                self.decolorized_write(sys.stderr, \"{}\\n\".format(err_msg))\n            else:\n                super().do_help(args.command)",
    "docstring": "List available commands or provide detailed help for a specific command"
  },
  {
    "code": "def _execute_hooks(self, element):\n        if self.hooks and self.finalize_hooks:\n            self.param.warning(\n                \"Supply either hooks or finalize_hooks not both, \"\n                \"using hooks and ignoring finalize_hooks.\")\n        hooks = self.hooks or self.finalize_hooks\n        for hook in hooks:\n            try:\n                hook(self, element)\n            except Exception as e:\n                self.param.warning(\"Plotting hook %r could not be \"\n                                   \"applied:\\n\\n %s\" % (hook, e))",
    "docstring": "Executes finalize hooks"
  },
  {
    "code": "def H6(self):\n        \"Sum average.\"\n        if not hasattr(self, '_H6'):\n            self._H6 = ((self.rlevels2 + 2) * self.p_xplusy).sum(1)\n        return self._H6",
    "docstring": "Sum average."
  },
  {
    "code": "def _parse_boolean(value):\n    if not value:\n        return False\n    try:\n        value = value.lower()\n        return value not in (\"none\", \"0\", \"false\", \"no\")\n    except AttributeError:\n        return True",
    "docstring": "Returns a boolean value corresponding to the given value.\n\n    :param value: Any value\n    :return: Its boolean value"
  },
  {
    "code": "def bulk_remove_entities(self, entities_and_kinds):\n        criteria = [\n            Q(entity=entity, sub_entity_kind=entity_kind)\n            for entity, entity_kind in entities_and_kinds\n        ]\n        criteria = reduce(lambda q1, q2: q1 | q2, criteria, Q())\n        EntityGroupMembership.objects.filter(\n            criteria, entity_group=self).delete()",
    "docstring": "Remove many entities and sub-entity groups to this EntityGroup.\n\n        :type entities_and_kinds: List of (Entity, EntityKind) pairs.\n        :param entities_and_kinds: A list of entity, entity-kind pairs\n            to remove from the group. In the pairs, the entity-kind\n            can be ``None``, to add a single entity, or some entity\n            kind to add all sub-entities of that kind."
  },
  {
    "code": "def parse_connection(self, global_params, region, connection):\n        connection['id'] = connection.pop('connectionId')\n        connection['name'] = connection.pop('connectionName')\n        self.connections[connection['id']] = connection",
    "docstring": "Parse a single connection and fetch additional attributes\n\n        :param global_params:           Parameters shared for all regions\n        :param region:                  Name of the AWS region\n        :param connection_url:               URL of the AWS connection"
  },
  {
    "code": "def create_vlan(self, id_vlan):\n        vlan_map = dict()\n        vlan_map['vlan_id'] = id_vlan\n        code, xml = self.submit({'vlan': vlan_map}, 'PUT', 'vlan/create/')\n        return self.response(code, xml)",
    "docstring": "Set column 'ativada = 1'.\n\n        :param id_vlan: VLAN identifier.\n\n        :return: None"
  },
  {
    "code": "def AddUser(self, uid, username, active):\n    user_path = '/org/freedesktop/login1/user/%i' % uid\n    if user_path in mockobject.objects:\n        raise dbus.exceptions.DBusException('User %i already exists' % uid,\n                                            name=MOCK_IFACE + '.UserExists')\n    self.AddObject(user_path,\n                   'org.freedesktop.login1.User',\n                   {\n                       'Sessions': dbus.Array([], signature='(so)'),\n                       'IdleHint': False,\n                       'DefaultControlGroup': 'systemd:/user/' + username,\n                       'Name': username,\n                       'RuntimePath': '/run/user/%i' % uid,\n                       'Service': '',\n                       'State': (active and 'active' or 'online'),\n                       'Display': ('', dbus.ObjectPath('/')),\n                       'UID': dbus.UInt32(uid),\n                       'GID': dbus.UInt32(uid),\n                       'IdleSinceHint': dbus.UInt64(0),\n                       'IdleSinceHintMonotonic': dbus.UInt64(0),\n                       'Timestamp': dbus.UInt64(42),\n                       'TimestampMonotonic': dbus.UInt64(42),\n                   },\n                   [\n                       ('Kill', 's', '', ''),\n                       ('Terminate', '', '', ''),\n                   ])\n    return user_path",
    "docstring": "Convenience method to add a user.\n\n    Return the object path of the new user."
  },
  {
    "code": "def create_project_config_path(\n    path, mode=0o777, parents=False, exist_ok=False\n):\n    project_path = Path(path).absolute().joinpath(RENKU_HOME)\n    project_path.mkdir(mode=mode, parents=parents, exist_ok=exist_ok)\n    return str(project_path)",
    "docstring": "Create new project configuration folder."
  },
  {
    "code": "def current(cls, with_exception=True):\n        if with_exception and len(cls.stack) == 0:\n            raise NoContext()\n        return cls.stack.top()",
    "docstring": "Returns the current database context."
  },
  {
    "code": "def set_data(self, data):\n        for name in self._fields:\n            setattr(self, name, data.get(name))\n        return self",
    "docstring": "Fills form with data\n\n        Args:\n            data (dict): Data to assign form fields.\n\n        Returns:\n            Self. Form object."
  },
  {
    "code": "def bind_name(self, name):\n        if self.name:\n            raise errors.Error('Already bound \"{0}\" with name \"{1}\" could not '\n                               'be rebound'.format(self, self.name))\n        self.name = name\n        self.storage_name = ''.join(('_', self.name))\n        return self",
    "docstring": "Bind field to its name in model class."
  },
  {
    "code": "def create_command(\n    principal, permissions, endpoint_plus_path, notify_email, notify_message\n):\n    if not principal:\n        raise click.UsageError(\"A security principal is required for this command\")\n    endpoint_id, path = endpoint_plus_path\n    principal_type, principal_val = principal\n    client = get_client()\n    if principal_type == \"identity\":\n        principal_val = maybe_lookup_identity_id(principal_val)\n        if not principal_val:\n            raise click.UsageError(\n                \"Identity does not exist. \"\n                \"Use --provision-identity to auto-provision an identity.\"\n            )\n    elif principal_type == \"provision-identity\":\n        principal_val = maybe_lookup_identity_id(principal_val, provision=True)\n        principal_type = \"identity\"\n    if not notify_email:\n        notify_message = None\n    rule_data = assemble_generic_doc(\n        \"access\",\n        permissions=permissions,\n        principal=principal_val,\n        principal_type=principal_type,\n        path=path,\n        notify_email=notify_email,\n        notify_message=notify_message,\n    )\n    res = client.add_endpoint_acl_rule(endpoint_id, rule_data)\n    formatted_print(\n        res,\n        text_format=FORMAT_TEXT_RECORD,\n        fields=[(\"Message\", \"message\"), (\"Rule ID\", \"access_id\")],\n    )",
    "docstring": "Executor for `globus endpoint permission create`"
  },
  {
    "code": "def on_epoch_end(self, **kwargs):\n        \"step the rest of the accumulated grads if not perfectly divisible\"\n        for p in (self.learn.model.parameters()):\n                if p.requires_grad: p.grad.div_(self.acc_samples)\n        if not self.drop_last: self.learn.opt.step()\n        self.learn.opt.zero_grad()",
    "docstring": "step the rest of the accumulated grads if not perfectly divisible"
  },
  {
    "code": "def _get_expiration_date(cert):\n    cert_obj = _read_cert(cert)\n    if cert_obj is None:\n        raise CommandExecutionError(\n            'Failed to read cert from {0}, see log for details'.format(cert)\n        )\n    return datetime.strptime(\n        salt.utils.stringutils.to_str(cert_obj.get_notAfter()),\n        four_digit_year_fmt\n    )",
    "docstring": "Returns a datetime.datetime object"
  },
  {
    "code": "def _append_expectation(self, expectation_config):\n        expectation_type = expectation_config['expectation_type']\n        json.dumps(expectation_config)\n        if 'column' in expectation_config['kwargs']:\n            column = expectation_config['kwargs']['column']\n            self._expectations_config.expectations = [f for f in filter(\n                lambda exp: (exp['expectation_type'] != expectation_type) or (\n                    'column' in exp['kwargs'] and exp['kwargs']['column'] != column),\n                self._expectations_config.expectations\n            )]\n        else:\n            self._expectations_config.expectations = [f for f in filter(\n                lambda exp: exp['expectation_type'] != expectation_type,\n                self._expectations_config.expectations\n            )]\n        self._expectations_config.expectations.append(expectation_config)",
    "docstring": "Appends an expectation to `DataAsset._expectations_config` and drops existing expectations of the same type.\n\n           If `expectation_config` is a column expectation, this drops existing expectations that are specific to \\\n           that column and only if it is the same expectation type as `expectation_config`. Otherwise, if it's not a \\\n           column expectation, this drops existing expectations of the same type as `expectation config`. \\\n           After expectations of the same type are dropped, `expectation_config` is appended to `DataAsset._expectations_config`.\n\n           Args:\n               expectation_config (json): \\\n                   The JSON-serializable expectation to be added to the DataAsset expectations in `_expectations_config`.\n\n           Notes:\n               May raise future errors once json-serializable tests are implemented to check for correct arg formatting"
  },
  {
    "code": "def check_species_object(species_name_or_object):\n    if isinstance(species_name_or_object, Species):\n        return species_name_or_object\n    elif isinstance(species_name_or_object, str):\n        return find_species_by_name(species_name_or_object)\n    else:\n        raise ValueError(\"Unexpected type for species: %s : %s\" % (\n            species_name_or_object, type(species_name_or_object)))",
    "docstring": "Helper for validating user supplied species names or objects."
  },
  {
    "code": "def use_internal_state(self):\n        old_state = random.getstate()\n        random.setstate(self._random_state)\n        yield\n        self._random_state = random.getstate()\n        random.setstate(old_state)",
    "docstring": "Use a specific RNG state."
  },
  {
    "code": "def get_property(self, prop):\n        prop = prop.split('.')\n        root = self\n        for p in prop:\n            if p in root:\n                root = root[p]\n            else:\n                return None\n        return root",
    "docstring": "Access nested value using dot separated keys\n\n        Args:\n            prop (:obj:`str`): Property in the form of dot separated keys\n\n        Returns:\n            Property value if exists, else `None`"
  },
  {
    "code": "def create_paired_list(value):\n    if isinstance(value, list):\n        value = \",\".join(value)\n    array = re.split('\\D+', value)\n    if len(array) % 2 == 0:\n        new_array = [list(array[i:i + 2]) for i in range(0, len(array), 2)]\n        return new_array\n    else:\n        raise ValueError('The string should include pairs and be formated. '\n                         'The format must be 003,003,004,004 (commas with '\n                         'no space)')",
    "docstring": "Create a list of paired items from a string.\n\n    :param value:\n        the format must be 003,003,004,004 (commas with no space)\n    :type value:\n        String\n\n    :returns:\n        List\n\n    :example:\n        >>> create_paired_list('003,003,004,004')\n        [['003','003'], ['004', '004']]"
  },
  {
    "code": "def rebuild_method(self, prepared_request, response):\n        method = prepared_request.method\n        if response.status_code == codes.see_other and method != 'HEAD':\n            method = 'GET'\n        if response.status_code == codes.found and method != 'HEAD':\n            method = 'GET'\n        if response.status_code == codes.moved and method == 'POST':\n            method = 'GET'\n        prepared_request.method = method",
    "docstring": "When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior."
  },
  {
    "code": "def valid_name(name):\n    \"Validate a cookie name string\"\n    if isinstance(name, bytes):\n        name = name.decode('ascii')\n    if not Definitions.COOKIE_NAME_RE.match(name):\n        return False\n    if name[0] == \"$\":\n        return False\n    return True",
    "docstring": "Validate a cookie name string"
  },
  {
    "code": "def answer(self):\n        if isinstance(self.validator, list):\n            return self.validator[0].choice()\n        return self.validator.choice()",
    "docstring": "Return the answer for the question from the validator.\n\n            This will ultimately only be called on the first validator if\n            multiple validators have been added."
  },
  {
    "code": "def csv(args):\n    from xlrd import open_workbook\n    p = OptionParser(csv.__doc__)\n    p.set_sep(sep=',')\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(not p.print_help())\n    excelfile, = args\n    sep = opts.sep\n    csvfile = excelfile.rsplit(\".\", 1)[0] + \".csv\"\n    wb = open_workbook(excelfile)\n    fw = open(csvfile, \"w\")\n    for s in wb.sheets():\n        print('Sheet:',s.name, file=sys.stderr)\n        for row in range(s.nrows):\n            values = []\n            for col in range(s.ncols):\n                values.append(s.cell(row, col).value)\n            print(sep.join(str(x) for x in values), file=fw)",
    "docstring": "%prog csv excelfile\n\n    Convert EXCEL to csv file."
  },
  {
    "code": "def get_parent_books(self, book_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.get_parent_catalogs(catalog_id=book_id)\n        return BookLookupSession(\n            self._proxy,\n            self._runtime).get_books_by_ids(\n                list(self.get_parent_book_ids(book_id)))",
    "docstring": "Gets the parent books of the given ``id``.\n\n        arg:    book_id (osid.id.Id): the ``Id`` of the ``Book`` to\n                query\n        return: (osid.commenting.BookList) - the parent books of the\n                ``id``\n        raise:  NotFound - a ``Book`` identified by ``Id is`` not found\n        raise:  NullArgument - ``book_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_tag_list(resource_tag_dict):\n    tag_list = []\n    if resource_tag_dict is None:\n        return tag_list\n    for tag_key, tag_value in resource_tag_dict.items():\n        tag = {_KEY: tag_key, _VALUE: tag_value if tag_value else \"\"}\n        tag_list.append(tag)\n    return tag_list",
    "docstring": "Transforms the SAM defined Tags into the form CloudFormation is expecting.\n\n    SAM Example:\n        ```\n        ...\n        Tags:\n          TagKey: TagValue\n        ```\n\n\n    CloudFormation equivalent:\n          - Key: TagKey\n            Value: TagValue\n        ```\n\n    :param resource_tag_dict: Customer defined dictionary (SAM Example from above)\n    :return: List of Tag Dictionaries (CloudFormation Equivalent from above)"
  },
  {
    "code": "def summary(self, raw):\n        taxonomies = []\n        level = \"info\"\n        namespace = \"Patrowl\"\n        if self.service == 'getreport':\n            if 'risk_level' in raw and raw['risk_level']:\n                risk_level = raw['risk_level']\n                if risk_level['grade'] in [\"A\", \"B\"]:\n                    level = \"safe\"\n                else:\n                    level = \"suspicious\"\n                taxonomies.append(self.build_taxonomy(level, namespace, \"Grade\", risk_level['grade']))\n                if risk_level['high'] > 0:\n                    level = \"malicious\"\n                elif risk_level['medium'] > 0 or risk_level['low'] > 0:\n                    level = \"suspicious\"\n                else:\n                    level = \"info\"\n                taxonomies.append(self.build_taxonomy(\n                    level, namespace, \"Findings\", \"{}/{}/{}/{}\".format(\n                        risk_level['high'],\n                        risk_level['medium'],\n                        risk_level['low'],\n                        risk_level['info']\n                    )))\n        return {\"taxonomies\": taxonomies}",
    "docstring": "Parse, format and return scan summary."
  },
  {
    "code": "def _any_would_run(func, filenames, *args):\n    if os.environ.get(\"_POLYSQUARE_GENERIC_FILE_LINTER_NO_STAMPING\", None):\n        return True\n    for filename in filenames:\n        stamp_args, stamp_kwargs = _run_lint_on_file_stamped_args(filename,\n                                                                  *args,\n                                                                  **{})\n        dependency = jobstamp.out_of_date(func,\n                                          *stamp_args,\n                                          **stamp_kwargs)\n        if dependency:\n            return True\n    return False",
    "docstring": "True if a linter function would be called on any of filenames."
  },
  {
    "code": "def to_element(self, root_name=None):\n        if not root_name:\n            root_name = self.nodename\n        elem = ElementTreeBuilder.Element(root_name)\n        for attrname in self.serializable_attributes():\n            try:\n                value = self.__dict__[attrname]\n            except KeyError:\n                continue\n            if attrname in self.xml_attribute_attributes:\n                elem.attrib[attrname] = six.text_type(value)\n            else:\n                sub_elem = self.element_for_value(attrname, value)\n                elem.append(sub_elem)\n        return elem",
    "docstring": "Serialize this `Resource` instance to an XML element."
  },
  {
    "code": "def clean_tenant_url(url_string):\n    if hasattr(settings, 'PUBLIC_SCHEMA_URLCONF'):\n        if (settings.PUBLIC_SCHEMA_URLCONF and\n                url_string.startswith(settings.PUBLIC_SCHEMA_URLCONF)):\n            url_string = url_string[len(settings.PUBLIC_SCHEMA_URLCONF):]\n    return url_string",
    "docstring": "Removes the TENANT_TOKEN from a particular string"
  },
  {
    "code": "def update_object(objref, data, **api_opts):\n    if '__opts__' in globals() and __opts__['test']:\n        return {'Test': 'Would attempt to update object: {0}'.format(objref)}\n    infoblox = _get_infoblox(**api_opts)\n    return infoblox.update_object(objref, data)",
    "docstring": "Update raw infoblox object. This is a low level api call.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-call infoblox.update_object objref=[ref_of_object] data={}"
  },
  {
    "code": "def _get_documents(self):\n        documents = self.tree.execute(\"$.documents\")\n        for doc in documents:\n            sentences = {s['@id']: s['text'] for s in doc.get('sentences', [])}\n            self.document_dict[doc['@id']] = {'sentences': sentences,\n                                              'location': doc['location']}",
    "docstring": "Populate sentences attribute with a dict keyed by document id."
  },
  {
    "code": "def get_user(self, id=None, name=None, email=None):\n        log.info(\"Picking user: %s (%s) (%s)\" % (name, email, id))\n        from qubell.api.private.user import User\n        if email:\n            user = User.get(self._router, organization=self, email=email)\n        else:\n            user = self.users[id or name]\n        return user",
    "docstring": "Get user object by email or id."
  },
  {
    "code": "def add_parser(self, name, func):\n        self.__parser_map__[name] = _func2method(func, method_name=name)\n        return None",
    "docstring": "Register a new parser method with the name ``name``. ``func`` must\n        receive the input value for an environment variable."
  },
  {
    "code": "def generate_heightmap(self, buffer=False, as_array=False):\n        non_solids = [0, 8, 9, 10, 11, 38, 37, 32, 31]\n        if buffer:\n            return BytesIO(pack(\">i\", 256)+self.generate_heightmap())\n        else:\n            bytes = []\n            for z in range(16):\n                for x in range(16):\n                    for y in range(127, -1, -1):\n                        offset = y + z*128 + x*128*16\n                        if (self.blocksList[offset] not in non_solids or y == 0):\n                            bytes.append(y+1)\n                            break\n            if (as_array):\n                return bytes\n            else:\n                return array.array('B', bytes).tostring()",
    "docstring": "Return a heightmap, representing the highest solid blocks in this chunk."
  },
  {
    "code": "def _format_csv(content, delimiter):\n    reader = csv_reader(StringIO(content), delimiter=builtin_str(delimiter))\n    rows = [row for row in reader]\n    max_widths = [max(map(len, column)) for column in zip(*rows)]\n    lines = [\n        \" \".join(\n            \"{entry:{width}}\".format(entry=entry, width=width + 2)\n            for entry, width in zip(row, max_widths)\n        )\n        for row in rows\n    ]\n    return \"\\n\".join(lines)",
    "docstring": "Format delimited text to have same column width.\n\n    Args:\n        content (str): The content of a metric.\n        delimiter (str): Value separator\n\n    Returns:\n        str: Formatted content.\n\n    Example:\n\n        >>> content = (\n            \"value_mse,deviation_mse,data_set\\n\"\n            \"0.421601,0.173461,train\\n\"\n            \"0.67528,0.289545,testing\\n\"\n            \"0.671502,0.297848,validation\\n\"\n        )\n        >>> _format_csv(content, \",\")\n\n        \"value_mse  deviation_mse   data_set\\n\"\n        \"0.421601   0.173461        train\\n\"\n        \"0.67528    0.289545        testing\\n\"\n        \"0.671502   0.297848        validation\\n\""
  },
  {
    "code": "def get_energy_buckingham(structure, gulp_cmd='gulp',\n                          keywords=('optimise', 'conp', 'qok'),\n                          valence_dict=None):\n    gio = GulpIO()\n    gc = GulpCaller(gulp_cmd)\n    gin = gio.buckingham_input(\n        structure, keywords, valence_dict=valence_dict\n    )\n    gout = gc.run(gin)\n    return gio.get_energy(gout)",
    "docstring": "Compute the energy of a structure using Buckingham potential.\n\n    Args:\n        structure: pymatgen.core.structure.Structure\n        gulp_cmd: GULP command if not in standard place\n        keywords: GULP first line keywords\n        valence_dict: {El: valence}. Needed if the structure is not charge\n            neutral."
  },
  {
    "code": "def get_sentence(self, offset: int) -> BioCSentence or None:\n        for sentence in self.sentences:\n            if sentence.offset == offset:\n                return sentence\n        return None",
    "docstring": "Gets sentence with specified offset\n\n        Args:\n            offset: sentence offset\n\n        Return:\n            the sentence with specified offset"
  },
  {
    "code": "def read(self, n):\n    while len(self.buf) < n:\n      chunk = self.f.recv(4096)\n      if not chunk:\n        raise EndOfStreamError()\n      self.buf += chunk\n    res, self.buf = self.buf[:n], self.buf[n:]\n    return res",
    "docstring": "Consume `n` characters from the stream."
  },
  {
    "code": "def maximum(lhs, rhs):\n    return _ufunc_helper(\n        lhs,\n        rhs,\n        op.broadcast_maximum,\n        lambda x, y: x if x > y else y,\n        _internal._maximum_scalar,\n        None)",
    "docstring": "Returns element-wise maximum of the input arrays with broadcasting.\n\n    Equivalent to ``mx.nd.broadcast_maximum(lhs, rhs)``.\n\n    .. note::\n\n       If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n       then the arrays are broadcastable to a common shape.\n\n    Parameters\n    ----------\n    lhs : scalar or mxnet.ndarray.array\n        First array to be compared.\n    rhs : scalar or mxnet.ndarray.array\n         Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n        broadcastable to a common shape.\n\n    Returns\n    -------\n    NDArray\n        The element-wise maximum of the input arrays.\n\n    Examples\n    --------\n    >>> x = mx.nd.ones((2,3))\n    >>> y = mx.nd.arange(2).reshape((2,1))\n    >>> z = mx.nd.arange(2).reshape((1,2))\n    >>> x.asnumpy()\n    array([[ 1.,  1.,  1.],\n           [ 1.,  1.,  1.]], dtype=float32)\n    >>> y.asnumpy()\n    array([[ 0.],\n           [ 1.]], dtype=float32)\n    >>> z.asnumpy()\n    array([[ 0.,  1.]], dtype=float32)\n    >>> mx.nd.maximum(x, 2).asnumpy()\n    array([[ 2.,  2.,  2.],\n           [ 2.,  2.,  2.]], dtype=float32)\n    >>> mx.nd.maximum(x, y).asnumpy()\n    array([[ 1.,  1.,  1.],\n           [ 1.,  1.,  1.]], dtype=float32)\n    >>> mx.nd.maximum(y, z).asnumpy()\n    array([[ 0.,  1.],\n           [ 1.,  1.]], dtype=float32)"
  },
  {
    "code": "def docs(ctx, output='html', rebuild=False, show=True, verbose=True):\n    sphinx_build = ctx.run(\n        'sphinx-build -b {output} {all} {verbose} docs docs/_build'.format(\n            output=output,\n            all='-a -E' if rebuild else '',\n            verbose='-v' if verbose else ''))\n    if not sphinx_build.ok:\n        fatal(\"Failed to build the docs\", cause=sphinx_build)\n    if show:\n        path = os.path.join(DOCS_OUTPUT_DIR, 'index.html')\n        if sys.platform == 'darwin':\n            path = 'file://%s' % os.path.abspath(path)\n        webbrowser.open_new_tab(path)",
    "docstring": "Build the docs and show them in default web browser."
  },
  {
    "code": "def get_column(self, name):\n        import ibis.expr.operations as ops\n        ref = ops.TableColumn(name, self)\n        return ref.to_expr()",
    "docstring": "Get a reference to a single column from the table\n\n        Returns\n        -------\n        column : array expression"
  },
  {
    "code": "def _log(self):\n        self._log_platform()\n        self._log_app_data()\n        self._log_python_version()\n        self._log_tcex_version()\n        self._log_tc_proxy()",
    "docstring": "Send System and App data to logs."
  },
  {
    "code": "def top_segment_proportions(mtx, ns):\n    if not (max(ns) <= mtx.shape[1] and min(ns) > 0):\n        raise IndexError(\"Positions outside range of features.\")\n    if issparse(mtx):\n        if not isspmatrix_csr(mtx):\n            mtx = csr_matrix(mtx)\n        return top_segment_proportions_sparse_csr(mtx.data, mtx.indptr,\n                                                  np.array(ns, dtype=np.int))\n    else:\n        return top_segment_proportions_dense(mtx, ns)",
    "docstring": "Calculates total percentage of counts in top ns genes.\n\n    Parameters\n    ----------\n    mtx : `Union[np.array, sparse.spmatrix]`\n        Matrix, where each row is a sample, each column a feature.\n    ns : `Container[Int]`\n        Positions to calculate cumulative proportion at. Values are considered\n        1-indexed, e.g. `ns=[50]` will calculate cumulative proportion up to\n        the 50th most expressed gene."
  },
  {
    "code": "def get_objective_banks_by_objective(self, objective_id):\n        mgr = self._get_provider_manager('LEARNING', local=True)\n        lookup_session = mgr.get_objective_bank_lookup_session(proxy=self._proxy)\n        return lookup_session.get_objective_banks_by_ids(\n            self.get_objective_bank_ids_by_objective(objective_id))",
    "docstring": "Gets the list of ``ObjectiveBanks`` mapped to an ``Objective``.\n\n        arg:    objective_id (osid.id.Id): ``Id`` of an ``Objective``\n        return: (osid.learning.ObjectiveBankList) - list of objective\n                banks\n        raise:  NotFound - ``objective_id`` is not found\n        raise:  NullArgument - ``objective_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def convert_iso_stamp(t, tz=None):\n    if t is None:\n        return None\n    dt = dateutil.parser.parse(t)\n    if tz is not None:\n        timezone = pytz.timezone(tz)\n        if dt.tzinfo is None:\n            dt = timezone.localize(dt)\n    return dt",
    "docstring": "Convert a string in ISO8601 form into a Datetime object.  This is mainly\n    used for converting timestamps sent from the TempoDB API, which are\n    assumed to be correct.\n\n    :param string t: the timestamp to convert\n    :rtype: Datetime object"
  },
  {
    "code": "def _ProcessHistogram(self, tag, wall_time, step, histo):\n    histo = self._ConvertHistogramProtoToTuple(histo)\n    histo_ev = HistogramEvent(wall_time, step, histo)\n    self.histograms.AddItem(tag, histo_ev)\n    self.compressed_histograms.AddItem(tag, histo_ev, self._CompressHistogram)",
    "docstring": "Processes a proto histogram by adding it to accumulated state."
  },
  {
    "code": "def _read_payload(socket, payload_size):\n    remaining = payload_size\n    while remaining > 0:\n        data = read(socket, remaining)\n        if data is None:\n            continue\n        if len(data) == 0:\n            break\n        remaining -= len(data)\n        yield data",
    "docstring": "From the given socket, reads and yields payload of the given size. With sockets, we don't receive all data at\n    once. Therefore this method will yield each time we read some data from the socket until the payload_size has\n    reached or socket has no more data.\n\n    Parameters\n    ----------\n    socket\n        Socket to read from\n\n    payload_size : int\n        Size of the payload to read. Exactly these many bytes are read from the socket before stopping the yield.\n\n    Yields\n    -------\n    int\n        Type of the stream (1 => stdout, 2 => stderr)\n    str\n        Data in the stream"
  },
  {
    "code": "def hash(self):\n        hash_request = etcdrpc.HashRequest()\n        return self.maintenancestub.Hash(hash_request).hash",
    "docstring": "Return the hash of the local KV state.\n\n        :returns: kv state hash\n        :rtype: int"
  },
  {
    "code": "def _rmv_pkg(self, package):\n        removes = []\n        if GetFromInstalled(package).name() and package not in self.skip:\n            ver = GetFromInstalled(package).version()\n            removes.append(package + ver)\n            self._removepkg(package)\n        return removes",
    "docstring": "Remove one signle package"
  },
  {
    "code": "def runm():\n    signal.signal(signal.SIGINT, signal_handler)\n    count = int(sys.argv.pop(1))\n    processes = [Process(target=run, args=()) for x in range(count)]\n    try:\n        for p in processes:\n            p.start()\n    except KeyError:\n        pass\n    finally:\n        for p in processes:\n            p.join()",
    "docstring": "This is super minimal and pretty hacky, but it counts as a first pass."
  },
  {
    "code": "def base64url_to_long(data):\n    _data = as_bytes(data)\n    _d = base64.urlsafe_b64decode(_data + b'==')\n    if [e for e in [b'+', b'/', b'='] if e in _data]:\n        raise ValueError(\"Not base64url encoded\")\n    return intarr2long(struct.unpack('%sB' % len(_d), _d))",
    "docstring": "Stricter then base64_to_long since it really checks that it's\n    base64url encoded\n\n    :param data: The base64 string\n    :return:"
  },
  {
    "code": "def get_instance_route53_names(self, instance):\n        instance_attributes = [ 'public_dns_name', 'private_dns_name',\n                                'ip_address', 'private_ip_address' ]\n        name_list = set()\n        for attrib in instance_attributes:\n            try:\n                value = getattr(instance, attrib)\n            except AttributeError:\n                continue\n            if value in self.route53_records:\n                name_list.update(self.route53_records[value])\n        return list(name_list)",
    "docstring": "Check if an instance is referenced in the records we have from\n        Route53. If it is, return the list of domain names pointing to said\n        instance. If nothing points to it, return an empty list."
  },
  {
    "code": "def get_list_of_applications():\n    apps = mod_prg.Programs('Applications', 'C:\\\\apps')\n    fl = mod_fl.FileList(['C:\\\\apps'], ['*.exe'], [\"\\\\bk\\\\\"])\n    for f in fl.get_list():\n        apps.add(f, 'autogenerated list')\n    apps.list()\n    apps.save()",
    "docstring": "Get list of applications"
  },
  {
    "code": "def _updateConstructorAndMembers(self):\n        syntheticMetaData = self._syntheticMetaData()\n        constructor = self._constructorFactory.makeConstructor(syntheticMetaData.originalConstructor(),\n                                                               syntheticMetaData.syntheticMemberList(),\n                                                               syntheticMetaData.doesConsumeArguments())\n        self._class.__init__ = constructor\n        for syntheticMember in syntheticMetaData.syntheticMemberList():\n            syntheticMember.apply(self._class,\n                                  syntheticMetaData.originalMemberNameList(),\n                                  syntheticMetaData.namingConvention())\n        if syntheticMetaData.hasEqualityGeneration():\n            eq = self._comparisonFactory.makeEqualFunction(syntheticMetaData.originalEqualFunction(),\n                                                           syntheticMetaData.syntheticMemberList())\n            ne = self._comparisonFactory.makeNotEqualFunction(syntheticMetaData.originalNotEqualFunction(),\n                                                              syntheticMetaData.syntheticMemberList())\n            hashFunc = self._comparisonFactory.makeHashFunction(syntheticMetaData.originalHashFunction(),\n                                                                syntheticMetaData.syntheticMemberList())\n            self._class.__eq__ = eq\n            self._class.__ne__ = ne\n            self._class.__hash__ = hashFunc",
    "docstring": "We overwrite constructor and accessors every time because the constructor might have to consume all\nmembers even if their decorator is below the \"synthesizeConstructor\" decorator and it also might need to update\nthe getters and setters because the naming convention has changed."
  },
  {
    "code": "def get_tag_html(tag_id):\n    tag_data = get_lazy_tag_data(tag_id)\n    tag = tag_data['tag']\n    args = tag_data['args']\n    kwargs = tag_data['kwargs']\n    lib, tag_name = get_lib_and_tag_name(tag)\n    args_str = ''\n    if args:\n        for arg in args:\n            if isinstance(arg, six.string_types):\n                args_str += \"'{0}' \".format(arg)\n            else:\n                args_str += \"{0} \".format(arg)\n    kwargs_str = ''\n    if kwargs:\n        for name, value in kwargs.items():\n            if isinstance(value, six.string_types):\n                kwargs_str += \"{0}='{1}' \".format(name, value)\n            else:\n                kwargs_str += \"{0}={1} \".format(name, value)\n    html = '{{% load {lib} %}}{{% {tag_name} {args}{kwargs}%}}'.format(\n        lib=lib, tag_name=tag_name, args=args_str, kwargs=kwargs_str)\n    return html",
    "docstring": "Returns the Django HTML to load the tag library and render the tag.\n\n    Args:\n        tag_id (str): The tag id for the to return the HTML for."
  },
  {
    "code": "def _get_complex_agents(self, complex_id):\n        agents = []\n        components = self._recursively_lookup_complex(complex_id)\n        for c in components:\n            db_refs = {}\n            name = uniprot_client.get_gene_name(c)\n            if name is None:\n                db_refs['SIGNOR'] = c\n            else:\n                db_refs['UP'] = c\n                hgnc_id = hgnc_client.get_hgnc_id(name)\n                if hgnc_id:\n                    db_refs['HGNC'] = hgnc_id\n            famplex_key = ('SIGNOR', c)\n            if famplex_key in famplex_map:\n                db_refs['FPLX'] = famplex_map[famplex_key]\n                if not name:\n                    name = db_refs['FPLX']\n            elif not name:\n                logger.info('Have neither a Uniprot nor Famplex grounding ' + \\\n                            'for ' + c)\n                if not name:\n                    name = db_refs['SIGNOR']\n            assert(name is not None)\n            agents.append(Agent(name, db_refs=db_refs))\n        return agents",
    "docstring": "Returns a list of agents corresponding to each of the constituents\n        in a SIGNOR complex."
  },
  {
    "code": "def add_properties(self, properties):\n        if isinstance(properties, dict):\n            self._properties.update(properties)",
    "docstring": "Updates the framework properties dictionary\n\n        :param properties: New framework properties to add"
  },
  {
    "code": "def draw_chimera_embedding(G, *args, **kwargs):\n    draw_embedding(G, chimera_layout(G), *args, **kwargs)",
    "docstring": "Draws an embedding onto the chimera graph G, according to layout.\n\n    If interaction_edges is not None, then only display the couplers in that\n    list.  If embedded_graph is not None, the only display the couplers between\n    chains with intended couplings according to embedded_graph.\n\n    Parameters\n    ----------\n    G : NetworkX graph\n        Should be a Chimera graph or a subgraph of a Chimera graph.\n\n    emb : dict\n        A dict of chains associated with each node in G.  Should be\n        of the form {node: chain, ...}.  Chains should be iterables\n        of qubit labels (qubits are nodes in G).\n\n    embedded_graph : NetworkX graph (optional, default None)\n        A graph which contains all keys of emb as nodes.  If specified,\n        edges of G will be considered interactions if and only if they\n        exist between two chains of emb if their keys are connected by\n        an edge in embedded_graph\n\n    interaction_edges : list (optional, default None)\n        A list of edges which will be used as interactions.\n\n    show_labels: boolean (optional, default False)\n        If show_labels is True, then each chain in emb is labelled with its key.\n\n    chain_color : dict (optional, default None)\n        A dict of colors associated with each key in emb.  Should be\n        of the form {node: rgba_color, ...}.  Colors should be length-4\n        tuples of floats between 0 and 1 inclusive. If chain_color is None,\n        each chain will be assigned a different color.\n\n    unused_color : tuple (optional, default (0.9,0.9,0.9,1.0))\n        The color to use for nodes and edges of G which are not involved\n        in chains, and edges which are neither chain edges nor interactions.\n        If unused_color is None, these nodes and edges will not be shown at all.\n\n    kwargs : optional keywords\n       See networkx.draw_networkx() for a description of optional keywords,\n       with the exception of the `pos` parameter which is not used by this\n       function. If `linear_biases` or `quadratic_biases` are provided,\n       any provided `node_color` or `edge_color` arguments are ignored."
  },
  {
    "code": "def convert_npdist(self, node):\n        with context(self.fname, node):\n            npdist = []\n            for np in node.nodalPlaneDist:\n                prob, strike, dip, rake = (\n                    np['probability'], np['strike'], np['dip'], np['rake'])\n                npdist.append((prob, geo.NodalPlane(strike, dip, rake)))\n            if not self.spinning_floating:\n                npdist = [(1, npdist[0][1])]\n            return pmf.PMF(npdist)",
    "docstring": "Convert the given node into a Nodal Plane Distribution.\n\n        :param node: a nodalPlaneDist node\n        :returns: a :class:`openquake.hazardlib.geo.NodalPlane` instance"
  },
  {
    "code": "def shared_databases(self):\n        endpoint = '/'.join((\n            self.server_url, '_api', 'v2', 'user', 'shared_databases'))\n        resp = self.r_session.get(endpoint)\n        resp.raise_for_status()\n        data = response_to_json_dict(resp)\n        return data.get('shared_databases', [])",
    "docstring": "Retrieves a list containing the names of databases shared\n        with this account.\n\n        :returns: List of database names"
  },
  {
    "code": "def _getBlobFromURL(cls, url, exists=False):\n        bucketName = url.netloc\n        fileName = url.path\n        if fileName.startswith('/'):\n            fileName = fileName[1:]\n        storageClient = storage.Client()\n        bucket = storageClient.get_bucket(bucketName)\n        blob = bucket.blob(bytes(fileName))\n        if exists:\n            if not blob.exists():\n                raise NoSuchFileException\n            blob.reload()\n        return blob",
    "docstring": "Gets the blob specified by the url.\n\n        caution: makes no api request. blob may not ACTUALLY exist\n\n        :param urlparse.ParseResult url: the URL\n\n        :param bool exists: if True, then syncs local blob object with cloud\n        and raises exceptions if it doesn't exist remotely\n\n        :return: the blob requested\n        :rtype: :class:`~google.cloud.storage.blob.Blob`"
  },
  {
    "code": "def clean(self):\n        data = super(PublishingAdminForm, self).clean()\n        cleaned_data = self.cleaned_data\n        instance = self.instance\n        unique_fields_set = instance.get_unique_together()\n        if not unique_fields_set:\n            return data\n        for unique_fields in unique_fields_set:\n            unique_filter = {}\n            for unique_field in unique_fields:\n                field = instance.get_field(unique_field)\n                if field.editable and unique_field in cleaned_data:\n                    unique_filter[unique_field] = cleaned_data[unique_field]\n                else:\n                    unique_filter[unique_field] = \\\n                        getattr(instance, unique_field)\n            existing_instances = type(instance).objects \\\n                                               .filter(**unique_filter) \\\n                                               .exclude(pk=instance.pk)\n            if instance.publishing_linked:\n                existing_instances = existing_instances.exclude(\n                    pk=instance.publishing_linked.pk)\n            if existing_instances:\n                for unique_field in unique_fields:\n                    self._errors[unique_field] = self.error_class(\n                        [_('This value must be unique.')])\n        return data",
    "docstring": "Additional clean data checks for path and keys.\n\n        These are not cleaned in their respective methods e.g.\n        `clean_slug` as they depend upon other field data.\n\n        :return: Cleaned data."
  },
  {
    "code": "def block(seed):\n    num = SAMPLE_RATE * BLOCK_SIZE\n    rng = RandomState(seed % 2**32)\n    variance = SAMPLE_RATE / 2\n    return rng.normal(size=num, scale=variance**0.5)",
    "docstring": "Return block of normal random numbers\n\n    Parameters\n    ----------\n    seed : {None, int}\n        The seed to generate the noise.sd\n\n    Returns\n    --------\n    noise : numpy.ndarray\n        Array of random numbers"
  },
  {
    "code": "def _validate_publish_parameters(body, exchange, immediate, mandatory,\n                                     properties, routing_key):\n        if not compatibility.is_string(body):\n            raise AMQPInvalidArgument('body should be a string')\n        elif not compatibility.is_string(routing_key):\n            raise AMQPInvalidArgument('routing_key should be a string')\n        elif not compatibility.is_string(exchange):\n            raise AMQPInvalidArgument('exchange should be a string')\n        elif properties is not None and not isinstance(properties, dict):\n            raise AMQPInvalidArgument('properties should be a dict or None')\n        elif not isinstance(mandatory, bool):\n            raise AMQPInvalidArgument('mandatory should be a boolean')\n        elif not isinstance(immediate, bool):\n            raise AMQPInvalidArgument('immediate should be a boolean')",
    "docstring": "Validate Publish Parameters.\n\n        :param bytes|str|unicode body: Message payload\n        :param str routing_key: Message routing key\n        :param str exchange: The exchange to publish the message to\n        :param dict properties: Message properties\n        :param bool mandatory: Requires the message is published\n        :param bool immediate: Request immediate delivery\n\n        :raises AMQPInvalidArgument: Invalid Parameters\n\n        :return:"
  },
  {
    "code": "def has_datastore(self):\n        success, result = self._read_from_hdx('datastore', self.data['id'], 'resource_id',\n                                              self.actions()['datastore_search'])\n        if not success:\n            logger.debug(result)\n        else:\n            if result:\n                return True\n        return False",
    "docstring": "Check if the resource has a datastore.\n\n        Returns:\n            bool: Whether the resource has a datastore or not"
  },
  {
    "code": "def list_bandwidth_limit_rules(self, policy_id,\n                                   retrieve_all=True, **_params):\n        return self.list('bandwidth_limit_rules',\n                         self.qos_bandwidth_limit_rules_path % policy_id,\n                         retrieve_all, **_params)",
    "docstring": "Fetches a list of all bandwidth limit rules for the given policy."
  },
  {
    "code": "def _call(self, resource_url, params=None):\n        url = \"%s%s\" % (self._endpoint(), resource_url)\n        if params:\n            url += \"?%s&%s\" % (params, self._auth())\n        else:\n            url += \"?%s\" % self._auth()\n        return requests.get(url)",
    "docstring": "Calls the Marvel API endpoint\n\n        :param resource_url: url slug of the resource\n        :type resource_url: str\n        :param params: query params to add to endpoint\n        :type params: str\n        \n        :returns:  response -- Requests response"
  },
  {
    "code": "def drop(verbose):\n    click.secho('Dropping all tables!', fg='red', bold=True)\n    with click.progressbar(reversed(_db.metadata.sorted_tables)) as bar:\n        for table in bar:\n            if verbose:\n                click.echo(' Dropping table {0}'.format(table))\n            table.drop(bind=_db.engine, checkfirst=True)\n        drop_alembic_version_table()\n    click.secho('Dropped all tables!', fg='green')",
    "docstring": "Drop tables."
  },
  {
    "code": "def exit(self, code=0, message=None):\n        if self._parser:\n            if code > 0:\n                self.parser.error(message)\n            else:\n                self.parser.exit(code, message)\n        else:\n            if message is not None:\n                if code > 0:\n                    sys.stderr.write(message)\n                else:\n                    sys.stdout.write(message)\n            sys.exit(code)\n        raise Exception(\"Unable to exit the %s\" % self.__class__.__name__)",
    "docstring": "Exit the console program sanely."
  },
  {
    "code": "def create(labels=None, **kw):\n    if labels is not None:\n        kw[u'labels'] = encoding.PyValueToMessage(MetricValue.LabelsValue,\n                                                  labels)\n    return MetricValue(**kw)",
    "docstring": "Constructs a new metric value.\n\n    This acts as an alternate to MetricValue constructor which\n    simplifies specification of labels.  Rather than having to create\n    a MetricValue.Labels instance, all that's necessary to specify the\n    required string.\n\n    Args:\n      labels (dict([string, [string]]):\n      **kw: any other valid keyword args valid in the MetricValue constructor\n\n    Returns\n      :class:`MetricValue`: the created instance"
  },
  {
    "code": "def _validate_list_type(self, name, obj, *args):\n        if obj is None:\n            return\n        if isinstance(obj, list):\n            for i in obj:\n                self._validate_type_not_null(name,  i, *args)\n        else:\n            self._validate_type(name, obj, *args)",
    "docstring": "Helper function that checks the input object type against each in a list of classes, or if the input object\n        is a list, each value that it contains against that list.\n\n        :param name: Name of the object.\n        :param obj: Object to check the type of.\n        :param args: List of classes.\n        :raises TypeError: if the input object is not of any of the allowed types."
  },
  {
    "code": "def open(self):\n        if self.flag == \"w\":\n            check_call(_LIB.MXRecordIOWriterCreate(self.uri, ctypes.byref(self.handle)))\n            self.writable = True\n        elif self.flag == \"r\":\n            check_call(_LIB.MXRecordIOReaderCreate(self.uri, ctypes.byref(self.handle)))\n            self.writable = False\n        else:\n            raise ValueError(\"Invalid flag %s\"%self.flag)\n        self.pid = current_process().pid\n        self.is_open = True",
    "docstring": "Opens the record file."
  },
  {
    "code": "def get_body(self):\n        body = copy.deepcopy(self.errors)\n        for error in body:\n            for key in error.keys():\n                if key not in self.ERROR_OBJECT_FIELDS:\n                    del error[key]\n        return json.dumps({'errors': body})",
    "docstring": "Return a HTTPStatus compliant body attribute\n\n        Be sure to purge any unallowed properties from the object.\n\n        TIP: At the risk of being a bit slow we copy the errors\n             instead of mutating them since they may have key/vals\n             like headers that are useful elsewhere."
  },
  {
    "code": "def create_qgis_template_output(output_path, layout):\n    dirname = os.path.dirname(output_path)\n    if not os.path.exists(dirname):\n        os.makedirs(dirname)\n    context = QgsReadWriteContext()\n    context.setPathResolver(QgsProject.instance().pathResolver())\n    layout.saveAsTemplate(output_path, context)\n    return output_path",
    "docstring": "Produce QGIS Template output.\n\n    :param output_path: The output path.\n    :type output_path: str\n\n    :param composition: QGIS Composition object to get template.\n        values\n    :type composition: qgis.core.QgsLayout\n\n    :return: Generated output path.\n    :rtype: str"
  },
  {
    "code": "def from_fits_images(cls, path_l, max_norder):\n        moc = MOC()\n        for path in path_l:\n            header = fits.getheader(path)\n            current_moc = MOC.from_image(header=header, max_norder=max_norder)\n            moc = moc.union(current_moc)\n        return moc",
    "docstring": "Loads a MOC from a set of FITS file images.\n\n        Parameters\n        ----------\n        path_l : [str]\n            A list of path where the fits image are located.\n        max_norder : int\n            The MOC resolution.\n\n        Returns\n        -------\n        moc : `~mocpy.moc.MOC`\n            The union of all the MOCs created from the paths found in ``path_l``."
  },
  {
    "code": "def generate_random_string(number_of_random_chars=8, character_set=string.ascii_letters):\n    return u('').join(random.choice(character_set)\n                      for _ in range(number_of_random_chars))",
    "docstring": "Generate a series of random characters.\n\n    Kwargs:\n        number_of_random_chars (int) : Number of characters long\n        character_set (str): Specify a character set.  Default is ASCII"
  },
  {
    "code": "def _make_request(self, method, url, post_data=None, body=None):\n        if not self.connection:\n            self._connect()\n        try:\n            self.connection.close()\n        except:\n            pass\n        self.connection.connect()\n        headers = {}\n        if self.auth_header:\n            headers[\"Authorization\"] = self.auth_header\n        self.connection.request(method, url, body, headers)\n        resp = self.connection.getresponse()\n        return resp",
    "docstring": "Make a request on this connection"
  },
  {
    "code": "def _is_ascii_stl(first_bytes):\n    is_ascii = False\n    if 'solid' in first_bytes.decode(\"utf-8\").lower():\n        is_ascii = True\n    return is_ascii",
    "docstring": "Determine if this is an ASCII based data stream, simply by checking the bytes for the word 'solid'."
  },
  {
    "code": "def _get_errors(self):\n        errors = self.json.get('data').get('failures')\n        if errors:\n            logger.error(errors)\n        return errors",
    "docstring": "Gets errors from HTTP response"
  },
  {
    "code": "def _key_values(self, sn: \"SequenceNode\") -> Union[EntryKeys, EntryValue]:\n        try:\n            keys = self.up_to(\"/\")\n        except EndOfInput:\n            keys = self.remaining()\n        if not keys:\n            raise UnexpectedInput(self, \"entry value or keys\")\n        if isinstance(sn, LeafListNode):\n            return EntryValue(unquote(keys))\n        ks = keys.split(\",\")\n        try:\n            if len(ks) != len(sn.keys):\n                raise UnexpectedInput(self, f\"exactly {len(sn.keys)} keys\")\n        except AttributeError:\n            raise BadSchemaNodeType(sn.qual_name, \"list\")\n        sel = {}\n        for j in range(len(ks)):\n            knod = sn.get_data_child(*sn.keys[j])\n            val = unquote(ks[j])\n            sel[(knod.name, None if knod.ns == sn.ns else knod.ns)] = val\n        return EntryKeys(sel)",
    "docstring": "Parse leaf-list value or list keys."
  },
  {
    "code": "def pad_zeroes(addr, n_zeroes):\n    if len(addr) < n_zeroes:\n        return pad_zeroes(\"0\" + addr, n_zeroes)\n    return addr",
    "docstring": "Padds the address with zeroes"
  },
  {
    "code": "def review_score(self, reviewer, product):\n        return self._g.retrieve_review(reviewer, product).score",
    "docstring": "Find a review score from a given reviewer to a product.\n\n        Args:\n          reviewer: Reviewer i.e. an instance of :class:`ria.bipartite.Reviewer`.\n          product: Product i.e. an instance of :class:`ria.bipartite.Product`.\n\n        Returns:\n          A review object representing the review from the reviewer to the product."
  },
  {
    "code": "def prefixes_to_fns(self, prefixes: List[str]) -> Tuple[List[str], List[str]]:\n        feat_fns = [str(self.feat_dir / (\"%s.%s.npy\" % (prefix, self.feat_type)))\n                    for prefix in prefixes]\n        label_fns = [str(self.label_dir / (\"%s.%s\" % (prefix, self.label_type)))\n                      for prefix in prefixes]\n        return feat_fns, label_fns",
    "docstring": "Fetches the file paths to the features files and labels files\n        corresponding to the provided list of features"
  },
  {
    "code": "def reconstruct(self, b, X=None):\n        if X is None:\n            X = self.getcoef()\n        Xf = sl.rfftn(X, None, self.cbpdn.cri.axisN)\n        slc = (slice(None),)*self.dimN + \\\n              (slice(self.chncs[b], self.chncs[b+1]),)\n        Sf = np.sum(self.cbpdn.Df[slc] * Xf, axis=self.cbpdn.cri.axisM)\n        return sl.irfftn(Sf, self.cbpdn.cri.Nv, self.cbpdn.cri.axisN)",
    "docstring": "Reconstruct representation of signal b in signal set."
  },
  {
    "code": "def valid_any_uri(item):\n    try:\n        part = urlparse(item)\n    except Exception:\n        raise NotValid(\"AnyURI\")\n    if part[0] == \"urn\" and part[1] == \"\":\n        return True\n    return True",
    "docstring": "very simplistic, ..."
  },
  {
    "code": "def set_storage(self, storage):\n        if isinstance(storage, BaseStorage):\n            self.storage = storage\n        elif isinstance(storage, dict):\n            if 'backend' not in storage and 'root_dir' in storage:\n                storage['backend'] = 'FileSystem'\n            try:\n                backend_cls = getattr(storage_package, storage['backend'])\n            except AttributeError:\n                try:\n                    backend_cls = import_module(storage['backend'])\n                except ImportError:\n                    self.logger.error('cannot find backend module %s',\n                                      storage['backend'])\n                    sys.exit()\n            kwargs = storage.copy()\n            del kwargs['backend']\n            self.storage = backend_cls(**kwargs)\n        else:\n            raise TypeError('\"storage\" must be a storage object or dict')",
    "docstring": "Set storage backend for downloader\n\n        For full list of storage backend supported, please see :mod:`storage`.\n\n        Args:\n            storage (dict or BaseStorage): storage backend configuration or instance"
  },
  {
    "code": "def minver_error(pkg_name):\n    print(\n        'ERROR: specify minimal version of \"{}\" using '\n        '\">=\" or \"==\"'.format(pkg_name),\n        file=sys.stderr\n    )\n    sys.exit(1)",
    "docstring": "Report error about missing minimum version constraint and exit."
  },
  {
    "code": "def _load_config(self):\n        self._config = ConfigParser.SafeConfigParser()\n        self._config.read(self.config_path)",
    "docstring": "Read the configuration file and load it into memory."
  },
  {
    "code": "def _get_at_pos(self, pos):\n        if pos < 0:\n            return None, None\n        if len(self.lines) > pos:\n            return self.lines[pos], pos\n        if self.file is None:\n            return None, None\n        assert pos == len(self.lines), \"out of order request?\"\n        self.read_next_line()\n        return self.lines[-1], pos",
    "docstring": "Return a widget for the line number passed."
  },
  {
    "code": "def _getSectionForDataDirectoryEntry(self, data_directory_entry, sections):\n        for section in sections:\n            if data_directory_entry.VirtualAddress >= section.header.VirtualAddress and \\\n            data_directory_entry.VirtualAddress < section.header.VirtualAddress + section.header.SizeOfRawData :\n                return section",
    "docstring": "Returns the section which contains the data of DataDirectory"
  },
  {
    "code": "def _terminate_procs(procs):\n    logging.warn(\"Stopping all remaining processes\")\n    for proc, g in procs.values():\n        logging.debug(\"[%s] SIGTERM\", proc.pid)\n        try:\n            proc.terminate()\n        except OSError as e:\n            if e.errno != errno.ESRCH:\n                raise\n    sys.exit(1)",
    "docstring": "Terminate all processes in the process dictionary"
  },
  {
    "code": "def play(self, filename, translate=False):\n        if translate:\n            with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:\n                fname = f.name\n            with audioread.audio_open(filename) as f:\n                with contextlib.closing(wave.open(fname, 'w')) as of:\n                    of.setnchannels(f.channels)\n                    of.setframerate(f.samplerate)\n                    of.setsampwidth(2)\n                    for buf in f:\n                        of.writeframes(buf)\n            filename = fname\n        if winsound:\n            winsound.PlaySound(str(filename), winsound.SND_FILENAME)\n        else:\n            cmd = ['aplay', str(filename)]\n            self._logger.debug('Executing %s', ' '.join([pipes.quote(arg) for arg in cmd]))\n            subprocess.call(cmd)\n        if translate:\n            os.remove(fname)",
    "docstring": "Plays the sounds.\n\n        :filename: The input file name\n        :translate: If True, it runs it through audioread which will translate from common compression formats to raw WAV."
  },
  {
    "code": "def datetimeparse(s):\n    try:\n        dt = dateutil.parser.parse(s)\n    except ValueError:\n        return None\n    return utc_dt(dt)",
    "docstring": "Parse a string date time to a datetime object.\n\n    Suitable for dates serialized with .isoformat()\n\n    :return: None, or an aware datetime instance, tz=UTC."
  },
  {
    "code": "def load_cli_plugins(cli, config_dir=None):\n    from .config import load_master_config\n    config = load_master_config(config_dir=config_dir)\n    plugins = discover_plugins(config.Plugins.dirs)\n    for plugin in plugins:\n        if not hasattr(plugin, 'attach_to_cli'):\n            continue\n        logger.debug(\"Attach plugin `%s` to CLI.\", _fullname(plugin))\n        try:\n            plugin().attach_to_cli(cli)\n        except Exception as e:\n            logger.error(\"Error when loading plugin `%s`: %s\", plugin, e)",
    "docstring": "Load all plugins and attach them to a CLI object."
  },
  {
    "code": "def init_conv_weight(layer):\n    n_filters = layer.filters\n    filter_shape = (layer.kernel_size,) * get_n_dim(layer)\n    weight = np.zeros((n_filters, n_filters) + filter_shape)\n    center = tuple(map(lambda x: int((x - 1) / 2), filter_shape))\n    for i in range(n_filters):\n        filter_weight = np.zeros((n_filters,) + filter_shape)\n        index = (i,) + center\n        filter_weight[index] = 1\n        weight[i, ...] = filter_weight\n    bias = np.zeros(n_filters)\n    layer.set_weights(\n        (add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1])))\n    )",
    "docstring": "initilize conv layer weight."
  },
  {
    "code": "def _magic(header, footer, mime, ext=None):\n    if not header:\n        raise ValueError(\"Input was empty\")\n    info = _identify_all(header, footer, ext)[0]\n    if mime:\n        return info.mime_type\n    return info.extension if not \\\n        isinstance(info.extension, list) else info[0].extension",
    "docstring": "Discover what type of file it is based on the incoming string"
  },
  {
    "code": "def run(self):\n        \"Run cli, processing arguments and executing subcommands.\"\n        arguments = self.argument_parser.parse_args()\n        argspec = inspect.getargspec(arguments.func)\n        vargs = []\n        for arg in argspec.args:\n            vargs.append(getattr(arguments, arg))\n        if argspec.varargs:\n            vargs.extend(getattr(arguments, argspec.varargs))\n        output = arguments.func(*vargs)\n        if getattr(arguments.func, '_cli_test_command', False):\n            self.exit_code = 0 if output else 1\n            output = ''\n        if getattr(arguments.func, '_cli_no_output', False):\n            output = ''\n        self.formatter.format_output(output, arguments.format)\n        if charmhelpers.core.unitdata._KV:\n            charmhelpers.core.unitdata._KV.flush()",
    "docstring": "Run cli, processing arguments and executing subcommands."
  },
  {
    "code": "def load_local_translationtable(self, name):\n        localtt_file = 'translationtable/' + name + '.yaml'\n        try:\n            with open(localtt_file):\n                pass\n        except IOError:\n            with open(localtt_file, 'w') as write_yaml:\n                yaml.dump({name: name}, write_yaml)\n        finally:\n            with open(localtt_file, 'r') as read_yaml:\n                localtt = yaml.safe_load(read_yaml)\n        self.localtcid = {v: k for k, v in localtt.items()}\n        return localtt",
    "docstring": "Load \"ingest specific\" translation from whatever they called something\n        to the ontology label we need to map it to.\n        To facilitate seeing more ontology lables in dipper ingests\n        a reverse mapping from ontology lables to external strings is also generated\n        and available as a dict localtcid"
  },
  {
    "code": "def parse_binary(self):\n\t\tself.mimetype = self.resource.rdf.graph.value(\n\t\t\tself.resource.uri,\n\t\t\tself.resource.rdf.prefixes.ebucore.hasMimeType).toPython()\n\t\tself.data = self.resource.repo.api.http_request(\n\t\t\t'GET',\n\t\t\tself.resource.uri,\n\t\t\tdata=None,\n\t\t\theaders={'Content-Type':self.resource.mimetype},\n\t\t\tis_rdf=False,\n\t\t\tstream=True)",
    "docstring": "when retrieving a NonRDF resource, parse binary data and make available\n\t\tvia generators"
  },
  {
    "code": "def add_instance(self, instance):\n        assert isinstance(instance, dict)\n        item = defaults[\"common\"].copy()\n        item.update(defaults[\"instance\"])\n        item.update(instance[\"data\"])\n        item.update(instance)\n        item[\"itemType\"] = \"instance\"\n        item[\"isToggled\"] = instance[\"data\"].get(\"publish\", True)\n        item[\"hasCompatible\"] = True\n        item[\"category\"] = item[\"category\"] or item[\"family\"]\n        self.add_section(item[\"category\"])\n        families = [instance[\"data\"][\"family\"]]\n        families.extend(instance[\"data\"].get(\"families\", []))\n        item[\"familiesConcatenated\"] += \", \".join(families)\n        item = self.add_item(item)\n        self.instances.append(item)",
    "docstring": "Append `instance` to model\n\n        Arguments:\n            instance (dict): Serialised instance\n\n        Schema:\n            instance.json"
  },
  {
    "code": "def _sumindex(self, index=None):\n        try:\n            ndim = len(index)\n        except TypeError:\n            index = (index,)\n            ndim = 1\n        if len(self.shape) != ndim:\n            raise ValueError(\"Index to %d-dimensional array %s has too %s dimensions\" %\n                (len(self.shape), self.name, [\"many\",\"few\"][len(self.shape) > ndim]))\n        sumindex = 0\n        for i in range(ndim-1,-1,-1):\n            index1 = index[i]\n            if index1 < 0 or index1 >= self.shape[i]:\n                raise ValueError(\"Dimension %d index for array %s is out of bounds (value=%d)\" %\n                    (i+1, self.name, index1))\n            sumindex = index1 + sumindex*self.shape[i]\n        return sumindex",
    "docstring": "Convert tuple index to 1-D index into value"
  },
  {
    "code": "def close(self):\n        if VERBOSE:\n            _print_out('\\nDummy_serial: Closing port\\n')\n        if not self._isOpen:\n            raise IOError('Dummy_serial: The port is already closed')\n        self._isOpen = False\n        self.port = None",
    "docstring": "Close a port on dummy_serial."
  },
  {
    "code": "def to_float_with_default(value, default_value):\n        result = FloatConverter.to_nullable_float(value)\n        return result if result != None else default_value",
    "docstring": "Converts value into float or returns default when conversion is not possible.\n\n        :param value: the value to convert.\n\n        :param default_value: the default value.\n\n        :return: float value or default value when conversion is not supported."
  },
  {
    "code": "def get_system(self, twig=None, **kwargs):\n        if twig is not None:\n            kwargs['twig'] = twig\n        kwargs['context'] = 'system'\n        return self.filter(**kwargs)",
    "docstring": "Filter in the 'system' context\n\n        :parameter str twig: twig to use for filtering\n        :parameter **kwargs: any other tags to do the filter\n            (except twig or context)\n\n        :return: :class:`phoebe.parameters.parameters.Parameter` or\n            :class:`phoebe.parameters.parameters.ParameterSet`"
  },
  {
    "code": "def compute_pairwise_similarity_score(self):\n        pairs = []\n        all_scores = []\n        for i, unit in enumerate(self.parsed_response):\n            for j, other_unit in enumerate(self.parsed_response):\n                if i != j:\n                    pair = (i, j)\n                    rev_pair = (j, i)\n                    if pair not in pairs and rev_pair not in pairs:\n                        score = self.compute_similarity_score(unit, other_unit)\n                        pairs.append(pair)\n                        pairs.append(rev_pair)\n                        all_scores.append(score)\n        all_scores = [i for i in all_scores if i != self.same_word_similarity]\n        self.measures[\"COLLECTION_\" + self.current_similarity_measure + \"_pairwise_similarity_score_mean\"] = get_mean(\n            all_scores) \\\n            if len(pairs) > 0 else 'NA'",
    "docstring": "Computes the average pairwise similarity score between all pairs of Units.\n\n        The pairwise similarity is calculated as the sum of similarity scores for all pairwise\n        word pairs in a response -- except any pair composed of a word and\n        itself -- divided by the total number of words in an attempt. I.e.,\n        the mean similarity for all pairwise word pairs.\n\n        Adds the following measures to the self.measures dictionary:\n            - COLLECTION_collection_pairwise_similarity_score_mean: mean of pairwise similarity scores\n\n        .. todo: divide by (count-1)?"
  },
  {
    "code": "def get_stats(self):\n        resp = requests.get('%s/api/stats.json' % self.url)\n        assert(resp.status_code == 200)\n        return resp.json()",
    "docstring": "Get kitty stats as a dictionary"
  },
  {
    "code": "def save_feedback(rdict):\n    if not os.path.exists(_feedback_dir):\n        os.makedirs(_feedback_dir)\n    jcont = json.dumps(rdict)\n    f = open(_feedback_file, 'w')\n    f.write(jcont)\n    f.close()",
    "docstring": "Save feedback file"
  },
  {
    "code": "def nfa(self):\n        finalstate = State(final=True)\n        nextstate = finalstate\n        for tokenexpr in reversed(self):\n            state = tokenexpr.nfa(nextstate)\n            nextstate = state\n        return NFA(state)",
    "docstring": "convert the expression into an NFA"
  },
  {
    "code": "def retrieve_object_query(self, view_kwargs, filter_field, filter_value):\n        return self.session.query(self.model).filter(filter_field == filter_value)",
    "docstring": "Build query to retrieve object\n\n        :param dict view_kwargs: kwargs from the resource view\n        :params sqlalchemy_field filter_field: the field to filter on\n        :params filter_value: the value to filter with\n        :return sqlalchemy query: a query from sqlalchemy"
  },
  {
    "code": "def default(self):\n        if self.MUTABLE:\n            return copy.deepcopy(self._default)\n        else:\n            return self._default",
    "docstring": "Returns the static value that this defaults to."
  },
  {
    "code": "def add_from_existing(self, resource, timeout=-1):\n        uri = self.URI + \"/from-existing\"\n        return self._client.create(resource, uri=uri, timeout=timeout)",
    "docstring": "Adds a volume that already exists in the Storage system\n\n        Args:\n            resource (dict):\n                Object to create.\n            timeout:\n                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n                in OneView, just stop waiting for its completion.\n\n        Returns:\n            dict: Added resource."
  },
  {
    "code": "def remove(config, username, filename, force):\n        client = Client()\n        client.prepare_connection()\n        user_api = UserApi(client)\n        key_api = API(client)\n        key_api.remove(username, user_api, filename, force)",
    "docstring": "Remove user's SSH public key from their LDAP entry."
  },
  {
    "code": "def generation(self):\n        with self._lock:\n            if self.state is not MemberState.STABLE:\n                return None\n            return self._generation",
    "docstring": "Get the current generation state if the group is stable.\n\n        Returns: the current generation or None if the group is unjoined/rebalancing"
  },
  {
    "code": "def _generate_attrs(self):\n        attrs = {}\n        if ismodule(self.doubled_obj):\n            for name, func in getmembers(self.doubled_obj, is_callable):\n                attrs[name] = Attribute(func, 'toplevel', self.doubled_obj)\n        else:\n            for attr in classify_class_attrs(self.doubled_obj_type):\n                attrs[attr.name] = attr\n        return attrs",
    "docstring": "Get detailed info about target object.\n\n        Uses ``inspect.classify_class_attrs`` to get several important details about each attribute\n        on the target object.\n\n        :return: The attribute details dict.\n        :rtype: dict"
  },
  {
    "code": "def select_action(self, **kwargs):\n        setattr(self.inner_policy, self.attr, self.get_current_value())\n        return self.inner_policy.select_action(**kwargs)",
    "docstring": "Choose an action to perform\n\n        # Returns\n            Action to take (int)"
  },
  {
    "code": "def remove_adapter(widget_class, flavour=None):\n    for it,tu in enumerate(__def_adapter):\n        if (widget_class == tu[WIDGET] and flavour == tu[FLAVOUR]):\n            del __def_adapter[it]\n            return True\n    return False",
    "docstring": "Removes the given widget class information from the default set\n    of adapters.\n\n    If widget_class had been previously added by using add_adapter,\n    the added adapter will be removed, restoring possibly previusly\n    existing adapter(s). Notice that this function will remove only\n    *one* adapter about given wiget_class (the first found in order),\n    even if many are currently stored.\n\n    @param flavour has to be used when the entry was added with a\n    particular flavour.\n\n    Returns True if one adapter was removed, False if no adapter was\n    removed."
  },
  {
    "code": "def ParseAgeSpecification(cls, age):\n    try:\n      return (0, int(age))\n    except (ValueError, TypeError):\n      pass\n    if age == NEWEST_TIME:\n      return data_store.DB.NEWEST_TIMESTAMP\n    elif age == ALL_TIMES:\n      return data_store.DB.ALL_TIMESTAMPS\n    elif len(age) == 2:\n      start, end = age\n      return (int(start), int(end))\n    raise ValueError(\"Unknown age specification: %s\" % age)",
    "docstring": "Parses an aff4 age and returns a datastore age specification."
  },
  {
    "code": "def sound_pressure_low(self):\n        self._ensure_mode(self.MODE_DBA)\n        return self.value(0) * self._scale('DBA')",
    "docstring": "A measurement of the measured sound pressure level, as a\n        percent. Uses A-weighting, which focuses on levels up to 55 dB."
  },
  {
    "code": "def draw(self):\n        for fig in self.figs2draw:\n            fig.canvas.draw()\n        self._figs2draw.clear()",
    "docstring": "Draw the figures and those that are shared and have been changed"
  },
  {
    "code": "def _ParseCachedEntryVista(self, value_data, cached_entry_offset):\n    try:\n      cached_entry = self._ReadStructureFromByteStream(\n          value_data[cached_entry_offset:], cached_entry_offset,\n          self._cached_entry_data_type_map)\n    except (ValueError, errors.ParseError) as exception:\n      raise errors.ParseError(\n          'Unable to parse cached entry value with error: {0!s}'.format(\n              exception))\n    path_size = cached_entry.path_size\n    maximum_path_size = cached_entry.maximum_path_size\n    path_offset = cached_entry.path_offset\n    if path_offset > 0 and path_size > 0:\n      path_size += path_offset\n      maximum_path_size += path_offset\n      try:\n        path = value_data[path_offset:path_size].decode('utf-16-le')\n      except UnicodeDecodeError:\n        raise errors.ParseError('Unable to decode cached entry path to string')\n    cached_entry_object = AppCompatCacheCachedEntry()\n    cached_entry_object.cached_entry_size = (\n        self._cached_entry_data_type_map.GetByteSize())\n    cached_entry_object.insertion_flags = cached_entry.insertion_flags\n    cached_entry_object.last_modification_time = (\n        cached_entry.last_modification_time)\n    cached_entry_object.path = path\n    cached_entry_object.shim_flags = cached_entry.shim_flags\n    return cached_entry_object",
    "docstring": "Parses a Windows Vista cached entry.\n\n    Args:\n      value_data (bytes): value data.\n      cached_entry_offset (int): offset of the first cached entry data\n          relative to the start of the value data.\n\n    Returns:\n      AppCompatCacheCachedEntry: cached entry.\n\n    Raises:\n      ParseError: if the value data could not be parsed."
  },
  {
    "code": "def return_input_paths(job, work_dir, ids, *args):\n    paths = OrderedDict()\n    for name in args:\n        if not os.path.exists(os.path.join(work_dir, name)):\n            file_path = job.fileStore.readGlobalFile(ids[name], os.path.join(work_dir, name))\n        else:\n            file_path = os.path.join(work_dir, name)\n        paths[name] = file_path\n        if len(args) == 1:\n            return file_path\n    return paths.values()",
    "docstring": "Returns the paths of files from the FileStore\n\n    Input1: Toil job instance\n    Input2: Working directory\n    Input3: jobstore id dictionary\n    Input4: names of files to be returned from the jobstore\n\n    Returns: path(s) to the file(s) requested -- unpack these!"
  },
  {
    "code": "def color_stream_mt(istream=sys.stdin, n=config.N_PROCESSES, **kwargs):\n    queue = multiprocessing.Queue(1000)\n    lock = multiprocessing.Lock()\n    pool = [multiprocessing.Process(target=color_process, args=(queue, lock),\n            kwargs=kwargs) for i in range(n)]\n    for p in pool:\n        p.start()\n    block = []\n    for line in istream:\n        block.append(line.strip())\n        if len(block) == config.BLOCK_SIZE:\n            queue.put(block)\n            block = []\n    if block:\n        queue.put(block)\n    for i in range(n):\n        queue.put(config.SENTINEL)\n    for p in pool:\n        p.join()",
    "docstring": "Read filenames from the input stream and detect their palette using\n    multiple processes."
  },
  {
    "code": "def python_sidebar_help(python_input):\n    token = 'class:sidebar.helptext'\n    def get_current_description():\n        i = 0\n        for category in python_input.options:\n            for option in category.options:\n                if i == python_input.selected_option_index:\n                    return option.description\n                i += 1\n        return ''\n    def get_help_text():\n        return [(token, get_current_description())]\n    return ConditionalContainer(\n        content=Window(\n            FormattedTextControl(get_help_text),\n            style=token,\n            height=Dimension(min=3)),\n        filter=ShowSidebar(python_input) &\n               Condition(lambda: python_input.show_sidebar_help) & ~is_done)",
    "docstring": "Create the `Layout` for the help text for the current item in the sidebar."
  },
  {
    "code": "def compute_K_factors(self, spacing=None, configs=None, numerical=False,\n                          elem_file=None, elec_file=None):\n        if configs is None:\n            use_configs = self.configs\n        else:\n            use_configs = configs\n        if numerical:\n            settings = {\n                'elem': elem_file,\n                'elec': elec_file,\n                'rho': 100,\n            }\n            K = edfK.compute_K_numerical(use_configs, settings)\n        else:\n            K = edfK.compute_K_analytical(use_configs, spacing=spacing)\n        return K",
    "docstring": "Compute analytical geometrical factors.\n\n        TODO: use real electrode positions from self.grid"
  },
  {
    "code": "def get_loader(module_or_name):\n    if module_or_name in sys.modules:\n        module_or_name = sys.modules[module_or_name]\n    if isinstance(module_or_name, ModuleType):\n        module = module_or_name\n        loader = getattr(module, '__loader__', None)\n        if loader is not None:\n            return loader\n        fullname = module.__name__\n    else:\n        fullname = module_or_name\n    return find_loader(fullname)",
    "docstring": "Get a PEP 302 \"loader\" object for module_or_name\n\n    If the module or package is accessible via the normal import\n    mechanism, a wrapper around the relevant part of that machinery\n    is returned.  Returns None if the module cannot be found or imported.\n    If the named module is not already imported, its containing package\n    (if any) is imported, in order to establish the package __path__.\n\n    This function uses iter_importers(), and is thus subject to the same\n    limitations regarding platform-specific special import locations such\n    as the Windows registry."
  },
  {
    "code": "def delete_user(self, username):\n        path = Client.urls['users_by_name'] % username\n        return self._call(path, 'DELETE')",
    "docstring": "Deletes a user from the server.\n\n        :param string username: Name of the user to delete from the server."
  },
  {
    "code": "def pix2vec(nside, ipix, nest=False):\n    lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring')\n    return ang2vec(*_lonlat_to_healpy(lon, lat))",
    "docstring": "Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`."
  },
  {
    "code": "def from_list(cls, l):\n        if len(l) == 3:\n                x, y, z = map(float, l)\n                return cls(x, y, z)\n        elif len(l) == 2:\n            x, y = map(float, l)\n            return cls(x, y)\n        else:\n            raise AttributeError",
    "docstring": "Return a Point instance from a given list"
  },
  {
    "code": "def instruction_PAGE(self, opcode):\n        op_address, opcode2 = self.read_pc_byte()\n        paged_opcode = opcode * 256 + opcode2\n        self.call_instruction_func(op_address - 1, paged_opcode)",
    "docstring": "call op from page 2 or 3"
  },
  {
    "code": "def preserve_context(f):\n    action = current_action()\n    if action is None:\n        return f\n    task_id = action.serialize_task_id()\n    called = threading.Lock()\n    def restore_eliot_context(*args, **kwargs):\n        if not called.acquire(False):\n            raise TooManyCalls(f)\n        with Action.continue_task(task_id=task_id):\n            return f(*args, **kwargs)\n    return restore_eliot_context",
    "docstring": "Package up the given function with the current Eliot context, and then\n    restore context and call given function when the resulting callable is\n    run. This allows continuing the action context within a different thread.\n\n    The result should only be used once, since it relies on\n    L{Action.serialize_task_id} whose results should only be deserialized\n    once.\n\n    @param f: A callable.\n\n    @return: One-time use callable that calls given function in context of\n        a child of current Eliot action."
  },
  {
    "code": "def get_lr_scheduler(learning_rate, lr_refactor_step, lr_refactor_ratio,\n                     num_example, batch_size, begin_epoch):\n    assert lr_refactor_ratio > 0\n    iter_refactor = [int(r) for r in lr_refactor_step.split(',') if r.strip()]\n    if lr_refactor_ratio >= 1:\n        return (learning_rate, None)\n    else:\n        lr = learning_rate\n        epoch_size = num_example // batch_size\n        for s in iter_refactor:\n            if begin_epoch >= s:\n                lr *= lr_refactor_ratio\n        if lr != learning_rate:\n            logging.getLogger().info(\"Adjusted learning rate to {} for epoch {}\".format(lr, begin_epoch))\n        steps = [epoch_size * (x - begin_epoch) for x in iter_refactor if x > begin_epoch]\n        if not steps:\n            return (lr, None)\n        lr_scheduler = mx.lr_scheduler.MultiFactorScheduler(step=steps, factor=lr_refactor_ratio)\n        return (lr, lr_scheduler)",
    "docstring": "Compute learning rate and refactor scheduler\n\n    Parameters:\n    ---------\n    learning_rate : float\n        original learning rate\n    lr_refactor_step : comma separated str\n        epochs to change learning rate\n    lr_refactor_ratio : float\n        lr *= ratio at certain steps\n    num_example : int\n        number of training images, used to estimate the iterations given epochs\n    batch_size : int\n        training batch size\n    begin_epoch : int\n        starting epoch\n\n    Returns:\n    ---------\n    (learning_rate, mx.lr_scheduler) as tuple"
  },
  {
    "code": "def get_dimension_index(self, dimension):\n        if isinstance(dimension, int):\n            if (dimension < (self.ndims + len(self.vdims)) or\n                dimension < len(self.dimensions())):\n                return dimension\n            else:\n                return IndexError('Dimension index out of bounds')\n        dim = dimension_name(dimension)\n        try:\n            dimensions = self.kdims+self.vdims\n            return [i for i, d in enumerate(dimensions) if d == dim][0]\n        except IndexError:\n            raise Exception(\"Dimension %s not found in %s.\" %\n                            (dim, self.__class__.__name__))",
    "docstring": "Get the index of the requested dimension.\n\n        Args:\n            dimension: Dimension to look up by name or by index\n\n        Returns:\n            Integer index of the requested dimension"
  },
  {
    "code": "def request(self,\n                hostport=None,\n                service=None,\n                arg_scheme=None,\n                retry=None,\n                **kwargs):\n        return self.peers.request(hostport=hostport,\n                                  service=service,\n                                  arg_scheme=arg_scheme,\n                                  retry=retry,\n                                  **kwargs)",
    "docstring": "Initiate a new request through this TChannel.\n\n        :param hostport:\n            Host to which the request will be made. If unspecified, a random\n            known peer will be picked. This is not necessary if using\n            Hyperbahn.\n\n        :param service:\n            The name of a service available on Hyperbahn. Defaults to an empty\n            string.\n\n        :param arg_scheme:\n            Determines the serialization scheme for the request. One of 'raw',\n            'json', or 'thrift'. Defaults to 'raw'.\n\n        :param rety:\n            One of 'n' (never retry), 'c' (retry on connection errors), 't'\n            (retry on timeout), 'ct' (retry on connection errors and timeouts).\n\n            Defaults to 'c'."
  },
  {
    "code": "def load_cli_config(args):\n    default_cli_config = _load_default_cli_config()\n    toml_config = _load_toml_cli_config()\n    for config in (toml_config, default_cli_config):\n        for key, val in config.items():\n            if key in args and getattr(args, key) is not None:\n                pass\n            else:\n                setattr(args, key, val)",
    "docstring": "Modifies ARGS in-place to have the attributes defined in the CLI\n    config file if it doesn't already have them. Certain default\n    values are given if they are not in ARGS or the config file."
  },
  {
    "code": "def get_col(self, col_name, filter = lambda _ : True):\n        if col_name not in self._headers:\n            raise ValueError(\"{} not found! Model has headers: {}\".format(col_name, self._headers))\n        col = []\n        for i in range(self.num_rows):\n            row = self._table[i + 1]\n            val = row[col_name]\n            if filter(val):\n                col.append(val)\n        return col",
    "docstring": "Return all values in the column corresponding to col_name that satisfies filter, which is\n        a function that takes in a value of the column's type and returns True or False\n\n        Parameters\n        ----------\n        col_name : str\n            Name of desired column\n        filter : function, optional\n            A function that takes in a value of the column's type and returns True or False\n            Defaults to a function that always returns True\n\n        Returns\n        -------\n        list\n            A list of values in the desired columns by order of their storage in the model\n\n        Raises\n        ------\n        ValueError\n            If the desired column name is not found in the model"
  },
  {
    "code": "def find(self, pattern):\n\t\tpos = self.current_segment.data.find(pattern)\n\t\tif pos == -1:\n\t\t\treturn -1\n\t\treturn pos + self.current_position",
    "docstring": "Searches for a pattern in the current memory segment"
  },
  {
    "code": "def norm_join(prefix, suffix):\n    if (prefix is None) and (suffix is None):\n        return \".\"\n    if prefix is None:\n        return os.path.normpath(suffix)\n    if suffix is None:\n        return os.path.normpath(prefix)\n    return os.path.normpath(os.path.join(prefix, suffix))",
    "docstring": "Join ``prefix`` and ``suffix`` paths\n    and return the resulting path, normalized.\n\n    :param string prefix: the prefix path\n    :param string suffix: the suffix path\n    :rtype: string"
  },
  {
    "code": "def PopAllChildren(self):\n        indexes = self.GetChildrenIndexes()\n        children = []\n        for c in indexes:\n            child = self.PopChild(c)\n            children.append(child)\n        return children",
    "docstring": "Method to remove and return all children of current node\n\n        :return: list of children"
  },
  {
    "code": "def _build_brokers(self, brokers):\n        for broker_id, metadata in six.iteritems(brokers):\n            self.brokers[broker_id] = self._create_broker(broker_id, metadata)",
    "docstring": "Build broker objects using broker-ids."
  },
  {
    "code": "def get_cmdclass():\n    cmdclass = versioneer.get_cmdclass()\n    try:\n        from wheel.bdist_wheel import bdist_wheel\n    except ImportError:\n        bdist_wheel = None\n    if bdist_wheel is not None:\n        cmdclass[\"bdist_wheel\"] = bdist_wheel\n    return cmdclass",
    "docstring": "A ``cmdclass`` that works around a setuptools deficiency.\n\n    There is no need to build wheels when installing a package, however some\n    versions of setuptools seem to mandate this. This is a hacky workaround\n    that modifies the ``cmdclass`` returned by versioneer so that not having\n    wheel installed is not a fatal error."
  },
  {
    "code": "def status(self, message, *args, **kwargs):\n    if self.isEnabledFor(GNUPG_STATUS_LEVEL):\n        self._log(GNUPG_STATUS_LEVEL, message, args, **kwargs)",
    "docstring": "LogRecord for GnuPG internal status messages."
  },
  {
    "code": "def refund_reward(event, agreement_id, did, service_agreement, price, consumer_account,\n                  publisher_address, condition_ids):\n    logger.debug(f\"trigger refund after event {event}.\")\n    access_id, lock_id = condition_ids[:2]\n    name_to_parameter = {param.name: param for param in\n                         service_agreement.condition_by_name['escrowReward'].parameters}\n    document_id = add_0x_prefix(name_to_parameter['_documentId'].value)\n    asset_id = add_0x_prefix(did_to_id(did))\n    assert document_id == asset_id, f'document_id {document_id} <=> asset_id {asset_id} mismatch.'\n    assert price == service_agreement.get_price(), 'price mismatch.'\n    try:\n        tx_hash = Keeper.get_instance().escrow_reward_condition.fulfill(\n            agreement_id,\n            price,\n            publisher_address,\n            consumer_account.address,\n            lock_id,\n            access_id,\n            consumer_account\n        )\n        process_tx_receipt(\n            tx_hash,\n            Keeper.get_instance().escrow_reward_condition.FULFILLED_EVENT,\n            'EscrowReward.Fulfilled'\n        )\n    except Exception as e:\n        raise e",
    "docstring": "Refund the reward to the publisher address.\n\n    :param event: AttributeDict with the event data.\n    :param agreement_id: id of the agreement, hex str\n    :param did: DID, str\n    :param service_agreement: ServiceAgreement instance\n    :param price: Asset price, int\n    :param consumer_account: Account instance of the consumer\n    :param publisher_address: ethereum account address of publisher, hex str\n    :param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32"
  },
  {
    "code": "def _validate_header(self, hed):\n        if not bool(hed):\n            return False\n        length = -1\n        for row in hed:\n            if not bool(row):\n                return False\n            elif length == -1:\n                length = len(row)\n            elif len(row) != length:\n                return False\n        return True",
    "docstring": "Validate the list that represents the table header.\n\n        :param hed: The list that represents the table header.\n        :type hed: list(list(hatemile.util.html.htmldomelement.HTMLDOMElement))\n        :return: True if the table header is valid or False if the table header\n                 is not valid.\n        :rtype: bool"
  },
  {
    "code": "def pkg_config_header_strings(pkg_libraries):\n    _, _, header_dirs = pkg_config(pkg_libraries)\n    header_strings = []\n    for header_dir in header_dirs:\n        header_strings.append(\"-I\" + header_dir)\n    return header_strings",
    "docstring": "Returns a list of header strings that could be passed to a compiler"
  },
  {
    "code": "def find_mapping(\n        self,\n        other_lattice: \"Lattice\",\n        ltol: float = 1e-5,\n        atol: float = 1,\n        skip_rotation_matrix: bool = False,\n    ) -> Optional[Tuple[\"Lattice\", Optional[np.ndarray], np.ndarray]]:\n        for x in self.find_all_mappings(\n            other_lattice, ltol, atol, skip_rotation_matrix=skip_rotation_matrix\n        ):\n            return x",
    "docstring": "Finds a mapping between current lattice and another lattice. There\n        are an infinite number of choices of basis vectors for two entirely\n        equivalent lattices. This method returns a mapping that maps\n        other_lattice to this lattice.\n\n        Args:\n            other_lattice (Lattice): Another lattice that is equivalent to\n                this one.\n            ltol (float): Tolerance for matching lengths. Defaults to 1e-5.\n            atol (float): Tolerance for matching angles. Defaults to 1.\n\n        Returns:\n            (aligned_lattice, rotation_matrix, scale_matrix) if a mapping is\n            found. aligned_lattice is a rotated version of other_lattice that\n            has the same lattice parameters, but which is aligned in the\n            coordinate system of this lattice so that translational points\n            match up in 3D. rotation_matrix is the rotation that has to be\n            applied to other_lattice to obtain aligned_lattice, i.e.,\n            aligned_matrix = np.inner(other_lattice, rotation_matrix) and\n            op = SymmOp.from_rotation_and_translation(rotation_matrix)\n            aligned_matrix = op.operate_multi(latt.matrix)\n            Finally, scale_matrix is the integer matrix that expresses\n            aligned_matrix as a linear combination of this\n            lattice, i.e., aligned_matrix = np.dot(scale_matrix, self.matrix)\n\n            None is returned if no matches are found."
  },
  {
    "code": "def set_color(self, rgb):\n        target = ','.join([str(c) for c in rgb])\n        self.set_service_value(\n            self.color_service,\n            'ColorRGB',\n            'newColorRGBTarget',\n            target)\n        rgbi = self.get_color_index(['R', 'G', 'B'])\n        if rgbi is None:\n            return\n        target = ('0=0,1=0,' +\n                  str(rgbi[0]) + '=' + str(rgb[0]) + ',' +\n                  str(rgbi[1]) + '=' + str(rgb[1]) + ',' +\n                  str(rgbi[2]) + '=' + str(rgb[2]))\n        self.set_cache_complex_value(\"CurrentColor\", target)",
    "docstring": "Set dimmer color."
  },
  {
    "code": "def _get_type_name(target_thing):\n    thing = target_thing\n    if hasattr(thing, 'im_class'):\n        return thing.im_class.__name__\n    if inspect.ismethod(thing):\n        for cls in inspect.getmro(thing.__self__.__class__):\n            if cls.__dict__.get(thing.__name__) is thing:\n                return cls.__name__\n        thing = thing.__func__\n    if inspect.isfunction(thing) and hasattr(thing, '__qualname__'):\n        qualifier = thing.__qualname__\n        if LOCALS_TOKEN in qualifier:\n            return _get_local_type_name(thing)\n        return _get_external_type_name(thing)\n    return inspect.getmodule(target_thing).__name__",
    "docstring": "Functions, bound methods and unbound methods change significantly in Python 3.\n\n    For instance:\n\n    class SomeObject(object):\n        def method():\n            pass\n\n    In Python 2:\n    - Unbound method inspect.ismethod(SomeObject.method) returns True\n    - Unbound inspect.isfunction(SomeObject.method) returns False\n    - Unbound hasattr(SomeObject.method, 'im_class') returns True\n    - Bound method inspect.ismethod(SomeObject().method) returns True\n    - Bound method inspect.isfunction(SomeObject().method) returns False\n    - Bound hasattr(SomeObject().method, 'im_class') returns True\n\n    In Python 3:\n    - Unbound method inspect.ismethod(SomeObject.method) returns False\n    - Unbound inspect.isfunction(SomeObject.method) returns True\n    - Unbound hasattr(SomeObject.method, 'im_class') returns False\n    - Bound method inspect.ismethod(SomeObject().method) returns True\n    - Bound method inspect.isfunction(SomeObject().method) returns False\n    - Bound hasattr(SomeObject().method, 'im_class') returns False\n\n    This method tries to consolidate the approach for retrieving the\n    enclosing type of a bound/unbound method and functions."
  },
  {
    "code": "def get_all_lines(self):\n        output = []\n        line = []\n        lineno = 1\n        for char in self.string:\n            line.append(char)\n            if char == '\\n':\n                output.append(SourceLine(''.join(line), lineno))\n                line = []\n                lineno += 1\n        if line:\n            output.append(SourceLine(''.join(line), lineno))\n        return output",
    "docstring": "Return all lines of the SourceString as a list of SourceLine's."
  },
  {
    "code": "def fetch_by_refresh_token(self, refresh_token):\n        row = self.fetchone(self.fetch_by_refresh_token_query, refresh_token)\n        if row is None:\n            raise AccessTokenNotFound\n        scopes = self._fetch_scopes(access_token_id=row[0])\n        data = self._fetch_data(access_token_id=row[0])\n        return self._row_to_token(data=data, scopes=scopes, row=row)",
    "docstring": "Retrieves an access token by its refresh token.\n\n        :param refresh_token: The refresh token of an access token as a `str`.\n\n        :return: An instance of :class:`oauth2.datatype.AccessToken`.\n\n        :raises: :class:`oauth2.error.AccessTokenNotFound` if not access token\n                 could be retrieved."
  },
  {
    "code": "def rename_fmapm(bids_base, basename):\n    files = dict()\n    for ext in ['nii.gz', 'json']:\n        for echo in [1, 2]:\n            fname = '{0}_e{1}.{2}'.format(basename, echo, ext)\n            src = os.path.join(bids_base, 'fmap', fname)\n            if os.path.exists(src):\n                dst = src.replace(\n                    'magnitude_e{0}'.format(echo),\n                    'magnitude{0}'.format(echo)\n                )\n                logger.debug('renaming %s to %s', src, dst)\n                os.rename(src, dst)\n                files[ext] = dst\n    return files",
    "docstring": "Rename magnitude fieldmap file to BIDS specification"
  },
  {
    "code": "def after(parents, func=None):\n    if func is None:\n        return lambda f: after(parents, f)\n    dep = Dependent(parents, func)\n    for parent in parents:\n        if parent.complete:\n            dep._incoming(parent, parent.value)\n        else:\n            parent._children.append(weakref.ref(dep))\n    return dep",
    "docstring": "Create a new Future whose completion depends on parent futures\n\n    The new future will have a function that it calls once all its parents\n    have completed, the return value of which will be its final value.\n    There is a special case, however, in which the dependent future's\n    callback returns a future or list of futures. In those cases, waiting\n    on the dependent will also wait for all those futures, and the result\n    (or list of results) of those future(s) will then be the final value.\n\n    :param parents:\n        A list of futures, all of which must be complete before the\n        dependent's function runs.\n    :type parents: list\n\n    :param function func:\n        The function to determine the value of the dependent future. It\n        will take as many arguments as it has parents, and they will be the\n        results of those futures.\n\n    :returns:\n        a :class:`Dependent`, which is a subclass of :class:`Future` and\n        has all its capabilities."
  },
  {
    "code": "def _get_destcache(self, graph, orig, branch, turn, tick, *, forward):\n        destcache, destcache_lru, get_keycachelike, successors, adds_dels_sucpred = self._get_destcache_stuff\n        lru_append(destcache, destcache_lru, ((graph, orig, branch), turn, tick), KEYCACHE_MAXSIZE)\n        return get_keycachelike(\n            destcache, successors, adds_dels_sucpred, (graph, orig),\n            branch, turn, tick, forward=forward\n        )",
    "docstring": "Return a set of destination nodes succeeding ``orig``"
  },
  {
    "code": "def parse_skypipe_data_stream(msg, for_pipe):\n    header = str(msg.pop(0))\n    command = str(msg.pop(0))\n    pipe_name = str(msg.pop(0))\n    data = str(msg.pop(0))\n    if header != SP_HEADER: return\n    if pipe_name != for_pipe: return\n    if command != SP_CMD_DATA: return\n    if data == SP_DATA_EOF:\n        raise EOFError()\n    else:\n        return data",
    "docstring": "May return data from skypipe message or raises EOFError"
  },
  {
    "code": "def weighted_std(values, weights):\n    average = np.average(values, weights=weights)\n    variance = np.average((values-average)**2, weights=weights)\n    return np.sqrt(variance)",
    "docstring": "Calculate standard deviation weighted by errors"
  },
  {
    "code": "def create_default_profiles(apps, schema_editor):\n    Profile = apps.get_model(\"edxval\", \"Profile\")\n    for profile in DEFAULT_PROFILES:\n        Profile.objects.get_or_create(profile_name=profile)",
    "docstring": "Add default profiles"
  },
  {
    "code": "def get_order_container(self, quote_id):\n        quote = self.client['Billing_Order_Quote']\n        container = quote.getRecalculatedOrderContainer(id=quote_id)\n        return container",
    "docstring": "Generate an order container from a quote object.\n\n        :param quote_id: ID number of target quote"
  },
  {
    "code": "def PrintTags(self, file):\n        print >>file, '/* Tag definition for %s */' % self._name\n        print >>file, 'enum %s_ {' % self._name.lower()\n        for entry in self._entries:\n            print >>file, '  %s=%d,' % (self.EntryTagName(entry),\n                                        entry.Tag())\n        print >>file, '  %s_MAX_TAGS' % (self._name.upper())\n        print >>file, '};\\n'",
    "docstring": "Prints the tag definitions for a structure."
  },
  {
    "code": "def get(self, name):\n        if not self.get_block(r'route-map\\s%s\\s\\w+\\s\\d+' % name):\n            return None\n        return self._parse_entries(name)",
    "docstring": "Provides a method to retrieve all routemap configuration\n        related to the name attribute.\n\n        Args:\n            name (string): The name of the routemap.\n\n        Returns:\n            None if the specified routemap does not exists. If the routermap\n            exists a dictionary will be provided as follows::\n\n                {\n                    'deny': {\n                            30: {\n                                    'continue': 200,\n                                    'description': None,\n                                    'match': ['as 2000',\n                                              'source-protocol ospf',\n                                              'interface Ethernet2'],\n                                    'set': []\n                                }\n                            },\n                    'permit': {\n                            10: {\n                                    'continue': 100,\n                                    'description': None,\n                                    'match': ['interface Ethernet1'],\n                                    'set': ['tag 50']},\n                            20: {\n                                    'continue': 200,\n                                    'description': None,\n                                    'match': ['as 2000',\n                                              'source-protocol ospf',\n                                              'interface Ethernet2'],\n                                    'set': []\n                                }\n                            }\n                }"
  },
  {
    "code": "def add_arguments(self, parser):\n        parser.add_argument('--length', default=self.length,\n                            type=int, help=_('SECRET_KEY length default=%d' % self.length))\n        parser.add_argument('--alphabet', default=self.allowed_chars,\n                            type=str, help=_('alphabet to use default=%s' % self.allowed_chars))",
    "docstring": "Define optional arguments with default values"
  },
  {
    "code": "def apply_purging(self, catalogue, flag_vector, magnitude_table):\n        output_catalogue = deepcopy(catalogue)\n        if magnitude_table is not None:\n            if flag_vector is not None:\n                output_catalogue.catalogue_mt_filter(\n                    magnitude_table, flag_vector)\n                return output_catalogue\n            else:\n                output_catalogue.catalogue_mt_filter(\n                    magnitude_table)\n                return output_catalogue\n        if flag_vector is not None:\n            output_catalogue.purge_catalogue(flag_vector)\n        return output_catalogue",
    "docstring": "Apply all the various purging conditions, if specified.\n\n        :param catalogue:\n            Earthquake catalogue as instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue`\n        :param numpy.array flag_vector:\n            Boolean vector specifying whether each event is valid (therefore\n            written) or otherwise\n        :param numpy.ndarray magnitude_table:\n            Magnitude-time table specifying the year and magnitudes of\n            completeness"
  },
  {
    "code": "def _generate_genesis_block(self):\n        genesis_header = block_pb2.BlockHeader(\n            block_num=0,\n            previous_block_id=NULL_BLOCK_IDENTIFIER,\n            signer_public_key=self._identity_signer.get_public_key().as_hex())\n        return BlockBuilder(genesis_header)",
    "docstring": "Returns a blocker wrapper with the basics of the block header in place"
  },
  {
    "code": "def requests_for_variant(self, request, variant_id=None):\n        requests = ProductRequest.objects.filter(variant__id=variant_id)\n        serializer = self.serializer_class(requests, many=True)\n        return Response(data=serializer.data, status=status.HTTP_200_OK)",
    "docstring": "Get all the requests for a single variant"
  },
  {
    "code": "def to_string(node):\n    with io.BytesIO() as f:\n        write([node], f)\n        return f.getvalue().decode('utf-8')",
    "docstring": "Convert a node into a string in NRML format"
  },
  {
    "code": "def create(symbol, X, y=None, ctx=None,\n               num_epoch=None, epoch_size=None, optimizer='sgd', initializer=Uniform(0.01),\n               eval_data=None, eval_metric='acc',\n               epoch_end_callback=None, batch_end_callback=None,\n               kvstore='local', logger=None, work_load_list=None,\n               eval_end_callback=LogValidationMetricsCallback(),\n               eval_batch_end_callback=None, **kwargs):\n        model = FeedForward(symbol, ctx=ctx, num_epoch=num_epoch,\n                            epoch_size=epoch_size,\n                            optimizer=optimizer, initializer=initializer, **kwargs)\n        model.fit(X, y, eval_data=eval_data, eval_metric=eval_metric,\n                  epoch_end_callback=epoch_end_callback,\n                  batch_end_callback=batch_end_callback,\n                  kvstore=kvstore,\n                  logger=logger,\n                  work_load_list=work_load_list,\n                  eval_end_callback=eval_end_callback,\n                  eval_batch_end_callback=eval_batch_end_callback)\n        return model",
    "docstring": "Functional style to create a model.\n        This function is more consistent with functional\n        languages such as R, where mutation is not allowed.\n\n        Parameters\n        ----------\n        symbol : Symbol\n            The symbol configuration of a computation network.\n        X : DataIter\n            Training data.\n        y : numpy.ndarray, optional\n            If `X` is a ``numpy.ndarray``, `y` must be set.\n        ctx : Context or list of Context, optional\n            The device context of training and prediction.\n            To use multi-GPU training, pass in a list of GPU contexts.\n        num_epoch : int, optional\n            The number of training epochs(epochs).\n        epoch_size : int, optional\n            Number of batches in a epoch. In default, it is set to\n            ``ceil(num_train_examples / batch_size)``.\n        optimizer : str or Optimizer, optional\n            The name of the chosen optimizer, or an optimizer object, used for training.\n        initializer : initializer function, optional\n            The initialization scheme used.\n        eval_data : DataIter or numpy.ndarray pair\n            If `eval_set` is ``numpy.ndarray`` pair, it should\n            be (`valid_data`, `valid_label`).\n        eval_metric : metric.EvalMetric or str or callable\n            The evaluation metric. Can be the name of an evaluation metric\n            or a custom evaluation function that returns statistics\n            based on a minibatch.\n        epoch_end_callback : callable(epoch, symbol, arg_params, aux_states)\n            A callback that is invoked at end of each epoch.\n            This can be used to checkpoint model each epoch.\n        batch_end_callback: callable(epoch)\n            A callback that is invoked at end of each batch for print purposes.\n        kvstore: KVStore or str, optional\n           The KVStore or a string kvstore type: 'local', 'dist_sync', 'dis_async'.\n           Defaults to 'local', often no need to change for single machine.\n        logger : logging logger, optional\n            When not specified, default logger will be used.\n        work_load_list : list of float or int, optional\n            The list of work load for different devices,\n            in the same order as `ctx`."
  },
  {
    "code": "async def get_default_min_hwe_kernel(cls) -> typing.Optional[str]:\n        data = await cls.get_config(\"default_min_hwe_kernel\")\n        return None if data is None or data == \"\" else data",
    "docstring": "Default minimum kernel version.\n\n        The minimum kernel version used on new and commissioned nodes."
  },
  {
    "code": "def http_context(self, worker_ctx):\n        http = {}\n        if isinstance(worker_ctx.entrypoint, HttpRequestHandler):\n            try:\n                request = worker_ctx.args[0]\n                try:\n                    if request.mimetype == 'application/json':\n                        data = request.data\n                    else:\n                        data = request.form\n                except ClientDisconnected:\n                    data = {}\n                urlparts = urlsplit(request.url)\n                http.update({\n                    'url': '{}://{}{}'.format(\n                        urlparts.scheme, urlparts.netloc, urlparts.path\n                    ),\n                    'query_string': urlparts.query,\n                    'method': request.method,\n                    'data': data,\n                    'headers': dict(get_headers(request.environ)),\n                    'env': dict(get_environ(request.environ)),\n                })\n            except:\n                pass\n        self.client.http_context(http)",
    "docstring": "Attempt to extract HTTP context if an HTTP entrypoint was used."
  },
  {
    "code": "def _decade_ranges_in_date_range(self, begin_date, end_date):\n        begin_dated = begin_date.year / 10\n        end_dated = end_date.year / 10\n        decades = []\n        for d in range(begin_dated, end_dated + 1):\n            decades.append('{}-{}'.format(d * 10, d * 10 + 9))\n        return decades",
    "docstring": "Return a list of decades which is covered by date range."
  },
  {
    "code": "def split_phylogeny(p, level=\"s\"):\n    level = level+\"__\"\n    result = p.split(level)\n    return result[0]+level+result[1].split(\";\")[0]",
    "docstring": "Return either the full or truncated version of a QIIME-formatted taxonomy string.\n\n    :type p: str\n    :param p: A QIIME-formatted taxonomy string: k__Foo; p__Bar; ...\n\n    :type level: str\n    :param level: The different level of identification are kingdom (k), phylum (p),\n                  class (c),order (o), family (f), genus (g) and species (s). If level is\n                  not provided, the default level of identification is species.\n\n    :rtype: str\n    :return: A QIIME-formatted taxonomy string up to the classification given\n            by param level."
  },
  {
    "code": "def _check_trim(data):\n    trim = data[\"algorithm\"].get(\"trim_reads\")\n    if trim:\n        if trim == \"fastp\" and data[\"algorithm\"].get(\"align_split_size\") is not False:\n            raise ValueError(\"In sample %s, `trim_reads: fastp` currently requires `align_split_size: false`\" %\n                             (dd.get_sample_name(data)))",
    "docstring": "Check for valid values for trim_reads."
  },
  {
    "code": "def touch_member(config, dcs):\n    p = Postgresql(config['postgresql'])\n    p.set_state('running')\n    p.set_role('master')\n    def restapi_connection_string(config):\n        protocol = 'https' if config.get('certfile') else 'http'\n        connect_address = config.get('connect_address')\n        listen = config['listen']\n        return '{0}://{1}/patroni'.format(protocol, connect_address or listen)\n    data = {\n        'conn_url': p.connection_string,\n        'api_url': restapi_connection_string(config['restapi']),\n        'state': p.state,\n        'role': p.role\n    }\n    return dcs.touch_member(data, permanent=True)",
    "docstring": "Rip-off of the ha.touch_member without inter-class dependencies"
  },
  {
    "code": "def repeat(coro, times=1, step=1, limit=1, loop=None):\n    assert_corofunction(coro=coro)\n    times = max(int(times), 1)\n    iterable = range(1, times + 1, step)\n    return (yield from map(coro, iterable, limit=limit, loop=loop))",
    "docstring": "Executes the coroutine function ``x`` number of  times,\n    and accumulates results in order as you would use with ``map``.\n\n    Execution concurrency is configurable using ``limit`` param.\n\n    This function is a coroutine.\n\n    Arguments:\n        coro (coroutinefunction): coroutine function to schedule.\n        times (int): number of times to execute the coroutine.\n        step (int): increment iteration step, as with ``range()``.\n        limit (int): concurrency execution limit. Defaults to 10.\n        loop (asyncio.BaseEventLoop): optional event loop to use.\n\n    Raises:\n        TypeError: if coro is not a coroutine function.\n\n    Returns:\n        list: accumulated yielded values returned by coroutine.\n\n    Usage::\n\n        async def mul_2(num):\n            return num * 2\n\n        await paco.repeat(mul_2, times=5)\n        # => [2, 4, 6, 8, 10]"
  },
  {
    "code": "def generate_lars_path(weighted_data, weighted_labels):\n        x_vector = weighted_data\n        alphas, _, coefs = lars_path(x_vector,\n                                     weighted_labels,\n                                     method='lasso',\n                                     verbose=False)\n        return alphas, coefs",
    "docstring": "Generates the lars path for weighted data.\n\n        Args:\n            weighted_data: data that has been weighted by kernel\n            weighted_label: labels, weighted by kernel\n\n        Returns:\n            (alphas, coefs), both are arrays corresponding to the\n            regularization parameter and coefficients, respectively"
  },
  {
    "code": "def list_security_groups(call=None):\n    if call == 'action':\n        raise SaltCloudSystemExit(\n            'The list_security_groups function must be called with -f or --function.'\n        )\n    server, user, password = _get_xml_rpc()\n    auth = ':'.join([user, password])\n    secgroup_pool = server.one.secgrouppool.info(auth, -2, -1, -1)[1]\n    groups = {}\n    for group in _get_xml(secgroup_pool):\n        groups[group.find('NAME').text] = _xml_to_dict(group)\n    return groups",
    "docstring": "Lists all security groups available to the user and the user's groups.\n\n    .. versionadded:: 2016.3.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -f list_security_groups opennebula"
  },
  {
    "code": "def NOT(fn):\n    @chainable\n    def validator(v):\n        try:\n            fn(v)\n        except ValueError:\n            return v\n        raise ValueError('invalid')\n    return validator",
    "docstring": "Reverse the effect of a chainable validator function"
  },
  {
    "code": "def terms_iterator_for_elasticsearch(fo: IO, index_name: str):\n    species_list = config[\"bel_resources\"].get(\"species_list\", [])\n    fo.seek(0)\n    with gzip.open(fo, \"rt\") as f:\n        for line in f:\n            term = json.loads(line)\n            if \"term\" not in term:\n                continue\n            term = term[\"term\"]\n            species_id = term.get(\"species_id\", None)\n            if species_list and species_id and species_id not in species_list:\n                continue\n            all_term_ids = set()\n            for term_id in [term[\"id\"]] + term.get(\"alt_ids\", []):\n                all_term_ids.add(term_id)\n                all_term_ids.add(lowercase_term_id(term_id))\n            term[\"alt_ids\"] = copy.copy(list(all_term_ids))\n            yield {\n                \"_op_type\": \"index\",\n                \"_index\": index_name,\n                \"_type\": \"term\",\n                \"_id\": term[\"id\"],\n                \"_source\": copy.deepcopy(term),\n            }",
    "docstring": "Add index_name to term documents for bulk load"
  },
  {
    "code": "def batch_iter(data, batch_size, num_epochs):\n    data = np.array(data)\n    data_size = len(data)\n    num_batches_per_epoch = int(len(data)/batch_size) + 1\n    for epoch in range(num_epochs):\n        shuffle_indices = np.random.permutation(np.arange(data_size))\n        shuffled_data = data[shuffle_indices]\n        for batch_num in range(num_batches_per_epoch):\n            start_index = batch_num * batch_size\n            end_index = min((batch_num + 1) * batch_size, data_size)\n            yield shuffled_data[start_index:end_index]",
    "docstring": "Generates a batch iterator for a dataset."
  },
  {
    "code": "def to_safe(self, word):\n        regex = \"[^A-Za-z0-9\\_\"\n        if not self.replace_dash_in_groups:\n            regex += \"\\-\"\n        return re.sub(regex + \"]\", \"_\", word)",
    "docstring": "Converts 'bad' characters in a string to underscores so they can be used as Ansible groups"
  },
  {
    "code": "def _begin_write(session: UpdateSession,\n                 loop: asyncio.AbstractEventLoop,\n                 rootfs_file_path: str):\n    session.set_progress(0)\n    session.set_stage(Stages.WRITING)\n    write_future = asyncio.ensure_future(loop.run_in_executor(\n        None, file_actions.write_update, rootfs_file_path,\n        session.set_progress))\n    def write_done(fut):\n        exc = fut.exception()\n        if exc:\n            session.set_error(getattr(exc, 'short', str(type(exc))),\n                              str(exc))\n        else:\n            session.set_stage(Stages.DONE)\n    write_future.add_done_callback(write_done)",
    "docstring": "Start the write process."
  },
  {
    "code": "def record(self):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('UDF Logical Volume Integrity Descriptor not initialized')\n        rec = struct.pack(self.FMT, b'\\x00' * 16,\n                          self.recording_date.record(), 1, 0, 0,\n                          self.logical_volume_contents_use.record(), 1,\n                          self.length_impl_use, self.free_space_table,\n                          self.size_table,\n                          self.logical_volume_impl_use.record())[16:]\n        return self.desc_tag.record(rec) + rec",
    "docstring": "A method to generate the string representing this UDF Logical Volume\n        Integrity Descriptor.\n\n        Parameters:\n         None.\n        Returns:\n         A string representing this UDF Logical Volume Integrity Descriptor."
  },
  {
    "code": "def parse_http_accept_header(header):\n    components = [item.strip() for item in header.split(',')]\n    l = []\n    for component in components:\n        if ';' in component:\n            subcomponents = [item.strip() for item in component.split(';')]\n            l.append(\n                (\n                    subcomponents[0],\n                    subcomponents[1][2:]\n                )\n            )\n        else:\n            l.append((component, '1'))\n    l.sort(\n        key = lambda i: i[1],\n        reverse = True\n    )\n    content_types = []\n    for i in l:\n        content_types.append(i[0])\n    return content_types",
    "docstring": "Return a list of content types listed in the HTTP Accept header\n    ordered by quality.\n\n    :param header: A string describing the contents of the HTTP Accept header."
  },
  {
    "code": "def generic_modis5kmto1km(*data5km):\n    cols5km = np.arange(2, 1354, 5)\n    cols1km = np.arange(1354)\n    lines = data5km[0].shape[0] * 5\n    rows5km = np.arange(2, lines, 5)\n    rows1km = np.arange(lines)\n    along_track_order = 1\n    cross_track_order = 3\n    satint = Interpolator(list(data5km),\n                          (rows5km, cols5km),\n                          (rows1km, cols1km),\n                          along_track_order,\n                          cross_track_order,\n                          chunk_size=10)\n    satint.fill_borders(\"y\", \"x\")\n    return satint.interpolate()",
    "docstring": "Getting 1km data for modis from 5km tiepoints."
  },
  {
    "code": "def daterange(self, datecol, date_start, op, **args):\n        df = self._daterange(datecol, date_start, op, **args)\n        if df is None:\n            self.err(\"Can not select date range data\")\n        self.df = df",
    "docstring": "Returns rows in a date range"
  },
  {
    "code": "def set_primary_contact(self, email):\n        params = {\"email\": email}\n        response = self._put(self.uri_for('primarycontact'), params=params)\n        return json_to_py(response)",
    "docstring": "assigns the primary contact for this client"
  },
  {
    "code": "def get_content_descendants_by_type(self, content_id, child_type, expand=None, start=None, limit=None,\n                                        callback=None):\n        params = {}\n        if expand:\n            params[\"expand\"] = expand\n        if start is not None:\n            params[\"start\"] = int(start)\n        if limit is not None:\n            params[\"limit\"] = int(limit)\n        return self._service_get_request(\"rest/api/content/{id}/descendant/{type}\"\n                                         \"\".format(id=content_id, type=child_type), params=params, callback=callback)",
    "docstring": "Returns the direct descendants of a piece of Content, limited to a single descendant type.\n\n        The {@link ContentType}(s) of the descendants returned is specified by the \"type\" path parameter in the request.\n\n        Currently the only supported descendants are comment descendants of non-comment Content.\n        :param content_id (string): A string containing the id of the content to retrieve descendants for\n        :param child_type (string): A {@link ContentType} to filter descendants on.\n        :param expand (string): OPTIONAL: A comma separated list of properties to expand on the descendants.\n                                Default: Empty\n        :param start (int): OPTIONAL: The index of the first item within the result set that should be returned.\n                            Default: 0.\n        :param limit (int): OPTIONAL: How many items should be returned after the start index.\n                            Default: 25 or site limit.\n        :param callback: OPTIONAL: The callback to execute on the resulting data, before the method returns.\n                         Default: None (no callback, raw data returned).\n        :return: The JSON data returned from the content/{id}/descendant/{type} endpoint, or the results of the\n                 callback. Will raise requests.HTTPError on bad input, potentially."
  },
  {
    "code": "def filterGraph(graph, node_fnc):\n\t\tnodes = filter(lambda l: node_fnc(l), graph.nodes())\n\t\tedges = {}\n\t\tgedges = graph.edges()\n\t\tfor u in gedges:\n\t\t\tif u not in nodes:\n\t\t\t\tcontinue\n\t\t\tfor v in gedges[u]:\n\t\t\t\tif v not in nodes:\n\t\t\t\t\tcontinue\n\t\t\t\ttry:\n\t\t\t\t\tedges[u].append(v)\n\t\t\t\texcept KeyError:\n\t\t\t\t\tedges[u] = [v]\n\t\treturn Graph(nodes, edges)",
    "docstring": "Remove all nodes for with node_fnc does not hold"
  },
  {
    "code": "def angprofile(self, **kwargs):\n        kwargs_copy = self.base_dict.copy()\n        kwargs_copy.update(**kwargs)\n        self._replace_none(kwargs_copy)        \n        localpath = NameFactory.angprofile_format.format(**kwargs_copy)\n        if kwargs.get('fullpath', False):\n            return self.fullpath(localpath=localpath)\n        return localpath",
    "docstring": "return the file name for sun or moon angular profiles"
  },
  {
    "code": "def get_config(config_file):\n    config = {}\n    tobool = lambda s: True if s.lower() == 'true' else False\n    if config_file:\n        try:\n            f = open(config_file, 'r')\n        except:\n            print (\"Unable to open configuration file '{0}'\".format(config_file))\n        else:\n            for line in f.readlines():\n                if len(line.strip()):\n                    key, value = line.split(\"=\", 1)\n                    key, value = key.strip(), value.strip()\n                    if key in ['init2class', 'first_line', 'convert_only']:\n                        value = tobool(value)\n                    config[key] = value\n    return config",
    "docstring": "Get the configuration from a file.\n\n    @param config_file: the configuration file\n    @return: the configuration\n    @rtype: dict"
  },
  {
    "code": "def _encode_params(**kw):\n    def _encode(L, k, v):\n        if isinstance(v, unicode):\n            L.append('%s=%s' % (k, urllib.quote(v.encode('utf-8'))))\n        elif isinstance(v, str):\n            L.append('%s=%s' % (k, urllib.quote(v)))\n        elif isinstance(v, collections.Iterable):\n            for x in v:\n                _encode(L, k, x)\n        else:\n            L.append('%s=%s' % (k, urllib.quote(str(v))))\n    args = []\n    for k, v in kw.iteritems():\n        _encode(args, k, v)\n    return '&'.join(args)",
    "docstring": "Do url-encode parameters\n\n    >>> _encode_params(a=1, b='R&D')\n    'a=1&b=R%26D'\n    >>> _encode_params(a=u'\\u4e2d\\u6587', b=['A', 'B', 123])\n    'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123'"
  },
  {
    "code": "def sconsign_dir(node):\n    if not node._sconsign:\n        import SCons.SConsign\n        node._sconsign = SCons.SConsign.ForDirectory(node)\n    return node._sconsign",
    "docstring": "Return the .sconsign file info for this directory,\n    creating it first if necessary."
  },
  {
    "code": "def mapPriority(levelno):\n        if levelno <= _logging.DEBUG:\n            return LOG_DEBUG\n        elif levelno <= _logging.INFO:\n            return LOG_INFO\n        elif levelno <= _logging.WARNING:\n            return LOG_WARNING\n        elif levelno <= _logging.ERROR:\n            return LOG_ERR\n        elif levelno <= _logging.CRITICAL:\n            return LOG_CRIT\n        else:\n            return LOG_ALERT",
    "docstring": "Map logging levels to journald priorities.\n\n        Since Python log level numbers are \"sparse\", we have\n        to map numbers in between the standard levels too."
  },
  {
    "code": "def line(self, x_0, y_0, x_1, y_1, color):\n        d_x = abs(x_1 - x_0)\n        d_y = abs(y_1 - y_0)\n        x, y = x_0, y_0\n        s_x = -1 if x_0 > x_1 else 1\n        s_y = -1 if y_0 > y_1 else 1\n        if d_x > d_y:\n            err = d_x / 2.0\n            while x != x_1:\n                self.pixel(x, y, color)\n                err -= d_y\n                if err < 0:\n                    y += s_y\n                    err += d_x\n                x += s_x\n        else:\n            err = d_y / 2.0\n            while y != y_1:\n                self.pixel(x, y, color)\n                err -= d_x\n                if err < 0:\n                    x += s_x\n                    err += d_y\n                y += s_y\n        self.pixel(x, y, color)",
    "docstring": "Bresenham's line algorithm"
  },
  {
    "code": "def flush_profile_data(self):\n        with self.lock:\n            events = self.events\n            self.events = []\n        if self.worker.mode == ray.WORKER_MODE:\n            component_type = \"worker\"\n        else:\n            component_type = \"driver\"\n        self.worker.raylet_client.push_profile_events(\n            component_type, ray.UniqueID(self.worker.worker_id),\n            self.worker.node_ip_address, events)",
    "docstring": "Push the logged profiling data to the global control store."
  },
  {
    "code": "def get_thumbnail_format(self):\n        if self.field.thumbnail_format:\n            return self.field.thumbnail_format.lower()\n        else:\n            filename_split = self.name.rsplit('.', 1)\n            return filename_split[-1]",
    "docstring": "Determines the target thumbnail type either by looking for a format\n        override specified at the model level, or by using the format the\n        user uploaded."
  },
  {
    "code": "def savings_score(y_true, y_pred, cost_mat):\n    y_true = column_or_1d(y_true)\n    y_pred = column_or_1d(y_pred)\n    n_samples = len(y_true)\n    cost_base = min(cost_loss(y_true, np.zeros(n_samples), cost_mat),\n                    cost_loss(y_true, np.ones(n_samples), cost_mat))\n    cost = cost_loss(y_true, y_pred, cost_mat)\n    return 1.0 - cost / cost_base",
    "docstring": "Savings score.\n\n    This function calculates the savings cost of using y_pred on y_true with\n    cost-matrix cost-mat, as the difference of y_pred and the cost_loss of a naive\n    classification model.\n\n    Parameters\n    ----------\n    y_true : array-like or label indicator matrix\n        Ground truth (correct) labels.\n\n    y_pred : array-like or label indicator matrix\n        Predicted labels, as returned by a classifier.\n\n    cost_mat : array-like of shape = [n_samples, 4]\n        Cost matrix of the classification problem\n        Where the columns represents the costs of: false positives, false negatives,\n        true positives and true negatives, for each example.\n\n    Returns\n    -------\n    score : float\n        Savings of a using y_pred on y_true with cost-matrix cost-mat\n\n        The best performance is 1.\n\n    References\n    ----------\n    .. [1] A. Correa Bahnsen, A. Stojanovic, D.Aouada, B, Ottersten,\n           `\"Improving Credit Card Fraud Detection with Calibrated Probabilities\" <http://albahnsen.com/files/%20Improving%20Credit%20Card%20Fraud%20Detection%20by%20using%20Calibrated%20Probabilities%20-%20Publish.pdf>`__, in Proceedings of the fourteenth SIAM International Conference on Data Mining,\n           677-685, 2014.\n\n    See also\n    --------\n    cost_loss\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from costcla.metrics import savings_score, cost_loss\n    >>> y_pred = [0, 1, 0, 0]\n    >>> y_true = [0, 1, 1, 0]\n    >>> cost_mat = np.array([[4, 1, 0, 0], [1, 3, 0, 0], [2, 3, 0, 0], [2, 1, 0, 0]])\n    >>> savings_score(y_true, y_pred, cost_mat)\n    0.5"
  },
  {
    "code": "def dice(self, n, d):\n        for i in range(0, n):\n            yield self.roll_die(d)",
    "docstring": "Roll ``n`` dice with ``d`` faces, and yield the results.\n\n        This is an iterator. You'll get the result of each die in\n        successon."
  },
  {
    "code": "def cleanup(self, release):\n        log.info(\"Performing cleanup.\")\n        return execute_actioncollection(release._releasefile, actioncollection=release._cleanup, confirm=True)",
    "docstring": "Perform cleanup actions on the releasefile of the given release\n\n        This is inteded to be used in a action unit.\n\n        :param release: the release with the releasefile and cleanup actions\n        :type release: :class:`Release`\n        :returns: the action status of the cleanup actions\n        :rtype: :class:`ActionStatus`\n        :raises: None"
  },
  {
    "code": "def _get_action(trans):\n    mark_action = {\n        '^': (_Action.ADD_MARK, Mark.HAT),\n        '+': (_Action.ADD_MARK, Mark.BREVE),\n        '*': (_Action.ADD_MARK, Mark.HORN),\n        '-': (_Action.ADD_MARK, Mark.BAR),\n    }\n    accent_action = {\n        '\\\\': (_Action.ADD_ACCENT, Accent.GRAVE),\n        '/': (_Action.ADD_ACCENT, Accent.ACUTE),\n        '?': (_Action.ADD_ACCENT, Accent.HOOK),\n        '~': (_Action.ADD_ACCENT, Accent.TIDLE),\n        '.': (_Action.ADD_ACCENT, Accent.DOT),\n    }\n    if trans[0] in ('<', '+'):\n        return _Action.ADD_CHAR, trans[1]\n    if trans[0] == \"_\":\n        return _Action.UNDO, trans[1:]\n    if len(trans) == 2:\n        return mark_action[trans[1]]\n    else:\n        return accent_action[trans[0]]",
    "docstring": "Return the action inferred from the transformation `trans`.\n    and the parameter going with this action\n    An _Action.ADD_MARK goes with a Mark\n    while an _Action.ADD_ACCENT goes with an Accent"
  },
  {
    "code": "def form_upload_valid(self, form):\n        self.current_step = self.STEP_LINES\n        lines = form.cleaned_data['file']\n        initial_lines = [dict(zip(self.get_columns(), line)) for line in lines]\n        inner_form = self.get_form(self.get_form_class(),\n            data=None,\n            files=None,\n            initial=initial_lines,\n        )\n        return self.render_to_response(self.get_context_data(form=inner_form))",
    "docstring": "Handle a valid upload form."
  },
  {
    "code": "def CAPM(self, benchmark, has_const=False, use_const=True):\n        return ols.OLS(\n            y=self, x=benchmark, has_const=has_const, use_const=use_const\n        )",
    "docstring": "Interface to OLS regression against `benchmark`.\n\n        `self.alpha()`, `self.beta()` and several other methods\n        stem from here.  For the full method set, see\n        `pyfinance.ols.OLS`.\n\n        Parameters\n        ----------\n        benchmark : {pd.Series, TSeries, pd.DataFrame, np.ndarray}\n            The benchmark securitie(s) to which `self` is compared.\n        has_const : bool, default False\n            Specifies whether `benchmark` includes a user-supplied constant\n            (a column vector).  If False, it is added at instantiation.\n        use_const : bool, default True\n            Whether to include an intercept term in the model output.  Note the\n            difference between `has_const` and `use_const`: the former\n            specifies whether a column vector of 1s is included in the\n            input; the latter specifies whether the model itself\n            should include a constant (intercept) term.  Exogenous\n            data that is ~N(0,1) would have a constant equal to zero;\n            specify use_const=False in this situation.\n\n        Returns\n        -------\n        pyfinance.ols.OLS"
  },
  {
    "code": "def errint(marker, number):\n    marker = stypes.stringToCharP(marker)\n    number = ctypes.c_int(number)\n    libspice.errint_c(marker, number)",
    "docstring": "Substitute an integer for the first occurrence of a marker found\n    in the current long error message.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errint_c.html\n\n    :param marker: A substring of the error message to be replaced.\n    :type marker: str\n    :param number: The integer to substitute for marker.\n    :type number: int"
  },
  {
    "code": "def dumb_css_parser(data):\n    data += ';'\n    importIndex = data.find('@import')\n    while importIndex != -1:\n        data = data[0:importIndex] + data[data.find(';', importIndex) + 1:]\n        importIndex = data.find('@import')\n    elements =  [x.split('{') for x in data.split('}') if '{' in x.strip()]\n    try:\n        elements = dict([(a.strip(), dumb_property_dict(b)) for a, b in elements])\n    except ValueError:\n        elements = {}\n    return elements",
    "docstring": "returns a hash of css selectors, each of which contains a hash of css attributes"
  },
  {
    "code": "def send_sticker(self, chat_id=None, sticker=None, reply_to_message_id=None, reply_markup=None):\n        payload = dict(chat_id=chat_id,\n                       reply_to_message_id=reply_to_message_id,\n                       reply_markup=reply_markup)\n        files = dict(sticker=open(sticker, 'rb'))\n        return Message.from_api(api, **self._post('sendSticker', payload, files))",
    "docstring": "Use this method to send .webp stickers. On success, the sent Message is returned."
  },
  {
    "code": "def wait_until_running(self, callback=None):\n        status = self.machine.scheduler.wait_until_running(\n                self.job, self.worker_config.time_out)\n        if status.running:\n            self.online = True\n            if callback:\n                callback(self)\n        else:\n            raise TimeoutError(\"Timeout while waiting for worker to run: \" +\n                               self.worker_config.name)",
    "docstring": "Waits until the remote worker is running, then calls the callback.\n        Usually, this method is passed to a different thread; the callback\n        is then a function patching results through to the result queue."
  },
  {
    "code": "def get_tgt_for(user):\n    if not settings.CAS_PROXY_CALLBACK:\n        raise CasConfigException(\"No proxy callback set in settings\")\n    try:\n        return Tgt.objects.get(username=user.username)\n    except ObjectDoesNotExist:\n        logger.warning('No ticket found for user {user}'.format(\n            user=user.username\n        ))\n        raise CasTicketException(\"no ticket found for user \" + user.username)",
    "docstring": "Fetch a ticket granting ticket for a given user.\n\n    :param user: UserObj\n\n    :return: TGT or Exepction"
  },
  {
    "code": "def pvals(cls, slice_, axis=0, weighted=True):\n        return cls._factory(slice_, axis, weighted).pvals",
    "docstring": "Wishart CDF values for slice columns as square ndarray.\n\n        Wishart CDF (Cumulative Distribution Function) is calculated to determine\n        statistical significance of slice columns, in relation to all other columns.\n        These values represent the answer to the question \"How much is a particular\n        column different from each other column in the slice\"."
  },
  {
    "code": "def add_version(f):\n    doc = f.__doc__\n    f.__doc__ = \"Version: \" + __version__ + \"\\n\\n\" + doc\n    return f",
    "docstring": "Add the version of wily to the help heading.\n\n    :param f: function to decorate\n    :return: decorated function"
  },
  {
    "code": "def get_urls(self):\n        urls = super(DashboardSite, self).get_urls()\n        custom_urls = [\n            url(r'^$',\n                self.admin_view(HomeView.as_view()),\n                name='index'),\n            url(r'^logs/', include(logs_urlpatterns(self.admin_view))),\n        ]\n        custom_urls += get_realtime_urls(self.admin_view)\n        del urls[0]\n        return custom_urls + urls",
    "docstring": "Get urls method.\n\n        Returns:\n            list: the list of url objects."
  },
  {
    "code": "def update_appt(self, complex: str, house: str, price: str, square: str, id: str, **kwargs):\n        self.check_house(complex, house)\n        kwargs['price'] = self._format_decimal(price)\n        kwargs['square'] = self._format_decimal(square)\n        self.put('developers/{developer}/complexes/{complex}/houses/{house}/appts/{id}'.format(\n            developer=self.developer,\n            complex=complex,\n            house=house,\n            id=id,\n            price=self._format_decimal(price),\n        ), data=kwargs)",
    "docstring": "Update existing appartment"
  },
  {
    "code": "def cmd_ok(cmd):\n    try:\n        sp.check_call(cmd, stderr=sp.PIPE, stdout=sp.PIPE)\n    except sp.CalledProcessError:\n        pass\n    except:\n        sys.stderr.write(\"{} not found, skipping\\n\".format(cmd))\n        return False\n    return True",
    "docstring": "Returns True if cmd can be run."
  },
  {
    "code": "def custom_decode(encoding):\n    encoding = encoding.lower()\n    alternates = {\n        'big5': 'big5hkscs',\n        'gb2312': 'gb18030',\n        'ascii': 'utf-8',\n        'MacCyrillic': 'cp1251',\n    }\n    if encoding in alternates:\n        return alternates[encoding]\n    else:\n        return encoding",
    "docstring": "Overrides encoding when charset declaration\n       or charset determination is a subset of a larger\n       charset.  Created because of issues with Chinese websites"
  },
  {
    "code": "def update(self, *args):\n        Logger.debug(\"Board: updating\")\n        self.remove_absent_pawns()\n        self.remove_absent_spots()\n        self.remove_absent_arrows()\n        self.add_new_spots()\n        if self.arrow_cls:\n            self.add_new_arrows()\n        self.add_new_pawns()\n        self.spotlayout.finalize_all()\n        Logger.debug(\"Board: updated\")",
    "docstring": "Force an update to match the current state of my character.\n\n        This polls every element of the character, and therefore\n        causes me to sync with the LiSE core for a long time. Avoid\n        when possible."
  },
  {
    "code": "def SetDefaultAgency(self, agency, validate=True):\n    assert isinstance(agency, self._gtfs_factory.Agency)\n    self._default_agency = agency\n    if agency.agency_id not in self._agencies:\n      self.AddAgencyObject(agency, validate=validate)",
    "docstring": "Make agency the default and add it to the schedule if not already added"
  },
  {
    "code": "def reset() -> None:\n    from wdom.document import get_new_document, set_document\n    from wdom.element import Element\n    from wdom.server import _tornado\n    from wdom.window import customElements\n    set_document(get_new_document())\n    _tornado.connections.clear()\n    _tornado.set_application(_tornado.Application())\n    Element._elements_with_id.clear()\n    Element._element_buffer.clear()\n    customElements.reset()",
    "docstring": "Reset all wdom objects.\n\n    This function clear all connections, elements, and resistered custom\n    elements. This function also makes new document/application and set them."
  },
  {
    "code": "def project_activity(index, start, end):\n    results = {\n        \"metrics\": [SubmittedPRs(index, start, end),\n                    ClosedPRs(index, start, end)]\n    }\n    return results",
    "docstring": "Compute the metrics for the project activity section of the enriched\n    github pull requests index.\n\n    Returns a dictionary containing a \"metric\" key. This key contains the\n    metrics for this section.\n\n    :param index: index object\n    :param start: start date to get the data from\n    :param end: end date to get the data upto\n    :return: dictionary with the value of the metrics"
  },
  {
    "code": "def in_degree(self, nbunch=None, t=None):\n        if nbunch in self:\n            return next(self.in_degree_iter(nbunch, t))[1]\n        else:\n            return dict(self.in_degree_iter(nbunch, t))",
    "docstring": "Return the in degree of a node or nodes at time t.\n\n        The node in degree is the number of incoming interaction to that node in a given time frame.\n\n        Parameters\n        ----------\n        nbunch : iterable container, optional (default=all nodes)\n            A container of nodes.  The container will be iterated\n            through once.\n\n        t : snapshot id (default=None)\n            If None will be returned the degree of nodes on the flattened graph.\n\n\n        Returns\n        -------\n        nd : dictionary, or number\n            A dictionary with nodes as keys and degree as values or\n            a number if a single node is specified.\n\n        Examples\n        --------\n        >>> G = dn.DynDiGraph()\n        >>> G.add_interaction(0,1, t=0)\n        >>> G.add_interaction(1,2, t=0)\n        >>> G.add_interaction(2,3, t=0)\n        >>> G.in_degree(0, t=0)\n        1\n        >>> G.in_degree([0,1], t=1)\n        {0: 0, 1: 0}\n        >>> list(G.in_degree([0,1], t=0).values())\n        [1, 2]"
  },
  {
    "code": "async def filterindex(source, func):\n    source = transform.enumerate.raw(source)\n    async with streamcontext(source) as streamer:\n        async for i, item in streamer:\n            if func(i):\n                yield item",
    "docstring": "Filter an asynchronous sequence using the index of the elements.\n\n    The given function is synchronous, takes the index as an argument,\n    and returns ``True`` if the corresponding should be forwarded,\n    ``False`` otherwise."
  },
  {
    "code": "def _build_response(self, resp):\n        self.response.content = resp.content\n        self.response.status_code = resp.status_code\n        self.response.headers = resp.headers",
    "docstring": "Build internal Response object from given response."
  },
  {
    "code": "def build_dump_order(orm_class, orm_classes):\n    if orm_class in orm_classes: return\n    for field_name, field_val in orm_class.schema.fields.items():\n        if field_val.is_ref():\n            build_dump_order(field_val.schema.orm_class, orm_classes)\n    if orm_class not in orm_classes:\n        orm_classes.append(orm_class)",
    "docstring": "pass in an array, when you encounter a ref, call this method again with the array\n    when something has no more refs, then it gets appended to the array and returns, each\n    time something gets through the list they are added, but before they are added to the\n    list it is checked to see if it is already in the listt"
  },
  {
    "code": "def configure_uploadfor(self, ns, definition):\n        upload_for = self.create_upload_func(ns, definition, ns.relation_path, Operation.UploadFor)\n        upload_for.__doc__ = \"Upload a {} for a {}\".format(ns.subject_name, ns.object_name)",
    "docstring": "Register an upload-for relation endpoint.\n\n        The definition's func should be an upload function, which must:\n        - accept kwargs for path data and query string parameters\n        - accept a list of tuples of the form (formname, tempfilepath, filename)\n        - optionall return a resource\n\n        :param ns: the namespace\n        :param definition: the endpoint definition"
  },
  {
    "code": "def _to_graph(self, contexts):\n        prev = None\n        for context in contexts:\n            if prev is None:\n                prev = context\n                continue\n            yield prev[0], context[1], context[0]\n            prev = context",
    "docstring": "This is an iterator that returns each edge of our graph\nwith its two nodes"
  },
  {
    "code": "def exists(self):\n        if '_id' not in self or self['_id'] is None:\n            return False\n        resp = self.r_session.head(self.document_url)\n        if resp.status_code not in [200, 404]:\n            resp.raise_for_status()\n        return resp.status_code == 200",
    "docstring": "Retrieves whether the document exists in the remote database or not.\n\n        :returns: True if the document exists in the remote database,\n            otherwise False"
  },
  {
    "code": "def _sanity_check_construct_result_block(ir_blocks):\n    if not isinstance(ir_blocks[-1], ConstructResult):\n        raise AssertionError(u'The last block was not ConstructResult: {}'.format(ir_blocks))\n    for block in ir_blocks[:-1]:\n        if isinstance(block, ConstructResult):\n            raise AssertionError(u'Found ConstructResult before the last block: '\n                                 u'{}'.format(ir_blocks))",
    "docstring": "Assert that ConstructResult is always the last block, and only the last block."
  },
  {
    "code": "def filenames(directory, tag='', sorted=False, recursive=False):\n    if recursive:\n        f = [os.path.join(directory, f) for directory, _, filename in os.walk(directory) for f in filename if f.find(tag) > -1] \n    else:\n        f = [os.path.join(directory, f) for f in os.listdir(directory) if f.find(tag) > -1]\n    if sorted:\n        f.sort()\n    return f",
    "docstring": "Reads in all filenames from a directory that contain a specified substring.\n\n    Parameters\n    ----------\n    directory : :obj:`str`\n        the directory to read from\n    tag : :obj:`str`\n        optional tag to match in the filenames\n    sorted : bool\n        whether or not to sort the filenames\n    recursive : bool\n        whether or not to search for the files recursively\n\n    Returns\n    -------\n    :obj:`list` of :obj:`str`\n        filenames to read from"
  },
  {
    "code": "def _read_body_until_close(self, response, file):\n        _logger.debug('Reading body until close.')\n        file_is_async = hasattr(file, 'drain')\n        while True:\n            data = yield from self._connection.read(self._read_size)\n            if not data:\n                break\n            self._data_event_dispatcher.notify_read(data)\n            content_data = self._decompress_data(data)\n            if file:\n                file.write(content_data)\n                if file_is_async:\n                    yield from file.drain()\n        content_data = self._flush_decompressor()\n        if file:\n            file.write(content_data)\n            if file_is_async:\n                yield from file.drain()",
    "docstring": "Read the response until the connection closes.\n\n        Coroutine."
  },
  {
    "code": "def parse(binary, **params):\n    binary = io.BytesIO(binary)\n    collection = list()\n    with zipfile.ZipFile(binary, 'r') as zip_:\n        for zip_info in zip_.infolist():\n            content_type, encoding = mimetypes.guess_type(zip_info.filename)\n            content = zip_.read(zip_info)\n            content = content_encodings.get(encoding).decode(content)\n            content = content_types.get(content_type).parse(content, **params)\n            collection.apppend((zip_info.filename, content))\n    return collection",
    "docstring": "Turns a ZIP file into a frozen sample."
  },
  {
    "code": "def get_contents(self):\n        childsigs = [n.get_csig() for n in self.children()]\n        return ''.join(childsigs)",
    "docstring": "The contents of an alias is the concatenation\n        of the content signatures of all its sources."
  },
  {
    "code": "def parse_field(cls: Type[DocumentType], field_name: str, line: str) -> Any:\n        try:\n            match = cls.fields_parsers[field_name].match(line)\n            if match is None:\n                raise AttributeError\n            value = match.group(1)\n        except AttributeError:\n            raise MalformedDocumentError(field_name)\n        return value",
    "docstring": "Parse a document field with regular expression and return the value\n\n        :param field_name: Name of the field\n        :param line: Line string to parse\n        :return:"
  },
  {
    "code": "def supported_types_for_region(region_code):\n    if not _is_valid_region_code(region_code):\n        return set()\n    metadata = PhoneMetadata.metadata_for_region(region_code.upper())\n    return _supported_types_for_metadata(metadata)",
    "docstring": "Returns the types for a given region which the library has metadata for.\n\n    Will not include FIXED_LINE_OR_MOBILE (if numbers in this region could\n    be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would\n    be present) and UNKNOWN.\n\n    No types will be returned for invalid or unknown region codes."
  },
  {
    "code": "def access_request(self, realm, exclusive=False,\n        passive=False, active=False, write=False, read=False):\n        args = AMQPWriter()\n        args.write_shortstr(realm)\n        args.write_bit(exclusive)\n        args.write_bit(passive)\n        args.write_bit(active)\n        args.write_bit(write)\n        args.write_bit(read)\n        self._send_method((30, 10), args)\n        return self.wait(allowed_methods=[\n                          (30, 11),\n                        ])",
    "docstring": "request an access ticket\n\n        This method requests an access ticket for an access realm. The\n        server responds by granting the access ticket.  If the client\n        does not have access rights to the requested realm this causes\n        a connection exception.  Access tickets are a per-channel\n        resource.\n\n        RULE:\n\n            The realm name MUST start with either \"/data\" (for\n            application resources) or \"/admin\" (for server\n            administration resources). If the realm starts with any\n            other path, the server MUST raise a connection exception\n            with reply code 403 (access refused).\n\n        RULE:\n\n            The server MUST implement the /data realm and MAY\n            implement the /admin realm.  The mapping of resources to\n            realms is not defined in the protocol - this is a server-\n            side configuration issue.\n\n        PARAMETERS:\n            realm: shortstr\n\n                name of requested realm\n\n                RULE:\n\n                    If the specified realm is not known to the server,\n                    the server must raise a channel exception with\n                    reply code 402 (invalid path).\n\n            exclusive: boolean\n\n                request exclusive access\n\n                Request exclusive access to the realm. If the server\n                cannot grant this - because there are other active\n                tickets for the realm - it raises a channel exception.\n\n            passive: boolean\n\n                request passive access\n\n                Request message passive access to the specified access\n                realm. Passive access lets a client get information\n                about resources in the realm but not to make any\n                changes to them.\n\n            active: boolean\n\n                request active access\n\n                Request message active access to the specified access\n                realm. Acvtive access lets a client get create and\n                delete resources in the realm.\n\n            write: boolean\n\n                request write access\n\n                Request write access to the specified access realm.\n                Write access lets a client publish messages to all\n                exchanges in the realm.\n\n            read: boolean\n\n                request read access\n\n                Request read access to the specified access realm.\n                Read access lets a client consume messages from queues\n                in the realm.\n\n        The most recently requested ticket is used as the channel's\n        default ticket for any method that requires a ticket."
  },
  {
    "code": "def list_external_jar_dependencies(self, binary):\n    classpath_products = self.context.products.get_data('runtime_classpath')\n    classpath_entries = classpath_products.get_artifact_classpath_entries_for_targets(\n        binary.closure(bfs=True, include_scopes=Scopes.JVM_RUNTIME_SCOPES,\n                       respect_intransitive=True))\n    external_jars = OrderedSet(jar_entry for conf, jar_entry in classpath_entries\n                               if conf == 'default')\n    return [(entry.path, entry.coordinate) for entry in external_jars\n            if not entry.is_excluded_by(binary.deploy_excludes)]",
    "docstring": "Returns the external jar dependencies of the given binary.\n\n    :param binary: The jvm binary target to list transitive external dependencies for.\n    :type binary: :class:`pants.backend.jvm.targets.jvm_binary.JvmBinary`\n    :returns: A list of (jar path, coordinate) tuples.\n    :rtype: list of (string, :class:`pants.java.jar.M2Coordinate`)"
  },
  {
    "code": "def _get_dns_info():\n    dns_list = []\n    try:\n        with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info:\n            lines = dns_info.readlines()\n            for line in lines:\n                if 'nameserver' in line:\n                    dns = line.split()[1].strip()\n                    if dns not in dns_list:\n                        dns_list.append(dns)\n    except IOError:\n        log.warning('Could not get domain\\n')\n    return dns_list",
    "docstring": "return dns list"
  },
  {
    "code": "def body(self):\n        body, _, is_markdown = self._entry_content\n        return TrueCallableProxy(\n            self._get_markup,\n            body,\n            is_markdown) if body else CallableProxy(None)",
    "docstring": "Get the above-the-fold entry body text"
  },
  {
    "code": "def load_json_body(handler):\n    @wraps(handler)\n    def wrapper(event, context):\n        if isinstance(event.get('body'), str):\n            try:\n                event['body'] = json.loads(event['body'])\n            except:\n                return {'statusCode': 400, 'body': 'BAD REQUEST'}\n        return handler(event, context)\n    return wrapper",
    "docstring": "Automatically deserialize event bodies with json.loads.\n\n    Automatically returns a 400 BAD REQUEST if there is an error while parsing.\n\n    Usage::\n\n      >>> from lambda_decorators import load_json_body\n      >>> @load_json_body\n      ... def handler(event, context):\n      ...     return event['body']['foo']\n      >>> handler({'body': '{\"foo\": \"bar\"}'}, object())\n      'bar'\n\n    note that ``event['body']`` is already a dictionary and didn't have to\n    explicitly be parsed."
  },
  {
    "code": "async def rollback(self):\n        if not self._parent._is_active:\n            return\n        await self._do_rollback()\n        self._is_active = False",
    "docstring": "Roll back this transaction."
  },
  {
    "code": "def _discarded_reads1_out_file_name(self):\n        if self.Parameters['-3'].isOn():\n            discarded_reads1 = self._absolute(str(self.Parameters['-3'].Value))\n        else:\n            raise ValueError(\n                \"No discarded-reads1 (flag -3) output path specified\")\n        return discarded_reads1",
    "docstring": "Checks if file name is set for discarded reads1 output.\n           Returns absolute path."
  },
  {
    "code": "def return_file_objects(connection, container, prefix='database'):\n    options = []\n    meta_data = objectstore.get_full_container_list(\n        connection, container, prefix='database')\n    env = ENV.upper()\n    for o_info in meta_data:\n        expected_file = f'database.{ENV}'\n        if o_info['name'].startswith(expected_file):\n            dt = dateparser.parse(o_info['last_modified'])\n            now = datetime.datetime.now()\n            delta = now - dt\n            LOG.debug('AGE: %d %s', delta.days, expected_file)\n            options.append((dt, o_info))\n        options.sort()\n    return options",
    "docstring": "Given connecton and container find database dumps"
  },
  {
    "code": "def reindex(self, force=False, background=True):\n        if background:\n            indexingStrategy = 'background'\n        else:\n            indexingStrategy = 'stoptheworld'\n        url = self._options['server'] + '/secure/admin/jira/IndexReIndex.jspa'\n        r = self._session.get(url, headers=self._options['headers'])\n        if r.status_code == 503:\n            return 503\n        if not r.text.find(\"To perform the re-index now, please go to the\") and force is False:\n            return True\n        if r.text.find('All issues are being re-indexed'):\n            logging.warning(\"JIRA re-indexing is already running.\")\n            return True\n        if r.text.find('To perform the re-index now, please go to the') or force:\n            r = self._session.post(url, headers=self._options['headers'],\n                                   params={\"indexingStrategy\": indexingStrategy, \"reindex\": \"Re-Index\"})\n            if r.text.find('All issues are being re-indexed') != -1:\n                return True\n            else:\n                logging.error(\"Failed to reindex jira, probably a bug.\")\n                return False",
    "docstring": "Start jira re-indexing. Returns True if reindexing is in progress or not needed, or False.\n\n        If you call reindex() without any parameters it will perform a background reindex only if JIRA thinks it should do it.\n\n        :param force: reindex even if JIRA doesn't say this is needed, False by default.\n        :param background: reindex in background, slower but does not impact the users, defaults to True."
  },
  {
    "code": "def getComplexFileData(self, fileInfo, data):\n\t\tresult = fileInfo[fileInfo.find(data + \"</td>\") + len(data + \"</td>\"):]\n\t\tresult = result[:result.find(\"</td>\")]\n\t\tresult = result[result.rfind(\">\") + 1:]\n\t\treturn result",
    "docstring": "Function to initialize the slightly more complicated data for file info"
  },
  {
    "code": "def load_kb_mappings_file(kbname, kbfile, separator):\n    num_added = 0\n    with open(kbfile) as kb_fd:\n        for line in kb_fd:\n            if not line.strip():\n                continue\n            try:\n                key, value = line.split(separator)\n            except ValueError:\n                current_app.logger.error(\"Error splitting: {0}\".format(line))\n                continue\n            add_kb_mapping(kbname, key, value)\n            num_added += 1\n    return num_added",
    "docstring": "Add KB values from file to given KB returning rows added."
  },
  {
    "code": "def flag_time_err(phase_err, time_thresh=0.02):\n    time_err = []\n    for stamp in phase_err:\n        if abs(stamp[1]) > time_thresh:\n            time_err.append(stamp[0])\n    return time_err",
    "docstring": "Find large time errors in list.\n\n    Scan through a list of tuples of time stamps and phase errors\n    and return a list of time stamps with timing errors above a threshold.\n\n    .. note::\n        This becomes important for networks cross-correlations, where\n        if timing information is uncertain at one site, the relative arrival\n        time (lag) will be incorrect, which will degrade the cross-correlation\n        sum.\n\n    :type phase_err: list\n    :param phase_err: List of Tuple of float, datetime.datetime\n    :type time_thresh: float\n    :param time_thresh: Threshold to declare a timing error for\n\n    :returns: List of :class:`datetime.datetime` when timing is questionable."
  },
  {
    "code": "def getCaCerts(self):\n        retn = []\n        path = s_common.genpath(self.certdir, 'cas')\n        for name in os.listdir(path):\n            if not name.endswith('.crt'):\n                continue\n            full = s_common.genpath(self.certdir, 'cas', name)\n            retn.append(self._loadCertPath(full))\n        return retn",
    "docstring": "Return a list of CA certs from the CertDir.\n\n        Returns:\n            [OpenSSL.crypto.X509]: List of CA certificates."
  },
  {
    "code": "def _get_compressor_options(\n        self,\n        side: str,\n        agreed_parameters: Dict[str, Any],\n        compression_options: Dict[str, Any] = None,\n    ) -> Dict[str, Any]:\n        options = dict(\n            persistent=(side + \"_no_context_takeover\") not in agreed_parameters\n        )\n        wbits_header = agreed_parameters.get(side + \"_max_window_bits\", None)\n        if wbits_header is None:\n            options[\"max_wbits\"] = zlib.MAX_WBITS\n        else:\n            options[\"max_wbits\"] = int(wbits_header)\n        options[\"compression_options\"] = compression_options\n        return options",
    "docstring": "Converts a websocket agreed_parameters set to keyword arguments\n        for our compressor objects."
  },
  {
    "code": "def object2code(key, code):\n    if key in [\"xscale\", \"yscale\"]:\n        if code == \"log\":\n            code = True\n        else:\n            code = False\n    else:\n        code = unicode(code)\n    return code",
    "docstring": "Returns code for widget from dict object"
  },
  {
    "code": "def do_set_hub_connection(self, args):\n        params = args.split()\n        username = None\n        password = None\n        host = None\n        port = None\n        try:\n            username = params[0]\n            password = params[1]\n            host = params[2]\n            port = params[3]\n        except IndexError:\n            pass\n        if username and password and host:\n            if not port:\n                port = 25105\n            self.tools.username = username\n            self.tools.password = password\n            self.tools.host = host\n            self.tools.port = port\n        else:\n            _LOGGING.error('username password host are required')\n            self.do_help('set_hub_connection')",
    "docstring": "Set Hub connection parameters.\n\n        Usage:\n            set_hub_connection username password host [port]\n\n        Arguments:\n            username: Hub username\n            password: Hub password\n            host: host name or IP address\n            port: IP port [default 25105]"
  },
  {
    "code": "def conv2bin(data):\n    if data.min() < 0 or data.max() > 1:\n        data = normalize(data)\n    out_data = data.copy()\n    for i, sample in enumerate(out_data):\n        for j, val in enumerate(sample):\n            if np.random.random() <= val:\n                out_data[i][j] = 1\n            else:\n                out_data[i][j] = 0\n    return out_data",
    "docstring": "Convert a matrix of probabilities into binary values.\n\n    If the matrix has values <= 0 or >= 1, the values are\n    normalized to be in [0, 1].\n\n    :type data: numpy array\n    :param data: input matrix\n    :return: converted binary matrix"
  },
  {
    "code": "def cd(dest):\n    origin = os.getcwd()\n    try:\n        os.chdir(dest)\n        yield dest\n    finally:\n        os.chdir(origin)",
    "docstring": "Temporarily cd into a directory"
  },
  {
    "code": "def num_taps(sample_rate, transitionwidth, gpass, gstop):\n    gpass = 10 ** (-gpass / 10.)\n    gstop = 10 ** (-gstop / 10.)\n    return int(2/3. * log10(1 / (10 * gpass * gstop)) *\n               sample_rate / transitionwidth)",
    "docstring": "Returns the number of taps for an FIR filter with the given shape\n\n    Parameters\n    ----------\n    sample_rate : `float`\n        sampling rate of target data\n\n    transitionwidth : `float`\n        the width (in the same units as `sample_rate` of the transition\n        from stop-band to pass-band\n\n    gpass : `float`\n        the maximum loss in the passband (dB)\n\n    gstop : `float`\n        the minimum attenuation in the stopband (dB)\n\n    Returns\n    -------\n    numtaps : `int`\n       the number of taps for an FIR filter\n\n    Notes\n    -----\n    Credit: http://dsp.stackexchange.com/a/31077/8223"
  },
  {
    "code": "def main(fast=False):\n    print('Running benchmarks...\\n')\n    results = bench_run(fast=fast)\n    bench_report(results)",
    "docstring": "Run all benchmarks and print report to the console."
  },
  {
    "code": "def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None,\n                 profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    if key_id.startswith('alias/'):\n        key_id = _get_key_id(key_id)\n    r = {}\n    try:\n        conn.revoke_grant(key_id, grant_id)\n        r['result'] = True\n    except boto.exception.BotoServerError as e:\n        r['result'] = False\n        r['error'] = __utils__['boto.get_error'](e)\n    return r",
    "docstring": "Revoke a grant from a key.\n\n    CLI example::\n\n        salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j..."
  },
  {
    "code": "def get(interface, method, version=1,\n        apihost=DEFAULT_PARAMS['apihost'], https=DEFAULT_PARAMS['https'],\n        caller=None, session=None, params=None):\n    url = u\"%s://%s/%s/%s/v%s/\" % (\n        'https' if https else 'http', apihost, interface, method, version)\n    return webapi_request(url, 'GET', caller=caller, session=session, params=params)",
    "docstring": "Send GET request to an API endpoint\n\n    .. versionadded:: 0.8.3\n\n    :param interface: interface name\n    :type interface: str\n    :param method: method name\n    :type method: str\n    :param version: method version\n    :type version: int\n    :param apihost: API hostname\n    :type apihost: str\n    :param https: whether to use HTTPS\n    :type https: bool\n    :param params: parameters for endpoint\n    :type params: dict\n    :return: endpoint response\n    :rtype: :class:`dict`, :class:`lxml.etree.Element`, :class:`str`"
  },
  {
    "code": "def message_to_event(zclient, msg):\n    if not isinstance(msg, zebra.ZebraMessage):\n        return None\n    body_cls = msg.get_body_class(msg.version, msg.command)\n    ev_cls = getattr(MOD, _event_name(body_cls), None)\n    if ev_cls is None:\n        return None\n    return ev_cls(zclient, msg)",
    "docstring": "Converts Zebra protocol message instance to Zebra protocol service\n    event instance.\n\n    If corresponding event class is not defined, returns None.\n\n    :param zclient: Zebra client instance.\n    :param msg: Zebra protocol message.\n    :return: Zebra protocol service event."
  },
  {
    "code": "def decode_arr(data):\n    data = data.encode('utf-8')\n    return frombuffer(base64.b64decode(data), float64)",
    "docstring": "Extract a numpy array from a base64 buffer"
  },
  {
    "code": "def retrieve_password_from_keyring(credential_id, username):\n    try:\n        import keyring\n        return keyring.get_password(credential_id, username)\n    except ImportError:\n        log.error('USE_KEYRING configured as a password, but no keyring module is installed')\n        return False",
    "docstring": "Retrieve particular user's password for a specified credential set from system keyring."
  },
  {
    "code": "def remove_move(name):\n    try:\n        delattr(_MovedItems, name)\n    except AttributeError:\n        try:\n            del moves.__dict__[name]\n        except KeyError:\n            raise AttributeError(\"no such move, %r\" % (name,))",
    "docstring": "Remove item from six.moves."
  },
  {
    "code": "def next_task(self, item, raise_exceptions=None, **kwargs):\n        filename = os.path.basename(item)\n        batch = self.get_batch(filename)\n        tx_deserializer = self.tx_deserializer_cls(\n            allow_self=self.allow_self, override_role=self.override_role\n        )\n        try:\n            tx_deserializer.deserialize_transactions(\n                transactions=batch.saved_transactions\n            )\n        except (DeserializationError, TransactionDeserializerError) as e:\n            raise TransactionsFileQueueError(e) from e\n        else:\n            batch.close()\n            self.archive(filename)",
    "docstring": "Deserializes all transactions for this batch and\n        archives the file."
  },
  {
    "code": "def put(self, id=None):\n        toa = self.request.headers.get(\"Caesium-TOA\")\n        if not toa:\n            self.raise_error(400, \"Caesium-TOA header is required, none found\")\n            self.finish(self.request.headers.get(\"Caesium-TOA\"))\n        meta = self._get_meta_data()\n        meta[\"bulk_id\"] = uuid.uuid4().get_hex()\n        ids = self.get_json_argument(\"ids\")\n        patch = self.get_json_argument(\"patch\")\n        self.get_json_argument(\"ids\", [])\n        for id in ids:\n            stack = AsyncSchedulableDocumentRevisionStack(self.client.collection_name, self.settings, master_id=id)\n            stack.push(patch, toa=toa, meta=meta)\n        self.write({\n            \"count\": len(ids),\n            \"result\": {\n                \"ids\": ids,\n                \"toa\": toa,\n                \"patch\": patch,\n            }\n        })\n        self.finish()",
    "docstring": "Update many objects with a single PUT.\n\n        Example Request::\n\n            {\n                \"ids\": [\"52b0ede98ac752b358b1bd69\", \"52b0ede98ac752b358b1bd70\"],\n                \"patch\": {\n                    \"foo\": \"bar\"\n                }\n            }"
  },
  {
    "code": "def get(self):\n        if self.num is None:\n            if self.num_inst == 0:\n                return (self.name, float('nan'))\n            else:\n                return (self.name, self.sum_metric / self.num_inst)\n        else:\n            names = ['%s'%(self.name[i]) for i in range(self.num)]\n            values = [x / y if y != 0 else float('nan') \\\n                for x, y in zip(self.sum_metric, self.num_inst)]\n            return (names, values)",
    "docstring": "Get the current evaluation result.\n        Override the default behavior\n\n        Returns\n        -------\n        name : str\n           Name of the metric.\n        value : float\n           Value of the evaluation."
  },
  {
    "code": "def compile_mako_files(self, app_config):\n        for subdir_name in self.SEARCH_DIRS:\n            subdir = subdir_name.format(\n                app_path=app_config.path,\n                app_name=app_config.name,\n            )\n            def recurse_path(path):\n                self.message('searching for Mako templates in {}'.format(path), 1)\n                if os.path.exists(path):\n                    for filename in os.listdir(path):\n                        filepath = os.path.join(path, filename)\n                        _, ext = os.path.splitext(filename)\n                        if filename.startswith('__'):\n                            continue\n                        elif os.path.isdir(filepath):\n                            recurse_path(filepath)\n                        elif ext.lower() in ( '.htm', '.html', '.mako' ):\n                            self.message('compiling {}'.format(filepath), 2)\n                            try:\n                                get_template_for_path(filepath)\n                            except TemplateSyntaxError:\n                                if not self.options.get('ignore_template_errors'):\n                                    raise\n            recurse_path(subdir)",
    "docstring": "Compiles the Mako templates within the apps of this system"
  },
  {
    "code": "def _write_summary(self, session, frame):\n    summary = session.run(self.summary_op, feed_dict={\n        self.frame_placeholder: frame\n    })\n    path = '{}/{}'.format(self.PLUGIN_LOGDIR, SUMMARY_FILENAME)\n    write_file(summary, path)",
    "docstring": "Writes the frame to disk as a tensor summary."
  },
  {
    "code": "def parse_trips(self, xml, requested_time):\n        obj = xmltodict.parse(xml)\n        trips = []\n        if 'error' in obj:\n            print('Error in trips: ' + obj['error']['message'])\n            return None\n        try:\n            for trip in obj['ReisMogelijkheden']['ReisMogelijkheid']:\n                newtrip = Trip(trip, requested_time)\n                trips.append(newtrip)\n        except TypeError:\n            return None\n        return trips",
    "docstring": "Parse the NS API xml result into Trip objects"
  },
  {
    "code": "def get_bars(self, lookback=None, as_dict=False):\n        bars = self._get_symbol_dataframe(self.parent.bars, self)\n        bars = self.parent._add_signal_history(df=bars, symbol=self)\n        lookback = self.bar_window if lookback is None else lookback\n        bars = bars[-lookback:]\n        if not bars.empty > 0 and bars['asset_class'].values[-1] not in (\"OPT\", \"FOP\"):\n            bars.drop(bars.columns[\n                bars.columns.str.startswith('opt_')].tolist(),\n                inplace=True, axis=1)\n        if as_dict:\n            bars.loc[:, 'datetime'] = bars.index\n            bars = bars.to_dict(orient='records')\n            if lookback == 1:\n                bars = None if not bars else bars[0]\n        return bars",
    "docstring": "Get bars for this instrument\n\n        :Parameters:\n            lookback : int\n                Max number of bars to get (None = all available bars)\n            as_dict : bool\n                Return a dict or a pd.DataFrame object\n\n        :Retruns:\n            bars : pd.DataFrame / dict\n                The bars for this instruments"
  },
  {
    "code": "async def get_authenticated_user(\n        self, redirect_uri: str, code: str\n    ) -> Dict[str, Any]:\n        handler = cast(RequestHandler, self)\n        http = self.get_auth_http_client()\n        body = urllib.parse.urlencode(\n            {\n                \"redirect_uri\": redirect_uri,\n                \"code\": code,\n                \"client_id\": handler.settings[self._OAUTH_SETTINGS_KEY][\"key\"],\n                \"client_secret\": handler.settings[self._OAUTH_SETTINGS_KEY][\"secret\"],\n                \"grant_type\": \"authorization_code\",\n            }\n        )\n        response = await http.fetch(\n            self._OAUTH_ACCESS_TOKEN_URL,\n            method=\"POST\",\n            headers={\"Content-Type\": \"application/x-www-form-urlencoded\"},\n            body=body,\n        )\n        return escape.json_decode(response.body)",
    "docstring": "Handles the login for the Google user, returning an access token.\n\n        The result is a dictionary containing an ``access_token`` field\n        ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)).\n        Unlike other ``get_authenticated_user`` methods in this package,\n        this method does not return any additional information about the user.\n        The returned access token can be used with `OAuth2Mixin.oauth2_request`\n        to request additional information (perhaps from\n        ``https://www.googleapis.com/oauth2/v2/userinfo``)\n\n        Example usage:\n\n        .. testcode::\n\n            class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,\n                                           tornado.auth.GoogleOAuth2Mixin):\n                async def get(self):\n                    if self.get_argument('code', False):\n                        access = await self.get_authenticated_user(\n                            redirect_uri='http://your.site.com/auth/google',\n                            code=self.get_argument('code'))\n                        user = await self.oauth2_request(\n                            \"https://www.googleapis.com/oauth2/v1/userinfo\",\n                            access_token=access[\"access_token\"])\n                        # Save the user and access token with\n                        # e.g. set_secure_cookie.\n                    else:\n                        await self.authorize_redirect(\n                            redirect_uri='http://your.site.com/auth/google',\n                            client_id=self.settings['google_oauth']['key'],\n                            scope=['profile', 'email'],\n                            response_type='code',\n                            extra_params={'approval_prompt': 'auto'})\n\n        .. testoutput::\n           :hide:\n\n        .. versionchanged:: 6.0\n\n           The ``callback`` argument was removed. Use the returned awaitable object instead."
  },
  {
    "code": "def get_coin_snapshot(fsym, tsym):\n\turl = build_url('coinsnapshot', fsym=fsym, tsym=tsym)\n\tdata = load_data(url)['Data']\n\treturn data",
    "docstring": "Get blockchain information, aggregated data as well as data for the \n\tindividual exchanges available for the specified currency pair.\n\n\tArgs:\n\t\tfsym: FROM symbol.\n\t\ttsym: TO symbol.\n\t\n\tReturns:\n\t\tThe function returns a dictionairy containing blockain as well as \n\t\ttrading information from the different exchanges were the specified \n\t\tcurrency pair is available.\n\n\t\t{'AggregatedData': dict,\n \t\t 'Algorithm': ...,\n\t\t 'BlockNumber': ...,\n\t\t 'BlockReward': ...,\n\t\t 'Exchanges': [dict1, dict2, ...],\n\t\t 'NetHashesPerSecond': ...,\n\t\t 'ProofType': ...,\n\t\t 'TotalCoinsMined': ...}\n\n\t\tdict = {'FLAGS': ...,\n\t\t        'FROMSYMBOL': ...,\n\t\t        'HIGH24HOUR': ...,\n\t\t        'LASTMARKET': ...,\n\t\t        'LASTTRADEID': ...,\n\t\t        'LASTUPDATE': ...,\n\t\t        'LASTVOLUME': ...,\n\t\t        'LASTVOLUMETO': ...,\n\t\t        'LOW24HOUR': ...,\n\t\t        'MARKET': ...,\n\t\t        'OPEN24HOUR': ...,\n\t\t        'PRICE': ...,\n\t\t        'TOSYMBOL': ...,\n\t\t        'TYPE': ...,\n\t\t        'VOLUME24HOUR': ...,\n\t\t        'VOLUME24HOURTO': ...}"
  },
  {
    "code": "def _normalize_files(item, fc_dir=None):\n    files = item.get(\"files\")\n    if files:\n        if isinstance(files, six.string_types):\n            files = [files]\n        fastq_dir = flowcell.get_fastq_dir(fc_dir) if fc_dir else os.getcwd()\n        files = [_file_to_abs(x, [os.getcwd(), fc_dir, fastq_dir]) for x in files]\n        files = [x for x in files if x]\n        _sanity_check_files(item, files)\n        item[\"files\"] = files\n    return item",
    "docstring": "Ensure the files argument is a list of absolute file names.\n    Handles BAM, single and paired end fastq, as well as split inputs."
  },
  {
    "code": "def on_storage_device_change(self, medium_attachment, remove, silent):\n        if not isinstance(medium_attachment, IMediumAttachment):\n            raise TypeError(\"medium_attachment can only be an instance of type IMediumAttachment\")\n        if not isinstance(remove, bool):\n            raise TypeError(\"remove can only be an instance of type bool\")\n        if not isinstance(silent, bool):\n            raise TypeError(\"silent can only be an instance of type bool\")\n        self._call(\"onStorageDeviceChange\",\n                     in_p=[medium_attachment, remove, silent])",
    "docstring": "Triggered when attached storage devices of the\n        associated virtual machine have changed.\n\n        in medium_attachment of type :class:`IMediumAttachment`\n            The medium attachment which changed.\n\n        in remove of type bool\n            TRUE if the device is removed, FALSE if it was added.\n\n        in silent of type bool\n            TRUE if the device is is silently reconfigured without\n            notifying the guest about it.\n\n        raises :class:`VBoxErrorInvalidVmState`\n            Session state prevents operation.\n        \n        raises :class:`VBoxErrorInvalidObjectState`\n            Session type prevents operation."
  },
  {
    "code": "def complete(self):\n        comp = []\n        for k, v in self.key.items():\n            if v['type'] == 'value':\n                if 'complete' in v:\n                    comp += v['complete'](self.inp_cmd[-1])\n            else:\n                comp.append(k)\n        return comp",
    "docstring": "Return list of valid completions\n\n            Returns a list of valid completions on the current level in the\n            tree. If an element of type 'value' is found, its complete callback\n            function is called (if set)."
  },
  {
    "code": "def filter(self, field_name, operand, value):\n        if operand not in self._FILTER_OPERANDS:\n            raise ValueError('Operand must be one of {}'.format(', '.join(self._FILTER_OPERANDS)))\n        record_stub = record_factory(self._app)\n        field = record_stub.get_field(field_name)\n        self._raw['filters'].append({\n            \"fieldId\": field.id,\n            \"filterType\": operand,\n            \"value\": field.get_report(value)\n        })",
    "docstring": "Adds a filter to report\n\n        Notes:\n            All filters are currently AND'ed together\n\n        Args:\n            field_name (str): Target field name to filter on\n            operand (str): Operand used in comparison. See `swimlane.core.search` for options\n            value: Target value used in comparision"
  },
  {
    "code": "def gen_procfile(ctx, wsgi, dev):\n    if wsgi is None:\n        if os.path.exists(\"wsgi.py\"):\n            wsgi = \"wsgi.py\"\n        elif os.path.exists(\"app.py\"):\n            wsgi = \"app.py\"\n        else:\n            wsgi = \"app.py\"\n            ctx.invoke(gen_apppy)\n    def write_procfile(filename, server_process, debug):\n        processes = [server_process] + current_app.processes\n        procfile = []\n        for name, cmd in procfile_processes(processes, debug).iteritems():\n            procfile.append(\"%s: %s\" % (name, cmd))\n        with open(filename, \"w\") as f:\n            f.write(\"\\n\".join(procfile))\n    write_procfile(\"Procfile\", (\"web\", [\"gunicorn\", wsgi]), False)\n    if dev:\n        write_procfile(\"Procfile.dev\", (\"web\", [\"frasco\", \"serve\"]), True)",
    "docstring": "Generates Procfiles which can be used with honcho or foreman."
  },
  {
    "code": "def _availableResultsFraction( self ):\n        tr = self.notebook().numberOfResults() + self.notebook().numberOfPendingResults()\n        if tr == 0:\n            return 0\n        else:\n            return (self.notebook().numberOfResults() + 0.0) / tr",
    "docstring": "Private method to return the fraction of results available, as a real number\n        between 0 and 1. This does not update the results fetched from the cluster.\n\n        :returns: the fraction of available results"
  },
  {
    "code": "def find_all(self, string, callback):\n\t\tfor index, output in self.iter(string):\n\t\t\tcallback(index, output)",
    "docstring": "Wrapper on iter method, callback gets an iterator result"
  },
  {
    "code": "def gauge(self, stat, value, rate=1, delta=False):\n        if value < 0 and not delta:\n            if rate < 1:\n                if random.random() > rate:\n                    return\n            with self.pipeline() as pipe:\n                pipe._send_stat(stat, '0|g', 1)\n                pipe._send_stat(stat, '%s|g' % value, 1)\n        else:\n            prefix = '+' if delta and value >= 0 else ''\n            self._send_stat(stat, '%s%s|g' % (prefix, value), rate)",
    "docstring": "Set a gauge value."
  },
  {
    "code": "def from_jd(jd, method=None):\n    method = method or 'equinox'\n    if method == 'equinox':\n        return _from_jd_equinox(jd)\n    else:\n        return _from_jd_schematic(jd, method)",
    "docstring": "Calculate date in the French Revolutionary\n    calendar from Julian day.  The five or six\n    \"sansculottides\" are considered a thirteenth\n    month in the results of this function."
  },
  {
    "code": "def initialize_memory(basic_block):\n    global MEMORY\n    MEMORY = basic_block.mem\n    get_labels(MEMORY, basic_block)\n    basic_block.mem = MEMORY",
    "docstring": "Initializes global memory array with the given one"
  },
  {
    "code": "def data_vectors(self):\n        return {field: self.record[field] for field in self.record.dtype.names\n                if field != 'sample'}",
    "docstring": "The per-sample data in a vector.\n\n        Returns:\n            dict: A dict where the keys are the fields in the record and the\n            values are the corresponding arrays.\n\n        Examples:\n            >>> sampleset = dimod.SampleSet.from_samples([[-1, 1], [1, 1]], dimod.SPIN,\n                                                         energy=[-1, 1])\n            >>> sampleset.data_vectors['energy']\n            array([-1,  1])\n\n            Note that this is equivalent to, and less performant than:\n\n            >>> sampleset = dimod.SampleSet.from_samples([[-1, 1], [1, 1]], dimod.SPIN,\n                                                         energy=[-1, 1])\n            >>> sampleset.record['energy']\n            array([-1,  1])"
  },
  {
    "code": "def from_string(values, separator, remove_duplicates = False):\n        result = AnyValueArray()\n        if values == None or len(values) == 0:\n            return result\n        items = str(values).split(separator)\n        for item in items:\n            if (item != None and len(item) > 0) or remove_duplicates == False:\n                result.append(item)\n        return result",
    "docstring": "Splits specified string into elements using a separator and assigns\n        the elements to a newly created AnyValueArray.\n\n        :param values: a string value to be split and assigned to AnyValueArray\n\n        :param separator: a separator to split the string\n\n        :param remove_duplicates: (optional) true to remove duplicated elements\n\n        :return: a newly created AnyValueArray."
  },
  {
    "code": "def loads(self, value):\n        raw = False if self.encoding == \"utf-8\" else True\n        if value is None:\n            return None\n        return msgpack.loads(value, raw=raw, use_list=self.use_list)",
    "docstring": "Deserialize value using ``msgpack.loads``.\n\n        :param value: bytes\n        :returns: obj"
  },
  {
    "code": "def list_depth(list_, func=max, _depth=0):\n    depth_list = [list_depth(item, func=func, _depth=_depth + 1)\n                  for item in  list_ if util_type.is_listlike(item)]\n    if len(depth_list) > 0:\n        return func(depth_list)\n    else:\n        return _depth",
    "docstring": "Returns the deepest level of nesting within a list of lists\n\n    Args:\n       list_  : a nested listlike object\n       func   : depth aggregation strategy (defaults to max)\n       _depth : internal var\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_list import *  # NOQA\n        >>> list_ = [[[[[1]]], [3]], [[1], [3]], [[1], [3]]]\n        >>> result = (list_depth(list_, _depth=0))\n        >>> print(result)"
  },
  {
    "code": "def list_clients():\n    p = '%s/pymux.sock.%s.*' % (tempfile.gettempdir(), getpass.getuser())\n    for path in glob.glob(p):\n        try:\n            yield PosixClient(path)\n        except socket.error:\n            pass",
    "docstring": "List all the servers that are running."
  },
  {
    "code": "def create_request_setting(self,\n\t\tservice_id,\n\t\tversion_number,\n\t\tname,\n\t\tdefault_host=None,\n\t\tforce_miss=None,\n\t\tforce_ssl=None,\n\t\taction=None,\n\t\tbypass_busy_wait=None,\n\t\tmax_stale_age=None,\n\t\thash_keys=None,\n\t\txff=None,\n\t\ttimer_support=None,\n\t\tgeo_headers=None,\n\t\trequest_condition=None):\n\t\tbody = self._formdata({\n\t\t\t\"name\": name,\n\t\t\t\"default_host\": default_host,\n\t\t\t\"force_miss\": force_miss,\n\t\t\t\"force_ssl\": force_ssl,\n\t\t\t\"action\": action,\n\t\t\t\"bypass_busy_wait\": bypass_busy_wait,\n\t\t\t\"max_stale_age\": max_stale_age,\n\t\t\t\"hash_keys\": hash_keys,\n\t\t\t\"xff\": xff,\n\t\t\t\"timer_support\": timer_support,\n\t\t\t\"geo_headers\": geo_headers,\n\t\t\t\"request_condition\": request_condition,\n\t\t}, FastlyRequestSetting.FIELDS)\n\t\tcontent = self._fetch(\"/service/%s/version/%d/request_settings\" % (service_id, version_number), method=\"POST\", body=body)\n\t\treturn FastlyRequestSetting(self, content)",
    "docstring": "Creates a new Request Settings object."
  },
  {
    "code": "def _handle_no_candidates(self):\n        if self.dom is not None and len(self.dom):\n            dom = prep_article(self.dom)\n            dom = build_base_document(dom, self._return_fragment)\n            return self._remove_orphans(\n                dom.get_element_by_id(\"readabilityBody\"))\n        else:\n            logger.info(\"No document to use.\")\n            return build_error_document(self._return_fragment)",
    "docstring": "If we fail to find a good candidate we need to find something else."
  },
  {
    "code": "def get_context(self, name):\n        contexts = self.data['contexts']\n        for context in contexts:\n            if context['name'] == name:\n                return context\n        raise KubeConfError(\"context name not found.\")",
    "docstring": "Get context from kubeconfig."
  },
  {
    "code": "def timeslice_generator(self):\n        slice_id = 0\n        while slice_id < self.n_timeslices:\n            blob = self.get_blob(slice_id)\n            yield blob\n            slice_id += 1",
    "docstring": "Uses slice ID as iterator"
  },
  {
    "code": "def ceilpow2(n):\n    signif,exponent = frexp(n)\n    if (signif < 0):\n        return 1;\n    if (signif == 0.5):\n        exponent -= 1;\n    return (1) << exponent;",
    "docstring": "convenience function to determine a power-of-2 upper frequency limit"
  },
  {
    "code": "def last_datetime(self):\n        from datetime import datetime\n        try:\n            return datetime.fromtimestamp(self.state.lasttime)\n        except TypeError:\n            return None",
    "docstring": "Return the time of the last operation on the bundle as a datetime object"
  },
  {
    "code": "def switch_to_next_app(self):\n        log.debug(\"switching to next app...\")\n        cmd, url = DEVICE_URLS[\"switch_to_next_app\"]\n        self.result = self._exec(cmd, url)",
    "docstring": "switches to the next app"
  },
  {
    "code": "def collect_filters_to_first_location_occurrence(compound_match_query):\n    new_match_queries = []\n    for match_query in compound_match_query.match_queries:\n        location_to_filters = _construct_location_to_filter_list(match_query)\n        already_filtered_locations = set()\n        new_match_traversals = []\n        for match_traversal in match_query.match_traversals:\n            result = _apply_filters_to_first_location_occurrence(\n                match_traversal, location_to_filters, already_filtered_locations)\n            new_match_traversal, newly_filtered_locations = result\n            new_match_traversals.append(new_match_traversal)\n            already_filtered_locations.update(newly_filtered_locations)\n        new_match_queries.append(\n            MatchQuery(\n                match_traversals=new_match_traversals,\n                folds=match_query.folds,\n                output_block=match_query.output_block,\n                where_block=match_query.where_block,\n            )\n        )\n    return CompoundMatchQuery(match_queries=new_match_queries)",
    "docstring": "Collect all filters for a particular location to the first instance of the location.\n\n    Adding edge field non-exsistence filters in `_prune_traverse_using_omitted_locations` may\n    result in filters being applied to locations after their first occurence.\n    OrientDB does not resolve this behavior correctly. Therefore, for each MatchQuery,\n    we collect all the filters for each location in a list. For each location,\n    we make a conjunction of the filter list (`_predicate_list_to_where_block`) and apply\n    the new filter to only the first instance of that location.\n    All other instances will have no filters (None).\n\n    Args:\n        compound_match_query: CompoundMatchQuery object containing 2^n MatchQuery objects\n\n    Returns:\n        CompoundMatchQuery with all filters for each location applied to the first instance\n        of that location."
  },
  {
    "code": "def elements(self):\n        return (self.country_code, self.check_digits, self.bank_identifier,\n                self.bank_account_number)",
    "docstring": "Return the IBAN's Country Code, check digits, Bank Identifier and\n        Bank Account Number as tuple."
  },
  {
    "code": "def asyncPipeStrconcat(context=None, _INPUT=None, conf=None, **kwargs):\n    splits = yield asyncGetSplits(_INPUT, conf['part'], **cdicts(opts, kwargs))\n    _OUTPUT = yield asyncStarMap(partial(maybeDeferred, parse_result), splits)\n    returnValue(iter(_OUTPUT))",
    "docstring": "A string module that asynchronously builds a string. Loopable. No direct\n    input.\n\n    Parameters\n    ----------\n    context : pipe2py.Context object\n    _INPUT : asyncPipe like object (twisted Deferred iterable of items)\n    conf : {\n        'part': [\n            {'value': <'<img src=\"'>},\n            {'subkey': <'img.src'>},\n            {'value': <'\">'>}\n        ]\n    }\n\n    Returns\n    -------\n    _OUTPUT : twisted.internet.defer.Deferred generator of joined strings"
  },
  {
    "code": "def tmdb_find(\n    api_key, external_source, external_id, language=\"en-US\", cache=True\n):\n    sources = [\"imdb_id\", \"freebase_mid\", \"freebase_id\", \"tvdb_id\", \"tvrage_id\"]\n    if external_source not in sources:\n        raise MapiProviderException(\"external_source must be in %s\" % sources)\n    if external_source == \"imdb_id\" and not match(r\"tt\\d+\", external_id):\n        raise MapiProviderException(\"invalid imdb tt-const value\")\n    url = \"https://api.themoviedb.org/3/find/\" + external_id or \"\"\n    parameters = {\n        \"api_key\": api_key,\n        \"external_source\": external_source,\n        \"language\": language,\n    }\n    keys = [\n        \"movie_results\",\n        \"person_results\",\n        \"tv_episode_results\",\n        \"tv_results\",\n        \"tv_season_results\",\n    ]\n    status, content = _request_json(url, parameters, cache=cache)\n    if status == 401:\n        raise MapiProviderException(\"invalid API key\")\n    elif status != 200 or not any(content.keys()):\n        raise MapiNetworkException(\"TMDb down or unavailable?\")\n    elif status == 404 or not any(content.get(k, {}) for k in keys):\n        raise MapiNotFoundException\n    return content",
    "docstring": "Search for The Movie Database objects using another DB's foreign key\n\n    Note: language codes aren't checked on this end or by TMDb, so if you\n        enter an invalid language code your search itself will succeed, but\n        certain fields like synopsis will just be empty\n\n    Online docs: developers.themoviedb.org/3/find"
  },
  {
    "code": "def fib(number: int) -> int:\n    if number < 2:\n        return number\n    return fib(number - 1) + fib(number - 2)",
    "docstring": "Simple Fibonacci function.\n\n    >>> fib(10)\n    55"
  },
  {
    "code": "def read_stream(self, stream_id, size=None):\n        rv = []\n        try:\n            with (yield from self._get_stream(stream_id).rlock):\n                if size is None:\n                    rv.append((\n                        yield from self._get_stream(stream_id).read_frame()))\n                    self._flow_control(stream_id)\n                elif size < 0:\n                    while True:\n                        rv.extend((\n                            yield from self._get_stream(stream_id).read_all()))\n                        self._flow_control(stream_id)\n                else:\n                    while size > 0:\n                        bufs, count = yield from self._get_stream(\n                            stream_id).read(size)\n                        rv.extend(bufs)\n                        size -= count\n                        self._flow_control(stream_id)\n        except StreamClosedError:\n            pass\n        except _StreamEndedException as e:\n            try:\n                self._flow_control(stream_id)\n            except StreamClosedError:\n                pass\n            rv.extend(e.bufs)\n        return b''.join(rv)",
    "docstring": "Read data from the given stream.\n\n        By default (`size=None`), this returns all data left in current HTTP/2\n        frame. In other words, default behavior is to receive frame by frame.\n\n        If size is given a number above zero, method will try to return as much\n        bytes as possible up to the given size, block until enough bytes are\n        ready or stream is remotely closed.\n\n        If below zero, it will read until the stream is remotely closed and\n        return everything at hand.\n\n        `size=0` is a special case that does nothing but returns `b''`. The\n        same result `b''` is also returned under other conditions if there is\n        no more data on the stream to receive, even under `size=None` and peer\n        sends an empty frame - you can use `b''` to safely identify the end of\n        the given stream.\n\n        Flow control frames will be automatically sent while reading clears the\n        buffer, allowing more data to come in.\n\n        :param stream_id: Stream to read\n        :param size: Expected size to read, `-1` for all, default frame.\n        :return: Bytes read or empty if there is no more to expect."
  },
  {
    "code": "def cudnnSetPooling2dDescriptor(poolingDesc, mode, windowHeight, windowWidth,\n                                verticalPadding, horizontalPadding, verticalStride, horizontalStride):\n    status = _libcudnn.cudnnSetPooling2dDescriptor(poolingDesc, mode, windowHeight,\n                                                 windowWidth, verticalPadding, horizontalPadding,\n                                                 verticalStride, horizontalStride)\n    cudnnCheckStatus(status)",
    "docstring": "Initialize a 2D pooling descriptor.\n\n    This function initializes a previously created pooling descriptor object.\n\n    Parameters\n    ----------\n    poolingDesc : cudnnPoolingDescriptor\n        Handle to a previously created pooling descriptor.\n    mode : cudnnPoolingMode\n        Enumerant to specify the pooling mode.\n    windowHeight : int\n        Height of the pooling window.\n    windowWidth : int\n        Width of the pooling window.\n    verticalPadding: int\n        Size of vertical padding.\n    horizontalPadding: int\n        Size of horizontal padding.\n    verticalStride : int\n        Pooling vertical stride.\n    horizontalStride : int\n        Pooling horizontal stride."
  },
  {
    "code": "def _build_logger(self, level=logging.INFO):\n        self._debug_stream = StringIO()\n        logger = logging.getLogger('sprinter')\n        out_hdlr = logging.StreamHandler(sys.stdout)\n        out_hdlr.setLevel(level)\n        logger.addHandler(out_hdlr)\n        debug_hdlr = logging.StreamHandler(self._debug_stream)\n        debug_hdlr.setFormatter(logging.Formatter('%(asctime)s %(message)s'))\n        debug_hdlr.setLevel(logging.DEBUG)\n        logger.addHandler(debug_hdlr)\n        logger.setLevel(logging.DEBUG)\n        return logger",
    "docstring": "return a logger. if logger is none, generate a logger from stdout"
  },
  {
    "code": "def merge_dimensions(dimensions_list):\n    dvalues = defaultdict(list)\n    dimensions = []\n    for dims in dimensions_list:\n        for d in dims:\n            dvalues[d.name].append(d.values)\n            if d not in dimensions:\n                dimensions.append(d)\n    dvalues = {k: list(unique_iterator(itertools.chain(*vals)))\n               for k, vals in dvalues.items()}\n    return [d(values=dvalues.get(d.name, [])) for d in dimensions]",
    "docstring": "Merges lists of fully or partially overlapping dimensions by\n    merging their values.\n\n    >>> from holoviews import Dimension\n    >>> dim_list = [[Dimension('A', values=[1, 2, 3]), Dimension('B')],\n    ...             [Dimension('A', values=[2, 3, 4])]]\n    >>> dimensions = merge_dimensions(dim_list)\n    >>> dimensions\n    [Dimension('A'), Dimension('B')]\n    >>> dimensions[0].values\n    [1, 2, 3, 4]"
  },
  {
    "code": "def extract_terms(self, nb):\n        emt = ExtractMetatabTerms()\n        emt.preprocess(nb, {})\n        return emt.terms",
    "docstring": "Extract some term values, usually set with tags or metadata"
  },
  {
    "code": "def random_regions(base, n, size):\n    spread = size // 2\n    base_info = collections.defaultdict(list)\n    for space, start, end in base:\n        base_info[space].append(start + spread)\n        base_info[space].append(end - spread)\n    regions = []\n    for _ in range(n):\n        space = random.choice(base_info.keys())\n        pos = random.randint(min(base_info[space]), max(base_info[space]))\n        regions.append([space, pos-spread, pos+spread])\n    return regions",
    "docstring": "Generate n random regions of 'size' in the provided base spread."
  },
  {
    "code": "def serialize(self, now=None):\n        created = self.created if self.created is not None else now\n        el = etree.Element(utils.lxmlns(\"mets\") + self.subsection, ID=self.id_string)\n        if created:\n            el.set(\"CREATED\", created)\n        status = self.get_status()\n        if status:\n            el.set(\"STATUS\", status)\n        if self.contents:\n            el.append(self.contents.serialize())\n        return el",
    "docstring": "Serialize this SubSection and all children to lxml Element and return it.\n\n        :param str now: Default value for CREATED if none set\n        :return: dmdSec/techMD/rightsMD/sourceMD/digiprovMD Element with all children"
  },
  {
    "code": "def inverable_unique_two_lists(item1_list, item2_list):\n    import utool as ut\n    unique_list1, inverse1 = np.unique(item1_list, return_inverse=True)\n    unique_list2, inverse2 = np.unique(item2_list, return_inverse=True)\n    flat_stacked, cumsum = ut.invertible_flatten2((unique_list1, unique_list2))\n    flat_unique, inverse3 = np.unique(flat_stacked, return_inverse=True)\n    reconstruct_tup = (inverse3, cumsum, inverse2, inverse1)\n    return flat_unique, reconstruct_tup",
    "docstring": "item1_list = aid1_list\n    item2_list = aid2_list"
  },
  {
    "code": "def clear(self):\n        logger.info(\"Resetting indexes\")\n        state = self.app_state\n        for _name, idx in state.indexes.items():\n            writer = AsyncWriter(idx)\n            writer.commit(merge=True, optimize=True, mergetype=CLEAR)\n        state.indexes.clear()\n        state.indexed_classes.clear()\n        state.indexed_fqcn.clear()\n        self.clear_update_queue()\n        if self.running:\n            self.stop()",
    "docstring": "Remove all content from indexes, and unregister all classes.\n\n        After clear() the service is stopped. It must be started again\n        to create new indexes and register classes."
  },
  {
    "code": "def tag_handler(self, cmd):\n        cmd.from_ = self._find_interesting_from(cmd.from_)\n        self.keep = cmd.from_ is not None",
    "docstring": "Process a TagCommand."
  },
  {
    "code": "def code(self):\n        code = getattr(self, '_code', None)\n        if not code:\n            if self.has_body():\n                code = 200\n            else:\n                code = 204\n        return code",
    "docstring": "the http status code to return to the client, by default, 200 if a body is present otherwise 204"
  },
  {
    "code": "def _os_install(self, package_file):\n        packages = \" \".join(json.load(package_file.open()))\n        if packages:\n            for packager in self.pkg_install_cmds:\n                if packager in self.context.externalbasis:\n                    installer = self.pkg_install_cmds[packager]\n            return f\"RUN    {installer} {packages}\"\n        else:\n            return \"\"",
    "docstring": "take in a dict return a string of docker build RUN directives\n        one RUN per package type\n        one package type per JSON key"
  },
  {
    "code": "def author_preview_view(self, context):\n        children_contents = []\n        fragment = Fragment()\n        for child_id in self.children:\n            child = self.runtime.get_block(child_id)\n            child_fragment = self._render_child_fragment(child, context, 'preview_view')\n            fragment.add_frag_resources(child_fragment)\n            children_contents.append(child_fragment.content)\n        render_context = {\n            'block': self,\n            'children_contents': children_contents\n        }\n        render_context.update(context)\n        fragment.add_content(self.loader.render_template(self.CHILD_PREVIEW_TEMPLATE, render_context))\n        return fragment",
    "docstring": "View for previewing contents in studio."
  },
  {
    "code": "def find_directories(root, pattern):\n    results = []\n    for base, dirs, files in os.walk(root):\n        matched = fnmatch.filter(dirs, pattern)\n        results.extend(os.path.join(base, d) for d in matched)\n    return results",
    "docstring": "Find all directories matching the glob pattern recursively\n\n    :param root: string\n    :param pattern: string\n    :return: list of dir paths relative to root"
  },
  {
    "code": "def get_event_attendees(self, event_id):\n        query = urllib.urlencode({'key': self._api_key,\n                                  'event_id': event_id})\n        url = '{0}?{1}'.format(RSVPS_URL, query)\n        data = self._http_get_json(url)\n        rsvps = data['results']\n        return [parse_member_from_rsvp(rsvp) for rsvp in rsvps\n                if rsvp['response'] != \"no\"]",
    "docstring": "Get the attendees of the identified event.\n\n        Parameters\n        ----------\n        event_id\n            ID of the event to get attendees for.\n\n        Returns\n        -------\n        List of ``pythonkc_meetups.types.MeetupMember``.\n\n        Exceptions\n        ----------\n        * PythonKCMeetupsBadJson\n        * PythonKCMeetupsBadResponse\n        * PythonKCMeetupsMeetupDown\n        * PythonKCMeetupsNotJson\n        * PythonKCMeetupsRateLimitExceeded"
  },
  {
    "code": "def merge_tree(self, rhs, base=None):\n        args = [\"--aggressive\", \"-i\", \"-m\"]\n        if base is not None:\n            args.append(base)\n        args.append(rhs)\n        self.repo.git.read_tree(args)\n        return self",
    "docstring": "Merge the given rhs treeish into the current index, possibly taking\n        a common base treeish into account.\n\n        As opposed to the from_tree_ method, this allows you to use an already\n        existing tree as the left side of the merge\n\n        :param rhs:\n            treeish reference pointing to the 'other' side of the merge.\n\n        :param base:\n            optional treeish reference pointing to the common base of 'rhs' and\n            this index which equals lhs\n\n        :return:\n            self ( containing the merge and possibly unmerged entries in case of\n            conflicts )\n\n        :raise GitCommandError:\n            If there is a merge conflict. The error will\n            be raised at the first conflicting path. If you want to have proper\n            merge resolution to be done by yourself, you have to commit the changed\n            index ( or make a valid tree from it ) and retry with a three-way\n            index.from_tree call."
  },
  {
    "code": "def sub(x, y, context=None):\n    return _apply_function_in_current_context(\n        BigFloat,\n        mpfr.mpfr_sub,\n        (\n            BigFloat._implicit_convert(x),\n            BigFloat._implicit_convert(y),\n        ),\n        context,\n    )",
    "docstring": "Return ``x`` - ``y``."
  },
  {
    "code": "def query_module_funcs(self, module):\n        funcs = self.session.query(Export).filter_by(\n            module=module).all()\n        return funcs",
    "docstring": "Query the functions in the specified module."
  },
  {
    "code": "def sentences(self):\n        sents = []\n        spans = self.sentence_tokenizer.span_tokenize(self.text)\n        for span in spans:\n            sent = Sentence(\n                text=self.text[span[0]:span[1]],\n                start=span[0],\n                end=span[1],\n                word_tokenizer=self.word_tokenizer,\n                lexicon=self.lexicon,\n                abbreviation_detector=self.abbreviation_detector,\n                pos_tagger=self.pos_tagger,\n                ner_tagger=self.ner_tagger,\n                parsers=self.parsers,\n                document=self.document\n            )\n            sents.append(sent)\n        return sents",
    "docstring": "Return a list of Sentences that make up this text passage."
  },
  {
    "code": "def get_scopes_information(self):\n        scopes = StandardScopeClaims.get_scopes_info(self.params['scope'])\n        if settings.get('OIDC_EXTRA_SCOPE_CLAIMS'):\n            scopes_extra = settings.get(\n                'OIDC_EXTRA_SCOPE_CLAIMS', import_str=True).get_scopes_info(self.params['scope'])\n            for index_extra, scope_extra in enumerate(scopes_extra):\n                for index, scope in enumerate(scopes[:]):\n                    if scope_extra['scope'] == scope['scope']:\n                        del scopes[index]\n        else:\n            scopes_extra = []\n        return scopes + scopes_extra",
    "docstring": "Return a list with the description of all the scopes requested."
  },
  {
    "code": "def transform_revision(self, revision):\n        config = self.manager.get_source('config')\n        return config.load_resource(revision)",
    "docstring": "make config revision look like describe output."
  },
  {
    "code": "def match_path(pathname,\n               included_patterns=None,\n               excluded_patterns=None,\n               case_sensitive=True):\n    included = [\"*\"] if included_patterns is None else included_patterns\n    excluded = [] if excluded_patterns is None else excluded_patterns\n    return _match_path(pathname, included, excluded, case_sensitive)",
    "docstring": "Matches a pathname against a set of acceptable and ignored patterns.\n\n    :param pathname:\n        A pathname which will be matched against a pattern.\n    :param included_patterns:\n        Allow filenames matching wildcard patterns specified in this list.\n        If no pattern is specified, the function treats the pathname as\n        a match_path.\n    :param excluded_patterns:\n        Ignores filenames matching wildcard patterns specified in this list.\n        If no pattern is specified, the function treats the pathname as\n        a match_path.\n    :param case_sensitive:\n        ``True`` if matching should be case-sensitive; ``False`` otherwise.\n    :returns:\n        ``True`` if the pathname matches; ``False`` otherwise.\n    :raises:\n        ValueError if included patterns and excluded patterns contain the\n        same pattern.\n\n    Doctests::\n        >>> match_path(\"/Users/gorakhargosh/foobar.py\")\n        True\n        >>> match_path(\"/Users/gorakhargosh/foobar.py\", case_sensitive=False)\n        True\n        >>> match_path(\"/users/gorakhargosh/foobar.py\", [\"*.py\"], [\"*.PY\"], True)\n        True\n        >>> match_path(\"/users/gorakhargosh/FOOBAR.PY\", [\"*.py\"], [\"*.PY\"], True)\n        False\n        >>> match_path(\"/users/gorakhargosh/foobar/\", [\"*.py\"], [\"*.txt\"], False)\n        False\n        >>> match_path(\"/users/gorakhargosh/FOOBAR.PY\", [\"*.py\"], [\"*.PY\"], False)\n        Traceback (most recent call last):\n            ...\n        ValueError: conflicting patterns `set(['*.py'])` included and excluded"
  },
  {
    "code": "def getpath(self, encoding='utf-8', errors='strict'):\n        path = self.__remove_dot_segments(self.path)\n        return uridecode(path, encoding, errors)",
    "docstring": "Return the normalized decoded URI path."
  },
  {
    "code": "def AddTransaction(self, tx):\n        if BC.Default() is None:\n            return False\n        if tx.Hash.ToBytes() in self.MemPool.keys():\n            return False\n        if BC.Default().ContainsTransaction(tx.Hash):\n            return False\n        if not tx.Verify(self.MemPool.values()):\n            logger.error(\"Verifying tx result... failed\")\n            return False\n        self.MemPool[tx.Hash.ToBytes()] = tx\n        return True",
    "docstring": "Add a transaction to the memory pool.\n\n        Args:\n            tx (neo.Core.TX.Transaction): instance.\n\n        Returns:\n            bool: True if successfully added. False otherwise."
  },
  {
    "code": "def replace_urls(status):\n    text = status.text\n    if not has_url(status):\n        return text\n    urls = [(e['indices'], e['expanded_url']) for e in status.entities['urls']]\n    urls.sort(key=lambda x: x[0][0], reverse=True)\n    for (start, end), url in urls:\n        text = text[:start] + url + text[end:]\n    return text",
    "docstring": "Replace shorturls in a status with expanded urls.\n\n    Args:\n        status (tweepy.status): A tweepy status object\n\n    Returns:\n        str"
  },
  {
    "code": "def get_portfolios3():\n    g1 = [0]\n    g2 = [1]\n    g7 = [2]\n    g13 = [3]\n    g14 = [4]\n    g15 = [5]\n    g16 = [6]\n    g18 = [7]\n    g21 = [8]\n    g22 = [9]\n    g23 = [10, 11]\n    portfolios = [g1 + g15 + g18,\n                  g2 + g16 + g21,\n                  g13 + g22,\n                  g7 + g23]\n    passive = g14\n    return portfolios, passive",
    "docstring": "Returns portfolios with U12 and U20 generators removed and generators\n    of the same type at the same bus aggregated."
  },
  {
    "code": "def save(self):\n        self.projects.save()\n        self.experiments.save()\n        safe_dump(self.global_config, self._globals_file,\n                  default_flow_style=False)",
    "docstring": "Save the entire configuration files"
  },
  {
    "code": "def list(self, limit=50, offset=0):\n        logger.info(\"list(limit=%s, offset=%s) [lid=%s,pid=%s]\", limit, offset, self.__lid, self.__pid)\n        evt = self._client._request_point_value_list(self.__lid, self.__pid, self._type, limit=limit, offset=offset)\n        self._client._wait_and_except_if_failed(evt)\n        return evt.payload['values']",
    "docstring": "List `all` the values on this Point.\n\n        Returns QAPI list function payload\n\n        Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)\n        containing the error if the infrastructure detects a problem\n\n        Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)\n        if there is a communications problem between you and the infrastructure\n\n        `limit` (optional) (integer) Return this many value details\n\n        `offset` (optional) (integer) Return value details starting at this offset"
  },
  {
    "code": "def get_root_path():\n    root_path = __file__\n    return os.path.dirname(os.path.realpath(root_path))",
    "docstring": "Get the root path for the application."
  },
  {
    "code": "def get_flow_by_idx(self, idx, bus):\n        P, Q = [], []\n        if type(idx) is not list:\n            idx = [idx]\n        if type(bus) is not list:\n            bus = [bus]\n        for line_idx, bus_idx in zip(idx, bus):\n            line_int = self.uid[line_idx]\n            if bus_idx == self.bus1[line_int]:\n                P.append(self.P1[line_int])\n                Q.append(self.Q1[line_int])\n            elif bus_idx == self.bus2[line_int]:\n                P.append(self.P2[line_int])\n                Q.append(self.Q2[line_int])\n        return matrix(P), matrix(Q)",
    "docstring": "Return seriesflow based on the external idx on the `bus` side"
  },
  {
    "code": "def response(self, msgtype, msgid, error, result):\n        self._proxy.response(msgid, error, result)",
    "docstring": "Handle an incoming response."
  },
  {
    "code": "def adaptive_universal_transformer_multilayer_hard():\n  hparams = adaptive_universal_transformer_multilayer_tpu()\n  hparams.batch_size = 256\n  hparams.hard_attention_k = 8\n  hparams.add_step_timing_signal = True\n  hparams.self_attention_type = \"dot_product_relative_v2\"\n  hparams.max_relative_position = 256\n  return hparams",
    "docstring": "Multi-layer config for adaptive Transformer with hard attention."
  },
  {
    "code": "def create_entity_class(self):\n        entity = Entity()\n        entity.PartitionKey = 'pk{}'.format(str(uuid.uuid4()).replace('-', ''))\n        entity.RowKey = 'rk{}'.format(str(uuid.uuid4()).replace('-', ''))\n        entity.age = 39\n        entity.large = 933311100\n        entity.sex = 'male'\n        entity.married = True\n        entity.ratio = 3.1\n        entity.birthday = datetime(1970, 10, 4)\n        entity.binary = EntityProperty(EdmType.BINARY, b'xyz')\n        entity.other = EntityProperty(EdmType.INT32, 20)\n        entity.clsid = EntityProperty(EdmType.GUID, 'c9da6455-213d-42c9-9a79-3e9149a57833')\n        return entity",
    "docstring": "Creates a class-based entity with fixed values, using all of the supported data types."
  },
  {
    "code": "def audio_visual_key(name=None):\n    if name is None:\n        name = 'AVI Field'\n    society_code = basic.numeric(3)\n    society_code = society_code.setName('Society Code') \\\n        .setResultsName('society_code')\n    av_number = basic.alphanum(15, extended=True, isLast=True)\n    field_empty = pp.Regex('[ ]{15}')\n    field_empty.setParseAction(pp.replaceWith(''))\n    av_number = av_number | field_empty\n    av_number = av_number.setName('Audio-Visual Number') \\\n        .setResultsName('av_number')\n    field = pp.Group(society_code + pp.Optional(av_number))\n    field.setParseAction(lambda v: _to_avi(v[0]))\n    field = field.setName(name)\n    return field.setResultsName('audio_visual_key')",
    "docstring": "Creates the grammar for an Audio Visual Key code.\n\n    This is a variation on the ISAN (International Standard Audiovisual Number)\n\n    :param name: name for the field\n    :return: grammar for an ISRC field"
  },
  {
    "code": "def endpoints(self):\n        children = [item.endpoints() for item in self.items]\n        return self.name, self.endpoint, children",
    "docstring": "Get all the endpoints under this node in a tree like structure.\n\n        Returns:\n            (tuple):\n                name (str): This node's name.\n                endpoint (str): Endpoint name relative to root.\n                children (list): ``child.endpoints for each child"
  },
  {
    "code": "def intranges_contain(int_, ranges):\n    tuple_ = _encode_range(int_, 0)\n    pos = bisect.bisect_left(ranges, tuple_)\n    if pos > 0:\n        left, right = _decode_range(ranges[pos-1])\n        if left <= int_ < right:\n            return True\n    if pos < len(ranges):\n        left, _ = _decode_range(ranges[pos])\n        if left == int_:\n            return True\n    return False",
    "docstring": "Determine if `int_` falls into one of the ranges in `ranges`."
  },
  {
    "code": "def stop(self, message):\n        self._stop = time.clock()\n        VSGLogger.info(\"{0:<20} - Finished [{1}s]\".format(message, self.pprint(self._stop - self._start)))",
    "docstring": "Manually stops timer with the message.\n\n        :param message:  The display message."
  },
  {
    "code": "def _pipe(obj, func, *args, **kwargs):\n    if isinstance(func, tuple):\n        func, target = func\n        if target in kwargs:\n            msg = '%s is both the pipe target and a keyword argument' % target\n            raise ValueError(msg)\n        kwargs[target] = obj\n        return func(*args, **kwargs)\n    else:\n        return func(obj, *args, **kwargs)",
    "docstring": "Apply a function ``func`` to object ``obj`` either by passing obj as the\n    first argument to the function or, in the case that the func is a tuple,\n    interpret the first element of the tuple as a function and pass the obj to\n    that function as a keyword argument whose key is the value of the second\n    element of the tuple.\n\n    Parameters\n    ----------\n    func : callable or tuple of (callable, string)\n        Function to apply to this object or, alternatively, a\n        ``(callable, data_keyword)`` tuple where ``data_keyword`` is a\n        string indicating the keyword of `callable`` that expects the\n        object.\n    args : iterable, optional\n        positional arguments passed into ``func``.\n    kwargs : dict, optional\n        a dictionary of keyword arguments passed into ``func``.\n\n    Returns\n    -------\n    object : the return type of ``func``."
  },
  {
    "code": "async def post(self):\n        post = (await self.region._get_messages(\n            fromid=self._post_id, limit=1))[0]\n        assert post.id == self._post_id\n        return post",
    "docstring": "Get the message lodged.\n\n        Returns\n        -------\n        an :class:`aionationstates.ApiQuery` of :class:`aionationstates.Post`"
  },
  {
    "code": "def merge_dicts(*dicts, **kwargs):\n    result = {}\n    for d in dicts:\n        result.update(d)\n    result.update(kwargs)\n    return result",
    "docstring": "Merges dicts and kwargs into one dict"
  },
  {
    "code": "def create_handler(cls, message_handler, buffer_size, logger):\n        cls.BUFFER_SIZE = buffer_size\n        cls.message_handler = message_handler\n        cls.logger = logger\n        cls.message_handler.logger = logging.getLogger(message_handler.__class__.__name__)\n        cls.message_handler.logger.setLevel(logger.level)\n        return cls",
    "docstring": "Class variables used here since the framework creates an instance for each connection\n\n        :param message_handler: the MessageHandler used to process each message.\n        :param buffer_size: the TCP buffer size.\n        :param logger: the global logger.\n        :return: this class."
  },
  {
    "code": "def clip_by_value(x, min, max):\n    r\n    from .function_bases import maximum2 as maximum2_base\n    from .function_bases import minimum2 as minimum2_base\n    return minimum2_base(maximum2_base(x, min), max)",
    "docstring": "r\"\"\"Clip inputs by values.\n\n    .. math::\n\n        y = \\begin{cases}\n                max & (x > max) \\\\\n                x & (otherwise) \\\\\n                min & (x < min)\n            \\end{cases}.\n\n    Args:\n        x (Variable): An input variable.\n        min (Variable): A min variable by which `x` is clipped. Note that the shape of `min` must be the same as `x`'s.\n        max (Variable): A max variable by which `x` is clipped. Note that the shape of `max` must be the same as `x`'s\n\n    Returns:\n        ~nnabla.Variable: N-D array."
  },
  {
    "code": "def _load_income_model(self):\n        self._add_model(self.income, self.state.income, IncomeModel)",
    "docstring": "Create income model from core income"
  },
  {
    "code": "def fw_create(self, data, fw_name=None, cache=False):\n        LOG.debug(\"FW create %s\", data)\n        try:\n            self._fw_create(fw_name, data, cache)\n        except Exception as exc:\n            LOG.error(\"Exception in fw_create %s\", str(exc))",
    "docstring": "Top level FW create function."
  },
  {
    "code": "def _parsePageToken(pageToken, numValues):\n    tokens = pageToken.split(\":\")\n    if len(tokens) != numValues:\n        msg = \"Invalid number of values in page token\"\n        raise exceptions.BadPageTokenException(msg)\n    try:\n        values = map(int, tokens)\n    except ValueError:\n        msg = \"Malformed integers in page token\"\n        raise exceptions.BadPageTokenException(msg)\n    return values",
    "docstring": "Parses the specified pageToken and returns a list of the specified\n    number of values. Page tokens are assumed to consist of a fixed\n    number of integers seperated by colons. If the page token does\n    not conform to this specification, raise a InvalidPageToken\n    exception."
  },
  {
    "code": "def combine_expression_columns(df, columns_to_combine, remove_combined=True):\n    df = df.copy()\n    for ca, cb in columns_to_combine:\n        df[\"%s_(x+y)/2_%s\" % (ca, cb)] = (df[ca] + df[cb]) / 2\n    if remove_combined:\n        for ca, cb in columns_to_combine:\n            df.drop([ca, cb], inplace=True, axis=1)\n    return df",
    "docstring": "Combine expression columns, calculating the mean for 2 columns\n\n\n    :param df: Pandas dataframe\n    :param columns_to_combine: A list of tuples containing the column names to combine\n    :return:"
  },
  {
    "code": "def getTheta(k, nTrials=100000):\n  theDots = np.zeros(nTrials)\n  w1 = getSparseTensor(k, k, nTrials, fixedRange=1.0/k)\n  for i in range(nTrials):\n    theDots[i] = w1[i].dot(w1[i])\n  dotMean = theDots.mean()\n  print(\"k=\", k, \"min/mean/max diag of w dot products\",\n        theDots.min(), dotMean, theDots.max())\n  theta = dotMean / 2.0\n  print(\"Using theta as mean / 2.0 = \", theta)\n  return theta, theDots",
    "docstring": "Estimate a reasonable value of theta for this k."
  },
  {
    "code": "def path(self, path):\n        self._path = self.manager.get_abs_image_path(path)\n        log.info('IOU \"{name}\" [{id}]: IOU image updated to \"{path}\"'.format(name=self._name, id=self._id, path=self._path))",
    "docstring": "Path of the IOU executable.\n\n        :param path: path to the IOU image executable"
  },
  {
    "code": "def from_config(cls, shelf, obj, **kwargs):\n        def subdict(d, keys):\n            new = {}\n            for k in keys:\n                if k in d:\n                    new[k] = d[k]\n            return new\n        core_kwargs = subdict(obj, recipe_schema['schema'].keys())\n        core_kwargs = normalize_schema(recipe_schema, core_kwargs)\n        core_kwargs['filters'] = [\n            parse_condition(filter, shelf.Meta.select_from)\n            if isinstance(filter, dict)\n            else filter\n            for filter in obj.get('filters', [])\n        ]\n        core_kwargs.update(kwargs)\n        recipe = cls(shelf=shelf, **core_kwargs)\n        for ext in recipe.recipe_extensions:\n            additional_schema = getattr(ext, 'recipe_schema', None)\n            if additional_schema is not None:\n                ext_data = subdict(obj, additional_schema.keys())\n                ext_data = normalize_dict(additional_schema, ext_data)\n                recipe = ext.from_config(ext_data)\n        return recipe",
    "docstring": "Construct a Recipe from a plain Python dictionary.\n\n        Most of the directives only support named ingredients, specified as\n        strings, and looked up on the shelf. But filters can be specified as\n        objects.\n\n        Additionally, each RecipeExtension can extract and handle data from the\n        configuration."
  },
  {
    "code": "def process_fasta(fasta, **kwargs):\n    logging.info(\"Nanoget: Starting to collect statistics from a fasta file.\")\n    inputfasta = handle_compressed_input(fasta, file_type=\"fasta\")\n    return ut.reduce_memory_usage(pd.DataFrame(\n        data=[len(rec) for rec in SeqIO.parse(inputfasta, \"fasta\")],\n        columns=[\"lengths\"]\n    ).dropna())",
    "docstring": "Combine metrics extracted from a fasta file."
  },
  {
    "code": "def authority(self, column=None, value=None, **kwargs):\n        return self._resolve_call('GIC_AUTHORITY', column, value, **kwargs)",
    "docstring": "Provides codes and associated authorizing statutes."
  },
  {
    "code": "def txn_storeAssociation(self, server_url, association):\n        a = association\n        self.db_set_assoc(\n            server_url,\n            a.handle,\n            self.blobEncode(a.secret),\n            a.issued,\n            a.lifetime,\n            a.assoc_type)",
    "docstring": "Set the association for the server URL.\n\n        Association -> NoneType"
  },
  {
    "code": "def gram_schmidt(matrix, return_opt='orthonormal'):\n    r\n    if return_opt not in ('orthonormal', 'orthogonal', 'both'):\n        raise ValueError('Invalid return_opt, options are: \"orthonormal\", '\n                         '\"orthogonal\" or \"both\"')\n    u = []\n    e = []\n    for vector in matrix:\n        if len(u) == 0:\n            u_now = vector\n        else:\n            u_now = vector - sum([project(u_i, vector) for u_i in u])\n        u.append(u_now)\n        e.append(u_now / np.linalg.norm(u_now, 2))\n    u = np.array(u)\n    e = np.array(e)\n    if return_opt == 'orthonormal':\n        return e\n    elif return_opt == 'orthogonal':\n        return u\n    elif return_opt == 'both':\n        return u, e",
    "docstring": "r\"\"\"Gram-Schmit\n\n    This method orthonormalizes the row vectors of the input matrix.\n\n    Parameters\n    ----------\n    matrix : np.ndarray\n        Input matrix array\n    return_opt : str {orthonormal, orthogonal, both}\n        Option to return u, e or both.\n\n    Returns\n    -------\n    Lists of orthogonal vectors, u, and/or orthonormal vectors, e\n\n    Examples\n    --------\n    >>> from modopt.math.matrix import gram_schmidt\n    >>> a = np.arange(9).reshape(3, 3)\n    >>> gram_schmidt(a)\n    array([[ 0.        ,  0.4472136 ,  0.89442719],\n           [ 0.91287093,  0.36514837, -0.18257419],\n           [-1.        ,  0.        ,  0.        ]])\n\n    Notes\n    -----\n    Implementation from:\n    https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process"
  },
  {
    "code": "def numeric_part(s):\n    m = re_numeric_part.match(s)\n    if m:\n        return int(m.group(1))\n    return None",
    "docstring": "Returns the leading numeric part of a string.\n\n    >>> numeric_part(\"20-alpha\")\n    20\n    >>> numeric_part(\"foo\")\n    >>> numeric_part(\"16b\")\n    16"
  },
  {
    "code": "def _validatePullParams(MaxObjectCount, context):\n    if (not isinstance(MaxObjectCount, six.integer_types) or\n            MaxObjectCount < 0):\n        raise ValueError(\n            _format(\"MaxObjectCount parameter must be integer >= 0 but is \"\n                    \"{0!A}\", MaxObjectCount))\n    if context is None or len(context) < 2:\n        raise ValueError(\n            _format(\"Pull... Context parameter must be valid tuple {0!A}\",\n                    context))",
    "docstring": "Validate the input paramaters for the PullInstances,\n        PullInstancesWithPath, and PullInstancePaths requests.\n\n        MaxObjectCount: Must be integer type and ge 0\n\n        context: Must be not None and length ge 2"
  },
  {
    "code": "def is_vert_aligned_left(c):\n    return all(\n        [\n            _to_span(c[i]).sentence.is_visual()\n            and bbox_vert_aligned_left(\n                bbox_from_span(_to_span(c[i])), bbox_from_span(_to_span(c[0]))\n            )\n            for i in range(len(c))\n        ]\n    )",
    "docstring": "Return true if all components are vertically aligned on their left border.\n\n    Vertical alignment means that the bounding boxes of each Mention of c\n    shares a similar x-axis value in the visual rendering of the document. In\n    this function the similarity of the x-axis value is based on the left\n    border of their bounding boxes.\n\n    :param c: The candidate to evaluate\n    :rtype: boolean"
  },
  {
    "code": "def from_status(status, message=None, extra=None):\n    if status in HTTP_STATUS_CODES:\n        return HTTP_STATUS_CODES[status](message=message, extra=extra)\n    else:\n        return Error(\n            code=status, message=message if message else \"Unknown Error\",\n            extra=extra\n        )",
    "docstring": "Try to create an error from status code\n\n    :param int status: HTTP status\n    :param str message: Body content\n    :param dict extra: Additional info\n    :return: An error\n    :rtype: cdumay_rest_client.errors.Error"
  },
  {
    "code": "def _get_acronyms(acronyms):\n    acronyms_str = {}\n    if acronyms:\n        for acronym, expansions in iteritems(acronyms):\n            expansions_str = \", \".join([\"%s (%d)\" % expansion\n                                        for expansion in expansions])\n            acronyms_str[acronym] = expansions_str\n    return [{'acronym': str(key), 'expansion': value.encode('utf8')}\n            for key, value in acronyms_str.iteritems()]",
    "docstring": "Return a formatted list of acronyms."
  },
  {
    "code": "def add(self, data, id='*', maxlen=None, approximate=True):\n        return self.database.xadd(self.key, data, id, maxlen, approximate)",
    "docstring": "Add data to a stream.\n\n        :param dict data: data to add to stream\n        :param id: identifier for message ('*' to automatically append)\n        :param maxlen: maximum length for stream\n        :param approximate: allow stream max length to be approximate\n        :returns: the added message id."
  },
  {
    "code": "def find_peaks(signal):\n    derivative = np.gradient(signal, 2)\n    peaks = np.where(np.diff(np.sign(derivative)))[0]\n    return(peaks)",
    "docstring": "Locate peaks based on derivative.\n\n    Parameters\n    ----------\n    signal : list or array\n        Signal.\n\n    Returns\n    ----------\n    peaks : array\n        An array containing the peak indices.\n\n    Example\n    ----------\n    >>> signal = np.sin(np.arange(0, np.pi*10, 0.05))\n    >>> peaks = nk.find_peaks(signal)\n    >>> nk.plot_events_in_signal(signal, peaks)\n\n    Notes\n    ----------\n    *Authors*\n\n    - `Dominique Makowski <https://dominiquemakowski.github.io/>`_\n\n    *Dependencies*\n\n    - scipy\n    - pandas"
  },
  {
    "code": "def azimuth(lons1, lats1, lons2, lats2):\n    lons1, lats1, lons2, lats2 = _prepare_coords(lons1, lats1, lons2, lats2)\n    cos_lat2 = numpy.cos(lats2)\n    true_course = numpy.degrees(numpy.arctan2(\n        numpy.sin(lons1 - lons2) * cos_lat2,\n        numpy.cos(lats1) * numpy.sin(lats2)\n        - numpy.sin(lats1) * cos_lat2 * numpy.cos(lons1 - lons2)\n    ))\n    return (360 - true_course) % 360",
    "docstring": "Calculate the azimuth between two points or two collections of points.\n\n    Parameters are the same as for :func:`geodetic_distance`.\n\n    Implements an \"alternative formula\" from\n    http://williams.best.vwh.net/avform.htm#Crs\n\n    :returns:\n        Azimuth as an angle between direction to north from first point and\n        direction to the second point measured clockwise in decimal degrees."
  },
  {
    "code": "def cpp_prog_builder(build_context, target):\n    yprint(build_context.conf, 'Build CppProg', target)\n    workspace_dir = build_context.get_workspace('CppProg', target.name)\n    build_cpp(build_context, target, target.compiler_config, workspace_dir)",
    "docstring": "Build a C++ binary executable"
  },
  {
    "code": "def regulatory_program(self, column=None, value=None, **kwargs):\n        return self._resolve_call('RAD_REGULATORY_PROG', column,\n                                  value, **kwargs)",
    "docstring": "Identifies the regulatory authority governing a facility, and, by\n        virtue of that identification, also identifies the regulatory program\n        of interest and the type of facility. \n\n        >>> RADInfo().regulatory_program('sec_cit_ref_flag', 'N')"
  },
  {
    "code": "def is_coord_subset(subset, superset, atol=1e-8):\n    c1 = np.array(subset)\n    c2 = np.array(superset)\n    is_close = np.all(np.abs(c1[:, None, :] - c2[None, :, :]) < atol, axis=-1)\n    any_close = np.any(is_close, axis=-1)\n    return np.all(any_close)",
    "docstring": "Tests if all coords in subset are contained in superset.\n    Doesn't use periodic boundary conditions\n\n    Args:\n        subset, superset: List of coords\n\n    Returns:\n        True if all of subset is in superset."
  },
  {
    "code": "def get_api_endpoints(self, apiname):\n        try:\n            return self.services_by_name\\\n                    .get(apiname)\\\n                    .get(\"endpoints\")\\\n                    .copy()\n        except AttributeError:\n            raise Exception(f\"Couldn't find the API endpoints\")",
    "docstring": "Returns the API endpoints"
  },
  {
    "code": "def double_click(self, on_element=None):\n        if on_element:\n            self.move_to_element(on_element)\n        if self._driver.w3c:\n            self.w3c_actions.pointer_action.double_click()\n            for _ in range(4):\n                self.w3c_actions.key_action.pause()\n        else:\n            self._actions.append(lambda: self._driver.execute(\n                                 Command.DOUBLE_CLICK, {}))\n        return self",
    "docstring": "Double-clicks an element.\n\n        :Args:\n         - on_element: The element to double-click.\n           If None, clicks on current mouse position."
  },
  {
    "code": "def arg_props(self):\n        d = dict(zip([str(e).lower() for e in self.section.property_names], self.args))\n        d[self.term_value_name.lower()] = self.value\n        return d",
    "docstring": "Return the value and scalar properties as a dictionary. Returns only argumnet properties,\n        properties declared on the same row as a term. It will return an entry for all of the args declared by the\n         term's section. Use props to get values of all children and\n        arg props combined"
  },
  {
    "code": "def add_to_group(self, group_path):\n        if self.get_group_path() != group_path:\n            post_data = ADD_GROUP_TEMPLATE.format(connectware_id=self.get_connectware_id(),\n                                                  group_path=group_path)\n            self._conn.put('/ws/DeviceCore', post_data)\n            self._device_json = None",
    "docstring": "Add a device to a group, if the group doesn't exist it is created\n\n        :param group_path: Path or \"name\" of the group"
  },
  {
    "code": "def once(func):\n\t@functools.wraps(func)\n\tdef wrapper(*args, **kwargs):\n\t\tif not hasattr(wrapper, 'saved_result'):\n\t\t\twrapper.saved_result = func(*args, **kwargs)\n\t\treturn wrapper.saved_result\n\twrapper.reset = lambda: vars(wrapper).__delitem__('saved_result')\n\treturn wrapper",
    "docstring": "Decorate func so it's only ever called the first time.\n\n\tThis decorator can ensure that an expensive or non-idempotent function\n\twill not be expensive on subsequent calls and is idempotent.\n\n\t>>> add_three = once(lambda a: a+3)\n\t>>> add_three(3)\n\t6\n\t>>> add_three(9)\n\t6\n\t>>> add_three('12')\n\t6\n\n\tTo reset the stored value, simply clear the property ``saved_result``.\n\n\t>>> del add_three.saved_result\n\t>>> add_three(9)\n\t12\n\t>>> add_three(8)\n\t12\n\n\tOr invoke 'reset()' on it.\n\n\t>>> add_three.reset()\n\t>>> add_three(-3)\n\t0\n\t>>> add_three(0)\n\t0"
  },
  {
    "code": "def getFasta(opened_file, sequence_name):\n    lines = opened_file.readlines()\n    seq=str(\"\")\n    for i in range(0, len(lines)):\n        line = lines[i]\n        if line[0] == \">\":\n            fChr=line.split(\" \")[0].split(\"\\n\")[0]\n            fChr=fChr[1:]\n            if fChr == sequence_name:\n                s=i\n                code=['N','A','C','T','G']\n                firstbase=lines[s+1][0]\n                while firstbase in code:\n                    s=s + 1\n                    seq=seq+lines[s]\n                    firstbase=lines[s+1][0]\n    if len(seq)==0:\n        seq=None\n    else:\n        seq=seq.split(\"\\n\")\n        seq=\"\".join(seq)\n    return seq",
    "docstring": "Retrieves a sequence from an opened multifasta file\n\n    :param opened_file: an opened multifasta file eg. opened_file=open(\"/path/to/file.fa\",'r+')\n    :param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome chromosome:GRCm38:2:1:182113224:1 REF' use: sequence_name=str(2)\n\n    returns: a string with the sequence of interest"
  },
  {
    "code": "def strip_caret_codes(text):\n    text = text.replace('^^', '\\x00')\n    for token, foo in _ANSI_CODES:\n        text = text.replace(token, '')\n    return text.replace('\\x00', '^')",
    "docstring": "Strip out any caret codes from a string."
  },
  {
    "code": "def set_parent(self, child, parent):\n        parents = cmds.listConnections(\"%s.parent\" % child, plugs=True, source=True)\n        if parents:\n            cmds.disconnectAttr(\"%s.parent\" % child, \"%s\" % parents[0])\n        if parent:\n            cmds.connectAttr(\"%s.parent\" % child, \"%s.children\" % parent, force=True, nextAvailable=True)",
    "docstring": "Set the parent of the child reftrack node\n\n        :param child: the child reftrack node\n        :type child: str\n        :param parent: the parent reftrack node\n        :type parent: str\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def fromtree(cls, tree):\n        mets = cls()\n        mets.tree = tree\n        mets._parse_tree(tree)\n        return mets",
    "docstring": "Create a METS from an ElementTree or Element.\n\n        :param ElementTree tree: ElementTree to build a METS document from."
  },
  {
    "code": "def execute_contract_creation(\n    laser_evm, contract_initialization_code, contract_name=None\n) -> Account:\n    open_states = laser_evm.open_states[:]\n    del laser_evm.open_states[:]\n    new_account = laser_evm.world_state.create_account(\n        0, concrete_storage=True, dynamic_loader=None, creator=CREATOR_ADDRESS\n    )\n    if contract_name:\n        new_account.contract_name = contract_name\n    for open_world_state in open_states:\n        next_transaction_id = get_next_transaction_id()\n        transaction = ContractCreationTransaction(\n            world_state=open_world_state,\n            identifier=next_transaction_id,\n            gas_price=symbol_factory.BitVecSym(\n                \"gas_price{}\".format(next_transaction_id), 256\n            ),\n            gas_limit=8000000,\n            origin=symbol_factory.BitVecSym(\n                \"origin{}\".format(next_transaction_id), 256\n            ),\n            code=Disassembly(contract_initialization_code),\n            caller=symbol_factory.BitVecVal(CREATOR_ADDRESS, 256),\n            callee_account=new_account,\n            call_data=[],\n            call_value=symbol_factory.BitVecSym(\n                \"call_value{}\".format(next_transaction_id), 256\n            ),\n        )\n        _setup_global_state_for_execution(laser_evm, transaction)\n    laser_evm.exec(True)\n    return new_account",
    "docstring": "Executes a contract creation transaction from all open states.\n\n    :param laser_evm:\n    :param contract_initialization_code:\n    :param contract_name:\n    :return:"
  },
  {
    "code": "def opponent_rank(self):\n        rank = re.findall(r'\\d+', self._opponent_name)\n        if len(rank) > 0:\n            return int(rank[0])\n        return None",
    "docstring": "Returns a ``string`` of the opponent's rank when the game was played\n        and None if the team was unranked."
  },
  {
    "code": "def transform(self, sequences):\n        check_iter_of_sequences(sequences)\n        transforms = []\n        for X in sequences:\n            transforms.append(self.partial_transform(X))\n        return transforms",
    "docstring": "Apply dimensionality reduction to sequences\n\n        Parameters\n        ----------\n        sequences: list of array-like, each of shape (n_samples_i, n_features)\n            Sequence data to transform, where n_samples_i in the number of samples\n            in sequence i and n_features is the number of features.\n\n        Returns\n        -------\n        sequence_new : list of array-like, each of shape (n_samples_i, n_components)"
  },
  {
    "code": "def time_from_number(self, value):\n        if not isinstance(value, numbers.Real):\n            return None\n        delta = datetime.timedelta(days=value)\n        minutes, second = divmod(delta.seconds, 60)\n        hour, minute = divmod(minutes, 60)\n        return datetime.time(hour, minute, second)",
    "docstring": "Converts a float value to corresponding time instance."
  },
  {
    "code": "def frames(skip=1):\n    from PyQt4 import QtGui\n    for i in range(0, viewer.traj_controls.max_index, skip):\n        viewer.traj_controls.goto_frame(i)\n        yield i\n        QtGui.qApp.processEvents()",
    "docstring": "Useful command to iterate on the trajectory frames. It can be\n    used in a for loop.\n\n    ::\n    \n        for i in frames():\n            coords = current_trajectory()[i]\n            # Do operation on coords\n\n    You can use the option *skip* to take every i :sup:`th` frame."
  },
  {
    "code": "def str(password,\n        opslimit=OPSLIMIT_INTERACTIVE,\n        memlimit=MEMLIMIT_INTERACTIVE):\n    return nacl.bindings.crypto_pwhash_scryptsalsa208sha256_str(password,\n                                                                opslimit,\n                                                                memlimit)",
    "docstring": "Hashes a password with a random salt, using the memory-hard\n    scryptsalsa208sha256 construct and returning an ascii string\n    that has all the needed info to check against a future password\n\n    The default settings for opslimit and memlimit are those deemed\n    correct for the interactive user login case.\n\n    :param bytes password:\n    :param int opslimit:\n    :param int memlimit:\n    :rtype: bytes\n\n    .. versionadded:: 1.2"
  },
  {
    "code": "def pop(self, strip=False):\n        r = self.contents()\n        self.clear()\n        if r and strip:\n            r = r.strip()\n        return r",
    "docstring": "Current content popped, useful for testing"
  },
  {
    "code": "def access_token(self):\n        access_token = self.get_auth_bearer()\n        if not access_token:\n            access_token = self.query_kwargs.get('access_token', '')\n            if not access_token:\n                access_token = self.body_kwargs.get('access_token', '')\n        return access_token",
    "docstring": "return an Oauth 2.0 Bearer access token if it can be found"
  },
  {
    "code": "def to_json(self, obj, host=None, indent=None):\n        if indent:\n            return json.dumps(deep_map(lambda o: self.encode(o, host), obj),\n                              indent=indent)\n        else:\n            return json.dumps(deep_map(lambda o: self.encode(o, host), obj))",
    "docstring": "Recursively encode `obj` and convert it to a JSON string.\n\n        :param obj:\n            Object to encode.\n\n        :param host:\n            hostname where this object is being encoded.\n        :type host: str"
  },
  {
    "code": "def get(key, value=None, conf_file=_DEFAULT_CONF):\n    current_conf = _parse_conf(conf_file)\n    stanza = current_conf.get(key, False)\n    if value:\n        if stanza:\n            return stanza.get(value, False)\n        _LOG.warning(\"Block '%s' not present or empty.\", key)\n    return stanza",
    "docstring": "Get the value for a specific configuration line.\n\n    :param str key: The command or stanza block to configure.\n    :param str value: The command value or command of the block specified by the key parameter.\n    :param str conf_file: The logrotate configuration file.\n\n    :return: The value for a specific configuration line.\n    :rtype: bool|int|str\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' logrotate.get rotate\n\n        salt '*' logrotate.get /var/log/wtmp rotate /etc/logrotate.conf"
  },
  {
    "code": "def update_kwargs(self, request, **kwargs):\n        if not 'base' in kwargs:\n            kwargs['base'] = self.base\n            if request.is_ajax() or request.GET.get('json'):\n                kwargs['base'] = self.partial_base\n        return kwargs",
    "docstring": "Hook for adding data to the context before\n        rendering a template.\n\n        :param kwargs: The current context keyword arguments.\n        :param request: The current request object."
  },
  {
    "code": "def _bin_zfill(num, width=None):\n    s = bin(num)[2:]\n    return s if width is None else s.zfill(width)",
    "docstring": "Convert a base-10 number to a binary string.\n\n    Parameters\n    num: int\n    width: int, optional\n        Zero-extend the string to this width.\n    Examples\n    --------\n\n    >>> _bin_zfill(42)\n    '101010'\n    >>> _bin_zfill(42, 8)\n    '00101010'"
  },
  {
    "code": "def lookup_online(byte_sig: str, timeout: int, proxies=None) -> List[str]:\n        if not ethereum_input_decoder:\n            return []\n        return list(\n            ethereum_input_decoder.decoder.FourByteDirectory.lookup_signatures(\n                byte_sig, timeout=timeout, proxies=proxies\n            )\n        )",
    "docstring": "Lookup function signatures from 4byte.directory.\n\n        :param byte_sig: function signature hash as hexstr\n        :param timeout: optional timeout for online lookup\n        :param proxies: optional proxy servers for online lookup\n        :return: a list of matching function signatures for this hash"
  },
  {
    "code": "def _short_chrom(self, chrom):\n        default_allowed = set([\"X\"])\n        allowed_chroms = set(getattr(config, \"goleft_indexcov_config\", {}).get(\"chromosomes\", []))\n        chrom_clean = chrom.replace(\"chr\", \"\")\n        try:\n            chrom_clean = int(chrom_clean)\n        except ValueError:\n            if chrom_clean not in default_allowed and chrom_clean not in allowed_chroms:\n                chrom_clean = None\n        if allowed_chroms:\n            if chrom in allowed_chroms or chrom_clean in allowed_chroms:\n                return chrom_clean\n        elif isinstance(chrom_clean, int) or chrom_clean in default_allowed:\n            return chrom_clean",
    "docstring": "Plot standard chromosomes + X, sorted numerically.\n\n        Allows specification from a list of chromosomes via config\n        for non-standard genomes."
  },
  {
    "code": "def addChildFn(self, fn, *args, **kwargs):\n        if PromisedRequirement.convertPromises(kwargs):\n            return self.addChild(PromisedRequirementFunctionWrappingJob.create(fn, *args, **kwargs))\n        else:\n            return self.addChild(FunctionWrappingJob(fn, *args, **kwargs))",
    "docstring": "Adds a function as a child job.\n\n        :param fn: Function to be run as a child job with ``*args`` and ``**kwargs`` as \\\n        arguments to this function. See toil.job.FunctionWrappingJob for reserved \\\n        keyword arguments used to specify resource requirements.\n        :return: The new child job that wraps fn.\n        :rtype: toil.job.FunctionWrappingJob"
  },
  {
    "code": "def __set_authoring_nodes(self, source, target):\n        editor = self.__script_editor.get_editor(source)\n        editor.set_file(target)\n        self.__script_editor.model.update_authoring_nodes(editor)",
    "docstring": "Sets given editor authoring nodes.\n\n        :param source: Source file.\n        :type source: unicode\n        :param target: Target file.\n        :type target: unicode"
  },
  {
    "code": "def find_orphans(model):\n    exchange = frozenset(model.exchanges)\n    return [\n        met for met in model.metabolites\n        if (len(met.reactions) > 0) and all(\n            (not rxn.reversibility) and (rxn not in exchange) and\n            (rxn.metabolites[met] < 0) for rxn in met.reactions\n        )\n    ]",
    "docstring": "Return metabolites that are only consumed in reactions.\n\n    Metabolites that are involved in an exchange reaction are never\n    considered to be orphaned.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model under investigation."
  },
  {
    "code": "def _GetUtf8Contents(self, file_name):\n    contents = self._FileContents(file_name)\n    if not contents:\n      return\n    if len(contents) >= 2 and contents[0:2] in (codecs.BOM_UTF16_BE,\n        codecs.BOM_UTF16_LE):\n      self._problems.FileFormat(\"appears to be encoded in utf-16\", (file_name, ))\n      contents = codecs.getdecoder('utf-16')(contents)[0].encode('utf-8')\n    null_index = contents.find('\\0')\n    if null_index != -1:\n      m = re.search(r'.{,20}\\0.{,20}', contents, re.DOTALL)\n      self._problems.FileFormat(\n          \"contains a null in text \\\"%s\\\" at byte %d\" %\n          (codecs.getencoder('string_escape')(m.group()), null_index + 1),\n          (file_name, ))\n      return\n    contents = contents.lstrip(codecs.BOM_UTF8)\n    return contents",
    "docstring": "Check for errors in file_name and return a string for csv reader."
  },
  {
    "code": "def read_cBpack(filename):\n    with gzip.open(filename, 'rb') as infile:\n        data = msgpack.load(infile, raw=False)\n    header = data[0]\n    if (\n        not isinstance(header, dict) or header.get('format') != 'cB'\n        or header.get('version') != 1\n    ):\n        raise ValueError(\"Unexpected header: %r\" % header)\n    return data[1:]",
    "docstring": "Read a file from an idiosyncratic format that we use for storing\n    approximate word frequencies, called \"cBpack\".\n\n    The cBpack format is as follows:\n\n    - The file on disk is a gzipped file in msgpack format, which decodes to a\n      list whose first element is a header, and whose remaining elements are\n      lists of words.\n\n    - The header is a dictionary with 'format' and 'version' keys that make\n      sure that we're reading the right thing.\n\n    - Each inner list of words corresponds to a particular word frequency,\n      rounded to the nearest centibel -- that is, one tenth of a decibel, or\n      a factor of 10 ** .01.\n\n      0 cB represents a word that occurs with probability 1, so it is the only\n      word in the data (this of course doesn't happen). -200 cB represents a\n      word that occurs once per 100 tokens, -300 cB represents a word that\n      occurs once per 1000 tokens, and so on.\n\n    - The index of each list within the overall list (without the header) is\n      the negative of its frequency in centibels.\n\n    - Each inner list is sorted in alphabetical order.\n\n    As an example, consider a corpus consisting only of the words \"red fish\n    blue fish\". The word \"fish\" occurs as 50% of tokens (-30 cB), while \"red\"\n    and \"blue\" occur as 25% of tokens (-60 cB). The cBpack file of their word\n    frequencies would decode to this:\n\n        [\n            {'format': 'cB', 'version': 1},\n            [], [], [], ...    # 30 empty lists\n            ['fish'],\n            [], [], [], ...    # 29 more empty lists\n            ['blue', 'red']\n        ]"
  },
  {
    "code": "def archive(cwd, output, rev='tip', fmt=None, prefix=None, user=None):\n    cmd = [\n            'hg',\n            'archive',\n            '{0}'.format(output),\n            '--rev',\n            '{0}'.format(rev),\n            ]\n    if fmt:\n        cmd.append('--type')\n        cmd.append('{0}'.format(fmt))\n    if prefix:\n        cmd.append('--prefix')\n        cmd.append('\"{0}\"'.format(prefix))\n    return __salt__['cmd.run'](cmd, cwd=cwd, runas=user, python_shell=False)",
    "docstring": "Export a tarball from the repository\n\n    cwd\n        The path to the Mercurial repository\n\n    output\n        The path to the archive tarball\n\n    rev: tip\n        The revision to create an archive from\n\n    fmt: None\n        Format of the resulting archive. Mercurial supports: tar,\n        tbz2, tgz, zip, uzip, and files formats.\n\n    prefix : None\n        Prepend <prefix>/ to every filename in the archive\n\n    user : None\n        Run hg as a user other than what the minion runs as\n\n    If ``prefix`` is not specified it defaults to the basename of the repo\n    directory.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' hg.archive /path/to/repo output=/tmp/archive.tgz fmt=tgz"
  },
  {
    "code": "def no_retry_on_failure(handler):\n    seen_request_ids = set()\n    @wraps(handler)\n    def wrapper(event, context):\n        if context.aws_request_id in seen_request_ids:\n            logger.critical('Retry attempt on request id %s detected.',\n                            context.aws_request_id)\n            return {'statusCode': 200}\n        seen_request_ids.add(context.aws_request_id)\n        return handler(event, context)\n    return wrapper",
    "docstring": "AWS Lambda retries scheduled lambdas that don't execute succesfully.\n\n    This detects this by storing requests IDs in memory and exiting early on\n    duplicates. Since this is in memory, don't use it on very frequently\n    scheduled lambdas. It logs a critical message then exits with a statusCode\n    of 200 to avoid further\n    retries.\n\n    Usage::\n\n      >>> import logging, sys\n      >>> from lambda_decorators import no_retry_on_failure, logger\n      >>> logger.addHandler(logging.StreamHandler(stream=sys.stdout))\n      >>> @no_retry_on_failure\n      ... def scheduled_handler(event, context):\n      ...     return {'statusCode': 500}\n      >>> class Context:\n      ...     aws_request_id = 1\n      >>> scheduled_handler({}, Context())\n      {'statusCode': 500}\n      >>> scheduled_handler({}, Context())\n      Retry attempt on request id 1 detected.\n      {'statusCode': 200}"
  },
  {
    "code": "def merge_dicts(target_dict: dict, merge_dict: dict) -> dict:\n    log.debug(\"merging dict %s into %s\", merge_dict, target_dict)\n    for key, value in merge_dict.items():\n        if key not in target_dict:\n            target_dict[key] = value\n    return target_dict",
    "docstring": "Merges ``merge_dict`` into ``target_dict`` if the latter does not already contain a value for each of the key\n    names in ``merge_dict``. Used to cleanly merge default and environ data into notification payload.\n\n    :param target_dict: The target dict to merge into and return, the user provided data for example\n    :param merge_dict: The data that should be merged into the target data\n    :return: A dict of merged data"
  },
  {
    "code": "def intr_read(self, dev_handle, ep, intf, size, timeout):\n        r\n        _not_implemented(self.intr_read)",
    "docstring": "r\"\"\"Perform an interrut read.\n\n        dev_handle is the value returned by the open_device() method.\n        The ep parameter is the bEndpointAddress field whose endpoint\n        the data will be received from. intf is the bInterfaceNumber field\n        of the interface containing the endpoint. The buff parameter\n        is the buffer to receive the data read, the length of the buffer\n        tells how many bytes should be read.  The timeout parameter\n        specifies a time limit to the operation in miliseconds.\n\n        The method returns the number of bytes actually read."
  },
  {
    "code": "def _load_configuration():\n    config = configparser.RawConfigParser()\n    module_dir = os.path.dirname(sys.modules[__name__].__file__)\n    if 'APPDATA' in os.environ:\n        os_config_path = os.environ['APPDATA']\n    elif 'XDG_CONFIG_HOME' in os.environ:\n        os_config_path = os.environ['XDG_CONFIG_HOME']\n    elif 'HOME' in os.environ:\n        os_config_path = os.path.join(os.environ['HOME'], '.config')\n    else:\n        os_config_path = None\n    locations = [os.path.join(module_dir, 'praw.ini'), 'praw.ini']\n    if os_config_path is not None:\n        locations.insert(1, os.path.join(os_config_path, 'praw.ini'))\n    if not config.read(locations):\n        raise Exception('Could not find config file in any of: {0}'\n                        .format(locations))\n    return config",
    "docstring": "Attempt to load settings from various praw.ini files."
  },
  {
    "code": "def set_pair(self, term1, term2, value, **kwargs):\n        key = self.key(term1, term2)\n        self.keys.update([term1, term2])\n        self.pairs[key] = value",
    "docstring": "Set the value for a pair of terms.\n\n        Args:\n            term1 (str)\n            term2 (str)\n            value (mixed)"
  },
  {
    "code": "def scramble_codelist(self, codelist):\n        path = \".//{0}[@{1}='{2}']\".format(E_ODM.CODELIST.value, A_ODM.OID.value, codelist)\n        elem = self.metadata.find(path)\n        codes = []\n        for c in elem.iter(E_ODM.CODELIST_ITEM.value):\n            codes.append(c.get(A_ODM.CODED_VALUE.value))\n        for c in elem.iter(E_ODM.ENUMERATED_ITEM.value):\n            codes.append(c.get(A_ODM.CODED_VALUE.value))\n        return fake.random_element(codes)",
    "docstring": "Return random element from code list"
  },
  {
    "code": "def _correctArtefacts(self, image, threshold):\r\n        image = np.nan_to_num(image)\r\n        medianThreshold(image, threshold, copy=False)\r\n        return image",
    "docstring": "Apply a thresholded median replacing high gradients \r\n        and values beyond the boundaries"
  },
  {
    "code": "def _infer_sequence_helper(node, context=None):\n    values = []\n    for elt in node.elts:\n        if isinstance(elt, nodes.Starred):\n            starred = helpers.safe_infer(elt.value, context)\n            if not starred:\n                raise exceptions.InferenceError(node=node, context=context)\n            if not hasattr(starred, \"elts\"):\n                raise exceptions.InferenceError(node=node, context=context)\n            values.extend(_infer_sequence_helper(starred))\n        else:\n            values.append(elt)\n    return values",
    "docstring": "Infer all values based on _BaseContainer.elts"
  },
  {
    "code": "def do_denyrep(self, line):\n        self._split_args(line, 0, 0)\n        self._command_processor.get_session().get_replication_policy().set_replication_allowed(\n            False\n        )\n        self._print_info_if_verbose(\"Set replication policy to deny replication\")",
    "docstring": "denyrep Prevent new objects from being replicated."
  },
  {
    "code": "def tx(self, *args, **kwargs):\n    if 0 == len(args): return TX(self) \n    ops = []\n    for op in args:\n      if isinstance(op, list):            ops += op\n      elif isinstance(op, (str,unicode)): ops.append(op)\n    if 'debug' in kwargs: pp(ops)\n    tx_proc =\"[ %s ]\" % \"\".join(ops)\n    x = self.rest('POST', self.uri_db, data={\"tx-data\": tx_proc})\n    return x",
    "docstring": "Executes a raw tx string, or get a new TX object to work with.\n\n    Passing a raw string or list of strings will immedately transact \n    and return the API response as a dict.\n    >>> resp = tx('{:db/id #db/id[:db.part/user] :person/name \"Bob\"}')\n    {db-before: db-after: tempids: }\n\n    This gets a fresh `TX()` to prepare a transaction with.\n    >>> tx = db.tx()\n\n    New `E()` object with person/fname and person/lname attributes\n    >>> person = tx.add('person/',   {'fname':'John', 'lname':'Doe'})\n\n    New state and city objects referencing the state\n    >>> state  = tx.add('loc/state', 'WA')\n    >>> city   = tx.add('loc/city',  'Seattle', 'isin', state)\n\n    Add person/city, person/state, and person/likes refs to the person entity\n    >>> person.add('person/', {'city': city, 'state': state, 'likes': [city, state]})\n\n    Excute the transaction\n    >>> resp = tx.tx()        \n\n    The resolved entity ids for our person\n    >>> person.eid, state.eid, city.eid\n\n    Fetch all attributes, behave like a dict\n    >>> person.items()\n    >>> person.iteritems()\n\n    Access attribute as an attribute\n    >>> person['person/name']\n\n    See `TX()` for options."
  },
  {
    "code": "def parse(self, buf):\n        self._tokenizer = tokenize_asdl(buf)\n        self._advance()\n        return self._parse_module()",
    "docstring": "Parse the ASDL in the buffer and return an AST with a Module root."
  },
  {
    "code": "def f_ac_power(inverter, v_mp, p_mp):\n    return pvlib.pvsystem.snlinverter(v_mp, p_mp, inverter).flatten()",
    "docstring": "Calculate AC power\n\n    :param inverter:\n    :param v_mp:\n    :param p_mp:\n    :return: AC power [W]"
  },
  {
    "code": "def _set_advertising_data(self, packet_type, data):\n        payload = struct.pack(\"<BB%ss\" % (len(data)), packet_type, len(data), bytes(data))\n        response = self._send_command(6, 9, payload)\n        result, = unpack(\"<H\", response.payload)\n        if result != 0:\n            return False, {'reason': 'Error code from BLED112 setting advertising data', 'code': result}\n        return True, None",
    "docstring": "Set the advertising data for advertisements sent out by this bled112\n\n        Args:\n            packet_type (int): 0 for advertisement, 1 for scan response\n            data (bytearray): the data to set"
  },
  {
    "code": "def add_checkpoint(html_note, counter):\n    if html_note.text:\n        html_note.text = (html_note.text + CHECKPOINT_PREFIX +\n                          str(counter) + CHECKPOINT_SUFFIX)\n    else:\n        html_note.text = (CHECKPOINT_PREFIX + str(counter) +\n                          CHECKPOINT_SUFFIX)\n    counter += 1\n    for child in html_note.iterchildren():\n        counter = add_checkpoint(child, counter)\n    if html_note.tail:\n        html_note.tail = (html_note.tail + CHECKPOINT_PREFIX +\n                          str(counter) + CHECKPOINT_SUFFIX)\n    else:\n        html_note.tail = (CHECKPOINT_PREFIX + str(counter) +\n                          CHECKPOINT_SUFFIX)\n    counter += 1\n    return counter",
    "docstring": "Recursively adds checkpoints to html tree."
  },
  {
    "code": "async def _run_socket(self):\n        try:\n            while True:\n                message = await ZMQUtils.recv(self._socket)\n                msg_class = message.__msgtype__\n                if msg_class in self._handlers_registered:\n                    self._loop.create_task(self._handlers_registered[msg_class](message))\n                elif msg_class in self._transactions:\n                    _1, get_key, coroutine_recv, _2, responsible = self._msgs_registered[msg_class]\n                    key = get_key(message)\n                    if key in self._transactions[msg_class]:\n                        for args, kwargs in self._transactions[msg_class][key]:\n                            self._loop.create_task(coroutine_recv(message, *args, **kwargs))\n                        for key2 in responsible:\n                            del self._transactions[key2][key]\n                    else:\n                        raise Exception(\"Received message %s for an unknown transaction %s\", msg_class, key)\n                else:\n                    raise Exception(\"Received unknown message %s\", msg_class)\n        except asyncio.CancelledError:\n            return\n        except KeyboardInterrupt:\n            return",
    "docstring": "Task that runs this client."
  },
  {
    "code": "def read_csv(filepath):\n    symbols = []\n    with open(filepath, 'rb') as csvfile:\n        spamreader = csv.DictReader(csvfile, delimiter=',', quotechar='\"')\n        for row in spamreader:\n            symbols.append(row)\n    return symbols",
    "docstring": "Read a CSV into a list of dictionarys. The first line of the CSV determines\n    the keys of the dictionary.\n\n    Parameters\n    ----------\n    filepath : string\n\n    Returns\n    -------\n    list of dictionaries"
  },
  {
    "code": "def vim_enter(self, filename):\n        success = self.setup(True, False)\n        if success:\n            self.editor.message(\"start_message\")",
    "docstring": "Set up EnsimeClient when vim enters.\n\n        This is useful to start the EnsimeLauncher as soon as possible."
  },
  {
    "code": "def route(cls, path):\n    if not path.startswith('/'):\n      raise ValueError('Routes must start with \"/\"')\n    def wrap(fn):\n      setattr(fn, cls.ROUTE_ATTRIBUTE, path)\n      return fn\n    return wrap",
    "docstring": "A decorator to indicate that a method should be a routable HTTP endpoint.\n\n    .. code-block:: python\n\n        from compactor.process import Process\n\n        class WebProcess(Process):\n          @Process.route('/hello/world')\n          def hello_world(self, handler):\n            return handler.write('<html><title>hello world</title></html>')\n\n    The handler passed to the method is a tornado RequestHandler.\n\n    WARNING: This interface is alpha and may change in the future if or when\n    we remove tornado as a compactor dependency.\n\n    :param path: The endpoint to route to this method.\n    :type path: ``str``"
  },
  {
    "code": "def ts_stream_keys(self, table, timeout=None):\n        if not riak.disable_list_exceptions:\n            raise ListError()\n        t = table\n        if isinstance(t, six.string_types):\n            t = Table(self, table)\n        _validate_timeout(timeout)\n        resource = self._acquire()\n        transport = resource.object\n        stream = transport.ts_stream_keys(t, timeout)\n        stream.attach(resource)\n        try:\n            for keylist in stream:\n                if len(keylist) > 0:\n                    yield keylist\n        finally:\n            stream.close()",
    "docstring": "Lists all keys in a time series table via a stream. This is a\n        generator method which should be iterated over.\n\n        The caller should explicitly close the returned iterator,\n        either using :func:`contextlib.closing` or calling ``close()``\n        explicitly. Consuming the entire iterator will also close the\n        stream. If it does not, the associated connection might\n        not be returned to the pool. Example::\n\n            from contextlib import closing\n\n            # Using contextlib.closing\n            with closing(client.ts_stream_keys(mytable)) as keys:\n                for key_list in keys:\n                    do_something(key_list)\n\n            # Explicit close()\n            stream = client.ts_stream_keys(mytable)\n            for key_list in stream:\n                 do_something(key_list)\n            stream.close()\n\n        :param table: the table from which to stream keys\n        :type table: string or :class:`Table <riak.table.Table>`\n        :param timeout: a timeout value in milliseconds\n        :type timeout: int\n        :rtype: iterator"
  },
  {
    "code": "def inputfiles(self, inputtemplate=None):\n        if isinstance(inputtemplate, InputTemplate):\n            inputtemplate = inputtemplate.id\n        for inputfile in self.input:\n            if not inputtemplate or inputfile.metadata.inputtemplate == inputtemplate:\n                yield inputfile",
    "docstring": "Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned regardless of inputtemplate."
  },
  {
    "code": "def get_methods(extension_name):\n    extension = get_extension(extension_name)\n    methods = {}\n    for name, i in inspect.getmembers(extension):\n        if hasattr(i, 'nago_access'):\n            api_name = i.nago_name\n            methods[api_name] = i\n    return methods",
    "docstring": "Return all methods in extension that have nago_access set"
  },
  {
    "code": "def process_polychord_run(file_root, base_dir, process_stats_file=True,\n                          **kwargs):\n    samples = np.loadtxt(os.path.join(base_dir, file_root) + '_dead-birth.txt')\n    ns_run = process_samples_array(samples, **kwargs)\n    ns_run['output'] = {'base_dir': base_dir, 'file_root': file_root}\n    if process_stats_file:\n        try:\n            ns_run['output'] = process_polychord_stats(file_root, base_dir)\n        except (OSError, IOError, ValueError) as err:\n            warnings.warn(\n                ('process_polychord_stats raised {} processing {}.stats file. '\n                 ' Proceeding without stats.').format(\n                     type(err).__name__, os.path.join(base_dir, file_root)),\n                UserWarning)\n    return ns_run",
    "docstring": "Loads data from a PolyChord run into the nestcheck dictionary format for\n    analysis.\n\n    N.B. producing required output file containing information about the\n    iso-likelihood contours within which points were sampled (where they were\n    \"born\") requies PolyChord version v1.13 or later and the setting\n    write_dead=True.\n\n    Parameters\n    ----------\n    file_root: str\n        Root for run output file names (PolyChord file_root setting).\n    base_dir: str\n        Directory containing data (PolyChord base_dir setting).\n    process_stats_file: bool, optional\n        Should PolyChord's <root>.stats file be processed? Set to False if you\n        don't have the <root>.stats file (such as if PolyChord was run with\n        write_stats=False).\n    kwargs: dict, optional\n        Options passed to ns_run_utils.check_ns_run.\n\n    Returns\n    -------\n    ns_run: dict\n        Nested sampling run dict (see the module docstring for more details)."
  },
  {
    "code": "def get_many_to_many_lines(self, force=False):\n        lines = []\n        for field, rel_items in self.many_to_many_waiting_list.items():\n            for rel_item in list(rel_items):\n                try:\n                    pk_name = rel_item._meta.pk.name\n                    key = '%s_%s' % (rel_item.__class__.__name__, getattr(rel_item, pk_name))\n                    value = \"%s\" % self.context[key]\n                    lines.append('%s.%s.add(%s)' % (self.variable_name, field.name, value))\n                    self.many_to_many_waiting_list[field].remove(rel_item)\n                except KeyError:\n                    if force:\n                        item_locator = orm_item_locator(rel_item)\n                        self.context[\"__extra_imports\"][rel_item._meta.object_name] = rel_item.__module__\n                        lines.append('%s.%s.add( %s )' % (self.variable_name, field.name, item_locator))\n                        self.many_to_many_waiting_list[field].remove(rel_item)\n        if lines:\n            lines.append(\"\")\n        return lines",
    "docstring": "Generate lines that define many to many relations for this instance."
  },
  {
    "code": "def _notify(self, task, message):\n        if self.notify_func:\n            message = common.to_utf8(message.strip())\n            title = common.to_utf8(u'Focus ({0})'.format(task.name))\n            self.notify_func(title, message)",
    "docstring": "Shows system notification message according to system requirements.\n\n            `message`\n                Status message."
  },
  {
    "code": "def get_path_directories():\n    pth = os.environ['PATH']\n    if sys.platform == 'win32' and os.environ.get(\"BASH\"):\n        if pth[1] == ';':\n            pth = pth.replace(';', ':', 1)\n    return [p.strip() for p in pth.split(os.pathsep) if p.strip()]",
    "docstring": "Return a list of all the directories on the path."
  },
  {
    "code": "def __get_service_from_factory(self, bundle, reference):\n        try:\n            factory, svc_reg = self.__svc_factories[reference]\n            imports = self.__bundle_imports.setdefault(bundle, {})\n            if reference not in imports:\n                usage_counter = _UsageCounter()\n                usage_counter.inc()\n                imports[reference] = usage_counter\n                reference.used_by(bundle)\n            factory_counter = self.__factory_usage.setdefault(\n                bundle, _FactoryCounter(bundle)\n            )\n            return factory_counter.get_service(factory, svc_reg)\n        except KeyError:\n            raise BundleException(\n                \"Service not found (reference: {0})\".format(reference)\n            )",
    "docstring": "Returns a service instance from a service factory or a prototype\n        service factory\n\n        :param bundle: The bundle requiring the service\n        :param reference: A reference pointing to a factory\n        :return: The requested service\n        :raise BundleException: The service could not be found"
  },
  {
    "code": "def transpose(self, name=None):\n    if name is None:\n      name = self.module_name + \"_transpose\"\n    if self._data_format == DATA_FORMAT_NWC:\n      stride = self._stride[1:-1]\n    else:\n      stride = self._stride[2:]\n    return Conv1D(output_channels=lambda: self.input_channels,\n                  kernel_shape=self.kernel_shape,\n                  stride=stride,\n                  padding=self.padding,\n                  use_bias=self._use_bias,\n                  initializers=self.initializers,\n                  partitioners=self.partitioners,\n                  regularizers=self.regularizers,\n                  data_format=self._data_format,\n                  custom_getter=self._custom_getter,\n                  name=name)",
    "docstring": "Returns matching `Conv1D` module.\n\n    Args:\n      name: Optional string assigning name of transpose module. The default name\n        is constructed by appending \"_transpose\" to `self.name`.\n\n    Returns:\n      `Conv1D` module."
  },
  {
    "code": "def workflows(self):\n        if self._workflows is None:\n            self._workflows = WorkflowList(self._version, workspace_sid=self._solution['sid'], )\n        return self._workflows",
    "docstring": "Access the workflows\n\n        :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList\n        :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowList"
  },
  {
    "code": "def get_resultsets(self, routine, *args):\n        (query, replacements) = self.__build_raw_query(routine, args)\n        connection = mm.db.ENGINE.raw_connection()\n        sets = []\n        try:\n            cursor = connection.cursor()\n            cursor.execute(query, replacements)\n            while 1:\n                names = [c[0] for c in cursor.description]\n                set_ = []\n                while 1:\n                    row_raw = cursor.fetchone()\n                    if row_raw is None:\n                        break\n                    row = dict(zip(names, row_raw))\n                    set_.append(row)\n                sets.append(list(set_))\n                if cursor.nextset() is None:\n                    break\n                if cursor.description is None:\n                    break\n        finally:\n            connection.close()\n        return sets",
    "docstring": "Return a list of lists of dictionaries, for when a query returns \n        more than one resultset."
  },
  {
    "code": "def get_last_commit_to_master(repo_path=\".\"):\n    last_commit = None\n    repo = None\n    try:\n        repo = Repo(repo_path)\n    except (InvalidGitRepositoryError, NoSuchPathError):\n        repo = None\n    if repo:\n        try:\n            last_commit = repo.commits()[0]\n        except AttributeError:\n            last_commit = repo.head.commit\n    return str(last_commit)",
    "docstring": "returns the last commit on the master branch. It would be more ideal to get the commit\n    from the branch we are currently on, but as this is a check mostly to help\n    with production issues, returning the commit from master will be sufficient."
  },
  {
    "code": "def remove_showcase(self, showcase):\n        dataset_showcase = self._get_dataset_showcase_dict(showcase)\n        showcase = hdx.data.showcase.Showcase({'id': dataset_showcase['showcase_id']}, configuration=self.configuration)\n        showcase._write_to_hdx('disassociate', dataset_showcase, 'package_id')",
    "docstring": "Remove dataset from showcase\n\n        Args:\n            showcase (Union[Showcase,Dict,str]): Either a showcase id string or showcase metadata from a Showcase object or dictionary\n\n        Returns:\n            None"
  },
  {
    "code": "def _update(self, data):\n      self.orderby = data['orderby']\n      self.revision = data['revisionid']\n      self.title = data['title']\n      self.lines = [Line(self.guideid, self.stepid, line['lineid'], data=line)\n                    for line in data['lines']]\n      if data['media']['type'] == 'image':\n         self.media = []\n         for image in data['media']['data']:\n            self.media.append(Image(image['id']))",
    "docstring": "Update the step using the blob of json-parsed data directly from the\n      API."
  },
  {
    "code": "def get_hosted_zones_by_domain(Name, region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    zones = [z for z in _collect_results(conn.list_hosted_zones, 'HostedZones', {})\n            if z['Name'] == aws_encode(Name)]\n    ret = []\n    for z in zones:\n        ret += get_hosted_zone(Id=z['Id'], region=region, key=key, keyid=keyid, profile=profile)\n    return ret",
    "docstring": "Find any zones with the given domain name and return detailed info about them.\n    Note that this can return multiple Route53 zones, since a domain name can be used in\n    both public and private zones.\n\n    Name\n        The domain name associated with the Hosted Zone(s).\n\n    region\n        Region to connect to.\n\n    key\n        Secret key to be used.\n\n    keyid\n        Access key to be used.\n\n    profile\n        Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto3_route53.get_hosted_zones_by_domain salt.org. \\\n                profile='{\"region\": \"us-east-1\", \"keyid\": \"A12345678AB\", \"key\": \"xblahblahblah\"}'"
  },
  {
    "code": "def _ssh_build_mic(self, session_id, username, service, auth_method):\n        mic = self._make_uint32(len(session_id))\n        mic += session_id\n        mic += struct.pack(\"B\", MSG_USERAUTH_REQUEST)\n        mic += self._make_uint32(len(username))\n        mic += username.encode()\n        mic += self._make_uint32(len(service))\n        mic += service.encode()\n        mic += self._make_uint32(len(auth_method))\n        mic += auth_method.encode()\n        return mic",
    "docstring": "Create the SSH2 MIC filed for gssapi-with-mic.\n\n        :param str session_id: The SSH session ID\n        :param str username: The name of the user who attempts to login\n        :param str service: The requested SSH service\n        :param str auth_method: The requested SSH authentication mechanism\n        :return: The MIC as defined in RFC 4462. The contents of the\n                 MIC field are:\n                 string    session_identifier,\n                 byte      SSH_MSG_USERAUTH_REQUEST,\n                 string    user-name,\n                 string    service (ssh-connection),\n                 string    authentication-method\n                           (gssapi-with-mic or gssapi-keyex)"
  },
  {
    "code": "def remove(obj, kind):\n    if not obj.get_badge(kind):\n        api.abort(404, 'Badge does not exists')\n    obj.remove_badge(kind)\n    return '', 204",
    "docstring": "Handle badge removal API\n\n    - Returns 404 if the badge for this kind is absent\n    - Returns 204 on success"
  },
  {
    "code": "def __getDataFromURL(url):\n        code = 0\n        while code != 200:\n            req = Request(url)\n            try:\n                response = urlopen(req)\n                code = response.code\n                sleep(0.01)\n            except HTTPError as error:\n                code = error.code\n                if code == 404:\n                    break\n            except URLError as error:\n                sleep(3)\n        if code == 404:\n            raise Exception(\"User was not found\")\n        return response.read().decode('utf-8')",
    "docstring": "Read HTML data from an user GitHub profile.\n\n        :param url: URL of the webpage to download.\n        :type url: str.\n        :return: webpage donwloaded.\n        :rtype: str."
  },
  {
    "code": "def new(cls, variable, **kwargs):\n        return cls.array2mask(numpy.full(variable.shape, True))",
    "docstring": "Return a new |DefaultMask| object associated with the\n        given |Variable| object."
  },
  {
    "code": "def search_product(self, limit=100, offset=0, with_price=0, with_supported_software=0,\n                       with_description=0):\n        response = self.request(E.searchProductSslCertRequest(\n            E.limit(limit),\n            E.offset(offset),\n            E.withPrice(int(with_price)),\n            E.withSupportedSoftware(int(with_supported_software)),\n            E.withDescription(int(with_description)),\n        ))\n        return response.as_models(SSLProduct)",
    "docstring": "Search the list of available products."
  },
  {
    "code": "def _api_scrape(json_inp, ndx):\n    try:\n        headers = json_inp['resultSets'][ndx]['headers']\n        values = json_inp['resultSets'][ndx]['rowSet']\n    except KeyError:\n        try:\n            headers = json_inp['resultSet'][ndx]['headers']\n            values = json_inp['resultSet'][ndx]['rowSet']\n        except KeyError:\n            headers = json_inp['resultSet']['headers']\n            values = json_inp['resultSet']['rowSet']\n    if HAS_PANDAS:\n        return DataFrame(values, columns=headers)\n    else:\n        return [dict(zip(headers, value)) for value in values]",
    "docstring": "Internal method to streamline the getting of data from the json\n\n    Args:\n        json_inp (json): json input from our caller\n        ndx (int): index where the data is located in the api\n\n    Returns:\n        If pandas is present:\n            DataFrame (pandas.DataFrame): data set from ndx within the\n            API's json\n        else:\n            A dictionary of both headers and values from the page"
  },
  {
    "code": "def from_string(self, repo, name, string):\n        try:\n            log.debug('Creating new item: %s' % name)\n            blob = Blob.from_string(string)\n            item = Item(parent=repo, sha=blob.sha, path=name)\n            item.blob = blob\n            return item\n        except AssertionError, e:\n            raise ItemError(e)",
    "docstring": "Create a new Item from a data stream.\n\n        :param repo: Repo object.\n        :param name: Name of item.\n        :param data: Data stream.\n\n        :return: New Item class instance."
  },
  {
    "code": "def sql(self, query):\n        limited_query = 'SELECT * FROM ({}) t0 LIMIT 0'.format(query)\n        schema = self._get_schema_using_query(limited_query)\n        return ops.SQLQueryResult(query, schema, self).to_expr()",
    "docstring": "Convert a SQL query to an Ibis table expression\n\n        Parameters\n        ----------\n\n        Returns\n        -------\n        table : TableExpr"
  },
  {
    "code": "def _audio_response_for_run(self, tensor_events, run, tag, sample):\n    response = []\n    index = 0\n    filtered_events = self._filter_by_sample(tensor_events, sample)\n    content_type = self._get_mime_type(run, tag)\n    for (index, tensor_event) in enumerate(filtered_events):\n      data = tensor_util.make_ndarray(tensor_event.tensor_proto)\n      label = data[sample, 1]\n      response.append({\n          'wall_time': tensor_event.wall_time,\n          'step': tensor_event.step,\n          'label': plugin_util.markdown_to_safe_html(label),\n          'contentType': content_type,\n          'query': self._query_for_individual_audio(run, tag, sample, index)\n      })\n    return response",
    "docstring": "Builds a JSON-serializable object with information about audio.\n\n    Args:\n      tensor_events: A list of image event_accumulator.TensorEvent objects.\n      run: The name of the run.\n      tag: The name of the tag the audio entries all belong to.\n      sample: The zero-indexed sample of the audio sample for which to\n      retrieve information. For instance, setting `sample` to `2` will\n        fetch information about only the third audio clip of each batch,\n        and steps with fewer than three audio clips will be omitted from\n        the results.\n\n    Returns:\n      A list of dictionaries containing the wall time, step, URL, width, and\n      height for each audio entry."
  },
  {
    "code": "def jd_to_struct_time(jd):\n    year, month, day = jdutil.jd_to_date(jd)\n    day_fraction = day - int(day)\n    hour, minute, second, ms = jdutil.days_to_hmsm(day_fraction)\n    day = int(day)\n    year, month, day, hour, minute, second = _roll_negative_time_fields(\n        year, month, day, hour, minute, second)\n    return struct_time(\n        [year, month, day, hour, minute, second] + TIME_EMPTY_EXTRAS\n    )",
    "docstring": "Return a `struct_time` converted from a Julian Date float number.\n\n    WARNING: Conversion to then from Julian Date value to `struct_time` can be\n    inaccurate and lose or gain time, especially for BC (negative) years.\n\n    NOTE: extra fields `tm_wday`, `tm_yday`, and `tm_isdst` are set to default\n    values, not real ones."
  },
  {
    "code": "def fix_symbol(self, symbol, reverse=False):\n        if not self.symbol_mapping:\n            return symbol\n        for old, new in self.symbol_mapping:\n            if reverse:\n                if symbol == new:\n                    return old\n            else:\n                if symbol == old:\n                    return new\n        return symbol",
    "docstring": "In comes a moneywagon format symbol, and returned in the symbol converted\n        to one the service can understand."
  },
  {
    "code": "def fpopen(*args, **kwargs):\n    uid = kwargs.pop('uid', -1)\n    gid = kwargs.pop('gid', -1)\n    mode = kwargs.pop('mode', None)\n    with fopen(*args, **kwargs) as f_handle:\n        path = args[0]\n        d_stat = os.stat(path)\n        if hasattr(os, 'chown'):\n            if (d_stat.st_uid != uid or d_stat.st_gid != gid) and \\\n                    [i for i in (uid, gid) if i != -1]:\n                os.chown(path, uid, gid)\n        if mode is not None:\n            mode_part = stat.S_IMODE(d_stat.st_mode)\n            if mode_part != mode:\n                os.chmod(path, (d_stat.st_mode ^ mode_part) | mode)\n        yield f_handle",
    "docstring": "Shortcut for fopen with extra uid, gid, and mode options.\n\n    Supported optional Keyword Arguments:\n\n    mode\n        Explicit mode to set. Mode is anything os.chmod would accept\n        as input for mode. Works only on unix/unix-like systems.\n\n    uid\n        The uid to set, if not set, or it is None or -1 no changes are\n        made. Same applies if the path is already owned by this uid.\n        Must be int. Works only on unix/unix-like systems.\n\n    gid\n        The gid to set, if not set, or it is None or -1 no changes are\n        made. Same applies if the path is already owned by this gid.\n        Must be int. Works only on unix/unix-like systems."
  },
  {
    "code": "def is_subdirectory(path_a, path_b):\n    path_a = os.path.realpath(path_a)\n    path_b = os.path.realpath(path_b)\n    relative = os.path.relpath(path_a, path_b)\n    return (not relative.startswith(os.pardir + os.sep))",
    "docstring": "Returns True if `path_a` is a subdirectory of `path_b`."
  },
  {
    "code": "def list_installed():\n    cmd = 'Get-WindowsFeature ' \\\n          '-ErrorAction SilentlyContinue ' \\\n          '-WarningAction SilentlyContinue ' \\\n          '| Select DisplayName,Name,Installed'\n    features = _pshell_json(cmd)\n    ret = {}\n    for entry in features:\n        if entry['Installed']:\n            ret[entry['Name']] = entry['DisplayName']\n    return ret",
    "docstring": "List installed features. Supported on Windows Server 2008 and Windows 8 and\n    newer.\n\n    Returns:\n        dict: A dictionary of installed features\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' win_servermanager.list_installed"
  },
  {
    "code": "def gather_registries() -> Tuple[Dict, Mapping, Mapping]:\n    id2devices = copy.copy(_id2devices)\n    registry = copy.copy(_registry)\n    selection = copy.copy(_selection)\n    dict_ = globals()\n    dict_['_id2devices'] = {}\n    dict_['_registry'] = {Node: {}, Element: {}}\n    dict_['_selection'] = {Node: {}, Element: {}}\n    return id2devices, registry, selection",
    "docstring": "Get and clear the current |Node| and |Element| registries.\n\n    Function |gather_registries| is thought to be used by class |Tester| only."
  },
  {
    "code": "def export_image_to_uri(self, image_id, uri, ibm_api_key=None):\n        if 'cos://' in uri:\n            return self.vgbdtg.copyToIcos({\n                'uri': uri,\n                'ibmApiKey': ibm_api_key\n            }, id=image_id)\n        else:\n            return self.vgbdtg.copyToExternalSource({'uri': uri}, id=image_id)",
    "docstring": "Export image into the given object storage\n\n        :param int image_id: The ID of the image\n        :param string uri: The URI for object storage of the format\n            swift://<objectStorageAccount>@<cluster>/<container>/<objectPath>\n            or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud\n            Object Storage\n        :param string ibm_api_key: Ibm Api Key needed to communicate with IBM\n            Cloud Object Storage"
  },
  {
    "code": "def libvlc_media_player_get_state(p_mi):\n    f = _Cfunctions.get('libvlc_media_player_get_state', None) or \\\n        _Cfunction('libvlc_media_player_get_state', ((1,),), None,\n                    State, MediaPlayer)\n    return f(p_mi)",
    "docstring": "Get current movie state.\n    @param p_mi: the Media Player.\n    @return: the current state of the media player (playing, paused, ...) See libvlc_state_t."
  },
  {
    "code": "async def _get_usage_data(self):\n        raw_res = await self._session.get(USAGE_URL)\n        content = await raw_res.text()\n        soup = BeautifulSoup(content, 'html.parser')\n        span_list = soup.find_all(\"span\", {\"class\": \"switchDisplay\"})\n        if span_list is None:\n            raise PyEboxError(\"Can not get usage page\")\n        usage_data = {}\n        for key, index in USAGE_MAP.items():\n            try:\n                str_value = span_list[index].attrs.get(\"data-m\").split()[0]\n                usage_data[key] = abs(float(str_value)) / 1024\n            except OSError:\n                raise PyEboxError(\"Can not get %s\", key)\n        return usage_data",
    "docstring": "Get data usage."
  },
  {
    "code": "def command(*args, **kwargs):\n    def decorator(f):\n        if 'description' not in kwargs:\n            kwargs['description'] = f.__doc__\n        if 'parents' in kwargs:\n            if not hasattr(f, '_argnames'):\n                f._argnames = []\n            for p in kwargs['parents']:\n                f._argnames += p._argnames if hasattr(p, '_argnames') else []\n            kwargs['parents'] = [p.parser for p in kwargs['parents']]\n        f.parser = argparse.ArgumentParser(*args, **kwargs)\n        f.climax = True\n        for arg in getattr(f, '_arguments', []):\n            f.parser.add_argument(*arg[0], **arg[1])\n        @wraps(f)\n        def wrapper(args=None):\n            kwargs = f.parser.parse_args(args)\n            return f(**vars(kwargs))\n        wrapper.func = f\n        return wrapper\n    return decorator",
    "docstring": "Decorator to define a command.\n\n    The arguments to this decorator are those of the\n    `ArgumentParser <https://docs.python.org/3/library/argparse.html\\\n#argumentparser-objects>`_\n    object constructor."
  },
  {
    "code": "def get_cache_key(bucket, name, args, kwargs):\n    u = ''.join(map(str, (bucket, name, args, kwargs)))\n    return 'native_tags.%s' % sha_constructor(u).hexdigest()",
    "docstring": "Gets a unique SHA1 cache key for any call to a native tag.\n    Use args and kwargs in hash so that the same arguments use the same key"
  },
  {
    "code": "def update_metadata(self, resource, keys_vals):\n        self.metadata_service.set_auth(self._token_metadata)\n        self.metadata_service.update(resource, keys_vals)",
    "docstring": "Updates key-value pairs with the given resource.\n\n        Will attempt to update all key-value pairs even if some fail.\n        Keys must already exist.\n\n        Args:\n            resource (intern.resource.boss.BossResource)\n            keys_vals (dictionary): Collection of key-value pairs to update on\n                the given resource.\n\n        Raises:\n            HTTPErrorList on failure."
  },
  {
    "code": "def _get_flaky_attributes(cls, test_item):\n        return {\n            attr: cls._get_flaky_attribute(\n                test_item,\n                attr,\n            ) for attr in FlakyNames()\n        }",
    "docstring": "Get all the flaky related attributes from the test.\n\n        :param test_item:\n            The test callable from which to get the flaky related attributes.\n        :type test_item:\n            `callable` or :class:`nose.case.Test` or :class:`Function`\n        :return:\n        :rtype:\n            `dict` of `unicode` to varies"
  },
  {
    "code": "def verify_day(self, now):\n        return self.day == \"*\" or str(now.day) in self.day.split(\" \")",
    "docstring": "Verify the day"
  },
  {
    "code": "def GetLastKey(self, voice=1):\n        voice_obj = self.GetChild(voice)\n        if voice_obj is not None:\n            key = BackwardSearch(KeyNode, voice_obj, 1)\n            if key is not None:\n                return key\n            else:\n                if hasattr(self, \"key\"):\n                    return self.key\n        else:\n            if hasattr(self, \"key\"):\n                return self.key",
    "docstring": "key as in musical key, not index"
  },
  {
    "code": "def get_items(self):\n        collection = JSONClientValidated('assessment',\n                                         collection='Item',\n                                         runtime=self._runtime)\n        result = collection.find(self._view_filter()).sort('_id', DESCENDING)\n        return objects.ItemList(result, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets all ``Items``.\n\n        In plenary mode, the returned list contains all known items or\n        an error results. Otherwise, the returned list may contain only\n        those items that are accessible through this session.\n\n        return: (osid.assessment.ItemList) - a list of ``Items``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def extract_bs(self, cutoff, ligcentroid, resis):\n        return [obres.GetIdx() for obres in resis if self.res_belongs_to_bs(obres, cutoff, ligcentroid)]",
    "docstring": "Return list of ids from residues belonging to the binding site"
  },
  {
    "code": "def configuration(ctx):\n    t = [[\"Key\", \"Value\"]]\n    for key in ctx.bitshares.config:\n        t.append([key, ctx.bitshares.config[key]])\n    print_table(t)",
    "docstring": "Show configuration variables"
  },
  {
    "code": "def local_docker(context: Context):\n    output = io.StringIO()\n    with contextlib.redirect_stdout(output):\n        context.shell('docker-machine', 'ip', 'default')\n    host_machine_ip = output.getvalue().strip() or socket.gethostbyname(socket.gethostname())\n    args = ()\n    if context.verbosity > 1:\n        args += ('--verbose',)\n    args += ('up', '--build', '--remove-orphans')\n    if not context.use_colour:\n        args += ('--no-color',)\n    context.shell('docker-compose', *args, environment={'HOST_MACHINE_IP': host_machine_ip})",
    "docstring": "Runs the app in a docker container; for local development only!\n    Once performed, `docker-compose up` can be used directly"
  },
  {
    "code": "def parse(self, *args):\n        if isinstance(self.dictionary, dict):\n            return self.dictionary\n        raise self.subparserException(\"Argument passed to Dictionary SubParser is not a dict: %s\" % type(self.dictionary))",
    "docstring": "Return our initialized dictionary arguments."
  },
  {
    "code": "def InputAA(seq_length, name=None, **kwargs):\n    return Input((seq_length, len(AMINO_ACIDS)), name=name, **kwargs)",
    "docstring": "Input placeholder for array returned by `encodeAA`\n\n    Wrapper for: `keras.layers.Input((seq_length, 22), name=name, **kwargs)`"
  },
  {
    "code": "def _reduction_output_shape(x, output_shape, reduced_dim):\n  if output_shape is None:\n    if reduced_dim is None:\n      return Shape([])\n    else:\n      if reduced_dim not in x.shape.dims:\n        raise ValueError(\n            \"reduced_dim=%s not in x.shape.dims=%s\" % (reduced_dim, x.shape))\n      return x.shape - reduced_dim\n  if reduced_dim is not None:\n    if [reduced_dim] != [d for d in x.shape.dims if d not in output_shape.dims]:\n      raise ValueError(\n          \"reduced_dim contradicts output_shape:\"\n          \"x=%s output_shape=%s reduced_dim=%s\" %\n          (x, output_shape, reduced_dim))\n  return output_shape",
    "docstring": "Helper function to reduce_sum, etc."
  },
  {
    "code": "def set_global_defaults(**kwargs):\n    valid_options = [\n        'active', 'selected', 'disabled', 'on', 'off',\n        'on_active', 'on_selected', 'on_disabled',\n        'off_active', 'off_selected', 'off_disabled',\n        'color', 'color_on', 'color_off',\n        'color_active', 'color_selected', 'color_disabled',\n        'color_on_selected', 'color_on_active', 'color_on_disabled',\n        'color_off_selected', 'color_off_active', 'color_off_disabled',\n        'animation', 'offset', 'scale_factor',\n        ]\n    for kw in kwargs:\n        if kw in valid_options:\n            _default_options[kw] = kwargs[kw]\n        else:\n            error = \"Invalid option '{0}'\".format(kw)\n            raise KeyError(error)",
    "docstring": "Set global defaults for the options passed to the icon painter."
  },
  {
    "code": "def _iterate_rules(rules, topology, max_iter):\n    atoms = list(topology.atoms())\n    for _ in range(max_iter):\n        max_iter -= 1\n        found_something = False\n        for rule in rules.values():\n            for match_index in rule.find_matches(topology):\n                atom = atoms[match_index]\n                if rule.name not in atom.whitelist:\n                    atom.whitelist.add(rule.name)\n                    atom.blacklist |= rule.overrides\n                    found_something = True\n        if not found_something:\n            break\n    else:\n        warn(\"Reached maximum iterations. Something probably went wrong.\")",
    "docstring": "Iteratively run all the rules until the white- and backlists converge.\n\n    Parameters\n    ----------\n    rules : dict\n        A dictionary mapping rule names (typically atomtype names) to\n        SMARTSGraphs that evaluate those rules.\n    topology : simtk.openmm.app.Topology\n        The topology that we are trying to atomtype.\n    max_iter : int\n        The maximum number of iterations."
  },
  {
    "code": "def coerce(self, value):\n        if not self.is_valid(value):\n            raise ex.SerializeException('{} is not a valid value for '\n                                        'type {}'.format(value, self.__class__.__name__))\n        return value",
    "docstring": "Subclasses should override this method for type coercion.\n\n        Default version will simply return the argument. If the argument\n        is not valid, a SerializeException is raised.\n\n        For primitives like booleans, ints, floats, and strings, use\n        this default version to avoid unintended type conversions."
  },
  {
    "code": "def upload_from_stream_with_id(self, file_id, filename, source,\n                                   chunk_size_bytes=None, metadata=None):\n        with self.open_upload_stream_with_id(\n                file_id, filename, chunk_size_bytes, metadata) as gin:\n            gin.write(source)",
    "docstring": "Uploads a user file to a GridFS bucket with a custom file id.\n\n        Reads the contents of the user file from `source` and uploads\n        it to the file `filename`. Source can be a string or file-like object.\n        For example::\n\n          my_db = MongoClient().test\n          fs = GridFSBucket(my_db)\n          file_id = fs.upload_from_stream(\n              ObjectId(),\n              \"test_file\",\n              \"data I want to store!\",\n              chunk_size_bytes=4,\n              metadata={\"contentType\": \"text/plain\"})\n\n        Raises :exc:`~gridfs.errors.NoFile` if no such version of\n        that file exists.\n        Raises :exc:`~ValueError` if `filename` is not a string.\n\n        :Parameters:\n          - `file_id`: The id to use for this file. The id must not have\n            already been used for another file.\n          - `filename`: The name of the file to upload.\n          - `source`: The source stream of the content to be uploaded. Must be\n            a file-like object that implements :meth:`read` or a string.\n          - `chunk_size_bytes` (options): The number of bytes per chunk of this\n            file. Defaults to the chunk_size_bytes of :class:`GridFSBucket`.\n          - `metadata` (optional): User data for the 'metadata' field of the\n            files collection document. If not provided the metadata field will\n            be omitted from the files collection document."
  },
  {
    "code": "def start_parallel(self):\n        self.num_processes = get_num_processes()\n        self.task_queue = multiprocessing.Queue(maxsize=Q_MAX_SIZE)\n        self.result_queue = multiprocessing.Queue()\n        self.log_queue = multiprocessing.Queue()\n        self.complete = multiprocessing.Event()\n        args = (self.compute, self.task_queue, self.result_queue,\n                self.log_queue, self.complete) + self.context\n        self.processes = [\n            multiprocessing.Process(target=self.worker, args=args, daemon=True)\n            for i in range(self.num_processes)]\n        for process in self.processes:\n            process.start()\n        self.log_thread = LogThread(self.log_queue)\n        self.log_thread.start()\n        self.initialize_tasks()",
    "docstring": "Initialize all queues and start the worker processes and the log\n        thread."
  },
  {
    "code": "def service_timeouts(cls):\n        timer_manager = cls._timers\n        while True:\n            next_end = timer_manager.service_timeouts()\n            sleep_time = max(next_end - time.time(), 0) if next_end else 10000\n            cls._new_timer.wait(sleep_time)\n            cls._new_timer.clear()",
    "docstring": "cls._timeout_watcher runs in this loop forever.\n        It is usually waiting for the next timeout on the cls._new_timer Event.\n        When new timers are added, that event is set so that the watcher can\n        wake up and possibly set an earlier timeout."
  },
  {
    "code": "def hasPESignature(self, rd):\n        rd.setOffset(0)\n        e_lfanew_offset = unpack(\"<L\",  rd.readAt(0x3c, 4))[0]\n        sign = rd.readAt(e_lfanew_offset, 2)\n        if sign == \"PE\":\n            return True\n        return False",
    "docstring": "Check for PE signature.\n\n        @type rd: L{ReadData}\n        @param rd: A L{ReadData} object.\n\n        @rtype: bool\n        @return: True is the given L{ReadData} stream has the PE signature. Otherwise, False."
  },
  {
    "code": "def interpret_expenditure_entry(entry):\n    try:\n        expenditure_amount = float(entry['ExpenditureAmount'])\n        entry['AmountsInterpreted'] = True\n        entry['ExpenditureAmount'] = expenditure_amount\n    except ValueError:\n        entry['AmountsInterpreted'] = False\n    try:\n        expenditure_date = parse_iso_str(entry['ExpenditureDate'])\n        filed_date = parse_iso_str(entry['FiledDate'])\n        entry['DatesInterpreted'] = True\n        entry['ExpenditureDate'] = expenditure_date\n        entry['FiledDate'] = filed_date\n    except ValueError:\n        entry['DatesInterpreted'] = False\n    try:\n        amended = parse_yes_no_str(entry['Amended'])\n        amendment = parse_yes_no_str(entry['Amendment'])\n        entry['BooleanFieldsInterpreted'] = True\n        entry['Amended'] = amended\n        entry['Amendment'] = amendment\n    except ValueError:\n        entry['BooleanFieldsInterpreted'] = False\n    return entry",
    "docstring": "Interpret data fields within a CO-TRACER expediture report.\n\n    Interpret the expenditure amount, expenditure date, filed date, amended,\n    and amendment fields of the provided entry. All dates (expenditure and\n    filed) are interpreted together and, if any fails, all will retain their\n    original value. Likewise, amended and amendment are interpreted together and\n    if one is malformed, both will retain their original value. Entry may be\n    edited in place and side-effects are possible in coupled code. However,\n    client code should use the return value to guard against future changes.\n\n    A value with the key 'AmountsInterpreted' will be set to True or False in\n    the returned entry if floating point values are successfully interpreted\n    (ExpenditureAmount) or not respectively.\n\n    A value with the key 'DatesInterpreted' will be set to True or False in\n    the returned entry if ISO 8601 strings are successfully interpreted\n    (ExpenditureDate and FiledDate) or not respectively.\n\n    A value with the key 'BooleanFieldsInterpreted' will be set to True or\n    False in the returned entry if boolean strings are successfully interpreted\n    (Amended and Amendment) or not respectively.\n\n    @param entry: The expenditure report data to manipulate / interpret.\n    @type entry: dict\n    @return: The entry passed \n    @raise ValueError: Raised if any expected field cannot be found in entry."
  },
  {
    "code": "def kill(self):\n        BaseShellOperator._close_process_input_stdin(self._batcmd.batch_to_file_s)\n        BaseShellOperator._wait_process(self._process, self._batcmd.sh_cmd, self._success_exitcodes)\n        BaseShellOperator._rm_process_input_tmpfiles(self._batcmd.batch_to_file_s)\n        self._process = None",
    "docstring": "Kill instantiated process\n\n        :raises: `AttributeError` if instantiated process doesn't seem to satisfy `constraints <relshell.daemon_shelloperator.DaemonShellOperator>`_"
  },
  {
    "code": "def multiply(x1, x2, output_shape=None, name=None):\n  if not isinstance(x2, Tensor):\n    return ScalarMultiplyOperation(x1, x2).outputs[0]\n  with tf.name_scope(name, default_name=\"mul\"):\n    x1, x2 = binary_arguments_to_tensors(x1, x2)\n    return einsum(\n        [x1, x2],\n        output_shape=_infer_binary_broadcast_shape(\n            x1.shape, x2.shape, output_shape))",
    "docstring": "Binary multiplication with broadcasting.\n\n  Args:\n    x1: a Tensor\n    x2: a Tensor\n    output_shape: an optional Shape\n    name: an optional string\n  Returns:\n    a Tensor"
  },
  {
    "code": "def dmrs(self):\n        dmrs = self.get('dmrs')\n        if dmrs is not None:\n            if isinstance(dmrs, dict):\n                dmrs = Dmrs.from_dict(dmrs)\n        return dmrs",
    "docstring": "Deserialize and return a Dmrs object for JSON-formatted DMRS\n        data; otherwise return the original string."
  },
  {
    "code": "def percentileOfSeries(requestContext, seriesList, n, interpolate=False):\n    if n <= 0:\n        raise ValueError(\n            'The requested percent is required to be greater than 0')\n    if not seriesList:\n        return []\n    name = 'percentileOfSeries(%s,%g)' % (seriesList[0].pathExpression, n)\n    start, end, step = normalize([seriesList])[1:]\n    values = [_getPercentile(row, n, interpolate)\n              for row in zip_longest(*seriesList)]\n    resultSeries = TimeSeries(name, start, end, step, values)\n    resultSeries.pathExpression = name\n    return [resultSeries]",
    "docstring": "percentileOfSeries returns a single series which is composed of the\n    n-percentile values taken across a wildcard series at each point.\n    Unless `interpolate` is set to True, percentile values are actual values\n    contained in one of the supplied series."
  },
  {
    "code": "def _set_time(self, time):\n        if len(self.time) == 0 :\n            self.time = np.array(time)\n            if self.h5 is not None:\n                self.h5.create_dataset('time', self.time.shape, dtype=self.time.dtype, data=self.time, compression=\"gzip\", shuffle=True, scaleoffset=3)\n        else:\n            if(len(time) != len(self.time)):\n                raise AssertionError(\"\\nTime or number of frame mismatch in input files.\\n Exiting...\\n\")",
    "docstring": "Set time in both class and hdf5 file"
  },
  {
    "code": "def should_check_ciphersuites(self):\n        if isinstance(self.mykey, PrivKeyRSA):\n            kx = \"RSA\"\n        elif isinstance(self.mykey, PrivKeyECDSA):\n            kx = \"ECDSA\"\n        if get_usable_ciphersuites(self.cur_pkt.ciphers, kx):\n            return\n        raise self.NO_USABLE_CIPHERSUITE()",
    "docstring": "We extract cipher suites candidates from the client's proposition."
  },
  {
    "code": "def service_unavailable(cls, errors=None):\n        if cls.expose_status:\n            cls.response.content_type = 'application/json'\n            cls.response._status_line = '503 Service Unavailable'\n        return cls(503, None, errors).to_json",
    "docstring": "Shortcut API for HTTP 503 `Service Unavailable` response.\n\n        Args:\n            errors (list): Response key/value data.\n\n        Returns:\n            WSResponse Instance."
  },
  {
    "code": "def create_event(\n    title,\n    event_type,\n    description='',\n    start_time=None,\n    end_time=None,\n    note=None,\n    **rrule_params\n):\n    if isinstance(event_type, tuple):\n        event_type, created = EventType.objects.get_or_create(\n            abbr=event_type[0],\n            label=event_type[1]\n        )\n    event = Event.objects.create(\n        title=title,\n        description=description,\n        event_type=event_type\n    )\n    if note is not None:\n        event.notes.create(note=note)\n    start_time = start_time or datetime.now().replace(\n        minute=0,\n        second=0,\n        microsecond=0\n    )\n    end_time = end_time or (start_time + swingtime_settings.DEFAULT_OCCURRENCE_DURATION)\n    event.add_occurrences(start_time, end_time, **rrule_params)\n    return event",
    "docstring": "Convenience function to create an ``Event``, optionally create an\n    ``EventType``, and associated ``Occurrence``s. ``Occurrence`` creation\n    rules match those for ``Event.add_occurrences``.\n\n    Returns the newly created ``Event`` instance.\n\n    Parameters\n\n    ``event_type``\n        can be either an ``EventType`` object or 2-tuple of ``(abbreviation,label)``,\n        from which an ``EventType`` is either created or retrieved.\n\n    ``start_time``\n        will default to the current hour if ``None``\n\n    ``end_time``\n        will default to ``start_time`` plus swingtime_settings.DEFAULT_OCCURRENCE_DURATION\n        hour if ``None``\n\n    ``freq``, ``count``, ``rrule_params``\n        follow the ``dateutils`` API (see http://labix.org/python-dateutil)"
  },
  {
    "code": "def read(self, amt=None):\n        chunk = self._raw_stream.read(amt)\n        self._amount_read += len(chunk)\n        return chunk",
    "docstring": "Read at most amt bytes from the stream.\n        If the amt argument is omitted, read all data."
  },
  {
    "code": "def generate_trajs(P, M, N, start=None, stop=None, dt=1):\n    sampler = MarkovChainSampler(P, dt=dt)\n    return sampler.trajectories(M, N, start=start, stop=stop)",
    "docstring": "Generates multiple realizations of the Markov chain with transition matrix P.\n\n    Parameters\n    ----------\n    P : (n, n) ndarray\n        transition matrix\n    M : int\n        number of trajectories\n    N : int\n        trajectory length\n    start : int, optional, default = None\n        starting state. If not given, will sample from the stationary distribution of P\n    stop : int or int-array-like, optional, default = None\n        stopping set. If given, the trajectory will be stopped before N steps\n        once a state of the stop set is reached\n    dt : int\n        trajectory will be saved every dt time steps.\n        Internally, the dt'th power of P is taken to ensure a more efficient simulation.\n\n    Returns\n    -------\n    traj_sliced : (N/dt, ) ndarray\n        A discrete trajectory with length N/dt"
  },
  {
    "code": "def set(self, x, y, value):\n        self._double_buffer[y][x] = value",
    "docstring": "Set the cell value from the specified location\n\n        :param x: The column (x coord) of the character.\n        :param y: The row (y coord) of the character.\n        :param value: A 5-tuple of (unicode, foreground, attributes, background, width)."
  },
  {
    "code": "def is_archive(self):\n        ns_prefix = self.archive_namespace\n        if ns_prefix:\n            if ns_prefix + '_archive' in self.feed.feed:\n                return True\n            if ns_prefix + '_current' in self.feed.feed:\n                return False\n        rels = collections.defaultdict(list)\n        for link in self.feed.feed.links:\n            rels[link.rel].append(link.href)\n        return ('current' in rels and\n                ('self' not in rels or\n                 rels['self'] != rels['current']))",
    "docstring": "Given a parsed feed, returns True if this is an archive feed"
  },
  {
    "code": "def contains(self, item):\n        check_not_none(item, \"Value can't be None\")\n        item_data = self._to_data(item)\n        return self._encode_invoke(set_contains_codec, value=item_data)",
    "docstring": "Determines whether this set contains the specified item or not.\n\n        :param item: (object), the specified item to be searched.\n        :return: (bool), ``true`` if the specified item exists in this set, ``false`` otherwise."
  },
  {
    "code": "def status(self, jobId=None, jobType=None):\n        params = {\n            \"f\" : \"json\"\n        }\n        if jobType is not None:\n            params['jobType'] = jobType\n        if jobId is not None:\n            params[\"jobId\"] = jobId\n        url = \"%s/status\" % self.root\n        return self._get(url=url,\n                            param_dict=params,\n                            securityHandler=self._securityHandler,\n                            proxy_port=self._proxy_port,\n                            proxy_url=self._proxy_url)",
    "docstring": "Inquire about status when publishing an item, adding an item in\n           async mode, or adding with a multipart upload. \"Partial\" is\n           available for Add Item Multipart, when only a part is uploaded\n           and the item is not committed.\n\n           Input:\n              jobType The type of asynchronous job for which the status has\n                      to be checked. Default is none, which check the\n                      item's status.  This parameter is optional unless\n                      used with the operations listed below.\n                      Values: publish, generateFeatures, export,\n                              and createService\n              jobId - The job ID returned during publish, generateFeatures,\n                      export, and createService calls."
  },
  {
    "code": "def unblock_all(self):\n        self.unblock()\n        for em in self._emitters.values():\n            em.unblock()",
    "docstring": "Unblock all emitters in this group."
  },
  {
    "code": "def is_imap(self, JPD):\n        if not isinstance(JPD, JointProbabilityDistribution):\n            raise TypeError(\"JPD must be an instance of JointProbabilityDistribution\")\n        factors = [cpd.to_factor() for cpd in self.get_cpds()]\n        factor_prod = reduce(mul, factors)\n        JPD_fact = DiscreteFactor(JPD.variables, JPD.cardinality, JPD.values)\n        if JPD_fact == factor_prod:\n            return True\n        else:\n            return False",
    "docstring": "Checks whether the bayesian model is Imap of given JointProbabilityDistribution\n\n        Parameters\n        -----------\n        JPD : An instance of JointProbabilityDistribution Class, for which you want to\n            check the Imap\n\n        Returns\n        --------\n        boolean : True if bayesian model is Imap for given Joint Probability Distribution\n                False otherwise\n        Examples\n        --------\n        >>> from pgmpy.models import BayesianModel\n        >>> from pgmpy.factors.discrete import TabularCPD\n        >>> from pgmpy.factors.discrete import JointProbabilityDistribution\n        >>> G = BayesianModel([('diff', 'grade'), ('intel', 'grade')])\n        >>> diff_cpd = TabularCPD('diff', 2, [[0.2], [0.8]])\n        >>> intel_cpd = TabularCPD('intel', 3, [[0.5], [0.3], [0.2]])\n        >>> grade_cpd = TabularCPD('grade', 3,\n        ...                        [[0.1,0.1,0.1,0.1,0.1,0.1],\n        ...                         [0.1,0.1,0.1,0.1,0.1,0.1],\n        ...                         [0.8,0.8,0.8,0.8,0.8,0.8]],\n        ...                        evidence=['diff', 'intel'],\n        ...                        evidence_card=[2, 3])\n        >>> G.add_cpds(diff_cpd, intel_cpd, grade_cpd)\n        >>> val = [0.01, 0.01, 0.08, 0.006, 0.006, 0.048, 0.004, 0.004, 0.032,\n                   0.04, 0.04, 0.32, 0.024, 0.024, 0.192, 0.016, 0.016, 0.128]\n        >>> JPD = JointProbabilityDistribution(['diff', 'intel', 'grade'], [2, 3, 3], val)\n        >>> G.is_imap(JPD)\n        True"
  },
  {
    "code": "def load_template(name, directory, extension, encoding, encoding_errors):\n    abs_path = get_abs_template_path(name, directory, extension)\n    return load_file(abs_path, encoding, encoding_errors)",
    "docstring": "Load a template and return its contents as a unicode string."
  },
  {
    "code": "def _set_seed(self):\n        if self.flags['SEED'] is not None:\n            tf.set_random_seed(self.flags['SEED'])\n            np.random.seed(self.flags['SEED'])",
    "docstring": "Set random seed for numpy and tensorflow packages"
  },
  {
    "code": "def restore(self, request):\n        self._connection.connection.rpush(self._request_key, pickle.dumps(request))",
    "docstring": "Push the request back onto the queue.\n\n        Args:\n            request (Request): Reference to a request object that should be pushed back\n                               onto the request queue."
  },
  {
    "code": "def emit_save_figure(self):\n        self.sig_save_figure.emit(self.canvas.fig, self.canvas.fmt)",
    "docstring": "Emit a signal when the toolbutton to save the figure is clicked."
  },
  {
    "code": "def dinfdistdown(np, ang, fel, slp, src, statsm, distm, edgecontamination, wg, dist,\n                     workingdir=None, mpiexedir=None, exedir=None,\n                     log_file=None, runtime_file=None, hostfile=None):\n        in_params = {'-m': '%s %s' % (TauDEM.convertstatsmethod(statsm),\n                                      TauDEM.convertdistmethod(distm))}\n        if StringClass.string_match(edgecontamination, 'false') or edgecontamination is False:\n            in_params['-nc'] = None\n        fname = TauDEM.func_name('dinfdistdown')\n        return TauDEM.run(FileClass.get_executable_fullpath(fname, exedir),\n                          {'-fel': fel, '-slp': slp, '-ang': ang, '-src': src, '-wg': wg},\n                          workingdir,\n                          in_params,\n                          {'-dd': dist},\n                          {'mpipath': mpiexedir, 'hostfile': hostfile, 'n': np},\n                          {'logfile': log_file, 'runtimefile': runtime_file})",
    "docstring": "Run D-inf distance down to stream"
  },
  {
    "code": "def _generate_placeholder(readable_text=None):\n        name = '_interm_' + str(Cache._counter)\n        Cache._counter += 1\n        if readable_text is not None:\n            assert isinstance(readable_text, str)\n            name += '_' + readable_text\n        return name",
    "docstring": "Generate a placeholder name to use while updating WeldObject.\n\n        Parameters\n        ----------\n        readable_text : str, optional\n            Appended to the name for a more understandable placeholder.\n\n        Returns\n        -------\n        str\n            Placeholder."
  },
  {
    "code": "def uuid_to_slug(uuid):\n    if not isinstance(uuid, int):\n        raise ArgumentError(\"Invalid id that is not an integer\", id=uuid)\n    if uuid < 0 or uuid > 0x7fffffff:\n        raise ArgumentError(\"Integer should be a positive number and smaller than 0x7fffffff\", id=uuid)\n    return '--'.join(['d', int64gid(uuid)])",
    "docstring": "Return IOTile Cloud compatible Device Slug\n\n    :param uuid: UUID\n    :return: string in the form of d--0000-0000-0000-0001"
  },
  {
    "code": "def exception_to_github(github_obj_to_comment, summary=\"\"):\n    context = ExceptionContext()\n    try:\n        yield context\n    except Exception:\n        if summary:\n            summary = \": ({})\".format(summary)\n        error_type = \"an unknown error\"\n        try:\n            raise\n        except CalledProcessError as err:\n            error_type = \"a Subprocess error\"\n            content = \"Command: {}\\n\".format(err.cmd)\n            content += \"Finished with return code {}\\n\".format(err.returncode)\n            if err.output:\n                content += \"and output:\\n```shell\\n{}\\n```\".format(err.output)\n            else:\n                content += \"and no output\"\n        except Exception:\n            content = \"```python\\n{}\\n```\".format(traceback.format_exc())\n        response = \"<details><summary>Encountered {}{}</summary><p>\\n\\n\".format(\n            error_type,\n            summary\n        )\n        response += content\n        response += \"\\n\\n</p></details>\"\n        context.comment = create_comment(github_obj_to_comment, response)",
    "docstring": "If any exception comes, log them in the given Github obj."
  },
  {
    "code": "def submit_action(self, ddata):\n        self._controller.post(ddata,\n                              url=HOME_ENDPOINT,\n                              referer=HOME_ENDPOINT)",
    "docstring": "Post data."
  },
  {
    "code": "def _write_buildproc_yaml(build_data, env, user, cmd, volumes, app_folder):\n    buildproc = ProcData({\n        'app_folder': str(app_folder),\n        'app_name': build_data.app_name,\n        'app_repo_url': '',\n        'app_repo_type': '',\n        'buildpack_url': '',\n        'buildpack_version': '',\n        'config_name': 'build',\n        'env': env,\n        'host': '',\n        'port': 0,\n        'version': build_data.version,\n        'release_hash': '',\n        'settings': {},\n        'user': user,\n        'cmd': cmd,\n        'volumes': volumes,\n        'proc_name': 'build',\n        'image_name': build_data.image_name,\n        'image_url': build_data.image_url,\n        'image_md5': build_data.image_md5,\n    })\n    with open('buildproc.yaml', 'w') as f:\n        f.write(buildproc.as_yaml())\n    return get_container_path(buildproc)",
    "docstring": "Write a proc.yaml for the container and return the container path"
  },
  {
    "code": "def getDefaultTMParams(self, inputSize, numInputBits):\n    sampleSize = int(1.5 * numInputBits)\n    if numInputBits == 20:\n      activationThreshold = 18\n      minThreshold = 18\n    elif numInputBits == 10:\n      activationThreshold = 8\n      minThreshold = 8\n    else:\n      activationThreshold = int(numInputBits * .6)\n      minThreshold = activationThreshold\n    return {\n      \"columnCount\": inputSize,\n      \"cellsPerColumn\": 16,\n      \"learn\": True,\n      \"learnOnOneCell\": False,\n      \"initialPermanence\": 0.41,\n      \"connectedPermanence\": 0.6,\n      \"permanenceIncrement\": 0.1,\n      \"permanenceDecrement\": 0.03,\n      \"minThreshold\": minThreshold,\n      \"basalPredictedSegmentDecrement\": 0.003,\n      \"apicalPredictedSegmentDecrement\": 0.0,\n      \"reducedBasalThreshold\": int(activationThreshold*0.6),\n      \"activationThreshold\": activationThreshold,\n      \"sampleSize\": sampleSize,\n      \"implementation\": \"ApicalTiebreak\",\n      \"seed\": self.seed\n    }",
    "docstring": "Returns a good default set of parameters to use in the TM region."
  },
  {
    "code": "def Analyze(self, hashes):\n    if not self._api_key:\n      raise RuntimeError('No API key specified for VirusTotal lookup.')\n    hash_analyses = []\n    json_response = self._QueryHashes(hashes) or []\n    if isinstance(json_response, dict):\n      json_response = [json_response]\n    for result in json_response:\n      resource = result['resource']\n      hash_analysis = interface.HashAnalysis(resource, result)\n      hash_analyses.append(hash_analysis)\n    return hash_analyses",
    "docstring": "Looks up hashes in VirusTotal using the VirusTotal HTTP API.\n\n    The API is documented here:\n      https://www.virustotal.com/en/documentation/public-api/\n\n    Args:\n      hashes (list[str]): hashes to look up.\n\n    Returns:\n      list[HashAnalysis]: analysis results.\n\n    Raises:\n      RuntimeError: If the VirusTotal API key has not been set."
  },
  {
    "code": "def header_check(self, content):\n        encode = None\n        m = RE_HTML_ENCODE.search(content)\n        if m:\n            enc = m.group(1).decode('ascii')\n            try:\n                codecs.getencoder(enc)\n                encode = enc\n            except LookupError:\n                pass\n        else:\n            encode = self._has_xml_encode(content)\n        return encode",
    "docstring": "Special HTML encoding check."
  },
  {
    "code": "def serialize(self):\n        pickle = super(ResourceParameter, self).serialize()\n        pickle['frequency'] = self.frequency\n        pickle['unit'] = self._unit.serialize()\n        return pickle",
    "docstring": "Convert the parameter into a dictionary.\n\n        :return: The parameter dictionary.\n        :rtype: dict"
  },
  {
    "code": "def migrate(db, name, package, conf={}):\n    (current_major_version, current_minor_version) = get_version(db, name)\n    package = importlib.import_module(package)\n    logging.debug('Migration version for %s is %s.%s',\n                  package.__name__,\n                  current_major_version,\n                  current_minor_version)\n    mods = get_mods(package)\n    migrations = get_new(mods,\n                         current_major_version,\n                         current_minor_version + 1)\n    for (modname, major_version, minor_version) in migrations:\n        mod = load_mod(modname, package)\n        run_migration(name, major_version, minor_version, db, mod, conf)\n        logging.debug(\"Finished migrating to %s\", modname)",
    "docstring": "Run all migrations that have not been run\n\n    Migrations will be run inside a transaction.\n\n    :param db:              database connection object\n    :param name:            name associated with the migrations\n    :param package:         package that contains the migrations\n    :param conf:            application configuration object"
  },
  {
    "code": "def where_session_id(cls, session_id):\r\n        try:\r\n            session = cls.query.filter_by(session_id=session_id).one()\r\n            return session\r\n        except (NoResultFound, MultipleResultsFound):\r\n            return None",
    "docstring": "Easy way to query by session id"
  },
  {
    "code": "def get_by_symbol(self, symbol: str) -> Commodity:\n        full_symbol = self.__parse_gc_symbol(symbol)\n        query = (\n            self.query\n            .filter(Commodity.mnemonic == full_symbol[\"mnemonic\"])\n        )\n        if full_symbol[\"namespace\"]:\n            query = query.filter(Commodity.namespace == full_symbol[\"namespace\"])\n        return query.first()",
    "docstring": "Returns the commodity with the given symbol.\n        If more are found, an exception will be thrown."
  },
  {
    "code": "def _update_names(self):\n        d = dict(\n            table=self.table_name,\n            time=self.time,\n            space=self.space,\n            grain=self.grain,\n            variant=self.variant,\n            segment=self.segment\n        )\n        assert self.dataset\n        name = PartialPartitionName(**d).promote(self.dataset.identity.name)\n        self.name = str(name.name)\n        self.vname = str(name.vname)\n        self.cache_key = name.cache_key\n        self.fqname = str(self.identity.fqname)",
    "docstring": "Update the derived names"
  },
  {
    "code": "def revoke_access_token(self, access_token):\n        payload = {'access_token': access_token,}\n        req = requests.post(settings.API_DEAUTHORIZATION_URL, data=payload)",
    "docstring": "Revokes the Access Token by accessing the De-authorization Endpoint\n        of Health Graph API.\n        \n        @param access_token: Access Token for querying Health Graph API."
  },
  {
    "code": "def update(self, other):\n        if type(self) != type(other):\n            return NotImplemented\n        else:\n            if other.bad:\n                self.error = other.error\n                self.bad = True\n            self._fieldDict.update(other._fieldDict)",
    "docstring": "Adds all the tag-entry pairs from _other_ to the `Grant`. If there is a conflict _other_ takes precedence.\n\n        # Parameters\n\n        _other_ : `Grant`\n\n        > Another `Grant` of the same type as _self_"
  },
  {
    "code": "def GetEmail(prompt):\n\tlast_email_file_name = os.path.expanduser(\"~/.last_codereview_email_address\")\n\tlast_email = \"\"\n\tif os.path.exists(last_email_file_name):\n\t\ttry:\n\t\t\tlast_email_file = open(last_email_file_name, \"r\")\n\t\t\tlast_email = last_email_file.readline().strip(\"\\n\")\n\t\t\tlast_email_file.close()\n\t\t\tprompt += \" [%s]\" % last_email\n\t\texcept IOError, e:\n\t\t\tpass\n\temail = raw_input(prompt + \": \").strip()\n\tif email:\n\t\ttry:\n\t\t\tlast_email_file = open(last_email_file_name, \"w\")\n\t\t\tlast_email_file.write(email)\n\t\t\tlast_email_file.close()\n\t\texcept IOError, e:\n\t\t\tpass\n\telse:\n\t\temail = last_email\n\treturn email",
    "docstring": "Prompts the user for their email address and returns it.\n\n\tThe last used email address is saved to a file and offered up as a suggestion\n\tto the user. If the user presses enter without typing in anything the last\n\tused email address is used. If the user enters a new address, it is saved\n\tfor next time we prompt."
  },
  {
    "code": "def bgwrite(fileObj, data, closeWhenFinished=False, chainAfter=None, ioPrio=4):\n    thread = BackgroundWriteProcess(fileObj, data, closeWhenFinished, chainAfter, ioPrio)\n    thread.start()\n    return thread",
    "docstring": "bgwrite - Start a background writing process\n\n            @param fileObj <stream> - A stream backed by an fd\n\n            @param data    <str/bytes/list> - The data to write. If a list is given, each successive element will be written to the fileObj and flushed. If a string/bytes is provided, it will be chunked according to the #BackgroundIOPriority chosen. If you would like a different chunking than the chosen ioPrio provides, use #bgwrite_chunk function instead.\n\n               Chunking makes the data available quicker on the other side, reduces iowait on this side, and thus increases interactivity (at penalty of throughput).\n\n            @param closeWhenFinished <bool> - If True, the given fileObj will be closed after all the data has been written. Default False.\n\n            @param chainAfter  <None/BackgroundWriteProcess> - If a BackgroundWriteProcess object is provided (the return of bgwrite* functions), this data will be held for writing until the data associated with the provided object has completed writing.\n            Use this to queue several background writes, but retain order within the resulting stream.\n\n\n            @return - BackgroundWriteProcess - An object representing the state of this operation. @see BackgroundWriteProcess"
  },
  {
    "code": "def _list_files_in_path(path, pattern=\"*.stan\"):\n    results = []\n    for dirname, subdirs, files in os.walk(path):\n        for name in files:\n            if fnmatch(name, pattern):\n                results.append(os.path.join(dirname, name))\n    return(results)",
    "docstring": "indexes a directory of stan files\n    returns as dictionary containing contents of files"
  },
  {
    "code": "def _wrap_result(name, data, sparse_index, fill_value, dtype=None):\n    if name.startswith('__'):\n        name = name[2:-2]\n    if name in ('eq', 'ne', 'lt', 'gt', 'le', 'ge'):\n        dtype = np.bool\n    fill_value = lib.item_from_zerodim(fill_value)\n    if is_bool_dtype(dtype):\n        fill_value = bool(fill_value)\n    return SparseArray(data,\n                       sparse_index=sparse_index,\n                       fill_value=fill_value,\n                       dtype=dtype)",
    "docstring": "wrap op result to have correct dtype"
  },
  {
    "code": "def path_exists(self, path, follow_symlinks=True):\n        \"test if path exists\"\n        return (\n            self.file_exists(path, follow_symlinks)\n            or self.symlink_exists(path, follow_symlinks)\n            or self.directory_exists(path, follow_symlinks)\n        )",
    "docstring": "test if path exists"
  },
  {
    "code": "def get_books_for_schedule(self, schedule):\n        slns = self._get_slns(schedule)\n        books = {}\n        for sln in slns:\n            try:\n                section_books = self.get_books_by_quarter_sln(\n                    schedule.term.quarter, sln\n                )\n                books[sln] = section_books\n            except DataFailureException:\n                pass\n        return books",
    "docstring": "Returns a dictionary of data.  SLNs are the keys, an array of Book\n        objects are the values."
  },
  {
    "code": "def detect_builtin_shadowing_definitions(self, contract):\n        result = []\n        for function in contract.functions:\n            if function.contract == contract:\n                if self.is_builtin_symbol(function.name):\n                    result.append((self.SHADOWING_FUNCTION, function, None))\n                result += self.detect_builtin_shadowing_locals(function)\n        for modifier in contract.modifiers:\n            if modifier.contract == contract:\n                if self.is_builtin_symbol(modifier.name):\n                    result.append((self.SHADOWING_MODIFIER, modifier, None))\n                result += self.detect_builtin_shadowing_locals(modifier)\n        for variable in contract.variables:\n            if variable.contract == contract:\n                if self.is_builtin_symbol(variable.name):\n                    result.append((self.SHADOWING_STATE_VARIABLE, variable, None))\n        for event in contract.events:\n            if event.contract == contract:\n                if self.is_builtin_symbol(event.name):\n                    result.append((self.SHADOWING_EVENT, event, None))\n        return result",
    "docstring": "Detects if functions, access modifiers, events, state variables, or local variables are named after built-in\n            symbols. Any such definitions are returned in a list.\n\n        Returns:\n            list of tuple: (type, definition, [local variable parent])"
  },
  {
    "code": "def reset(self):\n        self.rawdata = ''\n        self.lasttag = '???'\n        self.interesting = interesting_normal\n        self.cdata_elem = None\n        _markupbase.ParserBase.reset(self)",
    "docstring": "Reset this instance.  Loses all unprocessed data."
  },
  {
    "code": "def parse(self, output):\n        output = self._get_lines_with_stems(output)\n        words = self._make_unique(output)\n        return self._parse_for_simple_stems(words)",
    "docstring": "Find stems for a given text."
  },
  {
    "code": "def doc(elt):\n    \"Show `show_doc` info in preview window along with link to full docs.\"\n    global use_relative_links\n    use_relative_links = False\n    elt = getattr(elt, '__func__', elt)\n    md = show_doc(elt, markdown=False)\n    if is_fastai_class(elt):\n        md += f'\\n\\n<a href=\"{get_fn_link(elt)}\" target=\"_blank\" rel=\"noreferrer noopener\">Show in docs</a>'\n    output = HTMLExporter().markdown2html(md)\n    use_relative_links = True\n    if IS_IN_COLAB: get_ipython().run_cell_magic(u'html', u'', output)\n    else:\n        try: page.page({'text/html': output})\n        except: display(Markdown(md))",
    "docstring": "Show `show_doc` info in preview window along with link to full docs."
  },
  {
    "code": "def _collapse(intervals):\n    span = None\n    for start, stop in intervals:\n        if span is None:\n            span = _Interval(start, stop)\n        elif start <= span.stop < stop:\n            span = _Interval(span.start, stop)\n        elif start > span.stop:\n            yield span\n            span = _Interval(start, stop)\n    if span is not None:\n        yield span",
    "docstring": "Collapse an iterable of intervals sorted by start coord."
  },
  {
    "code": "def __search_ca_path(self):\n        if \"X509_CERT_DIR\" in os.environ:\n            self._ca_path = os.environ['X509_CERT_DIR']\n        elif os.path.exists('/etc/grid-security/certificates'):\n            self._ca_path = '/etc/grid-security/certificates'\n        else:\n            raise ClientAuthException(\"Could not find a valid CA path\")",
    "docstring": "Get CA Path to check the validity of the server host certificate on the client side"
  },
  {
    "code": "def update(self, addr, raw_addr, name=None, rssi=None):\n        if addr in self._devices:\n            self._devices[addr].update(name, rssi)\n            return False\n        else:\n            self._devices[addr] = ScanResult(addr, raw_addr, name, rssi)\n            logger.debug('Scan result: {} / {}'.format(addr, name))\n            return True",
    "docstring": "Updates the collection of results with a newly received scan response.\n\n        Args:\n            addr (str): Device hardware address in xx:xx:xx:xx:xx:xx format.\n            raw_addr (bytearray): Device hardware address as raw bytes.\n            name (str): Device name (if available) as ASCII text. May be None.\n            rssi (float): Latest RSSI from the scan result for the device. May be 0.\n\n        Returns:\n            True if an existing device was updated, False if a new entry was created."
  },
  {
    "code": "def writegroup(self, auth, entries, defer=False):\n        return self._call('writegroup', auth, [entries], defer)",
    "docstring": "Writes the given values for the respective resources in the list, all writes have same\n        timestamp.\n\n        Args:\n            auth: cik for authentication.\n            entries: List of key, value lists. eg. [[key, value], [k,v],,,]"
  },
  {
    "code": "def moving_hfs_rank(h, size, start=0, stop=None):\n    windows = np.asarray(list(index_windows(h, size=size, start=start,\n                                            stop=stop, step=None)))\n    hr = np.zeros((windows.shape[0], h.shape[1]), dtype='i4')\n    for i, (window_start, window_stop) in enumerate(windows):\n        hw = h[window_start:window_stop]\n        hc = hw.distinct_counts()\n        hc.sort()\n        hc = hc[::-1]\n        cp = 0\n        for j, c in enumerate(hc):\n            if c > 1:\n                hr[i, cp:cp+c] = j+1\n            cp += c\n    return hr",
    "docstring": "Helper function for plotting haplotype frequencies in moving windows.\n\n    Parameters\n    ----------\n    h : array_like, int, shape (n_variants, n_haplotypes)\n        Haplotype array.\n    size : int\n        The window size (number of variants).\n    start : int, optional\n        The index at which to start.\n    stop : int, optional\n        The index at which to stop.\n\n    Returns\n    -------\n    hr : ndarray, int, shape (n_windows, n_haplotypes)\n        Haplotype rank array."
  },
  {
    "code": "def change_subscription(self, topics):\n        if self._user_assignment:\n            raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE)\n        if isinstance(topics, six.string_types):\n            topics = [topics]\n        if self.subscription == set(topics):\n            log.warning(\"subscription unchanged by change_subscription(%s)\",\n                        topics)\n            return\n        for t in topics:\n            self._ensure_valid_topic_name(t)\n        log.info('Updating subscribed topics to: %s', topics)\n        self.subscription = set(topics)\n        self._group_subscription.update(topics)\n        for tp in set(self.assignment.keys()):\n            if tp.topic not in self.subscription:\n                del self.assignment[tp]",
    "docstring": "Change the topic subscription.\n\n        Arguments:\n            topics (list of str): topics for subscription\n\n        Raises:\n            IllegalStateErrror: if assign_from_user has been used already\n            TypeError: if a topic is None or a non-str\n            ValueError: if a topic is an empty string or\n                        - a topic name is '.' or '..' or\n                        - a topic name does not consist of ASCII-characters/'-'/'_'/'.'"
  },
  {
    "code": "def get_notebook_daemon_command(self, name, action, port=0, *extra):\n        return [self.python, self.cmd, action, self.get_pid(name), self.get_work_folder(name), port, self.kill_timeout] + list(extra)",
    "docstring": "Assume we launch Notebook with the same Python which executed us."
  },
  {
    "code": "def register(self):\n        log.info('Installing ssh key, %s' % self.name)\n        self.consul.create_ssh_pub_key(self.name, self.key)",
    "docstring": "Registers SSH key with provider."
  },
  {
    "code": "def _create_label(self, array):\n        if len(array.shape) == 3:\n            bands = array.shape[0]\n            lines = array.shape[1]\n            line_samples = array.shape[2]\n        else:\n            bands = 1\n            lines = array.shape[0]\n            line_samples = array.shape[1]\n        record_bytes = line_samples * array.itemsize\n        label_module = pvl.PVLModule([\n            ('PDS_VERSION_ID', 'PDS3'),\n            ('RECORD_TYPE', 'FIXED_LENGTH'),\n            ('RECORD_BYTES', record_bytes),\n            ('LABEL_RECORDS', 1),\n            ('^IMAGE', 1),\n            ('IMAGE',\n                {'BANDS': bands,\n                 'LINES': lines,\n                 'LINE_SAMPLES': line_samples,\n                 'MAXIMUM': 0,\n                 'MEAN': 0,\n                 'MEDIAN': 0,\n                 'MINIMUM': 0,\n                 'SAMPLE_BITS': array.itemsize * 8,\n                 'SAMPLE_TYPE': 'MSB_INTEGER',\n                 'STANDARD_DEVIATION': 0})\n            ])\n        return self._update_label(label_module, array)",
    "docstring": "Create sample PDS3 label for NumPy Array.\n        It is called by 'image.py' to create PDS3Image object\n        from Numpy Array.\n\n        Returns\n        -------\n        PVLModule label for the given NumPy array.\n\n        Usage: self.label = _create_label(array)"
  },
  {
    "code": "def first_time_setup(self):\n        if not self._auto_unlock_key_position():\n            pw  = password.create_passwords()[0]\n            attrs = {'application': self.keyring}\n            gkr.item_create_sync(self.default_keyring\n                                ,gkr.ITEM_GENERIC_SECRET\n                                ,self.keyring\n                                ,attrs\n                                ,pw\n                                ,True)\n        found_pos = self._auto_unlock_key_position()\n        item_info = gkr.item_get_info_sync(self.default_keyring, found_pos)\n        gkr.create_sync(self.keyring, item_info.get_secret())",
    "docstring": "First time running Open Sesame? \n        \n        Create keyring and an auto-unlock key in default keyring. Make sure\n        these things don't already exist."
  },
  {
    "code": "def access_elementusers(self, elementuser_id, access_id=None, tenant_id=None, api_version=\"v2.0\"):\n        if tenant_id is None and self._parent_class.tenant_id:\n            tenant_id = self._parent_class.tenant_id\n        elif not tenant_id:\n            raise TypeError(\"tenant_id is required but not set or cached.\")\n        cur_ctlr = self._parent_class.controller\n        if not access_id:\n            url = str(cur_ctlr) + \"/{}/api/tenants/{}/elementusers/{}/access\".format(api_version,\n                                                                                     tenant_id,\n                                                                                     elementuser_id)\n        else:\n            url = str(cur_ctlr) + \"/{}/api/tenants/{}/elementusers/{}/access/{}\".format(api_version,\n                                                                                        tenant_id,\n                                                                                        elementuser_id,\n                                                                                        access_id)\n        api_logger.debug(\"URL = %s\", url)\n        return self._parent_class.rest_call(url, \"get\")",
    "docstring": "Get all accesses for a particular user\n\n          **Parameters:**:\n\n          - **elementuser_id**: Element User ID\n          - **access_id**: (optional) Access ID\n          - **tenant_id**: Tenant ID\n          - **api_version**: API version to use (default v2.0)\n\n        **Returns:** requests.Response object extended with cgx_status and cgx_content properties."
  },
  {
    "code": "def removepage(self, page):\n    try:\n      self._api_entrypoint.removePage(self._session_token, page)\n    except XMLRPCError as e:\n      raise ConfluenceError('Failed to delete page: %s' % e)",
    "docstring": "Deletes a page from confluence.\n    raises ConfluenceError if the page could not be removed."
  },
  {
    "code": "def init_recorder(self, recorder_config):\n        if not recorder_config:\n            self.recorder = None\n            self.recorder_path = None\n            return\n        if isinstance(recorder_config, str):\n            recorder_coll = recorder_config\n            recorder_config = {}\n        else:\n            recorder_coll = recorder_config['source_coll']\n        dedup_index = None\n        warc_writer = MultiFileWARCWriter(self.warcserver.archive_paths,\n                                          max_size=int(recorder_config.get('rollover_size', 1000000000)),\n                                          max_idle_secs=int(recorder_config.get('rollover_idle_secs', 600)),\n                                          filename_template=recorder_config.get('filename_template'),\n                                          dedup_index=dedup_index)\n        self.recorder = RecorderApp(self.RECORD_SERVER % str(self.warcserver_server.port), warc_writer,\n                                    accept_colls=recorder_config.get('source_filter'))\n        recorder_server = GeventServer(self.recorder, port=0)\n        self.recorder_path = self.RECORD_API % (recorder_server.port, recorder_coll)",
    "docstring": "Initialize the recording functionality of pywb. If recording_config is None this function is a no op"
  },
  {
    "code": "def errorprint():\n    try:\n        yield\n    except ConfigurationError as e:\n        click.secho('%s' % e, err=True, fg='red')\n        sys.exit(1)",
    "docstring": "Print out descriptions from ConfigurationError."
  },
  {
    "code": "def prior_neighbor(C, alpha=0.001):\n    r\n    if isdense(C):\n        B = sparse.prior.prior_neighbor(csr_matrix(C), alpha=alpha)\n        return B.toarray()\n    else:\n        return sparse.prior.prior_neighbor(C, alpha=alpha)",
    "docstring": "r\"\"\"Neighbor prior for the given count matrix.\n\n    Parameters\n    ----------\n    C : (M, M) ndarray or scipy.sparse matrix\n        Count matrix\n    alpha : float (optional)\n        Value of prior counts\n\n    Returns\n    -------\n    B : (M, M) ndarray or scipy.sparse matrix\n        Prior count matrix\n\n    Notes\n    ------\n    The neighbor prior :math:`b_{ij}` is defined as\n\n    .. math:: b_{ij}=\\left \\{ \\begin{array}{rl}\n                     \\alpha & c_{ij}+c_{ji}>0 \\\\\n                     0      & \\text{else}\n                     \\end{array} \\right .\n\n    Examples\n    --------\n\n    >>> import numpy as np\n    >>> from msmtools.estimation import prior_neighbor\n\n    >>> C = np.array([[10, 1, 0], [2, 0, 3], [0, 1, 4]])\n    >>> B = prior_neighbor(C)\n    >>> B\n    array([[ 0.001,  0.001,  0.   ],\n           [ 0.001,  0.   ,  0.001],\n           [ 0.   ,  0.001,  0.001]])"
  },
  {
    "code": "def _get_decimal_digits(decimal_number_match, number_of_significant_digits):\n    assert 'e' not in decimal_number_match.group()\n    try:\n        num_of_digits = int(number_of_significant_digits)\n    except TypeError:\n        num_of_digits = DEFAULT_NUMBER_OF_SIGNIFICANT_DIGITS\n    if not decimal_number_match.group(GROUP_DEC_PART):\n        return 0\n    if int(decimal_number_match.group(GROUP_INT_PART)) == 0 \\\n            and int(decimal_number_match.group(GROUP_DEC_PART)[1:]) != 0:\n        max_num_of_digits = len(decimal_number_match.group(GROUP_SIG_DEC_PART))\n        num_of_digits = min(num_of_digits, max_num_of_digits)\n        curr_dec_digits = len(decimal_number_match.group(GROUP_ZEROES)) + int(num_of_digits)\n    else:\n        max_num_of_digits = \\\n            len(decimal_number_match.group(GROUP_INT_PART)) + len(decimal_number_match.group(GROUP_DEC_PART))\n        num_of_digits = min(num_of_digits, max_num_of_digits)\n        curr_dec_digits = int(num_of_digits) - len(decimal_number_match.group(GROUP_INT_PART))\n    return curr_dec_digits",
    "docstring": "Returns the amount of decimal digits of the given regex match, considering the number of significant\n    digits for the provided column.\n\n    @param decimal_number_match: a regex match of a decimal number, resulting from REGEX_MEASURE.match(x).\n    @param number_of_significant_digits: the number of significant digits required\n    @return: the number of decimal digits of the given decimal number match's representation, after expanding\n        the number to the required amount of significant digits"
  },
  {
    "code": "def modSymbolsFromLabelInfo(labelDescriptor):\n    modSymbols = set()\n    for labelStateEntry in viewvalues(labelDescriptor.labels):\n        for labelPositionEntry in viewvalues(labelStateEntry['aminoAcidLabels']):\n            for modSymbol in aux.toList(labelPositionEntry):\n                if modSymbol != '':\n                    modSymbols.add(modSymbol)\n    return modSymbols",
    "docstring": "Returns a set of all modiciation symbols which were used in the\n    labelDescriptor\n\n    :param labelDescriptor: :class:`LabelDescriptor` describes the label setup\n        of an experiment\n\n    :returns: #TODO: docstring"
  },
  {
    "code": "def reparse(self):\n        self._remove_all_children()\n        self._parse_context(self._context, self.orb)",
    "docstring": "Reparse all children of this directory.\n\n        This effectively rebuilds the tree below this node.\n\n        This operation takes an unbounded time to complete; if there are a lot\n        of objects registered below this directory's context, they will all\n        need to be parsed."
  },
  {
    "code": "def translate(obj, vec, **kwargs):\n    if not vec or not isinstance(vec, (tuple, list)):\n        raise GeomdlException(\"The input must be a list or a tuple\")\n    if len(vec) != obj.dimension:\n        raise GeomdlException(\"The input vector must have \" + str(obj.dimension) + \" components\")\n    inplace = kwargs.get('inplace', False)\n    if not inplace:\n        geom = copy.deepcopy(obj)\n    else:\n        geom = obj\n    for g in geom:\n        new_ctrlpts = []\n        for pt in g.ctrlpts:\n            temp = [v + vec[i] for i, v in enumerate(pt)]\n            new_ctrlpts.append(temp)\n        g.ctrlpts = new_ctrlpts\n    return geom",
    "docstring": "Translates curves, surface or volumes by the input vector.\n\n    Keyword Arguments:\n        * ``inplace``: if False, operation applied to a copy of the object. *Default: False*\n\n    :param obj: input geometry\n    :type obj: abstract.SplineGeometry or multi.AbstractContainer\n    :param vec: translation vector\n    :type vec: list, tuple\n    :return: translated geometry object"
  },
  {
    "code": "def lookup_subclass(cls, d):\n        try:\n            typeid = d[\"typeid\"]\n        except KeyError:\n            raise FieldError(\"typeid not present in keys %s\" % list(d))\n        subclass = cls._subcls_lookup.get(typeid, None)\n        if not subclass:\n            raise FieldError(\"'%s' not a valid typeid\" % typeid)\n        else:\n            return subclass",
    "docstring": "Look up a class based on a serialized dictionary containing a typeid\n\n        Args:\n            d (dict): Dictionary with key \"typeid\"\n\n        Returns:\n            Serializable subclass"
  },
  {
    "code": "def _set_status_self(self, key=JobDetails.topkey, status=JobStatus.unknown):\n        fullkey = JobDetails.make_fullkey(self.full_linkname, key)\n        if fullkey in self.jobs:\n            self.jobs[fullkey].status = status\n            if self._job_archive:\n                self._job_archive.register_job(self.jobs[fullkey])\n        else:\n            self._register_self('dummy.log', key, status)",
    "docstring": "Set the status of this job, both in self.jobs and\n        in the `JobArchive` if it is present."
  },
  {
    "code": "def add_note(note, **kwargs):\n    note_i = Note()\n    note_i.ref_key = note.ref_key\n    note_i.set_ref(note.ref_key, note.ref_id)\n    note_i.value = note.value\n    note_i.created_by = kwargs.get('user_id')\n    db.DBSession.add(note_i)\n    db.DBSession.flush()\n    return note_i",
    "docstring": "Add a new note"
  },
  {
    "code": "def has_property(obj, name):\n        if obj == None or name == None:\n            return False\n        names = name.split(\".\")\n        if names == None or len(names) == 0: \n            return False\n        return RecursiveObjectReader._perform_has_property(obj, names, 0)",
    "docstring": "Checks recursively if object or its subobjects has a property with specified name.\n\n        The object can be a user defined object, map or array.\n        The property name correspondently must be object property, map key or array index.\n\n        :param obj: an object to introspect.\n\n        :param name: a name of the property to check.\n\n        :return: true if the object has the property and false if it doesn't."
  },
  {
    "code": "def get_namespace_and_tag(name):\n        if isinstance(name, str):\n            if name[0] == \"{\":\n                uri, ignore, tag = name[1:].partition(\"}\")\n            else:\n                uri = None\n                tag = name\n        else:\n            uri = None\n            tag = None\n        return uri, tag",
    "docstring": "Separates the namespace and tag from an element.\n\n        :param str name: Tag.\n        :returns: Namespace URI and Tag namespace.\n        :rtype: tuple"
  },
  {
    "code": "def get_credits_by_section_and_regid(section, regid):\n    deprecation(\"Use get_credits_by_reg_url\")\n    url = \"{}{},{},{},{},{},{},.json\".format(\n        reg_credits_url_prefix,\n        section.term.year,\n        section.term.quarter,\n        re.sub(' ', '%20', section.curriculum_abbr),\n        section.course_number,\n        section.section_id,\n        regid\n    )\n    reg_data = get_resource(url)\n    try:\n        return Decimal(reg_data['Credits'].strip())\n    except InvalidOperation:\n        pass",
    "docstring": "Returns a uw_sws.models.Registration object\n    for the section and regid passed in."
  },
  {
    "code": "def destroyManager(self, force=False):\n        if self.getManager(force=force) is not None:\n            key = self.getSessionKey()\n            del self.session[key]",
    "docstring": "Delete any YadisServiceManager with this starting URL and\n        suffix from the session.\n\n        If there is no service manager or the service manager is for a\n        different URL, it silently does nothing.\n\n        @param force: True if the manager should be deleted regardless\n        of whether it's a manager for self.url."
  },
  {
    "code": "def thin_samples_for_writing(fp, samples, parameters, last_iteration):\n    if fp.thinned_by > 1:\n        if last_iteration is None:\n            raise ValueError(\"File's thinned_by attribute is > 1 ({}), \"\n                             \"but last_iteration not provided.\"\n                             .format(fp.thinned_by))\n        thinned_samples = {}\n        for param in parameters:\n            data = samples[param]\n            nsamples = data.shape[-1]\n            thin_start = fp.last_iteration(param) + fp.thinned_by \\\n                - (last_iteration - nsamples) - 1\n            thinned_samples[param] = data[..., thin_start::fp.thinned_by]\n    else:\n        thinned_samples = samples\n    return thinned_samples",
    "docstring": "Thins samples for writing to disk.\n\n    The thinning interval to use is determined by the given file handler's\n    ``thinned_by`` attribute. If that attribute is 1, just returns the samples.\n\n    Parameters\n    ----------\n    fp : MCMCMetadataIO instance\n        The file the sampels will be written to. Needed to determine the\n        thin interval used on disk.\n    samples : dict\n        Dictionary mapping parameter names to arrays of (unthinned) samples.\n        The arrays are thinned along their last dimension.\n    parameters : list of str\n        The parameters to thin in ``samples`` before writing. All listed\n        parameters must be in ``samples``.\n    last_iteration : int\n        The iteration that the last sample in ``samples`` occurred at. This is\n        needed to figure out where to start the thinning in ``samples``, such\n        that the interval between the last sample on disk and the first new\n        sample is the same as all of the other samples.\n\n    Returns\n    -------\n    dict :\n        Dictionary of the thinned samples to write."
  },
  {
    "code": "def _parse_shape(self, space):\n    if isinstance(space, gym.spaces.Discrete):\n      return ()\n    if isinstance(space, gym.spaces.Box):\n      return space.shape\n    raise NotImplementedError()",
    "docstring": "Get a tensor shape from a OpenAI Gym space.\n\n    Args:\n      space: Gym space.\n\n    Raises:\n      NotImplementedError: For spaces other than Box and Discrete.\n\n    Returns:\n      Shape tuple."
  },
  {
    "code": "def cublasSgbmv(handle, trans, m, n, kl, ku, alpha, A, lda,\n                x, incx, beta, y, incy):\n    status = _libcublas.cublasSgbmv_v2(handle,\n                                       trans, m, n, kl, ku,\n                                       ctypes.byref(ctypes.c_float(alpha)),\n                                       int(A), lda,\n                                       int(x), incx,\n                                       ctypes.byref(ctypes.c_float(beta)),\n                                       int(y), incy)\n    cublasCheckStatus(status)",
    "docstring": "Matrix-vector product for real general banded matrix."
  },
  {
    "code": "def setup(self, redis_conn=None, host='localhost', port=6379):\n        if redis_conn is None:\n            if host is not None and port is not None:\n                self.redis_conn = redis.Redis(host=host, port=port)\n            else:\n                raise Exception(\"Please specify some form of connection \"\n                                    \"to Redis\")\n        else:\n            self.redis_conn = redis_conn\n        self.redis_conn.info()",
    "docstring": "Set up the redis connection"
  },
  {
    "code": "def fromfilenames(cls, filenames, coltype=LIGOTimeGPS):\n\t\tcache = cls()\n\t\tfor filename in filenames:\n\t\t\tcache.extend(cls.fromfile(open(filename), coltype=coltype))\n\t\treturn cache",
    "docstring": "Read Cache objects from the files named and concatenate the results into a\n\t\tsingle Cache."
  },
  {
    "code": "def _get_dvportgroup_dict(pg_ref):\n    props = salt.utils.vmware.get_properties_of_managed_object(\n        pg_ref, ['name', 'config.description', 'config.numPorts',\n                 'config.type', 'config.defaultPortConfig'])\n    pg_dict = {'name': props['name'],\n               'description': props.get('config.description'),\n               'num_ports': props['config.numPorts'],\n               'type': props['config.type']}\n    if props['config.defaultPortConfig']:\n        dpg = props['config.defaultPortConfig']\n        if dpg.vlan and \\\n           isinstance(dpg.vlan,\n                      vim.VmwareDistributedVirtualSwitchVlanIdSpec):\n            pg_dict.update({'vlan_id': dpg.vlan.vlanId})\n        pg_dict.update({'out_shaping':\n                        _get_dvportgroup_out_shaping(\n                            props['name'],\n                            props['config.defaultPortConfig'])})\n        pg_dict.update({'security_policy':\n                        _get_dvportgroup_security_policy(\n                            props['name'],\n                            props['config.defaultPortConfig'])})\n        pg_dict.update({'teaming':\n                        _get_dvportgroup_teaming(\n                            props['name'],\n                            props['config.defaultPortConfig'])})\n    return pg_dict",
    "docstring": "Returns a dictionary with a distributed virutal portgroup data\n\n\n    pg_ref\n        Portgroup reference"
  },
  {
    "code": "def show_customer(self, customer_id):\n        request = self._get('customers/' + str(customer_id))\n        return self.responder(request)",
    "docstring": "Shows an existing customer."
  },
  {
    "code": "def _build_layout(self):\n        \" Rebuild a new Container object and return that. \"\n        logger.info('Rebuilding layout.')\n        if not self.pymux.arrangement.windows:\n            return Window()\n        active_window = self.pymux.arrangement.get_active_window()\n        if active_window.zoom:\n            return to_container(_create_container_for_process(\n                self.pymux, active_window, active_window.active_pane, zoom=True))\n        else:\n            window = self.pymux.arrangement.get_active_window()\n            return HSplit([\n                ConditionalContainer(\n                    content=Window(height=1),\n                    filter=Condition(lambda: self.pymux.enable_pane_status)),\n                _create_split(self.pymux, window, window.root)\n            ])",
    "docstring": "Rebuild a new Container object and return that."
  },
  {
    "code": "def to_cli_filter(bool_or_filter):\n    if not isinstance(bool_or_filter, (bool, CLIFilter)):\n        raise TypeError('Expecting a bool or a CLIFilter instance. Got %r' % bool_or_filter)\n    return {\n        True: _always,\n        False: _never,\n    }.get(bool_or_filter, bool_or_filter)",
    "docstring": "Accept both booleans and CLIFilters as input and\n    turn it into a CLIFilter."
  },
  {
    "code": "def equals(df1, df2, ignore_order=set(), ignore_indices=set(), all_close=False, _return_reason=False):\n    result = _equals(df1, df2, ignore_order, ignore_indices, all_close)\n    if _return_reason:\n        return result\n    else:\n        return result[0]",
    "docstring": "Get whether 2 data frames are equal.\n\n    ``NaN`` is considered equal to ``NaN`` and `None`.\n\n    Parameters\n    ----------\n    df1 : ~pandas.DataFrame\n        Data frame to compare.\n    df2 : ~pandas.DataFrame\n        Data frame to compare.\n    ignore_order : ~typing.Set[int]\n        Axi in which to ignore order.\n    ignore_indices : ~typing.Set[int]\n        Axi of which to ignore the index. E.g. ``{1}`` allows differences in\n        ``df.columns.name`` and ``df.columns.equals(df2.columns)``.\n    all_close : bool\n        If `False`, values must match exactly, if `True`, floats are compared as if\n        compared with `numpy.isclose`.\n    _return_reason : bool\n        Internal. If `True`, `equals` returns a tuple containing the reason, else\n        `equals` only returns a bool indicating equality (or equivalence\n        rather).\n\n    Returns\n    -------\n    bool\n        Whether they are equal (after ignoring according to the parameters).\n\n        Internal note: if ``_return_reason``, ``Tuple[bool, str or None]`` is\n        returned. The former is whether they're equal, the latter is `None` if\n        equal or a short explanation of why the data frames aren't equal,\n        otherwise.\n\n    Notes\n    -----\n    All values (including those of indices) must be copyable and ``__eq__`` must\n    be such that a copy must equal its original. A value must equal itself\n    unless it's ``NaN``. Values needn't be orderable or hashable (however\n    pandas requires index values to be orderable and hashable). By consequence,\n    this is not an efficient function, but it is flexible.\n\n    Examples\n    --------\n    >>> from pytil import data_frame as df_\n    >>> import pandas as pd\n    >>> df = pd.DataFrame([\n    ...        [1, 2, 3],\n    ...        [4, 5, 6],\n    ...        [7, 8, 9]\n    ...    ],\n    ...    index=pd.Index(('i1', 'i2', 'i3'), name='index1'),\n    ...    columns=pd.Index(('c1', 'c2', 'c3'), name='columns1')\n    ... )\n    >>> df\n    columns1  c1  c2  c3\n    index1              \n    i1         1   2   3\n    i2         4   5   6\n    i3         7   8   9\n    >>> df2 = df.reindex(('i3', 'i1', 'i2'), columns=('c2', 'c1', 'c3'))\n    >>> df2\n    columns1  c2  c1  c3\n    index1              \n    i3         8   7   9\n    i1         2   1   3\n    i2         5   4   6\n    >>> df_.equals(df, df2)\n    False\n    >>> df_.equals(df, df2, ignore_order=(0,1))\n    True\n    >>> df2 = df.copy()\n    >>> df2.index = [1,2,3]\n    >>> df2\n    columns1  c1  c2  c3\n    1          1   2   3\n    2          4   5   6\n    3          7   8   9\n    >>> df_.equals(df, df2)\n    False\n    >>> df_.equals(df, df2, ignore_indices={0})\n    True\n    >>> df2 = df.reindex(('i3', 'i1', 'i2'))\n    >>> df2\n    columns1  c1  c2  c3\n    index1              \n    i3         7   8   9\n    i1         1   2   3\n    i2         4   5   6\n    >>> df_.equals(df, df2, ignore_indices={0})  # does not ignore row order!\n    False\n    >>> df_.equals(df, df2, ignore_order={0})\n    True\n    >>> df2 = df.copy()\n    >>> df2.index.name = 'other'\n    >>> df_.equals(df, df2)  # df.index.name must match as well, same goes for df.columns.name\n    False"
  },
  {
    "code": "def parse(timestring):\n    for parser in _PARSERS:\n        match = parser['pattern'].match(timestring)\n        if match:\n            groups = match.groups()\n            ints = tuple(map(int, groups))\n            time = parser['factory'](ints)\n            return time\n    raise TimeError('Unsupported time format {}'.format(timestring))",
    "docstring": "Convert a statbank time string to a python datetime object."
  },
  {
    "code": "def app0(self):\n        for m in self._markers:\n            if m.marker_code == JPEG_MARKER_CODE.APP0:\n                return m\n        raise KeyError('no APP0 marker in image')",
    "docstring": "First APP0 marker in image markers."
  },
  {
    "code": "def purge_old_user_tasks():\n    limit = now() - settings.USER_TASKS_MAX_AGE\n    UserTaskStatus.objects.filter(created__lt=limit).delete()",
    "docstring": "Delete any UserTaskStatus and UserTaskArtifact records older than ``settings.USER_TASKS_MAX_AGE``.\n\n    Intended to be run as a scheduled task."
  },
  {
    "code": "def diagonalSize(self):\n        szs = [a.diagonalSize() for a in self.actors]\n        return np.max(szs)",
    "docstring": "Return the maximum diagonal size of the ``Actors`` of the ``Assembly``."
  },
  {
    "code": "def _get_opts_seaborn(self, opts, style):\n        if opts is None:\n            if self.chart_opts is None:\n                opts = {}\n            else:\n                opts = self.chart_opts\n        if style is None:\n            if self.chart_style is None:\n                style = self.chart_style\n            else:\n                style = {}\n        return opts, style",
    "docstring": "Initialialize for chart rendering"
  },
  {
    "code": "def is_list(self, key):\r\n        data = self.model.get_data()\r\n        return isinstance(data[key], (tuple, list))",
    "docstring": "Return True if variable is a list or a tuple"
  },
  {
    "code": "def create_convert_sbml_id_function(\n        compartment_prefix='C_', reaction_prefix='R_',\n        compound_prefix='M_', decode_id=entry_id_from_cobra_encoding):\n    def convert_sbml_id(entry):\n        if isinstance(entry, BaseCompartmentEntry):\n            prefix = compartment_prefix\n        elif isinstance(entry, BaseReactionEntry):\n            prefix = reaction_prefix\n        elif isinstance(entry, BaseCompoundEntry):\n            prefix = compound_prefix\n        new_id = entry.id\n        if decode_id is not None:\n            new_id = decode_id(new_id)\n        if prefix is not None and new_id.startswith(prefix):\n            new_id = new_id[len(prefix):]\n        return new_id\n    return convert_sbml_id",
    "docstring": "Create function for converting SBML IDs.\n\n    The returned function will strip prefixes, decode the ID using the provided\n    function. These prefixes are common on IDs in SBML models because the IDs\n    live in a global namespace."
  },
  {
    "code": "def process_tokendef(cls, name, tokendefs=None):\n        processed = cls._all_tokens[name] = {}\n        tokendefs = tokendefs or cls.tokens[name]\n        for state in list(tokendefs):\n            cls._process_state(tokendefs, processed, state)\n        return processed",
    "docstring": "Preprocess a dictionary of token definitions."
  },
  {
    "code": "def validate_maximum(value, maximum, is_exclusive, **kwargs):\n    if is_exclusive:\n        comparison_text = \"less than\"\n        compare_fn = operator.lt\n    else:\n        comparison_text = \"less than or equal to\"\n        compare_fn = operator.le\n    if not compare_fn(value, maximum):\n        raise ValidationError(\n            MESSAGES['maximum']['invalid'].format(value, comparison_text, maximum),\n        )",
    "docstring": "Validator function for validating that a value does not violate it's\n    maximum allowed value.  This validation can be inclusive, or exclusive of\n    the maximum depending on the value of `is_exclusive`."
  },
  {
    "code": "def coerce(self, value):\n        if self._coerce is not None:\n            value = self._coerce(value)\n        return value",
    "docstring": "Coerce a cleaned value."
  },
  {
    "code": "def find_hostname(use_chroot=True):\n    for chroot_file in CHROOT_FILES:\n        try:\n            with open(chroot_file) as handle:\n                first_line = next(handle)\n                name = first_line.strip()\n                if name:\n                    return name\n        except Exception:\n            pass\n    return socket.gethostname()",
    "docstring": "Find the host name to include in log messages.\n\n    :param use_chroot: Use the name of the chroot when inside a chroot?\n                       (boolean, defaults to :data:`True`)\n    :returns: A suitable host name (a string).\n\n    Looks for :data:`CHROOT_FILES` that have a nonempty first line (taken to be\n    the chroot name). If none are found then :func:`socket.gethostname()` is\n    used as a fall back."
  },
  {
    "code": "def extend(self, other):\n\t\tfor key, value in other.iteritems():\n\t\t\tif key not in self:\n\t\t\t\tself[key] = _shallowcopy(value)\n\t\t\telse:\n\t\t\t\tself[key].extend(value)",
    "docstring": "Appends the segmentlists from other to the corresponding\n\t\tsegmentlists in self, adding new segmentslists to self as\n\t\tneeded."
  },
  {
    "code": "def loadMsbwt(self, dirName, logger):\n        self.dirName = dirName\n        self.bwt = np.load(self.dirName+'/comp_msbwt.npy', 'r')\n        self.constructTotalCounts(logger)\n        self.constructIndexing()\n        self.constructFMIndex(logger)",
    "docstring": "This functions loads a BWT file and constructs total counts, indexes start positions, and constructs an FM index in memory\n        @param dirName - the directory to load, inside should be '<DIR>/comp_msbwt.npy' or it will fail"
  },
  {
    "code": "def _post(self, endpoint, data, **kwargs):\n        return self._request(endpoint, 'post', data, **kwargs)",
    "docstring": "Method to perform POST request on the API.\n\n        :param endpoint: Endpoint of the API.\n        :param data: POST DATA for the request.\n        :param kwargs: Other keyword arguments for requests.\n\n        :return: Response of the POST request."
  },
  {
    "code": "def cleanup(self):\n        self._processing_stop = True\n        self._wakeup_processing_thread()\n        self._processing_stopped_event.wait(3)",
    "docstring": "Stop backgroud thread and cleanup resources"
  },
  {
    "code": "def file_copy(src=None, dest=None):\n    conn = __proxy__['junos.conn']()\n    ret = {}\n    ret['out'] = True\n    if src is None:\n        ret['message'] = \\\n            'Please provide the absolute path of the file to be copied.'\n        ret['out'] = False\n        return ret\n    if not os.path.isfile(src):\n        ret['message'] = 'Invalid source file path'\n        ret['out'] = False\n        return ret\n    if dest is None:\n        ret['message'] = \\\n            'Please provide the absolute path of the destination where the file is to be copied.'\n        ret['out'] = False\n        return ret\n    try:\n        with SCP(conn, progress=True) as scp:\n            scp.put(src, dest)\n        ret['message'] = 'Successfully copied file from {0} to {1}'.format(\n            src, dest)\n    except Exception as exception:\n        ret['message'] = 'Could not copy file : \"{0}\"'.format(exception)\n        ret['out'] = False\n    return ret",
    "docstring": "Copies the file from the local device to the junos device\n\n    src\n        The source path where the file is kept.\n\n    dest\n        The destination path on the where the file will be copied\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'device_name' junos.file_copy /home/m2/info.txt info_copy.txt"
  },
  {
    "code": "def to_unit(self, unit):\n        new_data_c = self.duplicate()\n        new_data_c.convert_to_unit(unit)\n        return new_data_c",
    "docstring": "Return a Data Collection in the input unit."
  },
  {
    "code": "def generic_translate(frm=None, to=None, delete=''):\n    if PY2:\n        delete_dict = dict.fromkeys(ord(unicode(d)) for d in delete)\n        if frm is None and to is None:\n            string_trans = None\n            unicode_table = delete_dict\n        else:\n            string_trans = string.maketrans(frm, to)\n            unicode_table = dict(((ord(unicode(f)), unicode(t))\n                for f, t in zip(frm, to)), **delete_dict)\n        string_args = (string_trans, delete) if delete else (string_trans,)\n        translate_args = [string_args, (unicode_table,)]\n        def translate(basestr):\n            args = translate_args[isinstance(basestr, unicode)]\n            return basestr.translate(*args)\n    else:\n        string_trans = str.maketrans(frm or '', to or '', delete or '')\n        def translate(basestr):\n            return basestr.translate(string_trans)\n    return translate",
    "docstring": "Return a translate function for strings and unicode.\n\n    >>> translate = generic_translate('Hoy', 'Bad', 'r')\n\n    >>> translate('Holy grail')\n    'Bald gail'\n\n    >>> translate(u'Holy grail') == u'Bald gail'\n    True"
  },
  {
    "code": "def create(example):\n    try:\n        this_dir = os.path.dirname(os.path.realpath(__file__))\n        example_dir = os.path.join(this_dir, os.pardir, \"examples\", example)\n        shutil.copytree(example_dir, os.path.join(os.getcwd(), example))\n        log(\"Example created.\", delay=0)\n    except TypeError:\n        click.echo(\"Example '{}' does not exist.\".format(example))\n    except OSError:\n        click.echo(\"Example '{}' already exists here.\".format(example))",
    "docstring": "Create a copy of the given example."
  },
  {
    "code": "def send_position_setpoint(self, x, y, z, yaw):\n        pk = CRTPPacket()\n        pk.port = CRTPPort.COMMANDER_GENERIC\n        pk.data = struct.pack('<Bffff', TYPE_POSITION,\n                              x, y, z, yaw)\n        self._cf.send_packet(pk)",
    "docstring": "Control mode where the position is sent as absolute x,y,z coordinate in\n        meter and the yaw is the absolute orientation.\n\n        x and y are in m\n        yaw is in degrees"
  },
  {
    "code": "def reduce_by(self, package_request):\n        if self.pr:\n            reqstr = _short_req_str(package_request)\n            self.pr.passive(\"reducing %s wrt %s...\", self, reqstr)\n        if self.solver.optimised:\n            if package_request in self.been_reduced_by:\n                return (self, [])\n        if (package_request.range is None) or \\\n                (package_request.name not in self.fam_requires):\n            return (self, [])\n        with self.solver.timed(self.solver.reduction_time):\n            return self._reduce_by(package_request)",
    "docstring": "Remove variants whos dependencies conflict with the given package\n        request.\n\n        Returns:\n            (VariantSlice, [Reduction]) tuple, where slice may be None if all\n            variants were reduced."
  },
  {
    "code": "def _iterslice(self, slice):\n        indices = range(*slice.indices(len(self._records)))\n        if self.is_attached():\n            rows = self._enum_attached_rows(indices)\n            if slice.step is not None and slice.step < 0:\n                rows = reversed(list(rows))\n        else:\n            rows = zip(indices, self._records[slice])\n        fields = self.fields\n        for i, row in rows:\n            yield Record._make(fields, row, self, i)",
    "docstring": "Yield records from a slice index."
  },
  {
    "code": "def __is_control_flow(self):\n        jump_instructions = (\n            'jmp', 'jecxz', 'jcxz',\n            'ja', 'jnbe', 'jae', 'jnb', 'jb', 'jnae', 'jbe', 'jna', 'jc', 'je',\n            'jz', 'jnc', 'jne', 'jnz', 'jnp', 'jpo', 'jp', 'jpe', 'jg', 'jnle',\n            'jge', 'jnl', 'jl', 'jnge', 'jle', 'jng', 'jno', 'jns', 'jo', 'js'\n        )\n        call_instructions = ( 'call', 'ret', 'retn' )\n        loop_instructions = ( 'loop', 'loopz', 'loopnz', 'loope', 'loopne' )\n        control_flow_instructions = call_instructions + loop_instructions + \\\n                                    jump_instructions\n        isControlFlow = False\n        instruction = None\n        if self.pc is not None and self.faultDisasm:\n            for disasm in self.faultDisasm:\n                if disasm[0] == self.pc:\n                    instruction = disasm[2].lower().strip()\n                    break\n        if instruction:\n            for x in control_flow_instructions:\n                if x in instruction:\n                    isControlFlow = True\n                    break\n        return isControlFlow",
    "docstring": "Private method to tell if the instruction pointed to by the program\n        counter is a control flow instruction.\n\n        Currently only works for x86 and amd64 architectures."
  },
  {
    "code": "def _map_arg_names(source, mapping):\n        return {cartopy_name: source[cf_name] for cartopy_name, cf_name in mapping\n                if cf_name in source}",
    "docstring": "Map one set of keys to another."
  },
  {
    "code": "def has_hardware_breakpoint(self, dwThreadId, address):\n        if dwThreadId in self.__hardwareBP:\n            bpSet = self.__hardwareBP[dwThreadId]\n            for bp in bpSet:\n                if bp.get_address() == address:\n                    return True\n        return False",
    "docstring": "Checks if a hardware breakpoint is defined at the given address.\n\n        @see:\n            L{define_hardware_breakpoint},\n            L{get_hardware_breakpoint},\n            L{erase_hardware_breakpoint},\n            L{enable_hardware_breakpoint},\n            L{enable_one_shot_hardware_breakpoint},\n            L{disable_hardware_breakpoint}\n\n        @type  dwThreadId: int\n        @param dwThreadId: Thread global ID.\n\n        @type  address: int\n        @param address: Memory address of breakpoint.\n\n        @rtype:  bool\n        @return: C{True} if the breakpoint is defined, C{False} otherwise."
  },
  {
    "code": "def read_to_end(self, record=None):\n        if not self.record:\n            return None\n        if self.member_info:\n            return None\n        curr_offset = self.offset\n        while True:\n            b = self.record.raw_stream.read(BUFF_SIZE)\n            if not b:\n                break\n        self.next_line, empty_size = self._consume_blanklines()\n        self.offset = self.fh.tell() - self.reader.rem_length()\n        if self.next_line:\n            self.offset -= len(self.next_line)\n        length = self.offset - curr_offset\n        if not self.reader.decompressor:\n            length -= empty_size\n        self.member_info = (curr_offset, length)",
    "docstring": "Read remainder of the stream\n        If a digester is included, update it\n        with the data read"
  },
  {
    "code": "def current(sam=False):\n    try:\n        if sam:\n            user_name = win32api.GetUserNameEx(win32con.NameSamCompatible)\n        else:\n            user_name = win32api.GetUserName()\n    except pywintypes.error as exc:\n        log.error('Failed to get current user')\n        log.error('nbr: %s', exc.winerror)\n        log.error('ctx: %s', exc.funcname)\n        log.error('msg: %s', exc.strerror)\n        raise CommandExecutionError('Failed to get current user', info=exc)\n    if not user_name:\n        raise CommandExecutionError('Failed to get current user')\n    return user_name",
    "docstring": "Get the username that salt-minion is running under. If salt-minion is\n    running as a service it should return the Local System account. If salt is\n    running from a command prompt it should return the username that started the\n    command prompt.\n\n    .. versionadded:: 2015.5.6\n\n    Args:\n        sam (bool, optional): False returns just the username without any domain\n            notation. True returns the domain with the username in the SAM\n            format. Ie: ``domain\\\\username``\n\n    Returns:\n        str: Returns username\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' user.current"
  },
  {
    "code": "def as_patch(self, **kwargs):\n        from matplotlib.patches import Rectangle\n        return Rectangle(xy=(self.extent[0], self.extent[2]),\n                         width=self.shape[1], height=self.shape[0], **kwargs)",
    "docstring": "Return a `matplotlib.patches.Rectangle` that represents the\n        bounding box.\n\n        Parameters\n        ----------\n        kwargs\n            Any keyword arguments accepted by\n            `matplotlib.patches.Patch`.\n\n        Returns\n        -------\n        result : `matplotlib.patches.Rectangle`\n            A matplotlib rectangular patch.\n\n        Examples\n        --------\n        .. plot::\n            :include-source:\n\n            import matplotlib.pyplot as plt\n            from photutils import BoundingBox\n            bbox = BoundingBox(2, 7, 3, 8)\n            fig = plt.figure()\n            ax = fig.add_subplot(1, 1, 1)\n            np.random.seed(12345)\n            ax.imshow(np.random.random((10, 10)), interpolation='nearest',\n                      cmap='viridis')\n            ax.add_patch(bbox.as_patch(facecolor='none', edgecolor='white',\n                         lw=2.))"
  },
  {
    "code": "def list_anime_series(self, sort=META.SORT_ALPHA, limit=META.MAX_SERIES, offset=0):\n        result = self._android_api.list_series(\n            media_type=ANDROID.MEDIA_TYPE_ANIME,\n            filter=sort,\n            limit=limit,\n            offset=offset)\n        return result",
    "docstring": "Get a list of anime series\n\n        @param str sort     pick how results should be sorted, should be one\n                                of META.SORT_*\n        @param int limit    limit number of series to return, there doesn't\n                                seem to be an upper bound\n        @param int offset   list series starting from this offset, for pagination\n        @return list<crunchyroll.models.Series>"
  },
  {
    "code": "def from_textfile(cls, textfile, workers=1, job_size=1000):\n    c = Counter()\n    if isinstance(textfile, string_types):\n      textfile = TextFile(textfile)\n    for result in textfile.apply(count, workers, job_size):\n      c.update(result)\n    return CountedVocabulary(word_count=c)",
    "docstring": "Count the set of words appeared in a text file.\n\n    Args:\n      textfile (string): The name of the text file or `TextFile` object.\n      min_count (integer): Minimum number of times a word/token appeared in the document\n                 to be considered part of the vocabulary.\n      workers (integer): Number of parallel workers to read the file simulatenously.\n      job_size (integer): Size of the batch send to each worker.\n      most_frequent (integer): if no min_count is specified, consider the most frequent k words for the vocabulary.\n\n    Returns:\n      A vocabulary of the most frequent words appeared in the document."
  },
  {
    "code": "def from_string(cls, string, format_=None, fps=None, **kwargs):\n        fp = io.StringIO(string)\n        return cls.from_file(fp, format_, fps=fps, **kwargs)",
    "docstring": "Load subtitle file from string.\n\n        See :meth:`SSAFile.load()` for full description.\n\n        Arguments:\n            string (str): Subtitle file in a string. Note that the string\n                must be Unicode (in Python 2).\n\n        Returns:\n            SSAFile\n\n        Example:\n            >>> text = '''\n            ... 1\n            ... 00:00:00,000 --> 00:00:05,000\n            ... An example SubRip file.\n            ... '''\n            >>> subs = SSAFile.from_string(text)"
  },
  {
    "code": "def list_records(self, rtype=None, name=None, content=None, **kwargs):\n        if not rtype and kwargs.get('type'):\n            warnings.warn('Parameter \"type\" is deprecated, use \"rtype\" instead.',\n                          DeprecationWarning)\n            rtype = kwargs.get('type')\n        return self._list_records(rtype=rtype, name=name, content=content)",
    "docstring": "List all records. Return an empty list if no records found\n        type, name and content are used to filter records.\n        If possible filter during the query, otherwise filter after response is received."
  },
  {
    "code": "def push(self, cart, env=None, callback=None):\n        juicer.utils.Log.log_debug(\"Initializing push of cart '%s'\" % cart.cart_name)\n        if not env:\n            env = self._defaults['start_in']\n        cart.current_env = env\n        self.sign_cart_for_env_maybe(cart, env)\n        self.upload(env, cart, callback)\n        return True",
    "docstring": "`cart` - Release cart to push items from\n        `callback` - Optional callback to call if juicer.utils.upload_rpm succeeds\n\n        Pushes the items in a release cart to the pre-release environment."
  },
  {
    "code": "def vector_check(vector):\n    for i in vector:\n        if isinstance(i, int) is False:\n            return False\n        if i < 0:\n            return False\n    return True",
    "docstring": "Check input vector items type.\n\n    :param vector: input vector\n    :type vector : list\n    :return: bool"
  },
  {
    "code": "def alias_log_entry(self, log_entry_id, alias_id):\n        self._alias_id(primary_id=log_entry_id, equivalent_id=alias_id)",
    "docstring": "Adds an ``Id`` to a ``LogEntry`` for the purpose of creating compatibility.\n\n        The primary ``Id`` of the ``LogEntry`` is determined by the\n        provider. The new ``Id`` performs as an alias to the primary\n        ``Id``. If the alias is a pointer to another log entry, it is\n        reassigned to the given log entry ``Id``.\n\n        arg:    log_entry_id (osid.id.Id): the ``Id`` of a ``LogEntry``\n        arg:    alias_id (osid.id.Id): the alias ``Id``\n        raise:  AlreadyExists - ``alias_id`` is already assigned\n        raise:  NotFound - ``log_entry_id`` not found\n        raise:  NullArgument - ``log_entry_id`` or ``alias_id`` is\n                ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _get_metadata(self, key):\n        if not self.is_done():\n            raise ValueError(\"Cannot get metadata for a program that isn't completed.\")\n        return self._raw.get(\"metadata\", {}).get(key, None)",
    "docstring": "If the server returned a metadata dictionary, retrieve a particular key from it. If no\n        metadata exists, or the key does not exist, return None.\n\n        :param key: Metadata key, e.g., \"gate_depth\"\n        :return: The associated metadata.\n        :rtype: Optional[Any]"
  },
  {
    "code": "def list_assets(self):\n        response = self.requests_session.get(self._base_url).content\n        if not response:\n            return {}\n        try:\n            asset_list = json.loads(response)\n        except TypeError:\n            asset_list = None\n        except ValueError:\n            raise ValueError(response.decode('UTF-8'))\n        if not asset_list:\n            return []\n        if 'ids' in asset_list:\n            return asset_list['ids']\n        return []",
    "docstring": "List all the assets registered in the aquarius instance.\n\n        :return: List of DID string"
  },
  {
    "code": "def get_collection_sizes(obj, collections: Optional[Tuple]=None,\n                         get_only_non_empty=False):\n    from pympler import asizeof\n    collections = collections or (list, dict, set, deque, abc.Sized)\n    if not isinstance(collections, tuple):\n        collections = tuple(collections)\n    result = []\n    for attr_name in dir(obj):\n        attr = getattr(obj, attr_name)\n        if isinstance(attr, collections) and (\n                not get_only_non_empty or len(attr) > 0):\n            result.append(\n                (attr_name, len(attr), asizeof.asizeof(attr, detail=1)))\n    return result",
    "docstring": "Iterates over `collections` of the gives object and gives its byte size\n    and number of items in collection"
  },
  {
    "code": "def get_image(server_):\n    images = avail_images()\n    server_image = six.text_type(config.get_cloud_config_value(\n        'image', server_, __opts__, search_global=False\n    ))\n    for image in images:\n        if server_image in (images[image]['name'], images[image]['id']):\n            return images[image]['id']\n    raise SaltCloudNotFound(\n        'The specified image, \\'{0}\\', could not be found.'.format(server_image)\n    )",
    "docstring": "Return the image object to use."
  },
  {
    "code": "def QueryLayer(self, text=None, Geometry=None, inSR=None, \n                   spatialRel='esriSpatialRelIntersects', where=None,\n                   outFields=None, returnGeometry=None, outSR=None,\n                   objectIds=None, time=None, maxAllowableOffset=None,\n                   returnIdsOnly=None):\n        if not inSR:\n            if Geometry:\n                inSR = Geometry.spatialReference\n        out = self._get_subfolder(\"./query\", JsonResult, {\n                                               'text': text,\n                                               'geometry': geometry,\n                                               'inSR': inSR,\n                                               'spatialRel': spatialRel,\n                                               'where': where,\n                                               'outFields': outFields,\n                                               'returnGeometry': \n                                                    returnGeometry,\n                                               'outSR': outSR,\n                                               'objectIds': objectIds,\n                                               'time': \n                                                    utils.pythonvaluetotime(\n                                                        time),\n                                               'maxAllowableOffset':\n                                                    maxAllowableOffset,\n                                               'returnIdsOnly':\n                                                    returnIdsOnly\n                                                })\n        return gptypes.GPFeatureRecordSetLayer.fromJson(out._json_struct)",
    "docstring": "The query operation is performed on a layer resource. The result\n           of this operation is a resultset resource. This resource provides\n           information about query results including the values for the fields\n           requested by the user. If you request geometry information, the\n           geometry of each result is also returned in the resultset.\n\n           B{Spatial Relation Options:}\n             - esriSpatialRelIntersects\n             - esriSpatialRelContains\n             - esriSpatialRelCrosses\n             - esriSpatialRelEnvelopeIntersects\n             - esriSpatialRelIndexIntersects\n             - esriSpatialRelOverlaps\n             - esriSpatialRelTouches\n             - esriSpatialRelWithin"
  },
  {
    "code": "def fbp_op(ray_trafo, padding=True, filter_type='Ram-Lak',\n           frequency_scaling=1.0):\n    return ray_trafo.adjoint * fbp_filter_op(ray_trafo, padding, filter_type,\n                                             frequency_scaling)",
    "docstring": "Create filtered back-projection operator from a `RayTransform`.\n\n    The filtered back-projection is an approximate inverse to the ray\n    transform.\n\n    Parameters\n    ----------\n    ray_trafo : `RayTransform`\n        The ray transform (forward operator) whose approximate inverse should\n        be computed. Its geometry has to be any of the following\n\n        `Parallel2dGeometry` : Exact reconstruction\n\n        `Parallel3dAxisGeometry` : Exact reconstruction\n\n        `FanBeamGeometry` : Approximate reconstruction, correct in limit of fan\n        angle = 0.\n        Only flat detectors are supported (det_curvature_radius is None).\n\n        `ConeFlatGeometry`, pitch = 0 (circular) : Approximate reconstruction,\n        correct in the limit of fan angle = 0 and cone angle = 0.\n\n        `ConeFlatGeometry`, pitch > 0 (helical) : Very approximate unless a\n        `tam_danielson_window` is used. Accurate with the window.\n\n        Other geometries: Not supported\n\n    padding : bool, optional\n        If the data space should be zero padded. Without padding, the data may\n        be corrupted due to the circular convolution used. Using padding makes\n        the algorithm slower.\n    filter_type : optional\n        The type of filter to be used.\n        The predefined options are, in approximate order from most noise\n        senstive to least noise sensitive:\n        ``'Ram-Lak'``, ``'Shepp-Logan'``, ``'Cosine'``, ``'Hamming'`` and\n        ``'Hann'``.\n        A callable can also be provided. It must take an array of values in\n        [0, 1] and return the filter for these frequencies.\n    frequency_scaling : float, optional\n        Relative cutoff frequency for the filter.\n        The normalized frequencies are rescaled so that they fit into the range\n        [0, frequency_scaling]. Any frequency above ``frequency_scaling`` is\n        set to zero.\n\n    Returns\n    -------\n    fbp_op : `Operator`\n        Approximate inverse operator of ``ray_trafo``.\n\n    See Also\n    --------\n    tam_danielson_window : Windowing for helical data.\n    parker_weighting : Windowing for overcomplete fan-beam data."
  },
  {
    "code": "def _to_representation(self, instance):\n        if self.enable_optimization:\n            representation = self._faster_to_representation(instance)\n        else:\n            representation = super(\n                WithDynamicSerializerMixin,\n                self\n            ).to_representation(instance)\n        if settings.ENABLE_LINKS:\n            representation = merge_link_object(\n                self, representation, instance\n            )\n        if self.debug:\n            representation['_meta'] = {\n                'id': instance.pk,\n                'type': self.get_plural_name()\n            }\n        return tag_dict(\n            representation,\n            serializer=self,\n            instance=instance,\n            embed=self.embed\n        )",
    "docstring": "Uncached `to_representation`."
  },
  {
    "code": "def CreateWeightTableECMWF(in_ecmwf_nc,\n                           in_catchment_shapefile,\n                           river_id,\n                           in_connectivity_file,\n                           out_weight_table,\n                           area_id=None,\n                           file_geodatabase=None):\n    data_ecmwf_nc = Dataset(in_ecmwf_nc)\n    variables_list = data_ecmwf_nc.variables.keys()\n    in_ecmwf_lat_var = 'lat'\n    if 'latitude' in variables_list:\n        in_ecmwf_lat_var = 'latitude'\n    in_ecmwf_lon_var = 'lon'\n    if 'longitude' in variables_list:\n        in_ecmwf_lon_var = 'longitude'\n    ecmwf_lon = \\\n        (data_ecmwf_nc.variables[in_ecmwf_lon_var][:] + 180) % 360 - 180\n    ecmwf_lat = data_ecmwf_nc.variables[in_ecmwf_lat_var][:]\n    data_ecmwf_nc.close()\n    rtree_create_weight_table(ecmwf_lat, ecmwf_lon,\n                              in_catchment_shapefile, river_id,\n                              in_connectivity_file, out_weight_table,\n                              file_geodatabase, area_id)",
    "docstring": "Create Weight Table for ECMWF Grids\n\n    .. note:: The grids are in the RAPIDpy package under\n              the gis/lsm_grids folder.\n\n    Parameters\n    ----------\n    in_ecmwf_nc: str\n        Path to the ECMWF NetCDF grid.\n    in_catchment_shapefile: str\n        Path to the Catchment shapefile.\n    river_id: str\n        The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').\n    in_connectivity_file: str\n        The path to the RAPID connectivity file.\n    out_weight_table: str\n        The path to the output weight table file.\n    area_id: str, optional\n        The name of the field with the area of each catchment stored in meters\n        squared. Default is it calculate the area.\n    file_geodatabase: str, optional\n        Path to the file geodatabase. If you use this option, in_drainage_line\n        is the name of the stream network feature class.\n        (WARNING: Not always stable with GDAL.)\n\n\n    Example:\n\n    .. code:: python\n\n        from RAPIDpy.gis.weight import CreateWeightTableECMWF\n\n        CreateWeightTableECMWF(\n            in_ecmwf_nc='/path/to/runoff_ecmwf_grid.nc'\n            in_catchment_shapefile='/path/to/catchment.shp',\n            river_id='LINKNO',\n            in_connectivity_file='/path/to/rapid_connect.csv',\n            out_weight_table='/path/to/ecmwf_weight.csv',\n        )"
  },
  {
    "code": "def add(self, files):\n    if files.__class__.__name__ == 'str':\n      self._files.append(files)\n    else:\n      self._files.extend(files)",
    "docstring": "Adds files to check.\n\n    Args:\n      files: List of files to check."
  },
  {
    "code": "def ensure_sink(self):\n        topic_info = self.pubsub.ensure_topic()\n        scope, sink_path, sink_info = self.get_sink(topic_info)\n        client = self.session.client('logging', 'v2', '%s.sinks' % scope)\n        try:\n            sink = client.execute_command('get', {'sinkName': sink_path})\n        except HttpError as e:\n            if e.resp.status != 404:\n                raise\n            sink = client.execute_command('create', sink_info)\n        else:\n            delta = delta_resource(sink, sink_info['body'])\n            if delta:\n                sink_info['updateMask'] = ','.join(delta)\n                sink_info['sinkName'] = sink_path\n                sink_info.pop('parent')\n                sink = client.execute_command('update', sink_info)\n            else:\n                return sink_path\n        self.pubsub.ensure_iam(publisher=sink['writerIdentity'])\n        return sink_path",
    "docstring": "Ensure the log sink and its pub sub topic exist."
  },
  {
    "code": "def out(msg, error=False):\n        \" Send message to shell \"\n        pipe = stdout\n        if error:\n            pipe = stderr\n            msg = color_msg(msg, \"warning\")\n        pipe.write(\"%s\\n\" % msg)",
    "docstring": "Send message to shell"
  },
  {
    "code": "def readResources(self, elem):\n        try:\n            iterator = getattr(elem, 'iter')\n        except AttributeError:\n            iterator = getattr(elem, 'getiterator')\n        for include in iterator(\"include\"):\n            loc = include.attrib.get(\"location\")\n            if loc and loc.endswith('.qrc'):\n                mname = os.path.basename(loc[:-4] + self._resource_suffix)\n                if mname not in self.resources:\n                    self.resources.append(mname)",
    "docstring": "Read a \"resources\" tag and add the module to import to the parser's\n        list of them."
  },
  {
    "code": "def parse_unicode(self, i, wide=False):\n        text = self.get_wide_unicode(i) if wide else self.get_narrow_unicode(i)\n        value = int(text, 16)\n        single = self.get_single_stack()\n        if self.span_stack:\n            text = self.convert_case(chr(value), self.span_stack[-1])\n            value = ord(self.convert_case(text, single)) if single is not None else ord(text)\n        elif single:\n            value = ord(self.convert_case(chr(value), single))\n        if self.use_format and value in _CURLY_BRACKETS_ORD:\n            self.handle_format(chr(value), i)\n        elif value <= 0xFF:\n            self.result.append('\\\\%03o' % value)\n        else:\n            self.result.append(chr(value))",
    "docstring": "Parse Unicode."
  },
  {
    "code": "def load_segment(self, f, is_irom_segment=False):\n        file_offs = f.tell()\n        (offset, size) = struct.unpack('<II', f.read(8))\n        self.warn_if_unusual_segment(offset, size, is_irom_segment)\n        segment_data = f.read(size)\n        if len(segment_data) < size:\n            raise FatalError('End of file reading segment 0x%x, length %d (actual length %d)' % (offset, size, len(segment_data)))\n        segment = ImageSegment(offset, segment_data, file_offs)\n        self.segments.append(segment)\n        return segment",
    "docstring": "Load the next segment from the image file"
  },
  {
    "code": "def to_value(original_string, corenlp_value=None):\n    if isinstance(original_string, Value):\n        return original_string\n    if not corenlp_value:\n        corenlp_value = original_string\n    amount = NumberValue.parse(corenlp_value)\n    if amount is not None:\n        return NumberValue(amount, original_string)\n    ymd = DateValue.parse(corenlp_value)\n    if ymd is not None:\n        if ymd[1] == ymd[2] == -1:\n            return NumberValue(ymd[0], original_string)\n        else:\n            return DateValue(ymd[0], ymd[1], ymd[2], original_string)\n    return StringValue(original_string)",
    "docstring": "Convert the string to Value object.\n\n    Args:\n        original_string (basestring): Original string\n        corenlp_value (basestring): Optional value returned from CoreNLP\n    Returns:\n        Value"
  },
  {
    "code": "def mklink():\n\tfrom optparse import OptionParser\n\tparser = OptionParser(usage=\"usage: %prog [options] link target\")\n\tparser.add_option(\n\t\t'-d', '--directory',\n\t\thelp=\"Target is a directory (only necessary if not present)\",\n\t\taction=\"store_true\")\n\toptions, args = parser.parse_args()\n\ttry:\n\t\tlink, target = args\n\texcept ValueError:\n\t\tparser.error(\"incorrect number of arguments\")\n\tsymlink(target, link, options.directory)\n\tsys.stdout.write(\"Symbolic link created: %(link)s --> %(target)s\\n\" % vars())",
    "docstring": "Like cmd.exe's mklink except it will infer directory status of the\n\ttarget."
  },
  {
    "code": "def _build_fields(self, defaults, fields):\n        return dict(list(defaults.get('@fields', {}).items()) + list(fields.items()))",
    "docstring": "Return provided fields including any in defaults\n\n        >>> f = LogstashFormatter()\n        # Verify that ``fields`` is used\n        >>> f._build_fields({}, {'foo': 'one'}) == \\\n                {'foo': 'one'}\n        True\n        # Verify that ``@fields`` in ``defaults`` is used\n        >>> f._build_fields({'@fields': {'bar': 'two'}}, {'foo': 'one'}) == \\\n                {'foo': 'one', 'bar': 'two'}\n        True\n        # Verify that ``fields`` takes precedence\n        >>> f._build_fields({'@fields': {'foo': 'two'}}, {'foo': 'one'}) == \\\n                {'foo': 'one'}\n        True"
  },
  {
    "code": "def as_proximal_lang_operator(op, norm_bound=None):\n    def forward(inp, out):\n        out[:] = op(inp).asarray()\n    def adjoint(inp, out):\n        out[:] = op.adjoint(inp).asarray()\n    import proximal\n    return proximal.LinOpFactory(input_shape=op.domain.shape,\n                                 output_shape=op.range.shape,\n                                 forward=forward,\n                                 adjoint=adjoint,\n                                 norm_bound=norm_bound)",
    "docstring": "Wrap ``op`` as a ``proximal.BlackBox``.\n\n    This is intended to be used with the `ProxImaL language solvers.\n    <https://github.com/comp-imaging/proximal>`_\n\n    For documentation on the proximal language (ProxImaL) see [Hei+2016].\n\n    Parameters\n    ----------\n    op : `Operator`\n        Linear operator to be wrapped. Its domain and range must implement\n        ``shape``, and elements in these need to implement ``asarray``.\n    norm_bound : float, optional\n        An upper bound on the spectral norm of the operator. Note that this is\n        the norm as defined by ProxImaL, and hence use the unweighted spaces.\n\n    Returns\n    -------\n    ``proximal.BlackBox`` : proximal_lang_operator\n        The wrapped operator.\n\n    Notes\n    -----\n    If the data representation of ``op``'s domain and range is of type\n    `NumpyTensorSpace` this incurs no significant overhead. If the data\n    space is implemented with CUDA or some other non-local representation,\n    the overhead is significant.\n\n    References\n    ----------\n    [Hei+2016] Heide, F et al. *ProxImaL: Efficient Image Optimization using\n    Proximal Algorithms*. ACM Transactions on Graphics (TOG), 2016."
  },
  {
    "code": "def path_to_resource(project, path, type=None):\n    project_path = path_relative_to_project_root(project, path)\n    if project_path is None:\n        project_path = rope.base.project._realpath(path)\n        project = rope.base.project.get_no_project()\n    if type is None:\n        return project.get_resource(project_path)\n    if type == 'file':\n        return project.get_file(project_path)\n    if type == 'folder':\n        return project.get_folder(project_path)\n    return None",
    "docstring": "Get the resource at path\n\n    You only need to specify `type` if `path` does not exist.  It can\n    be either 'file' or 'folder'.  If the type is `None` it is assumed\n    that the resource already exists.\n\n    Note that this function uses `Project.get_resource()`,\n    `Project.get_file()`, and `Project.get_folder()` methods."
  },
  {
    "code": "def handle_table(self, table_dict):\n        table = table_dict['table']\n        tab = table_dict['tab']\n        tab.load_table_data()\n        table_name = table._meta.name\n        tab._tables[table_name]._meta.has_prev_data = self.has_prev_data(table)\n        tab._tables[table_name]._meta.has_more_data = self.has_more_data(table)\n        handled = tab._tables[table_name].maybe_handle()\n        return handled",
    "docstring": "Loads the table data based on a given table_dict and handles them.\n\n        For the given dict containing a ``DataTable`` and a ``TableTab``\n        instance, it loads the table data for that tab and calls the\n        table's :meth:`~horizon.tables.DataTable.maybe_handle` method.\n        The return value will be the result of ``maybe_handle``."
  },
  {
    "code": "def set_trunk_groups(self, vid, value=None, default=False, disable=False):\n        if default:\n            return self.configure_vlan(vid, 'default trunk group')\n        if disable:\n            return self.configure_vlan(vid, 'no trunk group')\n        current_value = self.get(vid)['trunk_groups']\n        failure = False\n        value = make_iterable(value)\n        for name in set(value).difference(current_value):\n            if not self.add_trunk_group(vid, name):\n                failure = True\n        for name in set(current_value).difference(value):\n            if not self.remove_trunk_group(vid, name):\n                failure = True\n        return not failure",
    "docstring": "Configures the list of trunk groups support on a vlan\n\n        This method handles configuring the vlan trunk group value to default\n        if the default flag is set to True.  If the default flag is set\n        to False, then this method will calculate the set of trunk\n        group names to be added and to be removed.\n\n        EosVersion:\n            4.13.7M\n\n        Args:\n            vid (str): The VLAN ID to configure\n            value (str): The list of trunk groups that should be configured\n                for this vlan id.\n            default (bool): Configures the trunk group value to default if\n                this value is true\n            disable (bool): Negates the trunk group value if set to true\n\n        Returns:\n            True if the operation was successful otherwise False"
  },
  {
    "code": "def _rank_results(results: List[Dict], method: SimAlgorithm) -> List[Dict]:\n        sorted_results = sorted(\n            results, reverse=True, key=lambda k: k[OwlSim2Api.method2key[method]]\n        )\n        if len(sorted_results) > 0:\n            rank = 1\n            previous_score = sorted_results[0][OwlSim2Api.method2key[method]]\n            for result in sorted_results:\n                if previous_score > result[OwlSim2Api.method2key[method]]:\n                    rank += 1\n                result['rank'] = rank\n                previous_score = result[OwlSim2Api.method2key[method]]\n        return sorted_results",
    "docstring": "Ranks results - for phenodigm results are ranks but ties need to accounted for\n                        for other methods, results need to be reranked\n\n        :param results: Results from search_by_attribute_set()['results'] or\n                                     compare_attribute_sets()['results']\n        :param method: sim method used to rank results\n        :return: Sorted results list"
  },
  {
    "code": "def get_data_files_tuple(*rel_path, **kwargs):\n    rel_path = os.path.join(*rel_path)\n    target_path = os.path.join(\"share\", *rel_path.split(os.sep)[1:])\n    if \"path_to_file\" in kwargs and kwargs[\"path_to_file\"]:\n        source_files = [rel_path]\n        target_path = os.path.dirname(target_path)\n    else:\n        source_files = [os.path.join(rel_path, filename) for filename in os.listdir(rel_path)]\n    return target_path, source_files",
    "docstring": "Return a tuple which can be used for setup.py's data_files\n\n    :param tuple path: List of path elements pointing to a file or a directory of files\n    :param dict kwargs: Set path_to_file to True is `path` points to a file\n    :return: tuple of install directory and list of source files\n    :rtype: tuple(str, [str])"
  },
  {
    "code": "def pre_dispatch(self, request, path_args):\n        secret_key = self.get_secret_key(request, path_args)\n        if not secret_key:\n            raise PermissionDenied('Signature not valid.')\n        try:\n            signing.verify_url_path(request.path, request.GET, secret_key)\n        except SigningError as ex:\n            raise PermissionDenied(str(ex))",
    "docstring": "Pre dispatch hook"
  },
  {
    "code": "def get_dir(self):\n        if \"-WD\" in sys.argv and self.FIRST_RUN:\n            ind = sys.argv.index('-WD')\n            self.WD = os.path.abspath(sys.argv[ind+1])\n            os.chdir(self.WD)\n            self.WD = os.getcwd()\n            self.dir_path.SetValue(self.WD)\n        else:\n            self.on_change_dir_button(None)\n        self.FIRST_RUN = False",
    "docstring": "Choose a working directory dialog.\n        Called by self.get_dm_and_wd."
  },
  {
    "code": "def put_records(self, records, partition_key=None):\n        for record in records:\n            self.put_record(record, partition_key)",
    "docstring": "Add a list of data records to the record queue in the proper format.\n        Convinience method that calls self.put_record for each element.\n\n        Parameters\n        ----------\n        records : list\n            Lists of records to send.\n        partition_key: str\n            Hash that determines which shard a given data record belongs to."
  },
  {
    "code": "def _line_start_indexes(self):\n        if self._cache.line_indexes is None:\n            line_lengths = map(len, self.lines)\n            indexes = [0]\n            append = indexes.append\n            pos = 0\n            for line_length in line_lengths:\n                pos += line_length + 1\n                append(pos)\n            if len(indexes) > 1:\n                indexes.pop()\n            self._cache.line_indexes = indexes\n        return self._cache.line_indexes",
    "docstring": "Array pointing to the start indexes of all the lines."
  },
  {
    "code": "def format_options(self, ctx, formatter):\n        super(Pyp2rpmCommand, self).format_options(ctx, formatter)\n        scl_opts = []\n        for param in self.get_params(ctx):\n            if isinstance(param, SclizeOption):\n                scl_opts.append(param.get_scl_help_record(ctx))\n        if scl_opts:\n            with formatter.section('SCL related options'):\n                formatter.write_dl(scl_opts)",
    "docstring": "Writes SCL related options into the formatter as a separate\n        group."
  },
  {
    "code": "async def next_done(self):\n        if not self._done and self._pending:\n            self._done_event.clear()\n            await self._done_event.wait()\n        if self._done:\n            return self._done.popleft()\n        return None",
    "docstring": "Returns the next completed task.  Returns None if no more tasks\n        remain. A TaskGroup may also be used as an asynchronous iterator."
  },
  {
    "code": "def to_pelias_dict(self):\n        vb = self.convert_srs(4326)\n        return {\n            'boundary.rect.min_lat': vb.bottom,\n            'boundary.rect.min_lon': vb.left,\n            'boundary.rect.max_lat': vb.top,\n            'boundary.rect.max_lon': vb.right\n        }",
    "docstring": "Convert Viewbox object to a string that can be used by Pelias\n        as a query parameter."
  },
  {
    "code": "def execute(self, input_data):\n        md5 = input_data['meta']['md5']\n        response = requests.get('http://www.virustotal.com/vtapi/v2/file/report', \n                                params={'apikey':self.apikey,'resource':md5, 'allinfo':1})\n        try:\n            vt_output = response.json()\n        except ValueError:\n            return {'vt_error': 'VirusTotal Query Error, no valid response... past per min quota?'}\n        output = {field:vt_output[field] for field in vt_output.keys() if field not in self.exclude}\n        not_found = False if output else True        \n        output['file_type'] = input_data['meta']['file_type']\n        if not_found:\n            output['not_found'] = True\n            return output\n        scan_results = collections.Counter()\n        for scan in vt_output['scans'].values():\n            if 'result' in scan:\n                if scan['result']:\n                    scan_results[scan['result']] += 1\n        output['scan_results'] = scan_results.most_common(5)\n        return output",
    "docstring": "Execute the VTQuery worker"
  },
  {
    "code": "def render(self):\n        release_notes = []\n        for parser in self.parsers:\n            parser_content = parser.render()\n            if parser_content is not None:\n                release_notes.append(parser_content)\n        return u\"\\r\\n\\r\\n\".join(release_notes)",
    "docstring": "Returns the rendered release notes from all parsers as a string"
  },
  {
    "code": "def create_base64encoded_randomness(num_bytes: int) -> str:\n    randbytes = os.urandom(num_bytes)\n    return base64.urlsafe_b64encode(randbytes).decode('ascii')",
    "docstring": "Create and return ``num_bytes`` of random data.\n\n    The result is encoded in a string with URL-safe ``base64`` encoding.\n\n    Used (for example) to generate session tokens.\n\n    Which generator to use? See\n    https://cryptography.io/en/latest/random-numbers/.\n\n    Do NOT use these methods:\n\n    .. code-block:: python\n\n        randbytes = M2Crypto.m2.rand_bytes(num_bytes) # NO!\n        randbytes = Crypto.Random.get_random_bytes(num_bytes) # NO!\n\n    Instead, do this:\n\n    .. code-block:: python\n\n        randbytes = os.urandom(num_bytes)  # YES"
  },
  {
    "code": "def open(filename, frame='unspecified'):\n        data = Image.load_data(filename)\n        if len(data.shape) > 2 and data.shape[2] > 1:\n            data = data[:, :, 0]\n        return BinaryImage(data, frame)",
    "docstring": "Creates a BinaryImage from a file.\n\n        Parameters\n        ----------\n        filename : :obj:`str`\n            The file to load the data from. Must be one of .png, .jpg,\n            .npy, or .npz.\n\n        frame : :obj:`str`\n            A string representing the frame of reference in which the new image\n            lies.\n\n        Returns\n        -------\n        :obj:`BinaryImage`\n            The new binary image."
  },
  {
    "code": "def writerow(self, row):\n        json_text = json.dumps(row)\n        if isinstance(json_text, bytes):\n            json_text = json_text.decode('utf-8')\n        self._out.write(json_text)\n        self._out.write(u'\\n')",
    "docstring": "Write a single row."
  },
  {
    "code": "def IsSymbolFileSane(self, position):\n    pos = [position[0], None, None]\n    self.EnsureGdbPosition(*pos)\n    try:\n      if GdbCache.DICT and GdbCache.TYPE and GdbCache.INTERP_HEAD:\n        tstate = GdbCache.INTERP_HEAD['tstate_head']\n        tstate['thread_id']\n        frame = tstate['frame']\n        frame_attrs = ['f_back',\n                       'f_locals',\n                       'f_localsplus',\n                       'f_globals',\n                       'f_builtins',\n                       'f_lineno',\n                       'f_lasti']\n        for attr_name in frame_attrs:\n          frame[attr_name]\n        code = frame['f_code']\n        code_attrs = ['co_name',\n                      'co_filename',\n                      'co_nlocals',\n                      'co_varnames',\n                      'co_lnotab',\n                      'co_firstlineno']\n        for attr_name in code_attrs:\n          code[attr_name]\n        return True\n    except gdb.error:\n      return False\n    return False",
    "docstring": "Performs basic sanity check by trying to look up a bunch of symbols."
  },
  {
    "code": "def Update(self,name):\n\t\tr = clc.v2.API.Call('PUT','antiAffinityPolicies/%s/%s' % (self.alias,self.id),{'name': name},session=self.session)\n\t\tself.name = name",
    "docstring": "Change the policy's name.\n\n\t\thttps://t3n.zendesk.com/entries/45066480-Update-Anti-Affinity-Policy\n\n\t\t*TODO* - currently returning 500 error"
  },
  {
    "code": "def slice(self, start=None, stop=None, step=None):\n        check_type(start, int)\n        check_type(stop, int)\n        check_type(step, int)\n        if step is not None and step < 0:\n            raise ValueError('Only positive steps are currently supported')\n        return _series_str_result(self, weld_str_slice, start=start, stop=stop, step=step)",
    "docstring": "Slice substrings from each element.\n\n        Note that negative step is currently not supported.\n\n        Parameters\n        ----------\n        start : int\n        stop : int\n        step : int\n\n        Returns\n        -------\n        Series"
  },
  {
    "code": "def filter_ints_based_on_vlan(interfaces, vlan, count=1):\n    filtered_interfaces = []\n    for interface in interfaces:\n        if interface.obj_type() == 'interface':\n            ixn_vlan = interface.get_object_by_type('vlan')\n            vlanEnable = is_true(ixn_vlan.get_attribute('vlanEnable'))\n            vlanCount = int(ixn_vlan.get_attribute('vlanCount'))\n        elif interface.obj_type() == 'range':\n            ixn_vlan = interface.get_object_by_type('vlanRange')\n            vlanEnable = is_true(ixn_vlan.get_attribute('enabled'))\n            vlanCount = len(ixn_vlan.get_objects_by_type('vlanIdInfo'))\n        else:\n            ixn_vlan = interface.get_object_by_type('ethernet')\n            vlanEnable = is_true(ixn_vlan.get_attribute('useVlans'))\n            vlanCount = int(ixn_vlan.get_attribute('vlanCount'))\n        if not (vlanEnable ^ vlan) and vlanCount == count:\n            filtered_interfaces.append(interface)\n    return filtered_interfaces",
    "docstring": "Filter list of interfaces based on VLAN presence or absence criteria.\n\n    :param interfaces: list of interfaces to filter.\n    :param vlan: boolean indicating whether to filter interfaces with or without VLAN.\n    :param vlan: number of expected VLANs (note that when vlanEnable == False, vlanCount == 1)\n    :return: interfaces with VLAN(s) if vlan == True and vlanCount == count else interfaces without\n        VLAN(s).\n\n    :todo: add vlanEnable and vlanCount to interface/range/deviceGroup classes."
  },
  {
    "code": "def media(request, path, hproPk=None):\n    if not settings.PIAPI_STANDALONE:\n        (plugIt, baseURI, _) = getPlugItObject(hproPk)\n    else:\n        global plugIt, baseURI\n    try:\n        (media, contentType, cache_control) = plugIt.getMedia(path)\n    except Exception as e:\n        report_backend_error(request, e, 'meta', hproPk)\n        return gen500(request, baseURI)\n    if not media:\n        raise Http404\n    response = HttpResponse(media)\n    response['Content-Type'] = contentType\n    response['Content-Length'] = len(media)\n    if cache_control:\n        response['Cache-Control'] = cache_control\n    return response",
    "docstring": "Ask the server for a media and return it to the client browser. Forward cache headers"
  },
  {
    "code": "def chat_delete(self, room_id, msg_id, **kwargs):\n        return self.__call_api_post('chat.delete', roomId=room_id, msgId=msg_id, kwargs=kwargs)",
    "docstring": "Deletes a chat message."
  },
  {
    "code": "def _open_list(self, list_type):\n        if list_type in LIST_TYPES.keys():\n            tag = LIST_TYPES[list_type]\n        else:\n            raise Exception('CustomSlackdownHTMLParser:_open_list: Not a valid list type.')\n        html = '<{t} class=\"list-container-{c}\">'.format(\n            t=tag,\n            c=list_type\n        )\n        self.cleaned_html += html\n        self.current_parent_element['tag'] = LIST_TYPES[list_type]\n        self.current_parent_element['attrs'] = {'class': list_type}",
    "docstring": "Add an open list tag corresponding to the specification in the\n        parser's LIST_TYPES."
  },
  {
    "code": "def get_zones(region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    return [z.name for z in conn.get_all_zones()]",
    "docstring": "Get a list of AZs for the configured region.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_ec2.get_zones"
  },
  {
    "code": "def cli(env, sortby, cpu, columns, datacenter, name, memory, disk, tag):\n    mgr = SoftLayer.DedicatedHostManager(env.client)\n    hosts = mgr.list_instances(cpus=cpu,\n                               datacenter=datacenter,\n                               hostname=name,\n                               memory=memory,\n                               disk=disk,\n                               tags=tag,\n                               mask=columns.mask())\n    table = formatting.Table(columns.columns)\n    table.sortby = sortby\n    for host in hosts:\n        table.add_row([value or formatting.blank()\n                       for value in columns.row(host)])\n    env.fout(table)",
    "docstring": "List dedicated host."
  },
  {
    "code": "def dense_to_deeper_block(dense_layer, weighted=True):\n    units = dense_layer.units\n    weight = np.eye(units)\n    bias = np.zeros(units)\n    new_dense_layer = StubDense(units, units)\n    if weighted:\n        new_dense_layer.set_weights(\n            (add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1])))\n        )\n    return [StubReLU(), new_dense_layer]",
    "docstring": "deeper dense layer."
  },
  {
    "code": "def joint(node):\n  node, _, _ = _fix(node)\n  body = node.body[0].body[:-1] + node.body[1].body\n  func = gast.Module(body=[gast.FunctionDef(\n      name=node.body[0].name, args=node.body[1].args, body=body,\n      decorator_list=[], returns=None)])\n  anno.clearanno(func)\n  return func",
    "docstring": "Merge the bodies of primal and adjoint into a single function.\n\n  Args:\n    node: A module with the primal and adjoint function definitions as returned\n        by `reverse_ad`.\n\n  Returns:\n    func: A `Module` node with a single function definition containing the\n        combined primal and adjoint."
  },
  {
    "code": "def _get_bases(type_):\n        try:\n            class _(type_):\n            BaseClass = type_\n        except TypeError:\n            BaseClass = object\n        class MetaClass(_ValidationMeta, BaseClass.__class__):\n        return BaseClass, MetaClass",
    "docstring": "Get the base and meta classes to use in creating a subclass.\n\n        Args:\n            type_: The type to subclass.\n\n        Returns:\n            A tuple containing two values: a base class, and a metaclass."
  },
  {
    "code": "def monkhorst_automatic(cls, structure, ngkpt,\n                            use_symmetries=True, use_time_reversal=True, chksymbreak=None, comment=None):\n        sg = SpacegroupAnalyzer(structure)\n        nshiftk = 1\n        shiftk = 3*(0.5,)\n        return cls.monkhorst(\n            ngkpt, shiftk=shiftk, use_symmetries=use_symmetries, use_time_reversal=use_time_reversal,\n            chksymbreak=chksymbreak, comment=comment if comment else \"Automatic Monkhorst-Pack scheme\")",
    "docstring": "Convenient static constructor for an automatic Monkhorst-Pack mesh.\n\n        Args:\n            structure: :class:`Structure` object.\n            ngkpt: Subdivisions N_1, N_2 and N_3 along reciprocal lattice vectors.\n            use_symmetries: Use spatial symmetries to reduce the number of k-points.\n            use_time_reversal: Use time-reversal symmetry to reduce the number of k-points.\n\n        Returns:\n            :class:`KSampling` object."
  },
  {
    "code": "def get_api_v1_info(api_prefix):\n    websocket_root = base_ws_uri() + EVENTS_ENDPOINT\n    docs_url = [\n        'https://docs.bigchaindb.com/projects/server/en/v',\n        version.__version__,\n        '/http-client-server-api.html',\n    ]\n    return {\n        'docs': ''.join(docs_url),\n        'transactions': '{}transactions/'.format(api_prefix),\n        'blocks': '{}blocks/'.format(api_prefix),\n        'assets': '{}assets/'.format(api_prefix),\n        'outputs': '{}outputs/'.format(api_prefix),\n        'streams': websocket_root,\n        'metadata': '{}metadata/'.format(api_prefix),\n        'validators': '{}validators'.format(api_prefix),\n    }",
    "docstring": "Return a dict with all the information specific for the v1 of the\n    api."
  },
  {
    "code": "def get_mean(self, grp=None):\n        self.init()\n        if len(self.weights) == 1:\n            pmap = self.get(0, grp)\n            for sid, pcurve in pmap.items():\n                array = numpy.zeros(pcurve.array.shape[:-1] + (2,))\n                array[:, 0] = pcurve.array[:, 0]\n                pcurve.array = array\n            return pmap\n        else:\n            dic = ({g: self.dstore['poes/' + g] for g in self.dstore['poes']}\n                   if grp is None else {grp: self.dstore['poes/' + grp]})\n            pmaps = self.rlzs_assoc.combine_pmaps(dic)\n            return stats.compute_pmap_stats(\n                pmaps, [stats.mean_curve, stats.std_curve],\n                self.weights, self.imtls)",
    "docstring": "Compute the mean curve as a ProbabilityMap\n\n        :param grp:\n            if not None must be a string of the form \"grp-XX\"; in that case\n            returns the mean considering only the contribution for group XX"
  },
  {
    "code": "def change_password(self, user, password):\n        if not self.__contains__(user):\n            raise UserNotExists\n        self.new_users[user] = self._encrypt_password(password) + \"\\n\"",
    "docstring": "Changes user password"
  },
  {
    "code": "def _deserialize(self):\n        if not self._responses or not self._responses[-1].body:\n            return None\n        if 'Content-Type' not in self._responses[-1].headers:\n            return self._responses[-1].body\n        try:\n            content_type = algorithms.select_content_type(\n                [headers.parse_content_type(\n                    self._responses[-1].headers['Content-Type'])],\n                AVAILABLE_CONTENT_TYPES)\n        except errors.NoMatch:\n            return self._responses[-1].body\n        if content_type[0] == CONTENT_TYPE_JSON:\n            return self._decode(\n                self._json.loads(self._decode(self._responses[-1].body)))\n        elif content_type[0] == CONTENT_TYPE_MSGPACK:\n            return self._decode(\n                self._msgpack.unpackb(self._responses[-1].body))",
    "docstring": "Try and deserialize a response body based upon the specified\n        content type.\n\n        :rtype: mixed"
  },
  {
    "code": "def _op_msg_uncompressed(flags, command, identifier, docs, check_keys, opts):\n    data, total_size, max_bson_size = _op_msg_no_header(\n        flags, command, identifier, docs, check_keys, opts)\n    request_id, op_message = __pack_message(2013, data)\n    return request_id, op_message, total_size, max_bson_size",
    "docstring": "Internal compressed OP_MSG message helper."
  },
  {
    "code": "def _format_python2_or_3(self):\n        pb_files = set()\n        with open(self.source, 'r', buffering=1) as csvfile:\n            reader = csv.reader(csvfile)\n            for row in reader:\n                _, _, proto = row\n                pb_files.add('riak/pb/{0}_pb2.py'.format(proto))\n        for im in sorted(pb_files):\n            with open(im, 'r', buffering=1) as pbfile:\n                contents = 'from six import *\\n' + pbfile.read()\n                contents = re.sub(r'riak_pb2',\n                                  r'riak.pb.riak_pb2',\n                                  contents)\n            contents = re.sub(\n                r'class\\s+(\\S+)\\((\\S+)\\):\\s*\\n'\n                '\\s+__metaclass__\\s+=\\s+(\\S+)\\s*\\n',\n                r'@add_metaclass(\\3)\\nclass \\1(\\2):\\n', contents)\n            with open(im, 'w', buffering=1) as pbfile:\n                pbfile.write(contents)",
    "docstring": "Change the PB files to use full pathnames for Python 3.x\n        and modify the metaclasses to be version agnostic"
  },
  {
    "code": "def destination(value):\n    def decorator(wrapped):\n        data = get_decorator_data(_get_base(wrapped), set_default=True)\n        data.override['destination'] = value\n        return wrapped\n    return decorator",
    "docstring": "Modifier decorator to update a patch's destination.\n\n    This only modifies the behaviour of the :func:`create_patches` function\n    and the :func:`patches` decorator, given that their parameter\n    ``use_decorators`` is set to ``True``.\n\n    Parameters\n    ----------\n    value : object\n        Patch destination.\n\n    Returns\n    -------\n    object\n        The decorated object."
  },
  {
    "code": "def validate(self, value):\n        try:\n            int_value = int(value)\n            self._choice = int_value\n            return True\n        except ValueError:\n            self.error_message = '%s is not a valid integer.' % value\n            return False",
    "docstring": "Return True if the choice is an integer; False otherwise.\n\n        If the value was cast successfully to an int, set the choice that will\n        make its way into the answers dict to the cast int value, not the\n        string representation."
  },
  {
    "code": "def dissociate(self, id_filter, id_eq_type):\n        if not is_valid_int_param(id_filter):\n            raise InvalidParameterError(\n                u'The identifier of Filter is invalid or was not informed.')\n        if not is_valid_int_param(id_eq_type):\n            raise InvalidParameterError(\n                u'The identifier of TipoEquipamento is invalid or was not informed.')\n        url = 'filter/' + \\\n            str(id_filter) + '/dissociate/' + str(id_eq_type) + '/'\n        code, xml = self.submit(None, 'PUT', url)\n        return self.response(code, xml)",
    "docstring": "Removes relationship between Filter and TipoEquipamento.\n\n        :param id_filter: Identifier of Filter. Integer value and greater than zero.\n        :param id_eq_type: Identifier of TipoEquipamento. Integer value, greater than zero.\n\n        :return: None\n\n        :raise FilterNotFoundError: Filter not registered.\n        :raise TipoEquipamentoNotFoundError: TipoEquipamento not registered.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def get_local_annotations(\n            cls, target, exclude=None, ctx=None, select=lambda *p: True\n    ):\n        result = []\n        exclude = () if exclude is None else exclude\n        try:\n            local_annotations = get_local_property(\n                target, Annotation.__ANNOTATIONS_KEY__, result, ctx=ctx\n            )\n            if not local_annotations:\n                if ismethod(target):\n                    func = get_method_function(target)\n                    local_annotations = get_local_property(\n                        func, Annotation.__ANNOTATIONS_KEY__,\n                        result, ctx=ctx\n                    )\n                    if not local_annotations:\n                        local_annotations = get_local_property(\n                            func, Annotation.__ANNOTATIONS_KEY__,\n                            result\n                        )\n                elif isfunction(target):\n                    local_annotations = get_local_property(\n                        target, Annotation.__ANNOTATIONS_KEY__,\n                        result\n                    )\n        except TypeError:\n            raise TypeError('target {0} must be hashable'.format(target))\n        for local_annotation in local_annotations:\n            inherited = isinstance(local_annotation, cls)\n            not_excluded = not isinstance(local_annotation, exclude)\n            selected = select(target, ctx, local_annotation)\n            if inherited and not_excluded and selected:\n                result.append(local_annotation)\n        return result",
    "docstring": "Get a list of local target annotations in the order of their\n            definition.\n\n        :param type cls: type of annotation to get from target.\n        :param target: target from where get annotations.\n        :param tuple/type exclude: annotation types to exclude from selection.\n        :param ctx: target ctx.\n        :param select: selection function which takes in parameters a target,\n            a ctx and an annotation and returns True if the annotation has to\n            be selected. True by default.\n\n        :return: target local annotations.\n        :rtype: list"
  },
  {
    "code": "def validate_set_ops(df, other):\n    if df.columns.values.tolist() != other.columns.values.tolist():\n        not_in_df = [col for col in other.columns if col not in df.columns]\n        not_in_other = [col for col in df.columns if col not in other.columns]\n        error_string = 'Error: not compatible.'\n        if len(not_in_df):\n            error_string += ' Cols in y but not x: ' + str(not_in_df) + '.'\n        if len(not_in_other):\n            error_string += ' Cols in x but not y: ' + str(not_in_other) + '.'\n        raise ValueError(error_string)\n    if len(df.index.names) != len(other.index.names):\n        raise ValueError('Index dimension mismatch')\n    if df.index.names != other.index.names:\n        raise ValueError('Index mismatch')\n    else:\n        return",
    "docstring": "Helper function to ensure that DataFrames are valid for set operations.\n    Columns must be the same name in the same order, and indices must be of the\n    same dimension with the same names."
  },
  {
    "code": "def __read_device(self):\n        state = XinputState()\n        res = self.manager.xinput.XInputGetState(\n            self.__device_number, ctypes.byref(state))\n        if res == XINPUT_ERROR_SUCCESS:\n            return state\n        if res != XINPUT_ERROR_DEVICE_NOT_CONNECTED:\n            raise RuntimeError(\n                \"Unknown error %d attempting to get state of device %d\" % (\n                    res, self.__device_number))\n        return None",
    "docstring": "Read the state of the gamepad."
  },
  {
    "code": "def _maybe_apply_history(self, method):\n        if self.is_historic():\n            for kwargs, result_callback in self._call_history:\n                res = self._hookexec(self, [method], kwargs)\n                if res and result_callback is not None:\n                    result_callback(res[0])",
    "docstring": "Apply call history to a new hookimpl if it is marked as historic."
  },
  {
    "code": "def import_(self, data):\n        return self.__import(json.loads(data, **self.kwargs))",
    "docstring": "Read JSON from `data`."
  },
  {
    "code": "def drop_privileges ():\n    if os.name != 'posix':\n        return\n    if os.geteuid() == 0:\n        log.warn(LOG_CHECK, _(\"Running as root user; \"\n                       \"dropping privileges by changing user to nobody.\"))\n        import pwd\n        os.seteuid(pwd.getpwnam('nobody')[3])",
    "docstring": "Make sure to drop root privileges on POSIX systems."
  },
  {
    "code": "def get_rectangle(self):\n        rec = [self.pos[0], self.pos[1]]*2\n        for age in self.nodes:\n            for node in age:\n                for i in range(2):\n                    if rec[0+i] > node.pos[i]:\n                        rec[0+i] = node.pos[i]\n                    elif rec[2+i] < node.pos[i]:\n                        rec[2+i] = node.pos[i]\n        return tuple(rec)",
    "docstring": "Gets the coordinates of the rectangle, in which the tree can be put.\n\n        Returns:\n            tupel: (x1, y1, x2, y2)"
  },
  {
    "code": "def load(self,path):\n        try:\n            if sys.platform == 'darwin':\n                return ctypes.CDLL(path, ctypes.RTLD_GLOBAL)\n            else:\n                return ctypes.cdll.LoadLibrary(path)\n        except OSError,e:\n            raise ImportError(e)",
    "docstring": "Given a path to a library, load it."
  },
  {
    "code": "def _injectWorkerFiles(self, node, botoExists):\n        node.waitForNode('toil_worker', keyName=self._keyName)\n        node.copySshKeys(self._keyName)\n        node.injectFile(self._credentialsPath, GoogleJobStore.nodeServiceAccountJson, 'toil_worker')\n        if self._sseKey:\n            node.injectFile(self._sseKey, self._sseKey, 'toil_worker')\n        if botoExists:\n            node.injectFile(self._botoPath, self.NODE_BOTO_PATH, 'toil_worker')",
    "docstring": "Set up the credentials on the worker."
  },
  {
    "code": "def default_sources(**kwargs):\n    S = OrderedDict()\n    total = 0\n    invalid_types = [t for t in kwargs.keys() if t not in SOURCE_VAR_TYPES]\n    for t in invalid_types:\n        montblanc.log.warning('Source type %s is not yet '\n            'implemented in montblanc. '\n            'Valid source types are %s' % (t, SOURCE_VAR_TYPES.keys()))\n    for k, v in SOURCE_VAR_TYPES.iteritems():\n        value = kwargs.get(k, 0)\n        try:\n            value = int(value)\n        except ValueError:\n            raise TypeError(('Supplied value %s '\n                'for source %s cannot be '\n                'converted to an integer') % \\\n                    (value, k))\n        total += value\n        S[k] = value\n    if total == 0:\n        S[POINT_TYPE] = 1\n    return S",
    "docstring": "Returns a dictionary mapping source types\n    to number of sources. If the number of sources\n    for the source type is supplied in the kwargs\n    these will be placed in the dictionary.\n\n    e.g. if we have 'point', 'gaussian' and 'sersic'\n    source types, then\n\n    default_sources(point=10, gaussian=20)\n\n    will return an OrderedDict {'point': 10, 'gaussian': 20, 'sersic': 0}"
  },
  {
    "code": "def user_exists(name, user=None, password=None, host=None, port=None,\n                database='admin', authdb=None):\n    users = user_list(user, password, host, port, database, authdb)\n    if isinstance(users, six.string_types):\n        return 'Failed to connect to mongo database'\n    for user in users:\n        if name == dict(user).get('user'):\n            return True\n    return False",
    "docstring": "Checks if a user exists in MongoDB\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' mongodb.user_exists <name> <user> <password> <host> <port> <database>"
  },
  {
    "code": "def dump_stack_peek(data, separator = ' ', width = 16, arch = None):\n        if data is None:\n            return ''\n        if arch is None:\n            arch = win32.arch\n        pointers = compat.keys(data)\n        pointers.sort()\n        result = ''\n        if pointers:\n            if arch == win32.ARCH_I386:\n                spreg = 'esp'\n            elif arch == win32.ARCH_AMD64:\n                spreg = 'rsp'\n            else:\n                spreg = 'STACK'\n            tag_fmt = '[%s+0x%%.%dx]' % (spreg, len( '%x' % pointers[-1] ) )\n            for offset in pointers:\n                dumped  = HexDump.hexline(data[offset], separator, width)\n                tag     = tag_fmt % offset\n                result += '%s -> %s\\n' % (tag, dumped)\n        return result",
    "docstring": "Dump data from pointers guessed within the given stack dump.\n\n        @type  data: str\n        @param data: Dictionary mapping stack offsets to the data they point to.\n\n        @type  separator: str\n        @param separator:\n            Separator between the hexadecimal representation of each character.\n\n        @type  width: int\n        @param width:\n            (Optional) Maximum number of characters to convert per text line.\n            This value is also used for padding.\n\n        @type  arch: str\n        @param arch: Architecture of the machine whose registers were dumped.\n            Defaults to the current architecture.\n\n        @rtype:  str\n        @return: Text suitable for logging."
  },
  {
    "code": "def cmp(self,range2,overlap_size=0):\n    if self.overlaps(range2,padding=overlap_size): return 0\n    if self.chr < range2.chr: return -1\n    elif self.chr > range2.chr: return 1\n    elif self.end < range2.start: return -1\n    elif self.start > range2.end: return 1\n    sys.stderr.write(\"ERROR: cmp function unexpcted state\\n\")\n    sys.exit()\n    return 0",
    "docstring": "the comparitor for ranges\n\n     * return 1 if greater than range2\n     * return -1 if less than range2\n     * return 0 if overlapped\n\n    :param range2:\n    :param overlap_size: allow some padding for an 'equal' comparison (default 0)\n    :type range2: GenomicRange\n    :type overlap_size: int"
  },
  {
    "code": "def applyns(self, ns):\n        if ns is None:\n            return\n        if not isinstance(ns, (list, tuple)):\n            raise Exception(\"namespace must be a list or a tuple\")\n        if ns[0] is None:\n            self.expns = ns[1]\n        else:\n            self.prefix = ns[0]\n            self.nsprefixes[ns[0]] = ns[1]",
    "docstring": "Apply the namespace to this node.\n\n        If the prefix is I{None} then this element's explicit namespace\n        I{expns} is set to the URI defined by I{ns}. Otherwise, the I{ns} is\n        simply mapped.\n\n        @param ns: A namespace.\n        @type ns: (I{prefix}, I{URI})"
  },
  {
    "code": "def Any(*validators):\n    @wraps(Any)\n    def built(value):\n        error = None\n        for validator in validators:\n            try:\n                return validator(value)\n            except Error as e:\n                error = e\n        raise error\n    return built",
    "docstring": "Combines all the given validator callables into one, running the given\n    value through them in sequence until a valid result is given."
  },
  {
    "code": "def row_sparse_data(self, row_id):\n        if self._stype != 'row_sparse':\n            raise RuntimeError(\"Cannot return a copy of Parameter %s via row_sparse_data() \" \\\n                               \"because its storage type is %s. Please use data() instead.\" \\\n                               %(self.name, self._stype))\n        return self._get_row_sparse(self._data, row_id.context, row_id)",
    "docstring": "Returns a copy of the 'row_sparse' parameter on the same context as row_id's.\n        The copy only retains rows whose ids occur in provided row ids.\n        The parameter must have been initialized on this context before.\n\n        Parameters\n        ----------\n        row_id: NDArray\n            Row ids to retain for the 'row_sparse' parameter.\n\n        Returns\n        -------\n        NDArray on row_id's context"
  },
  {
    "code": "def validate_get_dbs(connection):\n    remote_dbs = set(rethinkdb.db_list().run(connection))\n    assert remote_dbs\n    return remote_dbs",
    "docstring": "validates the connection object is capable of read access to rethink\n\n    should be at least one test database by default\n\n    :param connection: <rethinkdb.net.DefaultConnection>\n    :return: <set> list of databases\n    :raises: ReqlDriverError AssertionError"
  },
  {
    "code": "def bonded(self, n1, n2, distance):\n        if distance > self.max_length * self.bond_tolerance:\n            return None\n        deviation = 0.0\n        pair = frozenset([n1, n2])\n        result = None\n        for bond_type in bond_types:\n            bond_length = self.lengths[bond_type].get(pair)\n            if (bond_length is not None) and \\\n               (distance < bond_length * self.bond_tolerance):\n                if result is None:\n                    result = bond_type\n                    deviation = abs(bond_length - distance)\n                else:\n                    new_deviation = abs(bond_length - distance)\n                    if deviation > new_deviation:\n                        result = bond_type\n                        deviation = new_deviation\n        return result",
    "docstring": "Return the estimated bond type\n\n           Arguments:\n            | ``n1``  --  the atom number of the first atom in the bond\n            | ``n2``  --  the atom number of the second atom the bond\n            | ``distance``  --  the distance between the two atoms\n\n           This method checks whether for the given pair of atom numbers, the\n           given distance corresponds to a certain bond length. The best\n           matching bond type will be returned. If the distance is a factor\n           ``self.bond_tolerance`` larger than a tabulated distance, the\n           algorithm will not relate them."
  },
  {
    "code": "def _get_go2nthdridx(self, gos_all):\n        go2nthdridx = {}\n        obj = GrouperInit.NtMaker(self)\n        for goid in gos_all:\n            go2nthdridx[goid] = obj.get_nt(goid)\n        return go2nthdridx",
    "docstring": "Get GO IDs header index for each user GO ID and corresponding parent GO IDs."
  },
  {
    "code": "def _request(self):\n        caller_frame = inspect.getouterframes(inspect.currentframe())[1]\n        args, _, _, values = inspect.getargvalues(caller_frame[0])\n        caller_name = caller_frame[3]\n        kwargs = {arg: values[arg] for arg in args if arg != 'self'}\n        func = reduce(\n            lambda resource, name: resource.__getattr__(name),\n            self.mappings[caller_name].split('.'), self)\n        return func(**kwargs)",
    "docstring": "retrieve the caller frame, extract the parameters from\n        the caller function, find the matching function,\n        and fire the request"
  },
  {
    "code": "def get_all_completed_tasks(self, api_token, **kwargs):\n        params = {\n            'token': api_token\n        }\n        return self._get('get_all_completed_items', params, **kwargs)",
    "docstring": "Return a list of a user's completed tasks.\n\n        .. warning:: Requires Todoist premium.\n\n        :param api_token: The user's login api_token.\n        :type api_token: str\n        :param project_id: Filter the tasks by project.\n        :type project_id: str\n        :param limit: The maximum number of tasks to return\n            (default ``30``, max ``50``).\n        :type limit: int\n        :param offset: Used for pagination if there are more tasks than limit.\n        :type offset: int\n        :param from_date: Return tasks with a completion date on or older than\n            from_date. Formatted as ``2007-4-29T10:13``.\n        :type from_date: str\n        :param to: Return tasks with a completion date on or less than\n            to_date. Formatted as ``2007-4-29T10:13``.\n        :type from_date: str\n        :return: The HTTP response to the request.\n        :rtype: :class:`requests.Response`\n\n        >>> from pytodoist.api import TodoistAPI\n        >>> api = TodoistAPI()\n        >>> response = api.login('john.doe@gmail.com', 'password')\n        >>> user_info = response.json()\n        >>> user_api_token = user_info['api_token']\n        >>> response = api.get_all_completed_tasks(user_api_token)\n        >>> completed_tasks = response.json()"
  },
  {
    "code": "def change_view(self, change_in_depth):\r\n        self.current_view_depth += change_in_depth\r\n        if self.current_view_depth < 0:\r\n            self.current_view_depth = 0\r\n        self.collapseAll()\r\n        if self.current_view_depth > 0:\r\n            for item in self.get_items(maxlevel=self.current_view_depth-1):\r\n                item.setExpanded(True)",
    "docstring": "Change the view depth by expand or collapsing all same-level nodes"
  },
  {
    "code": "def compose_tree_path(tree, issn=False):\n    if issn:\n        return join(\n            \"/\",\n            ISSN_DOWNLOAD_KEY,\n            basename(tree.issn)\n        )\n    return join(\n        \"/\",\n        PATH_DOWNLOAD_KEY,\n        quote_plus(tree.path).replace(\"%2F\", \"/\"),\n    )",
    "docstring": "Compose absolute path for given `tree`.\n\n    Args:\n        pub (obj): :class:`.Tree` instance.\n        issn (bool, default False): Compose URL using ISSN.\n\n    Returns:\n        str: Absolute path of the tree, without server's address and protocol."
  },
  {
    "code": "def start_http_server(self, port, args):\n        LOGGER.info(\"Starting Tornado v%s HTTPServer on port %i Args: %r\",\n                    tornado_version, port, args)\n        http_server = httpserver.HTTPServer(self.app, **args)\n        http_server.bind(port, family=socket.AF_INET)\n        http_server.start(1)\n        return http_server",
    "docstring": "Start the HTTPServer\n\n        :param int port: The port to run the HTTPServer on\n        :param dict args: Dictionary of arguments for HTTPServer\n        :rtype: tornado.httpserver.HTTPServer"
  },
  {
    "code": "def file_length(in_file):\n    fid = open(in_file)\n    data = fid.readlines()\n    fid.close()\n    return len(data)",
    "docstring": "Function to return the length of a file."
  },
  {
    "code": "def widget_from_tuple(o):\n        if _matches(o, (Real, Real)):\n            min, max, value = _get_min_max_value(o[0], o[1])\n            if all(isinstance(_, Integral) for _ in o):\n                cls = IntSlider\n            else:\n                cls = FloatSlider\n            return cls(value=value, min=min, max=max)\n        elif _matches(o, (Real, Real, Real)):\n            step = o[2]\n            if step <= 0:\n                raise ValueError(\"step must be >= 0, not %r\" % step)\n            min, max, value = _get_min_max_value(o[0], o[1], step=step)\n            if all(isinstance(_, Integral) for _ in o):\n                cls = IntSlider\n            else:\n                cls = FloatSlider\n            return cls(value=value, min=min, max=max, step=step)",
    "docstring": "Make widgets from a tuple abbreviation."
  },
  {
    "code": "def parse_xhtml_reaction_notes(entry):\n    properties = {}\n    if entry.xml_notes is not None:\n        cobra_notes = dict(parse_xhtml_notes(entry))\n        if 'subsystem' in cobra_notes:\n            properties['subsystem'] = cobra_notes['subsystem']\n        if 'gene_association' in cobra_notes:\n            properties['genes'] = cobra_notes['gene_association']\n        if 'ec_number' in cobra_notes:\n            properties['ec'] = cobra_notes['ec_number']\n        if 'authors' in cobra_notes:\n            properties['authors'] = [\n                a.strip() for a in cobra_notes['authors'].split(';')]\n        if 'confidence' in cobra_notes:\n            try:\n                value = int(cobra_notes['confidence'])\n            except ValueError:\n                logger.warning(\n                    'Unable to parse confidence level for {} as an'\n                    ' integer: {}'.format(\n                        entry.id, cobra_notes['confidence']))\n                value = cobra_notes['confidence']\n            properties['confidence'] = value\n    return properties",
    "docstring": "Return reaction properties defined in the XHTML notes.\n\n    Older SBML models often define additional properties in the XHTML notes\n    section because structured methods for defining properties had not been\n    developed. This will try to parse the following properties: ``SUBSYSTEM``,\n    ``GENE ASSOCIATION``, ``EC NUMBER``, ``AUTHORS``, ``CONFIDENCE``.\n\n    Args:\n        entry: :class:`SBMLReactionEntry`."
  },
  {
    "code": "def _load_profile(self, profile_name):\n        default_profile = self._profile_list[0]\n        for profile in self._profile_list:\n            if profile.get('default', False):\n                default_profile = profile\n            if profile['display_name'] == profile_name:\n                break\n        else:\n            if profile_name:\n                raise ValueError(\"No such profile: %s. Options include: %s\" % (\n                    profile_name, ', '.join(p['display_name'] for p in self._profile_list)\n                ))\n            else:\n                profile = default_profile\n        self.log.debug(\"Applying KubeSpawner override for profile '%s'\", profile['display_name'])\n        kubespawner_override = profile.get('kubespawner_override', {})\n        for k, v in kubespawner_override.items():\n            if callable(v):\n                v = v(self)\n                self.log.debug(\".. overriding KubeSpawner value %s=%s (callable result)\", k, v)\n            else:\n                self.log.debug(\".. overriding KubeSpawner value %s=%s\", k, v)\n            setattr(self, k, v)",
    "docstring": "Load a profile by name\n\n        Called by load_user_options"
  },
  {
    "code": "def make_primitive_extrapolate_ends(cas_coords, smoothing_level=2):\n    try:\n        smoothed_primitive = make_primitive_smoothed(\n            cas_coords, smoothing_level=smoothing_level)\n    except ValueError:\n        smoothed_primitive = make_primitive_smoothed(\n            cas_coords, smoothing_level=smoothing_level - 1)\n    if len(smoothed_primitive) < 3:\n        smoothed_primitive = make_primitive_smoothed(\n            cas_coords, smoothing_level=smoothing_level - 1)\n    final_primitive = []\n    for ca in cas_coords:\n        prim_dists = [distance(ca, p) for p in smoothed_primitive]\n        closest_indices = sorted([x[0] for x in sorted(\n            enumerate(prim_dists), key=lambda k: k[1])[:3]])\n        a, b, c = [smoothed_primitive[x] for x in closest_indices]\n        ab_foot = find_foot(a, b, ca)\n        bc_foot = find_foot(b, c, ca)\n        ca_foot = (ab_foot + bc_foot) / 2\n        final_primitive.append(ca_foot)\n    return final_primitive",
    "docstring": "Generates smoothed helix primitives and extrapolates lost ends.\n\n    Notes\n    -----\n    From an input list of CA coordinates, the running average is\n    calculated to form a primitive. The smoothing_level dictates how\n    many times to calculate the running average. A higher\n    smoothing_level generates a 'smoother' primitive - i.e. the\n    points on the primitive more closely fit a smooth curve in R^3.\n    Each time the smoothing level is increased by 1, a point is lost\n    from either end of the primitive. To correct for this, the primitive\n    is extrapolated at the ends to approximate the lost values. There\n    is a trade-off then between the smoothness of the primitive and\n    its accuracy at the ends.\n\n\n    Parameters\n    ----------\n    cas_coords : list(numpy.array or float or tuple)\n        Each element of the list must have length 3.\n    smoothing_level : int\n        Number of times to run the averaging.\n\n    Returns\n    -------\n    final_primitive : list(numpy.array)\n        Each array has length 3."
  },
  {
    "code": "def chage(username, lastday=None, expiredate=None, inactive=None,\n          mindays=None, maxdays=None, root=None, warndays=None):\n    cmd = ['chage']\n    if root:\n        cmd.extend(['--root', root])\n    if lastday:\n        cmd.extend(['--lastday', lastday])\n    if expiredate:\n        cmd.extend(['--expiredate', expiredate])\n    if inactive:\n        cmd.extend(['--inactive', inactive])\n    if mindays:\n        cmd.extend(['--mindays', mindays])\n    if maxdays:\n        cmd.extend(['--maxdays', maxdays])\n    if warndays:\n        cmd.extend(['--warndays', warndays])\n    cmd.append(username)\n    subprocess.check_call(cmd)",
    "docstring": "Change user password expiry information\n\n    :param str username: User to update\n    :param str lastday: Set when password was changed in YYYY-MM-DD format\n    :param str expiredate: Set when user's account will no longer be\n                           accessible in YYYY-MM-DD format.\n                           -1 will remove an account expiration date.\n    :param str inactive: Set the number of days of inactivity after a password\n                         has expired before the account is locked.\n                         -1 will remove an account's inactivity.\n    :param str mindays: Set the minimum number of days between password\n                        changes to MIN_DAYS.\n                        0 indicates the password can be changed anytime.\n    :param str maxdays: Set the maximum number of days during which a\n                        password is valid.\n                        -1 as MAX_DAYS will remove checking maxdays\n    :param str root: Apply changes in the CHROOT_DIR directory\n    :param str warndays: Set the number of days of warning before a password\n                         change is required\n    :raises subprocess.CalledProcessError: if call to chage fails"
  },
  {
    "code": "def get_by_id(self, id):\n        for child in self.children:\n            if child[self.child_id_attribute] == id:\n                return child\n            else:\n                continue\n        return None",
    "docstring": "Return object based on ``child_id_attribute``.\n\n        Parameters\n        ----------\n        val : str\n\n        Returns\n        -------\n        object\n\n        Notes\n        -----\n        Based on `.get()`_ from `backbone.js`_.\n\n        .. _backbone.js: http://backbonejs.org/\n        .. _.get(): http://backbonejs.org/#Collection-get"
  },
  {
    "code": "def attach_tracker(self, stanza, tracker=None):\n        if stanza.xep0184_received is not None:\n            raise ValueError(\n                \"requesting delivery receipts for delivery receipts is not \"\n                \"allowed\"\n            )\n        if stanza.type_ == aioxmpp.MessageType.ERROR:\n            raise ValueError(\n                \"requesting delivery receipts for errors is not supported\"\n            )\n        if tracker is None:\n            tracker = aioxmpp.tracking.MessageTracker()\n        stanza.xep0184_request_receipt = True\n        stanza.autoset_id()\n        self._bare_jid_maps[stanza.to, stanza.id_] = tracker\n        return tracker",
    "docstring": "Return a new tracker or modify one to track the stanza.\n\n        :param stanza: Stanza to track.\n        :type stanza: :class:`aioxmpp.Message`\n        :param tracker: Existing tracker to attach to.\n        :type tracker: :class:`.tracking.MessageTracker`\n        :raises ValueError: if the stanza is of type\n            :attr:`~aioxmpp.MessageType.ERROR`\n        :raises ValueError: if the stanza contains a delivery receipt\n        :return: The message tracker for the stanza.\n        :rtype: :class:`.tracking.MessageTracker`\n\n        The `stanza` gets a :xep:`184` reciept request attached and internal\n        handlers are set up to update the `tracker` state once a confirmation\n        is received.\n\n        .. warning::\n\n           See the :ref:`api-tracking-memory`."
  },
  {
    "code": "def k_array_rank_jit(a):\n    k = len(a)\n    idx = a[0]\n    for i in range(1, k):\n        idx += comb_jit(a[i], i+1)\n    return idx",
    "docstring": "Numba jit version of `k_array_rank`.\n\n    Notes\n    -----\n    An incorrect value will be returned without warning or error if\n    overflow occurs during the computation. It is the user's\n    responsibility to ensure that the rank of the input array fits\n    within the range of possible values of `np.intp`; a sufficient\n    condition for it is `scipy.special.comb(a[-1]+1, len(a), exact=True)\n    <= np.iinfo(np.intp).max`."
  },
  {
    "code": "def reset(self, index=None):\n        points_handler_count = len(self.registration_view.points)\n        if index is None:\n            indexes = range(points_handler_count)\n        else:\n            indexes = [index]\n        indexes = [i for i in indexes if i < points_handler_count]\n        for i in indexes:\n            self.registration_view.points[i].reset()\n        if indexes:\n            self.registration_view.update_transform()",
    "docstring": "Reset the points for the specified index position.  If no index is\n        specified, reset points for all point handlers."
  },
  {
    "code": "def naccess_available():\n    available = False\n    try:\n        subprocess.check_output(['naccess'], stderr=subprocess.DEVNULL)\n    except subprocess.CalledProcessError:\n        available = True\n    except FileNotFoundError:\n        print(\"naccess has not been found on your path. If you have already \"\n              \"installed naccess but are unsure how to add it to your path, \"\n              \"check out this: https://stackoverflow.com/a/14638025\")\n    return available",
    "docstring": "True if naccess is available on the path."
  },
  {
    "code": "def _fix_time(self, dt):\n        if dt.tzinfo is not None:\n            dt = dt.replace(tzinfo=None)\n        return dt",
    "docstring": "Stackdistiller converts all times to utc.\n\n        We store timestamps as utc datetime. However, the explicit\n        UTC timezone on incoming datetimes causes comparison issues\n        deep in sqlalchemy. We fix this by converting all datetimes\n        to naive utc timestamps"
  },
  {
    "code": "def setup_task_signals(self, ):\n        log.debug(\"Setting up task page signals.\")\n        self.task_user_view_pb.clicked.connect(self.task_view_user)\n        self.task_user_add_pb.clicked.connect(self.task_add_user)\n        self.task_user_remove_pb.clicked.connect(self.task_remove_user)\n        self.task_dep_view_pb.clicked.connect(self.task_view_dep)\n        self.task_link_view_pb.clicked.connect(self.task_view_link)\n        self.task_deadline_de.dateChanged.connect(self.task_save)\n        self.task_status_cb.currentIndexChanged.connect(self.task_save)",
    "docstring": "Setup the signals for the task page\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def UsesArtifact(self, artifacts):\n    if isinstance(artifacts, string_types):\n      return artifacts in self.artifacts\n    else:\n      return any(True for artifact in artifacts if artifact in self.artifacts)",
    "docstring": "Determines if the check uses the specified artifact.\n\n    Args:\n      artifacts: Either a single artifact name, or a list of artifact names\n\n    Returns:\n      True if the check uses a specific artifact."
  },
  {
    "code": "def execute_return_result(cmd):\n    ret = _run_all(cmd)\n    if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n        msg = 'Command Failed: {0}\\n'.format(cmd)\n        msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n        msg += 'Output: {0}\\n'.format(ret['stdout'])\n        msg += 'Error: {0}\\n'.format(ret['stderr'])\n        raise CommandExecutionError(msg)\n    return ret['stdout']",
    "docstring": "Executes the passed command. Returns the standard out if successful\n\n    :param str cmd: The command to run\n\n    :return: The standard out of the command if successful, otherwise returns\n    an error\n    :rtype: str\n\n    :raises: Error if command fails or is not supported"
  },
  {
    "code": "def indices_from_symbol(self, symbol: str) -> tuple:\n        return tuple((i for i, specie in enumerate(self.species)\n                      if specie.symbol == symbol))",
    "docstring": "Returns a tuple with the sequential indices of the sites\n        that contain an element with the given chemical symbol."
  },
  {
    "code": "def load_modules(self):\n        if self.INTERFACES_MODULE is None:\n            raise NotImplementedError(\"A module containing interfaces modules \"\n                                      \"should be setup in INTERFACES_MODULE !\")\n        else:\n            for module, permission in self.modules.items():\n                i = getattr(self.INTERFACES_MODULE,\n                            module).Interface(self, permission)\n                self.interfaces[module] = i",
    "docstring": "Should instance interfaces and set them to interface, following `modules`"
  },
  {
    "code": "def rename(self, newpath):\n        \"Move folder to a new name, possibly a whole new path\"\n        params = {'mvDir':'/%s%s' % (self.jfs.username, newpath)}\n        r = self.jfs.post(self.path,\n                          extra_headers={'Content-Type':'application/octet-stream'},\n                          params=params)\n        return r",
    "docstring": "Move folder to a new name, possibly a whole new path"
  },
  {
    "code": "def evaluate(condition):\n        success = False\n        if len(condition) > 0:\n            try:\n                rule_name, ast_tokens, evaluate_function = Condition.find_rule(condition)\n                if not rule_name == 'undefined':\n                    success = evaluate_function(ast_tokens)\n            except AttributeError as exception:\n                Logger.get_logger(__name__).error(\"Attribute error: %s\", exception)\n        else:\n            success = True\n        return success",
    "docstring": "Evaluate simple condition.\n\n        >>> Condition.evaluate('  2  ==  2  ')\n        True\n        >>> Condition.evaluate('  not  2  ==  2  ')\n        False\n        >>> Condition.evaluate('  not  \"abc\"  ==  \"xyz\"  ')\n        True\n        >>> Condition.evaluate('2 in [2, 4, 6, 8, 10]')\n        True\n        >>> Condition.evaluate('5 in [2, 4, 6, 8, 10]')\n        False\n        >>> Condition.evaluate('\"apple\" in [\"apple\", \"kiwi\", \"orange\"]')\n        True\n        >>> Condition.evaluate('5 not in [2, 4, 6, 8, 10]')\n        True\n        >>> Condition.evaluate('\"apple\" not in [\"kiwi\", \"orange\"]')\n        True\n\n        Args:\n            condition (str): Python condition as string.\n\n        Returns:\n            bool: True when condition evaluates to True."
  },
  {
    "code": "def build_absolute_uri(request, relative_url):\n    webroot = getattr(settings, 'WEBROOT', '')\n    if webroot.endswith(\"/\") and relative_url.startswith(\"/\"):\n        webroot = webroot[:-1]\n    return request.build_absolute_uri(webroot + relative_url)",
    "docstring": "Ensure absolute_uri are relative to WEBROOT."
  },
  {
    "code": "def form_number(self):\n\t\tk1, o1, m2, s2 = (\n\t\t\tnp.extract(self.model['constituent'] == c, self.model['amplitude'])\n\t\t\tfor c in [constituent._K1, constituent._O1, constituent._M2, constituent._S2]\n\t\t)\n\t\treturn (k1+o1)/(m2+s2)",
    "docstring": "Returns the model's form number, a helpful heuristic for classifying tides."
  },
  {
    "code": "def assume_script(self) -> 'Language':\n        if self._assumed is not None:\n            return self._assumed\n        if self.language and not self.script:\n            try:\n                self._assumed = self.update_dict({'script': DEFAULT_SCRIPTS[self.language]})\n            except KeyError:\n                self._assumed = self\n        else:\n            self._assumed = self\n        return self._assumed",
    "docstring": "Fill in the script if it's missing, and if it can be assumed from the\n        language subtag. This is the opposite of `simplify_script`.\n\n        >>> Language.make(language='en').assume_script()\n        Language.make(language='en', script='Latn')\n\n        >>> Language.make(language='yi').assume_script()\n        Language.make(language='yi', script='Hebr')\n\n        >>> Language.make(language='yi', script='Latn').assume_script()\n        Language.make(language='yi', script='Latn')\n\n        This fills in nothing when the script cannot be assumed -- such as when\n        the language has multiple scripts, or it has no standard orthography:\n\n        >>> Language.make(language='sr').assume_script()\n        Language.make(language='sr')\n\n        >>> Language.make(language='eee').assume_script()\n        Language.make(language='eee')\n\n        It also dosn't fill anything in when the language is unspecified.\n\n        >>> Language.make(region='US').assume_script()\n        Language.make(region='US')"
  },
  {
    "code": "def _element_path_create_new(element_path):\n    element_names = element_path.split('/')\n    start_element = ET.Element(element_names[0])\n    end_element = _element_append_path(start_element, element_names[1:])\n    return start_element, end_element",
    "docstring": "Create an entirely new element path.\n\n    Return a tuple where the first item is the first element in the path, and the second item is\n    the final element in the path."
  },
  {
    "code": "def create_module_rst_file(module_name):\n    return_text = 'Module:  ' + module_name\n    dash = '=' * len(return_text)\n    return_text += '\\n' + dash + '\\n\\n'\n    return_text += '.. automodule:: ' + module_name + '\\n'\n    return_text += '   :members:\\n\\n'\n    return return_text",
    "docstring": "Function for creating content in each .rst file for a module.\n\n    :param module_name: name of the module.\n    :type module_name: str\n\n    :returns: A content for auto module.\n    :rtype: str"
  },
  {
    "code": "def buffer_read_into(self, buffer, dtype):\n        ctype = self._check_dtype(dtype)\n        cdata, frames = self._check_buffer(buffer, ctype)\n        frames = self._cdata_io('read', cdata, ctype, frames)\n        return frames",
    "docstring": "Read from the file into a given buffer object.\n\n        Fills the given `buffer` with frames in the given data format\n        starting at the current read/write position (which can be\n        changed with :meth:`.seek`) until the buffer is full or the end\n        of the file is reached.  This advances the read/write position\n        by the number of frames that were read.\n\n        Parameters\n        ----------\n        buffer : writable buffer\n            Audio frames from the file are written to this buffer.\n        dtype : {'float64', 'float32', 'int32', 'int16'}\n            The data type of `buffer`.\n\n        Returns\n        -------\n        int\n            The number of frames that were read from the file.\n            This can be less than the size of `buffer`.\n            The rest of the buffer is not filled with meaningful data.\n\n        See Also\n        --------\n        buffer_read, .read"
  },
  {
    "code": "def will_print(level=1):\n    if level == 1:\n        return quiet is None or quiet == False\n    else:\n        return ((isinstance(verbosity, int) and level <= verbosity) or\n                (isinstance(verbosity, bool) and verbosity == True))",
    "docstring": "Returns True if the current global status of messaging would print a\n    message using any of the printing functions in this module."
  },
  {
    "code": "def role_create(name, profile=None, **connection_args):\n    kstone = auth(profile, **connection_args)\n    if 'Error' not in role_get(name=name, profile=profile, **connection_args):\n        return {'Error': 'Role \"{0}\" already exists'.format(name)}\n    kstone.roles.create(name)\n    return role_get(name=name, profile=profile, **connection_args)",
    "docstring": "Create a named role.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' keystone.role_create admin"
  },
  {
    "code": "def cudaGetDevice():\n    dev = ctypes.c_int()\n    status = _libcudart.cudaGetDevice(ctypes.byref(dev))\n    cudaCheckStatus(status)\n    return dev.value",
    "docstring": "Get current CUDA device.\n\n    Return the identifying number of the device currently used to\n    process CUDA operations.\n\n    Returns\n    -------\n    dev : int\n        Device number."
  },
  {
    "code": "def psnr(data1, data2, method='starck', max_pix=255):\n    r\n    if method == 'starck':\n        return (20 * np.log10((data1.shape[0] * np.abs(np.max(data1) -\n                np.min(data1))) / np.linalg.norm(data1 - data2)))\n    elif method == 'wiki':\n        return (20 * np.log10(max_pix) - 10 *\n                np.log10(mse(data1, data2)))\n    else:\n        raise ValueError('Invalid PSNR method. Options are \"starck\" and '\n                         '\"wiki\"')",
    "docstring": "r\"\"\"Peak Signal-to-Noise Ratio\n\n    This method calculates the Peak Signal-to-Noise Ratio between an two data\n    sets\n\n    Parameters\n    ----------\n    data1 : np.ndarray\n        First data set\n    data2 : np.ndarray\n        Second data set\n    method : str {'starck', 'wiki'}, optional\n        PSNR implementation, default ('starck')\n    max_pix : int, optional\n        Maximum number of pixels, default (max_pix=255)\n\n    Returns\n    -------\n    float PSNR value\n\n    Examples\n    --------\n    >>> from modopt.math.stats import psnr\n    >>> a = np.arange(9).reshape(3, 3)\n    >>> psnr(a, a + 2)\n    12.041199826559248\n\n    >>> psnr(a, a + 2, method='wiki')\n    42.110203695399477\n\n    Notes\n    -----\n    'starck':\n\n        Implements eq.3.7 from _[S2010]\n\n    'wiki':\n\n        Implements PSNR equation on\n        https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio\n\n        .. math::\n\n            \\mathrm{PSNR} = 20\\log_{10}(\\mathrm{MAX}_I -\n            10\\log_{10}(\\mathrm{MSE}))"
  },
  {
    "code": "def get_display_label(choices, status):\n    for (value, label) in choices:\n        if value == (status or '').lower():\n            display_label = label\n            break\n    else:\n        display_label = status\n    return display_label",
    "docstring": "Get a display label for resource status.\n\n    This method is used in places where a resource's status or\n    admin state labels need to assigned before they are sent to the\n    view template."
  },
  {
    "code": "def _start_auth_proc(self):\n        log.debug('Computing the signing key hex')\n        verify_key = self.__signing_key.verify_key\n        sgn_verify_hex = verify_key.encode(encoder=nacl.encoding.HexEncoder)\n        log.debug('Starting the authenticator subprocess')\n        auth = NapalmLogsAuthProc(self.certificate,\n                                  self.keyfile,\n                                  self.__priv_key,\n                                  sgn_verify_hex,\n                                  self.auth_address,\n                                  self.auth_port)\n        proc = Process(target=auth.start)\n        proc.start()\n        proc.description = 'Auth process'\n        log.debug('Started auth process as %s with PID %s', proc._name, proc.pid)\n        return proc",
    "docstring": "Start the authenticator process."
  },
  {
    "code": "def get_tree(root=None):\n    from insights import run\n    return run(MultipathConfTree, root=root).get(MultipathConfTree)",
    "docstring": "This is a helper function to get a multipath configuration component for\n    your local machine or an archive. It's for use in interactive sessions."
  },
  {
    "code": "def get_notebook_app_versions():\n    notebook_apps = dxpy.find_apps(name=NOTEBOOK_APP, all_versions=True)\n    versions = [str(dxpy.describe(app['id'])['version']) for app in notebook_apps]\n    return versions",
    "docstring": "Get the valid version numbers of the notebook app."
  },
  {
    "code": "def _on_axes_updated(self):\n        self.attrs[\"axes\"] = [a.identity.encode() for a in self._axes]\n        while len(self._current_axis_identities_in_natural_namespace) > 0:\n            key = self._current_axis_identities_in_natural_namespace.pop(0)\n            try:\n                delattr(self, key)\n            except AttributeError:\n                pass\n        for a in self._axes:\n            key = a.natural_name\n            setattr(self, key, a)\n            self._current_axis_identities_in_natural_namespace.append(key)",
    "docstring": "Method to run when axes are changed in any way.\n\n        Propagates updated axes properly."
  },
  {
    "code": "def branch_order(h,section, path=[]):\n    path.append(section)\n    sref = h.SectionRef(sec=section)\n    if sref.has_parent() < 0.9:\n        return 0\n    else:\n        nchild = len(list(h.SectionRef(sec=sref.parent).child))\n        if nchild <= 1.1:\n            return branch_order(h,sref.parent,path)\n        else:\n            return 1+branch_order(h,sref.parent,path)",
    "docstring": "Returns the branch order of a section"
  },
  {
    "code": "def play_Note(self, note):\n        velocity = 64\n        channel = 1\n        if hasattr(note, 'dynamics'):\n            if 'velocity' in note.dynamics:\n                velocity = note.dynamics['velocity']\n            if 'channel' in note.dynamics:\n                channel = note.dynamics['channel']\n        if hasattr(note, 'channel'):\n            channel = note.channel\n        if hasattr(note, 'velocity'):\n            velocity = note.velocity\n        if self.change_instrument:\n            self.set_instrument(channel, self.instrument)\n            self.change_instrument = False\n        self.track_data += self.note_on(channel, int(note) + 12, velocity)",
    "docstring": "Convert a Note object to a midi event and adds it to the\n        track_data.\n\n        To set the channel on which to play this note, set Note.channel, the\n        same goes for Note.velocity."
  },
  {
    "code": "def import_module_or_none(module_label):\n    try:\n        return importlib.import_module(module_label)\n    except ImportError:\n        __, __, exc_traceback = sys.exc_info()\n        frames = traceback.extract_tb(exc_traceback)\n        frames = [f for f in frames\n                  if f[0] != \"<frozen importlib._bootstrap>\" and\n                  f[0] != IMPORT_PATH_IMPORTLIB and\n                  not f[0].endswith(IMPORT_PATH_GEVENT) and\n                  not IMPORT_PATH_PYDEV in f[0]]\n        if len(frames) > 1:\n            raise\n    return None",
    "docstring": "Imports the module with the given name.\n\n    Returns None if the module doesn't exist,\n    but it does propagates import errors in deeper modules."
  },
  {
    "code": "def union(self, *sets):\n        cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet\n        containers = map(list, it.chain([self], sets))\n        items = it.chain.from_iterable(containers)\n        return cls(items)",
    "docstring": "Combines all unique items.\n        Each items order is defined by its first appearance.\n\n        Example:\n            >>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0])\n            >>> print(oset)\n            OrderedSet([3, 1, 4, 5, 2, 0])\n            >>> oset.union([8, 9])\n            OrderedSet([3, 1, 4, 5, 2, 0, 8, 9])\n            >>> oset | {10}\n            OrderedSet([3, 1, 4, 5, 2, 0, 10])"
  },
  {
    "code": "def collect_data(self, correct_only):\n        self.results = []\n        def get_value_from_logfile(lines, identifier):\n            return load_tool(self).get_value_from_output(lines, identifier)\n        log_zip_cache = {}\n        try:\n            for xml_result, result_file in self._xml_results:\n                self.results.append(RunResult.create_from_xml(\n                    xml_result, get_value_from_logfile, self.columns,\n                    correct_only, log_zip_cache, self.columns_relevant_for_diff, result_file))\n        finally:\n            for file in log_zip_cache.values():\n                file.close()\n        for column in self.columns:\n            column_values = (run_result.values[run_result.columns.index(column)] for run_result in self.results)\n            column.type, column.unit, column.source_unit, column.scale_factor = get_column_type(column, column_values)\n        del self._xml_results",
    "docstring": "Load the actual result values from the XML file and the log files.\n        This may take some time if many log files have to be opened and parsed."
  },
  {
    "code": "def add_component(self, entity: int, component_instance: Any) -> None:\n        component_type = type(component_instance)\n        if component_type not in self._components:\n            self._components[component_type] = set()\n        self._components[component_type].add(entity)\n        if entity not in self._entities:\n            self._entities[entity] = {}\n        self._entities[entity][component_type] = component_instance\n        self.clear_cache()",
    "docstring": "Add a new Component instance to an Entity.\n\n        Add a Component instance to an Entiy. If a Component of the same type\n        is already assigned to the Entity, it will be replaced.\n\n        :param entity: The Entity to associate the Component with.\n        :param component_instance: A Component instance."
  },
  {
    "code": "def CreateChatWith(self, *Usernames):\n        return Chat(self, chop(self._DoCommand('CHAT CREATE %s' % ', '.join(Usernames)), 2)[1])",
    "docstring": "Creates a chat with one or more users.\n\n        :Parameters:\n          Usernames : str\n            One or more Skypenames of the users.\n\n        :return: A chat object\n        :rtype: `Chat`\n\n        :see: `Chat.AddMembers`"
  },
  {
    "code": "def get_blink_cookie(self, name):\n        value = self.get_cookie(name)\n        if value != None:\n            self.clear_cookie(name)\n            return escape.url_unescape(value)",
    "docstring": "Gets a blink cookie value"
  },
  {
    "code": "def com_google_fonts_check_metadata_valid_copyright(font_metadata):\n  import re\n  string = font_metadata.copyright\n  does_match = re.search(r'Copyright [0-9]{4} The .* Project Authors \\([^\\@]*\\)',\n                           string)\n  if does_match:\n    yield PASS, \"METADATA.pb copyright string is good\"\n  else:\n    yield FAIL, (\"METADATA.pb: Copyright notices should match\"\n                 \" a pattern similar to:\"\n                 \" 'Copyright 2017 The Familyname\"\n                 \" Project Authors (git url)'\\n\"\n                 \"But instead we have got:\"\n                 \" '{}'\").format(string)",
    "docstring": "Copyright notices match canonical pattern in METADATA.pb"
  },
  {
    "code": "def from_json(cls, stream, json_data):\n        type_converter = _get_decoder_method(stream.get_data_type())\n        data = type_converter(json_data.get(\"data\"))\n        return cls(\n            stream_id=stream.get_stream_id(),\n            data_type=stream.get_data_type(),\n            units=stream.get_units(),\n            data=data,\n            description=json_data.get(\"description\"),\n            timestamp=json_data.get(\"timestampISO\"),\n            server_timestamp=json_data.get(\"serverTimestampISO\"),\n            quality=json_data.get(\"quality\"),\n            location=json_data.get(\"location\"),\n            dp_id=json_data.get(\"id\"),\n        )",
    "docstring": "Create a new DataPoint object from device cloud JSON data\n\n        :param DataStream stream: The :class:`~DataStream` out of which this data is coming\n        :param dict json_data: Deserialized JSON data from Device Cloud about this device\n        :raises ValueError: if the data is malformed\n        :return: (:class:`~DataPoint`) newly created :class:`~DataPoint`"
  },
  {
    "code": "def format_query_result(self, query_result, query_path, return_type=list, preceding_depth=None):\n        if type(query_result) != return_type:\n            converted_result = self.format_with_handler(query_result, return_type)\n        else:\n            converted_result = query_result\n        converted_result = self.add_preceding_dict(converted_result, query_path, preceding_depth)\n        return converted_result",
    "docstring": "Formats the query result based on the return type requested.\n\n        :param query_result: (dict or str or list), yaml query result\n        :param query_path: (str, list(str)), representing query path\n        :param return_type: type, return type of object user desires\n        :param preceding_depth: int, the depth to which we want to encapsulate back up config tree\n                                    -1 : defaults to entire tree\n        :return: (dict, OrderedDict, str, list), specified return type"
  },
  {
    "code": "def get(cls, bucket, key, upload_id, with_completed=False):\n        q = cls.query.filter_by(\n            upload_id=upload_id,\n            bucket_id=as_bucket_id(bucket),\n            key=key,\n        )\n        if not with_completed:\n            q = q.filter(cls.completed.is_(False))\n        return q.one_or_none()",
    "docstring": "Fetch a specific multipart object."
  },
  {
    "code": "def get_file(type_str, open_files, basedir):\n    if type_str not in open_files:\n        filename = type_str+\".html\"\n        encoding = 'utf-8'\n        fd = codecs.open(os.path.join(basedir, filename), 'w', encoding)\n        open_files[type_str] = fd\n        write_html_header(fd, type_str, encoding)\n    return open_files[type_str]",
    "docstring": "Get already opened file, or open and initialize a new one."
  },
  {
    "code": "def createZone(self, zone, zoneFile=None, callback=None, errback=None,\n                   **kwargs):\n        import ns1.zones\n        zone = ns1.zones.Zone(self.config, zone)\n        return zone.create(zoneFile=zoneFile, callback=callback,\n                           errback=errback, **kwargs)",
    "docstring": "Create a new zone, and return an associated high level Zone object.\n        Several optional keyword arguments are available to configure the SOA\n        record.\n\n        If zoneFile is specified, upload the specific zone definition file\n        to populate the zone with.\n\n        :param str zone: zone name, like 'example.com'\n        :param str zoneFile: absolute path of a zone file\n        :keyword int retry: retry time\n        :keyword int refresh: refresh ttl\n        :keyword int expiry: expiry ttl\n        :keyword int nx_ttl: nxdomain TTL\n\n        :rtype: :py:class:`ns1.zones.Zone`"
  },
  {
    "code": "def internal_assert(condition, message=None, item=None, extra=None):\n    if DEVELOP and callable(condition):\n        condition = condition()\n    if not condition:\n        if message is None:\n            message = \"assertion failed\"\n            if item is None:\n                item = condition\n        raise CoconutInternalException(message, item, extra)",
    "docstring": "Raise InternalException if condition is False.\n    If condition is a function, execute it on DEVELOP only."
  },
  {
    "code": "def _cache_get(self, date):\n        if date in self.cache_data:\n            logger.debug('Using class-cached data for date %s',\n                         date.strftime('%Y-%m-%d'))\n            return self.cache_data[date]\n        logger.debug('Getting data from cache for date %s',\n                     date.strftime('%Y-%m-%d'))\n        data = self.cache.get(self.project_name, date)\n        self.cache_data[date] = data\n        return data",
    "docstring": "Return cache data for the specified day; cache locally in this class.\n\n        :param date: date to get data for\n        :type date: datetime.datetime\n        :return: cache data for date\n        :rtype: dict"
  },
  {
    "code": "def _zmq_socket_context(context, socket_type, bind_endpoints):\n    socket = context.socket(socket_type)\n    try:\n        for endpoint in bind_endpoints:\n            try:\n                socket.bind(endpoint)\n            except Exception:\n                _logger.fatal(\"Could not bind to '%s'.\", endpoint)\n                raise\n        yield socket\n    finally:\n        socket.close()",
    "docstring": "A ZeroMQ socket context that both constructs a socket and closes it."
  },
  {
    "code": "def insert_local_var(self, vname, vtype, position):\r\n        \"Inserts a new local variable\"\r\n        index = self.insert_id(vname, SharedData.KINDS.LOCAL_VAR, [SharedData.KINDS.LOCAL_VAR, SharedData.KINDS.PARAMETER], vtype)\r\n        self.table[index].attribute = position",
    "docstring": "Inserts a new local variable"
  },
  {
    "code": "def init_log_file(self):\n        self.old_stdout = sys.stdout\n        sys.stdout = open(os.path.join(self.WD, \"demag_gui.log\"), 'w+')",
    "docstring": "redirects stdout to a log file to prevent printing to a hanging\n        terminal when dealing with the compiled binary."
  },
  {
    "code": "def fromXMLname(string):\n    retval = sub(r'_xFFFF_','', string )\n    def fun( matchobj ):\n        return _fromUnicodeHex( matchobj.group(0) )\n    retval = sub(r'_x[0-9A-Za-z]+_', fun, retval )\n    return retval",
    "docstring": "Convert XML name to unicode string."
  },
  {
    "code": "def size(self):\n        \"The canonical serialized size of this branch.\"\n        if getattr(self, '_size', None) is None:\n            self._size = getattr(self.node, 'size', 0)\n        return self._size",
    "docstring": "The canonical serialized size of this branch."
  },
  {
    "code": "def ensure_hbounds(self):\n        self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)",
    "docstring": "Ensure the cursor is within horizontal screen bounds."
  },
  {
    "code": "def csv_dict(d):\n    if len(d) == 0:\n        return \"{}\"\n    return \"{\" + ', '.join([\"'{}': {}\".format(k, quotable(v))\n                            for k, v in d.items()]) + \"}\"",
    "docstring": "Format dict to a string with comma-separated values."
  },
  {
    "code": "def _add_identities_xml(self, document):\n        for fingerprint in self.identities:\n            identity_element = document.createElement(\n                'allow-access-from-identity'\n            )\n            signatory_element = document.createElement(\n                'signatory'\n            )\n            certificate_element = document.createElement(\n                'certificate'\n            )\n            certificate_element.setAttribute(\n                'fingerprint',\n                fingerprint)\n            certificate_element.setAttribute(\n                'fingerprint-algorithm',\n                'sha-1')\n            signatory_element.appendChild(certificate_element)\n            identity_element.appendChild(signatory_element)\n            document.documentElement.appendChild(identity_element)",
    "docstring": "Generates the XML elements for allowed digital signatures."
  },
  {
    "code": "def construct_scratch_path(self, dirname, basename):\n        return os.path.join(self.scratchdir, dirname, basename)",
    "docstring": "Construct and return a path in the scratch area.\n\n        This will be  <self.scratchdir>/<dirname>/<basename>"
  },
  {
    "code": "def load_plug_in(self, name):\n        if not isinstance(name, basestring):\n            raise TypeError(\"name can only be an instance of type basestring\")\n        plug_in_name = self._call(\"loadPlugIn\",\n                     in_p=[name])\n        return plug_in_name",
    "docstring": "Loads a DBGF plug-in.\n\n        in name of type str\n            The plug-in name or DLL. Special name 'all' loads all installed plug-ins.\n\n        return plug_in_name of type str\n            The name of the loaded plug-in."
  },
  {
    "code": "def delete_intel_notifications(self, ids, timeout=None):\n        if not isinstance(ids, list):\n            raise TypeError(\"ids must be a list\")\n        data = json.dumps(ids)\n        try:\n            response = requests.post(\n                self.base + 'hunting/delete-notifications/programmatic/?key=' + self.api_key,\n                data=data,\n                proxies=self.proxies,\n                timeout=timeout)\n        except requests.RequestException as e:\n            return dict(error=str(e))\n        return _return_response_and_status_code(response)",
    "docstring": "Programmatically delete notifications via the Intel API.\n\n        :param ids: A list of IDs to delete from the notification feed.\n        :returns: The post response."
  },
  {
    "code": "def copy_keys(source, destination, keys=None):\n    if keys is None:\n        keys = destination.keys()\n    for k in set(source) & set(keys):\n        destination[k] = source[k]\n    return destination",
    "docstring": "Add keys in source to destination\n\n    Parameters\n    ----------\n    source : dict\n\n    destination: dict\n\n    keys : None | iterable\n        The keys in source to be copied into destination. If\n        None, then `keys = destination.keys()`"
  },
  {
    "code": "def asDict(self):\n        ret = {}\n        for field in BackgroundTaskInfo.FIELDS:\n            ret[field] = getattr(self, field)\n        return ret",
    "docstring": "asDict - Returns a copy of the current state as a dictionary. This copy will not be updated automatically.\n\n            @return <dict> - Dictionary with all fields in BackgroundTaskInfo.FIELDS"
  },
  {
    "code": "def set_timestamp(self, data):\n        if 'hittime' in data:\n            data['qt'] = self.hittime(timestamp=data.pop('hittime', None))\n        if 'hitage' in data:\n            data['qt'] = self.hittime(age=data.pop('hitage', None))",
    "docstring": "Interpret time-related options, apply queue-time parameter as needed"
  },
  {
    "code": "def unique_list(seq: Iterable[Any]) -> List[Any]:\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]",
    "docstring": "Returns a list of all the unique elements in the input list.\n\n    Args:\n        seq: input list\n\n    Returns:\n        list of unique elements\n\n    As per\n    http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserving-order"
  },
  {
    "code": "def _GetSqliteSchema(self, proto_struct_class, prefix=\"\"):\n    schema = collections.OrderedDict()\n    for type_info in proto_struct_class.type_infos:\n      if type_info.__class__ is rdf_structs.ProtoEmbedded:\n        schema.update(\n            self._GetSqliteSchema(\n                type_info.type, prefix=\"%s%s.\" % (prefix, type_info.name)))\n      else:\n        field_name = utils.SmartStr(prefix + type_info.name)\n        schema[field_name] = Rdf2SqliteAdapter.GetConverter(type_info)\n    return schema",
    "docstring": "Returns a mapping of SQLite column names to Converter objects."
  },
  {
    "code": "def highlightBlock(self, text):\n        cb = self.currentBlock()\n        p = cb.position()\n        text = str(self.document().toPlainText()) + '\\n'\n        highlight(text, self.lexer, self.formatter)\n        for i in range(len(str(text))):\n            try:\n                self.setFormat(i, 1, self.formatter.data[p + i])\n            except IndexError:\n                pass\n        self.tstamp = time.time()",
    "docstring": "Takes a block, applies format to the document.\n        according to what's in it."
  },
  {
    "code": "def getStorageLevel(self):\n        java_storage_level = self._jrdd.getStorageLevel()\n        storage_level = StorageLevel(java_storage_level.useDisk(),\n                                     java_storage_level.useMemory(),\n                                     java_storage_level.useOffHeap(),\n                                     java_storage_level.deserialized(),\n                                     java_storage_level.replication())\n        return storage_level",
    "docstring": "Get the RDD's current storage level.\n\n        >>> rdd1 = sc.parallelize([1,2])\n        >>> rdd1.getStorageLevel()\n        StorageLevel(False, False, False, False, 1)\n        >>> print(rdd1.getStorageLevel())\n        Serialized 1x Replicated"
  },
  {
    "code": "def write(self, file_or_filename):\n        if isinstance(file_or_filename, basestring):\n            self._fcn_name, _ = splitext(basename(file_or_filename))\n        else:\n            self._fcn_name = self.case.name\n        self._fcn_name = self._fcn_name.replace(\",\", \"\").replace(\" \", \"_\")\n        super(MATPOWERWriter, self).write(file_or_filename)",
    "docstring": "Writes case data to file in MATPOWER format."
  },
  {
    "code": "def _cleanup(self):\n        for filename in os.listdir(self._storage_dir):\n            file_path = path.join(self._storage_dir, filename)\n            file_stat = os.stat(file_path)\n            evaluate = max(file_stat.st_ctime, file_stat.st_mtime)\n            if evaluate + self._duration < time.time():\n                LOGGER.debug('Removing stale file: %s', file_path)\n                os.unlink(file_path)",
    "docstring": "Remove any stale files from the session storage directory"
  },
  {
    "code": "def import_related_module(package, pkg_path, related_name,\n                          ignore_exceptions=False):\n    try:\n        imp.find_module(related_name, pkg_path)\n    except ImportError:\n        return\n    try:\n        return getattr(\n            __import__('%s' % (package), globals(), locals(), [related_name]),\n            related_name\n        )\n    except Exception as e:\n        if ignore_exceptions:\n            current_app.logger.exception(\n                'Can not import \"{}\" package'.format(package)\n            )\n        else:\n            raise e",
    "docstring": "Import module from given path."
  },
  {
    "code": "def _on_open(self, _):\n        nick = self._format_nick(self._nick, self._pwd)\n        data = {\"cmd\": \"join\", \"channel\": self._channel, \"nick\": nick}\n        self._send_packet(data)\n        self._thread = True\n        threading.Thread(target=self._ping).start()",
    "docstring": "Joins the hack.chat channel and starts pinging."
  },
  {
    "code": "def drain_events(self, allowed_methods=None, timeout=None):\n        return self.wait_multi(self.channels.values(), timeout=timeout)",
    "docstring": "Wait for an event on any channel."
  },
  {
    "code": "def save_code(self, authorization_code):\n        self.write(authorization_code.code,\n                   {\"client_id\": authorization_code.client_id,\n                    \"code\": authorization_code.code,\n                    \"expires_at\": authorization_code.expires_at,\n                    \"redirect_uri\": authorization_code.redirect_uri,\n                    \"scopes\": authorization_code.scopes,\n                    \"data\": authorization_code.data,\n                    \"user_id\": authorization_code.user_id})",
    "docstring": "Stores the data belonging to an authorization code token in redis.\n\n        See :class:`oauth2.store.AuthCodeStore`."
  },
  {
    "code": "def get_objects_dex(self):\n        for digest, d in self.analyzed_dex.items():\n            yield digest, d, self.analyzed_vms[digest]",
    "docstring": "Yields all dex objects inclduing their Analysis objects\n\n        :returns: tuple of (sha256, DalvikVMFormat, Analysis)"
  },
  {
    "code": "def set_params(self, subs=None, numticks=None):\n        if numticks is not None:\n            self.numticks = numticks\n        if subs is not None:\n            self._subs = subs",
    "docstring": "Set parameters within this locator.\n\n        Parameters\n        ----------\n        subs : array, optional\n            Subtick values, as multiples of the main ticks.\n        numticks : array, optional\n            Number of ticks."
  },
  {
    "code": "def find_one(self, filter=None):\n        if self.table is None:\n            self.build_table()\n        allcond = self.parse_query(filter)\n        return self.table.get(allcond)",
    "docstring": "Finds one matching query element\n\n        :param query: dictionary representing the mongo query\n        :return: the resulting document (if found)"
  },
  {
    "code": "def get_field_type(cls, name):\n        python_type = cls._get_field_python_type(cls.model, name)\n        if python_type in _COLUMN_FIELD_MAP:\n            field_class = _COLUMN_FIELD_MAP[python_type]\n            return field_class(name)\n        return BaseField(name)",
    "docstring": "Takes a field name and gets an appropriate BaseField instance\n        for that column.  It inspects the Model that is set on the manager\n        to determine what the BaseField subclass should be.\n\n        :param unicode name:\n        :return: A BaseField subclass that is appropriate for\n            translating a string input into the appropriate format.\n        :rtype: ripozo.viewsets.fields.base.BaseField"
  },
  {
    "code": "def get_instance(self, payload):\n        return VoipInstance(\n            self._version,\n            payload,\n            account_sid=self._solution['account_sid'],\n            country_code=self._solution['country_code'],\n        )",
    "docstring": "Build an instance of VoipInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.api.v2010.account.available_phone_number.voip.VoipInstance\n        :rtype: twilio.rest.api.v2010.account.available_phone_number.voip.VoipInstance"
  },
  {
    "code": "def getWorker(self, name):\n\t\tif not name in self.worker_list:\n\t\t\tself.logger.error(\"Worker {0} is not registered!\".format(name))\n\t\t\traise Exception(\"Worker {0} is not registered!\".format(name))\n\t\treturn self.worker_list[name]",
    "docstring": "Retrieve the Worker registered under the given name.\n\n\t\tIf the given name does not exists in the Worker list, an Exception is raised.\n\n\t\tParameters\n\t\t----------\n\t\tname: string\n\t\t\tName of the Worker to retrieve"
  },
  {
    "code": "def is_expired(self):\n        if self.window is not None:\n            return (self._time() - self.start_time) >= self.window\n        return False",
    "docstring": "Returns true if the time is beyond the window"
  },
  {
    "code": "def send(self, *args, **kwargs):\n        return self.send_with_options(args=args, kwargs=kwargs)",
    "docstring": "Asynchronously send a message to this actor.\n\n        Parameters:\n          *args(tuple): Positional arguments to send to the actor.\n          **kwargs(dict): Keyword arguments to send to the actor.\n\n        Returns:\n          Message: The enqueued message."
  },
  {
    "code": "def rfcformat(dt, localtime=False):\n    if not localtime:\n        return formatdate(timegm(dt.utctimetuple()))\n    else:\n        return local_rfcformat(dt)",
    "docstring": "Return the RFC822-formatted representation of a datetime object.\n\n    :param datetime dt: The datetime.\n    :param bool localtime: If ``True``, return the date relative to the local\n        timezone instead of UTC, displaying the proper offset,\n        e.g. \"Sun, 10 Nov 2013 08:23:45 -0600\""
  },
  {
    "code": "def set_country(self, country):\n        country = _convert_to_charp(country)\n        self._set_country_func(self.alpr_pointer, country)",
    "docstring": "This sets the country for detecting license plates. For example,\n        setting country to \"us\" for United States or \"eu\" for Europe.\n\n        :param country: A unicode/ascii string (Python 2/3) or bytes array (Python 3)\n        :return: None"
  },
  {
    "code": "def _get_version():\n    version_string = __salt__['cmd.run'](\n        [_check_pkgin(), '-v'],\n        output_loglevel='trace')\n    if version_string is None:\n        return False\n    version_match = VERSION_MATCH.search(version_string)\n    if not version_match:\n        return False\n    return version_match.group(1).split('.')",
    "docstring": "Get the pkgin version"
  },
  {
    "code": "def _ParseLogline(self, parser_mediator, structure):\n    month, day_of_month, year, hours, minutes, seconds, milliseconds = (\n        structure.date_time)\n    time_elements_tuple = (\n        year, month, day_of_month, hours, minutes, seconds, milliseconds)\n    try:\n      date_time = dfdatetime_time_elements.TimeElementsInMilliseconds(\n          time_elements_tuple=time_elements_tuple)\n    except ValueError:\n      parser_mediator.ProduceExtractionWarning(\n          'invalid date time value: {0!s}'.format(structure.date_time))\n      return\n    event_data = SkyDriveOldLogEventData()\n    event_data.log_level = structure.log_level\n    event_data.offset = self.offset\n    event_data.source_code = structure.source_code\n    event_data.text = structure.text\n    event = time_events.DateTimeValuesEvent(\n        date_time, definitions.TIME_DESCRIPTION_ADDED)\n    parser_mediator.ProduceEventWithEventData(event, event_data)\n    self._last_date_time = date_time\n    self._last_event_data = event_data",
    "docstring": "Parse a logline and store appropriate attributes.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      structure (pyparsing.ParseResults): structure of tokens derived from\n          a line of a text file."
  },
  {
    "code": "def compile_tag_re(self, tags):\n        return re.compile(self.raw_tag_re % tags, self.re_flags)",
    "docstring": "Return the regex used to look for Mustache tags compiled to work with\n        specific opening tags, close tags, and tag types."
  },
  {
    "code": "def calc_osc_accels(self, osc_freqs, osc_damping=0.05, tf=None):\n        if tf is None:\n            tf = np.ones_like(self.freqs)\n        else:\n            tf = np.asarray(tf).astype(complex)\n        resp = np.array([\n            self.calc_peak(tf * self._calc_sdof_tf(of, osc_damping))\n            for of in osc_freqs\n        ])\n        return resp",
    "docstring": "Compute the pseudo-acceleration spectral response of an oscillator\n        with a specific frequency and damping.\n\n        Parameters\n        ----------\n        osc_freq : float\n            Frequency of the oscillator (Hz).\n        osc_damping : float\n            Fractional damping of the oscillator (dec). For example, 0.05 for a\n            damping ratio of 5%.\n        tf : array_like, optional\n            Transfer function to be applied to motion prior calculation of the\n            oscillator response.\n\n        Returns\n        -------\n        spec_accels : :class:`numpy.ndarray`\n            Peak pseudo-spectral acceleration of the oscillator"
  },
  {
    "code": "def letter2num(letters, zbase=False):\n    letters = letters.upper()\n    res = 0\n    weight = len(letters) - 1\n    assert weight >= 0, letters\n    for i, c in enumerate(letters):\n        assert 65 <= ord(c) <= 90, c\n        res += (ord(c) - 64) * 26**(weight - i)\n    if not zbase:\n        return res\n    return res - 1",
    "docstring": "A = 1, C = 3 and so on. Convert spreadsheet style column\n    enumeration to a number.\n\n    Answers:\n    A = 1, Z = 26, AA = 27, AZ = 52, ZZ = 702, AMJ = 1024\n\n    >>> from channelpack.pullxl import letter2num\n\n    >>> letter2num('A') == 1\n    True\n    >>> letter2num('Z') == 26\n    True\n    >>> letter2num('AZ') == 52\n    True\n    >>> letter2num('ZZ') == 702\n    True\n    >>> letter2num('AMJ') == 1024\n    True\n    >>> letter2num('AMJ', zbase=True) == 1023\n    True\n    >>> letter2num('A', zbase=True) == 0\n    True"
  },
  {
    "code": "def generate_term(self, **kwargs):\n        term_map = kwargs.pop('term_map')\n        if hasattr(term_map, \"termType\") and\\\n            term_map.termType == NS_MGR.rr.BlankNode.rdflib:\n            return rdflib.BNode()\n        if not hasattr(term_map, 'datatype'):\n            term_map.datatype = NS_MGR.xsd.anyURI.rdflib\n        if hasattr(term_map, \"template\") and term_map.template is not None:\n            template_vars = kwargs\n            template_vars.update(self.constants)\n            for key, value in template_vars.items():\n                if hasattr(value, \"__call__\"):\n                    template_vars[key] = value()\n            raw_value = term_map.template.format(**template_vars)\n            if term_map.datatype == NS_MGR.xsd.anyURI.rdflib:\n                return rdflib.URIRef(raw_value)\n            return rdflib.Literal(raw_value,\n                                  datatype=term_map.datatype)\n        if term_map.reference is not None:\n            return self.__generate_reference__(term_map, **kwargs)",
    "docstring": "Method generates a rdflib.Term based on kwargs"
  },
  {
    "code": "def _wait_for_finishing(self):\n        self.state_machine_running = True\n        self.__running_state_machine.join()\n        self.__set_execution_mode_to_finished()\n        self.state_machine_manager.active_state_machine_id = None\n        plugins.run_on_state_machine_execution_finished()\n        self.state_machine_running = False",
    "docstring": "Observe running state machine and stop engine if execution has finished"
  },
  {
    "code": "def _finalize(self, all_msg_errors=None):\n        if all_msg_errors is None:\n            all_msg_errors = []\n        for key in self.stored():\n            try:\n                getattr(self, key)\n            except (ValueError, TypeError) as err:\n                all_msg_errors.append(err.args[0])\n        if all_msg_errors:\n            raise ValueError(all_msg_errors)",
    "docstring": "Access all the instance descriptors\n\n        This wil trigger an exception if a required\n        parameter is not set"
  },
  {
    "code": "def get_mem(device_handle):\n    try:\n        memory_info = pynvml.nvmlDeviceGetMemoryInfo(device_handle)\n        return memory_info.used * 100.0 / memory_info.total\n    except pynvml.NVMLError:\n        return None",
    "docstring": "Get GPU device memory consumption in percent."
  },
  {
    "code": "def sum(self, axis=None, keepdims=False):\n        return self.numpy().sum(axis=axis, keepdims=keepdims)",
    "docstring": "Return sum along specified axis"
  },
  {
    "code": "def from_fs_path(path):\n    scheme = 'file'\n    params, query, fragment = '', '', ''\n    path, netloc = _normalize_win_path(path)\n    return urlunparse((scheme, netloc, path, params, query, fragment))",
    "docstring": "Returns a URI for the given filesystem path."
  },
  {
    "code": "def GetOutputClasses(cls):\n    for _, output_class in iter(cls._output_classes.items()):\n      yield output_class.NAME, output_class",
    "docstring": "Retrieves the available output classes its associated name.\n\n    Yields:\n      tuple[str, type]: output class name and type object."
  },
  {
    "code": "def to_xml_string(self):\n        self.update_xml_element()\n        xml = self.xml_element\n        return etree.tostring(xml, pretty_print=True).decode('utf-8')",
    "docstring": "Exports the element in XML format.\n\n        :returns: element in XML format.\n        :rtype: str"
  },
  {
    "code": "def update(self, id, name=None, description=None, image_url=None,\n               office_mode=None, share=None, **kwargs):\n        path = '{}/update'.format(id)\n        url = utils.urljoin(self.url, path)\n        payload = {\n            'name': name,\n            'description': description,\n            'image_url': image_url,\n            'office_mode': office_mode,\n            'share': share,\n        }\n        payload.update(kwargs)\n        response = self.session.post(url, json=payload)\n        return Group(self, **response.data)",
    "docstring": "Update the details of a group.\n\n        .. note::\n\n            There are significant bugs in this endpoint!\n            1. not providing ``name`` produces 400: \"Topic can't be blank\"\n            2. not providing ``office_mode`` produces 500: \"sql: Scan error on\n            column index 14: sql/driver: couldn't convert <nil> (<nil>) into\n            type bool\"\n\n            Note that these issues are \"handled\" automatically when calling\n            update on a :class:`~groupy.api.groups.Group` object.\n\n        :param str id: group ID\n        :param str name: group name (140 characters maximum)\n        :param str description: short description (255 characters maximum)\n        :param str image_url: GroupMe image service URL\n        :param bool office_mode: (undocumented)\n        :param bool share: whether to generate a share URL\n        :return: an updated group\n        :rtype: :class:`~groupy.api.groups.Group`"
  },
  {
    "code": "def add(self, logical_id, property, value):\n        if not logical_id or not property:\n            raise ValueError(\"LogicalId and property must be a non-empty string\")\n        if not value or not isinstance(value, string_types):\n            raise ValueError(\"Property value must be a non-empty string\")\n        if logical_id not in self._refs:\n            self._refs[logical_id] = {}\n        if property in self._refs[logical_id]:\n            raise ValueError(\"Cannot add second reference value to {}.{} property\".format(logical_id, property))\n        self._refs[logical_id][property] = value",
    "docstring": "Add the information that resource with given `logical_id` supports the given `property`, and that a reference\n        to `logical_id.property` resolves to given `value.\n\n        Example:\n\n            \"MyApi.Deployment\" -> \"MyApiDeployment1234567890\"\n\n        :param logical_id: Logical ID of the resource  (Ex: MyLambdaFunction)\n        :param property: Property on the resource that can be referenced (Ex: Alias)\n        :param value: Value that this reference resolves to.\n        :return: nothing"
  },
  {
    "code": "def getitem(self, index, context=None):\n        try:\n            methods = dunder_lookup.lookup(self, \"__getitem__\")\n        except exceptions.AttributeInferenceError as exc:\n            raise exceptions.AstroidTypeError(node=self, context=context) from exc\n        method = methods[0]\n        new_context = contextmod.bind_context_to_node(context, self)\n        new_context.callcontext = contextmod.CallContext(args=[index])\n        try:\n            return next(method.infer_call_result(self, new_context))\n        except exceptions.InferenceError:\n            return util.Uninferable",
    "docstring": "Return the inference of a subscript.\n\n        This is basically looking up the method in the metaclass and calling it.\n\n        :returns: The inferred value of a subscript to this class.\n        :rtype: NodeNG\n\n        :raises AstroidTypeError: If this class does not define a\n            ``__getitem__`` method."
  },
  {
    "code": "def users_setPhoto(self, *, image: Union[str, IOBase], **kwargs) -> SlackResponse:\n        self._validate_xoxp_token()\n        return self.api_call(\"users.setPhoto\", files={\"image\": image}, data=kwargs)",
    "docstring": "Set the user profile photo\n\n        Args:\n            image (str): Supply the path of the image you'd like to upload.\n                e.g. 'myimage.png'"
  },
  {
    "code": "async def enable_events(self) -> asyncio.Task:\n        return await self._connection.ws_connect(\n            on_message=self._ws_on_message, on_error=self._ws_on_error\n        )",
    "docstring": "Connects to the websocket. Returns a listening task."
  },
  {
    "code": "def mutate_rows(self, rows, retry=DEFAULT_RETRY):\n        retryable_mutate_rows = _RetryableMutateRowsWorker(\n            self._instance._client,\n            self.name,\n            rows,\n            app_profile_id=self._app_profile_id,\n            timeout=self.mutation_timeout,\n        )\n        return retryable_mutate_rows(retry=retry)",
    "docstring": "Mutates multiple rows in bulk.\n\n        For example:\n\n        .. literalinclude:: snippets_table.py\n            :start-after: [START bigtable_mutate_rows]\n            :end-before: [END bigtable_mutate_rows]\n\n        The method tries to update all specified rows.\n        If some of the rows weren't updated, it would not remove mutations.\n        They can be applied to the row separately.\n        If row mutations finished successfully, they would be cleaned up.\n\n        Optionally, a ``retry`` strategy can be specified to re-attempt\n        mutations on rows that return transient errors. This method will retry\n        until all rows succeed or until the request deadline is reached. To\n        specify a ``retry`` strategy of \"do-nothing\", a deadline of ``0.0``\n        can be specified.\n\n        :type rows: list\n        :param rows: List or other iterable of :class:`.DirectRow` instances.\n\n        :type retry: :class:`~google.api_core.retry.Retry`\n        :param retry:\n            (Optional) Retry delay and deadline arguments. To override, the\n            default value :attr:`DEFAULT_RETRY` can be used and modified with\n            the :meth:`~google.api_core.retry.Retry.with_delay` method or the\n            :meth:`~google.api_core.retry.Retry.with_deadline` method.\n\n        :rtype: list\n        :returns: A list of response statuses (`google.rpc.status_pb2.Status`)\n                  corresponding to success or failure of each row mutation\n                  sent. These will be in the same order as the `rows`."
  },
  {
    "code": "def table_drop(self):\n        for engine in self.engines():\n            tables = self._get_tables(engine, create_drop=True)\n            logger.info('Drop all tables for %s', engine)\n            self.metadata.drop_all(engine, tables=tables)",
    "docstring": "Drops all tables."
  },
  {
    "code": "def _generate_collection(group, ax, ctype, colors):\n    color = TREE_COLOR[ctype]\n    collection = PolyCollection(group, closed=False, antialiaseds=True,\n                                edgecolors='face', facecolors=color)\n    ax.add_collection(collection)\n    if color not in colors:\n        label = str(ctype).replace('NeuriteType.', '').replace('_', ' ').capitalize()\n        ax.plot((0., 0.), (0., 0.), c=color, label=label)\n        colors.add(color)",
    "docstring": "Render rectangle collection"
  },
  {
    "code": "def dispatch_hook(cls, _pkt=None, *args, **kargs):\n        if _pkt:\n            attr_type = orb(_pkt[0])\n            return cls.registered_attributes.get(attr_type, cls)\n        return cls",
    "docstring": "Returns the right RadiusAttribute class for the given data."
  },
  {
    "code": "def _serialize(self, value, attr, obj):\n        value = super(PhoneNumberField, self)._serialize(value, attr, obj)\n        if value:\n            value = self._format_phone_number(value, attr)\n        return value",
    "docstring": "Format and validate the phone number user libphonenumber."
  },
  {
    "code": "def uniquecols(df):\n    bool_idx = df.apply(lambda col: len(np.unique(col)) == 1, axis=0)\n    df = df.loc[:, bool_idx].iloc[0:1, :].reset_index(drop=True)\n    return df",
    "docstring": "Return unique columns\n\n    This is used for figuring out which columns are\n    constant within a group"
  },
  {
    "code": "def _latex_labels(self, labels):\n        config = self._configuration.get(\"latex_labels\", {})\n        return [config.get(label, label) for label in labels]",
    "docstring": "LaTeX-ify labels based on information provided in the configuration."
  },
  {
    "code": "def check_learns_zero_output_rnn(model, sgd, X, Y, initial_hidden=None):\n    outputs, get_dX = model.begin_update(X, initial_hidden)\n    Yh, h_n = outputs\n    tupleDy = (Yh - Y, h_n)\n    dX = get_dX(tupleDy, sgd=sgd)\n    prev = numpy.abs(Yh.sum())\n    print(prev)\n    for i in range(1000):\n        outputs, get_dX = model.begin_update(X)\n        Yh, h_n = outputs\n        current_sum = numpy.abs(Yh.sum())\n        tupleDy = (Yh - Y, h_n)\n        dX = get_dX(tupleDy, sgd=sgd)\n    print(current_sum)",
    "docstring": "Check we can learn to output a zero vector"
  },
  {
    "code": "def get_one_ping_per_client(pings):\n    if isinstance(pings.first(), binary_type):\n        pings = pings.map(lambda p: json.loads(p.decode('utf-8')))\n    filtered = pings.filter(lambda p: \"clientID\" in p or \"clientId\" in p)\n    if not filtered:\n        raise ValueError(\"Missing clientID/clientId attribute.\")\n    if \"clientID\" in filtered.first():\n        client_id = \"clientID\"\n    else:\n        client_id = \"clientId\"\n    return filtered.map(lambda p: (p[client_id], p)) \\\n                   .reduceByKey(lambda p1, p2: p1) \\\n                   .map(lambda p: p[1])",
    "docstring": "Returns a single ping for each client in the RDD.\n\n    THIS METHOD IS NOT RECOMMENDED: The ping to be returned is essentially\n    selected at random. It is also expensive as it requires data to be\n    shuffled around. It should be run only after extracting a subset with\n    get_pings_properties."
  },
  {
    "code": "def delete_function(FunctionName, Qualifier=None, region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        if Qualifier:\n            conn.delete_function(\n                FunctionName=FunctionName, Qualifier=Qualifier)\n        else:\n            conn.delete_function(FunctionName=FunctionName)\n        return {'deleted': True}\n    except ClientError as e:\n        return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Given a function name and optional version qualifier, delete it.\n\n    Returns {deleted: true} if the function was deleted and returns\n    {deleted: false} if the function was not deleted.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_lambda.delete_function myfunction"
  },
  {
    "code": "def replace_orig_field(self, option):\n        if option:\n            option_new = list(option)\n            for opt in option:\n                if opt in self.trans_opts.fields:\n                    index = option_new.index(opt)\n                    option_new[index:index + 1] = get_translation_fields(opt)\n                elif isinstance(opt, (tuple, list)) and (\n                        [o for o in opt if o in self.trans_opts.fields]):\n                    index = option_new.index(opt)\n                    option_new[index:index + 1] = self.replace_orig_field(opt)\n            option = option_new\n        return option",
    "docstring": "Replaces each original field in `option` that is registered for\n        translation by its translation fields.\n\n        Returns a new list with replaced fields. If `option` contains no\n        registered fields, it is returned unmodified.\n\n        >>> self = TranslationAdmin()  # PyFlakes\n        >>> print(self.trans_opts.fields.keys())\n        ['title',]\n        >>> get_translation_fields(self.trans_opts.fields.keys()[0])\n        ['title_de', 'title_en']\n        >>> self.replace_orig_field(['title', 'url'])\n        ['title_de', 'title_en', 'url']\n\n        Note that grouped fields are flattened. We do this because:\n\n            1. They are hard to handle in the jquery-ui tabs implementation\n            2. They don't scale well with more than a few languages\n            3. It's better than not handling them at all (okay that's weak)\n\n        >>> self.replace_orig_field((('title', 'url'), 'email', 'text'))\n        ['title_de', 'title_en', 'url_de', 'url_en', 'email_de', 'email_en', 'text']"
  },
  {
    "code": "def splitext(filepath):\n    exts = getattr(CRE_FILENAME_EXT.search(filepath), 'group', str)()\n    return (filepath[:(-len(exts) or None)], exts)",
    "docstring": "Like os.path.splitext except splits compound extensions as one long one\n\n    >>> splitext('~/.bashrc.asciidoc.ext.ps4.42')\n    ('~/.bashrc', '.asciidoc.ext.ps4.42')\n    >>> splitext('~/.bash_profile')\n    ('~/.bash_profile', '')"
  },
  {
    "code": "def stringify(obj):\n    out = obj\n    if isinstance(obj, uuid.UUID):\n        out = str(obj)\n    elif hasattr(obj, 'strftime'):\n        out = obj.strftime('%Y-%m-%dT%H:%M:%S.%f%z')\n    elif isinstance(obj, memoryview):\n        out = obj.tobytes()\n    elif isinstance(obj, bytearray):\n        out = bytes(obj)\n    elif sys.version_info[0] < 3 and isinstance(obj, buffer):\n        out = bytes(obj)\n    if isinstance(out, bytes):\n        out = out.decode('utf-8')\n    return out",
    "docstring": "Return the string representation of an object.\n\n    :param obj: object to get the representation of\n    :returns: unicode string representation of `obj` or `obj` unchanged\n\n    This function returns a string representation for many of the\n    types from the standard library.  It does not convert numeric or\n    Boolean values to strings -- it only converts non-primitive instances\n    such as :class:`datetime.datetime`.  The following table describes\n    the types that are handled and describes how they are represented.\n\n    +----------------------------+--------------------------------------------+\n    | Class                      | Behavior                                   |\n    +============================+============================================+\n    | :class:`uuid.UUID`         | ``str(obj)``                               |\n    +----------------------------+--------------------------------------------+\n    | :class:`datetime.datetime` | ``obj.strftime('%Y-%m-%dT%H:%M:%S.%f%z')`` |\n    +----------------------------+--------------------------------------------+\n    | :class:`memoryview`        | ``obj.tobytes().decode('utf-8')``          |\n    +----------------------------+--------------------------------------------+\n    | :class:`bytearray`         | ``bytes(obj).decode('utf-8')``             |\n    +----------------------------+--------------------------------------------+\n    | :class:`buffer`            | ``bytes(obj).decode('utf-8')``             |\n    +----------------------------+--------------------------------------------+\n    | :class:`bytes`             | ``obj.decode('utf-8')``                    |\n    +----------------------------+--------------------------------------------+\n\n    Other types are returned unharmed."
  },
  {
    "code": "def _ps_extract_pid(self, line):\n        this_pid = self.regex['pid'].sub(r'\\g<1>', line)\n        this_parent = self.regex['parent'].sub(r'\\g<1>', line)\n        return this_pid, this_parent",
    "docstring": "Extract PID and parent PID from an output line from the PS command"
  },
  {
    "code": "def closed(self):\n        closed = self._closing or self._closed\n        if not closed and self._reader and self._reader.at_eof():\n            self._closing = closed = True\n            self._loop.call_soon(self._do_close, None)\n        return closed",
    "docstring": "True if connection is closed."
  },
  {
    "code": "def extract_rzip (archive, compression, cmd, verbosity, interactive, outdir):\n    cmdlist = [cmd, '-d', '-k']\n    if verbosity > 1:\n        cmdlist.append('-v')\n    outfile = util.get_single_outfile(outdir, archive)\n    cmdlist.extend([\"-o\", outfile, archive])\n    return cmdlist",
    "docstring": "Extract an RZIP archive."
  },
  {
    "code": "def byte_to_housecode(bytecode):\n    hc = list(HC_LOOKUP.keys())[list(HC_LOOKUP.values()).index(bytecode)]\n    return hc.upper()",
    "docstring": "Return an X10 housecode value from a byte value."
  },
  {
    "code": "def processor_coordinates_to_pnum(mesh_shape, coord):\n  ret = 0\n  multiplier = 1\n  for c, d in zip(coord[::-1], mesh_shape.to_integer_list[::-1]):\n    ret += multiplier * c\n    multiplier *= d\n  return ret",
    "docstring": "Inverse of pnum_to_processor_coordinates.\n\n  Args:\n    mesh_shape: a Shape\n    coord: a list of integers with length len(mesh_shape)\n\n  Returns:\n    an integer less than len(mesh_shape)"
  },
  {
    "code": "def register_action (self, action_name, command='', bound_list = [], flags = [],\n                         function = None):\n        assert isinstance(action_name, basestring)\n        assert isinstance(command, basestring)\n        assert is_iterable(bound_list)\n        assert is_iterable(flags)\n        assert function is None or callable(function)\n        bjam_flags = reduce(operator.or_,\n                            (action_modifiers[flag] for flag in flags), 0)\n        assert command or function\n        if command:\n            bjam_interface.define_action(action_name, command, bound_list, bjam_flags)\n        self.actions[action_name] = BjamAction(\n            action_name, function, has_command=bool(command))",
    "docstring": "Creates a new build engine action.\n\n        Creates on bjam side an action named 'action_name', with\n        'command' as the command to be executed, 'bound_variables'\n        naming the list of variables bound when the command is executed\n        and specified flag.\n        If 'function' is not None, it should be a callable taking three\n        parameters:\n            - targets\n            - sources\n            - instance of the property_set class\n        This function will be called by set_update_action, and can\n        set additional target variables."
  },
  {
    "code": "def _default_next_char(particle):\n        return particle.chars[\n            (len(particle.chars) - 1) * particle.time // particle.life_time]",
    "docstring": "Default next character implementation - linear progression through\n        each character."
  },
  {
    "code": "def process_file(vcs, commit, force, gitlint_config, file_data):\n    filename, extra_data = file_data\n    if force:\n        modified_lines = None\n    else:\n        modified_lines = vcs.modified_lines(\n            filename, extra_data, commit=commit)\n    result = linters.lint(filename, modified_lines, gitlint_config)\n    result = result[filename]\n    return filename, result",
    "docstring": "Lint the file\n\n    Returns:\n      The results from the linter."
  },
  {
    "code": "def write(self, *messages):\n        for i in self.graph.outputs_of(BEGIN):\n            for message in messages:\n                self[i].write(message)",
    "docstring": "Push a list of messages in the inputs of this graph's inputs, matching the output of special node \"BEGIN\" in\n        our graph."
  },
  {
    "code": "def fix_type(typ, size, additional=None):\n    if additional is not None:\n        my_types = types + additional\n    else:\n        my_types = types\n    for t, info in my_types:\n        if callable(t):\n            matches = t(typ)\n        else:\n            matches = t == typ\n        if matches:\n            if callable(info):\n                fmt_str, true_size = info(size)\n            else:\n                fmt_str, true_size = info\n            assert size == true_size, ('{}: Got size {} instead of {}'.format(typ, size,\n                                                                              true_size))\n            return fmt_str.format(size=size)\n    raise ValueError('No type match! ({})'.format(typ))",
    "docstring": "Fix up creating the appropriate struct type based on the information in the column."
  },
  {
    "code": "def secret_list(backend,path):\n    click.echo(click.style('%s - Getting the list of secrets' % get_datetime(), fg='green'))\n    check_and_print(\n        DKCloudCommandRunner.secret_list(backend.dki,path))",
    "docstring": "List all Secrets"
  },
  {
    "code": "def images(self, filter='global'):\n        if filter and filter not in ('my_images', 'global'):\n            raise DOPException('\"filter\" must be either \"my_images\" or \"global\"')\n        params = {}\n        if filter:\n            params['filter'] = filter\n        json = self.request('/images', method='GET', params=params)\n        status = json.get('status')\n        if status == 'OK':\n            images_json = json.get('images', [])\n            images = [Image.from_json(image) for image in images_json]\n            return images\n        else:\n            message = json.get('message')\n            raise DOPException('[%s]: %s' % (status, message))",
    "docstring": "This method returns all the available images that can be accessed by\n        your client ID. You will have access to all public images by default,\n        and any snapshots or backups that you have created in your own account.\n\n        Optional parameters\n\n            filter:\n                String, either \"my_images\" or \"global\""
  },
  {
    "code": "def validate(self, raise_unsupported=False):\n        fields = set(self.keys())\n        flattened_required_fields = set()\n        required_errors = []\n        for field in self.required_fields:\n            found = False\n            if isinstance(field, (list, tuple)):\n                for real_f in field:\n                    if real_f in fields:\n                        flattened_required_fields.add(real_f)\n                        found = True\n            else:\n                flattened_required_fields.add(field)\n                if field in fields:\n                    found = True\n            if not found:\n                required_errors.append(field)\n        unsupported_fields = fields - flattened_required_fields \\\n                - set(self.optional_fields)\n        if len(required_errors) or (raise_unsupported\n                and len(unsupported_fields)):\n            raise exceptions.InvalidStructure(\"Missing or unsupported fields found\",\n                    required_fields=required_errors,\n                    unsupported_fields=unsupported_fields)",
    "docstring": "Checks if the Entry instance includes all the required fields of its\n        type. If ``raise_unsupported`` is set to ``True`` it will also check\n        for potentially unsupported types.\n\n        If a problem is found, an InvalidStructure exception is raised."
  },
  {
    "code": "def intercalate(elems, list_):\n    ensure_sequence(elems)\n    ensure_sequence(list_)\n    if len(list_) <= 1:\n        return list_\n    return sum(\n        (elems + list_[i:i+1] for i in xrange(1, len(list_))),\n        list_[:1])",
    "docstring": "Insert given elements between existing elements of a list.\n\n    :param elems: List of elements to insert between elements of ``list_`\n    :param list_: List to insert the elements to\n\n    :return: A new list where items from ``elems`` are inserted\n             between every two elements of ``list_``"
  },
  {
    "code": "def to_bytes(s):\n    if isinstance(s, six.binary_type):\n        return s\n    if isinstance(s, six.string_types):\n        return s.encode('utf-8')\n    raise TypeError('want string or bytes, got {}', type(s))",
    "docstring": "Return s as a bytes type, using utf-8 encoding if necessary.\n    @param s string or bytes\n    @return bytes"
  },
  {
    "code": "def unique(segments, digits=5):\n    segments = np.asanyarray(segments, dtype=np.float64)\n    inverse = grouping.unique_rows(\n        segments.reshape((-1, segments.shape[2])),\n        digits=digits)[1].reshape((-1, 2))\n    inverse.sort(axis=1)\n    index = grouping.unique_rows(inverse)\n    unique = segments[index[0]]\n    return unique",
    "docstring": "Find unique line segments.\n\n    Parameters\n    ------------\n    segments : (n, 2, (2|3)) float\n      Line segments in space\n    digits : int\n      How many digits to consider when merging vertices\n\n    Returns\n    -----------\n    unique : (m, 2, (2|3)) float\n      Segments with duplicates merged"
  },
  {
    "code": "def url(self, name):\n        key = blobstore.create_gs_key('/gs' + name)\n        return images.get_serving_url(key)",
    "docstring": "Ask blobstore api for an url to directly serve the file"
  },
  {
    "code": "def update_dimensions(self, dims):\n        if isinstance(dims, collections.Mapping):\n            dims = dims.itervalues()\n        for dim in dims:\n            if isinstance(dim, dict):\n                self.update_dimension(**dim)\n            elif isinstance(dim, Dimension):\n                self._dims[dim.name] = dim\n            else:\n                raise TypeError(\"Unhandled type '{t}'\"\n                    \"in update_dimensions\".format(t=type(dim)))",
    "docstring": "Update multiple dimension on the cube.\n\n        .. code-block:: python\n\n            cube.update_dimensions([\n                {'name' : 'ntime', 'global_size' : 10,\n                'lower_extent' : 2, 'upper_extent' : 7 },\n                {'name' : 'na', 'global_size' : 3,\n                'lower_extent' : 2, 'upper_extent' : 7 },\n            ])\n\n        Parameters\n        ----------\n        dims : list or dict:\n            A list or dictionary of dimension updates"
  },
  {
    "code": "def open(filename, frame='unspecified'):\n        data = Image.load_data(filename).astype(np.uint8)\n        return ColorImage(data, frame)",
    "docstring": "Creates a ColorImage from a file.\n\n        Parameters\n        ----------\n        filename : :obj:`str`\n            The file to load the data from. Must be one of .png, .jpg,\n            .npy, or .npz.\n\n        frame : :obj:`str`\n            A string representing the frame of reference in which the new image\n            lies.\n\n        Returns\n        -------\n        :obj:`ColorImage`\n            The new color image."
  },
  {
    "code": "def add_book(self, publisher=None, place=None, date=None):\n        imprint = {}\n        if date is not None:\n            imprint['date'] = normalize_date(date)\n        if place is not None:\n            imprint['place'] = place\n        if publisher is not None:\n            imprint['publisher'] = publisher\n        self._append_to('imprints', imprint)",
    "docstring": "Make a dictionary that is representing a book.\n\n        :param publisher: publisher name\n\n        :type publisher: string\n\n        :param place: place of publication\n        :type place: string\n\n        :param date: A (partial) date in any format.\n            The date should contain at least a year\n        :type date: string\n\n        :rtype: dict"
  },
  {
    "code": "async def set_max_relative_mod(self, max_mod,\n                                   timeout=OTGW_DEFAULT_TIMEOUT):\n        if isinstance(max_mod, int) and not 0 <= max_mod <= 100:\n            return None\n        cmd = OTGW_CMD_MAX_MOD\n        status = {}\n        ret = await self._wait_for_cmd(cmd, max_mod, timeout)\n        if ret not in ['-', None]:\n            ret = int(ret)\n        if ret == '-':\n            status[DATA_SLAVE_MAX_RELATIVE_MOD] = None\n        else:\n            status[DATA_SLAVE_MAX_RELATIVE_MOD] = ret\n        self._update_status(status)\n        return ret",
    "docstring": "Override the maximum relative modulation from the thermostat.\n        Valid values are 0 through 100. Clear the setting by specifying\n        a non-numeric value.\n        Return the newly accepted value, '-' if a previous value was\n        cleared, or None on failure.\n\n        This method is a coroutine"
  },
  {
    "code": "def find_module_registrations(c_file):\n    global pattern\n    if c_file is None:\n        return set()\n    with io.open(c_file, encoding='utf-8') as c_file_obj:\n        return set(re.findall(pattern, c_file_obj.read()))",
    "docstring": "Find any MP_REGISTER_MODULE definitions in the provided c file.\n\n    :param str c_file: path to c file to check\n    :return: List[(module_name, obj_module, enabled_define)]"
  },
  {
    "code": "def gui_call(self, method, *args, **kwdargs):\n        my_id = thread.get_ident()\n        if my_id == self.gui_thread_id:\n            return method(*args, **kwdargs)\n        else:\n            future = self.gui_do(method, *args, **kwdargs)\n            return future.wait()",
    "docstring": "General method for synchronously calling into the GUI.\n        This waits until the method has completed before returning."
  },
  {
    "code": "def maybe_reverse_features(self, feature_map):\n    if not self._was_reversed:\n      return\n    inputs = feature_map.pop(\"inputs\", None)\n    targets = feature_map.pop(\"targets\", None)\n    inputs_seg = feature_map.pop(\"inputs_segmentation\", None)\n    targets_seg = feature_map.pop(\"targets_segmentation\", None)\n    inputs_pos = feature_map.pop(\"inputs_position\", None)\n    targets_pos = feature_map.pop(\"targets_position\", None)\n    if inputs is not None:\n      feature_map[\"targets\"] = inputs\n    if targets is not None:\n      feature_map[\"inputs\"] = targets\n    if inputs_seg is not None:\n      feature_map[\"targets_segmentation\"] = inputs_seg\n    if targets_seg is not None:\n      feature_map[\"inputs_segmentation\"] = targets_seg\n    if inputs_pos is not None:\n      feature_map[\"targets_position\"] = inputs_pos\n    if targets_pos is not None:\n      feature_map[\"inputs_position\"] = targets_pos",
    "docstring": "Reverse features between inputs and targets if the problem is '_rev'."
  },
  {
    "code": "def _create_index(self):\n        if not self.index_exists:\n            index_settings = {}\n            headers = {'Content-Type': 'application/json', 'DB-Method': 'POST'}\n            url = '/v2/exchange/db/{}/{}'.format(self.domain, self.data_type)\n            r = self.tcex.session.post(url, json=index_settings, headers=headers)\n            if not r.ok:\n                error = r.text or r.reason\n                self.tcex.handle_error(800, [r.status_code, error])\n            self.tcex.log.debug(\n                'creating index. status_code: {}, response: \"{}\".'.format(r.status_code, r.text)\n            )",
    "docstring": "Create index if it doesn't exist."
  },
  {
    "code": "def vecdiff(htilde, hinterp, sample_points, psd=None):\n    vecdiffs = numpy.zeros(sample_points.size-1, dtype=float)\n    for kk,thisf in enumerate(sample_points[:-1]):\n        nextf = sample_points[kk+1]\n        vecdiffs[kk] = abs(_vecdiff(htilde, hinterp, thisf, nextf, psd=psd))\n    return vecdiffs",
    "docstring": "Computes a statistic indicating between which sample points a waveform\n    and the interpolated waveform differ the most."
  },
  {
    "code": "def decode(codec, stream, image):\n    OPENJP2.opj_decode.argtypes = [CODEC_TYPE, STREAM_TYPE_P,\n                                   ctypes.POINTER(ImageType)]\n    OPENJP2.opj_decode.restype = check_error\n    OPENJP2.opj_decode(codec, stream, image)",
    "docstring": "Reads an entire image.\n\n    Wraps the openjp2 library function opj_decode.\n\n    Parameters\n    ----------\n    codec : CODEC_TYPE\n        The JPEG2000 codec\n    stream : STREAM_TYPE_P\n        The stream to decode.\n    image : ImageType\n        Output image structure.\n\n    Raises\n    ------\n    RuntimeError\n        If the OpenJPEG library routine opj_decode fails."
  },
  {
    "code": "def _append_theme_dir(self, name):\n        path = \"[{}]\".format(get_file_directory() + \"/\" + name)\n        self.tk.call(\"lappend\", \"auto_path\", path)",
    "docstring": "Append a theme dir to the Tk interpreter auto_path"
  },
  {
    "code": "def go_to_marker(self, row, col, table_type):\n        if table_type == 'dataset':\n            marker_time = self.idx_marker.property('start')[row]\n            marker_end_time = self.idx_marker.property('end')[row]\n        else:\n            marker_time = self.idx_annot_list.property('start')[row]\n            marker_end_time = self.idx_annot_list.property('end')[row]\n        window_length = self.parent.value('window_length')\n        if self.parent.traces.action['centre_event'].isChecked():\n            window_start = (marker_time + marker_end_time - window_length) / 2\n        else:\n            window_start = floor(marker_time / window_length) * window_length\n        self.parent.overview.update_position(window_start)\n        if table_type == 'annot':\n            for annot in self.parent.traces.idx_annot:\n                if annot.marker.x() == marker_time:\n                    self.parent.traces.highlight_event(annot)\n                    break",
    "docstring": "Move to point in time marked by the marker.\n\n        Parameters\n        ----------\n        row : QtCore.int\n\n        column : QtCore.int\n\n        table_type : str\n            'dataset' table or 'annot' table, it works on either"
  },
  {
    "code": "def stop_all_periodic_tasks(self, remove_tasks=True):\n        for task in self._periodic_tasks:\n            task.stop(remove_task=remove_tasks)",
    "docstring": "Stop sending any messages that were started using bus.send_periodic\n\n        :param bool remove_tasks:\n            Stop tracking the stopped tasks."
  },
  {
    "code": "def wrap_around_re(aClass, wildcard, advice):\n    matcher = re.compile(wildcard)\n    for aMember in dir(aClass):\n        realMember = getattr(aClass, aMember)\n        if callable(realMember) and aMember[:6]!=\"__wrap\" and \\\n           aMember[:9]!=\"__proceed\" and \\\n           matcher.match(aMember):\n            wrap_around(realMember, advice)",
    "docstring": "Same as wrap_around but works with regular expression based\n    wildcards to map which methods are going to be used."
  },
  {
    "code": "def kwargstr(self):\n\t\ttemp = [' [--' + k + (' ' + str(v) if v is not False else '') + ']' for k, v in self.defaults.items()]\n\t\treturn ''.join(temp)",
    "docstring": "Concatenate keyword arguments into a string."
  },
  {
    "code": "def lookup(self, name: str):\n        if name in self._moduleMap:\n            return self._moduleMap[name]\n        (module_name, type_name, fragment_name) = self.split_typename(name)\n        if not module_name and type_name:\n            click.secho('not able to lookup symbol: {0}'.format(name), fg='red')\n            return None\n        module = self._moduleMap[module_name]\n        return module.lookup(type_name, fragment_name)",
    "docstring": "lookup a symbol by fully qualified name."
  },
  {
    "code": "def wnvald(insize, n, window):\n    assert isinstance(window, stypes.SpiceCell)\n    assert window.dtype == 1\n    insize = ctypes.c_int(insize)\n    n = ctypes.c_int(n)\n    libspice.wnvald_c(insize, n, ctypes.byref(window))\n    return window",
    "docstring": "Form a valid double precision window from the contents\n    of a window array.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnvald_c.html\n\n    :param insize: Size of window. \n    :type insize: int\n    :param n: Original number of endpoints. \n    :type n: int\n    :param window: Input window. \n    :type window: spiceypy.utils.support_types.SpiceCell\n    :return: The union of the intervals in the input cell.\n    :rtype: spiceypy.utils.support_types.SpiceCell"
  },
  {
    "code": "def parse(response):\n        tokens = {r[0]: r[1] for r in [r.split('=') for r in response.split(\"&\")]}\n        if 'dummy' in tokens:\n            del tokens['dummy']\n        if re.match('\\D\\d+$', tokens.keys()[0]):\n            set_tokens = []\n            for key, value in tokens:\n                key = re.match('^(.+\\D)(\\d+)$', key)\n                if key is not None:\n                    if key.group(1) not in set_tokens:\n                        set_tokens[key.group(1)] = {}\n                    set_tokens[key.group(1)][key.group(0).rstrip('_')] = value\n            tokens = set_tokens\n        return tokens",
    "docstring": "Parse a postdata-style response format from the API into usable data"
  },
  {
    "code": "def get_ports(self, scan_id, target):\n        if target:\n            for item in self.scans_table[scan_id]['targets']:\n                if target == item[0]:\n                    return item[1]\n        return self.scans_table[scan_id]['targets'][0][1]",
    "docstring": "Get a scan's ports list. If a target is specified\n        it will return the corresponding port for it. If not,\n        it returns the port item of the first nested list in\n        the target's list."
  },
  {
    "code": "def UpdateInfo(self):\n        ret = vmGuestLib.VMGuestLib_UpdateInfo(self.handle.value)\n        if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)",
    "docstring": "Updates information about the virtual machine. This information is associated with\n           the VMGuestLibHandle.\n\n           VMGuestLib_UpdateInfo requires similar CPU resources to a system call and\n           therefore can affect performance. If you are concerned about performance, minimize\n           the number of calls to VMGuestLib_UpdateInfo.\n\n           If your program uses multiple threads, each thread must use a different handle.\n           Otherwise, you must implement a locking scheme around update calls. The vSphere\n           Guest API does not implement internal locking around access with a handle."
  },
  {
    "code": "def _coerce_topic(topic):\n    if not isinstance(topic, string_types):\n        raise TypeError('topic={!r} must be text'.format(topic))\n    if not isinstance(topic, text_type):\n        topic = topic.decode('ascii')\n    if len(topic) < 1:\n        raise ValueError('invalid empty topic name')\n    if len(topic) > 249:\n        raise ValueError('topic={!r} name is too long: {} > 249'.format(\n            topic, len(topic)))\n    return topic",
    "docstring": "Ensure that the topic name is text string of a valid length.\n\n    :param topic: Kafka topic name. Valid characters are in the set ``[a-zA-Z0-9._-]``.\n    :raises ValueError: when the topic name exceeds 249 bytes\n    :raises TypeError: when the topic is not :class:`unicode` or :class:`str`"
  },
  {
    "code": "def generate(self, chars, format='png'):\n        im = self.generate_image(chars)\n        out = BytesIO()\n        im.save(out, format=format)\n        out.seek(0)\n        return out",
    "docstring": "Generate an Image Captcha of the given characters.\n\n        :param chars: text to be generated.\n        :param format: image file format"
  },
  {
    "code": "def _convert_to_floats(self, data):\n        for key, value in data.items():\n            data[key] = float(value)\n        return data",
    "docstring": "Convert all values in a dict to floats"
  },
  {
    "code": "def load_all(self, group):\n        for ep in iter_entry_points(group=group):\n            plugin = ep.load()\n            plugin(self.__config)",
    "docstring": "Loads all plugins advertising entry points with the given group name.\n        The specified plugin needs to be a callable that accepts the everest\n        configurator as single argument."
  },
  {
    "code": "def fixtags(self, text):\n\t\ttext = _guillemetLeftPat.sub(ur'\\1&nbsp;\\2', text)\n\t\ttext = _guillemetRightPat.sub(ur'\\1&nbsp;', text)\n\t\treturn text",
    "docstring": "Clean up special characters, only run once, next-to-last before doBlockLevels"
  },
  {
    "code": "def save(self):\n        if self.SacrificeDate:\n            self.Active = False\n        super(PlugEvents, self).save()",
    "docstring": "Over-rides the default save function for PlugEvents.\n\n        If a sacrifice date is set for an object in this model, then Active is set to False."
  },
  {
    "code": "def list_subdomains_next_page(self):\n        uri = self._paging.get(\"subdomain\", {}).get(\"next_uri\")\n        if uri is None:\n            raise exc.NoMoreResults(\"There are no more pages of subdomains \"\n                    \"to list.\")\n        return self._list_subdomains(uri)",
    "docstring": "When paging through subdomain results, this will return the next page,\n        using the same limit. If there are no more results, a NoMoreResults\n        exception will be raised."
  },
  {
    "code": "def send(self):\n        self.log.info(\"Saying hello (%d).\" % self.counter)\n        f = stomper.Frame()\n        f.unpack(stomper.send(DESTINATION, 'hello there (%d)' % self.counter))\n        self.counter += 1        \n        self.transport.write(f.pack())",
    "docstring": "Send out a hello message periodically."
  },
  {
    "code": "def lb_edit(lbn, settings, profile='default'):\n    settings['cmd'] = 'update'\n    settings['mime'] = 'prop'\n    settings['w'] = lbn\n    return _do_http(settings, profile)['worker.result.type'] == 'OK'",
    "docstring": "Edit the loadbalancer settings\n\n    Note: http://tomcat.apache.org/connectors-doc/reference/status.html\n    Data Parameters for the standard Update Action\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt '*' modjk.lb_edit loadbalancer1 \"{'vlr': 1, 'vlt': 60}\"\n        salt '*' modjk.lb_edit loadbalancer1 \"{'vlr': 1, 'vlt': 60}\" other-profile"
  },
  {
    "code": "def _extract_jump_targets(stmt):\n        targets = [ ]\n        if isinstance(stmt, ailment.Stmt.Jump):\n            targets.append(stmt.target.value)\n        elif isinstance(stmt, ailment.Stmt.ConditionalJump):\n            targets.append(stmt.true_target.value)\n            targets.append(stmt.false_target.value)\n        return targets",
    "docstring": "Extract goto targets from a Jump or a ConditionalJump statement.\n\n        :param stmt:    The statement to analyze.\n        :return:        A list of known concrete jump targets.\n        :rtype:         list"
  },
  {
    "code": "def build(self):\n        monomers = [HelicalHelix(major_pitch=self.major_pitches[i],\n                                 major_radius=self.major_radii[i],\n                                 major_handedness=self.major_handedness[i],\n                                 aa=self.aas[i],\n                                 minor_helix_type=self.minor_helix_types[i],\n                                 orientation=self.orientations[i],\n                                 phi_c_alpha=self.phi_c_alphas[i],\n                                 minor_repeat=self.minor_repeats[i],\n                                 )\n                    for i in range(self.oligomeric_state)]\n        axis_unit_vector = numpy.array([0, 0, 1])\n        for i, m in enumerate(monomers):\n            m.rotate(angle=self.rotational_offsets[i], axis=axis_unit_vector)\n            m.translate(axis_unit_vector * self.z_shifts[i])\n        self._molecules = monomers[:]\n        self.relabel_all()\n        for m in self._molecules:\n            m.ampal_parent = self\n        return",
    "docstring": "Builds a model of a coiled coil protein using input parameters."
  },
  {
    "code": "def shutdown(self):\n        'Close the hub connection'\n        log.info(\"shutting down\")\n        self._peer.go_down(reconnect=False, expected=True)",
    "docstring": "Close the hub connection"
  },
  {
    "code": "def get_models(self):\n        try:\n            rels = self.rels_ext.content\n        except RequestFailed:\n            if \"RELS-EXT\" not in self.ds_list.keys():\n                return []\n            else:\n                raise\n        return list(rels.objects(self.uriref, modelns.hasModel))",
    "docstring": "Get a list of content models the object subscribes to."
  },
  {
    "code": "def get_parser_class():\n    global distro\n    if distro == 'Linux':\n        Parser = parser.LinuxParser\n        if not os.path.exists(Parser.get_command()[0]):\n            Parser = parser.UnixIPParser\n    elif distro in ['Darwin', 'MacOSX']:\n        Parser = parser.MacOSXParser\n    elif distro == 'Windows':\n        Parser = parser.WindowsParser\n    else:\n        Parser = parser.NullParser\n        Log.error(\"Unknown distro type '%s'.\" % distro)\n    Log.debug(\"Distro detected as '%s'\" % distro)\n    Log.debug(\"Using '%s'\" % Parser)\n    return Parser",
    "docstring": "Returns the parser according to the system platform"
  },
  {
    "code": "def _inject_addresses(self, subjects):\n    logger.debug('Injecting addresses to %s: %s', self, subjects)\n    with self._resolve_context():\n      addresses = tuple(subjects)\n      thts, = self._scheduler.product_request(TransitiveHydratedTargets,\n                                              [BuildFileAddresses(addresses)])\n    self._index(thts.closure)\n    yielded_addresses = set()\n    for address in subjects:\n      if address not in yielded_addresses:\n        yielded_addresses.add(address)\n        yield address",
    "docstring": "Injects targets into the graph for each of the given `Address` objects, and then yields them.\n\n    TODO: See #5606 about undoing the split between `_inject_addresses` and `_inject_specs`."
  },
  {
    "code": "def add_rule(self, rule_class, target_class=_Nothing):\n        if isinstance(target_class, Iterable):\n            for cls in target_class:\n                self._rules[cls] = rule_class\n        else:\n            self._rules[target_class] = rule_class",
    "docstring": "Adds an authorization rule.\n\n        :param rule_class: a class of authorization rule.\n        :param target_class: (optional) a class\n            or an iterable with classes to associate the rule with."
  },
  {
    "code": "def _update_visible_blocks(self, *args):\n        self._visible_blocks[:] = []\n        block = self.firstVisibleBlock()\n        block_nbr = block.blockNumber()\n        top = int(self.blockBoundingGeometry(block).translated(\n            self.contentOffset()).top())\n        bottom = top + int(self.blockBoundingRect(block).height())\n        ebottom_top = 0\n        ebottom_bottom = self.height()\n        while block.isValid():\n            visible = (top >= ebottom_top and bottom <= ebottom_bottom)\n            if not visible:\n                break\n            if block.isVisible():\n                self._visible_blocks.append((top, block_nbr, block))\n            block = block.next()\n            top = bottom\n            bottom = top + int(self.blockBoundingRect(block).height())\n            block_nbr = block.blockNumber()",
    "docstring": "Updates the list of visible blocks"
  },
  {
    "code": "def add_hash(self, value):\n        self.leaves.append(Node(codecs.decode(value, 'hex_codec'), prehashed=True))",
    "docstring": "Add a Node based on a precomputed, hex encoded, hash value."
  },
  {
    "code": "def get_reader_factory_for(self, name, *, format=None):\n        return self.get_factory_for(READER, name, format=format)",
    "docstring": "Returns a callable to build a reader for the provided filename, eventually forcing a format.\n\n        :param name: filename\n        :param format: format\n        :return: type"
  },
  {
    "code": "def inverse_mod( a, m ):\n  if a < 0 or m <= a: a = a % m\n  c, d = a, m\n  uc, vc, ud, vd = 1, 0, 0, 1\n  while c != 0:\n    q, c, d = divmod( d, c ) + ( c, )\n    uc, vc, ud, vd = ud - q*uc, vd - q*vc, uc, vc\n  assert d == 1\n  if ud > 0: return ud\n  else: return ud + m",
    "docstring": "Inverse of a mod m."
  },
  {
    "code": "def folder_name(self):\n        name = self.site_packages_name\n        if name is None:\n            name = self.name\n        return name",
    "docstring": "The name of the build folders containing this recipe."
  },
  {
    "code": "def get_device_tree(self):\n        root = DevNode(None, None, [], None)\n        device_nodes = {\n            dev.object_path: DevNode(dev, dev.parent_object_path, [],\n                                     self._ignore_device(dev))\n            for dev in self.udisks\n        }\n        for node in device_nodes.values():\n            device_nodes.get(node.root, root).children.append(node)\n        device_nodes['/'] = root\n        for node in device_nodes.values():\n            node.children.sort(key=DevNode._sort_key)\n        def propagate_ignored(node):\n            for child in node.children:\n                if child.ignored is None:\n                    child.ignored = node.ignored\n                propagate_ignored(child)\n        propagate_ignored(root)\n        return device_nodes",
    "docstring": "Get a tree of all devices."
  },
  {
    "code": "def retrieve_old_notifications(self):\n        date = ago(days=DELETE_OLD)\n        return Notification.objects.filter(added__lte=date)",
    "docstring": "Retrieve notifications older than X days, where X is specified in settings"
  },
  {
    "code": "def rpc_method(func=None, name=None, entry_point=ALL, protocol=ALL,\n               str_standardization=settings.MODERNRPC_PY2_STR_TYPE,\n               str_standardization_encoding=settings.MODERNRPC_PY2_STR_ENCODING):\n    def decorated(_func):\n        _func.modernrpc_enabled = True\n        _func.modernrpc_name = name or _func.__name__\n        _func.modernrpc_entry_point = entry_point\n        _func.modernrpc_protocol = protocol\n        _func.str_standardization = str_standardization\n        _func.str_standardization_encoding = str_standardization_encoding\n        return _func\n    if func is None:\n        return decorated\n    return decorated(func)",
    "docstring": "Mark a standard python function as RPC method.\n\n    All arguments are optional\n\n    :param func: A standard function\n    :param name: Used as RPC method name instead of original function name\n    :param entry_point: Default: ALL. Used to limit usage of the RPC method for a specific set of entry points\n    :param protocol: Default: ALL. Used to limit usage of the RPC method for a specific protocol (JSONRPC or XMLRPC)\n    :param str_standardization: Default: settings.MODERNRPC_PY2_STR_TYPE. Configure string standardization on python 2.\n    Ignored on python 3.\n    :param str_standardization_encoding: Default: settings.MODERNRPC_PY2_STR_ENCODING. Configure the encoding used\n    to perform string standardization conversion. Ignored on python 3.\n    :type name: str\n    :type entry_point: str\n    :type protocol: str\n    :type str_standardization: type str or unicode\n    :type str_standardization_encoding: str"
  },
  {
    "code": "def prepare_csv_read(data, field_names, *args, **kwargs):\n    if hasattr(data, 'readlines') or isinstance(data, list):\n        pass\n    elif isinstance(data, basestring):\n        data = open(data)\n    else:\n        raise TypeError('Unable to handle data of type %r' % type(data))\n    return csv.DictReader(data, field_names, *args, **kwargs)",
    "docstring": "Prepare various input types for CSV parsing.\n\n    Args:\n        data (iter): Data to read\n        field_names (tuple of str): Ordered names to assign to fields\n\n    Returns:\n        csv.DictReader: CSV reader suitable for parsing\n\n    Raises:\n        TypeError: Invalid value for data"
  },
  {
    "code": "def add_uniform_precip_event(self, intensity, duration):\n        self.project_manager.setCard('PRECIP_UNIF', '')\n        self.project_manager.setCard('RAIN_INTENSITY', str(intensity))\n        self.project_manager.setCard('RAIN_DURATION', str(duration.total_seconds()/60.0))",
    "docstring": "Add a uniform precip event"
  },
  {
    "code": "def get():\n        return {\n            attr: getattr(Conf, attr)\n            for attr in dir(Conf()) if not callable(getattr(Conf, attr)) and not attr.startswith(\"__\")\n        }",
    "docstring": "Gets the configuration as a dict"
  },
  {
    "code": "def list(self, full_properties=False, filter_args=None):\n        uris_prop = self.adapter.port_uris_prop\n        if not uris_prop:\n            return []\n        uris = self.adapter.get_property(uris_prop)\n        assert uris is not None\n        uris = list(set(uris))\n        resource_obj_list = []\n        for uri in uris:\n            resource_obj = self.resource_class(\n                manager=self,\n                uri=uri,\n                name=None,\n                properties=None)\n            if self._matches_filters(resource_obj, filter_args):\n                resource_obj_list.append(resource_obj)\n                if full_properties:\n                    resource_obj.pull_full_properties()\n        self._name_uri_cache.update_from(resource_obj_list)\n        return resource_obj_list",
    "docstring": "List the Ports of this Adapter.\n\n        If the adapter does not have any ports, an empty list is returned.\n\n        Authorization requirements:\n\n        * Object-access permission to this Adapter.\n\n        Parameters:\n\n          full_properties (bool):\n            Controls whether the full set of resource properties should be\n            retrieved, vs. only the short set as returned by the list\n            operation.\n\n          filter_args (dict):\n            Filter arguments that narrow the list of returned resources to\n            those that match the specified filter arguments. For details, see\n            :ref:`Filtering`.\n\n            `None` causes no filtering to happen, i.e. all resources are\n            returned.\n\n        Returns:\n\n          : A list of :class:`~zhmcclient.Port` objects.\n\n        Raises:\n\n          :exc:`~zhmcclient.HTTPError`\n          :exc:`~zhmcclient.ParseError`\n          :exc:`~zhmcclient.AuthError`\n          :exc:`~zhmcclient.ConnectionError`"
  },
  {
    "code": "def main():\n    argv = sys.argv[1:]\n    returncode = 1\n    try:\n        returncode = _main(os.environ, argv)\n    except exceptions.InvalidArgument as error:\n        if error.message:\n            sys.stderr.write(\"Error: \" + error.message + '\\n')\n        else:\n            raise\n    sys.exit(returncode)",
    "docstring": "The main command-line entry point, with system interactions."
  },
  {
    "code": "def signal_wrapper(f):\n    @wraps(f)\n    def wrapper(*args, **kwds):\n        args = map(convert, args)\n        kwds = {convert(k): convert(v) for k, v in kwds.items()}\n        return f(*args, **kwds)\n    return wrapper",
    "docstring": "Decorator converts function's arguments from dbus types to python."
  },
  {
    "code": "def finalize(self):\n        super(StatisticsConsumer, self).finalize()\n        self.result = zip(self.grid, map(self.statistics, self.result))",
    "docstring": "finalize for StatisticsConsumer"
  },
  {
    "code": "def to_records(cls, attr_names, value_matrix):\n        return [cls.to_record(attr_names, record) for record in value_matrix]",
    "docstring": "Convert a value matrix to records to be inserted into a database.\n\n        :param list attr_names:\n            List of attributes for the converting records.\n        :param value_matrix: Values to be converted.\n        :type value_matrix: list of |dict|/|namedtuple|/|list|/|tuple|\n\n        .. seealso:: :py:meth:`.to_record`"
  },
  {
    "code": "def ready_argument_list(self, arguments):\n        ctype_args = [ None for _ in arguments]\n        for i, arg in enumerate(arguments):\n            if not isinstance(arg, (numpy.ndarray, numpy.number)):\n                raise TypeError(\"Argument is not numpy ndarray or numpy scalar %s\" % type(arg))\n            dtype_str = str(arg.dtype)\n            data = arg.copy()\n            if isinstance(arg, numpy.ndarray):\n                if dtype_str in dtype_map.keys():\n                    data_ctypes = data.ctypes.data_as(C.POINTER(dtype_map[dtype_str]))\n                else:\n                    raise TypeError(\"unknown dtype for ndarray\")\n            elif isinstance(arg, numpy.generic):\n                data_ctypes = dtype_map[dtype_str](arg)\n            ctype_args[i] = Argument(numpy=data, ctypes=data_ctypes)\n        return ctype_args",
    "docstring": "ready argument list to be passed to the C function\n\n        :param arguments: List of arguments to be passed to the C function.\n            The order should match the argument list on the C function.\n            Allowed values are numpy.ndarray, and/or numpy.int32, numpy.float32, and so on.\n        :type arguments: list(numpy objects)\n\n        :returns: A list of arguments that can be passed to the C function.\n        :rtype: list(Argument)"
  },
  {
    "code": "def send(self, msg_string, immediate=True):\n        try:\n            mailhost = api.get_tool(\"MailHost\")\n            mailhost.send(msg_string, immediate=immediate)\n        except SMTPException as e:\n            logger.error(e)\n            return False\n        except socket.error as e:\n            logger.error(e)\n            return False\n        return True",
    "docstring": "Send the email via the MailHost tool"
  },
  {
    "code": "def generate_headline_from_description(sender, instance, *args, **kwargs):\n    lines = instance.description.split('\\n')\n    headline = truncatewords(lines[0], 20)\n    if headline[:-3] == '...':\n        headline = truncatechars(headline.replace(' ...', ''), 250)\n    else:\n        headline = truncatechars(headline, 250)\n    instance.headline = headline",
    "docstring": "Auto generate the headline of the node from the first lines of the description."
  },
  {
    "code": "def colorize(txt, fg=None, bg=None):\n    setting = ''\n    setting += _SET_FG.format(fg) if fg else ''\n    setting += _SET_BG.format(bg) if bg else ''\n    return setting + str(txt) + _STYLE_RESET",
    "docstring": "Print escape codes to set the terminal color.\n\n    fg and bg are indices into the color palette for the foreground and\n    background colors."
  },
  {
    "code": "def detect_response_encoding(response, is_html=False, peek=131072):\n    encoding = get_heading_encoding(response)\n    encoding = wpull.string.detect_encoding(\n        wpull.util.peek_file(response.body, peek), encoding=encoding, is_html=is_html\n    )\n    _logger.debug(__('Got encoding: {0}', encoding))\n    return encoding",
    "docstring": "Return the likely encoding of the response document.\n\n    Args:\n        response (Response): An instance of :class:`.http.Response`.\n        is_html (bool): See :func:`.util.detect_encoding`.\n        peek (int): The maximum number of bytes of the document to be analyzed.\n\n    Returns:\n        ``str``, ``None``: The codec name."
  },
  {
    "code": "def has_unclosed_brackets(text):\n    stack = []\n    text = re.sub(r, '', text)\n    for c in reversed(text):\n        if c in '])}':\n            stack.append(c)\n        elif c in '[({':\n            if stack:\n                if ((c == '[' and stack[-1] == ']') or\n                        (c == '{' and stack[-1] == '}') or\n                        (c == '(' and stack[-1] == ')')):\n                    stack.pop()\n            else:\n                return True\n    return False",
    "docstring": "Starting at the end of the string. If we find an opening bracket\n    for which we didn't had a closing one yet, return True."
  },
  {
    "code": "def _processing_limit(self, spec):\n    processing_rate = float(spec.mapper.params.get(\"processing_rate\", 0))\n    slice_processing_limit = -1\n    if processing_rate > 0:\n      slice_processing_limit = int(math.ceil(\n          parameters.config._SLICE_DURATION_SEC*processing_rate/\n          int(spec.mapper.shard_count)))\n    return slice_processing_limit",
    "docstring": "Get the limit on the number of map calls allowed by this slice.\n\n    Args:\n      spec: a Mapreduce spec.\n\n    Returns:\n      The limit as a positive int if specified by user. -1 otherwise."
  },
  {
    "code": "def system_requirements():\n        command_exists(\"systemd-nspawn\",\n            [\"systemd-nspawn\", \"--version\"],\n            \"Command systemd-nspawn does not seems to be present on your system\"\n            \"Do you have system with systemd\")\n        command_exists(\n            \"machinectl\",\n            [\"machinectl\", \"--no-pager\", \"--help\"],\n            \"Command machinectl does not seems to be present on your system\"\n            \"Do you have system with systemd\")\n        if \"Enforcing\" in run_cmd([\"getenforce\"], return_output=True, ignore_status=True):\n            logger.error(\"Please disable selinux (setenforce 0), selinux blocks some nspawn operations\"\n                         \"This may lead to strange behaviour\")",
    "docstring": "Check if all necessary packages are installed on system\n\n        :return: None or raise exception if some tooling is missing"
  },
  {
    "code": "def build_license_file(directory, spec):\n    name, text = '', ''\n    try:\n        name = spec['LICENSE']\n        text = spec['X_MSI_LICENSE_TEXT']\n    except KeyError:\n        pass\n    if name!='' or text!='':\n        file = open( os.path.join(directory.get_path(), 'License.rtf'), 'w' )\n        file.write('{\\\\rtf')\n        if text!='':\n             file.write(text.replace('\\n', '\\\\par '))\n        else:\n             file.write(name+'\\\\par\\\\par')\n        file.write('}')\n        file.close()",
    "docstring": "Creates a License.rtf file with the content of \"X_MSI_LICENSE_TEXT\"\n    in the given directory"
  },
  {
    "code": "def do_find(self, params):\n        for path in self._zk.find(params.path, params.match, 0):\n            self.show_output(path)",
    "docstring": "\\x1b[1mNAME\\x1b[0m\n        find - Find znodes whose path matches a given text\n\n\\x1b[1mSYNOPSIS\\x1b[0m\n        find [path] [match]\n\n\\x1b[1mOPTIONS\\x1b[0m\n        * path: the path (default: cwd)\n        * match: the string to match in the paths (default: '')\n\n\\x1b[1mEXAMPLES\\x1b[0m\n        > find / foo\n        /foo2\n        /fooish/wayland\n        /fooish/xorg\n        /copy/foo"
  },
  {
    "code": "def launch_processes(tests, run_module, group=True, **config):\n    manager = multiprocessing.Manager()\n    test_summaries = manager.dict()\n    process_handles = [multiprocessing.Process(target=run_module.run_suite,\n                       args=(test, config[test], test_summaries)) for test in tests]\n    for p in process_handles:\n        p.start()\n    for p in process_handles:\n        p.join()\n    if group:\n        summary = run_module.populate_metadata(tests[0], config[tests[0]])\n        summary[\"Data\"] = dict(test_summaries)\n        return summary\n    else:\n        test_summaries = dict(test_summaries)\n        summary = []\n        for ii, test in enumerate(tests):\n            summary.append(run_module.populate_metadata(test, config[test]))\n            if summary[ii]:\n                summary[ii]['Data'] = {test: test_summaries[test]}\n        return summary",
    "docstring": "Helper method to launch processes and sync output"
  },
  {
    "code": "def add_text(self, value):\n        if isinstance(value, (list, tuple)):\n            self.pieces.extend(value)\n        else:\n            self.pieces.append(value)",
    "docstring": "Adds text corresponding to `value` into `self.pieces`."
  },
  {
    "code": "def on_finish(func, handler, args, kwargs):\n    tracing = handler.settings.get('opentracing_tracing')\n    tracing._finish_tracing(handler)\n    return func(*args, **kwargs)",
    "docstring": "Wrap the handler ``on_finish`` method to finish the Span for the\n    given request, if available."
  },
  {
    "code": "def reseed_random(seed):\n    r = random.Random(seed)\n    random_internal_state = r.getstate()\n    set_random_state(random_internal_state)",
    "docstring": "Reseed factory.fuzzy's random generator."
  },
  {
    "code": "def topil(self, **kwargs):\n        if self.has_preview():\n            return pil_io.convert_image_data_to_pil(self._record, **kwargs)\n        return None",
    "docstring": "Get PIL Image.\n\n        :return: :py:class:`PIL.Image`, or `None` if the composed image is not\n            available."
  },
  {
    "code": "def get_bank_ids_by_item(self, item_id):\n        mgr = self._get_provider_manager('ASSESSMENT', local=True)\n        lookup_session = mgr.get_item_lookup_session(proxy=self._proxy)\n        lookup_session.use_federated_bank_view()\n        item = lookup_session.get_item(item_id)\n        id_list = []\n        for idstr in item._my_map['assignedBankIds']:\n            id_list.append(Id(idstr))\n        return IdList(id_list)",
    "docstring": "Gets the list of ``Bank``  ``Ids`` mapped to an ``Item``.\n\n        arg:    item_id (osid.id.Id): ``Id`` of an ``Item``\n        return: (osid.id.IdList) - list of bank ``Ids``\n        raise:  NotFound - ``item_id`` is not found\n        raise:  NullArgument - ``item_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - assessment failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def __dict_to_BetterDict(self, attr):\n        if type(self[attr]) == dict:\n            self[attr] = BetterDict(self[attr])\n        return self[attr]",
    "docstring": "Convert the passed attr to a BetterDict if the value is a dict\n\n        Returns: The new value of the passed attribute."
  },
  {
    "code": "def _parse_binary(v, header_d):\n    v = nullify(v)\n    if v is None:\n        return None\n    if six.PY2:\n        try:\n            return six.binary_type(v).strip()\n        except UnicodeEncodeError:\n            return six.text_type(v).strip()\n    else:\n        try:\n            return six.binary_type(v, 'utf-8').strip()\n        except UnicodeEncodeError:\n            return six.text_type(v).strip()",
    "docstring": "Parses binary string.\n\n    Note:\n        <str> for py2 and <binary> for py3."
  },
  {
    "code": "def get_usb_controller_count_by_type(self, type_p):\n        if not isinstance(type_p, USBControllerType):\n            raise TypeError(\"type_p can only be an instance of type USBControllerType\")\n        controllers = self._call(\"getUSBControllerCountByType\",\n                     in_p=[type_p])\n        return controllers",
    "docstring": "Returns the number of USB controllers of the given type attached to the VM.\n\n        in type_p of type :class:`USBControllerType`\n\n        return controllers of type int"
  },
  {
    "code": "def remove(self, dist):\n        while dist.location in self.paths:\n            self.paths.remove(dist.location)\n            self.dirty = True\n        Environment.remove(self, dist)",
    "docstring": "Remove `dist` from the distribution map"
  },
  {
    "code": "def get_indicators(self, from_time=None, to_time=None, enclave_ids=None,\n                       included_tag_ids=None, excluded_tag_ids=None,\n                       start_page=0, page_size=None):\n        indicators_page_generator = self._get_indicators_page_generator(\n            from_time=from_time,\n            to_time=to_time,\n            enclave_ids=enclave_ids,\n            included_tag_ids=included_tag_ids,\n            excluded_tag_ids=excluded_tag_ids,\n            page_number=start_page,\n            page_size=page_size\n        )\n        indicators_generator = Page.get_generator(page_generator=indicators_page_generator)\n        return indicators_generator",
    "docstring": "Creates a generator from the |get_indicators_page| method that returns each successive indicator as an\n        |Indicator| object containing values for the 'value' and 'type' attributes only; all\n        other |Indicator| object attributes will contain Null values.\n\n        :param int from_time: start of time window in milliseconds since epoch (defaults to 7 days ago).\n        :param int to_time: end of time window in milliseconds since epoch (defaults to current time).\n        :param list(string) enclave_ids: a list of enclave IDs from which to get indicators from. \n        :param list(string) included_tag_ids: only indicators containing ALL of these tag GUIDs will be returned.\n        :param list(string) excluded_tag_ids: only indicators containing NONE of these tags GUIDs be returned. \n        :param int start_page: see 'page_size' explanation.\n        :param int page_size: Passing the integer 1000 as the argument to this parameter should result in your script \n        making fewer API calls because it returns the largest quantity of indicators with each API call.  An API call \n        has to be made to fetch each |Page|.   \n        :return: A generator of |Indicator| objects containing values for the \"value\" and \"type\" attributes only.\n        All other attributes of the |Indicator| object will contain Null values."
  },
  {
    "code": "def copy2(src, dst, metadata=None, retry_params=None):\n  common.validate_file_path(src)\n  common.validate_file_path(dst)\n  if metadata is None:\n    metadata = {}\n    copy_meta = 'COPY'\n  else:\n    copy_meta = 'REPLACE'\n  metadata.update({'x-goog-copy-source': src,\n                   'x-goog-metadata-directive': copy_meta})\n  api = storage_api._get_storage_api(retry_params=retry_params)\n  status, resp_headers, content = api.put_object(\n      api_utils._quote_filename(dst), headers=metadata)\n  errors.check_status(status, [200], src, metadata, resp_headers, body=content)",
    "docstring": "Copy the file content from src to dst.\n\n  Args:\n    src: /bucket/filename\n    dst: /bucket/filename\n    metadata: a dict of metadata for this copy. If None, old metadata is copied.\n      For example, {'x-goog-meta-foo': 'bar'}.\n    retry_params: An api_utils.RetryParams for this call to GCS. If None,\n      the default one is used.\n\n  Raises:\n    errors.AuthorizationError: if authorization failed.\n    errors.NotFoundError: if an object that's expected to exist doesn't."
  },
  {
    "code": "def _get_config(self):\n    filename = '{}/{}'.format(self.PLUGIN_LOGDIR, CONFIG_FILENAME)\n    modified_time = os.path.getmtime(filename)\n    if modified_time != self.config_last_modified_time:\n      config = read_pickle(filename, default=self.previous_config)\n      self.previous_config = config\n    else:\n      config = self.previous_config\n    self.config_last_modified_time = modified_time\n    return config",
    "docstring": "Reads the config file from disk or creates a new one."
  },
  {
    "code": "def init_prior(self, R):\n        centers, widths = self.init_centers_widths(R)\n        prior = np.zeros(self.K * (self.n_dim + 1))\n        self.set_centers(prior, centers)\n        self.set_widths(prior, widths)\n        self.set_prior(prior)\n        return self",
    "docstring": "initialize prior for the subject\n\n        Returns\n        -------\n        TFA\n            Returns the instance itself."
  },
  {
    "code": "def sg_transpose(tensor, opt):\n    r\n    assert opt.perm is not None, 'perm is mandatory'\n    return tf.transpose(tensor, opt.perm, name=opt.name)",
    "docstring": "r\"\"\"Permutes the dimensions according to `opt.perm`.\n\n    See `tf.transpose()` in tensorflow.\n\n    Args:\n      tensor: A `Tensor` (automatically given by chain).\n      opt:\n        perm: A permutation of the dimensions of `tensor`. The target shape.\n        name: If provided, replace current tensor's name.\n\n    Returns:\n      A `Tensor`."
  },
  {
    "code": "def download_to_file(self, file):\n        con = ConnectionManager().get_connection(self._connection_alias)\n        return con.download_to_file(self.file, file, append_base_url=False)",
    "docstring": "Download and store the file of the sample.\n\n        :param file: A file-like object to store the file."
  },
  {
    "code": "def array(self, dimensions=None):\n        if dimensions is None:\n            dims = [d for d in self.kdims + self.vdims]\n        else:\n            dims = [self.get_dimension(d, strict=True) for d in dimensions]\n        columns, types = [], []\n        for dim in dims:\n            column = self.dimension_values(dim)\n            columns.append(column)\n            types.append(column.dtype.kind)\n        if len(set(types)) > 1:\n            columns = [c.astype('object') for c in columns]\n        return np.column_stack(columns)",
    "docstring": "Convert dimension values to columnar array.\n\n        Args:\n            dimensions: List of dimensions to return\n\n        Returns:\n            Array of columns corresponding to each dimension"
  },
  {
    "code": "def make(self, cmd_args, db_args):\n        with NamedTemporaryFile(delete=True) as f:\n            format_file = f.name + '.bcp-format'\n        format_args = cmd_args + ['format', NULL_FILE, '-c', '-f', format_file, '-t,'] + db_args\n        _run_cmd(format_args)\n        self.load(format_file)\n        return format_file",
    "docstring": "Runs bcp FORMAT command to create a format file that will assist in creating the bulk data file"
  },
  {
    "code": "def find_suitable_period():\n    highest_acceptable_factor = int(math.sqrt(SIZE))\n    starting_point = len(VALID_CHARS) > 14 and len(VALID_CHARS) / 2 or 13\n    for p in range(starting_point, 7, -1) \\\n            + range(highest_acceptable_factor, starting_point + 1, -1) \\\n            + [6, 5, 4, 3, 2]:\n        if SIZE % p == 0:\n            return p\n    raise Exception(\"No valid period could be found for SIZE=%d.\\n\"\n                    \"Try avoiding prime numbers\" % SIZE)",
    "docstring": "Automatically find a suitable period to use.\n        Factors are best, because they will have 1 left over when\n        dividing SIZE+1.\n        This only needs to be run once, on import."
  },
  {
    "code": "def report_build_messages(self):\n        if os.getenv('TEAMCITY_VERSION'):\n            tc_build_message_warning = \"\n            tc_build_message_error = \"\n            stdout.write(tc_build_message_warning.format(self.total_warnings))\n            stdout.write(tc_build_message_error.format(self.total_errors))\n            stdout.flush()",
    "docstring": "Checks environment variables to see whether pepper8 is run under a build agent such as TeamCity\n        and performs the adequate actions to report statistics.\n\n        Will not perform any action if HTML output is written to OUTPUT_FILE and not stdout.\n        Currently only supports TeamCity.\n\n        :return: A list of build message strings destined for stdout"
  },
  {
    "code": "def get_next_ip(self, tenant_id, direc):\n        if direc == 'in':\n            subnet_dict = self.get_in_ip_addr(tenant_id)\n        else:\n            subnet_dict = self.get_out_ip_addr(tenant_id)\n        if subnet_dict:\n            return subnet_dict\n        if direc == 'in':\n            ip_next = self.check_allocate_ip(self.service_in_ip, \"in\")\n        else:\n            ip_next = self.check_allocate_ip(self.service_out_ip, \"out\")\n        return {'subnet': ip_next, 'start': self.get_start_ip(ip_next),\n                'end': self.get_end_ip(ip_next),\n                'gateway': self.get_gateway(ip_next),\n                'sec_gateway': self.get_secondary_gateway(ip_next)}",
    "docstring": "Retrieve the next available subnet.\n\n        Given a tenant, it returns the service subnet values assigned\n        to it based on direction."
  },
  {
    "code": "def OnTimerToggle(self, event):\n        if self.grid.timer_running:\n            self.grid.timer_running = False\n            self.grid.timer.Stop()\n            del self.grid.timer\n        else:\n            self.grid.timer_running = True\n            self.grid.timer = wx.Timer(self.grid)\n            self.grid.timer.Start(config[\"timer_interval\"])",
    "docstring": "Toggles the timer for updating frozen cells"
  },
  {
    "code": "def handle_presentation(msg):\n    if msg.child_id == SYSTEM_CHILD_ID:\n        sensorid = msg.gateway.add_sensor(msg.node_id)\n        if sensorid is None:\n            return None\n        msg.gateway.sensors[msg.node_id].type = msg.sub_type\n        msg.gateway.sensors[msg.node_id].protocol_version = msg.payload\n        msg.gateway.sensors[msg.node_id].reboot = False\n        msg.gateway.alert(msg)\n        return msg\n    if not msg.gateway.is_sensor(msg.node_id):\n        _LOGGER.error('Node %s is unknown, will not add child %s',\n                      msg.node_id, msg.child_id)\n        return None\n    child_id = msg.gateway.sensors[msg.node_id].add_child_sensor(\n        msg.child_id, msg.sub_type, msg.payload)\n    if child_id is None:\n        return None\n    msg.gateway.alert(msg)\n    return msg",
    "docstring": "Process a presentation message."
  },
  {
    "code": "def _combine_lines(self, lines):\n        lines = filter(None, map(lambda x: x.strip(), lines))\n        return '[' + ','.join(lines) + ']'",
    "docstring": "Combines a list of JSON objects into one JSON object."
  },
  {
    "code": "def create(self, ip_dest, next_hop, **kwargs):\n        return self._set_route(ip_dest, next_hop, **kwargs)",
    "docstring": "Create a static route\n\n        Args:\n            ip_dest (string): The ip address of the destination in the\n                form of A.B.C.D/E\n            next_hop (string): The next hop interface or ip address\n            **kwargs['next_hop_ip'] (string): The next hop address on\n                destination interface\n            **kwargs['distance'] (string): Administrative distance for this\n                route\n            **kwargs['tag'] (string): Route tag\n            **kwargs['route_name'] (string): Route name\n\n        Returns:\n            True if the operation succeeds, otherwise False."
  },
  {
    "code": "def addReward(self, r=None):\n        r = self.getReward() if r is None else r\n        if self.discount:\n            self.cumulativeReward += power(self.discount, self.samples) * r\n        else:\n            self.cumulativeReward += r",
    "docstring": "A filtered mapping towards performAction of the underlying\n            environment."
  },
  {
    "code": "def phase_from_polarizations(h_plus, h_cross, remove_start_phase=True):\n    p = numpy.unwrap(numpy.arctan2(h_cross.data, h_plus.data)).astype(\n        real_same_precision_as(h_plus))\n    if remove_start_phase:\n        p += -p[0]\n    return TimeSeries(p, delta_t=h_plus.delta_t, epoch=h_plus.start_time,\n        copy=False)",
    "docstring": "Return gravitational wave phase\n\n    Return the gravitation-wave phase from the h_plus and h_cross\n    polarizations of the waveform. The returned phase is always\n    positive and increasing with an initial phase of 0.\n\n    Parameters\n    ----------\n    h_plus : TimeSeries\n        An PyCBC TmeSeries vector that contains the plus polarization of the\n        gravitational waveform.\n    h_cross : TimeSeries\n        A PyCBC TmeSeries vector that contains the cross polarization of the\n        gravitational waveform.\n\n    Returns\n    -------\n    GWPhase : TimeSeries\n        A TimeSeries containing the gravitational wave phase.\n\n    Examples\n    --------s\n    >>> from pycbc.waveform import get_td_waveform, phase_from_polarizations\n    >>> hp, hc = get_td_waveform(approximant=\"TaylorT4\", mass1=10, mass2=10,\n                         f_lower=30, delta_t=1.0/4096)\n    >>> phase = phase_from_polarizations(hp, hc)"
  },
  {
    "code": "def _get_interval(variant_regions, region, out_file, items):\n    target = shared.subset_variant_regions(variant_regions, region, out_file, items)\n    if target:\n        if isinstance(target, six.string_types) and os.path.isfile(target):\n            return \"--interval %s\" % target\n        else:\n            return \"--interval %s\" % bamprep.region_to_gatk(target)\n    else:\n        return \"\"",
    "docstring": "Retrieve interval to run analysis in. Handles no targets, BED and regions\n\n    region can be a single region or list of multiple regions for multicore calling."
  },
  {
    "code": "def save_encoder(self, name:str):\n        \"Save the encoder to `name` inside the model directory.\"\n        encoder = get_model(self.model)[0]\n        if hasattr(encoder, 'module'): encoder = encoder.module\n        torch.save(encoder.state_dict(), self.path/self.model_dir/f'{name}.pth')",
    "docstring": "Save the encoder to `name` inside the model directory."
  },
  {
    "code": "def terminate(self):\n        try:\n            self.id2sims.terminate()\n        except:\n            pass\n        import glob\n        for fname in glob.glob(self.fname + '*'):\n            try:\n                os.remove(fname)\n                logger.info(\"deleted %s\" % fname)\n            except Exception, e:\n                logger.warning(\"failed to delete %s: %s\" % (fname, e))\n        for val in self.__dict__.keys():\n            try:\n                delattr(self, val)\n            except:\n                pass",
    "docstring": "Delete all files created by this index, invalidating `self`. Use with care."
  },
  {
    "code": "def closed(lower_value, upper_value):\n    return Interval(Interval.CLOSED, lower_value, upper_value, Interval.CLOSED)",
    "docstring": "Helper function to construct an interval object with closed lower and upper.\n\n    For example:\n\n    >>> closed(100.2, 800.9)\n    [100.2, 800.9]"
  },
  {
    "code": "def draw(self):\n        cell_background_renderer = GridCellBackgroundCairoRenderer(\n            self.context,\n            self.code_array,\n            self.key,\n            self.rect,\n            self.view_frozen)\n        cell_content_renderer = GridCellContentCairoRenderer(\n            self.context,\n            self.code_array,\n            self.key,\n            self.rect,\n            self.spell_check)\n        cell_border_renderer = GridCellBorderCairoRenderer(\n            self.context,\n            self.code_array,\n            self.key,\n            self.rect)\n        cell_background_renderer.draw()\n        cell_content_renderer.draw()\n        cell_border_renderer.draw()",
    "docstring": "Draws cell to context"
  },
  {
    "code": "def _parse_info(self, info_str, num_alts):\n        result = OrderedDict()\n        if info_str == \".\":\n            return result\n        for entry in info_str.split(\";\"):\n            if \"=\" not in entry:\n                key = entry\n                result[key] = parse_field_value(self.header.get_info_field_info(key), True)\n            else:\n                key, value = split_mapping(entry)\n                result[key] = parse_field_value(self.header.get_info_field_info(key), value)\n            self._info_checker.run(key, result[key], num_alts)\n        return result",
    "docstring": "Parse INFO column from string"
  },
  {
    "code": "def currentText(self):\n        lineEdit = self.lineEdit()\n        if lineEdit:\n            return lineEdit.currentText()\n        text = nativestring(super(XComboBox, self).currentText())\n        if not text:\n            return self._hint\n        return text",
    "docstring": "Returns the current text for this combobox, including the hint option \\\n        if no text is set."
  },
  {
    "code": "def add_native_name(self, name):\n        self._ensure_field('name', {})\n        self.obj['name'].setdefault('native_names', []).append(name)",
    "docstring": "Add native name.\n\n        Args:\n            :param name: native name for the current author.\n            :type name: string"
  },
  {
    "code": "def _runPopUp(workbench, popUp):\n    workbench.display(popUp)\n    d = popUp.notifyCompleted()\n    d.addCallback(_popUpCompleted, workbench)\n    return d",
    "docstring": "Displays the pop-up on the workbench and gets a completion\n    notification deferred. When that fires, undisplay the pop-up and\n    return the result of the notification deferred verbatim."
  },
  {
    "code": "def _name_helper(name: str):\n    name = name.rstrip()\n    if name.endswith(('.service', '.socket', '.target')):\n        return name\n    return name + '.service'",
    "docstring": "default to returning a name with `.service`"
  },
  {
    "code": "def light(obj, sun):\n    dist = angle.distance(sun.lon, obj.lon)\n    faster = sun if sun.lonspeed > obj.lonspeed else obj\n    if faster == sun:\n        return LIGHT_DIMINISHING if dist < 180 else LIGHT_AUGMENTING\n    else:\n        return LIGHT_AUGMENTING if dist < 180 else LIGHT_DIMINISHING",
    "docstring": "Returns if an object is augmenting or diminishing light."
  },
  {
    "code": "def gauss_box_model_deriv(x, amplitude=1.0, mean=0.0, stddev=1.0, hpix=0.5):\n    z = (x - mean) / stddev\n    z2 = z + hpix / stddev\n    z1 = z - hpix / stddev\n    da = norm.cdf(z2) - norm.cdf(z1)\n    fp2 = norm_pdf_t(z2)\n    fp1 = norm_pdf_t(z1)\n    dl = -amplitude / stddev * (fp2 - fp1)\n    ds = -amplitude / stddev * (fp2 * z2 - fp1 * z1)\n    dd = amplitude / stddev * (fp2 + fp1)\n    return da, dl, ds, dd",
    "docstring": "Derivative of the integral of  a Gaussian profile."
  },
  {
    "code": "def difference(self, second_iterable, selector=identity):\n        if self.closed():\n            raise ValueError(\"Attempt to call difference() on a \"\n                             \"closed Queryable.\")\n        if not is_iterable(second_iterable):\n            raise TypeError(\"Cannot compute difference() with second_iterable\"\n               \"of non-iterable {0}\".format(str(type(second_iterable))[7: -2]))\n        if not is_callable(selector):\n            raise TypeError(\"difference() parameter selector={0} is \"\n                \"not callable\".format(repr(selector)))\n        return self._create(self._generate_difference_result(second_iterable,\n                                                            selector))",
    "docstring": "Returns those elements which are in the source sequence which are not\n        in the second_iterable.\n\n        This method is equivalent to the Except() LINQ operator, renamed to a\n        valid Python identifier.\n\n        Note: This method uses deferred execution, but as soon as execution\n            commences the entirety of the second_iterable is consumed;\n            therefore, although the source sequence may be infinite the\n            second_iterable must be finite.\n\n        Args:\n            second_iterable: Elements from this sequence are excluded from the\n                returned sequence. This sequence will be consumed in its\n                entirety, so must be finite.\n\n            selector: A optional single argument function with selects from the\n                elements of both sequences the values which will be\n                compared for equality. If omitted the identity function will\n                be used.\n\n        Returns:\n            A sequence containing all elements in the source sequence except\n            those which are also members of the second sequence.\n\n        Raises:\n            ValueError: If the Queryable has been closed.\n            TypeError: If the second_iterable is not in fact iterable.\n            TypeError: If the selector is not callable."
  },
  {
    "code": "def create_from_remote_file(self, group, snapshot=True, **args):\n        import requests\n        url = \"http://snapshot.geneontology.org/annotations/{}.gaf.gz\".format(group)\n        r = requests.get(url, stream=True, headers={'User-Agent': get_user_agent(modules=[requests], caller_name=__name__)})\n        p = GafParser()\n        results = p.skim(r.raw)\n        return self.create_from_tuples(results, **args)",
    "docstring": "Creates from remote GAF"
  },
  {
    "code": "def emit(events, stream=None, Dumper=Dumper,\n        canonical=None, indent=None, width=None,\n        allow_unicode=None, line_break=None):\n    getvalue = None\n    if stream is None:\n        from StringIO import StringIO\n        stream = StringIO()\n        getvalue = stream.getvalue\n    dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,\n            allow_unicode=allow_unicode, line_break=line_break)\n    try:\n        for event in events:\n            dumper.emit(event)\n    finally:\n        dumper.dispose()\n    if getvalue:\n        return getvalue()",
    "docstring": "Emit YAML parsing events into a stream.\n    If stream is None, return the produced string instead."
  },
  {
    "code": "def invoice_pdf(self, invoice_id):\n        return self._create_get_request(resource=INVOICES, billomat_id=invoice_id, command=PDF)",
    "docstring": "Opens a pdf of an invoice\n\n        :param invoice_id: the invoice id\n        :return: dict"
  },
  {
    "code": "def has_tag(self, p_key, p_value=\"\"):\n        tags = self.fields['tags']\n        return p_key in tags and (p_value == \"\" or p_value in tags[p_key])",
    "docstring": "Returns true when there is at least one tag with the given key. If a\n        value is passed, it will only return true when there exists a tag with\n        the given key-value combination."
  },
  {
    "code": "def smooth(sig, window_size):\n    box = np.ones(window_size)/window_size\n    return np.convolve(sig, box, mode='same')",
    "docstring": "Apply a uniform moving average filter to a signal\n\n    Parameters\n    ----------\n    sig : numpy array\n        The signal to smooth.\n    window_size : int\n        The width of the moving average filter."
  },
  {
    "code": "def dump(self):\n        dumpfile = self.args.dumpfile\n        if not dumpfile:\n            db, env = self.get_db_args_env()\n            dumpfile = fileutils.timestamp_filename(\n                'omero-database-%s' % db['name'], 'pgdump')\n        log.info('Dumping database to %s', dumpfile)\n        if not self.args.dry_run:\n            self.pgdump('-Fc', '-f', dumpfile)",
    "docstring": "Dump the database using the postgres custom format"
  },
  {
    "code": "def mask_xdata(self) -> DataAndMetadata.DataAndMetadata:\n        display_data_channel = self.__display_item.display_data_channel\n        shape = display_data_channel.display_data_shape\n        mask = numpy.zeros(shape)\n        for graphic in self.__display_item.graphics:\n            if isinstance(graphic, (Graphics.SpotGraphic, Graphics.WedgeGraphic, Graphics.RingGraphic, Graphics.LatticeGraphic)):\n                mask = numpy.logical_or(mask, graphic.get_mask(shape))\n        return DataAndMetadata.DataAndMetadata.from_data(mask)",
    "docstring": "Return the mask by combining any mask graphics on this data item as extended data.\n\n        .. versionadded:: 1.0\n\n        Scriptable: Yes"
  },
  {
    "code": "def write(self, string):\n        x, y = self._normalizeCursor(*self._cursor)\n        width, height = self.get_size()\n        wrapper = _textwrap.TextWrapper(initial_indent=(' '*x), width=width)\n        writeLines = []\n        for line in string.split('\\n'):\n            if line:\n                writeLines += wrapper.wrap(line)\n                wrapper.initial_indent = ''\n            else:\n                writeLines.append([])\n        for line in writeLines:\n            x, y = self._normalizeCursor(x, y)\n            self.draw_str(x, y, line[x:], self._fg, self._bg)\n            y += 1\n            x = 0\n        y -= 1\n        self._cursor = (x, y)",
    "docstring": "This method mimics basic file-like behaviour.\n\n        Because of this method you can replace sys.stdout or sys.stderr with\n        a :any:`Console` or :any:`Window` instance.\n\n        This is a convoluted process and behaviour seen now can be excepted to\n        change on later versions.\n\n        Args:\n            string (Text): The text to write out.\n\n        .. seealso:: :any:`set_colors`, :any:`set_mode`, :any:`Window`"
  },
  {
    "code": "def do_callback(self, pkt):\n        callback, parser = self.get_callback_parser(pkt)\n        if asyncio.iscoroutinefunction(callback):\n            self.loop.call_soon_threadsafe(self._do_async_callback,\n                                           callback, parser)\n        else:\n            self.loop.call_soon(callback, parser)",
    "docstring": "Add the callback to the event loop, we use call soon because we just\n        want it to be called at some point, but don't care when particularly."
  },
  {
    "code": "def _find_all_simple(path):\n    results = (\n        os.path.join(base, file)\n        for base, dirs, files in os.walk(path, followlinks=True)\n        for file in files\n    )\n    return filter(os.path.isfile, results)",
    "docstring": "Find all files under 'path'"
  },
  {
    "code": "def _generate_upload_key(self, allow_timeout=False):\n        while not self.user.nick:\n            with ARBITRATOR.condition:\n                ARBITRATOR.condition.wait()\n        while True:\n            params = {\n                \"name\": self.user.nick,\n                \"room\": self.room_id,\n                \"c\": self.__upload_count,\n            }\n            if self.key:\n                params[\"roomKey\"] = self.key\n            if self.password:\n                params[\"password\"] = self.password\n            info = self.conn.make_api_call(\"getUploadKey\", params)\n            self.__upload_count += 1\n            try:\n                return info[\"key\"], info[\"server\"], info[\"file_id\"]\n            except Exception:\n                to = int(info.get(\"error\", {}).get(\"info\", {}).get(\"timeout\", 0))\n                if to <= 0 or not allow_timeout:\n                    raise IOError(f\"Failed to retrieve key {info}\")\n                time.sleep(to / 10000)",
    "docstring": "Generates a new upload key"
  },
  {
    "code": "def get_currencies(self):\n        try:\n            resp = get(self.endpoint)\n            resp.raise_for_status()\n        except exceptions.RequestException as e:\n            self.log(logging.ERROR, \"%s: Problem whilst contacting endpoint:\\n%s\", self.name, e)\n        else:\n            with open(self._cached_currency_file, 'wb') as fd:\n                fd.write(resp.content)\n        try:\n            root = ET.parse(self._cached_currency_file).getroot()\n        except FileNotFoundError as e:\n            raise RuntimeError(\"%s: XML not found at endpoint or as cached file:\\n%s\" % (self.name, e))\n        return root",
    "docstring": "Downloads xml currency data or if not available tries to use cached file copy"
  },
  {
    "code": "def require_auth(function):\n    @functools.wraps(function)\n    def wrapper(self, *args, **kwargs):\n        if not self.access_token():\n            raise MissingAccessTokenError\n        return function(self, *args, **kwargs)\n    return wrapper",
    "docstring": "A decorator that wraps the passed in function and raises exception\n    if access token is missing"
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'input' in _dict:\n            args['input'] = MessageInput._from_dict(_dict.get('input'))\n        if 'intents' in _dict:\n            args['intents'] = [\n                RuntimeIntent._from_dict(x) for x in (_dict.get('intents'))\n            ]\n        if 'entities' in _dict:\n            args['entities'] = [\n                RuntimeEntity._from_dict(x) for x in (_dict.get('entities'))\n            ]\n        if 'alternate_intents' in _dict:\n            args['alternate_intents'] = _dict.get('alternate_intents')\n        if 'context' in _dict:\n            args['context'] = Context._from_dict(_dict.get('context'))\n        if 'output' in _dict:\n            args['output'] = OutputData._from_dict(_dict.get('output'))\n        if 'actions' in _dict:\n            args['actions'] = [\n                DialogNodeAction._from_dict(x) for x in (_dict.get('actions'))\n            ]\n        return cls(**args)",
    "docstring": "Initialize a MessageRequest object from a json dictionary."
  },
  {
    "code": "def sinter(self, keys, *args):\n        func = lambda left, right: left.intersection(right)\n        return self._apply_to_sets(func, \"SINTER\", keys, *args)",
    "docstring": "Emulate sinter."
  },
  {
    "code": "def optimal_mapping(self, reference, hypothesis, uem=None):\n        if uem:\n            reference, hypothesis = self.uemify(reference, hypothesis, uem=uem)\n        mapping = self.mapper_(hypothesis, reference)\n        return mapping",
    "docstring": "Optimal label mapping\n\n        Parameters\n        ----------\n        reference : Annotation\n        hypothesis : Annotation\n            Reference and hypothesis diarization\n        uem : Timeline\n            Evaluation map\n\n        Returns\n        -------\n        mapping : dict\n            Mapping between hypothesis (key) and reference (value) labels"
  },
  {
    "code": "def _nth(arr, n):\n    try:\n        return arr.iloc[n]\n    except (KeyError, IndexError):\n        return np.nan",
    "docstring": "Return the nth value of array\n\n    If it is missing return NaN"
  },
  {
    "code": "def _download_file_from_drive(filename, url):\n    confirm_token = None\n    confirm_token = None\n    session = requests.Session()\n    response = session.get(url, stream=True)\n    for k, v in response.cookies.items():\n        if k.startswith(\"download_warning\"):\n            confirm_token = v\n    if confirm_token:\n        url = url + \"&confirm=\" + confirm_token\n    logger.info(\"Downloading %s to %s\" % (url, filename))\n    response = session.get(url, stream=True)\n    chunk_size = 16 * 1024\n    with open(filename, \"wb\") as f:\n        for chunk in response.iter_content(chunk_size):\n            if chunk:\n                f.write(chunk)\n    statinfo = os.stat(filename)\n    logger.info(\"Successfully downloaded %s, %s bytes.\" % (filename, statinfo.st_size))",
    "docstring": "Download filename from google drive unless it's already in directory.\n\n    Args:\n        filename (str): Name of the file to download to (do nothing if it already exists).\n        url (str): URL to download from."
  },
  {
    "code": "def create_collection(self, name=\"collection\", position=None, **kwargs):\n        if name in self.item_names:\n            wt_exceptions.ObjectExistsWarning.warn(name)\n            return self[name]\n        collection = Collection(\n            filepath=self.filepath, parent=self.name, name=name, edit_local=True, **kwargs\n        )\n        if position is not None:\n            self.attrs[\"item_names\"] = np.insert(\n                self.attrs[\"item_names\"][:-1], position, collection.natural_name.encode()\n            )\n        setattr(self, name, collection)\n        return collection",
    "docstring": "Create a new child colleciton.\n\n        Parameters\n        ----------\n        name : string\n            Unique identifier.\n        position : integer (optional)\n            Location to insert. Default is None (append).\n        kwargs\n            Additional arguments to child collection instantiation.\n\n        Returns\n        -------\n        WrightTools Collection\n            New child."
  },
  {
    "code": "def _add_to_to_ordered_dict(self, d, dataset_index, recommended_only=False):\n        if self.doses_dropped_sessions:\n            for key in sorted(list(self.doses_dropped_sessions.keys())):\n                session = self.doses_dropped_sessions[key]\n                session._add_single_session_to_to_ordered_dict(d, dataset_index, recommended_only)\n        self._add_single_session_to_to_ordered_dict(d, dataset_index, recommended_only)",
    "docstring": "Save a session to an ordered dictionary. In some cases, a single session may include\n        a final session, as well as other BMDS executions where doses were dropped. This\n        will include all sessions."
  },
  {
    "code": "def bulk_launch(self, jobs=None, filter=None, all=False):\n        json = None\n        if jobs is not None:\n            schema = JobSchema(exclude=('id', 'status', 'package_name', 'config_name', 'device_name', 'result_id', 'user_id', 'created', 'updated', 'automatic'))\n            jobs_json = self.service.encode(schema, jobs, many=True)\n            json = {self.RESOURCE: jobs_json}\n        schema = JobSchema()\n        resp = self.service.post(self.base,\n                                 params={'bulk': 'launch', 'filter': filter, 'all': all}, json=json)\n        return self.service.decode(schema, resp, many=True)",
    "docstring": "Bulk launch a set of jobs.\n\n        :param jobs: :class:`jobs.Job <jobs.Job>` list\n        :param filter: (optional) Filters to apply as a string list.\n        :param all: (optional) Apply to all if bool `True`."
  },
  {
    "code": "def get_backend(name):\n    for backend in _BACKENDS:\n        if backend.NAME == name:\n            return backend\n    raise KeyError(\"Backend %r not available\" % name)",
    "docstring": "Returns the backend by name or raises KeyError"
  },
  {
    "code": "def DeleteGRRTempFile(path):\n  precondition.AssertType(path, Text)\n  if not os.path.isabs(path):\n    raise ErrorBadPath(\"Path must be absolute\")\n  prefix = config.CONFIG[\"Client.tempfile_prefix\"]\n  directories = [\n      GetTempDirForRoot(root) for root in config.CONFIG[\"Client.tempdir_roots\"]\n  ]\n  if not _CheckIfPathIsValidForDeletion(\n      path, prefix=prefix, directories=directories):\n    msg = (\"Can't delete temp file %s. Filename must start with %s \"\n           \"or lie within any of %s.\")\n    raise ErrorNotTempFile(msg % (path, prefix, \";\".join(directories)))\n  if os.path.exists(path):\n    files.FILE_HANDLE_CACHE.Flush()\n    os.remove(path)\n  else:\n    raise ErrorNotAFile(\"%s does not exist.\" % path)",
    "docstring": "Delete a GRR temp file.\n\n  To limit possible damage the path must be absolute and either the\n  file must be within any of the Client.tempdir_roots or the file name\n  must begin with Client.tempfile_prefix.\n\n  Args:\n    path: path string to file to be deleted.\n\n  Raises:\n    OSError: Permission denied, or file not found.\n    ErrorBadPath: Path must be absolute.\n    ErrorNotTempFile: Filename must start with Client.tempfile_prefix.\n    ErrorNotAFile: File to delete does not exist."
  },
  {
    "code": "def list_vlans(self, datacenter=None, vlan_number=None, name=None, **kwargs):\n        _filter = utils.NestedDict(kwargs.get('filter') or {})\n        if vlan_number:\n            _filter['networkVlans']['vlanNumber'] = (\n                utils.query_filter(vlan_number))\n        if name:\n            _filter['networkVlans']['name'] = utils.query_filter(name)\n        if datacenter:\n            _filter['networkVlans']['primaryRouter']['datacenter']['name'] = (\n                utils.query_filter(datacenter))\n        kwargs['filter'] = _filter.to_dict()\n        if 'mask' not in kwargs:\n            kwargs['mask'] = DEFAULT_VLAN_MASK\n        kwargs['iter'] = True\n        return self.account.getNetworkVlans(**kwargs)",
    "docstring": "Display a list of all VLANs on the account.\n\n        This provides a quick overview of all VLANs including information about\n        data center residence and the number of devices attached.\n\n        :param string datacenter: If specified, the list will only contain\n                                    VLANs in the specified data center.\n        :param int vlan_number: If specified, the list will only contain the\n                                  VLAN matching this VLAN number.\n        :param int name: If specified, the list will only contain the\n                                  VLAN matching this VLAN name.\n        :param dict \\\\*\\\\*kwargs: response-level options (mask, limit, etc.)"
  },
  {
    "code": "def cbpdnmsk_class_label_lookup(label):\n    clsmod = {'admm': admm_cbpdn.ConvBPDNMaskDcpl,\n              'fista': fista_cbpdn.ConvBPDNMask}\n    if label in clsmod:\n        return clsmod[label]\n    else:\n        raise ValueError('Unknown ConvBPDNMask solver method %s' % label)",
    "docstring": "Get a ConvBPDNMask class from a label string."
  },
  {
    "code": "def completed_task(self):\n        if self.remote_channel and self.remote_channel.exit_status_ready():\n            while self.remote_channel.recv_ready():\n                self.stdout += self.remote_channel.recv(1024)\n            while self.remote_channel.recv_stderr_ready():\n                self.stderr += self.remote_channel.recv_stderr(1024)\n            return self.remote_channel.recv_exit_status()\n        elif self.process:\n            self.stdout, self.stderr = (self._read_temp_file(self.stdout_file),\n                                        self._read_temp_file(self.stderr_file))\n            for temp_file in [self.stdout_file, self.stderr_file]:\n                temp_file.close()\n            return self.process.returncode",
    "docstring": "Handle wrapping up a completed task, local or remote"
  },
  {
    "code": "def locate_bar_r(icut, epos):\n    sm = len(icut)\n    def swap_coor(x):\n        return sm - 1 - x\n    def swap_line(tab):\n        return tab[::-1]\n    return _locate_bar_gen(icut, epos, transform1=swap_coor,\n                           transform2=swap_line)",
    "docstring": "Fine position of the right CSU bar"
  },
  {
    "code": "def get_child_for_path(self, path):\n        path = ensure_str(path)\n        if not path:\n            raise InvalidPathError(\"%s is not a valid path\" % path)\n        as_private = True\n        if path.startswith(\"M\"):\n            as_private = False\n        if path.endswith(\".pub\"):\n            as_private = False\n            path = path[:-4]\n        parts = path.split(\"/\")\n        if len(parts) == 0:\n            raise InvalidPathError()\n        child = self\n        for part in parts:\n            if part.lower() == \"m\":\n                continue\n            is_prime = None\n            if part[-1] in \"'p\":\n                is_prime = True\n                part = part.replace(\"'\", \"\").replace(\"p\", \"\")\n            try:\n                child_number = long_or_int(part)\n            except ValueError:\n                raise InvalidPathError(\"%s is not a valid path\" % path)\n            child = child.get_child(child_number, is_prime)\n        if not as_private:\n            return child.public_copy()\n        return child",
    "docstring": "Get a child for a given path.\n\n        Rather than repeated calls to get_child, children can be found\n        by a derivation path. Paths look like:\n\n            m/0/1'/10\n\n        Which is the same as\n\n            self.get_child(0).get_child(-1).get_child(10)\n\n        Or, in other words, the 10th publicly derived child of the 1st\n        privately derived child of the 0th publicly derived child of master.\n\n        You can use either ' or p to denote a prime (that is, privately\n        derived) child.\n\n        A child that has had its private key stripped can be requested by\n        either passing a capital M or appending '.pub' to the end of the path.\n        These three paths all give the same child that has had its private\n        key scrubbed:\n\n            M/0/1\n            m/0/1.pub\n            M/0/1.pub"
  },
  {
    "code": "def _args_checks_gen(self, decorated_function, function_spec, arg_specs):\n\t\tinspected_args = function_spec.args\n\t\targs_check = {}\n\t\tfor i in range(len(inspected_args)):\n\t\t\targ_name = inspected_args[i]\n\t\t\tif arg_name in arg_specs.keys():\n\t\t\t\targs_check[arg_name] = self.check(arg_specs[arg_name], arg_name, decorated_function)\n\t\treturn args_check",
    "docstring": "Generate checks for positional argument testing\n\n\t\t:param decorated_function: function decorator\n\t\t:param function_spec: function inspect information\n\t\t:param arg_specs: argument specification (same as arg_specs in :meth:`.Verifier.decorate`)\n\n\t\t:return: internal structure, that is used by :meth:`.Verifier._args_checks_test`"
  },
  {
    "code": "def _extract_ocsp_certs(self, ocsp_response):\n        status = ocsp_response['response_status'].native\n        if status == 'successful':\n            response_bytes = ocsp_response['response_bytes']\n            if response_bytes['response_type'].native == 'basic_ocsp_response':\n                response = response_bytes['response'].parsed\n                if response['certs']:\n                    for other_cert in response['certs']:\n                        if self.certificate_registry.add_other_cert(other_cert):\n                            self._revocation_certs[other_cert.issuer_serial] = other_cert",
    "docstring": "Extracts any certificates included with an OCSP response and adds them\n        to the certificate registry\n\n        :param ocsp_response:\n            An asn1crypto.ocsp.OCSPResponse object to look for certs inside of"
  },
  {
    "code": "def get_required_config(self):\n        required_config = Namespace()\n        for k, v in iteritems_breadth_first(self.required_config):\n            required_config[k] = v\n        try:\n            subparser_namespaces = (\n                self.configman_subparsers_option.foreign_data\n                .argparse.subprocessor_from_string_converter\n            )\n            subparsers = (\n                self._argparse_subparsers._configman_option.foreign_data\n                .argparse.subparsers\n            )\n            for subparser_name, subparser_data in six.iteritems(subparsers):\n                subparser_namespaces.add_namespace(\n                    subparser_name,\n                    subparser_data.subparser.get_required_config()\n                )\n        except AttributeError:\n            pass\n        return required_config",
    "docstring": "because of the exsistance of subparsers, the configman options\n        that correspond with argparse arguments are not a constant.  We need\n        to produce a copy of the namespace rather than the actual embedded\n        namespace."
  },
  {
    "code": "def filter_significant_motifs(fname, result, bg, metrics=None):\n    sig_motifs = []\n    with open(fname, \"w\") as f:\n        for motif in result.motifs:\n            stats = result.stats.get(\n                    \"%s_%s\" % (motif.id, motif.to_consensus()), {}).get(bg, {}\n                    ) \n            if _is_significant(stats, metrics):\n                f.write(\"%s\\n\" % motif.to_pfm())\n                sig_motifs.append(motif)\n    logger.info(\"%s motifs are significant\", len(sig_motifs))\n    logger.debug(\"written to %s\", fname)\n    return sig_motifs",
    "docstring": "Filter significant motifs based on several statistics.\n\n    Parameters\n    ----------\n    fname : str\n        Filename of output file were significant motifs will be saved.\n\n    result : PredictionResult instance\n        Contains motifs and associated statistics.\n\n    bg : str\n        Name of background type to use.\n\n    metrics : sequence\n        Metric with associated minimum values. The default is\n        ((\"max_enrichment\", 3), (\"roc_auc\", 0.55), (\"enr_at_f[r\", 0.55))\n\n    Returns\n    -------\n    motifs : list\n        List of Motif instances."
  },
  {
    "code": "def collect_tokens_until(self, token_type):\n        self.next()\n        if self.current_token.type == token_type:\n            return\n        while True:\n            yield self.current_token\n            self.next()\n            if self.current_token.type == token_type:\n                return\n            if self.current_token.type != 'COMMA':\n                raise self.error(f'Expected comma but got '\n                                 f'{self.current_token.value!r}')\n            self.next()",
    "docstring": "Yield the item tokens in a comma-separated tag collection."
  },
  {
    "code": "def source_filename(self, docname: str, srcdir: str):\n        docpath = Path(srcdir, docname)\n        parent = docpath.parent\n        imgpath = parent.joinpath(self.filename)\n        if not imgpath.exists():\n            msg = f'Image does not exist at \"{imgpath}\"'\n            raise SphinxError(msg)\n        return imgpath",
    "docstring": "Get the full filename to referenced image"
  },
  {
    "code": "def tile_to_path(self, tile):\n\t\treturn os.path.join(self.cache_path, self.service, tile.path())",
    "docstring": "return full path to a tile"
  },
  {
    "code": "def calculate_sampling_decision(trace_header, recorder, sampling_req):\n    if trace_header.sampled is not None and trace_header.sampled != '?':\n        return trace_header.sampled\n    elif not recorder.sampling:\n        return 1\n    else:\n        decision = recorder.sampler.should_trace(sampling_req)\n    return decision if decision else 0",
    "docstring": "Return 1 or the matched rule name if should sample and 0 if should not.\n    The sampling decision coming from ``trace_header`` always has\n    the highest precedence. If the ``trace_header`` doesn't contain\n    sampling decision then it checks if sampling is enabled or not\n    in the recorder. If not enbaled it returns 1. Otherwise it uses user\n    defined sampling rules to decide."
  },
  {
    "code": "def set_all_tiers(key, value, django_cache_timeout=DEFAULT_TIMEOUT):\n        DEFAULT_REQUEST_CACHE.set(key, value)\n        django_cache.set(key, value, django_cache_timeout)",
    "docstring": "Caches the value for the provided key in both the request cache and the\n        django cache.\n\n        Args:\n            key (string)\n            value (object)\n            django_cache_timeout (int): (Optional) Timeout used to determine\n                if and for how long to cache in the django cache. A timeout of\n                0 will skip the django cache. If timeout is provided, use that\n                timeout for the key; otherwise use the default cache timeout."
  },
  {
    "code": "def create_traj_ranges(start, stop, N):\n    steps = (1.0/(N-1)) * (stop - start)\n    if np.isscalar(steps):\n        return steps*np.arange(N) + start\n    else:\n        return steps[:, None]*np.arange(N) + start[:, None]",
    "docstring": "Fills in the trajectory range.\n\n    # Adapted from https://stackoverflow.com/a/40624614"
  },
  {
    "code": "def tokenize(self, string):\n        if self.language == 'akkadian':\n            tokens = tokenize_akkadian_words(string)\n        elif self.language == 'arabic':\n            tokens = tokenize_arabic_words(string)\n        elif self.language == 'french':\n            tokens = tokenize_french_words(string)\n        elif self.language == 'greek':\n            tokens = tokenize_greek_words(string)\n        elif self.language == 'latin':\n            tokens = tokenize_latin_words(string)\n        elif self.language == 'old_norse':\n            tokens = tokenize_old_norse_words(string)\n        elif self.language == 'middle_english':\n            tokens = tokenize_middle_english_words(string)\n        elif self.language == 'middle_high_german':\n            tokens = tokenize_middle_high_german_words(string)\n        else:\n            tokens = nltk_tokenize_words(string)\n        return tokens",
    "docstring": "Tokenize incoming string."
  },
  {
    "code": "def isAuthorized(self, pid, action, vendorSpecific=None):\n        response = self.isAuthorizedResponse(pid, action, vendorSpecific)\n        return self._read_boolean_401_response(response)",
    "docstring": "Return True if user is allowed to perform ``action`` on ``pid``, else\n        False."
  },
  {
    "code": "def is_zipfile(filename):\n    result = False\n    try:\n        if hasattr(filename, \"read\"):\n            result = _check_zipfile(fp=filename)\n        else:\n            with open(filename, \"rb\") as fp:\n                result = _check_zipfile(fp)\n    except OSError:\n        pass\n    return result",
    "docstring": "Quickly see if a file is a ZIP file by checking the magic number.\n\n    The filename argument may be a file or file-like object too."
  },
  {
    "code": "def complete_func(self, findstart, base):\n        self.log.debug('complete_func: in %s %s', findstart, base)\n        def detect_row_column_start():\n            row, col = self.editor.cursor()\n            start = col\n            line = self.editor.getline()\n            while start > 0 and line[start - 1] not in \" .,([{\":\n                start -= 1\n            return row, col, start if start else 1\n        if str(findstart) == \"1\":\n            row, col, startcol = detect_row_column_start()\n            self.complete(row, col)\n            self.completion_started = True\n            return startcol\n        else:\n            result = []\n            if self.completion_started:\n                self.unqueue(timeout=self.completion_timeout, should_wait=True)\n                suggestions = self.suggestions or []\n                self.log.debug('complete_func: suggestions in')\n                for m in suggestions:\n                    result.append(m)\n                self.suggestions = None\n                self.completion_started = False\n            return result",
    "docstring": "Handle omni completion."
  },
  {
    "code": "def orders_after_any(self, other, *, visited=None):\n        if not other:\n            return False\n        if visited is None:\n            visited = set()\n        elif self in visited:\n            return False\n        visited.add(self)\n        for item in self.PATCHED_ORDER_AFTER:\n            if item in visited:\n                continue\n            if item in other:\n                return True\n            if item.orders_after_any(other, visited=visited):\n                return True\n        return False",
    "docstring": "Return whether `self` orders after any of the services in the set\n        `other`.\n\n        :param other: Another service.\n        :type other: A :class:`set` of\n          :class:`aioxmpp.service.Service` instances\n\n        .. versionadded:: 0.11"
  },
  {
    "code": "def _tuple_from_str(bbox):\n        return tuple([float(s) for s in bbox.replace(',', ' ').split() if s])",
    "docstring": "Parses a string of numbers separated by any combination of commas and spaces\n\n        :param bbox: e.g. str of the form `min_x ,min_y  max_x, max_y`\n        :return: tuple (min_x,min_y,max_x,max_y)"
  },
  {
    "code": "def get_prep_value(self, value):\n        value = super(NullBooleanPGPPublicKeyField, self).get_prep_value(value)\n        if value is None:\n            return None\n        return \"%s\" % bool(value)",
    "docstring": "Before encryption, need to prepare values."
  },
  {
    "code": "def namespace(sharing=None, owner=None, app=None, **kwargs):\n    if sharing in [\"system\"]:\n        return record({'sharing': sharing, 'owner': \"nobody\", 'app': \"system\" })\n    if sharing in [\"global\", \"app\"]:\n        return record({'sharing': sharing, 'owner': \"nobody\", 'app': app})\n    if sharing in [\"user\", None]:\n        return record({'sharing': sharing, 'owner': owner, 'app': app})\n    raise ValueError(\"Invalid value for argument: 'sharing'\")",
    "docstring": "This function constructs a Splunk namespace.\n\n    Every Splunk resource belongs to a namespace. The namespace is specified by\n    the pair of values ``owner`` and ``app`` and is governed by a ``sharing`` mode.\n    The possible values for ``sharing`` are: \"user\", \"app\", \"global\" and \"system\",\n    which map to the following combinations of ``owner`` and ``app`` values:\n\n        \"user\"   => {owner}, {app}\n\n        \"app\"    => nobody, {app}\n\n        \"global\" => nobody, {app}\n\n        \"system\" => nobody, system\n\n    \"nobody\" is a special user name that basically means no user, and \"system\"\n    is the name reserved for system resources.\n\n    \"-\" is a wildcard that can be used for both ``owner`` and ``app`` values and\n    refers to all users and all apps, respectively.\n\n    In general, when you specify a namespace you can specify any combination of\n    these three values and the library will reconcile the triple, overriding the\n    provided values as appropriate.\n\n    Finally, if no namespacing is specified the library will make use of the\n    ``/services`` branch of the REST API, which provides a namespaced view of\n    Splunk resources equivelent to using ``owner={currentUser}`` and\n    ``app={defaultApp}``.\n\n    The ``namespace`` function returns a representation of the namespace from\n    reconciling the values you provide. It ignores any keyword arguments other\n    than ``owner``, ``app``, and ``sharing``, so you can provide ``dicts`` of\n    configuration information without first having to extract individual keys.\n\n    :param sharing: The sharing mode (the default is \"user\").\n    :type sharing: \"system\", \"global\", \"app\", or \"user\"\n    :param owner: The owner context (the default is \"None\").\n    :type owner: ``string``\n    :param app: The app context (the default is \"None\").\n    :type app: ``string``\n    :returns: A :class:`splunklib.data.Record` containing the reconciled\n        namespace.\n\n    **Example**::\n\n        import splunklib.binding as binding\n        n = binding.namespace(sharing=\"user\", owner=\"boris\", app=\"search\")\n        n = binding.namespace(sharing=\"global\", app=\"search\")"
  },
  {
    "code": "def _get_config():\n    cfg = os.path.expanduser('~/.dockercfg')\n    try:\n        fic = open(cfg)\n        try:\n            config = json.loads(fic.read())\n        finally:\n            fic.close()\n    except Exception:\n        config = {'rootPath': '/dev/null'}\n    if not 'Configs' in config:\n        config['Configs'] = {}\n    return config",
    "docstring": "Get user docker configuration\n\n    Return: dict"
  },
  {
    "code": "def annualization_factor(period, annualization):\n    if annualization is None:\n        try:\n            factor = ANNUALIZATION_FACTORS[period]\n        except KeyError:\n            raise ValueError(\n                \"Period cannot be '{}'. \"\n                \"Can be '{}'.\".format(\n                    period, \"', '\".join(ANNUALIZATION_FACTORS.keys())\n                )\n            )\n    else:\n        factor = annualization\n    return factor",
    "docstring": "Return annualization factor from period entered or if a custom\n    value is passed in.\n\n    Parameters\n    ----------\n    period : str, optional\n        Defines the periodicity of the 'returns' data for purposes of\n        annualizing. Value ignored if `annualization` parameter is specified.\n        Defaults are::\n\n            'monthly':12\n            'weekly': 52\n            'daily': 252\n\n    annualization : int, optional\n        Used to suppress default values available in `period` to convert\n        returns into annual returns. Value should be the annual frequency of\n        `returns`.\n\n    Returns\n    -------\n    annualization_factor : float"
  },
  {
    "code": "def AllBalancesZeroOrLess(self):\n        for key, fixed8 in self.Balances.items():\n            if fixed8.value > 0:\n                return False\n        return True",
    "docstring": "Flag indicating if all balances are 0 or less.\n\n        Returns:\n            bool: True if all balances are <= 0. False, otherwise."
  },
  {
    "code": "def gather_details():\n    try:\n        data = {\n            'kernel': platform.uname(),\n            'distribution': platform.linux_distribution(),\n            'libc': platform.libc_ver(),\n            'arch': platform.machine(),\n            'python_version': platform.python_version(),\n            'os_name': platform.system(),\n            'static_hostname': platform.node(),\n            'cpu': platform.processor(),\n            'fqdn': socket.getfqdn(),\n        }\n    except AttributeError:\n        return {}\n    return data",
    "docstring": "Get details about the host that is executing habu."
  },
  {
    "code": "def xslt(request):\n    foos = foobar_models.Foo.objects.all()\n    return render_xslt_to_response('xslt/model-to-xml.xsl', foos, mimetype='text/xml')",
    "docstring": "Shows xml output transformed with standard xslt"
  },
  {
    "code": "def AddDateTimeRange(\n      self, time_value, start_time_string=None, end_time_string=None):\n    if not isinstance(time_value, py2to3.STRING_TYPES):\n      raise ValueError('Filter type must be a string.')\n    if start_time_string is None and end_time_string is None:\n      raise ValueError(\n          'Filter must have either a start or an end date time value.')\n    time_value_lower = time_value.lower()\n    if time_value_lower not in self._SUPPORTED_TIME_VALUES:\n      raise ValueError('Unsupported time value: {0:s}.'.format(time_value))\n    start_date_time = None\n    if start_time_string:\n      start_date_time = time_elements.TimeElementsInMicroseconds()\n      start_date_time.CopyFromDateTimeString(start_time_string)\n    end_date_time = None\n    if end_time_string:\n      end_date_time = time_elements.TimeElementsInMicroseconds()\n      end_date_time.CopyFromDateTimeString(end_time_string)\n    if (None not in (start_date_time, end_date_time) and\n        start_date_time > end_date_time):\n      raise ValueError(\n          'Invalid date time value start must be earlier than end.')\n    self._date_time_ranges.append(self._DATE_TIME_RANGE_TUPLE(\n        time_value_lower, start_date_time, end_date_time))",
    "docstring": "Adds a date time filter range.\n\n    The time strings are formatted as:\n    YYYY-MM-DD hh:mm:ss.######[+-]##:##\n    Where # are numeric digits ranging from 0 to 9 and the seconds\n    fraction can be either 3 or 6 digits. The time of day, seconds fraction\n    and timezone offset are optional. The default timezone is UTC.\n\n    Args:\n      time_value (str): time value, such as, atime, ctime, crtime, dtime, bkup\n          and mtime.\n      start_time_string (str): start date and time value string.\n      end_time_string (str): end date and time value string.\n\n    Raises:\n      ValueError: If the filter is badly formed."
  },
  {
    "code": "def write_data(fo, datum, schema):\n    record_type = extract_record_type(schema)\n    logical_type = extract_logical_type(schema)\n    fn = WRITERS.get(record_type)\n    if fn:\n        if logical_type:\n            prepare = LOGICAL_WRITERS.get(logical_type)\n            if prepare:\n                datum = prepare(datum, schema)\n        return fn(fo, datum, schema)\n    else:\n        return write_data(fo, datum, SCHEMA_DEFS[record_type])",
    "docstring": "Write a datum of data to output stream.\n\n    Paramaters\n    ----------\n    fo: file-like\n        Output file\n    datum: object\n        Data to write\n    schema: dict\n        Schemda to use"
  },
  {
    "code": "def createVertex(self, collectionName, docAttributes, waitForSync = False) :\n        url = \"%s/vertex/%s\" % (self.URL, collectionName)\n        store = DOC.DocumentStore(self.database[collectionName], validators=self.database[collectionName]._fields, initDct=docAttributes)\n        store.validate()\n        r = self.connection.session.post(url, data = json.dumps(docAttributes, default=str), params = {'waitForSync' : waitForSync})\n        data = r.json()\n        if r.status_code == 201 or r.status_code == 202 :\n            return self.database[collectionName][data[\"vertex\"][\"_key\"]]\n        raise CreationError(\"Unable to create vertice, %s\" % data[\"errorMessage\"], data)",
    "docstring": "adds a vertex to the graph and returns it"
  },
  {
    "code": "def file_search(self, query, offset=None, timeout=None):\n        params = dict(apikey=self.api_key, query=query, offset=offset)\n        try:\n            response = requests.get(self.base + 'file/search', params=params, proxies=self.proxies, timeout=timeout)\n        except requests.RequestException as e:\n            return dict(error=str(e))\n        return _return_response_and_status_code(response)",
    "docstring": "Search for samples.\n\n        In addition to retrieving all information on a particular file, VirusTotal allows you to perform what we\n        call \"advanced reverse searches\". Reverse searches take you from a file property to a list of files that\n        match that property. For example, this functionality enables you to retrieve all those files marked by at\n        least one antivirus vendor as Zbot, or all those files that have a size under 90KB and are detected by at\n        least 10 antivirus solutions, or all those PDF files that have an invalid XREF section, etc.\n\n        This API is equivalent to VirusTotal Intelligence advanced searches. A very wide variety of search modifiers\n        are available, including: file size, file type, first submission date to VirusTotal, last submission date to\n        VirusTotal, number of positives, dynamic behavioural properties, binary content, submission file name, and a\n        very long etcetera. The full list of search modifiers allowed for file search queries is documented at:\n        https://www.virustotal.com/intelligence/help/file-search/#search-modifiers\n\n        NOTE:\n        Daily limited! No matter what API step you have licensed, this API call is limited to 50K requests per day.\n        If you need any more, chances are you are approaching your engineering problem erroneously and you can\n        probably solve it using the file distribution call. Do not hesitate to contact us with your particular\n        use case.\n\n        EXAMPLE:\n        search_options = 'type:peexe size:90kb+ positives:5+ behaviour:\"taskkill\"'\n\n        :param query: A search modifier compliant file search query.\n        :param offset: (optional) The offset value returned by a previously issued identical query, allows you to\n        paginate over the results. If not specified the first 300 matching files sorted according to last submission\n        date to VirusTotal in a descending fashion will be returned.\n        :param timeout: The amount of time in seconds the request should wait before timing out.\n\n        :return: JSON response -  By default the list returned contains at most 300 hashes, ordered according to\n        last submission date to VirusTotal in a descending fashion."
  },
  {
    "code": "def getbit(self, key, offset):\n        key = self._encode(key)\n        index, bits, mask = self._get_bits_and_offset(key, offset)\n        if index >= len(bits):\n            return 0\n        return 1 if (bits[index] & mask) else 0",
    "docstring": "Returns the bit value at ``offset`` in ``key``."
  },
  {
    "code": "def _md5(path, blocksize=2 ** 20):\n    m = hashlib.md5()\n    with open(path, 'rb') as f:\n        while True:\n            buf = f.read(blocksize)\n            if not buf:\n                break\n            m.update(buf)\n    return m.hexdigest()",
    "docstring": "Compute the checksum of a file."
  },
  {
    "code": "def is_accessable_by_others(filename):\n    mode = os.stat(filename)[stat.ST_MODE]\n    return mode & (stat.S_IRWXG | stat.S_IRWXO)",
    "docstring": "Check if file is group or world accessable."
  },
  {
    "code": "def list_service_profiles(self, retrieve_all=True, **_params):\n        return self.list('service_profiles', self.service_profiles_path,\n                         retrieve_all, **_params)",
    "docstring": "Fetches a list of all Neutron service flavor profiles."
  },
  {
    "code": "def atomic(self, func):\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            session = self.session\n            session_info = session.info\n            if session_info.get(_ATOMIC_FLAG_SESSION_INFO_KEY):\n                return func(*args, **kwargs)\n            f = retry_on_deadlock(session)(func)\n            session_info[_ATOMIC_FLAG_SESSION_INFO_KEY] = True\n            try:\n                result = f(*args, **kwargs)\n                session.flush()\n                session.expunge_all()\n                session.commit()\n                return result\n            except Exception:\n                session.rollback()\n                raise\n            finally:\n                session_info[_ATOMIC_FLAG_SESSION_INFO_KEY] = False\n        return wrapper",
    "docstring": "A decorator that wraps a function in an atomic block.\n\n        Example::\n\n          db = CustomSQLAlchemy()\n\n          @db.atomic\n          def f():\n              write_to_db('a message')\n              return 'OK'\n\n          assert f() == 'OK'\n\n        This code defines the function ``f``, which is wrapped in an\n        atomic block. Wrapping a function in an atomic block gives\n        several guarantees:\n\n        1. The database transaction will be automatically committed if\n           the function returns normally, and automatically rolled\n           back if the function raises unhandled exception.\n\n        2. When the transaction is committed, all objects in\n           ``db.session`` will be expunged. This means that no lazy\n           loading will be performed on them.\n\n        3. If a transaction serialization error occurs during the\n           execution of the function, the function will be\n           re-executed. (It might be re-executed several times.)\n\n        Atomic blocks can be nested, but in this case the outermost\n        block takes full control of transaction's life-cycle, and\n        inner blocks do nothing."
  },
  {
    "code": "def days_since_last_snowfall(self, value=99):\n        if value is not None:\n            try:\n                value = int(value)\n            except ValueError:\n                raise ValueError(\n                    'value {} need to be of type int '\n                    'for field `days_since_last_snowfall`'.format(value))\n        self._days_since_last_snowfall = value",
    "docstring": "Corresponds to IDD Field `days_since_last_snowfall`\n\n        Args:\n            value (int): value for IDD Field `days_since_last_snowfall`\n                Missing value: 99\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def pvalues(self):\n        self.compute_statistics()\n        lml_alts = self.alt_lmls()\n        lml_null = self.null_lml()\n        lrs = -2 * lml_null + 2 * asarray(lml_alts)\n        from scipy.stats import chi2\n        chi2 = chi2(df=1)\n        return chi2.sf(lrs)",
    "docstring": "Association p-value for candidate markers."
  },
  {
    "code": "def _register_service_type(cls, subclass):\n        if hasattr(subclass, '__service_type__'):\n            cls._service_type_mapping[subclass.__service_type__] = subclass\n            if subclass.__service_type__:\n                setattr(subclass,\n                        subclass.__service_type__,\n                        property(lambda x: x))\n        return subclass",
    "docstring": "Registers subclass handlers of various service-type-specific service\n           implementations. Look for classes decorated with\n           @Folder._register_service_type for hints on how this works."
  },
  {
    "code": "def get_nodes(n=8, exclude=[], loop=None):\n    report = _get_ukko_report()\n    nodes = _parse_ukko_report(report)\n    ret = []\n    while len(ret) < n and len(nodes) > 0:\n        node = nodes[0]\n        if node not in exclude:\n            reachable = True\n            if loop is not None:\n                reachable = loop.run_until_complete(_test_node(node))\n            if reachable:\n                ret.append(node)\n        nodes = nodes[1:]\n    return ret",
    "docstring": "Get Ukko nodes with the least amount of load.\n\n    May return less than *n* nodes if there are not as many nodes available,\n    the nodes are reserved or the nodes are on the exclude list.\n\n    :param int n: Number of Ukko nodes to return.\n    :param list exclude: Nodes to exclude from the returned list.\n    :param loop:\n        asyncio's event loop to test if each returned node is currently\n        loggable. The test is done by trying to connect to the node with\n        (async)ssh.\n\n    :rtype list:\n    :returns: Locations of Ukko nodes with the least amount of load"
  },
  {
    "code": "def shape_list(x):\n  x = tf.convert_to_tensor(x)\n  if x.get_shape().dims is None:\n    return tf.shape(x)\n  static = x.get_shape().as_list()\n  shape = tf.shape(x)\n  ret = []\n  for i, dim in enumerate(static):\n    if dim is None:\n      dim = shape[i]\n    ret.append(dim)\n  return ret",
    "docstring": "Return list of dims, statically where possible."
  },
  {
    "code": "def _is_builtin_module(module):\n    if (not hasattr(module, '__file__')) or  module.__name__ in sys.builtin_module_names:\n        return True\n    if module.__name__ in _stdlib._STD_LIB_MODULES:\n        return True\n    amp = os.path.abspath(module.__file__)\n    if 'site-packages' in amp:\n        return False\n    if amp.startswith(_STD_MODULE_DIR):\n        return True\n    if not '.' in module.__name__:\n        return False\n    mn_top = module.__name__.split('.')[0]\n    return mn_top in _stdlib._STD_LIB_MODULES",
    "docstring": "Is builtin or part of standard library"
  },
  {
    "code": "def _randomized_roundoff_to_bfloat16(x, noise, cand1, cand2):\n  cand1_f = tf.to_float(cand1)\n  cand2_f = tf.to_float(cand2)\n  step_size = cand2_f - cand1_f\n  fpart = (x - cand1_f) / step_size\n  ret = tf.where(tf.greater(fpart, noise), cand2, cand1)\n  return ret",
    "docstring": "Round-off x to cand1 or to cand2 in an unbiased way.\n\n  Cand1 and cand2 are the same shape as x.\n  For every element of x, the corresponding elements of cand1 and cand2 should\n  be the two closest bfloat16 values to x.  Order does not matter.\n  cand1 and cand2 must differ from each other.\n\n  Args:\n    x: A float32 Tensor.\n    noise: A Tensor broadcastable to the shape of x containing\n    random uniform values in [0.0, 1.0].\n    cand1: A bfloat16 Tensor the same shape as x.\n    cand2: A bfloat16 Tensor the same shape as x.\n\n  Returns:\n    A bfloat16 Tensor."
  },
  {
    "code": "def eval_str_to_list(input_str: str) -> List[str]:\n    inner_cast = ast.literal_eval(input_str)\n    if isinstance(inner_cast, list):\n        return inner_cast\n    else:\n        raise ValueError",
    "docstring": "Turn str into str or tuple."
  },
  {
    "code": "def weighted_mean(X, embedding, neighbors, distances):\n    n_samples = X.shape[0]\n    n_components = embedding.shape[1]\n    partial_embedding = np.zeros((n_samples, n_components))\n    for i in range(n_samples):\n        partial_embedding[i] = np.average(\n            embedding[neighbors[i]], axis=0, weights=distances[i],\n        )\n    return partial_embedding",
    "docstring": "Initialize points onto an existing embedding by placing them in the\n    weighted mean position of their nearest neighbors on the reference embedding.\n\n    Parameters\n    ----------\n    X: np.ndarray\n    embedding: TSNEEmbedding\n    neighbors: np.ndarray\n    distances: np.ndarray\n\n    Returns\n    -------\n    np.ndarray"
  },
  {
    "code": "def degrees_of_freedom(self):\n        if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None\n        r = self.studentized_residuals()\n        if r == None: return\n        N = 0.0\n        for i in range(len(r)): N += len(r[i])\n        return N-len(self._pnames)",
    "docstring": "Returns the number of degrees of freedom."
  },
  {
    "code": "def process_mixcloud(vargs):\n    artist_url = vargs['artist_url']\n    if 'mixcloud.com' in artist_url:\n        mc_url = artist_url\n    else:\n        mc_url = 'https://mixcloud.com/' + artist_url\n    filenames = scrape_mixcloud_url(mc_url, num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])\n    if vargs['open']:\n        open_files(filenames)\n    return",
    "docstring": "Main MixCloud path."
  },
  {
    "code": "def print_docs(self):\n        docs = {}\n        for name, func in six.iteritems(self.minion.functions):\n            if name not in docs:\n                if func.__doc__:\n                    docs[name] = func.__doc__\n        for name in sorted(docs):\n            if name.startswith(self.opts.get('fun', '')):\n                salt.utils.stringutils.print_cli('{0}:\\n{1}\\n'.format(name, docs[name]))",
    "docstring": "Pick up the documentation for all of the modules and print it out."
  },
  {
    "code": "def face_colors(self, values):\n        if values is None:\n            if 'face_colors' in self._data:\n                self._data.data.pop('face_colors')\n            return\n        colors = to_rgba(values)\n        if (self.mesh is not None and\n                colors.shape == (4,)):\n            count = len(self.mesh.faces)\n            colors = np.tile(colors, (count, 1))\n        self._data.clear()\n        self._data['face_colors'] = colors\n        self._cache.verify()",
    "docstring": "Set the colors for each face of a mesh.\n\n        This will apply these colors and delete any previously specified\n        color information.\n\n        Parameters\n        ------------\n        colors: (len(mesh.faces), 3), set each face to the specified color\n                (len(mesh.faces), 4), set each face to the specified color\n                (3,) int, set the whole mesh this color\n                (4,) int, set the whole mesh this color"
  },
  {
    "code": "def wrap_value(self, value):\n        try:\n            return self.item_type.wrap_value(value)\n        except BadValueException:\n            pass\n        try:\n            return self.wrap(value)\n        except BadValueException:\n            pass\n        self._fail_validation(value, 'Could not wrap value as the correct type.  Tried %s and %s' % (self.item_type, self))",
    "docstring": "A function used to wrap a value used in a comparison.  It will\n            first try to wrap as the sequence's sub-type, and then as the\n            sequence itself"
  },
  {
    "code": "def add_fields(self, fields):\n        if isinstance(fields, string_types):\n            fields = [fields]\n        elif type(fields) is tuple:\n            fields = list(fields)\n        field_objects = [self.add_field(field) for field in fields]\n        return field_objects",
    "docstring": "Adds all of the passed fields to the table's current field list\n\n        :param fields: The fields to select from ``table``. This can be\n            a single field, a tuple of fields, or a list of fields. Each field can be a string\n            or ``Field`` instance\n        :type fields: str or tuple or list of str or list of Field or :class:`Field <querybuilder.fields.Field>`"
  },
  {
    "code": "def broadcast_status(self, status):\n        self._broadcast(\n            \"transient.status\",\n            json.dumps(status),\n            headers={\"expires\": str(int((15 + time.time()) * 1000))},\n        )",
    "docstring": "Broadcast transient status information to all listeners"
  },
  {
    "code": "def rank(tensor: BKTensor) -> int:\n    if isinstance(tensor, np.ndarray):\n        return len(tensor.shape)\n    return len(tensor[0].size())",
    "docstring": "Return the number of dimensions of a tensor"
  },
  {
    "code": "def logical_drives(self):\n        return logical_drive.HPELogicalDriveCollection(\n            self._conn, utils.get_subresource_path_by(\n                self, ['Links', 'LogicalDrives']),\n            redfish_version=self.redfish_version)",
    "docstring": "Gets the resource HPELogicalDriveCollection of ArrayControllers"
  },
  {
    "code": "def prepare_input(self, extracted_str):\n        if self.options['remove_whitespace']:\n            optimized_str = re.sub(' +', '', extracted_str)\n        else:\n            optimized_str = extracted_str\n        if self.options['remove_accents']:\n            optimized_str = unidecode(optimized_str)\n        if self.options['lowercase']:\n            optimized_str = optimized_str.lower()\n        for replace in self.options['replace']:\n            assert len(replace) == 2, 'A replace should be a list of 2 items'\n            optimized_str = optimized_str.replace(replace[0], replace[1])\n        return optimized_str",
    "docstring": "Input raw string and do transformations, as set in template file."
  },
  {
    "code": "def _parse_account_information(self, rows):\n        acc_info = {}\n        if not rows:\n            return\n        for row in rows:\n            cols_raw = row.find_all('td')\n            cols = [ele.text.strip() for ele in cols_raw]\n            field, value = cols\n            field = field.replace(\"\\xa0\", \"_\").replace(\" \", \"_\").replace(\":\", \"\").lower()\n            value = value.replace(\"\\xa0\", \" \")\n            acc_info[field] = value\n        created = parse_tibia_datetime(acc_info[\"created\"])\n        loyalty_title = None if acc_info[\"loyalty_title\"] == \"(no title)\" else acc_info[\"loyalty_title\"]\n        position = acc_info.get(\"position\")\n        self.account_information = AccountInformation(created, loyalty_title, position)",
    "docstring": "Parses the character's account information\n\n        Parameters\n        ----------\n        rows: :class:`list` of :class:`bs4.Tag`, optional\n            A list of all rows contained in the table."
  },
  {
    "code": "def make_module_reload_func(module_name=None, module_prefix='[???]', module=None):\n    module = _get_module(module_name, module, register=False)\n    if module_name is None:\n        module_name = str(module.__name__)\n    def rrr(verbose=True):\n        if not __RELOAD_OK__:\n            raise Exception('Reloading has been forced off')\n        try:\n            import imp\n            if verbose and not QUIET:\n                builtins.print('RELOAD: ' + str(module_prefix) + ' __name__=' + module_name)\n            imp.reload(module)\n        except Exception as ex:\n            print(ex)\n            print('%s Failed to reload' % module_prefix)\n            raise\n    return rrr",
    "docstring": "Injects dynamic module reloading"
  },
  {
    "code": "def _process_loop(self):\n        while not self._web_client_session.done():\n            self._item_session.request = self._web_client_session.next_request()\n            verdict, reason = self._should_fetch_reason()\n            _logger.debug('Filter verdict {} reason {}', verdict, reason)\n            if not verdict:\n                self._item_session.skip()\n                break\n            exit_early, wait_time = yield from self._fetch_one(cast(Request, self._item_session.request))\n            if wait_time:\n                _logger.debug('Sleeping {}', wait_time)\n                yield from asyncio.sleep(wait_time)\n            if exit_early:\n                break",
    "docstring": "Fetch URL including redirects.\n\n        Coroutine."
  },
  {
    "code": "def set_max_entries(self):\n        if self.cache:\n            self.max_entries = float(max([i[0] for i in self.cache.values()]))",
    "docstring": "Define the maximum of entries for computing the priority\n        of each items later."
  },
  {
    "code": "def _advertisement(self):\n        flags = int(self.device.pending_data) | (0 << 1) | (0 << 2) | (1 << 3) | (1 << 4)\n        return struct.pack(\"<LH\", self.device.iotile_id, flags)",
    "docstring": "Create advertisement data."
  },
  {
    "code": "def get_attachment_size(self, attachment):\n        fsize = 0\n        file = attachment.getAttachmentFile()\n        if file:\n            fsize = file.get_size()\n        if fsize < 1024:\n            fsize = '%s b' % fsize\n        else:\n            fsize = '%s Kb' % (fsize / 1024)\n        return fsize",
    "docstring": "Get the human readable size of the attachment"
  },
  {
    "code": "def _parse_ppt_segment(self, fptr):\n        offset = fptr.tell() - 2\n        read_buffer = fptr.read(3)\n        length, zppt = struct.unpack('>HB', read_buffer)\n        length = length\n        zppt = zppt\n        numbytes = length - 3\n        ippt = fptr.read(numbytes)\n        return PPTsegment(zppt, ippt, length, offset)",
    "docstring": "Parse the PPT segment.\n\n        The packet headers are not parsed, i.e. they remain \"uninterpreted\"\n        raw data beffers.\n\n        Parameters\n        ----------\n        fptr : file object\n            The file to parse.\n\n        Returns\n        -------\n        PPTSegment\n            The current PPT segment."
  },
  {
    "code": "def branch_inlet_outlet(data, commdct, branchname):\n    objkey = 'Branch'.upper()\n    theobjects = data.dt[objkey]\n    theobject = [obj for obj in theobjects if obj[1] == branchname]\n    theobject = theobject[0]\n    inletindex = 6\n    outletindex = len(theobject) - 2\n    return [theobject[inletindex], theobject[outletindex]]",
    "docstring": "return the inlet and outlet of a branch"
  },
  {
    "code": "def handle_unset_evidence(self, line: str, position: int, tokens: ParseResults) -> ParseResults:\n        if self.evidence is None:\n            raise MissingAnnotationKeyWarning(self.get_line_number(), line, position, tokens[EVIDENCE])\n        self.evidence = None\n        return tokens",
    "docstring": "Unset the evidence, or throws an exception if it is not already set.\n\n        The value for ``tokens[EVIDENCE]`` corresponds to which alternate of SupportingText or Evidence was used in\n        the BEL script.\n\n        :raises: MissingAnnotationKeyWarning"
  },
  {
    "code": "def create_dir(entry, section, domain, output):\n    full_output_dir = os.path.join(output, section, domain, entry['assembly_accession'])\n    try:\n        os.makedirs(full_output_dir)\n    except OSError as err:\n        if err.errno == errno.EEXIST and os.path.isdir(full_output_dir):\n            pass\n        else:\n            raise\n    return full_output_dir",
    "docstring": "Create the output directory for the entry if needed."
  },
  {
    "code": "def delete_topic(self, topic):\n        nsq.assert_valid_topic_name(topic)\n        return self._request('POST', '/topic/delete', fields={'topic': topic})",
    "docstring": "Delete a topic."
  },
  {
    "code": "def engine(self):\n        return self.backend({\n            'APP_DIRS': True,\n            'DIRS': [str(ROOT / self.backend.app_dirname)],\n            'NAME': 'djangoforms',\n            'OPTIONS': {},\n        })",
    "docstring": "Return Render Engine."
  },
  {
    "code": "def includeme(config):\n    from .models import (\n        AuthUserMixin,\n        random_uuid,\n        lower_strip,\n        encrypt_password,\n    )\n    add_proc = config.add_field_processors\n    add_proc(\n        [random_uuid, lower_strip],\n        model=AuthUserMixin, field='username')\n    add_proc([lower_strip], model=AuthUserMixin, field='email')\n    add_proc([encrypt_password], model=AuthUserMixin, field='password')",
    "docstring": "Set up event subscribers."
  },
  {
    "code": "def _post_parse_request(self, request, client_id='', **kwargs):\n        request = RefreshAccessTokenRequest(**request.to_dict())\n        try:\n            keyjar = self.endpoint_context.keyjar\n        except AttributeError:\n            keyjar = \"\"\n        request.verify(keyjar=keyjar, opponent_id=client_id)\n        if \"client_id\" not in request:\n            request[\"client_id\"] = client_id\n        logger.debug(\"%s: %s\" % (request.__class__.__name__, sanitize(request)))\n        return request",
    "docstring": "This is where clients come to refresh their access tokens\n\n        :param request: The request\n        :param authn: Authentication info, comes from HTTP header\n        :returns:"
  },
  {
    "code": "def _get_api_key_ops():\n    auth_header = request.authorization\n    if not auth_header:\n        logging.debug('API request lacks authorization header')\n        abort(flask.Response(\n            'API key required', 401,\n            {'WWW-Authenticate': 'Basic realm=\"API key required\"'}))\n    return operations.ApiKeyOps(auth_header.username, auth_header.password)",
    "docstring": "Gets the operations.ApiKeyOps instance for the current request."
  },
  {
    "code": "def check_ensembl_api_version(self):\n        self.attempt = 0\n        headers = {\"content-type\": \"application/json\"}\n        ext = \"/info/rest\"\n        r = self.ensembl_request(ext, headers)\n        response = json.loads(r)\n        self.cache.set_ensembl_api_version(response[\"release\"])",
    "docstring": "check the ensembl api version matches a currently working version\n        \n        This function is included so when the api version changes, we notice the\n        change, and we can manually check the responses for the new version."
  },
  {
    "code": "def by_youtube_id(cls, youtube_id):\n        qset = cls.objects.filter(\n            encoded_videos__profile__profile_name='youtube',\n            encoded_videos__url=youtube_id\n        ).prefetch_related('encoded_videos', 'courses')\n        return qset",
    "docstring": "Look up video by youtube id"
  },
  {
    "code": "def update(self, eid, data, token):\n        final_dict = {\"data\": {\"id\": eid, \"type\": \"libraryEntries\", \"attributes\": data}}\n        final_headers = self.header\n        final_headers['Authorization'] = \"Bearer {}\".format(token)\n        r = requests.patch(self.apiurl + \"/library-entries/{}\".format(eid), json=final_dict, headers=final_headers)\n        if r.status_code != 200:\n            raise ConnectionError(r.text)\n        return True",
    "docstring": "Update a given Library Entry.\n\n        :param eid str: Entry ID\n        :param data dict: Attributes\n        :param token str: OAuth token\n        :return: True or ServerError\n        :rtype: Bool or Exception"
  },
  {
    "code": "def reportFailed(self, *args, **kwargs):\n        return self._makeApiCall(self.funcinfo[\"reportFailed\"], *args, **kwargs)",
    "docstring": "Report Run Failed\n\n        Report a run failed, resolving the run as `failed`. Use this to resolve\n        a run that failed because the task specific code behaved unexpectedly.\n        For example the task exited non-zero, or didn't produce expected output.\n\n        Do not use this if the task couldn't be run because if malformed\n        payload, or other unexpected condition. In these cases we have a task\n        exception, which should be reported with `reportException`.\n\n        This method gives output: ``v1/task-status-response.json#``\n\n        This method is ``stable``"
  },
  {
    "code": "def memory_write32(self, addr, data, zone=None):\n        return self.memory_write(addr, data, zone, 32)",
    "docstring": "Writes words to memory of a target system.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          addr (int): start address to write to\n          data (list): list of words to write\n          zone (str): optional memory zone to access\n\n        Returns:\n          Number of words written to target.\n\n        Raises:\n          JLinkException: on memory access error."
  },
  {
    "code": "def _get_nn_layers(spec):\n    layers = []\n    if spec.WhichOneof('Type') == 'pipeline':\n        layers = []\n        for model_spec in spec.pipeline.models:\n            if not layers:\n                return _get_nn_layers(model_spec)\n            else:\n                layers.extend(_get_nn_layers(model_spec))\n    elif spec.WhichOneof('Type') in ['pipelineClassifier',\n                                        'pipelineRegressor']:\n        layers = []\n        for model_spec in spec.pipeline.models:\n            if not layers:\n                return _get_nn_layers(model_spec)\n            else:\n                layers.extend(_get_nn_layers(model_spec))\n    elif spec.neuralNetwork.layers:\n        layers = spec.neuralNetwork.layers\n    elif spec.neuralNetworkClassifier.layers:\n        layers = spec.neuralNetworkClassifier.layers\n    elif spec.neuralNetworkRegressor.layers:\n        layers = spec.neuralNetworkRegressor.layers\n    return layers",
    "docstring": "Returns a list of neural network layers if the model contains any.\n\n    Parameters\n    ----------\n    spec: Model_pb\n        A model protobuf specification.\n\n    Returns\n    -------\n    [NN layer]\n        list of all layers (including layers from elements of a pipeline"
  },
  {
    "code": "def _enable_cleanup(func):\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        self = args[0]\n        result = func(*args, **kwargs)\n        self.cleanup(self)\n        return result\n    return wrapper",
    "docstring": "Execute cleanup operation when the decorated function completed."
  },
  {
    "code": "def get_extname(self):\n        name = self._info['extname']\n        if name.strip() == '':\n            name = self._info['hduname']\n        return name.strip()",
    "docstring": "Get the name for this extension, can be an empty string"
  },
  {
    "code": "def download(self, filename, representation, overwrite=False):\n        download(self.input, filename, representation, overwrite, self.resolvers, self.get3d, **self.kwargs)",
    "docstring": "Download the resolved structure as a file.\n\n        :param string filename: File path to save to\n        :param string representation: Desired output representation\n        :param bool overwrite: (Optional) Whether to allow overwriting of an existing file"
  },
  {
    "code": "def summarize(self):\n        data = [\n            ['Sequence ID', self.seqrecord.id],\n            ['G domain', ' '.join(self.gdomain_regions) if self.gdomain_regions else None],\n            ['E-value vs rab db', self.evalue_bh_rabs],\n            ['E-value vs non-rab db', self.evalue_bh_non_rabs],\n            ['RabF motifs', ' '.join(map(str, self.rabf_motifs)) if self.rabf_motifs else None],\n            ['Is Rab?', self.is_rab()]\n        ]\n        summary = ''\n        for name, value in data:\n            summary += '{:25s}{}\\n'.format(name, value)\n        if self.is_rab():\n            summary += '{:25s}{}\\n'.format('Top 5 subfamilies',\n                                           ', '.join('{:s} ({:.2g})'.format(name, score) for name, score\n                                                     in self.rab_subfamily_top5))\n        return summary",
    "docstring": "G protein annotation summary in a text format\n\n        :return: A string summary of the annotation\n        :rtype: str"
  },
  {
    "code": "def guess_strategy_type(file_name_or_ext):\n    if '.' not in file_name_or_ext:\n        ext = file_name_or_ext\n    else:\n        name, ext = os.path.splitext(file_name_or_ext)\n    ext = ext.lstrip('.')\n    file_type_map = get_file_type_map()\n    return file_type_map.get(ext, None)",
    "docstring": "Guess strategy type to use for file by extension.\n\n    Args:\n        file_name_or_ext: Either a file name with an extension or just\n            an extension\n\n    Returns:\n        Strategy: Type corresponding to extension or None if there's no\n            corresponding strategy type"
  },
  {
    "code": "def _register_resources(self, api_dirs, do_checks):\n        msg = 'Looking-up for APIs in the following directories: {}'\n        log.debug(msg.format(api_dirs))\n        if do_checks:\n            check_and_load(api_dirs)\n        else:\n            msg = 'Loading module \"{}\" from directory \"{}\"'\n            for loader, mname, _ in pkgutil.walk_packages(api_dirs):\n                sys.path.append(os.path.abspath(loader.path))\n                log.debug(msg.format(mname, loader.path))\n                import_module(mname)",
    "docstring": "Register all Apis, Resources and Models with the application."
  },
  {
    "code": "def is_pod_running(self, pod):\n        is_running = (\n            pod is not None and\n            pod.status.phase == 'Running' and\n            pod.status.pod_ip is not None and\n            pod.metadata.deletion_timestamp is None and\n            all([cs.ready for cs in pod.status.container_statuses])\n        )\n        return is_running",
    "docstring": "Check if the given pod is running\n\n        pod must be a dictionary representing a Pod kubernetes API object."
  },
  {
    "code": "def get_totals_by_payee(self, account, start_date=None, end_date=None):\n        qs = Transaction.objects.filter(account=account, parent__isnull=True)\n        qs = qs.values('payee').annotate(models.Sum('value_gross'))\n        qs = qs.order_by('payee__name')\n        return qs",
    "docstring": "Returns transaction totals grouped by Payee."
  },
  {
    "code": "def defaults(self):\n        (start, end) = get_week_window(timezone.now() - relativedelta(days=7))\n        return {\n            'from_date': start,\n            'to_date': end,\n            'billable': True,\n            'non_billable': False,\n            'paid_leave': False,\n            'trunc': 'day',\n            'projects': [],\n        }",
    "docstring": "Default filter form data when no GET data is provided."
  },
  {
    "code": "def launch(self):\n        import subprocess\n        try:\n            retcode = subprocess.call(self.fullname, shell=True)\n            if retcode < 0:\n                print(\"Child was terminated by signal\", -retcode, file=sys.stderr)\n                return False\n            else:\n                print(\"Child returned\", retcode, file=sys.stderr)\n                return True\n        except OSError as e:\n            print(\"Execution failed:\", e, file=sys.stderr)\n            return False",
    "docstring": "launch a file - used for starting html pages"
  },
  {
    "code": "def confirm_execution(self):\n        permit = ''\n        while permit.lower() not in ('yes', 'no'):\n            permit = input('Execute Proposed Plan? [yes/no] ')\n        if permit.lower() == 'yes':\n            return True\n        else:\n            return False",
    "docstring": "Confirm from your if proposed-plan be executed."
  },
  {
    "code": "def set_current_time(self, current_time):\n        current_time = c_double(current_time)\n        try:\n            self.library.set_current_time.argtypes = [POINTER(c_double)]\n            self.library.set_current_time.restype = None\n            self.library.set_current_time(byref(current_time))\n        except AttributeError:\n            logger.warn(\"Tried to set current time but method is not implemented in %s\", self.engine)",
    "docstring": "sets current time of simulation"
  },
  {
    "code": "def _container_whitelist(self):\n        if self.__container_whitelist is None:\n            self.__container_whitelist = \\\n                set(self.CLOUD_BROWSER_CONTAINER_WHITELIST or [])\n        return self.__container_whitelist",
    "docstring": "Container whitelist."
  },
  {
    "code": "def describe_security_groups(self, *names):\n        group_names = {}\n        if names:\n            group_names = dict([(\"GroupName.%d\" % (i + 1), name)\n                                for i, name in enumerate(names)])\n        query = self.query_factory(\n            action=\"DescribeSecurityGroups\", creds=self.creds,\n            endpoint=self.endpoint, other_params=group_names)\n        d = query.submit()\n        return d.addCallback(self.parser.describe_security_groups)",
    "docstring": "Describe security groups.\n\n        @param names: Optionally, a list of security group names to describe.\n            Defaults to all security groups in the account.\n        @return: A C{Deferred} that will fire with a list of L{SecurityGroup}s\n            retrieved from the cloud."
  },
  {
    "code": "def htmlMarkup(self, realm, return_to=None, immediate=False,\n            form_tag_attrs=None):\n        return oidutil.autoSubmitHTML(self.formMarkup(realm, \n                                                      return_to,\n                                                      immediate, \n                                                      form_tag_attrs))",
    "docstring": "Get an autosubmitting HTML page that submits this request to the\n        IDP.  This is just a wrapper for formMarkup.\n\n        @see: formMarkup\n\n        @returns: str"
  },
  {
    "code": "def next_line(last_line, next_line_8bit):\n    base_line = last_line - (last_line & 255)\n    line = base_line + next_line_8bit\n    lower_line = line - 256\n    upper_line = line + 256\n    if last_line - lower_line <= line - last_line:\n        return lower_line\n    if upper_line - last_line < last_line - line:\n        return upper_line\n    return line",
    "docstring": "Compute the next line based on the last line and a 8bit next line.\n\n    The behaviour of the function is specified in :ref:`reqline`.\n\n    :param int last_line: the last line that was processed\n    :param int next_line_8bit: the lower 8 bits of the next line\n    :return: the next line closest to :paramref:`last_line`\n\n    .. seealso:: :ref:`reqline`"
  },
  {
    "code": "def backwardeuler(dfun, xzero, timerange, timestep):\n    return zip(*list(BackwardEuler(dfun, xzero, timerange, timestep)))",
    "docstring": "Backward Euler method integration. This function wraps BackwardEuler.\n\n        :param dfun:\n            Derivative function of the system.\n            The differential system arranged as a series of first-order\n            equations: \\dot{X} = dfun(t, x)\n        :param xzero:\n            The initial condition of the system.\n        :param vzero:\n            The initial condition of first derivative of the system.\n        :param timerange:\n            The start and end times as (starttime, endtime).\n        :param timestep:\n           The timestep.\n        :param convergencethreshold:\n            Each step requires an iterative solution of an implicit equation.\n            This is the threshold of convergence.\n        :param maxiterations:\n            Maximum iterations of the implicit equation before raising\n            an exception.\n        :returns: t, x:\n            as lists."
  },
  {
    "code": "def addDataFrameColumn(self, columnName, dtype=str, defaultValue=None):\n        if not self.editable or dtype not in SupportedDtypes.allTypes():\n            return False\n        elements = self.rowCount()\n        columnPosition = self.columnCount()\n        newColumn = pandas.Series([defaultValue]*elements, index=self._dataFrame.index, dtype=dtype)\n        self.beginInsertColumns(QtCore.QModelIndex(), columnPosition - 1, columnPosition - 1)\n        try:\n            self._dataFrame.insert(columnPosition, columnName, newColumn, allow_duplicates=False)\n        except ValueError as e:\n            return False\n        self.endInsertColumns()\n        self.propagateDtypeChanges(columnPosition, newColumn.dtype)\n        return True",
    "docstring": "Adds a column to the dataframe as long as\n        the model's editable property is set to True and the\n        dtype is supported.\n\n        :param columnName: str\n            name of the column.\n        :param dtype: qtpandas.models.SupportedDtypes option\n        :param defaultValue: (object)\n            to default the column's value to, should be the same as the dtype or None\n        :return: (bool)\n            True on success, False otherwise."
  },
  {
    "code": "def send_custom_hsm(self, whatsapp_id, template_name, language, variables):\n        data = {\n            \"to\": whatsapp_id,\n            \"type\": \"hsm\",\n            \"hsm\": {\n                \"namespace\": self.hsm_namespace,\n                \"element_name\": template_name,\n                \"language\": {\"policy\": \"deterministic\", \"code\": language},\n                \"localizable_params\": [{\"default\": variable} for variable in variables],\n            },\n        }\n        if self.ttl is not None:\n            data[\"ttl\"] = self.ttl\n        response = self.session.post(\n            urllib_parse.urljoin(self.api_url, \"/v1/messages\"), json=data\n        )\n        return self.return_response(response)",
    "docstring": "Sends an HSM with more customizable fields than the send_hsm function"
  },
  {
    "code": "def append(self, filename_in_zip, file_contents):\n        self.in_memory_zip.seek(-1, io.SEEK_END)\n        zf = zipfile.ZipFile(self.in_memory_zip, \"a\", zipfile.ZIP_DEFLATED, False)\n        zf.writestr(filename_in_zip, file_contents)\n        for zfile in zf.filelist:\n            zfile.create_system = 0\n        zf.close()\n        self.in_memory_zip.seek(0)\n        return self",
    "docstring": "Appends a file with name filename_in_zip and contents of\n        file_contents to the in-memory zip."
  },
  {
    "code": "def point_consensus(self, consensus_type):\n        if \"mean\" in consensus_type:\n            consensus_data = np.mean(self.data, axis=0)\n        elif \"std\" in consensus_type:\n            consensus_data = np.std(self.data, axis=0)\n        elif \"median\" in consensus_type:\n            consensus_data = np.median(self.data, axis=0)\n        elif \"max\" in consensus_type:\n            consensus_data = np.max(self.data, axis=0)\n        elif \"percentile\" in consensus_type:\n            percentile = int(consensus_type.split(\"_\")[1])\n            consensus_data = np.percentile(self.data, percentile, axis=0)\n        else:\n            consensus_data = np.zeros(self.data.shape[1:])\n        consensus = EnsembleConsensus(consensus_data, consensus_type, self.ensemble_name,\n                                      self.run_date, self.variable, self.start_date, self.end_date, self.units)\n        return consensus",
    "docstring": "Calculate grid-point statistics across ensemble members.\n\n        Args:\n            consensus_type: mean, std, median, max, or percentile_nn\n\n        Returns:\n            EnsembleConsensus containing point statistic"
  },
  {
    "code": "def get(self, url, headers=None, **kwargs):\n        if headers is None: headers = []\n        if kwargs:\n            url = url + UrlEncoded('?' + _encode(**kwargs), skip_encode=True)\n        return self.request(url, { 'method': \"GET\", 'headers': headers })",
    "docstring": "Sends a GET request to a URL.\n\n        :param url: The URL.\n        :type url: ``string``\n        :param headers: A list of pairs specifying the headers for the HTTP\n            response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``).\n        :type headers: ``list``\n        :param kwargs: Additional keyword arguments (optional). These arguments\n            are interpreted as the query part of the URL. The order of keyword\n            arguments is not preserved in the request, but the keywords and\n            their arguments will be URL encoded.\n        :type kwargs: ``dict``\n        :returns: A dictionary describing the response (see :class:`HttpLib` for\n            its structure).\n        :rtype: ``dict``"
  },
  {
    "code": "def get_effective_agent_id_with_proxy(proxy):\n    if is_authenticated_with_proxy(proxy):\n        if proxy.has_effective_agent():\n            return proxy.get_effective_agent_id()\n        else:\n            return proxy.get_authentication().get_agent_id()\n    else:\n        return Id(\n            identifier='MC3GUE$T@MIT.EDU',\n            namespace='authentication.Agent',\n            authority='MIT-ODL')",
    "docstring": "Given a Proxy, returns the Id of the effective Agent"
  },
  {
    "code": "def _construct_location_to_filter_list(match_query):\n    location_to_filters = {}\n    for match_traversal in match_query.match_traversals:\n        for match_step in match_traversal:\n            current_filter = match_step.where_block\n            if current_filter is not None:\n                current_location = match_step.as_block.location\n                location_to_filters.setdefault(current_location, []).append(\n                    current_filter)\n    return location_to_filters",
    "docstring": "Return a dict mapping location -> list of filters applied at that location.\n\n    Args:\n        match_query: MatchQuery object from which to extract location -> filters dict\n\n    Returns:\n        dict mapping each location in match_query to a list of\n            Filter objects applied at that location"
  },
  {
    "code": "def arg_strings(parsed_args, name=None):\n    name = name or 'arg_strings'\n    value = getattr(parsed_args, name, [])\n    if isinstance(value, str):\n        return [value]\n    try:\n        return [v for v in value if isinstance(v, str)]\n    except TypeError:\n        return []",
    "docstring": "A list of all strings for the named arg"
  },
  {
    "code": "def _add_secondary_if_exists(secondary, out, get_retriever):\n    secondary = [_file_local_or_remote(y, get_retriever) for y in secondary]\n    secondary = [z for z in secondary if z]\n    if secondary:\n        out[\"secondaryFiles\"] = [{\"class\": \"File\", \"path\": f} for f in secondary]\n    return out",
    "docstring": "Add secondary files only if present locally or remotely."
  },
  {
    "code": "def generate_optimized_y_move_down_x_SOL(y_dist):\n    string = \"\\x1b[{0}E\".format(y_dist)\n    if y_dist < len(string):\n        string = '\\n' * y_dist\n    return string",
    "docstring": "move down y_dist, set x=0"
  },
  {
    "code": "def validate(self, *args):\n        super(self.__class__, self).validate(*args)\n        if not self.name:\n            raise ValidationError('name is required for Data')",
    "docstring": "Validate contents of class"
  },
  {
    "code": "def run_coral(clus_obj, out_dir, args):\n    if not args.bed:\n        raise ValueError(\"This module needs the bed file output from cluster subcmd.\")\n    workdir = op.abspath(op.join(args.out, 'coral'))\n    safe_dirs(workdir)\n    bam_in = op.abspath(args.bam)\n    bed_in = op.abspath(args.bed)\n    reference = op.abspath(args.ref)\n    with chdir(workdir):\n        bam_clean = coral.prepare_bam(bam_in, bed_in)\n        out_dir = op.join(workdir, \"regions\")\n        safe_dirs(out_dir)\n        prefix = \"seqcluster\"\n        loci_file = coral.detect_regions(bam_clean, bed_in, out_dir, prefix)\n        coral.create_features(bam_clean, loci_file, reference, out_dir)",
    "docstring": "Run some CoRaL modules to predict small RNA function"
  },
  {
    "code": "def fromexportupdate(cls, bundle, export_reg):\n        exc = export_reg.get_exception()\n        if exc:\n            return RemoteServiceAdminEvent(\n                RemoteServiceAdminEvent.EXPORT_ERROR,\n                bundle,\n                export_reg.get_export_container_id(),\n                export_reg.get_remoteservice_id(),\n                None,\n                export_reg.get_export_reference(),\n                None,\n                export_reg.get_description(),\n            )\n        return RemoteServiceAdminEvent(\n            RemoteServiceAdminEvent.EXPORT_UPDATE,\n            bundle,\n            export_reg.get_export_container_id(),\n            export_reg.get_remoteservice_id(),\n            None,\n            export_reg.get_export_reference(),\n            None,\n            export_reg.get_description(),\n        )",
    "docstring": "Creates a RemoteServiceAdminEvent object from the update of an\n        ExportRegistration"
  },
  {
    "code": "def drop_invalid_columns(feed: \"Feed\") -> \"Feed\":\n    feed = feed.copy()\n    for table, group in cs.GTFS_REF.groupby(\"table\"):\n        f = getattr(feed, table)\n        if f is None:\n            continue\n        valid_columns = group[\"column\"].values\n        for col in f.columns:\n            if col not in valid_columns:\n                print(f\"{table}: dropping invalid column {col}\")\n                del f[col]\n        setattr(feed, table, f)\n    return feed",
    "docstring": "Drop all DataFrame columns of the given \"Feed\" that are not\n    listed in the GTFS.\n    Return the resulting new \"Feed\"."
  },
  {
    "code": "def epoch(self):\n        epoch_sec = pytz.utc.localize(datetime.utcfromtimestamp(0))\n        now_sec = pytz.utc.normalize(self._dt)\n        delta_sec = now_sec - epoch_sec\n        return get_total_second(delta_sec)",
    "docstring": "Returns the total seconds since epoch associated with\n        the Delorean object.\n\n        .. testsetup::\n\n            from datetime import datetime\n            from delorean import Delorean\n\n        .. doctest::\n\n            >>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific')\n            >>> d.epoch\n            1420099200.0"
  },
  {
    "code": "def add_interrupt(self, interrupt):\n\t\tself.interrupts.append(interrupt)\n\t\tself.constants[interrupt.name] = interrupt.address",
    "docstring": "Adds the interrupt to the internal interrupt storage ``self.interrupts`` and\n\t\tregisters the interrupt address in the internal constants."
  },
  {
    "code": "def query_plugins(entry_point_name):\n    entries = {}\n    for entry_point in pkg_resources.iter_entry_points(entry_point_name):\n        entries[entry_point.name] = entry_point.load()\n    return entries",
    "docstring": "Find everything with a specific entry_point.  Results will be returned as a\n    dictionary, with the name as the key and the entry_point itself as the\n    value.\n\n    Arguments:\n    entry_point_name - the name of the entry_point to populate"
  },
  {
    "code": "def explode(self, hosts, hostgroups, contactgroups):\n        for i in self:\n            self.explode_host_groups_into_hosts(i, hosts, hostgroups)\n            self.explode_contact_groups_into_contacts(i, contactgroups)",
    "docstring": "Loop over all escalation and explode hostsgroups in host\n        and contactgroups in contacts\n\n        Call Item.explode_host_groups_into_hosts and Item.explode_contact_groups_into_contacts\n\n        :param hosts: host list to explode\n        :type hosts: alignak.objects.host.Hosts\n        :param hostgroups: hostgroup list to explode\n        :type hostgroups: alignak.objects.hostgroup.Hostgroups\n        :param contactgroups: contactgroup list to explode\n        :type contactgroups: alignak.objects.contactgroup.Contactgroups\n        :return: None"
  },
  {
    "code": "def get_mapping(self, meta_fields=True):\n        return {'properties': dict((name, field.json()) for name, field in iteritems(self.fields) if meta_fields or name not in AbstractField.meta_fields)}",
    "docstring": "Returns the mapping for the index as a dictionary.\n\n        :param meta_fields: Also include elasticsearch meta fields in the dictionary.\n        :return: a dictionary which can be used to generate the elasticsearch index mapping for this doctype."
  },
  {
    "code": "def get_include_fields(request):\n    include_fields = []\n    rif = request.get(\"include_fields\", \"\")\n    if \"include_fields\" in request:\n        include_fields = [x.strip()\n                          for x in rif.split(\",\")\n                          if x.strip()]\n    if \"include_fields[]\" in request:\n        include_fields = request['include_fields[]']\n    return include_fields",
    "docstring": "Retrieve include_fields values from the request"
  },
  {
    "code": "def _start(self):\n        self._enable_logpersist()\n        logcat_file_path = self._configs.output_file_path\n        if not logcat_file_path:\n            f_name = 'adblog,%s,%s.txt' % (self._ad.model,\n                                           self._ad._normalized_serial)\n            logcat_file_path = os.path.join(self._ad.log_path, f_name)\n        utils.create_dir(os.path.dirname(logcat_file_path))\n        cmd = '\"%s\" -s %s logcat -v threadtime %s >> \"%s\"' % (\n            adb.ADB, self._ad.serial, self._configs.logcat_params,\n            logcat_file_path)\n        process = utils.start_standing_subprocess(cmd, shell=True)\n        self._adb_logcat_process = process\n        self.adb_logcat_file_path = logcat_file_path",
    "docstring": "The actual logic of starting logcat."
  },
  {
    "code": "def discard_queue_messages(self):\n\t\tzmq_stream_queue = self.handler().stream()._send_queue\n\t\twhile not zmq_stream_queue.empty():\n\t\t\ttry:\n\t\t\t\tzmq_stream_queue.get(False)\n\t\t\texcept queue.Empty:\n\t\t\t\tcontinue\n\t\t\tzmq_stream_queue.task_done()",
    "docstring": "Sometimes it is necessary to drop undelivered messages. These messages may be stored in different\n\t\tcaches, for example in a zmq socket queue. With different zmq flags we can tweak zmq sockets and\n\t\tcontexts no to keep those messages. But inside ZMQStream class there is a queue that can not be\n\t\tcleaned other way then the way it does in this method. So yes, it is dirty to access protected\n\t\tmembers, and yes it can be broken at any moment. And yes without correct locking procedure there\n\t\tis a possibility of unpredicted behaviour. But still - there is no other way to drop undelivered\n\t\tmessages\n\n\t\tDiscussion of the problem: https://github.com/zeromq/pyzmq/issues/1095\n\n\t\t:return: None"
  },
  {
    "code": "def cli(env, identifier):\n    nw_mgr = SoftLayer.NetworkManager(env.client)\n    result = nw_mgr.get_nas_credentials(identifier)\n    table = formatting.Table(['username', 'password'])\n    table.add_row([result.get('username', 'None'),\n                   result.get('password', 'None')])\n    env.fout(table)",
    "docstring": "List NAS account credentials."
  },
  {
    "code": "def pickle_save(thing,fname=None):\n    if fname is None:\n        fname=os.path.expanduser(\"~\")+\"/%d.pkl\"%time.time()\n    assert type(fname) is str and os.path.isdir(os.path.dirname(fname))\n    pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n    print(\"saved\",fname)",
    "docstring": "save something to a pickle file"
  },
  {
    "code": "def set_process(self, process = None):\n        if process is None:\n            self.__process = None\n        else:\n            global Process\n            if Process is None:\n                from winappdbg.process import Process\n            if not isinstance(process, Process):\n                msg  = \"Parent process must be a Process instance, \"\n                msg += \"got %s instead\" % type(process)\n                raise TypeError(msg)\n            self.__process = process",
    "docstring": "Manually set the parent process. Use with care!\n\n        @type  process: L{Process}\n        @param process: (Optional) Process object. Use C{None} for no process."
  },
  {
    "code": "def camera_position(self, camera_location):\n        if camera_location is None:\n            return\n        if isinstance(camera_location, str):\n            camera_location = camera_location.lower()\n            if camera_location == 'xy':\n                self.view_xy()\n            elif camera_location == 'xz':\n                self.view_xz()\n            elif camera_location == 'yz':\n                self.view_yz()\n            elif camera_location == 'yx':\n                self.view_xy(True)\n            elif camera_location == 'zx':\n                self.view_xz(True)\n            elif camera_location == 'zy':\n                self.view_yz(True)\n            return\n        if isinstance(camera_location[0], (int, float)):\n            return self.view_vector(camera_location)\n        self.camera.SetPosition(camera_location[0])\n        self.camera.SetFocalPoint(camera_location[1])\n        self.camera.SetViewUp(camera_location[2])\n        self.ResetCameraClippingRange()\n        self.camera_set = True",
    "docstring": "Set camera position of all active render windows"
  },
  {
    "code": "def header_id_from_text(self, text, prefix, n):\n        header_id = _slugify(text)\n        if prefix and isinstance(prefix, base_string_type):\n            header_id = prefix + '-' + header_id\n        if header_id in self._count_from_header_id:\n            self._count_from_header_id[header_id] += 1\n            header_id += '-%s' % self._count_from_header_id[header_id]\n        else:\n            self._count_from_header_id[header_id] = 1\n        return header_id",
    "docstring": "Generate a header id attribute value from the given header\n        HTML content.\n\n        This is only called if the \"header-ids\" extra is enabled.\n        Subclasses may override this for different header ids.\n\n        @param text {str} The text of the header tag\n        @param prefix {str} The requested prefix for header ids. This is the\n            value of the \"header-ids\" extra key, if any. Otherwise, None.\n        @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag.\n        @returns {str} The value for the header tag's \"id\" attribute. Return\n            None to not have an id attribute and to exclude this header from\n            the TOC (if the \"toc\" extra is specified)."
  },
  {
    "code": "def write_mesh(fname, vertices, faces, normals, texcoords, name='',\n               format='obj', overwrite=False, reshape_faces=True):\n    if op.isfile(fname) and not overwrite:\n        raise IOError('file \"%s\" exists, use overwrite=True' % fname)\n    if format not in ('obj'):\n        raise ValueError('Only \"obj\" format writing currently supported')\n    WavefrontWriter.write(fname, vertices, faces,\n                          normals, texcoords, name, reshape_faces)",
    "docstring": "Write mesh data to file.\n\n    Parameters\n    ----------\n    fname : str\n        Filename to write. Must end with \".obj\" or \".gz\".\n    vertices : array\n        Vertices.\n    faces : array | None\n        Triangle face definitions.\n    normals : array\n        Normals for the mesh.\n    texcoords : array | None\n        Texture coordinates.\n    name : str\n        Name of the object.\n    format : str\n        Currently only \"obj\" is supported.\n    overwrite : bool\n        If the file exists, overwrite it.\n    reshape_faces : bool\n        Reshape the `faces` array to (Nf, 3). Set to `False`\n        if you need to write a mesh with non triangular faces."
  },
  {
    "code": "def getPositionByName(self, name):\n        try:\n            return self.__nameToPosMap[name]\n        except KeyError:\n            raise error.PyAsn1Error('Name %s not found' % (name,))",
    "docstring": "Return field position by filed name.\n\n        Parameters\n        ----------\n        name: :py:class:`str`\n            Field name\n\n        Returns\n        -------\n        : :py:class:`int`\n            Field position in fields set\n\n        Raises\n        ------\n        : :class:`~pyasn1.error.PyAsn1Error`\n            If *name* is not present or not unique within callee *NamedTypes*"
  },
  {
    "code": "def rotate(self, azimuth, axis=None):\n        target = self._target\n        y_axis = self._n_pose[:3, 1].flatten()\n        if axis is not None:\n            y_axis = axis\n        x_rot_mat = transformations.rotation_matrix(azimuth, y_axis, target)\n        self._n_pose = x_rot_mat.dot(self._n_pose)\n        y_axis = self._pose[:3, 1].flatten()\n        if axis is not None:\n            y_axis = axis\n        x_rot_mat = transformations.rotation_matrix(azimuth, y_axis, target)\n        self._pose = x_rot_mat.dot(self._pose)",
    "docstring": "Rotate the trackball about the \"Up\" axis by azimuth radians.\n\n        Parameters\n        ----------\n        azimuth : float\n            The number of radians to rotate."
  },
  {
    "code": "def edit(directory=None, revision='current'):\n    if alembic_version >= (0, 8, 0):\n        config = current_app.extensions['migrate'].migrate.get_config(\n            directory)\n        command.edit(config, revision)\n    else:\n        raise RuntimeError('Alembic 0.8.0 or greater is required')",
    "docstring": "Edit current revision."
  },
  {
    "code": "def trim_req(req):\n    reqfirst = next(iter(req))\n    if '.' in reqfirst:\n        return {reqfirst.split('.')[0]: req[reqfirst]}\n    return req",
    "docstring": "Trim any function off of a requisite"
  },
  {
    "code": "def _get_validated_stages(stages):\n    if not isinstance(stages, list):\n        raise WorkflowBuilderException(\"Stages must be specified as a list of dictionaries\")\n    validated_stages = []\n    for index, stage in enumerate(stages):\n        validated_stages.append(_get_validated_stage(stage, index))\n    return validated_stages",
    "docstring": "Validates stages of the workflow as a list of dictionaries."
  },
  {
    "code": "def post_build(self, p, pay):\n    p += pay\n    if self.type in [0, 0x31, 0x32, 0x22]:\n      p = p[:1]+chr(0)+p[2:]\n    if self.chksum is None:\n      ck = checksum(p[:2]+p[4:])\n      p = p[:2]+ck.to_bytes(2, 'big')+p[4:]\n    return p",
    "docstring": "Called implicitly before a packet is sent to compute and place IGMPv3 checksum.\n\n    Parameters:\n      self    The instantiation of an IGMPv3 class\n      p       The IGMPv3 message in hex in network byte order\n      pay     Additional payload for the IGMPv3 message"
  },
  {
    "code": "def draw_variable(loc, scale, shape, skewness, nsims):\n        return loc + scale*Skewt.rvs(shape, skewness, nsims)",
    "docstring": "Draws random variables from Skew t distribution\n\n        Parameters\n        ----------\n        loc : float\n            location parameter for the distribution\n\n        scale : float\n            scale parameter for the distribution\n\n        shape : float\n            tail thickness parameter for the distribution\n\n        skewness : float\n            skewness parameter for the distribution\n\n        nsims : int or list\n            number of draws to take from the distribution\n\n        Returns\n        ----------\n        - Random draws from the distribution"
  },
  {
    "code": "def request_eval(self, req, expression):\n        r = str(eval(expression))\n        self._eval_result.set_value(r)\n        return (\"ok\", r)",
    "docstring": "Evaluate a Python expression."
  },
  {
    "code": "async def open_async(self):\n        if not self.loop:\n            self.loop = asyncio.get_event_loop()\n        await self.partition_manager.start_async()",
    "docstring": "Starts the host."
  },
  {
    "code": "def match_patterns(pathname, patterns):\n    for pattern in patterns:\n        if fnmatch(pathname, pattern):\n            return True\n    return False",
    "docstring": "Returns ``True`` if the pathname matches any of the given patterns."
  },
  {
    "code": "def box_filter(array, n_iqr=1.5, return_index=False):\n    if not isinstance(array, np.ndarray):\n        array = np.array(array)\n    Q3 = np.percentile(array, 75)\n    Q1 = np.percentile(array, 25)\n    IQR = Q3 - Q1\n    lower, upper = Q1 - n_iqr * IQR, Q3 + n_iqr * IQR\n    good_index = np.where(np.logical_and(array >= lower, array <= upper))\n    bad_index = np.where(np.logical_or(array < lower, array > upper))\n    if return_index:\n        return good_index[0], bad_index[0]\n    else:\n        return array[good_index], array[bad_index]",
    "docstring": "Box plot outlier detector.\n\n    :param array: array of data.\n    :param n_std: default 1.5, exclude data out of ``n_iqr`` IQR.\n    :param return_index: boolean, default False, if True, only returns index."
  },
  {
    "code": "def cycle_class(self):\n        if isinstance(self, RelaxTask):\n            return abiinspect.Relaxation\n        elif isinstance(self, GsTask):\n            return abiinspect.GroundStateScfCycle\n        elif self.is_dfpt_task:\n            return abiinspect.D2DEScfCycle\n        return None",
    "docstring": "Return the subclass of ScfCycle associated to the task or\n        None if no SCF algorithm if associated to the task."
  },
  {
    "code": "def verify_arguments(self, args=None, kwargs=None):\n        args = self.args if args is None else args\n        kwargs = self.kwargs if kwargs is None else kwargs\n        try:\n            verify_arguments(self._target, self._method_name, args, kwargs)\n        except VerifyingBuiltinDoubleArgumentError:\n            if doubles.lifecycle.ignore_builtin_verification():\n                raise",
    "docstring": "Ensures that the arguments specified match the signature of the real method.\n\n        :raise: ``VerifyingDoubleError`` if the arguments do not match."
  },
  {
    "code": "def add_port(self, port):\n        self.ports.append(port)\n        if port.io_type not in self.port_seqs:\n            self.port_seqs[port.io_type] = 0\n        self.port_seqs[port.io_type] += 1\n        port.sequence = self.port_seqs[port.io_type]\n        return self",
    "docstring": "Add a port object to the definition\n\n        :param port: port definition\n        :type port: PortDef"
  },
  {
    "code": "def parse(self, charset=None, headers=None):\n        if headers:\n            self.headers = headers\n        else:\n            if self.head:\n                responses = self.head.rsplit(b'\\nHTTP/', 1)\n                _, response = responses[-1].split(b'\\n', 1)\n                response = response.decode('utf-8', 'ignore')\n            else:\n                response = u''\n            if six.PY2:\n                response = response.encode('utf-8')\n            self.headers = email.message_from_string(response)\n        if charset is None:\n            if isinstance(self.body, six.text_type):\n                self.charset = 'utf-8'\n            else:\n                self.detect_charset()\n        else:\n            self.charset = charset.lower()\n        self._unicode_body = None",
    "docstring": "Parse headers.\n\n        This method is called after Grab instance performs network request."
  },
  {
    "code": "def flaky(max_runs=None, min_passes=None, rerun_filter=None):\n    wrapped = None\n    if hasattr(max_runs, '__call__'):\n        wrapped, max_runs = max_runs, None\n    attrib = default_flaky_attributes(max_runs, min_passes, rerun_filter)\n    def wrapper(wrapped_object):\n        for name, value in attrib.items():\n            setattr(wrapped_object, name, value)\n        return wrapped_object\n    return wrapper(wrapped) if wrapped is not None else wrapper",
    "docstring": "Decorator used to mark a test as \"flaky\". When used in conjuction with\n    the flaky nosetests plugin, will cause the decorated test to be retried\n    until min_passes successes are achieved out of up to max_runs test runs.\n\n    :param max_runs:\n        The maximum number of times the decorated test will be run.\n    :type max_runs:\n        `int`\n    :param min_passes:\n        The minimum number of times the test must pass to be a success.\n    :type min_passes:\n        `int`\n    :param rerun_filter:\n        Filter function to decide whether a test should be rerun if it fails.\n        Function signature is as follows:\n            (err, name, test, plugin) -> should_rerun\n        - err (`tuple` of `class`, :class:`Exception`, `traceback`):\n            Information about the test failure (from sys.exc_info())\n        - name (`unicode`):\n            The test name\n        - test (:class:`nose.case.Test` or :class:`Function`):\n            The test that has raised an error\n        - plugin (:class:`FlakyNosePlugin` or :class:`FlakyPytestPlugin`):\n            The flaky plugin. Has a :prop:`stream` that can be written to in\n            order to add to the Flaky Report.\n    :type rerun_filter:\n        `callable`\n    :return:\n        A wrapper function that includes attributes describing the flaky test.\n    :rtype:\n        `callable`"
  },
  {
    "code": "def download_remote_video(self, remote_node, session_id, video_name):\n        try:\n            video_url = self._get_remote_video_url(remote_node, session_id)\n        except requests.exceptions.ConnectionError:\n            self.logger.warning(\"Remote server seems not to have video capabilities\")\n            return\n        if not video_url:\n            self.logger.warning(\"Test video not found in node '%s'\", remote_node)\n            return\n        self._download_video(video_url, video_name)",
    "docstring": "Download the video recorded in the remote node during the specified test session and save it in videos folder\n\n        :param remote_node: remote node name\n        :param session_id: test session id\n        :param video_name: video name"
  },
  {
    "code": "def component_mul(vec1, vec2):\n        new_vec = Vector2()\n        new_vec.X = vec1.X * vec2.X\n        new_vec.Y = vec1.Y * vec2.Y\n        return new_vec",
    "docstring": "Multiply the components of the vectors and return the result."
  },
  {
    "code": "def create(klass, account, name):\n        audience = klass(account)\n        getattr(audience, '__create_audience__')(name)\n        try:\n            return audience.reload()\n        except BadRequest as e:\n            audience.delete()\n            raise e",
    "docstring": "Creates a new tailored audience."
  },
  {
    "code": "def unmount(self, path):\n        del self._mountpoints[self._join_chunks(self._normalize_path(path))]",
    "docstring": "Remove a mountpoint from the filesystem."
  },
  {
    "code": "def fulfill(self):\n        is_fulfilled, result = self._check_fulfilled()\n        if is_fulfilled:\n            return result\n        else:\n            raise BrokenPromise(self)",
    "docstring": "Evaluate the promise and return the result.\n\n        Returns:\n             The result of the `Promise` (second return value from the `check_func`)\n\n        Raises:\n            BrokenPromise: the `Promise` was not satisfied within the time or attempt limits."
  },
  {
    "code": "def passive_mode(self) -> Tuple[str, int]:\n        yield from self._control_stream.write_command(Command('PASV'))\n        reply = yield from self._control_stream.read_reply()\n        self.raise_if_not_match(\n            'Passive mode', ReplyCodes.entering_passive_mode, reply)\n        try:\n            return wpull.protocol.ftp.util.parse_address(reply.text)\n        except ValueError as error:\n            raise ProtocolError(str(error)) from error",
    "docstring": "Enable passive mode.\n\n        Returns:\n            The address (IP address, port) of the passive port.\n\n        Coroutine."
  },
  {
    "code": "def add_exp_key(self, key, value, ex):\n        \"Expired in seconds\"\n        return self.c.set(key, value, ex)",
    "docstring": "Expired in seconds"
  },
  {
    "code": "def flip(f):\n    def wrapped(*args, **kwargs):\n        return f(*flip_first_two(args), **kwargs)\n    f_spec = make_func_curry_spec(f)\n    return curry_by_spec(f_spec, wrapped)",
    "docstring": "Calls the function f by flipping the first two positional\n    arguments"
  },
  {
    "code": "def unique(self, key=None):\n        if isinstance(key, basestring):\n            key = lambda r, attr=key: getattr(r, attr, None)\n        ret = self.copy_template()\n        seen = set()\n        for ob in self:\n            if key is None:\n                try:\n                    ob_dict = vars(ob)\n                except TypeError:\n                    ob_dict = dict((k, getattr(ob, k)) for k in _object_attrnames(ob))\n                reckey = tuple(sorted(ob_dict.items()))\n            else:\n                reckey = key(ob)\n            if reckey not in seen:\n                seen.add(reckey)\n                ret.insert(ob)\n        return ret",
    "docstring": "Create a new table of objects,containing no duplicate values.\n\n        @param key: (default=None) optional callable for computing a representative unique key for each\n        object in the table. If None, then a key will be composed as a tuple of all the values in the object.\n        @type key: callable, takes the record as an argument, and returns the key value or tuple to be used\n        to represent uniqueness."
  },
  {
    "code": "def _set_expressions(self, expressions):\n        Symbolic_core._set_expressions(self, expressions)\n        Symbolic_core._set_variables(self, self.cacheable)\n        for x, z in zip(self.variables['X'], self.variables['Z']):\n            expressions['kdiag'] = expressions['kdiag'].subs(z, x)\n        Symbolic_core._set_expressions(self, expressions)",
    "docstring": "This method is overwritten because we need to modify kdiag by substituting z for x. We do this by calling the parent expression method to extract variables from expressions, then subsitute the z variables that are present with x."
  },
  {
    "code": "def get(self, indexes, as_list=False):\n        if isinstance(indexes, (list, blist)):\n            return self.get_rows(indexes, as_list)\n        else:\n            return self.get_cell(indexes)",
    "docstring": "Given indexes will return a sub-set of the Series. This method will direct to the specific methods\n        based on what types are passed in for the indexes. The type of the return is determined by the\n        types of the parameters.\n\n        :param indexes: index value, list of index values, or a list of booleans.\n        :param as_list: if True then return the values as a list, if False return a Series.\n        :return: either Series, list, or single value. The return is a shallow copy"
  },
  {
    "code": "def ecoclass_to_coderef(self, cls):\n        code = ''\n        ref = None\n        for (code,ref,this_cls) in self.mappings():\n            if cls == this_cls:\n                return code, ref\n        return None, None",
    "docstring": "Map an ECO class to a GAF code\n\n        This is the reciprocal to :ref:`coderef_to_ecoclass`\n\n        Arguments\n        ---------\n        cls : str\n            GAF evidence code, e.g. ISS, IDA\n        reference: str\n            ECO class CURIE/ID\n\n        Return\n        ------\n        (str, str)\n            code, reference tuple"
  },
  {
    "code": "def build(matrix):\n    max_x = max(matrix, key=lambda t: t[0])[0]\n    min_x = min(matrix, key=lambda t: t[0])[0]\n    max_y = max(matrix, key=lambda t: t[1])[1]\n    min_y = min(matrix, key=lambda t: t[1])[1]\n    yield from (\n        ''.join(matrix[i, j] for i in range(min_x, max_x+1))\n        for j in range(min_y, max_y+1)\n    )",
    "docstring": "Yield lines generated from given matrix"
  },
  {
    "code": "def df2sd(self, df: 'pd.DataFrame', table: str = '_df', libref: str = '',\n              results: str = '', keep_outer_quotes: bool = False) -> 'SASdata':\n        return self.dataframe2sasdata(df, table, libref, results, keep_outer_quotes)",
    "docstring": "This is an alias for 'dataframe2sasdata'. Why type all that?\n\n        :param df: :class:`pandas.DataFrame` Pandas Data Frame to import to a SAS Data Set\n        :param table: the name of the SAS Data Set to create\n        :param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned\n        :param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives\n        :param keep_outer_quotes: the defualt is for SAS to strip outer quotes from delimitted data. This lets you keep them\n        :return: SASdata object"
  },
  {
    "code": "def to_array(self):\n        array = super(ShippingAddress, self).to_array()\n        array['country_code'] = u(self.country_code)\n        array['state'] = u(self.state)\n        array['city'] = u(self.city)\n        array['street_line1'] = u(self.street_line1)\n        array['street_line2'] = u(self.street_line2)\n        array['post_code'] = u(self.post_code)\n        return array",
    "docstring": "Serializes this ShippingAddress to a dictionary.\n\n        :return: dictionary representation of this object.\n        :rtype: dict"
  },
  {
    "code": "def audits(self, ticket=None, include=None, **kwargs):\n        if ticket is not None:\n            return self._query_zendesk(self.endpoint.audits, 'ticket_audit', id=ticket, include=include)\n        else:\n            return self._query_zendesk(self.endpoint.audits.cursor, 'ticket_audit', include=include, **kwargs)",
    "docstring": "Retrieve TicketAudits. If ticket is passed, return the tickets for a specific audit.\n\n        If ticket_id is None, a TicketAuditGenerator is returned to handle pagination. The way this generator\n        works is a different to the other Zenpy generators as it is cursor based, allowing you to change the\n        direction that you are consuming objects. This is done with the reversed() python method.\n\n        For example:\n\n        .. code-block:: python\n\n            for audit in reversed(zenpy_client.tickets.audits()):\n                print(audit)\n\n        See the `Zendesk docs <https://developer.zendesk.com/rest_api/docs/core/ticket_audits#pagination>`__ for\n        information on additional parameters.\n\n        :param include: list of objects to sideload. `Side-loading API Docs \n            <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.\n        :param ticket: Ticket object or id"
  },
  {
    "code": "def _get_mu_tensor(self):\n    root = self._get_cubic_root()\n    dr = self._h_max / self._h_min\n    mu = tf.maximum(\n        root**2, ((tf.sqrt(dr) - 1) / (tf.sqrt(dr) + 1))**2)\n    return mu",
    "docstring": "Get the min mu which minimize the surrogate.\n\n    Returns:\n      The mu_t."
  },
  {
    "code": "def timestamp_from_datetime(dt):\n    try:\n        utc_dt = dt.astimezone(pytz.utc)\n    except ValueError:\n        utc_dt = dt.replace(tzinfo=pytz.utc)\n    return timegm(utc_dt.timetuple())",
    "docstring": "Compute timestamp from a datetime object that could be timezone aware\n    or unaware."
  },
  {
    "code": "def save_pip(self, out_dir):\n        try:\n            import pkg_resources\n            installed_packages = [d for d in iter(pkg_resources.working_set)]\n            installed_packages_list = sorted(\n                [\"%s==%s\" % (i.key, i.version) for i in installed_packages]\n            )\n            with open(os.path.join(out_dir, 'requirements.txt'), 'w') as f:\n                f.write(\"\\n\".join(installed_packages_list))\n        except Exception as e:\n            logger.error(\"Error saving pip packages\")",
    "docstring": "Saves the current working set of pip packages to requirements.txt"
  },
  {
    "code": "async def _senddms(self):\n        data = self.bot.config.get(\"meta\", {})\n        tosend = data.get('send_dms', True)\n        data['send_dms'] = not tosend\n        await self.bot.config.put('meta', data)\n        await self.bot.responses.toggle(message=\"Forwarding of DMs to owner has been {status}.\", success=data['send_dms'])",
    "docstring": "Toggles sending DMs to owner."
  },
  {
    "code": "def take(self, n):\n        if n <= 0:\n            return self._transform(transformations.take_t(0))\n        else:\n            return self._transform(transformations.take_t(n))",
    "docstring": "Take the first n elements of the sequence.\n\n        >>> seq([1, 2, 3, 4]).take(2)\n        [1, 2]\n\n        :param n: number of elements to take\n        :return: first n elements of sequence"
  },
  {
    "code": "def generate_brome_config():\n    config = {}\n    for key in iter(default_config):\n        for inner_key, value in iter(default_config[key].items()):\n            if key not in config:\n                config[key] = {}\n            config[key][inner_key] = value['default']\n    return config",
    "docstring": "Generate a brome config with default value\n\n    Returns:\n        config (dict)"
  },
  {
    "code": "def hasBeenRotated(self):\n      try:\n         return os.stat(self._path).st_ino != self._inode\n      except OSError:\n         return True",
    "docstring": "Returns a boolean indicating whether the file has been removed and recreated during the time it has been open."
  },
  {
    "code": "def static_dag_launchpoint(job, job_vars):\n    input_args, ids = job_vars\n    if input_args['config_fastq']:\n        cores = input_args['cpu_count']\n        a = job.wrapJobFn(mapsplice, job_vars, cores=cores, disk='130G').encapsulate()\n    else:\n        a = job.wrapJobFn(merge_fastqs, job_vars, disk='70 G').encapsulate()\n    b = job.wrapJobFn(consolidate_output, job_vars, a.rv())\n    job.addChild(a)\n    a.addChild(b)",
    "docstring": "Statically define jobs in the pipeline\n\n    job_vars: tuple     Tuple of dictionaries: input_args and ids"
  },
  {
    "code": "def cursor_save_attrs (self):\n        self.cur_saved_r = self.cur_r\n        self.cur_saved_c = self.cur_c",
    "docstring": "Save current cursor position."
  },
  {
    "code": "async def command(dev, service, method, parameters):\n    params = None\n    if parameters is not None:\n        params = ast.literal_eval(parameters)\n    click.echo(\"Calling %s.%s with params %s\" % (service, method, params))\n    res = await dev.raw_command(service, method, params)\n    click.echo(res)",
    "docstring": "Run a raw command."
  },
  {
    "code": "def set_forbidden_types(self, types):\n        if self._forbidden_types == types:\n            return\n        self._forbidden_types = types\n        self.invalidateFilter()",
    "docstring": "Set all forbidden type values\n\n        :param typees: a list with forbidden type values\n        :type typees: list\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def write_file(self, filename=\"paths.dat\"):\n        with zopen(filename, \"wt\") as f:\n            f.write(str(self) + \"\\n\")",
    "docstring": "Write paths.dat."
  },
  {
    "code": "def section_path_lengths(neurites, neurite_type=NeuriteType.all):\n    dist = {}\n    neurite_filter = is_type(neurite_type)\n    for s in iter_sections(neurites, neurite_filter=neurite_filter):\n        dist[s] = s.length\n    def pl2(node):\n        return sum(dist[n] for n in node.iupstream())\n    return map_sections(pl2, neurites, neurite_type=neurite_type)",
    "docstring": "Path lengths of a collection of neurites"
  },
  {
    "code": "def get_rule(self, template_name):\n        for regex, render_func in self.rules:\n            if re.match(regex, template_name):\n                return render_func\n        raise ValueError(\"no matching rule\")",
    "docstring": "Find a matching compilation rule for a function.\n\n        Raises a :exc:`ValueError` if no matching rule can be found.\n\n        :param template_name: the name of the template"
  },
  {
    "code": "def format_progress(i, n):\r\n    if n == 0:\r\n        fraction = 0\r\n    else:\r\n        fraction = float(i)/n\r\n    LEN_BAR = 25\r\n    num_plus = int(round(fraction*LEN_BAR))\r\n    s_plus = '+'*num_plus\r\n    s_point = '.'*(LEN_BAR-num_plus)\r\n    return '[{0!s}{1!s}] {2:d}/{3:d} - {4:.1f}%'.format(s_plus, s_point, i, n, fraction*100)",
    "docstring": "Returns string containing a progress bar, a percentage, etc."
  },
  {
    "code": "def normalize_placeholders(arg, inject_quotes=False):\n    number_placeholders = re.findall(r'{{\\s*\\d+\\s*}}', arg)\n    for number_placeholder in number_placeholders:\n        number = re.search(r'\\d+', number_placeholder).group()\n        arg = arg.replace(number_placeholder, '{{_' + number + '}}')\n    return arg.replace('{{', '\"{{').replace('}}', '}}\"') if inject_quotes else arg",
    "docstring": "Normalize placeholders' names so that the template can be ingested into Jinja template engine.\n    - Jinja does not accept numbers as placeholder names, so add a \"_\"\n        before the numbers to make them valid placeholder names.\n    - Surround placeholders expressions with \"\" so we can preserve spaces inside the positional arguments.\n\n    Args:\n        arg: The string to process.\n        inject_qoutes: True if we want to surround placeholders with a pair of quotes.\n\n    Returns:\n        A processed string where placeholders are surrounded by \"\" and\n        numbered placeholders are prepended with \"_\"."
  },
  {
    "code": "def transform(self, Y):\n        try:\n            return self.data_pca.transform(Y)\n        except AttributeError:\n            try:\n                if Y.shape[1] != self.data.shape[1]:\n                    raise ValueError\n                return Y\n            except IndexError:\n                raise ValueError\n        except ValueError:\n            raise ValueError(\"data of shape {} cannot be transformed\"\n                             \" to graph built on data of shape {}\".format(\n                                 Y.shape, self.data.shape))",
    "docstring": "Transform input data `Y` to reduced data space defined by `self.data`\n\n        Takes data in the same ambient space as `self.data` and transforms it\n        to be in the same reduced space as `self.data_nu`.\n\n        Parameters\n        ----------\n        Y : array-like, shape=[n_samples_y, n_features]\n            n_features must be the same as `self.data`.\n\n        Returns\n        -------\n        Transformed data, shape=[n_samples_y, n_pca]\n\n        Raises\n        ------\n        ValueError : if Y.shape[1] != self.data.shape[1]"
  },
  {
    "code": "def get_session_identifiers(cls, folder=None, inputfile=None):\n        sessions = []\n        if inputfile and folder:\n            raise MQ2Exception(\n                'You should specify either a folder or a file')\n        if folder:\n            if not os.path.isdir(folder):\n                return sessions\n            for root, dirs, files in os.walk(folder):\n                for filename in files:\n                    filename = os.path.join(root, filename)\n                    for ext in SUPPORTED_FILES:\n                        if filename.endswith(ext):\n                            wbook = xlrd.open_workbook(filename)\n                            for sheet in wbook.sheets():\n                                if sheet.name not in sessions:\n                                    sessions.append(sheet.name)\n        elif inputfile:\n            if os.path.isdir(inputfile):\n                return sessions\n            for ext in SUPPORTED_FILES:\n                if inputfile.endswith(ext):\n                    wbook = xlrd.open_workbook(inputfile)\n                    for sheet in wbook.sheets():\n                        if sheet.name not in sessions:\n                            sessions.append(sheet.name)\n        return sessions",
    "docstring": "Retrieve the list of session identifiers contained in the\n        data on the folder or the inputfile.\n        For this plugin, it returns the list of excel sheet available.\n\n        :kwarg folder: the path to the folder containing the files to\n            check. This folder may contain sub-folders.\n        :kwarg inputfile: the path to the input file to use"
  },
  {
    "code": "def from_dsn(cls, dsn, **kwargs):\n        r\n        init_args = _parse_dsn(dsn)\n        host, port = init_args.pop('hosts')[0]\n        init_args['host'] = host\n        init_args['port'] = port\n        init_args.update(kwargs)\n        return cls(**init_args)",
    "docstring": "r\"\"\"Generate an instance of InfluxDBClient from given data source name.\n\n        Return an instance of :class:`~.InfluxDBClient` from the provided\n        data source name. Supported schemes are \"influxdb\", \"https+influxdb\"\n        and \"udp+influxdb\". Parameters for the :class:`~.InfluxDBClient`\n        constructor may also be passed to this method.\n\n        :param dsn: data source name\n        :type dsn: string\n        :param kwargs: additional parameters for `InfluxDBClient`\n        :type kwargs: dict\n        :raises ValueError: if the provided DSN has any unexpected values\n\n        :Example:\n\n        ::\n\n            >> cli = InfluxDBClient.from_dsn('influxdb://username:password@\\\n            localhost:8086/databasename', timeout=5)\n            >> type(cli)\n            <class 'influxdb.client.InfluxDBClient'>\n            >> cli = InfluxDBClient.from_dsn('udp+influxdb://username:pass@\\\n            localhost:8086/databasename', timeout=5, udp_port=159)\n            >> print('{0._baseurl} - {0.use_udp} {0.udp_port}'.format(cli))\n            http://localhost:8086 - True 159\n\n        .. note:: parameters provided in `**kwargs` may override dsn parameters\n        .. note:: when using \"udp+influxdb\" the specified port (if any) will\n            be used for the TCP connection; specify the UDP port with the\n            additional `udp_port` parameter (cf. examples)."
  },
  {
    "code": "def fft(xi, yi, axis=0) -> tuple:\n    if xi.ndim != 1:\n        raise wt_exceptions.DimensionalityError(1, xi.ndim)\n    spacing = np.diff(xi)\n    if not np.allclose(spacing, spacing.mean()):\n        raise RuntimeError(\"WrightTools.kit.fft: argument xi must be evenly spaced\")\n    yi = np.fft.fft(yi, axis=axis)\n    d = (xi.max() - xi.min()) / (xi.size - 1)\n    xi = np.fft.fftfreq(xi.size, d=d)\n    xi = np.fft.fftshift(xi)\n    yi = np.fft.fftshift(yi, axes=axis)\n    return xi, yi",
    "docstring": "Take the 1D FFT of an N-dimensional array and return \"sensible\" properly shifted arrays.\n\n    Parameters\n    ----------\n    xi : numpy.ndarray\n        1D array over which the points to be FFT'ed are defined\n    yi : numpy.ndarray\n        ND array with values to FFT\n    axis : int\n        axis of yi to perform FFT over\n\n    Returns\n    -------\n    xi : 1D numpy.ndarray\n        1D array. Conjugate to input xi. Example: if input xi is in the time\n        domain, output xi is in frequency domain.\n    yi : ND numpy.ndarray\n        FFT. Has the same shape as the input array (yi)."
  },
  {
    "code": "def to_sky(self, wcs, mode='all'):\n        sky_params = self._to_sky_params(wcs, mode=mode)\n        return SkyEllipticalAnnulus(**sky_params)",
    "docstring": "Convert the aperture to a `SkyEllipticalAnnulus` object defined\n        in celestial coordinates.\n\n        Parameters\n        ----------\n        wcs : `~astropy.wcs.WCS`\n            The world coordinate system (WCS) transformation to use.\n\n        mode : {'all', 'wcs'}, optional\n            Whether to do the transformation including distortions\n            (``'all'``; default) or only including only the core WCS\n            transformation (``'wcs'``).\n\n        Returns\n        -------\n        aperture : `SkyEllipticalAnnulus` object\n            A `SkyEllipticalAnnulus` object."
  },
  {
    "code": "def load_datafile(self, name, search_path=None, **kwargs):\n        if not search_path:\n            search_path = self.define_dir\n        self.debug_msg('loading datafile %s from %s' % (name, str(search_path)))\n        return codec.load_datafile(name, search_path, **kwargs)",
    "docstring": "find datafile and load them from codec"
  },
  {
    "code": "def set_meta_rdf(self, rdf, fmt='n3'):\n        evt = self._client._request_point_meta_set(self._type, self.__lid, self.__pid, rdf, fmt=fmt)\n        self._client._wait_and_except_if_failed(evt)",
    "docstring": "Set the metadata for this Point in rdf fmt"
  },
  {
    "code": "def add_reward_function(self):\n        reward_function = self.model['reward_function']\n        for condition in reward_function:\n            condprob = etree.SubElement(self.reward_function, 'Func')\n            self.add_conditions(condition, condprob)\n        return self.__str__(self.reward_function)[:-1]",
    "docstring": "add reward function tag to pomdpx model\n\n        Return\n        ---------------\n        string containing the xml for reward function tag"
  },
  {
    "code": "def encode (self):\n    return self.attrs.encode() + self.delay.encode() + self.cmd.encode()",
    "docstring": "Encodes this SeqCmd to binary and returns a bytearray."
  },
  {
    "code": "def qstat(jobid, context='grid'):\n  scmd = ['qstat', '-j', '%d' % jobid, '-f']\n  logger.debug(\"Qstat command '%s'\", ' '.join(scmd))\n  from .setshell import sexec\n  data = str_(sexec(context, scmd, error_on_nonzero=False))\n  retval = {}\n  for line in data.split('\\n'):\n    s = line.strip()\n    if s.lower().find('do not exist') != -1: return {}\n    if not s or s.find(10*'=') != -1: continue\n    kv = QSTAT_FIELD_SEPARATOR.split(s, 1)\n    if len(kv) == 2: retval[kv[0]] = kv[1]\n  return retval",
    "docstring": "Queries status of a given job.\n\n  Keyword parameters:\n\n  jobid\n    The job identifier as returned by qsub()\n\n  context\n    The setshell context in which we should try a 'qsub'. Normally you don't\n    need to change the default. This variable can also be set to a context\n    dictionary in which case we just setup using that context instead of\n    probing for a new one, what can be fast.\n\n  Returns a dictionary with the specific job properties"
  },
  {
    "code": "def spa_length_in_time(**kwds):\n    m1 = kwds['mass1']\n    m2 = kwds['mass2']\n    flow = kwds['f_lower']\n    porder = int(kwds['phase_order'])\n    return findchirp_chirptime(m1, m2, flow, porder)",
    "docstring": "Returns the length in time of the template,\n    based on the masses, PN order, and low-frequency\n    cut-off."
  },
  {
    "code": "def delete_api_key(self, api_key_id):\n        api = self._get_api(iam.DeveloperApi)\n        api.delete_api_key(api_key_id)\n        return",
    "docstring": "Delete an API key registered in the organisation.\n\n        :param str api_key_id: The ID of the API key (Required)\n        :returns: void"
  },
  {
    "code": "def remove(self, item):\n        check_not_none(item, \"Value can't be None\")\n        item_data = self._to_data(item)\n        return self._encode_invoke(list_remove_codec, value=item_data)",
    "docstring": "Removes the specified element's first occurrence from the list if it exists in this list.\n\n        :param item: (object), the specified element.\n        :return: (bool), ``true`` if the specified element is present in this list."
  },
  {
    "code": "def _scale_tensor(tensor, range_min, range_max, scale_min, scale_max):\n  if range_min == range_max:\n    return tensor\n  float_tensor = tf.to_float(tensor)\n  scaled_tensor = tf.divide((tf.subtract(float_tensor, range_min) *\n                             tf.constant(float(scale_max - scale_min))),\n                            tf.constant(float(range_max - range_min)))\n  shifted_tensor = scaled_tensor + tf.constant(float(scale_min))\n  return shifted_tensor",
    "docstring": "Scale a tensor to scale_min to scale_max.\n\n  Args:\n    tensor: input tensor. Should be a numerical tensor.\n    range_min: min expected value for this feature/tensor.\n    range_max: max expected Value.\n    scale_min: new expected min value.\n    scale_max: new expected max value.\n\n  Returns:\n    scaled tensor."
  },
  {
    "code": "def function(self, function_name, word):\n        word = self._parse_filter_word(word)\n        self._add_filter(\n            *self._prepare_function(function_name, self._attribute, word,\n                                    self._negation))\n        return self",
    "docstring": "Apply a function on given word\n\n        :param str function_name: function to apply\n        :param str word: word to apply function on\n        :rtype: Query"
  },
  {
    "code": "def run(self, once=False):\n        self._once = once\n        self.start()\n        while self.running:\n            try:\n                time.sleep(1.0)\n            except KeyboardInterrupt:\n                self.stop()\n                self.join()",
    "docstring": "Runs the reactor in the main thread."
  },
  {
    "code": "def getStats(self):\n        stats = protocol.ReadStats()\n        stats.aligned_read_count = self.getNumAlignedReads()\n        stats.unaligned_read_count = self.getNumUnalignedReads()\n        return stats",
    "docstring": "Returns the GA4GH protocol representation of this read group's\n        ReadStats."
  },
  {
    "code": "def send(self, auth_header=None, callback=None, **data):\n        message = self.encode(data)\n        return self.send_encoded(message, auth_header=auth_header, callback=callback)",
    "docstring": "Serializes the message and passes the payload onto ``send_encoded``."
  },
  {
    "code": "def make_global_and_nonlocal_decls(code_instrs):\n    globals_ = sorted(set(\n        i.arg for i in code_instrs if isinstance(i, instrs.STORE_GLOBAL)\n    ))\n    nonlocals = sorted(set(\n        i.arg for i in code_instrs\n        if isinstance(i, instrs.STORE_DEREF) and i.vartype == 'free'\n    ))\n    out = []\n    if globals_:\n        out.append(ast.Global(names=globals_))\n    if nonlocals:\n        out.append(ast.Nonlocal(names=nonlocals))\n    return out",
    "docstring": "Find all STORE_GLOBAL and STORE_DEREF instructions in `instrs` and convert\n    them into a canonical list of `ast.Global` and `ast.Nonlocal` declarations."
  },
  {
    "code": "def info(args):\n    session = c.Session(args)\n    if \"all\" in args[\"names\"]:\n        feeds = session.list_feeds()\n    else:\n        feeds = args[\"names\"]\n    for feed in feeds:\n        aux.pretty_print(session, feed)",
    "docstring": "Provide information of a number of feeds"
  },
  {
    "code": "def load_migration_file(self, filename):\n        path = os.path.join(self.directory, filename)\n        module = imp.load_source(\"migration\", path)\n        return module",
    "docstring": "Load migration file as module."
  },
  {
    "code": "def render(self, container, rerender=False):\n        if rerender:\n            container.clear()\n            if not self._rerendering:\n                self._state = copy(self._fresh_page_state)\n                self._rerendering = True\n        try:\n            self.done = False\n            self.flowables.flow(container, last_descender=None,\n                                state=self._state)\n            if container == self.last_container:\n                self._init_state()\n            self.done = True\n        except PageBreakException as exc:\n            self._state = exc.flowable_state\n            self._fresh_page_state = copy(self._state)\n            raise\n        except EndOfContainer as e:\n            self._state = e.flowable_state\n            if container == self.last_container:\n                self._fresh_page_state = copy(self._state)\n        except ReflowRequired:\n            self._rerendering = False\n            raise",
    "docstring": "Flow the flowables into the containers that have been added to this\n        chain."
  },
  {
    "code": "def get_first_webview_context(self):\n        for context in self.driver_wrapper.driver.contexts:\n            if context.startswith('WEBVIEW'):\n                return context\n        raise Exception('No WEBVIEW context has been found')",
    "docstring": "Return the first WEBVIEW context or raise an exception if it is not found\n\n        :returns: first WEBVIEW context"
  },
  {
    "code": "def normal_meanvar(data):\n    data = np.hstack(([0.0], np.array(data)))\n    cumm = np.cumsum(data)\n    cumm_sq = np.cumsum([val**2 for val in data])\n    def cost(s, t):\n        ts_i = 1.0 / (t-s)\n        mu = (cumm[t] - cumm[s]) * ts_i\n        sig = (cumm_sq[t] - cumm_sq[s]) * ts_i - mu**2\n        sig_i = 1.0 / sig\n        return (t-s) * np.log(sig) + (cumm_sq[t] - cumm_sq[s]) * sig_i - 2*(cumm[t] - cumm[s])*mu*sig_i + ((t-s)*mu**2)*sig_i\n    return cost",
    "docstring": "Creates a segment cost function for a time series with a\n        Normal distribution with changing mean and variance\n\n    Args:\n        data (:obj:`list` of float): 1D time series data\n    Returns:\n        function: Function with signature\n            (int, int) -> float\n            where the first arg is the starting index, and the second\n            is the last arg. Returns the cost of that segment"
  },
  {
    "code": "def on_redis_error(self, fname, exc_type, exc_value):\n        if self.shared_client:\n            Storage.storage = None\n        else:\n            self.storage = None\n        if self.context.config.REDIS_STORAGE_IGNORE_ERRORS is True:\n            logger.error(\"[REDIS_STORAGE] %s\" % exc_value)\n            if fname == '_exists':\n                return False\n            return None\n        else:\n            raise exc_value",
    "docstring": "Callback executed when there is a redis error.\n\n        :param string fname: Function name that was being called.\n        :param type exc_type: Exception type\n        :param Exception exc_value: The current exception\n        :returns: Default value or raise the current exception"
  },
  {
    "code": "def has_next(self):\n        try:\n            next_item = self.paginator.object_list[self.paginator.per_page]\n        except IndexError:\n            return False\n        return True",
    "docstring": "Checks for one more item than last on this page."
  },
  {
    "code": "def add_isosurface_grid_data(self, data, origin, extent, resolution,\n                                 isolevel=0.3, scale=10,\n                                 style=\"wireframe\", color=0xffffff):\n        spacing = np.array(extent/resolution)/scale\n        if isolevel >= 0:\n            triangles = marching_cubes(data, isolevel)\n        else:\n            triangles = marching_cubes(-data, -isolevel)\n        faces = []\n        verts = []\n        for i, t in enumerate(triangles):\n            faces.append([i * 3, i * 3 +1, i * 3 + 2])\n            verts.extend(t)\n        faces = np.array(faces)\n        verts = origin + spacing/2 + np.array(verts)*spacing\n        rep_id = self.add_representation('surface', {'verts': verts.astype('float32'),\n                                                     'faces': faces.astype('int32'),\n                                                     'style': style,\n                                                     'color': color})\n        self.autozoom(verts)",
    "docstring": "Add an isosurface to current scence using pre-computed data on a grid"
  },
  {
    "code": "def generate(env):\n    global PDFTeXAction\n    if PDFTeXAction is None:\n        PDFTeXAction = SCons.Action.Action('$PDFTEXCOM', '$PDFTEXCOMSTR')\n    global PDFLaTeXAction\n    if PDFLaTeXAction is None:\n        PDFLaTeXAction = SCons.Action.Action(\"$PDFLATEXCOM\", \"$PDFLATEXCOMSTR\")\n    global PDFTeXLaTeXAction\n    if PDFTeXLaTeXAction is None:\n        PDFTeXLaTeXAction = SCons.Action.Action(PDFTeXLaTeXFunction,\n                              strfunction=SCons.Tool.tex.TeXLaTeXStrFunction)\n    env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)\n    from . import pdf\n    pdf.generate(env)\n    bld = env['BUILDERS']['PDF']\n    bld.add_action('.tex', PDFTeXLaTeXAction)\n    bld.add_emitter('.tex', SCons.Tool.tex.tex_pdf_emitter)\n    pdf.generate2(env)\n    SCons.Tool.tex.generate_common(env)",
    "docstring": "Add Builders and construction variables for pdftex to an Environment."
  },
  {
    "code": "def _plugin_get(self, plugin_name):\n        if not plugin_name:\n            return None, u\"Plugin name not set\"\n        for plugin in self.controller.plugins:\n            if not isinstance(plugin, SettablePlugin):\n                continue\n            if plugin.name == plugin_name:\n                return plugin, \"\"\n        return None, u\"Settable plugin '{}' not found\".format(plugin_name)",
    "docstring": "Find plugins in controller\n\n        :param plugin_name: Name of the plugin to find\n        :type plugin_name: str | None\n        :return: Plugin or None and error message\n        :rtype: (settable_plugin.SettablePlugin | None, str)"
  },
  {
    "code": "def _item_to_bucket(iterator, item):\n    name = item.get(\"name\")\n    bucket = Bucket(iterator.client, name)\n    bucket._set_properties(item)\n    return bucket",
    "docstring": "Convert a JSON bucket to the native object.\n\n    :type iterator: :class:`~google.api_core.page_iterator.Iterator`\n    :param iterator: The iterator that has retrieved the item.\n\n    :type item: dict\n    :param item: An item to be converted to a bucket.\n\n    :rtype: :class:`.Bucket`\n    :returns: The next bucket in the page."
  },
  {
    "code": "def set_config_variables(repo, variables):\n    with repo.config_writer() as writer:\n        for k, value in variables.items():\n            section, option = k.split('.')\n            writer.set_value(section, option, value)\n        writer.release()",
    "docstring": "Set config variables\n\n    Args:\n        repo (git.Repo): repo\n        variables (dict): entries of the form 'user.email': 'you@example.com'"
  },
  {
    "code": "def _addsub_offset_array(self, other, op):\n        assert op in [operator.add, operator.sub]\n        if len(other) == 1:\n            return op(self, other[0])\n        warnings.warn(\"Adding/subtracting array of DateOffsets to \"\n                      \"{cls} not vectorized\"\n                      .format(cls=type(self).__name__), PerformanceWarning)\n        left = lib.values_from_object(self.astype('O'))\n        res_values = op(left, np.array(other))\n        kwargs = {}\n        if not is_period_dtype(self):\n            kwargs['freq'] = 'infer'\n        return self._from_sequence(res_values, **kwargs)",
    "docstring": "Add or subtract array-like of DateOffset objects\n\n        Parameters\n        ----------\n        other : Index, np.ndarray\n            object-dtype containing pd.DateOffset objects\n        op : {operator.add, operator.sub}\n\n        Returns\n        -------\n        result : same class as self"
  },
  {
    "code": "def list_dataset_uris(cls, base_uri, config_path):\n        parsed_uri = generous_parse_uri(base_uri)\n        uri_list = []\n        path = parsed_uri.path\n        if IS_WINDOWS:\n            path = unix_to_windows_path(parsed_uri.path, parsed_uri.netloc)\n        for d in os.listdir(path):\n            dir_path = os.path.join(path, d)\n            if not os.path.isdir(dir_path):\n                continue\n            storage_broker = cls(dir_path, config_path)\n            if not storage_broker.has_admin_metadata():\n                continue\n            uri = storage_broker.generate_uri(\n                name=d,\n                uuid=None,\n                base_uri=base_uri\n            )\n            uri_list.append(uri)\n        return uri_list",
    "docstring": "Return list containing URIs in location given by base_uri."
  },
  {
    "code": "def cache_key_name(cls, *args):\n        if cls.KEY_FIELDS != ():\n            if len(args) != len(cls.KEY_FIELDS):\n                raise TypeError(\n                    \"cache_key_name() takes exactly {} arguments ({} given)\".format(len(cls.KEY_FIELDS), len(args))\n                )\n            return 'configuration/{}/current/{}'.format(cls.__name__, ','.join(six.text_type(arg) for arg in args))\n        else:\n            return 'configuration/{}/current'.format(cls.__name__)",
    "docstring": "Return the name of the key to use to cache the current configuration"
  },
  {
    "code": "def read_ncbi_gene2go(fin_gene2go, taxids=None, **kws):\n    obj = Gene2GoReader(fin_gene2go, taxids=taxids)\n    if 'taxid2asscs' not in kws:\n        if len(obj.taxid2asscs) == 1:\n            taxid = next(iter(obj.taxid2asscs))\n            kws_ncbi = {k:v for k, v in kws.items() if k in AnnoOptions.keys_exp}\n            kws_ncbi['taxid'] = taxid\n            return obj.get_id2gos(**kws_ncbi)\n    t2asscs_ret = obj.get_taxid2asscs(taxids, **kws)\n    t2asscs_usr = kws.get('taxid2asscs', defaultdict(lambda: defaultdict(lambda: defaultdict(set))))\n    if 'taxid2asscs' in kws:\n        obj.fill_taxid2asscs(t2asscs_usr, t2asscs_ret)\n    return obj.get_id2gos_all(t2asscs_ret)",
    "docstring": "Read NCBI's gene2go. Return gene2go data for user-specified taxids."
  },
  {
    "code": "def get_location(self, obj):\n        if not obj.city and not obj.country:\n            return None\n        elif obj.city and obj.country:\n            return '%s, %s' % (obj.city, obj.country)\n        elif obj.city or obj.country:\n            return obj.city or obj.country",
    "docstring": "return user's location"
  },
  {
    "code": "def discover_setup_packages():\n    logger = logging.getLogger(__name__)\n    import eups\n    eups_client = eups.Eups()\n    products = eups_client.getSetupProducts()\n    packages = {}\n    for package in products:\n        name = package.name\n        info = {\n            'dir': package.dir,\n            'version': package.version\n        }\n        packages[name] = info\n        logger.debug('Found setup package: {name} {version} {dir}'.format(\n            name=name, **info))\n    return packages",
    "docstring": "Summarize packages currently set up by EUPS, listing their\n    set up directories and EUPS version names.\n\n    Returns\n    -------\n    packages : `dict`\n       Dictionary with keys that are EUPS package names. Values are\n       dictionaries with fields:\n\n       - ``'dir'``: absolute directory path of the set up package.\n       - ``'version'``: EUPS version string for package.\n\n    Notes\n    -----\n    This function imports the ``eups`` Python package, which is assumed to\n    be available in the build environmen. This function is designed to\n    encapsulate all direct EUPS interactions need by the stack documentation\n    build process."
  },
  {
    "code": "def agent_checks(consul_url=None, token=None):\n    ret = {}\n    if not consul_url:\n        consul_url = _get_config()\n        if not consul_url:\n            log.error('No Consul URL found.')\n            ret['message'] = 'No Consul URL found.'\n            ret['res'] = False\n            return ret\n    function = 'agent/checks'\n    ret = _query(consul_url=consul_url,\n                 function=function,\n                 token=token,\n                 method='GET')\n    return ret",
    "docstring": "Returns the checks the local agent is managing\n\n    :param consul_url: The Consul server URL.\n    :return: Returns the checks the local agent is managing\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' consul.agent_checks"
  },
  {
    "code": "def rich_presence(self):\n        kvs = self.get_ps('rich_presence')\n        data = {}\n        if kvs:\n            for kv in kvs:\n                data[kv.key] = kv.value\n        return data",
    "docstring": "Contains Rich Presence key-values\n\n        :rtype: dict"
  },
  {
    "code": "def immediateAssignment(ChannelDescription_presence=0,\n                        PacketChannelDescription_presence=0,\n                        StartingTime_presence=0):\n    a = L2PseudoLength()\n    b = TpPd(pd=0x6)\n    c = MessageType(mesType=0x3F)\n    d = PageModeAndDedicatedModeOrTBF()\n    packet = a / b / c / d\n    if ChannelDescription_presence is 1:\n        f = ChannelDescription()\n        packet = packet / f\n    if PacketChannelDescription_presence is 1:\n        g = PacketChannelDescription()\n        packet = packet / g\n    h = RequestReference()\n    i = TimingAdvance()\n    j = MobileAllocation()\n    packet = packet / h / i / j\n    if StartingTime_presence is 1:\n        k = StartingTimeHdr(ieiST=0x7C, eightBitST=0x0)\n        packet = packet / k\n    l = IaRestOctets()\n    packet = packet / l\n    return packet",
    "docstring": "IMMEDIATE ASSIGNMENT Section 9.1.18"
  },
  {
    "code": "def register (self, cmd):\n        if cmd.name is None:\n            raise ValueError ('no name set for Command object %r' % cmd)\n        if cmd.name in self.commands:\n            raise ValueError ('a command named \"%s\" has already been '\n                              'registered' % cmd.name)\n        self.commands[cmd.name] = cmd\n        return self",
    "docstring": "Register a new command with the tool. 'cmd' is expected to be an instance\n        of `Command`, although here only the `cmd.name` attribute is\n        investigated. Multiple commands with the same name are not allowed to\n        be registered. Returns 'self'."
  },
  {
    "code": "def file_loc():\n    import sys\n    import inspect\n    try:\n        raise Exception\n    except:\n        file_ = '.../' + '/'.join((inspect.currentframe().f_code.co_filename.split('/'))[-3:])\n        line_ = sys.exc_info()[2].tb_frame.f_back.f_lineno\n        return \"{}:{}\".format(file_, line_)",
    "docstring": "Return file and line number"
  },
  {
    "code": "def url_join(base, *args):\n    scheme, netloc, path, query, fragment = urlsplit(base)\n    path = path if len(path) else \"/\"\n    path = posixpath.join(path, *[('%s' % x) for x in args])\n    return urlunsplit([scheme, netloc, path, query, fragment])",
    "docstring": "Helper function to join an arbitrary number of url segments together."
  },
  {
    "code": "def element_at(self, index):\n        if self.closed():\n            raise ValueError(\"Attempt to call element_at() on a \"\n                             \"closed Queryable.\")\n        if index < 0:\n            raise OutOfRangeError(\"Attempt to use negative index.\")\n        try:\n            return self._iterable[index]\n        except IndexError:\n            raise OutOfRangeError(\"Index out of range.\")\n        except TypeError:\n            pass\n        for i, item in enumerate(self):\n            if i == index:\n                return item\n        raise OutOfRangeError(\"element_at(index) out of range.\")",
    "docstring": "Return the element at ordinal index.\n\n        Note: This method uses immediate execution.\n\n        Args:\n            index: The index of the element to be returned.\n\n        Returns:\n            The element at ordinal index in the source sequence.\n\n        Raises:\n            ValueError: If the Queryable is closed().\n            ValueError: If index is out of range."
  },
  {
    "code": "def finished(self):\n    return self.__state in (Job.ERROR, Job.SUCCESS, Job.CANCELLED)",
    "docstring": "True if the job run and finished. There is no difference if the job\n    finished successfully or errored."
  },
  {
    "code": "def update_widget(self, idx=None):\n        if idx is None:\n            for w in self._widgets:\n                idx = self._get_idx_from_widget(w)\n                self._write_widget(self._read_property(idx), idx)\n            pass\n        else: self._write_widget(self._read_property(idx), idx)\n        return",
    "docstring": "Forces the widget at given index to be updated from the\n        property value. If index is not given, all controlled\n        widgets will be updated. This method should be called\n        directly by the user when the property is not observable, or\n        in very unusual conditions."
  },
  {
    "code": "def set_target_from_config(self, cp, section):\n        if cp.has_option(section, \"niterations\"):\n            niterations = int(cp.get(section, \"niterations\"))\n        else:\n            niterations = None\n        if cp.has_option(section, \"effective-nsamples\"):\n            nsamples = int(cp.get(section, \"effective-nsamples\"))\n        else:\n            nsamples = None\n        self.set_target(niterations=niterations, eff_nsamples=nsamples)",
    "docstring": "Sets the target using the given config file.\n\n        This looks for ``niterations`` to set the ``target_niterations``, and\n        ``effective-nsamples`` to set the ``target_eff_nsamples``.\n\n        Parameters\n        ----------\n        cp : ConfigParser\n            Open config parser to retrieve the argument from.\n        section : str\n            Name of the section to retrieve from."
  },
  {
    "code": "def get_dataset_date_as_datetime(self):\n        dataset_date = self.data.get('dataset_date', None)\n        if dataset_date:\n            if '-' in dataset_date:\n                dataset_date = dataset_date.split('-')[0]\n            return datetime.strptime(dataset_date, '%m/%d/%Y')\n        else:\n            return None",
    "docstring": "Get dataset date as datetime.datetime object. For range returns start date.\n\n        Returns:\n            Optional[datetime.datetime]: Dataset date in datetime object or None if no date is set"
  },
  {
    "code": "def _op_generic_Ctz(self, args):\n        wtf_expr = claripy.BVV(self._from_size, self._from_size)\n        for a in reversed(range(self._from_size)):\n            bit = claripy.Extract(a, a, args[0])\n            wtf_expr = claripy.If(bit == 1, claripy.BVV(a, self._from_size), wtf_expr)\n        return wtf_expr",
    "docstring": "Count the trailing zeroes"
  },
  {
    "code": "def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]):\n    app = inliner.document.settings.env.app\n    ref = 'https://www.github.com/' + text\n    node = nodes.reference(rawtext, text, refuri=ref, **options)\n    return [node], []",
    "docstring": "Link to a GitHub user.\n\n    Returns 2 part tuple containing list of nodes to insert into the\n    document and a list of system messages.  Both are allowed to be\n    empty.\n\n    :param name: The role name used in the document.\n    :param rawtext: The entire markup snippet, with role.\n    :param text: The text marked with the role.\n    :param lineno: The line number where rawtext appears in the input.\n    :param inliner: The inliner instance that called us.\n    :param options: Directive options for customization.\n    :param content: The directive content for customization."
  },
  {
    "code": "def set_allow_repeat_items(self, allow_repeat_items):\n        if self.get_allow_repeat_items_metadata().is_read_only():\n            raise NoAccess()\n        if not self.my_osid_object_form._is_valid_boolean(allow_repeat_items):\n            raise InvalidArgument()\n        self.my_osid_object_form._my_map['allowRepeatItems'] = allow_repeat_items",
    "docstring": "determines if repeat items will be shown, or if the scaffold iteration will simply stop"
  },
  {
    "code": "def _concat_nbest_translations(translations: List[Translation], stop_ids: Set[int],\n                               length_penalty: LengthPenalty,\n                               brevity_penalty: Optional[BrevityPenalty] = None) -> Translation:\n    expanded_translations = (_expand_nbest_translation(translation) for translation in translations)\n    concatenated_translations = []\n    for translations_to_concat in zip(*expanded_translations):\n        concatenated_translations.append(_concat_translations(translations=list(translations_to_concat),\n                                                              stop_ids=stop_ids,\n                                                              length_penalty=length_penalty,\n                                                              brevity_penalty=brevity_penalty))\n    return _reduce_nbest_translations(concatenated_translations)",
    "docstring": "Combines nbest translations through concatenation.\n\n    :param translations: A list of translations (sequence starting with BOS symbol,\n        attention_matrix), score and length.\n    :param stop_ids: The EOS symbols.\n    :param length_penalty: LengthPenalty.\n    :param brevity_penalty: Optional BrevityPenalty.\n    :return: A concatenation of the translations with a score."
  },
  {
    "code": "def step_size(self, t0=None, t1=None):\n    if t0!=None and t1!=None:\n      tb0 = self.to_bucket( t0 )\n      tb1 = self.to_bucket( t1, steps=1 )\n      if tb0==tb1:\n        return self._step\n      return self.from_bucket( tb1 ) - self.from_bucket( tb0 )\n    return self._step",
    "docstring": "Return the time in seconds of a step. If a begin and end timestamp,\n    return the time in seconds between them after adjusting for what buckets\n    they alias to. If t1 and t0 resolve to the same bucket,"
  },
  {
    "code": "def from_name(cls, name, all_fallback=True):\n        name = name.upper()\n        for vocation in cls:\n            if vocation.name in name or vocation.name[:-1] in name and vocation != cls.ALL:\n                return vocation\n        if all_fallback or name.upper() == \"ALL\":\n            return cls.ALL\n        return None",
    "docstring": "Gets a vocation filter from a vocation's name.\n\n        Parameters\n        ----------\n        name: :class:`str`\n            The name of the vocation.\n        all_fallback: :class:`bool`\n            Whether to return :py:attr:`ALL` if no match is found. Otherwise, ``None`` will be returned.\n\n        Returns\n        -------\n        VocationFilter, optional:\n            The matching vocation filter."
  },
  {
    "code": "def execute_side_effect(side_effect=UNDEFINED, args=UNDEFINED, kwargs=UNDEFINED):\n    if args == UNDEFINED:\n        args = tuple()\n    if kwargs == UNDEFINED:\n        kwargs = {}\n    if isinstance(side_effect, (BaseException, Exception, StandardError)):\n        raise side_effect\n    elif hasattr(side_effect, '__call__'):\n        return side_effect(*args, **kwargs)\n    else:\n        raise Exception(\"Caliendo doesn't know what to do with your side effect. {0}\".format(side_effect))",
    "docstring": "Executes a side effect if one is defined.\n\n    :param side_effect: The side effect to execute\n    :type side_effect: Mixed. If it's an exception it's raised. If it's callable it's called with teh parameters.\n    :param tuple args: The arguments passed to the stubbed out method\n    :param dict kwargs: The kwargs passed to the subbed out method.\n\n    :rtype: mixed\n    :returns: Whatever the passed side_effect returns\n    :raises: Whatever error is defined as the side_effect"
  },
  {
    "code": "def get_likelihood(self, uni_matrix):\n        uni_dim = uni_matrix.shape[1]\n        num_edge = len(self.edges)\n        values = np.zeros([1, num_edge])\n        new_uni_matrix = np.empty([uni_dim, uni_dim])\n        for i in range(num_edge):\n            edge = self.edges[i]\n            value, left_u, right_u = edge.get_likelihood(uni_matrix)\n            new_uni_matrix[edge.L, edge.R] = left_u\n            new_uni_matrix[edge.R, edge.L] = right_u\n            values[0, i] = np.log(value)\n        return np.sum(values), new_uni_matrix",
    "docstring": "Compute likelihood of the tree given an U matrix.\n\n        Args:\n            uni_matrix(numpy.array): univariate matrix to evaluate likelihood on.\n\n        Returns:\n            tuple[float, numpy.array]:\n                likelihood of the current tree, next level conditional univariate matrix"
  },
  {
    "code": "def parser_help_text(help_text):\n    if help_text is None:\n        return None, {}\n    main_text = ''\n    params_help = {}\n    for line in help_text.splitlines():\n        line = line.strip()\n        match = re.search(r':\\s*param\\s*(?P<param>\\w+)\\s*:(?P<help>.*)$', line)\n        if match:\n            params_help[match.group('param')] = match.group('help').strip()\n        else:\n            main_text += line + ' '\n    main_text = main_text.strip()\n    return main_text, params_help",
    "docstring": "Takes the help text supplied as a doc string and extraxts the\n    description and any param arguments."
  },
  {
    "code": "def make_node(lower, upper, lineno):\n        if not is_static(lower, upper):\n            syntax_error(lineno, 'Array bounds must be constants')\n            return None\n        if isinstance(lower, SymbolVAR):\n            lower = lower.value\n        if isinstance(upper, SymbolVAR):\n            upper = upper.value\n        lower.value = int(lower.value)\n        upper.value = int(upper.value)\n        if lower.value < 0:\n            syntax_error(lineno, 'Array bounds must be greater than 0')\n            return None\n        if lower.value > upper.value:\n            syntax_error(lineno, 'Lower array bound must be less or equal to upper one')\n            return None\n        return SymbolBOUND(lower.value, upper.value)",
    "docstring": "Creates an array bound"
  },
  {
    "code": "def return_small_clade(treenode):\n    \"used to produce balanced trees, returns a tip node from the smaller clade\"\n    node = treenode\n    while 1:\n        if node.children:\n            c1, c2 = node.children\n            node = sorted([c1, c2], key=lambda x: len(x.get_leaves()))[0]\n        else:\n            return node",
    "docstring": "used to produce balanced trees, returns a tip node from the smaller clade"
  },
  {
    "code": "def _partition(entity, sep):\n    parts = entity.split(sep, 1)\n    if len(parts) == 2:\n        return parts[0], sep, parts[1]\n    else:\n        return entity, '', ''",
    "docstring": "Python2.4 doesn't have a partition method so we provide\n    our own that mimics str.partition from later releases.\n\n    Split the string at the first occurrence of sep, and return a\n    3-tuple containing the part before the separator, the separator\n    itself, and the part after the separator. If the separator is not\n    found, return a 3-tuple containing the string itself, followed\n    by two empty strings."
  },
  {
    "code": "def key_release_event(self, event):\r\n        self.example.key_event(event.key(), self.keys.ACTION_RELEASE)",
    "docstring": "Process Qt key release events forwarding them to the example"
  },
  {
    "code": "def guest_inspect_stats(self, userid_list):\n        if not isinstance(userid_list, list):\n            userid_list = [userid_list]\n        action = \"get the statistics of guest '%s'\" % str(userid_list)\n        with zvmutils.log_and_reraise_sdkbase_error(action):\n            return self._monitor.inspect_stats(userid_list)",
    "docstring": "Get the statistics including cpu and mem of the guests\n\n        :param userid_list: a single userid string or a list of guest userids\n        :returns: dictionary describing the cpu statistics of the vm\n                  in the form {'UID1':\n                  {\n                  'guest_cpus': xx,\n                  'used_cpu_time_us': xx,\n                  'elapsed_cpu_time_us': xx,\n                  'min_cpu_count': xx,\n                  'max_cpu_limit': xx,\n                  'samples_cpu_in_use': xx,\n                  'samples_cpu_delay': xx,\n                  'used_mem_kb': xx,\n                  'max_mem_kb': xx,\n                  'min_mem_kb': xx,\n                  'shared_mem_kb': xx\n                  },\n                  'UID2':\n                  {\n                  'guest_cpus': xx,\n                  'used_cpu_time_us': xx,\n                  'elapsed_cpu_time_us': xx,\n                  'min_cpu_count': xx,\n                  'max_cpu_limit': xx,\n                  'samples_cpu_in_use': xx,\n                  'samples_cpu_delay': xx,\n                  'used_mem_kb': xx,\n                  'max_mem_kb': xx,\n                  'min_mem_kb': xx,\n                  'shared_mem_kb': xx\n                  }\n                  }\n                  for the guests that are shutdown or not exist, no data\n                  returned in the dictionary"
  },
  {
    "code": "def set_metadata(self, metadata: MetaData) -> None:\n        self._parent.set_metadata(metadata)\n        self._child.set_metadata(metadata)",
    "docstring": "Sets the metadata for the parent and child tables."
  },
  {
    "code": "def tryload(self, cfgstr=None):\n        if cfgstr is None:\n            cfgstr = self.cfgstr\n        if cfgstr is None:\n            import warnings\n            warnings.warn('No cfgstr given in Cacher constructor or call')\n            cfgstr = ''\n        if not self.enabled:\n            if self.verbose > 0:\n                print('[cache] ... %s Cacher disabled' % (self.fname))\n            return None\n        try:\n            if self.verbose > 1:\n                print('[cache] tryload fname=%s' % (self.fname,))\n            return self.load(cfgstr)\n        except IOError:\n            if self.verbose > 0:\n                print('[cache] ... %s Cacher miss' % (self.fname))",
    "docstring": "Like load, but returns None if the load fails"
  },
  {
    "code": "def create_app(applet_id, applet_name, src_dir, publish=False, set_default=False, billTo=None, try_versions=None,\n               try_update=True, confirm=True, regional_options=None):\n    return _create_app(dict(applet=applet_id), applet_name, src_dir, publish=publish, set_default=set_default,\n                       billTo=billTo, try_versions=try_versions, try_update=try_update, confirm=confirm)",
    "docstring": "Creates a new app object from the specified applet.\n\n    .. deprecated:: 0.204.0\n       Use :func:`create_app_multi_region()` instead."
  },
  {
    "code": "def vertices(self):\n        if self._v_out is None:\n            output = qhalf('Fp', self.halfspaces, self.interior_point)\n            pts = []\n            for l in output[2:]:\n                pt = []\n                for c in l.split():\n                    c = float(c)\n                    if c != 10.101 and c != -10.101:\n                        pt.append(c)\n                    else:\n                        pt.append(np.inf)\n                pts.append(pt)\n            self._v_out = np.array(pts)\n        return self._v_out",
    "docstring": "Returns the vertices of the halfspace intersection"
  },
  {
    "code": "def add_vlan_to_interface(self, interface, vlan_id):\n        subif = '%s.%s' % (interface, vlan_id)\n        vlan_id = '%s' % vlan_id\n        cmd = ['ip', 'link', 'add', 'link', interface, 'name',\n               subif, 'type', 'vlan', 'id', vlan_id]\n        stdcode, stdout = agent_utils.execute(cmd, root=True)\n        if stdcode == 0:\n            return agent_utils.make_response(code=stdcode)\n        message = stdout.pop(0)\n        return agent_utils.make_response(code=stdcode, message=message)",
    "docstring": "Add vlan interface.\n\n        ip link add link eth0 name eth0.10 type vlan id 10"
  },
  {
    "code": "def _sync_with_file(self):\n        self._records = []\n        i = -1\n        for i, line in self._enum_lines():\n            self._records.append(None)\n        self._last_synced_index = i",
    "docstring": "Clear in-memory structures so table is synced with the file."
  },
  {
    "code": "def verify(self):\n        if self._lock != 0:\n            return\n        id_new = self._id_function()\n        if id_new != self.id_current:\n            if len(self.cache) > 0:\n                log.debug('%d items cleared from cache: %s',\n                          len(self.cache),\n                          str(list(self.cache.keys())))\n            self.cache = {}\n            self.id_current = id_new",
    "docstring": "Verify that the cached values are still for the same\n        value of id_function and delete all stored items if\n        the value of id_function has changed."
  },
  {
    "code": "def _get_authentication_from_public_key_id(self, key_id):\n        for authentication in self._authentications:\n            if authentication.is_key_id(key_id):\n                return authentication\n        return None",
    "docstring": "Return the authentication based on it's id."
  },
  {
    "code": "def _HandleLegacy(self, args, token=None):\n    hunt_urn = args.hunt_id.ToURN()\n    hunt_obj = aff4.FACTORY.Open(\n        hunt_urn, aff4_type=implementation.GRRHunt, token=token)\n    clients_by_status = hunt_obj.GetClientsByStatus()\n    hunt_clients = clients_by_status[args.client_status.name]\n    total_count = len(hunt_clients)\n    if args.count:\n      hunt_clients = sorted(hunt_clients)[args.offset:args.offset + args.count]\n    else:\n      hunt_clients = sorted(hunt_clients)[args.offset:]\n    flow_id = \"%s:hunt\" % hunt_urn.Basename()\n    results = [\n        ApiHuntClient(client_id=c.Basename(), flow_id=flow_id)\n        for c in hunt_clients\n    ]\n    return ApiListHuntClientsResult(items=results, total_count=total_count)",
    "docstring": "Retrieves the clients for a hunt."
  },
  {
    "code": "def ecg_find_peaks(signal, sampling_rate=1000):\n    rpeaks, = biosppy.ecg.hamilton_segmenter(np.array(signal), sampling_rate=sampling_rate)\n    rpeaks, = biosppy.ecg.correct_rpeaks(signal=np.array(signal), rpeaks=rpeaks, sampling_rate=sampling_rate, tol=0.05)\n    return(rpeaks)",
    "docstring": "Find R peaks indices on the ECG channel.\n\n    Parameters\n    ----------\n    signal : list or ndarray\n        ECG signal (preferably filtered).\n    sampling_rate : int\n        Sampling rate (samples/second).\n\n\n    Returns\n    ----------\n    rpeaks : list\n        List of R-peaks location indices.\n\n    Example\n    ----------\n    >>> import neurokit as nk\n    >>> Rpeaks = nk.ecg_find_peaks(signal)\n\n    Notes\n    ----------\n    *Authors*\n\n    - the bioSSPy dev team (https://github.com/PIA-Group/BioSPPy)\n\n    *Dependencies*\n\n    - biosppy\n\n    *See Also*\n\n    - BioSPPY: https://github.com/PIA-Group/BioSPPy"
  },
  {
    "code": "def find_one(self, tname, where=None, where_not=None, columns=None, astype=None):\n        records = self.find(tname, where=where, where_not=where_not, columns=columns,\n                            astype='dataframe')\n        return self._output(records, single=True, astype=astype)",
    "docstring": "Find a single record in the provided table from the database. If multiple match, return\n        the first one based on the internal order of the records. If no records are found, return\n        empty dictionary, string or series depending on the value of `astype`.\n\n        Parameters\n        ----------\n        tname : str\n            Table to search records from.\n        where : dict or None (default `None`)\n            Dictionary of <column, value> where value can be of str type for exact match or a\n            compiled regex expression for more advanced matching.\n        where_not : dict or None (default `None`)\n            Identical to `where` but for negative-matching.\n        columns: list of str, str or None (default `None`)\n            Column(s) to return for the found records, if any.\n        astype: str, type or None (default `None`)\n            Type to cast the output to. Possible values are: `nonetype`, `series`, `str`, `dict`,\n            `json`. If this is `None`, falls back to the type provided to the constructor.\n            If a type was provided to the constructor but the user wants to avoid any casting,\n            \"nonetype\" should be passed as the value.\n\n        Returns\n        -------\n        records : str, dict or series\n            Output type depends on `astype` parameter.\n\n        Examples\n        --------\n        >>> db = PandasDatabase(\"test\")\n        >>> db.insert(\"test\", record={\"Name\": \"John\"})\n            Name                                      John\n            __id__    dc876999-1f5b-4262-b6bf-c23b875f3a54\n            dtype: object\n        >>> db.find_one(\"test\", astype=\"dict\")\n            {'Name': 'John', '__id__': 'dc876999-1f5b-4262-b6bf-c23b875f3a54'}\n        >>> db.find_one(\"test\", astype=\"series\")\n            __id__    dc876999-1f5b-4262-b6bf-c23b875f3a54\n            Name                                      John\n            Name: 0, dtype: object\n        >>> db.find_one(\"test\", astype=None)\n            __id__    dc876999-1f5b-4262-b6bf-c23b875f3a54\n            Name                                      John\n            Name: 0, dtype: object\n        >>> db.find_one(\"test\", where={\"Name\": \"John\"}, astype=\"dict\")\n            {'Name': 'John', '__id__': 'dc876999-1f5b-4262-b6bf-c23b875f3a54'}\n        >>> db.find_one(\"test\", where_not={\"Name\": \"John\"}, astype=\"dict\")\n            {}"
  },
  {
    "code": "def save_nk_object(obj, filename=\"file\", path=\"\", extension=\"nk\", compress=False, compatibility=-1):\n    if compress is True:\n        with gzip.open(path + filename + \".\" + extension, 'wb') as name:\n            pickle.dump(obj, name, protocol=compatibility)\n    else:\n        with open(path + filename + \".\" + extension, 'wb') as name:\n            pickle.dump(obj, name, protocol=compatibility)",
    "docstring": "Save whatever python object to a pickled file.\n\n    Parameters\n    ----------\n    file : object\n        Whatever python thing (list, dict, ...).\n    filename : str\n        File's name.\n    path : str\n        File's path.\n    extension : str\n        File's extension. Default \"nk\" but can be whatever.\n    compress: bool\n        Enable compression using gzip.\n    compatibility : int\n        See :func:`pickle.dump`.\n\n\n    Example\n    ----------\n    >>> import neurokit as nk\n    >>> obj = [1, 2]\n    >>> nk.save_nk_object(obj, filename=\"myobject\")\n\n    Notes\n    ----------\n    *Authors*\n\n    - `Dominique Makowski <https://dominiquemakowski.github.io/>`_\n\n    *Dependencies*\n\n    - pickle\n    - gzip"
  },
  {
    "code": "def getAttributeName(self, index):\n        offset = self._get_attribute_offset(index)\n        name = self.m_attributes[offset + const.ATTRIBUTE_IX_NAME]\n        res = self.sb[name]\n        if not res:\n            attr = self.m_resourceIDs[name]\n            if attr in public.SYSTEM_RESOURCES['attributes']['inverse']:\n                res = 'android:' + public.SYSTEM_RESOURCES['attributes']['inverse'][attr]\n            else:\n                res = 'android:UNKNOWN_SYSTEM_ATTRIBUTE_{:08x}'.format(attr)\n        return res",
    "docstring": "Returns the String which represents the attribute name"
  },
  {
    "code": "def add_swagger(app, json_route, html_route, **kwargs):\n    spec = getattr(app, SWAGGER_ATTR_NAME)\n    if spec:\n        spec = spec.swagger_definition(**kwargs)\n    else:\n        spec = {}\n    encoded_spec = json.dumps(spec).encode(\"UTF-8\")\n    @app.route(json_route)\n    def swagger():\n        return Response(\n            encoded_spec,\n            headers={\"Access-Control-Allow-Origin\": \"*\"},\n            content_type=\"application/json\",\n        )\n    static_root = get_swagger_static_root()\n    swagger_body = generate_swagger_html(\n        STATIC_PATH, json_route\n    ).encode(\"utf-8\")\n    @app.route(html_route)\n    def swagger_ui():\n        return Response(swagger_body, content_type=\"text/html\")\n    blueprint = Blueprint('swagger', __name__, static_url_path=STATIC_PATH,\n                          static_folder=static_root)\n    app.register_blueprint(blueprint)",
    "docstring": "add a swagger html page, and a swagger.json generated\n    from the routes added to the app."
  },
  {
    "code": "async def unmount(self):\n        self._data = await self._handler.unmount(\n            system_id=self.node.system_id, id=self.id)",
    "docstring": "Unmount this block device."
  },
  {
    "code": "def fit(self, X, y=None):\n        self.transformer_list = list(self.transformer_list)\n        self._validate_transformers()\n        with Pool(self.n_jobs) as pool:\n            transformers = pool.starmap(_fit_one_transformer,\n                        ((trans, X[trans['col_pick']] if hasattr(trans, 'col_pick') else X, y) for _, trans, _ in self._iter()))\n        self._update_transformer_list(transformers)\n        return self",
    "docstring": "Fit all transformers using X.\n\n        Parameters\n        ----------\n        X : iterable or array-like, depending on transformers\n            Input data, used to fit transformers.\n\n        y : array-like, shape (n_samples, ...), optional\n            Targets for supervised learning.\n\n        Returns\n        -------\n        self : FeatureUnion\n            This estimator"
  },
  {
    "code": "def _get_attribute_tensors(onnx_model_proto):\n    for node in onnx_model_proto.graph.node:\n        for attribute in node.attribute:\n            if attribute.HasField(\"t\"):\n                yield attribute.t\n            for tensor in attribute.tensors:\n                yield tensor",
    "docstring": "Create an iterator of tensors from node attributes of an ONNX model."
  },
  {
    "code": "def fix_size(self, content):\n        if content:\n            width, height = self.get_item_size(content)\n            parent = self.parent()\n            relative_width = parent.geometry().width() * 0.65\n            if relative_width > self.MAX_WIDTH:\n                relative_width = self.MAX_WIDTH\n            self.list.setMinimumWidth(relative_width)\n            if len(content) < 15:\n                max_entries = len(content)\n            else:\n                max_entries = 15\n            max_height = height * max_entries * 1.7\n            self.list.setMinimumHeight(max_height)\n            self.list.resize(relative_width, self.list.height())",
    "docstring": "Adjusts the width and height of the file switcher\n        based on the relative size of the parent and content."
  },
  {
    "code": "def _get_record(self):\n        if not self.pk:\n            raise AJAXError(400, _('Invalid request for record.'))\n        try:\n            return self.model.objects.get(pk=self.pk)\n        except self.model.DoesNotExist:\n            raise AJAXError(404, _('%s with id of \"%s\" not found.') % (\n                self.model.__name__, self.pk))",
    "docstring": "Fetch a given record.\n\n        Handles fetching a record from the database along with throwing an\n        appropriate instance of ``AJAXError`."
  },
  {
    "code": "def register_tile(self, hw_type, api_major, api_minor, name, fw_major, fw_minor, fw_patch, exec_major, exec_minor, exec_patch, slot, unique_id):\n        api_info = (api_major, api_minor)\n        fw_info = (fw_major, fw_minor, fw_patch)\n        exec_info = (exec_major, exec_minor, exec_patch)\n        address = 10 + slot\n        info = TileInfo(hw_type, name, api_info, fw_info, exec_info, slot, unique_id, state=TileState.JUST_REGISTERED, address=address)\n        self.tile_manager.insert_tile(info)\n        debug = int(self.tile_manager.debug_mode)\n        if self.tile_manager.safe_mode:\n            run_level = RunLevel.SAFE_MODE\n            info.state = TileState.SAFE_MODE\n            config_rpcs = []\n        else:\n            run_level = RunLevel.START_ON_COMMAND\n            info.state = TileState.BEING_CONFIGURED\n            config_rpcs = self.config_database.stream_matching(address, name)\n        self.tile_manager.queue.put_nowait((info, config_rpcs))\n        return [address, run_level, debug]",
    "docstring": "Register a tile with this controller.\n\n        This function adds the tile immediately to its internal cache of registered tiles\n        and queues RPCs to send all config variables and start tile rpcs back to the tile."
  },
  {
    "code": "def _construct(self):\n        self._acyclic_cfg = self._cfg.copy()\n        self._pre_process_cfg()\n        self._pd_construct()\n        self._graph = networkx.DiGraph()\n        rdf = compute_dominance_frontier(self._normalized_cfg, self._post_dom)\n        for y in self._cfg.graph.nodes():\n            if y not in rdf:\n                continue\n            for x in rdf[y]:\n                self._graph.add_edge(x, y)",
    "docstring": "Construct a control dependence graph.\n\n        This implementation is based on figure 6 of paper An Efficient Method of Computing Static Single Assignment\n        Form by Ron Cytron, etc."
  },
  {
    "code": "def exception(self, s):\n        self.error(s)\n        type, value, tb = sys.exc_info()\n        self.writelines(traceback.format_stack(), 1)\n        self.writelines(traceback.format_tb(tb)[1:], 1)\n        self.writelines(traceback.format_exception_only(type, value), 1)",
    "docstring": "Write error message with traceback info."
  },
  {
    "code": "def authenticated_session(username, password):\n    session = requests.Session()\n    session.headers.update(headers())\n    response = session.get(url())\n    login_path = path(response.text)\n    login_url = urljoin(response.url, login_path)\n    login_post_data = post_data(response.text, username, password)\n    response = session.post(login_url, data=login_post_data)\n    if response.headers['connection'] == 'close':\n        raise Exception('Authencation failed')\n    return session",
    "docstring": "Given username and password, return an authenticated Yahoo `requests`\n    session that can be used for further scraping requests.\n\n    Throw an AuthencationError if authentication fails."
  },
  {
    "code": "def _get_data_from_csv_files(self):\n    all_df = []\n    for file_name in self._input_csv_files:\n      with _util.open_local_or_gcs(file_name, mode='r') as f:\n        all_df.append(pd.read_csv(f, names=self._headers))\n    df = pd.concat(all_df, ignore_index=True)\n    return df",
    "docstring": "Get data from input csv files."
  },
  {
    "code": "def set_windows_env_var(key, value):\n    if not isinstance(key, text_type):\n        raise TypeError(\"%r not of type %r\" % (key, text_type))\n    if not isinstance(value, text_type):\n        raise TypeError(\"%r not of type %r\" % (value, text_type))\n    status = winapi.SetEnvironmentVariableW(key, value)\n    if status == 0:\n        raise ctypes.WinError()",
    "docstring": "Set an env var.\n\n    Raises:\n        WindowsError"
  },
  {
    "code": "def assign_role(backend, user, response, *args, **kwargs):\n    if backend.name is 'passthrough' and settings.DEMO is True and 'role' in kwargs['request'].session[passthrough.SESSION_VAR]:\n        role = kwargs['request'].session[passthrough.SESSION_VAR]['role']\n        if role == 'tutor':\n            make_tutor(user)\n        if role == 'admin':\n            make_admin(user)\n        if role == 'owner':\n            make_owner(user)",
    "docstring": "Part of the Python Social Auth Pipeline.\n    Checks if the created demo user should be pushed into some group."
  },
  {
    "code": "def _callback_new_block(self, latest_block: Dict):\n        with self.event_poll_lock:\n            latest_block_number = latest_block['number']\n            confirmed_block_number = max(\n                GENESIS_BLOCK_NUMBER,\n                latest_block_number - self.config['blockchain']['confirmation_blocks'],\n            )\n            confirmed_block = self.chain.client.web3.eth.getBlock(confirmed_block_number)\n            for event in self.blockchain_events.poll_blockchain_events(confirmed_block_number):\n                on_blockchain_event(self, event)\n            state_change = Block(\n                block_number=confirmed_block_number,\n                gas_limit=confirmed_block['gasLimit'],\n                block_hash=BlockHash(bytes(confirmed_block['hash'])),\n            )\n            self.handle_and_track_state_change(state_change)",
    "docstring": "Called once a new block is detected by the alarm task.\n\n        Note:\n            This should be called only once per block, otherwise there will be\n            duplicated `Block` state changes in the log.\n\n            Therefore this method should be called only once a new block is\n            mined with the corresponding block data from the AlarmTask."
  },
  {
    "code": "def left_sections(self):\n        lines = self.text.split('\\n')\n        sections = 0\n        for i in range(len(lines)):\n            if lines[i].startswith('+'):\n                sections += 1\n        sections -= 1\n        return sections",
    "docstring": "The number of sections that touch the left side.\n\n        During merging, the cell's text will grow to include other\n        cells. This property keeps track of the number of sections that\n        are touching the left side. For example::\n\n                        +-----+-----+\n            section --> | foo | dog | <-- section\n                        +-----+-----+\n            section --> | cat |\n                        +-----+\n\n        Has 2 sections on the left, but 1 on the right\n\n        Returns\n        -------\n        sections : int\n            The number of sections on the left"
  },
  {
    "code": "def get_vdp_failure_reason(self, reply):\n        try:\n            fail_reason = reply.partition(\n                \"filter\")[0].replace('\\t', '').split('\\n')[-2]\n            if len(fail_reason) == 0:\n                fail_reason = vdp_const.retrieve_failure_reason % (reply)\n        except Exception:\n            fail_reason = vdp_const.retrieve_failure_reason % (reply)\n        return fail_reason",
    "docstring": "Parse the failure reason from VDP."
  },
  {
    "code": "def similarity(self, other):\n        if self.magnitude == 0 or other.magnitude == 0:\n            return 0\n        return self.dot(other) / self.magnitude",
    "docstring": "Calculates the cosine similarity between this vector and another\n        vector."
  },
  {
    "code": "def updateEditorGeometry(self, editor, option, index):\n        cti = index.model().getItem(index)\n        if cti.checkState is None:\n            displayRect = option.rect\n        else:\n            checkBoxRect = widgetSubCheckBoxRect(editor, option)\n            offset = checkBoxRect.x() + checkBoxRect.width()\n            displayRect = option.rect\n            displayRect.adjust(offset, 0, 0, 0)\n        editor.setGeometry(displayRect)",
    "docstring": "Ensures that the editor is displayed correctly with respect to the item view."
  },
  {
    "code": "def compute_path(self, start_x, start_y, dest_x, dest_y,\n                     diagonal_cost=_math.sqrt(2)):\n        return tcod.path.AStar(self, diagonal_cost).get_path(start_x, start_y,\n                                                             dest_x, dest_y)",
    "docstring": "Get the shortest path between two points.\n\n        Args:\n            start_x (int): Starting x-position.\n            start_y (int): Starting y-position.\n            dest_x (int): Destination x-position.\n            dest_y (int): Destination y-position.\n            diagonal_cost (float): Multiplier for diagonal movement.\n\n                Can be set to zero to disable diagonal movement entirely.\n\n        Returns:\n            List[Tuple[int, int]]: The shortest list of points to the\n                destination position from the starting position.\n\n            The start point is not included in this list."
  },
  {
    "code": "def term_from_uri(uri):\n    if uri is None:\n        return None\n    if isinstance(uri, rdflib.Literal):\n        uri = str(uri.toPython())\n    patterns = ['http://www.openbel.org/bel/namespace//(.*)',\n                'http://www.openbel.org/vocabulary//(.*)',\n                'http://www.openbel.org/bel//(.*)',\n                'http://www.openbel.org/bel/namespace/(.*)',\n                'http://www.openbel.org/vocabulary/(.*)',\n                'http://www.openbel.org/bel/(.*)']\n    for pr in patterns:\n        match = re.match(pr, uri)\n        if match is not None:\n            term = match.groups()[0]\n            term = unquote(term)\n            return term\n    return uri",
    "docstring": "Removes prepended URI information from terms."
  },
  {
    "code": "def _find_flats_edges(self, data, mag, direction):\n        i12 = np.arange(data.size).reshape(data.shape)\n        flat = mag == FLAT_ID_INT\n        flats, n = spndi.label(flat, structure=FLATS_KERNEL3)\n        objs = spndi.find_objects(flats)\n        f = flat.ravel()\n        d = data.ravel()\n        for i, _obj in enumerate(objs):\n            region = flats[_obj] == i+1\n            I = i12[_obj][region]\n            J = get_adjacent_index(I, data.shape, data.size)\n            f[J] = d[J] == d[I[0]]\n        flat = f.reshape(data.shape)\n        return flat",
    "docstring": "Extend flats 1 square downstream\n        Flats on the downstream side of the flat might find a valid angle,\n        but that doesn't mean that it's a correct angle. We have to find\n        these and then set them equal to a flat"
  },
  {
    "code": "def validate_valid_transition(enum, from_value, to_value):\n    validate_available_choice(enum, to_value)\n    if hasattr(enum, '_transitions') and not enum.is_valid_transition(from_value, to_value):\n        message = _(six.text_type('{enum} can not go from \"{from_value}\" to \"{to_value}\"'))\n        raise InvalidStatusOperationError(message.format(\n            enum=enum.__name__,\n            from_value=enum.name(from_value),\n            to_value=enum.name(to_value) or to_value\n        ))",
    "docstring": "Validate that to_value is a valid choice and that to_value is a valid transition from from_value."
  },
  {
    "code": "def login(self):\n        _LOGGER.debug(\"Attempting to login to ZoneMinder\")\n        login_post = {'view': 'console', 'action': 'login'}\n        if self._username:\n            login_post['username'] = self._username\n        if self._password:\n            login_post['password'] = self._password\n        req = requests.post(urljoin(self._server_url, 'index.php'),\n                            data=login_post, verify=self._verify_ssl)\n        self._cookies = req.cookies\n        req = requests.get(\n            urljoin(self._server_url, 'api/host/getVersion.json'),\n            cookies=self._cookies,\n            timeout=ZoneMinder.DEFAULT_TIMEOUT,\n            verify=self._verify_ssl)\n        if not req.ok:\n            _LOGGER.error(\"Connection error logging into ZoneMinder\")\n            return False\n        return True",
    "docstring": "Login to the ZoneMinder API."
  },
  {
    "code": "def packets_to_flows(self):\n        for packet in self.input_stream:\n            flow_id = flow_utils.flow_tuple(packet)\n            self._flows[flow_id].add_packet(packet)\n            for flow in list(self._flows.values()):\n                if flow.ready():\n                    flow_info = flow.get_flow()\n                    yield flow_info\n                    del self._flows[flow_info['flow_id']]\n        print('---- NO MORE INPUT ----')\n        for flow in sorted(self._flows.values(), key=lambda x: x.meta['start']):\n            yield flow.get_flow()",
    "docstring": "Combine packets into flows"
  },
  {
    "code": "def _new_device_id(self, key):\n        device_id = Id.SERVER + 1\n        if key in self._key2deviceId:\n            return self._key2deviceId[key]\n        while device_id in self._clients:\n            device_id += 1\n        return device_id",
    "docstring": "Generate a new device id or return existing device id for key\n\n        :param key: Key for device\n        :type key: unicode\n        :return: The device id\n        :rtype: int"
  },
  {
    "code": "def plot(args):\n    from jcvi.graphics.base import savefig\n    p = OptionParser(plot.__doc__)\n    opts, args, iopts = p.set_image_options(args, figsize=\"8x7\", format=\"png\")\n    if len(args) != 3:\n        sys.exit(not p.print_help())\n    workdir, sample_key, chrs = args\n    chrs = chrs.split(\",\")\n    hmm = CopyNumberHMM(workdir=workdir)\n    hmm.plot(sample_key, chrs=chrs)\n    image_name = sample_key + \"_cn.\" + iopts.format\n    savefig(image_name, dpi=iopts.dpi, iopts=iopts)",
    "docstring": "%prog plot workdir sample chr1,chr2\n\n    Plot some chromosomes for visual proof. Separate multiple chromosomes with\n    comma. Must contain folder workdir/sample-cn/."
  },
  {
    "code": "def psisloo(log_lik, **kwargs):\n    r\n    kwargs['overwrite_lw'] = True\n    lw = -log_lik\n    lw, ks = psislw(lw, **kwargs)\n    lw += log_lik\n    loos = sumlogs(lw, axis=0)\n    loo = loos.sum()\n    return loo, loos, ks",
    "docstring": "r\"\"\"PSIS leave-one-out log predictive densities.\n\n    Computes the log predictive densities given posterior samples of the log\n    likelihood terms :math:`p(y_i|\\theta^s)` in input parameter `log_lik`.\n    Returns a sum of the leave-one-out log predictive densities `loo`,\n    individual leave-one-out log predictive density terms `loos` and an estimate\n    of Pareto tail indeces `ks`. The estimates are unreliable if tail index\n    ``k > 0.7`` (see more in the references listed in the module docstring).\n\n    Additional keyword arguments are passed to the :meth:`psislw()` function\n    (see the corresponding documentation).\n\n    Parameters\n    ----------\n    log_lik : ndarray\n        Array of size n x m containing n posterior samples of the log likelihood\n        terms :math:`p(y_i|\\theta^s)`.\n\n    Returns\n    -------\n    loo : scalar\n        sum of the leave-one-out log predictive densities\n\n    loos : ndarray\n        individual leave-one-out log predictive density terms\n\n    ks : ndarray\n        estimated Pareto tail indeces"
  },
  {
    "code": "def _verify_barycentric(lambda1, lambda2, lambda3):\n        weights_total = lambda1 + lambda2 + lambda3\n        if not np.allclose(weights_total, 1.0, atol=0.0):\n            raise ValueError(\n                \"Weights do not sum to 1\", lambda1, lambda2, lambda3\n            )\n        if lambda1 < 0.0 or lambda2 < 0.0 or lambda3 < 0.0:\n            raise ValueError(\n                \"Weights must be positive\", lambda1, lambda2, lambda3\n            )",
    "docstring": "Verifies that weights are barycentric and on the reference triangle.\n\n        I.e., checks that they sum to one and are all non-negative.\n\n        Args:\n            lambda1 (float): Parameter along the reference triangle.\n            lambda2 (float): Parameter along the reference triangle.\n            lambda3 (float): Parameter along the reference triangle.\n\n        Raises:\n            ValueError: If the weights are not valid barycentric\n                coordinates, i.e. they don't sum to ``1``.\n            ValueError: If some weights are negative."
  },
  {
    "code": "def main(host='localhost', port=8086):\n    user = 'root'\n    password = 'root'\n    dbname = 'demo'\n    protocol = 'json'\n    client = DataFrameClient(host, port, user, password, dbname)\n    print(\"Create pandas DataFrame\")\n    df = pd.DataFrame(data=list(range(30)),\n                      index=pd.date_range(start='2014-11-16',\n                                          periods=30, freq='H'), columns=['0'])\n    print(\"Create database: \" + dbname)\n    client.create_database(dbname)\n    print(\"Write DataFrame\")\n    client.write_points(df, 'demo', protocol=protocol)\n    print(\"Write DataFrame with Tags\")\n    client.write_points(df, 'demo',\n                        {'k1': 'v1', 'k2': 'v2'}, protocol=protocol)\n    print(\"Read DataFrame\")\n    client.query(\"select * from demo\")\n    print(\"Delete database: \" + dbname)\n    client.drop_database(dbname)",
    "docstring": "Instantiate the connection to the InfluxDB client."
  },
  {
    "code": "def _display_stream(normalized_data, stream):\n    try:\n        stream.write(normalized_data['stream'])\n    except UnicodeEncodeError:\n        stream.write(normalized_data['stream'].encode(\"utf-8\"))",
    "docstring": "print stream message from docker-py stream."
  },
  {
    "code": "def create_ospf_area_with_message_digest_auth():\n    OSPFKeyChain.create(name='secure-keychain',\n                        key_chain_entry=[{'key': 'fookey',\n                                          'key_id': 10,\n                                          'send_key': True}])\n    key_chain = OSPFKeyChain('secure-keychain')\n    OSPFInterfaceSetting.create(name='authenicated-ospf',\n                                authentication_type='message_digest',\n                                key_chain_ref=key_chain.href)\n    for profile in describe_ospfv2_interface_settings():\n        if profile.name.startswith('Default OSPF'):\n            interface_profile = profile.href\n    OSPFArea.create(name='area0',\n                    interface_settings_ref=interface_profile,\n                    area_id=0)",
    "docstring": "If you require message-digest authentication for your OSPFArea, you must\n    create an OSPF key chain configuration."
  },
  {
    "code": "def mnist(training):\n  if training:\n    data_filename = 'train-images-idx3-ubyte.gz'\n    labels_filename = 'train-labels-idx1-ubyte.gz'\n    count = 60000\n  else:\n    data_filename = 't10k-images-idx3-ubyte.gz'\n    labels_filename = 't10k-labels-idx1-ubyte.gz'\n    count = 10000\n  data_filename = maybe_download(MNIST_URL, data_filename)\n  labels_filename = maybe_download(MNIST_URL, labels_filename)\n  return (mnist_extract_data(data_filename, count),\n          mnist_extract_labels(labels_filename, count))",
    "docstring": "Downloads MNIST and loads it into numpy arrays."
  },
  {
    "code": "def _init_formats(self):\n        theme = self._color_scheme\n        fmt = QtGui.QTextCharFormat()\n        fmt.setForeground(theme.foreground)\n        fmt.setBackground(theme.background)\n        self._formats[OutputFormat.NormalMessageFormat] = fmt\n        fmt = QtGui.QTextCharFormat()\n        fmt.setForeground(theme.error)\n        fmt.setBackground(theme.background)\n        self._formats[OutputFormat.ErrorMessageFormat] = fmt\n        fmt = QtGui.QTextCharFormat()\n        fmt.setForeground(theme.custom)\n        fmt.setBackground(theme.background)\n        self._formats[OutputFormat.CustomFormat] = fmt",
    "docstring": "Initialise default formats."
  },
  {
    "code": "def _do_denormalize (version_tuple):\n    version_parts_list = []\n    for parts_tuple in itertools.imap(None,*([iter(version_tuple)]*4)):\n        version_part = ''.join(fn(x) for fn, x in\n                               zip(_denormalize_fn_list, parts_tuple))\n        if version_part:\n            version_parts_list.append(version_part)\n    return '.'.join(version_parts_list)",
    "docstring": "separate action function to allow for the memoize decorator.  Lists,\n    the most common thing passed in to the 'denormalize' below are not hashable."
  },
  {
    "code": "def _par_vector2dict(v, pars, dims, starts=None):\n    if starts is None:\n        starts = _calc_starts(dims)\n    d = OrderedDict()\n    for i in range(len(pars)):\n        l = int(np.prod(dims[i]))\n        start = starts[i]\n        end = start + l\n        y = np.asarray(v[start:end])\n        if len(dims[i]) > 1:\n            y = y.reshape(dims[i], order='F')\n        d[pars[i]] = y.squeeze() if y.shape == (1,) else y\n    return d",
    "docstring": "Turn a vector of samples into an OrderedDict according to param dims.\n\n    Parameters\n    ----------\n    y : list of int or float\n    pars : list of str\n        parameter names\n    dims : list of list of int\n        list of dimensions of parameters\n\n    Returns\n    -------\n    d : dict\n\n    Examples\n    --------\n    >>> v = list(range(31))\n    >>> dims = [[5], [5, 5], []]\n    >>> pars = ['mu', 'Phi', 'eta']\n    >>> _par_vector2dict(v, pars, dims)  # doctest: +ELLIPSIS\n    OrderedDict([('mu', array([0, 1, 2, 3, 4])), ('Phi', array([[ 5, ..."
  },
  {
    "code": "def set_off(self):\n        try:\n            request = requests.post(\n                '{}/{}/{}/'.format(self.resource, URI, self._mac),\n                data={'action': 'off'}, timeout=self.timeout)\n            if request.status_code == 200:\n                pass\n        except requests.exceptions.ConnectionError:\n            raise exceptions.MyStromConnectionError()",
    "docstring": "Turn the bulb off."
  },
  {
    "code": "def get_operator_output_port(self):\n        return OperatorOutputPort(self.rest_client.make_request(self.operatorOutputPort), self.rest_client)",
    "docstring": "Get the output port of this exported stream.\n\n        Returns:\n            OperatorOutputPort: Output port of this exported stream."
  },
  {
    "code": "def simple_write(self, s, frame, node=None):\n        self.start_write(frame, node)\n        self.write(s)\n        self.end_write(frame)",
    "docstring": "Simple shortcut for start_write + write + end_write."
  },
  {
    "code": "def write_array(self, obj):\n        classdesc = obj.get_class()\n        self._writeStruct(\">B\", 1, (self.TC_ARRAY,))\n        self.write_classdesc(classdesc)\n        self._writeStruct(\">i\", 1, (len(obj),))\n        self.references.append(obj)\n        logging.debug(\n            \"*** Adding ref 0x%X for array []\",\n            len(self.references) - 1 + self.BASE_REFERENCE_IDX,\n        )\n        type_char = classdesc.name[0]\n        assert type_char == self.TYPE_ARRAY\n        type_char = classdesc.name[1]\n        if type_char == self.TYPE_OBJECT:\n            for o in obj:\n                self._write_value(classdesc.name[1:], o)\n        elif type_char == self.TYPE_ARRAY:\n            for a in obj:\n                self.write_array(a)\n        else:\n            log_debug(\"Write array of type %s\" % type_char)\n            for v in obj:\n                log_debug(\"Writing: %s\" % v)\n                self._write_value(type_char, v)",
    "docstring": "Writes a JavaArray\n\n        :param obj: A JavaArray object"
  },
  {
    "code": "def get_base_branch():\n    base_branch = git.guess_base_branch()\n    if base_branch is None:\n        log.info(\"Can't guess the base branch, you have to pick one yourself:\")\n        base_branch = choose_branch()\n    return base_branch",
    "docstring": "Return the base branch for the current branch.\n\n    This function will first try to guess the base branch and if it can't it\n    will let the user choose the branch from the list of all local branches.\n\n    Returns:\n        str: The name of the branch the current branch is based on."
  },
  {
    "code": "def run(command, verbose=False):\n    def do_nothing(*args, **kwargs):\n        return None\n    v_print = print if verbose else do_nothing\n    p = subprocess.Popen(\n        command,\n        shell=True,\n        stdout=subprocess.PIPE,\n        stderr=subprocess.STDOUT,\n        universal_newlines=True,\n    )\n    v_print(\"run:\", command)\n    def log_and_yield(line):\n        if six.PY2:\n            if isinstance(line, str):\n                line = line.decode('utf8', 'replace')\n        v_print(line)\n        return line\n    output = ''.join(map(log_and_yield, p.stdout))\n    status_code = p.wait()\n    return CommandResult(command, output, status_code)",
    "docstring": "Run a shell command.  Capture the stdout and stderr as a single stream.\n    Capture the status code.\n\n    If verbose=True, then print command and the output to the terminal as it\n    comes in."
  },
  {
    "code": "def _clear_stats(self):\n        for stat in (STAT_BYTES_RECEIVED,\n                     STAT_BYTES_SENT,\n                     STAT_MSG_RECEIVED,\n                     STAT_MSG_SENT,\n                     STAT_CLIENTS_MAXIMUM,\n                     STAT_CLIENTS_CONNECTED,\n                     STAT_CLIENTS_DISCONNECTED,\n                     STAT_PUBLISH_RECEIVED,\n                     STAT_PUBLISH_SENT):\n            self._stats[stat] = 0",
    "docstring": "Initializes broker statistics data structures"
  },
  {
    "code": "def discovery_mqtt(self):\n        self.context.install_bundle(\"pelix.remote.discovery.mqtt\").start()\n        with use_waiting_list(self.context) as ipopo:\n            ipopo.add(\n                rs.FACTORY_DISCOVERY_MQTT,\n                \"pelix-discovery-mqtt\",\n                {\n                    \"application.id\": \"sample.rs\",\n                    \"mqtt.host\": self.arguments.mqtt_host,\n                    \"mqtt.port\": self.arguments.mqtt_port,\n                },\n            )",
    "docstring": "Installs the MQTT discovery bundles and instantiates components"
  },
  {
    "code": "def first(self, callback=None, default=None):\n        if callback is not None:\n            for val in self.items:\n                if callback(val):\n                    return val\n            return value(default)\n        if len(self.items) > 0:\n            return self.items[0]\n        else:\n            return default",
    "docstring": "Get the first item of the collection.\n\n        :param default: The default value\n        :type default: mixed"
  },
  {
    "code": "def remove_user_from_group(uid, gid):\n    acl_url = urljoin(_acl_url(), 'groups/{}/users/{}'.format(gid, uid))\n    try:\n        r = http.delete(acl_url)\n        assert r.status_code == 204\n    except dcos.errors.DCOSBadRequest:\n        pass",
    "docstring": "Removes a user from a group within DCOS Enterprise.\n\n        :param uid: user id\n        :type uid: str\n        :param gid: group id\n        :type gid: str"
  },
  {
    "code": "def from_dict(cls, arr_dict, dtype=None, fillna=False, **kwargs):\n        if dtype is None:\n            names = sorted(list(arr_dict.keys()))\n        else:\n            dtype = np.dtype(dtype)\n            dt_names = [f for f in dtype.names]\n            dict_names = [k for k in arr_dict.keys()]\n            missing_names = set(dt_names) - set(dict_names)\n            if missing_names:\n                if fillna:\n                    dict_names = dt_names\n                    for missing_name in missing_names:\n                        arr_dict[missing_name] = np.nan\n                else:\n                    raise KeyError(\n                        'Dictionary keys and dtype fields do not match!'\n                    )\n            names = list(dtype.names)\n        arr_dict = cls._expand_scalars(arr_dict)\n        data = [arr_dict[key] for key in names]\n        return cls(np.rec.fromarrays(data, names=names, dtype=dtype), **kwargs)",
    "docstring": "Generate a table from a dictionary of arrays."
  },
  {
    "code": "def primary_key(self, hkey, rkey=None):\n        if isinstance(hkey, dict):\n            def decode(val):\n                if isinstance(val, Decimal):\n                    return float(val)\n                return val\n            pkey = {self.hash_key.name: decode(hkey[self.hash_key.name])}\n            if self.range_key is not None:\n                pkey[self.range_key.name] = decode(hkey[self.range_key.name])\n            return pkey\n        else:\n            pkey = {self.hash_key.name: hkey}\n            if self.range_key is not None:\n                if rkey is None:\n                    raise ValueError(\"Range key is missing!\")\n                pkey[self.range_key.name] = rkey\n            return pkey",
    "docstring": "Construct a primary key dictionary\n\n        You can either pass in a (hash_key[, range_key]) as the arguments, or\n        you may pass in an Item itself"
  },
  {
    "code": "def data_from_techshop_ws(tws_url):\n    r = requests.get(tws_url)\n    if r.status_code == 200:\n        data = BeautifulSoup(r.text, \"lxml\")\n    else:\n        data = \"There was an error while accessing data on techshop.ws.\"\n    return data",
    "docstring": "Scrapes data from techshop.ws."
  },
  {
    "code": "def create(self, name, plugin_name, hadoop_version, description=None,\n               cluster_configs=None, node_groups=None, anti_affinity=None,\n               net_id=None, default_image_id=None, use_autoconfig=None,\n               shares=None, is_public=None, is_protected=None,\n               domain_name=None):\n        data = {\n            'name': name,\n            'plugin_name': plugin_name,\n            'hadoop_version': hadoop_version,\n        }\n        return self._do_create(data, description, cluster_configs,\n                               node_groups, anti_affinity, net_id,\n                               default_image_id, use_autoconfig, shares,\n                               is_public, is_protected, domain_name)",
    "docstring": "Create a Cluster Template."
  },
  {
    "code": "def find_config(revision):\n    if not is_git_repo():\n        return None\n    cfg_path = f\"{revision}:.cherry_picker.toml\"\n    cmd = \"git\", \"cat-file\", \"-t\", cfg_path\n    try:\n        output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)\n        path_type = output.strip().decode(\"utf-8\")\n        return cfg_path if path_type == \"blob\" else None\n    except subprocess.CalledProcessError:\n        return None",
    "docstring": "Locate and return the default config for current revison."
  },
  {
    "code": "def process_result_value(self, value, dialect):\n        if value is not None:\n            with BytesIO(value) as stream:\n                with GzipFile(fileobj=stream, mode=\"rb\") as file_handle:\n                    value = json.loads(file_handle.read().decode(\"utf-8\"))\n        return value",
    "docstring": "Convert a JSON encoded string to a dictionary structure."
  },
  {
    "code": "def _get_librato(ret=None):\n    _options = _get_options(ret)\n    conn = librato.connect(\n        _options.get('email'),\n        _options.get('api_token'),\n        sanitizer=librato.sanitize_metric_name,\n        hostname=_options.get('api_url'))\n    log.info(\"Connected to librato.\")\n    return conn",
    "docstring": "Return a Librato connection object."
  },
  {
    "code": "def tensor_kraus_maps(k1, k2):\n    return [np.kron(k1j, k2l) for k1j in k1 for k2l in k2]",
    "docstring": "Generate the Kraus map corresponding to the composition\n    of two maps on different qubits.\n\n    :param list k1: The Kraus operators for the first qubit.\n    :param list k2: The Kraus operators for the second qubit.\n    :return: A list of tensored Kraus operators."
  },
  {
    "code": "def close(self):\n        self.out_stream.close()\n        if self.in_place:\n            shutil.move(self.temp_file.name, self.out)",
    "docstring": "Close the stream. Assumes stream has 'close' method."
  },
  {
    "code": "def unix_word_rubout(event, WORD=True):\n    buff = event.current_buffer\n    pos = buff.document.find_start_of_previous_word(count=event.arg, WORD=WORD)\n    if pos is None:\n        pos = - buff.cursor_position\n    if pos:\n        deleted = buff.delete_before_cursor(count=-pos)\n        if event.is_repeat:\n            deleted += event.cli.clipboard.get_data().text\n        event.cli.clipboard.set_text(deleted)\n    else:\n        event.cli.output.bell()",
    "docstring": "Kill the word behind point, using whitespace as a word boundary.\n    Usually bound to ControlW."
  },
  {
    "code": "def minimise(routing_table, target_length):\n    table, _ = ordered_covering(routing_table, target_length, no_raise=True)\n    return remove_default_routes(table, target_length)",
    "docstring": "Reduce the size of a routing table by merging together entries where\n    possible and by removing any remaining default routes.\n\n    .. warning::\n\n        The input routing table *must* also include entries which could be\n        removed and replaced by default routing.\n\n    .. warning::\n\n        It is assumed that the input routing table is not in any particular\n        order and may be reordered into ascending order of generality (number\n        of don't cares/Xs in the key-mask) without affecting routing\n        correctness.  It is also assumed that if this table is unordered it is\n        at least orthogonal (i.e., there are no two entries which would match\n        the same key) and reorderable.\n\n        .. note::\n\n            If *all* the keys in the table are derived from a single instance\n            of :py:class:`~rig.bitfield.BitField` then the table is guaranteed\n            to be orthogonal and reorderable.\n\n        .. note::\n\n            Use :py:meth:`~rig.routing_table.expand_entries` to generate an\n            orthogonal table and receive warnings if the input table is not\n            orthogonal.\n\n    Parameters\n    ----------\n    routing_table : [:py:class:`~rig.routing_table.RoutingTableEntry`, ...]\n        Routing entries to be merged.\n    target_length : int or None\n        Target length of the routing table; the minimisation procedure will\n        halt once either this target is reached or no further minimisation is\n        possible. If None then the table will be made as small as possible.\n\n    Raises\n    ------\n    MinimisationFailedError\n        If the smallest table that can be produced is larger than\n        `target_length`.\n\n    Returns\n    -------\n    [:py:class:`~rig.routing_table.RoutingTableEntry`, ...]\n        Reduced routing table entries."
  },
  {
    "code": "def register_scf_task(self, *args, **kwargs):\n        kwargs[\"task_class\"] = ScfTask\n        return self.register_task(*args, **kwargs)",
    "docstring": "Register a Scf task."
  },
  {
    "code": "def intersection(self, other):\n        ivs = set()\n        shorter, longer = sorted([self, other], key=len)\n        for iv in shorter:\n            if iv in longer:\n                ivs.add(iv)\n        return IntervalTree(ivs)",
    "docstring": "Returns a new tree of all intervals common to both self and\n        other."
  },
  {
    "code": "def _find_logs(self, compile_workunit):\n    for idx, workunit in enumerate(compile_workunit.children):\n      for output_name, outpath in workunit.output_paths().items():\n        if output_name in ('stdout', 'stderr'):\n          yield idx, workunit.name, output_name, outpath",
    "docstring": "Finds all logs under the given workunit."
  },
  {
    "code": "def SetUpperTimestamp(cls, timestamp):\n    if not hasattr(cls, '_upper'):\n      cls._upper = timestamp\n      return\n    if timestamp > cls._upper:\n      cls._upper = timestamp",
    "docstring": "Sets the upper bound timestamp."
  },
  {
    "code": "def reset_all(self):\n        for item in self.inputs:\n            setattr(self, \"_%s\" % item, None)\n        self.stack = []",
    "docstring": "Resets all parameters to None"
  },
  {
    "code": "def run_zone(self, minutes, zone=None):\n        if zone is None:\n            zone_cmd = 'runall'\n            relay_id = None\n        else:\n            if zone < 0 or zone > (len(self.relays) - 1):\n                return None\n            else:\n                zone_cmd = 'run'\n                relay_id = self.relays[zone]['relay_id']\n        if minutes <= 0:\n            time_cmd = 0\n            if zone is None:\n                zone_cmd = 'stopall'\n            else:\n                zone_cmd = 'stop'\n        else:\n            time_cmd = minutes * 60\n        return set_zones(self._user_token, zone_cmd, relay_id, time_cmd)",
    "docstring": "Run or stop a zone or all zones for an amount of time.\n\n        :param minutes: The number of minutes to run.\n        :type minutes: int\n        :param zone: The zone number to run. If no zone is specified then run\n                     all zones.\n        :type zone: int or None\n        :returns: The response from set_zones() or None if there was an error.\n        :rtype: None or string"
  },
  {
    "code": "def viewbox_key_event(self, event):\n        PerspectiveCamera.viewbox_key_event(self, event)\n        if event.handled or not self.interactive:\n            return\n        if not self._timer.running:\n            self._timer.start()\n        if event.key in self._keymap:\n            val_dims = self._keymap[event.key]\n            val = val_dims[0]\n            if val == 0:\n                vec = self._brake\n                val = 1\n            else:\n                vec = self._acc\n            if event.type == 'key_release':\n                val = 0\n            for dim in val_dims[1:]:\n                factor = 1.0\n                vec[dim-1] = val * factor",
    "docstring": "ViewBox key event handler\n\n        Parameters\n        ----------\n        event : instance of Event\n            The event."
  },
  {
    "code": "def base_path(self):\n    path = self.request.path\n    base_path = path[:path.rfind(\"/\")]\n    if not base_path.endswith(\"/command\"):\n      raise BadRequestPathError(\n          \"Json handlers should have /command path prefix\")\n    return base_path[:base_path.rfind(\"/\")]",
    "docstring": "Base path for all mapreduce-related urls.\n\n    JSON handlers are mapped to /base_path/command/command_name thus they\n    require special treatment.\n\n    Raises:\n      BadRequestPathError: if the path does not end with \"/command\".\n\n    Returns:\n      The base path."
  },
  {
    "code": "def encode (self):\n    byte = self.default\n    for bit, name, value0, value1, default in SeqCmdAttrs.Table:\n      if name in self.attrs:\n        value = self.attrs[name]\n        byte  = setBit(byte, bit, value == value1)\n    return struct.pack('B', byte)",
    "docstring": "Encodes this SeqCmdAttrs to binary and returns a bytearray."
  },
  {
    "code": "def qt_at_least(needed_version, test_version=None):\n    major, minor, patch = needed_version.split('.')\n    needed_version = '0x0%s0%s0%s' % (major, minor, patch)\n    needed_version = int(needed_version, 0)\n    installed_version = Qt.QT_VERSION\n    if test_version is not None:\n        installed_version = test_version\n    if needed_version <= installed_version:\n        return True\n    else:\n        return False",
    "docstring": "Check if the installed Qt version is greater than the requested\n\n    :param needed_version: minimally needed Qt version in format like 4.8.4\n    :type needed_version: str\n\n    :param test_version: Qt version as returned from Qt.QT_VERSION. As in\n     0x040100 This is used only for tests\n    :type test_version: int\n\n    :returns: True if the installed Qt version is greater than the requested\n    :rtype: bool"
  },
  {
    "code": "def depth_first(problem, graph_search=False, viewer=None):\n    return _search(problem,\n                   LifoList(),\n                   graph_search=graph_search,\n                   viewer=viewer)",
    "docstring": "Depth first search.\n\n    If graph_search=True, will avoid exploring repeated states.\n    Requires: SearchProblem.actions, SearchProblem.result, and\n    SearchProblem.is_goal."
  },
  {
    "code": "def get_permissions_for_registration(self):\n        qs = Permission.objects.none()\n        for instance in self.modeladmin_instances:\n            qs = qs | instance.get_permissions_for_registration()\n        return qs",
    "docstring": "Utilised by Wagtail's 'register_permissions' hook to allow permissions\n        for a all models grouped by this class to be assigned to Groups in\n        settings."
  },
  {
    "code": "def send_mail(to_list, sub, content, cc=None):\n    sender = SMTP_CFG['name'] + \"<\" + SMTP_CFG['user'] + \">\"\n    msg = MIMEText(content, _subtype='html', _charset='utf-8')\n    msg['Subject'] = sub\n    msg['From'] = sender\n    msg['To'] = \";\".join(to_list)\n    if cc:\n        msg['cc'] = ';'.join(cc)\n    try:\n        smtper = smtplib.SMTP_SSL(SMTP_CFG['host'], port=994)\n        smtper.login(SMTP_CFG['user'], SMTP_CFG['pass'])\n        smtper.sendmail(sender, to_list, msg.as_string())\n        smtper.close()\n        return True\n    except:\n        return False",
    "docstring": "Sending email via Python."
  },
  {
    "code": "def flush(self):\n        if self._num_outstanding_events == 0 or self._recordio_writer is None:\n            return\n        self._recordio_writer.flush()\n        if self._logger is not None:\n            self._logger.info('wrote %d %s to disk', self._num_outstanding_events,\n                              'event' if self._num_outstanding_events == 1 else 'events')\n        self._num_outstanding_events = 0",
    "docstring": "Flushes the event file to disk."
  },
  {
    "code": "def _datetime_to_millis(dtm):\n    if dtm.utcoffset() is not None:\n        dtm = dtm - dtm.utcoffset()\n    return int(calendar.timegm(dtm.timetuple()) * 1000 +\n               dtm.microsecond // 1000)",
    "docstring": "Convert datetime to milliseconds since epoch UTC."
  },
  {
    "code": "def remove_all_timers(self):\n        with self.lock:\n            if self.rtimer is not None:\n                self.rtimer.cancel()\n            self.timers = {}\n            self.heap = []\n            self.rtimer = None\n            self.expiring = False",
    "docstring": "Remove all waiting timers and terminate any blocking threads."
  },
  {
    "code": "def make_tophat_ei (lower, upper):\n    if not np.isfinite (lower):\n        raise ValueError ('\"lower\" argument must be finite number; got %r' % lower)\n    if not np.isfinite (upper):\n        raise ValueError ('\"upper\" argument must be finite number; got %r' % upper)\n    def range_tophat_ei (x):\n        x = np.asarray (x)\n        x1 = np.atleast_1d (x)\n        r = ((lower < x1) & (x1 <= upper)).astype (x.dtype)\n        if x.ndim == 0:\n            return np.asscalar (r)\n        return r\n    range_tophat_ei.__doc__ = ('Ranged tophat function, left-exclusive and '\n                               'right-inclusive. Returns 1 if %g < x <= %g, '\n                               '0 otherwise.') % (lower, upper)\n    return range_tophat_ei",
    "docstring": "Return a ufunc-like tophat function on the defined range, left-exclusive\n    and right-inclusive. Returns 1 if lower < x <= upper, 0 otherwise."
  },
  {
    "code": "def pctile(self,pct,res=1000):\n        grid = np.linspace(self.minval,self.maxval,res)\n        return grid[np.argmin(np.absolute(pct-self.cdf(grid)))]",
    "docstring": "Returns the desired percentile of the distribution.\n\n        Will only work if properly normalized.  Designed to mimic\n        the `ppf` method of the `scipy.stats` random variate objects.\n        Works by gridding the CDF at a given resolution and matching the nearest\n        point.  NB, this is of course not as precise as an analytic ppf.\n\n        Parameters\n        ----------\n\n        pct : float\n            Percentile between 0 and 1.\n\n        res : int, optional\n            The resolution at which to grid the CDF to find the percentile.\n\n        Returns\n        -------\n        percentile : float"
  },
  {
    "code": "async def fetch_wallet_search_next_records(wallet_handle: int,\n                                           wallet_search_handle: int,\n                                           count: int) -> str:\n    logger = logging.getLogger(__name__)\n    logger.debug(\"fetch_wallet_search_next_records: >>> wallet_handle: %r, wallet_search_handle: %r, count: %r\",\n                 wallet_handle,\n                 wallet_search_handle,\n                 count)\n    if not hasattr(fetch_wallet_search_next_records, \"cb\"):\n        logger.debug(\"fetch_wallet_search_next_records: Creating callback\")\n        fetch_wallet_search_next_records.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_char_p))\n    c_wallet_handle = c_int32(wallet_handle)\n    c_wallet_search_handle = c_int32(wallet_search_handle)\n    c_count = c_uint(count)\n    records_json = await do_call('indy_fetch_wallet_search_next_records',\n                                 c_wallet_handle,\n                                 c_wallet_search_handle,\n                                 c_count,\n                                 fetch_wallet_search_next_records.cb)\n    res = records_json.decode()\n    logger.debug(\"fetch_wallet_search_next_records: <<< res: %r\", res)\n    return res",
    "docstring": "Fetch next records for wallet search.\n\n    :param wallet_handle: wallet handler (created by open_wallet).\n    :param wallet_search_handle: wallet wallet handle (created by open_wallet_search)\n    :param count: Count of records to fetch\n    :return: wallet records json:\n     {\n       totalCount: <str>, // present only if retrieveTotalCount set to true\n       records: [{ // present only if retrieveRecords set to true\n           id: \"Some id\",\n           type: \"Some type\", // present only if retrieveType set to true\n           value: \"Some value\", // present only if retrieveValue set to true\n           tags: <tags json>, // present only if retrieveTags set to true\n       }],\n     }"
  },
  {
    "code": "def find_type(cls, val):\n        mt = \"\"\n        index = val.rfind(\".\")\n        if index == -1:\n            val = \"fake.{}\".format(val)\n        elif index == 0:\n            val = \"fake{}\".format(val)\n        mt = mimetypes.guess_type(val)[0]\n        if mt is None:\n            mt = \"\"\n        return mt",
    "docstring": "return the mimetype from the given string value\n\n        if value is a path, then the extension will be found, if val is an extension then\n        that will be used to find the mimetype"
  },
  {
    "code": "def split(self, amount):\n        split_objs = list(self.all())\n        if not split_objs:\n            raise NoSplitsFoundForRecurringCost()\n        portions = [split_obj.portion for split_obj in split_objs]\n        split_amounts = ratio_split(amount, portions)\n        return [\n            (split_objs[i], split_amount)\n            for i, split_amount\n            in enumerate(split_amounts)\n        ]",
    "docstring": "Split the value given by amount according to the RecurringCostSplit's portions\n\n        Args:\n            amount (Decimal):\n\n        Returns:\n            list[(RecurringCostSplit, Decimal)]: A list with elements in the form (RecurringCostSplit, Decimal)"
  },
  {
    "code": "def needs_label(model_field, field_name):\n    default_label = field_name.replace('_', ' ').capitalize()\n    return capfirst(model_field.verbose_name) != default_label",
    "docstring": "Returns `True` if the label based on the model's verbose name\n    is not equal to the default label it would have based on it's field name."
  },
  {
    "code": "def usearch61_chimera_check_denovo(abundance_fp,\n                                   uchime_denovo_fp,\n                                   minlen=64,\n                                   output_dir=\".\",\n                                   remove_usearch_logs=False,\n                                   uchime_denovo_log_fp=\"uchime_denovo.log\",\n                                   usearch61_minh=0.28,\n                                   usearch61_xn=8.0,\n                                   usearch61_dn=1.4,\n                                   usearch61_mindiffs=3,\n                                   usearch61_mindiv=0.8,\n                                   usearch61_abundance_skew=2.0,\n                                   HALT_EXEC=False):\n    params = {'--minseqlength': minlen,\n              '--uchime_denovo': abundance_fp,\n              '--uchimeout': uchime_denovo_fp,\n              '--minh': usearch61_minh,\n              '--xn': usearch61_xn,\n              '--dn': usearch61_dn,\n              '--mindiffs': usearch61_mindiffs,\n              '--mindiv': usearch61_mindiv,\n              '--abskew': usearch61_abundance_skew\n              }\n    if not remove_usearch_logs:\n        params['--log'] = uchime_denovo_log_fp\n    app = Usearch61(params, WorkingDir=output_dir, HALT_EXEC=HALT_EXEC)\n    app_result = app()\n    return uchime_denovo_fp, app_result",
    "docstring": "Does de novo, abundance based chimera checking with usearch61\n\n    abundance_fp: input consensus fasta file with abundance information for\n     each cluster.\n    uchime_denovo_fp: output uchime file for chimera results.\n    minlen: minimum sequence length for usearch input fasta seqs.\n    output_dir: output directory\n    removed_usearch_logs: suppresses creation of log file.\n    uchime_denovo_log_fp: output filepath for log file.\n    usearch61_minh: Minimum score (h) to be classified as chimera.\n     Increasing this value tends to the number of false positives (and also\n     sensitivity).\n    usearch61_xn:  Weight of \"no\" vote.  Increasing this value tends to the\n     number of false positives (and also sensitivity).\n    usearch61_dn:  Pseudo-count prior for \"no\" votes. (n). Increasing this\n     value tends to the number of false positives (and also sensitivity).\n    usearch61_mindiffs:  Minimum number of diffs in a segment. Increasing this\n     value tends to reduce the number of false positives while reducing\n     sensitivity to very low-divergence chimeras.\n    usearch61_mindiv:  Minimum divergence, i.e. 100% - identity between the\n     query and closest reference database sequence. Expressed as a percentage,\n     so the default is 0.8%, which allows chimeras that are up to 99.2% similar\n     to a reference sequence.\n    usearch61_abundance_skew: abundance skew for de novo chimera comparisons.\n    HALTEXEC: halt execution and returns command used for app controller."
  },
  {
    "code": "def parse_feed(content):\n        feed = feedparser.parse(content)\n        articles = []\n        for entry in feed['entries']:\n            article = {\n                'title': entry['title'],\n                'link': entry['link']\n            }\n            try:\n                article['media'] = entry['media_content'][0]['url']\n            except KeyError:\n                article['media'] = None\n            articles.append(article)\n        return articles",
    "docstring": "utility function to parse feed"
  },
  {
    "code": "def read_bytes(self):\n\t\tglobal exit_flag\n\t\tfor self.i in range(0, self.length) :\n\t\t\tself.bytes[self.i] = i_max[self.i]\n\t\t\tself.maxbytes[self.i] = total_chunks[self.i]\n\t\t\tself.progress[self.i][\"maximum\"] = total_chunks[self.i]\n\t\t\tself.progress[self.i][\"value\"] = self.bytes[self.i]\n\t\t\tself.str[self.i].set(file_name[self.i]+ \"       \" + str(self.bytes[self.i]) \n\t\t\t\t\t\t\t\t  + \"KB / \" + str(int(self.maxbytes[self.i] + 1)) + \" KB\")\n\t\tif exit_flag == self.length:\n\t\t\texit_flag = 0\n\t\t\tself.frame.destroy()\n\t\telse:\n\t\t\tself.frame.after(10, self.read_bytes)",
    "docstring": "reading bytes; update progress bar after 1 ms"
  },
  {
    "code": "def textMD5(text):\n    m = hash_md5()\n    if isinstance(text, str):\n        m.update(text.encode())\n    else:\n        m.update(text)\n    return m.hexdigest()",
    "docstring": "Get md5 of a piece of text"
  },
  {
    "code": "def get_contour(mask):\n    if isinstance(mask, np.ndarray) and len(mask.shape) == 2:\n        mask = [mask]\n        ret_list = False\n    else:\n        ret_list = True\n    contours = []\n    for mi in mask:\n        c0 = find_contours(mi.transpose(),\n                           level=.9999,\n                           positive_orientation=\"low\",\n                           fully_connected=\"high\")[0]\n        c1 = np.asarray(np.round(c0), int)\n        c2 = remove_duplicates(c1)\n        contours.append(c2)\n    if ret_list:\n        return contours\n    else:\n        return contours[0]",
    "docstring": "Compute the image contour from a mask\n\n    The contour is computed in a very inefficient way using scikit-image\n    and a conversion of float coordinates to pixel coordinates.\n\n    Parameters\n    ----------\n    mask: binary ndarray of shape (M,N) or (K,M,N)\n        The mask outlining the pixel positions of the event.\n        If a 3d array is given, then `K` indexes the individual\n        contours.\n\n    Returns\n    -------\n    cont: ndarray or list of K ndarrays of shape (J,2)\n        A 2D array that holds the contour of an event (in pixels)\n        e.g. obtained using `mm.contour` where  `mm` is an instance\n        of `RTDCBase`. The first and second columns of `cont`\n        correspond to the x- and y-coordinates of the contour."
  },
  {
    "code": "def count(self):\n        \"The number of items, pruned or otherwise, contained by this branch.\"\n        if getattr(self, '_count', None) is None:\n            self._count = getattr(self.node, 'count', 0)\n        return self._count",
    "docstring": "The number of items, pruned or otherwise, contained by this branch."
  },
  {
    "code": "def disconnect(self):\n        if self.connected:\n            self._socket.close()\n            self._socket = None\n            self.connected = False",
    "docstring": "Disconnect from deluge"
  },
  {
    "code": "def get_signatures(self):\n        signatures = self.request_list('GetSignatures')\n        return [zobjects.Signature.from_dict(i) for i in signatures]",
    "docstring": "Get all signatures for the current user\n\n        :returns: a list of zobjects.Signature"
  },
  {
    "code": "def authenticate_credentials(self, token):\n        msg = _('Invalid token.')\n        token = token.decode(\"utf-8\")\n        for auth_token in AuthToken.objects.filter(\n                token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH]):\n            if self._cleanup_token(auth_token):\n                continue\n            try:\n                digest = hash_token(token, auth_token.salt)\n            except (TypeError, binascii.Error):\n                raise exceptions.AuthenticationFailed(msg)\n            if compare_digest(digest, auth_token.digest):\n                if knox_settings.AUTO_REFRESH and auth_token.expiry:\n                    self.renew_token(auth_token)\n                return self.validate_user(auth_token)\n        raise exceptions.AuthenticationFailed(msg)",
    "docstring": "Due to the random nature of hashing a salted value, this must inspect\n        each auth_token individually to find the correct one.\n\n        Tokens that have expired will be deleted and skipped"
  },
  {
    "code": "async def pull(\n        self,\n        from_image: str,\n        *,\n        auth: Optional[Union[MutableMapping, str, bytes]] = None,\n        tag: str = None,\n        repo: str = None,\n        stream: bool = False\n    ) -> Mapping:\n        image = from_image\n        params = {\"fromImage\": image}\n        headers = {}\n        if repo:\n            params[\"repo\"] = repo\n        if tag:\n            params[\"tag\"] = tag\n        if auth is not None:\n            registry, has_registry_host, _ = image.partition(\"/\")\n            if not has_registry_host:\n                raise ValueError(\n                    \"Image should have registry host \"\n                    \"when auth information is provided\"\n                )\n            headers[\"X-Registry-Auth\"] = compose_auth_header(auth, registry)\n        response = await self.docker._query(\n            \"images/create\", \"POST\", params=params, headers=headers\n        )\n        return await json_stream_result(response, stream=stream)",
    "docstring": "Similar to `docker pull`, pull an image locally\n\n        Args:\n            fromImage: name of the image to pull\n            repo: repository name given to an image when it is imported\n            tag: if empty when pulling an image all tags\n                 for the given image to be pulled\n            auth: special {'auth': base64} pull private repo"
  },
  {
    "code": "def _text_io_wrapper(stream, mode, encoding, errors, newline):\n    if \"t\" in mode and not hasattr(stream, 'encoding'):\n        text_stream = TextIOWrapper(\n            stream, encoding=encoding, errors=errors, newline=newline)\n        yield text_stream\n        text_stream.flush()\n    else:\n        yield stream",
    "docstring": "Wrap a binary stream to Text stream.\n\n    Args:\n        stream (file-like object): binary stream.\n        mode (str): Open mode.\n        encoding (str): Stream encoding.\n        errors (str): Decoding error handling.\n        newline (str): Universal newlines"
  },
  {
    "code": "def point(self, x, y):\n        return EllipticCurve.ECPoint(self, self.field.value(x), self.field.value(y))",
    "docstring": "construct a point from 2 values"
  },
  {
    "code": "def mse(predicted, actual):\n    diff = predicted - actual\n    return np.average(diff * diff, axis=0)",
    "docstring": "Mean squared error of predictions.\n\n    .. versionadded:: 0.5.0\n\n    Parameters\n    ----------\n    predicted : ndarray\n        Predictions on which to measure error. May\n        contain a single or multiple column but must\n        match `actual` in shape.\n\n    actual : ndarray\n        Actual values against which to measure predictions.\n\n    Returns\n    -------\n    err : ndarray\n        Mean squared error of predictions relative to actual\n        values."
  },
  {
    "code": "def clear():\n    utils.check_for_local_server()\n    click.confirm(\n        \"Are you sure you want to do this? It will delete all of your data\",\n        abort=True\n    )\n    server = Server(config[\"local_server\"][\"url\"])\n    for db_name in all_dbs:\n        del server[db_name]",
    "docstring": "Clear all data on the local server. Useful for debugging purposed."
  },
  {
    "code": "def pop_cell(self, idy=None, idx=None, tags=False):\n        idy = idy if idy is not None else len(self.body) - 1\n        idx = idx if idx is not None else len(self.body[idy]) - 1\n        cell = self.body[idy].pop(idx)\n        return cell if tags else cell.childs[0]",
    "docstring": "Pops a cell, default the last of the last row"
  },
  {
    "code": "def _get_ssl_context(self, req: 'ClientRequest') -> Optional[SSLContext]:\n        if req.is_ssl():\n            if ssl is None:\n                raise RuntimeError('SSL is not supported.')\n            sslcontext = req.ssl\n            if isinstance(sslcontext, ssl.SSLContext):\n                return sslcontext\n            if sslcontext is not None:\n                return self._make_ssl_context(False)\n            sslcontext = self._ssl\n            if isinstance(sslcontext, ssl.SSLContext):\n                return sslcontext\n            if sslcontext is not None:\n                return self._make_ssl_context(False)\n            return self._make_ssl_context(True)\n        else:\n            return None",
    "docstring": "Logic to get the correct SSL context\n\n        0. if req.ssl is false, return None\n\n        1. if ssl_context is specified in req, use it\n        2. if _ssl_context is specified in self, use it\n        3. otherwise:\n            1. if verify_ssl is not specified in req, use self.ssl_context\n               (will generate a default context according to self.verify_ssl)\n            2. if verify_ssl is True in req, generate a default SSL context\n            3. if verify_ssl is False in req, generate a SSL context that\n               won't verify"
  },
  {
    "code": "def nlargest(n, mapping):\n    try:\n        it = mapping.iteritems()\n    except AttributeError:\n        it = iter(mapping.items())\n    pq = minpq()\n    try:\n        for i in range(n):\n            pq.additem(*next(it))\n    except StopIteration:\n        pass\n    try:\n        while it:\n            pq.pushpopitem(*next(it))\n    except StopIteration:\n        pass\n    out = list(pq.popkeys())\n    out.reverse()\n    return out",
    "docstring": "Takes a mapping and returns the n keys associated with the largest values\n    in descending order. If the mapping has fewer than n items, all its keys\n    are returned.\n\n    Equivalent to:\n        ``next(zip(*heapq.nlargest(mapping.items(), key=lambda x: x[1])))``\n\n    Returns\n    -------\n    list of up to n keys from the mapping"
  },
  {
    "code": "def fit(self, X, y):\n        self._word_vocab.add_documents(X)\n        self._label_vocab.add_documents(y)\n        if self._use_char:\n            for doc in X:\n                self._char_vocab.add_documents(doc)\n        self._word_vocab.build()\n        self._char_vocab.build()\n        self._label_vocab.build()\n        return self",
    "docstring": "Learn vocabulary from training set.\n\n        Args:\n            X : iterable. An iterable which yields either str, unicode or file objects.\n\n        Returns:\n            self : IndexTransformer."
  },
  {
    "code": "def build_source_files(self):\n        from .files import BuildSourceFileAccessor\n        return BuildSourceFileAccessor(self, self.dataset, self.source_fs)",
    "docstring": "Return acessors to the build files"
  },
  {
    "code": "def json(self):\n        self.pendingvalidation()\n        jsondoc = {'id': self.id, 'children': [], 'declarations': self.jsondeclarations() }\n        if self.version:\n            jsondoc['version'] = self.version\n        else:\n            jsondoc['version'] = FOLIAVERSION\n        jsondoc['generator'] = 'pynlpl.formats.folia-v' + LIBVERSION\n        for text in self.data:\n            jsondoc['children'].append(text.json())\n        return jsondoc",
    "docstring": "Serialise the document to a ``dict`` ready for serialisation to JSON.\n\n        Example::\n\n            import json\n            jsondoc = json.dumps(doc.json())"
  },
  {
    "code": "def data(self, buffer_index):\n        expired = self.time - self.max_time     \n        exp = self.buffer_expire[buffer_index]\n        j = 0\n        while j < len(exp):\n            if exp[j] >= expired:\n                self.buffer_expire[buffer_index] = exp[j:].copy()\n                self.buffer[buffer_index] = self.buffer[buffer_index][j:].copy()\n                break\n            j += 1\n        return self.buffer[buffer_index]",
    "docstring": "Return the data vector for a given ring buffer"
  },
  {
    "code": "def tofile(self, fobj, format):\n        if format == 'hex':\n            self.write_hex_file(fobj)\n        elif format == 'bin':\n            self.tobinfile(fobj)\n        else:\n            raise ValueError('format should be either \"hex\" or \"bin\";'\n                ' got %r instead' % format)",
    "docstring": "Write data to hex or bin file. Preferred method over tobin or tohex.\n\n        @param  fobj        file name or file-like object\n        @param  format      file format (\"hex\" or \"bin\")"
  },
  {
    "code": "def writeln (self, s=u\"\", **args):\n        self.write(u\"%s%s\" % (s, unicode(os.linesep)), **args)",
    "docstring": "Write string to output descriptor plus a newline."
  },
  {
    "code": "def _finalize_cwl_in(data, work_dir, passed_keys, output_cwl_keys, runtime):\n    data[\"dirs\"] = {\"work\": work_dir}\n    if not tz.get_in([\"config\", \"algorithm\"], data):\n        if \"config\" not in data:\n            data[\"config\"] = {}\n        data[\"config\"][\"algorithm\"] = {}\n    if \"rgnames\" not in data and \"description\" in data:\n        data[\"rgnames\"] = {\"sample\": data[\"description\"]}\n    data[\"cwl_keys\"] = passed_keys\n    data[\"output_cwl_keys\"] = output_cwl_keys\n    data = _add_resources(data, runtime)\n    data = cwlutils.normalize_missing(data)\n    data = run_info.normalize_world(data)\n    return data",
    "docstring": "Finalize data object with inputs from CWL."
  },
  {
    "code": "def publish(self, *args, **kwargs):\n        user_cb = kwargs.pop('cb', None)\n        channel = self._get_channel()\n        if channel and not channel.active:\n            inactive_channels = set()\n            while channel and not channel.active:\n                inactive_channels.add(channel)\n                channel = self._get_channel()\n            self._free_channels.update(inactive_channels)\n        def committed():\n            self._free_channels.add(channel)\n            if channel.active and not channel.closed:\n                self._process_queue()\n            if user_cb is not None:\n                user_cb()\n        if channel:\n            channel.publish_synchronous(*args, cb=committed, **kwargs)\n        else:\n            kwargs['cb'] = user_cb\n            self._queue.append((args, kwargs))",
    "docstring": "Publish a message. Caller can supply an optional callback which will\n        be fired when the transaction is committed. Tries very hard to avoid\n        closed and inactive channels, but a ChannelError or ConnectionError\n        may still be raised."
  },
  {
    "code": "def segment_array(arr, length, overlap=.5):\n    arr = N.array(arr)\n    offset = float(overlap) * length\n    total_segments = int((N.shape(arr)[0] - length) / offset) + 1\n    other_shape = N.shape(arr)[1:]\n    out_shape = [total_segments, length]\n    out_shape.extend(other_shape)\n    out = N.empty(out_shape)\n    for i in xrange(total_segments):\n        out[i][:] = arr[i * offset:i * offset + length]\n    return out",
    "docstring": "Segment array into chunks of a specified length, with a specified\n    proportion overlap.\n\n    Operates on axis 0.\n\n    :param integer length: Length of each segment\n    :param float overlap: Proportion overlap of each frame"
  },
  {
    "code": "def expandEntitiesFromEmail(e):\n    email = {}\n    email[\"type\"] = \"i3visio.email\"\n    email[\"value\"] = e\n    email[\"attributes\"] = []\n    alias = {}\n    alias[\"type\"] = \"i3visio.alias\"\n    alias[\"value\"] = e.split(\"@\")[0]\n    alias[\"attributes\"] = []\n    domain= {}\n    domain[\"type\"] = \"i3visio.domain\"\n    domain[\"value\"] = e.split(\"@\")[1]\n    domain[\"attributes\"] = []\n    return [email, alias, domain]",
    "docstring": "Method that receives an email an creates linked entities\n\n    Args:\n    -----\n        e:   Email to verify.\n\n    Returns:\n    --------\n        Three different values: email, alias and domain in a list."
  },
  {
    "code": "def _normalize_for_correlation(data, axis, return_nans=False):\n    shape = data.shape\n    data = zscore(data, axis=axis, ddof=0)\n    if not return_nans:\n        data = np.nan_to_num(data)\n    data = data / math.sqrt(shape[axis])\n    return data",
    "docstring": "normalize the data before computing correlation\n\n    The data will be z-scored and divided by sqrt(n)\n    along the assigned axis\n\n    Parameters\n    ----------\n    data: 2D array\n\n    axis: int\n        specify which dimension of the data should be normalized\n\n    return_nans: bool, default:False\n        If False, return zeros for NaNs; if True, return NaNs\n\n    Returns\n    -------\n    data: 2D array\n        the normalized data"
  },
  {
    "code": "def get_md_header(header_text_line: str,\n                  header_duplicate_counter: dict,\n                  keep_header_levels: int = 3,\n                  parser: str = 'github',\n                  no_links: bool = False) -> dict:\n    r\n    result = get_atx_heading(header_text_line, keep_header_levels, parser,\n                             no_links)\n    if result is None:\n        return result\n    else:\n        header_type, header_text_trimmed = result\n        header = {\n            'type':\n            header_type,\n            'text_original':\n            header_text_trimmed,\n            'text_anchor_link':\n            build_anchor_link(header_text_trimmed, header_duplicate_counter,\n                              parser)\n        }\n        return header",
    "docstring": "r\"\"\"Build a data structure with the elements needed to create a TOC line.\n\n    :parameter header_text_line: a single markdown line that needs to be\n         transformed into a TOC line.\n    :parameter header_duplicate_counter: a data structure that contains the\n         number of occurrencies of each header anchor link. This is used to\n         avoid duplicate anchor links and it is meaningful only for certain\n         values of parser.\n    :parameter keep_header_levels: the maximum level of headers to be\n         considered as such when building the table of contents.\n         Defaults to ``3``.\n    :parameter parser: decides rules on how to generate anchor links.\n         Defaults to ``github``.\n    :type header_text_line: str\n    :type header_duplicate_counter: dict\n    :type keep_header_levels: int\n    :type parser: str\n    :returns: None if the input line does not correspond to one of the\n         designated cases or a data structure containing the necessary\n         components to create a table of contents line, otherwise.\n    :rtype: dict\n    :raises: a built-in exception.\n\n    .. note::\n         This works like a wrapper to other functions."
  },
  {
    "code": "def get_error_message(status_code):\n    errmsg = ctypes.create_string_buffer(1024)\n    nican.ncStatusToString(status_code, len(errmsg), errmsg)\n    return errmsg.value.decode(\"ascii\")",
    "docstring": "Convert status code to descriptive string."
  },
  {
    "code": "def authenticated(\n    method: Callable[..., Optional[Awaitable[None]]]\n) -> Callable[..., Optional[Awaitable[None]]]:\n    @functools.wraps(method)\n    def wrapper(\n        self: RequestHandler, *args, **kwargs\n    ) -> Optional[Awaitable[None]]:\n        if not self.current_user:\n            if self.request.method in (\"GET\", \"HEAD\"):\n                url = self.get_login_url()\n                if \"?\" not in url:\n                    if urllib.parse.urlsplit(url).scheme:\n                        next_url = self.request.full_url()\n                    else:\n                        assert self.request.uri is not None\n                        next_url = self.request.uri\n                    url += \"?\" + urlencode(dict(next=next_url))\n                self.redirect(url)\n                return None\n            raise HTTPError(403)\n        return method(self, *args, **kwargs)\n    return wrapper",
    "docstring": "Decorate methods with this to require that the user be logged in.\n\n    If the user is not logged in, they will be redirected to the configured\n    `login url <RequestHandler.get_login_url>`.\n\n    If you configure a login url with a query parameter, Tornado will\n    assume you know what you're doing and use it as-is.  If not, it\n    will add a `next` parameter so the login page knows where to send\n    you once you're logged in."
  },
  {
    "code": "def apply_defaults(self, instance):\n        for field, spec in self.doc_spec.iteritems():\n            field_type = spec['type']\n            if field not in instance:\n                if 'default' in spec:\n                    default = spec['default']\n                    if callable(default):\n                        instance[field] = default()\n                    else:\n                        instance[field] = copy.deepcopy(default)\n            if field in instance:\n                value = instance[field]\n                if isinstance(field_type, Schema) and isinstance(value, dict):\n                    field_type.apply_defaults(value)\n                elif isinstance(field_type, Array) and isinstance(field_type.contained_type, Schema) and isinstance(value, list):\n                    for item in value:\n                        field_type.contained_type.apply_defaults(item)",
    "docstring": "Applies the defaults described by the this schema to the given\n        document instance as appropriate. Defaults are only applied to\n        fields which are currently unset."
  },
  {
    "code": "def find_keyword_in_context(tokens, keyword, contextsize=1):\n    if isinstance(keyword,tuple) and isinstance(keyword,list):\n        l = len(keyword)\n    else:\n        keyword = (keyword,)\n        l = 1\n    n = l + contextsize*2\n    focuspos = contextsize + 1\n    for ngram in Windower(tokens,n,None,None):\n        if ngram[focuspos:focuspos+l] == keyword:\n            yield ngram[:focuspos], ngram[focuspos:focuspos+l],ngram[focuspos+l+1:]",
    "docstring": "Find a keyword in a particular sequence of tokens, and return the local context. Contextsize is the number of words to the left and right. The keyword may have multiple word, in which case it should to passed as a tuple or list"
  },
  {
    "code": "def get_tp_from_file(file_path):\n    match = TP_FROM_FILE_REGEX.match(file_path)\n    if not match:\n        print(\"File path is not valid: \" + file_path)\n        sys.exit(1)\n    return match.group(1)",
    "docstring": "Return the name of the topic-partition given the path to the file.\n\n    :param file_path: the path to the log file\n    :type file_path: str\n    :returns: the name of the topic-partition, ex. \"topic_name-0\"\n    :rtype: str"
  },
  {
    "code": "def cursor(self, *cursors):\n        self._ensure_alive()\n        self._last_usage = self._loop.time()\n        try:\n            if cursors and \\\n                    any(not issubclass(cursor, Cursor) for cursor in cursors):\n                raise TypeError('Custom cursor must be subclass of Cursor')\n        except TypeError:\n            raise TypeError('Custom cursor must be subclass of Cursor')\n        if cursors and len(cursors) == 1:\n            cur = cursors[0](self, self._echo)\n        elif cursors:\n            cursor_name = ''.join(map(lambda x: x.__name__, cursors)) \\\n                .replace('Cursor', '') + 'Cursor'\n            cursor_class = type(cursor_name, cursors, {})\n            cur = cursor_class(self, self._echo)\n        else:\n            cur = self.cursorclass(self, self._echo)\n        fut = self._loop.create_future()\n        fut.set_result(cur)\n        return _ContextManager(fut)",
    "docstring": "Instantiates and returns a cursor\n\n        By default, :class:`Cursor` is returned. It is possible to also give a\n        custom cursor through the cursor_class parameter, but it needs to\n        be a subclass  of :class:`Cursor`\n\n        :param cursor: custom cursor class.\n        :returns: instance of cursor, by default :class:`Cursor`\n        :raises TypeError: cursor_class is not a subclass of Cursor."
  },
  {
    "code": "def query_fetch_one(self, query, values):\n        self.cursor.execute(query, values)\n        retval = self.cursor.fetchone()\n        self.__close_db()\n        return retval",
    "docstring": "Executes a db query, gets the first value, and closes the connection."
  },
  {
    "code": "def rpc_get_names(self, filename, source, offset):\n        names = jedi.api.names(source=source,\n                               path=filename, encoding='utf-8',\n                               all_scopes=True,\n                               definitions=True,\n                               references=True)\n        result = []\n        for name in names:\n            if name.module_path == filename:\n                offset = linecol_to_pos(source, name.line, name.column)\n            elif name.module_path is not None:\n                with open(name.module_path) as f:\n                    text = f.read()\n                offset = linecol_to_pos(text, name.line, name.column)\n            result.append({\"name\": name.name,\n                           \"filename\": name.module_path,\n                           \"offset\": offset})\n        return result",
    "docstring": "Return the list of possible names"
  },
  {
    "code": "def set_terminal(self, terminal):\n        if self.terminal is not None:\n            raise RuntimeError(\"TerminalBox: terminal already set\")\n        self.terminal = terminal\n        self.terminal.connect(\"grab-focus\", self.on_terminal_focus)\n        self.terminal.connect(\"button-press-event\", self.on_button_press, None)\n        self.terminal.connect('child-exited', self.on_terminal_exited)\n        self.pack_start(self.terminal, True, True, 0)\n        self.terminal.show()\n        self.add_scroll_bar()",
    "docstring": "Packs the terminal widget."
  },
  {
    "code": "def queuedb_append(path, queue_id, name, data):\n    sql = \"INSERT INTO queue VALUES (?,?,?);\"\n    args = (name, queue_id, data)\n    db = queuedb_open(path)\n    if db is None:\n        raise Exception(\"Failed to open %s\" % path)\n    cur = db.cursor()\n    res = queuedb_query_execute(cur, sql, args)\n    db.commit()\n    db.close()\n    return True",
    "docstring": "Append an element to the back of the queue.\n    Return True on success\n    Raise on error"
  },
  {
    "code": "def returner(ret):\n    log.debug('sqlite3 returner <returner> called with data: %s', ret)\n    conn = _get_conn(ret)\n    cur = conn.cursor()\n    sql =\n    cur.execute(sql,\n                {'fun': ret['fun'],\n                 'jid': ret['jid'],\n                 'id': ret['id'],\n                 'fun_args': six.text_type(ret['fun_args']) if ret.get('fun_args') else None,\n                 'date': six.text_type(datetime.datetime.now()),\n                 'full_ret': salt.utils.json.dumps(ret['return']),\n                 'success': ret.get('success', '')})\n    _close_conn(conn)",
    "docstring": "Insert minion return data into the sqlite3 database"
  },
  {
    "code": "def _connect(self, database=None):\n        conn_args = {\n            'host': self.config['host'],\n            'user': self.config['user'],\n            'password': self.config['password'],\n            'port': self.config['port'],\n            'sslmode': self.config['sslmode'],\n        }\n        if database:\n            conn_args['database'] = database\n        else:\n            conn_args['database'] = 'postgres'\n        if self.config['password_provider'] == 'pgpass':\n            del conn_args['password']\n        try:\n            conn = psycopg2.connect(**conn_args)\n        except Exception as e:\n            self.log.error(e)\n            raise e\n        conn.set_isolation_level(0)\n        return conn",
    "docstring": "Connect to given database"
  },
  {
    "code": "def transform_non_affine(self, x, mask_out_of_range=True):\n        if mask_out_of_range:\n            x_masked = np.ma.masked_where((x < self._xmin) | (x > self._xmax),\n                                          x)\n        else:\n            x_masked = x\n        return np.interp(x_masked, self._x_range, self._s_range)",
    "docstring": "Transform a Nx1 numpy array.\n\n        Parameters\n        ----------\n        x : array\n            Data to be transformed.\n        mask_out_of_range : bool, optional\n            Whether to mask input values out of range.\n\n        Return\n        ------\n        array or masked array\n            Transformed data."
  },
  {
    "code": "def compute_merkletree_with(\n        merkletree: MerkleTreeState,\n        lockhash: LockHash,\n) -> Optional[MerkleTreeState]:\n    result = None\n    leaves = merkletree.layers[LEAVES]\n    if lockhash not in leaves:\n        leaves = list(leaves)\n        leaves.append(Keccak256(lockhash))\n        result = MerkleTreeState(compute_layers(leaves))\n    return result",
    "docstring": "Register the given lockhash with the existing merkle tree."
  },
  {
    "code": "def generate(env):\n    M4Action = SCons.Action.Action('$M4COM', '$M4COMSTR')\n    bld = SCons.Builder.Builder(action = M4Action, src_suffix = '.m4')\n    env['BUILDERS']['M4'] = bld\n    env['M4']      = 'm4'\n    env['M4FLAGS'] = SCons.Util.CLVar('-E')\n    env['M4COM']   = 'cd ${SOURCE.rsrcdir} && $M4 $M4FLAGS < ${SOURCE.file} > ${TARGET.abspath}'",
    "docstring": "Add Builders and construction variables for m4 to an Environment."
  },
  {
    "code": "def persist_checksum(self, requirement, cache_file):\n        if not self.config.trust_mod_times:\n            checksum_file = '%s.txt' % cache_file\n            with AtomicReplace(checksum_file) as temporary_file:\n                with open(temporary_file, 'w') as handle:\n                    handle.write('%s\\n' % requirement.checksum)",
    "docstring": "Persist the checksum of the input used to generate a binary distribution.\n\n        :param requirement: A :class:`.Requirement` object.\n        :param cache_file: The pathname of a cached binary distribution (a string).\n\n        .. note:: The checksum is only calculated and persisted when\n                  :attr:`~.Config.trust_mod_times` is :data:`False`."
  },
  {
    "code": "def erode_edge(dem, iterations=1):\n    import scipy.ndimage as ndimage \n    print('Eroding pixels near nodata: %i iterations' % iterations)\n    mask = np.ma.getmaskarray(dem)\n    mask_dilate = ndimage.morphology.binary_dilation(mask, iterations=iterations)\n    out = np.ma.array(dem, mask=mask_dilate)\n    return out",
    "docstring": "Erode pixels near nodata"
  },
  {
    "code": "def run(args, shell=False, exit=True):\n    if \"GH_TOKEN\" in os.environ:\n        token = get_token()\n    else:\n        token = b''\n    if not shell:\n        command = ' '.join(map(shlex.quote, args))\n    else:\n        command = args\n    command = command.replace(token.decode('utf-8'), '~'*len(token))\n    print(blue(command))\n    sys.stdout.flush()\n    returncode = run_command_hiding_token(args, token, shell=shell)\n    if exit and returncode != 0:\n        sys.exit(red(\"%s failed: %s\" % (command, returncode)))\n    return returncode",
    "docstring": "Run the command ``args``.\n\n    Automatically hides the secret GitHub token from the output.\n\n    If shell=False (recommended for most commands), args should be a list of\n    strings. If shell=True, args should be a string of the command to run.\n\n    If exit=True, it exits on nonzero returncode. Otherwise it returns the\n    returncode."
  },
  {
    "code": "def _iterate_through_class(self, class_dict):\n        output_dict = {}\n        for key in class_dict:\n            val = class_dict[key]\n            try:\n                val = val.__dict__\n            except AttributeError:\n                pass\n            if type(val) is dict:\n                val = self._iterate_through_class(val)\n            if type(val) is list:\n                temp_val = []\n                for val_i in val:\n                    try:\n                        val_i = val_i.__dict__\n                    except AttributeError:\n                        pass\n                    if type(val_i) is dict:\n                        val_i = self._iterate_through_class(val_i)\n                    temp_val.append(val_i)\n                val = temp_val\n            output_dict[key] = val\n        return output_dict",
    "docstring": "Recursive function for output dictionary creation.\n\n        Function will check each value in a dictionary to see if it is a\n        class, list, or dictionary object. The idea is to turn all class objects into\n        dictionaries. If it is a class object it will pass its ``class.__dict__``\n        recursively through this function again. If it is a dictionary,\n        it will pass the dictionary recursively through this functin again.\n\n        If the object is a list, it will iterate through entries checking for class\n        or dictionary objects and pass them recursively through this function.\n        This uses the knowledge of the list structures in the code.\n\n        Args:\n            class_dict (obj): Dictionary to iteratively check.\n\n        Returns:\n            Dictionary with all class objects turned into dictionaries."
  },
  {
    "code": "def etree_to_dict(tree):\n    d = {tree.tag.split('}')[1]: map(\n        etree_to_dict, tree.iterchildren()\n    ) or tree.text}\n    return d",
    "docstring": "Translate etree into dictionary.\n\n    :param tree: etree dictionary object\n    :type tree: <http://lxml.de/api/lxml.etree-module.html>"
  },
  {
    "code": "def secure(view):\n    AUTH = getattr(\n        settings,\n        'SLACKCHAT_AUTH_DECORATOR',\n        'django.contrib.admin.views.decorators.staff_member_required'\n    )\n    auth_decorator = import_class(AUTH)\n    return method_decorator(auth_decorator, name='dispatch')(view)",
    "docstring": "Set an auth decorator applied for views.\n    If DEBUG is on, we serve the view without authenticating.\n    Default is 'django.contrib.auth.decorators.login_required'.\n    Can also be 'django.contrib.admin.views.decorators.staff_member_required'\n    or a custom decorator."
  },
  {
    "code": "def parse_singular_int(t, tag_name):\n    pos = t.getElementsByTagName(tag_name)\n    assert(len(pos) == 1)\n    pos = pos[0]\n    assert(len(pos.childNodes) == 1)\n    v = pos.childNodes[0].data\n    assert(v.isdigit())\n    return int(v)",
    "docstring": "Parses the sole integer value with name tag_name in tag t. Heavy-handed with the asserts."
  },
  {
    "code": "def set_record(self, record, **kw):\n        if isstring(record):\n            card = FITSCard(record)\n            self.update(card)\n            self.verify()\n        else:\n            if isinstance(record, FITSRecord):\n                self.update(record)\n            elif isinstance(record, dict):\n                if 'name' in record and 'value' in record:\n                    self.update(record)\n                elif 'card_string' in record:\n                    self.set_record(record['card_string'])\n                else:\n                    raise ValueError('record must have name,value fields '\n                                     'or a card_string field')\n            else:\n                raise ValueError(\"record must be a string card or \"\n                                 \"dictionary or FITSRecord\")",
    "docstring": "check the record is valid and set keys in the dict\n\n        parameters\n        ----------\n        record: string\n            Dict representing a record or a string representing a FITS header\n            card"
  },
  {
    "code": "def gradient_log_joint(self, x):\n        T, D = self.T, self.D_latent\n        assert x.shape == (T, D)\n        _, h_init, _ = self.info_init_params\n        _, _, _, h1, h2, _ = self.info_dynamics_params\n        H_diag, H_upper_diag = self.sparse_J_prior\n        g = -1 * symm_block_tridiag_matmul(H_diag, H_upper_diag, x)\n        g[0] += h_init\n        g[:-1] += h1\n        g[1:] += h2\n        g += self.grad_local_log_likelihood(x)\n        return g",
    "docstring": "The gradient of the log joint probability.\n\n        For the Gaussian terms, this is\n\n            d/dx [-1/2 x^T J x + h^T x] = -Jx + h.\n\n        For the likelihood terms, we have for each time t\n\n            d/dx log p(yt | xt)"
  },
  {
    "code": "def getShocks(self):\n        IndShockConsumerType.getShocks(self)\n        PrefShkNow = np.zeros(self.AgentCount)\n        for t in range(self.T_cycle):\n            these = t == self.t_cycle\n            N = np.sum(these)\n            if N > 0:\n                PrefShkNow[these] = self.RNG.permutation(approxMeanOneLognormal(N,sigma=self.PrefShkStd[t])[1])\n        self.PrefShkNow = PrefShkNow",
    "docstring": "Gets permanent and transitory income shocks for this period as well as preference shocks.\n\n        Parameters\n        ----------\n        None\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def _handle_final_metric_data(self, data):\n        id_ = data['parameter_id']\n        value = data['value']\n        if id_ in _customized_parameter_ids:\n            self.tuner.receive_customized_trial_result(id_, _trial_params[id_], value)\n        else:\n            self.tuner.receive_trial_result(id_, _trial_params[id_], value)",
    "docstring": "Call tuner to process final results"
  },
  {
    "code": "def parse_docstring(docstring):\n    short_desc = long_desc = ''\n    if docstring:\n        docstring = trim(docstring.lstrip('\\n'))\n        lines = docstring.split('\\n\\n', 1)\n        short_desc = lines[0].strip().replace('\\n', ' ')\n        if len(lines) > 1:\n            long_desc = lines[1].strip()\n    return short_desc, long_desc",
    "docstring": "Parse a PEP-257 docstring.\n\n    SHORT -> blank line -> LONG"
  },
  {
    "code": "def print_all() -> None:\n    for code in sorted(term2hex_map):\n        print(' '.join((\n            '\\033[48;5;{code}m{code:<3}:{hexval:<6}\\033[0m',\n            '\\033[38;5;{code}m{code:<3}:{hexval:<6}\\033[0m'\n        )).format(code=code, hexval=term2hex_map[code]))",
    "docstring": "Print all 256 xterm color codes."
  },
  {
    "code": "def add_url(self, *args, **kwargs):\n        if len(args) == 1 and not kwargs and isinstance(args[0], UrlEntry):\n            self.urls.append(args[0])\n        else:\n            self.urls.append(UrlEntry(*args, **kwargs))",
    "docstring": "Add a new url to the sitemap.\n\n        This function can either be called with a :class:`UrlEntry`\n        or some keyword and positional arguments that are forwarded to\n        the :class:`UrlEntry` constructor."
  },
  {
    "code": "def restore_grid(func):\n    @wraps(func)\n    def wrapped_func(self, *args, **kwargs):\n        grid = (self.xaxis._gridOnMinor, self.xaxis._gridOnMajor,\n                self.yaxis._gridOnMinor, self.yaxis._gridOnMajor)\n        try:\n            return func(self, *args, **kwargs)\n        finally:\n            self.xaxis.grid(grid[0], which=\"minor\")\n            self.xaxis.grid(grid[1], which=\"major\")\n            self.yaxis.grid(grid[2], which=\"minor\")\n            self.yaxis.grid(grid[3], which=\"major\")\n    return wrapped_func",
    "docstring": "Wrap ``func`` to preserve the Axes current grid settings."
  },
  {
    "code": "def bind_type(type_to_bind: hexdi.core.restype, accessor: hexdi.core.clstype, lifetime_manager: hexdi.core.ltype):\n    hexdi.core.get_root_container().bind_type(type_to_bind, accessor, lifetime_manager)",
    "docstring": "shortcut for bind_type on root container\n\n    :param type_to_bind: type that will be resolved by accessor\n    :param accessor: accessor for resolving object\n    :param lifetime_manager: type of lifetime manager for this binding"
  },
  {
    "code": "def get_station_board(\n        self,\n        crs,\n        rows=17,\n        include_departures=True,\n        include_arrivals=False,\n        destination_crs=None,\n        origin_crs=None\n    ):\n        if include_departures and include_arrivals:\n            query_type = 'GetArrivalDepartureBoard'\n        elif include_departures:\n            query_type = 'GetDepartureBoard'\n        elif include_arrivals:\n            query_type = 'GetArrivalBoard'\n        else:\n            raise ValueError(\n                \"get_station_board must have either include_departures or \\\ninclude_arrivals set to True\"\n            )\n        q = partial(self._base_query()[query_type], crs=crs, numRows=rows)\n        if destination_crs:\n            if origin_crs:\n                log.warn(\n                    \"Station board query can only filter on one of \\\ndestination_crs and origin_crs, using only destination_crs\"\n                )\n            q = partial(q, filterCrs=destination_crs, filterType='to')\n        elif origin_crs:\n            q = partial(q, filterCrs=origin_crs, filterType='from')\n        try:\n            soap_response = q()\n        except WebFault:\n            raise WebServiceError\n        return StationBoard(soap_response)",
    "docstring": "Query the darwin webservice to obtain a board for a particular station\n        and return a StationBoard instance\n\n        Positional arguments:\n        crs -- the three letter CRS code of a UK station\n\n        Keyword arguments:\n        rows -- the number of rows to retrieve (default 10)\n        include_departures -- include departing services in the departure board\n        (default True)\n        include_arrivals -- include arriving services in the departure board\n        (default False)\n        destination_crs -- filter results so they only include services\n        calling at a particular destination (default None)\n        origin_crs -- filter results so they only include services\n        originating from a particular station (default None)"
  },
  {
    "code": "def add_child(self, child):\n        if self.type.lower() != \"directory\":\n            raise ValueError(\"Only directory objects can have children\")\n        if child is self:\n            raise ValueError(\"Cannot be a child of itself!\")\n        if child not in self._children:\n            self._children.append(child)\n        child.parent = self\n        return child",
    "docstring": "Add a child FSEntry to this FSEntry.\n\n        Only FSEntrys with a type of 'directory' can have children.\n\n        This does not detect cyclic parent/child relationships, but that will\n        cause problems.\n\n        :param metsrw.fsentry.FSEntry child: FSEntry to add as a child\n        :return: The newly added child\n        :raises ValueError: If this FSEntry cannot have children.\n        :raises ValueError: If the child and the parent are the same"
  },
  {
    "code": "def recCopyElement(oldelement):\n    newelement = ETREE.Element(oldelement.tag, oldelement.attrib)\n    if len(oldelement.getchildren()) > 0:\n        for childelement in oldelement.getchildren():\n            newelement.append(recCopyElement(childelement))\n    return newelement",
    "docstring": "Generates a copy of an xml element and recursively of all\n    child elements.\n\n    :param oldelement: an instance of lxml.etree._Element\n\n    :returns: a copy of the \"oldelement\"\n\n    .. warning::\n        doesn't copy ``.text`` or ``.tail`` of xml elements"
  },
  {
    "code": "def to_int(self):\n        num = self.to_uint()\n        if num and self._items[-1].unbox():\n            return num - (1 << self.size)\n        else:\n            return num",
    "docstring": "Convert vector to an integer, if possible.\n\n        This is only useful for arrays filled with zero/one entries."
  },
  {
    "code": "def plot_obsseries(self, **kwargs: Any) -> None:\n        self.__plot_series([self.sequences.obs], kwargs)",
    "docstring": "Plot the |IOSequence.series| of the |Obs| sequence object.\n\n        See method |Node.plot_allseries| for further information."
  },
  {
    "code": "def handle_channel_disconnected(self):\n        for namespace in self.app_namespaces:\n            if namespace in self._handlers:\n                self._handlers[namespace].channel_disconnected()\n        self.app_namespaces = []\n        self.destination_id = None\n        self.session_id = None",
    "docstring": "Handles a channel being disconnected."
  },
  {
    "code": "def parse_event(data, attendees=None, photos=None):\n    return MeetupEvent(\n        id=data.get('id', None),\n        name=data.get('name', None),\n        description=data.get('description', None),\n        time=parse_datetime(data.get('time', None),\n                            data.get('utc_offset', None)),\n        status=data.get('status', None),\n        yes_rsvp_count=data.get('yes_rsvp_count', None),\n        maybe_rsvp_count=data.get('maybe_rsvp_count', None),\n        event_url=data.get('event_url', None),\n        photo_url=data.get('photo_url', None),\n        venue=parse_venue(data['venue']) if 'venue' in data else None,\n        attendees=attendees,\n        photos=photos\n    )",
    "docstring": "Parse a ``MeetupEvent`` from the given response data.\n\n    Returns\n    -------\n    A ``pythonkc_meetups.types.MeetupEvent``."
  },
  {
    "code": "def get_definition(self, stmt: Statement,\n                       sctx: SchemaContext) -> Tuple[Statement, SchemaContext]:\n        if stmt.keyword == \"uses\":\n            kw = \"grouping\"\n        elif stmt.keyword == \"type\":\n            kw = \"typedef\"\n        else:\n            raise ValueError(\"not a 'uses' or 'type' statement\")\n        loc, did = self.resolve_pname(stmt.argument, sctx.text_mid)\n        if did == sctx.text_mid:\n            dstmt = stmt.get_definition(loc, kw)\n            if dstmt:\n                return (dstmt, sctx)\n        else:\n            dstmt = self.modules[did].statement.find1(kw, loc)\n            if dstmt:\n                return (dstmt, SchemaContext(sctx.schema_data, sctx.default_ns, did))\n        for sid in self.modules[did].submodules:\n            dstmt = self.modules[sid].statement.find1(kw, loc)\n            if dstmt:\n                return (\n                    dstmt, SchemaContext(sctx.schema_data, sctx.default_ns, sid))\n        raise DefinitionNotFound(kw, stmt.argument)",
    "docstring": "Find the statement defining a grouping or derived type.\n\n        Args:\n            stmt: YANG \"uses\" or \"type\" statement.\n            sctx: Schema context where the definition is used.\n\n        Returns:\n            A tuple consisting of the definition statement ('grouping' or\n            'typedef') and schema context of the definition.\n\n        Raises:\n            ValueError: If `stmt` is neither \"uses\" nor \"type\" statement.\n            ModuleNotRegistered: If `mid` is not registered in the data model.\n            UnknownPrefix: If the prefix specified in the argument of `stmt`\n                is not declared.\n            DefinitionNotFound: If the corresponding definition is not found."
  },
  {
    "code": "def _get_avaliable_tasks(self):\n        base_task = posixpath.join(self._queue_path, self.TASK_PREFIX)\n        tasks = self._client.kv.find(prefix=base_task)\n        return sorted(tasks.items())",
    "docstring": "Get all tasks present in the queue."
  },
  {
    "code": "def get_interleave_mask():\n    nodemask = nodemask_t()\n    bitmask = libnuma.numa_get_interleave_mask()\n    libnuma.copy_bitmask_to_nodemask(bitmask, byref(nodemask))\n    libnuma.numa_bitmask_free(bitmask)\n    return numa_nodemask_to_set(nodemask)",
    "docstring": "Get interleave mask for current thread.\n\n    @return: node mask\n    @rtype: C{set}"
  },
  {
    "code": "def get_event(self):\n        if not self.is_event_message:\n            return None\n        query = self.q().select('subject').expand('event')\n        url = self.build_url(self._endpoints.get('get_message').format(id=self.object_id))\n        response = self.con.get(url, params=query.as_params())\n        if not response:\n            return None\n        data = response.json()\n        event_data = data.get(self._cc('event'))\n        return Event(parent=self, **{self._cloud_data_key: event_data})",
    "docstring": "If this is a EventMessage it should return the related Event"
  },
  {
    "code": "def delete(self):\n        session = self._session\n        url = session._build_url(self._resource_path(), self.id)\n        return session.delete(url, CB.boolean(204))",
    "docstring": "Delete the resource.\n\n        Returns:\n\n          True if the delete is successful. Will throw an error if\n          other errors occur"
  },
  {
    "code": "def generate(env,**kw):\n  import SCons.Util\n  from SCons.Tool.GettextCommon import _detect_msginit\n  try:\n    env['MSGINIT'] = _detect_msginit(env)\n  except:\n    env['MSGINIT'] = 'msginit'\n  msginitcom = '$MSGINIT ${_MSGNoTranslator(__env__)} -l ${_MSGINITLOCALE}' \\\n             + ' $MSGINITFLAGS -i $SOURCE -o $TARGET'\n  env.SetDefault(\n    POSUFFIX = ['.po'],\n    POTSUFFIX = ['.pot'],\n    _MSGINITLOCALE = '${TARGET.filebase}',\n    _MSGNoTranslator = _optional_no_translator_flag,\n    MSGINITCOM = msginitcom,\n    MSGINITCOMSTR = '',\n    MSGINITFLAGS = [ ],\n    POAUTOINIT = False,\n    POCREATE_ALIAS = 'po-create'\n  )\n  env.Append( BUILDERS = { '_POInitBuilder' : _POInitBuilder(env) } )\n  env.AddMethod(_POInitBuilderWrapper, 'POInit')\n  env.AlwaysBuild(env.Alias('$POCREATE_ALIAS'))",
    "docstring": "Generate the `msginit` tool"
  },
  {
    "code": "def scan_results(self):\n        bsses = self._wifi_ctrl.scan_results(self._raw_obj)\n        if self._logger.isEnabledFor(logging.INFO):\n            for bss in bsses:\n                self._logger.info(\"Find bss:\")\n                self._logger.info(\"\\tbssid: %s\", bss.bssid)\n                self._logger.info(\"\\tssid: %s\", bss.ssid)\n                self._logger.info(\"\\tfreq: %d\", bss.freq)\n                self._logger.info(\"\\tauth: %s\", bss.auth)\n                self._logger.info(\"\\takm: %s\", bss.akm)\n                self._logger.info(\"\\tsignal: %d\", bss.signal)\n        return bsses",
    "docstring": "Return the scan result."
  },
  {
    "code": "def getTextualNode(self, subreference=None):\n        if isinstance(subreference, URN):\n            urn = str(subreference)\n        elif isinstance(subreference, CtsReference):\n            urn = \"{0}:{1}\".format(self.urn, str(subreference))\n        elif isinstance(subreference, str):\n            if \":\" in subreference:\n                urn = subreference\n            else:\n                urn = \"{0}:{1}\".format(self.urn.upTo(URN.NO_PASSAGE), subreference)\n        elif isinstance(subreference, list):\n            urn = \"{0}:{1}\".format(self.urn, \".\".join(subreference))\n        else:\n            urn = str(self.urn)\n        response = xmlparser(self.retriever.getPassage(urn=urn))\n        self._parse_request(response.xpath(\"//ti:request\", namespaces=XPATH_NAMESPACES)[0])\n        return CtsPassage(urn=urn, resource=response, retriever=self.retriever)",
    "docstring": "Retrieve a passage and store it in the object\n\n        :param subreference: CtsReference of the passage (Note : if given a list, this should be a list of string that \\\n        compose the reference)\n        :type subreference: Union[CtsReference, URN, str, list]\n        :rtype: CtsPassage\n        :returns: Object representing the passage\n        :raises: *TypeError* when reference is not a list or a CtsReference"
  },
  {
    "code": "def create_config_map(self, name, data):\n        config_data_file = os.path.join(self.os_conf.get_build_json_store(), 'config_map.json')\n        with open(config_data_file) as f:\n            config_data = json.load(f)\n        config_data['metadata']['name'] = name\n        data_dict = {}\n        for key, value in data.items():\n            data_dict[key] = json.dumps(value)\n        config_data['data'] = data_dict\n        response = self.os.create_config_map(config_data)\n        config_map_response = ConfigMapResponse(response.json())\n        return config_map_response",
    "docstring": "Create an ConfigMap object on the server\n\n        Raises exception on error\n\n        :param name: str, name of configMap\n        :param data: dict, dictionary of data to be stored\n        :returns: ConfigMapResponse containing the ConfigMap with name and data"
  },
  {
    "code": "def greedy_mapping(self, reference, hypothesis, uem=None):\n        if uem:\n            reference, hypothesis = self.uemify(reference, hypothesis, uem=uem)\n        return self.mapper_(hypothesis, reference)",
    "docstring": "Greedy label mapping\n\n        Parameters\n        ----------\n        reference : Annotation\n        hypothesis : Annotation\n            Reference and hypothesis diarization\n        uem : Timeline\n            Evaluation map\n\n        Returns\n        -------\n        mapping : dict\n            Mapping between hypothesis (key) and reference (value) labels"
  },
  {
    "code": "def create_ssl_certs(self):\n        for key, file in self.ssl.items():\n            file[\"file\"] = self.create_temp_file(file[\"suffix\"], file[\"content\"])",
    "docstring": "Creates SSL cert files"
  },
  {
    "code": "def lstsq(A, b):\n    r\n    A = asarray(A, float)\n    b = asarray(b, float)\n    if A.ndim == 1:\n        A = A[:, newaxis]\n    if A.shape[1] == 1:\n        return dot(A.T, b) / squeeze(dot(A.T, A))\n    rcond = finfo(double).eps * max(*A.shape)\n    return npy_lstsq(A, b, rcond=rcond)[0]",
    "docstring": "r\"\"\"Return the least-squares solution to a linear matrix equation.\n\n    Args:\n        A (array_like): Coefficient matrix.\n        b (array_like): Ordinate values.\n\n    Returns:\n        :class:`numpy.ndarray`: Least-squares solution."
  },
  {
    "code": "def get_eargs():\n    settings = {}\n    zmq = os.environ.get(\"ZMQ_PREFIX\", None)\n    if zmq is not None:\n        debug(\"Found environ var ZMQ_PREFIX=%s\" % zmq)\n        settings['zmq_prefix'] = zmq\n    return settings",
    "docstring": "Look for options in environment vars"
  },
  {
    "code": "def parse_hosted_zones(self, hosted_zone, params):\n        hosted_zone_id = hosted_zone.pop('Id')\n        hosted_zone['name'] = hosted_zone.pop('Name')\n        api_client = params['api_client']\n        record_sets = handle_truncated_response(api_client.list_resource_record_sets, {'HostedZoneId': hosted_zone_id}, ['ResourceRecordSets'])\n        hosted_zone.update(record_sets)\n        self.hosted_zones[hosted_zone_id] = hosted_zone",
    "docstring": "Parse a single Route53hosted_zoness hosted_zones"
  },
  {
    "code": "def switch_schema(task, kwargs, **kw):\n    from .compat import get_public_schema_name, get_tenant_model\n    old_schema = (connection.schema_name, connection.include_public_schema)\n    setattr(task, '_old_schema', old_schema)\n    schema = (\n        get_schema_name_from_task(task, kwargs) or\n        get_public_schema_name()\n    )\n    if connection.schema_name == schema:\n        return\n    if connection.schema_name != get_public_schema_name():\n        connection.set_schema_to_public()\n    if schema == get_public_schema_name():\n        return\n    tenant = get_tenant_model().objects.get(schema_name=schema)\n    connection.set_tenant(tenant, include_public=True)",
    "docstring": "Switches schema of the task, before it has been run."
  },
  {
    "code": "def _fetch_channels(self):\n        json = requests.get(self._channels_url).json()\n        self._channels = {c['channel']['code']: c['channel']['name']\n                          for c in json['channels']}",
    "docstring": "Retrieve Ziggo channel information."
  },
  {
    "code": "def create_organizations_parser(stream):\n    import sortinghat.parsing as parsing\n    for p in parsing.SORTINGHAT_ORGS_PARSERS:\n        klass = parsing.SORTINGHAT_ORGS_PARSERS[p]\n        parser = klass()\n        if parser.check(stream):\n            return parser\n    raise InvalidFormatError(cause=INVALID_FORMAT_MSG)",
    "docstring": "Create an organizations parser for the given stream.\n\n    Factory function that creates an organizations parser for the\n    given stream. The stream is only used to guess the type of the\n    required parser.\n\n    :param stream: stream used to guess the type of the parser\n\n    :returns: an organizations parser\n\n    :raise InvalidFormatError: raised when no one of the available\n        parsers can parse the given stream"
  },
  {
    "code": "def get_parent(self, level=1):\n        try:\n            parent_path = self.path.get_parent(level)\n        except ValueError:\n            return None\n        assert parent_path\n        return DirectoryInfo(parent_path)",
    "docstring": "get parent dir as a `DirectoryInfo`.\n\n        return `None` if self is top."
  },
  {
    "code": "def clean(self):\n        for _, item in self.queue.items():\n            if item['status'] in ['paused', 'running', 'stopping', 'killing']:\n                item['status'] = 'queued'\n                item['start'] = ''\n                item['end'] = ''",
    "docstring": "Clean queue items from a previous session.\n\n        In case a previous session crashed and there are still some running\n        entries in the queue ('running', 'stopping', 'killing'), we clean those\n        and enqueue them again."
  },
  {
    "code": "def _deposit_payload(to_deposit):\n    pubsub = to_deposit['pubsub']\n    id = to_deposit['id']\n    with r_client.pipeline() as pipe:\n        pipe.set(id, json.dumps(to_deposit), ex=REDIS_KEY_TIMEOUT)\n        pipe.publish(pubsub, json.dumps({\"update\": [id]}))\n        pipe.execute()",
    "docstring": "Store job info, and publish an update\n\n    Parameters\n    ----------\n    to_deposit : dict\n        The job info"
  },
  {
    "code": "def get_fitness(self, solution):\n        return self._fitness_function(solution, *self._fitness_args,\n                                      **self._fitness_kwargs)",
    "docstring": "Return fitness for the given solution."
  },
  {
    "code": "def metabolites_per_compartment(model, compartment_id):\n    return [met for met in model.metabolites\n            if met.compartment == compartment_id]",
    "docstring": "Identify all metabolites that belong to a given compartment.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model under investigation.\n    compartment_id : string\n        Model specific compartment identifier.\n\n    Returns\n    -------\n    list\n        List of metabolites belonging to a given compartment."
  },
  {
    "code": "def get_each_choice(self, cls=None, **kwargs):\n        defaults = {attr: kwargs[attr][0] for attr in kwargs}\n        for set_of_values in izip_longest(*kwargs.values()):\n            case = cls() if cls else self._CasesClass()\n            for attr, value in izip(kwargs.keys(), set_of_values):\n                if value is None:\n                    value = defaults[attr]\n                setattr(case, attr, value)\n            yield case",
    "docstring": "Returns a generator that generates positive cases by\n        \"each choice\" algorithm."
  },
  {
    "code": "def clear(self):\n        super(SuperChange, self).clear()\n        for c in self.changes:\n            c.clear()\n        self.changes = tuple()",
    "docstring": "clears all child changes and drops the reference to them"
  },
  {
    "code": "def split_code(cls, code, PS1, PS2):\n        processed_lines = []\n        for line in textwrap.dedent(code).splitlines():\n            if not line or line.startswith(PS1) or line.startswith(PS2):\n                processed_lines.append(line)\n                continue\n            assert len(processed_lines) > 0, 'code improperly formatted: {}'.format(code)\n            if not isinstance(processed_lines[-1], CodeAnswer):\n                processed_lines.append(CodeAnswer())\n            processed_lines[-1].update(line)\n        return processed_lines",
    "docstring": "Splits the given string of code based on the provided PS1 and PS2\n        symbols.\n\n        PARAMETERS:\n        code -- str; lines of interpretable code, using PS1 and PS2 prompts\n        PS1  -- str; first-level prompt symbol\n        PS2  -- str; second-level prompt symbol\n\n        RETURN:\n        list; a processed sequence of lines corresponding to the input code."
  },
  {
    "code": "def _set_env(self, env):\n        for callback in self.callbacks:\n            if callable(getattr(callback, '_set_env', None)):\n                callback._set_env(env)",
    "docstring": "Set environment for each callback in callbackList"
  },
  {
    "code": "def color_diffs(string):\n    string = string.replace('--- ', color('--- ', 'red'))\n    string = string.replace('\\n+++ ', color('\\n+++ '))\n    string = string.replace('\\n-', color('\\n-', 'red'))\n    string = string.replace('\\n+', color('\\n+'))\n    string = string.replace('\\n@@ ', color('\\n@@ ', 'yel'))\n    return string",
    "docstring": "Add color ANSI codes for diff lines.\n\n    Purpose: Adds the ANSI/win32 color coding for terminal output to output\n           | produced from difflib.\n\n    @param string: The string to be replacing\n    @type string: str\n\n    @returns: The new string with ANSI codes injected.\n    @rtype: str"
  },
  {
    "code": "def is_duplicate_edge(data, data_other):\n    is_dupe = False\n    osmid = set(data['osmid']) if isinstance(data['osmid'], list) else data['osmid']\n    osmid_other = set(data_other['osmid']) if isinstance(data_other['osmid'], list) else data_other['osmid']\n    if osmid == osmid_other:\n        if ('geometry' in data) and ('geometry' in data_other):\n            if is_same_geometry(data['geometry'], data_other['geometry']):\n                is_dupe = True\n        elif ('geometry' in data) and ('geometry' in data_other):\n            is_dupe = True\n        else:\n            pass\n    return is_dupe",
    "docstring": "Check if two edge data dictionaries are the same based on OSM ID and\n    geometry.\n\n    Parameters\n    ----------\n    data : dict\n        the first edge's data\n    data_other : dict\n        the second edge's data\n\n    Returns\n    -------\n    is_dupe : bool"
  },
  {
    "code": "def get_user_matches(session, user_id, from_timestamp=None, limit=None):\n    return get_recent_matches(session, '{}{}/{}/Matches/games/matches/user/{}/0'.format(\n        session.auth.base_url, PROFILE_URL, user_id, user_id), from_timestamp, limit)",
    "docstring": "Get recent matches by user."
  },
  {
    "code": "def compile_output(self, input_sample, num_samples, num_params,\n                       maximum_combo, num_groups=None):\n        if num_groups is None:\n            num_groups = num_params\n        self.check_input_sample(input_sample, num_groups, num_samples)\n        index_list = self._make_index_list(num_samples, num_params, num_groups)\n        output = np.zeros(\n            (np.size(maximum_combo) * (num_groups + 1), num_params))\n        for counter, combo in enumerate(maximum_combo):\n            output[index_list[counter]] = np.array(\n                input_sample[index_list[combo]])\n        return output",
    "docstring": "Picks the trajectories from the input\n\n        Arguments\n        ---------\n        input_sample : numpy.ndarray\n        num_samples : int\n        num_params : int\n        maximum_combo : list\n        num_groups : int"
  },
  {
    "code": "def request_error_header(exception):\n    from .conf import options\n    header = \"Bearer realm=\\\"%s\\\"\" % (options.realm, )\n    if hasattr(exception, \"error\"):\n        header = header + \", error=\\\"%s\\\"\" % (exception.error, )\n    if hasattr(exception, \"reason\"):\n        header = header + \", error_description=\\\"%s\\\"\" % (exception.reason, )\n    return header",
    "docstring": "Generates the error header for a request using a Bearer token based on a given OAuth exception."
  },
  {
    "code": "def _get_kvc(kv_arg):\n    if isinstance(kv_arg, Mapping):\n        return six.iterkeys(kv_arg), six.itervalues(kv_arg), len(kv_arg)\n    assert 2 <= len(kv_arg) <= 3, \\\n        'Argument must be a mapping or a sequence (keys, values, [len])'\n    return (\n        kv_arg[0],\n        kv_arg[1],\n        kv_arg[2] if len(kv_arg) == 3 else len(kv_arg[0]))",
    "docstring": "Returns a tuple keys, values, count for kv_arg (which can be a dict or a\n        tuple containing keys, values and optinally count."
  },
  {
    "code": "def decode_pdf_date(s: str) -> datetime:\n    if isinstance(s, String):\n        s = str(s)\n    if s.startswith('D:'):\n        s = s[2:]\n    if s.endswith(\"Z00'00'\"):\n        s = s.replace(\"Z00'00'\", '+0000')\n    elif s.endswith('Z'):\n        s = s.replace('Z', '+0000')\n    s = s.replace(\"'\", \"\")\n    try:\n        return datetime.strptime(s, r'%Y%m%d%H%M%S%z')\n    except ValueError:\n        return datetime.strptime(s, r'%Y%m%d%H%M%S')",
    "docstring": "Decode a pdfmark date to a Python datetime object\n\n    A pdfmark date is a string in a paritcular format. See the pdfmark\n    Reference for the specification."
  },
  {
    "code": "def chown(self, uid=-1, gid=-1):\n        if hasattr(os, 'chown'):\n            if 'pwd' in globals() and isinstance(uid, str):\n                uid = pwd.getpwnam(uid).pw_uid\n            if 'grp' in globals() and isinstance(gid, str):\n                gid = grp.getgrnam(gid).gr_gid\n            os.chown(self, uid, gid)\n        else:\n            msg = \"Ownership not available on this platform.\"\n            raise NotImplementedError(msg)\n        return self",
    "docstring": "Change the owner and group by names rather than the uid or gid numbers.\n\n        .. seealso:: :func:`os.chown`"
  },
  {
    "code": "def _check_existing_logger(loggername, short_name):\n    if loggername in LOGGERS:\n        if isinstance(LOGGERS[loggername], BenchLoggerAdapter):\n            if (\"source\" not in LOGGERS[loggername].extra or\n                    LOGGERS[loggername].extra[\"source\"] != short_name):\n                LOGGERS[loggername].extra[\"source\"] = short_name\n        return LOGGERS[loggername]\n    return None",
    "docstring": "Check if logger with name loggername exists.\n\n    :param loggername: Name of logger.\n    :param short_name: Shortened name for the logger.\n    :return: Logger or None"
  },
  {
    "code": "def get_client_key_exchange_record(\n            cls,\n            robot_payload_enum: RobotPmsPaddingPayloadEnum,\n            tls_version: TlsVersionEnum,\n            modulus: int,\n            exponent: int\n    ) -> TlsRsaClientKeyExchangeRecord:\n        pms_padding = cls._compute_pms_padding(modulus)\n        tls_version_hex = binascii.b2a_hex(TlsRecordTlsVersionBytes[tls_version.name].value).decode('ascii')\n        pms_with_padding_payload = cls._CKE_PAYLOADS_HEX[robot_payload_enum]\n        final_pms = pms_with_padding_payload.format(\n            pms_padding=pms_padding, tls_version=tls_version_hex, pms=cls._PMS_HEX\n        )\n        cke_robot_record = TlsRsaClientKeyExchangeRecord.from_parameters(\n            tls_version, exponent, modulus, int(final_pms, 16)\n        )\n        return cke_robot_record",
    "docstring": "A client key exchange record with a hardcoded pre_master_secret, and a valid or invalid padding."
  },
  {
    "code": "def format(self, fmt):\n        _fmt_params = {\n            'base': self.base,\n            'bin': self.bin,\n            'binary': self.binary,\n            'bits': self.bits,\n            'bytes': self.bytes,\n            'power': self.power,\n            'system': self.system,\n            'unit': self.unit,\n            'unit_plural': self.unit_plural,\n            'unit_singular': self.unit_singular,\n            'value': self.value\n        }\n        return fmt.format(**_fmt_params)",
    "docstring": "Return a representation of this instance formatted with user\nsupplied syntax"
  },
  {
    "code": "def _resolve_method(self, request):\n        try:\n            return getattr(requests, request.method.lower())\n        except AttributeError:\n            raise ApiClientException(\n                \"Invalid request method: {}\".format(request.method))",
    "docstring": "Resolve the method from request object to `requests` http\n        call.\n\n        :param request: Request to dispatch to the ApiClient\n        :type request: ApiClientRequest\n        :return: The HTTP method that maps to the request call.\n        :rtype: Callable\n        :raises :py:class:`ask_sdk_core.exceptions.ApiClientException`\n            if invalid http request method is being called"
  },
  {
    "code": "async def handle(self, record):\n        if (not self.disabled) and self.filter(record):\n            await self.callHandlers(record)",
    "docstring": "Call the handlers for the specified record.\n\n        This method is used for unpickled records received from a socket, as\n        well as those created locally. Logger-level filtering is applied."
  },
  {
    "code": "def load_devices(self):\n        self._devices = []\n        if os.path.exists(self._devices_filename):\n            log.debug(\n                \"loading devices from '{}'...\".format(self._devices_filename)\n            )\n            with codecs.open(self._devices_filename, \"rb\", \"utf-8\") as f:\n                self._devices = json.load(f)\n        return self._devices",
    "docstring": "load stored devices from the local file"
  },
  {
    "code": "def get_cam_bounds(self):\n        world_pos = self.get_world_pos()\n        screen_res = Ragnarok.get_world().get_backbuffer_size() * .5\n        return (self.pan.X - screen_res.X), (self.pan.Y - screen_res.Y), (self.pan.X + screen_res.X), (\n                self.pan.Y + screen_res.Y)",
    "docstring": "Return the bounds of the camera in x, y, xMax, and yMax format."
  },
  {
    "code": "def _empty_cache(self, termlist=None):\n        if termlist is None:\n            for term in six.itervalues(self.terms):\n                term._empty_cache()\n        else:\n            for term in termlist:\n                try:\n                    self.terms[term.id]._empty_cache()\n                except AttributeError:\n                    self.terms[term]._empty_cache()",
    "docstring": "Empty the cache associated with each `Term` instance.\n\n        This method is called when merging Ontologies or including\n        new terms in the Ontology to make sure the cache of each\n        term is cleaned and avoid returning wrong memoized values\n        (such as Term.rchildren() TermLists, which get memoized for\n        performance concerns)"
  },
  {
    "code": "def findExtname(fimg, extname, extver=None):\n    i = 0\n    extnum = None\n    for chip in fimg:\n        hdr = chip.header\n        if 'EXTNAME' in hdr:\n            if hdr['EXTNAME'].strip() == extname.upper():\n                if extver is None or hdr['EXTVER'] == extver:\n                    extnum = i\n                    break\n        i += 1\n    return extnum",
    "docstring": "Returns the list number of the extension corresponding to EXTNAME given."
  },
  {
    "code": "def set_param(self, key, value):\n        self.__dict__[key] = value\n        self._parameters[key] = value",
    "docstring": "Set the value of a parameter."
  },
  {
    "code": "def setLog(self, fileName, writeName=False):\n        self.log = 1\n        self.logFile = fileName\n        self._logPtr = open(fileName, \"w\")\n        if writeName:\n            self._namePtr = open(fileName + \".name\", \"w\")",
    "docstring": "Opens a log file with name fileName."
  },
  {
    "code": "def paragraphs(self, index = None):\n        if index is None:\n            return self.select(Paragraph)\n        else:\n            if index < 0:\n                index = sum(t.count(Paragraph) for t in self.data) + index\n            for t in self.data:\n                for i,e in enumerate(t.select(Paragraph)) :\n                    if i == index:\n                        return e\n            raise IndexError",
    "docstring": "Return a generator of all paragraphs found in the document.\n\n        If an index is specified, return the n'th paragraph only (starting at 0)"
  },
  {
    "code": "def add(self, event, pk, ts=None, ttl=None):\n        key = self._keygen(event, ts)\n        try:\n            self._zadd(key, pk, ts, ttl)\n            return True\n        except redis.ConnectionError as e:\n            self.logger.error(\n                \"redis event store failed with connection error %r\" % e)\n            return False",
    "docstring": "Add an event to event store.\n\n        All events were stored in a sorted set in redis with timestamp as\n        rank  score.\n\n        :param event: the event to be added, format should be ``table_action``\n        :param pk: the primary key of event\n        :param ts: timestamp of the event, default to redis_server's\n         current timestamp\n        :param ttl: the expiration time of event since the last update\n        :return: bool"
  },
  {
    "code": "def QA_SU_save_stock_info(engine, client=DATABASE):\n    engine = select_save_engine(engine)\n    engine.QA_SU_save_stock_info(client=client)",
    "docstring": "save stock info\n\n    Arguments:\n        engine {[type]} -- [description]\n\n    Keyword Arguments:\n        client {[type]} -- [description] (default: {DATABASE})"
  },
  {
    "code": "def _get_last_entries(db, qty):\n    doc_ids = [post.doc_id for post in db.posts.all()]\n    doc_ids = sorted(doc_ids, reverse=True)\n    entries = [Entry(os.path.join(CONFIG['content_root'],\n                     db.posts.get(doc_id=doc_id)['filename']), doc_id)\n               for doc_id in doc_ids]\n    entries.sort(key=operator.attrgetter('date'), reverse=True)\n    return entries[:qty], entries",
    "docstring": "get all entries and the last qty entries"
  },
  {
    "code": "def create(self):\n        self.consul.create_bucket(\"%s-%s\" % (self.stack.name, self.name))",
    "docstring": "Creates a new bucket"
  },
  {
    "code": "def _declarations_as_string(self, declarations):\n        return ''.join('%s:%s%s;' % (\n            d.name,\n            d.value.as_css(),\n            ' !' + d.priority if d.priority else '') for d in declarations)",
    "docstring": "Returns a list of declarations as a formatted CSS string\n\n        :param declarations: The list of tinycss Declarations to format\n        :type declarations: list of tinycss.css21.Declaration\n        :returns: The CSS string for the declarations list\n        :rtype: str"
  },
  {
    "code": "def send_feature_report(self, data, report_id=0x0):\n        self._check_device_status()\n        bufp = ffi.new(\"unsigned char[]\", len(data)+1)\n        buf = ffi.buffer(bufp, len(data)+1)\n        buf[0] = report_id\n        buf[1:] = data\n        rv = hidapi.hid_send_feature_report(self._device, bufp, len(bufp))\n        if rv == -1:\n            raise IOError(\"Failed to send feature report to HID device: {0}\"\n                          .format(self._get_last_error_string()))",
    "docstring": "Send a Feature report to the device.\n\n        Feature reports are sent over the Control endpoint as a Set_Report\n        transfer.\n\n        :param data:        The data to send\n        :type data:         str/bytes\n        :param report_id:   The Report ID to send to\n        :type report_id:    int"
  },
  {
    "code": "def add_prefix(self, name, *args, **kwargs):\n        if os.path.exists(self.join(name)):\n            raise LagoPrefixAlreadyExistsError(name, self.path)\n        self.prefixes[name] = self.prefix_class(\n            self.join(name), *args, **kwargs\n        )\n        self.prefixes[name].initialize()\n        if self.current is None:\n            self.set_current(name)\n        return self.prefixes[name]",
    "docstring": "Adds a new prefix to the workdir.\n\n        Args:\n            name(str): Name of the new prefix to add\n            *args: args to pass along to the prefix constructor\n            *kwargs: kwargs to pass along to the prefix constructor\n\n        Returns:\n            The newly created prefix\n\n        Raises:\n            LagoPrefixAlreadyExistsError: if prefix name already exists in the\n            workdir"
  },
  {
    "code": "def code(item):\n    _res = []\n    i = 0\n    for attr in ATTR:\n        val = getattr(item, attr)\n        if val:\n            _res.append(\"%d=%s\" % (i, quote(val)))\n        i += 1\n    return \",\".join(_res)",
    "docstring": "Turn a NameID class instance into a quoted string of comma separated\n    attribute,value pairs. The attribute names are replaced with digits.\n    Depends on knowledge on the specific order of the attributes for the\n    class that is used.\n\n    :param item: The class instance\n    :return: A quoted string"
  },
  {
    "code": "def calc_smoothpar_logistic2(metapar):\n    if metapar <= 0.:\n        return 0.\n    return optimize.newton(_error_smoothpar_logistic2,\n                           .3 * metapar**.84,\n                           _smooth_logistic2_derivative,\n                           args=(metapar,))",
    "docstring": "Return the smoothing parameter corresponding to the given meta\n    parameter when using |smooth_logistic2|.\n\n    Calculate the smoothing parameter value corresponding the meta parameter\n    value 2.5:\n\n    >>> from hydpy.auxs.smoothtools import calc_smoothpar_logistic2\n    >>> smoothpar = calc_smoothpar_logistic2(2.5)\n\n    Using this smoothing parameter value, the output of function\n    |smooth_logistic2| differs by\n    1 % from the related `true` discontinuous step function for the\n    input values -2.5 and 2.5 (which are located at a distance of 2.5\n    from the position of the discontinuity):\n\n    >>> from hydpy.cythons import smoothutils\n    >>> from hydpy import round_\n    >>> round_(smoothutils.smooth_logistic2(-2.5, smoothpar))\n    0.01\n    >>> round_(smoothutils.smooth_logistic2(2.5, smoothpar))\n    2.51\n\n    For zero or negative meta parameter values, a zero smoothing parameter\n    value is returned:\n\n    >>> round_(calc_smoothpar_logistic2(0.0))\n    0.0\n    >>> round_(calc_smoothpar_logistic2(-1.0))\n    0.0"
  },
  {
    "code": "def on_click(self, button, **kwargs):\n        if button in (4, 5):\n            return super().on_click(button, **kwargs)\n        else:\n            activemodule = self.get_active_module()\n            if not activemodule:\n                return\n            return activemodule.on_click(button, **kwargs)",
    "docstring": "Capture scrollup and scorlldown to move in groups\n        Pass everthing else to the module itself"
  },
  {
    "code": "def nonzero(self):\n        return [i for i in xrange(self.size()) if self.test(i)]",
    "docstring": "Get all non-zero bits"
  },
  {
    "code": "def filter(self, filter_fn):\n        op = Operator(\n            _generate_uuid(),\n            OpType.Filter,\n            \"Filter\",\n            filter_fn,\n            num_instances=self.env.config.parallelism)\n        return self.__register(op)",
    "docstring": "Applies a filter to the stream.\n\n        Attributes:\n             filter_fn (function): The user-defined filter function."
  },
  {
    "code": "def repeat(self, rid, count, index=0):\n        elems = None\n        if rid in self.__repeat_ids:\n            elems = self.__repeat_ids[rid]\n        elif rid in self.__element_ids:\n            elems = self.__element_ids\n        if elems and index < len(elems):\n            elem = elems[index]\n            self.__repeat(elem, count)",
    "docstring": "Repeat an xml element marked with the matching rid."
  },
  {
    "code": "def is_probably_packed( pe ):\n    total_pe_data_length = len( pe.trim() )\n    if not total_pe_data_length:\n        return True\n    has_significant_amount_of_compressed_data = False\n    total_compressed_data = 0\n    for section in pe.sections:\n        s_entropy = section.get_entropy()\n        s_length = len( section.get_data() )\n        if s_entropy > 7.4:\n            total_compressed_data += s_length\n    if ((1.0 * total_compressed_data)/total_pe_data_length) > .2:\n        has_significant_amount_of_compressed_data = True\n    return has_significant_amount_of_compressed_data",
    "docstring": "Returns True is there is a high likelihood that a file is packed or contains compressed data.\n\n    The sections of the PE file will be analyzed, if enough sections\n    look like containing compressed data and the data makes\n    up for more than 20% of the total file size, the function will\n    return True."
  },
  {
    "code": "def is_elaborated(type_):\n    nake_type = remove_alias(type_)\n    if isinstance(nake_type, cpptypes.elaborated_t):\n        return True\n    elif isinstance(nake_type, cpptypes.reference_t):\n        return is_elaborated(nake_type.base)\n    elif isinstance(nake_type, cpptypes.pointer_t):\n        return is_elaborated(nake_type.base)\n    elif isinstance(nake_type, cpptypes.volatile_t):\n        return is_elaborated(nake_type.base)\n    elif isinstance(nake_type, cpptypes.const_t):\n        return is_elaborated(nake_type.base)\n    return False",
    "docstring": "returns True, if type represents C++ elaborated type, False otherwise"
  },
  {
    "code": "def create_async_dynamodb_table(self, table_name, read_capacity, write_capacity):\n        try:\n            dynamodb_table = self.dynamodb_client.describe_table(TableName=table_name)\n            return False, dynamodb_table\n        except botocore.exceptions.ClientError:\n            dynamodb_table = self.dynamodb_client.create_table(\n                AttributeDefinitions=[\n                    {\n                        'AttributeName': 'id',\n                        'AttributeType': 'S'\n                    }\n                ],\n                TableName=table_name,\n                KeySchema=[\n                    {\n                        'AttributeName': 'id',\n                        'KeyType': 'HASH'\n                    },\n                ],\n                ProvisionedThroughput = {\n                    'ReadCapacityUnits': read_capacity,\n                    'WriteCapacityUnits': write_capacity\n                }\n            )\n            if dynamodb_table:\n                try:\n                    self._set_async_dynamodb_table_ttl(table_name)\n                except botocore.exceptions.ClientError:\n                    time.sleep(10)\n                    self._set_async_dynamodb_table_ttl(table_name)\n        return True, dynamodb_table",
    "docstring": "Create the DynamoDB table for async task return values"
  },
  {
    "code": "def on_transmit(self, broker):\n        _vv and IOLOG.debug('%r.on_transmit()', self)\n        if self._output_buf:\n            buf = self._output_buf.popleft()\n            written = self.transmit_side.write(buf)\n            if not written:\n                _v and LOG.debug('%r.on_transmit(): disconnection detected', self)\n                self.on_disconnect(broker)\n                return\n            elif written != len(buf):\n                self._output_buf.appendleft(BufferType(buf, written))\n            _vv and IOLOG.debug('%r.on_transmit() -> len %d', self, written)\n            self._output_buf_len -= written\n        if not self._output_buf:\n            broker._stop_transmit(self)",
    "docstring": "Transmit buffered messages."
  },
  {
    "code": "def set_position(self, position):\n        if position < 0:\n            position += len(self.checkdefs)\n        while position >= len(self.checkdefs):\n            self.checkdefs.append(([], []))\n        self.position = position",
    "docstring": "Sets the if-statement position."
  },
  {
    "code": "def compute_output(t0, t1):\n    if t0 is None or t1 is None:\n        return -1.0\n    else:\n        response = 1.1 - 0.1 * abs(t0 - t1)\n        return max(0.0, min(1.0, response))",
    "docstring": "Compute the network's output based on the \"time to first spike\" of the two output neurons."
  },
  {
    "code": "def _load(self, dataset_spec):\n        for idx, ds in enumerate(dataset_spec):\n            self.append(ds, idx)",
    "docstring": "Actual loading of datasets"
  },
  {
    "code": "def param_request_list_send(self, target_system, target_component, force_mavlink1=False):\n                return self.send(self.param_request_list_encode(target_system, target_component), force_mavlink1=force_mavlink1)",
    "docstring": "Request all parameters of this component. After this request, all\n                parameters are emitted.\n\n                target_system             : System ID (uint8_t)\n                target_component          : Component ID (uint8_t)"
  },
  {
    "code": "def _set_random_data(self):\n        rdata = self._load_response('random')\n        rdata = rdata['query']['random'][0]\n        pageid = rdata.get('id')\n        title = rdata.get('title')\n        self.data.update({'pageid': pageid,\n                          'title': title})",
    "docstring": "sets page data from random request"
  },
  {
    "code": "def transform(self):\n        ax = self.ax\n        return {'axes': ax.transAxes,\n                'fig': ax.get_figure().transFigure,\n                'data': ax.transData}",
    "docstring": "Dictionary containing the relevant transformations"
  },
  {
    "code": "def enable_parallel(processnum=None):\n    global pool, dt, cut, cut_for_search\n    from multiprocessing import cpu_count\n    if os.name == 'nt':\n        raise NotImplementedError(\n            \"jieba: parallel mode only supports posix system\")\n    else:\n        from multiprocessing import Pool\n    dt.check_initialized()\n    if processnum is None:\n        processnum = cpu_count()\n    pool = Pool(processnum)\n    cut = _pcut\n    cut_for_search = _pcut_for_search",
    "docstring": "Change the module's `cut` and `cut_for_search` functions to the\n    parallel version.\n\n    Note that this only works using dt, custom Tokenizer\n    instances are not supported."
  },
  {
    "code": "def _ensure_value_is_in_objects(self,val):\n        if not (val in self.objects):\n           self.objects.append(val)",
    "docstring": "Make sure that the provided value is present on the objects list.\n        Subclasses can override if they support multiple items on a list,\n        to check each item instead."
  },
  {
    "code": "def operate_multi(self, points):\n        points = np.array(points)\n        affine_points = np.concatenate(\n            [points, np.ones(points.shape[:-1] + (1,))], axis=-1)\n        return np.inner(affine_points, self.affine_matrix)[..., :-1]",
    "docstring": "Apply the operation on a list of points.\n\n        Args:\n            points: List of Cartesian coordinates\n\n        Returns:\n            Numpy array of coordinates after operation"
  },
  {
    "code": "def AddPerformanceOptions(self, argument_group):\n    argument_group.add_argument(\n        '--buffer_size', '--buffer-size', '--bs', dest='buffer_size',\n        action='store', default=0, help=(\n            'The buffer size for the output (defaults to 196MiB).'))\n    argument_group.add_argument(\n        '--queue_size', '--queue-size', dest='queue_size', action='store',\n        default=0, help=(\n            'The maximum number of queued items per worker '\n            '(defaults to {0:d})').format(self._DEFAULT_QUEUE_SIZE))",
    "docstring": "Adds the performance options to the argument group.\n\n    Args:\n      argument_group (argparse._ArgumentGroup): argparse argument group."
  },
  {
    "code": "def check_1d(inp):\n    if isinstance(inp, list):\n        return check_1d(np.array(inp))\n    if isinstance(inp, np.ndarray):\n        if inp.ndim == 1:\n            return inp",
    "docstring": "Check input to be a vector. Converts lists to np.ndarray.\n\n    Parameters\n    ----------\n    inp : obj\n        Input vector\n\n    Returns\n    -------\n    numpy.ndarray or None\n        Input vector or None\n\n    Examples\n    --------\n    >>> check_1d([0, 1, 2, 3])\n    [0, 1, 2, 3]\n\n    >>> check_1d('test')\n    None"
  },
  {
    "code": "def Convert(self, metadata, config, token=None):\n    result = ExportedDNSClientConfiguration(\n        metadata=metadata,\n        dns_servers=\" \".join(config.dns_server),\n        dns_suffixes=\" \".join(config.dns_suffix))\n    yield result",
    "docstring": "Converts DNSClientConfiguration to ExportedDNSClientConfiguration."
  },
  {
    "code": "def delete_file(f):\n    fp = f.get_fullpath()\n    log.info(\"Deleting file %s\", fp)\n    os.remove(fp)",
    "docstring": "Delete the given file\n\n    :param f: the file to delete\n    :type f: :class:`JB_File`\n    :returns: None\n    :rtype: None\n    :raises: :class:`OSError`"
  },
  {
    "code": "def boundary_cell_fractions(self):\n        frac_list = []\n        for ax, (cvec, bmin, bmax) in enumerate(zip(\n                self.grid.coord_vectors, self.set.min_pt, self.set.max_pt)):\n            if len(cvec) == 1:\n                frac_list.append((1.0, 1.0))\n            else:\n                left_frac = 0.5 + (cvec[0] - bmin) / (cvec[1] - cvec[0])\n                right_frac = 0.5 + (bmax - cvec[-1]) / (cvec[-1] - cvec[-2])\n                frac_list.append((left_frac, right_frac))\n        return tuple(frac_list)",
    "docstring": "Return a tuple of contained fractions of boundary cells.\n\n        Since the outermost grid points can have any distance to the\n        boundary of the partitioned set, the \"natural\" outermost cell\n        around these points can either be cropped or extended. This\n        property is a tuple of (float, float) tuples, one entry per\n        dimension, where the fractions of the left- and rightmost\n        cells inside the set are stored. If a grid point lies exactly\n        on the boundary, the value is 1/2 since the cell is cut in half.\n        Otherwise, any value larger than 1/2 is possible.\n\n        Returns\n        -------\n        on_bdry : tuple of 2-tuples of floats\n            Each 2-tuple contains the fraction of the leftmost\n            (first entry) and rightmost (second entry) cell in the\n            partitioned set in the corresponding dimension.\n\n        See Also\n        --------\n        cell_boundary_vecs\n\n        Examples\n        --------\n        We create a partition of the rectangle [0, 1.5] x [-2, 2] with\n        the grid points [0, 1] x [-1, 0, 2]. The \"natural\" cells at the\n        boundary would be:\n\n            [-0.5, 0.5] and [0.5, 1.5] in the first axis\n\n            [-1.5, -0.5] and [1, 3] in the second axis\n\n        Thus, in the first axis, the fractions contained in [0, 1.5]\n        are 0.5 and 1, and in the second axis, [-2, 2] contains the\n        fractions 1.5 and 0.5.\n\n        >>> rect = odl.IntervalProd([0, -2], [1.5, 2])\n        >>> grid = odl.RectGrid([0, 1], [-1, 0, 2])\n        >>> part = odl.RectPartition(rect, grid)\n        >>> part.boundary_cell_fractions\n        ((0.5, 1.0), (1.5, 0.5))"
  },
  {
    "code": "def need_record_permission(factory_name):\n    def need_record_permission_builder(f):\n        @wraps(f)\n        def need_record_permission_decorator(self, record=None, *args,\n                                             **kwargs):\n            permission_factory = (\n                getattr(self, factory_name) or\n                getattr(current_records_rest, factory_name)\n            )\n            request._methodview = self\n            if permission_factory:\n                verify_record_permission(permission_factory, record)\n            return f(self, record=record, *args, **kwargs)\n        return need_record_permission_decorator\n    return need_record_permission_builder",
    "docstring": "Decorator checking that the user has the required permissions on record.\n\n    :param factory_name: name of the permission factory."
  },
  {
    "code": "def get_all(self, references, field_paths=None, transaction=None):\n        document_paths, reference_map = _reference_info(references)\n        mask = _get_doc_mask(field_paths)\n        response_iterator = self._firestore_api.batch_get_documents(\n            self._database_string,\n            document_paths,\n            mask,\n            transaction=_helpers.get_transaction_id(transaction),\n            metadata=self._rpc_metadata,\n        )\n        for get_doc_response in response_iterator:\n            yield _parse_batch_get(get_doc_response, reference_map, self)",
    "docstring": "Retrieve a batch of documents.\n\n        .. note::\n\n           Documents returned by this method are not guaranteed to be\n           returned in the same order that they are given in ``references``.\n\n        .. note::\n\n           If multiple ``references`` refer to the same document, the server\n           will only return one result.\n\n        See :meth:`~.firestore_v1beta1.client.Client.field_path` for\n        more information on **field paths**.\n\n        If a ``transaction`` is used and it already has write operations\n        added, this method cannot be used (i.e. read-after-write is not\n        allowed).\n\n        Args:\n            references (List[.DocumentReference, ...]): Iterable of document\n                references to be retrieved.\n            field_paths (Optional[Iterable[str, ...]]): An iterable of field\n                paths (``.``-delimited list of field names) to use as a\n                projection of document fields in the returned results. If\n                no value is provided, all fields will be returned.\n            transaction (Optional[~.firestore_v1beta1.transaction.\\\n                Transaction]): An existing transaction that these\n                ``references`` will be retrieved in.\n\n        Yields:\n            .DocumentSnapshot: The next document snapshot that fulfills the\n            query, or :data:`None` if the document does not exist."
  },
  {
    "code": "def load_key(self, key):\n        self._serialize(key)\n        if isinstance(key, ec.EllipticCurvePrivateKey):\n            self.priv_key = key\n            self.pub_key = key.public_key()\n        else:\n            self.pub_key = key\n        return self",
    "docstring": "Load an Elliptic curve key\n\n        :param key: An elliptic curve key instance, private or public.\n        :return: Reference to this instance"
  },
  {
    "code": "def is_distributed(partition_column, lower_bound, upper_bound):\n    if (\n        (partition_column is not None)\n        and (lower_bound is not None)\n        and (upper_bound is not None)\n    ):\n        if upper_bound > lower_bound:\n            return True\n        else:\n            raise InvalidArguments(\"upper_bound must be greater than lower_bound.\")\n    elif (partition_column is None) and (lower_bound is None) and (upper_bound is None):\n        return False\n    else:\n        raise InvalidArguments(\n            \"Invalid combination of partition_column, lower_bound, upper_bound.\"\n            \"All these arguments should be passed (distributed) or none of them (standard pandas).\"\n        )",
    "docstring": "Check if is possible distribute a query given that args\n\n    Args:\n        partition_column: column used to share the data between the workers\n        lower_bound: the minimum value to be requested from the partition_column\n        upper_bound: the maximum value to be requested from the partition_column\n\n    Returns:\n        True for distributed or False if not"
  },
  {
    "code": "def color_msg(msg, color):\n    \" Return colored message \"\n    return ''.join((COLORS.get(color, COLORS['endc']), msg, COLORS['endc']))",
    "docstring": "Return colored message"
  },
  {
    "code": "def get_archive(self, archive_name, default_version=None):\n        auth, archive_name = self._normalize_archive_name(archive_name)\n        res = self.manager.get_archive(archive_name)\n        if default_version is None:\n            default_version = self._default_versions.get(archive_name, None)\n        if (auth is not None) and (auth != res['authority_name']):\n            raise ValueError(\n                'Archive \"{}\" not found on {}.'.format(archive_name, auth) +\n                ' Did you mean \"{}://{}\"?'.format(\n                    res['authority_name'], archive_name))\n        return self._ArchiveConstructor(\n            api=self,\n            default_version=default_version,\n            **res)",
    "docstring": "Retrieve a data archive\n\n        Parameters\n        ----------\n\n        archive_name: str\n            Name of the archive to retrieve\n\n        default_version: version\n            str or :py:class:`~distutils.StrictVersion` giving the default\n            version number to be used on read operations\n\n        Returns\n        -------\n        archive: object\n            New :py:class:`~datafs.core.data_archive.DataArchive` object\n\n        Raises\n        ------\n\n        KeyError:\n            A KeyError is raised when the ``archive_name`` is not found"
  },
  {
    "code": "def build_available_time_string(availabilities):\n    prefix = 'We have availabilities at '\n    if len(availabilities) > 3:\n        prefix = 'We have plenty of availability, including '\n    prefix += build_time_output_string(availabilities[0])\n    if len(availabilities) == 2:\n        return '{} and {}'.format(prefix, build_time_output_string(availabilities[1]))\n    return '{}, {} and {}'.format(prefix, build_time_output_string(availabilities[1]), build_time_output_string(availabilities[2]))",
    "docstring": "Build a string eliciting for a possible time slot among at least two availabilities."
  },
  {
    "code": "def apply_settings(settings):\n    for key, value in settings.items():\n        ConfigManager.SETTINGS[key] = value",
    "docstring": "Allows new settings to be added without users having to lose all their configuration"
  },
  {
    "code": "def xpath(self, xpath, dom=None):\n        if dom is None:\n            dom = self.browser\n        return expect(dom.find_by_xpath, args=[xpath])",
    "docstring": "xpath find function abbreviation"
  },
  {
    "code": "def kcore_bd(CIJ, k, peel=False):\n    if peel:\n        peelorder, peellevel = ([], [])\n    iter = 0\n    CIJkcore = CIJ.copy()\n    while True:\n        id, od, deg = degrees_dir(CIJkcore)\n        ff, = np.where(np.logical_and(deg < k, deg > 0))\n        if ff.size == 0:\n            break\n        iter += 1\n        CIJkcore[ff, :] = 0\n        CIJkcore[:, ff] = 0\n        if peel:\n            peelorder.append(ff)\n        if peel:\n            peellevel.append(iter * np.ones((len(ff),)))\n    kn = np.sum(deg > 0)\n    if peel:\n        return CIJkcore, kn, peelorder, peellevel\n    else:\n        return CIJkcore, kn",
    "docstring": "The k-core is the largest subnetwork comprising nodes of degree at\n    least k. This function computes the k-core for a given binary directed\n    connection matrix by recursively peeling off nodes with degree lower\n    than k, until no such nodes remain.\n\n    Parameters\n    ----------\n    CIJ : NxN np.ndarray\n        binary directed adjacency matrix\n    k : int\n        level of k-core\n    peel : bool\n        If True, additionally calculates peelorder and peellevel. Defaults to\n        False.\n\n    Returns\n    -------\n    CIJkcore : NxN np.ndarray\n        connection matrix of the k-core. This matrix only contains nodes of\n        degree at least k.\n    kn : int\n        size of k-core\n    peelorder : Nx1 np.ndarray\n        indices in the order in which they were peeled away during k-core\n        decomposition. only returned if peel is specified.\n    peellevel : Nx1 np.ndarray\n        corresponding level - nodes in at the same level have been peeled\n        away at the same time. only return if peel is specified\n\n    Notes\n    -----\n    'peelorder' and 'peellevel' are similar the the k-core sub-shells\n    described in Modha and Singh (2010)."
  },
  {
    "code": "def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque):\n    _salt_send_domain_event(opaque, conn, domain, opaque['event'], {\n        'dev': dev,\n        'path': path,\n        'threshold': threshold,\n        'excess': excess\n    })",
    "docstring": "Domain block threshold events handler"
  },
  {
    "code": "def delete_network_postcommit(self, context):\n        network = context.current\n        log_context(\"delete_network_postcommit: network\", network)\n        segments = context.network_segments\n        tenant_id = network['project_id']\n        self.delete_segments(segments)\n        self.delete_network(network)\n        self.delete_tenant_if_removed(tenant_id)",
    "docstring": "Delete the network from CVX"
  },
  {
    "code": "def getCoeff(self, name, light=None, date=None):\r\n        d = self.coeffs[name]\r\n        try:\r\n            c = d[light]\r\n        except KeyError:\r\n            try:\r\n                k, i = next(iter(d.items()))\r\n                if light is not None:\r\n                    print(\r\n                        'no calibration found for [%s] - using [%s] instead' % (light, k))\r\n            except StopIteration:\r\n                return None\r\n            c = i\r\n        except TypeError:\r\n            c = d\r\n        return _getFromDate(c, date)",
    "docstring": "try to get calibration for right light source, but\r\n        use another if they is none existent"
  },
  {
    "code": "def get_assignable_bin_ids(self, bin_id):\n        mgr = self._get_provider_manager('RESOURCE', local=True)\n        lookup_session = mgr.get_bin_lookup_session(proxy=self._proxy)\n        bins = lookup_session.get_bins()\n        id_list = []\n        for bin in bins:\n            id_list.append(bin.get_id())\n        return IdList(id_list)",
    "docstring": "Gets a list of bins including and under the given bin node in which any resource can be assigned.\n\n        arg:    bin_id (osid.id.Id): the ``Id`` of the ``Bin``\n        return: (osid.id.IdList) - list of assignable bin ``Ids``\n        raise:  NullArgument - ``bin_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def comment(self, text):\n        url = self._imgur._base_url + \"/3/comment\"\n        payload = {'image_id': self.id, 'comment': text}\n        resp = self._imgur._send_request(url, params=payload, needs_auth=True,\n                                         method='POST')\n        return Comment(resp, imgur=self._imgur, has_fetched=False)",
    "docstring": "Make a top-level comment to this.\n\n        :param text: The comment text."
  },
  {
    "code": "def __remove_trailing_zeros(self, collection):\n        index = len(collection) - 1\n        while index >= 0 and collection[index] == 0:\n            index -= 1\n        return collection[:index + 1]",
    "docstring": "Removes trailing zeroes from indexable collection of numbers"
  },
  {
    "code": "def button_pressed(self, key_code, prefix=None):\n        if prefix is not None:\n            state = self.buttons_by_code.get(prefix + str(key_code))\n        else:\n            state = self.buttons_by_code.get(key_code)\n        if state is not None:\n            for handler in state.button_handlers:\n                handler(state.button)\n            state.is_pressed = True\n            state.last_pressed = time()\n            state.was_pressed_since_last_check = True\n        else:\n            logger.debug('Unknown button code {} ({})'.format(key_code, prefix))",
    "docstring": "Called from the controller classes to update the state of this button manager when a button is pressed.\n\n        :internal:\n\n        :param key_code:\n            The code specified when populating Button instances\n        :param prefix:\n            Applied to key code if present"
  },
  {
    "code": "def event_html_page_context(app, pagename, templatename, context, doctree):\n    assert app or pagename or templatename\n    if 'script_files' in context and doctree and any(hasattr(n, 'disqus_shortname') for n in doctree.traverse()):\n        context['script_files'] = context['script_files'][:] + ['_static/disqus.js']",
    "docstring": "Called when the HTML builder has created a context dictionary to render a template with.\n\n    Conditionally adding disqus.js to <head /> if the directive is used in a page.\n\n    :param sphinx.application.Sphinx app: Sphinx application object.\n    :param str pagename: Name of the page being rendered (without .html or any file extension).\n    :param str templatename: Page name with .html.\n    :param dict context: Jinja2 HTML context.\n    :param docutils.nodes.document doctree: Tree of docutils nodes."
  },
  {
    "code": "def unregisterHandler(self, fh):\n        try:\n            self.fds.remove(fh)\n        except KeyError:\n            pass\n        self.lock.acquire()\n        try:\n            self.data.rollover()\n        finally:\n            self.lock.release()\n        if self.closing and not self.fds:\n            self.data.close()",
    "docstring": "Unregister a file descriptor. Clean data, if such operation has been scheduled.\n\n        Parameters\n        ----------\n        fh : int\n            File descriptor."
  },
  {
    "code": "def getValidReff(self, urn, inventory=None, level=None):\n        return self.call({\n            \"inv\": inventory,\n            \"urn\": urn,\n            \"level\": level,\n            \"request\": \"GetValidReff\"\n        })",
    "docstring": "Retrieve valid urn-references for a text\n\n        :param urn: URN identifying the text\n        :type urn: text\n        :param inventory: Name of the inventory\n        :type inventory: text\n        :param level: Depth of references expected\n        :type level: int\n        :return: XML Response from the API as string\n        :rtype: str"
  },
  {
    "code": "def validate(self,\n                 _portfolio,\n                 account,\n                 algo_datetime,\n                 _algo_current_data):\n        if (algo_datetime > self.deadline and\n                account.leverage < self.min_leverage):\n            self.fail()",
    "docstring": "Make validation checks if we are after the deadline.\n        Fail if the leverage is less than the min leverage."
  },
  {
    "code": "def remove(self, path):\n        entry = self.find(path)\n        if not entry:\n            raise ValueError(\"%s does not exists\" % path)\n        if entry.type == 'root storage':\n            raise ValueError(\"can no remove root entry\")\n        if entry.type == \"storage\" and not entry.child_id is None:\n            raise ValueError(\"storage contains children\")\n        entry.pop()\n        if entry.type == \"stream\":\n            self.free_fat_chain(entry.sector_id, entry.byte_size < self.min_stream_max_size)\n        self.free_dir_entry(entry)",
    "docstring": "Removes both streams and storage DirEntry types from file.\n        storage type entries need to be empty dirs."
  },
  {
    "code": "def size(self, type=None, failed=False):\n        return len(self.nodes(type=type, failed=failed))",
    "docstring": "How many nodes in a network.\n\n        type specifies the class of node, failed\n        can be True/False/all."
  },
  {
    "code": "def undefine(self):\n        if lib.EnvUndefrule(self._env, self._rule) != 1:\n            raise CLIPSError(self._env)\n        self._env = None",
    "docstring": "Undefine the Rule.\n\n        Python equivalent of the CLIPS undefrule command.\n\n        The object becomes unusable after this method has been called."
  },
  {
    "code": "def with_translations(self, **kwargs):\n        force = kwargs.pop(\"force\", False)\n        if self._prefetch_translations_done and force is False:\n            return self\n        self._prefetched_translations_cache = utils.get_grouped_translations(\n            self, **kwargs\n        )\n        self._prefetch_translations_done = True\n        return self._clone()",
    "docstring": "Prefetches translations.\n\n        Takes three optional keyword arguments:\n\n        * ``field_names``: ``field_name`` values for SELECT IN\n        * ``languages``: ``language`` values for SELECT IN\n        * ``chunks_length``: fetches IDs by chunk"
  },
  {
    "code": "def _format_volume_string(self, volume_string):\n        return '[' + volume_string[volume_string.find(self.volume_string):].replace(' %','%').replace('ume', '')+'] '",
    "docstring": "format mplayer's volume"
  },
  {
    "code": "def get_object_key(self, key, using_name=True):\n        try:\n            if using_name:\n                return self.o_name[key].key\n            else:\n                return self.o[key].key\n        except KeyError:\n            raise ValueError(\"'%s' are not found!\" % key)",
    "docstring": "Given a object key or name, return it's object key."
  },
  {
    "code": "def authenticate_peer(self, auth_data, peer_id, message):\n        logger.debug('message: {}'.format(dump(message)))\n        signed_octets = message + self.Ni + prf(self.SK_pr, peer_id._data)\n        auth_type = const.AuthenticationType(struct.unpack(const.AUTH_HEADER, auth_data[:4])[0])\n        assert auth_type == const.AuthenticationType.RSA\n        logger.debug(dump(auth_data))\n        try:\n            return pubkey.verify(signed_octets, auth_data[4:], 'tests/peer.pem')\n        except pubkey.VerifyError:\n            raise IkeError(\"Remote peer authentication failed.\")",
    "docstring": "Verifies the peers authentication."
  },
  {
    "code": "def create(self, service_name, json, **kwargs):\n        return self._send(requests.post, service_name, json, **kwargs)",
    "docstring": "Create a new AppNexus object"
  },
  {
    "code": "def user_fields(self, user):\n        return self._query_zendesk(self.endpoint.user_fields, 'user_field', id=user)",
    "docstring": "Retrieve the user fields for this user.\n\n        :param user: User object or id"
  },
  {
    "code": "def __get_labels(self):\n        labels = []\n        try:\n            with self.fs.open(self.fs.join(self.path, self.LABEL_FILE),\n                                'r') as file_desc:\n                for line in file_desc.readlines():\n                    line = line.strip()\n                    (label_name, label_color) = line.split(\",\", 1)\n                    labels.append(Label(name=label_name,\n                                        color=label_color))\n        except IOError:\n            pass\n        return labels",
    "docstring": "Read the label file of the documents and extract all the labels\n\n        Returns:\n            An array of labels.Label objects"
  },
  {
    "code": "def is_transition_metal(self):\n        ns = list(range(21, 31))\n        ns.extend(list(range(39, 49)))\n        ns.append(57)\n        ns.extend(list(range(72, 81)))\n        ns.append(89)\n        ns.extend(list(range(104, 113)))\n        return self.Z in ns",
    "docstring": "True if element is a transition metal."
  },
  {
    "code": "def global_lppooling(attrs, inputs, proto_obj):\n    p_value = attrs.get('p', 2)\n    new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True,\n                                                                'kernel': (1, 1),\n                                                                'pool_type': 'lp',\n                                                                'p_value': p_value})\n    new_attrs = translation_utils._remove_attributes(new_attrs, ['p'])\n    return 'Pooling', new_attrs, inputs",
    "docstring": "Performs global lp pooling on the input."
  },
  {
    "code": "def show_wait_cursor(object):\n    @functools.wraps(object)\n    def show_wait_cursorWrapper(*args, **kwargs):\n        QApplication.setOverrideCursor(Qt.WaitCursor)\n        value = None\n        try:\n            value = object(*args, **kwargs)\n        finally:\n            QApplication.restoreOverrideCursor()\n            return value\n    return show_wait_cursorWrapper",
    "docstring": "Shows a wait cursor while processing.\n\n    :param object: Object to decorate.\n    :type object: object\n    :return: Object.\n    :rtype: object"
  },
  {
    "code": "def extract_along_line(self, pid, xy0, xy1, N=10):\n        assert N >= 2\n        xy0 = np.array(xy0).squeeze()\n        xy1 = np.array(xy1).squeeze()\n        assert xy0.size == 2\n        assert xy1.size == 2\n        points = [(x, y) for x, y in zip(\n            np.linspace(xy0[0], xy1[0], N), np.linspace(xy0[1], xy1[1], N)\n        )]\n        result = self.extract_points(pid, points)\n        results_xyv = np.hstack((\n            points,\n            result[:, np.newaxis]\n        ))\n        return results_xyv",
    "docstring": "Extract parameter values along a given line.\n\n        Parameters\n        ----------\n        pid: int\n            The parameter id to extract values from\n        xy0: tuple\n            A tupe with (x,y) start point coordinates\n        xy1: tuple\n            A tupe with (x,y) end point coordinates\n        N: integer, optional\n            The number of values to extract along the line (including start and\n            end point)\n\n        Returns\n        -------\n        values: numpy.ndarray (n x 1)\n            data values for extracted data points"
  },
  {
    "code": "def encode_coin_link(copper, silver=0, gold=0):\n    return encode_chat_link(gw2api.TYPE_COIN, copper=copper, silver=silver,\n                            gold=gold)",
    "docstring": "Encode a chat link for an amount of coins."
  },
  {
    "code": "def get_tx(tx_id, api_code=None):\n    resource = 'rawtx/' + tx_id\n    if api_code is not None:\n        resource += '?api_code=' + api_code\n    response = util.call_api(resource)\n    json_response = json.loads(response)\n    return Transaction(json_response)",
    "docstring": "Get a single transaction based on a transaction hash.\n\n    :param str tx_id: transaction hash to look up\n    :param str api_code: Blockchain.info API code (optional)\n    :return: an instance of :class:`Transaction` class"
  },
  {
    "code": "def _inject_dist(distname, kwargs={}, ns=locals()):\n    dist_logp, dist_random, grad_logp = name_to_funcs(distname, ns)\n    classname = capitalize(distname)\n    ns[classname] = stochastic_from_dist(distname, dist_logp,\n                                         dist_random,\n                                         grad_logp, **kwargs)",
    "docstring": "Reusable function to inject Stochastic subclasses into module\n    namespace"
  },
  {
    "code": "def cores(self):\n        for (x, y), chip_info in iteritems(self):\n            for p, state in enumerate(chip_info.core_states):\n                yield (x, y, p, state)",
    "docstring": "Generate the set of all cores in the system.\n\n        Yields\n        ------\n        (x, y, p, :py:class:`~rig.machine_control.consts.AppState`)\n            A core in the machine, and its state. Cores related to a specific\n            chip are yielded consecutively in ascending order of core number."
  },
  {
    "code": "def get_comments_of_invoice_per_page(self, invoice_id, per_page=1000, page=1):\n        return self._get_resource_per_page(\n            resource=INVOICE_COMMENTS,\n            per_page=per_page,\n            page=page,\n            params={'invoice_id': invoice_id},\n        )",
    "docstring": "Get comments of invoice per page\n\n        :param invoice_id: the invoice id\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :return: list"
  },
  {
    "code": "def _repr__base(self, rich_output=False):\n        repr_dict = collections.OrderedDict()\n        key = '%s (point source)' % self.name\n        repr_dict[key] = collections.OrderedDict()\n        repr_dict[key]['position'] = self._sky_position.to_dict(minimal=True)\n        repr_dict[key]['spectrum'] = collections.OrderedDict()\n        for component_name, component in self.components.iteritems():\n            repr_dict[key]['spectrum'][component_name] = component.to_dict(minimal=True)\n        return dict_to_list(repr_dict, rich_output)",
    "docstring": "Representation of the object\n\n        :param rich_output: if True, generates HTML, otherwise text\n        :return: the representation"
  },
  {
    "code": "def split_taf(txt: str) -> [str]:\n    lines = []\n    split = txt.split()\n    last_index = 0\n    for i, item in enumerate(split):\n        if starts_new_line(item) and i != 0 and not split[i - 1].startswith('PROB'):\n            lines.append(' '.join(split[last_index:i]))\n            last_index = i\n    lines.append(' '.join(split[last_index:]))\n    return lines",
    "docstring": "Splits a TAF report into each distinct time period"
  },
  {
    "code": "def triangles(self):\n        triangles = collections.deque()\n        triangles_node = collections.deque()\n        for node_name in self.graph.nodes_geometry:\n            transform, geometry_name = self.graph[node_name]\n            geometry = self.geometry[geometry_name]\n            if not hasattr(geometry, 'triangles'):\n                continue\n            triangles.append(\n                transformations.transform_points(\n                    geometry.triangles.copy().reshape((-1, 3)),\n                    matrix=transform))\n            triangles_node.append(\n                np.tile(node_name,\n                        len(geometry.triangles)))\n        self._cache['triangles_node'] = np.hstack(triangles_node)\n        triangles = np.vstack(triangles).reshape((-1, 3, 3))\n        return triangles",
    "docstring": "Return a correctly transformed polygon soup of the\n        current scene.\n\n        Returns\n        ----------\n        triangles: (n,3,3) float, triangles in space"
  },
  {
    "code": "def create_dir(self, jbfile):\n        try:\n            jbfile.create_directory()\n        except os.error:\n            self.statusbar.showMessage('Could not create path: %s' % jbfile.get_path())",
    "docstring": "Create a dir for the given dirfile and display an error message, if it fails.\n\n        :param jbfile: the jb file to make the directory for\n        :type jbfile: class:`JB_File`\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def list_(self):\n        with self.lock:\n            self.send('LIST')\n            list_ = {}\n            while self.readable():\n                msg = self._recv(expected_replies=('322', '321', '323'))\n                if msg[0] == '322':\n                    channel, usercount, modes, topic = msg[2].split(' ', 3)\n                    modes = modes.replace(':', '', 1).replace(':', '', 1)\n                    modes = modes.replace('[', '').replace( \\\n                                                    ']', '').replace('+', '')\n                    list_[channel] = usercount, modes, topic\n                elif msg[0] == '321':\n                    pass\n                elif msg[0] == '323':\n                    break\n            return list_",
    "docstring": "Gets a list of channels on the server."
  },
  {
    "code": "def parse_template(self):\n        self.templ_dict = {'actions': {'definition': {}}}\n        self.templ_dict['name'] = self._get_template_name()\n        self._add_cli_scripts()\n        self._add_sections()\n        self._add_attrs()\n        return self.templ_dict",
    "docstring": "Parse the template string into a dict.\n\n        Find the (large) inner sections first, save them, and remove them from\n        a modified string. Then find the template attributes in the modified\n        string.\n\n        :returns: dictionary of parsed template"
  },
  {
    "code": "def _begin_request(self):\n        headers = self.m2req.headers\n        self._request = HTTPRequest(connection=self,\n            method=headers.get(\"METHOD\"),\n            uri=self.m2req.path,\n            version=headers.get(\"VERSION\"),\n            headers=headers,\n            remote_ip=headers.get(\"x-forwarded-for\"))\n        if len(self.m2req.body) > 0:\n            self._request.body = self.m2req.body\n        if self.m2req.is_disconnect():\n            self.finish()\n        elif headers.get(\"x-mongrel2-upload-done\", None):\n            expected = headers.get(\"x-mongrel2-upload-start\", \"BAD\")\n            upload = headers.get(\"x-mongrel2-upload-done\", None)\n            if expected == upload:\n                self.request_callback(self._request)\n        elif headers.get(\"x-mongrel2-upload-start\", None):\n            pass\n        else:\n            self.request_callback(self._request)",
    "docstring": "Actually start executing this request."
  },
  {
    "code": "def _publish_replset(self, data, base_prefix):\n        prefix = base_prefix + ['replset']\n        self._publish_dict_with_prefix(data, prefix)\n        total_nodes = len(data['members'])\n        healthy_nodes = reduce(lambda value, node: value + node['health'],\n                               data['members'], 0)\n        self._publish_dict_with_prefix({\n            'healthy_nodes': healthy_nodes,\n            'total_nodes': total_nodes\n        }, prefix)\n        for node in data['members']:\n            replset_node_name = node[self.config['replset_node_name']]\n            node_name = str(replset_node_name.split('.')[0])\n            self._publish_dict_with_prefix(node, prefix + ['node', node_name])",
    "docstring": "Given a response to replSetGetStatus, publishes all numeric values\n            of the instance, aggregate stats of healthy nodes vs total nodes,\n            and the observed statuses of all nodes in the replica set."
  },
  {
    "code": "def branch_out(self, limb=None):\n        if not limb:\n            limbs = self._cfg.sections()\n        else:\n            limb = limb if isinstance(limb, list) else [limb]\n            limbs = ['general']\n            limbs.extend(limb)\n        for leaf in limbs:\n            leaf = leaf if leaf in self._cfg.sections() else leaf.upper()\n            self.environ[leaf] = OrderedDict()\n            options = self._cfg.options(leaf)\n            for opt in options:\n                if opt in self.environ['default']:\n                    continue\n                val = self._cfg.get(leaf, opt)\n                if val.find(self._file_replace) == 0:\n                    val = val.replace(self._file_replace, self.sasbasedir)\n                self.environ[leaf][opt] = val",
    "docstring": "Set the individual section branches\n\n        This adds the various sections of the config file into the\n        tree environment for access later. Optically can specify a specific\n        branch.  This does not yet load them into the os environment.\n\n        Parameters:\n            limb (str/list):\n                The name of the section of the config to add into the environ\n                or a list of strings"
  },
  {
    "code": "def build_sample_ace_problem_breiman85(N=200):\n    x_cubed = numpy.random.standard_normal(N)\n    x = scipy.special.cbrt(x_cubed)\n    noise = numpy.random.standard_normal(N)\n    y = numpy.exp((x ** 3.0) + noise)\n    return [x], y",
    "docstring": "Sample problem from Breiman 1985."
  },
  {
    "code": "def read_command(self):\n        reader = self.reader\n        line = yield from reader.readline()\n        if line == b'':\n            raise ConnectionResetError()\n        try:\n            codeobj = self.attempt_compile(line.rstrip(b'\\n'))\n        except SyntaxError:\n            yield from self.send_exception()\n            return\n        return codeobj",
    "docstring": "Read a command from the user line by line.\n\n        Returns a code object suitable for execution."
  },
  {
    "code": "def _create_in_progress(self):\n        instance = self.service.service.get_instance(self.service.name)\n        if (instance['last_operation']['state'] == 'in progress' and\n           instance['last_operation']['type'] == 'create'):\n               return True\n        return False",
    "docstring": "Creating this service is handled asynchronously so this method will\n        simply check if the create is in progress.  If it is not in progress,\n        we could probably infer it either failed or succeeded."
  },
  {
    "code": "def filter_pipeline(effects, filters):\n    for filter_fn in filters:\n        filtered_effects = filter_fn(effects)\n        if len(effects) == 1:\n            return effects\n        elif len(filtered_effects) > 1:\n            effects = filtered_effects\n    return effects",
    "docstring": "Apply each filter to the effect list sequentially. If any filter\n    returns zero values then ignore it. As soon as only one effect is left,\n    return it.\n\n    Parameters\n    ----------\n    effects : list of MutationEffect subclass instances\n\n    filters : list of functions\n        Each function takes a list of effects and returns a list of effects\n\n    Returns list of effects"
  },
  {
    "code": "def _build_gan_trainer(self, input, model):\n        self.tower_func = TowerFuncWrapper(model.build_graph, model.get_input_signature())\n        with TowerContext('', is_training=True):\n            self.tower_func(*input.get_input_tensors())\n        opt = model.get_optimizer()\n        with tf.name_scope('optimize'):\n            g_min = opt.minimize(model.g_loss, var_list=model.g_vars, name='g_op')\n            with tf.control_dependencies([g_min]):\n                d_min = opt.minimize(model.d_loss, var_list=model.d_vars, name='d_op')\n        self.train_op = d_min",
    "docstring": "We need to set tower_func because it's a TowerTrainer,\n        and only TowerTrainer supports automatic graph creation for inference during training.\n\n        If we don't care about inference during training, using tower_func is\n        not needed. Just calling model.build_graph directly is OK."
  },
  {
    "code": "def pretty_xml(string_input, add_ns=False):\n    if add_ns:\n        elem = \"<foo \"\n        for key, value in DOC_CONTENT_ATTRIB.items():\n            elem += ' %s=\"%s\"' % (key, value)\n        string_input = elem + \">\" + string_input + \"</foo>\"\n    doc = minidom.parseString(string_input)\n    if add_ns:\n        s1 = doc.childNodes[0].childNodes[0].toprettyxml(\"  \")\n    else:\n        s1 = doc.toprettyxml(\"  \")\n    return s1",
    "docstring": "pretty indent string_input"
  },
  {
    "code": "def runSearchRnaQuantifications(self, request):\n        return self.runSearchRequest(\n            request, protocol.SearchRnaQuantificationsRequest,\n            protocol.SearchRnaQuantificationsResponse,\n            self.rnaQuantificationsGenerator)",
    "docstring": "Returns a SearchRnaQuantificationResponse for the specified\n        SearchRnaQuantificationRequest object."
  },
  {
    "code": "def resample_singlechan(x, ann, fs, fs_target):\n    resampled_x, resampled_t = resample_sig(x, fs, fs_target)\n    new_sample = resample_ann(resampled_t, ann.sample)\n    assert ann.sample.shape == new_sample.shape\n    resampled_ann = Annotation(record_name=ann.record_name,\n                               extension=ann.extension,\n                               sample=new_sample,\n                               symbol=ann.symbol,\n                               subtype=ann.subtype,\n                               chan=ann.chan,\n                               num=ann.num,\n                               aux_note=ann.aux_note,\n                               fs=fs_target)\n    return resampled_x, resampled_ann",
    "docstring": "Resample a single-channel signal with its annotations\n\n    Parameters\n    ----------\n    x: numpy array\n        The signal array\n    ann : wfdb Annotation\n        The wfdb annotation object\n    fs : int, or float\n        The original frequency\n    fs_target : int, or float\n        The target frequency\n\n    Returns\n    -------\n    resampled_x : numpy array\n        Array of the resampled signal values\n    resampled_ann : wfdb Annotation\n        Annotation containing resampled annotation locations"
  },
  {
    "code": "def list_users(self, envs=[], query=\"/users/\"):\n        juicer.utils.Log.log_debug(\n                \"List Users In: %s\", \", \".join(envs))\n        for env in envs:\n            juicer.utils.Log.log_info(\"%s:\" % (env))\n            _r = self.connectors[env].get(query)\n            if _r.status_code == Constants.PULP_GET_OK:\n                for user in juicer.utils.load_json_str(_r.content):\n                    roles = user['roles']\n                    if roles:\n                        user_roles = ', '.join(roles)\n                    else:\n                        user_roles = \"None\"\n                    juicer.utils.Log.log_info(\"\\t%s - %s\" % (user['login'], user_roles))\n            else:\n                _r.raise_for_status()\n        return True",
    "docstring": "List users in specified environments"
  },
  {
    "code": "def clear_cache():\n    fsb_cachedir = os.path.join(__opts__['cachedir'], 'svnfs')\n    list_cachedir = os.path.join(__opts__['cachedir'], 'file_lists/svnfs')\n    errors = []\n    for rdir in (fsb_cachedir, list_cachedir):\n        if os.path.exists(rdir):\n            try:\n                shutil.rmtree(rdir)\n            except OSError as exc:\n                errors.append('Unable to delete {0}: {1}'.format(rdir, exc))\n    return errors",
    "docstring": "Completely clear svnfs cache"
  },
  {
    "code": "def export(self):\n        data = {}\n        for key, value in self.items():\n            data[key] = value\n        return data",
    "docstring": "Exports as dictionary"
  },
  {
    "code": "def function_end(self):\r\n        self.newline_label(self.shared.function_name + \"_exit\", True, True)\r\n        self.move(\"%14\", \"%15\")\r\n        self.pop(\"%14\")\r\n        self.newline_text(\"RET\", True)",
    "docstring": "Inserts an exit label and function return instructions"
  },
  {
    "code": "def populate_jobset(job, jobset, depth):\n    jobset.add(job)\n    if len(job.dependencies) == 0:\n        return jobset\n    for j in job.dependencies:\n        jobset = populate_jobset(j, jobset, depth+1)\n    return jobset",
    "docstring": "Creates a set of jobs, containing jobs at difference depths of the\n    dependency tree, retaining dependencies as strings, not Jobs."
  },
  {
    "code": "async def _pinger(self):\n        async def _do_ping():\n            try:\n                await pinger_facade.Ping()\n                await asyncio.sleep(10, loop=self.loop)\n            except CancelledError:\n                pass\n        pinger_facade = client.PingerFacade.from_connection(self)\n        try:\n            while True:\n                await utils.run_with_interrupt(\n                    _do_ping(),\n                    self.monitor.close_called,\n                    loop=self.loop)\n                if self.monitor.close_called.is_set():\n                    break\n        except websockets.exceptions.ConnectionClosed:\n            log.debug('ping failed because of closed connection')\n            pass",
    "docstring": "A Controller can time us out if we are silent for too long. This\n        is especially true in JaaS, which has a fairly strict timeout.\n\n        To prevent timing out, we send a ping every ten seconds."
  },
  {
    "code": "def distance_to_line(a, b, p):\n    return distance(closest_point(a, b, p), p)",
    "docstring": "Closest distance between a line segment and a point\n\n    Args:\n        a ([float, float]): x and y coordinates. Line start\n        b ([float, float]): x and y coordinates. Line end\n        p ([float, float]): x and y coordinates. Point to compute the distance\n    Returns:\n        float"
  },
  {
    "code": "def group_tasks(self):\n        tasks = set()\n        for node in walk_tree(self):\n            for ctrl in node.controllers.values():\n                tasks.update(ctrl.tasks)\n        return tasks",
    "docstring": "All tasks in the hierarchy, affected by this group."
  },
  {
    "code": "def getDynMeth(name):\n    cname, fname = name.rsplit('.', 1)\n    clas = getDynLocal(cname)\n    if clas is None:\n        return None\n    return getattr(clas, fname, None)",
    "docstring": "Retrieve and return an unbound method by python path."
  },
  {
    "code": "def continuous_partition_data(data, bins='auto', n_bins=10):\n    if bins == 'uniform':\n        bins = np.linspace(start=np.min(data), stop=np.max(data), num=n_bins+1)\n    elif bins == 'ntile':\n        bins = np.percentile(data, np.linspace(\n            start=0, stop=100, num=n_bins+1))\n    elif bins != 'auto':\n        raise ValueError(\"Invalid parameter for bins argument\")\n    hist, bin_edges = np.histogram(data, bins, density=False)\n    return {\n        \"bins\": bin_edges,\n        \"weights\": hist / len(data)\n    }",
    "docstring": "Convenience method for building a partition object on continuous data\n\n    Args:\n        data (list-like): The data from which to construct the estimate.\n        bins (string): One of 'uniform' (for uniformly spaced bins), 'ntile' (for percentile-spaced bins), or 'auto' (for automatically spaced bins)\n        n_bins (int): Ignored if bins is auto.\n\n    Returns:\n        A new partition_object::\n\n        {\n            \"bins\": (list) The endpoints of the partial partition of reals,\n            \"weights\": (list) The densities of the bins implied by the partition.\n        }"
  },
  {
    "code": "def _create_models_for_relation_step(self, rel_model_name,\n                                     rel_key, rel_value, model):\n    model = get_model(model)\n    lookup = {rel_key: rel_value}\n    rel_model = get_model(rel_model_name).objects.get(**lookup)\n    data = guess_types(self.hashes)\n    for hash_ in data:\n        hash_['%s' % rel_model_name] = rel_model\n    try:\n        func = _WRITE_MODEL[model]\n    except KeyError:\n        func = partial(write_models, model)\n    func(data, None)",
    "docstring": "Create a new model linked to the given model.\n\n    Syntax:\n\n        And `model` with `field` \"`value`\" has `new model` in the database:\n\n    Example:\n\n    .. code-block:: gherkin\n\n        And project with name \"Ball Project\" has goals in the database:\n            | description                             |\n            | To have fun playing with balls of twine |"
  },
  {
    "code": "def serverdefaults(self, force_reload=False):\n        if not self._server_defaults or force_reload:\n            request = client_proto.GetServerDefaultsRequestProto()\n            response = self.service.getServerDefaults(request).serverDefaults\n            self._server_defaults = {'blockSize': response.blockSize, 'bytesPerChecksum': response.bytesPerChecksum,\n                'writePacketSize': response.writePacketSize, 'replication': response.replication,\n                'fileBufferSize': response.fileBufferSize, 'encryptDataTransfer': response.encryptDataTransfer,\n                'trashInterval': response.trashInterval, 'checksumType': response.checksumType}\n        return self._server_defaults.copy()",
    "docstring": "Get server defaults, caching the results. If there are no results saved, or the force_reload flag is True,\n        it will query the HDFS server for its default parameter values. Otherwise, it will simply return the results\n        it has already queried.\n\n        Note: This function returns a copy of the results loaded from the server, so you can manipulate or change\n        them as you'd like. If for any reason you need to change the results the client saves, you must access\n        the property client._server_defaults directly.\n\n        :param force_reload: Should the server defaults be reloaded even if they already exist?\n        :type force_reload: bool\n        :returns: dictionary with the following keys: blockSize, bytesPerChecksum, writePacketSize, replication, fileBufferSize, encryptDataTransfer, trashInterval, checksumType\n\n        **Example:**\n\n        >>> client.serverdefaults()\n        [{'writePacketSize': 65536, 'fileBufferSize': 4096, 'replication': 1, 'bytesPerChecksum': 512, 'trashInterval': 0L, 'blockSize': 134217728L, 'encryptDataTransfer': False, 'checksumType': 2}]"
  },
  {
    "code": "def extract_subject_from_dn(cert_obj):\n    return \",\".join(\n        \"{}={}\".format(\n            OID_TO_SHORT_NAME_DICT.get(v.oid.dotted_string, v.oid.dotted_string),\n            rdn_escape(v.value),\n        )\n        for v in reversed(list(cert_obj.subject))\n    )",
    "docstring": "Serialize a DN to a DataONE subject string.\n\n    Args:\n      cert_obj: cryptography.Certificate\n\n    Returns:\n      str:\n        Primary subject extracted from the certificate DN.\n\n    The certificate DN (DistinguishedName) is a sequence of RDNs\n    (RelativeDistinguishedName). Each RDN is a set of AVAs (AttributeValueAssertion /\n    AttributeTypeAndValue). A DataONE subject is a plain string. As there is no single\n    standard specifying how to create a string representation of a DN, DataONE selected\n    one of the most common ways, which yield strings such as:\n\n    CN=Some Name A123,O=Some Organization,C=US,DC=Some Domain,DC=org\n\n    In particular, the sequence of RDNs is reversed. Attribute values are escaped,\n    attribute type and value pairs are separated by \"=\", and AVAs are joined together\n    with \",\". If an RDN contains an unknown OID, the OID is serialized as a dotted\n    string.\n\n    As all the information in the DN is preserved, it is not possible to create the\n    same subject with two different DNs, and the DN can be recreated from the subject."
  },
  {
    "code": "def put_admin_metadata(self, admin_metadata):\n        logger.debug(\"Putting admin metdata\")\n        text = json.dumps(admin_metadata)\n        key = self.get_admin_metadata_key()\n        self.put_text(key, text)",
    "docstring": "Store the admin metadata."
  },
  {
    "code": "def connect_apps(self):\n        if self._connect_apps is None:\n            self._connect_apps = ConnectAppList(self._version, account_sid=self._solution['sid'], )\n        return self._connect_apps",
    "docstring": "Access the connect_apps\n\n        :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppList\n        :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppList"
  },
  {
    "code": "def add_segments(self, segments):\n        self.tracks.update([seg.track for seg in segments])\n        self.segments.extend(segments)",
    "docstring": "Add a list of segments to the composition\n\n        :param segments: Segments to add to composition\n        :type segments: list of :py:class:`radiotool.composer.Segment`"
  },
  {
    "code": "def p_current_col(self):\n        \"Return currnet column in line\"\n        prefix = self.input[:self.pos]\n        nlidx = prefix.rfind('\\n')\n        if nlidx == -1:\n            return self.pos\n        return self.pos - nlidx",
    "docstring": "Return currnet column in line"
  },
  {
    "code": "def _make_win(n, mono=False):\n    if mono:\n        win = np.hanning(n) + 0.00001\n    else:\n        win = np.array([np.hanning(n) + 0.00001, np.hanning(n) + 0.00001])\n    win = np.transpose(win)\n    return win",
    "docstring": "Generate a window for a given length.\n\n    :param n: an integer for the length of the window.\n    :param mono: True for a mono window, False for a stereo window.\n    :return: an numpy array containing the window value."
  },
  {
    "code": "def remove(self, uid, filename=None):\n        if not filename:\n            filename = self._filename\n        elif filename not in self._reminders:\n            return\n        uid = uid.split('@')[0]\n        with self._lock:\n            rem = open(filename).readlines()\n            for (index, line) in enumerate(rem):\n                if uid == md5(line[:-1].encode('utf-8')).hexdigest():\n                    del rem[index]\n                    open(filename, 'w').writelines(rem)\n                    break",
    "docstring": "Remove the Remind command with the uid from the file"
  },
  {
    "code": "def set_monitor_timeout(timeout, power='ac', scheme=None):\n    return _set_powercfg_value(\n        scheme=scheme,\n        sub_group='SUB_VIDEO',\n        setting_guid='VIDEOIDLE',\n        power=power,\n        value=timeout)",
    "docstring": "Set the monitor timeout in minutes for the given power scheme\n\n    Args:\n        timeout (int):\n            The amount of time in minutes before the monitor will timeout\n\n        power (str):\n            Set the value for AC or DC power. Default is ``ac``. Valid options\n            are:\n\n                - ``ac`` (AC Power)\n                - ``dc`` (Battery)\n\n        scheme (str):\n            The scheme to use, leave as ``None`` to use the current. Default is\n            ``None``. This can be the GUID or the Alias for the Scheme. Known\n            Aliases are:\n\n                - ``SCHEME_BALANCED`` - Balanced\n                - ``SCHEME_MAX`` - Power saver\n                - ``SCHEME_MIN`` - High performance\n\n    Returns:\n        bool: ``True`` if successful, otherwise ``False``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        # Sets the monitor timeout to 30 minutes\n        salt '*' powercfg.set_monitor_timeout 30"
  },
  {
    "code": "def _fastfood_build(args):\n    written_files, cookbook = food.build_cookbook(\n        args.config_file, args.template_pack,\n        args.cookbooks, args.force)\n    if len(written_files) > 0:\n        print(\"%s: %s files written\" % (cookbook,\n                                        len(written_files)))\n    else:\n        print(\"%s up to date\" % cookbook)\n    return written_files, cookbook",
    "docstring": "Run on `fastfood build`."
  },
  {
    "code": "def handle_errors(f):\n    import traceback\n    from plone.jsonapi.core.helpers import error\n    def decorator(*args, **kwargs):\n        try:\n            return f(*args, **kwargs)\n        except Exception:\n            var = traceback.format_exc()\n            return error(var)\n    return decorator",
    "docstring": "simple JSON error handler"
  },
  {
    "code": "def cache_control_expires(num_hours):\n    num_seconds = int(num_hours * 60 * 60)\n    def decorator(func):\n        @wraps(func)\n        def inner(request, *args, **kwargs):\n            response = func(request, *args, **kwargs)\n            patch_response_headers(response, num_seconds)\n            return response\n        return inner\n    return decorator",
    "docstring": "Set the appropriate Cache-Control and Expires headers for the given\n    number of hours."
  },
  {
    "code": "def normalize_column_name(name):\n    if not isinstance(name, six.string_types):\n        raise ValueError('%r is not a valid column name.' % name)\n    name = name.strip()[:63]\n    if isinstance(name, six.text_type):\n        while len(name.encode('utf-8')) >= 64:\n            name = name[:len(name) - 1]\n    if not len(name) or '.' in name or '-' in name:\n        raise ValueError('%r is not a valid column name.' % name)\n    return name",
    "docstring": "Check if a string is a reasonable thing to use as a column name."
  },
  {
    "code": "def get_authorization_vault_session(self):\n        if not self.supports_authorization_vault():\n            raise errors.Unimplemented()\n        return sessions.AuthorizationVaultSession(runtime=self._runtime)",
    "docstring": "Gets the session for retrieving authorization to vault mappings.\n\n        return: (osid.authorization.AuthorizationVaultSession) - an\n                ``AuthorizationVaultSession``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_authorization_vault()`` is\n                ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_authorization_vault()`` is ``true``.*"
  },
  {
    "code": "def delete_operation(self, name, options=None):\n        request = operations_pb2.DeleteOperationRequest(name=name)\n        self._delete_operation(request, options)",
    "docstring": "Deletes a long-running operation. This method indicates that the client is\n        no longer interested in the operation result. It does not cancel the\n        operation. If the server doesn't support this method, it returns\n        ``google.rpc.Code.UNIMPLEMENTED``.\n\n        Example:\n          >>> from google.gapic.longrunning import operations_client\n          >>> api = operations_client.OperationsClient()\n          >>> name = ''\n          >>> api.delete_operation(name)\n\n        Args:\n          name (string): The name of the operation resource to be deleted.\n          options (:class:`google.gax.CallOptions`): Overrides the default\n            settings for this call, e.g, timeout, retries etc.\n\n        Raises:\n          :exc:`google.gax.errors.GaxError` if the RPC is aborted.\n          :exc:`ValueError` if the parameters are invalid."
  },
  {
    "code": "def builtin_info(builtin):\n    help_obj = load_template_help(builtin)\n    if help_obj.get('name') and help_obj.get('help'):\n        print(\"The %s template\" % (help_obj['name']))\n        print(help_obj['help'])\n    else:\n        print(\"No help for %s\" % builtin)\n    if help_obj.get('args'):\n        for arg, arg_help in iteritems(help_obj['args']):\n            print(\"  %-*s %s\" % (20, arg, arg_help))",
    "docstring": "Show information on a particular builtin template"
  },
  {
    "code": "def connect(self, *args, **kwargs):\n        self.connection = DynamoDBConnection.connect(*args, **kwargs)\n        self._session = kwargs.get(\"session\")\n        if self._session is None:\n            self._session = botocore.session.get_session()",
    "docstring": "Proxy to DynamoDBConnection.connect."
  },
  {
    "code": "def prefixes(self, key):\n        res = []\n        index = self.dct.ROOT\n        if not isinstance(key, bytes):\n            key = key.encode('utf8')\n        pos = 1\n        for ch in key:\n            index = self.dct.follow_char(int_from_byte(ch), index)\n            if not index:\n                break\n            if self._has_value(index):\n                res.append(key[:pos].decode('utf8'))\n            pos += 1\n        return res",
    "docstring": "Returns a list with keys of this DAWG that are prefixes of the ``key``."
  },
  {
    "code": "def start(backdate=None):\n    if f.s.cum:\n        raise StartError(\"Already have stamps, can't start again (must reset).\")\n    if f.t.subdvsn_awaiting or f.t.par_subdvsn_awaiting:\n        raise StartError(\"Already have subdivisions, can't start again (must reset).\")\n    if f.t.stopped:\n        raise StoppedError(\"Timer already stopped (must open new or reset).\")\n    t = timer()\n    if backdate is None:\n        t_start = t\n    else:\n        if f.t is f.root:\n            raise BackdateError(\"Cannot backdate start of root timer.\")\n        if not isinstance(backdate, float):\n            raise TypeError(\"Backdate must be type float.\")\n        if backdate > t:\n            raise BackdateError(\"Cannot backdate to future time.\")\n        if backdate < f.tm1.last_t:\n            raise BackdateError(\"Cannot backdate start to time previous to latest stamp in parent timer.\")\n        t_start = backdate\n    f.t.paused = False\n    f.t.tmp_total = 0.\n    f.t.start_t = t_start\n    f.t.last_t = t_start\n    return t",
    "docstring": "Mark the start of timing, overwriting the automatic start data written on\n    import, or the automatic start at the beginning of a subdivision.\n\n    Notes:\n        Backdating: For subdivisions only.  Backdate time must be in the past\n        but more recent than the latest stamp in the parent timer.\n\n    Args:\n        backdate (float, optional): time to use for start instead of current.\n\n    Returns:\n        float: The current time.\n\n    Raises:\n        BackdateError: If given backdate time is out of range or used in root timer.\n        StartError: If the timer is not in a pristine state (if any stamps or\n            subdivisions, must reset instead).\n        StoppedError: If the timer is already stopped (must reset instead).\n        TypeError: If given backdate value is not type float."
  },
  {
    "code": "def element_exists(self, element):\n        if not self.__elements:\n            return False\n        for item in foundations.walkers.dictionaries_walker(self.__elements):\n            path, key, value = item\n            if key == element:\n                LOGGER.debug(\"> '{0}' attribute exists.\".format(element))\n                return True\n        LOGGER.debug(\"> '{0}' element doesn't exists.\".format(element))\n        return False",
    "docstring": "Checks if given element exists.\n\n        Usage::\n\n            >>> plist_file_parser = PlistFileParser(\"standard.plist\")\n            >>> plist_file_parser.parse()\n            True\n            >>> plist_file_parser.element_exists(\"String A\")\n            True\n            >>> plist_file_parser.element_exists(\"String Nemo\")\n            False\n\n        :param element: Element to check existence.\n        :type element: unicode\n        :return: Element existence.\n        :rtype: bool"
  },
  {
    "code": "def _load_script(self):\n        script_text = filesystem.read_file(self.path, self.filename)\n        if not script_text:\n            raise IOError(\"Script file could not be opened or was empty: {0}\"\n                          \"\".format(os.path.join(self.path, self.filename)))\n        self.script = script_text",
    "docstring": "Loads the script from the filesystem\n\n        :raises exceptions.IOError: if the script file could not be opened"
  },
  {
    "code": "def CountHuntResultsByType(self, hunt_id, cursor=None):\n    hunt_id_int = db_utils.HuntIDToInt(hunt_id)\n    query = (\"SELECT type, COUNT(*) FROM flow_results \"\n             \"WHERE hunt_id = %s GROUP BY type\")\n    cursor.execute(query, [hunt_id_int])\n    return dict(cursor.fetchall())",
    "docstring": "Counts number of hunts results per type."
  },
  {
    "code": "def inserir(\n            self,\n            nome,\n            protegida,\n            descricao,\n            id_ligacao_front,\n            id_ligacao_back,\n            id_equipamento,\n            tipo=None,\n            vlan=None):\n        interface_map = dict()\n        interface_map['nome'] = nome\n        interface_map['protegida'] = protegida\n        interface_map['descricao'] = descricao\n        interface_map['id_ligacao_front'] = id_ligacao_front\n        interface_map['id_ligacao_back'] = id_ligacao_back\n        interface_map['id_equipamento'] = id_equipamento\n        interface_map['tipo'] = tipo\n        interface_map['vlan'] = vlan\n        code, xml = self.submit(\n            {'interface': interface_map}, 'POST', 'interface/')\n        return self.response(code, xml)",
    "docstring": "Insert new interface for an equipment.\n\n        :param nome: Interface name.\n        :param protegida: Indication of protected ('0' or '1').\n        :param descricao: Interface description.\n        :param id_ligacao_front: Front end link interface identifier.\n        :param id_ligacao_back: Back end link interface identifier.\n        :param id_equipamento: Equipment identifier.\n\n        :return: Dictionary with the following: {'interface': {'id': < id >}}\n\n        :raise EquipamentoNaoExisteError: Equipment does not exist.\n        :raise InvalidParameterError: The parameters nome, protegida and/or equipment id are none or invalid.\n        :raise NomeInterfaceDuplicadoParaEquipamentoError: There is already an interface with this name for this equipment.\n        :raise InterfaceNaoExisteError: Front link interface and/or back link interface doesn't exist.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def week_date(self, start: int = 2017, end: int = 2018) -> str:\n        year = self.year(start, end)\n        week = self.random.randint(1, 52)\n        return '{year}-W{week}'.format(\n            year=year,\n            week=week,\n        )",
    "docstring": "Get week number with year.\n\n        :param start: From start.\n        :param end: To end.\n        :return: Week number."
  },
  {
    "code": "def asd(M1, M2):\n    from scipy.fftpack import fft2\n    spectra1 = np.abs(fft2(M1))\n    spectra2 = np.abs(fft2(M2))\n    return np.linalg.norm(spectra2 - spectra1)",
    "docstring": "Compute a Fourier transform based distance\n    between two matrices.\n\n    Inspired from Galiez et al., 2015\n    (https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4535829/)"
  },
  {
    "code": "def xmltreefromstring(s):\n    if sys.version < '3':\n        if isinstance(s,unicode):\n            s = s.encode('utf-8')\n        try:\n            return ElementTree.parse(StringIO(s), ElementTree.XMLParser(collect_ids=False))\n        except TypeError:\n            return ElementTree.parse(StringIO(s), ElementTree.XMLParser())\n    else:\n        if isinstance(s,str):\n            s = s.encode('utf-8')\n        try:\n            return ElementTree.parse(BytesIO(s), ElementTree.XMLParser(collect_ids=False))\n        except TypeError:\n            return ElementTree.parse(BytesIO(s), ElementTree.XMLParser())",
    "docstring": "Internal function, deals with different Python versions, unicode strings versus bytes, and with the leak bug in lxml"
  },
  {
    "code": "def fit(self, data):\n        jmodel = callMLlibFunc(\"fitChiSqSelector\", self.selectorType, self.numTopFeatures,\n                               self.percentile, self.fpr, self.fdr, self.fwe, data)\n        return ChiSqSelectorModel(jmodel)",
    "docstring": "Returns a ChiSquared feature selector.\n\n        :param data: an `RDD[LabeledPoint]` containing the labeled dataset\n                     with categorical features. Real-valued features will be\n                     treated as categorical for each distinct value.\n                     Apply feature discretizer before using this function."
  },
  {
    "code": "def validate_conversion_arguments(to_wrap):\n    @functools.wraps(to_wrap)\n    def wrapper(*args, **kwargs):\n        _assert_one_val(*args, **kwargs)\n        if kwargs:\n            _validate_supported_kwarg(kwargs)\n        if len(args) == 0 and \"primitive\" not in kwargs:\n            _assert_hexstr_or_text_kwarg_is_text_type(**kwargs)\n        return to_wrap(*args, **kwargs)\n    return wrapper",
    "docstring": "Validates arguments for conversion functions.\n    - Only a single argument is present\n    - Kwarg must be 'primitive' 'hexstr' or 'text'\n    - If it is 'hexstr' or 'text' that it is a text type"
  },
  {
    "code": "def alias_activity(self, activity_id, alias_id):\n        self._alias_id(primary_id=activity_id, equivalent_id=alias_id)",
    "docstring": "Adds an ``Id`` to an ``Activity`` for the purpose of creating compatibility.\n\n        The primary ``Id`` of the ``Activity`` is determined by the\n        provider. The new ``Id`` performs as an alias to the primary\n        ``Id``. If the alias is a pointer to another activity, it is\n        reassigned to the given activity ``Id``.\n\n        arg:    activity_id (osid.id.Id): the ``Id`` of an ``Activity``\n        arg:    alias_id (osid.id.Id): the alias ``Id``\n        raise:  AlreadyExists - ``alias_id`` is already assigned\n        raise:  NotFound - ``activity_id`` not found\n        raise:  NullArgument - ``activity_id`` or ``alias_id`` is\n                ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def CreateTypes(self, allTypes):\n      enumTypes, dataTypes, managedTypes = self._ConvertAllTypes(allTypes)\n      self._CreateAllTypes(enumTypes, dataTypes, managedTypes)",
    "docstring": "Create pyVmomi types from vmodl.reflect.DynamicTypeManager.AllTypeInfo"
  },
  {
    "code": "def getAllNodes(self):\n        ret = TagCollection()\n        for rootNode in self.getRootNodes():\n            ret.append(rootNode)\n            ret += rootNode.getAllChildNodes()\n        return ret",
    "docstring": "getAllNodes - Get every element\n\n            @return TagCollection<AdvancedTag>"
  },
  {
    "code": "def get_as_boolean(self, key):\n        value = self.get(key)\n        return BooleanConverter.to_boolean(value)",
    "docstring": "Converts map element into a boolean or returns false if conversion is not possible.\n\n        :param key: an index of element to get.\n\n        :return: boolean value ot the element or false if conversion is not supported."
  },
  {
    "code": "def api_params(service, file_id, owner_token, download_limit):\n    service += 'api/params/%s' % file_id\n    r = requests.post(service, json={'owner_token': owner_token, 'dlimit': download_limit})\n    r.raise_for_status()\n    if r.text == 'OK':\n        return True\n    return False",
    "docstring": "Change the download limit for a file hosted on a Send Server"
  },
  {
    "code": "def __recordFmt(self):\r\n        if not self.numRecords:\r\n            self.__dbfHeader()\r\n        fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in self.fields])\r\n        fmtSize = calcsize(fmt)\r\n        return (fmt, fmtSize)",
    "docstring": "Calculates the size of a .shp geometry record."
  },
  {
    "code": "def Uptime():\n    uptime = ''\n    try:\n        uptime = check_output(['uptime'], close_fds=True).decode('utf-8')[1:]\n    except Exception as e:\n        logger.error('Could not get current uptime ' + str(e))\n    return uptime",
    "docstring": "Get the current uptime information"
  },
  {
    "code": "def add_field(self, fieldname, fieldspec=whoosh_module_fields.TEXT):\n    self._whoosh.add_field(fieldname, fieldspec)\n    return self._whoosh.schema",
    "docstring": "Add a field in the index of the model.\n\n    Args:\n        fieldname (Text): This parameters register a new field in specified model.\n        fieldspec (Name, optional): This option adds various options as were described before.\n\n    Returns:\n        TYPE: The new schema after deleted is returned."
  },
  {
    "code": "def restart_agent(self, agent_id, **kwargs):\n        host_medium = self.get_medium('host_agent')\n        agent = host_medium.get_agent()\n        d = host_medium.get_document(agent_id)\n        d.addCallback(\n            lambda desc: agent.start_agent(desc.doc_id, **kwargs))\n        return d",
    "docstring": "tells the host agent running in this agency to restart the agent."
  },
  {
    "code": "def summary(self, scoring):\n        if scoring == 'class_confusion':\n            print('*' * 50)\n            print('  Confusion Matrix ')\n            print('x-axis: ' + ' | '.join(list(self.class_dictionary.keys())))\n            print('y-axis: ' + ' | '.join(self.truth_classes))\n            print(self.confusion_matrix())",
    "docstring": "Prints out the summary of validation for giving scoring function."
  },
  {
    "code": "def namedb_get_account_history(cur, address, offset=None, count=None):\n    sql = 'SELECT * FROM accounts WHERE address = ? ORDER BY block_id DESC, vtxindex DESC'\n    args = (address,)\n    if count is not None:\n        sql += ' LIMIT ?'\n        args += (count,)\n    if offset is not None:\n        sql += ' OFFSET ?'\n        args += (offset,)\n    sql += ';'\n    rows = namedb_query_execute(cur, sql, args)\n    ret = []\n    for rowdata in rows:\n        tmp = {}\n        tmp.update(rowdata)\n        ret.append(tmp)\n    return ret",
    "docstring": "Get the history of an account's tokens"
  },
  {
    "code": "def GetPythonLibraryDirectoryPath():\n  path = sysconfig.get_python_lib(True)\n  _, _, path = path.rpartition(sysconfig.PREFIX)\n  if path.startswith(os.sep):\n    path = path[1:]\n  return path",
    "docstring": "Retrieves the Python library directory path."
  },
  {
    "code": "def _make_request_data(self, teststep_dict, entry_json):\n        method = entry_json[\"request\"].get(\"method\")\n        if method in [\"POST\", \"PUT\", \"PATCH\"]:\n            postData = entry_json[\"request\"].get(\"postData\", {})\n            mimeType = postData.get(\"mimeType\")\n            if \"text\" in postData:\n                post_data = postData.get(\"text\")\n            else:\n                params = postData.get(\"params\", [])\n                post_data = utils.convert_list_to_dict(params)\n            request_data_key = \"data\"\n            if not mimeType:\n                pass\n            elif mimeType.startswith(\"application/json\"):\n                try:\n                    post_data = json.loads(post_data)\n                    request_data_key = \"json\"\n                except JSONDecodeError:\n                    pass\n            elif mimeType.startswith(\"application/x-www-form-urlencoded\"):\n                post_data = utils.convert_x_www_form_urlencoded_to_dict(post_data)\n            else:\n                pass\n            teststep_dict[\"request\"][request_data_key] = post_data",
    "docstring": "parse HAR entry request data, and make teststep request data\n\n        Args:\n            entry_json (dict):\n                {\n                    \"request\": {\n                        \"method\": \"POST\",\n                        \"postData\": {\n                            \"mimeType\": \"application/x-www-form-urlencoded; charset=utf-8\",\n                            \"params\": [\n                                {\"name\": \"a\", \"value\": 1},\n                                {\"name\": \"b\", \"value\": \"2\"}\n                            }\n                        },\n                    },\n                    \"response\": {...}\n                }\n\n\n        Returns:\n            {\n                \"request\": {\n                    \"method\": \"POST\",\n                    \"data\": {\"v\": \"1\", \"w\": \"2\"}\n                }\n            }"
  },
  {
    "code": "def in6_6to4ExtractAddr(addr):\n    try:\n        addr = inet_pton(socket.AF_INET6, addr)\n    except:\n        return None\n    if addr[:2] != b\" \\x02\":\n        return None\n    return inet_ntop(socket.AF_INET, addr[2:6])",
    "docstring": "Extract IPv4 address embbeded in 6to4 address. Passed address must be\n    a 6to4 addrees. None is returned on error."
  },
  {
    "code": "def set_cache_impl(self, cache_impl, maxsize, **kwargs):\n        new_cache = self._get_cache_impl(cache_impl, maxsize, **kwargs)\n        self._populate_new_cache(new_cache)\n        self.cache = new_cache",
    "docstring": "Change cache implementation. The contents of the old cache will\n        be transferred to the new one.\n\n        :param cache_impl: Name of cache implementation, must exist in AVAILABLE_CACHES"
  },
  {
    "code": "def hide_announcement_view(request):\n    if request.method == \"POST\":\n        announcement_id = request.POST.get(\"announcement_id\")\n        if announcement_id:\n            announcement = Announcement.objects.get(id=announcement_id)\n            try:\n                announcement.user_map.users_hidden.add(request.user)\n                announcement.user_map.save()\n            except IntegrityError:\n                logger.warning(\"Duplicate value when hiding announcement {} for {}.\".format(announcement_id, request.user.username))\n            return http.HttpResponse(\"Hidden\")\n        raise http.Http404\n    else:\n        return http.HttpResponseNotAllowed([\"POST\"], \"HTTP 405: METHOD NOT ALLOWED\")",
    "docstring": "Hide an announcement for the logged-in user.\n\n        announcements_hidden in the user model is the related_name for\n        \"users_hidden\" in the announcement model."
  },
  {
    "code": "def get_buildfile_path(settings):\n    base = os.path.basename(settings.build_url)\n    return os.path.join(BUILDS_ROOT, base)",
    "docstring": "Path to which a build tarball should be downloaded."
  },
  {
    "code": "def transfer(self, receiver_address, amount, sender_account):\n        self._keeper.token.token_approve(receiver_address, amount,\n                                         sender_account)\n        self._keeper.token.transfer(receiver_address, amount, sender_account)",
    "docstring": "Transfer a number of tokens from `sender_account` to `receiver_address`\n\n        :param receiver_address: hex str ethereum address to receive this transfer of tokens\n        :param amount: int number of tokens to transfer\n        :param sender_account: Account instance to take the tokens from\n        :return: bool"
  },
  {
    "code": "def get_filter(filetypes, ext):\n    if not ext:\n        return ALL_FILTER\n    for title, ftypes in filetypes:\n        if ext in ftypes:\n            return _create_filter(title, ftypes)\n    else:\n        return ''",
    "docstring": "Return filter associated to file extension"
  },
  {
    "code": "def purview_state(self, direction):\n        return {\n            Direction.CAUSE: self.before_state,\n            Direction.EFFECT: self.after_state\n        }[direction]",
    "docstring": "The state of the purview when we are computing coefficients in\n        ``direction``.\n\n        For example, if we are computing the cause coefficient of a mechanism\n        in ``after_state``, the direction is``CAUSE`` and the ``purview_state``\n        is ``before_state``."
  },
  {
    "code": "def IterateAllClientSnapshots(self, min_last_ping=None, batch_size=50000):\n    all_client_ids = self.ReadAllClientIDs(min_last_ping=min_last_ping)\n    for batch in collection.Batch(all_client_ids, batch_size):\n      res = self.MultiReadClientSnapshot(batch)\n      for snapshot in itervalues(res):\n        if snapshot:\n          yield snapshot",
    "docstring": "Iterates over all available clients and yields client snapshot objects.\n\n    Args:\n      min_last_ping: If provided, only snapshots for clients with last-ping\n        timestamps newer than (or equal to) the given value will be returned.\n      batch_size: Always reads <batch_size> snapshots at a time.\n\n    Yields:\n      An rdfvalues.objects.ClientSnapshot object for each client in the db."
  },
  {
    "code": "def run(self):\n        try:\n            threading.Thread.run(self)\n        except Exception:\n            t, v, tb = sys.exc_info()\n            error = traceback.format_exception_only(t, v)[0][:-1]\n            tback = (self.name + ' Traceback (most recent call last):\\n' +\n                     ''.join(traceback.format_tb(tb)))\n            self.fifo.put((self.name, error, tback))",
    "docstring": "Version of run that traps Exceptions and stores\n        them in the fifo"
  },
  {
    "code": "def search_games(self, query, live=True):\n        r = self.kraken_request('GET', 'search/games',\n                                params={'query': query,\n                                        'type': 'suggest',\n                                        'live': live})\n        games = models.Game.wrap_search(r)\n        for g in games:\n            self.fetch_viewers(g)\n        return games",
    "docstring": "Search for games that are similar to the query\n\n        :param query: the query string\n        :type query: :class:`str`\n        :param live: If true, only returns games that are live on at least one\n                     channel\n        :type live: :class:`bool`\n        :returns: A list of games\n        :rtype: :class:`list` of :class:`models.Game` instances\n        :raises: None"
  },
  {
    "code": "def _print_quota(self, conn):\n        quota = conn.get_send_quota()\n        quota = quota['GetSendQuotaResponse']['GetSendQuotaResult']\n        print \"--- SES Quota ---\"\n        print \"  24 Hour Quota: %s\" % quota['Max24HourSend']\n        print \"  Sent (Last 24 hours): %s\" % quota['SentLast24Hours']\n        print \"  Max sending rate: %s/sec\" % quota['MaxSendRate']",
    "docstring": "Prints some basic quota statistics."
  },
  {
    "code": "def show_deployment(name, namespace='default', **kwargs):\n    cfg = _setup_conn(**kwargs)\n    try:\n        api_instance = kubernetes.client.ExtensionsV1beta1Api()\n        api_response = api_instance.read_namespaced_deployment(name, namespace)\n        return api_response.to_dict()\n    except (ApiException, HTTPError) as exc:\n        if isinstance(exc, ApiException) and exc.status == 404:\n            return None\n        else:\n            log.exception(\n                'Exception when calling '\n                'ExtensionsV1beta1Api->read_namespaced_deployment'\n            )\n            raise CommandExecutionError(exc)\n    finally:\n        _cleanup(**cfg)",
    "docstring": "Return the kubernetes deployment defined by name and namespace\n\n    CLI Examples::\n\n        salt '*' kubernetes.show_deployment my-nginx default\n        salt '*' kubernetes.show_deployment name=my-nginx namespace=default"
  },
  {
    "code": "def set_date_bounds(self, date):\n        if date is not None:\n            split = date.split('~')\n            if len(split) == 1:\n                self._lbound = ts2dt(date)\n                self._rbound = ts2dt(date)\n            elif len(split) == 2:\n                if split[0] != '':\n                    self._lbound = ts2dt(split[0])\n                if split[1] != '':\n                    self._rbound = ts2dt(split[1])\n            else:\n                raise Exception('Date %s is not in the correct format' % date)",
    "docstring": "Pass in the date used in the original query.\n\n        :param date: Date (date range) that was queried:\n            date -> 'd', '~d', 'd~', 'd~d'\n            d -> '%Y-%m-%d %H:%M:%S,%f', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d'"
  },
  {
    "code": "def has_next_page(self):\n        return self.current_page < math.ceil(self.total_count / self.per_page)",
    "docstring": "Whether there is a next page or not\n\n        :getter: Return true if there is a next page"
  },
  {
    "code": "def chunk_iter(iterable, n):\n    assert n > 0\n    iterable = iter(iterable)\n    chunk = tuple(itertools.islice(iterable, n))\n    while chunk:\n        yield chunk\n        chunk = tuple(itertools.islice(iterable, n))",
    "docstring": "Yields an iterator in chunks\n\n    For example you can do\n\n    for a, b in chunk_iter([1, 2, 3, 4, 5, 6], 2):\n        print('{} {}'.format(a, b))\n\n    # Prints\n    # 1 2\n    # 3 4\n    # 5 6\n\n    Args:\n        iterable - Some iterable\n        n - Chunk size (must be greater than 0)"
  },
  {
    "code": "def last_timestamp(self, sid, epoch=False):\n        timestamp, value = self.last_datapoint(sid, epoch)\n        return timestamp",
    "docstring": "Get the theoretical last timestamp for a sensor\n\n        Parameters\n        ----------\n        sid : str\n            SensorID\n        epoch : bool\n            default False\n            If True return as epoch\n            If False return as pd.Timestamp\n\n        Returns\n        -------\n        pd.Timestamp | int"
  },
  {
    "code": "def set_comment(self,c):\n        c = ' '+c.replace('-','').strip()+' '\n        self.node.insert(0,etree.Comment(c))",
    "docstring": "Sets the comment for the element\n        @type c: string\n        @param c: comment for the element"
  },
  {
    "code": "def set_rules(rules, overwrite=True, use_conf=False):\n    init(use_conf=False)\n    _ENFORCER.set_rules(rules, overwrite, use_conf)",
    "docstring": "Set rules based on the provided dict of rules.\n\n    Note:\n        Used in tests only.\n\n    :param rules: New rules to use. It should be an instance of dict\n    :param overwrite: Whether to overwrite current rules or update them\n                      with the new rules.\n    :param use_conf: Whether to reload rules from config file."
  },
  {
    "code": "def get_manual_classification_line(self):\n        try:\n            text_log_error = TextLogError.objects.get(step__job=self)\n        except (TextLogError.DoesNotExist, TextLogError.MultipleObjectsReturned):\n            return None\n        from treeherder.model.error_summary import get_useful_search_results\n        search_results = get_useful_search_results(self)\n        if len(search_results) != 1:\n            return None\n        failure_line = text_log_error.get_failure_line()\n        if failure_line is None:\n            return None\n        if not (failure_line.action == \"test_result\" and\n                failure_line.test and\n                failure_line.status and\n                failure_line.expected):\n            return None\n        return text_log_error",
    "docstring": "If this Job has a single TextLogError line, return that TextLogError.\n\n        Some Jobs only have one related [via TextLogStep] TextLogError.  This\n        method checks if this Job is one of those (returning None if not) by:\n        * checking the number of related TextLogErrors\n        * counting the number of search results for the single TextLogError\n        * checking there is a related FailureLine\n        * checking the related FailureLine is in a given state\n\n        If all these checks pass the TextLogError is returned, any failure returns None."
  },
  {
    "code": "def _get_sorted_mosaics(dicom_input):\n    sorted_mosaics = sorted(dicom_input, key=lambda x: x.AcquisitionNumber)\n    for index in range(0, len(sorted_mosaics) - 1):\n        if sorted_mosaics[index].AcquisitionNumber >= sorted_mosaics[index + 1].AcquisitionNumber:\n            raise ConversionValidationError(\"INCONSISTENT_ACQUISITION_NUMBERS\")\n    return sorted_mosaics",
    "docstring": "Search all mosaics in the dicom directory, sort and validate them"
  },
  {
    "code": "def generate_phase_2(phase_1, dim = 40):\n  phase_2 = []\n  for i in range(dim):\n    indices = [numpy.random.randint(0, dim) for i in range(4)]\n    phase_2.append(numpy.prod([phase_1[i] for i in indices]))\n  return phase_2",
    "docstring": "The second step in creating datapoints in the Poirazi & Mel model.\n  This takes a phase 1 vector, and creates a phase 2 vector where each point\n  is the product of four elements of the phase 1 vector, randomly drawn with\n  replacement."
  },
  {
    "code": "def _create_dynamic_subplots(self, key, items, ranges, **init_kwargs):\n        length = self.style_grouping\n        group_fn = lambda x: (x.type.__name__, x.last.group, x.last.label)\n        for i, (k, obj) in enumerate(items):\n            vmap = self.hmap.clone([(key, obj)])\n            self.map_lengths[group_fn(vmap)[:length]] += 1\n            subplot = self._create_subplot(k, vmap, [], ranges)\n            if subplot is None:\n                continue\n            self.subplots[k] = subplot\n            subplot.initialize_plot(ranges, **init_kwargs)\n            subplot.update_frame(key, ranges, element=obj)\n            self.dynamic_subplots.append(subplot)",
    "docstring": "Handles the creation of new subplots when a DynamicMap returns\n        a changing set of elements in an Overlay."
  },
  {
    "code": "def apply_replacements(cfile, replacements):\n    if not replacements:\n        return cfile\n    for rep in replacements:\n        if not rep.get('with_extension', False):\n            cfile, cext = os.path.splitext(cfile)\n        else:\n            cfile = cfile\n            cext = ''\n        if 'is_regex' in rep and rep['is_regex']:\n            cfile = re.sub(rep['match'], rep['replacement'], cfile)\n        else:\n            cfile = cfile.replace(rep['match'], rep['replacement'])\n        cfile = cfile + cext\n    return cfile",
    "docstring": "Applies custom replacements.\n\n    mapping(dict), where each dict contains:\n        'match' - filename match pattern to check against, the filename\n        replacement is applied.\n\n        'replacement' - string used to replace the matched part of the filename\n\n        'is_regex' - if True, the pattern is treated as a\n        regex. If False, simple substring check is used (if\n        'match' in filename). Default is False\n\n        'with_extension' - if True, the file extension is not included in the\n        pattern matching. Default is False\n\n    Example replacements::\n\n        {'match': ':',\n         'replacement': '-',\n         'is_regex': False,\n         'with_extension': False,\n         }\n\n    :param str cfile: name of a file\n    :param list replacements: mapping(dict) filename pattern matching\n                              directives\n    :returns: formatted filename\n    :rtype: str"
  },
  {
    "code": "def show_dropped(self):\n        ctx = _find_context(self.broker)\n        if ctx and ctx.all_files:\n            ds = self.broker.get_by_type(datasource)\n            vals = []\n            for v in ds.values():\n                if isinstance(v, list):\n                    vals.extend(d.path for d in v)\n                else:\n                    vals.append(v.path)\n            dropped = set(ctx.all_files) - set(vals)\n            pprint(\"Dropped Files:\", stream=self.stream)\n            pprint(dropped, indent=4, stream=self.stream)",
    "docstring": "Show dropped files"
  },
  {
    "code": "def encode_async_options(async):\n    options = copy.deepcopy(async._options)\n    options['_type'] = reference_to_path(async.__class__)\n    eta = options.get('task_args', {}).get('eta')\n    if eta:\n        options['task_args']['eta'] = time.mktime(eta.timetuple())\n    callbacks = async._options.get('callbacks')\n    if callbacks:\n        options['callbacks'] = encode_callbacks(callbacks)\n    if '_context_checker' in options:\n        _checker = options.pop('_context_checker')\n        options['__context_checker'] = reference_to_path(_checker)\n    if '_process_results' in options:\n        _processor = options.pop('_process_results')\n        options['__process_results'] = reference_to_path(_processor)\n    return options",
    "docstring": "Encode Async options for JSON encoding."
  },
  {
    "code": "def calcWeightedAvg(data,weights):\n    data_avg = np.mean(data,axis=1)\n    weighted_sum = np.dot(data_avg,weights)\n    return weighted_sum",
    "docstring": "Generates a weighted average of simulated data.  The Nth row of data is averaged\n    and then weighted by the Nth element of weights in an aggregate average.\n\n    Parameters\n    ----------\n    data : numpy.array\n        An array of data with N rows of J floats\n    weights : numpy.array\n        A length N array of weights for the N rows of data.\n\n    Returns\n    -------\n    weighted_sum : float\n        The weighted sum of the data."
  },
  {
    "code": "def remove(self, method: Method):\n        self._table = [fld for fld in self._table if fld is not method]",
    "docstring": "Removes a `method` from the table by identity."
  },
  {
    "code": "def _update_from_api_repr(self, resource):\n        self.destination = resource[\"destination\"]\n        self.filter_ = resource.get(\"filter\")\n        self._writer_identity = resource.get(\"writerIdentity\")",
    "docstring": "Helper for API methods returning sink resources."
  },
  {
    "code": "def connect(sock, addr):\n    try:\n        sock.connect(addr)\n    except ssl.SSLError as e:\n        return (ssl.SSLError, e.strerror if e.strerror else e.message)\n    except socket.herror as (_, msg):\n        return (socket.herror, msg)\n    except socket.gaierror as (_, msg):\n        return (socket.gaierror, msg)\n    except socket.timeout:\n        return (socket.timeout, \"timeout\")\n    except socket.error as e:\n        return (socket.error, e.strerror if e.strerror else e.message)\n    return None",
    "docstring": "Connect to some addr."
  },
  {
    "code": "def reverse_toctree(app, doctree, docname):\n    if docname == \"changes\":\n        for node in doctree.traverse():\n            if node.tagname == \"toctree\" and node.get(\"glob\"):\n                node[\"entries\"].reverse()\n                break",
    "docstring": "Reverse the order of entries in the root toctree if 'glob' is used."
  },
  {
    "code": "def get_ip(request):\n    if getsetting('LOCAL_GEOLOCATION_IP'):\n        return getsetting('LOCAL_GEOLOCATION_IP')\n    forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n    if not forwarded_for:\n        return UNKNOWN_IP\n    for ip in forwarded_for.split(','):\n        ip = ip.strip()\n        if not ip.startswith('10.') and not ip == '127.0.0.1':\n            return ip\n    return UNKNOWN_IP",
    "docstring": "Return the IP address inside the HTTP_X_FORWARDED_FOR var inside\n    the `request` object.\n\n    The return of this function can be overrided by the\n    `LOCAL_GEOLOCATION_IP` variable in the `conf` module.\n\n    This function will skip local IPs (starting with 10. and equals to\n    127.0.0.1)."
  },
  {
    "code": "def parse_xml_node(self, node):\n        self.sequence = int(node.getAttributeNS(RTS_NS, 'sequence'))\n        c = node.getElementsByTagNameNS(RTS_NS, 'TargetComponent')\n        if c.length != 1:\n            raise InvalidParticipantNodeError\n        self.target_component = TargetExecutionContext().parse_xml_node(c[0])\n        for c in get_direct_child_elements_xml(node, prefix=RTS_EXT_NS,\n                                               local_name='Properties'):\n            name, value = parse_properties_xml(c)\n            self._properties[name] = value\n        return self",
    "docstring": "Parse an xml.dom Node object representing a condition into this\n        object."
  },
  {
    "code": "def _perform_power_op(self, oper):\n        power_settings = {\"Action\": \"Reset\",\n                          \"ResetType\": oper}\n        systems_uri = \"/rest/v1/Systems/1\"\n        status, headers, response = self._rest_post(systems_uri, None,\n                                                    power_settings)\n        if status >= 300:\n            msg = self._get_extended_error(response)\n            raise exception.IloError(msg)",
    "docstring": "Perform requested power operation.\n\n        :param oper: Type of power button press to simulate.\n                     Supported values: 'ON', 'ForceOff', 'ForceRestart' and\n                     'Nmi'\n        :raises: IloError, on an error from iLO."
  },
  {
    "code": "def create_profile(self, user, save=False, **kwargs):\n        profile = self.get_model()(user=user, **kwargs)\n        if save:\n            profile.save()\n        return profile",
    "docstring": "Create a profile model.\n\n        :param user: A user object\n        :param save: If this is set, the profile will\n            be saved to DB straight away\n        :type save: bool"
  },
  {
    "code": "def a1_to_rowcol(label):\n    m = CELL_ADDR_RE.match(label)\n    if m:\n        column_label = m.group(1).upper()\n        row = int(m.group(2))\n        col = 0\n        for i, c in enumerate(reversed(column_label)):\n            col += (ord(c) - MAGIC_NUMBER) * (26 ** i)\n    else:\n        raise IncorrectCellLabel(label)\n    return (row, col)",
    "docstring": "Translates a cell's address in A1 notation to a tuple of integers.\n\n    :param label: A cell label in A1 notation, e.g. 'B1'.\n                  Letter case is ignored.\n    :type label: str\n\n    :returns: a tuple containing `row` and `column` numbers. Both indexed\n              from 1 (one).\n\n    Example:\n\n    >>> a1_to_rowcol('A1')\n    (1, 1)"
  },
  {
    "code": "def btc_tx_extend(partial_tx_hex, new_inputs, new_outputs, **blockchain_opts):\n    tx = btc_tx_deserialize(partial_tx_hex)\n    tx_inputs, tx_outputs = tx['ins'], tx['outs']\n    locktime, version = tx['locktime'], tx['version']\n    tx_inputs += new_inputs\n    tx_outputs += new_outputs\n    new_tx = {\n        'ins': tx_inputs,\n        'outs': tx_outputs,\n        'locktime': locktime,\n        'version': version,\n    }\n    new_unsigned_tx = btc_tx_serialize(new_tx)\n    return new_unsigned_tx",
    "docstring": "Given an unsigned serialized transaction, add more inputs and outputs to it.\n    @new_inputs and @new_outputs will be virtualchain-formatted:\n    * new_inputs[i] will have {'outpoint': {'index':..., 'hash':...}, 'script':..., 'witness_script': ...}\n    * new_outputs[i] will have {'script':..., 'value':... (in fundamental units, e.g. satoshis!)}"
  },
  {
    "code": "def getEthernetLinkStatus(self, wanInterfaceId=1, timeout=1):\n        namespace = Wan.getServiceType(\"getEthernetLinkStatus\") + str(wanInterfaceId)\n        uri = self.getControlURL(namespace)\n        results = self.execute(uri, namespace, \"GetEthernetLinkStatus\", timeout=timeout)\n        return results[\"NewEthernetLinkStatus\"]",
    "docstring": "Execute GetEthernetLinkStatus action to get the status of the ethernet link.\n\n        :param int wanInterfaceId: the id of the WAN device\n        :param float timeout: the timeout to wait for the action to be executed\n        :return: status of the ethernet link\n        :rtype: str"
  },
  {
    "code": "def json_hash(obj, digest=None, encoder=None):\n  json_str = json.dumps(obj, ensure_ascii=True, allow_nan=False, sort_keys=True, cls=encoder)\n  return hash_all(json_str, digest=digest)",
    "docstring": "Hashes `obj` by dumping to JSON.\n\n  :param obj: An object that can be rendered to json using the given `encoder`.\n  :param digest: An optional `hashlib` compatible message digest. Defaults to `hashlib.sha1`.\n  :param encoder: An optional custom json encoder.\n  :type encoder: :class:`json.JSONEncoder`\n  :returns: A hash of the given `obj` according to the given `encoder`.\n  :rtype: str\n\n  :API: public"
  },
  {
    "code": "def _verbose(self, msg, level=log.debug):\n        if self.opts.get('verbose', False) is True:\n            self.ui.status(msg)\n        level(msg)",
    "docstring": "Display verbose information"
  },
  {
    "code": "def spliced_offset(self, position):\n        assert type(position) == int, \\\n            \"Position argument must be an integer, got %s : %s\" % (\n                position, type(position))\n        if position < self.start or position > self.end:\n            raise ValueError(\n                \"Invalid position: %d (must be between %d and %d)\" % (\n                    position,\n                    self.start,\n                    self.end))\n        unspliced_offset = self.offset(position)\n        total_spliced_offset = 0\n        for exon in self.exons:\n            exon_unspliced_start, exon_unspliced_end = self.offset_range(\n                exon.start, exon.end)\n            if exon_unspliced_start <= unspliced_offset <= exon_unspliced_end:\n                exon_offset = unspliced_offset - exon_unspliced_start\n                return total_spliced_offset + exon_offset\n            else:\n                exon_length = len(exon)\n                total_spliced_offset += exon_length\n        raise ValueError(\n            \"Couldn't find position %d on any exon of %s\" % (\n                position, self.id))",
    "docstring": "Convert from an absolute chromosomal position to the offset into\n        this transcript\"s spliced mRNA.\n\n        Position must be inside some exon (otherwise raise exception)."
  },
  {
    "code": "def _normalize_address(self, region_id, relative_address, target_region=None):\n        if self._stack_region_map.is_empty and self._generic_region_map.is_empty:\n            return AddressWrapper(region_id, 0, relative_address, False, None)\n        if region_id.startswith('stack_'):\n            absolute_address = self._stack_region_map.absolutize(region_id, relative_address)\n        else:\n            absolute_address = self._generic_region_map.absolutize(region_id, relative_address)\n        stack_base = self._stack_region_map.stack_base\n        if stack_base - self._stack_size < relative_address <= stack_base and \\\n                (target_region is not None and target_region.startswith('stack_')):\n            new_region_id, new_relative_address, related_function_addr = self._stack_region_map.relativize(\n                absolute_address,\n                target_region_id=target_region\n            )\n            return AddressWrapper(new_region_id, self._region_base(new_region_id), new_relative_address, True,\n                                  related_function_addr\n                                  )\n        else:\n            new_region_id, new_relative_address, related_function_addr = self._generic_region_map.relativize(\n                absolute_address,\n                target_region_id=target_region\n            )\n            return AddressWrapper(new_region_id, self._region_base(new_region_id), new_relative_address, False, None)",
    "docstring": "If this is a stack address, we convert it to a correct region and address\n\n        :param region_id: a string indicating which region the address is relative to\n        :param relative_address: an address that is relative to the region parameter\n        :param target_region: the ideal target region that address is normalized to. None means picking the best fit.\n        :return: an AddressWrapper object"
  },
  {
    "code": "def _transform_state_to_string(self, state: State) -> str:\n        return ''.join(str(state[gene]) for gene in self.model.genes)",
    "docstring": "Private method which transform a state to a string.\n\n        Examples\n        --------\n\n        The model contains 2 genes: operon = {0, 1, 2}\n                                    mucuB = {0, 1}\n\n        >>> graph._transform_state_to_string({operon: 1, mucuB: 0})\n        \"10\"\n        >>> graph._transform_state_to_string({operon: 2, mucuB: 1})\n        \"21\""
  },
  {
    "code": "def put_ops(self, key, time, ops):\n        if self._store.get(key) is None:\n            self._store[key] = ops",
    "docstring": "Put an ops only if not already there, otherwise it's a no op."
  },
  {
    "code": "def dead_code_elimination(graph, du, ud):\n    for node in graph.rpo:\n        for i, ins in node.get_loc_with_ins():\n            reg = ins.get_lhs()\n            if reg is not None:\n                if (reg, i) not in du:\n                    if ins.is_call():\n                        ins.remove_defined_var()\n                    elif ins.has_side_effect():\n                        continue\n                    else:\n                        update_chain(graph, i, du, ud)\n                        graph.remove_ins(i)",
    "docstring": "Run a dead code elimination pass.\n    Instructions are checked to be dead. If it is the case, we remove them and\n    we update the DU & UD chains of its variables to check for further dead\n    instructions."
  },
  {
    "code": "def current_item(self):\n        if self._history and self._index >= 0:\n            self._check_index()\n            return self._history[self._index]",
    "docstring": "Return the current element."
  },
  {
    "code": "def rereference(self):\n        selectedItems = self.idx_l0.selectedItems()\n        chan_to_plot = []\n        for selected in selectedItems:\n            chan_to_plot.append(selected.text())\n        self.highlight_channels(self.idx_l1, chan_to_plot)",
    "docstring": "Automatically highlight channels to use as reference, based on\n        selected channels."
  },
  {
    "code": "def get_token_from_authorization_code(self,\n                                          authorization_code, redirect_uri):\n        token_dict = {\n            \"client_id\": self._key,\n            \"client_secret\": self._secret,\n            \"grant_type\": \"authorization_code\",\n            \"code\": authorization_code,\n            \"redirect_uri\": redirect_uri,\n        }\n        response = requests.post(self._token_url, data=token_dict,\n                                 headers={'Accept': 'application/json'},\n                                 timeout=self._timeout)\n        response.raise_for_status()\n        if self.do_store_raw_response:\n            self.raw_response = response\n        return json.loads(response.text)",
    "docstring": "Like `get_token`, but using an OAuth 2 authorization code.\n\n        Use this method if you run a webserver that serves as an endpoint for\n        the redirect URI. The webserver can retrieve the authorization code\n        from the URL that is requested by ORCID.\n\n        Parameters\n        ----------\n        :param redirect_uri: string\n            The redirect uri of the institution.\n        :param authorization_code: string\n            The authorization code.\n\n        Returns\n        -------\n        :returns: dict\n            All data of the access token.  The access token itself is in the\n            ``\"access_token\"`` key."
  },
  {
    "code": "def from_string(cls, xml_string, validate=True):\n        return xmlmap.load_xmlobject_from_string(xml_string, xmlclass=cls, validate=validate)",
    "docstring": "Creates a Python object from a XML string\n\n        :param xml_string: XML string\n        :param validate: XML should be validated against the embedded XSD definition\n        :type validate: Boolean\n        :returns: the Python object"
  },
  {
    "code": "def convert(values):\n    dtype = values.dtype\n    if is_categorical_dtype(values):\n        return values\n    elif is_object_dtype(dtype):\n        return values.ravel().tolist()\n    if needs_i8_conversion(dtype):\n        values = values.view('i8')\n    v = values.ravel()\n    if compressor == 'zlib':\n        _check_zlib()\n        if dtype == np.object_:\n            return v.tolist()\n        v = v.tostring()\n        return ExtType(0, zlib.compress(v))\n    elif compressor == 'blosc':\n        _check_blosc()\n        if dtype == np.object_:\n            return v.tolist()\n        v = v.tostring()\n        return ExtType(0, blosc.compress(v, typesize=dtype.itemsize))\n    return ExtType(0, v.tostring())",
    "docstring": "convert the numpy values to a list"
  },
  {
    "code": "def GetMessage(self, log_source, lcid, message_identifier):\n    event_log_provider_key = self._GetEventLogProviderKey(log_source)\n    if not event_log_provider_key:\n      return None\n    generator = self._GetMessageFileKeys(event_log_provider_key)\n    if not generator:\n      return None\n    message_string = None\n    for message_file_key in generator:\n      message_string = self._GetMessage(\n          message_file_key, lcid, message_identifier)\n      if message_string:\n        break\n    if self._string_format == 'wrc':\n      message_string = self._ReformatMessageString(message_string)\n    return message_string",
    "docstring": "Retrieves a specific message for a specific Event Log source.\n\n    Args:\n      log_source (str): Event Log source.\n      lcid (int): language code identifier (LCID).\n      message_identifier (int): message identifier.\n\n    Returns:\n      str: message string or None if not available."
  },
  {
    "code": "def remove(self, address):\n        recipients = []\n        if isinstance(address, str):\n            address = {address}\n        elif isinstance(address, (list, tuple)):\n            address = set(address)\n        for recipient in self._recipients:\n            if recipient.address not in address:\n                recipients.append(recipient)\n        if len(recipients) != len(self._recipients):\n            self._track_changes()\n        self._recipients = recipients",
    "docstring": "Remove an address or multiple addresses\n\n        :param address: list of addresses to remove\n        :type address: str or list[str]"
  },
  {
    "code": "def _updateNamespace(item, new_namespace):\n    temp_item = ''\n    i = item.tag.find('}')\n    if i >= 0:\n        temp_item = item.tag[i+1:]\n    else:\n        temp_item = item.tag\n    item.tag = '{{{0}}}{1}'.format(new_namespace, temp_item)\n    for child in item.getiterator():\n        if isinstance(child.tag, six.string_types):\n            temp_item = ''\n            i = child.tag.find('}')\n            if i >= 0:\n                temp_item = child.tag[i+1:]\n            else:\n                temp_item = child.tag\n            child.tag = '{{{0}}}{1}'.format(new_namespace, temp_item)\n    return item",
    "docstring": "helper function to recursively update the namespaces of an item"
  },
  {
    "code": "def conv_cond_concat(x, y):\n    x_shapes = x.get_shape()\n    y_shapes = y.get_shape()\n    return tf.concat(3, [x, y*tf.ones([x_shapes[0], x_shapes[1], x_shapes[2], y_shapes[3]])])",
    "docstring": "Concatenate conditioning vector on feature map axis."
  },
  {
    "code": "def naturaltime(val):\n    val = val.replace(tzinfo=pytz.utc) \\\n        if isinstance(val, datetime) else parse(val)\n    now = datetime.utcnow().replace(tzinfo=pytz.utc)\n    return humanize.naturaltime(now - val)",
    "docstring": "Get humanized version of time."
  },
  {
    "code": "def register_target(repo_cmd, repo_service):\n    def decorate(klass):\n        log.debug('Loading service module class: {}'.format(klass.__name__) )\n        klass.command = repo_cmd\n        klass.name = repo_service\n        RepositoryService.service_map[repo_service] = klass\n        RepositoryService.command_map[repo_cmd] = repo_service\n        return klass\n    return decorate",
    "docstring": "Decorator to register a class with an repo_service"
  },
  {
    "code": "def main(pyc_file, asm_path):\n    if os.stat(asm_path).st_size == 0:\n        print(\"Size of assembly file %s is zero\" % asm_path)\n        sys.exit(1)\n    asm = asm_file(asm_path)\n    if not pyc_file and asm_path.endswith('.pyasm'):\n        pyc_file = asm_path[:-len('.pyasm')] + '.pyc'\n    write_pycfile(pyc_file, asm)",
    "docstring": "Create Python bytecode from a Python assembly file.\n\n    ASM_PATH gives the input Python assembly file. We suggest ending the\n    file in .pyc\n\n    If --pyc-file is given, that indicates the path to write the\n    Python bytecode. The path should end in '.pyc'.\n\n    See https://github.com/rocky/python-xasm/blob/master/HOW-TO-USE.rst\n    for how to write a Python assembler file."
  },
  {
    "code": "def accuracy(self, test_set, format=None):\n        if isinstance(test_set, basestring):\n            test_data = self._read_data(test_set)\n        else:\n            test_data = test_set\n        test_features = [(self.extract_features(d), c) for d, c in test_data]\n        return nltk.classify.accuracy(self.classifier, test_features)",
    "docstring": "Compute the accuracy on a test set.\n\n        :param test_set: A list of tuples of the form ``(text, label)``, or a\n            filename.\n        :param format: If ``test_set`` is a filename, the file format, e.g.\n            ``\"csv\"`` or ``\"json\"``. If ``None``, will attempt to detect the\n            file format."
  },
  {
    "code": "def _find_corresponding_multicol_key(key, keys_multicol):\n    for mk in keys_multicol:\n        if key.startswith(mk) and 'of' in key:\n            return mk\n    return None",
    "docstring": "Find the corresponding multicolumn key."
  },
  {
    "code": "def detect_model_num(string):\n    match = re.match(MODEL_NUM_REGEX, string)\n    if match:\n        return int(match.group())\n    return None",
    "docstring": "Takes a string related to a model name and extract its model number.\n\n    For example:\n        '000000-bootstrap.index' => 0"
  },
  {
    "code": "def map_sid2sub(self, sid, sub):\n        self.set('sid2sub', sid, sub)\n        self.set('sub2sid', sub, sid)",
    "docstring": "Store the connection between a Session ID and a subject ID.\n\n        :param sid: Session ID\n        :param sub: subject ID"
  },
  {
    "code": "def _gl_initialize(self):\n        if '.es' in gl.current_backend.__name__:\n            pass\n        else:\n            GL_VERTEX_PROGRAM_POINT_SIZE = 34370\n            GL_POINT_SPRITE = 34913\n            gl.glEnable(GL_VERTEX_PROGRAM_POINT_SIZE)\n            gl.glEnable(GL_POINT_SPRITE)\n        if self.capabilities['max_texture_size'] is None:\n            self.capabilities['gl_version'] = gl.glGetParameter(gl.GL_VERSION)\n            self.capabilities['max_texture_size'] = \\\n                gl.glGetParameter(gl.GL_MAX_TEXTURE_SIZE)\n            this_version = self.capabilities['gl_version'].split(' ')[0]\n            this_version = LooseVersion(this_version)",
    "docstring": "Deal with compatibility; desktop does not have sprites\n        enabled by default. ES has."
  },
  {
    "code": "def _page_gen(self):\n        track = \"\"\n        for page in self.__pages__:\n            track += \"/{page}\".format(page=page)\n        return track",
    "docstring": "Generates The String for pages"
  },
  {
    "code": "def key_deploy(self, host, ret):\n        if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):\n            target = self.targets[host]\n            if target.get('passwd', False) or self.opts['ssh_passwd']:\n                self._key_deploy_run(host, target, False)\n            return ret\n        if ret[host].get('stderr', '').count('Permission denied'):\n            target = self.targets[host]\n            print(('Permission denied for host {0}, do you want to deploy '\n                   'the salt-ssh key? (password required):').format(host))\n            deploy = input('[Y/n] ')\n            if deploy.startswith(('n', 'N')):\n                return ret\n            target['passwd'] = getpass.getpass(\n                    'Password for {0}@{1}: '.format(target['user'], host)\n                )\n            return self._key_deploy_run(host, target, True)\n        return ret",
    "docstring": "Deploy the SSH key if the minions don't auth"
  },
  {
    "code": "def conflicts_with(self, other):\n        if isinstance(other, Requirement):\n            if (self.name_ != other.name_) or (self.range is None) \\\n                    or (other.range is None):\n                return False\n            elif self.conflict:\n                return False if other.conflict \\\n                    else self.range_.issuperset(other.range_)\n            elif other.conflict:\n                return other.range_.issuperset(self.range_)\n            else:\n                return not self.range_.intersects(other.range_)\n        else:\n            if (self.name_ != other.name_) or (self.range is None):\n                return False\n            if self.conflict:\n                return (other.version_ in self.range_)\n            else:\n                return (other.version_ not in self.range_)",
    "docstring": "Returns True if this requirement conflicts with another `Requirement`\n        or `VersionedObject`."
  },
  {
    "code": "def get_package_manager(self, target=None):\n    package_manager = None\n    if target:\n      target_package_manager_field = target.payload.get_field('package_manager')\n      if target_package_manager_field:\n        package_manager = target_package_manager_field.value\n    return self.node_distribution.get_package_manager(package_manager=package_manager)",
    "docstring": "Returns package manager for target argument or global config."
  },
  {
    "code": "def start_map(name,\n              handler_spec,\n              reader_spec,\n              mapper_parameters,\n              shard_count=None,\n              output_writer_spec=None,\n              mapreduce_parameters=None,\n              base_path=None,\n              queue_name=None,\n              eta=None,\n              countdown=None,\n              hooks_class_name=None,\n              _app=None,\n              in_xg_transaction=False):\n  if shard_count is None:\n    shard_count = parameters.config.SHARD_COUNT\n  if mapper_parameters:\n    mapper_parameters = dict(mapper_parameters)\n  mr_params = map_job.JobConfig._get_default_mr_params()\n  if mapreduce_parameters:\n    mr_params.update(mapreduce_parameters)\n  if base_path:\n    mr_params[\"base_path\"] = base_path\n  mr_params[\"queue_name\"] = util.get_queue_name(queue_name)\n  mapper_spec = model.MapperSpec(handler_spec,\n                                 reader_spec,\n                                 mapper_parameters,\n                                 shard_count,\n                                 output_writer_spec=output_writer_spec)\n  if in_xg_transaction and not db.is_in_transaction():\n    logging.warning(\"Expects an opened xg transaction to start mapreduce \"\n                    \"when transactional is True.\")\n  return handlers.StartJobHandler._start_map(\n      name,\n      mapper_spec,\n      mr_params,\n      queue_name=mr_params[\"queue_name\"],\n      eta=eta,\n      countdown=countdown,\n      hooks_class_name=hooks_class_name,\n      _app=_app,\n      in_xg_transaction=in_xg_transaction)",
    "docstring": "Start a new, mapper-only mapreduce.\n\n  Deprecated! Use map_job.start instead.\n\n  If a value can be specified both from an explicit argument and from\n  a dictionary, the value from the explicit argument wins.\n\n  Args:\n    name: mapreduce name. Used only for display purposes.\n    handler_spec: fully qualified name of mapper handler function/class to call.\n    reader_spec: fully qualified name of mapper reader to use\n    mapper_parameters: dictionary of parameters to pass to mapper. These are\n      mapper-specific and also used for reader/writer initialization.\n      Should have format {\"input_reader\": {}, \"output_writer\":{}}. Old\n      deprecated style does not have sub dictionaries.\n    shard_count: number of shards to create.\n    mapreduce_parameters: dictionary of mapreduce parameters relevant to the\n      whole job.\n    base_path: base path of mapreduce library handler specified in app.yaml.\n      \"/mapreduce\" by default.\n    queue_name: taskqueue queue name to be used for mapreduce tasks.\n      see util.get_queue_name.\n    eta: absolute time when the MR should execute. May not be specified\n      if 'countdown' is also supplied. This may be timezone-aware or\n      timezone-naive.\n    countdown: time in seconds into the future that this MR should execute.\n      Defaults to zero.\n    hooks_class_name: fully qualified name of a hooks.Hooks subclass.\n    in_xg_transaction: controls what transaction scope to use to start this MR\n      job. If True, there has to be an already opened cross-group transaction\n      scope. MR will use one entity group from it.\n      If False, MR will create an independent transaction to start the job\n      regardless of any existing transaction scopes.\n\n  Returns:\n    mapreduce id as string."
  },
  {
    "code": "def trunc_list(s: List) -> List:\n    if len(s) > max_list_size:\n        i = max_list_size // 2\n        j = i - 1\n        s = s[:i] + [ELLIPSIS] + s[-j:]\n    return s",
    "docstring": "Truncate lists to maximum length."
  },
  {
    "code": "def output_component(graph, edge_stack, u, v):\n    edge_list = []\n    while len(edge_stack) > 0:\n        edge_id = edge_stack.popleft()\n        edge_list.append(edge_id)\n        edge = graph.get_edge(edge_id)\n        tpl_a = (u, v)\n        tpl_b = (v, u)\n        if tpl_a == edge['vertices'] or tpl_b == edge['vertices']:\n            break\n    return edge_list",
    "docstring": "Helper function to pop edges off the stack and produce a list of them."
  },
  {
    "code": "async def query_firmware(self):\n        _version = await self.request.get(join_path(self._base_path, \"/fwversion\"))\n        _fw = _version.get(\"firmware\")\n        if _fw:\n            _main = _fw.get(\"mainProcessor\")\n            if _main:\n                self._main_processor_version = self._make_version(_main)\n            _radio = _fw.get(\"radio\")\n            if _radio:\n                self._radio_version = self._make_version(_radio)",
    "docstring": "Query the firmware versions."
  },
  {
    "code": "def iter_previewers(self, previewers=None):\n        if self.entry_point_group is not None:\n            self.load_entry_point_group(self.entry_point_group)\n            self.entry_point_group = None\n        previewers = previewers or \\\n            self.app.config.get('PREVIEWER_PREFERENCE', [])\n        for item in previewers:\n            if item in self.previewers:\n                yield self.previewers[item]",
    "docstring": "Get previewers ordered by PREVIEWER_PREVIEWERS_ORDER."
  },
  {
    "code": "def _strftime(pattern, time_struct=time.localtime()):\n    try:\n        return time.strftime(pattern, time_struct)\n    except OSError:\n        dt = datetime.datetime.fromtimestamp(_mktime(time_struct))\n        original = dt.year\n        current = datetime.datetime.now().year\n        dt = dt.replace(year=current)\n        ts = dt.timestamp()\n        if _isdst(dt):\n            ts -= 3600\n        string = time.strftime(pattern, time.localtime(ts))\n        string = string.replace(str(current), str(original))\n        return string",
    "docstring": "Custom strftime because Windows is shit again."
  },
  {
    "code": "def _sequence_range_check(self, result, last):\n        removed = False\n        first = result[-2]\n        v1 = ord(first[1:2] if len(first) > 1 else first)\n        v2 = ord(last[1:2] if len(last) > 1 else last)\n        if v2 < v1:\n            result.pop()\n            result.pop()\n            removed = True\n        else:\n            result.append(last)\n        return removed",
    "docstring": "If range backwards, remove it.\n\n        A bad range will cause the regular expression to fail,\n        so we need to remove it, but return that we removed it\n        so the caller can know the sequence wasn't empty.\n        Caller will have to craft a sequence that makes sense\n        if empty at the end with either an impossible sequence\n        for inclusive sequences or a sequence that matches\n        everything for an exclusive sequence."
  },
  {
    "code": "def check_valid_time_and_sort(df, timescol, days=5, warning=True):\n    timediff = (df[timescol].max() - df[timescol].min()).days\n    if timediff < days:\n        return df.sort_values(timescol).reset_index(drop=True).reset_index()\n    else:\n        if warning:\n            sys.stderr.write(\n                \"\\nWarning: data generated is from more than {} days.\\n\".format(str(days)))\n            sys.stderr.write(\"Likely this indicates you are combining multiple runs.\\n\")\n            sys.stderr.write(\n                \"Plots based on time are invalid and therefore truncated to first {} days.\\n\\n\"\n                .format(str(days)))\n            logging.warning(\"Time plots truncated to first {} days: invalid timespan: {} days\"\n                            .format(str(days), str(timediff)))\n        return df[df[timescol] < timedelta(days=days)] \\\n            .sort_values(timescol) \\\n            .reset_index(drop=True) \\\n            .reset_index()",
    "docstring": "Check if the data contains reads created within the same `days` timeframe.\n\n    if not, print warning and only return part of the data which is within `days` days\n    Resetting the index twice to get also an \"index\" column for plotting the cum_yield_reads plot"
  },
  {
    "code": "def del_actor(self, actor):\n        if _debug: TCPClientDirector._debug(\"del_actor %r\", actor)\n        del self.clients[actor.peer]\n        if self.serviceElement:\n            self.sap_request(del_actor=actor)\n        if actor.peer in self.reconnect:\n            connect_task = FunctionTask(self.connect, actor.peer)\n            connect_task.install_task(_time() + self.reconnect[actor.peer])",
    "docstring": "Remove an actor when the socket is closed."
  },
  {
    "code": "def list_locks(root=None):\n    locks = {}\n    _locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS\n    try:\n        with salt.utils.files.fopen(_locks) as fhr:\n            items = salt.utils.stringutils.to_unicode(fhr.read()).split('\\n\\n')\n            for meta in [item.split('\\n') for item in items]:\n                lock = {}\n                for element in [el for el in meta if el]:\n                    if ':' in element:\n                        lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))\n                if lock.get('solvable_name'):\n                    locks[lock.pop('solvable_name')] = lock\n    except IOError:\n        pass\n    except Exception:\n        log.warning('Detected a problem when accessing %s', _locks)\n    return locks",
    "docstring": "List current package locks.\n\n    root\n        operate on a different root directory.\n\n    Return a dict containing the locked package with attributes::\n\n        {'<package>': {'case_sensitive': '<case_sensitive>',\n                       'match_type': '<match_type>'\n                       'type': '<type>'}}\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' pkg.list_locks"
  },
  {
    "code": "def update(self, instance, validated_data):\n        instance.title = validated_data.get('title', instance.title)\n        instance.code = validated_data.get('code', instance.code)\n        instance.linenos = validated_data.get('linenos', instance.linenos)\n        instance.language = validated_data.get('language', instance.language)\n        instance.style = validated_data.get('style', instance.style)\n        instance.save()\n        return instance",
    "docstring": "Update and return an existing `Snippet` instance, given the validated data."
  },
  {
    "code": "def on_message(self, message):\n        self._record_activity()\n        if hasattr(self, 'ws'):\n            self.ws.write_message(message, binary=isinstance(message, bytes))",
    "docstring": "Called when we receive a message from our client.\n\n        We proxy it to the backend."
  },
  {
    "code": "def exclude(self, **filters):\n        exclude = {'-%s' % key: value for key, value in filters.items()}\n        return self.filter(**exclude)",
    "docstring": "Applies query filters for excluding matching records from result set.\n\n        Args:\n            **filters: Query filters as keyword arguments.\n\n        Returns:\n            Self. Queryset object.\n\n        Examples:\n            >>> Person.objects.exclude(age=None)\n            >>> Person.objects.filter(name__startswith='jo').exclude(age__lte=16)"
  },
  {
    "code": "def mu_so(species, motif, spin_state):\n        try:\n            sp = get_el_sp(species)\n            n = sp.get_crystal_field_spin(coordination=motif, spin_config=spin_state)\n            return np.sqrt(n * (n + 2))\n        except AttributeError:\n            return None",
    "docstring": "Calculates the spin-only magnetic moment for a\n        given species. Only supports transition metals.\n\n        :param species: str or Species\n        :param motif: \"oct\" or \"tet\"\n        :param spin_state: \"high\" or \"low\"\n        :return: spin-only magnetic moment in Bohr magnetons"
  },
  {
    "code": "def get_svg_layers(svg_sources):\n    layers = []\n    width, height = None, None\n    def extract_length(attr):\n        'Extract length in pixels.'\n        match = CRE_MM_LENGTH.match(attr)\n        if match:\n            return INKSCAPE_PPmm.magnitude * float(match.group('length'))\n        else:\n            return float(attr)\n    for svg_source_i in svg_sources:\n        xml_root = etree.parse(svg_source_i)\n        svg_root = xml_root.xpath('/svg:svg', namespaces=INKSCAPE_NSMAP)[0]\n        width = max(extract_length(svg_root.attrib['width']), width)\n        height = max(extract_length(svg_root.attrib['height']), height)\n        layers += svg_root.xpath('//svg:g[@inkscape:groupmode=\"layer\"]',\n                                 namespaces=INKSCAPE_NSMAP)\n    for i, layer_i in enumerate(layers):\n        layer_i.attrib['id'] = 'layer%d' % (i + 1)\n    return (width, height), layers",
    "docstring": "Collect layers from input svg sources.\n\n    Args:\n\n        svg_sources (list) : A list of file-like objects, each containing\n            one or more XML layers.\n\n    Returns\n    -------\n    (width, height), layers : (int, int), list\n        The first item in the tuple is the shape of the largest layer, and the\n        second item is a list of ``Element`` objects (from :mod:`lxml.etree`\n        module), one per SVG layer."
  },
  {
    "code": "def _get_queue_name(cls, queue_name=None):\n        if queue_name is None and cls.queue_name is None:\n            raise LimpydJobsException(\"Queue's name not defined\")\n        if queue_name is None:\n            return cls.queue_name\n        return queue_name",
    "docstring": "Return the given queue_name if defined, else the class's one.\n        If both are None, raise an Exception"
  },
  {
    "code": "async def runRuntLift(self, full, valu=None, cmpr=None):\n        func = self._runtLiftFuncs.get(full)\n        if func is None:\n            raise s_exc.NoSuchLift(mesg='No runt lift implemented for requested property.',\n                                   full=full, valu=valu, cmpr=cmpr)\n        async for buid, rows in func(full, valu, cmpr):\n            yield buid, rows",
    "docstring": "Execute a runt lift function.\n\n        Args:\n            full (str): Property to lift by.\n            valu:\n            cmpr:\n\n        Returns:\n            bytes, list: Yields bytes, list tuples where the list contains a series of\n                key/value pairs which are used to construct a Node object."
  },
  {
    "code": "def expanduser(path):\n    if '~' not in path:\n        return path\n    if os.name == \"nt\":\n        if 'HOME' in os.environ:\n            userhome = os.environ['HOME']\n        elif 'USERPROFILE' in os.environ:\n            userhome = os.environ['USERPROFILE']\n        elif 'HOMEPATH' in os.environ:\n            drive = os.environ.get('HOMEDRIVE', '')\n            userhome = os.path.join(drive, os.environ['HOMEPATH'])\n        else:\n            return path\n    else:\n        userhome = os.path.expanduser('~')\n    def _expanduser(path):\n        return EXPANDUSER_RE.sub(\n            lambda m: m.groups()[0] + userhome + m.groups()[1],\n            path)\n    return os.path.normpath(_expanduser(path))",
    "docstring": "Expand '~' to home directory in the given string.\n\n    Note that this function deliberately differs from the builtin\n    os.path.expanduser() on Linux systems, which expands strings such as\n    '~sclaus' to that user's homedir. This is problematic in rez because the\n    string '~packagename' may inadvertently convert to a homedir, if a package\n    happens to match a username."
  },
  {
    "code": "def parse_delta(__string: str) -> datetime.timedelta:\n    if not __string:\n        return datetime.timedelta(0)\n    match = re.fullmatch(r\n, __string, re.VERBOSE)\n    if not match:\n        raise ValueError('Unable to parse delta {!r}'.format(__string))\n    match_dict = {k: int(v) if v else 0 for k, v in match.groupdict().items()}\n    return datetime.timedelta(**match_dict)",
    "docstring": "Parse ISO-8601 duration string.\n\n    Args:\n        __string: Duration string to parse\n    Returns:\n        Parsed delta object"
  },
  {
    "code": "def _explain(self, tree):\n        self._explaining = True\n        self._call_list = []\n        old_call = self.connection.call\n        def fake_call(command, **kwargs):\n            if command == \"describe_table\":\n                return old_call(command, **kwargs)\n            self._call_list.append((command, kwargs))\n            raise ExplainSignal\n        self.connection.call = fake_call\n        try:\n            ret = self._run(tree[1])\n            try:\n                list(ret)\n            except TypeError:\n                pass\n        finally:\n            self.connection.call = old_call\n            self._explaining = False",
    "docstring": "Set up the engine to do a dry run of a query"
  },
  {
    "code": "def update(self):\n        self._controller.update(self._id, wake_if_asleep=False)\n        data = self._controller.get_state_params(self._id)\n        if data:\n            self.__odometer = data['odometer']\n        data = self._controller.get_gui_params(self._id)\n        if data:\n            if data['gui_distance_units'] == \"mi/hr\":\n                self.measurement = 'LENGTH_MILES'\n            else:\n                self.measurement = 'LENGTH_KILOMETERS'\n            self.__rated = (data['gui_range_display'] == \"Rated\")",
    "docstring": "Update the odometer and the unit of measurement based on GUI."
  },
  {
    "code": "def visit_BinOp(self, node):\n        res = combine(node.op, self.visit(node.left), self.visit(node.right))\n        return self.add(node, res)",
    "docstring": "Combine operands ranges for given operator.\n\n        >>> import gast as ast\n        >>> from pythran import passmanager, backend\n        >>> node = ast.parse('''\n        ... def foo():\n        ...     a = 2\n        ...     c = 3\n        ...     d = a - c''')\n        >>> pm = passmanager.PassManager(\"test\")\n        >>> res = pm.gather(RangeValues, node)\n        >>> res['d']\n        Interval(low=-1, high=-1)"
  },
  {
    "code": "def searchType(libtype):\n    libtype = compat.ustr(libtype)\n    if libtype in [compat.ustr(v) for v in SEARCHTYPES.values()]:\n        return libtype\n    if SEARCHTYPES.get(libtype) is not None:\n        return SEARCHTYPES[libtype]\n    raise NotFound('Unknown libtype: %s' % libtype)",
    "docstring": "Returns the integer value of the library string type.\n\n        Parameters:\n            libtype (str): LibType to lookup (movie, show, season, episode, artist, album, track,\n                                              collection)\n        Raises:\n            :class:`plexapi.exceptions.NotFound`: Unknown libtype"
  },
  {
    "code": "def getChildren(self, returned_properties=None):\n        children_tag = (\"rtc_cm:com.ibm.team.workitem.linktype.\"\n                        \"parentworkitem.children\")\n        rp = returned_properties\n        return (self.rtc_obj\n                    ._get_paged_resources(\"Children\",\n                                          workitem_id=self.identifier,\n                                          customized_attr=children_tag,\n                                          page_size=\"10\",\n                                          returned_properties=rp))",
    "docstring": "Get all the children workitems of this workitem\n\n        If no children, None will be returned.\n\n        :param returned_properties: the returned properties that you want.\n            Refer to :class:`rtcclient.client.RTCClient` for more explanations\n        :return: a :class:`rtcclient.workitem.Workitem` object\n        :rtype: rtcclient.workitem.Workitem"
  },
  {
    "code": "def to_file(self, path):\n        xmp_path = path + '.xmp'\n        if os.path.exists(xmp_path):\n            os.unlink(xmp_path)\n        md_path = path\n        md = GExiv2.Metadata()\n        try:\n            md.open_path(md_path)\n        except GLib.GError:\n            md_path = xmp_path\n            with open(md_path, 'w') as of:\n                of.write(\n)\n            md = GExiv2.Metadata()\n            md.open_path(md_path)\n        md.register_xmp_namespace(\n            'https://github.com/jim-easterbrook/pyctools', 'pyctools')\n        for tag, value in self.data.items():\n            if md.get_tag_type(tag) in ('XmpBag', 'XmpSeq'):\n                md.set_tag_multiple(tag, value)\n            else:\n                md.set_tag_string(tag, value)\n        if self.comment is not None:\n            md.set_comment(self.comment)\n        md.save_file(md_path)",
    "docstring": "Write metadata to an image, video or XMP sidecar file.\n\n        :param str path: The image/video file path name."
  },
  {
    "code": "def remove(mod, persist=False, comment=True):\n    pre_mods = lsmod()\n    res = __salt__['cmd.run_all']('kldunload {0}'.format(mod),\n                            python_shell=False)\n    if res['retcode'] == 0:\n        post_mods = lsmod()\n        mods = _rm_mods(pre_mods, post_mods)\n        persist_mods = set()\n        if persist:\n            persist_mods = _remove_persistent_module(mod, comment)\n        return sorted(list(mods | persist_mods))\n    else:\n        return 'Error removing module {0}: {1}'.format(mod, res['stderr'])",
    "docstring": "Remove the specified kernel module\n\n    mod\n        Name of module to remove\n\n    persist\n        Also remove module from /boot/loader.conf\n\n    comment\n        If persist is set don't remove line from /boot/loader.conf but only\n        comment it\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' kmod.remove vmm"
  },
  {
    "code": "def report_alerts(alerts, output_format='table'):\n    num_alerts = len(alerts)\n    if output_format == 'json':\n        click.echo(json.dumps(alerts, indent=4))\n    else:\n        console.info('Issues found: {0}'.format(num_alerts))\n        if num_alerts > 0:\n            click.echo(tabulate([[a['alert'], a['risk'], a['cweid'], a['url']] for a in alerts],\n                                headers=['Alert', 'Risk', 'CWE ID', 'URL'], tablefmt='grid'))",
    "docstring": "Print our alerts in the given format."
  },
  {
    "code": "def draw_text(self, video_name, out, start, end, x, y, text,\n                  color='0xFFFFFF', show_background=0,\n                  background_color='0x000000', size=16):\n        cfilter = (r\"[0:0]drawtext=fontfile=/Library/Fonts/AppleGothic.ttf:\"\n                   r\"x={x}:y={y}:fontcolor='{font_color}':\"\n                   r\"box={show_background}:\"\n                   r\"boxcolor='{background_color}':\"\n                   r\"text='{text}':fontsize={size}:\"\n                   r\"enable='between(t,{start},{end})'[vout];\"\n                   r\"[0:1]apad=pad_len=0[aout]\")\\\n            .format(x=x, y=y, font_color=color,\n                    show_background=show_background,\n                    background_color=background_color, text=text, start=start,\n                    end=end, size=size)\n        command = ['ffmpeg', '-i', video_name, '-c:v', 'huffyuv', '-y',\n                   '-filter_complex', cfilter,  '-an', '-y',\n                   '-map', '[vout]',\n                   '-map', '[aout]',\n                   out]\n        if self.verbose:\n            print 'Drawing text \"{0}\" onto {1} output as {2}'.format(\n                text,\n                video_name,\n                out,\n            )\n            print ' '.join(command)\n        call(command)",
    "docstring": "Draws text over a video\n        @param video_name : name of video input file\n        @param out : name of video output file\n        @param start : start timecode to draw text hh:mm:ss\n        @param end : end timecode to draw text hh:mm:ss\n        @param x : x position of text (px)\n        @param y : y position of text (px)\n        @param text : text content to draw\n        @param color : text color\n        @param show_background : boolean to show a background box behind the\n                                 text\n        @param background_color : color of background box"
  },
  {
    "code": "def find(self, value):\n        value = str(value).lower()\n        rtn_dict = RegistryDictionary()\n        for key, item in self.items():\n            if value in key.lower():\n                rtn_dict[key] = item\n        return rtn_dict",
    "docstring": "returns a dictionary of items based on the a lowercase search\n\n        args:\n            value: the value to search by"
  },
  {
    "code": "def make_dbm():\n    try:\n        data_dir = config.get('coilmq', 'qstore.dbm.data_dir')\n        cp_ops = config.getint('coilmq', 'qstore.dbm.checkpoint_operations')\n        cp_timeout = config.getint('coilmq', 'qstore.dbm.checkpoint_timeout')\n    except ConfigParser.NoOptionError as e:\n        raise ConfigError('Missing configuration parameter: %s' % e)\n    if not os.path.exists(data_dir):\n        raise ConfigError('DBM directory does not exist: %s' % data_dir)\n    if not os.access(data_dir, os.W_OK | os.R_OK):\n        raise ConfigError('Cannot read and write DBM directory: %s' % data_dir)\n    store = DbmQueue(data_dir, checkpoint_operations=cp_ops,\n                     checkpoint_timeout=cp_timeout)\n    return store",
    "docstring": "Creates a DBM queue store, pulling config values from the CoilMQ configuration."
  },
  {
    "code": "def user_deleted(sender, **kwargs):\n    if kwargs.get('created'):\n        write('user_variations', {'variation': 1}, tags={'action': 'created'})\n        write('user_count', {'total': User.objects.count()})",
    "docstring": "collect metrics about new users signing up"
  },
  {
    "code": "def saveSettings(self):\n        try:\n            self.saveProfile()\n        except Exception as ex:\n            logger.warn(ex)\n            if DEBUGGING:\n                raise\n        finally:\n            self._settingsSaved = True",
    "docstring": "Saves the persistent settings. Only saves the profile."
  },
  {
    "code": "def _copy_stream(src, dest, length=0):\n    if length == 0:\n        shutil.copyfileobj(src, dest)\n        return\n    bytes_left = length\n    while bytes_left > 0:\n        buf_size = min(_BUFFER_SIZE, bytes_left)\n        buf = src.read(buf_size)\n        dest.write(buf)\n        bytes_left -= buf_size",
    "docstring": "Similar to shutil.copyfileobj, but supports limiting data size.\n\n    As for why this is required, refer to\n    https://www.python.org/dev/peps/pep-0333/#input-and-error-streams\n\n    Yes, there are WSGI implementations which do not support EOFs, and\n    believe me, you don't want to debug this.\n\n    Args:\n        src: source file-like object\n        dest: destination file-like object\n        length: optional file size hint\n            If not 0, exactly length bytes will be written.\n            If 0, write will continue until EOF is encountered."
  },
  {
    "code": "def get_host_ip(logHost):\r\n        s = None\r\n        try:\r\n            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n            s.connect((logHost, 80))\r\n            ip = s.getsockname()[0]\r\n            return ip\r\n        except Exception:\r\n            return '127.0.0.1'\r\n        finally:\r\n            if s:\r\n                s.close()",
    "docstring": "If it is not match your local ip, you should fill the PutLogsRequest\r\n        parameter source by yourself."
  },
  {
    "code": "def resizeEvent(self, event):\n        super(XOverlayWidget, self).resizeEvent(event)\n        self.adjustSize()",
    "docstring": "Handles a resize event for this overlay, centering the central widget if\n        one is found.\n\n        :param      event | <QtCore.QEvent>"
  },
  {
    "code": "def get_statements(self):\n        edges = _get_dict_from_list('edges', self.cx)\n        for edge in edges:\n            edge_type = edge.get('i')\n            if not edge_type:\n                continue\n            stmt_type = _stmt_map.get(edge_type)\n            if stmt_type:\n                id = edge['@id']\n                source_agent = self._node_agents.get(edge['s'])\n                target_agent = self._node_agents.get(edge['t'])\n                if not source_agent or not target_agent:\n                    logger.info(\"Skipping edge %s->%s: %s\" %\n                                (self._node_names[edge['s']],\n                                 self._node_names[edge['t']], edge))\n                    continue\n                ev = self._create_evidence(id)\n                if stmt_type == Complex:\n                    stmt = stmt_type([source_agent, target_agent], evidence=ev)\n                else:\n                    stmt = stmt_type(source_agent, target_agent, evidence=ev)\n                self.statements.append(stmt)\n        return self.statements",
    "docstring": "Convert network edges into Statements.\n\n        Returns\n        -------\n        list of Statements\n            Converted INDRA Statements."
  },
  {
    "code": "def update_reg(self, addr, mask, new_val):\n        shift = _mask_to_shift(mask)\n        val = self.read_reg(addr)\n        val &= ~mask\n        val |= (new_val << shift) & mask\n        self.write_reg(addr, val)\n        return val",
    "docstring": "Update register at 'addr', replace the bits masked out by 'mask'\n        with new_val. new_val is shifted left to match the LSB of 'mask'\n\n        Returns just-written value of register."
  },
  {
    "code": "def make_primitive_smoothed(cas_coords, smoothing_level=2):\n    try:\n        s_primitive = make_primitive(cas_coords)\n        for x in range(smoothing_level):\n            s_primitive = make_primitive(s_primitive)\n    except ValueError:\n        raise ValueError(\n            'Smoothing level {0} too high, try reducing the number of rounds'\n            ' or give a longer Chain (curent length = {1}).'.format(\n                smoothing_level, len(cas_coords)))\n    return s_primitive",
    "docstring": "Generates smoothed primitive from a list of coordinates.\n\n    Parameters\n    ----------\n    cas_coords : list(numpy.array or float or tuple)\n        Each element of the list must have length 3.\n    smoothing_level : int, optional\n        Number of times to run the averaging.\n\n    Returns\n    -------\n    s_primitive : list(numpy.array)\n        Each array has length 3.\n\n    Raises\n    ------\n    ValueError\n        If the smoothing level is too great compared to the length\n        of cas_coords."
  },
  {
    "code": "def sphcyl(radius, colat, slon):\n    radius = ctypes.c_double(radius)\n    colat = ctypes.c_double(colat)\n    slon = ctypes.c_double(slon)\n    r = ctypes.c_double()\n    lon = ctypes.c_double()\n    z = ctypes.c_double()\n    libspice.sphcyl_c(radius, colat, slon, ctypes.byref(r), ctypes.byref(lon),\n                      ctypes.byref(z))\n    return r.value, lon.value, z.value",
    "docstring": "This routine converts from spherical coordinates to cylindrical\n    coordinates.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphcyl_c.html\n\n    :param radius: Distance of point from origin.\n    :type radius: float\n    :param colat: Polar angle (co-latitude in radians) of point.\n    :type colat: float\n    :param slon: Azimuthal angle (longitude) of point (radians).\n    :type slon: float\n    :return:\n            Distance of point from z axis,\n            angle (radians) of point from XZ plane,\n            Height of point above XY plane.\n    :rtype: tuple"
  },
  {
    "code": "def _do_highlight(content, query, tag='em'):\n        for term in query:\n            term = term.decode('utf-8')\n            for match in re.findall('[^A-Z]+', term):\n                match_re = re.compile(match, re.I)\n                content = match_re.sub('<%s>%s</%s>' % (tag, term, tag), content)\n        return content",
    "docstring": "Highlight `query` terms in `content` with html `tag`.\n\n        This method assumes that the input text (`content`) does not contain\n        any special formatting.  That is, it does not contain any html tags\n        or similar markup that could be screwed up by the highlighting.\n\n        Required arguments:\n            `content` -- Content to search for instances of `text`\n            `text` -- The text to be highlighted"
  },
  {
    "code": "def register_error_handler(self, error: Union[Type[Exception], int], func: Callable) -> None:\n        self.record_once(lambda state: state.app.register_error_handler(error, func, self.name))",
    "docstring": "Add an error handler function to the blueprint.\n\n        This is designed to be used on the blueprint directly, and\n        has the same arguments as\n        :meth:`~quart.Quart.register_error_handler`. An example usage,\n\n        .. code-block:: python\n\n            def not_found():\n                ...\n\n            blueprint = Blueprint(__name__)\n            blueprint.register_error_handler(404, not_found)"
  },
  {
    "code": "def VerifyStructure(self, parser_mediator, lines):\n    return (re.match(self._VERIFICATION_REGEX, lines) or\n            re.match(self._CHROMEOS_VERIFICATION_REGEX, lines)) is not None",
    "docstring": "Verifies that this is a syslog-formatted file.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between\n          parsers and other components, such as storage and dfvfs.\n      lines (str): one or more lines from the text file.\n\n    Returns:\n      bool: True if this is the correct parser, False otherwise."
  },
  {
    "code": "def option_changed(self, option, value):\r\n        setattr(self, to_text_string(option), value)\r\n        self.shellwidget.set_namespace_view_settings()\r\n        self.refresh_table()",
    "docstring": "Option has changed"
  },
  {
    "code": "def needs_path(f):\n    @wraps(f)\n    def wrapped(pathlike, *args, **kwargs):\n        path = pathlib.Path(pathlike)\n        return f(path, *args, **kwargs)\n    return wrapped",
    "docstring": "Wraps a function that accepts path-like to give it a pathlib.Path"
  },
  {
    "code": "def from_rgb(cls, r: int, g: int, b: int) -> 'ColorCode':\n        c = cls()\n        c._init_rgb(r, g, b)\n        return c",
    "docstring": "Return a ColorCode from a RGB tuple."
  },
  {
    "code": "def set_default_color_scheme(name, replace=True):\n    assert name in sh.COLOR_SCHEME_NAMES\n    set_color_scheme(name, sh.get_color_scheme(name), replace=replace)",
    "docstring": "Reset color scheme to default values"
  },
  {
    "code": "def to_ipa(s, delimiter=' ', all_readings=False, container='[]'):\n    numbered_pinyin = to_pinyin(s, delimiter, all_readings, container, False)\n    ipa = pinyin_to_ipa(numbered_pinyin)\n    return ipa",
    "docstring": "Convert a string's Chinese characters to IPA.\n\n    *s* is a string containing Chinese characters.\n\n    *delimiter* is the character used to indicate word boundaries in *s*.\n    This is used to differentiate between words and characters so that a more\n    accurate reading can be returned.\n\n    *all_readings* is a boolean value indicating whether or not to return all\n    possible readings in the case of words/characters that have multiple\n    readings. *container* is a two character string that is used to\n    enclose words/characters if *all_readings* is ``True``. The default\n    ``'[]'`` is used like this: ``'[READING1/READING2]'``.\n\n    Characters not recognized as Chinese are left untouched."
  },
  {
    "code": "def is_supergroup(self, subgroup):\n        warnings.warn(\"This is not fully functional. Only trivial subsets are \"\n                      \"tested right now. \")\n        return set(subgroup.symmetry_ops).issubset(self.symmetry_ops)",
    "docstring": "True if this group is a supergroup of the supplied group.\n\n        Args:\n            subgroup (SymmetryGroup): Subgroup to test.\n\n        Returns:\n            True if this group is a supergroup of the supplied group."
  },
  {
    "code": "def remove(self):\n        if isfile(self.pid_file):\n            try:\n                remove(self.pid_file)\n            except Exception as e:\n                self.die('Failed to remove PID file: {}'.format(str(e)))\n        else:\n            return True",
    "docstring": "Remove the PID file."
  },
  {
    "code": "def fetch_platform_informations(self, callback):\n        self._protocolVersion = -1\n        self._callback = callback\n        self._request_protocol_version()",
    "docstring": "Fetch platform info from the firmware\n        Should be called at the earliest in the connection sequence"
  },
  {
    "code": "def in_interactions_iter(self, nbunch=None, t=None):\n        if nbunch is None:\n            nodes_nbrs_pred = self._pred.items()\n        else:\n            nodes_nbrs_pred = [(n, self._pred[n]) for n in self.nbunch_iter(nbunch)]\n        for n, nbrs in nodes_nbrs_pred:\n            for nbr in nbrs:\n                if t is not None:\n                    if self.__presence_test(nbr, n, t):\n                        yield (nbr, n, {\"t\": [t]})\n                else:\n                    if nbr in self._pred[n]:\n                        yield (nbr, n, self._pred[n][nbr])",
    "docstring": "Return an iterator over the in interactions present in a given snapshot.\n\n        Edges are returned as tuples in the order (node, neighbor).\n\n        Parameters\n        ----------\n        nbunch : iterable container, optional (default= all nodes)\n            A container of nodes.  The container will be iterated\n            through once.\n        t : snapshot id (default=None)\n            If None the the method returns an iterator over the edges of the flattened graph.\n\n        Returns\n        -------\n        edge_iter : iterator\n            An iterator of (u,v) tuples of interaction.\n\n        Notes\n        -----\n        Nodes in nbunch that are not in the graph will be (quietly) ignored.\n        For directed graphs this returns the out-interaction.\n\n        Examples\n        --------\n        >>> G = dn.DynDiGraph()\n        >>> G.add_interaction(0,1, 0)\n        >>> G.add_interaction(1,2, 0)\n        >>> G.add_interaction(2,3,1)\n        >>> [e for e in G.in_interactions_iter(t=0)]\n        [(0, 1), (1, 2)]\n        >>> list(G.in_interactions_iter())\n        [(0, 1), (1, 2), (2, 3)]"
  },
  {
    "code": "def get_notifications(self, new=True):\n        url = (self._imgur._base_url + \"/3/account/{0}/\"\n               \"notifications\".format(self.name))\n        resp = self._imgur._send_request(url, params=locals(), needs_auth=True)\n        msgs = [Message(msg_dict, self._imgur, has_fetched=True) for msg_dict\n                in resp['messages']]\n        replies = [Comment(com_dict, self._imgur, has_fetched=True) for\n                   com_dict in resp['replies']]\n        return {'messages': msgs, 'replies': replies}",
    "docstring": "Return all the notifications for this user."
  },
  {
    "code": "def arrayuniqify(X, retainorder=False):\n    s = X.argsort()\n    X = X[s]\n    D = np.append([True],X[1:] != X[:-1])\n    if retainorder:\n        DD = np.append(D.nonzero()[0],len(X))\n        ind = [min(s[x:DD[i+1]]) for (i,x) in enumerate(DD[:-1])]\n        ind.sort()\n        return ind\n    else:\n        return [D,s]",
    "docstring": "Very fast uniqify routine for numpy arrays.\n\n    **Parameters**\n\n            **X** :  numpy array\n\n                    Determine the unique elements of this numpy array.\n\n            **retainorder** :  Boolean, optional\n\n                    Whether or not to return indices corresponding to unique \n                    values of `X` that also sort the values.  Default value is \n                    `False`, in which case `[D,s]` is returned.  This can be \n                    used to produce a uniqified version of `X` by simply \n                    taking::\n\n                            X[s][D]\n\n                    or::\n\n                            X[s[D.nonzero()[0]]]\n\n    **Returns**\n\n            **D** :  numpy array\n\n                    List of \"first differences\" in the sorted verion of `X`.  \n                    Returned when `retainorder` is `False` (default).\n\n            **s** :  numpy array\n\n                    Permutation that will sort `X`.  Returned when \n                    `retainorder` is `False` (default).\n\n            **ind** :  numpy array\n\n                    List of indices that correspond to unique values of `X`, \n                    without sorting those values.  Returned when `retainorder` \n                    is `True`.\n\n    **See Also:**\n\n            :func:`tabular.fast.recarrayuniqify`"
  },
  {
    "code": "def extract_operations(self, migrations):\n        operations = []\n        for migration in migrations:\n            for operation in migration.operations:\n                if isinstance(operation, RunSQL):\n                    statements = sqlparse.parse(dedent(operation.sql))\n                    for statement in statements:\n                        operation = SqlObjectOperation.parse(statement)\n                        if operation:\n                            operations.append(operation)\n                            if self.verbosity >= 2:\n                                self.stdout.write(\" > % -100s (%s)\" % (operation, migration))\n        return operations",
    "docstring": "Extract SQL operations from the given migrations"
  },
  {
    "code": "async def send_notification(self, method, args=()):\n        message = self.connection.send_notification(Notification(method, args))\n        await self._send_message(message)",
    "docstring": "Send an RPC notification over the network."
  },
  {
    "code": "def _grains():\n    try:\n        host = __pillar__['proxy']['host']\n        if host:\n            username, password = _find_credentials(host)\n            protocol = __pillar__['proxy'].get('protocol')\n            port = __pillar__['proxy'].get('port')\n            ret = salt.modules.vsphere.system_info(host=host,\n                                                   username=username,\n                                                   password=password,\n                                                   protocol=protocol,\n                                                   port=port)\n            GRAINS_CACHE.update(ret)\n    except KeyError:\n        pass\n    return GRAINS_CACHE",
    "docstring": "Get the grains from the proxied device."
  },
  {
    "code": "def create(self, doc_details):\n        title = '%s.create' % self.__class__.__name__\n        if self.model:\n            doc_details = self.model.validate(doc_details, path_to_root='', object_title='%s(doc_details={...}' % title)\n        from copy import deepcopy\n        new_record = deepcopy(doc_details)\n        url = self.bucket_url + '/'\n        response = requests.post(url, json=new_record)\n        if response.status_code not in (200, 201):\n            response = response.json()\n            raise Exception('%s() error: %s' % (title, response))\n        response = response.json()\n        new_record['_id'] = response['id']\n        new_record['_rev'] = response['rev']\n        return new_record",
    "docstring": "a method to create a new document in the collection\n\n        :param doc_details: dictionary with document details and user id value\n        :return: dictionary with document details and _id and _rev values"
  },
  {
    "code": "def _process_hints(self, analyzed_addrs):\n        while self._pending_function_hints:\n            f = self._pending_function_hints.pop()\n            if f not in analyzed_addrs:\n                new_state = self.project.factory.entry_state(mode='fastpath')\n                new_state.ip = new_state.solver.BVV(f, self.project.arch.bits)\n                if new_state.arch.name in ('MIPS32', 'MIPS64'):\n                    new_state.registers.store('t9', f)\n                new_path_wrapper = CFGJob(f,\n                                          new_state,\n                                          self._context_sensitivity_level\n                                          )\n                self._insert_job(new_path_wrapper)\n                self._register_analysis_job(f, new_path_wrapper)\n                l.debug('Picking a function 0x%x from pending function hints.', f)\n                self.kb.functions.function(new_path_wrapper.func_addr, create=True)\n                break",
    "docstring": "Process function hints in the binary.\n\n        :return: None"
  },
  {
    "code": "def since(self, timestamp=None, version=None, deleted=False):\n        qset = self\n        if timestamp is not None:\n            if isinstance(timestamp, numbers.Real):\n                timestamp = datetime.datetime.fromtimestamp(timestamp)\n            qset = qset.filter(\n                models.Q(created__gt=timestamp) |\n                models.Q(updated__gt=timestamp)\n            )\n        if version is not None:\n            qset = qset.filter(version__gt=version)\n        if not deleted:\n            qset = qset.undeleted()\n        return qset",
    "docstring": "Queries the database for objects updated since timestamp or version\n\n        Arguments:\n\n        timestamp <DateTime=None|int=None> if specified return all objects modified since\n        that specified time. If integer is submitted it is treated like a unix timestamp\n\n        version <int=None> if specified return all objects with a version greater\n        then the one specified\n\n        deleted <bool=False> if true include soft-deleted objects in the result\n\n        Either timestamp or version needs to be provided"
  },
  {
    "code": "def validate(in_, options=None):\n    obj_json = json.load(in_)\n    results = validate_parsed_json(obj_json, options)\n    return results",
    "docstring": "Validate objects from JSON data in a textual stream.\n\n    :param in_: A textual stream of JSON data.\n    :param options: Validation options\n    :return: An ObjectValidationResults instance, or a list of such."
  },
  {
    "code": "def add_it(workbench, file_list, labels):\n    md5s = []\n    for filename in file_list:\n        if filename != '.DS_Store':\n            with open(filename, 'rb') as pe_file:\n                base_name = os.path.basename(filename)\n                md5 = workbench.store_sample(pe_file.read(), base_name, 'exe')\n                workbench.add_node(md5, md5[:6], labels)\n                md5s.append(md5)\n    return md5s",
    "docstring": "Add the given file_list to workbench as samples, also add them as nodes.\n\n    Args:\n        workbench: Instance of Workbench Client.\n        file_list: list of files.\n        labels: labels for the nodes.\n\n    Returns:\n        A list of md5s."
  },
  {
    "code": "def _dedup(items, insensitive):\n    deduped = []\n    if insensitive:\n        i_deduped = []\n        for item in items:\n            lowered = item.lower()\n            if lowered not in i_deduped:\n                deduped.append(item)\n                i_deduped.append(lowered)\n    else:\n        for item in items:\n            if item not in deduped:\n                deduped.append(item)\n    return deduped",
    "docstring": "Deduplicate an item list, and preserve order.\n\n    For case-insensitive lists, drop items if they case-insensitively match\n    a prior item."
  },
  {
    "code": "def save_data(self, trigger_id, **data):\n        title, content = super(ServiceEvernote, self).save_data(trigger_id, **data)\n        trigger = Evernote.objects.get(trigger_id=trigger_id)\n        note_store = self._notestore(trigger_id, data)\n        if isinstance(note_store, evernote.api.client.Store):\n            note = self._notebook(trigger, note_store)\n            note = self._attributes(note, data)\n            content = self._footer(trigger, data, content)\n            note.title = limit_content(title, 255)\n            note = self._content(note, content)\n            return EvernoteMgr.create_note(note_store, note, trigger_id, data)\n        else:\n            return note_store",
    "docstring": "let's save the data\n            don't want to handle empty title nor content\n            otherwise this will produce an Exception by\n            the Evernote's API\n\n            :param trigger_id: trigger ID from which to save data\n            :param data: the data to check to be used and save\n            :type trigger_id: int\n            :type data:  dict\n            :return: the status of the save statement\n            :rtype: boolean"
  },
  {
    "code": "def name(self):\n        return ffi.string(lib.EnvGetDefmessageHandlerName(\n            self._env, self._cls, self._idx)).decode()",
    "docstring": "MessageHandler name."
  },
  {
    "code": "def _jit_predict_fun(model_predict, num_devices):\n  def predict(x, params=(), rng=None):\n    if num_devices == 1:\n      return backend.jit(model_predict)(x, params, rng=rng)\n    @functools.partial(backend.pmap, axis_name=\"batch\")\n    def mapped_predict(x, params, rng):\n      return model_predict(x, params, rng=rng)\n    pred = mapped_predict(\n        reshape_by_device(x, num_devices),\n        params,\n        jax_random.split(rng, num_devices))\n    if not isinstance(x, (list, tuple)):\n      batch_size = x.shape[0]\n      return np.reshape(pred, [batch_size] + list(pred.shape[2:]))\n    batch_size = x[0].shape[0]\n    return [np.reshape(p, [batch_size] + list(p.shape[2:])) for p in pred]\n  return predict",
    "docstring": "Use jit on model_predict if required."
  },
  {
    "code": "def log_weights(self):\n        m = self.kernel.feature_log_prob_[self._match_class_pos()]\n        u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()]\n        return self._prob_inverse_transform(m - u)",
    "docstring": "Log weights as described in the FS framework."
  },
  {
    "code": "def create_assembly_instance(self, assembly_uri, part_uri, configuration):\n        payload = {\n          \"documentId\": part_uri[\"did\"],\n          \"elementId\": part_uri[\"eid\"],\n          \"versionId\": part_uri[\"wvm\"],\n          \"isAssembly\": False,\n          \"isWholePartStudio\": True,\n          \"configuration\": self.encode_configuration(part_uri[\"did\"], part_uri[\"eid\"], configuration)\n        }\n        return self._api.request('post', '/api/assemblies/d/' + assembly_uri[\"did\"] + '/' + assembly_uri[\"wvm_type\"] +\n                                 '/' + assembly_uri[\"wvm\"] + '/e/' + assembly_uri[\"eid\"] + '/instances', body=payload)",
    "docstring": "Insert a configurable part into an assembly.\n\n        Args:\n            - assembly (dict): eid, wid, and did of the assembly into which will be inserted\n            - part (dict): eid and did of the configurable part\n            - configuration (dict): the configuration\n\n        Returns:\n            - requests.Response: Onshape response data"
  },
  {
    "code": "def flaskify(response, headers=None, encoder=None):\n    status_code = response.status\n    data = response.errors or response.message\n    mimetype = 'text/plain'\n    if isinstance(data, list) or isinstance(data, dict):\n        mimetype = 'application/json'\n        data = json.dumps(data, cls=encoder)\n    return flask.Response(\n        response=data, status=status_code, headers=headers, mimetype=mimetype)",
    "docstring": "Format the response to be consumeable by flask.\n\n    The api returns mostly JSON responses. The format method converts the dicts\n    into a json object (as a string), and the right response is returned (with\n    the valid mimetype, charset and status.)\n\n    Args:\n        response (Response): The dictionary object to convert into a json\n            object. If the value is a string, a dictionary is created with the\n            key \"message\".\n        headers (dict): optional headers for the flask response.\n        encoder (Class): The class of the encoder (if any).\n\n    Returns:\n        flask.Response: The flask response with formatted data, headers, and\n            mimetype."
  },
  {
    "code": "def add_letter_to_axis(ax, let, col, x, y, height):\n    if len(let) == 2:\n        colors = [col, \"white\"]\n    elif len(let) == 1:\n        colors = [col]\n    else:\n        raise ValueError(\"3 or more Polygons are not supported\")\n    for polygon, color in zip(let, colors):\n        new_polygon = affinity.scale(\n            polygon, yfact=height, origin=(0, 0, 0))\n        new_polygon = affinity.translate(\n            new_polygon, xoff=x, yoff=y)\n        patch = PolygonPatch(\n            new_polygon, edgecolor=color, facecolor=color)\n        ax.add_patch(patch)\n    return",
    "docstring": "Add 'let' with position x,y and height height to matplotlib axis 'ax'."
  },
  {
    "code": "def init_sources(path):\n    for f in dir_list(path):\n        if(os.path.splitext(f)[1][1:] == config.source_ext):\n            print \"Source file discovered: %s\" % (f)\n            script = Script(f)\n            if (script.filename not in config.sources.keys()):\n                config.sources[script.path] = script\n                parse.parse_dependencies(script,script)",
    "docstring": "initializes array of groups and their associated js files"
  },
  {
    "code": "def create_sync_ops(self, host_device):\n    sync_ops = []\n    host_params = self.params_device[host_device]\n    for device, params in (self.params_device).iteritems():\n      if device == host_device:\n        continue\n      for k in self.params_names:\n        if isinstance(params[k], tf.Variable):\n          sync_ops += [tf.assign(params[k], host_params[k])]\n    return sync_ops",
    "docstring": "Create an assignment operation for each weight on all devices. The\n    weight is assigned the value of the copy on the `host_device'."
  },
  {
    "code": "def _handle_ssh_callback(self, submission_id, host, port, password):\n        if host is not None:\n            obj = {\n                \"ssh_host\": host,\n                \"ssh_port\": port,\n                \"ssh_password\": password\n            }\n            self._database.submissions.update_one({\"_id\": submission_id}, {\"$set\": obj})",
    "docstring": "Handles the creation of a remote ssh server"
  },
  {
    "code": "def get_thread_id(self):\r\n        if self._id is None:\r\n            for thread_id, obj in list(threading._active.items()):\r\n                if obj is self:\r\n                    self._id = thread_id\r\n        return self._id",
    "docstring": "Return thread id"
  },
  {
    "code": "def GetTopicsTree(self):\n        if self.topics is None:\n            return None\n        if self.topics:\n            res, ui = chmlib.chm_resolve_object(self.file, self.topics)\n            if (res != chmlib.CHM_RESOLVE_SUCCESS):\n                return None\n        size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, ui.length)\n        if (size == 0):\n            sys.stderr.write('GetTopicsTree: file size = 0\\n')\n            return None\n        return text",
    "docstring": "Reads and returns the topics tree.\n        This auxiliary function reads and returns the topics tree file\n        contents for the CHM archive."
  },
  {
    "code": "def print_images(self, *printable_images):\n        printable_image = reduce(lambda x, y: x.append(y), list(printable_images))\n        self.print_image(printable_image)",
    "docstring": "This method allows printing several images in one shot. This is useful if the client code does not want the\n        printer to make pause during printing"
  },
  {
    "code": "def delete_rows(self, condition, info_str=None):\n        self.df['num'] = list(range(len(self.df)))\n        df_data = self.df\n        if len(df_data[condition]) > 0:\n            inds = df_data[condition]['num']\n            for ind in inds[::-1]:\n                df_data = self.delete_row(ind)\n                if info_str:\n                    print(\"-I- Deleting {}. \".format(info_str), end=' ')\n                    print('deleting row {}'.format(str(ind)))\n        df_data.sort_index(inplace=True)\n        df_data['num'] = list(range(len(df_data)))\n        self.df = df_data\n        return df_data",
    "docstring": "delete all rows with  condition==True\n        inplace\n\n        Parameters\n        ----------\n        condition : pandas DataFrame indexer\n            all self.df rows that meet this condition will be deleted\n        info_str : str\n            description of the kind of rows to be deleted,\n            e.g \"specimen rows with blank method codes\"\n\n        Returns\n        --------\n        df_data : pandas DataFrame\n            updated self.df"
  },
  {
    "code": "def _parseStats(self, lines, parse_slabs = False):\n        info_dict = {}\n        info_dict['slabs'] = {}\n        for line in lines:\n            mobj = re.match('^STAT\\s(\\w+)\\s(\\S+)$',  line)\n            if mobj:\n                info_dict[mobj.group(1)] = util.parse_value(mobj.group(2), True)\n                continue\n            elif parse_slabs:\n                mobj = re.match('STAT\\s(\\w+:)?(\\d+):(\\w+)\\s(\\S+)$',  line)\n                if mobj:\n                    (slab, key, val) = mobj.groups()[-3:]      \n                    if not info_dict['slabs'].has_key(slab):\n                        info_dict['slabs'][slab] = {}\n                    info_dict['slabs'][slab][key] = util.parse_value(val, True)\n        return info_dict",
    "docstring": "Parse stats output from memcached and return dictionary of stats-\n        \n        @param lines:       Array of lines of input text.\n        @param parse_slabs: Parse slab stats if True.\n        @return:            Stats dictionary."
  },
  {
    "code": "def is_default_port(self):\n        if self.port is None:\n            return False\n        default = DEFAULT_PORTS.get(self.scheme)\n        if default is None:\n            return False\n        return self.port == default",
    "docstring": "A check for default port.\n\n        Return True if port is default for specified scheme,\n        e.g. 'http://python.org' or 'http://python.org:80', False\n        otherwise."
  },
  {
    "code": "def y_axis_transform(compound, new_origin=None,\n                     point_on_y_axis=None,\n                     point_on_xy_plane=None):\n    x_axis_transform(compound, new_origin=new_origin,\n                     point_on_x_axis=point_on_y_axis,\n                     point_on_xy_plane=point_on_xy_plane)\n    rotate_around_z(compound, np.pi / 2)",
    "docstring": "Move a compound such that the y-axis lies on specified points.\n\n    Parameters\n    ----------\n    compound : mb.Compound\n        The compound to move.\n    new_origin : mb.Compound or like-like of size 3, optional, default=[0.0, 0.0, 0.0]\n        Where to place the new origin of the coordinate system.\n    point_on_y_axis : mb.Compound or list-like of size 3, optional, default=[0.0, 1.0, 0.0]\n        A point on the new y-axis.\n    point_on_xy_plane : mb.Compound or list-like of size 3, optional, default=[0.0, 1.0, 0.0]\n        A point on the new xy-plane."
  },
  {
    "code": "def create_account(\n        self,\n        balance=0,\n        address=None,\n        concrete_storage=False,\n        dynamic_loader=None,\n        creator=None,\n    ) -> Account:\n        address = address if address else self._generate_new_address(creator)\n        new_account = Account(\n            address,\n            balance=balance,\n            dynamic_loader=dynamic_loader,\n            concrete_storage=concrete_storage,\n        )\n        self._put_account(new_account)\n        return new_account",
    "docstring": "Create non-contract account.\n\n        :param address: The account's address\n        :param balance: Initial balance for the account\n        :param concrete_storage: Interpret account storage as concrete\n        :param dynamic_loader: used for dynamically loading storage from the block chain\n        :return: The new account"
  },
  {
    "code": "def list_editors(self, node=None):\n        return [editor_node.editor for editor_node in self.list_editor_nodes(node) if editor_node.editor]",
    "docstring": "Returns the Model editors.\n\n        :param node: Node to start walking from.\n        :type node: AbstractNode or AbstractCompositeNode or Object\n        :return: Editors.\n        :rtype: list"
  },
  {
    "code": "def parse_extension_item_param(\n    header: str, pos: int, header_name: str\n) -> Tuple[ExtensionParameter, int]:\n    name, pos = parse_token(header, pos, header_name)\n    pos = parse_OWS(header, pos)\n    value: Optional[str] = None\n    if peek_ahead(header, pos) == \"=\":\n        pos = parse_OWS(header, pos + 1)\n        if peek_ahead(header, pos) == '\"':\n            pos_before = pos\n            value, pos = parse_quoted_string(header, pos, header_name)\n            if _token_re.fullmatch(value) is None:\n                raise InvalidHeaderFormat(\n                    header_name, \"invalid quoted header content\", header, pos_before\n                )\n        else:\n            value, pos = parse_token(header, pos, header_name)\n        pos = parse_OWS(header, pos)\n    return (name, value), pos",
    "docstring": "Parse a single extension parameter from ``header`` at the given position.\n\n    Return a ``(name, value)`` pair and the new position.\n\n    Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs."
  },
  {
    "code": "def find_similar(self, *args, **kwargs):\n        if self.session is not None and self.autosession:\n            self.commit()\n        return self.stable.find_similar(*args, **kwargs)",
    "docstring": "Find similar articles.\n\n        With autosession off, use the index state *before* current session started,\n        so that changes made in the session will not be visible here. With autosession\n        on, close the current session first (so that session changes *are* committed\n        and visible)."
  },
  {
    "code": "def set_thread_params(\n            self, enable=None, count=None, count_offload=None, stack_size=None, no_wait=None):\n        self._set('enable-threads', enable, cast=bool)\n        self._set('no-threads-wait', no_wait, cast=bool)\n        self._set('threads', count)\n        self._set('offload-threads', count_offload)\n        if count:\n            self._section.print_out('Threads per worker: %s' % count)\n        self._set('threads-stacksize', stack_size)\n        return self._section",
    "docstring": "Sets threads related params.\n\n        :param bool enable: Enable threads in the embedded languages.\n            This will allow to spawn threads in your app.\n\n            .. warning:: Threads will simply *not work* if this option is not enabled.\n                There will likely be no error, just no execution of your thread code.\n\n        :param int count: Run each worker in prethreaded mode with the specified number\n            of threads per worker.\n\n            .. warning:: Do not use with ``gevent``.\n\n            .. note:: Enables threads automatically.\n\n        :param int count_offload: Set the number of threads (per-worker) to spawn\n            for offloading. Default: 0.\n\n            These threads run such tasks in a non-blocking/evented way allowing\n            for a huge amount of concurrency. Various components of the uWSGI stack\n            are offload-friendly.\n\n            .. note:: Try to set it to the number of CPU cores to take advantage of SMP.\n\n            * http://uwsgi-docs.readthedocs.io/en/latest/OffloadSubsystem.html\n\n        :param int stack_size: Set threads stacksize.\n\n        :param bool no_wait: Do not wait for threads cancellation on quit/reload."
  },
  {
    "code": "def scientific(number, operation, number2=None, logbase=10):\n    if operation == 'log':\n        return math.log(number, logbase)\n    elif operation == 'acos':\n        return math.acos(number)\n    elif operation == 'asin':\n        return math.asin(number)\n    elif operation == 'atan':\n        return math.atan(number)\n    elif operation == 'cos':\n        return math.cos(number)\n    elif operation == 'hypot':\n        return math.hypot(number, number2)\n    elif operation == 'sin':\n        return math.sin(number)\n    elif operation == 'tan':\n        return math.tan(number)",
    "docstring": "Solve scientific operations manually"
  },
  {
    "code": "def get_rotation_program(pauli_term: PauliTerm) -> Program:\n    meas_basis_change = Program()\n    for index, gate in pauli_term:\n        if gate == 'X':\n            meas_basis_change.inst(RY(-np.pi / 2, index))\n        elif gate == 'Y':\n            meas_basis_change.inst(RX(np.pi / 2, index))\n        elif gate == 'Z':\n            pass\n        else:\n            raise ValueError()\n    return meas_basis_change",
    "docstring": "Generate a rotation program so that the pauli term is diagonal.\n\n    :param pauli_term: The Pauli term used to generate diagonalizing one-qubit rotations.\n    :return: The rotation program."
  },
  {
    "code": "def clean_perms(self):\n        logging.info('Cleaning faulty perms')\n        sesh = self.get_session\n        pvms = (\n            sesh.query(ab_models.PermissionView)\n            .filter(or_(\n                ab_models.PermissionView.permission == None,\n                ab_models.PermissionView.view_menu == None,\n            ))\n        )\n        deleted_count = pvms.delete()\n        sesh.commit()\n        if deleted_count:\n            logging.info('Deleted {} faulty permissions'.format(deleted_count))",
    "docstring": "FAB leaves faulty permissions that need to be cleaned up"
  },
  {
    "code": "def attempt_dev_link_via_import(self, egg):\n        try:\n            imported = __import__(egg)\n        except ImportError:\n            self.logger.warn(\"Tried importing '%s', but that also didn't work.\", egg)\n            self.logger.debug(\"For reference, sys.path is %s\", sys.path)\n            return\n        self.logger.info(\"Importing %s works, however\", egg)\n        try:\n            probable_location = os.path.dirname(imported.__file__)\n        except:\n            self.logger.exception(\"Determining the location failed, however\")\n            return\n        filesystem_egg_link = os.path.join(\n            self.dev_egg_dir,\n            '%s.egg-link' % egg)\n        f = open(filesystem_egg_link, 'w')\n        f.write(probable_location)\n        f.close()\n        self.logger.info('Using sysegg %s for %s', probable_location, egg)\n        self.added.append(filesystem_egg_link)\n        return True",
    "docstring": "Create egg-link to FS location if an egg is found through importing.\n\n        Sometimes an egg *is* installed, but without a proper egg-info file.\n        So we attempt to import the egg in order to return a link anyway.\n\n        TODO: currently it only works with simple package names like\n        \"psycopg2\" and \"mapnik\"."
  },
  {
    "code": "def authorize_url(self, state=''):\n        url = 'https://openapi.youku.com/v2/oauth2/authorize?'\n        params = {\n            'client_id': self.client_id,\n            'response_type': 'code',\n            'state': state,\n            'redirect_uri': self.redirect_uri\n        }\n        return url + urlencode(params)",
    "docstring": "return user authorize url"
  },
  {
    "code": "def get_kwargs(self, args):\n        kwargs = {}\n        argspec = inspect.getargspec(self._func)\n        required = set(argspec.args[:-len(argspec.defaults)]\n                       if argspec.defaults else argspec.args)\n        for arg_name in argspec.args:\n            try:\n                kwargs[arg_name] = getattr(args, arg_name)\n            except AttributeError:\n                if arg_name in required:\n                    raise\n        if argspec.keywords:\n            for key, value in args.__dict__.items():\n                if key in kwargs:\n                    continue\n                kwargs[key] = value\n        return kwargs",
    "docstring": "Given a Namespace object drawn from argparse, determines the\n        keyword arguments to pass to the underlying function.  Note\n        that, if the underlying function accepts all keyword\n        arguments, the dictionary returned will contain the entire\n        contents of the Namespace object.  Also note that an\n        AttributeError will be raised if any argument required by the\n        function is not set in the Namespace object.\n\n        :param args: A Namespace object from argparse."
  },
  {
    "code": "def write(parsed_obj, spec=None, filename=None):\n    if not isinstance(parsed_obj, BreadStruct):\n        raise ValueError(\n            'Object to write must be a structure created '\n            'by bread.parse')\n    if filename is not None:\n        with open(filename, 'wb') as fp:\n            parsed_obj._data_bits[:parsed_obj._length].tofile(fp)\n    else:\n        return bytearray(parsed_obj._data_bits[:parsed_obj._length].tobytes())",
    "docstring": "Writes an object created by `parse` to either a file or a bytearray.\n\n    If the object doesn't end on a byte boundary, zeroes are appended to it\n    until it does."
  },
  {
    "code": "def read_config(conf_dir=DEFAULT_CONFIG_DIR):\n    \"Find and read config file for a directory, return None if not found.\"\n    conf_path = os.path.expanduser(conf_dir)\n    if not os.path.exists(conf_path):\n        if conf_dir != DEFAULT_CONFIG_DIR:\n            raise IOError(\"Config directory not found at %s\" % (conf_path, ))\n    return munge.load_datafile('config', conf_path, default=None)",
    "docstring": "Find and read config file for a directory, return None if not found."
  },
  {
    "code": "def attach(self, engine, log_handler, event_name):\n        if event_name not in State.event_to_attr:\n            raise RuntimeError(\"Unknown event name '{}'\".format(event_name))\n        engine.add_event_handler(event_name, log_handler, self, event_name)",
    "docstring": "Attach the logger to the engine and execute `log_handler` function at `event_name` events.\n\n        Args:\n            engine (Engine): engine object.\n            log_handler (callable): a logging handler to execute\n            event_name: event to attach the logging handler to. Valid events are from :class:`~ignite.engine.Events`\n                or any `event_name` added by :meth:`~ignite.engine.Engine.register_events`."
  },
  {
    "code": "def charge_sign(self):\n        if self.charge > 0:\n            sign = \"+\"\n        elif self.charge < 0:\n            sign = \"–\"\n        else:\n            return \"\"\n        ab = abs(self.charge)\n        if ab > 1:\n            return str(ab) + sign\n        return sign",
    "docstring": "Charge sign text"
  },
  {
    "code": "def set(self, key, value, *args, **kwargs):\n        if self.cfg.jsonpickle:\n            value = jsonpickle.encode(value)\n        return self.conn.set(key, value, *args, **kwargs)",
    "docstring": "Store the given value into Redis.\n\n        :returns: a coroutine"
  },
  {
    "code": "def evaluate(self, train_data, test_data=None, metric='perplexity'):\n        train_data = _check_input(train_data)\n        if test_data is None:\n            test_data = train_data\n        else:\n            test_data = _check_input(test_data)\n        predictions = self.predict(train_data, output_type='probability')\n        topics = self.topics\n        ret = {}\n        ret['perplexity'] = perplexity(test_data,\n                                       predictions,\n                                       topics['topic_probabilities'],\n                                       topics['vocabulary'])\n        return ret",
    "docstring": "Estimate the model's ability to predict new data. Imagine you have a\n        corpus of books. One common approach to evaluating topic models is to\n        train on the first half of all of the books and see how well the model\n        predicts the second half of each book.\n\n        This method returns a metric called perplexity, which  is related to the\n        likelihood of observing these words under the given model. See\n        :py:func:`~turicreate.topic_model.perplexity` for more details.\n\n        The provided `train_data` and `test_data` must have the same length,\n        i.e., both data sets must have the same number of documents; the model\n        will use train_data to estimate which topic the document belongs to, and\n        this is used to estimate the model's performance at predicting the\n        unseen words in the test data.\n\n        See :py:func:`~turicreate.topic_model.TopicModel.predict` for details\n        on how these predictions are made, and see\n        :py:func:`~turicreate.text_analytics.random_split` for a helper function\n        that can be used for making train/test splits.\n\n        Parameters\n        ----------\n        train_data : SArray or SFrame\n            A set of documents to predict topics for.\n\n        test_data : SArray or SFrame, optional\n            A set of documents to evaluate performance on.\n            By default this will set to be the same as train_data.\n\n        metric : str\n            The chosen metric to use for evaluating the topic model.\n            Currently only 'perplexity' is supported.\n\n        Returns\n        -------\n        out : dict\n            The set of estimated evaluation metrics.\n\n        See Also\n        --------\n        predict, turicreate.toolkits.text_analytics.random_split\n\n        Examples\n        --------\n        >>> docs = turicreate.SArray('https://static.turi.com/datasets/nips-text')\n        >>> train_data, test_data = turicreate.text_analytics.random_split(docs)\n        >>> m = turicreate.topic_model.create(train_data)\n        >>> m.evaluate(train_data, test_data)\n        {'perplexity': 2467.530370396021}"
  },
  {
    "code": "def _get_local_users(self, disabled=None):\n        users = dict()\n        path = '/etc/passwd'\n        with salt.utils.files.fopen(path, 'r') as fp_:\n            for line in fp_:\n                line = line.strip()\n                if ':' not in line:\n                    continue\n                name, password, uid, gid, gecos, directory, shell = line.split(':')\n                active = not (password == '*' or password.startswith('!'))\n                if (disabled is False and active) or (disabled is True and not active) or disabled is None:\n                    users[name] = {\n                        'uid': uid,\n                        'git': gid,\n                        'info': gecos,\n                        'home': directory,\n                        'shell': shell,\n                        'disabled': not active\n                    }\n        return users",
    "docstring": "Return all known local accounts to the system."
  },
  {
    "code": "def log_message(self, format, *args):\n        code = args[1][0]\n        levels = {\n            '4': 'warning',\n            '5': 'error'\n        }\n        log_handler = getattr(logger, levels.get(code, 'info'))\n        log_handler(format % args)",
    "docstring": "overrides the ``log_message`` method from the wsgiref server so that\n        normal logging works with whatever configuration the application has\n        been set to.\n\n        Levels are inferred from the HTTP status code, 4XX codes are treated as\n        warnings, 5XX as errors and everything else as INFO level."
  },
  {
    "code": "def root(venv_name):\n    inenv = InenvManager()\n    inenv.get_venv(venv_name)\n    venv = inenv.registered_venvs[venv_name]\n    click.secho(venv['root'])",
    "docstring": "Print the root directory of a virtualenv"
  },
  {
    "code": "def setup_logging(name):\n    logger = logging.getLogger(__name__)\n    if 'NVIM_PYTHON_LOG_FILE' in os.environ:\n        prefix = os.environ['NVIM_PYTHON_LOG_FILE'].strip()\n        major_version = sys.version_info[0]\n        logfile = '{}_py{}_{}'.format(prefix, major_version, name)\n        handler = logging.FileHandler(logfile, 'w', 'utf-8')\n        handler.formatter = logging.Formatter(\n            '%(asctime)s [%(levelname)s @ '\n            '%(filename)s:%(funcName)s:%(lineno)s] %(process)s - %(message)s')\n        logging.root.addHandler(handler)\n        level = logging.INFO\n        if 'NVIM_PYTHON_LOG_LEVEL' in os.environ:\n            lvl = getattr(logging,\n                          os.environ['NVIM_PYTHON_LOG_LEVEL'].strip(),\n                          level)\n            if isinstance(lvl, int):\n                level = lvl\n        logger.setLevel(level)",
    "docstring": "Setup logging according to environment variables."
  },
  {
    "code": "def add_payload(self, payload):\n        if self.payloads:\n            self.payloads[-1].next_payload = payload._type\n        self.payloads.append(payload)",
    "docstring": "Adds a payload to packet, updating last payload's next_payload field"
  },
  {
    "code": "def get_items(self, assessment_taken_id):\n        mgr = self._get_provider_manager('ASSESSMENT', local=True)\n        taken_lookup_session = mgr.get_assessment_taken_lookup_session(proxy=self._proxy)\n        taken_lookup_session.use_federated_bank_view()\n        taken = taken_lookup_session.get_assessment_taken(assessment_taken_id)\n        ils = get_item_lookup_session(runtime=self._runtime, proxy=self._proxy)\n        ils.use_federated_bank_view()\n        item_list = []\n        if 'sections' in taken._my_map:\n            for section_id in taken._my_map['sections']:\n                section = get_assessment_section(Id(section_id),\n                                                 runtime=self._runtime,\n                                                 proxy=self._proxy)\n                for question in section._my_map['questions']:\n                    item_list.append(ils.get_item(Id(question['questionId'])))\n        return ItemList(item_list)",
    "docstring": "Gets the items questioned in a assessment.\n\n        arg:    assessment_taken_id (osid.id.Id): ``Id`` of the\n                ``AssessmentTaken``\n        return: (osid.assessment.ItemList) - the list of assessment\n                questions\n        raise:  NotFound - ``assessment_taken_id`` is not found\n        raise:  NullArgument - ``assessment_taken_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _build_url(self, path):\n        if path.startswith('http://') or path.startswith('https://'):\n            return path\n        else:\n            return '%s%s' % (self._url, path)",
    "docstring": "Returns the full url from path.\n\n        If path is already a url, return it unchanged. If it's a path, append\n        it to the stored url.\n\n        Returns:\n            str: The full URL"
  },
  {
    "code": "def add_nexusport_binding(port_id, vlan_id, vni, switch_ip, instance_id,\n                          is_native=False, ch_grp=0):\n    LOG.debug(\"add_nexusport_binding() called\")\n    session = bc.get_writer_session()\n    binding = nexus_models_v2.NexusPortBinding(port_id=port_id,\n                  vlan_id=vlan_id,\n                  vni=vni,\n                  switch_ip=switch_ip,\n                  instance_id=instance_id,\n                  is_native=is_native,\n                  channel_group=ch_grp)\n    session.add(binding)\n    session.flush()\n    return binding",
    "docstring": "Adds a nexusport binding."
  },
  {
    "code": "def train(self, ftrain):\n        self.coeffs = 0*self.coeffs\n        upoints, wpoints = self.getQuadraturePointsAndWeights()\n        try:\n            fpoints = [ftrain(u) for u in upoints]\n        except TypeError:\n            fpoints = ftrain\n        for ipoly in np.arange(self.N_poly):\n            inds = tuple(self.index_polys[ipoly])\n            coeff = 0.0\n            for (u, q, w) in zip(upoints, fpoints, wpoints):\n                coeff += eval_poly(u, inds, self.J_list)*q*np.prod(w)\n            self.coeffs[inds] = coeff\n        return None",
    "docstring": "Trains the polynomial expansion.\n\n        :param numpy.ndarray/function ftrain: output values corresponding to the\n            quadrature points given by the getQuadraturePoints method to\n            which the expansion should be trained. Or a function that should be evaluated\n            at the quadrature points to give these output values.\n\n        *Sample Usage*::\n\n            >>> thePC = PolySurrogate(dimensions=2)\n            >>> thePC.train(myFunc)\n            >>> predicted_q = thePC.predict([0, 1])\n\n            >>> thePC = PolySurrogate(dimensions=2)\n            >>> U = thePC.getQuadraturePoints()\n            >>> Q = [myFunc(u) for u in U]\n            >>> thePC.train(Q)\n            >>> predicted_q = thePC.predict([0, 1])"
  },
  {
    "code": "def commit_hash(self):\n        commit_hash = None\n        branch = None\n        branch_file = '.git/HEAD'\n        if os.path.isfile(branch_file):\n            with open(branch_file, 'r') as f:\n                try:\n                    branch = f.read().strip().split('/')[2]\n                except IndexError:\n                    pass\n            if branch:\n                hash_file = '.git/refs/heads/{}'.format(branch)\n                if os.path.isfile(hash_file):\n                    with open(hash_file, 'r') as f:\n                        commit_hash = f.read().strip()\n        return commit_hash",
    "docstring": "Return the current commit hash if available.\n\n        This is not a required task so best effort is fine. In other words this is not guaranteed\n        to work 100% of the time."
  },
  {
    "code": "def build_loss(model_logits, sparse_targets):\n  time_major_shape = [FLAGS.unroll_steps, FLAGS.batch_size]\n  flat_batch_shape = [FLAGS.unroll_steps * FLAGS.batch_size, -1]\n  xent = tf.nn.sparse_softmax_cross_entropy_with_logits(\n      logits=tf.reshape(model_logits, flat_batch_shape),\n      labels=tf.reshape(sparse_targets, flat_batch_shape[:-1]))\n  xent = tf.reshape(xent, time_major_shape)\n  sequence_neg_log_prob = tf.reduce_sum(xent, axis=0)\n  return tf.reduce_mean(sequence_neg_log_prob, axis=0)",
    "docstring": "Compute the log loss given predictions and targets."
  },
  {
    "code": "def get_content_hash(self):\n        if not self.rexists():\n            return SCons.Util.MD5signature('')\n        fname = self.rfile().get_abspath()\n        try:\n            cs = SCons.Util.MD5filesignature(fname,\n                chunksize=SCons.Node.FS.File.md5_chunksize*1024)\n        except EnvironmentError as e:\n            if not e.filename:\n                e.filename = fname\n            raise\n        return cs",
    "docstring": "Compute and return the MD5 hash for this file."
  },
  {
    "code": "def buckets_get(self, bucket, projection='noAcl'):\n    args = {'projection': projection}\n    url = Api._ENDPOINT + (Api._BUCKET_PATH % bucket)\n    return google.datalab.utils.Http.request(url, credentials=self._credentials, args=args)",
    "docstring": "Issues a request to retrieve information about a bucket.\n\n    Args:\n      bucket: the name of the bucket.\n      projection: the projection of the bucket information to retrieve.\n    Returns:\n      A parsed bucket information dictionary.\n    Raises:\n      Exception if there is an error performing the operation."
  },
  {
    "code": "def inherit(prop, name, **kwargs):\n    flags = []\n    if kwargs.get('recursive', False):\n        flags.append('-r')\n    if kwargs.get('revert', False):\n        flags.append('-S')\n    res = __salt__['cmd.run_all'](\n        __utils__['zfs.zfs_command'](\n            command='inherit',\n            flags=flags,\n            property_name=prop,\n            target=name,\n        ),\n        python_shell=False,\n    )\n    return __utils__['zfs.parse_command_result'](res, 'inherited')",
    "docstring": "Clears the specified property\n\n    prop : string\n        name of property\n    name : string\n        name of the filesystem, volume, or snapshot\n    recursive : boolean\n        recursively inherit the given property for all children.\n    revert : boolean\n        revert the property to the received value if one exists; otherwise\n        operate as if the -S option was not specified.\n\n    .. versionadded:: 2016.3.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' zfs.inherit canmount myzpool/mydataset [recursive=True|False]"
  },
  {
    "code": "def _factorize_array(values, na_sentinel=-1, size_hint=None,\n                     na_value=None):\n    (hash_klass, _), values = _get_data_algo(values, _hashtables)\n    table = hash_klass(size_hint or len(values))\n    uniques, labels = table.factorize(values, na_sentinel=na_sentinel,\n                                      na_value=na_value)\n    labels = ensure_platform_int(labels)\n    return labels, uniques",
    "docstring": "Factorize an array-like to labels and uniques.\n\n    This doesn't do any coercion of types or unboxing before factorization.\n\n    Parameters\n    ----------\n    values : ndarray\n    na_sentinel : int, default -1\n    size_hint : int, optional\n        Passsed through to the hashtable's 'get_labels' method\n    na_value : object, optional\n        A value in `values` to consider missing. Note: only use this\n        parameter when you know that you don't have any values pandas would\n        consider missing in the array (NaN for float data, iNaT for\n        datetimes, etc.).\n\n    Returns\n    -------\n    labels, uniques : ndarray"
  },
  {
    "code": "def _PrintTasksInformation(self, storage_reader):\n    table_view = views.ViewsFactory.GetTableView(\n        self._views_format_type, title='Tasks')\n    for task_start, _ in storage_reader.GetSessions():\n      start_time = timelib.Timestamp.CopyToIsoFormat(\n          task_start.timestamp)\n      task_identifier = uuid.UUID(hex=task_start.identifier)\n      task_identifier = '{0!s}'.format(task_identifier)\n      table_view.AddRow([task_identifier, start_time])\n    table_view.Write(self._output_writer)",
    "docstring": "Prints information about the tasks.\n\n    Args:\n      storage_reader (StorageReader): storage reader."
  },
  {
    "code": "def __require_kytos_config(self):\n        if self.__enabled is None:\n            uri = self._kytos_api + 'api/kytos/core/config/'\n            try:\n                options = json.loads(urllib.request.urlopen(uri).read())\n            except urllib.error.URLError:\n                print('Kytos is not running.')\n                sys.exit()\n            self.__enabled = Path(options.get('napps'))\n            self.__installed = Path(options.get('installed_napps'))",
    "docstring": "Set path locations from kytosd API.\n\n        It should not be called directly, but from properties that require a\n        running kytosd instance."
  },
  {
    "code": "def _stop_process(p, name):\n    if p.poll() is not None:\n        print(\"{} is already stopped.\".format(name))\n        return\n    p.terminate()\n    time.sleep(0.1)\n    if p.poll() is not None:\n        print(\"{} is terminated.\".format(name))\n        return\n    p.kill()\n    print(\"{} is killed.\".format(name))",
    "docstring": "Stop process, by applying terminate and kill."
  },
  {
    "code": "def first_n_three_layer_P(reference_patterns, estimated_patterns, n=5):\n    validate(reference_patterns, estimated_patterns)\n    if _n_onset_midi(reference_patterns) == 0 or \\\n       _n_onset_midi(estimated_patterns) == 0:\n        return 0., 0., 0.\n    fn_est_patterns = estimated_patterns[:min(len(estimated_patterns), n)]\n    F, P, R = three_layer_FPR(reference_patterns, fn_est_patterns)\n    return P",
    "docstring": "First n three-layer precision.\n\n    This metric is basically the same as the three-layer FPR but it is only\n    applied to the first n estimated patterns, and it only returns the\n    precision. In MIREX and typically, n = 5.\n\n    Examples\n    --------\n    >>> ref_patterns = mir_eval.io.load_patterns(\"ref_pattern.txt\")\n    >>> est_patterns = mir_eval.io.load_patterns(\"est_pattern.txt\")\n    >>> P = mir_eval.pattern.first_n_three_layer_P(ref_patterns,\n    ...                                            est_patterns, n=5)\n\n    Parameters\n    ----------\n    reference_patterns : list\n        The reference patterns in the format returned by\n        :func:`mir_eval.io.load_patterns()`\n    estimated_patterns : list\n        The estimated patterns in the same format\n    n : int\n        Number of patterns to consider from the estimated results, in\n        the order they appear in the matrix\n        (Default value = 5)\n\n    Returns\n    -------\n    precision : float\n        The first n three-layer Precision"
  },
  {
    "code": "def spawn(func, *args, **kwargs):\n    fiber = Fiber(func, args, **kwargs)\n    fiber.start()\n    return fiber",
    "docstring": "Spawn a new fiber.\n\n    A new :class:`Fiber` is created with main function *func* and positional\n    arguments *args*. The keyword arguments are passed to the :class:`Fiber`\n    constructor, not to the main function. The fiber is then scheduled to start\n    by calling its :meth:`~Fiber.start` method.\n\n    The fiber instance is returned."
  },
  {
    "code": "def erase(ctx):\n    if os.path.exists(ctx.obj['report']):\n        os.remove(ctx.obj['report'])",
    "docstring": "Erase the existing smother report."
  },
  {
    "code": "def from_bytes(rawbytes):\n        icmpv6popts = ICMPv6OptionList()\n        i = 0\n        while i < len(rawbytes):\n            opttype = rawbytes[i]\n            optnum = ICMPv6OptionNumber(opttype)\n            obj = ICMPv6OptionClasses[optnum]()\n            eaten = obj.from_bytes(rawbytes[i:])\n            i += eaten\n            icmpv6popts.append(obj)\n        return icmpv6popts",
    "docstring": "Takes a byte string as a parameter and returns a list of\n        ICMPv6Option objects."
  },
  {
    "code": "def import_log_funcs():\n    global g_logger\n    curr_mod = sys.modules[__name__]\n    for func_name in _logging_funcs:\n        func = getattr(g_logger, func_name)\n        setattr(curr_mod, func_name, func)",
    "docstring": "Import the common log functions from the global logger to the module."
  },
  {
    "code": "def add_success(self, group=None, type_='', field='', description=''):\n        group = group or '(200)'\n        group = int(group.lower()[1:-1])\n        self.retcode = self.retcode or group\n        if group != self.retcode:\n            raise ValueError('Two or more retcodes!')\n        type_ = type_ or '{String}'\n        p = Param(type_, field, description)\n        self.params['responce'][p.field] = p",
    "docstring": "parse and append a success data param"
  },
  {
    "code": "def uninstall_ruby(ruby, runas=None):\n    ruby = re.sub(r'^ruby-', '', ruby)\n    _rbenv_exec(['uninstall', '--force', ruby], runas=runas)\n    return True",
    "docstring": "Uninstall a ruby implementation.\n\n    ruby\n        The version of ruby to uninstall. Should match one of the versions\n        listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.\n\n    runas\n        The user under which to run rbenv. If not specified, then rbenv will be\n        run as the user under which Salt is running.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rbenv.uninstall_ruby 2.0.0-p0"
  },
  {
    "code": "def Validate(self):\n    bad_filters = []\n    for f in self.filters:\n      try:\n        f.Validate()\n      except DefinitionError as e:\n        bad_filters.append(\"%s: %s\" % (f.expression, e))\n    if bad_filters:\n      raise DefinitionError(\n          \"Filters with invalid expressions: %s\" % \", \".join(bad_filters))",
    "docstring": "Verifies this filter set can process the result data."
  },
  {
    "code": "def move(self, new_location):\n        self._perform_change(change.MoveResource(self, new_location),\n                             'Moving <%s> to <%s>' % (self.path, new_location))",
    "docstring": "Move resource to `new_location`"
  },
  {
    "code": "def get_context_data(self, **kwargs):\n        context = super(TermsView, self).get_context_data(**kwargs)\n        context['terms_base_template'] = getattr(settings, 'TERMS_BASE_TEMPLATE', DEFAULT_TERMS_BASE_TEMPLATE)\n        return context",
    "docstring": "Pass additional context data"
  },
  {
    "code": "def hour(self):\n        self.magnification = 3600\n        self._update(self.baseNumber, self.magnification)\n        return self",
    "docstring": "set unit to hour"
  },
  {
    "code": "def hlist(self, name_start, name_end, limit=10):\n        limit = get_positive_integer('limit', limit)\n        return self.execute_command('hlist', name_start, name_end, limit)",
    "docstring": "Return a list of the top ``limit`` hash's name between ``name_start`` and\n        ``name_end`` in ascending order\n\n        .. note:: The range is (``name_start``, ``name_end``]. The ``name_start``\n           isn't in the range, but ``name_end`` is.\n\n        :param string name_start: The lower bound(not included) of hash names to\n         be returned, empty string ``''`` means -inf\n        :param string name_end: The upper bound(included) of hash names to be\n         returned, empty string ``''`` means +inf\n        :param int limit: number of elements will be returned.\n        :return: a list of hash's name\n        :rtype: list\n        \n        >>> ssdb.hlist('hash_ ', 'hash_z', 10)\n        ['hash_1', 'hash_2']\n        >>> ssdb.hlist('hash_ ', '', 3)\n        ['hash_1', 'hash_2']\n        >>> ssdb.hlist('', 'aaa_not_exist', 10)\n        []"
  },
  {
    "code": "def get_args_setting(args, jsonpath='scenario_setting.json'):\n    if not jsonpath == None:\n        with open(jsonpath) as f:\n            args = json.load(f)\n    return args",
    "docstring": "Get and open json file with scenaio settings of eTraGo ``args``.\n    The settings incluedes all eTraGo specific settings of arguments and \n    parameters for a reproducible calculation.\n\n    Parameters\n    ----------\n    json_file : str\n        Default: ``scenario_setting.json``\n        Name of scenario setting json file\n\n    Returns\n    -------\n    args : dict\n        Dictionary of json file"
  },
  {
    "code": "def create_graph():\n  with tf.gfile.FastGFile(os.path.join(\n      FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:\n    graph_def = tf.GraphDef()\n    graph_def.ParseFromString(f.read())\n    _ = tf.import_graph_def(graph_def, name='')",
    "docstring": "Creates a graph from saved GraphDef file and returns a saver."
  },
  {
    "code": "def add_token_layer(self, words_file, connected):\n        for word in etree.parse(words_file).iterfind('//word'):\n            token_node_id = word.attrib['id']\n            self.tokens.append(token_node_id)\n            token_str = ensure_unicode(word.text)\n            self.add_node(token_node_id,\n                          layers={self.ns, self.ns+':token'},\n                          attr_dict={self.ns+':token': token_str,\n                                     'label': token_str})\n            if connected:\n                self.add_edge(self.root, token_node_id,\n                              layers={self.ns, self.ns+':token'})",
    "docstring": "parses a _words.xml file, adds every token to the document graph\n        and adds an edge from the MMAX root node to it.\n\n        Parameters\n        ----------\n        connected : bool\n            Make the graph connected, i.e. add an edge from root to each\n            token."
  },
  {
    "code": "def writemessage(self, text):\n        self.IQUEUELOCK.acquire()\n        TelnetHandlerBase.writemessage(self, text)\n        self.IQUEUELOCK.release()",
    "docstring": "Put data in output queue, rebuild the prompt and entered data"
  },
  {
    "code": "def __timestamp():\n    today = time.time()\n    ret = struct.pack(b'=L', int(today))\n    return ret",
    "docstring": "Generate timestamp data for pyc header."
  },
  {
    "code": "def pipe(data, *fns):\n    return reduce(lambda acc, f: f(acc), fns, data)",
    "docstring": "Apply functions recursively on your data\n\n    :param data: the data\n    :param fns: functions\n    :returns: an object\n\n    >>> inc = lambda x: x + 1\n    >>> pipe(42, inc, str)\n    '43'"
  },
  {
    "code": "def FileTransfer(*args, **kwargs):\n    if len(args) >= 1:\n        device_type = args[0].device_type\n    else:\n        device_type = kwargs[\"ssh_conn\"].device_type\n    if device_type not in scp_platforms:\n        raise ValueError(\n            \"Unsupported SCP device_type: \"\n            \"currently supported platforms are: {}\".format(scp_platforms_str)\n        )\n    FileTransferClass = FILE_TRANSFER_MAP[device_type]\n    return FileTransferClass(*args, **kwargs)",
    "docstring": "Factory function selects the proper SCP class and creates object based on device_type."
  },
  {
    "code": "def get_user_ratings(self, item_type=None):\n        if item_type:\n            query_string = 'itemType=%s' % item_type\n            return self.parse_raw_response(\n                requests_util.run_request('get', self.API_BASE_URL + '/user/ratings/qeury?%s' % query_string,\n                                          headers=self.__get_header_with_auth()))\n        else:\n            return self.__get_user_ratings()",
    "docstring": "Returns a list of the ratings for the type of item provided, for the current user.\n\n        :param item_type: One of: series, episode or banner.\n        :return: a python dictionary with either the result of the search or an error from TheTVDB."
  },
  {
    "code": "def predict(self, X, k=None, depth=None):\n        if depth is None:\n            if self.opt_depth is not None:\n                depth = self.opt_depth\n                if self.verbose > 0:\n                    'using optimal depth to predict'\n            else:\n                depth = float('inf')\n        response = self._predict(X=X, depth=depth)\n        if k is not None:\n                mean = self.predict(X=self.X, depth=depth).reshape(-1, 1)\n                response += self.BLUP.predict(XTest=X, k=k,\n                                              mean=mean).reshape(-1)\n        return response",
    "docstring": "Predict response for X.\n\n        The response to an input sample is computed as the sum of\n        (1) the mean prediction of the trees in the forest (fixed effect) and\n        (2) the estimated random effect.\n\n        Parameters\n        ----------\n        X : array-like of shape = [n_samples, n_features]\n            The input samples.\n        k: array-like of shape = [n_samples, n_samples_fitting]\n            The cross-dependency structure between the samples used for learning\n            the forest and the input samples.\n            If not specified only the estimated fixed effect is returned.\n\n        Returns\n        -------\n        y : array of shape = [n_samples, 1]\n            The response"
  },
  {
    "code": "def _iter_list_for_dicts(self, check_list):\n        list_copy = copy.deepcopy(check_list)\n        for index, elem in enumerate(check_list):\n            if isinstance(elem, dict):\n                list_copy[index] = self._check_for_python_keywords(elem)\n            elif isinstance(elem, list):\n                list_copy[index] = self._iter_list_for_dicts(elem)\n            else:\n                list_copy[index] = elem\n        return list_copy",
    "docstring": "Iterate over list to find dicts and check for python keywords."
  },
  {
    "code": "def delete_usage_plan(plan_id, region=None, key=None, keyid=None, profile=None):\n    try:\n        existing = describe_usage_plans(plan_id=plan_id, region=region, key=key, keyid=keyid, profile=profile)\n        if 'error' in existing:\n            return {'error': existing['error']}\n        if 'plans' in existing and existing['plans']:\n            conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n            res = conn.delete_usage_plan(usagePlanId=plan_id)\n        return {'deleted': True, 'usagePlanId': plan_id}\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Deletes usage plan identified by plan_id\n\n    .. versionadded:: 2017.7.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_apigateway.delete_usage_plan plan_id='usage plan id'"
  },
  {
    "code": "def post_card(name,\n              message,\n              hook_url=None,\n              title=None,\n              theme_color=None):\n    ret = {'name': name,\n           'changes': {},\n           'result': False,\n           'comment': ''}\n    if __opts__['test']:\n        ret['comment'] = 'The following message is to be sent to Teams: {0}'.format(message)\n        ret['result'] = None\n        return ret\n    if not message:\n        ret['comment'] = 'Teams message is missing: {0}'.format(message)\n        return ret\n    try:\n        result = __salt__['msteams.post_card'](\n            message=message,\n            hook_url=hook_url,\n            title=title,\n            theme_color=theme_color,\n        )\n    except SaltInvocationError as sie:\n        ret['comment'] = 'Failed to send message ({0}): {1}'.format(sie, name)\n    else:\n        if isinstance(result, bool) and result:\n            ret['result'] = True\n            ret['comment'] = 'Sent message: {0}'.format(name)\n        else:\n            ret['comment'] = 'Failed to send message ({0}): {1}'.format(result['message'], name)\n    return ret",
    "docstring": "Send a message to a Microsft Teams channel\n\n    .. code-block:: yaml\n\n        send-msteams-message:\n          msteams.post_card:\n            - message: 'This state was executed successfully.'\n            - hook_url: https://outlook.office.com/webhook/837\n\n    The following parameters are required:\n\n    message\n        The message that is to be sent to the MS Teams channel.\n\n    The following parameters are optional:\n\n    hook_url\n        The webhook URL given configured in Teams interface,\n        if not specified in the configuration options of master or minion.\n    title\n        The title for the card posted to the channel\n    theme_color\n        A hex code for the desired highlight color"
  },
  {
    "code": "def rewrite(\n    filepath: Union[str, Path], mode: str = \"w\", **kw: Any\n) -> Generator[IO, None, None]:\n    if isinstance(filepath, str):\n        base_dir = os.path.dirname(filepath)\n        filename = os.path.basename(filepath)\n    else:\n        base_dir = str(filepath.parent)\n        filename = filepath.name\n    with tempfile.NamedTemporaryFile(\n        mode=mode, prefix=f\".{filename}.\", delete=False, dir=base_dir, **kw\n    ) as f:\n        filepath_tmp = f.name\n        yield f\n    if not os.path.exists(filepath_tmp):\n        return\n    os.chmod(filepath_tmp, 0o100644)\n    os.rename(filepath_tmp, filepath)",
    "docstring": "Rewrite an existing file atomically to avoid programs running in\n    parallel to have race conditions while reading."
  },
  {
    "code": "def get_inner_edges(self):\n        inner_edges = [e for e in self._tree.preorder_edge_iter() if e.is_internal()\n                       and e.head_node and e.tail_node]\n        return inner_edges",
    "docstring": "Returns a list of the internal edges of the tree."
  },
  {
    "code": "def validate (properties):\n    if isinstance(properties, Property):\n        properties = [properties]\n    assert is_iterable_typed(properties, Property)\n    for p in properties:\n        __validate1(p)",
    "docstring": "Exit with error if any of the properties is not valid.\n        properties may be a single property or a sequence of properties."
  },
  {
    "code": "def agg_wt_avg(mat, min_wt = 0.01, corr_metric='spearman'):\n    assert mat.shape[1] > 0, \"mat is empty! mat: {}\".format(mat)\n    if mat.shape[1] == 1:\n        out_sig = mat\n        upper_tri_df = None\n        raw_weights = None\n        weights = None\n    else:\n        assert corr_metric in [\"spearman\", \"pearson\"]\n        corr_mat = mat.corr(method=corr_metric)\n        upper_tri_df = get_upper_triangle(corr_mat)\n        raw_weights, weights = calculate_weights(corr_mat, min_wt)\n        weighted_values = mat * weights\n        out_sig = weighted_values.sum(axis=1)\n    return out_sig, upper_tri_df, raw_weights, weights",
    "docstring": "Aggregate a set of replicate profiles into a single signature using\n    a weighted average.\n\n    Args:\n    mat (pandas df): a matrix of replicate profiles, where the columns are\n        samples and the rows are features; columns correspond to the\n        replicates of a single perturbagen\n    min_wt (float): Minimum raw weight when calculating weighted average\n    corr_metric (string): Spearman or Pearson; the correlation method\n\n    Returns:\n    out_sig (pandas series): weighted average values\n    upper_tri_df (pandas df): the correlations between each profile that went into the signature\n    raw weights (pandas series): weights before normalization\n    weights (pandas series): weights after normalization"
  },
  {
    "code": "def unregister_switch_address(addr):\n    ofp_handler = app_manager.lookup_service_brick(ofp_event.NAME)\n    if ofp_handler.controller is None:\n        return\n    ofp_handler.controller.stop_client_loop(addr)",
    "docstring": "Unregister the given switch address.\n\n    Unregisters the given switch address to let\n    ryu.controller.controller.OpenFlowController stop trying to initiate\n    connection to switch.\n\n    :param addr: A tuple of (host, port) pair of switch."
  },
  {
    "code": "def _raise_on_error(data: Union[str, dict]) -> None:\n    if isinstance(data, str):\n        raise_error(data)\n    elif 'status' in data and data['status'] != 'success':\n        raise_error(data['data']['message'])",
    "docstring": "Raise the appropriate exception on error."
  },
  {
    "code": "def get_url_param(self, index, default=None):\n        params = self.get_url_params()\n        return params[index] if index < len(params) else default",
    "docstring": "Return url parameter with given index.\n\n        Args:\n        - index: starts from zero, and come after controller and\n          action names in url."
  },
  {
    "code": "def get_parents_for(self, child_ids):\n        self._cache_init()\n        parent_candidates = []\n        for parent, children in self._cache_get_entry(self.CACHE_NAME_PARENTS).items():\n            if set(children).intersection(child_ids):\n                parent_candidates.append(parent)\n        return set(parent_candidates)",
    "docstring": "Returns parent aliases for a list of child IDs.\n\n        :param list child_ids:\n        :rtype: set\n        :return: a set of parent aliases"
  },
  {
    "code": "def interactive_login(self, username: str) -> None:\n        if self.context.quiet:\n            raise LoginRequiredException(\"Quiet mode requires given password or valid session file.\")\n        try:\n            password = None\n            while password is None:\n                password = getpass.getpass(prompt=\"Enter Instagram password for %s: \" % username)\n                try:\n                    self.login(username, password)\n                except BadCredentialsException as err:\n                    print(err, file=sys.stderr)\n                    password = None\n        except TwoFactorAuthRequiredException:\n            while True:\n                try:\n                    code = input(\"Enter 2FA verification code: \")\n                    self.two_factor_login(code)\n                    break\n                except BadCredentialsException:\n                    pass",
    "docstring": "Logs in and internally stores session, asking user for password interactively.\n\n        :raises LoginRequiredException: when in quiet mode.\n        :raises InvalidArgumentException: If the provided username does not exist.\n        :raises ConnectionException: If connection to Instagram failed."
  },
  {
    "code": "def page_through(page_size, function, *args, **kwargs):\n        kwargs[\"limit\"] = page_size\n        def get_page(token):\n            page_kwargs = kwargs.copy()\n            if token:\n                page_kwargs[\"token\"] = token\n            return function(*args, **page_kwargs)\n        def page_generator():\n            token = None\n            while True:\n                try:\n                    response = get_page(token)\n                    token = response.headers.get(\"x-next-token\")\n                except PureError as err:\n                    yield None, err\n                else:\n                    if response:\n                        sent_token = yield response, None\n                        if sent_token is not None:\n                            token = sent_token\n                    else:\n                        return\n        return page_generator()",
    "docstring": "Return an iterator over all pages of a REST operation.\n\n        :param page_size: Number of elements to retrieve per call.\n        :param function: FlashArray function that accepts limit as an argument.\n        :param \\*args: Positional arguments to be passed to function.\n        :param \\*\\*kwargs: Keyword arguments to be passed to function.\n\n        :returns: An iterator of tuples containing a page of results for the\n                  function(\\*args, \\*\\*kwargs) and None, or None and a PureError\n                  if a call to retrieve a page fails.\n        :rtype: iterator\n\n        .. note::\n\n            Requires use of REST API 1.7 or later.\n\n            Only works with functions that accept limit as an argument.\n\n            Iterator will retrieve page_size elements per call\n\n            Iterator will yield None and an error if a call fails. The next\n            call will repeat the same call, unless the caller sends in an\n            alternate page token."
  },
  {
    "code": "def replace_complexes(self, linked_stmts=None):\n        if linked_stmts is None:\n            linked_stmts = self.infer_complexes(self.statements)\n        new_stmts = []\n        for stmt in self.statements:\n            if not isinstance(stmt, Complex):\n                new_stmts.append(stmt)\n                continue\n            found = False\n            for linked_stmt in linked_stmts:\n                if linked_stmt.refinement_of(stmt, hierarchies):\n                    found = True\n            if not found:\n                new_stmts.append(stmt)\n            else:\n                logger.info('Removing complex: %s' % stmt)\n        self.statements = new_stmts",
    "docstring": "Remove Complex Statements that can be inferred out.\n\n        This function iterates over self.statements and looks for Complex\n        Statements that either match or are refined by inferred Complex\n        Statements that were linked (provided as the linked_stmts argument).\n        It removes Complex Statements from self.statements that can be\n        explained by the linked statements.\n\n        Parameters\n        ----------\n        linked_stmts : Optional[list[indra.mechlinker.LinkedStatement]]\n            A list of linked statements, optionally passed from outside.\n            If None is passed, the MechLinker runs self.infer_complexes to\n            infer Complexes and obtain a list of LinkedStatements that are\n            then used for removing existing Complexes in self.statements."
  },
  {
    "code": "def configure(logger=None):\n    global LOGGER\n    if logger is None:\n        LOGGER = logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n    else:\n        LOGGER = logger",
    "docstring": "Pass stump a logger to use. If no logger is supplied, a basic logger\n    of level INFO will print to stdout."
  },
  {
    "code": "def call_command(self, cmd, *argv):\n        parser = self.get_parser()\n        args = [cmd] + list(argv)\n        namespace = parser.parse_args(args)\n        self.run_command(namespace)",
    "docstring": "Runs a command.\n\n        :param cmd: command to run (key at the registry)\n        :param argv: arguments that would be passed to the command"
  },
  {
    "code": "def read_little_endian64(self):\n        try:\n            i = struct.unpack(wire_format.FORMAT_UINT64_LITTLE_ENDIAN,\n                              self._input.read(8))\n            self._pos += 8\n            return i[0]\n        except struct.error as e:\n            raise errors.DecodeError(e)",
    "docstring": "Interprets the next 8 bytes of the stream as a little-endian\n        encoded, unsiged 64-bit integer, and returns that integer."
  },
  {
    "code": "def download_kegg_gene_metadata(gene_id, outdir=None, force_rerun=False):\n    if not outdir:\n        outdir = ''\n    outfile = op.join(outdir, '{}.kegg'.format(custom_slugify(gene_id)))\n    if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):\n        raw_text = bs_kegg.get(\"{}\".format(gene_id))\n        if raw_text == 404:\n            return\n        with io.open(outfile, mode='wt', encoding='utf-8') as f:\n            f.write(raw_text)\n        log.debug('{}: downloaded KEGG metadata file'.format(outfile))\n    else:\n        log.debug('{}: KEGG metadata file already exists'.format(outfile))\n    return outfile",
    "docstring": "Download the KEGG flatfile for a KEGG ID and return the path.\n\n    Args:\n        gene_id: KEGG gene ID (with organism code), i.e. \"eco:1244\"\n        outdir: optional output directory of metadata\n\n    Returns:\n        Path to metadata file"
  },
  {
    "code": "def set_args(self, namespace, dots=False):\n        self.set(self._build_namespace_dict(namespace, dots))",
    "docstring": "Overlay parsed command-line arguments, generated by a library\n        like argparse or optparse, onto this view's value.\n\n        :param namespace: Dictionary or Namespace to overlay this config with.\n            Supports nested Dictionaries and Namespaces.\n        :type namespace: dict or Namespace\n        :param dots: If True, any properties on namespace that contain dots (.)\n            will be broken down into child dictionaries.\n            :Example:\n\n            {'foo.bar': 'car'}\n            # Will be turned into\n            {'foo': {'bar': 'car'}}\n        :type dots: bool"
  },
  {
    "code": "def bulk_cursor_execute(self, bulk_cursor):\n        try:\n            result = bulk_cursor.execute()\n        except BulkWriteError as bwe:\n            msg = \"bulk_cursor_execute: Exception in executing Bulk cursor to mongo with {error}\".format(\n                error=str(bwe))\n            raise Exception(msg)\n        except Exception as e:\n            msg = \"Mongo Bulk cursor could not be fetched, Error: {error}\".format(\n                error=str(e))\n            raise Exception(msg)",
    "docstring": "Executes the bulk_cursor\n\n            :param bulk_cursor: Cursor to perform bulk operations\n            :type bulk_cursor: pymongo bulk cursor object\n\n            :returns: pymongo bulk cursor object (for bulk operations)"
  },
  {
    "code": "def get_transactions(self, account: SEPAAccount, start_date: datetime.date = None, end_date: datetime.date = None):\n        with self._get_dialog() as dialog:\n            hkkaz = self._find_highest_supported_command(HKKAZ5, HKKAZ6, HKKAZ7)\n            logger.info('Start fetching from {} to {}'.format(start_date, end_date))\n            responses = self._fetch_with_touchdowns(\n                dialog,\n                lambda touchdown: hkkaz(\n                    account=hkkaz._fields['account'].type.from_sepa_account(account),\n                    all_accounts=False,\n                    date_start=start_date,\n                    date_end=end_date,\n                    touchdown_point=touchdown,\n                ),\n                'HIKAZ'\n            )\n            logger.info('Fetching done.')\n        statement = []\n        for seg in responses:\n            statement += mt940_to_array(seg.statement_booked.decode('iso-8859-1'))\n        logger.debug('Statement: {}'.format(statement))\n        return statement",
    "docstring": "Fetches the list of transactions of a bank account in a certain timeframe.\n\n        :param account: SEPA\n        :param start_date: First day to fetch\n        :param end_date: Last day to fetch\n        :return: A list of mt940.models.Transaction objects"
  },
  {
    "code": "def execute(self, query, parameters=None, timeout=_NOT_SET, trace=False,\n                custom_payload=None, execution_profile=EXEC_PROFILE_DEFAULT,\n                paging_state=None, host=None):\n        return self.execute_async(query, parameters, trace, custom_payload,\n                                  timeout, execution_profile, paging_state, host).result()",
    "docstring": "Execute the given query and synchronously wait for the response.\n\n        If an error is encountered while executing the query, an Exception\n        will be raised.\n\n        `query` may be a query string or an instance of :class:`cassandra.query.Statement`.\n\n        `parameters` may be a sequence or dict of parameters to bind.  If a\n        sequence is used, ``%s`` should be used the placeholder for each\n        argument.  If a dict is used, ``%(name)s`` style placeholders must\n        be used.\n\n        `timeout` should specify a floating-point timeout (in seconds) after\n        which an :exc:`.OperationTimedOut` exception will be raised if the query\n        has not completed.  If not set, the timeout defaults to\n        :attr:`~.Session.default_timeout`.  If set to :const:`None`, there is\n        no timeout. Please see :meth:`.ResponseFuture.result` for details on\n        the scope and effect of this timeout.\n\n        If `trace` is set to :const:`True`, the query will be sent with tracing enabled.\n        The trace details can be obtained using the returned :class:`.ResultSet` object.\n\n        `custom_payload` is a :ref:`custom_payload` dict to be passed to the server.\n        If `query` is a Statement with its own custom_payload. The message payload\n        will be a union of the two, with the values specified here taking precedence.\n\n        `execution_profile` is the execution profile to use for this request. It can be a key to a profile configured\n        via :meth:`Cluster.add_execution_profile` or an instance (from :meth:`Session.execution_profile_clone_update`,\n        for example\n\n        `paging_state` is an optional paging state, reused from a previous :class:`ResultSet`.\n\n        `host` is the :class:`pool.Host` that should handle the query. Using this is discouraged except in a few\n        cases, e.g., querying node-local tables and applying schema changes."
  },
  {
    "code": "def GetMatchingShape(pattern_poly, trip, matches, max_distance, verbosity=0):\n  if len(matches) == 0:\n    print ('No matching shape found within max-distance %d for trip %s '\n           % (max_distance, trip.trip_id))\n    return None\n  if verbosity >= 1:\n    for match in matches:\n      print(\"match: size %d\" % match.GetNumPoints())\n  scores = [(pattern_poly.GreedyPolyMatchDist(match), match)\n            for match in matches]\n  scores.sort()\n  if scores[0][0] > max_distance:\n    print ('No matching shape found within max-distance %d for trip %s '\n           '(min score was %f)'\n           % (max_distance, trip.trip_id, scores[0][0]))\n    return None\n  return scores[0][1]",
    "docstring": "Tries to find a matching shape for the given pattern Poly object,\n  trip, and set of possibly matching Polys from which to choose a match."
  },
  {
    "code": "def get_profiles(self, profile_base=\"/data/b2g/mozilla\", timeout=None):\n        rv = {}\n        if timeout is None:\n            timeout = self._timeout\n        profile_path = posixpath.join(profile_base, \"profiles.ini\")\n        try:\n            proc = self.shell(\"cat %s\" % profile_path, timeout=timeout)\n            config = ConfigParser.ConfigParser()\n            config.readfp(proc.stdout_file)\n            for section in config.sections():\n                items = dict(config.items(section))\n                if \"name\" in items and \"path\" in items:\n                    path = items[\"path\"]\n                    if \"isrelative\" in items and int(items[\"isrelative\"]):\n                        path = posixpath.normpath(\"%s/%s\" % (profile_base, path))\n                    rv[items[\"name\"]] = path\n        finally:\n            proc.stdout_file.close()\n            proc.stderr_file.close()\n        return rv",
    "docstring": "Return a list of paths to gecko profiles on the device,\n\n        :param timeout: Timeout of each adb command run\n        :param profile_base: Base directory containing the profiles.ini file"
  },
  {
    "code": "def _parse_json(cls, resources, exactly_one=True):\n        if not len(resources['features']):\n            return None\n        if exactly_one:\n            return cls.parse_resource(resources['features'][0])\n        else:\n            return [cls.parse_resource(resource) for resource\n                    in resources['features']]",
    "docstring": "Parse display name, latitude, and longitude from a JSON response."
  },
  {
    "code": "def spm_hrf_compat(t,\n                   peak_delay=6,\n                   under_delay=16,\n                   peak_disp=1,\n                   under_disp=1,\n                   p_u_ratio=6,\n                   normalize=True,\n                   ):\n    if len([v for v in [peak_delay, peak_disp, under_delay, under_disp]\n            if v <= 0]):\n        raise ValueError(\"delays and dispersions must be > 0\")\n    hrf = np.zeros(t.shape, dtype=np.float)\n    pos_t = t[t > 0]\n    peak = sps.gamma.pdf(pos_t,\n                         peak_delay / peak_disp,\n                         loc=0,\n                         scale=peak_disp)\n    undershoot = sps.gamma.pdf(pos_t,\n                               under_delay / under_disp,\n                               loc=0,\n                               scale=under_disp)\n    hrf[t > 0] = peak - undershoot / p_u_ratio\n    if not normalize:\n        return hrf\n    return hrf / np.max(hrf)",
    "docstring": "SPM HRF function from sum of two gamma PDFs\n\n    This function is designed to be partially compatible with SPMs `spm_hrf.m`\n    function.\n\n    The SPN HRF is a *peak* gamma PDF (with location `peak_delay` and\n    dispersion `peak_disp`), minus an *undershoot* gamma PDF (with location\n    `under_delay` and dispersion `under_disp`, and divided by the `p_u_ratio`).\n\n    Parameters\n    ----------\n    t : array-like\n        vector of times at which to sample HRF\n    peak_delay : float, optional\n        delay of peak\n    peak_disp : float, optional\n        width (dispersion) of peak\n    under_delay : float, optional\n        delay of undershoot\n    under_disp : float, optional\n        width (dispersion) of undershoot\n    p_u_ratio : float, optional\n        peak to undershoot ratio.  Undershoot divided by this value before\n        subtracting from peak.\n    normalize : {True, False}, optional\n        If True, divide HRF values by their sum before returning. SPM does this\n        by default.\n\n    Returns\n    -------\n    hrf : array\n        vector length ``len(t)`` of samples from HRF at times `t`\n\n    Notes\n    -----\n    See ``spm_hrf.m`` in the SPM distribution."
  },
  {
    "code": "def get_cool_off() -> Optional[timedelta]:\n    cool_off = settings.AXES_COOLOFF_TIME\n    if isinstance(cool_off, int):\n        return timedelta(hours=cool_off)\n    return cool_off",
    "docstring": "Return the login cool off time interpreted from settings.AXES_COOLOFF_TIME.\n\n    The return value is either None or timedelta.\n\n    Notice that the settings.AXES_COOLOFF_TIME is either None, timedelta, or integer of hours,\n    and this function offers a unified _timedelta or None_ representation of that configuration\n    for use with the Axes internal implementations.\n\n    :exception TypeError: if settings.AXES_COOLOFF_TIME is of wrong type."
  },
  {
    "code": "def gene_name(st, exclude=(\"ev\",), sep=\".\"):\n    if any(st.startswith(x) for x in exclude):\n        sep = None\n    st = st.split('|')[0]\n    if sep and sep in st:\n        name, suffix = st.rsplit(sep, 1)\n    else:\n        name, suffix = st, \"\"\n    if len(suffix) != 1:\n        name = st\n    return name",
    "docstring": "Helper functions in the BLAST filtering to get rid alternative splicings.\n    This is ugly, but different annotation groups are inconsistent with respect\n    to how the alternative splicings are named. Mostly it can be done by removing\n    the suffix, except for ones in the exclude list."
  },
  {
    "code": "def get_env(key, *default, **kwargs):\n    assert len(default) in (0, 1), \"Too many args supplied.\"\n    func = kwargs.get('coerce', lambda x: x)\n    required = (len(default) == 0)\n    default = default[0] if not required else None\n    return _get_env(key, default=default, coerce=func, required=required)",
    "docstring": "Return env var.\n\n    This is the parent function of all other get_foo functions,\n    and is responsible for unpacking args/kwargs into the values\n    that _get_env expects (it is the root function that actually\n    interacts with environ).\n\n    Args:\n        key: string, the env var name to look up.\n        default: (optional) the value to use if the env var does not\n            exist. If this value is not supplied, then the env var is\n            considered to be required, and a RequiredSettingMissing\n            error will be raised if it does not exist.\n\n    Kwargs:\n        coerce: a func that may be supplied to coerce the value into\n            something else. This is used by the default get_foo functions\n            to cast strings to builtin types, but could be a function that\n            returns a custom class.\n\n    Returns the env var, coerced if required, and a default if supplied."
  },
  {
    "code": "def approx_equals(self, other, atol):\n        if other is self:\n            return True\n        return (type(other) is type(self) and\n                self.ndim == other.ndim and\n                self.shape == other.shape and\n                all(np.allclose(vec_s, vec_o, atol=atol, rtol=0.0)\n                    for (vec_s, vec_o) in zip(self.coord_vectors,\n                                              other.coord_vectors)))",
    "docstring": "Test if this grid is equal to another grid.\n\n        Parameters\n        ----------\n        other :\n            Object to be tested\n        atol : float\n            Allow deviations up to this number in absolute value\n            per vector entry.\n\n        Returns\n        -------\n        equals : bool\n            ``True`` if ``other`` is a `RectGrid` instance with all\n            coordinate vectors equal (up to the given tolerance), to\n            the ones of this grid, ``False`` otherwise.\n\n        Examples\n        --------\n        >>> g1 = RectGrid([0, 1], [-1, 0, 2])\n        >>> g2 = RectGrid([-0.1, 1.1], [-1, 0.1, 2])\n        >>> g1.approx_equals(g2, atol=0)\n        False\n        >>> g1.approx_equals(g2, atol=0.15)\n        True"
  },
  {
    "code": "def get_preservation_data(self):\n        for obj in self.get_preservations():\n            info = self.get_base_info(obj)\n            yield info",
    "docstring": "Returns a list of Preservation data"
  },
  {
    "code": "def from_args(cls, target_url, default_url, test_url):\n        return cls(\"You're trying to upload to the legacy PyPI site '{}'. \"\n                   \"Uploading to those sites is deprecated. \\n \"\n                   \"The new sites are pypi.org and test.pypi.org. Try using \"\n                   \"{} (or {}) to upload your packages instead. \"\n                   \"These are the default URLs for Twine now. \\n More at \"\n                   \"https://packaging.python.org/guides/migrating-to-pypi-org/\"\n                   \" .\".format(target_url, default_url, test_url)\n                   )",
    "docstring": "Return an UploadToDeprecatedPyPIDetected instance."
  },
  {
    "code": "def rewind(self, position=0):\n        if position < 0 or position > len(self._data):\n            raise Exception(\"Invalid position to rewind cursor to: %s.\" % position)\n        self._position = position",
    "docstring": "Set the position of the data buffer cursor to 'position'."
  },
  {
    "code": "def get_instance(self, payload):\n        return TerminatingSipDomainInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], )",
    "docstring": "Build an instance of TerminatingSipDomainInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainInstance\n        :rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainInstance"
  },
  {
    "code": "def split_points(self, point_cloud):\n        if not isinstance(point_cloud, PointCloud):\n            raise ValueError('Can only split point clouds')\n        above_plane = point_cloud._data - np.tile(self._x0.data, [1, point_cloud.num_points]).T.dot(self._n) > 0\n        above_plane = point_cloud.z_coords > 0 & above_plane\n        below_plane = point_cloud._data - np.tile(self._x0.data, [1, point_cloud.num_points]).T.dot(self._n) <= 0\n        below_plane = point_cloud.z_coords > 0 & below_plane\n        above_data = point_cloud.data[:, above_plane]\n        below_data = point_cloud.data[:, below_plane]\n        return PointCloud(above_data, point_cloud.frame), PointCloud(below_data, point_cloud.frame)",
    "docstring": "Split a point cloud into two along this plane.\n\n        Parameters\n        ----------\n        point_cloud : :obj:`PointCloud`\n            The PointCloud to divide in two.\n\n        Returns\n        -------\n        :obj:`tuple` of :obj:`PointCloud`\n            Two new PointCloud objects. The first contains points above the\n            plane, and the second contains points below the plane.\n\n        Raises\n        ------\n        ValueError\n            If the input is not a PointCloud."
  },
  {
    "code": "def run(self):\n        unread = 0\n        current_unread = 0\n        for id, backend in enumerate(self.backends):\n            temp = backend.unread or 0\n            unread = unread + temp\n            if id == self.current_backend:\n                current_unread = temp\n        if not unread:\n            color = self.color\n            urgent = \"false\"\n            if self.hide_if_null:\n                self.output = None\n                return\n        else:\n            color = self.color_unread\n            urgent = \"true\"\n        format = self.format\n        if unread > 1:\n            format = self.format_plural\n        account_name = getattr(self.backends[self.current_backend], \"account\", \"No name\")\n        self.output = {\n            \"full_text\": format.format(unread=unread, current_unread=current_unread, account=account_name),\n            \"urgent\": urgent,\n            \"color\": color,\n        }",
    "docstring": "Returns the sum of unread messages across all registered backends"
  },
  {
    "code": "def compute(self):\n        self._compute_primary_smooths()\n        self._smooth_the_residuals()\n        self._select_best_smooth_at_each_point()\n        self._enhance_bass()\n        self._smooth_best_span_estimates()\n        self._apply_best_spans_to_primaries()\n        self._smooth_interpolated_smooth()\n        self._store_unsorted_results(self.smooth_result, numpy.zeros(len(self.smooth_result)))",
    "docstring": "Run the SuperSmoother."
  },
  {
    "code": "def str_dict_cast(dict_, include_keys=True, include_vals=True, **kwargs):\n    new_keys = str_list_cast(dict_.keys(), **kwargs) if include_keys else dict_.keys()\n    new_vals = str_list_cast(dict_.values(), **kwargs) if include_vals else dict_.values()\n    new_dict = dict(zip_(new_keys, new_vals))\n    return new_dict",
    "docstring": "Converts any bytes-like items in input dict to string-like values, with\n    respect to python version\n\n    Parameters\n    ----------\n    dict_ : dict\n        any bytes-like objects contained in the dict will be converted to a\n        string\n    include_keys : bool, default=True\n        if True, cast keys to a string, else ignore\n    include_values : bool, default=True\n        if True, cast values to a string, else ignore\n    kwargs:\n        encoding: str, default: 'utf-8'\n            encoding to be used when decoding bytes"
  },
  {
    "code": "def _iter_candidate_groups(self, init_match, edges0, edges1):\n        sources = {}\n        for start_vertex0, end_vertex0 in edges0:\n            l = sources.setdefault(start_vertex0, [])\n            l.append(end_vertex0)\n        dests = {}\n        for start_vertex1, end_vertex1 in edges1:\n            start_vertex0 = init_match.reverse[start_vertex1]\n            l = dests.setdefault(start_vertex0, [])\n            l.append(end_vertex1)\n        for start_vertex0, end_vertices0 in sources.items():\n            end_vertices1 = dests.get(start_vertex0, [])\n            yield end_vertices0, end_vertices1",
    "docstring": "Divide the edges into groups"
  },
  {
    "code": "def issuers(self):\n        issuers = self._get_property('issuers') or []\n        result = {\n            '_embedded': {\n                'issuers': issuers,\n            },\n            'count': len(issuers),\n        }\n        return List(result, Issuer)",
    "docstring": "Return the list of available issuers for this payment method."
  },
  {
    "code": "async def process_check_ins(self):\n        params = {\n                'include_participants': 1,\n                'include_matches': 1 if AUTO_GET_MATCHES else 0\n            }\n        res = await self.connection('POST', 'tournaments/{}/process_check_ins'.format(self._id), **params)\n        self._refresh_from_json(res)",
    "docstring": "finalize the check in phase\n\n        |methcoro|\n\n        Warning:\n            |unstable|\n\n        Note:\n            |from_api| This should be invoked after a tournament's check-in window closes before the tournament is started.\n            1. Marks participants who have not checked in as inactive.\n            2. Moves inactive participants to bottom seeds (ordered by original seed).\n            3. Transitions the tournament state from 'checking_in' to 'checked_in'\n            NOTE: Checked in participants on the waiting list will be promoted if slots become available.\n\n        Raises:\n            APIException"
  },
  {
    "code": "def setup_ics(graph):\n    ics = []\n    for i0, i1 in graph.edges:\n        ics.append(BondLength(i0, i1))\n    for i1 in range(graph.num_vertices):\n        n = list(graph.neighbors[i1])\n        for index, i0 in enumerate(n):\n            for i2 in n[:index]:\n                ics.append(BendingAngle(i0, i1, i2))\n    for i1, i2 in graph.edges:\n        for i0 in graph.neighbors[i1]:\n            if i0==i2:\n                continue\n            for i3 in graph.neighbors[i2]:\n                if i3==i1 or i3==i0:\n                    continue\n                ics.append(DihedralAngle(i0, i1, i2, i3))\n    return ics",
    "docstring": "Make a list of internal coordinates based on the graph\n\n       Argument:\n        | ``graph`` -- A Graph instance.\n\n       The list of internal coordinates will include all bond lengths, all\n       bending angles, and all dihedral angles."
  },
  {
    "code": "def standardize():\r\n    def f(G, bim):\r\n        G_out = standardize_snps(G)\r\n        return G_out, bim\r\n    return f",
    "docstring": "return variant standarize function"
  },
  {
    "code": "def plot_sediment_rate(self, ax=None):\n        if ax is None:\n            ax = plt.gca()\n        y_prior, x_prior = self.prior_sediment_rate()\n        ax.plot(x_prior, y_prior, label='Prior')\n        y_posterior = self.mcmcfit.sediment_rate\n        density = scipy.stats.gaussian_kde(y_posterior.flat)\n        density.covariance_factor = lambda: 0.25\n        density._compute_covariance()\n        ax.plot(x_prior, density(x_prior), label='Posterior')\n        acc_shape = self.mcmcsetup.mcmc_kws['acc_shape']\n        acc_mean = self.mcmcsetup.mcmc_kws['acc_mean']\n        annotstr_template = 'acc_shape: {0}\\nacc_mean: {1}'\n        annotstr = annotstr_template.format(acc_shape, acc_mean)\n        ax.annotate(annotstr, xy=(0.9, 0.9), xycoords='axes fraction',\n                    horizontalalignment='right', verticalalignment='top')\n        ax.set_ylabel('Density')\n        ax.set_xlabel('Acc. rate (yr/cm)')\n        ax.grid(True)\n        return ax",
    "docstring": "Plot sediment accumulation rate prior and posterior distributions"
  },
  {
    "code": "def saveto(self, path, sortkey = True):\n        with open(path, 'w') as f:\n            self.savetofile(f, sortkey)",
    "docstring": "Save configurations to path"
  },
  {
    "code": "def refill(self, from_address, to_address, nfees, ntokens, password, min_confirmations=6, sync=False):\n        path, from_address = from_address\n        verb = Spoolverb()\n        inputs = self.select_inputs(from_address, nfees + 1, ntokens, min_confirmations=min_confirmations)\n        outputs = [{'address': to_address, 'value': self.token}] * ntokens\n        outputs += [{'address': to_address, 'value': self.fee}] * nfees\n        outputs += [{'script': self._t._op_return_hex(verb.fuel), 'value': 0}]\n        unsigned_tx = self._t.build_transaction(inputs, outputs)\n        signed_tx = self._t.sign_transaction(unsigned_tx, password, path=path)\n        txid = self._t.push(signed_tx)\n        return txid",
    "docstring": "Refill wallets with the necessary fuel to perform spool transactions\n\n        Args:\n            from_address (Tuple[str]): Federation wallet address. Fuels the wallets with tokens and fees. All transactions to wallets\n                holding a particular piece should come from the Federation wallet\n            to_address (str): Wallet address that needs to perform a spool transaction\n            nfees (int): Number of fees to transfer. Each fee is 10000 satoshi. Used to pay for the transactions\n            ntokens (int): Number of tokens to transfer. Each token is 600 satoshi. Used to register hashes in the blockchain\n            password (str): Password for the Federation wallet. Used to sign the transaction\n            min_confirmations (int): Number of confirmations when chosing the inputs of the transaction. Defaults to 6\n            sync (bool): Perform the transaction in synchronous mode, the call to the function will block until there is at\n                least on confirmation on the blockchain. Defaults to False\n\n        Returns:\n            str: transaction id"
  },
  {
    "code": "def role_update(auth=None, **kwargs):\n    cloud = get_operator_cloud(auth)\n    kwargs = _clean_kwargs(**kwargs)\n    if 'new_name' in kwargs:\n        kwargs['name'] = kwargs.pop('new_name')\n    return cloud.update_role(**kwargs)",
    "docstring": "Update a role\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' keystoneng.role_update name=role1 new_name=newrole\n        salt '*' keystoneng.role_update name=1eb6edd5525e4ac39af571adee673559 new_name=newrole"
  },
  {
    "code": "def get_families(self):\n        if self.retrieved:\n            raise errors.IllegalState('List has already been retrieved.')\n        self.retrieved = True\n        return objects.FamilyList(self._results, runtime=self._runtime)",
    "docstring": "Gets the family list resulting from a search.\n\n        return: (osid.relationship.FamilyList) - the family list\n        raise:  IllegalState - list already retrieved\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def register_scr_task(self, *args, **kwargs):\n        kwargs[\"task_class\"] = ScrTask\n        return self.register_task(*args, **kwargs)",
    "docstring": "Register a screening task."
  },
  {
    "code": "def parseFilename(filename):\n    _indx = filename.find('[')\n    if _indx > 0:\n        _fname = filename[:_indx]\n        _extn = filename[_indx + 1:-1]\n    else:\n        _fname = filename\n        _extn = None\n    return _fname, _extn",
    "docstring": "Parse out filename from any specified extensions.\n\n    Returns rootname and string version of extension name."
  },
  {
    "code": "def result(self):\n        if self.cancelled or (self._fn is not None):\n            raise NotExecutedYet()\n        if self._fn_exc is not None:\n            six.reraise(*self._fn_exc)\n        else:\n            return self._fn_res",
    "docstring": "The result from the executed task.  Raises NotExecutedYet if not yet\n        executed."
  },
  {
    "code": "def kde_statsmodels_m(data, grid, **kwargs):\n    kde = KDEMultivariate(data, **kwargs)\n    return kde.pdf(grid)",
    "docstring": "Multivariate Kernel Density Estimation with Statsmodels\n\n    Parameters\n    ----------\n    data : numpy.array\n        Data points used to compute a density estimator. It\n        has `n x p` dimensions, representing n points and p\n        variables.\n    grid : numpy.array\n        Data points at which the desity will be estimated. It\n        has `m x p` dimensions, representing m points and p\n        variables.\n\n    Returns\n    -------\n    out : numpy.array\n        Density estimate. Has `m x 1` dimensions"
  },
  {
    "code": "def getRelativePath(basepath, path):\n    basepath = splitpath(os.path.abspath(basepath))\n    path = splitpath(os.path.abspath(path))\n    afterCommon = False\n    for c in basepath:\n        if afterCommon or path[0] != c:\n            path.insert(0, os.path.pardir)\n            afterCommon = True\n        else:\n            del path[0]\n    return os.path.join(*path)",
    "docstring": "Get a path that is relative to the given base path."
  },
  {
    "code": "def getstrs(self):\n        status, label, unit, format = _C.SDgetdimstrs(self._id, 128)\n        _checkErr('getstrs', status, 'cannot execute')\n        return label, unit, format",
    "docstring": "Retrieve the dimension standard string attributes.\n\n        Args::\n\n          no argument\n\n        Returns::\n\n          3-element tuple holding:\n            -dimension label  (attribute 'long_name')\n            -dimension unit   (attribute 'units')\n            -dimension format (attribute 'format')\n\n        An exception is raised if the standard attributes have\n        not been set.\n\n        C library equivalent: SDgetdimstrs"
  },
  {
    "code": "def _initialize_tables(self):\n        self.table_struct, self.idnt_struct_size = self._create_struct_table()\n        self.table_values, self.idnt_values_size = self._create_values_table()",
    "docstring": "Create tables for structure and values, word->vocabulary"
  },
  {
    "code": "def decode_offset_response(cls, response):\n        return [\n            kafka.structs.OffsetResponsePayload(topic, partition, error, tuple(offsets))\n            for topic, partitions in response.topics\n            for partition, error, offsets in partitions\n        ]",
    "docstring": "Decode OffsetResponse into OffsetResponsePayloads\n\n        Arguments:\n            response: OffsetResponse\n\n        Returns: list of OffsetResponsePayloads"
  },
  {
    "code": "def aggregate_history(slugs, granularity=\"daily\", since=None, with_data_table=False):\n    r = get_r()\n    slugs = list(slugs)\n    try:\n        if since and len(since) == 10:\n            since = datetime.strptime(since, \"%Y-%m-%d\")\n        elif since and len(since) == 19:\n            since = datetime.strptime(since, \"%Y-%m-%d %H:%M:%S\")\n    except (TypeError, ValueError):\n        pass\n    history = r.get_metric_history_chart_data(\n        slugs=slugs,\n        since=since,\n        granularity=granularity\n    )\n    return {\n        'chart_id': \"metric-aggregate-history-{0}\".format(\"-\".join(slugs)),\n        'slugs': slugs,\n        'since': since,\n        'granularity': granularity,\n        'metric_history': history,\n        'with_data_table': with_data_table,\n    }",
    "docstring": "Template Tag to display history for multiple metrics.\n\n    * ``slug_list`` -- A list of slugs to display\n    * ``granularity`` -- the granularity: seconds, minutes, hourly,\n                         daily, weekly, monthly, yearly\n    * ``since`` -- a datetime object or a string string matching one of the\n      following patterns: \"YYYY-mm-dd\" for a date or \"YYYY-mm-dd HH:MM:SS\" for\n      a date & time.\n    * ``with_data_table`` -- if True, prints the raw data in a table."
  },
  {
    "code": "def translate_month_abbr(\n        date_str,\n        source_lang=DEFAULT_DATE_LANG,\n        target_lang=DEFAULT_DATE_LANG):\n    month_num, month_abbr = get_month_from_date_str(date_str, source_lang)\n    with calendar.different_locale(LOCALES[target_lang]):\n        translated_abbr = calendar.month_abbr[month_num]\n        return re.sub(\n            month_abbr, translated_abbr, date_str, flags=re.IGNORECASE)",
    "docstring": "Translate the month abbreviation from one locale to another."
  },
  {
    "code": "def discretize(value, factor=100):\n    if not isinstance(value, Iterable):\n        return int(value * factor)\n    int_value = list(deepcopy(value))\n    for i in range(len(int_value)):\n        int_value[i] = int(int_value[i] * factor)\n    return int_value",
    "docstring": "Discretize the given value, pre-multiplying by the given factor"
  },
  {
    "code": "def drain_to(self, list, max_size=-1):\n        def drain_result(f):\n            resp = f.result()\n            list.extend(resp)\n            return len(resp)\n        return self._encode_invoke(queue_drain_to_max_size_codec, max_size=max_size).continue_with(\n            drain_result)",
    "docstring": "Transfers all available items to the given `list`_ and removes these items from this queue. If a max_size is\n        specified, it transfers at most the given number of items. In case of a failure, an item can exist in both\n        collections or none of them.\n\n        This operation may be more efficient than polling elements repeatedly and putting into collection.\n\n        :param list: (`list`_), the list where the items in this queue will be transferred.\n        :param max_size: (int), the maximum number items to transfer (optional).\n        :return: (int), number of transferred items.\n\n        .. _list: https://docs.python.org/2/library/functions.html#list"
  },
  {
    "code": "def get_limit(self, request):\n        if self.limit_query_param:\n            try:\n                return _positive_int(\n                    get_query_param(request, self.limit_query_param),\n                    strict=True,\n                    cutoff=self.max_limit\n                )\n            except (KeyError, ValueError):\n                pass\n        return self.default_limit",
    "docstring": "Return limit parameter."
  },
  {
    "code": "def _reset_plain(self):\n        if self._text:\n            self._blocks.append(BlockText('\\n'.join(self._text)))\n        self._text.clear()",
    "docstring": "Create a BlockText from the captured lines and clear _text."
  },
  {
    "code": "def validate(self):\n        super().validate()\n        nb_entities = len(self.entities)\n        if nb_entities != self.rows + self.columns:\n            raise self.error(\n                'Number of entities: %s != number of rows + '\n                'number of columns: %s+%s=%s' % (\n                    nb_entities, self.rows, self.columns,\n                    self.rows + self.columns))",
    "docstring": "Base validation + entities = rows + columns."
  },
  {
    "code": "def get_hosting_devices_for_agent(self, context):\n        cctxt = self.client.prepare()\n        return cctxt.call(context,\n                          'get_hosting_devices_for_agent',\n                          host=self.host)",
    "docstring": "Get a list of hosting devices assigned to this agent."
  },
  {
    "code": "def _one_or_more_stages_remain(self, deploymentId):\n        stages = __salt__['boto_apigateway.describe_api_stages'](restApiId=self.restApiId,\n                                                                 deploymentId=deploymentId,\n                                                                 **self._common_aws_args).get('stages')\n        return bool(stages)",
    "docstring": "Helper function to find whether there are other stages still associated with a deployment"
  },
  {
    "code": "def check_package_exists(package, lib_dir):\n    try:\n        req = pkg_resources.Requirement.parse(package)\n    except ValueError:\n        req = pkg_resources.Requirement.parse(urlparse(package).fragment)\n    if lib_dir is not None:\n        if any(dist in req for dist in\n               pkg_resources.find_distributions(lib_dir)):\n            return True\n    return any(dist in req for dist in pkg_resources.working_set)",
    "docstring": "Check if a package is installed globally or in lib_dir.\n\n    Returns True when the requirement is met.\n    Returns False when the package is not installed or doesn't meet req."
  },
  {
    "code": "def myGrades(year, candidateNumber, badFormat, length):\n    weights1 = [1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5]\n    weights2 = [1, 1, 1, 1, 1, 1, 0.5, 0.5]\n    if year == 1:\n        myFinalResult = sum([int(badFormat[candidateNumber][2*(i + 1)])\n                             * weights1[i] for i in range(length-1)]) / 6\n    elif year == 2 or year == 3:\n        myFinalResult = sum([int(badFormat[candidateNumber][2*(i + 1)])\n                             * weights2[i] for i in range(length-1)]) / 7\n    elif year == 4:\n        myFinalResult = sum([int(badFormat[candidateNumber][2*(i + 1)])\n                             for i in range(length-1)]) / 8\n    return myFinalResult",
    "docstring": "returns final result of candidateNumber in year\n\n    Arguments:\n        year {int} -- the year candidateNumber is in\n        candidateNumber {str} -- the candidateNumber of candidateNumber\n        badFormat {dict} -- candNumber : [results for candidate]\n        length {int} -- length of each row in badFormat divided by 2\n\n\n    Returns:\n        int -- a weighted average for a specific candidate number and year"
  },
  {
    "code": "async def probe_message(self, _message, context):\n        client_id = context.user_data\n        await self.probe(client_id)",
    "docstring": "Handle a probe message.\n\n        See :meth:`AbstractDeviceAdapter.probe`."
  },
  {
    "code": "def page(request):\n    context = {}\n    page = getattr(request, \"page\", None)\n    if isinstance(page, Page):\n        context = {\"request\": request, \"page\": page, \"_current_page\": page}\n        page.set_helpers(context)\n    return context",
    "docstring": "Adds the current page to the template context and runs its\n    ``set_helper`` method. This was previously part of\n    ``PageMiddleware``, but moved to a context processor so that\n    we could assign these template context variables without\n    the middleware depending on Django's ``TemplateResponse``."
  },
  {
    "code": "def build_relation_predicate(relations: Strings) -> EdgePredicate:\n    if isinstance(relations, str):\n        @edge_predicate\n        def relation_predicate(edge_data: EdgeData) -> bool:\n            return edge_data[RELATION] == relations\n    elif isinstance(relations, Iterable):\n        relation_set = set(relations)\n        @edge_predicate\n        def relation_predicate(edge_data: EdgeData) -> bool:\n            return edge_data[RELATION] in relation_set\n    else:\n        raise TypeError\n    return relation_predicate",
    "docstring": "Build an edge predicate that passes for edges with the given relation."
  },
  {
    "code": "def _check_pub_data(self, pub_data, listen=True):\n        if pub_data == '':\n            raise EauthAuthenticationError(\n                'Failed to authenticate! This is most likely because this '\n                'user is not permitted to execute commands, but there is a '\n                'small possibility that a disk error occurred (check '\n                'disk/inode usage).'\n            )\n        if 'error' in pub_data:\n            print(pub_data['error'])\n            log.debug('_check_pub_data() error: %s', pub_data['error'])\n            return {}\n        elif 'jid' not in pub_data:\n            return {}\n        if pub_data['jid'] == '0':\n            print('Failed to connect to the Master, '\n                  'is the Salt Master running?')\n            return {}\n        if not self.opts.get('order_masters'):\n            if not pub_data['minions']:\n                print('No minions matched the target. '\n                      'No command was sent, no jid was assigned.')\n                return {}\n        if not listen:\n            return pub_data\n        if self.opts.get('order_masters'):\n            self.event.subscribe('syndic/.*/{0}'.format(pub_data['jid']), 'regex')\n        self.event.subscribe('salt/job/{0}'.format(pub_data['jid']))\n        return pub_data",
    "docstring": "Common checks on the pub_data data structure returned from running pub"
  },
  {
    "code": "def resolve_input_references(to_resolve, inputs_to_reference):\n    splitted = split_input_references(to_resolve)\n    result = []\n    for part in splitted:\n        if is_input_reference(part):\n            result.append(str(resolve_input_reference(part, inputs_to_reference)))\n        else:\n            result.append(part)\n    return ''.join(result)",
    "docstring": "Resolves input references given in the string to_resolve by using the inputs_to_reference.\n\n    See http://www.commonwl.org/user_guide/06-params/index.html for more information.\n\n    Example:\n    \"$(inputs.my_file.nameroot).md\" -> \"filename.md\"\n\n    :param to_resolve: The path to match\n    :param inputs_to_reference: Inputs which are used to resolve input references like $(inputs.my_input_file.basename).\n\n    :return: A string in which the input references are replaced with actual values."
  },
  {
    "code": "def __update(self):\n        width, height = self.size\n        super(BaseWidget, self).__setattr__(\"width\", width)\n        super(BaseWidget, self).__setattr__(\"height\", height)\n        super(BaseWidget, self).__setattr__(self.anchor, self.pos)",
    "docstring": "This is called each time an attribute is asked, to be sure every params are updated, beceause of callbacks."
  },
  {
    "code": "def _process_remove_objects_batch(self, bucket_name, objects_batch):\n        content = xml_marshal_delete_objects(objects_batch)\n        headers = {\n            'Content-Md5': get_md5_base64digest(content),\n            'Content-Length': len(content)\n        }\n        query = {'delete': ''}\n        content_sha256_hex = get_sha256_hexdigest(content)\n        response = self._url_open(\n            'POST', bucket_name=bucket_name,\n            headers=headers, body=content,\n            query=query, content_sha256=content_sha256_hex,\n        )\n        return parse_multi_object_delete_response(response.data)",
    "docstring": "Requester and response parser for remove_objects"
  },
  {
    "code": "def get_mor_by_name(si, obj_type, obj_name):\n    inventory = get_inventory(si)\n    container = inventory.viewManager.CreateContainerView(inventory.rootFolder, [obj_type], True)\n    for item in container.view:\n        if item.name == obj_name:\n            return item\n    return None",
    "docstring": "Get reference to an object of specified object type and name\n\n    si\n        ServiceInstance for the vSphere or ESXi server (see get_service_instance)\n\n    obj_type\n        Type of the object (vim.StoragePod, vim.Datastore, etc)\n\n    obj_name\n        Name of the object"
  },
  {
    "code": "def create_columns(self):\n        reader = self._get_csv_reader()\n        headings = six.next(reader)\n        try:\n            examples = six.next(reader)\n        except StopIteration:\n            examples = []\n        found_fields = set()\n        for i, value in enumerate(headings):\n            if i >= 20:\n                break\n            infer_field = self.has_headings and value not in found_fields\n            to_field = (\n                {\n                    \"date\": \"date\",\n                    \"amount\": \"amount\",\n                    \"description\": \"description\",\n                    \"memo\": \"description\",\n                    \"notes\": \"description\",\n                }.get(value.lower(), \"\")\n                if infer_field\n                else \"\"\n            )\n            if to_field:\n                found_fields.add(to_field)\n            TransactionCsvImportColumn.objects.update_or_create(\n                transaction_import=self,\n                column_number=i + 1,\n                column_heading=value if self.has_headings else \"\",\n                to_field=to_field,\n                example=examples[i].strip() if examples else \"\",\n            )",
    "docstring": "For each column in file create a TransactionCsvImportColumn"
  },
  {
    "code": "def body(self):\n        content = []\n        length = 0\n        for chunk in self:\n            content.append(chunk)\n            length += len(chunk)\n            if self.length_limit and length > self.length_limit:\n                self.close()\n                raise ContentLimitExceeded(\"Content length is more than %d \"\n                                           \"bytes\" % self.length_limit)\n        return b(\"\").join(content)",
    "docstring": "Response body.\n\n        :raises: :class:`ContentLimitExceeded`, :class:`ContentDecodingError`"
  },
  {
    "code": "def fit(self, X, y):\n        if not isinstance(X, pd.DataFrame):\n            X = pd.DataFrame(X.copy())\n        if not isinstance(y, pd.Series):\n            y = pd.Series(y.copy())\n        relevance_table = calculate_relevance_table(\n                                X, y, ml_task=self.ml_task, n_jobs=self.n_jobs,\n                                chunksize=self.chunksize, fdr_level=self.fdr_level,\n                                hypotheses_independent=self.hypotheses_independent,\n                                test_for_binary_target_real_feature=self.test_for_binary_target_real_feature)\n        self.relevant_features = relevance_table.loc[relevance_table.relevant].feature.tolist()\n        self.feature_importances_ = 1.0 - relevance_table.p_value.values\n        self.p_values = relevance_table.p_value.values\n        self.features = relevance_table.index.tolist()\n        return self",
    "docstring": "Extract the information, which of the features are relevent using the given target.\n\n        For more information, please see the :func:`~tsfresh.festure_selection.festure_selector.check_fs_sig_bh`\n        function. All columns in the input data sample are treated as feature. The index of all\n        rows in X must be present in y.\n\n        :param X: data sample with the features, which will be classified as relevant or not\n        :type X: pandas.DataFrame or numpy.array\n\n        :param y: target vector to be used, to classify the features\n        :type y: pandas.Series or numpy.array\n\n        :return: the fitted estimator with the information, which features are relevant\n        :rtype: FeatureSelector"
  },
  {
    "code": "def get_disease_mappings(self, att_ind_start):\n        all_disease_ids = self.get_all_unique_diseases()\n        disease_enum = enumerate(all_disease_ids, start=att_ind_start)\n        disease_mappings = {}\n        for num, dis in disease_enum:\n            disease_mappings[dis] = num\n        return disease_mappings",
    "docstring": "Get a dictionary of enumerations for diseases.\n\n        :param int att_ind_start: Starting index for enumeration.\n        :return: Dictionary of disease, number pairs."
  },
  {
    "code": "def change_message_visibility(self, queue, receipt_handle,\n                                  visibility_timeout, callback=None):\n        params = {'ReceiptHandle' : receipt_handle,\n                  'VisibilityTimeout' : visibility_timeout}\n        return self.get_status('ChangeMessageVisibility', params, queue.id, callback=callback)",
    "docstring": "Extends the read lock timeout for the specified message from\n        the specified queue to the specified value.\n\n        :type queue: A :class:`boto.sqs.queue.Queue` object\n        :param queue: The Queue from which messages are read.\n        \n        :type receipt_handle: str\n        :param queue: The receipt handle associated with the message whose\n                      visibility timeout will be changed.\n        \n        :type visibility_timeout: int\n        :param visibility_timeout: The new value of the message's visibility\n                                   timeout in seconds."
  },
  {
    "code": "def _chk_docopt_exit(self, args, exp_letters):\n        if args is None:\n            args = sys.argv[1:]\n        keys_all = self.exp_keys.union(self.exp_elems)\n        if exp_letters:\n            keys_all |= exp_letters\n        unknown_args = self._chk_docunknown(args, keys_all)\n        if unknown_args:\n            raise RuntimeError(\"{USAGE}\\n    **FATAL: UNKNOWN ARGS: {UNK}\".format(\n                USAGE=self.doc, UNK=\" \".join(unknown_args)))",
    "docstring": "Check if docopt exit was for an unknown argument."
  },
  {
    "code": "def has_option(self, option):\n        if len(self.options) == 0:\n            return False\n        for op in self.options:\n            if (self._sized_op and op[0] == option) or (op == option):\n                return True\n        return False",
    "docstring": "Return True if the option is included in this key.\n\n        Parameters\n        ----------\n        option : str\n            The option.\n\n        Returns\n        -------\n        has : bool\n            True if the option can be found. Otherwise False will be returned."
  },
  {
    "code": "def register_project(self, path, ensure_uniqueness=False):\n        if ensure_uniqueness:\n            if self.get_project_nodes(path):\n                raise foundations.exceptions.ProgrammingError(\"{0} | '{1}' project is already registered!\".format(\n                    self.__class__.__name__, path))\n        LOGGER.debug(\"> Registering '{0}' project.\".format(path))\n        row = self.root_node.children_count()\n        self.beginInsertRows(self.get_node_index(self.root_node, ), row, row)\n        project_node = ProjectNode(name=os.path.basename(path),\n                                   path=path,\n                                   parent=self.root_node)\n        self.endInsertRows()\n        self.project_registered.emit(project_node)\n        return project_node",
    "docstring": "Registers given path in the Model as a project.\n\n        :param path: Project path to register.\n        :type path: unicode\n        :param ensure_uniqueness: Ensure registrar uniqueness.\n        :type ensure_uniqueness: bool\n        :return: ProjectNode.\n        :rtype: ProjectNode"
  },
  {
    "code": "def list_instances(self):\n        response = self.get_proto(path='/instances')\n        message = rest_pb2.ListInstancesResponse()\n        message.ParseFromString(response.content)\n        instances = getattr(message, 'instance')\n        return iter([Instance(instance) for instance in instances])",
    "docstring": "Lists the instances.\n\n        Instances are returned in lexicographical order.\n\n        :rtype: ~collections.Iterable[.Instance]"
  },
  {
    "code": "def get_count(self,name):\n        if name not in self.mlt_counter:\n            self.mlt_counter[name] = 1\n            c = 0\n        else:\n            c = self.mlt_counter[name]\n            self.mlt_counter[name] += 1\n        return c",
    "docstring": "get the latest counter for a certain parameter type.\n\n        Parameters\n        ----------\n        name : str\n            the parameter type\n\n        Returns\n        -------\n        count : int\n            the latest count for a parameter type\n\n        Note\n        ----\n        calling this function increments the counter for the passed\n        parameter type"
  },
  {
    "code": "def n_frames_total(self, stride=1, skip=0):\n        r\n        if not IteratorState.is_uniform_stride(stride):\n            return len(stride)\n        return sum(self.trajectory_lengths(stride=stride, skip=skip))",
    "docstring": "r\"\"\"Returns total number of frames.\n\n        Parameters\n        ----------\n        stride : int\n            return value is the number of frames in trajectories when\n            running through them with a step size of `stride`.\n        skip : int, default=0\n            skip the first initial n frames per trajectory.\n        Returns\n        -------\n        n_frames_total : int\n            total number of frames."
  },
  {
    "code": "def startsafter(self, other):\n        if self.is_valid_range(other):\n            if self.lower == other.lower:\n                return other.lower_inc or not self.lower_inc\n            elif self.lower_inf:\n                return False\n            elif other.lower_inf:\n                return True\n            else:\n                return self.lower > other.lower\n        elif self.is_valid_scalar(other):\n            return self.lower >= other\n        else:\n            raise TypeError(\n                \"Unsupported type to test for starts after '{}'\".format(\n                    other.__class__.__name__))",
    "docstring": "Test if this range starts after `other`. `other` may be either range or\n        scalar. This only takes the lower end of the ranges into consideration.\n        If the scalar or the lower end of the given range is greater than or\n        equal to this range's lower end, ``True`` is returned.\n\n            >>> intrange(1, 5).startsafter(0)\n            True\n            >>> intrange(1, 5).startsafter(intrange(0, 5))\n            True\n\n        If ``other`` has the same start as the given\n\n        :param other: Range or scalar to test.\n        :return: ``True`` if this range starts after `other`, otherwise ``False``\n        :raises TypeError: If `other` is of the wrong type."
  },
  {
    "code": "def list_files(dir_path, recursive=True):\n    for root, dirs, files in os.walk(dir_path):\n        file_list = [os.path.join(root, f) for f in files]\n        if recursive:\n            for dir in dirs:\n                dir = os.path.join(root, dir)\n                file_list.extend(list_files(dir, recursive=True))\n        return file_list",
    "docstring": "Return a list of files in dir_path."
  },
  {
    "code": "def publish_scene_velocity(self, scene_id, velocity):\n        self.sequence_number += 1\n        self.publisher.send_multipart(msgs.MessageBuilder.scene_velocity(self.sequence_number, scene_id, velocity))\n        return self.sequence_number",
    "docstring": "publish a changed scene velovity"
  },
  {
    "code": "def _new_java_array(pylist, java_class):\n        sc = SparkContext._active_spark_context\n        java_array = None\n        if len(pylist) > 0 and isinstance(pylist[0], list):\n            inner_array_length = 0\n            for i in xrange(len(pylist)):\n                inner_array_length = max(inner_array_length, len(pylist[i]))\n            java_array = sc._gateway.new_array(java_class, len(pylist), inner_array_length)\n            for i in xrange(len(pylist)):\n                for j in xrange(len(pylist[i])):\n                    java_array[i][j] = pylist[i][j]\n        else:\n            java_array = sc._gateway.new_array(java_class, len(pylist))\n            for i in xrange(len(pylist)):\n                java_array[i] = pylist[i]\n        return java_array",
    "docstring": "Create a Java array of given java_class type. Useful for\n        calling a method with a Scala Array from Python with Py4J.\n        If the param pylist is a 2D array, then a 2D java array will be returned.\n        The returned 2D java array is a square, non-jagged 2D array that is big\n        enough for all elements. The empty slots in the inner Java arrays will\n        be filled with null to make the non-jagged 2D array.\n\n        :param pylist:\n          Python list to convert to a Java Array.\n        :param java_class:\n          Java class to specify the type of Array. Should be in the\n          form of sc._gateway.jvm.* (sc is a valid Spark Context).\n        :return:\n          Java Array of converted pylist.\n\n        Example primitive Java classes:\n          - basestring -> sc._gateway.jvm.java.lang.String\n          - int -> sc._gateway.jvm.java.lang.Integer\n          - float -> sc._gateway.jvm.java.lang.Double\n          - bool -> sc._gateway.jvm.java.lang.Boolean"
  },
  {
    "code": "def make_dbsource(**kwargs):\n    if 'spatialite' in connection.settings_dict.get('ENGINE'):\n        kwargs.setdefault('file', connection.settings_dict['NAME'])\n        return mapnik.SQLite(wkb_format='spatialite', **kwargs)\n    names = (('dbname', 'NAME'), ('user', 'USER'),\n             ('password', 'PASSWORD'), ('host', 'HOST'), ('port', 'PORT'))\n    for mopt, dopt in names:\n        val = connection.settings_dict.get(dopt)\n        if val:\n            kwargs.setdefault(mopt, val)\n    return mapnik.PostGIS(**kwargs)",
    "docstring": "Returns a mapnik PostGIS or SQLite Datasource."
  },
  {
    "code": "def save(self, outfile, close_file=True, **kwargs):\n        if isinstance(outfile, text_type) or isinstance(outfile, binary_type):\n            fid = open(outfile, 'wb')\n        else:\n            fid = outfile\n        root = self.get_root()\n        html = root.render(**kwargs)\n        fid.write(html.encode('utf8'))\n        if close_file:\n            fid.close()",
    "docstring": "Saves an Element into a file.\n\n        Parameters\n        ----------\n        outfile : str or file object\n            The file (or filename) where you want to output the html.\n        close_file : bool, default True\n            Whether the file has to be closed after write."
  },
  {
    "code": "def as_singular(result_key):\n    if result_key.endswith('ies'):\n        return re.sub('ies$', 'y', result_key)\n    elif result_key.endswith('uses'):\n        return re.sub(\"uses$\", \"us\", result_key)\n    elif result_key.endswith('addresses'):\n        return result_key[:-2]\n    elif result_key.endswith('s'):\n        return result_key[:-1]\n    else:\n        return result_key",
    "docstring": "Given a result key, return in the singular form"
  },
  {
    "code": "def frange(start, stop, step, digits_to_round=3):\n        while start < stop:\n            yield round(start, digits_to_round)\n            start += step",
    "docstring": "Works like range for doubles\n\n        :param start: starting value\n        :param stop: ending value\n        :param step: the increment_value\n        :param digits_to_round: the digits to which to round \\\n        (makes floating-point numbers much easier to work with)\n        :return: generator"
  },
  {
    "code": "def hasIP(self, ip):\n        for f in self.features:\n            if (f.prop.startswith(\"net_interface.\") and\n                    f.prop.endswith(\".ip\") and f.value == ip):\n                return True\n        return False",
    "docstring": "Return True if some system has this IP."
  },
  {
    "code": "def compute_convex_hull(feed: \"Feed\") -> Polygon:\n    m = sg.MultiPoint(feed.stops[[\"stop_lon\", \"stop_lat\"]].values)\n    return m.convex_hull",
    "docstring": "Return a Shapely Polygon representing the convex hull formed by\n    the stops of the given Feed."
  },
  {
    "code": "def parse_collection(obj: dict) -> BioCCollection:\r\n    collection = BioCCollection()\r\n    collection.source = obj['source']\r\n    collection.date = obj['date']\r\n    collection.key = obj['key']\r\n    collection.infons = obj['infons']\r\n    for doc in obj['documents']:\r\n        collection.add_document(parse_doc(doc))\r\n    return collection",
    "docstring": "Deserialize a dict obj to a BioCCollection object"
  },
  {
    "code": "def parse_colors(s, length=1):\n    if length and length > 1:\n        return parse_ctuple(s,length=length);\n    if re.match('^ *{} *$'.format(isrx_s), s):\n        return [s];\n    elif re.match('^ *{} *$'.format(rgbrx_s), s):\n        return [eval(s)];\n    else:\n        return parse_ctuple(s,length=length);",
    "docstring": "helper for parsing a string that can be either a matplotlib\n       color or be a tuple of colors. Returns a tuple of them either\n       way."
  },
  {
    "code": "def remove_population(self,pop):\n        iremove=None\n        for i in range(len(self.poplist)):\n            if self.modelnames[i]==self.poplist[i].model:\n                iremove=i\n        if iremove is not None:\n            self.modelnames.pop(i)\n            self.shortmodelnames.pop(i)\n            self.poplist.pop(i)",
    "docstring": "Removes population from PopulationSet"
  },
  {
    "code": "def _normalize_xml_search_response(self, xml):\n        target = XMLSearchResult()\n        parser = ElementTree.XMLParser(target=target)\n        parser.feed(xml)\n        return parser.close()",
    "docstring": "Normalizes an XML search response so that PB and HTTP have the\n        same return value"
  },
  {
    "code": "def _adjust_regs(self):\n        if not self.adjust_stack:\n            return\n        bp = self.state.arch.register_names[self.state.arch.bp_offset]\n        sp = self.state.arch.register_names[self.state.arch.sp_offset]\n        stack_shift = self.state.arch.initial_sp - self.real_stack_top\n        self.state.registers.store(sp, self.state.regs.sp + stack_shift)\n        if not self.omit_fp:\n            self.state.registers.store(bp, self.state.regs.bp + stack_shift)",
    "docstring": "Adjust bp and sp w.r.t. stack difference between GDB session and angr.\n        This matches sp and bp registers, but there is a high risk of pointers inconsistencies."
  },
  {
    "code": "def refer(self, text):\n        data = self.reply(text)\n        data['refer_key'] = self['key']\n        return data",
    "docstring": "Refers current message and replys a new message\n\n        Args:\n            text(str): message content\n\n        Returns:\n            RTMMessage"
  },
  {
    "code": "def endGroup(self):\r\n        if self._customFormat:\r\n            self._customFormat.endGroup()\r\n        else:\r\n            super(XSettings, self).endGroup()",
    "docstring": "Ends the current group of xml data."
  },
  {
    "code": "def GET_save_conditionvalues(self) -> None:\n        state.conditions[self._id] = state.conditions.get(self._id, {})\n        state.conditions[self._id][state.idx2] = state.hp.conditions",
    "docstring": "Save the |StateSequence| and |LogSequence| object values of the\n        current |HydPy| instance for the current simulation endpoint."
  },
  {
    "code": "def to_tex(self, text_size='large', table_width=5, clear_pages = False):\n        max_ex_scheme = 0\n        if self._rendered:\n            for (week, day, dynamic_ex) in self._yield_week_day_dynamic():\n                lengths = [len(s) for s in\n                           self._rendered[week][day][dynamic_ex]['strings']]\n                max_ex_scheme = max(max_ex_scheme, max(lengths))\n        env = self.jinja2_environment\n        template = env.get_template(self.TEMPLATE_NAMES['tex'])\n        return template.render(program=self, text_size=text_size,\n                               table_width=table_width, clear_pages = clear_pages)",
    "docstring": "Write the program information to a .tex file, which can be\n        rendered to .pdf running pdflatex. The program can then be\n        printed and brought to the gym.\n\n        Parameters\n        ----------\n        text_size\n            The tex text size, e.g. '\\small', 'normalsize', 'large', 'Large'\n            or 'LARGE'.\n\n        table_width\n            The table with of the .tex code.\n\n        Returns\n        -------\n        string\n            Program as tex."
  },
  {
    "code": "def patch(self, delta):\n        \"Applies delta for local file to remote file via API.\"\n        return self.api.post('path/sync/patch', self.path, delta=delta)",
    "docstring": "Applies delta for local file to remote file via API."
  },
  {
    "code": "def run(self):\n        self.busy = True\n        for i in range(9):\n            self.counter += 1\n            time.sleep(0.5)\n            pass\n        self.counter += 1\n        self.busy = False\n        return",
    "docstring": "This method is run by a separated thread"
  },
  {
    "code": "def _parse_size(self, size, has_time=False):\n        if has_time:\n            size = size or 4\n        else:\n            size = size or 10\n        if isinstance(size, str):\n            size = {'column': size}\n        if isinstance(size, dict):\n            if 'column' not in size:\n                raise ValueError(\"`size` must include a 'column' key/value\")\n            if has_time:\n                raise ValueError(\"When time is specified, size can \"\n                                 \"only be a fixed size\")\n            old_size = size\n            size = {\n                'range': [5, 25],\n                'bins': 5,\n                'bin_method': BinMethod.quantiles,\n            }\n            old_size['range'] = old_size.get('range', size['range'])\n            if 'min' in old_size:\n                old_size['range'][0] = old_size['min']\n                old_size.pop('min')\n            if 'max' in old_size:\n                old_size['range'][1] = old_size['max']\n                old_size.pop('max')\n            size.update(old_size)\n            self.style_cols[size['column']] = None\n        return size",
    "docstring": "Parse size inputs"
  },
  {
    "code": "def main():\n    trig_pin = 17\n    echo_pin = 27\n    hole_depth = 31.5\n    value = sensor.Measurement(trig_pin,\n                               echo_pin,\n                               temperature=68,\n                               unit='imperial',\n                               round_to=2\n                               )\n    raw_measurement = value.raw_distance()\n    liquid_depth = value.depth_imperial(raw_measurement, hole_depth)\n    print(\"Depth = {} inches\".format(liquid_depth))",
    "docstring": "Calculate the depth of a liquid in inches using a HCSR04 sensor\n       and a Raspberry Pi"
  },
  {
    "code": "def url_builder(self, endpoint, *, root=None, params=None, url_params=None):\n        if root is None:\n            root = self.ROOT\n        return ''.join([\n            root,\n            endpoint,\n            '?' + urlencode(url_params) if url_params else '',\n        ]).format(**params or {})",
    "docstring": "Create a URL for the specified endpoint.\n\n        Arguments:\n          endpoint (:py:class:`str`): The API endpoint to access.\n          root: (:py:class:`str`, optional): The root URL for the\n            service API.\n          params: (:py:class:`dict`, optional): The values for format\n            into the created URL (defaults to ``None``).\n          url_params: (:py:class:`dict`, optional): Parameters to add\n            to the end of the URL (defaults to ``None``).\n\n        Returns:\n          :py:class:`str`: The resulting URL."
  },
  {
    "code": "def future_check_sensor(self, name, update=None):\n        exist = False\n        yield self.until_data_synced()\n        if name in self._sensors_index:\n            exist = True\n        else:\n            if update or (update is None and self._update_on_lookup):\n                yield self.inspect_sensors(name)\n                exist = yield self.future_check_sensor(name, False)\n        raise tornado.gen.Return(exist)",
    "docstring": "Check if the sensor exists.\n\n        Used internally by future_get_sensor. This method is aware of\n        synchronisation in progress and if inspection of the server is allowed.\n\n        Parameters\n        ----------\n        name : str\n            Name of the sensor to verify.\n        update : bool or None, optional\n            If a katcp request to the server should be made to check if the\n            sensor is on the server now.\n\n        Notes\n        -----\n        Ensure that self.state.data_synced == True if yielding to\n        future_check_sensor from a state-change callback, or a deadlock will\n        occur."
  },
  {
    "code": "def spawn(mode, func, *args, **kwargs):\n    if mode is None:\n        mode = 'threading'\n    elif mode not in spawn.modes:\n        raise ValueError('Invalid spawn mode: %s' % mode)\n    if mode == 'threading':\n        return spawn_thread(func, *args, **kwargs)\n    elif mode == 'gevent':\n        import gevent\n        import gevent.monkey\n        gevent.monkey.patch_select()\n        gevent.monkey.patch_socket()\n        return gevent.spawn(func, *args, **kwargs)\n    elif mode == 'eventlet':\n        import eventlet\n        eventlet.patcher.monkey_patch(select=True, socket=True)\n        return eventlet.spawn(func, *args, **kwargs)\n    assert False",
    "docstring": "Spawns a thread-like object which runs the given function concurrently.\n\n    Available modes:\n\n    - `threading`\n    - `greenlet`\n    - `eventlet`"
  },
  {
    "code": "def makeLabel(self, value):\n        value, prefix = format_units(value, self.step,\n                                     system=self.unitSystem)\n        span, spanPrefix = format_units(self.span, self.step,\n                                        system=self.unitSystem)\n        if prefix:\n            prefix += \" \"\n        if value < 0.1:\n            return \"%g %s\" % (float(value), prefix)\n        elif value < 1.0:\n            return \"%.2f %s\" % (float(value), prefix)\n        if span > 10 or spanPrefix != prefix:\n            if type(value) is float:\n                return \"%.1f %s\" % (value, prefix)\n            else:\n                return \"%d %s\" % (int(value), prefix)\n        elif span > 3:\n            return \"%.1f %s\" % (float(value), prefix)\n        elif span > 0.1:\n            return \"%.2f %s\" % (float(value), prefix)\n        else:\n            return \"%g %s\" % (float(value), prefix)",
    "docstring": "Create a label for the specified value.\n\n        Create a label string containing the value and its units (if any),\n        based on the values of self.step, self.span, and self.unitSystem."
  },
  {
    "code": "def map2matrix(data_map, layout):\n    r\n    layout = np.array(layout)\n    n_obj = np.prod(layout)\n    image_shape = (np.array(data_map.shape) // layout)[0]\n    data_matrix = []\n    for i in range(n_obj):\n        lower = (image_shape * (i // layout[1]),\n                 image_shape * (i % layout[1]))\n        upper = (image_shape * (i // layout[1] + 1),\n                 image_shape * (i % layout[1] + 1))\n        data_matrix.append((data_map[lower[0]:upper[0],\n                            lower[1]:upper[1]]).reshape(image_shape ** 2))\n    return np.array(data_matrix).T",
    "docstring": "r\"\"\"Map to Matrix\n\n    This method transforms a 2D map to a 2D matrix\n\n    Parameters\n    ----------\n    data_map : np.ndarray\n        Input data map, 2D array\n    layout : tuple\n        2D layout of 2D images\n\n    Returns\n    -------\n    np.ndarray 2D matrix\n\n    Raises\n    ------\n    ValueError\n        For invalid layout\n\n    Examples\n    --------\n    >>> from modopt.base.transform import map2matrix\n    >>> a = np.array([[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13],\n    [10, 11, 14, 15]])\n    >>> map2matrix(a, (2, 2))\n    array([[ 0,  4,  8, 12],\n           [ 1,  5,  9, 13],\n           [ 2,  6, 10, 14],\n           [ 3,  7, 11, 15]])"
  },
  {
    "code": "def strip_masked(fasta, min_len, print_masked):\n    for seq in parse_fasta(fasta):\n        nm, masked = parse_masked(seq, min_len)\n        nm = ['%s removed_masked >=%s' % (seq[0], min_len), ''.join(nm)]\n        yield [0, nm]\n        if print_masked is True:\n            for i, m in enumerate([i for i in masked if i != []], 1):\n                m = ['%s insertion:%s' % (seq[0], i), ''.join(m)]\n                yield [1, m]",
    "docstring": "remove masked regions from fasta file as long as\n    they are longer than min_len"
  },
  {
    "code": "def configure_root_iam_credentials(self, access_key, secret_key, region=None, iam_endpoint=None, sts_endpoint=None,\n                                       max_retries=-1, mount_point=DEFAULT_MOUNT_POINT):\n        params = {\n            'access_key': access_key,\n            'secret_key': secret_key,\n            'region': region,\n            'iam_endpoint': iam_endpoint,\n            'sts_endpoint': sts_endpoint,\n            'max_retries': max_retries,\n        }\n        api_path = '/v1/{mount_point}/config/root'.format(mount_point=mount_point)\n        return self._adapter.post(\n            url=api_path,\n            json=params,\n        )",
    "docstring": "Configure the root IAM credentials to communicate with AWS.\n\n        There are multiple ways to pass root IAM credentials to the Vault server, specified below with the highest\n        precedence first. If credentials already exist, this will overwrite them.\n\n        The official AWS SDK is used for sourcing credentials from env vars, shared files, or IAM/ECS instances.\n\n            * Static credentials provided to the API as a payload\n            * Credentials in the AWS_ACCESS_KEY, AWS_SECRET_KEY, and AWS_REGION environment variables on the server\n            * Shared credentials files\n            * Assigned IAM role or ECS task role credentials\n\n        At present, this endpoint does not confirm that the provided AWS credentials are valid AWS credentials with\n        proper permissions.\n\n        Supported methods:\n            POST: /{mount_point}/config/root. Produces: 204 (empty body)\n\n        :param access_key: Specifies the AWS access key ID.\n        :type access_key: str | unicode\n        :param secret_key: Specifies the AWS secret access key.\n        :type secret_key: str | unicode\n        :param region: Specifies the AWS region. If not set it will use the AWS_REGION env var, AWS_DEFAULT_REGION env\n            var, or us-east-1 in that order.\n        :type region: str | unicode\n        :param iam_endpoint: Specifies a custom HTTP IAM endpoint to use.\n        :type iam_endpoint: str | unicode\n        :param sts_endpoint: Specifies a custom HTTP STS endpoint to use.\n        :type sts_endpoint: str | unicode\n        :param max_retries: Number of max retries the client should use for recoverable errors. The default (-1) falls\n            back to the AWS SDK's default behavior.\n        :type max_retries: int\n        :param mount_point: The \"path\" the method/backend was mounted on.\n        :type mount_point: str | unicode\n        :return: The response of the request.\n        :rtype: requests.Response"
  },
  {
    "code": "def is_to_be_built_or_is_installed(self, shutit_module_obj):\n\t\tshutit_global.shutit_global_object.yield_to_draw()\n\t\tcfg = self.cfg\n\t\tif cfg[shutit_module_obj.module_id]['shutit.core.module.build']:\n\t\t\treturn True\n\t\treturn self.is_installed(shutit_module_obj)",
    "docstring": "Returns true if this module is configured to be built, or if it is already installed."
  },
  {
    "code": "def get(self, filename):\n        params = {\n            \"v\": 'dreambox',\n            \"kolejka\": \"false\",\n            \"nick\": \"\",\n            \"pass\": \"\",\n            \"napios\": sys.platform,\n            \"l\": self.language.upper(),\n            \"f\": self.prepareHash(filename),\n        }\n        params['t'] = self.discombobulate(params['f'])\n        url = self.url_base + urllib.urlencode(params)\n        subs = urllib.urlopen(url).read()\n        if subs.startswith('brak pliku tymczasowego'):\n            raise NapiprojektException('napiprojekt.pl API error')\n        if subs[0:4] != 'NPc0':\n            for cdc in ['cp1250', 'utf8']:\n                try:\n                    return codecs.decode(subs, cdc)\n                except:\n                    pass",
    "docstring": "returns subtitles as string"
  },
  {
    "code": "def confirm_updated(value, check_fun, normalize_ret=False, wait=5):\n    for i in range(wait):\n        state = validate_enabled(check_fun()) if normalize_ret else check_fun()\n        if value in state:\n            return True\n        time.sleep(1)\n    return False",
    "docstring": "Wait up to ``wait`` seconds for a system parameter to be changed before\n    deciding it hasn't changed.\n\n    :param str value: The value indicating a successful change\n\n    :param function check_fun: The function whose return is compared with\n        ``value``\n\n    :param bool normalize_ret: Whether to normalize the return from\n        ``check_fun`` with ``validate_enabled``\n\n    :param int wait: The maximum amount of seconds to wait for a system\n        parameter to change"
  },
  {
    "code": "def parse_z(cls, offset):\n        assert len(offset) == 5, 'Invalid offset string format, must be \"+HHMM\"'\n        return timedelta(hours=int(offset[:3]), minutes=int(offset[0] + offset[3:]))",
    "docstring": "Parse %z offset into `timedelta`"
  },
  {
    "code": "def get_endpoint_server_root(self):\n        parsed = urlparse(self._endpoint)\n        root = parsed.scheme + \"://\" + parsed.hostname\n        if parsed.port is not None:\n            root += \":\" + unicode(parsed.port)\n        return root",
    "docstring": "Parses RemoteLRS object's endpoint and returns its root\n\n        :return: Root of the RemoteLRS object endpoint\n        :rtype: unicode"
  },
  {
    "code": "def do_serialize(self, line):\n        opts = self.SERIALIZE_OPTS\n        if not self.current:\n            self._help_noontology()\n            return\n        line = line.split()\n        g = self.current['graph']\n        if not line:\n            line = ['turtle']\n        if line[0] not in opts:\n            self.help_serialize()\n            return\n        elif self.currentEntity:\n            self.currentEntity['object'].printSerialize(line[0])\n        else:\n            self._print(g.rdf_source(format=line[0]))",
    "docstring": "Serialize an entity into an RDF flavour"
  },
  {
    "code": "def get_user(self, username):\n        sql = \n        self._db_curs.execute(sql, (username, ))\n        user = self._db_curs.fetchone()\n        return user",
    "docstring": "Fetch the user from the database\n\n            The function will return None if the user is not found"
  },
  {
    "code": "def write(self):\n        with open(storage.config_file, 'w') as cfg:\n            yaml.dump(self.as_dict(), cfg, default_flow_style=False)\n        storage.refresh()",
    "docstring": "write the current settings to the config file"
  },
  {
    "code": "def remove_from_known_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False):\n        for host in hosts:\n            logger.info('[%s] Removing the remote host SSH public key from [%s]...', host.hostname, known_hosts)\n            cmd = ['ssh-keygen', '-f', known_hosts, '-R', host.hostname]\n            logger.debug('Call: %s', ' '.join(cmd))\n            if not dry:\n                try:\n                    subprocess.check_call(cmd)\n                except subprocess.CalledProcessError as ex:\n                    logger.error(format_error(format_exception(ex)))",
    "docstring": "Remove the remote host SSH public key to the `known_hosts` file.\n\n        :param hosts: the list of the remote `Host` objects.\n        :param known_hosts: the `known_hosts` file to store the SSH public keys.\n        :param dry: perform a dry run."
  },
  {
    "code": "def parse_eddystone_service_data(data):\n    if data['frame_type'] == EDDYSTONE_UID_FRAME:\n        return EddystoneUIDFrame(data['frame'])\n    elif data['frame_type'] == EDDYSTONE_TLM_FRAME:\n        if data['frame']['tlm_version'] == EDDYSTONE_TLM_ENCRYPTED:\n            return EddystoneEncryptedTLMFrame(data['frame']['data'])\n        elif data['frame']['tlm_version'] == EDDYSTONE_TLM_UNENCRYPTED:\n            return EddystoneTLMFrame(data['frame']['data'])\n    elif data['frame_type'] == EDDYSTONE_URL_FRAME:\n        return EddystoneURLFrame(data['frame'])\n    elif data['frame_type'] == EDDYSTONE_EID_FRAME:\n        return EddystoneEIDFrame(data['frame'])\n    else:\n        return None",
    "docstring": "Parse Eddystone service data."
  },
  {
    "code": "def check_type_of_param_list_elements(param_list):\n    try:\n        assert isinstance(param_list[0], np.ndarray)\n        assert all([(x is None or isinstance(x, np.ndarray))\n                    for x in param_list])\n    except AssertionError:\n        msg = \"param_list[0] must be a numpy array.\"\n        msg_2 = \"All other elements must be numpy arrays or None.\"\n        total_msg = msg + \"\\n\" + msg_2\n        raise TypeError(total_msg)\n    return None",
    "docstring": "Ensures that all elements of param_list are ndarrays or None. Raises a\n    helpful ValueError if otherwise."
  },
  {
    "code": "def _subtoken_id_to_subtoken_string(self, subtoken):\n    if 0 <= subtoken < self.vocab_size:\n      return self._all_subtoken_strings[subtoken]\n    return u\"\"",
    "docstring": "Converts a subtoken integer ID to a subtoken string."
  },
  {
    "code": "async def list(source):\n    result = []\n    async with streamcontext(source) as streamer:\n        async for item in streamer:\n            result.append(item)\n    yield result",
    "docstring": "Generate a single list from an asynchronous sequence."
  },
  {
    "code": "def _AsList(arg):\n    if (isinstance(arg, string_types) or\n        not isinstance(arg, collections.Iterable)):\n      return [arg]\n    else:\n      return list(arg)",
    "docstring": "Encapsulates an argument in a list, if it's not already iterable."
  },
  {
    "code": "def least_squares(Cui, X, Y, regularization, num_threads=0):\n    users, n_factors = X.shape\n    YtY = Y.T.dot(Y)\n    for u in range(users):\n        X[u] = user_factor(Y, YtY, Cui, u, regularization, n_factors)",
    "docstring": "For each user in Cui, calculate factors Xu for them\n    using least squares on Y.\n\n    Note: this is at least 10 times slower than the cython version included\n    here."
  },
  {
    "code": "def StartingAgeEnum(ctx):\n    return Enum(\n        ctx,\n        what=-2,\n        unset=-1,\n        dark=0,\n        feudal=1,\n        castle=2,\n        imperial=3,\n        postimperial=4,\n        dmpostimperial=6\n    )",
    "docstring": "Starting Age Enumeration."
  },
  {
    "code": "def show_floating_ip(kwargs=None, call=None):\n    if call != 'function':\n        log.error(\n            'The show_floating_ip function must be called with -f or --function.'\n        )\n        return False\n    if not kwargs:\n        kwargs = {}\n    if 'floating_ip' not in kwargs:\n        log.error('A floating IP is required.')\n        return False\n    floating_ip = kwargs['floating_ip']\n    log.debug('Floating ip is %s', floating_ip)\n    details = query(method='floating_ips', command=floating_ip)\n    return details",
    "docstring": "Show the details of a floating IP\n\n    .. versionadded:: 2016.3.0\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47'"
  },
  {
    "code": "def get_inheritors(cls):\n    subclasses = set()\n    work = [cls]\n    while work:\n        parent = work.pop()\n        for child in parent.__subclasses__():\n            if child not in subclasses:\n                subclasses.add(child)\n                work.append(child)\n    return subclasses",
    "docstring": "Get a set of all classes that inherit from the given class."
  },
  {
    "code": "def _parse_incval(incunit, incval):\n        try:\n            retn = [int(val) for val in incval.split(',')]\n        except ValueError:\n            return None\n        return retn[0] if len(retn) == 1 else retn",
    "docstring": "Parse a non-day increment value. Should be an integer or a comma-separated integer list."
  },
  {
    "code": "def options(self, context, module_options):\n        if not 'URL' in module_options:\n            context.log.error('URL option is required!')\n            exit(1)\n        self.url = module_options['URL']",
    "docstring": "URL  URL for the download cradle"
  },
  {
    "code": "def getDate():\n    _ltime = _time.localtime(_time.time())\n    date_str = _time.strftime('%Y-%m-%dT%H:%M:%S',_ltime)\n    return date_str",
    "docstring": "Returns a formatted string with the current date."
  },
  {
    "code": "def CheckTaskReadyForMerge(self, task):\n    if self._storage_type != definitions.STORAGE_TYPE_SESSION:\n      raise IOError('Unsupported storage type.')\n    if not self._processed_task_storage_path:\n      raise IOError('Missing processed task storage path.')\n    processed_storage_file_path = self._GetProcessedStorageFilePath(task)\n    try:\n      stat_info = os.stat(processed_storage_file_path)\n    except (IOError, OSError):\n      return False\n    task.storage_file_size = stat_info.st_size\n    return True",
    "docstring": "Checks if a task is ready for merging with this session storage.\n\n    If the task is ready to be merged, this method also sets the task's\n    storage file size.\n\n    Args:\n      task (Task): task.\n\n    Returns:\n      bool: True if the task is ready to be merged.\n\n    Raises:\n      IOError: if the storage type is not supported or\n      OSError: if the storage type is not supported or\n          if the temporary path for the task storage does not exist."
  },
  {
    "code": "def find_span_linear(degree, knot_vector, num_ctrlpts, knot, **kwargs):\n    span = 0\n    while span < num_ctrlpts and knot_vector[span] <= knot:\n        span += 1\n    return span - 1",
    "docstring": "Finds the span of a single knot over the knot vector using linear search.\n\n    Alternative implementation for the Algorithm A2.1 from The NURBS Book by Piegl & Tiller.\n\n    :param degree: degree, :math:`p`\n    :type degree: int\n    :param knot_vector: knot vector, :math:`U`\n    :type knot_vector: list, tuple\n    :param num_ctrlpts: number of control points, :math:`n + 1`\n    :type num_ctrlpts: int\n    :param knot: knot or parameter, :math:`u`\n    :type knot: float\n    :return: knot span\n    :rtype: int"
  },
  {
    "code": "def check_units_and_type(input, expected_units, num=None, is_scalar=False):\n    if hasattr(input, 'unit'):\n        if expected_units is None:\n            raise ValueError('Expecting dimensionless input')\n        elif input.unit != expected_units:\n            raise ValueError('Expecting input units of ' + str(expected_units))\n        else:\n            dimensionless = input.value\n    else:\n        dimensionless = input\n    if is_scalar is False:\n        dimensionfull = check_array_or_list(dimensionless)\n    else:\n        dimensionfull = dimensionless\n    if expected_units is not None:\n        dimensionfull = dimensionfull * expected_units\n    if num is not None:\n        check_input_size(dimensionfull, num)\n    return dimensionfull",
    "docstring": "Check whether variable has expected units and type.\n\n    If input does not have units and expected units is not None, then the\n    output will be assigned those units. If input has units that conflict\n    with expected units a ValueError will be raised.\n\n    Parameters\n    ----------\n    input : array_like or float\n        Variable that will be checked for units and type. Variable should\n        be 1D or scalar.\n    expected_units : astropy.units or None\n        Unit expected for input.\n    num : int, optional\n        Length expected for input, if it is an array or list.\n    is_scalar : bool, optional\n        Sets whether the input is a scalar quantity. Default is False for\n        array_like inputs; set is_scalar=True to check scalar units only.\n\n    Returns\n    ----------\n    ndarray or float, with astropy.units\n        Returns the input array or scalar with expected units, unless a\n        conflict of units or array length occurs, which raise errors."
  },
  {
    "code": "def linear_gradient(start_hex, finish_hex, n=10):\n    s = hex2rgb(start_hex)\n    f = hex2rgb(finish_hex)\n    gradient = [s]\n    for t in range(1, n):\n        curr_vector = [int(s[j] + (float(t)/(n-1))*(f[j]-s[j])) for j in range(3)]\n        gradient.append(curr_vector)\n    return [rgb2hex([c/255. for c in rgb]) for rgb in gradient]",
    "docstring": "Interpolates the color gradient between to hex colors"
  },
  {
    "code": "def combine_recs(rec_list, key):\n    final_recs = {}\n    for rec in rec_list:\n        rec_key = rec[key]\n        if rec_key in final_recs:\n            for k, v in rec.iteritems():\n                if k in final_recs[rec_key] and final_recs[rec_key][k] != v:\n                    raise Exception(\"Mis-match for key '%s'\" % k)\n                final_recs[rec_key][k] = v\n        else:\n            final_recs[rec_key] = rec\n    return final_recs.values()",
    "docstring": "Use a common key to combine a list of recs"
  },
  {
    "code": "def Pc(x, y):\n    r\n    try:\n        term = exp(-x*(1. - y))\n        return (1. - term)/(1. - y*term)\n    except ZeroDivisionError:\n        return x/(1. + x)",
    "docstring": "r'''Basic helper calculator which accepts a transformed R1 and NTU1 as \n    inputs for a common term used in the calculation of the P-NTU method for \n    plate exchangers.\n    \n    Returns a value which is normally used in other calculations before the \n    actual P1 is calculated. Nominally used in counterflow calculations \n\n    .. math::\n        P_c(x, y) = \\frac{1 - \\exp[-x(1 - y)]}{1 - y\\exp[-x(1 - y)]}\n        \n    Parameters\n    ----------\n    x : float\n        A modification of NTU1, the Thermal Number of Transfer Units [-]\n    y : float\n        A modification of R1, the thermal effectiveness [-]\n\n    Returns\n    -------\n    z : float\n        Just another term in the calculation, [-]\n\n    Notes\n    -----\n    Used with the P-NTU plate method for heat exchanger design. At y =-1,\n    this function has a ZeroDivisionError but can be evaluated at the limit\n    to be :math:`z = \\frac{x}{1+x}`.\n\n    Examples\n    --------\n    >>> Pc(5, .7)\n    0.9206703686051108\n\n    References\n    ----------\n    .. [1] Shah, Ramesh K., and Dusan P. Sekulic. Fundamentals of Heat \n       Exchanger Design. 1st edition. Hoboken, NJ: Wiley, 2002.\n    .. [2] Rohsenow, Warren and James Hartnett and Young Cho. Handbook of Heat\n       Transfer, 3E. New York: McGraw-Hill, 1998."
  },
  {
    "code": "def get_bin_indices(self, values):\n        return tuple([self.get_axis_bin_index(values[ax_i], ax_i)\n                      for ax_i in range(self.dimensions)])",
    "docstring": "Returns index tuple in histogram of bin which contains value"
  },
  {
    "code": "def replace_with(self, other):\n        self.after(other)\n        self.parent.pop(self._own_index)\n        return other",
    "docstring": "Replace this element with the given DOMElement."
  },
  {
    "code": "def parse_compound(compound_def, context=None):\n    compound_id = compound_def.get('id')\n    _check_id(compound_id, 'Compound')\n    mark = FileMark(context, None, None)\n    return CompoundEntry(compound_def, mark)",
    "docstring": "Parse a structured compound definition as obtained from a YAML file\n\n    Returns a CompoundEntry."
  },
  {
    "code": "def get_section_by_label(label,\n                         include_instructor_not_on_time_schedule=True):\n    validate_section_label(label)\n    url = \"{}/{}.json\".format(course_res_url_prefix,\n                              encode_section_label(label))\n    return get_section_by_url(url,\n                              include_instructor_not_on_time_schedule)",
    "docstring": "Returns a uw_sws.models.Section object for\n    the passed section label."
  },
  {
    "code": "def _find_batch_containing_event(self, uuid):\n        if self.estore.key_exists(uuid):\n            return self.batchno\n        else:\n            for batchno in range(self.batchno - 1, -1, -1):\n                db = self._open_event_store(batchno)\n                with contextlib.closing(db):\n                    if db.key_exists(uuid):\n                        return batchno\n        return None",
    "docstring": "Find the batch number that contains a certain event.\n\n        Parameters:\n        uuid    -- the event uuid to search for.\n\n        returns -- a batch number, or None if not found."
  },
  {
    "code": "def _get_normalized_args(parser):\n    env = os.environ\n    if '_' in env and env['_'] != sys.argv[0] and len(sys.argv) >= 1 and \" \" in sys.argv[1]:\n        return parser.parse_args(shlex.split(sys.argv[1]) + sys.argv[2:])\n    else:\n        return parser.parse_args()",
    "docstring": "Return the parsed command line arguments.\n\n    Support the case when executed from a shebang, where all the\n    parameters come in sys.argv[1] in a single string separated\n    by spaces (in this case, the third parameter is what is being\n    executed)"
  },
  {
    "code": "def get_labels(self, field):\n        return {c: self.cluster_meta.get(field, c)\n                for c in self.clustering.cluster_ids}",
    "docstring": "Return the labels of all clusters, for a given field."
  },
  {
    "code": "def _write_wrapped(self, line, sep=\" \", indent=\"\", width=78):\n        words = line.split(sep)\n        lines = []\n        line  = \"\"\n        buf   = []\n        while len(words):\n            buf.append(words.pop(0))\n            line = sep.join(buf)\n            if len(line) > width:\n                words.insert(0, buf.pop())\n                lines.append(sep.join(buf))\n                buf = []\n                line = \"\"\n        if line:\n            lines.append(line)\n        result = lines.pop(0)\n        if len(lines):\n            eol = \"\"\n            if sep == \" \":\n                eol = \"\\s\"\n            for item in lines:\n                result += eol + \"\\n\" + indent + \"^ \" + item\n        return result",
    "docstring": "Word-wrap a line of RiveScript code for being written to a file.\n\n        :param str line: The original line of text to word-wrap.\n        :param str sep: The word separator.\n        :param str indent: The indentation to use (as a set of spaces).\n        :param int width: The character width to constrain each line to.\n\n        :return str: The reformatted line(s)."
  },
  {
    "code": "def compute_dual_rmetric(self,Ynew=None):\n        usedY = self.Y if Ynew is None else Ynew\n        rieman_metric = RiemannMetric(usedY, self.laplacian_matrix)\n        return rieman_metric.get_dual_rmetric()",
    "docstring": "Helper function to calculate the"
  },
  {
    "code": "def contains_exclusive(self, x, y):\n        left, bottom, right, top = self._aarect.lbrt()\n        return (left <= x < right) and (bottom < y <= top)",
    "docstring": "Return True if the given point is contained within the\n        bounding box, where the bottom and right boundaries are\n        considered exclusive."
  },
  {
    "code": "def get(cls, object_version, key):\n        return cls.query.filter_by(\n            version_id=as_object_version_id(object_version),\n            key=key,\n        ).one_or_none()",
    "docstring": "Get the tag object."
  },
  {
    "code": "def _get_cache_dir(candidate):\n    if candidate:\n        return candidate\n    import distutils.dist\n    import distutils.command.build\n    build_cmd = distutils.command.build.build(distutils.dist.Distribution())\n    build_cmd.finalize_options()\n    cache_dir = os.path.abspath(build_cmd.build_temp)\n    try:\n        os.makedirs(cache_dir)\n    except OSError as error:\n        if error.errno != errno.EEXIST:\n            raise error\n    return cache_dir",
    "docstring": "Get the current cache directory."
  },
  {
    "code": "def watch_instances(self, flag):\n        lib.EnvSetDefclassWatchInstances(self._env, int(flag), self._cls)",
    "docstring": "Whether or not the Class Instances are being watched."
  },
  {
    "code": "def decode_embedded_strs(src):\n    if not six.PY3:\n        return src\n    if isinstance(src, dict):\n        return _decode_embedded_dict(src)\n    elif isinstance(src, list):\n        return _decode_embedded_list(src)\n    elif isinstance(src, bytes):\n        try:\n            return src.decode()\n        except UnicodeError:\n            return src\n    else:\n        return src",
    "docstring": "Convert enbedded bytes to strings if possible.\n    This is necessary because Python 3 makes a distinction\n    between these types.\n\n    This wouldn't be needed if we used \"use_bin_type=True\" when encoding\n    and \"encoding='utf-8'\" when decoding. Unfortunately, this would break\n    backwards compatibility due to a change in wire protocol, so this less\n    than ideal solution is used instead."
  },
  {
    "code": "def fetch(self):\n        params = values.of({})\n        payload = self._version.fetch(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return FunctionVersionInstance(\n            self._version,\n            payload,\n            service_sid=self._solution['service_sid'],\n            function_sid=self._solution['function_sid'],\n            sid=self._solution['sid'],\n        )",
    "docstring": "Fetch a FunctionVersionInstance\n\n        :returns: Fetched FunctionVersionInstance\n        :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionInstance"
  },
  {
    "code": "def make_reverse_dict(in_dict, warn=True):\n    out_dict = {}\n    for k, v in in_dict.items():\n        for vv in v:\n            if vv in out_dict:\n                if warn:\n                    print(\"Dictionary collision %i\" % vv)\n            out_dict[vv] = k\n    return out_dict",
    "docstring": "Build a reverse dictionary from a cluster dictionary\n\n    Parameters\n    ----------\n    in_dict : dict(int:[int,])    \n        A dictionary of clusters.  Each cluster is a source index and\n        the list of other source in the cluster.\n\n    Returns\n    -------\n    out_dict : dict(int:int)    \n       A single valued dictionary pointing from source index to\n       cluster key for each source in a cluster.  Note that the key\n       does not point to itself."
  },
  {
    "code": "def info(self):\n        return sorted(self._checkers.values(), key=lambda x: (x.ns, x.name))",
    "docstring": "Returns information on all the registered checkers.\n\n        Sorted by namespace and then name\n        :returns a list of CheckerInfo"
  },
  {
    "code": "def inband_solarflux(self, rsr, scale=1.0, **options):\n        return self._band_calculations(rsr, True, scale, **options)",
    "docstring": "Derive the inband solar flux for a given instrument relative\n        spectral response valid for an earth-sun distance of one AU."
  },
  {
    "code": "def consensus(self, vs=None):\n        r\n        return functools.reduce(operator.and_, self.iter_cofactors(vs))",
    "docstring": "r\"\"\"Return the consensus of a function over a sequence of N variables.\n\n        The *vs* argument is a sequence of :math:`N` Boolean variables.\n\n        The *consensus* of :math:`f(x_1, x_2, \\dots, x_i, \\dots, x_n)` with\n        respect to variable :math:`x_i` is:\n        :math:`C_{x_i}(f) = f_{x_i} \\cdot f_{x_i'}`\n\n        This is the same as the universal quantification operator:\n        :math:`\\forall \\{x_1, x_2, \\dots\\} \\: f`"
  },
  {
    "code": "def on_compiled(self, name=None, key_schema=None, value_schema=None, as_mapping_key=None):\n        if self.name is None:\n            self.name = name\n        if self.key_schema is None:\n            self.key_schema = key_schema\n        if self.value_schema is None:\n            self.value_schema = value_schema\n        if as_mapping_key:\n            self.as_mapping_key = True\n        return self",
    "docstring": "When CompiledSchema compiles this marker, it sets informational values onto it.\n\n        Note that arguments may be provided in two incomplete sets,\n        e.g. (name, key_schema, None) and then (None, None, value_schema).\n        Thus, all assignments must be handled individually.\n\n        It is possible that a marker may have no `value_schema` at all:\n        e.g. in the case of { Extra: Reject } -- `Reject` will have no value schema,\n        but `Extra` will have compiled `Reject` as the value.\n\n        :param key_schema: Compiled key schema\n        :type key_schema: CompiledSchema|None\n        :param value_schema: Compiled value schema\n        :type value_schema: CompiledSchema|None\n        :param name: Human-friendly marker name\n        :type name: unicode|None\n        :param as_mapping_key: Whether it's used as a mapping key?\n        :type as_mapping_key: bool|None\n        :rtype: Marker"
  },
  {
    "code": "def remove_constraint(self,*names):\n        for name in names:\n            for pop in self.poplist:\n                if name in pop.constraints:\n                    pop.remove_constraint(name)\n                else:\n                    logging.info('%s model does not have %s constraint' % (pop.model,name))\n            if name in self.constraints:\n                self.constraints.remove(name)",
    "docstring": "Removes constraint from each population\n\n        See :func:`vespa.stars.StarPopulation.remove_constraint"
  },
  {
    "code": "def update_node(self, job_record):\n        if job_record.process_name not in self.process_hierarchy:\n            raise ValueError('unable to update the node due to unknown process: {0}'.format(job_record.process_name))\n        time_qualifier = self.process_hierarchy[job_record.process_name].process_entry.time_qualifier\n        node = self._get_node(time_qualifier, job_record.timeperiod)\n        node.job_record = job_record",
    "docstring": "Updates job record property for a tree node associated with the given Job"
  },
  {
    "code": "def read_json(fn):\n    with open(fn) as f:\n        return json.load(f, object_hook=_operator_object_hook)",
    "docstring": "Convenience method to read pyquil.operator_estimation objects from a JSON file.\n\n    See :py:func:`to_json`."
  },
  {
    "code": "def subpacket_prefix_len(item):\n    n = len(item)\n    if n >= 8384:\n        prefix = b'\\xFF' + struct.pack('>L', n)\n    elif n >= 192:\n        n = n - 192\n        prefix = struct.pack('BB', (n // 256) + 192, n % 256)\n    else:\n        prefix = struct.pack('B', n)\n    return prefix + item",
    "docstring": "Prefix subpacket length according to RFC 4880 section-5.2.3.1."
  },
  {
    "code": "def body(self, data, data_type, **kwargs):\n        if data is None:\n            raise ValidationError(\"required\", \"body\", True)\n        internal_data_type = data_type.strip('[]{}')\n        internal_data_type = self.dependencies.get(internal_data_type, None)\n        if internal_data_type and not isinstance(internal_data_type, Enum):\n            try:\n                deserializer = Deserializer(self.dependencies)\n                deserializer.additional_properties_detection = False\n                if issubclass(internal_data_type, Model) and internal_data_type.is_xml_model():\n                    deserializer.key_extractors = [\n                        attribute_key_case_insensitive_extractor,\n                    ]\n                else:\n                    deserializer.key_extractors = [\n                        rest_key_case_insensitive_extractor,\n                        attribute_key_case_insensitive_extractor,\n                        last_rest_key_case_insensitive_extractor\n                    ]\n                data = deserializer._deserialize(data_type, data)\n            except DeserializationError as err:\n                raise_with_traceback(\n                    SerializationError, \"Unable to build a model: \"+str(err), err)\n        if self.client_side_validation:\n            errors = _recursive_validate(data_type, data_type, data)\n            if errors:\n                raise errors[0]\n        return self._serialize(data, data_type, **kwargs)",
    "docstring": "Serialize data intended for a request body.\n\n        :param data: The data to be serialized.\n        :param str data_type: The type to be serialized from.\n        :rtype: dict\n        :raises: SerializationError if serialization fails.\n        :raises: ValueError if data is None"
  },
  {
    "code": "def vowels(self):\n        return IPAString(ipa_chars=[c for c in self.ipa_chars if c.is_vowel])",
    "docstring": "Return a new IPAString, containing only the vowels in the current string.\n\n        :rtype: IPAString"
  },
  {
    "code": "def paretoint(avg, alpha):\n    return int(random.paretovariate(alpha) * avg / (alpha / (alpha - 1)))",
    "docstring": "Returns a random integer that's avg on average, following a power law.\n    alpha determines the shape of the power curve. alpha has to be larger\n    than 1. The closer alpha is to 1, the higher the variation of the returned\n    numbers."
  },
  {
    "code": "def get_project_by_network_id(network_id,**kwargs):\n    user_id = kwargs.get('user_id')\n    projects_i = db.DBSession.query(Project).join(ProjectOwner).join(Network, Project.id==Network.project_id).filter(\n                                                    Network.id==network_id,\n                                                    ProjectOwner.user_id==user_id).order_by('name').all()\n    ret_project = None\n    for project_i in projects_i:\n        try:\n            project_i.check_read_permission(user_id)\n            ret_project = project_i\n        except:\n            log.info(\"Can't return project %s. User %s does not have permission to read it.\", project_i.id, user_id)\n    return ret_project",
    "docstring": "get a project complexmodel by a network_id"
  },
  {
    "code": "def get_json(self):\n        json = {\n            'DHCPUsage': self.dhcp_usage,\n            'AuthenticationMethod': self.auth_method,\n        }\n        if not self.dhcp_usage:\n            json['Name'] = self.iqn\n            json['IPv4Address'] = self.ip\n            json['PortNumber'] = self.port\n            json['BootLUN'] = self.lun\n        if self.chap_user:\n            json['ChapUserName'] = self.chap_user\n        if self.chap_secret:\n            json['ChapSecret'] = self.chap_secret\n        if self.mutual_chap_secret:\n            json['MutualChapSecret'] = self.mutual_chap_secret\n        return json",
    "docstring": "Create JSON data for iSCSI target.\n\n        :returns: JSON data for iSCSI target as follows:\n\n            {\n                \"DHCPUsage\":{\n                },\n                \"Name\":{\n                },\n                \"IPv4Address\":{\n                },\n                \"PortNumber\":{\n                },\n                \"BootLUN\":{\n                },\n                \"AuthenticationMethod\":{\n                },\n                \"ChapUserName\":{\n                },\n                \"ChapSecret\":{\n                },\n                \"MutualChapSecret\":{\n                }\n            }"
  },
  {
    "code": "def handle(self, *args, **options):\n        for index in options.pop(\"indexes\"):\n            data = {}\n            try:\n                data = self.do_index_command(index, **options)\n            except TransportError as ex:\n                logger.warning(\"ElasticSearch threw an error: %s\", ex)\n                data = {\"index\": index, \"status\": ex.status_code, \"reason\": ex.error}\n            finally:\n                logger.info(data)",
    "docstring": "Run do_index_command on each specified index and log the output."
  },
  {
    "code": "def init_app(self, app):\n        if self.path:\n            self.register_endpoint(self.path, app)\n        if self._export_defaults:\n            self.export_defaults(\n                self.buckets, self.group_by,\n                self._defaults_prefix, app\n            )",
    "docstring": "This callback can be used to initialize an application for the\n        use with this prometheus reporter setup.\n\n        This is usually used with a flask \"app factory\" configuration. Please\n        see: http://flask.pocoo.org/docs/1.0/patterns/appfactories/\n\n        Note, that you need to use `PrometheusMetrics(app=None, ...)`\n        for this mode, otherwise it is called automatically.\n\n        :param app: the Flask application"
  },
  {
    "code": "def get_relationship_search_session_for_family(self, family_id=None, proxy=None):\n        if not family_id:\n            raise NullArgument\n        if not self.supports_relationship_search():\n            raise Unimplemented()\n        try:\n            from . import sessions\n        except ImportError:\n            raise OperationFailed()\n        proxy = self._convert_proxy(proxy)\n        try:\n            session = sessions.RelationshipSearchSession(family_id, proxy=proxy, runtime=self._runtime)\n        except AttributeError:\n            raise OperationFailed()\n        return session",
    "docstring": "Gets the ``OsidSession`` associated with the relationship search service for the given family.\n\n        arg:    family_id (osid.id.Id): the ``Id`` of the family\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.relationship.RelationshipSearchSession) - a\n                ``RelationshipSearchSession``\n        raise:  NotFound - no ``Family`` found by the given ``Id``\n        raise:  NullArgument - ``family_id`` or ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_relationship_search()`` or\n                ``supports_visible_federation()`` is ``false``\n        *compliance: optional -- This method must be implemented if ``supports_relationship_search()``\n            and ``supports_visible_federation()`` are ``true``*"
  },
  {
    "code": "def register_model_once(cls, ModelClass, **kwargs):\n        if cls._static_registry.get_for_model(ModelClass) is None:\n            logger.warn(\"Model is already registered with {0}: '{1}'\"\n                        .format(cls, ModelClass))\n        else:\n            cls.register_model.register(ModelClass, **kwargs)",
    "docstring": "Tweaked version of `AnyUrlField.register_model` that only registers the\n        given model after checking that it is not already registered."
  },
  {
    "code": "def fix_tags_on_cands_missing_reals(user_id, vos_dir, property):\n    \"At the moment this just checks for a single user's missing reals. Easy to generalise it to all users.\"\n    con = context.get_context(vos_dir)\n    user_progress = []\n    listing = con.get_listing(tasks.get_suffix('reals'))\n    mpc_listing = con.get_listing('mpc')\n    for filename in listing:\n        if not filename.startswith('fk'):\n            user = storage.get_property(con.get_full_path(filename), property)\n            if (user is not None):\n                is_present = False\n                for mpcfile in [f for f in mpc_listing if not f.startswith('fk')]:\n                    if mpcfile.startswith(filename):\n                        print filename, user, 'exists!', mpcfile\n                        is_present = True\n                if not is_present:\n                    user_progress.append(filename)\n                    print filename, user, 'no mpc file'\n                    storage.set_property(con.get_full_path(filename), property, None)\n    print 'Fixed files:', len(user_progress)\n    return",
    "docstring": "At the moment this just checks for a single user's missing reals. Easy to generalise it to all users."
  },
  {
    "code": "def handleResponse(self, response):\n        requestId = KafkaCodec.get_response_correlation_id(response)\n        tReq = self.requests.pop(requestId, None)\n        if tReq is None:\n            log.warning('Unexpected response with correlationId=%d: %r',\n                        requestId, reprlib.repr(response))\n        else:\n            tReq.d.callback(response)",
    "docstring": "Handle the response string received by KafkaProtocol.\n\n        Ok, we've received the response from the broker. Find the requestId\n        in the message, lookup & fire the deferred with the response."
  },
  {
    "code": "def create_condition(self, \n\t\tservice_id, \n\t\tversion_number,\n\t\tname,\n\t\t_type,\n\t\tstatement,\n\t\tpriority=\"10\", \n\t\tcomment=None):\n\t\tbody = self._formdata({\n\t\t\t\"name\": name,\n\t\t\t\"type\": _type,\n\t\t\t\"statement\": statement,\n\t\t\t\"priority\": priority,\n\t\t\t\"comment\": comment,\n\t\t}, FastlyCondition.FIELDS)\n\t\tcontent = self._fetch(\"/service/%s/version/%d/condition\" % (service_id, version_number), method=\"POST\", body=body)\n\t\treturn FastlyCondition(self, content)",
    "docstring": "Creates a new condition."
  },
  {
    "code": "def get_pager(self, *path, **kwargs):\n        page_arg = kwargs.pop('page_size', None)\n        limit_arg = kwargs.pop('limit', None)\n        kwargs['limit'] = page_arg or limit_arg or self.default_page_size\n        return self.adapter.get_pager(self.get, path, kwargs)",
    "docstring": "A generator for all the results a resource can provide. The pages\n        are lazily loaded."
  },
  {
    "code": "def to_coo(self):\n        try:\n            from scipy.sparse import coo_matrix\n        except ImportError:\n            raise ImportError('Scipy is not installed')\n        dtype = find_common_type(self.dtypes)\n        if isinstance(dtype, SparseDtype):\n            dtype = dtype.subtype\n        cols, rows, datas = [], [], []\n        for col, name in enumerate(self):\n            s = self[name]\n            row = s.sp_index.to_int_index().indices\n            cols.append(np.repeat(col, len(row)))\n            rows.append(row)\n            datas.append(s.sp_values.astype(dtype, copy=False))\n        cols = np.concatenate(cols)\n        rows = np.concatenate(rows)\n        datas = np.concatenate(datas)\n        return coo_matrix((datas, (rows, cols)), shape=self.shape)",
    "docstring": "Return the contents of the frame as a sparse SciPy COO matrix.\n\n        .. versionadded:: 0.20.0\n\n        Returns\n        -------\n        coo_matrix : scipy.sparse.spmatrix\n            If the caller is heterogeneous and contains booleans or objects,\n            the result will be of dtype=object. See Notes.\n\n        Notes\n        -----\n        The dtype will be the lowest-common-denominator type (implicit\n        upcasting); that is to say if the dtypes (even of numeric types)\n        are mixed, the one that accommodates all will be chosen.\n\n        e.g. If the dtypes are float16 and float32, dtype will be upcast to\n        float32. By numpy.find_common_type convention, mixing int64 and\n        and uint64 will result in a float64 dtype."
  },
  {
    "code": "def get_backup_paths(cls, block_id, impl, working_dir):\n        backup_dir = config.get_backups_directory(impl, working_dir)\n        backup_paths = []\n        for p in cls.get_state_paths(impl, working_dir):\n            pbase = os.path.basename(p)\n            backup_path = os.path.join( backup_dir, pbase + (\".bak.%s\" % block_id))\n            backup_paths.append( backup_path )\n        return backup_paths",
    "docstring": "Get the set of backup paths, given the virtualchain implementation module and block number"
  },
  {
    "code": "def html_load_time(self):\n        load_times = self.get_load_times('html')\n        return round(mean(load_times), self.decimal_precision)",
    "docstring": "Returns aggregate html load time for all pages."
  },
  {
    "code": "def save(self, msg=None):\n        if msg is None:\n            msg = 'Saving %s' % self.name\n        log.debug(msg)\n        self.repo.addItem(self, msg)",
    "docstring": "Modify item data and commit to repo. \n        Git objects are immutable, to save means adding a new item\n\n        :param msg: Commit message."
  },
  {
    "code": "def from_annotype(cls, anno, writeable, **kwargs):\n        ret = cls(description=anno.description, writeable=writeable, **kwargs)\n        widget = ret.default_widget()\n        if widget != Widget.NONE:\n            ret.set_tags([widget.tag()])\n        return ret",
    "docstring": "Return an instance of this class from an Anno"
  },
  {
    "code": "def _update_separator(self, offset):\n        offset_line = self.handles['offset_line']\n        if offset == 0:\n            offset_line.set_visible(False)\n        else:\n            offset_line.set_visible(True)\n            if self.invert_axes:\n                offset_line.set_xdata(offset)\n            else:\n                offset_line.set_ydata(offset)",
    "docstring": "Compute colorbar offset and update separator line\n        if map is non-zero."
  },
  {
    "code": "def get_blocks_byte_array(self, buffer=False):\n        if buffer:\n            length = len(self.blocksList)\n            return BytesIO(pack(\">i\", length)+self.get_blocks_byte_array())\n        else:\n            return array.array('B', self.blocksList).tostring()",
    "docstring": "Return a list of all blocks in this chunk."
  },
  {
    "code": "def add_showcase(self, showcase, showcases_to_check=None):\n        dataset_showcase = self._get_dataset_showcase_dict(showcase)\n        if showcases_to_check is None:\n            showcases_to_check = self.get_showcases()\n        for showcase in showcases_to_check:\n            if dataset_showcase['showcase_id'] == showcase['id']:\n                return False\n        showcase = hdx.data.showcase.Showcase({'id': dataset_showcase['showcase_id']}, configuration=self.configuration)\n        showcase._write_to_hdx('associate', dataset_showcase, 'package_id')\n        return True",
    "docstring": "Add dataset to showcase\n\n        Args:\n            showcase (Union[Showcase,Dict,str]): Either a showcase id or showcase metadata from a Showcase object or dictionary\n            showcases_to_check (List[Showcase]): list of showcases against which to check existence of showcase. Defaults to showcases containing dataset.\n\n        Returns:\n            bool: True if the showcase was added, False if already present"
  },
  {
    "code": "def reconnect(self):\n        if self._connection.closed():\n            self._connection.reset()\n            yield from self._connection.connect()",
    "docstring": "Connected the stream if needed.\n\n        Coroutine."
  },
  {
    "code": "def _build_inheritance_chain(cls, bases, *names, merge=False):\n        result = []\n        for name in names:\n            maps = []\n            for base in bases:\n                bmap = getattr(base, name, None)\n                if bmap is not None:\n                    assert isinstance(bmap, (dict, ChainMap))\n                    if len(bmap):\n                        if isinstance(bmap, ChainMap):\n                            maps.extend(bmap.maps)\n                        else:\n                            maps.append(bmap)\n            result.append(ChainMap({}, *maps))\n        if merge:\n            result = [dict(map) for map in result]\n        if len(names) == 1:\n            return result[0]\n        return result",
    "docstring": "For all of the names build a ChainMap containing a map for every\n        base class."
  },
  {
    "code": "def add_text(self, setting, width=300, height=100, multiline=False):\n        tab = self.panel(setting.tab)\n        if multiline:\n            ctrl = wx.TextCtrl(tab, -1, \"\", size=(width,height), style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER)\n        else:\n            ctrl = wx.TextCtrl(tab, -1, \"\", size=(width,-1) )\n        self._add_input(setting, ctrl)",
    "docstring": "add a text input line"
  },
  {
    "code": "def arithm_expr_parse(line):\n    vals = []\n    ops = []\n    for tok in line + [';']:\n        if tok in priority:\n            while (tok != '(' and ops and\n                   priority[ops[-1]] >= priority[tok]):\n                right = vals.pop()\n                left = vals.pop()\n                vals.append((left, ops.pop(), right))\n            if tok == ')':\n                ops.pop()\n            else:\n                ops.append(tok)\n        elif tok.isdigit():\n            vals.append(int(tok))\n        else:\n            vals.append(tok)\n    return vals.pop()",
    "docstring": "Constructs an arithmetic expression tree\n\n    :param line: list of token strings containing the expression\n    :returns: expression tree\n\n    :complexity:     linear"
  },
  {
    "code": "def get_spell_damage(self, amount: int) -> int:\n\t\tamount += self.spellpower\n\t\tamount <<= self.controller.spellpower_double\n\t\treturn amount",
    "docstring": "Returns the amount of damage \\a amount will do, taking\n\t\tSPELLPOWER and SPELLPOWER_DOUBLE into account."
  },
  {
    "code": "def _get_background_color(self):\n        color = self.cell_attributes[self.key][\"bgcolor\"]\n        return tuple(c / 255.0 for c in color_pack2rgb(color))",
    "docstring": "Returns background color rgb tuple of right line"
  },
  {
    "code": "def _get_point_data_handler_for(self, point):\n        with self.__point_data_handlers:\n            try:\n                return self.__point_data_handlers[point]\n            except KeyError:\n                return self.__point_data_handlers.setdefault(point, PointDataObjectHandler(point, self))",
    "docstring": "Used by point instances and data callbacks"
  },
  {
    "code": "def showMenu(self, point):\r\n        menu = QMenu(self)\r\n        acts = {}\r\n        acts['edit'] = menu.addAction('Edit quick filter...')\r\n        trigger = menu.exec_(self.mapToGlobal(point))\r\n        if trigger == acts['edit']:\r\n            text, accepted = XTextEdit.getText(self.window(),\r\n                                                  'Edit Format',\r\n                                                  'Format:',\r\n                                                  self.filterFormat(),\r\n                                                  wrapped=False)\r\n            if accepted:\r\n                self.setFilterFormat(text)",
    "docstring": "Displays the menu for this filter widget."
  },
  {
    "code": "def Any(a, axis, keep_dims):\n    return np.any(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                  keepdims=keep_dims),",
    "docstring": "Any reduction op."
  },
  {
    "code": "def on_menu_import_meas_file(self, event):\n        meas_file = self.choose_meas_file()\n        WD = os.path.split(meas_file)[0]\n        self.WD = WD\n        self.magic_file = meas_file\n        self.reset_backend()",
    "docstring": "Open measurement file, reset self.magic_file\n        and self.WD, and reset everything."
  },
  {
    "code": "def construct_field(model_name, field_name, field_type, all_models, **kwargs):\n    field_type_parts = field_type.split('->')\n    _field_type = field_type_parts[0].strip().split('[]')[0].strip()\n    back_populates = field_type_parts[1].strip() if len(field_type_parts) > 1 else None\n    error_context = kwargs.pop('error_context', StatikErrorContext())\n    _kwargs = copy(kwargs)\n    _kwargs['back_populates'] = back_populates\n    if _field_type not in FIELD_TYPES and _field_type not in all_models:\n        raise InvalidFieldTypeError(\n            model_name,\n            field_name,\n            context=error_context\n        )\n    if _field_type in FIELD_TYPES:\n        return FIELD_TYPES[_field_type](field_name, **_kwargs)\n    if field_type_parts[0].strip().endswith('[]'):\n        return StatikManyToManyField(field_name, _field_type, **_kwargs)\n    return StatikForeignKeyField(field_name, _field_type, **_kwargs)",
    "docstring": "Helper function to build a field from the given field name and\n    type.\n\n    Args:\n        model_name: The name of the model for which we're building this field.\n        field_name: The name of the field to build.\n        field_type: A string indicator as to which field type must be built.\n        all_models: A list containing the names of all of the models, which\n            will help us when building foreign key lookups."
  },
  {
    "code": "def update_labels(self, func):\n        if not isinstance(self.data, LabelArray):\n            raise TypeError(\n                'update_labels only supported if data is of type LabelArray.'\n            )\n        self._data = self._data.map(func)\n        for _, row_adjustments in iteritems(self.adjustments):\n            for adjustment in row_adjustments:\n                adjustment.value = func(adjustment.value)",
    "docstring": "Map a function over baseline and adjustment values in place.\n\n        Note that the baseline data values must be a LabelArray."
  },
  {
    "code": "def main(argv: Optional[Sequence[str]] = None) -> None:\n    parser = ArgumentParser(description=\"Convert Jupyter Notebook assignments to PDFs\")\n    parser.add_argument(\n        \"--hw\",\n        type=int,\n        required=True,\n        help=\"Homework number to convert\",\n        dest=\"hw_num\",\n    )\n    parser.add_argument(\n        \"-p\",\n        \"--problems\",\n        type=int,\n        help=\"Problem numbers to convert\",\n        dest=\"problems\",\n        nargs=\"*\",\n    )\n    parser.add_argument(\n        \"--by-hand\",\n        type=int,\n        help=\"Problem numbers to be completed by hand\",\n        dest=\"by_hand\",\n        nargs=\"*\",\n    )\n    args = parser.parse_args(argv)\n    prefix = Path(f\"homework/homework-{args.hw_num}\")\n    process(args.hw_num, args.problems, prefix=prefix, by_hand=args.by_hand)",
    "docstring": "Parse arguments and process the homework assignment."
  },
  {
    "code": "def add_repo_to_team(self, auth, team_id, repo_name):\n        url = \"/admin/teams/{t}/repos/{r}\".format(t=team_id, r=repo_name)\n        self.put(url, auth=auth)",
    "docstring": "Add or update repo from team.\n\n        :param auth.Authentication auth: authentication object, must be admin-level\n        :param str team_id: Team's id\n        :param str repo_name: Name of the repo to be added to the team\n        :raises NetworkFailure: if there is an error communicating with the server\n        :raises ApiFailure: if the request cannot be serviced"
  },
  {
    "code": "def register_precmd_hook(self, func: Callable[[plugin.PrecommandData], plugin.PrecommandData]) -> None:\n        self._validate_prepostcmd_hook(func, plugin.PrecommandData)\n        self._precmd_hooks.append(func)",
    "docstring": "Register a hook to be called before the command function."
  },
  {
    "code": "def _register(self, assignment):\n        name = assignment.dependency.name\n        old_positive = self._positive.get(name)\n        if old_positive is not None:\n            self._positive[name] = old_positive.intersect(assignment)\n            return\n        ref = assignment.dependency.name\n        negative_by_ref = self._negative.get(name)\n        old_negative = None if negative_by_ref is None else negative_by_ref.get(ref)\n        if old_negative is None:\n            term = assignment\n        else:\n            term = assignment.intersect(old_negative)\n        if term.is_positive():\n            if name in self._negative:\n                del self._negative[name]\n            self._positive[name] = term\n        else:\n            if name not in self._negative:\n                self._negative[name] = {}\n            self._negative[name][ref] = term",
    "docstring": "Registers an Assignment in _positive or _negative."
  },
  {
    "code": "def runInactiveDeviceCleanup(self):\n        yield self.deleteInactiveDevicesByQuota(\n            self.__inactive_per_jid_max,\n            self.__inactive_global_max\n        )\n        yield self.deleteInactiveDevicesByAge(self.__inactive_max_age)",
    "docstring": "Runs both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota\n        methods with the configuration that was set when calling create."
  },
  {
    "code": "def advance2(self, height, ignore_overflow=False):\n        if height <= self.remaining_height:\n            self._self_cursor.grow(height)\n        elif ignore_overflow:\n            self._self_cursor.grow(float(self.remaining_height))\n        else:\n            return False\n        return True",
    "docstring": "Advance the cursor by `height`. Returns `True` on success.\n\n        Returns `False` if this would cause the cursor to point beyond the\n        bottom of the container."
  },
  {
    "code": "def get_user(user=None):\n    if user is None:\n        user = getSecurityManager().getUser()\n    elif isinstance(user, MemberData):\n        user = user.getUser()\n    elif isinstance(user, basestring):\n        user = get_member_by_login_name(get_portal(), user, False)\n        if user:\n            user = user.getUser()\n    return user",
    "docstring": "Get the user object\n\n    :param user: A user id, memberdata object or None for the current user\n    :returns: Plone User (PlonePAS) / Propertied User (PluggableAuthService)"
  },
  {
    "code": "def convert_to_sngl_inspiral_table(params, proc_id):\n    sngl_inspiral_table = lsctables.New(lsctables.SnglInspiralTable)\n    col_names = ['mass1','mass2','spin1z','spin2z']\n    for values in params:\n        tmplt = return_empty_sngl()\n        tmplt.process_id = proc_id\n        for colname, value in zip(col_names, values):\n            setattr(tmplt, colname, value)\n        tmplt.mtotal, tmplt.eta = pnutils.mass1_mass2_to_mtotal_eta(\n            tmplt.mass1, tmplt.mass2)\n        tmplt.mchirp, _ = pnutils.mass1_mass2_to_mchirp_eta(\n            tmplt.mass1, tmplt.mass2)\n        tmplt.template_duration = 0\n        tmplt.event_id = sngl_inspiral_table.get_next_id()\n        sngl_inspiral_table.append(tmplt)\n    return sngl_inspiral_table",
    "docstring": "Convert a list of m1,m2,spin1z,spin2z values into a basic sngl_inspiral\n    table with mass and spin parameters populated and event IDs assigned\n\n    Parameters\n    -----------\n    params : iterable\n        Each entry in the params iterable should be a sequence of\n        [mass1, mass2, spin1z, spin2z] in that order\n    proc_id : ilwd char\n        Process ID to add to each row of the sngl_inspiral table\n\n    Returns\n    ----------\n    SnglInspiralTable\n        Bank of templates in SnglInspiralTable format"
  },
  {
    "code": "def _threaded(self, *args, **kwargs):\n        for target in self.targets:\n            result = target(*args, **kwargs)\n            self.queue.put(result)",
    "docstring": "Call the target and put the result in the Queue."
  },
  {
    "code": "def UpdateUser(self, user, ssh_keys):\n    if not bool(USER_REGEX.match(user)):\n      self.logger.warning('Invalid user account name %s.', user)\n      return False\n    if not self._GetUser(user):\n      if not (self._AddUser(user)\n              and self._UpdateUserGroups(user, self.groups)):\n        return False\n    if not self._UpdateSudoer(user, sudoer=True):\n      return False\n    pw_entry = self._GetUser(user)\n    if pw_entry and os.path.basename(pw_entry.pw_shell) == 'nologin':\n      message = 'Not updating user %s. User set `nologin` as login shell.'\n      self.logger.debug(message, user)\n      return True\n    try:\n      self._UpdateAuthorizedKeys(user, ssh_keys)\n    except (IOError, OSError) as e:\n      message = 'Could not update the authorized keys file for user %s. %s.'\n      self.logger.warning(message, user, str(e))\n      return False\n    else:\n      return True",
    "docstring": "Update a Linux user with authorized SSH keys.\n\n    Args:\n      user: string, the name of the Linux user account.\n      ssh_keys: list, the SSH key strings associated with the user.\n\n    Returns:\n      bool, True if the user account updated successfully."
  },
  {
    "code": "def create_xml_string(self):\n        root = self.create_xml()\n        xml = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' + tostring(\n            root, pretty_print=True\n        )\n        return xml",
    "docstring": "Create a UNTL document in a string from a UNTL metadata\n        root object.\n\n        untl_xml_string = metadata_root_object.create_xml_string()"
  },
  {
    "code": "def lookup(self,value):\n        for k,v in self.iteritems():\n            if value == v:\n                return k\n        return None",
    "docstring": "return the first key in dict where value is name"
  },
  {
    "code": "def eval_grad(self):\n        return self.D.T.dot(self.D.dot(self.Y) - self.S)",
    "docstring": "Compute gradient in spatial domain for variable Y."
  },
  {
    "code": "def _next_timestamp(self, now, last):\n        if now > last:\n            self.last = now\n            return now\n        else:\n            self._maybe_warn(now=now)\n            self.last = last + 1\n            return self.last",
    "docstring": "Returns the timestamp that should be used if ``now`` is the current\n        time and ``last`` is the last timestamp returned by this object.\n        Intended for internal and testing use only; to generate timestamps,\n        call an instantiated ``MonotonicTimestampGenerator`` object.\n\n        :param int now: an integer to be used as the current time, typically\n            representing the current time in microseconds since the UNIX epoch\n        :param int last: an integer representing the last timestamp returned by\n            this object"
  },
  {
    "code": "def _handle_processing_error(err, errstream, client):\n    errors = sorted(err.events, key=operator.attrgetter(\"index\"))\n    failed = [e.event for e in errors]\n    silent = all(isinstance(e.error, OutOfOrderError) for e in errors)\n    if errstream:\n        _deliver_errored_events(errstream, failed)\n        must_raise = False\n    else:\n        must_raise = True\n    for _, event, error, tb in errors:\n        if isinstance(error, OutOfOrderError):\n            continue\n        try:\n            raise six.reraise(*tb)\n        except Exception as err:\n            if client:\n                client.captureException()\n            msg = \"{}{}: {}\".format(type(err).__name__,\n                    err.args, json.dumps(event, indent=4))\n            rlogger.error(msg, exc_info=tb)\n            if must_raise:\n                raise",
    "docstring": "Handle ProcessingError exceptions."
  },
  {
    "code": "def x10(self, feature):\n        x10_product = None\n        for product in self._x10_products:\n            if feature.lower() == product.feature:\n                x10_product = product\n        if not x10_product:\n            x10_product = X10Product(feature, None)\n        return x10_product",
    "docstring": "Return an X10 device based on a feature.\n\n        Current features:\n        - OnOff\n        - Dimmable"
  },
  {
    "code": "def send(self, content):\n        try:\n            self.process.stdin.write(content)\n        except IOError as e:\n            raise ProxyCommandFailure(\" \".join(self.cmd), e.strerror)\n        return len(content)",
    "docstring": "Write the content received from the SSH client to the standard\n        input of the forked command.\n\n        :param str content: string to be sent to the forked command"
  },
  {
    "code": "def gaussian_kernel(gstd):\n    Nc = np.ceil(gstd*3)*2+1\n    x = np.linspace(-(Nc-1)/2,(Nc-1)/2,Nc,endpoint=True)\n    g = np.exp(-.5*((x/gstd)**2))\n    g = g/np.sum(g)\n    return g",
    "docstring": "Generate odd sized truncated Gaussian\n\n    The generated filter kernel has a cutoff at $3\\sigma$\n    and is normalized to sum to 1\n\n    Parameters\n    -------------\n    gstd : float\n            Standard deviation of filter\n\n    Returns\n    -------------\n    g : ndarray\n            Array with kernel coefficients"
  },
  {
    "code": "def find_all_matches(text_log_error, matchers):\n    for matcher_func in matchers:\n        matches = matcher_func(text_log_error)\n        if not matches:\n            continue\n        for score, classified_failure_id in matches:\n            yield TextLogErrorMatch(\n                score=score,\n                matcher_name=matcher_func.__name__,\n                classified_failure_id=classified_failure_id,\n                text_log_error=text_log_error,\n            )",
    "docstring": "Find matches for the given error using the given matcher classes\n\n    Returns *unsaved* TextLogErrorMatch instances."
  },
  {
    "code": "def get_listing_calendar(self, listing_id, starting_date=datetime.datetime.now(), calendar_months=6):\n        params = {\n            '_format': 'host_calendar_detailed'\n        }\n        starting_date_str = starting_date.strftime(\"%Y-%m-%d\")\n        ending_date_str = (\n            starting_date + datetime.timedelta(days=30)).strftime(\"%Y-%m-%d\")\n        r = self._session.get(API_URL + \"/calendars/{}/{}/{}\".format(\n            str(listing_id), starting_date_str, ending_date_str), params=params)\n        r.raise_for_status()\n        return r.json()",
    "docstring": "Get host availability calendar for a given listing"
  },
  {
    "code": "def get_files_from_storage(paths):\n        for path in paths:\n            f = default_storage.open(path)\n            f.name = os.path.basename(path)\n            try:\n                yield f\n            except ClientError:\n                logger.exception(\"File not found: %s\", path)",
    "docstring": "Return S3 file where the name does not include the path."
  },
  {
    "code": "def start_stream_subscriber(self):\n        if not self._stream_process_started:\n            if sys.platform.startswith(\"win\"):\n                self._stream_process_started = True\n                self._stream()\n            self._stream_process_started = True\n            self._stream_process.start()",
    "docstring": "Starts the stream consumer's main loop.\n\n            Called when the stream consumer has been set up with the correct callbacks."
  },
  {
    "code": "def _get_type_list(self, props):\n        type_list = []\n        for k, v in list(props.items()):\n            t = self._get_property_type(v)\n            if t is not None:\n                type_list.append(t)\n        return sorted(type_list)",
    "docstring": "Return a list of non-primitive types used by this object."
  },
  {
    "code": "def write(self, path, data, offset, fh):\n        with self.attr_lock:\n            base = self.attr[path][BASE_KEY]\n            staged = self.attr[path][STAGED_KEY]\n            if not staged.closed:\n                base.st_size += len(data)\n                staged.write(data)\n        return len(data)",
    "docstring": "This is a readonly filesystem right now"
  },
  {
    "code": "def set_meta(self, name, format, *args):\n        return lib.zcert_set_meta(self._as_parameter_, name, format, *args)",
    "docstring": "Set certificate metadata from formatted string."
  },
  {
    "code": "def _operations_from_methods(handler_class):\n        for httpmethod in yaml_utils.PATH_KEYS:\n            method = getattr(handler_class, httpmethod)\n            operation_data = yaml_utils.load_yaml_from_docstring(method.__doc__)\n            if operation_data:\n                operation = {httpmethod: operation_data}\n                yield operation",
    "docstring": "Generator of operations described in handler's http methods\n\n        :param handler_class:\n        :type handler_class: RequestHandler descendant"
  },
  {
    "code": "def missing_or_other_newer(path, other_path, cwd=None):\n    cwd = cwd or '.'\n    path = get_abspath(path, cwd=cwd)\n    other_path = get_abspath(other_path, cwd=cwd)\n    if not os.path.exists(path):\n        return True\n    if os.path.getmtime(other_path) - 1e-6 >= os.path.getmtime(path):\n        return True\n    return False",
    "docstring": "Investigate if path is non-existant or older than provided reference\n    path.\n\n    Parameters\n    ==========\n    path: string\n        path to path which might be missing or too old\n    other_path: string\n        reference path\n    cwd: string\n        working directory (root of relative paths)\n\n    Returns\n    =======\n    True if path is older or missing."
  },
  {
    "code": "def Notify(self, message_type, subject, msg, source):\n    pending = self.Get(self.Schema.PENDING_NOTIFICATIONS)\n    if pending is None:\n      pending = self.Schema.PENDING_NOTIFICATIONS()\n    if message_type.split(\n        \":\", 2)[0] not in rdf_flows.Notification.notification_types:\n      raise TypeError(\"Invalid notification type %s\" % message_type)\n    pending.Append(\n        type=message_type,\n        subject=subject,\n        message=msg,\n        source=source,\n        timestamp=int(time.time() * 1e6))\n    while len(pending) > 50:\n      pending.Pop(0)\n    self.Set(self.Schema.PENDING_NOTIFICATIONS, pending)",
    "docstring": "Send an AFF4-based notification to the user in the UI.\n\n    Args:\n      message_type: One of aff4_grr.Notification.notification_types e.g.\n        \"ViewObject\", \"HostInformation\", \"GrantAccess\" or\n        the same with an added \":[new-style notification type] suffix, e.g.\n        \"ViewObject:TYPE_CLIENT_INTERROGATED\".\n      subject: The subject to use, normally a URN.\n      msg: The message to display.\n      source: The class doing the notification.\n\n    Raises:\n      TypeError: On invalid message_type."
  },
  {
    "code": "def orientation(self, image, geometry, options):\n        if options.get('orientation', settings.THUMBNAIL_ORIENTATION):\n            return self._orientation(image)\n        self.reoriented = True\n        return image",
    "docstring": "Wrapper for ``_orientation``"
  },
  {
    "code": "def flush(self):\n        items = []\n        for data in self._to_put:\n            items.append(encode_put(self.connection.dynamizer, data))\n        for data in self._to_delete:\n            items.append(encode_delete(self.connection.dynamizer, data))\n        self._write(items)\n        self._to_put = []\n        self._to_delete = []",
    "docstring": "Flush pending items to Dynamo"
  },
  {
    "code": "def _hash(x, elementType, relicHashFunc):\n    barray = bytearray()\n    map(barray.extend, bytes(x))\n    result = elementType()\n    buf = getBuffer(barray)\n    relicHashFunc(byref(result), byref(buf), sizeof(buf))\n    return result",
    "docstring": "Hash an array of bytes, @x, using @relicHashFunc and returns the result\n    of @elementType."
  },
  {
    "code": "def port(port_number, return_format=None):\n    response = _get('port/{number}'.format(number=port_number), return_format)\n    if 'bad port number' in str(response):\n        raise Error('Bad port number, {number}'.format(number=port_number))\n    else:\n        return response",
    "docstring": "Summary information about a particular port.\n\n    In the returned data:\n\n    Records: Total number of records for a given date.\n    Targets: Number of unique destination IP addresses.\n    Sources: Number of unique originating IPs.\n\n    :param port_number: a string or integer port number"
  },
  {
    "code": "def get_notebook_item(name):\n  env = notebook_environment()\n  return google.datalab.utils.get_item(env, name)",
    "docstring": "Get an item from the IPython environment."
  },
  {
    "code": "def do_header(self, node):\n        data = self.extract_text(node)\n        self.add_text('\\n/*\\n %s \\n*/\\n' % data)\n        parent = node.parentNode\n        idx = parent.childNodes.index(node)\n        if len(parent.childNodes) >= idx + 2:\n            nd = parent.childNodes[idx + 2]\n            if nd.nodeName == 'description':\n                nd = parent.removeChild(nd)\n                self.add_text('\\n/*')\n                self.subnode_parse(nd)\n                self.add_text('\\n*/\\n')",
    "docstring": "For a user defined section def a header field is present\n        which should not be printed as such, so we comment it in the\n        output."
  },
  {
    "code": "def _show_selection(self, text, bbox):\n        x, y, width, height = bbox\n        textw = self._font.measure(text)\n        canvas = self._canvas\n        canvas.configure(width=width, height=height)\n        canvas.coords(canvas.text, width - textw, height / 2 - 1)\n        canvas.itemconfigure(canvas.text, text=text)\n        canvas.place(in_=self._calendar, x=x, y=y)",
    "docstring": "Configure canvas for a new selection."
  },
  {
    "code": "def dump_graph(self):\n        with self.lock:\n            return {\n                dot_separated(k): v.dump_graph_entry()\n                for k, v in self.relations.items()\n            }",
    "docstring": "Dump a key-only representation of the schema to a dictionary. Every\n        known relation is a key with a value of a list of keys it is referenced\n        by."
  },
  {
    "code": "def for_category(self, category, context=None):\n        assert self.installed(), \"Actions not enabled on this application\"\n        actions = self._state[\"categories\"].get(category, [])\n        if context is None:\n            context = self.context\n        return [a for a in actions if a.available(context)]",
    "docstring": "Returns actions list for this category in current application.\n\n        Actions are filtered according to :meth:`.Action.available`.\n\n        if `context` is None, then current action context is used\n        (:attr:`context`)"
  },
  {
    "code": "def match_option_with_value(arguments, option, value):\n    return ('%s=%s' % (option, value) in arguments or\n            contains_sublist(arguments, [option, value]))",
    "docstring": "Check if a list of command line options contains an option with a value.\n\n    :param arguments: The command line arguments (a list of strings).\n    :param option: The long option (a string).\n    :param value: The expected value (a string).\n    :returns: :data:`True` if the command line contains the option/value pair,\n              :data:`False` otherwise."
  },
  {
    "code": "def load_combo_catalog():\n    user_dir = user_data_dir()\n    global_dir = global_data_dir()\n    desc = 'Generated from data packages found on your intake search path'\n    cat_dirs = []\n    if os.path.isdir(user_dir):\n        cat_dirs.append(user_dir + '/*.yaml')\n        cat_dirs.append(user_dir + '/*.yml')\n    if os.path.isdir(global_dir):\n        cat_dirs.append(global_dir + '/*.yaml')\n        cat_dirs.append(global_dir + '/*.yml')\n    for path_dir in conf.get('catalog_path', []):\n        if path_dir != '':\n            if not path_dir.endswith(('yaml', 'yml')):\n                cat_dirs.append(path_dir + '/*.yaml')\n                cat_dirs.append(path_dir + '/*.yml')\n            else:\n                cat_dirs.append(path_dir)\n    return YAMLFilesCatalog(cat_dirs, name='builtin', description=desc)",
    "docstring": "Load a union of the user and global catalogs for convenience"
  },
  {
    "code": "def reset(self, n_particles=None, only_params=None, reset_weights=True):\n        if n_particles is not None and only_params is not None:\n            raise ValueError(\"Cannot set both n_particles and only_params.\")\n        if n_particles is None:\n            n_particles = self.n_particles\n        if reset_weights:\n            self.particle_weights = np.ones((n_particles,)) / n_particles\n        if only_params is None:\n            sl = np.s_[:, :]\n            self.particle_locations = np.zeros((n_particles, self.model.n_modelparams))\n        else:\n            sl = np.s_[:, only_params]\n        self.particle_locations[sl] = self.prior.sample(n=n_particles)[sl]\n        if self._canonicalize:\n            self.particle_locations[sl] = self.model.canonicalize(self.particle_locations[sl])",
    "docstring": "Causes all particle locations and weights to be drawn fresh from the\n        initial prior.\n\n        :param int n_particles: Forces the size of the new particle set. If\n            `None`, the size of the particle set is not changed.\n        :param slice only_params: Resets only some of the parameters. Cannot\n            be set if ``n_particles`` is also given.\n        :param bool reset_weights: Resets the weights as well as the particles."
  },
  {
    "code": "def browse_node_lookup(self, ResponseGroup=\"BrowseNodeInfo\", **kwargs):\n        response = self.api.BrowseNodeLookup(\n            ResponseGroup=ResponseGroup, **kwargs)\n        root = objectify.fromstring(response)\n        if root.BrowseNodes.Request.IsValid == 'False':\n            code = root.BrowseNodes.Request.Errors.Error.Code\n            msg = root.BrowseNodes.Request.Errors.Error.Message\n            raise BrowseNodeLookupException(\n                \"Amazon BrowseNode Lookup Error: '{0}', '{1}'\".format(\n                    code, msg))\n        return [AmazonBrowseNode(node.BrowseNode) for node in root.BrowseNodes]",
    "docstring": "Browse Node Lookup.\n\n        Returns the specified browse node's name, children, and ancestors.\n        Example:\n            >>> api.browse_node_lookup(BrowseNodeId='163357')"
  },
  {
    "code": "def _update_from_database(self):\n        collection = JSONClientValidated('assessment',\n                                         collection='AssessmentSection',\n                                         runtime=self._runtime)\n        self._my_map = collection.find_one({'_id': self._my_map['_id']})",
    "docstring": "Updates map to latest state in database.\n\n        Should be called prior to major object events to assure that an\n        assessment being taken on multiple devices are reasonably synchronized."
  },
  {
    "code": "def get_oauth_url(self):\n        params = OrderedDict()\n        if \"?\" in self.url:\n            url = self.url[:self.url.find(\"?\")]\n            for key, value in parse_qsl(urlparse(self.url).query):\n                params[key] = value\n        else:\n            url = self.url\n        params[\"oauth_consumer_key\"] = self.consumer_key\n        params[\"oauth_timestamp\"] = self.timestamp\n        params[\"oauth_nonce\"] = self.generate_nonce()\n        params[\"oauth_signature_method\"] = \"HMAC-SHA256\"\n        params[\"oauth_signature\"] = self.generate_oauth_signature(params, url)\n        query_string = urlencode(params)\n        return \"%s?%s\" % (url, query_string)",
    "docstring": "Returns the URL with OAuth params"
  },
  {
    "code": "def residual_block(x, hparams):\n  k = (hparams.kernel_height, hparams.kernel_width)\n  dilations_and_kernels = [((1, 1), k) for _ in range(3)]\n  y = common_layers.subseparable_conv_block(\n      x,\n      hparams.hidden_size,\n      dilations_and_kernels,\n      padding=\"SAME\",\n      separability=0,\n      name=\"residual_block\")\n  x = common_layers.layer_norm(x + y, hparams.hidden_size, name=\"lnorm\")\n  return tf.nn.dropout(x, 1.0 - hparams.dropout)",
    "docstring": "A stack of convolution blocks with residual connection."
  },
  {
    "code": "def correction(self, word):\n        return max(self.candidates(word), key=self.word_probability)",
    "docstring": "The most probable correct spelling for the word\n\n            Args:\n                word (str): The word to correct\n            Returns:\n                str: The most likely candidate"
  },
  {
    "code": "def create_default_item_node(field, state):\n    default_item = nodes.definition_list_item()\n    default_item.append(nodes.term(text=\"Default\"))\n    default_item_content = nodes.definition()\n    default_item_content.append(\n        nodes.literal(text=repr(field.default))\n    )\n    default_item.append(default_item_content)\n    return default_item",
    "docstring": "Create a definition list item node that describes the default value\n    of a Field config.\n\n    Parameters\n    ----------\n    field : ``lsst.pex.config.Field``\n        A configuration field.\n    state : ``docutils.statemachine.State``\n        Usually the directive's ``state`` attribute.\n\n    Returns\n    -------\n    ``docutils.nodes.definition_list_item``\n        Definition list item that describes the default target of a\n        ConfigurableField config."
  },
  {
    "code": "def logodds(args):\n    from math import log\n    from jcvi.formats.base import DictFile\n    p = OptionParser(logodds.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n    cnt1, cnt2 = args\n    d = DictFile(cnt2)\n    fp = open(cnt1)\n    for row in fp:\n        scf, c1 = row.split()\n        c2 = d[scf]\n        c1, c2 = float(c1), float(c2)\n        c1 += 1\n        c2 += 1\n        score = int(100 * (log(c1) - log(c2)))\n        print(\"{0}\\t{1}\".format(scf, score))",
    "docstring": "%prog logodds cnt1 cnt2\n\n    Compute log likelihood between two db."
  },
  {
    "code": "def cli(ctx):\n    ctx.obj = dict()\n    ctx.obj['app_key'] = os.environ.get('TRELLOSTATS_APP_KEY')\n    ctx.obj['app_token'] = os.environ.get('TRELLOSTATS_APP_TOKEN')\n    init_db(db_proxy)",
    "docstring": "This is a command line app to get useful stats from a trello board\n        and report on them in useful ways.\n\n        Requires the following environment varilables:\n\n        TRELLOSTATS_APP_KEY=<your key here>\n        TRELLOSTATS_APP_TOKEN=<your token here>"
  },
  {
    "code": "def _repr_html_(self):\n        TileServer.run_tileserver(self, self.footprint())\n        capture = \"raster: %s\" % self._filename\n        mp = TileServer.folium_client(self, self.footprint(), capture=capture)\n        return mp._repr_html_()",
    "docstring": "Required for jupyter notebook to show raster as an interactive map."
  },
  {
    "code": "def get_config_string_option(parser: ConfigParser,\n                             section: str,\n                             option: str,\n                             default: str = None) -> str:\n    if not parser.has_section(section):\n        raise ValueError(\"config missing section: \" + section)\n    return parser.get(section, option, fallback=default)",
    "docstring": "Retrieves a string value from a parser.\n\n    Args:\n        parser: instance of :class:`ConfigParser`\n        section: section name within config file\n        option: option (variable) name within that section\n        default: value to return if option is absent\n\n    Returns:\n        string value\n\n    Raises:\n        ValueError: if the section is absent"
  },
  {
    "code": "def get_projects(self, **kwargs):\n        _login = kwargs.get('login', self._login)\n        search_url = SEARCH_URL.format(login=_login)\n        return self._request_api(url=search_url).json()",
    "docstring": "Get a user's project.\n\n        :param str login: User's login (Default: self._login)\n        :return: JSON"
  },
  {
    "code": "def _preprocess_edges_for_pydot(edges_with_data):\n    for (source, target, attrs) in edges_with_data:\n        if 'label' in attrs:\n            yield (quote_for_pydot(source), quote_for_pydot(target),\n                   {'label': quote_for_pydot(attrs['label'])})\n        else:\n            yield (quote_for_pydot(source), quote_for_pydot(target), {})",
    "docstring": "throw away all edge attributes, except for 'label"
  },
  {
    "code": "def item_after(self, item):\n        next_iter = self._next_iter_for(item)\n        if next_iter is not None:\n            return self._object_at_iter(next_iter)",
    "docstring": "The item after an item"
  },
  {
    "code": "def is_valid_geometry(geometry):\n    if isinstance(geometry, Polygon) or isinstance(geometry, MultiPolygon):\n        return True\n    else:\n        return False",
    "docstring": "Confirm that the geometry type is of type Polygon or MultiPolygon.\n\n    Args:\n        geometry (BaseGeometry): BaseGeometry instance (e.g. Polygon)\n\n    Returns:\n        bool"
  },
  {
    "code": "def get_cmd_handler(self, cmd):\n        cmd = cmd.replace('-', '_')\n        handler = getattr(self, cmd, None)\n        if not handler:\n            raise BuildException(\n                'Command {} is not supported as a '\n                'build command'.format(cmd)\n            )\n        return handler",
    "docstring": "Return an handler for cmd.\n        The handler and the command should have the same name.\n        See class description for more info about handlers.\n\n        Args:\n            cmd (str): The name of the command\n\n        Returns:\n            callable: which handles cmd\n\n        Raises:\n            lago.build.BuildException: If an handler for cmd doesn't exist"
  },
  {
    "code": "def _handle_actionconstantpool(self, _):\n        obj = _make_object(\"ActionConstantPool\")\n        obj.Count = count = unpack_ui16(self._src)\n        obj.ConstantPool = pool = []\n        for _ in range(count):\n            pool.append(self._get_struct_string())\n        yield obj",
    "docstring": "Handle the ActionConstantPool action."
  },
  {
    "code": "def tagify(suffix='', prefix='', base=SALT):\n    parts = [base, TAGS.get(prefix, prefix)]\n    if hasattr(suffix, 'append'):\n        parts.extend(suffix)\n    else:\n        parts.append(suffix)\n    for index, _ in enumerate(parts):\n        try:\n            parts[index] = salt.utils.stringutils.to_str(parts[index])\n        except TypeError:\n            parts[index] = str(parts[index])\n    return TAGPARTER.join([part for part in parts if part])",
    "docstring": "convenience function to build a namespaced event tag string\n    from joining with the TABPART character the base, prefix and suffix\n\n    If string prefix is a valid key in TAGS Then use the value of key prefix\n    Else use prefix string\n\n    If suffix is a list Then join all string elements of suffix individually\n    Else use string suffix"
  },
  {
    "code": "def clone(self):\n        clone = InferenceContext(self.path, inferred=self.inferred)\n        clone.callcontext = self.callcontext\n        clone.boundnode = self.boundnode\n        clone.extra_context = self.extra_context\n        return clone",
    "docstring": "Clone inference path\n\n        For example, each side of a binary operation (BinOp)\n        starts with the same context but diverge as each side is inferred\n        so the InferenceContext will need be cloned"
  },
  {
    "code": "def walk(self, work, predicate=None):\n    if not callable(work):\n      raise ValueError('work must be callable but was {}'.format(work))\n    if predicate and not callable(predicate):\n      raise ValueError('predicate must be callable but was {}'.format(predicate))\n    self._build_graph.walk_transitive_dependency_graph([self.address], work, predicate)",
    "docstring": "Walk of this target's dependency graph, DFS preorder traversal, visiting each node exactly\n    once.\n\n    If a predicate is supplied it will be used to test each target before handing the target to\n    work and descending. Work can return targets in which case these will be added to the walk\n    candidate set if not already walked.\n\n    :API: public\n\n    :param work: Callable that takes a :py:class:`pants.build_graph.target.Target`\n      as its single argument.\n    :param predicate: Callable that takes a :py:class:`pants.build_graph.target.Target`\n      as its single argument and returns True if the target should passed to ``work``."
  },
  {
    "code": "def _findSamesetProteins(protToPeps, proteins=None):\n    proteins = viewkeys(protToPeps) if proteins is None else proteins\n    equalEvidence = ddict(set)\n    for protein in proteins:\n        peptides = protToPeps[protein]\n        equalEvidence[tuple(sorted(peptides))].add(protein)\n    equalProteins = list()\n    for proteins in viewvalues(equalEvidence):\n        if len(proteins) > 1:\n            equalProteins.append(tuple(sorted(proteins)))\n    return equalProteins",
    "docstring": "Find proteins that are mapped to an identical set of peptides.\n\n    :param protToPeps: dict, for each protein (=key) contains a set of\n        associated peptides (=value). For Example {protein: {peptide, ...}, ...}\n    :param proteins: iterable, proteins that are tested for having equal\n        evidence. If not specified all proteins are tested\n    :returns: a list of sorted protein tuples that share equal peptide evidence"
  },
  {
    "code": "def check_authorization(self, response):\n        if not hasattr(request, '_authorized'):\n            raise Unauthorized\n        elif not request._authorized:\n            raise Unauthorized\n        return response",
    "docstring": "checks that an authorization call has been made during the request"
  },
  {
    "code": "def delete_subscription(self):\n        url = self._build_url('subscription', base_url=self._api)\n        return self._boolean(self._delete(url), 204, 404)",
    "docstring": "Delete subscription for this thread.\n\n        :returns: bool"
  },
  {
    "code": "def add_empty_magic_table(self, dtype, col_names=None, groups=None):\n        if dtype not in self.table_names:\n            print(\"-W- {} is not a valid MagIC table name\".format(dtype))\n            print(\"-I- Valid table names are: {}\".format(\", \".join(self.table_names)))\n            return\n        data_container = MagicDataFrame(dtype=dtype, columns=col_names, groups=groups)\n        self.tables[dtype] = data_container",
    "docstring": "Add a blank MagicDataFrame to the contribution.\n        You can provide either a list of column names,\n        or a list of column group names.\n        If provided, col_names takes precedence."
  },
  {
    "code": "def get_children(self, path, watch=None):\n        _log.debug(\n            \"ZK: Getting children of {path}\".format(path=path),\n        )\n        return self.zk.get_children(path, watch)",
    "docstring": "Returns the children of the specified node."
  },
  {
    "code": "def get_name(self):\n        return getattr(self, 'dependent_host_name', '') + '/'\\\n            + getattr(self, 'dependent_service_description', '') \\\n            + '..' + getattr(self, 'host_name', '') + '/' \\\n            + getattr(self, 'service_description', '')",
    "docstring": "Get name based on 4 class attributes\n        Each attribute is substituted by '' if attribute does not exist\n\n        :return: dependent_host_name/dependent_service_description..host_name/service_description\n        :rtype: str\n        TODO: Clean this function (use format for string)"
  },
  {
    "code": "def tag(self, tags):\n        tags = tags.lower()\n        previous = self.tagged\n        tagset = previous.copy()\n        for tag in tags.replace(',', ' ').split():\n            if tag.startswith('-'):\n                tagset.discard(tag[1:])\n            elif tag.startswith('+'):\n                tagset.add(tag[1:])\n            else:\n                tagset.add(tag)\n        tagset.discard('')\n        if tagset != previous:\n            tagset = ' '.join(sorted(tagset))\n            self._make_it_so(\"setting tags %r on\" % (tagset,), [\"custom.set\"], \"tags\", tagset)\n            self._fields[\"custom_tags\"] = tagset",
    "docstring": "Add or remove tags."
  },
  {
    "code": "def _setup(self):\n        settings_module = os.environ.get(ENVIRONMENT_SETTINGS_VARIABLE, 'settings')\n        if not settings_module:\n            raise ImproperlyConfigured(\n                'Requested settings module points to an empty variable. '\n                'You must either define the environment variable {0} '\n                'or call settings.configure() before accessing the settings.'\n                .format(ENVIRONMENT_SETTINGS_VARIABLE))\n        self._wrapped = Settings(settings_module, default_settings=global_settings)",
    "docstring": "Load the settings module pointed to by the environment variable. This\n        is used the first time we need any settings at all, if the user has not\n        previously configured the settings manually."
  },
  {
    "code": "def get_schedules(profile='pagerduty', subdomain=None, api_key=None):\n    return _list_items(\n        'schedules',\n        'id',\n        profile=profile,\n        subdomain=subdomain,\n        api_key=api_key,\n    )",
    "docstring": "List schedules belonging to this account\n\n    CLI Example:\n\n        salt myminion pagerduty.get_schedules"
  },
  {
    "code": "def _raise_document_too_large(operation, doc_size, max_size):\n    if operation == \"insert\":\n        raise DocumentTooLarge(\"BSON document too large (%d bytes)\"\n                               \" - the connected server supports\"\n                               \" BSON document sizes up to %d\"\n                               \" bytes.\" % (doc_size, max_size))\n    else:\n        raise DocumentTooLarge(\"%r command document too large\" % (operation,))",
    "docstring": "Internal helper for raising DocumentTooLarge."
  },
  {
    "code": "def connect(self):\n        if self.state == DISCONNECTED:\n            raise errors.NSQException('connection already closed')\n        if self.is_connected:\n            return\n        stream = Stream(self.address, self.port, self.timeout)\n        stream.connect()\n        self.stream = stream\n        self.state = CONNECTED\n        self.send(nsq.MAGIC_V2)",
    "docstring": "Initialize connection to the nsqd."
  },
  {
    "code": "def load_img(path, grayscale=False, target_size=None):\n    img = io.imread(path, grayscale)\n    if target_size:\n        img = transform.resize(img, target_size, preserve_range=True).astype('uint8')\n    return img",
    "docstring": "Utility function to load an image from disk.\n\n    Args:\n      path: The image file path.\n      grayscale: True to convert to grayscale image (Default value = False)\n      target_size: (w, h) to resize. (Default value = None)\n\n    Returns:\n        The loaded numpy image."
  },
  {
    "code": "def flush_all(self):\n        for queue_name in chain(self.queues, self.delay_queues):\n            self.flush(queue_name)",
    "docstring": "Drop all messages from all declared queues."
  },
  {
    "code": "def n_tasks(dec_num):\n    bitstring = \"\"\n    try:\n        bitstring = dec_num[2:]\n    except:\n        bitstring = bin(int(dec_num))[2:]\n    return bitstring.count(\"1\")",
    "docstring": "Takes a decimal number as input and returns the number of ones in the\n    binary representation.\n    This translates to the number of tasks being done by an organism with a\n    phenotype represented as a decimal number."
  },
  {
    "code": "def get_ini_config(config=os.path.join(os.path.expanduser('~'), '.zdeskcfg'),\n        default_section=None, section=None):\n    plac_ini.call(__placeholder__, config=config, default_section=default_section)\n    return __placeholder__.getconfig(section)",
    "docstring": "This is a convenience function for getting the zdesk configuration\n    from an ini file without the need to decorate and call your own function.\n    Handy when using zdesk and zdeskcfg from the interactive prompt."
  },
  {
    "code": "def Set(self, key, value):\n        if not value == None: self.prefs[key] = value\n        else:                 self.prefs.pop(key)\n        self.Dump()",
    "docstring": "Sets the key-value pair and dumps to the preferences file."
  },
  {
    "code": "def get_or_create_in_transaction_wrapper(tsession, model, values, missing_columns = [], variable_columns = [], updatable_columns = [], only_use_supplied_columns = False, read_only = False):\n    return get_or_create_in_transaction(tsession, model, values, missing_columns = missing_columns, variable_columns = variable_columns, updatable_columns = updatable_columns, only_use_supplied_columns = only_use_supplied_columns, read_only = read_only)",
    "docstring": "This function can be used to determine which calling method is spending time in get_or_create_in_transaction when profiling the database API.\n       Switch out calls to get_or_create_in_transaction to get_or_create_in_transaction_wrapper in the suspected functions to determine where the pain lies."
  },
  {
    "code": "def add_user(self, attrs):\n        username = attrs[self.key]\n        if username in self.users:\n            raise UserAlreadyExists(username, self.backend_name)\n        self.users[username] = attrs\n        self.users[username]['groups'] = set([])",
    "docstring": "Add a user to the backend\n\n        :param attrs: attributes of the user\n        :type attrs: dict ({<attr>: <value>})\n\n        .. warning:: raise UserAlreadyExists if user already exists"
  },
  {
    "code": "def factory(cls, config, db):\n        if not hasattr(db, 'register_script'):\n            LOG.debug(\"Redis client does not support register_script()\")\n            return GetBucketKeyByLock(config, db)\n        info = db.info()\n        if version_greater('2.6', info['redis_version']):\n            LOG.debug(\"Redis server supports register_script()\")\n            return GetBucketKeyByScript(config, db)\n        LOG.debug(\"Redis server does not support register_script()\")\n        return GetBucketKeyByLock(config, db)",
    "docstring": "Given a configuration and database, select and return an\n        appropriate instance of a subclass of GetBucketKey.  This will\n        ensure that both client and server support are available for\n        the Lua script feature of Redis, and if not, a lock will be\n        used.\n\n        :param config: A dictionary of compactor options.\n        :param db: A database handle for the Redis database.\n\n        :returns: An instance of a subclass of GetBucketKey, dependent\n                  on the support for the Lua script feature of Redis."
  },
  {
    "code": "def get_broker_id(data_path):\n    META_FILE_PATH = \"{data_path}/meta.properties\"\n    if not data_path:\n        raise ValueError(\"You need to specify the data_path if broker_id == -1\")\n    meta_properties_path = META_FILE_PATH.format(data_path=data_path)\n    return _read_generated_broker_id(meta_properties_path)",
    "docstring": "This function will look into the data folder to get the automatically created\n    broker_id.\n\n    :param string data_path: the path to the kafka data folder\n    :returns int: the real broker_id"
  },
  {
    "code": "def init_db(self, app, entry_point_group='invenio_db.models', **kwargs):\n        app.config.setdefault(\n            'SQLALCHEMY_DATABASE_URI',\n            'sqlite:///' + os.path.join(app.instance_path, app.name + '.db')\n        )\n        app.config.setdefault('SQLALCHEMY_ECHO', False)\n        database = kwargs.get('db', db)\n        database.init_app(app)\n        self.init_versioning(app, database, kwargs.get('versioning_manager'))\n        if entry_point_group:\n            for base_entry in pkg_resources.iter_entry_points(\n                    entry_point_group):\n                base_entry.load()\n        sa.orm.configure_mappers()\n        if app.config['DB_VERSIONING']:\n            manager = self.versioning_manager\n            if manager.pending_classes:\n                if not versioning_models_registered(manager, database.Model):\n                    manager.builder.configure_versioned_classes()\n            elif 'transaction' not in database.metadata.tables:\n                manager.declarative_base = database.Model\n                manager.create_transaction_model()\n                manager.plugins.after_build_tx_class(manager)",
    "docstring": "Initialize Flask-SQLAlchemy extension."
  },
  {
    "code": "def set_playback(self, playback):\n        req_url = ENDPOINTS[\"setPlayback\"].format(self._ip_address)\n        params = {\"playback\": playback}\n        return request(req_url, params=params)",
    "docstring": "Send Playback command."
  },
  {
    "code": "def for_target(self, target):\n    if not isinstance(target, JarLibrary):\n      return None\n    found_target = target.managed_dependencies\n    if not found_target:\n      return self.default_artifact_set\n    return self._artifact_set_map[found_target.id]",
    "docstring": "Computes and returns the PinnedJarArtifactSet that should be used to manage the given target.\n\n    This returns None if the target is not a JarLibrary.\n\n    :param Target target: The jar_library for which to find the managed_jar_dependencies object.\n    :return: The the artifact set of the managed_jar_dependencies object for the target, or the\n      default artifact set from --default-target.\n    :rtype: PinnedJarArtifactSet"
  },
  {
    "code": "def cancelAllPendingResults( self ):\n        for k in self._results.keys():\n            rs = self._results[k]\n            self._results[k] = [ j for j in rs if isinstance(j, dict) ]\n        self._pending = dict()",
    "docstring": "Cancel all pending results. Note that this only affects the\n        notebook's record, not any job running in a lab."
  },
  {
    "code": "def add_listener(self, callback, event_type=None):\n        listener_id = uuid4()\n        self.listeners.append(\n            {\n                'uid': listener_id,\n                'callback': callback,\n                'event_type': event_type\n            }\n        )\n        return listener_id",
    "docstring": "Add a callback handler for events going to this room.\n\n        Args:\n            callback (func(room, event)): Callback called when an event arrives.\n            event_type (str): The event_type to filter for.\n        Returns:\n            uuid.UUID: Unique id of the listener, can be used to identify the listener."
  },
  {
    "code": "def update(self, **kwargs):\n        if 'monitor' in kwargs:\n            value = self._format_monitor_parameter(kwargs['monitor'])\n            kwargs['monitor'] = value\n        elif 'monitor' in self.__dict__:\n            value = self._format_monitor_parameter(self.__dict__['monitor'])\n            self.__dict__['monitor'] = value\n        return super(Pool, self)._update(**kwargs)",
    "docstring": "Custom update method to implement monitor parameter formatting."
  },
  {
    "code": "def remove_connection(self, connection):\n        if not self._closing:\n            self.connections.remove(connection)\n            logger.debug(\"removed connection\")",
    "docstring": "Called by the connections themselves when they have been closed."
  },
  {
    "code": "def forget(empowered, powerupClass, interface):\n    className = fullyQualifiedName(powerupClass)\n    withThisName = _StoredByName.className == className\n    items = empowered.store.query(_StoredByName, withThisName)\n    if items.count() == 0:\n        template = \"No named powerups for {} (interface: {})\".format\n        raise ValueError(template(powerupClass, interface))\n    for stored in items:\n        empowered.powerDown(stored, interface)\n        stored.deleteFromStore()",
    "docstring": "Forgets powerups previously stored with ``remember``.\n\n    :param empowered: The Empowered (Store or Item) to be powered down.\n    :type empowered: ``axiom.item.Empowered``\n    :param powerupClass: The class for which powerups will be forgotten.\n    :type powerupClass: class\n    :param interface: The interface the powerups were installed for.\n    :type interface: ``zope.interface.Interface``\n    :returns: ``None``\n    :raises ValueError: Class wasn't previously remembered."
  },
  {
    "code": "def getConfigFile():\n    fileName = '.wakatime.cfg'\n    home = os.environ.get('WAKATIME_HOME')\n    if home:\n        return os.path.join(os.path.expanduser(home), fileName)\n    return os.path.join(os.path.expanduser('~'), fileName)",
    "docstring": "Returns the config file location.\n\n    If $WAKATIME_HOME env varialbe is defined, returns\n    $WAKATIME_HOME/.wakatime.cfg, otherwise ~/.wakatime.cfg."
  },
  {
    "code": "def stream(self, sha):\n        hexsha, typename, size, stream = self._git.stream_object_data(bin_to_hex(sha))\n        return OStream(hex_to_bin(hexsha), typename, size, stream)",
    "docstring": "For now, all lookup is done by git itself"
  },
  {
    "code": "def accept_lit(char, buf, pos):\n    if pos >= len(buf) or buf[pos] != char:\n        return None, pos\n    return char, pos+1",
    "docstring": "Accept a literal character at the current buffer position."
  },
  {
    "code": "def handle_json_GET_boundboxstops(self, params):\n    schedule = self.server.schedule\n    n = float(params.get('n'))\n    e = float(params.get('e'))\n    s = float(params.get('s'))\n    w = float(params.get('w'))\n    limit = int(params.get('limit'))\n    stops = schedule.GetStopsInBoundingBox(north=n, east=e, south=s, west=w, n=limit)\n    return [StopToTuple(s) for s in stops]",
    "docstring": "Return a list of up to 'limit' stops within bounding box with 'n','e'\n    and 's','w' in the NE and SW corners. Does not handle boxes crossing\n    longitude line 180."
  },
  {
    "code": "def camel_to_snake(camel_str):\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', camel_str)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()",
    "docstring": "Convert `camel_str` from camelCase to snake_case"
  },
  {
    "code": "def publish_topology_description_changed(self, previous_description,\n                                             new_description, topology_id):\n        event = TopologyDescriptionChangedEvent(previous_description,\n                                                new_description, topology_id)\n        for subscriber in self.__topology_listeners:\n            try:\n                subscriber.description_changed(event)\n            except Exception:\n                _handle_exception()",
    "docstring": "Publish a TopologyDescriptionChangedEvent to all topology listeners.\n\n        :Parameters:\n         - `previous_description`: The previous topology description.\n         - `new_description`: The new topology description.\n         - `topology_id`: A unique identifier for the topology this server\n           is a part of."
  },
  {
    "code": "def _get_siblings(self, pos):\n        parent = self.parent_position(pos)\n        siblings = [pos]\n        if parent is not None:\n            siblings = self._list_dir(parent)\n        return siblings",
    "docstring": "lists the parent directory of pos"
  },
  {
    "code": "def list_authors():\n    authors = Author.query.all()\n    content = '<p>Authors:</p>'\n    for author in authors:\n        content += '<p>%s</p>' % author.name\n    return content",
    "docstring": "List all authors.\n\n    e.g.: GET /authors"
  },
  {
    "code": "def _sample_oat(problem, N, num_levels=4):\n    group_membership = np.asmatrix(np.identity(problem['num_vars'],\n                                               dtype=int))\n    num_params = group_membership.shape[0]\n    sample = np.zeros((N * (num_params + 1), num_params))\n    sample = np.array([generate_trajectory(group_membership,\n                                           num_levels)\n                       for n in range(N)])\n    return sample.reshape((N * (num_params + 1), num_params))",
    "docstring": "Generate trajectories without groups\n\n    Arguments\n    ---------\n    problem : dict\n        The problem definition\n    N : int\n        The number of samples to generate\n    num_levels : int, default=4\n        The number of grid levels"
  },
  {
    "code": "def top(self, container, ps_args=None):\n        u = self._url(\"/containers/{0}/top\", container)\n        params = {}\n        if ps_args is not None:\n            params['ps_args'] = ps_args\n        return self._result(self._get(u, params=params), True)",
    "docstring": "Display the running processes of a container.\n\n        Args:\n            container (str): The container to inspect\n            ps_args (str): An optional arguments passed to ps (e.g. ``aux``)\n\n        Returns:\n            (str): The output of the top\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def index_labels(labels, case_sensitive=False):\n    label_to_index = {}\n    index_to_label = {}\n    if not case_sensitive:\n        labels = [str(s).lower() for s in labels]\n    for index, s in enumerate(sorted(set(labels))):\n        label_to_index[s] = index\n        index_to_label[index] = s\n    indices = [label_to_index[s] for s in labels]\n    return indices, index_to_label",
    "docstring": "Convert a list of string identifiers into numerical indices.\n\n    Parameters\n    ----------\n    labels : list of strings, shape=(n,)\n        A list of annotations, e.g., segment or chord labels from an\n        annotation file.\n\n    case_sensitive : bool\n        Set to True to enable case-sensitive label indexing\n        (Default value = False)\n\n    Returns\n    -------\n    indices : list, shape=(n,)\n        Numerical representation of ``labels``\n    index_to_label : dict\n        Mapping to convert numerical indices back to labels.\n        ``labels[i] == index_to_label[indices[i]]``"
  },
  {
    "code": "def get_lang_array(self):\n        r = self.yandex_translate_request(\"getLangs\", \"\")\n        self.handle_errors(r)\n        return r.json()[\"dirs\"]",
    "docstring": "gets supported langs as an array"
  },
  {
    "code": "def collect_variables(self, selections) -> None:\n        super().collect_variables(selections)\n        self.insert_variables(self.device2base, self.basespecs, selections)",
    "docstring": "Apply method |ChangeItem.collect_variables| of the base class\n        |ChangeItem| and also apply method |ExchangeItem.insert_variables|\n        of class |ExchangeItem| to collect the relevant base variables\n        handled by the devices of the given |Selections| object.\n\n        >>> from hydpy.core.examples import prepare_full_example_2\n        >>> hp, pub, TestIO = prepare_full_example_2()\n        >>> from hydpy import AddItem\n        >>> item = AddItem(\n        ...     'alpha', 'hland_v1', 'control.sfcf', 'control.rfcf', 0)\n        >>> item.collect_variables(pub.selections)\n        >>> land_dill = hp.elements.land_dill\n        >>> control = land_dill.model.parameters.control\n        >>> item.device2target[land_dill] is control.sfcf\n        True\n        >>> item.device2base[land_dill] is control.rfcf\n        True\n        >>> for device in sorted(item.device2base, key=lambda x: x.name):\n        ...     print(device)\n        land_dill\n        land_lahn_1\n        land_lahn_2\n        land_lahn_3"
  },
  {
    "code": "def _has_commit(version, debug=False):\n    if _has_tag(version, debug) or _has_branch(version, debug):\n        return False\n    cmd = sh.git.bake('cat-file', '-e', version)\n    try:\n        util.run_command(cmd, debug=debug)\n        return True\n    except sh.ErrorReturnCode:\n        return False",
    "docstring": "Determine a version is a local git commit sha or not.\n\n    :param version: A string containing the branch/tag/sha to be determined.\n    :param debug: An optional bool to toggle debug output.\n    :return: bool"
  },
  {
    "code": "def _machinectl(cmd,\n                output_loglevel='debug',\n                ignore_retcode=False,\n                use_vt=False):\n    prefix = 'machinectl --no-legend --no-pager'\n    return __salt__['cmd.run_all']('{0} {1}'.format(prefix, cmd),\n                                   output_loglevel=output_loglevel,\n                                   ignore_retcode=ignore_retcode,\n                                   use_vt=use_vt)",
    "docstring": "Helper function to run machinectl"
  },
  {
    "code": "def _init_job_from_response(self, response):\n    job = None\n    if response and 'jobReference' in response:\n      job = _job.Job(job_id=response['jobReference']['jobId'], context=self._context)\n    return job",
    "docstring": "Helper function to create a Job instance from a response."
  },
  {
    "code": "def use_embedded_pkgs(embedded_lib_path=None):\n    if embedded_lib_path is None:\n        embedded_lib_path = get_embedded_lib_path()\n    old_sys_path = list(sys.path)\n    sys.path.insert(\n        1,\n        embedded_lib_path\n    )\n    try:\n        yield\n    finally:\n        sys.path = old_sys_path",
    "docstring": "Temporarily prepend embedded packages to sys.path."
  },
  {
    "code": "def knots_from_marginal(marginal, nr_knots, spline_order):\n    cumsum = np.cumsum(marginal)\n    cumsum = cumsum/cumsum.max()\n    borders = np.linspace(0,1,nr_knots)\n    knot_placement = [0] + np.unique([np.where(cumsum>=b)[0][0] for b in borders[1:-1]]).tolist() +[len(marginal)-1]\n    knots = augknt(knot_placement, spline_order)\n    return knots",
    "docstring": "Determines knot placement based on a marginal distribution.  \n\n    It places knots such that each knot covers the same amount \n    of probability mass. Two of the knots are reserved for the\n    borders which are treated seperatly. For example, a uniform\n    distribution with 5 knots will cause the knots to be equally \n    spaced with 25% of the probability mass between each two \n    knots.\n\n    Input:\n        marginal: Array\n            Estimate of the marginal distribution used to estimate\n            knot placement.\n        nr_knots: int\n            Number of knots to be placed.\n        spline_order: int \n            Order of the splines\n\n    Returns:\n        knots: Array\n            Sequence of knot positions"
  },
  {
    "code": "def get_itoken(self, env):\n        if not self.itoken or self.itoken_expires < time() or \\\n                env.get('HTTP_X_AUTH_NEW_TOKEN', 'false').lower() in \\\n                TRUE_VALUES:\n            self.itoken = '%sitk%s' % (self.reseller_prefix, uuid4().hex)\n            memcache_key = '%s/auth/%s' % (self.reseller_prefix, self.itoken)\n            self.itoken_expires = time() + self.token_life\n            memcache_client = cache_from_env(env)\n            if not memcache_client:\n                raise Exception(\n                    'No memcache set up; required for Swauth middleware')\n            memcache_client.set(\n                memcache_key,\n                (self.itoken_expires,\n                 '.auth,.reseller_admin,%s.auth' % self.reseller_prefix),\n                time=self.token_life)\n        return self.itoken",
    "docstring": "Returns the current internal token to use for the auth system's own\n        actions with other services. Each process will create its own\n        itoken and the token will be deleted and recreated based on the\n        token_life configuration value. The itoken information is stored in\n        memcache because the auth process that is asked by Swift to validate\n        the token may not be the same as the auth process that created the\n        token."
  },
  {
    "code": "def get_last_post_for_model(cr, uid, ids, model_pool):\n    if type(ids) is not list:\n        ids = [ids]\n    res = {}\n    for obj in model_pool.browse(cr, uid, ids):\n        message_ids = obj.message_ids\n        if message_ids:\n            res[obj.id] = sorted(\n                message_ids, key=lambda x: x.date, reverse=True)[0].date\n        else:\n            res[obj.id] = False\n    return res",
    "docstring": "Given a set of ids and a model pool, return a dict of each object ids with\n    their latest message date as a value.\n    To be called in post-migration scripts\n\n    :param cr: database cursor\n    :param uid: user id, assumed to be openerp.SUPERUSER_ID\n    :param ids: ids of the model in question to retrieve ids\n    :param model_pool: orm model pool, assumed to be from pool.get()\n    :return: a dict with ids as keys and with dates as values"
  },
  {
    "code": "def commit(self):\n        num_mutations = len(self._rule_pb_list)\n        if num_mutations == 0:\n            return {}\n        if num_mutations > MAX_MUTATIONS:\n            raise ValueError(\n                \"%d total append mutations exceed the maximum \"\n                \"allowable %d.\" % (num_mutations, MAX_MUTATIONS)\n            )\n        data_client = self._table._instance._client.table_data_client\n        row_response = data_client.read_modify_write_row(\n            table_name=self._table.name, row_key=self._row_key, rules=self._rule_pb_list\n        )\n        self.clear()\n        return _parse_rmw_row_response(row_response)",
    "docstring": "Makes a ``ReadModifyWriteRow`` API request.\n\n        This commits modifications made by :meth:`append_cell_value` and\n        :meth:`increment_cell_value`. If no modifications were made, makes\n        no API request and just returns ``{}``.\n\n        Modifies a row atomically, reading the latest existing\n        timestamp / value from the specified columns and writing a new value by\n        appending / incrementing. The new cell created uses either the current\n        server time or the highest timestamp of a cell in that column (if it\n        exceeds the server time).\n\n        After committing the accumulated mutations, resets the local mutations.\n\n        For example:\n\n        .. literalinclude:: snippets_table.py\n            :start-after: [START bigtable_row_commit]\n            :end-before: [END bigtable_row_commit]\n\n        :rtype: dict\n        :returns: The new contents of all modified cells. Returned as a\n                  dictionary of column families, each of which holds a\n                  dictionary of columns. Each column contains a list of cells\n                  modified. Each cell is represented with a two-tuple with the\n                  value (in bytes) and the timestamp for the cell.\n        :raises: :class:`ValueError <exceptions.ValueError>` if the number of\n                 mutations exceeds the :data:`MAX_MUTATIONS`."
  },
  {
    "code": "def _beam_decode(self,\n                   features,\n                   decode_length,\n                   beam_size,\n                   top_beams,\n                   alpha,\n                   use_tpu=False):\n    return self._beam_decode_slow(features, decode_length, beam_size, top_beams,\n                                  alpha, use_tpu)",
    "docstring": "Beam search decoding.\n\n    Models should ideally implement a more efficient version of this function.\n\n    Args:\n      features: an map of string to `Tensor`\n      decode_length: an integer.  How many additional timesteps to decode.\n      beam_size: number of beams.\n      top_beams: an integer. How many of the beams to return.\n      alpha: Float that controls the length penalty. larger the alpha, stronger\n        the preference for longer translations.\n      use_tpu: A bool, whether to do beam decode on TPU.\n\n    Returns:\n       samples: an integer `Tensor`. Top samples from the beam search"
  },
  {
    "code": "def whois_nameservers(self, nameservers):\n        api_name = 'opendns-whois-nameservers'\n        fmt_url_path = u'whois/nameservers/{0}'\n        return self._multi_get(api_name, fmt_url_path, nameservers)",
    "docstring": "Calls WHOIS Nameserver end point\n\n        Args:\n            emails: An enumerable of nameservers\n        Returns:\n            A dict of {nameserver: domain_result}"
  },
  {
    "code": "def fit(self, x, y, dcoef='none'):\n        self.x = x\n        self.y = y\n        if dcoef is not 'none':\n            coef = dcoef\n        else:\n            coef = self.coef\n        fcoef=optimize.leastsq(self.residual,coef,args=(y,self.func,x))\n        self.fcoef = fcoef[0].tolist()\n        return fcoef[1]",
    "docstring": "performs the fit\n\n        x, y : list\n            Matching data arrays that define a numerical function y(x),\n            this is the data to be fitted.\n        dcoef : list or string\n            You can provide a different guess for the coefficients, or\n            provide the string 'none' to use the inital guess.  The\n            default is 'none'.\n\n        Returns\n        -------\n        ierr\n            Values between 1 and 4 signal success.\n\n        Notes\n        -----\n        self.fcoef, contains the fitted coefficients."
  },
  {
    "code": "def window(ible, length):\n    if length <= 0:\n        raise ValueError\n    ible = iter(ible)\n    while True:\n        elts = [xx for ii, xx in zip(range(length), ible)]\n        if elts:\n            yield elts\n        else:\n            break",
    "docstring": "Split `ible` into multiple lists of length `length`.\n\n    >>> list(window(range(5), 2))\n    [[0, 1], [2, 3], [4]]"
  },
  {
    "code": "def unique_field_data_types(self):\n        data_type_names = set()\n        for field in self.fields:\n            if not is_void_type(field.data_type):\n                if field.data_type.name in data_type_names:\n                    return False\n                else:\n                    data_type_names.add(field.data_type.name)\n        else:\n            return True",
    "docstring": "Checks if all variants have different data types.\n\n        If so, the selected variant can be determined just by the data type of\n        the value without needing a field name / tag. In some languages, this\n        lets us make a shortcut"
  },
  {
    "code": "def _normalise_key_values(filter_obj, attr_map=None):\n    new_filter = {}\n    for key, constraints in filter_obj.items():\n        aliased_key = key\n        if attr_map is not None:\n            aliased_key = attr_map.get(key)\n            if aliased_key is None:\n                raise CloudValueError(\n                    'Invalid key %r for filter attribute; must be one of:\\n%s' % (\n                        key,\n                        attr_map.keys()\n                    )\n                )\n        if not isinstance(constraints, dict):\n            constraints = {'eq': constraints}\n        for operator, value in constraints.items():\n            canonical_operator = FILTER_OPERATOR_ALIASES.get(operator.lstrip('$'))\n            if canonical_operator is None:\n                raise CloudValueError(\n                    'Invalid operator %r for filter key %s; must be one of:\\n%s' % (\n                        operator,\n                        key,\n                        FILTER_OPERATOR_ALIASES.keys()\n                    )\n                )\n            canonical_key = str('%s__%s' % (aliased_key, canonical_operator))\n            new_filter[canonical_key] = _normalise_value(value)\n    return new_filter",
    "docstring": "Converts nested dictionary filters into django-style key value pairs\n\n    Map filter operators and aliases to operator-land\n    Additionally, perform replacements according to attribute map\n    Automatically assumes __eq if not explicitly defined"
  },
  {
    "code": "def is_child_of_family(self, id_, family_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.is_child_of_catalog(id_=id_, catalog_id=family_id)\n        return self._hierarchy_session.is_child(id_=family_id, child_id=id_)",
    "docstring": "Tests if a family is a direct child of another.\n\n        arg:    id (osid.id.Id): an ``Id``\n        arg:    family_id (osid.id.Id): the ``Id`` of a family\n        return: (boolean) - ``true`` if the ``id`` is a child of\n                ``family_id,``  ``false`` otherwise\n        raise:  NotFound - ``family_id`` is not found\n        raise:  NullArgument - ``id`` or ``family_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*\n        *implementation notes*: If ``id`` not found return ``false``."
  },
  {
    "code": "def get_resource_cache(resourceid):\n        if not resourceid:\n            raise ResourceInitError(\"Resource id missing\")\n        if not DutInformationList._cache.get(resourceid):\n            DutInformationList._cache[resourceid] = dict()\n        return DutInformationList._cache[resourceid]",
    "docstring": "Get a cached dictionary related to an individual resourceid.\n\n        :param resourceid: String resource id.\n        :return: dict"
  },
  {
    "code": "def render_unregistered(error=None):\n    return template(\n        read_index_template(),\n        registered=False,\n        error=error,\n        seeder_data=None,\n        url_id=None,\n    )",
    "docstring": "Render template file for the unregistered user.\n\n    Args:\n        error (str, default None): Optional error message.\n\n    Returns:\n        str: Template filled with data."
  },
  {
    "code": "def unpack(self, data):\n        size = self._get_calculated_size(self.size, data)\n        self.set_value(data[0:size])\n        return data[len(self):]",
    "docstring": "Takes in a byte string and set's the field value based on field\n        definition.\n\n        :param structure: The message structure class object\n        :param data: The byte string of the data to unpack\n        :return: The remaining data for subsequent fields"
  },
  {
    "code": "def inverse_transform(self, maps):\n        out = {}\n        out[parameters.chirp_distance] = \\\n                conversions.chirp_distance(maps[parameters.distance],\n                                            maps[parameters.mchirp], ref_mass=self.ref_mass)\n        return self.format_output(maps, out)",
    "docstring": "This function transforms from luminosity distance to chirp distance,\n        given the chirp mass.\n\n        Parameters\n        ----------\n        maps : a mapping object\n\n        Examples\n        --------\n        Convert a dict of numpy.array:\n\n        >>> import numpy as np\n        >>> from pycbc import transforms\n        >>> t = transforms.ChirpDistanceToDistance()\n        >>> t.inverse_transform({'distance': np.array([40.]), 'mchirp': np.array([1.2])})\n        {'distance': array([ 40.]), 'chirp_distance': array([ 40.52073522]), 'mchirp': array([ 1.2])}\n\n        Returns\n        -------\n        out : dict\n            A dict with key as parameter name and value as numpy.array or float\n            of transformed values."
  },
  {
    "code": "def organization_fields(self, organization):\n        return self._query_zendesk(self.endpoint.organization_fields, 'organization_field', id=organization)",
    "docstring": "Retrieve the organization fields for this organization.\n\n        :param organization: Organization object or id"
  },
  {
    "code": "def send_command(self, command: str, *args, **kwargs):\n        info = 'send command `%s` to bot. Args: %s | Kwargs: %s'\n        self._messaging_logger.command.info(info, command, args, kwargs)\n        command = command.encode('utf8')\n        args = _json.dumps(args).encode('utf8')\n        kwargs = _json.dumps(kwargs).encode('utf8')\n        frame = (b'', command, args, kwargs)\n        debug = ' send command run_control_loop: %s'\n        self._messaging_logger.command.debug(debug, self._run_control_loop)\n        if self._run_control_loop:\n            self.add_callback(self.command_socket.send_multipart, frame)\n        else:\n            self.command_socket.send_multipart(frame)",
    "docstring": "For request bot to perform some action"
  },
  {
    "code": "def cmd_follow(self, args):\n        if len(args) < 2:\n            print(\"map follow 0|1\")\n            return\n        follow = int(args[1])\n        self.map.set_follow(follow)",
    "docstring": "control following of vehicle"
  },
  {
    "code": "def monkhorst(cls, ngkpt, shiftk=(0.5, 0.5, 0.5), chksymbreak=None, use_symmetries=True,\n                  use_time_reversal=True, comment=None):\n        return cls(\n            kpts=[ngkpt], kpt_shifts=shiftk,\n            use_symmetries=use_symmetries, use_time_reversal=use_time_reversal, chksymbreak=chksymbreak,\n            comment=comment if comment else \"Monkhorst-Pack scheme with user-specified shiftk\")",
    "docstring": "Convenient static constructor for a Monkhorst-Pack mesh.\n\n        Args:\n            ngkpt: Subdivisions N_1, N_2 and N_3 along reciprocal lattice vectors.\n            shiftk: Shift to be applied to the kpoints.\n            use_symmetries: Use spatial symmetries to reduce the number of k-points.\n            use_time_reversal: Use time-reversal symmetry to reduce the number of k-points.\n\n        Returns:\n            :class:`KSampling` object."
  },
  {
    "code": "def get_proxy_ancestor_classes(klass):\n    proxy_ancestor_classes = set()\n    for superclass in klass.__bases__:\n        if hasattr(superclass, '_meta') and superclass._meta.proxy:\n            proxy_ancestor_classes.add(superclass)\n        proxy_ancestor_classes.update(\n            get_proxy_ancestor_classes(superclass))\n    return proxy_ancestor_classes",
    "docstring": "Return a set containing all the proxy model classes that are ancestors\n    of the given class.\n\n    NOTE: This implementation is for Django 1.7, it might need to work\n    differently for other versions especially 1.8+."
  },
  {
    "code": "def write_long(self, n, pack=Struct('>I').pack):\n        if 0 <= n <= 0xFFFFFFFF:\n            self._output_buffer.extend(pack(n))\n        else:\n            raise ValueError('Long %d out of range 0..0xFFFFFFFF', n)\n        return self",
    "docstring": "Write an integer as an unsigned 32-bit value."
  },
  {
    "code": "def _convert(self, format):\n        if self.format == format:\n            return self\n        else:\n            image = Image(self.pil_image)\n            image._format = format\n            return image",
    "docstring": "Return a new Image instance with the given format.\n\n        Returns self if the format is already the same."
  },
  {
    "code": "def generate_openmp_enabled_py(packagename, srcdir='.', disable_openmp=None):\n    if packagename.lower() == 'astropy':\n        packagetitle = 'Astropy'\n    else:\n        packagetitle = packagename\n    epoch = int(os.environ.get('SOURCE_DATE_EPOCH', time.time()))\n    timestamp = datetime.datetime.utcfromtimestamp(epoch)\n    if disable_openmp is not None:\n        import builtins\n        builtins._ASTROPY_DISABLE_SETUP_WITH_OPENMP_ = disable_openmp\n    if _ASTROPY_DISABLE_SETUP_WITH_OPENMP_:\n        log.info(\"OpenMP support has been explicitly disabled.\")\n    openmp_support = False if _ASTROPY_DISABLE_SETUP_WITH_OPENMP_ else is_openmp_supported()\n    src = _IS_OPENMP_ENABLED_SRC.format(packagetitle=packagetitle,\n                                        timestamp=timestamp,\n                                        return_bool=openmp_support)\n    package_srcdir = os.path.join(srcdir, *packagename.split('.'))\n    is_openmp_enabled_py = os.path.join(package_srcdir, 'openmp_enabled.py')\n    with open(is_openmp_enabled_py, 'w') as f:\n        f.write(src)",
    "docstring": "Generate ``package.openmp_enabled.is_openmp_enabled``, which can then be used\n    to determine, post build, whether the package was built with or without\n    OpenMP support."
  },
  {
    "code": "def insert(self, row):\n        data = self._convert_value(row)\n        self._service.InsertRow(data, self._ss.id, self.id)",
    "docstring": "Insert a new row. The row will be added to the end of the\n        spreadsheet. Before inserting, the field names in the given \n        row will be normalized and values with empty field names \n        removed."
  },
  {
    "code": "def zmag(self,):\n        if self._zmag is None:\n            hdulist_index = self.get_hdulist_idx(self.reading.get_ccd_num())\n            self._zmag = self.hdulist[hdulist_index].header.get('PHOTZP', 0.0)\n        return self._zmag",
    "docstring": "Return the photometric zeropoint of the CCD associated with the reading.\n        @return: float"
  },
  {
    "code": "def parse(self, rule: str):\n        if not rule:\n            return checks.TrueCheck()\n        for token, value in self._parse_tokenize(rule):\n            self._shift(token, value)\n        try:\n            return self.result\n        except ValueError:\n            LOG.exception('Failed to understand rule %r', rule)\n            return checks.FalseCheck()",
    "docstring": "Parses policy to tree.\n\n        Translate a policy written in the policy language into a tree of\n        Check objects."
  },
  {
    "code": "def _send(self, msg):\n        if isinstance(msg, six.binary_type):\n            method = uwsgi.websocket_send_binary\n        else:\n            method = uwsgi.websocket_send\n        if self._req_ctx is not None:\n            method(msg, request_context=self._req_ctx)\n        else:\n            method(msg)",
    "docstring": "Transmits message either in binary or UTF-8 text mode,\n        depending on its type."
  },
  {
    "code": "def bind(\n        self,\n        port: int,\n        address: str = None,\n        family: socket.AddressFamily = socket.AF_UNSPEC,\n        backlog: int = 128,\n        reuse_port: bool = False,\n    ) -> None:\n        sockets = bind_sockets(\n            port, address=address, family=family, backlog=backlog, reuse_port=reuse_port\n        )\n        if self._started:\n            self.add_sockets(sockets)\n        else:\n            self._pending_sockets.extend(sockets)",
    "docstring": "Binds this server to the given port on the given address.\n\n        To start the server, call `start`. If you want to run this server\n        in a single process, you can call `listen` as a shortcut to the\n        sequence of `bind` and `start` calls.\n\n        Address may be either an IP address or hostname.  If it's a hostname,\n        the server will listen on all IP addresses associated with the\n        name.  Address may be an empty string or None to listen on all\n        available interfaces.  Family may be set to either `socket.AF_INET`\n        or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise\n        both will be used if available.\n\n        The ``backlog`` argument has the same meaning as for\n        `socket.listen <socket.socket.listen>`. The ``reuse_port`` argument\n        has the same meaning as for `.bind_sockets`.\n\n        This method may be called multiple times prior to `start` to listen\n        on multiple ports or interfaces.\n\n        .. versionchanged:: 4.4\n           Added the ``reuse_port`` argument."
  },
  {
    "code": "def try_run_setup(**kwargs):\n    try:\n        run_setup(**kwargs)\n    except Exception as e:\n        print(str(e))\n        if \"xgboost\" in str(e).lower():\n            kwargs[\"test_xgboost\"] = False\n            print(\"Couldn't install XGBoost for testing!\")\n            try_run_setup(**kwargs)\n        elif \"lightgbm\" in str(e).lower():\n            kwargs[\"test_lightgbm\"] = False\n            print(\"Couldn't install LightGBM for testing!\")\n            try_run_setup(**kwargs)\n        elif kwargs[\"with_binary\"]:\n            kwargs[\"with_binary\"] = False\n            print(\"WARNING: The C extension could not be compiled, sklearn tree models not supported.\")\n            try_run_setup(**kwargs)\n        else:\n            print(\"ERROR: Failed to build!\")",
    "docstring": "Fails gracefully when various install steps don't work."
  },
  {
    "code": "def get_org_smarthost(self, orgid, serverid):\n        return self.api_call(\n            ENDPOINTS['orgsmarthosts']['get'],\n            dict(orgid=orgid, serverid=serverid))",
    "docstring": "Get an organization smarthost"
  },
  {
    "code": "def _maybe_get_plugin_name(cls, classpath_element):\n    def process_info_file(cp_elem, info_file):\n      plugin_info = ElementTree.parse(info_file).getroot()\n      if plugin_info.tag != 'plugin':\n        raise TaskError('File {} in {} is not a valid scalac plugin descriptor'.format(\n            _SCALAC_PLUGIN_INFO_FILE, cp_elem))\n      return plugin_info.find('name').text\n    if os.path.isdir(classpath_element):\n      try:\n        with open(os.path.join(classpath_element, _SCALAC_PLUGIN_INFO_FILE), 'r') as plugin_info_file:\n          return process_info_file(classpath_element, plugin_info_file)\n      except IOError as e:\n        if e.errno != errno.ENOENT:\n          raise\n    else:\n      with open_zip(classpath_element, 'r') as jarfile:\n        try:\n          with closing(jarfile.open(_SCALAC_PLUGIN_INFO_FILE, 'r')) as plugin_info_file:\n            return process_info_file(classpath_element, plugin_info_file)\n        except KeyError:\n          pass\n    return None",
    "docstring": "If classpath_element is a scalac plugin, returns its name.\n\n    Returns None otherwise."
  },
  {
    "code": "def device(value):\n    browser = None\n    for regex, name in BROWSERS:\n        if regex.search(value):\n            browser = name\n            break\n    device = None\n    for regex, name in DEVICES:\n        if regex.search(value):\n            device = name\n            break\n    if browser and device:\n        return _('%(browser)s on %(device)s') % {\n            'browser': browser,\n            'device': device\n        }\n    if browser:\n        return browser\n    if device:\n        return device\n    return None",
    "docstring": "Transform a User Agent into human readable text.\n\n    Example output:\n\n    * Safari on iPhone\n    * Chrome on Windows 8.1\n    * Safari on OS X\n    * Firefox\n    * Linux\n    * None"
  },
  {
    "code": "def reset_instance_attribute(self, instance_id, attribute):\n        params = {'InstanceId' : instance_id,\n                  'Attribute' : attribute}\n        return self.get_status('ResetInstanceAttribute', params, verb='POST')",
    "docstring": "Resets an attribute of an instance to its default value.\n\n        :type instance_id: string\n        :param instance_id: ID of the instance\n\n        :type attribute: string\n        :param attribute: The attribute to reset. Valid values are:\n                          kernel|ramdisk\n\n        :rtype: bool\n        :return: Whether the operation succeeded or not"
  },
  {
    "code": "def get_formset(self, request, obj=None, **kwargs):\n        data = super().get_formset(request, obj, **kwargs)\n        if obj:\n            data.form.base_fields['user'].initial = request.user.id\n        return data",
    "docstring": "Default user to the current version owner."
  },
  {
    "code": "def RunOnce(self):\n    from grr_response_server.gui import gui_plugins\n    if config.CONFIG.Get(\"AdminUI.django_secret_key\", None):\n      logging.warning(\n          \"The AdminUI.django_secret_key option has been deprecated, \"\n          \"please use AdminUI.csrf_secret_key instead.\")",
    "docstring": "Import the plugins once only."
  },
  {
    "code": "def preRun_(self):\n        self.report(\"preRun_\")\n        super().preRun_()\n        self.client = ShmemRGBClient(\n            name=self.shmem_name,\n            n_ringbuffer=self.n_buffer,\n            width=self.image_dimensions[0],\n            height=self.image_dimensions[1],\n            mstimeout=1000,\n            verbose=False\n        )",
    "docstring": "Create the shared memory client immediately after fork"
  },
  {
    "code": "def show(ctx, short_name):\n    wva = get_wva(ctx)\n    subscription = wva.get_subscription(short_name)\n    cli_pprint(subscription.get_metadata())",
    "docstring": "Show metadata for a specific subscription\n\nExample:\n\n\\b\n    $ wva subscriptions show speed\n    {'buffer': 'queue', 'interval': 5, 'uri': 'vehicle/data/VehicleSpeed'}"
  },
  {
    "code": "def fromfile(cls, path):\n        parser = etree.XMLParser(remove_blank_text=True)\n        return cls.fromtree(etree.parse(path, parser=parser))",
    "docstring": "Creates a METS by parsing a file.\n\n        :param str path: Path to a METS document."
  },
  {
    "code": "def _add_dynamic_field_to_instance(self, field, field_name):\n        new_field = field._create_dynamic_version()\n        new_field.name = field_name\n        new_field._attach_to_instance(self)\n        if field_name not in self._fields:\n            if id(self._fields) == id(self.__class__._fields):\n                self._fields = list(self._fields)\n            self._fields.append(field_name)\n        if isinstance(field, limpyd_fields.InstanceHashField):\n            if id(self._instancehash_fields) == id(self.__class__._instancehash_fields):\n                self._instancehash_fields = list(self._instancehash_fields)\n            self._instancehash_fields.append(field_name)\n        setattr(self, field_name, new_field)\n        return new_field",
    "docstring": "Add a copy of the DynamicField \"field\" to the current instance using the\n        \"field_name\" name"
  },
  {
    "code": "def __get_rc_handle(self, root_dir):\n        rc_path = os.path.join(root_dir, '.rc')\n        env_path = os.path.join(root_dir, '.env')\n        fh = open(rc_path, \"w+\")\n        fh.write(source_template % (env_path, env_path))\n        return (rc_path, fh)",
    "docstring": "get the filepath and filehandle to the rc file for the environment"
  },
  {
    "code": "def expect_all(a, b):\n    assert all(_a == _b for _a, _b in zip_longest(a, b))",
    "docstring": "\\\n    Asserts that two iterables contain the same values."
  },
  {
    "code": "def setAndDrawInspectorById(self, identifier):\n        self.setInspectorById(identifier)\n        regItem = self.inspectorRegItem\n        if regItem and not regItem.successfullyImported:\n            msg = \"Unable to import {} inspector.\\n{}\".format(regItem.identifier, regItem.exception)\n            QtWidgets.QMessageBox.warning(self, \"Warning\", msg)\n            logger.warn(msg)\n        self.drawInspectorContents(reason=UpdateReason.INSPECTOR_CHANGED)",
    "docstring": "Sets the inspector and draw the contents.\n\n            Does NOT trigger any actions, so the check marks in the menus are not updated. To\n            achieve this, the user must update the actions by hand (or call\n            getInspectorActionById(identifier).trigger() instead)."
  },
  {
    "code": "def create_group(self, attrs, members, folder_id=None, tags=None):\n        cn = {}\n        cn['m'] = members\n        if folder_id:\n            cn['l'] = str(folder_id)\n        if tags:\n            cn['tn'] = tags\n        attrs = [{'n': k, '_content': v} for k, v in attrs.items()]\n        attrs.append({'n': 'type', '_content': 'group'})\n        cn['a'] = attrs\n        resp = self.request_single('CreateContact', {'cn': cn})\n        return zobjects.Contact.from_dict(resp)",
    "docstring": "Create a contact group\n\n        XML example :\n        <cn l=\"7> ## ContactSpec\n            <a n=\"lastName\">MARTIN</a>\n            <a n=\"firstName\">Pierre</a>\n            <a n=\"email\">pmartin@example.com</a>\n        </cn>\n        Which would be in zimsoap : attrs = { 'lastname': 'MARTIN',\n                                        'firstname': 'Pierre',\n                                        'email': 'pmartin@example.com' }\n                                    folder_id = 7\n\n        :param folder_id: a string of the ID's folder where to create\n        contact. Default '7'\n        :param tags:     comma-separated list of tag names\n        :param members:  list of dict. Members with their type. Example\n        {'type': 'I', 'value': 'manual_addresse@example.com'}.\n        :param attrs:   a dictionary of attributes to set ({key:value,...}). At\n        least one attr is required\n        :returns:       the created zobjects.Contact"
  },
  {
    "code": "def wormhole(context, dump_timing, transit_helper, relay_url, appid):\n    context.obj = cfg = Config()\n    cfg.appid = appid\n    cfg.relay_url = relay_url\n    cfg.transit_helper = transit_helper\n    cfg.dump_timing = dump_timing",
    "docstring": "Create a Magic Wormhole and communicate through it.\n\n    Wormholes are created by speaking the same magic CODE in two\n    different places at the same time.  Wormholes are secure against\n    anyone who doesn't use the same code."
  },
  {
    "code": "def release_downloads(request, package_name, version):\n    session = DBSession()\n    release_files = ReleaseFile.by_release(session, package_name, version)\n    if release_files:\n        release_files = [(f.release.package.name,\n                            f.filename) for f in release_files]\n    return release_files",
    "docstring": "Retrieve a list of files and download count for a given package and\n    release version."
  },
  {
    "code": "def namelist(self):\n        l = []\n        for data in self.filelist:\n            l.append(data.filename)\n        return l",
    "docstring": "Return a list of file names in the archive."
  },
  {
    "code": "def _reachable_subsystems(network, indices, state):\n    validate.is_network(network)\n    for subset in utils.powerset(indices, nonempty=True, reverse=True):\n        try:\n            yield Subsystem(network, state, subset)\n        except exceptions.StateUnreachableError:\n            pass",
    "docstring": "A generator over all subsystems in a valid state."
  },
  {
    "code": "def download_person_playlists(self):\n        with open(person_info_path, 'r') as person_info:\n            user_id = int(person_info.read())\n        self.download_user_playlists_by_id(user_id)",
    "docstring": "Download person playlist including private playlist.\n\n        note: login required."
  },
  {
    "code": "def isometric_view_interactive(self):\n        interactor = self.iren.GetInteractorStyle()\n        renderer = interactor.GetCurrentRenderer()\n        renderer.view_isometric()",
    "docstring": "sets the current interactive render window to isometric view"
  },
  {
    "code": "def _shallow_copy(self, obj=None, obj_type=None, **kwargs):\n        if obj is None:\n            obj = self._selected_obj.copy()\n        if obj_type is None:\n            obj_type = self._constructor\n        if isinstance(obj, obj_type):\n            obj = obj.obj\n        for attr in self._attributes:\n            if attr not in kwargs:\n                kwargs[attr] = getattr(self, attr)\n        return obj_type(obj, **kwargs)",
    "docstring": "return a new object with the replacement attributes"
  },
  {
    "code": "def shiftImage(u, v, t, img, interpolation=cv2.INTER_LANCZOS4):\r\n    ny,nx = u.shape\r\n    sy, sx = np.mgrid[:float(ny):1,:float(nx):1]\r\n    sx += u*t\r\n    sy += v*t\r\n    return cv2.remap(img.astype(np.float32), \r\n                    (sx).astype(np.float32),\r\n                    (sy).astype(np.float32), interpolation)",
    "docstring": "remap an image using velocity field"
  },
  {
    "code": "def plot(self, entity):\n        df = self._binary_df[[entity]]\n        resampled = df.resample(\"s\").ffill()\n        resampled.columns = [\"value\"]\n        fig, ax = plt.subplots(1, 1, figsize=(16, 2))\n        ax.fill_between(resampled.index, y1=0, y2=1, facecolor=\"royalblue\", label=\"off\")\n        ax.fill_between(\n            resampled.index,\n            y1=0,\n            y2=1,\n            where=(resampled[\"value\"] > 0),\n            facecolor=\"red\",\n            label=\"on\",\n        )\n        ax.set_title(entity)\n        ax.set_xlabel(\"Date\")\n        ax.set_frame_on(False)\n        ax.set_yticks([])\n        plt.legend(loc=(1.01, 0.7))\n        plt.show()\n        return",
    "docstring": "Basic plot of a single binary sensor data.\n\n        Parameters\n        ----------\n        entity : string\n            The entity to plot"
  },
  {
    "code": "def absolute_url(self):\n        if self.is_root():\n            return utils.concat_urls(self.url)\n        return utils.concat_urls(self.parent.absolute_url, self.url)",
    "docstring": "Get the absolute url of ``self``.\n\n        Returns:\n            str: the absolute url."
  },
  {
    "code": "def set_hash_key(self, file):\n        filehasher = hashlib.md5()\n        while True:\n            data = file.read(8192)\n            if not data:\n                break\n            filehasher.update(data)\n        file.seek(0)\n        self.hash_key = filehasher.hexdigest()",
    "docstring": "Calculate and store hash key for file."
  },
  {
    "code": "def getParent(self, returned_properties=None):\n        parent_tag = (\"rtc_cm:com.ibm.team.workitem.linktype.\"\n                      \"parentworkitem.parent\")\n        rp = returned_properties\n        parent = (self.rtc_obj\n                      ._get_paged_resources(\"Parent\",\n                                            workitem_id=self.identifier,\n                                            customized_attr=parent_tag,\n                                            page_size=\"5\",\n                                            returned_properties=rp))\n        if parent:\n            return parent[0]\n        return None",
    "docstring": "Get the parent workitem of this workitem\n\n        If no parent, None will be returned.\n\n        :param returned_properties: the returned properties that you want.\n            Refer to :class:`rtcclient.client.RTCClient` for more explanations\n        :return: a :class:`rtcclient.workitem.Workitem` object\n        :rtype: rtcclient.workitem.Workitem"
  },
  {
    "code": "def setval(self, varname, value):\n        if varname in self:\n            self[varname]['value'] = value\n        else:\n            self[varname] = Variable(self.default_type, value=value)",
    "docstring": "Set the value of the variable with the given name."
  },
  {
    "code": "def generate(data, format=\"auto\"):\n    try:\n        with open(data) as in_file:\n            if format == 'auto':\n                format = data.split('.')[-1]\n            data = in_file.read()\n    except:\n        if format == 'auto':\n            format = 'smi'\n    return format_converter.convert(data, format, 'json')",
    "docstring": "Converts input chemical formats to json and optimizes structure.\n\n    Args:\n        data: A string or file representing a chemical\n        format: The format of the `data` variable (default is 'auto')\n\n    The `format` can be any value specified by Open Babel\n    (http://openbabel.org/docs/2.3.1/FileFormats/Overview.html). The 'auto'\n    option uses the extension for files (ie. my_file.mol -> mol) and defaults\n    to SMILES (smi) for strings."
  },
  {
    "code": "def print_result_for_plain_cgi_script(contenttype: str,\n                                      headers: TYPE_WSGI_RESPONSE_HEADERS,\n                                      content: bytes,\n                                      status: str = '200 OK') -> None:\n    headers = [\n        (\"Status\", status),\n        (\"Content-Type\", contenttype),\n        (\"Content-Length\", str(len(content))),\n    ] + headers\n    sys.stdout.write(\"\\n\".join([h[0] + \": \" + h[1] for h in headers]) + \"\\n\\n\")\n    sys.stdout.write(content)",
    "docstring": "Writes HTTP request result to stdout."
  },
  {
    "code": "def get_cached_source_variable(self, source_id, variable, default=None):\n        source_id = int(source_id)\n        try:\n            return self._retrieve_cached_source_variable(\n                    source_id, variable)\n        except UncachedVariable:\n            return default",
    "docstring": "Get the cached value of a source variable. If the variable is not\n        cached return the default value."
  },
  {
    "code": "def CurrentNode(self):\n        ret = libxml2mod.xmlTextReaderCurrentNode(self._o)\n        if ret is None:raise treeError('xmlTextReaderCurrentNode() failed')\n        __tmp = xmlNode(_obj=ret)\n        return __tmp",
    "docstring": "Hacking interface allowing to get the xmlNodePtr\n          correponding to the current node being accessed by the\n          xmlTextReader. This is dangerous because the underlying\n           node may be destroyed on the next Reads."
  },
  {
    "code": "def to_hostnames_list(ref, tab):\n    res = []\n    for host in tab:\n        if hasattr(host, 'host_name'):\n            res.append(host.host_name)\n    return res",
    "docstring": "Convert Host list into a list of  host_name\n\n    :param ref: Not used\n    :type ref:\n    :param tab: Host list\n    :type tab: list[alignak.objects.host.Host]\n    :return: host_name list\n    :rtype: list"
  },
  {
    "code": "def list_to_tree(cls, files):\n        def attach(branch, trunk):\n            parts = branch.split('/', 1)\n            if len(parts) == 1:\n                trunk[FILE_MARKER].append(parts[0])\n            else:\n                node, others = parts\n                if node not in trunk:\n                    trunk[node] = defaultdict(dict, ((FILE_MARKER, []), ))\n                attach(others, trunk[node])\n        tree = defaultdict(dict, ((FILE_MARKER, []), ))\n        for line in files:\n            attach(line, tree)\n        return tree",
    "docstring": "Converts a list of filenames into a directory tree structure."
  },
  {
    "code": "def base64_user_pass(self):\n        if self._username is None or self._password is None:\n            return None\n        hash_ = base64.urlsafe_b64encode(bytes_(\"{username}:{password}\".format(\n            username=self._username,\n            password=self._password\n        )))\n        return \"Basic {0}\".format(unicode_(hash_))",
    "docstring": "Composes a basic http auth string, suitable for use with the\n        _replicator database, and other places that need it.\n\n        :returns: Basic http authentication string"
  },
  {
    "code": "def json_obj(self, method, params=None, auth=True):\n        if params is None:\n            params = {}\n        obj = {\n            'jsonrpc': '2.0',\n            'method': method,\n            'params': params,\n            'auth': self.__auth if auth else None,\n            'id': self.id,\n        }\n        return json.dumps(obj)",
    "docstring": "Return JSON object expected by the Zabbix API"
  },
  {
    "code": "def get_annotation(self, key, result_format='list'):\n        value = self.get('_annotations_by_key', {}).get(key)\n        if not value:\n            return value\n        if result_format == 'one':\n            return value[0]\n        return value",
    "docstring": "Is a convenience method for accessing annotations on models that have them"
  },
  {
    "code": "def preprocess_async(train_dataset, output_dir, eval_dataset=None, checkpoint=None, cloud=None):\n  with warnings.catch_warnings():\n    warnings.simplefilter(\"ignore\")\n    if cloud is None:\n      return _local.Local.preprocess(train_dataset, output_dir, eval_dataset, checkpoint)\n    if not isinstance(cloud, dict):\n      cloud = {}\n    return _cloud.Cloud.preprocess(train_dataset, output_dir, eval_dataset, checkpoint, cloud)",
    "docstring": "Preprocess data. Produce output that can be used by training efficiently.\n\n  Args:\n    train_dataset: training data source to preprocess. Can be CsvDataset or BigQueryDataSet.\n        If eval_dataset is None, the pipeline will randomly split train_dataset into\n        train/eval set with 7:3 ratio.\n    output_dir: The output directory to use. Preprocessing will create a sub directory under\n        it for each run, and also update \"latest\" file which points to the latest preprocessed\n        directory. Users are responsible for cleanup. Can be local or GCS path.\n    eval_dataset: evaluation data source to preprocess. Can be CsvDataset or BigQueryDataSet.\n        If specified, it will be used for evaluation during training, and train_dataset will be\n        completely used for training.\n    checkpoint: the Inception checkpoint to use. If None, a default checkpoint is used.\n    cloud: a DataFlow pipeline option dictionary such as {'num_workers': 3}. If anything but\n        not None, it will run in cloud. Otherwise, it runs locally.\n\n  Returns:\n    A google.datalab.utils.Job object that can be used to query state from or wait."
  },
  {
    "code": "def compare(sig1, sig2):\n    if isinstance(sig1, six.text_type):\n        sig1 = sig1.encode(\"ascii\")\n    if isinstance(sig2, six.text_type):\n        sig2 = sig2.encode(\"ascii\")\n    if not isinstance(sig1, six.binary_type):\n        raise TypeError(\n            \"First argument must be of string, unicode or bytes type not \"\n            \"'%s'\" % type(sig1)\n        )\n    if not isinstance(sig2, six.binary_type):\n        raise TypeError(\n            \"Second argument must be of string, unicode or bytes type not \"\n            \"'%r'\" % type(sig2)\n        )\n    res = binding.lib.fuzzy_compare(sig1, sig2)\n    if res < 0:\n        raise InternalError(\"Function returned an unexpected error code\")\n    return res",
    "docstring": "Computes the match score between two fuzzy hash signatures.\n\n    Returns a value from zero to 100 indicating the match score of the\n    two signatures. A match score of zero indicates the signatures\n    did not match.\n\n    :param Bytes|String sig1: First fuzzy hash signature\n    :param Bytes|String sig2: Second fuzzy hash signature\n    :return: Match score (0-100)\n    :rtype: Integer\n    :raises InternalError: If lib returns an internal error\n    :raises TypeError: If sig is not String, Unicode or Bytes"
  },
  {
    "code": "def _assert_keys_match(keys1, keys2):\n  if set(keys1) != set(keys2):\n    raise ValueError('{} {}'.format(list(keys1), list(keys2)))",
    "docstring": "Ensure the two list of keys matches."
  },
  {
    "code": "def _init(self):\n        self._entry_points = {}\n        for entry_point in self.raw_entry_points:\n            if entry_point.dist.project_name != self.reserved.get(\n                    entry_point.name, entry_point.dist.project_name):\n                logger.error(\n                    \"registry '%s' for '%s' is reserved for package '%s'\",\n                    entry_point.name, self.registry_name,\n                    self.reserved[entry_point.name],\n                )\n                continue\n            if self.get_record(entry_point.name):\n                logger.warning(\n                    \"registry '%s' for '%s' is already registered.\",\n                    entry_point.name, self.registry_name,\n                )\n                existing = self._entry_points[entry_point.name]\n                logger.debug(\n                    \"registered '%s' from '%s'\", existing, existing.dist)\n                logger.debug(\n                    \"discarded '%s' from '%s'\", entry_point, entry_point.dist)\n                continue\n            logger.debug(\n                \"recording '%s' from '%s'\", entry_point, entry_point.dist)\n            self._entry_points[entry_point.name] = entry_point",
    "docstring": "Turn the records into actual usable keys."
  },
  {
    "code": "def __build_markable_token_mapper(self, coreference_layer=None,\n                                      markable_layer=None):\n        tok2markables = defaultdict(set)\n        markable2toks = defaultdict(list)\n        markable2chains = defaultdict(list)\n        coreference_chains = get_pointing_chains(self.docgraph,\n                                                 layer=coreference_layer)\n        for chain_id, chain in enumerate(coreference_chains):\n            for markable_node_id in chain:\n                markable2chains[markable_node_id].append(chain_id)\n        singleton_id = len(coreference_chains)\n        for markable_node_id in select_nodes_by_layer(self.docgraph,\n                                                      markable_layer):\n            span = get_span(self.docgraph, markable_node_id)\n            markable2toks[markable_node_id] = span\n            for token_node_id in span:\n                tok2markables[token_node_id].add(markable_node_id)\n            if markable_node_id not in markable2chains:\n                markable2chains[markable_node_id] = [singleton_id]\n                singleton_id += 1\n        return tok2markables, markable2toks, markable2chains",
    "docstring": "Creates mappings from tokens to the markable spans they belong to\n        and the coreference chains these markables are part of.\n\n        Returns\n        -------\n        tok2markables : dict (str -> set of str)\n            Maps from a token (node ID) to all the markables (node IDs)\n            it is part of.\n        markable2toks : dict (str -> list of str)\n            Maps from a markable (node ID) to all the tokens (node IDs)\n            that belong to it.\n        markable2chains : dict (str -> list of int)\n            Maps from a markable (node ID) to all the chains (chain ID) it\n            belongs to."
  },
  {
    "code": "def read(self, domain, type_name, search_command, body=None):\n        return self._request(domain, type_name, search_command, 'GET', body)",
    "docstring": "Read entry in ThreatConnect Data Store\n\n        Args:\n            domain (string): One of 'local', 'organization', or 'system'.\n            type_name (string): This is a free form index type name. The ThreatConnect API will use\n                this resource verbatim.\n            search_command (string): Search command to pass to ES.\n            body (str): JSON body"
  },
  {
    "code": "def get_node_host(name, region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    if not conn:\n        return None\n    try:\n        cc = conn.describe_cache_clusters(name,\n                                          show_cache_node_info=True)\n    except boto.exception.BotoServerError as e:\n        msg = 'Failed to get config for cache cluster {0}.'.format(name)\n        log.error(msg)\n        log.debug(e)\n        return {}\n    cc = cc['DescribeCacheClustersResponse']['DescribeCacheClustersResult']\n    host = cc['CacheClusters'][0]['CacheNodes'][0]['Endpoint']['Address']\n    return host",
    "docstring": "Get hostname from cache node\n\n    CLI example::\n\n        salt myminion boto_elasticache.get_node_host myelasticache"
  },
  {
    "code": "def check_that_operator_can_be_applied_to_produces_items(op, g1, g2):\n    g1_tmp_copy = g1.spawn()\n    g2_tmp_copy = g2.spawn()\n    sample_item_1 = next(g1_tmp_copy)\n    sample_item_2 = next(g2_tmp_copy)\n    try:\n        op(sample_item_1, sample_item_2)\n    except TypeError:\n        raise TypeError(f\"Operator '{op.__name__}' cannot be applied to items produced by {g1} and {g2} \"\n                        f\"(which have type {type(sample_item_1)} and {type(sample_item_2)}, respectively)\")",
    "docstring": "Helper function to check that the operator `op` can be applied to items produced by g1 and g2."
  },
  {
    "code": "async def list(self) -> List[str]:\n        LOGGER.debug('NodePoolManager.list >>>')\n        rv = [p['pool'] for p in await pool.list_pools()]\n        LOGGER.debug('NodePoolManager.list <<< %s', rv)\n        return rv",
    "docstring": "Return list of pool names configured, empty list for none.\n\n        :return: list of pool names."
  },
  {
    "code": "def get(context, request, key=None):\n    registry_records = api.get_registry_records_by_keyword(key)\n    size = req.get_batch_size()\n    start = req.get_batch_start()\n    batch = api.make_batch(registry_records, size, start)\n    return {\n        \"pagesize\": batch.get_pagesize(),\n        \"next\": batch.make_next_url(),\n        \"previous\": batch.make_prev_url(),\n        \"page\": batch.get_pagenumber(),\n        \"pages\": batch.get_numpages(),\n        \"count\": batch.get_sequence_length(),\n        \"items\": [registry_records],\n        \"url\": api.url_for(\"senaite.jsonapi.v1.registry\", key=key),\n    }",
    "docstring": "Return all registry items if key is None, otherwise try to fetch the registry key"
  },
  {
    "code": "def get_biome_color_based_on_elevation(world, elev, x, y, rng):\n    v = world.biome_at((x, y)).name()\n    biome_color = _biome_satellite_colors[v]\n    noise = (0, 0, 0)\n    if world.is_land((x, y)):\n        noise = rng.randint(-NOISE_RANGE, NOISE_RANGE, size=3)\n        if elev > HIGH_MOUNTAIN_ELEV:     \n            noise = add_colors(noise, HIGH_MOUNTAIN_NOISE_MODIFIER)\n            biome_color = average_colors(biome_color, MOUNTAIN_COLOR)\n        elif elev > MOUNTAIN_ELEV:   \n            noise = add_colors(noise, MOUNTAIN_NOISE_MODIFIER)\n            biome_color = average_colors(biome_color, MOUNTAIN_COLOR)\n        elif elev > HIGH_HILL_ELEV:   \n            noise = add_colors(noise, HIGH_HILL_NOISE_MODIFIER)\n        elif elev > HILL_ELEV:   \n            noise = add_colors(noise, HILL_NOISE_MODIFIER)\n    modification_amount = int(elev / BASE_ELEVATION_INTENSITY_MODIFIER)\n    base_elevation_modifier = (modification_amount, modification_amount, modification_amount)\n    this_tile_color = add_colors(biome_color, noise, base_elevation_modifier)\n    return this_tile_color",
    "docstring": "This is the \"business logic\" for determining the base biome color in satellite view.\n        This includes generating some \"noise\" at each spot in a pixel's rgb value, potentially \n        modifying the noise based on elevation, and finally incorporating this with the base biome color. \n\n        The basic rules regarding noise generation are:\n        - Oceans have no noise added\n        - land tiles start with noise somewhere inside (-NOISE_RANGE, NOISE_RANGE) for each rgb value\n        - land tiles with high elevations further modify the noise by set amounts (to drain some of the \n          color and make the map look more like mountains) \n\n        The biome's base color may be interpolated with a predefined mountain brown color if the elevation is high enough.\n\n        Finally, the noise plus the biome color are added and returned.\n\n        rng refers to an instance of a random number generator used to draw the random samples needed by this function."
  },
  {
    "code": "def use_federated_book_view(self):\n        self._book_view = FEDERATED\n        for session in self._get_provider_sessions():\n            try:\n                session.use_federated_book_view()\n            except AttributeError:\n                pass",
    "docstring": "Pass through to provider CommentLookupSession.use_federated_book_view"
  },
  {
    "code": "def add(self, private_key):\n        if not isinstance(private_key, PaillierPrivateKey):\n            raise TypeError(\"private_key should be of type PaillierPrivateKey, \"\n                            \"not %s\" % type(private_key))\n        self.__keyring[private_key.public_key] = private_key",
    "docstring": "Add a key to the keyring.\n\n        Args:\n          private_key (PaillierPrivateKey): a key to add to this keyring."
  },
  {
    "code": "def execute_pending_service_agreements(storage_path, account, actor_type, did_resolver_fn):\n    keeper = Keeper.get_instance()\n    for (agreement_id, did, _,\n         price, files, start_time, _) in get_service_agreements(storage_path):\n        ddo = did_resolver_fn(did)\n        for service in ddo.services:\n            if service.type != 'Access':\n                continue\n            consumer_provider_tuple = keeper.escrow_access_secretstore_template.get_agreement_data(\n                agreement_id)\n            if not consumer_provider_tuple:\n                continue\n            consumer, provider = consumer_provider_tuple\n            did = ddo.did\n            service_agreement = ServiceAgreement.from_service_dict(service.as_dictionary())\n            condition_ids = service_agreement.generate_agreement_condition_ids(\n                agreement_id, did, consumer, provider, keeper)\n            if actor_type == 'consumer':\n                assert account.address == consumer\n                process_agreement_events_consumer(\n                    provider, agreement_id, did, service_agreement,\n                    price, account, condition_ids, None)\n            else:\n                assert account.address == provider\n                process_agreement_events_publisher(\n                    account, agreement_id, did, service_agreement,\n                    price, consumer, condition_ids)",
    "docstring": "Iterates over pending service agreements recorded in the local storage,\n    fetches their service definitions, and subscribes to service agreement events.\n\n    :param storage_path: storage path for the internal db, str\n    :param account:\n    :param actor_type:\n    :param did_resolver_fn:\n    :return:"
  },
  {
    "code": "def unfollow(self, login):\n        resp = False\n        if login:\n            url = self._build_url('user', 'following', login)\n            resp = self._boolean(self._delete(url), 204, 404)\n        return resp",
    "docstring": "Make the authenticated user stop following login\n\n        :param str login: (required)\n        :returns: bool"
  },
  {
    "code": "def _passes_cortex_depth(line, min_depth):\n    parts = line.split(\"\\t\")\n    cov_index = parts[8].split(\":\").index(\"COV\")\n    passes_depth = False\n    for gt in parts[9:]:\n        cur_cov = gt.split(\":\")[cov_index]\n        cur_depth = sum(int(x) for x in cur_cov.split(\",\"))\n        if cur_depth >= min_depth:\n            passes_depth = True\n    return passes_depth",
    "docstring": "Do any genotypes in the cortex_var VCF line passes the minimum depth requirement?"
  },
  {
    "code": "def make_layer_stack(layers=gin.REQUIRED, num_layers=6):\n  return LayerStack([cls() for cls in layers] * num_layers)",
    "docstring": "Configurable layer stack.\n\n  Args:\n    layers: a list of subclasses of TransformerLayer\n    num_layers: an integer\n  Returns:\n    a LayerStack"
  },
  {
    "code": "def convert(cls, value, from_base, to_base):\n        return cls.convert_from_int(\n           cls.convert_to_int(value, from_base),\n           to_base\n        )",
    "docstring": "Convert value from a base to a base.\n\n        :param value: the value to convert\n        :type value: sequence of int\n        :param int from_base: base of value\n        :param int to_base: base of result\n        :returns: the conversion result\n        :rtype: list of int\n        :raises ConvertError: if from_base is less than 2\n        :raises ConvertError: if to_base is less than 2\n        :raises ConvertError: if elements in value outside bounds\n\n        Preconditions:\n          * all integers in value must be no less than 0\n          * from_base, to_base must be at least 2\n\n        Complexity: O(len(value))"
  },
  {
    "code": "def to_0d_object_array(value: Any) -> np.ndarray:\n    result = np.empty((), dtype=object)\n    result[()] = value\n    return result",
    "docstring": "Given a value, wrap it in a 0-D numpy.ndarray with dtype=object."
  },
  {
    "code": "def install(self, binder, module):\n        ModuleAdapter(module, self._injector).configure(binder)",
    "docstring": "Add another module's bindings to a binder."
  },
  {
    "code": "def crpss(self):\n        crps_f = self.crps()\n        crps_c = self.crps_climo()\n        return 1.0 - float(crps_f) / float(crps_c)",
    "docstring": "Calculate the continous ranked probability skill score from existing data."
  },
  {
    "code": "def console_get_default_background(con: tcod.console.Console) -> Color:\n    return Color._new_from_cdata(\n        lib.TCOD_console_get_default_background(_console(con))\n    )",
    "docstring": "Return this consoles default background color.\n\n    .. deprecated:: 8.5\n        Use :any:`Console.default_bg` instead."
  },
  {
    "code": "def AddComment(self, comment):\n    if not comment:\n      return\n    if not self.comment:\n      self.comment = comment\n    else:\n      self.comment = ''.join([self.comment, comment])",
    "docstring": "Adds a comment to the event tag.\n\n    Args:\n      comment (str): comment."
  },
  {
    "code": "def get_app_metadata(template_dict):\n    if SERVERLESS_REPO_APPLICATION in template_dict.get(METADATA, {}):\n        app_metadata_dict = template_dict.get(METADATA).get(SERVERLESS_REPO_APPLICATION)\n        return ApplicationMetadata(app_metadata_dict)\n    raise ApplicationMetadataNotFoundError(\n        error_message='missing {} section in template Metadata'.format(SERVERLESS_REPO_APPLICATION))",
    "docstring": "Get the application metadata from a SAM template.\n\n    :param template_dict: SAM template as a dictionary\n    :type template_dict: dict\n    :return: Application metadata as defined in the template\n    :rtype: ApplicationMetadata\n    :raises ApplicationMetadataNotFoundError"
  },
  {
    "code": "def _getJavaStorageLevel(self, storageLevel):\n        if not isinstance(storageLevel, StorageLevel):\n            raise Exception(\"storageLevel must be of type pyspark.StorageLevel\")\n        newStorageLevel = self._jvm.org.apache.spark.storage.StorageLevel\n        return newStorageLevel(storageLevel.useDisk,\n                               storageLevel.useMemory,\n                               storageLevel.useOffHeap,\n                               storageLevel.deserialized,\n                               storageLevel.replication)",
    "docstring": "Returns a Java StorageLevel based on a pyspark.StorageLevel."
  },
  {
    "code": "def condensed_coords(i, j, n):\n    if i == j or i >= n or j >= n or i < 0 or j < 0:\n        raise ValueError('invalid coordinates: %s, %s' % (i, j))\n    i, j = sorted([i, j])\n    x = i * ((2 * n) - i - 1) / 2\n    ix = x + j - i - 1\n    return int(ix)",
    "docstring": "Transform square distance matrix coordinates to the corresponding\n    index into a condensed, 1D form of the matrix.\n\n    Parameters\n    ----------\n    i : int\n        Row index.\n    j : int\n        Column index.\n    n : int\n        Size of the square matrix (length of first or second dimension).\n\n    Returns\n    -------\n    ix : int"
  },
  {
    "code": "def reversal_circuit(qubits: Qubits) -> Circuit:\n    N = len(qubits)\n    circ = Circuit()\n    for n in range(N // 2):\n        circ += SWAP(qubits[n], qubits[N-1-n])\n    return circ",
    "docstring": "Returns a circuit to reverse qubits"
  },
  {
    "code": "def get_keywords(self, entry):\n        keyword_objects = []\n        for keyword in entry.iterfind(\"./keyword\"):\n            identifier = keyword.get('id')\n            name = keyword.text\n            keyword_hash = hash(identifier)\n            if keyword_hash not in self.keywords:\n                self.keywords[keyword_hash] = models.Keyword(**{'identifier': identifier, 'name': name})\n            keyword_objects.append(self.keywords[keyword_hash])\n        return keyword_objects",
    "docstring": "get list of models.Keyword objects from XML node entry\n\n        :param entry: XML node entry\n        :return: list of :class:`pyuniprot.manager.models.Keyword` objects"
  },
  {
    "code": "def after_start_check(self):\n        try:\n            conn = HTTPConnection(self.host, self.port)\n            conn.request('HEAD', self.url.path)\n            status = str(conn.getresponse().status)\n            if status == self.status or self.status_re.match(status):\n                conn.close()\n                return True\n        except (HTTPException, socket.timeout, socket.error):\n            return False",
    "docstring": "Check if defined URL returns expected status to a HEAD request."
  },
  {
    "code": "def _apply_discrete_colormap(arr, cmap):\n    res = np.zeros((arr.shape[1], arr.shape[2], 3), dtype=np.uint8)\n    for k, v in cmap.items():\n        res[arr[0] == k] = v\n    return np.transpose(res, [2, 0, 1])",
    "docstring": "Apply discrete colormap.\n\n    Attributes\n    ----------\n    arr : numpy.ndarray\n        1D image array to convert.\n    color_map: dict\n        Discrete ColorMap dictionary\n        e.g:\n        {\n            1: [255, 255, 255],\n            2: [255, 0, 0]\n        }\n\n    Returns\n    -------\n    arr: numpy.ndarray"
  },
  {
    "code": "def interface(enode, portlbl, addr=None, up=None, shell=None):\n    assert portlbl\n    port = enode.ports[portlbl]\n    if addr is not None:\n        assert ip_interface(addr)\n        cmd = 'ip addr add {addr} dev {port}'.format(addr=addr, port=port)\n        response = enode(cmd, shell=shell)\n        assert not response\n    if up is not None:\n        cmd = 'ip link set dev {port} {state}'.format(\n            port=port, state='up' if up else 'down'\n        )\n        response = enode(cmd, shell=shell)\n        assert not response",
    "docstring": "Configure a interface.\n\n    All parameters left as ``None`` are ignored and thus no configuration\n    action is taken for that parameter (left \"as-is\").\n\n    :param enode: Engine node to communicate with.\n    :type enode: topology.platforms.base.BaseNode\n    :param str portlbl: Port label to configure. Port label will be mapped to\n     real port automatically.\n    :param str addr: IPv4 or IPv6 address to add to the interface:\n     - IPv4 address and netmask to assign to the interface in the form\n     ``'192.168.20.20/24'``.\n     - IPv6 address and subnets to assign to the interface in the form\n     ``'2001::1/120'``.\n    :param bool up: Bring up or down the interface.\n    :param str shell: Shell name to execute commands.\n     If ``None``, use the Engine Node default shell."
  },
  {
    "code": "def process_bind_param(self, value, dialect):\n        if self.__use_json(dialect) or value is None:\n            return value\n        return self.__json_codec.dumps(value, ensure_ascii=not self.__enforce_unicode)",
    "docstring": "Encode data, if required."
  },
  {
    "code": "def register_connection(self, alias, api_key, base_url, timeout=5):\n        if not base_url.endswith('/'):\n            base_url += '/'\n        self._connections[alias] = Connection(api_key, base_url, timeout)",
    "docstring": "Create and register a new connection.\n\n        :param alias:   The alias of the connection. If not changed with `switch_connection`,\n                        the connection with default 'alias' is used by the resources.\n        :param api_key: The private api key.\n        :param base_url: The api url including protocol, host, port (optional) and location.\n        :param timeout: The time in seconds to wait for 'connect' and 'read' respectively.\n                        Use a tuple to set these values separately or None to wait forever.\n        :return:"
  },
  {
    "code": "def makeAla(segID, N, CA, C, O, geo):\n    CA_CB_length=geo.CA_CB_length\n    C_CA_CB_angle=geo.C_CA_CB_angle\n    N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle\n    carbon_b= calculateCoordinates(N, C, CA, CA_CB_length, C_CA_CB_angle, N_C_CA_CB_diangle)\n    CB= Atom(\"CB\", carbon_b, 0.0 , 1.0, \" \",\" CB\", 0,\"C\")\n    res = Residue((' ', segID, ' '), \"ALA\", '    ')\n    res.add(N)\n    res.add(CA)\n    res.add(C)\n    res.add(O)\n    res.add(CB)\n    return res",
    "docstring": "Creates an Alanine residue"
  },
  {
    "code": "def get_status(self):\n        yield self._manager.poll_sensor(self._name)\n        raise Return(self._reading.status)",
    "docstring": "Get a fresh sensor status from the KATCP resource\n\n        Returns\n        -------\n        reply : tornado Future resolving with  :class:`KATCPSensorReading` object\n\n        Note\n        ----\n\n        As a side-effect this will update the reading stored in this object, and result in\n        registered listeners being called."
  },
  {
    "code": "def close(self, connection, reason='Closed via management api'):\n        close_payload = json.dumps({\n            'name': connection,\n            'reason': reason\n        })\n        connection = quote(connection, '')\n        return self.http_client.delete(API_CONNECTION % connection,\n                                       payload=close_payload,\n                                       headers={\n                                           'X-Reason': reason\n                                       })",
    "docstring": "Close Connection.\n\n        :param str connection: Connection name\n        :param str reason: Reason for closing connection.\n\n        :raises ApiError: Raises if the remote server encountered an error.\n        :raises ApiConnectionError: Raises if there was a connectivity issue.\n\n        :rtype: None"
  },
  {
    "code": "def db_create_table(self, table_name, columns):\n        formatted_columns = ''\n        for col in set(columns):\n            formatted_columns += '\"{}\" text, '.format(col.strip('\"').strip('\\''))\n        formatted_columns = formatted_columns.strip(', ')\n        create_table_sql = 'CREATE TABLE IF NOT EXISTS {} ({});'.format(\n            table_name, formatted_columns\n        )\n        try:\n            cr = self.db_conn.cursor()\n            cr.execute(create_table_sql)\n        except sqlite3.Error as e:\n            self.handle_error(e)",
    "docstring": "Create a temporary DB table.\n\n        Arguments:\n            table_name (str): The name of the table.\n            columns (list): List of columns to add to the DB."
  },
  {
    "code": "def get_attachment_types(self):\n        bika_setup_catalog = api.get_tool(\"bika_setup_catalog\")\n        attachment_types = bika_setup_catalog(portal_type='AttachmentType',\n                                              is_active=True,\n                                              sort_on=\"sortable_title\",\n                                              sort_order=\"ascending\")\n        return attachment_types",
    "docstring": "Returns a list of available attachment types"
  },
  {
    "code": "def listen(self, listener):\n        for message in listener.listen():\n            try:\n                data = json.loads(message['data'])\n                if data['event'] in ('canceled', 'lock_lost', 'put'):\n                    self.kill(data['jid'])\n            except:\n                logger.exception('Pubsub error')",
    "docstring": "Listen for events that affect our ownership of a job"
  },
  {
    "code": "def get_all(cls, include_disabled=True):\n        if cls == BaseAccount:\n            raise InquisitorError('get_all on BaseAccount is not supported')\n        account_type_id = db.AccountType.find_one(account_type=cls.account_type).account_type_id\n        qry = db.Account.order_by(desc(Account.enabled), Account.account_type_id, Account.account_name)\n        if not include_disabled:\n            qry = qry.filter(Account.enabled == 1)\n        accounts = qry.find(Account.account_type_id == account_type_id)\n        return {res.account_id: cls(res) for res in accounts}",
    "docstring": "Returns a list of all accounts of a given type\n\n        Args:\n            include_disabled (`bool`): Include disabled accounts. Default: `True`\n\n        Returns:\n            list of account objects"
  },
  {
    "code": "def derivativeZ(self,x,y,z):\n        xShift = self.lowerBound(y)\n        dfdz_out = self.func.derivativeZ(x-xShift,y,z)\n        return dfdz_out",
    "docstring": "Evaluate the first derivative with respect to z of the function at given\n        state space points.\n\n        Parameters\n        ----------\n        x : np.array\n             First input values.\n        y : np.array\n             Second input values; should be of same shape as x.\n        z : np.array\n             Third input values; should be of same shape as x.\n\n        Returns\n        -------\n        dfdz_out : np.array\n            First derivative of function with respect to the third input,\n            evaluated at (x,y,z), of same shape as inputs."
  },
  {
    "code": "def create_session(self, user_agent, remote_address, client_version):\n        self.session_counter += 1\n        self.sessions[self.session_counter] = session = self.session_class()\n        session.user_agent = user_agent\n        session.remote_address = remote_address\n        session.client_version = client_version\n        invoke_hooks(self.hooks, \"session_created\", self.session_counter)\n        return self.session_counter",
    "docstring": "Create a new session.\n\n        :param str user_agent: Client user agent\n        :param str remote_addr: Remote address of client\n        :param str client_version: Remote client version\n        :return: The new session id\n        :rtype: int"
  },
  {
    "code": "def parse(self, rrstr):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('PL record already initialized!')\n        (su_len, su_entry_version_unused, parent_log_block_num_le, parent_log_block_num_be) = struct.unpack_from('=BBLL', rrstr[:12], 2)\n        if su_len != RRPLRecord.length():\n            raise pycdlibexception.PyCdlibInvalidISO('Invalid length on rock ridge extension')\n        if parent_log_block_num_le != utils.swab_32bit(parent_log_block_num_be):\n            raise pycdlibexception.PyCdlibInvalidISO('Little endian block num does not equal big endian; corrupt ISO')\n        self.parent_log_block_num = parent_log_block_num_le\n        self._initialized = True",
    "docstring": "Parse a Rock Ridge Parent Link record out of a string.\n\n        Parameters:\n         rrstr - The string to parse the record out of.\n        Returns:\n         Nothing."
  },
  {
    "code": "def describe_api_stage(restApiId, stageName, region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        stage = conn.get_stage(restApiId=restApiId, stageName=stageName)\n        return {'stage': _convert_datetime_str(stage)}\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Get API stage for a given apiID and stage name\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_apigateway.describe_api_stage restApiId stageName"
  },
  {
    "code": "def should_trigger(self, dt):\n        return self.composer(\n            self.first.should_trigger,\n            self.second.should_trigger,\n            dt\n        )",
    "docstring": "Composes the two rules with a lazy composer."
  },
  {
    "code": "def get(self, *args, **kwargs):\n        self.before_get(args, kwargs)\n        qs = QSManager(request.args, self.schema)\n        obj = self.get_object(kwargs, qs)\n        self.before_marshmallow(args, kwargs)\n        schema = compute_schema(self.schema,\n                                getattr(self, 'get_schema_kwargs', dict()),\n                                qs,\n                                qs.include)\n        result = schema.dump(obj).data\n        final_result = self.after_get(result)\n        return final_result",
    "docstring": "Get object details"
  },
  {
    "code": "def items(self, *keys):\n        if keys:\n            d = []\n            for key in keys:\n                try:\n                    i = self.index(key)\n                except KeyError:\n                    d.append((key, None))\n                else:\n                    d.append((self.__keys[i], self[i]))\n            return d\n        return list((self.__keys[i], super(Record, self).__getitem__(i)) for i in range(len(self)))",
    "docstring": "Return the fields of the record as a list of key and value tuples\n\n        :return:"
  },
  {
    "code": "def clip_or_fit_solutions(self, pop, idx):\n        for k in idx:\n            self.repair_genotype(pop[k])",
    "docstring": "make sure that solutions fit to sample distribution, this interface will probably change.\n\n        In particular the frequency of long vectors appearing in pop[idx] - self.mean is limited."
  },
  {
    "code": "def get_list(\n        self,\n        search='',\n        start=0,\n        limit=0,\n        order_by='',\n        order_by_dir='ASC',\n        published_only=False,\n        minimal=False\n    ):\n        parameters = {}\n        args = ['search', 'start', 'limit', 'minimal']\n        for arg in args:\n            if arg in locals() and locals()[arg]:\n                parameters[arg] = locals()[arg]\n        if order_by:\n            parameters['orderBy'] = order_by\n        if order_by_dir:\n            parameters['orderByDir'] = order_by_dir\n        if published_only:\n            parameters['publishedOnly'] = 'true'\n        response = self._client.session.get(\n            self.endpoint_url, params=parameters\n        )\n        return self.process_response(response)",
    "docstring": "Get a list of items\n\n        :param search: str\n        :param start: int\n        :param limit: int\n        :param order_by: str\n        :param order_by_dir: str\n        :param published_only: bool\n        :param minimal: bool\n        :return: dict|str"
  },
  {
    "code": "def Group(expressions, final_function, inbetweens, name=\"\"):\n    lengths = []\n    functions = []\n    regex = \"\"\n    i = 0\n    for expression in expressions:\n        regex += inbetweens[i]\n        regex += \"(?:\" + expression.regex + \")\"\n        lengths.append(sum(expression.group_lengths))\n        functions.append(expression.run)\n        i += 1\n    regex += inbetweens[i]\n    return Expression(regex, functions, lengths, final_function, name)",
    "docstring": "Group expressions together with ``inbetweens`` and with the output of a ``final_functions``."
  },
  {
    "code": "def from_array(array):\n        if array is None or not array:\n            return None\n        assert_type_or_raise(array, dict, parameter_name=\"array\")\n        from pytgbot.api_types.receivable.media import Location\n        from pytgbot.api_types.receivable.peer import User\n        data = {}\n        data['id'] = u(array.get('id'))\n        data['from_peer'] = User.from_array(array.get('from'))\n        data['query'] = u(array.get('query'))\n        data['offset'] = u(array.get('offset'))\n        data['location'] = Location.from_array(array.get('location')) if array.get('location') is not None else None\n        data['_raw'] = array\n        return InlineQuery(**data)",
    "docstring": "Deserialize a new InlineQuery from a given dictionary.\n\n        :return: new InlineQuery instance.\n        :rtype: InlineQuery"
  },
  {
    "code": "def do(stream, action, key, default=None, dump=yaml_dump,\n       loader=ShyamlSafeLoader):\n    at_least_one_content = False\n    for content in yaml.load_all(stream, Loader=loader):\n        at_least_one_content = True\n        value = traverse(content, key, default=default)\n        yield act(action, value, dump=dump)\n    if at_least_one_content is False:\n        value = traverse(None, key, default=default)\n        yield act(action, value, dump=dump)",
    "docstring": "Return string representations of target value in stream YAML\n\n    The key is used for traversal of the YAML structure to target\n    the value that will be dumped.\n\n    :param stream:  file like input yaml content\n    :param action:  string identifying one of the possible supported actions\n    :param key:     string dotted expression to traverse yaml input\n    :param default: optional default value in case of missing end value when\n                    traversing input yaml.  (default is ``None``)\n    :param dump:    callable that will be given python objet to dump in yaml\n                    (default is ``yaml_dump``)\n    :param loader:  PyYAML's *Loader subclass to parse YAML\n                    (default is ShyamlSafeLoader)\n    :return:        generator of string representation of target value per\n                    YAML docs in the given stream.\n\n    :raises ActionTypeError: when there's a type mismatch between the\n        action selected and the type of the targetted value.\n        (ie: action 'key-values' on non-struct)\n    :raises InvalidAction: when selected action is not a recognised valid\n        action identifier.\n    :raises InvalidPath: upon inexistent content when traversing YAML\n        input following the key specification."
  },
  {
    "code": "def get_lang_tags(index_page):\n    dom = dhtmlparser.parseString(index_page)\n    lang_tags = [\n        get_html_lang_tags(dom),\n        get_dc_lang_tags(dom),\n        [detect_language(dom)],\n        get_html_tag_lang_params(dom),\n    ]\n    return list(sorted(set(\n        SourceString(normalize(lang), source=lang.source)\n        for lang in sum(lang_tags, [])\n    )))",
    "docstring": "Collect informations about language of the page from HTML and Dublin core\n    tags and langdetect guesses.\n\n    Args:\n        index_page (str): HTML content of the page you wish to analyze.\n\n    Returns:\n        list: List of :class:`.SourceString` objects."
  },
  {
    "code": "def apply_pre_filters(instance, html):\n    for post_func in appsettings.PRE_FILTER_FUNCTIONS:\n        html = post_func(instance, html)\n    return html",
    "docstring": "Perform optimizations in the HTML source code.\n\n    :type instance: fluent_contents.models.ContentItem\n    :raise ValidationError: when one of the filters detects a problem."
  },
  {
    "code": "def init_edge_number(self) -> int:\n        return len(frozenset(frozenset(edge) for edge in self.initial_edges()))",
    "docstring": "Return the number of edges present in the non-compressed graph"
  },
  {
    "code": "def generate_trajectory(group_membership, num_levels=4):\n    delta = compute_delta(num_levels)\n    num_params = group_membership.shape[0]\n    num_groups = group_membership.shape[1]\n    B = np.tril(np.ones([num_groups + 1, num_groups],\n                        dtype=int), -1)\n    P_star = generate_p_star(num_groups)\n    J = np.ones((num_groups + 1, num_params))\n    D_star = np.diag([rd.choice([-1, 1]) for _ in range(num_params)])\n    x_star = generate_x_star(num_params, num_levels)\n    B_star = compute_b_star(J, x_star, delta, B,\n                            group_membership, P_star, D_star)\n    return B_star",
    "docstring": "Return a single trajectory\n\n    Return a single trajectory of size :math:`(g+1)`-by-:math:`k`\n    where :math:`g` is the number of groups,\n    and :math:`k` is the number of factors,\n    both implied by the dimensions of `group_membership`\n\n    Arguments\n    ---------\n    group_membership : np.ndarray\n        a k-by-g matrix which notes factor membership of groups\n    num_levels : int, default=4\n        The number of levels in the grid\n\n    Returns\n    -------\n    np.ndarray"
  },
  {
    "code": "def try_read(self, address, size):\n        value = 0x0\n        for i in range(0, size):\n            addr = address + i\n            if addr in self._memory:\n                value |= self._read_byte(addr) << (i * 8)\n            else:\n                return False, None\n        return True, value",
    "docstring": "Try to read memory content at specified address.\n\n        If any location was not written before, it returns a tuple\n        (False, None). Otherwise, it returns (True, memory content)."
  },
  {
    "code": "def edit_command(self, payload):\n        key = payload['key']\n        command = payload['command']\n        if self.queue[key]:\n            if self.queue[key]['status'] in ['queued', 'stashed']:\n                self.queue[key]['command'] = command\n                answer = {'message': 'Command updated', 'status': 'error'}\n            else:\n                answer = {'message': \"Entry is not 'queued' or 'stashed'\",\n                          'status': 'error'}\n        else:\n            answer = {'message': 'No entry with this key', 'status': 'error'}\n        return answer",
    "docstring": "Edit the command of a specific entry."
  },
  {
    "code": "def _cast_page(val):\n        try:\n            val = int(val)\n            if val < 0:\n                raise ValueError\n            return val\n        except (TypeError, ValueError):\n            raise ValueError",
    "docstring": "Convert the page limit & offset into int's & type check"
  },
  {
    "code": "def get_agent(self):\n        agent_id = self.get_agent_id()\n        return Agent(identifier=agent_id.identifier,\n                     namespace=agent_id.namespace,\n                     authority=agent_id.authority)",
    "docstring": "Gets the ``Agent`` identified in this authentication credential.\n\n        :return: the ``Agent``\n        :rtype: ``osid.authentication.Agent``\n        :raise: ``OperationFailed`` -- unable to complete request\n\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def analyze(self,\n                features,\n                text=None,\n                html=None,\n                url=None,\n                clean=None,\n                xpath=None,\n                fallback_to_raw=None,\n                return_analyzed_text=None,\n                language=None,\n                limit_text_characters=None,\n                **kwargs):\n        if features is None:\n            raise ValueError('features must be provided')\n        features = self._convert_model(features, Features)\n        headers = {}\n        if 'headers' in kwargs:\n            headers.update(kwargs.get('headers'))\n        sdk_headers = get_sdk_headers('natural-language-understanding', 'V1',\n                                      'analyze')\n        headers.update(sdk_headers)\n        params = {'version': self.version}\n        data = {\n            'features': features,\n            'text': text,\n            'html': html,\n            'url': url,\n            'clean': clean,\n            'xpath': xpath,\n            'fallback_to_raw': fallback_to_raw,\n            'return_analyzed_text': return_analyzed_text,\n            'language': language,\n            'limit_text_characters': limit_text_characters\n        }\n        url = '/v1/analyze'\n        response = self.request(\n            method='POST',\n            url=url,\n            headers=headers,\n            params=params,\n            json=data,\n            accept_json=True)\n        return response",
    "docstring": "Analyze text.\n\n        Analyzes text, HTML, or a public webpage for the following features:\n        - Categories\n        - Concepts\n        - Emotion\n        - Entities\n        - Keywords\n        - Metadata\n        - Relations\n        - Semantic roles\n        - Sentiment\n        - Syntax (Experimental).\n\n        :param Features features: Specific features to analyze the document for.\n        :param str text: The plain text to analyze. One of the `text`, `html`, or `url`\n        parameters is required.\n        :param str html: The HTML file to analyze. One of the `text`, `html`, or `url`\n        parameters is required.\n        :param str url: The webpage to analyze. One of the `text`, `html`, or `url`\n        parameters is required.\n        :param bool clean: Set this to `false` to disable webpage cleaning. To learn more\n        about webpage cleaning, see the [Analyzing\n        webpages](https://cloud.ibm.com/docs/services/natural-language-understanding/analyzing-webpages.html)\n        documentation.\n        :param str xpath: An [XPath\n        query](https://cloud.ibm.com/docs/services/natural-language-understanding/analyzing-webpages.html#xpath)\n        to perform on `html` or `url` input. Results of the query will be appended to the\n        cleaned webpage text before it is analyzed. To analyze only the results of the\n        XPath query, set the `clean` parameter to `false`.\n        :param bool fallback_to_raw: Whether to use raw HTML content if text cleaning\n        fails.\n        :param bool return_analyzed_text: Whether or not to return the analyzed text.\n        :param str language: ISO 639-1 code that specifies the language of your text. This\n        overrides automatic language detection. Language support differs depending on the\n        features you include in your analysis. See [Language\n        support](https://www.bluemix.net/docs/services/natural-language-understanding/language-support.html)\n        for more information.\n        :param int limit_text_characters: Sets the maximum number of characters that are\n        processed by the service.\n        :param dict headers: A `dict` containing the request headers\n        :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n        :rtype: DetailedResponse"
  },
  {
    "code": "def is_valid_query(self, query):\n        if not query:\n            return False\n        if len(query) < self.get_query_size_min():\n            return False\n        return True",
    "docstring": "Return True if the search query is valid.\n\n        e.g.:\n        * not empty,\n        * not too short,"
  },
  {
    "code": "def nested_insert(self, item_list):\n        if len(item_list) == 1:\n            self[item_list[0]] = LIVVDict()\n        elif len(item_list) > 1:\n            if item_list[0] not in self:\n                self[item_list[0]] = LIVVDict()\n            self[item_list[0]].nested_insert(item_list[1:])",
    "docstring": "Create a series of nested LIVVDicts given a list"
  },
  {
    "code": "def _update(self, datapoints):\n        if len(datapoints) == 1:\n            timestamp, value = datapoints[0]\n            whisper.update(self.path, value, timestamp)\n        else:\n            whisper.update_many(self.path, datapoints)",
    "docstring": "This method store in the datapoints in the current database.\n\n            :datapoints: is a list of tupple with the epoch timestamp and value\n                 [(1368977629,10)]"
  },
  {
    "code": "def get_found_includes(self, env, scanner, path):\n        memo_key = (id(env), id(scanner), path)\n        try:\n            memo_dict = self._memo['get_found_includes']\n        except KeyError:\n            memo_dict = {}\n            self._memo['get_found_includes'] = memo_dict\n        else:\n            try:\n                return memo_dict[memo_key]\n            except KeyError:\n                pass\n        if scanner:\n            result = [n.disambiguate() for n in scanner(self, env, path)]\n        else:\n            result = []\n        memo_dict[memo_key] = result\n        return result",
    "docstring": "Return the included implicit dependencies in this file.\n        Cache results so we only scan the file once per path\n        regardless of how many times this information is requested."
  },
  {
    "code": "def gzip_file(self, target_path, html):\n        logger.debug(\"Gzipping to {}{}\".format(self.fs_name, target_path))\n        data_buffer = six.BytesIO()\n        kwargs = dict(\n            filename=path.basename(target_path),\n            mode='wb',\n            fileobj=data_buffer\n        )\n        if float(sys.version[:3]) >= 2.7:\n            kwargs['mtime'] = 0\n        with gzip.GzipFile(**kwargs) as f:\n            f.write(six.binary_type(html))\n        with self.fs.open(smart_text(target_path), 'wb') as outfile:\n            outfile.write(data_buffer.getvalue())\n            outfile.close()",
    "docstring": "Zips up the provided HTML as a companion for the provided path.\n\n        Intended to take advantage of the peculiarities of\n        Amazon S3's GZIP service.\n\n        mtime, an option that writes a timestamp to the output file\n        is set to 0, to avoid having s3cmd do unnecessary uploads because\n        of differences in the timestamp"
  },
  {
    "code": "def start(self):\r\n        self.update_device_info()\r\n        self.get_device_status(0)\n        self.hook()\r\n        self.thread = threading.Thread(target=self._run)\r\n        self.thread.start()\r\n        self.running = True",
    "docstring": "start running in background."
  },
  {
    "code": "def withdict(parser, token):\n    bits = token.split_contents()\n    if len(bits) != 2:\n        raise TemplateSyntaxError(\"{% withdict %} expects one argument\")\n    nodelist = parser.parse(('endwithdict',))\n    parser.delete_first_token()\n    return WithDictNode(\n        nodelist=nodelist,\n        context_expr=parser.compile_filter(bits[1])\n    )",
    "docstring": "Take a complete context dict as extra layer."
  },
  {
    "code": "def run_hmmbuild(self):\n        for alignment in self.alignment_list:\n            print 'building Hmm for', alignment\n            alignment_full_path = self.alignment_dir + alignment\n            query_name = alignment.split(\"_\")[0]\n            self.query_names.append(query_name)\n            new_hmm= self.hmm_dir + query_name + \".hmm\"\n            hmmbuild_output = subprocess.call([\"hmmbuild\", new_hmm,\n             alignment_full_path])\n        print 'hhbuild complete for', self.query_names",
    "docstring": "Generate hmm with hhbuild,\n        output to file. Also stores query names."
  },
  {
    "code": "def merge(self, resource_type, resource_properties):\n        if resource_type not in self.template_globals:\n            return resource_properties\n        global_props = self.template_globals[resource_type]\n        return global_props.merge(resource_properties)",
    "docstring": "Adds global properties to the resource, if necessary. This method is a no-op if there are no global properties\n        for this resource type\n\n        :param string resource_type: Type of the resource (Ex: AWS::Serverless::Function)\n        :param dict resource_properties: Properties of the resource that need to be merged\n        :return dict: Merged properties of the resource"
  },
  {
    "code": "def _import_model(models, crumbs):\n    logger_jsons.info(\"enter import_model\".format(crumbs))\n    _models = OrderedDict()\n    try:\n        for _idx, model in enumerate(models):\n            if \"summaryTable\" in model:\n                model[\"summaryTable\"] = _idx_table_by_name(model[\"summaryTable\"], \"{}{}{}\".format(crumbs, _idx, \"summary\"))\n            if \"ensembleTable\" in model:\n                model[\"ensembleTable\"] = _idx_table_by_name(model[\"ensembleTable\"], \"{}{}{}\".format(crumbs, _idx, \"ensemble\"))\n            if \"distributionTable\" in model:\n                model[\"distributionTable\"] = _idx_table_by_name(model[\"distributionTable\"], \"{}{}{}\".format(crumbs, _idx, \"distribution\"))\n            _table_name = \"{}{}\".format(crumbs, _idx)\n            _models[_table_name] = model\n    except Exception as e:\n        logger_jsons.error(\"import_model: {}\".format(e))\n        print(\"Error: import_model: {}\".format(e))\n    logger_jsons.info(\"exit import_model: {}\".format(crumbs))\n    return _models",
    "docstring": "Change the nested items of the paleoModel data. Overwrite the data in-place.\n\n    :param list models: Metadata\n    :param str crumbs: Crumbs\n    :return dict _models: Metadata"
  },
  {
    "code": "def get(path):\n    file_path = __get_docker_file_path(path)\n    if file_path is None:\n        return __standardize_result(False,\n                                    'Path {} is not present'.format(path),\n                                    None, None)\n    salt_result = __read_docker_compose_file(file_path)\n    if not salt_result['status']:\n        return salt_result\n    project = __load_project(path)\n    if isinstance(project, dict):\n        salt_result['return']['valid'] = False\n    else:\n        salt_result['return']['valid'] = True\n    return salt_result",
    "docstring": "Get the content of the docker-compose file into a directory\n\n    path\n        Path where the docker-compose file is stored on the server\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion dockercompose.get /path/where/docker-compose/stored"
  },
  {
    "code": "def set_ptr(self, ptr):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('Directory Record not yet initialized')\n        self.ptr = ptr",
    "docstring": "A method to set the Path Table Record associated with this Directory\n        Record.\n\n        Parameters:\n         ptr - The path table record to associate with this Directory Record.\n        Returns:\n         Nothing."
  },
  {
    "code": "def checkPos(self):\n        soup = BeautifulSoup(self.css1(path['movs-table']).html, 'html.parser')\n        poss = []\n        for label in soup.find_all(\"tr\"):\n            pos_id = label['id']\n            pos_list = [x for x in self.positions if x.id == pos_id]\n            if pos_list:\n                pos = pos_list[0]\n                pos.update(label)\n            else:\n                pos = self.new_pos(label)\n            pos.get_gain()\n            poss.append(pos)\n        self.positions.clear()\n        self.positions.extend(poss)\n        logger.debug(\"%d positions update\" % len(poss))\n        return self.positions",
    "docstring": "check all positions"
  },
  {
    "code": "def add(self, callback_type, callback):\n        with self.lock:\n            self.callbacks[callback_type].append(callback)",
    "docstring": "Add a new listener"
  },
  {
    "code": "def addItemTag(self, item, tag):\n        if self.inItemTagTransaction:\n            if not tag in self.addTagBacklog:\n                self.addTagBacklog[tag] = []                \n            self.addTagBacklog[tag].append({'i': item.id, 's': item.parent.id})\n            return \"OK\"\n        else:\n            return self._modifyItemTag(item.id, 'a', tag)",
    "docstring": "Add a tag to an individal item.\n\n        tag string must be in form \"user/-/label/[tag]\""
  },
  {
    "code": "def authorization_error_class(response):\n    message = response.headers.get(\"www-authenticate\")\n    if message:\n        error = message.replace('\"', \"\").rsplit(\"=\", 1)[1]\n    else:\n        error = response.status_code\n    return _auth_error_mapping[error](response)",
    "docstring": "Return an exception instance that maps to the OAuth Error.\n\n    :param response: The HTTP response containing a www-authenticate error."
  },
  {
    "code": "def list_user_permissions(name, runas=None):\n    if runas is None and not salt.utils.platform.is_windows():\n        runas = salt.utils.user.get_user()\n    res = __salt__['cmd.run_all'](\n        [RABBITMQCTL, 'list_user_permissions', name, '-q'],\n        reset_system_locale=False,\n        runas=runas,\n        python_shell=False)\n    return _output_to_dict(res)",
    "docstring": "List permissions for a user via rabbitmqctl list_user_permissions\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rabbitmq.list_user_permissions user"
  },
  {
    "code": "def _DoubleDecoder():\n  local_unpack = struct.unpack\n  def InnerDecode(buffer, pos):\n    new_pos = pos + 8\n    double_bytes = buffer[pos:new_pos]\n    if ((double_bytes[7:8] in b'\\x7F\\xFF')\n        and (double_bytes[6:7] >= b'\\xF0')\n        and (double_bytes[0:7] != b'\\x00\\x00\\x00\\x00\\x00\\x00\\xF0')):\n      return (_NAN, new_pos)\n    result = local_unpack('<d', double_bytes)[0]\n    return (result, new_pos)\n  return _SimpleDecoder(wire_format.WIRETYPE_FIXED64, InnerDecode)",
    "docstring": "Returns a decoder for a double field.\n\n  This code works around a bug in struct.unpack for not-a-number."
  },
  {
    "code": "def is_allowed_view(perm):\n    for view in ACL_EXCLUDED_VIEWS:\n        module, separator, view_name = view.partition('*')\n        if view and perm.startswith(module):\n            return False\n    for view in ACL_ALLOWED_VIEWS:\n        module, separator, view_name = view.partition('*')\n        if separator and not module and not view_name:\n            return True\n        elif separator and module and perm.startswith(module):\n            return True\n        elif separator and view_name and perm.endswith(view_name):\n            return True\n        elif not separator and view == perm:\n            return True\n    return False",
    "docstring": "Check if permission is in acl list."
  },
  {
    "code": "def state_machine_selection_changed(self, state_machine_m, signal_name, signal_msg):\n        if self.CORE_ELEMENT_CLASS in signal_msg.arg.affected_core_element_classes:\n            self.update_selection_sm_prior()",
    "docstring": "Notify tree view about state machine selection"
  },
  {
    "code": "def check_origin(self, origin: str) -> bool:\n        parsed_origin = urlparse(origin)\n        origin = parsed_origin.netloc\n        origin = origin.lower()\n        host = self.request.headers.get(\"Host\")\n        return origin == host",
    "docstring": "Override to enable support for allowing alternate origins.\n\n        The ``origin`` argument is the value of the ``Origin`` HTTP\n        header, the url responsible for initiating this request.  This\n        method is not called for clients that do not send this header;\n        such requests are always allowed (because all browsers that\n        implement WebSockets support this header, and non-browser\n        clients do not have the same cross-site security concerns).\n\n        Should return ``True`` to accept the request or ``False`` to\n        reject it. By default, rejects all requests with an origin on\n        a host other than this one.\n\n        This is a security protection against cross site scripting attacks on\n        browsers, since WebSockets are allowed to bypass the usual same-origin\n        policies and don't use CORS headers.\n\n        .. warning::\n\n           This is an important security measure; don't disable it\n           without understanding the security implications. In\n           particular, if your authentication is cookie-based, you\n           must either restrict the origins allowed by\n           ``check_origin()`` or implement your own XSRF-like\n           protection for websocket connections. See `these\n           <https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html>`_\n           `articles\n           <https://devcenter.heroku.com/articles/websocket-security>`_\n           for more.\n\n        To accept all cross-origin traffic (which was the default prior to\n        Tornado 4.0), simply override this method to always return ``True``::\n\n            def check_origin(self, origin):\n                return True\n\n        To allow connections from any subdomain of your site, you might\n        do something like::\n\n            def check_origin(self, origin):\n                parsed_origin = urllib.parse.urlparse(origin)\n                return parsed_origin.netloc.endswith(\".mydomain.com\")\n\n        .. versionadded:: 4.0"
  },
  {
    "code": "def save_signal(self,filename=None):\n        if filename is None:\n            filename = os.path.join(self.folder,'trsig.pkl')\n        self.trsig.save(filename)",
    "docstring": "Saves TransitSignal.\n\n        Calls :func:`TransitSignal.save`; default filename is\n        ``trsig.pkl`` in ``self.folder``."
  },
  {
    "code": "def activateAaPdpContextReject(ProtocolConfigurationOptions_presence=0):\n    a = TpPd(pd=0x8)\n    b = MessageType(mesType=0x52)\n    c = SmCause()\n    packet = a / b / c\n    if ProtocolConfigurationOptions_presence is 1:\n        d = ProtocolConfigurationOptions(ieiPCO=0x27)\n        packet = packet / d\n    return packet",
    "docstring": "ACTIVATE AA PDP CONTEXT REJECT Section 9.5.12"
  },
  {
    "code": "def get_userinfo(self, access_token, id_token, payload):\n        user_response = requests.get(\n            self.OIDC_OP_USER_ENDPOINT,\n            headers={\n                'Authorization': 'Bearer {0}'.format(access_token)\n            },\n            verify=self.get_settings('OIDC_VERIFY_SSL', True))\n        user_response.raise_for_status()\n        return user_response.json()",
    "docstring": "Return user details dictionary. The id_token and payload are not used in\n        the default implementation, but may be used when overriding this method"
  },
  {
    "code": "def transformToNative(obj):\n        if obj.isNative:\n            return obj\n        obj.isNative = True\n        obj.value = splitFields(obj.value)\n        return obj",
    "docstring": "Turn obj.value into a list."
  },
  {
    "code": "def calc(path):\n    total = 0\n    err = None\n    if os.path.isdir(path):\n        try:\n            for entry in os.scandir(path):\n                try:\n                    is_dir = entry.is_dir(follow_symlinks=False)\n                except (PermissionError, FileNotFoundError):\n                    err = \"!\"\n                    return total, err\n                if is_dir:\n                    result = calc(entry.path)\n                    total += result[0]\n                    err = result[1]\n                    if err:\n                        return total, err\n                else:\n                    try:\n                        total += entry.stat(follow_symlinks=False).st_size\n                    except (PermissionError, FileNotFoundError):\n                        err = \"!\"\n                        return total, err\n        except (PermissionError, FileNotFoundError):\n            err = \"!\"\n            return total, err\n    else:\n        total += os.path.getsize(path)\n    return total, err",
    "docstring": "Takes a path as an argument and returns the total size in bytes of the file\n    or directory. If the path is a directory the size will be calculated\n    recursively."
  },
  {
    "code": "def _message_received(self, msg):\n        msg = Message.from_node(msg)\n        return self.dispatch(msg)",
    "docstring": "Callback run when an XMPP Message is reveived.\n        This callback delivers the message to every behaviour\n        that is waiting for it. First, the aioxmpp.Message is\n        converted to spade.message.Message\n\n        Args:\n          msg (aioxmpp.Messagge): the message just received.\n\n        Returns:\n            list(asyncio.Future): a list of futures of the append of the message at each matched behaviour."
  },
  {
    "code": "def get_host_lock(url):\n    hostname = get_hostname(url)\n    return host_locks.setdefault(hostname, threading.Lock())",
    "docstring": "Get lock object for given URL host."
  },
  {
    "code": "def run(hsm, aead_backend, args):\n    write_pid_file(args.pid_file)\n    server_address = (args.listen_addr, args.listen_port)\n    httpd = YHSM_KSMServer(server_address,\n                           partial(YHSM_KSMRequestHandler, hsm, aead_backend, args))\n    my_log_message(args.debug or args.verbose, syslog.LOG_INFO,\n                   \"Serving requests to 'http://%s:%s%s' with key handle(s) %s (YubiHSM: '%s', AEADs in '%s', DB in '%s')\"\n                   % (args.listen_addr, args.listen_port, args.serve_url, args.key_handles, args.device, args.aead_dir, args.db_url))\n    httpd.serve_forever()",
    "docstring": "Start a BaseHTTPServer.HTTPServer and serve requests forever."
  },
  {
    "code": "def rwishart_cov(n, C):\n    p = np.shape(C)[0]\n    sig = np.linalg.cholesky(C)\n    if n <= (p-1):\n        raise ValueError('Wishart parameter n must be greater '\n                         'than size of matrix.')\n    norms = np.random.normal(size=(p * (p - 1)) // 2)\n    chi_sqs = np.sqrt(np.random.chisquare(df=np.arange(n, n - p, -1)))\n    A = flib.expand_triangular(chi_sqs, norms)\n    flib.dtrmm_wrap(sig, A, side='L', uplo='L', transa='N', alpha=1.)\n    w = np.asmatrix(np.dot(A, A.T))\n    flib.symmetrize(w)\n    return w",
    "docstring": "Return a Wishart random matrix.\n\n    :Parameters:\n      n : int\n        Degrees of freedom, > 0.\n      C : matrix\n        Symmetric and positive definite"
  },
  {
    "code": "def _parse_error(self, error):\n        error = str(error)\n        m = re.match(r'(\\d+)\\((\\d+)\\)\\s*:\\s(.*)', error)\n        if m:\n            return int(m.group(2)), m.group(3)\n        m = re.match(r'ERROR:\\s(\\d+):(\\d+):\\s(.*)', error)\n        if m:\n            return int(m.group(2)), m.group(3)\n        m = re.match(r'(\\d+):(\\d+)\\((\\d+)\\):\\s(.*)', error)\n        if m:\n            return int(m.group(2)), m.group(4)\n        return None, error",
    "docstring": "Parses a single GLSL error and extracts the linenr and description\n        Other GLIR implementations may omit this."
  },
  {
    "code": "def srandmember(self, name, number=None):\n        with self.pipe as pipe:\n            f = Future()\n            res = pipe.srandmember(self.redis_key(name), number=number)\n            def cb():\n                if number is None:\n                    f.set(self.valueparse.decode(res.result))\n                else:\n                    f.set([self.valueparse.decode(v) for v in res.result])\n            pipe.on_execute(cb)\n            return f",
    "docstring": "Return a random member of the set.\n\n        :param name: str     the name of the redis key\n        :return: Future()"
  },
  {
    "code": "def modify(self, service_name, json, **kwargs):\n        return self._send(requests.put, service_name, json, **kwargs)",
    "docstring": "Modify an AppNexus object"
  },
  {
    "code": "def get_agents(self):\n        if self.retrieved:\n            raise errors.IllegalState('List has already been retrieved.')\n        self.retrieved = True\n        return objects.AgentList(self._results, runtime=self._runtime)",
    "docstring": "Gets the agent list resulting from the search.\n\n        return: (osid.authentication.AgentList) - the agent list\n        raise:  IllegalState - list already retrieved\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def ipmi_method(self, command):       \n        ipmi = ipmitool(self.console, self.password, self.username)\n        if command == \"reboot\":\n            self.ipmi_method(command=\"status\")\n            if self.output == \"Chassis Power is off\":\n                command = \"on\"\n        ipmi.execute(self.ipmi_map[command])\n        if ipmi.status:\n            self.error = ipmi.error.strip()\n        else:\n            self.output = ipmi.output.strip()        \n        self.status = ipmi.status",
    "docstring": "Use ipmitool to run commands with ipmi protocol"
  },
  {
    "code": "def overwrite_line(self, n, text):\n        with self._moveback(n):\n            self.term.stream.write(text)",
    "docstring": "Move back N lines and overwrite line with `text`."
  },
  {
    "code": "def plot_evec(fignum, Vs, symsize, title):\n    plt.figure(num=fignum)\n    plt.text(-1.1, 1.15, title)\n    symb, symkey = ['s', 'v', 'o'], 0\n    col = ['r', 'b', 'k']\n    for VEC in range(3):\n        X, Y = [], []\n        for Vdirs in Vs:\n            XY = pmag.dimap(Vdirs[VEC][0], Vdirs[VEC][1])\n            X.append(XY[0])\n            Y.append(XY[1])\n        plt.scatter(X, Y, s=symsize,\n                    marker=symb[VEC], c=col[VEC], edgecolors='none')\n    plt.axis(\"equal\")",
    "docstring": "plots eigenvector directions of S vectors\n\n    Paramters\n    ________\n    fignum : matplotlib figure number\n    Vs : nested list of eigenvectors\n    symsize : size in pts for symbol\n    title : title for plot"
  },
  {
    "code": "def font_width(self):\n        return self.get_font_width(font_name=self.font_name, font_size=self.font_size)",
    "docstring": "Return the badge font width."
  },
  {
    "code": "def alphabetical_formula(self):\n        alph_formula = super().alphabetical_formula\n        chg_str = \"\"\n        if self.charge > 0:\n            chg_str = \" +\" + formula_double_format(self.charge, False)\n        elif self.charge < 0:\n            chg_str = \" \" + formula_double_format(self.charge, False)\n        return alph_formula + chg_str",
    "docstring": "Returns a reduced formula string with appended charge"
  },
  {
    "code": "def get_vault_ids_by_authorization(self, authorization_id):\n        mgr = self._get_provider_manager('AUTHORIZATION', local=True)\n        lookup_session = mgr.get_authorization_lookup_session(proxy=self._proxy)\n        lookup_session.use_federated_vault_view()\n        authorization = lookup_session.get_authorization(authorization_id)\n        id_list = []\n        for idstr in authorization._my_map['assignedVaultIds']:\n            id_list.append(Id(idstr))\n        return IdList(id_list)",
    "docstring": "Gets the list of ``Vault``  ``Ids`` mapped to an ``Authorization``.\n\n        arg:    authorization_id (osid.id.Id): ``Id`` of an\n                ``Authorization``\n        return: (osid.id.IdList) - list of vault ``Ids``\n        raise:  NotFound - ``authorization_id`` is not found\n        raise:  NullArgument - ``authorization_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_functions_by_search(self, function_query, function_search):\n        if not self._can('search'):\n            raise PermissionDenied()\n        return self._provider_session.get_functions_by_search(function_query, function_search)",
    "docstring": "Pass through to provider FunctionSearchSession.get_functions_by_search"
  },
  {
    "code": "async def remove(self, name: str) -> None:\n        LOGGER.debug('NodePoolManager.remove >>> name: %s', name)\n        try:\n            await pool.delete_pool_ledger_config(name)\n        except IndyError as x_indy:\n            LOGGER.info('Abstaining from node pool removal; indy-sdk error code %s', x_indy.error_code)\n        LOGGER.debug('NodePool.remove <<<')",
    "docstring": "Remove serialized pool info if it exists. Abstain from removing open node pool."
  },
  {
    "code": "def _prepare_wsdl_objects(self):\n        self.DeletionControlType = self.client.factory.create('DeletionControlType')\n        self.TrackingId = self.client.factory.create('TrackingId')\n        self.TrackingId.TrackingIdType = self.client.factory.create('TrackingIdType')",
    "docstring": "Preps the WSDL data structures for the user."
  },
  {
    "code": "def conjugate(self):\n        return self.__class__(scalar=self.scalar, vector= -self.vector)",
    "docstring": "Quaternion conjugate, encapsulated in a new instance.\n\n        For a unit quaternion, this is the same as the inverse.\n\n        Returns:\n            A new Quaternion object clone with its vector part negated"
  },
  {
    "code": "def getPysamVariants(self, referenceName, startPosition, endPosition):\n        if referenceName in self._chromFileMap:\n            varFileName = self._chromFileMap[referenceName]\n            referenceName, startPosition, endPosition = \\\n                self.sanitizeVariantFileFetch(\n                    referenceName, startPosition, endPosition)\n            cursor = self.getFileHandle(varFileName).fetch(\n                referenceName, startPosition, endPosition)\n            for record in cursor:\n                yield record",
    "docstring": "Returns an iterator over the pysam VCF records corresponding to the\n        specified query."
  },
  {
    "code": "def _set_annotation_to_str(annotation_data: Mapping[str, Mapping[str, bool]], key: str) -> str:\n    value = annotation_data[key]\n    if len(value) == 1:\n        return 'SET {} = \"{}\"'.format(key, list(value)[0])\n    x = ('\"{}\"'.format(v) for v in sorted(value))\n    return 'SET {} = {{{}}}'.format(key, ', '.join(x))",
    "docstring": "Return a set annotation string."
  },
  {
    "code": "def is_quoted(value):\n    ret = ''\n    if isinstance(value, six.string_types) \\\n            and value[0] == value[-1] \\\n            and value.startswith(('\\'', '\"')):\n        ret = value[0]\n    return ret",
    "docstring": "Return a single or double quote, if a string is wrapped in extra quotes.\n    Otherwise return an empty string."
  },
  {
    "code": "def libvlc_media_new_location(p_instance, psz_mrl):\n    f = _Cfunctions.get('libvlc_media_new_location', None) or \\\n        _Cfunction('libvlc_media_new_location', ((1,), (1,),), class_result(Media),\n                    ctypes.c_void_p, Instance, ctypes.c_char_p)\n    return f(p_instance, psz_mrl)",
    "docstring": "Create a media with a certain given media resource location,\n    for instance a valid URL.\n    @note: To refer to a local file with this function,\n    the file://... URI syntax B{must} be used (see IETF RFC3986).\n    We recommend using L{libvlc_media_new_path}() instead when dealing with\n    local files.\n    See L{libvlc_media_release}.\n    @param p_instance: the instance.\n    @param psz_mrl: the media location.\n    @return: the newly created media or NULL on error."
  },
  {
    "code": "def _get_cookie(self, name, domain):\n        for c in self.session.cookies:\n            if c.name==name and c.domain==domain:\n                return c\n        return None",
    "docstring": "Return the cookie \"name\" for \"domain\" if found\n            If there are mote than one, only the first is returned"
  },
  {
    "code": "def Run(self, unused_arg):\n    reply = rdf_flows.GrrStatus(status=rdf_flows.GrrStatus.ReturnedStatus.OK)\n    self.SendReply(reply, message_type=rdf_flows.GrrMessage.Type.STATUS)\n    self.grr_worker.Sleep(10)\n    logging.info(\"Dying on request.\")\n    os._exit(242)",
    "docstring": "Run the kill."
  },
  {
    "code": "def from_parent(cls,\n                    parent: 'BlockHeader',\n                    gas_limit: int,\n                    difficulty: int,\n                    timestamp: int,\n                    coinbase: Address=ZERO_ADDRESS,\n                    nonce: bytes=None,\n                    extra_data: bytes=None,\n                    transaction_root: bytes=None,\n                    receipt_root: bytes=None) -> 'BlockHeader':\n        header_kwargs = {\n            'parent_hash': parent.hash,\n            'coinbase': coinbase,\n            'state_root': parent.state_root,\n            'gas_limit': gas_limit,\n            'difficulty': difficulty,\n            'block_number': parent.block_number + 1,\n            'timestamp': timestamp,\n        }\n        if nonce is not None:\n            header_kwargs['nonce'] = nonce\n        if extra_data is not None:\n            header_kwargs['extra_data'] = extra_data\n        if transaction_root is not None:\n            header_kwargs['transaction_root'] = transaction_root\n        if receipt_root is not None:\n            header_kwargs['receipt_root'] = receipt_root\n        header = cls(**header_kwargs)\n        return header",
    "docstring": "Initialize a new block header with the `parent` header as the block's\n        parent hash."
  },
  {
    "code": "def iter_milestones(self, state=None, sort=None, direction=None,\n                        number=-1, etag=None):\n        url = self._build_url('milestones', base_url=self._api)\n        accepted = {'state': ('open', 'closed'),\n                    'sort': ('due_date', 'completeness'),\n                    'direction': ('asc', 'desc')}\n        params = {'state': state, 'sort': sort, 'direction': direction}\n        for (k, v) in list(params.items()):\n            if not (v and (v in accepted[k])):\n                del params[k]\n        if not params:\n            params = None\n        return self._iter(int(number), url, Milestone, params, etag)",
    "docstring": "Iterates over the milestones on this repository.\n\n        :param str state: (optional), state of the milestones, accepted\n            values: ('open', 'closed')\n        :param str sort: (optional), how to sort the milestones, accepted\n            values: ('due_date', 'completeness')\n        :param str direction: (optional), direction to sort the milestones,\n            accepted values: ('asc', 'desc')\n        :param int number: (optional), number of milestones to return.\n            Default: -1 returns all milestones\n        :param str etag: (optional), ETag from a previous request to the same\n            endpoint\n        :returns: generator of\n            :class:`Milestone <github3.issues.milestone.Milestone>`\\ s"
  },
  {
    "code": "def has_blocking_background_send(self):\n\t\tfor background_object in self.background_objects:\n\t\t\tif background_object.block_other_commands and background_object.run_state in ('S','N'):\n\t\t\t\tself.shutit_obj.log('All objects are: ' + str(self),level=logging.DEBUG)\n\t\t\t\tself.shutit_obj.log('The current blocking send object is: ' + str(background_object),level=logging.DEBUG)\n\t\t\t\treturn True\n\t\t\telif background_object.block_other_commands and background_object.run_state in ('F','C','T'):\n\t\t\t\tassert False, shutit_util.print_debug(msg='Blocking command should have been removed, in run_state: ' + background_object.run_state)\n\t\t\telse:\n\t\t\t\tassert background_object.block_other_commands is False, shutit_util.print_debug()\n\t\treturn False",
    "docstring": "Check whether any blocking background commands are waiting to run.\n        If any are, return True. If none are, return False."
  },
  {
    "code": "def estimate_map(interface, state, label, inp):\n    out = interface.output(0)\n    centers = {}\n    for row in inp:\n        row = row.strip().split(state[\"delimiter\"])\n        if len(row) > 1:\n            x = [(0 if row[i] in state[\"missing_vals\"] else float(row[i])) for i in state[\"X_indices\"]]\n            cluster = min((state['dist'](c, x), i) for i, c in state['centers'])[1]\n            vertex = state['create'](x, 1.0)\n            centers[cluster] = vertex if cluster not in centers else state[\"update\"](centers[cluster], vertex)\n    for cluster, values in centers.iteritems():\n        out.add(cluster, values)",
    "docstring": "Find the cluster `i` that is closest to the datapoint `e`."
  },
  {
    "code": "def get_user_best(self, username, *, mode=OsuMode.osu, limit=50):\n        return self._make_req(endpoints.USER_BEST, dict(\n            k=self.key,\n            u=username,\n            type=_username_type(username),\n            m=mode.value,\n            limit=limit\n            ), JsonList(SoloScore))",
    "docstring": "Get a user's best scores.\n\n        Parameters\n        ----------\n        username : str or int\n            A `str` representing the user's username, or an `int` representing the user's id.\n        mode : :class:`osuapi.enums.OsuMode`\n            The osu! game mode for which to look up. Defaults to osu!standard.\n        limit\n            The maximum number of results to return. Defaults to 50, maximum 100."
  },
  {
    "code": "def currentRepoTreeItemChanged(self):\n        currentItem, currentIndex = self.getCurrentItem()\n        hasCurrent = currentIndex.isValid()\n        assert hasCurrent == (currentItem is not None), \\\n            \"If current idex is valid, currentIndex may not be None\"\n        if hasCurrent:\n            logger.info(\"Adding rti to collector: {}\".format(currentItem.nodePath))\n            self.collector.setRti(currentItem)\n        self.currentItemActionGroup.setEnabled(hasCurrent)\n        isTopLevel = hasCurrent and self.model().isTopLevelIndex(currentIndex)\n        self.topLevelItemActionGroup.setEnabled(isTopLevel)\n        self.openItemAction.setEnabled(currentItem is not None\n                                       and currentItem.hasChildren()\n                                       and not currentItem.isOpen)\n        self.closeItemAction.setEnabled(currentItem is not None\n                                        and currentItem.hasChildren()\n                                        and currentItem.isOpen)\n        logger.debug(\"Emitting sigRepoItemChanged: {}\".format(currentItem))\n        self.sigRepoItemChanged.emit(currentItem)",
    "docstring": "Called to update the GUI when a repo tree item has changed or a new one was selected."
  },
  {
    "code": "def fold(self, node):\n        node = self.generic_visit(node)\n        try:\n            return nodes.Const.from_untrusted(node.as_const(),\n                                              lineno=node.lineno,\n                                              environment=self.environment)\n        except nodes.Impossible:\n            return node",
    "docstring": "Do constant folding."
  },
  {
    "code": "def variables(self):\n        p = lambda o: isinstance(o, Variable) and self._docfilter(o)\n        return sorted(filter(p, self.doc.values()))",
    "docstring": "Returns all documented module level variables in the module\n        sorted alphabetically as a list of `pydoc.Variable`."
  },
  {
    "code": "def getOverlayWidthInMeters(self, ulOverlayHandle):\n        fn = self.function_table.getOverlayWidthInMeters\n        pfWidthInMeters = c_float()\n        result = fn(ulOverlayHandle, byref(pfWidthInMeters))\n        return result, pfWidthInMeters.value",
    "docstring": "Returns the width of the overlay quad in meters. By default overlays are rendered on a quad that is 1 meter across"
  },
  {
    "code": "def save(self, fname, compression='blosc'):\n        egg = {\n            'data' : self.data,\n            'analysis' : self.analysis,\n            'list_length' : self.list_length,\n            'n_lists' : self.n_lists,\n            'n_subjects' : self.n_subjects,\n            'position' : self.position,\n            'date_created' : self.date_created,\n            'meta' : self.meta\n        }\n        if fname[-4:]!='.fegg':\n            fname+='.fegg'\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            dd.io.save(fname, egg, compression=compression)",
    "docstring": "Save method for the FriedEgg object\n\n        The data will be saved as a 'fegg' file, which is a dictionary containing\n        the elements of a FriedEgg saved in the hd5 format using\n        `deepdish`.\n\n        Parameters\n        ----------\n\n        fname : str\n            A name for the file.  If the file extension (.fegg) is not specified,\n            it will be appended.\n\n        compression : str\n            The kind of compression to use.  See the deepdish documentation for\n            options: http://deepdish.readthedocs.io/en/latest/api_io.html#deepdish.io.save"
  },
  {
    "code": "def keygrip_ed25519(vk):\n    return _compute_keygrip([\n        ['p', util.num2bytes(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED, size=32)],\n        ['a', b'\\x01'],\n        ['b', util.num2bytes(0x2DFC9311D490018C7338BF8688861767FF8FF5B2BEBE27548A14B235ECA6874A, size=32)],\n        ['g', util.num2bytes(0x04216936D3CD6E53FEC0A4E231FDD6DC5C692CC7609525A7B2C9562D608F25D51A6666666666666666666666666666666666666666666666666666666666666658, size=65)],\n        ['n', util.num2bytes(0x1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED, size=32)],\n        ['q', vk.to_bytes()],\n    ])",
    "docstring": "Compute keygrip for Ed25519 public keys."
  },
  {
    "code": "def add_migrations(self, migrations):\n        if self.__closed:\n            raise MigrationSessionError(\"Can't change applied session\")\n        self._to_apply.extend(migrations)",
    "docstring": "Add migrations to be applied.\n\n        Args:\n            migrations: a list of migrations to add of the form [(app, migration_name), ...]\n        Raises:\n            MigrationSessionError if called on a closed MigrationSession"
  },
  {
    "code": "def get_html_clear_filename(filename):\n    newFilename = filename.replace(\".html\", \"\")\n    newFilename = newFilename.replace(\".md\", \"\")\n    newFilename = newFilename.replace(\".txt\", \"\")\n    newFilename = newFilename.replace(\".tile\", \"\")\n    newFilename = newFilename.replace(\".jade\", \"\")\n    newFilename = newFilename.replace(\".rst\", \"\")\n    newFilename = newFilename.replace(\".docx\", \"\")\n    newFilename = newFilename.replace(\"index\", \"home\")\n    newFilename = newFilename.replace(\"-\", \" \")\n    newFilename = newFilename.replace(\"_\", \" \")\n    newFilename = newFilename.title()\n    return newFilename",
    "docstring": "Clears the file extension from the filename and makes it nice looking"
  },
  {
    "code": "def verify(expr, params=None):\n    try:\n        compile(expr, params=params)\n        return True\n    except com.TranslationError:\n        return False",
    "docstring": "Determine if expression can be successfully translated to execute on\n    MapD"
  },
  {
    "code": "def clear_operations_touching(self,\n                                  qubits: Iterable[ops.Qid],\n                                  moment_indices: Iterable[int]):\n        qubits = frozenset(qubits)\n        for k in moment_indices:\n            if 0 <= k < len(self._moments):\n                self._moments[k] = self._moments[k].without_operations_touching(\n                    qubits)",
    "docstring": "Clears operations that are touching given qubits at given moments.\n\n        Args:\n            qubits: The qubits to check for operations on.\n            moment_indices: The indices of moments to check for operations\n                within."
  },
  {
    "code": "def get_tags(self, only_autocomplete = False):\n        return self._to_dict(('id', 'name', 'autocomplete'), self.conn.GetTags(only_autocomplete))",
    "docstring": "returns list of all tags. by default only those that have been set for autocomplete"
  },
  {
    "code": "def got_broker_module_type_defined(self, module_type):\n        for broker_link in self.brokers:\n            for module in broker_link.modules:\n                if module.is_a_module(module_type):\n                    return True\n        return False",
    "docstring": "Check if a module type is defined in one of the brokers\n\n        :param module_type: module type to search for\n        :type module_type: str\n        :return: True if mod_type is found else False\n        :rtype: bool"
  },
  {
    "code": "def check_version(version: str):\n    code_version = parse_version(__version__)\n    given_version = parse_version(version)\n    check_condition(code_version[0] == given_version[0],\n                    \"Given release version (%s) does not match release code version (%s)\" % (version, __version__))\n    check_condition(code_version[1] == given_version[1],\n                    \"Given major version (%s) does not match major code version (%s)\" % (version, __version__))",
    "docstring": "Checks given version against code version and determines compatibility.\n    Throws if versions are incompatible.\n\n    :param version: Given version."
  },
  {
    "code": "def get_window_size(self, windowHandle='current'):\n        command = Command.GET_WINDOW_SIZE\n        if self.w3c:\n            if windowHandle != 'current':\n                warnings.warn(\"Only 'current' window is supported for W3C compatibile browsers.\")\n            size = self.get_window_rect()\n        else:\n            size = self.execute(command, {'windowHandle': windowHandle})\n        if size.get('value', None) is not None:\n            size = size['value']\n        return {k: size[k] for k in ('width', 'height')}",
    "docstring": "Gets the width and height of the current window.\n\n        :Usage:\n            ::\n\n                driver.get_window_size()"
  },
  {
    "code": "def clear_cache():\n        del Cache._keys\n        for k in list(Cache._cache.keys()):\n            it = Cache._cache.pop(k)\n            del it\n        del Cache._cache\n        Cache._keys = []\n        Cache._cache = {}\n        gc.collect()",
    "docstring": "Remove all cached objects"
  },
  {
    "code": "async def _get_smallest_env(self):\n        async def slave_task(mgr_addr):\n            r_manager = await self.env.connect(mgr_addr, timeout=TIMEOUT)\n            ret = await r_manager.get_agents(addr=True)\n            return mgr_addr, len(ret)\n        sizes = await create_tasks(slave_task, self.addrs, flatten=False)\n        return sorted(sizes, key=lambda x: x[1])[0][0]",
    "docstring": "Get address of the slave environment manager with the smallest\n        number of agents."
  },
  {
    "code": "def __get_user(self):\n        storage = object.__getattribute__(self, '_LazyUser__storage')\n        user = getattr(self.__auth, 'get_user')()\n        setattr(storage, self.__user_name, user)\n        return user",
    "docstring": "Return the real user object."
  },
  {
    "code": "def getUserSignupDate(self):\n        userinfo = self.getUserInfo()\n        timestamp = int(float(userinfo[\"signupTimeSec\"]))\n        return time.strftime(\"%m/%d/%Y %H:%M\", time.gmtime(timestamp))",
    "docstring": "Returns the human readable date of when the user signed up for google reader."
  },
  {
    "code": "def reset_position(self):\n        self.pos = 0\n        self.col = 0\n        self.row = 1\n        self.eos = 0",
    "docstring": "Reset all current positions."
  },
  {
    "code": "def find(self, name):\n        collectors = self.get_collectors()\n        for collector in collectors:\n            if name.lower() == collector['name'].lower():\n                self.collector_id = collector['id']\n                return collector\n        return {'status': 'No results found.'}",
    "docstring": "Returns a dict of collector's details if found.\n\n        Args:\n            name (str): name of collector searching for"
  },
  {
    "code": "def to_tensor(self):\n    a_shape = shape_list(self.a)\n    b_shape = shape_list(self.b)\n    inner_dim = b_shape[1]\n    result_dim = b_shape[0]\n    flat_a = tf.reshape(self.a, [-1, inner_dim])\n    product = tf.matmul(flat_a, self.b, transpose_b=True)\n    product_shape = a_shape[:-1] + [result_dim]\n    product = tf.reshape(product, product_shape)\n    product.set_shape(self.a.get_shape().as_list()[:-1] +\n                      [self.b.get_shape()[0]])\n    return product",
    "docstring": "Convert to Tensor."
  },
  {
    "code": "def patchFile(filename, replacements):\n\t\tpatched = Utility.readFile(filename)\n\t\tfor key in replacements:\n\t\t\tpatched = patched.replace(key, replacements[key])\n\t\tUtility.writeFile(filename, patched)",
    "docstring": "Applies the supplied list of replacements to a file"
  },
  {
    "code": "def score(self, test_X, test_Y):\n        with self.tf_graph.as_default():\n            with tf.Session() as self.tf_session:\n                self.tf_saver.restore(self.tf_session, self.model_path)\n                feed = {\n                    self.input_data: test_X,\n                    self.input_labels: test_Y,\n                    self.keep_prob: 1\n                }\n                return self.accuracy.eval(feed)",
    "docstring": "Compute the mean accuracy over the test set.\n\n        Parameters\n        ----------\n\n        test_X : array_like, shape (n_samples, n_features)\n            Test data.\n\n        test_Y : array_like, shape (n_samples, n_features)\n            Test labels.\n\n        Returns\n        -------\n\n        float : mean accuracy over the test set"
  },
  {
    "code": "def _create_table(self, table_name, column_types, primary=None, nullable=()):\n        require_string(table_name, \"table name\")\n        require_iterable_of(column_types, tuple, name=\"rows\")\n        if primary is not None:\n            require_string(primary, \"primary\")\n        require_iterable_of(nullable, str, name=\"nullable\")\n        column_decls = []\n        for column_name, column_type in column_types:\n            decl = \"%s %s\" % (column_name, column_type)\n            if column_name == primary:\n                decl += \" UNIQUE PRIMARY KEY\"\n            if column_name not in nullable:\n                decl += \" NOT NULL\"\n            column_decls.append(decl)\n        column_decl_str = \", \".join(column_decls)\n        create_table_sql = \\\n            \"CREATE TABLE %s (%s)\" % (table_name, column_decl_str)\n        self.execute_sql(create_table_sql)",
    "docstring": "Creates a sqlite3 table from the given metadata.\n\n        Parameters\n        ----------\n\n        column_types : list of (str, str) pairs\n            First element of each tuple is the column name, second element is the sqlite3 type\n\n        primary : str, optional\n            Which column is the primary key\n\n        nullable : iterable, optional\n            Names of columns which have null values"
  },
  {
    "code": "def get_lastfm(method, lastfm_key='', **kwargs):\n    if not lastfm_key:\n        if 'lastfm_key' not in CONFIG or not CONFIG['lastfm_key']:\n            logger.warning('No lastfm key configured')\n            return ''\n        else:\n            lastfm_key = CONFIG['lastfm_key']\n    url = 'http://ws.audioscrobbler.com/2.0/?method={}&api_key={}&format=json'\n    url = url.format(method, lastfm_key)\n    for key in kwargs:\n        url += '&{}={}'.format(key, kwargs[key])\n    response = get_url(url, parser='json')\n    if 'error' in response:\n        logger.error('Error number %d in lastfm query: %s',\n                     response['error'], response['message'])\n        return ''\n    return response",
    "docstring": "Request the specified method from the lastfm api."
  },
  {
    "code": "def genms(self, scans=[]):\n        if len(scans):\n            scanstr = string.join([str(ss) for ss in sorted(scans)], ',')\n        else:\n            scanstr = self.allstr\n        print 'Splitting out all cal scans (%s) with 1s int time' % scanstr\n        newname = ps.sdm2ms(self.sdmfile, self.sdmfile.rstrip('/')+'.ms', scanstr, inttime='1')\n        return newname",
    "docstring": "Generate an MS that contains all calibrator scans with 1 s integration time."
  },
  {
    "code": "def _join_keys_v1(left, right):\n    if left.endswith(':') or '::' in left:\n        raise ValueError(\"Can't join a left string ending in ':' or containing '::'\")\n    return u\"{}::{}\".format(_encode_v1(left), _encode_v1(right))",
    "docstring": "Join two keys into a format separable by using _split_keys_v1."
  },
  {
    "code": "def load_jws_from_request(req):\n    current_app.logger.info(\"loading request with headers: %s\" % req.headers)\n    if ((\"content-type\" in req.headers and\n         \"application/jose\" in req.headers['content-type']) or\n        (\"Content-Type\" in req.headers and\n         \"application/jose\" in req.headers['Content-Type'])):\n        path = urlparse.urlsplit(req.url).path\n        for rule in current_app.url_map.iter_rules():\n            if path == rule.rule and req.method in rule.methods:\n                dedata = req.get_data().decode('utf8')\n                bp = current_app.bitjws.basepath\n                req.jws_header, req.jws_payload = \\\n                    bitjws.validate_deserialize(dedata, requrl=bp + rule.rule)\n                break",
    "docstring": "This function performs almost entirely bitjws authentication tasks.\n    If valid bitjws message and signature headers are found,\n    then the request will be assigned 'jws_header' and 'jws_payload' attributes.\n\n    :param req: The flask request to load the jwt claim set from."
  },
  {
    "code": "def _to_api_value(self, attribute_type, value):\n        if not value:\n            return None\n        if isinstance(attribute_type, properties.Instance):\n            return value.to_api()\n        if isinstance(attribute_type, properties.List):\n            return self._parse_api_value_list(value)\n        return attribute_type.serialize(value)",
    "docstring": "Return a parsed value for the API."
  },
  {
    "code": "def end_body(self):\n        if self.write_copy_script:\n            self.write(\n                '<textarea id=\"c\" class=\"invisible\"></textarea>'\n                '<script>'\n                'function cp(t){'\n                'var c=document.getElementById(\"c\");'\n                'c.value=t;'\n                'c.select();'\n                'try{document.execCommand(\"copy\")}'\n                'catch(e){}}'\n                '</script>'\n            )\n        self.write('</div>{}</body></html>', self._script)",
    "docstring": "Ends the whole document. This should be called the last"
  },
  {
    "code": "def add_root_bank(self, bank_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.add_root_catalog(catalog_id=bank_id)\n        return self._hierarchy_session.add_root(id_=bank_id)",
    "docstring": "Adds a root bank.\n\n        arg:    bank_id (osid.id.Id): the ``Id`` of a bank\n        raise:  AlreadyExists - ``bank_id`` is already in hierarchy\n        raise:  NotFound - ``bank_id`` not found\n        raise:  NullArgument - ``bank_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def derive_annotations(self, annotations):\n        cls = type(self)\n        return cls(\n            self[0],\n            self[1],\n            self[2],\n            self[3],\n            annotations,\n            self[5]\n        )",
    "docstring": "Derives a new event from this one setting the ``annotations`` attribute.\n\n        Args:\n            annotations: (Sequence[Union[amazon.ion.symbols.SymbolToken, unicode]]):\n                The annotations associated with the derived event.\n\n        Returns:\n            IonEvent: The newly generated event."
  },
  {
    "code": "def update_billing_info(self, billing_info):\n        url = urljoin(self._url, '/billing_info')\n        response = billing_info.http_request(url, 'PUT', billing_info,\n            {'Content-Type': 'application/xml; charset=utf-8'})\n        if response.status == 200:\n            pass\n        elif response.status == 201:\n            billing_info._url = response.getheader('Location')\n        else:\n            billing_info.raise_http_error(response)\n        response_xml = response.read()\n        logging.getLogger('recurly.http.response').debug(response_xml)\n        billing_info.update_from_element(ElementTree.fromstring(response_xml))",
    "docstring": "Change this account's billing information to the given `BillingInfo`."
  },
  {
    "code": "def whois_domains(self, domains):\n        api_name = 'opendns-whois-domain'\n        fmt_url_path = u'whois/{0}'\n        return self._multi_get(api_name, fmt_url_path, domains)",
    "docstring": "Calls WHOIS domain end point\n\n        Args:\n            domains: An enumerable of domains\n        Returns:\n            A dict of {domain: domain_result}"
  },
  {
    "code": "def _build_url(self, api_call):\n        if self.api_version in ('1.13.0', '1.13.0+update.1', '1.13.0+update.2'):\n            if '/' not in api_call:\n                return \"{0}/{1}/index.json\".format(self.site_url, api_call)\n        return \"{0}/{1}.json\".format(self.site_url, api_call)",
    "docstring": "Build request url.\n\n        Parameters:\n            api_call (str): Base API Call.\n\n        Returns:\n            Complete url (str)."
  },
  {
    "code": "def detail(self, detail=None, ret_r=False):\n        if detail or ret_r:\n            self._detail = detail\n            return self\n        return self._detail",
    "docstring": "code's detail"
  },
  {
    "code": "def noam_norm(x, epsilon=1.0, name=None):\n  with tf.name_scope(name, default_name=\"noam_norm\", values=[x]):\n    shape = x.get_shape()\n    ndims = len(shape)\n    return (tf.nn.l2_normalize(x, ndims - 1, epsilon=epsilon) * tf.sqrt(\n        to_float(shape[-1])))",
    "docstring": "One version of layer normalization."
  },
  {
    "code": "def callConfirmed(RepeatIndicator_presence=0,\n                  BearerCapability_presence=0, BearerCapability_presence1=0,\n                  Cause_presence=0, CallControlCapabilities_presence=0):\n    a = TpPd(pd=0x3)\n    b = MessageType(mesType=0x8)\n    packet = a / b\n    if RepeatIndicator_presence is 1:\n        c = RepeatIndicatorHdr(ieiRI=0xD, eightBitRI=0x0)\n        packet = packet / c\n    if BearerCapability_presence is 1:\n        d = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0)\n        packet = packet / d\n    if BearerCapability_presence1 is 1:\n        e = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0)\n        packet = packet / e\n    if Cause_presence is 1:\n        f = CauseHdr(ieiC=0x08, eightBitC=0x0)\n        packet = packet / f\n    if CallControlCapabilities_presence is 1:\n        g = CallControlCapabilitiesHdr(ieiCCC=0x15, eightBitCCC=0x0)\n        packet = packet / g\n    return packet",
    "docstring": "CALL CONFIRMED Section 9.3.2"
  },
  {
    "code": "def _restore_stdout(self):\n        if self.buffer:\n            if self._mirror_output:\n                output = sys.stdout.getvalue()\n                error = sys.stderr.getvalue()\n                if output:\n                    if not output.endswith('\\n'):\n                        output += '\\n'\n                    self._original_stdout.write(STDOUT_LINE % output)\n                if error:\n                    if not error.endswith('\\n'):\n                        error += '\\n'\n                    self._original_stderr.write(STDERR_LINE % error)\n            sys.stdout = self._original_stdout\n            sys.stderr = self._original_stderr\n            self._stdout_buffer.seek(0)\n            self._stdout_buffer.truncate()\n            self._stderr_buffer.seek(0)\n            self._stderr_buffer.truncate()",
    "docstring": "Unhook stdout and stderr if buffering is enabled."
  },
  {
    "code": "def before_request(self, request, method, url, headers):\n        parts = urllib.parse.urlsplit(url)\n        audience = urllib.parse.urlunsplit(\n            (parts.scheme, parts.netloc, parts.path, \"\", \"\"))\n        token = self._get_jwt_for_audience(audience)\n        self.apply(headers, token=token)",
    "docstring": "Performs credential-specific before request logic.\n\n        Args:\n            request (Any): Unused. JWT credentials do not need to make an\n                HTTP request to refresh.\n            method (str): The request's HTTP method.\n            url (str): The request's URI. This is used as the audience claim\n                when generating the JWT.\n            headers (Mapping): The request's headers."
  },
  {
    "code": "def selectReceivePath(self, paths):\n        logger.debug(\"%s\", paths)\n        if not paths:\n            path = os.path.basename(self.userPath) + '/Anon'\n        try:\n            path = [p for p in paths if not p.startswith(\"/\")][0]\n        except IndexError:\n            path = os.path.relpath(list(paths)[0], self.userPath)\n        return self._fullPath(path)",
    "docstring": "From a set of source paths, recommend a destination path.\n\n        The paths are relative or absolute, in a source Store.\n        The result will be absolute, suitable for this destination Store."
  },
  {
    "code": "def play_Track(self, track):\n        if hasattr(track, 'name'):\n            self.set_track_name(track.name)\n        self.delay = 0\n        instr = track.instrument\n        if hasattr(instr, 'instrument_nr'):\n            self.change_instrument = True\n            self.instrument = instr.instrument_nr\n        for bar in track:\n            self.play_Bar(bar)",
    "docstring": "Convert a Track object to MIDI events and write them to the\n        track_data."
  },
  {
    "code": "def init_drivers(enable_debug_driver=False):\n    for driver in DRIVERS:\n        try:\n            if driver != DebugDriver or enable_debug_driver:\n                CLASSES.append(driver)\n        except Exception:\n            continue",
    "docstring": "Initialize all the drivers."
  },
  {
    "code": "def _register_info(self, server):\n    server_url = urllib.parse.urlparse(server.get_url())\n    info = manager.TensorBoardInfo(\n        version=version.VERSION,\n        start_time=int(time.time()),\n        port=server_url.port,\n        pid=os.getpid(),\n        path_prefix=self.flags.path_prefix,\n        logdir=self.flags.logdir,\n        db=self.flags.db,\n        cache_key=self.cache_key,\n    )\n    atexit.register(manager.remove_info_file)\n    manager.write_info_file(info)",
    "docstring": "Write a TensorBoardInfo file and arrange for its cleanup.\n\n    Args:\n      server: The result of `self._make_server()`."
  },
  {
    "code": "def __live_receivers(signal):\n    with __lock:\n        __purge()\n        receivers = [funcref() for funcref in __receivers[signal]]\n    return receivers",
    "docstring": "Return all signal handlers that are currently still alive for the\n    input `signal`.\n\n    Args:\n        signal: A signal name.\n\n    Returns:\n        A list of callable receivers for the input signal."
  },
  {
    "code": "def tunable(self, obj):\n        self.tune = dict()\n        if 'tune' in obj:\n            for tunable in MOUNT_TUNABLES:\n                tunable_key = tunable[0]\n                map_val(self.tune, obj['tune'], tunable_key)\n                if tunable_key in self.tune and \\\n                   is_vault_time(self.tune[tunable_key]):\n                    vault_time_s = vault_time_to_s(self.tune[tunable_key])\n                    self.tune[tunable_key] = vault_time_s\n        if 'description'in obj:\n            self.tune['description'] = obj['description']",
    "docstring": "A tunable resource maps against a backend..."
  },
  {
    "code": "def rotation(cls, angle, pivot=None):\n        ca, sa = cos_sin_deg(angle)\n        if pivot is None:\n            return tuple.__new__(cls, (ca, sa, 0.0, -sa, ca, 0.0, 0.0, 0.0, 1.0))\n        else:\n            px, py = pivot\n            return tuple.__new__(\n                cls,\n                (\n                    ca,\n                    sa,\n                    px - px * ca + py * sa,\n                    -sa,\n                    ca,\n                    py - px * sa - py * ca,\n                    0.0,\n                    0.0,\n                    1.0,\n                ),\n            )",
    "docstring": "Create a rotation transform at the specified angle,\n        optionally about the specified pivot point.\n\n        :param angle: Rotation angle in degrees\n        :type angle: float\n        :param pivot: Point to rotate about, if omitted the\n            rotation is about the origin.\n        :type pivot: sequence\n        :rtype: Affine"
  },
  {
    "code": "def get_dexseq_gff(config, default=None):\n    dexseq_gff = tz.get_in(tz.get_in(['dexseq_gff', 'keys'], LOOKUPS, {}),\n                           config, None)\n    if not dexseq_gff:\n        return None\n    gtf_file = get_gtf_file(config)\n    if gtf_file:\n        base_dir = os.path.dirname(gtf_file)\n    else:\n        base_dir = os.path.dirname(dexseq_gff)\n    base, _ = os.path.splitext(dexseq_gff)\n    gff_file = os.path.join(base_dir, base + \".gff\")\n    if file_exists(gff_file):\n        return gff_file\n    gtf_file = os.path.join(base_dir, base + \".gff3\")\n    if file_exists(gtf_file):\n        return gtf_file\n    else:\n        return None",
    "docstring": "some older versions of the genomes have the DEXseq gff file as\n    gff instead of gff3, so this handles that by looking for either one"
  },
  {
    "code": "def _force_float(v):\n    try:\n        return float(v)\n    except Exception as exc:\n        return float('nan')\n        logger.warning('Failed to convert {} to float with {} error. Using 0 instead.'.format(v, exc))",
    "docstring": "Converts given argument to float. On fail logs warning and returns 0.0.\n\n    Args:\n        v (any): value to convert to float\n\n    Returns:\n        float: converted v or 0.0 if conversion failed."
  },
  {
    "code": "def compose(*funcs: Callable) -> Callable:\n    def _compose(*args, **kw):\n        ret = reduce(lambda acc, x: lambda f: f(acc(x)),\n                     funcs[::-1],\n                     lambda f: f(*args, **kw))\n        return ret(lambda x: x)\n    return _compose",
    "docstring": "Compose multiple functions right to left.\n\n    Composes zero or more functions into a functional composition. The\n    functions are composed right to left. A composition of zero\n    functions gives back the identity function.\n\n    compose()(x) == x\n    compose(f)(x) == f(x)\n    compose(g, f)(x) == g(f(x))\n    compose(h, g, f)(x) == h(g(f(x)))\n    ...\n\n    Returns the composed function."
  },
  {
    "code": "def generichash_blake2b_init(key=b'', salt=b'',\n                             person=b'',\n                             digest_size=crypto_generichash_BYTES):\n    _checkparams(digest_size, key, salt, person)\n    state = Blake2State(digest_size)\n    _salt = ffi.new(\"unsigned char []\", crypto_generichash_SALTBYTES)\n    _person = ffi.new(\"unsigned char []\", crypto_generichash_PERSONALBYTES)\n    ffi.memmove(_salt, salt, len(salt))\n    ffi.memmove(_person, person, len(person))\n    rc = lib.crypto_generichash_blake2b_init_salt_personal(state._statebuf,\n                                                           key, len(key),\n                                                           digest_size,\n                                                           _salt, _person)\n    ensure(rc == 0, 'Unexpected failure',\n           raising=exc.RuntimeError)\n    return state",
    "docstring": "Create a new initialized blake2b hash state\n\n    :param key: must be at most\n                :py:data:`.crypto_generichash_KEYBYTES_MAX` long\n    :type key: bytes\n    :param salt: must be at most\n                 :py:data:`.crypto_generichash_SALTBYTES` long;\n                 will be zero-padded if needed\n    :type salt: bytes\n    :param person: must be at most\n                   :py:data:`.crypto_generichash_PERSONALBYTES` long:\n                   will be zero-padded if needed\n    :type person: bytes\n    :param digest_size: must be at most\n                        :py:data:`.crypto_generichash_BYTES_MAX`;\n                        the default digest size is\n                        :py:data:`.crypto_generichash_BYTES`\n    :type digest_size: int\n    :return: a initialized :py:class:`.Blake2State`\n    :rtype: object"
  },
  {
    "code": "def __validInterval(self, start, finish):\n        url = self.__getURL(1,\n                            start.strftime(\"%Y-%m-%d\"),\n                            finish.strftime(\"%Y-%m-%d\"))\n        data = self.__readAPI(url)\n        if data[\"total_count\"] >= 1000:\n            middle = start + (finish - start)/2\n            self.__validInterval(start, middle)\n            self.__validInterval(middle, finish)\n        else:\n            self.__intervals.append([start.strftime(\"%Y-%m-%d\"),\n                                     finish.strftime(\"%Y-%m-%d\")])\n            self.__logger.info(\"New valid interval: \" +\n                               start.strftime(\"%Y-%m-%d\") +\n                               \" to \" +\n                               finish.strftime(\"%Y-%m-%d\"))",
    "docstring": "Check if the interval is correct.\n\n        An interval is correct if it has less than 1001\n        users. If the interval is correct, it will be added\n        to '_intervals' attribute. Else, interval will be\n        split in two news intervals and these intervals\n        will be checked.\n\n        :param start: start date of the interval.\n        :type start: datetime.date.\n        :param finish: finish date of the interval.\n        :type finish: datetime.date."
  },
  {
    "code": "def save_assets(self, dest_path):\n        for idx, subplot in enumerate(self.subplots):\n            subplot.save_assets(dest_path, suffix='_%d' % idx)",
    "docstring": "Save plot assets alongside dest_path.\n\n        Some plots may have assets, like bitmap files, which need to be\n        saved alongside the rendered plot file.\n\n        :param dest_path: path of the main output file."
  },
  {
    "code": "def _AssertDataIsList(key, lst):\n  if not isinstance(lst, list) and not isinstance(lst, tuple):\n    raise NotAListError('%s must be a list' % key)\n  for element in lst:\n    if not isinstance(element, str):\n      raise ElementNotAStringError('Unsupported list element %s found in %s',\n                                   (element, lst))",
    "docstring": "Assert that lst contains list data and is not structured."
  },
  {
    "code": "def pub_connect(self):\n        if self.pub_sock:\n            self.pub_close()\n        ctx = zmq.Context.instance()\n        self._sock_data.sock = ctx.socket(zmq.PUSH)\n        self.pub_sock.setsockopt(zmq.LINGER, -1)\n        if self.opts.get('ipc_mode', '') == 'tcp':\n            pull_uri = 'tcp://127.0.0.1:{0}'.format(\n                self.opts.get('tcp_master_publish_pull', 4514)\n                )\n        else:\n            pull_uri = 'ipc://{0}'.format(\n                os.path.join(self.opts['sock_dir'], 'publish_pull.ipc')\n                )\n        log.debug(\"Connecting to pub server: %s\", pull_uri)\n        self.pub_sock.connect(pull_uri)\n        return self._sock_data.sock",
    "docstring": "Create and connect this thread's zmq socket. If a publisher socket\n        already exists \"pub_close\" is called before creating and connecting a\n        new socket."
  },
  {
    "code": "def unlock():\n    conn = __proxy__['junos.conn']()\n    ret = {}\n    ret['out'] = True\n    try:\n        conn.cu.unlock()\n        ret['message'] = \"Successfully unlocked the configuration.\"\n    except jnpr.junos.exception.UnlockError as exception:\n        ret['message'] = \\\n            'Could not unlock configuration due to : \"{0}\"'.format(exception)\n        ret['out'] = False\n    return ret",
    "docstring": "Unlocks the candidate configuration.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'device_name' junos.unlock"
  },
  {
    "code": "def resource(self, uri, methods=frozenset({'GET'}), host=None,\n                 strict_slashes=None, stream=False, version=None, name=None,\n                 **kwargs):\n        if strict_slashes is None:\n            strict_slashes = self.strict_slashes\n        def decorator(handler):\n            self.resources.append((\n                FutureRoute(handler, uri, methods, host, strict_slashes,\n                            stream, version, name),\n                kwargs))\n            return handler\n        return decorator",
    "docstring": "Create a blueprint resource route from a decorated function.\n\n        :param uri: endpoint at which the route will be accessible.\n        :param methods: list of acceptable HTTP methods.\n        :param host:\n        :param strict_slashes:\n        :param version:\n        :param name: user defined route name for url_for\n        :return: function or class instance\n\n        Accepts any keyword argument that will be passed to the app resource."
  },
  {
    "code": "def job_success_message(self, job, queue, job_result):\n        return '[%s|%s|%s] success, in %s' % (queue._cached_name, job.pk.get(),\n                                           job._cached_identifier, job.duration)",
    "docstring": "Return the message to log when a job is successful"
  },
  {
    "code": "def generate (self, ps):\n        assert isinstance(ps, property_set.PropertySet)\n        self.manager_.targets ().start_building (self)\n        ps = ps.expand ()\n        all_property_sets = self.apply_default_build (ps)\n        result = GenerateResult ()\n        for p in all_property_sets:\n            result.extend (self.__generate_really (p))\n        self.manager_.targets ().end_building (self)\n        return result",
    "docstring": "Select an alternative for this main target, by finding all alternatives\n            which requirements are satisfied by 'properties' and picking the one with\n            longest requirements set.\n            Returns the result of calling 'generate' on that alternative."
  },
  {
    "code": "def image(random=random, width=800, height=600, https=False, *args, **kwargs):\n    target_fn = noun\n    if width+height > 300:\n        target_fn = thing\n    if width+height > 2000:\n        target_fn = sentence\n    s = \"\"\n    if https:\n        s = \"s\"\n    if random.choice([True, False]):\n        return \"http{s}://dummyimage.com/{width}x{height}/292929/e3e3e3&text={text}\".format(\n                s=s,\n                width=width,\n                height=height,\n                text=target_fn(random=random))\n    else:\n        return \"http{s}://placekitten.com/{width}/{height}\".format(s=s, width=width, height=height)",
    "docstring": "Generate the address of a placeholder image.\n\n    >>> mock_random.seed(0)\n    >>> image(random=mock_random)\n    'http://dummyimage.com/800x600/292929/e3e3e3&text=mighty poop'\n    >>> image(random=mock_random, width=60, height=60)\n    'http://placekitten.com/60/60'\n    >>> image(random=mock_random, width=1920, height=1080)\n    'http://dummyimage.com/1920x1080/292929/e3e3e3&text=To get to Westeros, you need to go to Britchestown, then drive west.'\n    >>> image(random=mock_random, https=True, width=1920, height=1080)\n    'https://dummyimage.com/1920x1080/292929/e3e3e3&text=East Mysteryhall is in Westeros.'"
  },
  {
    "code": "def scan_dir(self, path):\n        r\n        for fname in glob.glob(os.path.join(path, '*' + TABLE_EXT)):\n            if os.path.isfile(fname):\n                with open(fname, 'r') as fobj:\n                    try:\n                        self.add_colortable(fobj, os.path.splitext(os.path.basename(fname))[0])\n                        log.debug('Added colortable from file: %s', fname)\n                    except RuntimeError:\n                        log.info('Skipping unparsable file: %s', fname)",
    "docstring": "r\"\"\"Scan a directory on disk for color table files and add them to the registry.\n\n        Parameters\n        ----------\n        path : str\n            The path to the directory with the color tables"
  },
  {
    "code": "def loads(cls, value):\n    if len(value) == 1 and cls.sentinel in value:\n      value = value[cls.sentinel]\n    return value",
    "docstring": "Returns mapping type deserialized `value`."
  },
  {
    "code": "def _get_compressed_vlan_list(self, pvlan_ids):\n        if not pvlan_ids:\n            return []\n        pvlan_list = list(pvlan_ids)\n        pvlan_list.sort()\n        compressed_list = []\n        begin = -1\n        prev_vlan = -1\n        for port_vlan in pvlan_list:\n            if prev_vlan == -1:\n                prev_vlan = port_vlan\n            else:\n                if (port_vlan - prev_vlan) == 1:\n                    if begin == -1:\n                        begin = prev_vlan\n                    prev_vlan = port_vlan\n                else:\n                    if begin == -1:\n                        compressed_list.append(str(prev_vlan))\n                    else:\n                        compressed_list.append(\"%d-%d\" % (begin, prev_vlan))\n                        begin = -1\n                    prev_vlan = port_vlan\n        if begin == -1:\n            compressed_list.append(str(prev_vlan))\n        else:\n            compressed_list.append(\"%s-%s\" % (begin, prev_vlan))\n        return compressed_list",
    "docstring": "Generate a compressed vlan list ready for XML using a vlan set.\n\n        Sample Use Case:\n\n        Input vlan set:\n        --------------\n        1 - s = set([11, 50, 25, 30, 15, 16, 3, 8, 2, 1])\n        2 - s = set([87, 11, 50, 25, 30, 15, 16, 3, 8, 2, 1, 88])\n\n        Returned compressed XML list:\n        ----------------------------\n        1 - compressed_list = ['1-3', '8', '11', '15-16', '25', '30', '50']\n        2 - compressed_list = ['1-3', '8', '11', '15-16', '25', '30',\n                               '50', '87-88']"
  },
  {
    "code": "def main():\n    parser.name('tinman')\n    parser.description(__desc__)\n    p = parser.get()\n    p.add_argument('-p', '--path',\n                   action='store',\n                   dest='path',\n                   help='Path to prepend to the Python system path')\n    helper.start(Controller)",
    "docstring": "Invoked by the script installed by setuptools."
  },
  {
    "code": "def copy_abiext(self, inext, outext):\n        infile = self.has_abiext(inext)\n        if not infile:\n            raise RuntimeError('no file with extension %s in %s' % (inext, self))\n        for i in range(len(infile) - 1, -1, -1):\n            if infile[i] == '_':\n                break\n        else:\n            raise RuntimeError('Extension %s could not be detected in file %s' % (inext, infile))\n        outfile = infile[:i] + '_' + outext\n        shutil.copy(infile, outfile)\n        return 0",
    "docstring": "Copy the Abinit file with extension inext to a new file withw extension outext"
  },
  {
    "code": "def total_msg_recv(self):\n        return (self.get_count(PeerCounterNames.RECV_UPDATES) +\n                self.get_count(PeerCounterNames.RECV_REFRESH) +\n                self.get_count(PeerCounterNames.RECV_NOTIFICATION))",
    "docstring": "Returns total number of UPDATE, NOTIFICATION and ROUTE_REFRESH\n        messages received from this peer."
  },
  {
    "code": "def walk_dependencies(root, visitor):\n    def visit(parent, visitor):\n        for d in get_dependencies(parent):\n            visitor(d, parent)\n            visit(d, visitor)\n    visitor(root, None)\n    visit(root, visitor)",
    "docstring": "Call visitor on root and all dependencies reachable from it in breadth\n    first order.\n\n    Args:\n        root (component): component function or class\n        visitor (function): signature is `func(component, parent)`.  The\n            call on root is `visitor(root, None)`."
  },
  {
    "code": "def _bytes_to_human(self, B):\n        KB = float(1024)\n        MB = float(KB ** 2)\n        GB = float(KB ** 3)\n        TB = float(KB ** 4)\n        if B < KB:\n            return '{0} B'.format(B)\n        B = float(B)\n        if KB <= B < MB:\n            return '{0:.2f} KB'.format(B/KB)\n        elif MB <= B < GB:\n            return '{0:.2f} MB'.format(B/MB)\n        elif GB <= B < TB:\n            return '{0:.2f} GB'.format(B/GB)\n        elif TB <= B:\n            return '{0:.2f} TB'.format(B/TB)",
    "docstring": "Return the given bytes as a human friendly KB, MB, GB, or TB string"
  },
  {
    "code": "def draw_rendered_map(self, surf):\n    surf.blit_np_array(features.Feature.unpack_rgb_image(\n        self._obs.observation.render_data.map))",
    "docstring": "Draw the rendered pixels."
  },
  {
    "code": "def unmarshal_props(self, fp, cls=None, id=None):\n        if isinstance(fp, str) or isinstance(fp, unicode):\n            doc = parseString(fp)\n        else:\n            doc = parse(fp)\n        return self.get_props_from_doc(cls, id, doc)",
    "docstring": "Same as unmarshalling an object, except it returns\n        from \"get_props_from_doc\""
  },
  {
    "code": "def find_module(self, modname, folder=None):\n        for src in self.get_source_folders():\n            module = _find_module_in_folder(src, modname)\n            if module is not None:\n                return module\n        for src in self.get_python_path_folders():\n            module = _find_module_in_folder(src, modname)\n            if module is not None:\n                return module\n        if folder is not None:\n            module = _find_module_in_folder(folder, modname)\n            if module is not None:\n                return module\n        return None",
    "docstring": "Returns a resource corresponding to the given module\n\n        returns None if it can not be found"
  },
  {
    "code": "def get_all_classes(module_name):\n    module = importlib.import_module(module_name)\n    return getmembers(module, lambda m: isclass(m) and not isabstract(m))",
    "docstring": "Load all non-abstract classes from package"
  },
  {
    "code": "def kelvin_to_rgb(kelvin):\n    temp = kelvin / 100.0\n    if temp <= 66:\n        red = 255\n    else:\n        red = 329.698727446 * ((temp - 60) ** -0.1332047592)\n    if temp <= 66:\n        green = 99.4708025861 * math.log(temp) - 161.1195681661\n    else:\n        green = 288.1221695283 * ((temp - 60) ** -0.0755148492)\n    if temp > 66:\n        blue = 255\n    elif temp <= 19:\n        blue = 0\n    else:\n        blue = 138.5177312231 * math.log(temp - 10) - 305.0447927307\n    return tuple(correct_output(c) for c in (red, green, blue))",
    "docstring": "Convert a color temperature given in kelvin to an approximate RGB value.\n\n    :param kelvin: Color temp in K\n    :return: Tuple of (r, g, b), equivalent color for the temperature"
  },
  {
    "code": "def ports(self):\n        with self._mutex:\n            if not self._ports:\n                self._ports = [ports.parse_port(port, self) \\\n                               for port in self._obj.get_ports()]\n        return self._ports",
    "docstring": "The list of all ports belonging to this component."
  },
  {
    "code": "def after_match(self, func, full_fallback=False):\n        iterator = iter(self)\n        for item in iterator:\n            if func(item):\n                return iterator\n        if full_fallback:\n            iterator = iter(self)\n        return iterator",
    "docstring": "Returns an iterator for all the elements after the first\n        match.  If `full_fallback` is `True`, it will return all the\n        messages if the function never matched."
  },
  {
    "code": "def get_evaluation_parameter(self, parameter_name, default_value=None):\n        if \"evaluation_parameters\" in self._expectations_config and \\\n                parameter_name in self._expectations_config['evaluation_parameters']:\n            return self._expectations_config['evaluation_parameters'][parameter_name]\n        else:\n            return default_value",
    "docstring": "Get an evaluation parameter value that has been stored in meta.\n\n        Args:\n            parameter_name (string): The name of the parameter to store.\n            default_value (any): The default value to be returned if the parameter is not found.\n\n        Returns:\n            The current value of the evaluation parameter."
  },
  {
    "code": "def get_cached(self, link, default=None):\n        if hasattr(link, 'uri'):\n            return self.id_map.get(link.uri, default)\n        else:\n            return self.id_map.get(link, default)",
    "docstring": "Retrieves a cached navigator from the id_map.\n\n        Either a Link object or a bare uri string may be passed in."
  },
  {
    "code": "def jtype(c):\n    ct = c['type']\n    return ct if ct != 'literal' else '{}, {}'.format(ct, c.get('xml:lang'))",
    "docstring": "Return the a string with the data type of a value, for JSON data"
  },
  {
    "code": "def retryable(retryer=retry_ex, times=3, cap=120000):\n    def _retryable(func):\n        @f.wraps(func)\n        def wrapper(*args, **kwargs):\n            return retryer(lambda: func(*args, **kwargs), times, cap)\n        return wrapper\n    return _retryable",
    "docstring": "A decorator to make a function retry. By default the retry\n    occurs when an exception is thrown, but this may be changed\n    by modifying the ``retryer`` argument.\n\n    See also :py:func:`retry_ex` and :py:func:`retry_bool`. By\n    default :py:func:`retry_ex` is used as the retry function.\n\n    Note that the decorator must be called even if not given\n    keyword arguments.\n\n    :param function retryer: A function to handle retries\n    :param int times: Number of times to retry on initial failure\n    :param int cap: Maximum wait time in milliseconds\n\n    :Example:\n\n    ::\n\n      @retryable()\n      def can_fail():\n          ....\n\n      @retryable(retryer=retry_bool, times=10)\n      def can_fail_bool():\n          ...."
  },
  {
    "code": "def CheckProg(context, prog_name):\n    res = SCons.Conftest.CheckProg(context, prog_name)\n    context.did_show_result = 1\n    return res",
    "docstring": "Simple check if a program exists in the path.  Returns the path\n    for the application, or None if not found."
  },
  {
    "code": "def _inner_search(obj, glob, separator, dirs=True, leaves=False):\n    for path in dpath.path.paths(obj, dirs, leaves, skip=True):\n        if dpath.path.match(path, glob):\n            yield path",
    "docstring": "Search the object paths that match the glob."
  },
  {
    "code": "def disable_cert_validation():\n    current_context = ssl._create_default_https_context\n    ssl._create_default_https_context = ssl._create_unverified_context\n    try:\n        yield\n    finally:\n        ssl._create_default_https_context = current_context",
    "docstring": "Context manager to temporarily disable certificate validation in the standard SSL\n    library.\n\n    Note: This should not be used in production code but is sometimes useful for\n    troubleshooting certificate validation issues.\n\n    By design, the standard SSL library does not provide a way to disable verification\n    of the server side certificate. However, a patch to disable validation is described\n    by the library developers. This context manager allows applying the patch for\n    specific sections of code."
  },
  {
    "code": "def solve(self):\n        board = Board(self.length, self.height)\n        permutations = Permutations(self.pieces, self.vector_size)\n        for positions in permutations:\n            board.reset()\n            for level, (piece_uid, linear_position) in enumerate(positions):\n                try:\n                    board.add(piece_uid, linear_position)\n                except (OccupiedPosition, VulnerablePosition, AttackablePiece):\n                    permutations.skip_branch(level)\n                    break\n            else:\n                self.result_counter += 1\n                yield board",
    "docstring": "Solve all possible positions of pieces within the context.\n\n        Depth-first, tree-traversal of the product space."
  },
  {
    "code": "def delete_servers(*servers, **options):\n    test = options.pop('test', False)\n    commit = options.pop('commit', True)\n    return __salt__['net.load_template']('delete_ntp_servers',\n                                         servers=servers,\n                                         test=test,\n                                         commit=commit,\n                                         inherit_napalm_device=napalm_device)",
    "docstring": "Removes NTP servers configured on the device.\n\n    :param servers: list of IP Addresses/Domain Names to be removed as NTP\n        servers\n    :param test (bool): discard loaded config. By default ``test`` is False\n        (will not dicard the changes)\n    :param commit (bool): commit loaded config. By default ``commit`` is True\n        (will commit the changes). Useful when the user does not want to commit\n        after each change, but after a couple.\n\n    By default this function will commit the config changes (if any). To load\n    without committing, use the ``commit`` option. For dry run use the ``test``\n    argument.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' ntp.delete_servers 8.8.8.8 time.apple.com\n        salt '*' ntp.delete_servers 172.17.17.1 test=True  # only displays the diff\n        salt '*' ntp.delete_servers 192.168.0.1 commit=False  # preserves the changes, but does not commit"
  },
  {
    "code": "def handle(self):\n        self.output = PyStratumStyle(self.input, self.output)\n        command = self.get_application().find('constants')\n        ret = command.execute(self.input, self.output)\n        if ret:\n            return ret\n        command = self.get_application().find('loader')\n        ret = command.execute(self.input, self.output)\n        if ret:\n            return ret\n        command = self.get_application().find('wrapper')\n        ret = command.execute(self.input, self.output)\n        self.output.writeln('')\n        return ret",
    "docstring": "Executes the actual Stratum program."
  },
  {
    "code": "def push_rule(self, name):\n        if name in self._name:\n            raise PolicyException(\n                \"Rule recursion detected; invocation chain: %s -> %s\" %\n                (' -> '.join(self._name), name))\n        self._name.append(name)\n        self._pc.append(0)\n        self._step.append(1)\n        try:\n            yield\n        except Exception as exc:\n            exc_info = sys.exc_info()\n            if not self.reported:\n                log = logging.getLogger('policies')\n                log.warn(\"Exception raised while evaluating rule %r: %s\" %\n                         (name, exc))\n                self.reported = True\n            six.reraise(*exc_info)\n        finally:\n            self._name.pop()\n            self._pc.pop()\n            self._step.pop()",
    "docstring": "Allow one rule to be evaluated in the context of another.\n        This allows keeping track of the rule names during nested rule\n        evaluation.\n\n        :param name: The name of the nested rule to be evaluated.\n\n        :returns: A context manager, suitable for use with the\n                  ``with`` statement.  No value is generated."
  },
  {
    "code": "def has_axis(self, axis):\n\t\tif self.type != EventType.POINTER_AXIS:\n\t\t\traise AttributeError(_wrong_meth.format(self.type))\n\t\treturn self._libinput.libinput_event_pointer_has_axis(\n\t\t\tself._handle, axis)",
    "docstring": "Check if the event has a valid value for the given axis.\n\n\t\tIf this method returns True for an axis and :meth:`get_axis_value`\n\t\treturns a value of 0, the event is a scroll stop event.\n\n\t\tFor pointer events that are not of type\n\t\t:attr:`~libinput.constant.EventType.POINTER_AXIS`, this method raises\n\t\t:exc:`AttributeError`.\n\n\t\tArgs:\n\t\t\taxis (~libinput.constant.PointerAxis): The axis to check.\n\t\tReturns:\n\t\t\tbool: True if this event contains a value for this axis.\n\t\tRaises:\n\t\t\tAttributeError"
  },
  {
    "code": "def get_local_admins():\n    admin_list = get_users_config()\n    response = []\n    if 'users' not in admin_list['result']:\n        return response\n    if isinstance(admin_list['result']['users']['entry'], list):\n        for entry in admin_list['result']['users']['entry']:\n            response.append(entry['name'])\n    else:\n        response.append(admin_list['result']['users']['entry']['name'])\n    return response",
    "docstring": "Show all local administrator accounts.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' panos.get_local_admins"
  },
  {
    "code": "def update_director(self, service_id, version_number, name_key, **kwargs):\n\t\tbody = self._formdata(kwargs, FastlyDirector.FIELDS)\n\t\tcontent = self._fetch(\"/service/%s/version/%d/director/%s\" % (service_id, version_number, name_key), method=\"PUT\", body=body)\n\t\treturn FastlyDirector(self, content)",
    "docstring": "Update the director for a particular service and version."
  },
  {
    "code": "def is_not_null_predicate(\n    raw_crash, dumps, processed_crash, processor, key=''\n):\n    try:\n        return bool(raw_crash[key])\n    except KeyError:\n        return False",
    "docstring": "a predicate that converts the key'd source to boolean.\n\n    parameters:\n        raw_crash - dict\n        dumps - placeholder in a fat interface - unused\n        processed_crash - placeholder in a fat interface - unused\n        processor - placeholder in a fat interface - unused"
  },
  {
    "code": "def make_label(var_name, selection, position=\"below\"):\n    if selection:\n        sel = selection_to_string(selection)\n        if position == \"below\":\n            sep = \"\\n\"\n        elif position == \"beside\":\n            sep = \" \"\n    else:\n        sep = sel = \"\"\n    return \"{}{}{}\".format(var_name, sep, sel)",
    "docstring": "Consistent labelling for plots.\n\n    Parameters\n    ----------\n    var_name : str\n       Name of the variable\n\n    selection : dict[Any] -> Any\n        Coordinates of the variable\n    position : whether to position the coordinates' label \"below\" (default) or \"beside\" the name\n               of the variable\n\n    Returns\n    -------\n    label\n        A text representation of the label"
  },
  {
    "code": "def mapPartitions(self, f, preservesPartitioning=False):\n        return (\n            self\n            .mapPartitionsWithIndex(lambda i, p: f(p), preservesPartitioning)\n            .transform(lambda rdd:\n                       rdd.setName('{}:{}'.format(rdd.prev.name(), f)))\n        )",
    "docstring": "Map partitions.\n\n        :param f: mapping function\n        :rtype: DStream"
  },
  {
    "code": "def next_blob(self):\n        blob_file = self.blob_file\n        try:\n            preamble = DAQPreamble(file_obj=blob_file)\n        except struct.error:\n            raise StopIteration\n        try:\n            data_type = DATA_TYPES[preamble.data_type]\n        except KeyError:\n            log.error(\"Unkown datatype: {0}\".format(preamble.data_type))\n            data_type = 'Unknown'\n        blob = Blob()\n        blob[data_type] = None\n        blob['DAQPreamble'] = preamble\n        if data_type == 'DAQSummaryslice':\n            daq_frame = DAQSummaryslice(blob_file)\n            blob[data_type] = daq_frame\n            blob['DAQHeader'] = daq_frame.header\n        elif data_type == 'DAQEvent':\n            daq_frame = DAQEvent(blob_file)\n            blob[data_type] = daq_frame\n            blob['DAQHeader'] = daq_frame.header\n        else:\n            log.warning(\n                \"Skipping DAQ frame with data type code '{0}'.\".format(\n                    preamble.data_type\n                )\n            )\n            blob_file.seek(preamble.length - DAQPreamble.size, 1)\n        return blob",
    "docstring": "Get the next frame from file"
  },
  {
    "code": "def mode_readable(self):\n        ret = \"\"\n        mode = self._raw_mode\n        if mode.MANUAL:\n            ret = \"manual\"\n            if self.target_temperature < self.min_temp:\n                ret += \" off\"\n            elif self.target_temperature >= self.max_temp:\n                ret += \" on\"\n            else:\n                ret += \" (%sC)\" % self.target_temperature\n        else:\n            ret = \"auto\"\n        if mode.AWAY:\n            ret += \" holiday\"\n        if mode.BOOST:\n            ret += \" boost\"\n        if mode.DST:\n            ret += \" dst\"\n        if mode.WINDOW:\n            ret += \" window\"\n        if mode.LOCKED:\n            ret += \" locked\"\n        if mode.LOW_BATTERY:\n            ret += \" low battery\"\n        return ret",
    "docstring": "Return a readable representation of the mode.."
  },
  {
    "code": "def get_utc_timestamp(self, handle):\n        fpath = self._fpath_from_handle(handle)\n        datetime_obj = datetime.datetime.utcfromtimestamp(\n            os.stat(fpath).st_mtime\n        )\n        return timestamp(datetime_obj)",
    "docstring": "Return the UTC timestamp."
  },
  {
    "code": "def get_objective_banks(self):\n        catalogs = self._get_provider_session('objective_bank_lookup_session').get_objective_banks()\n        cat_list = []\n        for cat in catalogs:\n            cat_list.append(ObjectiveBank(self._provider_manager, cat, self._runtime, self._proxy))\n        return ObjectiveBankList(cat_list)",
    "docstring": "Pass through to provider ObjectiveBankLookupSession.get_objective_banks"
  },
  {
    "code": "def similarity(self, other: Trigram) -> float:\n        return max((self._match(x, other) for x in self.trigrams), default=0)",
    "docstring": "Find the best similarity within known trigrams."
  },
  {
    "code": "def iterate(self, resource_type=None):\n        for logicalId, resource_dict in self.resources.items():\n            resource = SamResource(resource_dict)\n            needs_filter = resource.valid()\n            if resource_type:\n                needs_filter = needs_filter and resource.type == resource_type\n            if needs_filter:\n                yield logicalId, resource",
    "docstring": "Iterate over all resources within the SAM template, optionally filtering by type\n\n        :param string resource_type: Optional type to filter the resources by\n        :yields (string, SamResource): Tuple containing LogicalId and the resource"
  },
  {
    "code": "def add_whitespace_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:\n        command = data.statement.command\n        command_pattern = re.compile(r'^([^\\s\\d]+)(\\d+)')\n        match = command_pattern.search(command)\n        if match:\n            data.statement = self.statement_parser.parse(\"{} {} {}\".format(\n                match.group(1),\n                match.group(2),\n                '' if data.statement.args is None else data.statement.args\n            ))\n        return data",
    "docstring": "A hook to split alphabetic command names immediately followed by a number.\n\n        l24 -> l 24\n        list24 -> list 24\n        list 24 -> list 24"
  },
  {
    "code": "def get_items_of_reminder_per_page(self, reminder_id, per_page=1000, page=1):\n        return self._get_resource_per_page(\n            resource=REMINDER_ITEMS,\n            per_page=per_page,\n            page=page,\n            params={'reminder_id': reminder_id},\n        )",
    "docstring": "Get items of reminder per page\n\n        :param reminder_id: the reminder id\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :return: list"
  },
  {
    "code": "def annotate(results, settings):\n    annotations = (generate_annotation(result, setting)\n                   for result, setting in zip(results, settings))\n    return '\\n'.join(annot for annot in annotations if annot)",
    "docstring": "Concatenate the annotations of all checkers"
  },
  {
    "code": "def download_series_gui(frame, urls, directory, min_file_size, max_file_size, no_redirects):\n\tif not os.path.exists(directory):\n\t\tos.makedirs(directory)\n\tapp = progress_class(frame, urls, directory, min_file_size, max_file_size, no_redirects)",
    "docstring": "called when user wants serial downloading"
  },
  {
    "code": "def create_index(self, index, index_type=GEO2D):\n        self.logger.info(\"Adding %s index to stores on attribute: %s\" % (index_type, index))\n        yield self.collection.create_index([(index, index_type)])",
    "docstring": "Create an index on a given attribute\n\n        :param str index: Attribute to set index on\n        :param str index_type: See PyMongo index types for further information, defaults to GEO2D index."
  },
  {
    "code": "def thaw(self, tmp_dir):\n        for resource in self.resources():\n            if resource.present:\n                resource.thaw(tmp_dir)",
    "docstring": "Will thaw every secret into an appropriate temporary location"
  },
  {
    "code": "def normalise_reads(self):\n        logging.info('Normalising reads to a kmer depth of 100')\n        for sample in self.metadata:\n            sample.general.normalisedreads = [fastq.split('.fastq.gz')[0] + '_normalised.fastq.gz'\n                                              for fastq in sorted(sample.general.fastqfiles)]\n            try:\n                out, err, cmd = bbtools.bbnorm(forward_in=sorted(sample.general.trimmedcorrectedfastqfiles)[0],\n                                               forward_out=sample.general.normalisedreads[0],\n                                               returncmd=True,\n                                               threads=self.cpus)\n                sample[self.analysistype].normalisecmd = cmd\n                write_to_logfile(out, err, self.logfile, sample.general.logout, sample.general.logerr, None, None)\n            except CalledProcessError:\n                sample.general.normalisedreads = sample.general.trimmedfastqfiles\n            except IndexError:\n                sample.general.normalisedreads = list()",
    "docstring": "Use bbnorm from the bbmap suite of tools to perform read normalisation"
  },
  {
    "code": "def render_revalidation_failure(self, step, form, **kwargs):\n        self.storage.current_step = step\n        return self.render(form, **kwargs)",
    "docstring": "Gets called when a form doesn't validate when rendering the done\n        view. By default, it changed the current step to failing forms step\n        and renders the form."
  },
  {
    "code": "def _get_odoo_version_info(addons_dir, odoo_version_override=None):\n    odoo_version_info = None\n    addons = os.listdir(addons_dir)\n    for addon in addons:\n        addon_dir = os.path.join(addons_dir, addon)\n        if is_installable_addon(addon_dir):\n            manifest = read_manifest(addon_dir)\n            _, _, addon_odoo_version_info = _get_version(\n                addon_dir, manifest, odoo_version_override,\n                git_post_version=False)\n            if odoo_version_info is not None and \\\n                    odoo_version_info != addon_odoo_version_info:\n                raise DistutilsSetupError(\"Not all addons are for the same \"\n                                          \"odoo version in %s (error detected \"\n                                          \"in %s)\" % (addons_dir, addon))\n            odoo_version_info = addon_odoo_version_info\n    return odoo_version_info",
    "docstring": "Detect Odoo version from an addons directory"
  },
  {
    "code": "def _get_bin_width(stdev, count):\n    w = int(round((3.5 * stdev) / (count ** (1.0 / 3))))\n    if w:\n        return w\n    else:\n        return 1",
    "docstring": "Return the histogram's optimal bin width based on Sturges\n\n    http://www.jstor.org/pss/2965501"
  },
  {
    "code": "def coerce(self, value, **kwargs):\n        result = []\n        for v in value:\n            result.append(self._coercion.coerce(v, **kwargs))\n        return result",
    "docstring": "Coerces array items with proper coercion."
  },
  {
    "code": "def sort_by_formula_id(raw_datasets):\n    by_formula_id = defaultdict(list)\n    for el in raw_datasets:\n        by_formula_id[el['handwriting'].formula_id].append(el['handwriting'])\n    return by_formula_id",
    "docstring": "Sort a list of formulas by `id`, where `id` represents the accepted\n    formula id.\n\n    Parameters\n    ----------\n    raw_datasets : list of dictionaries\n        A list of raw datasets.\n\n    Examples\n    --------\n    The parameter `raw_datasets` has to be of the format\n\n    >>> rd = [{'is_in_testset': 0,\n    ...        'formula_id': 31,\n    ...        'handwriting': HandwrittenData(raw_data_id=2953),\n    ...        'formula_in_latex': 'A',\n    ...        'id': 2953},\n    ...       {'is_in_testset': 0,\n    ...        'formula_id': 31,\n    ...        'handwriting': HandwrittenData(raw_data_id=4037),\n    ...        'formula_in_latex': 'A',\n    ...        'id': 4037},\n    ...       {'is_in_testset': 0,\n    ...        'formula_id': 31,\n    ...        'handwriting': HandwrittenData(raw_data_id=4056),\n    ...        'formula_in_latex': 'A',\n    ...        'id': 4056}]\n    >>> sort_by_formula_id(rd)"
  },
  {
    "code": "def can_access_objective_hierarchy(self):\n        url_path = construct_url('authorization',\n                                 bank_id=self._catalog_idstr)\n        return self._get_request(url_path)['objectiveHierarchyHints']['canAccessHierarchy']",
    "docstring": "Tests if this user can perform hierarchy queries.\n\n        A return of true does not guarantee successful authorization. A\n        return of false indicates that it is known all methods in this\n        session will result in a PermissionDenied. This is intended as a\n        hint to an an application that may not offer traversal functions\n        to unauthorized users.\n\n        return: (boolean) - false if hierarchy traversal methods are not\n                authorized, true otherwise\n        compliance: mandatory - This method must be implemented."
  },
  {
    "code": "def is_ipaddress(hostname):\n    if six.PY3 and isinstance(hostname, bytes):\n        hostname = hostname.decode('ascii')\n    families = [socket.AF_INET]\n    if hasattr(socket, 'AF_INET6'):\n        families.append(socket.AF_INET6)\n    for af in families:\n        try:\n            inet_pton(af, hostname)\n        except (socket.error, ValueError, OSError):\n            pass\n        else:\n            return True\n    return False",
    "docstring": "Detects whether the hostname given is an IP address.\n\n    :param str hostname: Hostname to examine.\n    :return: True if the hostname is an IP address, False otherwise."
  },
  {
    "code": "def remove(self, *l):\n        for a in flatten(l):\n            self._remove([self.Inner(a)], self.l)",
    "docstring": "remove inner from outer\n\n        Args:\n            *l element that is passes into Inner init"
  },
  {
    "code": "def has_basis_notes(family, data_dir=None):\n    file_path = _basis_notes_path(family, data_dir)\n    return os.path.isfile(file_path)",
    "docstring": "Check if notes exist for a given basis set\n\n    Returns True if they exist, false otherwise"
  },
  {
    "code": "def as_wfn(self):\n        wfn = []\n        wfn.append(CPE2_3_WFN.CPE_PREFIX)\n        for ck in CPEComponent.CPE_COMP_KEYS:\n            lc = self._get_attribute_components(ck)\n            comp = lc[0]\n            if (isinstance(comp, CPEComponentUndefined) or\n               isinstance(comp, CPEComponentEmpty)):\n                continue\n            else:\n                v = []\n                v.append(ck)\n                v.append(\"=\")\n                v.append('\"')\n                v.append(comp.as_wfn())\n                v.append('\"')\n                wfn.append(\"\".join(v))\n                wfn.append(CPEComponent2_3_WFN.SEPARATOR_COMP)\n        wfn = wfn[:-1]\n        wfn.append(CPE2_3_WFN.CPE_SUFFIX)\n        return \"\".join(wfn)",
    "docstring": "Returns the CPE Name as WFN string of version 2.3.\n        Only shows the first seven components.\n\n        :return: CPE Name as WFN string\n        :rtype: string\n        :exception: TypeError - incompatible version"
  },
  {
    "code": "def count_exceptions(self, c, broker):\n        if c in broker.exceptions:\n            self.counts['exception'] += len(broker.exceptions[c])\n        return self",
    "docstring": "Count exceptions as processing proceeds"
  },
  {
    "code": "def merge_coords(objs, compat='minimal', join='outer', priority_arg=None,\n                 indexes=None):\n    _assert_compat_valid(compat)\n    coerced = coerce_pandas_values(objs)\n    aligned = deep_align(coerced, join=join, copy=False, indexes=indexes)\n    expanded = expand_variable_dicts(aligned)\n    priority_vars = _get_priority_vars(aligned, priority_arg, compat=compat)\n    variables = merge_variables(expanded, priority_vars, compat=compat)\n    assert_unique_multiindex_level_names(variables)\n    return variables",
    "docstring": "Merge coordinate variables.\n\n    See merge_core below for argument descriptions. This works similarly to\n    merge_core, except everything we don't worry about whether variables are\n    coordinates or not."
  },
  {
    "code": "def GetInstanceInfo(r, instance, static=None):\n    if static is None:\n        return r.request(\"get\", \"/2/instances/%s/info\" % instance)\n    else:\n        return r.request(\"get\", \"/2/instances/%s/info\" % instance,\n                         query={\"static\": static})",
    "docstring": "Gets information about an instance.\n\n    @type instance: string\n    @param instance: Instance name\n    @rtype: string\n    @return: Job ID"
  },
  {
    "code": "def error_from_exc(nsdk, tracer_h, e_val=None, e_ty=None):\n    if not tracer_h:\n        return\n    if e_ty is None and e_val is None:\n        e_ty, e_val = sys.exc_info()[:2]\n    if e_ty is None and e_val is not None:\n        e_ty = type(e_val)\n    nsdk.tracer_error(tracer_h, getfullname(e_ty), str(e_val))",
    "docstring": "Attach appropriate error information to tracer_h.\n\n    If e_val and e_ty are None, the current exception is used."
  },
  {
    "code": "def expand_query(config, kwds):\n    pattern = []\n    for query in kwds.pop('pattern', []):\n        expansion = config.search.alias.get(query)\n        if expansion is None:\n            pattern.append(query)\n        else:\n            parser = SafeArgumentParser()\n            search_add_arguments(parser)\n            ns = parser.parse_args(expansion)\n            for (key, value) in vars(ns).items():\n                if isinstance(value, (list, tuple)):\n                    if not kwds.get(key):\n                        kwds[key] = value\n                    else:\n                        kwds[key].extend(value)\n                else:\n                    kwds[key] = value\n    kwds['pattern'] = pattern\n    return config.search.kwds_adapter(kwds)",
    "docstring": "Expand `kwds` based on `config.search.query_expander`.\n\n    :type config: .config.Configuration\n    :type kwds: dict\n    :rtype: dict\n    :return: Return `kwds`, modified in place."
  },
  {
    "code": "def path(self):\n        if self.parent:\n            try:\n                parent_path = self.parent.path.encode()\n            except AttributeError:\n                parent_path = self.parent.path\n            return os.path.join(parent_path, self.name)\n        return b\"/\"",
    "docstring": "Node's relative path from the root node"
  },
  {
    "code": "def make_niche_grid(res_dict, world_size=(60, 60)):\n    world = initialize_grid(world_size, set())\n    for res in res_dict:\n        for cell in res_dict[res]:\n            world[cell[1]][cell[0]].add(res)\n    return world",
    "docstring": "Converts dictionary specifying where resources are to nested lists\n    specifying what sets of resources are where.\n\n    res_dict - a dictionary in which keys are resources in the environment\n    and values are list of tuples representing the cells they're in.\n\n    world_size - a tuple indicating the dimensions of the world.\n           Default = 60x60, because that's the default Avida world size\n\n    Returns a list of lists of sets indicating the set of resources\n    available at each x,y location in the Avida grid."
  },
  {
    "code": "def value_from_object(self, obj):\n        val = super(JSONField, self).value_from_object(obj)\n        return self.get_prep_value(val)",
    "docstring": "Return value dumped to string."
  },
  {
    "code": "def copy_file_internal(\n    src_fs,\n    src_path,\n    dst_fs,\n    dst_path,\n):\n    if src_fs is dst_fs:\n        src_fs.copy(src_path, dst_path, overwrite=True)\n    elif dst_fs.hassyspath(dst_path):\n        with dst_fs.openbin(dst_path, \"w\") as write_file:\n            src_fs.download(src_path, write_file)\n    else:\n        with src_fs.openbin(src_path) as read_file:\n            dst_fs.upload(dst_path, read_file)",
    "docstring": "Low level copy, that doesn't call manage_fs or lock.\n\n    If the destination exists, and is a file, it will be first truncated.\n\n    This method exists to optimize copying in loops. In general you\n    should prefer `copy_file`.\n\n    Arguments:\n        src_fs (FS): Source filesystem.\n        src_path (str): Path to a file on the source filesystem.\n        dst_fs (FS: Destination filesystem.\n        dst_path (str): Path to a file on the destination filesystem."
  },
  {
    "code": "def lchownr(path, owner, group):\n    chownr(path, owner, group, follow_links=False)",
    "docstring": "Recursively change user and group ownership of files and directories\n    in a given path, not following symbolic links. See the documentation for\n    'os.lchown' for more information.\n\n    :param str path: The string path to start changing ownership.\n    :param str owner: The owner string to use when looking up the uid.\n    :param str group: The group string to use when looking up the gid."
  },
  {
    "code": "def extract_col(self, col):\n        new_col = [row[col] for row in self.grid]\n        return new_col",
    "docstring": "get column number 'col'"
  },
  {
    "code": "def MAE(x1, x2=-1):\n    e = get_valid_error(x1, x2)\n    return np.sum(np.abs(e)) / float(len(e))",
    "docstring": "Mean absolute error - this function accepts two series of data or directly\n    one series with error.\n\n    **Args:**\n\n    * `x1` - first data series or error (1d array)\n\n    **Kwargs:**\n\n    * `x2` - second series (1d array) if first series was not error directly,\\\\\n        then this should be the second series\n\n    **Returns:**\n\n    * `e` - MAE of error (float) obtained directly from `x1`, \\\\\n        or as a difference of `x1` and `x2`"
  },
  {
    "code": "def _compute_anelestic_attenuation_term(self, C, dists):\r\n        f_aat = np.zeros_like(dists.rjb)\r\n        idx = dists.rjb > 80.0\r\n        f_aat[idx] = C[\"b10\"] * (dists.rjb[idx] - 80.0)\r\n        return f_aat",
    "docstring": "Compute and return anelastic attenuation term in equation 5,\r\n        page 970."
  },
  {
    "code": "def check_unique_tokens(sender, instance, **kwargs):\n    if isinstance(instance, CallbackToken):\n        if CallbackToken.objects.filter(key=instance.key, is_active=True).exists():\n            instance.key = generate_numeric_token()",
    "docstring": "Ensures that mobile and email tokens are unique or tries once more to generate."
  },
  {
    "code": "def exclusion_path(cls, project, exclusion):\n        return google.api_core.path_template.expand(\n            \"projects/{project}/exclusions/{exclusion}\",\n            project=project,\n            exclusion=exclusion,\n        )",
    "docstring": "Return a fully-qualified exclusion string."
  },
  {
    "code": "def string_to_timestruct(input_string):\n    try:\n        timestruct = time.strptime(input_string.decode('utf-8'), VolumeDescriptorDate.TIME_FMT)\n    except ValueError:\n        timestruct = time.struct_time((0, 0, 0, 0, 0, 0, 0, 0, 0))\n    return timestruct",
    "docstring": "A cacheable function to take an input string and decode it into a\n    time.struct_time from the time module.  If the string cannot be decoded\n    because of an illegal value, then the all-zero time.struct_time will be\n    returned instead.\n\n    Parameters:\n     input_string - The string to attempt to parse.\n    Returns:\n     A time.struct_time object representing the time."
  },
  {
    "code": "def get_view_name(namespace, view):\n    name = \"\"\n    if namespace != \"\":\n        name = namespace + \"_\"\n    return sanitize(name + view.name)",
    "docstring": "create the name for the view"
  },
  {
    "code": "def delete(self, id=None):\n        if id is not None:\n            self.where('id', '=', id)\n        sql = self._grammar.compile_delete(self)\n        return self._connection.delete(sql, self.get_bindings())",
    "docstring": "Delete a record from the database\n\n        :param id: The id of the row to delete\n        :type id: mixed\n\n        :return: The number of rows deleted\n        :rtype: int"
  },
  {
    "code": "def start(self, *args, **kwargs):\n        forever = kwargs.get('forever', True)\n        timeout = kwargs.get('timeout', None)\n        if forever:\n            return self.run(timeout=timeout)\n        elif timeout:\n            next((self.consume(timeout=timeout)), None)\n        else:\n            next((self.consume(limit=1, timeout=timeout)), None)",
    "docstring": "| Launch the consumer.\n        | It can listen forever for messages or just wait for one.\n\n        :param forever: If set, the consumer listens forever. Default to `True`.\n        :type forever: bool\n        :param timeout: If set, the consumer waits the specified seconds before quitting.\n        :type timeout: None, int\n        :rtype: None\n        :raises socket.timeout: when no message has been received since `timeout`."
  },
  {
    "code": "def setup_file_watcher(path, use_polling=False):\n    if use_polling:\n        observer_class = watchdog.observers.polling.PollingObserver\n    else:\n        observer_class = EVENTED_OBSERVER\n    file_event_handler = _SourceChangesHandler(patterns=[\"*.py\"])\n    file_watcher = observer_class()\n    file_watcher.schedule(file_event_handler, path, recursive=True)\n    file_watcher.start()\n    return file_watcher",
    "docstring": "Sets up a background thread that watches for source changes and\n    automatically sends SIGHUP to the current process whenever a file\n    changes."
  },
  {
    "code": "def set_default(self):\n        try:\n            os.makedirs(os.path.dirname(self._configfile))\n        except:\n            pass\n        self._config = configparser.RawConfigParser()\n        self._config.add_section('Settings')\n        for key, val in self.DEFAULTS.items():\n            self._config.set('Settings', key, val)\n        with open(self._configfile, 'w') as f:\n            self._config.write(f)",
    "docstring": "Set config to default."
  },
  {
    "code": "def Poll(generator=None, condition=None, interval=None, timeout=None):\n  if not generator:\n    raise ValueError(\"generator has to be a lambda\")\n  if not condition:\n    raise ValueError(\"condition has to be a lambda\")\n  if interval is None:\n    interval = DEFAULT_POLL_INTERVAL\n  if timeout is None:\n    timeout = DEFAULT_POLL_TIMEOUT\n  started = time.time()\n  while True:\n    obj = generator()\n    check_result = condition(obj)\n    if check_result:\n      return obj\n    if timeout and (time.time() - started) > timeout:\n      raise errors.PollTimeoutError(\n          \"Polling on %s timed out after %ds.\" % (obj, timeout))\n    time.sleep(interval)",
    "docstring": "Periodically calls generator function until a condition is satisfied."
  },
  {
    "code": "def get_target_transcript(self,min_intron=1):\n    if min_intron < 1: \n      sys.stderr.write(\"ERROR minimum intron should be 1 base or longer\\n\")\n      sys.exit()\n    rngs = [self.alignment_ranges[0][0].copy()]\n    for i in range(len(self.alignment_ranges)-1):\n      dist = self.alignment_ranges[i+1][0].start - rngs[-1].end-1\n      if dist >= min_intron:\n        rngs.append(self.alignment_ranges[i+1][0].copy())\n      else:\n        rngs[-1].end = self.alignment_ranges[i+1][0].end\n    tx = Transcript(rngs,options=Transcript.Options(\n         direction=self.strand,\n         name = self.alignment_ranges[0][1].chr,\n         gene_name = self.alignment_ranges[0][1].chr\n                                                  ))\n    return tx",
    "docstring": "Get the mapping of to the target strand\n\n    :returns: Transcript mapped to target\n    :rtype: Transcript"
  },
  {
    "code": "def pkg_version_list(self, pkg_id):\n        pkg_data = self.__reg_software.get(pkg_id, None)\n        if not pkg_data:\n            return []\n        if isinstance(pkg_data, list):\n            return pkg_data\n        installed_versions = list(pkg_data.get('version').keys())\n        return sorted(installed_versions, key=cmp_to_key(self.__oldest_to_latest_version))",
    "docstring": "Returns information on a package.\n\n        Args:\n            pkg_id (str): Package Id of the software/component.\n\n        Returns:\n            list: List of version numbers installed."
  },
  {
    "code": "def add_param(self, param_key, param_val):\n        self.params.append([param_key, param_val])\n        if param_key == '__success_test':\n            self.success = param_val",
    "docstring": "adds parameters as key value pairs"
  },
  {
    "code": "def check_by_selector(self, selector):\n    elem = find_element_by_jquery(world.browser, selector)\n    if not elem.is_selected():\n        elem.click()",
    "docstring": "Check the checkbox matching the CSS selector."
  },
  {
    "code": "def binarycontent_sections(chunk):\n    binary_content_tag = BINARY_CONTENT_START[1:]\n    if binary_content_tag not in chunk:\n        yield chunk\n    else:\n        sections = chunk.split(binary_content_tag)\n        for sec in sections:\n            extra = b''\n            if sec.endswith(b'</'):\n                extra = sec[-2:]\n                yield sec[:-2]\n            elif sec.endswith(b'<'):\n                extra = sec[-1:]\n                yield sec[:-1]\n            else:\n                yield sec\n            if extra:\n                yield b''.join([extra, binary_content_tag])",
    "docstring": "Split a chunk of data into sections by start and end binary\n    content tags."
  },
  {
    "code": "def tag_secondary_structure(self, force=False):\n        for polymer in self._molecules:\n            if polymer.molecule_type == 'protein':\n                polymer.tag_secondary_structure(force=force)\n        return",
    "docstring": "Tags each `Monomer` in the `Assembly` with it's secondary structure.\n\n        Notes\n        -----\n        DSSP must be available to call. Check by running\n        `isambard.external_programs.dssp.test_dssp`. If DSSP is not\n        available, please follow instruction here to add it:\n        https://github.com/woolfson-group/isambard#external-programs\n\n        For more information on DSSP see [1].\n\n        References\n        ----------\n        .. [1] Kabsch W, Sander C (1983) \"Dictionary of protein \n           secondary structure: pattern recognition of hydrogen-bonded\n           and geometrical features\", Biopolymers, 22, 2577-637.\n\n        Parameters\n        ----------\n        force : bool, optional\n            If True the tag will be run even if `Monomers` are already tagged"
  },
  {
    "code": "def assemble(self):\n        self.canonify()\n        args = [sys.argv and sys.argv[0] or \"python\"]\n        if self.mountpoint:\n            args.append(self.mountpoint)\n        for m, v in self.modifiers.items():\n            if v:\n                args.append(self.fuse_modifiers[m])\n        opta = []\n        for o, v in self.optdict.items():\n                opta.append(o + '=' + v)\n        opta.extend(self.optlist)\n        if opta:\n            args.append(\"-o\" + \",\".join(opta))\n        return args",
    "docstring": "Mangle self into an argument array"
  },
  {
    "code": "def create_data_item_from_data_and_metadata(self, data_and_metadata: DataAndMetadata.DataAndMetadata, title: str=None) -> DataItem:\n        data_item = DataItemModule.new_data_item(data_and_metadata)\n        if title is not None:\n            data_item.title = title\n        self.__document_model.append_data_item(data_item)\n        return DataItem(data_item)",
    "docstring": "Create a data item in the library from a data and metadata object.\n\n        The data for the data item will be written to disk immediately and unloaded from memory. If you wish to delay\n        writing to disk and keep using the data, create an empty data item and use the data item methods to modify\n        the data.\n\n        :param data_and_metadata: The data and metadata.\n        :param title: The title of the data item (optional).\n        :return: The new :py:class:`nion.swift.Facade.DataItem` object.\n        :rtype: :py:class:`nion.swift.Facade.DataItem`\n\n        .. versionadded:: 1.0\n\n        Scriptable: Yes"
  },
  {
    "code": "def item_transaction(self, item) -> Transaction:\n        items = self.__build_transaction_items(item)\n        transaction = Transaction(self, item, items)\n        self.__transactions.append(transaction)\n        return transaction",
    "docstring": "Begin transaction state for item.\n\n        A transaction state is exists to prevent writing out to disk, mainly for performance reasons.\n        All changes to the object are delayed until the transaction state exits.\n\n        This method is thread safe."
  },
  {
    "code": "def collections(record, key, value):\n    return {\n        'primary': value.get('a'),\n        'secondary': value.get('b'),\n        'deleted': value.get('c'),\n    }",
    "docstring": "Parse custom MARC tag 980."
  },
  {
    "code": "def scan_url(self, this_url):\n        params = {'apikey': self.api_key, 'url': this_url}\n        try:\n            response = requests.post(self.base + 'url/scan', params=params, proxies=self.proxies)\n        except requests.RequestException as e:\n            return dict(error=e.message)\n        return _return_response_and_status_code(response)",
    "docstring": "Submit a URL to be scanned by VirusTotal.\n\n        :param this_url: The URL that should be scanned. This parameter accepts a list of URLs (up to 4 with the\n                         standard request rate) so as to perform a batch scanning request with one single call. The\n                         URLs must be separated by a new line character.\n        :return: JSON response that contains scan_id and permalink."
  },
  {
    "code": "def action(args):\n    log.info('loading reference package')\n    refpkg.Refpkg(args.refpkg, create=False).strip()",
    "docstring": "Strips non-current files and rollback information from a refpkg.\n\n    *args* should be an argparse object with fields refpkg (giving the\n    path to the refpkg to operate on)."
  },
  {
    "code": "def annotate_segments(self, Z):\n        P = Z.copy()\n        P[~np.isfinite(P)] = -1\n        _, mapping = np.unique(np.cumsum(P >= 0), return_index=True)\n        dZ = Z.compressed()\n        uniq, idx = np.unique(dZ, return_inverse=True)\n        segments = []\n        for i, mean_cn in enumerate(uniq):\n            if not np.isfinite(mean_cn):\n                continue\n            for rr in contiguous_regions(idx == i):\n                segments.append((mean_cn, mapping[rr]))\n        return segments",
    "docstring": "Report the copy number and start-end segment"
  },
  {
    "code": "def get_limits(self):\n        vals = self._hook_manager.call_hook('task_limits', course=self.get_course(), task=self, default=self._limits)\n        return vals[0] if len(vals) else self._limits",
    "docstring": "Return the limits of this task"
  },
  {
    "code": "def changes(self, **kwargs):\n        path = '%s/%s/changes' % (self.manager.path, self.get_id())\n        return self.manager.gitlab.http_get(path, **kwargs)",
    "docstring": "List the merge request changes.\n\n        Args:\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabListError: If the list could not be retrieved\n\n        Returns:\n            RESTObjectList: List of changes"
  },
  {
    "code": "def for_json(self):\n        if self.multiselect:\n            return super(MultiSelectField, self).for_json()\n        value = self.get_python()\n        if hasattr(value, 'for_json'):\n            return value.for_json()\n        return value",
    "docstring": "Handle multi-select vs single-select"
  },
  {
    "code": "def _special_value_maxLength(em, newValue=NOT_PROVIDED):\n    if newValue is NOT_PROVIDED:\n        if not em.hasAttribute('maxlength'):\n            return -1\n        curValue = em.getAttribute('maxlength', '-1')\n        invalidDefault = -1\n    else:\n        curValue = newValue\n        invalidDefault = IndexSizeErrorException\n    return convertToIntRange(curValue, minValue=0, maxValue=None, emptyValue='0', invalidDefault=invalidDefault)",
    "docstring": "_special_value_maxLength - Handle the special \"maxLength\" property\n\n            @param em <AdvancedTag> - The tag element\n\n            @param newValue - Default NOT_PROVIDED, if provided will use that value instead of the\n\n                current .getAttribute value on the tag. This is because this method can be used for both validation\n                 \n                and getting/setting"
  },
  {
    "code": "def from_csv(cls, filename):\n        instance = cls()\n        instance.data = np.loadtxt(filename, delimiter=',')\n        return instance",
    "docstring": "Create gyro stream from CSV data\n\n        Load data from a CSV file.\n        The data must be formatted with three values per line: (x, y, z)\n        where x, y, z is the measured angular velocity (in radians) of the specified axis.\n\n        Parameters\n        -------------------\n        filename : str\n            Path to the CSV file\n\n        Returns\n        ---------------------\n        GyroStream\n            A gyroscope stream"
  },
  {
    "code": "def commit(cls, client=None):\n        if not client:\n            client = cls._client\n        rtn = client.write_points(cls._json_body_())\n        cls._reset_()\n        return rtn",
    "docstring": "Commit everything from datapoints via the client.\n\n        :param client: InfluxDBClient instance for writing points to InfluxDB.\n        :attention: any provided client will supersede the class client.\n        :return: result of client.write_points."
  },
  {
    "code": "def is_enable_action_dependent(self, hosts, services):\n        enable_action = False\n        for (dep_id, status, _, _) in self.act_depend_of:\n            if 'n' in status:\n                enable_action = True\n            else:\n                if dep_id in hosts:\n                    dep = hosts[dep_id]\n                else:\n                    dep = services[dep_id]\n                p_is_down = False\n                dep_match = [dep.is_state(stat) for stat in status]\n                if True in dep_match:\n                    p_is_down = True\n                if not p_is_down:\n                    enable_action = True\n        return enable_action",
    "docstring": "Check if dependencies states match dependencies statuses\n        This basically means that a dependency is in a bad state and\n        it can explain this object state.\n\n        :param hosts: hosts objects, used to get object in act_depend_of\n        :type hosts: alignak.objects.host.Hosts\n        :param services: services objects,  used to get object in act_depend_of\n        :type services: alignak.objects.service.Services\n        :return: True if all dependencies matches the status, false otherwise\n        :rtype: bool"
  },
  {
    "code": "def time(self):\n        x, _, = self._canvas_ticks.coords(self._time_marker_image)\n        return self.get_position_time(x)",
    "docstring": "Current value the time marker is pointing to\n\n        :rtype: float"
  },
  {
    "code": "def extend_extents(extents, factor=1.1):\n    width = extents[2] - extents[0]\n    height = extents[3] - extents[1]\n    add_width = (factor - 1) * width\n    add_height = (factor - 1) * height\n    x1 = extents[0] - add_width / 2\n    x2 = extents[2] + add_width / 2\n    y1 = extents[1] - add_height / 2\n    y2 = extents[3] + add_height / 2\n    return x1, y1, x2, y2",
    "docstring": "Extend a given bounding box\n\n    The bounding box (x1, y1, x2, y2) is centrally stretched by the given factor.\n\n    :param extents: The bound box extents\n    :param factor: The factor for stretching\n    :return: (x1, y1, x2, y2) of the extended bounding box"
  },
  {
    "code": "def embed(self, width=600, height=650):\n        from IPython.display import IFrame\n        return IFrame(self.url, width, height)",
    "docstring": "Embed a viewer into a Jupyter notebook."
  },
  {
    "code": "def _find_models(self, constructor, table_name, constraints=None, *, columns=None,\n                   order_by=None, limiting=None):\n    for record in self.find_all(table_name, constraints, columns=columns, order_by=order_by,\n                                limiting=limiting):\n      yield constructor(record)",
    "docstring": "Calls DataAccess.find_all and passes the results to the given constructor."
  },
  {
    "code": "def HeadList(self):\n        return [(rname, repo.currenthead) for rname, repo in self.repos.items()\n                ]",
    "docstring": "Return a list of all the currently loaded repo HEAD objects."
  },
  {
    "code": "def _create_instance_attributes(self, arguments):\n        for attribute_name, type_instance in self.getmembers():\n            if isinstance(type_instance, DataType):\n                self._templates[attribute_name] = type_instance\n                value = None\n                if attribute_name in arguments:\n                    value = arguments[attribute_name]\n                try:\n                    self._attributes[attribute_name] = type_instance.validate(value)\n                except exception.RequiredAttributeError:\n                    self._attributes[attribute_name] = None",
    "docstring": "Copies class level attribute templates and makes instance placeholders\n\n        This step is required for direct uses of Model classes. This creates a\n        copy of attribute_names ignores methods and private variables.\n        DataCollection types are deep copied to ignore memory reference conflicts.\n\n        DataType instances are initialized to None or default value."
  },
  {
    "code": "def _setup_preferred_paths(self, preferred_conversion_paths):\n        for path in preferred_conversion_paths:\n            for pair in pair_looper(path):\n                if pair not in self.converters:\n                    log.warning('Invalid conversion path %s, unknown step %s' %\n                                (repr(path), repr(pair)))\n                    break\n            else:\n                self.dgraph.add_preferred_path(*path)",
    "docstring": "Add given valid preferred conversion paths"
  },
  {
    "code": "def generateDirectoryNodeDocuments(self):\n        all_dirs = []\n        for d in self.dirs:\n            d.findNestedDirectories(all_dirs)\n        for d in all_dirs:\n            self.generateDirectoryNodeRST(d)",
    "docstring": "Generates all of the directory reStructuredText documents."
  },
  {
    "code": "def load_file_contents(file_path, as_list=True):\n    abs_file_path = join(HERE, file_path)\n    with open(abs_file_path, encoding='utf-8') as file_pointer:\n        if as_list:\n            return file_pointer.read().splitlines()\n        return file_pointer.read()",
    "docstring": "Load file as string or list"
  },
  {
    "code": "def run(self):\n        self._connect()\n        super(irc.bot.SingleServerIRCBot, self).start()",
    "docstring": "Run the bot in a thread.\n\n        Implementing the IRC listener as a thread allows it to\n        listen without blocking IRCLego's ability to listen\n        as a pykka actor.\n\n        :return: None"
  },
  {
    "code": "def render(self, data, accepted_media_type=None, renderer_context=None):\n        form = data.serializer\n        style = renderer_context.get('style', {})\n        if 'template_pack' not in style:\n            style['template_pack'] = self.template_pack\n        style['renderer'] = self\n        template_pack = style['template_pack'].strip('/')\n        template_name = template_pack + '/' + self.base_template\n        template = loader.get_template(template_name)\n        context = {\n            'form': form,\n            'style': style\n        }\n        return template_render(template, context)",
    "docstring": "Render serializer data and return an HTML form, as a string."
  },
  {
    "code": "def queue_context_entry(exchange,\n                        queue_name,\n                        routing=None):\n    if routing is None:\n        routing = queue_name\n    queue_entry = QueueContextEntry(mq_queue=queue_name,\n                                    mq_exchange=exchange,\n                                    mq_routing_key=routing)\n    return queue_entry",
    "docstring": "forms queue's context entry"
  },
  {
    "code": "def free(self):\n        if self._ptr is None:\n            return\n        Gauged.map_free(self.ptr)\n        SparseMap.ALLOCATIONS -= 1\n        self._ptr = None",
    "docstring": "Free the map"
  },
  {
    "code": "def filter_event(tag, data, defaults):\n    ret = {}\n    keys = []\n    use_defaults = True\n    for ktag in __opts__.get('filter_events', {}):\n        if tag != ktag:\n            continue\n        keys = __opts__['filter_events'][ktag]['keys']\n        use_defaults = __opts__['filter_events'][ktag].get('use_defaults', True)\n    if use_defaults is False:\n        defaults = []\n    if not isinstance(defaults, list):\n        defaults = list(defaults)\n    defaults = list(set(defaults + keys))\n    for key in defaults:\n        if key in data:\n            ret[key] = data[key]\n    return ret",
    "docstring": "Accept a tag, a dict and a list of default keys to return from the dict, and\n    check them against the cloud configuration for that tag"
  },
  {
    "code": "def get_events_for_object(self, content_object, distinction='', inherit=True):\n        ct = ContentType.objects.get_for_model(type(content_object))\n        if distinction:\n            dist_q = Q(eventrelation__distinction=distinction)\n            cal_dist_q = Q(calendar__calendarrelation__distinction=distinction)\n        else:\n            dist_q = Q()\n            cal_dist_q = Q()\n        if inherit:\n            inherit_q = Q(\n                cal_dist_q,\n                calendar__calendarrelation__content_type=ct,\n                calendar__calendarrelation__object_id=content_object.id,\n                calendar__calendarrelation__inheritable=True,\n            )\n        else:\n            inherit_q = Q()\n        event_q = Q(dist_q, eventrelation__content_type=ct, eventrelation__object_id=content_object.id)\n        return Event.objects.filter(inherit_q | event_q)",
    "docstring": "returns a queryset full of events, that relate to the object through, the\n        distinction\n\n        If inherit is false it will not consider the calendars that the events\n        belong to. If inherit is true it will inherit all of the relations and\n        distinctions that any calendar that it belongs to has, as long as the\n        relation has inheritable set to True.  (See Calendar)\n\n        >>> event = Event.objects.get(title='Test1')\n        >>> user = User.objects.get(username = 'alice')\n        >>> EventRelation.objects.get_events_for_object(user, 'owner', inherit=False)\n        [<Event: Test1: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>]\n\n        If a distinction is not declared it will not vet the relations based on\n        distinction.\n        >>> EventRelation.objects.get_events_for_object(user, inherit=False)\n        [<Event: Test1: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>, <Event: Test2: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>]\n\n        Now if there is a Calendar\n        >>> calendar = Calendar(name = 'MyProject')\n        >>> calendar.save()\n\n        And an event that belongs to that calendar\n        >>> event = Event.objects.get(title='Test2')\n        >>> calendar.events.add(event)\n\n        If we relate this calendar to some object with inheritable set to true,\n        that relation will be inherited\n        >>> user = User.objects.get(username='bob')\n        >>> cr = calendar.create_relation(user, 'viewer', True)\n        >>> EventRelation.objects.get_events_for_object(user, 'viewer')\n        [<Event: Test1: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>, <Event: Test2: Tuesday, Jan. 1, 2008-Friday, Jan. 11, 2008>]"
  },
  {
    "code": "def _altair_hline_(self, xfield, yfield, opts, style, encode):\n        try:\n            rawy = yfield\n            if \":\" in yfield:\n                rawy = yfield.split(\":\")[0]\n            mean = self.df[rawy].mean()\n            l = []\n            i = 0\n            while i < len(self.df[rawy]):\n                l.append(mean)\n                i += 1\n            self.df[\"Mean\"] = l\n            chart = Chart(self.df).mark_line(**style).encode(x=xfield, \\\n                                            y=\"Mean\", **encode).properties(**opts)\n            self.drop(\"Mean\")\n            return chart\n        except Exception as e:\n            self.err(e, \"Can not draw mean line chart\")",
    "docstring": "Get a mean line chart"
  },
  {
    "code": "def get_value(self, key):\n        for title in _TITLES.get(key, ()) + (key,):\n            try:\n                value = [entry['lastMeasurement']['value'] for entry in\n                         self.data['sensors'] if entry['title'] == title][0]\n                return value\n            except IndexError:\n                pass\n        return None",
    "docstring": "Extract a value for a given key."
  },
  {
    "code": "def wave(self, wavelength):\n        if not isinstance(wavelength, q.quantity.Quantity):\n            raise ValueError(\"Wavelength must be in length units.\")\n        self._wave = wavelength\n        self.wave_units = wavelength.unit",
    "docstring": "A setter for the wavelength\n\n        Parameters\n        ----------\n        wavelength: astropy.units.quantity.Quantity\n            The array with units"
  },
  {
    "code": "def list_resource_groups(access_token, subscription_id):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/resourceGroups/',\n                        '?api-version=', RESOURCE_API])\n    return do_get(endpoint, access_token)",
    "docstring": "List the resource groups in a subscription.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n\n    Returns:\n        HTTP response."
  },
  {
    "code": "def _get_contigs_to_keep(self, filename):\n        if filename is None:\n            return set()\n        with open(filename) as f:\n            return {line.rstrip() for line in f}",
    "docstring": "Returns a set of names from file called filename. If filename is None, returns an empty set"
  },
  {
    "code": "async def read(cls, node, block_device):\n        if isinstance(node, str):\n            system_id = node\n        elif isinstance(node, Node):\n            system_id = node.system_id\n        else:\n            raise TypeError(\n                \"node must be a Node or str, not %s\"\n                % type(node).__name__)\n        if isinstance(block_device, int):\n            block_device = block_device\n        elif isinstance(block_device, BlockDevice):\n            block_device = block_device.id\n        else:\n            raise TypeError(\n                \"node must be a Node or str, not %s\"\n                % type(block_device).__name__)\n        data = await cls._handler.read(\n            system_id=system_id, device_id=block_device)\n        return cls(\n            cls._object(item)\n            for item in data)",
    "docstring": "Get list of `Partitions`'s for `node` and `block_device`."
  },
  {
    "code": "def _auto_unlock_key_position(self):\n        found_pos = None\n        default_keyring_ids = gkr.list_item_ids_sync(self.default_keyring)\n        for pos in default_keyring_ids:\n            item_attrs = gkr.item_get_attributes_sync(self.default_keyring, pos)\n            app = 'application'\n            if item_attrs.has_key(app) and item_attrs[app] == \"opensesame\":\n                found_pos = pos\n                break\n        return found_pos",
    "docstring": "Find the open sesame password in the default keyring"
  },
  {
    "code": "def set_cumulative(self, cumulative):\n        if self.get_cumulative_metadata().is_read_only():\n            raise errors.NoAccess()\n        if not self._is_valid_boolean(cumulative):\n            raise errors.InvalidArgument()\n        self._my_map['cumulative'] = cumulative",
    "docstring": "Applies this rule to all previous assessment parts.\n\n        arg:    cumulative (boolean): ``true`` to apply to all previous\n                assessment parts. ``false`` to apply to the immediate\n                previous assessment part\n        raise:  InvalidArgument - ``cumulative`` is invalid\n        raise:  NoAccess - ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def connect_s3_bucket_to_lambda(self, bucket, function_arn, events,\n                                    prefix=None, suffix=None):\n        s3 = self._client('s3')\n        existing_config = s3.get_bucket_notification_configuration(\n            Bucket=bucket)\n        existing_config.pop('ResponseMetadata', None)\n        existing_lambda_config = existing_config.get(\n            'LambdaFunctionConfigurations', [])\n        single_config = {\n            'LambdaFunctionArn': function_arn, 'Events': events\n        }\n        filter_rules = []\n        if prefix is not None:\n            filter_rules.append({'Name': 'Prefix', 'Value': prefix})\n        if suffix is not None:\n            filter_rules.append({'Name': 'Suffix', 'Value': suffix})\n        if filter_rules:\n            single_config['Filter'] = {'Key': {'FilterRules': filter_rules}}\n        new_config = self._merge_s3_notification_config(existing_lambda_config,\n                                                        single_config)\n        existing_config['LambdaFunctionConfigurations'] = new_config\n        s3.put_bucket_notification_configuration(\n            Bucket=bucket,\n            NotificationConfiguration=existing_config,\n        )",
    "docstring": "Configure S3 bucket to invoke a lambda function.\n\n        The S3 bucket must already have permission to invoke the\n        lambda function before you call this function, otherwise\n        the service will return an error.  You can add permissions\n        by using the ``add_permission_for_s3_event`` below.  The\n        ``events`` param matches the event strings supported by the\n        service.\n\n        This method also only supports a single prefix/suffix for now,\n        which is what's offered in the Lambda console."
  },
  {
    "code": "def _buffer_decode(self, input, errors, final):\n        decoded_segments = []\n        position = 0\n        while True:\n            decoded, consumed = self._buffer_decode_step(\n                input[position:],\n                errors,\n                final\n            )\n            if consumed == 0:\n                break\n            decoded_segments.append(decoded)\n            position += consumed\n        if final:\n            assert position == len(input)\n        return ''.join(decoded_segments), position",
    "docstring": "Decode bytes that may be arriving in a stream, following the Codecs\n        API.\n\n        `input` is the incoming sequence of bytes. `errors` tells us how to\n        handle errors, though we delegate all error-handling cases to the real\n        UTF-8 decoder to ensure correct behavior. `final` indicates whether\n        this is the end of the sequence, in which case we should raise an\n        error given incomplete input.\n\n        Returns as much decoded text as possible, and the number of bytes\n        consumed."
  },
  {
    "code": "def label_from_re(self, pat:str, full_path:bool=False, label_cls:Callable=None, **kwargs)->'LabelList':\n        \"Apply the re in `pat` to determine the label of every filename.  If `full_path`, search in the full name.\"\n        pat = re.compile(pat)\n        def _inner(o):\n            s = str((os.path.join(self.path,o) if full_path else o).as_posix())\n            res = pat.search(s)\n            assert res,f'Failed to find \"{pat}\" in \"{s}\"'\n            return res.group(1)\n        return self.label_from_func(_inner, label_cls=label_cls, **kwargs)",
    "docstring": "Apply the re in `pat` to determine the label of every filename.  If `full_path`, search in the full name."
  },
  {
    "code": "def group_device_names(devices, group_size):\n    num_devices = len(devices)\n    if group_size > num_devices:\n        raise ValueError(\n            \"only %d devices, but group_size=%d\" % (num_devices, group_size))\n    num_groups = (\n        num_devices // group_size + (1 if\n                                     (num_devices % group_size != 0) else 0))\n    groups = [[] for i in range(num_groups)]\n    for i in range(0, num_groups * group_size):\n        groups[i % num_groups].append(devices[i % num_devices])\n    return groups",
    "docstring": "Group device names into groups of group_size.\n\n  Args:\n    devices: list of strings naming devices.\n    group_size: int >= 1\n\n  Returns:\n    list of lists of devices, where each inner list is group_size long,\n      and each device appears at least once in an inner list.  If\n      len(devices) % group_size = 0 then each device will appear\n      exactly once.\n\n  Raises:\n    ValueError: group_size > len(devices)"
  },
  {
    "code": "def get_email(self, token):\n        resp = requests.get(self.emails_url,\n                            params={'access_token': token.token})\n        emails = resp.json().get('values', [])\n        email = ''\n        try:\n            email = emails[0].get('email')\n            primary_emails = [e for e in emails if e.get('is_primary', False)]\n            email = primary_emails[0].get('email')\n        except (IndexError, TypeError, KeyError):\n            return ''\n        finally:\n            return email",
    "docstring": "Fetches email address from email API endpoint"
  },
  {
    "code": "def _random_ipv4_address_from_subnet(self, subnet, network=False):\n        address = str(\n            subnet[self.generator.random.randint(\n                0, subnet.num_addresses - 1,\n            )],\n        )\n        if network:\n            address += '/' + str(self.generator.random.randint(\n                subnet.prefixlen,\n                subnet.max_prefixlen,\n            ))\n            address = str(ip_network(address, strict=False))\n        return address",
    "docstring": "Produces a random IPv4 address or network with a valid CIDR\n        from within a given subnet.\n\n        :param subnet: IPv4Network to choose from within\n        :param network: Return a network address, and not an IP address"
  },
  {
    "code": "def color_normalize(src, mean, std=None):\n    if mean is not None:\n        src -= mean\n    if std is not None:\n        src /= std\n    return src",
    "docstring": "Normalize src with mean and std.\n\n    Parameters\n    ----------\n    src : NDArray\n        Input image\n    mean : NDArray\n        RGB mean to be subtracted\n    std : NDArray\n        RGB standard deviation to be divided\n\n    Returns\n    -------\n    NDArray\n        An `NDArray` containing the normalized image."
  },
  {
    "code": "def get_site_decorator(site_param='site', obj_param='obj', context_param='context'):\n    def site_method(**extra_params):\n        def decorator(fn):\n            @wraps(fn)\n            def wrapper(request, **kwargs):\n                try:\n                    site = kwargs.pop(site_param)\n                except KeyError:\n                    raise ValueError(\"'%s' parameter must be passed to \"\n                                     \"decorated view (%s)\" % (site_param, fn))\n                params={}\n                for key in extra_params:\n                    value = kwargs.pop(key, extra_params[key])\n                    params.update({key:value})\n                try:\n                    obj = site.object_getter(**kwargs)\n                except models.ObjectDoesNotExist:\n                    raise Http404(\"Base object does not exist.\")\n                context = site.get_common_context(obj)\n                context_instance = RequestContext(request, context,\n                                       processors=site.context_processors)\n                params.update({\n                                site_param:site,\n                                obj_param: obj,\n                                context_param: context_instance\n                             })\n                return fn(request, **params)\n            return wrapper\n        return decorator\n    return site_method",
    "docstring": "It is a function that returns decorator factory useful for PluggableSite\n        views. This decorator factory returns decorator that do some\n        boilerplate work and make writing PluggableSite views easier.\n        It passes PluggableSite instance to decorated view,\n        retreives and passes object that site is attached to and passes\n        common context. It also passes and all the decorator factory's\n        keyword arguments.\n\n        For example usage please check photo_albums.views.\n\n        Btw, this decorator seems frightening for me. It feels that\n        \"views as PluggableSite methods\" approach can easily make this decorator\n        obsolete. But for now it just works."
  },
  {
    "code": "def onEnable(self):\n        trace('onEnable')\n        self._disable()\n        self._aio_context.submit(self._aio_recv_block_list)\n        self._real_onCanSend()\n        self._enabled = True",
    "docstring": "The configuration containing this function has been enabled by host.\n        Endpoints become working files, so submit some read operations."
  },
  {
    "code": "def set_margins(self, left,top,right=-1):\n        \"Set left, top and right margins\"\n        self.l_margin=left\n        self.t_margin=top\n        if(right==-1):\n            right=left\n        self.r_margin=right",
    "docstring": "Set left, top and right margins"
  },
  {
    "code": "def write_header(self):\n        for properties in self.header.values():\n            value = properties['value']\n            offset_bytes = int(properties['offset'])\n            self.file.seek(offset_bytes)\n            value.tofile(self.file)",
    "docstring": "Write `header` to `file`.\n\n        See Also\n        --------\n        write_data"
  },
  {
    "code": "def performance_view(dstore):\n    data = sorted(dstore['performance_data'], key=operator.itemgetter(0))\n    out = []\n    for operation, group in itertools.groupby(data, operator.itemgetter(0)):\n        counts = 0\n        time = 0\n        mem = 0\n        for _operation, time_sec, memory_mb, counts_ in group:\n            counts += counts_\n            time += time_sec\n            mem = max(mem, memory_mb)\n        out.append((operation, time, mem, counts))\n    out.sort(key=operator.itemgetter(1), reverse=True)\n    return numpy.array(out, perf_dt)",
    "docstring": "Returns the performance view as a numpy array."
  },
  {
    "code": "def receive_message(self):\n        if not ('REQUEST_METHOD' in os.environ\n                and os.environ['REQUEST_METHOD'] == 'POST'):\n            print(\"Status: 405 Method not Allowed; only POST is accepted\")\n            exit(0)\n        content_length = int(os.environ['CONTENT_LENGTH'])\n        request_json = sys.stdin.read(content_length)\n        request_json = urlparse.unquote(request_json)\n        return None, request_json",
    "docstring": "Receive a message from the transport.\n\n        Blocks until a message has been received. May return a context\n        opaque to clients that should be passed to :py:func:`send_reply`\n        to identify the client later on.\n\n        :return: A tuple consisting of ``(context, message)``."
  },
  {
    "code": "def cartesian_square_centred_on_point(self, point, distance, **kwargs):\n        point_surface = Point(point.longitude, point.latitude, 0.)\n        north_point = point_surface.point_at(distance, 0., 0.)\n        east_point = point_surface.point_at(distance, 0., 90.)\n        south_point = point_surface.point_at(distance, 0., 180.)\n        west_point = point_surface.point_at(distance, 0., 270.)\n        is_long = np.logical_and(\n            self.catalogue.data['longitude'] >= west_point.longitude,\n            self.catalogue.data['longitude'] < east_point.longitude)\n        is_surface = np.logical_and(\n            is_long,\n            self.catalogue.data['latitude'] >= south_point.latitude,\n            self.catalogue.data['latitude'] < north_point.latitude)\n        upper_depth, lower_depth = _check_depth_limits(kwargs)\n        is_valid = np.logical_and(\n            is_surface,\n            self.catalogue.data['depth'] >= upper_depth,\n            self.catalogue.data['depth'] < lower_depth)\n        return self.select_catalogue(is_valid)",
    "docstring": "Select earthquakes from within a square centered on a point\n\n        :param point:\n            Centre point as instance of nhlib.geo.point.Point class\n\n        :param distance:\n            Distance (km)\n\n        :returns:\n            Instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue`\n            class containing only selected events"
  },
  {
    "code": "def get_token(url: str, scopes: str, credentials_dir: str) -> dict:\n    tokens.configure(url=url, dir=credentials_dir)\n    tokens.manage('lizzy', [scopes])\n    tokens.start()\n    return tokens.get('lizzy')",
    "docstring": "Get access token info."
  },
  {
    "code": "def link_label(link):\n        if hasattr(link, 'label'):\n            label = link.label\n        else:\n            label = str(link.linknum+1)\n        return label",
    "docstring": "return a link label as a string"
  },
  {
    "code": "def generate_data_for_env_problem(problem_name):\n  assert FLAGS.env_problem_max_env_steps > 0, (\"--env_problem_max_env_steps \"\n                                               \"should be greater than zero\")\n  assert FLAGS.env_problem_batch_size > 0, (\"--env_problem_batch_size should be\"\n                                            \" greather than zero\")\n  problem = registry.env_problem(problem_name)\n  task_id = None if FLAGS.task_id < 0 else FLAGS.task_id\n  data_dir = os.path.expanduser(FLAGS.data_dir)\n  tmp_dir = os.path.expanduser(FLAGS.tmp_dir)\n  problem.initialize(batch_size=FLAGS.env_problem_batch_size)\n  env_problem_utils.play_env_problem_randomly(\n      problem, num_steps=FLAGS.env_problem_max_env_steps)\n  problem.generate_data(data_dir=data_dir, tmp_dir=tmp_dir, task_id=task_id)",
    "docstring": "Generate data for `EnvProblem`s."
  },
  {
    "code": "def _merge_assets_key_collection(saved_model_proto, path):\n  for meta_graph in saved_model_proto.meta_graphs:\n    node_asset_map = {}\n    if tf_v1.saved_model.constants.ASSETS_KEY in meta_graph.collection_def:\n      assets_any_proto = meta_graph.collection_def[\n          tf_v1.saved_model.constants.ASSETS_KEY].any_list.value\n      for asset_any_proto in assets_any_proto:\n        asset_proto = meta_graph_pb2.AssetFileDef()\n        asset_any_proto.Unpack(asset_proto)\n        asset_filename = _get_asset_filename(path, asset_proto.filename)\n        node_asset_map[_get_node_name_from_tensor(\n            asset_proto.tensor_info.name)] = asset_filename\n      del meta_graph.collection_def[tf_v1.saved_model.constants.ASSETS_KEY]\n    for node in meta_graph.graph_def.node:\n      asset_filepath = node_asset_map.get(node.name)\n      if asset_filepath:\n        _check_asset_node_def(node)\n        node.attr[\"value\"].tensor.string_val[0] = asset_filepath",
    "docstring": "Merges the ASSETS_KEY collection into the GraphDefs in saved_model_proto.\n\n  Removes the ASSETS_KEY collection from the GraphDefs in the SavedModel and\n  modifies nodes with the assets filenames to point to the assets in `path`.\n  After this transformation, the SavedModel GraphDefs can be used without\n  feeding asset tensors.\n\n  Args:\n    saved_model_proto: SavedModel proto to be modified.\n    path: path where the SavedModel is being loaded from."
  },
  {
    "code": "def remove(package_name):\n    if package_name not in packages:\n        raise HolodeckException(\"Unknown package name \" + package_name)\n    for config, path in _iter_packages():\n        if config[\"name\"] == package_name:\n            shutil.rmtree(path)",
    "docstring": "Removes a holodeck package.\n\n    Args:\n        package_name (str): the name of the package to remove"
  },
  {
    "code": "def date_parser(items):\n    try:\n        dt = datetime.strptime(items,\"%d/%m/%Y %H:%M:%S\")\n    except Exception as e:\n        try:\n            dt = datetime.strptime(items,\"%m/%d/%Y %H:%M:%S\")\n        except Exception as ee:\n            raise Exception(\"error parsing datetime string\" +\\\n                            \" {0}: \\n{1}\\n{2}\".format(str(items),str(e),str(ee)))\n    return dt",
    "docstring": "datetime parser to help load smp files\n\n    Parameters\n    ----------\n    items : iterable\n        something or somethings to try to parse into datetimes\n\n    Returns\n    -------\n    dt : iterable\n        the cast datetime things"
  },
  {
    "code": "def processPhoneList(platformNames=[], numbers=[], excludePlatformNames=[]):\n    platforms = platform_selection.getPlatformsByName(platformNames, mode=\"phonefy\", excludePlatformNames=excludePlatformNames)\n    results = []\n    for num in numbers:\n        for pla in platforms:\n            entities = pla.getInfo(query=num, process=True, mode=\"phonefy\")\n            if entities != {}:\n                results+=json.loads(entities)\n    return results",
    "docstring": "Method to perform searchs on a series of numbers.\n\n    Args:\n    -----\n        platformNames: List of names of the platforms.\n        numbers: List of numbers to be queried.\n        excludePlatformNames: A list of platforms not to be searched.\n\n    Return:\n    -------\n        A list of verified emails."
  },
  {
    "code": "def is_not_from_subdomain(self, response, site_dict):\n        root_url = re.sub(re_url_root, '', site_dict[\"url\"])\n        return UrlExtractor.get_allowed_domain(response.url) == root_url",
    "docstring": "Ensures the response's url isn't from a subdomain.\n\n        :param obj response: The scrapy response\n        :param dict site_dict: The site object from the JSON-File\n\n        :return bool: Determines if the response's url is from a subdomain"
  },
  {
    "code": "def _on_write(self, sender, *args, **kwargs):\n        self.on_write(data=kwargs.get('data', None))",
    "docstring": "Internal handler for writing to the device."
  },
  {
    "code": "def unicode2str(content):\n    if isinstance(content, dict):\n        result = {}\n        for key in content.keys():\n            result[unicode2str(key)] = unicode2str(content[key])\n        return result\n    elif isinstance(content, list):\n        return [unicode2str(element) for element in content]\n    elif isinstance(content, int) or isinstance(content, float):\n        return content\n    else:\n        return content.encode(\"utf-8\")",
    "docstring": "Convert the unicode element of the content to str recursively."
  },
  {
    "code": "def exact(self, *args, **kwargs):\n        compare = Exact(*args, **kwargs)\n        self.add(compare)\n        return self",
    "docstring": "Compare attributes of pairs exactly.\n\n        Shortcut of :class:`recordlinkage.compare.Exact`::\n\n            from recordlinkage.compare import Exact\n\n            indexer = recordlinkage.Compare()\n            indexer.add(Exact())"
  },
  {
    "code": "def _get(self, key, section=None, default=_onion_dict_guard):\n        if section is not None:\n            section_dict = self.__sections.get(section, {})\n            if key in section_dict:\n                return section_dict[key]\n        for d in self.__dictionaries:\n            if key in d:\n                return d[key]\n        if default is _onion_dict_guard:\n            raise KeyError(key)\n        else:\n            return default",
    "docstring": "Try to get the key from each dict in turn.\n        If you specify the optional section it looks there first."
  },
  {
    "code": "def _bool_encode(self, d):\n        for k, v in d.items():\n            if isinstance(v, bool):\n                d[k] = str(v).lower()\n        return d",
    "docstring": "Converts bool values to lowercase strings"
  },
  {
    "code": "def getlist(self, section, option, raw=False, vars=None, fallback=[], delimiters=','):\n        v = self.get(section, option, raw=raw, vars=vars, fallback=fallback)\n        return self._convert_to_list(v, delimiters=delimiters)",
    "docstring": "A convenience method which coerces the option in the specified section to a list of strings."
  },
  {
    "code": "def disposal_date(self):\n        date_sampled = self.getDateSampled()\n        if not date_sampled:\n            return None\n        retention_period = self.getSampleType().getRetentionPeriod() or {}\n        retention_period_delta = timedelta(\n            days=int(retention_period.get(\"days\", 0)),\n            hours=int(retention_period.get(\"hours\", 0)),\n            minutes=int(retention_period.get(\"minutes\", 0))\n        )\n        return dt2DT(DT2dt(date_sampled) + retention_period_delta)",
    "docstring": "Returns the date the retention period ends for this sample based on\n        the retention period from the Sample Type. If the sample hasn't been\n        collected yet, returns None"
  },
  {
    "code": "def figures(df,specs,asList=False):\n\tfigs=[]\n\tfor spec in specs:\n\t\tfigs.append(df.figure(**spec))\n\tif asList:\n\t\treturn figs\n\telse:\n\t\treturn merge_figures(figs)",
    "docstring": "Generates multiple Plotly figures for a given DataFrame\n\n\tParameters:\n\t-----------\n\t\tdf : DataFrame\n\t\t\tPandas DataFrame\n\t\tspecs : list(dict)\n\t\t\tList of dictionaries with the properties\n\t\t\tof each figure.\n\t\t\tAll properties avaialbe can be seen with\n\t\t\thelp(cufflinks.pd.DataFrame.iplot)\n\t\tasList : boolean\n\t\t\tIf True, then a list of figures is returned.\n\t\t\tOtherwise a single (merged) figure is returned.\n\t\t\tDefault : False"
  },
  {
    "code": "def GetItemContainerInfo(self_link, alt_content_path, id_from_response):\n    self_link = TrimBeginningAndEndingSlashes(self_link) + '/'\n    index = IndexOfNth(self_link, '/', 4)\n    if index != -1:\n        collection_id = self_link[0:index]\n        if 'colls' in self_link:\n            index_second_slash = IndexOfNth(alt_content_path, '/', 2)\n            if index_second_slash == -1:\n                collection_name = alt_content_path + '/colls/' + urllib_quote(id_from_response)\n                return collection_id, collection_name\n            else:\n                collection_name = alt_content_path\n                return collection_id, collection_name\n        else:\n            raise ValueError('Response Not from Server Partition, self_link: {0}, alt_content_path: {1}, id: {2}'\n                .format(self_link, alt_content_path, id_from_response))\n    else:\n        raise ValueError('Unable to parse document collection link from ' + self_link)",
    "docstring": "Given the self link and alt_content_path from the reponse header and result\n        extract the collection name and collection id\n\n        Ever response header has alt-content-path that is the \n        owner's path in ascii. For document create / update requests, this can be used\n        to get the collection name, but for collection create response, we can't use it.\n        So we also rely on  \n\n    :param str self_link:\n        Self link of the resource, as obtained from response result.\n    :param str alt_content_path:\n        Owner path of the resource, as obtained from response header.\n    :param str resource_id:\n        'id' as returned from the response result. This is only used if it is deduced that the\n         request was to create a collection.\n\n    :return:\n        tuple of (collection rid, collection name)\n    :rtype: tuple"
  },
  {
    "code": "def set_process(self, process = None):\n        if process is None:\n            self.dwProcessId = None\n            self.__process   = None\n        else:\n            self.__load_Process_class()\n            if not isinstance(process, Process):\n                msg  = \"Parent process must be a Process instance, \"\n                msg += \"got %s instead\" % type(process)\n                raise TypeError(msg)\n            self.dwProcessId = process.get_pid()\n            self.__process = process",
    "docstring": "Manually set the parent Process object. Use with care!\n\n        @type  process: L{Process}\n        @param process: (Optional) Process object. Use C{None} for no process."
  },
  {
    "code": "def add_grant(self, grant):\n        if hasattr(grant, \"expires_in\"):\n            self.token_generator.expires_in[grant.grant_type] = grant.expires_in\n        if hasattr(grant, \"refresh_expires_in\"):\n            self.token_generator.refresh_expires_in = grant.refresh_expires_in\n        self.grant_types.append(grant)",
    "docstring": "Adds a Grant that the provider should support.\n\n        :param grant: An instance of a class that extends\n                      :class:`oauth2.grant.GrantHandlerFactory`\n        :type grant: oauth2.grant.GrantHandlerFactory"
  },
  {
    "code": "def estimate(self, maxiter=250, convergence=1e-7):\n        self.loglik = np.zeros(maxiter)\n        iter = 0\n        while iter < maxiter:\n            self.loglik[iter] = self.E_step()\n            if np.isnan(self.loglik[iter]):\n                    print(\"undefined log-likelihood\")\n                    break\n            self.M_step()\n            if self.loglik[iter] - self.loglik[iter - 1] < 0 and iter > 0:\n                    print(\"log-likelihood decreased by %f at iteration %d\"\n                          % (self.loglik[iter] - self.loglik[iter - 1],\n                             iter))\n            elif self.loglik[iter] - self.loglik[iter - 1] < convergence \\\n                    and iter > 0:\n                    print(\"convergence at iteration %d, loglik = %f\" %\n                           (iter, self.loglik[iter]))\n                    self.loglik = self.loglik[self.loglik < 0]\n                    break\n            iter += 1",
    "docstring": "run EM algorithm until convergence, or until maxiter reached"
  },
  {
    "code": "def get_periodic_soap_locals(obj, Hpos, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0):\n    suce = _get_supercell(obj, rCut)\n    arrsoap = get_soap_locals(suce, Hpos, alp, bet, rCut, nMax=nMax, Lmax=Lmax, crossOver=crossOver, all_atomtypes=all_atomtypes, eta=eta)\n    return arrsoap",
    "docstring": "Get the RBF basis SOAP output for the given position in a periodic system.\n\n    Args:\n        obj(ase.Atoms): Atomic structure for which the SOAP output is\n            calculated.\n        alp: Alphas\n        bet: Betas\n        rCut: Radial cutoff.\n        nMax: Maximum nmber of radial basis functions\n        Lmax: Maximum spherical harmonics degree\n        crossOver:\n        all_atomtypes: Can be used to specify the atomic elements for which to\n            calculate the output. If given the output is calculated only for the\n            given species.\n        eta: The gaussian smearing width.\n\n    Returns:\n        np.ndarray: SOAP output for the given position."
  },
  {
    "code": "def get_network_versions(self, name: str) -> Set[str]:\n        return {\n            version\n            for version, in self.session.query(Network.version).filter(Network.name == name).all()\n        }",
    "docstring": "Return all of the versions of a network with the given name."
  },
  {
    "code": "def rescale_around1(self, times):\n        if self._unit == self._UNIT_STEP:\n            return times, 'step'\n        m = np.mean(times)\n        mult = 1.0\n        cur_unit = self._unit\n        if (m < 0.001):\n            while mult*m < 0.001 and cur_unit >= 0:\n                mult *= 1000\n                cur_unit -= 1\n            return mult*times, self._unit_names[cur_unit]\n        if (m > 1000):\n            while mult*m > 1000 and cur_unit <= 5:\n                mult /= 1000\n                cur_unit += 1\n            return mult*times, self._unit_names[cur_unit]\n        return times, self._unit",
    "docstring": "Suggests a rescaling factor and new physical time unit to balance the given time multiples around 1.\n\n        Parameters\n        ----------\n        times : float array\n            array of times in multiple of the present elementary unit"
  },
  {
    "code": "def gt(name, value):\n    ret = {'name': name,\n           'result': False,\n           'comment': '',\n           'changes': {}}\n    if name not in __reg__:\n        ret['result'] = False\n        ret['comment'] = 'Value {0} not in register'.format(name)\n        return ret\n    if __reg__[name]['val'] > value:\n        ret['result'] = True\n    return ret",
    "docstring": "Only succeed if the value in the given register location is greater than\n    the given value\n\n    USAGE:\n\n    .. code-block:: yaml\n\n        foo:\n          check.gt:\n            - value: 42\n\n        run_remote_ex:\n          local.cmd:\n            - tgt: '*'\n            - func: test.ping\n            - require:\n              - check: foo"
  },
  {
    "code": "def handle_collect(self, msg):\n        (success, sequence_number, comment) = self._handle_collect(msg)\n        self.collector.send_multipart(msgs.MessageWriter().bool(success).uint64(sequence_number).string(comment).get())",
    "docstring": "handle an incoming message"
  },
  {
    "code": "def eliminate(self, node, data):\n        self.eliminated[node] = data\n        others = self.checks[node]\n        del self.checks[node]\n        for check in others:\n            check.check ^= data\n            check.src_nodes.remove(node)\n            if len(check.src_nodes) == 1:\n                yield (next(iter(check.src_nodes)), check.check)",
    "docstring": "Resolves a source node, passing the message to all associated checks"
  },
  {
    "code": "def result(self):\n        final_result = {'epoch_idx': self.global_epoch_idx}\n        for key, value in self.frozen_results.items():\n            final_result[key] = value\n        return final_result",
    "docstring": "Return the epoch result"
  },
  {
    "code": "def load_json(cls, data, default_rule=None, raise_error=False):\n        rules = {k: _parser.parse_rule(v, raise_error)\n                 for k, v in json.loads(data).items()}\n        return cls(rules, default_rule)",
    "docstring": "Allow loading of JSON rule data."
  },
  {
    "code": "def from_section(cls, stream, section_name='.pic'):\n        binary = Executable(stream)\n        section_data = binary.get_section_data(section_name)\n        return cls(section_data, binary.system)",
    "docstring": "Construct a Converter object from the specified section\n        of the specified binary stream."
  },
  {
    "code": "def inMicrolensRegion(ra_deg, dec_deg, padding=0):\n    fov = getKeplerFov(9)\n    try:\n        ch, col, row = fov.getChannelColRow(ra_deg, dec_deg,\n                                            allowIllegalReturnValues=False)\n        return maskInMicrolensRegion(ch, col, row, padding=padding)\n    except ValueError:\n        return False",
    "docstring": "Returns `True` if the given sky oordinate falls on the K2C9 superstamp.\n\n    Parameters\n    ----------\n    ra_deg : float\n        Right Ascension (J2000) in decimal degrees.\n\n    dec_deg : float\n        Declination (J2000) in decimal degrees.\n\n    padding : float\n        Target must be at least `padding` pixels away from the edge of the\n        superstamp. (Note that CCD boundaries are not considered as edges\n        in this case.)\n\n    Returns\n    -------\n    onMicrolensRegion : bool\n        `True` if the given coordinate is within the K2C9 microlens superstamp."
  },
  {
    "code": "def import_class(klass):\n    mod = __import__(klass.rpartition('.')[0])\n    for segment in klass.split('.')[1:-1]:\n        mod = getattr(mod, segment)\n    return getattr(mod, klass.rpartition('.')[2])",
    "docstring": "Import the named class and return that class"
  },
  {
    "code": "def get_organization(self, organization_id):\n        url = 'rest/servicedeskapi/organization/{}'.format(organization_id)\n        return self.get(url, headers=self.experimental_headers)",
    "docstring": "Get an organization for a given organization ID\n\n        :param organization_id: str\n        :return: Organization"
  },
  {
    "code": "def set_scope(self, http_method, scope):\n        for con in self.conditions:\n            if http_method in con['httpMethods']:\n                if isinstance(scope, list):\n                    con['scopes'] = scope\n                elif isinstance(scope, str) or isinstance(scope, unicode):\n                    con['scopes'].append(scope)\n                return\n        if isinstance(scope, list):\n            self.conditions.append({'httpMethods': [http_method],\n                                    'scopes': scope})\n        elif isinstance(scope, str) or isinstance(scope, unicode):\n            self.conditions.append({'httpMethods': [http_method],\n                                    'scopes': [scope]})",
    "docstring": "Set a scope condition for the resource for a http_method\n\n        Parameters:\n            * **http_method (str):** HTTP method like GET, POST, PUT, DELETE\n            * **scope (str, list):** the scope of access control as str if single, or as a list of strings if multiple scopes are to be set"
  },
  {
    "code": "def where(cls, session, include=None, metadata=None, filter=None):\n        url = session._build_url(cls._resource_path())\n        params = build_request_include(include, None)\n        if metadata is not None:\n            params['filter[metadata]'] = to_json(metadata)\n        process = cls._mk_many(session, include=include, filter=filter)\n        return session.get(url, CB.json(200, process), params=params)",
    "docstring": "Get filtered resources of the given resource class.\n\n        This should be called on sub-classes only.\n\n        The include argument allows relationship fetches to be\n        optimized by including the target resources in the request of\n        the containing resource. For example::\n\n        .. code-block:: python\n\n            org = Organization.singleton(session, include=[Sensor])\n            org.sensors(use_included=True)\n\n        Will fetch the sensors for the authorized organization as part\n        of retrieving the organization. The ``use_included`` forces\n        the use of included resources and avoids making a separate\n        request to get the sensors for the organization.\n\n        The metadata argument enables filtering on resources that\n        support metadata filters. For example::\n\n        .. code-block:: python\n\n            sensors = Sensor.where(session, metadata={ 'asset_id': '23456' })\n\n        Will fetch all sensors that match the given metadata attribute.\n\n        The filter argument enables filtering the resulting resources\n        based on a passed in function. For example::\n\n        .. code-block::python\n\n            sensors = Sensor.where(session, filter=lambda s: s.name.startswith(\"a\"))\n\n        Will fetch all sensors and apply the given filter to only\n        return sensors who's name start with the given string.\n\n\n        Args:\n\n            session(Session): The session to look up the resources in\n\n        Keyword Args:\n\n            incldue(list): The resource classes to include in the\n                request.\n\n            metadata(dict or list): The metadata filter to apply\n\n        Returns:\n\n            iterable(Resource): An iterator over all found resources\n                of this type"
  },
  {
    "code": "def prepareToSolve(self):\n        self.setAndUpdateValues(self.solution_next,self.IncomeDstn,self.LivPrb,self.DiscFac)\n        self.defBoroCnst(self.BoroCnstArt)",
    "docstring": "Perform preparatory work before calculating the unconstrained consumption\n        function.\n\n        Parameters\n        ----------\n        none\n\n        Returns\n        -------\n        none"
  },
  {
    "code": "def check_aggregations_privacy(self, aggregations_params):\n        fields = self.get_aggregations_fields(aggregations_params)\n        fields_dict = dictset.fromkeys(fields)\n        fields_dict['_type'] = self.view.Model.__name__\n        try:\n            validate_data_privacy(self.view.request, fields_dict)\n        except wrappers.ValidationError as ex:\n            raise JHTTPForbidden(\n                'Not enough permissions to aggregate on '\n                'fields: {}'.format(ex))",
    "docstring": "Check per-field privacy rules in aggregations.\n\n        Privacy is checked by making sure user has access to the fields\n        used in aggregations."
  },
  {
    "code": "def get_handler(self, handler_input, exception):\n        for handler in self.exception_handlers:\n            if handler.can_handle(\n                    handler_input=handler_input, exception=exception):\n                return handler\n        return None",
    "docstring": "Get the exception handler that can handle the input and\n        exception.\n\n        :param handler_input: Generic input passed to the\n            dispatcher.\n        :type handler_input: Input\n        :param exception: Exception thrown by\n            :py:class:`ask_sdk_runtime.dispatch.GenericRequestDispatcher`\n            dispatch method.\n        :type exception: Exception\n        :return: Exception Handler that can handle the input or None.\n        :rtype: Union[None, ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler]"
  },
  {
    "code": "def __select_text_under_cursor_blocks(self, cursor):\n        start_block = self.document().findBlock(cursor.selectionStart()).firstLineNumber()\n        end_block = self.document().findBlock(cursor.selectionEnd()).firstLineNumber()\n        cursor.setPosition(self.document().findBlockByLineNumber(start_block).position())\n        cursor.movePosition(QTextCursor.StartOfLine, QTextCursor.MoveAnchor)\n        cursor.movePosition(QTextCursor.Down, QTextCursor.KeepAnchor, end_block - start_block)\n        cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor)",
    "docstring": "Selects the document text under cursor blocks.\n\n        :param cursor: Cursor.\n        :type cursor: QTextCursor"
  },
  {
    "code": "def _parse_data_desc(data_names, label_names, data_shapes, label_shapes):\n    data_shapes = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in data_shapes]\n    _check_names_match(data_names, data_shapes, 'data', True)\n    if label_shapes is not None:\n        label_shapes = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in label_shapes]\n        _check_names_match(label_names, label_shapes, 'label', False)\n    else:\n        _check_names_match(label_names, [], 'label', False)\n    return data_shapes, label_shapes",
    "docstring": "parse data_attrs into DataDesc format and check that names match"
  },
  {
    "code": "def maps(map_id=None, lang=\"en\"):\n    if map_id:\n        cache_name = \"maps.%s.%s.json\" % (map_id, lang)\n        params = {\"map_id\": map_id, \"lang\": lang}\n    else:\n        cache_name = \"maps.%s.json\" % lang\n        params = {\"lang\": lang}\n    data = get_cached(\"maps.json\", cache_name, params=params).get(\"maps\")\n    return data.get(str(map_id)) if map_id else data",
    "docstring": "This resource returns details about maps in the game, including details\n    about floor and translation data on how to translate between world\n    coordinates and map coordinates.\n\n    :param map_id: Only list this map.\n    :param lang: Show localized texts in the specified language.\n\n    The response is a dictionary where the key is the map id and the value is\n    a dictionary containing the following properties:\n\n    map_name (string)\n        The map name.\n\n    min_level (number)\n        The minimal level of this map.\n\n    max_level (number)\n        The maximum level of this map.\n\n    default_floor (number)\n        The default floor of this map.\n\n    floors (list)\n        A list of available floors for this map.\n\n    region_id (number)\n        The id of the region this map belongs to.\n\n    region_name (string)\n        The name of the region this map belongs to.\n\n    continent_id (number)\n        The id of the continent this map belongs to.\n\n    continent_name (string)\n        The name of the continent this map belongs to.\n\n    map_rect (rect)\n        The dimensions of the map.\n\n    continent_rect (rect)\n        The dimensions of the map within the continent coordinate system.\n\n    If a map_id is given, only the values for that map are returned."
  },
  {
    "code": "def sample(self, size=(), rule=\"R\", antithetic=None):\n        size_ = numpy.prod(size, dtype=int)\n        dim = len(self)\n        if dim > 1:\n            if isinstance(size, (tuple, list, numpy.ndarray)):\n                shape = (dim,) + tuple(size)\n            else:\n                shape = (dim, size)\n        else:\n            shape = size\n        from . import sampler\n        out = sampler.generator.generate_samples(\n            order=size_, domain=self, rule=rule, antithetic=antithetic)\n        try:\n            out = out.reshape(shape)\n        except:\n            if len(self) == 1:\n                out = out.flatten()\n            else:\n                out = out.reshape(dim, int(out.size/dim))\n        return out",
    "docstring": "Create pseudo-random generated samples.\n\n        By default, the samples are created using standard (pseudo-)random\n        samples. However, if needed, the samples can also be created by either\n        low-discrepancy sequences, and/or variance reduction techniques.\n\n        Changing the sampling scheme, use the following ``rule`` flag:\n\n        +-------+-------------------------------------------------+\n        | key   | Description                                     |\n        +=======+=================================================+\n        | ``C`` | Roots of the first order Chebyshev polynomials. |\n        +-------+-------------------------------------------------+\n        | ``NC``| Chebyshev nodes adjusted to ensure nested.      |\n        +-------+-------------------------------------------------+\n        | ``K`` | Korobov lattice.                                |\n        +-------+-------------------------------------------------+\n        | ``R`` | Classical (Pseudo-)Random samples.              |\n        +-------+-------------------------------------------------+\n        | ``RG``| Regular spaced grid.                            |\n        +-------+-------------------------------------------------+\n        | ``NG``| Nested regular spaced grid.                     |\n        +-------+-------------------------------------------------+\n        | ``L`` | Latin hypercube samples.                        |\n        +-------+-------------------------------------------------+\n        | ``S`` | Sobol low-discrepancy sequence.                 |\n        +-------+-------------------------------------------------+\n        | ``H`` | Halton low-discrepancy sequence.                |\n        +-------+-------------------------------------------------+\n        | ``M`` | Hammersley low-discrepancy sequence.            |\n        +-------+-------------------------------------------------+\n\n        All samples are created on the ``[0, 1]``-hypercube, which then is\n        mapped into the domain of the distribution using the inverse Rosenblatt\n        transformation.\n\n        Args:\n            size (numpy.ndarray):\n                The size of the samples to generate.\n            rule (str):\n                Indicator defining the sampling scheme.\n            antithetic (bool, numpy.ndarray):\n                If provided, will be used to setup antithetic variables. If\n                array, defines the axes to mirror.\n\n        Returns:\n            (numpy.ndarray):\n                Random samples with shape ``(len(self),)+self.shape``."
  },
  {
    "code": "def done(p_queue, host=None):\n    if host is not None:\n        return _path(_c.FSQ_DONE, root=_path(host, root=hosts(p_queue)))\n    return _path(p_queue, _c.FSQ_DONE)",
    "docstring": "Construct a path to the done dir for a queue"
  },
  {
    "code": "def populate(self, fields=None, **fields_kwargs):\n        pop_fields = {}\n        fields = self.make_dict(fields, fields_kwargs)\n        for k in self.schema.fields.keys():\n            pop_fields[k] = fields.get(k, None)\n        self._populate(pop_fields)",
    "docstring": "take the passed in fields, combine them with missing fields that should\n        be there and then run all those through appropriate methods to hydrate this\n        orm.\n\n        The method replaces cls.hydrate() since it was becoming hard to understand\n        what was going on with all these methods that did things just a little bit\n        different.\n\n        This is used to completely set all the fields of self. If you just want\n        to set certain fields, you can use the submethod _populate\n\n        :param fields: dict, the fields in a dict\n        :param **fields_kwargs: dict, if you would like to pass the fields as key=val\n            this picks those up and combines them with fields"
  },
  {
    "code": "def iterkeys(self):\n        stack = collections.deque(self._hives)\n        stack.reverse()\n        return self.__iterate(stack)",
    "docstring": "Returns an iterator that crawls the entire Windows Registry."
  },
  {
    "code": "def get_subdomain_iterator(self, domain, limit=None, offset=None):\n        return SubdomainResultsIterator(self._manager, domain=domain)",
    "docstring": "Returns an iterator that will return each available subdomain for the\n        specified domain. If there are more than the limit of 100 subdomains,\n        the iterator will continue to fetch subdomains from the API until all\n        subdomains have been returned."
  },
  {
    "code": "def evolve(self, rho: Density) -> Density:\n        N = rho.qubit_nb\n        qubits = rho.qubits\n        indices = list([qubits.index(q) for q in self.qubits]) + \\\n            list([qubits.index(q) + N for q in self.qubits])\n        tensor = bk.tensormul(self.tensor, rho.tensor, indices)\n        return Density(tensor, qubits, rho.memory)",
    "docstring": "Apply the action of this channel upon a density"
  },
  {
    "code": "def today(self):\n        today = timezone.now().date()\n        try:\n            return Day.objects.get(date=today)\n        except Day.DoesNotExist:\n            return None",
    "docstring": "Return the Day for the current day"
  },
  {
    "code": "def stop(self):\n        self._clean_prior()\n        if not self._loaded:\n            raise errors.NoActiveTask\n        self._clean()",
    "docstring": "Stops the current task and cleans up, including removing active\n            task config file.\n\n            * Raises ``NoActiveTask`` exception if no active task found."
  },
  {
    "code": "def load_file(self, filepath, **kwargs):\n        log.setLevel(kwargs.get(\"log_level\", self.log_level))\n        filename = os.path.split(filepath)[-1]\n        if filename in self.loaded:\n            if self.loaded_times.get(filename,\n                    datetime.datetime(2001,1,1)).timestamp() \\\n                    < os.path.getmtime(filepath):\n                self.drop_file(filename, **kwargs)\n            else:\n                return\n        conn = self.__get_conn__(**kwargs)\n        conn.load_data(graph=getattr(__NSM__.kdr, filename).clean_uri,\n                       data=filepath,\n                       is_file=True)\n        self.__update_time__(filename, **kwargs)\n        log.warning(\"\\n\\tfile: '%s' loaded\\n\\tconn: '%s'\\n\\tpath: %s\",\n                    filename,\n                    conn,\n                    filepath)\n        self.loaded.append(filename)",
    "docstring": "loads a file into the defintion triplestore\n\n        args:\n            filepath: the path to the file"
  },
  {
    "code": "def ratio_split(amount, ratios):\n    ratio_total = sum(ratios)\n    divided_value = amount / ratio_total\n    values = []\n    for ratio in ratios:\n        value = divided_value * ratio\n        values.append(value)\n    rounded = [v.quantize(Decimal(\"0.01\")) for v in values]\n    remainders = [v - rounded[i] for i, v in enumerate(values)]\n    remainder = sum(remainders)\n    rounded[-1] = (rounded[-1] + remainder).quantize(Decimal(\"0.01\"))\n    assert sum(rounded) == amount\n    return rounded",
    "docstring": "Split in_value according to the ratios specified in `ratios`\n\n    This is special in that it ensures the returned values always sum to\n    in_value (i.e. we avoid losses or gains due to rounding errors). As a\n    result, this method returns a list of `Decimal` values with length equal\n    to that of `ratios`.\n\n    Examples:\n\n        .. code-block:: python\n\n            >>> from hordak.utilities.money import ratio_split\n            >>> from decimal import Decimal\n            >>> ratio_split(Decimal('10'), [Decimal('1'), Decimal('2')])\n            [Decimal('3.33'), Decimal('6.67')]\n\n        Note the returned values sum to the original input of ``10``. If we were to\n        do this calculation in a naive fashion then the returned values would likely\n        be ``3.33`` and ``6.66``, which would sum to ``9.99``, thereby loosing\n        ``0.01``.\n\n    Args:\n        amount (Decimal): The amount to be split\n        ratios (list[Decimal]): The ratios that will determine the split\n\n    Returns: list(Decimal)"
  },
  {
    "code": "def _raw_recv(self):\n        with self.lock:\n            if self._index >= len(self._buffer):\n                self._mcon()\n            if self._index >= 199:\n                self._resetbuffer()\n                self._mcon()\n            msg = self._buffer[self._index]\n            while self.find(msg, 'PING :'):\n                self._index += 1\n                try:\n                    msg = self._buffer[self._index]\n                except IndexError:\n                    self._mcon()\n                    self.stepback(append=False)\n            self._index += 1\n            return msg",
    "docstring": "Return the next available IRC message in the buffer."
  },
  {
    "code": "def get(cls, tab_uuid, tab_attachment_tab_id, custom_headers=None):\n        if custom_headers is None:\n            custom_headers = {}\n        api_client = client.ApiClient(cls._get_api_context())\n        endpoint_url = cls._ENDPOINT_URL_READ.format(tab_uuid,\n                                                     tab_attachment_tab_id)\n        response_raw = api_client.get(endpoint_url, {}, custom_headers)\n        return BunqResponseTabAttachmentTab.cast_from_bunq_response(\n            cls._from_json(response_raw, cls._OBJECT_TYPE_GET)\n        )",
    "docstring": "Get a specific attachment. The header of the response contains the\n        content-type of the attachment.\n\n        :type api_context: context.ApiContext\n        :type tab_uuid: str\n        :type tab_attachment_tab_id: int\n        :type custom_headers: dict[str, str]|None\n\n        :rtype: BunqResponseTabAttachmentTab"
  },
  {
    "code": "def get(self, id):\n        url = self._url('%s' % (id))\n        return self.client.get(url)",
    "docstring": "Retrieves custom domain.\n\n        See: https://auth0.com/docs/api/management/v2#!/Custom_Domains/get_custom_domains_by_id"
  },
  {
    "code": "def epilogue(app_name):\n    app_name = clr.stringc(app_name, \"bright blue\")\n    command = clr.stringc(\"command\", \"cyan\")\n    help = clr.stringc(\"--help\", \"green\")\n    return \"\\n%s %s %s for more info on a command\\n\" % (app_name,\n                                                        command, help)",
    "docstring": "Return the epilogue for the help command."
  },
  {
    "code": "def cache_it(self, url):\n        cached = self._cache_it(url)\n        if not isfile(cached.name):\n            self._cache_it.cache_clear()\n            cached = self._cache_it(url)\n        return cached.name",
    "docstring": "Take an url which deliver a plain document  and convert it to a\n        temporary file, this document is an xslt file expecting contains all\n        xslt definitions, then the cache process is recursive.\n\n        :param url: document origin url\n        :type url: str\n\n        :return file_path: local new absolute path\n        :rtype file_path: str"
  },
  {
    "code": "def datasets_org_count(self):\n        from udata.models import Dataset\n        return sum(Dataset.objects(organization=org).visible().count()\n                   for org in self.organizations)",
    "docstring": "Return the number of datasets of user's organizations."
  },
  {
    "code": "def exporter(directory, method, datasets):\n    if method.lower() == 'json':\n        json_string = json.dumps(datasets, indent=4)\n        savefile = open('{}/exported.json'.format(directory), 'w+')\n        savefile.write(json_string)\n        savefile.close()\n    if method.lower() == 'csv':\n        with open('{}/exported.csv'.format(directory), 'w+') as csvfile:\n            csv_writer = csv.writer(\n                csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)\n            for key, values in datasets.items():\n                if values is None:\n                    csv_writer.writerow([key])\n                else:\n                    csv_writer.writerow([key] + values)\n        csvfile.close()",
    "docstring": "Export the results."
  },
  {
    "code": "def get_artifact_url(context, task_id, path):\n    if path.startswith(\"public/\"):\n        url = context.queue.buildUrl('getLatestArtifact', task_id, path)\n    else:\n        url = context.queue.buildSignedUrl(\n            'getLatestArtifact', task_id, path,\n        )\n    return url",
    "docstring": "Get a TaskCluster artifact url.\n\n    Args:\n        context (scriptworker.context.Context): the scriptworker context\n        task_id (str): the task id of the task that published the artifact\n        path (str): the relative path of the artifact\n\n    Returns:\n        str: the artifact url\n\n    Raises:\n        TaskClusterFailure: on failure."
  },
  {
    "code": "def __format_occurence(self, occurence):\n        color = \"rgb({0}, {1}, {2})\"\n        span_format = \"<span style=\\\"color: {0};\\\">{{0}}</span>\".format(color.format(self.__default_line_color.red(),\n                                                                                     self.__default_line_color.green(),\n                                                                                     self.__default_line_color.blue()))\n        line = foundations.strings.to_string(occurence.text)\n        start = span_format.format(line[:occurence.column])\n        pattern = \"<b>{0}</b>\".format(line[occurence.column:occurence.column + occurence.length])\n        end = span_format.format(line[occurence.column + occurence.length:])\n        return \"\".join((start, pattern, end))",
    "docstring": "Formats the given occurence and returns the matching rich html text.\n\n        :param occurence: Occurence to format.\n        :type occurence: Occurence\n        :return: Rich text.\n        :rtype: unicode"
  },
  {
    "code": "def get_neutral(array_list):\n    res = []\n    for x in array_list:\n        res.append(np.zeros_like(x))\n    return res",
    "docstring": "Get list of zero-valued numpy arrays for\n    specified list of numpy arrays\n\n    :param array_list: list of numpy arrays\n    :return: list of zeros of same shape as input"
  },
  {
    "code": "def _style(self, retval):\n        \"Applies custom option tree to values return by the callback.\"\n        if self.id not in Store.custom_options():\n            return retval\n        spec = StoreOptions.tree_to_dict(Store.custom_options()[self.id])\n        return retval.opts(spec)",
    "docstring": "Applies custom option tree to values return by the callback."
  },
  {
    "code": "def intersect(self, **kwargs):\n        end_point = kwargs.pop('end_point')\n        depth = self.get_depth(location=end_point)\n        if depth < 0 and depth > end_point.depth:\n            inter = True\n        else:\n            inter = False\n        return inter",
    "docstring": "Intersect Point and Bathymetry\n            returns bool"
  },
  {
    "code": "def cpp_spec():\n    return {\n        INDENTATION    : '\\t',\n        BEG_BLOCK      : '{',\n        END_BLOCK      : '}',\n        BEG_LINE       : '',\n        END_LINE       : '\\n',\n        BEG_ACTION     : '',\n        END_ACTION     : ';',\n        BEG_CONDITION  : 'if(',\n        END_CONDITION  : ')',\n        LOGICAL_AND    : ' && ',\n        LOGICAL_OR     : ' || '\n    }",
    "docstring": "C++ specification, provided for example, and java compatible."
  },
  {
    "code": "def get_languages_from_application(app_label):\n        try:\n            mod_lan = TransApplicationLanguage.objects.filter(application=app_label).get()\n            languages = [lang.code for lang in mod_lan.languages.all()]\n            return languages\n        except TransApplicationLanguage.DoesNotExist:\n            return []",
    "docstring": "Get the languages configured for the current application\n\n        :param app_label:\n        :return:"
  },
  {
    "code": "def unsubscribe(self, subscription):\n        params = {'ContentType' : 'JSON',\n                  'SubscriptionArn' : subscription}\n        response = self.make_request('Unsubscribe', params, '/', 'GET')\n        body = response.read()\n        if response.status == 200:\n            return json.loads(body)\n        else:\n            boto.log.error('%s %s' % (response.status, response.reason))\n            boto.log.error('%s' % body)\n            raise self.ResponseError(response.status, response.reason, body)",
    "docstring": "Allows endpoint owner to delete subscription.\n        Confirmation message will be delivered.\n\n        :type subscription: string\n        :param subscription: The ARN of the subscription to be deleted."
  },
  {
    "code": "def bounding_box(self):\n        if self.world_coords:\n            return self.world_obj.findSolid().BoundingBox()\n        return self.local_obj.findSolid().BoundingBox()",
    "docstring": "Generate a bounding box based on the full complexity part.\n\n        :return: bounding box of part\n        :rtype: cadquery.BoundBox"
  },
  {
    "code": "def set_stream_class_lists_url(self, session_id):\n        url = self.api_url + '/v2/project/' + self.api_key + '/session/' + session_id + '/stream'\n        return url",
    "docstring": "this method returns the url to set the stream class list"
  },
  {
    "code": "def get_percent_identity(a_aln_seq, b_aln_seq):\n    if len(a_aln_seq) != len(b_aln_seq):\n        raise ValueError('Sequence lengths not equal - was an alignment run?')\n    count = 0\n    gaps = 0\n    for n in range(0, len(a_aln_seq)):\n        if a_aln_seq[n] == b_aln_seq[n]:\n            if a_aln_seq[n] != \"-\":\n                count += 1\n            else:\n                gaps += 1\n    return count / float((len(a_aln_seq) - gaps))",
    "docstring": "Get the percent identity between two alignment strings"
  },
  {
    "code": "def authenticated_users(func):\n    is_object_permission = \"has_object\" in func.__name__\n    @wraps(func)\n    def func_wrapper(*args, **kwargs):\n        request = args[0]\n        if is_object_permission:\n            request = args[1]\n        if not(request.user and request.user.is_authenticated):\n            return False\n        return func(*args, **kwargs)\n    return func_wrapper",
    "docstring": "This decorator is used to abstract common authentication checking functionality\n    out of permission checks. It determines which parameter is the request based on name."
  },
  {
    "code": "def gamma_humic_acid_to_coag(ConcAl, ConcNatOrgMat, NatOrgMat, coag):\n    return min(((ConcNatOrgMat / conc_precipitate(ConcAl, coag).magnitude)\n                * (coag.Density / NatOrgMat.Density)\n                * (coag.Diameter / (4 * NatOrgMat.Diameter))\n                ),\n               1)",
    "docstring": "Return the fraction of the coagulant that is coated with humic acid.\n\n    :param ConcAl: Concentration of alumninum in solution\n    :type ConcAl: float\n    :param ConcNatOrgMat: Concentration of natural organic matter in solution\n    :type ConcNatOrgMat: float\n    :param NatOrgMat: type of natural organic matter, e.g. floc_model.HumicAcid\n    :type NatOrgMat: floc_model.Material\n    :param coag: Type of coagulant in solution, e.g. floc_model.PACl\n    :type coag: floc_model.Material\n\n    :return: fraction of the coagulant that is coated with humic acid\n    :rtype: float"
  },
  {
    "code": "def get_wifi_state(self):\n        log.debug(\"getting wifi state...\")\n        cmd, url = DEVICE_URLS[\"get_wifi_state\"]\n        return self._exec(cmd, url)",
    "docstring": "returns the current Wi-Fi state the device is connected to"
  },
  {
    "code": "def grad(self, xs, ys):\n        return self.sess.run(\n            self.cross_entropy_grads, feed_dict={\n                self.x: xs,\n                self.y_: ys\n            })",
    "docstring": "Computes the gradients of the network."
  },
  {
    "code": "def toggleAttributesDOM(isEnabled):\n    if isEnabled:\n        AdvancedTag.attributes = AdvancedTag.attributesDOM\n    else:\n        AdvancedTag.attributes = AdvancedTag.attributesDict",
    "docstring": "toggleAttributesDOM - Toggle if the old DOM tag.attributes NamedNodeMap model should be used for the .attributes method, versus\n\n           a more sane direct dict implementation.\n\n            The DOM version is always accessable as AdvancedTag.attributesDOM\n            The dict version is always accessable as AdvancedTag.attributesDict\n\n            Default for AdvancedTag.attributes is to be attributesDict implementation.\n\n          @param isEnabled <bool> - If True, .attributes will be changed to use the DOM-provider. Otherwise, it will use the dict provider."
  },
  {
    "code": "def group(self):\n        \"Group inherited from main element\"\n        if self.main and self.main.group != type(self.main).__name__:\n            return self.main.group\n        else:\n            return 'AdjointLayout'",
    "docstring": "Group inherited from main element"
  },
  {
    "code": "def __check_field(self, key):\n        if not self._props.get(key):\n            raise KeyError(\n                'The field \"%s\" does not exist on \"%s\"' % (\n                    key, self.__class__.__name__,\n                ),\n            )",
    "docstring": "Raises a KeyError if the field doesn't exist."
  },
  {
    "code": "def extract_props(self, settings):\n        props = {}\n        for param in self.call_parameters:\n            if param in settings:\n                props[param] = settings[param]\n            else:\n                props[param] = None\n        return props",
    "docstring": "Extract all valuable properties to be displayed"
  },
  {
    "code": "def clear_cache(self):\n        errors = []\n        for rdir in (self.cache_root, self.file_list_cachedir):\n            if os.path.exists(rdir):\n                try:\n                    shutil.rmtree(rdir)\n                except OSError as exc:\n                    errors.append(\n                        'Unable to delete {0}: {1}'.format(rdir, exc)\n                    )\n        return errors",
    "docstring": "Completely clear cache"
  },
  {
    "code": "def get_or_create_hosted_zone(client, zone_name):\n    zone_id = get_hosted_zone_by_name(client, zone_name)\n    if zone_id:\n        return zone_id\n    logger.debug(\"Zone %s does not exist, creating.\", zone_name)\n    reference = uuid.uuid4().hex\n    response = client.create_hosted_zone(Name=zone_name,\n                                         CallerReference=reference)\n    return parse_zone_id(response[\"HostedZone\"][\"Id\"])",
    "docstring": "Get the Id of an existing zone, or create it.\n\n    Args:\n        client (:class:`botocore.client.Route53`): The connection used to\n            interact with Route53's API.\n        zone_name (string): The name of the DNS hosted zone to create.\n\n    Returns:\n        string: The Id of the Hosted Zone."
  },
  {
    "code": "def _get_domain_id(self, domain_text_element):\n        try:\n            tr_anchor = domain_text_element.parent.parent.parent\n            td_anchor = tr_anchor.find('td', {'class': 'td_2'})\n            link = td_anchor.find('a')['href']\n            domain_id = link.rsplit('/', 1)[-1]\n            return domain_id\n        except Exception as error:\n            errmsg = ('Cannot get the domain id even though the domain seems '\n                      'to exist (%s).', error)\n            LOGGER.warning(errmsg)\n            raise AssertionError(errmsg)",
    "docstring": "Return the easyname id of the domain."
  },
  {
    "code": "def linear_weighted_moving_average(data, period):\n    catch_errors.check_for_period_error(data, period)\n    idx_period = list(range(1, period+1))\n    lwma = [(sum([i * idx_period[data[idx-(period-1):idx+1].index(i)]\n              for i in data[idx-(period-1):idx+1]])) /\n            sum(range(1, len(data[idx+1-period:idx+1])+1)) for idx in range(period-1, len(data))]\n    lwma = fill_for_noncomputable_vals(data, lwma)\n    return lwma",
    "docstring": "Linear Weighted Moving Average.\n\n    Formula:\n    LWMA = SUM(DATA[i]) * i / SUM(i)"
  },
  {
    "code": "def _start_io_loop(self):\n        def mark_as_ready():\n            self._ready.set()\n        if not self._io_loop:\n            self._io_loop = ioloop.IOLoop()\n        self._io_loop.add_callback(mark_as_ready)\n        self._io_loop.start()",
    "docstring": "Start IOLoop then set ready threading.Event."
  },
  {
    "code": "def _format_select(formatter, name):\n    for caster in formatter.split('-'):\n        if caster == 'SEC_TO_MICRO':\n            name = \"%s*1000000\" % name\n        elif ':' in caster:\n            caster, args = caster.split(':')\n            name = \"%s(%s,%s)\" % (caster, name, args)\n        else:\n            name = \"%s(%s)\" % (caster, name)\n    return name",
    "docstring": "Modify the query selector by applying any formatters to it.\n\n    Parameters\n    ----------\n    formatter : str\n       Hyphen-delimited formatter string where formatters are\n       applied inside-out, e.g. the formatter string\n       SEC_TO_MICRO-INTEGER-FORMAT_UTC_USEC applied to the selector\n       foo would result in FORMAT_UTC_USEC(INTEGER(foo*1000000)).\n    name: str\n        The name of the selector to apply formatters to.\n\n    Returns\n    -------\n    str\n        The formatted selector"
  },
  {
    "code": "def clear_sequestered(self):\n        if (self.get_sequestered_metadata().is_read_only() or\n                self.get_sequestered_metadata().is_required()):\n            raise errors.NoAccess()\n        self._my_map['sequestered'] = self._sequestered_default",
    "docstring": "Clears the sequestered flag.\n\n        raise:  NoAccess - ``Metadata.isRequired()`` or\n                ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def cookiecutter(template, checkout=None, no_input=False, extra_context=None):\n    config_dict = get_user_config()\n    template = expand_abbreviations(template, config_dict)\n    if 'git@' in template or 'https://' in template:\n        repo_dir = clone(\n            repo_url=template,\n            checkout=checkout,\n            clone_to_dir=config_dict['cookiecutters_dir'],\n            no_input=no_input\n        )\n    else:\n        repo_dir = template\n    context_file = os.path.join(repo_dir, 'cookiecutter.json')\n    logging.debug('context_file is {0}'.format(context_file))\n    context = generate_context(\n        context_file=context_file,\n        default_context=config_dict['default_context'],\n        extra_context=extra_context,\n    )\n    generate_files(\n        repo_dir=repo_dir,\n        context=context\n    )",
    "docstring": "Replacement for cookiecutter's own cookiecutter.\n\n    The difference with cookiecutter's cookiecutter function\n    is that this one doesn't automatically str() all the values\n    passed along to the template.\n\n    :param template: A directory containing a project template directory,\n        or a URL to a git repository.\n    :param checkout: The branch, tag or commit ID to checkout after clone.\n    :param no_input: Prompt the user at command line for manual configuration?\n    :param extra_context: A dictionary of context that overrides default\n        and user configuration."
  },
  {
    "code": "def emoji_list(server, n=1):\n    global EMOJI\n    if EMOJI is None:\n        EMOJI = EmojiCache(server)\n    return EMOJI.get(n)",
    "docstring": "return a list of `n` random emoji"
  },
  {
    "code": "def seen_nonce(id, nonce, timestamp):\n    key = '{id}:{n}:{ts}'.format(id=id, n=nonce, ts=timestamp)\n    if cache.get(key):\n        log.warning('replay attack? already processed nonce {k}'\n                    .format(k=key))\n        return True\n    else:\n        log.debug('caching nonce {k}'.format(k=key))\n        cache.set(key, True,\n                  timeout=getattr(settings, 'HAWK_MESSAGE_EXPIRATION',\n                                  default_message_expiration) + 5)\n        return False",
    "docstring": "Returns True if the Hawk nonce has been seen already."
  },
  {
    "code": "def folders(self):\n        if self._folders is None :\n            self.__init()\n        if self._folders is not None and isinstance(self._folders, list):\n            if len(self._folders) == 0:\n                self._loadFolders()\n        return self._folders",
    "docstring": "gets the property value for folders"
  },
  {
    "code": "def MaxPool(a, k, strides, padding, data_format):\n    if data_format.decode(\"ascii\") == \"NCHW\":\n        a = np.rollaxis(a, 1, -1),\n    patches = _pool_patches(a, k, strides, padding.decode(\"ascii\"))\n    pool = np.amax(patches, axis=tuple(range(-len(k), 0)))\n    if data_format.decode(\"ascii\") == \"NCHW\":\n        pool = np.rollaxis(pool, -1, 1)\n    return pool,",
    "docstring": "Maximum pooling op."
  },
  {
    "code": "def add_quantity_modifier(self, quantity, modifier, overwrite=False):\n        if quantity in self._quantity_modifiers and not overwrite:\n            raise ValueError('quantity `{}` already exists'.format(quantity))\n        self._quantity_modifiers[quantity] = modifier\n        self._check_quantities_exist([quantity], raise_exception=False)",
    "docstring": "Add a quantify modifier.\n        Consider useing the high-level function `add_derived_quantity` instead!\n\n        Parameters\n        ----------\n        quantity : str\n            name of the derived quantity to add\n\n        modifier : None or str or tuple\n            If the quantity modifier is a tuple of length >=2 and the first element is a callable,\n            it should be in the formate of `(callable, native quantity 1,  native quantity 2, ...)`.\n            And the modifier would work as callable(native quantity 1,  native quantity 2, ...)\n            If the quantity modifier is None, the quantity will be used as the native quantity name\n            Otherwise, the modifier would be use directly as a native quantity name\n\n        overwrite : bool, optional\n            If False and quantity are already specified in _quantity_modifiers, raise an ValueError"
  },
  {
    "code": "def domain_search(self, domain=None, company=None, limit=None, offset=None,\n                      emails_type=None, raw=False):\n        if not domain and not company:\n            raise MissingCompanyError(\n                'You must supply at least a domain name or a company name'\n            )\n        if domain:\n            params = {'domain': domain, 'api_key': self.api_key}\n        elif company:\n            params = {'company': company, 'api_key': self.api_key}\n        if limit:\n            params['limit'] = limit\n        if offset:\n            params['offset'] = offset\n        if emails_type:\n            params['type'] = emails_type\n        endpoint = self.base_endpoint.format('domain-search')\n        return self._query_hunter(endpoint, params, raw=raw)",
    "docstring": "Return all the email addresses found for a given domain.\n\n        :param domain: The domain on which to search for emails. Must be\n        defined if company is not.\n\n        :param company: The name of the company on which to search for emails.\n        Must be defined if domain is not.\n\n        :param limit: The maximum number of emails to give back. Default is 10.\n\n        :param offset: The number of emails to skip. Default is 0.\n\n        :param emails_type: The type of emails to give back. Can be one of\n        'personal' or 'generic'.\n\n        :param raw: Gives back the entire response instead of just the 'data'.\n\n        :return: Full payload of the query as a dict, with email addresses\n        found."
  },
  {
    "code": "def read_from_buffer(cls, buf, identifier_str=None):\n        try:\n            return cls._read_from_buffer(buf, identifier_str)\n        except Exception as e:\n            cls._load_error(e, identifier_str)",
    "docstring": "Load the context from a buffer."
  },
  {
    "code": "def upload(self, href, vobject_item):\n        if self.is_fake:\n            return\n        content = vobject_item.serialize()\n        try:\n            item = self.get(href)\n            etesync_item = item.etesync_item\n            etesync_item.content = content\n        except api.exceptions.DoesNotExist:\n            etesync_item = self.collection.get_content_class().create(self.collection, content)\n        etesync_item.save()\n        return self.get(href)",
    "docstring": "Upload a new or replace an existing item."
  },
  {
    "code": "def to_unix_ms(dt: datetime) -> int:\n    utcoffset = dt.utcoffset()\n    ep = epoch if utcoffset is None else epoch_tz\n    return as_int((dt - ep).total_seconds() * 1000)",
    "docstring": "convert a datetime to number of milliseconds since 1970 and calculate timezone offset"
  },
  {
    "code": "def extract_links(html):\n        links = []\n        soup = BeautifulSoup(html, 'html.parser')\n        for link in soup.findAll('a'):\n            href = link.get('href')\n            if not href:\n                continue\n            if href.startswith('/'):\n                href = 'https://www.reddit.com' + href\n            links.append({'text': link.text, 'href': href})\n        return links",
    "docstring": "Extract a list of hyperlinks from an HTML document."
  },
  {
    "code": "def _get_iris_args(attrs):\n    import cf_units\n    args = {'attributes': _filter_attrs(attrs, iris_forbidden_keys)}\n    args.update(_pick_attrs(attrs, ('standard_name', 'long_name',)))\n    unit_args = _pick_attrs(attrs, ('calendar',))\n    if 'units' in attrs:\n        args['units'] = cf_units.Unit(attrs['units'], **unit_args)\n    return args",
    "docstring": "Converts the xarray attrs into args that can be passed into Iris"
  },
  {
    "code": "def remove_existing_fpaths(fpath_list, verbose=VERBOSE, quiet=QUIET,\n                           strict=False, print_caller=PRINT_CALLER,\n                           lbl='files'):\n    import utool as ut\n    if print_caller:\n        print(util_dbg.get_caller_name(range(1, 4)) + ' called remove_existing_fpaths')\n    fpath_list_ = ut.filter_Nones(fpath_list)\n    exists_list = list(map(exists, fpath_list_))\n    if verbose:\n        n_total = len(fpath_list)\n        n_valid = len(fpath_list_)\n        n_exist = sum(exists_list)\n        print('[util_path.remove_existing_fpaths] request delete of %d %s' % (\n            n_total, lbl))\n        if n_valid != n_total:\n            print(('[util_path.remove_existing_fpaths] '\n                   'trying to delete %d/%d non None %s ') %\n                  (n_valid, n_total, lbl))\n        print(('[util_path.remove_existing_fpaths] '\n               ' %d/%d exist and need to be deleted')\n              % (n_exist, n_valid))\n    existing_fpath_list = ut.compress(fpath_list_, exists_list)\n    return remove_fpaths(existing_fpath_list, verbose=verbose, quiet=quiet,\n                            strict=strict, print_caller=False, lbl=lbl)",
    "docstring": "checks existance before removing. then tries to remove exisint paths"
  },
  {
    "code": "def resolve_egg_link(path):\n    referenced_paths = non_empty_lines(path)\n    resolved_paths = (\n        os.path.join(os.path.dirname(path), ref)\n        for ref in referenced_paths\n    )\n    dist_groups = map(find_distributions, resolved_paths)\n    return next(dist_groups, ())",
    "docstring": "Given a path to an .egg-link, resolve distributions\n    present in the referenced path."
  },
  {
    "code": "def read(self, mode='r', *, buffering=-1, encoding=None, newline=None):\n        with self.open(mode=mode, buffering=buffering, encoding=encoding, newline=newline) as fp:\n            return fp.read()",
    "docstring": "read data from the file."
  },
  {
    "code": "def use_federated_log_view(self):\n        self._log_view = FEDERATED\n        for session in self._get_provider_sessions():\n            try:\n                session.use_federated_log_view()\n            except AttributeError:\n                pass",
    "docstring": "Pass through to provider LogEntryLookupSession.use_federated_log_view"
  },
  {
    "code": "def sheetDelete(book=None,sheet=None):\n    if book is None:\n        book=activeBook()\n    if sheet in sheetNames():\n        PyOrigin.WorksheetPages(book).Layers(sheetNames().index(sheet)).Destroy()",
    "docstring": "Delete a sheet from a book. If either isn't given, use the active one."
  },
  {
    "code": "def csch(x, context=None):\n    return _apply_function_in_current_context(\n        BigFloat,\n        mpfr.mpfr_csch,\n        (BigFloat._implicit_convert(x),),\n        context,\n    )",
    "docstring": "Return the hyperbolic cosecant of x."
  },
  {
    "code": "def codes_get_double_array(handle, key, size):\n    values = ffi.new('double[]', size)\n    size_p = ffi.new('size_t *', size)\n    _codes_get_double_array(handle, key.encode(ENC), values, size_p)\n    return list(values)",
    "docstring": "Get double array values from a key.\n\n    :param bytes key: the keyword whose value(s) are to be extracted\n\n    :rtype: T.List(float)"
  },
  {
    "code": "def _change(self, changes):\n        if changes is None:\n            return\n        for position, new_tile in changes:\n            self._array[position] = new_tile",
    "docstring": "Apply the given changes to the board.\n\n        changes: sequence of (position, new tile) pairs or None"
  },
  {
    "code": "def set_modules(self, modules=None):\n        node_flags = int(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n        modules = modules or self.get_modules()\n        root_node = umbra.ui.nodes.DefaultNode(name=\"InvisibleRootNode\")\n        for module in modules:\n            module_node = ModuleNode(module=module,\n                                     name=foundations.strings.to_string(module.__name__),\n                                     parent=root_node,\n                                     node_flags=node_flags,\n                                     attributes_flags=int(Qt.ItemIsSelectable | Qt.ItemIsEnabled))\n        root_node.sort_children()\n        self.__model.initialize_model(root_node)\n        return True",
    "docstring": "Sets the modules Model nodes.\n\n        :param modules: Modules to set.\n        :type modules: list\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def fetch_mga_scores(mga_vec,\n                     codon_pos,\n                     default_mga=None):\n    len_mga = len(mga_vec)\n    good_codon_pos = [p for p in codon_pos if p < len_mga]\n    if good_codon_pos:\n        mga_ent_scores = mga_vec[good_codon_pos]\n    else:\n        mga_ent_scores = None\n    return mga_ent_scores",
    "docstring": "Get MGAEntropy scores from pre-computed scores in array.\n\n    Parameters\n    ----------\n    mga_vec : np.array\n        numpy vector containing MGA Entropy conservation scores for residues\n    codon_pos: list of int\n        position of codon in protein sequence\n    default_mga: float or None, default=None\n        value to use if MGA entropy score not available for a given mutation.\n        Drop mutations if no default specified.\n\n    Returns\n    -------\n    mga_ent_scores : np.array\n        score results for MGA entropy conservation"
  },
  {
    "code": "def format_pkg_list(packages, versions_as_list, attr):\n    ret = copy.deepcopy(packages)\n    if attr:\n        requested_attr = {'epoch', 'version', 'release', 'arch', 'install_date', 'install_date_time_t'}\n        if attr != 'all':\n            requested_attr &= set(attr + ['version'])\n        for name in ret:\n            versions = []\n            for all_attr in ret[name]:\n                filtered_attr = {}\n                for key in requested_attr:\n                    if all_attr[key]:\n                        filtered_attr[key] = all_attr[key]\n                versions.append(filtered_attr)\n            ret[name] = versions\n        return ret\n    for name in ret:\n        ret[name] = [format_version(d['epoch'], d['version'], d['release'])\n                     for d in ret[name]]\n    if not versions_as_list:\n        stringify(ret)\n    return ret",
    "docstring": "Formats packages according to parameters for list_pkgs."
  },
  {
    "code": "def connect(host=None,\n            port=rethinkdb.DEFAULT_PORT,\n            timeout=20,\n            verify=True,\n            **kwargs):\n    if not host:\n        host = DEFAULT_HOSTS.get(check_stage_env())\n    connection = None\n    tries = 0\n    time_quit = time() + timeout\n    while not connection and time() <= time_quit:\n        tries += 1\n        connection = _attempt_connect(host, port, timeout/3, verify, **kwargs)\n        if not connection:\n            sleep(0.5)\n    if not connection:\n        raise BrainNotReady(\n            \"Tried ({}:{}) {} times at {} second max timeout\".format(host,\n                                                                     port,\n                                                                     tries,\n                                                                     timeout))\n    return connection",
    "docstring": "RethinkDB semantic connection wrapper\n\n    raises <brain.connection.BrainNotReady> if connection verification fails\n\n    :param verify: <bool> (default True) whether to run POST\n    :param timeout: <int> max time (s) to wait for connection\n    :param kwargs:  <dict> passthrough rethinkdb arguments\n    :return:"
  },
  {
    "code": "def upsert_into(self, table):\n    return SessionContext.session.execute(\n        insert(table).from_select(\n            self.c,\n            self,\n        ).on_conflict_do_nothing(),\n    ).rowcount",
    "docstring": "Upsert from a temporarty table into another table."
  },
  {
    "code": "def _get_visualization_classes():\n    visualization_attr = vars(import_module('picasso.visualizations'))\n    visualization_submodules = [\n        visualization_attr[x]\n        for x in visualization_attr\n        if isinstance(visualization_attr[x], ModuleType)]\n    visualization_classes = []\n    for submodule in visualization_submodules:\n        attrs = vars(submodule)\n        for attr_name in attrs:\n            attr = attrs[attr_name]\n            if (inspect.isclass(attr)\n                and issubclass(attr, BaseVisualization)\n                    and attr is not BaseVisualization):\n                visualization_classes.append(attr)\n    return visualization_classes",
    "docstring": "Import visualizations classes dynamically"
  },
  {
    "code": "def get_ip(host):\n    hosts = _list_hosts()\n    if not hosts:\n        return ''\n    for addr in hosts:\n        if host in hosts[addr]:\n            return addr\n    return ''",
    "docstring": "Return the ip associated with the named host\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' hosts.get_ip <hostname>"
  },
  {
    "code": "def make_ifar_plot(workflow, trigger_file, out_dir, tags=None,\n                   hierarchical_level=None):\n    if hierarchical_level is not None and tags:\n        tags = [(\"HIERARCHICAL_LEVEL_{:02d}\".format(\n                hierarchical_level))] + tags\n    elif hierarchical_level is not None and not tags:\n        tags = [\"HIERARCHICAL_LEVEL_{:02d}\".format(hierarchical_level)]\n    elif hierarchical_level is None and not tags:\n        tags = []\n    makedir(out_dir)\n    node = PlotExecutable(workflow.cp, 'page_ifar', ifos=workflow.ifos,\n                    out_dir=out_dir, tags=tags).create_node()\n    node.add_input_opt('--trigger-file', trigger_file)\n    if hierarchical_level is not None:\n        node.add_opt('--use-hierarchical-level', hierarchical_level)\n    node.new_output_file_opt(workflow.analysis_time, '.png', '--output-file')\n    workflow += node\n    return node.output_files[0]",
    "docstring": "Creates a node in the workflow for plotting cumulative histogram\n    of IFAR values."
  },
  {
    "code": "def add_router_interface(self, context, router_info):\n        if router_info:\n            self._select_dicts(router_info['ip_version'])\n            cidr = router_info['cidr']\n            subnet_mask = cidr.split('/')[1]\n            router_name = self._arista_router_name(router_info['id'],\n                                                   router_info['name'])\n            if self._mlag_configured:\n                mlag_peer_failed = False\n                for i, server in enumerate(self._servers):\n                    router_ip = self._get_router_ip(cidr, i,\n                                                    router_info['ip_version'])\n                    try:\n                        self.add_interface_to_router(router_info['seg_id'],\n                                                     router_name,\n                                                     router_info['gip'],\n                                                     router_ip, subnet_mask,\n                                                     server)\n                        mlag_peer_failed = False\n                    except Exception:\n                        if not mlag_peer_failed:\n                            mlag_peer_failed = True\n                        else:\n                            msg = (_('Failed to add interface to router '\n                                     '%s on EOS') % router_name)\n                            LOG.exception(msg)\n                            raise arista_exc.AristaServicePluginRpcError(\n                                msg=msg)\n            else:\n                for s in self._servers:\n                    self.add_interface_to_router(router_info['seg_id'],\n                                                 router_name,\n                                                 router_info['gip'],\n                                                 None, subnet_mask, s)",
    "docstring": "Adds an interface to a router created on Arista HW router.\n\n        This deals with both IPv6 and IPv4 configurations."
  },
  {
    "code": "def remove(self, member):\n        if not self.client.srem(self.name, member):\n            raise KeyError(member)",
    "docstring": "Remove element from set; it must be a member.\n\n        :raises KeyError: if the element is not a member."
  },
  {
    "code": "def _at_exit(self):\n        if self.process_exit:\n            try:\n                term = self.term\n                if self.set_scroll:\n                    term.reset()\n                else:\n                    term.move_to(0, term.height)\n                self.term.feed()\n            except ValueError:\n                pass",
    "docstring": "Resets terminal to normal configuration"
  },
  {
    "code": "def _create_session(team, auth):\n    session = requests.Session()\n    session.hooks.update(dict(\n        response=partial(_handle_response, team)\n    ))\n    session.headers.update({\n        \"Content-Type\": \"application/json\",\n        \"Accept\": \"application/json\",\n        \"User-Agent\": \"quilt-cli/%s (%s %s) %s/%s\" % (\n            VERSION, platform.system(), platform.release(),\n            platform.python_implementation(), platform.python_version()\n        )\n    })\n    if auth is not None:\n        session.headers[\"Authorization\"] = \"Bearer %s\" % auth['access_token']\n    return session",
    "docstring": "Creates a session object to be used for `push`, `install`, etc."
  },
  {
    "code": "def _read_cache_from_file(self):\n        cache = {}\n        try:\n            with(open(self._cache_file_name, 'r')) as fp:\n                contents = fp.read()\n                cache = simplejson.loads(contents)\n        except (IOError, JSONDecodeError):\n            pass\n        return cache",
    "docstring": "Read the contents of the cache from a file on disk."
  },
  {
    "code": "def _walk_factory(self, dep_predicate):\n    walk = None\n    if dep_predicate:\n      walk = self.DepPredicateWalk(dep_predicate)\n    else:\n      walk = self.NoDepPredicateWalk()\n    return walk",
    "docstring": "Construct the right context object for managing state during a transitive walk."
  },
  {
    "code": "def c_var_decls(self):\n        if self.opts.no_structs:\n            mod_decl = 'HMODULE {} = NULL;\\n'.format(self.name)\n            return [mod_decl] + [\n                '{} *{} = NULL;\\n'.format(\n                    self._c_type_name(name), name\n                )\n                for name, dummy_args in self.funcs\n            ]\n        if self.opts.windll:\n            return ''\n        return [\n            '{} _{} = {{ 0 }};\\n'.format(\n                self._c_struct_names()[1], self.name\n            )\n        ]",
    "docstring": "Get the needed variable definitions."
  },
  {
    "code": "def wninsd(left, right, window):\n    assert isinstance(window, stypes.SpiceCell)\n    assert window.dtype == 1\n    left = ctypes.c_double(left)\n    right = ctypes.c_double(right)\n    libspice.wninsd_c(left, right, ctypes.byref(window))",
    "docstring": "Insert an interval into a double precision window.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wninsd_c.html\n\n    :param left: Left endpoints of new interval. \n    :type left: float\n    :param right: Right endpoints of new interval. \n    :type right: float\n    :param window: Input window. \n    :type window: spiceypy.utils.support_types.SpiceCell"
  },
  {
    "code": "def contained(self, key, include_self=True, exclusive=False, biggest_first=True, only=None):\n        if 'RoW' not in self:\n            if key == 'RoW':\n                return ['RoW'] if 'RoW' in (only or []) else []\n            elif only and 'RoW' in only:\n                only.pop(only.index('RoW'))\n        possibles = self.topology if only is None else {k: self[k] for k in only}\n        faces = self[key]\n        lst = [\n            (k, len(v))\n            for k, v in possibles.items()\n            if v and faces.issuperset(v)\n        ]\n        return self._finish_filter(lst, key, include_self, exclusive, biggest_first)",
    "docstring": "Get all locations that are completely within this location.\n\n        If the ``resolved_row`` context manager is not used, ``RoW`` doesn't have a spatial definition. Therefore, ``.contained(\"RoW\")`` returns a list with either ``RoW`` or nothing."
  },
  {
    "code": "def get_dev_vlans(auth, url, devid=None, devip=None):\n    if devip is not None:\n        devid = get_dev_details(devip, auth, url)['id']\n    get_dev_vlans_url = \"/imcrs/vlan?devId=\" + str(devid) + \"&start=0&size=5000&total=false\"\n    f_url = url + get_dev_vlans_url\n    response = requests.get(f_url, auth=auth, headers=HEADERS)\n    try:\n        if response.status_code == 200:\n            dev_vlans = (json.loads(response.text))\n            return dev_vlans['vlan']\n        elif response.status_code == 409:\n            return {'vlan': 'no vlans'}\n    except requests.exceptions.RequestException as error:\n        return \"Error:\\n\" + str(error) + ' get_dev_vlans: An Error has occured'",
    "docstring": "Function takes input of devID to issue RESTUL call to HP IMC\n\n    :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class\n\n    :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass\n\n    :param devid: str requires devId as the only input parameter\n\n    :param devip: str of ipv4 address of the target device\n\n    :return: list of dictionaries where each element of the list represents one vlan on the\n    target device\n\n    :rtype: list\n\n    >>> from pyhpeimc.auth import *\n\n    >>> from pyhpeimc.plat.vlanm import *\n\n    >>> auth = IMCAuth(\"http://\", \"10.101.0.203\", \"8080\", \"admin\", \"admin\")\n\n    >>> vlans = get_dev_vlans('350', auth.creds, auth.url)\n\n    >>> assert type(vlans) is list\n\n    >>> assert 'vlanId' in vlans[0]"
  },
  {
    "code": "def parse(cls, compoundIdStr):\n        if not isinstance(compoundIdStr, basestring):\n            raise exceptions.BadIdentifierException(compoundIdStr)\n        try:\n            deobfuscated = cls.deobfuscate(compoundIdStr)\n        except TypeError:\n            raise exceptions.ObjectWithIdNotFoundException(compoundIdStr)\n        try:\n            encodedSplits = cls.split(deobfuscated)\n            splits = [cls.decode(split) for split in encodedSplits]\n        except (UnicodeDecodeError, ValueError):\n            raise exceptions.ObjectWithIdNotFoundException(compoundIdStr)\n        fieldsLength = len(cls.fields)\n        if cls.differentiator is not None:\n            differentiatorIndex = cls.fields.index(\n                cls.differentiatorFieldName)\n            if differentiatorIndex < len(splits):\n                del splits[differentiatorIndex]\n            else:\n                raise exceptions.ObjectWithIdNotFoundException(\n                    compoundIdStr)\n            fieldsLength -= 1\n        if len(splits) != fieldsLength:\n            raise exceptions.ObjectWithIdNotFoundException(compoundIdStr)\n        return cls(None, *splits)",
    "docstring": "Parses the specified compoundId string and returns an instance\n        of this CompoundId class.\n\n        :raises: An ObjectWithIdNotFoundException if parsing fails. This is\n        because this method is a client-facing method, and if a malformed\n        identifier (under our internal rules) is provided, the response should\n        be that the identifier does not exist."
  },
  {
    "code": "def receive_nack(self, msg):\n        self.observe_proposal(msg.promised_proposal_id)\n        if msg.proposal_id == self.proposal_id and self.nacks_received is not None:\n            self.nacks_received.add(msg.from_uid)\n            if len(self.nacks_received) == self.quorum_size:\n                return self.prepare()",
    "docstring": "Returns a new Prepare message if the number of Nacks received reaches\n        a quorum."
  },
  {
    "code": "def write_secret(path, **kwargs):\n    log.debug('Writing vault secrets for %s at %s', __grains__['id'], path)\n    data = dict([(x, y) for x, y in kwargs.items() if not x.startswith('__')])\n    try:\n        url = 'v1/{0}'.format(path)\n        response = __utils__['vault.make_request']('POST', url, json=data)\n        if response.status_code == 200:\n            return response.json()['data']\n        elif response.status_code != 204:\n            response.raise_for_status()\n        return True\n    except Exception as err:\n        log.error('Failed to write secret! %s: %s', type(err).__name__, err)\n        return False",
    "docstring": "Set secret at the path in vault. The vault policy used must allow this.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n            salt '*' vault.write_secret \"secret/my/secret\" user=\"foo\" password=\"bar\""
  },
  {
    "code": "def backup_key(self, name, mount_point=DEFAULT_MOUNT_POINT):\n        api_path = '/v1/{mount_point}/backup/{name}'.format(\n            mount_point=mount_point,\n            name=name,\n        )\n        response = self._adapter.get(\n            url=api_path,\n        )\n        return response.json()",
    "docstring": "Return a plaintext backup of a named key.\n\n        The backup contains all the configuration data and keys of all the versions along with the HMAC key. The\n        response from this endpoint can be used with the /restore endpoint to restore the key.\n\n        Supported methods:\n            GET: /{mount_point}/backup/{name}. Produces: 200 application/json\n\n        :param name: Name of the key.\n        :type name: str | unicode\n        :param mount_point: The \"path\" the method/backend was mounted on.\n        :type mount_point: str | unicode\n        :return: The JSON response of the request.\n        :rtype: requests.Response"
  },
  {
    "code": "def _check_shape(s1, s2):\n    if s1 and s2 and s1 != s2:\n        raise ValueError(\"Shape mismatch detected. \" + str(s1) + \" v.s. \" + str(s2))",
    "docstring": "check s1 == s2 if both are not None"
  },
  {
    "code": "def _resolve_user_group_names(opts):\n    name_id_opts = {'uid': 'user.info',\n                    'gid': 'group.info'}\n    for ind, opt in enumerate(opts):\n        if opt.split('=')[0] in name_id_opts:\n            _givenid = opt.split('=')[1]\n            _param = opt.split('=')[0]\n            _id = _givenid\n            if not re.match('[0-9]+$', _givenid):\n                _info = __salt__[name_id_opts[_param]](_givenid)\n                if _info and _param in _info:\n                    _id = _info[_param]\n            opts[ind] = _param + '=' + six.text_type(_id)\n        opts[ind] = opts[ind].replace('\\\\040', '\\\\ ')\n    return opts",
    "docstring": "Resolve user and group names in related opts"
  },
  {
    "code": "def setup(self, in_name=None, out_name=None, required=None, hidden=None,\n                multiple=None, defaults=None):\n        if in_name is not None:\n            self.in_name = in_name if isinstance(in_name, list) else [in_name]\n        if out_name is not None:\n            self.out_name = out_name\n        if required is not None:\n            self.required = required\n        if hidden is not None:\n            self.hidden = hidden\n        if multiple is not None:\n            self.multiple = multiple\n        if defaults is not None:\n            self.defaults = defaults",
    "docstring": "Set the options of the block.\n        Only the not None given options are set\n\n        .. note:: a block may have multiple inputs but have only one output\n\n        :param in_name: name(s) of the block input data\n        :type in_name: str or list of str\n        :param out_name: name of the block output data\n        :type out_name: str\n        :param required: whether the block will be required or not\n        :type required: bool\n        :param hidden: whether the block will be hidden to the user or not\n        :type hidden: bool\n        :param multiple: if True more than one component may be selected/ run) \n        :type multiple: bool\n        :param defaults: names of the selected components\n        :type defaults: list of str, or str"
  },
  {
    "code": "def rename_experiment(self, new_name):\n        logger.info('rename experiment \"%s\"', self.experiment_name)\n        content = {'name': new_name}\n        url = self._build_api_url(\n            '/experiments/{experiment_id}'.format(\n                experiment_id=self._experiment_id\n            )\n        )\n        res = self._session.put(url, json=content)\n        res.raise_for_status()\n        self.experiment_name = new_name",
    "docstring": "Renames the experiment.\n\n        Parameters\n        ----------\n\n        See also\n        --------\n        :func:`tmserver.api.experiment.update_experiment`\n        :class:`tmlib.models.experiment.ExperimentReference`"
  },
  {
    "code": "def time(self) -> Time:\n        random_time = time(\n            self.random.randint(0, 23),\n            self.random.randint(0, 59),\n            self.random.randint(0, 59),\n            self.random.randint(0, 999999),\n        )\n        return random_time",
    "docstring": "Generate a random time object.\n\n        :return: ``datetime.time`` object."
  },
  {
    "code": "def sort_by_priority(iterable, reverse=False, default_priority=10):\n    return sorted(iterable, reverse=reverse, key=lambda o: getattr(o, 'priority', default_priority))",
    "docstring": "Return a list or objects sorted by a priority value."
  },
  {
    "code": "def list_vhosts(runas=None):\n    if runas is None and not salt.utils.platform.is_windows():\n        runas = salt.utils.user.get_user()\n    res = __salt__['cmd.run_all'](\n        [RABBITMQCTL, 'list_vhosts', '-q'],\n        reset_system_locale=False,\n        runas=runas,\n        python_shell=False)\n    _check_response(res)\n    return _output_to_list(res['stdout'])",
    "docstring": "Return a list of vhost based on rabbitmqctl list_vhosts.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rabbitmq.list_vhosts"
  },
  {
    "code": "def get_preset_prices(self, preset):\n        mask = 'mask[prices[item]]'\n        prices = self.package_preset.getObject(id=preset, mask=mask)\n        return prices",
    "docstring": "Get preset item prices.\n\n        Retrieve a SoftLayer_Product_Package_Preset record.\n\n        :param int preset: preset identifier.\n        :returns: A list of price IDs associated with the given preset_id."
  },
  {
    "code": "def scale2x(self, surface):\n        assert(self._scale == 2)\n        return self._pygame.transform.scale2x(surface)",
    "docstring": "Scales using the AdvanceMAME Scale2X algorithm which does a\n        'jaggie-less' scale of bitmap graphics."
  },
  {
    "code": "def UpdateForemanStatus(\n      self, identifier, status, pid, used_memory, display_name,\n      number_of_consumed_sources, number_of_produced_sources,\n      number_of_consumed_events, number_of_produced_events,\n      number_of_consumed_event_tags, number_of_produced_event_tags,\n      number_of_consumed_reports, number_of_produced_reports,\n      number_of_consumed_warnings, number_of_produced_warnings):\n    if not self.foreman_status:\n      self.foreman_status = ProcessStatus()\n    self._UpdateProcessStatus(\n        self.foreman_status, identifier, status, pid, used_memory, display_name,\n        number_of_consumed_sources, number_of_produced_sources,\n        number_of_consumed_events, number_of_produced_events,\n        number_of_consumed_event_tags, number_of_produced_event_tags,\n        number_of_consumed_reports, number_of_produced_reports,\n        number_of_consumed_warnings, number_of_produced_warnings)",
    "docstring": "Updates the status of the foreman.\n\n    Args:\n      identifier (str): foreman identifier.\n      status (str): human readable status of the foreman e.g. 'Idle'.\n      pid (int): process identifier (PID).\n      used_memory (int): size of used memory in bytes.\n      display_name (str): human readable of the file entry currently being\n          processed by the foreman.\n      number_of_consumed_sources (int): total number of event sources consumed\n          by the foreman.\n      number_of_produced_sources (int): total number of event sources produced\n          by the foreman.\n      number_of_consumed_events (int): total number of events consumed by\n          the foreman.\n      number_of_produced_events (int): total number of events produced by\n          the foreman.\n      number_of_consumed_event_tags (int): total number of event tags consumed\n          by the foreman.\n      number_of_produced_event_tags (int): total number of event tags produced\n          by the foreman.\n      number_of_consumed_warnings (int): total number of warnings consumed by\n          the foreman.\n      number_of_produced_warnings (int): total number of warnings produced by\n          the foreman.\n      number_of_consumed_reports (int): total number of event reports consumed\n          by the process.\n      number_of_produced_reports (int): total number of event reports produced\n          by the process."
  },
  {
    "code": "def get_binary_iterator(self):\n        CHUNK_SIZE = 1024\n        return (item for item in requests.get(self.url).iter_content(CHUNK_SIZE))",
    "docstring": "Generator to stream the remote file piece by piece."
  },
  {
    "code": "def rename_files(files, name=None):\n    for fil in files:\n        elev_file = GdalReader(file_name=fil)\n        elev, = elev_file.raster_layers\n        fn = get_fn(elev, name)\n        del elev_file\n        del elev\n        fn = os.path.join(os.path.split(fil)[0], fn)\n        os.rename(fil, fn)\n        print \"Renamed\", fil, \"to\", fn",
    "docstring": "Given a list of file paths for elevation files, this function will rename\n    those files to the format required by the pyDEM package.\n\n    This assumes a .tif extension.\n\n    Parameters\n    -----------\n    files : list\n        A list of strings of the paths to the elevation files that will be\n        renamed\n    name : str (optional)\n        Default = None. A suffix to the filename. For example\n        <filename>_suffix.tif\n\n    Notes\n    ------\n    The files are renamed in the same directory as the original file locations"
  },
  {
    "code": "def _to_fields(self, *values):\n        result = []\n        for related_instance in values:\n            if not isinstance(related_instance, model.RedisModel):\n                related_instance = self.related_field._model(related_instance)\n            result.append(getattr(related_instance, self.related_field.name))\n        return result",
    "docstring": "Take a list of values, which must be primary keys of the model linked\n        to the related collection, and return a list of related fields."
  },
  {
    "code": "def lazy_constant(fn):\n    class NewLazyConstant(LazyConstant):\n        @functools.wraps(fn)\n        def __call__(self):\n            return self.get_value()\n    return NewLazyConstant(fn)",
    "docstring": "Decorator to make a function that takes no arguments use the LazyConstant class."
  },
  {
    "code": "def combine_dictionaries(a, b):\n    c = {}\n    for key in list(b.keys()): c[key]=b[key]\n    for key in list(a.keys()): c[key]=a[key]\n    return c",
    "docstring": "returns the combined dictionary.  a's values preferentially chosen"
  },
  {
    "code": "def _createAction(self, widget, iconFileName, text, shortcut, slot):\n        icon = qutepart.getIcon(iconFileName)\n        action = QAction(icon, text, widget)\n        action.setShortcut(QKeySequence(shortcut))\n        action.setShortcutContext(Qt.WidgetShortcut)\n        action.triggered.connect(slot)\n        widget.addAction(action)\n        return action",
    "docstring": "Create QAction with given parameters and add to the widget"
  },
  {
    "code": "def _generate_sequences(self, primary_label, secondary_label, ngrams):\n        cols = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME]\n        primary_works = self._matches[self._matches[\n            constants.LABEL_FIELDNAME] == primary_label][\n                cols].drop_duplicates()\n        secondary_works = self._matches[self._matches[\n            constants.LABEL_FIELDNAME] == secondary_label][\n                cols].drop_duplicates()\n        for index, (work1, siglum1) in primary_works.iterrows():\n            text1 = self._get_text(self._corpus.get_witness(work1, siglum1))\n            label1 = '{}_{}'.format(work1, siglum1)\n            for index, (work2, siglum2) in secondary_works.iterrows():\n                text2 = self._get_text(self._corpus.get_witness(\n                    work2, siglum2))\n                label2 = '{}_{}'.format(work2, siglum2)\n                self._generate_sequences_for_texts(label1, text1, label2,\n                                                   text2, ngrams)",
    "docstring": "Generates aligned sequences between each witness labelled\n        `primary_label` and each witness labelled `secondary_label`,\n        based around `ngrams`.\n\n        :param primary_label: label for one side of the pairs of\n                              witnesses to align\n        :type primary_label: `str`\n        :param secondary_label: label for the other side of the pairs\n                                of witnesses to align\n        :type secondary_label: `str`\n        :param ngrams: n-grams to base sequences off\n        :type ngrams: `list` of `str`"
  },
  {
    "code": "def create(self, vlans):\n        data = {'vlans': vlans}\n        return super(ApiVlan, self).post('api/v3/vlan/', data)",
    "docstring": "Method to create vlan's\n\n        :param vlans: List containing vlan's desired to be created on database\n        :return: None"
  },
  {
    "code": "async def service(self, limit=None, quota: Optional[Quota] = None) -> int:\n        if self.listener:\n            await self._serviceStack(self.age, quota)\n        else:\n            logger.info(\"{} is stopped\".format(self))\n        r = len(self.rxMsgs)\n        if r > 0:\n            pracLimit = limit if limit else sys.maxsize\n            return self.processReceived(pracLimit)\n        return 0",
    "docstring": "Service `limit` number of received messages in this stack.\n\n        :param limit: the maximum number of messages to be processed. If None,\n        processes all of the messages in rxMsgs.\n        :return: the number of messages processed."
  },
  {
    "code": "def get_contacts_by_explosion(self, contactgroups):\n        self.already_exploded = True\n        if self.rec_tag:\n            logger.error(\"[contactgroup::%s] got a loop in contactgroup definition\",\n                         self.get_name())\n            if hasattr(self, 'members'):\n                return self.members\n            return ''\n        self.rec_tag = True\n        cg_mbrs = self.get_contactgroup_members()\n        for cg_mbr in cg_mbrs:\n            contactgroup = contactgroups.find_by_name(cg_mbr.strip())\n            if contactgroup is not None:\n                value = contactgroup.get_contacts_by_explosion(contactgroups)\n                if value is not None:\n                    self.add_members(value)\n        if hasattr(self, 'members'):\n            return self.members\n        return ''",
    "docstring": "Get contacts of this group\n\n        :param contactgroups: Contactgroups object, use to look for a specific one\n        :type contactgroups: alignak.objects.contactgroup.Contactgroups\n        :return: list of contact of this group\n        :rtype: list[alignak.objects.contact.Contact]"
  },
  {
    "code": "def add_item(self, key, value, cache_name=None):\n        cache_name = cache_name or ''\n        value = '%s %s=%s' % (cache_name, key, value)\n        self._set('add-cache-item', value.strip(), multi=True)\n        return self._section",
    "docstring": "Add an item into the given cache.\n\n        This is a commodity option (mainly useful for testing) allowing you\n        to store an item in a uWSGI cache during startup.\n\n        :param str|unicode key:\n\n        :param value:\n\n        :param str|unicode cache_name: If not set, default will be used."
  },
  {
    "code": "def __set_bp(self, aProcess):\n        address = self.get_address()\n        self.__previousValue = aProcess.read(address, len(self.bpInstruction))\n        if self.__previousValue == self.bpInstruction:\n            msg = \"Possible overlapping code breakpoints at %s\"\n            msg = msg % HexDump.address(address)\n            warnings.warn(msg, BreakpointWarning)\n        aProcess.write(address, self.bpInstruction)",
    "docstring": "Writes a breakpoint instruction at the target address.\n\n        @type  aProcess: L{Process}\n        @param aProcess: Process object."
  },
  {
    "code": "def filter_butter_coeffs(filtertype, freq, samplerate, order=5):\n    assert filtertype in ('low', 'high', 'band')\n    nyq = 0.5 * samplerate\n    if isinstance(freq, tuple):\n        assert filtertype == 'band'\n        low, high = freq\n        low  /= nyq\n        high /= nyq\n        b, a = signal.butter(order, [low, high], btype='band')\n    else:\n        freq = freq / nyq\n        b, a = signal.butter(order, freq, btype=filtertype)\n    return b, a",
    "docstring": "calculates the coefficients for a digital butterworth filter\n\n    filtertype: 'low', 'high', 'band'\n    freq      : cutoff freq.\n                in the case of 'band': (low, high)\n\n    Returns --> (b, a)"
  },
  {
    "code": "def refresh(self, updated_self):\n\t\tlogger.debug('refreshing binary attributes')\n\t\tself.mimetype = updated_self.binary.mimetype\n\t\tself.data = updated_self.binary.data",
    "docstring": "method to refresh binary attributes and data\n\n\t\tArgs:\n\t\t\tupdated_self (Resource): resource this binary data attaches to\n\n\t\tReturns:\n\t\t\tNone: updates attributes"
  },
  {
    "code": "def get_app_ticket(self, app_id):\n        return self.send_job_and_wait(MsgProto(EMsg.ClientGetAppOwnershipTicket),\n                                      {'app_id': app_id},\n                                      timeout=15\n                                     )",
    "docstring": "Get app ownership ticket\n\n        :param app_id: app id\n        :type app_id: :class:`int`\n        :return: `CMsgClientGetAppOwnershipTicketResponse <https://github.com/ValvePython/steam/blob/39627fe883feeed2206016bacd92cf0e4580ead6/protobufs/steammessages_clientserver.proto#L158-L162>`_\n        :rtype: proto message"
  },
  {
    "code": "def select_extended(cat_table):\n    try:\n        l = [len(row.strip()) > 0 for row in cat_table['Extended_Source_Name'].data]\n        return np.array(l, bool)\n    except KeyError:\n        return cat_table['Extended']",
    "docstring": "Select only rows representing extended sources from a catalog table"
  },
  {
    "code": "def _find_header_row(self):\n        th_max = 0\n        header_idx = 0\n        for idx, tr in enumerate(self._tr_nodes):\n            th_count = len(tr.contents.filter_tags(matches=ftag('th')))\n            if th_count > th_max:\n                th_max = th_count\n                header_idx = idx\n        if not th_max:\n            return\n        self._log('found header at row %d (%d <th> elements)' % \\\n                    (header_idx, th_max))\n        header_row = self._tr_nodes.pop(header_idx)\n        return header_row.contents.filter_tags(matches=ftag('th'))",
    "docstring": "Evaluate all rows and determine header position, based on\n        greatest number of 'th' tagged elements"
  },
  {
    "code": "def add(self, histogram: Histogram1D):\n        if self.binning and not self.binning == histogram.binning:\n            raise ValueError(\"Cannot add histogram with different binning.\")\n        self.histograms.append(histogram)",
    "docstring": "Add a histogram to the collection."
  },
  {
    "code": "def get_versioned_references_for(self, instance):\n        vrefs = []\n        refs = instance.getRefs(relationship=self.relationship)\n        ref_versions = getattr(instance, REFERENCE_VERSIONS, None)\n        if ref_versions is None:\n            return refs\n        for ref in refs:\n            uid = api.get_uid(ref)\n            version = ref_versions.get(uid)\n            vrefs.append(self.retrieve_version(ref, version))\n        return vrefs",
    "docstring": "Returns the versioned references for the given instance"
  },
  {
    "code": "def AddAccelerator(self, modifiers, key, action):\n newId = wx.NewId()\n self.Bind(wx.EVT_MENU, action, id = newId)\n self.RawAcceleratorTable.append((modifiers, key, newId))\n self.SetAcceleratorTable(wx.AcceleratorTable(self.RawAcceleratorTable))\n return newId",
    "docstring": "Add an accelerator.\n \n Modifiers and key follow the same pattern as the list used to create wx.AcceleratorTable objects."
  },
  {
    "code": "def readXML(self):\n        data = self.readLongString()\n        root = xml.fromstring(data)\n        self.context.addObject(root)\n        return root",
    "docstring": "Read XML."
  },
  {
    "code": "def to_match(self):\n        self.validate()\n        mark_name, field_name = self.location.get_location_name()\n        validate_safe_string(mark_name)\n        if field_name is None:\n            return u'$matched.%s' % (mark_name,)\n        else:\n            validate_safe_string(field_name)\n            return u'$matched.%s.%s' % (mark_name, field_name)",
    "docstring": "Return a unicode object with the MATCH representation of this ContextField."
  },
  {
    "code": "def undefinedImageType(self):\n        if self._undefinedImageType is None:\n            ctx = SparkContext._active_spark_context\n            self._undefinedImageType = \\\n                ctx._jvm.org.apache.spark.ml.image.ImageSchema.undefinedImageType()\n        return self._undefinedImageType",
    "docstring": "Returns the name of undefined image type for the invalid image.\n\n        .. versionadded:: 2.3.0"
  },
  {
    "code": "def make_call_keywords(stack_builders, count):\n    out = []\n    for _ in range(count):\n        value = make_expr(stack_builders)\n        load_kwname = stack_builders.pop()\n        if not isinstance(load_kwname, instrs.LOAD_CONST):\n            raise DecompilationError(\n                \"Expected a LOAD_CONST, but got %r\" % load_kwname\n            )\n        if not isinstance(load_kwname.arg, str):\n            raise DecompilationError(\n                \"Expected LOAD_CONST of a str, but got %r.\" % load_kwname,\n            )\n        out.append(ast.keyword(arg=load_kwname.arg, value=value))\n    out.reverse()\n    return out",
    "docstring": "Make the keywords entry for an ast.Call node."
  },
  {
    "code": "async def receive_events(self, request: HttpRequest):\n        body = await request.read()\n        s = self.settings()\n        try:\n            content = ujson.loads(body)\n        except ValueError:\n            return json_response({\n                'error': True,\n                'message': 'Cannot decode body'\n            }, status=400)\n        secret = s['app_secret']\n        actual_sig = request.headers['X-Hub-Signature']\n        expected_sig = sign_message(body, secret)\n        if not hmac.compare_digest(actual_sig, expected_sig):\n            return json_response({\n                'error': True,\n                'message': 'Invalid signature',\n            }, status=401)\n        for entry in content['entry']:\n            for raw_message in entry.get('messaging', []):\n                message = FacebookMessage(raw_message, self)\n                await self.handle_event(message)\n        return json_response({\n            'ok': True,\n        })",
    "docstring": "Events received from Facebook"
  },
  {
    "code": "def get_share_properties(self, share_name, timeout=None):\n        _validate_not_none('share_name', share_name)\n        request = HTTPRequest()\n        request.method = 'GET'\n        request.host = self._get_host()\n        request.path = _get_path(share_name)\n        request.query = [\n            ('restype', 'share'),\n            ('timeout', _int_to_str(timeout)),\n        ]\n        response = self._perform_request(request)\n        return _parse_share(share_name, response)",
    "docstring": "Returns all user-defined metadata and system properties for the\n        specified share. The data returned does not include the shares's\n        list of files or directories.\n\n        :param str share_name:\n            Name of existing share.\n        :param int timeout:\n            The timeout parameter is expressed in seconds.\n        :return: A Share that exposes properties and metadata.\n        :rtype: :class:`.Share`"
  },
  {
    "code": "def install_event_handlers(self, categories=None, handlers=None):\n        if categories is not None and handlers is not None:\n            raise ValueError(\"categories and handlers are mutually exclusive!\")\n        from .events import get_event_handler_classes\n        if categories:\n            raise NotImplementedError()\n            handlers = [cls() for cls in get_event_handler_classes(categories=categories)]\n        else:\n            handlers = handlers or [cls() for cls in get_event_handler_classes()]\n        self._event_handlers = handlers",
    "docstring": "Install the `EventHandlers for this `Node`. If no argument is provided\n        the default list of handlers is installed.\n\n        Args:\n            categories: List of categories to install e.g. base + can_change_physics\n            handlers: explicit list of :class:`EventHandler` instances.\n                      This is the most flexible way to install handlers.\n\n        .. note::\n\n            categories and handlers are mutually exclusive."
  },
  {
    "code": "def import_extension_module(ext_name):\n    import importlib\n    try:\n        return importlib.import_module('.' + ext_name, 'nnabla_ext')\n    except ImportError as e:\n        from nnabla import logger\n        logger.error('Extension `{}` does not exist.'.format(ext_name))\n        raise e",
    "docstring": "Import an extension module by name.\n\n    The extension modules are installed under the `nnabla_ext` package as\n    namespace packages. All extension modules provide a unified set of APIs.\n\n    Args:\n        ext_name(str): Extension name. e.g. 'cpu', 'cuda', 'cudnn' etc.\n\n    Returns: module\n        An Python module of a particular NNabla extension.\n\n    Example:\n\n        .. code-block:: python\n\n            ext = import_extension_module('cudnn')\n            available_devices = ext.get_devices()\n            print(available_devices)\n            ext.device_synchronize(available_devices[0])\n            ext.clear_memory_cache()"
  },
  {
    "code": "def check_positive(value, strict=False):\n    if not strict and value < 0:\n        raise ValueError(\"Value must be positive or zero, not %s\" % str(value))\n    if strict and value <= 0:\n        raise ValueError(\"Value must be positive, not %s\" % str(value))",
    "docstring": "Checks if variable is positive\n\n    @param value: value to check\n    @type value: C{integer types}, C{float} or C{Decimal}\n\n    @return: None when check successful\n\n    @raise ValueError: check failed"
  },
  {
    "code": "def filename(self, prefix='', suffix='', extension='.py'):\n        return BASE_NAME.format(prefix, self.num, suffix, extension)",
    "docstring": "Returns filename padded with leading zeros"
  },
  {
    "code": "def wait_for_workers(self, min_n_workers=1):\n\t\tself.logger.debug('wait_for_workers trying to get the condition')\n\t\twith self.thread_cond:\n\t\t\twhile (self.dispatcher.number_of_workers() < min_n_workers):\n\t\t\t\tself.logger.debug('HBMASTER: only %i worker(s) available, waiting for at least %i.'%(self.dispatcher.number_of_workers(), min_n_workers))\n\t\t\t\tself.thread_cond.wait(1)\n\t\t\t\tself.dispatcher.trigger_discover_worker()\n\t\tself.logger.debug('Enough workers to start this run!')",
    "docstring": "helper function to hold execution until some workers are active\n\n\t\tParameters\n\t\t----------\n\t\tmin_n_workers: int\n\t\t\tminimum number of workers present before the run starts"
  },
  {
    "code": "def cols_(self) -> pd.DataFrame:\n        try:\n            s = self.df.iloc[0]\n            df = pd.DataFrame(s)\n            df = df.rename(columns={0: \"value\"})\n            def run(row):\n                t = row[0]\n                return type(t).__name__\n            s = df.apply(run, axis=1)\n            df = df.rename(columns={0: \"value\"})\n            df[\"types\"] = s\n            return df\n        except Exception as e:\n            self.err(e)",
    "docstring": "Returns a dataframe with columns info\n\n        :return: a pandas dataframe\n        :rtype: pd.DataFrame\n\n        :example: ``ds.cols_()``"
  },
  {
    "code": "def check_custom_concurrency(default, forced, logger=None):\n    logger = logger or LOGGER\n    cmc_msg = 'Invalid \"max_concurrent_tasks: '\n    if not isinstance(forced, int):\n        logger.warn(cmc_msg + 'expecting int')\n    elif forced > default:\n        msg = 'may not be greater than: %s' % default\n        logger.warn(cmc_msg + msg)\n    elif forced < 1:\n        msg = 'may not be less than 1'\n        logger.warn(cmc_msg + msg)\n    else:\n        default = forced\n    return default",
    "docstring": "Get the proper concurrency value according to the default one\n    and the one specified by the crawler.\n\n    :param int default:\n      default tasks concurrency\n\n    :param forced:\n      concurrency asked by crawler\n\n    :return:\n      concurrency to use.\n    :rtype: int"
  },
  {
    "code": "async def ping(self, conversation_id: uuid.UUID = None) -> float:\n        cmd = convo.Ping(conversation_id=conversation_id or uuid.uuid4())\n        result = await self.dispatcher.start_conversation(cmd)\n        return await result",
    "docstring": "Send a message to the remote server to check liveness.\n\n        Returns:\n            The round-trip time to receive a Pong message in fractional seconds\n\n        Examples:\n\n            >>> async with connect() as conn:\n            >>>     print(\"Sending a PING to the server\")\n            >>>     time_secs = await conn.ping()\n            >>>     print(\"Received a PONG after {} secs\".format(time_secs))"
  },
  {
    "code": "def initial_global_state(self) -> GlobalState:\n        environment = Environment(\n            self.callee_account,\n            self.caller,\n            self.call_data,\n            self.gas_price,\n            self.call_value,\n            self.origin,\n            code=self.code or self.callee_account.code,\n        )\n        return super().initial_global_state_from_environment(\n            environment, active_function=\"fallback\"\n        )",
    "docstring": "Initialize the execution environment."
  },
  {
    "code": "def __validate1 (property):\n    assert isinstance(property, Property)\n    msg = None\n    if not property.feature.free:\n        feature.validate_value_string (property.feature, property.value)",
    "docstring": "Exit with error if property is not valid."
  },
  {
    "code": "def remove_monitor(self, handle):\n        action = (handle, \"delete\", None, None)\n        if self._currently_notifying:\n            self._deferred_adjustments.append(action)\n        else:\n            self._adjust_monitor_internal(*action)",
    "docstring": "Remove a previously registered monitor.\n\n        See :meth:`AbstractDeviceAdapter.adjust_monitor`."
  },
  {
    "code": "def classify_dataset(dataset, fn):\n    if fn is None:\n        fn = default_classify_function\n    classified_dataset = OrderedDict()\n    for data in dataset:\n        classify_name = fn(data)\n        if classify_name not in classified_dataset:\n            classified_dataset[classify_name] = []\n        classified_dataset[classify_name].append(data)\n    return classified_dataset",
    "docstring": "Classify dataset via fn\n\n    Parameters\n    ----------\n    dataset : list\n        A list of data\n    fn : function\n        A function which recieve :attr:`data` and return classification string.\n        It if is None, a function which return the first item of the\n        :attr:`data` will be used (See ``with_filename`` parameter of\n        :func:`maidenhair.load` function).\n\n    Returns\n    -------\n    dict\n        A classified dataset"
  },
  {
    "code": "def prepare_onetime_pipeline():\n    runner = ForemastRunner()\n    runner.write_configs()\n    runner.create_pipeline(onetime=os.getenv('ENV'))\n    runner.cleanup()",
    "docstring": "Entry point for single use pipeline setup in the defined app."
  },
  {
    "code": "def gc2gdlat(gclat):\n    WGS84_e2 = 0.006694379990141317\n    return np.rad2deg(-np.arctan(np.tan(np.deg2rad(gclat))/(WGS84_e2 - 1)))",
    "docstring": "Converts geocentric latitude to geodetic latitude using WGS84.\n\n    Parameters\n    ==========\n    gclat : array_like\n        Geocentric latitude\n\n    Returns\n    =======\n    gdlat : ndarray or float\n        Geodetic latitude"
  },
  {
    "code": "def time_question_features(self, text):\n        features = {}\n        all_words = \" \".join(self.positive + self.negative).split()\n        all_first_words = []\n        for sentence in self.positive + self.negative:\n            all_first_words.append(\n                sentence.split(' ', 1)[0]\n            )\n        for word in text.split():\n            features['first_word({})'.format(word)] = (word in all_first_words)\n        for word in text.split():\n            features['contains({})'.format(word)] = (word in all_words)\n        for letter in 'abcdefghijklmnopqrstuvwxyz':\n            features['count({})'.format(letter)] = text.lower().count(letter)\n            features['has({})'.format(letter)] = (letter in text.lower())\n        return features",
    "docstring": "Provide an analysis of significant features in the string."
  },
  {
    "code": "def get_class_method(cls_or_inst, method_name):\n    cls = cls_or_inst if isinstance(cls_or_inst, type) else cls_or_inst.__class__\n    meth = getattr(cls, method_name, None)\n    if isinstance(meth, property):\n        meth = meth.fget\n    elif isinstance(meth, cached_property):\n        meth = meth.func\n    return meth",
    "docstring": "Returns a method from a given class or instance. When the method doest not exist, it returns `None`. Also works with\n    properties and cached properties."
  },
  {
    "code": "def random_expr_with_required_var(depth, required_var, optional_list, ops):\n  if not depth:\n    if required_var:\n      return required_var\n    return str(optional_list[random.randrange(len(optional_list))])\n  max_depth_side = random.randrange(2)\n  other_side_depth = random.randrange(depth)\n  required_var_side = random.randrange(2)\n  left = random_expr_with_required_var(\n      depth - 1 if max_depth_side else other_side_depth, required_var\n      if required_var_side else None, optional_list, ops)\n  right = random_expr_with_required_var(\n      depth - 1 if not max_depth_side else other_side_depth, required_var\n      if not required_var_side else None, optional_list, ops)\n  op = ops[random.randrange(len(ops))]\n  return ExprNode(left, right, op)",
    "docstring": "Generate a random expression tree with a required variable.\n\n  The required variable appears exactly once in the expression.\n\n  Args:\n    depth: At least one leaf will be this many levels down from the top.\n    required_var: A char. This char is guaranteed to be placed exactly once at\n        a leaf somewhere in the tree. This is the var to solve for.\n    optional_list: A list of chars. These chars are randomly selected as leaf\n        values. These are constant vars.\n    ops: A list of ExprOp instances.\n\n  Returns:\n    An ExprNode instance which is the root of the generated expression tree."
  },
  {
    "code": "def make_request(endpoint, **kwargs):\n        data = kwargs.get('json', [])\n        package = kwargs.get('package', None)\n        method = kwargs.get('method', 'GET')\n        function = getattr(requests, method.lower())\n        try:\n            if package:\n                response = function(endpoint, data=data,\n                                    files={'file': package})\n            else:\n                response = function(endpoint, json=data)\n        except requests.exceptions.ConnectionError:\n            LOG.error(\"Couldn't connect to NApps server %s.\", endpoint)\n            sys.exit(1)\n        return response",
    "docstring": "Send a request to server."
  },
  {
    "code": "def IsPathSuffix(mod_path, path):\n  return (mod_path.endswith(path) and\n          (len(mod_path) == len(path) or\n           mod_path[:-len(path)].endswith(os.sep)))",
    "docstring": "Checks whether path is a full path suffix of mod_path.\n\n  Args:\n    mod_path: Must be an absolute path to a source file. Must not have\n              file extension.\n    path: A relative path. Must not have file extension.\n\n  Returns:\n    True if path is a full path suffix of mod_path. False otherwise."
  },
  {
    "code": "def read_scenarios(filename):\n    filename = os.path.abspath(filename)\n    blocks = {}\n    parser = ConfigParser()\n    try:\n        parser.read(filename)\n    except MissingSectionHeaderError:\n        base_name = os.path.basename(filename)\n        name = os.path.splitext(base_name)[0]\n        section = '[%s]\\n' % name\n        content = section + open(filename).read()\n        parser.readfp(StringIO(content))\n    for section in parser.sections():\n        items = parser.items(section)\n        items.append(('scenario_name', section))\n        items.append(('full_path', filename))\n        blocks[section] = {}\n        for key, value in items:\n            blocks[section][key] = value\n    return blocks",
    "docstring": "Read keywords dictionary from file.\n\n    :param filename: Name of file holding scenarios .\n\n    :return Dictionary of with structure like this\n        {{ 'foo' : { 'a': 'b', 'c': 'd'},\n            { 'bar' : { 'd': 'e', 'f': 'g'}}\n\n    A scenarios file may look like this:\n\n        [jakarta_flood]\n        hazard: /path/to/hazard.tif\n        exposure: /path/to/exposure.tif\n        function: function_id\n        aggregation: /path/to/aggregation_layer.tif\n        extent: minx, miny, maxx, maxy\n\n    Notes:\n        path for hazard, exposure, and aggregation are relative to scenario\n        file path"
  },
  {
    "code": "def len_gt(name, value):\n    ret = {'name': name,\n           'result': False,\n           'comment': '',\n           'changes': {}}\n    if name not in __reg__:\n        ret['result'] = False\n        ret['comment'] = 'Value {0} not in register'.format(name)\n        return ret\n    if len(__reg__[name]['val']) > value:\n        ret['result'] = True\n    return ret",
    "docstring": "Only succeed if length of the given register location is greater than\n    the given value.\n\n    USAGE:\n\n    .. code-block:: yaml\n\n        foo:\n          check.len_gt:\n            - value: 42\n\n        run_remote_ex:\n          local.cmd:\n            - tgt: '*'\n            - func: test.ping\n            - require:\n              - check: foo"
  },
  {
    "code": "def write_interactions(G, path, delimiter=' ',  encoding='utf-8'):\n    for line in generate_interactions(G, delimiter):\n        line += '\\n'\n        path.write(line.encode(encoding))",
    "docstring": "Write a DyNetx graph in interaction list format.\n\n\n        Parameters\n        ----------\n\n        G : graph\n            A DyNetx graph.\n\n        path : basestring\n            The desired output filename\n\n        delimiter : character\n            Column delimiter"
  },
  {
    "code": "def export_organizations(self, outfile):\n        exporter = SortingHatOrganizationsExporter(self.db)\n        dump = exporter.export()\n        try:\n            outfile.write(dump)\n            outfile.write('\\n')\n        except IOError as e:\n            raise RuntimeError(str(e))\n        return CMD_SUCCESS",
    "docstring": "Export organizations information to a file.\n\n        The method exports information related to organizations, to\n        the given 'outfile' output file.\n\n        :param outfile: destination file object"
  },
  {
    "code": "def _reset_session(self):\n        headers = {\"User-Agent\": self._user_agent}\n        self._session = requests.Session()\n        self._session.headers.update(headers)\n        self._is_logged_in = False",
    "docstring": "Set session information"
  },
  {
    "code": "def pprint(self, imports=None, prefix=\"\\n    \",unknown_value='<?>',\n               qualify=False, separator=\"\"):\n        r = Parameterized.pprint(self,imports,prefix,\n                                 unknown_value=unknown_value,\n                                 qualify=qualify,separator=separator)\n        classname=self.__class__.__name__\n        return r.replace(\".%s(\"%classname,\".%s.instance(\"%classname)",
    "docstring": "Same as Parameterized.pprint, except that X.classname(Y\n        is replaced with X.classname.instance(Y"
  },
  {
    "code": "def run(self):\n        while not self._finished.isSet():\n            self._func(self._reference)\n            self._finished.wait(self._func._interval / 1000.0)",
    "docstring": "Keep running this thread until it's stopped"
  },
  {
    "code": "def export(self, exporter=None, force_stroke=False):\n        exporter = SVGExporter() if exporter is None else exporter\n        if self._data is None:\n            raise Exception(\"This SWF was not loaded! (no data)\")\n        if len(self.tags) == 0:\n            raise Exception(\"This SWF doesn't contain any tags!\")\n        return exporter.export(self, force_stroke)",
    "docstring": "Export this SWF using the specified exporter. \n        When no exporter is passed in the default exporter used \n        is swf.export.SVGExporter.\n        \n        Exporters should extend the swf.export.BaseExporter class.\n        \n        @param exporter : the exporter to use\n        @param force_stroke : set to true to force strokes on fills,\n                              useful for some edge cases."
  },
  {
    "code": "def inrypl(vertex, direct, plane):\n    assert (isinstance(plane, stypes.Plane))\n    vertex = stypes.toDoubleVector(vertex)\n    direct = stypes.toDoubleVector(direct)\n    nxpts = ctypes.c_int()\n    xpt = stypes.emptyDoubleVector(3)\n    libspice.inrypl_c(vertex, direct, ctypes.byref(plane), ctypes.byref(nxpts),\n                      xpt)\n    return nxpts.value, stypes.cVectorToPython(xpt)",
    "docstring": "Find the intersection of a ray and a plane.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/inrypl_c.html\n\n    :param vertex: Vertex vector of ray.\n    :type vertex: 3-Element Array of floats\n    :param direct: Direction vector of ray.\n    :type direct: 3-Element Array of floats\n    :param plane: A SPICE plane.\n    :type plane: spiceypy.utils.support_types.Plane\n    :return:\n            Number of intersection points of ray and plane,\n            Intersection point,\n            if nxpts == 1.\n    :rtype: tuple"
  },
  {
    "code": "def outlays(self):\n        return pd.DataFrame({x.name: x.outlays for x in self.securities})",
    "docstring": "Returns a DataFrame of outlays for each child SecurityBase"
  },
  {
    "code": "def node_cmd(cmd_name, node_dict):\n    sc = {\"run\": cmd_startstop, \"stop\": cmd_startstop,\n          \"connect\": cmd_connect, \"details\": cmd_details}\n    node_num = node_selection(cmd_name, len(node_dict))\n    refresh_main = None\n    if node_num != 0:\n        (node_valid, node_info) = node_validate(node_dict, node_num, cmd_name)\n        if node_valid:\n            sub_cmd = sc[cmd_name]\n            refresh_main = sub_cmd(node_dict[node_num], cmd_name, node_info)\n        else:\n            ui_print_suffix(node_info, C_ERR)\n            sleep(1.5)\n    else:\n        ui_print(\" - Exit Command\")\n        sleep(0.5)\n    return refresh_main",
    "docstring": "Process commands that target specific nodes."
  },
  {
    "code": "def filter_from_alias(self, alias, backend=None):\n        def alias_filter(key_item):\n            key, item = key_item\n            return ((alias is None or alias in key) and\n                    (backend is None or item.backend == backend))\n        items = six.moves.filter(alias_filter, six.iteritems(self))\n        aliases = collections.OrderedDict(sorted(items, key=lambda a: a[0].lower()))\n        return aliases",
    "docstring": "Return aliases that start with the given `alias`, optionally filtered\n        by backend."
  },
  {
    "code": "def notify_change(self, screen_id, x_origin, y_origin, width, height):\n        if not isinstance(screen_id, baseinteger):\n            raise TypeError(\"screen_id can only be an instance of type baseinteger\")\n        if not isinstance(x_origin, baseinteger):\n            raise TypeError(\"x_origin can only be an instance of type baseinteger\")\n        if not isinstance(y_origin, baseinteger):\n            raise TypeError(\"y_origin can only be an instance of type baseinteger\")\n        if not isinstance(width, baseinteger):\n            raise TypeError(\"width can only be an instance of type baseinteger\")\n        if not isinstance(height, baseinteger):\n            raise TypeError(\"height can only be an instance of type baseinteger\")\n        self._call(\"notifyChange\",\n                     in_p=[screen_id, x_origin, y_origin, width, height])",
    "docstring": "Requests a size change.\n\n        in screen_id of type int\n            Logical guest screen number.\n\n        in x_origin of type int\n            Location of the screen in the guest.\n\n        in y_origin of type int\n            Location of the screen in the guest.\n\n        in width of type int\n            Width of the guest display, in pixels.\n\n        in height of type int\n            Height of the guest display, in pixels."
  },
  {
    "code": "def _set(self, jsonData) :\n        self[\"username\"] = jsonData[\"user\"]\n        self[\"active\"] = jsonData[\"active\"]\n        self[\"extra\"] = jsonData[\"extra\"]\n        try:\n            self[\"changePassword\"] = jsonData[\"changePassword\"]\n        except Exception as e:\n            pass\n        try :\n            self[\"password\"] = jsonData[\"passwd\"]\n        except KeyError :\n            self[\"password\"] = \"\"\n        self.URL = \"%s/user/%s\" % (self.connection.URL, self[\"username\"])",
    "docstring": "Initialize all fields at once. If no password is specified, it will be set as an empty string"
  },
  {
    "code": "def _check_cmd(call):\n    if call['retcode'] != 0:\n        comment = ''\n        std_err = call.get('stderr')\n        std_out = call.get('stdout')\n        if std_err:\n            comment += std_err\n        if std_out:\n            comment += std_out\n        raise CommandExecutionError('Error running command: {0}'.format(comment))\n    return call",
    "docstring": "Check the output of the cmd.run_all function call."
  },
  {
    "code": "def apply_network(network, x, chunksize=None):\n    network_is_cuda = next(network.parameters()).is_cuda\n    x = torch.from_numpy(x)\n    with torch.no_grad():\n        if network_is_cuda:\n            x = x.cuda()\n        if chunksize is None:\n            return from_var(network(x))\n        return np.concatenate(\n            [from_var(network(x[i: i + chunksize]))\n             for i in range(0, len(x), chunksize)])",
    "docstring": "Apply a pytorch network, potentially in chunks"
  },
  {
    "code": "def closest(self, obj, group, defaults=True):\n        components = (obj.__class__.__name__,\n                      group_sanitizer(obj.group),\n                      label_sanitizer(obj.label))\n        target = '.'.join([c for c in components if c])\n        return self.find(components).options(group, target=target,\n                                             defaults=defaults)",
    "docstring": "This method is designed to be called from the root of the\n        tree. Given any LabelledData object, this method will return\n        the most appropriate Options object, including inheritance.\n\n        In addition, closest supports custom options by checking the\n        object"
  },
  {
    "code": "def with_defaults(self, obj):\n        self.check_valid_keys(obj)\n        obj = dict(obj)\n        for (key, value) in self.defaults.items():\n            if key not in obj:\n                obj[key] = value\n        return obj",
    "docstring": "Given a dict of hyperparameter settings, return a dict containing\n        those settings augmented by the defaults for any keys missing from\n        the dict."
  },
  {
    "code": "def transform_data(self, data, request=None, response=None, context=None):\n        transform = self.transform\n        if hasattr(transform, 'context'):\n            self.transform.context = context\n        if transform and not (isinstance(transform, type) and isinstance(data, transform)):\n            if self._params_for_transform:\n                return transform(data, **self._arguments(self._params_for_transform, request, response))\n            else:\n                return transform(data)\n        return data",
    "docstring": "Runs the transforms specified on this endpoint with the provided data, returning the data modified"
  },
  {
    "code": "def classify_harmonic(self, partial_labels, use_CMN=True):\n    labels = np.array(partial_labels, copy=True)\n    unlabeled = labels == -1\n    fl, classes = _onehot(labels[~unlabeled])\n    L = self.laplacian(normed=False)\n    if ss.issparse(L):\n      L = L.tocsr()[unlabeled].toarray()\n    else:\n      L = L[unlabeled]\n    Lul = L[:,~unlabeled]\n    Luu = L[:,unlabeled]\n    fu = -np.linalg.solve(Luu, Lul.dot(fl))\n    if use_CMN:\n      scale = (1 + fl.sum(axis=0)) / fu.sum(axis=0)\n      fu *= scale\n    labels[unlabeled] = classes[fu.argmax(axis=1)]\n    return labels",
    "docstring": "Harmonic function method for semi-supervised classification,\n    also known as the Gaussian Mean Fields algorithm.\n\n    partial_labels: (n,) array of integer labels, -1 for unlabeled.\n    use_CMN : when True, apply Class Mass Normalization\n\n    From \"Semi-Supervised Learning Using Gaussian Fields and Harmonic Functions\"\n      by Zhu, Ghahramani, and Lafferty in 2003.\n\n    Based on the matlab code at:\n      http://pages.cs.wisc.edu/~jerryzhu/pub/harmonic_function.m"
  },
  {
    "code": "def qstring(option):\n    if (re.match(NODE_ATTR_RE, option) is None and\n            re.match(CHEF_CONST_RE, option) is None):\n        return \"'%s'\" % option\n    else:\n        return option",
    "docstring": "Custom quoting method for jinja."
  },
  {
    "code": "def single_case(self, i, case):\n        if self.single_stack:\n            self.single_stack.pop()\n        self.single_stack.append(case)\n        try:\n            t = next(i)\n            if self.use_format and t in _CURLY_BRACKETS:\n                self.handle_format(t, i)\n            elif t == '\\\\':\n                try:\n                    t = next(i)\n                    self.reference(t, i)\n                except StopIteration:\n                    self.result.append(t)\n                    raise\n            elif self.single_stack:\n                self.result.append(self.convert_case(t, self.get_single_stack()))\n        except StopIteration:\n            pass",
    "docstring": "Uppercase or lowercase the next character."
  },
  {
    "code": "def early_arbiter_linking(self, arbiter_name, params):\n        if not self.arbiters:\n            params.update({\n                'name': arbiter_name, 'arbiter_name': arbiter_name,\n                'host_name': socket.gethostname(),\n                'address': '127.0.0.1', 'port': 7770,\n                'spare': '0'\n            })\n            logger.warning(\"There is no arbiter, I add myself (%s) reachable on %s:%d\",\n                           arbiter_name, params['address'], params['port'])\n            arb = ArbiterLink(params, parsing=True)\n            self.arbiters = ArbiterLinks([arb])\n        self.arbiters.fill_default()\n        self.modules.fill_default()\n        self.arbiters.linkify(modules=self.modules)\n        self.modules.linkify()",
    "docstring": "Prepare the arbiter for early operations\n\n        :param arbiter_name: default arbiter name if no arbiter exist in the configuration\n        :type arbiter_name: str\n        :return: None"
  },
  {
    "code": "def get_lock(self, path):\n        if self.lockfile:\n            return self.lockfile.LockFile(path)\n        else:\n            with self.job_locks_lock:\n                if path not in self.job_locks:\n                    lock = threading.Lock()\n                    self.job_locks[path] = lock\n                else:\n                    lock = self.job_locks[path]\n            return lock",
    "docstring": "Get a job lock corresponding to the path - assumes parent\n        directory exists but the file itself does not."
  },
  {
    "code": "def compose(*funcs):\n    if not funcs:\n        return lambda *args: args[0] if args else None\n    if len(funcs) == 1:\n        return funcs[0]\n    last = funcs[-1]\n    rest = funcs[0:-1]\n    return lambda *args: reduce(lambda ax, func: func(ax),\n                                reversed(rest), last(*args))",
    "docstring": "chained function composition wrapper\n\n    creates function f, where f(x) = arg0(arg1(arg2(...argN(x))))\n\n    if *funcs is empty, an identity function is returned.\n\n    Args:\n        *funcs: list of functions to chain\n    \n    Returns:\n        a new function composed of chained calls to *args"
  },
  {
    "code": "def _save_multi(data, file_name, sep=\";\"):\n    logger.debug(\"saving multi\")\n    with open(file_name, \"w\", newline='') as f:\n        logger.debug(f\"{file_name} opened\")\n        writer = csv.writer(f, delimiter=sep)\n        try:\n            writer.writerows(itertools.zip_longest(*data))\n        except Exception as e:\n            logger.info(f\"Exception encountered in batch._save_multi: {e}\")\n            raise ExportFailed\n        logger.debug(\"wrote rows using itertools in _save_multi\")",
    "docstring": "convenience function for storing data column-wise in a csv-file."
  },
  {
    "code": "def process(self):\n        for locale in self._fields.keys():\n            self._client._put(\n                \"{0}/files/{1}/process\".format(\n                    self.__class__.base_url(\n                        self.space.id,\n                        self.id,\n                        environment_id=self._environment_id\n                    ),\n                    locale\n                ),\n                {},\n                headers=self._update_headers()\n            )\n        return self.reload()",
    "docstring": "Calls the process endpoint for all locales of the asset.\n\n        API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets/asset-processing"
  },
  {
    "code": "def create(*events):\n    or_event = threading.Event()\n    def changed():\n        if any([event.is_set() for event in events]):\n            or_event.set()\n        else:\n            or_event.clear()\n    for e in events:\n        orify(e, changed)\n    changed()\n    return or_event",
    "docstring": "Creates a new multi_event\n\n    The multi_event listens to all events passed in the \"events\" parameter.\n\n    :param events: a list of threading.Events\n    :return: The multi_event\n    :rtype: threading.Event"
  },
  {
    "code": "def get_error_redirect(self, provider, reason):\n        info = self.model._meta.app_label, self.model._meta.model_name\n        return reverse('admin:%s_%s_changelist' % info)",
    "docstring": "Return url to redirect on login failure."
  },
  {
    "code": "def showstructure(self, dataman=True, column=True, subtable=False,\n                      sort=False):\n        return self._showstructure(dataman, column, subtable, sort)",
    "docstring": "Show table structure in a formatted string.\n\n        The structure of this table and optionally its subtables is shown.\n        It shows the data manager info and column descriptions.\n        Optionally the columns are sorted in alphabetical order.\n\n        `dataman`\n          Show data manager info? If False, only column info is shown.\n          If True, data manager info and columns per data manager are shown.\n        `column`\n          Show column description per data manager? Only takes effect if\n          dataman=True.\n        `subtable`\n          Show the structure of all subtables (recursively).\n          The names of subtables are always shown.\n        'sort'\n          Sort the columns in alphabetical order?"
  },
  {
    "code": "def get_state_for_transition(self, transition):\n        if not isinstance(transition, Transition):\n            raise TypeError(\"transition must be of type Transition\")\n        if transition.to_state == self.state_id or transition.to_state is None:\n            return self\n        else:\n            return self.states[transition.to_state]",
    "docstring": "Calculate the target state of a transition\n\n        :param transition: The transition of which the target state is determined\n        :return: the to-state of the transition\n        :raises exceptions.TypeError: if the transition parameter is of wrong type"
  },
  {
    "code": "def delete(self, using=None):\n        if self.is_alone:\n            self.topic.delete()\n        else:\n            super(AbstractPost, self).delete(using)\n            self.topic.update_trackers()",
    "docstring": "Deletes the post instance."
  },
  {
    "code": "def extract(text, default=UNKNOWN):\n        if not text:\n            return default\n        found = CALLING_CONVENTION_TYPES.pattern.match(text)\n        if found:\n            return found.group('cc')\n        return default",
    "docstring": "extracts calling convention from the text. If the calling convention\n        could not be found, the \"default\"is used"
  },
  {
    "code": "def _day_rule_matches(self, rule, dt):\n        if dt.weekday() == 4:\n            sat = dt + datetime.timedelta(days=1)\n            if super(USFederalHolidays, self)._day_rule_matches(rule, sat):\n                return True\n        elif dt.weekday() == 0:\n            sun = dt - datetime.timedelta(days=1)\n            if super(USFederalHolidays, self)._day_rule_matches(rule, sun):\n                return True\n        return super(USFederalHolidays, self)._day_rule_matches(rule, dt)",
    "docstring": "Day-of-month-specific US federal holidays that fall on Sat or Sun are\n        observed on Fri or Mon respectively. Note that this method considers\n        both the actual holiday and the day of observance to be holidays."
  },
  {
    "code": "def init_reddit(generator):\n    auth_dict = generator.settings.get('REDDIT_POSTER_AUTH')\n    if auth_dict is None:\n        log.info(\"Could not find REDDIT_POSTER_AUTH key in settings, reddit plugin won't function\")\n        generator.get_reddit = lambda: None\n        return\n    reddit = praw.Reddit(**auth_dict)\n    generator.get_reddit = lambda: reddit",
    "docstring": "this is a hack to make sure the reddit object keeps track of a session\n    trough article scanning, speeding up networking as the connection can be \n    kept alive."
  },
  {
    "code": "def group_callback(self, iocb):\n        if _debug: IOGroup._debug(\"group_callback %r\", iocb)\n        for iocb in self.ioMembers:\n            if not iocb.ioComplete.isSet():\n                if _debug: IOGroup._debug(\"    - waiting for child: %r\", iocb)\n                break\n        else:\n            if _debug: IOGroup._debug(\"    - all children complete\")\n            self.ioState = COMPLETED\n            self.trigger()",
    "docstring": "Callback when a child iocb completes."
  },
  {
    "code": "def get(self, sid):\n        return CallContext(self._version, account_sid=self._solution['account_sid'], sid=sid, )",
    "docstring": "Constructs a CallContext\n\n        :param sid: The unique string that identifies this resource\n\n        :returns: twilio.rest.api.v2010.account.call.CallContext\n        :rtype: twilio.rest.api.v2010.account.call.CallContext"
  },
  {
    "code": "def call(self, **data):\n        uri, body, headers = self.prepare(data)\n        return self.dispatch(uri, body, headers)",
    "docstring": "Issue the call.\n\n        :param data: Data to pass in the *body* of the request."
  },
  {
    "code": "def set_clear_color(self, color='black', alpha=None):\n        self.glir.command('FUNC', 'glClearColor', *Color(color, alpha).rgba)",
    "docstring": "Set the screen clear color\n\n        This is a wrapper for gl.glClearColor.\n\n        Parameters\n        ----------\n        color : str | tuple | instance of Color\n            Color to use. See vispy.color.Color for options.\n        alpha : float | None\n            Alpha to use."
  },
  {
    "code": "def reference(self, taskfileinfo):\n        assert self.status() is None,\\\n            \"Can only reference, if the entity is not already referenced/imported. Use replace instead.\"\n        refobj = self.create_refobject()\n        with self.set_parent_on_new(refobj):\n            self.get_refobjinter().reference(taskfileinfo, refobj)\n        self.set_refobj(refobj)\n        self.fetch_new_children()\n        self.update_restrictions()\n        self.emit_data_changed()",
    "docstring": "Reference the entity into the scene. Only possible if the current status is None.\n\n        This will create a new refobject, then call :meth:`RefobjInterface.reference` and\n        afterwards set the refobj on the :class:`Reftrack` instance.\n\n        :param taskfileinfo: the taskfileinfo to reference\n        :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo`\n        :returns: None\n        :rtype: None\n        :raises: :class:`ReftrackIntegrityError`"
  },
  {
    "code": "def socket_read(fp):\n    response = ''\n    oldlen = 0\n    newlen = 0\n    while True:\n        response += fp.read(buffSize)\n        newlen = len(response)\n        if newlen - oldlen == 0:\n            break\n        else:\n            oldlen = newlen\n    return response",
    "docstring": "Buffered read from socket. Reads all data available from socket.\n    \n    @fp:     File pointer for socket.\n    @return: String of characters read from buffer."
  },
  {
    "code": "def get_attrs(cls):\n        ignore = dir(type('dummy', (object,), {})) + ['__metaclass__']\n        attrs = [\n            item for item in inspect.getmembers(cls) if item[0] not in ignore\n            and not isinstance(\n                item[1], (\n                    types.FunctionType,\n                    types.MethodType,\n                    classmethod,\n                    staticmethod,\n                    property))]\n        attrs.sort(key=lambda attr: (getattr(attr[1], 'idx', -1), attr[0]))\n        return attrs",
    "docstring": "Get all class attributes ordered by definition"
  },
  {
    "code": "def unpack_glist(glist_ptr, cffi_type, transfer_full=True):\n    current = glist_ptr\n    while current:\n        yield ffi.cast(cffi_type, current.data)\n        if transfer_full:\n            free(current.data)\n        current = current.next\n    if transfer_full:\n        lib.g_list_free(glist_ptr)",
    "docstring": "Takes a glist ptr, copies the values casted to type_ in to a list\n    and frees all items and the list.\n\n    If an item is returned all yielded before are invalid."
  },
  {
    "code": "def rotate(self, log):\n        self.write(log, rotate=True)\n        self.write({})",
    "docstring": "Move the current log to a new file with timestamp and create a new empty log file."
  },
  {
    "code": "def dockDetailPane(self, detailPane, title=None, area=None):\n        title = detailPane.classLabel() if title is None else title\n        area = Qt.LeftDockWidgetArea if area is None else area\n        dockWidget = self.dockWidget(detailPane, title, area)\n        dockWidget.visibilityChanged.connect(detailPane.dockVisibilityChanged)\n        if len(self._detailDockWidgets) > 0:\n            self.tabifyDockWidget(self._detailDockWidgets[-1], dockWidget)\n        self._detailDockWidgets.append(dockWidget)\n        return dockWidget",
    "docstring": "Creates a dockWidget and add the detailPane with a default title.\n            By default the detail widget is added to the Qt.LeftDockWidgetArea."
  },
  {
    "code": "def _date_based_where(self, type, query, where):\n        value = str(where['value']).zfill(2)\n        value = self.parameter(value)\n        return 'strftime(\\'%s\\', %s) %s %s'\\\n               % (type, self.wrap(where['column']),\n                  where['operator'], value)",
    "docstring": "Compiled a date where based clause\n\n        :param type: The date type\n        :type type: str\n\n        :param query: A QueryBuilder instance\n        :type query: QueryBuilder\n\n        :param where: The condition\n        :type where: dict\n\n        :return: The compiled clause\n        :rtype: str"
  },
  {
    "code": "def NHot(n, *xs, simplify=True):\n    if not isinstance(n, int):\n        raise TypeError(\"expected n to be an int\")\n    if not 0 <= n <= len(xs):\n        fstr = \"expected 0 <= n <= {}, got {}\"\n        raise ValueError(fstr.format(len(xs), n))\n    xs = [Expression.box(x).node for x in xs]\n    num = len(xs)\n    terms = list()\n    for hot_idxs in itertools.combinations(range(num), n):\n        hot_idxs = set(hot_idxs)\n        _xs = [xs[i] if i in hot_idxs else exprnode.not_(xs[i])\n               for i in range(num)]\n        terms.append(exprnode.and_(*_xs))\n    y = exprnode.or_(*terms)\n    if simplify:\n        y = y.simplify()\n    return _expr(y)",
    "docstring": "Return an expression that means\n    \"exactly N input functions are true\".\n\n    If *simplify* is ``True``, return a simplified expression."
  },
  {
    "code": "def _sign_threshold_signature_fulfillment(cls, input_, message, key_pairs):\n        input_ = deepcopy(input_)\n        message = sha3_256(message.encode())\n        if input_.fulfills:\n            message.update('{}{}'.format(\n                input_.fulfills.txid, input_.fulfills.output).encode())\n        for owner_before in set(input_.owners_before):\n            ccffill = input_.fulfillment\n            subffills = ccffill.get_subcondition_from_vk(\n                base58.b58decode(owner_before))\n            if not subffills:\n                raise KeypairMismatchException('Public key {} cannot be found '\n                                               'in the fulfillment'\n                                               .format(owner_before))\n            try:\n                private_key = key_pairs[owner_before]\n            except KeyError:\n                raise KeypairMismatchException('Public key {} is not a pair '\n                                               'to any of the private keys'\n                                               .format(owner_before))\n            for subffill in subffills:\n                subffill.sign(\n                    message.digest(), base58.b58decode(private_key.encode()))\n        return input_",
    "docstring": "Signs a ThresholdSha256.\n\n            Args:\n                input_ (:class:`~bigchaindb.common.transaction.\n                    Input`) The Input to be signed.\n                message (str): The message to be signed\n                key_pairs (dict): The keys to sign the Transaction with."
  },
  {
    "code": "async def scan(self, timeout=1):\n        adapters = await self.loop.run_in_executor(None, ifaddr.get_adapters)\n        ips = [ip.ip for adapter in ifaddr.get_adapters() for ip in adapter.ips if ip.is_IPv4]\n        if not ips:\n            return []\n        tasks = []\n        discoveries = []\n        for ip in ips:\n            manager = ScanManager(ip)\n            lifx_discovery = LifxDiscovery(self.loop, manager)\n            discoveries.append(lifx_discovery)\n            lifx_discovery.start(listen_ip=ip)\n            tasks.append(self.loop.create_task(manager.lifx_ip()))\n        (done, pending) = await aio.wait(tasks, timeout=timeout)\n        for discovery in discoveries:\n            discovery.cleanup()\n        for task in pending:\n            task.cancel()\n        return [task.result() for task in done]",
    "docstring": "Return a list of local IP addresses on interfaces with LIFX bulbs."
  },
  {
    "code": "def compile(self, root, relpaths):\n    with named_temporary_file() as fp:\n      fp.write(to_bytes(_COMPILER_MAIN % {'root': root, 'relpaths': relpaths}, encoding='utf-8'))\n      fp.flush()\n      try:\n        out, _ = Executor.execute([self._interpreter.binary, '-sE', fp.name])\n      except Executor.NonZeroExit as e:\n        raise self.CompilationFailure(\n          'encountered %r during bytecode compilation.\\nstderr was:\\n%s\\n' % (e, e.stderr)\n        )\n      return out.splitlines()",
    "docstring": "Compiles the given python source files using this compiler's interpreter.\n\n    :param string root: The root path all the source files are found under.\n    :param list relpaths: The realtive paths from the `root` of the source files to compile.\n    :returns: A list of relative paths of the compiled bytecode files.\n    :raises: A :class:`Compiler.Error` if there was a problem bytecode compiling any of the files."
  },
  {
    "code": "def material_formula(self):\n        try:\n            form = self.header.formula\n        except IndexError:\n            form = 'No formula provided'\n        return \"\".join(map(str, form))",
    "docstring": "Returns chemical formula of material from feff.inp file"
  },
  {
    "code": "def new_name(self, template=u\"xxx_todo_changeme\"):\n        name = template\n        while name in self.used_names:\n            name = template + unicode(self.numbers.next())\n        self.used_names.add(name)\n        return name",
    "docstring": "Return a string suitable for use as an identifier\n\n        The new name is guaranteed not to conflict with other identifiers."
  },
  {
    "code": "def as_required_fields(self, fields=[]):\n        fields = self.filter_fields(fields)\n        for f in fields:\n            f = self.fields[f.name]\n            f.required = True",
    "docstring": "set required to True"
  },
  {
    "code": "def updaten(self, rangesets):\n        for rng in rangesets:\n            if isinstance(rng, set):\n                self.update(rng)\n            else:\n                self.update(RangeSet(rng))",
    "docstring": "Update a rangeset with the union of itself and several others."
  },
  {
    "code": "def resolve_path_from_base(path_to_resolve, base_path):\n    return os.path.abspath(\n        os.path.join(\n            base_path,\n            os.path.expanduser(path_to_resolve)))",
    "docstring": "If path-to_resolve is a relative path, create an absolute path\n    with base_path as the base.\n\n    If path_to_resolve is an absolute path or a user path (~), just\n    resolve it to an absolute path and return."
  },
  {
    "code": "def upload_timeline(self, timeline_name, plaso_storage_path):\n    resource_url = '{0:s}/upload/'.format(self.api_base_url)\n    files = {'file': open(plaso_storage_path, 'rb')}\n    data = {'name': timeline_name}\n    response = self.session.post(resource_url, files=files, data=data)\n    try:\n      response_dict = response.json()\n    except ValueError:\n      raise RuntimeError(\n          'Could not decode JSON response from Timesketch'\n          ' (Status {0:d}):\\n{1:s}'.format(\n              response.status_code, response.content))\n    index_id = response_dict['objects'][0]['id']\n    return index_id",
    "docstring": "Create a timeline with the specified name from the given plaso file.\n\n    Args:\n      timeline_name (str): Name of timeline\n      plaso_storage_path (str): Local path of plaso file to be uploaded\n\n    Returns:\n      int: ID of uploaded timeline\n\n    Raises:\n      RuntimeError: When the JSON response from Timesketch cannot be decoded."
  },
  {
    "code": "def hasBidAsk(self) -> bool:\n        return (\n            self.bid != -1 and not isNan(self.bid) and self.bidSize > 0 and\n            self.ask != -1 and not isNan(self.ask) and self.askSize > 0)",
    "docstring": "See if this ticker has a valid bid and ask."
  },
  {
    "code": "def schedule_exception_in(secs, exception, target):\n    schedule_exception_at(time.time() + secs, exception, target)",
    "docstring": "schedule a greenlet receive an exception after a number of seconds\n\n    :param secs: the number of seconds to wait before raising\n    :type secs: int or float\n    :param exception: the exception to raise in the greenlet\n    :type exception: Exception\n    :param target: the greenlet that should receive the exception\n    :type target: greenlet"
  },
  {
    "code": "def walk_level(path, level=1):\n    if level is None:\n        level = float('inf')\n    path = expand_path(path)\n    if os.path.isdir(path):\n        root_level = path.count(os.path.sep)\n        for root, dirs, files in os.walk(path):\n            yield root, dirs, files\n            if root.count(os.path.sep) >= root_level + level:\n                del dirs[:]\n    elif os.path.isfile(path):\n        yield os.path.dirname(path), [], [os.path.basename(path)]\n    else:\n        raise RuntimeError(\"Can't find a valid folder or file for path {0}\".format(repr(path)))",
    "docstring": "Like os.walk, but takes `level` kwarg that indicates how deep the recursion will go.\n\n    Notes:\n        TODO: refactor `level`->`depth`\n\n    References:\n        http://stackoverflow.com/a/234329/623735\n\n    Args:\n        path (str):  Root path to begin file tree traversal (walk)\n            level (int, optional): Depth of file tree to halt recursion at.\n            None = full recursion to as deep as it goes\n            0 = nonrecursive, just provide a list of files at the root level of the tree\n            1 = one level of depth deeper in the tree\n\n    Examples:\n        >>> root = os.path.dirname(__file__)\n        >>> all((os.path.join(base,d).count('/') == (root.count('/')+1))\n        ...     for (base, dirs, files) in walk_level(root, level=0) for d in dirs)\n        True"
  },
  {
    "code": "def generate_example(config, ext='json'):\n    template_name = 'example.{0}'.format(ext.lower())\n    template = ENV.get_template(template_name)\n    return template.render(config=config)",
    "docstring": "Generate an example file based on the given Configuration object.\n\n    Args:\n        config (confpy.core.configuration.Configuration): The configuration\n            object on which to base the example.\n        ext (str): The file extension to render. Choices: JSON and INI.\n\n    Returns:\n        str: The text of the example file."
  },
  {
    "code": "def GetAllUsers(self, pagination_size=10):\n    next_page_token, accounts = self.rpc_helper.DownloadAccount(\n        None, pagination_size)\n    while accounts:\n      for account in accounts:\n        yield GitkitUser.FromApiResponse(account)\n      next_page_token, accounts = self.rpc_helper.DownloadAccount(\n          next_page_token, pagination_size)",
    "docstring": "Gets all user info from Gitkit server.\n\n    Args:\n      pagination_size: int, how many users should be returned per request.\n          The account info are retrieved in pagination.\n\n    Yields:\n      A generator to iterate all users."
  },
  {
    "code": "def title(self, value: typing.Union[None, str]):\n        if not self._project:\n            raise RuntimeError('Failed to assign title to an unloaded project')\n        self._project.title = value",
    "docstring": "Modifies the title of the project, which is initially loaded from the\n        `cauldron.json` file."
  },
  {
    "code": "def web_hooks(self, include_global=True):\n        from fabric_bolt.web_hooks.models import Hook\n        ors = [Q(project=self)]\n        if include_global:\n            ors.append(Q(project=None))\n        hooks = Hook.objects.filter(reduce(operator.or_, ors))\n        return hooks",
    "docstring": "Get all web hooks for this project. Includes global hooks."
  },
  {
    "code": "def status(self):\n        try:\n            res = self.run(['info'])\n            if res[0]['clientName'] == '*unknown*':\n                return ConnectionStatus.INVALID_CLIENT\n            self.run(['user', '-o'])\n        except errors.CommandError as err:\n            if 'password (P4PASSWD) invalid or unset' in str(err.args[0]):\n                return ConnectionStatus.NO_AUTH\n            if 'Connect to server failed' in str(err.args[0]):\n                return ConnectionStatus.OFFLINE\n        return ConnectionStatus.OK",
    "docstring": "The status of the connection to perforce"
  },
  {
    "code": "def _get_nadir_pixel(earth_mask, sector):\n        if sector == FULL_DISC:\n            logger.debug('Computing nadir pixel')\n            rmin, rmax, cmin, cmax = bbox(earth_mask)\n            nadir_row = rmin + (rmax - rmin) // 2\n            nadir_col = cmin + (cmax - cmin) // 2\n            return nadir_row, nadir_col\n        return None, None",
    "docstring": "Find the nadir pixel\n\n        Args:\n            earth_mask: Mask identifying earth and space pixels\n            sector: Specifies the scanned sector\n        Returns:\n            nadir row, nadir column"
  },
  {
    "code": "def rollsingle(self, func, window=20, name=None, fallback=False,\n               align='right', **kwargs):\n    rname = 'roll_{0}'.format(func)\n    if fallback:\n        rfunc = getattr(lib.fallback, rname)\n    else:\n        rfunc = getattr(lib, rname, None)\n        if not rfunc:\n            rfunc = getattr(lib.fallback, rname)\n    data = np.array([list(rfunc(serie, window)) for serie in self.series()])\n    name = name or self.makename(func, window=window)\n    dates = asarray(self.dates())\n    desc = settings.desc\n    if (align == 'right' and not desc) or desc:\n        dates = dates[window-1:]\n    else:\n        dates = dates[:-window+1]\n    return self.clone(dates, data.transpose(), name=name)",
    "docstring": "Efficient rolling window calculation for min, max type functions"
  },
  {
    "code": "def _translate_timeperiod(self, timeperiod):\n        if self.time_grouping == 1:\n            return timeperiod\n        year, month, day, hour = time_helper.tokenize_timeperiod(timeperiod)\n        if self.time_qualifier == QUALIFIER_HOURLY:\n            stem = self._do_stem_grouping(timeperiod, int(hour))\n            result = '{0}{1}{2}{3:02d}'.format(year, month, day, stem)\n        elif self.time_qualifier == QUALIFIER_DAILY:\n            stem = self._do_stem_grouping(timeperiod, int(day))\n            result = '{0}{1}{2:02d}{3}'.format(year, month, stem, hour)\n        else:\n            stem = self._do_stem_grouping(timeperiod, int(month))\n            result = '{0}{1:02d}{2}{3}'.format(year, stem, day, hour)\n        return result",
    "docstring": "method translates given timeperiod to the grouped timeperiod"
  },
  {
    "code": "def monthdayscalendar(cls, year, month):\n        weeks = []\n        week = []\n        for day in NepCal.itermonthdays(year, month):\n            week.append(day)\n            if len(week) == 7:\n                weeks.append(week)\n                week = []\n        if len(week) > 0:\n            weeks.append(week)\n        return weeks",
    "docstring": "Return a list of the weeks in the month month of the year as full weeks.\n        Weeks are lists of seven day numbers."
  },
  {
    "code": "def _none_rejecter(validation_callable\n                   ):\n    def reject_none(x):\n        if x is not None:\n            return validation_callable(x)\n        else:\n            raise ValueIsNone(wrong_value=x)\n    reject_none.__name__ = 'reject_none({})'.format(get_callable_name(validation_callable))\n    return reject_none",
    "docstring": "Wraps the given validation callable to reject None values. When a None value is received by the wrapper,\n    it is not passed to the validation_callable and instead this function will raise a WrappingFailure. When any other value is\n    received the validation_callable is called as usual.\n\n    :param validation_callable:\n    :return:"
  },
  {
    "code": "def _ParseDateTimeValue(self, byte_stream, file_offset):\n    datetime_value_map = self._GetDataTypeMap('cups_ipp_datetime_value')\n    try:\n      value = self._ReadStructureFromByteStream(\n          byte_stream, file_offset, datetime_value_map)\n    except (ValueError, errors.ParseError) as exception:\n      raise errors.ParseError(\n          'Unable to parse datetime value with error: {0!s}'.format(exception))\n    direction_from_utc = chr(value.direction_from_utc)\n    rfc2579_date_time_tuple = (\n        value.year, value.month, value.day_of_month,\n        value.hours, value.minutes, value.seconds, value.deciseconds,\n        direction_from_utc, value.hours_from_utc, value.minutes_from_utc)\n    return dfdatetime_rfc2579_date_time.RFC2579DateTime(\n        rfc2579_date_time_tuple=rfc2579_date_time_tuple)",
    "docstring": "Parses a CUPS IPP RFC2579 date-time value from a byte stream.\n\n    Args:\n      byte_stream (bytes): byte stream.\n      file_offset (int): offset of the attribute data relative to the start of\n          the file-like object.\n\n    Returns:\n      dfdatetime.RFC2579DateTime: RFC2579 date-time stored in the value.\n\n    Raises:\n      ParseError: when the RFC2579 date-time value cannot be parsed."
  },
  {
    "code": "def create_roteiro(self):\n        return Roteiro(\n            self.networkapi_url,\n            self.user,\n            self.password,\n            self.user_ldap)",
    "docstring": "Get an instance of roteiro services facade."
  },
  {
    "code": "def _fix_valid_indices(cls, valid_indices, insertion_index, dim):\n        indices = np.array(sorted(valid_indices[dim]))\n        slice_index = np.sum(indices <= insertion_index)\n        indices[slice_index:] += 1\n        indices = np.insert(indices, slice_index, insertion_index + 1)\n        valid_indices[dim] = indices.tolist()\n        return valid_indices",
    "docstring": "Add indices for H&S inserted elements."
  },
  {
    "code": "def save(self):\n        while True:\n            username = sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]\n            try:\n                get_user_model().objects.get(username__iexact=username)\n            except get_user_model().DoesNotExist: break\n        self.cleaned_data['username'] = username\n        return super(SignupFormOnlyEmail, self).save()",
    "docstring": "Generate a random username before falling back to parent signup form"
  },
  {
    "code": "def replace_all_tokens(self, token):\n        b = self.data_buffer\n        for y, row in b.items():\n            for x, char in row.items():\n                b[y][x] = _CHAR_CACHE[char.char, token]",
    "docstring": "For all the characters in the screen. Set the token to the given `token`."
  },
  {
    "code": "def bulk_load_docs(es, docs):\n    chunk_size = 200\n    try:\n        results = elasticsearch.helpers.bulk(es, docs, chunk_size=chunk_size)\n        log.debug(f\"Elasticsearch documents loaded: {results[0]}\")\n        if len(results[1]) > 0:\n            log.error(\"Bulk load errors {}\".format(results))\n    except elasticsearch.ElasticsearchException as e:\n        log.error(\"Indexing error: {}\\n\".format(e))",
    "docstring": "Bulk load docs\n\n    Args:\n        es: elasticsearch handle\n        docs: Iterator of doc objects - includes index_name"
  },
  {
    "code": "def data_it(db_data, user_type):\n        data_type = {\n            'array': (list),\n            'dict': (dict),\n            'entity': (dict),\n            'list': (list),\n            'str': (string_types),\n            'string': (string_types),\n        }\n        if user_type is None:\n            if db_data is None:\n                return True\n        elif user_type.lower() in ['null', 'none']:\n            if db_data is None:\n                return True\n        elif user_type.lower() in 'binary':\n            try:\n                base64.b64decode(db_data)\n                return True\n            except Exception:\n                return False\n        elif data_type.get(user_type.lower()) is not None:\n            if isinstance(db_data, data_type.get(user_type.lower())):\n                return True\n        return False",
    "docstring": "Validate data is type.\n\n        Args:\n            db_data (dict|str|list): The data store in Redis.\n            user_data (str): The user provided data.\n\n        Returns:\n            bool: True if the data passed validation."
  },
  {
    "code": "def _setup_regex(self):\n        self.RE_COMMENTS = cache.RE_COMMENTS\n        self.RE_MODULE = cache.RE_MODULE\n        self.RE_TYPE = cache.RE_TYPE\n        self.RE_EXEC = cache.RE_EXEC\n        self.RE_MEMBERS = cache.RE_MEMBERS\n        self.RE_DEPEND = cache.RE_DEPEND",
    "docstring": "Sets up the constant regex strings etc. that can be used to\n        parse the strings for determining context."
  },
  {
    "code": "def IntersectPath(self, path, intersection):\n    node = self._root\n    for name in path.split('.'):\n      if name not in node:\n        return\n      elif not node[name]:\n        intersection.AddPath(path)\n        return\n      node = node[name]\n    intersection.AddLeafNodes(path, node)",
    "docstring": "Calculates the intersection part of a field path with this tree.\n\n    Args:\n      path: The field path to calculates.\n      intersection: The out tree to record the intersection part."
  },
  {
    "code": "def get_availability(channels, start, end,\n                     connection=None, host=None, port=None):\n    from ..segments import (Segment, SegmentList, SegmentListDict)\n    connection.set_epoch(start, end)\n    names = list(map(\n        _get_nds2_name, find_channels(channels, epoch=(start, end),\n                                      connection=connection, unique=True),\n    ))\n    result = connection.get_availability(names)\n    out = SegmentListDict()\n    for name, result in zip(channels, result):\n        out[name] = SegmentList([Segment(s.gps_start, s.gps_stop) for s in\n                                 result.simple_list()])\n    return out",
    "docstring": "Query an NDS2 server for data availability\n\n    Parameters\n    ----------\n    channels : `list` of `str`\n        list of channel names to query; this list is mapped to NDS channel\n        names using :func:`find_channels`.\n\n    start : `int`\n        GPS start time of query\n\n    end : `int`\n        GPS end time of query\n\n    connection : `nds2.connection`, optional\n        open NDS2 connection to use for query\n\n    host : `str`, optional\n        name of NDS2 server to query, required if ``connection`` is not\n        given\n\n    port : `int`, optional\n        port number on host to use for NDS2 connection\n\n    Returns\n    -------\n    segdict : `~gwpy.segments.SegmentListDict`\n        dict of ``(name, SegmentList)`` pairs\n\n    Raises\n    ------\n    ValueError\n        if the given channel name cannot be mapped uniquely to a name\n        in the NDS server database.\n\n    See also\n    --------\n    nds2.connection.get_availability\n        for documentation on the underlying query method"
  },
  {
    "code": "def _post_action(self, action):\n        reward = self.reward(action)\n        self.done = (self.timestep >= self.horizon) and not self.ignore_done\n        return reward, self.done, {}",
    "docstring": "Do any housekeeping after taking an action."
  },
  {
    "code": "def virtualbox_host():\n    if query_yes_no(question='Uninstall virtualbox-dkms?', default='yes'):\n        run('sudo apt-get remove virtualbox-dkms')\n    install_packages([\n        'virtualbox',\n        'virtualbox-qt',\n        'virtualbox-dkms',\n        'virtualbox-guest-dkms',\n        'virtualbox-guest-additions-iso',\n    ])\n    users = [env.user]\n    for username in users:\n        run(flo('sudo  adduser {username} vboxusers'))",
    "docstring": "Install a VirtualBox host system.\n\n    More Infos:\n     * overview:     https://wiki.ubuntuusers.de/VirtualBox/\n     * installation: https://wiki.ubuntuusers.de/VirtualBox/Installation/"
  },
  {
    "code": "def newsnr_threshold(self, threshold):\n        if not self.opt.chisq_bins:\n            raise RuntimeError('Chi-square test must be enabled in order to '\n                               'use newsnr threshold')\n        remove = [i for i, e in enumerate(self.events) if\n                  ranking.newsnr(abs(e['snr']), e['chisq'] / e['chisq_dof'])\n                  < threshold]\n        self.events = numpy.delete(self.events, remove)",
    "docstring": "Remove events with newsnr smaller than given threshold"
  },
  {
    "code": "def remove_prefix(text, prefix):\n\tnull, prefix, rest = text.rpartition(prefix)\n\treturn rest",
    "docstring": "Remove the prefix from the text if it exists.\n\n\t>>> remove_prefix('underwhelming performance', 'underwhelming ')\n\t'performance'\n\n\t>>> remove_prefix('something special', 'sample')\n\t'something special'"
  },
  {
    "code": "def get_volumes_for_instance(self, arg, device=None):\n        instance = self.get(arg)\n        filters = {'attachment.instance-id': instance.id}\n        if device is not None:\n            filters['attachment.device'] = device\n        return self.get_all_volumes(filters=filters)",
    "docstring": "Return all EC2 Volume objects attached to ``arg`` instance name or ID.\n\n        May specify ``device`` to limit to the (single) volume attached as that\n        device."
  },
  {
    "code": "def _get_indent(self, node):\n        lineno = node.lineno\n        if lineno > len(self._lines):\n            return -1\n        wsindent = self._wsregexp.match(self._lines[lineno - 1])\n        return len(wsindent.group(1))",
    "docstring": "Get node indentation level."
  },
  {
    "code": "def value_net(rng_key,\n              batch_observations_shape,\n              num_actions,\n              bottom_layers=None):\n  del num_actions\n  if bottom_layers is None:\n    bottom_layers = []\n  bottom_layers.extend([\n      layers.Dense(1),\n  ])\n  net = layers.Serial(*bottom_layers)\n  return net.initialize(batch_observations_shape, rng_key), net",
    "docstring": "A value net function."
  },
  {
    "code": "def get_service_account_token(request, service_account='default'):\n    token_json = get(\n        request,\n        'instance/service-accounts/{0}/token'.format(service_account))\n    token_expiry = _helpers.utcnow() + datetime.timedelta(\n        seconds=token_json['expires_in'])\n    return token_json['access_token'], token_expiry",
    "docstring": "Get the OAuth 2.0 access token for a service account.\n\n    Args:\n        request (google.auth.transport.Request): A callable used to make\n            HTTP requests.\n        service_account (str): The string 'default' or a service account email\n            address. The determines which service account for which to acquire\n            an access token.\n\n    Returns:\n        Union[str, datetime]: The access token and its expiration.\n\n    Raises:\n        google.auth.exceptions.TransportError: if an error occurred while\n            retrieving metadata."
  },
  {
    "code": "def text(self):\n        parts = [(\"%s\" if isinstance(p, Insert) else p) for p in self.parts]\n        parts = [(\"%%\" if p == \"%\" else p) for p in parts]\n        return \"\".join(parts)",
    "docstring": "The text displayed on the block.\n\n        String containing ``\"%s\"`` in place of inserts.\n\n        eg. ``'say %s for %s secs'``"
  },
  {
    "code": "def user_disable_throw_rest_endpoint(self, username, url='rest/scriptrunner/latest/custom/disableUser',\n                                         param='userName'):\n        url = \"{}?{}={}\".format(url, param, username)\n        return self.get(path=url)",
    "docstring": "The disable method throw own rest enpoint"
  },
  {
    "code": "def validate(user_input, ret_errs=False, print_errs=False):\n    errs = run_validator(user_input)\n    passed = len(errs) == 0\n    if print_errs:\n        for err in errs:\n            print(err)\n    if ret_errs:\n        return passed, errs\n    return passed",
    "docstring": "Wrapper for run_validator function that returns True if the user_input\n    contains a valid STIX pattern or False otherwise. The error messages may\n    also be returned or printed based upon the ret_errs and print_errs arg\n    values."
  },
  {
    "code": "def from_json_and_lambdas(cls, file: str, lambdas):\n        with open(file, \"r\") as f:\n            data = json.load(f)\n        return cls.from_dict(data, lambdas)",
    "docstring": "Builds a GrFN from a JSON object.\n\n        Args:\n            cls: The class variable for object creation.\n            file: Filename of a GrFN JSON file.\n\n        Returns:\n            type: A GroundedFunctionNetwork object."
  },
  {
    "code": "def _fetchAzureAccountKey(accountName):\n    try:\n        return os.environ['AZURE_ACCOUNT_KEY_' + accountName]\n    except KeyError:\n        try:\n            return os.environ['AZURE_ACCOUNT_KEY']\n        except KeyError:\n            configParser = RawConfigParser()\n            configParser.read(os.path.expanduser(credential_file_path))\n            try:\n                return configParser.get('AzureStorageCredentials', accountName)\n            except NoOptionError:\n                raise RuntimeError(\"No account key found for '%s', please provide it in '%s'\" %\n                                   (accountName, credential_file_path))",
    "docstring": "Find the account key for a given Azure storage account.\n\n    The account key is taken from the AZURE_ACCOUNT_KEY_<account> environment variable if it\n    exists, then from plain AZURE_ACCOUNT_KEY, and then from looking in the file\n    ~/.toilAzureCredentials. That file has format:\n\n    [AzureStorageCredentials]\n    accountName1=ACCOUNTKEY1==\n    accountName2=ACCOUNTKEY2=="
  },
  {
    "code": "def Failed(self):\n    interval = self._current_interval_sec\n    self._current_interval_sec = min(\n        self.max_interval_sec, self._current_interval_sec * self.multiplier)\n    return interval",
    "docstring": "Indicates that a request has failed.\n\n    Returns:\n      Time interval to wait before retrying (in seconds)."
  },
  {
    "code": "def populate_times(self):\n        stop_time = self.meta_data.get(\"stop_time\")\n        if stop_time:\n            stop_naive = datetime.utcfromtimestamp(stop_time)\n            self.stop_time = stop_naive.replace(tzinfo=tzutc())\n        creation_time = self.meta_data.get(\"creation_time\")\n        if creation_time:\n            creation_naive = datetime.utcfromtimestamp(creation_time)\n            self.creation_time = creation_naive.replace(tzinfo=tzutc())\n        start_time = self.meta_data.get(\"start_time\")\n        if start_time:\n            start_naive = datetime.utcfromtimestamp(start_time)\n            self.start_time = start_naive.replace(tzinfo=tzutc())",
    "docstring": "Populates all different meta data times that comes with measurement if\n        they are present."
  },
  {
    "code": "def get_thread(self, thread_id, update_if_cached=True, raise_404=False):\n        cached_thread = self._thread_cache.get(thread_id)\n        if cached_thread:\n            if update_if_cached:\n                cached_thread.update()\n            return cached_thread\n        res = self._requests_session.get(\n            self._url.thread_api_url(\n                thread_id = thread_id\n                )\n        )\n        if raise_404:\n            res.raise_for_status()\n        elif not res.ok:\n            return None\n        thread = Thread._from_request(self, res, thread_id)\n        self._thread_cache[thread_id] = thread\n        return thread",
    "docstring": "Get a thread from 4chan via 4chan API.\n\n        Args:\n            thread_id (int): Thread ID\n            update_if_cached (bool): Whether the thread should be updated if it's already in our cache\n            raise_404 (bool): Raise an Exception if thread has 404'd\n\n        Returns:\n            :class:`basc_py4chan.Thread`: Thread object"
  },
  {
    "code": "def throw(self, type, value=None, traceback=None):\n        return self.__wrapped__.throw(type, value, traceback)",
    "docstring": "Raise an exception in this element"
  },
  {
    "code": "def _resolve_value(self, name):\n        name = str(name)\n        if name in self._metadata._meta.elements:\n            element = self._metadata._meta.elements[name]\n            if element.editable:\n                value = getattr(self, name)\n                if value:\n                    return value\n            populate_from = element.populate_from\n            if isinstance(populate_from, collections.Callable):\n                return populate_from(self, **self._populate_from_kwargs())\n            elif isinstance(populate_from, Literal):\n                return populate_from.value\n            elif populate_from is not NotSet:\n                return self._resolve_value(populate_from)\n        try:\n            value = getattr(self._metadata, name)\n        except AttributeError:\n            pass\n        else:\n            if isinstance(value, collections.Callable):\n                if getattr(value, '__self__', None):\n                    return value(self)\n                else:\n                    return value(self._metadata, obj=self)\n            return value",
    "docstring": "Returns an appropriate value for the given name."
  },
  {
    "code": "def print(self, output_file=sys.stdout, log=False):\n        for soln in iter(self):\n            print(soln, file=output_file)\n            print(SOLN_SEP, file=output_file)\n        if self.status == 0:\n            print(SEARCH_COMPLETE, file=output_file)\n        if (self.status == 1 and self._n_solns == 0) or self.status >= 2:\n            print({\n                Status.INCOMPLETE : ERROR,\n                Status.UNKNOWN: UNKNOWN,\n                Status.UNSATISFIABLE: UNSATISFIABLE,\n                Status.UNBOUNDED: UNBOUNDED,\n                Status.UNSATorUNBOUNDED: UNSATorUNBOUNDED,\n                Status.ERROR: ERROR\n            }[self.status], file=output_file)\n            if self.stderr:\n                print(self.stderr.strip(), file=sys.stderr)\n        elif log:\n            print(str(self.log), file=output_file)",
    "docstring": "Print the solution stream"
  },
  {
    "code": "def print_error(msg, color=True):\n    if color and is_posix():\n        safe_print(u\"%s[ERRO] %s%s\" % (ANSI_ERROR, msg, ANSI_END))\n    else:\n        safe_print(u\"[ERRO] %s\" % (msg))",
    "docstring": "Print an error message.\n\n    :param string msg: the message\n    :param bool color: if ``True``, print with POSIX color"
  },
  {
    "code": "def Printer(open_file=sys.stdout, closing=False):\n    try:\n        while True:\n            logstr = (yield)\n            open_file.write(logstr)\n            open_file.write('\\n')\n    except GeneratorExit:\n        if closing:\n            try: open_file.close()\n            except: pass",
    "docstring": "Prints items with a timestamp."
  },
  {
    "code": "def encrypt(self,plaintext,n=''):\n        self.ed = 'e'\n        if self.mode == MODE_XTS:\n            return self.chain.update(plaintext,'e',n)\n        else:\n            return self.chain.update(plaintext,'e')",
    "docstring": "Encrypt some plaintext\n\n            plaintext   = a string of binary data\n            n           = the 'tweak' value when the chaining mode is XTS\n\n        The encrypt function will encrypt the supplied plaintext.\n        The behavior varies slightly depending on the chaining mode.\n\n        ECB, CBC:\n        ---------\n        When the supplied plaintext is not a multiple of the blocksize\n          of the cipher, then the remaining plaintext will be cached.\n        The next time the encrypt function is called with some plaintext,\n          the new plaintext will be concatenated to the cache and then\n          cache+plaintext will be encrypted.\n\n        CFB, OFB, CTR:\n        --------------\n        When the chaining mode allows the cipher to act as a stream cipher,\n          the encrypt function will always encrypt all of the supplied\n          plaintext immediately. No cache will be kept.\n\n        XTS:\n        ----\n        Because the handling of the last two blocks is linked,\n          it needs the whole block of plaintext to be supplied at once.\n        Every encrypt function called on a XTS cipher will output\n          an encrypted block based on the current supplied plaintext block.\n\n        CMAC:\n        -----\n        Everytime the function is called, the hash from the input data is calculated.\n        No finalizing needed.\n        The hashlength is equal to block size of the used block cipher."
  },
  {
    "code": "def get_peers_public_keys(self):\n        with self._lock:\n            return [key for key\n                    in (self._network.connection_id_to_public_key(peer)\n                        for peer\n                        in copy.copy(self._peers))\n                    if key is not None]",
    "docstring": "Returns the list of public keys for all peers."
  },
  {
    "code": "def allow_inbound_connection(self):\n        LOGGER.debug(\"Determining whether inbound connection should \"\n                     \"be allowed. num connections: %s max %s\",\n                     len(self._connections),\n                     self._max_incoming_connections)\n        return self._max_incoming_connections >= len(self._connections)",
    "docstring": "Determines if an additional incoming network connection\n        should be permitted.\n\n        Returns:\n            bool"
  },
  {
    "code": "def clear(self):\n        super(NGram, self).clear()\n        self._grams = {}\n        self.length = {}",
    "docstring": "Remove all elements from this set.\n\n        >>> from ngram import NGram\n        >>> n = NGram(['spam', 'eggs'])\n        >>> sorted(list(n))\n        ['eggs', 'spam']\n        >>> n.clear()\n        >>> list(n)\n        []"
  },
  {
    "code": "def _get_msiexec(use_msiexec):\n    if use_msiexec is False:\n        return False, ''\n    if isinstance(use_msiexec, six.string_types):\n        if os.path.isfile(use_msiexec):\n            return True, use_msiexec\n        else:\n            log.warning(\n                \"msiexec path '%s' not found. Using system registered \"\n                \"msiexec instead\", use_msiexec\n            )\n            use_msiexec = True\n    if use_msiexec is True:\n        return True, 'msiexec'",
    "docstring": "Return if msiexec.exe will be used and the command to invoke it."
  },
  {
    "code": "def _assert_category(self, category):\n        category = category.lower()\n        valid_categories = ['cable', 'broadcast', 'final', 'tv']\n        assert_msg = \"%s is not a valid category.\" % (category)\n        assert (category in valid_categories), assert_msg",
    "docstring": "Validate category argument"
  },
  {
    "code": "def download_preview(self, image, url_field='url'):\n        return self.download(image, url_field=url_field, suffix='preview')",
    "docstring": "Downlaod the binary data of an image attachment at preview size.\n\n        :param str url_field: the field of the image with the right URL\n        :return: binary image data\n        :rtype: bytes"
  },
  {
    "code": "def measures(self):\n        from ambry.valuetype.core import ROLE\n        return [c for c in self.columns if c.role == ROLE.MEASURE]",
    "docstring": "Iterate over all measures"
  },
  {
    "code": "def connect(provider_id):\n    provider = get_provider_or_404(provider_id)\n    callback_url = get_authorize_callback('connect', provider_id)\n    allow_view = get_url(config_value('CONNECT_ALLOW_VIEW'))\n    pc = request.form.get('next', allow_view)\n    session[config_value('POST_OAUTH_CONNECT_SESSION_KEY')] = pc\n    return provider.authorize(callback_url)",
    "docstring": "Starts the provider connection OAuth flow"
  },
  {
    "code": "def fit_to_structure(self, structure, symprec=0.1):\n        sga = SpacegroupAnalyzer(structure, symprec)\n        symm_ops = sga.get_symmetry_operations(cartesian=True)\n        return sum([self.transform(symm_op)\n                    for symm_op in symm_ops]) / len(symm_ops)",
    "docstring": "Returns a tensor that is invariant with respect to symmetry\n        operations corresponding to a structure\n\n        Args:\n            structure (Structure): structure from which to generate\n                symmetry operations\n            symprec (float): symmetry tolerance for the Spacegroup Analyzer\n                used to generate the symmetry operations"
  },
  {
    "code": "def get(self, key, default=None, index=-1, type=None):\n        try:\n            val = self.dict[key][index]\n            return type(val) if type else val\n        except Exception, e:\n            pass\n        return default",
    "docstring": "Return the most recent value for a key.\n\n            :param default: The default value to be returned if the key is not\n                   present or the type conversion fails.\n            :param index: An index for the list of available values.\n            :param type: If defined, this callable is used to cast the value\n                    into a specific type. Exception are suppressed and result in\n                    the default value to be returned."
  },
  {
    "code": "def populate_obj(self, obj=None, form=None):\n        if not form:\n            form = current_context.data.form\n        if obj is None:\n            obj = AttrDict()\n        form.populate_obj(obj)\n        return obj",
    "docstring": "Populates an object with the form's data"
  },
  {
    "code": "def step_interpolation(x, xp, fp, **kwargs):\n  del kwargs\n  xp = np.expand_dims(xp, -1)\n  lower, upper = xp[:-1], xp[1:]\n  conditions = (x >= lower) & (x < upper)\n  conditions = np.concatenate([[x < xp[0]], conditions, [x >= xp[-1]]])\n  values = np.concatenate([[fp[0]], fp])\n  assert np.all(np.sum(conditions, 0) == 1), 'xp must be increasing.'\n  indices = np.argmax(conditions, 0)\n  return values[indices].astype(np.float32)",
    "docstring": "Multi-dimensional step interpolation.\n\n  Returns the multi-dimensional step interpolant to a function with\n  given discrete data points (xp, fp), evaluated at x.\n\n  Note that *N and *M indicate zero or more dimensions.\n\n  Args:\n    x: An array of shape [*N], the x-coordinates of the interpolated values.\n    xp: An np.array of shape [D], the x-coordinates of the data points, must be\n      increasing.\n    fp: An np.array of shape [D, *M], the y-coordinates of the data points.\n    **kwargs: Unused.\n\n  Returns:\n    An array of shape [*N, *M], the interpolated values."
  },
  {
    "code": "def create_thumbnail(self, image, geometry,\n                         upscale=True, crop=None, colorspace='RGB'):\n        image = self.colorspace(image, colorspace)\n        image = self.scale(image, geometry, upscale, crop)\n        image = self.crop(image, geometry, crop)\n        return image",
    "docstring": "This serves as a really basic example of a thumbnailing method. You\n        may want to implement your own logic, but this will work for\n        simple cases.\n\n        :param Image image: This is your engine's ``Image`` object. For\n            PIL it's PIL.Image.\n        :param tuple geometry: Geometry of the image in the format of (x,y).\n        :keyword str crop: A cropping offset string. This is either one or two\n            space-separated values. If only one value is specified, the cropping\n            amount (pixels or percentage) for both X and Y dimensions is the\n            amount given. If two values are specified, X and Y dimension cropping\n            may be set independently. Some examples: '50% 50%', '50px 20px',\n            '50%', '50px'.\n        :keyword str colorspace: The colorspace to set/convert the image to.\n            This is typically 'RGB' or 'GRAY'.\n        :returns: The thumbnailed image. The returned type depends on your\n            choice of Engine."
  },
  {
    "code": "def selectAll( self ):\n        currLayer = self._currentLayer\n        for item in self.items():\n            layer = item.layer()\n            if ( layer == currLayer or not layer ):\n                item.setSelected(True)",
    "docstring": "Selects all the items in the scene."
  },
  {
    "code": "def FillDeviceCapabilities(device, descriptor):\n  preparsed_data = PHIDP_PREPARSED_DATA(0)\n  ret = hid.HidD_GetPreparsedData(device, ctypes.byref(preparsed_data))\n  if not ret:\n    raise ctypes.WinError()\n  try:\n    caps = HidCapabilities()\n    ret = hid.HidP_GetCaps(preparsed_data, ctypes.byref(caps))\n    if ret != HIDP_STATUS_SUCCESS:\n      raise ctypes.WinError()\n    descriptor.usage = caps.Usage\n    descriptor.usage_page = caps.UsagePage\n    descriptor.internal_max_in_report_len = caps.InputReportByteLength\n    descriptor.internal_max_out_report_len = caps.OutputReportByteLength\n  finally:\n    hid.HidD_FreePreparsedData(preparsed_data)",
    "docstring": "Fill out device capabilities.\n\n  Fills the HidCapabilitites of the device into descriptor.\n\n  Args:\n    device: A handle to the open device\n    descriptor: DeviceDescriptor to populate with the\n      capabilities\n\n  Returns:\n    none\n\n  Raises:\n    WindowsError when unable to obtain capabilitites."
  },
  {
    "code": "def what(self):\n        originalFromDt = dt.datetime.combine(self.except_date,\n                                             timeFrom(self.overrides.time_from))\n        changedFromDt = dt.datetime.combine(self.date, timeFrom(self.time_from))\n        originalDaysDelta = dt.timedelta(days=self.overrides.num_days - 1)\n        originalToDt = getAwareDatetime(self.except_date + originalDaysDelta,\n                                        self.overrides.time_to, self.tz)\n        changedDaysDelta = dt.timedelta(days=self.num_days - 1)\n        changedToDt = getAwareDatetime(self.except_date + changedDaysDelta,\n                                        self.time_to, self.tz)\n        if originalFromDt < changedFromDt:\n            return _(\"Postponed\")\n        elif originalFromDt > changedFromDt or originalToDt != changedToDt:\n            return _(\"Rescheduled\")\n        else:\n            return None",
    "docstring": "May return a 'postponed' or 'rescheduled' string depending what\n        the start and finish time of the event has been changed to."
  },
  {
    "code": "def _filter_child_model_fields(cls, fields):\n        indexes_to_remove = set([])\n        for index1, field1 in enumerate(fields):\n            for index2, field2 in enumerate(fields):\n                if index1 < index2 and index1 not in indexes_to_remove and\\\n                        index2 not in indexes_to_remove:\n                    if issubclass(field1.related_model, field2.related_model):\n                        indexes_to_remove.add(index1)\n                    if issubclass(field2.related_model, field1.related_model):\n                        indexes_to_remove.add(index2)\n        fields = [field for index, field in enumerate(fields)\n                  if index not in indexes_to_remove]\n        return fields",
    "docstring": "Keep only related model fields.\n\n        Example: Inherited models: A -> B -> C\n        B has one-to-many relationship to BMany.\n        after inspection BMany would have links to B and C. Keep only B. Parent\n        model A could not be used (It would not be in fields)\n\n        :param list fields: model fields.\n        :return list fields: filtered fields."
  },
  {
    "code": "def dbmin05years(self, value=None):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type float '\n                                 'for field `dbmin05years`'.format(value))\n        self._dbmin05years = value",
    "docstring": "Corresponds to IDD Field `dbmin05years`\n        5-year return period values for minimum extreme dry-bulb temperature\n\n        Args:\n            value (float): value for IDD Field `dbmin05years`\n                Unit: C\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def get_downstream_causal_subgraph(graph, nbunch: Union[BaseEntity, Iterable[BaseEntity]]):\n    return get_subgraph_by_edge_filter(graph, build_downstream_edge_predicate(nbunch))",
    "docstring": "Induce a sub-graph from all of the downstream causal entities of the nodes in the nbunch.\n\n    :type graph: pybel.BELGraph\n    :rtype: pybel.BELGraph"
  },
  {
    "code": "async def show_help(self):\n        e = discord.Embed()\n        messages = ['Welcome to the interactive paginator!\\n']\n        messages.append('This interactively allows you to see pages of text by navigating with ' \\\n                        'reactions. They are as follows:\\n')\n        for (emoji, func) in self.reaction_emojis:\n            messages.append('%s %s' % (emoji, func.__doc__))\n        e.description = '\\n'.join(messages)\n        e.colour =  0x738bd7\n        e.set_footer(text='We were on page %s before this message.' % self.current_page)\n        await self.bot.edit_message(self.message, embed=e)\n        async def go_back_to_current_page():\n            await asyncio.sleep(60.0)\n            await self.show_current_page()\n        self.bot.loop.create_task(go_back_to_current_page())",
    "docstring": "shows this message"
  },
  {
    "code": "def languages(self):\n        language = PageView.headers['Accept-Language']\n        first_language = fn.SubStr(\n            language,\n            1,\n            fn.StrPos(language, ';'))\n        return (self.get_query()\n                .select(first_language, fn.Count(PageView.id))\n                .group_by(first_language)\n                .order_by(fn.Count(PageView.id).desc())\n                .tuples())",
    "docstring": "Retrieve languages, sorted by most common to least common. The\n        Accept-Languages header sometimes looks weird, i.e.\n        \"en-US,en;q=0.8,is;q=0.6,da;q=0.4\" We will split on the first semi-\n        colon."
  },
  {
    "code": "def graphql_impl(\n    schema,\n    source,\n    root_value,\n    context_value,\n    variable_values,\n    operation_name,\n    field_resolver,\n    type_resolver,\n    middleware,\n    execution_context_class,\n) -> AwaitableOrValue[ExecutionResult]:\n    schema_validation_errors = validate_schema(schema)\n    if schema_validation_errors:\n        return ExecutionResult(data=None, errors=schema_validation_errors)\n    try:\n        document = parse(source)\n    except GraphQLError as error:\n        return ExecutionResult(data=None, errors=[error])\n    except Exception as error:\n        error = GraphQLError(str(error), original_error=error)\n        return ExecutionResult(data=None, errors=[error])\n    from .validation import validate\n    validation_errors = validate(schema, document)\n    if validation_errors:\n        return ExecutionResult(data=None, errors=validation_errors)\n    return execute(\n        schema,\n        document,\n        root_value,\n        context_value,\n        variable_values,\n        operation_name,\n        field_resolver,\n        type_resolver,\n        middleware,\n        execution_context_class,\n    )",
    "docstring": "Execute a query, return asynchronously only if necessary."
  },
  {
    "code": "def new(cls, mode, size, color=0, depth=8, **kwargs):\n        header = cls._make_header(mode, size, depth)\n        image_data = ImageData.new(header, color=color, **kwargs)\n        return cls(PSD(\n            header=header,\n            image_data=image_data,\n            image_resources=ImageResources.new(),\n        ))",
    "docstring": "Create a new PSD document.\n\n        :param mode: The color mode to use for the new image.\n        :param size: A tuple containing (width, height) in pixels.\n        :param color: What color to use for the image. Default is black.\n        :return: A :py:class:`~psd_tools.api.psd_image.PSDImage` object."
  },
  {
    "code": "def get_token(self, request):\n        return stripe.Token.create(\n            card={\n                \"number\": request.data[\"number\"],\n                \"exp_month\": request.data[\"exp_month\"],\n                \"exp_year\": request.data[\"exp_year\"],\n                \"cvc\": request.data[\"cvc\"]\n            }\n        )",
    "docstring": "Create a stripe token for a card"
  },
  {
    "code": "def delete(self, **kwargs):\n        if self.is_valid:\n            if '_id' in self._document:\n                to_delete = self.find_one({'_id': self._id})\n                if to_delete:\n                    before = self.before_delete()\n                    if before:\n                        return before\n                    try:\n                        self.delete_one({'_id': self._id})\n                        self.after_delete()\n                        return self._document\n                    except PyMongoException as exc:\n                        return PyMongoError(\n                            error_message=exc.details.get(\n                                'errmsg', exc.details.get(\n                                    'err', 'PyMongoError.'\n                                )\n                            ),\n                            operation='delete', collection=type(self).__name__,\n                            document=self._document,\n                        )\n                else:\n                    return DocumentNotFoundError(type(self).__name__, self._id)\n            else:\n                return UnidentifiedDocumentError(\n                    type(self).__name__, self._document\n                )",
    "docstring": "Deletes the document if it is saved in the collection."
  },
  {
    "code": "def extract_lrzip (archive, compression, cmd, verbosity, interactive, outdir):\n    cmdlist = [cmd, '-d']\n    if verbosity > 1:\n        cmdlist.append('-v')\n    outfile = util.get_single_outfile(outdir, archive)\n    cmdlist.extend([\"-o\", outfile, os.path.abspath(archive)])\n    return cmdlist",
    "docstring": "Extract a LRZIP archive."
  },
  {
    "code": "def cmd_logcat(self, *args):\n        self.check_requirements()\n        serial = self.serials[0:]\n        if not serial:\n            return\n        filters = self.buildozer.config.getrawdefault(\n            \"app\", \"android.logcat_filters\", \"\", section_sep=\":\", split_char=\" \")\n        filters = \" \".join(filters)\n        self.buildozer.environ['ANDROID_SERIAL'] = serial[0]\n        self.buildozer.cmd('{adb} logcat {filters}'.format(adb=self.adb_cmd,\n                                                           filters=filters),\n                           cwd=self.buildozer.global_platform_dir,\n                           show_output=True)\n        self.buildozer.environ.pop('ANDROID_SERIAL', None)",
    "docstring": "Show the log from the device"
  },
  {
    "code": "def do_load(self, arg):\n        from os import path\n        import json\n        fullpath = path.expanduser(arg)\n        if path.isfile(fullpath):\n            with open(fullpath) as f:\n                data = json.load(f)\n            for stagepath in data[\"tests\"]:\n                self.do_parse(stagepath)\n            self.args = data[\"args\"]",
    "docstring": "Loads a saved session variables, settings and test results to the shell."
  },
  {
    "code": "def _to_pandas(ob):\n    if isinstance(ob, (pd.Series, pd.DataFrame)):\n        return ob\n    if ob.ndim == 1:\n        return pd.Series(ob)\n    elif ob.ndim == 2:\n        return pd.DataFrame(ob)\n    else:\n        raise ValueError(\n            'cannot convert array of dim > 2 to a pandas structure',\n        )",
    "docstring": "Convert an array-like to a pandas object.\n\n    Parameters\n    ----------\n    ob : array-like\n        The object to convert.\n\n    Returns\n    -------\n    pandas_structure : pd.Series or pd.DataFrame\n        The correct structure based on the dimensionality of the data."
  },
  {
    "code": "def _url(self, uri):\n        prefix = \"{}://{}{}\".format(\n            self._protocol,\n            self.real_connection.host,\n            self._port_postfix(),\n        )\n        return uri.replace(prefix, '', 1)",
    "docstring": "Returns request selector url from absolute URI"
  },
  {
    "code": "def parse_xml(self, node):\n        self._set_properties(node)\n        self.extend(TiledObject(self.parent, child)\n                    for child in node.findall('object'))\n        return self",
    "docstring": "Parse an Object Group from ElementTree xml node\n\n        :param node: ElementTree xml node\n        :return: self"
  },
  {
    "code": "def put(self, name_to_val):\n    self._check_open()\n    for name, val in name_to_val.iteritems():\n      try:\n        self.client.PutFullMatrix(name, 'base', val, None)\n      except:\n        self.client.PutWorkspaceData(name, 'base', val)",
    "docstring": "Loads a dictionary of variable names into the matlab com client."
  },
  {
    "code": "def require_condition(cls, expr, message, *format_args, **format_kwds):\n        if not expr:\n            raise cls(message, *format_args, **format_kwds)",
    "docstring": "used to assert a certain state. If the expression renders a false\n        value, an exception will be raised with the supplied message\n\n        :param: message:     The failure message to attach to the raised Buzz\n        :param: expr:        A boolean value indicating an evaluated expression\n        :param: format_args: Format arguments. Follows str.format convention\n        :param: format_kwds: Format keyword args. Follows str.format convetion"
  },
  {
    "code": "def append_note(self, note, root, scale=0):\n        root_val = note_to_val(root)\n        note_val = note_to_val(note) - root_val + scale * 12\n        if note_val not in self.components:\n            self.components.append(note_val)\n            self.components.sort()",
    "docstring": "Append a note to quality\n\n        :param str note: note to append on quality\n        :param str root: root note of chord\n        :param int scale: key scale"
  },
  {
    "code": "def delete_all_banks(self):\n        for file in glob(str(self.data_path) + \"/*.json\"):\n            Persistence.delete(file)",
    "docstring": "Delete all banks files.\n\n        Util for manual save, because isn't possible know which banks\n        were removed"
  },
  {
    "code": "def set_led(self, led_id, color):\n        if not set_leds_color(self.corsair_sdk, LedColor(led_id, *color)):\n            self._raise_corsair_error()\n        return True",
    "docstring": "Set color of an led\n\n        :param led_id: id of led to set color\n        :type led_id: int\n        :param color: list of rgb values of new colors. eg. [255, 255, 255]\n        :type color: list\n        :returns: true if successful\n        :rtype: bool"
  },
  {
    "code": "def create_307_response(self):\n        request = get_current_request()\n        msg_mb = UserMessageMember(self.message)\n        coll = request.root['_messages']\n        coll.add(msg_mb)\n        qs = self.__get_new_query_string(request.query_string,\n                                         self.message.slug)\n        resubmit_url = \"%s?%s\" % (request.path_url, qs)\n        headers = [('Warning', '299 %s' % self.message.text),\n                   ]\n        http_exc = HttpWarningResubmit(location=resubmit_url,\n                                       detail=self.message.text,\n                                       headers=headers)\n        return request.get_response(http_exc)",
    "docstring": "Creates a 307 \"Temporary Redirect\" response including a HTTP Warning\n        header with code 299 that contains the user message received during\n        processing the request."
  },
  {
    "code": "def get_sorted_pointlist(self):\n        pointlist = self.get_pointlist()\n        for i in range(len(pointlist)):\n            pointlist[i] = sorted(pointlist[i], key=lambda p: p['time'])\n        pointlist = sorted(pointlist, key=lambda stroke: stroke[0]['time'])\n        return pointlist",
    "docstring": "Make sure that the points and strokes are in order.\n\n        Returns\n        -------\n        list\n            A list of all strokes in the recording. Each stroke is represented\n            as a list of dicts {'time': 123, 'x': 45, 'y': 67}"
  },
  {
    "code": "def get_meta_clusters(self, clusters):\n        meta_clusters = collections.defaultdict(list)\n        for cluster in clusters:\n            if not cluster.meta_cluster:\n                continue\n            meta_clusters[cluster.meta_cluster].append(cluster)\n        unconfigured_meta_clusters = [\n            name for name in meta_clusters.keys()\n            if name not in self.meta_clusters\n        ]\n        for name in unconfigured_meta_clusters:\n            logger.error(\"Meta cluster %s not configured!\")\n            del meta_clusters[name]\n        return meta_clusters",
    "docstring": "Returns a dictionary keyed off of meta cluster names, where the values\n        are lists of clusters associated with the meta cluster name.\n\n        If a meta cluster name doesn't have a port defined in the\n        `meta_cluster_ports` attribute an error is given and the meta cluster\n        is removed from the mapping."
  },
  {
    "code": "def listDatasetParents(self, dataset=\"\"):\n        if( dataset == \"\" ):\n            dbsExceptionHandler(\"dbsException-invalid-input\", \"DBSDataset/listDatasetParents. Child Dataset name is required.\")\n        conn = self.dbi.connection()\n        try:\n            result = self.datasetparentlist.execute(conn, dataset)\n            return result\n        finally:\n            if conn:\n                conn.close()",
    "docstring": "takes required dataset parameter\n        returns only parent dataset name"
  },
  {
    "code": "def get_group_headers(self, table_name, group_name):\n        df = self.dm[table_name]\n        cond = df['group'] == group_name\n        return df[cond].index",
    "docstring": "Return a list of all headers for a given group"
  },
  {
    "code": "def deep_merge(*dicts):\n    result = {}\n    for d in dicts:\n        if not isinstance(d, dict):\n            raise Exception('Can only deep_merge dicts, got {}'.format(d))\n        for k, v in d.items():\n            if isinstance(v, dict):\n                v = deep_merge(result.get(k, {}), v)\n            result[k] = v\n    return result",
    "docstring": "Recursively merge all input dicts into a single dict."
  },
  {
    "code": "def normalize(x:TensorImage, mean:FloatTensor,std:FloatTensor)->TensorImage:\n    \"Normalize `x` with `mean` and `std`.\"\n    return (x-mean[...,None,None]) / std[...,None,None]",
    "docstring": "Normalize `x` with `mean` and `std`."
  },
  {
    "code": "def dateint_to_weekday(dateint, first_day='Monday'):\n    weekday_ix = dateint_to_datetime(dateint).weekday()\n    return (weekday_ix - WEEKDAYS.index(first_day)) % 7",
    "docstring": "Returns the weekday of the given dateint.\n\n    Arguments\n    ---------\n    dateint : int\n        An integer object decipting a specific calendaric day; e.g. 20161225.\n    first_day : str, default 'Monday'\n        The first day of the week.\n\n    Returns\n    -------\n    int\n        The weekday of the given dateint, when first day of the week = 0,\n        last day of the week = 6.\n\n    Example\n    -------\n    >>> dateint_to_weekday(20170213)\n    0\n    >>> dateint_to_weekday(20170212)\n    6\n    >>> dateint_to_weekday(20170214)\n    1\n    >>> dateint_to_weekday(20170212, 'Sunday)\n    0\n    >>> dateint_to_weekday(20170214, 'Sunday')\n    2"
  },
  {
    "code": "def address_():\n    ret = {}\n    cmd = 'hciconfig'\n    out = __salt__['cmd.run'](cmd).splitlines()\n    dev = ''\n    for line in out:\n        if line.startswith('hci'):\n            comps = line.split(':')\n            dev = comps[0]\n            ret[dev] = {\n                'device': dev,\n                'path': '/sys/class/bluetooth/{0}'.format(dev),\n            }\n        if 'BD Address' in line:\n            comps = line.split()\n            ret[dev]['address'] = comps[2]\n        if 'DOWN' in line:\n            ret[dev]['power'] = 'off'\n        if 'UP RUNNING' in line:\n            ret[dev]['power'] = 'on'\n    return ret",
    "docstring": "Get the many addresses of the Bluetooth adapter\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' bluetooth.address"
  },
  {
    "code": "def sha1sum(filename):\n    sha1 = hashlib.sha1()\n    with open(filename, 'rb') as f:\n        for chunk in iter(lambda: f.read(128 * sha1.block_size), b''):\n            sha1.update(chunk)\n    return sha1.hexdigest()",
    "docstring": "Calculates sha1 hash of a file"
  },
  {
    "code": "def _pack_output(self, init_parameter):\n        output = {}\n        for i, param in enumerate(init_parameter):\n            output[self.key_order[i]] = param\n        return output",
    "docstring": "Pack the output\n\n        Parameters\n        ----------\n        init_parameter : dict\n\n        Returns\n        -------\n        output : dict"
  },
  {
    "code": "def buffer_to_audio(buffer: bytes) -> np.ndarray:\n    return np.fromstring(buffer, dtype='<i2').astype(np.float32, order='C') / 32768.0",
    "docstring": "Convert a raw mono audio byte string to numpy array of floats"
  },
  {
    "code": "def optimize(self):\n        with open(LIBRARIES_FILE, 'r') as f:\n            libs_data = json.load(f)\n        for alg, libs_names in libs_data.items():\n            libs = self.get_libs(alg)\n            if not libs:\n                continue\n            self.libs[alg] = [lib for lib in libs if [lib.module_name, lib.func_name] in libs_names]\n            self.libs[alg].sort(key=lambda lib: libs_names.index([lib.module_name, lib.func_name]))",
    "docstring": "Sort algorithm implementations by speed."
  },
  {
    "code": "def _make_futures(futmap_keys, class_check, make_result_fn):\n        futmap = {}\n        for key in futmap_keys:\n            if class_check is not None and not isinstance(key, class_check):\n                raise ValueError(\"Expected list of {}\".format(type(class_check)))\n            futmap[key] = concurrent.futures.Future()\n            if not futmap[key].set_running_or_notify_cancel():\n                raise RuntimeError(\"Future was cancelled prematurely\")\n        f = concurrent.futures.Future()\n        f.add_done_callback(lambda f: make_result_fn(f, futmap))\n        if not f.set_running_or_notify_cancel():\n            raise RuntimeError(\"Future was cancelled prematurely\")\n        return f, futmap",
    "docstring": "Create futures and a futuremap for the keys in futmap_keys,\n        and create a request-level future to be bassed to the C API."
  },
  {
    "code": "def codes_get_long_array(handle, key, size):\n    values = ffi.new('long[]', size)\n    size_p = ffi.new('size_t *', size)\n    _codes_get_long_array(handle, key.encode(ENC), values, size_p)\n    return list(values)",
    "docstring": "Get long array values from a key.\n\n    :param bytes key: the keyword whose value(s) are to be extracted\n\n    :rtype: List(int)"
  },
  {
    "code": "def create_instructor_answer(self, post, content, revision, anonymous=False):\n        try:\n            cid = post[\"id\"]\n        except KeyError:\n            cid = post\n        params = {\n            \"cid\": cid,\n            \"type\": \"i_answer\",\n            \"content\": content,\n            \"revision\": revision,\n            \"anonymous\": \"yes\" if anonymous else \"no\",\n        }\n        return self._rpc.content_instructor_answer(params)",
    "docstring": "Create an instructor's answer to a post `post`.\n\n        It seems like if the post has `<p>` tags, then it's treated as HTML,\n        but is treated as text otherwise. You'll want to provide `content`\n        accordingly.\n\n        :type  post: dict|str|int\n        :param post: Either the post dict returned by another API method, or\n            the `cid` field of that post.\n        :type  content: str\n        :param content: The content of the answer.\n        :type  revision: int\n        :param revision: The number of revisions the answer has gone through.\n            The first responder should out 0, the first editor 1, etc.\n        :type  anonymous: bool\n        :param anonymous: Whether or not to post anonymously.\n        :rtype: dict\n        :returns: Dictionary with information about the created answer."
  },
  {
    "code": "def start_tty(self, conf, interactive):\n        try:\n            api = conf.harpoon.docker_context_maker().api\n            container_id = conf.container_id\n            stdin = conf.harpoon.tty_stdin\n            stdout = conf.harpoon.tty_stdout\n            stderr = conf.harpoon.tty_stderr\n            if callable(stdin): stdin = stdin()\n            if callable(stdout): stdout = stdout()\n            if callable(stderr): stderr = stderr()\n            dockerpty.start(api, container_id, interactive=interactive, stdout=stdout, stderr=stderr, stdin=stdin)\n        except KeyboardInterrupt:\n            pass",
    "docstring": "Startup a tty"
  },
  {
    "code": "def get_sigmoid_parameters(self, filename='shlp_sigmoid_factors.csv'):\n        file = os.path.join(self.datapath, filename)\n        sigmoid = pd.read_csv(file, index_col=0)\n        sigmoid = sigmoid.query(\n            'building_class=={0} and '.format(self.building_class) +\n            'shlp_type==\"{0}\" and '.format(self.shlp_type) +\n            'wind_impact=={0}'.format(self.wind_class))\n        a = float(sigmoid['parameter_a'])\n        b = float(sigmoid['parameter_b'])\n        c = float(sigmoid['parameter_c'])\n        if self.ww_incl:\n            d = float(sigmoid['parameter_d'])\n        else:\n            d = 0\n        return a, b, c, d",
    "docstring": "Retrieve the sigmoid parameters from csv-files\n\n        Parameters\n        ----------\n        filename : string\n            name of file where sigmoid factors are stored"
  },
  {
    "code": "def bam_conversion(job, samfile, sample_type, univ_options, samtools_options):\n    work_dir = os.getcwd()\n    input_files = {\n        sample_type + '.sam': samfile}\n    input_files = get_files_from_filestore(job, input_files, work_dir,\n                                           docker=True)\n    bamfile = '/'.join([work_dir, sample_type + '.bam'])\n    parameters = ['view',\n                  '-bS',\n                  '-o', docker_path(bamfile),\n                  input_files[sample_type + '.sam']\n                  ]\n    docker_call(tool='samtools', tool_parameters=parameters, work_dir=work_dir,\n                dockerhub=univ_options['dockerhub'], tool_version=samtools_options['version'])\n    output_file = job.fileStore.writeGlobalFile(bamfile)\n    job.fileStore.deleteGlobalFile(samfile)\n    job.fileStore.logToMaster('Ran sam2bam on %s:%s successfully'\n                              % (univ_options['patient'], sample_type))\n    return output_file",
    "docstring": "Convert a sam to a bam.\n\n    :param dict samfile: The input sam file\n    :param str sample_type: Description of the sample to inject into the filename\n    :param dict univ_options: Dict of universal options used by almost all tools\n    :param dict samtools_options: Options specific to samtools\n    :return: fsID for the generated bam\n    :rtype: toil.fileStore.FileID"
  },
  {
    "code": "def _get_response(self, parse_result=True):\n        self.vw_process.expect_exact('\\r\\n', searchwindowsize=-1)\n        if parse_result:\n            output = self.vw_process.before\n            result_struct = VWResult(output, active_mode=self.active_mode)\n        else:\n            result_struct = None\n        return result_struct",
    "docstring": "If 'parse_result' is False, ignore the received output and return None."
  },
  {
    "code": "def unique_string(length=UUID_LENGTH):\n    string = str(uuid4()) * int(math.ceil(length / float(UUID_LENGTH)))\n    return string[:length] if length else string",
    "docstring": "Generate a unique string"
  },
  {
    "code": "def format_datetime(date):\n    if date.utcoffset() is None:\n        return date.isoformat() + 'Z'\n    utc_offset_sec = date.utcoffset()\n    utc_date = date - utc_offset_sec\n    utc_date_without_offset = utc_date.replace(tzinfo=None)\n    return utc_date_without_offset.isoformat() + 'Z'",
    "docstring": "Convert datetime to UTC ISO 8601"
  },
  {
    "code": "def _split_after_delimiter(self, item, indent_amt):\n        self._delete_whitespace()\n        if self.fits_on_current_line(item.size):\n            return\n        last_space = None\n        for item in reversed(self._lines):\n            if (\n                last_space and\n                (not isinstance(item, Atom) or not item.is_colon)\n            ):\n                break\n            else:\n                last_space = None\n            if isinstance(item, self._Space):\n                last_space = item\n            if isinstance(item, (self._LineBreak, self._Indent)):\n                return\n        if not last_space:\n            return\n        self.add_line_break_at(self._lines.index(last_space), indent_amt)",
    "docstring": "Split the line only after a delimiter."
  },
  {
    "code": "def authenticate(self, request):\n        jwt_value = self.get_jwt_value(request)\n        if jwt_value is None:\n            return None\n        try:\n            payload = jwt_decode_handler(jwt_value)\n        except jwt.ExpiredSignature:\n            msg = _('Signature has expired.')\n            raise exceptions.AuthenticationFailed(msg)\n        except jwt.DecodeError:\n            msg = _('Error decoding signature.')\n            raise exceptions.AuthenticationFailed(msg)\n        except jwt.InvalidTokenError:\n            raise exceptions.AuthenticationFailed()\n        user = self.authenticate_credentials(payload)\n        return (user, jwt_value)",
    "docstring": "Returns a two-tuple of `User` and token if a valid signature has been\n        supplied using JWT-based authentication.  Otherwise returns `None`."
  },
  {
    "code": "def serve_forever(args=None):\n    class Unbuffered(object):\n        def __init__(self, stream):\n            self.stream = stream\n        def write(self, data):\n            self.stream.write(data)\n            self.stream.flush()\n        def __getattr__(self, attr):\n            return getattr(self.stream, attr)\n    sys.stdout = Unbuffered(sys.stdout)\n    sys.stderr = Unbuffered(sys.stderr)\n    server = JsonServer(args=args)\n    server.serve_forever()",
    "docstring": "Creates the server and serves forever\n\n    :param args: Optional args if you decided to use your own\n        argument parser. Default is None to let the JsonServer setup its own\n        parser and parse command line arguments."
  },
  {
    "code": "def prepare_dispatches(cls, message, recipients=None):\n        return Dispatch.create(message, recipients or cls.get_subscribers())",
    "docstring": "Creates Dispatch models for a given message and return them.\n\n        :param Message message: Message model instance\n        :param list|None recipients: A list or Recipient objects\n        :return: list of created Dispatch models\n        :rtype: list"
  },
  {
    "code": "def search(self, pattern, count=None):\n        return self._scan(match=pattern, count=count)",
    "docstring": "Search the keys of the given hash using the specified pattern.\n\n        :param str pattern: Pattern used to match keys.\n        :param int count: Limit number of results returned.\n        :returns: An iterator yielding matching key/value pairs."
  },
  {
    "code": "def get_requires(self, requires_types):\n        if not isinstance(requires_types, list):\n            requires_types = list(requires_types)\n        extracted_requires = []\n        for requires_name in requires_types:\n            for requires in self.json_metadata.get(requires_name, []):\n                if 'win' in requires.get('environment', {}):\n                    continue\n                extracted_requires.extend(requires['requires'])\n        return extracted_requires",
    "docstring": "Extracts requires of given types from metadata file, filter windows\n        specific requires."
  },
  {
    "code": "def backup_restore(cls, block_id, impl, working_dir):\n        backup_dir = config.get_backups_directory(impl, working_dir)\n        backup_paths = cls.get_backup_paths(block_id, impl, working_dir)\n        for p in backup_paths:\n            assert os.path.exists(p), \"No such backup file: {}\".format(p)\n        for p in cls.get_state_paths(impl, working_dir):\n            pbase = os.path.basename(p)\n            backup_path = os.path.join(backup_dir, pbase + (\".bak.{}\".format(block_id)))\n            log.debug(\"Restoring '{}' to '{}'\".format(backup_path, p))\n            shutil.copy(backup_path, p)\n        return True",
    "docstring": "Restore from a backup, given the virutalchain implementation module and block number.\n        NOT THREAD SAFE.  DO NOT CALL WHILE INDEXING.\n        \n        Return True on success\n        Raise exception on error, i.e. if a backup file is missing"
  },
  {
    "code": "def read_stack_qwords(self, count, offset = 0):\n        stackData = self.read_stack_data(count * 8, offset)\n        return struct.unpack('<'+('Q'*count), stackData)",
    "docstring": "Reads QWORDs from the top of the stack.\n\n        @type  count: int\n        @param count: Number of QWORDs to read.\n\n        @type  offset: int\n        @param offset: Offset from the stack pointer to begin reading.\n\n        @rtype:  tuple( int... )\n        @return: Tuple of integers read from the stack.\n\n        @raise WindowsError: Could not read the requested data."
  },
  {
    "code": "def merge_odd_even_csu_configurations(conf_odd, conf_even):\n    merged_conf = deepcopy(conf_odd)\n    for i in range(EMIR_NBARS):\n        ibar = i + 1\n        if ibar % 2 == 0:\n            merged_conf._csu_bar_left[i] = conf_even._csu_bar_left[i]\n            merged_conf._csu_bar_right[i] = conf_even._csu_bar_right[i]\n            merged_conf._csu_bar_slit_center[i] = \\\n                conf_even._csu_bar_slit_center[i]\n            merged_conf._csu_bar_slit_width[i] = \\\n                conf_even._csu_bar_slit_width[i]\n    return merged_conf",
    "docstring": "Merge CSU configuration using odd- and even-numbered values.\n\n    The CSU returned CSU configuration include the odd-numbered values\n    from 'conf_odd' and the even-numbered values from 'conf_even'.\n\n    Parameters\n    ----------\n    conf_odd : CsuConfiguration instance\n        CSU configuration corresponding to odd-numbered slitlets.\n    conf_even : CsuConfiguration instance\n        CSU configuration corresponding to even-numbered slitlets.\n\n    Returns\n    -------\n    merged_conf : CsuConfiguration instance\n        CSU configuration resulting from the merging process."
  },
  {
    "code": "def handle_context_missing(self):\n        if self.context_missing == 'RUNTIME_ERROR':\n            log.error(MISSING_SEGMENT_MSG)\n            raise SegmentNotFoundException(MISSING_SEGMENT_MSG)\n        else:\n            log.error(MISSING_SEGMENT_MSG)",
    "docstring": "Called whenever there is no trace entity to access or mutate."
  },
  {
    "code": "def session_ended(self, f):\n        self._session_ended_view_func = f\n        @wraps(f)\n        def wrapper(*args, **kw):\n            self._flask_view_func(*args, **kw)\n        return f",
    "docstring": "Decorator routes Alexa SessionEndedRequest to the wrapped view function to end the skill.\n\n        @ask.session_ended\n        def session_ended():\n            return \"{}\", 200\n\n        The wrapped function is registered as the session_ended view function\n        and renders the response for requests to the end of the session.\n\n        Arguments:\n            f {function} -- session_ended view function"
  },
  {
    "code": "def delete_user(self, user_id):\n        api = self._get_api(iam.AccountAdminApi)\n        api.delete_user(user_id)\n        return",
    "docstring": "Delete user specified user.\n\n        :param str user_id: the ID of the user to delete (Required)\n        :returns: void"
  },
  {
    "code": "def camel_to_snake(s: str) -> str:\n    return CAMEL_CASE_RE.sub(r'_\\1', s).strip().lower()",
    "docstring": "Convert string from camel case to snake case."
  },
  {
    "code": "def skip_if_empty(func):\n    @partial_safe_wraps(func)\n    def inner(value, *args, **kwargs):\n        if value is EMPTY:\n            return\n        else:\n            return func(value, *args, **kwargs)\n    return inner",
    "docstring": "Decorator for validation functions which makes them pass if the value\n    passed in is the EMPTY sentinal value."
  },
  {
    "code": "def miniaturize(self):\n\t\telement = self._first('NN')\n\t\tif element:\n\t\t\tif re.search('verkleinwoord: (\\w+)', element, re.U):\n\t\t\t\treturn re.findall('verkleinwoord: (\\w+)', element, re.U)\n\t\t\telse:\n\t\t\t\treturn ['']\n\t\treturn [None]",
    "docstring": "Tries to scrape the miniaturized version from vandale.nl."
  },
  {
    "code": "def suspend_processes(self, as_group, scaling_processes=None):\n        params = {'AutoScalingGroupName': as_group}\n        if scaling_processes:\n            self.build_list_params(params, scaling_processes, 'ScalingProcesses')\n        return self.get_status('SuspendProcesses', params)",
    "docstring": "Suspends Auto Scaling processes for an Auto Scaling group.\n\n        :type as_group: string\n        :param as_group: The auto scaling group to suspend processes on.\n\n        :type scaling_processes: list\n        :param scaling_processes: Processes you want to suspend. If omitted, all\n            processes will be suspended."
  },
  {
    "code": "def iter_factories():\n    factories = (entry.load() for entry in iter_entry_points(FACTORY_ENTRYPOINT))\n    for factory in sorted(factories, key=lambda f: getattr(f, 'priority', -1000), reverse=True):\n        yield factory",
    "docstring": "Iterate through all factories identified by the factory entrypoint.\n\n    Yields:\n        function: A function that accepts a :class:`.Specification` and\n        returns a :class:`.PenaltyModel`."
  },
  {
    "code": "def get_info(domain_name):\n    opts = salt.utils.namecheap.get_opts('namecheap.domains.getinfo')\n    opts['DomainName'] = domain_name\n    response_xml = salt.utils.namecheap.get_request(opts)\n    if response_xml is None:\n        return []\n    domaingetinforesult = response_xml.getElementsByTagName(\"DomainGetInfoResult\")[0]\n    return salt.utils.namecheap.xml_to_dict(domaingetinforesult)",
    "docstring": "Returns information about the requested domain\n\n    returns a dictionary of information about the domain_name\n\n    domain_name\n        string  Domain name to get information about\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'my-minion' namecheap_domains.get_info my-domain-name"
  },
  {
    "code": "def SPI_write(self, chip_select, data):\n        'Writes data to SPI device selected by chipselect bit. '\n        dat = list(data)\n        dat.insert(0, chip_select)\n        return self.bus.write_i2c_block(self.address, dat);",
    "docstring": "Writes data to SPI device selected by chipselect bit."
  },
  {
    "code": "def add(self, cards, end=TOP):\n        if end is TOP:\n            try:\n                self.cards += cards\n            except:\n                self.cards += [cards]\n        elif end is BOTTOM:\n            try:\n                self.cards.extendleft(cards)\n            except:\n                self.cards.extendleft([cards])",
    "docstring": "Adds the given list of ``Card`` instances to the top of the stack.\n\n        :arg cards:\n            The cards to add to the ``Stack``. Can be a single ``Card``\n            instance, or a ``list`` of cards.\n        :arg str end:\n            The end of the ``Stack`` to add the cards to. Can be ``TOP`` (\"top\")\n            or ``BOTTOM`` (\"bottom\")."
  },
  {
    "code": "def _split_date(self, time):\n        if isinstance(time, str):\n            month, day, year = [int(t) for t in re.split(r'-|/', time)]\n            if year < 100:\n                year += 2000\n            time = date(year, month, day)\n        return time.strftime('%Y-%m-%dT%H:%M:%SZ')",
    "docstring": "Split apart a date string."
  },
  {
    "code": "def nanrankdata(a, axis=-1, inplace=False):\n    from scipy.stats import rankdata\n    if hasattr(a, \"dtype\") and issubdtype(a.dtype, integer):\n        raise ValueError(\"Integer type is not supported.\")\n    if isinstance(a, (tuple, list)):\n        if inplace:\n            raise ValueError(\"Can't use `inplace=True` for {}.\".format(type(a)))\n        a = asarray(a, float)\n    orig_shape = a.shape\n    if a.ndim == 1:\n        a = a.reshape(orig_shape + (1,))\n    if not inplace:\n        a = a.copy()\n    def rank1d(x):\n        idx = ~isnan(x)\n        x[idx] = rankdata(x[idx])\n        return x\n    a = a.swapaxes(1, axis)\n    a = apply_along_axis(rank1d, 0, a)\n    a = a.swapaxes(1, axis)\n    return a.reshape(orig_shape)",
    "docstring": "Rank data for arrays contaning NaN values.\n\n    Parameters\n    ----------\n    X : array_like\n        Array of values.\n    axis : int, optional\n        Axis value. Defaults to `1`.\n    inplace : bool, optional\n        Defaults to `False`.\n\n\n    Returns\n    -------\n    array_like\n        Ranked array.\n\n    Examples\n    --------\n\n    .. doctest::\n\n        >>> from numpy_sugar import nanrankdata\n        >>> from numpy import arange\n        >>>\n        >>> X = arange(15).reshape((5, 3)).astype(float)\n        >>> print(nanrankdata(X))\n        [[1. 1. 1.]\n         [2. 2. 2.]\n         [3. 3. 3.]\n         [4. 4. 4.]\n         [5. 5. 5.]]"
  },
  {
    "code": "def move_parent_up(self):\n        cursor = self.nav.absolute_index\n        if cursor > 0:\n            level = max(self.content.get(cursor)['level'], 1)\n            while self.content.get(cursor - 1)['level'] >= level:\n                self._move_cursor(-1)\n                cursor -= 1\n            self._move_cursor(-1)\n        else:\n            self.term.flash()\n        self.clear_input_queue()",
    "docstring": "Move the cursor up to the comment's parent. If the comment is\n        top-level, jump to the previous top-level comment."
  },
  {
    "code": "def _FetchServerCertificate(self):\n    if self.server_certificate:\n      return True\n    response = self.http_manager.OpenServerEndpoint(\n        \"server.pem\", verify_cb=self.VerifyServerPEM)\n    if response.Success():\n      self.server_certificate = response.data\n      return True\n    self.timer.SlowPoll()\n    return False",
    "docstring": "Attempts to fetch the server cert.\n\n    Returns:\n      True if we succeed."
  },
  {
    "code": "def _get_sorted_inputs(filename):\n  with tf.gfile.Open(filename) as f:\n    records = f.read().split(\"\\n\")\n    inputs = [record.strip() for record in records]\n    if not inputs[-1]:\n      inputs.pop()\n  input_lens = [(i, len(line.split())) for i, line in enumerate(inputs)]\n  sorted_input_lens = sorted(input_lens, key=lambda x: x[1], reverse=True)\n  sorted_inputs = []\n  sorted_keys = {}\n  for i, (index, _) in enumerate(sorted_input_lens):\n    sorted_inputs.append(inputs[index])\n    sorted_keys[index] = i\n  return sorted_inputs, sorted_keys",
    "docstring": "Read and sort lines from the file sorted by decreasing length.\n\n  Args:\n    filename: String name of file to read inputs from.\n  Returns:\n    Sorted list of inputs, and dictionary mapping original index->sorted index\n    of each element."
  },
  {
    "code": "def callback(func):\n    @functools.wraps(func)\n    def wrapped(*args, **kwargs):\n        result = func(*args, **kwargs)\n        if inspect.iscoroutine(result):\n            aio_loop.create_task(result)\n    return wrapped",
    "docstring": "This decorator turns `func` into a callback for Tkinter\n    to be able to use, even if `func` is an awaitable coroutine."
  },
  {
    "code": "def vrelg(v1, v2, ndim):\n    v1 = stypes.toDoubleVector(v1)\n    v2 = stypes.toDoubleVector(v2)\n    ndim = ctypes.c_int(ndim)\n    return libspice.vrelg_c(v1, v2, ndim)",
    "docstring": "Return the relative difference between two vectors of general dimension.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vrelg_c.html\n\n    :param v1: First vector \n    :type v1: Array of floats\n    :param v2: Second vector \n    :type v2: Array of floats\n    :param ndim: Dimension of v1 and v2.\n    :type ndim: int\n    :return: the relative difference between v1 and v2.\n    :rtype: float"
  },
  {
    "code": "def validate(self, **kwargs):\n        self.check_crossrefs()\n        for value in self.values():\n            value.validate(**kwargs)",
    "docstring": "Validates each entry (passing the provided arguments down to them and\n        also tries to resolve all cross-references between the entries."
  },
  {
    "code": "def set_weights(self, new_weights):\n        self._check_sess()\n        assign_list = [\n            self.assignment_nodes[name] for name in new_weights.keys()\n            if name in self.assignment_nodes\n        ]\n        assert assign_list, (\"No variables in the input matched those in the \"\n                             \"network. Possible cause: Two networks were \"\n                             \"defined in the same TensorFlow graph. To fix \"\n                             \"this, place each network definition in its own \"\n                             \"tf.Graph.\")\n        self.sess.run(\n            assign_list,\n            feed_dict={\n                self.placeholders[name]: value\n                for (name, value) in new_weights.items()\n                if name in self.placeholders\n            })",
    "docstring": "Sets the weights to new_weights.\n\n        Note:\n            Can set subsets of variables as well, by only passing in the\n            variables you want to be set.\n\n        Args:\n            new_weights (Dict): Dictionary mapping variable names to their\n                weights."
  },
  {
    "code": "def run(self):\n        \"sets up the desired services and runs the requested action\"\n        self.addServices()\n        self.catalogServers(self.hendrix)\n        action = self.action\n        fd = self.options['fd']\n        if action.startswith('start'):\n            chalk.blue(self._listening_message())\n            getattr(self, action)(fd)\n            try:\n                self.reactor.run()\n            finally:\n                shutil.rmtree(PID_DIR, ignore_errors=True)\n        elif action == 'restart':\n            getattr(self, action)(fd=fd)\n        else:\n            getattr(self, action)()",
    "docstring": "sets up the desired services and runs the requested action"
  },
  {
    "code": "def to_dict(self):\n    ret = {}\n    for key in ['name', 'cmd', 'id', 'start_time', 'end_time',\n                'outcome', 'start_time_string', 'start_delta_string']:\n      val = getattr(self, key)\n      ret[key] = val() if hasattr(val, '__call__') else val\n    ret['parent'] = self.parent.to_dict() if self.parent else None\n    return ret",
    "docstring": "Useful for providing arguments to templates.\n\n    :API: public"
  },
  {
    "code": "def clean_caches(path):\n    for dirname, subdirlist, filelist in os.walk(path):\n        for f in filelist:\n            if f.endswith('pyc'):\n                try:\n                    os.remove(os.path.join(dirname, f))\n                except FileNotFoundError:\n                    pass\n        if dirname.endswith('__pycache__'):\n            shutil.rmtree(dirname)",
    "docstring": "Removes all python cache files recursively on a path.\n\n    :param path: the path\n    :return: None"
  },
  {
    "code": "def getAngle(self, mode='deg'):\n        if self.refresh is True:\n            self.getMatrix()\n        try:\n            if self.mflag:\n                if mode == 'deg':\n                    return self.bangle / np.pi * 180\n                else:\n                    return self.bangle\n            else:\n                return 0\n        except AttributeError:\n            print(\"Please execute getMatrix() first.\")",
    "docstring": "return bend angle\n\n        :param mode: 'deg' or 'rad'\n        :return: deflecting angle in RAD"
  },
  {
    "code": "def log_normalize(a, axis=None):\n    with np.errstate(under=\"ignore\"):\n        a_lse = logsumexp(a, axis)\n    a -= a_lse[:, np.newaxis]",
    "docstring": "Normalizes the input array so that the exponent of the sum is 1.\n\n    Parameters\n    ----------\n    a : array\n        Non-normalized input data.\n\n    axis : int\n        Dimension along which normalization is performed.\n\n    Notes\n    -----\n    Modifies the input **inplace**."
  },
  {
    "code": "def _verify_run(out, cmd=None):\n    if out.get('retcode', 0) and out['stderr']:\n        if cmd:\n            log.debug('Command: \\'%s\\'', cmd)\n        log.debug('Return code: %s', out.get('retcode'))\n        log.debug('Error output:\\n%s', out.get('stderr', 'N/A'))\n        raise CommandExecutionError(out['stderr'])",
    "docstring": "Crash to the log if command execution was not successful."
  },
  {
    "code": "def send_facebook(self, token):\n        self.send_struct('<B%iB' % len(token), 81, *map(ord, token))\n        self.facebook_token = token",
    "docstring": "Tells the server which Facebook account this client uses.\n\n        After sending, the server takes some time to\n        get the data from Facebook.\n\n        Seems to be broken in recent versions of the game."
  },
  {
    "code": "def drawAsInfinite(requestContext, seriesList):\n    for series in seriesList:\n        series.options['drawAsInfinite'] = True\n        series.name = 'drawAsInfinite(%s)' % series.name\n    return seriesList",
    "docstring": "Takes one metric or a wildcard seriesList.\n    If the value is zero, draw the line at 0. If the value is above zero, draw\n    the line at infinity. If the value is null or less than zero, do not draw\n    the line.\n\n    Useful for displaying on/off metrics, such as exit codes. (0 = success,\n    anything else = failure.)\n\n    Example::\n\n        drawAsInfinite(Testing.script.exitCode)"
  },
  {
    "code": "def dfs_present(path):\n    cmd_return = _hadoop_cmd('dfs', 'stat', path)\n    match = 'No such file or directory'\n    return False if match in cmd_return else True",
    "docstring": "Check if a file or directory is present on the distributed FS.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' hadoop.dfs_present /some_random_file\n\n    Returns True if the file is present"
  },
  {
    "code": "def activate_program(self, program):\n        self.logger.debug(\"activate_program %s\", program)\n        if program in self.program_stack:\n            return\n        with self._program_lock:\n            self.logger.debug(\"activate_program got through %s\", program)\n            self.program_stack.append(program)\n            self._update_program_stack()",
    "docstring": "Called by program which desires to manipulate this actuator, when it is activated."
  },
  {
    "code": "def can_solve(cls, resource):\n        for solvable_resource in cls.solvable_resources:\n            if isinstance(resource, solvable_resource):\n                return True\n        return False",
    "docstring": "Tells if the solver is able to resolve the given resource.\n\n        Arguments\n        ---------\n        resource : subclass of ``dataql.resources.Resource``\n            The resource to check if it is solvable by the current solver class\n\n        Returns\n        -------\n        boolean\n            ``True`` if the current solver class can solve the given resource, ``False`` otherwise.\n\n        Example\n        -------\n\n        >>> AttributeSolver.solvable_resources\n        (<class 'dataql.resources.Field'>,)\n        >>> AttributeSolver.can_solve(Field('foo'))\n        True\n        >>> AttributeSolver.can_solve(Object('bar'))\n        False"
  },
  {
    "code": "def verify(self, keys=None):\n        try:\n            res = self._verify()\n        except AssertionError as err:\n            logger.error(\"Verification error on the response: %s\", err)\n            raise\n        else:\n            if res is None:\n                return None\n        if not isinstance(self.response, samlp.Response):\n            return self\n        if self.parse_assertion(keys):\n            return self\n        else:\n            logger.error(\"Could not parse the assertion\")\n            return None",
    "docstring": "Verify that the assertion is syntactically correct and the\n        signature is correct if present.\n\n        :param keys: If not the default key file should be used then use one\n        of these."
  },
  {
    "code": "def init_hierarchy(cls, model_admin):\n        hierarchy = getattr(model_admin, 'hierarchy')\n        if hierarchy:\n            if not isinstance(hierarchy, Hierarchy):\n                hierarchy = AdjacencyList()\n        else:\n            hierarchy = NoHierarchy()\n        model_admin.hierarchy = hierarchy",
    "docstring": "Initializes model admin with hierarchy data."
  },
  {
    "code": "def polynomial(img, mask, inplace=False, replace_all=False,\r\n               max_dev=1e-5, max_iter=20, order=2):\r\n    if inplace:\r\n        out = img\r\n    else:\r\n        out = img.copy()\r\n    lastm = 0\r\n    for _ in range(max_iter):\r\n        out2 = polyfit2dGrid(out, mask, order=order, copy=not inplace,\r\n                             replace_all=replace_all)\r\n        if replace_all:\r\n            out = out2\r\n            break\r\n        res = (np.abs(out2 - out)).mean()\r\n        print('residuum: ', res)\r\n        if res < max_dev:\r\n            out = out2\r\n            break\r\n        out = out2\r\n        mask = _highGrad(out)\r\n        m = mask.sum()\r\n        if m == lastm or m == img.size:\r\n            break\r\n        lastm = m\r\n    out = np.clip(out, 0, 1, out=out)\n    return out",
    "docstring": "replace all masked values\r\n    calculate flatField from 2d-polynomal fit filling\r\n    all high gradient areas within averaged fit-image\r\n\r\n    returns flatField, average background level, fitted image, valid indices mask"
  },
  {
    "code": "def main(args=None):\n    if args is None:\n        args = sys.argv[1:]\n    o = Options()\n    try:\n        o.parseOptions(args)\n    except usage.UsageError, e:\n        raise SystemExit(str(e))\n    else:\n        return createSSLCertificate(o)",
    "docstring": "Create a private key and a certificate and write them to a file."
  },
  {
    "code": "def get_static_lib_paths():\n    libs = []\n    is_linux = sys.platform.startswith('linux')\n    if is_linux:\n        libs += ['-Wl,--start-group']\n    libs += get_raw_static_lib_path()\n    if is_linux:\n        libs += ['-Wl,--end-group']\n    return libs",
    "docstring": "Return the required static libraries path"
  },
  {
    "code": "def set_deployment_run_name(self):\n        log = logging.getLogger(self.cls_logger + '.set_deployment_run_name')\n        self.deployment_run_name = self.get_value('cons3rt.deploymentRun.name')\n        log.info('Found deployment run name: {n}'.format(n=self.deployment_run_name))",
    "docstring": "Sets the deployment run name from deployment properties\n\n        :return: None"
  },
  {
    "code": "def _element_find_from_root(\n        root,\n        element_path\n):\n    element = None\n    element_names = element_path.split('/')\n    if element_names[0] == root.tag:\n        if len(element_names) > 1:\n            element = root.find('/'.join(element_names[1:]))\n        else:\n            element = root\n    return element",
    "docstring": "Find the element specified by the given path starting from the root element of the document.\n\n    The first component of the element path is expected to be the name of the root element. Return\n    None if the element is not found."
  },
  {
    "code": "def get_trial(self, trial_id):\n        response = requests.get(\n            urljoin(self._path, \"trials/{}\".format(trial_id)))\n        return self._deserialize(response)",
    "docstring": "Returns trial information by trial_id."
  },
  {
    "code": "def check(branch: str = 'master'):\n    if os.environ.get('TRAVIS') == 'true':\n        travis(branch)\n    elif os.environ.get('SEMAPHORE') == 'true':\n        semaphore(branch)\n    elif os.environ.get('FRIGG') == 'true':\n        frigg(branch)\n    elif os.environ.get('CIRCLECI') == 'true':\n        circle(branch)\n    elif os.environ.get('GITLAB_CI') == 'true':\n        gitlab(branch)\n    elif 'BITBUCKET_BUILD_NUMBER' in os.environ:\n        bitbucket(branch)",
    "docstring": "Detects the current CI environment, if any, and performs necessary\n    environment checks.\n\n    :param branch: The branch that should be the current branch."
  },
  {
    "code": "def Jobs(self, crawlId=None):\n        crawlId = crawlId if crawlId else defaultCrawlId()\n        return JobClient(self.server, crawlId, self.confId)",
    "docstring": "Create a JobClient for listing and creating jobs.\n        The JobClient inherits the confId from the Nutch client.\n\n        :param crawlId: crawlIds to use for this client.  If not provided, will be generated\n         by nutch.defaultCrawlId()\n        :return: a JobClient"
  },
  {
    "code": "def _new_alloc_handle(shape, ctx, delay_alloc, dtype=mx_real_t):\n    hdl = NDArrayHandle()\n    check_call(_LIB.MXNDArrayCreateEx(\n        c_array_buf(mx_uint, native_array('I', shape)),\n        mx_uint(len(shape)),\n        ctypes.c_int(ctx.device_typeid),\n        ctypes.c_int(ctx.device_id),\n        ctypes.c_int(int(delay_alloc)),\n        ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])),\n        ctypes.byref(hdl)))\n    return hdl",
    "docstring": "Return a new handle with specified shape and context.\n\n    Empty handle is only used to hold results.\n\n    Returns\n    -------\n    handle\n        A new empty `NDArray` handle."
  },
  {
    "code": "def handle(cls, value, **kwargs):\n        try:\n            env_var_name, default_val = value.split(\"::\", 1)\n        except ValueError:\n            raise ValueError(\"Invalid value for default: %s. Must be in \"\n                             \"<env_var>::<default value> format.\" % value)\n        if env_var_name in kwargs['context'].environment:\n            return kwargs['context'].environment[env_var_name]\n        else:\n            return default_val",
    "docstring": "Use a value from the environment or fall back to a default if the\n           environment doesn't contain the variable.\n\n        Format of value:\n\n            <env_var>::<default value>\n\n        For example:\n\n            Groups: ${default app_security_groups::sg-12345,sg-67890}\n\n        If `app_security_groups` is defined in the environment, its defined\n        value will be returned. Otherwise, `sg-12345,sg-67890` will be the\n        returned value.\n\n        This allows defaults to be set at the config file level."
  },
  {
    "code": "def _load_data(batch, targets, major_axis):\n    if isinstance(batch, list):\n        new_batch = []\n        for i in range(len(targets)):\n            new_batch.append([b.data[i] for b in batch])\n        new_targets = [[dst for _, dst in d_target] for d_target in targets]\n        _load_general(new_batch, new_targets, major_axis)\n    else:\n        _load_general(batch.data, targets, major_axis)",
    "docstring": "Load data into sliced arrays."
  },
  {
    "code": "def move_to_next_bit_address(self):\n        self._current_bit_address = self.next_bit_address()\n        self.mark_address(self._current_bit_address.split('.')[0], self._size_of_current_register_address)",
    "docstring": "Moves to next available bit address position"
  },
  {
    "code": "def irreducible_causes(self):\n        return tuple(link for link in self\n                     if link.direction is Direction.CAUSE)",
    "docstring": "The set of irreducible causes in this |Account|."
  },
  {
    "code": "def set_attr(self, **kwargs):\n        for key, value in kwargs.items():\n            if value is not None:\n                if not isinstance(value, string_type):\n                    raise ValueError(\"Only string values are accepted\")\n                self.__attr[key] = value\n            else:\n                self.__attr.pop(key, None)\n        return self",
    "docstring": "Set attributes to the Booster.\n\n        Parameters\n        ----------\n        **kwargs\n            The attributes to set.\n            Setting a value to None deletes an attribute.\n\n        Returns\n        -------\n        self : Booster\n            Booster with set attributes."
  },
  {
    "code": "def qualified_class_name(o):\n    module = o.__class__.__module__\n    if module is None or module == str.__class__.__module__:\n        return o.__class__.__name__\n    return module + '.' + o.__class__.__name__",
    "docstring": "Full name of an object, including the module"
  },
  {
    "code": "def max(self, axis=None, skipna=True):\n        nv.validate_minmax_axis(axis)\n        return nanops.nanmax(self._values, skipna=skipna)",
    "docstring": "Return the maximum value of the Index.\n\n        Parameters\n        ----------\n        axis : int, optional\n            For compatibility with NumPy. Only 0 or None are allowed.\n        skipna : bool, default True\n\n        Returns\n        -------\n        scalar\n            Maximum value.\n\n        See Also\n        --------\n        Index.min : Return the minimum value in an Index.\n        Series.max : Return the maximum value in a Series.\n        DataFrame.max : Return the maximum values in a DataFrame.\n\n        Examples\n        --------\n        >>> idx = pd.Index([3, 2, 1])\n        >>> idx.max()\n        3\n\n        >>> idx = pd.Index(['c', 'b', 'a'])\n        >>> idx.max()\n        'c'\n\n        For a MultiIndex, the maximum is determined lexicographically.\n\n        >>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)])\n        >>> idx.max()\n        ('b', 2)"
  },
  {
    "code": "def substitute(self, values: Dict[str, Any]) -> str:\n        return self.template.substitute(values)",
    "docstring": "generate url with url template"
  },
  {
    "code": "def shell_source(script):\n    pipe = subprocess.Popen(\n        \". %s; env\" % script, stdout=subprocess.PIPE, shell=True)\n    output = pipe.communicate()[0].decode()\n    env = {}\n    for line in output.splitlines():\n        try:\n            keyval = line.split(\"=\", 1)\n            env[keyval[0]] = keyval[1]\n        except:\n            pass\n    os.environ.update(env)",
    "docstring": "Sometime you want to emulate the action of \"source\" in bash,\n    settings some environment variables. Here is a way to do it."
  },
  {
    "code": "def _handle_sigusr2(self, signum: int, frame: Any) -> None:\n        logger.warning(\"Catched SIGUSR2\")\n        if self.current_task:\n            logger.warning(\"Dropping current task...\")\n            raise Discard",
    "docstring": "Drop current task."
  },
  {
    "code": "def get_printer(colors: bool = True, width_limit: bool = True, disabled: bool = False) -> Printer:\n    global _printer\n    global _colors\n    colors = colors and _colors\n    if not _printer or (colors != _printer._colors) or (width_limit != _printer._width_limit):\n        _printer = Printer(DefaultWriter(disabled=disabled), colors=colors, width_limit=width_limit)\n    return _printer",
    "docstring": "Returns an already initialized instance of the printer.\n\n    :param colors: If False, no colors will be printed.\n    :param width_limit: If True, printing width will be limited by console width.\n    :param disabled: If True, nothing will be printed."
  },
  {
    "code": "def load_fixture(fixture_path: str,\n                 fixture_key: str,\n                 normalize_fn: Callable[..., Any]=identity) -> Dict[str, Any]:\n    file_fixtures = load_json_fixture(fixture_path)\n    fixture = normalize_fn(file_fixtures[fixture_key])\n    return fixture",
    "docstring": "Loads a specific fixture from a fixture file, optionally passing it through\n    a normalization function."
  },
  {
    "code": "def exception_set(self, exception=None):\n        if not exception:\n            exception = sys.exc_info()\n        self.exception = exception\n        self.exception_raise = self._exception_raise",
    "docstring": "Records an exception to be raised at the appropriate time.\n\n        This also changes the \"exception_raise\" attribute to point\n        to the method that will, in fact"
  },
  {
    "code": "def _smooth_the_residuals(self):\n        for primary_smooth in self._primary_smooths:\n            smooth = smoother.perform_smooth(self.x,\n                                             primary_smooth.cross_validated_residual,\n                                             MID_SPAN)\n            self._residual_smooths.append(smooth.smooth_result)",
    "docstring": "Apply the MID_SPAN to the residuals of the primary smooths.\n\n        \"For stability reasons, it turns out to be a little better to smooth\n        |r_{i}(J)| against xi\" - [1]"
  },
  {
    "code": "def traverse(self, traverser, **kwargs):\n        result = self.rule.traverse(traverser, **kwargs)\n        return self.conversion(result)",
    "docstring": "Implementation of mandatory interface for traversing the whole rule tree.\n        This method will call the ``traverse`` method of child rule tree and\n        then perform arbitrary conversion of the result before returning it back.\n        The optional ``kwargs`` are passed down to traverser callback as additional\n        arguments and can be used to provide additional data or context.\n\n        :param pynspect.rules.RuleTreeTraverser traverser: Traverser object providing appropriate interface.\n        :param dict kwargs: Additional optional keyword arguments to be passed down to traverser callback."
  },
  {
    "code": "def _solve(self, sense=None):\n        while len(self._remove_constr) > 0:\n            self._remove_constr.pop().delete()\n        try:\n            return self._prob.solve(sense=sense)\n        except lp.SolverError as e:\n            raise_from(MOMAError(text_type(e)), e)\n        finally:\n            self._remove_constr = []",
    "docstring": "Remove old constraints and then solve the current problem.\n\n        Args:\n            sense: Minimize or maximize the objective.\n                (:class:`.lp.ObjectiveSense)\n\n        Returns:\n            The Result object for the solved LP problem"
  },
  {
    "code": "def load_config(args, config_path=\".inlineplz.yml\"):\n    config = {}\n    try:\n        with open(config_path) as configfile:\n            config = yaml.safe_load(configfile) or {}\n            if config:\n                print(\"Loaded config from {}\".format(config_path))\n                pprint.pprint(config)\n    except (IOError, OSError, yaml.parser.ParserError):\n        traceback.print_exc()\n    args = update_from_config(args, config)\n    args.ignore_paths = args.__dict__.get(\"ignore_paths\") or [\n        \"node_modules\",\n        \".git\",\n        \".tox\",\n        \"godeps\",\n        \"vendor\",\n        \"site-packages\",\n        \"venv\",\n        \".env\",\n        \"spec\",\n        \"migrate\",\n        \"bin\",\n        \"fixtures\",\n        \"cassettes\",\n        \".cache\",\n        \".idea\",\n        \".pytest_cache\",\n        \"__pycache__\",\n        \"dist\",\n    ]\n    if config_path != \".inlineplz.yml\":\n        return args\n    if args.config_dir and not config:\n        new_config_path = os.path.join(args.config_dir, config_path)\n        if os.path.exists(new_config_path):\n            return load_config(args, new_config_path)\n    return args",
    "docstring": "Load inline-plz config from yaml config file with reasonable defaults."
  },
  {
    "code": "def check_url(self, url, is_image_src=False):\n        return bool(self._allowed_url_re.match(url))",
    "docstring": "This method is used to check a URL.\n\n        Returns :obj:`True` if the URL is \"safe\", :obj:`False` otherwise.\n\n        The default implementation only allows HTTP and HTTPS links. That means\n        no ``mailto:``, no ``xmpp:``, no ``ftp:``, etc.\n\n        This method exists specifically to allow easy customization of link\n        filtering through subclassing, so don't hesitate to write your own.\n\n        If you're thinking of implementing a blacklist approach, see\n        \"`Which URL schemes are dangerous (XSS exploitable)?\n        <http://security.stackexchange.com/q/148428/37409>`_\"."
  },
  {
    "code": "def rsync(local_path, remote_path, exclude=None, extra_opts=None):\n    if not local_path.endswith('/'):\n        local_path += '/'\n    exclude = exclude or []\n    exclude.extend(['*.egg-info', '*.pyc', '.git', '.gitignore',\n                    '.gitmodules', '/build/', '/dist/'])\n    with hide('running'):\n        run(\"mkdir -p '{}'\".format(remote_path))\n        return rsync_project(\n            remote_path, local_path, delete=True,\n            extra_opts='-i --omit-dir-times -FF ' +\n                       (extra_opts if extra_opts else ''),\n            ssh_opts='-o StrictHostKeyChecking=no',\n            exclude=exclude)",
    "docstring": "Helper to rsync submodules across"
  },
  {
    "code": "def _pct_diff(self, best, other):\n        return colorize(\"{}%\".format(\n            round(((best-other)/best)*100, 2)).rjust(10), \"red\")",
    "docstring": "Calculates and colorizes the percent difference between @best\n            and @other"
  },
  {
    "code": "def profile_path(self, path, must_exist=False):\n        full_path = self.session.profile / path\n        if must_exist and not full_path.exists():\n            raise FileNotFoundError(\n                errno.ENOENT,\n                os.strerror(errno.ENOENT),\n                PurePath(full_path).name,\n            )\n        return full_path",
    "docstring": "Return path from current profile."
  },
  {
    "code": "def _convert_value(self, column, value):\n        if isinstance(value, GObject.Value):\n            return value\n        return GObject.Value(self.get_column_type(column), value)",
    "docstring": "Convert value to a GObject.Value of the expected type"
  },
  {
    "code": "def label(self):\n        if self.valuetype_class.is_label():\n            return self\n        for c in self.table.columns:\n            if c.parent == self.name and  c.valuetype_class.is_label():\n                return c\n        return None",
    "docstring": "Return first child of the column that is marked as a label. Returns self if the column is a label"
  },
  {
    "code": "def _convert_punctuation(punctuation, conversion_table):\n    if punctuation in conversion_table:\n        return conversion_table[punctuation]\n    return re.escape(punctuation)",
    "docstring": "Return a regular expression for a punctuation string."
  },
  {
    "code": "def safe_args(args,\n              options,\n              max_args=None,\n              argfile=None,\n              delimiter='\\n',\n              quoter=None,\n              delete=True):\n  max_args = max_args or options.max_subprocess_args\n  if len(args) > max_args:\n    def create_argfile(f):\n      logger.debug('Creating argfile {} with contents {}'.format(f.name, ' '.join(args)))\n      f.write(delimiter.join(args))\n      f.close()\n      return [quoter(f.name) if quoter else '@{}'.format(f.name)]\n    if argfile:\n      try:\n        with safe_open(argfile, 'w') as fp:\n          yield create_argfile(fp)\n      finally:\n        if delete and os.path.exists(argfile):\n          os.unlink(argfile)\n    else:\n      with temporary_file(cleanup=delete, binary_mode=False) as fp:\n        yield create_argfile(fp)\n  else:\n    yield args",
    "docstring": "Yields args if there are less than a limit otherwise writes args to an argfile and yields an\n  argument list with one argument formed from the path of the argfile.\n\n  :param args: The args to work with.\n  :param OptionValueContainer options: scoped options object for this task\n  :param max_args: The maximum number of args to let though without writing an argfile.  If not\n    specified then the maximum will be loaded from the --max-subprocess-args option.\n  :param argfile: The file to write args to when there are too many; defaults to a temporary file.\n  :param delimiter: The delimiter to insert between args written to the argfile, defaults to '\\n'\n  :param quoter: A function that can take the argfile path and return a single argument value;\n    defaults to: <code>lambda f: '@' + f<code>\n  :param delete: If True deletes any arg files created upon exit from this context; defaults to\n    True."
  },
  {
    "code": "def compute_average_oxidation_state(site):\n    try:\n        avg_oxi = sum([sp.oxi_state * occu\n                       for sp, occu in site.species.items()\n                       if sp is not None])\n        return avg_oxi\n    except AttributeError:\n        pass\n    try:\n        return site.charge\n    except AttributeError:\n        raise ValueError(\"Ewald summation can only be performed on structures \"\n                         \"that are either oxidation state decorated or have \"\n                         \"site charges.\")",
    "docstring": "Calculates the average oxidation state of a site\n\n    Args:\n        site: Site to compute average oxidation state\n\n    Returns:\n        Average oxidation state of site."
  },
  {
    "code": "def mpim_history(self, *, channel: str, **kwargs) -> SlackResponse:\n        kwargs.update({\"channel\": channel})\n        return self.api_call(\"mpim.history\", http_verb=\"GET\", params=kwargs)",
    "docstring": "Fetches history of messages and events from a multiparty direct message.\n\n        Args:\n            channel (str): Multiparty direct message to fetch history for. e.g. 'G1234567890'"
  },
  {
    "code": "def get_error(self):\n        exc_info = sys.exc_info()\n        if exc_info[0] is None:\n            return None\n        else:\n            err_type, err_value, err_trace = exc_info[0], exc_info[1], None\n            if self.verbose and len(exc_info) > 2:\n                err_trace = exc_info[2]\n            return format_error(err_type, err_value, err_trace)",
    "docstring": "Properly formats the current error."
  },
  {
    "code": "def set_trace(host='', port=5555, patch_stdstreams=False):\n    pdb = WebPdb.active_instance\n    if pdb is None:\n        pdb = WebPdb(host, port, patch_stdstreams)\n    else:\n        pdb.remove_trace()\n    pdb.set_trace(sys._getframe().f_back)",
    "docstring": "Start the debugger\n\n    This method suspends execution of the current script\n    and starts a PDB debugging session. The web-interface is opened\n    on the specified port (default: ``5555``).\n\n    Example::\n\n        import web_pdb;web_pdb.set_trace()\n\n    Subsequent :func:`set_trace` calls can be used as hardcoded breakpoints.\n\n    :param host: web-UI hostname or IP-address\n    :type host: str\n    :param port: web-UI port. If ``port=-1``, choose a random port value\n     between 32768 and 65536.\n    :type port: int\n    :param patch_stdstreams: redirect all standard input and output\n        streams to the web-UI.\n    :type patch_stdstreams: bool"
  },
  {
    "code": "def FinalizeTransferUrl(self, url):\n        url_builder = _UrlBuilder.FromUrl(url)\n        if self.global_params.key:\n            url_builder.query_params['key'] = self.global_params.key\n        return url_builder.url",
    "docstring": "Modify the url for a given transfer, based on auth and version."
  },
  {
    "code": "def three_cornered_hat_phase(phasedata_ab, phasedata_bc,\n                             phasedata_ca, rate, taus, function):\n    (tau_ab, dev_ab, err_ab, ns_ab) = function(phasedata_ab,\n                                               data_type='phase',\n                                               rate=rate, taus=taus)\n    (tau_bc, dev_bc, err_bc, ns_bc) = function(phasedata_bc,\n                                               data_type='phase',\n                                               rate=rate, taus=taus)\n    (tau_ca, dev_ca, err_ca, ns_ca) = function(phasedata_ca,\n                                               data_type='phase',\n                                               rate=rate, taus=taus)\n    var_ab = dev_ab * dev_ab\n    var_bc = dev_bc * dev_bc\n    var_ca = dev_ca * dev_ca\n    assert len(var_ab) == len(var_bc) == len(var_ca)\n    var_a = 0.5 * (var_ab + var_ca - var_bc)\n    var_a[var_a < 0] = 0\n    dev_a = np.sqrt(var_a)\n    err_a = [d/np.sqrt(nn) for (d, nn) in zip(dev_a, ns_ab)]\n    return tau_ab, dev_a, err_a, ns_ab",
    "docstring": "Three Cornered Hat Method\n\n    Given three clocks A, B, C, we seek to find their variances\n    :math:`\\\\sigma^2_A`, :math:`\\\\sigma^2_B`, :math:`\\\\sigma^2_C`.\n    We measure three phase differences, assuming no correlation between\n    the clocks, the measurements have variances:\n\n    .. math::\n\n        \\\\sigma^2_{AB} = \\\\sigma^2_{A} + \\\\sigma^2_{B}\n\n        \\\\sigma^2_{BC} = \\\\sigma^2_{B} + \\\\sigma^2_{C}\n\n        \\\\sigma^2_{CA} = \\\\sigma^2_{C} + \\\\sigma^2_{A}\n\n    Which allows solving for the variance of one clock as:\n\n    .. math::\n\n        \\\\sigma^2_{A}  = {1 \\\\over 2} ( \\\\sigma^2_{AB} +\n        \\\\sigma^2_{CA} - \\\\sigma^2_{BC} )\n\n    and similarly cyclic permutations for :math:`\\\\sigma^2_B` and\n    :math:`\\\\sigma^2_C`\n\n    Parameters\n    ----------\n    phasedata_ab: np.array\n        phase measurements between clock A and B, in seconds\n    phasedata_bc: np.array\n        phase measurements between clock B and C, in seconds\n    phasedata_ca: np.array\n        phase measurements between clock C and A, in seconds\n    rate: float\n        The sampling rate for phase, in Hz\n    taus: np.array\n        The tau values for deviations, in seconds\n    function: allantools deviation function\n        The type of statistic to compute, e.g. allantools.oadev\n\n    Returns\n    -------\n    tau_ab: np.array\n        Tau values corresponding to output deviations\n    dev_a: np.array\n        List of computed values for clock A\n\n    References\n    ----------\n    http://www.wriley.com/3-CornHat.htm"
  },
  {
    "code": "def html_entity_decode_codepoint(self, m,\n                                     defs=htmlentities.codepoint2name):\n        try:\n            char = defs[m.group(1)]\n            return \"&{char};\".format(char=char)\n        except ValueError:\n            return m.group(0)\n        except KeyError:\n            return m.group(0)",
    "docstring": "decode html entity into one of the codepoint2name"
  },
  {
    "code": "def _send(self, line):\n        if not line.endswith('\\r\\n'):\n            if line.endswith('\\n'):\n                logger.debug('Fixing bare LF before sending data to socket')\n                line = line[0:-1] + '\\r\\n'\n            else:\n                logger.debug(\n                    'Fixing missing CRLF before sending data to socket')\n                line = line + '\\r\\n'\n        logger.debug('Client sent: ' + line.rstrip())\n        self._socket.send(line)",
    "docstring": "Write a line of data to the server.\n\n        Args:\n        line -- A single line of data to write to the socket."
  },
  {
    "code": "def request_token(self):\n        client = OAuth1(\n            client_key=self._server_cache[self.client.server].key,\n            client_secret=self._server_cache[self.client.server].secret,\n            callback_uri=self.callback,\n        )\n        request = {\"auth\": client}\n        response = self._requester(\n            requests.post,\n            \"oauth/request_token\",\n            **request\n        )\n        data = parse.parse_qs(response.text)\n        data = {\n            'token': data[self.PARAM_TOKEN][0],\n            'token_secret': data[self.PARAM_TOKEN_SECRET][0]\n        }\n        return data",
    "docstring": "Gets OAuth request token"
  },
  {
    "code": "def generate_epochs_info(epoch_list):\n    time1 = time.time()\n    epoch_info = []\n    for sid, epoch in enumerate(epoch_list):\n        for cond in range(epoch.shape[0]):\n            sub_epoch = epoch[cond, :, :]\n            for eid in range(epoch.shape[1]):\n                r = np.sum(sub_epoch[eid, :])\n                if r > 0:\n                    start = np.nonzero(sub_epoch[eid, :])[0][0]\n                    epoch_info.append((cond, sid, start, start + r))\n    time2 = time.time()\n    logger.debug(\n        'epoch separation done, takes %.2f s' %\n        (time2 - time1)\n    )\n    return epoch_info",
    "docstring": "use epoch_list to generate epoch_info defined below\n\n    Parameters\n    ----------\n    epoch_list: list of 3D (binary) array in shape [condition, nEpochs, nTRs]\n        Contains specification of epochs and conditions, assuming\n        1. all subjects have the same number of epochs;\n        2. len(epoch_list) equals the number of subjects;\n        3. an epoch is always a continuous time course.\n\n    Returns\n    -------\n    epoch_info: list of tuple (label, sid, start, end).\n        label is the condition labels of the epochs;\n        sid is the subject id, corresponding to the index of raw_data;\n        start is the start TR of an epoch (inclusive);\n        end is the end TR of an epoch(exclusive).\n        Assuming len(labels) labels equals the number of epochs and\n        the epochs of the same sid are adjacent in epoch_info"
  },
  {
    "code": "def cache(self, dependency: Dependency, value):\n        if dependency.threadlocal:\n            setattr(self._local, dependency.name, value)\n        elif dependency.singleton:\n            self._singleton[dependency.name] = value",
    "docstring": "Store an instance of dependency in the cache.\n        Does nothing if dependency is NOT a threadlocal\n        or a singleton.  \n\n        :param dependency: The ``Dependency`` to cache\n        :param value: The value to cache for dependency\n\n        :type dependency: Dependency"
  },
  {
    "code": "def asserted(self):\n        if self.index == 0:\n            return False\n        return bool(lib.EnvFactExistp(self._env, self._fact))",
    "docstring": "True if the fact has been asserted within CLIPS."
  },
  {
    "code": "def untrace_module(module):\n    for name, function in inspect.getmembers(module, inspect.isfunction):\n        untrace_function(module, function)\n    for name, cls in inspect.getmembers(module, inspect.isclass):\n        untrace_class(cls)\n    set_untraced(module)\n    return True",
    "docstring": "Untraces given module members.\n\n    :param module: Module to untrace.\n    :type module: ModuleType\n    :return: Definition success.\n    :rtype: bool"
  },
  {
    "code": "def get_label(self, label_name):\n        for label in self.get_labels():\n            if label.name == label_name:\n                return label",
    "docstring": "Return the user's label that has a given name.\n\n        :param label_name: The name to search for.\n        :type label_name: str\n        :return: A label that has a matching name or ``None`` if not found.\n        :rtype: :class:`pytodoist.todoist.Label`\n\n        >>> from pytodoist import todoist\n        >>> user = todoist.login('john.doe@gmail.com', 'password')\n        >>> label = user.get_label('family')"
  },
  {
    "code": "def set_title(self, index, title):\n        index = unicode_type(int(index))\n        self._titles[index] = title\n        self.send_state('_titles')",
    "docstring": "Sets the title of a container page.\n\n        Parameters\n        ----------\n        index : int\n            Index of the container page\n        title : unicode\n            New title"
  },
  {
    "code": "def from_file(cls, filename):\n        with open(filename) as infp:\n            if filename.endswith('.yaml') or filename.endswith('.yml'):\n                import yaml\n                data = yaml.safe_load(infp)\n            else:\n                import json\n                data = json.load(infp)\n        return cls.from_data(data)",
    "docstring": "Construct an APIDefinition by parsing the given `filename`.\n\n        If PyYAML is installed, YAML files are supported.\n        JSON files are always supported.\n\n        :param filename: The filename to read.\n        :rtype: APIDefinition"
  },
  {
    "code": "def _create_tcex_dirs():\n        dirs = ['tcex.d', 'tcex.d/data', 'tcex.d/profiles']\n        for d in dirs:\n            if not os.path.isdir(d):\n                os.makedirs(d)",
    "docstring": "Create tcex.d directory and sub directories."
  },
  {
    "code": "def _validate_complex_fault_geometry(self, node, _float_re):\n        valid_edges = []\n        for edge_node in node.nodes:\n            try:\n                coords = split_coords_3d(edge_node.LineString.posList.text)\n                edge = geo.Line([geo.Point(*p) for p in coords])\n            except ValueError:\n                edge = []\n            if len(edge):\n                valid_edges.append(True)\n            else:\n                valid_edges.append(False)\n        if node[\"spacing\"] and all(valid_edges):\n            return\n        raise LogicTreeError(\n            node, self.filename,\n            \"'complexFaultGeometry' node is not valid\")",
    "docstring": "Validates a node representation of a complex fault geometry - this\n        check merely verifies that the format is correct. If the geometry\n        does not conform to the Aki & Richards convention this will not be\n        verified here, but will raise an error when the surface is created."
  },
  {
    "code": "def get_public_key(self, key_id, is_search_embedded=False):\n        if isinstance(key_id, int):\n            return self._public_keys[key_id]\n        for item in self._public_keys:\n            if item.get_id() == key_id:\n                return item\n        if is_search_embedded:\n            for authentication in self._authentications:\n                if authentication.get_public_key_id() == key_id:\n                    return authentication.get_public_key()\n        return None",
    "docstring": "Key_id can be a string, or int. If int then the index in the list of keys."
  },
  {
    "code": "def between(y, z):\n        return _combinable(lambda x: (y <= x < z) or _equal_or_float_equal(x, y))",
    "docstring": "Greater than or equal to y and less than z."
  },
  {
    "code": "def parse_server_addr(str_addr, default_port=26000):\n    m = ADDR_STR_RE.match(str_addr)\n    if m is None:\n        raise ValueError('Bad address string \"{0}\"'.format(str_addr))\n    dct = m.groupdict()\n    port = dct.get('port')\n    if port is None:\n        port = default_port\n    else:\n        port = int(port)\n    if port == 0:\n        raise ValueError(\"Port can't be zero\")\n    host = dct['host'] if dct['host'] else dct['host6']\n    return host, port",
    "docstring": "Parse address and returns host and port\n\n    Args:\n        str_addr --- string that contains server ip or hostname and optionaly\n        port\n\n    Returns: tuple (host, port)\n\n    Examples:\n\n    >>> parse_server_addr('127.0.0.1:26006')\n    ('127.0.0.1', 26006)\n    >>> parse_server_addr('[2001:db8:85a3:8d3:1319:8a2e:370:7348]:26006')\n    ('2001:db8:85a3:8d3:1319:8a2e:370:7348', 26006)\n    >>> parse_server_addr('[2001:db8:85a3:8d3:1319:8a2e:370:7348]')\n    ('2001:db8:85a3:8d3:1319:8a2e:370:7348', 26000)\n    >>> parse_server_addr('localhost:123')\n    ('localhost', 123)\n    >>> parse_server_addr('localhost:1d23')\n    Traceback (most recent call last):\n        ...\n    ValueError: Bad address string \"localhost:1d23\""
  },
  {
    "code": "def get_rec_dtype(self, **keys):\n        colnums = keys.get('colnums', None)\n        vstorage = keys.get('vstorage', self._vstorage)\n        if colnums is None:\n            colnums = self._extract_colnums()\n        descr = []\n        isvararray = numpy.zeros(len(colnums), dtype=numpy.bool)\n        for i, colnum in enumerate(colnums):\n            dt, isvar = self.get_rec_column_descr(colnum, vstorage)\n            descr.append(dt)\n            isvararray[i] = isvar\n        dtype = numpy.dtype(descr)\n        offsets = numpy.zeros(len(colnums), dtype='i8')\n        for i, n in enumerate(dtype.names):\n            offsets[i] = dtype.fields[n][1]\n        return dtype, offsets, isvararray",
    "docstring": "Get the dtype for the specified columns\n\n        parameters\n        ----------\n        colnums: integer array\n            The column numbers, 0 offset\n        vstorage: string, optional\n            See docs in read_columns"
  },
  {
    "code": "def get_jwt_decrypt_keys(self, jwt, **kwargs):\n        try:\n            _key_type = jwe_alg2keytype(jwt.headers['alg'])\n        except KeyError:\n            _key_type = ''\n        try:\n            _kid = jwt.headers['kid']\n        except KeyError:\n            logger.info('Missing kid')\n            _kid = ''\n        keys = self.get(key_use='enc', owner='', key_type=_key_type)\n        try:\n            _aud = kwargs['aud']\n        except KeyError:\n            _aud = ''\n        if _aud:\n            try:\n                allow_missing_kid = kwargs['allow_missing_kid']\n            except KeyError:\n                allow_missing_kid = False\n            try:\n                nki = kwargs['no_kid_issuer']\n            except KeyError:\n                nki = {}\n            keys = self._add_key(keys, _aud, 'enc', _key_type, _kid, nki,\n                                 allow_missing_kid)\n        keys = [k for k in keys if k.appropriate_for('decrypt')]\n        return keys",
    "docstring": "Get decryption keys from this keyjar based on information carried\n        in a JWE. These keys should be usable to decrypt an encrypted JWT.\n\n        :param jwt: A cryptojwt.jwt.JWT instance\n        :param kwargs: Other key word arguments\n        :return: list of usable keys"
  },
  {
    "code": "def _create(self, **kwargs):\n        if 'uri' in self._meta_data:\n            error = \"There was an attempt to assign a new uri to this \"\\\n                    \"resource, the _meta_data['uri'] is %s and it should\"\\\n                    \" not be changed.\" % (self._meta_data['uri'])\n            raise URICreationCollision(error)\n        self._check_exclusive_parameters(**kwargs)\n        requests_params = self._handle_requests_params(kwargs)\n        self._minimum_one_is_missing(**kwargs)\n        self._check_create_parameters(**kwargs)\n        kwargs = self._check_for_python_keywords(kwargs)\n        for key1, key2 in self._meta_data['reduction_forcing_pairs']:\n            kwargs = self._reduce_boolean_pair(kwargs, key1, key2)\n        _create_uri = self._meta_data['container']._meta_data['uri']\n        session = self._meta_data['bigip']._meta_data['icr_session']\n        kwargs = self._prepare_request_json(kwargs)\n        response = session.post(_create_uri, json=kwargs, **requests_params)\n        result = self._produce_instance(response)\n        return result",
    "docstring": "wrapped by `create` override that in subclasses to customize"
  },
  {
    "code": "def _get_image_url(self, image_id):\n        gce = self._connect()\n        filter = \"name eq %s\" % image_id\n        request = gce.images().list(project=self._project_id, filter=filter)\n        response = self._execute_request(request)\n        response = self._wait_until_done(response)\n        image_url = None\n        if \"items\" in response:\n            image_url = response[\"items\"][0][\"selfLink\"]\n        if image_url:\n            return image_url\n        else:\n            raise ImageError(\"Could not find given image id `%s`\" % image_id)",
    "docstring": "Gets the url for the specified image. Unfortunatly this only works\n        for images uploaded by the user. The images provided by google will\n        not be found.\n\n        :param str image_id: image identifier\n        :return: str - api url of the image"
  },
  {
    "code": "def prompt_for(self, next_param, intent_name):\n        def decorator(f):\n            prompts = self._intent_prompts.get(intent_name)\n            if prompts:\n                prompts[next_param] = f\n            else:\n                self._intent_prompts[intent_name] = {}\n                self._intent_prompts[intent_name][next_param] = f\n            @wraps(f)\n            def wrapper(*args, **kw):\n                self._flask_assitant_view_func(*args, **kw)\n            return f\n        return decorator",
    "docstring": "Decorates a function to prompt for an action's required parameter.\n\n        The wrapped function is called if next_param was not recieved with the given intent's\n        request and is required for the fulfillment of the intent's action.\n\n        Arguments:\n            next_param {str} -- name of the parameter required for action function\n            intent_name {str} -- name of the intent the dependent action belongs to"
  },
  {
    "code": "def bitstring_to_bytes(bitstr):\n    bitlist = list(bitstr)\n    bits_missing = (8 - len(bitlist) % 8) % 8\n    bitlist = [0]*bits_missing + bitlist\n    result = bytearray()\n    for i in range(0, len(bitlist), 8):\n        byte = 0\n        for j in range(8):\n            byte = (byte << 1) | bitlist[i+j]\n        result.append(byte)\n    return bytes(result)",
    "docstring": "Converts a pyasn1 univ.BitString instance to byte sequence of type 'bytes'.\n    The bit string is interpreted big-endian and is left-padded with 0 bits to form a multiple of 8."
  },
  {
    "code": "def respond_webhook(self, environ):\n        request = FieldStorage(fp=environ[\"wsgi.input\"], environ=environ)\n        url = environ[\"PATH_INFO\"]\n        params = dict([(k, request[k].value) for k in request])\n        try:\n            if self.bot is None:\n                raise NotImplementedError\n            response = self.bot.handle_webhook_event(environ, url, params)\n        except NotImplementedError:\n            return 404\n        except:\n            self.logger.debug(format_exc())\n            return 500\n        return response or 200",
    "docstring": "Passes the request onto a bot with a webhook if the webhook\n        path is requested."
  },
  {
    "code": "def clear(self):\n        for root, dirs, files in os.walk(self._root_dir, topdown=False):\n            for file in files:\n                os.unlink(os.path.join(root, file))\n            os.rmdir(root)\n        root_dir = os.path.abspath(\n            os.path.join(self._root_dir, os.pardir))\n        self.__init__(root_dir)",
    "docstring": "Clears all data from the data store permanently"
  },
  {
    "code": "def _set_child(self, name, child):\n        if not isinstance(child, Parentable):\n            raise ValueError('Parentable child object expected, not {child}'.format(child=child))\n        child._set_parent(self)\n        self._store_child(name, child)",
    "docstring": "Set child.\n\n        :param name: Child name.\n        :param child: Parentable object."
  },
  {
    "code": "def sources_add(source_uri, ruby=None, runas=None, gem_bin=None):\n    return _gem(['sources', '--add', source_uri],\n                ruby,\n                gem_bin=gem_bin,\n                runas=runas)",
    "docstring": "Add a gem source.\n\n    :param source_uri: string\n        The source URI to add.\n    :param gem_bin: string : None\n        Full path to ``gem`` binary to use.\n    :param ruby: string : None\n        If RVM or rbenv are installed, the ruby version and gemset to use.\n        Ignored if ``gem_bin`` is specified.\n    :param runas: string : None\n        The user to run gem as.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' gem.sources_add http://rubygems.org/"
  },
  {
    "code": "def text_cleanup(data, key, last_type):\n    if key in data and last_type == STRING_TYPE:\n        data[key] = data[key].strip()\n    return data",
    "docstring": "I strip extra whitespace off multi-line strings if they are ready to be stripped!"
  },
  {
    "code": "def as_event_class(obj):\n    if is_string(obj):\n        for c in all_subclasses(AbinitEvent):\n            if c.__name__ == obj or c.yaml_tag == obj: return c\n        raise ValueError(\"Cannot find event class associated to %s\" % obj)\n    assert obj in all_subclasses(AbinitEvent)\n    return obj",
    "docstring": "Convert obj into a subclass of AbinitEvent.\n    obj can be either a class or a string with the class name or the YAML tag"
  },
  {
    "code": "def restart(self):\n        command = const.CMD_RESTART\n        cmd_response = self.__send_command(command)\n        if cmd_response.get('status'):\n            self.is_connect = False\n            self.next_uid = 1\n            return True\n        else:\n            raise ZKErrorResponse(\"can't restart device\")",
    "docstring": "restart the device\n\n        :return: bool"
  },
  {
    "code": "def cmd_list(options):\n    (i_info, param_str) = gather_data(options)\n    if i_info:\n        awsc.get_all_aminames(i_info)\n        param_str = \"Instance List - \" + param_str + \"\\n\"\n        list_instances(i_info, param_str)\n    else:\n        print(\"No instances found with parameters: {}\".format(param_str))",
    "docstring": "Gather data for instances matching args and call display func.\n\n    Args:\n        options (object): contains args and data from parser."
  },
  {
    "code": "def get_marshaller_for_type(self, tp):\n        if not isinstance(tp, str):\n            tp = tp.__module__ + '.' + tp.__name__\n        if tp in self._types:\n            index = self._types[tp]\n        else:\n            return None, False\n        m = self._marshallers[index]\n        if self._imported_required_modules[index]:\n            return m, True\n        if not self._has_required_modules[index]:\n            return m, False\n        success = self._import_marshaller_modules(m)\n        self._has_required_modules[index] = success\n        self._imported_required_modules[index] = success\n        return m, success",
    "docstring": "Gets the appropriate marshaller for a type.\n\n        Retrieves the marshaller, if any, that can be used to read/write\n        a Python object with type 'tp'. The modules it requires, if\n        available, will be loaded.\n\n        Parameters\n        ----------\n        tp : type or str\n            Python object ``type`` (which would be the class reference)\n            or its string representation like ``'collections.deque'``.\n\n        Returns\n        -------\n        marshaller : marshaller or None\n            The marshaller that can read/write the type to\n            file. ``None`` if no appropriate marshaller is found.\n        has_required_modules : bool\n            Whether the required modules for reading the type are\n            present or not.\n\n        See Also\n        --------\n        hdf5storage.Marshallers.TypeMarshaller.types"
  },
  {
    "code": "def checkConfig():\n    config_file_dir = os.path.join(cwd, \"config.py\")\n    if os.path.exists(config_file_dir):\n        print(\"Making a backup of your config file!\")\n        config_file_dir2 = os.path.join(cwd, \"config.py.oldbak\")\n        copyfile(config_file_dir, config_file_dir2)",
    "docstring": "If the config.py file exists, back it up"
  },
  {
    "code": "def _compute_mod_regs(self, regs_init, regs_fini):\n        assert regs_init.keys() == regs_fini.keys()\n        modified_regs = []\n        for reg in regs_init:\n            if regs_init[reg] != regs_fini[reg]:\n                modified_regs.append(reg)\n        return modified_regs",
    "docstring": "Compute modified registers."
  },
  {
    "code": "def wait_for_event(self,\n                       event_name,\n                       predicate,\n                       timeout=DEFAULT_TIMEOUT,\n                       *args,\n                       **kwargs):\n        deadline = time.time() + timeout\n        while True:\n            event = None\n            try:\n                event = self.pop_event(event_name, 1)\n            except queue.Empty:\n                pass\n            if event and predicate(event, *args, **kwargs):\n                return event\n            if time.time() > deadline:\n                raise queue.Empty(\n                    'Timeout after {}s waiting for event: {}'.format(\n                        timeout, event_name))",
    "docstring": "Wait for an event that satisfies a predicate to appear.\n\n        Continuously pop events of a particular name and check against the\n        predicate until an event that satisfies the predicate is popped or\n        timed out. Note this will remove all the events of the same name that\n        do not satisfy the predicate in the process.\n\n        Args:\n            event_name: Name of the event to be popped.\n            predicate: A function that takes an event and returns True if the\n                predicate is satisfied, False otherwise.\n            timeout: Number of seconds to wait.\n            *args: Optional positional args passed to predicate().\n            **kwargs: Optional keyword args passed to predicate().\n\n        Returns:\n            The event that satisfies the predicate.\n\n        Raises:\n            queue.Empty: Raised if no event that satisfies the predicate was\n                found before time out."
  },
  {
    "code": "def _bsecurate_cli_print_component_file(args):\n    data = fileio.read_json_basis(args.file)\n    return printing.component_basis_str(data, elements=args.elements)",
    "docstring": "Handles the print-component-file subcommand"
  },
  {
    "code": "def refweights(self):\n        return numpy.full(self.shape, 1./self.shape[0], dtype=float)",
    "docstring": "A |numpy| |numpy.ndarray| with equal weights for all segment\n        junctions..\n\n        >>> from hydpy.models.hstream import *\n        >>> parameterstep('1d')\n        >>> states.qjoints.shape = 5\n        >>> states.qjoints.refweights\n        array([ 0.2,  0.2,  0.2,  0.2,  0.2])"
  },
  {
    "code": "def get_buffer_size_in_pages(cls, address, size):\n        if size < 0:\n            size    = -size\n            address = address - size\n        begin, end = cls.align_address_range(address, address + size)\n        return int(float(end - begin) / float(cls.pageSize))",
    "docstring": "Get the number of pages in use by the given buffer.\n\n        @type  address: int\n        @param address: Aligned memory address.\n\n        @type  size: int\n        @param size: Buffer size.\n\n        @rtype:  int\n        @return: Buffer size in number of pages."
  },
  {
    "code": "def run():\n    args = client_helper.grab_server_args()\n    workbench = zerorpc.Client(timeout=300, heartbeat=60)\n    workbench.connect('tcp://'+args['server']+':'+args['port'])\n    all_set = workbench.generate_sample_set()\n    results = workbench.set_work_request('view_customer', all_set)\n    for customer in results:\n        print customer['customer']",
    "docstring": "This client generates customer reports on all the samples in workbench."
  },
  {
    "code": "def _on_disconnect(_loop, adapter, _adapter_id, conn_id):\n    conn_string = adapter._get_property(conn_id, 'connection_string')\n    if conn_string is None:\n        adapter._logger.debug(\"Dropping disconnect notification with unknown conn_id=%s\", conn_id)\n        return\n    adapter._teardown_connection(conn_id, force=True)\n    event = dict(reason='no reason passed from legacy adapter', expected=False)\n    adapter.notify_event_nowait(conn_string, 'disconnection', event)",
    "docstring": "Callback when a device disconnects unexpectedly."
  },
  {
    "code": "def command_repo_remove(self):\n        if len(self.args) == 2 and self.args[0] == \"repo-remove\":\n            Repo().remove(self.args[1])\n        else:\n            usage(\"\")",
    "docstring": "Remove custom repositories"
  },
  {
    "code": "def _acceptpeak(peak, amp, definitive_peaks, spk1, rr_buffer):\n    definitive_peaks_out = definitive_peaks\n    definitive_peaks_out = numpy.append(definitive_peaks_out, peak)\n    spk1 = 0.125 * amp + 0.875 * spk1\n    if len(definitive_peaks_out) > 1:\n        rr_buffer.pop(0)\n        rr_buffer += [definitive_peaks_out[-1] - definitive_peaks_out[-2]]\n    return numpy.array(definitive_peaks_out), spk1, rr_buffer",
    "docstring": "Private function intended to insert a new RR interval in the buffer.\n\n    ----------\n    Parameters\n    ----------\n    peak : int\n        Sample where the peak under analysis is located.\n    amp : int\n        Amplitude of the peak under analysis.\n    definitive_peaks : list\n        List with the definitive_peaks stored until the present instant.\n    spk1 : float\n        Actual value of SPK1 parameter defined in Pan-Tompkins real-time R peak detection algorithm\n        (named signal peak).\n    rr_buffer : list\n        Data structure that stores the duration of the last eight RR intervals.\n\n    Returns\n    -------\n    definitive_peaks_out : list\n        Definitive peaks list.\n    spk1 : float\n        Updated value of SPK1 parameter.\n    rr_buffer : list\n        Buffer after appending a new RR interval and excluding the oldest one."
  },
  {
    "code": "def _add_inline_definition(item, statement):\n    global _current_statement\n    backup = _current_statement\n    type_, options = _expand_one_key_dictionary(item)\n    _current_statement = UnnamedStatement(type=type_)\n    _parse_statement(options)\n    statement.add_child(_current_statement)\n    _current_statement = backup",
    "docstring": "Adds an inline definition to statement."
  },
  {
    "code": "def TextInfo(filename=None, editable=False, **kwargs):\n    args = []\n    if filename:\n        args.append('--filename=%s' % filename)\n    if editable:\n        args.append('--editable')\n    for generic_args in kwargs_helper(kwargs):\n        args.append('--%s=%s' % generic_args)\n    p = run_zenity('--text-info', *args)\n    if p.wait() == 0:\n        return p.stdout.read()",
    "docstring": "Show the text of a file to the user.\n\n    This will raise a Zenity Text Information Dialog presenting the user with \n    the contents of a file.  It returns the contents of the text box.\n\n    filename - The path to the file to show.\n    editable - True if the text should be editable.\n    kwargs - Optional command line parameters for Zenity such as height,\n             width, etc."
  },
  {
    "code": "def parse_feeds(self, message_channel=True):\n        if parse:\n            for feed_url in self.feeds:\n                feed = parse(feed_url)\n                for item in feed.entries:\n                    if item[\"id\"] not in self.feed_items:\n                        self.feed_items.add(item[\"id\"])\n                        if message_channel:\n                            message = self.format_item_message(feed, item)\n                            self.message_channel(message)\n                            return",
    "docstring": "Iterates through each of the feed URLs, parses their items, and\n        sends any items to the channel that have not been previously\n        been parsed."
  },
  {
    "code": "def run(self):\n        services = Service.objects.all()\n        for service in services:\n            poll_service.apply_async(kwargs={\"service_id\": str(service.id)})\n        return \"Queued <%s> Service(s) for Polling\" % services.count()",
    "docstring": "Queues all services to be polled. Should be run via beat."
  },
  {
    "code": "def destroy(self, folder=None, as_coro=False):\n        async def _destroy(folder):\n            ret = self.save_info(folder)\n            for a in self.get_agents(addr=False):\n                a.close(folder=folder)\n            await self.shutdown(as_coro=True)\n            return ret\n        return run_or_coro(_destroy(folder), as_coro)",
    "docstring": "Destroy the environment.\n\n        Does the following:\n\n        1. calls :py:meth:`~creamas.core.Environment.save_info`\n        2. for each agent: calls :py:meth:`close`\n        3. Shuts down its RPC-service."
  },
  {
    "code": "def is_nash(self, action_profile, tol=None):\n        if self.N == 2:\n            for i, player in enumerate(self.players):\n                own_action, opponent_action = \\\n                    action_profile[i], action_profile[1-i]\n                if not player.is_best_response(own_action, opponent_action,\n                                               tol):\n                    return False\n        elif self.N >= 3:\n            for i, player in enumerate(self.players):\n                own_action = action_profile[i]\n                opponents_actions = \\\n                    tuple(action_profile[i+1:]) + tuple(action_profile[:i])\n                if not player.is_best_response(own_action, opponents_actions,\n                                               tol):\n                    return False\n        else:\n            if not self.players[0].is_best_response(action_profile[0], None,\n                                                    tol):\n                return False\n        return True",
    "docstring": "Return True if `action_profile` is a Nash equilibrium.\n\n        Parameters\n        ----------\n        action_profile : array_like(int or array_like(float))\n            An array of N objects, where each object must be an integer\n            (pure action) or an array of floats (mixed action).\n\n        tol : scalar(float)\n            Tolerance level used in determining best responses. If None,\n            default to each player's `tol` attribute value.\n\n        Returns\n        -------\n        bool\n            True if `action_profile` is a Nash equilibrium; False\n            otherwise."
  },
  {
    "code": "def user_defined_symbols(self):\n        sym_in_current = set(self.symtable.keys())\n        sym_from_construction = set(self.no_deepcopy)\n        unique_symbols = sym_in_current.difference(sym_from_construction)\n        return unique_symbols",
    "docstring": "Return a set of symbols that have been added to symtable after\n        construction.\n\n        I.e., the symbols from self.symtable that are not in\n        self.no_deepcopy.\n\n        Returns\n        -------\n        unique_symbols : set\n            symbols in symtable that are not in self.no_deepcopy"
  },
  {
    "code": "def _check_ndim(self, values, ndim):\n        if ndim is None:\n            ndim = values.ndim\n        if self._validate_ndim and values.ndim != ndim:\n            msg = (\"Wrong number of dimensions. values.ndim != ndim \"\n                   \"[{} != {}]\")\n            raise ValueError(msg.format(values.ndim, ndim))\n        return ndim",
    "docstring": "ndim inference and validation.\n\n        Infers ndim from 'values' if not provided to __init__.\n        Validates that values.ndim and ndim are consistent if and only if\n        the class variable '_validate_ndim' is True.\n\n        Parameters\n        ----------\n        values : array-like\n        ndim : int or None\n\n        Returns\n        -------\n        ndim : int\n\n        Raises\n        ------\n        ValueError : the number of dimensions do not match"
  },
  {
    "code": "def getTamilWords( tweet ):\n        tweet = TamilTweetParser.cleanupPunct( tweet );\n        nonETwords = filter( lambda x: len(x) > 0 , re.split(r'\\s+',tweet) );\n        tamilWords = filter( TamilTweetParser.isTamilPredicate, nonETwords );\n        return tamilWords",
    "docstring": "word needs to all be in the same tamil language"
  },
  {
    "code": "def _trim_dict_in_dict(data, max_val_size, replace_with):\n    for key in data:\n        if isinstance(data[key], dict):\n            _trim_dict_in_dict(data[key],\n                               max_val_size,\n                               replace_with)\n        else:\n            if sys.getsizeof(data[key]) > max_val_size:\n                data[key] = replace_with",
    "docstring": "Takes a dictionary, max_val_size and replace_with\n    and recursively loops through and replaces any values\n    that are greater than max_val_size."
  },
  {
    "code": "def _submatch(self, node, results=None):\n        if self.wildcards:\n            for c, r in generate_matches(self.content, node.children):\n                if c == len(node.children):\n                    if results is not None:\n                        results.update(r)\n                    return True\n            return False\n        if len(self.content) != len(node.children):\n            return False\n        for subpattern, child in zip(self.content, node.children):\n            if not subpattern.match(child, results):\n                return False\n        return True",
    "docstring": "Match the pattern's content to the node's children.\n\n        This assumes the node type matches and self.content is not None.\n\n        Returns True if it matches, False if not.\n\n        If results is not None, it must be a dict which will be\n        updated with the nodes matching named subpatterns.\n\n        When returning False, the results dict may still be updated."
  },
  {
    "code": "def decrypt(data, digest=True):\n    alg, _, data = data.rpartition(\"$\")\n    if not alg:\n        return data\n    data = _from_hex_digest(data) if digest else data\n    try:\n        return implementations[\"decryption\"][alg](\n            data, implementations[\"get_key\"]()\n        )\n    except KeyError:\n        raise CryptError(\"Can not decrypt key for algorithm: %s\" % alg)",
    "docstring": "Decrypt provided data."
  },
  {
    "code": "def invoke(self, function_name, raw_python=False, command=None, no_color=False):\n        key = command if command is not None else 'command'\n        if raw_python:\n            command = {'raw_command': function_name}\n        else:\n            command = {key: function_name}\n        import json as json\n        response = self.zappa.invoke_lambda_function(\n            self.lambda_name,\n            json.dumps(command),\n            invocation_type='RequestResponse',\n        )\n        if 'LogResult' in response:\n            if no_color:\n                print(base64.b64decode(response['LogResult']))\n            else:\n                decoded = base64.b64decode(response['LogResult']).decode()\n                formatted = self.format_invoke_command(decoded)\n                colorized = self.colorize_invoke_command(formatted)\n                print(colorized)\n        else:\n            print(response)\n        if 'FunctionError' in response:\n            raise ClickException(\n                \"{} error occurred while invoking command.\".format(response['FunctionError'])\n)",
    "docstring": "Invoke a remote function."
  },
  {
    "code": "def correctly_signed_response(self, decoded_xml, must=False, origdoc=None, only_valid_cert=False, require_response_signature=False, **kwargs):\n        response = samlp.any_response_from_string(decoded_xml)\n        if not response:\n            raise TypeError('Not a Response')\n        if response.signature:\n            if 'do_not_verify' in kwargs:\n                pass\n            else:\n                self._check_signature(decoded_xml, response,\n                                      class_name(response), origdoc)\n        elif require_response_signature:\n            raise SignatureError('Signature missing for response')\n        return response",
    "docstring": "Check if a instance is correctly signed, if we have metadata for\n        the IdP that sent the info use that, if not use the key that are in\n        the message if any.\n\n        :param decoded_xml: The SAML message as a XML string\n        :param must: Whether there must be a signature\n        :param origdoc:\n        :param only_valid_cert:\n        :param require_response_signature:\n        :return: None if the signature can not be verified otherwise an instance"
  },
  {
    "code": "def call_me(iocb):\n    if _debug: call_me._debug(\"callback_function %r\", iocb)\n    print(\"call me, %r or %r\" % (iocb.ioResponse, iocb.ioError))",
    "docstring": "When a controller completes the processing of a request, \n    the IOCB can contain one or more functions to be called."
  },
  {
    "code": "def set_field_value(document_data, field_path, value):\n    current = document_data\n    for element in field_path.parts[:-1]:\n        current = current.setdefault(element, {})\n    if value is _EmptyDict:\n        value = {}\n    current[field_path.parts[-1]] = value",
    "docstring": "Set a value into a document for a field_path"
  },
  {
    "code": "def distance(self, other):\n        return distance(self.lat, self.lon, None, other.lat, other.lon, None)",
    "docstring": "Distance between points\n\n        Args:\n            other (:obj:`Point`)\n        Returns:\n            float: Distance in km"
  },
  {
    "code": "def _improve_class_docs(app, cls, lines):\n    if issubclass(cls, models.Model):\n        _add_model_fields_as_params(app, cls, lines)\n    elif issubclass(cls, forms.Form):\n        _add_form_fields(cls, lines)",
    "docstring": "Improve the documentation of a class."
  },
  {
    "code": "def json_expand(json_op):\n    if type(json_op) == dict and 'json' in json_op:\n        return update_in(json_op, ['json'], safe_json_loads)\n    return json_op",
    "docstring": "For custom_json ops."
  },
  {
    "code": "def get_ituz(self, callsign, timestamp=timestamp_now):\n        return self.get_all(callsign, timestamp)[const.ITUZ]",
    "docstring": "Returns ITU Zone of a callsign\n\n        Args:\n            callsign (str): Amateur Radio callsign\n            timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)\n\n        Returns:\n            int: containing the callsign's CQ Zone\n\n        Raises:\n            KeyError: No ITU Zone found for callsign\n\n        Note:\n            Currently, only Country-files.com lookup database contains ITU Zones"
  },
  {
    "code": "def setStyle(self, stylename):\n        self.style = importlib.import_module(stylename)\n        newHandler = Handler()\n        newHandler.setFormatter(Formatter(self.style))\n        self.addHandler(newHandler)",
    "docstring": "Adjusts the output format of messages based on the style name provided\n\n        Styles are loaded like python modules, so you can import styles from your own modules or use the ones in fastlog.styles\n\n        Available styles can be found under /fastlog/styles/\n\n        The default style is 'fastlog.styles.pwntools'"
  },
  {
    "code": "def _fix_review_dates(self, item):\n        for date_field in ['timestamp', 'createdOn', 'lastUpdated']:\n            if date_field in item.keys():\n                date_ts = item[date_field]\n                item[date_field] = unixtime_to_datetime(date_ts).isoformat()\n        if 'patchSets' in item.keys():\n            for patch in item['patchSets']:\n                pdate_ts = patch['createdOn']\n                patch['createdOn'] = unixtime_to_datetime(pdate_ts).isoformat()\n                if 'approvals' in patch:\n                    for approval in patch['approvals']:\n                        adate_ts = approval['grantedOn']\n                        approval['grantedOn'] = unixtime_to_datetime(adate_ts).isoformat()\n        if 'comments' in item.keys():\n            for comment in item['comments']:\n                cdate_ts = comment['timestamp']\n                comment['timestamp'] = unixtime_to_datetime(cdate_ts).isoformat()",
    "docstring": "Convert dates so ES detect them"
  },
  {
    "code": "def vars_(self):\n        return [x for x in self[self.current_scope].values() if x.class_ == CLASS.var]",
    "docstring": "Returns symbol instances corresponding to variables\n        of the current scope."
  },
  {
    "code": "def _get_hanging_wall_coeffs_rx(self, C, rup, r_x):\n        r_1 = rup.width * cos(radians(rup.dip))\n        r_2 = 62.0 * rup.mag - 350.0\n        fhngrx = np.zeros(len(r_x))\n        idx = np.logical_and(r_x >= 0., r_x < r_1)\n        fhngrx[idx] = self._get_f1rx(C, r_x[idx], r_1)\n        idx = r_x >= r_1\n        f2rx = self._get_f2rx(C, r_x[idx], r_1, r_2)\n        f2rx[f2rx < 0.0] = 0.0\n        fhngrx[idx] = f2rx\n        return fhngrx",
    "docstring": "Returns the hanging wall r-x caling term defined in equation 7 to 12"
  },
  {
    "code": "def setup(self, url, stream=True, post=False, parameters=None, timeout=None):\n        self.close_response()\n        self.response = None\n        try:\n            if post:\n                full_url, parameters = self.get_url_params_for_post(url, parameters)\n                self.response = self.session.post(full_url, data=parameters, stream=stream, timeout=timeout)\n            else:\n                self.response = self.session.get(self.get_url_for_get(url, parameters), stream=stream, timeout=timeout)\n            self.response.raise_for_status()\n        except Exception as e:\n            raisefrom(DownloadError, 'Setup of Streaming Download of %s failed!' % url, e)\n        return self.response",
    "docstring": "Setup download from provided url returning the response\n\n        Args:\n            url (str): URL to download\n            stream (bool): Whether to stream download. Defaults to True.\n            post (bool): Whether to use POST instead of GET. Defaults to False.\n            parameters (Optional[Dict]): Parameters to pass. Defaults to None.\n            timeout (Optional[float]): Timeout for connecting to URL. Defaults to None (no timeout).\n\n        Returns:\n            requests.Response: requests.Response object"
  },
  {
    "code": "def reassign_authorization_to_vault(self, authorization_id, from_vault_id, to_vault_id):\n        self.assign_authorization_to_vault(authorization_id, to_vault_id)\n        try:\n            self.unassign_authorization_from_vault(authorization_id, from_vault_id)\n        except:\n            self.unassign_authorization_from_vault(authorization_id, to_vault_id)\n            raise",
    "docstring": "Moves an ``Authorization`` from one ``Vault`` to another.\n\n        Mappings to other ``Vaults`` are unaffected.\n\n        arg:    authorization_id (osid.id.Id): the ``Id`` of the\n                ``Authorization``\n        arg:    from_vault_id (osid.id.Id): the ``Id`` of the current\n                ``Vault``\n        arg:    to_vault_id (osid.id.Id): the ``Id`` of the destination\n                ``Vault``\n        raise:  NotFound - ``authorization_id, from_vault_id,`` or\n                ``to_vault_id`` not found or ``authorization_id`` not\n                mapped to ``from_vault_id``\n        raise:  NullArgument - ``authorization_id, from_vault_id,`` or\n                ``to_vault_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def missing_count(self):\n        if self.means:\n            return self.means.missing_count\n        return self._cube_dict[\"result\"].get(\"missing\", 0)",
    "docstring": "numeric representing count of missing rows in cube response."
  },
  {
    "code": "def _repr_html_(self):\n        out=\"<table class='taqltable'>\\n\"\n        if not(self.name()[:4]==\"Col_\"):\n            out+=\"<tr>\"\n            out+=\"<th><b>\"+self.name()+\"</b></th>\"\n            out+=\"</tr>\"\n        cropped=False\n        rowcount=0\n        colkeywords=self.getkeywords()\n        for row in self:\n            out +=\"\\n<tr>\"\n            out += \"<td>\" + _format_cell(row, colkeywords) + \"</td>\\n\"\n            out += \"</tr>\\n\"\n            rowcount+=1\n            out+=\"\\n\"\n            if rowcount>=20:\n                cropped=True\n                break\n        if out[-2:]==\"\\n\\n\":\n            out=out[:-1]\n        out+=\"</table>\"\n        if cropped:\n            out+=\"<p style='text-align:center'>(\"+str(self.nrows()-20)+\" more rows)</p>\\n\"\n        return out",
    "docstring": "Give a nice representation of columns in notebooks."
  },
  {
    "code": "def xidz(numerator, denominator, value_if_denom_is_zero):\n    small = 1e-6\n    if abs(denominator) < small:\n        return value_if_denom_is_zero\n    else:\n        return numerator * 1.0 / denominator",
    "docstring": "Implements Vensim's XIDZ function.\n    This function executes a division, robust to denominator being zero.\n    In the case of zero denominator, the final argument is returned.\n\n    Parameters\n    ----------\n    numerator: float\n    denominator: float\n        Components of the division operation\n    value_if_denom_is_zero: float\n        The value to return if the denominator is zero\n\n    Returns\n    -------\n    numerator / denominator if denominator > 1e-6\n    otherwise, returns value_if_denom_is_zero"
  },
  {
    "code": "def all_subclasses(cls):\n    subclasses = cls.__subclasses__() \n    return subclasses + [g for s in subclasses for g in all_subclasses(s)]",
    "docstring": "Given a class `cls`, this recursive function returns a list with\n    all subclasses, subclasses of subclasses, and so on."
  },
  {
    "code": "def start_volume(name, force=False):\n    cmd = 'volume start {0}'.format(name)\n    if force:\n        cmd = '{0} force'.format(cmd)\n    volinfo = info(name)\n    if name not in volinfo:\n        log.error(\"Cannot start non-existing volume %s\", name)\n        return False\n    if not force and volinfo[name]['status'] == '1':\n        log.info(\"Volume %s already started\", name)\n        return True\n    return _gluster(cmd)",
    "docstring": "Start a gluster volume\n\n    name\n        Volume name\n\n    force\n        Force the volume start even if the volume is started\n        .. versionadded:: 2015.8.4\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' glusterfs.start mycluster"
  },
  {
    "code": "def copy_folder_content(src, dst):\n    for file in os.listdir(src):\n        file_path = os.path.join(src, file)\n        dst_file_path = os.path.join(dst, file)\n        if os.path.isdir(file_path):\n            shutil.copytree(file_path, dst_file_path)\n        else:\n            shutil.copyfile(file_path, dst_file_path)",
    "docstring": "Copy all content in src directory to dst directory.\n    The src and dst must exist."
  },
  {
    "code": "def gen_lines_from_binary_files(\n        files: Iterable[BinaryIO],\n        encoding: str = UTF8) -> Generator[str, None, None]:\n    for file in files:\n        for byteline in file:\n            line = byteline.decode(encoding).strip()\n            yield line",
    "docstring": "Generates lines from binary files.\n    Strips out newlines.\n\n    Args:\n        files: iterable of :class:`BinaryIO` file-like objects\n        encoding: encoding to use\n\n    Yields:\n        each line of all the files"
  },
  {
    "code": "def purge_all(user=None, fast=False):\n    user = user or getpass.getuser()\n    if os.path.exists(datadir):\n        if fast:\n            shutil.rmtree(datadir)\n            print('Removed %s' % datadir)\n        else:\n            for fname in os.listdir(datadir):\n                mo = re.match('calc_(\\d+)\\.hdf5', fname)\n                if mo is not None:\n                    calc_id = int(mo.group(1))\n                    purge_one(calc_id, user)",
    "docstring": "Remove all calculations of the given user"
  },
  {
    "code": "def rollforward(self, date):\n        if self.onOffset(date):\n            return date\n        else:\n            return date + QuarterBegin(month=self.month)",
    "docstring": "Roll date forward to nearest start of quarter"
  },
  {
    "code": "def deep_merge_dict(a, b):\n    if not isinstance(a, dict):\n        raise TypeError(\"a must be a dict, but found %s\" % a.__class__.__name__)\n    if not isinstance(b, dict):\n        raise TypeError(\"b must be a dict, but found %s\" % b.__class__.__name__)\n    _a = copy(a)\n    _b = copy(b)\n    for key_b, val_b in iteritems(_b):\n        if isinstance(val_b, dict):\n            if key_b not in _a or not isinstance(_a[key_b], dict):\n                _a[key_b] = {}\n            _a[key_b] = deep_merge_dict(_a[key_b], val_b)\n        else:\n            _a[key_b] = val_b\n    return _a",
    "docstring": "Deep merges dictionary b into dictionary a."
  },
  {
    "code": "def run_command(self, data):\n        command = data.get(\"command\")\n        if self.debug:\n            self.py3_wrapper.log(\"Running remote command %s\" % command)\n        if command == \"refresh\":\n            self.refresh(data)\n        elif command == \"refresh_all\":\n            self.py3_wrapper.refresh_modules()\n        elif command == \"click\":\n            self.click(data)",
    "docstring": "check the given command and send to the correct dispatcher"
  },
  {
    "code": "def SetFields(fields):\n    @use_context\n    @use_no_input\n    def _SetFields(context):\n        nonlocal fields\n        if not context.output_type:\n            context.set_output_fields(fields)\n        return NOT_MODIFIED\n    return _SetFields",
    "docstring": "Transformation factory that sets the field names on first iteration, without touching the values.\n\n    :param fields:\n    :return: callable"
  },
  {
    "code": "def UpdateNumberOfWarnings(\n      self, number_of_consumed_warnings, number_of_produced_warnings):\n    consumed_warnings_delta = 0\n    if number_of_consumed_warnings is not None:\n      if number_of_consumed_warnings < self.number_of_consumed_warnings:\n        raise ValueError(\n            'Number of consumed warnings smaller than previous update.')\n      consumed_warnings_delta = (\n          number_of_consumed_warnings - self.number_of_consumed_warnings)\n      self.number_of_consumed_warnings = number_of_consumed_warnings\n      self.number_of_consumed_warnings_delta = consumed_warnings_delta\n    produced_warnings_delta = 0\n    if number_of_produced_warnings is not None:\n      if number_of_produced_warnings < self.number_of_produced_warnings:\n        raise ValueError(\n            'Number of produced warnings smaller than previous update.')\n      produced_warnings_delta = (\n          number_of_produced_warnings - self.number_of_produced_warnings)\n      self.number_of_produced_warnings = number_of_produced_warnings\n      self.number_of_produced_warnings_delta = produced_warnings_delta\n    return consumed_warnings_delta > 0 or produced_warnings_delta > 0",
    "docstring": "Updates the number of warnings.\n\n    Args:\n      number_of_consumed_warnings (int): total number of warnings consumed by\n          the process.\n      number_of_produced_warnings (int): total number of warnings produced by\n          the process.\n\n    Returns:\n      bool: True if either number of warnings has increased.\n\n    Raises:\n      ValueError: if the consumed or produced number of warnings is smaller\n          than the value of the previous update."
  },
  {
    "code": "def reference_axis_from_chains(chains):\n    if not len(set([len(x) for x in chains])) == 1:\n        raise ValueError(\"All chains must be of the same length\")\n    coords = [numpy.array(chains[0].primitive.coordinates)]\n    orient_vector = polypeptide_vector(chains[0])\n    for i, c in enumerate(chains[1:]):\n        if is_acute(polypeptide_vector(c), orient_vector):\n            coords.append(numpy.array(c.primitive.coordinates))\n        else:\n            coords.append(numpy.flipud(numpy.array(c.primitive.coordinates)))\n    reference_axis = numpy.mean(numpy.array(coords), axis=0)\n    return Primitive.from_coordinates(reference_axis)",
    "docstring": "Average coordinates from a set of primitives calculated from Chains.\n\n    Parameters\n    ----------\n    chains : list(Chain)\n\n    Returns\n    -------\n    reference_axis : numpy.array\n        The averaged (x, y, z) coordinates of the primitives for\n        the list of Chains. In the case of a coiled coil barrel,\n        this would give the central axis for calculating e.g. Crick\n        angles.\n\n    Raises\n    ------\n    ValueError :\n        If the Chains are not all of the same length."
  },
  {
    "code": "def recursive_copy(source, destination):\n    if os.path.isdir(source):\n        copy_tree(source, destination)",
    "docstring": "A wrapper around distutils.dir_util.copy_tree but won't throw any exception when the source\n    directory does not exist.\n\n    Args:\n        source (str): source path\n        destination (str): destination path"
  },
  {
    "code": "def _refreshNodeFromTarget(self):\n        for key, value in self.viewBox.state.items():\n            if key != \"limits\":\n                childItem = self.childByNodeName(key)\n                childItem.data = value\n            else:\n                for limitKey, limitValue in value.items():\n                    limitChildItem = self.limitsItem.childByNodeName(limitKey)\n                    limitChildItem.data = limitValue",
    "docstring": "Updates the config settings"
  },
  {
    "code": "def retrieve_product(self, product_id):\n        response = self.request(E.retrieveProductSslCertRequest(\n            E.id(product_id)\n        ))\n        return response.as_model(SSLProduct)",
    "docstring": "Retrieve details on a single product."
  },
  {
    "code": "def check_mod_enabled(mod):\n    if mod.endswith('.load') or mod.endswith('.conf'):\n        mod_name = mod[:-5]\n    else:\n        mod_name = mod\n    cmd = 'a2enmod -l'\n    try:\n        active_mods = __salt__['cmd.run'](cmd, python_shell=False).split(' ')\n    except Exception as e:\n        return e\n    return mod_name in active_mods",
    "docstring": "Checks to see if the specific apache mod is enabled.\n\n    This will only be functional on operating systems that support\n    `a2enmod -l` to list the enabled mods.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' apache.check_mod_enabled status"
  },
  {
    "code": "def check_validation_level(validation_level):\n    if validation_level not in (VALIDATION_LEVEL.QUIET, VALIDATION_LEVEL.STRICT, VALIDATION_LEVEL.TOLERANT):\n        raise UnknownValidationLevel",
    "docstring": "Validate the given validation level\n\n    :type validation_level: ``int``\n    :param validation_level: validation level (see :class:`hl7apy.consts.VALIDATION_LEVEL`)\n    :raises: :exc:`hl7apy.exceptions.UnknownValidationLevel` if the given validation level is unsupported"
  },
  {
    "code": "def model_info(model_dir: Optional[str] = None) -> Tuple[str, bool]:\n    if model_dir is None:\n        try:\n            model_dir = resource_filename(PACKAGE, DATADIR.format('model'))\n        except DistributionNotFound as error:\n            LOGGER.warning(\"Cannot load model from packages: %s\", error)\n            model_dir = str(DATA_FALLBACK.joinpath('model').absolute())\n        is_default_model = True\n    else:\n        is_default_model = False\n    model_path = Path(model_dir)\n    model_path.mkdir(exist_ok=True)\n    LOGGER.debug(\"Using model: %s, default: %s\", model_path, is_default_model)\n    return (model_dir, is_default_model)",
    "docstring": "Retrieve Guesslang model directory name,\n    and tells if it is the default model.\n\n    :param model_dir: model location, if `None` default model is selected\n    :return: selected model directory with an indication\n        that the model is the default or not"
  },
  {
    "code": "def best_parent( self, node, tree_type=None ):\n        parents = self.parents(node)\n        selected_parent = None\n        if node['type'] == 'type':\n            module = \".\".join( node['name'].split( '.' )[:-1] )\n            if module:\n                for mod in parents:\n                    if mod['type'] == 'module' and mod['name'] == module:\n                        selected_parent = mod \n        if parents and selected_parent is None:\n            parents.sort( key = lambda x: self.value(node, x) )\n            return parents[-1]\n        return selected_parent",
    "docstring": "Choose the best parent for a given node"
  },
  {
    "code": "def _logpdf(self, **kwargs):\n        return self._polardist._logpdf(**kwargs) +\\\n            self._azimuthaldist._logpdf(**kwargs)",
    "docstring": "Returns the logpdf at the given angles.\n\n        Parameters\n        ----------\n        \\**kwargs:\n            The keyword arguments should specify the value for each angle,\n            using the names of the polar and azimuthal angles as the keywords.\n            Unrecognized arguments are ignored.\n\n        Returns\n        -------\n        float\n            The value of the pdf at the given values."
  },
  {
    "code": "def _init_login_manager(app_):\n    login_manager = flogin.LoginManager()\n    login_manager.setup_app(app_)\n    login_manager.anonymous_user = Anonymous\n    login_manager.login_view = \"login\"\n    users = {app_.config['USERNAME']: User('Admin', 0)}\n    names = dict((int(v.get_id()), k) for k, v in users.items())\n    @login_manager.user_loader\n    def load_user(userid):\n        userid = int(userid)\n        name = names.get(userid)\n        return users.get(name)\n    return users, names",
    "docstring": "Initialise and configure the login manager."
  },
  {
    "code": "def add_primitives_path(path):\n    if path not in _PRIMITIVES_PATHS:\n        if not os.path.isdir(path):\n            raise ValueError('Invalid path: {}'.format(path))\n        LOGGER.debug('Adding new primitives path %s', path)\n        _PRIMITIVES_PATHS.insert(0, os.path.abspath(path))",
    "docstring": "Add a new path to look for primitives.\n\n    The new path will be inserted in the first place of the list,\n    so any primitive found in this new folder will take precedence\n    over any other primitive with the same name that existed in the\n    system before.\n\n    Args:\n        path (str): path to add\n\n    Raises:\n        ValueError: A `ValueError` will be raised if the path is not valid."
  },
  {
    "code": "def pathconf(path,\n             os_name=os.name,\n             isdir_fnc=os.path.isdir,\n             pathconf_fnc=getattr(os, 'pathconf', None),\n             pathconf_names=getattr(os, 'pathconf_names', ())):\n    if pathconf_fnc and pathconf_names:\n        return {key: pathconf_fnc(path, key) for key in pathconf_names}\n    if os_name == 'nt':\n        maxpath = 246 if isdir_fnc(path) else 259\n    else:\n        maxpath = 255\n    return {\n        'PC_PATH_MAX': maxpath,\n        'PC_NAME_MAX': maxpath - len(path),\n        }",
    "docstring": "Get all pathconf variables for given path.\n\n    :param path: absolute fs path\n    :type path: str\n    :returns: dictionary containing pathconf keys and their values (both str)\n    :rtype: dict"
  },
  {
    "code": "def _process_items(items, user_conf, error_protocol):\n    def process_meta(item, error_protocol):\n        try:\n            return item._parse()\n        except Exception, e:\n            error_protocol.append(\n                \"Can't parse %s: %s\" % (item._get_filenames()[0], e.message)\n            )\n            if isinstance(item, DataPair):\n                return item.ebook_file\n    out = []\n    for item in items:\n        if isinstance(item, EbookFile):\n            out.append(item)\n        else:\n            out.append(process_meta(item, error_protocol))\n    out = filter(lambda x: x, out)\n    fn_pool = []\n    soon_removed = out if conf_merger(user_conf, \"LEAVE_BAD_FILES\") else items\n    for item in soon_removed:\n        fn_pool.extend(item._get_filenames())\n    _remove_files(fn_pool)\n    return out",
    "docstring": "Parse metadata. Remove processed and sucessfully parsed items.\n\n    Returns sucessfully processed items."
  },
  {
    "code": "def load(self, path, name=None):\n        if name is None:\n            name = os.path.splitext(os.path.basename(path))[0]\n        with open(path, 'r') as f:\n            document = f.read()\n        return self.compiler.compile(name, document, path).link().surface",
    "docstring": "Load and compile the given Thrift file.\n\n        :param str path:\n            Path to the ``.thrift`` file.\n        :param str name:\n            Name of the generated module. Defaults to the base name of the\n            file.\n        :returns:\n            The compiled module."
  },
  {
    "code": "def get_nearest_site(self, latitude=None,  longitude=None):\n        warning_message = 'This function is deprecated. Use get_nearest_forecast_site() instead'\n        warn(warning_message, DeprecationWarning, stacklevel=2)\n        return self.get_nearest_forecast_site(latitude, longitude)",
    "docstring": "Deprecated. This function returns nearest Site object to the specified\n        coordinates."
  },
  {
    "code": "def array_controllers(self):\n        return array_controller.HPEArrayControllerCollection(\n            self._conn, utils.get_subresource_path_by(\n                self, ['Links', 'ArrayControllers']),\n            redfish_version=self.redfish_version)",
    "docstring": "This property gets the list of instances for array controllers\n\n        This property gets the list of instances for array controllers\n        :returns: a list of instances of array controllers."
  },
  {
    "code": "def set_row_name(self, index, name):\n        javabridge.call(self.jobject, \"setRowName\", \"(ILjava/lang/String;)V\", index, name)",
    "docstring": "Sets the row name.\n\n        :param index: the 0-based row index\n        :type index: int\n        :param name: the name of the row\n        :type name: str"
  },
  {
    "code": "def _terminal_notifier(title, message):\n    try:\n        paths = common.extract_app_paths(['terminal-notifier'])\n    except ValueError:\n        pass\n    common.shell_process([paths[0], '-title', title, '-message', message])",
    "docstring": "Shows user notification message via `terminal-notifier` command.\n\n        `title`\n            Notification title.\n        `message`\n            Notification message."
  },
  {
    "code": "def releaseLicense(self, username):\n        url = self._url + \"/licenses/releaseLicense\"\n        params = {\n            \"username\" : username,\n            \"f\" : \"json\"\n        }\n        return self._post(url=url,\n                          param_dict=params,\n                          proxy_url=self._proxy_url,\n                          proxy_port=self._proxy_port)",
    "docstring": "If a user checks out an ArcGIS Pro license for offline or\n        disconnected use, this operation releases the license for the\n        specified account. A license can only be used with a single device\n        running ArcGIS Pro. To check in the license, a valid access token\n        and refresh token is required. If the refresh token for the device\n        is lost, damaged, corrupted, or formatted, the user will not be\n        able to check in the license. This prevents the user from logging\n        in to ArcGIS Pro from any other device. As an administrator, you\n        can release the license. This frees the outstanding license and\n        allows the user to check out a new license or use ArcGIS Pro in a\n        connected environment.\n\n        Parameters:\n           username - username of  the account"
  },
  {
    "code": "def pip(self, cmd):\n        pip_bin = self.cmd_path('pip')\n        cmd = '{0} {1}'.format(pip_bin, cmd)\n        return self._execute(cmd)",
    "docstring": "Execute some pip function using the virtual environment pip."
  },
  {
    "code": "def shrink(self):\n        \"Get rid of one worker from the pool. Raises IndexError if empty.\"\n        if self._size <= 0:\n            raise IndexError(\"pool is already empty\")\n        self._size -= 1\n        self.put(SuicideJob())",
    "docstring": "Get rid of one worker from the pool. Raises IndexError if empty."
  },
  {
    "code": "def read1(self, size=-1):\n        self._check_can_read()\n        if size is None:\n            raise TypeError(\"Read size should be an integer, not None\")\n        if (size == 0 or self._mode == _MODE_READ_EOF or\n            not self._fill_buffer()):\n            return b\"\"\n        if 0 < size < len(self._buffer):\n            data = self._buffer[:size]\n            self._buffer = self._buffer[size:]\n        else:\n            data = self._buffer\n            self._buffer = None\n        self._pos += len(data)\n        return data",
    "docstring": "Read up to size uncompressed bytes, while trying to avoid\n        making multiple reads from the underlying stream.\n\n        Returns b\"\" if the file is at EOF."
  },
  {
    "code": "def save_libsvm(X, y, path):\n    dump_svmlight_file(X, y, path, zero_based=False)",
    "docstring": "Save data as a LibSVM file.\n\n    Args:\n        X (numpy or scipy sparse matrix): Data matrix\n        y (numpy array): Target vector.\n        path (str): Path to the CSV file to save data."
  },
  {
    "code": "def _pass_list(self) -> List[Dict[str, Any]]:\n        stops: List[Dict[str, Any]] = []\n        for stop in self.journey.PassList.BasicStop:\n            index = stop.get(\"index\")\n            station = stop.Location.Station.HafasName.Text.text\n            station_id = stop.Location.Station.ExternalId.text\n            stops.append({\"index\": index, \"stationId\": station_id, \"station\": station})\n        return stops",
    "docstring": "Extract next stops along the journey."
  },
  {
    "code": "def sign(hash,priv,k=0):\n    if k == 0:\n        k = generate_k(priv, hash)\n    hash = int(hash,16)\n    priv = int(priv,16)\n    r = int(privtopub(dechex(k,32),True)[2:],16) % N\n    s = ((hash + (r*priv)) * modinv(k,N)) % N\n    if s > (N / 2):\n        s = N - s\n    r, s = inttoDER(r), inttoDER(s)\n    olen = dechex(len(r+s)//2,1)\n    return '30' + olen + r + s",
    "docstring": "Returns a DER-encoded signature from a input of a hash and private\n    key, and optionally a K value.\n\n    Hash and private key inputs must be 64-char hex strings,\n    k input is an int/long.\n\n    >>> h = 'f7011e94125b5bba7f62eb25efe23339eb1637539206c87df3ee61b5ec6b023e'\n    >>> p = 'c05694a7af0e01dceb63e5912a415c28d3fc823ca1fd3fa34d41afde03740466'\n    >>> k = 4 # chosen by fair dice roll, guaranteed to be random\n    >>> sign(h,p,k)\n    '3045022100e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd130220598e37e2e66277ef4d0caf0e32d095debb3c744219508cd394b9747e548662b7'"
  },
  {
    "code": "def try_one_generator_really (project, name, generator, target_type, properties, sources):\n    if __debug__:\n        from .targets import ProjectTarget\n        assert isinstance(project, ProjectTarget)\n        assert isinstance(name, basestring) or name is None\n        assert isinstance(generator, Generator)\n        assert isinstance(target_type, basestring)\n        assert isinstance(properties, property_set.PropertySet)\n        assert is_iterable_typed(sources, virtual_target.VirtualTarget)\n    targets = generator.run (project, name, properties, sources)\n    usage_requirements = []\n    success = False\n    dout(\"returned \" + str(targets))\n    if targets:\n        success = True;\n        if isinstance (targets[0], property_set.PropertySet):\n            usage_requirements = targets [0]\n            targets = targets [1]\n        else:\n            usage_requirements = property_set.empty ()\n    dout(  \"  generator\" + generator.id() + \" spawned \")\n    if success:\n        return (usage_requirements, targets)\n    else:\n        return None",
    "docstring": "Returns usage requirements + list of created targets."
  },
  {
    "code": "def parse_values_from_lines(self,lines):\n        assert len(lines) == 3,\"SvdData.parse_values_from_lines: expected \" + \\\n                               \"3 lines, not {0}\".format(len(lines))\n        try:\n            self.svdmode = int(lines[0].strip().split()[0])\n        except Exception as e:\n            raise Exception(\"SvdData.parse_values_from_lines: error parsing\" + \\\n                            \" svdmode from line {0}: {1} \\n\".format(lines[0],str(e)))\n        try:\n            raw = lines[1].strip().split()\n            self.maxsing = int(raw[0])\n            self.eigthresh = float(raw[1])\n        except Exception as e:\n            raise Exception(\"SvdData.parse_values_from_lines: error parsing\" + \\\n                            \" maxsing and eigthresh from line {0}: {1} \\n\"\\\n                            .format(lines[1],str(e)))\n        self.eigwrite = lines[2].strip()",
    "docstring": "parse values from lines of the SVD section\n\n        Parameters\n        ----------\n        lines : list"
  },
  {
    "code": "def save(self):\n        if not self.is_loaded and self.id is None or self.id == '':\n            data = self.resource.post(data=self.data, collection=self.collection)\n            self.id = data['_id']\n            self.key = data['_key']\n            self.revision = data['_rev']\n            self.is_loaded = True\n        else:\n            data = self.resource(self.id).patch(data=self.data)\n            self.revision = data['_rev']",
    "docstring": "If its internal state is loaded than it will only updated the\n            set properties but otherwise it will create a new document."
  },
  {
    "code": "def put(self, key, value):\n    self.shardDatastore(key).put(key, value)",
    "docstring": "Stores the object to the corresponding datastore."
  },
  {
    "code": "def assign_item_to_bank(self, item_id, bank_id):\n        mgr = self._get_provider_manager('ASSESSMENT', local=True)\n        lookup_session = mgr.get_bank_lookup_session(proxy=self._proxy)\n        lookup_session.get_bank(bank_id)\n        self._assign_object_to_catalog(item_id, bank_id)",
    "docstring": "Adds an existing ``Item`` to a ``Bank``.\n\n        arg:    item_id (osid.id.Id): the ``Id`` of the ``Item``\n        arg:    bank_id (osid.id.Id): the ``Id`` of the ``Bank``\n        raise:  AlreadyExists - ``item_id`` is already assigned to\n                ``bank_id``\n        raise:  NotFound - ``item_id`` or ``bank_id`` not found\n        raise:  NullArgument - ``item_id`` or ``bank_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def calculate_file_md5(filepath, blocksize=2 ** 20):\n    checksum = hashlib.md5()\n    with click.open_file(filepath, \"rb\") as f:\n        def update_chunk():\n            buf = f.read(blocksize)\n            if buf:\n                checksum.update(buf)\n            return bool(buf)\n        while update_chunk():\n            pass\n    return checksum.hexdigest()",
    "docstring": "Calculate an MD5 hash for a file."
  },
  {
    "code": "def update(self):\n        vehicle = self.api.vehicles(vid=self.vid)['vehicle']\n        newbus = self.fromapi(self.api, vehicle)\n        self.__dict__ = newbus.__dict__\n        del newbus",
    "docstring": "Update this bus by creating a new one and transplanting dictionaries."
  },
  {
    "code": "def team_scores(self, team_scores, time):\n        data = []\n        for score in team_scores['matches']:\n            if score['status'] == 'FINISHED':\n                item = {'date': score[\"utcDate\"].split('T')[0],\n                        'homeTeamName': score['homeTeam']['name'],\n                        'goalsHomeTeam': score['score']['fullTime']['homeTeam'],\n                        'goalsAwayTeam': score['score']['fullTime']['awayTeam'],\n                        'awayTeamName': score['awayTeam']['name']}\n                data.append(item)\n        self.generate_output({'team_scores': data})",
    "docstring": "Store output of team scores to a JSON file"
  },
  {
    "code": "def integrate(ii, r0, c0, r1, c1):\n    S = np.zeros(ii.shape[-1])\n    S += ii[r1, c1]\n    if (r0 - 1 >= 0) and (c0 - 1 >= 0):\n        S += ii[r0 - 1, c0 - 1]\n    if (r0 - 1 >= 0):\n        S -= ii[r0 - 1, c1]\n    if (c0 - 1 >= 0):\n        S -= ii[r1, c0 - 1]\n    return S",
    "docstring": "Use an integral image to integrate over a given window.\n\n    Parameters\n    ----------\n    ii : ndarray\n        Integral image.\n    r0, c0 : int\n        Top-left corner of block to be summed.\n    r1, c1 : int\n        Bottom-right corner of block to be summed.\n\n    Returns\n    -------\n    S : int\n        Integral (sum) over the given window."
  },
  {
    "code": "def inquire(self):\n        status, nRecs, interlace, fldNames, size, vName = \\\n                _C.VSinquire(self._id)\n        _checkErr('inquire', status, \"cannot query vdata info\")\n        return nRecs, interlace, fldNames.split(','), size, vName",
    "docstring": "Retrieve info about the vdata.\n\n        Args::\n\n          no argument\n\n        Returns::\n\n          5-element tuple with the following elements:\n            -number of records in the vdata\n            -interlace mode\n            -list of vdata field names\n            -size in bytes of the vdata record\n            -name of the vdata\n\n        C library equivalent : VSinquire"
  },
  {
    "code": "def float_str(value, symbol_str=\"\", symbol_value=1, after=False,\n              max_denominator=1000000):\n  if value == 0:\n    return \"0\"\n  frac = Fraction(value/symbol_value).limit_denominator(max_denominator)\n  num, den = frac.numerator, frac.denominator\n  output_data = []\n  if num < 0:\n    num = -num\n    output_data.append(\"-\")\n  if (num != 1) or (symbol_str == \"\") or after:\n    output_data.append(str(num))\n  if (value != 0) and not after:\n    output_data.append(symbol_str)\n  if den != 1:\n    output_data.extend([\"/\", str(den)])\n  if after:\n    output_data.append(symbol_str)\n  return \"\".join(output_data)",
    "docstring": "Pretty rational string from float numbers.\n\n  Converts a given numeric value to a string based on rational fractions of\n  the given symbol, useful for labels in plots.\n\n  Parameters\n  ----------\n  value :\n    A float number or an iterable with floats.\n  symbol_str :\n    String data that will be in the output representing the data as a\n    numerator multiplier, if needed. Defaults to an empty string.\n  symbol_value :\n    The conversion value for the given symbol (e.g. pi = 3.1415...). Defaults\n    to one (no effect).\n  after :\n    Chooses the place where the ``symbol_str`` should be written. If ``True``,\n    that's the end of the string. If ``False``, that's in between the\n    numerator and the denominator, before the slash. Defaults to ``False``.\n  max_denominator :\n    An int instance, used to round the float following the given limit.\n    Defaults to the integer 1,000,000 (one million).\n\n  Returns\n  -------\n  A string with the rational number written into as a fraction, with or\n  without a multiplying symbol.\n\n  Examples\n  --------\n  >>> float_str.frac(12.5)\n  '25/2'\n  >>> float_str.frac(0.333333333333333)\n  '1/3'\n  >>> float_str.frac(0.333)\n  '333/1000'\n  >>> float_str.frac(0.333, max_denominator=100)\n  '1/3'\n  >>> float_str.frac(0.125, symbol_str=\"steps\")\n  'steps/8'\n  >>> float_str.frac(0.125, symbol_str=\" Hz\",\n  ...                after=True) # The symbol includes whitespace!\n  '1/8 Hz'\n\n  See Also\n  --------\n  float_str.pi :\n    This fraction/ratio formatter, but configured with the \"pi\" symbol."
  },
  {
    "code": "def FMErrorByNum( num ):\n    if not num in FMErrorNum.keys():\n        raise FMServerError, (num, FMErrorNum[-1])\n    elif num == 102:\n        raise FMFieldError, (num, FMErrorNum[num])\n    else:\n        raise FMServerError, (num, FMErrorNum[num])",
    "docstring": "This function raises an error based on the specified error code."
  },
  {
    "code": "def move_mouse_relative(self, x, y):\n        _libxdo.xdo_move_mouse_relative(self._xdo, x, y)",
    "docstring": "Move the mouse relative to it's current position.\n\n        :param x: the distance in pixels to move on the X axis.\n        :param y: the distance in pixels to move on the Y axis."
  },
  {
    "code": "def parse_response(self, raw):\n        tables = raw.json()['tables']\n        crit = raw.json()['criteria_map']\n        return self.parse(tables, crit)",
    "docstring": "Format the requested data model into a dictionary of DataFrames\n        and a criteria map DataFrame.\n        Take data returned by a requests.get call to Earthref.\n\n        Parameters\n        ----------\n        raw: 'requests.models.Response'\n\n        Returns\n        ---------\n        data_model : dictionary of DataFrames\n        crit_map : DataFrame"
  },
  {
    "code": "def iter_fasta(file_path):\n    fh = open(file_path)\n    faiter = (x[1] for x in groupby(fh, lambda line: line[0] == \">\"))\n    for header in faiter:\n        headerStr = header.__next__()[1:].strip()\n        seq = \"\".join(s.strip() for s in faiter.__next__())\n        yield (headerStr, seq)",
    "docstring": "Returns an iterator over the fasta file\n\n    Given a fasta file. yield tuples of header, sequence\n\n    Code modified from Brent Pedersen's:\n    \"Correct Way To Parse A Fasta File In Python\"\n\n\n    # Example\n\n        ```python\n            fasta = fasta_iter(\"hg19.fa\")\n            for header, seq in fasta:\n               print(header)\n        ```"
  },
  {
    "code": "def edge(self, tail_name, head_name, label=None, _attributes=None, **attrs):\n        tail_name = self._quote_edge(tail_name)\n        head_name = self._quote_edge(head_name)\n        attr_list = self._attr_list(label, attrs, _attributes)\n        line = self._edge % (tail_name, head_name, attr_list)\n        self.body.append(line)",
    "docstring": "Create an edge between two nodes.\n\n        Args:\n            tail_name: Start node identifier.\n            head_name: End node identifier.\n            label: Caption to be displayed near the edge.\n            attrs: Any additional edge attributes (must be strings)."
  },
  {
    "code": "def keys_info(gandi, fqdn, key):\n    key_info = gandi.dns.keys_info(fqdn, key)\n    output_keys = ['uuid', 'algorithm', 'algorithm_name', 'ds', 'fingerprint',\n                   'public_key', 'flags', 'tag', 'status']\n    output_generic(gandi, key_info, output_keys, justify=15)\n    return key_info",
    "docstring": "Display information about a domain key."
  },
  {
    "code": "def jsonFn(self, comic):\n        fn = os.path.join(self.basepath, comic, 'dosage.json')\n        fn = os.path.abspath(fn)\n        return fn",
    "docstring": "Get filename for the JSON file for a comic."
  },
  {
    "code": "def check_sensors():\n    all_sensors = walk_data(sess, oid_description, helper)[0]\n    all_status = walk_data(sess, oid_status, helper)[0]\n    zipped = zip(all_sensors, all_status)\n    for sensor in zipped:\n        description = sensor[0]\n        status = sensor[1]\n        try:\n            status_string = senor_status_table[status]\n        except KeyError:\n            helper.exit(summary=\"received an undefined value from device: \" + status, exit_code=unknown, perfdata='')\n        helper.add_summary(\"%s: %s\" % (description, status_string))\n        if status == \"2\":\n            helper.status(critical)\n        if status == \"3\":\n            helper.status(warning)",
    "docstring": "collect and check all available sensors"
  },
  {
    "code": "def extract_tree_block(self):\n        \"iterate through data file to extract trees\"        \n        lines = iter(self.data)\n        while 1:\n            try:\n                line = next(lines).strip()\n            except StopIteration:\n                break\n            if line.lower() == \"begin trees;\":\n                while 1:\n                    sub = next(lines).strip().split()\n                    if not sub:\n                        continue\n                    if sub[0].lower() == \"translate\":\n                        while sub[0] != \";\":\n                            sub = next(lines).strip().split()\n                            self.tdict[sub[0]] = sub[-1].strip(\",\")\n                    if sub[0].lower().startswith(\"tree\"):\n                        self.newicks.append(sub[-1])\n                    if sub[0].lower() == \"end;\":\n                        break",
    "docstring": "iterate through data file to extract trees"
  },
  {
    "code": "def is_valid_mpls_label(label):\n    if (not isinstance(label, numbers.Integral) or\n            (4 <= label <= 15) or\n            (label < 0 or label > 2 ** 20)):\n        return False\n    return True",
    "docstring": "Validates `label` according to MPLS label rules\n\n    RFC says:\n    This 20-bit field.\n    A value of 0 represents the \"IPv4 Explicit NULL Label\".\n    A value of 1 represents the \"Router Alert Label\".\n    A value of 2 represents the \"IPv6 Explicit NULL Label\".\n    A value of 3 represents the \"Implicit NULL Label\".\n    Values 4-15 are reserved."
  },
  {
    "code": "def resolve_revision(self, dest, url, rev_options):\n        rev = rev_options.arg_rev\n        sha, is_branch = self.get_revision_sha(dest, rev)\n        if sha is not None:\n            rev_options = rev_options.make_new(sha)\n            rev_options.branch_name = rev if is_branch else None\n            return rev_options\n        if not looks_like_hash(rev):\n            logger.warning(\n                \"Did not find branch or tag '%s', assuming revision or ref.\",\n                rev,\n            )\n        if not rev.startswith('refs/'):\n            return rev_options\n        self.run_command(\n            ['fetch', '-q', url] + rev_options.to_args(),\n            cwd=dest,\n        )\n        sha = self.get_revision(dest, rev='FETCH_HEAD')\n        rev_options = rev_options.make_new(sha)\n        return rev_options",
    "docstring": "Resolve a revision to a new RevOptions object with the SHA1 of the\n        branch, tag, or ref if found.\n\n        Args:\n          rev_options: a RevOptions object."
  },
  {
    "code": "def info(self, message, *args, **kwargs):\n        self.system.info(message, *args, **kwargs)",
    "docstring": "Log info event.\n\n        Compatible with logging.info signature."
  },
  {
    "code": "def create_message(username, message):\r\n    message = message.replace('\\n', '<br/>')\r\n    return '{{\"service\":1, \"data\":{{\"message\":\"{mes}\", \"username\":\"{user}\"}} }}'.format(mes=message, user=username)",
    "docstring": "Creates a standard message from a given user with the message \r\n        Replaces newline with html break"
  },
  {
    "code": "def negociate_content(default='json-ld'):\n    mimetype = request.accept_mimetypes.best_match(ACCEPTED_MIME_TYPES.keys())\n    return ACCEPTED_MIME_TYPES.get(mimetype, default)",
    "docstring": "Perform a content negociation on the format given the Accept header"
  },
  {
    "code": "def handle_na(self, data):\n        return remove_missing(data,\n                              self.params['na_rm'],\n                              list(self.REQUIRED_AES | self.NON_MISSING_AES),\n                              self.__class__.__name__)",
    "docstring": "Remove rows with NaN values\n\n        geoms that infer extra information from missing values\n        should override this method. For example\n        :class:`~plotnine.geoms.geom_path`.\n\n        Parameters\n        ----------\n        data : dataframe\n            Data\n\n        Returns\n        -------\n        out : dataframe\n            Data without the NaNs.\n\n        Notes\n        -----\n        Shows a warning if the any rows are removed and the\n        `na_rm` parameter is False. It only takes into account\n        the columns of the required aesthetics."
  },
  {
    "code": "def y1(x, context=None):\n    return _apply_function_in_current_context(\n        BigFloat,\n        mpfr.mpfr_y1,\n        (BigFloat._implicit_convert(x),),\n        context,\n    )",
    "docstring": "Return the value of the second kind Bessel function of order 1 at x."
  },
  {
    "code": "def get_child_models(self):\n        child_models = []\n        for plugin in self.child_model_plugin_class.get_plugins():\n            child_models.append((plugin.model, plugin.model_admin))\n        if not child_models:\n            child_models.append((\n                self.child_model_admin.base_model,\n                self.child_model_admin,\n            ))\n        return child_models",
    "docstring": "Get child models from registered plugins. Fallback to the child model\n        admin and its base model if no plugins are registered."
  },
  {
    "code": "def __get_descendants(node, dfs_data):\n    list_of_descendants = []\n    stack = deque()\n    children_lookup = dfs_data['children_lookup']\n    current_node = node\n    children = children_lookup[current_node]\n    dfs_current_node = D(current_node, dfs_data)\n    for n in children:\n        dfs_child = D(n, dfs_data)\n        if dfs_child > dfs_current_node:\n            stack.append(n)\n    while len(stack) > 0:\n        current_node = stack.pop()\n        list_of_descendants.append(current_node)\n        children = children_lookup[current_node]\n        dfs_current_node = D(current_node, dfs_data)\n        for n in children:\n            dfs_child = D(n, dfs_data)\n            if dfs_child > dfs_current_node:\n                stack.append(n)\n    return list_of_descendants",
    "docstring": "Gets the descendants of a node."
  },
  {
    "code": "def _clear(self):\n        (colour, attr, bg) = self.palette[\"background\"]\n        self._canvas.clear_buffer(colour, attr, bg)",
    "docstring": "Clear the current canvas."
  },
  {
    "code": "def currentVersion(self):\n        if self._currentVersion is None:\n            self.__init(self._url)\n        return self._currentVersion",
    "docstring": "returns the current version of the site"
  },
  {
    "code": "def on_cluster_remove(self, name):\n        discovery_name = self.configurables[Cluster][name].discovery\n        if discovery_name in self.configurables[Discovery]:\n            self.configurables[Discovery][discovery_name].stop_watching(\n                self.configurables[Cluster][name]\n            )\n            self.kill_thread(name)\n        self.sync_balancer_files()",
    "docstring": "Stops the cluster's associated discovery method from watching for\n        changes to the cluster's nodes."
  },
  {
    "code": "def _get_fullpath(self, filepath):\n        if filepath[0] == '/':\n            return filepath\n        return os.path.join(self._base_path, filepath)",
    "docstring": "Return filepath with the base_path prefixed"
  },
  {
    "code": "def get_key(self, path, geometry, filters, options):\n        seed = u' '.join([\n            str(path),\n            str(geometry),\n            str(filters),\n            str(options),\n        ]).encode('utf8')\n        return md5(seed).hexdigest()",
    "docstring": "Generates the thumbnail's key from it's arguments.\n        If the arguments doesn't change the key will not change"
  },
  {
    "code": "def inform_if_paths_invalid(egrc_path, examples_dir, custom_dir, debug=True):\n    if (not debug):\n        return\n    if (egrc_path):\n        _inform_if_path_does_not_exist(egrc_path)\n    if (examples_dir):\n        _inform_if_path_does_not_exist(examples_dir)\n    if (custom_dir):\n        _inform_if_path_does_not_exist(custom_dir)",
    "docstring": "If egrc_path, examples_dir, or custom_dir is truthy and debug is True,\n    informs the user that a path is not set.\n\n    This should be used to verify input arguments from the command line."
  },
  {
    "code": "def apply(self, fn, *column_or_columns):\n        if not column_or_columns:\n            return np.array([fn(row) for row in self.rows])\n        else:\n            if len(column_or_columns) == 1 and \\\n                    _is_non_string_iterable(column_or_columns[0]):\n                warnings.warn(\n                   \"column lists are deprecated; pass each as an argument\", FutureWarning)\n                column_or_columns = column_or_columns[0]\n            rows = zip(*self.select(*column_or_columns).columns)\n            return np.array([fn(*row) for row in rows])",
    "docstring": "Apply ``fn`` to each element or elements of ``column_or_columns``.\n        If no ``column_or_columns`` provided, `fn`` is applied to each row.\n\n        Args:\n            ``fn`` (function) -- The function to apply.\n            ``column_or_columns``: Columns containing the arguments to ``fn``\n                as either column labels (``str``) or column indices (``int``).\n                The number of columns must match the number of arguments\n                that ``fn`` expects.\n\n        Raises:\n            ``ValueError`` -- if  ``column_label`` is not an existing\n                column in the table.\n            ``TypeError`` -- if insufficent number of ``column_label`` passed\n                to ``fn``.\n\n        Returns:\n            An array consisting of results of applying ``fn`` to elements\n            specified by ``column_label`` in each row.\n\n        >>> t = Table().with_columns(\n        ...     'letter', make_array('a', 'b', 'c', 'z'),\n        ...     'count',  make_array(9, 3, 3, 1),\n        ...     'points', make_array(1, 2, 2, 10))\n        >>> t\n        letter | count | points\n        a      | 9     | 1\n        b      | 3     | 2\n        c      | 3     | 2\n        z      | 1     | 10\n        >>> t.apply(lambda x: x - 1, 'points')\n        array([0, 1, 1, 9])\n        >>> t.apply(lambda x, y: x * y, 'count', 'points')\n        array([ 9,  6,  6, 10])\n        >>> t.apply(lambda x: x - 1, 'count', 'points')\n        Traceback (most recent call last):\n            ...\n        TypeError: <lambda>() takes 1 positional argument but 2 were given\n        >>> t.apply(lambda x: x - 1, 'counts')\n        Traceback (most recent call last):\n            ...\n        ValueError: The column \"counts\" is not in the table. The table contains these columns: letter, count, points\n\n        Whole rows are passed to the function if no columns are specified.\n\n        >>> t.apply(lambda row: row[1] * 2)\n        array([18,  6,  6,  2])"
  },
  {
    "code": "def parse_value(source: SourceType, **options: dict) -> ValueNode:\n    if isinstance(source, str):\n        source = Source(source)\n    lexer = Lexer(source, **options)\n    expect_token(lexer, TokenKind.SOF)\n    value = parse_value_literal(lexer, False)\n    expect_token(lexer, TokenKind.EOF)\n    return value",
    "docstring": "Parse the AST for a given string containing a GraphQL value.\n\n    Throws GraphQLError if a syntax error is encountered.\n\n    This is useful within tools that operate upon GraphQL Values directly and in\n    isolation of complete GraphQL documents.\n\n    Consider providing the results to the utility function: `value_from_ast()`."
  },
  {
    "code": "def arp(interface='', ipaddr='', macaddr='', **kwargs):\n    proxy_output = salt.utils.napalm.call(\n        napalm_device,\n        'get_arp_table',\n        **{\n        }\n    )\n    if not proxy_output.get('result'):\n        return proxy_output\n    arp_table = proxy_output.get('out')\n    if interface:\n        arp_table = _filter_list(arp_table, 'interface', interface)\n    if ipaddr:\n        arp_table = _filter_list(arp_table, 'ip', ipaddr)\n    if macaddr:\n        arp_table = _filter_list(arp_table, 'mac', macaddr)\n    proxy_output.update({\n        'out': arp_table\n    })\n    return proxy_output",
    "docstring": "NAPALM returns a list of dictionaries with details of the ARP entries.\n\n    :param interface: interface name to filter on\n    :param ipaddr: IP address to filter on\n    :param macaddr: MAC address to filter on\n    :return: List of the entries in the ARP table\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' net.arp\n        salt '*' net.arp macaddr='5c:5e:ab:da:3c:f0'\n\n    Example output:\n\n    .. code-block:: python\n\n        [\n            {\n                'interface' : 'MgmtEth0/RSP0/CPU0/0',\n                'mac'       : '5c:5e:ab:da:3c:f0',\n                'ip'        : '172.17.17.1',\n                'age'       : 1454496274.84\n            },\n            {\n                'interface': 'MgmtEth0/RSP0/CPU0/0',\n                'mac'       : '66:0e:94:96:e0:ff',\n                'ip'        : '172.17.17.2',\n                'age'       : 1435641582.49\n            }\n        ]"
  },
  {
    "code": "def comment (self, s, **args):\n        self.write(u\"<!-- \")\n        self.write(s, **args)\n        self.writeln(u\" -->\")",
    "docstring": "Write XML comment."
  },
  {
    "code": "def monitor(self, timeout):\n        def check(self, timeout):\n            time.sleep(timeout)\n            self.stop()\n        wather = threading.Thread(target=check)\n        wather.setDaemon(True)\n        wather.start()",
    "docstring": "Monitor the process, check whether it runs out of time."
  },
  {
    "code": "def dendrite_filter(n):\n    return n.type == NeuriteType.basal_dendrite or n.type == NeuriteType.apical_dendrite",
    "docstring": "Select only dendrites"
  },
  {
    "code": "def index(self, value, floating=False):\n        value = np.atleast_1d(self.set.element(value))\n        result = []\n        for val, cell_bdry_vec in zip(value, self.cell_boundary_vecs):\n            ind = np.searchsorted(cell_bdry_vec, val)\n            if floating:\n                if cell_bdry_vec[ind] == val:\n                    result.append(float(ind))\n                else:\n                    csize = float(cell_bdry_vec[ind] - cell_bdry_vec[ind - 1])\n                    result.append(ind - (cell_bdry_vec[ind] - val) / csize)\n            else:\n                if cell_bdry_vec[ind] == val and ind != len(cell_bdry_vec) - 1:\n                    result.append(ind)\n                else:\n                    result.append(ind - 1)\n        if self.ndim == 1:\n            result = result[0]\n        else:\n            result = tuple(result)\n        return result",
    "docstring": "Return the index of a value in the domain.\n\n        Parameters\n        ----------\n        value : ``self.set`` element\n            Point whose index to find.\n        floating : bool, optional\n            If True, then the index should also give the position inside the\n            voxel. This is given by returning the integer valued index of the\n            voxel plus the distance from the left cell boundary as a fraction\n            of the full cell size.\n\n        Returns\n        -------\n        index : int, float, tuple of int or tuple of float\n            Index of the value, as counted from the left.\n            If ``self.ndim > 1`` the result is a tuple, else a scalar.\n            If ``floating=True`` the scalar is a float, else an int.\n\n        Examples\n        --------\n        Get the indices of start and end:\n\n        >>> p = odl.uniform_partition(0, 2, 5)\n        >>> p.index(0)\n        0\n        >>> p.index(2)\n        4\n\n        For points inside voxels, the index of the containing cell is returned:\n\n        >>> p.index(0.2)\n        0\n\n        By using the ``floating`` argument, partial positions inside the voxels\n        can instead be determined:\n\n        >>> p.index(0.2, floating=True)\n        0.5\n\n        These indices work with indexing, extracting the voxel in which the\n        point lies:\n\n        >>> p[p.index(0.1)]\n        uniform_partition(0.0, 0.4, 1)\n\n        The same principle also works in higher dimensions:\n\n        >>> p = uniform_partition([0, -1], [1, 2], (4, 1))\n        >>> p.index([0.5, 2])\n        (2, 0)\n        >>> p[p.index([0.5, 2])]\n        uniform_partition([ 0.5, -1. ], [ 0.75,  2.  ], (1, 1))"
  },
  {
    "code": "def vsubg(v1, v2, ndim):\n    v1 = stypes.toDoubleVector(v1)\n    v2 = stypes.toDoubleVector(v2)\n    vout = stypes.emptyDoubleVector(ndim)\n    ndim = ctypes.c_int(ndim)\n    libspice.vsubg_c(v1, v2, ndim, vout)\n    return stypes.cVectorToPython(vout)",
    "docstring": "Compute the difference between two double precision\n    vectors of arbitrary dimension.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsubg_c.html\n\n    :param v1: First vector (minuend). \n    :type v1: Array of floats\n    :param v2: Second vector (subtrahend). \n    :type v2: Array of floats\n    :param ndim: Dimension of v1, v2, and vout. \n    :type ndim: int\n    :return: Difference vector, v1 - v2.\n    :rtype: Array of floats"
  },
  {
    "code": "def get_data_disk_size(vm_, swap, linode_id):\n    disk_size = get_linode(kwargs={'linode_id': linode_id})['TOTALHD']\n    root_disk_size = config.get_cloud_config_value(\n        'disk_size', vm_, __opts__, default=disk_size - swap\n    )\n    return disk_size - root_disk_size - swap",
    "docstring": "Return the size of of the data disk in MB\n\n    .. versionadded:: 2016.3.0"
  },
  {
    "code": "def add_column(connection, column):\n    stmt = alembic.ddl.base.AddColumn(_State.table.name, column)\n    connection.execute(stmt)\n    _State.reflect_metadata()",
    "docstring": "Add a column to the current table."
  },
  {
    "code": "def get_probability_no_exceedance(self, poes):\n        if numpy.isnan(self.occurrence_rate):\n            if len(poes.shape) == 1:\n                poes = numpy.reshape(poes, (-1, len(poes)))\n            p_kT = self.probs_occur\n            prob_no_exceed = numpy.array(\n                [v * ((1 - poes) ** i) for i, v in enumerate(p_kT)])\n            prob_no_exceed = numpy.sum(prob_no_exceed, axis=0)\n            prob_no_exceed[prob_no_exceed > 1.] = 1.\n            prob_no_exceed[poes == 0.] = 1.\n            return prob_no_exceed\n        tom = self.temporal_occurrence_model\n        return tom.get_probability_no_exceedance(self.occurrence_rate, poes)",
    "docstring": "Compute and return the probability that in the time span for which the\n        rupture is defined, the rupture itself never generates a ground motion\n        value higher than a given level at a given site.\n\n        Such calculation is performed starting from the conditional probability\n        that an occurrence of the current rupture is producing a ground motion\n        value higher than the level of interest at the site of interest.\n        The actual formula used for such calculation depends on the temporal\n        occurrence model the rupture is associated with.\n        The calculation can be performed for multiple intensity measure levels\n        and multiple sites in a vectorized fashion.\n\n        :param poes:\n            2D numpy array containing conditional probabilities the the a\n            rupture occurrence causes a ground shaking value exceeding a\n            ground motion level at a site. First dimension represent sites,\n            second dimension intensity measure levels. ``poes`` can be obtained\n            calling the :meth:`method\n            <openquake.hazardlib.gsim.base.GroundShakingIntensityModel.get_poes>"
  },
  {
    "code": "def save(self, doc):\n        self.log.debug('save()')\n        self.docs.append(doc)\n        self.commit()",
    "docstring": "Save a doc to cache"
  },
  {
    "code": "def titles(self, key, value):\n    if not key.startswith('245'):\n        return {\n            'source': value.get('9'),\n            'subtitle': value.get('b'),\n            'title': value.get('a'),\n        }\n    self.setdefault('titles', []).insert(0, {\n        'source': value.get('9'),\n        'subtitle': value.get('b'),\n        'title': value.get('a'),\n    })",
    "docstring": "Populate the ``titles`` key."
  },
  {
    "code": "def owner(self):\n        if self._writer is not None:\n            return self.WRITER\n        if self._readers:\n            return self.READER\n        return None",
    "docstring": "Returns whether the lock is locked by a writer or reader."
  },
  {
    "code": "def uri(self, value):\n        if value == self.__uri:\n            return\n        match = URI_REGEX.match(value)\n        if match is None:\n            raise ValueError('Unable to match URI from `{}`'.format(value))\n        for key, value in match.groupdict().items():\n            setattr(self, key, value)",
    "docstring": "Attempt to validate URI and split into individual values"
  },
  {
    "code": "def remove(self):\n        self.clean()\n        if os.path.isfile(self.schema_zip_file):\n            os.remove(self.schema_zip_file)\n        if os.path.isdir(self.schema_root_dir) and \\\n                os.listdir(self.schema_root_dir) == []:\n            os.rmdir(self.schema_root_dir)",
    "docstring": "The `schema_mof_dir` directory is removed if it esists and the\n        `schema_zip_file` is removed if it exists. If the `schema_root_dir` is\n        empty after these removals that directory is removed."
  },
  {
    "code": "def earth_gyro(RAW_IMU,ATTITUDE):\n    r = rotation(ATTITUDE)\n    accel = Vector3(degrees(RAW_IMU.xgyro), degrees(RAW_IMU.ygyro), degrees(RAW_IMU.zgyro)) * 0.001\n    return r * accel",
    "docstring": "return earth frame gyro vector"
  },
  {
    "code": "def _read_hopopt_options(self, length):\n        counter = 0\n        optkind = list()\n        options = dict()\n        while counter < length:\n            code = self._read_unpack(1)\n            if not code:\n                break\n            abbr, desc = _HOPOPT_OPT.get(code, ('none', 'Unassigned'))\n            data = _HOPOPT_PROC(abbr)(self, code, desc=desc)\n            enum = _OPT_TYPE.get(code)\n            counter += data['length']\n            if enum in optkind:\n                if isinstance(options[abbr], tuple):\n                    options[abbr] += (Info(data),)\n                else:\n                    options[abbr] = (Info(options[abbr]), Info(data))\n            else:\n                optkind.append(enum)\n                options[abbr] = data\n        if counter != length:\n            raise ProtocolError(f'{self.alias}: invalid format')\n        return tuple(optkind), options",
    "docstring": "Read HOPOPT options.\n\n        Positional arguments:\n            * length -- int, length of options\n\n        Returns:\n            * dict -- extracted HOPOPT options"
  },
  {
    "code": "def _update_metadata_for_video(self, metadata_href, video):\n        current_metadata = self.clarify_client.get_metadata(metadata_href)\n        cur_data = current_metadata.get('data')\n        if cur_data.get('updated_at') != video['updated_at']:\n            self.log('Updating metadata for video {0}'.format(video['id']))\n            if not self.dry_run:\n                metadata = self._metadata_from_video(video)\n                self.clarify_client.update_metadata(metadata_href, metadata=metadata)\n            self.sync_stats['updated'] += 1",
    "docstring": "Update the metadata for the video if video has been updated in Brightcove since the bundle\n        metadata was last updated."
  },
  {
    "code": "def _pipeline_cell(args, cell_body):\n  if args['action'] == 'deploy':\n    raise Exception('Deploying a pipeline is not yet supported')\n  env = {}\n  for key, value in datalab.utils.commands.notebook_environment().items():\n    if isinstance(value, datalab.bigquery._udf.UDF):\n      env[key] = value\n  query = _get_query_argument(args, cell_body, env)\n  if args['verbose']:\n    print(query.sql)\n  if args['action'] == 'dryrun':\n    print(query.sql)\n    result = query.execute_dry_run()\n    return datalab.bigquery._query_stats.QueryStats(total_bytes=result['totalBytesProcessed'],\n                                                    is_cached=result['cacheHit'])\n  if args['action'] == 'run':\n    return query.execute(args['target'], table_mode=args['mode'], use_cache=not args['nocache'],\n                         allow_large_results=args['large'], dialect=args['dialect'],\n                         billing_tier=args['billing']).results",
    "docstring": "Implements the BigQuery cell magic used to validate, execute or deploy BQ pipelines.\n\n   The supported syntax is:\n   %%bigquery pipeline [-q|--sql <query identifier>] <other args> <action>\n   [<YAML or JSON cell_body or inline SQL>]\n\n  Args:\n    args: the arguments following '%bigquery pipeline'.\n    cell_body: optional contents of the cell interpreted as YAML or JSON.\n  Returns:\n    The QueryResultsTable"
  },
  {
    "code": "def THUMBNAIL_OPTIONS(self):\n        from django.core.exceptions import ImproperlyConfigured\n        size = self._setting('DJNG_THUMBNAIL_SIZE', (200, 200))\n        if not (isinstance(size, (list, tuple)) and len(size) == 2 and isinstance(size[0], int) and isinstance(size[1], int)):\n            raise ImproperlyConfigured(\"'DJNG_THUMBNAIL_SIZE' must be a 2-tuple of integers.\")\n        return {'crop': True, 'size': size}",
    "docstring": "Set the size as a 2-tuple for thumbnailed images after uploading them."
  },
  {
    "code": "def generic_stitch(cube, arrays):\n    for name, ary in arrays.iteritems():\n        if name not in type(cube).__dict__:\n            setattr(type(cube), name, ArrayDescriptor(name))\n        setattr(cube, name, ary)",
    "docstring": "Creates descriptors associated with array name and\n    then sets the array as a member variable"
  },
  {
    "code": "def get_public_inline_preview_url(self, id, submission_id=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"id\"] = id\r\n        if submission_id is not None:\r\n            params[\"submission_id\"] = submission_id\r\n        self.logger.debug(\"GET /api/v1/files/{id}/public_url with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"GET\", \"/api/v1/files/{id}/public_url\".format(**path), data=data, params=params, no_data=True)",
    "docstring": "Get public inline preview url.\r\n\r\n        Determine the URL that should be used for inline preview of the file."
  },
  {
    "code": "def _check_type(self, check_type, properties):\n        if 'PrimitiveType' in properties:\n            return properties['PrimitiveType'] == check_type\n        if properties['Type'] == 'List':\n            if 'ItemType' in properties:\n                return properties['ItemType'] == check_type\n            else:\n                return properties['PrimitiveItemType'] == check_type\n        return False",
    "docstring": "Decode a properties type looking for a specific type."
  },
  {
    "code": "def do_add_item(self, args):\n        if args.food:\n            add_item = args.food\n        elif args.sport:\n            add_item = args.sport\n        elif args.other:\n            add_item = args.other\n        else:\n            add_item = 'no items'\n        self.poutput(\"You added {}\".format(add_item))",
    "docstring": "Add item command help"
  },
  {
    "code": "def _close(self, id):\n        connection = self.connections[id]\n        connection.connectionLost(Failure(CONNECTION_DONE))\n        return {}",
    "docstring": "Respond to a CLOSE command, dumping some data onto the stream.  As with\n        WRITE, this returns an empty acknowledgement.\n\n        An occurrence of I{Close} on the wire, together with the response\n        generated by this method, might have this apperance::\n\n            C: -Command: Close\n            C: -Ask: 1\n            C: Id: glyph@divmod.com->radix@twistedmatrix.com:q2q-example:0\n            C:\n            S: -Answer: 1\n            S:"
  },
  {
    "code": "def get_message_content(self, message_id, timeout=None):\n        response = self._get(\n            '/v2/bot/message/{message_id}/content'.format(message_id=message_id),\n            stream=True, timeout=timeout\n        )\n        return Content(response)",
    "docstring": "Call get content API.\n\n        https://devdocs.line.me/en/#get-content\n\n        Retrieve image, video, and audio data sent by users.\n\n        :param str message_id: Message ID\n        :param timeout: (optional) How long to wait for the server\n            to send data before giving up, as a float,\n            or a (connect timeout, read timeout) float tuple.\n            Default is self.http_client.timeout\n        :type timeout: float | tuple(float, float)\n        :rtype: :py:class:`linebot.models.responses.Content`\n        :return: Content instance"
  },
  {
    "code": "def subscriptions(self):\n        if not hasattr(self, '_subscriptions'):\n            subscriptions_resource = self.resource.subscriptions\n            self._subscriptions = Subscriptions(\n                subscriptions_resource, self.client)\n        return self._subscriptions",
    "docstring": "Fetch and return Subscriptions associated with this user."
  },
  {
    "code": "def draw_str(self, x, y, string, fg=Ellipsis, bg=Ellipsis):\n        x, y = self._normalizePoint(x, y)\n        fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)\n        width, height = self.get_size()\n        def _drawStrGen(x=x, y=y, string=string, width=width, height=height):\n            for char in _format_str(string):\n                if y == height:\n                    raise TDLError('End of console reached.')\n                yield((x, y), char)\n                x += 1\n                if x == width:\n                    x = 0\n                    y += 1\n        self._set_batch(_drawStrGen(), fg, bg)",
    "docstring": "Draws a string starting at x and y.\n\n        A string that goes past the right side will wrap around.  A string\n        wrapping to below the console will raise :any:`tdl.TDLError` but will\n        still be written out.\n        This means you can safely ignore the errors with a\n        try..except block if you're fine with partially written strings.\n\n        \\\\r and \\\\n are drawn on the console as normal character tiles.  No\n        special encoding is done and any string will translate to the character\n        table as is.\n\n        For a string drawing operation that respects special characters see\n        :any:`print_str`.\n\n        Args:\n            x (int): x-coordinate to start at.\n            y (int): y-coordinate to start at.\n            string (Union[Text, Iterable[int]]): A string or an iterable of\n                numbers.\n\n                Special characters are ignored and rendered as any other\n                character.\n            fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])\n            bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])\n\n        Raises:\n            AssertionError: Having x or y values that can't be placed inside\n                            of the console will raise an AssertionError.\n\n                You can use always use ``((x, y) in console)`` to check if\n                a tile is drawable.\n\n        .. seealso:: :any:`print_str`"
  },
  {
    "code": "def _precesion(date):\n    t = date.change_scale('TT').julian_century\n    zeta = (2306.2181 * t + 0.30188 * t ** 2 + 0.017998 * t ** 3) / 3600.\n    theta = (2004.3109 * t - 0.42665 * t ** 2 - 0.041833 * t ** 3) / 3600.\n    z = (2306.2181 * t + 1.09468 * t ** 2 + 0.018203 * t ** 3) / 3600.\n    return zeta, theta, z",
    "docstring": "Precession in degrees"
  },
  {
    "code": "def update(self, callback=None, errback=None, **kwargs):\n        if not self.data:\n            raise MonitorException('monitor not loaded')\n        def success(result, *args):\n            self.data = result\n            if callback:\n                return callback(self)\n            else:\n                return self\n        return self._rest.update(self.data['id'], {}, callback=success, errback=errback, **kwargs)",
    "docstring": "Update monitor configuration. Pass a list of keywords and their values to\n        update."
  },
  {
    "code": "def run_kernel(self, func, gpu_args, threads, grid):\n        global_size = (grid[0]*threads[0], grid[1]*threads[1], grid[2]*threads[2])\n        local_size = threads\n        event = func(self.queue, global_size, local_size, *gpu_args)\n        event.wait()",
    "docstring": "runs the OpenCL kernel passed as 'func'\n\n        :param func: An OpenCL Kernel\n        :type func: pyopencl.Kernel\n\n        :param gpu_args: A list of arguments to the kernel, order should match the\n            order in the code. Allowed values are either variables in global memory\n            or single values passed by value.\n        :type gpu_args: list( pyopencl.Buffer, numpy.int32, ...)\n\n        :param threads: A tuple listing the number of work items in each dimension of\n            the work group.\n        :type threads: tuple(int, int, int)\n\n        :param grid: A tuple listing the number of work groups in each dimension\n            of the NDRange.\n        :type grid: tuple(int, int)"
  },
  {
    "code": "def execute(self):\n        logger.info(\"Starting Argos event loop...\")\n        exitCode = self.qApplication.exec_()\n        logger.info(\"Argos event loop finished with exit code: {}\".format(exitCode))\n        return exitCode",
    "docstring": "Executes all main windows by starting the Qt main application"
  },
  {
    "code": "def persist_booking(booking, user):\n    if booking is not None:\n        existing_bookings = Booking.objects.filter(\n            user=user, booking_status__slug='inprogress').exclude(\n            pk=booking.pk)\n        existing_bookings.delete()\n        booking.session = None\n        booking.user = user\n        booking.save()",
    "docstring": "Ties an in-progress booking from a session to a user when the user logs in.\n\n    If we don't do this, the booking will be lost, because on a login, the\n    old session will be deleted and a new one will be created. Since the\n    booking has a FK to the session, it would be deleted as well when the user\n    logs in.\n\n    We assume that a user can only have one booking that is in-progress.\n    Therefore we will delete any existing in-progress bookings of this user\n    before tying the one from the session to the user.\n\n    TODO: Find a more generic solution for this, as this assumes that there is\n    a status called inprogress and that a user can only have one such booking.\n\n    :param booking: The booking that should be tied to the user.\n    :user: The user the booking should be tied to."
  },
  {
    "code": "def filter_objects(self, objects, perm=None):\n        if perm is None:\n            perm = build_permission_name(self.model_class, 'view')\n        return filter(lambda o: self.user.has_perm(perm, obj=o), objects)",
    "docstring": "Return only objects with specified permission in objects list. If perm not specified, 'view' perm will be used."
  },
  {
    "code": "def setReferenceVoltage(self, caldb, calv):\n        self.caldb = caldb\n        self.calv = calv",
    "docstring": "Sets the reference point to determine what outgoing voltage will produce what intensity, \n        used to calculate the proper output amplitude of components\n\n        :param caldb: calibration intensity in dbSPL\n        :type caldb: float\n        :param calv: calibration voltage that was used to record the intensity provided\n        :type calv: float"
  },
  {
    "code": "def list_projects(self):\n        data = self._run(\n            url_path=\"projects/list\"\n        )\n        projects = data['result'].get('projects', [])\n        return [self._project_formatter(item) for item in projects]",
    "docstring": "Returns the list of projects owned by user."
  },
  {
    "code": "def get_monomials(variables, degree):\n    if degree == -1:\n        return []\n    if not variables:\n        return [S.One]\n    else:\n        _variables = variables[:]\n        _variables.insert(0, 1)\n        ncmonomials = [S.One]\n        ncmonomials.extend(var for var in variables)\n        for var in variables:\n            if not is_hermitian(var):\n                ncmonomials.append(var.adjoint())\n        for _ in range(1, degree):\n            temp = []\n            for var in _variables:\n                for new_var in ncmonomials:\n                    temp.append(var * new_var)\n                    if var != 1 and not is_hermitian(var):\n                        temp.append(var.adjoint() * new_var)\n            ncmonomials = unique(temp[:])\n        return ncmonomials",
    "docstring": "Generates all noncommutative monomials up to a degree\n\n    :param variables: The noncommutative variables to generate monomials from\n    :type variables: list of :class:`sympy.physics.quantum.operator.Operator`\n                     or\n                     :class:`sympy.physics.quantum.operator.HermitianOperator`.\n    :param degree: The maximum degree.\n    :type degree: int.\n\n    :returns: list of monomials."
  },
  {
    "code": "def serialize(self):\n        return {\n            'name' : self.name,\n            'weight' : self.weight,\n            'value' : self.value,\n            'msgs' : self.msgs,\n            'children' : [i.serialize() for i in self.children]\n        }",
    "docstring": "Returns a serializable dictionary that represents the result object"
  },
  {
    "code": "def works(self, member_id):\n        context = '%s/%s' % (self.ENDPOINT, str(member_id))\n        return Works(context=context)",
    "docstring": "This method retrieve a iterable of Works of the given member.\n\n        args: Member ID (Integer)\n\n        return: Works()"
  },
  {
    "code": "def SetDecodedStreamSize(self, decoded_stream_size):\n    if self._is_open:\n      raise IOError('Already open.')\n    if decoded_stream_size < 0:\n      raise ValueError((\n          'Invalid decoded stream size: {0:d} value out of '\n          'bounds.').format(decoded_stream_size))\n    self._decoded_stream_size = decoded_stream_size",
    "docstring": "Sets the decoded stream size.\n\n    This function is used to set the decoded stream size if it can be\n    determined separately.\n\n    Args:\n      decoded_stream_size (int): size of the decoded stream in bytes.\n\n    Raises:\n      IOError: if the file-like object is already open.\n      OSError: if the file-like object is already open.\n      ValueError: if the decoded stream size is invalid."
  },
  {
    "code": "def ignore_further_calls_to_server(self, server):\n        log.error(u'ignoring further calls to {}'.format(server))\n        self.api.servers.remove(server)",
    "docstring": "Takes a server out of the list."
  },
  {
    "code": "def sample_tmatrix(C, nsample=1, nsteps=None, reversible=False, mu=None, T0=None, return_statdist=False):\n    r\n    if issparse(C):\n        _showSparseConversionWarning()\n        C = C.toarray()\n    sampler = tmatrix_sampler(C, reversible=reversible, mu=mu, T0=T0, nsteps=nsteps)\n    return sampler.sample(nsamples=nsample, return_statdist=return_statdist)",
    "docstring": "r\"\"\"samples transition matrices from the posterior distribution\n\n    Parameters\n    ----------\n    C : (M, M) ndarray or scipy.sparse matrix\n        Count matrix\n    nsample : int\n        number of samples to be drawn\n    nstep : int, default=None\n        number of full Gibbs sampling sweeps internally done for each sample\n        returned. This option is meant to ensure approximately uncorrelated\n        samples for every call to sample(). If None, the number of steps will\n        be automatically determined based on the other options and  the matrix\n        size. nstep>1 will only be used for reversible sampling, because\n        nonreversible sampling generates statistically independent transition\n        matrices every step.\n    reversible : bool\n        If true sample from the ensemble of transition matrices\n        restricted to those obeying a detailed balance condition,\n        else draw from the whole ensemble of stochastic matrices.\n    mu : array_like\n        A fixed stationary distribution. Transition matrices with that stationary distribution will be sampled\n    T0 : ndarray, shape=(n, n) or scipy.sparse matrix\n        Starting point of the MC chain of the sampling algorithm.\n        Has to obey the required constraints.\n    return_statdist : bool, optional, default = False\n        if true, will also return the stationary distribution.\n\n    Returns\n    -------\n    P : ndarray(n,n) or array of ndarray(n,n)\n        sampled transition matrix (or multiple matrices if nsample > 1)\n\n    Notes\n    -----\n    The transition matrix sampler generates transition matrices from\n    the posterior distribution. The posterior distribution is given as\n    a product of Dirichlet distributions\n\n    .. math:: \\mathbb{P}(T|C) \\propto \\prod_{i=1}^{M} \\left( \\prod_{j=1}^{M} p_{ij}^{c_{ij}} \\right)\n\n    See also\n    --------\n    tmatrix_sampler"
  },
  {
    "code": "def featured_event_query(self, **kwargs):\n        if not kwargs.get('location') and (not kwargs.get('latitude') or not kwargs.get('longitude')):\n            raise ValueError('A valid location (parameter \"location\") or latitude/longitude combination '\n                             '(parameters \"latitude\" and \"longitude\") must be provided.')\n        return self._query(FEATURED_EVENT_API_URL, **kwargs)",
    "docstring": "Query the Yelp Featured Event API.\n\n            documentation: https://www.yelp.com/developers/documentation/v3/featured_event\n\n            required parameters:\n                * one of either:\n                    * location - text specifying a location to search for\n                    * latitude and longitude"
  },
  {
    "code": "def _check_valid_basic(self, get_params):\n        try:\n            if get_params(self.variable):\n                return self.default\n        except:\n            pass\n        return not self.default",
    "docstring": "Simple check that the variable is set"
  },
  {
    "code": "def save_ds9(output, filename):\n    ds9_file = open(filename, 'wt')\n    ds9_file.write(output)\n    ds9_file.close()",
    "docstring": "Save ds9 region output info filename.\n\n    Parameters\n    ----------\n    output : str\n        String containing the full output to be exported as a ds9 region\n        file.\n    filename : str\n        Output file name."
  },
  {
    "code": "def get_chatlist(chatfile):\n    if not chatfile:\n        return set()\n    try:\n        with open(chatfile) as file_contents:\n            return set(int(chat) for chat in file_contents)\n    except (OSError, IOError) as exc:\n        LOGGER.error('could not load saved chats:\\n%s', exc)\n        return set()",
    "docstring": "Try reading ids of saved chats from file.\n    If we fail, return empty set"
  },
  {
    "code": "def add_include(self, name, included_scope, module):\n        assert name not in self.included_scopes\n        self.included_scopes[name] = included_scope\n        self.add_surface(name, module)",
    "docstring": "Register an imported module into this scope.\n\n        Raises ``ThriftCompilerError`` if the name has already been used."
  },
  {
    "code": "def attach_pipeline(self, pipeline, name, chunks=None, eager=True):\n        if chunks is None:\n            chunks = chain([5], repeat(126))\n        elif isinstance(chunks, int):\n            chunks = repeat(chunks)\n        if name in self._pipelines:\n            raise DuplicatePipelineName(name=name)\n        self._pipelines[name] = AttachedPipeline(pipeline, iter(chunks), eager)\n        return pipeline",
    "docstring": "Register a pipeline to be computed at the start of each day.\n\n        Parameters\n        ----------\n        pipeline : Pipeline\n            The pipeline to have computed.\n        name : str\n            The name of the pipeline.\n        chunks : int or iterator, optional\n            The number of days to compute pipeline results for. Increasing\n            this number will make it longer to get the first results but\n            may improve the total runtime of the simulation. If an iterator\n            is passed, we will run in chunks based on values of the iterator.\n            Default is True.\n        eager : bool, optional\n            Whether or not to compute this pipeline prior to\n            before_trading_start.\n\n        Returns\n        -------\n        pipeline : Pipeline\n            Returns the pipeline that was attached unchanged.\n\n        See Also\n        --------\n        :func:`zipline.api.pipeline_output`"
  },
  {
    "code": "def index_to_coords(index, shape):\r\n    coords = []\r\n    for i in xrange(1, len(shape)):\r\n        divisor = int(np.product(shape[i:]))\r\n        value = index // divisor\r\n        coords.append(value)\r\n        index -= value * divisor\r\n    coords.append(index)\r\n    return tuple(coords)",
    "docstring": "convert index to coordinates given the shape"
  },
  {
    "code": "def remove_leading_zeros(num: str) -> str:\n    if not num:\n        return num\n    if num.startswith('M'):\n        ret = 'M' + num[1:].lstrip('0')\n    elif num.startswith('-'):\n        ret = '-' + num[1:].lstrip('0')\n    else:\n        ret = num.lstrip('0')\n    return '0' if ret in ('', 'M', '-') else ret",
    "docstring": "Strips zeros while handling -, M, and empty strings"
  },
  {
    "code": "def _assert_occurrence(probe, target, amount=1):\n    occ = len(probe)\n    if occ > amount:\n        msg = 'more than'\n    elif occ < amount:\n        msg = 'less than'\n    elif not occ:\n        msg = 'no'\n    else:\n        msg = None\n    if msg:\n        raise CommandExecutionError('Found {0} expected occurrences in \"{1}\" expression'.format(msg, target))\n    return occ",
    "docstring": "Raise an exception, if there are different amount of specified occurrences in src."
  },
  {
    "code": "def print_mhc_peptide(neoepitope_info, peptides, pepmap, outfile, netmhc=False):\n    if netmhc:\n        peptide_names = [neoepitope_info.peptide_name]\n    else:\n        peptide_names = [x for x, y in peptides.items() if neoepitope_info.pept in y]\n    neoepitope_info = neoepitope_info._asdict()\n    if neoepitope_info['normal_pept'] == 'N' * len(neoepitope_info['pept']):\n        neoepitope_info['normal_pept'] = neoepitope_info['normal_pred'] = 'NA'\n    for peptide_name in peptide_names:\n        print('{ni[allele]}\\t'\n              '{ni[pept]}\\t'\n              '{ni[normal_pept]}\\t'\n              '{pname}\\t'\n              '{ni[core]}\\t'\n              '0\\t'\n              '{ni[tumor_pred]}\\t'\n              '{ni[normal_pred]}\\t'\n              '{pmap}'.format(ni=neoepitope_info, pname=peptide_name,\n                                                  pmap=pepmap[peptide_name]), file=outfile)\n    return None",
    "docstring": "Accept data about one neoepitope from merge_mhc_peptide_calls and print it to outfile.  This is\n    a generic module to reduce code redundancy.\n\n    :param pandas.core.frame neoepitope_info: object containing with allele, pept, pred, core,\n           normal_pept, normal_pred\n    :param dict peptides: Dict of pepname: pep sequence for all IARS considered\n    :param dict pepmap: Dict containing teh contents from the peptide map file.\n    :param file outfile: An open file descriptor to the output file\n    :param bool netmhc: Does this record correspond to a netmhcIIpan record? These are processed\n           differently."
  },
  {
    "code": "def parse_trailer(header):\n    pos = 0\n    names = []\n    while pos < len(header):\n        name, pos = expect_re(re_token, header, pos)\n        if name:\n            names.append(name)\n        _, pos = accept_ws(header, pos)\n        _, pos = expect_lit(',', header, pos)\n        _, pos = accept_ws(header, pos)\n    return names",
    "docstring": "Parse the \"Trailer\" header."
  },
  {
    "code": "def inspect(self, tab_width=2, ident_char='-'):\n    startpath = self.path\n    output = []\n    for (root, dirs, files) in os.walk(startpath):\n      level = root.replace(startpath, '').count(os.sep)\n      indent = ident_char * tab_width * (level)\n      if level == 0:\n        output.append('{}{}/'.format(indent, os.path.basename(root)))\n      else:\n        output.append('|{}{}/'.format(indent, os.path.basename(root)))\n      subindent = ident_char * tab_width * (level + 1)\n      [output.append('|{}{}'.format(subindent, f)) for f in files]\n    return '\\n'.join(output)",
    "docstring": "Inspects a project file structure based based on the instance folder property.\n\n    :param tab_width: width size for subfolders and files.\n    :param ident_char: char to be used to show identation level\n\n    Returns\n      A string containing the project structure."
  },
  {
    "code": "async def delete_shade_from_scene(self, shade_id, scene_id):\n        return await self.request.delete(\n            self._base_path, params={ATTR_SCENE_ID: scene_id, ATTR_SHADE_ID: shade_id}\n        )",
    "docstring": "Delete a shade from a scene."
  },
  {
    "code": "def SendSms(self, *TargetNumbers, **Properties):\n        sms = self.CreateSms(smsMessageTypeOutgoing, *TargetNumbers)\n        for name, value in Properties.items():\n            if isinstance(getattr(sms.__class__, name, None), property):\n                setattr(sms, name, value)\n            else:\n                raise TypeError('Unknown property: %s' % prop)\n        sms.Send()\n        return sms",
    "docstring": "Creates and sends an SMS message.\n\n        :Parameters:\n          TargetNumbers : str\n            One or more target SMS numbers.\n          Properties\n            Message properties. Properties available are same as `SmsMessage` object properties.\n\n        :return: An sms message object. The message is already sent at this point.\n        :rtype: `SmsMessage`"
  },
  {
    "code": "def inverted(self):\n        out = self.copy()\n        out.setInverted(not self.isInverted())\n        return out",
    "docstring": "Returns an inverted copy of this query.\n\n        :return     <orb.Query>"
  },
  {
    "code": "def seek(self, offset, whence=SEEK_SET):\n        if whence == SEEK_SET:\n            self.__sf.seek(offset)\n        elif whence == SEEK_CUR:\n            self.__sf.seek(self.tell() + offset)\n        elif whence == SEEK_END:\n            self.__sf.seek(self.__sf.filesize - offset)",
    "docstring": "Reposition the file pointer."
  },
  {
    "code": "def from_request(cls, header_data, ignore_bad_cookies=False):\n        \"Construct a Cookies object from request header data.\"\n        cookies = cls()\n        cookies.parse_request(\n            header_data, ignore_bad_cookies=ignore_bad_cookies)\n        return cookies",
    "docstring": "Construct a Cookies object from request header data."
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'final' in _dict or 'final_results' in _dict:\n            args['final_results'] = _dict.get('final') or _dict.get(\n                'final_results')\n        else:\n            raise ValueError(\n                'Required property \\'final\\' not present in SpeechRecognitionResult JSON'\n            )\n        if 'alternatives' in _dict:\n            args['alternatives'] = [\n                SpeechRecognitionAlternative._from_dict(x)\n                for x in (_dict.get('alternatives'))\n            ]\n        else:\n            raise ValueError(\n                'Required property \\'alternatives\\' not present in SpeechRecognitionResult JSON'\n            )\n        if 'keywords_result' in _dict:\n            args['keywords_result'] = _dict.get('keywords_result')\n        if 'word_alternatives' in _dict:\n            args['word_alternatives'] = [\n                WordAlternativeResults._from_dict(x)\n                for x in (_dict.get('word_alternatives'))\n            ]\n        return cls(**args)",
    "docstring": "Initialize a SpeechRecognitionResult object from a json dictionary."
  },
  {
    "code": "def vinet_v(p, v0, k0, k0p, min_strain=0.01):\n    if isuncertainties([p, v0, k0, k0p]):\n        f_u = np.vectorize(uct.wrap(vinet_v_single), excluded=[1, 2, 3, 4])\n        return f_u(p, v0, k0, k0p, min_strain=min_strain)\n    else:\n        f_v = np.vectorize(vinet_v_single, excluded=[1, 2, 3, 4])\n        return f_v(p, v0, k0, k0p, min_strain=min_strain)",
    "docstring": "find volume at given pressure\n\n    :param p: pressure in GPa\n    :param v0: unit-cell volume in A^3 at 1 bar\n    :param k0: bulk modulus at reference conditions\n    :param k0p: pressure derivative of bulk modulus at reference conditions\n    :param min_strain: defining minimum v/v0 value to search volume for\n    :return: unit cell volume at high pressure in A^3\n    :note: wrapper function vetorizing vinet_v_single"
  },
  {
    "code": "def _set_key(self):\n        if self.roll:\n            self.date = time.strftime(self.date_format,\n                                      time.gmtime(self.start_time))\n            self.final_key = '{}:{}'.format(self.key, self.date)\n        else:\n            self.final_key = self.key",
    "docstring": "sets the final key to be used currently"
  },
  {
    "code": "def send_one_ping(sock: socket, dest_addr: str, icmp_id: int, seq: int, size: int):\n    try:\n        dest_addr = socket.gethostbyname(dest_addr)\n    except socket.gaierror as e:\n        print(\"Cannot resolve {}: Unknown host\".format(dest_addr))\n        raise errors.HostUnknown(dest_addr) from e\n    pseudo_checksum = 0\n    icmp_header = struct.pack(ICMP_HEADER_FORMAT, IcmpType.ECHO_REQUEST, ICMP_DEFAULT_CODE, pseudo_checksum, icmp_id, seq)\n    padding = (size - struct.calcsize(ICMP_TIME_FORMAT) - struct.calcsize(ICMP_HEADER_FORMAT)) * \"Q\"\n    icmp_payload = struct.pack(ICMP_TIME_FORMAT, default_timer()) + padding.encode()\n    real_checksum = checksum(icmp_header + icmp_payload)\n    icmp_header = struct.pack(ICMP_HEADER_FORMAT, IcmpType.ECHO_REQUEST, ICMP_DEFAULT_CODE, socket.htons(real_checksum), icmp_id, seq)\n    packet = icmp_header + icmp_payload\n    sock.sendto(packet, (dest_addr, 0))",
    "docstring": "Sends one ping to the given destination.\n\n    ICMP Header (bits): type (8), code (8), checksum (16), id (16), sequence (16)\n    ICMP Payload: time (double), data\n    ICMP Wikipedia: https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol\n\n    Args:\n        sock: Socket.\n        dest_addr: The destination address, can be an IP address or a domain name. Ex. \"192.168.1.1\"/\"example.com\"\n        icmp_id: ICMP packet id, usually is same as pid.\n        seq: ICMP packet sequence, usually increases from 0 in the same process.\n        size: The ICMP packet payload size in bytes. Note this is only for the payload part.\n\n    Raises:\n        HostUnkown: If destination address is a domain name and cannot resolved."
  },
  {
    "code": "def nextpow2(value):\n    if value >= 1:\n        return 2**np.ceil(np.log2(value)).astype(int)\n    elif value > 0:\n        return 1\n    elif value == 0:\n        return 0\n    else:\n        raise ValueError('Value must be positive')",
    "docstring": "Compute the nearest power of two greater or equal to the input value"
  },
  {
    "code": "def _create_complete_graph(node_ids):\n    g = nx.Graph()\n    g.add_nodes_from(node_ids)\n    for (i, j) in combinations(node_ids, 2):\n        g.add_edge(i, j)\n    return g",
    "docstring": "Create a complete graph from the list of node ids.\n\n    Args:\n        node_ids: a list of node ids\n\n    Returns:\n        An undirected graph (as a networkx.Graph)"
  },
  {
    "code": "def update(self, duration):\n        if duration >= 0:\n            self.histogram.update(duration)\n            self.meter.mark()",
    "docstring": "Add a recorded duration."
  },
  {
    "code": "def c_time_locale():\n    old_time_locale = locale.getlocale(locale.LC_TIME)\n    locale.setlocale(locale.LC_TIME, 'C')\n    yield\n    locale.setlocale(locale.LC_TIME, old_time_locale)",
    "docstring": "Context manager with C LC_TIME locale"
  },
  {
    "code": "def read_scoring_scheme( f, gap_open, gap_extend, gap1=\"-\", gap2=None, **kwargs ):\n    close_it = False\n    if (type(f) == str):\n        f = file(f,\"rt\")\n        close_it = True\n    ss = build_scoring_scheme(\"\".join([line for line in f]),gap_open, gap_extend, gap1=gap1, gap2=gap2, **kwargs)\n    if (close_it):\n        f.close()\n    return ss",
    "docstring": "Initialize scoring scheme from a file containint a blastz style text blob.\n    f can be either a file or the name of a file."
  },
  {
    "code": "def get_modifications(self):\n        for modtype, modclass in modtype_to_modclass.items():\n            if modtype == 'modification':\n                continue\n            stmts = self._get_generic_modification(modclass)\n            self.statements += stmts",
    "docstring": "Extract INDRA Modification Statements from the BioPAX model.\n\n        To extract Modifications, this method reuses the structure of\n        BioPAX Pattern's\n        org.biopax.paxtools.pattern.PatternBox.constrolsStateChange pattern\n        with additional constraints to specify the type of state change\n        occurring (phosphorylation, deubiquitination, etc.)."
  },
  {
    "code": "def check_column_existence(col_name, df, presence=True):\n    if presence:\n        if col_name not in df.columns:\n            msg = \"Ensure that `{}` is in `df.columns`.\"\n            raise ValueError(msg.format(col_name))\n    else:\n        if col_name in df.columns:\n            msg = \"Ensure that `{}` is not in `df.columns`.\"\n            raise ValueError(msg.format(col_name))\n    return None",
    "docstring": "Checks whether or not `col_name` is in `df` and raises a helpful error msg\n    if the desired condition is not met.\n\n    Parameters\n    ----------\n    col_name : str.\n        Should represent a column whose presence in `df` is to be checked.\n    df : pandas DataFrame.\n        The dataframe that will be checked for the presence of `col_name`.\n    presence : bool, optional.\n        If True, then this function checks for the PRESENCE of `col_name` from\n        `df`. If False, then this function checks for the ABSENCE of\n        `col_name` in `df`. Default == True.\n\n    Returns\n    -------\n    None."
  },
  {
    "code": "def _convert(self, image, output=None):\n        with Image.open(image) as im:\n            width, height = im.size\n            co = CanvasObjects()\n            co.add(CanvasImg(image, 1.0, w=width, h=height))\n            return WatermarkDraw(co, tempdir=self.tempdir, pagesize=(width, height)).write(output)",
    "docstring": "Private method for converting a single PNG image to a PDF."
  },
  {
    "code": "def rdopkg_runner():\n    aman = ActionManager()\n    aman.add_actions_modules(actions)\n    aman.fill_aliases()\n    return ActionRunner(action_manager=aman)",
    "docstring": "default rdopkg action runner including rdopkg action modules"
  },
  {
    "code": "def parse_create(prs, conn):\n    prs_create = prs.add_parser(\n        'create', help='create record of specific zone')\n    set_option(prs_create, 'domain')\n    conn_options(prs_create, conn)\n    prs_create.set_defaults(func=create)",
    "docstring": "Create record.\n\n    Arguments:\n\n        prs:  parser object of argparse\n        conn: dictionary of connection information"
  },
  {
    "code": "def create_logout_request(self, destination, issuer_entity_id,\n                              subject_id=None, name_id=None,\n                              reason=None, expire=None, message_id=0,\n                              consent=None, extensions=None, sign=False,\n                              session_indexes=None, sign_alg=None,\n                              digest_alg=None):\n        if subject_id:\n            if self.entity_type == \"idp\":\n                name_id = NameID(text=self.users.get_entityid(subject_id,\n                                                              issuer_entity_id,\n                                                              False))\n            else:\n                name_id = NameID(text=subject_id)\n        if not name_id:\n            raise SAMLError(\"Missing subject identification\")\n        args = {}\n        if session_indexes:\n            sis = []\n            for si in session_indexes:\n                if isinstance(si, SessionIndex):\n                    sis.append(si)\n                else:\n                    sis.append(SessionIndex(text=si))\n            args[\"session_index\"] = sis\n        return self._message(LogoutRequest, destination, message_id,\n                             consent, extensions, sign, name_id=name_id,\n                             reason=reason, not_on_or_after=expire,\n                             issuer=self._issuer(), sign_alg=sign_alg,\n                             digest_alg=digest_alg, **args)",
    "docstring": "Constructs a LogoutRequest\n\n        :param destination: Destination of the request\n        :param issuer_entity_id: The entity ID of the IdP the request is\n            target at.\n        :param subject_id: The identifier of the subject\n        :param name_id: A NameID instance identifying the subject\n        :param reason: An indication of the reason for the logout, in the\n            form of a URI reference.\n        :param expire: The time at which the request expires,\n            after which the recipient may discard the message.\n        :param message_id: Request identifier\n        :param consent: Whether the principal have given her consent\n        :param extensions: Possible extensions\n        :param sign: Whether the query should be signed or not.\n        :param session_indexes: SessionIndex instances or just values\n        :return: A LogoutRequest instance"
  },
  {
    "code": "def _config(self):\n        config = 0\n        if self.mode == MODE_NORMAL:\n            config += (self._t_standby << 5)\n        if self._iir_filter:\n            config += (self._iir_filter << 2)\n        return config",
    "docstring": "Value to be written to the device's config register"
  },
  {
    "code": "def render_payment_form(self):\n        self.context[self.form_context_name] = self.payment_form_cls()\n        return TemplateResponse(self.request, self.payment_template, self.context)",
    "docstring": "Display the DirectPayment for entering payment information."
  },
  {
    "code": "def setup_runner(self):\n        runner = ApplicationRunner(\n            url=self.config['transport_host'],\n            realm=u'realm1',\n            extra={\n                'config': self.config,\n                'handlers': self.handlers,\n            }\n        )\n        return runner",
    "docstring": "Setup instance of runner var"
  },
  {
    "code": "def open_report_template_path(self):\n        directory_name = QFileDialog.getExistingDirectory(\n            self,\n            self.tr('Templates directory'),\n            self.leReportTemplatePath.text(),\n            QFileDialog.ShowDirsOnly)\n        if directory_name:\n            self.leReportTemplatePath.setText(directory_name)",
    "docstring": "Open File dialog to choose the report template path."
  },
  {
    "code": "def instance(cls, interval=5):\n        if not cls._instance:\n            cls._instance = _Messenger(interval)\n        return cls._instance",
    "docstring": "Returns existing instance of messenger. If one does not exist it will\n        be created and returned.\n\n        :param int interval:\n            Number of miliseconds that represents interval when messages will\n            be processed.\n            Note that this parameter will be used only the first time when\n            instance is requested, every other time it will be ignored\n            because existing instance of :class:`._Messenger` is returned."
  },
  {
    "code": "def _run_automation(self, conf):\n        self._fill_form(self._find_form(conf))\n        self._run_scenario(conf)\n        self._delay(conf)",
    "docstring": "1. Fill form.\n        2. Run scenario.\n        3. Delay."
  },
  {
    "code": "def _initialize_trunk_interfaces_to_none(self, switch_ip, replay=True):\n        try:\n            switch_ifs = self._mdriver._get_switch_interfaces(\n                switch_ip, cfg_only=(False if replay else True))\n            if not switch_ifs:\n                LOG.debug(\"Skipping switch %s which has no configured \"\n                          \"interfaces\",\n                          switch_ip)\n                return\n            self._driver.initialize_all_switch_interfaces(\n                switch_ifs, switch_ip)\n        except Exception:\n            with excutils.save_and_reraise_exception():\n                LOG.warning(\"Unable to initialize interfaces to \"\n                            \"switch %(switch_ip)s\",\n                            {'switch_ip': switch_ip})\n                self._mdriver.register_switch_as_inactive(switch_ip,\n                    'replay init_interface')\n        if self._mdriver.is_replay_enabled():\n            return",
    "docstring": "Initialize all nexus interfaces to trunk allowed none."
  },
  {
    "code": "def begin_application(self, req, res):\n        self.loop.create_task(self.http_application.handle_client_request(req, res))",
    "docstring": "Entry point for the application middleware chain for an asyncio\n        event loop."
  },
  {
    "code": "def branch_rate(self, filename=None):\n        if filename is None:\n            el = self.xml\n        else:\n            el = self._get_class_element_by_filename(filename)\n        return float(el.attrib['branch-rate'])",
    "docstring": "Return the global branch rate of the coverage report. If the\n        `filename` file is given, return the branch rate of the file."
  },
  {
    "code": "def init(parser = None):\n    global p,subparsers\n    if parser is None:\n        p = argparse.ArgumentParser()\n    else:\n        p = parser\n    arg = p.add_argument\n    subparsers = p.add_subparsers()",
    "docstring": "module needs to be initialized by 'init'.\n\n    Can be called with parser to use a pre-built parser, otherwise\n    a simple default parser is created"
  },
  {
    "code": "def folder_created_message(self, request, folder):\n        messages.success(request, _(\"Folder {} was created\".format(folder)))",
    "docstring": "Send messages.success message after successful folder creation."
  },
  {
    "code": "def parse_view(query):\n    try:\n        idx = query.lower().index('where')\n        query = query[:idx]\n    except ValueError:\n        pass\n    if not query.endswith(';'):\n        query = query.strip()\n        query += ';'\n    result = _view_stmt.parseString(query)\n    return View(result)",
    "docstring": "Parses asql query to view object.\n\n    Args:\n        query (str): asql query\n\n    Returns:\n        View instance: parsed view."
  },
  {
    "code": "def create_os_dummy_rtr(self, tenant_id, fw_dict, is_fw_virt=False):\n        res = fw_const.OS_DUMMY_RTR_CREATE_SUCCESS\n        tenant_name = fw_dict.get('tenant_name')\n        try:\n            rtr_id = fw_dict.get('router_id')\n            if rtr_id is None:\n                LOG.error(\"Invalid router id, attaching dummy interface\"\n                          \" failed\")\n                return False\n            if is_fw_virt:\n                net_id = subnet_id = None\n            else:\n                net_id, subnet_id = (\n                    self._attach_dummy_intf_rtr(tenant_id, tenant_name,\n                                                rtr_id))\n                if net_id is None or subnet_id is None:\n                    LOG.error(\"Invalid net_id or subnet_id, creating dummy\"\n                              \" interface failed\")\n                    return False\n        except Exception as exc:\n            LOG.error(\"Creation of Openstack Router failed \"\n                      \"tenant %(tenant)s, Exception %(exc)s\",\n                      {'tenant': tenant_id, 'exc': str(exc)})\n            res = fw_const.OS_DUMMY_RTR_CREATE_FAIL\n        self.store_fw_db_router(tenant_id, net_id, subnet_id, rtr_id, res)\n        return True",
    "docstring": "Create the dummy interface and attach it to router.\n\n        Attach the dummy interface to the Openstack router and store the\n        info in DB."
  },
  {
    "code": "def close_pages_for_specific_sm_id(self, sm_id):\n        states_to_be_closed = []\n        for state_identifier in self.tabs:\n            state_m = self.tabs[state_identifier][\"state_m\"]\n            if state_m.state.get_state_machine().state_machine_id == sm_id:\n                states_to_be_closed.append(state_identifier)\n        for state_identifier in states_to_be_closed:\n            self.close_page(state_identifier, delete=False)",
    "docstring": "Closes all tabs of the states editor for a specific sm_id"
  },
  {
    "code": "def root(self) -> \"GameNode\":\n        node = self\n        while node.parent:\n            node = node.parent\n        return node",
    "docstring": "Gets the root node, i.e., the game."
  },
  {
    "code": "def reference_year(self, index):\n        ref_date = self.reference_date(index)\n        try:\n            return parse(ref_date).year\n        except ValueError:\n            matched = re.search(r\"\\d{4}\", ref_date)\n            if matched:\n                return int(matched.group())\n            else:\n                return \"\"",
    "docstring": "Return the reference publication year."
  },
  {
    "code": "def autocomplete(self):\n        self.facet = False\n        params = self.solr_params()\n        logging.info(\"PARAMS=\" + str(params))\n        results = self.solr.search(**params)\n        logging.info(\"Docs found: {}\".format(results.hits))\n        return self._process_autocomplete_results(results)",
    "docstring": "Execute solr autocomplete"
  },
  {
    "code": "def file(mode='w+b', suffix='', prefix='tmp', dir=None, ignore_missing=False):\n    if isinstance(suffix, int):\n        raise ValueError('Passed an integer as suffix. Did you want to '\n                         'specify the deprecated parameter `bufsize`?')\n    fp = tempfile.NamedTemporaryFile(mode=mode,\n                                     suffix=suffix,\n                                     prefix=prefix,\n                                     dir=dir,\n                                     delete=False)\n    try:\n        yield fp\n    finally:\n        try:\n            os.unlink(fp.name)\n        except OSError as e:\n            if e.errno != ENOENT or ignore_missing is False:\n                raise",
    "docstring": "Create a temporary file.\n\n    A contextmanager that creates and returns a named temporary file and\n    removes it on exit. Differs from temporary file functions in\n    :mod:`tempfile` by not deleting the file once it is closed, making it safe\n    to write and close the file and then processing it with an external\n    program.\n\n    If the temporary file is moved elsewhere later on, `ignore_missing` should\n    be set to `True`.\n\n    :param mode: Passed on to :func:`tempfile.NamedTemporaryFile`.\n    :param suffix: Passed on to :func:`tempfile.NamedTemporaryFile`.\n    :param prefix: Passed on to :func:`tempfile.NamedTemporaryFile`.\n    :param dir: Passed on to :func:`tempfile.NamedTemporaryFile`.\n    :param ignore_missing: If set to `True`, no exception will be raised if the\n                           temporary file has been deleted when trying to clean\n                           it up.\n    :return: A file object with a `.name`."
  },
  {
    "code": "def query_tracking_code(tracking_code, year=None):\n    payload = {\n        'Anio': year or datetime.now().year,\n        'Tracking': tracking_code,\n    }\n    response = _make_request(TRACKING_URL, payload)\n    if not response['d']:\n        return []\n    data = response['d'][0]\n    destination = data['RetornoCadena6']\n    payload.update({\n        'Destino': destination,\n    })\n    response = _make_request(TRACKING_DETAIL_URL, payload)\n    return _process_detail(response['d'])",
    "docstring": "Given a tracking_code return a list of events related the tracking code"
  },
  {
    "code": "def create_dataset(\n        self,\n        parent,\n        dataset,\n        retry=google.api_core.gapic_v1.method.DEFAULT,\n        timeout=google.api_core.gapic_v1.method.DEFAULT,\n        metadata=None,\n    ):\n        if \"create_dataset\" not in self._inner_api_calls:\n            self._inner_api_calls[\n                \"create_dataset\"\n            ] = google.api_core.gapic_v1.method.wrap_method(\n                self.transport.create_dataset,\n                default_retry=self._method_configs[\"CreateDataset\"].retry,\n                default_timeout=self._method_configs[\"CreateDataset\"].timeout,\n                client_info=self._client_info,\n            )\n        request = service_pb2.CreateDatasetRequest(parent=parent, dataset=dataset)\n        if metadata is None:\n            metadata = []\n        metadata = list(metadata)\n        try:\n            routing_header = [(\"parent\", parent)]\n        except AttributeError:\n            pass\n        else:\n            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(\n                routing_header\n            )\n            metadata.append(routing_metadata)\n        return self._inner_api_calls[\"create_dataset\"](\n            request, retry=retry, timeout=timeout, metadata=metadata\n        )",
    "docstring": "Creates a dataset.\n\n        Example:\n            >>> from google.cloud import automl_v1beta1\n            >>>\n            >>> client = automl_v1beta1.AutoMlClient()\n            >>>\n            >>> parent = client.location_path('[PROJECT]', '[LOCATION]')\n            >>>\n            >>> # TODO: Initialize `dataset`:\n            >>> dataset = {}\n            >>>\n            >>> response = client.create_dataset(parent, dataset)\n\n        Args:\n            parent (str): The resource name of the project to create the dataset for.\n            dataset (Union[dict, ~google.cloud.automl_v1beta1.types.Dataset]): The dataset to create.\n\n                If a dict is provided, it must be of the same form as the protobuf\n                message :class:`~google.cloud.automl_v1beta1.types.Dataset`\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.automl_v1beta1.types.Dataset` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def zip(value=data, mu=mu, psi=psi):\n    like = 0.0\n    for x in value:\n        if not x:\n            like += np.log((1. - psi) + psi * np.exp(-mu))\n        else:\n            like += np.log(psi) + poisson_like(x, mu)\n    return like",
    "docstring": "Zero-inflated Poisson likelihood"
  },
  {
    "code": "def run_command(cmd_to_run):\n    with tempfile.TemporaryFile() as stdout_file, tempfile.TemporaryFile() as stderr_file:\n        popen = subprocess.Popen(cmd_to_run, stdout=stdout_file, stderr=stderr_file)\n        popen.wait()\n        stderr_file.seek(0)\n        stdout_file.seek(0)\n        stderr = stderr_file.read()\n        stdout = stdout_file.read()\n        if six.PY3:\n            stderr = stderr.decode()\n            stdout = stdout.decode()\n        return stderr, stdout",
    "docstring": "Wrapper around subprocess that pipes the stderr and stdout from `cmd_to_run`\n    to temporary files. Using the temporary files gets around subprocess.PIPE's\n    issues with handling large buffers.\n\n    Note: this command will block the python process until `cmd_to_run` has completed.\n\n    Returns a tuple, containing the stderr and stdout as strings."
  },
  {
    "code": "def load_crawler(self, crawler, url, ignore_regex):\n        self.process = CrawlerProcess(self.cfg.get_scrapy_options())\n        self.process.crawl(\n            crawler,\n            self.helper,\n            url=url,\n            config=self.cfg,\n            ignore_regex=ignore_regex)",
    "docstring": "Loads the given crawler with the given url.\n\n        :param class crawler: class of the crawler to load\n        :param str url: url to start the crawler with\n        :param regex ignore_regex: to be able to ignore urls that match this\n                                   regex code"
  },
  {
    "code": "def _document_root(self, fully_qualified=True):\n        nsmap = {\"xsi\": utils.NAMESPACES[\"xsi\"], \"xlink\": utils.NAMESPACES[\"xlink\"]}\n        if fully_qualified:\n            nsmap[\"mets\"] = utils.NAMESPACES[\"mets\"]\n        else:\n            nsmap[None] = utils.NAMESPACES[\"mets\"]\n        attrib = {\n            \"{}schemaLocation\".format(utils.lxmlns(\"xsi\")): utils.SCHEMA_LOCATIONS\n        }\n        if self.objid:\n            attrib[\"OBJID\"] = self.objid\n        return etree.Element(utils.lxmlns(\"mets\") + \"mets\", nsmap=nsmap, attrib=attrib)",
    "docstring": "Return the mets Element for the document root."
  },
  {
    "code": "def parse(self, words):\n        def exact(words):\n            try:\n                return float(words)\n            except:\n                return None\n        guess = exact(words)\n        if guess is not None:\n            return guess\n        split = words.split(' ')\n        if split[-1] in self.__fractions__:\n            split[-1] = self.__fractions__[split[-1]]\n        elif split[-1] in self.__ordinals__:\n            split[-1] = self.__ordinals__[split[-1]]\n        parsed_ordinals = ' '.join(split)\n        return self.parseFloat(parsed_ordinals)",
    "docstring": "A general method for parsing word-representations of numbers.\n        Supports floats and integers.\n\n        Args:\n            words (str): Description of an arbitrary number.\n\n        Returns:\n            A double representation of the words."
  },
  {
    "code": "def generate(self):\n        s = self._docstring\n        s += self._get_source().replace(\n            'endpoints = {}',\n            'endpoints = ' + self._config_src\n        ).replace(\n            'logger.setLevel(logging.INFO)',\n            'logger.setLevel(logging.%s)' % self.config.logging_level\n        )\n        return s",
    "docstring": "Generate Lambda function source; return it as a string.\n\n        :rtype: str\n        :returns: lambda function source"
  },
  {
    "code": "def write(self, text):\n        if self.disabled:\n            self.write_with_encoding(self.encoding, text)\n            return\n        to_write, text = split_writable_text(self.encoder, text, self.encoding)\n        if to_write:\n            self.write_with_encoding(self.encoding, to_write)\n        while text:\n            encoding = self.encoder.find_suitable_encoding(text[0])\n            if not encoding:\n                self._handle_character_failed(text[0])\n                text = text[1:]\n                continue\n            to_write, text = split_writable_text(self.encoder, text, encoding)\n            if to_write:\n                self.write_with_encoding(encoding, to_write)",
    "docstring": "Write the text, automatically switching encodings."
  },
  {
    "code": "def _detect_encoding(data=None):\n    import locale\n    enc_list = ['utf-8', 'latin-1', 'iso8859-1', 'iso8859-2',\n                'utf-16', 'cp720']\n    code = locale.getpreferredencoding(False)\n    if data is None:\n        return code\n    if code.lower() not in enc_list:\n        enc_list.insert(0, code.lower())\n    for c in enc_list:\n        try:\n            for line in data:\n                line.decode(c)\n        except (UnicodeDecodeError, UnicodeError, AttributeError):\n            continue\n        return c\n    print(\"Encoding not detected. Please pass encoding value manually\")",
    "docstring": "Return the default system encoding. If data is passed, try\n    to decode the data with the default system encoding or from a short\n    list of encoding types to test.\n\n    Args:\n        data - list of lists\n    Returns:\n        enc - system encoding"
  },
  {
    "code": "def get_approximate_times(times: List[int]) -> List[int]:\n    approximate_times = []\n    for time in times:\n        hour = int(time/HOUR_TO_TWENTY_FOUR) % 24\n        minute = time % HOUR_TO_TWENTY_FOUR\n        approximate_time = datetime.now()\n        approximate_time = approximate_time.replace(hour=hour, minute=minute)\n        start_time_range = approximate_time - timedelta(minutes=30)\n        end_time_range = approximate_time + timedelta(minutes=30)\n        approximate_times.extend([start_time_range.hour * HOUR_TO_TWENTY_FOUR + start_time_range.minute,\n                                  end_time_range.hour * HOUR_TO_TWENTY_FOUR + end_time_range.minute])\n    return approximate_times",
    "docstring": "Given a list of times that follow a word such as ``about``,\n    we return a list of times that could appear in the query as a result\n    of this. For example if ``about 7pm`` appears in the utterance, then\n    we also want to add ``1830`` and ``1930``."
  },
  {
    "code": "def save(self):\n        redis = type(self).get_redis()\n        pipe = to_pipeline(redis)\n        pipe.hset(self.key(), 'id', self.id)\n        for fieldname, field in self.proxy:\n            if not isinstance(field, Relation):\n                field.save(getattr(self, fieldname), pipe, commit=False)\n        pipe.sadd(type(self).members_key(), self.id)\n        pipe.execute()\n        if self.notify:\n            data = json.dumps({\n                'event': 'create' if not self._persisted else 'update',\n                'data': self.to_json(),\n            })\n            redis.publish(type(self).cls_key(), data)\n            redis.publish(self.key(), data)\n        self._persisted = True\n        return self",
    "docstring": "Persists this object to the database. Each field knows how to store\n        itself so we don't have to worry about it"
  },
  {
    "code": "def load_word_file(filename):\n    words_file = resource_filename(__name__, \"words/%s\" % filename)\n    handle = open(words_file, 'r')\n    words = handle.readlines()\n    handle.close()\n    return words",
    "docstring": "Loads a words file as a list of lines"
  },
  {
    "code": "def clean(self, *args, **kwargs):\n        if not self.pk:\n            node = self.node\n            if node.participation_settings.comments_allowed is False:\n                raise ValidationError(\"Comments not allowed for this node\")\n            if 'nodeshot.core.layers' in settings.INSTALLED_APPS:\n                layer = node.layer\n                if layer.participation_settings.comments_allowed is False:\n                    raise ValidationError(\"Comments not allowed for this layer\")",
    "docstring": "Check if comments can be inserted for parent node or parent layer"
  },
  {
    "code": "def dict_to_switch(d):\n    def lookup(query):\n        return d[query]\n    lookup._always_inline_ = True\n    unrolling_items = unrolling_iterable(d.items())\n    return lookup",
    "docstring": "Convert of dictionary with integer keys to a switch statement."
  },
  {
    "code": "def close_handle(self):\n        try:\n            if hasattr(self.hThread, 'close'):\n                self.hThread.close()\n            elif self.hThread not in (None, win32.INVALID_HANDLE_VALUE):\n                win32.CloseHandle(self.hThread)\n        finally:\n            self.hThread = None",
    "docstring": "Closes the handle to the thread.\n\n        @note: Normally you don't need to call this method. All handles\n            created by I{WinAppDbg} are automatically closed when the garbage\n            collector claims them."
  },
  {
    "code": "def notifications_view(request):\n    page_name = \"Your Notifications\"\n    notifications = list(request.user.notifications.all())\n    request.user.notifications.mark_all_as_read()\n    return render_to_response(\"list_notifications.html\", {\n        \"page_name\": page_name,\n        \"notifications\": notifications,\n        }, context_instance=RequestContext(request))",
    "docstring": "Show a user their notifications."
  },
  {
    "code": "def identify_gwf(origin, filepath, fileobj, *args, **kwargs):\n    if fileobj is not None:\n        loc = fileobj.tell()\n        fileobj.seek(0)\n        try:\n            if fileobj.read(4) == GWF_SIGNATURE:\n                return True\n        finally:\n            fileobj.seek(loc)\n    if filepath is not None:\n        if filepath.endswith('.gwf'):\n            return True\n        if filepath.endswith(('.lcf', '.cache')):\n            try:\n                cache = read_cache(filepath)\n            except IOError:\n                return False\n            else:\n                if cache[0].path.endswith('.gwf'):\n                    return True",
    "docstring": "Identify a filename or file object as GWF\n\n    This function is overloaded in that it will also identify a cache file\n    as 'gwf' if the first entry in the cache contains a GWF file extension"
  },
  {
    "code": "def services(self):\n        if self._resources is None:\n            self.__init()\n        if \"services\" in self._resources:\n            url = self._url + \"/services\"\n            return _services.Services(url=url,\n                                      securityHandler=self._securityHandler,\n                                      proxy_url=self._proxy_url,\n                                      proxy_port=self._proxy_port,\n                                      initialize=True)\n        else:\n            return None",
    "docstring": "Gets the services object which will provide the ArcGIS Server's\n        admin information about services and folders."
  },
  {
    "code": "def get_machines(self, origin, hostnames):\n        hostnames = {\n            hostname: True\n            for hostname in hostnames\n        }\n        machines = origin.Machines.read(hostnames=hostnames)\n        machines = [\n            machine\n            for machine in machines\n            if hostnames.pop(machine.hostname, False)\n        ]\n        if len(hostnames) > 0:\n            raise CommandError(\n                \"Unable to find %s %s.\" % (\n                    \"machines\" if len(hostnames) > 1 else \"machine\",\n                    ','.join(hostnames)))\n        return machines",
    "docstring": "Return a set of machines based on `hostnames`.\n\n        Any hostname that is not found will result in an error."
  },
  {
    "code": "def connected(G, method_name, **kwargs):\n    warnings.warn(\"To be removed in 0.8. Use GraphCollection.analyze instead.\",\n                  DeprecationWarning)\n    return G.analyze(['connected', method_name], **kwargs)",
    "docstring": "Performs analysis methods from networkx.connected on each graph in the\n    collection.\n\n    Parameters\n    ----------\n    G : :class:`.GraphCollection`\n        The :class:`.GraphCollection` to analyze. The specified method will be\n        applied to each graph in ``G``.\n    method : string\n        Name of method in networkx.connected.\n    **kwargs : kwargs\n        Keyword arguments, passed directly to method.\n\n    Returns\n    -------\n    results : dict\n        Keys are graph indices, values are output of method for that graph.\n\n    Raises\n    ------\n    ValueError\n        If name is not in networkx.connected, or if no such method exists."
  },
  {
    "code": "def render_or_send(func, message):\n    if request.endpoint != func.func_name:\n        mail.send(message)\n    if (current_user.is_authenticated() and current_user.superuser):\n        return render_template('debug_email.html', message=message)",
    "docstring": "Renders an email message for debugging or actually sends it."
  },
  {
    "code": "def make_id(self):\n        if self.url_id is None:\n            self.url_id = select([func.coalesce(func.max(self.__class__.url_id + 1), 1)],\n                self.__class__.parent == self.parent)",
    "docstring": "Create a new URL id that is unique to the parent container"
  },
  {
    "code": "def hideValue(self, value):\n        list.remove(self, value)\n        self._hidden.append(value)",
    "docstring": "Hide the given value from the domain\n\n        After that call the given value won't be seen as a possible value\n        on that domain anymore. The hidden value will be restored when the\n        previous saved state is popped.\n\n        @param value: Object currently available in the domain"
  },
  {
    "code": "def unicoder(p):\n    if isinstance(p, unicode):\n        return p\n    if isinstance(p, str):\n        return decoder(p)\n    else:\n        return unicode(decoder(p))",
    "docstring": "Make sure a Unicode string is returned"
  },
  {
    "code": "def _prepare_bam_file(bam_file, tmp_dir, config):\n    sort_mode = _get_sort_order(bam_file, config)\n    if sort_mode != \"queryname\":\n        bam_file = sort(bam_file, config, \"queryname\")\n    return bam_file",
    "docstring": "Pipe sort by name cmd in case sort by coordinates"
  },
  {
    "code": "def multipleOrderComparison(cls, orders):\n    comparers = [ (o.keyfn, 1 if o.isAscending() else -1) for o in orders]\n    def cmpfn(a, b):\n      for keyfn, ascOrDesc in comparers:\n        comparison = cmp(keyfn(a), keyfn(b)) * ascOrDesc\n        if comparison is not 0:\n          return comparison\n      return 0\n    return cmpfn",
    "docstring": "Returns a function that will compare two items according to `orders`"
  },
  {
    "code": "def list_tags(self):\n        from highton.models.tag import Tag\n        return fields.ListField(\n            name=self.ENDPOINT,\n            init_class=Tag\n        ).decode(\n            self.element_from_string(\n                self._get_request(\n                    endpoint=self.ENDPOINT + '/' + str(self.id) + '/' + Tag.ENDPOINT,\n                ).text\n            )\n        )",
    "docstring": "Get the tags of current object\n\n        :return: the tags\n        :rtype: list"
  },
  {
    "code": "def gotoHome(self):\r\n        mode = QTextCursor.MoveAnchor\r\n        if QApplication.instance().keyboardModifiers() == Qt.ShiftModifier:\r\n            mode = QTextCursor.KeepAnchor\r\n        cursor = self.textCursor()\r\n        block  = projex.text.nativestring(cursor.block().text())\r\n        cursor.movePosition( QTextCursor.StartOfBlock, mode )\r\n        if block.startswith('>>> '):\r\n            cursor.movePosition(QTextCursor.Right, mode, 4)\r\n        elif block.startswith('... '):\r\n            match = re.match('...\\s*', block)\r\n            cursor.movePosition(QTextCursor.Right, mode, match.end())\r\n        self.setTextCursor(cursor)",
    "docstring": "Navigates to the home position for the edit."
  },
  {
    "code": "def is_compliant(self, path):\n        if not os.path.isdir(path):\n            log('Path specified %s is not a directory.' % path, level=ERROR)\n            raise ValueError(\"%s is not a directory.\" % path)\n        if not self.recursive:\n            return super(DirectoryPermissionAudit, self).is_compliant(path)\n        compliant = True\n        for root, dirs, _ in os.walk(path):\n            if len(dirs) > 0:\n                continue\n            if not super(DirectoryPermissionAudit, self).is_compliant(root):\n                compliant = False\n                continue\n        return compliant",
    "docstring": "Checks if the directory is compliant.\n\n        Used to determine if the path specified and all of its children\n        directories are in compliance with the check itself.\n\n        :param path: the directory path to check\n        :returns: True if the directory tree is compliant, otherwise False."
  },
  {
    "code": "def odt_to_ri(f, res, nm):\n    r\n    km = (2 * np.pi * nm) / res\n    ri = nm * np.sqrt(f / km**2 + 1)\n    negrootcoord = np.where(ri.real < 0)\n    ri[negrootcoord] *= -1\n    return ri",
    "docstring": "r\"\"\"Convert the ODT object function to refractive index\n\n    In :abbr:`ODT (Optical Diffraction Tomography)`, the object function\n    is defined by the Helmholtz equation\n\n    .. math::\n\n        f(\\mathbf{r})  =  k_\\mathrm{m}^2 \\left[\n            \\left( \\frac{n(\\mathbf{r})}{n_\\mathrm{m}} \\right)^2 - 1\n            \\right]\n\n    with :math:`k_\\mathrm{m} = \\frac{2\\pi n_\\mathrm{m}}{\\lambda}`.\n    By inverting this equation, we obtain the refractive index\n    :math:`n(\\mathbf{r})`.\n\n    .. math::\n\n        n(\\mathbf{r})  = n_\\mathrm{m}\n            \\sqrt{\\frac{f(\\mathbf{r})}{k_\\mathrm{m}^2} + 1 }\n\n    Parameters\n    ----------\n    f: n-dimensional ndarray\n        The reconstructed object function :math:`f(\\mathbf{r})`.\n    res: float\n        The size of the vacuum wave length :math:`\\lambda` in pixels.\n    nm: float\n        The refractive index of the medium :math:`n_\\mathrm{m}` that\n        surrounds the object in :math:`f(\\mathbf{r})`.\n\n    Returns\n    -------\n    ri: n-dimensional ndarray\n        The complex refractive index :math:`n(\\mathbf{r})`.\n\n    Notes\n    -----\n    Because this function computes the root of a complex number, there\n    are several solutions to the refractive index. Always the positive\n    (real) root of the refractive index is used."
  },
  {
    "code": "def __ensure_suffix_stem(t, suffix):\n    tpath = str(t)\n    if not tpath.endswith(suffix):\n        stem = tpath\n        tpath += suffix\n        return tpath, stem\n    else:\n        stem, ext = os.path.splitext(tpath)\n    return t, stem",
    "docstring": "Ensure that the target t has the given suffix, and return the file's stem."
  },
  {
    "code": "async def query(cls, query: str,\n                    variables: Optional[Mapping[str, Any]] = None,\n                    ) -> Any:\n        gql_query = {\n            'query': query,\n            'variables': variables if variables else {},\n        }\n        rqst = Request(cls.session, 'POST', '/admin/graphql')\n        rqst.set_json(gql_query)\n        async with rqst.fetch() as resp:\n            return await resp.json()",
    "docstring": "Sends the GraphQL query and returns the response.\n\n        :param query: The GraphQL query string.\n        :param variables: An optional key-value dictionary\n            to fill the interpolated template variables\n            in the query.\n\n        :returns: The object parsed from the response JSON string."
  },
  {
    "code": "def pprint(self, ind):\n        pp = pprint.PrettyPrinter(indent=ind)\n        pp.pprint(self.tree)",
    "docstring": "pretty prints the tree with indentation"
  },
  {
    "code": "def song_play(self, song):\n\t\tif 'storeId' in song:\n\t\t\tsong_id = song['storeId']\n\t\telif 'trackId' in song:\n\t\t\tsong_id = song['trackId']\n\t\telse:\n\t\t\tsong_id = song['id']\n\t\tsong_duration = song['durationMillis']\n\t\tevent = mc_calls.ActivityRecordRealtime.play(song_id, song_duration)\n\t\tresponse = self._call(\n\t\t\tmc_calls.ActivityRecordRealtime,\n\t\t\tevent\n\t\t)\n\t\treturn True if response.body['eventResults'][0]['code'] == 'OK' else False",
    "docstring": "Add play to song play count.\n\n\t\tParameters:\n\t\t\tsong (dict): A song dict.\n\n\t\tReturns:\n\t\t\tbool: ``True`` if successful, ``False`` if not."
  },
  {
    "code": "def get_item_name(self, item, parent):\n        names = self.get_name_elements(item)\n        if not names:\n            raise MissingNameElementError\n        name = names[0].text\n        prefix = self.item_name_prefix(parent)\n        if prefix:\n            name = prefix + name\n        return name",
    "docstring": "Returns the value of the first name element found inside of element"
  },
  {
    "code": "def sunrise(self, date=None, local=True, use_elevation=True):\n        if local and self.timezone is None:\n            raise ValueError(\"Local time requested but Location has no timezone set.\")\n        if self.astral is None:\n            self.astral = Astral()\n        if date is None:\n            date = datetime.date.today()\n        elevation = self.elevation if use_elevation else 0\n        sunrise = self.astral.sunrise_utc(date, self.latitude, self.longitude, elevation)\n        if local:\n            return sunrise.astimezone(self.tz)\n        else:\n            return sunrise",
    "docstring": "Return sunrise time.\n\n        Calculates the time in the morning when the sun is a 0.833 degrees\n        below the horizon. This is to account for refraction.\n\n        :param date: The date for which to calculate the sunrise time.\n                     If no date is specified then the current date will be used.\n        :type date:  :class:`~datetime.date`\n\n        :param local: True  = Time to be returned in location's time zone;\n                      False = Time to be returned in UTC.\n                      If not specified then the time will be returned in local time\n        :type local:  bool\n\n        :param use_elevation: True  = Return times that allow for the location's elevation;\n                              False = Return times that don't use elevation.\n                              If not specified then times will take elevation into account.\n        :type use_elevation:  bool\n\n        :returns: The date and time at which sunrise occurs.\n        :rtype: :class:`~datetime.datetime`"
  },
  {
    "code": "def disconnect_child(self, sprite, *handlers):\n        handlers = handlers or self._child_handlers.get(sprite, [])\n        for handler in list(handlers):\n            if sprite.handler_is_connected(handler):\n                sprite.disconnect(handler)\n            if handler in self._child_handlers.get(sprite, []):\n                self._child_handlers[sprite].remove(handler)\n        if not self._child_handlers[sprite]:\n            del self._child_handlers[sprite]",
    "docstring": "disconnects from child event. if handler is not specified, will\n        disconnect from all the child sprite events"
  },
  {
    "code": "def _put_bucket_logging(self):\n        logging_config = {}\n        if self.s3props['logging']['enabled']:\n            logging_config = {\n                'LoggingEnabled': {\n                    'TargetBucket': self.s3props['logging']['logging_bucket'],\n                    'TargetGrants': self.s3props['logging']['logging_grants'],\n                    'TargetPrefix': self.s3props['logging']['logging_bucket_prefix']\n                }\n            }\n        _response = self.s3client.put_bucket_logging(Bucket=self.bucket, BucketLoggingStatus=logging_config)\n        LOG.debug('Response setting up S3 logging: %s', _response)\n        LOG.info('S3 logging configuration updated')",
    "docstring": "Adds bucket logging policy to bucket for s3 access requests"
  },
  {
    "code": "def bel_process_belrdf():\n    if request.method == 'OPTIONS':\n        return {}\n    response = request.body.read().decode('utf-8')\n    body = json.loads(response)\n    belrdf = body.get('belrdf')\n    bp = bel.process_belrdf(belrdf)\n    return _stmts_from_proc(bp)",
    "docstring": "Process BEL RDF and return INDRA Statements."
  },
  {
    "code": "def resample_nn_1d(a, centers):\n    ix = []\n    for center in centers:\n        index = (np.abs(a - center)).argmin()\n        if index not in ix:\n            ix.append(index)\n    return ix",
    "docstring": "Return one-dimensional nearest-neighbor indexes based on user-specified centers.\n\n    Parameters\n    ----------\n    a : array-like\n        1-dimensional array of numeric values from which to\n        extract indexes of nearest-neighbors\n    centers : array-like\n        1-dimensional array of numeric values representing a subset of values to approximate\n\n    Returns\n    -------\n        An array of indexes representing values closest to given array values"
  },
  {
    "code": "def get_enabled():\n    ret = set()\n    for name in _iter_service_names():\n        if _service_is_upstart(name):\n            if _upstart_is_enabled(name):\n                ret.add(name)\n        else:\n            if _service_is_sysv(name):\n                if _sysv_is_enabled(name):\n                    ret.add(name)\n    return sorted(ret)",
    "docstring": "Return the enabled services\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' service.get_enabled"
  },
  {
    "code": "def image_list(list_aliases=False, remote_addr=None,\n               cert=None, key=None, verify_cert=True):\n    client = pylxd_client_get(remote_addr, cert, key, verify_cert)\n    images = client.images.all()\n    if list_aliases:\n        return {i.fingerprint: [a['name'] for a in i.aliases] for i in images}\n    return map(_pylxd_model_to_dict, images)",
    "docstring": "Lists all images from the LXD.\n\n        list_aliases :\n\n            Return a dict with the fingerprint as key and\n            a list of aliases as value instead.\n\n        remote_addr :\n            An URL to a remote Server, you also have to give cert and key if\n            you provide remote_addr and its a TCP Address!\n\n            Examples:\n                https://myserver.lan:8443\n                /var/lib/mysocket.sock\n\n        cert :\n            PEM Formatted SSL Certificate.\n\n            Examples:\n                ~/.config/lxc/client.crt\n\n        key :\n            PEM Formatted SSL Key.\n\n            Examples:\n                ~/.config/lxc/client.key\n\n        verify_cert : True\n            Wherever to verify the cert, this is by default True\n            but in the most cases you want to set it off as LXD\n            normaly uses self-signed certificates.\n\n        CLI Examples:\n\n        .. code-block:: bash\n\n            $ salt '*' lxd.image_list true --out=json\n            $ salt '*' lxd.image_list --out=json"
  },
  {
    "code": "def numberOfConnectedDistalSynapses(self, cells=None):\n    if cells is None:\n      cells = xrange(self.numberOfCells())\n    n = _countWhereGreaterEqualInRows(self.internalDistalPermanences, cells,\n                                      self.connectedPermanenceDistal)\n    for permanences in self.distalPermanences:\n      n += _countWhereGreaterEqualInRows(permanences, cells,\n                                         self.connectedPermanenceDistal)\n    return n",
    "docstring": "Returns the number of connected distal synapses on these cells.\n\n    Parameters:\n    ----------------------------\n    @param  cells (iterable)\n            Indices of the cells. If None return count for all cells."
  },
  {
    "code": "def rollback(self, rb_id=1):\n        rpc_command = '<Unlock/><Rollback><Previous>{rb_id}</Previous></Rollback><Lock/>'.format(rb_id=rb_id)\n        self._execute_rpc(rpc_command)",
    "docstring": "Rollback the last committed configuration.\n\n        :param rb_id: Rollback a specific number of steps. Default: 1"
  },
  {
    "code": "def _update_explicit_bucket_count(a_float, dist):\n    buckets = dist.explicitBuckets\n    if buckets is None:\n        raise ValueError(_BAD_UNSET_BUCKETS % (u'explicit buckets'))\n    bucket_counts = dist.bucketCounts\n    bounds = buckets.bounds\n    if len(bucket_counts) < len(bounds) + 1:\n        raise ValueError(_BAD_LOW_BUCKET_COUNT)\n    bucket_counts[bisect.bisect(bounds, a_float)] += 1",
    "docstring": "Adds `a_float` to `dist`, updating its explicit buckets.\n\n    Args:\n      a_float (float): a new value\n      dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):\n        the Distribution being updated\n\n    Raises:\n      ValueError: if `dist` does not already have explict buckets defined\n      ValueError: if there are not enough bucket count fields in `dist`"
  },
  {
    "code": "def is_sw_writable(self):\n        sw = self.get_property('sw')\n        return sw in (rdltypes.AccessType.rw, rdltypes.AccessType.rw1,\n                        rdltypes.AccessType.w, rdltypes.AccessType.w1)",
    "docstring": "Field is writable by software"
  },
  {
    "code": "def save(self):\n        out = Outgest(self.output, self.selection_array.astype('uint8'), self.headers, self.config_path)\n        out.save()\n        out.upload()",
    "docstring": "Save as a FITS file and attempt an upload if designated in the configuration file"
  },
  {
    "code": "def _daterange(self, recarr, date_range):\n        idx = self._datetime64_index(recarr)\n        if idx and len(recarr):\n            dts = recarr[idx]\n            mask = Series(np.zeros(len(dts)), index=dts)\n            start, end = _start_end(date_range, dts)\n            mask[start:end] = 1.0\n            return recarr[mask.values.astype(bool)]\n        return recarr",
    "docstring": "Given a recarr, slice out the given artic.date.DateRange if a\n        datetime64 index exists"
  },
  {
    "code": "def apply(self, func, args=(), **kwargs):\n        kwargs.pop('shortcut', None)\n        applied = (func(ds, *args, **kwargs) for ds in self._iter_grouped())\n        combined = self._combine(applied)\n        return combined.rename({self._resample_dim: self._dim})",
    "docstring": "Apply a function over each Dataset in the groups generated for\n        resampling  and concatenate them together into a new Dataset.\n\n        `func` is called like `func(ds, *args, **kwargs)` for each dataset `ds`\n        in this group.\n\n        Apply uses heuristics (like `pandas.GroupBy.apply`) to figure out how\n        to stack together the datasets. The rule is:\n        1. If the dimension along which the group coordinate is defined is\n           still in the first grouped item after applying `func`, then stack\n           over this dimension.\n        2. Otherwise, stack over the new dimension given by name of this\n           grouping (the argument to the `groupby` function).\n\n        Parameters\n        ----------\n        func : function\n            Callable to apply to each sub-dataset.\n        args : tuple, optional\n            Positional arguments passed on to `func`.\n        **kwargs\n            Used to call `func(ds, **kwargs)` for each sub-dataset `ar`.\n\n        Returns\n        -------\n        applied : Dataset or DataArray\n            The result of splitting, applying and combining this dataset."
  },
  {
    "code": "def get_bin_version_str(bin_path, version_flag='-v', kw={}):\n    try:\n        prog = _get_exec_binary(bin_path, kw)\n        version_str = version_expr.search(\n            check_output([prog, version_flag], **kw).decode(locale)\n        ).groups()[0]\n    except OSError:\n        logger.warning(\"failed to execute '%s'\", bin_path)\n        return None\n    except Exception:\n        logger.exception(\n            \"encountered unexpected error while trying to find version of \"\n            \"'%s':\", bin_path\n        )\n        return None\n    logger.info(\"'%s' is version '%s'\", bin_path, version_str)\n    return version_str",
    "docstring": "Get the version string through the binary."
  },
  {
    "code": "def _send_command(self, command, expected_bytes):\n        response = self.con.send_xid_command(command, expected_bytes)\n        return response",
    "docstring": "Send an XID command to the device"
  },
  {
    "code": "def shift_up_right(self, times=1):\n        try:\n            return Location(self._rank + times, self._file + times)\n        except IndexError as e:\n            raise IndexError(e)",
    "docstring": "Finds Location shifted up right by 1\n\n        :rtype: Location"
  },
  {
    "code": "def read(self, entity=None, attrs=None, ignore=None, params=None):\n        if attrs is None:\n            attrs = self.read_json()\n        attrs['search_'] = attrs.pop('search')\n        attr = 'max_count'\n        if ignore is None:\n            ignore = set()\n        if attr not in ignore:\n            attrs[attr] = DiscoveryRule(\n                self._server_config,\n                id=attrs['id'],\n            ).update_json([])[attr]\n        return super(DiscoveryRule, self).read(entity, attrs, ignore, params)",
    "docstring": "Work around a bug. Rename ``search`` to ``search_``.\n\n        For more information on the bug, see `Bugzilla #1257255\n        <https://bugzilla.redhat.com/show_bug.cgi?id=1257255>`_."
  },
  {
    "code": "def installation(self):\n        self.locations = []\n        url = (\"https://tccna.honeywell.com/WebAPI/emea/api/v1/location\"\n               \"/installationInfo?userId=%s\"\n               \"&includeTemperatureControlSystems=True\"\n               % self.account_info['userId'])\n        response = requests.get(url, headers=self._headers())\n        response.raise_for_status()\n        self.installation_info = response.json()\n        self.system_id = (self.installation_info[0]['gateways'][0]\n                          ['temperatureControlSystems'][0]['systemId'])\n        for loc_data in self.installation_info:\n            self.locations.append(Location(self, loc_data))\n        return self.installation_info",
    "docstring": "Return the details of the installation."
  },
  {
    "code": "def show_pageitems(_, token):\n    if len(token.contents.split()) != 1:\n        msg = '%r tag takes no arguments' % token.contents.split()[0]\n        raise template.TemplateSyntaxError(msg)\n    return ShowPageItemsNode()",
    "docstring": "Show page items.\n\n    Usage:\n\n    .. code-block:: html+django\n\n        {% show_pageitems per_page %}"
  },
  {
    "code": "def is_dataset(ds):\n  import tensorflow as tf\n  from tensorflow_datasets.core.utils import py_utils\n  dataset_types = [tf.data.Dataset]\n  v1_ds = py_utils.rgetattr(tf, \"compat.v1.data.Dataset\", None)\n  v2_ds = py_utils.rgetattr(tf, \"compat.v2.data.Dataset\", None)\n  if v1_ds is not None:\n    dataset_types.append(v1_ds)\n  if v2_ds is not None:\n    dataset_types.append(v2_ds)\n  return isinstance(ds, tuple(dataset_types))",
    "docstring": "Whether ds is a Dataset. Compatible across TF versions."
  },
  {
    "code": "def _construct_location_stack_entry(location, num_traverses):\n    if not isinstance(num_traverses, int) or num_traverses < 0:\n        raise AssertionError(u'Attempted to create a LocationStackEntry namedtuple with an invalid '\n                             u'value for \"num_traverses\" {}. This is not allowed.'\n                             .format(num_traverses))\n    if not isinstance(location, Location):\n        raise AssertionError(u'Attempted to create a LocationStackEntry namedtuple with an invalid '\n                             u'value for \"location\" {}. This is not allowed.'\n                             .format(location))\n    return LocationStackEntry(location=location, num_traverses=num_traverses)",
    "docstring": "Return a LocationStackEntry namedtuple with the specified parameters."
  },
  {
    "code": "def rrtmg_lw_gen_source(ext, build_dir):\n    thispath = config.local_path\n    module_src = []\n    for item in modules:\n        fullname = join(thispath,'rrtmg_lw_v4.85','gcm_model','modules',item)\n        module_src.append(fullname)\n    for item in src:\n        if item in mod_src:\n            fullname = join(thispath,'sourcemods',item)\n        else:\n            fullname = join(thispath,'rrtmg_lw_v4.85','gcm_model','src',item)\n        module_src.append(fullname)\n    sourcelist = [join(thispath, '_rrtmg_lw.pyf'),\n                  join(thispath, 'Driver.f90')]\n    try:\n        config.have_f90c()\n        return module_src + sourcelist\n    except:\n        print('No Fortran 90 compiler found, not building RRTMG_LW extension!')\n        return None",
    "docstring": "Add RRTMG_LW fortran source if Fortran 90 compiler available,\n    if no compiler is found do not try to build the extension."
  },
  {
    "code": "def open_url(url, retries=0, sleep=0.5):\n    return open_conn(retries=retries, sleep=sleep, **parse_url(url))",
    "docstring": "Open a mysql connection to a url.  Note that if your password has\n    punctuation characters, it might break the parsing of url.\n\n    url: A string in the form \"mysql://username:password@host.domain/database\""
  },
  {
    "code": "def client_secrets(cls, client_id):\n        secrets = yield cls.view.get(key=client_id, include_docs=True)\n        raise Return([cls(**secret['doc']) for secret in secrets['rows']])",
    "docstring": "Get the client's secrets using the client_id\n\n        :param client_id: the client ID, e.g. a service ID\n        :returns: list OAuthSecret instances"
  },
  {
    "code": "def add_key(self, attributes, store_key):\n        undefined = False\n        try:\n            value = self.get_value(attributes)\n        except (KeyError, IndexError):\n            undefined = True\n        self.remove_key(store_key)\n        if not undefined:\n            if isinstance(value, (list,tuple)):\n                values = value\n                hash_value = self.get_hash_for(value)\n                self.add_hashed_value(hash_value, store_key)\n            else:\n                values = [value]\n            for value in values:\n                hash_value = self.get_hash_for(value)\n                self.add_hashed_value(hash_value, store_key)\n        else:\n            self.add_undefined(store_key)",
    "docstring": "Add key to the index.\n\n        :param attributes: Attributes to be added to the index\n        :type attributes: dict(str)\n        :param store_key: The key for the document in the store\n        :type store_key: str"
  },
  {
    "code": "def versions(runas=None):\n    ret = _rbenv_exec(['versions', '--bare'], runas=runas)\n    return [] if ret is False else ret.splitlines()",
    "docstring": "List the installed versions of ruby\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rbenv.versions"
  },
  {
    "code": "def overlay_class_names(self, image, predictions):\n        scores = predictions.get_field(\"scores\").tolist()\n        labels = predictions.get_field(\"labels\").tolist()\n        labels = [self.CATEGORIES[i] for i in labels]\n        boxes = predictions.bbox\n        template = \"{}: {:.2f}\"\n        for box, score, label in zip(boxes, scores, labels):\n            x, y = box[:2]\n            s = template.format(label, score)\n            cv2.putText(\n                image, s, (x, y), cv2.FONT_HERSHEY_SIMPLEX, .5, (255, 255, 255), 1\n            )\n        return image",
    "docstring": "Adds detected class names and scores in the positions defined by the\n        top-left corner of the predicted bounding box\n\n        Arguments:\n            image (np.ndarray): an image as returned by OpenCV\n            predictions (BoxList): the result of the computation by the model.\n                It should contain the field `scores` and `labels`."
  },
  {
    "code": "async def delete(self):\n        if self.refresh_handle:\n            self.refresh_handle.cancel()\n            self.refresh_handle = None\n        request = stun.Message(message_method=stun.Method.REFRESH,\n                               message_class=stun.Class.REQUEST)\n        request.attributes['LIFETIME'] = 0\n        await self.request(request)\n        logger.info('TURN allocation deleted %s', self.relayed_address)\n        if self.receiver:\n            self.receiver.connection_lost(None)",
    "docstring": "Delete the TURN allocation."
  },
  {
    "code": "def update(self, table_name, set_query, where=None):\n        self.validate_access_permission([\"w\", \"a\"])\n        self.verify_table_existence(table_name)\n        query = SqlQuery.make_update(table_name, set_query, where)\n        return self.execute_query(query, logging.getLogger().findCaller())",
    "docstring": "Execute an UPDATE query.\n\n        Args:\n            table_name (|str|):\n                Table name of executing the query.\n            set_query (|str|):\n                ``SET`` clause for the update query.\n            where (|arg_where_type| , optional):\n                ``WHERE`` clause for the update query.\n                Defaults to |None|.\n\n        Raises:\n            IOError:\n                |raises_write_permission|\n            simplesqlite.NullDatabaseConnectionError:\n                |raises_check_connection|\n            simplesqlite.TableNotFoundError:\n                |raises_verify_table_existence|\n            simplesqlite.OperationalError:\n                |raises_operational_error|"
  },
  {
    "code": "def query(self, string, repeat_n_times=None):\n        if not repeat_n_times:\n            repeat_n_times = self.__determine_how_many_times_to_repeat_query(string)\n        lines = self.__get_command_lines(string)\n        return_list = []\n        for line in lines:\n            lst = self.__query_n_times(line, repeat_n_times)\n            if lst and lst[0]:\n                return_list = lst\n        return return_list",
    "docstring": "This method performs the operations onto self.g\n\n        :param string: The list of operations to perform. The sequences of commands should be separated by a semicolon\n                       An example might be\n                         CREATE {'tag': 'PERSON', 'text': 'joseph'}(v1), {'relation': 'LIVES_AT'}(v1,v2),\n                                {'tag': 'PLACE', 'text': 'London'}(v2)\n                         MATCH {}(_a), {'relation': 'LIVES_AT'}(_a,_b), {}(_b)\n                           WHERE (= (get _a \"text\") \"joseph\")\n                         RETURN _a,_b;\n        :param repeat_n_times: The maximum number of times the graph is queried. It sets the maximum length of\n                               the return list. If None then the value is set by the function\n                               self.__determine_how_many_times_to_repeat_query(string)\n\n        :return: If the RETURN command is called with a list of variables names, a list of JSON with\n                 the corresponding properties is returned. If the RETURN command is used alone, a list with the entire\n                 graph is returned. Otherwise it returns an empty list"
  },
  {
    "code": "def set_user_perm(obj, perm, sid):\n    info = (\n        win32security.OWNER_SECURITY_INFORMATION |\n        win32security.GROUP_SECURITY_INFORMATION |\n        win32security.DACL_SECURITY_INFORMATION\n    )\n    sd = win32security.GetUserObjectSecurity(obj, info)\n    dacl = sd.GetSecurityDescriptorDacl()\n    ace_cnt = dacl.GetAceCount()\n    found = False\n    for idx in range(0, ace_cnt):\n        (aceType, aceFlags), ace_mask, ace_sid = dacl.GetAce(idx)\n        ace_exists = (\n            aceType == ntsecuritycon.ACCESS_ALLOWED_ACE_TYPE and\n            ace_mask == perm and\n            ace_sid == sid\n        )\n        if ace_exists:\n            break\n    else:\n        dacl.AddAccessAllowedAce(dacl.GetAclRevision(), perm, sid)\n        sd.SetSecurityDescriptorDacl(1, dacl, 0)\n        win32security.SetUserObjectSecurity(obj, info, sd)",
    "docstring": "Set an object permission for the given user sid"
  },
  {
    "code": "def strip_head(sequence, values):\n    values = set(values)\n    return list(itertools.dropwhile(lambda x: x in values, sequence))",
    "docstring": "Strips elements of `values` from the beginning of `sequence`."
  },
  {
    "code": "def ReceiveSOAP(self, readerclass=None, **kw):\n        if self.ps: return self.ps\n        if not self.IsSOAP():\n            raise TypeError(\n                'Response is \"%s\", not \"text/xml\"' % self.reply_headers.type)\n        if len(self.data) == 0:\n            raise TypeError('Received empty response')\n        self.ps = ParsedSoap(self.data, \n                        readerclass=readerclass or self.readerclass, \n                        encodingStyle=kw.get('encodingStyle'))\n        if self.sig_handler is not None:\n            self.sig_handler.verify(self.ps)\n        return self.ps",
    "docstring": "Get back a SOAP message."
  },
  {
    "code": "def select(self, sql):\n        cursor = self.connection.cursor()\n        try:\n            cursor.execute(sql)\n            results = [list(i) for i in cursor.fetchall()]\n        finally:\n            cursor.close()\n        return results",
    "docstring": "Execute arbitrary SQL select query against the database\n        and return the results.\n\n        :param sql: SQL select query to execute\n        :type sql: string\n        :returns: SQL select query result\n        :rtype: list of lists\n        :raises: MySQLdb.Error"
  },
  {
    "code": "def get_domain(self, service_id, version_number, name):\n\t\tcontent = self._fetch(\"/service/%s/version/%d/domain/%s\" % (service_id, version_number, name))\n\t\treturn FastlyDomain(self, content)",
    "docstring": "Get the domain for a particular service and version."
  },
  {
    "code": "def _check_accept_keywords(approved, flag):\n    if flag in approved:\n        return False\n    elif (flag.startswith('~') and flag[1:] in approved) \\\n            or ('~'+flag in approved):\n        return False\n    else:\n        return True",
    "docstring": "check compatibility of accept_keywords"
  },
  {
    "code": "def _snapshot_to_data(snapshot):\n    data = {}\n    data['id'] = snapshot[0]\n    data['type'] = ['single', 'pre', 'post'][snapshot[1]]\n    if data['type'] == 'post':\n        data['pre'] = snapshot[2]\n    if snapshot[3] != -1:\n        data['timestamp'] = snapshot[3]\n    else:\n        data['timestamp'] = int(time.time())\n    data['user'] = getpwuid(snapshot[4])[0]\n    data['description'] = snapshot[5]\n    data['cleanup'] = snapshot[6]\n    data['userdata'] = {}\n    for key, value in snapshot[7].items():\n        data['userdata'][key] = value\n    return data",
    "docstring": "Returns snapshot data from a D-Bus response.\n\n    A snapshot D-Bus response is a dbus.Struct containing the\n    information related to a snapshot:\n\n    [id, type, pre_snapshot, timestamp, user, description,\n     cleanup_algorithm, userdata]\n\n    id: dbus.UInt32\n    type: dbus.UInt16\n    pre_snapshot: dbus.UInt32\n    timestamp: dbus.Int64\n    user: dbus.UInt32\n    description: dbus.String\n    cleaup_algorithm: dbus.String\n    userdata: dbus.Dictionary"
  },
  {
    "code": "def default_storable(python_type, exposes=None, version=None, storable_type=None, peek=default_peek):\n    if not exposes:\n        for extension in expose_extensions:\n            try:\n                exposes = extension(python_type)\n            except (SystemExit, KeyboardInterrupt):\n                raise\n            except:\n                pass\n            else:\n                if exposes:\n                    break\n        if not exposes:\n            raise AttributeError('`exposes` required for type: {!r}'.format(python_type))\n    return Storable(python_type, key=storable_type, \\\n        handlers=StorableHandler(version=version, exposes=exposes, \\\n        poke=poke(exposes), peek=peek(python_type, exposes)))",
    "docstring": "Default mechanics for building the storable instance for a type.\n\n    Arguments:\n\n        python_type (type): type.\n\n        exposes (iterable): attributes exposed by the type.\n\n        version (tuple): version number.\n\n        storable_type (str): universal string identifier for the type.\n\n        peek (callable): peeking routine.\n\n    Returns:\n\n        Storable: storable instance."
  },
  {
    "code": "def apply_to_structure(self, structure):\n        def_struct = structure.copy()\n        old_latt = def_struct.lattice.matrix\n        new_latt = np.transpose(np.dot(self, np.transpose(old_latt)))\n        def_struct.lattice = Lattice(new_latt)\n        return def_struct",
    "docstring": "Apply the deformation gradient to a structure.\n\n        Args:\n            structure (Structure object): the structure object to\n                be modified by the deformation"
  },
  {
    "code": "def reroot_graph(G: nx.DiGraph, node: str) -> nx.DiGraph:\n    G = G.copy()\n    for n, successors in list(nx.bfs_successors(G, source=node)):\n        for s in successors:\n            G.add_edge(s, n, **G.edges[n, s])\n            G.remove_edge(n, s)\n    return G",
    "docstring": "Return a copy of the graph rooted at the given node"
  },
  {
    "code": "def get_or_generate_vocabulary(data_dir,\n                               tmp_dir,\n                               data_prefix,\n                               max_page_size_exp,\n                               approx_vocab_size=32768,\n                               strip=True):\n  num_pages_for_vocab_generation = approx_vocab_size // 3\n  vocab_file = vocab_filename(approx_vocab_size, strip)\n  def my_generator(data_prefix):\n    count = 0\n    for page in corpus_page_generator(\n        all_corpus_files(data_prefix)[::-1], tmp_dir, max_page_size_exp):\n      revisions = page[\"revisions\"]\n      if revisions:\n        text = get_text(revisions[-1], strip=strip)\n        yield text\n        count += 1\n        if count % 100 == 0:\n          tf.logging.info(\"reading pages for vocab %d\" % count)\n        if count > num_pages_for_vocab_generation:\n          break\n  return generator_utils.get_or_generate_vocab_inner(data_dir, vocab_file,\n                                                     approx_vocab_size,\n                                                     my_generator(data_prefix))",
    "docstring": "Get or generate the vocabulary.\n\n  Args:\n    data_dir: a string\n    tmp_dir: a string\n    data_prefix: a string\n    max_page_size_exp: an integer\n    approx_vocab_size: an integer\n    strip: a boolean\n\n  Returns:\n    a TextEncoder"
  },
  {
    "code": "def get_config_dir(path, pattern=\"*.config\", configspec=None, allow_errors=False):\n\tlogger = logging.getLogger(__name__)\n\tlogger.debug(\"Loading all files matching {0} in {1}\".format(pattern, path))\n\tfiles = Globber(path, include=[pattern], recursive=False).glob()\n\tfiles = sorted(files)\n\tconfig = ConfigObj()\n\tfor filename in files:\n\t\tlogger.debug(\"- Loading config for {0}\".format(filename))\n\t\ttry:\n\t\t\tconf = ConfigObj(filename, configspec=configspec)\n\t\texcept ConfigObjError, coe:\n\t\t\tlogger.error(\"An error occurred while parsing {0}: {1}\".format(filename, str(coe)))\n\t\t\tcontinue\n\t\tif configspec:\n\t\t\tconf.validate(Validator())\n\t\tconfig.merge(conf)\n\treturn config",
    "docstring": "Load an entire directory of configuration files, merging them into one.\n\n\tThis function will load multiple configuration files matching the given pattern,\n\tin the given path, and merge them. The found files are first sorted alphabetically,\n\tand then loaded and merged. A good practice is to use ConfigObj sections, for easy\n\tloading of information like per-host configuration.\n\n\tParameters\n\t----------\n\tpath: string\n\t\tAbsolute path to a directory of ConfigObj files\n\tpattern: string\n\t\tGlobbing pattern used to find files. Defaults to *.config.\n\tconfigspec: ConfigObj\n\t\tUsed to sanitize the values in the resulting ConfigObj. Validation errors are currently\n\t\tnot exposed to the caller.\n\tallow_errors: boolean\n\t\tIf False, errors raised by ConfigObj are not caught.\n\t\tIf True, errors raise by ConfigObj are caught, and an error is logged using logger."
  },
  {
    "code": "def process_added_port(self, device_details):\n        device = device_details['device']\n        port_id = device_details['port_id']\n        reprocess = True\n        try:\n            self._process_added_port(device_details)\n            LOG.debug(\"Updating cached port %s status as UP.\", port_id)\n            self._update_port_status_cache(device, device_bound=True)\n            LOG.info(\"Port %s processed.\", port_id)\n        except os_win_exc.HyperVvNicNotFound:\n            LOG.debug('vNIC %s not found. This can happen if the VM was '\n                      'destroyed.', port_id)\n            reprocess = False\n        except os_win_exc.HyperVPortNotFoundException:\n            LOG.debug('vSwitch port %s not found. This can happen if the VM '\n                      'was destroyed.', port_id)\n        except Exception as ex:\n            LOG.exception(\"Exception encountered while processing \"\n                          \"port %(port_id)s. Exception: %(ex)s\",\n                          dict(port_id=port_id, ex=ex))\n        else:\n            reprocess = False\n        if reprocess:\n            self._added_ports.add(device)\n            self._refresh_cache = True\n            return False\n        return True",
    "docstring": "Process the new ports.\n\n        Wraps _process_added_port, and treats the sucessful and exception\n        cases."
  },
  {
    "code": "async def load_kube_config(config_file=None, context=None,\n                           client_configuration=None,\n                           persist_config=True):\n    if config_file is None:\n        config_file = KUBE_CONFIG_DEFAULT_LOCATION\n    loader = _get_kube_config_loader_for_yaml_file(\n        config_file, active_context=context,\n        persist_config=persist_config)\n    if client_configuration is None:\n        config = type.__call__(Configuration)\n        await loader.load_and_set(config)\n        Configuration.set_default(config)\n    else:\n        await loader.load_and_set(client_configuration)\n    return loader",
    "docstring": "Loads authentication and cluster information from kube-config file\n    and stores them in kubernetes.client.configuration.\n\n    :param config_file: Name of the kube-config file.\n    :param context: set the active context. If is set to None, current_context\n        from config file will be used.\n    :param client_configuration: The kubernetes.client.Configuration to\n        set configs to.\n    :param persist_config: If True, config file will be updated when changed\n        (e.g GCP token refresh)."
  },
  {
    "code": "def scgi_request(url, methodname, *params, **kw):\n    xmlreq = xmlrpclib.dumps(params, methodname)\n    xmlresp = SCGIRequest(url).send(xmlreq)\n    if kw.get(\"deserialize\", True):\n        xmlresp = xmlresp.replace(\"<i8>\", \"<i4>\").replace(\"</i8>\", \"</i4>\")\n        return xmlrpclib.loads(xmlresp)[0][0]\n    else:\n        return xmlresp",
    "docstring": "Send a XMLRPC request over SCGI to the given URL.\n\n        @param url: Endpoint URL.\n        @param methodname: XMLRPC method name.\n        @param params: Tuple of simple python objects.\n        @keyword deserialize: Parse XML result? (default is True)\n        @return: XMLRPC response, or the equivalent Python data."
  },
  {
    "code": "def _get_states(self, result):\n        if 'devices' not in result.keys():\n            return\n        for device_states in result['devices']:\n            device = self.__devices[device_states['deviceURL']]\n            try:\n                device.set_active_states(device_states['states'])\n            except KeyError:\n                pass",
    "docstring": "Get states of devices."
  },
  {
    "code": "def token_network_connect(\n            self,\n            registry_address: PaymentNetworkID,\n            token_address: TokenAddress,\n            funds: TokenAmount,\n            initial_channel_target: int = 3,\n            joinable_funds_target: float = 0.4,\n    ) -> None:\n        if not is_binary_address(registry_address):\n            raise InvalidAddress('registry_address must be a valid address in binary')\n        if not is_binary_address(token_address):\n            raise InvalidAddress('token_address must be a valid address in binary')\n        token_network_identifier = views.get_token_network_identifier_by_token_address(\n            chain_state=views.state_from_raiden(self.raiden),\n            payment_network_id=registry_address,\n            token_address=token_address,\n        )\n        connection_manager = self.raiden.connection_manager_for_token_network(\n            token_network_identifier,\n        )\n        has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve(\n            raiden=self.raiden,\n            channels_to_open=initial_channel_target,\n        )\n        if not has_enough_reserve:\n            raise InsufficientGasReserve((\n                'The account balance is below the estimated amount necessary to '\n                'finish the lifecycles of all active channels. A balance of at '\n                f'least {estimated_required_reserve} wei is required.'\n            ))\n        connection_manager.connect(\n            funds=funds,\n            initial_channel_target=initial_channel_target,\n            joinable_funds_target=joinable_funds_target,\n        )",
    "docstring": "Automatically maintain channels open for the given token network.\n\n        Args:\n            token_address: the ERC20 token network to connect to.\n            funds: the amount of funds that can be used by the ConnectionMananger.\n            initial_channel_target: number of channels to open proactively.\n            joinable_funds_target: fraction of the funds that will be used to join\n                channels opened by other participants."
  },
  {
    "code": "def handleRequest(self, req):\n        name = req[\"method\"]\n        params = req[\"params\"]\n        id=req[\"id\"]\n        obj=None\n        try:\n            obj = getMethodByName(self.service, name)\n        except MethodNameNotAllowed,e:\n            self.sendResponse(id, None, e)\n        except:\n            self.sendResponse(id, None, MethodNotFound())\n        if obj:\n            try:\n                rslt = obj(*params)\n                self.sendResponse(id, rslt, None)\n            except TypeError:\n                s=getTracebackStr()\n                self.sendResponse(id, None, InvalidMethodParameters())\n            except:\n                s=getTracebackStr()\n                self.sendResponse(id, None, s)",
    "docstring": "handles a request by calling the appropriete method the service exposes"
  },
  {
    "code": "def rotateInZMat(theta_deg):\n    ct = np.cos( np.radians(theta_deg))\n    st = np.sin( np.radians(theta_deg))\n    rMat = np.array([  [ ct, -st, 0],\n                       [ st,  ct, 0],\n                       [  0,   0, 1],\n                    ])\n    return rMat",
    "docstring": "Rotate a vector theta degrees around the z-axis\n\n    Equivalent to yaw left\n\n    Rotates the vector in the sense that the x-axis is rotated\n    towards the y-axis. If looking along the z-axis (which is\n    not the way you usually look at it), the vector rotates\n    clockwise.\n\n    If sitting on the vector [1,0,0], the rotation is towards the left\n\n    Input:\n    theta_deg   (float) Angle through which vectors should be\n                rotated in degrees\n\n    Returns:\n    A matrix\n\n    To rotate a vector, premultiply by this matrix.\n    To rotate the coord sys underneath the vector, post multiply"
  },
  {
    "code": "def is_recording(self) -> Optional[bool]:\n        status_response = self._client.get_state(\n            'api/monitors/alarm/id:{}/command:status.json'.format(\n                self._monitor_id\n            )\n        )\n        if not status_response:\n            _LOGGER.warning('Could not get status for monitor {}'.format(\n                self._monitor_id\n            ))\n            return None\n        status = status_response.get('status')\n        if status == '':\n            return False\n        return int(status) == STATE_ALARM",
    "docstring": "Indicate if this Monitor is currently recording."
  },
  {
    "code": "def get_queryset(self):\n        try:\n            date = ElectionDay.objects.get(date=self.kwargs[\"date\"])\n        except Exception:\n            raise APIException(\n                \"No elections on {}.\".format(self.kwargs[\"date\"])\n            )\n        division_ids = []\n        normal_elections = date.elections.filter()\n        if len(normal_elections) > 0:\n            for election in date.elections.all():\n                if election.division.level.name == DivisionLevel.STATE:\n                    division_ids.append(election.division.uid)\n                elif election.division.level.name == DivisionLevel.DISTRICT:\n                    division_ids.append(election.division.parent.uid)\n        return Division.objects.filter(uid__in=division_ids)",
    "docstring": "Returns a queryset of all states holding a non-special election on\n        a date."
  },
  {
    "code": "def filename_addstring(filename, text):\n    fn, ext = os.path.splitext(filename)\n    return fn + text + ext",
    "docstring": "Add `text` to filename, keeping the extension in place\n    For example when adding a timestamp to the filename"
  },
  {
    "code": "def FromFile(cls, filename, overwrite=False, auto_transfer=True, **kwds):\n        path = os.path.expanduser(filename)\n        if os.path.exists(path) and not overwrite:\n            raise exceptions.InvalidUserInputError(\n                'File %s exists and overwrite not specified' % path)\n        return cls(open(path, 'wb'), close_stream=True,\n                   auto_transfer=auto_transfer, **kwds)",
    "docstring": "Create a new download object from a filename."
  },
  {
    "code": "def createMonitor(self, callback=None, errback=None, **kwargs):\n        import ns1.monitoring\n        monitor = ns1.monitoring.Monitor(self.config)\n        return monitor.create(callback=callback, errback=errback, **kwargs)",
    "docstring": "Create a monitor"
  },
  {
    "code": "def get_all_messages_in_thread(self, participant_id, thread_id, check_who_read=True):\n        try:\n            messages = Message.objects.filter(thread__id=thread_id).\\\n                order_by('-id').\\\n                select_related('thread').\\\n                prefetch_related('thread__participation_set', 'thread__participation_set__participant')\n        except Exception:\n            return Message.objects.none()\n        messages = self.check_who_read(messages)\n        return messages",
    "docstring": "Returns all the messages in a thread."
  },
  {
    "code": "def read_piezo_tensor(self):\n        header_pattern = r\"PIEZOELECTRIC TENSOR  for field in x, y, \" \\\n                         r\"z\\s+\\(C/m\\^2\\)\\s+([X-Z][X-Z]\\s+)+\\-+\"\n        row_pattern = r\"[x-z]\\s+\" + r\"\\s+\".join([r\"(\\-*[\\.\\d]+)\"] * 6)\n        footer_pattern = r\"BORN EFFECTIVE\"\n        pt_table = self.read_table_pattern(header_pattern, row_pattern,\n                                           footer_pattern, postprocess=float)\n        self.data[\"piezo_tensor\"] = pt_table",
    "docstring": "Parse the piezo tensor data"
  },
  {
    "code": "def set_album(self, album):\n        self._set_attr(TALB(encoding=3, text=album.decode('utf-8')))",
    "docstring": "Sets song's album\n\n        :param album: album"
  },
  {
    "code": "def put(self, request, **resources):\n        if not self._meta.form:\n            return None\n        if not self._meta.name in resources or not resources[self._meta.name]:\n            raise HttpError(\n                \"Resource not found.\", status=status.HTTP_404_NOT_FOUND)\n        resource = resources.pop(self._meta.name)\n        updated = UpdatedList()\n        for o in as_tuple(resource):\n            form = self._meta.form(data=request.data, instance=o, **resources)\n            if not form.is_valid():\n                raise FormError(form)\n            updated.append(form.save())\n        return updated if len(updated) > 1 else updated[-1]",
    "docstring": "Default PUT method. Uses self form. Allow bulk update.\n\n        :return object: changed instance or raise form's error"
  },
  {
    "code": "def get_world_size():\n    if torch.distributed.is_available() and torch.distributed.is_initialized():\n        world_size = torch.distributed.get_world_size()\n    else:\n        world_size = 1\n    return world_size",
    "docstring": "Gets total number of distributed workers or returns one if distributed is\n    not initialized."
  },
  {
    "code": "def almost_equal_norm(self,other,tol,relative=True):\n        if (tol<0):\n            raise ValueError(\"Tolerance cannot be negative\")\n        if type(other) != type(self):\n            return False\n        if self.dtype != other.dtype:\n            return False\n        if len(self) != len(other):\n            return False\n        diff = self.numpy()-other.numpy()\n        dnorm = norm(diff)\n        if relative:\n            return (dnorm <= tol*norm(self))\n        else:\n            return (dnorm <= tol)",
    "docstring": "Compare whether two array types are almost equal, normwise.\n\n        If the 'relative' parameter is 'True' (the default) then the\n        'tol' parameter (which must be positive) is interpreted as a\n        relative tolerance, and the comparison returns 'True' only if\n        abs(norm(self-other)) <= tol*abs(norm(self)).\n\n        If 'relative' is 'False', then 'tol' is an absolute tolerance,\n        and the comparison is true only if\n        abs(norm(self-other)) <= tol\n\n        Other meta-data (type, dtype, and length) must be exactly equal.\n        If either object's memory lives on the GPU it will be copied to\n        the CPU for the comparison, which may be slow.  But the original\n        object itself will not have its memory relocated nor scheme\n        changed.\n\n        Parameters\n        ----------\n        other\n            another Python object, that should be tested for\n            almost-equality with 'self', based on their norms.\n        tol \n            a non-negative number, the tolerance, which is interpreted\n            as either a relative tolerance (the default) or an absolute\n            tolerance.\n        relative\n            A boolean, indicating whether 'tol' should be interpreted\n            as a relative tolerance (if True, the default if this argument\n            is omitted) or as an absolute tolerance (if tol is False).\n\n        Returns\n        -------\n        boolean\n            'True' if the data agree within the tolerance, as\n            interpreted by the 'relative' keyword, and if the types,\n            lengths, and dtypes are exactly the same."
  },
  {
    "code": "def _add_transcripts(self, variant_obj, gemini_variant):\n        query = \"SELECT * from variant_impacts WHERE variant_id = {0}\".format(\n            gemini_variant['variant_id']\n        )\n        gq = GeminiQuery(self.db)\n        gq.run(query)\n        for gemini_transcript in gq:\n            transcript = Transcript(\n                hgnc_symbol=gemini_transcript['gene'],\n                transcript_id=gemini_transcript['transcript'],\n                consequence=gemini_transcript['impact_so'],\n                biotype=gemini_transcript['biotype'],\n                polyphen=gemini_transcript['polyphen_pred'],\n                sift=gemini_transcript['sift_pred'],\n                HGVSc=gemini_transcript['codon_change'],\n                HGVSp=', '.join([gemini_transcript['aa_change'] or '', gemini_transcript['aa_length'] or ''])\n                )\n            variant_obj.add_transcript(transcript)",
    "docstring": "Add all transcripts for a variant\n\n        Go through all transcripts found for the variant\n\n            Args:\n                gemini_variant (GeminiQueryRow): The gemini variant\n\n            Yields:\n                transcript (puzzle.models.Transcript)"
  },
  {
    "code": "def get_product_metadata_path(product_name):\n    string_date = product_name.split('_')[-1]\n    date = datetime.datetime.strptime(string_date, '%Y%m%dT%H%M%S')\n    path = 'products/{0}/{1}/{2}/{3}'.format(date.year, date.month, date.day, product_name)\n    return {\n        product_name: {\n            'metadata': '{0}/{1}'.format(path, 'metadata.xml'),\n            'tiles': get_tile_metadata_path('{0}/{1}'.format(path, 'productInfo.json'))\n        }\n    }",
    "docstring": "gets a single products metadata"
  },
  {
    "code": "def hmget(key, *fields, **options):\n    host = options.get('host', None)\n    port = options.get('port', None)\n    database = options.get('db', None)\n    password = options.get('password', None)\n    server = _connect(host, port, database, password)\n    return server.hmget(key, *fields)",
    "docstring": "Returns the values of all the given hash fields.\n\n    .. versionadded:: 2017.7.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' redis.hmget foo_hash bar_field1 bar_field2"
  },
  {
    "code": "def segment(self, eps, min_time):\n        new_segments = []\n        for segment in self.segments:\n            segmented = segment.segment(eps, min_time)\n            for seg in segmented:\n                new_segments.append(Segment(seg))\n        self.segments = new_segments\n        return self",
    "docstring": "In-place segmentation of segments\n\n        Spatio-temporal segmentation of each segment\n        The number of segments may increse after this step\n\n        Returns:\n            This track"
  },
  {
    "code": "def set_suffix(self):\n        self.suffix = self.w.suffix.get_text()\n        self.logger.debug('Output suffix set to {0}'.format(self.suffix))",
    "docstring": "Set output suffix."
  },
  {
    "code": "def jdnDate(jdn):\n    a = jdn + 32044\n    b = (4*a + 3) // 146097\n    c = a - (146097*b) // 4\n    d = (4*c + 3) // 1461\n    e = c - (1461*d) // 4\n    m = (5*e + 2) // 153\n    day = e + 1 - (153*m + 2) // 5\n    month = m + 3 - 12*(m//10)\n    year = 100*b + d - 4800 + m//10\n    return [year, month, day]",
    "docstring": "Converts Julian Day Number to Gregorian date."
  },
  {
    "code": "def sortable_title(portal, title):\n    if not title:\n        return ''\n    def_charset = portal.plone_utils.getSiteEncoding()\n    sortabletitle = str(title.lower().strip())\n    sortabletitle = num_sort_regex.sub(zero_fill, sortabletitle)\n    for charset in [def_charset, 'latin-1', 'utf-8']:\n        try:\n            sortabletitle = safe_unicode(sortabletitle, charset)[:30]\n            sortabletitle = sortabletitle.encode(def_charset or 'utf-8')\n            break\n        except UnicodeError:\n            pass\n        except TypeError:\n            sortabletitle = sortabletitle[:30]\n            break\n    return sortabletitle",
    "docstring": "Convert title to sortable title"
  },
  {
    "code": "def public_key_sec(self):\n        if self.is_coinbase():\n            return None\n        opcodes = ScriptTools.opcode_list(self.script)\n        if len(opcodes) == 2 and opcodes[0].startswith(\"[30\"):\n            sec = h2b(opcodes[1][1:-1])\n            return sec\n        return None",
    "docstring": "Return the public key as sec, or None in case of failure."
  },
  {
    "code": "def list_scans(self, source_id=None):\n        if source_id:\n            target_url = self.client.get_url('SCAN', 'GET', 'multi', {'source_id': source_id})\n        else:\n            target_url = self.client.get_ulr('SCAN', 'GET', 'all')\n        return base.Query(self.client.get_manager(Scan), target_url)",
    "docstring": "Filterable list of Scans for a Source.\n        Ordered newest to oldest by default"
  },
  {
    "code": "def process_delayed_asserts(self, print_only=False):\n        if self.__delayed_assert_failures:\n            exception_output = ''\n            exception_output += \"\\n*** DELAYED ASSERTION FAILURES FOR: \"\n            exception_output += \"%s\\n\" % self.id()\n            all_failing_checks = self.__delayed_assert_failures\n            self.__delayed_assert_failures = []\n            for tb in all_failing_checks:\n                exception_output += \"%s\\n\" % tb\n            if print_only:\n                print(exception_output)\n            else:\n                raise Exception(exception_output)",
    "docstring": "To be used with any test that uses delayed_asserts, which are\n            non-terminating verifications that only raise exceptions\n            after this method is called.\n            This is useful for pages with multiple elements to be checked when\n            you want to find as many bugs as possible in a single test run\n            before having all the exceptions get raised simultaneously.\n            Might be more useful if this method is called after processing all\n            the delayed asserts on a single html page so that the failure\n            screenshot matches the location of the delayed asserts.\n            If \"print_only\" is set to True, the exception won't get raised."
  },
  {
    "code": "def changed(self, code_changed=False, value_changed=False):\n        for d in self._dependents:\n            d._dep_changed(self, code_changed=code_changed,\n                           value_changed=value_changed)",
    "docstring": "Inform dependents that this shaderobject has changed."
  },
  {
    "code": "def multi_lpop(self, queue, number, transaction=False):\r\n        try:\r\n            self._multi_lpop_pipeline(self, queue, number)\r\n        except:\r\n            raise",
    "docstring": "Pops multiple elements from a list"
  },
  {
    "code": "def visit_DictComp(self, node: ast.DictComp) -> None:\n        if node in self._recomputed_values:\n            value = self._recomputed_values[node]\n            text = self._atok.get_text(node)\n            self.reprs[text] = value\n        self.generic_visit(node=node)",
    "docstring": "Represent the dictionary comprehension by dumping its source code."
  },
  {
    "code": "def validate(self, value):\n        if self.required and not value:\n            raise OAuthValidationError({'error': 'invalid_request'})\n        for val in value:\n            if not self.valid_value(val):\n                raise OAuthValidationError({\n                    'error': 'invalid_request',\n                    'error_description': _(\"'%s' is not a valid scope.\") % \\\n                            val})",
    "docstring": "Validates that the input is a list or tuple."
  },
  {
    "code": "def _from_rest_on_create(model, props):\n    fields = model.get_fields_with_prop('on_create')\n    for field in fields:\n        props[field[0]] = field[1]",
    "docstring": "Assign the default values when creating a model\n\n    This is done on fields with `on_create=<value>`."
  },
  {
    "code": "def load_args(self, args, clargs):\n        args = self.parser.parse_args(args=clargs, namespace=args)\n        if args.subcommand is None:\n            self.parser.print_help()\n            args = None\n        return args",
    "docstring": "Parse arguments and return configuration settings."
  },
  {
    "code": "def hosts_args(self):\n        host_args = []\n        for row in self.hosts:\n            if isinstance(row, dict):\n                host_args.append(row[\"host\"])\n            else:\n                host_args.append(row)\n        dedupe = list()\n        for each in host_args:\n            if each not in dedupe:\n                dedupe.append(each)\n        return dedupe",
    "docstring": "hosts list can contain strings specifying a host directly\n        or dicts containing a \"host\" key to specify the host\n\n        this way we can allow passing further config details (color, name etc.)\n        with each host as well as simply dropping in addresses for quick\n        setup depending on the user's needs"
  },
  {
    "code": "def run(self):\n    self.graphite.start()\n    while True:\n      log.debug('Graphite pusher is sleeping for %d seconds', self.period)\n      time.sleep(self.period)\n      log.debug('Pushing stats to Graphite')\n      try:\n        self.push()\n        log.debug('Done pushing stats to Graphite')\n      except:\n        log.exception('Exception while pushing stats to Graphite')\n        raise",
    "docstring": "Loop forever, pushing out stats."
  },
  {
    "code": "def itermovieshash(self):\n        cur = self._db.firstkey()\n        while cur is not None:\n            yield cur\n            cur = self._db.nextkey(cur)",
    "docstring": "Iterate over movies hash stored in the database."
  },
  {
    "code": "def aes_encrypt(key: bytes, plain_text: bytes) -> bytes:\n    aes_cipher = AES.new(key, AES_CIPHER_MODE)\n    encrypted, tag = aes_cipher.encrypt_and_digest(plain_text)\n    cipher_text = bytearray()\n    cipher_text.extend(aes_cipher.nonce)\n    cipher_text.extend(tag)\n    cipher_text.extend(encrypted)\n    return bytes(cipher_text)",
    "docstring": "AES-GCM encryption\n\n    Parameters\n    ----------\n    key: bytes\n        AES session key, which derived from two secp256k1 keys\n    plain_text: bytes\n        Plain text to encrypt\n\n    Returns\n    -------\n    bytes\n        nonce(16 bytes) + tag(16 bytes) + encrypted data"
  },
  {
    "code": "def scroll_to(self, selector, by=By.CSS_SELECTOR,\n                  timeout=settings.SMALL_TIMEOUT):\n        if self.demo_mode:\n            self.slow_scroll_to(selector, by=by, timeout=timeout)\n            return\n        if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:\n            timeout = self.__get_new_timeout(timeout)\n        element = self.wait_for_element_visible(\n            selector, by=by, timeout=timeout)\n        try:\n            self.__scroll_to_element(element)\n        except (StaleElementReferenceException, ENI_Exception):\n            self.wait_for_ready_state_complete()\n            time.sleep(0.05)\n            element = self.wait_for_element_visible(\n                selector, by=by, timeout=timeout)\n            self.__scroll_to_element(element)",
    "docstring": "Fast scroll to destination"
  },
  {
    "code": "def get_blocks(self, block_structure=None):\n        if block_structure is None:\n            block_structure = self.block_structure\n        try:\n            return self._get_blocks(block_structure)\n        except IncompatibleBlockStructures as e:\n            raise e",
    "docstring": "For a reducible circuit, get a sequence of subblocks that when\n        concatenated again yield the original circuit.  The block structure\n        given has to be compatible with the circuits actual block structure,\n        i.e. it can only be more coarse-grained.\n\n        Args:\n            block_structure (tuple): The block structure according to which the\n                subblocks are generated (default = ``None``, corresponds to the\n                circuit's own block structure)\n\n        Returns:\n            A tuple of subblocks that the circuit consists of.\n\n        Raises:\n            .IncompatibleBlockStructures"
  },
  {
    "code": "def blend_rect(self, x0, y0, x1, y1, dx, dy, destination, alpha=0xff):\n        x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)\n        for x in range(x0, x1 + 1):\n            for y in range(y0, y1 + 1):\n                o = self._offset(x, y)\n                rgba = self.canvas[o:o + 4]\n                rgba[3] = alpha\n                destination.point(dx + x - x0, dy + y - y0, rgba)",
    "docstring": "Blend a rectangle onto the image"
  },
  {
    "code": "def asset_class(self) -> str:\n        result = self.parent.name if self.parent else \"\"\n        cursor = self.parent\n        while cursor:\n            result = cursor.name + \":\" + result\n            cursor = cursor.parent\n        return result",
    "docstring": "Returns the full asset class path for this stock"
  },
  {
    "code": "def get_plugin_font(self, rich_text=False):\n        if rich_text:\n            option = 'rich_font'\n            font_size_delta = self.RICH_FONT_SIZE_DELTA\n        else:\n            option = 'font'\n            font_size_delta = self.FONT_SIZE_DELTA\n        return get_font(option=option, font_size_delta=font_size_delta)",
    "docstring": "Return plugin font option.\n\n        All plugins in Spyder use a global font. This is a convenience method\n        in case some plugins will have a delta size based on the default size."
  },
  {
    "code": "def _get_flowcell_id(in_file, require_single=True):\n    fc_ids = set([x[0] for x in _read_input_csv(in_file)])\n    if require_single and len(fc_ids) > 1:\n        raise ValueError(\"There are several FCIDs in the same samplesheet file: %s\" % in_file)\n    else:\n        return fc_ids",
    "docstring": "Retrieve the unique flowcell id represented in the SampleSheet."
  },
  {
    "code": "def dynamic_message_event(self, sender, message):\n        _ = sender\n        self.dynamic_messages.append(message)\n        self.dynamic_messages_log.append(message)\n        self.show_messages()\n        return",
    "docstring": "Dynamic event handler - set message state based on event.\n\n        Dynamic messages don't clear the message buffer.\n\n        :param sender: Unused - the object that sent the message.\n        :type sender: Object, None\n\n        :param message: A message to show in the viewer.\n        :type message: safe.messaging.Message"
  },
  {
    "code": "def sanitize_label(self, label):\n        (module, function, offset) = self.split_label_fuzzy(label)\n        label = self.parse_label(module, function, offset)\n        return label",
    "docstring": "Converts a label taken from user input into a well-formed label.\n\n        @type  label: str\n        @param label: Label taken from user input.\n\n        @rtype:  str\n        @return: Sanitized label."
  },
  {
    "code": "async def subscribe(\n    schema: GraphQLSchema,\n    document: DocumentNode,\n    root_value: Any = None,\n    context_value: Any = None,\n    variable_values: Dict[str, Any] = None,\n    operation_name: str = None,\n    field_resolver: GraphQLFieldResolver = None,\n    subscribe_field_resolver: GraphQLFieldResolver = None,\n) -> Union[AsyncIterator[ExecutionResult], ExecutionResult]:\n    try:\n        result_or_stream = await create_source_event_stream(\n            schema,\n            document,\n            root_value,\n            context_value,\n            variable_values,\n            operation_name,\n            subscribe_field_resolver,\n        )\n    except GraphQLError as error:\n        return ExecutionResult(data=None, errors=[error])\n    if isinstance(result_or_stream, ExecutionResult):\n        return result_or_stream\n    result_or_stream = cast(AsyncIterable, result_or_stream)\n    async def map_source_to_response(payload):\n        result = execute(\n            schema,\n            document,\n            payload,\n            context_value,\n            variable_values,\n            operation_name,\n            field_resolver,\n        )\n        return await result if isawaitable(result) else result\n    return MapAsyncIterator(result_or_stream, map_source_to_response)",
    "docstring": "Create a GraphQL subscription.\n\n    Implements the \"Subscribe\" algorithm described in the GraphQL spec.\n\n    Returns a coroutine object which yields either an AsyncIterator (if successful) or\n    an ExecutionResult (client error). The coroutine will raise an exception if a server\n    error occurs.\n\n    If the client-provided arguments to this function do not result in a compliant\n    subscription, a GraphQL Response (ExecutionResult) with descriptive errors and no\n    data will be returned.\n\n    If the source stream could not be created due to faulty subscription resolver logic\n    or underlying systems, the coroutine object will yield a single ExecutionResult\n    containing `errors` and no `data`.\n\n    If the operation succeeded, the coroutine will yield an AsyncIterator, which yields\n    a stream of ExecutionResults representing the response stream."
  },
  {
    "code": "def print_vertical(vertical_rows, labels, color, args):\n    if color:\n        sys.stdout.write(f'\\033[{color}m')\n    for row in vertical_rows:\n        print(*row)\n    sys.stdout.write('\\033[0m')\n    print(\"-\" * len(row) + \"Values\" + \"-\" * len(row))\n    for value in zip_longest(*value_list, fillvalue=' '):\n        print(\"  \".join(value))\n    if args['no_labels'] == False:\n        print(\"-\" * len(row) + \"Labels\" + \"-\" * len(row))\n        for label in zip_longest(*labels, fillvalue=''):\n            print(\"  \".join(label))",
    "docstring": "Print the whole vertical graph."
  },
  {
    "code": "def apply_features(body, features):\n    lines = [line for line in body.splitlines() if line.strip()]\n    last_lines = lines[-SIGNATURE_MAX_LINES:]\n    return ([[f(line) for f in features] for line in last_lines] or\n            [[0 for f in features]])",
    "docstring": "Applies features to message body lines.\n\n    Returns list of lists. Each of the lists corresponds to the body line\n    and is constituted by the numbers of features occurrences (0 or 1).\n    E.g. if element j of list i equals 1 this means that\n    feature j occurred in line i (counting from the last line of the body)."
  },
  {
    "code": "def get_waiting_components(self):\n        with self.__instances_lock:\n            result = []\n            for name, (context, _) in self.__waiting_handlers.items():\n                missing = set(context.factory_context.get_handlers_ids())\n                missing.difference_update(self._handlers.keys())\n                result.append((name, context.factory_context.name, missing))\n            result.sort()\n            return result",
    "docstring": "Returns the list of the instances waiting for their handlers\n\n        :return: A list of (name, factory name, missing handlers) tuples"
  },
  {
    "code": "def norm(self) -> bk.BKTensor:\n        return bk.absolute(bk.inner(self.tensor, self.tensor))",
    "docstring": "Return the norm of this vector"
  },
  {
    "code": "def answer_challenge(authzr, client, responders):\n    responder, challb = _find_supported_challenge(authzr, responders)\n    response = challb.response(client.key)\n    def _stop_responding():\n        return maybeDeferred(\n            responder.stop_responding,\n            authzr.body.identifier.value,\n            challb.chall,\n            response)\n    return (\n        maybeDeferred(\n            responder.start_responding,\n            authzr.body.identifier.value,\n            challb.chall,\n            response)\n        .addCallback(lambda _: client.answer_challenge(challb, response))\n        .addCallback(lambda _: _stop_responding)\n        )",
    "docstring": "Complete an authorization using a responder.\n\n    :param ~acme.messages.AuthorizationResource auth: The authorization to\n        complete.\n    :param .Client client: The ACME client.\n\n    :type responders: List[`~txacme.interfaces.IResponder`]\n    :param responders: A list of responders that can be used to complete the\n        challenge with.\n\n    :return: A deferred firing when the authorization is verified."
  },
  {
    "code": "def _size_36():\n    from shutil import get_terminal_size\n    dim = get_terminal_size()\n    if isinstance(dim, list):\n        return dim[0], dim[1]\n    return dim.lines, dim.columns",
    "docstring": "returns the rows, columns of terminal"
  },
  {
    "code": "def _get_smallest_dimensions(self, data):\n        min_width = 0\n        min_height = 0\n        for element in self.elements:\n            if not element: continue\n            size = element.get_minimum_size(data)\n            min_width = max(min_width, size.x)\n            min_height = max(min_height, size.y)\n        return datatypes.Point(min_width, min_height)",
    "docstring": "A utility method to return the minimum size needed to fit\n        all the elements in."
  },
  {
    "code": "def _process_comparison_filter_directive(filter_operation_info, location,\n                                         context, parameters, operator=None):\n    comparison_operators = {u'=', u'!=', u'>', u'<', u'>=', u'<='}\n    if operator not in comparison_operators:\n        raise AssertionError(u'Expected a valid comparison operator ({}), but got '\n                             u'{}'.format(comparison_operators, operator))\n    filtered_field_type = filter_operation_info.field_type\n    filtered_field_name = filter_operation_info.field_name\n    argument_inferred_type = strip_non_null_from_type(filtered_field_type)\n    argument_expression, non_existence_expression = _represent_argument(\n        location, context, parameters[0], argument_inferred_type)\n    comparison_expression = expressions.BinaryComposition(\n        operator, expressions.LocalField(filtered_field_name), argument_expression)\n    final_expression = None\n    if non_existence_expression is not None:\n        final_expression = expressions.BinaryComposition(\n            u'||', non_existence_expression, comparison_expression)\n    else:\n        final_expression = comparison_expression\n    return blocks.Filter(final_expression)",
    "docstring": "Return a Filter basic block that performs the given comparison against the property field.\n\n    Args:\n        filter_operation_info: FilterOperationInfo object, containing the directive and field info\n                               of the field where the filter is to be applied.\n        location: Location where this filter is used.\n        context: dict, various per-compilation data (e.g. declared tags, whether the current block\n                 is optional, etc.). May be mutated in-place in this function!\n        parameters: list of 1 element, containing the value to perform the comparison against;\n                    if the parameter is optional and missing, the check will return True\n        operator: unicode, a comparison operator, like '=', '!=', '>=' etc.\n                  This is a kwarg only to preserve the same positional arguments in the\n                  function signature, to ease validation.\n\n    Returns:\n        a Filter basic block that performs the requested comparison"
  },
  {
    "code": "def set_language(self, language):\n        LOGGER.debug(\"> Setting editor language to '{0}'.\".format(language.name))\n        self.__language = language or umbra.ui.languages.PYTHON_LANGUAGE\n        self.__set_language_description()\n        self.language_changed.emit()\n        return True",
    "docstring": "Sets the language.\n\n        :param language: Language to set.\n        :type language: Language\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def list_train_dirs(dir_: str, recursive: bool, all_: bool, long: bool, verbose: bool) -> None:\n    if verbose:\n        long = True\n    if dir_ == CXF_DEFAULT_LOG_DIR and not path.exists(CXF_DEFAULT_LOG_DIR):\n        print('The default log directory `{}` does not exist.\\n'\n              'Consider specifying the directory to be listed as an argument.'.format(CXF_DEFAULT_LOG_DIR))\n        quit(1)\n    if not path.exists(dir_):\n        print('Specified dir `{}` does not exist'.format(dir_))\n        quit(1)\n    all_trainings = _ls_print_listing(dir_, recursive, all_, long)\n    if long and len(all_trainings) > 1:\n        if not recursive:\n            print()\n        _ls_print_summary(all_trainings)\n    if verbose and len(all_trainings) == 1:\n        if not recursive:\n            print()\n        _ls_print_verbose(all_trainings[0])",
    "docstring": "List training dirs contained in the given dir with options and outputs similar to the regular `ls` command.\n    The function is accessible through cxflow CLI `cxflow ls`.\n\n    :param dir_: dir to be listed\n    :param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option)\n    :param all_: include train dirs with no epochs done (--all option)\n    :param long: list more details including model name, odel and dataset class,\n                 age, duration and epochs done (--long option)\n    :param verbose: print more verbose output with list of additional artifacts and training config,\n                    applicable only when a single train dir is listed (--verbose option)"
  },
  {
    "code": "def close(self, wait=False):\n        self.session.close()\n        self.pool.shutdown(wait=wait)",
    "docstring": "Close session, shutdown pool."
  },
  {
    "code": "def generate_tags(self):\n        self.tags = dict()\n        for section in self.sections():\n            if self.has_option(section, 'tags'):\n                tags = self.get(section, 'tags')\n                for tag in [str(t).strip() for t in tags.split(',')]:\n                    if tag not in self.tags:\n                        self.tags[tag] = list()\n                    self.tags[tag].append(section.split(':')[1])",
    "docstring": "Generates the tags with collection with hosts"
  },
  {
    "code": "def get_middle_point(lon1, lat1, lon2, lat2):\n    if lon1 == lon2 and lat1 == lat2:\n        return lon1, lat1\n    dist = geodetic.geodetic_distance(lon1, lat1, lon2, lat2)\n    azimuth = geodetic.azimuth(lon1, lat1, lon2, lat2)\n    return geodetic.point_at(lon1, lat1, azimuth, dist / 2.0)",
    "docstring": "Given two points return the point exactly in the middle lying on the same\n    great circle arc.\n\n    Parameters are point coordinates in degrees.\n\n    :returns:\n        Tuple of longitude and latitude of the point in the middle."
  },
  {
    "code": "def task(name=None, t=INFO, *args, **kwargs):\n    def c_run(name, f, t, args, kwargs):\n        def run(*largs, **lkwargs):\n            thread = __get_current_thread()\n            old_name = __THREAD_PARAMS[thread][__THREAD_PARAMS_FNAME_KEY]\n            __THREAD_PARAMS[thread][__THREAD_PARAMS_FNAME_KEY] = name\n            r = log(name, f, t, largs, lkwargs, *args, **kwargs)\n            __THREAD_PARAMS[thread][__THREAD_PARAMS_FNAME_KEY] = old_name\n            return r\n        return run\n    if callable(name):\n        f = name\n        name = f.__name__\n        return c_run(name, f, t, args, kwargs)\n    if name == None:\n        def wrapped(f):\n            name = f.__name__\n            return c_run(name, f, t, args, kwargs)\n        return wrapped\n    else:\n        return lambda f: c_run(name, f, t, args, kwargs)",
    "docstring": "This decorator modifies current function such that its start, end, and\n    duration is logged in console. If the task name is not given, it will\n    attempt to infer it from the function name. Optionally, the decorator\n    can log information into files."
  },
  {
    "code": "def sweObject(obj, jd):\n    sweObj = SWE_OBJECTS[obj]\n    sweList = swisseph.calc_ut(jd, sweObj)\n    return {\n        'id': obj,\n        'lon': sweList[0],\n        'lat': sweList[1],\n        'lonspeed': sweList[3],\n        'latspeed': sweList[4]\n    }",
    "docstring": "Returns an object from the Ephemeris."
  },
  {
    "code": "def get_transitions_for(brain_or_object):\n    workflow = get_tool('portal_workflow')\n    transitions = []\n    instance = get_object(brain_or_object)\n    for wfid in get_workflows_for(brain_or_object):\n        wf = workflow[wfid]\n        tlist = wf.getTransitionsFor(instance)\n        transitions.extend([t for t in tlist if t not in transitions])\n    return transitions",
    "docstring": "List available workflow transitions for all workflows\n\n    :param brain_or_object: A single catalog brain or content object\n    :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain\n    :returns: All possible available and allowed transitions\n    :rtype: list[dict]"
  },
  {
    "code": "def _merge_layout(x: go.Layout, y: go.Layout) -> go.Layout:\n    xjson = x.to_plotly_json()\n    yjson = y.to_plotly_json()\n    if 'shapes' in yjson and 'shapes' in xjson:\n        xjson['shapes'] += yjson['shapes']\n    yjson.update(xjson)\n    return go.Layout(yjson)",
    "docstring": "Merge attributes from two layouts."
  },
  {
    "code": "def _ensure_sequence(self, mutable=False):\n        if self.is_sequence:\n            if mutable and not isinstance(self.response, list):\n                self.response = list(self.response)\n            return\n        if self.direct_passthrough:\n            raise RuntimeError('Attempted implicit sequence conversion '\n                               'but the response object is in direct '\n                               'passthrough mode.')\n        if not self.implicit_sequence_conversion:\n            raise RuntimeError('The response object required the iterable '\n                               'to be a sequence, but the implicit '\n                               'conversion was disabled.  Call '\n                               'make_sequence() yourself.')\n        self.make_sequence()",
    "docstring": "This method can be called by methods that need a sequence.  If\n        `mutable` is true, it will also ensure that the response sequence\n        is a standard Python list.\n\n        .. versionadded:: 0.6"
  },
  {
    "code": "def pipe(p1, p2):\n    if isinstance(p1, Pipeable) or isinstance(p2, Pipeable):\n        return p1 | p2\n    return Pipe([p1, p2])",
    "docstring": "Joins two pipes"
  },
  {
    "code": "def _topology_from_residue(res):\n    topology = app.Topology()\n    chain = topology.addChain()\n    new_res = topology.addResidue(res.name, chain)\n    atoms = dict()\n    for res_atom in res.atoms():\n        topology_atom = topology.addAtom(name=res_atom.name,\n                         element=res_atom.element,\n                         residue=new_res)\n        atoms[res_atom] = topology_atom\n        topology_atom.bond_partners = []\n    for bond in res.bonds():\n        atom1 = atoms[bond.atom1]\n        atom2 = atoms[bond.atom2]\n        topology.addBond(atom1, atom2)\n        atom1.bond_partners.append(atom2)\n        atom2.bond_partners.append(atom1)\n    return topology",
    "docstring": "Converts a openmm.app.Topology.Residue to openmm.app.Topology.\n\n    Parameters\n    ----------\n    res : openmm.app.Topology.Residue\n        An individual residue in an openmm.app.Topology\n\n    Returns\n    -------\n    topology : openmm.app.Topology\n        The generated topology"
  },
  {
    "code": "def read_auth_method_tuning(self, path):\n        api_path = '/v1/sys/auth/{path}/tune'.format(\n            path=path,\n        )\n        response = self._adapter.get(\n            url=api_path,\n        )\n        return response.json()",
    "docstring": "Read the given auth path's configuration.\n\n        This endpoint requires sudo capability on the final path, but the same functionality can be achieved without\n        sudo via sys/mounts/auth/[auth-path]/tune.\n\n        Supported methods:\n            GET: /sys/auth/{path}/tune. Produces: 200 application/json\n\n        :param path: The path the method was mounted on. If not provided, defaults to the value of the \"method_type\"\n            argument.\n        :type path: str | unicode\n        :return: The JSON response of the request.\n        :rtype: dict"
  },
  {
    "code": "def consume_payload(rlp, prefix, start, type_, length):\n    if type_ is bytes:\n        item = rlp[start: start + length]\n        return (item, [prefix + item], start + length)\n    elif type_ is list:\n        items = []\n        per_item_rlp = []\n        list_rlp = prefix\n        next_item_start = start\n        end = next_item_start + length\n        while next_item_start < end:\n            p, t, l, s = consume_length_prefix(rlp, next_item_start)\n            item, item_rlp, next_item_start = consume_payload(rlp, p, s, t, l)\n            per_item_rlp.append(item_rlp)\n            list_rlp += item_rlp[0]\n            items.append(item)\n        per_item_rlp.insert(0, list_rlp)\n        if next_item_start > end:\n            raise DecodingError('List length prefix announced a too small '\n                                'length', rlp)\n        return (items, per_item_rlp, next_item_start)\n    else:\n        raise TypeError('Type must be either list or bytes')",
    "docstring": "Read the payload of an item from an RLP string.\n\n    :param rlp: the rlp string to read from\n    :param type_: the type of the payload (``bytes`` or ``list``)\n    :param start: the position at which to start reading\n    :param length: the length of the payload in bytes\n    :returns: a tuple ``(item, per_item_rlp, end)``, where ``item`` is\n              the read item, per_item_rlp is a list containing the RLP\n              encoding of each item and ``end`` is the position of the\n              first unprocessed byte"
  },
  {
    "code": "def interbase_range_affected_by_variant_on_transcript(variant, transcript):\n    if variant.is_insertion:\n        if transcript.strand == \"+\":\n            start_offset = transcript.spliced_offset(variant.start) + 1\n        else:\n            start_offset = transcript.spliced_offset(variant.start)\n        end_offset = start_offset\n    else:\n        offsets = []\n        assert len(variant.ref) > 0\n        for dna_pos in range(variant.start, variant.start + len(variant.ref)):\n            try:\n                offsets.append(transcript.spliced_offset(dna_pos))\n            except ValueError:\n                logger.info(\n                    \"Couldn't find position %d from %s on exons of %s\",\n                    dna_pos,\n                    variant,\n                    transcript)\n        if len(offsets) == 0:\n            raise ValueError(\n                \"Couldn't find any exonic reference bases affected by %s on %s\",\n                variant,\n                transcript)\n        start_offset = min(offsets)\n        end_offset = max(offsets) + 1\n    return (start_offset, end_offset)",
    "docstring": "Convert from a variant's position in global genomic coordinates on the\n    forward strand to an interval of interbase offsets on a particular\n    transcript's mRNA.\n\n    Parameters\n    ----------\n    variant : varcode.Variant\n\n    transcript : pyensembl.Transcript\n\n    Assumes that the transcript overlaps the variant.\n\n    Returns (start, end) tuple of offsets into the transcript's cDNA sequence\n    which indicates which bases in the reference sequence are affected by a\n    variant.\n\n    Example:\n        The insertion of \"TTT\" into the middle of an exon would result in an\n        offset pair such as (100,100) since no reference bases are changed\n        or deleted by an insertion.\n\n        On the other hand, deletion the preceding \"CGG\" at that same locus could\n        result in an offset pair such as (97, 100)"
  },
  {
    "code": "def on_treeview_delete_selection(self, event=None):\n        tv = self.treeview\n        selection = tv.selection()\n        self.filter_remove(remember=True)\n        toplevel_items = tv.get_children()\n        parents_to_redraw = set()\n        for item in selection:\n            try:\n                parent = ''\n                if item not in toplevel_items:\n                    parent = self.get_toplevel_parent(item)\n                else:\n                    self.previewer.delete(item)\n                del self.treedata[item]\n                tv.delete(item)\n                self.app.set_changed()\n                if parent:\n                    self._update_max_grid_rc(parent)\n                    parents_to_redraw.add(parent)\n                self.widget_editor.hide_all()\n            except tk.TclError:\n                pass\n        for item in parents_to_redraw:\n            self.draw_widget(item)\n        self.filter_restore()",
    "docstring": "Removes selected items from treeview"
  },
  {
    "code": "def copy(self):\n        copy_distribution = GaussianDistribution(variables=self.variables,\n                                                 mean=self.mean.copy(),\n                                                 cov=self.covariance.copy())\n        if self._precision_matrix is not None:\n            copy_distribution._precision_matrix = self._precision_matrix.copy()\n        return copy_distribution",
    "docstring": "Return a copy of the distribution.\n\n        Returns\n        -------\n        GaussianDistribution: copy of the distribution\n\n        Examples\n        --------\n        >>> import numpy as np\n        >>> from pgmpy.factors.distributions import GaussianDistribution as GD\n        >>> gauss_dis = GD(variables=['x1', 'x2', 'x3'],\n        ...                mean=[1, -3, 4],\n        ...                cov=[[4, 2, -2],\n        ...                     [2, 5, -5],\n        ...                     [-2, -5, 8]])\n        >>> copy_dis = gauss_dis.copy()\n        >>> copy_dis.variables\n        ['x1', 'x2', 'x3']\n        >>> copy_dis.mean\n        array([[ 1],\n                [-3],\n                [ 4]])\n        >>> copy_dis.covariance\n        array([[ 4,  2, -2],\n                [ 2,  5, -5],\n                [-2, -5,  8]])\n        >>> copy_dis.precision_matrix\n        array([[ 0.3125    , -0.125     ,  0.        ],\n                [-0.125     ,  0.58333333,  0.33333333],\n                [ 0.        ,  0.33333333,  0.33333333]])"
  },
  {
    "code": "def console_set_custom_font(\n    fontFile: AnyStr,\n    flags: int = FONT_LAYOUT_ASCII_INCOL,\n    nb_char_horiz: int = 0,\n    nb_char_vertic: int = 0,\n) -> None:\n    if not os.path.exists(fontFile):\n        raise RuntimeError(\n            \"File not found:\\n\\t%s\" % (os.path.realpath(fontFile),)\n        )\n    lib.TCOD_console_set_custom_font(\n        _bytes(fontFile), flags, nb_char_horiz, nb_char_vertic\n    )",
    "docstring": "Load the custom font file at `fontFile`.\n\n    Call this before function before calling :any:`tcod.console_init_root`.\n\n    Flags can be a mix of the following:\n\n    * tcod.FONT_LAYOUT_ASCII_INCOL:\n      Decode tileset raw in column-major order.\n    * tcod.FONT_LAYOUT_ASCII_INROW:\n      Decode tileset raw in row-major order.\n    * tcod.FONT_TYPE_GREYSCALE:\n      Force tileset to be read as greyscale.\n    * tcod.FONT_TYPE_GRAYSCALE\n    * tcod.FONT_LAYOUT_TCOD:\n      Unique layout used by libtcod.\n    * tcod.FONT_LAYOUT_CP437:\n      Decode a row-major Code Page 437 tileset into Unicode.\n\n    `nb_char_horiz` and `nb_char_vertic` are the columns and rows of the font\n    file respectfully."
  },
  {
    "code": "def _get_struct_bevelfilter(self):\n        obj = _make_object(\"BevelFilter\")\n        obj.ShadowColor = self._get_struct_rgba()\n        obj.HighlightColor = self._get_struct_rgba()\n        obj.BlurX = unpack_fixed16(self._src)\n        obj.BlurY = unpack_fixed16(self._src)\n        obj.Angle = unpack_fixed16(self._src)\n        obj.Distance = unpack_fixed16(self._src)\n        obj.Strength = unpack_fixed8(self._src)\n        bc = BitConsumer(self._src)\n        obj.InnerShadow = bc.u_get(1)\n        obj.Knockout = bc.u_get(1)\n        obj.CompositeSource = bc.u_get(1)\n        obj.OnTop = bc.u_get(1)\n        obj.Passes = bc.u_get(4)\n        return obj",
    "docstring": "Get the values for the BEVELFILTER record."
  },
  {
    "code": "def get_key_section_header(self, key, spaces):\n        header = super(NumpydocTools, self).get_key_section_header(key, spaces)\n        header = spaces + header + '\\n' + spaces + '-' * len(header) + '\\n'\n        return header",
    "docstring": "Get the key of the header section\n\n        :param key: the key name\n        :param spaces: spaces to set at the beginning of the header"
  },
  {
    "code": "def _parse_remote_response(self, response):\n        try:\n            if response.headers[\"Content-Type\"] != 'application/json':\n                logger.warning('Wrong Content_type ({})'.format(\n                    response.headers[\"Content-Type\"]))\n        except KeyError:\n            pass\n        logger.debug(\"Loaded JWKS: %s from %s\" % (response.text, self.source))\n        try:\n            return json.loads(response.text)\n        except ValueError:\n            return None",
    "docstring": "Parse JWKS from the HTTP response.\n\n        Should be overriden by subclasses for adding support of e.g. signed\n        JWKS.\n        :param response: HTTP response from the 'jwks_uri' endpoint\n        :return: response parsed as JSON"
  },
  {
    "code": "def import_foreign(name, custom_name=None):\n    if lab.is_python3():\n        io.error((\"Ignoring attempt to import foreign module '{mod}' \"\n                  \"using python version {major}.{minor}\"\n                  .format(mod=name, major=sys.version_info[0],\n                          minor=sys.version_info[1])))\n        return\n    custom_name = custom_name or name\n    f, pathname, desc = imp.find_module(name, sys.path[1:])\n    module = imp.load_module(custom_name, f, pathname, desc)\n    f.close()\n    return module",
    "docstring": "Import a module with a custom name.\n\n    NOTE this is only needed for Python2. For Python3, import the\n    module using the \"as\" keyword to declare the custom name.\n\n    For implementation details, see:\n    http://stackoverflow.com/a/6032023\n\n    Example:\n\n      To import the standard module \"math\" as \"std_math\":\n\n          if labm8.is_python3():\n            import math as std_math\n          else:\n            std_math = modules.import_foreign(\"math\", \"std_math\")\n\n    Arguments:\n\n        name (str): The name of the module to import.\n        custom_name (str, optional): The custom name to assign the module to.\n\n    Raises:\n        ImportError: If the module is not found."
  },
  {
    "code": "def _write_output_manifest(self, manifest, filestore_root):\n        output = os.path.basename(manifest)\n        fieldnames, source_manifest = self._parse_manifest(manifest)\n        if 'file_path' not in fieldnames:\n            fieldnames.append('file_path')\n        with atomic_write(output, overwrite=True) as f:\n            delimiter = b'\\t' if USING_PYTHON2 else '\\t'\n            writer = csv.DictWriter(f, fieldnames, delimiter=delimiter, quoting=csv.QUOTE_NONE)\n            writer.writeheader()\n            for row in source_manifest:\n                row['file_path'] = self._file_path(row['file_sha256'], filestore_root)\n                writer.writerow(row)\n            if os.path.isfile(output):\n                logger.warning('Overwriting manifest %s', output)\n        logger.info('Rewrote manifest %s with additional column containing path to downloaded files.', output)",
    "docstring": "Adds the file path column to the manifest and writes the copy to the current directory. If the original manifest\n        is in the current directory it is overwritten with a warning."
  },
  {
    "code": "def styles(self, mutagen_file):\n        for style in self._styles:\n            if mutagen_file.__class__.__name__ in style.formats:\n                yield style",
    "docstring": "Yields the list of storage styles of this field that can\n        handle the MediaFile's format."
  },
  {
    "code": "def __gather_avail(self):\n        avail = {}\n        for saltenv in self._get_envs():\n            avail[saltenv] = self.client.list_states(saltenv)\n        return avail",
    "docstring": "Gather the lists of available sls data from the master"
  },
  {
    "code": "def send_result(self, type, task, result):\n        if self.outqueue:\n            try:\n                self.outqueue.put((task, result))\n            except Exception as e:\n                logger.exception(e)",
    "docstring": "Send fetch result to processor"
  },
  {
    "code": "def hpai_body(self):\n        body = []\n        body.extend([self.channel])\n        body.extend([0x00])\n        body.extend([0x08])\n        body.extend([0x01])\n        body.extend(ip_to_array(self.control_socket.getsockname()[0]))\n        body.extend(int_to_array(self.control_socket.getsockname()[1]))\n        return body",
    "docstring": "Create a body with HPAI information.\n\n        This is used for disconnect and connection state requests."
  },
  {
    "code": "def getClassPath():\n    global _CLASSPATHS\n    global _SEP\n    out=[]\n    for path in _CLASSPATHS:\n        if path=='':\n            continue\n        if path.endswith('*'):\n            paths=_glob.glob(path+\".jar\")\n            if len(path)==0:\n                continue \n            out.extend(paths)\n        else:\n            out.append(path)\n    return _SEP.join(out)",
    "docstring": "Get the full java class path.\n\n    Includes user added paths and the environment CLASSPATH."
  },
  {
    "code": "def contract(self, jobs, result):\n        for j in jobs:\n            WorkerPool.put(self, j)\n        r = []\n        for i in xrange(len(jobs)):\n            r.append(result.get())\n        return r",
    "docstring": "Perform a contract on a number of jobs and block until a result is\n        retrieved for each job."
  },
  {
    "code": "def get_extra(descriptor):\n    result = []\n    extra_length = descriptor.extra_length\n    if extra_length:\n        extra = buffer_at(descriptor.extra.value, extra_length)\n        append = result.append\n        while extra:\n            length = _string_item_to_int(extra[0])\n            if not 0 < length <= len(extra):\n                raise ValueError(\n                    'Extra descriptor %i is incomplete/invalid' % (\n                        len(result),\n                    ),\n                )\n            append(extra[:length])\n            extra = extra[length:]\n    return result",
    "docstring": "Python-specific helper to access \"extra\" field of descriptors,\n    because it's not as straight-forward as in C.\n    Returns a list, where each entry is an individual extra descriptor."
  },
  {
    "code": "def _printf(self, *args, **kwargs):\n        if self._stream and not kwargs.get('file'):\n            kwargs['file'] = self._stream\n        _printf(*args, **kwargs)",
    "docstring": "Print to configured stream if any is specified and the file argument\n        is not already set for this specific call."
  },
  {
    "code": "def stream_logs(container, timeout=10.0, **logs_kwargs):\n    stream = container.logs(stream=True, **logs_kwargs)\n    return stream_timeout(\n        stream, timeout, 'Timeout waiting for container logs.')",
    "docstring": "Stream logs from a Docker container within a timeout.\n\n    :param ~docker.models.containers.Container container:\n        Container who's log lines to stream.\n    :param timeout:\n        Timeout value in seconds.\n    :param logs_kwargs:\n        Additional keyword arguments to pass to ``container.logs()``. For\n        example, the ``stdout`` and ``stderr`` boolean arguments can be used to\n        determine whether to stream stdout or stderr or both (the default).\n\n    :raises TimeoutError:\n        When the timeout value is reached before the logs have completed."
  },
  {
    "code": "def sort_window_ids(winid_list, order='mru'):\n        import utool as ut\n        winid_order = XCtrl.sorted_window_ids(order)\n        sorted_win_ids = ut.isect(winid_order, winid_list)\n        return sorted_win_ids",
    "docstring": "Orders window ids by most recently used"
  },
  {
    "code": "def combinecrinfo(crinfo1, crinfo2):\n    crinfo1 = fix_crinfo(crinfo1)\n    crinfo2 = fix_crinfo(crinfo2)\n    crinfo = [\n        [crinfo1[0][0] + crinfo2[0][0], crinfo1[0][0] + crinfo2[0][1]],\n        [crinfo1[1][0] + crinfo2[1][0], crinfo1[1][0] + crinfo2[1][1]],\n        [crinfo1[2][0] + crinfo2[2][0], crinfo1[2][0] + crinfo2[2][1]],\n    ]\n    return crinfo",
    "docstring": "Combine two crinfos. First used is crinfo1, second used is crinfo2."
  },
  {
    "code": "def create(ctx, to, amount, symbol, secret, hash, account, expiration):\n    ctx.blockchain.blocking = True\n    tx = ctx.blockchain.htlc_create(\n        Amount(amount, symbol),\n        to,\n        secret,\n        hash_type=hash,\n        expiration=expiration,\n        account=account,\n    )\n    tx.pop(\"trx\", None)\n    print_tx(tx)\n    results = tx.get(\"operation_results\", {})\n    if results:\n        htlc_id = results[0][1]\n        print(\"Your htlc_id is: {}\".format(htlc_id))",
    "docstring": "Create an HTLC contract"
  },
  {
    "code": "def call_graphviz_dot(src, fmt):\n    try:\n        svg = dot(src, T=fmt)\n    except OSError as e:\n        if e.errno == 2:\n            cli.error(\n)\n        raise\n    return svg",
    "docstring": "Call dot command, and provide helpful error message if we\n       cannot find it."
  },
  {
    "code": "def check_name(self, name=None):\n        if name:\n            self.plugin_info['check_name'] = name\n        if self.plugin_info['check_name'] is not None:\n            return self.plugin_info['check_name']\n        return self.__class__.__name__",
    "docstring": "Checks the plugin name and sets it accordingly.\n        Uses name if specified, class name if not set."
  },
  {
    "code": "async def restore_networking_configuration(self):\n        self._data = await self._handler.restore_networking_configuration(\n            system_id=self.system_id)",
    "docstring": "Restore machine's networking configuration to its initial state."
  },
  {
    "code": "def _approximate_common_period(periods: List[float],\n                               approx_denom: int = 60,\n                               reject_atol: float = 1e-8) -> Optional[float]:\n    if not periods:\n        return None\n    if any(e == 0 for e in periods):\n        return None\n    if len(periods) == 1:\n        return abs(periods[0])\n    approx_rational_periods = [\n        fractions.Fraction(int(np.round(abs(p) * approx_denom)), approx_denom)\n        for p in periods\n    ]\n    common = float(_common_rational_period(approx_rational_periods))\n    for p in periods:\n        if p != 0 and abs(p * np.round(common / p) - common) > reject_atol:\n            return None\n    return common",
    "docstring": "Finds a value that is nearly an integer multiple of multiple periods.\n\n    The returned value should be the smallest non-negative number with this\n    property. If `approx_denom` is too small the computation can fail to satisfy\n    the `reject_atol` criteria and return `None`. This is actually desirable\n    behavior, since otherwise the code would e.g. return a nonsense value when\n    asked to compute the common period of `np.e` and `np.pi`.\n\n    Args:\n        periods: The result must be an approximate integer multiple of each of\n            these.\n        approx_denom: Determines how the floating point values are rounded into\n            rational values (so that integer methods such as lcm can be used).\n            Each floating point value f_k will be rounded to a rational number\n            of the form n_k / approx_denom. If you want to recognize rational\n            periods of the form i/d then d should divide `approx_denom`.\n        reject_atol: If the computed approximate common period is at least this\n            far from an integer multiple of any of the given periods, then it\n            is discarded and `None` is returned instead.\n\n    Returns:\n        The approximate common period, or else `None` if the given\n        `approx_denom` wasn't sufficient to approximate the common period to\n        within the given `reject_atol`."
  },
  {
    "code": "def close(self):\n        if self.filename != ':memory:':\n            if self._conn is not None:\n                self._conn.commit()\n                self._conn.close()\n                self._conn = None",
    "docstring": "Closes the connection unless we're working in-memory"
  },
  {
    "code": "def get_page_generator(func, start_page=0, page_size=None):\n        page_number = start_page\n        more_pages = True\n        while more_pages:\n            page = func(page_number=page_number, page_size=page_size)\n            yield page\n            more_pages = page.has_more_pages()\n            page_number += 1",
    "docstring": "Constructs a generator for retrieving pages from a paginated endpoint.  This method is intended for internal\n        use.\n\n        :param func: Should take parameters ``page_number`` and ``page_size`` and return the corresponding |Page| object.\n        :param start_page: The page to start on.\n        :param page_size: The size of each page.\n        :return: A generator that generates each successive page."
  },
  {
    "code": "def get_ports_by_name(device_name):\n    filtered_devices = filter(\n        lambda device: device_name in device[1],\n        list_ports.comports()\n    )\n    device_ports = [device[0] for device in filtered_devices]\n    return device_ports",
    "docstring": "Returns all serial devices with a given name"
  },
  {
    "code": "def terminate_process(self, idf):\n        try:\n            p = self.q.pop(idf)\n            p.terminate()\n            return p\n        except:\n            return None",
    "docstring": "Terminate a process by id"
  },
  {
    "code": "def to_csv(self, filename, delimiter=\",\", recommended_only=False, include_io=True):\n        df = self.to_df(recommended_only, include_io)\n        df.to_csv(filename, index=False, sep=delimiter)",
    "docstring": "Return a CSV for each model and dataset.\n\n        Parameters\n        ----------\n        filename : str or file\n            Either the file name (string) or an open file (file-like object)\n            where the data will be saved.\n        delimiter : str, optional\n            Delimiter used in CSV file between fields.\n        recommended_only : bool, optional\n            If True, only recommended models for each session are included. If\n            no model is recommended, then a row with it's ID will be included,\n            but all fields will be null.\n        include_io :  bool, optional\n            If True, then the input/output files from BMDS will also be\n            included, specifically the (d) input file and the out file.\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def set_viewup(self, vector):\n        if isinstance(vector, np.ndarray):\n            if vector.ndim != 1:\n                vector = vector.ravel()\n        self.camera.SetViewUp(vector)\n        self._render()",
    "docstring": "sets camera viewup vector"
  },
  {
    "code": "def get_lock_requests(self):\n        d = defaultdict(list)\n        if self._context:\n            for variant in self._context.resolved_packages:\n                name = variant.name\n                version = variant.version\n                lock = self.patch_locks.get(name)\n                if lock is None:\n                    lock = self.default_patch_lock\n                request = get_lock_request(name, version, lock)\n                if request is not None:\n                    d[lock].append(request)\n        return d",
    "docstring": "Take the current context, and the current patch locks, and determine\n        the effective requests that will be added to the main request.\n\n        Returns:\n            A dict of (PatchLock, [Requirement]) tuples. Each requirement will be\n            a weak package reference. If there is no current context, an empty\n            dict will be returned."
  },
  {
    "code": "def get_key(key, host=None, port=None, db=None, password=None):\n    server = _connect(host, port, db, password)\n    return server.get(key)",
    "docstring": "Get redis key value\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' redis.get_key foo"
  },
  {
    "code": "def replace_file_or_dir(dest, source):\n    from rez.vendor.atomicwrites import replace_atomic\n    if not os.path.exists(dest):\n        try:\n            os.rename(source, dest)\n            return\n        except:\n            if not os.path.exists(dest):\n                raise\n    try:\n        replace_atomic(source, dest)\n        return\n    except:\n        pass\n    with make_tmp_name(dest) as tmp_dest:\n        os.rename(dest, tmp_dest)\n        os.rename(source, dest)",
    "docstring": "Replace `dest` with `source`.\n\n    Acts like an `os.rename` if `dest` does not exist. Otherwise, `dest` is\n    deleted and `src` is renamed to `dest`."
  },
  {
    "code": "def validate(template_dict, schema=None):\n        if not schema:\n            schema = SamTemplateValidator._read_schema()\n        validation_errors = \"\"\n        try:\n            jsonschema.validate(template_dict, schema)\n        except ValidationError as ex:\n            validation_errors = str(ex)\n            pass\n        return validation_errors",
    "docstring": "Is this a valid SAM template dictionary\n\n        :param dict template_dict: Data to be validated\n        :param dict schema: Optional, dictionary containing JSON Schema representing SAM template\n        :return: Empty string if there are no validation errors in template"
  },
  {
    "code": "def _pip_exists(self):\n        return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))",
    "docstring": "Returns True if pip exists inside the virtual environment. Can be\n        used as a naive way to verify that the environment is installed."
  },
  {
    "code": "def get_position_label(i, words, tags, heads, labels, ents):\n    if len(words) < 20:\n        return \"short-doc\"\n    elif i == 0:\n        return \"first-word\"\n    elif i < 10:\n        return \"early-word\"\n    elif i < 20:\n        return \"mid-word\"\n    elif i == len(words) - 1:\n        return \"last-word\"\n    else:\n        return \"late-word\"",
    "docstring": "Return labels indicating the position of the word in the document."
  },
  {
    "code": "def insert(self, action: Action, where: 'Union[int, Delegate.Where]'):\n        if isinstance(where, int):\n            self.actions.insert(where, action)\n            return\n        here = where(self.actions)\n        self.actions.insert(here, action)",
    "docstring": "add a new action with specific priority\n\n        >>> delegate: Delegate\n        >>> delegate.insert(lambda task, product, ctx: print(product), where=Delegate.Where.after(lambda action: action.__name__ == 'myfunc'))\n        the codes above inserts an action after the specific action whose name is 'myfunc'."
  },
  {
    "code": "def conv_uuid(self, column, name, **kwargs):\n        return [f(column, name, **kwargs) for f in self.uuid_filters]",
    "docstring": "Convert UUID filter."
  },
  {
    "code": "def count_variables_by_type(variables=None):\n  if variables is None:\n    variables = tf.global_variables() + tf.local_variables()\n  unique_types = set(v.dtype.base_dtype for v in variables)\n  results_dict = {}\n  for dtype in unique_types:\n    if dtype == tf.string:\n      tf.logging.warning(\n          \"NB: string Variables present. The memory usage for these  Variables \"\n          \"will not be accurately computed as it depends on the exact strings \"\n          \"stored in a particular session.\")\n    vars_of_type = [v for v in variables if v.dtype.base_dtype == dtype]\n    num_scalars = sum(v.shape.num_elements() for v in vars_of_type)\n    results_dict[dtype] = {\n        \"num_variables\": len(vars_of_type),\n        \"num_scalars\": num_scalars\n    }\n  return results_dict",
    "docstring": "Returns a dict mapping dtypes to number of variables and scalars.\n\n  Args:\n    variables: iterable of `tf.Variable`s, or None. If None is passed, then all\n      global and local variables in the current graph are used.\n\n  Returns:\n    A dict mapping tf.dtype keys to a dict containing the keys 'num_scalars' and\n      'num_variables'."
  },
  {
    "code": "def _n_parameters(self):\n        ndim = self.means_.shape[1]\n        if self.covariance_type == 'full':\n            cov_params = self.n_components * ndim * (ndim + 1) / 2.\n        elif self.covariance_type == 'diag':\n            cov_params = self.n_components * ndim\n        elif self.covariance_type == 'tied':\n            cov_params = ndim * (ndim + 1) / 2.\n        elif self.covariance_type == 'spherical':\n            cov_params = self.n_components\n        mean_params = ndim * self.n_components\n        return int(cov_params + mean_params + self.n_components - 1)",
    "docstring": "Return the number of free parameters in the model."
  },
  {
    "code": "def askopenfile(mode=\"r\", **options):\n    \"Ask for a filename to open, and returned the opened file\"\n    filename = askopenfilename(**options)\n    if filename:\n        return open(filename, mode)\n    return None",
    "docstring": "Ask for a filename to open, and returned the opened file"
  },
  {
    "code": "def visit_NameConstant(self, node: ast.NameConstant) -> Any:\n        self.recomputed_values[node] = node.value\n        return node.value",
    "docstring": "Forward the node value as a result."
  },
  {
    "code": "def run(features, labels, regularization=0., constfeat=True):\n    n_col = (features.shape[1] if len(features.shape) > 1 else 1)\n    reg_matrix = regularization * np.identity(n_col, dtype='float64')\n    if constfeat:\n        reg_matrix[0, 0] = 0.\n    return np.linalg.lstsq(features.T.dot(features) + reg_matrix, features.T.dot(labels))[0]",
    "docstring": "Run linear regression on the given data.\n\n    .. versionadded:: 0.5.0\n\n    If a regularization parameter is provided, this function\n    is a simplification and specialization of ridge\n    regression, as implemented in `scikit-learn\n    <http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Ridge.html#sklearn.linear_model.Ridge>`_.\n    Setting `solver` to `'svd'` in :class:`sklearn.linear_model.Ridge` and equating\n    our `regularization` with their `alpha` will yield the same results.\n\n    Parameters\n    ----------\n    features : ndarray\n        Features on which to run linear regression.\n\n    labels : ndarray\n        Labels for the given features. Multiple columns\n        of labels are allowed.\n\n    regularization : float, optional\n        Regularization parameter. Defaults to 0.\n\n    constfeat : bool, optional\n        Whether or not the first column of features is\n        the constant feature 1. If True, the first column\n        will be excluded from regularization. Defaults to True.\n\n    Returns\n    -------\n    model : ndarray\n        Regression model for the given data."
  },
  {
    "code": "def _CreateTempDir(prefix, run_dir=None):\n  temp_dir = tempfile.mkdtemp(prefix=prefix + '-', dir=run_dir)\n  try:\n    yield temp_dir\n  finally:\n    shutil.rmtree(temp_dir)",
    "docstring": "Context manager for creating a temporary directory.\n\n  Args:\n    prefix: string, the prefix for the temporary directory.\n    run_dir: string, the base directory location of the temporary directory.\n\n  Yields:\n    string, the temporary directory created."
  },
  {
    "code": "def headers(self):\n        if py3k:\n            return dict((k.lower(), v) for k, v in self.getheaders())\n        else:\n            return dict(self.getheaders())",
    "docstring": "Response headers.\n\n        Response headers is a dict with all keys in lower case.\n\n        >>> import urlfetch\n        >>> response = urlfetch.get(\"http://docs.python.org/\")\n        >>> response.headers\n        {\n            'content-length': '8719',\n            'x-cache': 'MISS from localhost',\n            'accept-ranges': 'bytes',\n            'vary': 'Accept-Encoding',\n            'server': 'Apache/2.2.16 (Debian)',\n            'last-modified': 'Tue, 26 Jun 2012 19:23:18 GMT',\n            'connection': 'close',\n            'etag': '\"13cc5e4-220f-4c36507ded580\"',\n            'date': 'Wed, 27 Jun 2012 06:50:30 GMT',\n            'content-type': 'text/html',\n            'x-cache-lookup': 'MISS from localhost:8080'\n        }"
  },
  {
    "code": "def get_obj_cacheable(obj, attr_name, calculate, recalculate=False):\n    if not recalculate and hasattr(obj, attr_name):\n        return getattr(obj, attr_name)\n    calculated = calculate()\n    setattr(obj, attr_name, calculated)\n    return calculated",
    "docstring": "Gets the result of a method call, using the given object and attribute name\n    as a cache"
  },
  {
    "code": "def count_tf(tokens_stream):\n    tf = defaultdict(int)\n    for tokens in tokens_stream:\n        for token in tokens:\n            tf[token] += 1\n    return tf",
    "docstring": "Count term frequencies for a single file."
  },
  {
    "code": "def download(self, sub_url):\n        response = requests.get(sub_url, headers=self.headers).text\n        soup = BS(response, 'lxml')\n        downlink = self.base_url+soup.select('.download a')[0]['href']\n        data = requests.get(downlink, headers=self.headers)\n        z = zipfile.ZipFile(cStringIO.StringIO(data.content))\n        srt_files = [f.filename for f in z.filelist\n                     if f.filename.rsplit('.')[-1].lower() in ['srt', 'ass']]\n        z.extract(srt_files[0], '/tmp/')\n        return srt_files[0]",
    "docstring": "download and unzip subtitle archive to a temp location"
  },
  {
    "code": "def update_annotation_version(xml_file):\n    with open(xml_file, 'r') as f:\n        s = f.read()\n    m = search('<annotations version=\"([0-9]*)\">', s)\n    current = int(m.groups()[0])\n    if current < 4:\n        s = sub('<marker><name>(.*?)</name><time>(.*?)</time></marker>',\n                 '<marker><marker_name>\\g<1></marker_name><marker_start>\\g<2></marker_start><marker_end>\\g<2></marker_end><marker_chan/></marker>',\n                 s)\n    if current < 5:\n        s = s.replace('marker', 'bookmark')\n        s = sub('<annotations version=\"[0-9]*\">',\n                '<annotations version=\"5\">', s)\n        with open(xml_file, 'w') as f:\n            f.write(s)",
    "docstring": "Update the fields that have changed over different versions.\n\n    Parameters\n    ----------\n    xml_file : path to file\n        xml file with the sleep scoring\n\n    Notes\n    -----\n    new in version 4: use 'marker_name' instead of simply 'name' etc\n\n    new in version 5: use 'bookmark' instead of 'marker'"
  },
  {
    "code": "def secured_task(f):\n    @wraps(f)\n    def secured_task_decorator(*args, **kwargs):\n        task_data = _get_data_from_args(args)\n        assert isinstance(task_data, TaskData)\n        if not verify_security_data(task_data.get_data()['security']):\n            raise SecurityException(\n                task_data.get_data()['security']['hashed_token'])\n        task_data.transform_payload(lambda x: x['data'])\n        return f(*args, **kwargs)\n    return secured_task_decorator",
    "docstring": "Secured task decorator."
  },
  {
    "code": "def ipaddr(value, options=None):\n    ipv4_obj = ipv4(value, options=options)\n    ipv6_obj = ipv6(value, options=options)\n    if ipv4_obj is None or ipv6_obj is None:\n        return ipv4_obj or ipv6_obj\n    else:\n        return ipv4_obj + ipv6_obj",
    "docstring": "Filters and returns only valid IP objects."
  },
  {
    "code": "def clean_password2(self):\n        password1 = self.cleaned_data.get(\"password1\")\n        password2 = self.cleaned_data.get(\"password2\")\n        if password1:\n            errors = []\n            if password1 != password2:\n                errors.append(ugettext(\"Passwords do not match\"))\n            if len(password1) < settings.ACCOUNTS_MIN_PASSWORD_LENGTH:\n                errors.append(\n                        ugettext(\"Password must be at least %s characters\") %\n                        settings.ACCOUNTS_MIN_PASSWORD_LENGTH)\n            if errors:\n                self._errors[\"password1\"] = self.error_class(errors)\n        return password2",
    "docstring": "Ensure the password fields are equal, and match the minimum\n        length defined by ``ACCOUNTS_MIN_PASSWORD_LENGTH``."
  },
  {
    "code": "def nl_recvmsgs_report(sk, cb):\n    if cb.cb_recvmsgs_ow:\n        return int(cb.cb_recvmsgs_ow(sk, cb))\n    return int(recvmsgs(sk, cb))",
    "docstring": "Receive a set of messages from a Netlink socket and report parsed messages.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L998\n\n    This function is identical to nl_recvmsgs() to the point that it will return the number of parsed messages instead\n    of 0 on success.\n\n    See nl_recvmsgs().\n\n    Positional arguments:\n    sk -- Netlink socket (nl_sock class instance).\n    cb -- set of callbacks to control behaviour (nl_cb class instance).\n\n    Returns:\n    Number of received messages or a negative error code from nl_recv()."
  },
  {
    "code": "def proxy(name, default = None):\n    proxymodule = _ProxyMetaClass(name, (_ProxyModule,), {'_default': default})\n    proxymodule.__module__ = sys._getframe(1).f_globals.get('__name__')\n    return proxymodule",
    "docstring": "Create a proxy module. A proxy module has a default implementation, but can be redirected to other\n    implementations with configurations. Other modules can depend on proxy modules."
  },
  {
    "code": "def configure_createfor(self, ns, definition):\n        @self.add_route(ns.relation_path, Operation.CreateFor, ns)\n        @request(definition.request_schema)\n        @response(definition.response_schema)\n        @wraps(definition.func)\n        def create(**path_data):\n            request_data = load_request_data(definition.request_schema)\n            response_data = require_response_data(definition.func(**merge_data(path_data, request_data)))\n            headers = encode_id_header(response_data)\n            definition.header_func(headers, response_data)\n            response_format = self.negotiate_response_content(definition.response_formats)\n            return dump_response_data(\n                definition.response_schema,\n                response_data,\n                Operation.CreateFor.value.default_code,\n                headers=headers,\n                response_format=response_format,\n            )\n        create.__doc__ = \"Create a new {} relative to a {}\".format(pluralize(ns.object_name), ns.subject_name)",
    "docstring": "Register a create-for relation endpoint.\n\n        The definition's func should be a create function, which must:\n        - accept kwargs for the new instance creation parameters\n        - return the created instance\n\n        :param ns: the namespace\n        :param definition: the endpoint definition"
  },
  {
    "code": "def _queryset_iterator(qs):\n    if issubclass(type(qs), UrlNodeQuerySet):\n        super_without_boobytrap_iterator = super(UrlNodeQuerySet, qs)\n    else:\n        super_without_boobytrap_iterator = super(PublishingQuerySet, qs)\n    if is_publishing_middleware_active() \\\n            and not is_draft_request_context():\n        for item in super_without_boobytrap_iterator.iterator():\n            if getattr(item, 'publishing_is_draft', False):\n                yield DraftItemBoobyTrap(item)\n            else:\n                yield item\n    else:\n        for item in super_without_boobytrap_iterator.iterator():\n            yield item",
    "docstring": "Override default iterator to wrap returned items in a publishing\n    sanity-checker \"booby trap\" to lazily raise an exception if DRAFT\n    items are mistakenly returned and mis-used in a public context\n    where only PUBLISHED items should be used.\n\n    This booby trap is added when all of:\n\n    - the publishing middleware is active, and therefore able to report\n    accurately whether the request is in a drafts-permitted context\n    - the publishing middleware tells us we are not in\n    a drafts-permitted context, which means only published items\n    should be used."
  },
  {
    "code": "def need_completion_refresh(queries):\n    tokens = {\n        'use', '\\\\u',\n        'create',\n        'drop'\n    }\n    for query in sqlparse.split(queries):\n        try:\n            first_token = query.split()[0]\n            if first_token.lower() in tokens:\n                return True\n        except Exception:\n            return False",
    "docstring": "Determines if the completion needs a refresh by checking if the sql\n    statement is an alter, create, drop or change db."
  },
  {
    "code": "def color(ip, mac, hue, saturation, value):\n    bulb = MyStromBulb(ip, mac)\n    bulb.set_color_hsv(hue, saturation, value)",
    "docstring": "Switch the bulb on with the given color."
  },
  {
    "code": "def validate_type(value, types, **kwargs):\n    if not is_value_of_any_type(value, types):\n        raise ValidationError(MESSAGES['type']['invalid'].format(\n            repr(value), get_type_for_value(value), types,\n        ))",
    "docstring": "Validate that the value is one of the provided primative types."
  },
  {
    "code": "def __group_tags(self, facts):\n        if not facts: return facts\n        grouped_facts = []\n        for fact_id, fact_tags in itertools.groupby(facts, lambda f: f[\"id\"]):\n            fact_tags = list(fact_tags)\n            grouped_fact = fact_tags[0]\n            keys = [\"id\", \"start_time\", \"end_time\", \"description\", \"name\",\n                    \"activity_id\", \"category\", \"tag\"]\n            grouped_fact = dict([(key, grouped_fact[key]) for key in keys])\n            grouped_fact[\"tags\"] = [ft[\"tag\"] for ft in fact_tags if ft[\"tag\"]]\n            grouped_facts.append(grouped_fact)\n        return grouped_facts",
    "docstring": "put the fact back together and move all the unique tags to an array"
  },
  {
    "code": "def init_from_adversarial_batches_write_to_datastore(self, submissions,\n                                                       adv_batches):\n    idx = 0\n    for s_id in iterkeys(submissions.defenses):\n      for adv_id in iterkeys(adv_batches.data):\n        class_batch_id = CLASSIFICATION_BATCH_ID_PATTERN.format(idx)\n        idx += 1\n        self.data[class_batch_id] = {\n            'adversarial_batch_id': adv_id,\n            'submission_id': s_id,\n            'result_path': os.path.join(\n                self._round_name,\n                CLASSIFICATION_BATCHES_SUBDIR,\n                s_id + '_' + adv_id + '.csv')\n        }\n    client = self._datastore_client\n    with client.no_transact_batch() as batch:\n      for key, value in iteritems(self.data):\n        entity = client.entity(client.key(KIND_CLASSIFICATION_BATCH, key))\n        entity.update(value)\n        batch.put(entity)",
    "docstring": "Populates data from adversarial batches and writes to datastore.\n\n    Args:\n      submissions: instance of CompetitionSubmissions\n      adv_batches: instance of AversarialBatches"
  },
  {
    "code": "def dict_to_pyxb(rp_dict):\n    rp_pyxb = d1_common.types.dataoneTypes.replicationPolicy()\n    rp_pyxb.replicationAllowed = rp_dict['allowed']\n    rp_pyxb.numberReplicas = rp_dict['num']\n    rp_pyxb.blockedMemberNode = rp_dict['block']\n    rp_pyxb.preferredMemberNode = rp_dict['pref']\n    normalize(rp_pyxb)\n    return rp_pyxb",
    "docstring": "Convert dict to ReplicationPolicy PyXB object.\n\n    Args:\n      rp_dict: Native Python structure representing a Replication Policy.\n\n    Example::\n\n      {\n        'allowed': True,\n        'num': 3,\n        'blockedMemberNode': {'urn:node:NODE1', 'urn:node:NODE2', 'urn:node:NODE3'},\n        'preferredMemberNode': {'urn:node:NODE4', 'urn:node:NODE5'},\n      }\n\n    Returns:\n      ReplicationPolicy PyXB object."
  },
  {
    "code": "def _value_decode(cls, member, value):\n        if value is None:\n            return None\n        try:\n            field_validator = cls.fields[member]\n        except KeyError:\n            return cls.valueparse.decode(value)\n        return field_validator.decode(value)",
    "docstring": "Internal method used to decode values from redis hash\n\n        :param member: str\n        :param value: bytes\n        :return: multi"
  },
  {
    "code": "def pants_setup_py(name, description, additional_classifiers=None, **kwargs):\n  if not name.startswith('pantsbuild.pants'):\n    raise ValueError(\"Pants distribution package names must start with 'pantsbuild.pants', \"\n                     \"given {}\".format(name))\n  standard_classifiers = [\n      'Intended Audience :: Developers',\n      'License :: OSI Approved :: Apache Software License',\n      'Operating System :: MacOS :: MacOS X',\n      'Operating System :: POSIX :: Linux',\n      'Programming Language :: Python',\n      'Topic :: Software Development :: Build Tools']\n  classifiers = OrderedSet(standard_classifiers + (additional_classifiers or []))\n  notes = PantsReleases.global_instance().notes_for_version(PANTS_SEMVER)\n  return PythonArtifact(\n      name=name,\n      version=VERSION,\n      description=description,\n      long_description=(_read_contents('src/python/pants/ABOUT.rst') + notes),\n      url='https://github.com/pantsbuild/pants',\n      license='Apache License, Version 2.0',\n      zip_safe=True,\n      classifiers=list(classifiers),\n      **kwargs)",
    "docstring": "Creates the setup_py for a pants artifact.\n\n  :param str name: The name of the package.\n  :param str description: A brief description of what the package provides.\n  :param list additional_classifiers: Any additional trove classifiers that apply to the package,\n                                      see: https://pypi.org/pypi?%3Aaction=list_classifiers\n  :param kwargs: Any additional keyword arguments to be passed to `setuptools.setup\n                 <https://pythonhosted.org/setuptools/setuptools.html>`_.\n  :returns: A setup_py suitable for building and publishing pants components."
  },
  {
    "code": "def parse_kwargs(kwargs, *keys, **keyvalues):\n    result = {}\n    for key in keys:\n        if key in kwargs:\n            result[key] = kwargs[key]\n            del kwargs[key]\n    for key, value in keyvalues.items():\n        if key in kwargs:\n            result[key] = kwargs[key]\n            del kwargs[key]\n        else:\n            result[key] = value\n    return result",
    "docstring": "Return dict with keys from keys|keyvals and values from kwargs|keyvals.\n\n    Existing keys are deleted from kwargs.\n\n    >>> kwargs = {'one': 1, 'two': 2, 'four': 4}\n    >>> kwargs2 = parse_kwargs(kwargs, 'two', 'three', four=None, five=5)\n    >>> kwargs == {'one': 1}\n    True\n    >>> kwargs2 == {'two': 2, 'four': 4, 'five': 5}\n    True"
  },
  {
    "code": "def get_definition(self):\n        cpds = self.model.get_cpds()\n        cpds.sort(key=lambda x: x.variable)\n        definition_tag = {}\n        for cpd in cpds:\n            definition_tag[cpd.variable] = etree.SubElement(self.network, \"DEFINITION\")\n            etree.SubElement(definition_tag[cpd.variable], \"FOR\").text = cpd.variable\n            for child in sorted(cpd.variables[:0:-1]):\n                etree.SubElement(definition_tag[cpd.variable], \"GIVEN\").text = child\n        return definition_tag",
    "docstring": "Add Definition to XMLBIF\n\n        Return\n        ------\n        dict: dict of type {variable: definition tag}\n\n        Examples\n        --------\n        >>> writer = XMLBIFWriter(model)\n        >>> writer.get_definition()\n        {'hear-bark': <Element DEFINITION at 0x7f1d48977408>,\n         'family-out': <Element DEFINITION at 0x7f1d489773c8>,\n         'dog-out': <Element DEFINITION at 0x7f1d48977388>,\n         'bowel-problem': <Element DEFINITION at 0x7f1d48977348>,\n         'light-on': <Element DEFINITION at 0x7f1d48977448>}"
  },
  {
    "code": "def filter_args_to_dict(filter_dict, accepted_filter_keys=[]):\n    out_dict = {}\n    for k, v in filter_dict.items():\n        if k not in accepted_filter_keys or v is None:\n            logger.debug(\n                'Filter was not in accepted_filter_keys or value is None.')\n            continue\n        filter_type = filter_type_map.get(k, None)\n        if filter_type is None:\n            logger.debug('Filter key not foud in map.')\n            continue\n        filter_cast_map = {\n            'int': cast_integer_filter,\n            'datetime': cast_datetime_filter\n        }\n        cast_function = filter_cast_map.get(filter_type, None)\n        if cast_function:\n            out_value = cast_function(v)\n        else:\n            out_value = v\n        out_dict[k] = out_value\n    return out_dict",
    "docstring": "Cast and validate filter args.\n\n    :param filter_dict: Filter kwargs\n    :param accepted_filter_keys: List of keys that are acceptable to use."
  },
  {
    "code": "def _get_output_template(self):\n        path = self._file_writer_session.extra_resource_path('.youtube-dl')\n        if not path:\n            self._temp_dir = tempfile.TemporaryDirectory(\n                dir=self._root_path, prefix='tmp-wpull-youtubedl'\n            )\n            path = '{}/tmp'.format(self._temp_dir.name)\n        return path, '{}.%(id)s.%(format_id)s.%(ext)s'.format(path)",
    "docstring": "Return the path prefix and output template."
  },
  {
    "code": "def open(self):\n        try:\n            self.device.open()\n        except ConnectTimeoutError as cte:\n            raise ConnectionException(cte.msg)\n        self.device.timeout = self.timeout\n        self.device._conn._session.transport.set_keepalive(self.keepalive)\n        if hasattr(self.device, \"cu\"):\n            del self.device.cu\n        self.device.bind(cu=Config)\n        if not self.lock_disable and self.session_config_lock:\n            self._lock()",
    "docstring": "Open the connection with the device."
  },
  {
    "code": "def build_tree(X, y, criterion, max_depth, current_depth=1):\n    if max_depth >= 0 and current_depth >= max_depth:\n        return Leaf(y)\n    gain, question = find_best_question(X, y, criterion)\n    if gain == 0:\n        return Leaf(y)\n    true_X, false_X, true_y, false_y = split(X, y, question)\n    true_branch = build_tree(\n        true_X, true_y,\n        criterion,\n        max_depth,\n        current_depth=current_depth+1\n    )\n    false_branch = build_tree(\n        false_X, false_y,\n        criterion,\n        max_depth,\n        current_depth=current_depth+1\n    )\n    return Node(\n        question=question,\n        true_branch=true_branch,\n        false_branch=false_branch\n    )",
    "docstring": "Builds the decision tree."
  },
  {
    "code": "def force_unlock(self, key):\n        check_not_none(key, \"key can't be None\")\n        key_data = self._to_data(key)\n        return self._encode_invoke_on_key(map_force_unlock_codec, key_data, key=key_data,\n                                          reference_id=self.reference_id_generator.get_and_increment())",
    "docstring": "Releases the lock for the specified key regardless of the lock owner. It always successfully unlocks the key,\n        never blocks, and returns immediately.\n\n        **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations\n        of __hash__ and __eq__ defined in key's class.**\n\n        :param key: (object), the key to lock."
  },
  {
    "code": "def get_event_exchange(service_name):\n    exchange_name = \"{}.events\".format(service_name)\n    exchange = Exchange(\n        exchange_name, type='topic', durable=True, delivery_mode=PERSISTENT\n    )\n    return exchange",
    "docstring": "Get an exchange for ``service_name`` events."
  },
  {
    "code": "def scram(self):\n        self.stop_all_children()\n        signal.signal(signal.SIGTERM, signal.SIG_DFL)\n        sys.exit(2)",
    "docstring": "Kill all workers and die ourselves.\n\n        This runs in response to SIGABRT, from a specific invocation\n        of the ``kill`` command.  It also runs if\n        :meth:`stop_gracefully` is called more than once."
  },
  {
    "code": "def initiate_upgrade_action_and_wait(self, components_mask, action,\n                                         timeout=2, interval=0.1):\n        try:\n            self.initiate_upgrade_action(components_mask, action)\n        except CompletionCodeError as e:\n            if e.cc == CC_LONG_DURATION_CMD_IN_PROGRESS:\n                self.wait_for_long_duration_command(\n                        constants.CMDID_HPM_INITIATE_UPGRADE_ACTION,\n                        timeout, interval)\n            else:\n                raise HpmError('initiate_upgrade_action CC=0x%02x' % e.cc)",
    "docstring": "Initiate Upgrade Action and wait for\n            long running command."
  },
  {
    "code": "def battery_reported(self, voltage, rawVoltage):\n        self._update_attribute(BATTERY_PERCENTAGE_REMAINING, voltage)\n        self._update_attribute(self.BATTERY_VOLTAGE_ATTR,\n                               int(rawVoltage / 100))",
    "docstring": "Battery reported."
  },
  {
    "code": "def check_no_self_dependency(cls, dap):\n        problems = list()\n        if 'package_name' in dap.meta and 'dependencies' in dap.meta:\n            dependencies = set()\n            for dependency in dap.meta['dependencies']:\n                if 'dependencies' in dap._badmeta and dependency in dap._badmeta['dependencies']:\n                    continue\n                if not re.search(r'[<=>]', dependency):\n                    dependencies.add(dependency)\n                for mark in ['==', '>=', '<=', '<', '>']:\n                    dep = dependency.split(mark)\n                    if len(dep) == 2:\n                        dependencies.add(dep[0].strip())\n                        break\n            if dap.meta['package_name'] in dependencies:\n                msg = 'Depends on dap with the same name as itself'\n                problems.append(DapProblem(msg))\n        return problems",
    "docstring": "Check that the package does not depend on itself.\n\n        Return a list of problems."
  },
  {
    "code": "def _repr_pretty_(self, p, cycle):\n        from IPython.lib.pretty import RepresentationPrinter\n        assert isinstance(p, RepresentationPrinter)\n        p.begin_group(1, \"SparkConfiguration(\")\n        def kv(k, v, do_comma=True):\n            p.text(k)\n            p.pretty(v)\n            if do_comma:\n                p.text(\", \")\n            p.breakable()\n        kv(\"launcher_arguments: \", self._spark_launcher_args)\n        kv(\"conf: \", self._spark_conf_helper)\n        kv(\"spark_home: \", self.spark_home)\n        kv(\"python_path: \", self._python_path, False)\n        p.end_group(1, ')')",
    "docstring": "Pretty printer for the spark cnofiguration"
  },
  {
    "code": "def configure(self, repositories):\n        self.enable_repositories(repositories)\n        self.create_stack_user()\n        self.install_base_packages()\n        self.clean_system()\n        self.yum_update(allow_reboot=True)\n        self.install_osp()\n        self.set_selinux('permissive')\n        self.fix_hostname()",
    "docstring": "Prepare the system to be ready for an undercloud installation."
  },
  {
    "code": "def from_coordinates(cls, coordinates):\n        prim = cls()\n        for coord in coordinates:\n            pm = PseudoMonomer(ampal_parent=prim)\n            pa = PseudoAtom(coord, ampal_parent=pm)\n            pm.atoms = OrderedDict([('CA', pa)])\n            prim.append(pm)\n        prim.relabel_all()\n        return prim",
    "docstring": "Creates a `Primitive` from a list of coordinates."
  },
  {
    "code": "def regularize_hidden(p0, P, reversible=True, stationary=False, C=None, eps=None):\n    n = P.shape[0]\n    if eps is None:\n        eps = 0.01 / n\n    P = np.maximum(P, eps)\n    P /= P.sum(axis=1)[:, None]\n    if reversible:\n        P = _tmatrix_disconnected.enforce_reversible_on_closed(P)\n    if stationary:\n        _tmatrix_disconnected.stationary_distribution(P, C=C)\n    else:\n        p0 = np.maximum(p0, eps)\n        p0 /= p0.sum()\n    return p0, P",
    "docstring": "Regularizes the hidden initial distribution and transition matrix.\n\n    Makes sure that the hidden initial distribution and transition matrix have\n    nonzero probabilities by setting them to eps and then renormalizing.\n    Avoids zeros that would cause estimation algorithms to crash or get stuck\n    in suboptimal states.\n\n    Parameters\n    ----------\n    p0 : ndarray(n)\n        Initial hidden distribution of the HMM\n    P : ndarray(n, n)\n        Hidden transition matrix\n    reversible : bool\n        HMM is reversible. Will make sure it is still reversible after modification.\n    stationary : bool\n        p0 is the stationary distribution of P. In this case, will not regularize\n        p0 separately. If stationary=False, the regularization will be applied to p0.\n    C : ndarray(n, n)\n        Hidden count matrix. Only needed for stationary=True and P disconnected.\n    epsilon : float or None\n        minimum value of the resulting transition matrix. Default: evaluates\n        to 0.01 / n. The coarse-graining equation can lead to negative elements\n        and thus epsilon should be set to at least 0. Positive settings of epsilon\n        are similar to a prior and enforce minimum positive values for all\n        transition probabilities.\n\n    Return\n    ------\n    p0 : ndarray(n)\n        regularized initial distribution\n    P : ndarray(n, n)\n        regularized transition matrix"
  },
  {
    "code": "def update_graderoster(graderoster, requestor):\n    label = graderoster.graderoster_label()\n    url = \"{}/{}\".format(graderoster_url, encode_section_label(label))\n    headers = {\"Content-Type\": \"application/xhtml+xml\",\n               \"Connection\": \"keep-alive\",\n               \"X-UW-Act-as\": requestor.uwnetid}\n    body = graderoster.xhtml()\n    response = SWS_GradeRoster_DAO().putURL(url, headers, body)\n    if response.status != 200:\n        root = etree.fromstring(response.data)\n        msg = root.find(\".//*[@class='status_description']\").text.strip()\n        raise DataFailureException(url, response.status, msg)\n    return GradeRoster(data=etree.fromstring(response.data.strip()),\n                       section=graderoster.section,\n                       instructor=graderoster.instructor)",
    "docstring": "Updates the graderoster resource for the passed restclients.GradeRoster\n    model. A new restclients.GradeRoster is returned, representing the\n    document returned from the update request."
  },
  {
    "code": "def OnUpdate(self, event):\n        if wx.ID_UNDO in self.id2menuitem:\n            undo_item = self.id2menuitem[wx.ID_UNDO]\n            undo_item.Enable(undo.stack().canundo())\n        if wx.ID_REDO in self.id2menuitem:\n            redo_item = self.id2menuitem[wx.ID_REDO]\n            redo_item.Enable(undo.stack().canredo())\n        event.Skip()",
    "docstring": "Menu state update"
  },
  {
    "code": "def farray(self):\n        bandwidths = 2 * pi ** (1/2.) * self.frequencies / self.q\n        return self.frequencies - bandwidths / 2.",
    "docstring": "Array of frequencies for the lower-edge of each frequency bin\n\n        :type: `numpy.ndarray`"
  },
  {
    "code": "def list_unit_states(self, machine_id=None, unit_name=None):\n        for page in self._request('UnitState.List', machineID=machine_id, unitName=unit_name):\n            for state in page.get('states', []):\n                yield UnitState(data=state)",
    "docstring": "Return the current UnitState for the fleet cluster\n\n        Args:\n            machine_id (str): filter all UnitState objects to those\n                              originating from a specific machine\n\n            unit_name (str):  filter all UnitState objects to those related\n                              to a specific unit\n\n        Yields:\n            UnitState: The next UnitState in the cluster\n\n        Raises:\n            fleet.v1.errors.APIError: Fleet returned a response code >= 400"
  },
  {
    "code": "def _get_current_deployment_id(self):\n        deploymentId = ''\n        stage = __salt__['boto_apigateway.describe_api_stage'](restApiId=self.restApiId,\n                                                               stageName=self._stage_name,\n                                                               **self._common_aws_args).get('stage')\n        if stage:\n            deploymentId = stage.get('deploymentId')\n        return deploymentId",
    "docstring": "Helper method to find the deployment id that the stage name is currently assocaited with."
  },
  {
    "code": "def _get_client(self, client=True):\n        client = client or None\n        if client is True and get_client is None:\n            log.debug(\"'dask.distributed' library was not found, will \"\n                      \"use simple serial processing.\")\n            client = None\n        elif client is True:\n            try:\n                client = get_client()\n            except ValueError:\n                log.warning(\"No dask distributed client was provided or found, \"\n                            \"but distributed features were requested. Will use simple serial processing.\")\n                client = None\n        return client",
    "docstring": "Determine what dask distributed client to use."
  },
  {
    "code": "def build_parameters(self, stack, provider_stack=None):\n        resolved = _resolve_parameters(stack.parameter_values, stack.blueprint)\n        required_parameters = list(stack.required_parameter_definitions)\n        all_parameters = list(stack.all_parameter_definitions)\n        parameters = _handle_missing_parameters(resolved, all_parameters,\n                                                required_parameters,\n                                                provider_stack)\n        param_list = []\n        for key, value in parameters:\n            param_dict = {\"ParameterKey\": key}\n            if value is UsePreviousParameterValue:\n                param_dict[\"UsePreviousValue\"] = True\n            else:\n                param_dict[\"ParameterValue\"] = str(value)\n            param_list.append(param_dict)\n        return param_list",
    "docstring": "Builds the CloudFormation Parameters for our stack.\n\n        Args:\n            stack (:class:`stacker.stack.Stack`): A stacker stack\n            provider_stack (dict): An optional Stacker provider object\n\n        Returns:\n            dict: The parameters for the given stack"
  },
  {
    "code": "def _component_of(name):\n    segments = name.split('.')\n    while segments:\n        test = '.'.join(segments)\n        if test in settings.get('COMPONENTS', []):\n            return test\n        segments.pop()\n    if not segments and '.models' in name:\n        return _component_of(name.replace('.models', ''))",
    "docstring": "Get the root package or module of the passed module."
  },
  {
    "code": "def dweet_for(thing_name, payload, key=None, session=None):\n    if key is not None:\n        params = {'key': key}\n    else:\n        params = None\n    return _send_dweet(payload, '/dweet/for/{0}'.format(thing_name), params=params, session=session)",
    "docstring": "Send a dweet to dweet.io for a thing with a known name"
  },
  {
    "code": "def decode(self):\n        \"Decode self.buffer, populating instance variables and return self.\"\n        buflen = len(self.buffer)\n        tftpassert(buflen >= 4, \"malformed ERR packet, too short\")\n        log.debug(\"Decoding ERR packet, length %s bytes\", buflen)\n        if buflen == 4:\n            log.debug(\"Allowing this affront to the RFC of a 4-byte packet\")\n            fmt = b\"!HH\"\n            log.debug(\"Decoding ERR packet with fmt: %s\", fmt)\n            self.opcode, self.errorcode = struct.unpack(fmt,\n                                                        self.buffer)\n        else:\n            log.debug(\"Good ERR packet > 4 bytes\")\n            fmt = b\"!HH%dsx\" % (len(self.buffer) - 5)\n            log.debug(\"Decoding ERR packet with fmt: %s\", fmt)\n            self.opcode, self.errorcode, self.errmsg = struct.unpack(fmt,\n                                                                     self.buffer)\n        log.error(\"ERR packet - errorcode: %d, message: %s\"\n                     % (self.errorcode, self.errmsg))\n        return self",
    "docstring": "Decode self.buffer, populating instance variables and return self."
  },
  {
    "code": "def shrink_patch(patch_path, target_file):\n    logging.debug(\"Shrinking patch file %s to keep only %s changes.\", patch_path, target_file)\n    shrinked_lines = []\n    patch_file = None\n    try:\n        patch_file = open(patch_path)\n        adding = False\n        search_line = \"diff --git a/%s b/%s\" % (target_file, target_file)\n        for line in patch_file.read().split(\"\\n\"):\n            if adding and line.startswith(\"diff --git a/\") and line != search_line:\n                adding = False\n            elif line == search_line:\n                adding = True\n            if adding:\n                shrinked_lines.append(line)\n    finally:\n        if patch_file:\n            patch_file.close()\n    if len(shrinked_lines):\n        patch_file = None\n        try:\n            patch_file = open(patch_path, \"w\")\n            content = \"\\n\".join(shrinked_lines)\n            if not content.endswith(\"\\n\"):\n                content = content + \"\\n\"\n            patch_file.write(content)\n        finally:\n            if patch_file:\n                patch_file.close()\n        return True\n    else:\n        return False",
    "docstring": "Shrinks a patch on patch_path to contain only changes for target_file.\n\n    :param patch_path: path to the shrinked patch file\n    :param target_file: filename of a file of which changes should be kept\n    :return: True if the is a section containing changes for target_file, Flase otherwise"
  },
  {
    "code": "def _get_app_config(self, app_name):\n        matches = [app_config for app_config in apps.get_app_configs()\n                   if app_config.name == app_name]\n        if not matches:\n            return\n        return matches[0]",
    "docstring": "Returns an app config for the given name, not by label."
  },
  {
    "code": "def download_directory(self, remote_path, local_path, progress=None):\n        urn = Urn(remote_path, directory=True)\n        if not self.is_dir(urn.path()):\n            raise OptionNotValid(name='remote_path', value=remote_path)\n        if os.path.exists(local_path):\n            shutil.rmtree(local_path)\n        os.makedirs(local_path)\n        for resource_name in self.list(urn.path()):\n            _remote_path = f'{urn.path()}{resource_name}'\n            _local_path = os.path.join(local_path, resource_name)\n            self.download(local_path=_local_path, remote_path=_remote_path, progress=progress)",
    "docstring": "Downloads directory and downloads all nested files and directories from remote WebDAV to local.\n        If there is something on local path it deletes directories and files then creates new.\n\n        :param remote_path: the path to directory for downloading form WebDAV server.\n        :param local_path: the path to local directory for saving downloaded files and directories.\n        :param progress: Progress function. Not supported now."
  },
  {
    "code": "def fulfill(self, agreement_id, message, account_address, signature, from_account):\n        return self._fulfill(\n            agreement_id,\n            message,\n            account_address,\n            signature,\n            transact={'from': from_account.address,\n                      'passphrase': from_account.password}\n        )",
    "docstring": "Fulfill the sign conditon.\n\n        :param agreement_id: id of the agreement, hex str\n        :param message:\n        :param account_address: ethereum account address, hex str\n        :param signature: signed agreement hash, hex str\n        :param from_account: Account doing the transaction\n        :return:"
  },
  {
    "code": "def getmacbyip6(ip6, chainCC=0):\n    if isinstance(ip6, Net6):\n        ip6 = str(ip6)\n    if in6_ismaddr(ip6):\n        mac = in6_getnsmac(inet_pton(socket.AF_INET6, ip6))\n        return mac\n    iff, a, nh = conf.route6.route(ip6)\n    if iff == scapy.consts.LOOPBACK_INTERFACE:\n        return \"ff:ff:ff:ff:ff:ff\"\n    if nh != '::':\n        ip6 = nh\n    mac = conf.netcache.in6_neighbor.get(ip6)\n    if mac:\n        return mac\n    res = neighsol(ip6, a, iff, chainCC=chainCC)\n    if res is not None:\n        if ICMPv6NDOptDstLLAddr in res:\n            mac = res[ICMPv6NDOptDstLLAddr].lladdr\n        else:\n            mac = res.src\n        conf.netcache.in6_neighbor[ip6] = mac\n        return mac\n    return None",
    "docstring": "Returns the MAC address corresponding to an IPv6 address\n\n    neighborCache.get() method is used on instantiated neighbor cache.\n    Resolution mechanism is described in associated doc string.\n\n    (chainCC parameter value ends up being passed to sending function\n     used to perform the resolution, if needed)"
  },
  {
    "code": "def create_incident(**kwargs):\n    incidents = cachet.Incidents(endpoint=ENDPOINT, api_token=API_TOKEN)\n    if 'component_id' in kwargs:\n        return incidents.post(name=kwargs['name'],\n                              message=kwargs['message'],\n                              status=kwargs['status'],\n                              component_id=kwargs['component_id'],\n                              component_status=kwargs['component_status'])\n    else:\n        return incidents.post(name=kwargs['name'],\n                              message=kwargs['message'],\n                              status=kwargs['status'])",
    "docstring": "Creates an incident"
  },
  {
    "code": "def format(self, text, width=78, indent=4):\n        return textwrap.fill(\n            text,\n            width=width,\n            initial_indent=' ' * indent,\n            subsequent_indent=' ' * indent,\n        )",
    "docstring": "Apply textwrap to a given text string"
  },
  {
    "code": "def index(request):\n    recent_jobs = JobRecord.objects.order_by(\"-start_time\")[0:100]\n    recent_trials = TrialRecord.objects.order_by(\"-start_time\")[0:500]\n    total_num = len(recent_trials)\n    running_num = sum(t.trial_status == Trial.RUNNING for t in recent_trials)\n    success_num = sum(\n        t.trial_status == Trial.TERMINATED for t in recent_trials)\n    failed_num = sum(t.trial_status == Trial.ERROR for t in recent_trials)\n    job_records = []\n    for recent_job in recent_jobs:\n        job_records.append(get_job_info(recent_job))\n    context = {\n        \"log_dir\": AUTOMLBOARD_LOG_DIR,\n        \"reload_interval\": AUTOMLBOARD_RELOAD_INTERVAL,\n        \"recent_jobs\": job_records,\n        \"job_num\": len(job_records),\n        \"trial_num\": total_num,\n        \"running_num\": running_num,\n        \"success_num\": success_num,\n        \"failed_num\": failed_num\n    }\n    return render(request, \"index.html\", context)",
    "docstring": "View for the home page."
  },
  {
    "code": "def close(self):\n        self.save()\n        self.manager.remove_temp()\n        self.cfb.close()\n        self.is_open = False\n        self.f.close()",
    "docstring": "Close the file. A closed file cannot be read or written any more."
  },
  {
    "code": "def on(cls, hook):\n        def decorator(function_):\n            cls._hooks[hook].append(function_)\n            return function_\n        return decorator",
    "docstring": "Hook decorator."
  },
  {
    "code": "def import_config(config_path):\n    if not os.path.isfile(config_path):\n        raise ConfigBuilderError(\n                'Could not find config file: ' + config_path)\n    loader = importlib.machinery.SourceFileLoader(config_path, config_path)\n    module = loader.load_module()\n    if not hasattr(module, 'config') or not isinstance(module.config, Config):\n        raise ConfigBuilderError(\n            'Could not load config file \"{}\": config files must contain '\n            'a variable called \"config\" that is '\n            'assigned to a Config object.'.format(config_path))\n    return module.config",
    "docstring": "Import a Config from a given path, relative to the current directory.\n\n    The module specified by the config file must contain a variable called `configuration` that is\n    assigned to a Config object."
  },
  {
    "code": "def cmpname(name1, name2):\n    if name1 is None and name2 is None:\n        return 0\n    if name1 is None:\n        return -1\n    if name2 is None:\n        return 1\n    lower_name1 = name1.lower()\n    lower_name2 = name2.lower()\n    if lower_name1 == lower_name2:\n        return 0\n    return -1 if lower_name1 < lower_name2 else 1",
    "docstring": "Compare two CIM names for equality and ordering.\n\n    The comparison is performed case-insensitively.\n\n    One or both of the items may be `None`, and `None` is considered the lowest\n    possible value.\n\n    The implementation delegates to the '==' and '<' operators of the\n    name datatypes.\n\n    If name1 == name2, 0 is returned.\n    If name1 < name2, -1 is returned.\n    Otherwise, +1 is returned."
  },
  {
    "code": "def get_schema(frame, name, keys=None, con=None, dtype=None):\n    pandas_sql = pandasSQL_builder(con=con)\n    return pandas_sql._create_sql_schema(frame, name, keys=keys, dtype=dtype)",
    "docstring": "Get the SQL db table schema for the given frame.\n\n    Parameters\n    ----------\n    frame : DataFrame\n    name : string\n        name of SQL table\n    keys : string or sequence, default: None\n        columns to use a primary key\n    con: an open SQL database connection object or a SQLAlchemy connectable\n        Using SQLAlchemy makes it possible to use any DB supported by that\n        library, default: None\n        If a DBAPI2 object, only sqlite3 is supported.\n    dtype : dict of column name to SQL type, default None\n        Optional specifying the datatype for columns. The SQL type should\n        be a SQLAlchemy type, or a string for sqlite3 fallback connection."
  },
  {
    "code": "def ncpos(string, chars, start):\n    string = stypes.stringToCharP(string)\n    chars = stypes.stringToCharP(chars)\n    start = ctypes.c_int(start)\n    return libspice.ncpos_c(string, chars, start)",
    "docstring": "Find the first occurrence in a string of a character NOT belonging\n    to a collection of characters, starting at a specified\n    location searching forward.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ncpos_c.html\n\n    :param string: Any character string.\n    :type string: str\n    :param chars: A collection of characters.\n    :type chars: str\n    :param start: Position to begin looking for one not in chars.\n    :type start: int\n    :return: index\n    :rtype: int"
  },
  {
    "code": "def _run_queries(self, queries, *args, **kwargs):\n        f = self._get_file()\n        for q in queries:\n            f.write(\"{};\\n\".format(q))\n        f.close()\n        psql_args = self._get_args('psql', '-X', '-f {}'.format(f.name))\n        return self._run_cmd(' '.join(psql_args), *args, **kwargs)",
    "docstring": "run the queries\n\n        queries -- list -- the queries to run\n        return -- string -- the results of the query?"
  },
  {
    "code": "def tag_list(self):\n        tags = [tag.strip() for tag in self.tag_string.split(\",\")]\n        return sorted(filter(None, tags))",
    "docstring": "Return a plain python list containing all of this Entry's tags."
  },
  {
    "code": "def stage_import_from_file(self, fd, filename='upload.gz'):\n        schema = ImportSchema()\n        resp = self.service.post(self.base,\n                                 files={'file': (filename, fd)})\n        return self.service.decode(schema, resp)",
    "docstring": "Stage an import from a file upload.\n\n        :param fd: File-like object to upload.\n        :param filename: (optional) Filename to use for import as string.\n        :return: :class:`imports.Import <imports.Import>` object"
  },
  {
    "code": "def show_terms_if_not_agreed(context, field=TERMS_HTTP_PATH_FIELD):\n    request = context['request']\n    url = urlparse(request.META[field])\n    not_agreed_terms = TermsAndConditions.get_active_terms_not_agreed_to(request.user)\n    if not_agreed_terms and is_path_protected(url.path):\n        return {'not_agreed_terms': not_agreed_terms, 'returnTo': url.path}\n    else:\n        return {}",
    "docstring": "Displays a modal on a current page if a user has not yet agreed to the\n    given terms. If terms are not specified, the default slug is used.\n\n    A small snippet is included into your template if a user\n    who requested the view has not yet agreed the terms. The snippet takes\n    care of displaying a respective modal."
  },
  {
    "code": "def picard_index_ref(picard, ref_file):\n    dict_file = \"%s.dict\" % os.path.splitext(ref_file)[0]\n    if not file_exists(dict_file):\n        with file_transaction(picard._config, dict_file) as tx_dict_file:\n            opts = [(\"REFERENCE\", ref_file),\n                    (\"OUTPUT\", tx_dict_file)]\n            picard.run(\"CreateSequenceDictionary\", opts)\n    return dict_file",
    "docstring": "Provide a Picard style dict index file for a reference genome."
  },
  {
    "code": "def exhaustive_ontology_ilx_diff_row_only( self, ontology_row: dict ) -> dict:\n        results = []\n        header = ['Index'] + list(self.existing_ids.columns)\n        for row in self.existing_ids.itertuples():\n            row = {header[i]:val for i, val in enumerate(row)}\n            check_list = [\n                {\n                    'external_ontology_row': ontology_row,\n                    'ilx_rows': [row],\n                },\n            ]\n            result = self.__exhaustive_diff(check_list)[0][0]\n            if result['same']:\n                results.append(result)\n        return results",
    "docstring": "WARNING RUNTIME IS AWEFUL"
  },
  {
    "code": "def image_needs_building(image):\n    d = docker_client()\n    try:\n        d.images.get(image)\n    except docker.errors.ImageNotFound:\n        pass\n    else:\n        return False\n    return image_needs_pushing(image)",
    "docstring": "Return whether an image needs building\n\n    Checks if the image exists (ignores commit range),\n    either locally or on the registry.\n\n    Args:\n\n    image (str): the `repository:tag` image to be build.\n\n    Returns:\n\n    True: if image needs to be built\n    False: if not (image already exists)"
  },
  {
    "code": "def check_int(**params):\n    for p in params:\n        if not isinstance(params[p], numbers.Integral):\n            raise ValueError(\n                \"Expected {} integer, got {}\".format(p, params[p]))",
    "docstring": "Check that parameters are integers as expected\n\n    Raises\n    ------\n    ValueError : unacceptable choice of parameters"
  },
  {
    "code": "def content(self, value):\n        value = self._prepend_seperator(value)\n        self._content = value",
    "docstring": "The main component of the log message.\n\n        The content field is a freeform field that\n        often begins with the process ID (pid) of the\n        program that created the message."
  },
  {
    "code": "async def upload_file(self, Filename, Bucket, Key, ExtraArgs=None, Callback=None, Config=None):\n    with open(Filename, 'rb') as open_file:\n        await upload_fileobj(self, open_file, Bucket, Key, ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)",
    "docstring": "Upload a file to an S3 object.\n\n    Usage::\n\n        import boto3\n        s3 = boto3.resource('s3')\n        s3.meta.client.upload_file('/tmp/hello.txt', 'mybucket', 'hello.txt')\n\n    Similar behavior as S3Transfer's upload_file() method,\n    except that parameters are capitalized."
  },
  {
    "code": "def append_variables(self, samples_like, sort_labels=True):\n        samples, labels = as_samples(samples_like)\n        num_samples = len(self)\n        if samples.shape[0] == num_samples:\n            pass\n        elif samples.shape[0] == 1 and num_samples:\n            samples = np.repeat(samples, num_samples, axis=0)\n        else:\n            msg = (\"mismatched shape. The samples to append should either be \"\n                   \"a single sample or should match the length of the sample \"\n                   \"set. Empty sample sets cannot be appended to.\")\n            raise ValueError(msg)\n        variables = self.variables\n        if any(v in variables for v in labels):\n            msg = \"Appended samples cannot contain variables in sample set\"\n            raise ValueError(msg)\n        new_variables = list(variables) + labels\n        new_samples = np.hstack((self.record.sample, samples))\n        return type(self).from_samples((new_samples, new_variables),\n                                       self.vartype,\n                                       info=copy.deepcopy(self.info),\n                                       sort_labels=sort_labels,\n                                       **self.data_vectors)",
    "docstring": "Create a new sampleset with the given variables with values added.\n\n        Not defined for empty sample sets. Note that when `sample_like` is\n        a :obj:`.SampleSet`, the data vectors and info are ignored.\n\n        Args:\n            samples_like:\n                Samples to add to the sample set. Should either be a single\n                sample or should match the length of the sample set. See\n                :func:`.as_samples` for what is allowed to be `samples_like`.\n\n            sort_labels (bool, optional, default=True):\n                If true, returned :attr:`.SampleSet.variables` will be in\n                sorted-order. Note that mixed types are not sortable in which\n                case the given order will be maintained.\n\n        Returns:\n            :obj:`.SampleSet`: A new sample set with the variables/values added.\n\n        Examples:\n\n            >>> sampleset = dimod.SampleSet.from_samples([{'a': -1, 'b': +1},\n            ...                                           {'a': +1, 'b': +1}],\n            ...                                          dimod.SPIN,\n            ...                                          energy=[-1.0, 1.0])\n            >>> new = sampleset.append_variables({'c': -1})\n            >>> print(new)\n               a  b  c energy num_oc.\n            0 -1 +1 -1   -1.0       1\n            1 +1 +1 -1    1.0       1\n            ['SPIN', 2 rows, 2 samples, 3 variables]\n\n            Add variables from another sampleset to the original above. Note\n            that the energies do not change.\n\n            >>> another = dimod.SampleSet.from_samples([{'c': -1, 'd': +1},\n            ...                                         {'c': +1, 'd': +1}],\n            ...                                        dimod.SPIN,\n            ...                                        energy=[-2.0, 1.0])\n            >>> new = sampleset.append_variables(another)\n            >>> print(new)\n               a  b  c  d energy num_oc.\n            0 -1 +1 -1 +1   -1.0       1\n            1 +1 +1 +1 +1    1.0       1\n            ['SPIN', 2 rows, 2 samples, 4 variables]"
  },
  {
    "code": "def list_scripts(zap_helper):\n    scripts = zap_helper.zap.script.list_scripts\n    output = []\n    for s in scripts:\n        if 'enabled' not in s:\n            s['enabled'] = 'N/A'\n        output.append([s['name'], s['type'], s['engine'], s['enabled']])\n    click.echo(tabulate(output, headers=['Name', 'Type', 'Engine', 'Enabled'], tablefmt='grid'))",
    "docstring": "List scripts currently loaded into ZAP."
  },
  {
    "code": "def pattern_from_collections_and_statement(data_collections, statement):\n        BaseCollection.are_collections_aligned(data_collections)\n        correct_var = BaseCollection._check_conditional_statement(\n            statement, len(data_collections))\n        num_statement_clean = BaseCollection._replace_operators(statement)\n        pattern = []\n        for i in xrange(len(data_collections[0])):\n            num_statement = num_statement_clean\n            for j, coll in enumerate(data_collections):\n                var = correct_var[j]\n                num_statement = num_statement.replace(var, str(coll[i]))\n            num_statement = BaseCollection._restore_operators(num_statement)\n            pattern.append(eval(num_statement, {}))\n        return pattern",
    "docstring": "Generate a list of booleans from data collections and a conditional statement.\n\n        Args:\n            data_collections: A list of aligned Data Collections to be evaluated\n                against the statement.\n            statement: A conditional statement as a string (e.g. a>25 and a%5==0).\n                The variable should always be named as 'a' (without quotations).\n\n        Return:\n            pattern: A list of True/False booleans with the length of the\n                Data Collections where True meets the conditional statement\n                and False does not."
  },
  {
    "code": "def get_all_attributes(self):\n        all_attributes = OrderedDict() if self.__preserve_order else dict()\n        for attributes in self.__sections.itervalues():\n            for attribute, value in attributes.iteritems():\n                all_attributes[attribute] = value\n        return all_attributes",
    "docstring": "Returns all sections attributes.\n\n        Usage::\n\n            >>> content = [\"[Section A]\\\\n\", \"; Comment.\\\\n\", \"Attribute 1 = \\\\\"Value A\\\\\"\\\\n\", \"\\\\n\", \\\n\"[Section B]\\\\n\", \"Attribute 2 = \\\\\"Value B\\\\\"\\\\n\"]\n            >>> sections_file_parser = SectionsFileParser()\n            >>> sections_file_parser.content = content\n            >>> sections_file_parser.parse()\n            <foundations.parsers.SectionsFileParser object at 0x845683844>\n            >>> sections_file_parser.get_all_attributes()\n            OrderedDict([(u'Section A|Attribute 1', u'Value A'), (u'Section B|Attribute 2', u'Value B')])\n            >>> sections_file_parser.preserve_order=False\n            >>> sections_file_parser.get_all_attributes()\n            {u'Section B|Attribute 2': u'Value B', u'Section A|Attribute 1': u'Value A'}\n\n        :return: All sections / files attributes.\n        :rtype: OrderedDict or dict"
  },
  {
    "code": "def get_file(self, cache_id_obj, section=None):\n        section = \"default\" if section is None else section\n        if \"/\" in section:\n            raise ValueError(\"invalid section '{0}'\".format(section))\n        cache_id = \"{:08x}\".format(\n            zlib.crc32(b\"&\".join(sorted([\n                str(k).encode('utf8') + b\"=\" + str(v).encode('utf8')\n                for k, v in cache_id_obj.items()\n            ]))) & 0xffffffff)\n        return os.path.join(self._full_base,\n                            os.path.join(section,\n                                         os.path.join(\n                                             \"{0}\".format(cache_id[:2]),\n                                             \"{0}.tmp\".format(cache_id[2:]))))",
    "docstring": "Returns the file path for the given cache object."
  },
  {
    "code": "def v1_subfolder_list(request, response, kvlclient, fid):\n    fid = urllib.unquote(fid)\n    try:\n        return sorted(imap(attrgetter('name'),\n                           ifilter(lambda it: it.is_folder(),\n                                   new_folders(kvlclient, request).list(fid))))\n    except KeyError:\n        response.status = 404\n        return []",
    "docstring": "Retrieves a list of subfolders in a folder for the current user.\n\n    The route for this endpoint is:\n    ``GET /dossier/v1/folder/<fid>/subfolder``.\n\n    (Temporarily, the \"current user\" can be set via the\n    ``annotator_id`` query parameter.)\n\n    The payload returned is a list of subfolder identifiers."
  },
  {
    "code": "def increment_lineno(node, n=1):\n    for node in zip((node,), walk(node)):\n        if 'lineno' in node._attributes:\n            node.lineno = getattr(node, 'lineno', 0) + n",
    "docstring": "Increment the line numbers of all nodes by `n` if they have line number\n    attributes.  This is useful to \"move code\" to a different location in a\n    file."
  },
  {
    "code": "def reload(self):\n        if not self.pending.acquire(False):\n            return\n        control_args = self.config['control']\n        try:\n            key = control_args.get('limits_key', 'limits')\n            self.limits.set_limits(self.db.zrange(key, 0, -1))\n        except Exception:\n            LOG.exception(\"Could not load limits\")\n            error_key = control_args.get('errors_key', 'errors')\n            error_channel = control_args.get('errors_channel', 'errors')\n            msg = \"Failed to load limits: \" + traceback.format_exc()\n            with utils.ignore_except():\n                self.db.sadd(error_key, msg)\n            with utils.ignore_except():\n                self.db.publish(error_channel, msg)\n        finally:\n            self.pending.release()",
    "docstring": "Reloads the limits configuration from the database.\n\n        If an error occurs loading the configuration, an error-level\n        log message will be emitted.  Additionally, the error message\n        will be added to the set specified by the 'redis.errors_key'\n        configuration ('errors' by default) and sent to the publishing\n        channel specified by the 'redis.errors_channel' configuration\n        ('errors' by default)."
  },
  {
    "code": "def shutdown(self):\n        logger.debug('Waiting for service manager thread to finish ...')\n        startTime = time.time()\n        self._terminate.set()\n        self._serviceStarter.join()\n        for services in list(self.toilState.servicesIssued.values()):\n            self.killServices(services, error=True)\n        logger.debug('... finished shutting down the service manager. Took %s seconds', time.time() - startTime)",
    "docstring": "Cleanly terminate worker threads starting and killing services. Will block\n        until all services are started and blocked."
  },
  {
    "code": "def intersects(self, other):\n\t\treturn any(key in self and self[key].intersects(value) for key, value in other.iteritems())",
    "docstring": "Returns True if there exists a segmentlist in self that\n\t\tintersects the corresponding segmentlist in other;  returns\n\t\tFalse otherwise.\n\n\t\tSee also:\n\n\t\t.intersects_all(), .all_intersects(), .all_intersects_all()"
  },
  {
    "code": "def clean_pubmed_identifiers(pmids: Iterable[str]) -> List[str]:\n    return sorted({str(pmid).strip() for pmid in pmids})",
    "docstring": "Clean a list of PubMed identifiers with string strips, deduplicates, and sorting."
  },
  {
    "code": "def log(duration, message=None, use_last_commit_message=False):\n    branch = git.branch\n    issue = jira.get_issue(branch)\n    comment = \"Working on issue %s\" % branch\n    if message:\n        comment = message\n    elif use_last_commit_message:\n        comment = git.get_last_commit_message()\n    if issue:\n        duration = jira.get_elapsed_time(issue) if duration == '.' else duration\n        if duration:\n            jira.add_worklog(issue, timeSpent=duration, adjustEstimate=None, newEstimate=None, reduceBy=None,\n                             comment=comment)\n            print \"Logged %s against issue %s (%s)\" % (duration, branch, comment)\n        else:\n            print \"No time logged, less than 0m elapsed.\"",
    "docstring": "Log time against the current active issue"
  },
  {
    "code": "def phonetic(s, method, concat=True, encoding='utf-8', decode_error='strict'):\n    if sys.version_info[0] == 2:\n        s = s.apply(\n            lambda x: x.decode(encoding, decode_error)\n            if type(x) == bytes else x)\n    if concat:\n        s = s.str.replace(r\"[\\-\\_\\s]\", \"\")\n    for alg in _phonetic_algorithms:\n        if method in alg['argument_names']:\n            phonetic_callback = alg['callback']\n            break\n    else:\n        raise ValueError(\"The algorithm '{}' is not known.\".format(method))\n    return s.str.upper().apply(\n        lambda x: phonetic_callback(x) if pandas.notnull(x) else np.nan\n    )",
    "docstring": "Convert names or strings into phonetic codes.\n\n    The implemented algorithms are `soundex\n    <https://en.wikipedia.org/wiki/Soundex>`_, `nysiis\n    <https://en.wikipedia.org/wiki/New_York_State_Identification_and_\n    Intelligence_System>`_, `metaphone\n    <https://en.wikipedia.org/wiki/Metaphone>`_ or  `match_rating\n    <https://en.wikipedia.org/wiki/Match_rating_approach>`_.\n\n    Parameters\n    ----------\n    s : pandas.Series\n        A pandas.Series with string values (often names) to encode.\n    method: str\n        The algorithm that is used to phonetically encode the values.\n        The possible options are \"soundex\", \"nysiis\", \"metaphone\" or\n        \"match_rating\".\n    concat: bool, optional\n        Remove whitespace before phonetic encoding.\n    encoding: str, optional\n        If bytes are given, this encoding is used to decode. Default\n        is 'utf-8'.\n    decode_error: {'strict', 'ignore', 'replace'}, optional\n        Instruction on what to do if a byte Series is given that\n        contains characters not of the given `encoding`. By default,\n        it is 'strict', meaning that a UnicodeDecodeError will be\n        raised. Other values are 'ignore' and 'replace'.\n\n    Returns\n    -------\n    pandas.Series\n        A Series with phonetic encoded values."
  },
  {
    "code": "def value(self):\n        if not self._done.is_set():\n            raise AttributeError(\"value\")\n        if self._failure:\n            raise self._failure[0], self._failure[1], self._failure[2]\n        return self._value",
    "docstring": "The final value, if it has arrived\n\n        :raises: AttributeError, if not yet complete\n        :raises: an exception if the Future was :meth:`abort`\\ed"
  },
  {
    "code": "def _write_import_root_map_file(path, import_root_map):\n    with safe_concurrent_creation(path) as safe_path:\n      with open(safe_path, 'w') as fp:\n        for import_path, root in sorted(import_root_map.items()):\n          fp.write('{}\\t{}\\n'.format(import_path, root))",
    "docstring": "Writes a file mapping import paths to roots."
  },
  {
    "code": "def idents_from_label(lab, subtopic=False):\n    if not subtopic:\n        return (lab.content_id1, None), (lab.content_id2, None)\n    else:\n        return (\n            (lab.content_id1, lab.subtopic_id1),\n            (lab.content_id2, lab.subtopic_id2),\n        )",
    "docstring": "Returns the \"ident\" of a label.\n\n    If ``subtopic`` is ``True``, then a pair of pairs is returned,\n    where each pair corresponds to the content id and subtopic id in\n    the given label.\n\n    Otherwise, a pair of pairs is returned, but the second element of each\n    pair is always ``None``.\n\n    This is a helper function that is useful for dealing with generic\n    label identifiers."
  },
  {
    "code": "def log_train_metric(period, auto_reset=False):\n    def _callback(param):\n        if param.nbatch % period == 0 and param.eval_metric is not None:\n            name_value = param.eval_metric.get_name_value()\n            for name, value in name_value:\n                logging.info('Iter[%d] Batch[%d] Train-%s=%f',\n                             param.epoch, param.nbatch, name, value)\n            if auto_reset:\n                param.eval_metric.reset_local()\n    return _callback",
    "docstring": "Callback to log the training evaluation result every period.\n\n    Parameters\n    ----------\n    period : int\n        The number of batch to log the training evaluation metric.\n    auto_reset : bool\n        Reset the metric after each log.\n\n    Returns\n    -------\n    callback : function\n        The callback function that can be passed as iter_epoch_callback to fit."
  },
  {
    "code": "def log(level, message):\n    if redis_instance is None:\n        __connect()\n    if level not in __error_levels:\n        raise InvalidErrorLevel('You have used an invalid error level. \\\n                Please choose in: ' + ', '.join(__error_levels))\n    if channel is None:\n        raise NoChannelError('Please set a channel.')\n    c = '{channel}.{level}'.format(channel=channel, level=level)\n    redis_instance.publish(c, message)",
    "docstring": "Publish `message` with the `level` the redis `channel`.\n\n    :param level: the level of the message\n    :param message: the message you want to log"
  },
  {
    "code": "def draw(self, img, pixmapper, bounds):\n        if self._img is None:\n            self._img = self.draw_legend()\n        w = self._img.shape[1]\n        h = self._img.shape[0]\n        px = 5\n        py = 5\n        img[py:py+h,px:px+w] = self._img",
    "docstring": "draw legend on the image"
  },
  {
    "code": "def clip_upper(self, threshold, axis=None, inplace=False):\n        warnings.warn('clip_upper(threshold) is deprecated, '\n                      'use clip(upper=threshold) instead',\n                      FutureWarning, stacklevel=2)\n        return self._clip_with_one_bound(threshold, method=self.le,\n                                         axis=axis, inplace=inplace)",
    "docstring": "Trim values above a given threshold.\n\n        .. deprecated:: 0.24.0\n            Use clip(upper=threshold) instead.\n\n        Elements above the `threshold` will be changed to match the\n        `threshold` value(s). Threshold can be a single value or an array,\n        in the latter case it performs the truncation element-wise.\n\n        Parameters\n        ----------\n        threshold : numeric or array-like\n            Maximum value allowed. All values above threshold will be set to\n            this value.\n\n            * float : every value is compared to `threshold`.\n            * array-like : The shape of `threshold` should match the object\n              it's compared to. When `self` is a Series, `threshold` should be\n              the length. When `self` is a DataFrame, `threshold` should 2-D\n              and the same shape as `self` for ``axis=None``, or 1-D and the\n              same length as the axis being compared.\n\n        axis : {0 or 'index', 1 or 'columns'}, default 0\n            Align object with `threshold` along the given axis.\n        inplace : bool, default False\n            Whether to perform the operation in place on the data.\n\n            .. versionadded:: 0.21.0\n\n        Returns\n        -------\n        Series or DataFrame\n            Original data with values trimmed.\n\n        See Also\n        --------\n        Series.clip : General purpose method to trim Series values to given\n            threshold(s).\n        DataFrame.clip : General purpose method to trim DataFrame values to\n            given threshold(s).\n\n        Examples\n        --------\n        >>> s = pd.Series([1, 2, 3, 4, 5])\n        >>> s\n        0    1\n        1    2\n        2    3\n        3    4\n        4    5\n        dtype: int64\n\n        >>> s.clip(upper=3)\n        0    1\n        1    2\n        2    3\n        3    3\n        4    3\n        dtype: int64\n\n        >>> elemwise_thresholds = [5, 4, 3, 2, 1]\n        >>> elemwise_thresholds\n        [5, 4, 3, 2, 1]\n\n        >>> s.clip(upper=elemwise_thresholds)\n        0    1\n        1    2\n        2    3\n        3    2\n        4    1\n        dtype: int64"
  },
  {
    "code": "def bitwise_xor(bs0: str, bs1: str) -> str:\n    if len(bs0) != len(bs1):\n        raise ValueError(\"Bit strings are not of equal length\")\n    n_bits = len(bs0)\n    return PADDED_BINARY_BIT_STRING.format(xor(int(bs0, 2), int(bs1, 2)), n_bits)",
    "docstring": "A helper to calculate the bitwise XOR of two bit string\n\n    :param bs0: String of 0's and 1's representing a number in binary representations\n    :param bs1: String of 0's and 1's representing a number in binary representations\n    :return: String of 0's and 1's representing the XOR between bs0 and bs1"
  },
  {
    "code": "def break_edge(self, from_index, to_index, to_jimage=None, allow_reverse=False):\n        existing_edges = self.graph.get_edge_data(from_index, to_index)\n        existing_reverse = None\n        if to_jimage is None:\n            raise ValueError(\"Image must be supplied, to avoid ambiguity.\")\n        if existing_edges:\n            for i, properties in existing_edges.items():\n                if properties[\"to_jimage\"] == to_jimage:\n                    edge_index = i\n            self.graph.remove_edge(from_index, to_index, edge_index)\n        else:\n            if allow_reverse:\n                existing_reverse = self.graph.get_edge_data(to_index, from_index)\n            if existing_reverse:\n                for i, properties in existing_reverse.items():\n                    if properties[\"to_jimage\"] == to_jimage:\n                        edge_index = i\n                self.graph.remove_edge(to_index, from_index, edge_index)\n            else:\n                raise ValueError(\"Edge cannot be broken between {} and {};\\\n                                no edge exists between those sites.\".format(\n                                from_index, to_index\n                                ))",
    "docstring": "Remove an edge from the StructureGraph. If no image is given, this method will fail.\n\n        :param from_index: int\n        :param to_index: int\n        :param to_jimage: tuple\n        :param allow_reverse: If allow_reverse is True, then break_edge will\n        attempt to break both (from_index, to_index) and, failing that,\n        will attempt to break (to_index, from_index).\n        :return:"
  },
  {
    "code": "def get_cpu_info(self):\n        info = snap7.snap7types.S7CpuInfo()\n        result = self.library.Cli_GetCpuInfo(self.pointer, byref(info))\n        check_error(result, context=\"client\")\n        return info",
    "docstring": "Retrieves CPU info from client"
  },
  {
    "code": "def traverse(self, predicate=lambda i, d: True,\n                 prune=lambda i, d: False, depth=-1, branch_first=True,\n                 visit_once=False, ignore_self=1):\n        return super(Tree, self).traverse(predicate, prune, depth, branch_first, visit_once, ignore_self)",
    "docstring": "For documentation, see util.Traversable.traverse\n        Trees are set to visit_once = False to gain more performance in the traversal"
  },
  {
    "code": "def generate_drone_plugin(self):\n        example = {}\n        example['pipeline'] = {}\n        example['pipeline']['appname'] = {}\n        example['pipeline']['appname']['image'] = \"\"\n        example['pipeline']['appname']['secrets'] = \"\"\n        for key, value in self.spec.items():\n            if value['type'] in (dict, list):\n                kvalue = f\"\\'{json.dumps(value.get('example', ''))}\\'\"\n            else:\n                kvalue = f\"{value.get('example', '')}\"\n            example['pipeline']['appname'][key.lower()] = kvalue\n        print(yaml.dump(example, default_flow_style=False))",
    "docstring": "Generate a sample drone plugin configuration"
  },
  {
    "code": "def _add_sync_queues_and_barrier(self, name, dependencies):\n        self._sync_queue_counter += 1\n        with tf.device(self.sync_queue_devices[self._sync_queue_counter % len(self.sync_queue_devices)]):\n            sync_queues = [\n                tf.FIFOQueue(self.num_worker, [tf.bool], shapes=[[]],\n                             shared_name='%s%s' % (name, i))\n                for i in range(self.num_worker)]\n            queue_ops = []\n            token = tf.constant(False)\n            with tf.control_dependencies(dependencies):\n                for i, q in enumerate(sync_queues):\n                    if i != self.task_index:\n                        queue_ops.append(q.enqueue(token))\n            queue_ops.append(\n                sync_queues[self.task_index].dequeue_many(len(sync_queues) - 1))\n            return tf.group(*queue_ops, name=name)",
    "docstring": "Adds ops to enqueue on all worker queues.\n\n        Args:\n            name: prefixed for the shared_name of ops.\n            dependencies: control dependency from ops.\n\n        Returns:\n            an op that should be used as control dependency before starting next step."
  },
  {
    "code": "def build():\n    try:\n        cloud_config = CloudConfig()\n        config_data = cloud_config.config_data('cluster')\n        cloud_init = CloudInit()\n        print(cloud_init.build(config_data))\n    except CloudComposeException as ex:\n        print(ex)",
    "docstring": "builds the cloud_init script"
  },
  {
    "code": "def GetCloudPath(self, resource_id, cache, database):\n    cloud_path = cache.GetResults('cloud_path')\n    if not cloud_path:\n      results = database.Query(self.CLOUD_PATH_CACHE_QUERY)\n      cache.CacheQueryResults(\n          results, 'cloud_path', 'resource_id', ('filename', 'parent'))\n      cloud_path = cache.GetResults('cloud_path')\n    if resource_id == 'folder:root':\n      return '/'\n    paths = []\n    parent_path, parent_id = cloud_path.get(resource_id, ['', ''])\n    while parent_path:\n      if parent_path == 'folder:root':\n        break\n      paths.append(parent_path)\n      parent_path, parent_id = cloud_path.get(parent_id, ['', ''])\n    if not paths:\n      return '/'\n    paths.reverse()\n    return '/{0:s}/'.format('/'.join(paths))",
    "docstring": "Return cloud path given a resource id.\n\n    Args:\n      resource_id (str): resource identifier for the file.\n      cache (SQLiteCache): cache.\n      database (SQLiteDatabase): database.\n\n    Returns:\n      str: full path to the resource value."
  },
  {
    "code": "def render_targets_weighted_spans(\n        targets,\n        preserve_density,\n    ):\n    prepared_weighted_spans = prepare_weighted_spans(\n        targets, preserve_density)\n    def _fmt_pws(pws):\n        name = ('<b>{}:</b> '.format(pws.doc_weighted_spans.vec_name)\n                if pws.doc_weighted_spans.vec_name else '')\n        return '{}{}'.format(name, render_weighted_spans(pws))\n    def _fmt_pws_list(pws_lst):\n        return '<br/>'.join(_fmt_pws(pws) for pws in pws_lst)\n    return [_fmt_pws_list(pws_lst) if pws_lst else None\n            for pws_lst in prepared_weighted_spans]",
    "docstring": "Return a list of rendered weighted spans for targets.\n    Function must accept a list in order to select consistent weight\n    ranges across all targets."
  },
  {
    "code": "def getRelationships(self, pid, subject=None, predicate=None, format=None):\n        http_args = {}\n        if subject is not None:\n            http_args['subject'] = subject\n        if predicate is not None:\n            http_args['predicate'] = predicate\n        if format is not None:\n            http_args['format'] = format\n        url = 'objects/%(pid)s/relationships' % {'pid': pid}\n        return self.get(url, params=http_args)",
    "docstring": "Get information about relationships on an object.\n\n        Wrapper function for\n         `Fedora REST API getRelationships <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-getRelationships>`_\n\n        :param pid: object pid\n        :param subject: subject (optional)\n        :param predicate: predicate (optional)\n        :param format: format\n        :rtype: :class:`requests.models.Response`"
  },
  {
    "code": "def overlap(self, x, ctrs, kdtree=None):\n        q = len(self.within(x, ctrs, kdtree=kdtree))\n        return q",
    "docstring": "Check how many balls `x` falls within. Uses a K-D Tree to\n        perform the search if provided."
  },
  {
    "code": "def handle_exception(error):\n    try:\n        if _get_acceptable_response_type() == JSON:\n            response = jsonify(error.to_dict())\n            response.status_code = error.code\n            return response\n        else:\n            return error.abort()\n    except InvalidAPIUsage:\n        response = jsonify(error.to_dict())\n        response.status_code = 415\n        return response",
    "docstring": "Return a response with the appropriate status code, message, and content\n    type when an ``InvalidAPIUsage`` exception is raised."
  },
  {
    "code": "def is_snp(reference_bases, alternate_bases):\n    if len(reference_bases) > 1:\n        return False\n    for alt in alternate_bases:\n        if alt is None:\n            return False\n        if alt not in ['A', 'C', 'G', 'T', 'N', '*']:\n            return False\n    return True",
    "docstring": "Return whether or not the variant is a SNP"
  },
  {
    "code": "def _add_cable_to_equipment_changes(network, line):\n    network.results.equipment_changes = \\\n        network.results.equipment_changes.append(\n            pd.DataFrame(\n                {'iteration_step': [0],\n                 'change': ['added'],\n                 'equipment': [line.type.name],\n                 'quantity': [1]\n                 },\n                index=[line]\n            )\n        )",
    "docstring": "Add cable to the equipment changes\n\n    All changes of equipment are stored in network.results.equipment_changes\n    which is used later to determine grid expansion costs.\n\n    Parameters\n    ----------\n    network : :class:`~.grid.network.Network`\n        The eDisGo container object\n    line : class:`~.grid.components.Line`\n        Line instance which is to be added"
  },
  {
    "code": "def gdal2np_dtype(b):\n    dt_dict = gdal_array.codes\n    if isinstance(b, str):\n        b = gdal.Open(b)\n    if isinstance(b, gdal.Dataset):\n        b = b.GetRasterBand(1)\n    if isinstance(b, gdal.Band):\n        b = b.DataType\n    if isinstance(b, int):\n        np_dtype = dt_dict[b]\n    else:\n        np_dtype = None\n        print(\"Input must be GDAL Dataset or RasterBand object\")\n    return np_dtype",
    "docstring": "Get NumPy datatype that corresponds with GDAL RasterBand datatype\n    Input can be filename, GDAL Dataset, GDAL RasterBand, or GDAL integer dtype"
  },
  {
    "code": "def add_resources(res_a, res_b):\n    return {resource: value + res_b.get(resource, 0)\n            for resource, value in iteritems(res_a)}",
    "docstring": "Return the resources after adding res_b's resources to res_a.\n\n    Parameters\n    ----------\n    res_a : dict\n        Dictionary `{resource: value, ...}`.\n    res_b : dict\n        Dictionary `{resource: value, ...}`. Must be a (non-strict) subset of\n        res_a. If A resource is not present in res_b, the value is presumed to\n        be 0."
  },
  {
    "code": "def find_by_ids(ids, connection=None, page_size=100, page_number=0,\n        sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER):\n        ids = ','.join([str(i) for i in ids])\n        return pybrightcove.connection.ItemResultSet('find_playlists_by_ids',\n            Playlist, connection, page_size, page_number, sort_by, sort_order,\n            playlist_ids=ids)",
    "docstring": "List playlists by specific IDs."
  },
  {
    "code": "def unregister_a_problem(self, prob):\n        self.source_problems.remove(prob.uuid)\n        if not self.source_problems:\n            self.is_impact = False\n            self.unset_impact_state()\n        self.broks.append(self.get_update_status_brok())",
    "docstring": "Remove the problem from our problems list\n        and check if we are still 'impacted'\n\n        :param prob: problem to remove\n        :type prob: alignak.objects.schedulingitem.SchedulingItem\n        :return: None"
  },
  {
    "code": "def task_start(self, **kw):\n        id, task = self.get_task(**kw)\n        self._execute(id, 'start')\n        return self.get_task(uuid=task['uuid'])[1]",
    "docstring": "Marks a task as started."
  },
  {
    "code": "def form_node(cls):\n    assert issubclass(cls, FormNode)\n    res = attrs(init=False, slots=True)(cls)\n    res._args = []\n    res._required_args = 0\n    res._rest_arg = None\n    state = _FormArgMode.REQUIRED\n    for field in fields(res):\n        if 'arg_mode' in field.metadata:\n            if state is _FormArgMode.REST:\n                raise RuntimeError('rest argument must be last')\n            if field.metadata['arg_mode'] is _FormArgMode.REQUIRED:\n                if state is _FormArgMode.OPTIONAL:\n                    raise RuntimeError('required arg after optional arg')\n                res._args.append(field)\n                res._required_args += 1\n            elif field.metadata['arg_mode'] is _FormArgMode.OPTIONAL:\n                state = _FormArgMode.OPTIONAL\n                res._args.append(field)\n            elif field.metadata['arg_mode'] is _FormArgMode.REST:\n                state = _FormArgMode.REST\n                res._rest_arg = field\n            else:\n                assert 0\n    return res",
    "docstring": "A class decorator to finalize fully derived FormNode subclasses."
  },
  {
    "code": "def format_arg(arg):\n    s = str(arg)\n    dot = s.rfind('.')\n    if dot >= 0:\n        s = s[dot + 1:]\n    s = s.replace(';', '')\n    s = s.replace('[]', 'Array')\n    if len(s) > 0:\n        c = s[0].lower()\n        s = c + s[1:]\n    return s",
    "docstring": "formats an argument to be shown"
  },
  {
    "code": "def clone(self):\n        \"Mimic the behavior of torch.clone for `ImagePoints` objects.\"\n        return self.__class__(FlowField(self.size, self.flow.flow.clone()), scale=False, y_first=False)",
    "docstring": "Mimic the behavior of torch.clone for `ImagePoints` objects."
  },
  {
    "code": "async def delete(self):\n        if self.is_channel:\n            await self._client(functions.channels.LeaveChannelRequest(\n                self.input_entity))\n        else:\n            if self.is_group:\n                await self._client(functions.messages.DeleteChatUserRequest(\n                    self.entity.id, types.InputPeerSelf()))\n            await self._client(functions.messages.DeleteHistoryRequest(\n                self.input_entity, 0))",
    "docstring": "Deletes the dialog from your dialog list. If you own the\n        channel this won't destroy it, only delete it from the list."
  },
  {
    "code": "def validate_signature(request, secret_key):\n    data = request.GET.copy()\n    if request.method != 'GET':\n        message_body = getattr(request, request.method, {})\n        data.update(message_body)\n    if data.get('sig', False):\n        sig = data['sig']\n        del data['sig']\n    else:\n        return False\n    if data.get('t', False):\n        timestamp = int(data.get('t', False))\n        del data['t']\n    else:\n        return False\n    local_time = datetime.utcnow()\n    remote_time = datetime.utcfromtimestamp(timestamp)\n    if local_time > remote_time:\n        delta = local_time - remote_time\n    else:   \n        delta = remote_time - local_time\n    if delta.seconds > 5 * 60:\n        return False\n    return sig == calculate_signature(secret_key, data, timestamp)",
    "docstring": "Validates the signature associated with the given request."
  },
  {
    "code": "def do_status(self, line):\n        print('{} {}'.format(bold('Pyrene version'), green(get_version())))\n        pip_conf = os.path.expanduser('~/.pip/pip.conf')\n        if os.path.exists(pip_conf):\n            conf = read_file(pip_conf)\n            repo = self._get_repo_for_pip_conf(conf)\n            if repo:\n                print(\n                    '{} is configured for repository \"{}\"'\n                    .format(bold(pip_conf), green(repo.name))\n                )\n            else:\n                print(\n                    '{} exists, but is a {}'\n                    .format(bold(pip_conf), red('custom configuration'))\n                )\n        else:\n            print('{} {}'.format(bold(pip_conf), red('does not exists')))\n        if os.path.exists(self.pypirc):\n            template = green('exists')\n        else:\n            template = red('does not exists')\n        template = '{} ' + template\n        print(template.format(bold(self.pypirc)))",
    "docstring": "Show python packaging configuration status"
  },
  {
    "code": "def RegisterBuiltin(cls, arg):\n        if arg in cls.types_dict:\n            raise RuntimeError, '%s already registered' %arg\n        class _Wrapper(arg):\n            'Wrapper for builtin %s\\n%s' %(arg, cls.__doc__)\n        _Wrapper.__name__ = '_%sWrapper' %arg.__name__\n        cls.types_dict[arg] = _Wrapper",
    "docstring": "register a builtin, create a new wrapper."
  },
  {
    "code": "def get_frame_list():\n    frame_info_list = []\n    frame_list = []\n    frame = inspect.currentframe()\n    while frame is not None:\n        frame_list.append(frame)\n        info = inspect.getframeinfo(frame)\n        frame_info_list.append(info)\n        frame = frame.f_back\n    frame_info_list.reverse()\n    frame_list.reverse()\n    frame_info_str_list = [format_frameinfo(fi) for fi in frame_info_list]\n    return frame_list, frame_info_list, frame_info_str_list",
    "docstring": "Create the list of frames"
  },
  {
    "code": "def _reset_model(self, table, model):\r\n        old_sel_model = table.selectionModel()\r\n        table.setModel(model)\r\n        if old_sel_model:\r\n            del old_sel_model",
    "docstring": "Set the model in the given table."
  },
  {
    "code": "def fit_heptad_register(crangles):\n    crangles = [x if x > 0 else 360 + x for x in crangles]\n    hept_p = [x * (360.0 / 7.0) + ((360.0 / 7.0) / 2.0) for x in range(7)]\n    ideal_crangs = [\n        hept_p[0],\n        hept_p[2],\n        hept_p[4],\n        hept_p[6],\n        hept_p[1],\n        hept_p[3],\n        hept_p[5]\n    ]\n    full_hept = len(crangles) // 7\n    ideal_crang_list = ideal_crangs * (full_hept + 2)\n    fitting = []\n    for i in range(7):\n        ang_pairs = zip(crangles, ideal_crang_list[i:])\n        ang_diffs = [abs(y - x) for x, y in ang_pairs]\n        fitting.append((i, numpy.mean(ang_diffs), numpy.std(ang_diffs)))\n    return sorted(fitting, key=lambda x: x[1])",
    "docstring": "Attempts to fit a heptad repeat to a set of Crick angles.\n\n    Parameters\n    ----------\n    crangles: [float]\n        A list of average Crick angles for the coiled coil.\n\n    Returns\n    -------\n    fit_data: [(float, float, float)]\n        Sorted list of fits for each heptad position."
  },
  {
    "code": "def get_valid_class_name(s: str) -> str:\n    s = str(s).strip()\n    s = ''.join([w.title() for w in re.split(r'\\W+|_', s)])\n    return re.sub(r'[^\\w|_]', '', s)",
    "docstring": "Return the given string converted so that it can be used for a class name\n\n    Remove leading and trailing spaces; removes spaces and capitalizes each\n    word; and remove anything that is not alphanumeric.  Returns a pep8\n    compatible class name.\n\n    :param s: The string to convert.\n    :returns: The updated string."
  },
  {
    "code": "def _check_compatibility(self):\n        stored_descr = self._file_trace_description()\n        try:\n            for k, v in self._model_trace_description():\n                assert(stored_descr[k][0] == v[0])\n        except:\n            raise ValueError(\n                \"The objects to tally are incompatible with the objects stored in the file.\")",
    "docstring": "Make sure the next objects to be tallied are compatible with the\n        stored trace."
  },
  {
    "code": "def convert_bytes(n):\n    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')\n    prefix = {}\n    for i, s in enumerate(symbols):\n        prefix[s] = 1 << (i + 1) * 10\n    for s in reversed(symbols):\n        if n >= prefix[s]:\n            value = float(n) / prefix[s]\n            return '%.1f%s' % (value, s)\n    return \"%sB\" % n",
    "docstring": "Convert a size number to 'K', 'M', .etc"
  },
  {
    "code": "def make_child_of(self, chunk):\n        if self.is_mapping():\n            for key, value in self.contents.items():\n                self.key(key, key).pointer.make_child_of(chunk.pointer)\n                self.val(key).make_child_of(chunk)\n        elif self.is_sequence():\n            for index, item in enumerate(self.contents):\n                self.index(index).make_child_of(chunk)\n        else:\n            self.pointer.make_child_of(chunk.pointer)",
    "docstring": "Link one YAML chunk to another.\n\n        Used when inserting a chunk of YAML into another chunk."
  },
  {
    "code": "def _describe_me(self):\n        return (\n            self.display_name,\n            ' (cont: %s)' % self.run_func if self.is_continuation else '',\n            ' (syscall)' if self.is_syscall else '',\n            ' (inline)' if not self.use_state_arguments else '',\n            ' (stub)' if self.is_stub else '',\n        )",
    "docstring": "return a 5-tuple of strings sufficient for formatting with ``%s%s%s%s%s`` to verbosely describe the procedure"
  },
  {
    "code": "def _name_search(cls, method, filters):\n        filters = cls._get_name_filters(filters)\n        return [\n            cls.deserialize(cls._zeep_to_dict(row)) for row in method(filters)\n        ]",
    "docstring": "Helper for search methods that use name filters.\n\n        Args:\n            method (callable): The Five9 API method to call with the name\n                filters.\n            filters (dict): A dictionary of search parameters, keyed by the\n                name of the field to search. This should conform to the\n                schema defined in :func:`five9.Five9.create_criteria`.\n\n        Returns:\n            list[BaseModel]: A list of records representing the result."
  },
  {
    "code": "def _initiate_replset(self, port, name, maxwait=30):\n        if not self.args['replicaset'] and name != 'configRepl':\n            if self.args['verbose']:\n                print('Skipping replica set initialization for %s' % name)\n            return\n        con = self.client('localhost:%i' % port)\n        try:\n            rs_status = con['admin'].command({'replSetGetStatus': 1})\n            return rs_status\n        except OperationFailure as e:\n            for i in range(maxwait):\n                try:\n                    con['admin'].command({'replSetInitiate':\n                                          self.config_docs[name]})\n                    break\n                except OperationFailure as e:\n                    print(e.message + \" - will retry\")\n                    time.sleep(1)\n            if self.args['verbose']:\n                print(\"initializing replica set '%s' with configuration: %s\"\n                      % (name, self.config_docs[name]))\n            print(\"replica set '%s' initialized.\" % name)",
    "docstring": "Initiate replica set."
  },
  {
    "code": "def _validate_xor_args(self, p):\n        if len(p[1]) != 2:\n            raise ValueError('Invalid syntax: XOR only accepts 2 arguments, got {0}: {1}'.format(len(p[1]), p))",
    "docstring": "Raises ValueError if 2 arguments are not passed to an XOR"
  },
  {
    "code": "def write_parfile(df,parfile):\n    columns = [\"parnme\",\"parval1\",\"scale\",\"offset\"]\n    formatters = {\"parnme\":lambda x:\"{0:20s}\".format(x),\n                  \"parval1\":lambda x:\"{0:20.7E}\".format(x),\n                  \"scale\":lambda x:\"{0:20.7E}\".format(x),\n                  \"offset\":lambda x:\"{0:20.7E}\".format(x)}\n    for col in columns:\n        assert col in df.columns,\"write_parfile() error: \" +\\\n                                 \"{0} not found in df\".format(col)\n    with open(parfile,'w') as f:\n        f.write(\"single point\\n\")\n        f.write(df.to_string(col_space=0,\n                      columns=columns,\n                      formatters=formatters,\n                      justify=\"right\",\n                      header=False,\n                      index=False,\n                      index_names=False) + '\\n')",
    "docstring": "write a pest parameter file from a dataframe\n\n    Parameters\n    ----------\n    df : (pandas.DataFrame)\n        dataframe with column names that correspond to the entries\n        in the parameter data section of a pest control file\n    parfile : str\n        name of the parameter file to write"
  },
  {
    "code": "def overlap(a, b):\n    _check_steps(a, b)\n    return a.stop >= b.start and b.stop >= a.start",
    "docstring": "Check if  two ranges overlap.\n\n    Parameters\n    ----------\n    a : range\n        The first range.\n    b : range\n        The second range.\n\n    Returns\n    -------\n    overlaps : bool\n        Do these ranges overlap.\n\n    Notes\n    -----\n    This function does not support ranges with step != 1."
  },
  {
    "code": "def validate(self,\n                 asset,\n                 amount,\n                 portfolio,\n                 algo_datetime,\n                 algo_current_data):\n        if self.restrictions.is_restricted(asset, algo_datetime):\n            self.handle_violation(asset, amount, algo_datetime)",
    "docstring": "Fail if the asset is in the restricted_list."
  },
  {
    "code": "def check_path(file_path):\n    directory = os.path.dirname(file_path)\n    if directory != '':\n        if not os.path.exists(directory):\n            os.makedirs(directory, 0o775)",
    "docstring": "Checks if the directories for this path exist, and creates them in case."
  },
  {
    "code": "def update(self):\n        stats = self.get_init_value()\n        if not LINUX:\n            return self.stats\n        if self.input_method == 'local':\n            stats = self.irq.get()\n        elif self.input_method == 'snmp':\n            pass\n        stats = sorted(stats,\n                       key=operator.itemgetter('irq_rate'),\n                       reverse=True)[:5]\n        self.stats = stats\n        return self.stats",
    "docstring": "Update the IRQ stats."
  },
  {
    "code": "def show(self, wid=None, text=None, title=None, url=None, verbose=False):\n        PARAMS={}\n        for p,v in zip([\"id\",\"text\",\"title\",\"url\"],[wid,text,title,url]):\n            if v:\n                PARAMS[p]=v\n        response=api(url=self.__url+\"/show?\",PARAMS=PARAMS, method=\"GET\", verbose=verbose)\n        return response",
    "docstring": "Launch an HTML browser in the Results Panel.\n\n        :param wid: Window ID\n        :param text: HTML text\n        :param title: Window Title\n        :param url: URL\n        :param verbose: print more"
  },
  {
    "code": "def expected_values(early_mean=early_mean,\n                    late_mean=late_mean,\n                    switchpoint=switchpoint):\n    n = len(disasters_array)\n    return concatenate(\n        (ones(switchpoint) * early_mean, ones(n - switchpoint) * late_mean))",
    "docstring": "Discrepancy measure for GOF using the Freeman-Tukey statistic"
  },
  {
    "code": "def collapse_degenerate_markers(linkage_records):\n    def degeneracy(linkage_record):\n        linkage_group, genetic_distance, scaffold = (\n            linkage_record[1],\n            linkage_record[2],\n            linkage_record[3],\n        )\n        return (linkage_group, genetic_distance, scaffold)\n    degenerate_records = []\n    for _, degenerate_group in itertools.groupby(\n        linkage_records, key=degeneracy\n    ):\n        group_list = list(degenerate_group)\n        start_record, end_record = group_list[0], group_list[-1]\n        assert (start_record[1], start_record[2], start_record[3]) == (\n            end_record[1],\n            end_record[2],\n            end_record[3],\n        )\n        start_position = start_record[-1]\n        end_position = end_record[-1]\n        scaffold = start_record[3]\n        linkage_group = start_record[1]\n        record = [linkage_group, start_position, end_position, scaffold]\n        degenerate_records.append(record)\n    return degenerate_records",
    "docstring": "Group all markers with no genetic distance as distinct features\n    to generate a BED file with.\n\n    Simple example with sixteen degenerate markers:\n\n        >>> marker_features = [\n        ... ['36915_sctg_207_31842', 1, 0, 207, 31842],\n        ... ['36941_sctg_207_61615', 1, 0, 207, 61615],\n        ... ['36956_sctg_207_77757', 1, 0, 207, 77757],\n        ... ['36957_sctg_207_78332', 1, 0, 207, 78332],\n        ... ['36972_sctg_207_94039', 1, 0, 207, 94039],\n        ... ['36788_sctg_207_116303', 1, 0.652, 207, 116303],\n        ... ['36812_sctg_207_158925', 1, 1.25, 207, 158925],\n        ... ['36819_sctg_207_165424', 1, 1.25, 207, 165424],\n        ... ['36828_sctg_207_190813', 1, 1.25, 207, 190813],\n        ... ['36830_sctg_207_191645', 1, 1.25, 207, 191645],\n        ... ['36834_sctg_207_195961', 1, 1.25, 207, 195961],\n        ... ['36855_sctg_207_233632', 1, 1.25, 207, 233632],\n        ... ['36881_sctg_207_258658', 1, 1.25, 207, 258658],\n        ... ['82072_sctg_486_41893', 1, 3.756, 486, 41893],\n        ... ['85634_sctg_516_36614', 1,\t3.756, 516, 36614],\n        ... ['85638_sctg_516_50582', 1, 3.756, 516, 50582]]\n\n        >>> len(marker_features)\n        16\n\n        >>> collapsed_features = collapse_degenerate_markers(marker_features)\n        >>> len(collapsed_features)\n        5\n\n    The degenerate features (identical linkage group, genetic distance and\n    original scaffold) are collapsed into a region:\n\n        >>> collapsed_features[0]\n        [1, 31842, 94039, 207]\n\n    The format is [linkage group, start, end, original scaffold].\n\n    If a singleton (non-degenerate) feature is found, the region is simply\n    a single point in the genome:\n\n        >>> collapsed_features[1]\n        [1, 116303, 116303, 207]\n\n    so 'start' and 'end' are identical.\n\n    Two markers are not considered degenerate if they belong to different\n    original scaffolds, even if they are in terms of genetic linkage:\n\n        >>> collapsed_features[2]\n        [1, 158925, 258658, 207]\n        >>> collapsed_features[3:]\n        [[1, 41893, 41893, 486], [1, 36614, 50582, 516]]"
  },
  {
    "code": "def clear_objects(self, obj):\n        for obj_name, obj_mjcf in self.mujoco_objects.items():\n            if obj_name == obj:\n                continue\n            else:\n                sim_state = self.sim.get_state()\n                sim_state.qpos[self.sim.model.get_joint_qpos_addr(obj_name)[0]] = 10\n                self.sim.set_state(sim_state)\n                self.sim.forward()",
    "docstring": "Clears objects with name @obj out of the task space. This is useful\n        for supporting task modes with single types of objects, as in\n        @self.single_object_mode without changing the model definition."
  },
  {
    "code": "def register_algorithm(self, alg_id, alg_obj):\n        if alg_id in self._algorithms:\n            raise ValueError('Algorithm already has a handler.')\n        if not isinstance(alg_obj, Algorithm):\n            raise TypeError('Object is not of type `Algorithm`')\n        self._algorithms[alg_id] = alg_obj\n        self._valid_algs.add(alg_id)",
    "docstring": "Registers a new Algorithm for use when creating and verifying tokens."
  },
  {
    "code": "def write_classifier(self, clf):\n        with open(os.path.join(self.repopath, 'classifier.pkl'), 'w') as fp:\n            pickle.dump(clf, fp)",
    "docstring": "Writes classifier object to pickle file"
  },
  {
    "code": "def setmode(mode):\n    if hasattr(mode, '__getitem__'):\n        set_custom_pin_mappings(mode)\n        mode = CUSTOM\n    assert mode in [BCM, BOARD, SUNXI, CUSTOM]\n    global _mode\n    _mode = mode",
    "docstring": "You must call this method prior to using all other calls.\n\n    :param mode: the mode, one of :py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM`,\n        :py:attr:`GPIO.SUNXI`, or a `dict` or `object` representing a custom\n        pin mapping."
  },
  {
    "code": "def _generate_sequences_for_ngram(self, t1, t2, ngram, covered_spans):\n        self._logger.debug('Generating sequences for n-gram \"{}\"'.format(\n            ngram))\n        pattern = re.compile(re.escape(ngram))\n        context_length = len(ngram)\n        t1_spans = [match.span() for match in pattern.finditer(t1)]\n        t2_spans = [match.span() for match in pattern.finditer(t2)]\n        sequences = []\n        self._logger.debug(t1)\n        for t1_span in t1_spans:\n            for t2_span in t2_spans:\n                if self._is_inside(t1_span, t2_span, covered_spans):\n                    self._logger.debug(\n                        'Skipping match due to existing coverage')\n                    continue\n                sequence = self._generate_sequence(\n                    t1, t1_span, t2, t2_span, context_length, covered_spans)\n                if sequence:\n                    sequences.append(sequence)\n        return sequences",
    "docstring": "Generates aligned sequences for the texts `t1` and `t2`, based\n        around `ngram`.\n\n        Does not generate sequences that occur within `covered_spans`.\n\n        :param t1: text content of first witness\n        :type t1: `str`\n        :param t2: text content of second witness\n        :type t2: `str`\n        :param ngram: n-gram to base sequences on\n        :type ngram: `str`\n        :param covered_spans: lists of start and end indices for parts\n                              of the texts already covered by a sequence\n        :type covered_spans: `list` of two `list`s of 2-`tuple` of `int`"
  },
  {
    "code": "def _add_delta(self, other):\n        if not isinstance(self.freq, Tick):\n            _raise_on_incompatible(self, other)\n        new_ordinals = super()._add_delta(other)\n        return type(self)(new_ordinals, freq=self.freq)",
    "docstring": "Add a timedelta-like, Tick, or TimedeltaIndex-like object\n        to self, yielding a new PeriodArray\n\n        Parameters\n        ----------\n        other : {timedelta, np.timedelta64, Tick,\n                 TimedeltaIndex, ndarray[timedelta64]}\n\n        Returns\n        -------\n        result : PeriodArray"
  },
  {
    "code": "def get_session():\n    config = PyquilConfig()\n    session = requests.Session()\n    retry_adapter = HTTPAdapter(max_retries=Retry(total=3,\n                                                  method_whitelist=['POST'],\n                                                  status_forcelist=[502, 503, 504, 521, 523],\n                                                  backoff_factor=0.2,\n                                                  raise_on_status=False))\n    session.mount(\"http://\", retry_adapter)\n    session.mount(\"https://\", retry_adapter)\n    session.headers.update({\"Accept\": \"application/octet-stream\",\n                            \"X-User-Id\": config.user_id,\n                            \"X-Api-Key\": config.api_key})\n    session.headers.update({\n        'Content-Type': 'application/json; charset=utf-8'\n    })\n    return session",
    "docstring": "Create a requests session to access the REST API\n\n    :return: requests session\n    :rtype: Session"
  },
  {
    "code": "def destroy(self, prefix_names=None):\n        if prefix_names is None:\n            self.destroy(prefix_names=self.prefixes.keys())\n            return\n        for prefix_name in prefix_names:\n            if prefix_name == 'current' and self.current in prefix_names:\n                continue\n            elif prefix_name == 'current':\n                prefix_name = self.current\n            self.get_prefix(prefix_name).destroy()\n            self.prefixes.pop(prefix_name)\n            if self.prefixes:\n                self._update_current()\n        if not self.prefixes:\n            shutil.rmtree(self.path)",
    "docstring": "Destroy all the given prefixes and remove any left files if no more\n        prefixes are left\n\n        Args:\n            prefix_names(list of str): list of prefix names to destroy, if None\n            passed (default) will destroy all of them"
  },
  {
    "code": "def iteritems(self):\n        \"Returns an iterator over the items of ConfigMap.\"\n        return chain(self._pb.StringMap.items(),\n                     self._pb.IntMap.items(),\n                     self._pb.FloatMap.items(),\n                     self._pb.BoolMap.items())",
    "docstring": "Returns an iterator over the items of ConfigMap."
  },
  {
    "code": "def from_data(cls, data):\n        messages = []\n        filename = data['checker']['filename']\n        for m in data['messages']:\n            for l in m['locations']:\n                location = l['path']\n                if not location.startswith(filename):\n                    location = filename + '/' + location\n                if l['line'] != -1:\n                    location += ':{}'.format(l['line'])\n                if l['column'] != -1:\n                    location += ':{}'.format(l['column'])\n                messages.append(\n                    cls(m['ID'], m['severity'], location, m['message'], m['suggestion'])\n                )\n        return messages",
    "docstring": "Create a list of Messages from deserialized epubcheck json output.\n\n        :param dict data: Decoded epubcheck json data\n        :return list[Message]: List of messages"
  },
  {
    "code": "def offset(requestContext, seriesList, factor):\n    for series in seriesList:\n        series.name = \"offset(%s,%g)\" % (series.name, float(factor))\n        series.pathExpression = series.name\n        for i, value in enumerate(series):\n            if value is not None:\n                series[i] = value + factor\n    return seriesList",
    "docstring": "Takes one metric or a wildcard seriesList followed by a constant, and adds\n    the constant to each datapoint.\n\n    Example::\n\n        &target=offset(Server.instance01.threads.busy,10)"
  },
  {
    "code": "def sort_and_distribute(array, splits=2):\n   if not isinstance(array, (list,tuple)): raise TypeError(\"array must be a list\")\n   if not isinstance(splits, int): raise TypeError(\"splits must be an integer\")\n   remaining = sorted(array)\n   if sys.version_info < (3, 0):\n      myrange = xrange(splits)\n   else:\n      myrange = range(splits)\n   groups = [[] for i in myrange]\n   while len(remaining) > 0:\n      for i in myrange:\n         if len(remaining) > 0: groups[i].append(remaining.pop(0))\n   return groups",
    "docstring": "Sort an array of strings to groups by alphabetically continuous\n       distribution"
  },
  {
    "code": "def save(self, parameterstep=None, simulationstep=None):\n        par = parametertools.Parameter\n        for (modelname, var2aux) in self:\n            for filename in var2aux.filenames:\n                with par.parameterstep(parameterstep), \\\n                         par.simulationstep(simulationstep):\n                    lines = [parametertools.get_controlfileheader(\n                        modelname, parameterstep, simulationstep)]\n                    for par in getattr(var2aux, filename):\n                        lines.append(repr(par) + '\\n')\n                hydpy.pub.controlmanager.save_file(filename, ''.join(lines))",
    "docstring": "Save all defined auxiliary control files.\n\n        The target path is taken from the |ControlManager| object stored\n        in module |pub|.  Hence we initialize one and override its\n        |property| `currentpath` with a simple |str| object defining the\n        test target path:\n\n        >>> from hydpy import pub\n        >>> pub.projectname = 'test'\n        >>> from hydpy.core.filetools import ControlManager\n        >>> class Test(ControlManager):\n        ...     currentpath = 'test_directory'\n        >>> pub.controlmanager = Test()\n\n        Normally, the control files would be written to disk, of course.\n        But to show (and test) the results in the following doctest,\n        file writing is temporarily redirected via |Open|:\n\n        >>> from hydpy import dummies\n        >>> from hydpy import Open\n        >>> with Open():\n        ...     dummies.aux.save(\n        ...         parameterstep='1d',\n        ...         simulationstep='12h')\n        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n        test_directory/file1.py\n        -----------------------------------\n        # -*- coding: utf-8 -*-\n        <BLANKLINE>\n        from hydpy.models.lland_v1 import *\n        <BLANKLINE>\n        simulationstep('12h')\n        parameterstep('1d')\n        <BLANKLINE>\n        eqd1(200.0)\n        <BLANKLINE>\n        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n        test_directory/file2.py\n        -----------------------------------\n        # -*- coding: utf-8 -*-\n        <BLANKLINE>\n        from hydpy.models.lland_v2 import *\n        <BLANKLINE>\n        simulationstep('12h')\n        parameterstep('1d')\n        <BLANKLINE>\n        eqd1(200.0)\n        eqd2(100.0)\n        <BLANKLINE>\n        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
  },
  {
    "code": "def _get_uri(self):\n        if not self.service.exists():\n            logging.warning(\"Service does not yet exist.\")\n        return self.service.settings.data['uri']",
    "docstring": "Will return the uri for an existing instance."
  },
  {
    "code": "def clear_all():\n    _TABLES.clear()\n    _COLUMNS.clear()\n    _STEPS.clear()\n    _BROADCASTS.clear()\n    _INJECTABLES.clear()\n    _TABLE_CACHE.clear()\n    _COLUMN_CACHE.clear()\n    _INJECTABLE_CACHE.clear()\n    for m in _MEMOIZED.values():\n        m.value.clear_cached()\n    _MEMOIZED.clear()\n    logger.debug('pipeline state cleared')",
    "docstring": "Clear any and all stored state from Orca."
  },
  {
    "code": "def _handle_tag_salt_auth_creds(self, tag, data):\n        key = tuple(data['key'])\n        log.debug(\n            'Updating auth data for %s: %s -> %s',\n            key, salt.crypt.AsyncAuth.creds_map.get(key), data['creds']\n        )\n        salt.crypt.AsyncAuth.creds_map[tuple(data['key'])] = data['creds']",
    "docstring": "Handle a salt_auth_creds event"
  },
  {
    "code": "def text_has_changed(self, text):\r\n        text = to_text_string(text)\r\n        if text:\r\n            self.lineno = int(text)\r\n        else:\r\n            self.lineno = None",
    "docstring": "Line edit's text has changed"
  },
  {
    "code": "def in_lamp_reach(p):\n    v1 = XYPoint(Lime.x - Red.x, Lime.y - Red.y)\n    v2 = XYPoint(Blue.x - Red.x, Blue.y - Red.y)\n    q = XYPoint(p.x - Red.x, p.y - Red.y)\n    s = cross_product(q, v2) / cross_product(v1, v2)\n    t = cross_product(v1, q) / cross_product(v1, v2)\n    return (s >= 0.0) and (t >= 0.0) and (s + t <= 1.0)",
    "docstring": "Check if the provided XYPoint can be recreated by a Hue lamp."
  },
  {
    "code": "def make_gradients(dims=DEFAULT_DIMS):\n    return np.meshgrid(\n        np.linspace(0.0, 1.0, dims[0]),\n        np.linspace(0.0, 1.0, dims[1])\n    )",
    "docstring": "Makes a pair of gradients to generate textures from numpy primitives.\n\n    Args:\n        dims (pair): the dimensions of the surface to create\n\n    Returns:\n        pair: A pair of surfaces."
  },
  {
    "code": "def safe_unicode_stdin(string):\n    if string is None:\n        return None\n    if is_bytes(string):\n        if FROZEN:\n            return string.decode(\"utf-8\")\n        try:\n            return string.decode(sys.stdin.encoding)\n        except UnicodeDecodeError:\n            return string.decode(sys.stdin.encoding, \"replace\")\n        except:\n            return string.decode(\"utf-8\")\n    return string",
    "docstring": "Safely convert the given string to a Unicode string,\n    decoding using ``sys.stdin.encoding`` if needed.\n\n    If running from a frozen binary, ``utf-8`` encoding is assumed.\n\n    :param variant string: the byte string or Unicode string to convert\n    :rtype: string"
  },
  {
    "code": "def get_context(self):\n        if not self.context:\n            return\n        else:\n            assert isinstance(self.context, tuple), 'Expected a Tuple not {0}'.format(type(self.context))\n        for model in self.context:\n            model_cls = utils.get_model_class(model)\n            key = utils.camel_to_snake(model_cls.__name__)\n            self.context_data[key] = self.get_instance_of(model_cls)",
    "docstring": "Create a dict with the context data\n        context is not required, but if it\n        is defined it should be a tuple"
  },
  {
    "code": "def with_code(self, code):\n        self.code = code if code != None else 'UNKNOWN'\n        self.name = code\n        return self",
    "docstring": "Sets a unique error code.\n        This method returns reference to this exception to implement Builder pattern to chain additional calls.\n\n        :param code: a unique error code\n\n        :return: this exception object"
  },
  {
    "code": "def delete_all_volumes(self):\n        if not self._manager:\n            raise RuntimeError('Volumes can only be deleted '\n                               'on swarm manager nodes')\n        volume_list = self.get_volume_list()\n        for volumes in volume_list:\n            self._api_client.remove_volume(volumes, force=True)",
    "docstring": "Remove all the volumes.\n\n        Only the manager nodes can delete a volume"
  },
  {
    "code": "def _maybe_unstack(self, obj):\n        if self._stacked_dim is not None and self._stacked_dim in obj.dims:\n            obj = obj.unstack(self._stacked_dim)\n            for dim in self._inserted_dims:\n                if dim in obj.coords:\n                    del obj.coords[dim]\n        return obj",
    "docstring": "This gets called if we are applying on an array with a\n        multidimensional group."
  },
  {
    "code": "def add_row_range_from_keys(\n        self, start_key=None, end_key=None, start_inclusive=True, end_inclusive=False\n    ):\n        row_range = RowRange(start_key, end_key, start_inclusive, end_inclusive)\n        self.row_ranges.append(row_range)",
    "docstring": "Add row range to row_ranges list from the row keys\n\n        For example:\n\n        .. literalinclude:: snippets_table.py\n            :start-after: [START bigtable_row_range_from_keys]\n            :end-before: [END bigtable_row_range_from_keys]\n\n        :type start_key: bytes\n        :param start_key: (Optional) Start key of the row range. If left empty,\n                          will be interpreted as the empty string.\n\n        :type end_key: bytes\n        :param end_key: (Optional) End key of the row range. If left empty,\n                        will be interpreted as the empty string and range will\n                        be unbounded on the high end.\n\n        :type start_inclusive: bool\n        :param start_inclusive: (Optional) Whether the ``start_key`` should be\n                        considered inclusive. The default is True (inclusive).\n\n        :type end_inclusive: bool\n        :param end_inclusive: (Optional) Whether the ``end_key`` should be\n                  considered inclusive. The default is False (exclusive)."
  },
  {
    "code": "def percentage_of_reoccurring_datapoints_to_all_datapoints(x):\n    if len(x) == 0:\n        return np.nan\n    unique, counts = np.unique(x, return_counts=True)\n    if counts.shape[0] == 0:\n        return 0\n    return np.sum(counts > 1) / float(counts.shape[0])",
    "docstring": "Returns the percentage of unique values, that are present in the time series\n    more than once.\n\n        len(different values occurring more than once) / len(different values)\n\n    This means the percentage is normalized to the number of unique values,\n    in contrast to the percentage_of_reoccurring_values_to_all_values.\n\n    :param x: the time series to calculate the feature of\n    :type x: numpy.ndarray\n    :return: the value of this feature\n    :return type: float"
  },
  {
    "code": "def node(self, content):\n        ns = content.type.namespace()\n        if content.type.form_qualified:\n            node = Element(content.tag, ns=ns)\n            if ns[0]:\n                node.addPrefix(ns[0], ns[1])\n        else:\n            node = Element(content.tag)\n        self.encode(node, content)\n        log.debug(\"created - node:\\n%s\", node)\n        return node",
    "docstring": "Create an XML node.\n\n        The XML node is namespace qualified as defined by the corresponding\n        schema element."
  },
  {
    "code": "def fetch(self):\r\n        fetch_kwargs = {'multiple': True}\r\n        fetch_args = []\r\n        if self.is_prune():\r\n            fetch_kwargs['prune'] = True\r\n        if self.settings['fetch.all']:\r\n            fetch_kwargs['all'] = True\r\n        else:\r\n            if '.' in self.remotes:\r\n                self.remotes.remove('.')\r\n                if not self.remotes:\r\n                    return\r\n            fetch_args.append(self.remotes)\r\n        try:\r\n            self.git.fetch(*fetch_args, **fetch_kwargs)\r\n        except GitError as error:\r\n            error.message = \"`git fetch` failed\"\r\n            raise error",
    "docstring": "Fetch the recent refs from the remotes.\r\n\r\n        Unless git-up.fetch.all is set to true, all remotes with\r\n        locally existent branches will be fetched."
  },
  {
    "code": "def origin_central_asia(origin):\n    return origin_afghanistan(origin) or origin_kazakhstan(origin) \\\n           or origin_kyrgyzstan(origin) or origin_tajikistan(origin) \\\n           or origin_turkmenistan(origin) or origin_uzbekistan(origin)",
    "docstring": "\\\n    Returns if the origin is located in Central Asia.\n\n    Holds true for the following countries:\n        * Afghanistan\n        * Kazakhstan\n        * Kyrgyzstan\n        * Tajikistan\n        * Turkmenistan\n        * Uzbekistan\n\n    `origin`\n        The origin to check."
  },
  {
    "code": "def get_library_progress(self):\n    kbp_dict = self._get_api_call('get_library_progress')\n    return {asin: KindleCloudReaderAPI._kbp_to_progress(kbp)\n            for asin, kbp in kbp_dict.iteritems()}",
    "docstring": "Returns the reading progress for all books in the kindle library.\n\n    Returns:\n      A mapping of ASINs to `ReadingProgress` instances corresponding to the\n      books in the current user's library."
  },
  {
    "code": "def attach(self, container, stdout=True, stderr=True,\n               stream=False, logs=False, demux=False):\n        params = {\n            'logs': logs and 1 or 0,\n            'stdout': stdout and 1 or 0,\n            'stderr': stderr and 1 or 0,\n            'stream': stream and 1 or 0\n        }\n        headers = {\n            'Connection': 'Upgrade',\n            'Upgrade': 'tcp'\n        }\n        u = self._url(\"/containers/{0}/attach\", container)\n        response = self._post(u, headers=headers, params=params, stream=True)\n        output = self._read_from_socket(\n            response, stream, self._check_is_tty(container), demux=demux)\n        if stream:\n            return CancellableStream(output, response)\n        else:\n            return output",
    "docstring": "Attach to a container.\n\n        The ``.logs()`` function is a wrapper around this method, which you can\n        use instead if you want to fetch/stream container output without first\n        retrieving the entire backlog.\n\n        Args:\n            container (str): The container to attach to.\n            stdout (bool): Include stdout.\n            stderr (bool): Include stderr.\n            stream (bool): Return container output progressively as an iterator\n                of strings, rather than a single string.\n            logs (bool): Include the container's previous output.\n            demux (bool): Keep stdout and stderr separate.\n\n        Returns:\n            By default, the container's output as a single string (two if\n            ``demux=True``: one for stdout and one for stderr).\n\n            If ``stream=True``, an iterator of output strings. If\n            ``demux=True``, two iterators are returned: one for stdout and one\n            for stderr.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def generate_trunc_gr_magnitudes(bval, mmin, mmax, nsamples):\n    sampler = np.random.uniform(0., 1., nsamples)\n    beta = bval * np.log(10.)\n    return (-1. / beta) * (\n        np.log(1. - sampler * (1 - np.exp(-beta * (mmax - mmin))))) + mmin",
    "docstring": "Generate a random list of magnitudes distributed according to a\n    truncated Gutenberg-Richter model\n\n    :param float bval:\n        b-value\n    :param float mmin:\n        Minimum Magnitude\n    :param float mmax:\n        Maximum Magnitude\n    :param int nsamples:\n        Number of samples\n\n    :returns:\n        Vector of generated magnitudes"
  },
  {
    "code": "def execute_command(command=None):\n    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    stdout, stdin = process.communicate()\n    process.wait()\n    return (stdout, stdin), process.returncode",
    "docstring": "Execute a command and return the stdout and stderr."
  },
  {
    "code": "def _get_assessment_part(self, part_id=None):\n        if part_id is None:\n            return self._assessment_part\n        if part_id not in self._assessment_parts:\n            lookup_session = self._get_assessment_part_lookup_session()\n            self._assessment_parts[part_id] = lookup_session.get_assessment_part(part_id)\n        return self._assessment_parts[part_id]",
    "docstring": "Gets an AssessmentPart given a part_id.\n\n        Returns this Section's own part if part_id is None.\n\n        Make this a private part, so that it doesn't collide with the AssessmentPart.get_assessment_part\n        method, which does not expect any arguments..."
  },
  {
    "code": "def reset(self, collection, jsonFieldInit = None) :\n        if not jsonFieldInit:\n            jsonFieldInit = {}\n        self.collection = collection\n        self.connection = self.collection.connection\n        self.documentsURL = self.collection.documentsURL\n        self.URL = None\n        self.setPrivates(jsonFieldInit)\n        self._store = DocumentStore(self.collection, validators=self.collection._fields, initDct=jsonFieldInit)\n        if self.collection._validation['on_load']:\n            self.validate()\n        self.modified = True",
    "docstring": "replaces the current values in the document by those in jsonFieldInit"
  },
  {
    "code": "def inflate_dtype(arr, names):\n    arr = np.asanyarray(arr)\n    if has_structured_dt(arr):\n        return arr.dtype\n    s_dt = arr.dtype\n    dt = [(n, s_dt) for n in names]\n    dt = np.dtype(dt)\n    return dt",
    "docstring": "Create structured dtype from a 2d ndarray with unstructured dtype."
  },
  {
    "code": "def get_complete_version(version=None):\n    if version is None:\n        from graphene import VERSION as version\n    else:\n        assert len(version) == 5\n        assert version[3] in (\"alpha\", \"beta\", \"rc\", \"final\")\n    return version",
    "docstring": "Returns a tuple of the graphene version. If version argument is non-empty,\n    then checks for correctness of the tuple provided."
  },
  {
    "code": "def add_sample(self, **data):\n        missing_dimensions = set(data).difference(self.dimensions)\n        if missing_dimensions:\n            raise KeyError('Dimensions not defined in this series: %s'\n                           % ', '.join(missing_dimensions))\n        for dim in self.dimensions:\n            getattr(self, dim).append(data.get(dim))",
    "docstring": "Add a sample to this series."
  },
  {
    "code": "def process_announcement( sender_namerec, op, working_dir ):\n    node_config = get_blockstack_opts()\n    announce_hash = op['message_hash']\n    announcer_id = op['announcer_id']\n    name_history = sender_namerec['history']\n    allowed_value_hashes = []\n    for block_height in name_history.keys():\n        for historic_namerec in name_history[block_height]:\n            if historic_namerec.get('value_hash'):\n                allowed_value_hashes.append(historic_namerec['value_hash'])\n    if announce_hash not in allowed_value_hashes:\n        log.warning(\"Announce hash {} not found in name history for {}\".format(announce_hash, announcer_id))\n        return \n    zonefiles_dir = node_config.get('zonefiles', None)\n    if not zonefiles_dir:\n        log.warning(\"This node does not store zone files, so no announcement can be found\")\n        return \n    announce_text = get_atlas_zonefile_data(announce_hash, zonefiles_dir)\n    if announce_text is None:\n        log.warning(\"No zone file {} found\".format(announce_hash))\n        return\n    log.critical(\"ANNOUNCEMENT (from %s): %s\\n------BEGIN MESSAGE------\\n%s\\n------END MESSAGE------\\n\" % (announcer_id, announce_hash, announce_text))         \n    store_announcement( working_dir, announce_hash, announce_text )",
    "docstring": "If the announcement is valid, then immediately record it."
  },
  {
    "code": "def _get_lowstate(self):\n        if not self.request.body:\n            return\n        data = self.deserialize(self.request.body)\n        self.request_payload = copy(data)\n        if data and 'arg' in data and not isinstance(data['arg'], list):\n            data['arg'] = [data['arg']]\n        if not isinstance(data, list):\n            lowstate = [data]\n        else:\n            lowstate = data\n        return lowstate",
    "docstring": "Format the incoming data into a lowstate object"
  },
  {
    "code": "def url_generator(network=None, path=''):\n    network_object = ipaddress.ip_network(network)\n    if network_object.num_addresses > 256:\n        logger.error('Scan limited to 256 addresses, requested %d.', network_object.num_addresses)\n        raise NotImplementedError\n    elif network_object.num_addresses > 1:\n        network_hosts = network_object.hosts()\n    else:\n        network_hosts = [network_object.network_address]\n    return (urlunsplit(('http',str(ip),path,'','')) for ip in network_hosts)",
    "docstring": "Return a tuple of URLs with path, one for each host on network\n\n    `network` - IP address and subnet mask compatible with \n    [ipaddress library](https://docs.python.org/3/library/ipaddress.html#ipaddress.ip_network)  \n    `path` - Path portion of a URL as defined by \n    [url(un)split](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlsplit)"
  },
  {
    "code": "def send_reset_password_instructions(user):\n    token = generate_reset_password_token(user)\n    url = url_for(\"login.reset_password\", token=token)\n    reset_link = request.url_root[:-1] + url\n    subject = _(\"Password reset instruction for {site_name}\").format(\n        site_name=current_app.config.get(\"SITE_NAME\")\n    )\n    mail_template = \"password_reset_instructions\"\n    send_mail(subject, user.email, mail_template, user=user, reset_link=reset_link)",
    "docstring": "Send the reset password instructions email for the specified user.\n\n    :param user: The user to send the instructions to"
  },
  {
    "code": "def handle_unsubscribe(self, request):\n        subscribe = self._subscription_keys.pop(request.generate_key())\n        ret = self._tree.handle_unsubscribe(subscribe, subscribe.path[1:])\n        return ret",
    "docstring": "Handle a Unsubscribe request from outside. Called with lock taken"
  },
  {
    "code": "def _has_converged(pi_star, pi):\n    node_count = pi.shape[0]\n    EPS = 10e-6\n    for i in range(node_count):\n        if pi[i] - pi_star[i] > EPS:\n            return False\n    return True",
    "docstring": "Checks if the random walk has converged.\n\n    :param pi_star: the new vector\n    :param pi: the old vector\n    :returns: bool-- True iff pi has converged."
  },
  {
    "code": "def getCursor(self):\n\t\tif self.connection is None:\n\t\t\tself.Connect()\n\t\treturn self.connection.cursor(MySQLdb.cursors.DictCursor)",
    "docstring": "Get a Dictionary Cursor for executing queries"
  },
  {
    "code": "def log_commit( self, block_id, vtxindex, op, opcode, op_data ):\n        debug_op = self.sanitize_op( op_data )\n        if 'history' in debug_op:\n            del debug_op['history'] \n        log.debug(\"COMMIT %s (%s) at (%s, %s) data: %s\", opcode, op, block_id, vtxindex, \n                \", \".join( [\"%s='%s'\" % (k, debug_op[k]) for k in sorted(debug_op.keys())] ) )\n        return",
    "docstring": "Log a committed operation"
  },
  {
    "code": "def handle_button(self, event, event_type):\n        mouse_button_number = self._get_mouse_button_number(event)\n        if event_type in (25, 26):\n            event_type = event_type + (mouse_button_number * 0.1)\n        event_type_string, event_code, value, scan = self.codes[event_type]\n        if event_type_string == \"Key\":\n            scan_event, key_event = self.emulate_press(\n                event_code, scan, value, self.timeval)\n            self.events.append(scan_event)\n            self.events.append(key_event)\n        click_state = self._get_click_state(event)\n        repeat = self.emulate_repeat(click_state, self.timeval)\n        self.events.append(repeat)",
    "docstring": "Convert the button information from quartz into evdev format."
  },
  {
    "code": "def deserialize(self, data):\n        ct_in_map = {\n            'application/x-www-form-urlencoded': self._form_loader,\n            'application/json': salt.utils.json.loads,\n            'application/x-yaml': salt.utils.yaml.safe_load,\n            'text/yaml': salt.utils.yaml.safe_load,\n            'text/plain': salt.utils.json.loads\n        }\n        try:\n            value, parameters = cgi.parse_header(self.request.headers['Content-Type'])\n            return ct_in_map[value](tornado.escape.native_str(data))\n        except KeyError:\n            self.send_error(406)\n        except ValueError:\n            self.send_error(400)",
    "docstring": "Deserialize the data based on request content type headers"
  },
  {
    "code": "def write(self, fd, bytes):\n        args = {\n            'fd': fd,\n            'block': base64.encodebytes(bytes).decode(),\n        }\n        return self._client.json('filesystem.write', args)",
    "docstring": "Write a block of bytes to an open file descriptor (that is open with one of the writing modes\n\n        :param fd: file descriptor\n        :param bytes: bytes block to write\n        :return:\n\n        :note: don't overkill the node with large byte chunks, also for large file upload check the upload method."
  },
  {
    "code": "def dump(cls):\n        d = OrderedDict(cls.Items())\n        d[\"__classname__\"] = cls.__name__\n        for attr, klass in cls.Subclasses():\n            d[attr] = klass.dump()\n        return OrderedDict([(cls.__name__, d)])",
    "docstring": "Dump data into a dict.\n\n        .. versionadded:: 0.0.2"
  },
  {
    "code": "def recompute_tabs_titles(self):\n        use_vte_titles = self.settings.general.get_boolean(\"use-vte-titles\")\n        if not use_vte_titles:\n            return\n        for terminal in self.get_notebook().iter_terminals():\n            page_num = self.get_notebook().page_num(terminal.get_parent())\n            self.get_notebook().rename_page(page_num, self.compute_tab_title(terminal), False)",
    "docstring": "Updates labels on all tabs. This is required when `self.abbreviate`\n        changes"
  },
  {
    "code": "def children(self):\n        from warnings import warn\n        warn(\"Deprecated. Use Scraper.descendants.\", DeprecationWarning)\n        for descendant in self.descendants:\n            yield descendant",
    "docstring": "Former, misleading name for descendants."
  },
  {
    "code": "def find(self, name):\n        for c in self.children:\n            if c.name == name:\n                return c\n            result = c.find(name)\n            if result:\n                return result",
    "docstring": "Finds a possible child whose name match the name parameter.\n\n        :param name: name of the child node to look up\n        :type name: str\n\n        :return: DocumentNode or None"
  },
  {
    "code": "def _check_for_boolean_pair_reduction(self, kwargs):\n        if 'reduction_forcing_pairs' in self._meta_data:\n            for key1, key2 in self._meta_data['reduction_forcing_pairs']:\n                kwargs = self._reduce_boolean_pair(kwargs, key1, key2)\n        return kwargs",
    "docstring": "Check if boolean pairs should be reduced in this resource."
  },
  {
    "code": "def evalall(self, loc=None, defaults=None):\n        self.check()\n        if defaults is None:\n            defaults = cma_default_options\n        if 'N' in loc:\n            popsize = self('popsize', defaults['popsize'], loc)\n            for k in list(self.keys()):\n                k = self.corrected_key(k)\n                self.eval(k, defaults[k],\n                          {'N':loc['N'], 'popsize':popsize})\n        self._lock_setting = True\n        return self",
    "docstring": "Evaluates all option values in environment `loc`.\n\n        :See: `eval()`"
  },
  {
    "code": "def generate_schema_mapping(resolver, schema_uri, depth=1):\n    visitor = SchemaVisitor({'$ref': schema_uri}, resolver)\n    return _generate_schema_mapping(visitor, set(), depth)",
    "docstring": "Try and recursively iterate a JSON schema and to generate an ES mapping\n    that encasulates it."
  },
  {
    "code": "def format_stackdriver_json(record, message):\n    subsecond, second = math.modf(record.created)\n    payload = {\n        \"message\": message,\n        \"timestamp\": {\"seconds\": int(second), \"nanos\": int(subsecond * 1e9)},\n        \"thread\": record.thread,\n        \"severity\": record.levelname,\n    }\n    return json.dumps(payload)",
    "docstring": "Helper to format a LogRecord in in Stackdriver fluentd format.\n\n        :rtype: str\n        :returns: JSON str to be written to the log file."
  },
  {
    "code": "def text_entry(self, prompt, message=None, allow_blank=False, strip=True,\n            rofi_args=None, **kwargs):\n        def text_validator(text):\n            if strip:\n                text = text.strip()\n            if not allow_blank:\n                if not text:\n                    return None, \"A value is required.\"\n            return text, None\n        return self.generic_entry(prompt, text_validator, message, rofi_args, **kwargs)",
    "docstring": "Prompt the user to enter a piece of text.\n\n        Parameters\n        ----------\n        prompt: string\n            Prompt to display to the user.\n        message: string, optional\n            Message to display under the entry line.\n        allow_blank: Boolean\n            Whether to allow blank entries.\n        strip: Boolean\n            Whether to strip leading and trailing whitespace from the entered\n            value.\n\n        Returns\n        -------\n        string, or None if the dialog was cancelled."
  },
  {
    "code": "def dispatch(self, *args, **kwargs):\n        return super(GetAppListJsonView, self).dispatch(*args, **kwargs)",
    "docstring": "Only staff members can access this view"
  },
  {
    "code": "def diffse(self, x1, x2):\n        f1, f1se = self(x1)\n        f2, f2se = self(x2)\n        if self.paired:\n            fx1 = np.array(self.cache[tuple(x1)])\n            fx2 = np.array(self.cache[tuple(x2)])\n            diffse = np.std(fx1-fx2, ddof=1)/self.N**.5 \n            return diffse\n        else:\n            return (f1se**2 + f2se**2)**.5",
    "docstring": "Standard error of the difference between the function values at x1 and x2"
  },
  {
    "code": "def server_list(endpoint_id):\n    endpoint, server_list = get_endpoint_w_server_list(endpoint_id)\n    if server_list == \"S3\":\n        server_list = {\"s3_url\": endpoint[\"s3_url\"]}\n        fields = [(\"S3 URL\", \"s3_url\")]\n        text_format = FORMAT_TEXT_RECORD\n    else:\n        fields = (\n            (\"ID\", \"id\"),\n            (\"URI\", lambda s: (s[\"uri\"] or \"none (Globus Connect Personal)\")),\n        )\n        text_format = FORMAT_TEXT_TABLE\n    formatted_print(server_list, text_format=text_format, fields=fields)",
    "docstring": "Executor for `globus endpoint server list`"
  },
  {
    "code": "def card(self):\n        body, more, is_markdown = self._entry_content\n        return TrueCallableProxy(\n            self._get_card,\n            body or more) if is_markdown else CallableProxy(None)",
    "docstring": "Get the entry's OpenGraph card"
  },
  {
    "code": "def get_virtualenv_env_data(mgr):\n    if not mgr.find_virtualenv_envs:\n        return {}\n    mgr.log.debug(\"Looking for virtualenv environments in %s...\", mgr.virtualenv_env_dirs)\n    env_paths = find_env_paths_in_basedirs(mgr.virtualenv_env_dirs)\n    mgr.log.debug(\"Scanning virtualenv environments for python kernels...\")\n    env_data = convert_to_env_data(mgr=mgr,\n                                   env_paths=env_paths,\n                                   validator_func=validate_IPykernel,\n                                   activate_func=_get_env_vars_for_virtualenv_env,\n                                   name_template=mgr.virtualenv_prefix_template,\n                                   display_name_template=mgr.display_name_template,\n                                   name_prefix=\"\")\n    return env_data",
    "docstring": "Finds kernel specs from virtualenv environments\n\n    env_data is a structure {name -> (resourcedir, kernel spec)}"
  },
  {
    "code": "def theme(self, text):\n        return self.theme_color + self.BRIGHT + text + self.RESET",
    "docstring": "Theme style."
  },
  {
    "code": "def product(sequence, initial=1):\n    if not isinstance(sequence, collections.Iterable):\n        raise TypeError(\"'{}' object is not iterable\".format(type(sequence).__name__))\n    return reduce(operator.mul, sequence, initial)",
    "docstring": "like the built-in sum, but for multiplication."
  },
  {
    "code": "def execute_code_block(elem, doc):\n    command = select_executor(elem, doc).split(' ')\n    code = elem.text\n    if 'plt' in elem.attributes or 'plt' in elem.classes:\n        code = save_plot(code, elem)\n    command.append(code)\n    if 'args' in elem.attributes:\n        for arg in elem.attributes['args'].split():\n            command.append(arg)\n    cwd = elem.attributes['wd'] if 'wd' in elem.attributes else None\n    return subprocess.run(command,\n                          encoding='utf8',\n                          stdout=subprocess.PIPE,\n                          stderr=subprocess.STDOUT,\n                          cwd=cwd).stdout",
    "docstring": "Executes a code block by passing it to the executor.\n\n    Args:\n        elem The AST element.\n        doc  The document.\n\n    Returns:\n        The output of the command."
  },
  {
    "code": "def associate_blocks(blocks, layout_pairs, start_peb_num):\n    seq_blocks = []\n    for layout_pair in layout_pairs:\n        seq_blocks = sort.by_image_seq(blocks, blocks[layout_pair[0]].ec_hdr.image_seq)\n        layout_pair.append(seq_blocks)\n    return layout_pairs",
    "docstring": "Group block indexes with appropriate layout pairs\n\n    Arguments:\n    List:blocks        -- List of block objects\n    List:layout_pairs  -- List of grouped layout blocks\n    Int:start_peb_num  -- Number of the PEB to start from.\n\n    Returns:\n    List -- Layout block pairs grouped with associated block ranges."
  },
  {
    "code": "def write_config(ip, mac, single, double, long, touch):\n    click.echo(\"Write configuration to device %s\" % ip)\n    data = {\n        'single': single,\n        'double': double,\n        'long': long,\n        'touch': touch,\n    }\n    request = requests.post(\n        'http://{}/{}/{}/'.format(ip, URI, mac), data=data, timeout=TIMEOUT)\n    if request.status_code == 200:\n        click.echo(\"Configuration of %s set\" % mac)",
    "docstring": "Write the current configuration of a myStrom button."
  },
  {
    "code": "def add_user_to_group(self, GroupID, UserID):\n        log.info('Add User %s to Group %s' % (UserID, GroupID))\n        self.put('groups/%s/add_user/%s.json' % (GroupID, UserID))",
    "docstring": "Add a user to a group."
  },
  {
    "code": "def schema_columns(self):\n        t = self.schema_term\n        columns = []\n        if t:\n            for i, c in enumerate(t.children):\n                if c.term_is(\"Table.Column\"):\n                    p = c.all_props\n                    p['pos'] = i\n                    p['name'] = c.value\n                    p['header'] = self._name_for_col_term(c, i)\n                    columns.append(p)\n        return columns",
    "docstring": "Return column informatino only from this schema"
  },
  {
    "code": "def rvs(self, *args, **kwargs):\n        size = kwargs.pop('size', 1)\n        random_state = kwargs.pop('size', None)\n        return self._kde.sample(n_samples=size, random_state=random_state)",
    "docstring": "Draw Random Variates.\n\n        Parameters\n        ----------\n        size: int, optional (default=1)\n        random_state_: optional (default=None)"
  },
  {
    "code": "def last_metric_eval(multiplexer, session_name, metric_name):\n  try:\n    run, tag = run_tag_from_session_and_metric(session_name, metric_name)\n    tensor_events = multiplexer.Tensors(run=run, tag=tag)\n  except KeyError as e:\n    raise KeyError(\n        'Can\\'t find metric %s for session: %s. Underlying error message: %s'\n        % (metric_name, session_name, e))\n  last_event = tensor_events[-1]\n  return (last_event.wall_time,\n          last_event.step,\n          tf.make_ndarray(last_event.tensor_proto).item())",
    "docstring": "Returns the last evaluations of the given metric at the given session.\n\n  Args:\n    multiplexer: The EventMultiplexer instance allowing access to\n        the exported summary data.\n    session_name: String. The session name for which to get the metric\n        evaluations.\n    metric_name: api_pb2.MetricName proto. The name of the metric to use.\n\n  Returns:\n    A 3-tuples, of the form [wall-time, step, value], denoting\n    the last evaluation of the metric, where wall-time denotes the wall time\n    in seconds since UNIX epoch of the time of the evaluation, step denotes\n    the training step at which the model is evaluated, and value denotes the\n    (scalar real) value of the metric.\n\n  Raises:\n    KeyError if the given session does not have the metric."
  },
  {
    "code": "def as_csv(self):\n        from io import StringIO\n        s = StringIO()\n        w = csv.writer(s)\n        for row in self.rows:\n            w.writerow(row)\n        return s.getvalue()",
    "docstring": "Return a CSV representation as a string"
  },
  {
    "code": "def create_organization_team(self, auth, org_name, name, description=None, permission=\"read\"):\n        data = {\n            \"name\": name,\n            \"description\": description,\n            \"permission\": permission\n        }\n        url = \"/admin/orgs/{o}/teams\".format(o=org_name)\n        response = self.post(url, auth=auth, data=data)\n        return GogsTeam.from_json(response.json())",
    "docstring": "Creates a new team of the organization.\n\n        :param auth.Authentication auth: authentication object, must be admin-level\n        :param str org_name: Organization user name\n        :param str name: Full name of the team\n        :param str description: Description of the team\n        :param str permission: Team permission, can be read, write or admin, default is read\n        :return: a representation of the created team\n        :rtype: GogsTeam\n        :raises NetworkFailure: if there is an error communicating with the server\n        :raises ApiFailure: if the request cannot be serviced"
  },
  {
    "code": "def log(db, job_id, timestamp, level, process, message):\n    db('INSERT INTO log (job_id, timestamp, level, process, message) '\n       'VALUES (?X)', (job_id, timestamp, level, process, message))",
    "docstring": "Write a log record in the database.\n\n    :param db:\n        a :class:`openquake.server.dbapi.Db` instance\n    :param job_id:\n        a job ID\n    :param timestamp:\n        timestamp to store in the log record\n    :param level:\n        logging level to store in the log record\n    :param process:\n        process ID to store in the log record\n    :param message:\n        message to store in the log record"
  },
  {
    "code": "def get_default_domain(request, get_name=True):\n    domain_id = request.session.get(\"domain_context\", None)\n    domain_name = request.session.get(\"domain_context_name\", None)\n    if VERSIONS.active >= 3 and domain_id is None:\n        domain_id = request.user.user_domain_id\n        domain_name = request.user.user_domain_name\n        if get_name and not request.user.is_federated:\n            try:\n                domain = domain_get(request, domain_id)\n                domain_name = domain.name\n            except exceptions.NotAuthorized:\n                LOG.debug(\"Cannot retrieve domain information for \"\n                          \"user (%(user)s) that does not have an admin role \"\n                          \"on project (%(project)s)\",\n                          {'user': request.user.username,\n                           'project': request.user.project_name})\n            except Exception:\n                LOG.warning(\"Unable to retrieve Domain: %s\", domain_id)\n    domain = base.APIDictWrapper({\"id\": domain_id,\n                                  \"name\": domain_name})\n    return domain",
    "docstring": "Gets the default domain object to use when creating Identity object.\n\n    Returns the domain context if is set, otherwise return the domain\n    of the logon user.\n\n    :param get_name: Whether to get the domain name from Keystone if the\n        context isn't set.  Setting this to False prevents an unnecessary call\n        to Keystone if only the domain ID is needed."
  },
  {
    "code": "def parse_expression(source: str) -> ExpressionSource:\n    if not is_expression(source):\n        msg = 'Expression is not valid. Expression should be matched with regular expression: {0}'\\\n              .format(EXPRESSION_REGEX)\n        raise ExpressionError(msg, source)\n    if not source.startswith('{'):\n        [type_, source] = source.split(':', 1)\n    elif source.endswith('}}'):\n        type_ = 'twoways'\n    else:\n        type_ = 'oneway'\n    return (type_, source[1:-1])",
    "docstring": "Returns tuple with expression type and expression body"
  },
  {
    "code": "def log(self, workunit, level, *msg_elements):\n    with self._lock:\n      for reporter in self._reporters.values():\n        reporter.handle_log(workunit, level, *msg_elements)",
    "docstring": "Log a message.\n\n    Each element of msg_elements is either a message string or a (message, detail) pair."
  },
  {
    "code": "def process_events(self, data):\n        events = bridge.loads(data)\n        if self.debug:\n            print(\"======== Py <-- Native ======\")\n            for event in events:\n                print(event)\n            print(\"===========================\")\n        for event in events:\n            if event[0] == 'event':\n                self.handle_event(event)",
    "docstring": "The native implementation must use this call to"
  },
  {
    "code": "def subscribed(self, build_root, handlers):\n    command_list = [['subscribe',\n                     build_root,\n                     handler.name,\n                     handler.metadata] for handler in handlers]\n    self._logger.debug('watchman command_list is: {}'.format(command_list))\n    try:\n      for event in self.client.stream_query(command_list):\n        if event is None:\n          yield None, None\n        elif 'subscribe' in event:\n          self._logger.info('confirmed watchman subscription: {}'.format(event))\n          yield None, None\n        elif 'subscription' in event:\n          yield event.get('subscription'), event\n        else:\n          self._logger.warning('encountered non-subscription event: {}'.format(event))\n    except self.client.WatchmanError as e:\n      raise self.WatchmanCrash(e)",
    "docstring": "Bulk subscribe generator for StreamableWatchmanClient.\n\n    :param str build_root: the build_root for all subscriptions.\n    :param iterable handlers: a sequence of Watchman.EventHandler namedtuple objects.\n    :yields: a stream of tuples in the form (subscription_name: str, subscription_event: dict)."
  },
  {
    "code": "def playlist(self, playlist_id, *, include_songs=False):\n\t\tplaylist_info = next(\n\t\t\t(\n\t\t\t\tplaylist\n\t\t\t\tfor playlist in self.playlists(include_songs=include_songs)\n\t\t\t\tif playlist['id'] == playlist_id\n\t\t\t),\n\t\t\tNone\n\t\t)\n\t\treturn playlist_info",
    "docstring": "Get information about a playlist.\n\n\t\tParameters:\n\t\t\tplaylist_id (str): A playlist ID.\n\t\t\tinclude_songs (bool, Optional): Include songs from\n\t\t\t\tthe playlist in the returned dict.\n\t\t\t\tDefault: ``False``\n\n\t\tReturns:\n\t\t\tdict: Playlist information."
  },
  {
    "code": "def _complete_statement(self, line: str) -> Statement:\n        while True:\n            try:\n                statement = self.statement_parser.parse(line)\n                if statement.multiline_command and statement.terminator:\n                    break\n                if not statement.multiline_command:\n                    break\n            except ValueError:\n                statement = self.statement_parser.parse_command_only(line)\n                if not statement.multiline_command:\n                    raise\n            try:\n                self.at_continuation_prompt = True\n                newline = self.pseudo_raw_input(self.continuation_prompt)\n                if newline == 'eof':\n                    newline = '\\n'\n                    self.poutput(newline)\n                line = '{}\\n{}'.format(statement.raw, newline)\n            except KeyboardInterrupt as ex:\n                if self.quit_on_sigint:\n                    raise ex\n                else:\n                    self.poutput('^C')\n                    statement = self.statement_parser.parse('')\n                    break\n            finally:\n                self.at_continuation_prompt = False\n        if not statement.command:\n            raise EmptyStatement()\n        return statement",
    "docstring": "Keep accepting lines of input until the command is complete.\n\n        There is some pretty hacky code here to handle some quirks of\n        self.pseudo_raw_input(). It returns a literal 'eof' if the input\n        pipe runs out. We can't refactor it because we need to retain\n        backwards compatibility with the standard library version of cmd."
  },
  {
    "code": "def update(self, *sources, follow_symlinks: bool=False,\n               maximum_depth: int=20):\n        for source in sources:\n            if isinstance(source, self.klass):\n                self.path_map[source.this.name.value] = source\n                self.class_cache[source.this.name.value] = source\n                continue\n            source = str(source)\n            if source.lower().endswith(('.zip', '.jar')):\n                zf = ZipFile(source, 'r')\n                self.path_map.update(zip(zf.namelist(), repeat(zf)))\n            elif os.path.isdir(source):\n                walker = _walk(\n                    source,\n                    follow_links=follow_symlinks,\n                    maximum_depth=maximum_depth\n                )\n                for root, dirs, files in walker:\n                    for file_ in files:\n                        path_full = os.path.join(root, file_)\n                        path_suffix = os.path.relpath(path_full, source)\n                        self.path_map[path_suffix] = path_full",
    "docstring": "Add one or more ClassFile sources to the class loader.\n\n        If a given source is a directory path, it is traversed up to the\n        maximum set depth and all files under it are added to the class loader\n        lookup table.\n\n        If a given source is a .jar or .zip file it will be opened and the\n        file index added to the class loader lookup table.\n\n        If a given source is a ClassFile or a subclass, it's immediately\n        added to the class loader lookup table and the class cache.\n\n        :param sources: One or more ClassFile sources to be added.\n        :param follow_symlinks: True if symlinks should be followed when\n                                traversing filesystem directories.\n                                [default: False]\n        :param maximum_depth: The maximum sub-directory depth when traversing\n                              filesystem directories. If set to `None` no limit\n                              will be enforced. [default: 20]"
  },
  {
    "code": "def match_taking_agent_id(self, agent_id, match):\n        self._add_match('takingAgentId', str(agent_id), bool(match))",
    "docstring": "Sets the agent ``Id`` for this query.\n\n        arg:    agent_id (osid.id.Id): an agent ``Id``\n        arg:    match (boolean): ``true`` for a positive match,\n                ``false`` for a negative match\n        raise:  NullArgument - ``agent_id`` is ``null``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_custom_value(self, key):\n        self._handled.add(key)\n        values = self._lookup[key]\n        if len(values) > 1:\n            raise RuntimeError(\n                \"More than one value for this customParameter: {}\".format(key)\n            )\n        if values:\n            return values[0]\n        return None",
    "docstring": "Return the first and only custom parameter matching the given name."
  },
  {
    "code": "def points_possible(self, include_hidden=False):\n        return sum([test_case.points for testable in self.testables\n                    for test_case in testable.test_cases\n                    if include_hidden or not testable.is_hidden])",
    "docstring": "Return the total points possible for this project."
  },
  {
    "code": "def verify_scores(scores):\n    scores = np.array(scores, copy=False)\n    if np.any(~np.isfinite(scores)):\n        raise ValueError(\"scores contains invalid values. \" +\n                         \"Please check that all values are finite.\")\n    if scores.ndim == 1:\n        scores = scores[:,np.newaxis]\n    return scores",
    "docstring": "Ensures that scores is stored as a numpy array and checks that all\n    values are finite."
  },
  {
    "code": "def start_output (self):\n        super(HtmlLogger, self).start_output()\n        header = {\n            \"encoding\": self.get_charset_encoding(),\n            \"title\": configuration.App,\n            \"body\": self.colorbackground,\n            \"link\": self.colorlink,\n            \"vlink\": self.colorlink,\n            \"alink\": self.colorlink,\n            \"url\": self.colorurl,\n            \"error\": self.colorerror,\n            \"valid\": self.colorok,\n            \"warning\": self.colorwarning,\n        }\n        self.write(HTML_HEADER % header)\n        self.comment(\"Generated by %s\" % configuration.App)\n        if self.has_part('intro'):\n            self.write(u\"<h2>\"+configuration.App+\n                       \"</h2><br/><blockquote>\"+\n                       configuration.Freeware+\"<br/><br/>\"+\n                       (_(\"Start checking at %s\") %\n                       strformat.strtime(self.starttime))+\n                       os.linesep+\"<br/>\")\n            self.check_date()\n        self.flush()",
    "docstring": "Write start of checking info."
  },
  {
    "code": "def get_ebuio_headers(request):\n    retour = {}\n    for (key, value) in request.headers:\n        if key.startswith('X-Plugit-'):\n            key = key[9:]\n            retour[key] = value\n    return retour",
    "docstring": "Return a dict with ebuio headers"
  },
  {
    "code": "def getpaths(self,libname):\n        if os.path.isabs(libname):\n            yield libname\n        else:\n            for path in self.getplatformpaths(libname):\n                yield path\n            path = ctypes.util.find_library(libname)\n            if path: yield path",
    "docstring": "Return a list of paths where the library might be found."
  },
  {
    "code": "def splitN(line, n):\n    x0, y0, x1, y1 = line\n    out = empty((n, 4), dtype=type(line[0]))\n    px, py = x0, y0\n    dx = (x1 - x0) / n\n    dy = (y1 - y0) / n\n    for i in range(n):\n        o = out[i]\n        o[0] = px\n        o[1] = py\n        px += dx\n        py += dy\n        o[2] = px\n        o[3] = py\n    return out",
    "docstring": "split a line n times\n    returns n sublines"
  },
  {
    "code": "def _validate(self):\n        for key in self:\n            if key not in DEFAULTS:\n                raise exceptions.ConfigurationException(\n                    'Unknown configuration key \"{}\"! Valid configuration keys are'\n                    \" {}\".format(key, list(DEFAULTS.keys()))\n                )\n        validate_queues(self[\"queues\"])\n        validate_bindings(self[\"bindings\"])\n        validate_client_properties(self[\"client_properties\"])",
    "docstring": "Perform checks on the configuration to assert its validity\n\n        Raises:\n            ConfigurationException: If the configuration is invalid."
  },
  {
    "code": "def add_compound(self, compound):\n        logger.debug(\"Adding compound {0} to variant {1}\".format(\n            compound, self['variant_id']))\n        self['compounds'].append(compound)",
    "docstring": "Add the information of a compound variant\n\n            This adds a compound dict to variant['compounds']\n\n            Args:\n                compound (dict): A compound dictionary"
  },
  {
    "code": "def list_subscriptions(self, client_id, client_secret):\n        result_fetcher = functools.partial(self.protocol.get, '/push_subscriptions', client_id=client_id,\n                                           client_secret=client_secret, use_webhook_server=True)\n        return BatchedResultsIterator(entity=model.Subscription,\n                                      bind_client=self,\n                                      result_fetcher=result_fetcher)",
    "docstring": "List current webhook event subscriptions in place for the current application.\n\n        http://strava.github.io/api/partner/v3/events/#list-push-subscriptions\n\n        :param client_id: application's ID, obtained during registration\n        :type client_id: int\n\n        :param client_secret: application's secret, obtained during registration\n        :type client_secret: str\n\n        :return: An iterator of :class:`stravalib.model.Subscription` objects.\n        :rtype: :class:`BatchedResultsIterator`"
  },
  {
    "code": "def warehouse_query(line, cell):\n    \"my cell magic\"\n    from IPython import get_ipython\n    parts = line.split()\n    w_var_name = parts.pop(0)\n    w = get_ipython().ev(w_var_name)\n    w.query(cell).close()",
    "docstring": "my cell magic"
  },
  {
    "code": "def umi_histogram(fastq):\n    annotations = detect_fastq_annotations(fastq)\n    re_string = construct_transformed_regex(annotations)\n    parser_re = re.compile(re_string)\n    counter = collections.Counter()\n    for read in read_fastq(fastq):\n        match = parser_re.search(read).groupdict()\n        counter[match['MB']] += 1\n    for bc, count in counter.most_common():\n        sys.stdout.write('{}\\t{}\\n'.format(bc, count))",
    "docstring": "Counts the number of reads for each UMI\n\n    Expects formatted fastq files."
  },
  {
    "code": "def readSB(self, bits):\n        shift = 32 - bits\n        return int32(self.readbits(bits) << shift) >> shift",
    "docstring": "Read a signed int using the specified number of bits"
  },
  {
    "code": "def unmarshaller(self, typed=True):\n        if typed:\n            return UmxEncoded(self.schema())\n        else:\n            return RPC.unmarshaller(self, typed)",
    "docstring": "Get the appropriate XML decoder.\n        @return: Either the (basic|typed) unmarshaller.\n        @rtype: L{UmxTyped}"
  },
  {
    "code": "def write_frame(self):\n        if not hasattr(self, 'mwriter'):\n            raise AssertionError('This plotter has not opened a movie or GIF file.')\n        self.mwriter.append_data(self.image)",
    "docstring": "Writes a single frame to the movie file"
  },
  {
    "code": "def get_assessment_metadata(self):\n        metadata = dict(self._mdata['assessment'])\n        metadata.update({'existing_id_values': self._my_map['assessmentId']})\n        return Metadata(**metadata)",
    "docstring": "Gets the metadata for an assessment.\n\n        return: (osid.Metadata) - metadata for the assessment\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def upload_submit(self, upload_request):\r\n        path = '/api/1.0/upload/save'\r\n        return self._api_post(definition.DatasetUploadResponse, path, upload_request)",
    "docstring": "The method is submitting dataset upload"
  },
  {
    "code": "def write(self, data, show_progress=False, invalid_data_behavior='warn'):\n        ctx = maybe_show_progress(\n            data,\n            show_progress=show_progress,\n            item_show_func=lambda e: e if e is None else str(e[0]),\n            label=\"Merging minute equity files:\",\n        )\n        write_sid = self.write_sid\n        with ctx as it:\n            for e in it:\n                write_sid(*e, invalid_data_behavior=invalid_data_behavior)",
    "docstring": "Write a stream of minute data.\n\n        Parameters\n        ----------\n        data : iterable[(int, pd.DataFrame)]\n            The data to write. Each element should be a tuple of sid, data\n            where data has the following format:\n              columns : ('open', 'high', 'low', 'close', 'volume')\n                  open : float64\n                  high : float64\n                  low  : float64\n                  close : float64\n                  volume : float64|int64\n              index : DatetimeIndex of market minutes.\n            A given sid may appear more than once in ``data``; however,\n            the dates must be strictly increasing.\n        show_progress : bool, optional\n            Whether or not to show a progress bar while writing."
  },
  {
    "code": "def formfield(self, **kwargs):\n        defaults = {'form_class': forms.TimeZoneField}\n        defaults.update(**kwargs)\n        return super(TimeZoneField, self).formfield(**defaults)",
    "docstring": "Returns a custom form field for the TimeZoneField."
  },
  {
    "code": "def get_resource_bin_session(self, proxy):\n        if not self.supports_resource_bin():\n            raise errors.Unimplemented()\n        return sessions.ResourceBinSession(proxy=proxy, runtime=self._runtime)",
    "docstring": "Gets the session for retrieving resource to bin mappings.\n\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.resource.ResourceBinSession) - a\n                ``ResourceBinSession``\n        raise:  NullArgument - ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_resource_bin()`` is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_resource_bin()`` is ``true``.*"
  },
  {
    "code": "def server_poweroff(host=None,\n                    admin_username=None,\n                    admin_password=None,\n                    module=None):\n    return __execute_cmd('serveraction powerdown',\n                         host=host, admin_username=admin_username,\n                         admin_password=admin_password, module=module)",
    "docstring": "Powers down the managed server.\n\n    host\n        The chassis host.\n\n    admin_username\n        The username used to access the chassis.\n\n    admin_password\n        The password used to access the chassis.\n\n    module\n        The element to power off on the chassis such as a blade.\n        If not provided, the chassis will be powered off.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt dell dracr.server_poweroff\n        salt dell dracr.server_poweroff module=server-1"
  },
  {
    "code": "def pause(self, scaling_group):\n        uri = \"/%s/%s/pause\" % (self.uri_base, utils.get_id(scaling_group))\n        resp, resp_body = self.api.method_post(uri)\n        return None",
    "docstring": "Pauses all execution of the policies for the specified scaling group."
  },
  {
    "code": "def _install_hiero(use_threaded_wrapper):\n    import hiero\n    import nuke\n    if \"--hiero\" not in nuke.rawArgs:\n        raise ImportError\n    def threaded_wrapper(func, *args, **kwargs):\n        return hiero.core.executeInMainThreadWithResult(\n            func, args, kwargs)\n    _common_setup(\"Hiero\", threaded_wrapper, use_threaded_wrapper)",
    "docstring": "Helper function to The Foundry Hiero support"
  },
  {
    "code": "def calc_point_distance(self, chi_coords):\n        chi1_bin, chi2_bin = self.find_point_bin(chi_coords)\n        min_dist = 1000000000\n        indexes = None\n        for chi1_bin_offset, chi2_bin_offset in self.bin_loop_order:\n            curr_chi1_bin = chi1_bin + chi1_bin_offset\n            curr_chi2_bin = chi2_bin + chi2_bin_offset\n            for idx, bank_chis in \\\n                            enumerate(self.bank[curr_chi1_bin][curr_chi2_bin]):\n                dist = coord_utils.calc_point_dist(chi_coords, bank_chis)\n                if dist < min_dist:\n                    min_dist = dist\n                    indexes = (curr_chi1_bin, curr_chi2_bin, idx)\n        return min_dist, indexes",
    "docstring": "Calculate distance between point and the bank. Return the closest\n        distance.\n\n        Parameters\n        -----------\n        chi_coords : numpy.array\n            The position of the point in the chi coordinates.\n\n        Returns\n        --------\n        min_dist : float\n            The smallest **SQUARED** metric distance between the test point and\n            the bank.\n        indexes : The chi1_bin, chi2_bin and position within that bin at which\n            the closest matching point lies."
  },
  {
    "code": "def find_field_by_name(browser, field_type, name):\n    return ElementSelector(\n        browser,\n        field_xpath(field_type, 'name') %\n        string_literal(name),\n        filter_displayed=True,\n    )",
    "docstring": "Locate the control input with the given ``name``.\n\n    :param browser: ``world.browser``\n    :param string field_type: a field type (i.e. `button`)\n    :param string name: ``name`` attribute\n\n    Returns: an :class:`ElementSelector`"
  },
  {
    "code": "def get_changelog_file_for_database(database=DEFAULT_DB_ALIAS):\n    from django.conf import settings\n    try:\n        return settings.LIQUIMIGRATE_CHANGELOG_FILES[database]\n    except AttributeError:\n        if database == DEFAULT_DB_ALIAS:\n            try:\n                return settings.LIQUIMIGRATE_CHANGELOG_FILE\n            except AttributeError:\n                raise ImproperlyConfigured(\n                        'Please set LIQUIMIGRATE_CHANGELOG_FILE or '\n                        'LIQUIMIGRATE_CHANGELOG_FILES in your '\n                        'project settings')\n        else:\n            raise ImproperlyConfigured(\n                'LIQUIMIGRATE_CHANGELOG_FILES dictionary setting '\n                'is required for multiple databases support')\n    except KeyError:\n        raise ImproperlyConfigured(\n            \"Liquibase changelog file is not set for database: %s\" % database)",
    "docstring": "get changelog filename for given `database` DB alias"
  },
  {
    "code": "def _group_sql(self, quote_char=None, groupby_alias=True, **kwargs):\n        clauses = []\n        selected_aliases = {s.alias for s in self._selects}\n        for field in self._groupbys:\n            if groupby_alias and field.alias and field.alias in selected_aliases:\n                clauses.append(\"{quote}{alias}{quote}\".format(\n                      alias=field.alias,\n                      quote=quote_char or '',\n                ))\n            else:\n                clauses.append(field.get_sql(quote_char=quote_char, **kwargs))\n        sql = ' GROUP BY {groupby}'.format(groupby=','.join(clauses))\n        if self._with_totals:\n            return sql + ' WITH TOTALS'\n        return sql",
    "docstring": "Produces the GROUP BY part of the query.  This is a list of fields. The clauses are stored in the query under\n        self._groupbys as a list fields.\n\n        If an groupby field is used in the select clause,\n        determined by a matching alias, and the groupby_alias is set True\n        then the GROUP BY clause will use the alias,\n        otherwise the entire field will be rendered as SQL."
  },
  {
    "code": "def build_target_areas(entry):\n    target_areas = []\n    areas = str(entry['cap:areaDesc']).split(';')\n    for area in areas:\n        target_areas.append(area.strip())\n    return target_areas",
    "docstring": "Cleanup the raw target areas description string"
  },
  {
    "code": "def minutes(self, start_date=None, end_date=None, grouping=None):\n        data = self.__format(start_date, end_date)\n        url = self.base_url + '/minutes'\n        return self.get(url, data=data)",
    "docstring": "Gets a detailed Report of encoded minutes and billable minutes for a\n        date range.\n\n        **Warning**: ``start_date`` and ``end_date`` must be ``datetime.date`` objects.\n\n        Example::\n            import datetime\n            start = datetime.date(2012, 12, 31)\n            end = datetime.today()\n            data = z.report.minutes(start, end)\n\n\n        https://app.zencoder.com/docs/api/reports/minutes"
  },
  {
    "code": "def _get_pattern(self, pys_style):\n        if \"bgcolor\" not in pys_style:\n            return\n        pattern = xlwt.Pattern()\n        pattern.pattern = xlwt.Pattern.SOLID_PATTERN\n        bgcolor = wx.Colour()\n        bgcolor.SetRGB(pys_style[\"bgcolor\"])\n        pattern.pattern_fore_colour = self.color2idx(*bgcolor.Get())\n        return pattern",
    "docstring": "Returns xlwt.pattern for pyspread style"
  },
  {
    "code": "def _check_if_must_download(request_list, redownload):\n    for request in request_list:\n        request.will_download = (request.save_response or request.return_data) \\\n                                and (not request.is_downloaded() or redownload)",
    "docstring": "Updates request.will_download attribute of each request in request_list.\n\n    **Note:** the function mutates the elements of the list!\n\n    :param request_list: a list of ``DownloadRequest`` instances\n    :type: list[DownloadRequest]\n    :param redownload: tells whether to download the data again or not\n    :type: bool"
  },
  {
    "code": "def replace_media(self,src_file,dst_file):\n        with open(dst_file, 'rb') as fh:\n            crc = self.get_file_crc(src_file)\n            self.crc_to_new_media[crc] = fh.read()",
    "docstring": "Replace one media by another one into a docx\n\n        This has been done mainly because it is not possible to add images in\n        docx header/footer.\n        With this function, put a dummy picture in your header/footer,\n        then specify it with its replacement in this function\n\n        Syntax: tpl.replace_media('dummy_media_to_replace.png','media_to_paste.jpg')\n\n        Note: for images, the aspect ratio will be the same as the replaced image\n        Note2 : it is important to have the source media file as it is required\n                to calculate its CRC to find them in the docx"
  },
  {
    "code": "def try_storage(self, identifier, req, resp, resource, uri_kwargs):\n        if identifier is None:\n            user = None\n        elif self.user_storage is not None:\n            user = self.user_storage.get_user(\n                self, identifier, req, resp, resource, uri_kwargs\n            )\n        elif self.user_storage is None and not self.only_with_storage:\n            user = {\n                'identified_with': self,\n                'identifier': identifier\n            }\n        else:\n            user = None\n        return user",
    "docstring": "Try to find user in configured user storage object.\n\n        Args:\n            identifier: User identifier.\n\n        Returns:\n            user object."
  },
  {
    "code": "def _handle_tag_removeobject(self):\n        obj = _make_object(\"RemoveObject\")\n        obj.CharacterId = unpack_ui16(self._src)\n        obj.Depth = unpack_ui16(self._src)\n        return obj",
    "docstring": "Handle the RemoveObject tag."
  },
  {
    "code": "def change_exteditor(self):\r\n        path, valid = QInputDialog.getText(self, _('External editor'),\r\n                          _('External editor executable path:'),\r\n                          QLineEdit.Normal,\r\n                          self.get_option('external_editor/path'))\r\n        if valid:\r\n            self.set_option('external_editor/path', to_text_string(path))",
    "docstring": "Change external editor path"
  },
  {
    "code": "def _save_token_cache(self, new_cache):\n        'Write out to the filesystem a cache of the OAuth2 information.'\n        logging.debug('Looking to write to local authentication cache...')\n        if not self._check_token_cache_type(new_cache):\n            logging.error('Attempt to save a bad value: %s', new_cache)\n            return\n        try:\n            logging.debug('About to write to fs cache file: %s',\n                          self.token_cache_file)\n            with open(self.token_cache_file, 'wb') as f:\n                cPickle.dump(new_cache, f, protocol=cPickle.HIGHEST_PROTOCOL)\n                logging.debug('Finished dumping cache_value to fs cache file.')\n        except:\n            logging.exception(\n                'Could not successfully cache OAuth2 secrets on the file '\n                'system.')",
    "docstring": "Write out to the filesystem a cache of the OAuth2 information."
  },
  {
    "code": "def _post_clean(self):\n        super()._post_clean()\n        password = self.cleaned_data.get('password1')\n        if password:\n            try:\n                password_validation.validate_password(password, self.instance)\n            except ValidationError as error:\n                self.add_error('password1', error)",
    "docstring": "Run password validaton after clean methods\n\n        When clean methods are run, the user instance does not yet\n        exist.  To properly compare model values agains the password (in\n        the UserAttributeSimilarityValidator), we wait until we have an\n        instance to compare against.\n\n        https://code.djangoproject.com/ticket/28127\n        https://github.com/django/django/pull/8408\n\n        Has no effect in Django prior to 1.9\n        May become unnecessary in Django 2.0 (if this superclass changes)"
  },
  {
    "code": "def stop_threadsafe(self):\n        if self.stopped:\n            return\n        try:\n            self._loop.run_coroutine(self.stop())\n        except asyncio.TimeoutError:\n            raise TimeoutExpiredError(\"Timeout stopping task {} with {} subtasks\".format(self.name, len(self.subtasks)))",
    "docstring": "Stop this task from another thread and wait for it to finish.\n\n        This method must not be called from within the BackgroundEventLoop but\n        will inject self.stop() into the event loop and block until it\n        returns.\n\n        Raises:\n            TimeoutExpiredError: If the task does not stop in the given\n                timeout specified in __init__()"
  },
  {
    "code": "def set(self, key, val):\n        return self.evolver().set(key, val).persistent()",
    "docstring": "Return a new PMap with key and val inserted.\n\n        >>> m1 = m(a=1, b=2)\n        >>> m2 = m1.set('a', 3)\n        >>> m3 = m1.set('c' ,4)\n        >>> m1\n        pmap({'a': 1, 'b': 2})\n        >>> m2\n        pmap({'a': 3, 'b': 2})\n        >>> m3\n        pmap({'a': 1, 'c': 4, 'b': 2})"
  },
  {
    "code": "def make_metatiles(size, tiles, date_time=None):\n    groups = defaultdict(list)\n    for tile in tiles:\n        key = tile['layer']\n        groups[key].append(tile)\n    metatiles = []\n    for group in groups.itervalues():\n        parent = _parent_tile(t['coord'] for t in group)\n        metatiles.extend(make_multi_metatile(parent, group, date_time))\n    return metatiles",
    "docstring": "Group by layers, and make metatiles out of all the tiles which share those\n    properties relative to the \"top level\" tile which is parent of them all.\n    Provide a 6-tuple date_time to set the timestamp on each tile within the\n    metatile, or leave it as None to use the current time."
  },
  {
    "code": "def by_interval_lookup(self, style_key, style_value):\n        style_attr = style_key if self.style_types[style_key] is bool else None\n        intervals = style_value[\"interval\"]\n        def proc(value, result):\n            try:\n                value = float(value)\n            except TypeError:\n                return result\n            for start, end, lookup_value in intervals:\n                if start is None:\n                    start = float(\"-inf\")\n                if end is None:\n                    end = float(\"inf\")\n                if start <= value < end:\n                    if not lookup_value:\n                        return result\n                    return self.render(style_attr or lookup_value, result)\n            return result\n        return proc",
    "docstring": "Return a processor for an \"interval\" style value.\n\n        Parameters\n        ----------\n        style_key : str\n            A style key.\n        style_value : dict\n            A dictionary with an \"interval\" key whose value consists of a\n            sequence of tuples where each tuple should have the form `(start,\n            end, x)`, where start is the start of the interval (inclusive), end\n            is the end of the interval, and x is either a style attribute (str)\n            and a boolean flag indicating to use the style attribute named by\n            `style_key`.\n\n        Returns\n        -------\n        A function."
  },
  {
    "code": "def get_scores(self, y_i, y_j):\n\t\tz_scores = self.get_zeta_i_j_given_separate_counts(y_i, y_j)\n\t\treturn z_scores",
    "docstring": "Same function as get_zeta_i_j_given_separate_counts\n\n\t\tParameters\n\t\t----------\n\t\ty_i, np.array(int)\n\t\t\tArrays of word counts of words occurring in positive class\n\t\ty_j, np.array(int)\n\n\t\tReturns\n\t\t-------\n\t\tnp.array of z-scores"
  },
  {
    "code": "def strip_py(arg):\n    for ext in PY_EXTENSIONS:\n        if arg.endswith(ext):\n            return arg[:-len(ext)]\n    return None",
    "docstring": "Strip a trailing .py or .pyi suffix.\n    Return None if no such suffix is found."
  },
  {
    "code": "def _get_representative(self, obj):\n        if obj not in self._parents:\n            self._parents[obj] = obj\n            self._weights[obj] = 1\n            self._prev_next[obj] = [obj, obj]\n            self._min_values[obj] = obj\n            return obj\n        path = [obj]\n        root = self._parents[obj]\n        while root != path[-1]:\n            path.append(root)\n            root = self._parents[root]\n        for ancestor in path:\n            self._parents[ancestor] = root\n        return root",
    "docstring": "Finds and returns the root of the set containing `obj`."
  },
  {
    "code": "def error_asymptotes(pca,**kwargs):\n    ax = kwargs.pop(\"ax\",current_axes())\n    lon,lat = pca.plane_errors('upper', n=1000)\n    ax.plot(lon,lat,'-')\n    lon,lat = pca.plane_errors('lower', n=1000)\n    ax.plot(lon,lat,'-')\n    ax.plane(*pca.strike_dip())",
    "docstring": "Plots asymptotic error bounds for\n    hyperbola on a stereonet."
  },
  {
    "code": "def _collapse_state(args: Dict[str, Any]):\n    index = args['index']\n    result = args['result']\n    prob_one = args['prob_one']\n    state = _state_shard(args)\n    normalization = np.sqrt(prob_one if result else 1 - prob_one)\n    state *= (_one_projector(args, index) * result +\n              (1 - _one_projector(args, index)) * (1 - result))\n    state /= normalization",
    "docstring": "Projects state shards onto the appropriate post measurement state.\n\n    This function makes no assumptions about the interpretation of quantum\n    theory.\n\n    Args:\n        args: The args from shard_num_args."
  },
  {
    "code": "def _handle_author(author):\n    lname = author.split(' ')\n    try:\n        auinit = lname[0][0]\n        final = lname[-1].upper()\n        if final in ['JR.', 'III']:\n            aulast = lname[-2].upper() + \" \" + final.strip(\".\")\n        else:\n            aulast = final\n    except IndexError:\n        raise ValueError(\"malformed author name\")\n    return aulast, auinit",
    "docstring": "Yields aulast and auinit from an author's full name.\n\n    Parameters\n    ----------\n    author : str or unicode\n        Author fullname, e.g. \"Richard L. Nixon\".\n\n    Returns\n    -------\n    aulast : str\n        Author surname.\n    auinit : str\n        Author first-initial."
  },
  {
    "code": "def count_sci_extensions(filename):\n    num_sci = 0\n    extname = 'SCI'\n    hdu_list = fileutil.openImage(filename, memmap=False)\n    for extn in hdu_list:\n        if 'extname' in extn.header and extn.header['extname'] == extname:\n            num_sci += 1\n    if num_sci == 0:\n        extname = 'PRIMARY'\n        num_sci = 1\n    hdu_list.close()\n    return num_sci,extname",
    "docstring": "Return the number of SCI extensions and the EXTNAME from a input MEF file."
  },
  {
    "code": "def check_power(self):\n    packet = bytearray(16)\n    packet[0] = 1\n    response = self.send_packet(0x6a, packet)\n    err = response[0x22] | (response[0x23] << 8)\n    if err == 0:\n      payload = self.decrypt(bytes(response[0x38:]))\n      if type(payload[0x4]) == int:\n        if payload[0x4] == 1 or payload[0x4] == 3 or payload[0x4] == 0xFD:\n          state = True\n        else:\n          state = False\n      else:\n        if ord(payload[0x4]) == 1 or ord(payload[0x4]) == 3 or ord(payload[0x4]) == 0xFD:\n          state = True\n        else:\n          state = False\n      return state",
    "docstring": "Returns the power state of the smart plug."
  },
  {
    "code": "def OnContextMenu(self, event):\n        self.grid.PopupMenu(self.grid.contextmenu)\n        event.Skip()",
    "docstring": "Context menu event handler"
  },
  {
    "code": "def get_default_keystore(prefix='AG_'):\n  path = os.environ.get('%s_KEYSTORE_PATH' % prefix, config.keystore.path)\n  storepass = os.environ.get('%s_KEYSTORE_STOREPASS' % prefix, config.keystore.storepass)\n  keypass = os.environ.get('%s_KEYSTORE_KEYPASS' % prefix, config.keystore.keypass)\n  alias = os.environ.get('%s_KEYSTORE_ALIAS' % prefix, config.keystore.alias)\n  return (path, storepass, keypass, alias)",
    "docstring": "Gets the default keystore information based on environment variables and a prefix.\n\n  $PREFIX_KEYSTORE_PATH - keystore file path, default is opt/digger/debug.keystore\n  $PREFIX_KEYSTORE_STOREPASS - keystore storepass, default is android\n  $PREFIX_KEYSTORE_KEYPASS - keystore keypass, default is android\n  $PREFIX_KEYSTORE_ALIAS - keystore alias, default is androiddebug\n  \n  :param prefix(str) - A prefix to be used for environment variables, default is AG_.\n\n  Returns:\n    A tuple containing the keystore information: (path, storepass, keypass, alias)"
  },
  {
    "code": "def from_text(text):\n    value = _by_text.get(text.upper())\n    if value is None:\n        match = _unknown_class_pattern.match(text)\n        if match == None:\n            raise UnknownRdataclass\n        value = int(match.group(1))\n        if value < 0 or value > 65535:\n            raise ValueError(\"class must be between >= 0 and <= 65535\")\n    return value",
    "docstring": "Convert text into a DNS rdata class value.\n    @param text: the text\n    @type text: string\n    @rtype: int\n    @raises dns.rdataclass.UnknownRdataClass: the class is unknown\n    @raises ValueError: the rdata class value is not >= 0 and <= 65535"
  },
  {
    "code": "def get_precision(self):\n        config_str = self.raw_sensor_strings[1].split()[4]\n        bit_base = int(config_str, 16) >> 5\n        return bit_base + 9",
    "docstring": "Get the current precision from the sensor.\n\n            :returns: sensor resolution from 9-12 bits\n            :rtype: int"
  },
  {
    "code": "def find_slot(self, wanted, slots=None):\n        for slot in self.find_slots(wanted, slots):\n            return slot\n        return None",
    "docstring": "Searches the given slots or, if not given,\n        active hotbar slot, hotbar, inventory, open window in this order.\n\n        Args:\n            wanted: function(Slot) or Slot or itemID or (itemID, metadata)\n\n        Returns:\n            Optional[Slot]: The first slot containing the item\n                            or None if not found."
  },
  {
    "code": "def read_file(path):\n    gen = textfile.read_separated_lines_generator(path, max_columns=6,\n                                                  ignore_lines_starting_with=[';;'])\n    utterances = collections.defaultdict(list)\n    for record in gen:\n        values = record[1:len(record)]\n        for i in range(len(values)):\n            if i == 1 or i == 2 or i == 4:\n                values[i] = float(values[i])\n        utterances[record[0]].append(values)\n    return utterances",
    "docstring": "Reads a ctm file.\n\n    Args:\n        path (str): Path to the file\n\n    Returns:\n        (dict): Dictionary with entries.\n\n    Example::\n\n        >>> read_file('/path/to/file.txt')\n        {\n            'wave-ab': [\n                ['1', 0.00, 0.07, 'HI', 1],\n                ['1', 0.09, 0.08, 'AH', 1]\n            ],\n            'wave-xy': [\n                ['1', 0.00, 0.07, 'HI', 1],\n                ['1', 0.09, 0.08, 'AH', 1]\n            ]\n        }"
  },
  {
    "code": "def iter_files(self):\n        if callable(self.file_iter):\n            return self.file_iter()\n        return iter(self.file_iter)",
    "docstring": "Iterate over files."
  },
  {
    "code": "def crossover(cross):\n    @functools.wraps(cross)\n    def inspyred_crossover(random, candidates, args):\n        if len(candidates) % 2 == 1:\n            candidates = candidates[:-1]\n        moms = candidates[::2]\n        dads = candidates[1::2]\n        children = []\n        for i, (mom, dad) in enumerate(zip(moms, dads)):\n            cross.index = i\n            offspring = cross(random, mom, dad, args)\n            for o in offspring:\n                children.append(o)\n        return children\n    inspyred_crossover.single_crossover = cross\n    return inspyred_crossover",
    "docstring": "Return an inspyred crossover function based on the given function.\n\n    This function generator takes a function that operates on only\n    two parent candidates to produce an iterable sequence of offspring\n    (typically two). The generator handles the pairing of selected\n    parents and collecting of all offspring.\n\n    The generated function chooses every odd candidate as a 'mom' and\n    every even as a 'dad' (discounting the last candidate if there is\n    an odd number). For each mom-dad pair, offspring are produced via\n    the `cross` function.\n\n    The given function ``cross`` must have the following signature::\n\n        offspring = cross(random, mom, dad, args)\n\n    This function is most commonly used as a function decorator with\n    the following usage::\n\n        @crossover\n        def cross(random, mom, dad, args):\n            # Implementation of paired crossing\n            pass\n\n    The generated function also contains an attribute named\n    ``single_crossover`` which holds the original crossover function.\n    In this way, the original single-set-of-parents function can be\n    retrieved if necessary."
  },
  {
    "code": "def struct(self):\r\n        data = {}\r\n        for var, fmap in self._def.items():\r\n            if hasattr(self, var):\r\n                data.update(fmap.get_outputs(getattr(self, var)))\r\n        return data",
    "docstring": "XML-RPC-friendly representation of the current object state"
  },
  {
    "code": "def jsonobjlen(self, name, path=Path.rootPath()):\n        return self.execute_command('JSON.OBJLEN', name, str_path(path))",
    "docstring": "Returns the length of the dictionary JSON value under ``path`` at key\n        ``name``"
  },
  {
    "code": "def send_mail(subject, body, email_from, emails_to):\n    msg = MIMEText(body)\n    msg['Subject'] = subject\n    msg['From'] = email_from\n    msg['To'] = \", \".join(emails_to)\n    s = smtplib.SMTP('smtp.gmail.com', 587)\n    s.ehlo()\n    s.starttls()\n    s.ehlo()\n    s.login(SMTP_USERNAME, SMTP_PASSWORD)\n    s.sendmail(email_from, emails_to, msg.as_string())\n    s.quit()",
    "docstring": "Funxtion for sending email though gmail"
  },
  {
    "code": "def init_database(connection=None, dbname=None):\n    connection = connection or connect()\n    dbname = dbname or bigchaindb.config['database']['name']\n    create_database(connection, dbname)\n    create_tables(connection, dbname)",
    "docstring": "Initialize the configured backend for use with BigchainDB.\n\n    Creates a database with :attr:`dbname` with any required tables\n    and supporting indexes.\n\n    Args:\n        connection (:class:`~bigchaindb.backend.connection.Connection`): an\n            existing connection to use to initialize the database.\n            Creates one if not given.\n        dbname (str): the name of the database to create.\n            Defaults to the database name given in the BigchainDB\n            configuration."
  },
  {
    "code": "def make_noise_surface(dims=DEFAULT_DIMS, blur=10, seed=None):\n    if seed is not None:\n        np.random.seed(seed)\n    return gaussian_filter(np.random.normal(size=dims), blur)",
    "docstring": "Makes a surface by generating random noise and blurring it.\n\n    Args:\n        dims (pair): the dimensions of the surface to create\n        blur (float): the amount of Gaussian blur to apply\n        seed (int): a random seed to use (optional)\n    \n    Returns:\n        surface: A surface."
  },
  {
    "code": "def push_state(self, new_file=''):\n        'Saves the current error state to parse subpackages'\n        self.subpackages.append({'detected_type': self.detected_type,\n                                 'message_tree': self.message_tree,\n                                 'resources': self.pushable_resources,\n                                 'metadata': self.metadata})\n        self.message_tree = {}\n        self.pushable_resources = {}\n        self.metadata = {'requires_chrome': False,\n                         'listed': self.metadata.get('listed'),\n                         'validator_version': validator.__version__}\n        self.package_stack.append(new_file)",
    "docstring": "Saves the current error state to parse subpackages"
  },
  {
    "code": "async def async_set_operation_mode(\n            self, operation_mode: OperationMode, password: str = '') -> None:\n        await self._protocol.async_execute(\n            SetOpModeCommand(operation_mode),\n            password=password)",
    "docstring": "Set the operation mode on the base unit.\n\n        :param operation_mode: the operation mode to change to\n        :param password: if specified, will be used instead of the password\n                         property when issuing the command"
  },
  {
    "code": "def startResponse(self, status, headers, excInfo=None):\n        self.status = status\n        self.headers = headers\n        self.reactor.callInThread(\n            responseInColor, self.request, status, headers\n        )\n        return self.write",
    "docstring": "extends startResponse to call speakerBox in a thread"
  },
  {
    "code": "def __remove_activity(self, id):\n        query = \"select count(*) as count from facts where activity_id = ?\"\n        bound_facts = self.fetchone(query, (id,))['count']\n        if bound_facts > 0:\n            self.execute(\"UPDATE activities SET deleted = 1 WHERE id = ?\", (id,))\n        else:\n            self.execute(\"delete from activities where id = ?\", (id,))",
    "docstring": "check if we have any facts with this activity and behave accordingly\n            if there are facts - sets activity to deleted = True\n            else, just remove it"
  },
  {
    "code": "def orientnii(imfile):\n    strorient = ['L-R', 'S-I', 'A-P']\n    niiorient = []\n    niixyz = np.zeros(3,dtype=np.int8)\n    if os.path.isfile(imfile):\n        nim = nib.load(imfile)\n        pct = nim.get_data()\n        A = nim.get_sform()\n        for i in range(3):\n            niixyz[i] = np.argmax(abs(A[i,:-1]))\n            niiorient.append( strorient[ niixyz[i] ] )\n        print niiorient",
    "docstring": "Get the orientation from NIfTI sform.  Not fully functional yet."
  },
  {
    "code": "def password_get(username=None):\n    password = keyring.get_password('supernova', username)\n    if password is None:\n        split_username = tuple(username.split(':'))\n        msg = (\"Couldn't find a credential for {0}:{1}. You need to set one \"\n               \"with: supernova-keyring -s {0} {1}\").format(*split_username)\n        raise LookupError(msg)\n    else:\n        return password.encode('ascii')",
    "docstring": "Retrieves a password from the keychain based on the environment and\n    configuration parameter pair.\n\n    If this fails, None is returned."
  },
  {
    "code": "def body(self):\n        if not self._auto_decode:\n            return self._body\n        if 'body' in self._decode_cache:\n            return self._decode_cache['body']\n        body = try_utf8_decode(self._body)\n        self._decode_cache['body'] = body\n        return body",
    "docstring": "Return the Message Body.\n\n            If auto_decode is enabled, the body will automatically be\n            decoded using decode('utf-8') if possible.\n\n        :rtype: bytes|str|unicode"
  },
  {
    "code": "def slice_indexer(self, start=None, end=None, step=None, kind=None):\n        start_slice, end_slice = self.slice_locs(start, end, step=step,\n                                                 kind=kind)\n        if not is_scalar(start_slice):\n            raise AssertionError(\"Start slice bound is non-scalar\")\n        if not is_scalar(end_slice):\n            raise AssertionError(\"End slice bound is non-scalar\")\n        return slice(start_slice, end_slice, step)",
    "docstring": "For an ordered or unique index, compute the slice indexer for input\n        labels and step.\n\n        Parameters\n        ----------\n        start : label, default None\n            If None, defaults to the beginning\n        end : label, default None\n            If None, defaults to the end\n        step : int, default None\n        kind : string, default None\n\n        Returns\n        -------\n        indexer : slice\n\n        Raises\n        ------\n        KeyError : If key does not exist, or key is not unique and index is\n            not ordered.\n\n        Notes\n        -----\n        This function assumes that the data is sorted, so use at your own peril\n\n        Examples\n        ---------\n        This is a method on all index types. For example you can do:\n\n        >>> idx = pd.Index(list('abcd'))\n        >>> idx.slice_indexer(start='b', end='c')\n        slice(1, 3)\n\n        >>> idx = pd.MultiIndex.from_arrays([list('abcd'), list('efgh')])\n        >>> idx.slice_indexer(start='b', end=('c', 'g'))\n        slice(1, 3)"
  },
  {
    "code": "def add_parent(self, parent):\n        parent.add_child(self)\n        self.parent = parent\n        return parent",
    "docstring": "Adds self as child of parent, then adds parent."
  },
  {
    "code": "def get_output(self, index):\n        pdata = ctypes.POINTER(mx_uint)()\n        ndim = mx_uint()\n        _check_call(_LIB.MXPredGetOutputShape(\n            self.handle, index,\n            ctypes.byref(pdata),\n            ctypes.byref(ndim)))\n        shape = tuple(pdata[:ndim.value])\n        data = np.empty(shape, dtype=np.float32)\n        _check_call(_LIB.MXPredGetOutput(\n            self.handle, mx_uint(index),\n            data.ctypes.data_as(mx_float_p),\n            mx_uint(data.size)))\n        return data",
    "docstring": "Get the index-th output.\n\n        Parameters\n        ----------\n        index : int\n            The index of output.\n\n        Returns\n        -------\n        out : numpy array.\n            The output array."
  },
  {
    "code": "def _quadratic_sum_cost(self, state: _STATE) -> float:\n        cost = 0.0\n        total_len = float(len(self._c))\n        seqs, _ = state\n        for seq in seqs:\n            cost += (len(seq) / total_len) ** 2\n        return -cost",
    "docstring": "Cost function that sums squares of lengths of sequences.\n\n        Args:\n          state: Search state, not mutated.\n\n        Returns:\n          Cost which is minus the normalized quadratic sum of each linear\n          sequence section in the state. This promotes single, long linear\n          sequence solutions and converges to number -1. The solution with a\n          lowest cost consists of every node being a single sequence and is\n          always less than 0."
  },
  {
    "code": "def get_resource_url(resource):\n    path = model_path(resource)\n    parsed = list(urlparse.urlparse(path))\n    parsed[1] = \"\"\n    return urlparse.urlunparse(parsed)",
    "docstring": "Returns the URL for the given resource."
  },
  {
    "code": "def hpx_to_axes(h, npix):\n    x = h.ebins\n    z = np.arange(npix[-1] + 1)\n    return x, z",
    "docstring": "Generate a sequence of bin edge vectors corresponding to the\n    axes of a HPX object."
  },
  {
    "code": "def remove_droppable(self, droppable_id):\n        updated_droppables = []\n        for droppable in self.my_osid_object_form._my_map['droppables']:\n            if droppable['id'] != droppable_id:\n                updated_droppables.append(droppable)\n        self.my_osid_object_form._my_map['droppables'] = updated_droppables",
    "docstring": "remove a droppable, given the id"
  },
  {
    "code": "def tail(self, n=5):\n        return MultiIndex([v.tail(n) for v in self.values], self.names)",
    "docstring": "Return MultiIndex with the last n values in each column.\n\n        Parameters\n        ----------\n        n : int\n            Number of values.\n\n        Returns\n        -------\n        MultiIndex\n            MultiIndex containing the last n values in each column."
  },
  {
    "code": "def _printUUID(uuid, detail='word'):\n    if not isinstance(detail, int):\n        detail = detailNum[detail]\n    if detail > detailNum['word']:\n        return uuid\n    if uuid is None:\n        return None\n    return \"%s...%s\" % (uuid[:4], uuid[-4:])",
    "docstring": "Return friendly abbreviated string for uuid."
  },
  {
    "code": "def set_regressor_interface_params(spec, features, output_features):\n    if output_features is None:\n        output_features = [(\"predicted_class\", datatypes.Double())]\n    else:\n        output_features = _fm.process_or_validate_features(output_features, 1)\n    if len(output_features) != 1:\n        raise ValueError(\"Provided output features for a regressor must be \"\n                    \"one Double feature.\")\n    if output_features[0][1] != datatypes.Double():\n        raise ValueError(\"Output type of a regressor must be a Double.\")\n    prediction_name = output_features[0][0]\n    spec.description.predictedFeatureName = prediction_name\n    features = _fm.process_or_validate_features(features)\n    for cur_input_name, feature_type in features:\n        input_ = spec.description.input.add()\n        input_.name = cur_input_name\n        datatypes._set_datatype(input_.type, feature_type)\n    output_ = spec.description.output.add()\n    output_.name = prediction_name\n    datatypes._set_datatype(output_.type, 'Double')\n    return spec",
    "docstring": "Common utilities to set the regressor interface params."
  },
  {
    "code": "def find_parent_id_for_component(self, component_id):\n        response = self.get_record(component_id)\n        if \"parent\" in response:\n            return (ArchivesSpaceClient.RESOURCE_COMPONENT, response[\"parent\"][\"ref\"])\n        elif \"resource\" in response:\n            return (ArchivesSpaceClient.RESOURCE, response[\"resource\"][\"ref\"])\n        else:\n            return (ArchivesSpaceClient.RESOURCE, component_id)",
    "docstring": "Given the URL to a component, returns the parent component's URL.\n\n        :param string component_id: The URL of the component.\n        :return: A tuple containing:\n            * The type of the parent record; valid values are ArchivesSpaceClient.RESOURCE and ArchivesSpaceClient.RESOURCE_COMPONENT.\n            * The URL of the parent record.\n            If the provided URL fragment references a resource, this method will simply return the same URL.\n        :rtype tuple:"
  },
  {
    "code": "def _requires_refresh_token(self):\n        expires_on = datetime.datetime.strptime(\n            self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ')\n        refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30)\n        return expires_on < refresh",
    "docstring": "Check if a refresh of the token is needed"
  },
  {
    "code": "def queryWorkitems(self, query_str, projectarea_id=None,\n                       projectarea_name=None, returned_properties=None,\n                       archived=False):\n        rp = returned_properties\n        return self.query.queryWorkitems(query_str=query_str,\n                                         projectarea_id=projectarea_id,\n                                         projectarea_name=projectarea_name,\n                                         returned_properties=rp,\n                                         archived=archived)",
    "docstring": "Query workitems with the query string in a certain project area\n\n        At least either of `projectarea_id` and `projectarea_name` is given\n\n        :param query_str: a valid query string\n        :param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`\n            id\n        :param projectarea_name: the project area name\n        :param returned_properties: the returned properties that you want.\n            Refer to :class:`rtcclient.client.RTCClient` for more explanations\n        :param archived: (default is False) whether the workitems are archived\n        :return: a :class:`list` that contains the queried\n            :class:`rtcclient.workitem.Workitem` objects\n        :rtype: list"
  },
  {
    "code": "def delete(self, refobj):\n        i = self.get_typ_interface(self.get_typ(refobj))\n        i.delete(refobj)\n        self.delete_refobj(refobj)",
    "docstring": "Delete the given refobj and the contents of the entity\n\n        :param refobj: the refobj to delete\n        :type refobj: refobj\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def restricted_to_files(self,\n                            filenames: List[str]\n                            ) -> 'Spectra':\n        tally_passing = \\\n            {fn: entries for (fn, entries) in self.__tally_passing.items() \\\n             if fn in filenames}\n        tally_failing = \\\n            {fn: entries for (fn, entries) in self.__tally_failing.items() \\\n             if fn in filenames}\n        return Spectra(self.__num_passing,\n                       self.__num_failing,\n                       tally_passing,\n                       tally_failing)",
    "docstring": "Returns a variant of this spectra that only contains entries for\n        lines that appear in any of the files whose name appear in the\n        given list."
  },
  {
    "code": "def add_campaign(self, name, device_filter, **kwargs):\n        device_filter = filters.legacy_filter_formatter(\n            dict(filter=device_filter),\n            Device._get_attributes_map()\n        )\n        campaign = Campaign._create_request_map(kwargs)\n        if 'when' in campaign:\n            campaign['when'] = force_utc(campaign['when'])\n        body = UpdateCampaignPostRequest(\n            name=name,\n            device_filter=device_filter['filter'],\n            **campaign)\n        api = self._get_api(update_service.DefaultApi)\n        return Campaign(api.update_campaign_create(body))",
    "docstring": "Add new update campaign.\n\n        Add an update campaign with a name and device filtering. Example:\n\n        .. code-block:: python\n\n            device_api, update_api = DeviceDirectoryAPI(), UpdateAPI()\n\n            # Get a filter to use for update campaign\n            query_obj = device_api.get_query(query_id=\"MYID\")\n\n            # Create the campaign\n            new_campaign = update_api.add_campaign(\n                name=\"foo\",\n                device_filter=query_obj.filter\n            )\n\n        :param str name: Name of the update campaign (Required)\n        :param str device_filter: The device filter to use (Required)\n        :param str manifest_id: ID of the manifest with description of the update\n        :param str description: Description of the campaign\n        :param int scheduled_at: The timestamp at which update campaign is scheduled to start\n        :param str state: The state of the campaign. Values:\n            \"draft\", \"scheduled\", \"devicefetch\", \"devicecopy\", \"publishing\",\n            \"deploying\", \"deployed\", \"manifestremoved\", \"expired\"\n        :return: newly created campaign object\n        :rtype: Campaign"
  },
  {
    "code": "def try_set_count(self, count):\n        check_not_negative(count, \"count can't be negative\")\n        return self._encode_invoke(count_down_latch_try_set_count_codec, count=count)",
    "docstring": "Sets the count to the given value if the current count is zero. If count is not zero, this method does nothing\n        and returns ``false``.\n\n        :param count: (int), the number of times count_down() must be invoked before threads can pass through await().\n        :return: (bool), ``true`` if the new count was set, ``false`` if the current count is not zero."
  },
  {
    "code": "def get_product_url(self, force_http=False):\n        base_url = self.base_http_url if force_http else self.base_url\n        return '{}products/{}/{}'.format(base_url, self.date.replace('-', '/'), self.product_id)",
    "docstring": "Creates base url of product location on AWS.\n\n        :param force_http: True if HTTP base URL should be used and False otherwise\n        :type force_http: str\n        :return: url of product location\n        :rtype: str"
  },
  {
    "code": "def _update_hasher(hasher, data):\n    if isinstance(data, (tuple, list, zip)):\n        needs_iteration = True\n    elif (util_type.HAVE_NUMPY and isinstance(data, np.ndarray) and\n          data.dtype.kind == 'O'):\n        needs_iteration = True\n    else:\n        needs_iteration = False\n    if needs_iteration:\n        SEP = b'SEP'\n        iter_prefix = b'ITER'\n        iter_ = iter(data)\n        hasher.update(iter_prefix)\n        try:\n            for item in iter_:\n                prefix, hashable = _covert_to_hashable(data)\n                binary_data = SEP + prefix + hashable\n                hasher.update(binary_data)\n        except TypeError:\n            _update_hasher(hasher, item)\n            for item in iter_:\n                hasher.update(SEP)\n                _update_hasher(hasher, item)\n    else:\n        prefix, hashable = _covert_to_hashable(data)\n        binary_data = prefix + hashable\n        hasher.update(binary_data)",
    "docstring": "This is the clear winner over the generate version.\n    Used by hash_data\n\n    Ignore:\n        import utool\n        rng = np.random.RandomState(0)\n        # str1 = rng.rand(0).dumps()\n        str1 = b'SEP'\n        str2 = rng.rand(10000).dumps()\n        for timer in utool.Timerit(100, label='twocall'):\n            hasher = hashlib.sha256()\n            with timer:\n                hasher.update(str1)\n                hasher.update(str2)\n        a = hasher.hexdigest()\n        for timer in utool.Timerit(100, label='concat'):\n            hasher = hashlib.sha256()\n            with timer:\n                hasher.update(str1 + str2)\n        b = hasher.hexdigest()\n        assert a == b\n        # CONCLUSION: Faster to concat in case of prefixes and seps\n\n        nested_data = {'1': [rng.rand(100), '2', '3'],\n                       '2': ['1', '2', '3', '4', '5'],\n                       '3': [('1', '2'), ('3', '4'), ('5', '6')]}\n        data = list(nested_data.values())\n\n\n        for timer in utool.Timerit(1000, label='cat-generate'):\n            hasher = hashlib.sha256()\n            with timer:\n                hasher.update(b''.join(_bytes_generator(data)))\n\n        for timer in utool.Timerit(1000, label='inc-generate'):\n            hasher = hashlib.sha256()\n            with timer:\n                for b in _bytes_generator(data):\n                    hasher.update(b)\n\n        for timer in utool.Timerit(1000, label='inc-generate'):\n            hasher = hashlib.sha256()\n            with timer:\n                for b in _bytes_generator(data):\n                    hasher.update(b)\n\n        for timer in utool.Timerit(1000, label='chunk-inc-generate'):\n            hasher = hashlib.sha256()\n            import ubelt as ub\n            with timer:\n                for chunk in ub.chunks(_bytes_generator(data), 5):\n                    hasher.update(b''.join(chunk))\n\n        for timer in utool.Timerit(1000, label='inc-update'):\n            hasher = hashlib.sha256()\n            with timer:\n                _update_hasher(hasher, data)\n\n        data = ut.lorium_ipsum()\n        hash_data(data)\n        ut.hashstr27(data)\n        %timeit hash_data(data)\n        %timeit ut.hashstr27(repr(data))\n\n        for timer in utool.Timerit(100, label='twocall'):\n            hasher = hashlib.sha256()\n            with timer:\n                hash_data(data)\n\n        hasher = hashlib.sha256()\n        hasher.update(memoryview(np.array([1])))\n        print(hasher.hexdigest())\n\n        hasher = hashlib.sha256()\n        hasher.update(np.array(['1'], dtype=object))\n        print(hasher.hexdigest())"
  },
  {
    "code": "def safe_compare_digest(val1, val2):\n    if len(val1) != len(val2):\n        return False\n    result = 0\n    if PY3 and isinstance(val1, bytes) and isinstance(val2, bytes):\n        for i, j in zip(val1, val2):\n            result |= i ^ j\n    else:\n        for i, j in zip(val1, val2):\n            result |= (ord(i) ^ ord(j))\n    return result == 0",
    "docstring": "safe_compare_digest method.\n\n    :param val1: string or bytes for compare\n    :type val1: str | bytes\n    :param val2: string or bytes for compare\n    :type val2: str | bytes"
  },
  {
    "code": "def normnorm(self):\n        n = self.norm()\n        return V2(-self.y / n, self.x / n)",
    "docstring": "Return a vecor noraml to this one with a norm of one\n\n        :return: V2"
  },
  {
    "code": "def get_default_base_name(self, viewset):\n        queryset = getattr(viewset, 'queryset', None)\n        if queryset is not None:\n            get_url_name = getattr(queryset.model, 'get_url_name', None)\n            if get_url_name is not None:\n                return get_url_name()\n        return super(SortedDefaultRouter, self).get_default_base_name(viewset)",
    "docstring": "Attempt to automatically determine base name using `get_url_name`."
  },
  {
    "code": "def __step4(self):\n        step = 0\n        done = False\n        row = -1\n        col = -1\n        star_col = -1\n        while not done:\n            (row, col) = self.__find_a_zero()\n            if row < 0:\n                done = True\n                step = 6\n            else:\n                self.marked[row][col] = 2\n                star_col = self.__find_star_in_row(row)\n                if star_col >= 0:\n                    col = star_col\n                    self.row_covered[row] = True\n                    self.col_covered[col] = False\n                else:\n                    done = True\n                    self.Z0_r = row\n                    self.Z0_c = col\n                    step = 5\n        return step",
    "docstring": "Find a noncovered zero and prime it. If there is no starred zero\n        in the row containing this primed zero, Go to Step 5. Otherwise,\n        cover this row and uncover the column containing the starred\n        zero. Continue in this manner until there are no uncovered zeros\n        left. Save the smallest uncovered value and Go to Step 6."
  },
  {
    "code": "def _unregister_service(self):\n        if self._registration is not None:\n            try:\n                self._registration.unregister()\n            except BundleException as ex:\n                logger = logging.getLogger(\n                    \"-\".join((self._ipopo_instance.name, \"ServiceRegistration\"))\n                )\n                logger.error(\"Error unregistering a service: %s\", ex)\n            self._ipopo_instance.safe_callback(\n                ipopo_constants.IPOPO_CALLBACK_POST_UNREGISTRATION,\n                self._svc_reference,\n            )\n            self._registration = None\n            self._svc_reference = None",
    "docstring": "Unregisters the provided service, if needed"
  },
  {
    "code": "def backness(self, value):\n        if (value is not None) and (not value in DG_V_BACKNESS):\n            raise ValueError(\"Unrecognized value for backness: '%s'\" % value)\n        self.__backness = value",
    "docstring": "Set the backness of the vowel.\n\n        :param str value: the value to be set"
  },
  {
    "code": "def _op(self, line, op=None, offset=0):\n        if op is None:\n            op = self.op_count[line]\n        return \"line{}_gate{}\".format(line, op + offset)",
    "docstring": "Returns the gate name for placing a gate on a line.\n\n        :param int line: Line number.\n        :param int op: Operation number or, by default, uses the current op count.\n        :return: Gate name.\n        :rtype: string"
  },
  {
    "code": "def get_version():\n        if PackageHelper.__version:\n            return PackageHelper.__version\n        PackageHelper.__version = \"Unknown\"\n        file = os.path.realpath(__file__)\n        folder = os.path.dirname(file)\n        try:\n            semver = open(folder + \"/../../.semver\", \"r\")\n            PackageHelper.__version = semver.read().rstrip()\n            semver.close()\n            return PackageHelper.__version\n        except:\n            pass\n        try:\n            distribution = pkg_resources.get_distribution(PackageHelper.get_alias())\n            if distribution.version:\n                PackageHelper.__version = distribution.version\n            return PackageHelper.__version\n        except:\n            pass\n        return PackageHelper.__version",
    "docstring": "Get the version number of this package.\n\n        Returns:\n            str: The version number (marjor.minor.patch).\n\n        Note:\n            When this package is installed, the version number will be available through the\n            package resource details. Otherwise this method will look for a ``.semver`` file.\n\n        Note:\n            In rare cases corrupt installs can cause the version number to be unknown. In this case\n            the version number will be set to the string \"Unknown\"."
  },
  {
    "code": "def create(self, query_name, saved_query):\n        url = \"{0}/{1}\".format(self.saved_query_url, query_name)\n        payload = saved_query\n        if not isinstance(payload, str):\n            payload = json.dumps(saved_query)\n        response = self._get_json(HTTPMethods.PUT, url, self._get_master_key(), data=payload)\n        return response",
    "docstring": "Creates the saved query via a PUT request to Keen IO Saved Query endpoint.\n        Master key must be set."
  },
  {
    "code": "def save(self, force_insert=False, force_update=False, using=None, update_fields=None):\n        super().save(force_insert, force_update, using, update_fields)\n        if self.main_language:\n            TransLanguage.objects.exclude(pk=self.pk).update(main_language=False)",
    "docstring": "Overwrite of the save method in order that when setting the language\n        as main we deactivate any other model selected as main before\n\n        :param force_insert:\n        :param force_update:\n        :param using:\n        :param update_fields:\n        :return:"
  },
  {
    "code": "def get_outputs(self, input_value):\r\n        output_value = self.convert_to_xmlrpc(input_value)\r\n        output = {}\r\n        for name in self.output_names:\r\n            output[name] = output_value\r\n        return output",
    "docstring": "Generate a set of output values for a given input."
  },
  {
    "code": "def which(self):\n        if self.binary is None:\n            return None\n        return which(self.binary, path=self.env_path)",
    "docstring": "Figure out which binary this will execute.\n\n        Returns None if the binary is not found."
  },
  {
    "code": "def get_access_control_function():\n    fn_path = getattr(settings, 'ROSETTA_ACCESS_CONTROL_FUNCTION', None)\n    if fn_path is None:\n        return is_superuser_staff_or_in_translators_group\n    perm_module, perm_func = fn_path.rsplit('.', 1)\n    perm_module = importlib.import_module(perm_module)\n    return getattr(perm_module, perm_func)",
    "docstring": "Return a predicate for determining if a user can\n    access the Rosetta views"
  },
  {
    "code": "def tag_dssp_solvent_accessibility(self, force=False):\n        tagged = ['dssp_acc' in x.tags.keys() for x in self._monomers]\n        if (not all(tagged)) or force:\n            dssp_out = run_dssp(self.pdb, path=False)\n            if dssp_out is None:\n                return\n            dssp_acc_list = extract_solvent_accessibility_dssp(\n                dssp_out, path=False)\n            for monomer, dssp_acc in zip(self._monomers, dssp_acc_list):\n                monomer.tags['dssp_acc'] = dssp_acc[-1]\n        return",
    "docstring": "Tags each `Residues` Polymer with its solvent accessibility.\n\n        Notes\n        -----\n        For more about DSSP's solvent accessibilty metric, see:\n            http://swift.cmbi.ru.nl/gv/dssp/HTML/descrip.html#ACC\n\n        References\n        ----------\n        .. [1] Kabsch W, Sander C (1983) \"Dictionary of protein\n           secondary structure: pattern recognition of hydrogen-bonded\n           and geometrical features\", Biopolymers, 22, 2577-637.\n\n        Parameters\n        ----------\n        force : bool, optional\n            If `True` the tag will be run even if `Residues` are\n            already tagged."
  },
  {
    "code": "def alloc_vpcid(nexus_ips):\n    LOG.debug(\"alloc_vpc() called\")\n    vpc_id = 0\n    intersect = _get_free_vpcids_on_switches(nexus_ips)\n    for intersect_tuple in intersect:\n        try:\n            update_vpc_entry(nexus_ips, intersect_tuple.vpc_id,\n                             False, True)\n            vpc_id = intersect_tuple.vpc_id\n            break\n        except Exception:\n            LOG.exception(\n                \"This exception is expected if another controller \"\n                \"beat us to vpcid %(vpcid)s for nexus %(ip)s\",\n                {'vpcid': intersect_tuple.vpc_id,\n                 'ip': ', '.join(map(str, nexus_ips))})\n    return vpc_id",
    "docstring": "Allocate a vpc id for the given list of switch_ips."
  },
  {
    "code": "def temperature_data_from_csv(\n    filepath_or_buffer,\n    tz=None,\n    date_col=\"dt\",\n    temp_col=\"tempF\",\n    gzipped=False,\n    freq=None,\n    **kwargs\n):\n    read_csv_kwargs = {\n        \"usecols\": [date_col, temp_col],\n        \"dtype\": {temp_col: np.float64},\n        \"parse_dates\": [date_col],\n        \"index_col\": date_col,\n    }\n    if gzipped:\n        read_csv_kwargs.update({\"compression\": \"gzip\"})\n    read_csv_kwargs.update(kwargs)\n    if tz is None:\n        tz = \"UTC\"\n    df = pd.read_csv(filepath_or_buffer, **read_csv_kwargs).tz_localize(tz)\n    if freq == \"hourly\":\n        df = df.resample(\"H\").sum()\n    return df[temp_col]",
    "docstring": "Load temperature data from a CSV file.\n\n    Default format::\n\n        dt,tempF\n        2017-01-01T00:00:00+00:00,21\n        2017-01-01T01:00:00+00:00,22.5\n        2017-01-01T02:00:00+00:00,23.5\n\n    Parameters\n    ----------\n    filepath_or_buffer : :any:`str` or file-handle\n        File path or object.\n    tz : :any:`str`, optional\n        E.g., ``'UTC'`` or ``'US/Pacific'``\n    date_col : :any:`str`, optional, default ``'dt'``\n        Date period start column.\n    temp_col : :any:`str`, optional, default ``'tempF'``\n        Temperature column.\n    gzipped : :any:`bool`, optional\n        Whether file is gzipped.\n    freq : :any:`str`, optional\n        If given, apply frequency to data using :any:`pandas.Series.resample`.\n    **kwargs\n        Extra keyword arguments to pass to :any:`pandas.read_csv`, such as\n        ``sep='|'``."
  },
  {
    "code": "def get_task_module(feature):\n    try:\n        importlib.import_module(feature)\n    except ImportError:\n        raise FeatureNotFound(feature)\n    tasks_module = None\n    try:\n        tasks_module = importlib.import_module(feature + '.apetasks')\n    except ImportError:\n        pass\n    try:\n        tasks_module = importlib.import_module(feature + '.tasks')\n    except ImportError:\n        pass\n    return tasks_module",
    "docstring": "Return imported task module of feature.\n\n    This function first tries to import the feature and raises FeatureNotFound\n    if that is not possible.\n    Thereafter, it looks for a submodules called ``apetasks`` and ``tasks`` in that order.\n    If such a submodule exists, it is imported and returned.\n\n    :param feature: name of feature to fet task module for.\n    :raises: FeatureNotFound if feature_module could not be imported.\n    :return: imported module containing the ape tasks of feature or None,\n                if module cannot be imported."
  },
  {
    "code": "def save_html(out_file, plot_html):\n    internal_open = False\n    if type(out_file) == str:\n        out_file = open(out_file, \"w\")\n        internal_open = True\n    out_file.write(\"<html><head><script>\\n\")\n    bundle_path = os.path.join(os.path.split(__file__)[0], \"resources\", \"bundle.js\")\n    with io.open(bundle_path, encoding=\"utf-8\") as f:\n        bundle_data = f.read()\n    out_file.write(bundle_data)\n    out_file.write(\"</script></head><body>\\n\")\n    out_file.write(plot_html.data)\n    out_file.write(\"</body></html>\\n\")\n    if internal_open:\n        out_file.close()",
    "docstring": "Save html plots to an output file."
  },
  {
    "code": "def remove(name, rc_file='~/.odoorpcrc'):\n    conf = ConfigParser()\n    conf.read([os.path.expanduser(rc_file)])\n    if not conf.has_section(name):\n        raise ValueError(\n            \"'%s' session does not exist in %s\" % (name, rc_file))\n    conf.remove_section(name)\n    with open(os.path.expanduser(rc_file), 'wb') as file_:\n        conf.write(file_)",
    "docstring": "Remove the session configuration identified by `name`\n    from the `rc_file` file.\n\n    >>> import odoorpc\n    >>> odoorpc.session.remove('foo')     # doctest: +SKIP\n\n    .. doctest::\n        :hide:\n\n        >>> import odoorpc\n        >>> session = '%s_session' % DB\n        >>> odoorpc.session.remove(session)\n\n    :raise: `ValueError` (wrong session name)"
  },
  {
    "code": "def results_history(history_log, no_color):\n    try:\n        with open(history_log, 'r') as f:\n            lines = f.readlines()\n    except Exception as error:\n        echo_style(\n            'Unable to process results history log: %s' % error,\n            no_color,\n            fg='red'\n        )\n        sys.exit(1)\n    index = len(lines)\n    for item in lines:\n        click.echo('{} {}'.format(index, item), nl=False)\n        index -= 1",
    "docstring": "Display a list of ipa test results history."
  },
  {
    "code": "def to_bytes(self):\n        raw = b''\n        if not self._options:\n            return raw\n        for ipopt in self._options:\n            raw += ipopt.to_bytes()\n        padbytes = 4 - (len(raw) % 4)\n        raw += b'\\x00'*padbytes\n        return raw",
    "docstring": "Takes a list of IPOption objects and returns a packed byte string\n        of options, appropriately padded if necessary."
  },
  {
    "code": "def changed(self, message=None, *args):\n        if message is not None:\n            self.logger.debug('%s: %s', self._repr(), message % args)\n        self.logger.debug('%s: changed', self._repr())\n        if self.parent is not None:\n            self.parent.changed()\n        elif isinstance(self, Mutable):\n            super(TrackedObject, self).changed()",
    "docstring": "Marks the object as changed.\n\n        If a `parent` attribute is set, the `changed()` method on the parent\n        will be called, propagating the change notification up the chain.\n\n        The message (if provided) will be debug logged."
  },
  {
    "code": "def merge_strings_files(old_strings_file, new_strings_file):\n    old_localizable_dict = generate_localization_key_to_entry_dictionary_from_file(old_strings_file)\n    output_file_elements = []\n    f = open_strings_file(new_strings_file, \"r+\")\n    for header_comment, comments, key, value in extract_header_comment_key_value_tuples_from_file(f):\n        if len(header_comment) > 0:\n            output_file_elements.append(Comment(header_comment))\n        localize_value = value\n        if key in old_localizable_dict:\n            localize_value = old_localizable_dict[key].value\n        output_file_elements.append(LocalizationEntry(comments, key, localize_value))\n    f.close()\n    write_file_elements_to_strings_file(old_strings_file, output_file_elements)",
    "docstring": "Merges the old strings file with the new one.\n\n    Args:\n        old_strings_file (str): The path to the old strings file (previously produced, and possibly altered)\n        new_strings_file (str): The path to the new strings file (newly produced)."
  },
  {
    "code": "def msg(self, level, s, *args):\n        if s and level <= self.debug:\n            print \"%s%s %s\" % (\"  \" * self.indent, s, ' '.join(map(repr, args)))",
    "docstring": "Print a debug message with the given level"
  },
  {
    "code": "def get_smart_task(self, task_id):\n        def process_result(result):\n            return SmartTask(self, result)\n        return Command('get', [ROOT_SMART_TASKS, task_id],\n                       process_result=process_result)",
    "docstring": "Return specified transition.\n\n        Returns a Command."
  },
  {
    "code": "async def add_shade_to_scene(self, shade_id, scene_id, position=None):\n        if position is None:\n            _shade = await self.get_shade(shade_id)\n            position = await _shade.get_current_position()\n        await (SceneMembers(self.request)).create_scene_member(\n            position, scene_id, shade_id\n        )",
    "docstring": "Add a shade to a scene."
  },
  {
    "code": "def cert_from_instance(instance):\n    if instance.signature:\n        if instance.signature.key_info:\n            return cert_from_key_info(instance.signature.key_info,\n                                      ignore_age=True)\n    return []",
    "docstring": "Find certificates that are part of an instance\n\n    :param instance: An instance\n    :return: possible empty list of certificates"
  },
  {
    "code": "def get_conv_out_grad(net, image, class_id=None, conv_layer_name=None):\n    return _get_grad(net, image, class_id, conv_layer_name, image_grad=False)",
    "docstring": "Get the output and gradients of output of a convolutional layer.\n\n    Parameters:\n    ----------\n    net: Block\n        Network to use for visualization.\n    image: NDArray\n        Preprocessed image to use for visualization.\n    class_id: int\n        Category ID this image belongs to. If not provided,\n        network's prediction will be used.\n    conv_layer_name: str\n        Name of the convolutional layer whose output and output's gradients need to be acptured."
  },
  {
    "code": "def config_conf(obj):\n    \"Extracts the configuration of the underlying ConfigParser from obj\"\n    cfg = {}\n    for name in dir(obj):\n        if name in CONFIG_PARSER_CFG:\n            cfg[name] = getattr(obj, name)\n    return cfg",
    "docstring": "Extracts the configuration of the underlying ConfigParser from obj"
  },
  {
    "code": "def _create_event(self, alert_type, msg_title, msg, server, tags=None):\n        msg_title = 'Couchbase {}: {}'.format(server, msg_title)\n        msg = 'Couchbase instance {} {}'.format(server, msg)\n        return {\n            'timestamp': int(time.time()),\n            'event_type': 'couchbase_rebalance',\n            'msg_text': msg,\n            'msg_title': msg_title,\n            'alert_type': alert_type,\n            'source_type_name': self.SOURCE_TYPE_NAME,\n            'aggregation_key': server,\n            'tags': tags,\n        }",
    "docstring": "Create an event object"
  },
  {
    "code": "def __parameter_enum(self, final_subfield):\n    if isinstance(final_subfield, messages.EnumField):\n      enum_descriptor = {}\n      for enum_value in final_subfield.type.to_dict().keys():\n        enum_descriptor[enum_value] = {'backendValue': enum_value}\n      return enum_descriptor",
    "docstring": "Returns enum descriptor of final subfield if it is an enum.\n\n    An enum descriptor is a dictionary with keys as the names from the enum and\n    each value is a dictionary with a single key \"backendValue\" and value equal\n    to the same enum name used to stored it in the descriptor.\n\n    The key \"description\" can also be used next to \"backendValue\", but protorpc\n    Enum classes have no way of supporting a description for each value.\n\n    Args:\n      final_subfield: A simple field from the end of a subfield list.\n\n    Returns:\n      The enum descriptor for the field, if it's an enum descriptor, else\n          returns None."
  },
  {
    "code": "def tags_getListUserPopular(user_id='', count=''):\n    method = 'flickr.tags.getListUserPopular'\n    auth = user_id == ''\n    data = _doget(method, auth=auth, user_id=user_id)\n    result = {}\n    if isinstance(data.rsp.tags.tag, list):\n        for tag in data.rsp.tags.tag:\n            result[tag.text] = tag.count\n    else:\n        result[data.rsp.tags.tag.text] = data.rsp.tags.tag.count\n    return result",
    "docstring": "Gets the popular tags for a user in dictionary form tag=>count"
  },
  {
    "code": "def with_source(self, lease):\n        super().with_source(lease)\n        self.offset = lease.offset\n        self.sequence_number = lease.sequence_number",
    "docstring": "Init Azure Blob Lease from existing."
  },
  {
    "code": "def waitForResponse(self, timeOut=None):\n        self.__evt.wait(timeOut)\n        if self.waiting():\n            raise Timeout()\n        else:\n            if self.response[\"error\"]:\n                raise Exception(self.response[\"error\"])\n            else:\n                return self.response[\"result\"]",
    "docstring": "blocks until the response arrived or timeout is reached."
  },
  {
    "code": "def _get_snmpv2c(self, oid):\n        snmp_target = (self.hostname, self.snmp_port)\n        cmd_gen = cmdgen.CommandGenerator()\n        (error_detected, error_status, error_index, snmp_data) = cmd_gen.getCmd(\n            cmdgen.CommunityData(self.community),\n            cmdgen.UdpTransportTarget(snmp_target, timeout=1.5, retries=2),\n            oid,\n            lookupNames=True,\n            lookupValues=True,\n        )\n        if not error_detected and snmp_data[0][1]:\n            return text_type(snmp_data[0][1])\n        return \"\"",
    "docstring": "Try to send an SNMP GET operation using SNMPv2 for the specified OID.\n\n        Parameters\n        ----------\n        oid : str\n            The SNMP OID that you want to get.\n\n        Returns\n        -------\n        string : str\n            The string as part of the value from the OID you are trying to retrieve."
  },
  {
    "code": "def model_ext_functions(vk, model):\n    model['ext_functions'] = {'instance': {}, 'device': {}}\n    alias = {v: k for k, v in model['alias'].items()}\n    for extension in get_extensions_filtered(vk):\n        for req in extension['require']:\n            if not req.get('command'):\n                continue\n            ext_type = extension['@type']\n            for x in req['command']:\n                name = x['@name']\n                if name in alias.keys():\n                    model['ext_functions'][ext_type][name] = alias[name]\n                else:\n                    model['ext_functions'][ext_type][name] = name",
    "docstring": "Fill the model with extensions functions"
  },
  {
    "code": "def setup():\n    install_requirements = [\"attrdict\"]\n    if sys.version_info[:2] < (3, 4):\n        install_requirements.append(\"pathlib\")\n    setup_requirements = ['six', 'setuptools>=17.1', 'setuptools_scm']\n    needs_sphinx = {\n        'build_sphinx',\n        'docs',\n        'upload_docs',\n    }.intersection(sys.argv)\n    if needs_sphinx:\n        setup_requirements.append('sphinx')\n    setuptools.setup(\n        author=\"David Gidwani\",\n        author_email=\"david.gidwani@gmail.com\",\n        classifiers=[\n            \"Development Status :: 4 - Beta\",\n            \"Intended Audience :: Developers\",\n            \"License :: OSI Approved :: BSD License\",\n            \"Operating System :: OS Independent\",\n            \"Programming Language :: Python\",\n            \"Programming Language :: Python :: 2\",\n            \"Programming Language :: Python :: 2.7\",\n            \"Programming Language :: Python :: 3\",\n            \"Programming Language :: Python :: 3.3\",\n            \"Programming Language :: Python :: 3.4\",\n            \"Topic :: Software Development\",\n            \"Topic :: Software Development :: Libraries :: Python Modules\",\n        ],\n        description=\"Painless access to namespaced environment variables\",\n        download_url=\"https://github.com/darvid/biome/tarball/0.1\",\n        install_requires=install_requirements,\n        keywords=\"conf config configuration environment\",\n        license=\"BSD\",\n        long_description=readme(),\n        name=\"biome\",\n        package_dir={'': 'src'},\n        packages=setuptools.find_packages('./src'),\n        setup_requires=setup_requirements,\n        tests_require=[\"pytest\"],\n        url=\"https://github.com/darvid/biome\",\n        use_scm_version=True,\n    )",
    "docstring": "Package setup entrypoint."
  },
  {
    "code": "def get(self, timeout=None, block=True, throw_dead=True):\n        _vv and IOLOG.debug('%r.get(timeout=%r, block=%r)', self, timeout, block)\n        try:\n            msg = self._latch.get(timeout=timeout, block=block)\n        except LatchError:\n            raise ChannelError(self.closed_msg)\n        if msg.is_dead and throw_dead:\n            msg._throw_dead()\n        return msg",
    "docstring": "Sleep waiting for a message to arrive on this receiver.\n\n        :param float timeout:\n            If not :data:`None`, specifies a timeout in seconds.\n\n        :raises mitogen.core.ChannelError:\n            The remote end indicated the channel should be closed,\n            communication with it was lost, or :meth:`close` was called in the\n            local process.\n\n        :raises mitogen.core.TimeoutError:\n            Timeout was reached.\n\n        :returns:\n            :class:`Message` that was received."
  },
  {
    "code": "def merge_blocks(a_blocks, b_blocks):\n    assert a_blocks[-1][2] == b_blocks[-1][2] == 0\n    assert a_blocks[-1] == b_blocks[-1]\n    combined_blocks = sorted(list(set(a_blocks + b_blocks)))\n    i = j = 0\n    for a, b, size in combined_blocks:\n        assert i <= a\n        assert j <= b\n        i = a + size\n        j = b + size\n    return combined_blocks",
    "docstring": "Given two lists of blocks, combine them, in the proper order.\n\n    Ensure that there are no overlaps, and that they are for sequences of the\n    same length."
  },
  {
    "code": "def recv_match(self, condition=None, type=None, blocking=False):\n        if type is not None and not isinstance(type, list):\n            type = [type]\n        while True:\n            m = self.recv_msg()\n            if m is None:\n                return None\n            if type is not None and not m.get_type() in type:\n                continue\n            if not mavutil.evaluate_condition(condition, self.messages):\n                continue\n            return m",
    "docstring": "recv the next message that matches the given condition\n        type can be a string or a list of strings"
  },
  {
    "code": "def personality(self, category: str = 'mbti') -> Union[str, int]:\n        mbtis = ('ISFJ', 'ISTJ', 'INFJ', 'INTJ',\n                 'ISTP', 'ISFP', 'INFP', 'INTP',\n                 'ESTP', 'ESFP', 'ENFP', 'ENTP',\n                 'ESTJ', 'ESFJ', 'ENFJ', 'ENTJ')\n        if category.lower() == 'rheti':\n            return self.random.randint(1, 10)\n        return self.random.choice(mbtis)",
    "docstring": "Generate a type of personality.\n\n        :param category: Category.\n        :return: Personality type.\n        :rtype: str or int\n\n        :Example:\n            ISFJ."
  },
  {
    "code": "def create_table(self, model_class):\n        if model_class.is_system_model():\n            raise DatabaseException(\"You can't create system table\")\n        if getattr(model_class, 'engine') is None:\n            raise DatabaseException(\"%s class must define an engine\" % model_class.__name__)\n        self._send(model_class.create_table_sql(self))",
    "docstring": "Creates a table for the given model class, if it does not exist already."
  },
  {
    "code": "def set_timezone(tz=None, deploy=False):\n    if not tz:\n        raise CommandExecutionError(\"Timezone name option must not be none.\")\n    ret = {}\n    query = {'type': 'config',\n             'action': 'set',\n             'xpath': '/config/devices/entry[@name=\\'localhost.localdomain\\']/deviceconfig/system/timezone',\n             'element': '<timezone>{0}</timezone>'.format(tz)}\n    ret.update(__proxy__['panos.call'](query))\n    if deploy is True:\n        ret.update(commit())\n    return ret",
    "docstring": "Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed.\n\n    CLI Example:\n\n    Args:\n        tz (str): The name of the timezone to set.\n\n        deploy (bool): If true then commit the full candidate configuration, if false only set pending change.\n\n    .. code-block:: bash\n\n        salt '*' panos.set_timezone UTC\n        salt '*' panos.set_timezone UTC deploy=True"
  },
  {
    "code": "def create_bigquery_table(self, database, schema, table_name, callback,\n                              sql):\n        conn = self.get_thread_connection()\n        client = conn.handle\n        view_ref = self.table_ref(database, schema, table_name, conn)\n        view = google.cloud.bigquery.Table(view_ref)\n        callback(view)\n        with self.exception_handler(sql):\n            client.create_table(view)",
    "docstring": "Create a bigquery table. The caller must supply a callback\n        that takes one argument, a `google.cloud.bigquery.Table`, and mutates\n        it."
  },
  {
    "code": "def random_alphanum(length):\n    charset = string.ascii_letters + string.digits\n    return random_string(length, charset)",
    "docstring": "Return a random string of ASCII letters and digits.\n\n    :param int length: The length of string to return\n    :returns: A random string\n    :rtype: str"
  },
  {
    "code": "def delete_table(table_name):\n    to_delete = [\n        make_key(table_name, rec['id'])\n        for rec in read_by_indexes(table_name, [])\n    ]\n    with DatastoreTransaction() as tx:\n        tx.get_commit_req().mutation.delete.extend(to_delete)",
    "docstring": "Mainly for testing."
  },
  {
    "code": "def main():\n    s = rawdata.content.DataFiles()\n    all_ingredients = list(s.get_collist_by_name(data_files[1]['file'], data_files[1]['col'])[0])\n    best_ingred, worst_ingred = find_best_ingredients(all_ingredients, dinner_guests)\n    print('best ingred  = ', best_ingred)\n    print('worst ingred = ', worst_ingred)\n    for have in ingredients_on_hand:\n        if have in best_ingred:\n            print('Use this = ', have)",
    "docstring": "script to find a list of recipes for a group of people \n    with specific likes and dislikes.\n    \n    Output of script\n\n        best ingred  =  ['Tea', 'Tofu', 'Cheese', 'Cucumber', 'Salad', 'Chocolate']\n        worst ingred =  ['Fish', 'Lamb', 'Pie', 'Asparagus', 'Chicken', 'Turnips']\n        Use this =  Tofu\n        Use this =  Cheese"
  },
  {
    "code": "def add_review(self, reviewer, product, review, date=None):\n        if not isinstance(reviewer, self._reviewer_cls):\n            raise TypeError(\n                \"Type of given reviewer isn't acceptable:\", reviewer,\n                \", expected:\", self._reviewer_cls)\n        elif not isinstance(product, self._product_cls):\n            raise TypeError(\n                \"Type of given product isn't acceptable:\", product,\n                \", expected:\", self._product_cls)\n        r = self._review_cls(review, date=date)\n        self.graph.add_edge(reviewer, product, review=r)\n        return r",
    "docstring": "Add a new review from a given reviewer to a given product.\n\n        Args:\n          reviewer: an instance of Reviewer.\n          product: an instance of Product.\n          review: a float value.\n          date: date the review issued.\n\n        Returns:\n          the added new review object.\n\n        Raises:\n          TypeError: when given reviewer and product aren't instance of\n            specified reviewer and product class when this graph is constructed."
  },
  {
    "code": "def isAudio(self):\n        val=False\n        if self.__dict__['codec_type']:\n            if str(self.__dict__['codec_type']) == 'audio':\n                val=True\n        return val",
    "docstring": "Is this stream labelled as an audio stream?"
  },
  {
    "code": "def run(self):\n        while True:\n            try:\n                data = None\n                if self.debug:\n                    self.py3_wrapper.log(\"waiting for a connection\")\n                connection, client_address = self.sock.accept()\n                try:\n                    if self.debug:\n                        self.py3_wrapper.log(\"connection from\")\n                    data = connection.recv(MAX_SIZE)\n                    if data:\n                        data = json.loads(data.decode(\"utf-8\"))\n                        if self.debug:\n                            self.py3_wrapper.log(u\"received %s\" % data)\n                        self.command_runner.run_command(data)\n                finally:\n                    connection.close()\n            except Exception:\n                if data:\n                    self.py3_wrapper.log(\"Command error\")\n                    self.py3_wrapper.log(data)\n                self.py3_wrapper.report_exception(\"command failed\")",
    "docstring": "Main thread listen to socket and send any commands to the\n        CommandRunner."
  },
  {
    "code": "def reset(self):\n        for index in range(self.counts_len):\n            self.counts[index] = 0\n        self.total_count = 0\n        self.min_value = sys.maxsize\n        self.max_value = 0\n        self.start_time_stamp_msec = sys.maxsize\n        self.end_time_stamp_msec = 0",
    "docstring": "Reset the histogram to a pristine state"
  },
  {
    "code": "def month_name(self, locale=None):\n        if self.tz is not None and not timezones.is_utc(self.tz):\n            values = self._local_timestamps()\n        else:\n            values = self.asi8\n        result = fields.get_date_name_field(values, 'month_name',\n                                            locale=locale)\n        result = self._maybe_mask_results(result, fill_value=None)\n        return result",
    "docstring": "Return the month names of the DateTimeIndex with specified locale.\n\n        .. versionadded:: 0.23.0\n\n        Parameters\n        ----------\n        locale : str, optional\n            Locale determining the language in which to return the month name.\n            Default is English locale.\n\n        Returns\n        -------\n        Index\n            Index of month names.\n\n        Examples\n        --------\n        >>> idx = pd.date_range(start='2018-01', freq='M', periods=3)\n        >>> idx\n        DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31'],\n                      dtype='datetime64[ns]', freq='M')\n        >>> idx.month_name()\n        Index(['January', 'February', 'March'], dtype='object')"
  },
  {
    "code": "def symmetry(self, input_entity, coefficients, duplicate=True):\n        d = {1: \"Line\", 2: \"Surface\", 3: \"Volume\"}\n        entity = \"{}{{{}}};\".format(d[input_entity.dimension], input_entity.id)\n        if duplicate:\n            entity = \"Duplicata{{{}}}\".format(entity)\n        self._GMSH_CODE.append(\n            \"Symmetry {{{}}} {{{}}}\".format(\n                \", \".join([str(co) for co in coefficients]), entity\n            )\n        )\n        return",
    "docstring": "Transforms all elementary entities symmetrically to a plane. The vector\n        should contain four expressions giving the coefficients of the plane's equation."
  },
  {
    "code": "def main():\n    alarm = XBeeAlarm('/dev/ttyUSB0', '\\x56\\x78')\n    routine = SimpleWakeupRoutine(alarm)\n    from time import sleep\n    while True:\n        try:\n            print \"Waiting 5 seconds...\"\n            sleep(5)\n            print \"Firing\"\n            routine.trigger()\n        except KeyboardInterrupt:\n            break",
    "docstring": "Run through simple demonstration of alarm concept"
  },
  {
    "code": "def get_ips(linode_id=None):\n    if linode_id:\n        ips = _query('linode', 'ip.list', args={'LinodeID': linode_id})\n    else:\n        ips = _query('linode', 'ip.list')\n    ips = ips['DATA']\n    ret = {}\n    for item in ips:\n        node_id = six.text_type(item['LINODEID'])\n        if item['ISPUBLIC'] == 1:\n            key = 'public_ips'\n        else:\n            key = 'private_ips'\n        if ret.get(node_id) is None:\n            ret.update({node_id: {'public_ips': [], 'private_ips': []}})\n        ret[node_id][key].append(item['IPADDRESS'])\n    if linode_id:\n        _all_ips = {'public_ips': [], 'private_ips': []}\n        matching_id = ret.get(six.text_type(linode_id))\n        if matching_id:\n            _all_ips['private_ips'] = matching_id['private_ips']\n            _all_ips['public_ips'] = matching_id['public_ips']\n        ret = _all_ips\n    return ret",
    "docstring": "Returns public and private IP addresses.\n\n    linode_id\n        Limits the IP addresses returned to the specified Linode ID."
  },
  {
    "code": "def filters(self):\n        if self._filters is None:\n            self._filters, self._attributes = self._fetch_configuration()\n        return self._filters",
    "docstring": "List of filters available for the dataset."
  },
  {
    "code": "def is_elem_ref(elem_ref):\n    return (\n        elem_ref\n        and isinstance(elem_ref, tuple)\n        and len(elem_ref) == 3\n        and (elem_ref[0] == ElemRefObj or elem_ref[0] == ElemRefArr)\n    )",
    "docstring": "Returns true if the elem_ref is an element reference\n\n    :param elem_ref:\n    :return:"
  },
  {
    "code": "def loads(s, encode_nominal=False, return_type=DENSE):\n    decoder = ArffDecoder()\n    return decoder.decode(s, encode_nominal=encode_nominal,\n                          return_type=return_type)",
    "docstring": "Convert a string instance containing the ARFF document into a Python\n    object.\n\n    :param s: a string object.\n    :param encode_nominal: boolean, if True perform a label encoding\n        while reading the .arff file.\n    :param return_type: determines the data structure used to store the\n        dataset. Can be one of `arff.DENSE`, `arff.COO`, `arff.LOD`,\n        `arff.DENSE_GEN` or `arff.LOD_GEN`.\n        Consult the sections on `working with sparse data`_ and `loading\n        progressively`_.\n    :return: a dictionary."
  },
  {
    "code": "def as_bool(self, key):\n        val = self[key]\n        if isinstance(val, bool):\n            return val\n        return val.lower() == \"yes\"",
    "docstring": "Express given key's value as a boolean type.\n\n        Typically, this is used for ``ssh_config``'s pseudo-boolean values\n        which are either ``\"yes\"`` or ``\"no\"``. In such cases, ``\"yes\"`` yields\n        ``True`` and any other value becomes ``False``.\n\n        .. note::\n            If (for whatever reason) the stored value is already boolean in\n            nature, it's simply returned.\n\n        .. versionadded:: 2.5"
  },
  {
    "code": "def get_conditions(self, service_id):\n        conditions = etree.Element('Conditions')\n        conditions.set('NotBefore', self.instant())\n        conditions.set('NotOnOrAfter', self.instant(offset=30))\n        restriction = etree.SubElement(conditions, 'AudienceRestrictionCondition')\n        audience = etree.SubElement(restriction, 'Audience')\n        audience.text = service_id\n        return conditions",
    "docstring": "Build a Conditions XML block for a SAML 1.1 Assertion."
  },
  {
    "code": "def find_var_end(self, text):\n        return self.find_end(text, self.start_var_token, self.end_var_token)",
    "docstring": "find the of a variable"
  },
  {
    "code": "def find_courses(self, partial):\n        partial = partial.lower()\n        keys = self.courses.keys()\n        keys = [k for k in keys if k.lower().find(partial) != -1]\n        courses = [self.courses[k] for k in keys]\n        return list(set(courses))",
    "docstring": "Finds all courses by a given substring. This is case-insensitive."
  },
  {
    "code": "def config_loader(app, **kwargs):\n    app.config.from_object(Config)\n    app.config.update(**kwargs)",
    "docstring": "Custom config loader."
  },
  {
    "code": "def _read_pdb(path):\n        r_mode = 'r'\n        openf = open\n        if path.endswith('.gz'):\n            r_mode = 'rb'\n            openf = gzip.open\n        with openf(path, r_mode) as f:\n            txt = f.read()\n        if path.endswith('.gz'):\n            if sys.version_info[0] >= 3:\n                txt = txt.decode('utf-8')\n            else:\n                txt = txt.encode('ascii')\n        return path, txt",
    "docstring": "Read PDB file from local drive."
  },
  {
    "code": "def install_board_with_programmer(mcu,\n                                  programmer,\n                                  f_cpu=16000000,\n                                  core='arduino',\n                                  replace_existing=False,\n                                  ):\n    bunch = AutoBunch()\n    board_id = '{mcu}_{f_cpu}_{programmer}'.format(f_cpu=f_cpu,\n                                             mcu=mcu,\n                                             programmer=programmer,\n                                             )\n    bunch.name = '{mcu}@{f} Prog:{programmer}'.format(f=strfreq(f_cpu),\n                                                      mcu=mcu,\n                                                      programmer=programmer,\n                                                      )\n    bunch.upload.using = programmer\n    bunch.build.mcu = mcu\n    bunch.build.f_cpu = str(f_cpu) + 'L'\n    bunch.build.core = core\n    install_board(board_id, bunch, replace_existing=replace_existing)",
    "docstring": "install board with programmer."
  },
  {
    "code": "def create_table(self):\n        all_tables = self.aws_conn.list_tables()['TableNames']\n        if self.table_name in all_tables:\n            log.info(\"Table %s already exists\" % self.table_name)\n        else:\n            log.info(\"Table %s does not exist: creating it\" % self.table_name)\n            self.table = Table.create(\n                self.table_name,\n                schema=[\n                    HashKey('key')\n                ],\n                throughput={\n                    'read': 10,\n                    'write': 10,\n                },\n                connection=self.aws_conn,\n            )",
    "docstring": "Create the DynamoDB table used by this ObjectStore, only if it does\n        not already exists."
  },
  {
    "code": "def releaseNativeOverlayHandle(self, ulOverlayHandle, pNativeTextureHandle):\n        fn = self.function_table.releaseNativeOverlayHandle\n        result = fn(ulOverlayHandle, pNativeTextureHandle)\n        return result",
    "docstring": "Release the pNativeTextureHandle provided from the GetOverlayTexture call, this allows the system to free the underlying GPU resources for this object,\n        so only do it once you stop rendering this texture."
  },
  {
    "code": "def regex_search(self, regex: str) -> List[HistoryItem]:\n        regex = regex.strip()\n        if regex.startswith(r'/') and regex.endswith(r'/'):\n            regex = regex[1:-1]\n        finder = re.compile(regex, re.DOTALL | re.MULTILINE)\n        def isin(hi):\n            return finder.search(hi) or finder.search(hi.expanded)\n        return [itm for itm in self if isin(itm)]",
    "docstring": "Find history items which match a given regular expression\n\n        :param regex: the regular expression to search for.\n        :return: a list of history items, or an empty list if the string was not found"
  },
  {
    "code": "def delete(name, profile=\"splunk\"):\n    client = _get_splunk(profile)\n    try:\n        client.saved_searches.delete(name)\n        return True\n    except KeyError:\n        return None",
    "docstring": "Delete a splunk search\n\n    CLI Example:\n\n       splunk_search.delete 'my search name'"
  },
  {
    "code": "def show(self, wait=1.2, scale=10, module_color=(0, 0, 0, 255),\n            background=(255, 255, 255, 255), quiet_zone=4):\n        import os\n        import time\n        import tempfile\n        import webbrowser\n        try:\n            from urlparse import urljoin\n            from urllib import pathname2url\n        except ImportError:\n            from urllib.parse import urljoin\n            from urllib.request import pathname2url\n        f = tempfile.NamedTemporaryFile('wb', suffix='.png', delete=False)\n        self.png(f, scale=scale, module_color=module_color,\n                 background=background, quiet_zone=quiet_zone)\n        f.close()\n        webbrowser.open_new_tab(urljoin('file:', pathname2url(f.name)))\n        time.sleep(wait)\n        os.unlink(f.name)",
    "docstring": "Displays this QR code.\n\n        This method is mainly intended for debugging purposes.\n\n        This method saves the output of the :py:meth:`png` method (with a default\n        scaling factor of 10) to a temporary file and opens it with the\n        standard PNG viewer application or within the standard webbrowser. The\n        temporary file is deleted afterwards.\n\n        If this method does not show any result, try to increase the `wait`\n        parameter. This parameter specifies the time in seconds to wait till\n        the temporary file is deleted. Note, that this method does not return\n        until the provided amount of seconds (default: 1.2) has passed.\n\n        The other parameters are simply passed on to the `png` method."
  },
  {
    "code": "def exit_and_fail(self, msg=None, out=None):\n    self.exit(result=PANTS_FAILED_EXIT_CODE, msg=msg, out=out)",
    "docstring": "Exits the runtime with a nonzero exit code, indicating failure.\n\n    :param msg: A string message to print to stderr or another custom file desciptor before exiting.\n                (Optional)\n    :param out: The file descriptor to emit `msg` to. (Optional)"
  },
  {
    "code": "def _org_path(self, which, payload):\n        return Subscription(\n            self._server_config,\n            organization=payload['organization_id'],\n        ).path(which)",
    "docstring": "A helper method for generating paths with organization IDs in them.\n\n        :param which: A path such as \"manifest_history\" that has an\n            organization ID in it.\n        :param payload: A dict with an \"organization_id\" key in it.\n        :returns: A string. The requested path."
  },
  {
    "code": "def ncontains(self, column, value):\n        df = self.df[self.df[column].str.contains(value) == False]\n        if df is None:\n            self.err(\"Can not select contained data\")\n            return\n        self.df = df",
    "docstring": "Set the main dataframe instance to rows that do not\n        contains a string value in a column"
  },
  {
    "code": "def get(self, sid):\n        return RecordingContext(self._version, account_sid=self._solution['account_sid'], sid=sid, )",
    "docstring": "Constructs a RecordingContext\n\n        :param sid: The unique string that identifies the resource\n\n        :returns: twilio.rest.api.v2010.account.recording.RecordingContext\n        :rtype: twilio.rest.api.v2010.account.recording.RecordingContext"
  },
  {
    "code": "def validate_answer(self, value):\n        try:\n            serialized = json.dumps(value)\n        except (ValueError, TypeError):\n            raise serializers.ValidationError(\"Answer value must be JSON-serializable\")\n        if len(serialized) > Submission.MAXSIZE:\n            raise serializers.ValidationError(\"Maximum answer size exceeded.\")\n        return value",
    "docstring": "Check that the answer is JSON-serializable and not too long."
  },
  {
    "code": "def detail_dict(self):\n        d = self.dict\n        def aug_col(c):\n            d = c.dict\n            d['stats'] = [s.dict for s in c.stats]\n            return d\n        d['table'] = self.table.dict\n        d['table']['columns'] = [aug_col(c) for c in self.table.columns]\n        return d",
    "docstring": "A more detailed dict that includes the descriptions, sub descriptions, table\n        and columns."
  },
  {
    "code": "def AddStopTime(self, stop, problems=None, schedule=None, **kwargs):\n    if problems is None:\n      problems = problems_module.default_problem_reporter\n    stoptime = self.GetGtfsFactory().StopTime(\n        problems=problems, stop=stop, **kwargs)\n    self.AddStopTimeObject(stoptime, schedule)",
    "docstring": "Add a stop to this trip. Stops must be added in the order visited.\n\n    Args:\n      stop: A Stop object\n      kwargs: remaining keyword args passed to StopTime.__init__\n\n    Returns:\n      None"
  },
  {
    "code": "def is_method(arg):\n    if inspect.ismethod(arg):\n        return True\n    if isinstance(arg, NonInstanceMethod):\n        return True\n    if inspect.isfunction(arg):\n        return _get_first_arg_name(arg) == 'self'\n    return False",
    "docstring": "Checks whether given object is a method."
  },
  {
    "code": "def mpub(self, topic, *messages):\n        with self.random_connection() as client:\n            client.mpub(topic, *messages)\n            return self.wait_response()",
    "docstring": "Publish messages to a topic"
  },
  {
    "code": "def model(self) -> 'modeltools.Model':\n        model = vars(self).get('model')\n        if model:\n            return model\n        raise AttributeError(\n            f'The model object of element `{self.name}` has '\n            f'been requested but not been prepared so far.')",
    "docstring": "The |Model| object handled by the actual |Element| object.\n\n        Directly after their initialisation, elements do not know\n        which model they require:\n\n        >>> from hydpy import Element\n        >>> hland = Element('hland', outlets='outlet')\n        >>> hland.model\n        Traceback (most recent call last):\n        ...\n        AttributeError: The model object of element `hland` has been \\\nrequested but not been prepared so far.\n\n        During scripting and when working interactively in the Python\n        shell, it is often convenient to assign a |model| directly.\n\n        >>> from hydpy.models.hland_v1 import *\n        >>> parameterstep('1d')\n        >>> hland.model = model\n        >>> hland.model.name\n        'hland_v1'\n\n        >>> del hland.model\n        >>> hasattr(hland, 'model')\n        False\n\n        For the \"usual\" approach to prepare models, please see the method\n        |Element.init_model|.\n\n        The following examples show that assigning |Model| objects\n        to property |Element.model| creates some connection required by\n        the respective model type automatically .  These\n        examples  should be relevant for developers only.\n\n        The following |hbranch| model branches a single input value\n        (from to node `inp`) to multiple outputs (nodes `out1` and `out2`):\n\n        >>> from hydpy import Element, Node, reverse_model_wildcard_import\n        >>> reverse_model_wildcard_import()\n        >>> element = Element('a_branch',\n        ...                   inlets='branch_input',\n        ...                   outlets=('branch_output_1', 'branch_output_2'))\n        >>> inp = element.inlets.branch_input\n        >>> out1, out2 = element.outlets\n        >>> from hydpy.models.hbranch import *\n        >>> parameterstep()\n        >>> xpoints(0.0, 3.0)\n        >>> ypoints(branch_output_1=[0.0, 1.0], branch_output_2=[0.0, 2.0])\n        >>> parameters.update()\n        >>> element.model = model\n\n        To show that the inlet and outlet connections are built properly,\n        we assign a new value to the inlet node `inp` and verify that the\n        suitable fractions of this value are passed to the outlet nodes\n        out1` and `out2` by calling method |Model.doit|:\n\n        >>> inp.sequences.sim = 999.0\n        >>> model.doit(0)\n        >>> fluxes.input\n        input(999.0)\n        >>> out1.sequences.sim\n        sim(333.0)\n        >>> out2.sequences.sim\n        sim(666.0)"
  },
  {
    "code": "def pull(self):\n        for json_e in self.d.pull(repository=self.name, tag=self.tag, stream=True, decode=True):\n            logger.debug(json_e)\n            status = graceful_get(json_e, \"status\")\n            if status:\n                logger.info(status)\n            else:\n                error = graceful_get(json_e, \"error\")\n                logger.error(status)\n                raise ConuException(\"There was an error while pulling the image %s: %s\",\n                                    self.name, error)\n        self.using_transport(SkopeoTransport.DOCKER_DAEMON)",
    "docstring": "Pull this image from registry. Raises an exception if the image is not found in\n        the registry.\n\n        :return: None"
  },
  {
    "code": "def get_interface_switch(self, nexus_host,\n                             intf_type, interface):\n        if intf_type == \"ethernet\":\n            path_interface = \"phys-[eth\" + interface + \"]\"\n        else:\n            path_interface = \"aggr-[po\" + interface + \"]\"\n        action = snipp.PATH_IF % path_interface\n        starttime = time.time()\n        response = self.client.rest_get(action, nexus_host)\n        self.capture_and_print_timeshot(starttime, \"getif\",\n            switch=nexus_host)\n        LOG.debug(\"GET call returned interface %(if_type)s %(interface)s \"\n            \"config\", {'if_type': intf_type, 'interface': interface})\n        return response",
    "docstring": "Get the interface data from host.\n\n        :param nexus_host: IP address of Nexus switch\n        :param intf_type:  String which specifies interface type.\n                           example: ethernet\n        :param interface:  String indicating which interface.\n                           example: 1/19\n        :returns response: Returns interface data"
  },
  {
    "code": "def require_ajax_logged_in(func):\n    @functools.wraps(func)\n    def inner_func(self, *pargs, **kwargs):\n        if not self._ajax_api.logged_in:\n            logger.info('Logging into AJAX API for required meta method')\n            if not self.has_credentials:\n                raise ApiLoginFailure(\n                    'Login is required but no credentials were provided')\n            self._ajax_api.User_Login(name=self._state['username'],\n                password=self._state['password'])\n        return func(self, *pargs, **kwargs)\n    return inner_func",
    "docstring": "Check if ajax API is logged in and login if not"
  },
  {
    "code": "def retry(\n        transport: 'UDPTransport',\n        messagedata: bytes,\n        message_id: UDPMessageID,\n        recipient: Address,\n        stop_event: Event,\n        timeout_backoff: Iterable[int],\n) -> bool:\n    async_result = transport.maybe_sendraw_with_result(\n        recipient,\n        messagedata,\n        message_id,\n    )\n    event_quit = event_first_of(\n        async_result,\n        stop_event,\n    )\n    for timeout in timeout_backoff:\n        if event_quit.wait(timeout=timeout) is True:\n            break\n        log.debug(\n            'retrying message',\n            node=pex(transport.raiden.address),\n            recipient=pex(recipient),\n            msgid=message_id,\n        )\n        transport.maybe_sendraw_with_result(\n            recipient,\n            messagedata,\n            message_id,\n        )\n    return async_result.ready()",
    "docstring": "Send messagedata until it's acknowledged.\n\n    Exit when:\n\n    - The message is delivered.\n    - Event_stop is set.\n    - The iterator timeout_backoff runs out.\n\n    Returns:\n        bool: True if the message was acknowledged, False otherwise."
  },
  {
    "code": "def base_list_parser():\n    base_parser = ArgumentParser(add_help=False)\n    base_parser.add_argument(\n        '-F', '--format',\n        action='store',\n        default='default',\n        choices=['csv', 'json', 'yaml', 'default'],\n        help='choose the output format')\n    return base_parser",
    "docstring": "Creates a parser with arguments specific to formatting lists\n    of resources.\n\n    Returns:\n        {ArgumentParser}: Base parser with defaul list args"
  },
  {
    "code": "def _coerce_client_id(client_id):\n    if isinstance(client_id, type(u'')):\n        client_id = client_id.encode('utf-8')\n    if not isinstance(client_id, bytes):\n        raise TypeError('{!r} is not a valid consumer group (must be'\n                        ' str or bytes)'.format(client_id))\n    return client_id",
    "docstring": "Ensure the provided client ID is a byte string. If a text string is\n    provided, it is encoded as UTF-8 bytes.\n\n    :param client_id: :class:`bytes` or :class:`str` instance"
  },
  {
    "code": "def append_query_parameter(url, parameters, ignore_if_exists=True):\n    if ignore_if_exists:\n        for key in parameters.keys():\n            if key + \"=\" in url:\n                del parameters[key]\n    parameters_str = \"&\".join(k + \"=\" + v for k, v in parameters.items())\n    append_token = \"&\" if \"?\" in url else \"?\"\n    return url + append_token + parameters_str",
    "docstring": "quick and dirty appending of query parameters to a url"
  },
  {
    "code": "def fail_eof(self, end_tokens=None, lineno=None):\n        stack = list(self._end_token_stack)\n        if end_tokens is not None:\n            stack.append(end_tokens)\n        return self._fail_ut_eof(None, stack, lineno)",
    "docstring": "Like fail_unknown_tag but for end of template situations."
  },
  {
    "code": "def main():\n    parser = build_command_parser()\n    options = parser.parse_args()\n    file_pointer = options.filename\n    input_format = options.input_format\n    with file_pointer:\n        json_data = json.load(file_pointer)\n    if input_format == SIMPLE_JSON:\n        report = Report(json_data)\n    elif input_format == EXTENDED_JSON:\n        report = Report(\n            json_data.get('messages'),\n            json_data.get('stats'),\n            json_data.get('previous'))\n    print(report.render(), file=options.output)",
    "docstring": "Pylint JSON to HTML Main Entry Point"
  },
  {
    "code": "def watch(self, limit=None, timeout=None):\n        start_time = time.time()\n        count = 0\n        while not timeout or time.time() - start_time < timeout:\n            new = self.read()\n            if new != self.temp:\n                count += 1\n                self.callback(new)\n                if count == limit:\n                    break\n            self.temp = new\n            time.sleep(self.interval)",
    "docstring": "Block method to watch the clipboard changing."
  },
  {
    "code": "def list_cleared_orders(self, bet_status='SETTLED', event_type_ids=None, event_ids=None, market_ids=None,\n                            runner_ids=None, bet_ids=None, customer_order_refs=None, customer_strategy_refs=None,\n                            side=None, settled_date_range=time_range(), group_by=None, include_item_description=None,\n                            locale=None, from_record=None, record_count=None, session=None, lightweight=None):\n        params = clean_locals(locals())\n        method = '%s%s' % (self.URI, 'listClearedOrders')\n        (response, elapsed_time) = self.request(method, params, session)\n        return self.process_response(response, resources.ClearedOrders, elapsed_time, lightweight)",
    "docstring": "Returns a list of settled bets based on the bet status,\n        ordered by settled date.\n\n        :param str bet_status: Restricts the results to the specified status\n        :param list event_type_ids: Optionally restricts the results to the specified Event Type IDs\n        :param list event_ids: Optionally restricts the results to the specified Event IDs\n        :param list market_ids: Optionally restricts the results to the specified market IDs\n        :param list runner_ids: Optionally restricts the results to the specified Runners\n        :param list bet_ids: If you ask for orders, restricts the results to orders with the specified bet IDs\n        :param list customer_order_refs: Optionally restricts the results to the specified customer order references\n        :param list customer_strategy_refs: Optionally restricts the results to the specified customer strategy\n        references\n        :param str side: Optionally restricts the results to the specified side\n        :param dict settled_date_range: Optionally restricts the results to be from/to the specified settled date\n        :param str group_by: How to aggregate the lines, if not supplied then the lowest level is returned\n        :param bool include_item_description: If true then an ItemDescription object is included in the response\n        :param str locale: The language used for the response\n        :param int from_record: Specifies the first record that will be returned\n        :param int record_count: Specifies how many records will be returned from the index position 'fromRecord'\n        :param requests.session session: Requests session object\n        :param bool lightweight: If True will return dict not a resource\n\n        :rtype: resources.ClearedOrders"
  },
  {
    "code": "def validate(self, val):\n        if self.nullable and val is None:\n            return\n        type_er = self.__type_check(val)\n        if type_er:\n            return type_er\n        spec_err = self._specific_validation(val)\n        if spec_err:\n            return spec_err",
    "docstring": "Performs basic validation of field value and then passes it for\n        specific validation.\n\n        :param val: field value to validate\n        :return: error message or None"
  },
  {
    "code": "def add_accounts_to_project(accounts_query, project):\n    query = accounts_query.filter(date_deleted__isnull=True)\n    for account in query:\n        add_account_to_project(account, project)",
    "docstring": "Add accounts to project."
  },
  {
    "code": "def runtime_import(object_path):\n    obj_module, obj_element = object_path.rsplit(\".\", 1)\n    loader = __import__(obj_module, globals(), locals(), [str(obj_element)])\n    return getattr(loader, obj_element)",
    "docstring": "Import at runtime."
  },
  {
    "code": "def slim_stem(token):\n    target_sulfixs = ['ic', 'tic', 'e', 'ive', 'ing', 'ical', 'nal', 'al', 'ism', 'ion', 'ation', 'ar', 'sis', 'us', 'ment']\n    for sulfix in sorted(target_sulfixs, key=len, reverse=True):\n        if token.endswith(sulfix):\n            token = token[0:-len(sulfix)]\n            break\n    if token.endswith('ll'):\n        token = token[:-1]\n    return token",
    "docstring": "A very simple stemmer, for entity of GO stemming.\n\n    >>> token = 'interaction'\n    >>> slim_stem(token)\n    'interact'"
  },
  {
    "code": "def iter_duration(self, iter_trigger):\n        print\n        process_info = ProcessInfo(self.frame_count, use_last_rates=4)\n        start_time = time.time()\n        next_status = start_time + 0.25\n        old_pos = next(iter_trigger)\n        for pos in iter_trigger:\n            duration = pos - old_pos\n            yield duration\n            old_pos = pos\n            if time.time() > next_status:\n                next_status = time.time() + 1\n                self._print_status(process_info)\n        self._print_status(process_info)\n        print",
    "docstring": "yield the duration of two frames in a row."
  },
  {
    "code": "def _ConsumeInteger(tokenizer, is_signed=False, is_long=False):\n  try:\n    result = ParseInteger(tokenizer.token, is_signed=is_signed, is_long=is_long)\n  except ValueError as e:\n    raise tokenizer.ParseError(str(e))\n  tokenizer.NextToken()\n  return result",
    "docstring": "Consumes an integer number from tokenizer.\n\n  Args:\n    tokenizer: A tokenizer used to parse the number.\n    is_signed: True if a signed integer must be parsed.\n    is_long: True if a long integer must be parsed.\n\n  Returns:\n    The integer parsed.\n\n  Raises:\n    ParseError: If an integer with given characteristics couldn't be consumed."
  },
  {
    "code": "def dict_to_nvlist(dict):\r\n    result = []\r\n    for item in list(dict.keys()):\r\n        result.append(SDOPackage.NameValue(item, omniORB.any.to_any(dict[item])))\r\n    return result",
    "docstring": "Convert a dictionary into a CORBA namevalue list."
  },
  {
    "code": "def service_present(name, service_type, description=None,\n                    profile=None, **connection_args):\n    ret = {'name': name,\n           'changes': {},\n           'result': True,\n           'comment': 'Service \"{0}\" already exists'.format(name)}\n    role = __salt__['keystone.service_get'](name=name,\n                                            profile=profile,\n                                            **connection_args)\n    if 'Error' not in role:\n        return ret\n    else:\n        if __opts__.get('test'):\n            ret['result'] = None\n            ret['comment'] = 'Service \"{0}\" will be added'.format(name)\n            return ret\n        __salt__['keystone.service_create'](name, service_type,\n                                            description,\n                                            profile=profile,\n                                            **connection_args)\n        ret['comment'] = 'Service \"{0}\" has been added'.format(name)\n        ret['changes']['Service'] = 'Created'\n    return ret",
    "docstring": "Ensure service present in Keystone catalog\n\n    name\n        The name of the service\n\n    service_type\n        The type of Openstack Service\n\n    description (optional)\n        Description of the service"
  },
  {
    "code": "def yellow(cls):\n        \"Make the text foreground color yellow.\"\n        wAttributes = cls._get_text_attributes()\n        wAttributes &= ~win32.FOREGROUND_MASK\n        wAttributes |=  win32.FOREGROUND_YELLOW\n        cls._set_text_attributes(wAttributes)",
    "docstring": "Make the text foreground color yellow."
  },
  {
    "code": "def OnViewFrozen(self, event):\n        self.grid._view_frozen = not self.grid._view_frozen\n        self.grid.grid_renderer.cell_cache.clear()\n        self.grid.ForceRefresh()\n        event.Skip()",
    "docstring": "Show cells as frozen status"
  },
  {
    "code": "def before(method_name):\n    def decorator(function):\n        @wraps(function)\n        def wrapper(self, *args, **kwargs):\n            returns = getattr(self, method_name)(*args, **kwargs)\n            if returns is None:\n                return function(self, *args, **kwargs)\n            else:\n                if isinstance(returns, HttpResponse):\n                    return returns\n                else:\n                    return function(self, *returns)\n        return wrapper\n    return decorator",
    "docstring": "Run the given method prior to the decorated view.\n\n    If you return anything besides ``None`` from the given method,\n    its return values will replace the arguments of the decorated\n    view.\n\n    If you return an instance of ``HttpResponse`` from the given method,\n    Respite will return it immediately without delegating the request to the\n    decorated view.\n\n    Example usage::\n\n        class ArticleViews(Views):\n\n            @before('_load')\n            def show(self, request, article):\n                return self._render(\n                    request = request,\n                    template = 'show',\n                    context = {\n                        'article': article\n                    }\n                )\n\n            def _load(self, request, id):\n                try:\n                    return request, Article.objects.get(id=id)\n                except Article.DoesNotExist:\n                    return self._error(request, 404, message='The article could not be found.')\n\n    :param method: A string describing a class method."
  },
  {
    "code": "def get_bool(self, property):\n        value = self.get(property)\n        if isinstance(value, bool):\n            return value\n        return value.lower() == \"true\"",
    "docstring": "Gets the value of the given property as boolean.\n\n        :param property: (:class:`~hazelcast.config.ClientProperty`), Property to get value from\n        :return: (bool), Value of the given property"
  },
  {
    "code": "def _is_wildcard_match(self, domain_labels, valid_domain_labels):\n        first_domain_label = domain_labels[0]\n        other_domain_labels = domain_labels[1:]\n        wildcard_label = valid_domain_labels[0]\n        other_valid_domain_labels = valid_domain_labels[1:]\n        if other_domain_labels != other_valid_domain_labels:\n            return False\n        if wildcard_label == '*':\n            return True\n        wildcard_regex = re.compile('^' + wildcard_label.replace('*', '.*') + '$')\n        if wildcard_regex.match(first_domain_label):\n            return True\n        return False",
    "docstring": "Determines if the labels in a domain are a match for labels from a\n        wildcard valid domain name\n\n        :param domain_labels:\n            A list of unicode strings, with A-label form for IDNs, of the labels\n            in the domain name to check\n\n        :param valid_domain_labels:\n            A list of unicode strings, with A-label form for IDNs, of the labels\n            in a wildcard domain pattern\n\n        :return:\n            A boolean - if the domain matches the valid domain"
  },
  {
    "code": "def _list_dir(self, path):\n        try:\n            elements = [\n                os.path.join(path, x) for x in os.listdir(path)\n            ] if os.path.isdir(path) else []\n            elements.sort()\n        except OSError:\n            elements = None\n        return elements",
    "docstring": "returns absolute paths for all entries in a directory"
  },
  {
    "code": "def install_dependencies(dependencies, verbose=False):\n    if not dependencies:\n        return\n    stdout = stderr = None if verbose else subprocess.DEVNULL\n    with tempfile.TemporaryDirectory() as req_dir:\n        req_file = Path(req_dir) / \"requirements.txt\"\n        with open(req_file, \"w\") as f:\n            for dependency in dependencies:\n                f.write(f\"{dependency}\\n\")\n        pip = [\"python3\", \"-m\", \"pip\", \"install\", \"-r\", req_file]\n        if sys.base_prefix == sys.prefix and not hasattr(sys, \"real_prefix\"):\n            pip.append(\"--user\")\n        try:\n            subprocess.check_call(pip, stdout=stdout, stderr=stderr)\n        except subprocess.CalledProcessError:\n            raise Error(_(\"failed to install dependencies\"))\n        importlib.reload(site)",
    "docstring": "Install all packages in dependency list via pip."
  },
  {
    "code": "def _create(self, **kwargs):\n        tmos_ver = self._meta_data['bigip']._meta_data['tmos_version']\n        legacy = kwargs.pop('legacy', False)\n        publish = kwargs.pop('publish', False)\n        self._filter_version_specific_options(tmos_ver, **kwargs)\n        if LooseVersion(tmos_ver) < LooseVersion('12.1.0'):\n            return super(Policy, self)._create(**kwargs)\n        else:\n            if legacy:\n                return super(Policy, self)._create(legacy=True, **kwargs)\n            else:\n                if 'subPath' not in kwargs:\n                    msg = \"The keyword 'subPath' must be specified when \" \\\n                        \"creating draft policy in TMOS versions >= 12.1.0. \" \\\n                        \"Try and specify subPath as 'Drafts'.\"\n                    raise MissingRequiredCreationParameter(msg)\n                self = super(Policy, self)._create(**kwargs)\n                if publish:\n                    self.publish()\n                return self",
    "docstring": "Allow creation of draft policy and ability to publish a draft\n\n        Draft policies only exist in 12.1.0 and greater versions of TMOS.\n        But there must be a method to create a draft, then publish it.\n\n        :raises: MissingRequiredCreationParameter"
  },
  {
    "code": "def ensure_unicode_args(function):\n    @wraps(function)\n    def wrapped(*args, **kwargs):\n        if six.PY2:\n            return function(\n                *salt.utils.data.decode_list(args),\n                **salt.utils.data.decode_dict(kwargs)\n            )\n        else:\n            return function(*args, **kwargs)\n    return wrapped",
    "docstring": "Decodes all arguments passed to the wrapped function"
  },
  {
    "code": "def default_output_name(self, input_file):\n        irom_segment = self.get_irom_segment()\n        if irom_segment is not None:\n            irom_offs = irom_segment.addr - ESP8266ROM.IROM_MAP_START\n        else:\n            irom_offs = 0\n        return \"%s-0x%05x.bin\" % (os.path.splitext(input_file)[0],\n                                  irom_offs & ~(ESPLoader.FLASH_SECTOR_SIZE - 1))",
    "docstring": "Derive a default output name from the ELF name."
  },
  {
    "code": "def determineMaxWindowSize(dtype, limit=None):\n\tvmem = psutil.virtual_memory()\n\tmaxSize = math.floor(math.sqrt(vmem.available / np.dtype(dtype).itemsize))\n\tif limit is None or limit >= maxSize:\n\t\treturn maxSize\n\telse:\n\t\treturn limit",
    "docstring": "Determines the largest square window size that can be used, based on\n\tthe specified datatype and amount of currently available system memory.\n\t\n\tIf `limit` is specified, then this value will be returned in the event\n\tthat it is smaller than the maximum computed size."
  },
  {
    "code": "def moys_dict(self):\n        moy_dict = {}\n        for val, dt in zip(self.values, self.datetimes):\n            moy_dict[dt.moy] = val\n        return moy_dict",
    "docstring": "Return a dictionary of this collection's values where the keys are the moys.\n\n        This is useful for aligning the values with another list of datetimes."
  },
  {
    "code": "def handle(self, connection_id, message_content):\n        if self._network.get_connection_status(connection_id) != \\\n                ConnectionStatus.CONNECTION_REQUEST:\n            LOGGER.debug(\"Connection's previous message was not a\"\n                         \" ConnectionRequest, Remove connection to %s\",\n                         connection_id)\n            violation = AuthorizationViolation(\n                violation=RoleType.Value(\"NETWORK\"))\n            return HandlerResult(\n                HandlerStatus.RETURN_AND_CLOSE,\n                message_out=violation,\n                message_type=validator_pb2.Message\n                .AUTHORIZATION_VIOLATION)\n        random_payload = os.urandom(PAYLOAD_LENGTH)\n        self._challenge_payload_cache[connection_id] = random_payload\n        auth_challenge_response = AuthorizationChallengeResponse(\n            payload=random_payload)\n        self._network.update_connection_status(\n            connection_id,\n            ConnectionStatus.AUTH_CHALLENGE_REQUEST)\n        return HandlerResult(\n            HandlerStatus.RETURN,\n            message_out=auth_challenge_response,\n            message_type=validator_pb2.Message.\n            AUTHORIZATION_CHALLENGE_RESPONSE)",
    "docstring": "If the connection wants to take on a role that requires a challenge to\n        be signed, it will request the challenge by sending an\n        AuthorizationChallengeRequest to the validator it wishes to connect to.\n        The validator will send back a random payload that must be signed.\n        If the connection has not sent a ConnectionRequest or the connection\n        has already recieved an AuthorizationChallengeResponse, an\n        AuthorizationViolation will be returned and the connection will be\n        closed."
  },
  {
    "code": "def read_file(file_path_name):\n    with io.open(os.path.join(os.path.dirname(__file__), file_path_name), mode='rt', encoding='utf-8') as fd:\n        return fd.read()",
    "docstring": "Read the content of the specified file.\n\n\n    @param file_path_name: path and name of the file to read.\n\n\n    @return: content of the specified file."
  },
  {
    "code": "def _format_state_result(name, result, changes=None, comment=''):\n    if changes is None:\n        changes = {'old': '', 'new': ''}\n    return {'name': name, 'result': result,\n            'changes': changes, 'comment': comment}",
    "docstring": "Creates the state result dictionary."
  },
  {
    "code": "def autodoc_skip(app, what, name, obj, skip, options):\n    if name in config.EXCLUDE_MEMBERS:\n        return True\n    if name in config.INCLUDE_MEMBERS:\n        return False\n    return skip",
    "docstring": "Hook that tells autodoc to include or exclude certain fields.\n\n    Sadly, it doesn't give a reference to the parent object,\n    so only the ``name`` can be used for referencing.\n\n    :type app: sphinx.application.Sphinx\n    :param what: The parent type, ``class`` or ``module``\n    :type what: str\n    :param name: The name of the child method/attribute.\n    :type name: str\n    :param obj: The child value (e.g. a method, dict, or module reference)\n    :param options: The current autodoc settings.\n    :type options: dict\n\n    .. seealso:: http://www.sphinx-doc.org/en/stable/ext/autodoc.html#event-autodoc-skip-member"
  },
  {
    "code": "def cli(wio, send):\n    command = send\n    click.echo(\"UDP command: {}\".format(command))\n    result = udp.common_send(command)\n    if result is None:\n        return debug_error()\n    else:\n        click.echo(result)",
    "docstring": "Sends a UDP command to the wio device.\n\n    \\b\n    DOES:\n        Support \"VERSION\", \"SCAN\", \"Blank?\", \"DEBUG\", \"ENDEBUG: 1\", \"ENDEBUG: 0\"\n        \"APCFG: AP\\\\tPWDs\\\\tTOKENs\\\\tSNs\\\\tSERVER_Domains\\\\tXSERVER_Domain\\\\t\\\\r\\\\n\",\n        Note:\n        1. Ensure your device is Configure Mode.\n        2. Change your computer network to Wio's AP.\n\n    \\b\n    EXAMPLE:\n        wio udp --send [command], send UPD command"
  },
  {
    "code": "def now_micros(absolute=False) -> int:\n  micros = int(time.time() * 1e6)\n  if absolute:\n    return micros\n  return micros - EPOCH_MICROS",
    "docstring": "Return current micros since epoch as integer."
  },
  {
    "code": "def serialize_options(options, block):\n    for index, option_dict in enumerate(block.options):\n        option = etree.SubElement(options, 'option')\n        if index == block.correct_answer:\n            option.set('correct', u'True')\n            if hasattr(block, 'correct_rationale'):\n                rationale = etree.SubElement(option, 'rationale')\n                rationale.text = block.correct_rationale['text']\n        text = etree.SubElement(option, 'text')\n        text.text = option_dict.get('text', '')\n        serialize_image(option_dict, option)",
    "docstring": "Serialize the options in peer instruction XBlock to xml\n\n    Args:\n        options (lxml.etree.Element): The <options> XML element.\n        block (PeerInstructionXBlock): The XBlock with configuration to serialize.\n\n    Returns:\n        None"
  },
  {
    "code": "def create_typed_target (self, type, project, name, sources, requirements, default_build, usage_requirements):\n        assert isinstance(type, basestring)\n        assert isinstance(project, ProjectTarget)\n        assert is_iterable_typed(sources, basestring)\n        assert is_iterable_typed(requirements, basestring)\n        assert is_iterable_typed(default_build, basestring)\n        return self.main_target_alternative (TypedTarget (name, project, type,\n            self.main_target_sources (sources, name),\n            self.main_target_requirements (requirements, project),\n            self.main_target_default_build (default_build, project),\n            self.main_target_usage_requirements (usage_requirements, project)))",
    "docstring": "Creates a TypedTarget with the specified properties.\n            The 'name', 'sources', 'requirements', 'default_build' and\n            'usage_requirements' are assumed to be in the form specified\n            by the user in Jamfile corresponding to 'project'."
  },
  {
    "code": "def batch_put_attributes(self, items, replace=True):\n        return self.connection.batch_put_attributes(self, items, replace)",
    "docstring": "Store attributes for multiple items.\n\n        :type items: dict or dict-like object\n        :param items: A dictionary-like object.  The keys of the dictionary are\n                      the item names and the values are themselves dictionaries\n                      of attribute names/values, exactly the same as the\n                      attribute_names parameter of the scalar put_attributes\n                      call.\n\n        :type replace: bool\n        :param replace: Whether the attribute values passed in will replace\n                        existing values or will be added as addition values.\n                        Defaults to True.\n\n        :rtype: bool\n        :return: True if successful"
  },
  {
    "code": "def _get_known_noncoding_het_snp(data_dict):\n        if data_dict['gene'] == '1':\n            return None\n        if data_dict['known_var'] == '1' and data_dict['ref_ctg_effect'] == 'SNP' \\\n          and data_dict['smtls_nts'] != '.' and ';' not in data_dict['smtls_nts']:\n            nucleotides = data_dict['smtls_nts'].split(',')\n            depths = data_dict['smtls_nts_depth'].split(',')\n            if len(nucleotides) != len(depths):\n                raise Error('Mismatch in number of inferred nucleotides from ctg_nt, smtls_nts, smtls_nts_depth columns. Cannot continue\\n' + str(data_dict))\n            try:\n                var_nucleotide = data_dict['known_var_change'][-1]\n                depths = [int(x) for x in depths]\n                nuc_to_depth = dict(zip(nucleotides, depths))\n                total_depth = sum(depths)\n                var_depth = nuc_to_depth.get(var_nucleotide, 0)\n                percent_depth = round(100 * var_depth / total_depth, 1)\n            except:\n                return None\n            return data_dict['known_var_change'], percent_depth\n        else:\n            return None",
    "docstring": "If ref is coding, return None. If the data dict has a known snp, and\n           samtools made a call, then return the string ref_name_change and the\n           % of reads supporting the variant type. If noncoding, but no\n           samtools call, then return None"
  },
  {
    "code": "def collectData(reads1, reads2, square, matchAmbiguous):\n    result = defaultdict(dict)\n    for id1, read1 in reads1.items():\n        for id2, read2 in reads2.items():\n            if id1 != id2 or not square:\n                match = compareDNAReads(\n                    read1, read2, matchAmbiguous=matchAmbiguous)['match']\n                if not matchAmbiguous:\n                    assert match['ambiguousMatchCount'] == 0\n                result[id1][id2] = result[id2][id1] = match\n    return result",
    "docstring": "Get pairwise matching statistics for two sets of reads.\n\n    @param reads1: An C{OrderedDict} of C{str} read ids whose values are\n        C{Read} instances. These will be the rows of the table.\n    @param reads2: An C{OrderedDict} of C{str} read ids whose values are\n        C{Read} instances. These will be the columns of the table.\n    @param square: If C{True} we are making a square table of a set of\n        sequences against themselves (in which case we show nothing on the\n        diagonal).\n    @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are\n        possibly correct as actually being correct. Otherwise, we are strict\n        and insist that only non-ambiguous nucleotides can contribute to the\n        matching nucleotide count."
  },
  {
    "code": "def vector_norm(data, axis=None, out=None):\n    data = np.array(data, dtype=np.float64, copy=True)\n    if out is None:\n        if data.ndim == 1:\n            return math.sqrt(np.dot(data, data))\n        data *= data\n        out = np.atleast_1d(np.sum(data, axis=axis))\n        np.sqrt(out, out)\n        return out\n    else:\n        data *= data\n        np.sum(data, axis=axis, out=out)\n        np.sqrt(out, out)",
    "docstring": "Return length, i.e. Euclidean norm, of ndarray along axis.\n\n    >>> v = np.random.random(3)\n    >>> n = vector_norm(v)\n    >>> np.allclose(n, np.linalg.norm(v))\n    True\n    >>> v = np.random.rand(6, 5, 3)\n    >>> n = vector_norm(v, axis=-1)\n    >>> np.allclose(n, np.sqrt(np.sum(v*v, axis=2)))\n    True\n    >>> n = vector_norm(v, axis=1)\n    >>> np.allclose(n, np.sqrt(np.sum(v*v, axis=1)))\n    True\n    >>> v = np.random.rand(5, 4, 3)\n    >>> n = np.empty((5, 3))\n    >>> vector_norm(v, axis=1, out=n)\n    >>> np.allclose(n, np.sqrt(np.sum(v*v, axis=1)))\n    True\n    >>> vector_norm([])\n    0.0\n    >>> vector_norm([1])\n    1.0"
  },
  {
    "code": "def hdc_disk_interface(self, hdc_disk_interface):\n        self._hdc_disk_interface = hdc_disk_interface\n        log.info('QEMU VM \"{name}\" [{id}] has set the QEMU hdc disk interface to {interface}'.format(name=self._name,\n                                                                                                     id=self._id,\n                                                                                                     interface=self._hdc_disk_interface))",
    "docstring": "Sets the hdc disk interface for this QEMU VM.\n\n        :param hdc_disk_interface: QEMU hdc disk interface"
  },
  {
    "code": "def switchport(self, **kwargs):\n        int_type = kwargs.pop('int_type').lower()\n        name = kwargs.pop('name')\n        enabled = kwargs.pop('enabled', True)\n        callback = kwargs.pop('callback', self._callback)\n        int_types = ['gigabitethernet', 'tengigabitethernet',\n                     'fortygigabitethernet', 'hundredgigabitethernet',\n                     'port_channel', 'vlan']\n        if int_type not in int_types:\n            raise ValueError(\"`int_type` must be one of: %s\" % repr(int_types))\n        if not pynos.utilities.valid_interface(int_type, name):\n            raise ValueError('`name` must be in the format of x/y/z for '\n                             'physical interfaces or x for port channel.')\n        switchport_args = dict(name=name)\n        switchport = getattr(self._interface,\n                             'interface_%s_switchport_basic_basic' % int_type)\n        config = switchport(**switchport_args)\n        if not enabled:\n            config.find('.//*switchport-basic').set('operation', 'delete')\n        if kwargs.pop('get', False):\n            return callback(config, handler='get_config')\n        else:\n            return callback(config)",
    "docstring": "Set interface switchport status.\n\n        Args:\n            int_type (str): Type of interface. (gigabitethernet,\n                tengigabitethernet, etc)\n            name (str): Name of interface. (1/0/5, 1/0/10, etc)\n            enabled (bool): Is the interface enabled? (True, False)\n            get (bool): Get config instead of editing config. (True, False)\n            callback (function): A function executed upon completion of the\n                method.  The only parameter passed to `callback` will be the\n                ``ElementTree`` `config`.\n\n        Returns:\n            Return value of `callback`.\n\n        Raises:\n            KeyError: if `int_type` or `name` is not specified.\n            ValueError: if `name` or `int_type` is not a valid\n                value.\n\n        Examples:\n            >>> import pynos.device\n            >>> switches = ['10.24.39.211', '10.24.39.203']\n            >>> auth = ('admin', 'password')\n            >>> for switch in switches:\n            ...     conn = (switch, '22')\n            ...     with pynos.device.Device(conn=conn, auth=auth) as dev:\n            ...         output = dev.interface.switchport(name='225/0/19',\n            ...         int_type='tengigabitethernet')\n            ...         output = dev.interface.switchport(name='225/0/19',\n            ...         int_type='tengigabitethernet', enabled=False)\n            ...         dev.interface.switchport()\n            ...         # doctest: +IGNORE_EXCEPTION_DETAIL\n            Traceback (most recent call last):\n            KeyError"
  },
  {
    "code": "def get_true_false_both(query_params, field_name, default):\n    valid = ('true', 'false', 'both')\n    value = query_params.get(field_name, default).lower()\n    if value in valid:\n        return value\n    v = ', '.join(sorted(valid))\n    raise serializers.ValidationError({\n        field_name: ['Must be one of [%s]' % v],\n    })",
    "docstring": "Tries to get and return a valid of true, false, or both from the field\n    name in the query string, raises a ValidationError for invalid values."
  },
  {
    "code": "def installStatsLoop(statsFile, statsDelay):\n  def dumpStats():\n    scales.dumpStatsTo(statsFile)\n    reactor.callLater(statsDelay, dumpStats)\n  def startStats():\n    reactor.callLater(statsDelay, dumpStats)\n  reactor.callWhenRunning(startStats)",
    "docstring": "Installs an interval loop that dumps stats to a file."
  },
  {
    "code": "def add_customers(self, service_desk_id, list_of_usernames):\n        url = 'rest/servicedeskapi/servicedesk/{}/customer'.format(service_desk_id)\n        data = {'usernames': list_of_usernames}\n        return self.post(url, headers=self.experimental_headers, data=data)",
    "docstring": "Adds one or more existing customers to the given service desk.\n        If you need to create a customer, see Create customer method.\n\n        Administer project permission is required, or agents if public signups\n        and invites are enabled for the Service Desk project.\n\n        :param service_desk_id: str\n        :param list_of_usernames: list\n        :return: the customers added to the service desk"
  },
  {
    "code": "def allRnaQuantifications(self):\n        for dataset in self.getDatasets():\n            for rnaQuantificationSet in dataset.getRnaQuantificationSets():\n                for rnaQuantification in \\\n                        rnaQuantificationSet.getRnaQuantifications():\n                    yield rnaQuantification",
    "docstring": "Return an iterator over all rna quantifications"
  },
  {
    "code": "def wait_for_job(self, job, interval=5, timeout=60):\n        complete = False\n        job_id = str(job if isinstance(job,\n                                       (six.binary_type, six.text_type, int))\n                     else job['jobReference']['jobId'])\n        job_resource = None\n        start_time = time()\n        elapsed_time = 0\n        while not (complete or elapsed_time > timeout):\n            sleep(interval)\n            request = self.bigquery.jobs().get(projectId=self.project_id,\n                                               jobId=job_id)\n            job_resource = request.execute(num_retries=self.num_retries)\n            self._raise_executing_exception_if_error(job_resource)\n            complete = job_resource.get('status').get('state') == u'DONE'\n            elapsed_time = time() - start_time\n        if not complete:\n            logger.error('BigQuery job %s timeout' % job_id)\n            raise BigQueryTimeoutException()\n        return job_resource",
    "docstring": "Waits until the job indicated by job_resource is done or has failed\n\n        Parameters\n        ----------\n        job : Union[dict, str]\n            ``dict`` representing a BigQuery job resource, or a ``str``\n            representing the BigQuery job id\n        interval : float, optional\n            Polling interval in seconds, default = 5\n        timeout : float, optional\n            Timeout in seconds, default = 60\n\n        Returns\n        -------\n        dict\n            Final state of the job resouce, as described here:\n            https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/python/latest/bigquery_v2.jobs.html#get\n\n        Raises\n        ------\n        Union[JobExecutingException, BigQueryTimeoutException]\n            On http/auth failures or timeout"
  },
  {
    "code": "def avail(search=None, verbose=False):\n    ret = {}\n    cmd = 'imgadm avail -j'\n    res = __salt__['cmd.run_all'](cmd)\n    retcode = res['retcode']\n    if retcode != 0:\n        ret['Error'] = _exit_status(retcode)\n        return ret\n    for image in salt.utils.json.loads(res['stdout']):\n        if image['manifest']['disabled'] or not image['manifest']['public']:\n            continue\n        if search and search not in image['manifest']['name']:\n            continue\n        uuid = image['manifest']['uuid']\n        data = _parse_image_meta(image, verbose)\n        if data:\n            ret[uuid] = data\n    return ret",
    "docstring": "Return a list of available images\n\n    search : string\n        search keyword\n    verbose : boolean (False)\n        toggle verbose output\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' imgadm.avail [percona]\n        salt '*' imgadm.avail verbose=True"
  },
  {
    "code": "def get_cached_token(self):\n        token_info = None\n        if self.cache_path:\n            try:\n                f = open(self.cache_path)\n                token_info_string = f.read()\n                f.close()\n                token_info = json.loads(token_info_string)\n                if self.is_token_expired(token_info):\n                    token_info = self.refresh_access_token(token_info['refresh_token'])\n            except IOError:\n                pass\n        return token_info",
    "docstring": "Gets a cached auth token"
  },
  {
    "code": "def verify(self, dataset, publication_date, source, refernce_url):\r\n        path = '/api/1.0/meta/verifydataset'\r\n        req = definition.DatasetVerifyRequest(dataset, publication_date, source, refernce_url)\r\n        result = self._api_post(definition.DatasetVerifyResponse, path, req)\r\n        if result.status == 'failed':\r\n            ver_err = '\\r\\n'.join(result.errors)\r\n            msg = 'Dataset has not been verified, because of the following error(s): {}'.format(ver_err)\r\n            raise ValueError(msg)",
    "docstring": "The method is verifying dataset by it's id"
  },
  {
    "code": "def spin_z_op(param, oper):\n    slaves = param['slaves']\n    oper['Sz'] = np.array([spin_z(slaves, spin) for spin in range(slaves)])\n    oper['Sz+1/2'] = oper['Sz'] + 0.5*np.eye(2**slaves)\n    oper['sumSz2'] = oper['Sz'].sum(axis=0)**2\n    Sz_mat_shape = oper['Sz'].reshape(param['orbitals'], 2, 2**slaves, 2**slaves)\n    oper['sumSz-sp2'] = (Sz_mat_shape.sum(axis=1)**2).sum(axis=0)\n    oper['sumSz-or2'] = (Sz_mat_shape.sum(axis=0)**2).sum(axis=0)",
    "docstring": "Generates the required Sz operators, given the system parameter setup\n       and the operator dictionary"
  },
  {
    "code": "def history(self):\n        if self.changeset is None:\n            raise NodeError('Unable to get changeset for this FileNode')\n        return self.changeset.get_file_history(self.path)",
    "docstring": "Returns a list of changeset for this file in which the file was changed"
  },
  {
    "code": "def add_url(self, post_data):\n        img_desc = post_data['desc']\n        img_path = post_data['file1']\n        cur_uid = tools.get_uudd(4)\n        while MEntity.get_by_uid(cur_uid):\n            cur_uid = tools.get_uudd(4)\n        MEntity.create_entity(cur_uid, img_path, img_desc, kind=post_data['kind'] if 'kind' in post_data else '3')\n        kwd = {\n            'kind': post_data['kind'] if 'kind' in post_data else '3',\n        }\n        self.render('misc/entity/entity_view.html',\n                    filename=img_path,\n                    cfg=config.CMS_CFG,\n                    kwd=kwd,\n                    userinfo=self.userinfo)",
    "docstring": "Adding the URL as entity."
  },
  {
    "code": "def GetMethodConfig(self, method):\n        method_config = self._method_configs.get(method)\n        if method_config:\n            return method_config\n        func = getattr(self, method, None)\n        if func is None:\n            raise KeyError(method)\n        method_config = getattr(func, 'method_config', None)\n        if method_config is None:\n            raise KeyError(method)\n        self._method_configs[method] = config = method_config()\n        return config",
    "docstring": "Returns service cached method config for given method."
  },
  {
    "code": "def _backward_delete_char(text, pos):\n    if pos == 0:\n        return text, pos\n    return text[:pos - 1] + text[pos:], pos - 1",
    "docstring": "Delete the character behind pos."
  },
  {
    "code": "def _frank_help(alpha, tau):\n        def debye(t):\n            return t / (np.exp(t) - 1)\n        debye_value = integrate.quad(debye, EPSILON, alpha)[0] / alpha\n        return 4 * (debye_value - 1) / alpha + 1 - tau",
    "docstring": "Compute first order debye function to estimate theta."
  },
  {
    "code": "def recv(request_context=None, non_blocking=False):\n    if non_blocking:\n        result = uwsgi.websocket_recv_nb(request_context)\n    else:\n        result = uwsgi.websocket_recv(request_context)\n    return result",
    "docstring": "Receives data from websocket.\n\n    :param request_context:\n\n    :param bool non_blocking:\n\n    :rtype: bytes|str\n\n    :raises IOError: If unable to receive a message."
  },
  {
    "code": "def CreateApproval(self,\n                     reason=None,\n                     notified_users=None,\n                     email_cc_addresses=None):\n    if not reason:\n      raise ValueError(\"reason can't be empty\")\n    if not notified_users:\n      raise ValueError(\"notified_users list can't be empty.\")\n    approval = user_pb2.ApiHuntApproval(\n        reason=reason,\n        notified_users=notified_users,\n        email_cc_addresses=email_cc_addresses or [])\n    args = user_pb2.ApiCreateHuntApprovalArgs(\n        hunt_id=self.hunt_id, approval=approval)\n    data = self._context.SendRequest(\"CreateHuntApproval\", args)\n    return HuntApproval(\n        data=data, username=self._context.username, context=self._context)",
    "docstring": "Create a new approval for the current user to access this hunt."
  },
  {
    "code": "def signature(cls):\n    snake_scope = cls.options_scope.replace('-', '_')\n    partial_construct_optionable = functools.partial(_construct_optionable, cls)\n    partial_construct_optionable.__name__ = 'construct_scope_{}'.format(snake_scope)\n    return dict(\n        output_type=cls.optionable_cls,\n        input_selectors=tuple(),\n        func=partial_construct_optionable,\n        input_gets=(Get.create_statically_for_rule_graph(ScopedOptions, Scope),),\n        dependency_optionables=(cls.optionable_cls,),\n      )",
    "docstring": "Returns kwargs to construct a `TaskRule` that will construct the target Optionable.\n\n    TODO: This indirection avoids a cycle between this module and the `rules` module."
  },
  {
    "code": "def findLabel(self, query, create=False):\n        if isinstance(query, six.string_types):\n            query = query.lower()\n        for label in self._labels.values():\n            if (isinstance(query, six.string_types) and query == label.name.lower()) or \\\n                (isinstance(query, Pattern) and query.search(label.name)):\n                return label\n        return self.createLabel(query) if create and isinstance(query, six.string_types) else None",
    "docstring": "Find a label with the given name.\n\n        Args:\n            name (Union[_sre.SRE_Pattern, str]): A str or regular expression to match against the name.\n            create (bool): Whether to create the label if it doesn't exist (only if name is a str).\n\n        Returns:\n            Union[gkeepapi.node.Label, None]: The label."
  },
  {
    "code": "def _in_list(self, original_list, item):\n        for item_list in original_list:\n            if item is item_list:\n                return True\n        return False",
    "docstring": "Check that an item as contained in a list.\n\n        :param original_list: The list.\n        :type original_list: list(object)\n        :param item: The item.\n        :type item: hatemile.util.html.htmldomelement.HTMLDOMElement\n        :return: True if the item contained in the list or False if not.\n        :rtype: bool"
  },
  {
    "code": "def _GetTempOutputFileHandles(self, value_type):\n    try:\n      return self.temp_output_trackers[value_type], False\n    except KeyError:\n      return self._CreateOutputFileHandles(value_type), True",
    "docstring": "Returns the tracker for a given value type."
  },
  {
    "code": "def handle_new_user(self, provider, access, info):\n        \"Create a shell auth.User and redirect.\"\n        user = self.get_or_create_user(provider, access, info)\n        access.user = user\n        AccountAccess.objects.filter(pk=access.pk).update(user=user)\n        user = authenticate(provider=access.provider, identifier=access.identifier)\n        login(self.request, user)\n        return redirect(self.get_login_redirect(provider, user, access, True))",
    "docstring": "Create a shell auth.User and redirect."
  },
  {
    "code": "def object_upload(self, bucket, key, content, content_type):\n    args = {'uploadType': 'media', 'name': key}\n    headers = {'Content-Type': content_type}\n    url = Api._UPLOAD_ENDPOINT + (Api._OBJECT_PATH % (bucket, ''))\n    return google.datalab.utils.Http.request(url, args=args, data=content, headers=headers,\n                                             credentials=self._credentials, raw_response=True)",
    "docstring": "Writes text content to the object.\n\n    Args:\n      bucket: the name of the bucket containing the object.\n      key: the key of the object to be written.\n      content: the text content to be written.\n      content_type: the type of text content.\n    Raises:\n      Exception if the object could not be written to."
  },
  {
    "code": "def on_click(self, event):\n        button = event[\"button\"]\n        if button == self.button_pause:\n            if self.state == \"STOP\":\n                self.py3.command_run(\"mocp --play\")\n            else:\n                self.py3.command_run(\"mocp --toggle-pause\")\n        elif button == self.button_stop:\n            self.py3.command_run(\"mocp --stop\")\n        elif button == self.button_next:\n            self.py3.command_run(\"mocp --next\")\n        elif button == self.button_previous:\n            self.py3.command_run(\"mocp --prev\")\n        else:\n            self.py3.prevent_refresh()",
    "docstring": "Control moc with mouse clicks."
  },
  {
    "code": "def _process_binary_trigger(trigger_value, condition):\n    ops = {\n        0: \">\",\n        1: \"<\",\n        2: \">=\",\n        3: \"<=\",\n        4: \"==\",\n        5: 'always'\n    }\n    sources = {\n        0: 'value',\n        1: 'count'\n    }\n    encoded_source = condition & 0b1\n    encoded_op = condition >> 1\n    oper = ops.get(encoded_op, None)\n    source = sources.get(encoded_source, None)\n    if oper is None:\n        raise ArgumentError(\"Unknown operation in binary trigger\", condition=condition, operation=encoded_op, known_ops=ops)\n    if source is None:\n        raise ArgumentError(\"Unknown value source in binary trigger\", source=source, known_sources=sources)\n    if oper == 'always':\n        return TrueTrigger()\n    return InputTrigger(source, oper, trigger_value)",
    "docstring": "Create an InputTrigger object."
  },
  {
    "code": "def _days_in_month(date):\n    if date.month == 12:\n        reference = type(date)(date.year + 1, 1, 1)\n    else:\n        reference = type(date)(date.year, date.month + 1, 1)\n    return (reference - timedelta(days=1)).day",
    "docstring": "The number of days in the month of the given date"
  },
  {
    "code": "def __run_post_all(self):\n        for d in self.dirs:\n            post_all_py_path = os.path.join(d, 'post-all.py')\n            if os.path.isfile(post_all_py_path):\n                print('     Applying post-all.py...', end=' ')\n                self.__run_py_file(post_all_py_path, 'post-all')\n                print('OK')\n            post_all_sql_path = os.path.join(d, 'post-all.sql')\n            if os.path.isfile(post_all_sql_path):\n                print('     Applying post-all.sql...', end=' ')\n                self.__run_sql_file(post_all_sql_path)\n                print('OK')",
    "docstring": "Execute the post-all.py and post-all.sql files if they exist"
  },
  {
    "code": "def OnSpellCheckToggle(self, event):\n        spelltoolid = self.main_window.main_toolbar.label2id[\"CheckSpelling\"]\n        self.main_window.main_toolbar.ToggleTool(spelltoolid,\n                                                 not config[\"check_spelling\"])\n        config[\"check_spelling\"] = repr(not config[\"check_spelling\"])\n        self.main_window.grid.grid_renderer.cell_cache.clear()\n        self.main_window.grid.ForceRefresh()",
    "docstring": "Spell checking toggle event handler"
  },
  {
    "code": "def install_dependencies(plugins_directory, ostream=sys.stdout):\n    plugin_directories = plugins_directory.realpath().dirs()\n    print >> ostream, 50 * '*'\n    print >> ostream, 'Processing plugins:'\n    print >> ostream, '\\n'.join(['  - {}'.format(p)\n                                    for p in plugin_directories])\n    print >> ostream, '\\n' + 50 * '-' + '\\n'\n    for plugin_dir_i in plugin_directories:\n        try:\n            on_plugin_install(plugin_dir_i, ostream=ostream)\n        except RuntimeError, exception:\n            print exception\n        print >> ostream, '\\n' + 50 * '-' + '\\n'",
    "docstring": "Run ``on_plugin_install`` script for each plugin directory found in\n    specified plugins directory.\n\n    Parameters\n    ----------\n    plugins_directory : str\n        File system path to directory containing zero or more plugin\n        subdirectories.\n    ostream : file-like\n        Output stream for status messages (default: ``sys.stdout``)."
  },
  {
    "code": "def get_term_by_year_and_quarter(year, quarter):\n    url = \"{}/{},{}.json\".format(\n        term_res_url_prefix, year, quarter.lower())\n    return _json_to_term_model(get_resource(url))",
    "docstring": "Returns a uw_sws.models.Term object,\n    for the passed year and quarter."
  },
  {
    "code": "def parse_net_kwargs(kwargs):\n    if not kwargs:\n        return kwargs\n    resolved = {}\n    for k, v in kwargs.items():\n        resolved[k] = _resolve_dotted_name(v)\n    return resolved",
    "docstring": "Parse arguments for the estimator.\n\n    Resolves dotted names and instantiated classes.\n\n    Examples\n    --------\n    >>> kwargs = {'lr': 0.1, 'module__nonlin': 'torch.nn.Hardtanh(-2, max_val=3)'}\n    >>> parse_net_kwargs(kwargs)\n    {'lr': 0.1, 'module__nonlin': Hardtanh(min_val=-2, max_val=3)}"
  },
  {
    "code": "def get_table_width(self):\n        if self.column_count == 0:\n            return 0\n        width = sum(self._column_widths)\n        width += ((self._column_count - 1)\n                  * termwidth(self.column_separator_char))\n        width += termwidth(self.left_border_char)\n        width += termwidth(self.right_border_char)\n        return width",
    "docstring": "Get the width of the table as number of characters.\n\n        Column width should be set prior to calling this method.\n\n        Returns\n        -------\n        int\n            Width of the table as number of characters."
  },
  {
    "code": "def resnet18(pretrained=False, **kwargs):\n    model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)\n    if pretrained:\n        model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))\n    return model",
    "docstring": "Constructs a ResNet-18 model.\n\n    Args:\n        pretrained (bool): If True, returns a model pre-trained on ImageNet"
  },
  {
    "code": "def _check_for_batch_clashes(xs):\n    names = set([x[\"description\"] for x in xs])\n    dups = set([])\n    for x in xs:\n        batches = tz.get_in((\"metadata\", \"batch\"), x)\n        if batches:\n            if not isinstance(batches, (list, tuple)):\n                batches = [batches]\n            for batch in batches:\n                if batch in names:\n                    dups.add(batch)\n    if len(dups) > 0:\n        raise ValueError(\"Batch names must be unique from sample descriptions.\\n\"\n                         \"Clashing batch names: %s\" % sorted(list(dups)))",
    "docstring": "Check that batch names do not overlap with sample names."
  },
  {
    "code": "def _sanitize_and_check(indexes):\n    kinds = list({type(index) for index in indexes})\n    if list in kinds:\n        if len(kinds) > 1:\n            indexes = [Index(com.try_sort(x))\n                       if not isinstance(x, Index) else\n                       x for x in indexes]\n            kinds.remove(list)\n        else:\n            return indexes, 'list'\n    if len(kinds) > 1 or Index not in kinds:\n        return indexes, 'special'\n    else:\n        return indexes, 'array'",
    "docstring": "Verify the type of indexes and convert lists to Index.\n\n    Cases:\n\n    - [list, list, ...]: Return ([list, list, ...], 'list')\n    - [list, Index, ...]: Return _sanitize_and_check([Index, Index, ...])\n        Lists are sorted and converted to Index.\n    - [Index, Index, ...]: Return ([Index, Index, ...], TYPE)\n        TYPE = 'special' if at least one special type, 'array' otherwise.\n\n    Parameters\n    ----------\n    indexes : list of Index or list objects\n\n    Returns\n    -------\n    sanitized_indexes : list of Index or list objects\n    type : {'list', 'array', 'special'}"
  },
  {
    "code": "def use_federated_vault_view(self):\n        self._vault_view = FEDERATED\n        for session in self._get_provider_sessions():\n            try:\n                session.use_federated_vault_view()\n            except AttributeError:\n                pass",
    "docstring": "Pass through to provider AuthorizationLookupSession.use_federated_vault_view"
  },
  {
    "code": "def on_demand_annotation(twitter_app_key, twitter_app_secret, user_twitter_id):\n    twitter = login(twitter_app_key, twitter_app_secret)\n    twitter_lists_list = twitter.get_list_memberships(user_id=user_twitter_id, count=1000)\n    for twitter_list in twitter_lists_list:\n        print(twitter_list)\n    return twitter_lists_list",
    "docstring": "A service that leverages twitter lists for on-demand annotation of popular users.\n\n    TODO: Do this."
  },
  {
    "code": "def close(self):\r\n        if not self.is_opened():\r\n            return\r\n        self.__open_status = False\r\n        if self.__reading_thread and self.__reading_thread.is_alive():\r\n            self.__reading_thread.abort()\r\n        if self._input_report_queue:\r\n            self._input_report_queue.release_events()\r\n        if self.__input_processing_thread and \\\r\n                self.__input_processing_thread.is_alive():\r\n            self.__input_processing_thread.abort()\r\n        if self.ptr_preparsed_data:\r\n            ptr_preparsed_data = self.ptr_preparsed_data\r\n            self.ptr_preparsed_data = None\r\n            hid_dll.HidD_FreePreparsedData(ptr_preparsed_data)\r\n        if self.__reading_thread:\r\n            self.__reading_thread.join()\r\n        if self.hid_handle:\r\n            winapi.CloseHandle(self.hid_handle)\r\n        if self.__input_processing_thread:\r\n            self.__input_processing_thread.join()\r\n        button_caps_storage = self.__button_caps_storage\r\n        self.__reset_vars()\r\n        while button_caps_storage:\r\n            item = button_caps_storage.pop()\r\n            del item",
    "docstring": "Release system resources"
  },
  {
    "code": "def spy(self):\n        spy = Spy(self)\n        self._expectations.append(spy)\n        return spy",
    "docstring": "Add a spy to this stub. Return the spy."
  },
  {
    "code": "def conflicting_deps(tree):\n    conflicting = defaultdict(list)\n    for p, rs in tree.items():\n        for req in rs:\n            if req.is_conflicting():\n                conflicting[p].append(req)\n    return conflicting",
    "docstring": "Returns dependencies which are not present or conflict with the\n    requirements of other packages.\n\n    e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed\n\n    :param tree: the requirements tree (dict)\n    :returns: dict of DistPackage -> list of unsatisfied/unknown ReqPackage\n    :rtype: dict"
  },
  {
    "code": "def _data_to_json(data):\n        if type(data) not in [str, unicode]:\n            data = json.dumps(data)\n        return data",
    "docstring": "Convert to json if it isn't already a string.\n\n        Args:\n            data (str): data to convert to json"
  },
  {
    "code": "def unassign(self):\n        if self.object_uuid is None and self.object_type is None:\n            return True\n        try:\n            with db.session.begin_nested():\n                if self.is_redirected():\n                    db.session.delete(Redirect.query.get(self.object_uuid))\n                    self.status = PIDStatus.REGISTERED\n                self.object_type = None\n                self.object_uuid = None\n                db.session.add(self)\n        except SQLAlchemyError:\n            logger.exception(\"Failed to unassign object.\".format(self),\n                             extra=dict(pid=self))\n            raise\n        logger.info(\"Unassigned object from {0}.\".format(self),\n                    extra=dict(pid=self))\n        return True",
    "docstring": "Unassign the registered object.\n\n        Note:\n        Only registered PIDs can be redirected so we set it back to registered.\n\n        :returns: `True` if the PID is successfully unassigned."
  },
  {
    "code": "def check_for_missing_options(config):\n    for section_name, section in config:\n        for option_name, option in section:\n            if option.required and option.value is None:\n                raise exc.MissingRequiredOption(\n                    \"Option {0} in namespace {1} is required.\".format(\n                        option_name,\n                        section_name,\n                    )\n                )\n    return config",
    "docstring": "Iter over a config and raise if a required option is still not set.\n\n    Args:\n        config (confpy.core.config.Configuration): The configuration object\n            to validate.\n\n    Raises:\n        MissingRequiredOption: If any required options are not set in the\n            configuration object.\n\n    Required options with default values are considered set and will not cause\n    this function to raise."
  },
  {
    "code": "def evaluate(self, x):\n        r\n        x = np.asanyarray(x)\n        y = np.empty([self.Nf] + list(x.shape))\n        for i, kernel in enumerate(self._kernels):\n            y[i] = kernel(x)\n        return y",
    "docstring": "r\"\"\"Evaluate the kernels at given frequencies.\n\n        Parameters\n        ----------\n        x : array_like\n            Graph frequencies at which to evaluate the filter.\n\n        Returns\n        -------\n        y : ndarray\n            Frequency response of the filters. Shape ``(g.Nf, len(x))``.\n\n        Examples\n        --------\n        Frequency response of a low-pass filter:\n\n        >>> import matplotlib.pyplot as plt\n        >>> G = graphs.Logo()\n        >>> G.compute_fourier_basis()\n        >>> f = filters.Expwin(G)\n        >>> G.compute_fourier_basis()\n        >>> y = f.evaluate(G.e)\n        >>> plt.plot(G.e, y[0])  # doctest: +ELLIPSIS\n        [<matplotlib.lines.Line2D object at ...>]"
  },
  {
    "code": "def generate_folds(node_label_matrix, labelled_node_indices, number_of_categories, percentage, number_of_folds=10):\n    number_of_labeled_nodes = labelled_node_indices.size\n    training_set_size = int(np.ceil(percentage*number_of_labeled_nodes/100))\n    train_list = list()\n    test_list = list()\n    for trial in np.arange(number_of_folds):\n        train, test = valid_train_test(node_label_matrix[labelled_node_indices, :],\n                                       training_set_size,\n                                       number_of_categories,\n                                       trial)\n        train = labelled_node_indices[train]\n        test = labelled_node_indices[test]\n        train_list.append(train)\n        test_list.append(test)\n    folds = ((train, test) for train, test in zip(train_list, test_list))\n    return folds",
    "docstring": "Form the seed nodes for training and testing.\n\n    Inputs:  - node_label_matrix: The node-label ground truth in a SciPy sparse matrix format.\n             - labelled_node_indices: A NumPy array containing the labelled node indices.\n             - number_of_categories: The number of categories/classes in the learning.\n             - percentage: The percentage of labelled samples that will be used for training.\n\n    Output:  - folds: A generator containing train/test set folds."
  },
  {
    "code": "def to_json(self):\n        result = super(ApiKey, self).to_json()\n        result.update({\n            'name': self.name,\n            'description': self.description,\n            'accessToken': self.access_token,\n            'environments': [e.to_json() for e in self.environments]\n        })\n        return result",
    "docstring": "Returns the JSON representation of the API key."
  },
  {
    "code": "def _make_info(self, name, stat_result, namespaces):\n        info = {\n            'basic': {\n                'name': name,\n                'is_dir': stat.S_ISDIR(stat_result.st_mode)\n            }\n        }\n        if 'details' in namespaces:\n            info['details'] = self._make_details_from_stat(stat_result)\n        if 'stat' in namespaces:\n            info['stat'] = {\n                k: getattr(stat_result, k)\n                for k in dir(stat_result) if k.startswith('st_')\n            }\n        if 'access' in namespaces:\n            info['access'] = self._make_access_from_stat(stat_result)\n        return Info(info)",
    "docstring": "Create an `Info` object from a stat result."
  },
  {
    "code": "def Open(self, filename, read_only=False):\n    if self._connection:\n      raise RuntimeError('Cannot open database already opened.')\n    self.filename = filename\n    self.read_only = read_only\n    try:\n      self._connection = sqlite3.connect(filename)\n    except sqlite3.OperationalError:\n      return False\n    if not self._connection:\n      return False\n    self._cursor = self._connection.cursor()\n    if not self._cursor:\n      return False\n    return True",
    "docstring": "Opens the database file.\n\n    Args:\n      filename (str): filename of the database.\n      read_only (Optional[bool]): True if the database should be opened in\n          read-only mode. Since sqlite3 does not support a real read-only\n          mode we fake it by only permitting SELECT queries.\n\n    Returns:\n      bool: True if successful.\n\n    Raises:\n      RuntimeError: if the database is already opened."
  },
  {
    "code": "def register_elastic_task(self, *args, **kwargs):\n        kwargs[\"task_class\"] = ElasticTask\n        return self.register_task(*args, **kwargs)",
    "docstring": "Register an elastic task."
  },
  {
    "code": "def yaml_tag_constructor(loader, tag, node):\n    def _f(loader, tag, node):\n        if tag == '!GetAtt':\n            return node.value.split('.')\n        elif type(node) == yaml.SequenceNode:\n            return loader.construct_sequence(node)\n        else:\n            return node.value\n    if tag == '!Ref':\n        key = 'Ref'\n    else:\n        key = 'Fn::{}'.format(tag[1:])\n    return {key: _f(loader, tag, node)}",
    "docstring": "convert shorthand intrinsic function to full name"
  },
  {
    "code": "def get_id(date=None, project: str = 'sip',\n               instance_id: int = None) -> str:\n        if date is None:\n            date = datetime.datetime.utcnow()\n        if isinstance(date, datetime.datetime):\n            date = date.strftime('%Y%m%d')\n        if instance_id is None:\n            instance_id = randint(0, 9999)\n        return 'SBI-{}-{}-{:04d}'.format(date, project, instance_id)",
    "docstring": "Get a SBI Identifier.\n\n        Args:\n            date (str or datetime.datetime, optional): UTC date of the SBI\n            project (str, optional ): Project Name\n            instance_id (int, optional): SBI instance identifier\n\n        Returns:\n            str, Scheduling Block Instance (SBI) ID."
  },
  {
    "code": "def strip_files(files, argv_max=(256 * 1024)):\n    tostrip = [(fn, flipwritable(fn)) for fn in files]\n    while tostrip:\n        cmd = list(STRIPCMD)\n        flips = []\n        pathlen = reduce(operator.add, [len(s) + 1 for s in cmd])\n        while pathlen < argv_max:\n            if not tostrip:\n                break\n            added, flip = tostrip.pop()\n            pathlen += len(added) + 1\n            cmd.append(added)\n            flips.append((added, flip))\n        else:\n            cmd.pop()\n            tostrip.append(flips.pop())\n        os.spawnv(os.P_WAIT, cmd[0], cmd)\n        for args in flips:\n            flipwritable(*args)",
    "docstring": "Strip a list of files"
  },
  {
    "code": "def get_field_mapping(self, using=None, **kwargs):\n        return self._get_connection(using).indices.get_field_mapping(index=self._name, **kwargs)",
    "docstring": "Retrieve mapping definition of a specific field.\n\n        Any additional keyword arguments will be passed to\n        ``Elasticsearch.indices.get_field_mapping`` unchanged."
  },
  {
    "code": "def get_target_list(module, action_parameter=None):\n    exec_output = exec_action(module, 'list', action_parameter=action_parameter)\n    if not exec_output:\n        return None\n    target_list = []\n    if isinstance(exec_output, list):\n        for item in exec_output:\n            target_list.append(item.split(None, 1)[0])\n        return target_list\n    return None",
    "docstring": "List available targets for the given module.\n\n    module\n        name of the module to be queried for its targets\n\n    action_parameter\n        additional params passed to the defined action\n\n        .. versionadded:: 2016.11.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' eselect.get_target_list kernel"
  },
  {
    "code": "def execute(self):\n        cluster_name = self.params.cluster\n        creator = make_creator(self.params.config,\n                               storage_path=self.params.storage)\n        try:\n            cluster = creator.load_cluster(cluster_name)\n        except (ClusterNotFound, ConfigurationError) as err:\n            log.error(\"Cannot stop cluster `%s`: %s\", cluster_name, err)\n            return os.EX_NOINPUT\n        if not self.params.yes:\n            confirm_or_abort(\n                \"Do you want really want to stop cluster `{cluster_name}`?\"\n                .format(cluster_name=cluster_name),\n                msg=\"Aborting upon user request.\")\n        print(\"Destroying cluster `%s` ...\" % cluster_name)\n        cluster.stop(force=self.params.force, wait=self.params.wait)",
    "docstring": "Stops the cluster if it's running."
  },
  {
    "code": "def copy(self):\n        fs = self.__class__.__new__(self.__class__)\n        fs.__dict__ = self.__dict__.copy()\n        fs._frameSet = None\n        if self._frameSet is not None:\n            fs._frameSet = self._frameSet.copy()\n        return fs",
    "docstring": "Create a deep copy of this sequence\n\n        Returns:\n            :obj:`.FileSequence`:"
  },
  {
    "code": "def parse_url(url):\n    try:\n        url = unicode(url)\n    except NameError:\n        url = url\n    parsed = pystache.parse(url)\n    variables = (element.key for element in parsed._parse_tree if isinstance(element, _EscapeNode))\n    return pystache.render(url, {variable: os.environ[variable] for variable in variables})",
    "docstring": "Parse the given url and update it with environment value if required.\n\n    :param basestring url:\n    :rtype: basestring\n    :raise: KeyError if environment variable is needed but not found."
  },
  {
    "code": "def html(self, data='', py=True):\n        if py:\n            value = self.to_html(data)\n        else:\n            value = data\n        if self.static:\n            return str('<span class=\"value\">%s</span>' % safe_str(value))\n        else:\n            if self.hidden:\n                build = Hidden\n            else:\n                build = self.build\n            self._get_http_attrs()\n            return str(build(name=self.name, value=value, id=self.id, **self.html_attrs))",
    "docstring": "Convert data to html value format."
  },
  {
    "code": "def gfdist(target, abcorr, obsrvr, relate, refval, adjust, step, nintvls,\n           cnfine, result=None):\n    assert isinstance(cnfine, stypes.SpiceCell)\n    assert cnfine.is_double()\n    if result is None:\n        result = stypes.SPICEDOUBLE_CELL(2000)\n    else:\n        assert isinstance(result, stypes.SpiceCell)\n        assert result.is_double()\n    target = stypes.stringToCharP(target)\n    abcorr = stypes.stringToCharP(abcorr)\n    obsrvr = stypes.stringToCharP(obsrvr)\n    relate = stypes.stringToCharP(relate)\n    refval = ctypes.c_double(refval)\n    adjust = ctypes.c_double(adjust)\n    step = ctypes.c_double(step)\n    nintvls = ctypes.c_int(nintvls)\n    libspice.gfdist_c(target, abcorr, obsrvr, relate, refval, adjust,\n                      step, nintvls, ctypes.byref(cnfine), ctypes.byref(result))\n    return result",
    "docstring": "Return the time window over which a specified constraint on\n    observer-target distance is met.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfdist_c.html\n\n    :param target: Name of the target body.\n    :type target: str\n    :param abcorr: Aberration correction flag.\n    :type abcorr: str\n    :param obsrvr: Name of the observing body.\n    :type obsrvr: str\n    :param relate: Relational operator.\n    :type relate: str\n    :param refval: Reference value.\n    :type refval: float\n    :param adjust: Adjustment value for absolute extrema searches.\n    :type adjust: float\n    :param step: Step size used for locating extrema and roots.\n    :type step: float\n    :param nintvls: Workspace window interval count.\n    :type nintvls: int\n    :param cnfine: SPICE window to which the search is confined.\n    :type cnfine: spiceypy.utils.support_types.SpiceCell\n    :param result: Optional SPICE window containing results.\n    :type result: spiceypy.utils.support_types.SpiceCell"
  },
  {
    "code": "def expires_on(self):\n    timestamp = self._info.get('expirationTime', None)\n    if timestamp is None:\n      return None\n    return _parser.Parser.parse_timestamp(timestamp)",
    "docstring": "The timestamp for when the table will expire, or None if unknown."
  },
  {
    "code": "def DetectGce():\n    metadata_url = 'http://{}'.format(\n        os.environ.get('GCE_METADATA_ROOT', 'metadata.google.internal'))\n    try:\n        o = urllib_request.build_opener(urllib_request.ProxyHandler({})).open(\n            urllib_request.Request(\n                metadata_url, headers={'Metadata-Flavor': 'Google'}))\n    except urllib_error.URLError:\n        return False\n    return (o.getcode() == http_client.OK and\n            o.headers.get('metadata-flavor') == 'Google')",
    "docstring": "Determine whether or not we're running on GCE.\n\n    This is based on:\n      https://cloud.google.com/compute/docs/metadata#runninggce\n\n    Returns:\n      True iff we're running on a GCE instance."
  },
  {
    "code": "def aggregate_returns(returns, convert_to):\n    def cumulate_returns(x):\n        return cum_returns(x).iloc[-1]\n    if convert_to == WEEKLY:\n        grouping = [lambda x: x.year, lambda x: x.isocalendar()[1]]\n    elif convert_to == MONTHLY:\n        grouping = [lambda x: x.year, lambda x: x.month]\n    elif convert_to == YEARLY:\n        grouping = [lambda x: x.year]\n    else:\n        raise ValueError(\n            'convert_to must be {}, {} or {}'.format(WEEKLY, MONTHLY, YEARLY)\n        )\n    return returns.groupby(grouping).apply(cumulate_returns)",
    "docstring": "Aggregates returns by week, month, or year.\n\n    Parameters\n    ----------\n    returns : pd.Series\n       Daily returns of the strategy, noncumulative.\n        - See full explanation in :func:`~empyrical.stats.cum_returns`.\n    convert_to : str\n        Can be 'weekly', 'monthly', or 'yearly'.\n\n    Returns\n    -------\n    aggregated_returns : pd.Series"
  },
  {
    "code": "def parse(self):\n        while True:\n            status, self._buffer, packet = Packet.parse_msg(self._buffer)\n            if status == PARSE_RESULT.INCOMPLETE:\n                return status\n            if status == PARSE_RESULT.OK and packet:\n                packet.received = datetime.datetime.now()\n                if isinstance(packet, UTETeachInPacket) and self.teach_in:\n                    response_packet = packet.create_response_packet(self.base_id)\n                    self.logger.info('Sending response to UTE teach-in.')\n                    self.send(response_packet)\n                if self.__callback is None:\n                    self.receive.put(packet)\n                else:\n                    self.__callback(packet)\n                self.logger.debug(packet)",
    "docstring": "Parses messages and puts them to receive queue"
  },
  {
    "code": "def inject_dll(self):\n        self.logger.info('Injecting DLL')\n        injector_dir = os.path.join(get_dll_directory(), 'RLBot_Injector.exe')\n        for file in ['RLBot_Injector.exe', 'RLBot_Core.dll', 'RLBot_Core_Interface.dll', 'RLBot_Core_Interface_32.dll']:\n            file_path = os.path.join(get_dll_directory(), file)\n            if not os.path.isfile(file_path):\n                raise FileNotFoundError(f'{file} was not found in {get_dll_directory()}. '\n                                        'Please check that the file exists and your antivirus '\n                                        'is not removing it. See https://github.com/RLBot/RLBot/wiki/Antivirus-Notes')\n        incode = subprocess.call([injector_dir, 'hidden'])\n        injector_codes = ['INJECTION_SUCCESSFUL',\n                          'INJECTION_FAILED',\n                          'MULTIPLE_ROCKET_LEAGUE_PROCESSES_FOUND',\n                          'RLBOT_DLL_ALREADY_INJECTED',\n                          'RLBOT_DLL_NOT_FOUND',\n                          'MULTIPLE_RLBOT_DLL_FILES_FOUND']\n        injector_valid_codes = ['INJECTION_SUCCESSFUL',\n                                'RLBOT_DLL_ALREADY_INJECTED']\n        injection_status = injector_codes[incode]\n        if injection_status in injector_valid_codes:\n            self.logger.info('Finished Injecting DLL')\n            return injection_status\n        else:\n            self.logger.error('Failed to inject DLL: ' + injection_status)\n            sys.exit()",
    "docstring": "Calling this function will inject the DLL without GUI\n        DLL will return status codes from 0 to 5 which correspond to injector_codes\n        DLL injection is only valid if codes are 0->'INJECTION_SUCCESSFUL' or 3->'RLBOT_DLL_ALREADY_INJECTED'\n        It will print the output code and if it's not valid it will kill runner.py\n        If RL isn't running the Injector will stay hidden waiting for RL to open and inject as soon as it does"
  },
  {
    "code": "def get_selected_text_metrics(self):\n        selected_text = self.get_selected_text()\n        if not selected_text:\n            return tuple()\n        return (selected_text, self.get_cursor_line(), self.get_cursor_column() - len(selected_text))",
    "docstring": "Returns current document selected text metrics.\n\n        :return: Selected text metrics.\n        :rtype: tuple"
  },
  {
    "code": "def dependency_list(self):\n        r\n        dtree = self.dependency_graph()\n        cycles = list(nx.simple_cycles(dtree))\n        if cycles:\n            raise Exception('Cyclic dependency found: ' + ' -> '.join(\n                            cycles[0] + [cycles[0][0]]))\n        d = nx.algorithms.dag.lexicographical_topological_sort(dtree, sorted)\n        return list(d)",
    "docstring": "r'''\n        Returns a list of dependencies in the order with which they should be\n        called to ensure data is calculated by one model before it's asked for\n        by another.\n\n        Notes\n        -----\n        This raises an exception if the graph has cycles which means the\n        dependencies are unresolvable (i.e. there is no order which the\n        models can be called that will work).  In this case it is possible\n        to visually inspect the graph using ``dependency_graph``.\n\n        See Also\n        --------\n        dependency_graph\n        dependency_map"
  },
  {
    "code": "def splitterfields(data, commdct):\n    objkey = \"Connector:Splitter\".upper()\n    fieldlists = splittermixerfieldlists(data, commdct, objkey)\n    return extractfields(data, commdct, objkey, fieldlists)",
    "docstring": "get splitter fields to diagram it"
  },
  {
    "code": "def preallocate_memory(self, capacity):\n        if capacity < 0:\n            raise ValueError(u\"The capacity value cannot be negative\")\n        if self.__samples is None:\n            self.log(u\"Not initialized\")\n            self.__samples = numpy.zeros(capacity)\n            self.__samples_length = 0\n        else:\n            self.log([u\"Previous sample length was   (samples): %d\", self.__samples_length])\n            self.log([u\"Previous sample capacity was (samples): %d\", self.__samples_capacity])\n            self.__samples = numpy.resize(self.__samples, capacity)\n            self.__samples_length = min(self.__samples_length, capacity)\n        self.__samples_capacity = capacity\n        self.log([u\"Current sample capacity is   (samples): %d\", self.__samples_capacity])",
    "docstring": "Preallocate memory to store audio samples,\n        to avoid repeated new allocations and copies\n        while performing several consecutive append operations.\n\n        If ``self.__samples`` is not initialized,\n        it will become an array of ``capacity`` zeros.\n\n        If ``capacity`` is larger than the current capacity,\n        the current ``self.__samples`` will be extended with zeros.\n\n        If ``capacity`` is smaller than the current capacity,\n        the first ``capacity`` values of ``self.__samples``\n        will be retained.\n\n        :param int capacity: the new capacity, in number of samples\n        :raises: ValueError: if ``capacity`` is negative\n\n        .. versionadded:: 1.5.0"
  },
  {
    "code": "def auto_display_limits(self):\n        display_data_and_metadata = self.get_calculated_display_values(True).display_data_and_metadata\n        data = display_data_and_metadata.data if display_data_and_metadata else None\n        if data is not None:\n            mn, mx = numpy.nanmin(data), numpy.nanmax(data)\n            self.display_limits = mn, mx",
    "docstring": "Calculate best display limits and set them."
  },
  {
    "code": "def get_length(self, y):\n        lens = [self.find_pad_index(row) for row in y]\n        return lens",
    "docstring": "Get true length of y.\n\n        Args:\n            y (list): padded list.\n\n        Returns:\n            lens: true length of y.\n\n        Examples:\n            >>> y = [[1, 0, 0], [1, 1, 0], [1, 1, 1]]\n            >>> self.get_length(y)\n            [1, 2, 3]"
  },
  {
    "code": "def _replace_oov(original_vocab, line):\n  return u\" \".join(\n      [word if word in original_vocab else u\"UNK\" for word in line.split()])",
    "docstring": "Replace out-of-vocab words with \"UNK\".\n\n  This maintains compatibility with published results.\n\n  Args:\n    original_vocab: a set of strings (The standard vocabulary for the dataset)\n    line: a unicode string - a space-delimited sequence of words.\n\n  Returns:\n    a unicode string - a space-delimited sequence of words."
  },
  {
    "code": "def aa3_to_aa1(seq):\n    if seq is None:\n        return None\n    return \"\".join(aa3_to_aa1_lut[aa3]\n                   for aa3 in [seq[i:i + 3] for i in range(0, len(seq), 3)])",
    "docstring": "convert string of 3-letter amino acids to 1-letter amino acids\n\n    >>> aa3_to_aa1(\"CysAlaThrSerAlaArgGluLeuAlaMetGlu\")\n    'CATSARELAME'\n\n    >>> aa3_to_aa1(None)"
  },
  {
    "code": "def intersect(lst1, lst2):\n    if isinstance(lst1, collections.Hashable) and isinstance(lst2, collections.Hashable):\n        return set(lst1) & set(lst2)\n    return unique([ele for ele in lst1 if ele in lst2])",
    "docstring": "Returns the intersection of two lists.\n\n    .. code-block:: jinja\n\n        {% my_list = [1,2,3,4] -%}\n        {{ set my_list | intersect([2, 4, 6]) }}\n\n    will be rendered as:\n\n    .. code-block:: text\n\n        [2, 4]"
  },
  {
    "code": "def append(self, data):\n        self.io.write(data)\n        if not self.monitors:\n            return\n        buf = str(self)\n        for item in self.monitors:\n            regex_list, callback, bytepos, limit = item\n            bytepos = max(bytepos, len(buf) - limit)\n            for i, regex in enumerate(regex_list):\n                match = regex.search(buf, bytepos)\n                if match is not None:\n                    item[2] = match.end()\n                    callback(i, match)",
    "docstring": "Appends the given data to the buffer, and triggers all connected\n        monitors, if any of them match the buffer content.\n\n        :type  data: str\n        :param data: The data that is appended."
  },
  {
    "code": "def inner_join(df, other, **kwargs):\n    left_on, right_on, suffixes = get_join_parameters(kwargs)\n    joined = df.merge(other, how='inner', left_on=left_on,\n                      right_on=right_on, suffixes=suffixes)\n    return joined",
    "docstring": "Joins on values present in both DataFrames.\n\n    Args:\n        df (pandas.DataFrame): Left DataFrame (passed in via pipe)\n        other (pandas.DataFrame): Right DataFrame\n\n    Kwargs:\n        by (str or list): Columns to join on. If a single string, will join\n            on that column. If a list of lists which contain strings or\n            integers, the right/left columns to join on.\n        suffixes (list): String suffixes to append to column names in left\n            and right DataFrames.\n\n    Example:\n        a >> inner_join(b, by='x1')\n\n          x1  x2     x3\n        0  A   1   True\n        1  B   2  False"
  },
  {
    "code": "def _get_id(self, player):\n        name_tag = player('td[data-stat=\"player\"] a')\n        name = re.sub(r'.*/players/./', '', str(name_tag))\n        return re.sub(r'\\.shtml.*', '', name)",
    "docstring": "Parse the player ID.\n\n        Given a PyQuery object representing a single player on the team roster,\n        parse the player ID and return it as a string.\n\n        Parameters\n        ----------\n        player : PyQuery object\n            A PyQuery object representing the player information from the\n            roster table.\n\n        Returns\n        -------\n        string\n            Returns a string of the player ID."
  },
  {
    "code": "def rewire_inputs(data_list):\n    if len(data_list) < 2:\n        return data_list\n    mapped_ids = {bundle['original'].id: bundle['copy'].id for bundle in data_list}\n    for bundle in data_list:\n        updated = False\n        copy = bundle['copy']\n        for field_schema, fields in iterate_fields(copy.input, copy.process.input_schema):\n            name = field_schema['name']\n            value = fields[name]\n            if field_schema['type'].startswith('data:') and value in mapped_ids:\n                fields[name] = mapped_ids[value]\n                updated = True\n            elif field_schema['type'].startswith('list:data:') and any([id_ in mapped_ids for id_ in value]):\n                fields[name] = [mapped_ids[id_] if id_ in mapped_ids else id_ for id_ in value]\n                updated = True\n        if updated:\n            copy.save()\n    return data_list",
    "docstring": "Rewire inputs of provided data objects.\n\n    Input parameter is a list of original and copied data object model\n    instances: ``[{'original': original, 'copy': copy}]``. This\n    function finds which objects reference other objects (in the list)\n    on the input and replaces original objects with the copies (mutates\n    copies' inputs)."
  },
  {
    "code": "def remove_from(self, target, ctx=None):\n        annotations_key = Annotation.__ANNOTATIONS_KEY__\n        try:\n            local_annotations = get_local_property(\n                target, annotations_key, ctx=ctx\n            )\n        except TypeError:\n            raise TypeError('target {0} must be hashable'.format(target))\n        if local_annotations is not None:\n            if target in self.targets:\n                self.targets.remove(target)\n                while self in local_annotations:\n                    local_annotations.remove(self)\n                if not local_annotations:\n                    del_properties(target, annotations_key)",
    "docstring": "Remove self annotation from target annotations.\n\n        :param target: target from where remove self annotation.\n        :param ctx: target ctx."
  },
  {
    "code": "def save_sentences(twg, stmts, filename, agent_limit=300):\n    sentences = []\n    unmapped_texts = [t[0] for t in twg]\n    counter = 0\n    logger.info('Getting sentences for top %d unmapped agent texts.' %\n                agent_limit)\n    for text in unmapped_texts:\n        agent_sentences = get_sentences_for_agent(text, stmts)\n        sentences += map(lambda tup: (text,) + tup, agent_sentences)\n        counter += 1\n        if counter >= agent_limit:\n            break\n    write_unicode_csv(filename, sentences, delimiter=',', quotechar='\"',\n                      quoting=csv.QUOTE_MINIMAL, lineterminator='\\r\\n')",
    "docstring": "Write evidence sentences for stmts with ungrounded agents to csv file.\n\n    Parameters\n    ----------\n    twg: list of tuple\n        list of tuples of ungrounded agent_texts with counts of the\n        number of times they are mentioned in the list of statements.\n        Should be sorted in descending order by the counts.\n        This is of the form output by the function ungrounded texts.\n\n    stmts: list of :py:class:`indra.statements.Statement`\n\n    filename : str\n        Path to output file\n\n    agent_limit : Optional[int]\n        Number of agents to include in output file. Takes the top agents\n        by count."
  },
  {
    "code": "def assign(self, V, py):\n        if isinstance(py, (bytes, unicode)):\n            for i,C in enumerate(V['value.choices'] or self._choices):\n                if py==C:\n                    V['value.index'] = i\n                    return\n        V['value.index'] = py",
    "docstring": "Store python value in Value"
  },
  {
    "code": "def get_stored_metadata(self, temp_ver):\n        with open(self._prefixed('%s.metadata' % temp_ver.name)) as f:\n            return json.load(f)",
    "docstring": "Retrieves the metadata for the given template version from the store\n\n        Args:\n            temp_ver (TemplateVersion): template version to retrieve the\n                metadata for\n\n        Returns:\n            dict: the metadata of the given template version"
  },
  {
    "code": "def run_action(self, event):\n        action = self.get_action()\n        if action is not None:\n            try:\n                return bool( action(event) )\n            except Exception:\n                e = sys.exc_info()[1]\n                msg = (\"Breakpoint action callback %r\"\n                       \" raised an exception: %s\")\n                msg = msg % (action, traceback.format_exc(e))\n                warnings.warn(msg, BreakpointCallbackWarning)\n                return False\n        return True",
    "docstring": "Executes the breakpoint action callback, if any was set.\n\n        @type  event: L{Event}\n        @param event: Debug event triggered by the breakpoint."
  },
  {
    "code": "def reduce(self, func):\n        return self.map(lambda x: (None, x)).reduceByKey(func, 1).map(lambda x: x[1])",
    "docstring": "Return a new DStream in which each RDD has a single element\n        generated by reducing each RDD of this DStream."
  },
  {
    "code": "def safe_values(self, value):\r\n        string_val = \"\"\r\n        if isinstance(value, datetime.date):\r\n            try:\r\n                string_val = value.strftime('{0}{1}{2}'.format(\r\n                    current_app.config['DATETIME']['DATE_FORMAT'],\r\n                    current_app.config['DATETIME']['SEPARATOR'],\r\n                    current_app.config['DATETIME']['TIME_FORMAT']))\r\n            except RuntimeError as error:\r\n                string_val = value.strftime('%Y-%m-%d %H:%M:%S')\r\n        elif isinstance(value, bytes):\r\n            string_val = value.decode('utf-8')\r\n        elif isinstance(value, decimal.Decimal):\r\n            string_val = float(value)\r\n        else:\r\n            string_val = value\r\n        return string_val",
    "docstring": "Parse non-string values that will not serialize"
  },
  {
    "code": "def data(self):\n        if self._children:\n            for child in self._children:\n                self._action_data.setdefault('children', []).append(child.data)\n        return self._action_data",
    "docstring": "Return File Occurrence data."
  },
  {
    "code": "def keys_of_type_exist(self, *keys):\n        keys_exist = [(key, key in self.keys(), expected_type)\n                      for key, expected_type in keys]\n        return tuple(ContextItemInfo(\n            key=k[0],\n            key_in_context=k[1],\n            expected_type=k[2],\n            is_expected_type=isinstance(self[k[0]], k[2])\n            if k[1] else None,\n            has_value=k[1] and not self[k[0]] is None\n        ) for k in keys_exist)",
    "docstring": "Check if keys exist in context and if types are as expected.\n\n        Args:\n            *keys: *args for keys to check in context.\n                   Each arg is a tuple (str, type)\n\n        Returns:\n            Tuple of namedtuple ContextItemInfo, same order as *keys.\n            ContextItemInfo(key,\n                            key_in_context,\n                            expected_type,\n                            is_expected_type)\n\n            Remember if there is only one key in keys, the return assignment\n            needs an extra comma to remind python that it's a tuple:\n            # one\n            a, = context.keys_of_type_exist('a')\n            # > 1\n            a, b = context.keys_of_type_exist('a', 'b')"
  },
  {
    "code": "def getObjectList(IDs, date, pos):\n    objList = [getObject(ID, date, pos) for ID in IDs]\n    return ObjectList(objList)",
    "docstring": "Returns a list of objects."
  },
  {
    "code": "def select(self, pyliste):\n        if self.isClosed or self.isEncrypted:\n            raise ValueError(\"operation illegal for closed / encrypted doc\")\n        val = _fitz.Document_select(self, pyliste)\n        self._reset_page_refs()\n        self.initData()\n        return val",
    "docstring": "Build sub-pdf with page numbers in 'list'."
  },
  {
    "code": "def _next_non_masked_element(a, idx):\n    try:\n        next_idx = idx + a[idx:].mask.argmin()\n        if ma.is_masked(a[next_idx]):\n            return None, None\n        else:\n            return next_idx, a[next_idx]\n    except (AttributeError, TypeError, IndexError):\n        return idx, a[idx]",
    "docstring": "Return the next non masked element of a masked array.\n\n    If an array is masked, return the next non-masked element (if the given index is masked).\n    If no other unmasked points are after the given masked point, returns none.\n\n    Parameters\n    ----------\n    a : array-like\n        1-dimensional array of numeric values\n    idx : integer\n        index of requested element\n\n    Returns\n    -------\n        Index of next non-masked element and next non-masked element"
  },
  {
    "code": "def detach(self):\n        self._client.post('{}/detach'.format(Volume.api_endpoint), model=self)\n        return True",
    "docstring": "Detaches this Volume if it is attached"
  },
  {
    "code": "def delete(key,\n           host=DEFAULT_HOST,\n           port=DEFAULT_PORT,\n           time=DEFAULT_TIME):\n    if not isinstance(time, six.integer_types):\n        raise SaltInvocationError('\\'time\\' must be an integer')\n    conn = _connect(host, port)\n    _check_stats(conn)\n    return bool(conn.delete(key, time))",
    "docstring": "Delete a key from memcache server\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' memcached.delete <key>"
  },
  {
    "code": "def lstlti(x, n, array):\n    array = stypes.toIntVector(array)\n    x = ctypes.c_int(x)\n    n = ctypes.c_int(n)\n    return libspice.lstlti_c(x, n, array)",
    "docstring": "Given a number x and an array of non-decreasing int,\n    find the index of the largest array element less than x.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstlti_c.html\n\n    :param x: Value to search against\n    :type x: int\n    :param n: Number elements in array\n    :type n: int\n    :param array: Array of possible lower bounds\n    :type array: list\n    :return: index of the last element of array that is less than x.\n    :rtype: int"
  },
  {
    "code": "def emit(self, **kwargs):\n        self._ensure_emit_kwargs(kwargs)\n        for slot in self.slots:\n            slot(**kwargs)",
    "docstring": "Emit signal by calling all connected slots.\n\n        The arguments supplied have to match the signal definition.\n\n        Args:\n            kwargs: Keyword arguments to be passed to connected slots.\n\n        Raises:\n            :exc:`InvalidEmit`: If arguments don't match signal specification."
  },
  {
    "code": "def service_create(image=str,\n                   name=str,\n                   command=str,\n                   hostname=str,\n                   replicas=int,\n                   target_port=int,\n                   published_port=int):\n    try:\n        salt_return = {}\n        replica_mode = docker.types.ServiceMode('replicated', replicas=replicas)\n        ports = docker.types.EndpointSpec(ports={target_port: published_port})\n        __context__['client'].services.create(name=name,\n                                              image=image,\n                                              command=command,\n                                              mode=replica_mode,\n                                              endpoint_spec=ports)\n        echoback = __context__['server_name'] + ' has a Docker Swarm Service running named ' + name\n        salt_return.update({'Info': echoback,\n                            'Minion': __context__['server_name'],\n                            'Name': name,\n                            'Image': image,\n                            'Command': command,\n                            'Hostname': hostname,\n                            'Replicas': replicas,\n                            'Target_Port': target_port,\n                            'Published_Port': published_port})\n    except TypeError:\n        salt_return = {}\n        salt_return.update({'Error': 'Please make sure you are passing arguments correctly '\n                                     '[image, name, command, hostname, replicas, target_port and published_port]'})\n    return salt_return",
    "docstring": "Create Docker Swarm Service Create\n\n    image\n        The docker image\n\n    name\n        Is the service name\n\n    command\n        The docker command to run in the container at launch\n\n    hostname\n        The hostname of the containers\n\n    replicas\n        How many replicas you want running in the swarm\n\n    target_port\n        The target port on the container\n\n    published_port\n        port thats published on the host/os\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' swarm.service_create image=httpd name=Test_Service \\\n            command=None hostname=salthttpd replicas=6 target_port=80 published_port=80"
  },
  {
    "code": "def sequence_type(seq):\n    if isinstance(seq, coral.DNA):\n        material = 'dna'\n    elif isinstance(seq, coral.RNA):\n        material = 'rna'\n    elif isinstance(seq, coral.Peptide):\n        material = 'peptide'\n    else:\n        raise ValueError('Input was not a recognized coral.sequence object.')\n    return material",
    "docstring": "Validates a coral.sequence data type.\n\n    :param sequence_in: input DNA sequence.\n    :type sequence_in: any\n    :returns: The material - 'dna', 'rna', or 'peptide'.\n    :rtype: str\n    :raises: ValueError"
  },
  {
    "code": "def ParseMultiple(self, result_dicts):\n    for result_dict in result_dicts:\n      yield rdf_client.HardwareInfo(\n          serial_number=result_dict[\"IdentifyingNumber\"],\n          system_manufacturer=result_dict[\"Vendor\"])",
    "docstring": "Parse the WMI output to get Identifying Number."
  },
  {
    "code": "def _ReadTable(self, tables, file_object, table_offset):\n    table_header = self._ReadTableHeader(file_object, table_offset)\n    for record_offset in table_header.record_offsets:\n      if record_offset == 0:\n        continue\n      record_offset += table_offset\n      if table_header.record_type == self._RECORD_TYPE_CSSM_DL_DB_SCHEMA_INFO:\n        self._ReadRecordSchemaInformation(tables, file_object, record_offset)\n      elif table_header.record_type == (\n          self._RECORD_TYPE_CSSM_DL_DB_SCHEMA_INDEXES):\n        self._ReadRecordSchemaIndexes(tables, file_object, record_offset)\n      elif table_header.record_type == (\n          self._RECORD_TYPE_CSSM_DL_DB_SCHEMA_ATTRIBUTES):\n        self._ReadRecordSchemaAttributes(tables, file_object, record_offset)\n      else:\n        self._ReadRecord(\n            tables, file_object, record_offset, table_header.record_type)",
    "docstring": "Reads the table.\n\n    Args:\n      tables (dict[int, KeychainDatabaseTable]): tables per identifier.\n      file_object (file): file-like object.\n      table_offset (int): offset of the table relative to the start of\n          the file.\n\n    Raises:\n      ParseError: if the table cannot be read."
  },
  {
    "code": "def get_base(self, option):\n        if option:\n            if option.isupper():\n                if len(option) > 3:\n                    return getattr(settings, option), True\n                elif len(option) == 3:\n                    return option, True\n            raise ImproperlyConfigured(\"Invalid currency code found: %s\" % option)\n        for attr in ('CURRENCIES_BASE', 'SHOP_DEFAULT_CURRENCY'):\n            try:\n                return getattr(settings, attr), True\n            except AttributeError:\n                continue\n        return 'USD', False",
    "docstring": "Parse the base command option. Can be supplied as a 3 character code or a settings variable name\n        If base is not supplied, looks for settings CURRENCIES_BASE and SHOP_DEFAULT_CURRENCY"
  },
  {
    "code": "def _check_environ(variable, value):\n    if is_not_none(value):\n        return value\n    else:\n        value = os.environ.get(variable)\n        if is_none(value):\n            stop(''.join([variable,\n]))\n        else:\n            return value",
    "docstring": "check if a variable is present in the environmental variables"
  },
  {
    "code": "def reset(self):\n        if self.state is not TimerState.stopped:\n            if self.on_reset and self.state is TimerState.overflow:\n                if callable(self.on_reset):\n                    self.on_reset()\n                else:\n                    execute(self.on_reset)\n            self.state = TimerState.stopped",
    "docstring": "Stop timer and execute ``on_reset`` if overflow occured."
  },
  {
    "code": "def set_snapshots(self,snapshots):\n        self.snapshots = pd.Index(snapshots)\n        self.snapshot_weightings = self.snapshot_weightings.reindex(self.snapshots,fill_value=1.)\n        if isinstance(snapshots, pd.DatetimeIndex) and _pd_version < '0.18.0':\n            snapshots = pd.Index(snapshots.values)\n        for component in self.all_components:\n            pnl = self.pnl(component)\n            attrs = self.components[component][\"attrs\"]\n            for k,default in attrs.default[attrs.varying].iteritems():\n                pnl[k] = pnl[k].reindex(self.snapshots).fillna(default)",
    "docstring": "Set the snapshots and reindex all time-dependent data.\n\n        This will reindex all pandas.Panels of time-dependent data; NaNs are filled\n        with the default value for that quantity.\n\n        Parameters\n        ----------\n        snapshots : list or pandas.Index\n            All time steps.\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def to_description_dict(self):\n        return {\n            'certificateArn': self.arn,\n            'certificateId': self.certificate_id,\n            'status': self.status,\n            'certificatePem': self.certificate_pem,\n            'ownedBy': self.owner,\n            'creationDate': self.creation_date,\n            'lastModifiedDate': self.last_modified_date,\n            'transferData': self.transfer_data\n        }",
    "docstring": "You might need keys below in some situation\n          - caCertificateId\n          - previousOwnedBy"
  },
  {
    "code": "def runlist_list(**kwargs):\n    ctx = Context(**kwargs)\n    ctx.execute_action('runlist:list', **{\n        'storage': ctx.repo.create_secure_service('storage'),\n    })",
    "docstring": "Show uploaded runlists."
  },
  {
    "code": "def stop_instance(self, instance):\n        params = {'state': 'stopped'}\n        url = '/instances/{}'.format(instance)\n        self.patch_proto(url, params=params)",
    "docstring": "Stops a single instance.\n\n        :param str instance: A Yamcs instance name."
  },
  {
    "code": "def copy_scubadir_file(self, name, source):\n        dest = os.path.join(self.__scubadir_hostpath, name)\n        assert not os.path.exists(dest)\n        shutil.copy2(source, dest)\n        return os.path.join(self.__scubadir_contpath, name)",
    "docstring": "Copies source into the scubadir\n\n        Returns the container-path of the copied file"
  },
  {
    "code": "def setWindowSize(self, winsz):\n        self.tracePlot.setWindowSize(winsz)\n        self.stimPlot.setWindowSize(winsz)",
    "docstring": "Sets the size of scroll window"
  },
  {
    "code": "def sort_url_qsl(cls, raw_url, **kwargs):\n        parsed_url = urlparse(raw_url)\n        qsl = parse_qsl(parsed_url.query)\n        return cls._join_url(parsed_url, sorted(qsl, **kwargs))",
    "docstring": "Do nothing but sort the params of url.\n\n            raw_url: the raw url to be sorted; \n            kwargs: (optional) same kwargs for ``sorted``."
  },
  {
    "code": "def query_all_collisions(collision_object):\n        global collidable_objects\n        colliding = []\n        for obj in collidable_objects:\n            if obj is not collision_object:\n                if collision_object.is_colliding(obj):\n                    colliding.append(obj)\n        return colliding",
    "docstring": "Check for and return the full list of objects colliding with collision_object"
  },
  {
    "code": "def _attach_to_instance(self, instance):\n        self._instance = instance\n        self.lockable = self.lockable and instance.lockable",
    "docstring": "Attach the current field to an instance of a model. Can be overriden to\n        do something when an instance is set"
  },
  {
    "code": "def do_sqlite_connect(dbapi_connection, connection_record):\n    cursor = dbapi_connection.cursor()\n    cursor.execute('PRAGMA foreign_keys=ON')\n    cursor.close()",
    "docstring": "Ensure SQLite checks foreign key constraints.\n\n    For further details see \"Foreign key support\" sections on\n    https://docs.sqlalchemy.org/en/latest/dialects/sqlite.html#foreign-key-support"
  },
  {
    "code": "def get_tag_value(self, i):\n        found = False\n        for t in i.get('Tags', ()):\n            if t['Key'].lower() == self.tag_key:\n                found = t['Value']\n                break\n        if found is False:\n            return False\n        value = found.lower().encode('utf8').decode('utf8')\n        value = value.strip(\"'\").strip('\"')\n        return value",
    "docstring": "Get the resource's tag value specifying its schedule."
  },
  {
    "code": "def on_pause(self):\n        self.engine.commit()\n        self.strings.save()\n        self.funcs.save()\n        self.config.write()",
    "docstring": "Sync the database with the current state of the game."
  },
  {
    "code": "def _get_encoding(encoding_or_label):\n    if hasattr(encoding_or_label, 'codec_info'):\n        return encoding_or_label\n    encoding = lookup(encoding_or_label)\n    if encoding is None:\n        raise LookupError('Unknown encoding label: %r' % encoding_or_label)\n    return encoding",
    "docstring": "Accept either an encoding object or label.\n\n    :param encoding: An :class:`Encoding` object or a label string.\n    :returns: An :class:`Encoding` object.\n    :raises: :exc:`~exceptions.LookupError` for an unknown label."
  },
  {
    "code": "def get_random(self, n, l=None):\n        random_f = Fasta()\n        if l:\n            ids = self.ids[:]\n            random.shuffle(ids)\n            i = 0\n            while (i < n) and (len(ids) > 0):\n                seq_id = ids.pop()\n                if (len(self[seq_id]) >= l):\n                    start = random.randint(0, len(self[seq_id]) - l)\n                    random_f[\"random%s\" % (i + 1)] = self[seq_id][start:start+l]\n                    i += 1\n            if len(random_f) != n:\n                sys.stderr.write(\"Not enough sequences of required length\")\n                return\n            else:\n                return random_f\n        else:\n            choice = random.sample(self.ids, n)\n            for i in range(n):\n                random_f[choice[i]] = self[choice[i]]\n        return random_f",
    "docstring": "Return n random sequences from this Fasta object"
  },
  {
    "code": "def delete_metadata(self, container, prefix=None):\n        if prefix is None:\n            prefix = CONTAINER_META_PREFIX\n        new_meta = {}\n        curr_meta = self.get_metadata(container, prefix=prefix)\n        for ckey in curr_meta:\n            new_meta[ckey] = \"\"\n        uri = \"/%s\" % utils.get_name(container)\n        resp, resp_body = self.api.method_post(uri, headers=new_meta)\n        return 200 <= resp.status_code <= 299",
    "docstring": "Removes all of the container's metadata.\n\n        By default, all metadata beginning with the standard container metadata\n        prefix ('X-Container-Meta-') is removed. If you wish to remove all\n        metadata beginning with a different prefix, you must specify that\n        prefix."
  },
  {
    "code": "def shrink(self, fraction=0.85):\n        poly = self.polydata(True)\n        shrink = vtk.vtkShrinkPolyData()\n        shrink.SetInputData(poly)\n        shrink.SetShrinkFactor(fraction)\n        shrink.Update()\n        return self.updateMesh(shrink.GetOutput())",
    "docstring": "Shrink the triangle polydata in the representation of the input mesh.\n\n        Example:\n            .. code-block:: python\n\n                from vtkplotter import *\n                pot = load(datadir + 'shapes/teapot.vtk').shrink(0.75)\n                s = Sphere(r=0.2).pos(0,0,-0.5)\n                show(pot, s)\n\n            |shrink| |shrink.py|_"
  },
  {
    "code": "def plot_bbox(sf,bbox,inside_only=True):\n    index,shape_records = bbox_match(sf,bbox,inside_only)\n    A,B,C,D = bbox\n    plot(shape_records,xlims=[bbox[0],bbox[2]],ylims=[bbox[1],bbox[3]])",
    "docstring": "Plot the geometry of a shapefile within a bbox\n\n    :param sf: shapefile\n    :type sf: shapefile object\n    :param bbox: bounding box\n    :type bbox: list of floats [x_min,y_min,x_max,y_max]\n    :inside_only: True if the objects returned are those that lie within the bbox and False if the objects returned are any that intersect the bbox\n    :type inside_only: Boolean"
  },
  {
    "code": "def Set(self, value, fields=None):\n    self._metric_values[_FieldsToKey(fields)] = self._value_type(value)",
    "docstring": "Sets the metric's current value."
  },
  {
    "code": "def get_profane_words(self):\n        profane_words = []\n        if self._custom_censor_list:\n            profane_words = [w for w in self._custom_censor_list]\n        else:\n            profane_words = [w for w in self._censor_list]\n        profane_words.extend(self._extra_censor_list)\n        profane_words.extend([inflection.pluralize(word) for word in profane_words])\n        profane_words = list(set(profane_words))\n        profane_words.sort(key=len)\n        profane_words.reverse()\n        return profane_words",
    "docstring": "Returns all profane words currently in use."
  },
  {
    "code": "def _parallel_predict(estimators, estimators_features, X, n_classes, combination, estimators_weight):\n    n_samples = X.shape[0]\n    pred = np.zeros((n_samples, n_classes))\n    n_estimators = len(estimators)\n    for estimator, features, weight in zip(estimators, estimators_features, estimators_weight):\n        predictions = estimator.predict(X[:, features])\n        for i in range(n_samples):\n            if combination == 'weighted_voting':\n                pred[i, int(predictions[i])] += 1 * weight\n            else:\n                pred[i, int(predictions[i])] += 1\n    return pred",
    "docstring": "Private function used to compute predictions within a job."
  },
  {
    "code": "def view_graph(graph_str, parent=None, prune_to=None):\n    from rezgui.dialogs.ImageViewerDialog import ImageViewerDialog\n    from rez.config import config\n    h = hash((graph_str, prune_to))\n    filepath = graph_file_lookup.get(h)\n    if filepath and not os.path.exists(filepath):\n        filepath = None\n    if filepath is None:\n        suffix = \".%s\" % config.dot_image_format\n        fd, filepath = tempfile.mkstemp(suffix=suffix, prefix=\"rez-graph-\")\n        os.close(fd)\n        dlg = WriteGraphDialog(graph_str, filepath, parent, prune_to=prune_to)\n        if not dlg.write_graph():\n            return\n    graph_file_lookup[h] = filepath\n    dlg = ImageViewerDialog(filepath, parent)\n    dlg.exec_()",
    "docstring": "View a graph."
  },
  {
    "code": "def num_model_per_iteration(self):\n        model_per_iter = ctypes.c_int(0)\n        _safe_call(_LIB.LGBM_BoosterNumModelPerIteration(\n            self.handle,\n            ctypes.byref(model_per_iter)))\n        return model_per_iter.value",
    "docstring": "Get number of models per iteration.\n\n        Returns\n        -------\n        model_per_iter : int\n            The number of models per iteration."
  },
  {
    "code": "def is_valid_device_id(device_id):\n    valid = valid_device_id.match(device_id)\n    if not valid:\n        logging.error(\"A valid device identifier contains \"\n                      \"only ascii word characters or dashes. \"\n                      \"Device '%s' not added.\", device_id)\n    return valid",
    "docstring": "Check if device identifier is valid.\n\n    A valid device identifier contains only ascii word characters or dashes.\n\n    :param device_id: Device identifier\n    :returns: Valid or not."
  },
  {
    "code": "def _tighten_triplet(self, max_iterations, later_iter, max_triplets, prolong):\n        triangles = self.find_triangles()\n        triplet_scores = self._get_triplet_scores(triangles)\n        sorted_scores = sorted(triplet_scores, key=triplet_scores.get)\n        for niter in range(max_iterations):\n            if self._is_converged(integrality_gap_threshold=self.integrality_gap_threshold):\n                break\n            add_triplets = []\n            for triplet_number in (range(len(sorted_scores))):\n                if triplet_number >= max_triplets:\n                    break\n                add_triplets.append(sorted_scores.pop())\n            if not add_triplets and prolong is False:\n                    break\n            self._update_triangles(add_triplets)\n            self._run_mplp(later_iter)",
    "docstring": "This method finds all the triplets that are eligible and adds them iteratively in the bunch of max_triplets\n\n        Parameters\n        ----------\n        max_iterations: integer\n                        Maximum number of times we tighten the relaxation\n\n        later_iter: integer\n                    Number of maximum iterations that we want MPLP to run. This is lesser than the initial number\n                    of iterations.\n\n        max_triplets: integer\n                      Maximum number of triplets that can be added atmost in one iteration.\n\n        prolong: bool\n                It sets the continuation of tightening after all the triplets are exhausted"
  },
  {
    "code": "def weighted_accuracy(comparisons, weights):\n    N = len(comparisons)\n    if weights.shape[0] != N:\n        raise ValueError('weights and comparisons should be of the same'\n                         ' length. len(weights) = {} but len(comparisons)'\n                         ' = {}'.format(weights.shape[0], N))\n    if (weights < 0).any():\n        raise ValueError('Weights should all be positive.')\n    if np.sum(weights) == 0:\n        warnings.warn('No nonzero weights, returning 0')\n        return 0\n    valid_idx = (comparisons >= 0)\n    if valid_idx.sum() == 0:\n        warnings.warn(\"No reference chords were comparable \"\n                      \"to estimated chords, returning 0.\")\n        return 0\n    comparisons = comparisons[valid_idx]\n    weights = weights[valid_idx]\n    total_weight = float(np.sum(weights))\n    normalized_weights = np.asarray(weights, dtype=float)/total_weight\n    return np.sum(comparisons*normalized_weights)",
    "docstring": "Compute the weighted accuracy of a list of chord comparisons.\n\n    Examples\n    --------\n    >>> (ref_intervals,\n    ...  ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')\n    >>> (est_intervals,\n    ...  est_labels) = mir_eval.io.load_labeled_intervals('est.lab')\n    >>> est_intervals, est_labels = mir_eval.util.adjust_intervals(\n    ...     est_intervals, est_labels, ref_intervals.min(),\n    ...     ref_intervals.max(), mir_eval.chord.NO_CHORD,\n    ...     mir_eval.chord.NO_CHORD)\n    >>> (intervals,\n    ...  ref_labels,\n    ...  est_labels) = mir_eval.util.merge_labeled_intervals(\n    ...      ref_intervals, ref_labels, est_intervals, est_labels)\n    >>> durations = mir_eval.util.intervals_to_durations(intervals)\n    >>> # Here, we're using the \"thirds\" function to compare labels\n    >>> # but any of the comparison functions would work.\n    >>> comparisons = mir_eval.chord.thirds(ref_labels, est_labels)\n    >>> score = mir_eval.chord.weighted_accuracy(comparisons, durations)\n\n    Parameters\n    ----------\n    comparisons : np.ndarray\n        List of chord comparison scores, in [0, 1] or -1\n    weights : np.ndarray\n        Weights (not necessarily normalized) for each comparison.\n        This can be a list of interval durations\n\n    Returns\n    -------\n    score : float\n        Weighted accuracy"
  },
  {
    "code": "def _value_validate(self, value, rnge, identifier=\"Given\"):\n        if value is not None and (value < rnge[0] or value > rnge[1]):\n            raise ValueError('%s value must be between %d and %d.'\n                             % (identifier, rnge[0], rnge[1]))",
    "docstring": "Make sure a value is within a given range"
  },
  {
    "code": "def run(self):\n        self.otherThread._Thread__stderr = self._stderr\n        if hasattr(self.otherThread, '_Thread__stop'):\n            self.otherThread._Thread__stop()\n        while self.otherThread.isAlive():\n            ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(self.otherThread.ident), ctypes.py_object(self.exception))\n            self.otherThread.join(self.repeatEvery)\n        try:\n            self._stderr.close()\n        except:\n            pass",
    "docstring": "run - The thread main. Will attempt to stop and join the attached thread."
  },
  {
    "code": "def first_name_capture(records):\n    logging.info('Applying _first_name_capture generator: '\n                 'making sure ID only contains the first whitespace-delimited '\n                 'word.')\n    whitespace = re.compile(r'\\s+')\n    for record in records:\n        if whitespace.search(record.description):\n            yield SeqRecord(record.seq, id=record.id,\n                            description=\"\")\n        else:\n            yield record",
    "docstring": "Take only the first whitespace-delimited word as the name of the sequence.\n    Essentially removes any extra text from the sequence's description."
  },
  {
    "code": "def visit_loop(self, node, cond=None):\n        for stmt in node.body:\n            self.visit(stmt)\n        old_range = self.result.copy()\n        for stmt in node.body:\n            self.visit(stmt)\n        for expr, range_ in old_range.items():\n            self.result[expr] = self.result[expr].widen(range_)\n        cond and self.visit(cond)\n        for stmt in node.body:\n            self.visit(stmt)\n        for stmt in node.orelse:\n            self.visit(stmt)",
    "docstring": "Handle incremented variables in loop body.\n\n        >>> import gast as ast\n        >>> from pythran import passmanager, backend\n        >>> node = ast.parse('''\n        ... def foo():\n        ...     a = b = c = 2\n        ...     while a > 0:\n        ...         a -= 1\n        ...         b += 1''')\n        >>> pm = passmanager.PassManager(\"test\")\n        >>> res = pm.gather(RangeValues, node)\n        >>> res['a']\n        Interval(low=-inf, high=2)\n        >>> res['b']\n        Interval(low=2, high=inf)\n        >>> res['c']\n        Interval(low=2, high=2)"
  },
  {
    "code": "def disable(self):\n        self._enabled = False\n        for child in self.children:\n            if isinstance(child, (Container, Widget)):\n                child.disable()",
    "docstring": "Disable all the widgets in this container"
  },
  {
    "code": "def _significant_pathways_dataframe(pvalue_information,\n                                    side_information,\n                                    alpha):\n    significant_pathways = pd.concat(\n        [pvalue_information, side_information], axis=1)\n    below_alpha, qvalues, _, _ = multipletests(\n        significant_pathways[\"p-value\"], alpha=alpha, method=\"fdr_bh\")\n    below_alpha = pd.Series(\n        below_alpha, index=pvalue_information.index, name=\"pass\")\n    qvalues = pd.Series(\n        qvalues, index=pvalue_information.index, name=\"q-value\")\n    significant_pathways = pd.concat(\n        [significant_pathways, below_alpha, qvalues], axis=1)\n    significant_pathways = significant_pathways[significant_pathways[\"pass\"]]\n    significant_pathways.drop(\"pass\", axis=1, inplace=True)\n    significant_pathways.loc[:, \"pathway\"] = significant_pathways.index\n    return significant_pathways",
    "docstring": "Create the significant pathways pandas.DataFrame.\n    Given the p-values corresponding to each pathway in a feature,\n    apply the FDR correction for multiple testing and remove those that\n    do not have a q-value of less than `alpha`."
  },
  {
    "code": "def start_logging(self, region, name):\n        ct = self.session.client('cloudtrail', region_name=region)\n        ct.start_logging(Name=name)\n        auditlog(\n            event='cloudtrail.start_logging',\n            actor=self.ns,\n            data={\n                'account': self.account.account_name,\n                'region': region\n            }\n        )\n        self.log.info('Enabled logging for {} ({})'.format(name, region))",
    "docstring": "Turn on logging for a CloudTrail Trail\n\n        Args:\n            region (`str`): Name of the AWS region\n            name (`str`): Name of the CloudTrail Trail\n\n        Returns:\n            `None`"
  },
  {
    "code": "def init_ui(self):\n        board_width = self.ms_game.board_width\n        board_height = self.ms_game.board_height\n        self.create_grid(board_width, board_height)\n        self.time = 0\n        self.timer = QtCore.QTimer()\n        self.timer.timeout.connect(self.timing_game)\n        self.timer.start(1000)",
    "docstring": "Init game interface."
  },
  {
    "code": "def dump_in_memory_result(self, result, output_path):\n        file_count = 0\n        logger.debug(\"Dumping in-memory processing results to output folder: %s\", output_path)\n        for k, v in iteritems(result):\n            cur_output_path = os.path.join(output_path, k)\n            if isinstance(v, dict):\n                file_count += self.dump_in_memory_result(v, cur_output_path)\n            else:\n                if not os.path.isdir(output_path):\n                    os.makedirs(output_path)\n                filename = os.path.join(output_path, k)\n                logger.debug(\"Writing output file: %s\", filename)\n                with open(filename, 'wt', encoding=self.config.encoding) as f:\n                    f.write(v)\n                file_count += 1\n        return file_count",
    "docstring": "Recursively dumps the result of our processing into files within the\n        given output path.\n\n        Args:\n            result: The in-memory result of our processing.\n            output_path: Full path to the folder into which to dump the files.\n\n        Returns:\n            The number of files generated (integer)."
  },
  {
    "code": "def get_nodes_by_tag(self, graph, tag_name):\n        for node, real_node in self.parsed_nodes(graph):\n            if tag_name in real_node.tags:\n                yield node",
    "docstring": "yields nodes from graph that have the specified tag"
  },
  {
    "code": "def get_next_environment(env):\n    config = _config_file()\n    juicer.utils.Log.log_debug(\"Finding next environment...\")\n    if env not in config.sections():\n        raise JuicerConfigError(\"%s is not a server configured in juicer.conf\", env)\n    section = dict(config.items(env))\n    if 'promotes_to' not in section.keys():\n        err = \"Environment `%s` has no entry for `promotes_to`\\nCheck man 5 juicer.conf.\" % env\n        raise JuicerConfigError(err)\n    return section['promotes_to']",
    "docstring": "Given an environment, return the next environment in the\n    promotion hierarchy"
  },
  {
    "code": "def current_timestamp(self) -> datetime:\n        timestamp = DB.get_hash_value(self._key, 'current_timestamp')\n        return datetime_from_isoformat(timestamp)",
    "docstring": "Get the current state timestamp."
  },
  {
    "code": "def feed_fetch_force(request, id, redirect_to):\n    feed = Feed.objects.get(id=id)\n    feed.fetch(force=True)\n    msg = _(\"Fetched tweets for %s\" % feed.name)\n    messages.success(request, msg, fail_silently=True)\n    return HttpResponseRedirect(redirect_to)",
    "docstring": "Forcibly fetch tweets for the feed"
  },
  {
    "code": "def load_werkzeug(path):\n    sys.path[0] = path\n    wz.__dict__.clear()\n    for key in sys.modules.keys():\n        if key.startswith(\"werkzeug.\") or key == \"werkzeug\":\n            sys.modules.pop(key, None)\n    import werkzeug\n    for key in werkzeug.__all__:\n        setattr(wz, key, getattr(werkzeug, key))\n    hg_tag = find_hg_tag(path)\n    try:\n        f = open(os.path.join(path, \"setup.py\"))\n    except IOError:\n        pass\n    else:\n        try:\n            for line in f:\n                line = line.strip()\n                if line.startswith(\"version=\"):\n                    return line[8:].strip(\" \\t,\")[1:-1], hg_tag\n        finally:\n            f.close()\n    print(\"Unknown werkzeug version loaded\", file=sys.stderr)\n    sys.exit(2)",
    "docstring": "Load werkzeug."
  },
  {
    "code": "def warp_object(self, tileMapObj):\n        print \"Collision\"\n        if tileMapObj.can_warp:\n            if self.map_association != self.exitWarp.map_association:\n                TileMapManager.load(exitWarp.map_association)\n            tileMapObj.parent.coords = self.exitWarp.coords",
    "docstring": "Warp the tile map object from one warp to another."
  },
  {
    "code": "def writeline(self, data):\n        try:\n            if self.ch_mode:\n                data += \"\\n\"\n                parts = split_by_n(data, self.ch_mode_chunk_size)\n                for split_str in parts:\n                    self.port.write(split_str.encode())\n                    time.sleep(self.ch_mode_ch_delay)\n            else:\n                self.port.write((data + \"\\n\").encode())\n        except SerialException as err:\n            self.logger.exception(\"SerialError occured while trying to write data {}.\".format(data))\n            raise RuntimeError(str(err))",
    "docstring": "Writes data to serial port.\n\n        :param data: Data to write\n        :return: Nothing\n        :raises: IOError if SerialException occurs."
  },
  {
    "code": "def delete(self, option):\n        if self.config is not None:\n            if option in self.config:\n                del self.config[option]",
    "docstring": "Deletes an option if exists"
  },
  {
    "code": "def user_can_delete_attachments(self):\n        context = self.context\n        user = api.get_current_user()\n        if not self.is_ar_editable():\n            return False\n        return (self.user_can_add_attachments() and\n                not user.allowed(context, [\"Client\"])) or \\\n            self.user_can_update_attachments()",
    "docstring": "Checks if the current logged in user is allowed to delete attachments"
  },
  {
    "code": "def _collect_cpu_info(run_info):\n  cpu_info = {}\n  cpu_info[\"num_cores\"] = multiprocessing.cpu_count()\n  import cpuinfo\n  info = cpuinfo.get_cpu_info()\n  cpu_info[\"cpu_info\"] = info[\"brand\"]\n  cpu_info[\"mhz_per_cpu\"] = info[\"hz_advertised_raw\"][0] / 1.0e6\n  run_info[\"machine_config\"][\"cpu_info\"] = cpu_info",
    "docstring": "Collect the CPU information for the local environment."
  },
  {
    "code": "def legend(self, values):\n        if not isinstance(values, list):\n            raise TypeError(\"legend must be a list of labels\")\n        self.options[\"legend\"] = values",
    "docstring": "Set the legend labels.\n\n            Args:\n                values (list): list of labels.\n\n            Raises:\n                ValueError: legend must be a list of labels."
  },
  {
    "code": "def store_meta_data(self, copy_path=None):\n        if copy_path:\n            meta_file_path_json = os.path.join(copy_path, self.state.get_storage_path(), storage.FILE_NAME_META_DATA)\n        else:\n            if self.state.file_system_path is None:\n                logger.error(\"Meta data of {0} can be stored temporary arbitrary but by default first after the \"\n                             \"respective state was stored and a file system path is set.\".format(self))\n                return\n            meta_file_path_json = os.path.join(self.state.file_system_path, storage.FILE_NAME_META_DATA)\n        meta_data = deepcopy(self.meta)\n        self._generate_element_meta_data(meta_data)\n        storage_utils.write_dict_to_json(meta_data, meta_file_path_json)",
    "docstring": "Save meta data of state model to the file system\n\n        This method generates a dictionary of the meta data of the state together with the meta data of all state\n        elements (data ports, outcomes, etc.) and stores it on the filesystem.\n        Secure that the store meta data method is called after storing the core data otherwise the last_stored_path is\n        maybe wrong or None.\n        The copy path is considered to be a state machine file system path but not the current one but e.g.\n        of a as copy saved state machine. The meta data will be stored in respective relative state folder in the state\n        machine  hierarchy. This folder has to exist.\n        Dues the core elements of the state machine has to be stored first.\n\n        :param str copy_path: Optional copy path if meta data is not stored to the file system path of state machine"
  },
  {
    "code": "def reset_status(self):\n        for row in range(self.table.rowCount()):\n            status_item = self.table.item(row, 1)\n            status_item.setText(self.tr(''))",
    "docstring": "Set all scenarios' status to empty in the table."
  },
  {
    "code": "def _asdict(self):\n    with self._cond:\n      if self._prompt is None:\n        return\n      return {'id': self._prompt.id,\n              'message': self._prompt.message,\n              'text-input': self._prompt.text_input}",
    "docstring": "Return a dictionary representation of the current prompt."
  },
  {
    "code": "def parse(self, debug=False):\n        if self._parsed is None:\n            try:\n                if self._mode == \"html\":\n                    self._parsed = self.html(self._content, self._show_everything, self._translation)\n                else:\n                    self._parsed = self.rst(self._content, self._show_everything, self._translation, debug=debug)\n            except Exception as e:\n                if debug:\n                    raise BaseException(\"Parsing failed\") from e\n                else:\n                    self._parsed = self._translation.gettext(\"<b>Parsing failed</b>: <pre>{}</pre>\").format(html.escape(self._content))\n        return self._parsed",
    "docstring": "Returns parsed text"
  },
  {
    "code": "def start_stream(self):\n        tracking_terms = self.term_checker.tracking_terms()\n        if len(tracking_terms) > 0 or self.unfiltered:\n            self.stream = tweepy.Stream(self.auth, self.listener,\n                                        stall_warnings=True,\n                                        timeout=90,\n                                        retry_count=self.retry_count)\n            if len(tracking_terms) > 0:\n                logger.info(\"Starting new twitter stream with %s terms:\", len(tracking_terms))\n                logger.info(\"  %s\", repr(tracking_terms))\n                self.stream.filter(track=tracking_terms, async=True, languages=self.languages)\n            else:\n                logger.info(\"Starting new unfiltered stream\")\n                self.stream.sample(async=True, languages=self.languages)",
    "docstring": "Starts a stream with teh current tracking terms"
  },
  {
    "code": "def _remove_duplicate_files(xs):\n    seen = set([])\n    out = []\n    for x in xs:\n        if x[\"path\"] not in seen:\n            out.append(x)\n            seen.add(x[\"path\"])\n    return out",
    "docstring": "Remove files specified multiple times in a list."
  },
  {
    "code": "def equals(self,junc):\n    if self.left.equals(junc.left): return False\n    if self.right.equals(junc.right): return False\n    return True",
    "docstring": "test equality with another junction"
  },
  {
    "code": "def l2_regularizer(weight=1.0, scope=None):\n  def regularizer(tensor):\n    with tf.name_scope(scope, 'L2Regularizer', [tensor]):\n      l2_weight = tf.convert_to_tensor(weight,\n                                       dtype=tensor.dtype.base_dtype,\n                                       name='weight')\n      return tf.multiply(l2_weight, tf.nn.l2_loss(tensor), name='value')\n  return regularizer",
    "docstring": "Define a L2 regularizer.\n\n  Args:\n    weight: scale the loss by this factor.\n    scope: Optional scope for name_scope.\n\n  Returns:\n    a regularizer function."
  },
  {
    "code": "def _set_directories(self):\n        if self._dirs['initial'] == None:\n            self._dirs['base'] = discover_base_dir(self._dirs['run'])  \n        else:\n            self._dirs['base'] = discover_base_dir(self._dirs['initial'])  \n        self._update_dirs_on_base()\n        self._tree_ready = verify_dir_structure(self._dirs['base'])\n        if self._tree_ready:\n            self._read_site_config()",
    "docstring": "Initialize variables based on evidence about the directories."
  },
  {
    "code": "def download(self, filename=None):\n        if filename is None:\n            filename = self.name\n        with self.remote_open() as infile:\n            with open(filename, 'wb') as outfile:\n                outfile.write(infile.read())",
    "docstring": "Download the dataset to a local file.\n\n        Parameters\n        ----------\n        filename : str, optional\n            The full path to which the dataset will be saved"
  },
  {
    "code": "def containment_angle_bin(self, egy_bins, fraction=0.68, scale_fn=None):\n        vals = self.interp_bin(egy_bins, self.dtheta, scale_fn=scale_fn)\n        dtheta = np.radians(self.dtheta[:, np.newaxis] * np.ones(vals.shape))\n        return self._calc_containment(dtheta, vals, fraction)",
    "docstring": "Evaluate the PSF containment angle averaged over energy bins."
  },
  {
    "code": "def smove(self, src, dst, value):\n        src_set = self._get_set(src, 'SMOVE')\n        dst_set = self._get_set(dst, 'SMOVE')\n        value = self._encode(value)\n        if value not in src_set:\n            return False\n        src_set.discard(value)\n        dst_set.add(value)\n        self.redis[self._encode(src)], self.redis[self._encode(dst)] = src_set, dst_set\n        return True",
    "docstring": "Emulate smove."
  },
  {
    "code": "def get_nodes(self, request):\n        nodes = []\n        nodes.append(NavigationNode(_('Tags'), reverse('zinnia:tag_list'),\n                                    'tags'))\n        for tag in tags_published():\n            nodes.append(NavigationNode(tag.name,\n                                        reverse('zinnia:tag_detail',\n                                                args=[tag.name]),\n                                        tag.pk, 'tags'))\n        return nodes",
    "docstring": "Return menu's node for tags"
  },
  {
    "code": "def deactivate_mfa_device(self, user_name, serial_number):\n        user = self.get_user(user_name)\n        if serial_number not in user.mfa_devices:\n            raise IAMNotFoundException(\n                \"Device {0} not found\".format(serial_number)\n            )\n        user.deactivate_mfa_device(serial_number)",
    "docstring": "Deactivate and detach MFA Device from user if device exists."
  },
  {
    "code": "def _HandleHelp(self, request):\n    help_path = request.path.split(\"/\", 2)[-1]\n    if not help_path:\n      raise werkzeug_exceptions.Forbidden(\"Error: Invalid help path.\")\n    return self._RedirectToRemoteHelp(help_path)",
    "docstring": "Handles help requests."
  },
  {
    "code": "def install_monitor(self, monitor_pattern: str, monitor_stat_func_name: str):\n        self._monitor = mx.monitor.Monitor(interval=C.MEASURE_SPEED_EVERY,\n                                           stat_func=C.MONITOR_STAT_FUNCS.get(monitor_stat_func_name),\n                                           pattern=monitor_pattern,\n                                           sort=True)\n        self.module.install_monitor(self._monitor)\n        logger.info(\"Installed MXNet monitor; pattern='%s'; statistics_func='%s'\",\n                    monitor_pattern, monitor_stat_func_name)",
    "docstring": "Installs an MXNet monitor onto the underlying module.\n\n        :param monitor_pattern: Pattern string.\n        :param monitor_stat_func_name: Name of monitor statistics function."
  },
  {
    "code": "def setup_ui(self, ):\n        self.main_vbox = QtGui.QVBoxLayout(self)\n        self.import_all_references_cb = QtGui.QCheckBox(\"Import references\")\n        self.main_vbox.addWidget(self.import_all_references_cb)",
    "docstring": "Create all ui elements and layouts\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def save_coeffs(coeffs, out_dir=''):\n    for platform in coeffs.keys():\n        fname = os.path.join(out_dir, \"%s_calibration_data.h5\" % platform)\n        fid = h5py.File(fname, 'w')\n        for chan in coeffs[platform].keys():\n            fid.create_group(chan)\n            fid[chan]['datetime'] = coeffs[platform][chan]['datetime']\n            fid[chan]['slope1'] = coeffs[platform][chan]['slope1']\n            fid[chan]['intercept1'] = coeffs[platform][chan]['intercept1']\n            fid[chan]['slope2'] = coeffs[platform][chan]['slope2']\n            fid[chan]['intercept2'] = coeffs[platform][chan]['intercept2']\n        fid.close()\n        print \"Calibration coefficients saved for %s\" % platform",
    "docstring": "Save calibration coefficients to HDF5 files."
  },
  {
    "code": "def ad_hoc_magic_from_file(filename, **kwargs):\n    with open(filename, 'rb') as stream:\n        head = stream.read(16)\n        if head[:4] == b'\\x7fELF':\n            return b'application/x-executable'\n        elif head[:2] == b'MZ':\n            return b'application/x-dosexec'\n        else:\n            raise NotImplementedError()",
    "docstring": "Ad-hoc emulation of magic.from_file from python-magic."
  },
  {
    "code": "def get_data_files(dname, ignore=None, parent=None):\n    parent = parent or \".\"\n    ignore = ignore or []\n    result = []\n    for directory, subdirectories, filenames in os.walk(dname):\n        resultfiles = []\n        for exname in EXCLUDE_NAMES:\n            if exname in subdirectories:\n                subdirectories.remove(exname)\n        for ig in ignore:\n            if ig in subdirectories:\n                subdirectories.remove(ig)\n        for filename in _filter_names(filenames):\n            resultfiles.append(filename)\n        if resultfiles:\n            for filename in resultfiles:\n                file_path = os.path.join(directory, filename)\n                if parent:\n                    file_path = file_path.replace(parent + os.sep, '')\n                result.append(file_path)\n    return result",
    "docstring": "Get all the data files that should be included in this distutils Project.\n\n    'dname' should be the path to the package that you're distributing.\n\n    'ignore' is a list of sub-packages to ignore.  This facilitates\n    disparate package hierarchies.  That's a fancy way of saying that\n    the 'twisted' package doesn't want to include the 'twisted.conch'\n    package, so it will pass ['conch'] as the value.\n\n    'parent' is necessary if you're distributing a subpackage like\n    twisted.conch.  'dname' should point to 'twisted/conch' and 'parent'\n    should point to 'twisted'.  This ensures that your data_files are\n    generated correctly, only using relative paths for the first element\n    of the tuple ('twisted/conch/*').\n    The default 'parent' is the current working directory."
  },
  {
    "code": "def get_fieldsets(self, request, obj=None):\n        fieldsets = list(super(CreateUpdateAdmin, self).get_fieldsets(\n            request=request, obj=obj))\n        fields = set()\n        to_add = set()\n        for fs in fieldsets:\n            fields = fields.union(fs[1]['fields'])\n        for k, v in self.ownership_info['fields'].items():\n            if (hasattr(self.model, k)\n                    and k not in fields\n                    and (not self.exclude\n                         or (self.exclude and k not in self.exclude))):\n                if ('readonly' in v and not v['readonly']) or obj:\n                    to_add.add(k)\n        if len(to_add) > 0:\n            fieldsets.append((self.ownership_info['label'],\n                              {'fields': tuple(to_add)}))\n        return tuple(fieldsets)",
    "docstring": "Add ownership info fields in fieldset with proper separation.\n\n        Author: Himanshu Shankar (https://himanshus.com)"
  },
  {
    "code": "def auth(self, transport, account_name, password):\n        auth_token = AuthToken()\n        auth_token.account_name = account_name\n        attrs = {sconstant.A_BY: sconstant.V_NAME}\n        account = SOAPpy.Types.stringType(data=account_name, attrs=attrs)\n        params = {sconstant.E_ACCOUNT: account,\n                  sconstant.E_PASSWORD: password}\n        self.log.debug('Authenticating account %s' % account_name)\n        try:\n            res = transport.invoke(zconstant.NS_ZIMBRA_ACC_URL,\n                                   sconstant.AuthRequest,\n                                   params,\n                                   auth_token)\n        except SoapException as exc:\n            raise AuthException(unicode(exc), exc)\n        auth_token.token = res.authToken\n        if hasattr(res, 'sessionId'):\n            auth_token.session_id = res.sessionId\n        self.log.info('Authenticated account %s, session id %s'\n                      % (account_name, auth_token.session_id))\n        return auth_token",
    "docstring": "Authenticates using username and password."
  },
  {
    "code": "def collect_info(self):\n        try:\n            info = {}\n            res = self._send_request('GET', \"/\")\n            info['server'] = {}\n            info['server']['name'] = res['name']\n            info['server']['version'] = res['version']\n            info['allinfo'] = res\n            info['status'] = self.cluster.status()\n            info['aliases'] = self.indices.aliases()\n            self.info = info\n            return True\n        except:\n            self.info = {}\n            return False",
    "docstring": "Collect info about the connection and fill the info dictionary."
  },
  {
    "code": "def update_DOM(self):\n        response = self.fetch()\n        self._DOM = html.fromstring(response.text)\n        return self",
    "docstring": "Makes a request and updates `self._DOM`.\n        Worth using only if you manually change `self.base_url` or `self.path`.\n\n        :return: self\n        :rtype: Url"
  },
  {
    "code": "def reset():\n    if hasattr(ray.worker.global_worker, \"signal_counters\"):\n        ray.worker.global_worker.signal_counters = defaultdict(lambda: b\"0\")",
    "docstring": "Reset the worker state associated with any signals that this worker\n    has received so far.\n\n    If the worker calls receive() on a source next, it will get all the\n    signals generated by that source starting with index = 1."
  },
  {
    "code": "def onex(self):\n        xCols=[i for i in range(self.nCols) if self.colTypes[i]==3]\n        if len(xCols)>1:\n            for colI in xCols[1:][::-1]:\n                self.colDelete(colI)",
    "docstring": "delete all X columns except the first one."
  },
  {
    "code": "def set_next_page_params(self):\n        if self.items:\n            index = self.get_last_item_index()\n            self.params[self.mode] = self.get_next_page_param(self.items[index])",
    "docstring": "Set the params so that the next page is fetched."
  },
  {
    "code": "def runlist_add_app(name, app, profile, force, **kwargs):\n    ctx = Context(**kwargs)\n    ctx.execute_action('runlist:add-app', **{\n        'storage': ctx.repo.create_secure_service('storage'),\n        'name': name,\n        'app': app,\n        'profile': profile,\n        'force': force\n    })",
    "docstring": "Add specified application with profile to the specified runlist.\n\n    Existence of application or profile is not checked."
  },
  {
    "code": "def in_coord_list_pbc(fcoord_list, fcoord, atol=1e-8):\n    return len(find_in_coord_list_pbc(fcoord_list, fcoord, atol=atol)) > 0",
    "docstring": "Tests if a particular fractional coord is within a fractional coord_list.\n\n    Args:\n        fcoord_list: List of fractional coords to test\n        fcoord: A specific fractional coord to test.\n        atol: Absolute tolerance. Defaults to 1e-8.\n\n    Returns:\n        True if coord is in the coord list."
  },
  {
    "code": "def update_state_active(self):\n        self.update_state(self.links[REF_UPDATE_STATE_ACTIVE], {'type' : RUN_ACTIVE})\n        return self.refresh()",
    "docstring": "Update the state of the model run to active.\n\n        Raises an exception if update fails or resource is unknown.\n\n        Returns\n        -------\n        ModelRunHandle\n            Refreshed run handle."
  },
  {
    "code": "def is_this_year(self):\n        return is_current_year(datetime.datetime.combine(self.date, datetime.time()))",
    "docstring": "Return whether the block occurs after September 1st of this school year."
  },
  {
    "code": "def detect_pattern_format(pattern_filename, encoding, on_word_boundaries):\n    tsv = True\n    boundaries = on_word_boundaries\n    with open_file(pattern_filename) as input_file:\n        for line in input_file:\n            line = line.decode(encoding)\n            if line.count('\\t') != 1:\n                tsv = False\n            if '\\\\b' in line:\n                boundaries = True\n            if boundaries and not tsv:\n                break\n    return tsv, boundaries",
    "docstring": "Automatically detects the pattern file format, and determines\n    whether the Aho-Corasick string matching should pay attention to\n    word boundaries or not.\n\n    Arguments:\n    - `pattern_filename`:\n    - `encoding`:\n    - `on_word_boundaries`:"
  },
  {
    "code": "def serialize(material_description):\n    material_description_bytes = bytearray(_MATERIAL_DESCRIPTION_VERSION)\n    for name, value in sorted(material_description.items(), key=lambda x: x[0]):\n        try:\n            material_description_bytes.extend(encode_value(to_bytes(name)))\n            material_description_bytes.extend(encode_value(to_bytes(value)))\n        except (TypeError, struct.error):\n            raise InvalidMaterialDescriptionError(\n                'Invalid name or value in material description: \"{name}\"=\"{value}\"'.format(name=name, value=value)\n            )\n    return {Tag.BINARY.dynamodb_tag: bytes(material_description_bytes)}",
    "docstring": "Serialize a material description dictionary into a DynamodDB attribute.\n\n    :param dict material_description: Material description dictionary\n    :returns: Serialized material description as a DynamoDB binary attribute value\n    :rtype: dict\n    :raises InvalidMaterialDescriptionError: if invalid name or value found in material description"
  },
  {
    "code": "def parse_name(name):\n    inverted, op = False, OP_EQ\n    if name is not None:\n        for op_ in (OP_NIN, OP_IN, OP_NOT, OP_LIKE):\n            if name.endswith(op_):\n                op = op_\n                name = name[:len(name) - len(op)]\n                break\n        if name.startswith('!'):\n            inverted = True\n            name = name[1:]\n    return name, inverted, op",
    "docstring": "Split a query name into field name, operator and whether it is\n    inverted."
  },
  {
    "code": "def Gamma(cls,\n            shape: 'TensorFluent',\n            scale: 'TensorFluent',\n            batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']:\n        if shape.scope != scale.scope:\n            raise ValueError('Gamma distribution: parameters must have same scope!')\n        concentration = shape.tensor\n        rate = 1 / scale.tensor\n        dist = tf.distributions.Gamma(concentration, rate)\n        batch = shape.batch or scale.batch\n        if not batch and batch_size is not None:\n            t = dist.sample(batch_size)\n            batch = True\n        else:\n            t = dist.sample()\n        scope = shape.scope.as_list()\n        return (dist, TensorFluent(t, scope, batch=batch))",
    "docstring": "Returns a TensorFluent for the Gamma sampling op with given shape and scale parameters.\n\n        Args:\n            shape: The shape parameter of the Gamma distribution.\n            scale: The scale parameter of the Gamma distribution.\n            batch_size: The size of the batch (optional).\n\n        Returns:\n            The Gamma distribution and a TensorFluent sample drawn from the distribution.\n\n        Raises:\n            ValueError: If parameters do not have the same scope."
  },
  {
    "code": "def fitness_vs(self):\n        \"Median Fitness in the validation set\"\n        l = [x.fitness_vs for x in self.models]\n        return np.median(l)",
    "docstring": "Median Fitness in the validation set"
  },
  {
    "code": "def cache(self, refreshing=None, next_action=None, data_blob=None, json_last_refresh=None, rollback_point=False):\n        LOGGER.debug(\"InjectorComponentSkeleton.cache\")\n        if json_last_refresh is None:\n            json_last_refresh = datetime.datetime.now()\n        if rollback_point:\n            self.rollback_point_refreshing = refreshing\n            self.rollback_point_next_action = next_action\n            self.rollback_point_data_blob = data_blob\n            self.rollback_point_refreshing = refreshing\n        return self.component_cache_actor.save(refreshing=refreshing, next_action=next_action,\n                                               json_last_refresh=json_last_refresh, data_blob=data_blob).get()",
    "docstring": "push this component into the cache\n\n        :param refreshing: the new refreshing value\n        :param next_action: the new next action value\n        :param data_blob: the new data blob value\n        :param json_last_refresh: the new json last refresh value - if None the date of this call\n        :param rollback_point: define the rollback point with provided values (refreshing, next_action, data_blob and\n        json_last_refresh)\n        :return:"
  },
  {
    "code": "def to_params(self):\n        params = {}\n        for name in self.PROPERTIES:\n            attr = '_{0}'.format(name)\n            value = getattr(self, attr, None) or getattr(self, name, None)\n            if value is None:\n                continue\n            if isinstance(value, datetime):\n                params[name] = format_time(value)\n            elif isinstance(value, list):\n                params[name] = ','.join(map(str, value))\n            elif isinstance(value, bool):\n                params[name] = str(value).lower()\n            else:\n                params[name] = value\n        return params",
    "docstring": "Generates a Hash of property values for the current object. This helper\n        handles all necessary type coercions as it generates its output."
  },
  {
    "code": "def ListGrrUsers(self):\n    args = user_management_pb2.ApiListGrrUsersArgs()\n    items = self._context.SendIteratorRequest(\"ListGrrUsers\", args)\n    return utils.MapItemsIterator(\n        lambda data: GrrUser(data=data, context=self._context), items)",
    "docstring": "Lists all registered GRR users."
  },
  {
    "code": "def stage_subset(self, *files_to_add: str):\n        LOGGER.info('staging files: %s', files_to_add)\n        self.repo.git.add(*files_to_add, A=True)",
    "docstring": "Stages a subset of files\n\n        :param files_to_add: files to stage\n        :type files_to_add: str"
  },
  {
    "code": "def setCurrentIndex(self, index):\n        if self._currentIndex == index:\n            return\n        self._currentIndex = index\n        self.currentIndexChanged.emit(index)\n        for i, item in enumerate(self.items()):\n            item.setMenuEnabled(i == index)\n        self.repaint()",
    "docstring": "Sets the current item to the item at the inputed index.\n\n        :param      index | <int>"
  },
  {
    "code": "def import_package(rel_path_to_package, package_name):\n    try:\n        curr_dir = os.path.dirname(os.path.realpath(__file__))\n    except NameError:\n        curr_dir = os.path.dirname(os.path.realpath(os.getcwd()))\n    package_path = os.path.join(curr_dir, rel_path_to_package)\n    if package_path not in sys.path:\n        sys.path = [package_path] + sys.path\n    package = __import__(package_name)\n    return package",
    "docstring": "Imports a python package into the current namespace.\n\n    Parameters\n    ----------\n    rel_path_to_package : str\n        Path to the package containing director relative from this script's\n        directory.\n    package_name : str\n        The name of the package to be imported.\n\n    Returns\n    ---------\n    package : The imported package object."
  },
  {
    "code": "def profiles(self):\n        raw_profiles = self.account.service.management().profiles().list(\n            accountId=self.account.id,\n            webPropertyId=self.id).execute()['items']\n        profiles = [Profile(raw, self) for raw in raw_profiles]\n        return addressable.List(profiles, indices=['id', 'name'], insensitive=True)",
    "docstring": "A list of all profiles on this web property. You may\n        select a specific profile using its name, its id\n        or an index.\n\n        ```python\n        property.profiles[0]\n        property.profiles['9234823']\n        property.profiles['marketing profile']\n        ```"
  },
  {
    "code": "def get_max_events_in_both_arrays(events_one, events_two):\n    events_one = np.ascontiguousarray(events_one)\n    events_two = np.ascontiguousarray(events_two)\n    event_result = np.empty(shape=(events_one.shape[0] + events_two.shape[0], ), dtype=events_one.dtype)\n    count = analysis_functions.get_max_events_in_both_arrays(events_one, events_two, event_result)\n    return event_result[:count]",
    "docstring": "Calculates the maximum count of events that exist in both arrays."
  },
  {
    "code": "def merge_all_cells(cells):\n    current = 0\n    while len(cells) > 1:\n        count = 0\n        while count < len(cells):\n            cell1 = cells[current]\n            cell2 = cells[count]\n            merge_direction = get_merge_direction(cell1, cell2)\n            if not merge_direction == \"NONE\":\n                merge_cells(cell1, cell2, merge_direction)\n                if current > count:\n                    current -= 1\n                cells.pop(count)\n            else:\n                count += 1\n        current += 1\n        if current >= len(cells):\n            current = 0\n    return cells[0].text",
    "docstring": "Loop through list of cells and piece them together one by one\n\n    Parameters\n    ----------\n    cells : list of dashtable.data2rst.Cell\n\n    Returns\n    -------\n    grid_table : str\n        The final grid table"
  },
  {
    "code": "def Disks(self):\n\t\tif not self.disks:  self.disks = clc.v2.Disks(server=self,disks_lst=self.data['details']['disks'],session=self.session)\n\t\treturn(self.disks)",
    "docstring": "Return disks object associated with server.\n\n\t\t>>> clc.v2.Server(\"WA1BTDIX01\").Disks()\n\t\t<clc.APIv2.disk.Disks object at 0x10feea190>"
  },
  {
    "code": "def handle_initialize(self, data):\n        logger.info('start to handle_initialize')\n        self.handle_update_search_space(data)\n        if self.search_space:\n            self.cg = CG_BOHB(configspace=self.search_space,\n                              min_points_in_model=self.min_points_in_model,\n                              top_n_percent=self.top_n_percent,\n                              num_samples=self.num_samples,\n                              random_fraction=self.random_fraction,\n                              bandwidth_factor=self.bandwidth_factor,\n                              min_bandwidth=self.min_bandwidth)\n        else:\n            raise ValueError('Error: Search space is None')\n        self.generate_new_bracket()\n        send(CommandType.Initialized, '')",
    "docstring": "Initialize Tuner, including creating Bayesian optimization-based parametric models \n        and search space formations\n\n        Parameters\n        ----------\n        data: search space\n            search space of this experiment\n\n        Raises\n        ------\n        ValueError\n            Error: Search space is None"
  },
  {
    "code": "def publish_proto_in_ipfs(self):\n        ipfs_hash_base58 = utils_ipfs.publish_proto_in_ipfs(self._get_ipfs_client(), self.args.protodir)\n        self._printout(ipfs_hash_base58)",
    "docstring": "Publish proto files in ipfs and print hash"
  },
  {
    "code": "def trt_pmf(matrices):\n    ntrts, nmags, ndists, nlons, nlats, neps = matrices.shape\n    pmf = numpy.zeros(ntrts)\n    for t in range(ntrts):\n        pmf[t] = 1. - numpy.prod(\n            [1. - matrices[t, i, j, k, l, m]\n             for i in range(nmags)\n             for j in range(ndists)\n             for k in range(nlons)\n             for l in range(nlats)\n             for m in range(neps)])\n    return pmf",
    "docstring": "Fold full disaggregation matrix to tectonic region type PMF.\n\n    :param matrices:\n        a matrix with T submatrices\n    :returns:\n        an array of T probabilities one per each tectonic region type"
  },
  {
    "code": "def from_json(cls, json):\n    obj = cls(key_range.KeyRange.from_json(json[\"key_range\"]),\n              model.QuerySpec.from_json(json[\"query_spec\"]))\n    cursor = json[\"cursor\"]\n    if cursor and json[\"cursor_object\"]:\n      obj._cursor = datastore_query.Cursor.from_websafe_string(cursor)\n    else:\n      obj._cursor = cursor\n    return obj",
    "docstring": "Reverse of to_json."
  },
  {
    "code": "def allReadGroups(self):\n        for dataset in self.getDatasets():\n            for readGroupSet in dataset.getReadGroupSets():\n                for readGroup in readGroupSet.getReadGroups():\n                    yield readGroup",
    "docstring": "Return an iterator over all read groups in the data repo"
  },
  {
    "code": "def summary_pairwise_indices(self):\n        summary_pairwise_indices = np.empty(\n            self.values[0].t_stats.shape[1], dtype=object\n        )\n        summary_pairwise_indices[:] = [\n            sig.summary_pairwise_indices for sig in self.values\n        ]\n        return summary_pairwise_indices",
    "docstring": "ndarray containing tuples of pairwise indices for the column summary."
  },
  {
    "code": "def check_gcdt_update():\n    try:\n        inst_version, latest_version = get_package_versions('gcdt')\n        if inst_version < latest_version:\n            log.warn('Please consider an update to gcdt version: %s' %\n                                 latest_version)\n    except GracefulExit:\n        raise\n    except Exception:\n        log.warn('PyPi appears to be down - we currently can\\'t check for newer gcdt versions')",
    "docstring": "Check whether a newer gcdt is available and output a warning."
  },
  {
    "code": "def plot_dot_graph(graph, filename=None):\n    if not plot.pygraphviz_available:\n        logger.error(\"Pygraphviz is not installed, cannot generate graph plot!\")\n        return\n    if not plot.PIL_available:\n        logger.error(\"PIL is not installed, cannot display graph plot!\")\n        return\n    agraph = AGraph(graph)\n    agraph.layout(prog='dot')\n    if filename is None:\n        filename = tempfile.mktemp(suffix=\".png\")\n    agraph.draw(filename)\n    image = Image.open(filename)\n    image.show()",
    "docstring": "Plots a graph in graphviz dot notation.\n\n    :param graph: the dot notation graph\n    :type graph: str\n    :param filename: the (optional) file to save the generated plot to. The extension determines the file format.\n    :type filename: str"
  },
  {
    "code": "def from_point(cls, point):\n        return cls(point.latitude, point.longitude, point.altitude)",
    "docstring": "Create and return a new ``Point`` instance from another ``Point``\n        instance."
  },
  {
    "code": "def edit(self):\n\t\tself.changed = False\n\t\twith self:\n\t\t\teditor = self.get_editor()\n\t\t\tcmd = [editor, self.name]\n\t\t\ttry:\n\t\t\t\tres = subprocess.call(cmd)\n\t\t\texcept Exception as e:\n\t\t\t\tprint(\"Error launching editor %(editor)s\" % locals())\n\t\t\t\tprint(e)\n\t\t\t\treturn\n\t\t\tif res != 0:\n\t\t\t\tmsg = '%(editor)s returned error status %(res)d' % locals()\n\t\t\t\traise EditProcessException(msg)\n\t\t\tnew_data = self.read()\n\t\t\tif new_data != self.data:\n\t\t\t\tself.changed = self._save_diff(self.data, new_data)\n\t\t\t\tself.data = new_data",
    "docstring": "Edit the file"
  },
  {
    "code": "def acquire_value_set(self, *tags):\n        setname = self._acquire_value_set(*tags)\n        if setname is None:\n            raise ValueError(\"Could not aquire a value set\")\n        return setname",
    "docstring": "Reserve a set of values for this execution.\n        No other process can reserve the same set of values while the set is\n        reserved. Acquired value set needs to be released after use to allow\n        other processes to access it.\n        Add tags to limit the possible value sets that this returns."
  },
  {
    "code": "def asDict(self):\n        d = {}\n        for k, v in self.items():\n            d[k] = v\n        return d",
    "docstring": "Return the Lib as a ``dict``.\n\n        This is a backwards compatibility method."
  },
  {
    "code": "def maybe_infer_tz(tz, inferred_tz):\n    if tz is None:\n        tz = inferred_tz\n    elif inferred_tz is None:\n        pass\n    elif not timezones.tz_compare(tz, inferred_tz):\n        raise TypeError('data is already tz-aware {inferred_tz}, unable to '\n                        'set specified tz: {tz}'\n                        .format(inferred_tz=inferred_tz, tz=tz))\n    return tz",
    "docstring": "If a timezone is inferred from data, check that it is compatible with\n    the user-provided timezone, if any.\n\n    Parameters\n    ----------\n    tz : tzinfo or None\n    inferred_tz : tzinfo or None\n\n    Returns\n    -------\n    tz : tzinfo or None\n\n    Raises\n    ------\n    TypeError : if both timezones are present but do not match"
  },
  {
    "code": "def boundary(self):\n        return (int(self.WESTERNMOST_LONGITUDE),\n                int(self.EASTERNMOST_LONGITUDE),\n                int(self.MINIMUM_LATITUDE),\n                int(self.MAXIMUM_LATITUDE))",
    "docstring": "Get the image boundary\n\n        Returns:\n            A tupple composed by the westernmost_longitude,\n            the westernmost_longitude, the minimum_latitude and\n            the maximum_latitude."
  },
  {
    "code": "def get_ws_endpoint(self, private=False):\n        path = 'bullet-public'\n        signed = private\n        if private:\n            path = 'bullet-private'\n        return self._post(path, signed)",
    "docstring": "Get websocket channel details\n\n        :param private: Name of symbol e.g. KCS-BTC\n        :type private: bool\n\n        https://docs.kucoin.com/#websocket-feed\n\n        .. code:: python\n\n            ws_details = client.get_ws_endpoint(private=True)\n\n        :returns: ApiResponse\n\n        .. code:: python\n\n            {\n                \"code\": \"200000\",\n                \"data\": {\n                    \"instanceServers\": [\n                        {\n                            \"pingInterval\": 50000,\n                            \"endpoint\": \"wss://push1-v2.kucoin.net/endpoint\",\n                            \"protocol\": \"websocket\",\n                            \"encrypt\": true,\n                            \"pingTimeout\": 10000\n                        }\n                    ],\n                    \"token\": \"vYNlCtbz4XNJ1QncwWilJnBtmmfe4geLQDUA62kKJsDChc6I4bRDQc73JfIrlFaVYIAE0Gv2--MROnLAgjVsWkcDq_MuG7qV7EktfCEIphiqnlfpQn4Ybg==.IoORVxR2LmKV7_maOR9xOg==\"\n                }\n            }\n\n        :raises: KucoinResponseException, KucoinAPIException"
  },
  {
    "code": "def getReference(self, id_):\n        if id_ not in self._referenceIdMap:\n            raise exceptions.ReferenceNotFoundException(id_)\n        return self._referenceIdMap[id_]",
    "docstring": "Returns the Reference with the specified ID or raises a\n        ReferenceNotFoundException if it does not exist."
  },
  {
    "code": "def list_branch(self, repo_name):\n        req = proto.ListBranchRequest(repo=proto.Repo(name=repo_name))\n        res = self.stub.ListBranch(req, metadata=self.metadata)\n        if hasattr(res, 'branch_info'):\n            return res.branch_info\n        return []",
    "docstring": "Lists the active Branch objects on a Repo.\n\n        Params:\n        * repo_name: The name of the repo."
  },
  {
    "code": "def calc_expectation(grad_dict, num_batches):\n    for key in grad_dict.keys():\n        grad_dict[str.format(key+\"_expectation\")] = mx.ndarray.sum(grad_dict[key], axis=0) / num_batches\n    return grad_dict",
    "docstring": "Calculates the expectation of the gradients per epoch for each parameter w.r.t number of batches\n\n    Parameters\n    ----------\n    grad_dict: dict\n        dictionary that maps parameter name to gradients in the mod executor group\n    num_batches: int\n        number of batches\n\n    Returns\n    ----------\n    grad_dict: dict\n        dictionary with new keys mapping to gradients expectations"
  },
  {
    "code": "def to_dict(self):\n        return {\n            'primitives': self.primitives,\n            'init_params': self.init_params,\n            'input_names': self.input_names,\n            'output_names': self.output_names,\n            'hyperparameters': self.get_hyperparameters(),\n            'tunable_hyperparameters': self._tunable_hyperparameters\n        }",
    "docstring": "Return all the details of this MLPipeline in a dict.\n\n        The dict structure contains all the `__init__` arguments of the\n        MLPipeline, as well as the current hyperparameter values and the\n        specification of the tunable_hyperparameters::\n\n            {\n                \"primitives\": [\n                    \"a_primitive\",\n                    \"another_primitive\"\n                ],\n                \"init_params\": {\n                    \"a_primitive\": {\n                        \"an_argument\": \"a_value\"\n                    }\n                },\n                \"hyperparameters\": {\n                    \"a_primitive#1\": {\n                        \"an_argument\": \"a_value\",\n                        \"another_argument\": \"another_value\",\n                    },\n                    \"another_primitive#1\": {\n                        \"yet_another_argument\": \"yet_another_value\"\n                     }\n                },\n                \"tunable_hyperparameters\": {\n                    \"another_primitive#1\": {\n                        \"yet_another_argument\": {\n                            \"type\": \"str\",\n                            \"default\": \"a_default_value\",\n                            \"values\": [\n                                \"a_default_value\",\n                                \"yet_another_value\"\n                            ]\n                        }\n                    }\n                }\n            }"
  },
  {
    "code": "def get_dict_for_attrs(obj, attrs):\n    data = {}\n    for attr in attrs:\n        data[attr] = getattr(obj, attr)\n    return data",
    "docstring": "Returns dictionary for each attribute from given ``obj``."
  },
  {
    "code": "def is_pinned(self, color: Color, square: Square) -> bool:\n        return self.pin_mask(color, square) != BB_ALL",
    "docstring": "Detects if the given square is pinned to the king of the given color."
  },
  {
    "code": "def remove_small_objects(image, min_size=50, connectivity=1):\n    return skimage.morphology.remove_small_objects(image,\n                                                   min_size=min_size,\n                                                   connectivity=connectivity)",
    "docstring": "Remove small objects from an boolean image.\n\n    :param image: boolean numpy array or :class:`jicbioimage.core.image.Image`\n    :returns: boolean :class:`jicbioimage.core.image.Image`"
  },
  {
    "code": "def _create_argument_parser(self):\n        parser = self._new_argument_parser()\n        self._add_base_arguments(parser)\n        self._add_required_arguments(parser)\n        return parser",
    "docstring": "Create and return the argument parser with all of the arguments\n        and configuration ready to go.\n\n        :rtype: argparse.ArgumentParser"
  },
  {
    "code": "def iterall(cls, connection=None, **kwargs):\n        try:\n            limit = kwargs['limit']\n        except KeyError:\n            limit = None\n        try:\n            page = kwargs['page']\n        except KeyError:\n            page = None\n        def _all_responses():\n            page = 1\n            params = kwargs.copy()\n            while True:\n                params.update(page=page, limit=250)\n                rsp = cls._make_request('GET', cls._get_all_path(), connection, params=params)\n                if rsp:\n                    yield rsp\n                    page += 1\n                else:\n                    yield []\n                    break\n        if not (limit or page):\n            for rsp in _all_responses():\n                for obj in rsp:\n                    yield cls._create_object(obj, connection=connection)\n        else:\n            response = cls._make_request('GET', cls._get_all_path(), connection, params=kwargs)\n            for obj in cls._create_object(response, connection=connection):\n                yield obj",
    "docstring": "Returns a autopaging generator that yields each object returned one by one."
  },
  {
    "code": "def dst_to_src(self, dst_file):\n        for map in self.mappings:\n            src_uri = map.dst_to_src(dst_file)\n            if (src_uri is not None):\n                return(src_uri)\n        raise MapperError(\n            \"Unable to translate destination path (%s) \"\n            \"into a source URI.\" % (dst_file))",
    "docstring": "Map destination path to source URI."
  },
  {
    "code": "def setModified(self, isModified: bool):\n        if not isModified:\n            self.qteUndoStack.saveState()\n        super().setModified(isModified)",
    "docstring": "Set the modified state to ``isModified``.\n\n        From a programmer's perspective this method does the same as\n        the native ``QsciScintilla`` method but also ensures that the\n        undo framework knows when the document state was changed.\n\n        |Args|\n\n        * ``isModified`` (**bool**): whether or not the document is considered\n          unmodified.\n\n        |Returns|\n\n        **None**\n\n        |Raises|\n\n        * **QtmacsArgumentError** if at least one argument has an invalid type."
  },
  {
    "code": "def register_rate_producer(self, rate_name: str, source: Callable[..., pd.DataFrame]=None) -> Pipeline:\n        return self._value_manager.register_rate_producer(rate_name, source)",
    "docstring": "Marks a ``Callable`` as the producer of a named rate.\n\n        This is a convenience wrapper around ``register_value_producer`` that makes sure\n        rate data is appropriately scaled to the size of the simulation time step.\n        It is equivalent to ``register_value_producer(value_name, source,\n        preferred_combiner=replace_combiner, preferred_post_processor=rescale_post_processor)``\n\n        Parameters\n        ----------\n        rate_name :\n            The name of the new dynamic rate pipeline.\n        source :\n            A callable source for the dynamic rate pipeline.\n\n        Returns\n        -------\n        Callable\n            A callable reference to the named dynamic rate pipeline."
  },
  {
    "code": "def update(self, folder, git_repository):\n        try:\n            self.clone(folder, git_repository)\n        except OSError:\n            self.update_git_repository(folder, git_repository)\n            self.pull(folder)",
    "docstring": "Creates or updates theme folder according given git repository.\n\n        :param git_repository: git url of the theme folder\n        :param folder: path of the git managed theme folder"
  },
  {
    "code": "def copy_files(src, ext, dst):\n    src_path = os.path.join(os.path.dirname(__file__), src)\n    dst_path = os.path.join(os.path.dirname(__file__), dst)\n    file_list = os.listdir(src_path)\n    for f in file_list:\n        if f == '__init__.py':\n            continue\n        f_path = os.path.join(src_path, f)\n        if os.path.isfile(f_path) and f.endswith(ext):\n            shutil.copy(f_path, dst_path)",
    "docstring": "Copies files with extensions \"ext\" from \"src\" to \"dst\" directory."
  },
  {
    "code": "def get_widths(self, estimation):\n        widths = estimation[self.map_offset[1]:self.map_offset[2]]\\\n            .reshape(self.K, 1)\n        return widths",
    "docstring": "Get estimation on widths\n\n\n        Parameters\n        ----------\n        estimation : 1D arrary\n             Either prior of posterior estimation\n\n\n        Returns\n        -------\n        fields : 2D array, in shape [K, 1]\n            Estimation of widths"
  },
  {
    "code": "def run(self, timeout=None, **kwargs):\n        from subprocess import Popen, PIPE\n        def target(**kw):\n            try:\n                self.process = Popen(self.command, **kw)\n                self.output, self.error = self.process.communicate()\n                self.retcode = self.process.returncode\n            except:\n                import traceback\n                self.error = traceback.format_exc()\n                self.retcode = -1\n        if 'stdout' not in kwargs:\n            kwargs['stdout'] = PIPE\n        if 'stderr' not in kwargs:\n            kwargs['stderr'] = PIPE\n        import threading\n        thread = threading.Thread(target=target, kwargs=kwargs)\n        thread.start()\n        thread.join(timeout)\n        if thread.is_alive():\n            self.process.terminate()\n            self.killed = True\n            thread.join()\n        return self",
    "docstring": "Run a command in a separated thread and wait timeout seconds.\n        kwargs are keyword arguments passed to Popen.\n\n        Return: self"
  },
  {
    "code": "def as_tuple(self, value):\n        if isinstance(value, list):\n            value = tuple(value)\n        return value",
    "docstring": "Utility function which converts lists to tuples."
  },
  {
    "code": "def restore_app_connection(self, port=None):\n        self.host_port = port or utils.get_available_host_port()\n        self._adb.forward(\n            ['tcp:%d' % self.host_port,\n             'tcp:%d' % self.device_port])\n        try:\n            self.connect()\n        except:\n            self.log.exception('Failed to re-connect to app.')\n            raise jsonrpc_client_base.AppRestoreConnectionError(\n                self._ad,\n                ('Failed to restore app connection for %s at host port %s, '\n                 'device port %s') % (self.package, self.host_port,\n                                      self.device_port))\n        self._proc = None\n        self._restore_event_client()",
    "docstring": "Restores the app after device got reconnected.\n\n        Instead of creating new instance of the client:\n          - Uses the given port (or find a new available host_port if none is\n            given).\n          - Tries to connect to remote server with selected port.\n\n        Args:\n          port: If given, this is the host port from which to connect to remote\n              device port. If not provided, find a new available port as host\n              port.\n\n        Raises:\n            AppRestoreConnectionError: When the app was not able to be started."
  },
  {
    "code": "def saelgv(vec1, vec2):\n    vec1 = stypes.toDoubleVector(vec1)\n    vec2 = stypes.toDoubleVector(vec2)\n    smajor = stypes.emptyDoubleVector(3)\n    sminor = stypes.emptyDoubleVector(3)\n    libspice.saelgv_c(vec1, vec2, smajor, sminor)\n    return stypes.cVectorToPython(smajor), stypes.cVectorToPython(sminor)",
    "docstring": "Find semi-axis vectors of an ellipse generated by two arbitrary\n    three-dimensional vectors.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/saelgv_c.html\n\n    :param vec1: First vector used to generate an ellipse.\n    :type vec1: 3-Element Array of floats\n    :param vec2: Second vector used to generate an ellipse.\n    :type vec2: 3-Element Array of floats\n    :return: Semi-major axis of ellipse, Semi-minor axis of ellipse.\n    :rtype: tuple"
  },
  {
    "code": "def quaternion_rotate(X, Y):\n    N = X.shape[0]\n    W = np.asarray([makeW(*Y[k]) for k in range(N)])\n    Q = np.asarray([makeQ(*X[k]) for k in range(N)])\n    Qt_dot_W = np.asarray([np.dot(Q[k].T, W[k]) for k in range(N)])\n    W_minus_Q = np.asarray([W[k] - Q[k] for k in range(N)])\n    A = np.sum(Qt_dot_W, axis=0)\n    eigen = np.linalg.eigh(A)\n    r = eigen[1][:, eigen[0].argmax()]\n    rot = quaternion_transform(r)\n    return rot",
    "docstring": "Calculate the rotation\n\n    Parameters\n    ----------\n    X : array\n        (N,D) matrix, where N is points and D is dimension.\n    Y: array\n        (N,D) matrix, where N is points and D is dimension.\n\n    Returns\n    -------\n    rot : matrix\n        Rotation matrix (D,D)"
  },
  {
    "code": "def get_ip_address_list(list_name):\n    payload = {\"jsonrpc\": \"2.0\",\n               \"id\": \"ID0\",\n               \"method\": \"get_policy_ip_addresses\",\n               \"params\": [list_name, 0, 256]}\n    response = __proxy__['bluecoat_sslv.call'](payload, False)\n    return _convert_to_list(response, 'item_name')",
    "docstring": "Retrieves a specific IP address list.\n\n    list_name(str): The name of the specific policy IP address list to retrieve.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList"
  },
  {
    "code": "def datetime(self, timezone=None):\n        if timezone is None:\n            timezone = self.timezone\n        return _dtfromtimestamp(self.__timestamp__ - timezone)",
    "docstring": "Returns a datetime object.\n\n        This object retains all information, including timezones.\n\n        :param timezone = self.timezone\n            The timezone (in seconds west of UTC) to return the value in. By\n            default, the timezone used when constructing the class is used\n            (local one by default). To use UTC, use timezone = 0. To use the\n            local tz, use timezone = chronyk.LOCALTZ."
  },
  {
    "code": "def table_names(self):\n        query = \"SELECT name FROM sqlite_master WHERE type='table'\"\n        cursor = self.connection.execute(query)\n        results = cursor.fetchall()\n        return [result_tuple[0] for result_tuple in results]",
    "docstring": "Returns names of all tables in the database"
  },
  {
    "code": "def batching(size):\n    if size < 1:\n        raise ValueError(\"batching() size must be at least 1\")\n    def batching_transducer(reducer):\n        return Batching(reducer, size)\n    return batching_transducer",
    "docstring": "Create a transducer which produces non-overlapping batches."
  },
  {
    "code": "def allDayForDate(self,this_date,timeZone=None):\n        if isinstance(this_date,datetime):\n            d = this_date.date()\n        else:\n            d = this_date\n        date_start = datetime(d.year,d.month,d.day)\n        naive_start = self.startTime if timezone.is_naive(self.startTime) else timezone.make_naive(self.startTime, timezone=timeZone)\n        naive_end = self.endTime if timezone.is_naive(self.endTime) else timezone.make_naive(self.endTime, timezone=timeZone)\n        return (\n            naive_start <= date_start and\n            naive_end >= date_start + timedelta(days=1,minutes=-30)\n        )",
    "docstring": "This method determines whether the occurrence lasts the entirety of\n        a specified day in the specified time zone.  If no time zone is specified,\n        then it uses the default time zone).  Also, give a grace period of a few\n        minutes to account for issues with the way events are sometimes entered."
  },
  {
    "code": "def gen_jid(opts=None):\n    if opts is None:\n        salt.utils.versions.warn_until(\n            'Sodium',\n            'The `opts` argument was not passed into salt.utils.jid.gen_jid(). '\n            'This will be required starting in {version}.'\n        )\n        opts = {}\n    global LAST_JID_DATETIME\n    if opts.get('utc_jid', False):\n        jid_dt = datetime.datetime.utcnow()\n    else:\n        jid_dt = datetime.datetime.now()\n    if not opts.get('unique_jid', False):\n        return '{0:%Y%m%d%H%M%S%f}'.format(jid_dt)\n    if LAST_JID_DATETIME and LAST_JID_DATETIME >= jid_dt:\n        jid_dt = LAST_JID_DATETIME + datetime.timedelta(microseconds=1)\n    LAST_JID_DATETIME = jid_dt\n    return '{0:%Y%m%d%H%M%S%f}_{1}'.format(jid_dt, os.getpid())",
    "docstring": "Generate a jid"
  },
  {
    "code": "def _get_indentation(line):\n    if line.strip():\n        non_whitespace_index = len(line) - len(line.lstrip())\n        return line[:non_whitespace_index]\n    else:\n        return ''",
    "docstring": "Return leading whitespace."
  },
  {
    "code": "def get(self, **kwargs):\n        id = None\n        if \"id\" in kwargs:\n            id = kwargs[\"id\"]\n            del kwargs[\"id\"]\n        elif \"pk\" in kwargs:\n            id = kwargs[\"pk\"]\n            del kwargs[\"pk\"]\n        else:\n            raise self.model.DoesNotExist(\"You must provide an id to find\")\n        es = connections.get_connection(\"default\")\n        doc_type = self.model.search_objects.mapping.doc_type\n        index = self.model.search_objects.mapping.index\n        try:\n            doc = es.get(index=index, doc_type=doc_type, id=id, **kwargs)\n        except NotFoundError:\n            message = \"Can't find a document for {}, using id {}\".format(\n                doc_type, id)\n            raise self.model.DoesNotExist(message)\n        return self.from_es(doc)",
    "docstring": "Get a object from Elasticsearch by id"
  },
  {
    "code": "def snake_to_pascal(name, singularize=False):\n  parts = name.split(\"_\")\n  if singularize:\n    return \"\".join(p.upper() if p in _ALL_CAPS else to_singular(p.title()) for p in parts)\n  else:\n    return \"\".join(p.upper() if p in _ALL_CAPS else p.title() for p in parts)",
    "docstring": "Converts snake_case to PascalCase. If singularize is True, an attempt is made at singularizing\n  each part of the resulting name."
  },
  {
    "code": "def yaml_str_join(l, n):\n    from photon.util.system import get_hostname, get_timestamp\n    s = l.construct_sequence(n)\n    for num, seq in enumerate(s):\n        if seq == 'hostname':\n            s[num] = '%s' % (get_hostname())\n        elif seq == 'timestamp':\n            s[num] = '%s' % (get_timestamp())\n    return ''.join([str(i) for i in s])",
    "docstring": "YAML loader to join strings\n\n    The keywords are as following:\n\n    * `hostname`: Your hostname (from :func:`util.system.get_hostname`)\n\n    * `timestamp`: Current timestamp (from :func:`util.system.get_timestamp`)\n\n    :returns:\n        A `non character` joined string |yaml_loader_returns|\n\n    .. note::\n        Be careful with timestamps when using a `config` in :ref:`settings`.\n\n    .. seealso:: |yaml_loader_seealso|"
  },
  {
    "code": "def ldap_login(self, username, password):\n        self.connect()\n        if self.config.get('USER_SEARCH'):\n            result = self.bind_search(username, password)\n        else:\n            result = self.direct_bind(username, password)\n        return result",
    "docstring": "Authenticate a user using ldap. This will return a userdata dict\n        if successfull.\n        ldap_login will return None if the user does not exist or if the credentials are invalid"
  },
  {
    "code": "def prepare_spec(self, spec, **kwargs):\n        self.prepare_spec_debug_flag(spec, **kwargs)\n        self.prepare_spec_export_target_checks(spec, **kwargs)\n        spec.advise(SETUP, self.prepare_spec_advice_packages, spec, **kwargs)",
    "docstring": "Prepare a spec for usage with the generic ToolchainRuntime.\n\n        Subclasses should avoid overriding this; override create_spec\n        instead."
  },
  {
    "code": "def bures_distance(rho0: Density, rho1: Density) -> float:\n    fid = fidelity(rho0, rho1)\n    op0 = asarray(rho0.asoperator())\n    op1 = asarray(rho1.asoperator())\n    tr0 = np.trace(op0)\n    tr1 = np.trace(op1)\n    return np.sqrt(tr0 + tr1 - 2.*np.sqrt(fid))",
    "docstring": "Return the Bures distance between mixed quantum states\n\n    Note: Bures distance cannot be calculated within the tensor backend."
  },
  {
    "code": "def get_instance(self, payload):\n        return UsageRecordInstance(self._version, payload, sim_sid=self._solution['sim_sid'], )",
    "docstring": "Build an instance of UsageRecordInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance\n        :rtype: twilio.rest.wireless.v1.sim.usage_record.UsageRecordInstance"
  },
  {
    "code": "def add_file_filters(self, file_filters):\n        file_filters = util.return_list(file_filters)\n        self.file_filters.extend(file_filters)",
    "docstring": "Adds `file_filters` to the internal file filters.\n        `file_filters` can be single object or iterable."
  },
  {
    "code": "def TLV_PUT(attrs, attrNum, format, value):\n    attrView = attrs[attrNum]\n    if format == 's':\n        format = str(attrView.len) + format\n    struct.pack_into(format, attrView.buf, attrView.offset, value)",
    "docstring": "Put a tag-length-value encoded attribute."
  },
  {
    "code": "def hash_opensubtitles(video_path):\n    bytesize = struct.calcsize(b'<q')\n    with open(video_path, 'rb') as f:\n        filesize = os.path.getsize(video_path)\n        filehash = filesize\n        if filesize < 65536 * 2:\n            return\n        for _ in range(65536 // bytesize):\n            filebuffer = f.read(bytesize)\n            (l_value,) = struct.unpack(b'<q', filebuffer)\n            filehash += l_value\n            filehash &= 0xFFFFFFFFFFFFFFFF\n        f.seek(max(0, filesize - 65536), 0)\n        for _ in range(65536 // bytesize):\n            filebuffer = f.read(bytesize)\n            (l_value,) = struct.unpack(b'<q', filebuffer)\n            filehash += l_value\n            filehash &= 0xFFFFFFFFFFFFFFFF\n    returnedhash = '%016x' % filehash\n    return returnedhash",
    "docstring": "Compute a hash using OpenSubtitles' algorithm.\n\n    :param str video_path: path of the video.\n    :return: the hash.\n    :rtype: str"
  },
  {
    "code": "def _get_environ(environ):\n    keys = [\"SERVER_NAME\", \"SERVER_PORT\"]\n    if _should_send_default_pii():\n        keys += [\"REMOTE_ADDR\", \"HTTP_X_FORWARDED_FOR\", \"HTTP_X_REAL_IP\"]\n    for key in keys:\n        if key in environ:\n            yield key, environ[key]",
    "docstring": "Returns our whitelisted environment variables."
  },
  {
    "code": "def file_name(self, file_type: Optional[FileType] = None) -> str:\n        name = self.__text.word()\n        ext = self.extension(file_type)\n        return '{name}{ext}'.format(\n            name=self.__sub(name),\n            ext=ext,\n        )",
    "docstring": "Get a random file name with some extension.\n\n        :param file_type: Enum object FileType\n        :return: File name.\n\n        :Example:\n            legislative.txt"
  },
  {
    "code": "def generate_dags(self, globals: Dict[str, Any]) -> None:\n        dag_configs: Dict[str, Dict[str, Any]] = self.get_dag_configs()\n        default_config: Dict[str, Any] = self.get_default_config()\n        for dag_name, dag_config in dag_configs.items():\n            dag_builder: DagBuilder = DagBuilder(dag_name=dag_name,\n                                                 dag_config=dag_config,\n                                                 default_config=default_config)\n            try:\n                dag: Dict[str, Union[str, DAG]] = dag_builder.build()\n            except Exception as e:\n                raise Exception(\n                    f\"Failed to generate dag {dag_name}. make sure config is properly populated. err:{e}\"\n                )\n            globals[dag[\"dag_id\"]]: DAG = dag[\"dag\"]",
    "docstring": "Generates DAGs from YAML config\n\n        :param globals: The globals() from the file used to generate DAGs. The dag_id\n            must be passed into globals() for Airflow to import"
  },
  {
    "code": "def cookie_name_check(cookie_name):\n\t\tcookie_match = WHTTPCookie.cookie_name_non_compliance_re.match(cookie_name.encode('us-ascii'))\n\t\treturn len(cookie_name) > 0 and cookie_match is None",
    "docstring": "Check cookie name for validity. Return True if name is valid\n\n\t\t:param cookie_name: name to check\n\t\t:return: bool"
  },
  {
    "code": "def get_tasks(self, list_id, completed=False):\n        return tasks_endpoint.get_tasks(self, list_id, completed=completed)",
    "docstring": "Gets tasks for the list with the given ID, filtered by the given completion flag"
  },
  {
    "code": "def count_mapped_reads(self, file_name, paired_end):\n        if file_name.endswith(\"bam\"):\n            return self.samtools_view(file_name, param=\"-c -F4\")\n        if file_name.endswith(\"sam\"):\n            return self.samtools_view(file_name, param=\"-c -F4 -S\")\n        return -1",
    "docstring": "Mapped_reads are not in fastq format, so this one doesn't need to accommodate fastq,\n        and therefore, doesn't require a paired-end parameter because it only uses samtools view.\n        Therefore, it's ok that it has a default parameter, since this is discarded.\n\n        :param str file_name: File for which to count mapped reads.\n        :param bool paired_end: This parameter is ignored; samtools automatically correctly responds depending\n            on the data in the bamfile. We leave the option here just for consistency, since all the other\n            counting functions require the parameter. This makes it easier to swap counting functions during\n            pipeline development.\n        :return int: Either return code from samtools view command, or -1 to indicate an error state."
  },
  {
    "code": "def remove(self, id):\n        p = Pool.get(int(id))\n        p.remove()\n        redirect(url(controller = 'pool', action = 'list'))",
    "docstring": "Remove pool."
  },
  {
    "code": "def _validate_partition_boundary(boundary):\n    boundary = six.text_type(boundary)\n    match = re.search(r'^([\\d.]+)(\\D*)$', boundary)\n    if match:\n        unit = match.group(2)\n        if not unit or unit in VALID_UNITS:\n            return\n    raise CommandExecutionError(\n        'Invalid partition boundary passed: \"{0}\"'.format(boundary)\n    )",
    "docstring": "Ensure valid partition boundaries are supplied."
  },
  {
    "code": "def systemd(service, start=True, enabled=True, unmask=False, restart=False):\n    with settings(hide('warnings', 'running', 'stdout', 'stderr'),\n                  warn_only=True, capture=True):\n        if restart:\n            sudo('systemctl restart %s' % service)\n        else:\n            if start:\n                sudo('systemctl start %s' % service)\n            else:\n                sudo('systemctl stop %s' % service)\n        if enabled:\n            sudo('systemctl enable %s' % service)\n        else:\n            sudo('systemctl disable %s' % service)\n        if unmask:\n            sudo('systemctl unmask %s' % service)",
    "docstring": "manipulates systemd services"
  },
  {
    "code": "def get_filename(self, renew=False):\n        if self._fname is None or renew:\n            self._fname = '%s.%s' % (self._id, self._format)\n        return self._fname",
    "docstring": "Get the filename of this content.\n\n        If the file name doesn't already exist, we created it as {id}.{format}."
  },
  {
    "code": "def copyfile(source, destination, force=True):\n    if os.path.exists(destination) and force is True:\n        os.remove(destination)\n    shutil.copyfile(source, destination)\n    return destination",
    "docstring": "copy a file from a source to its destination."
  },
  {
    "code": "def get(self, key):\n        o = self.data[key]()\n        if o is None:\n            del self.data[key]\n            raise CacheFault(\n                \"FinalizingCache has %r but its value is no more.\" % (key,))\n        log.msg(interface=iaxiom.IStatEvent, stat_cache_hits=1, key=key)\n        return o",
    "docstring": "Get an entry from the cache by key.\n\n        @raise KeyError: if the given key is not present in the cache.\n\n        @raise CacheFault: (a L{KeyError} subclass) if the given key is present\n            in the cache, but the value it points to is gone."
  },
  {
    "code": "def copy(copy_entry: FILE_COPY_ENTRY):\n    source_path = environ.paths.clean(copy_entry.source)\n    output_path = environ.paths.clean(copy_entry.destination)\n    copier = shutil.copy2 if os.path.isfile(source_path) else shutil.copytree\n    make_output_directory(output_path)\n    for i in range(3):\n        try:\n            copier(source_path, output_path)\n            return\n        except Exception:\n            time.sleep(0.5)\n    raise IOError('Unable to copy \"{source}\" to \"{destination}\"'.format(\n        source=source_path,\n        destination=output_path\n    ))",
    "docstring": "Copies the specified file from its source location to its destination\n    location."
  },
  {
    "code": "def find_base_path_and_format(main_path, formats):\n    for fmt in formats:\n        try:\n            return base_path(main_path, fmt), fmt\n        except InconsistentPath:\n            continue\n    raise InconsistentPath(u\"Path '{}' matches none of the export formats. \"\n                           \"Please make sure that jupytext.formats covers the current file \"\n                           \"(e.g. add '{}' to the export formats)\".format(main_path,\n                                                                          os.path.splitext(main_path)[1][1:]))",
    "docstring": "Return the base path and the format corresponding to the given path"
  },
  {
    "code": "def from_list(cls, terms_list, coefficient=1.0):\n        if not all([isinstance(op, tuple) for op in terms_list]):\n            raise TypeError(\"The type of terms_list should be a list of (name, index) \"\n                            \"tuples suitable for PauliTerm().\")\n        pterm = PauliTerm(\"I\", 0)\n        assert all([op[0] in PAULI_OPS for op in terms_list])\n        indices = [op[1] for op in terms_list]\n        assert all(_valid_qubit(index) for index in indices)\n        if len(set(indices)) != len(indices):\n            raise ValueError(\"Elements of PauliTerm that are allocated using from_list must \"\n                             \"be on disjoint qubits. Use PauliTerm multiplication to simplify \"\n                             \"terms instead.\")\n        for op, index in terms_list:\n            if op != \"I\":\n                pterm._ops[index] = op\n        if not isinstance(coefficient, Number):\n            raise ValueError(\"coefficient of PauliTerm must be a Number.\")\n        pterm.coefficient = complex(coefficient)\n        return pterm",
    "docstring": "Allocates a Pauli Term from a list of operators and indices. This is more efficient than\n        multiplying together individual terms.\n\n        :param list terms_list: A list of tuples, e.g. [(\"X\", 0), (\"Y\", 1)]\n        :return: PauliTerm"
  },
  {
    "code": "def drawPoints(self, pointPen, filterRedundantPoints=False):\n        if filterRedundantPoints:\n            pointPen = FilterRedundantPointPen(pointPen)\n        for contour in self.contours:\n            pointPen.beginPath(identifier=contour[\"identifier\"])\n            for segmentType, pt, smooth, name, identifier in contour[\"points\"]:\n                pointPen.addPoint(pt=pt, segmentType=segmentType, smooth=smooth, name=name, identifier=identifier)\n            pointPen.endPath()\n        for component in self.components:\n            pointPen.addComponent(component[\"baseGlyph\"], component[\"transformation\"], identifier=component[\"identifier\"])",
    "docstring": "draw self using pointPen"
  },
  {
    "code": "def petl(self, *args, **kwargs):\n        import petl\n        t = self.resolved_url.get_resource().get_target()\n        if t.target_format == 'txt':\n            return petl.fromtext(str(t.fspath), *args, **kwargs)\n        elif t.target_format == 'csv':\n            return petl.fromcsv(str(t.fspath), *args, **kwargs)\n        else:\n            raise Exception(\"Can't handle\")",
    "docstring": "Return a PETL source object"
  },
  {
    "code": "def from_Z(z: int):\n        for sym, data in _pt_data.items():\n            if data[\"Atomic no\"] == z:\n                return Element(sym)\n        raise ValueError(\"No element with this atomic number %s\" % z)",
    "docstring": "Get an element from an atomic number.\n\n        Args:\n            z (int): Atomic number\n\n        Returns:\n            Element with atomic number z."
  },
  {
    "code": "def dotproduct(a, b):\n    \"Calculates the dotproduct between two vecors\"\n    assert(len(a) == len(b))\n    out = 0\n    for i in range(len(a)):\n        out += a[i] * b[i]\n    return out",
    "docstring": "Calculates the dotproduct between two vecors"
  },
  {
    "code": "def getVariable(self, name):\n        return lock_and_call(\n            lambda: Variable(self._impl.getVariable(name)),\n            self._lock\n        )",
    "docstring": "Get the variable with the corresponding name.\n\n        Args:\n            name: Name of the variable to be found.\n\n        Raises:\n            TypeError: if the specified variable does not exist."
  },
  {
    "code": "def _parse_directory(self):\n        if self._parser.has_option('storage', 'directory'):\n            directory = self._parser.get('storage', 'directory')\n            if directory == CUSTOM_APPS_DIR:\n                raise ConfigError(\"{} cannot be used as a storage directory.\"\n                                  .format(CUSTOM_APPS_DIR))\n        else:\n            directory = MACKUP_BACKUP_PATH\n        return str(directory)",
    "docstring": "Parse the storage directory in the config.\n\n        Returns:\n            str"
  },
  {
    "code": "def names(cls):\n        if not cls._files:\n            for f in os.listdir(cls._image_path):\n                if(not f.startswith('.') and\n                   os.path.isfile(os.path.join(cls._image_path, f))):\n                    cls._files.append(os.path.splitext(f)[0])\n        return cls._files",
    "docstring": "A list of all emoji names without file extension."
  },
  {
    "code": "def _base_placeholder(self):\n        notes_master = self.part.notes_master\n        ph_type = self.element.ph_type\n        return notes_master.placeholders.get(ph_type=ph_type)",
    "docstring": "Return the notes master placeholder this notes slide placeholder\n        inherits from, or |None| if no placeholder of the matching type is\n        present."
  },
  {
    "code": "def cost(self, i, j):\n        return dist(self.endpoints[i][1], self.endpoints[j][0])",
    "docstring": "Returns the distance between the end of path i\n        and the start of path j."
  },
  {
    "code": "def set_last_component_continued(self):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('SL record not yet initialized!')\n        if not self.symlink_components:\n            raise pycdlibexception.PyCdlibInternalError('Trying to set continued on a non-existent component!')\n        self.symlink_components[-1].set_continued()",
    "docstring": "Set the previous component of this SL record to continued.\n\n        Parameters:\n         None.\n        Returns:\n         Nothing."
  },
  {
    "code": "def _get_bank_keys_redis_key(bank):\n    opts = _get_redis_keys_opts()\n    return '{prefix}{separator}{bank}'.format(\n        prefix=opts['bank_keys_prefix'],\n        separator=opts['separator'],\n        bank=bank\n    )",
    "docstring": "Return the Redis key for the SET of keys under a certain bank, given the bank name."
  },
  {
    "code": "def selection_paste_data_gen(self, selection, data, freq=None):\n        (bb_top, bb_left), (bb_bottom, bb_right) = \\\n            selection.get_grid_bbox(self.grid.code_array.shape)\n        bbox_height = bb_bottom - bb_top + 1\n        bbox_width = bb_right - bb_left + 1\n        for row, row_data in enumerate(itertools.cycle(data)):\n            if row >= bbox_height:\n                break\n            row_data = list(row_data)\n            duplicated_row_data = row_data * (bbox_width // len(row_data) + 1)\n            duplicated_row_data = duplicated_row_data[:bbox_width]\n            for col in xrange(len(duplicated_row_data)):\n                if (bb_top, bb_left + col) not in selection:\n                    duplicated_row_data[col] = None\n            yield duplicated_row_data",
    "docstring": "Generator that yields data for selection paste"
  },
  {
    "code": "def remove_additional_model(self, model_list_or_dict, core_objects_dict, model_name, model_key, destroy=True):\n        if model_name == \"income\":\n            self.income.prepare_destruction()\n            self.income = None\n            return\n        for model_or_key in model_list_or_dict:\n            model = model_or_key if model_key is None else model_list_or_dict[model_or_key]\n            found = False\n            for core_object in core_objects_dict.values():\n                if core_object is getattr(model, model_name):\n                    found = True\n                    break\n            if not found:\n                if model_key is None:\n                    if destroy:\n                        model.prepare_destruction()\n                    model_list_or_dict.remove(model)\n                else:\n                    if destroy:\n                        model_list_or_dict[model_or_key].prepare_destruction()\n                    del model_list_or_dict[model_or_key]\n                return",
    "docstring": "Remove one unnecessary model\n\n        The method will search for the first model-object out of\n        model_list_or_dict that represents no core-object in the dictionary of core-objects handed by core_objects_dict,\n        remove it and return without continue to search for more model-objects which maybe are unnecessary, too.\n\n        :param model_list_or_dict: could be a list or dictionary of one model type\n        :param core_objects_dict: dictionary of one type of core-elements (rafcon.core)\n        :param model_name: prop_name for the core-element hold by the model, this core-element is covered by the model\n        :param model_key: if model_list_or_dict is a dictionary the key is the id of the respective element\n                          (e.g. 'state_id')\n        :return:"
  },
  {
    "code": "def getHeadingLevel(ts, hierarchy=default_hierarchy):\n        try:\n            return hierarchy.index(ts.name)+1\n        except ValueError:\n            if ts.name.endswith('section'):\n                i, name = 0, ts.name\n                while name.startswith('sub'):\n                    name, i = name[3:], i+1\n                if name == 'section':\n                    return i+2\n            return float('inf')\n        except (AttributeError, TypeError):\n            return float('inf')",
    "docstring": "Extract heading level for a particular Tex element, given a specified\n        hierarchy.\n\n        >>> ts = TexSoup(r'\\section{Hello}').section\n        >>> TOC.getHeadingLevel(ts)\n        2\n        >>> ts2 = TexSoup(r'\\chapter{hello again}').chapter\n        >>> TOC.getHeadingLevel(ts2)\n        1\n        >>> ts3 = TexSoup(r'\\subsubsubsubsection{Hello}').subsubsubsubsection\n        >>> TOC.getHeadingLevel(ts3)\n        6"
  },
  {
    "code": "def write_document(doc, fnm):\n    with codecs.open(fnm, 'wb', 'ascii') as f:\n        f.write(json.dumps(doc, indent=2))",
    "docstring": "Write a Text document to file.\n\n    Parameters\n    ----------\n    doc: Text\n        The document to save.\n    fnm: str\n        The filename to save the document"
  },
  {
    "code": "def waypoint_count_send(self, seq):\n        if self.mavlink10():\n            self.mav.mission_count_send(self.target_system, self.target_component, seq)\n        else:\n            self.mav.waypoint_count_send(self.target_system, self.target_component, seq)",
    "docstring": "wrapper for waypoint_count_send"
  },
  {
    "code": "def has_signature(body, sender):\n    non_empty = [line for line in body.splitlines() if line.strip()]\n    candidate = non_empty[-SIGNATURE_MAX_LINES:]\n    upvotes = 0\n    for line in candidate:\n        if len(line.strip()) > 27:\n            continue\n        elif contains_sender_names(sender)(line):\n            return True\n        elif (binary_regex_search(RE_RELAX_PHONE)(line) +\n              binary_regex_search(RE_EMAIL)(line) +\n              binary_regex_search(RE_URL)(line) == 1):\n            upvotes += 1\n    if upvotes > 1:\n        return True",
    "docstring": "Checks if the body has signature. Returns True or False."
  },
  {
    "code": "def process_route_spec_config(con, vpc_info, route_spec,\n                              failed_ips, questionable_ips):\n    if CURRENT_STATE._stop_all:\n        logging.debug(\"Routespec processing. Stop requested, abort operation\")\n        return\n    if failed_ips:\n        logging.debug(\"Route spec processing. Failed IPs: %s\" %\n                      \",\".join(failed_ips))\n    else:\n        logging.debug(\"Route spec processing. No failed IPs.\")\n    routes_in_rts  = {}\n    CURRENT_STATE.vpc_state.setdefault(\"time\",\n                                       datetime.datetime.now().isoformat())\n    chosen_routers = _update_existing_routes(route_spec,\n                                             failed_ips, questionable_ips,\n                                             vpc_info, con, routes_in_rts)\n    _add_missing_routes(route_spec, failed_ips, questionable_ips,\n                        chosen_routers,\n                        vpc_info, con, routes_in_rts)",
    "docstring": "Look through the route spec and update routes accordingly.\n\n    Idea: Make sure we have a route for each CIDR.\n\n    If we have a route to any of the IP addresses for a given CIDR then we are\n    good. Otherwise, pick one (usually the first) IP and create a route to that\n    IP.\n\n    If a route points at a failed or questionable IP then a new candidate is\n    chosen, if possible."
  },
  {
    "code": "def iterscrapers(self, method, mode = None):\n\t\tglobal discovered\n\t\tif discovered.has_key(self.language) and discovered[self.language].has_key(method):\n\t\t\tfor Scraper in discovered[self.language][method]:\n\t\t\t\tyield Scraper",
    "docstring": "Iterates over all available scrapers."
  },
  {
    "code": "def get_valid_build_systems(working_dir, package=None):\n    from rez.plugin_managers import plugin_manager\n    from rez.exceptions import PackageMetadataError\n    try:\n        package = package or get_developer_package(working_dir)\n    except PackageMetadataError:\n        pass\n    if package:\n        if getattr(package, \"build_command\", None) is not None:\n            buildsys_name = \"custom\"\n        else:\n            buildsys_name = getattr(package, \"build_system\", None)\n        if buildsys_name:\n            cls = plugin_manager.get_plugin_class('build_system', buildsys_name)\n            return [cls]\n    clss = []\n    for buildsys_name in get_buildsys_types():\n        cls = plugin_manager.get_plugin_class('build_system', buildsys_name)\n        if cls.is_valid_root(working_dir, package=package):\n            clss.append(cls)\n    child_clss = set(x.child_build_system() for x in clss)\n    clss = list(set(clss) - child_clss)\n    return clss",
    "docstring": "Returns the build system classes that could build the source in given dir.\n\n    Args:\n        working_dir (str): Dir containing the package definition and potentially\n            build files.\n        package (`Package`): Package to be built. This may or may not be needed\n            to determine the build system. For eg, cmake just has to look for\n            a CMakeLists.txt file, whereas the 'build_command' package field\n            must be present for the 'custom' build system type.\n\n    Returns:\n        List of class: Valid build system class types."
  },
  {
    "code": "def make_type(cls, basename, cardinality):\n        if cardinality is Cardinality.one:\n            return basename\n        type_name = \"%s%s\" % (basename, cls.to_char_map[cardinality])\n        return type_name",
    "docstring": "Build new type name according to CardinalityField naming scheme.\n\n        :param basename:  Type basename of primary type (as string).\n        :param cardinality: Cardinality of the new type (as Cardinality item).\n        :return: Type name with CardinalityField suffix (if needed)"
  },
  {
    "code": "def load_file(self, cursor, target, fname, options):\n        \"Parses and loads a single file into the target table.\"\n        with open(fname) as fin:\n            log.debug(\"opening {0} in {1} load_file\".format(fname, __name__))\n            encoding = options.get('encoding', 'utf-8')\n            if target in self.processors:\n                reader = self.processors[target](fin, encoding=encoding)\n            else:\n                reader = self.default_processor(fin, encoding=encoding)\n            columns = getattr(reader, 'output_columns', None)\n            for _ in xrange(int(options.get('skip-lines', 0))):\n                fin.readline()\n            cursor.copy_from(reader, self.qualified_names[target],\n                             columns=columns)",
    "docstring": "Parses and loads a single file into the target table."
  },
  {
    "code": "def get(filename, ignore_fields=None):\n    if ignore_fields is None:\n        ignore_fields = []\n    with open(filename, 'r') as fh:\n        bibtex = bibtexparser.load(fh)\n    bibtex.entries = [{k: entry[k]\n                       for k in entry if k not in ignore_fields}\n                      for entry in bibtex.entries]\n    return bibtex",
    "docstring": "Get all entries from a BibTeX file.\n\n    :param filename: The name of the BibTeX file.\n    :param ignore_fields: An optional list of fields to strip from the BibTeX \\\n            file.\n\n    :returns: A ``bibtexparser.BibDatabase`` object representing the fetched \\\n            entries."
  },
  {
    "code": "def _antisymm_12(C):\n    nans = np.isnan(C)\n    C[nans] = -np.einsum('jikl', C)[nans]\n    return C",
    "docstring": "To get rid of NaNs produced by _scalar2array, antisymmetrize the first\n    two indices of operators where C_ijkl = -C_jikl"
  },
  {
    "code": "def reset():\n    global _handlers, python_signal\n    for sig, (previous, _) in _handlers.iteritems():\n        if not previous:\n            previous = SIG_DFL\n        python_signal.signal(sig, previous)\n    _handlers = dict()",
    "docstring": "Clear global data and remove the handlers.\n    CAUSION! This method sets as a signal handlers the ones which it has\n    noticed on initialization time. If there has been another handler installed\n    on top of us it will get removed by this method call."
  },
  {
    "code": "async def start_serving(self, address=None, sockets=None, **kw):\n        if self._server:\n            raise RuntimeError('Already serving')\n        server = DGServer(self._loop)\n        loop = self._loop\n        if sockets:\n            for sock in sockets:\n                transport, _ = await loop.create_datagram_endpoint(\n                    self.create_protocol, sock=sock)\n                server.transports.append(transport)\n        elif isinstance(address, tuple):\n            transport, _ = await loop.create_datagram_endpoint(\n                self.create_protocol, local_addr=address)\n            server.transports.append(transport)\n        else:\n            raise RuntimeError('sockets or address must be supplied')\n        self._set_server(server)",
    "docstring": "create the server endpoint."
  },
  {
    "code": "def record_corrected_value(self, value, expected_interval, count=1):\n        while True:\n            if not self.record_value(value, count):\n                return False\n            if value <= expected_interval or expected_interval <= 0:\n                return True\n            value -= expected_interval",
    "docstring": "Record a new value into the histogram and correct for\n        coordinated omission if needed\n\n        Args:\n            value: the value to record (must be in the valid range)\n            expected_interval: the expected interval between 2 value samples\n            count: incremental count (defaults to 1)"
  },
  {
    "code": "def ParseYAMLAuthorizationsList(yaml_data):\n    try:\n      raw_list = yaml.ParseMany(yaml_data)\n    except (ValueError, pyyaml.YAMLError) as e:\n      raise InvalidAPIAuthorization(\"Invalid YAML: %s\" % e)\n    result = []\n    for auth_src in raw_list:\n      auth = APIAuthorization()\n      auth.router_cls = _GetRouterClass(auth_src[\"router\"])\n      auth.users = auth_src.get(\"users\", [])\n      auth.groups = auth_src.get(\"groups\", [])\n      auth.router_params = auth_src.get(\"router_params\", {})\n      result.append(auth)\n    return result",
    "docstring": "Parses YAML data into a list of APIAuthorization objects."
  },
  {
    "code": "def edit(self, id, seq, resource):\n        return self.create_or_edit(id, seq, resource)",
    "docstring": "Edit a highlight.\n\n        :param id: Result ID as an int.\n        :param seq: TestResult sequence ID as an int.\n        :param resource: :class:`highlights.Highlight <highlights.Highlight>` object\n        :return: :class:`highlights.Highlight <highlights.Highlight>` object\n        :rtype: highlights.Highlight"
  },
  {
    "code": "def person(self, person_id):\n        if not self.cache['persons'].get(person_id, None):\n            try:\n                person_xml = self.bc.person(person_id)\n                p = Person(person_xml)\n                self.cache['persons'][person_id] = p\n            except HTTPError:\n                return None\n        return self.cache['persons'][person_id]",
    "docstring": "Access a Person object by id"
  },
  {
    "code": "def _get_signature(self):\n        keys = list(self.params.keys())\n        keys.sort()\n        string = \"\"\n        for name in keys:\n            string += name\n            string += self.params[name]\n        string += self.api_secret\n        return md5(string)",
    "docstring": "Returns a 32-character hexadecimal md5 hash of the signature string."
  },
  {
    "code": "def _flatten_up_to_token(self, token):\n        if token.is_group:\n            token = next(token.flatten())\n        for t in self._curr_stmt.flatten():\n            if t == token:\n                break\n            yield t",
    "docstring": "Yields all tokens up to token but excluding current."
  },
  {
    "code": "def change_domain(self, domain):\n        logger.info('Running %(name)s.change_domain() with new domain range:[%(ymin)s, %(ymax)s]',\n                    {\"name\": self.__class__, \"ymin\": np.min(domain), \"ymax\": np.max(domain)})\n        if np.max(domain) > np.max(self.x) or np.min(domain) < np.min(self.x):\n            logger.error('Old domain range: [%(xmin)s, %(xmax)s] does not include new domain range:'\n                         '[%(ymin)s, %(ymax)s]', {\"xmin\": np.min(self.x), \"xmax\": np.max(self.x),\n                                                  \"ymin\": np.min(domain), \"ymax\": np.max(domain)})\n            raise ValueError('in change_domain():' 'the old domain does not include the new one')\n        y = np.interp(domain, self.x, self.y)\n        obj = self.__class__(np.dstack((domain, y))[0], **self.__dict__['metadata'])\n        return obj",
    "docstring": "Creating new Curve object in memory with domain passed as a parameter.\n        New domain must include in the original domain.\n        Copies values from original curve and uses interpolation to calculate\n        values for new points in domain.\n\n        Calculate y - values of example curve with changed domain:\n        >>> print(Curve([[0,0], [5, 5], [10, 0]])\\\n            .change_domain([1, 2, 8, 9]).y)\n        [1. 2. 2. 1.]\n\n        :param domain: set of points representing new domain.\n            Might be a list or np.array.\n        :return: new Curve object with domain set by 'domain' parameter"
  },
  {
    "code": "def wait_for_completion(self, job_id, timeout=None):\n        while 1:\n            job = self.wait(job_id, timeout=timeout)\n            if job.state in [State.COMPLETED, State.FAILED, State.CANCELED]:\n                return job\n            else:\n                continue",
    "docstring": "Wait for the job given by job_id to change to COMPLETED or CANCELED. Raises a\n        iceqube.exceptions.TimeoutError if timeout is exceeded before each job change.\n\n        :param job_id: the id of the job to wait for.\n        :param timeout: how long to wait for a job state change before timing out."
  },
  {
    "code": "def lock(cls, pid, connection, session):\n        with cls._lock:\n            cls._ensure_pool_exists(pid)\n            cls._pools[pid].lock(connection, session)",
    "docstring": "Explicitly lock the specified connection in the pool\n\n        :param str pid: The pool id\n        :type connection: psycopg2.extensions.connection\n        :param connection: The connection to add to the pool\n        :param queries.Session session: The session to hold the lock"
  },
  {
    "code": "def can_user_approve_this_page(self, user):\n        self.ensure_one()\n        if not self.is_approval_required:\n            return True\n        if user.has_group('document_page.group_document_manager'):\n            return True\n        if not user.has_group(\n                'document_page_approval.group_document_approver_user'):\n            return False\n        if not self.approver_group_ids:\n            return True\n        return len(user.groups_id & self.approver_group_ids) > 0",
    "docstring": "Check if a user can approve this page."
  },
  {
    "code": "def maxEntropy(n,k):\n  s = float(k)/n\n  if s > 0.0 and s < 1.0:\n    entropy = - s * math.log(s,2) - (1 - s) * math.log(1 - s,2)\n  else:\n    entropy = 0\n  return n*entropy",
    "docstring": "The maximum enropy we could get with n units and k winners"
  },
  {
    "code": "def save(self, file_or_wfs, filename, overwrite=False):\n        self.write(filename, file_or_wfs.read())\n        return filename",
    "docstring": "Save a file-like object or a `werkzeug.FileStorage` with the specified filename.\n\n        :param storage: The file or the storage to be saved.\n        :param filename: The destination in the storage.\n        :param overwrite: if `False`, raise an exception if file exists in storage\n\n        :raises FileExists: when file exists and overwrite is `False`"
  },
  {
    "code": "def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None,\n                                  region=None, key=None, keyid=None, profile=None):\n    try:\n        vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile)\n        if not vpc_id:\n            return {'associated': False,\n                    'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}}\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        if conn.associate_dhcp_options(dhcp_options_id, vpc_id):\n            log.info('DHCP options with id %s were associated with VPC %s',\n                     dhcp_options_id, vpc_id)\n            return {'associated': True}\n        else:\n            log.warning('DHCP options with id %s were not associated with VPC %s',\n                        dhcp_options_id, vpc_id)\n            return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}}\n    except BotoServerError as e:\n        return {'associated': False, 'error': __utils__['boto.get_error'](e)}",
    "docstring": "Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC.\n\n    Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402'"
  },
  {
    "code": "def meta(self):\n        if not self._pv.meta_data_property or not self._meta_target:\n            return {}\n        return getattr(self._meta_target, self._pv.meta_data_property)",
    "docstring": "Value of the bound meta-property on the target."
  },
  {
    "code": "def readInfoElement(self, infoElement, instanceObject):\n        infoLocation = self.locationFromElement(infoElement)\n        instanceObject.addInfo(infoLocation, copySourceName=self.infoSource)",
    "docstring": "Read the info element.\n\n            ::\n\n                <info/>\n\n                <info\">\n                <location/>\n                </info>"
  },
  {
    "code": "def matlab_compatible(name):\n    compatible_name = [ch if ch in ALLOWED_MATLAB_CHARS else \"_\" for ch in name]\n    compatible_name = \"\".join(compatible_name)\n    if compatible_name[0] not in string.ascii_letters:\n        compatible_name = \"M_\" + compatible_name\n    return compatible_name[:60]",
    "docstring": "make a channel name compatible with Matlab variable naming\n\n    Parameters\n    ----------\n    name : str\n        channel name\n\n    Returns\n    -------\n    compatible_name : str\n        channel name compatible with Matlab"
  },
  {
    "code": "def close(self):\n        if self.fd:\n            os.close(self.fd)\n            self.fd = None",
    "docstring": "Close the i2c connection."
  },
  {
    "code": "def LEB128toint(LEBinput):\n    reversedbytes = hexreverse(LEBinput)\n    binstr = \"\"\n    for i in range(len(LEBinput) // 2):\n        if i == 0:\n            assert int(reversedbytes[2*i:(2*i + 2)],16) < 128\n        else:\n            assert int(reversedbytes[2*i:(2*i + 2)],16) >= 128\n        tempbin = str(bin(int(reversedbytes[2*i:(2*i + 2)],16))) \\\n                  .lstrip(\"0b\").replace(\"b\",\"\").replace(\"L\",\"\") \\\n                  .replace(\"'\",\"\").replace('\"',\"\") \\\n                  .zfill(8)\n        binstr += tempbin[1:]\n    return int(binstr,2)",
    "docstring": "Convert unsigned LEB128 hex to integer"
  },
  {
    "code": "def inspect(self, **kwargs):\n        try:\n            scf_cycle = abiinspect.GroundStateScfCycle.from_file(self.output_file.path)\n        except IOError:\n            return None\n        if scf_cycle is not None:\n            if \"title\" not in kwargs: kwargs[\"title\"] = str(self)\n            return scf_cycle.plot(**kwargs)\n        return None",
    "docstring": "Plot the SCF cycle results with matplotlib.\n\n        Returns\n            `matplotlib` figure, None if some error occurred."
  },
  {
    "code": "async def async_init(self):\n        self.pool = await aioredis.create_pool(\n            (self.host, self.port),\n            db=self.db_id,\n            minsize=self.min_pool_size,\n            maxsize=self.max_pool_size,\n            loop=asyncio.get_event_loop(),\n        )",
    "docstring": "Handle here the asynchronous part of the init."
  },
  {
    "code": "def account(self, id):\n        id = self.__unpack_id(id)\n        url = '/api/v1/accounts/{0}'.format(str(id))\n        return self.__api_request('GET', url)",
    "docstring": "Fetch account information by user `id`.\n        \n        Does not require authentication.\n        \n        Returns a `user dict`_."
  },
  {
    "code": "async def await_rpc(self, address, rpc_id, *args, **kwargs):\n        self.verify_calling_thread(True, \"await_rpc must be called from **inside** the event loop\")\n        if isinstance(rpc_id, RPCDeclaration):\n            arg_format = rpc_id.arg_format\n            resp_format = rpc_id.resp_format\n            rpc_id = rpc_id.rpc_id\n        else:\n            arg_format = kwargs.get('arg_format', None)\n            resp_format = kwargs.get('resp_format', None)\n        arg_payload = b''\n        if arg_format is not None:\n            arg_payload = pack_rpc_payload(arg_format, args)\n        self._logger.debug(\"Sending rpc to %d:%04X, payload=%s\", address, rpc_id, args)\n        response = AwaitableResponse()\n        self._rpc_queue.put_rpc(address, rpc_id, arg_payload, response)\n        try:\n            resp_payload = await response.wait(1.0)\n        except RPCRuntimeError as err:\n            resp_payload = err.binary_error\n        if resp_format is None:\n            return []\n        resp = unpack_rpc_payload(resp_format, resp_payload)\n        return resp",
    "docstring": "Send an RPC from inside the EmulationLoop.\n\n        This is the primary method by which tasks running inside the\n        EmulationLoop dispatch RPCs.  The RPC is added to the queue of waiting\n        RPCs to be drained by the RPC dispatch task and this coroutine will\n        block until it finishes.\n\n        **This method must only be called from inside the EmulationLoop**\n\n        Args:\n            address (int): The address of the tile that has the RPC.\n            rpc_id (int): The 16-bit id of the rpc we want to call\n            *args: Any required arguments for the RPC as python objects.\n            **kwargs: Only two keyword arguments are supported:\n                - arg_format: A format specifier for the argument list\n                - result_format: A format specifier for the result\n\n        Returns:\n            list: A list of the decoded response members from the RPC."
  },
  {
    "code": "def reindex_like(self, other, method=None, copy=True, limit=None,\n                     tolerance=None):\n        d = other._construct_axes_dict(axes=self._AXIS_ORDERS, method=method,\n                                       copy=copy, limit=limit,\n                                       tolerance=tolerance)\n        return self.reindex(**d)",
    "docstring": "Return an object with matching indices as other object.\n\n        Conform the object to the same index on all axes. Optional\n        filling logic, placing NaN in locations having no value\n        in the previous index. A new object is produced unless the\n        new index is equivalent to the current one and copy=False.\n\n        Parameters\n        ----------\n        other : Object of the same data type\n            Its row and column indices are used to define the new indices\n            of this object.\n        method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}\n            Method to use for filling holes in reindexed DataFrame.\n            Please note: this is only applicable to DataFrames/Series with a\n            monotonically increasing/decreasing index.\n\n            * None (default): don't fill gaps\n            * pad / ffill: propagate last valid observation forward to next\n              valid\n            * backfill / bfill: use next valid observation to fill gap\n            * nearest: use nearest valid observations to fill gap\n\n        copy : bool, default True\n            Return a new object, even if the passed indexes are the same.\n        limit : int, default None\n            Maximum number of consecutive labels to fill for inexact matches.\n        tolerance : optional\n            Maximum distance between original and new labels for inexact\n            matches. The values of the index at the matching locations most\n            satisfy the equation ``abs(index[indexer] - target) <= tolerance``.\n\n            Tolerance may be a scalar value, which applies the same tolerance\n            to all values, or list-like, which applies variable tolerance per\n            element. List-like includes list, tuple, array, Series, and must be\n            the same size as the index and its dtype must exactly match the\n            index's type.\n\n            .. versionadded:: 0.21.0 (list-like tolerance)\n\n        Returns\n        -------\n        Series or DataFrame\n            Same type as caller, but with changed indices on each axis.\n\n        See Also\n        --------\n        DataFrame.set_index : Set row labels.\n        DataFrame.reset_index : Remove row labels or move them to new columns.\n        DataFrame.reindex : Change to new indices or expand indices.\n\n        Notes\n        -----\n        Same as calling\n        ``.reindex(index=other.index, columns=other.columns,...)``.\n\n        Examples\n        --------\n        >>> df1 = pd.DataFrame([[24.3, 75.7, 'high'],\n        ...                     [31, 87.8, 'high'],\n        ...                     [22, 71.6, 'medium'],\n        ...                     [35, 95, 'medium']],\n        ...     columns=['temp_celsius', 'temp_fahrenheit', 'windspeed'],\n        ...     index=pd.date_range(start='2014-02-12',\n        ...                         end='2014-02-15', freq='D'))\n\n        >>> df1\n                    temp_celsius  temp_fahrenheit windspeed\n        2014-02-12          24.3             75.7      high\n        2014-02-13          31.0             87.8      high\n        2014-02-14          22.0             71.6    medium\n        2014-02-15          35.0             95.0    medium\n\n        >>> df2 = pd.DataFrame([[28, 'low'],\n        ...                     [30, 'low'],\n        ...                     [35.1, 'medium']],\n        ...     columns=['temp_celsius', 'windspeed'],\n        ...     index=pd.DatetimeIndex(['2014-02-12', '2014-02-13',\n        ...                             '2014-02-15']))\n\n        >>> df2\n                    temp_celsius windspeed\n        2014-02-12          28.0       low\n        2014-02-13          30.0       low\n        2014-02-15          35.1    medium\n\n        >>> df2.reindex_like(df1)\n                    temp_celsius  temp_fahrenheit windspeed\n        2014-02-12          28.0              NaN       low\n        2014-02-13          30.0              NaN       low\n        2014-02-14           NaN              NaN       NaN\n        2014-02-15          35.1              NaN    medium"
  },
  {
    "code": "def get_script_extension_property(value, is_bytes=False):\n    obj = unidata.ascii_script_extensions if is_bytes else unidata.unicode_script_extensions\n    if value.startswith('^'):\n        negated = value[1:]\n        value = '^' + unidata.unicode_alias['script'].get(negated, negated)\n    else:\n        value = unidata.unicode_alias['script'].get(value, value)\n    return obj[value]",
    "docstring": "Get `SCX` property."
  },
  {
    "code": "def save_model(self, file_name='model.cx'):\n        with open(file_name, 'wt') as fh:\n            cx_str = self.print_cx()\n            fh.write(cx_str)",
    "docstring": "Save the assembled CX network in a file.\n\n        Parameters\n        ----------\n        file_name : Optional[str]\n            The name of the file to save the CX network to. Default: model.cx"
  },
  {
    "code": "def letter_set(self):\n        end_str = ctypes.create_string_buffer(MAX_CHARS)\n        cgaddag.gdg_letter_set(self.gdg, self.node, end_str)\n        return [char for char in end_str.value.decode(\"ascii\")]",
    "docstring": "Return the letter set of this node."
  },
  {
    "code": "def _from_keras_log_format(data, **kwargs):\n    data_val = pd.DataFrame(data[['epoch']])\n    data_val['acc'] = data['val_acc']\n    data_val['loss'] = data['val_loss']\n    data_val['data'] = 'validation'\n    data_training = pd.DataFrame(data[['acc', 'loss', 'epoch']])\n    data_training['data'] = 'training'\n    result = pd.concat([data_training, data_val], sort=False)\n    plot(result, **kwargs)",
    "docstring": "Plot accuracy and loss from a panda's dataframe.\n\n    Args:\n        data: Panda dataframe in the format of the Keras CSV log.\n        output_dir_path: The path to the directory where the resultings plots\n            should end up."
  },
  {
    "code": "def get_xritdecompress_outfile(stdout):\n    outfile = b''\n    for line in stdout:\n        try:\n            k, v = [x.strip() for x in line.split(b':', 1)]\n        except ValueError:\n            break\n        if k == b'Decompressed file':\n            outfile = v\n            break\n    return outfile",
    "docstring": "Analyse the output of the xRITDecompress command call and return the file."
  },
  {
    "code": "def stop_job(self, job_id, array_id = None):\n    self.lock()\n    job, array_job = self._job_and_array(job_id, array_id)\n    if job is not None:\n      if job.status in ('executing', 'queued', 'waiting'):\n        logger.info(\"Reset job '%s' (%s) in the database\", job.name, self._format_log(job.id))\n        job.status = 'submitted'\n      if array_job is not None and array_job.status in ('executing', 'queued', 'waiting'):\n        logger.debug(\"Reset array job '%s' in the database\", array_job)\n        array_job.status = 'submitted'\n      if array_job is None:\n        for array_job in job.array:\n          if array_job.status in ('executing', 'queued', 'waiting'):\n            logger.debug(\"Reset array job '%s' in the database\", array_job)\n            array_job.status = 'submitted'\n    self.session.commit()\n    self.unlock()",
    "docstring": "Resets the status of the given to 'submitted' when they are labeled as 'executing'."
  },
  {
    "code": "def small_integer(self, column, auto_increment=False, unsigned=False):\n        return self._add_column(\n            \"small_integer\", column, auto_increment=auto_increment, unsigned=unsigned\n        )",
    "docstring": "Create a new small integer column on the table.\n\n        :param column: The column\n        :type column: str\n\n        :type auto_increment: bool\n\n        :type unsigned: bool\n\n        :rtype: Fluent"
  },
  {
    "code": "def once(self, event, callback):\n        'Define a callback to handle the first event emitted by the server'\n        self._once_events.add(event)\n        self.on(event, callback)",
    "docstring": "Define a callback to handle the first event emitted by the server"
  },
  {
    "code": "def by_login(cls, session, login, local=True):\n        user = cls.first(session,\n                         where=((cls.login == login),\n                                (cls.local == local),)\n                         )\n        return user if user and user.login == login else None",
    "docstring": "Get a user from a given login.\n\n        :param session: SQLAlchemy session\n        :type session: :class:`sqlalchemy.Session`\n\n        :param login: the user login\n        :type login: unicode\n\n        :return: the associated user\n        :rtype: :class:`pyshop.models.User`"
  },
  {
    "code": "def _is_exception_rule(self, element):\n        if element[0].isdigit() and element[-1].isdigit():\n            return True\n        if len(element) > 1 and element[0].isdigit() and element[-2].isdigit() and element[-1].isalpha():\n            return True\n        if len(element) == 1 and element.isalpha():\n            return True\n        return False",
    "docstring": "Check for \"exception rule\".\n\n        Address elements will be appended onto a new line on the lable except\n        for when the penultimate lable line fulfils certain criteria, in which\n        case the element will be concatenated onto the penultimate line. This\n        method checks for those criteria.\n\n        i) First and last characters of the Building Name are numeric\n          (eg '1to1' or '100:1')\n        ii) First and penultimate characters are numeric, last character is\n          alphabetic (eg '12A')\n        iii) Building Name has only one character (eg 'A')"
  },
  {
    "code": "def _register_default_option(nsobj, opt):\n    item = ConfigItem.get(nsobj.namespace_prefix, opt.name)\n    if not item:\n        logger.info('Adding {} ({}) = {} to {}'.format(\n            opt.name,\n            opt.type,\n            opt.default_value,\n            nsobj.namespace_prefix\n        ))\n        item = ConfigItem()\n        item.namespace_prefix = nsobj.namespace_prefix\n        item.key = opt.name\n        item.value = opt.default_value\n        item.type = opt.type\n        item.description = opt.description\n        nsobj.config_items.append(item)\n    else:\n        if item.description != opt.description:\n            logger.info('Updating description of {} / {}'.format(item.namespace_prefix, item.key))\n            item.description = opt.description\n            db.session.add(item)",
    "docstring": "Register default ConfigOption value if it doesn't exist. If does exist, update the description if needed"
  },
  {
    "code": "def _transform_field(field):\n    if isinstance(field, bool):\n        return TRUE if field else FALSE\n    elif isinstance(field, (list, dict)):\n        return json.dumps(field, sort_keys=True, ensure_ascii=False)\n    else:\n        return field",
    "docstring": "transform field for displaying"
  },
  {
    "code": "def splits(cls, datasets, batch_sizes=None, **kwargs):\n        if batch_sizes is None:\n            batch_sizes = [kwargs.pop('batch_size')] * len(datasets)\n        ret = []\n        for i in range(len(datasets)):\n            train = i == 0\n            ret.append(cls(\n                datasets[i], batch_size=batch_sizes[i], train=train, **kwargs))\n        return tuple(ret)",
    "docstring": "Create Iterator objects for multiple splits of a dataset.\n\n        Arguments:\n            datasets: Tuple of Dataset objects corresponding to the splits. The\n                first such object should be the train set.\n            batch_sizes: Tuple of batch sizes to use for the different splits,\n                or None to use the same batch_size for all splits.\n            Remaining keyword arguments: Passed to the constructor of the\n                iterator class being used."
  },
  {
    "code": "def _check_cb(cb_):\n    if cb_ is not None:\n        if hasattr(cb_, '__call__'):\n            return cb_\n        else:\n            log.error('log_callback is not callable, ignoring')\n    return lambda x: x",
    "docstring": "If the callback is None or is not callable, return a lambda that returns\n    the value passed."
  },
  {
    "code": "def dedent(s):\n    head, _, tail = s.partition('\\n')\n    dedented_tail = textwrap.dedent(tail)\n    result = \"{head}\\n{tail}\".format(\n        head=head,\n        tail=dedented_tail)\n    return result",
    "docstring": "Removes the hanging dedent from all the first line of a string."
  },
  {
    "code": "def update(self, request, datum):\n        if getattr(self, 'action_present', False):\n            self.verbose_name = self._get_action_name()\n            self.verbose_name_plural = self._get_action_name('plural')",
    "docstring": "Switches the action verbose name, if needed."
  },
  {
    "code": "def normalize(rp_pyxb):\n    def sort(r, a):\n        d1_common.xml.sort_value_list_pyxb(_get_attr_or_list(r, a))\n    rp_pyxb.preferredMemberNode = set(_get_attr_or_list(rp_pyxb, 'pref')) - set(\n        _get_attr_or_list(rp_pyxb, 'block')\n    )\n    sort(rp_pyxb, 'block')\n    sort(rp_pyxb, 'pref')",
    "docstring": "Normalize a ReplicationPolicy PyXB type in place.\n\n    The preferred and blocked lists are sorted alphabetically. As blocked nodes\n    override preferred nodes, and any node present in both lists is removed from the\n    preferred list.\n\n    Args:\n      rp_pyxb : ReplicationPolicy PyXB object\n        The object will be normalized in place."
  },
  {
    "code": "def get_analysis_element(self, element, sep='|'):\n        return [self.__get_key(word[ANALYSIS], element, sep) for word in self.words]",
    "docstring": "The list of analysis elements of ``words`` layer.\n\n        Parameters\n        ----------\n        element: str\n            The name of the element, for example \"lemma\", \"postag\".\n        sep: str\n            The separator for ambiguous analysis (default: \"|\").\n            As morphological analysis cannot always yield unambiguous results, we\n            return ambiguous values separated by the pipe character as default."
  },
  {
    "code": "def authenticate(self, password):\n        if self.isClosed:\n            raise ValueError(\"operation illegal for closed doc\")\n        val = _fitz.Document_authenticate(self, password)\n        if val:\n            self.isEncrypted = 0\n            self.initData()\n            self.thisown = True\n        return val",
    "docstring": "Decrypt document with a password."
  },
  {
    "code": "def cmd_gimbal_status(self, args):\n        master = self.master\n        if 'GIMBAL_REPORT' in master.messages:\n            print(master.messages['GIMBAL_REPORT'])\n        else:\n            print(\"No GIMBAL_REPORT messages\")",
    "docstring": "show gimbal status"
  },
  {
    "code": "def subtract_months(self, months: int) -> datetime:\n        self.value = self.value - relativedelta(months=months)\n        return self.value",
    "docstring": "Subtracts a number of months from the current value"
  },
  {
    "code": "def crypt(password, cost=2):\n    salt = _generate_salt(cost)\n    hashed = pbkdf2.pbkdf2_hex(password, salt, cost * 500)\n    return \"$pbkdf2-256-1$\" + str(cost) + \"$\" + salt.decode(\"utf-8\") + \"$\" + hashed",
    "docstring": "Hash a password\n\n    result sample:\n        $pbkdf2-256-1$8$FRakfnkgpMjnqs1Xxgjiwgycdf68be9b06451039cc\\\n        0f7075ec1c369fa36f055b1705ec7a\n\n    The returned string is broken down into\n        - The algorithm and version used\n        - The cost factor, number of iterations over the hash\n        - The salt\n        - The password"
  },
  {
    "code": "def union(self, *others, **kwargs):\n        return self._combine_variant_collections(\n            combine_fn=set.union,\n            variant_collections=(self,) + others,\n            kwargs=kwargs)",
    "docstring": "Returns the union of variants in a several VariantCollection objects."
  },
  {
    "code": "def pad_to_3d(a):\n    a_pad = np.zeros([len(a), 3], dtype=a.dtype)\n    a_pad[:, :a.shape[-1]] = a\n    return a_pad",
    "docstring": "Return 1- or 2-dimensional cartesian vectors, converted into a\n    3-dimensional representation, with additional dimensional coordinates\n    assumed to be zero.\n\n    Parameters\n    ----------\n    a: array, shape (n, d), d < 3\n\n    Returns\n    -------\n    ap: array, shape (n, 3)"
  },
  {
    "code": "def get_point_source_fluxes(self, id, energies, tag=None):\n        return self._point_sources.values()[id](energies, tag=tag)",
    "docstring": "Get the fluxes from the id-th point source\n\n        :param id: id of the source\n        :param energies: energies at which you need the flux\n        :param tag: a tuple (integration variable, a, b) specifying the integration to perform. If this\n        parameter is specified then the returned value will be the average flux for the source computed as the integral\n        between a and b over the integration variable divided by (b-a). The integration variable must be an independent\n        variable contained in the model. If b is None, then instead of integrating the integration variable will be\n        set to a and the model evaluated in a.\n        :return: fluxes"
  },
  {
    "code": "def validate(self, command, token, team_id, method):\n        if (team_id, command) not in self._commands:\n            raise SlackError('Command {0} is not found in team {1}'.format(\n                             command, team_id))\n        func, _token, methods, kwargs = self._commands[(team_id, command)]\n        if method not in methods:\n            raise SlackError('{} request is not allowed'.format(method))\n        if token != _token:\n            raise SlackError('Your token {} is invalid'.format(token))",
    "docstring": "Validate request queries with registerd commands\n\n        :param command: command parameter from request\n        :param token: token parameter from request\n        :param team_id: team_id parameter from request\n        :param method: the request method"
  },
  {
    "code": "def act(self, action):\n        action = int(action)\n        assert isinstance(action, int)\n        assert action < self.actions_num, \"%r (%s) invalid\"%(action, type(action))\n        for k in self.world_layer.buttons:\n            self.world_layer.buttons[k] = 0\n        for key in self.world_layer.player.controls[action]:\n            if key in self.world_layer.buttons:\n                self.world_layer.buttons[key] = 1\n        self.step()\n        observation = self.world_layer.get_state()\n        reward = self.world_layer.player.get_reward()\n        terminal = self.world_layer.player.game_over\n        info = {}\n        return observation, reward, terminal, info",
    "docstring": "Take one action for one step"
  },
  {
    "code": "def listener(messages):\n    for m in messages:\n        if m.content_type == 'text':\n            print(str(m.chat.first_name) + \" [\" + str(m.chat.id) + \"]: \" + m.text)",
    "docstring": "When new messages arrive TeleBot will call this function."
  },
  {
    "code": "def find_cookie(self):\n        return_cookies = []\n        origin_domain = self.request_object.dest_addr\n        for cookie in self.cookiejar:\n            for cookie_morsals in cookie[0].values():\n                cover_domain = cookie_morsals['domain']\n                if cover_domain == '':\n                    if origin_domain == cookie[1]:\n                        return_cookies.append(cookie[0])\n                else:\n                    bvalue = cover_domain.lower()\n                    hdn = origin_domain.lower()\n                    nend = hdn.find(bvalue)\n                    if nend is not False:\n                        return_cookies.append(cookie[0])\n        return return_cookies",
    "docstring": "Find a list of all cookies for a given domain"
  },
  {
    "code": "def is_rpm_package_installed(pkg):\n    with settings(hide('warnings', 'running', 'stdout', 'stderr'),\n                  warn_only=True, capture=True):\n        result = sudo(\"rpm -q %s\" % pkg)\n        if result.return_code == 0:\n            return True\n        elif result.return_code == 1:\n            return False\n        else:\n            print(result)\n            raise SystemExit()",
    "docstring": "checks if a particular rpm package is installed"
  },
  {
    "code": "def branches(self):\n        branches = []\n        if self._taken_branch:\n            branches += [(self._taken_branch, 'taken')]\n        if self._not_taken_branch:\n            branches += [(self._not_taken_branch, 'not-taken')]\n        if self._direct_branch:\n            branches += [(self._direct_branch, 'direct')]\n        return branches",
    "docstring": "Get basic block branches."
  },
  {
    "code": "def pipe_sort(context=None, _INPUT=None, conf=None, **kwargs):\n    test = kwargs.pop('pass_if', None)\n    _pass = utils.get_pass(test=test)\n    key_defs = imap(DotDict, utils.listize(conf['KEY']))\n    get_value = partial(utils.get_value, **kwargs)\n    parse_conf = partial(utils.parse_conf, parse_func=get_value, **kwargs)\n    keys = imap(parse_conf, key_defs)\n    order = ('%s%s' % ('-' if k.dir == 'DESC' else '', k.field) for k in keys)\n    comparers = map(get_comparer, order)\n    cmp_func = partial(multikeysort, comparers=comparers)\n    _OUTPUT = _INPUT if _pass else iter(sorted(_INPUT, cmp=cmp_func))\n    return _OUTPUT",
    "docstring": "An operator that sorts the input source according to the specified key.\n    Not loopable. Not lazy.\n\n    Parameters\n    ----------\n    context : pipe2py.Context object\n    _INPUT : pipe2py.modules pipe like object (iterable of items)\n    kwargs -- other inputs, e.g. to feed terminals for rule values\n    conf : {\n        'KEY': [\n            {\n                'field': {'type': 'text', 'value': 'title'},\n                'dir': {'type': 'text', 'value': 'DESC'}\n            }\n        ]\n    }\n\n    Returns\n    -------\n    _OUTPUT : generator of sorted items"
  },
  {
    "code": "def _parse_cpe_name(cpe):\n    part = {\n        'o': 'operating system',\n        'h': 'hardware',\n        'a': 'application',\n    }\n    ret = {}\n    cpe = (cpe or '').split(':')\n    if len(cpe) > 4 and cpe[0] == 'cpe':\n        if cpe[1].startswith('/'):\n            ret['vendor'], ret['product'], ret['version'] = cpe[2:5]\n            ret['phase'] = cpe[5] if len(cpe) > 5 else None\n            ret['part'] = part.get(cpe[1][1:])\n        elif len(cpe) == 13 and cpe[1] == '2.3':\n            ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]\n            ret['part'] = part.get(cpe[2])\n    return ret",
    "docstring": "Parse CPE_NAME data from the os-release\n\n    Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe\n\n    :param cpe:\n    :return:"
  },
  {
    "code": "def doc_children(self, doctype, limiters=[]):\n        result = []\n        for doc in self.docstring:\n            if len(limiters) == 0 or doc.doctype in limiters:\n                result.extend(doc.children(doctype))\n        return result",
    "docstring": "Finds all grand-children of this element's docstrings that match\n        the specified doctype. If 'limiters' is specified, only docstrings\n        with those doctypes are searched."
  },
  {
    "code": "def wr_row_mergeall(self, worksheet, txtstr, fmt, row_idx):\n        hdridxval = len(self.hdrs) - 1\n        worksheet.merge_range(row_idx, 0, row_idx, hdridxval, txtstr, fmt)\n        return row_idx + 1",
    "docstring": "Merge all columns and place text string in widened cell."
  },
  {
    "code": "def cli(context, host, username, password):\n    context.obj = FritzBox(host, username, password)",
    "docstring": "FritzBox SmartHome Tool\n\n    \\b\n    Provides the following functions:\n    - A easy to use library for querying SmartHome actors\n    - This CLI tool for testing\n    - A carbon client for pipeing data into graphite"
  },
  {
    "code": "def example_reading_spec(self):\n    processed_reward_type = tf.float32\n    if self.is_processed_rewards_discrete:\n      processed_reward_type = tf.int64\n    data_fields = {\n        TIMESTEP_FIELD: tf.FixedLenFeature((1,), tf.int64),\n        RAW_REWARD_FIELD: tf.FixedLenFeature((1,), tf.float32),\n        PROCESSED_REWARD_FIELD: tf.FixedLenFeature((1,), processed_reward_type),\n        DONE_FIELD: tf.FixedLenFeature((1,), tf.int64),\n        OBSERVATION_FIELD: self.observation_spec,\n        ACTION_FIELD: self.action_spec,\n    }\n    data_items_to_decoders = {\n        field: tf.contrib.slim.tfexample_decoder.Tensor(field)\n        for field in data_fields\n    }\n    return data_fields, data_items_to_decoders",
    "docstring": "Data fields to store on disk and their decoders."
  },
  {
    "code": "def prepare_auth(self, auth, url=''):\n        if auth is None:\n            url_auth = get_auth_from_url(self.url)\n            auth = url_auth if any(url_auth) else None\n        if auth:\n            if isinstance(auth, tuple) and len(auth) == 2:\n                auth = HTTPBasicAuth(*auth)\n            r = auth(self)\n            self.__dict__.update(r.__dict__)\n            self.prepare_content_length(self.body)",
    "docstring": "Prepares the given HTTP auth data."
  },
  {
    "code": "def _prime_group_perm_caches(self):\n        perm_cache = self._get_group_cached_perms()\n        self.group._authority_perm_cache = perm_cache\n        self.group._authority_perm_cache_filled = True",
    "docstring": "Prime the group cache and put them on the ``self.group``.\n        In addition add a cache filled flag on ``self.group``."
  },
  {
    "code": "def _prettify_response(self, response):\n        if response.content_type == 'text/html; charset=utf-8':\n            ugly = response.get_data(as_text=True)\n            soup = BeautifulSoup(ugly, 'html.parser')\n            pretty = soup.prettify(formatter='html')\n            response.direct_passthrough = False\n            response.set_data(pretty)\n        return response",
    "docstring": "Prettify the HTML response.\n\n        :param response: A Flask Response object."
  },
  {
    "code": "def field_keyword_for_the_layer(self):\n        layer_purpose_key = self.step_kw_purpose.selected_purpose()['key']\n        if layer_purpose_key == layer_purpose_aggregation['key']:\n            return get_compulsory_fields(layer_purpose_key)['key']\n        elif layer_purpose_key in [\n                layer_purpose_exposure['key'], layer_purpose_hazard['key']]:\n            layer_subcategory_key = \\\n                self.step_kw_subcategory.selected_subcategory()['key']\n            return get_compulsory_fields(\n                layer_purpose_key, layer_subcategory_key)['key']\n        else:\n            raise InvalidParameterError",
    "docstring": "Return the proper keyword for field for the current layer.\n\n        :returns: the field keyword\n        :rtype: str"
  },
  {
    "code": "def persistent_attributes(self):\n        if not self._persistence_adapter:\n            raise AttributesManagerException(\n                \"Cannot get PersistentAttributes without Persistence adapter\")\n        if not self._persistent_attributes_set:\n            self._persistence_attributes = (\n                self._persistence_adapter.get_attributes(\n                    request_envelope=self._request_envelope))\n            self._persistent_attributes_set = True\n        return self._persistence_attributes",
    "docstring": "Attributes stored at the Persistence level of the skill lifecycle.\n\n        :return: persistent_attributes retrieved from persistence adapter\n        :rtype: Dict[str, object]\n        :raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException`\n            if trying to get persistent attributes without persistence adapter"
  },
  {
    "code": "def build_blast_cmd(self, fname, dbname):\n        return self.funcs.blastn_func(fname, dbname, self.outdir, self.exes.blast_exe)",
    "docstring": "Return BLASTN command"
  },
  {
    "code": "def _set_visible(self, visibility, grid_index=None):\n        if grid_index is None:\n            for ax in self.flat_grid:\n                ax.set_visible(visibility)\n        else:\n            if grid_index < 0 or grid_index >= len(self.grids):\n                raise IndexError('Valid indices : 0 to {}'.format(len(self.grids) - 1))\n            for ax in self.grids[grid_index]:\n                ax.set_visible(visibility)",
    "docstring": "Sets the visibility property of all axes."
  },
  {
    "code": "def load(self, geojson, uri=None, db=None, collection=None):\n        logging.info(\"Mongo URI: {0}\".format(uri))\n        logging.info(\"Mongo DB: {0}\".format(db))\n        logging.info(\"Mongo Collection: {0}\".format(collection))\n        logging.info(\"Geojson File to be loaded: {0}\".format(geojson))\n        mongo = MongoGeo(db=db, collection=collection, uri=uri)\n        GeoJSONLoader().load(geojson, mongo.insert)",
    "docstring": "Load geojson file into mongodb instance"
  },
  {
    "code": "def add_path(G, data, one_way):\n    path_nodes = data['nodes']\n    del data['nodes']\n    data['oneway'] = one_way\n    path_edges = list(zip(path_nodes[:-1], path_nodes[1:]))\n    G.add_edges_from(path_edges, **data)\n    if not one_way:\n        path_edges_opposite_direction = [(v, u) for u, v in path_edges]\n        G.add_edges_from(path_edges_opposite_direction, **data)",
    "docstring": "Add a path to the graph.\n\n    Parameters\n    ----------\n    G : networkx multidigraph\n    data : dict\n        the attributes of the path\n    one_way : bool\n        if this path is one-way or if it is bi-directional\n\n    Returns\n    -------\n    None"
  },
  {
    "code": "def example_lab_to_xyz():\n    print(\"=== Simple Example: Lab->XYZ ===\")\n    lab = LabColor(0.903, 16.296, -2.22)\n    print(lab)\n    xyz = convert_color(lab, XYZColor)\n    print(xyz)\n    print(\"=== End Example ===\\n\")",
    "docstring": "This function shows a simple conversion of an Lab color to an XYZ color."
  },
  {
    "code": "def throw(self, typ, val=None, tb=None):\n        if self._hub is None or not self._fiber.is_alive():\n            return\n        self._hub.run_callback(self._fiber.throw, typ, val, tb)\n        self._hub = self._fiber = None",
    "docstring": "Throw an exception into the origin fiber. The exception is thrown\n        the next time the event loop runs."
  },
  {
    "code": "def get_initkwargs(cls, form_list, initial_dict=None,\n        instance_dict=None, condition_dict=None, *args, **kwargs):\n        kwargs.update({\n            'initial_dict': initial_dict or {},\n            'instance_dict': instance_dict or {},\n            'condition_dict': condition_dict or {},\n        })\n        init_form_list = SortedDict()\n        assert len(form_list) > 0, 'at least one form is needed'\n        for i, form in enumerate(form_list):\n            if isinstance(form, (list, tuple)):\n                init_form_list[unicode(form[0])] = form[1]\n            else:\n                init_form_list[unicode(i)] = form\n        for form in init_form_list.itervalues():\n            if issubclass(form, formsets.BaseFormSet):\n                form = form.form\n            for field in form.base_fields.itervalues():\n                if (isinstance(field, forms.FileField) and\n                        not hasattr(cls, 'file_storage')):\n                    raise NoFileStorageConfigured\n        kwargs['form_list'] = init_form_list\n        return kwargs",
    "docstring": "Creates a dict with all needed parameters for the form wizard instances.\n\n        * `form_list` - is a list of forms. The list entries can be single form\n          classes or tuples of (`step_name`, `form_class`). If you pass a list\n          of forms, the formwizard will convert the class list to\n          (`zero_based_counter`, `form_class`). This is needed to access the\n          form for a specific step.\n        * `initial_dict` - contains a dictionary of initial data dictionaries.\n          The key should be equal to the `step_name` in the `form_list` (or\n          the str of the zero based counter - if no step_names added in the\n          `form_list`)\n        * `instance_dict` - contains a dictionary of instance objects. This list\n          is only used when `ModelForm`s are used. The key should be equal to\n          the `step_name` in the `form_list`. Same rules as for `initial_dict`\n          apply.\n        * `condition_dict` - contains a dictionary of boolean values or\n          callables. If the value of for a specific `step_name` is callable it\n          will be called with the formwizard instance as the only argument.\n          If the return value is true, the step's form will be used."
  },
  {
    "code": "def call_many(self, callback, args):\n        if isinstance(callback, str):\n            callback = getattr(self, callback)\n        f = None\n        for arg in args:\n            f = callback(*arg)\n        return f",
    "docstring": "callback is run with each arg but run a call per second"
  },
  {
    "code": "def _enough_time_has_passed(self, FPS):\n    if FPS == 0:\n      return False\n    else:\n      earliest_time = self.last_update_time + (1.0 / FPS)\n      return time.time() >= earliest_time",
    "docstring": "For limiting how often frames are computed."
  },
  {
    "code": "def convertToDatetime(fmt=\"%Y-%m-%dT%H:%M:%S.%f\"):\n        def cvt_fn(s,l,t):\n            try:\n                return datetime.strptime(t[0], fmt)\n            except ValueError as ve:\n                raise ParseException(s, l, str(ve))\n        return cvt_fn",
    "docstring": "Helper to create a parse action for converting parsed\n        datetime string to Python datetime.datetime\n\n        Params -\n         - fmt - format to be passed to datetime.strptime (default= ``\"%Y-%m-%dT%H:%M:%S.%f\"``)\n\n        Example::\n\n            dt_expr = pyparsing_common.iso8601_datetime.copy()\n            dt_expr.setParseAction(pyparsing_common.convertToDatetime())\n            print(dt_expr.parseString(\"1999-12-31T23:59:59.999\"))\n\n        prints::\n\n            [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]"
  },
  {
    "code": "def get_position(self, rst_tree, node_id=None):\n        if node_id is None:\n            node_id = self.root_id\n        if node_id in rst_tree.edu_set:\n            return rst_tree.edus.index(node_id)\n        return min(self.get_position(rst_tree, child_node_id)\n                   for child_node_id in rst_tree.child_dict[node_id])",
    "docstring": "Get the linear position of an element of this DGParentedTree in an RSTTree.\n\n        If ``node_id`` is given, this will return the position of the subtree\n        with that node ID. Otherwise, the position of the root of this\n        DGParentedTree in the given RSTTree is returned."
  },
  {
    "code": "def _get_rate(self, value):\n        if value == 0:\n            return 0\n        else:\n            return MINIMAL_RATE_HZ * math.exp(value * self._get_factor())",
    "docstring": "Return the rate in Hz from the short int value"
  },
  {
    "code": "def _combined_wildcards_iter(flatterm: Iterator[TermAtom]) -> Iterator[TermAtom]:\n        last_wildcard = None\n        for term in flatterm:\n            if isinstance(term, Wildcard) and not isinstance(term, SymbolWildcard):\n                if last_wildcard is not None:\n                    new_min_count = last_wildcard.min_count + term.min_count\n                    new_fixed_size = last_wildcard.fixed_size and term.fixed_size\n                    last_wildcard = Wildcard(new_min_count, new_fixed_size)\n                else:\n                    last_wildcard = Wildcard(term.min_count, term.fixed_size)\n            else:\n                if last_wildcard is not None:\n                    yield last_wildcard\n                    last_wildcard = None\n                yield term\n        if last_wildcard is not None:\n            yield last_wildcard",
    "docstring": "Combine consecutive wildcards in a flatterm into a single one."
  },
  {
    "code": "def _find_path(self, search_dirs, file_name):\n        for dir_path in search_dirs:\n            file_path = os.path.join(dir_path, file_name)\n            if os.path.exists(file_path):\n                return file_path\n        return None",
    "docstring": "Search for the given file, and return the path.\n\n        Returns None if the file is not found."
  },
  {
    "code": "def validate_deprecation_semver(version_string, version_description):\n  if version_string is None:\n    raise MissingSemanticVersionError('The {} must be provided.'.format(version_description))\n  if not isinstance(version_string, six.string_types):\n    raise BadSemanticVersionError('The {} must be a version string.'.format(version_description))\n  try:\n    v = Version(version_string)\n    if len(v.base_version.split('.')) != 3:\n      raise BadSemanticVersionError('The given {} is not a valid version: '\n                                   '{}'.format(version_description, version_string))\n    if not v.is_prerelease:\n      raise NonDevSemanticVersionError('The given {} is not a dev version: {}\\n'\n                                      'Features should generally be removed in the first `dev` release '\n                                      'of a release cycle.'.format(version_description, version_string))\n    return v\n  except InvalidVersion as e:\n    raise BadSemanticVersionError('The given {} {} is not a valid version: '\n                                 '{}'.format(version_description, version_string, e))",
    "docstring": "Validates that version_string is a valid semver.\n\n  If so, returns that semver.  Raises an error otherwise.\n\n  :param str version_string: A pantsbuild.pants version which affects some deprecated entity.\n  :param str version_description: A string used in exception messages to describe what the\n                                  `version_string` represents.\n  :rtype: `packaging.version.Version`\n  :raises DeprecationApplicationError: if the version_string parameter is invalid."
  },
  {
    "code": "def get_composition(self):\n        if not bool(self._my_map['compositionId']):\n            raise errors.IllegalState('composition empty')\n        mgr = self._get_provider_manager('REPOSITORY')\n        if not mgr.supports_composition_lookup():\n            raise errors.OperationFailed('Repository does not support Composition lookup')\n        lookup_session = mgr.get_composition_lookup_session(proxy=getattr(self, \"_proxy\", None))\n        lookup_session.use_federated_repository_view()\n        return lookup_session.get_composition(self.get_composition_id())",
    "docstring": "Gets the Composition corresponding to this asset.\n\n        return: (osid.repository.Composition) - the composiiton\n        raise:  IllegalState - ``is_composition()`` is ``false``\n        raise:  OperationFailed - unable to complete request\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _get_appointee(id):\n    url = \"%s%s.json\" % (URL_PREFIX, id)\n    response = get_resource(url)\n    return process_json(response)",
    "docstring": "Return a restclients.models.hrp.AppointeePerson object"
  },
  {
    "code": "def debug(self, msg, indent=0, **kwargs):\n        return self.logger.debug(self._indent(msg, indent), **kwargs)",
    "docstring": "invoke ``self.logger.debug``"
  },
  {
    "code": "def rlw_filter(name, location, size, unsize):\n    arch = _meta_.arch\n    if arch.startswith(\"i\") and arch.endswith(\"86\"):\n        arch = \"i486\"\n    (fname, flocation, fsize, funsize) = ([] for i in range(4))\n    for n, l, s, u in zip(name, location, size, unsize):\n        loc = l.split(\"/\")\n        if arch == loc[-1]:\n            fname.append(n)\n            flocation.append(l)\n            fsize.append(s)\n            funsize.append(u)\n    return [fname, flocation, fsize, funsize]",
    "docstring": "Filter rlw repository data"
  },
  {
    "code": "def post(self, path, data={}):\n        response = requests.post(API_URL + path, data=json.dumps(data), headers=self._set_headers())\n        return self._check_response(response, self.post, path, data)",
    "docstring": "Perform POST Request"
  },
  {
    "code": "def fi_business_id(business_id):\n    if not business_id or not re.match(business_id_pattern, business_id):\n        return False\n    factors = [7, 9, 10, 5, 8, 4, 2]\n    numbers = map(int, business_id[:7])\n    checksum = int(business_id[8])\n    sum_ = sum(f * n for f, n in zip(factors, numbers))\n    modulo = sum_ % 11\n    return (11 - modulo == checksum) or (modulo == 0 and checksum == 0)",
    "docstring": "Validate a Finnish Business ID.\n\n    Each company in Finland has a distinct business id. For more\n    information see `Finnish Trade Register`_\n\n    .. _Finnish Trade Register:\n        http://en.wikipedia.org/wiki/Finnish_Trade_Register\n\n    Examples::\n\n        >>> fi_business_id('0112038-9')  # Fast Monkeys Ltd\n        True\n\n        >>> fi_business_id('1234567-8')  # Bogus ID\n        ValidationFailure(func=fi_business_id, ...)\n\n    .. versionadded:: 0.4\n    .. versionchanged:: 0.5\n        Method renamed from ``finnish_business_id`` to ``fi_business_id``\n\n    :param business_id: business_id to validate"
  },
  {
    "code": "def update_on_event(self, e):\n        if e.type == QUIT:\n            self.running = False\n        elif e.type == KEYDOWN:\n            if e.key == K_ESCAPE:\n                self.running = False\n            elif e.key == K_F4 and e.mod & KMOD_ALT:\n                self.running = False\n        elif e.type == VIDEORESIZE:\n            self.SCREEN_SIZE = e.size\n            self.screen = self.new_screen()",
    "docstring": "Process a single event."
  },
  {
    "code": "def init_app(self, app):\n        app.url_rule_class = partial(NavigationRule, copilot=self)\n        app.context_processor(self.inject_context)",
    "docstring": "Register the extension with the application.\n\n        Args:\n            app (flask.Flask): The application to register with."
  },
  {
    "code": "def get_edge_list(self):\n        edge_objs = list()\n        for obj_dict_list in self.obj_dict['edges'].values():\n            edge_objs.extend([\n                Edge(obj_dict=obj_d)\n                for obj_d\n                in obj_dict_list])\n        return edge_objs",
    "docstring": "Get the list of Edge instances.\n\n        This method returns the list of Edge instances\n        composing the graph."
  },
  {
    "code": "def configure_client(\n            cls, address: Union[str, Tuple[str, int], Path] = 'localhost', port: int = 6379,\n            db: int = 0, password: str = None, ssl: Union[bool, str, SSLContext] = False,\n            **client_args) -> Dict[str, Any]:\n        assert check_argument_types()\n        if isinstance(address, str) and not address.startswith('/'):\n            address = (address, port)\n        elif isinstance(address, Path):\n            address = str(address)\n        client_args.update({\n            'address': address,\n            'db': db,\n            'password': password,\n            'ssl': resolve_reference(ssl)\n        })\n        return client_args",
    "docstring": "Configure a Redis client.\n\n        :param address: IP address, host name or path to a UNIX socket\n        :param port: port number to connect to (ignored for UNIX sockets)\n        :param db: database number to connect to\n        :param password: password used if the server requires authentication\n        :param ssl: one of the following:\n\n            * ``False`` to disable SSL\n            * ``True`` to enable SSL using the default context\n            * an :class:`~ssl.SSLContext` instance\n            * a ``module:varname`` reference to an :class:`~ssl.SSLContext` instance\n            * name of an :class:`~ssl.SSLContext` resource\n        :param client_args: extra keyword arguments passed to :func:`~aioredis.create_redis_pool`"
  },
  {
    "code": "def build_authorization_endpoint(self, request, disable_sso=None):\n        self.load_config()\n        redirect_to = request.GET.get(REDIRECT_FIELD_NAME, None)\n        if not redirect_to:\n            redirect_to = django_settings.LOGIN_REDIRECT_URL\n        redirect_to = base64.urlsafe_b64encode(redirect_to.encode()).decode()\n        query = QueryDict(mutable=True)\n        query.update({\n            \"response_type\": \"code\",\n            \"client_id\": settings.CLIENT_ID,\n            \"resource\": settings.RELYING_PARTY_ID,\n            \"redirect_uri\": self.redirect_uri(request),\n            \"state\": redirect_to,\n        })\n        if self._mode == \"openid_connect\":\n            query[\"scope\"] = \"openid\"\n            if (disable_sso is None and settings.DISABLE_SSO) or disable_sso is True:\n                query[\"prompt\"] = \"login\"\n        return \"{0}?{1}\".format(self.authorization_endpoint, query.urlencode())",
    "docstring": "This function returns the ADFS authorization URL.\n\n        Args:\n            request(django.http.request.HttpRequest): A django Request object\n            disable_sso(bool): Whether to disable single sign-on and force the ADFS server to show a login prompt.\n\n        Returns:\n            str: The redirect URI"
  },
  {
    "code": "def registerTrailingStop(self, tickerId, orderId=0, quantity=1,\n            lastPrice=0, trailPercent=100., trailAmount=0., parentId=0, **kwargs):\n        ticksize = self.contractDetails(tickerId)[\"m_minTick\"]\n        trailingStop = self.trailingStops[tickerId] = {\n            \"orderId\": orderId,\n            \"parentId\": parentId,\n            \"lastPrice\": lastPrice,\n            \"trailAmount\": trailAmount,\n            \"trailPercent\": trailPercent,\n            \"quantity\": quantity,\n            \"ticksize\": ticksize\n        }\n        return trailingStop",
    "docstring": "adds trailing stop to monitor list"
  },
  {
    "code": "def inc(self):\n        self.lock.acquire()\n        cur = self.counter\n        self.counter += 1\n        self.lock.release()\n        return cur",
    "docstring": "Get index for new entry."
  },
  {
    "code": "async def amiUsage(self, *args, **kwargs):\n        return await self._makeApiCall(self.funcinfo[\"amiUsage\"], *args, **kwargs)",
    "docstring": "See the list of AMIs and their usage\n\n        List AMIs and their usage by returning a list of objects in the form:\n        {\n        region: string\n          volumetype: string\n          lastused: timestamp\n        }\n\n        This method is ``experimental``"
  },
  {
    "code": "def listdir(self, target_directory):\n        target_directory = self.resolve_path(target_directory, allow_fd=True)\n        directory = self.confirmdir(target_directory)\n        directory_contents = directory.contents\n        return list(directory_contents.keys())",
    "docstring": "Return a list of file names in target_directory.\n\n        Args:\n            target_directory: Path to the target directory within the\n                fake filesystem.\n\n        Returns:\n            A list of file names within the target directory in arbitrary\n            order.\n\n        Raises:\n            OSError: if the target is not a directory."
  },
  {
    "code": "def rand_crop(*args, padding_mode='reflection', p:float=1.):\n    \"Randomized version of `crop_pad`.\"\n    return crop_pad(*args, **rand_pos, padding_mode=padding_mode, p=p)",
    "docstring": "Randomized version of `crop_pad`."
  },
  {
    "code": "def _set_tag(self, tag=None, tags=None, value=True):\n        existing_tags = self._requirements.get(\"tags\")\n        if tags and not tag:\n            existing_tags = merge(existing_tags, tags)\n            self._requirements[\"tags\"] = existing_tags\n        elif tag and not tags:\n            existing_tags[tag] = value\n            self._requirements[\"tags\"] = existing_tags",
    "docstring": "Sets the value of a specific tag or merges existing tags with a dict of new tags.\n        Either tag or tags must be None.\n\n        :param tag: Tag which needs to be set.\n        :param tags: Set of tags which needs to be merged with existing tags.\n        :param value: Value to set for net tag named by :param tag.\n        :return: Nothing"
  },
  {
    "code": "def is_date(self):\n        dt = DATA_TYPES['date']\n        if type(self.data) is dt['type'] and '-' in str(self.data) and str(self.data).count('-') == 2:\n            date_split = str(self.data).split('-')\n            y, m, d = date_split[0], date_split[1], date_split[2]\n            valid_year, valid_months, valid_days = int(y) in YEARS, int(m) in MONTHS, int(d) in DAYS\n            if all(i is True for i in (valid_year, valid_months, valid_days)):\n                self.type = 'date'.upper()\n                self.len = None\n                return True",
    "docstring": "Determine if a data record is of type DATE."
  },
  {
    "code": "def pixel_data(self):\n        from .. import extensions as _extensions\n        data = _np.zeros((self.height, self.width, self.channels), dtype=_np.uint8)\n        _extensions.image_load_to_numpy(self, data.ctypes.data, data.strides)\n        if self.channels == 1:\n            data = data.squeeze(2)\n        return data",
    "docstring": "Returns the pixel data stored in the Image object.\n\n        Returns\n        -------\n        out : numpy.array\n            The pixel data of the Image object. It returns a multi-dimensional\n            numpy array, where the shape of the array represents the shape of\n            the image (height, weight, channels).\n\n        See Also\n        --------\n        width, channels, height\n\n        Examples\n        --------\n        >>> img = turicreate.Image('https://static.turi.com/datasets/images/sample.jpg')\n        >>> image_array = img.pixel_data"
  },
  {
    "code": "def entry_verifier(entries, regex, delimiter):\n    cregex = re.compile(regex)\n    python_version = int(sys.version.split('.')[0])\n    decoder = 'unicode-escape' if python_version == 3 else 'string-escape'\n    dedelimiter = codecs.decode(delimiter, decoder)\n    for entry in entries:\n        match = re.match(cregex, entry)\n        if not match:\n            split_regex = regex.split(delimiter)\n            split_entry = entry.split(dedelimiter)\n            part = 0\n            for regex_segment, entry_segment in zip(split_regex, split_entry):\n                if not regex_segment[0] == '^':\n                    regex_segment = '^' + regex_segment\n                if not regex_segment[-1] == '$':\n                    regex_segment += '$'\n                if not re.match(regex_segment, entry_segment):\n                    raise FormatError(template=regex_segment,\n                                      subject=entry_segment,\n                                      part=part)\n                part += 1",
    "docstring": "Checks each entry against regex for validity,\n\n    If an entry does not match the regex, the entry and regex\n    are broken down by the delimiter and each segment is analyzed\n    to produce an accurate error message.\n\n    Args:\n        entries (list): List of entries to check with regex\n\n        regex (str): Regular expression to compare entries with\n\n        delimiter (str): Character to split entry and regex by, used to check\n            parts of entry and regex to narrow in on the error\n\n    Raises:\n        FormatError: Class containing regex match error data\n\n    Example:\n        >>> regex = r'^>.+\\\\n[ACGTU]+\\\\n$'\n        >>> entry = [r'>entry1\\\\nAGGGACTA\\\\n']\n        >>> entry_verifier(entry, regex, '\\\\n')"
  },
  {
    "code": "def inverse_tile_2d(input, k_x, k_y, name):\n    batch_size, h, w, c = input.get_shape().as_list()\n    if batch_size is None:\n        batch_size = -1\n    assert w % k_x == 0 and h % k_y == 0\n    with tf.variable_scope(name) as scope:\n        tmp = input\n        tmp = tf.reshape(tmp, (batch_size, int(h * k_y), w, int(c * k_x)))\n        tmp = tf.transpose(tmp, [0, 2, 1, 3])\n        tmp = tf.reshape(tmp, (batch_size, w, h, int(c * k_y * k_x)))\n        tmp = tf.transpose(tmp, [0, 2, 1, 3])\n    return tmp",
    "docstring": "An inverse tiling layer.\n\n        An inverse to the tiling layer can be of great use, since you can keep the resolution of your output low,\n        but harness the benefits of the resolution of a higher level feature layer.\n        If you insist on a source you can call it very lightly inspired by yolo9000 \"passthrough layer\".\n\n        :param input: Your input tensor. (Assert input.shape[1] % k_y = 0 and input.shape[2] % k_x = 0)\n        :param k_x: The tiling factor in x direction [int].\n        :param k_y: The tiling factor in y direction [int].\n        :param name: The name of the layer.\n        :return: The output tensor of shape [batch_size, inp.height / k_y, inp.width / k_x, inp.channels * k_x * k_y]."
  },
  {
    "code": "def remote_sys_name_uneq_store(self, remote_system_name):\n        if remote_system_name != self.remote_system_name:\n            self.remote_system_name = remote_system_name\n            return True\n        return False",
    "docstring": "This function saves the system name, if different from stored."
  },
  {
    "code": "def get_node(self, key):\n        self._check_if_open()\n        try:\n            if not key.startswith('/'):\n                key = '/' + key\n            return self._handle.get_node(self.root, key)\n        except _table_mod.exceptions.NoSuchNodeError:\n            return None",
    "docstring": "return the node with the key or None if it does not exist"
  },
  {
    "code": "def _crc16_checksum(bytes):\n    crc = 0x0000\n    polynomial = 0x1021\n    for byte in bytes:\n        for i in range(8):\n            bit = (byte >> (7 - i) & 1) == 1\n            c15 = (crc >> 15 & 1) == 1\n            crc <<= 1\n            if c15 ^ bit:\n                crc ^= polynomial\n    return crc & 0xFFFF",
    "docstring": "Returns the CRC-16 checksum of bytearray bytes\n\n    Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html\n\n    Initial value changed to 0x0000 to match Stellar configuration."
  },
  {
    "code": "def get(self, *args, **kwargs):\n        payload = self.buf.get(*args, **kwargs)\n        logger.debug(\"Removing RPC payload from ControlBuffer queue: %s\", payload)\n        return payload",
    "docstring": "Call from main thread."
  },
  {
    "code": "def get_one(self, criteria):\n        try:\n            items = [item for item in self._get_with_criteria(criteria, limit=1)]\n            return items[0]\n        except:\n            return None",
    "docstring": "return one item"
  },
  {
    "code": "def _list_response(self, response):\n        if type(response) is list:\n            return response\n        if type(response) is dict:\n            return [response]",
    "docstring": "This method check if the response is a dict and wrap it into a list.\n        If the response is already a list, it returns the response directly.\n        This workaround is necessary because the API doesn't return a list\n        if only one item is found."
  },
  {
    "code": "def get_Generic_parameters(tp, generic_supertype):\n    try:\n        res = _select_Generic_superclass_parameters(tp, generic_supertype)\n    except TypeError:\n        res = None\n    if res is None:\n        raise TypeError(\"%s has no proper parameters defined by %s.\"%\n                (type_str(tp), type_str(generic_supertype)))\n    else:\n        return tuple(res)",
    "docstring": "tp must be a subclass of generic_supertype.\n    Retrieves the type values from tp that correspond to parameters\n    defined by generic_supertype.\n\n    E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent\n    to get_Mapping_key_value(tp) except for the error message.\n\n    Note that get_Generic_itemtype(tp) is not exactly equal to\n    get_Generic_parameters(tp, typing.Container), as that method\n    additionally contains treatment for typing.Tuple and typing.Iterable."
  },
  {
    "code": "def validate(self):\n        if self.access_token is None:\n            raise ConfigurationError('No access token provided. '\n                                     'Set your access token during client initialization using: '\n                                     '\"basecrm.Client(access_token= <YOUR_PERSONAL_ACCESS_TOKEN>)\"')\n        if re.search(r'\\s', self.access_token):\n            raise ConfigurationError('Provided access token is invalid '\n                                     'as it contains disallowed characters. '\n                                     'Please double-check you access token.')\n        if len(self.access_token) != 64:\n            raise ConfigurationError('Provided access token is invalid '\n                                     'as it has invalid length. '\n                                     'Please double-check your access token.')\n        if not self.base_url or not re.match(self.URL_REGEXP, self.base_url):\n            raise ConfigurationError('Provided base url is invalid '\n                                     'as it not a valid URI. '\n                                     'Please make sure it incldues the schema part, '\n                                     'both http and https are accepted, '\n                                     'and the hierarchical part')\n        return True",
    "docstring": "Validates whether a configuration is valid.\n\n        :rtype: bool\n        :raises ConfigurationError: if no ``access_token`` provided.\n        :raises ConfigurationError: if provided ``access_token`` is invalid - contains disallowed characters.\n        :raises ConfigurationError: if provided ``access_token`` is invalid - has invalid length.\n        :raises ConfigurationError: if provided ``base_url`` is invalid."
  },
  {
    "code": "def set_tag(self, key, value, update_session=True):\n        existing_tags = {x.key: x for x in self.tags}\n        if key in existing_tags:\n            tag = existing_tags[key]\n            if tag.value == value:\n                return False\n            tag.value = value\n        else:\n            tag = Tag()\n            tag.resource_id = self.id\n            tag.key = key\n            tag.value = value\n            self.tags.append(tag)\n        if update_session:\n            db.session.add(tag)\n        return True",
    "docstring": "Create or set the value of the tag with `key` to `value`. Returns `True` if the tag was created or updated or\n        `False` if there were no changes to be made.\n\n        Args:\n            key (str): Key of the tag\n            value (str): Value of the tag\n            update_session (bool): Automatically add the change to the SQLAlchemy session. Default: True\n\n        Returns:\n            `bool`"
  },
  {
    "code": "def get_history(self, filters=(), pagesize=15, offset=0):\n        response = None\n        try:\n            response = requests.get(\n                urls.history(self._giid),\n                headers={\n                    'Accept': 'application/json, text/javascript, */*; q=0.01',\n                    'Cookie': 'vid={}'.format(self._vid)},\n                params={\n                    \"offset\": int(offset),\n                    \"pagesize\": int(pagesize),\n                    \"notificationCategories\": filters})\n        except requests.exceptions.RequestException as ex:\n            raise RequestError(ex)\n        _validate_response(response)\n        return json.loads(response.text)",
    "docstring": "Get recent events\n\n        Args:\n            filters (string set): 'ARM', 'DISARM', 'FIRE', 'INTRUSION',\n                                  'TECHNICAL', 'SOS', 'WARNING', 'LOCK',\n                                  'UNLOCK'\n            pagesize (int): Number of events to display\n            offset (int): Skip pagesize * offset first events"
  },
  {
    "code": "def _HandleLegacy(self, args, token=None):\n    hunt_obj = aff4.FACTORY.Open(\n        args.hunt_id.ToURN(), aff4_type=implementation.GRRHunt, token=token)\n    if isinstance(hunt_obj.context, rdf_hunts.HuntContext):\n      state = api_call_handler_utils.ApiDataObject()\n      result = ApiGetHuntContextResult(context=hunt_obj.context, state=state)\n      result.args = hunt_obj.args\n      return result\n    else:\n      context = api_call_handler_utils.ApiDataObject().InitFromDataObject(\n          hunt_obj.context)\n      return ApiGetHuntContextResult(state=context)",
    "docstring": "Retrieves the context for a hunt."
  },
  {
    "code": "def deprecated(replacement_description):\n    def decorate(fn_or_class):\n        if isinstance(fn_or_class, type):\n            pass\n        else:\n            try:\n                fn_or_class.__doc__ = \"This API point is obsolete. %s\\n\\n%s\" % (\n                    replacement_description,\n                    fn_or_class.__doc__,\n                )\n            except AttributeError:\n                pass\n        return fn_or_class\n    return decorate",
    "docstring": "States that method is deprecated.\n\n    :param replacement_description: Describes what must be used instead.\n    :return: the original method with modified docstring."
  },
  {
    "code": "def build_napp_package(napp_name):\n        ignored_extensions = ['.swp', '.pyc', '.napp']\n        ignored_dirs = ['__pycache__', '.git', '.tox']\n        files = os.listdir()\n        for filename in files:\n            if os.path.isfile(filename) and '.' in filename and \\\n                    filename.rsplit('.', 1)[1] in ignored_extensions:\n                files.remove(filename)\n            elif os.path.isdir(filename) and filename in ignored_dirs:\n                files.remove(filename)\n        napp_file = tarfile.open(napp_name + '.napp', 'x:xz')\n        for local_f in files:\n            napp_file.add(local_f)\n        napp_file.close()\n        file_payload = open(napp_name + '.napp', 'rb')\n        os.remove(napp_name + '.napp')\n        return file_payload",
    "docstring": "Build the .napp file to be sent to the napps server.\n\n        Args:\n            napp_identifier (str): Identifier formatted as\n                <username>/<napp_name>\n\n        Return:\n            file_payload (binary): The binary representation of the napp\n                package that will be POSTed to the napp server."
  },
  {
    "code": "def httpapi_request(client, **params) -> 'Response':\n    return requests.get(\n        _HTTPAPI,\n        params={\n            'client': client.name,\n            'clientver': client.version,\n            'protover': 1,\n            **params\n        })",
    "docstring": "Send a request to AniDB HTTP API.\n\n    https://wiki.anidb.net/w/HTTP_API_Definition"
  },
  {
    "code": "def update_glances(self):\n        try:\n            server_stats = json.loads(self.client.getAll())\n        except socket.error:\n            return \"Disconnected\"\n        except Fault:\n            return \"Disconnected\"\n        else:\n            self.stats.update(server_stats)\n            return \"Connected\"",
    "docstring": "Get stats from Glances server.\n\n        Return the client/server connection status:\n        - Connected: Connection OK\n        - Disconnected: Connection NOK"
  },
  {
    "code": "def findViewsWithAttribute(self, attr, val, root=\"ROOT\"):\n        return self.__findViewsWithAttributeInTree(attr, val, root)",
    "docstring": "Finds the Views with the specified attribute and value.\n        This allows you to see all items that match your criteria in the view hierarchy\n\n        Usage:\n          buttons = v.findViewsWithAttribute(\"class\", \"android.widget.Button\")"
  },
  {
    "code": "def match(self, dom, act):\n        return self.match_domain(dom) and self.match_action(act)",
    "docstring": "Check if the given `domain` and `act` are allowed\n        by this capability"
  },
  {
    "code": "def parse_time(time):\n    unit = time[-1]\n    if unit not in ['s', 'm', 'h', 'd']:\n        print_error('the unit of time could only from {s, m, h, d}')\n        exit(1)\n    time = time[:-1]\n    if not time.isdigit():\n        print_error('time format error!')\n        exit(1)\n    parse_dict = {'s':1, 'm':60, 'h':3600, 'd':86400}\n    return int(time) * parse_dict[unit]",
    "docstring": "Change the time to seconds"
  },
  {
    "code": "def sampleLocation(self):\n    areaRatio = self.radius / (self.radius + self.height)\n    if random.random() < areaRatio:\n      return self._sampleLocationOnDisc()\n    else:\n      return self._sampleLocationOnSide()",
    "docstring": "Simple method to sample uniformly from a cylinder."
  },
  {
    "code": "def output_channels(self):\n    if callable(self._output_channels):\n      self._output_channels = self._output_channels()\n    self._output_channels = int(self._output_channels)\n    return self._output_channels",
    "docstring": "Returns the number of output channels."
  },
  {
    "code": "def edit_ticket_links(self, ticket_id, **kwargs):\n        post_data = ''\n        for key in kwargs:\n            post_data += \"{}: {}\\n\".format(key, str(kwargs[key]))\n        msg = self.__request('ticket/{}/links'.format(str(ticket_id), ),\n                             post_data={'content': post_data})\n        state = msg.split('\\n')[2]\n        return self.RE_PATTERNS['links_updated_pattern'].match(state) is not None",
    "docstring": "Edit ticket links.\n\n        .. warning:: This method is deprecated in favour of edit_link method, because\n           there exists bug in RT 3.8 REST API causing mapping created links to\n           ticket/1. The only drawback is that edit_link cannot process multiple\n           links all at once.\n\n        :param ticket_id: ID of ticket to edit\n        :keyword kwargs: Other arguments possible to set: DependsOn,\n                         DependedOnBy, RefersTo, ReferredToBy, Members,\n                         MemberOf. Each value should be either ticker ID or\n                         external link. Int types are converted. Use empty\n                         string as value to delete existing link.\n        :returns: ``True``\n                      Operation was successful\n                  ``False``\n                      Ticket with given ID does not exist or unknown parameter\n                      was set (in this case all other valid fields are changed)"
  },
  {
    "code": "def to_dict(self):\n        return {\n            'mean': self.mean,\n            'var': self.var,\n            'min': self.min,\n            'max': self.max,\n            'num': self.num\n        }",
    "docstring": "Return the stats as a dictionary."
  },
  {
    "code": "def get_duration(self, matrix_name):\n        duration = 0.0\n        if matrix_name in self.data:\n            duration = sum([stage.duration() for stage in self.data[matrix_name]])\n        return duration",
    "docstring": "Get duration for a concrete matrix.\n\n        Args:\n            matrix_name (str): name of the Matrix.\n\n        Returns:\n            float: duration of concrete matrix in seconds."
  },
  {
    "code": "def move(self, folder):\n        if self.object_id is None:\n            raise RuntimeError('Attempting to move an unsaved Message')\n        url = self.build_url(\n            self._endpoints.get('move_message').format(id=self.object_id))\n        if isinstance(folder, str):\n            folder_id = folder\n        else:\n            folder_id = getattr(folder, 'folder_id', None)\n        if not folder_id:\n            raise RuntimeError('Must Provide a valid folder_id')\n        data = {self._cc('destinationId'): folder_id}\n        response = self.con.post(url, data=data)\n        if not response:\n            return False\n        self.folder_id = folder_id\n        return True",
    "docstring": "Move the message to a given folder\n\n        :param folder: Folder object or Folder id or Well-known name to\n         move this message to\n        :type folder: str or mailbox.Folder\n        :return: Success / Failure\n        :rtype: bool"
  },
  {
    "code": "def _decode(image_data):\n    from ...data_structures.sarray import SArray as _SArray\n    from ... import extensions as _extensions\n    if type(image_data) is _SArray:\n        return _extensions.decode_image_sarray(image_data)\n    elif type(image_data) is _Image:\n        return _extensions.decode_image(image_data)",
    "docstring": "Internal helper function for decoding a single Image or an SArray of Images"
  },
  {
    "code": "def interval_tree(intervals):\n    if intervals == []:\n        return None\n    center = intervals[len(intervals) // 2][0]\n    L = []\n    R = []\n    C = []\n    for I in intervals:\n        if I[1] <= center:\n            L.append(I)\n        elif center < I[0]:\n            R.append(I)\n        else:\n            C.append(I)\n    by_low = sorted((I[0], I) for I in C)\n    by_high = sorted((I[1], I) for I in C)\n    IL = interval_tree(L)\n    IR = interval_tree(R)\n    return _Node(center, by_low, by_high, IL, IR)",
    "docstring": "Construct an interval tree\n\n    :param intervals: list of half-open intervals\n                      encoded as value pairs *[left, right)*\n    :assumes: intervals are lexicographically ordered\n              ``>>> assert intervals == sorted(intervals)``\n    :returns: the root of the interval tree\n    :complexity: :math:`O(n)`"
  },
  {
    "code": "def struct_member_error(err, sid, name, offset, size):\n    exception, msg = STRUCT_ERROR_MAP[err]\n    struct_name = idc.GetStrucName(sid)\n    return exception(('AddStructMember(struct=\"{}\", member=\"{}\", offset={}, size={}) '\n                      'failed: {}').format(\n        struct_name,\n        name,\n        offset,\n        size,\n        msg\n    ))",
    "docstring": "Create and format a struct member exception.\n\n    Args:\n        err: The error value returned from struct member creation\n        sid: The struct id\n        name: The member name\n        offset: Memeber offset\n        size: Member size\n\n    Returns:\n        A ``SarkErrorAddStructMemeberFailed`` derivative exception, with an\n        informative message."
  },
  {
    "code": "def getTicker(pair, connection=None, info=None):\n    if info is not None:\n        info.validate_pair(pair)\n    if connection is None:\n        connection = common.BTCEConnection()\n    response = connection.makeJSONRequest(\"/api/3/ticker/%s\" % pair)\n    if type(response) is not dict:\n        raise TypeError(\"The response is a %r, not a dict.\" % type(response))\n    elif u'error' in response:\n        print(\"There is a error \\\"%s\\\" while obtaining ticker %s\" % (response['error'], pair))\n        ticker = None\n    else:\n        ticker = Ticker(**response[pair])\n    return ticker",
    "docstring": "Retrieve the ticker for the given pair.  Returns a Ticker instance."
  },
  {
    "code": "def list(path, ext=None, start=None, stop=None, recursive=False):\n        files = listflat(path, ext) if not recursive else listrecursive(path, ext)\n        if len(files) < 1:\n            raise FileNotFoundError('Cannot find files of type \"%s\" in %s'\n                                    % (ext if ext else '*', path))\n        files = select(files, start, stop)\n        return files",
    "docstring": "Get sorted list of file paths matching path and extension"
  },
  {
    "code": "def check_future(self, fut):\n        done = self.done = fut.done()\n        if done and not self.prev_done:\n            self.done_since = self.ioloop.time()\n        self.prev_done = done",
    "docstring": "Call with each future that is to be yielded on"
  },
  {
    "code": "def get_stoch(self, symbol, interval='daily', fastkperiod=None,\n                  slowkperiod=None, slowdperiod=None, slowkmatype=None, slowdmatype=None):\n        _FUNCTION_KEY = \"STOCH\"\n        return _FUNCTION_KEY, 'Technical Analysis: STOCH', 'Meta Data'",
    "docstring": "Return the stochatic oscillator values in two\n        json objects as data and meta_data. It raises ValueError when problems\n        arise\n\n        Keyword Arguments:\n            symbol:  the symbol for the equity we want to get its data\n            interval:  time interval between two conscutive values,\n                supported values are '1min', '5min', '15min', '30min', '60min', 'daily',\n                'weekly', 'monthly' (default 'daily')\n            fastkperiod:  The time period of the fastk moving average. Positive\n                integers are accepted (default=None)\n            slowkperiod:  The time period of the slowk moving average. Positive\n                integers are accepted (default=None)\n            slowdperiod: The time period of the slowd moving average. Positive\n                integers are accepted (default=None)\n            slowkmatype:  Moving average type for the slowk moving average.\n                By default, fastmatype=0. Integers 0 - 8 are accepted\n                (check  down the mappings) or the string containing the math type can\n                also be used.\n            slowdmatype:  Moving average type for the slowd moving average.\n                By default, slowmatype=0. Integers 0 - 8 are accepted\n                (check down the mappings) or the string containing the math type can\n                also be used.\n\n                * 0 = Simple Moving Average (SMA),\n                * 1 = Exponential Moving Average (EMA),\n                * 2 = Weighted Moving Average (WMA),\n                * 3 = Double Exponential Moving Average (DEMA),\n                * 4 = Triple Exponential Moving Average (TEMA),\n                * 5 = Triangular Moving Average (TRIMA),\n                * 6 = T3 Moving Average,\n                * 7 = Kaufman Adaptive Moving Average (KAMA),\n                * 8 = MESA Adaptive Moving Average (MAMA)"
  },
  {
    "code": "def thumbnail(parser, token):\n    thumb = None\n    if SORL:\n        try:\n            thumb = sorl_thumb(parser, token)\n        except Exception:\n            thumb = False\n    if EASY and not thumb:\n        thumb = easy_thumb(parser, token)\n    return thumb",
    "docstring": "This template tag supports both syntax for declare thumbanil in template"
  },
  {
    "code": "def context_menu_requested(self, event):\n        if self.fig:\n            pos = QPoint(event.x(), event.y())\n            context_menu = QMenu(self)\n            context_menu.addAction(ima.icon('editcopy'), \"Copy Image\",\n                                   self.copy_figure,\n                                   QKeySequence(\n                                       get_shortcut('plots', 'copy')))\n            context_menu.popup(self.mapToGlobal(pos))",
    "docstring": "Popup context menu."
  },
  {
    "code": "async def spawn_slaves(self, slave_addrs, slave_env_cls, slave_mgr_cls,\n                           slave_kwargs=None):\n        pool, r = spawn_containers(slave_addrs, env_cls=slave_env_cls,\n                                   env_params=slave_kwargs,\n                                   mgr_cls=slave_mgr_cls)\n        self._pool = pool\n        self._r = r\n        self._manager_addrs = [\"{}{}\".format(_get_base_url(a), 0) for\n                               a in slave_addrs]",
    "docstring": "Spawn slave environments.\n\n        :param slave_addrs:\n            List of (HOST, PORT) addresses for the slave-environments.\n\n        :param slave_env_cls: Class for the slave environments.\n\n        :param slave_kwargs:\n            If not None, must be a list of the same size as *addrs*. Each item\n            in the list containing parameter values for one slave environment.\n\n        :param slave_mgr_cls:\n            Class of the slave environment managers."
  },
  {
    "code": "def get_fit_failed_candidate_model(model_type, formula):\n    warnings = [\n        EEMeterWarning(\n            qualified_name=\"eemeter.caltrack_daily.{}.model_results\".format(model_type),\n            description=(\n                \"Error encountered in statsmodels.formula.api.ols method. (Empty data?)\"\n            ),\n            data={\"traceback\": traceback.format_exc()},\n        )\n    ]\n    return CalTRACKUsagePerDayCandidateModel(\n        model_type=model_type, formula=formula, status=\"ERROR\", warnings=warnings\n    )",
    "docstring": "Return a Candidate model that indicates the fitting routine failed.\n\n    Parameters\n    ----------\n    model_type : :any:`str`\n        Model type (e.g., ``'cdd_hdd'``).\n    formula : :any:`float`\n        The candidate model formula.\n\n    Returns\n    -------\n    candidate_model : :any:`eemeter.CalTRACKUsagePerDayCandidateModel`\n        Candidate model instance with status ``'ERROR'``, and warning with\n        traceback."
  },
  {
    "code": "def by_prefix(self,\n                  prefix,\n                  zipcode_type=ZipcodeType.Standard,\n                  sort_by=SimpleZipcode.zipcode.name,\n                  ascending=True,\n                  returns=DEFAULT_LIMIT):\n        return self.query(\n            prefix=prefix,\n            sort_by=sort_by, zipcode_type=zipcode_type,\n            ascending=ascending, returns=returns,\n        )",
    "docstring": "Search zipcode information by first N digits.\n\n        Returns multiple results."
  },
  {
    "code": "def search_image(name=None, path=['.']):\n    name = strutils.decode(name)\n    for image_dir in path:\n        if not os.path.isdir(image_dir):\n            continue\n        image_dir = strutils.decode(image_dir)\n        image_path = os.path.join(image_dir, name)\n        if os.path.isfile(image_path):\n            return strutils.encode(image_path)\n        for image_path in list_all_image(image_dir):\n            if not image_name_match(name, image_path):\n                continue\n            return strutils.encode(image_path)\n    return None",
    "docstring": "look for the image real path, if name is None, then return all images under path.\n\n    @return system encoded path string\n    FIXME(ssx): this code is just looking wired."
  },
  {
    "code": "def command(self, name=None):\n        def decorator(f):\n            self.add_command(f, name)\n            return f\n        return decorator",
    "docstring": "A decorator to add subcommands."
  },
  {
    "code": "def setup_step_out(self, frame):\n        self.frame_calling = None\n        self.frame_stop = None\n        self.frame_return = frame.f_back\n        self.frame_suspend = False\n        self.pending_stop = True \n        return",
    "docstring": "Setup debugger for a \"stepOut\""
  },
  {
    "code": "def get_command(arguments):\n    cmds = list(filter(lambda k: not (k.startswith('-') or\n                                 k.startswith('<')) and arguments[k],\n                  arguments.keys()))\n    if len(cmds) != 1:\n        raise Exception('invalid command line!')\n    return cmds[0]",
    "docstring": "Utility function to extract command from docopt arguments.\n\n    :param arguments:\n    :return: command"
  },
  {
    "code": "def filenames(self):\n        return [os.path.basename(source) for source in self.sources if source]",
    "docstring": "Assuming sources are paths to VCF or MAF files, trim their directory\n        path and return just the file names."
  },
  {
    "code": "def get_config_var_data(self, index, offset):\n        if index == 0 or index > len(self.config_database.entries):\n            return [Error.INVALID_ARRAY_KEY, b'']\n        entry = self.config_database.entries[index - 1]\n        if not entry.valid:\n            return [ConfigDatabaseError.OBSOLETE_ENTRY, b'']\n        if offset >= len(entry.data):\n            return [Error.INVALID_ARRAY_KEY, b'']\n        data_chunk = entry.data[offset:offset + 16]\n        return [Error.NO_ERROR, data_chunk]",
    "docstring": "Get a chunk of data for a config variable."
  },
  {
    "code": "def expect_file_hash_to_equal(self, value, hash_alg='md5', result_format=None,\n                                  include_config=False, catch_exceptions=None,\n                                  meta=None):\n        success = False\n        try:\n            hash = hashlib.new(hash_alg)\n            BLOCKSIZE = 65536\n            try:\n                with open(self._path, 'rb') as file:\n                    file_buffer = file.read(BLOCKSIZE)\n                    while file_buffer:\n                        hash.update(file_buffer)\n                        file_buffer = file.read(BLOCKSIZE)\n                    success = hash.hexdigest() == value\n            except IOError:\n                raise\n        except ValueError:\n            raise\n        return {\"success\":success}",
    "docstring": "Expect computed file hash to equal some given value.\n\n        Args:\n            value: A string to compare with the computed hash value\n\n        Keyword Args:\n            hash_alg (string):  Indicates the hash algorithm to use\n\n            result_format (str or None): \\\n                Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`,\n                or `SUMMARY`. For more detail, see :ref:`result_format <result_format>`.\n            include_config (boolean): \\\n                If True, then include the expectation config as part of the\n                result object. For more detail, see :ref:`include_config`.\n            catch_exceptions (boolean or None): \\\n                If True, then catch exceptions and include them as part of the result object. \\\n                For more detail, see :ref:`catch_exceptions`.\n            meta (dict or None): \\\n                A JSON-serializable dictionary (nesting allowed) that will be\n                included in the output without modification. For more detail,\n                see :ref:`meta`.\n\n        Returns:\n            A JSON-serializable expectation result object.\n\n        Exact fields vary depending on the values passed to :ref:`result_format\n        <result_format>` and :ref:`include_config`, :ref:`catch_exceptions`,\n        and :ref:`meta`."
  },
  {
    "code": "def relocate_instance(part, target_parent, name=None, include_children=True):\n    if not name:\n        name = \"CLONE - {}\".format(part.name)\n    part_model = part.model()\n    target_parent_model = target_parent.model()\n    relocate_model(part=part_model, target_parent=target_parent_model, name=part_model.name,\n                   include_children=include_children)\n    if include_children:\n        part.populate_descendants()\n    moved_instance = move_part_instance(part_instance=part, target_parent=target_parent, part_model=part_model,\n                                        name=name, include_children=include_children)\n    return moved_instance",
    "docstring": "Move the `Part` instance to target parent.\n\n    .. versionadded:: 2.3\n\n    :param part: `Part` object to be moved\n    :type part: :class:`Part`\n    :param target_parent: `Part` object under which the desired `Part` is moved\n    :type target_parent: :class:`Part`\n    :param name: how the moved top-level `Part` should be called\n    :type name: basestring\n    :param include_children: True to move also the descendants of `Part`. If False, the children will be lost.\n    :type include_children: bool\n    :return: moved :class: `Part` instance"
  },
  {
    "code": "def app_start_service(self, *args) -> None:\n        _, error = self._execute('-s', self.device_sn,\n                                 'shell', 'am', 'startservice', *args)\n        if error and error.startswith('Error'):\n            raise ApplicationsException(error.split(':', 1)[-1].strip())",
    "docstring": "Start a service."
  },
  {
    "code": "def create_ini(self, board, project_dir='', sayyes=False):\n        project_dir = util.check_dir(project_dir)\n        ini_path = util.safe_join(project_dir, PROJECT_FILENAME)\n        boards = Resources().boards\n        if board not in boards.keys():\n            click.secho(\n                'Error: no such board \\'{}\\''.format(board),\n                fg='red')\n            sys.exit(1)\n        if isfile(ini_path):\n            if sayyes:\n                self._create_ini_file(board, ini_path, PROJECT_FILENAME)\n            else:\n                click.secho(\n                    'Warning: {} file already exists'.format(PROJECT_FILENAME),\n                    fg='yellow')\n                if click.confirm('Do you want to replace it?'):\n                    self._create_ini_file(board, ini_path, PROJECT_FILENAME)\n                else:\n                    click.secho('Abort!', fg='red')\n        else:\n            self._create_ini_file(board, ini_path, PROJECT_FILENAME)",
    "docstring": "Creates a new apio project file"
  },
  {
    "code": "def emit(signal, *args, **kwargs):\n    if signal not in __receivers:\n        return\n    receivers = __live_receivers(signal)\n    for func in receivers:\n        func(*args, **kwargs)",
    "docstring": "Emit a signal by serially calling each registered signal receiver for\n    the `signal`.\n\n    Note:\n        The receiver must accept the *args and/or **kwargs that have been\n        passed to it. There expected parameters are not dictated by\n        mixbox.\n        \n    Args:\n        signal: A signal identifier or name.\n        *args: A variable-length argument list to pass to the receiver.\n        **kwargs: Keyword-arguments to pass to the receiver."
  },
  {
    "code": "def check_failhard(self, low, running):\n        tag = _gen_tag(low)\n        if self.opts.get('test', False):\n            return False\n        if low.get('failhard', self.opts['failhard']) and tag in running:\n            if running[tag]['result'] is None:\n                return False\n            return not running[tag]['result']\n        return False",
    "docstring": "Check if the low data chunk should send a failhard signal"
  },
  {
    "code": "def _convert(lines):\n    def parse(line):\n        line = line.replace(\"from PySide2 import\", \"from Qt import QtCompat,\")\n        line = line.replace(\"QtWidgets.QApplication.translate\",\n                            \"QtCompat.translate\")\n        if \"QtCore.SIGNAL\" in line:\n            raise NotImplementedError(\"QtCore.SIGNAL is missing from PyQt5 \"\n                                      \"and so Qt.py does not support it: you \"\n                                      \"should avoid defining signals inside \"\n                                      \"your ui files.\")\n        return line\n    parsed = list()\n    for line in lines:\n        line = parse(line)\n        parsed.append(line)\n    return parsed",
    "docstring": "Convert compiled .ui file from PySide2 to Qt.py\n\n    Arguments:\n        lines (list): Each line of of .ui file\n\n    Usage:\n        >> with open(\"myui.py\") as f:\n        ..   lines = _convert(f.readlines())"
  },
  {
    "code": "def map_resnum_a_to_resnum_b(resnums, a_aln, b_aln):\n    resnums = ssbio.utils.force_list(resnums)\n    aln_df = get_alignment_df(a_aln, b_aln)\n    maps = aln_df[aln_df.id_a_pos.isin(resnums)]\n    able_to_map_to_b = maps[pd.notnull(maps.id_b_pos)]\n    successful_map_from_a = able_to_map_to_b.id_a_pos.values.tolist()\n    mapping = dict([(int(a), int(b)) for a,b in zip(able_to_map_to_b.id_a_pos, able_to_map_to_b.id_b_pos)])\n    cant_map = list(set(resnums).difference(successful_map_from_a))\n    if len(cant_map) > 0:\n        log.warning('Unable to map residue numbers {} in first sequence to second'.format(cant_map))\n    return mapping",
    "docstring": "Map a residue number in a sequence to the corresponding residue number in an aligned sequence.\n\n    Examples:\n    >>> map_resnum_a_to_resnum_b([1,2,3], '--ABCDEF', 'XXABCDEF')\n    {1: 3, 2: 4, 3: 5}\n    >>> map_resnum_a_to_resnum_b(5, '--ABCDEF', 'XXABCDEF')\n    {5: 7}\n    >>> map_resnum_a_to_resnum_b(5, 'ABCDEF', 'ABCD--')\n    {}\n    >>> map_resnum_a_to_resnum_b(5, 'ABCDEF--', 'ABCD--GH')\n    {}\n    >>> map_resnum_a_to_resnum_b([9,10], '--MKCDLHRLE-E', 'VSNEYSFEGYKLD')\n    {9: 11, 10: 13}\n\n    Args:\n        resnums (int, list): Residue number or numbers in the first aligned sequence\n        a_aln (str, Seq, SeqRecord): Aligned sequence string\n        b_aln (str, Seq, SeqRecord): Aligned sequence string\n\n    Returns:\n        int: Residue number in the second aligned sequence"
  },
  {
    "code": "def translate_message_tokens(message_tokens):\n    trans_tokens = []\n    if message_tokens[0] in cv_dict[channels_key]:\n        trans_tokens.append(cv_dict[channels_key][message_tokens[0]])\n    else:\n        trans_tokens.append(int(message_tokens[0]))\n    for token in message_tokens[1:]:\n        if token in cv_dict[values_key]:\n            trans_tokens.extend(cv_dict[values_key][token])\n        else:\n            trans_tokens.append(int(token))\n    return trans_tokens",
    "docstring": "Translates alias references to their defined values.\n    The first token is a channel alias.\n    The remaining tokens are value aliases."
  },
  {
    "code": "def get_mouse_pos(self, window_pos=None):\n    window_pos = window_pos or pygame.mouse.get_pos()\n    window_pt = point.Point(*window_pos) + 0.5\n    for surf in reversed(self._surfaces):\n      if (surf.surf_type != SurfType.CHROME and\n          surf.surf_rect.contains_point(window_pt)):\n        surf_rel_pt = window_pt - surf.surf_rect.tl\n        world_pt = surf.world_to_surf.back_pt(surf_rel_pt)\n        return MousePos(world_pt, surf)",
    "docstring": "Return a MousePos filled with the world position and surf it hit."
  },
  {
    "code": "def cdhit_from_seqs(seqs, moltype, params=None):\n    seqs = SequenceCollection(seqs, MolType=moltype)\n    if params is None:\n        params = {}\n    if '-o' not in params:\n        _, params['-o'] = mkstemp()\n    working_dir = mkdtemp()\n    if moltype is PROTEIN:\n        app = CD_HIT(WorkingDir=working_dir, params=params)\n    elif moltype is RNA:\n        app = CD_HIT_EST(WorkingDir=working_dir, params=params)\n    elif moltype is DNA:\n        app = CD_HIT_EST(WorkingDir=working_dir, params=params)\n    else:\n        raise ValueError, \"Moltype must be either PROTEIN, RNA, or DNA\"\n    res = app(seqs.toFasta())\n    new_seqs = dict(parse_fasta(res['FASTA']))\n    res.cleanUp()\n    shutil.rmtree(working_dir)\n    remove(params['-o'] + '.bak.clstr')\n    return SequenceCollection(new_seqs, MolType=moltype)",
    "docstring": "Returns the CD-HIT results given seqs\n\n    seqs    : dict like collection of sequences\n    moltype : cogent.core.moltype object\n    params  : cd-hit parameters\n\n    NOTE: This method will call CD_HIT if moltype is PROTIEN,\n        CD_HIT_EST if moltype is RNA/DNA, and raise if any other\n        moltype is passed."
  },
  {
    "code": "def natural_name(self):\n        try:\n            assert self._natural_name is not None\n        except (AssertionError, AttributeError):\n            self._natural_name = self.attrs[\"name\"]\n        finally:\n            return self._natural_name",
    "docstring": "Natural name."
  },
  {
    "code": "def uriunsplit(parts):\n    scheme, authority, path, query, fragment = parts\n    if isinstance(path, bytes):\n        result = SplitResultBytes\n    else:\n        result = SplitResultUnicode\n    return result(scheme, authority, path, query, fragment).geturi()",
    "docstring": "Combine the elements of a five-item iterable into a URI reference's\n    string representation."
  },
  {
    "code": "def ctor_args(self):\n        return dict(\n            config=self._config,\n            search=self._search,\n            echo=self._echo,\n            read_only=self.read_only\n        )",
    "docstring": "Return arguments for constructing a copy"
  },
  {
    "code": "def create_log2fc_bigwigs(matrix, outdir, args):\n    call(\"mkdir -p {}\".format(outdir), shell=True)\n    genome_size_dict = args.chromosome_sizes\n    outpaths = []\n    for bed_file in matrix[args.treatment]:\n        outpath = join(outdir, splitext(basename(bed_file))[0] + \"_log2fc.bw\")\n        outpaths.append(outpath)\n    data = create_log2fc_data(matrix, args)\n    Parallel(n_jobs=args.number_cores)(delayed(_create_bigwig)(bed_column, outpath, genome_size_dict) for outpath, bed_column in zip(outpaths, data))",
    "docstring": "Create bigwigs from matrix."
  },
  {
    "code": "def delete_all(self, criteria: Q = None):\n        if criteria:\n            items = self._filter(criteria, self.conn['data'][self.schema_name])\n            with self.conn['lock']:\n                for identifier in items:\n                    self.conn['data'][self.schema_name].pop(identifier, None)\n            return len(items)\n        else:\n            with self.conn['lock']:\n                if self.schema_name in self.conn['data']:\n                    del self.conn['data'][self.schema_name]",
    "docstring": "Delete the dictionary object by its criteria"
  },
  {
    "code": "def value(self, value):\n        if value is None or (\n                self.ptype is None or isinstance(value, self.ptype)\n        ):\n            self._value = value\n        else:\n            error = TypeError(\n                'Wrong value type of {0} ({1}). {2} expected.'.format(\n                    self.name, value, self.ptype\n                )\n            )\n            self._error = error\n            raise error",
    "docstring": "Change of parameter value.\n\n        If an error occured, it is stored in this error attribute.\n\n        :param value: new value to use. If input value is not an instance of\n            self.ptype, self error\n        :raises: TypeError if input value is not an instance of self ptype."
  },
  {
    "code": "def find_stateless_by_name(name):\n    try:\n        dsa_app = StatelessApp.objects.get(app_name=name)\n        return dsa_app.as_dash_app()\n    except:\n        pass\n    dash_app = get_stateless_by_name(name)\n    dsa_app = StatelessApp(app_name=name)\n    dsa_app.save()\n    return dash_app",
    "docstring": "Find stateless app given its name\n\n    First search the Django ORM, and if not found then look the app up in a local registry.\n    If the app does not have an ORM entry then a StatelessApp model instance is created."
  },
  {
    "code": "def ToInternal(self):\n        self.validate_units()\n        savewunits = self.waveunits\n        angwave = self.waveunits.Convert(self._wavetable, 'angstrom')\n        self._wavetable = angwave.copy()\n        self.waveunits = savewunits",
    "docstring": "Convert wavelengths to the internal representation of angstroms.\n        For internal use only."
  },
  {
    "code": "def chain_frames(self):\n        prev_tb = None\n        for tb in self.frames:\n            if prev_tb is not None:\n                prev_tb.tb_next = tb\n            prev_tb = tb\n        prev_tb.tb_next = None",
    "docstring": "Chains the frames.  Requires ctypes or the speedups extension."
  },
  {
    "code": "def indent (text, indent_string=\"  \"):\n    lines = str(text).splitlines()\n    return os.linesep.join(\"%s%s\" % (indent_string, x) for x in lines)",
    "docstring": "Indent each line of text with the given indent string."
  },
  {
    "code": "def decrypt(text):\n    'Decrypt a string using an encryption key based on the django SECRET_KEY'\n    crypt = EncryptionAlgorithm.new(_get_encryption_key())\n    return crypt.decrypt(text).rstrip(ENCRYPT_PAD_CHARACTER)",
    "docstring": "Decrypt a string using an encryption key based on the django SECRET_KEY"
  },
  {
    "code": "def names(self, with_namespace=False):\n        N = self.count()\n        names = self.name.split(settings.splittingnames)[:N]\n        n = 0\n        while len(names) < N:\n            n += 1\n            names.append('unnamed%s' % n)\n        if with_namespace and self.namespace:\n            n = self.namespace\n            s = settings.field_separator\n            return [n + s + f for f in names]\n        else:\n            return names",
    "docstring": "List of names for series in dataset.\n\n        It will always return a list or names with length given by\n        :class:`~.DynData.count`."
  },
  {
    "code": "def run(self, params):\n        self.params = list(reversed(params))\n        if not self.params:\n            self.help()\n            return\n        while self.params:\n            p = self.params.pop()\n            if p in self.command:\n                self.command[p](self)\n            elif os.path.exists(p):\n                self.read_moc(p)\n            else:\n                raise CommandError('file or command {0} not found'.format(p))",
    "docstring": "Main run method for PyMOC tool.\n\n        Takes a list of command line arguments to process.\n\n        Each operation is performed on a current \"running\" MOC\n        object."
  },
  {
    "code": "def _asvector(self, arr):\n        result = moveaxis(arr, [-2, -1], [0, 1])\n        return self.domain.element(result)",
    "docstring": "Convert ``arr`` to a `domain` element.\n\n        This is the inverse of `_asarray`."
  },
  {
    "code": "def make_simulated_env_kwargs(real_env, hparams, **extra_kwargs):\n  objs_and_attrs = [\n      (real_env, [\n          \"reward_range\", \"observation_space\", \"action_space\", \"frame_height\",\n          \"frame_width\"\n      ]),\n      (hparams, [\"frame_stack_size\", \"intrinsic_reward_scale\"])\n  ]\n  kwargs = {\n      attr: getattr(obj, attr)\n      for (obj, attrs) in objs_and_attrs for attr in attrs\n  }\n  kwargs[\"model_name\"] = hparams.generative_model\n  kwargs[\"model_hparams\"] = trainer_lib.create_hparams(\n      hparams.generative_model_params\n  )\n  if hparams.wm_policy_param_sharing:\n    kwargs[\"model_hparams\"].optimizer_zero_grads = True\n  kwargs.update(extra_kwargs)\n  return kwargs",
    "docstring": "Extracts simulated env kwargs from real_env and loop hparams."
  },
  {
    "code": "def find_observatories(self, match=None):\n        url = \"%s/gwf.json\" % _url_prefix\n        response = self._requestresponse(\"GET\", url)\n        sitelist = sorted(set(decode(response.read())))\n        if match:\n            regmatch = re.compile(match)\n            sitelist = [site for site in sitelist if regmatch.search(site)]\n        return sitelist",
    "docstring": "Query the LDR host for observatories. Use match to\n        restrict returned observatories to those matching the\n        regular expression.\n\n        Example:\n\n        >>> connection.find_observatories()\n        ['AGHLT', 'G', 'GHLTV', 'GHLV', 'GHT', 'H', 'HL', 'HLT',\n         'L', 'T', 'V', 'Z']\n        >>> connection.find_observatories(\"H\")\n        ['H', 'HL', 'HLT']\n\n        @type  match: L{str}\n        @param match:\n            name to match return observatories against\n\n        @returns: L{list} of observatory prefixes"
  },
  {
    "code": "def waypoint_request_send(self, seq):\n        if self.mavlink10():\n            self.mav.mission_request_send(self.target_system, self.target_component, seq)\n        else:\n            self.mav.waypoint_request_send(self.target_system, self.target_component, seq)",
    "docstring": "wrapper for waypoint_request_send"
  },
  {
    "code": "def filter_nonspellcheckable_tokens(line, block_out_regexes=None):\n    all_block_out_regexes = [\n        r\"[^\\s]*:[^\\s]*[/\\\\][^\\s]*\",\n        r\"[^\\s]*[/\\\\][^\\s]*\",\n        r\"\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]+\\b\"\n    ] + (block_out_regexes or list())\n    for block_regex in all_block_out_regexes:\n        for marker in re.finditer(block_regex, line):\n            spaces = \" \" * (marker.end() - marker.start())\n            line = line[:marker.start()] + spaces + line[marker.end():]\n    return line",
    "docstring": "Return line with paths, urls and emails filtered out.\n\n    Block out other strings of text matching :block_out_regexes: if passed in."
  },
  {
    "code": "def qcut(expr, bins, labels=False, sort=None, ascending=True):\n    if labels is None or labels:\n        raise NotImplementedError('Showing bins or customizing labels not supported')\n    return _rank_op(expr, QCut, types.int64, sort=sort, ascending=ascending,\n                    _bins=bins)",
    "docstring": "Get quantile-based bin indices of every element of a grouped and sorted expression.\n    The indices of bins start from 0. If cuts are not of equal sizes, extra items will\n    be appended into the first group.\n\n    :param expr: expression for calculation\n    :param bins: number of bins\n    :param sort: name of the sort column\n    :param ascending: whether to sort in ascending order\n    :return: calculated column"
  },
  {
    "code": "def flip(f):\n    ensure_callable(f)\n    result = lambda *args, **kwargs: f(*reversed(args), **kwargs)\n    functools.update_wrapper(result, f, ('__name__', '__module__'))\n    return result",
    "docstring": "Flip the order of positonal arguments of given function."
  },
  {
    "code": "def add_traits(self, **traits):\n        super(Widget, self).add_traits(**traits)\n        for name, trait in traits.items():\n            if trait.get_metadata('sync'):\n                self.keys.append(name)\n                self.send_state(name)",
    "docstring": "Dynamically add trait attributes to the Widget."
  },
  {
    "code": "def show_label(self, text, size = None, color = None, font_desc = None):\n        font_desc = pango.FontDescription(font_desc or _font_desc)\n        if color: self.set_color(color)\n        if size: font_desc.set_absolute_size(size * pango.SCALE)\n        self.show_layout(text, font_desc)",
    "docstring": "display text. unless font_desc is provided, will use system's default font"
  },
  {
    "code": "def update(self, friendly_name=values.unset, max_size=values.unset):\n        return self._proxy.update(friendly_name=friendly_name, max_size=max_size, )",
    "docstring": "Update the QueueInstance\n\n        :param unicode friendly_name: A string to describe this resource\n        :param unicode max_size: The max number of calls allowed in the queue\n\n        :returns: Updated QueueInstance\n        :rtype: twilio.rest.api.v2010.account.queue.QueueInstance"
  },
  {
    "code": "def delete_storage_account(access_token, subscription_id, rgname, account_name):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/resourcegroups/', rgname,\n                        '/providers/Microsoft.Storage/storageAccounts/', account_name,\n                        '?api-version=', STORAGE_API])\n    return do_delete(endpoint, access_token)",
    "docstring": "Delete a storage account in the specified resource group.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n        rgname (str): Azure resource group name.\n        account_name (str): Name of the new storage account.\n\n    Returns:\n        HTTP response."
  },
  {
    "code": "def _draw_chars(self, data, to_draw):\n        i = 0\n        while not self._cursor.atBlockEnd() and i < len(to_draw) and len(to_draw) > 1:\n            self._cursor.deleteChar()\n            i += 1\n        self._cursor.insertText(to_draw, data.fmt)",
    "docstring": "Draw the specified charachters using the specified format."
  },
  {
    "code": "def migrate(vm_, target,\n            live=1, port=0, node=-1, ssl=None, change_home_server=0):\n    with _get_xapi_session() as xapi:\n        vm_uuid = _get_label_uuid(xapi, 'VM', vm_)\n        if vm_uuid is False:\n            return False\n        other_config = {\n            'port': port,\n            'node': node,\n            'ssl': ssl,\n            'change_home_server': change_home_server\n        }\n        try:\n            xapi.VM.migrate(vm_uuid, target, bool(live), other_config)\n            return True\n        except Exception:\n            return False",
    "docstring": "Migrates the virtual machine to another hypervisor\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' virt.migrate <vm name> <target hypervisor> [live] [port] [node] [ssl] [change_home_server]\n\n    Optional values:\n\n    live\n        Use live migration\n    port\n        Use a specified port\n    node\n        Use specified NUMA node on target\n    ssl\n        use ssl connection for migration\n    change_home_server\n        change home server for managed domains"
  },
  {
    "code": "def decr(self, key, delta=1):\n        return uwsgi.cache_dec(key, delta, self.timeout, self.name)",
    "docstring": "Decrements the specified key value by the specified value.\n\n        :param str|unicode key:\n\n        :param int delta:\n\n        :rtype: bool"
  },
  {
    "code": "def get(self, sid):\n        return SyncListContext(self._version, service_sid=self._solution['service_sid'], sid=sid, )",
    "docstring": "Constructs a SyncListContext\n\n        :param sid: The sid\n\n        :returns: twilio.rest.sync.v1.service.sync_list.SyncListContext\n        :rtype: twilio.rest.sync.v1.service.sync_list.SyncListContext"
  },
  {
    "code": "def qeuler(yaw, pitch, roll):\n    yaw = np.radians(yaw)\n    pitch = np.radians(pitch)\n    roll = np.radians(roll)\n    cy = np.cos(yaw * 0.5)\n    sy = np.sin(yaw * 0.5)\n    cr = np.cos(roll * 0.5)\n    sr = np.sin(roll * 0.5)\n    cp = np.cos(pitch * 0.5)\n    sp = np.sin(pitch * 0.5)\n    q = np.array((\n        cy * cr * cp + sy * sr * sp, cy * sr * cp - sy * cr * sp,\n        cy * cr * sp + sy * sr * cp, sy * cr * cp - cy * sr * sp\n    ))\n    return q",
    "docstring": "Convert Euler angle to quaternion.\n\n    Parameters\n    ----------\n    yaw: number\n    pitch: number\n    roll: number\n\n    Returns\n    -------\n    np.array"
  },
  {
    "code": "def extend(self, *iterables):\n        for value in iterables:\n            list.extend(self, value)\n        return self",
    "docstring": "Add all values of all iterables at the end of the list\n\n        Args:\n            iterables: iterable which content to add at the end\n\n        Example:\n\n            >>> from ww import l\n            >>> lst = l([])\n            >>> lst.extend([1, 2])\n            [1, 2]\n            >>> lst\n            [1, 2]\n            >>> lst.extend([3, 4]).extend([5, 6])\n            [1, 2, 3, 4, 5, 6]\n            >>> lst\n            [1, 2, 3, 4, 5, 6]"
  },
  {
    "code": "def makedirs(path):\n    path = Path(path)\n    if not path.exists():\n        path.mkdir(parents=True)",
    "docstring": "Creates the directory tree if non existing."
  },
  {
    "code": "def update_api_endpoint():\n    environment = subprocess.check_output(['pipenv',\n                                           'run',\n                                           'runway',\n                                           'whichenv']).decode().strip()\n    environment_file = os.path.join(\n        os.path.dirname(os.path.realpath(__file__)),\n        'src',\n        'environments',\n        'environment.prod.ts' if environment == 'prod' else 'environment.ts'\n    )\n    cloudformation = boto3.resource('cloudformation')\n    stack = cloudformation.Stack(STACK_PREFIX + environment)\n    endpoint = [i['OutputValue'] for i in stack.outputs\n                if i['OutputKey'] == 'ServiceEndpoint'][0]\n    with open(environment_file, 'r') as stream:\n        content = stream.read()\n    content = re.sub(r'api_url: \\'.*\\'$',\n                     \"api_url: '%s/api'\" % endpoint,\n                     content,\n                     flags=re.M)\n    with open(environment_file, 'w') as stream:\n        stream.write(content)",
    "docstring": "Update app environment file with backend endpoint."
  },
  {
    "code": "def validate_complex(prop, value, xpath_map=None):\n    if value is not None:\n        validate_type(prop, value, dict)\n        if prop in _complex_definitions:\n            complex_keys = _complex_definitions[prop]\n        else:\n            complex_keys = {} if xpath_map is None else xpath_map\n        for complex_prop, complex_val in iteritems(value):\n            complex_key = '.'.join((prop, complex_prop))\n            if complex_prop not in complex_keys:\n                _validation_error(prop, None, value, ('keys: {0}'.format(','.join(complex_keys))))\n            validate_type(complex_key, complex_val, (string_types, list))",
    "docstring": "Default validation for single complex data structure"
  },
  {
    "code": "def get_state(self):\n        self.step_methods = set()\n        for s in self.stochastics:\n            self.step_methods |= set(self.step_method_dict[s])\n        state = Sampler.get_state(self)\n        state['step_methods'] = {}\n        for sm in self.step_methods:\n            state['step_methods'][sm._id] = sm.current_state().copy()\n        return state",
    "docstring": "Return the sampler and step methods current state in order to\n        restart sampling at a later time."
  },
  {
    "code": "def facet_query_matching_method(self, facet_query_matching_method):\n        allowed_values = [\"CONTAINS\", \"STARTSWITH\", \"EXACT\", \"TAGPATH\"]\n        if facet_query_matching_method not in allowed_values:\n            raise ValueError(\n                \"Invalid value for `facet_query_matching_method` ({0}), must be one of {1}\"\n                .format(facet_query_matching_method, allowed_values)\n            )\n        self._facet_query_matching_method = facet_query_matching_method",
    "docstring": "Sets the facet_query_matching_method of this FacetSearchRequestContainer.\n\n        The matching method used to filter when 'facetQuery' is used. Defaults to CONTAINS.  # noqa: E501\n\n        :param facet_query_matching_method: The facet_query_matching_method of this FacetSearchRequestContainer.  # noqa: E501\n        :type: str"
  },
  {
    "code": "def from_mongo(cls, doc):\n\t\tif doc is None:\n\t\t\treturn None\n\t\tif isinstance(doc, Document):\n\t\t\treturn doc\n\t\tif cls.__type_store__ and cls.__type_store__ in doc:\n\t\t\tcls = load(doc[cls.__type_store__], 'marrow.mongo.document')\n\t\tinstance = cls(_prepare_defaults=False)\n\t\tinstance.__data__ = doc\n\t\tinstance._prepare_defaults()\n\t\treturn instance",
    "docstring": "Convert data coming in from the MongoDB wire driver into a Document instance."
  },
  {
    "code": "def parse_args( self, args = None, values = None ):\n        q = multiproc.Queue()\n        p = multiproc.Process(target=self._parse_args, args=(q, args, values))\n        p.start()\n        ret = q.get()\n        p.join()\n        return ret",
    "docstring": "multiprocessing wrapper around _parse_args"
  },
  {
    "code": "def validate_units(self):\n        if (not isinstance(self.waveunits, units.WaveUnits)):\n            raise TypeError(\"%s is not a valid WaveUnit\" % self.waveunits)\n        if (not isinstance(self.fluxunits, units.FluxUnits)):\n            raise TypeError(\"%s is not a valid FluxUnit\" % self.fluxunits)",
    "docstring": "Ensure that wavelenth and flux units belong to the\n        correct classes.\n\n        Raises\n        ------\n        TypeError\n            Wavelength unit is not `~pysynphot.units.WaveUnits` or\n            flux unit is not `~pysynphot.units.FluxUnits`."
  },
  {
    "code": "def validate_week(year, week):\n        max_week = datetime.strptime(\"{}-{}-{}\".format(12, 31, year), \"%m-%d-%Y\").isocalendar()[1]\n        if max_week == 1:\n            max_week = 53\n        return 1 <= week <= max_week",
    "docstring": "Validate week."
  },
  {
    "code": "def copy_framebuffer(self, dst, src) -> None:\n        self.mglo.copy_framebuffer(dst.mglo, src.mglo)",
    "docstring": "Copy framebuffer content.\n\n            Use this method to:\n\n                - blit framebuffers.\n                - copy framebuffer content into a texture.\n                - downsample framebuffers. (it will allow to read the framebuffer's content)\n                - downsample a framebuffer directly to a texture.\n\n            Args:\n                dst (Framebuffer or Texture): Destination framebuffer or texture.\n                src (Framebuffer): Source framebuffer."
  },
  {
    "code": "def _results(self, scheduler_instance_id):\n        with self.app.lock:\n            res = self.app.get_results_from_passive(scheduler_instance_id)\n        return serialize(res, True)",
    "docstring": "Get the results of the executed actions for the scheduler which instance id is provided\n\n        Calling this method for daemons that are not configured as passive do not make sense.\n        Indeed, this service should only be exposed on poller and reactionner daemons.\n\n        :param scheduler_instance_id: instance id of the scheduler\n        :type scheduler_instance_id: string\n        :return: serialized list\n        :rtype: str"
  },
  {
    "code": "def get_compatible_pyplot(backend=None, debug=True):\n    import matplotlib\n    existing_backend = matplotlib.get_backend()\n    if backend is not None:\n        matplotlib.use(backend)\n        if debug:\n            sys.stderr.write(\"Currently using '%s' MPL backend, \"\n                             \"switching to '%s' backend%s\"\n                             % (existing_backend, backend, os.linesep))\n    elif debug:\n        sys.stderr.write(\"Using '%s' MPL backend%s\"\n                         % (existing_backend, os.linesep))\n    from matplotlib import pyplot as plt\n    return plt",
    "docstring": "Make the backend of MPL compatible.\n\n    In Travis Mac distributions, python is not installed as a framework. This\n    means that using the TkAgg backend is the best solution (so it doesn't\n    try to use the mac OS backend by default).\n\n    Parameters\n    ----------\n    backend : str, optional (default=\"TkAgg\")\n        The backend to default to.\n\n    debug : bool, optional (default=True)\n        Whether to log the existing backend to stderr."
  },
  {
    "code": "def from_barset(\n            cls, barset, name=None, delay=None,\n            use_wrapper=True, wrapper=None):\n        if wrapper:\n            data = tuple(barset.wrap_str(s, wrapper=wrapper) for s in barset)\n        elif use_wrapper:\n            data = tuple(barset.wrap_str(s) for s in barset)\n        else:\n            data = barset.data\n        return cls(\n            data,\n            name=name,\n            delay=delay\n        )",
    "docstring": "Copy a BarSet's frames to create a new FrameSet.\n\n            Arguments:\n                barset      : An existing BarSet object to copy frames from.\n                name        : A name for the new FrameSet.\n                delay       : Delay for the animation.\n                use_wrapper : Whether to use the old barset's wrapper in the\n                              frames.\n                wrapper     : A new wrapper pair to use for each frame.\n                              This overrides the `use_wrapper` option."
  },
  {
    "code": "def delete(self, request, **kwargs):\n\t\ttry:\n\t\t\tcustomer, _created = Customer.get_or_create(\n\t\t\t\tsubscriber=subscriber_request_callback(self.request)\n\t\t\t)\n\t\t\tcustomer.subscription.cancel(at_period_end=CANCELLATION_AT_PERIOD_END)\n\t\t\treturn Response(status=status.HTTP_204_NO_CONTENT)\n\t\texcept Exception:\n\t\t\treturn Response(\n\t\t\t\t\"Something went wrong cancelling the subscription.\",\n\t\t\t\tstatus=status.HTTP_400_BAD_REQUEST,\n\t\t\t)",
    "docstring": "Mark the customers current subscription as cancelled.\n\n\t\tReturns with status code 204."
  },
  {
    "code": "def download(self, sources, output_directory, filename):\n        valid_sources = self._filter_sources(sources)\n        if not valid_sources:\n            return {'error': 'no valid sources'}\n        manager = Manager()\n        successful_downloads = manager.list([])\n        def f(source):\n            if not successful_downloads:\n                result = self.download_from_host(\n                    source, output_directory, filename)\n                if 'error' in result:\n                    self._host_errors[source['host_name']] += 1\n                else:\n                    successful_downloads.append(result)\n        multiprocessing.dummy.Pool(len(valid_sources)).map(f, valid_sources)\n        return successful_downloads[0] if successful_downloads else {}",
    "docstring": "Download a file from one of the provided sources\n\n        The sources will be ordered by least amount of errors, so most\n        successful hosts will be tried first. In case of failure, the next\n        source will be attempted, until the first successful download is\n        completed or all sources have been depleted.\n\n        :param sources: A list of dicts with 'host_name' and 'url' keys.\n        :type sources: list\n        :param output_directory: Directory to save the downloaded file in.\n        :type output_directory: str\n        :param filename: Filename assigned to the downloaded file.\n        :type filename: str\n        :returns: A dict with 'host_name' and 'filename' keys if the download\n                  is successful, or an empty dict otherwise.\n        :rtype: dict"
  },
  {
    "code": "def remove_peer_from_bgp_speaker(self, speaker_id, body=None):\n        return self.put((self.bgp_speaker_path % speaker_id) +\n                        \"/remove_bgp_peer\", body=body)",
    "docstring": "Removes a peer from BGP speaker."
  },
  {
    "code": "def decode(self, data, erase_pos=None, only_erasures=False):\n        if isinstance(data, str):\n            data = bytearray(data, \"latin-1\")\n        dec = bytearray()\n        for i in xrange(0, len(data), self.nsize):\n            chunk = data[i:i+self.nsize]\n            e_pos = []\n            if erase_pos:\n                e_pos = [x for x in erase_pos if x <= self.nsize]\n                erase_pos = [x - (self.nsize+1) for x in erase_pos if x > self.nsize]\n            dec.extend(rs_correct_msg(chunk, self.nsym, fcr=self.fcr, generator=self.generator, erase_pos=e_pos, only_erasures=only_erasures)[0])\n        return dec",
    "docstring": "Repair a message, whatever its size is, by using chunking"
  },
  {
    "code": "def moveTab(self, fromIndex, toIndex):\n        try:\n            item = self.layout().itemAt(fromIndex)\n            self.layout().insertItem(toIndex, item.widget())\n        except StandardError:\n            pass",
    "docstring": "Moves the tab from the inputed index to the given index.\n\n        :param      fromIndex | <int>\n                    toIndex   | <int>"
  },
  {
    "code": "def cmdline(argv=sys.argv[1:]):\n    parser = ArgumentParser(\n        description='Create and merge collections of stop words')\n    parser.add_argument(\n        'language', help='The language used in the collection')\n    parser.add_argument('sources', metavar='FILE', nargs='+',\n                        help='Source files to parse')\n    options = parser.parse_args(argv)\n    factory = StopWordFactory()\n    language = options.language\n    stop_words = factory.get_stop_words(language, fail_safe=True)\n    for filename in options.sources:\n        stop_words += StopWord(language, factory.read_collection(filename))\n    filename = factory.get_collection_filename(stop_words.language)\n    factory.write_collection(filename, stop_words.collection)",
    "docstring": "Script for merging different collections of stop words."
  },
  {
    "code": "def index(args):\n    p = OptionParser(index.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(not p.print_help())\n    dbfile, = args\n    check_index(dbfile)",
    "docstring": "%prog index database.fasta\n\n    Wrapper for `bwa index`. Same interface."
  },
  {
    "code": "def to_json(self):\n    mapper_spec = self.mapper.to_json()\n    return {\n        \"name\": self.name,\n        \"mapreduce_id\": self.mapreduce_id,\n        \"mapper_spec\": mapper_spec,\n        \"params\": self.params,\n        \"hooks_class_name\": self.hooks_class_name,\n    }",
    "docstring": "Serializes all data in this mapreduce spec into json form.\n\n    Returns:\n      data in json format."
  },
  {
    "code": "def start(self):\n        self.agent.submit(self._start())\n        self.is_running = True",
    "docstring": "starts behaviour in the event loop"
  },
  {
    "code": "def _download_and_clean_file(filename, url):\n  temp_file, _ = urllib.request.urlretrieve(url)\n  with tf.gfile.Open(temp_file, 'r') as temp_eval_file:\n    with tf.gfile.Open(filename, 'w') as eval_file:\n      for line in temp_eval_file:\n        line = line.strip()\n        line = line.replace(', ', ',')\n        if not line or ',' not in line:\n          continue\n        if line[-1] == '.':\n          line = line[:-1]\n        line += '\\n'\n        eval_file.write(line)\n  tf.gfile.Remove(temp_file)",
    "docstring": "Downloads data from url, and makes changes to match the CSV format."
  },
  {
    "code": "def get_model(LAB_DIR):\n    coeffs = np.load(\"%s/coeffs.npz\" %LAB_DIR)['arr_0']\n    scatters = np.load(\"%s/scatters.npz\" %LAB_DIR)['arr_0']\n    chisqs = np.load(\"%s/chisqs.npz\" %LAB_DIR)['arr_0']\n    pivots = np.load(\"%s/pivots.npz\" %LAB_DIR)['arr_0']\n    return coeffs, scatters, chisqs, pivots",
    "docstring": "Cannon model params"
  },
  {
    "code": "def _initialize(self, **resource_attributes):\n        self._set_attributes(**resource_attributes)\n        for attribute, attribute_type in list(self._mapper.items()):\n            if attribute in resource_attributes and isinstance(resource_attributes[attribute], dict):\n                setattr(self, attribute, attribute_type(**resource_attributes[attribute]))",
    "docstring": "Initialize a resource.\n        Default behavior is just to set all the attributes. You may want to override this.\n\n        :param resource_attributes: The resource attributes"
  },
  {
    "code": "def get(object_ids):\n    if isinstance(object_ids, (tuple, np.ndarray)):\n        return ray.get(list(object_ids))\n    elif isinstance(object_ids, dict):\n        keys_to_get = [\n            k for k, v in object_ids.items() if isinstance(v, ray.ObjectID)\n        ]\n        ids_to_get = [\n            v for k, v in object_ids.items() if isinstance(v, ray.ObjectID)\n        ]\n        values = ray.get(ids_to_get)\n        result = object_ids.copy()\n        for key, value in zip(keys_to_get, values):\n            result[key] = value\n        return result\n    else:\n        return ray.get(object_ids)",
    "docstring": "Get a single or a collection of remote objects from the object store.\n\n    This method is identical to `ray.get` except it adds support for tuples,\n    ndarrays and dictionaries.\n\n    Args:\n        object_ids: Object ID of the object to get, a list, tuple, ndarray of\n            object IDs to get or a dict of {key: object ID}.\n\n    Returns:\n        A Python object, a list of Python objects or a dict of {key: object}."
  },
  {
    "code": "def add_mrp_service(self, info, address):\n        if self.protocol and self.protocol != PROTOCOL_MRP:\n            return\n        name = info.properties[b'Name'].decode('utf-8')\n        self._handle_service(address, name, conf.MrpService(info.port))",
    "docstring": "Add a new MediaRemoteProtocol device to discovered list."
  },
  {
    "code": "def get_attribute(self, name):\n        def get_attribute_element():\n            return self.element.get_attribute(name)\n        return self.execute_and_handle_webelement_exceptions(get_attribute_element, 'get attribute \"' + str(name) + '\"')",
    "docstring": "Retrieves specified attribute from WebElement\n\n        @type name:     str\n        @param name:    Attribute to retrieve\n\n        @rtype:         str\n        @return:        String representation of the attribute"
  },
  {
    "code": "def fields(self):\n        for attr, value in self._meta.fields.items():\n            if isinstance(value, Field):\n                yield attr, value",
    "docstring": "Provides an iterable for all model fields."
  },
  {
    "code": "def _save_sign(self, filepath):\n        if self.code_array.safe_mode:\n            msg = _(\"File saved but not signed because it is unapproved.\")\n            try:\n                post_command_event(self.main_window, self.StatusBarMsg,\n                                   text=msg)\n            except TypeError:\n                pass\n        else:\n            try:\n                self.sign_file(filepath)\n            except ValueError, err:\n                msg = \"Signing file failed. \" + unicode(err)\n                post_command_event(self.main_window, self.StatusBarMsg,\n                                   text=msg)",
    "docstring": "Sign so that the new file may be retrieved without safe mode"
  },
  {
    "code": "def update(self, key, item):\n        return lib.zhash_update(self._as_parameter_, key, item)",
    "docstring": "Update item into hash table with specified key and item.\nIf key is already present, destroys old item and inserts new one.\nUse free_fn method to ensure deallocator is properly called on item."
  },
  {
    "code": "def array(self, size, type, name, *parameters):\n        self._new_list(size, name)\n        BuiltIn().run_keyword(type, '', *parameters)\n        self._end_list()",
    "docstring": "Define a new array of given `size` and containing fields of type `type`.\n\n        `name` if the name of this array element. The `type` is the name of keyword that is executed as the contents of\n        the array and optional extra parameters are passed as arguments to this keyword.\n\n        Examples:\n        | Array | 8 | u16 | myArray |\n\n        | u32 | length |\n        | Array | length | someStruct | myArray | <argument for someStruct> |"
  },
  {
    "code": "def get_psd(self, omega):\n        w = np.asarray(omega)\n        (alpha_real, beta_real, alpha_complex_real, alpha_complex_imag,\n         beta_complex_real, beta_complex_imag) = self.coefficients\n        p = get_psd_value(\n            alpha_real, beta_real,\n            alpha_complex_real, alpha_complex_imag,\n            beta_complex_real, beta_complex_imag,\n            w.flatten(),\n        )\n        return p.reshape(w.shape)",
    "docstring": "Compute the PSD of the term for an array of angular frequencies\n\n        Args:\n            omega (array[...]): An array of frequencies where the PSD should\n                be evaluated.\n\n        Returns:\n            The value of the PSD for each ``omega``. This will have the same\n            shape as ``omega``."
  },
  {
    "code": "def read(self, cnt=None):\n        if cnt is None or cnt < 0:\n            cnt = self._remain\n        elif cnt > self._remain:\n            cnt = self._remain\n        if cnt == 0:\n            return EMPTY\n        data = self._read(cnt)\n        if data:\n            self._md_context.update(data)\n            self._remain -= len(data)\n        if len(data) != cnt:\n            raise BadRarFile(\"Failed the read enough data\")\n        if not data or self._remain == 0:\n            self._check()\n        return data",
    "docstring": "Read all or specified amount of data from archive entry."
  },
  {
    "code": "def draw(self):\n        self.context.set_line_cap(cairo.LINE_CAP_SQUARE)\n        self.context.save()\n        self.context.rectangle(*self.rect)\n        self.context.clip()\n        cell_borders = CellBorders(self.cell_attributes, self.key, self.rect)\n        borders = list(cell_borders.gen_all())\n        borders.sort(key=attrgetter('width', 'color'))\n        for border in borders:\n            border.draw(self.context)\n        self.context.restore()",
    "docstring": "Draws cell border to context"
  },
  {
    "code": "def select(self, columns=(), by=(), where=(), **kwds):\n        return self._seu('select', columns, by, where, kwds)",
    "docstring": "select from self\n\n        >>> t = q('([]a:1 2 3; b:10 20 30)')\n        >>> t.select('a', where='b > 20').show()\n        a\n        -\n        3"
  },
  {
    "code": "def unesc(line, language):\n    comment = _COMMENT[language]\n    if line.startswith(comment + ' '):\n        return line[len(comment) + 1:]\n    if line.startswith(comment):\n        return line[len(comment):]\n    return line",
    "docstring": "Uncomment once a commented line"
  },
  {
    "code": "def _prune_all_if_small(self, small_size, a_or_u):\n        \"Return True and delete children if small enough.\"\n        if self._nodes is None:\n            return True\n        total_size = (self.app_size() if a_or_u else self.use_size())\n        if total_size < small_size:\n            if a_or_u:\n                self._set_size(total_size, self.use_size())\n            else:\n                self._set_size(self.app_size(), total_size)\n            return True\n        return False",
    "docstring": "Return True and delete children if small enough."
  },
  {
    "code": "def score(self, X, y=None, train=False, **kwargs):\n        score = self.estimator.score(X, y, **kwargs)\n        if train:\n            self.train_score_ = score\n        else:\n            self.test_score_ = score\n        y_pred = self.predict(X)\n        scores = y_pred - y\n        self.draw(y_pred, scores, train=train)\n        return score",
    "docstring": "Generates predicted target values using the Scikit-Learn\n        estimator.\n\n        Parameters\n        ----------\n        X : array-like\n            X (also X_test) are the dependent variables of test set to predict\n\n        y : array-like\n            y (also y_test) is the independent actual variables to score against\n\n        train : boolean\n            If False, `score` assumes that the residual points being plotted\n            are from the test data; if True, `score` assumes the residuals\n            are the train data.\n\n        Returns\n        ------\n        score : float\n            The score of the underlying estimator, usually the R-squared score\n            for regression estimators."
  },
  {
    "code": "def roc(y_true, y_score, ax=None):\n    if any((val is None for val in (y_true, y_score))):\n        raise ValueError(\"y_true and y_score are needed to plot ROC\")\n    if ax is None:\n        ax = plt.gca()\n    y_score_is_vector = is_column_vector(y_score) or is_row_vector(y_score)\n    if y_score_is_vector:\n        n_classes = 2\n    else:\n        _, n_classes = y_score.shape\n    if n_classes > 2:\n        y_true_bin = label_binarize(y_true, classes=np.unique(y_true))\n        _roc_multi(y_true_bin, y_score, ax=ax)\n        for i in range(n_classes):\n            _roc(y_true_bin[:, i], y_score[:, i], ax=ax)\n    else:\n        if y_score_is_vector:\n            _roc(y_true, y_score, ax)\n        else:\n            _roc(y_true, y_score[:, 1], ax)\n    return ax",
    "docstring": "Plot ROC curve.\n\n    Parameters\n    ----------\n    y_true : array-like, shape = [n_samples]\n        Correct target values (ground truth).\n    y_score : array-like, shape = [n_samples] or [n_samples, 2] for binary\n              classification or [n_samples, n_classes] for multiclass\n\n        Target scores (estimator predictions).\n    ax: matplotlib Axes\n        Axes object to draw the plot onto, otherwise uses current Axes\n\n    Notes\n    -----\n    It is assumed that the y_score parameter columns are in order. For example,\n    if ``y_true = [2, 2, 1, 0, 0, 1, 2]``, then the first column in y_score\n    must countain the scores for class 0, second column for class 1 and so on.\n\n\n    Returns\n    -------\n    ax: matplotlib Axes\n        Axes containing the plot\n\n    Examples\n    --------\n    .. plot:: ../../examples/roc.py"
  },
  {
    "code": "def yank_last_arg(event):\n    n = (event.arg if event.arg_present else None)\n    event.current_buffer.yank_last_arg(n)",
    "docstring": "Like `yank_nth_arg`, but if no argument has been given, yank the last word\n    of each line."
  },
  {
    "code": "def _replace_missing_values_column(values, mv):\n    for idx, v in enumerate(values):\n        try:\n            if v in EMPTY or v == mv:\n                values[idx] = \"nan\"\n            elif math.isnan(float(v)):\n                values[idx] = \"nan\"\n            else:\n                values[idx] = v\n        except (TypeError, ValueError):\n            values[idx] = v\n    return values",
    "docstring": "Replace missing values in the values list where applicable\n\n    :param list values: Metadata (column values)\n    :return list values: Metadata (column values)"
  },
  {
    "code": "def get_content_type(self, content_type):\n        qs = self.get_queryset()\n        return qs.filter(content_type__name=content_type)",
    "docstring": "Get all the items of the given content type related to this item."
  },
  {
    "code": "def data_import(self, json_response):\n        if 'data' not in json_response:\n            raise PyVLXException('no element data found: {0}'.format(\n                json.dumps(json_response)))\n        data = json_response['data']\n        for item in data:\n            if 'category' not in item:\n                raise PyVLXException('no element category: {0}'.format(\n                    json.dumps(item)))\n            category = item['category']\n            if category == 'Window opener':\n                self.load_window_opener(item)\n            elif category in ['Roller shutter', 'Dual Shutter']:\n                self.load_roller_shutter(item)\n            elif category in ['Blind']:\n                self.load_blind(item)\n            else:\n                self.pyvlx.logger.warning(\n                    'WARNING: Could not parse product: %s', category)",
    "docstring": "Import data from json response."
  },
  {
    "code": "def file_needs_update(target_file, source_file):\n    if not os.path.isfile(target_file) or get_md5_file_hash(target_file) != get_md5_file_hash(source_file):\n        return True\n    return False",
    "docstring": "Checks if target_file is not existing or differing from source_file\n\n    :param target_file: File target for a copy action\n    :param source_file: File to be copied\n    :return: True, if target_file not existing or differing from source_file, else False\n    :rtype: False"
  },
  {
    "code": "def update(self, url, doc):\n        if self.pid.is_deleted():\n            logger.info(\"Reactivate in DataCite\",\n                        extra=dict(pid=self.pid))\n        try:\n            self.api.metadata_post(doc)\n            self.api.doi_post(self.pid.pid_value, url)\n        except (DataCiteError, HttpError):\n            logger.exception(\"Failed to update in DataCite\",\n                             extra=dict(pid=self.pid))\n            raise\n        if self.pid.is_deleted():\n            self.pid.sync_status(PIDStatus.REGISTERED)\n        logger.info(\"Successfully updated in DataCite\",\n                    extra=dict(pid=self.pid))\n        return True",
    "docstring": "Update metadata associated with a DOI.\n\n        This can be called before/after a DOI is registered.\n\n        :param doc: Set metadata for DOI.\n        :returns: `True` if is updated successfully."
  },
  {
    "code": "def plot(self, pts_per_edge, color=None, ax=None, with_nodes=False):\n        if self._dimension != 2:\n            raise NotImplementedError(\n                \"2D is the only supported dimension\",\n                \"Current dimension\",\n                self._dimension,\n            )\n        if ax is None:\n            ax = _plot_helpers.new_axis()\n        _plot_helpers.add_patch(ax, color, pts_per_edge, *self._get_edges())\n        if with_nodes:\n            ax.plot(\n                self._nodes[0, :],\n                self._nodes[1, :],\n                color=\"black\",\n                marker=\"o\",\n                linestyle=\"None\",\n            )\n        return ax",
    "docstring": "Plot the current surface.\n\n        Args:\n            pts_per_edge (int): Number of points to plot per edge.\n            color (Optional[Tuple[float, float, float]]): Color as RGB profile.\n            ax (Optional[matplotlib.artist.Artist]): matplotlib axis object\n                to add plot to.\n            with_nodes (Optional[bool]): Determines if the control points\n                should be added to the plot. Off by default.\n\n        Returns:\n            matplotlib.artist.Artist: The axis containing the plot. This\n            may be a newly created axis.\n\n        Raises:\n            NotImplementedError: If the surface's dimension is not ``2``."
  },
  {
    "code": "def get_functions_and_classes(package):\n    classes, functions = [], []\n    for name, member in inspect.getmembers(package):\n        if not name.startswith('_'):\n            if inspect.isclass(member):\n                classes.append([name, member])\n            elif inspect.isfunction(member):\n                functions.append([name, member])\n    return classes, functions",
    "docstring": "Retun lists of functions and classes from a package.\n\n    Parameters\n    ----------\n    package : python package object\n\n    Returns\n    --------\n    list, list : list of classes and functions\n        Each sublist consists of [name, member] sublists."
  },
  {
    "code": "def cleanup_dataset(dataset, data_home=None, ext=\".zip\"):\n    removed = 0\n    data_home = get_data_home(data_home)\n    datadir = os.path.join(data_home, dataset)\n    archive = os.path.join(data_home, dataset+ext)\n    if os.path.exists(datadir):\n        shutil.rmtree(datadir)\n        removed += 1\n    if os.path.exists(archive):\n        os.remove(archive)\n        removed += 1\n    return removed",
    "docstring": "Removes the dataset directory and archive file from the data home directory.\n\n    Parameters\n    ----------\n    dataset : str\n        The name of the dataset; should either be a folder in data home or\n        specified in the yellowbrick.datasets.DATASETS variable.\n\n    data_home : str, optional\n        The path on disk where data is stored. If not passed in, it is looked\n        up from YELLOWBRICK_DATA or the default returned by ``get_data_home``.\n\n    ext : str, default: \".zip\"\n        The extension of the archive file.\n\n    Returns\n    -------\n    removed : int\n        The number of objects removed from data_home."
  },
  {
    "code": "def parse(version):\n    match = _REGEX.match(version)\n    if match is None:\n        raise ValueError('%s is not valid SemVer string' % version)\n    version_parts = match.groupdict()\n    version_parts['major'] = int(version_parts['major'])\n    version_parts['minor'] = int(version_parts['minor'])\n    version_parts['patch'] = int(version_parts['patch'])\n    return version_parts",
    "docstring": "Parse version to major, minor, patch, pre-release, build parts.\n\n    :param version: version string\n    :return: dictionary with the keys 'build', 'major', 'minor', 'patch',\n             and 'prerelease'. The prerelease or build keys can be None\n             if not provided\n    :rtype: dict\n\n    >>> import semver\n    >>> ver = semver.parse('3.4.5-pre.2+build.4')\n    >>> ver['major']\n    3\n    >>> ver['minor']\n    4\n    >>> ver['patch']\n    5\n    >>> ver['prerelease']\n    'pre.2'\n    >>> ver['build']\n    'build.4'"
  },
  {
    "code": "def offset_limit(func):\n    def func_wrapper(self, start, stop):\n        offset = start\n        limit = stop - start\n        return func(self, offset, limit)\n    return func_wrapper",
    "docstring": "Decorator that converts python slicing to offset and limit"
  },
  {
    "code": "def hex2term(hexval: str, allow_short: bool = False) -> str:\n    return rgb2term(*hex2rgb(hexval, allow_short=allow_short))",
    "docstring": "Convert a hex value into the nearest terminal code number."
  },
  {
    "code": "def shutdown(self):\n        task = asyncio.ensure_future(self.core.shutdown())\n        self.loop.run_until_complete(task)",
    "docstring": "Shutdown the application and exit\n\n        :returns: No return value"
  },
  {
    "code": "def start(self, zone_id, duration):\n        path = 'zone/start'\n        payload = {'id': zone_id, 'duration': duration}\n        return self.rachio.put(path, payload)",
    "docstring": "Start a zone."
  },
  {
    "code": "def add(self, item):\n        if not item.startswith(self.prefix):\n            item = os.path.join(self.base, item)\n        self.files.add(os.path.normpath(item))",
    "docstring": "Add a file to the manifest.\n\n        :param item: The pathname to add. This can be relative to the base."
  },
  {
    "code": "def create_object(self, name, image_sets):\n        identifier = str(uuid.uuid4()).replace('-','')\n        properties = {datastore.PROPERTY_NAME: name}\n        obj = PredictionImageSetHandle(identifier, properties, image_sets)\n        self.insert_object(obj)\n        return obj",
    "docstring": "Create a prediction image set list.\n\n        Parameters\n        ----------\n        name : string\n            User-provided name for the image group.\n        image_sets : list(PredictionImageSet)\n            List of prediction image sets\n\n        Returns\n        -------\n        PredictionImageSetHandle\n            Object handle for created prediction image set"
  },
  {
    "code": "def _backup_file(path):\n    backup_base = '/var/local/woven-backup'\n    backup_path = ''.join([backup_base,path])\n    if not exists(backup_path):\n        directory = ''.join([backup_base,os.path.split(path)[0]])\n        sudo('mkdir -p %s'% directory)\n        sudo('cp %s %s'% (path,backup_path))",
    "docstring": "Backup a file but never overwrite an existing backup file"
  },
  {
    "code": "def get_setting(key, *default):\n    if default:\n        return get_settings().get(key, default[0])\n    else:\n        return get_settings()[key]",
    "docstring": "Return specific search setting from Django conf."
  },
  {
    "code": "def get_widget(name):\n    for widget in registry:\n        if widget.__name__ == name:\n            return widget\n    raise WidgetNotFound(\n        _('The widget %s has not been registered.') % name)",
    "docstring": "Give back a widget class according to his name."
  },
  {
    "code": "def config_required(f):\n    def new_func(obj, *args, **kwargs):\n        if 'config' not in obj:\n            click.echo(_style(obj.get('show_color', False),\n                              'Could not find a valid configuration file!',\n                              fg='red', bold=True))\n            raise click.Abort()\n        else:\n            return f(obj, *args, **kwargs)\n    return update_wrapper(new_func, f)",
    "docstring": "Decorator that checks whether a configuration file was set."
  },
  {
    "code": "def copyNamespaceList(self):\n        ret = libxml2mod.xmlCopyNamespaceList(self._o)\n        if ret is None:raise treeError('xmlCopyNamespaceList() failed')\n        __tmp = xmlNs(_obj=ret)\n        return __tmp",
    "docstring": "Do a copy of an namespace list."
  },
  {
    "code": "def __import_vars(self, env_file):\n        with open(env_file, \"r\") as f:\n            for line in f:\n                try:\n                    line = line.lstrip()\n                    if line.startswith('export'):\n                        line = line.replace('export', '', 1)\n                    key, val = line.strip().split('=', 1)\n                except ValueError:\n                    pass\n                else:\n                    if not callable(val):\n                        if self.verbose_mode:\n                            if key in self.app.config:\n                                print(\n                                    \" * Overwriting an existing config var:\"\n                                    \" {0}\".format(key))\n                            else:\n                                print(\n                                    \" * Setting an entirely new config var:\"\n                                    \" {0}\".format(key))\n                        self.app.config[key] = re.sub(\n                            r\"\\A[\\\"']|[\\\"']\\Z\", \"\", val)",
    "docstring": "Actual importing function."
  },
  {
    "code": "def text(self, data):\n        data = data\n        middle = data.lstrip(spaceCharacters)\n        left = data[:len(data) - len(middle)]\n        if left:\n            yield {\"type\": \"SpaceCharacters\", \"data\": left}\n        data = middle\n        middle = data.rstrip(spaceCharacters)\n        right = data[len(middle):]\n        if middle:\n            yield {\"type\": \"Characters\", \"data\": middle}\n        if right:\n            yield {\"type\": \"SpaceCharacters\", \"data\": right}",
    "docstring": "Generates SpaceCharacters and Characters tokens\n\n        Depending on what's in the data, this generates one or more\n        ``SpaceCharacters`` and ``Characters`` tokens.\n\n        For example:\n\n            >>> from html5lib.treewalkers.base import TreeWalker\n            >>> # Give it an empty tree just so it instantiates\n            >>> walker = TreeWalker([])\n            >>> list(walker.text(''))\n            []\n            >>> list(walker.text('  '))\n            [{u'data': '  ', u'type': u'SpaceCharacters'}]\n            >>> list(walker.text(' abc '))  # doctest: +NORMALIZE_WHITESPACE\n            [{u'data': ' ', u'type': u'SpaceCharacters'},\n            {u'data': u'abc', u'type': u'Characters'},\n            {u'data': u' ', u'type': u'SpaceCharacters'}]\n\n        :arg data: the text data\n\n        :returns: one or more ``SpaceCharacters`` and ``Characters`` tokens"
  },
  {
    "code": "def inject_coordinates(self,\n                           x_coords,\n                           y_coords,\n                           rescale_x=None,\n                           rescale_y=None,\n                           original_x=None,\n                           original_y=None):\n        self._verify_coordinates(x_coords, 'x')\n        self._verify_coordinates(y_coords, 'y')\n        self.x_coords = x_coords\n        self.y_coords = y_coords\n        self._rescale_x = rescale_x\n        self._rescale_y = rescale_y\n        self.original_x = x_coords if original_x is None else original_x\n        self.original_y = y_coords if original_y is None else original_y",
    "docstring": "Inject custom x and y coordinates for each term into chart.\n\n        Parameters\n        ----------\n        x_coords: array-like\n            positions on x-axis \\in [0,1]\n        y_coords: array-like\n            positions on y-axis \\in [0,1]\n        rescale_x: lambda list[0,1]: list[0,1], default identity\n            Rescales x-axis after filtering\n        rescale_y: lambda list[0,1]: list[0,1], default identity\n            Rescales y-axis after filtering\n        original_x : array-like, optional\n            Original, unscaled x-values.  Defaults to x_coords\n        original_y : array-like, optional\n            Original, unscaled y-values.  Defaults to y_coords\n        Returns\n        -------\n        self: ScatterChart"
  },
  {
    "code": "def delete_thumbnails(self, image_file):\n        thumbnail_keys = self._get(image_file.key, identity='thumbnails')\n        if thumbnail_keys:\n            for key in thumbnail_keys:\n                thumbnail = self._get(key)\n                if thumbnail:\n                    self.delete(thumbnail, False)\n                    thumbnail.delete()\n            self._delete(image_file.key, identity='thumbnails')",
    "docstring": "Deletes references to thumbnails as well as thumbnail ``image_files``."
  },
  {
    "code": "def __set_whitelist(self, whitelist=None):\n        self.whitelist = {}\n        self.sanitizelist = ['script', 'style']\n        if isinstance(whitelist, dict) and '*' in whitelist.keys():\n            self.isNotPurify = True\n            self.whitelist_keys = []\n            return\n        else:\n            self.isNotPurify = False\n        self.whitelist.update(whitelist or {})\n        self.whitelist_keys = self.whitelist.keys()",
    "docstring": "Update default white list by customer white list"
  },
  {
    "code": "def _check_module_is_image_embedding(module_spec):\n  issues = []\n  input_info_dict = module_spec.get_input_info_dict()\n  if (list(input_info_dict.keys()) != [\"images\"] or\n      input_info_dict[\"images\"].dtype != tf.float32):\n    issues.append(\"Module 'default' signature must require a single input, \"\n                  \"which must have type float32 and name 'images'.\")\n  else:\n    try:\n      image_util.get_expected_image_size(module_spec)\n    except ValueError as e:\n      issues.append(\"Module does not support hub.get_expected_image_size(); \"\n                    \"original error was:\\n\" + str(e))\n  output_info_dict = module_spec.get_output_info_dict()\n  if \"default\" not in output_info_dict:\n    issues.append(\"Module 'default' signature must have a 'default' output.\")\n  else:\n    output_type = output_info_dict[\"default\"].dtype\n    output_shape = output_info_dict[\"default\"].get_shape()\n    if not (output_type == tf.float32 and output_shape.ndims == 2 and\n            output_shape.dims[1].value):\n      issues.append(\"Module 'default' signature must have a 'default' output \"\n                    \"of tf.Tensor(shape=(_,K), dtype=float32).\")\n  if issues:\n    raise ValueError(\"Module is not usable as image embedding: %r\" % issues)",
    "docstring": "Raises ValueError if `module_spec` is not usable as image embedding.\n\n  Args:\n    module_spec: A `_ModuleSpec` to test.\n\n  Raises:\n    ValueError: if `module_spec` default signature is not compatible with\n        mappingan \"images\" input to a Tensor(float32, shape=(_,K))."
  },
  {
    "code": "def t_php_OBJECT_OPERATOR(t):\n    r'->'\n    if re.match(r'[A-Za-z_]', peek(t.lexer)):\n        t.lexer.push_state('property')\n    return t",
    "docstring": "r'->"
  },
  {
    "code": "def dump(self):\n        out = []\n        out.append(self.filetype)\n        out.append(\"Format: {}\".format(self.version))\n        out.append(\"Type: ASCII\")\n        out.append(\"\")\n        for cmd in self.commands:\n            out.append(self.encode(cmd))\n        return \"\\n\".join(out) + \"\\n\"",
    "docstring": "Dump all commands in this object to a string.\n\n        Returns:\n            str: An encoded list of commands separated by\n                \\n characters suitable for saving to a file."
  },
  {
    "code": "def concatenate_and_rewrite(self, paths, output_filename, variant=None):\n        stylesheets = []\n        for path in paths:\n            def reconstruct(match):\n                quote = match.group(1) or ''\n                asset_path = match.group(2)\n                if NON_REWRITABLE_URL.match(asset_path):\n                    return \"url(%s%s%s)\" % (quote, asset_path, quote)\n                asset_url = self.construct_asset_path(asset_path, path,\n                                                      output_filename, variant)\n                return \"url(%s)\" % asset_url\n            content = self.read_text(path)\n            content = re.sub(URL_DETECTOR, reconstruct, content)\n            stylesheets.append(content)\n        return '\\n'.join(stylesheets)",
    "docstring": "Concatenate together files and rewrite urls"
  },
  {
    "code": "def find_clique_embedding(k, m, n=None, t=None, target_edges=None):\n    import random\n    _, nodes = k\n    m, n, t, target_edges = _chimera_input(m, n, t, target_edges)\n    if len(nodes) == 1:\n        qubits = set().union(*target_edges)\n        qubit = random.choice(tuple(qubits))\n        embedding = [[qubit]]\n    elif len(nodes) == 2:\n        if not isinstance(target_edges, list):\n            edges = list(target_edges)\n        edge = edges[random.randrange(len(edges))]\n        embedding = [[edge[0]], [edge[1]]]\n    else:\n        embedding = processor(target_edges, M=m, N=n, L=t).tightestNativeClique(len(nodes))\n    if not embedding:\n        raise ValueError(\"cannot find a K{} embedding for given Chimera lattice\".format(k))\n    return dict(zip(nodes, embedding))",
    "docstring": "Find an embedding for a clique in a Chimera graph.\n\n    Given a target :term:`Chimera` graph size, and a clique (fully connect graph),\n    attempts to find an embedding.\n\n    Args:\n        k (int/iterable):\n            Clique to embed. If k is an integer, generates an embedding for a clique of size k\n            labelled [0,k-1].\n            If k is an iterable, generates an embedding for a clique of size len(k), where\n            iterable k is the variable labels.\n\n        m (int):\n            Number of rows in the Chimera lattice.\n\n        n (int, optional, default=m):\n            Number of columns in the Chimera lattice.\n\n        t (int, optional, default 4):\n            Size of the shore within each Chimera tile.\n\n        target_edges (iterable[edge]):\n            A list of edges in the target Chimera graph. Nodes are labelled as\n            returned by :func:`~dwave_networkx.generators.chimera_graph`.\n\n    Returns:\n        dict: An embedding mapping a clique to the Chimera lattice.\n\n    Examples:\n        The first example finds an embedding for a :math:`K_4` complete graph in a single\n        Chimera unit cell. The second for an alphanumerically labeled :math:`K_3`\n        graph in 4 unit cells.\n\n        >>> from dwave.embedding.chimera import find_clique_embedding\n        ...\n        >>> embedding = find_clique_embedding(4, 1, 1)\n        >>> embedding  # doctest: +SKIP\n        {0: [4, 0], 1: [5, 1], 2: [6, 2], 3: [7, 3]}\n\n        >>> from dwave.embedding.chimera import find_clique_embedding\n        ...\n        >>> embedding = find_clique_embedding(['a', 'b', 'c'], m=2, n=2, t=4)\n        >>> embedding  # doctest: +SKIP\n        {'a': [20, 16], 'b': [21, 17], 'c': [22, 18]}"
  },
  {
    "code": "def lists(self, value, key=None):\n        results = map(lambda x: x[value], self._items)\n        return list(results)",
    "docstring": "Get a list with the values of a given key\n\n        :rtype: list"
  },
  {
    "code": "def remove(self, objs):\n        if self.readonly:\n            raise NotImplementedError(\n                '{} links can\\'t be modified'.format(self._slug)\n            )\n        if not self._parent.id:\n            raise ObjectNotSavedException(\n                \"Links can not be modified before the object has been saved.\"\n            )\n        _objs = [obj for obj in self._build_obj_list(objs) if obj in self]\n        if not _objs:\n            return\n        _obj_ids = \",\".join(_objs)\n        self._parent.http_delete(\n            '{}/links/{}/{}'.format(self._parent.id, self._slug, _obj_ids),\n            retry=True,\n        )\n        self._linked_object_ids = [\n            obj for obj in self._linked_object_ids if obj not in _objs\n        ]",
    "docstring": "Removes the given `objs` from this `LinkCollection`.\n\n        - **objs** can be a list of :py:class:`.PanoptesObject` instances, a\n          list of object IDs, a single :py:class:`.PanoptesObject` instance, or\n          a single object ID.\n\n        Examples::\n\n            organization.links.projects.remove(1234)\n            organization.links.projects.remove(Project(1234))\n            workflow.links.subject_sets.remove([1,2,3,4])\n            workflow.links.subject_sets.remove([Project(12), Project(34)])"
  },
  {
    "code": "def command_line():\n    from docopt import docopt\n    doc = docopt( __doc__, version=VERSION )\n    args = pd.Series({k.replace('--', ''): v for k, v in doc.items()})\n    if args.all:\n        graph = Graph2Pandas(args.file, _type='all')\n    elif args.type:\n        graph = Graph2Pandas(args.file, _type=args.type)\n    else:\n        graph = Graph2Pandas(args.file)\n    graph.save(args.output)",
    "docstring": "If you want to use the command line"
  },
  {
    "code": "def get_by(self, field, value):\n        if field == 'userName' or field == 'name':\n            return self._client.get(self.URI + '/' + value)\n        elif field == 'role':\n            value = value.replace(\" \", \"%20\")\n            return self._client.get(self.URI + '/roles/users/' + value)['members']\n        else:\n            raise HPOneViewException('Only userName, name and role can be queried for this resource.')",
    "docstring": "Gets all Users that match the filter.\n\n        The search is case-insensitive.\n\n        Args:\n            field: Field name to filter. Accepted values: 'name', 'userName', 'role'\n            value: Value to filter.\n\n        Returns:\n            list: A list of Users."
  },
  {
    "code": "def process_tick(self, tick_tup):\n        self._tick_counter += 1\n        self.ack(tick_tup)\n        if self._tick_counter > self.ticks_between_batches and self._batches:\n            self.process_batches()\n            self._tick_counter = 0",
    "docstring": "Increment tick counter, and call ``process_batch`` for all current\n        batches if tick counter exceeds ``ticks_between_batches``.\n\n        See :class:`pystorm.component.Bolt` for more information.\n\n        .. warning::\n            This method should **not** be overriden.  If you want to tweak\n            how Tuples are grouped into batches, override ``group_key``."
  },
  {
    "code": "def solve_each(expr, vars):\n    lhs_values, _ = __solve_for_repeated(expr.lhs, vars)\n    for lhs_value in repeated.getvalues(lhs_values):\n        result = solve(expr.rhs, __nest_scope(expr.lhs, vars, lhs_value))\n        if not result.value:\n            return result._replace(value=False)\n    return Result(True, ())",
    "docstring": "Return True if RHS evaluates to a true value with each state of LHS.\n\n    If LHS evaluates to a normal IAssociative object then this is the same as\n    a regular let-form, except the return value is always a boolean. If LHS\n    evaluates to a repeared var (see efilter.protocols.repeated) of\n    IAssociative objects then RHS will be evaluated with each state and True\n    will be returned only if each result is true."
  },
  {
    "code": "def setParentAnalysisRequest(self, value):\n        self.Schema().getField(\"ParentAnalysisRequest\").set(self, value)\n        if not value:\n            noLongerProvides(self, IAnalysisRequestPartition)\n        else:\n            alsoProvides(self, IAnalysisRequestPartition)",
    "docstring": "Sets a parent analysis request, making the current a partition"
  },
  {
    "code": "def error(self, line_number, offset, text, check):\n        code = super(_PycodestyleReport, self).error(\n            line_number, offset, text, check)\n        if code:\n            self.errors.append(dict(\n                text=text,\n                type=code.replace('E', 'C'),\n                col=offset + 1,\n                lnum=line_number,\n            ))",
    "docstring": "Save errors."
  },
  {
    "code": "def set_walltime(self, walltime):\n        if not isinstance(walltime, timedelta):\n            raise TypeError(\n                'walltime must be an instance of datetime.timedelta. %s given' %\n                type(walltime)\n            )\n        self._options['walltime'] = walltime\n        return self",
    "docstring": "Setting a walltime for the job\n\n        >>> job.set_walltime(datetime.timedelta(hours=2, minutes=30))\n\n        :param walltime: Walltime of the job (an instance of timedelta)\n        :returns: self\n        :rtype: self"
  },
  {
    "code": "def recv_rpc(self, context, payload):\n        logger.debug(\"Adding RPC payload to ControlBuffer queue: %s\", payload)\n        self.buf.put(('rpc', (context, payload)))\n        with self.cv:\n            self.cv.notifyAll()",
    "docstring": "Call from any thread"
  },
  {
    "code": "def _process_pod_rate(self, metric_name, metric, scraper_config):\n        if metric.type not in METRIC_TYPES:\n            self.log.error(\"Metric type %s unsupported for metric %s\" % (metric.type, metric.name))\n            return\n        samples = self._sum_values_by_context(metric, self._get_pod_uid_if_pod_metric)\n        for pod_uid, sample in iteritems(samples):\n            if '.network.' in metric_name and self._is_pod_host_networked(pod_uid):\n                continue\n            tags = tagger.tag('kubernetes_pod://%s' % pod_uid, tagger.HIGH)\n            tags += scraper_config['custom_tags']\n            val = sample[self.SAMPLE_VALUE]\n            self.rate(metric_name, val, tags)",
    "docstring": "Takes a simple metric about a pod, reports it as a rate.\n        If several series are found for a given pod, values are summed before submission."
  },
  {
    "code": "def index_resources(self):\n        if not self.__index_resources:\n            self.__index_resources = IndexResources(self.__connection)\n        return self.__index_resources",
    "docstring": "Gets the Index Resources API client.\n\n        Returns:\n            IndexResources:"
  },
  {
    "code": "def rebase(self, text, char='X'):\n        regexp = re.compile(r'\\b(%s)\\b' % '|'.join(self.collection),\n                            re.IGNORECASE | re.UNICODE)\n        def replace(m):\n            word = m.group(1)\n            return char * len(word)\n        return regexp.sub(replace, text)",
    "docstring": "Rebases text with stop words removed."
  },
  {
    "code": "def fill_subparser(subparser):\n    urls = ([None] * len(ALL_FILES))\n    filenames = list(ALL_FILES)\n    subparser.set_defaults(urls=urls, filenames=filenames)\n    subparser.add_argument('-P', '--url-prefix', type=str, default=None,\n                           help=\"URL prefix to prepend to the filenames of \"\n                                \"non-public files, in order to download them. \"\n                                \"Be sure to include the trailing slash.\")\n    return default_downloader",
    "docstring": "Sets up a subparser to download the ILSVRC2012 dataset files.\n\n    Note that you will need to use `--url-prefix` to download the\n    non-public files (namely, the TARs of images). This is a single\n    prefix that is common to all distributed files, which you can\n    obtain by registering at the ImageNet website [DOWNLOAD].\n\n    Note that these files are quite large and you may be better off\n    simply downloading them separately and running ``fuel-convert``.\n\n    .. [DOWNLOAD] http://www.image-net.org/download-images\n\n\n    Parameters\n    ----------\n    subparser : :class:`argparse.ArgumentParser`\n        Subparser handling the `ilsvrc2012` command."
  },
  {
    "code": "def build_query(self, sql, lookup):\n        for key, val in six.iteritems(lookup):\n            sql = sql.replace(\"$\" + key, val)\n        return sql",
    "docstring": "Modify table and field name variables in a sql string with a dict.\n        This seems to be discouraged by psycopg2 docs but it makes small\n        adjustments to large sql strings much easier, making prepped queries\n        much more versatile.\n\n        USAGE\n        sql = 'SELECT $myInputField FROM $myInputTable'\n        lookup = {'myInputField':'customer_id', 'myInputTable':'customers'}\n        sql = db.build_query(sql, lookup)"
  },
  {
    "code": "def distros_for_filename(filename, metadata=None):\n    return distros_for_location(\n        normalize_path(filename), os.path.basename(filename), metadata\n    )",
    "docstring": "Yield possible egg or source distribution objects based on a filename"
  },
  {
    "code": "def get_report_rst(self):\n        res = ''\n        res += '-----------------------------------\\n' \n        res += self.nme  + '\\n'\n        res += '-----------------------------------\\n\\n'\n        res += self.desc + '\\n'\n        res += self.fldr + '\\n\\n'\n        res += '.. contents:: \\n\\n\\n'\n        res += 'Overview\\n' + '===========================================\\n\\n'\n        res += 'This document contains details on the project ' + self.nme + '\\n\\n'\n        for d in self.details:\n            res += ' - ' + d[0] + ' = ' + d[1] + '\\n\\n'\n        res += '\\nTABLES\\n' + '===========================================\\n\\n'\n        for t in self.datatables:\n            res +=  t.name + '\\n'\n            res += '-------------------------\\n\\n'\n            res += t.format_rst() + '\\n\\n'\n        return res",
    "docstring": "formats the project into a report in RST format"
  },
  {
    "code": "def parse_address(text: str) -> Tuple[str, int]:\n    match = re.search(\n        r'\\('\n        r'(\\d{1,3})\\s*,'\n        r'\\s*(\\d{1,3})\\s*,'\n        r'\\s*(\\d{1,3})\\s*,'\n        r'\\s*(\\d{1,3})\\s*,'\n        r'\\s*(\\d{1,3})\\s*,'\n        r'\\s*(\\d{1,3})\\s*'\n        r'\\)',\n        text)\n    if match:\n        return (\n            '{0}.{1}.{2}.{3}'.format(int(match.group(1)),\n                                     int(match.group(2)),\n                                     int(match.group(3)),\n                                     int(match.group(4))\n                                     ),\n            int(match.group(5)) << 8 | int(match.group(6))\n            )\n    else:\n        raise ValueError('No address found')",
    "docstring": "Parse PASV address."
  },
  {
    "code": "def check_and_consume(self):\n        if self._count < 1.0:\n            self._fill()\n        consumable = self._count >= 1.0\n        if consumable:\n            self._count -= 1.0\n            self.throttle_count = 0\n        else:\n            self.throttle_count += 1\n        return consumable",
    "docstring": "Returns True if there is currently at least one token, and reduces\n        it by one."
  },
  {
    "code": "def removeSubscriber(self, email):\n        headers, raw_data = self._perform_subscribe()\n        missing_flag, raw_data = self._remove_subscriber(email, raw_data)\n        if missing_flag:\n            return\n        self._update_subscribe(headers, raw_data)\n        self.log.info(\"Successfully remove a subscriber: %s for <Workitem %s>\",\n                      email, self)",
    "docstring": "Remove a subscriber from this workitem\n\n        If the subscriber has not been added, no more actions will be\n        performed.\n\n        :param email: the subscriber's email"
  },
  {
    "code": "def _make_request(self, opener, request, timeout=None):\n        timeout = timeout or self.timeout\n        try:\n            return opener.open(request, timeout=timeout)\n        except HTTPError as err:\n            exc = handle_error(err)\n            exc.__cause__ = None\n            raise exc",
    "docstring": "Make the API call and return the response. This is separated into\n           it's own function, so we can mock it easily for testing.\n\n        :param opener:\n        :type opener:\n        :param request: url payload to request\n        :type request: urllib.Request object\n        :param timeout: timeout value or None\n        :type timeout: float\n        :return: urllib response"
  },
  {
    "code": "def generate_certificate(self, common_name, public_key_algorithm='rsa',\n            signature_algorithm='rsa_sha_512', key_length=2048,\n            signing_ca=None):\n        return GatewayCertificate._create(self, common_name, public_key_algorithm,\n            signature_algorithm, key_length, signing_ca)",
    "docstring": "Generate an internal gateway certificate used for VPN on this engine.\n        Certificate request should be an instance of VPNCertificate.\n\n        :param: str common_name: common name for certificate\n        :param str public_key_algorithm: public key type to use. Valid values\n            rsa, dsa, ecdsa.\n        :param str signature_algorithm: signature algorithm. Valid values\n            dsa_sha_1, dsa_sha_224, dsa_sha_256, rsa_md5, rsa_sha_1, rsa_sha_256,\n            rsa_sha_384, rsa_sha_512, ecdsa_sha_1, ecdsa_sha_256, ecdsa_sha_384,\n            ecdsa_sha_512. (Default: rsa_sha_512)\n        :param int key_length: length of key. Key length depends on the key\n            type. For example, RSA keys can be 1024, 2048, 3072, 4096. See SMC\n            documentation for more details.\n        :param str,VPNCertificateCA signing_ca: by default will use the\n            internal RSA CA\n        :raises CertificateError: error generating certificate\n        :return: GatewayCertificate"
  },
  {
    "code": "def variant_to_list(obj):\n    if isinstance(obj, list):\n        return obj\n    elif is_unicode_string(obj):\n        return [s for s in obj.split() if len(s) > 0]\n    elif isinstance(obj, set) or isinstance(obj, frozenset):\n        return list(obj)\n    raise TypeError(\"The given value must be a list or a set of descriptor strings, or a Unicode string.\")",
    "docstring": "Return a list containing the descriptors in the given object.\n\n    The ``obj`` can be a list or a set of descriptor strings, or a Unicode string.\n    \n    If ``obj`` is a Unicode string, it will be split using spaces as delimiters.\n\n    :param variant obj: the object to be parsed\n    :rtype: list \n    :raise TypeError: if the ``obj`` has a type not listed above"
  },
  {
    "code": "def _create_word_graph_file(name, file_storage, word_set):\n    word_graph_file = file_storage.create_file(name)\n    spelling.wordlist_to_graph_file(sorted(list(word_set)),\n                                    word_graph_file)\n    return copy_to_ram(file_storage).open_file(name)",
    "docstring": "Create a word graph file and open it in memory."
  },
  {
    "code": "def redirect_to_lang(*args, **kwargs):\n    endpoint = request.endpoint.replace('_redirect', '')\n    kwargs = multi_to_dict(request.args)\n    kwargs.update(request.view_args)\n    kwargs['lang_code'] = default_lang\n    return redirect(url_for(endpoint, **kwargs))",
    "docstring": "Redirect non lang-prefixed urls to default language."
  },
  {
    "code": "def _control_line(self, line):\n        if line > float(self.LINE_LAST_PIXEL):\n            return int(self.LINE_LAST_PIXEL)\n        elif line < float(self.LINE_FIRST_PIXEL):\n            return int(self.LINE_FIRST_PIXEL)\n        else:\n            return line",
    "docstring": "Control the asked line is ok"
  },
  {
    "code": "def message_interactions(self):\n        if self._message_interactions is None:\n            self._message_interactions = MessageInteractionList(\n                self._version,\n                service_sid=self._solution['service_sid'],\n                session_sid=self._solution['session_sid'],\n                participant_sid=self._solution['sid'],\n            )\n        return self._message_interactions",
    "docstring": "Access the message_interactions\n\n        :returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList\n        :rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList"
  },
  {
    "code": "def list_users(self):\n        url = self.bucket_url + '/_user/'\n        response = requests.get(url)\n        response = response.json()\n        return response",
    "docstring": "a method to list all the user ids of all users in the bucket"
  },
  {
    "code": "def from_string(species_string: str):\n        m = re.search(r\"([A-Z][a-z]*)([0-9.]*)([+\\-])(.*)\", species_string)\n        if m:\n            sym = m.group(1)\n            oxi = 1 if m.group(2) == \"\" else float(m.group(2))\n            oxi = -oxi if m.group(3) == \"-\" else oxi\n            properties = None\n            if m.group(4):\n                toks = m.group(4).replace(\",\", \"\").split(\"=\")\n                properties = {toks[0]: float(toks[1])}\n            return Specie(sym, oxi, properties)\n        else:\n            raise ValueError(\"Invalid Species String\")",
    "docstring": "Returns a Specie from a string representation.\n\n        Args:\n            species_string (str): A typical string representation of a\n                species, e.g., \"Mn2+\", \"Fe3+\", \"O2-\".\n\n        Returns:\n            A Specie object.\n\n        Raises:\n            ValueError if species_string cannot be intepreted."
  },
  {
    "code": "def copy_node_info(src, dest):\n    for attr in ['lineno', 'fromlineno', 'tolineno',\n                 'col_offset', 'parent']:\n        if hasattr(src, attr):\n            setattr(dest, attr, getattr(src, attr))",
    "docstring": "Copy information from src to dest\n\n    Every node in the AST has to have line number information.  Get\n    the information from the old stmt."
  },
  {
    "code": "def _get_callargs(self, *args, **kwargs):\n        callargs = getcallargs(self.func, *args, **kwargs)\n        return callargs",
    "docstring": "Retrieve all arguments that `self.func` needs and\n        return a dictionary with call arguments."
  },
  {
    "code": "def setup_actions(self):\n        self.actionOpen.triggered.connect(self.on_open)\n        self.actionNew.triggered.connect(self.on_new)\n        self.actionSave.triggered.connect(self.on_save)\n        self.actionSave_as.triggered.connect(self.on_save_as)\n        self.actionQuit.triggered.connect(QtWidgets.QApplication.instance().quit)\n        self.tabWidget.current_changed.connect(\n            self.on_current_tab_changed)\n        self.actionAbout.triggered.connect(self.on_about)",
    "docstring": "Connects slots to signals"
  },
  {
    "code": "def t_newline(self, t):\n        r'\\n'\n        t.lexer.lineno += 1\n        t.lexer.latest_newline = t.lexpos",
    "docstring": "r'\\n"
  },
  {
    "code": "def import_keypair(kwargs=None, call=None):\n    with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename:\n        public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read())\n    digitalocean_kwargs = {\n        'name': kwargs['keyname'],\n        'public_key': public_key_content\n    }\n    created_result = create_key(digitalocean_kwargs, call=call)\n    return created_result",
    "docstring": "Upload public key to cloud provider.\n    Similar to EC2 import_keypair.\n\n    .. versionadded:: 2016.11.0\n\n    kwargs\n        file(mandatory): public key file-name\n        keyname(mandatory): public key name in the provider"
  },
  {
    "code": "def config(self, config):\n        for section, data in config.items():\n            for variable, value in data.items():\n                self.set_value(section, variable, value)",
    "docstring": "Set config values from config dictionary."
  },
  {
    "code": "def delete_proficiency(self, proficiency_id):\n        collection = JSONClientValidated('learning',\n                                         collection='Proficiency',\n                                         runtime=self._runtime)\n        if not isinstance(proficiency_id, ABCId):\n            raise errors.InvalidArgument('the argument is not a valid OSID Id')\n        proficiency_map = collection.find_one(\n            dict({'_id': ObjectId(proficiency_id.get_identifier())},\n                 **self._view_filter()))\n        objects.Proficiency(osid_object_map=proficiency_map, runtime=self._runtime, proxy=self._proxy)._delete()\n        collection.delete_one({'_id': ObjectId(proficiency_id.get_identifier())})",
    "docstring": "Deletes a ``Proficiency``.\n\n        arg:    proficiency_id (osid.id.Id): the ``Id`` of the\n                ``Proficiency`` to remove\n        raise:  NotFound - ``proficiency_id`` not found\n        raise:  NullArgument - ``proficiency_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def make_random(cls):\n        self = object.__new__(cls)\n        self.rank = Rank.make_random()\n        self.suit = Suit.make_random()\n        return self",
    "docstring": "Returns a random Card instance."
  },
  {
    "code": "def _read_addr_resolve(self, length, htype):\n        if htype == 1:\n            _byte = self._read_fileng(6)\n            _addr = '-'.join(textwrap.wrap(_byte.hex(), 2))\n        else:\n            _addr = self._read_fileng(length)\n        return _addr",
    "docstring": "Resolve MAC address according to protocol.\n\n        Positional arguments:\n            * length -- int, hardware address length\n            * htype -- int, hardware type\n\n        Returns:\n            * str -- MAC address"
  },
  {
    "code": "def index():\n    identity = g.identity\n    actions = {}\n    for action in access.actions.values():\n        actions[action.value] = DynamicPermission(action).allows(identity)\n    if current_user.is_anonymous:\n        return render_template(\"invenio_access/open.html\",\n                               actions=actions,\n                               identity=identity)\n    else:\n        return render_template(\"invenio_access/limited.html\",\n                               message='',\n                               actions=actions,\n                               identity=identity)",
    "docstring": "Basic test view."
  },
  {
    "code": "def autodiscover_media_extensions():\n    import copy\n    from django.conf import settings\n    from django.utils.module_loading import module_has_submodule\n    for app in settings.INSTALLED_APPS:\n        mod = import_module(app)\n        try:\n            import_module('%s.media_extension' % app)\n        except:\n            if module_has_submodule(mod, 'media_extension'):\n                raise",
    "docstring": "Auto-discover INSTALLED_APPS media_extensions.py modules and fail silently when\n    not present. This forces an import on them to register any media extension bits\n    they may want.\n\n    Rip of django.contrib.admin.autodiscover()"
  },
  {
    "code": "def check_honeypot(func=None, field_name=None):\n    if isinstance(func, six.string_types):\n        func, field_name = field_name, func\n    def decorated(func):\n        def inner(request, *args, **kwargs):\n            response = verify_honeypot_value(request, field_name)\n            if response:\n                return response\n            else:\n                return func(request, *args, **kwargs)\n        return wraps(func, assigned=available_attrs(func))(inner)\n    if func is None:\n        def decorator(func):\n            return decorated(func)\n        return decorator\n    return decorated(func)",
    "docstring": "Check request.POST for valid honeypot field.\n\n        Takes an optional field_name that defaults to HONEYPOT_FIELD_NAME if\n        not specified."
  },
  {
    "code": "def _apply_line_rules(lines, commit, rules, line_nr_start):\n        all_violations = []\n        line_nr = line_nr_start\n        for line in lines:\n            for rule in rules:\n                violations = rule.validate(line, commit)\n                if violations:\n                    for violation in violations:\n                        violation.line_nr = line_nr\n                        all_violations.append(violation)\n            line_nr += 1\n        return all_violations",
    "docstring": "Iterates over the lines in a given list of lines and validates a given list of rules against each line"
  },
  {
    "code": "def set_all_curriculums_to_lesson_num(self, lesson_num):\n        for _, curriculum in self.brains_to_curriculums.items():\n            curriculum.lesson_num = lesson_num",
    "docstring": "Sets all the curriculums in this meta curriculum to a specified\n        lesson number.\n\n        Args:\n            lesson_num (int): The lesson number which all the curriculums will\n                be set to."
  },
  {
    "code": "async def set(self, *args, **kwargs):\n        return await _maybe_await(self.event.set(*args, **kwargs))",
    "docstring": "Sets the value of the event."
  },
  {
    "code": "def welcome(self, user):\n        self.send_message(create_message('RoomServer', 'Please welcome {name} to the server!\\nThere are currently {i} users online -\\n {r}\\n'.format(name=user.id, \n                          i=self.amount_of_users_connected, \n                          r=' '.join(self.user_names))))\n        logging.debug('Welcoming user {user} to {room}'.format(user=user.id.name, room=self.name))",
    "docstring": "welcomes a user to the roomserver"
  },
  {
    "code": "def run(self):\n        def receive():\n            if self.with_communicate:\n                self.stdout, self.stderr = self.process.communicate(input=self.stdin)\n            elif self.wait:\n                self.process.wait()\n        if not self.timeout:\n            receive()\n        else:\n            rt = threading.Thread(target=receive)\n            rt.start()\n            rt.join(self.timeout)\n            if rt.isAlive():\n                self.process.kill()\n                def terminate():\n                    if rt.isAlive():\n                        self.process.terminate()\n                threading.Timer(10, terminate).start()\n                raise salt.exceptions.TimedProcTimeoutError(\n                    '{0} : Timed out after {1} seconds'.format(\n                        self.command,\n                        six.text_type(self.timeout),\n                    )\n                )\n        return self.process.returncode",
    "docstring": "wait for subprocess to terminate and return subprocess' return code.\n        If timeout is reached, throw TimedProcTimeoutError"
  },
  {
    "code": "def remove(self, spec_or_id, multi=True, *args, **kwargs):\n        if multi:\n            return self.delete_many(spec_or_id)\n        return self.delete_one(spec_or_id)",
    "docstring": "Backwards compatibility with remove"
  },
  {
    "code": "def archive(self):\n        for path, dirs, files in os.walk(self.work_path, topdown=False):\n            for f_name in files:\n                f_path = os.path.join(path, f_name)\n                if os.path.islink(f_path) or os.path.getsize(f_path) == 0:\n                    os.remove(f_path)\n            if len(os.listdir(path)) == 0:\n                os.rmdir(path)",
    "docstring": "Store model output to laboratory archive."
  },
  {
    "code": "def keys_info(cls, fqdn, key):\n        return cls.json_get('%s/domains/%s/keys/%s' %\n                            (cls.api_url, fqdn, key))",
    "docstring": "Retrieve key information."
  },
  {
    "code": "def update(sc, filename, asset_id):\n    addresses = []\n    with open(filename) as hostfile:\n        for line in hostfile.readlines():\n            addresses.append(line.strip('\\n'))\n    sc.asset_update(asset_id, dns=addresses)",
    "docstring": "Updates a DNS Asset List with the contents of the filename.  The assumed\n    format of the file is 1 entry per line.  This function will convert the\n    file contents into an array of entries and then upload that array into\n    SecurityCenter."
  },
  {
    "code": "def clean_source_index(self):\n        cleanup_timer = Timer()\n        cleanup_counter = 0\n        for entry in os.listdir(self.config.source_index):\n            pathname = os.path.join(self.config.source_index, entry)\n            if os.path.islink(pathname) and not os.path.exists(pathname):\n                logger.warn(\"Cleaning up broken symbolic link: %s\", pathname)\n                os.unlink(pathname)\n                cleanup_counter += 1\n        logger.debug(\"Cleaned up %i broken symbolic links from source index in %s.\", cleanup_counter, cleanup_timer)",
    "docstring": "Cleanup broken symbolic links in the local source distribution index.\n\n        The purpose of this method requires some context to understand. Let me\n        preface this by stating that I realize I'm probably overcomplicating\n        things, but I like to preserve forward / backward compatibility when\n        possible and I don't feel like dropping everyone's locally cached\n        source distribution archives without a good reason to do so. With that\n        out of the way:\n\n        - Versions of pip-accel based on pip 1.4.x maintained a local source\n          distribution index based on a directory containing symbolic links\n          pointing directly into pip's download cache. When files were removed\n          from pip's download cache, broken symbolic links remained in\n          pip-accel's local source distribution index directory. This resulted\n          in very confusing error messages. To avoid this\n          :func:`clean_source_index()` cleaned up broken symbolic links\n          whenever pip-accel was about to invoke pip.\n\n        - More recent versions of pip (6.x) no longer support the same style of\n          download cache that contains source distribution archives that can be\n          re-used directly by pip-accel. To cope with the changes in pip 6.x\n          new versions of pip-accel tell pip to download source distribution\n          archives directly into the local source distribution index directory\n          maintained by pip-accel.\n\n        - It is very reasonable for users of pip-accel to have multiple\n          versions of pip-accel installed on their system (imagine a dozen\n          Python virtual environments that won't all be updated at the same\n          time; this is the situation I always find myself in :-). These\n          versions of pip-accel will be sharing the same local source\n          distribution index directory.\n\n        - All of this leads up to the local source distribution index directory\n          containing a mixture of symbolic links and regular files with no\n          obvious way to atomically and gracefully upgrade the local source\n          distribution index directory while avoiding fights between old and\n          new versions of pip-accel :-).\n\n        - I could of course switch to storing the new local source distribution\n          index in a differently named directory (avoiding potential conflicts\n          between multiple versions of pip-accel) but then I would have to\n          introduce a new configuration option, otherwise everyone who has\n          configured pip-accel to store its source index in a non-default\n          location could still be bitten by compatibility issues.\n\n        For now I've decided to keep using the same directory for the local\n        source distribution index and to keep cleaning up broken symbolic\n        links. This enables cooperating between old and new versions of\n        pip-accel and avoids trashing user's local source distribution indexes.\n        The main disadvantage is that pip-accel is still required to clean up\n        broken symbolic links..."
  },
  {
    "code": "def _bnd(self, xloc, dist, length, cache):\n        lower, upper = evaluation.evaluate_bound(\n            dist, xloc.reshape(1, -1))\n        lower = lower.reshape(length, -1)\n        upper = upper.reshape(length, -1)\n        assert lower.shape == xloc.shape, (lower.shape, xloc.shape)\n        assert upper.shape == xloc.shape\n        return lower, upper",
    "docstring": "boundary function.\n\n        Example:\n            >>> print(chaospy.Iid(chaospy.Uniform(0, 2), 2).range(\n            ...     [[0.1, 0.2, 0.3], [0.2, 0.2, 0.3]]))\n            [[[0. 0. 0.]\n              [0. 0. 0.]]\n            <BLANKLINE>\n             [[2. 2. 2.]\n              [2. 2. 2.]]]"
  },
  {
    "code": "def _gen_back(self):\n        back = set()\n        if self.backends:\n            for backend in self.backends:\n                fun = '{0}.targets'.format(backend)\n                if fun in self.rosters:\n                    back.add(backend)\n            return back\n        return sorted(back)",
    "docstring": "Return a list of loaded roster backends"
  },
  {
    "code": "def data_from_dict(self, data):\n        nvars = []\n        for key, val in data.items():\n            self.__dict__[key].extend(val)\n            if len(nvars) > 1 and len(val) != nvars[-1]:\n                raise IndexError(\n                    'Model <{}> parameter <{}> must have the same length'.\n                    format(self._name, key))\n            nvars.append(len(val))\n        for i, idx in zip(range(self.n), self.idx):\n            self.uid[idx] = i",
    "docstring": "Populate model parameters from a dictionary of parameters\n\n        Parameters\n        ----------\n        data : dict\n            List of parameter dictionaries\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def makeDirectory(self, full_path, dummy = 40841):\n        if full_path[-1] is not '/':\n            full_path += '/'\n        data = {'dstresource': full_path,\n                'userid': self.user_id,\n                'useridx': self.useridx,\n                'dummy': dummy,\n                }\n        s, metadata = self.POST('makeDirectory', data)\n        return s",
    "docstring": "Make a directory\n\n            >>> nd.makeDirectory('/test')\n        \n        :param full_path: The full path to get the directory property. Should be end with '/'.\n\n        :return: ``True`` when success to make a directory or ``False``"
  },
  {
    "code": "def split_list(\n    list_object = None,\n    granularity = None\n    ):\n    if granularity < 0:\n        raise Exception(\"negative granularity\")\n    mean_length = len(list_object) / float(granularity)\n    split_list_object = []\n    last_length = float(0)\n    if len(list_object) > granularity:\n        while last_length < len(list_object):\n            split_list_object.append(\n                list_object[int(last_length):int(last_length + mean_length)]\n            )\n            last_length += mean_length\n    else:\n        split_list_object = [[element] for element in list_object]\n    return split_list_object",
    "docstring": "This function splits a list into a specified number of lists. It returns a\n    list of lists that correspond to these parts. Negative numbers of parts are\n    not accepted and numbers of parts greater than the number of elements in the\n    list result in the maximum possible number of lists being returned."
  },
  {
    "code": "def __GetRequestField(self, method_description, body_type):\n        body_field_name = self.__BodyFieldName(body_type)\n        if body_field_name in method_description.get('parameters', {}):\n            body_field_name = self.__names.FieldName(\n                '%s_resource' % body_field_name)\n        while body_field_name in method_description.get('parameters', {}):\n            body_field_name = self.__names.FieldName(\n                '%s_body' % body_field_name)\n        return body_field_name",
    "docstring": "Determine the request field for this method."
  },
  {
    "code": "def reply(self, ticket_id, text='', cc='', bcc='', content_type='text/plain', files=[]):\n        return self.__correspond(ticket_id, text, 'correspond', cc, bcc, content_type, files)",
    "docstring": "Sends email message to the contacts in ``Requestors`` field of\n        given ticket with subject as is set in ``Subject`` field.\n\n        Form of message according to documentation::\n\n            id: <ticket-id>\n            Action: correspond\n            Text: the text comment\n                  second line starts with the same indentation as first\n            Cc: <...>\n            Bcc: <...>\n            TimeWorked: <...>\n            Attachment: an attachment filename/path\n\n        :param ticket_id: ID of ticket to which message belongs\n        :keyword text: Content of email message\n        :keyword content_type: Content type of email message, default to text/plain\n        :keyword cc: Carbon copy just for this reply\n        :keyword bcc: Blind carbon copy just for this reply\n        :keyword files: Files to attach as multipart/form-data\n                        List of 2/3 tuples: (filename, file-like object, [content type])\n        :returns: ``True``\n                      Operation was successful\n                  ``False``\n                      Sending failed (status code != 200)\n        :raises BadRequest: When ticket does not exist"
  },
  {
    "code": "def create_session_engine(uri=None, cfg=None):\n    if uri is not None:\n        eng = sa.create_engine(uri)\n    elif cfg is not None:\n        eng = sa.create_engine(cfg.get('db', 'SA_ENGINE_URI'))\n    else:\n        raise IOError(\"unable to connect to SQL database\")\n    ses = orm.sessionmaker(bind=eng)()\n    return ses, eng",
    "docstring": "Create an sqlalchemy session and engine.\n\n    :param str uri: The database URI to connect to\n    :param cfg: The configuration object with database URI info.\n    :return: The session and the engine as a list (in that order)"
  },
  {
    "code": "def get_onchain_locksroots(\n        chain: 'BlockChainService',\n        canonical_identifier: CanonicalIdentifier,\n        participant1: Address,\n        participant2: Address,\n        block_identifier: BlockSpecification,\n) -> Tuple[Locksroot, Locksroot]:\n    payment_channel = chain.payment_channel(canonical_identifier=canonical_identifier)\n    token_network = payment_channel.token_network\n    participants_details = token_network.detail_participants(\n        participant1=participant1,\n        participant2=participant2,\n        channel_identifier=canonical_identifier.channel_identifier,\n        block_identifier=block_identifier,\n    )\n    our_details = participants_details.our_details\n    our_locksroot = our_details.locksroot\n    partner_details = participants_details.partner_details\n    partner_locksroot = partner_details.locksroot\n    return our_locksroot, partner_locksroot",
    "docstring": "Return the locksroot for `participant1` and `participant2` at `block_identifier`."
  },
  {
    "code": "def assert_instance_created(self, model_class, **kwargs):\n        return _InstanceContext(\n            self.assert_instance_does_not_exist,\n            self.assert_instance_exists,\n            model_class,\n            **kwargs\n        )",
    "docstring": "Checks if a model instance was created in the database.\n\n        For example::\n\n        >>> with self.assert_instance_created(Article, slug='lorem-ipsum'):\n        ...     Article.objects.create(slug='lorem-ipsum')"
  },
  {
    "code": "def delete(self):\n        r\n        parent = self.parent\n        if parent.expr._supports_contents():\n            parent.remove(self)\n            return\n        for arg in parent.args:\n            if self.expr in arg.contents:\n                arg.contents.remove(self.expr)",
    "docstring": "r\"\"\"Delete this node from the parse tree.\n\n        Where applicable, this will remove all descendants of this node from\n        the parse tree.\n\n        >>> from TexSoup import TexSoup\n        >>> soup = TexSoup(r'''\\textit{\\color{blue}{Silly}}\\textit{keep me!}''')\n        >>> soup.textit.color.delete()\n        >>> soup\n        \\textit{}\\textit{keep me!}\n        >>> soup.textit.delete()\n        >>> soup\n        \\textit{keep me!}"
  },
  {
    "code": "def format_payload(enc, **kwargs):\n    payload = {'enc': enc}\n    load = {}\n    for key in kwargs:\n        load[key] = kwargs[key]\n    payload['load'] = load\n    return package(payload)",
    "docstring": "Pass in the required arguments for a payload, the enc type and the cmd,\n    then a list of keyword args to generate the body of the load dict."
  },
  {
    "code": "def get_metadata(self, loadbalancer, node=None, raw=False):\n        if node:\n            uri = \"/loadbalancers/%s/nodes/%s/metadata\" % (\n                    utils.get_id(loadbalancer), utils.get_id(node))\n        else:\n            uri = \"/loadbalancers/%s/metadata\" % utils.get_id(loadbalancer)\n        resp, body = self.api.method_get(uri)\n        meta = body.get(\"metadata\", [])\n        if raw:\n            return meta\n        ret = dict([(itm[\"key\"], itm[\"value\"]) for itm in meta])\n        return ret",
    "docstring": "Returns the current metadata for the load balancer. If 'node' is\n        provided, returns the current metadata for that node."
  },
  {
    "code": "def set_default_keychain(keychain, domain=\"user\", user=None):\n    cmd = \"security default-keychain -d {0} -s {1}\".format(domain, keychain)\n    return __salt__['cmd.run'](cmd, runas=user)",
    "docstring": "Set the default keychain\n\n    keychain\n        The location of the keychain to set as default\n\n    domain\n        The domain to use valid values are user|system|common|dynamic, the default is user\n\n    user\n        The user to set the default keychain as\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' keychain.set_keychain /Users/fred/Library/Keychains/login.keychain"
  },
  {
    "code": "def get_modelnames() -> List[str]:\n        return sorted(str(fn.split('.')[0])\n                      for fn in os.listdir(models.__path__[0])\n                      if (fn.endswith('.py') and (fn != '__init__.py')))",
    "docstring": "Return a sorted |list| containing all application model names.\n\n        >>> from hydpy.auxs.xmltools import XSDWriter\n        >>> print(XSDWriter.get_modelnames())    # doctest: +ELLIPSIS\n        [...'dam_v001', 'dam_v002', 'dam_v003', 'dam_v004', 'dam_v005',...]"
  },
  {
    "code": "def when_file_changed(*filenames, **kwargs):\n    def _register(action):\n        handler = Handler.get(action)\n        handler.add_predicate(partial(any_file_changed, filenames, **kwargs))\n        return action\n    return _register",
    "docstring": "Register the decorated function to run when one or more files have changed.\n\n    :param list filenames: The names of one or more files to check for changes\n        (a callable returning the name is also accepted).\n    :param str hash_type: The type of hash to use for determining if a file has\n        changed.  Defaults to 'md5'.  Must be given as a kwarg."
  },
  {
    "code": "def use_options(allowed):\n    def update_docstring(f):\n        _update_option_docstring(f, allowed)\n        @functools.wraps(f)\n        def check_options(*args, **kwargs):\n            options = kwargs.get('options', {})\n            not_allowed = [\n                option for option in options if option not in allowed\n                and not option.startswith('_')\n            ]\n            if not_allowed:\n                logging.warning(\n                    'The following options are not supported by '\n                    'this function and will likely result in '\n                    'undefined behavior: {}.'.format(not_allowed)\n                )\n            return f(*args, **kwargs)\n        return check_options\n    return update_docstring",
    "docstring": "Decorator that logs warnings when unpermitted options are passed into its\n    wrapped function.\n\n    Requires that wrapped function has an keyword-only argument named\n    `options`. If wrapped function has {options} in its docstring, fills in\n    with the docs for allowed options.\n\n    Args:\n        allowed (list str): list of option keys allowed. If the wrapped\n            function is called with an option not in allowed, log a warning.\n            All values in allowed must also be present in `defaults`.\n\n    Returns:\n        Wrapped function with options validation.\n\n    >>> @use_options(['title'])\n    ... def test(*, options={}): return options['title']\n\n    >>> test(options={'title': 'Hello'})\n    'Hello'\n\n    >>> # test(options={'not_allowed': 123}) # Also logs error message\n    ''"
  },
  {
    "code": "def validate(self, data):\n        if data is not None and not isinstance(data, dict):\n            raise serializers.ValidationError(\"Invalid data\")\n        try:\n            profiles = [ev[\"profile\"] for ev in data.get(\"encoded_videos\", [])]\n            if len(profiles) != len(set(profiles)):\n                raise serializers.ValidationError(\"Invalid data: duplicate profiles\")\n        except KeyError:\n            raise serializers.ValidationError(\"profile required for deserializing\")\n        except TypeError:\n            raise serializers.ValidationError(\"profile field needs to be a profile_name (str)\")\n        course_videos = [(course_video, image) for course_video, image in data.get('courses', []) if course_video]\n        data['courses'] = course_videos\n        return data",
    "docstring": "Check that the video data is valid."
  },
  {
    "code": "def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True,\n        cmap:str='tab20', alpha:float=0.5, **kwargs):\n        \"Show the `ImageSegment` on `ax`.\"\n        ax = show_image(self, ax=ax, hide_axis=hide_axis, cmap=cmap, figsize=figsize,\n                        interpolation='nearest', alpha=alpha, vmin=0)\n        if title: ax.set_title(title)",
    "docstring": "Show the `ImageSegment` on `ax`."
  },
  {
    "code": "def _remove_existing_jobs(data):\n    new_data = []\n    guids = [datum['job']['job_guid'] for datum in data]\n    state_map = {\n        guid: state for (guid, state) in Job.objects.filter(\n            guid__in=guids).values_list('guid', 'state')\n    }\n    for datum in data:\n        job = datum['job']\n        if not state_map.get(job['job_guid']):\n            new_data.append(datum)\n        else:\n            current_state = state_map[job['job_guid']]\n            if current_state == 'completed' or (\n                    job['state'] == 'pending' and\n                    current_state == 'running'):\n                continue\n            new_data.append(datum)\n    return new_data",
    "docstring": "Remove jobs from data where we already have them in the same state.\n\n    1. split the incoming jobs into pending, running and complete.\n    2. fetch the ``job_guids`` from the db that are in the same state as they\n       are in ``data``.\n    3. build a new list of jobs in ``new_data`` that are not already in\n       the db and pass that back.  It could end up empty at that point."
  },
  {
    "code": "def assign_agent_to_resource(self, agent_id, resource_id):\n        collection = JSONClientValidated('resource',\n                                         collection='Resource',\n                                         runtime=self._runtime)\n        resource = collection.find_one({'_id': ObjectId(resource_id.get_identifier())})\n        try:\n            ResourceAgentSession(\n                self._catalog_id, self._proxy, self._runtime).get_resource_by_agent(agent_id)\n        except errors.NotFound:\n            pass\n        else:\n            raise errors.AlreadyExists()\n        if 'agentIds' not in resource:\n            resource['agentIds'] = [str(agent_id)]\n        else:\n            resource['agentIds'].append(str(agent_id))\n        collection.save(resource)",
    "docstring": "Adds an existing ``Agent`` to a ``Resource``.\n\n        arg:    agent_id (osid.id.Id): the ``Id`` of the ``Agent``\n        arg:    resource_id (osid.id.Id): the ``Id`` of the ``Resource``\n        raise:  AlreadyExists - ``agent_id`` is already assigned to\n                ``resource_id``\n        raise:  NotFound - ``agent_id`` or ``resource_id`` not found\n        raise:  NullArgument - ``agent_id`` or ``resource_id`` is\n                ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def overlaps(self,junc,tolerance=0):\n    if not self.left.overlaps(junc.left,padding=tolerance): return False\n    if not self.right.overlaps(junc.right,padding=tolerance): return False\n    return True",
    "docstring": "see if junction overlaps with tolerance"
  },
  {
    "code": "def fig_to_src(figure, image_format='png', dpi=80):\n    if image_format == 'png':\n        f = io.BytesIO()\n        figure.savefig(f, format=image_format, dpi=dpi)\n        f.seek(0)\n        return png_to_src(f.read())\n    elif image_format == 'svg':\n        f = io.StringIO()\n        figure.savefig(f, format=image_format, dpi=dpi)\n        f.seek(0)\n        return svg_to_src(f.read())",
    "docstring": "Convert a matplotlib figure to an inline HTML image.\n\n    :param matplotlib.figure.Figure figure: Figure to display.\n    :param str image_format: png (default) or svg\n    :param int dpi: dots-per-inch for raster graphics.\n    :rtype: str"
  },
  {
    "code": "def get_dir_walker(recursive, topdown=True, followlinks=False):\n    if recursive:\n        walk = partial(os.walk, topdown=topdown, followlinks=followlinks)\n    else:\n        def walk(path, topdown=topdown, followlinks=followlinks):\n            try:\n                yield next(os.walk(path, topdown=topdown, followlinks=followlinks))\n            except NameError:\n                yield os.walk(path, topdown=topdown, followlinks=followlinks).next()\n    return walk",
    "docstring": "Returns a recursive or a non-recursive directory walker.\n\n    :param recursive:\n        ``True`` produces a recursive walker; ``False`` produces a non-recursive\n        walker.\n    :returns:\n        A walker function."
  },
  {
    "code": "def syscal_save_to_config_txt(filename, configs, spacing=1):\n    print('Number of measurements: ', configs.shape[0])\n    number_of_electrodes = configs.max().astype(int)\n    with open(filename, 'w') as fid:\n        _syscal_write_electrode_coords(fid, spacing, number_of_electrodes)\n        _syscal_write_quadpoles(fid, configs.astype(int))",
    "docstring": "Write configurations to a Syscal ascii file that can be read by the\n    Electre Pro program.\n\n    Parameters\n    ----------\n    filename: string\n        output filename\n    configs: numpy.ndarray\n        Nx4 array with measurement configurations A-B-M-N"
  },
  {
    "code": "def _bind(self):\n        self._bind_as(self.settings.BIND_DN, self.settings.BIND_PASSWORD, sticky=True)",
    "docstring": "Binds to the LDAP server with AUTH_LDAP_BIND_DN and\n        AUTH_LDAP_BIND_PASSWORD."
  },
  {
    "code": "def parameters(self, sequence, value_means, value_ranges, arrangement):\n        self._params['sequence'] = sequence\n        self._params['value_means'] = value_means\n        self._params['value_ranges'] = value_ranges\n        self._params['arrangement'] = arrangement\n        if any(x <= 0 for x in self._params['value_ranges']):\n            raise ValueError(\"range values must be greater than zero\")\n        self._params['variable_parameters'] = []\n        for i in range(len(self._params['value_means'])):\n            self._params['variable_parameters'].append(\n                \"\".join(['var', str(i)]))\n        if len(set(arrangement).intersection(\n                self._params['variable_parameters'])) != len(\n                    self._params['value_means']):\n            raise ValueError(\"argument mismatch!\")\n        if len(self._params['value_ranges']) != len(\n                self._params['value_means']):\n            raise ValueError(\"argument mismatch!\")",
    "docstring": "Relates the individual to be evolved to the full parameter string.\n\n        Parameters\n        ----------\n        sequence: str\n            Full amino acid sequence for specification object to be\n            optimized. Must be equal to the number of residues in the\n            model.\n        value_means: list\n            List containing mean values for parameters to be optimized.\n        value_ranges: list\n            List containing ranges for parameters to be optimized.\n            Values must be positive.\n        arrangement: list\n            Full list of fixed and variable parameters for model\n            building. Fixed values are the appropriate value. Values\n            to be varied should be listed as 'var0', 'var1' etc,\n            and must be in ascending numerical order.\n            Variables can be repeated if required."
  },
  {
    "code": "def get_calculated_display_values(self, immediate: bool=False) -> DisplayValues:\n        if not immediate or not self.__is_master or not self.__last_display_values:\n            if not self.__current_display_values and self.__data_item:\n                self.__current_display_values = DisplayValues(self.__data_item.xdata, self.sequence_index, self.collection_index, self.slice_center, self.slice_width, self.display_limits, self.complex_display_type, self.__color_map_data)\n                def finalize(display_values):\n                    self.__last_display_values = display_values\n                    self.display_values_changed_event.fire()\n                self.__current_display_values.on_finalize = finalize\n            return self.__current_display_values\n        return self.__last_display_values",
    "docstring": "Return the display values.\n\n        Return the current (possibly uncalculated) display values unless 'immediate' is specified.\n\n        If 'immediate', return the existing (calculated) values if they exist. Using the 'immediate' values\n        avoids calculation except in cases where the display values haven't already been calculated."
  },
  {
    "code": "def log(array, cutoff):\n    arr = numpy.copy(array)\n    arr[arr < cutoff] = cutoff\n    return numpy.log(arr)",
    "docstring": "Compute the logarithm of an array with a cutoff on the small values"
  },
  {
    "code": "def save(self, value, redis, *, commit=True):\n        value = self.prepare(value)\n        if value is not None:\n            redis.hset(self.obj.key(), self.name, value)\n        else:\n            redis.hdel(self.obj.key(), self.name)\n        if self.index:\n            key = self.key()\n            if self.name in self.obj._old:\n                redis.hdel(key, self.obj._old[self.name])\n            if value is not None:\n                redis.hset(key, value, self.obj.id)",
    "docstring": "Sets this fields value in the databse"
  },
  {
    "code": "def currentuser(self):\n        request = requests.get(\n            '{0}/api/v3/user'.format(self.host),\n            headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)\n        return request.json()",
    "docstring": "Returns the current user parameters. The current user is linked to the secret token\n\n        :return: a list with the current user properties"
  },
  {
    "code": "def system(self):\n        if self._base == 2:\n            return \"NIST\"\n        elif self._base == 10:\n            return \"SI\"\n        else:\n            raise ValueError(\"Instances mathematical base is an unsupported value: %s\" % (\n                str(self._base)))",
    "docstring": "The system of units used to measure an instance"
  },
  {
    "code": "def _set_overlay_verify(name, overlay_path, config_path):\n    global DEBUG\n    if os.path.exists(config_path):\n        print(\"Config path already exists! Not moving forward\")\n        print(\"config_path: {0}\".format(config_path))\n        return -1\n    os.makedirs(config_path)\n    with open(config_path + \"/dtbo\", 'wb') as outfile:\n        with open(overlay_path, 'rb') as infile:\n            shutil.copyfileobj(infile, outfile)\n    time.sleep(0.2)\n    if name == \"CUST\":\n        return 0\n    elif name == \"PWM0\":\n        if os.path.exists(PWMSYSFSPATH):\n            if DEBUG:\n                print(\"PWM IS LOADED!\")\n            return 0\n        else:\n            if DEBUG:\n                print(\"ERROR LOAIDNG PWM0\")\n            return 1\n    elif name == \"SPI2\":\n        if os.listdir(SPI2SYSFSPATH) != \"\":\n            if DEBUG:\n                print(\"SPI2 IS LOADED!\")\n            return 0\n        else:\n            if DEBUG:\n                print(\"ERROR LOADING SPI2\")\n            return 0",
    "docstring": "_set_overlay_verify - Function to load the overlay and verify it was setup properly"
  },
  {
    "code": "def disengage(self):\n        if self._driver and self._driver.is_connected():\n            self._driver.home()\n            self._engaged = False",
    "docstring": "Home the magnet"
  },
  {
    "code": "def add(self, properties):\n        new_nic = super(FakedNicManager, self).add(properties)\n        partition = self.parent\n        if 'virtual-switch-uri' in new_nic.properties:\n            vswitch_uri = new_nic.properties['virtual-switch-uri']\n            try:\n                vswitch = self.hmc.lookup_by_uri(vswitch_uri)\n            except KeyError:\n                raise InputError(\"The virtual switch specified in the \"\n                                 \"'virtual-switch-uri' property does not \"\n                                 \"exist: {!r}\".format(vswitch_uri))\n            connected_uris = vswitch.properties['connected-vnic-uris']\n            if new_nic.uri not in connected_uris:\n                connected_uris.append(new_nic.uri)\n        if 'device-number' not in new_nic.properties:\n            devno = partition.devno_alloc()\n            new_nic.properties['device-number'] = devno\n        assert 'nic-uris' in partition.properties\n        partition.properties['nic-uris'].append(new_nic.uri)\n        return new_nic",
    "docstring": "Add a faked NIC resource.\n\n        Parameters:\n\n          properties (dict):\n            Resource properties.\n\n            Special handling and requirements for certain properties:\n\n            * 'element-id' will be auto-generated with a unique value across\n              all instances of this resource type, if not specified.\n            * 'element-uri' will be auto-generated based upon the element ID,\n              if not specified.\n            * 'class' will be auto-generated to 'nic',\n              if not specified.\n            * Either 'network-adapter-port-uri' (for backing ROCE adapters) or\n              'virtual-switch-uri'(for backing OSA or Hipersockets adapters) is\n              required to be specified.\n            * 'device-number' will be auto-generated with a unique value\n              within the partition in the range 0x8000 to 0xFFFF, if not\n              specified.\n\n            This method also updates the 'nic-uris' property in the parent\n            faked Partition resource, by adding the URI for the faked NIC\n            resource.\n\n            This method also updates the 'connected-vnic-uris' property in the\n            virtual switch referenced by 'virtual-switch-uri' property,\n            and sets it to the URI of the faked NIC resource.\n\n        Returns:\n          :class:`zhmcclient_mock.FakedNic`: The faked NIC resource.\n\n        Raises:\n          :exc:`zhmcclient_mock.InputError`: Some issue with the input\n            properties."
  },
  {
    "code": "def process(self, metric):\n        for rule in self.rules:\n            rule.process(metric, self)",
    "docstring": "process a single metric\n        @type metric: diamond.metric.Metric\n        @param metric: metric to process\n        @rtype None"
  },
  {
    "code": "def memory(self):\n        class GpuMemoryInfo(Structure):\n            _fields_ = [\n                ('total', c_ulonglong),\n                ('free', c_ulonglong),\n                ('used', c_ulonglong),\n            ]\n        c_memory = GpuMemoryInfo()\n        _check_return(_NVML.get_function(\n            \"nvmlDeviceGetMemoryInfo\")(self.hnd, byref(c_memory)))\n        return {'total': c_memory.total, 'free': c_memory.free, 'used': c_memory.used}",
    "docstring": "Memory information in bytes\n\n        Example:\n\n            >>> print(ctx.device(0).memory())\n            {'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L}\n\n        Returns:\n            total/used/free memory in bytes"
  },
  {
    "code": "def floating_ip_disassociate(self, server_name, floating_ip):\n        nt_ks = self.compute_conn\n        server_ = self.server_by_name(server_name)\n        server = nt_ks.servers.get(server_.__dict__['id'])\n        server.remove_floating_ip(floating_ip)\n        return self.floating_ip_list()[floating_ip]",
    "docstring": "Disassociate a floating IP from server\n\n        .. versionadded:: 2016.3.0"
  },
  {
    "code": "def cli(env, identifier, name, all, note):\n    vsi = SoftLayer.VSManager(env.client)\n    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')\n    capture = vsi.capture(vs_id, name, all, note)\n    table = formatting.KeyValueTable(['name', 'value'])\n    table.align['name'] = 'r'\n    table.align['value'] = 'l'\n    table.add_row(['vs_id', capture['guestId']])\n    table.add_row(['date', capture['createDate'][:10]])\n    table.add_row(['time', capture['createDate'][11:19]])\n    table.add_row(['transaction', formatting.transaction_status(capture)])\n    table.add_row(['transaction_id', capture['id']])\n    table.add_row(['all_disks', all])\n    env.fout(table)",
    "docstring": "Capture one or all disks from a virtual server to a SoftLayer image."
  },
  {
    "code": "def get_FORCE_SETS_lines(dataset, forces=None):\n    if 'first_atoms' in dataset:\n        return _get_FORCE_SETS_lines_type1(dataset, forces=forces)\n    elif 'forces' in dataset:\n        return _get_FORCE_SETS_lines_type2(dataset)",
    "docstring": "Generate FORCE_SETS string\n\n    See the format of dataset in the docstring of\n    Phonopy.set_displacement_dataset. Optionally for the type-1 (traditional)\n    format, forces can be given. In this case, sets of forces are\n    unnecessary to be stored in the dataset."
  },
  {
    "code": "def datasets(data = 'all', type = None, uuid = None, query = None, id = None,\n\t\t\t\t\t\t\tlimit = 100, offset = None, **kwargs):\n\targs = {'q': query, 'type': type, 'limit': limit, 'offset': offset}\n\tdata_choices = ['all', 'organization', 'contact', 'endpoint',\n\t\t\t\t\t\t\t\t\t'identifier', 'tag', 'machinetag', 'comment',\n\t\t\t\t\t\t\t\t\t'constituents', 'document', 'metadata', 'deleted',\n\t\t\t\t\t\t\t\t\t'duplicate', 'subDataset', 'withNoEndpoint']\n\tcheck_data(data, data_choices)\n\tif len2(data) ==1:\n\t\treturn datasets_fetch(data, uuid, args, **kwargs)\n\telse:\n\t\treturn [datasets_fetch(x, uuid, args, **kwargs) for x in data]",
    "docstring": "Search for datasets and dataset metadata.\n\n\t:param data: [str] The type of data to get. Default: ``all``\n\t:param type: [str] Type of dataset, options include ``OCCURRENCE``, etc.\n\t:param uuid: [str] UUID of the data node provider. This must be specified if data\n\t\t is anything other than ``all``.\n\t:param query: [str] Query term(s). Only used when ``data = 'all'``\n\t:param id: [int] A metadata document id.\n\n\tReferences http://www.gbif.org/developer/registry#datasets\n\n\tUsage::\n\n\t\t\tfrom pygbif import registry\n\t\t\tregistry.datasets(limit=5)\n\t\t\tregistry.datasets(type=\"OCCURRENCE\")\n\t\t\tregistry.datasets(uuid=\"a6998220-7e3a-485d-9cd6-73076bd85657\")\n\t\t\tregistry.datasets(data='contact', uuid=\"a6998220-7e3a-485d-9cd6-73076bd85657\")\n\t\t\tregistry.datasets(data='metadata', uuid=\"a6998220-7e3a-485d-9cd6-73076bd85657\")\n\t\t\tregistry.datasets(data='metadata', uuid=\"a6998220-7e3a-485d-9cd6-73076bd85657\", id=598)\n\t\t\tregistry.datasets(data=['deleted','duplicate'])\n\t\t\tregistry.datasets(data=['deleted','duplicate'], limit=1)"
  },
  {
    "code": "def popen_multiple(commands, command_args, *args, **kwargs):\n    for i, command in enumerate(commands):\n        cmd = [command] + command_args\n        try:\n            return subprocess.Popen(cmd, *args, **kwargs)\n        except OSError:\n            if i == len(commands) - 1:\n                raise",
    "docstring": "Like `subprocess.Popen`, but can try multiple commands in case\n    some are not available.\n\n    `commands` is an iterable of command names and `command_args` are\n    the rest of the arguments that, when appended to the command name,\n    make up the full first argument to `subprocess.Popen`. The\n    other positional and keyword arguments are passed through."
  },
  {
    "code": "def setup(app):\n    app.add_domain(EverettDomain)\n    app.add_directive('autocomponent', AutoComponentDirective)\n    return {\n        'version': __version__,\n        'parallel_read_safe': True,\n        'parallel_write_safe': True\n    }",
    "docstring": "Register domain and directive in Sphinx."
  },
  {
    "code": "def received_new(self, msg):\n        logger.info(\"Receiving msg, delivering to Lamson...\")\n        logger.debug(\"Relaying msg to lamson: From: %s, To: %s\",\n                     msg['From'], msg['To'])\n        self._relay.deliver(msg)",
    "docstring": "As new messages arrive, deliver them to the lamson relay."
  },
  {
    "code": "def salt_call():\n    import salt.cli.call\n    if '' in sys.path:\n        sys.path.remove('')\n    client = salt.cli.call.SaltCall()\n    _install_signal_handlers(client)\n    client.run()",
    "docstring": "Directly call a salt command in the modules, does not require a running\n    salt minion to run."
  },
  {
    "code": "def read(self, filename):\n        try:\n            with open(filename, 'r') as _file:\n                self._filename = filename\n                self.readstream(_file)\n            return True\n        except IOError:\n            self._filename = None\n            return False",
    "docstring": "Reads the file specified and tokenizes the data for parsing."
  },
  {
    "code": "def integrate_fluxes(self):\n        fluxes = self.sequences.fluxes\n        for flux in fluxes.numerics:\n            points = getattr(fluxes.fastaccess, '_%s_points' % flux.name)\n            coefs = self.numconsts.a_coefs[self.numvars.idx_method-1,\n                                           self.numvars.idx_stage,\n                                           :self.numvars.idx_method]\n            flux(self.numvars.dt *\n                 numpy.dot(coefs, points[:self.numvars.idx_method]))",
    "docstring": "Perform a dot multiplication between the fluxes and the\n        A coefficients associated with the different stages of the\n        actual method.\n\n        >>> from hydpy.models.test_v1 import *\n        >>> parameterstep()\n        >>> model.numvars.idx_method = 2\n        >>> model.numvars.idx_stage = 1\n        >>> model.numvars.dt = 0.5\n        >>> points = numpy.asarray(fluxes.fastaccess._q_points)\n        >>> points[:4] = 15., 2., -999., 0.\n        >>> model.integrate_fluxes()\n        >>> from hydpy import round_\n        >>> from hydpy import pub\n        >>> round_(numpy.asarray(model.numconsts.a_coefs)[1, 1, :2])\n        0.375, 0.125\n        >>> fluxes.q\n        q(2.9375)"
  },
  {
    "code": "def put(self, key, value, format=None, append=False, **kwargs):\n        if format is None:\n            format = get_option(\"io.hdf.default_format\") or 'fixed'\n        kwargs = self._validate_format(format, kwargs)\n        self._write_to_group(key, value, append=append, **kwargs)",
    "docstring": "Store object in HDFStore\n\n        Parameters\n        ----------\n        key      : object\n        value    : {Series, DataFrame}\n        format   : 'fixed(f)|table(t)', default is 'fixed'\n            fixed(f) : Fixed format\n                       Fast writing/reading. Not-appendable, nor searchable\n            table(t) : Table format\n                       Write as a PyTables Table structure which may perform\n                       worse but allow more flexible operations like searching\n                       / selecting subsets of the data\n        append   : boolean, default False\n            This will force Table format, append the input data to the\n            existing.\n        data_columns : list of columns to create as data columns, or True to\n            use all columns. See\n            `here <http://pandas.pydata.org/pandas-docs/stable/io.html#query-via-data-columns>`__ # noqa\n        encoding : default None, provide an encoding for strings\n        dropna   : boolean, default False, do not write an ALL nan row to\n            the store settable by the option 'io.hdf.dropna_table'"
  },
  {
    "code": "def _get_logging_id(self):\n        return \"{}.{}/{}\".format(\n            self._request.viewset_class.__module__,\n            self._request.viewset_class.__name__,\n            self._request.viewset_method,\n        )",
    "docstring": "Get logging identifier."
  },
  {
    "code": "def select_token(request, scopes='', new=False):\n    @tokens_required(scopes=scopes, new=new)\n    def _token_list(r, tokens):\n        context = {\n            'tokens': tokens,\n            'base_template': app_settings.ESI_BASE_TEMPLATE,\n        }\n        return render(r, 'esi/select_token.html', context=context)\n    return _token_list(request)",
    "docstring": "Presents the user with a selection of applicable tokens for the requested view."
  },
  {
    "code": "def is_format_selected(image_format, formats, progs):\n    intersection = formats & Settings.formats\n    mode = _is_program_selected(progs)\n    result = (image_format in intersection) and mode\n    return result",
    "docstring": "Determine if the image format is selected by command line arguments."
  },
  {
    "code": "def validate(config):\n    if not isinstance(config, list):\n        return False, 'Configuration for napalm beacon must be a list.'\n    for mod in config:\n        fun = mod.keys()[0]\n        fun_cfg = mod.values()[0]\n        if not isinstance(fun_cfg, dict):\n            return False, 'The match structure for the {} execution function output must be a dictionary'.format(fun)\n        if fun not in __salt__:\n            return False, 'Execution function {} is not availabe!'.format(fun)\n    return True, 'Valid configuration for the napal beacon!'",
    "docstring": "Validate the beacon configuration."
  },
  {
    "code": "def truncate_rows(A, nz_per_row):\n    if not isspmatrix(A):\n        raise ValueError(\"Sparse matrix input needed\")\n    if isspmatrix_bsr(A):\n        blocksize = A.blocksize\n    if isspmatrix_csr(A):\n        A = A.copy()\n    Aformat = A.format\n    A = A.tocsr()\n    nz_per_row = int(nz_per_row)\n    pyamg.amg_core.truncate_rows_csr(A.shape[0], nz_per_row, A.indptr,\n                                     A.indices, A.data)\n    A.eliminate_zeros()\n    if Aformat == 'bsr':\n        A = A.tobsr(blocksize)\n    else:\n        A = A.asformat(Aformat)\n    return A",
    "docstring": "Truncate the rows of A by keeping only the largest in magnitude entries in each row.\n\n    Parameters\n    ----------\n    A : sparse_matrix\n\n    nz_per_row : int\n        Determines how many entries in each row to keep\n\n    Returns\n    -------\n    A : sparse_matrix\n        Each row has been truncated to at most nz_per_row entries\n\n    Examples\n    --------\n    >>> from pyamg.gallery import poisson\n    >>> from pyamg.util.utils import truncate_rows\n    >>> from scipy import array\n    >>> from scipy.sparse import csr_matrix\n    >>> A = csr_matrix( array([[-0.24, -0.5 ,  0.  ,  0.  ],\n    ...                        [ 1.  , -1.1 ,  0.49,  0.1 ],\n    ...                        [ 0.  ,  0.4 ,  1.  ,  0.5 ]])  )\n    >>> truncate_rows(A, 2).todense()\n    matrix([[-0.24, -0.5 ,  0.  ,  0.  ],\n            [ 1.  , -1.1 ,  0.  ,  0.  ],\n            [ 0.  ,  0.  ,  1.  ,  0.5 ]])"
  },
  {
    "code": "def difference(self, other):\n        if not self.is_valid_range(other):\n            msg = \"Unsupported type to test for difference '{.__class__.__name__}'\"\n            raise TypeError(msg.format(other))\n        if not self or not other or not self.overlap(other):\n            return self\n        elif self in other:\n            return self.empty()\n        elif other in self and not (self.startswith(other) or self.endswith(other)):\n            raise ValueError(\"Other range must not be within this range\")\n        elif self.endsbefore(other):\n            return self.replace(upper=other.lower, upper_inc=not other.lower_inc)\n        elif self.startsafter(other):\n            return self.replace(lower=other.upper, lower_inc=not other.upper_inc)\n        else:\n            return self.empty()",
    "docstring": "Compute the difference between this and a given range.\n\n            >>> intrange(1, 10).difference(intrange(10, 15))\n            intrange([1,10))\n            >>> intrange(1, 10).difference(intrange(5, 10))\n            intrange([1,5))\n            >>> intrange(1, 5).difference(intrange(5, 10))\n            intrange([1,5))\n            >>> intrange(1, 5).difference(intrange(1, 10))\n            intrange(empty)\n\n        The difference can not be computed if the resulting range would be split\n        in two separate ranges. This happens when the given range is completely\n        within this range and does not start or end at the same value.\n\n            >>> intrange(1, 15).difference(intrange(5, 10))\n            Traceback (most recent call last):\n              File \"<stdin>\", line 1, in <module>\n            ValueError: Other range must not be within this range\n\n        This does not modify the range in place.\n\n        This is the same as the ``-`` operator for two ranges in PostgreSQL.\n\n        :param other: Range to difference against.\n        :return: A new range that is the difference between this and `other`.\n        :raises ValueError: If difference bethween this and `other` can not be\n                            computed."
  },
  {
    "code": "def get_backend_path(service):\n    for backend in _get_backends():\n        try:\n            if backend.service_allowed(service):\n                return \"%s.%s\" % (backend.__class__.__module__, backend.__class__.__name__)\n        except AttributeError:\n            raise NotImplementedError(\"%s.%s.service_allowed() not implemented\" % (\n                backend.__class__.__module__, backend.__class__.__name__)\n            )\n    return None",
    "docstring": "Return the dotted path of the matching backend."
  },
  {
    "code": "def setup_webserver():\n    run('sudo apt-get update')\n    install_packages(packages_webserver)\n    execute(custom.latex)\n    execute(setup.solarized)\n    execute(setup.vim)\n    execute(setup.tmux)\n    checkup_git_repo_legacy(url='git@github.com:letsencrypt/letsencrypt.git')\n    execute(setup.service.fdroid)\n    execute(setup.service.owncloud)\n    from fabfile import dfh, check_reboot\n    dfh()\n    check_reboot()",
    "docstring": "Run setup tasks to set up a nicely configured webserver.\n\n    Features:\n     * owncloud service\n     * fdroid repository\n     * certificates via letsencrypt\n     * and more\n\n    The task is defined in file fabsetup_custom/fabfile_addtitions/__init__.py\n    and could be customized by Your own needs.  More info: README.md"
  },
  {
    "code": "def _from_string(cls, serialized):\n        course_key = CourseLocator._from_string(serialized)\n        parsed_parts = cls.parse_url(serialized)\n        block_id = parsed_parts.get('block_id', None)\n        if block_id is None:\n            raise InvalidKeyError(cls, serialized)\n        return cls(course_key, parsed_parts.get('block_type'), block_id)",
    "docstring": "Requests CourseLocator to deserialize its part and then adds the local deserialization of block"
  },
  {
    "code": "def create(cls, name, frame_type='eth2', value1=None, comment=None):\n        json = {'frame_type': frame_type,\n                'name': name,\n                'value1': int(value1, 16),\n                'comment': comment}\n        return ElementCreator(cls, json)",
    "docstring": "Create an ethernet service\n\n        :param str name: name of service\n        :param str frame_type: ethernet frame type, eth2\n        :param str value1: hex code representing ethertype field\n        :param str comment: optional comment\n        :raises CreateElementFailed: failure creating element with reason\n        :return: instance with meta\n        :rtype: EthernetService"
  },
  {
    "code": "def register_event(self, *names):\n        for name in names:\n            if name in self.__events:\n                continue\n            self.__events[name] = Event(name)",
    "docstring": "Registers new events after instance creation\n\n        Args:\n            *names (str): Name or names of the events to register"
  },
  {
    "code": "def is_absolute(self):\n        return self.namespace and self.ext and self.scheme and self.path",
    "docstring": "Validates that uri contains all parts except version"
  },
  {
    "code": "def pop(self, option, default=None):\n        val = self[option]\n        del self[option]\n        return (val is None and default) or val",
    "docstring": "Just like `dict.pop`"
  },
  {
    "code": "def get_downsample_pct(in_bam, target_counts, data):\n    total = sum(x.aligned for x in idxstats(in_bam, data))\n    with pysam.Samfile(in_bam, \"rb\") as work_bam:\n        n_rgs = max(1, len(work_bam.header.get(\"RG\", [])))\n    rg_target = n_rgs * target_counts\n    if total > rg_target:\n        pct = float(rg_target) / float(total)\n        if pct < 0.9:\n            return pct",
    "docstring": "Retrieve percentage of file to downsample to get to target counts.\n\n    Avoids minimal downsample which is not especially useful for\n    improving QC times; 90& or more of reads."
  },
  {
    "code": "def kinematic_flux(vel, b, perturbation=False, axis=-1):\n    r\n    kf = np.mean(vel * b, axis=axis)\n    if not perturbation:\n        kf -= np.mean(vel, axis=axis) * np.mean(b, axis=axis)\n    return np.atleast_1d(kf)",
    "docstring": "r\"\"\"Compute the kinematic flux from two time series.\n\n    Compute the kinematic flux from the time series of two variables `vel`\n    and b. Note that to be a kinematic flux, at least one variable must be\n    a component of velocity.\n\n    Parameters\n    ----------\n    vel : array_like\n        A component of velocity\n\n    b : array_like\n        May be a component of velocity or a scalar variable (e.g. Temperature)\n\n    perturbation : bool, optional\n        `True` if the `vel` and `b` variables are perturbations. If `False`, perturbations\n        will be calculated by removing the mean value from each variable. Defaults to `False`.\n\n    Returns\n    -------\n    array_like\n        The corresponding kinematic flux\n\n    Other Parameters\n    ----------------\n    axis : int, optional\n           The index of the time axis, along which the calculations will be\n           performed. Defaults to -1\n\n    Notes\n    -----\n    A kinematic flux is computed as\n\n    .. math:: \\overline{u^{\\prime} s^{\\prime}}\n\n    where at the prime notation denotes perturbation variables, and at least\n    one variable is perturbation velocity. For example, the vertical kinematic\n    momentum flux (two velocity components):\n\n    .. math:: \\overline{u^{\\prime} w^{\\prime}}\n\n    or the vertical kinematic heat flux (one velocity component, and one\n    scalar):\n\n    .. math:: \\overline{w^{\\prime} T^{\\prime}}\n\n    If perturbation variables are passed into this function (i.e.\n    `perturbation` is True), the kinematic flux is computed using the equation\n    above.\n\n    However, the equation above can be rewritten as\n\n    .. math:: \\overline{us} - \\overline{u}~\\overline{s}\n\n    which is computationally more efficient. This is how the kinematic flux\n    is computed in this function if `perturbation` is False.\n\n    For more information on the subject, please see [Garratt1994]_."
  },
  {
    "code": "def remove_data_flows_with_data_port_id(self, data_port_id):\n        if not self.is_root_state and not self.is_root_state_of_library:\n            data_flow_ids_to_remove = []\n            for data_flow_id, data_flow in self.parent.data_flows.items():\n                if data_flow.from_state == self.state_id and data_flow.from_key == data_port_id or \\\n                                        data_flow.to_state == self.state_id and data_flow.to_key == data_port_id:\n                    data_flow_ids_to_remove.append(data_flow_id)\n            for data_flow_id in data_flow_ids_to_remove:\n                self.parent.remove_data_flow(data_flow_id)\n        data_flow_ids_to_remove = []\n        for data_flow_id, data_flow in self.data_flows.items():\n            if data_flow.from_state == self.state_id and data_flow.from_key == data_port_id or \\\n                                    data_flow.to_state == self.state_id and data_flow.to_key == data_port_id:\n                data_flow_ids_to_remove.append(data_flow_id)\n        for data_flow_id in data_flow_ids_to_remove:\n            self.remove_data_flow(data_flow_id)",
    "docstring": "Remove an data ports whose from_key or to_key equals the passed data_port_id\n\n        :param int data_port_id: the id of a data_port of which all data_flows should be removed, the id can be a input or\n                            output data port id"
  },
  {
    "code": "def dummy_image(filetype='gif'):\n    GIF = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'\n    tmp_file = tempfile.NamedTemporaryFile(suffix='.%s' % filetype)\n    tmp_file.write(base64.b64decode(GIF))\n    return open(tmp_file.name, 'rb')",
    "docstring": "Generate empty image in temporary file for testing"
  },
  {
    "code": "def phi( n ):\n  assert isinstance( n, integer_types )\n  if n < 3: return 1\n  result = 1\n  ff = factorization( n )\n  for f in ff:\n    e = f[1]\n    if e > 1:\n      result = result * f[0] ** (e-1) * ( f[0] - 1 )\n    else:\n      result = result * ( f[0] - 1 )\n  return result",
    "docstring": "Return the Euler totient function of n."
  },
  {
    "code": "def SetDecryptedStreamSize(self, decrypted_stream_size):\n    if self._is_open:\n      raise IOError('Already open.')\n    if decrypted_stream_size < 0:\n      raise ValueError((\n          'Invalid decrypted stream size: {0:d} value out of '\n          'bounds.').format(decrypted_stream_size))\n    self._decrypted_stream_size = decrypted_stream_size",
    "docstring": "Sets the decrypted stream size.\n\n    This function is used to set the decrypted stream size if it can be\n    determined separately.\n\n    Args:\n      decrypted_stream_size (int): size of the decrypted stream in bytes.\n\n    Raises:\n      IOError: if the file-like object is already open.\n      OSError: if the file-like object is already open.\n      ValueError: if the decrypted stream size is invalid."
  },
  {
    "code": "def register_magnitude_model(self, pid):\n        if self.assignments['forward_model'] is None:\n            self.assignments['forward_model'] = [None, None]\n        self.assignments['forward_model'][0] = pid",
    "docstring": "Set a given parameter model to the forward magnitude model"
  },
  {
    "code": "def get(self):\n        email = {}\n        if self.name is not None:\n            email[\"name\"] = self.name\n        if self.email is not None:\n            email[\"email\"] = self.email\n        return email",
    "docstring": "Get a JSON-ready representation of this Email.\n\n        :returns: This Email, ready for use in a request body.\n        :rtype: dict"
  },
  {
    "code": "def iscomplex(polynomial):\n    if isinstance(polynomial, (int, float)):\n        return False\n    if isinstance(polynomial, complex):\n        return True\n    polynomial = polynomial.expand()\n    for monomial in polynomial.as_coefficients_dict():\n        for variable in monomial.as_coeff_mul()[1]:\n            if isinstance(variable, complex) or variable == I:\n                return True\n    return False",
    "docstring": "Returns whether the polynomial has complex coefficients\n\n    :param polynomial: Polynomial of noncommutive variables.\n    :type polynomial: :class:`sympy.core.expr.Expr`.\n\n    :returns: bool -- whether there is a complex coefficient."
  },
  {
    "code": "def query_string_parser(search_pattern):\n    if not hasattr(current_oaiserver, 'query_parser'):\n        query_parser = current_app.config['OAISERVER_QUERY_PARSER']\n        if isinstance(query_parser, six.string_types):\n            query_parser = import_string(query_parser)\n        current_oaiserver.query_parser = query_parser\n    return current_oaiserver.query_parser('query_string', query=search_pattern)",
    "docstring": "Elasticsearch query string parser."
  },
  {
    "code": "def prepare_request_uri(self, uri, redirect_uri=None, scope=None,\n                            state=None, **kwargs):\n        return prepare_grant_uri(uri, self.client_id, self.response_type,\n                                 redirect_uri=redirect_uri, state=state, scope=scope, **kwargs)",
    "docstring": "Prepare the implicit grant request URI.\n\n        The client constructs the request URI by adding the following\n        parameters to the query component of the authorization endpoint URI\n        using the \"application/x-www-form-urlencoded\" format, per `Appendix B`_:\n\n        :param redirect_uri:  OPTIONAL. The redirect URI must be an absolute URI\n                              and it should have been registerd with the OAuth\n                              provider prior to use. As described in `Section 3.1.2`_.\n\n        :param scope:  OPTIONAL. The scope of the access request as described by\n                       Section 3.3`_. These may be any string but are commonly\n                       URIs or various categories such as ``videos`` or ``documents``.\n\n        :param state:   RECOMMENDED.  An opaque value used by the client to maintain\n                        state between the request and callback.  The authorization\n                        server includes this value when redirecting the user-agent back\n                        to the client.  The parameter SHOULD be used for preventing\n                        cross-site request forgery as described in `Section 10.12`_.\n\n        :param kwargs:  Extra arguments to include in the request URI.\n\n        In addition to supplied parameters, OAuthLib will append the ``client_id``\n        that was provided in the constructor as well as the mandatory ``response_type``\n        argument, set to ``token``::\n\n            >>> from oauthlib.oauth2 import MobileApplicationClient\n            >>> client = MobileApplicationClient('your_id')\n            >>> client.prepare_request_uri('https://example.com')\n            'https://example.com?client_id=your_id&response_type=token'\n            >>> client.prepare_request_uri('https://example.com', redirect_uri='https://a.b/callback')\n            'https://example.com?client_id=your_id&response_type=token&redirect_uri=https%3A%2F%2Fa.b%2Fcallback'\n            >>> client.prepare_request_uri('https://example.com', scope=['profile', 'pictures'])\n            'https://example.com?client_id=your_id&response_type=token&scope=profile+pictures'\n            >>> client.prepare_request_uri('https://example.com', foo='bar')\n            'https://example.com?client_id=your_id&response_type=token&foo=bar'\n\n        .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B\n        .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2\n        .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2\n        .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3\n        .. _`Section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12"
  },
  {
    "code": "def save_as_nifti_file(data: np.ndarray, affine: np.ndarray,\n                       path: Union[str, Path]) -> None:\n    if not isinstance(path, str):\n        path = str(path)\n    img = Nifti1Pair(data, affine)\n    nib.nifti1.save(img, path)",
    "docstring": "Create a Nifti file and save it.\n\n    Parameters\n    ----------\n    data\n        Brain data.\n    affine\n        Affine of the image, usually inherited from an existing image.\n    path\n        Output filename."
  },
  {
    "code": "def create_or_update_group_by_name(self, name, group_type=\"internal\", metadata=None, policies=None, member_group_ids=None,\n                                       member_entity_ids=None, mount_point=DEFAULT_MOUNT_POINT):\n        if metadata is None:\n            metadata = {}\n        if not isinstance(metadata, dict):\n            error_msg = 'unsupported metadata argument provided \"{arg}\" ({arg_type}), required type: dict\"'\n            raise exceptions.ParamValidationError(error_msg.format(\n                arg=metadata,\n                arg_type=type(metadata),\n            ))\n        if group_type not in ALLOWED_GROUP_TYPES:\n            error_msg = 'unsupported group_type argument provided \"{arg}\", allowed values: ({allowed_values})'\n            raise exceptions.ParamValidationError(error_msg.format(\n                arg=group_type,\n                allowed_values=ALLOWED_GROUP_TYPES,\n            ))\n        params = {\n            'type': group_type,\n            'metadata': metadata,\n            'policies': policies,\n            'member_group_ids': member_group_ids,\n            'member_entity_ids': member_entity_ids,\n        }\n        api_path = '/v1/{mount_point}/group/name/{name}'.format(\n            mount_point=mount_point,\n            name=name,\n        )\n        response = self._adapter.post(\n            url=api_path,\n            json=params,\n        )\n        return response",
    "docstring": "Create or update a group by its name.\n\n        Supported methods:\n            POST: /{mount_point}/group/name/{name}. Produces: 200 application/json\n\n        :param name: Name of the group.\n        :type name: str | unicode\n        :param group_type: Type of the group, internal or external. Defaults to internal.\n        :type group_type: str | unicode\n        :param metadata: Metadata to be associated with the group.\n        :type metadata: dict\n        :param policies: Policies to be tied to the group.\n        :type policies: str | unicode\n        :param member_group_ids: Group IDs to be assigned as group members.\n        :type member_group_ids: str | unicode\n        :param member_entity_ids: Entity IDs to be assigned as group members.\n        :type member_entity_ids: str | unicode\n        :param mount_point: The \"path\" the method/backend was mounted on.\n        :type mount_point: str | unicode\n        :return: The response of the request.\n        :rtype: requests.Response"
  },
  {
    "code": "def human_size_to_bytes(human_size):\n    size_exp_map = {'K': 1, 'M': 2, 'G': 3, 'T': 4, 'P': 5}\n    human_size_str = six.text_type(human_size)\n    match = re.match(r'^(\\d+)([KMGTP])?$', human_size_str)\n    if not match:\n        raise ValueError(\n            'Size must be all digits, with an optional unit type '\n            '(K, M, G, T, or P)'\n        )\n    size_num = int(match.group(1))\n    unit_multiplier = 1024 ** size_exp_map.get(match.group(2), 0)\n    return size_num * unit_multiplier",
    "docstring": "Convert human-readable units to bytes"
  },
  {
    "code": "def qset(self, name, index, value):\n        index = get_integer('index', index)        \n        return self.execute_command('qset', name, index, value)",
    "docstring": "Set the list element at ``index`` to ``value``. \n\n        :param string name: the queue name\n        :param int index: the specified index, can < 0\n        :param string value: the element value\n        :return: Unknown\n        :rtype: True"
  },
  {
    "code": "def _save_states(self, state, serialized_readers_entity):\n    mr_id = state.key().id_or_name()\n    fresh_state = model.MapreduceState.get_by_job_id(mr_id)\n    if not self._check_mr_state(fresh_state, mr_id):\n      return False\n    if fresh_state.active_shards != 0:\n      logging.warning(\n          \"Mapreduce %s already has active shards. Looks like spurious task \"\n          \"execution.\", mr_id)\n      return None\n    config = util.create_datastore_write_config(state.mapreduce_spec)\n    db.put([state, serialized_readers_entity], config=config)\n    return True",
    "docstring": "Run transaction to save state.\n\n    Args:\n      state: a model.MapreduceState entity.\n      serialized_readers_entity: a model._HugeTaskPayload entity containing\n        json serialized input readers.\n\n    Returns:\n      False if a fatal error is encountered and this task should be dropped\n    immediately. True if transaction is successful. None if a previous\n    attempt of this same transaction has already succeeded."
  },
  {
    "code": "def get_default_version(env):\n    if 'MSVS' not in env or not SCons.Util.is_Dict(env['MSVS']):\n        versions = [vs.version for vs in get_installed_visual_studios()]\n        env['MSVS'] = {'VERSIONS' : versions}\n    else:\n        versions = env['MSVS'].get('VERSIONS', [])\n    if 'MSVS_VERSION' not in env:\n        if versions:\n            env['MSVS_VERSION'] = versions[0]\n        else:\n            debug('get_default_version: WARNING: no installed versions found, '\n                  'using first in SupportedVSList (%s)'%SupportedVSList[0].version)\n            env['MSVS_VERSION'] = SupportedVSList[0].version\n    env['MSVS']['VERSION'] = env['MSVS_VERSION']\n    return env['MSVS_VERSION']",
    "docstring": "Returns the default version string to use for MSVS.\n\n    If no version was requested by the user through the MSVS environment\n    variable, query all the available visual studios through\n    get_installed_visual_studios, and take the highest one.\n\n    Return\n    ------\n    version: str\n        the default version."
  },
  {
    "code": "def _setBatchSystemEnvVars(self):\n        for envDict in (self._jobStore.getEnv(), self.config.environment):\n            for k, v in iteritems(envDict):\n                self._batchSystem.setEnv(k, v)",
    "docstring": "Sets the environment variables required by the job store and those passed on command line."
  },
  {
    "code": "def contains(self, order, cell, include_smaller=False):\n        order = self._validate_order(order)\n        cell = self._validate_cell(order, cell)\n        return self._compare_operation(order, cell, include_smaller, 'check')",
    "docstring": "Test whether the MOC contains the given cell.\n\n        If the include_smaller argument is true then the MOC is considered\n        to include a cell if it includes part of that cell (at a higher\n        order).\n\n        >>> m = MOC(1, (5,))\n        >>> m.contains(0, 0)\n        False\n        >>> m.contains(0, 1, True)\n        True\n        >>> m.contains(0, 1, False)\n        False\n        >>> m.contains(1, 4)\n        False\n        >>> m.contains(1, 5)\n        True\n        >>> m.contains(2, 19)\n        False\n        >>> m.contains(2, 21)\n        True"
  },
  {
    "code": "def iter_entry_points(self, group, name=None):\n        return (\n            entry\n            for dist in self\n            for entry in dist.get_entry_map(group).values()\n            if name is None or name == entry.name\n        )",
    "docstring": "Yield entry point objects from `group` matching `name`\n\n        If `name` is None, yields all entry points in `group` from all\n        distributions in the working set, otherwise only ones matching\n        both `group` and `name` are yielded (in distribution order)."
  },
  {
    "code": "def flush(self, multithread=True, **kwargs):\n        if self._write_buf.tell() > 0:\n            data = self._write_buf.getvalue()\n            self._write_buf = BytesIO()\n            if multithread:\n                self._async_upload_part_request(data, index=self._cur_part, **kwargs)\n            else:\n                self.upload_part(data, self._cur_part, **kwargs)\n            self._cur_part += 1\n        if len(self._http_threadpool_futures) > 0:\n            dxpy.utils.wait_for_all_futures(self._http_threadpool_futures)\n            try:\n                for future in self._http_threadpool_futures:\n                    if future.exception() != None:\n                        raise future.exception()\n            finally:\n                self._http_threadpool_futures = set()",
    "docstring": "Flushes the internal write buffer."
  },
  {
    "code": "def write(self, path=None, *args, **kwargs):\n        if path is None:\n            print(self.format(*args, **kwargs))\n        else:\n            with io.open(path, 'w', newline=\"\") as f:\n                f.write(self.format(*args, **kwargs))",
    "docstring": "Perform formatting and write the formatted string to a file or stdout.\n\n        Optional arguments can be used to format the editor's contents. If no\n        file path is given, prints to standard output.\n\n        Args:\n            path (str): Full file path (default None, prints to stdout)\n            *args: Positional arguments to format the editor with\n            **kwargs: Keyword arguments to format the editor with"
  },
  {
    "code": "def kill(self, exc_info=None):\n        if self._being_killed:\n            _log.debug('already killing %s ... waiting for death', self)\n            try:\n                self._died.wait()\n            except:\n                pass\n            return\n        self._being_killed = True\n        if self._died.ready():\n            _log.debug('already stopped %s', self)\n            return\n        if exc_info is not None:\n            _log.info('killing %s due to %s', self, exc_info[1])\n        else:\n            _log.info('killing %s', self)\n        def safely_kill_extensions(ext_set):\n            try:\n                ext_set.kill()\n            except Exception as exc:\n                _log.warning('Extension raised `%s` during kill', exc)\n        safely_kill_extensions(self.entrypoints.all)\n        self._kill_worker_threads()\n        safely_kill_extensions(self.extensions.all)\n        self._kill_managed_threads()\n        self.started = False\n        if not self._died.ready():\n            self._died.send(None, exc_info)",
    "docstring": "Kill the container in a semi-graceful way.\n\n        Entrypoints are killed, followed by any active worker threads.\n        Next, dependencies are killed. Finally, any remaining managed threads\n        are killed.\n\n        If ``exc_info`` is provided, the exception will be raised by\n        :meth:`~wait``."
  },
  {
    "code": "async def get_agents(self, addr=True, agent_cls=None):\n        return await self.menv.get_agents(addr=True, agent_cls=None,\n                                          as_coro=True)",
    "docstring": "Get addresses of all agents in all the slave environments.\n\n        This is a managing function for\n        :meth:`creamas.mp.MultiEnvironment.get_agents`.\n\n        .. note::\n\n            Since :class:`aiomas.rpc.Proxy` objects do not seem to handle\n            (re)serialization, ``addr`` and ``agent_cls`` parameters are\n            omitted from the call to underlying multi-environment's\n            :meth:`get_agents`.\n\n            If :class:`aiomas.rpc.Proxy` objects from all the agents are\n            needed, call each slave environment manager's :meth:`get_agents`\n            directly."
  },
  {
    "code": "def get_current_url():\n    if current_app.config.get('SERVER_NAME') and (\n            request.environ['HTTP_HOST'].split(':', 1)[0] != current_app.config['SERVER_NAME'].split(':', 1)[0]):\n        return request.url\n    url = url_for(request.endpoint, **request.view_args)\n    query = request.query_string\n    if query:\n        return url + '?' + query.decode()\n    else:\n        return url",
    "docstring": "Return the current URL including the query string as a relative path. If the app uses\n    subdomains, return an absolute path"
  },
  {
    "code": "def get_dois(query_str, count=100):\n    url = '%s/%s' % (elsevier_search_url, query_str)\n    params = {'query': query_str,\n              'count': count,\n              'httpAccept': 'application/xml',\n              'sort': '-coverdate',\n              'field': 'doi'}\n    res = requests.get(url, params)\n    if not res.status_code == 200:\n        return None\n    tree = ET.XML(res.content, parser=UTB())\n    doi_tags = tree.findall('atom:entry/prism:doi', elsevier_ns)\n    dois = [dt.text for dt in doi_tags]\n    return dois",
    "docstring": "Search ScienceDirect through the API for articles.\n\n    See http://api.elsevier.com/content/search/fields/scidir for constructing a\n    query string to pass here.  Example: 'abstract(BRAF) AND all(\"colorectal\n    cancer\")'"
  },
  {
    "code": "def get_sentence(start=None, depth=7):\n    if not GRAMMAR:\n        return 'Please set a GRAMMAR file'\n    start = start if start else GRAMMAR.start()\n    if isinstance(start, Nonterminal):\n        productions = GRAMMAR.productions(start)\n        if not depth:\n            terminals = [p for p in productions if not isinstance(start, Nonterminal)]\n            if len(terminals):\n                production = terminals\n        production = random.choice(productions)\n        sentence = []\n        for piece in production.rhs():\n            sentence += get_sentence(start=piece, depth=depth-1)\n        return sentence\n    else:\n        return [start]",
    "docstring": "follow the grammatical patterns to generate a random sentence"
  },
  {
    "code": "def get_fields(model):\n    try:\n        if hasattr(model, \"knockout_fields\"):\n            fields = model.knockout_fields()\n        else:\n            try:\n                fields = model_to_dict(model).keys()\n            except Exception as e:\n                fields = model._meta.get_fields()\n        return fields\n    except Exception as e:\n        logger.exception(e)\n        return []",
    "docstring": "Returns a Model's knockout_fields,\n    or the default set of field names."
  },
  {
    "code": "def get(self, obj, key):\n        if key not in self._exposed:\n            raise MethodNotExposed()\n        rightFuncs = self._exposed[key]\n        T = obj.__class__\n        seen = {}\n        for subT in inspect.getmro(T):\n            for name, value in subT.__dict__.items():\n                for rightFunc in rightFuncs:\n                    if value is rightFunc:\n                        if name in seen:\n                            raise MethodNotExposed()\n                        return value.__get__(obj, T)\n                seen[name] = True\n        raise MethodNotExposed()",
    "docstring": "Retrieve 'key' from an instance of a class which previously exposed it.\n\n        @param key: a hashable object, previously passed to L{Exposer.expose}.\n\n        @return: the object which was exposed with the given name on obj's key.\n\n        @raise MethodNotExposed: when the key in question was not exposed with\n        this exposer."
  },
  {
    "code": "def clean_regex(regex):\n    ret_regex = regex\n    escape_chars = '[^$.?*+(){}'\n    ret_regex = ret_regex.replace('\\\\', '')\n    for c in escape_chars:\n        ret_regex = ret_regex.replace(c, '\\\\' + c)\n    while True:\n        old_regex = ret_regex\n        ret_regex = ret_regex.replace('||', '|')\n        if old_regex == ret_regex:\n            break\n    while len(ret_regex) >= 1 and ret_regex[-1] == '|':\n        ret_regex = ret_regex[:-1]\n    return ret_regex",
    "docstring": "Escape any regex special characters other than alternation.\n\n    :param regex: regex from datatables interface\n    :type regex: str\n    :rtype: str with regex to use with database"
  },
  {
    "code": "def authenticate(self, request, **credentials):\n        from allauth.account.auth_backends import AuthenticationBackend\n        self.pre_authenticate(request, **credentials)\n        AuthenticationBackend.unstash_authenticated_user()\n        user = authenticate(request, **credentials)\n        alt_user = AuthenticationBackend.unstash_authenticated_user()\n        user = user or alt_user\n        if user and app_settings.LOGIN_ATTEMPTS_LIMIT:\n            cache_key = self._get_login_attempts_cache_key(\n                request, **credentials)\n            cache.delete(cache_key)\n        else:\n            self.authentication_failed(request, **credentials)\n        return user",
    "docstring": "Only authenticates, does not actually login. See `login`"
  },
  {
    "code": "def _percent_match(result, out, yP=None, *argl):\n    if len(argl) > 1:\n        if yP is None:\n            Xt = argl[1]\n            key = id(Xt)\n            if key in _splits:\n                yP = _splits[key][3]\n        if yP is not None:\n            import math\n            out[\"%\"] = round(1.-sum(abs(yP - result))/float(len(result)), 3)",
    "docstring": "Returns the percent match for the specified prediction call; requires\n    that the data was split before using an analyzed method.\n\n    Args:\n        out (dict): output dictionary to save the result to."
  },
  {
    "code": "def upload(ui, repo, name, **opts):\n\tif codereview_disabled:\n\t\traise hg_util.Abort(codereview_disabled)\n\trepo.ui.quiet = True\n\tcl, err = LoadCL(ui, repo, name, web=True)\n\tif err != \"\":\n\t\traise hg_util.Abort(err)\n\tif not cl.local:\n\t\traise hg_util.Abort(\"cannot upload non-local change\")\n\tcl.Upload(ui, repo)\n\tprint \"%s%s\\n\" % (server_url_base, cl.name)\n\treturn 0",
    "docstring": "upload diffs to the code review server\n\n\tUploads the current modifications for a given change to the server."
  },
  {
    "code": "def det_dataset(eb, passband, dataid, comp, time):\n    rvs = eb.get_dataset(kind='rv').datasets\n    if dataid == 'Undefined':\n        dataid = None\n    try:\n        eb._check_label(dataid)\n        rv_dataset = eb.add_dataset('rv', dataset=dataid, times=[])\n    except ValueError:\n        logger.warning(\"The name picked for the radial velocity curve is forbidden. Applying default name instead\")\n        rv_dataset = eb.add_dataset('rv', times=[])\n    return rv_dataset",
    "docstring": "Since RV datasets can have values related to each component in phoebe2, but are component specific in phoebe1\n    , it is important to determine which dataset to add parameters to. This function will do that.\n    eb - bundle\n    rvpt - relevant phoebe 1 parameters"
  },
  {
    "code": "def _on_move(self, event):\n        w = self.winfo_width()\n        x = min(max(event.x, 0), w)\n        self.coords('cursor', x, 0, x, self.winfo_height())\n        self._variable.set(round2((360. * x) / w))",
    "docstring": "Make selection cursor follow the cursor."
  },
  {
    "code": "def match_any(patterns, name):\n    if not patterns:\n        return True\n    return any(match(pattern, name) for pattern in patterns)",
    "docstring": "Test if a name matches any of a list of patterns.\n\n    Will return `True` if ``patterns`` is an empty list.\n\n    Arguments:\n        patterns (list): A list of wildcard pattern, e.g ``[\"*.py\",\n            \"*.pyc\"]``\n        name (str): A filename.\n\n    Returns:\n        bool: `True` if the name matches at least one of the patterns."
  },
  {
    "code": "def update_room_name(self):\n        try:\n            response = self.client.api.get_room_name(self.room_id)\n            if \"name\" in response and response[\"name\"] != self.name:\n                self.name = response[\"name\"]\n                return True\n            else:\n                return False\n        except MatrixRequestError:\n            return False",
    "docstring": "Updates self.name and returns True if room name has changed."
  },
  {
    "code": "def get_table_idbb_field(endianess, data):\n\tbfld = struct.unpack(endianess + 'H', data[:2])[0]\n\tproc_nbr = bfld & 0x7ff\n\tstd_vs_mfg = bool(bfld & 0x800)\n\tselector = (bfld & 0xf000) >> 12\n\treturn (proc_nbr, std_vs_mfg, selector)",
    "docstring": "Return data from a packed TABLE_IDB_BFLD bit-field.\n\n\t:param str endianess: The endianess to use when packing values ('>' or '<')\n\t:param str data: The packed and machine-formatted data to parse\n\t:rtype: tuple\n\t:return: Tuple of (proc_nbr, std_vs_mfg)"
  },
  {
    "code": "def ReadPathInfoHistory(self, client_id, path_type, components):\n    histories = self.ReadPathInfosHistories(client_id, path_type, [components])\n    return histories[components]",
    "docstring": "Reads a collection of hash and stat entry for given path.\n\n    Args:\n      client_id: An identifier string for a client.\n      path_type: A type of a path to retrieve path history for.\n      components: A tuple of path components corresponding to path to retrieve\n        information for.\n\n    Returns:\n      A list of `rdf_objects.PathInfo` ordered by timestamp in ascending order."
  },
  {
    "code": "def find_by_content_type(content_type):\n    for format in FORMATS:\n        if content_type in format.content_types:\n            return format\n    raise UnknownFormat('No format found with content type \"%s\"' % content_type)",
    "docstring": "Find and return a format by content type.\n\n    :param content_type: A string describing the internet media type of the format."
  },
  {
    "code": "def complete(self, query, current_url):\n        endpoint = self.session.get(self._token_key)\n        message = Message.fromPostArgs(query)\n        response = self.consumer.complete(message, endpoint, current_url)\n        try:\n            del self.session[self._token_key]\n        except KeyError:\n            pass\n        if (response.status in ['success', 'cancel'] and\n            response.identity_url is not None):\n            disco = Discovery(self.session,\n                              response.identity_url,\n                              self.session_key_prefix)\n            disco.cleanup(force=True)\n        return response",
    "docstring": "Called to interpret the server's response to an OpenID\n        request. It is called in step 4 of the flow described in the\n        consumer overview.\n\n        @param query: A dictionary of the query parameters for this\n            HTTP request.\n\n        @param current_url: The URL used to invoke the application.\n            Extract the URL from your application's web\n            request framework and specify it here to have it checked\n            against the openid.return_to value in the response.  If\n            the return_to URL check fails, the status of the\n            completion will be FAILURE.\n\n        @returns: a subclass of Response. The type of response is\n            indicated by the status attribute, which will be one of\n            SUCCESS, CANCEL, FAILURE, or SETUP_NEEDED.\n\n        @see: L{SuccessResponse<openid.consumer.consumer.SuccessResponse>}\n        @see: L{CancelResponse<openid.consumer.consumer.CancelResponse>}\n        @see: L{SetupNeededResponse<openid.consumer.consumer.SetupNeededResponse>}\n        @see: L{FailureResponse<openid.consumer.consumer.FailureResponse>}"
  },
  {
    "code": "def service_restarted(self, sentry_unit, service, filename,\n                          pgrep_full=None, sleep_time=20):\n        self.log.warn('DEPRECATION WARNING:  use '\n                      'validate_service_config_changed instead of '\n                      'service_restarted due to known races.')\n        time.sleep(sleep_time)\n        if (self._get_proc_start_time(sentry_unit, service, pgrep_full) >=\n                self._get_file_mtime(sentry_unit, filename)):\n            return True\n        else:\n            return False",
    "docstring": "Check if service was restarted.\n\n           Compare a service's start time vs a file's last modification time\n           (such as a config file for that service) to determine if the service\n           has been restarted."
  },
  {
    "code": "def get_oauth_token_secret_name(self, provider):\n        for _provider in self.oauth_providers:\n            if _provider[\"name\"] == provider:\n                return _provider.get(\"token_secret\", \"oauth_token_secret\")",
    "docstring": "Returns the token_secret name for the oauth provider\n            if none is configured defaults to oauth_secret\n            this is configured using OAUTH_PROVIDERS and token_secret"
  },
  {
    "code": "def _readfloatle(self, length, start):\n        startbyte, offset = divmod(start + self._offset, 8)\n        if not offset:\n            if length == 32:\n                f, = struct.unpack('<f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4)))\n            elif length == 64:\n                f, = struct.unpack('<d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8)))\n        else:\n            if length == 32:\n                f, = struct.unpack('<f', self._readbytes(32, start))\n            elif length == 64:\n                f, = struct.unpack('<d', self._readbytes(64, start))\n        try:\n            return f\n        except NameError:\n            raise InterpretError(\"floats can only be 32 or 64 bits long, \"\n                                 \"not {0} bits\", length)",
    "docstring": "Read bits and interpret as a little-endian float."
  },
  {
    "code": "def build_tree_file_pathname(filename, directory_depth=8, pathname_separator_character=os.sep):\n    return build_tree_pathname(filename, directory_depth, pathname_separator_character) + filename",
    "docstring": "Return a file pathname which pathname is built of the specified\n    number of sub-directories, and where each directory is named after the\n    nth letter of the filename corresponding to the directory depth.\n\n    Examples::\n\n        >>> build_tree_file_pathname('foo.txt', 2, '/')\n        'f/o/foo.txt'\n        >>> build_tree_file_pathname('0123456789abcdef')\n        '0/1/2/3/4/5/6/7/0123456789abcdef'\n\n    @param filename: name of a file, with or without extension.\n\n    @param directory_depth: number of sub-directories to be generated.\n\n    @param pathname_separator_character: character to be used to separate\n           pathname components, such as '/' for POSIX and '\\\\' for\n           Windows.  If not defined, the default is the character used by\n           the operating system ``os.sep``.\n\n    @return: a file pathname."
  },
  {
    "code": "def _special_value_size(em):\n    if em.tagName == 'input':\n        return convertToPositiveInt(em.getAttribute('size', 20), invalidDefault=20)\n    return em.getAttribute('size', '')",
    "docstring": "handle \"size\" property, which has different behaviour for input vs everything else"
  },
  {
    "code": "def get_user_trades(self, limit=0, offset=0, sort='desc'):\n        self._log('get user trades')\n        res = self._rest_client.post(\n            endpoint='/user_transactions',\n            payload={\n                'book': self.name,\n                'limit': limit,\n                'offset': offset,\n                'sort': sort\n            }\n        )\n        return res[:limit] if len(res) > limit > 0 else res",
    "docstring": "Return user's trade history.\n\n        :param limit: Maximum number of trades to return. If set to 0 or lower,\n            all trades are returned (default: 0).\n        :type limit: int\n        :param offset: Number of trades to skip.\n        :type offset: int\n        :param sort: Method used to sort the results by date and time. Allowed\n            values are \"desc\" for descending order, and \"asc\" for ascending\n            order (default: \"desc\").\n        :type sort: str | unicode\n        :return: User's trade history.\n        :rtype: [dict]"
  },
  {
    "code": "def init(module_paths, work_db, config):\n    operator_names = cosmic_ray.plugins.operator_names()\n    work_db.set_config(config=config)\n    work_db.clear()\n    for module_path in module_paths:\n        module_ast = get_ast(\n            module_path, python_version=config.python_version)\n        for op_name in operator_names:\n            operator = get_operator(op_name)(config.python_version)\n            visitor = WorkDBInitVisitor(module_path, op_name, work_db,\n                                        operator)\n            visitor.walk(module_ast)\n    apply_interceptors(work_db, config.sub('interceptors').get('enabled', ()))",
    "docstring": "Clear and initialize a work-db with work items.\n\n    Any existing data in the work-db will be cleared and replaced with entirely\n    new work orders. In particular, this means that any results in the db are\n    removed.\n\n    Args:\n      module_paths: iterable of pathlib.Paths of modules to mutate.\n      work_db: A `WorkDB` instance into which the work orders will be saved.\n      config: The configuration for the new session."
  },
  {
    "code": "def dependencies(self, task, params={}, **options): \n        path = \"/tasks/%s/dependencies\" % (task)\n        return self.client.get(path, params, **options)",
    "docstring": "Returns the compact representations of all of the dependencies of a task.\n\n        Parameters\n        ----------\n        task : {Id} The task to get dependencies on.\n        [params] : {Object} Parameters for the request"
  },
  {
    "code": "def cli(obj):\n    client = obj['client']\n    metrics = client.mgmt_status()['metrics']\n    headers = {'title': 'METRIC', 'type': 'TYPE', 'name': 'NAME', 'value': 'VALUE', 'average': 'AVERAGE'}\n    click.echo(tabulate([{\n        'title': m['title'],\n        'type': m['type'],\n        'name': '{}.{}'.format(m['group'], m['name']),\n        'value': m.get('value', None) or m.get('count', 0),\n        'average': int(m['totalTime']) * 1.0 / int(m['count']) if m['type'] == 'timer' else None\n    } for m in metrics], headers=headers, tablefmt=obj['output']))",
    "docstring": "Display API server switch status and usage metrics."
  },
  {
    "code": "def fishrot(k=20, n=100, dec=0, inc=90, di_block=True):\n    directions = []\n    declinations = []\n    inclinations = []\n    if di_block == True:\n        for data in range(n):\n            d, i = pmag.fshdev(k)\n            drot, irot = pmag.dodirot(d, i, dec, inc)\n            directions.append([drot, irot, 1.])\n        return directions\n    else:\n        for data in range(n):\n            d, i = pmag.fshdev(k)\n            drot, irot = pmag.dodirot(d, i, dec, inc)\n            declinations.append(drot)\n            inclinations.append(irot)\n        return declinations, inclinations",
    "docstring": "Generates Fisher distributed unit vectors from a specified distribution\n    using the pmag.py fshdev and dodirot functions.\n\n    Parameters\n    ----------\n    k : kappa precision parameter (default is 20)\n    n : number of vectors to determine (default is 100)\n    dec : mean declination of distribution (default is 0)\n    inc : mean inclination of distribution (default is 90)\n    di_block : this function returns a nested list of [dec,inc,1.0] as the default\n    if di_block = False it will return a list of dec and a list of inc\n\n    Returns\n    ---------\n    di_block : a nested list of [dec,inc,1.0] (default)\n    dec, inc : a list of dec and a list of inc (if di_block = False)\n\n    Examples\n    --------\n    >>> ipmag.fishrot(k=20, n=5, dec=40, inc=60)\n    [[44.766285502555775, 37.440866867657235, 1.0],\n     [33.866315796883725, 64.732532250463436, 1.0],\n     [47.002912770597163, 54.317853800896977, 1.0],\n     [36.762165614432547, 56.857240672884252, 1.0],\n     [71.43950604474395, 59.825830945715431, 1.0]]"
  },
  {
    "code": "def contracts_deployed_path(\n        chain_id: int,\n        version: Optional[str] = None,\n        services: bool = False,\n):\n    data_path = contracts_data_path(version)\n    chain_name = ID_TO_NETWORKNAME[chain_id] if chain_id in ID_TO_NETWORKNAME else 'private_net'\n    return data_path.joinpath(f'deployment_{\"services_\" if services else \"\"}{chain_name}.json')",
    "docstring": "Returns the path of the deplolyment data JSON file."
  },
  {
    "code": "def _respond(self, resp):\n        response_queue = self._response_queues.get(timeout=0.1)\n        response_queue.put(resp)\n        self._completed_response_lines = []\n        self._is_multiline = None",
    "docstring": "Respond to the person waiting"
  },
  {
    "code": "def _build(self, items, chunk_size=10000):\n        _log.debug(\"_build, chunk_size={:d}\".format(chunk_size))\n        n, i = 0, 0\n        for i, item in enumerate(items):\n            if i == 0:\n                _log.debug(\"_build, first item\")\n            if 0 == (i + 1) % chunk_size:\n                if self._seq:\n                    self._run(0)\n                else:\n                    self._run_parallel_fn()\n                if self._status.has_failures():\n                    break\n                n = i + 1\n            self._queue.put(item)\n        if self._seq:\n            self._run(0)\n        else:\n            self._run_parallel_fn()\n        if not self._status.has_failures():\n            n = i + 1\n        return n",
    "docstring": "Build the output, in chunks.\n\n        :return: Number of items processed\n        :rtype: int"
  },
  {
    "code": "def size_limit(self):\n        limits = [\n            lim for lim in current_files_rest.file_size_limiters(\n                self)\n            if lim.limit is not None\n        ]\n        return min(limits) if limits else None",
    "docstring": "Get size limit for this bucket.\n\n        The limit is based on the minimum output of the file size limiters."
  },
  {
    "code": "def alien_filter(packages, sizes):\n    cache, npkg, nsize = [], [], []\n    for p, s in zip(packages, sizes):\n        name = split_package(p)[0]\n        if name not in cache:\n            cache.append(name)\n            npkg.append(p)\n            nsize.append(s)\n    return npkg, nsize",
    "docstring": "This filter avoid list double packages from\n    alien repository"
  },
  {
    "code": "def hacking_python3x_octal_literals(logical_line, tokens, noqa):\n    r\n    if noqa:\n        return\n    for token_type, text, _, _, _ in tokens:\n        if token_type == tokenize.NUMBER:\n            match = RE_OCTAL.match(text)\n            if match:\n                yield 0, (\"H232: Python 3.x incompatible octal %s should be \"\n                          \"written as 0o%s \" %\n                          (match.group(0)[1:], match.group(1)))",
    "docstring": "r\"\"\"Check for octal literals in Python 3.x compatible form.\n\n    As of Python 3.x, the construct \"0755\" has been removed.\n    Use \"0o755\" instead\".\n\n\n    Okay: f(0o755)\n    Okay: 'f(0755)'\n    Okay: f(755)\n    Okay: f(0)\n    Okay: f(000)\n    Okay: MiB = 1.0415\n    H232: f(0755)\n    Okay: f(0755)  # noqa"
  },
  {
    "code": "def step_definition(step_name):\n    if not orca.is_step(step_name):\n        abort(404)\n    filename, lineno, source = \\\n        orca.get_step(step_name).func_source_data()\n    html = highlight(source, PythonLexer(), HtmlFormatter())\n    return jsonify(filename=filename, lineno=lineno, text=source, html=html)",
    "docstring": "Get the source of a step function. Returned object has keys\n    \"filename\", \"lineno\", \"text\" and \"html\". \"text\" is the raw\n    text of the function, \"html\" has been marked up by Pygments."
  },
  {
    "code": "def __parse_config(self):\n        if self.should_parse_config and (self.args.config or self.config_file):\n            self.config = ConfigParser.SafeConfigParser()\n            self.config.read(self.args.config or self.config_file)",
    "docstring": "Invoke the config file parser."
  },
  {
    "code": "def interruptRead(self, endpoint, size, timeout = 100):\n        r\n        return self.dev.read(endpoint, size, timeout)",
    "docstring": "r\"\"\"Performs a interrupt read request to the endpoint specified.\n\n            Arguments:\n                endpoint: endpoint number.\n                size: number of bytes to read.\n                timeout: operation timeout in milliseconds. (default: 100)\n            Returns a tuple with the data read."
  },
  {
    "code": "def lookup_forward(name):\n    ip_addresses = {}\n    addresses = list(set(str(ip[4][0]) for ip in socket.getaddrinfo(\n        name, None)))\n    if addresses is None:\n        return ip_addresses\n    for address in addresses:\n        if type(ipaddress.ip_address(address)) is ipaddress.IPv4Address:\n            ip_addresses['ipv4'] = address\n        if type(ipaddress.ip_address(address)) is ipaddress.IPv6Address:\n            ip_addresses['ipv6'] = address\n    return ip_addresses",
    "docstring": "Perform a forward lookup of a hostname."
  },
  {
    "code": "def CopyToIsoFormat(cls, timestamp, timezone=pytz.UTC, raise_error=False):\n    datetime_object = cls.CopyToDatetime(\n        timestamp, timezone, raise_error=raise_error)\n    return datetime_object.isoformat()",
    "docstring": "Copies the timestamp to an ISO 8601 formatted string.\n\n    Args:\n      timestamp: The timestamp which is an integer containing the number\n                 of micro seconds since January 1, 1970, 00:00:00 UTC.\n      timezone: Optional timezone (instance of pytz.timezone).\n      raise_error: Boolean that if set to True will not absorb an OverflowError\n                   if the timestamp is out of bounds. By default there will be\n                   no error raised.\n\n    Returns:\n      A string containing an ISO 8601 formatted date and time."
  },
  {
    "code": "def bind_sockets(address, port):\n    ss = netutil.bind_sockets(port=port or 0, address=address)\n    assert len(ss)\n    ports = {s.getsockname()[1] for s in ss}\n    assert len(ports) == 1, \"Multiple ports assigned??\"\n    actual_port = ports.pop()\n    if port:\n        assert actual_port == port\n    return ss, actual_port",
    "docstring": "Bind a socket to a port on an address.\n\n    Args:\n        address (str) :\n            An address to bind a port on, e.g. ``\"localhost\"``\n\n        port (int) :\n            A port number to bind.\n\n            Pass 0 to have the OS automatically choose a free port.\n\n    This function returns a 2-tuple with the new socket as the first element,\n    and the port that was bound as the second. (Useful when passing 0 as a port\n    number to bind any free port.)\n\n    Returns:\n        (socket, port)"
  },
  {
    "code": "def dependencies(self) -> List[Dependency]:\n        dependencies_str = DB.get_hash_value(self.key, 'dependencies')\n        dependencies = []\n        for dependency in ast.literal_eval(dependencies_str):\n            dependencies.append(Dependency(dependency))\n        return dependencies",
    "docstring": "Return the PB dependencies."
  },
  {
    "code": "def _read_current_marker(self):\n        return self._geno_values[\n            np.frombuffer(self._bed.read(self._nb_bytes), dtype=np.uint8)\n        ].flatten(order=\"C\")[:self._nb_samples]",
    "docstring": "Reads the current marker and returns its genotypes."
  },
  {
    "code": "def check(self, _):\n        try:\n            import yaml\n        except:\n            return True\n        try:\n            yaml.safe_load(self.recipes)\n        except Exception as e:\n            raise RADLParseException(\"Invalid YAML code: %s.\" % e, line=self.line)\n        return True",
    "docstring": "Check this configure."
  },
  {
    "code": "def add_config_source(self, config_source, position=None):\n        rank = position if position is not None else len(self._config_sources)\n        self._config_sources.insert(rank, config_source)",
    "docstring": "Add a config source to the current ConfigResolver instance.\n        If position is not set, this source will be inserted with the lowest priority."
  },
  {
    "code": "def _get_all_volumes_paths(conn):\n    volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l]\n    return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')]\n            for vol in volumes if _is_valid_volume(vol)}",
    "docstring": "Extract the path and backing stores path of all volumes.\n\n    :param conn: libvirt connection to use"
  },
  {
    "code": "def _chunk(self, response, size=4096):\n        method = response.headers.get(\"content-encoding\")\n        if method == \"gzip\":\n            d = zlib.decompressobj(16+zlib.MAX_WBITS)\n            b = response.read(size)\n            while b:\n                data = d.decompress(b)\n                yield data\n                b = response.read(size)\n                del data\n        else:\n            while True:\n                chunk = response.read(size)\n                if not chunk: break\n                yield chunk",
    "docstring": "downloads a web response in pieces"
  },
  {
    "code": "def write_to_disk(filename, delete=False, content=get_time()):\n    if not os.path.exists(os.path.dirname(filename)):\n        return\n    if delete:\n        if os.path.lexists(filename):\n            os.remove(filename)\n    else:\n        with open(filename, 'wb') as f:\n            f.write(content.encode('utf-8'))",
    "docstring": "Write filename out to disk"
  },
  {
    "code": "def create(self, ami, count, config=None):\n        return self.Launcher(config=config).launch(ami, count)",
    "docstring": "Create an instance using the launcher."
  },
  {
    "code": "def load_all(cls, vr, params=None):\n        ob_docs = vr.query(cls.base, params)\n        return [cls(vr, ob) for ob in ob_docs]",
    "docstring": "Create instances of all objects found"
  },
  {
    "code": "def logout(request, redirect_url=settings.LOGOUT_REDIRECT_URL):\n    django_logout(request)\n    return HttpResponseRedirect(request.build_absolute_uri(redirect_url))",
    "docstring": "Nothing hilariously hidden here, logs a user out. Strip this out if your\n        application already has hooks to handle this."
  },
  {
    "code": "def next(self):\n        line = self.filehandle.readline()\n        line = line.decode('utf-8', 'replace')\n        if line == '':\n            raise StopIteration\n        line = line.rstrip('\\n')\n        le = LogEvent(line)\n        if self._datetime_format and self._datetime_nextpos is not None:\n            ret = le.set_datetime_hint(self._datetime_format,\n                                       self._datetime_nextpos,\n                                       self.year_rollover)\n            if not ret:\n                self._datetime_format = None\n                self._datetime_nextpos = None\n        elif le.datetime:\n            self._datetime_format = le.datetime_format\n            self._datetime_nextpos = le._datetime_nextpos\n        return le",
    "docstring": "Get next line, adjust for year rollover and hint datetime format."
  },
  {
    "code": "def ping():\n    r = __salt__['dracr.system_info'](host=DETAILS['host'],\n                                      admin_username=DETAILS['admin_username'],\n                                      admin_password=DETAILS['admin_password'])\n    if r.get('retcode', 0) == 1:\n        return False\n    else:\n        return True\n    try:\n        return r['dict'].get('ret', False)\n    except Exception:\n        return False",
    "docstring": "Is the chassis responding?\n\n    :return: Returns False if the chassis didn't respond, True otherwise."
  },
  {
    "code": "def get_chinese_text():\n    if not os.path.isdir(\"data/\"):\n        os.system(\"mkdir data/\")\n    if (not os.path.exists('data/pos.txt')) or \\\n       (not os.path.exists('data/neg')):\n        os.system(\"wget -q https://raw.githubusercontent.com/dmlc/web-data/master/mxnet/example/chinese_text.zip \"\n                  \"-P data/\")\n        os.chdir(\"./data\")\n        os.system(\"unzip -u chinese_text.zip\")\n        os.chdir(\"..\")",
    "docstring": "Download the chinese_text dataset and unzip it"
  },
  {
    "code": "def _on_move(self, event):\n        w = self.winfo_width()\n        h = self.winfo_height()\n        x = min(max(event.x, 0), w)\n        y = min(max(event.y, 0), h)\n        self.coords('cross_h', 0, y, w, y)\n        self.coords('cross_v', x, 0, x, h)\n        self.event_generate(\"<<ColorChanged>>\")",
    "docstring": "Make the cross follow the cursor."
  },
  {
    "code": "def spoken_number(num: str) -> str:\n    ret = []\n    for part in num.split(' '):\n        if part in FRACTIONS:\n            ret.append(FRACTIONS[part])\n        else:\n            ret.append(' '.join([NUMBER_REPL[char] for char in part if char in NUMBER_REPL]))\n    return ' and '.join(ret)",
    "docstring": "Returns the spoken version of a number\n\n    Ex: 1.2 -> one point two\n        1 1/2 -> one and one half"
  },
  {
    "code": "def insert(self, index, child, by_name_index=-1):\n        if self._can_add_child(child):\n            try:\n                if by_name_index == -1:\n                    self.indexes[child.name].append(child)\n                else:\n                    self.indexes[child.name].insert(by_name_index, child)\n            except KeyError:\n                self.indexes[child.name] = [child]\n            self.list.insert(index, child)",
    "docstring": "Add the child at the given index\n\n        :type index: ``int``\n        :param index: child position\n\n        :type child: :class:`Element <hl7apy.core.Element>`\n        :param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass"
  },
  {
    "code": "def add_property(self, prop):\n        if _debug: Object._debug(\"add_property %r\", prop)\n        self._properties = _copy(self._properties)\n        self._properties[prop.identifier] = prop\n        self._values[prop.identifier] = prop.default",
    "docstring": "Add a property to an object.  The property is an instance of\n        a Property or one of its derived classes.  Adding a property\n        disconnects it from the collection of properties common to all of the\n        objects of its class."
  },
  {
    "code": "def consider_member(name_member, member, module, class_=None):\n        if name_member.startswith('_'):\n            return False\n        if inspect.ismodule(member):\n            return False\n        real_module = getattr(member, '__module__', None)\n        if not real_module:\n            return True\n        if real_module != module.__name__:\n            if class_ and hasattr(member, '__get__'):\n                return True\n            if 'hydpy' in real_module:\n                return False\n            if module.__name__ not in real_module:\n                return False\n        return True",
    "docstring": "Return |True| if the given member should be added to the\n        substitutions. If not return |False|.\n\n        Some examples based on the site-package |numpy|:\n\n        >>> from hydpy.core.autodoctools import Substituter\n        >>> import numpy\n\n        A constant like |nan| should be added:\n\n        >>> Substituter.consider_member(\n        ...     'nan', numpy.nan, numpy)\n        True\n\n        Members with a prefixed underscore should not be added:\n\n        >>> Substituter.consider_member(\n        ...     '_NoValue', numpy._NoValue, numpy)\n        False\n\n        Members that are actually imported modules should not be added:\n\n        >>> Substituter.consider_member(\n        ...     'warnings', numpy.warnings, numpy)\n        False\n\n        Members that are actually defined in other modules should\n        not be added:\n\n        >>> numpy.Substituter = Substituter\n        >>> Substituter.consider_member(\n        ...     'Substituter', numpy.Substituter, numpy)\n        False\n        >>> del numpy.Substituter\n\n        Members that are defined in submodules of a given package\n        (either from the standard library or from site-packages)\n        should be added...\n\n        >>> Substituter.consider_member(\n        ...     'clip', numpy.clip, numpy)\n        True\n\n        ...but not members defined in *HydPy* submodules:\n\n        >>> import hydpy\n        >>> Substituter.consider_member(\n        ...     'Node', hydpy.Node, hydpy)\n        False\n\n        For descriptor instances (with method `__get__`) beeing members\n        of classes should be added:\n\n        >>> from hydpy.auxs import anntools\n        >>> Substituter.consider_member(\n        ...     'shape_neurons', anntools.ANN.shape_neurons,\n        ...     anntools, anntools.ANN)\n        True"
  },
  {
    "code": "def get_cardinality(self, node=None):\n        if node:\n            return self.get_cpds(node).cardinality[0]\n        else:\n            cardinalities = defaultdict(int)\n            for cpd in self.cpds:\n                cardinalities[cpd.variable] = cpd.cardinality[0]\n            return cardinalities",
    "docstring": "Returns the cardinality of the node. Throws an error if the CPD for the\n        queried node hasn't been added to the network.\n\n        Parameters\n        ----------\n        node: Any hashable python object(optional).\n              The node whose cardinality we want. If node is not specified returns a\n              dictionary with the given variable as keys and their respective cardinality\n              as values.\n\n        Returns\n        -------\n        int or dict : If node is specified returns the cardinality of the node.\n                      If node is not specified returns a dictionary with the given\n                      variable as keys and their respective cardinality as values.\n\n        Examples\n        --------\n        >>> from pgmpy.models import BayesianModel\n        >>> from pgmpy.factors.discrete import TabularCPD\n        >>> student = BayesianModel([('diff', 'grade'), ('intel', 'grade')])\n        >>> cpd_diff = TabularCPD('diff',2,[[0.6,0.4]]);\n        >>> cpd_intel = TabularCPD('intel',2,[[0.7,0.3]]);\n        >>> cpd_grade = TabularCPD('grade', 2, [[0.1, 0.9, 0.2, 0.7],\n        ...                                     [0.9, 0.1, 0.8, 0.3]],\n        ...                                 ['intel', 'diff'], [2, 2])\n        >>> student.add_cpds(cpd_diff,cpd_intel,cpd_grade)\n        >>> student.get_cardinality()\n        defaultdict(int, {'diff': 2, 'grade': 2, 'intel': 2})\n\n        >>> student.get_cardinality('intel')\n        2"
  },
  {
    "code": "def scene_remove(sequence_number, scene_id):\n        return MessageWriter().string(\"scene.rm\").uint64(sequence_number).uint32(scene_id).get()",
    "docstring": "Create a scene.rm message"
  },
  {
    "code": "def unique(self):\n        from pandas import unique\n        uniques = unique(self.astype(object))\n        return self._from_sequence(uniques, dtype=self.dtype)",
    "docstring": "Compute the ExtensionArray of unique values.\n\n        Returns\n        -------\n        uniques : ExtensionArray"
  },
  {
    "code": "def start(self):\n        if self.started is True:\n            raise WampyError(\"Router already started\")\n        crossbar_config_path = self.config_path\n        cbdir = self.crossbar_directory\n        cmd = [\n            'crossbar', 'start',\n            '--cbdir', cbdir,\n            '--config', crossbar_config_path,\n        ]\n        self.proc = subprocess.Popen(cmd, preexec_fn=os.setsid)\n        self._wait_until_ready()\n        logger.info(\n            \"Crosbar.io is ready for connections on %s (IPV%s)\",\n            self.url, self.ipv\n        )\n        self.started = True",
    "docstring": "Start Crossbar.io in a subprocess."
  },
  {
    "code": "def filter(self, filter_func, reverse=False):\n        new_log_file = Log()\n        new_log_file.logfile = self.logfile\n        new_log_file.total_lines = 0\n        new_log_file._valid_lines = []\n        new_log_file._invalid_lines = self._invalid_lines[:]\n        if not reverse:\n            for i in self._valid_lines:\n                if filter_func(i):\n                    new_log_file.total_lines += 1\n                    new_log_file._valid_lines.append(i)\n        else:\n            for i in self._valid_lines:\n                if not filter_func(i):\n                    new_log_file.total_lines += 1\n                    new_log_file._valid_lines.append(i)\n        return new_log_file",
    "docstring": "Filter current log lines by a given filter function.\n\n        This allows to drill down data out of the log file by filtering the\n        relevant log lines to analyze.\n\n        For example, filter by a given IP so only log lines for that IP are\n        further processed with commands (top paths, http status counter...).\n\n        :param filter_func: [required] Filter method, see filters.py for all\n          available filters.\n        :type filter_func: function\n        :param reverse: negate the filter (so accept all log lines that return\n          ``False``).\n        :type reverse: boolean\n        :returns: a new instance of Log containing only log lines\n          that passed the filter function.\n        :rtype: :class:`Log`"
  },
  {
    "code": "def get_boundaries(self, filter_type, value):\n        assert filter_type in self.handled_suffixes\n        start = '-inf'\n        end = '+inf'\n        exclude = None\n        if filter_type in (None, 'eq'):\n            start = end = value\n        elif filter_type == 'gt':\n            start = '(%s' % value\n        elif filter_type == 'gte':\n            start = value\n        elif filter_type == 'lt':\n            end = '(%s' % value\n        elif filter_type == 'lte':\n            end = value\n        return start, end, exclude",
    "docstring": "Compute the boundaries to pass to the sorted-set command depending of the filter type\n\n        The third return value, ``exclude`` is always ``None`` because we can easily restrict the\n        score to filter on in the sorted-set.\n\n        For the parameters, see BaseRangeIndex.store\n\n        Notes\n        -----\n        For zrangebyscore:\n        - `(` means \"not included\"\n        - `-inf` alone means \"from the very beginning\"\n        - `+inf` alone means \"to the very end\""
  },
  {
    "code": "def HMAC(self, message, use_sha256=False):\n    h = self._NewHMAC(use_sha256=use_sha256)\n    h.update(message)\n    return h.finalize()",
    "docstring": "Calculates the HMAC for a given message."
  },
  {
    "code": "def convert_type(df, columns):\n    out_df = df.copy()\n    for col in columns:\n        column_values = pd.Series(out_df[col].unique())\n        column_values = column_values[~column_values.isnull()]\n        if len(column_values) == 0:\n            continue\n        if set(column_values.values) < {'True', 'False'}:\n            out_df[col] = out_df[col].map({'True': True, 'False': False})\n            continue\n        if pd.to_numeric(column_values, errors='coerce').isnull().sum() == 0:\n            out_df[col] = pd.to_numeric(out_df[col], errors='ignore')\n            continue\n        if pd.to_datetime(column_values, errors='coerce').isnull().sum() == 0:\n            out_df[col] = pd.to_datetime(out_df[col], errors='ignore',\n                                         infer_datetime_format=True)\n            continue\n    return out_df",
    "docstring": "Helper function that attempts to convert columns into their appropriate\n    data type."
  },
  {
    "code": "def expose(rule, **options):\n    def decorator(f):\n        if not hasattr(f, \"urls\"):\n            f.urls = []\n        if isinstance(rule, (list, tuple)):\n            f.urls.extend(rule)\n        else:\n            f.urls.append((rule, options))\n        return f\n    return decorator",
    "docstring": "Decorator to add an url rule to a function"
  },
  {
    "code": "def start(self):\n        super(Syndic, self).start()\n        if check_user(self.config['user']):\n            self.action_log_info('Starting up')\n            self.verify_hash_type()\n            try:\n                self.syndic.tune_in()\n            except KeyboardInterrupt:\n                self.action_log_info('Stopping')\n                self.shutdown()",
    "docstring": "Start the actual syndic.\n\n        If sub-classed, don't **ever** forget to run:\n\n            super(YourSubClass, self).start()\n\n        NOTE: Run any required code before calling `super()`."
  },
  {
    "code": "def show_plain_text(self, text):\r\n        self.switch_to_plugin()\r\n        self.switch_to_plain_text()\r\n        self.set_plain_text(text, is_code=False)",
    "docstring": "Show text in plain mode"
  },
  {
    "code": "def sysinfo2float(version_info=sys.version_info):\n    vers_str = '.'.join([str(v) for v in version_info[0:3]])\n    if version_info[3] != 'final':\n        vers_str += '.' + ''.join([str(i) for i in version_info[3:]])\n    if IS_PYPY:\n        vers_str += 'pypy'\n    else:\n        try:\n            import platform\n            platform = platform.python_implementation()\n            if platform in ('Jython', 'Pyston'):\n                vers_str += platform\n                pass\n        except ImportError:\n            pass\n        except AttributeError:\n            pass\n    return py_str2float(vers_str)",
    "docstring": "Convert a sys.versions_info-compatible list into a 'canonic'\n    floating-point number which that can then be used to look up a\n    magic number.  Note that this can only be used for released version\n    of C Python, not interim development versions, since we can't\n    represent that as a floating-point number.\n\n    For handling Pypy, pyston, jython, etc. and interim versions of\n    C Python, use sysinfo2magic."
  },
  {
    "code": "def to_json(self):\n        capsule = {}\n        capsule[\"Hierarchy\"] = []\n        for (\n            dying,\n            (persistence, surviving, saddle),\n        ) in self.merge_sequence.items():\n            capsule[\"Hierarchy\"].append(\n                {\n                    \"Persistence\": persistence,\n                    \"Dying\": dying,\n                    \"Surviving\": surviving,\n                    \"Saddle\": saddle,\n                }\n            )\n        capsule[\"Partitions\"] = []\n        base = np.array([None] * len(self.Y))\n        for label, items in self.base_partitions.items():\n            base[items] = label\n        capsule[\"Partitions\"] = base.tolist()\n        return json.dumps(capsule, separators=(\",\", \":\"))",
    "docstring": "Writes the complete Morse complex merge hierarchy to a\n            string object.\n            @ Out, a string object storing the entire merge hierarchy of\n            all maxima."
  },
  {
    "code": "def _get_api_urls(self, api_urls=None):\n        view_name = self.__class__.__name__\n        api_urls = api_urls or {}\n        api_urls[\"read\"] = url_for(view_name + \".api_read\")\n        api_urls[\"delete\"] = url_for(view_name + \".api_delete\", pk=\"\")\n        api_urls[\"create\"] = url_for(view_name + \".api_create\")\n        api_urls[\"update\"] = url_for(view_name + \".api_update\", pk=\"\")\n        return api_urls",
    "docstring": "Completes a dict with the CRUD urls of the API.\n\n        :param api_urls: A dict with the urls {'<FUNCTION>':'<URL>',...}\n        :return: A dict with the CRUD urls of the base API."
  },
  {
    "code": "def serve_forever(django=False):\n    logger = getLogger(\"irc.dispatch\")\n    logger.setLevel(settings.LOG_LEVEL)\n    logger.addHandler(StreamHandler())\n    app = IRCApplication(django)\n    server = SocketIOServer((settings.HTTP_HOST, settings.HTTP_PORT), app)\n    print \"%s [Bot: %s] listening on %s:%s\" % (\n        settings.GNOTTY_VERSION_STRING,\n        app.bot.__class__.__name__,\n        settings.HTTP_HOST,\n        settings.HTTP_PORT,\n    )\n    server.serve_forever()",
    "docstring": "Starts the gevent-socketio server."
  },
  {
    "code": "def parse_transmission_id(header, reference_id=None):\n    m = _TID_PATTERN.search(header)\n    if not m:\n        return None\n    return m.group(1)",
    "docstring": "\\\n    Returns the transmission ID of the cable. If no transmission identifier was\n    found, ``None`` is returned.\n\n    `header`\n        The cable's header\n    `reference_id`\n        The cable's reference ID."
  },
  {
    "code": "def get(self, column_name, default=None):\n        if column_name in self.table.default_columns:\n            index = self.table.default_columns.index(column_name)\n            return Datum(self.cells[index], self.row_num, column_name, self.table)\n        return default",
    "docstring": "Return the Datum for column_name, or default."
  },
  {
    "code": "def _filenames_from_arg(filename):\n    if isinstance(filename, string_types):\n        filenames = [filename]\n    elif isinstance(filename, (list, tuple)):\n        filenames = filename\n    else:\n        raise Exception('filename argument must be string, list or tuple')\n    for fn in filenames:\n        if not os.path.exists(fn):\n            raise ValueError('file not found: %s' % fn)\n        if not os.path.isfile(fn):\n            raise ValueError('not a file: %s' % fn)\n    return filenames",
    "docstring": "Utility function to deal with polymorphic filenames argument."
  },
  {
    "code": "def get_account_info(self):\n        request = self._get_request()\n        response = request.get(self.ACCOUNT_INFO_URL)\n        self.account.json_data = response[\"account\"]\n        return self.account",
    "docstring": "Get current account information\n\n        The information then will be saved in `self.account` so that you can\n        access the information like this:\n\n        >>> hsclient = HSClient()\n        >>> acct = hsclient.get_account_info()\n        >>> print acct.email_address\n\n        Returns:\n            An Account object"
  },
  {
    "code": "def _highlight_path(self, hl_path, tf):\n        fc = self.settings.get('row_font_color', 'green')\n        try:\n            self.treeview.highlight_path(hl_path, tf, font_color=fc)\n        except Exception as e:\n            self.logger.info('Error changing highlight on treeview path '\n                             '({0}): {1}'.format(hl_path, str(e)))",
    "docstring": "Highlight or unhighlight a single entry.\n\n        Examples\n        --------\n        >>> hl_path = self._get_hl_key(chname, image)\n        >>> self._highlight_path(hl_path, True)"
  },
  {
    "code": "def factorize_and_solve(self, A, b):\n        self.factorize(A)\n        return self.solve(b)",
    "docstring": "Factorizes A and solves Ax=b.\n\n        Returns\n        -------\n        x : vector"
  },
  {
    "code": "def do_search(self, arg=None):\n        new_cats = []\n        for cat in self.cats:\n            new_cat = cat.search(self.inputs.text,\n                                 depth=self.inputs.depth)\n            if len(list(new_cat)) > 0:\n                new_cats.append(new_cat)\n        if len(new_cats) > 0:\n            self.done_callback(new_cats)\n            self.visible = False",
    "docstring": "Do search and close panel"
  },
  {
    "code": "def lrun(command, *args, **kwargs):\n    return run('cd {0} && {1}'.format(ROOT, command), *args, **kwargs)",
    "docstring": "Run a local command from project root"
  },
  {
    "code": "def _compute_matrix(cls, sentences, weighting='frequency', norm=None):\n        if norm not in ('l1', 'l2', None):\n            raise ValueError('Parameter \"norm\" can only take values \"l1\", \"l2\" or None')\n        if weighting.lower() == 'binary':\n            vectorizer = CountVectorizer(min_df=1, ngram_range=(1, 1), binary=True, stop_words=None)\n        elif weighting.lower() == 'frequency':\n            vectorizer = CountVectorizer(min_df=1, ngram_range=(1, 1), binary=False, stop_words=None)\n        elif weighting.lower() == 'tfidf':\n            vectorizer = TfidfVectorizer(min_df=1, ngram_range=(1, 1), stop_words=None)\n        else:\n            raise ValueError('Parameter \"method\" must take one of the values \"binary\", \"frequency\" or \"tfidf\".')\n        frequency_matrix = vectorizer.fit_transform(sentences).astype(float)\n        if norm in ('l1', 'l2'):\n            frequency_matrix = normalize(frequency_matrix, norm=norm, axis=1)\n        elif norm is not None:\n            raise ValueError('Parameter \"norm\" can only take values \"l1\", \"l2\" or None')\n        return frequency_matrix",
    "docstring": "Compute the matrix of term frequencies given a list of sentences"
  },
  {
    "code": "def match_end_date(self, start, end, match):\n        if match:\n            if end < start:\n                raise errors.InvalidArgument('end date must be >= start date when match = True')\n            self._query_terms['endDate'] = {\n                '$gte': start,\n                '$lte': end\n            }\n        else:\n            raise errors.InvalidArgument('match = False not currently supported')",
    "docstring": "Matches temporals whose effective end date falls in between the given dates inclusive.\n\n        arg:    start (osid.calendaring.DateTime): start of date range\n        arg:    end (osid.calendaring.DateTime): end of date range\n        arg:    match (boolean): ``true`` if a positive match, ``false``\n                for negative match\n        raise:  InvalidArgument - ``start`` is less than ``end``\n        raise:  NullArgument - ``start`` or ``end`` is ``null``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def attach(session_type, address=None, port=None,\n           path=None, argv=None, decode=None):\n    session = (tcp_session(address, port) if session_type == 'tcp' else\n               socket_session(path) if session_type == 'socket' else\n               stdio_session() if session_type == 'stdio' else\n               child_session(argv) if session_type == 'child' else\n               None)\n    if not session:\n        raise Exception('Unknown session type \"%s\"' % session_type)\n    if decode is None:\n        decode = IS_PYTHON3\n    return Nvim.from_session(session).with_decode(decode)",
    "docstring": "Provide a nicer interface to create python api sessions.\n\n    Previous machinery to create python api sessions is still there. This only\n    creates a facade function to make things easier for the most usual cases.\n    Thus, instead of:\n        from pynvim import socket_session, Nvim\n        session = tcp_session(address=<address>, port=<port>)\n        nvim = Nvim.from_session(session)\n    You can now do:\n        from pynvim import attach\n        nvim = attach('tcp', address=<address>, port=<port>)\n    And also:\n        nvim = attach('socket', path=<path>)\n        nvim = attach('child', argv=<argv>)\n        nvim = attach('stdio')\n\n    When the session is not needed anymore, it is recommended to explicitly\n    close it:\n       nvim.close()\n    It is also possible to use the session as a context mangager:\n       with attach('socket', path=thepath) as nvim:\n           print(nvim.funcs.getpid())\n           print(nvim.current.line)\n    This will automatically close the session when you're done with it, or\n    when an error occured."
  },
  {
    "code": "def _open_tracing_interface(self, conn_id, callback):\n        try:\n            handle = self._find_handle(conn_id)\n            services = self._connections[handle]['services']\n        except (ValueError, KeyError):\n            callback(conn_id, self.id, False, 'Connection closed unexpectedly before we could open the streaming interface')\n            return\n        self._command_task.async_command(['_enable_tracing', handle, services],\n                                         self._on_interface_finished, {'connection_id': conn_id, 'callback': callback})",
    "docstring": "Enable the debug tracing interface for this IOTile device\n\n        Args:\n            conn_id (int): the unique identifier for the connection\n            callback (callback): Callback to be called when this command finishes\n                callback(conn_id, adapter_id, success, failure_reason)"
  },
  {
    "code": "def dehydrate_point(value):\n    dim = len(value)\n    if dim == 2:\n        return Structure(b\"X\", value.srid, *value)\n    elif dim == 3:\n        return Structure(b\"Y\", value.srid, *value)\n    else:\n        raise ValueError(\"Cannot dehydrate Point with %d dimensions\" % dim)",
    "docstring": "Dehydrator for Point data.\n\n    :param value:\n    :type value: Point\n    :return:"
  },
  {
    "code": "def construct_optional_traversal_tree(complex_optional_roots, location_to_optional_roots):\n    tree = OptionalTraversalTree(complex_optional_roots)\n    for optional_root_locations_stack in six.itervalues(location_to_optional_roots):\n        tree.insert(list(optional_root_locations_stack))\n    return tree",
    "docstring": "Return a tree of complex optional root locations.\n\n    Args:\n        complex_optional_roots: list of @optional locations (location immmediately preceding\n                                an @optional Traverse) that expand vertex fields\n        location_to_optional_roots: dict mapping from location -> optional_roots where location is\n                                    within some number of @optionals and optional_roots is a list\n                                    of optional root locations preceding the successive @optional\n                                    scopes within which the location resides\n\n    Returns:\n        OptionalTraversalTree object representing the tree of complex optional roots"
  },
  {
    "code": "def run_std_server(self):\n    config = tf.estimator.RunConfig()\n    server = tf.train.Server(\n        config.cluster_spec,\n        job_name=config.task_type,\n        task_index=config.task_id,\n        protocol=config.protocol)\n    server.join()",
    "docstring": "Starts a TensorFlow server and joins the serving thread.\n\n    Typically used for parameter servers.\n\n    Raises:\n      ValueError: if not enough information is available in the estimator's\n        config to create a server."
  },
  {
    "code": "def _checkremove_que(self, word):\n        in_que_pass_list = False\n        que_pass_list = ['atque',\n                        'quoque',\n                        'neque',\n                        'itaque',\n                        'absque',\n                        'apsque',\n                        'abusque',\n                        'adaeque',\n                        'adusque',\n                        'denique',\n                        'deque',\n                        'susque',\n                        'oblique',\n                        'peraeque',\n                        'plenisque',\n                        'quandoque',\n                        'quisque',\n                        'quaeque',\n                        'cuiusque',\n                        'cuique',\n                        'quemque',\n                        'quamque',\n                        'quaque',\n                        'quique',\n                        'quorumque',\n                        'quarumque',\n                        'quibusque',\n                        'quosque',\n                        'quasque',\n                        'quotusquisque',\n                        'quousque',\n                        'ubique',\n                        'undique',\n                        'usque',\n                        'uterque',\n                        'utique',\n                        'utroque',\n                        'utribique',\n                        'torque',\n                        'coque',\n                        'concoque',\n                        'contorque',\n                        'detorque',\n                        'decoque',\n                        'excoque',\n                        'extorque',\n                        'obtorque',\n                        'optorque',\n                        'retorque',\n                        'recoque',\n                        'attorque',\n                        'incoque',\n                        'intorque',\n                        'praetorque']\n        if word not in que_pass_list:\n            word = re.sub(r'que$', '', word)\n        else:\n            in_que_pass_list = True\n        return word, in_que_pass_list",
    "docstring": "If word ends in -que and if word is not in pass list, strip -que"
  },
  {
    "code": "def update_firewall_rule(self, firewall_rule, body=None):\n        return self.put(self.firewall_rule_path % (firewall_rule), body=body)",
    "docstring": "Updates a firewall rule."
  },
  {
    "code": "def _PrepareAttributeContainer(self, attribute_container):\n    attribute_values_hash = hash(attribute_container.GetAttributeValuesString())\n    identifier = identifiers.FakeIdentifier(attribute_values_hash)\n    attribute_container.SetIdentifier(identifier)\n    return copy.deepcopy(attribute_container)",
    "docstring": "Prepares an attribute container for storage.\n\n    Args:\n      attribute_container (AttributeContainer): attribute container.\n\n    Returns:\n      AttributeContainer: copy of the attribute container to store in\n          the fake storage."
  },
  {
    "code": "def _eq_dicts(d1, d2):\n        if not d1.keys() == d2.keys():\n            return False\n        for k, v1 in d1.items():\n            v2 = d2[k]\n            if not type(v1) == type(v2):\n                return False\n            if isinstance(v1, np.ndarray):\n                if not np.array_equal(v1, v2):\n                    return False\n            else:\n                if not v1 == v2:\n                    return False\n        return True",
    "docstring": "Returns True if d1 == d2, False otherwise"
  },
  {
    "code": "def virtual_interface_list(provider, names, **kwargs):\n    client = _get_client()\n    return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs)",
    "docstring": "List virtual interfaces on a server\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt minionname cloud.virtual_interface_list my-nova names=['salt-master']"
  },
  {
    "code": "def _param_deprecation_warning(schema, deprecated, context):\r\n    for i in deprecated:\r\n        if i in schema:\r\n                msg = 'When matching {ctx}, parameter {word} is deprecated, use __{word}__ instead'\r\n                msg = msg.format(ctx = context, word = i)\r\n                warnings.warn(msg, Warning)",
    "docstring": "Raises warning about using the 'old' names for some parameters.\r\n\r\n    The new naming scheme just has two underscores on each end of the word for consistency"
  },
  {
    "code": "def get_root_resource(config):\n    app_package_name = get_app_package_name(config)\n    return config.registry._root_resources.setdefault(\n        app_package_name, Resource(config))",
    "docstring": "Returns the root resource."
  },
  {
    "code": "def split_box( fraction, x,y, w,h ):\n    if w >= h:\n        new_w = int(w*fraction)\n        if new_w:\n            return (x,y,new_w,h),(x+new_w,y,w-new_w,h)\n        else:\n            return None,None\n    else:\n        new_h = int(h*fraction)\n        if new_h:\n            return (x,y,w,new_h),(x,y+new_h,w,h-new_h)\n        else:\n            return None,None",
    "docstring": "Return set of two boxes where first is the fraction given"
  },
  {
    "code": "def node_to_object(self, node, object):\n        \"Map a single node to one object's attributes\"\n        attribute = self.to_lower(node.tag)\n        attribute = \"_yield\" if attribute == \"yield\" else attribute\n        try:\n            valueString = node.text or \"\"\n            value = float(valueString)\n        except ValueError:\n            value = node.text\n        try:\n            setattr(object, attribute, value)\n        except AttributeError():\n            sys.stderr.write(\"Attribute <%s> not supported.\" % attribute)",
    "docstring": "Map a single node to one object's attributes"
  },
  {
    "code": "def shrink (self):\n        trim = int(0.05*len(self))\n        if trim:\n            items = super(LFUCache, self).items()\n            keyfunc = lambda x: x[1][0]\n            values = sorted(items, key=keyfunc)\n            for item in values[0:trim]:\n                del self[item[0]]",
    "docstring": "Shrink ca. 5% of entries."
  },
  {
    "code": "def update_beta(self, beta):\n        r\n        if self._safeguard:\n            beta *= self.xi_restart\n            beta = max(beta, self.min_beta)\n        return beta",
    "docstring": "r\"\"\"Update beta\n\n        This method updates beta only in the case of safeguarding (should only\n        be done in the greedy restarting strategy).\n\n        Parameters\n        ----------\n        beta: float\n            The beta parameter\n\n        Returns\n        -------\n        float: the new value for the beta parameter"
  },
  {
    "code": "def browse_home_listpage_url(self,\n                                 state=None,\n                                 county=None,\n                                 zipcode=None,\n                                 street=None,\n                                 **kwargs):\n        url = self.domain_browse_homes\n        for item in [state, county, zipcode, street]:\n            if item:\n                url = url + \"/%s\" % item\n        url = url + \"/\"\n        return url",
    "docstring": "Construct an url of home list page by state, county, zipcode, street.\n\n        Example:\n\n        - https://www.zillow.com/browse/homes/ca/\n        - https://www.zillow.com/browse/homes/ca/los-angeles-county/\n        - https://www.zillow.com/browse/homes/ca/los-angeles-county/91001/\n        - https://www.zillow.com/browse/homes/ca/los-angeles-county/91001/tola-ave_5038895/"
  },
  {
    "code": "def makeStylesheetResource(self, path, registry):\n        return StylesheetRewritingResourceWrapper(\n            File(path), self.installedOfferingNames, self.rootURL)",
    "docstring": "Return a resource for the css at the given path with its urls rewritten\n        based on self.rootURL."
  },
  {
    "code": "def _find_special(self):\n        charnames = self._get_char_names()\n        for eventdir in glob.glob('/sys/class/input/event*'):\n            char_name = os.path.split(eventdir)[1]\n            if char_name in charnames:\n                continue\n            name_file = os.path.join(eventdir, 'device', 'name')\n            with open(name_file) as name_file:\n                device_name = name_file.read().strip()\n                if device_name in self.codes['specials']:\n                    self._parse_device_path(\n                        self.codes['specials'][device_name],\n                        os.path.join('/dev/input', char_name))",
    "docstring": "Look for special devices."
  },
  {
    "code": "def toList(value, itemcast=None, delim=','):\n    value = value or ''\n    itemcast = itemcast or str\n    return [itemcast(item) for item in value.split(delim) if item != '']",
    "docstring": "Returns a list of strings from the specified value.\n\n        Parameters:\n            value (str): comma delimited string to convert to list.\n            itemcast (func): Function to cast each list item to (default str).\n            delim (str): string delimiter (optional; default ',')."
  },
  {
    "code": "def exception_format():\n    return \"\".join(traceback.format_exception(\n        sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]\n    ))",
    "docstring": "Convert exception info into a string suitable for display."
  },
  {
    "code": "def log_exception(func, handler, args, kwargs):\n    value = args[1] if len(args) == 3 else None\n    if value is None:\n        return func(*args, **kwargs)\n    tracing = handler.settings.get('opentracing_tracing')\n    if not isinstance(value, HTTPError) or 500 <= value.status_code <= 599:\n        tracing._finish_tracing(handler, error=value)\n    return func(*args, **kwargs)",
    "docstring": "Wrap the handler ``log_exception`` method to finish the Span for the\n    given request, if available. This method is called when an Exception\n    is not handled in the user code."
  },
  {
    "code": "def config_status():\n    s = boto3.Session()\n    client = s.client('config')\n    channels = client.describe_delivery_channel_status()[\n        'DeliveryChannelsStatus']\n    for c in channels:\n        print(yaml.safe_dump({\n            c['name']: dict(\n                snapshot=str(\n                    c['configSnapshotDeliveryInfo'].get('lastSuccessfulTime')),\n                history=str(\n                    c['configHistoryDeliveryInfo'].get('lastSuccessfulTime')),\n                stream=str(\n                    c['configStreamDeliveryInfo'].get('lastStatusChangeTime'))\n            ),\n        }, default_flow_style=False))",
    "docstring": "Check config status in an account."
  },
  {
    "code": "def cublasZsyrk(handle, uplo, trans, n, k, alpha, A, lda, beta, C, ldc):\n    status = _libcublas.cublasZsyrk_v2(handle,\n                                       _CUBLAS_FILL_MODE[uplo], \n                                       _CUBLAS_OP[trans], \n                                       n, k, ctypes.byref(cuda.cuDoubleComplex(alpha.real,    \n                                                                               alpha.imag)),\n                                       int(A), lda,\n                                       ctypes.byref(cuda.cuDoubleComplex(beta.real,\n                                                                         beta.imag)),\n                                       int(C), ldc)\n    cublasCheckStatus(status)",
    "docstring": "Rank-k operation on complex symmetric matrix."
  },
  {
    "code": "def apply_new_scoped_variable_default_value(self, path, new_default_value_str):\n        data_port_id = self.get_list_store_row_from_cursor_selection()[self.ID_STORAGE_ID]\n        try:\n            if str(self.model.state.scoped_variables[data_port_id].default_value) != new_default_value_str:\n                self.model.state.scoped_variables[data_port_id].default_value = new_default_value_str\n        except (TypeError, AttributeError) as e:\n            logger.error(\"Error while changing default value: {0}\".format(e))",
    "docstring": "Applies the new default value of the scoped variable defined by path\n\n        :param str path: The path identifying the edited variable\n        :param str new_default_value_str: New default value as string"
  },
  {
    "code": "def _get_kwarg(self, name, kwargs):\n        at_name = '@{}'.format(name)\n        if name in kwargs:\n            if at_name in kwargs:\n                raise ValueError('Both {!r} and {!r} specified in kwargs'.format(name, at_name))\n            return kwargs[name]\n        if at_name in kwargs:\n            return kwargs[at_name]\n        return not_set",
    "docstring": "Helper to get value of a named attribute irrespective of whether it is passed\n        with or without \"@\" prefix."
  },
  {
    "code": "def finger_master(hash_type=None):\n    keyname = 'master.pub'\n    if hash_type is None:\n        hash_type = __opts__['hash_type']\n    fingerprint = salt.utils.crypt.pem_finger(\n        os.path.join(__opts__['pki_dir'], keyname), sum_type=hash_type)\n    return {'local': {keyname: fingerprint}}",
    "docstring": "Return the fingerprint of the master's public key\n\n    hash_type\n        The hash algorithm used to calculate the fingerprint\n\n    .. code-block:: python\n\n        >>> wheel.cmd('key.finger_master')\n        {'local': {'master.pub': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}"
  },
  {
    "code": "def main():\n    outf=\"\"\n    N=100\n    if '-h' in sys.argv:\n        print(main.__doc__)\n        sys.exit()\n    if '-F' in sys.argv:\n        ind=sys.argv.index('-F')\n        outf=sys.argv[ind+1]\n    if outf!=\"\": out=open(outf,'w')\n    if '-n' in sys.argv:\n        ind=sys.argv.index('-n')\n        N=int(sys.argv[ind+1])\n    dirs=pmag.get_unf(N)\n    if outf=='':\n        for dir in dirs:\n            print('%7.1f %7.1f'%(dir[0],dir[1]))\n    else:\n        numpy.savetxt(outf,dirs,fmt='%7.1f %7.1f')",
    "docstring": "NAME\n        uniform.py\n\n    DESCRIPTION\n        draws N directions from uniform distribution on a sphere\n    \n    SYNTAX \n        uniform.py [-h][command line options]\n        -h prints help message and quits\n        -n N, specify N on the command line (default is 100)\n        -F file, specify output file name, default is standard output"
  },
  {
    "code": "def structured_iterator(failure_lines):\n    summary = partial(failure_line_summary, TbplFormatter())\n    for failure_line in failure_lines:\n        repr_str = summary(failure_line)\n        if repr_str:\n            yield failure_line, repr_str\n    while True:\n        yield None, None",
    "docstring": "Create FailureLine, Tbpl-formatted-string tuples."
  },
  {
    "code": "def build_self_uri_list(self_uri_list):\n    \"parse the self-uri tags, build Uri objects\"\n    uri_list = []\n    for self_uri in self_uri_list:\n        uri = ea.Uri()\n        utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))\n        utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))\n        uri_list.append(uri)\n    return uri_list",
    "docstring": "parse the self-uri tags, build Uri objects"
  },
  {
    "code": "def check_option(self, key, subkey, value):\n        key, subkey = _lower_keys(key, subkey)\n        _entry_must_exist(self.gc, key, subkey)\n        df = self.gc[(self.gc[\"k1\"] == key) & (self.gc[\"k2\"] == subkey)]\n        ev.value_eval(value, df[\"type\"].values[0])\n        if df[\"values\"].values[0] is not None:\n            return value in df[\"values\"].values[0]\n        return True",
    "docstring": "Evaluate if a given value fits the option.\n\n        If an option has a limited set of available values, check if the\n        provided value is amongst them.\n\n        :param str key: First identifier of the option.\n        :param str subkey: Second identifier of the option.\n        :param value: Value to test (type varies).\n\n        :return: :class:`bool` - does ``value`` belong to the options?\n\n        :raise:\n            :NotRegisteredError: If ``key`` or ``subkey`` do not define any\n                option.\n            :ValueError: If the provided value is not the expected\n                type for the option."
  },
  {
    "code": "def cut_matrix(self, n):\n        cm = np.zeros((n, n))\n        for part in self.partition:\n            from_, to = self.direction.order(part.mechanism, part.purview)\n            external = tuple(set(self.indices) - set(to))\n            cm[np.ix_(from_, external)] = 1\n        return cm",
    "docstring": "The matrix of connections that are severed by this cut."
  },
  {
    "code": "def unmatched_brackets_in_line(self, text, closing_brackets_type=None):\n        if closing_brackets_type is None:\n            opening_brackets = self.BRACKETS_LEFT.values()\n            closing_brackets = self.BRACKETS_RIGHT.values()\n        else:\n            closing_brackets = [closing_brackets_type]\n            opening_brackets = [{')': '(', '}': '{',\n                                 ']': '['}[closing_brackets_type]]\n        block = self.editor.textCursor().block()\n        line_pos = block.position()\n        for pos, char in enumerate(text):\n            if char in opening_brackets:\n                match = self.editor.find_brace_match(line_pos+pos, char,\n                                                     forward=True)\n                if (match is None) or (match > line_pos+len(text)):\n                    return True\n            if char in closing_brackets:\n                match = self.editor.find_brace_match(line_pos+pos, char,\n                                                     forward=False)\n                if (match is None) or (match < line_pos):\n                    return True\n        return False",
    "docstring": "Checks if there is an unmatched brackets in the 'text'.\n\n        The brackets type can be general or specified by closing_brackets_type\n        (')', ']' or '}')"
  },
  {
    "code": "def registercls(self, data_types, schemacls=None):\n        if schemacls is None:\n            return lambda schemacls: self.registercls(\n                data_types=data_types, schemacls=schemacls\n            )\n        for data_type in data_types:\n            self._schbytype[data_type] = schemacls\n        return schemacls",
    "docstring": "Register schema class with associated data_types.\n\n        Can be used such as a decorator.\n\n        :param list data_types: data types to associate with schema class.\n        :param type schemacls: schema class to register.\n        :return: schemacls.\n        :rtype: type"
  },
  {
    "code": "def table_describe(table_name):\n    desc = orca.get_table(table_name).to_frame().describe()\n    return (\n        desc.to_json(orient='split', date_format='iso'),\n        200,\n        {'Content-Type': 'application/json'})",
    "docstring": "Return summary statistics of a table as JSON. Includes all columns.\n    Uses Pandas' \"split\" JSON format."
  },
  {
    "code": "def _update_trial_queue(self, blocking=False, timeout=600):\n        trials = self._search_alg.next_trials()\n        if blocking and not trials:\n            start = time.time()\n            while (not trials and not self.is_finished()\n                   and time.time() - start < timeout):\n                logger.info(\"Blocking for next trial...\")\n                trials = self._search_alg.next_trials()\n                time.sleep(1)\n        for trial in trials:\n            self.add_trial(trial)",
    "docstring": "Adds next trials to queue if possible.\n\n        Note that the timeout is currently unexposed to the user.\n\n        Args:\n            blocking (bool): Blocks until either a trial is available\n                or is_finished (timeout or search algorithm finishes).\n            timeout (int): Seconds before blocking times out."
  },
  {
    "code": "def _zip_with_scalars(args):\n  zipped = []\n  for arg in args:\n    if isinstance(arg, prettytensor.PrettyTensor):\n      zipped.append(arg if arg.is_sequence() else itertools.repeat(arg))\n    elif (isinstance(arg, collections.Sequence) and\n          not isinstance(arg, tf.compat.bytes_or_text_types)):\n      zipped.append(arg)\n    else:\n      zipped.append(itertools.repeat(arg))\n  assert len(args) == len(zipped)\n  return zip(*zipped)",
    "docstring": "Zips across args in order and replaces non-iterables with repeats."
  },
  {
    "code": "def camelcase_to_underscores(argument):\n    result = ''\n    prev_char_title = True\n    if not argument:\n        return argument\n    for index, char in enumerate(argument):\n        try:\n            next_char_title = argument[index + 1].istitle()\n        except IndexError:\n            next_char_title = True\n        upper_to_lower = char.istitle() and not next_char_title\n        lower_to_upper = char.istitle() and not prev_char_title\n        if index and (upper_to_lower or lower_to_upper):\n            result += \"_\"\n        prev_char_title = char.istitle()\n        if not char.isspace():\n            result += char.lower()\n    return result",
    "docstring": "Converts a camelcase param like theNewAttribute to the equivalent\n    python underscore variable like the_new_attribute"
  },
  {
    "code": "def to_str(instance, encoding='utf-8'):\n    if isinstance(instance, str):\n        return instance\n    elif hasattr(instance, 'decode'):\n        return instance.decode(encoding)\n    elif isinstance(instance, list):\n        return list([to_str(item, encoding) for item in instance])\n    elif isinstance(instance, tuple):\n        return tuple([to_str(item, encoding) for item in instance])\n    elif isinstance(instance, dict):\n        return dict(\n            [(to_str(key, encoding), to_str(value, encoding))\n                for key, value in instance.items()])\n    else:\n        return instance",
    "docstring": "Convert an instance recursively to string."
  },
  {
    "code": "def _domain_event_block_job_cb(conn, domain, disk, job_type, status, opaque):\n    _salt_send_domain_event(opaque, conn, domain, opaque['event'], {\n        'disk': disk,\n        'type': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_TYPE_', job_type),\n        'status': _get_libvirt_enum_string('VIR_DOMAIN_BLOCK_JOB_', status)\n    })",
    "docstring": "Domain block job events handler"
  },
  {
    "code": "def get(self, country_code):\n        return AvailablePhoneNumberCountryContext(\n            self._version,\n            account_sid=self._solution['account_sid'],\n            country_code=country_code,\n        )",
    "docstring": "Constructs a AvailablePhoneNumberCountryContext\n\n        :param country_code: The ISO country code of the country to fetch available phone number information about\n\n        :returns: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryContext\n        :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryContext"
  },
  {
    "code": "def authorize_security_group(self, group_name=None,\n                                 src_security_group_name=None,\n                                 src_security_group_owner_id=None,\n                                 ip_protocol=None, from_port=None, to_port=None,\n                                 cidr_ip=None, group_id=None,\n                                 src_security_group_group_id=None):\n        if src_security_group_name:\n            if from_port is None and to_port is None and ip_protocol is None:\n                return self.authorize_security_group_deprecated(\n                    group_name, src_security_group_name,\n                    src_security_group_owner_id)\n        params = {}\n        if group_name:\n            params['GroupName'] = group_name\n        if group_id:\n            params['GroupId'] = group_id\n        if src_security_group_name:\n            param_name = 'IpPermissions.1.Groups.1.GroupName'\n            params[param_name] = src_security_group_name\n        if src_security_group_owner_id:\n            param_name = 'IpPermissions.1.Groups.1.UserId'\n            params[param_name] = src_security_group_owner_id\n        if src_security_group_group_id:\n            param_name = 'IpPermissions.1.Groups.1.GroupId'\n            params[param_name] = src_security_group_group_id\n        if ip_protocol:\n            params['IpPermissions.1.IpProtocol'] = ip_protocol\n        if from_port is not None:\n            params['IpPermissions.1.FromPort'] = from_port\n        if to_port is not None:\n            params['IpPermissions.1.ToPort'] = to_port\n        if cidr_ip:\n            params['IpPermissions.1.IpRanges.1.CidrIp'] = cidr_ip\n        return self.get_status('AuthorizeSecurityGroupIngress',\n                               params, verb='POST')",
    "docstring": "Add a new rule to an existing security group.\n        You need to pass in either src_security_group_name and\n        src_security_group_owner_id OR ip_protocol, from_port, to_port,\n        and cidr_ip.  In other words, either you are authorizing another\n        group or you are authorizing some ip-based rule.\n\n        :type group_name: string\n        :param group_name: The name of the security group you are adding\n                           the rule to.\n\n        :type src_security_group_name: string\n        :param src_security_group_name: The name of the security group you are\n                                        granting access to.\n\n        :type src_security_group_owner_id: string\n        :param src_security_group_owner_id: The ID of the owner of the security\n                                            group you are granting access to.\n\n        :type ip_protocol: string\n        :param ip_protocol: Either tcp | udp | icmp\n\n        :type from_port: int\n        :param from_port: The beginning port number you are enabling\n\n        :type to_port: int\n        :param to_port: The ending port number you are enabling\n\n        :type cidr_ip: string\n        :param cidr_ip: The CIDR block you are providing access to.\n                        See http://goo.gl/Yj5QC\n\n        :type group_id: string\n        :param group_id: ID of the EC2 or VPC security group to modify.\n                         This is required for VPC security groups and\n                         can be used instead of group_name for EC2\n                         security groups.\n\n        :type group_id: string\n        :param group_id: ID of the EC2 or VPC source security group.\n                         This is required for VPC security groups and\n                         can be used instead of group_name for EC2\n                         security groups.\n\n        :rtype: bool\n        :return: True if successful."
  },
  {
    "code": "def expression(callable, rule_name, grammar):\n    num_args = len(getargspec(callable).args)\n    if num_args == 2:\n        is_simple = True\n    elif num_args == 5:\n        is_simple = False\n    else:\n        raise RuntimeError(\"Custom rule functions must take either 2 or 5 \"\n                           \"arguments, not %s.\" % num_args)\n    class AdHocExpression(Expression):\n        def _uncached_match(self, text, pos, cache, error):\n            result = (callable(text, pos) if is_simple else\n                      callable(text, pos, cache, error, grammar))\n            if isinstance(result, integer_types):\n                end, children = result, None\n            elif isinstance(result, tuple):\n                end, children = result\n            else:\n                return result\n            return Node(self, text, pos, end, children=children)\n        def _as_rhs(self):\n            return '{custom function \"%s\"}' % callable.__name__\n    return AdHocExpression(name=rule_name)",
    "docstring": "Turn a plain callable into an Expression.\n\n    The callable can be of this simple form::\n\n        def foo(text, pos):\n            '''If this custom expression matches starting at text[pos], return\n            the index where it stops matching. Otherwise, return None.'''\n            if the expression matched:\n                return end_pos\n\n    If there child nodes to return, return a tuple::\n\n        return end_pos, children\n\n    If the expression doesn't match at the given ``pos`` at all... ::\n\n        return None\n\n    If your callable needs to make sub-calls to other rules in the grammar or\n    do error reporting, it can take this form, gaining additional arguments::\n\n        def foo(text, pos, cache, error, grammar):\n            # Call out to other rules:\n            node = grammar['another_rule'].match_core(text, pos, cache, error)\n            ...\n            # Return values as above.\n\n    The return value of the callable, if an int or a tuple, will be\n    automatically transmuted into a :class:`~parsimonious.Node`. If it returns\n    a Node-like class directly, it will be passed through unchanged.\n\n    :arg rule_name: The rule name to attach to the resulting\n        :class:`~parsimonious.Expression`\n    :arg grammar: The :class:`~parsimonious.Grammar` this expression will be a\n        part of, to make delegating to other rules possible"
  },
  {
    "code": "def get_options(server):\n    try:\n        response = requests.options(\n            server, allow_redirects=False, verify=False, timeout=5)\n    except (requests.exceptions.ConnectionError,\n            requests.exceptions.MissingSchema):\n        return \"Server {} is not available!\".format(server)\n    try:\n        return {'allowed': response.headers['Allow']}\n    except KeyError:\n        return \"Unable to get HTTP methods\"",
    "docstring": "Retrieve the available HTTP verbs"
  },
  {
    "code": "def _recv_ack(self, method_frame):\n        if self._ack_listener:\n            delivery_tag = method_frame.args.read_longlong()\n            multiple = method_frame.args.read_bit()\n            if multiple:\n                while self._last_ack_id < delivery_tag:\n                    self._last_ack_id += 1\n                    self._ack_listener(self._last_ack_id)\n            else:\n                self._last_ack_id = delivery_tag\n                self._ack_listener(self._last_ack_id)",
    "docstring": "Receive an ack from the broker."
  },
  {
    "code": "def get_scc_from_tuples(constraints):\n    classes = unionfind.classes(constraints)\n    return dict((x, tuple(c)) for x, c in classes.iteritems())",
    "docstring": "Given set of equivalences, return map of transitive equivalence classes.\n\n    >> constraints = [(1,2), (2,3)]\n    >> get_scc_from_tuples(constraints)\n    {\n        1: (1, 2, 3),\n        2: (1, 2, 3),\n        3: (1, 2, 3),\n    }"
  },
  {
    "code": "def overlap_slices(large_array_shape, small_array_shape, position):\n    edges_min = [int(pos - small_shape // 2) for (pos, small_shape) in\n                 zip(position, small_array_shape)]\n    edges_max = [int(pos + (small_shape - small_shape // 2)) for\n                 (pos, small_shape) in\n                 zip(position, small_array_shape)]\n    slices_large = tuple(slice(max(0, edge_min), min(large_shape, edge_max))\n                         for (edge_min, edge_max, large_shape) in\n                         zip(edges_min, edges_max, large_array_shape))\n    slices_small = tuple(slice(max(0, -edge_min),\n                               min(large_shape - edge_min,\n                                   edge_max - edge_min))\n                         for (edge_min, edge_max, large_shape) in\n                         zip(edges_min, edges_max, large_array_shape))\n    return slices_large, slices_small",
    "docstring": "Modified version of `~astropy.nddata.utils.overlap_slices`.\n\n    Get slices for the overlapping part of a small and a large array.\n\n    Given a certain position of the center of the small array, with\n    respect to the large array, tuples of slices are returned which can be\n    used to extract, add or subtract the small array at the given\n    position. This function takes care of the correct behavior at the\n    boundaries, where the small array is cut of appropriately.\n\n    Parameters\n    ----------\n    large_array_shape : tuple\n        Shape of the large array.\n    small_array_shape : tuple\n        Shape of the small array.\n    position : tuple\n        Position of the small array's center, with respect to the large array.\n        Coordinates should be in the same order as the array shape.\n\n    Returns\n    -------\n    slices_large : tuple of slices\n        Slices in all directions for the large array, such that\n        ``large_array[slices_large]`` extracts the region of the large array\n        that overlaps with the small array.\n    slices_small : slice\n        Slices in all directions for the small array, such that\n        ``small_array[slices_small]`` extracts the region that is inside the\n        large array."
  },
  {
    "code": "def synthesize(self, modules, use_string, x64, native):\n        print(hash_func)\n        groups = group_by(modules, ends_with_punctuation)\n        sources = self.make_source(groups, self.database)\n        if sources:\n            return stylify_files(\n                {'defs.h': sources[0], 'init.c': sources[1]}\n            )\n        else:\n            return ''",
    "docstring": "Transform sources."
  },
  {
    "code": "async def punsubscribe(self, *args):\n        if args:\n            args = list_or_args(args[0], args[1:])\n        return await self.execute_command('PUNSUBSCRIBE', *args)",
    "docstring": "Unsubscribe from the supplied patterns. If empy, unsubscribe from\n        all patterns."
  },
  {
    "code": "def cli(env, identifier, body):\n    mgr = SoftLayer.TicketManager(env.client)\n    ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket')\n    if body is None:\n        body = click.edit('\\n\\n' + ticket.TEMPLATE_MSG)\n    mgr.update_ticket(ticket_id=ticket_id, body=body)\n    env.fout(\"Ticket Updated!\")",
    "docstring": "Adds an update to an existing ticket."
  },
  {
    "code": "def read(self, size=-1):\n        logger.debug(\"reading with size: %d\", size)\n        if self.response is None:\n            return b''\n        if size == 0:\n            return b''\n        elif size < 0 and len(self._read_buffer) == 0:\n            retval = self.response.raw.read()\n        elif size < 0:\n            retval = self._read_buffer.read() + self.response.raw.read()\n        else:\n            while len(self._read_buffer) < size:\n                logger.debug(\"http reading more content at current_pos: %d with size: %d\", self._current_pos, size)\n                bytes_read = self._read_buffer.fill(self._read_iter)\n                if bytes_read == 0:\n                    retval = self._read_buffer.read()\n                    self._current_pos += len(retval)\n                    return retval\n            retval = self._read_buffer.read(size)\n        self._current_pos += len(retval)\n        return retval",
    "docstring": "Mimics the read call to a filehandle object."
  },
  {
    "code": "def get_source_handler(self, model, source):\n        if isinstance(source, Column):\n            return source\n        modelfield = resolve_orm_path(model, source)\n        column_class = get_column_for_modelfield(modelfield)\n        return column_class()",
    "docstring": "Allow the nested Column source to be its own handler."
  },
  {
    "code": "def confusion_matrix(self):\n        return plot.confusion_matrix(self.y_true, self.y_pred,\n                                     self.target_names, ax=_gen_ax())",
    "docstring": "Confusion matrix plot"
  },
  {
    "code": "def to_api_repr(self):\n        config = copy.deepcopy(self._properties)\n        if self.options is not None:\n            r = self.options.to_api_repr()\n            if r != {}:\n                config[self.options._RESOURCE_NAME] = r\n        return config",
    "docstring": "Build an API representation of this object.\n\n        Returns:\n            Dict[str, Any]:\n                A dictionary in the format used by the BigQuery API."
  },
  {
    "code": "def xiphias_get_users_by_alias(self, alias_jids: Union[str, List[str]]):\n        return self._send_xmpp_element(xiphias.UsersByAliasRequest(alias_jids))",
    "docstring": "Like xiphias_get_users, but for aliases instead of jids.\n\n        :param alias_jids: one jid, or a list of jids"
  },
  {
    "code": "def _create_url(self, date):\n        return BOXSCORES_URL % (date.year, date.month, date.day)",
    "docstring": "Build the URL based on the passed datetime object.\n\n        In order to get the proper boxscore page, the URL needs to include the\n        requested month, day, and year.\n\n        Parameters\n        ----------\n        date : datetime object\n            The date to search for any matches. The month, day, and year are\n            required for the search, but time is not factored into the search.\n\n        Returns\n        -------\n        string\n            Returns a ``string`` of the boxscore URL including the requested\n            date."
  },
  {
    "code": "def get_section_by_name(self, section_name):\n        sections = self.unravel_sections(self.get_sections())\n        for section in sections:\n            if section['name'] == section_name:\n                return section['groupId'], section\n        return None, None",
    "docstring": "Get a section by its name.\n\n        Get a list of sections for a given gradebook,\n        specified by a gradebookid.\n\n        Args:\n            section_name (str): The section's name.\n\n        Raises:\n            requests.RequestException: Exception connection error\n            ValueError: Unable to decode response content\n\n        Returns:\n            tuple: tuple of group id, and section dictionary\n\n            An example return value is:\n\n            .. code-block:: python\n\n                (\n                    1327565,\n                    {\n                        u'editable': True,\n                        u'groupId': 1327565,\n                        u'groupingScheme': u'Recitation',\n                        u'members': None,\n                        u'name': u'r01',\n                        u'shortName': u'r01',\n                        u'staffs': None\n                    }\n                )"
  },
  {
    "code": "def GetName(self):\n        if self.AssetType == AssetType.GoverningToken:\n            return \"NEO\"\n        elif self.AssetType == AssetType.UtilityToken:\n            return \"NEOGas\"\n        if type(self.Name) is bytes:\n            return self.Name.decode('utf-8')\n        return self.Name",
    "docstring": "Get the asset name based on its type.\n\n        Returns:\n            str: 'NEO' or 'NEOGas'"
  },
  {
    "code": "def _parse(string):\n    if string:\n        return suds.sax.parser.Parser().parse(string=string)",
    "docstring": "Parses given XML document content.\n\n    Returns the resulting root XML element node or None if the given XML\n    content is empty.\n\n    @param string: XML document content to parse.\n    @type string: I{bytes}\n    @return: Resulting root XML element node or None.\n    @rtype: L{Element}|I{None}"
  },
  {
    "code": "def provision(self, tool: Tool) -> docker.models.containers.Container:\n        if not self.is_installed(tool):\n            raise Exception(\"tool is not installed: {}\".format(tool.name))\n        client = self.__installation.docker\n        return client.containers.create(tool.image)",
    "docstring": "Provisions a mountable Docker container for a given tool."
  },
  {
    "code": "def get_audits():\n    audits = [TemplatedFile('/etc/login.defs', LoginContext(),\n                            template_dir=TEMPLATES_DIR,\n                            user='root', group='root', mode=0o0444)]\n    return audits",
    "docstring": "Get OS hardening login.defs audits.\n\n    :returns:  dictionary of audits"
  },
  {
    "code": "def to_python_(self, table_name: str=\"data\") -> list:\n        try:\n            renderer = pytablewriter.PythonCodeTableWriter\n            data = self._build_export(renderer, table_name)\n            return data\n        except Exception as e:\n            self.err(e, \"Can not convert data to python list\")",
    "docstring": "Convert the main dataframe to python a python list\n\n        :param table_name: python variable name, defaults to \"data\"\n        :param table_name: str, optional\n        :return: a python list of lists with the data\n        :rtype: str\n\n        :example: ``ds.to_python_(\"myvar\")``"
  },
  {
    "code": "def is_valid(self):\n        return (self.is_primitive and self.name) \\\n            or (self.is_complex and self.name) \\\n            or (self.is_list and self.nested) \\\n            or (self.is_map and self.nested) \\\n            or (self.is_model and self.nested)",
    "docstring": "checks if type is a valid type"
  },
  {
    "code": "def _request(self, function, params, method='POST', headers={}):\n        if method is 'POST':\n            params = urllib.parse.urlencode(params)\n            headers = { \"Content-type\": \"application/x-www-form-urlencoded\", \"Accept\": \"text/plain\" }\n        path = '/%s/%s' % (self._version, function)\n        self._conn.request(method, path, params, headers)\n        return self._conn.getresponse()",
    "docstring": "Builds a request object."
  },
  {
    "code": "def from_inline(cls: Type[RevocationType], version: int, currency: str, inline: str) -> RevocationType:\n        cert_data = Revocation.re_inline.match(inline)\n        if cert_data is None:\n            raise MalformedDocumentError(\"Revokation\")\n        pubkey = cert_data.group(1)\n        signature = cert_data.group(2)\n        return cls(version, currency, pubkey, signature)",
    "docstring": "Return Revocation document instance from inline string\n\n        Only self.pubkey is populated.\n        You must populate self.identity with an Identity instance to use raw/sign/signed_raw methods\n\n        :param version: Version number\n        :param currency: Name of the currency\n        :param inline: Inline document\n\n        :return:"
  },
  {
    "code": "def _prepare_env(self):\n        env = self.state.document.settings.env\n        if not hasattr(env, self.directive_name):\n            state = DirectiveState()\n            setattr(env, self.directive_name, state)\n        else:\n            state = getattr(env, self.directive_name)\n        return env, state",
    "docstring": "Setup the document's environment, if necessary."
  },
  {
    "code": "def multiply(self, x1, x2, out=None):\n        if out is None:\n            out = self.element()\n        if out not in self:\n            raise LinearSpaceTypeError('`out` {!r} is not an element of '\n                                       '{!r}'.format(out, self))\n        if x1 not in self:\n            raise LinearSpaceTypeError('`x1` {!r} is not an element of '\n                                       '{!r}'.format(x1, self))\n        if x2 not in self:\n            raise LinearSpaceTypeError('`x2` {!r} is not an element of '\n                                       '{!r}'.format(x2, self))\n        self._multiply(x1, x2, out)\n        return out",
    "docstring": "Return the pointwise product of ``x1`` and ``x2``.\n\n        Parameters\n        ----------\n        x1, x2 : `LinearSpaceElement`\n            Multiplicands in the product.\n        out : `LinearSpaceElement`, optional\n            Element to which the result is written.\n\n        Returns\n        -------\n        out : `LinearSpaceElement`\n            Product of the elements. If ``out`` was provided, the\n            returned object is a reference to it."
  },
  {
    "code": "def entropy_of_antennas(positions, normalize=False):\n    counter = Counter(p for p in positions)\n    raw_entropy = entropy(list(counter.values()))\n    n = len(counter)\n    if normalize and n > 1:\n        return raw_entropy / math.log(n)\n    else:\n        return raw_entropy",
    "docstring": "The entropy of visited antennas.\n\n    Parameters\n    ----------\n    normalize: boolean, default is False\n        Returns a normalized entropy between 0 and 1."
  },
  {
    "code": "def running_jobs(self, exit_on_error=True):\n        with self.handling_exceptions():\n            if self.using_jobs:\n                from concurrent.futures import ProcessPoolExecutor\n                try:\n                    with ProcessPoolExecutor(self.jobs) as self.executor:\n                        yield\n                finally:\n                    self.executor = None\n            else:\n                yield\n        if exit_on_error:\n            self.exit_on_error()",
    "docstring": "Initialize multiprocessing."
  },
  {
    "code": "def format_item(self, action, item_type='actor'):\n        obj = getattr(action, item_type)\n        return {\n            'id': self.get_uri(action, obj),\n            'url': self.get_url(action, obj),\n            'objectType': ContentType.objects.get_for_model(obj).name,\n            'displayName': text_type(obj)\n        }",
    "docstring": "Returns a formatted dictionary for an individual item based on the action and item_type."
  },
  {
    "code": "def load_table(self, table_name):\n        table_name = normalize_table_name(table_name)\n        with self.lock:\n            if table_name not in self._tables:\n                self._tables[table_name] = Table(self, table_name)\n            return self._tables.get(table_name)",
    "docstring": "Load a table.\n\n        This will fail if the tables does not already exist in the database. If\n        the table exists, its columns will be reflected and are available on\n        the :py:class:`Table <dataset.Table>` object.\n\n        Returns a :py:class:`Table <dataset.Table>` instance.\n        ::\n\n            table = db.load_table('population')"
  },
  {
    "code": "def macro2blackbox_outputs(self, macro_indices):\n        if not self.blackbox:\n            raise ValueError('System is not blackboxed')\n        return tuple(sorted(set(\n            self.macro2micro(macro_indices)\n        ).intersection(self.blackbox.output_indices)))",
    "docstring": "Given a set of macro elements, return the blackbox output elements\n        which compose these elements."
  },
  {
    "code": "def perform_smooth(x_values, y_values, span=None, smoother_cls=None):\n    if smoother_cls is None:\n        smoother_cls = DEFAULT_BASIC_SMOOTHER\n    smoother = smoother_cls()\n    smoother.specify_data_set(x_values, y_values)\n    smoother.set_span(span)\n    smoother.compute()\n    return smoother",
    "docstring": "Convenience function to run the basic smoother.\n\n    Parameters\n    ----------\n    x_values : iterable\n        List of x value observations\n    y_ values : iterable\n        list of y value observations\n    span : float, optional\n        Fraction of data to use as the window\n    smoother_cls : Class\n        The class of smoother to use to smooth the data\n\n    Returns\n    -------\n    smoother : object\n        The smoother object with results stored on it."
  },
  {
    "code": "def _do_pnp(self, pnp, anchor=None):\n        if anchor or pnp and pnp.endswith(\"PNP\"):\n            if anchor is not None:\n                m = find(lambda x: x.startswith(\"P\"), anchor)\n            else:\n                m = None\n            if self.pnp \\\n             and pnp \\\n             and pnp != OUTSIDE \\\n             and pnp.startswith(\"B-\") is False \\\n             and self.words[-2].pnp is not None:\n                self.pnp[-1].append(self.words[-1])\n            elif m is not None and m == self._attachment:\n                self.pnp[-1].append(self.words[-1])\n            else:\n                ch = PNPChunk(self, [self.words[-1]], type=\"PNP\")\n                self.pnp.append(ch)                \n            self._attachment = m",
    "docstring": "Attaches prepositional noun phrases.\n            Identifies PNP's from either the PNP tag or the P-attachment tag.\n            This does not determine the PP-anchor, it only groups words in a PNP chunk."
  },
  {
    "code": "def _general_multithread(func):\n    def multithread(templates, stream, *args, **kwargs):\n        with pool_boy(ThreadPool, len(stream), **kwargs) as pool:\n            return _pool_normxcorr(templates, stream, pool=pool, func=func)\n    return multithread",
    "docstring": "return the general multithreading function using func"
  },
  {
    "code": "def prepare_for_sending(self):\n        if [arbiter_link for arbiter_link in self.arbiters if arbiter_link.spare]:\n            logger.info('Serializing the configuration for my spare arbiter...')\n            self.spare_arbiter_conf = serialize(self)",
    "docstring": "The configuration needs to be serialized before being sent to a spare arbiter\n\n        :return: None"
  },
  {
    "code": "def generate_antisense_sequence(sequence):\n    dna_antisense = {\n        'A': 'T',\n        'T': 'A',\n        'C': 'G',\n        'G': 'C'\n    }\n    antisense = [dna_antisense[x] for x in sequence[::-1]]\n    return ''.join(antisense)",
    "docstring": "Creates the antisense sequence of a DNA strand."
  },
  {
    "code": "def failover_limitation(self):\n        if not self.reachable:\n            return 'not reachable'\n        if self.tags.get('nofailover', False):\n            return 'not allowed to promote'\n        if self.watchdog_failed:\n            return 'not watchdog capable'\n        return None",
    "docstring": "Returns reason why this node can't promote or None if everything is ok."
  },
  {
    "code": "def page_has_tag(page, tag):\n    from .models import PageTags\n    if hasattr(tag, 'slug'):\n        slug = tag.slug\n    else:\n        slug = tag\n    try:\n        return page.pagetags.tags.filter(slug=slug).exists()\n    except PageTags.DoesNotExist:\n        return False",
    "docstring": "Check if a Page object is associated with the given tag.\n\n    :param page: a Page instance\n    :param tag: a Tag instance or a slug string.\n\n    :return: whether the Page instance has the given tag attached (False if no Page or no\n             attached PageTags exists)\n    :type: Boolean"
  },
  {
    "code": "def start_trial(self, trial, checkpoint=None):\n        self._commit_resources(trial.resources)\n        try:\n            self._start_trial(trial, checkpoint)\n        except Exception as e:\n            logger.exception(\"Error starting runner for Trial %s\", str(trial))\n            error_msg = traceback.format_exc()\n            time.sleep(2)\n            self._stop_trial(trial, error=True, error_msg=error_msg)\n            if isinstance(e, AbortTrialExecution):\n                return\n            try:\n                trial.clear_checkpoint()\n                logger.info(\n                    \"Trying to start runner for Trial %s without checkpoint.\",\n                    str(trial))\n                self._start_trial(trial)\n            except Exception:\n                logger.exception(\n                    \"Error starting runner for Trial %s, aborting!\",\n                    str(trial))\n                error_msg = traceback.format_exc()\n                self._stop_trial(trial, error=True, error_msg=error_msg)",
    "docstring": "Starts the trial.\n\n        Will not return resources if trial repeatedly fails on start.\n\n        Args:\n            trial (Trial): Trial to be started.\n            checkpoint (Checkpoint): A Python object or path storing the state\n                of trial."
  },
  {
    "code": "def get_zones(self, q=None, **kwargs):\n        uri = \"/v1/zones\"\n        params = build_params(q, kwargs)\n        return self.rest_api_connection.get(uri, params)",
    "docstring": "Returns a list of zones across all of the user's accounts.\n\n        Keyword Arguments:\n        q -- The search parameters, in a dict.  Valid keys are:\n             name - substring match of the zone name\n             zone_type - one of:\n                PRIMARY\n                SECONDARY\n                ALIAS\n        sort -- The sort column used to order the list. Valid values for the sort field are:\n                NAME\n                ACCOUNT_NAME\n                RECORD_COUNT\n                ZONE_TYPE\n        reverse -- Whether the list is ascending(False) or descending(True)\n        offset -- The position in the list for the first returned element(0 based)\n        limit -- The maximum number of rows to be returned."
  },
  {
    "code": "def apply_widget_css_class(self, field_name):\n        field = self.fields[field_name]\n        class_name = self.get_widget_css_class(field_name, field)\n        if class_name:\n            field.widget.attrs['class'] = join_css_class(\n                field.widget.attrs.get('class', None), class_name)",
    "docstring": "Applies CSS classes to widgets if available.\n\n        The method uses the `get_widget_css_class` method to determine if the widget\n        CSS class should be changed. If a CSS class is returned, it is appended to\n        the current value of the class property of the widget instance.\n\n        :param field_name: A field name of the form."
  },
  {
    "code": "def update_mute(self, data):\n        self._group['muted'] = data['mute']\n        self.callback()\n        _LOGGER.info('updated mute on %s', self.friendly_name)",
    "docstring": "Update mute."
  },
  {
    "code": "def _get_max_sigma(self, R):\n        max_sigma = 2.0 * math.pow(np.nanmax(np.std(R, axis=0)), 2)\n        return max_sigma",
    "docstring": "Calculate maximum sigma of scanner RAS coordinates\n\n        Parameters\n        ----------\n\n        R : 2D array, with shape [n_voxel, n_dim]\n            The coordinate matrix of fMRI data from one subject\n\n        Returns\n        -------\n\n        max_sigma : float\n            The maximum sigma of scanner coordinates."
  },
  {
    "code": "def rownumbers(self, table=None):\n        if table is None:\n            return self._rownumbers(Table())\n        return self._rownumbers(table)",
    "docstring": "Return a list containing the row numbers of this table.\n\n        This method can be useful after a selection or a sort.\n        It returns the row numbers of the rows in this table with respect\n        to the given table. If no table is given, the original table is used.\n\n        For example::\n\n          t = table('W53.MS')\n          t1 = t.selectrows([1,3,5,7,9])  # select a few rows\n          t1.rownumbers(t)\n          # [1 3 5 7 9]\n          t2 = t1.selectrows([2,5])       # select rows from the selection\n          t2.rownumbers(t1)\n          # [2 5]                         # rownrs of t2 in table t1\n          t2.rownumbers(t)\n          # [3 9]                         # rownrs of t2 in t\n          t2.rownumbers()\n          # [3 9]\n\n        The last statements show that the method returns the row numbers\n        referring to the given table. Table t2 contains rows 2 and 5 in\n        table t1, which are rows 3 and 9 in table t."
  },
  {
    "code": "def zero_pad(ts, n_zeros):\n    zeros_shape = ts.shape[:-1] + (n_zeros,)\n    zzs = np.zeros(zeros_shape)\n    new_data = np.concatenate((zzs, ts.data, zzs), axis=-1)\n    return nts.TimeSeries(new_data, sampling_rate=ts.sampling_rate)",
    "docstring": "Pad a nitime.TimeSeries class instance with n_zeros before and after the\n    data\n\n    Parameters\n    ----------\n    ts : a nitime.TimeSeries class instance"
  },
  {
    "code": "def version(self):\n        version = int(self._dll.JLINKARM_GetDLLVersion())\n        major = version / 10000\n        minor = (version / 100) % 100\n        rev = version % 100\n        rev = '' if rev == 0 else chr(rev + ord('a') - 1)\n        return '%d.%02d%s' % (major, minor, rev)",
    "docstring": "Returns the device's version.\n\n        The device's version is returned as a string of the format: M.mr where\n        ``M`` is major number, ``m`` is minor number, and ``r`` is revision\n        character.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n\n        Returns:\n          Device version string."
  },
  {
    "code": "def error_handler(self, handler):\n        if not self.opened():\n            handler = handler or util.noop\n            self._error_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)\n            self._dll.JLINKARM_SetErrorOutHandler(self._error_handler)",
    "docstring": "Setter for the error handler function.\n\n        If the DLL is open, this function is a no-op, so it should be called\n        prior to calling ``open()``.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          handler (function): function to call on error messages\n\n        Returns:\n          ``None``"
  },
  {
    "code": "def single_row_or_col_df_to_series(desired_type: Type[T], single_rowcol_df: pd.DataFrame, logger: Logger, **kwargs)\\\n        -> pd.Series:\n    if single_rowcol_df.shape[0] == 1:\n        return single_rowcol_df.transpose()[0]\n    elif single_rowcol_df.shape[1] == 2 and isinstance(single_rowcol_df.index, pd.RangeIndex):\n        d = single_rowcol_df.set_index(single_rowcol_df.columns[0])\n        return d[d.columns[0]]\n    elif single_rowcol_df.shape[1] == 1:\n        d = single_rowcol_df\n        return d[d.columns[0]]\n    else:\n        raise ValueError('Unable to convert provided dataframe to a series : '\n                         'expected exactly 1 row or 1 column, found : ' + str(single_rowcol_df.shape) + '')",
    "docstring": "Helper method to convert a dataframe with one row or one or two columns into a Series\n\n    :param desired_type:\n    :param single_col_df:\n    :param logger:\n    :param kwargs:\n    :return:"
  },
  {
    "code": "def create_service(self, service_type, plan_name, service_name, params,\n            async=False, **kwargs):\n        if self.space.has_service_with_name(service_name):\n            logging.warning(\"Service already exists with that name.\")\n            return self.get_instance(service_name)\n        if self.space.has_service_of_type(service_type):\n            logging.warning(\"Service type already exists.\")\n        guid = self.get_service_plan_guid(service_type, plan_name)\n        if not guid:\n            raise ValueError(\"No service plan named: %s\" % (plan_name))\n        body = {\n            'name': service_name,\n            'space_guid': self.space.guid,\n            'service_plan_guid': guid,\n            'parameters': params\n            }\n        uri = '/v2/service_instances?accepts_incomplete=true'\n        if async:\n            uri += '&async=true'\n        return self.api.post(uri, body)",
    "docstring": "Create a service instance."
  },
  {
    "code": "def get_parent_banks(self, bank_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.get_parent_catalogs(catalog_id=bank_id)\n        return BankLookupSession(\n            self._proxy,\n            self._runtime).get_banks_by_ids(\n                list(self.get_parent_bank_ids(bank_id)))",
    "docstring": "Gets the parents of the given bank.\n\n        arg:    bank_id (osid.id.Id): a bank ``Id``\n        return: (osid.assessment.BankList) - the parents of the bank\n        raise:  NotFound - ``bank_id`` is not found\n        raise:  NullArgument - ``bank_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def data_received(self, data):\n        _LOGGER.debug(\"Starting: data_received\")\n        _LOGGER.debug('Received %d bytes from PLM: %s',\n                      len(data), binascii.hexlify(data))\n        self._buffer.put_nowait(data)\n        asyncio.ensure_future(self._peel_messages_from_buffer(),\n                              loop=self._loop)\n        _LOGGER.debug(\"Finishing: data_received\")",
    "docstring": "Receive data from the protocol.\n\n        Called when asyncio.Protocol detects received data from network."
  },
  {
    "code": "def getbulk_by_oid(self, non_repeaters, max_repetitions, *oid):\n        if self.version.startswith('3'):\n            errorIndication, errorStatus, errorIndex, varBinds = self.cmdGen.getCmd(\n                cmdgen.UsmUserData(self.user, self.auth),\n                cmdgen.UdpTransportTarget((self.host, self.port)),\n                non_repeaters,\n                max_repetitions,\n                *oid\n            )\n        if self.version.startswith('2'):\n            errorIndication, errorStatus, errorIndex, varBindTable = self.cmdGen.bulkCmd(\n                cmdgen.CommunityData(self.community),\n                cmdgen.UdpTransportTarget((self.host, self.port)),\n                non_repeaters,\n                max_repetitions,\n                *oid\n            )\n        else:\n            return []\n        return self.__bulk_result__(errorIndication, errorStatus, errorIndex, varBindTable)",
    "docstring": "SNMP getbulk request.\n\n        In contrast to snmpwalk, this information will typically be gathered in\n        a single transaction with the agent, rather than one transaction per\n        variable found.\n\n        * non_repeaters: This specifies the number of supplied variables that\n          should not be iterated over.\n        * max_repetitions: This specifies the maximum number of iterations over\n          the repeating variables.\n        * oid: oid list\n        > Return a list of dicts"
  },
  {
    "code": "def factory(data):\n        if 'object' not in data:\n            raise exceptions.UnknownAPIResource('Missing `object` key in resource.')\n        for reconstituable_api_resource_type in ReconstituableAPIResource.__subclasses__():\n            if reconstituable_api_resource_type.object_type == data['object']:\n                return reconstituable_api_resource_type(**data)\n        raise exceptions.UnknownAPIResource('Unknown object `' + data['object'] + '`.')",
    "docstring": "Try to reconstruct the APIResource from its data.\n\n        :param data: The APIResource data\n        :type data: dict\n\n        :return: The guessed APIResource\n\n        :raise\n            exceptions.UnkownAPIResource when it's impossible to reconstruct the APIResource from its data."
  },
  {
    "code": "def encodeEntitiesReentrant(self, input):\n        ret = libxml2mod.xmlEncodeEntitiesReentrant(self._o, input)\n        return ret",
    "docstring": "Do a global encoding of a string, replacing the predefined\n          entities and non ASCII values with their entities and\n          CharRef counterparts. Contrary to xmlEncodeEntities, this\n           routine is reentrant, and result must be deallocated."
  },
  {
    "code": "def move_entry_in_group(self, entry = None, index = None):\n        if entry is None or index is None or type(entry) is not v1Entry \\\n            or type(index) is not int:\n            raise KPError(\"Need an entry and an index.\")\n        elif index < 0 or index > len(entry.group.entries)-1:\n            raise KPError(\"Index is not valid.\")\n        elif entry not in self.entries:\n            raise KPError(\"Entry not found.\")\n        pos_in_group = entry.group.entries.index(entry)\n        pos_in_entries = self.entries.index(entry)\n        entry_at_index = entry.group.entries[index]\n        pos_in_entries2 = self.entries.index(entry_at_index)\n        entry.group.entries[index] = entry\n        entry.group.entries[pos_in_group] = entry_at_index\n        self.entries[pos_in_entries2] = entry\n        self.entries[pos_in_entries] = entry_at_index\n        return True",
    "docstring": "Move entry to another position inside a group.\n\n        An entry and a valid index to insert the entry in the\n        entry list of the holding group is needed. 0 means\n        that the entry is moved to the first position 1 to\n        the second and so on."
  },
  {
    "code": "def __init_configrs(self, rs_cfg):\n        rs_cfg['id'] = rs_cfg.pop('rs_id', None)\n        for member in rs_cfg.setdefault('members', [{}]):\n            member['procParams'] = self._strip_auth(\n                member.get('procParams', {}))\n            member['procParams']['configsvr'] = True\n            if self.enable_ipv6:\n                common.enable_ipv6_single(member['procParams'])\n        rs_cfg['sslParams'] = self.sslParams\n        self._configsvrs.append(ReplicaSets().create(rs_cfg))",
    "docstring": "Create and start a config replica set."
  },
  {
    "code": "def fswap(p, q):\n    yield cirq.ISWAP(q, p), cirq.Z(p) ** 1.5\n    yield cirq.Z(q) ** 1.5",
    "docstring": "Decompose the Fermionic SWAP gate into two single-qubit gates and\n    one iSWAP gate.\n\n    Args:\n        p: the id of the first qubit\n        q: the id of the second qubit"
  },
  {
    "code": "def register_or_check(klass, finish, mean, between, refresh_presision, configuration):\n\t\tm, created = klass.objects.get_or_create(finish=finish, configuration=configuration)\n\t\tif created:\n\t\t\tm.mean=mean\n\t\t\tm.between=between\n\t\t\tm.refresh_presision=refresh_presision\n\t\t\tm.save()\n\t\telse:\n\t\t\tdiff = abs(float(m.mean) - mean)\n\t\t\tif not(diff < 0.006 and m.between == between and m.refresh_presision == refresh_presision):\n\t\t\t\traise InvalidMeasurementError(\"There are diferents values for the same measurement.\")\n\t\treturn m",
    "docstring": "Return the active configurations."
  },
  {
    "code": "def post_silence_request(self, kwargs):\n        self._request('POST', '/silenced', data=json.dumps(kwargs))\n        return True",
    "docstring": "Create a silence entry."
  },
  {
    "code": "def update_account(self, **kwargs):\n        api = self._get_api(iam.AccountAdminApi)\n        account = Account._create_request_map(kwargs)\n        body = AccountUpdateReq(**account)\n        return Account(api.update_my_account(body))",
    "docstring": "Update details of account associated with current API key.\n\n        :param str address_line1: Postal address line 1.\n        :param str address_line2: Postal address line 2.\n        :param str city: The city part of the postal address.\n        :param str display_name: The display name for the account.\n        :param str country: The country part of the postal address.\n        :param str company: The name of the company.\n        :param str state: The state part of the postal address.\n        :param str contact: The name of the contact person for this account.\n        :param str postal_code: The postal code part of the postal address.\n        :param str parent_id: The ID of the parent account.\n        :param str phone_number: The phone number of the company.\n        :param str email: Email address for this account.\n        :param list[str] aliases: List of aliases\n        :returns: an account object.\n        :rtype: Account"
  },
  {
    "code": "async def unixlisten(path, onlink):\n    info = {'path': path, 'unix': True}\n    async def onconn(reader, writer):\n        link = await Link.anit(reader, writer, info=info)\n        link.schedCoro(onlink(link))\n    return await asyncio.start_unix_server(onconn, path=path)",
    "docstring": "Start an PF_UNIX server listening on the given path."
  },
  {
    "code": "def predict_proba(estimator, X):\n    if is_probabilistic_classifier(estimator):\n        try:\n            proba, = estimator.predict_proba(X)\n            return proba\n        except NotImplementedError:\n            return None\n    else:\n        return None",
    "docstring": "Return result of predict_proba, if an estimator supports it, or None."
  },
  {
    "code": "def _rewrite_q(self, q):\n        if isinstance(q, tuple) and len(q) == 2:\n            return rewrite_lookup_key(self.model, q[0]), q[1]\n        if isinstance(q, Node):\n            q.children = list(map(self._rewrite_q, q.children))\n        return q",
    "docstring": "Rewrite field names inside Q call."
  },
  {
    "code": "def checkout(self, ref, branch=None):\n        return git_checkout(self.repo_dir, ref, branch=branch)",
    "docstring": "Do a git checkout of `ref`."
  },
  {
    "code": "def comment(value, comment_text):\n    if isinstance(value, Doc):\n        return comment_doc(value, comment_text)\n    return comment_value(value, comment_text)",
    "docstring": "Annotates a value or a Doc with a comment.\n\n    When printed by prettyprinter, the comment will be\n    rendered next to the value or Doc."
  },
  {
    "code": "def add_access_list(self, loadbalancer, access_list):\n        req_body = {\"accessList\": access_list}\n        uri = \"/loadbalancers/%s/accesslist\" % utils.get_id(loadbalancer)\n        resp, body = self.api.method_post(uri, body=req_body)\n        return body",
    "docstring": "Adds the access list provided to the load balancer.\n\n        The 'access_list' should be a list of dicts in the following format:\n\n            [{\"address\": \"192.0.43.10\", \"type\": \"DENY\"},\n             {\"address\": \"192.0.43.11\", \"type\": \"ALLOW\"},\n             ...\n             {\"address\": \"192.0.43.99\", \"type\": \"DENY\"},\n            ]\n\n        If no access list exists, it is created. If an access list\n        already exists, it is updated with the provided list."
  },
  {
    "code": "def AgregarAjusteMonetario(self, precio_unitario, precio_recupero=None, \n                               **kwargs):\n        \"Agrega campos al detalle de item por un ajuste monetario\"\n        d = {'precioUnitario': precio_unitario, \n             'precioRecupero': precio_recupero,\n            }\n        item_liq = self.solicitud['itemDetalleAjusteLiquidacion'][-1]\n        item_liq['ajusteMonetario'] = d\n        return True",
    "docstring": "Agrega campos al detalle de item por un ajuste monetario"
  },
  {
    "code": "def prepare_query(query):\n    for name in query:\n        value = query[name]\n        if value is None:\n            query[name] = \"\"\n        elif isinstance(value, bool):\n            query[name] = int(value)\n        elif isinstance(value, dict):\n            raise ValueError(\"Invalid query data type %r\" %\n                             type(value).__name__)",
    "docstring": "Prepare a query object for the RAPI.\n\n    RAPI has lots of curious rules for coercing values.\n\n    This function operates on dicts in-place and has no return value.\n\n    @type query: dict\n    @param query: Query arguments"
  },
  {
    "code": "def add(self, crash):\n        if crash not in self:\n            key  = crash.key()\n            skey = self.marshall_key(key)\n            data = self.marshall_value(crash, storeMemoryMap = True)\n            self.__db[skey] = data",
    "docstring": "Adds a new crash to the container.\n        If the crash appears to be already known, it's ignored.\n\n        @see: L{Crash.key}\n\n        @type  crash: L{Crash}\n        @param crash: Crash object to add."
  },
  {
    "code": "def create_lbaas_member(self, lbaas_pool, body=None):\n        return self.post(self.lbaas_members_path % lbaas_pool, body=body)",
    "docstring": "Creates a lbaas_member."
  },
  {
    "code": "def check_workers(self):\n        if time.time() - self._worker_alive_time > 5:\n            self._worker_alive_time = time.time()\n            [worker.join() for worker in self._workers if not worker.is_alive()]\n            self._workers = [\n                worker for worker in self._workers if worker.is_alive()\n            ]\n            if len(self._workers) < self._num_workers:\n                raise ProcessKilled('One of the workers has been killed.')",
    "docstring": "Kill workers that have been pending for a while and check if all workers\n        are alive."
  },
  {
    "code": "def counts(self, ids=None, setdata=False, output_format='DataFrame'):\n        return self.apply(lambda x: x.counts, ids=ids, setdata=setdata, output_format=output_format)",
    "docstring": "Return the counts in each of the specified measurements.\n\n        Parameters\n        ----------\n        ids : [hashable | iterable of hashables | None]\n            Keys of measurements to get counts of.\n            If None is given get counts of all measurements.\n        setdata : bool\n            Whether to set the data in the Measurement object.\n            Used only if data is not already set.\n        output_format : DataFrame | dict\n            Specifies the output format for that data.\n\n        Returns\n        -------\n        [DataFrame | Dictionary]\n            Dictionary keys correspond to measurement keys."
  },
  {
    "code": "def to_code(self, context: Context =None):\n        context = context or Context()\n        for imp in self.imports:\n            if imp not in context.imports:\n                context.imports.append(imp)\n        counter = Counter()\n        lines = list(self.to_lines(context=context, counter=counter))\n        if counter.num_indented_non_doc_blocks == 0:\n            if self.expects_body_or_pass:\n                lines.append(\"    pass\")\n            elif self.closed_by:\n                lines[-1] += self.closed_by\n        else:\n            if self.closed_by:\n                lines.append(self.closed_by)\n        return join_lines(*lines) + self._suffix",
    "docstring": "Generate the code and return it as a string."
  },
  {
    "code": "def add_scroll_bar(self):\n        adj = self.terminal.get_vadjustment()\n        scroll = Gtk.VScrollbar(adj)\n        scroll.show()\n        self.pack_start(scroll, False, False, 0)",
    "docstring": "Packs the scrollbar."
  },
  {
    "code": "def draw(self, parent, box):\n        import wx\n        from MAVProxy.modules.lib import mp_widgets\n        if self.imgpanel is None:\n            self.imgpanel = mp_widgets.ImagePanel(parent, self.img())\n            box.Add(self.imgpanel, flag=wx.LEFT, border=0)\n            box.Layout()",
    "docstring": "redraw the image"
  },
  {
    "code": "def cli_program_names(self):\n        r\n        program_names = {}\n        for cli_class in self.cli_classes:\n            instance = cli_class()\n            program_names[instance.program_name] = cli_class\n        return program_names",
    "docstring": "r\"\"\"Developer script program names."
  },
  {
    "code": "def get_int(bytearray_, byte_index):\n    data = bytearray_[byte_index:byte_index + 2]\n    data[1] = data[1] & 0xff\n    data[0] = data[0] & 0xff\n    packed = struct.pack('2B', *data)\n    value = struct.unpack('>h', packed)[0]\n    return value",
    "docstring": "Get int value from bytearray.\n\n    int are represented in two bytes"
  },
  {
    "code": "def get_local_version(sigdir, sig):\n    version = None\n    filename = os.path.join(sigdir, '%s.cvd' % sig)\n    if os.path.exists(filename):\n        cmd = ['sigtool', '-i', filename]\n        sigtool = Popen(cmd, stdout=PIPE, stderr=PIPE)\n        while True:\n            line = sigtool.stdout.readline()\n            if line and line.startswith('Version:'):\n                version = line.split()[1]\n                break\n            if not line:\n                break\n        sigtool.wait()\n    return version",
    "docstring": "Get the local version of a signature"
  },
  {
    "code": "def select_relevant_id_columns(rows):\n    relevant_id_columns = [True]\n    if rows:\n        prototype_id = rows[0].id\n        for column in range(1, len(prototype_id)):\n            def id_equal_to_prototype(row):\n                return row.id[column] == prototype_id[column]\n            relevant_id_columns.append(not all(map(id_equal_to_prototype, rows)))\n    return relevant_id_columns",
    "docstring": "Find out which of the entries in Row.id are equal for all given rows.\n    @return: A list of True/False values according to whether the i-th part of the id is always equal."
  },
  {
    "code": "def __set_status(self, value):\n        if value not in [DELIVERY_METHOD_STATUS_PENDING,\n                         DELIVERY_METHOD_STATUS_SENT,\n                         DELIVERY_METHOD_STATUS_CONFIRMED,\n                         DELIVERY_METHOD_STATUS_BOUNCED]:\n            raise ValueError(\"Invalid deliveries method status '%s'\" % value)\n        self.__status = value",
    "docstring": "Sets the deliveries status of this method.\n        @param value: str"
  },
  {
    "code": "def to_yaml(cls, dumper, vividict):\n        dictionary = cls.vividict_to_dict(vividict)\n        node = dumper.represent_mapping(cls.yaml_tag, dictionary)\n        return node",
    "docstring": "Implementation for the abstract method of the base class YAMLObject"
  },
  {
    "code": "def download(self, path, args=[], filepath=None, opts={},\n                 compress=True, **kwargs):\n        url = self.base + path\n        wd = filepath or '.'\n        params = []\n        params.append(('stream-channels', 'true'))\n        params.append(('archive', 'true'))\n        if compress:\n            params.append(('compress', 'true'))\n        for opt in opts.items():\n            params.append(opt)\n        for arg in args:\n            params.append(('arg', arg))\n        method = 'get'\n        res = self._do_request(method, url, params=params, stream=True,\n                               **kwargs)\n        self._do_raise_for_status(res)\n        mode = 'r|gz' if compress else 'r|'\n        with tarfile.open(fileobj=res.raw, mode=mode) as tf:\n            tf.extractall(path=wd)",
    "docstring": "Makes a request to the IPFS daemon to download a file.\n\n        Downloads a file or files from IPFS into the current working\n        directory, or the directory given by ``filepath``.\n\n        Raises\n        ------\n        ~ipfsapi.exceptions.ErrorResponse\n        ~ipfsapi.exceptions.ConnectionError\n        ~ipfsapi.exceptions.ProtocolError\n        ~ipfsapi.exceptions.StatusError\n        ~ipfsapi.exceptions.TimeoutError\n\n        Parameters\n        ----------\n        path : str\n            The REST command path to send\n        filepath : str\n            The local path where IPFS will store downloaded files\n\n            Defaults to the current working directory.\n        args : list\n            Positional parameters to be sent along with the HTTP request\n        opts : dict\n            Query string paramters to be sent along with the HTTP request\n        compress : bool\n            Whether the downloaded file should be GZip compressed by the\n            daemon before being sent to the client\n        kwargs : dict\n            Additional arguments to pass to :mod:`requests`"
  },
  {
    "code": "def _GetEnableOsLoginValue(self, metadata_dict):\n    instance_data, project_data = self._GetInstanceAndProjectAttributes(\n        metadata_dict)\n    instance_value = instance_data.get('enable-oslogin')\n    project_value = project_data.get('enable-oslogin')\n    value = instance_value or project_value or ''\n    return value.lower() == 'true'",
    "docstring": "Get the value of the enable-oslogin metadata key.\n\n    Args:\n      metadata_dict: json, the deserialized contents of the metadata server.\n\n    Returns:\n      bool, True if OS Login is enabled for VM access."
  },
  {
    "code": "def date_range(start, end, boo):\n  earliest = datetime.strptime(start.replace('-', ' '), '%Y %m %d')\n  latest = datetime.strptime(end.replace('-', ' '), '%Y %m %d')\n  num_days = (latest - earliest).days + 1\n  all_days = [latest - timedelta(days=x) for x in range(num_days)]\n  all_days.reverse()\n  output = []\n  if boo:\n    for d in all_days:\n      output.append(int(str(d).replace('-', '')[:8]))\n  else:\n    for d in all_days:\n      output.append(str(d)[:10])\n  return output",
    "docstring": "Return list of dates within a specified range, inclusive.\n\n  Args:\n    start: earliest date to include, String (\"2015-11-25\")\n    end: latest date to include, String (\"2015-12-01\")\n    boo: if true, output list contains Numbers (20151230); if false, list contains Strings (\"2015-12-30\")\n  Returns:\n    list of either Numbers or Strings"
  },
  {
    "code": "def recruit(self):\n        if self.networks(full=False):\n            self.recruiter.recruit(n=1)\n        else:\n            self.recruiter.close_recruitment()",
    "docstring": "Recruit one participant at a time until all networks are full."
  },
  {
    "code": "def _meanvalueattr(self,v):\n        sug = self.layout\n        if not self.prevlayer(): return sug.grx[v].bar\n        bars = [sug.grx[x].bar for x in self._neighbors(v)]\n        return sug.grx[v].bar if len(bars)==0 else float(sum(bars))/len(bars)",
    "docstring": "find new position of vertex v according to adjacency in prevlayer.\n        position is given by the mean value of adjacent positions.\n        experiments show that meanvalue heuristic performs better than median."
  },
  {
    "code": "def run(self):\n        if self.directive_name is None:\n            raise NotImplementedError('directive_name must be implemented by '\n                                      'subclasses of BaseDirective')\n        env, state = self._prepare_env()\n        state.doc_names.add(env.docname)\n        directive_name = '<{}>'.format(self.directive_name)\n        node = nodes.section()\n        node.document = self.state.document\n        result = ViewList()\n        for line in self._render_rst():\n            if line.startswith(HEADING_TOKEN):\n                heading = line[HEADING_TOKEN_LENGTH:]\n                result.append(heading, directive_name)\n                result.append('-' * len(heading), directive_name)\n            else:\n                result.append(line, directive_name)\n        nested_parse_with_titles(self.state, result, node)\n        return node.children",
    "docstring": "Called by Sphinx to generate documentation for this directive."
  },
  {
    "code": "def set_broadcast_layout(self, broadcast_id, layout_type, stylesheet=None):\n        payload = {\n            'type': layout_type,\n        }\n        if layout_type == 'custom':\n            if stylesheet is not None:\n                payload['stylesheet'] = stylesheet\n        endpoint = self.endpoints.broadcast_url(broadcast_id, layout=True)\n        response = requests.put(\n            endpoint,\n            data=json.dumps(payload),\n            headers=self.json_headers(),\n            proxies=self.proxies,\n            timeout=self.timeout\n        )\n        if response.status_code == 200:\n            pass\n        elif response.status_code == 400:\n            raise BroadcastError(\n                'Invalid request. This response may indicate that data in your request data is '\n                'invalid JSON. It may also indicate that you passed in invalid layout options.')\n        elif response.status_code == 403:\n            raise AuthError('Authentication error.')\n        else:\n            raise RequestError('OpenTok server error.', response.status_code)",
    "docstring": "Use this method to change the layout type of a live streaming broadcast\n\n        :param String broadcast_id: The ID of the broadcast that will be updated\n\n        :param String layout_type: The layout type for the broadcast. Valid values are:\n        'bestFit', 'custom', 'horizontalPresentation', 'pip' and 'verticalPresentation'\n\n        :param String stylesheet optional: CSS used to style the custom layout.\n        Specify this only if you set the type property to 'custom'"
  },
  {
    "code": "def handle_message(self, msg):\n        if msg.msg_id in self.messagesAllowed:\n            super(LimitedReporter, self).handle_message(msg)",
    "docstring": "Manage message of different type and in the context of path."
  },
  {
    "code": "def _det_inference(self):\n        if (self.n_randEffs==2) and (~sp.isnan(self.Y).any()):\n            rv = 'GP2KronSum'\n        else:\n            rv = 'GP'\n        return rv",
    "docstring": "Internal method for determining the inference method"
  },
  {
    "code": "def writeDrizKeywords(hdr,imgnum,drizdict):\n    _keyprefix = 'D%03d'%imgnum\n    for key in drizdict:\n        val = drizdict[key]['value']\n        if val is None: val = \"\"\n        comment = drizdict[key]['comment']\n        if comment is None: comment = \"\"\n        hdr[_keyprefix+key] = (val, drizdict[key]['comment'])",
    "docstring": "Write basic drizzle-related keywords out to image header as a record\n        of the processing performed to create the image\n\n        The dictionary 'drizdict' will contain the keywords and values to be\n        written out to the header."
  },
  {
    "code": "def _get_request(self, auth=None):\n        self.request = HSRequest(auth or self.auth, self.env)\n        self.request.response_callback = self.response_callback\n        return self.request",
    "docstring": "Return an http request object\n\n            auth: Auth data to use\n\n            Returns:\n                A HSRequest object"
  },
  {
    "code": "def visible(self):\n        query_results = self.map(lambda el: el.is_displayed(), 'visible').results\n        if query_results:\n            return all(query_results)\n        return False",
    "docstring": "Check whether all matched elements are visible.\n\n        Returns:\n            bool"
  },
  {
    "code": "def _chunk_write(chunk, local_file, progress):\n    local_file.write(chunk)\n    if progress is not None:\n        progress.update(len(chunk))",
    "docstring": "Write a chunk to file and update the progress bar."
  },
  {
    "code": "async def add_local_charm_dir(self, charm_dir, series):\n        fh = tempfile.NamedTemporaryFile()\n        CharmArchiveGenerator(charm_dir).make_archive(fh.name)\n        with fh:\n            func = partial(\n                self.add_local_charm, fh, series, os.stat(fh.name).st_size)\n            charm_url = await self._connector.loop.run_in_executor(None, func)\n        log.debug('Uploaded local charm: %s -> %s', charm_dir, charm_url)\n        return charm_url",
    "docstring": "Upload a local charm to the model.\n\n        This will automatically generate an archive from\n        the charm dir.\n\n        :param charm_dir: Path to the charm directory\n        :param series: Charm series"
  },
  {
    "code": "def get_historical_data(symbols, start=None, end=None, **kwargs):\n    start, end = _sanitize_dates(start, end)\n    return HistoricalReader(symbols, start=start, end=end, **kwargs).fetch()",
    "docstring": "Function to obtain historical date for a symbol or list of\n    symbols. Return an instance of HistoricalReader\n\n    Parameters\n    ----------\n    symbols: str or list\n        A symbol or list of symbols\n    start: datetime.datetime, default None\n        Beginning of desired date range\n    end: datetime.datetime, default None\n        End of required date range\n    kwargs:\n        Additional Request Parameters (see base class)\n\n    Returns\n    -------\n    list or DataFrame\n        Historical stock prices over date range, start to end"
  },
  {
    "code": "def mangle_agreement(correct_sentence):\n    bad_sents = []\n    doc = nlp(correct_sentence)\n    verbs = [(i, v) for (i, v) in enumerate(doc) if v.tag_.startswith('VB')]\n    for i, v in verbs:\n        for alt_verb in lexeme(doc[i].text):\n            if alt_verb == doc[i].text:\n                continue\n            if (tenses(alt_verb) == tenses(v.text) or\n                    (alt_verb.startswith(v.text) and alt_verb.endswith(\"n't\"))):\n                continue\n            new_sent = str(doc[:i]) + \" {} \".format(alt_verb) + str(doc[i+1:]) \n            new_sent = new_sent.replace(' ,', ',')\n            bad_sents.append(new_sent)\n    return bad_sents",
    "docstring": "Given a correct sentence, return a sentence or sentences with a subject\n    verb agreement error"
  },
  {
    "code": "def get_resampler_for_grouping(groupby, rule, how=None, fill_method=None,\n                               limit=None, kind=None, **kwargs):\n    kwargs['key'] = kwargs.pop('on', None)\n    tg = TimeGrouper(freq=rule, **kwargs)\n    resampler = tg._get_resampler(groupby.obj, kind=kind)\n    r = resampler._get_resampler_for_grouping(groupby=groupby)\n    return _maybe_process_deprecations(r,\n                                       how=how,\n                                       fill_method=fill_method,\n                                       limit=limit)",
    "docstring": "Return our appropriate resampler when grouping as well."
  },
  {
    "code": "def flattened(self):\n        parsed = self['parsed_whois']\n        flat = OrderedDict()\n        for key in ('domain', 'created_date', 'updated_date', 'expired_date', 'statuses', 'name_servers'):\n            value = parsed[key]\n            flat[key] = ' | '.join(value) if type(value) in (list, tuple) else value\n        registrar = parsed.get('registrar', {})\n        for key in ('name', 'abuse_contact_phone', 'abuse_contact_email', 'iana_id', 'url', 'whois_server'):\n            flat['registrar_{0}'.format(key)] = registrar[key]\n        for contact_type in ('registrant', 'admin', 'tech', 'billing'):\n            contact = parsed.get('contacts', {}).get(contact_type, {})\n            for key in ('name', 'email', 'org', 'street', 'city', 'state', 'postal', 'country', 'phone', 'fax'):\n                value = contact[key]\n                flat['{0}_{1}'.format(contact_type, key)] = ' '.join(value) if type(value) in (list, tuple) else value\n        return flat",
    "docstring": "Returns a flattened version of the parsed whois data"
  },
  {
    "code": "def on_vrde_server_change(self, restart):\n        if not isinstance(restart, bool):\n            raise TypeError(\"restart can only be an instance of type bool\")\n        self._call(\"onVRDEServerChange\",\n                     in_p=[restart])",
    "docstring": "Triggered when settings of the VRDE server object of the\n        associated virtual machine have changed.\n\n        in restart of type bool\n            Flag whether the server must be restarted\n\n        raises :class:`VBoxErrorInvalidVmState`\n            Session state prevents operation.\n        \n        raises :class:`VBoxErrorInvalidObjectState`\n            Session type prevents operation."
  },
  {
    "code": "def img_opacity(image, opacity):\n    assert 0 <= opacity <= 1, 'Opacity must be a float between 0 and 1'\n    assert os.path.isfile(image), 'Image is not a file'\n    im = Image.open(image)\n    if im.mode != 'RGBA':\n        im = im.convert('RGBA')\n    else:\n        im = im.copy()\n    alpha = im.split()[3]\n    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)\n    im.putalpha(alpha)\n    dst = _add_suffix(image, str(str(int(opacity * 100)) + '%'), ext='.png')\n    im.save(dst)\n    return dst",
    "docstring": "Reduce the opacity of a PNG image.\n\n    Inspiration: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879\n\n    :param image: PNG image file\n    :param opacity: float representing opacity percentage\n    :return: Path to modified PNG"
  },
  {
    "code": "def _build_block_element_list(self):\n        return sorted(\n            [e for e in self.block_elements.values() if not e.virtual],\n            key=lambda e: e.priority,\n            reverse=True\n        )",
    "docstring": "Return a list of block elements, ordered from highest priority to lowest."
  },
  {
    "code": "def mpl_to_bokeh(properties):\n    new_properties = {}\n    for k, v in properties.items():\n        if isinstance(v, dict):\n            new_properties[k] = v\n        elif k == 's':\n            new_properties['size'] = v\n        elif k == 'marker':\n            new_properties.update(markers.get(v, {'marker': v}))\n        elif (k == 'color' or k.endswith('_color')) and not isinstance(v, (dict, dim)):\n            with abbreviated_exception():\n                v = COLOR_ALIASES.get(v, v)\n            if isinstance(v, tuple):\n                with abbreviated_exception():\n                    v = rgb2hex(v)\n            new_properties[k] = v\n        else:\n            new_properties[k] = v\n    new_properties.pop('cmap', None)\n    return new_properties",
    "docstring": "Utility to process style properties converting any\n    matplotlib specific options to their nearest bokeh\n    equivalent."
  },
  {
    "code": "def get_twitter_id(self, cache=True):\n        if not (cache and ('twitter' in self.cache)):\n            response = self.get_attribute('twitter')\n            self.cache['twitter'] = response['artist'].get('twitter')\n        return self.cache['twitter']",
    "docstring": "Get the twitter id for this artist if it exists\n\n        Args:\n\n        Kwargs:\n\n        Returns:\n            A twitter ID string\n\n        Example:\n\n        >>> a = artist.Artist('big boi')\n        >>> a.get_twitter_id()\n        u'BigBoi'\n        >>>"
  },
  {
    "code": "def read(self, location):\n        location = os.path.expanduser(location)\n        for e in ENCODINGS:\n            try:\n                with codecs.open(location, 'r', e) as f:\n                    return f.read(), e\n            except UnicodeDecodeError:\n                pass\n        raise Exception('Unable to open file: %r' % location)",
    "docstring": "Read file from disk."
  },
  {
    "code": "def _add_form_fields(obj, lines):\n    lines.append(\"**Form fields:**\")\n    lines.append(\"\")\n    for name, field in obj.base_fields.items():\n        field_type = \"{}.{}\".format(field.__class__.__module__, field.__class__.__name__)\n        tpl = \"* ``{name}``: {label} (:class:`~{field_type}`)\"\n        lines.append(tpl.format(\n            name=name,\n            field=field,\n            label=field.label or name.replace('_', ' ').title(),\n            field_type=field_type\n        ))",
    "docstring": "Improve the documentation of a Django Form class.\n\n    This highlights the available fields in the form."
  },
  {
    "code": "def getfiles(qfiles, dirname, names):\n    for name in names:\n        fullname = os.path.join(dirname, name)\n        if os.path.isfile(fullname) and \\\n            fullname.endswith('.cf') or \\\n                fullname.endswith('.post'):\n            qfiles.put(fullname)",
    "docstring": "Get rule files in a directory"
  },
  {
    "code": "def selected_classification(self):\n        item = self.lstClassifications.currentItem()\n        try:\n            return definition(item.data(QtCore.Qt.UserRole))\n        except (AttributeError, NameError):\n            return None",
    "docstring": "Obtain the classification selected by user.\n\n        :returns: Metadata of the selected classification.\n        :rtype: dict, None"
  },
  {
    "code": "def solve_sweep_wavelength(\n        self,\n        structure,\n        wavelengths,\n        filename=\"wavelength_n_effs.dat\",\n        plot=True,\n    ):\n        n_effs = []\n        for w in tqdm.tqdm(wavelengths, ncols=70):\n            structure.change_wavelength(w)\n            self.solve(structure)\n            n_effs.append(np.real(self.n_effs))\n        if filename:\n            self._write_n_effs_to_file(\n                n_effs, self._modes_directory + filename, wavelengths\n            )\n            if plot:\n                if MPL:\n                    title = \"$n_{eff}$ vs Wavelength\"\n                    y_label = \"$n_{eff}$\"\n                else:\n                    title = \"n_{effs} vs Wavelength\" % x_label\n                    y_label = \"n_{eff}\"\n                self._plot_n_effs(\n                    self._modes_directory + filename,\n                    self._modes_directory + \"fraction_te.dat\",\n                    \"Wavelength\",\n                    \"n_{eff}\",\n                    title,\n                )\n        return n_effs",
    "docstring": "Solve for the effective indices of a fixed structure at\n        different wavelengths.\n\n        Args:\n            structure (Slabs): The target structure to solve\n                for modes.\n            wavelengths (list): A list of wavelengths to sweep\n                over.\n            filename (str): The nominal filename to use when saving the\n                effective indices.  Defaults to 'wavelength_n_effs.dat'.\n            plot (bool): `True` if plots should be generates,\n                otherwise `False`.  Default is `True`.\n\n        Returns:\n            list: A list of the effective indices found for each wavelength."
  },
  {
    "code": "def equivalent_crust_cohesion(self):\n        deprecation(\"Will be moved to a function\")\n        if len(self.layers) > 1:\n            crust = self.layer(0)\n            crust_phi_r = np.radians(crust.phi)\n            equivalent_cohesion = crust.cohesion + crust.k_0 * self.crust_effective_unit_weight * \\\n                                                    self.layer_depth(1) / 2 * np.tan(crust_phi_r)\n            return equivalent_cohesion",
    "docstring": "Calculate the equivalent crust cohesion strength according to Karamitros et al. 2013 sett, pg 8 eq. 14\n\n        :return: equivalent cohesion [Pa]"
  },
  {
    "code": "def get_section2items(self, itemkey):\n        sec_items = []\n        section2usrnts = self.get_section2usrnts()\n        for section, usrnts in section2usrnts.items():\n            items = set([e for nt in usrnts for e in getattr(nt, itemkey, set())])\n            sec_items.append((section, items))\n        return cx.OrderedDict(sec_items)",
    "docstring": "Collect all items into a single set per section."
  },
  {
    "code": "def create(gandi, private_key, certificate, certificate_id):\n    if not certificate and not certificate_id:\n        gandi.echo('One of --certificate or --certificate-id is needed.')\n        return\n    if certificate and certificate_id:\n        gandi.echo('Only one of --certificate or --certificate-id is needed.')\n    if os.path.isfile(private_key):\n        with open(private_key) as fhandle:\n            private_key = fhandle.read()\n    if certificate:\n        if os.path.isfile(certificate):\n            with open(certificate) as fhandle:\n                certificate = fhandle.read()\n    else:\n        cert = gandi.certificate.info(certificate_id)\n        certificate = gandi.certificate.pretty_format_cert(cert)\n    result = gandi.hostedcert.create(private_key, certificate)\n    output_keys = ['id', 'subject', 'date_created', 'date_expire',\n                   'fqdns', 'vhosts']\n    output_hostedcert(gandi, result, output_keys)\n    return result",
    "docstring": "Create a new hosted certificate."
  },
  {
    "code": "def _sync_outlineexplorer_file_order(self):\r\n        if self.outlineexplorer is not None:\r\n            self.outlineexplorer.treewidget.set_editor_ids_order(\r\n                [finfo.editor.get_document_id() for finfo in self.data])",
    "docstring": "Order the root file items of the outline explorer as in the tabbar\r\n        of the current EditorStack."
  },
  {
    "code": "def fetch_request_ids(item_ids, cls, attr_name, verification_list=None):\n    if not item_ids:\n        return []\n    items = []\n    for item_id in item_ids:\n        item = cls.fetch_by_id(item_id)\n        if not item or (verification_list is not None and\n                        item not in verification_list):\n            raise InvalidId(attr_name)\n        items.append(item)\n    return items",
    "docstring": "Return a list of cls instances for all the ids provided in item_ids.\n\n    :param item_ids: The list of ids to fetch objects for\n    :param cls: The class to fetch the ids from\n    :param attr_name: The name of the attribute for exception purposes\n    :param verification_list: If provided, a list of acceptable instances\n\n    Raise InvalidId exception using attr_name if any do not\n        exist, or are not present in the verification_list."
  },
  {
    "code": "def constraints(self, chunk):\n        a = [self._map1[w.index] for w in chunk.words if w.index in self._map1]\n        b = []; [b.append(constraint) for constraint in a if constraint not in b]\n        return b",
    "docstring": "Returns a list of constraints that match the given Chunk."
  },
  {
    "code": "def outlier_cutoff(a, threshold=3.5):\n    A = np.array(a, dtype=float)\n    M = np.median(A)\n    D = np.absolute(A - M)\n    MAD = np.median(D)\n    C = threshold / .67449 * MAD\n    return M - C, M + C",
    "docstring": "Iglewicz and Hoaglin's robust, returns the cutoff values - lower bound and\n    upper bound."
  },
  {
    "code": "def memory_data():\n    vm = psutil.virtual_memory()\n    sw = psutil.swap_memory()\n    return {\n        'virtual': {\n            'total': mark(vm.total, 'bytes'),\n            'free': mark(vm.free, 'bytes'),\n            'percent': mark(vm.percent, 'percentage')\n        },\n        'swap': {\n            'total': mark(sw.total, 'bytes'),\n            'free': mark(sw.free, 'bytes'),\n            'percent': mark(sw.percent, 'percentage')\n        },\n    }",
    "docstring": "Returns memory data."
  },
  {
    "code": "def center_land(world):\n    y_sums = world.layers['elevation'].data.sum(1)\n    y_with_min_sum = y_sums.argmin()\n    if get_verbose():\n        print(\"geo.center_land: height complete\")\n    x_sums = world.layers['elevation'].data.sum(0)\n    x_with_min_sum = x_sums.argmin()\n    if get_verbose():\n        print(\"geo.center_land: width complete\")\n    latshift = 0\n    world.layers['elevation'].data = numpy.roll(numpy.roll(world.layers['elevation'].data, -y_with_min_sum + latshift, axis=0), - x_with_min_sum, axis=1)\n    world.layers['plates'].data = numpy.roll(numpy.roll(world.layers['plates'].data, -y_with_min_sum + latshift, axis=0), - x_with_min_sum, axis=1)\n    if get_verbose():\n        print(\"geo.center_land: width complete\")",
    "docstring": "Translate the map horizontally and vertically to put as much ocean as\n       possible at the borders. It operates on elevation and plates map"
  },
  {
    "code": "def SUB(classical_reg, right):\n    left, right = unpack_reg_val_pair(classical_reg, right)\n    return ClassicalSub(left, right)",
    "docstring": "Produce a SUB instruction.\n\n    :param classical_reg: Left operand for the arithmetic operation. Also serves as the store target.\n    :param right: Right operand for the arithmetic operation.\n    :return: A ClassicalSub instance."
  },
  {
    "code": "def analyze(self, webpage):\n        detected_apps = set()\n        for app_name, app in self.apps.items():\n            if self._has_app(app, webpage):\n                detected_apps.add(app_name)\n        detected_apps |= self._get_implied_apps(detected_apps)\n        return detected_apps",
    "docstring": "Return a list of applications that can be detected on the web page."
  },
  {
    "code": "def add_options(cls, manager):\n        kw = {}\n        if flake8.__version__ >= '3.0.0':\n            kw['parse_from_config'] = True\n        manager.add_option(\n            \"--known-modules\",\n            action='store',\n            default=\"\",\n            help=(\n                \"User defined mapping between a project name and a list of\"\n                \" provided modules. For example: ``--known-modules=project:\"\n                \"[Project],extra-project:[extras,utilities]``.\"\n            ),\n            **kw\n        )",
    "docstring": "Register plug-in specific options."
  },
  {
    "code": "def extract_data(data_path, feature):\n    population = nm.load_neurons(data_path)\n    feature_data = [nm.get(feature, n) for n in population]\n    feature_data = list(chain(*feature_data))\n    return stats.optimal_distribution(feature_data)",
    "docstring": "Loads a list of neurons, extracts feature\n       and transforms the fitted distribution in the correct format.\n       Returns the optimal distribution, corresponding parameters,\n       minimun and maximum values."
  },
  {
    "code": "def one_or_none(self):\n        if self._metadata is not None:\n            raise RuntimeError(\n                \"Can not call `.one` or `.one_or_none` after \"\n                \"stream consumption has already started.\"\n            )\n        iterator = iter(self)\n        try:\n            answer = next(iterator)\n        except StopIteration:\n            return None\n        try:\n            next(iterator)\n            raise ValueError(\"Expected one result; got more.\")\n        except StopIteration:\n            return answer",
    "docstring": "Return exactly one result, or None if there are no results.\n\n        :raises: :exc:`ValueError`: If there are multiple results.\n        :raises: :exc:`RuntimeError`: If consumption has already occurred,\n            in whole or in part."
  },
  {
    "code": "def start_watcher(conf, watcher_plugin_class, health_plugin_class,\n                  iterations=None, sleep_time=1):\n    if CURRENT_STATE._stop_all:\n        logging.debug(\"Not starting plugins: Global stop\")\n        return\n    watcher_plugin, health_plugin = \\\n            start_plugins(conf, watcher_plugin_class, health_plugin_class,\n                          sleep_time)\n    CURRENT_STATE.add_plugin(watcher_plugin)\n    CURRENT_STATE.add_plugin(health_plugin)\n    _event_monitor_loop(conf['region_name'], conf['vpc_id'],\n                        watcher_plugin, health_plugin,\n                        iterations, sleep_time, conf['route_recheck_interval'])\n    stop_plugins(watcher_plugin, health_plugin)",
    "docstring": "Start watcher loop, listening for config changes or failed hosts.\n\n    Also starts the various service threads.\n\n    VPC router watches for any changes in the config and updates/adds/deletes\n    routes as necessary. If failed hosts are reported, routes are also updated\n    as needed.\n\n    This function starts a few working threads:\n\n    - The watcher plugin to monitor for updated route specs.\n    - A health monitor plugin for instances mentioned in the route spec.\n\n    It then drops into a loop to receive messages from the health monitoring\n    thread and watcher plugin and re-process the config if any failed IPs are\n    reported.\n\n    The loop itself is in its own function to facilitate easier testing."
  },
  {
    "code": "def regular_index(*dfs):\n    original_index = [df.index for df in dfs]\n    have_bad_index = [not isinstance(df.index, pd.RangeIndex)\n                      for df in dfs]\n    for df, bad in zip(dfs, have_bad_index):\n        if bad:\n            df.reset_index(drop=True, inplace=True)\n    try:\n        yield dfs\n    finally:\n        for df, bad, idx in zip(dfs, have_bad_index, original_index):\n            if bad and len(df.index) == len(idx):\n                df.index = idx",
    "docstring": "Change & restore the indices of dataframes\n\n    Dataframe with duplicate values can be hard to work with.\n    When split and recombined, you cannot restore the row order.\n    This can be the case even if the index has unique but\n    irregular/unordered. This contextmanager resets the unordered\n    indices of any dataframe passed to it, on exit it restores\n    the original index.\n\n    A regular index is of the form::\n\n        RangeIndex(start=0, stop=n, step=1)\n\n    Parameters\n    ----------\n    dfs : tuple\n        Dataframes\n\n    Yields\n    ------\n    dfs : tuple\n        Dataframe\n\n    Examples\n    --------\n    Create dataframes with different indices\n\n    >>> df1 = pd.DataFrame([4, 3, 2, 1])\n    >>> df2 = pd.DataFrame([3, 2, 1], index=[3, 0, 0])\n    >>> df3 = pd.DataFrame([11, 12, 13], index=[11, 12, 13])\n\n    Within the contexmanager all frames have nice range indices\n\n    >>> with regular_index(df1, df2, df3):\n    ...     print(df1.index)\n    ...     print(df2.index)\n    ...     print(df3.index)\n    RangeIndex(start=0, stop=4, step=1)\n    RangeIndex(start=0, stop=3, step=1)\n    RangeIndex(start=0, stop=3, step=1)\n\n    Indices restored\n\n    >>> df1.index\n    RangeIndex(start=0, stop=4, step=1)\n    >>> df2.index\n    Int64Index([3, 0, 0], dtype='int64')\n    >>> df3.index\n    Int64Index([11, 12, 13], dtype='int64')"
  },
  {
    "code": "def get (self, key, def_val=None):\n        assert isinstance(key, basestring)\n        return dict.get(self, key.lower(), def_val)",
    "docstring": "Return lowercase key value."
  },
  {
    "code": "def contains(self, val):\n        (start, end) = self.__val_convert(val)\n        retlen = 0\n        for r in self.__has:\n            if start < r[1] and end > r[0]:\n                retlen += ((end < r[1] and end) or r[1]) - ((start > r[0] and start) or r[0])\n        return retlen",
    "docstring": "Check if given value or range is present.\n\n        Parameters\n        ----------\n        val : int or tuple or list or range\n            Range or integer being checked.\n\n        Returns\n        -------\n        retlen : int\n            Length of overlapping with `val` subranges."
  },
  {
    "code": "def _has_streamhandler(logger, level=None, fmt=LOG_FORMAT,\n                       stream=DEFAULT_STREAM):\n    if isinstance(level, basestring):\n        level = logging.getLevelName(level)\n    for handler in logger.handlers:\n        if not isinstance(handler, logging.StreamHandler):\n            continue\n        if handler.stream is not stream:\n            continue\n        if handler.level != level:\n            continue\n        if not handler.formatter or handler.formatter._fmt != fmt:\n            continue\n        return True\n    return False",
    "docstring": "Check the named logger for an appropriate existing StreamHandler.\n\n    This only returns True if a StreamHandler that exaclty matches\n    our specification is found. If other StreamHandlers are seen,\n    we assume they were added for a different purpose."
  },
  {
    "code": "def is_empty(bam_file):\n    bam_file = objectstore.cl_input(bam_file)\n    cmd = (\"set -o pipefail; \"\n           \"samtools view {bam_file} | head -1 | wc -l\")\n    p = subprocess.Popen(cmd.format(**locals()), shell=True,\n                         executable=do.find_bash(),\n                         stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n                         preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL))\n    stdout, stderr = p.communicate()\n    stdout = stdout.decode()\n    stderr = stderr.decode()\n    if ((p.returncode == 0 or p.returncode == 141) and\n         (stderr == \"\" or (stderr.startswith(\"gof3r\") and stderr.endswith(\"broken pipe\")))):\n        return int(stdout) == 0\n    else:\n        raise ValueError(\"Failed to check empty status of BAM file: %s\" % str(stderr))",
    "docstring": "Determine if a BAM file is empty"
  },
  {
    "code": "def setup_catalog_mappings(portal):\n    logger.info(\"*** Setup Catalog Mappings ***\")\n    at = api.get_tool(\"archetype_tool\")\n    for portal_type, catalogs in CATALOG_MAPPINGS:\n        at.setCatalogsByType(portal_type, catalogs)",
    "docstring": "Setup portal_type -> catalog mappings"
  },
  {
    "code": "def func_source_data(func):\n    filename = inspect.getsourcefile(func)\n    lineno = inspect.getsourcelines(func)[1]\n    source = inspect.getsource(func)\n    return filename, lineno, source",
    "docstring": "Return data about a function source, including file name,\n    line number, and source code.\n\n    Parameters\n    ----------\n    func : object\n        May be anything support by the inspect module, such as a function,\n        method, or class.\n\n    Returns\n    -------\n    filename : str\n    lineno : int\n        The line number on which the function starts.\n    source : str"
  },
  {
    "code": "def _get_param(self, section, key, config, default=None):\n        if section in config and key in config[section]:\n            return config[section][key]\n        if default is not None:\n            return default\n        else:\n            raise MissingParameter(section, key)",
    "docstring": "Get configuration parameter \"key\" from config\n        @str section: the section of the config file\n        @str key: the key to get\n        @dict config: the configuration (dictionnary)\n        @str default: the default value if parameter \"key\" is not present\n        @rtype: str (value of config['key'] if present default otherwith"
  },
  {
    "code": "def _put(self, rtracker):\n        with self._lock:\n            if self._available < self.capacity:\n                for i in self._unavailable_range():\n                    if self._reference_queue[i] is rtracker:\n                        break\n                else:\n                    raise UnknownResourceError\n                j = self._resource_end\n                rq = self._reference_queue\n                rq[i], rq[j] = rq[j], rq[i]\n                self._resource_end = (self._resource_end + 1) % self.maxsize\n                self._available += 1\n                self._not_empty.notify()\n            else:\n                raise PoolFullError",
    "docstring": "Put a resource back in the queue.\n\n        :param rtracker: A resource.\n        :type rtracker: :class:`_ResourceTracker`\n\n        :raises PoolFullError: If pool is full.\n        :raises UnknownResourceError: If resource can't be found."
  },
  {
    "code": "def recent(self):\n        kwd = {\n            'pager': '',\n            'title': 'Recent Pages',\n        }\n        self.render('wiki_page/wiki_list.html',\n                    view=MWiki.query_recent(),\n                    format_date=tools.format_date,\n                    kwd=kwd,\n                    userinfo=self.userinfo)",
    "docstring": "List recent wiki."
  },
  {
    "code": "def plot(self, **kwds):\n        ax = plt.gca()\n        self.coords.plot.scatter(x=0, y=1, ax=ax, **kwds)\n        ax.get_xaxis().set_major_locator(MultipleLocator(base=1.0))\n        ax.get_yaxis().set_major_locator(MultipleLocator(base=1.0))\n        ax.set_xticklabels([])\n        ax.set_yticklabels([])\n        ax.set_xlabel('')\n        ax.set_ylabel('')\n        ax.set_aspect(1)\n        return ax",
    "docstring": "Plot the coordinates in the first two dimensions of the projection.\n\n        Removes axis and tick labels, and sets the grid spacing to 1 unit.\n        One way to display the grid is to use `Seaborn`_:\n\n        Args:\n            **kwds: Passed to :py:meth:`pandas.DataFrame.plot.scatter`.\n\n        Examples:\n\n            >>> from pymds import DistanceMatrix\n            >>> import pandas as pd\n            >>> import seaborn as sns\n            >>> sns.set_style('whitegrid')\n            >>> dist = pd.DataFrame({\n            ...    'a': [0.0, 1.0, 2.0],\n            ...    'b': [1.0, 0.0, 3 ** 0.5],\n            ...    'c': [2.0, 3 ** 0.5, 0.0]} , index=['a', 'b', 'c'])\n            >>> dm = DistanceMatrix(dist)\n            >>> pro = dm.optimize()\n            >>> ax = pro.plot(c='black', s=50, edgecolor='white')\n\n        Returns:\n            :py:obj:`matplotlib.axes.Axes`\n\n        .. _Seaborn:\n            https://seaborn.pydata.org/"
  },
  {
    "code": "def get_version():\n    config = RawConfigParser()\n    config.read(os.path.join('..', 'setup.cfg'))\n    return config.get('metadata', 'version')",
    "docstring": "Return package version from setup.cfg"
  },
  {
    "code": "def _get_record(self, model_class, record_id):\n        url = '{host}/{namespace}/{model}/{id}'.format(\n            host=self._host,\n            namespace=self._namespace,\n            model=self._translate_name(model_class.__name__),\n            id=record_id\n        )\n        data = self._get_json(url)['data']\n        fresh_model = model_class(data['attributes'])\n        fresh_model.id = data['id']\n        fresh_model.validate()\n        if self._cache is not None:\n            self._cache.set_record(model_class.__name__, fresh_model.id, fresh_model)\n        return fresh_model",
    "docstring": "Get a single record from the API.\n\n        Args:\n            model_class (:class:`cinder_data.model.CinderModel`): A subclass of\n                :class:`cinder_data.model.CinderModel` of your chosen model.\n            record_id (int): The id of the record requested.\n\n        Returns:\n            :class:`cinder_data.model.CinderModel`: An instance of model_class or None."
  },
  {
    "code": "def set_sdk_enabled(cls, value):\n        if cls.XRAY_ENABLED_KEY in os.environ:\n            cls.__SDK_ENABLED = str(os.getenv(cls.XRAY_ENABLED_KEY, 'true')).lower() != 'false'\n        else:\n            if type(value) == bool:\n                cls.__SDK_ENABLED = value\n            else:\n                cls.__SDK_ENABLED = True\n                log.warning(\"Invalid parameter type passed into set_sdk_enabled(). Defaulting to True...\")",
    "docstring": "Modifies the enabled flag if the \"AWS_XRAY_SDK_ENABLED\" environment variable is not set,\n        otherwise, set the enabled flag to be equal to the environment variable. If the\n        env variable is an invalid string boolean, it will default to true.\n\n        :param bool value: Flag to set whether the SDK is enabled or disabled.\n\n        Environment variables AWS_XRAY_SDK_ENABLED overrides argument value."
  },
  {
    "code": "def nonnegative_float(s):\n    err_msg = \"must be either positive or zero, not %r\" % s\n    try:\n        value = float(s)\n    except ValueError:\n        raise argparse.ArgumentTypeError(err_msg)\n    if value < 0:\n        raise argparse.ArgumentTypeError(err_msg)\n    return value",
    "docstring": "Ensure argument is a positive real number or zero and return it as float.\n\n    To be used as type in argparse arguments."
  },
  {
    "code": "def first_active(self):\n        result = None\n        for actor in self.actors:\n            if not actor.skip:\n                result = actor\n                break\n        return result",
    "docstring": "Returns the first non-skipped actor.\n\n        :return: the first active actor, None if not available\n        :rtype: Actor"
  },
  {
    "code": "def _check_env_var(envvar: str) -> bool:\n    if os.getenv(envvar) is None:\n        raise KeyError(\n            \"Required ENVVAR: {0} is not set\".format(envvar))\n    if not os.getenv(envvar):\n        raise KeyError(\n            \"Required ENVVAR: {0} is empty\".format(envvar))\n    return True",
    "docstring": "Check Environment Variable to verify that it is set and not empty.\n\n    :param envvar: Environment Variable to Check.\n\n    :returns: True if Environment Variable is set and not empty.\n\n    :raises: KeyError if Environment Variable is not set or is empty.\n\n    .. versionadded:: 0.0.12"
  },
  {
    "code": "def html2rst(html_string, force_headers=False, center_cells=False,\n             center_headers=False):\n    if os.path.isfile(html_string):\n        file = open(html_string, 'r', encoding='utf-8')\n        lines = file.readlines()\n        file.close()\n        html_string = ''.join(lines)\n    table_data, spans, use_headers = html2data(\n        html_string)\n    if table_data == '':\n        return ''\n    if force_headers:\n        use_headers = True\n    return data2rst(table_data, spans, use_headers, center_cells, center_headers)",
    "docstring": "Convert a string or html file to an rst table string.\n\n    Parameters\n    ----------\n    html_string : str\n        Either the html string, or the filepath to the html\n    force_headers : bool\n        Make the first row become headers, whether or not they are\n        headers in the html file.\n    center_cells : bool\n        Whether or not to center the contents of the cells\n    center_headers : bool\n        Whether or not to center the contents of the header cells\n\n    Returns\n    -------\n    str\n        The html table converted to an rst grid table\n\n    Notes\n    -----\n    This function **requires** BeautifulSoup_ to work.\n\n    Example\n    -------\n    >>> html_text = '''\n    ... <table>\n    ...     <tr>\n    ...         <th>\n    ...             Header 1\n    ...         </th>\n    ...         <th>\n    ...             Header 2\n    ...         </th>\n    ...         <th>\n    ...             Header 3\n    ...         </th>\n    ...     <tr>\n    ...         <td>\n    ...             <p>This is a paragraph</p>\n    ...         </td>\n    ...         <td>\n    ...             <ul>\n    ...                 <li>List item 1</li>\n    ...                 <li>List item 2</li>\n    ...             </ul>\n    ...         </td>\n    ...         <td>\n    ...             <ol>\n    ...                 <li>Ordered 1</li>\n    ...                 <li>Ordered 2</li>\n    ...             </ol>\n    ...         </td>\n    ...     </tr>\n    ... </table>\n    ... '''\n    >>> import dashtable\n    >>> print(dashtable.html2rst(html_text))\n    +---------------------+----------------+--------------+\n    | Header 1            | Header 2       | Header 3     |\n    +=====================+================+==============+\n    | This is a paragraph | -  List item 1 | #. Ordered 1 |\n    |                     | -  List item 2 | #. Ordered 2 |\n    +---------------------+----------------+--------------+\n\n    .. _BeautifulSoup: https://www.crummy.com/software/BeautifulSoup/"
  },
  {
    "code": "def unpack(packet):\n    validate_packet(packet)\n    version = packet[0]\n    try:\n        pyof_lib = PYOF_VERSION_LIBS[version]\n    except KeyError:\n        raise UnpackException('Version not supported')\n    try:\n        message = pyof_lib.common.utils.unpack_message(packet)\n        return message\n    except (UnpackException, ValueError) as exception:\n        raise UnpackException(exception)",
    "docstring": "Unpack the OpenFlow Packet and returns a message.\n\n    Args:\n        packet: buffer with the openflow packet.\n\n    Returns:\n        GenericMessage: Message unpacked based on openflow packet.\n\n    Raises:\n        UnpackException: if the packet can't be unpacked."
  },
  {
    "code": "def first(self, offset):\n        if not isinstance(self.index, DatetimeIndex):\n            raise TypeError(\"'first' only supports a DatetimeIndex index\")\n        if len(self.index) == 0:\n            return self\n        offset = to_offset(offset)\n        end_date = end = self.index[0] + offset\n        if not offset.isAnchored() and hasattr(offset, '_inc'):\n            if end_date in self.index:\n                end = self.index.searchsorted(end_date, side='left')\n                return self.iloc[:end]\n        return self.loc[:end]",
    "docstring": "Convenience method for subsetting initial periods of time series data\n        based on a date offset.\n\n        Parameters\n        ----------\n        offset : string, DateOffset, dateutil.relativedelta\n\n        Returns\n        -------\n        subset : same type as caller\n\n        Raises\n        ------\n        TypeError\n            If the index is not  a :class:`DatetimeIndex`\n\n        See Also\n        --------\n        last : Select final periods of time series based on a date offset.\n        at_time : Select values at a particular time of the day.\n        between_time : Select values between particular times of the day.\n\n        Examples\n        --------\n        >>> i = pd.date_range('2018-04-09', periods=4, freq='2D')\n        >>> ts = pd.DataFrame({'A': [1,2,3,4]}, index=i)\n        >>> ts\n                    A\n        2018-04-09  1\n        2018-04-11  2\n        2018-04-13  3\n        2018-04-15  4\n\n        Get the rows for the first 3 days:\n\n        >>> ts.first('3D')\n                    A\n        2018-04-09  1\n        2018-04-11  2\n\n        Notice the data for 3 first calender days were returned, not the first\n        3 days observed in the dataset, and therefore data for 2018-04-13 was\n        not returned."
  },
  {
    "code": "def confirmation(self, pdu):\n        if _debug: StreamToPacket._debug(\"StreamToPacket.confirmation %r\", pdu)\n        for packet in self.packetize(pdu, self.upstreamBuffer):\n            self.response(packet)",
    "docstring": "Message going upstream."
  },
  {
    "code": "def _ParseEntryArrayObject(self, file_object, file_offset):\n    entry_array_object_map = self._GetDataTypeMap(\n        'systemd_journal_entry_array_object')\n    try:\n      entry_array_object, _ = self._ReadStructureFromFileObject(\n          file_object, file_offset, entry_array_object_map)\n    except (ValueError, errors.ParseError) as exception:\n      raise errors.ParseError((\n          'Unable to parse entry array object at offset: 0x{0:08x} with error: '\n          '{1!s}').format(file_offset, exception))\n    if entry_array_object.object_type != self._OBJECT_TYPE_ENTRY_ARRAY:\n      raise errors.ParseError('Unsupported object type: {0:d}.'.format(\n          entry_array_object.object_type))\n    if entry_array_object.object_flags != 0:\n      raise errors.ParseError('Unsupported object flags: 0x{0:02x}.'.format(\n          entry_array_object.object_flags))\n    return entry_array_object",
    "docstring": "Parses an entry array object.\n\n    Args:\n      file_object (dfvfs.FileIO): a file-like object.\n      file_offset (int): offset of the entry array object relative to the start\n          of the file-like object.\n\n    Returns:\n      systemd_journal_entry_array_object: entry array object.\n\n    Raises:\n      ParseError: if the entry array object cannot be parsed."
  },
  {
    "code": "def registrations(self):\n        if self._registrations is None:\n            self._registrations = AuthTypeRegistrationsList(\n                self._version,\n                account_sid=self._solution['account_sid'],\n                domain_sid=self._solution['domain_sid'],\n            )\n        return self._registrations",
    "docstring": "Access the registrations\n\n        :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.AuthTypeRegistrationsList\n        :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.AuthTypeRegistrationsList"
  },
  {
    "code": "def partition_by_vid(self, ref):\n        from ambry.orm import Partition\n        p = self.session.query(Partition).filter(Partition.vid == str(ref)).first()\n        if p:\n            return self.wrap_partition(p)\n        else:\n            return None",
    "docstring": "A much faster way to get partitions, by vid only"
  },
  {
    "code": "def add_filter(self, filter_):\n        assert has_pil, _(\"Cannot add filters without python PIL\")\n        self.cache.basename += filter_.basename\n        self._filters.append(filter_)",
    "docstring": "Add an image filter for post-processing"
  },
  {
    "code": "def _hashi_weight_generator(self, node_name, node_conf):\n        ks = (node_conf['vnodes'] * len(self._nodes) *\n              node_conf['weight']) // self._weight_sum\n        for w in range(0, ks):\n            w_node_name = '%s-%s' % (node_name, w)\n            for i in range(0, self._replicas):\n                yield self.hashi(w_node_name, replica=i)",
    "docstring": "Calculate the weight factor of the given node and\n        yield its hash key for every configured replica.\n\n        :param node_name: the node name."
  },
  {
    "code": "def generate_argument_parser(cls, tree, actions={}):\n        cur_as, cur_subas = tree\n        parser = devassistant_argparse.ArgumentParser(argument_default=argparse.SUPPRESS,\n                                                      usage=argparse.SUPPRESS,\n                                                      add_help=False)\n        cls.add_default_arguments_to(parser)\n        for arg in cur_as.args:\n            arg.add_argument_to(parser)\n        if cur_subas or actions:\n            subparsers = cls._add_subparsers_required(parser,\n                dest=settings.SUBASSISTANT_N_STRING.format('0'))\n            for subas in sorted(cur_subas, key=lambda x: x[0].name):\n                for alias in [subas[0].name] + getattr(subas[0], 'aliases', []):\n                    cls.add_subassistants_to(subparsers, subas, level=1, alias=alias)\n            for action, subactions in sorted(actions.items(), key=lambda x: x[0].name):\n                cls.add_action_to(subparsers, action, subactions, level=1)\n        return parser",
    "docstring": "Generates argument parser for given assistant tree and actions.\n\n        Args:\n            tree: assistant tree as returned by\n                  devassistant.assistant_base.AssistantBase.get_subassistant_tree\n            actions: dict mapping actions (devassistant.actions.Action subclasses) to their\n                     subaction dicts\n        Returns:\n            instance of devassistant_argparse.ArgumentParser (subclass of argparse.ArgumentParser)"
  },
  {
    "code": "def remove_log_action(portal):\n    logger.info(\"Removing Log Tab ...\")\n    portal_types = api.get_tool(\"portal_types\")\n    for name in portal_types.listContentTypes():\n        ti = portal_types[name]\n        actions = map(lambda action: action.id, ti._actions)\n        for index, action in enumerate(actions):\n            if action == \"log\":\n                logger.info(\"Removing Log Action for {}\".format(name))\n                ti.deleteActions([index])\n                break\n    logger.info(\"Removing Log Tab [DONE]\")",
    "docstring": "Removes the old Log action from types"
  },
  {
    "code": "def get_table_key(key, d, fallback=\"\"):\n    try:\n        var = d[key]\n        return var\n    except KeyError:\n        logger_misc.info(\"get_variable_name_table: KeyError: missing {}, use name: {}\".format(key, fallback))\n        return fallback",
    "docstring": "Try to get a table name from a data table\n\n    :param str key: Key to try first\n    :param dict d: Data table\n    :param str fallback: (optional) If we don't find a table name, use this as a generic name fallback.\n    :return str var: Data table name"
  },
  {
    "code": "def do_bb_intersect(a, b):\n    return a.p1.x <= b.p2.x \\\n        and a.p2.x >= b.p1.x \\\n        and a.p1.y <= b.p2.y \\\n        and a.p2.y >= b.p1.y",
    "docstring": "Check if BoundingBox a intersects with BoundingBox b."
  },
  {
    "code": "def model_factory(schema, resolver=None, base_class=model.Model, name=None):\n    schema = copy.deepcopy(schema)\n    resolver = resolver\n    class Model(base_class):\n        def __init__(self, *args, **kwargs):\n            self.__dict__['schema'] = schema\n            self.__dict__['resolver'] = resolver\n            base_class.__init__(self, *args, **kwargs)\n    if resolver is not None:\n        Model.resolver = resolver\n    if name is not None:\n        Model.__name__ = name\n    elif 'name' in schema:\n        Model.__name__ = str(schema['name'])\n    return Model",
    "docstring": "Generate a model class based on the provided JSON Schema\n\n    :param schema: dict representing valid JSON schema\n    :param name: A name to give the class, if `name` is not in `schema`"
  },
  {
    "code": "def new_bundle(self, name: str, created_at: dt.datetime=None) -> models.Bundle:\n        new_bundle = self.Bundle(name=name, created_at=created_at)\n        return new_bundle",
    "docstring": "Create a new file bundle."
  },
  {
    "code": "def _Assign(self, t):\n        self._fill()\n        for target in t.nodes:\n            self._dispatch(target)\n            self._write(\" = \")\n        self._dispatch(t.expr)\n        if not self._do_indent:\n            self._write('; ')",
    "docstring": "Expression Assignment such as \"a = 1\".\n\n            This only handles assignment in expressions.  Keyword assignment\n            is handled separately."
  },
  {
    "code": "def security_errors(self):\n        errors = ErrorDict()\n        for f in [\"honeypot\", \"timestamp\", \"security_hash\"]:\n            if f in self.errors:\n                errors[f] = self.errors[f]\n        return errors",
    "docstring": "Return just those errors associated with security"
  },
  {
    "code": "def rows(self, cell_mode=CellMode.cooked):\n    for row_index in range(self.nrows):\n      yield self.parse_row(self.get_row(row_index), row_index, cell_mode)",
    "docstring": "Generates a sequence of parsed rows from the worksheet. The cells are parsed according to the\n    cell_mode argument."
  },
  {
    "code": "def call_spellchecker(cmd, input_text=None, encoding=None):\n    process = get_process(cmd)\n    if input_text is not None:\n        for line in input_text.splitlines():\n            offset = 0\n            end = len(line)\n            while True:\n                chunk_end = offset + 0x1fff\n                m = None if chunk_end >= end else RE_LAST_SPACE_IN_CHUNK.search(line, offset, chunk_end)\n                if m:\n                    chunk_end = m.start(1)\n                    chunk = line[offset:m.start(1)]\n                    offset = m.end(1)\n                else:\n                    chunk = line[offset:chunk_end]\n                    offset = chunk_end\n                if chunk and not chunk.isspace():\n                    process.stdin.write(chunk + b'\\n')\n                if offset >= end:\n                    break\n    return get_process_output(process, encoding)",
    "docstring": "Call spell checker with arguments."
  },
  {
    "code": "def _linreg_future(self, series, since, days=20):\n        last_days = pd.date_range(end=since, periods=days)\n        hist = self.history(last_days)\n        xi = np.array(map(dt2ts, hist.index))\n        A = np.array([xi, np.ones(len(hist))])\n        y = hist.values\n        w = np.linalg.lstsq(A.T, y)[0]\n        for d in series.index[series.index > since]:\n            series[d] = w[0] * dt2ts(d) + w[1]\n            series[d] = 0 if series[d] < 0 else series[d]\n        return series",
    "docstring": "Predicts future using linear regression.\n\n        :param series:\n            A series in which the values will be places.\n            The index will not be touched.\n            Only the values on dates > `since` will be predicted.\n        :param since:\n            The starting date from which the future will be predicted.\n        :param days:\n            Specifies how many past days should be used in the linear\n            regression."
  },
  {
    "code": "def clone(self):\n        base_dir = '/'.join(self.path.split('/')[:-2])\n        try:\n            os.makedirs(base_dir, 0o700)\n        except OSError:\n            pass\n        self._cmd(['git', 'clone', self._clone_url, self.path], cwd=os.getcwd())",
    "docstring": "Clones a directory based on the clone_url and plugin_name given to the\n        constructor. The clone will be located at self.path."
  },
  {
    "code": "def _avro_schema(read_session):\n    json_schema = json.loads(read_session.avro_schema.schema)\n    column_names = tuple((field[\"name\"] for field in json_schema[\"fields\"]))\n    return fastavro.parse_schema(json_schema), column_names",
    "docstring": "Extract and parse Avro schema from a read session.\n\n    Args:\n        read_session ( \\\n            ~google.cloud.bigquery_storage_v1beta1.types.ReadSession \\\n        ):\n            The read session associated with this read rows stream. This\n            contains the schema, which is required to parse the data\n            blocks.\n\n    Returns:\n        Tuple[fastavro.schema, Tuple[str]]:\n            A parsed Avro schema, using :func:`fastavro.schema.parse_schema`\n            and the column names for a read session."
  },
  {
    "code": "def set_active_state(self, name, value):\n        if name not in self.__active_states.keys():\n            raise ValueError(\"Can not set unknown state '\" + name + \"'\")\n        if (isinstance(self.__active_states[name], int) and\n                isinstance(value, str)):\n            self.__active_states[name] = int(value)\n        elif (isinstance(self.__active_states[name], float) and\n              isinstance(value, str)):\n            self.__active_states[name] = float(value)\n        else:\n            self.__active_states[name] = value",
    "docstring": "Set active state."
  },
  {
    "code": "def get_task_positions_objs(client, list_id):\n    params = {\n            'list_id' : int(list_id)\n            }\n    response = client.authenticated_request(client.api.Endpoints.TASK_POSITIONS, params=params)\n    return response.json()",
    "docstring": "Gets a list containing the object that encapsulates information about the order lists are laid out in. This list will always contain exactly one object.\n\n    See https://developer.wunderlist.com/documentation/endpoints/positions for more info\n\n    Return:\n    A list containing a single ListPositionsObj-mapped object"
  },
  {
    "code": "def join(self, table, one=None,\n             operator=None, two=None, type='inner', where=False):\n        if isinstance(table, JoinClause):\n            self.joins.append(table)\n        else:\n            if one is None:\n                raise ArgumentError('Missing \"one\" argument')\n            join = JoinClause(table, type)\n            self.joins.append(join.on(\n                one, operator, two, 'and', where\n            ))\n        return self",
    "docstring": "Add a join clause to the query\n\n        :param table: The table to join with, can also be a JoinClause instance\n        :type table: str or JoinClause\n\n        :param one: The first column of the join condition\n        :type one: str\n\n        :param operator: The operator of the join condition\n        :type operator: str\n\n        :param two: The second column of the join condition\n        :type two: str\n\n        :param type: The join type\n        :type type: str\n\n        :param where: Whether to use a \"where\" rather than a \"on\"\n        :type where: bool\n\n        :return: The current QueryBuilder instance\n        :rtype: QueryBuilder"
  },
  {
    "code": "def download_all(data_home=None, replace=False):\n    for _, meta in DATASETS.items():\n        download_data(\n            meta['url'], meta['signature'], data_home=data_home, replace=replace\n        )\n    print(\n        \"Downloaded {} datasets to {}\".format(len(DATASETS), get_data_home(data_home))\n    )",
    "docstring": "Downloads all the example datasets to the data directory specified by\n    ``get_data_home``. This function ensures that all datasets are available\n    for use with the examples."
  },
  {
    "code": "def pdftoxml(pdfdata, options=\"\"):\n    pdffout = tempfile.NamedTemporaryFile(suffix='.pdf')\n    pdffout.write(pdfdata)\n    pdffout.flush()\n    xmlin = tempfile.NamedTemporaryFile(mode='r', suffix='.xml')\n    tmpxml = xmlin.name\n    cmd = 'pdftohtml -xml -nodrm -zoom 1.5 -enc UTF-8 -noframes %s \"%s\" \"%s\"' % (\n        options, pdffout.name, os.path.splitext(tmpxml)[0])\n    cmd = cmd + \" >/dev/null 2>&1\"\n    os.system(cmd)\n    pdffout.close()\n    xmldata = xmlin.read()\n    xmlin.close()\n    return xmldata.decode('utf-8')",
    "docstring": "converts pdf file to xml file"
  },
  {
    "code": "def report_estimation_accuracy(request):\n    contracts = ProjectContract.objects.filter(\n        status=ProjectContract.STATUS_COMPLETE,\n        type=ProjectContract.PROJECT_FIXED\n    )\n    data = [('Target (hrs)', 'Actual (hrs)', 'Point Label')]\n    for c in contracts:\n        if c.contracted_hours() == 0:\n            continue\n        pt_label = \"%s (%.2f%%)\" % (c.name,\n                                    c.hours_worked / c.contracted_hours() * 100)\n        data.append((c.contracted_hours(), c.hours_worked, pt_label))\n        chart_max = max([max(x[0], x[1]) for x in data[1:]])\n    return render(request, 'timepiece/reports/estimation_accuracy.html', {\n        'data': json.dumps(data, cls=DecimalEncoder),\n        'chart_max': chart_max,\n    })",
    "docstring": "Idea from Software Estimation, Demystifying the Black Art, McConnel 2006 Fig 3-3."
  },
  {
    "code": "def format_manager(cls):\n        if cls._instance is None:\n            cls._instance = cls().register_entrypoints()\n        return cls._instance",
    "docstring": "Return the instance singleton, creating if necessary"
  },
  {
    "code": "def paginated_retrieval(methodname, itemtype):\n    return compose(\n        reusable,\n        basic_interaction,\n        map_yield(partial(_params_as_get, methodname)),\n    )",
    "docstring": "decorator factory for retrieval queries from query params"
  },
  {
    "code": "def load_data_and_build(self, filename, delimiter=\",\"):\n        data = np.genfromtxt(\n            filename, dtype=float, delimiter=delimiter, names=True\n        )\n        data = data.view(np.float64).reshape(data.shape + (-1,))\n        X = data[:, 0:-1]\n        Y = data[:, -1]\n        self.build(X=X, Y=Y)",
    "docstring": "Convenience function for directly working with a data file.\n            This opens a file and reads the data into an array, sets the\n            data as an nparray and list of dimnames\n            @ In, filename, string representing the data file"
  },
  {
    "code": "def update_selected(self, linenum):\n        self.parents = _get_parents(self.funcs, linenum)\n        update_selected_cb(self.parents, self.method_cb)\n        self.parents = _get_parents(self.classes, linenum)\n        update_selected_cb(self.parents, self.class_cb)",
    "docstring": "Updates the dropdowns to reflect the current class and function."
  },
  {
    "code": "def register(self, service, provider, singleton=False):\n        def get_singleton(*args, **kwargs):\n            result = self._get_singleton(service)\n            if not result:\n                instantiator = self._get_instantiator(provider)\n                result = instantiator(*args, **kwargs)\n                self._set_singleton(service, result)\n            return result\n        if not callable(provider):\n            self._set_provider(service, lambda *args, **kwargs: provider)\n        elif singleton:\n            self._set_provider(service, get_singleton)\n        else:\n            self._set_provider(service, self._get_instantiator(provider))",
    "docstring": "Registers a service provider for a given service.\n\n        @param service\n            A key that identifies the service being registered.\n        @param provider\n            This is either the service being registered, or a callable that will\n            either instantiate it or return it.\n        @param singleton\n            Indicates that the service is to be registered as a singleton.\n            This is only relevant if the provider is a callable. Services that\n            are not callable will always be registered as singletons."
  },
  {
    "code": "def find_killers(self, var_def, simplified_graph=True):\n        if simplified_graph:\n            graph = self.simplified_data_graph\n        else:\n            graph = self.data_graph\n        if var_def not in graph:\n            return []\n        killers = []\n        out_edges = graph.out_edges(var_def, data=True)\n        for _, dst, data in out_edges:\n            if 'type' in data and data['type'] == 'kill':\n                killers.append(dst)\n        return killers",
    "docstring": "Find all killers to the specified variable definition.\n\n        :param ProgramVariable var_def: The variable definition.\n        :param bool simplified_graph: True if we want to search in the simplified graph, False otherwise.\n        :return: A collection of all killers to the specified variable definition.\n        :rtype: list"
  },
  {
    "code": "def yaml_load(stream):\n    global _HAS_YAML_LIBRARY\n    if _HAS_YAML_LIBRARY is None:\n        _HAS_YAML_LIBRARY = hasattr(yaml, 'CSafeLoader')\n        if not _HAS_YAML_LIBRARY:\n            logger.warning('libyaml was not found! Please install libyaml to'\n                           ' speed up loading the model files.')\n    if _HAS_YAML_LIBRARY:\n        loader = yaml.CSafeLoader(stream)\n    else:\n        loader = yaml.SafeLoader(stream)\n    loader.add_constructor('tag:yaml.org,2002:float', float_constructor)\n    return loader.get_data()",
    "docstring": "Load YAML file using safe loader."
  },
  {
    "code": "def get_config():\n    global token\n    config = configparser.ConfigParser()\n    config.read(os.path.join(os.path.expanduser('~'), '.config/scdl/scdl.cfg'))\n    try:\n        token = config['scdl']['auth_token']\n        path = config['scdl']['path']\n    except:\n        logger.error('Are you sure scdl.cfg is in $HOME/.config/scdl/ ?')\n        logger.error('Are both \"auth_token\" and \"path\" defined there?')\n        sys.exit()\n    if os.path.exists(path):\n        os.chdir(path)\n    else:\n        logger.error('Invalid path in scdl.cfg...')\n        sys.exit()",
    "docstring": "Reads the music download filepath from scdl.cfg"
  },
  {
    "code": "def _ldp_id_adjustlen(pkt, x):\n    f, v = pkt.getfield_and_val('id')\n    return len(_LLDPidField.i2m(f, pkt, v)) + 1",
    "docstring": "Return the length of the `id` field,\n    according to its real encoded type"
  },
  {
    "code": "def static_get_type_attr(t, name):\n    for type_ in t.mro():\n        try:\n            return vars(type_)[name]\n        except KeyError:\n            pass\n    raise AttributeError(name)",
    "docstring": "Get a type attribute statically, circumventing the descriptor protocol."
  },
  {
    "code": "def tconvert(gpsordate='now'):\n    try:\n        float(gpsordate)\n    except (TypeError, ValueError):\n        return to_gps(gpsordate)\n    return from_gps(gpsordate)",
    "docstring": "Convert GPS times to ISO-format date-times and vice-versa.\n\n    Parameters\n    ----------\n    gpsordate : `float`, `astropy.time.Time`, `datetime.datetime`, ...\n        input gps or date to convert, many input types are supported\n\n    Returns\n    -------\n    date : `datetime.datetime` or `LIGOTimeGPS`\n        converted gps or date\n\n    Notes\n    -----\n    If the input object is a `float` or `LIGOTimeGPS`, it will get\n    converted from GPS format into a `datetime.datetime`, otherwise\n    the input will be converted into `LIGOTimeGPS`.\n\n    Examples\n    --------\n    Integers and floats are automatically converted from GPS to\n    `datetime.datetime`:\n\n    >>> from gwpy.time import tconvert\n    >>> tconvert(0)\n    datetime.datetime(1980, 1, 6, 0, 0)\n    >>> tconvert(1126259462.3910)\n    datetime.datetime(2015, 9, 14, 9, 50, 45, 391000)\n\n    while strings are automatically converted to `~gwpy.time.LIGOTimeGPS`:\n\n    >>> to_gps('Sep 14 2015 09:50:45.391')\n    LIGOTimeGPS(1126259462, 391000000)\n\n    Additionally, a few special-case words as supported, which all return\n    `~gwpy.time.LIGOTimeGPS`:\n\n    >>> tconvert('now')\n    >>> tconvert('today')\n    >>> tconvert('tomorrow')\n    >>> tconvert('yesterday')"
  },
  {
    "code": "def netloc(self):\n        url = self._tuple\n        if url.username and url.password:\n            netloc = '%s:%s@%s' % (url.username, url.password, url.host)\n        elif url.username and not url.password:\n            netloc = '%s@%s' % (url.username, url.host)\n        else:\n            netloc = url.host\n        if url.port:\n            netloc = '%s:%s' % (netloc, url.port)\n        return netloc",
    "docstring": "Return the netloc"
  },
  {
    "code": "def redistribute(self, **kwargs):\n        source = kwargs.pop('source')\n        afi = kwargs.pop('afi', 'ipv4')\n        callback = kwargs.pop('callback', self._callback)\n        if afi not in ['ipv4', 'ipv6']:\n            raise AttributeError('Invalid AFI.')\n        args = dict(rbridge_id=kwargs.pop('rbridge_id', '1'),\n                    afi=afi, source=source)\n        redistribute = self._redistribute_builder(afi=afi, source=source)\n        config = redistribute(**args)\n        if kwargs.pop('get', False):\n            return callback(config, handler='get_config')\n        if kwargs.pop('delete', False):\n            tag = 'redistribute-%s' % source\n            config.find('.//*%s' % tag).set('operation', 'delete')\n        return callback(config)",
    "docstring": "Set BGP redistribute properties.\n\n        Args:\n            vrf (str): The VRF for this BGP process.\n            rbridge_id (str): The rbridge ID of the device on which BGP will be\n                configured in a VCS fabric.\n            source (str): Source for redistributing. (connected)\n            afi (str): Address family to configure. (ipv4, ipv6)\n            get (bool): Get config instead of editing config. (True, False)\n            callback (function): A function executed upon completion of the\n                method.  The only parameter passed to `callback` will be the\n                ``ElementTree`` `config`.\n\n        Returns:\n            Return value of `callback`.\n\n        Raises:\n            KeyError: if `source` is not specified.\n\n        Examples:\n            >>> import pynos.device\n            >>> conn = ('10.24.39.203', '22')\n            >>> auth = ('admin', 'password')\n            >>> with pynos.device.Device(conn=conn, auth=auth) as dev:\n            ...     output = dev.bgp.redistribute(source='connected',\n            ...     rbridge_id='225')\n            ...     output = dev.bgp.redistribute(source='connected',\n            ...     rbridge_id='225', get=True)\n            ...     output = dev.bgp.redistribute(source='connected',\n            ...     rbridge_id='225', delete=True)\n            ...     dev.bgp.redistribute() # doctest: +IGNORE_EXCEPTION_DETAIL\n            Traceback (most recent call last):\n            KeyError\n            ...     dev.bgp.redistribute(source='connected', rbridge_id='225',\n            ...     afi='hodor') # doctest: +IGNORE_EXCEPTION_DETAIL\n            Traceback (most recent call last):\n            AttributeError\n            ...     dev.bgp.redistribute(source='hodor', rbridge_id='225',\n            ...     afi='ipv4') # doctest: +IGNORE_EXCEPTION_DETAIL\n            Traceback (most recent call last):\n            AttributeError"
  },
  {
    "code": "def full_like(other, fill_value, dtype: Union[str, np.dtype, None] = None):\n    from .dataarray import DataArray\n    from .dataset import Dataset\n    from .variable import Variable\n    if isinstance(other, Dataset):\n        data_vars = OrderedDict(\n            (k, _full_like_variable(v, fill_value, dtype))\n            for k, v in other.data_vars.items())\n        return Dataset(data_vars, coords=other.coords, attrs=other.attrs)\n    elif isinstance(other, DataArray):\n        return DataArray(\n            _full_like_variable(other.variable, fill_value, dtype),\n            dims=other.dims, coords=other.coords, attrs=other.attrs,\n            name=other.name)\n    elif isinstance(other, Variable):\n        return _full_like_variable(other, fill_value, dtype)\n    else:\n        raise TypeError(\"Expected DataArray, Dataset, or Variable\")",
    "docstring": "Return a new object with the same shape and type as a given object.\n\n    Parameters\n    ----------\n    other : DataArray, Dataset, or Variable\n        The reference object in input\n    fill_value : scalar\n        Value to fill the new object with before returning it.\n    dtype : dtype, optional\n        dtype of the new array. If omitted, it defaults to other.dtype.\n\n    Returns\n    -------\n    out : same as object\n        New object with the same shape and type as other, with the data\n        filled with fill_value. Coords will be copied from other.\n        If other is based on dask, the new one will be as well, and will be\n        split in the same chunks."
  },
  {
    "code": "def retrieve(self, request, project, pk=None):\n        job_id, bug_id = map(int, pk.split(\"-\"))\n        job = Job.objects.get(repository__name=project, id=job_id)\n        try:\n            bug_job_map = BugJobMap.objects.get(job=job, bug_id=bug_id)\n            serializer = BugJobMapSerializer(bug_job_map)\n            return Response(serializer.data)\n        except BugJobMap.DoesNotExist:\n            return Response(\"Object not found\", status=HTTP_404_NOT_FOUND)",
    "docstring": "Retrieve a bug-job-map entry. pk is a composite key in the form\n        bug_id-job_id"
  },
  {
    "code": "def reload_exports():\n    ret = {}\n    command = 'exportfs -r'\n    output = __salt__['cmd.run_all'](command)\n    ret['stdout'] = output['stdout']\n    ret['stderr'] = output['stderr']\n    ret['result'] = output['stderr'] == ''\n    return ret",
    "docstring": "Trigger a reload of the exports file to apply changes\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' nfs3.reload_exports"
  },
  {
    "code": "def cmd_xor(k, i, o):\n    o.write(xor(i.read(), k.encode()))",
    "docstring": "XOR cipher.\n\n    Note: XOR is not a 'secure cipher'. If you need strong crypto you must use\n    algorithms like AES. You can use habu.fernet for that.\n\n    Example:\n\n    \\b\n    $ habu.xor -k mysecretkey -i /bin/ls > xored\n    $ habu.xor -k mysecretkey -i xored > uxored\n    $ sha1sum /bin/ls uxored\n    $ 6fcf930fcee1395a1c95f87dd38413e02deff4bb  /bin/ls\n    $ 6fcf930fcee1395a1c95f87dd38413e02deff4bb  uxored"
  },
  {
    "code": "def delete(name):\n    with Session() as session:\n        try:\n            session.VFolder(name).delete()\n            print_done('Deleted.')\n        except Exception as e:\n            print_error(e)\n            sys.exit(1)",
    "docstring": "Delete the given virtual folder. This operation is irreversible!\n\n    NAME: Name of a virtual folder."
  },
  {
    "code": "def catch_lane_change(self):\n        if self.current.lane_name:\n            if self.current.old_lane and self.current.lane_name != self.current.old_lane:\n                if (self.current.lane_id not in self.current.pool or\n                            self.current.pool[self.current.lane_id] != self.current.user_id):\n                    self.current.log.info(\"LANE CHANGE : %s >> %s\" % (self.current.old_lane,\n                                                                      self.current.lane_name))\n                    if self.current.lane_auto_sendoff:\n                        self.current.sendoff_current_user()\n                    self.current.flow_enabled = False\n                    if self.current.lane_auto_invite:\n                        self.current.invite_other_parties(self._get_possible_lane_owners())\n                    return True",
    "docstring": "trigger a lane_user_change signal if we switched to a new lane\n        and new lane's user is different from current one"
  },
  {
    "code": "def update_score(self):\n        if not self.subject_token:\n            return\n        vote_score = 0\n        replies_score = 0\n        for msg in self.message_set.all():\n            replies_score += self._get_score(300, msg.received_time)\n            for vote in msg.vote_set.all():\n                vote_score += self._get_score(100, vote.created)\n        page_view_score = self.hits * 10\n        self.score = (page_view_score + vote_score + replies_score) // 10\n        self.save()",
    "docstring": "Update the relevance score for this thread.\n\n        The score is calculated with the following variables:\n\n        * vote_weight: 100 - (minus) 1 for each 3 days since\n          voted with minimum of 5.\n        * replies_weight: 300 - (minus) 1 for each 3 days since\n          replied with minimum of 5.\n        * page_view_weight: 10.\n\n        * vote_score: sum(vote_weight)\n        * replies_score: sum(replies_weight)\n        * page_view_score: sum(page_view_weight)\n\n        * score = (vote_score + replies_score + page_view_score) // 10\n        with minimum of 0 and maximum of 5000"
  },
  {
    "code": "def get_changeform_initial_data(self, request):\n        initial = super(PageAdmin, self).get_changeform_initial_data(request)\n        if ('translation_of' in request.GET):\n            original = self.model._tree_manager.get(\n                pk=request.GET.get('translation_of'))\n            initial['layout'] = original.layout\n            initial['theme'] = original.theme\n            initial['color_scheme'] = original.color_scheme\n            old_lang = translation.get_language()\n            translation.activate(request.GET.get('language'))\n            title = _(original.title)\n            if title != original.title:\n                initial['title'] = title\n                initial['slug'] = slugify(title)\n            translation.activate(old_lang)\n        return initial",
    "docstring": "Copy initial data from parent"
  },
  {
    "code": "def _fromGUI(self, value):\n        if value == '':\n            if not self.IsNoneAllowed():\n                return 0\n            else:\n                return\n        else:\n            try:\n                return int(value)\n            except ValueError:\n                if self.IsLongAllowed():\n                    try:\n                        return long(value)\n                    except ValueError:\n                        wx.TextCtrl.SetValue(self, \"0\")\n                        return 0\n                else:\n                    raise",
    "docstring": "Conversion function used in getting the value of the control."
  },
  {
    "code": "def touch_model(self, model, **data):\n        instance, created = model.objects.get_or_create(**data)\n        if not created:\n            if instance.updated < self.import_start_datetime:\n                instance.save()\n        return (instance, created)",
    "docstring": "This method create or look up a model with the given data\n        it saves the given model if it exists, updating its\n        updated field"
  },
  {
    "code": "def quantile(self, q=0.5, axis=0, numeric_only=True,\n                 interpolation='linear'):\n        self._check_percentile(q)\n        data = self._get_numeric_data() if numeric_only else self\n        axis = self._get_axis_number(axis)\n        is_transposed = axis == 1\n        if is_transposed:\n            data = data.T\n        result = data._data.quantile(qs=q,\n                                     axis=1,\n                                     interpolation=interpolation,\n                                     transposed=is_transposed)\n        if result.ndim == 2:\n            result = self._constructor(result)\n        else:\n            result = self._constructor_sliced(result, name=q)\n        if is_transposed:\n            result = result.T\n        return result",
    "docstring": "Return values at the given quantile over requested axis.\n\n        Parameters\n        ----------\n        q : float or array-like, default 0.5 (50% quantile)\n            Value between 0 <= q <= 1, the quantile(s) to compute.\n        axis : {0, 1, 'index', 'columns'} (default 0)\n            Equals 0 or 'index' for row-wise, 1 or 'columns' for column-wise.\n        numeric_only : bool, default True\n            If False, the quantile of datetime and timedelta data will be\n            computed as well.\n        interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}\n            This optional parameter specifies the interpolation method to use,\n            when the desired quantile lies between two data points `i` and `j`:\n\n            * linear: `i + (j - i) * fraction`, where `fraction` is the\n              fractional part of the index surrounded by `i` and `j`.\n            * lower: `i`.\n            * higher: `j`.\n            * nearest: `i` or `j` whichever is nearest.\n            * midpoint: (`i` + `j`) / 2.\n\n            .. versionadded:: 0.18.0\n\n        Returns\n        -------\n        Series or DataFrame\n\n            If ``q`` is an array, a DataFrame will be returned where the\n              index is ``q``, the columns are the columns of self, and the\n              values are the quantiles.\n            If ``q`` is a float, a Series will be returned where the\n              index is the columns of self and the values are the quantiles.\n\n        See Also\n        --------\n        core.window.Rolling.quantile: Rolling quantile.\n        numpy.percentile: Numpy function to compute the percentile.\n\n        Examples\n        --------\n        >>> df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]),\n        ...                   columns=['a', 'b'])\n        >>> df.quantile(.1)\n        a    1.3\n        b    3.7\n        Name: 0.1, dtype: float64\n        >>> df.quantile([.1, .5])\n               a     b\n        0.1  1.3   3.7\n        0.5  2.5  55.0\n\n        Specifying `numeric_only=False` will also compute the quantile of\n        datetime and timedelta data.\n\n        >>> df = pd.DataFrame({'A': [1, 2],\n        ...                    'B': [pd.Timestamp('2010'),\n        ...                          pd.Timestamp('2011')],\n        ...                    'C': [pd.Timedelta('1 days'),\n        ...                          pd.Timedelta('2 days')]})\n        >>> df.quantile(0.5, numeric_only=False)\n        A                    1.5\n        B    2010-07-02 12:00:00\n        C        1 days 12:00:00\n        Name: 0.5, dtype: object"
  },
  {
    "code": "def get_first_molecule(self):\n        title, coordinates = self._first\n        molecule = Molecule(self.numbers, coordinates, title, symbols=self.symbols)\n        return molecule",
    "docstring": "Get the first molecule from the trajectory\n\n           This can be useful to configure your program before handeling the\n           actual trajectory."
  },
  {
    "code": "def _new_point(self, loglstar, logvol):\n        ncall, nupdate = 0, 0\n        while True:\n            u, v, logl, nc, blob = self._get_point_value(loglstar)\n            ncall += nc\n            ucheck = ncall >= self.update_interval * (1 + nupdate)\n            bcheck = self._beyond_unit_bound(loglstar)\n            if blob is not None and self.nqueue <= 0 and bcheck:\n                self.update_proposal(blob)\n            if logl >= loglstar:\n                break\n            if ucheck and bcheck:\n                pointvol = math.exp(logvol) / self.nlive\n                bound = self.update(pointvol)\n                if self.save_bounds:\n                    self.bound.append(bound)\n                self.nbound += 1\n                nupdate += 1\n                self.since_update = -ncall\n        return u, v, logl, ncall",
    "docstring": "Propose points until a new point that satisfies the log-likelihood\n        constraint `loglstar` is found."
  },
  {
    "code": "def get(self, key, **kwargs):\n        return self._get('/'.join([self._endpoint, key]), payload=kwargs)",
    "docstring": "Fetch value at the given key\n        kwargs can hold `recurse`, `wait` and `index` params"
  },
  {
    "code": "def get_regex(regex):\n    if isinstance(regex, basestring):\n        return re.compile(regex)\n    elif not isinstance(regex, re._pattern_type):\n        raise TypeError(\"Invalid regex type: %r\" % (regex,))\n    return regex",
    "docstring": "Ensure we have a compiled regular expression object.\n\n        >>> import re\n        >>> get_regex('string') # doctest: +ELLIPSIS\n        <_sre.SRE_Pattern object at 0x...>\n        >>> pattern = re.compile(r'string')\n        >>> get_regex(pattern) is pattern\n        True\n        >>> get_regex(3) # doctest: +ELLIPSIS\n        Traceback (most recent call last):\n        ...\n        TypeError: Invalid regex type: 3"
  },
  {
    "code": "def copy_to_clipboard(self, url):\n        if url is None:\n            self.term.flash()\n            return\n        try:\n            clipboard_copy(url)\n        except (ProgramError, OSError) as e:\n            _logger.exception(e)\n            self.term.show_notification(\n                'Failed to copy url: {0}'.format(e))\n        else:\n            self.term.show_notification(\n                ['Copied to clipboard:', url], timeout=1)",
    "docstring": "Attempt to copy the selected URL to the user's clipboard"
  },
  {
    "code": "def get_joining_group_property(value, is_bytes=False):\n    obj = unidata.ascii_joining_group if is_bytes else unidata.unicode_joining_group\n    if value.startswith('^'):\n        negated = value[1:]\n        value = '^' + unidata.unicode_alias['joininggroup'].get(negated, negated)\n    else:\n        value = unidata.unicode_alias['joininggroup'].get(value, value)\n    return obj[value]",
    "docstring": "Get `JOINING GROUP` property."
  },
  {
    "code": "def _validate_iterable(iterable_type, value):\n    if isinstance(value, six.string_types):\n        msg = \"Invalid iterable of type(%s): %s\"\n        raise ValidationError(msg % (type(value), value))\n    try:\n        return iterable_type(value)\n    except TypeError:\n        raise ValidationError(\"Invalid iterable: %s\" % (value))",
    "docstring": "Convert the iterable to iterable_type, or raise a Configuration\n    exception."
  },
  {
    "code": "def _get_csv_from_section(sections, crumbs, csvs):\n    logger_csvs.info(\"enter get_csv_from_section: {}\".format(crumbs))\n    _idx = 0\n    try:\n        for _name, _section in sections.items():\n            if \"measurementTable\" in _section:\n                sections[_name][\"measurementTable\"], csvs = _get_csv_from_table(_section[\"measurementTable\"],\"{}{}{}\".format(crumbs, _idx, \"measurement\") , csvs)\n            if \"model\" in _section:\n                sections[_name][\"model\"], csvs = _get_csv_from_model(_section[\"model\"], \"{}{}{}\".format(crumbs, _idx, \"model\") , csvs)\n            _idx += 1\n    except Exception as e:\n        logger_csvs.error(\"get_csv_from_section: {}, {}\".format(crumbs, e))\n        print(\"Error: get_csv_from_section: {}, {}\".format(crumbs, e))\n    logger_csvs.info(\"exit get_csv_from_section: {}\".format(crumbs))\n    return sections, csvs",
    "docstring": "Get table name, variable name, and column values from paleo metadata\n\n    :param dict sections: Metadata\n    :param str crumbs: Crumbs\n    :param dict csvs: Csv\n    :return dict sections: Metadata\n    :return dict csvs: Csv"
  },
  {
    "code": "def get(self, key):\n        try:\n            data = self._data[key]\n        except KeyError:\n            raise StoreKeyNotFound(key)\n        return data",
    "docstring": "Get data for given store key. Raise hug.exceptions.StoreKeyNotFound if key does not exist."
  },
  {
    "code": "def temporary_tag(tag):\n    if tag:\n        CTX.repo.tag(tag)\n    try:\n        yield\n    finally:\n        if tag:\n            CTX.repo.remove_tag(tag)",
    "docstring": "Temporarily tags the repo"
  },
  {
    "code": "def update(self, section, val, data):\n        k = self.get(section, val)\n        if data is not None and k != data:\n            self.set(section, val, data)",
    "docstring": "Add a setting to the config, but if same as default or None then no action.\n        This saves the .save writing the defaults\n\n        `section` (mandatory) (string) the section name in the config E.g. `\"agent\"`\n\n        `val` (mandatory) (string) the section name in the config E.g. `\"host\"`\n\n        `data` (mandatory) (as appropriate) the new value for the `val`"
  },
  {
    "code": "def _address2long(address):\n    parsed = ipv4.ip2long(address)\n    if parsed is None:\n        parsed = ipv6.ip2long(address)\n    return parsed",
    "docstring": "Convert an address string to a long."
  },
  {
    "code": "def transFringe(beta=None, rho=None):\n    m = np.eye(6, 6, dtype=np.float64)\n    if None in (beta, rho):\n        print(\"warning: 'theta', 'rho' should be positive float numbers.\")\n        return m\n    else:\n        m[1, 0] = np.tan(beta) / rho\n        m[3, 2] = -np.tan(beta) / rho\n        return m",
    "docstring": "Transport matrix of fringe field\n\n    :param beta: angle of rotation of pole-face in [RAD]\n    :param rho: bending radius in [m]\n    :return: 6x6 numpy array"
  },
  {
    "code": "def common_options(*args, **kwargs):\n    def decorate(f, **kwargs):\n        f = version_option(f)\n        f = debug_option(f)\n        f = verbose_option(f)\n        f = click.help_option(\"-h\", \"--help\")(f)\n        if not kwargs.get(\"no_format_option\"):\n            f = format_option(f)\n        if not kwargs.get(\"no_map_http_status_option\"):\n            f = map_http_status_option(f)\n        return f\n    return detect_and_decorate(decorate, args, kwargs)",
    "docstring": "This is a multi-purpose decorator for applying a \"base\" set of options\n    shared by all commands.\n    It can be applied either directly, or given keyword arguments.\n\n    Usage:\n\n    >>> @common_options\n    >>> def mycommand(abc, xyz):\n    >>>     ...\n\n    or\n\n    >>> @common_options(no_format_option=True)\n    >>> def mycommand(abc, xyz):\n    >>>     ..."
  },
  {
    "code": "def _mix(color1, color2, weight=0.5, **kwargs):\n    weight = float(weight)\n    c1 = color1.value\n    c2 = color2.value\n    p = 0.0 if weight < 0 else 1.0 if weight > 1 else weight\n    w = p * 2 - 1\n    a = c1[3] - c2[3]\n    w1 = ((w if (w * a == -1) else (w + a) / (1 + w * a)) + 1) / 2.0\n    w2 = 1 - w1\n    q = [w1, w1, w1, p]\n    r = [w2, w2, w2, 1 - p]\n    return ColorValue([c1[i] * q[i] + c2[i] * r[i] for i in range(4)])",
    "docstring": "Mixes two colors together."
  },
  {
    "code": "def start(self, network_name, trunk_name, trunk_type):\n        if not isinstance(network_name, basestring):\n            raise TypeError(\"network_name can only be an instance of type basestring\")\n        if not isinstance(trunk_name, basestring):\n            raise TypeError(\"trunk_name can only be an instance of type basestring\")\n        if not isinstance(trunk_type, basestring):\n            raise TypeError(\"trunk_type can only be an instance of type basestring\")\n        self._call(\"start\",\n                     in_p=[network_name, trunk_name, trunk_type])",
    "docstring": "Starts DHCP server process.\n\n        in network_name of type str\n            Name of internal network DHCP server should attach to.\n\n        in trunk_name of type str\n            Name of internal network trunk.\n\n        in trunk_type of type str\n            Type of internal network trunk.\n\n        raises :class:`OleErrorFail`\n            Failed to start the process."
  },
  {
    "code": "def save_assessment(self, assessment_form, *args, **kwargs):\n        if assessment_form.is_for_update():\n            return self.update_assessment(assessment_form, *args, **kwargs)\n        else:\n            return self.create_assessment(assessment_form, *args, **kwargs)",
    "docstring": "Pass through to provider AssessmentAdminSession.update_assessment"
  },
  {
    "code": "def revision_list(\n    request, template_name='wakawaka/revision_list.html', extra_context=None\n):\n    revision_list = Revision.objects.all()\n    template_context = {'revision_list': revision_list}\n    template_context.update(extra_context or {})\n    return render(request, template_name, template_context)",
    "docstring": "Displays a list of all recent revisions."
  },
  {
    "code": "def has_name_in(cls, names):\r\n        return cls.sha512.in_({\r\n            cls.hash_name(name)\r\n            for name in names\r\n        })",
    "docstring": "Build a filter if the author has any of the given names."
  },
  {
    "code": "def remove_tweet(self, id):\n        try:\n            self._client.destroy_status(id=id)\n            return True\n        except TweepError as e:\n            if e.api_code in [TWITTER_PAGE_DOES_NOT_EXISTS_ERROR, TWITTER_DELETE_OTHER_USER_TWEET]:\n                return False\n            raise",
    "docstring": "Delete a tweet.\n\n        :param id: ID of the tweet in question\n        :return: True if success, False otherwise"
  },
  {
    "code": "def backup(id):\n    filename = dump_database(id)\n    key = \"{}.dump\".format(id)\n    bucket = user_s3_bucket()\n    bucket.upload_file(filename, key)\n    return _generate_s3_url(bucket, key)",
    "docstring": "Backup the database to S3."
  },
  {
    "code": "def get_connection(self, **kwargs):\n        if self.is_rtscts():\n            return RTSCTSConnection(self, **kwargs)\n        if self.is_dsrdtr():\n            return DSRDTRConnection(self, **kwargs)\n        else:\n            raise RuntimeError('Serial protocol \"%s\" is not available.' % (\n                    self.protocol))",
    "docstring": "Return a serial connection implementation suitable for the specified\n        protocol. Raises ``RuntimeError`` if there is no implementation for\n        the given protocol.\n\n        .. warn::\n\n            This may be a little bit confusing since there is no effective\n            connection but an implementation of a connection pattern."
  },
  {
    "code": "def comicPageLink(self, comic, url, prevUrl):\n        for handler in _handlers:\n            handler.comicPageLink(comic, url, prevUrl)",
    "docstring": "Emit an event to inform the handler about links between comic pages. Should be overridden in subclass."
  },
  {
    "code": "def header(cls, name, type_=Type.String, description=None, default=None, required=None, **options):\n        return cls(name, In.Header, type_, None, description,\n                   required=required, default=default,\n                   **options)",
    "docstring": "Define a header parameter."
  },
  {
    "code": "def _scipy_distribution_positional_args_from_dict(distribution, params):\n    params['loc'] = params.get('loc', 0)\n    if 'scale' not in params:\n        params['scale'] = 1\n    if distribution == 'norm':\n        return params['mean'], params['std_dev']\n    elif distribution == 'beta':\n        return params['alpha'], params['beta'], params['loc'], params['scale']\n    elif distribution == 'gamma':\n        return params['alpha'], params['loc'], params['scale']\n    elif distribution == 'uniform':\n        return params['min'], params['max']\n    elif distribution == 'chi2':\n        return params['df'], params['loc'], params['scale']\n    elif distribution == 'expon':\n        return params['loc'], params['scale']",
    "docstring": "Helper function that returns positional arguments for a scipy distribution using a dict of parameters.\n\n       See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\\\n       to see an example of scipy's positional arguments. This function returns the arguments specified by the \\\n       scipy.stat.distribution.cdf() for tha distribution.\n\n       Args:\n           distribution (string): \\\n               The scipy distribution name.\n           params (dict): \\\n               A dict of named parameters.\n\n       Raises:\n           AttributeError: \\\n               If an unsupported distribution is provided."
  },
  {
    "code": "def adversary(self, name, owner=None, **kwargs):\n        return Adversary(self.tcex, name, owner=owner, **kwargs)",
    "docstring": "Create the Adversary TI object.\n\n        Args:\n            owner:\n            name:\n            **kwargs:\n\n        Return:"
  },
  {
    "code": "def get_nts(self, fin_davidchart):\n        nts = []\n        with open(fin_davidchart) as ifstrm:\n            hdr_seen = False\n            for line in ifstrm:\n                line = line.rstrip()\n                flds = line.split('\\t')\n                if hdr_seen:\n                    ntd = self._init_nt(flds)\n                    nts.append(ntd)\n                else:\n                    if line[:8] == 'Category':\n                        assert len(flds) == 13, len(flds)\n                        hdr_seen = True\n            sys.stdout.write(\"  READ {N:5} GO IDs from DAVID Chart: {TSV}\\n\".format(\n                N=len(nts), TSV=fin_davidchart))\n        return nts",
    "docstring": "Read DAVID Chart file. Store each line in a namedtuple."
  },
  {
    "code": "def property_data_zpool():\n    property_data = _property_parse_cmd(_zpool_cmd(), {\n        'allocated': 'alloc',\n        'autoexpand': 'expand',\n        'autoreplace': 'replace',\n        'listsnapshots': 'listsnaps',\n        'fragmentation': 'frag',\n    })\n    zpool_size_extra = [\n        'capacity-alloc', 'capacity-free',\n        'operations-read', 'operations-write',\n        'bandwith-read', 'bandwith-write',\n        'read', 'write',\n    ]\n    zpool_numeric_extra = [\n        'cksum', 'cap',\n    ]\n    for prop in zpool_size_extra:\n        property_data[prop] = {\n            'edit': False,\n            'type': 'size',\n            'values': '<size>',\n        }\n    for prop in zpool_numeric_extra:\n        property_data[prop] = {\n            'edit': False,\n            'type': 'numeric',\n            'values': '<count>',\n        }\n    return property_data",
    "docstring": "Return a dict of zpool properties\n\n    .. note::\n\n        Each property will have an entry with the following info:\n            - edit : boolean - is this property editable after pool creation\n            - type : str - either bool, bool_alt, size, numeric, or string\n            - values : str - list of possible values\n\n    .. warning::\n\n        This data is probed from the output of 'zpool get' with some suplimental\n        data that is hardcoded. There is no better way to get this informatio aside\n        from reading the code."
  },
  {
    "code": "def q(cls, **kwargs):\n        redis = cls.get_redis()\n        return QuerySet(cls, redis.sscan_iter(cls.members_key()))",
    "docstring": "Creates an iterator over the members of this class that applies the\n        given filters and returns only the elements matching them"
  },
  {
    "code": "def floor(cls, x: 'TensorFluent') -> 'TensorFluent':\n        return cls._unary_op(x, tf.floor, tf.float32)",
    "docstring": "Returns a TensorFluent for the floor function.\n\n        Args:\n            x: The input fluent.\n\n        Returns:\n            A TensorFluent wrapping the floor function."
  },
  {
    "code": "def setup_logging(name, prefix=\"trademanager\", cfg=None):\n    logname = \"/var/log/%s/%s_tapp.log\" % (prefix, name)\n    logfile = cfg.get('log', 'LOGFILE') if cfg is not None and \\\n        cfg.get('log', 'LOGFILE') is not None and cfg.get('log', 'LOGFILE') != \"\" else logname\n    loglevel = cfg.get('log', 'LOGLEVEL') if cfg is not None and \\\n        cfg.get('log', 'LOGLEVEL') is not None else logging.INFO\n    logging.basicConfig(filename=logfile, level=loglevel)\n    return logging.getLogger(name)",
    "docstring": "Create a logger, based on the given configuration.\n    Accepts LOGFILE and LOGLEVEL settings.\n\n    :param name: the name of the tapp to log\n    :param cfg: The configuration object with logging info.\n    :return: The session and the engine as a list (in that order)"
  },
  {
    "code": "def getAllFtpConnections(self):\n        outputMsg = \"Current ftp connections:\\n\"\n        counter = 1\n        for k in self.ftpList:\n            outputMsg += str(counter) + \". \" + k + \" \"\n            outputMsg += str(self.ftpList[k]) + \"\\n\"\n            counter += 1\n        if self.printOutput:\n            logger.info(outputMsg)\n        return self.ftpList",
    "docstring": "Returns a dictionary containing active ftp connections."
  },
  {
    "code": "def make_remote_image_result(annotations=None, labels=None):\n        return BuildResult(image_id=BuildResult.REMOTE_IMAGE,\n                           annotations=annotations, labels=labels)",
    "docstring": "Instantiate BuildResult for image not built locally."
  },
  {
    "code": "def wait_callback(self, callback, msg_type=None, timeout=1.0):\n        event = threading.Event()\n        def cb(msg, **metadata):\n            callback(msg, **metadata)\n            event.set()\n        self.add_callback(cb, msg_type)\n        event.wait(timeout)\n        self.remove_callback(cb, msg_type)",
    "docstring": "Wait for a SBP message with a callback.\n\n        Parameters\n        ----------\n        callback : fn\n          Callback function\n        msg_type : int | iterable\n          Message type to register callback against. Default `None` means global callback.\n          Iterable type adds the callback to all the message types.\n        timeout : float\n          Waiting period"
  },
  {
    "code": "def serialize(self):\n        return json.dumps({\n            \"name\": self.name,\n            \"ip\": self.ip,\n            \"port\": self.port\n        }, sort_keys=True)",
    "docstring": "Serializes the Peer data as a simple JSON map string."
  },
  {
    "code": "def filter_table(table, *column_filters):\n    keep = numpy.ones(len(table), dtype=bool)\n    for name, op_func, operand in parse_column_filters(*column_filters):\n        col = table[name].view(numpy.ndarray)\n        keep &= op_func(col, operand)\n    return table[keep]",
    "docstring": "Apply one or more column slice filters to a `Table`\n\n    Multiple column filters can be given, and will be applied\n    concurrently\n\n    Parameters\n    ----------\n    table : `~astropy.table.Table`\n        the table to filter\n\n    column_filter : `str`, `tuple`\n        a column slice filter definition, in one of two formats:\n\n        - `str` - e.g. ``'snr > 10``\n        - `tuple` - ``(<column>, <operator>, <operand>)``, e.g.\n          ``('snr', operator.gt, 10)``\n\n        multiple filters can be given and will be applied in order\n\n    Returns\n    -------\n    table : `~astropy.table.Table`\n        a view of the input table with only those rows matching the filters\n\n    Examples\n    --------\n    >>> filter(my_table, 'snr>10', 'frequency<1000')\n\n    custom operations can be defined using filter tuple definitions:\n\n    >>> from gwpy.table.filters import in_segmentlist\n    >>> filter(my_table, ('time', in_segmentlist, segs))"
  },
  {
    "code": "def verify_challenge(uri):\n    while True:\n        try:\n            resp = urlopen(uri)\n            challenge_status = json.loads(resp.read().decode('utf8'))\n        except IOError as e:\n            raise ValueError(\"Error checking challenge: {0} {1}\".format(\n                e.code, json.loads(e.read().decode('utf8'))))\n        if challenge_status['status'] == \"pending\":\n            time.sleep(2)\n        elif challenge_status['status'] == \"valid\":\n            LOGGER.info(\"Domain verified!\")\n            break\n        else:\n            raise ValueError(\"Domain challenge did not pass: {0}\".format(\n                challenge_status))",
    "docstring": "Loop until our challenge is verified, else fail."
  },
  {
    "code": "def rpc_start( working_dir, port, subdomain_index=None, thread=True ):\n    rpc_srv = BlockstackdRPCServer( working_dir, port, subdomain_index=subdomain_index )\n    log.debug(\"Starting RPC on port {}\".format(port))\n    if thread:\n        rpc_srv.start()\n    return rpc_srv",
    "docstring": "Start the global RPC server thread\n    Returns the RPC server thread"
  },
  {
    "code": "def cont(self, event = None):\n        if event is None:\n            event = self.lastEvent\n        if not event:\n            return\n        dwProcessId      = event.get_pid()\n        dwThreadId       = event.get_tid()\n        dwContinueStatus = event.continueStatus\n        if self.is_debugee(dwProcessId):\n            try:\n                if self.system.has_process(dwProcessId):\n                    aProcess = self.system.get_process(dwProcessId)\n                else:\n                    aProcess = Process(dwProcessId)\n                aProcess.flush_instruction_cache()\n            except WindowsError:\n                pass\n            win32.ContinueDebugEvent(dwProcessId, dwThreadId, dwContinueStatus)\n        if event == self.lastEvent:\n            self.lastEvent = None",
    "docstring": "Resumes execution after processing a debug event.\n\n        @see: dispatch(), loop(), wait()\n\n        @type  event: L{Event}\n        @param event: (Optional) Event object returned by L{wait}.\n\n        @raise WindowsError: Raises an exception on error."
  },
  {
    "code": "def _parse_from_incar(filename, key):\n    dirname = os.path.dirname(filename)\n    for f in os.listdir(dirname):\n        if re.search(r\"INCAR\", f):\n            warnings.warn(\"INCAR found. Using \" + key + \" from INCAR.\")\n            incar = Incar.from_file(os.path.join(dirname, f))\n            if key in incar:\n                return incar[key]\n            else:\n                return None\n    return None",
    "docstring": "Helper function to parse a parameter from the INCAR."
  },
  {
    "code": "def _valid(m, comment=VALID_RESPONSE, out=None):\n    return _set_status(m, status=True, comment=comment, out=out)",
    "docstring": "Return valid status."
  },
  {
    "code": "def OnActivateCard(self, card):\n        SimpleSCardAppEventObserver.OnActivateCard(self, card)\n        self.feedbacktext.SetLabel('Activated card: ' + repr(card))\n        self.transmitbutton.Enable()",
    "docstring": "Called when a card is activated by double-clicking\n        on the card or reader tree control or toolbar.\n        In this sample, we just connect to the card on the first activation."
  },
  {
    "code": "def TimeFromTicks(ticks, tz=None):\n    dt = datetime.datetime.fromtimestamp(ticks, tz=tz)\n    return dt.timetz()",
    "docstring": "Construct a DB-API time value from the given ticks value.\n\n    :type ticks: float\n    :param ticks:\n        a number of seconds since the epoch; see the documentation of the\n        standard Python time module for details.\n\n    :type tz: :class:`datetime.tzinfo`\n    :param tz: (Optional) time zone to use for conversion\n\n    :rtype: :class:`datetime.time`\n    :returns: time represented by ticks."
  },
  {
    "code": "def directory(self, key):\n    if key.name != 'directory':\n      key = key.instance('directory')\n    return self.get(key) or []",
    "docstring": "Retrieves directory entries for given key."
  },
  {
    "code": "def identify(self, req, resp, resource, uri_kwargs):\n        header = req.get_header(\"Authorization\", False)\n        auth = header.split(\" \") if header else None\n        if auth is None or auth[0].lower() != 'basic':\n            return None\n        if len(auth) != 2:\n            raise HTTPBadRequest(\n                \"Invalid Authorization header\",\n                \"The Authorization header for Basic auth should be in form:\\n\"\n                \"Authorization: Basic <base64-user-pass>\"\n            )\n        user_pass = auth[1]\n        try:\n            decoded = base64.b64decode(user_pass).decode()\n        except (TypeError, UnicodeDecodeError, binascii.Error):\n            raise HTTPBadRequest(\n                \"Invalid Authorization header\",\n                \"Credentials for Basic auth not correctly base64 encoded.\"\n            )\n        username, _, password = decoded.partition(\":\")\n        return username, password",
    "docstring": "Identify user using Authenticate header with Basic auth."
  },
  {
    "code": "def count_signatures(self, conditions={}):\n        url = self.SIGNS_COUNT_URL + '?'\n        for key, value in conditions.items():\n            if key is 'ids':\n                value = \",\".join(value)\n            url += '&%s=%s' % (key, value)\n        connection = Connection(self.token)\n        connection.set_url(self.production, url)\n        return connection.get_request()",
    "docstring": "Count all signatures"
  },
  {
    "code": "def fix_command(known_args):\n    settings.init(known_args)\n    with logs.debug_time('Total'):\n        logs.debug(u'Run with settings: {}'.format(pformat(settings)))\n        raw_command = _get_raw_command(known_args)\n        try:\n            command = types.Command.from_raw_script(raw_command)\n        except EmptyCommand:\n            logs.debug('Empty command, nothing to do')\n            return\n        corrected_commands = get_corrected_commands(command)\n        selected_command = select_command(corrected_commands)\n        if selected_command:\n            selected_command.run(command)\n        else:\n            sys.exit(1)",
    "docstring": "Fixes previous command. Used when `thefuck` called without arguments."
  },
  {
    "code": "def applyTuple(self, tuple, right, env):\n    if len(right) != 1:\n      raise exceptions.EvaluationError('Tuple (%r) can only be applied to one argument, got %r' % (self.left, self.right))\n    right = right[0]\n    return tuple(right)",
    "docstring": "Apply a tuple to something else."
  },
  {
    "code": "def is_redundant_union_item(first, other):\n    if isinstance(first, ClassType) and isinstance(other, ClassType):\n        if first.name == 'str' and other.name == 'Text':\n            return True\n        elif first.name == 'bool' and other.name == 'int':\n            return True\n        elif first.name == 'int' and other.name == 'float':\n            return True\n        elif (first.name in ('List', 'Dict', 'Set') and\n                  other.name == first.name):\n            if not first.args and other.args:\n                return True\n            elif len(first.args) == len(other.args) and first.args:\n                result = all(first_arg == other_arg or other_arg == AnyType()\n                             for first_arg, other_arg\n                             in zip(first.args, other.args))\n                return result\n    return False",
    "docstring": "If union has both items, is the first one redundant?\n\n    For example, if first is 'str' and the other is 'Text', return True.\n\n    If items are equal, return False."
  },
  {
    "code": "def radius(d, offsets, motor_ofs):\n    (mag, motor) = d\n    return (mag + offsets + motor*motor_ofs).length()",
    "docstring": "return radius give data point and offsets"
  },
  {
    "code": "def bearing(self, format='numeric'):\n        bearings = []\n        for segment in self:\n            if len(segment) < 2:\n                bearings.append([])\n            else:\n                bearings.append(segment.bearing(format))\n        return bearings",
    "docstring": "Calculate bearing between locations in segments.\n\n        Args:\n            format (str): Format of the bearing string to return\n\n        Returns:\n            list of list of float: Groups of bearings between points in\n                segments"
  },
  {
    "code": "def transaction_effects(self, tx_hash, cursor=None, order='asc', limit=10):\n        endpoint = '/transactions/{tx_hash}/effects'.format(tx_hash=tx_hash)\n        params = self.__query_params(cursor=cursor, order=order, limit=limit)\n        return self.query(endpoint, params)",
    "docstring": "This endpoint represents all effects that occurred as a result of a\n        given transaction.\n\n        `GET /transactions/{hash}/effects{?cursor,limit,order}\n        <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-transaction.html>`_\n\n        :param str tx_hash: The hex-encoded transaction hash.\n        :param int cursor: A paging token, specifying where to start returning records from.\n        :param str order: The order in which to return rows, \"asc\" or \"desc\".\n        :param int limit: Maximum number of records to return.\n        :return: A single transaction's effects.\n        :rtype: dict"
  },
  {
    "code": "def _unhash(hashed, alphabet):\n    number = 0\n    len_alphabet = len(alphabet)\n    for character in hashed:\n        position = alphabet.index(character)\n        number *= len_alphabet\n        number += position\n    return number",
    "docstring": "Restores a number tuple from hashed using the given `alphabet` index."
  },
  {
    "code": "def _InstallInstallers(self):\n    installer_amd64 = glob.glob(\n        os.path.join(args.output_dir, \"dbg_*_amd64.exe\")).pop()\n    self._CleanupInstall()\n    subprocess.check_call([installer_amd64])\n    self._CheckInstallSuccess()",
    "docstring": "Install the installer built by RepackTemplates."
  },
  {
    "code": "def load(self):\n        self._validate()\n        formatter = SqliteTableFormatter(self.source)\n        formatter.accept(self)\n        return formatter.to_table_data()",
    "docstring": "Extract tabular data as |TableData| instances from a SQLite database\n        file. |load_source_desc_file|\n\n        :return:\n            Loaded table data iterator.\n            |load_table_name_desc|\n\n            ===================  ==============================================\n            Format specifier     Value after the replacement\n            ===================  ==============================================\n            ``%(filename)s``     |filename_desc|\n            ``%(key)s``          ``%(format_name)s%(format_id)s``\n            ``%(format_name)s``  ``\"sqlite\"``\n            ``%(format_id)s``    |format_id_desc|\n            ``%(global_id)s``    |global_id|\n            ===================  ==============================================\n        :rtype: |TableData| iterator\n        :raises pytablereader.DataError:\n            If the SQLite database file data is invalid or empty."
  },
  {
    "code": "def pass_outflow_v1(self):\n    flu = self.sequences.fluxes.fastaccess\n    out = self.sequences.outlets.fastaccess\n    out.q[0] += flu.outflow",
    "docstring": "Update the outlet link sequence |dam_outlets.Q|."
  },
  {
    "code": "def reply(self, message, text, opts=None):\n        metadata = Metadata(source=self.actor_urn,\n                            dest=message['metadata']['source']).__dict__\n        metadata['opts'] = opts\n        message = Message(text=text, metadata=metadata,\n                          should_log=message['should_log']).__dict__\n        dest_actor = ActorRegistry.get_by_urn(message['metadata']['dest'])\n        if dest_actor is not None:\n            dest_actor.tell(message)\n        else:\n            raise(\"Tried to send message to nonexistent actor\")",
    "docstring": "Reply to the sender of the provided message with a message \\\n        containing the provided text.\n\n        :param message: the message to reply to\n        :param text: the text to reply with\n        :param opts: A dictionary of additional values to add to metadata\n        :return: None"
  },
  {
    "code": "def head(self, *args, **kwargs):\n        return self.session.head(*args, **self.get_kwargs(**kwargs))",
    "docstring": "Executes an HTTP HEAD.\n\n        :Parameters:\n           - `args`: Non-keyword arguments\n           - `kwargs`: Keyword arguments"
  },
  {
    "code": "def main():\n    arg_parser = ArgumentParser(\n        description=\"Opentrons robot software\",\n        parents=[build_arg_parser()])\n    args = arg_parser.parse_args()\n    run(**vars(args))\n    arg_parser.exit(message=\"Stopped\\n\")",
    "docstring": "The main entrypoint for the Opentrons robot API server stack.\n\n    This function\n    - creates and starts the server for both the RPC routes\n      handled by :py:mod:`opentrons.server.rpc` and the HTTP routes handled\n      by :py:mod:`opentrons.server.http`\n    - initializes the hardware interaction handled by either\n      :py:mod:`opentrons.legacy_api` or :py:mod:`opentrons.hardware_control`\n\n    This function does not return until the server is brought down."
  },
  {
    "code": "def get_date_range_this_year(now=None):\n    if now is None:\n        now = datetime.datetime.now().date()\n    if now.month <= settings.YEAR_TURNOVER_MONTH:\n        date_start = datetime.datetime(now.year - 1, 8, 1)\n        date_end = datetime.datetime(now.year, 7, 1)\n    else:\n        date_start = datetime.datetime(now.year, 8, 1)\n        date_end = datetime.datetime(now.year + 1, 7, 1)\n    return timezone.make_aware(date_start), timezone.make_aware(date_end)",
    "docstring": "Return the starting and ending date of the current school year."
  },
  {
    "code": "def _check_1st_line(line, **kwargs):\n    components = kwargs.get(\"components\", ())\n    max_first_line = kwargs.get(\"max_first_line\", 50)\n    errors = []\n    lineno = 1\n    if len(line) > max_first_line:\n        errors.append((\"M190\", lineno, max_first_line, len(line)))\n    if line.endswith(\".\"):\n        errors.append((\"M191\", lineno))\n    if ':' not in line:\n        errors.append((\"M110\", lineno))\n    else:\n        component, msg = line.split(':', 1)\n        if component not in components:\n            errors.append((\"M111\", lineno, component))\n    return errors",
    "docstring": "First line check.\n\n    Check that the first line has a known component name followed by a colon\n    and then a short description of the commit.\n\n    :param line: first line\n    :type line: str\n    :param components: list of known component names\n    :type line: list\n    :param max_first_line: maximum length of the first line\n    :type max_first_line: int\n    :return: errors as in (code, line number, *args)\n    :rtype: list"
  },
  {
    "code": "def check_shapes(self):\n        assert self.covX.shape == (self.dx, self.dx), error_msg\n        assert self.covY.shape == (self.dy, self.dy), error_msg\n        assert self.F.shape == (self.dx, self.dx), error_msg\n        assert self.G.shape == (self.dy, self.dx), error_msg\n        assert self.mu0.shape == (self.dx,), error_msg\n        assert self.cov0.shape == (self.dx, self.dx), error_msg",
    "docstring": "Check all dimensions are correct."
  },
  {
    "code": "def _link_vertex_and_edge_types(self):\n        for edge_class_name in self._edge_class_names:\n            edge_element = self._elements[edge_class_name]\n            if (EDGE_SOURCE_PROPERTY_NAME not in edge_element.properties or\n                    EDGE_DESTINATION_PROPERTY_NAME not in edge_element.properties):\n                if edge_element.abstract:\n                    continue\n                else:\n                    raise AssertionError(u'Found a non-abstract edge class with undefined '\n                                         u'endpoint types: {}'.format(edge_element))\n            from_class_name = edge_element.properties[EDGE_SOURCE_PROPERTY_NAME].qualifier\n            to_class_name = edge_element.properties[EDGE_DESTINATION_PROPERTY_NAME].qualifier\n            edge_schema_element = self._elements[edge_class_name]\n            for from_class in self._subclass_sets[from_class_name]:\n                from_schema_element = self._elements[from_class]\n                from_schema_element.out_connections.add(edge_class_name)\n                edge_schema_element.in_connections.add(from_class)\n            for to_class in self._subclass_sets[to_class_name]:\n                to_schema_element = self._elements[to_class]\n                edge_schema_element.out_connections.add(to_class)\n                to_schema_element.in_connections.add(edge_class_name)",
    "docstring": "For each edge, link it to the vertex types it connects to each other."
  },
  {
    "code": "def check_duplicate_axis(self, ds):\n        ret_val = []\n        geophysical_variables = self._find_geophysical_vars(ds)\n        for name in geophysical_variables:\n            no_duplicates = TestCtx(BaseCheck.HIGH, self.section_titles['5'])\n            axis_map = cfutil.get_axis_map(ds, name)\n            axes = []\n            for axis, coordinates in axis_map.items():\n                for coordinate in coordinates:\n                    axis_attr = getattr(ds.variables[coordinate], 'axis', None)\n                    no_duplicates.assert_true(axis_attr is None or axis_attr not in axes,\n                                              \"'{}' has duplicate axis {} defined by {}\".format(name, axis_attr, coordinate))\n                    if axis_attr and axis_attr not in axes:\n                        axes.append(axis_attr)\n            ret_val.append(no_duplicates.to_result())\n        return ret_val",
    "docstring": "Checks that no variable contains two coordinates defining the same\n        axis.\n\n        Chapter 5 paragraph 6\n\n        If an axis attribute is attached to an auxiliary coordinate variable,\n        it can be used by applications in the same way the `axis` attribute\n        attached to a coordinate variable is used. However, it is not\n        permissible for a [geophysical variable] to have both a coordinate\n        variable and an auxiliary coordinate variable, or more than one of\n        either type of variable, having an `axis` attribute with any given\n        value e.g. there must be no more than one axis attribute for X for any\n        [geophysical variable].\n\n        :param netCDF4.Dataset ds: An open netCDF dataset\n        :rtype: compliance_checker.base.Result\n        :return: List of results"
  },
  {
    "code": "def _combine_season_stats(self, table_rows, career_stats, all_stats_dict):\n        most_recent_season = self._most_recent_season\n        if not table_rows:\n            table_rows = []\n        for row in table_rows:\n            season = self._parse_season(row)\n            try:\n                all_stats_dict[season]['data'] += str(row)\n            except KeyError:\n                all_stats_dict[season] = {'data': str(row)}\n            most_recent_season = season\n        self._most_recent_season = most_recent_season\n        if not career_stats:\n            return all_stats_dict\n        try:\n            all_stats_dict['Career']['data'] += str(next(career_stats))\n        except KeyError:\n            try:\n                all_stats_dict['Career'] = {'data': str(next(career_stats))}\n            except StopIteration:\n                return all_stats_dict\n        return all_stats_dict",
    "docstring": "Combine all stats for each season.\n\n        Since all of the stats are spread across multiple tables, they should\n        be combined into a single field which can be used to easily query stats\n        at once.\n\n        Parameters\n        ----------\n        table_rows : generator\n            A generator where each element is a row in a stats table.\n        career_stats : generator\n            A generator where each element is a row in the footer of a stats\n            table. Career stats are kept in the footer, hence the usage.\n        all_stats_dict : dictionary\n            A dictionary of all stats separated by season where each key is the\n            season ``string``, such as '2017', and the value is a\n            ``dictionary`` with a ``string`` of 'data' and ``string``\n            containing all of the data.\n\n        Returns\n        -------\n        dictionary\n            Returns an updated version of the passed all_stats_dict which\n            includes more metrics from the provided table."
  },
  {
    "code": "def reward_bonus(self, assignment_id, amount, reason):\n        logger.info(\n            'Award ${} for assignment {}, with reason \"{}\"'.format(\n                amount, assignment_id, reason\n            )\n        )",
    "docstring": "Print out bonus info for the assignment"
  },
  {
    "code": "def _get_belief_package(stmt):\n    belief_packages = []\n    for st in stmt.supports:\n        parent_packages = _get_belief_package(st)\n        package_stmt_keys = [pkg.statement_key for pkg in belief_packages]\n        for package in parent_packages:\n            if package.statement_key not in package_stmt_keys:\n                belief_packages.append(package)\n    belief_package = BeliefPackage(stmt.matches_key(), stmt.evidence)\n    belief_packages.append(belief_package)\n    return belief_packages",
    "docstring": "Return the belief packages of a given statement recursively."
  },
  {
    "code": "def _wrap_result(self, response):\n        if isinstance(response, int):\n            response = self._wrap_response(response)\n        return HandlerResult(\n            status=HandlerStatus.RETURN,\n            message_out=self._response_proto(**response),\n            message_type=self._response_type)",
    "docstring": "Wraps child's response in a HandlerResult to be sent back to client.\n\n        Args:\n            response (enum or dict): Either an integer status enum, or a dict\n                of attributes to be added to the protobuf response."
  },
  {
    "code": "def period(self, unit, size = 1):\n        assert unit in (DAY, MONTH, YEAR), 'Invalid unit: {} of type {}'.format(unit, type(unit))\n        assert isinstance(size, int) and size >= 1, 'Invalid size: {} of type {}'.format(size, type(size))\n        return Period((unit, self, size))",
    "docstring": "Create a new period starting at instant.\n\n        >>> instant(2014).period('month')\n        Period(('month', Instant((2014, 1, 1)), 1))\n        >>> instant('2014-2').period('year', 2)\n        Period(('year', Instant((2014, 2, 1)), 2))\n        >>> instant('2014-2-3').period('day', size = 2)\n        Period(('day', Instant((2014, 2, 3)), 2))"
  },
  {
    "code": "def isnumber(*args):\n    return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args))",
    "docstring": "Checks if value is an integer, long integer or float.\n\n    NOTE: Treats booleans as numbers, where True=1 and False=0."
  },
  {
    "code": "def rgb2gray(img):\n    T = np.linalg.inv(np.array([\n        [1.0,  0.956,  0.621],\n        [1.0, -0.272, -0.647],\n        [1.0, -1.106,  1.703],\n    ]))\n    r_c, g_c, b_c = T[0]\n    r, g, b = np.rollaxis(as_float_image(img), axis=-1)\n    return r_c * r + g_c * g + b_c * b",
    "docstring": "Converts an RGB image to grayscale using matlab's algorithm."
  },
  {
    "code": "def strip(self, inplace=False):\n        if not inplace:\n            t = self.copy()\n        else:\n            t = self\n        for e in t._tree.preorder_edge_iter():\n            e.length = None\n        t._dirty = True\n        return t",
    "docstring": "Sets all edge lengths to None"
  },
  {
    "code": "def persistent_id(self, obj):\n        if isinstance(obj, Element):\n            return obj.__class__.__name__, obj.symbol\n        else:\n            return None",
    "docstring": "Instead of pickling as a regular class instance, we emit a\n        persistent ID."
  },
  {
    "code": "def startup(self):\n        self.runner.info_log(\"Startup\")\n        if self.browser_config.config.get('enable_proxy'):\n            self.start_proxy()",
    "docstring": "Start the instance\n\n        This is mainly use to start the proxy"
  },
  {
    "code": "def get_mailbox(self, email=None, email_hash=None):\n        if email is None:\n            email = self.get_email_address()\n        if email_hash is None:\n            email_hash = self.get_hash(email)\n        url = 'http://{0}/request/mail/id/{1}/format/json/'.format(\n            self.api_domain, email_hash)\n        req = requests.get(url)\n        return req.json()",
    "docstring": "Return list of emails in given email address\n        or dict with `error` key if mail box is empty.\n\n        :param email: (optional) email address.\n        :param email_hash: (optional) md5 hash from email address."
  },
  {
    "code": "def retrieve(self, block_height, headers=None):\n        path = self.path + block_height\n        return self.transport.forward_request(\n            method='GET', path=path, headers=None)",
    "docstring": "Retrieves the block with the given ``block_height``.\n\n        Args:\n            block_height (str): height of the block to retrieve.\n            headers (dict): Optional headers to pass to the request.\n\n        Returns:\n            dict: The block with the given ``block_height``."
  },
  {
    "code": "def select(self, index=0):\n        if self._clustering:\n            raise exceptions.InvalidClusterCommand\n        future = self._execute(\n            [b'SELECT', ascii(index).encode('ascii')], b'OK')\n        def on_selected(f):\n            self._connection.database = index\n        self.io_loop.add_future(future, on_selected)\n        return future",
    "docstring": "Select the DB with having the specified zero-based numeric index.\n        New connections always use DB ``0``.\n\n        :param int index: The database to select\n        :rtype: bool\n        :raises: :exc:`~tredis.exceptions.RedisError`\n        :raises: :exc:`~tredis.exceptions.InvalidClusterCommand`"
  },
  {
    "code": "def tcp_accept(self):\n        self.conn, self.addr = self.tcp_socket.accept()\n        print(\"[MESSAGE] The connection is established at: \", self.addr)\n        self.tcp_send(\"> \")",
    "docstring": "Waiting for a TCP connection."
  },
  {
    "code": "def extend_memory(self, start_position: int, size: int) -> None:\n        validate_uint256(start_position, title=\"Memory start position\")\n        validate_uint256(size, title=\"Memory size\")\n        before_size = ceil32(len(self._memory))\n        after_size = ceil32(start_position + size)\n        before_cost = memory_gas_cost(before_size)\n        after_cost = memory_gas_cost(after_size)\n        if self.logger.show_debug2:\n            self.logger.debug2(\n                \"MEMORY: size (%s -> %s) | cost (%s -> %s)\",\n                before_size,\n                after_size,\n                before_cost,\n                after_cost,\n            )\n        if size:\n            if before_cost < after_cost:\n                gas_fee = after_cost - before_cost\n                self._gas_meter.consume_gas(\n                    gas_fee,\n                    reason=\" \".join((\n                        \"Expanding memory\",\n                        str(before_size),\n                        \"->\",\n                        str(after_size),\n                    ))\n                )\n            self._memory.extend(start_position, size)",
    "docstring": "Extend the size of the memory to be at minimum ``start_position + size``\n        bytes in length.  Raise `eth.exceptions.OutOfGas` if there is not enough\n        gas to pay for extending the memory."
  },
  {
    "code": "def _store_in_native_memory(self, data, data_type, addr=None):\n        if addr is not None and self.state.solver.symbolic(addr):\n            raise NotImplementedError('Symbolic addresses are not supported.')\n        type_size = ArchSoot.sizeof[data_type]\n        native_memory_endness = self.state.arch.memory_endness\n        if isinstance(data, int):\n            if addr is None:\n                addr = self._allocate_native_memory(size=type_size//8)\n            value = self.state.solver.BVV(data, type_size)\n            self.state.memory.store(addr, value, endness=native_memory_endness)\n        elif isinstance(data, list):\n            if addr is None:\n                addr = self._allocate_native_memory(size=type_size*len(data)//8)\n            for idx, value in enumerate(data):\n                memory_addr = addr+idx*type_size//8\n                self.state.memory.store(memory_addr, value, endness=native_memory_endness)\n        return addr",
    "docstring": "Store in native memory.\n\n        :param data:      Either a single value or a list.\n                          Lists get interpreted as an array.\n        :param data_type: Java type of the element(s).\n        :param addr:      Native store address.\n                          If not set, native memory is allocated.\n        :return:          Native addr of the stored data."
  },
  {
    "code": "def _currentLineExtraSelections(self):\n        if self._currentLineColor is None:\n            return []\n        def makeSelection(cursor):\n            selection = QTextEdit.ExtraSelection()\n            selection.format.setBackground(self._currentLineColor)\n            selection.format.setProperty(QTextFormat.FullWidthSelection, True)\n            cursor.clearSelection()\n            selection.cursor = cursor\n            return selection\n        rectangularSelectionCursors = self._rectangularSelection.cursors()\n        if rectangularSelectionCursors:\n            return [makeSelection(cursor) \\\n                        for cursor in rectangularSelectionCursors]\n        else:\n            return [makeSelection(self.textCursor())]",
    "docstring": "QTextEdit.ExtraSelection, which highlightes current line"
  },
  {
    "code": "def to_json(self, filename=None,\n                encoding=\"utf-8\", errors=\"strict\",\n                multiline=False, **json_kwargs):\n        if filename and multiline:\n            lines = [_to_json(item, filename=False, encoding=encoding,\n                              errors=errors, **json_kwargs) for item in self]\n            with open(filename, 'w', encoding=encoding, errors=errors) as f:\n                f.write(\"\\n\".join(lines).decode('utf-8') if\n                        sys.version_info < (3, 0) else \"\\n\".join(lines))\n        else:\n            return _to_json(self.to_list(), filename=filename,\n                            encoding=encoding, errors=errors, **json_kwargs)",
    "docstring": "Transform the BoxList object into a JSON string.\n\n        :param filename: If provided will save to file\n        :param encoding: File encoding\n        :param errors: How to handle encoding errors\n        :param multiline: Put each item in list onto it's own line\n        :param json_kwargs: additional arguments to pass to json.dump(s)\n        :return: string of JSON or return of `json.dump`"
  },
  {
    "code": "def _generate_class_comment(self, data_type):\n        if is_struct_type(data_type):\n            class_type = 'struct'\n        elif is_union_type(data_type):\n            class_type = 'union'\n        else:\n            raise TypeError('Can\\'t handle type %r' % type(data_type))\n        self.emit(comment_prefix)\n        self.emit_wrapped_text(\n            'The `{}` {}.'.format(fmt_class(data_type.name), class_type),\n            prefix=comment_prefix)\n        if data_type.doc:\n            self.emit(comment_prefix)\n            self.emit_wrapped_text(\n                self.process_doc(data_type.doc, self._docf),\n                prefix=comment_prefix)\n        self.emit(comment_prefix)\n        protocol_str = (\n            'This class implements the `DBSerializable` protocol '\n            '(serialize and deserialize instance methods), which is required '\n            'for all Obj-C SDK API route objects.')\n        self.emit_wrapped_text(\n            protocol_str.format(fmt_class_prefix(data_type), class_type),\n            prefix=comment_prefix)\n        self.emit(comment_prefix)",
    "docstring": "Emits a generic class comment for a union or struct."
  },
  {
    "code": "def pca_to_mapping(pca,**extra_props):\n    from .axes import sampling_axes\n    method = extra_props.pop('method',sampling_axes)\n    return dict(\n        axes=pca.axes.tolist(),\n        covariance=method(pca).tolist(),\n        **extra_props)",
    "docstring": "A helper to return a mapping of a PCA result set suitable for\n    reconstructing a planar error surface in other software packages\n\n    kwargs: method (defaults to sampling axes)"
  },
  {
    "code": "def load(self, filename, bs=512):\n        with open(filename, 'rb') as f:\n            f.seek(GPT_HEADER_OFFSET + 0x0C)\n            header_size = struct.unpack(\"<I\", f.read(4))[0]\n            f.seek(GPT_HEADER_OFFSET)\n            header_data = f.read(header_size)\n            self.header = GPT_HEADER(header_data)\n            if (self.header.signature != GPT_SIGNATURE):\n                raise Exception(\"Invalid GPT signature\")\n            self.__load_partition_entries(f, bs)",
    "docstring": "Loads GPT partition table.\n\n        Args:\n            filename (str): path to file or device to open for reading\n            bs (uint): Block size of the volume, default: 512\n\n        Raises:\n            IOError: If file does not exist or not readable"
  },
  {
    "code": "def single_traj_from_n_files(file_list, top):\n    traj = None\n    for ff in file_list:\n        if traj is None:\n            traj = md.load(ff, top=top)\n        else:\n            traj = traj.join(md.load(ff, top=top))\n    return traj",
    "docstring": "Creates a single trajectory object from a list of files"
  },
  {
    "code": "def make_agent_from_hparams(\n    agent_type, base_env, stacked_env, loop_hparams, policy_hparams,\n    planner_hparams, model_dir, policy_dir, sampling_temp, video_writers=()\n):\n  def sim_env_kwargs_fn():\n    return rl.make_simulated_env_kwargs(\n        base_env, loop_hparams, batch_size=planner_hparams.batch_size,\n        model_dir=model_dir\n    )\n  planner_kwargs = planner_hparams.values()\n  planner_kwargs.pop(\"batch_size\")\n  planner_kwargs.pop(\"rollout_agent_type\")\n  planner_kwargs.pop(\"env_type\")\n  return make_agent(\n      agent_type, stacked_env, policy_hparams, policy_dir, sampling_temp,\n      sim_env_kwargs_fn, loop_hparams.frame_stack_size,\n      planner_hparams.rollout_agent_type,\n      inner_batch_size=planner_hparams.batch_size,\n      env_type=planner_hparams.env_type,\n      video_writers=video_writers, **planner_kwargs\n  )",
    "docstring": "Creates an Agent from hparams."
  },
  {
    "code": "def from_url(cls, url: URL,\n                 *, encoding: str='latin1') -> Optional['BasicAuth']:\n        if not isinstance(url, URL):\n            raise TypeError(\"url should be yarl.URL instance\")\n        if url.user is None:\n            return None\n        return cls(url.user, url.password or '', encoding=encoding)",
    "docstring": "Create BasicAuth from url."
  },
  {
    "code": "def fixpath(path):\n    return os.path.normpath(os.path.realpath(os.path.expanduser(path)))",
    "docstring": "Uniformly format a path."
  },
  {
    "code": "def all(self):\n        results = self.data[self.data_type]\n        while self.current < self.total:\n            self.fetch_next_page()\n            results.extend(self.data[self.data_type])\n        return results",
    "docstring": "Return all results as a list by automatically fetching all pages.\n\n        :return: All results.\n        :rtype: ``list``"
  },
  {
    "code": "def get_object(self, identifier, mask=None):\n        if mask is None:\n            mask = \"mask[instances[billingItem[item[keyName],category], guest], backendRouter[datacenter]]\"\n        result = self.client.call(self.rcg_service, 'getObject', id=identifier, mask=mask)\n        return result",
    "docstring": "Get a Reserved Capacity Group\n\n        :param int identifier: Id of the SoftLayer_Virtual_ReservedCapacityGroup\n        :param string mask: override default object Mask"
  },
  {
    "code": "def location(self):\n        location = Element.from_href(self.location_ref)\n        if location and location.name == 'Default':\n            return None\n        return location",
    "docstring": "The location for this engine. May be None if no specific\n        location has been assigned.\n\n        :param value: location to assign engine. Can be name, str href,\n            or Location element. If name, it will be automatically created\n            if a Location with the same name doesn't exist.\n        :raises UpdateElementFailed: failure to update element\n        :return: Location element or None"
  },
  {
    "code": "def list2dict(list_of_options):\n    d = {}\n    for key, value in list_of_options:\n        d[key] = value\n    return d",
    "docstring": "Transforms a list of 2 element tuples to a dictionary"
  },
  {
    "code": "def getAvailableClassesInPackage(package):\n    l = list(x[1] for x in inspect.getmembers(package, inspect.isclass))\n    modules = list(x[1] for x in inspect.getmembers(package, inspect.ismodule))\n    for m in modules:\n        l.extend(list(x[1] for x in inspect.getmembers(m, inspect.isclass)))\n    l = [x for x in l if x.__name__[0] != \"_\"]\n    n = 0\n    while n < len(l):\n        cls = l[n]\n        if not cls.__module__.startswith(package.__name__):\n            l.pop(n)\n            n -= 1\n        n += 1\n    return l",
    "docstring": "return a list of all classes in the given package\n    whose modules dont begin with '_'"
  },
  {
    "code": "def _call_pip(self, name=None, prefix=None, extra_args=None,\n                  callback=None):\n        cmd_list = self._pip_cmd(name=name, prefix=prefix)\n        cmd_list.extend(extra_args)\n        process_worker = ProcessWorker(cmd_list, pip=True, callback=callback)\n        process_worker.sig_finished.connect(self._start)\n        self._queue.append(process_worker)\n        self._start()\n        return process_worker",
    "docstring": "Call pip in QProcess worker."
  },
  {
    "code": "def find_in_bids(filename, pattern=None, generator=False, upwards=False,\n                 wildcard=True, **kwargs):\n    if upwards and generator:\n        raise ValueError('You cannot search upwards and have a generator')\n    if pattern is None:\n        pattern = _generate_pattern(wildcard, kwargs)\n    lg.debug(f'Searching {pattern} in {filename}')\n    if upwards and filename == find_root(filename):\n        raise FileNotFoundError(f'Could not find file matchting {pattern} in {filename}')\n    if generator:\n        return filename.rglob(pattern)\n    matches = list(filename.rglob(pattern))\n    if len(matches) == 1:\n        return matches[0]\n    elif len(matches) == 0:\n        if upwards:\n            return find_in_bids(filename.parent, pattern=pattern, upwards=upwards)\n        else:\n            raise FileNotFoundError(f'Could not find file matching {pattern} in {filename}')\n    else:\n        matches_str = '\"\\n\\t\"'.join(str(x) for x in matches)\n        raise FileNotFoundError(f'Multiple files matching \"{pattern}\":\\n\\t\"{matches_str}\"')",
    "docstring": "Find nearest file matching some criteria.\n\n    Parameters\n    ----------\n    filename : instance of Path\n        search the root for this file\n    pattern : str\n        glob string for search criteria of the filename of interest (remember\n        to include '*'). The pattern is passed directly to rglob.\n    wildcard : bool\n        use wildcards for unspecified fields or not (if True, add \"_*_\" between\n        fields)\n    upwards : bool\n        where to keep on searching upwards\n    kwargs : dict\n\n\n    Returns\n    -------\n    Path\n        filename matching the pattern"
  },
  {
    "code": "def get_lux_count(lux_byte):\r\n    LUX_VALID_MASK = 0b10000000\r\n    LUX_CHORD_MASK = 0b01110000\r\n    LUX_STEP_MASK = 0b00001111\r\n    valid = lux_byte & LUX_VALID_MASK\r\n    if valid != 0:\r\n        step_num = (lux_byte & LUX_STEP_MASK)\r\n        chord_num = (lux_byte & LUX_CHORD_MASK) >> 4\r\n        step_val = 2**chord_num\r\n        chord_val = int(16.5 * (step_val - 1))\r\n        count = chord_val + step_val * step_num\r\n        return count\r\n    else:\r\n        raise SensorError(\"Invalid lux sensor data.\")",
    "docstring": "Method to convert data from the TSL2550D lux sensor\r\n    into more easily usable ADC count values."
  },
  {
    "code": "def get_event_stream(self):\n        if self._event_stream is None:\n            self._event_stream = WVAEventStream(self._http_client)\n        return self._event_stream",
    "docstring": "Get the event stream associated with this WVA\n\n        Note that this event stream is shared across all users of this WVA device\n        as the WVA only supports a single event stream.\n\n        :return: a new :class:`WVAEventStream` instance"
  },
  {
    "code": "def normalize_rust_function(self, function, line):\n        function = drop_prefix_and_return_type(function)\n        function = collapse(\n            function,\n            open_string='<',\n            close_string='>',\n            replacement='<T>',\n            exceptions=(' as ',)\n        )\n        if self.collapse_arguments:\n            function = collapse(\n                function,\n                open_string='(',\n                close_string=')',\n                replacement=''\n            )\n        if self.signatures_with_line_numbers_re.match(function):\n            function = '{}:{}'.format(function, line)\n        function = self.fixup_space.sub('', function)\n        function = self.fixup_comma.sub(', ', function)\n        function = self.fixup_hash.sub('', function)\n        return function",
    "docstring": "Normalizes a single rust frame with a function"
  },
  {
    "code": "def _domain_event_pmwakeup_cb(conn, domain, reason, opaque):\n    _salt_send_domain_event(opaque, conn, domain, opaque['event'], {\n        'reason': 'unknown'\n    })",
    "docstring": "Domain wakeup events handler"
  },
  {
    "code": "def to_bytes_safe(text, encoding=\"utf-8\"):\n    if not isinstance(text, (bytes, text_type)):\n        raise TypeError(\"must be string type\")\n    if isinstance(text, text_type):\n        return text.encode(encoding)\n    return text",
    "docstring": "Convert the input value into bytes type.\n\n    If the input value is string type and could be encode as UTF-8 bytes, the\n    encoded value will be returned. Otherwise, the encoding has failed, the\n    origin value will be returned as well.\n\n    :param text: the input value which could be string or bytes.\n    :param encoding: the expected encoding be used while converting the string\n                     input into bytes.\n    :rtype: :class:`~__builtin__.bytes`"
  },
  {
    "code": "def find_products(self, product_type):\n        if self.filter_prods and product_type in self.LIST_PRODUCTS and product_type not in self.desired_prods:\n            return []\n        if product_type in self.LIST_PRODUCTS:\n            found_products = self.products.get(product_type, [])\n        else:\n            found_products = [x[0] for x in self.products.items()\n                              if x[1] == product_type and (not self.filter_prods or x[0] in self.desired_prods)]\n        found_products = [self._ensure_product_string(x) for x in found_products]\n        declaration = self.PATH_PRODUCTS.get(product_type)\n        if declaration is not None:\n            found_products = [self._process_product_path(x, declaration) for x in found_products]\n        return found_products",
    "docstring": "Search for products of a given type.\n\n        Search through the products declared by this IOTile component and\n        return only those matching the given type.  If the product is described\n        by the path to a file, a complete normalized path will be returned.\n        The path could be different depending on whether this IOTile component\n        is in development or release mode.\n\n        The behavior of this function when filter_products has been called is\n        slightly different based on whether product_type is in LIST_PRODUCTS\n        or not.  If product type is in LIST_PRODUCTS, then all matching\n        products are returned if product_type itself was passed.  So to get\n        all tilebus_definitions you would call\n        ``filter_products('tilebus_definitions')``\n\n        By contrast, other products are filtered product-by-product.  So there\n        is no way to filter and get **all libraries**.  Instead you pass the\n        specific product names of the libraries that you want to\n        ``filter_products`` and those specific libraries are returned.\n        Passing the literal string ``library`` to ``filter_products`` will not\n        return only the libraries, it will return nothing since no library is\n        named ``library``.\n\n        Args:\n            product_type (str): The type of product that we wish to return.\n\n        Returns:\n            list of str: The list of all products of the given type.\n\n            If no such products are found, an empty list will be returned.\n            If filter_products() has been called and the filter does not include\n            this product type, an empty list will be returned."
  },
  {
    "code": "def read(self):\n        \"Read and interpret data from the daemon.\"\n        status = gpscommon.read(self)\n        if status <= 0:\n            return status\n        if self.response.startswith(\"{\") and self.response.endswith(\"}\\r\\n\"):\n            self.unpack(self.response)\n            self.__oldstyle_shim()\n            self.newstyle = True\n            self.valid |= PACKET_SET\n        elif self.response.startswith(\"GPSD\"):\n            self.__oldstyle_unpack(self.response)\n            self.valid |= PACKET_SET\n        return 0",
    "docstring": "Read and interpret data from the daemon."
  },
  {
    "code": "def initRnaQuantificationSet(self):\n        store = rnaseq2ga.RnaSqliteStore(self._args.filePath)\n        store.createTables()",
    "docstring": "Initialize an empty RNA quantification set"
  },
  {
    "code": "def back_off_until(self):\n        if self._back_off_until is None:\n            return None\n        with self._back_off_lock:\n            if self._back_off_until is None:\n                return None\n            if self._back_off_until < datetime.datetime.now():\n                self._back_off_until = None\n                return None\n            return self._back_off_until",
    "docstring": "Returns the back off value as a datetime. Resets the current back off value if it has expired."
  },
  {
    "code": "def create_attribute(self,column=None,listType=None,namespace=None, network=None, atype=None, verbose=False):\n        network=check_network(self,network,verbose=verbose)\n        PARAMS=set_param([\"column\",\"listType\",\"namespace\",\"network\",\"type\"],[column,listType,namespace,network,atype])\n        response=api(url=self.__url+\"/create attribute\", PARAMS=PARAMS, method=\"POST\", verbose=verbose)\n        return response",
    "docstring": "Creates a new edge column.\n\n        :param column (string, optional): Unique name of column\n        :param listType (string, optional): Can be one of integer, long, double,\n            or string.\n        :param namespace (string, optional): Node, Edge, and Network objects\n            support the default, local, and hidden namespaces. Root networks\n            also support the shared namespace. Custom namespaces may be specified\n            by Apps.\n        :param network (string, optional): Specifies a network by name, or by\n            SUID if the prefix SUID: is used. The keyword CURRENT, or a blank\n            value can also be used to specify the current network.\n        :param atype (string, optional): Can be one of integer, long, double,\n            string, or list.\n        :param verbose: print more"
  },
  {
    "code": "def open(filename, frame='unspecified'):\n        data = Image.load_data(filename)\n        return NormalCloudImage(data, frame)",
    "docstring": "Creates a NormalCloudImage from a file.\n\n        Parameters\n        ----------\n        filename : :obj:`str`\n            The file to load the data from. Must be one of .png, .jpg,\n            .npy, or .npz.\n\n        frame : :obj:`str`\n            A string representing the frame of reference in which the new image\n            lies.\n\n        Returns\n        -------\n        :obj:`NormalCloudImage`\n            The new NormalCloudImage."
  },
  {
    "code": "def sanitize(value):\n    if isinstance(value, basestring):\n        value = bleach.clean(value, tags=ALLOWED_TAGS,\n                             attributes=ALLOWED_ATTRIBUTES, \n                             styles=ALLOWED_STYLES, strip=False)\n    return value",
    "docstring": "Sanitizes strings according to SANITIZER_ALLOWED_TAGS,\n    SANITIZER_ALLOWED_ATTRIBUTES and SANITIZER_ALLOWED_STYLES variables in\n    settings.\n\n    Example usage:\n\n    {% load sanitizer %}\n    {{ post.content|escape_html }}"
  },
  {
    "code": "def processor_for(content_model_or_slug, exact_page=False):\n    content_model = None\n    slug = \"\"\n    if isinstance(content_model_or_slug, (str, _str)):\n        try:\n            parts = content_model_or_slug.split(\".\", 1)\n            content_model = apps.get_model(*parts)\n        except (TypeError, ValueError, LookupError):\n            slug = content_model_or_slug\n    elif issubclass(content_model_or_slug, Page):\n        content_model = content_model_or_slug\n    else:\n        raise TypeError(\"%s is not a valid argument for page_processor, \"\n                        \"which should be a model subclass of Page in class \"\n                        \"or string form (app.model), or a valid slug\" %\n                        content_model_or_slug)\n    def decorator(func):\n        parts = (func, exact_page)\n        if content_model:\n            model_name = content_model._meta.object_name.lower()\n            processors[model_name].insert(0, parts)\n        else:\n            processors[\"slug:%s\" % slug].insert(0, parts)\n        return func\n    return decorator",
    "docstring": "Decorator that registers the decorated function as a page\n    processor for the given content model or slug.\n\n    When a page exists that forms the prefix of custom urlpatterns\n    in a project (eg: the blog page and app), the page will be\n    added to the template context. Passing in ``True`` for the\n    ``exact_page`` arg, will ensure that the page processor is not\n    run in this situation, requiring that the loaded page object\n    is for the exact URL currently being viewed."
  },
  {
    "code": "def get_repository_notification_session(self, repository_receiver, proxy):\n        if repository_receiver is None:\n            raise NullArgument()\n        if not self.supports_repository_notification():\n            raise Unimplemented()\n        try:\n            from . import sessions\n        except ImportError:\n            raise\n        proxy = self._convert_proxy(proxy)\n        try:\n            session = sessions.RepositoryNotificationSession(repository_receiver, proxy, runtime=self._runtime)\n        except AttributeError:\n            raise\n        return session",
    "docstring": "Gets the notification session for subscribing to changes to a\n        repository.\n\n        arg:    repository_receiver\n                (osid.repository.RepositoryReceiver): the notification\n                callback\n        arg     proxy (osid.proxy.Proxy): a proxy\n        return: (osid.repository.RepositoryNotificationSession) - a\n                RepositoryNotificationSession\n        raise:  NullArgument - repository_receiver is null\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - supports_repository_notification() is\n                false\n        compliance: optional - This method must be implemented if\n                    supports_repository_notification() is true."
  },
  {
    "code": "def avl_split_first(root):\n    if root is None:\n        raise IndexError('Empty tree has no maximum element')\n    root, left, right = avl_release_kids(root)\n    if left is None:\n        new_root, first_node = right, root\n    else:\n        new_left, first_node = avl_split_first(left)\n        new_root = avl_join(new_left, right, root)\n    return (new_root, first_node)",
    "docstring": "Removes the minimum element from the tree\n\n    Returns:\n        tuple: new_root, first_node\n\n    O(log(n)) = O(height(root))"
  },
  {
    "code": "def _next_ontology(self):\n        currentfile = self.current['file']\n        try:\n            idx = self.all_ontologies.index(currentfile)\n            return self.all_ontologies[idx+1]\n        except:\n            return self.all_ontologies[0]",
    "docstring": "Dynamically retrieves the next ontology in the list"
  },
  {
    "code": "def set_reload_on_exception_params(self, do_reload=None, etype=None, evalue=None, erepr=None):\n        self._set('reload-on-exception', do_reload, cast=bool)\n        self._set('reload-on-exception-type', etype)\n        self._set('reload-on-exception-value', evalue)\n        self._set('reload-on-exception-repr', erepr)\n        return self._section",
    "docstring": "Sets workers reload on exceptions parameters.\n\n        :param bool do_reload: Reload a worker when an exception is raised.\n\n        :param str etype: Reload a worker when a specific exception type is raised.\n\n        :param str evalue: Reload a worker when a specific exception value is raised.\n\n        :param str erepr: Reload a worker when a specific exception type+value (language-specific) is raised."
  },
  {
    "code": "def cause_effect_info(self, mechanism, purview):\n        return min(self.cause_info(mechanism, purview),\n                   self.effect_info(mechanism, purview))",
    "docstring": "Return the cause-effect information for a mechanism over a purview.\n\n        This is the minimum of the cause and effect information."
  },
  {
    "code": "def delete_device(self, device_id):\n        api = self._get_api(device_directory.DefaultApi)\n        return api.device_destroy(id=device_id)",
    "docstring": "Delete device from catalog.\n\n        :param str device_id: ID of device in catalog to delete (Required)\n        :return: void"
  },
  {
    "code": "def set_cursor(self, x, y):\n        curses.curs_set(1)\n        self.screen.move(y, x)",
    "docstring": "Sets the cursor to the desired position.\n\n        :param x: X position\n        :param y: Y position"
  },
  {
    "code": "def add(self, *tokens: str) -> None:\n        from wdom.web_node import WdomElement\n        _new_tokens = []\n        for token in tokens:\n            self._validate_token(token)\n            if token and token not in self:\n                self._list.append(token)\n                _new_tokens.append(token)\n        if isinstance(self._owner, WdomElement) and _new_tokens:\n            self._owner.js_exec('addClass', _new_tokens)",
    "docstring": "Add new tokens to list."
  },
  {
    "code": "def fit(self, train_events, test_events, n_epoch=1):\n        for e in train_events:\n            self.__validate(e)\n            self.rec.users[e.user.index]['known_items'].add(e.item.index)\n            self.item_buffer.append(e.item.index)\n        for e in test_events:\n            self.__validate(e)\n            self.item_buffer.append(e.item.index)\n        self.__batch_update(train_events, test_events, n_epoch)\n        for e in test_events:\n            self.rec.users[e.user.index]['known_items'].add(e.item.index)\n            self.rec.update(e)",
    "docstring": "Train a model using the first 30% positive events to avoid cold-start.\n\n        Evaluation of this batch training is done by using the next 20% positive events.\n        After the batch SGD training, the models are incrementally updated by using the 20% test events.\n\n        Args:\n            train_events (list of Event): Positive training events (0-30%).\n            test_events (list of Event): Test events (30-50%).\n            n_epoch (int): Number of epochs for the batch training."
  },
  {
    "code": "def caution_title_header_element(feature, parent):\n    _ = feature, parent\n    header = caution_title_header['string_format']\n    return header.capitalize()",
    "docstring": "Retrieve caution title header string from definitions."
  },
  {
    "code": "def _eval(self, node):\n        try:\n            handler = self.nodes[type(node)]\n        except KeyError:\n            raise ValueError(\"Sorry, {0} is not available in this evaluator\".format(type(node).__name__))\n        return handler(node)",
    "docstring": "Evaluate a node\n\n        :param node: Node to eval\n        :return: Result of node"
  },
  {
    "code": "def get_normed_x(self, rows=None, cols=None):\n        if rows is None:\n            rows = list(range(0, self.get_sample_size()))\n        if cols is None:\n            cols = list(range(0, self.get_dimensionality()))\n        if not hasattr(rows, \"__iter__\"):\n            rows = [rows]\n        rows = sorted(list(set(rows)))\n        retValue = self.Xnorm[rows, :]\n        return retValue[:, cols]",
    "docstring": "Returns the normalized input data requested by the user\n            @ In, rows, a list of non-negative integers specifying the\n            row indices to return\n            @ In, cols, a list of non-negative integers specifying the\n            column indices to return\n            @ Out, a matrix of floating point values specifying the\n            normalized data values used in internal computations\n            filtered by the three input parameters."
  },
  {
    "code": "def get_session_class(cls, interface_type, resource_class):\n        try:\n            return cls._session_classes[(interface_type, resource_class)]\n        except KeyError:\n            raise ValueError('No class registered for %s, %s' % (interface_type, resource_class))",
    "docstring": "Return the session class for a given interface type and resource class.\n\n        :type interface_type: constants.InterfaceType\n        :type resource_class: str\n        :return: Session"
  },
  {
    "code": "def view_rect(self) -> QRectF:\n        top_left = self.mapToScene(0, 0)\n        bottom_right = self.mapToScene(self.viewport().width() - 1, self.viewport().height() - 1)\n        return QRectF(top_left, bottom_right)",
    "docstring": "Return the boundaries of the view in scene coordinates"
  },
  {
    "code": "def start(self, reloading=False):\n        for event in self.event_handlers:\n            self.controller.listen(event)",
    "docstring": "Called when the module is loaded.\n\n        If the load is due to a reload of the module, then the 'reloading'\n        argument will be set to True. By default, this method calls the\n        controller's listen() for each event in the self.event_handlers dict."
  },
  {
    "code": "def lacp_timeout(self, **kwargs):\n        int_type = kwargs.pop('int_type').lower()\n        name = kwargs.pop('name')\n        timeout = kwargs.pop('timeout')\n        callback = kwargs.pop('callback', self._callback)\n        int_types = [\n            'gigabitethernet',\n            'tengigabitethernet',\n            'fortygigabitethernet',\n            'hundredgigabitethernet'\n        ]\n        if int_type not in int_types:\n            raise ValueError(\"Incorrect int_type value.\")\n        valid_timeouts = ['long', 'short']\n        if timeout not in valid_timeouts:\n            raise ValueError(\"Incorrect timeout value\")\n        timeout_args = dict(name=name, timeout=timeout)\n        if not pynos.utilities.valid_interface(int_type, name):\n            raise ValueError(\"Incorrect name value.\")\n        config = getattr(\n            self._interface,\n            'interface_%s_lacp_timeout' % int_type\n        )(**timeout_args)\n        return callback(config)",
    "docstring": "Set lacp timeout.\n\n        Args:\n            int_type (str): Type of interface. (gigabitethernet,\n                tengigabitethernet, etc)\n            timeout (str):  Timeout length.  (short, long)\n            name (str): Name of interface. (1/0/5, 1/0/10, etc)\n            callback (function): A function executed upon completion of the\n                method.  The only parameter passed to `callback` will be the\n                ``ElementTree`` `config`.\n\n        Returns:\n            Return value of `callback`.\n\n        Raises:\n            KeyError: if `int_type`, `name`, or `timeout` is not specified.\n            ValueError: if `int_type`, `name`, or `timeout is not valid.\n\n        Examples:\n            >>> import pynos.device\n            >>> switches = ['10.24.39.211', '10.24.39.203']\n            >>> auth = ('admin', 'password')\n            >>> int_type = 'tengigabitethernet'\n            >>> name = '225/0/39'\n            >>> for switch in switches:\n            ...     conn = (switch, '22')\n            ...     with pynos.device.Device(conn=conn, auth=auth) as dev:\n            ...         output = dev.interface.channel_group(name=name,\n            ...         int_type=int_type, port_int='1',\n            ...         channel_type='standard', mode='active')\n            ...         output = dev.interface.lacp_timeout(name=name,\n            ...         int_type=int_type, timeout='long')\n            ...         dev.interface.lacp_timeout()\n            ...         # doctest: +IGNORE_EXCEPTION_DETAIL\n            Traceback (most recent call last):\n            KeyError"
  },
  {
    "code": "def println(self, text=\"\"):\n        if self.word_wrap:\n            directives = ansi_color.find_directives(text, self)\n            clean_text = ansi_color.strip_ansi_codes(text)\n            clean_lines = self.tw.wrap(clean_text)\n            index = 0\n            for line in clean_lines:\n                line_length = len(line)\n                y = 0\n                while y < line_length:\n                    method, args = directives[index]\n                    if method == self.putch:\n                        y += 1\n                    method(*args)\n                    index += 1\n                self.newline()\n        else:\n            self.puts(text)\n            self.newline()",
    "docstring": "Prints the supplied text to the device, scrolling where necessary.\n        The text is always followed by a newline.\n\n        :param text: The text to print.\n        :type text: str"
  },
  {
    "code": "def predict_mappings(self, mappings):\r\n        if self.nat_type not in self.predictable_nats:\r\n            msg = \"Can't predict mappings for non-predictable NAT type.\"\r\n            raise Exception(msg)\r\n        for mapping in mappings:\r\n            mapping[\"bound\"] = mapping[\"sock\"].getsockname()[1]\r\n            if self.nat_type == \"preserving\":\r\n                mapping[\"remote\"] = mapping[\"source\"]\r\n            if self.nat_type == \"delta\":\r\n                max_port = 65535\r\n                mapping[\"remote\"] = int(mapping[\"source\"]) + self.delta\r\n                if mapping[\"remote\"] > max_port:\r\n                    mapping[\"remote\"] -= max_port\r\n                if mapping[\"remote\"] < 0:\r\n                    mapping[\"remote\"] = max_port - -mapping[\"remote\"]\r\n                if mapping[\"remote\"] < 1 or mapping[\"remote\"] > max_port:\r\n                    mapping[\"remote\"] = 1\r\n                mapping[\"remote\"] = str(mapping[\"remote\"])\r\n        return mappings",
    "docstring": "This function is used to predict the remote ports that a NAT\r\n        will map a local connection to. It requires the NAT type to\r\n        be determined before use. Current support for preserving and\r\n        delta type mapping behaviour."
  },
  {
    "code": "def refresh(self):\n        url = CONST.AUTOMATION_ID_URL\n        url = url.replace(\n            '$AUTOMATIONID$', self.automation_id)\n        response = self._abode.send_request(method=\"get\", url=url)\n        response_object = json.loads(response.text)\n        if isinstance(response_object, (tuple, list)):\n            response_object = response_object[0]\n        if str(response_object['id']) != self.automation_id:\n            raise AbodeException((ERROR.INVALID_AUTOMATION_REFRESH_RESPONSE))\n        self.update(response_object)",
    "docstring": "Refresh the automation."
  },
  {
    "code": "def parse_poi_query(north, south, east, west, amenities=None, timeout=180, maxsize=''):\n    if amenities:\n        query_template = ('[out:json][timeout:{timeout}]{maxsize};((node[\"amenity\"~\"{amenities}\"]({south:.6f},'\n                          '{west:.6f},{north:.6f},{east:.6f});(._;>;););(way[\"amenity\"~\"{amenities}\"]({south:.6f},'\n                          '{west:.6f},{north:.6f},{east:.6f});(._;>;););(relation[\"amenity\"~\"{amenities}\"]'\n                          '({south:.6f},{west:.6f},{north:.6f},{east:.6f});(._;>;);););out;')\n        query_str = query_template.format(amenities=\"|\".join(amenities), north=north, south=south, east=east, west=west,\n                                          timeout=timeout, maxsize=maxsize)\n    else:\n        query_template = ('[out:json][timeout:{timeout}]{maxsize};((node[\"amenity\"]({south:.6f},'\n                          '{west:.6f},{north:.6f},{east:.6f});(._;>;););(way[\"amenity\"]({south:.6f},'\n                          '{west:.6f},{north:.6f},{east:.6f});(._;>;););(relation[\"amenity\"]'\n                          '({south:.6f},{west:.6f},{north:.6f},{east:.6f});(._;>;);););out;')\n        query_str = query_template.format(north=north, south=south, east=east, west=west,\n                                          timeout=timeout, maxsize=maxsize)\n    return query_str",
    "docstring": "Parse the Overpass QL query based on the list of amenities.\n\n    Parameters\n    ----------\n    \n    north : float\n        Northernmost coordinate from bounding box of the search area.\n    south : float\n        Southernmost coordinate from bounding box of the search area.\n    east : float\n        Easternmost coordinate from bounding box of the search area.\n    west : float\n        Westernmost coordinate of the bounding box of the search area.\n    amenities : list\n        List of amenities that will be used for finding the POIs from the selected area.\n    timeout : int\n        Timeout for the API request."
  },
  {
    "code": "def mkdir(self, paths, create_parent=False, mode=0o755):\n        if not isinstance(paths, list):\n            raise InvalidInputException(\"Paths should be a list\")\n        if not paths:\n            raise InvalidInputException(\"mkdirs: no path given\")\n        for path in paths:\n            if not path.startswith(\"/\"):\n                path = self._join_user_path(path)\n            fileinfo = self._get_file_info(path)\n            if not fileinfo:\n                try:\n                    request = client_proto.MkdirsRequestProto()\n                    request.src = path\n                    request.masked.perm = mode\n                    request.createParent = create_parent\n                    response = self.service.mkdirs(request)\n                    yield {\"path\": path, \"result\": response.result}\n                except RequestError as e:\n                    yield {\"path\": path, \"result\": False, \"error\": str(e)}\n            else:\n                yield {\"path\": path, \"result\": False, \"error\": \"mkdir: `%s': File exists\" % path}",
    "docstring": "Create a directoryCount\n\n        :param paths: Paths to create\n        :type paths: list of strings\n        :param create_parent: Also create the parent directories\n        :type create_parent: boolean\n        :param mode: Mode the directory should be created with\n        :type mode: int\n        :returns: a generator that yields dictionaries"
  },
  {
    "code": "def reprcall(name, args=(), kwargs=(), keywords='', sep=', ',\n        argfilter=repr):\n    if keywords:\n        keywords = ((', ' if (args or kwargs) else '') +\n                    '**' + keywords)\n    argfilter = argfilter or repr\n    return \"{name}({args}{sep}{kwargs}{keywords})\".format(\n            name=name, args=reprargs(args, filter=argfilter),\n            sep=(args and kwargs) and sep or \"\",\n            kwargs=reprkwargs(kwargs, sep), keywords=keywords or '')",
    "docstring": "Format a function call for display."
  },
  {
    "code": "def publish(self):\n        while True:\n            event = yield from self.event_source.get()\n            str_buffer = []\n            if event == POISON_PILL:\n                return\n            if isinstance(event, str):\n                str_buffer.append(event)\n            elif event.type == EventTypes.BLOCK_VALID:\n                str_buffer = map(json.dumps, eventify_block(event.data))\n            for str_item in str_buffer:\n                for _, websocket in self.subscribers.items():\n                    yield from websocket.send_str(str_item)",
    "docstring": "Publish new events to the subscribers."
  },
  {
    "code": "def get_snapshot_attribute(self, snapshot_id,\n                               attribute='createVolumePermission'):\n        params = {'Attribute' : attribute}\n        if snapshot_id:\n            params['SnapshotId'] = snapshot_id\n        return self.get_object('DescribeSnapshotAttribute', params,\n                               SnapshotAttribute, verb='POST')",
    "docstring": "Get information about an attribute of a snapshot.  Only one attribute\n        can be specified per call.\n\n        :type snapshot_id: str\n        :param snapshot_id: The ID of the snapshot.\n\n        :type attribute: str\n        :param attribute: The requested attribute.  Valid values are:\n\n                          * createVolumePermission\n\n        :rtype: list of :class:`boto.ec2.snapshotattribute.SnapshotAttribute`\n        :return: The requested Snapshot attribute"
  },
  {
    "code": "def retrieve_file_from_url(url):\n    try:\n        alias_source, _ = urlretrieve(url)\n        with open(alias_source, 'r') as f:\n            content = f.read()\n            if content[:3].isdigit():\n                raise CLIError(ALIAS_FILE_URL_ERROR.format(url, content.strip()))\n    except Exception as exception:\n        if isinstance(exception, CLIError):\n            raise\n        raise CLIError(ALIAS_FILE_URL_ERROR.format(url, exception))\n    return alias_source",
    "docstring": "Retrieve a file from an URL\n\n    Args:\n        url: The URL to retrieve the file from.\n\n    Returns:\n        The absolute path of the downloaded file."
  },
  {
    "code": "def _address_content(self, x):\n    mem_keys = tf.layers.dense(self.mem_vals, self.key_depth,\n                               bias_initializer=tf.constant_initializer(1.0),\n                               name=\"mem_key\")\n    mem_query = tf.layers.dense(x, self.key_depth,\n                                bias_initializer=tf.constant_initializer(1.0),\n                                name=\"mem_query\")\n    norm = tf.matmul(self._norm(mem_query), self._norm(mem_keys),\n                     transpose_b=True)\n    dot_product = tf.matmul(mem_query, mem_keys, transpose_b=True)\n    cos_dist = tf.div(dot_product, norm + 1e-7, name=\"cos_dist\")\n    access_logits = self.sharpen_factor * cos_dist\n    return access_logits",
    "docstring": "Address the memory based on content similarity.\n\n    Args:\n      x: a tensor in the shape of [batch_size, length, depth].\n    Returns:\n      the logits for each memory entry [batch_size, length, memory_size]."
  },
  {
    "code": "def get_cpu_state(self):\n        state = c_int(0)\n        self.library.Cli_GetPlcStatus(self.pointer,byref(state))\n        try:\n            status_string = cpu_statuses[state.value]\n        except KeyError:\n            status_string = None\n        if not status_string:\n            raise Snap7Exception(\"The cpu state (%s) is invalid\" % state.value)\n        logger.debug(\"CPU state is %s\" % status_string)\n        return status_string",
    "docstring": "Retrieves CPU state from client"
  },
  {
    "code": "def intersect(a, b):\n    if a[x0] == a[x1] or a[y0] == a[y1]:\n        return False\n    if b[x0] == b[x1] or b[y0] == b[y1]:\n        return False\n    return a[x0] <= b[x1] and b[x0] <= a[x1] and a[y0] <= b[y1] and b[y0] <= a[y1]",
    "docstring": "Check if two rectangles intersect"
  },
  {
    "code": "def check_enable_mode(self, check_string=\"\"):\n        self.write_channel(self.RETURN)\n        output = self.read_until_prompt()\n        return check_string in output",
    "docstring": "Check if in enable mode. Return boolean.\n\n        :param check_string: Identification of privilege mode from device\n        :type check_string: str"
  },
  {
    "code": "def noninteractive_changeset_update(self, fqn, template, old_parameters,\n                                        parameters, stack_policy, tags,\n                                        **kwargs):\n        logger.debug(\"Using noninterative changeset provider mode \"\n                     \"for %s.\", fqn)\n        _changes, change_set_id = create_change_set(\n            self.cloudformation, fqn, template, parameters, tags,\n            'UPDATE', service_role=self.service_role, **kwargs\n        )\n        self.deal_with_changeset_stack_policy(fqn, stack_policy)\n        self.cloudformation.execute_change_set(\n            ChangeSetName=change_set_id,\n        )",
    "docstring": "Update a Cloudformation stack using a change set.\n\n        This is required for stacks with a defined Transform (i.e. SAM), as the\n        default update_stack API cannot be used with them.\n\n        Args:\n            fqn (str): The fully qualified name of the Cloudformation stack.\n            template (:class:`stacker.providers.base.Template`): A Template\n                object to use when updating the stack.\n            old_parameters (list): A list of dictionaries that defines the\n                parameter list on the existing Cloudformation stack.\n            parameters (list): A list of dictionaries that defines the\n                parameter list to be applied to the Cloudformation stack.\n            stack_policy (:class:`stacker.providers.base.Template`): A template\n                object representing a stack policy.\n            tags (list): A list of dictionaries that defines the tags\n                that should be applied to the Cloudformation stack."
  },
  {
    "code": "def female_vulnerability_section_header_element(feature, parent):\n    _ = feature, parent\n    header = female_vulnerability_section_header['string_format']\n    return header.capitalize()",
    "docstring": "Retrieve female vulnerability section header string from definitions."
  },
  {
    "code": "def get_network_id(self, is_full: bool = False) -> int:\n        payload = self.generate_json_rpc_payload(RpcMethod.GET_NETWORK_ID)\n        response = self.__post(self.__url, payload)\n        if is_full:\n            return response\n        return response['result']",
    "docstring": "This interface is used to get the network id of current network.\n\n        Return:\n            the network id of current network."
  },
  {
    "code": "def calculated_intervals(self):\n        if self._calculated_intervals is None:\n            logging.debug(\"get calculated intervals\")\n            self.load()\n            return self.mongo_model.get_calculated_intervals()\n        return self._calculated_intervals",
    "docstring": "Gets the calculated intervals from the database\n\n        :return: The calculated intervals"
  },
  {
    "code": "def _get_bandfilenames(self):\n        for band in self.bandnames:\n            LOG.debug(\"Band = %s\", str(band))\n            self.filenames[band] = os.path.join(self.path,\n                                                self.options[self.platform_name + '-' +\n                                                             self.instrument][band])\n            LOG.debug(self.filenames[band])\n            if not os.path.exists(self.filenames[band]):\n                LOG.warning(\"Couldn't find an existing file for this band: %s\",\n                            str(self.filenames[band]))",
    "docstring": "Get the instrument rsr filenames"
  },
  {
    "code": "async def get_pinstate_report(self, command):\n        pin = int(command[0])\n        value = await self.core.get_pin_state(pin)\n        if value:\n            reply = json.dumps({\"method\": \"pin_state_reply\", \"params\": value})\n        else:\n            reply = json.dumps({\"method\": \"pin_state_reply\", \"params\": \"Unknown\"})\n        await self.websocket.send(reply)",
    "docstring": "This method retrieves a Firmata pin_state report for a pin..\n\n        See: http://firmata.org/wiki/Protocol#Pin_State_Query\n\n        :param command: {\"method\": \"get_pin_state\", \"params\": [PIN]}\n        :returns: {\"method\": \"get_pin_state_reply\", \"params\": [PIN_NUMBER, PIN_MODE, PIN_STATE]}"
  },
  {
    "code": "def remember_identity(self, subject, authc_token, account_id):\n        try:\n            identifiers = self.get_identity_to_remember(subject, account_id)\n        except AttributeError:\n            msg = \"Neither account_id nor identifier arguments passed\"\n            raise AttributeError(msg)\n        encrypted = self.convert_identifiers_to_bytes(identifiers)\n        self.remember_encrypted_identity(subject, encrypted)",
    "docstring": "Yosai consolidates rememberIdentity, an overloaded method in java,\n        to a method that will use an identifier-else-account logic.\n\n        Remembers a subject-unique identity for retrieval later.  This\n        implementation first resolves the exact identifying attributes to\n        remember.  It then remembers these identifying attributes by calling\n            remember_identity(Subject, IdentifierCollection)\n\n        :param subject:  the subject for which the identifying attributes are\n                         being remembered\n        :param authc_token:  ignored in the AbstractRememberMeManager\n        :param account_id: the account id of authenticated account"
  },
  {
    "code": "def version(msg):\n    tc = typecode(msg)\n    if tc != 31:\n        raise RuntimeError(\"%s: Not a status operation message, expecting TC = 31\" % msg)\n    msgbin = common.hex2bin(msg)\n    version = common.bin2int(msgbin[72:75])\n    return version",
    "docstring": "ADS-B Version\n\n    Args:\n        msg (string): 28 bytes hexadecimal message string, TC = 31\n\n    Returns:\n        int: version number"
  },
  {
    "code": "def setup_zmq(self):\n        self.context = zmq.Context()\n        self.push = self.context.socket(zmq.PUSH)\n        self.push_port = self.push.bind_to_random_port(\"tcp://%s\" % self.host)\n        eventlet.spawn(self.zmq_pull)\n        eventlet.sleep(0)",
    "docstring": "Set up a PUSH and a PULL socket.  The PUSH socket will push out\n        requests to the workers.  The PULL socket will receive responses from\n        the workers and reply through the server socket."
  },
  {
    "code": "def count_channels(self):\n        merge = self.index['merge']\n        if len(self.idx_chan.selectedItems()) > 1:\n            if merge.isEnabled():\n                return\n            else:\n                merge.setEnabled(True)\n        else:\n            self.index['merge'].setCheckState(Qt.Unchecked)\n            self.index['merge'].setEnabled(False)",
    "docstring": "If more than one channel selected, activate merge checkbox."
  },
  {
    "code": "def cmd_wp_undo(self):\n        if self.undo_wp_idx == -1 or self.undo_wp is None:\n            print(\"No undo information\")\n            return\n        wp = self.undo_wp\n        if self.undo_type == 'move':\n            wp.target_system    = self.target_system\n            wp.target_component = self.target_component\n            self.loading_waypoints = True\n            self.loading_waypoint_lasttime = time.time()\n            self.master.mav.mission_write_partial_list_send(self.target_system,\n                                                            self.target_component,\n                                                            self.undo_wp_idx, self.undo_wp_idx)\n            self.wploader.set(wp, self.undo_wp_idx)\n            print(\"Undid WP move\")\n        elif self.undo_type == 'remove':\n            self.wploader.insert(self.undo_wp_idx, wp)\n            self.fix_jumps(self.undo_wp_idx, 1)\n            self.send_all_waypoints()\n            print(\"Undid WP remove\")\n        else:\n            print(\"bad undo type\")\n        self.undo_wp = None\n        self.undo_wp_idx = -1",
    "docstring": "handle wp undo"
  },
  {
    "code": "def _is_lang_change(self, request):\n        if 'lang' not in request.GET:\n            return False\n        return not any(request.path.endswith(url) for url in self.exempt_urls)",
    "docstring": "Return True if the lang param is present and URL isn't exempt."
  },
  {
    "code": "def get_all_mfa_devices(self, user_name, marker=None, max_items=None):\n        params = {'UserName' : user_name}\n        if marker:\n            params['Marker'] = marker\n        if max_items:\n            params['MaxItems'] = max_items\n        return self.get_response('ListMFADevices',\n                                 params, list_marker='MFADevices')",
    "docstring": "Get all MFA devices associated with an account.\n\n        :type user_name: string\n        :param user_name: The username of the user\n\n        :type marker: string\n        :param marker: Use this only when paginating results and only in\n                       follow-up request after you've received a response\n                       where the results are truncated.  Set this to the\n                       value of the Marker element in the response you\n                       just received.\n\n        :type max_items: int\n        :param max_items: Use this only when paginating results to indicate\n                          the maximum number of groups you want in the\n                          response."
  },
  {
    "code": "def set_major(self):\n        old_version = self.get_version()\n        new_version = str(int(old_version.split('.', 5)[0])+1) + '.0.0'\n        self.set_version(old_version, new_version)",
    "docstring": "Increment the major number of project"
  },
  {
    "code": "def register_binary_type(content_type, dumper, loader):\n    content_type = headers.parse_content_type(content_type)\n    content_type.parameters.clear()\n    key = str(content_type)\n    _content_types[key] = content_type\n    handler = _content_handlers.setdefault(key, _ContentHandler(key))\n    handler.dict_to_bytes = dumper\n    handler.bytes_to_dict = loader",
    "docstring": "Register handling for a binary content type.\n\n    :param str content_type: content type to register the hooks for\n    :param dumper: called to decode bytes into a dictionary.\n        Calling convention: ``dumper(obj_dict) -> bytes``.\n    :param loader: called to encode a dictionary into a byte string.\n        Calling convention: ``loader(obj_bytes) -> dict``"
  },
  {
    "code": "def execute(self):\n        self.print_info()\n        if self._config.command_args.get('destroy') == 'never':\n            msg = \"Skipping, '--destroy=never' requested.\"\n            LOG.warn(msg)\n            return\n        if self._config.driver.delegated and not self._config.driver.managed:\n            msg = 'Skipping, instances are delegated.'\n            LOG.warn(msg)\n            return\n        self._config.provisioner.destroy()\n        self._config.state.reset()",
    "docstring": "Execute the actions necessary to perform a `molecule destroy` and\n        returns None.\n\n        :return: None"
  },
  {
    "code": "async def get_current_position(self, refresh=True) -> dict:\n        if refresh:\n            await self.refresh()\n        position = self._raw_data.get(ATTR_POSITION_DATA)\n        return position",
    "docstring": "Return the current shade position.\n\n        :param refresh: If True it queries the hub for the latest info.\n        :return: Dictionary with position data."
  },
  {
    "code": "def types(self):\n        return [x for x in self[self.current_scope].values() if isinstance(x, symbols.TYPE)]",
    "docstring": "Returns symbol instances corresponding to type declarations\n        within the current scope."
  },
  {
    "code": "def set_scenemode(self, scenemode='auto'):\n        if scenemode not in self.available_settings['scenemode']:\n            _LOGGER.debug('%s is not a valid scenemode', scenemode)\n            return False\n        return self.change_setting('scenemode', scenemode)",
    "docstring": "Set the video scene mode.\n\n        Return a coroutine."
  },
  {
    "code": "def get_by_id(cls, record_id, execute=True):\n        query = cls.base_query().where(cls.id == record_id)\n        if execute:\n            return query.get()\n        return query",
    "docstring": "Return a single instance of the model queried by ID.\n\n        Args:\n            record_id (int): Integer representation of the ID to query on.\n\n        Keyword Args:\n            execute (bool, optional):\n                Should this method execute the query or return a query object\n                for further manipulation?\n\n        Returns:\n            cls | :py:class:`peewee.SelectQuery`:\n                If ``execute`` is ``True``, the query is executed, otherwise\n                a query is returned.\n\n        Raises:\n            :py:class:`peewee.DoesNotExist`:\n                Raised if a record with that ID doesn't exist."
  },
  {
    "code": "def exitContainer(self):\r\n        try:\r\n            entry = self._compoundStack.pop()\r\n        except IndexError:\r\n            return\r\n        container = self.currentContainer()\r\n        entry.setQuery(container.query())\r\n        self.slideInPrev()",
    "docstring": "Removes the current query container."
  },
  {
    "code": "def add_ops(op_classes):\n    def f(cls):\n        for op_attr_name, op_class in op_classes.items():\n            ops = getattr(cls, '{name}_ops'.format(name=op_attr_name))\n            ops_map = getattr(cls, '{name}_op_nodes_map'.format(\n                name=op_attr_name))\n            for op in ops:\n                op_node = ops_map[op]\n                if op_node is not None:\n                    made_op = _op_maker(op_class, op)\n                    setattr(cls, 'visit_{node}'.format(node=op_node), made_op)\n        return cls\n    return f",
    "docstring": "Decorator to add default implementation of ops."
  },
  {
    "code": "def scan(self, callback=None):\n        def scan_finished():\n            time.sleep(3)\n            logging.info('Scan finished')\n            self._nb_of_modules_loaded = 0\n            def module_loaded():\n                self._nb_of_modules_loaded += 1\n                if self._nb_of_modules_loaded >= len(self._modules):\n                    callback()\n            for module in self._modules:\n                self._modules[module].load(module_loaded)\n        for address in range(0, 256):\n            message = velbus.ModuleTypeRequestMessage(address)\n            if address == 255:\n                self.send(message, scan_finished)\n            else:\n                self.send(message)",
    "docstring": "Scan the bus and call the callback when a new module is discovered\n\n        :return: None"
  },
  {
    "code": "def info(self):\n        buf = _C.array_int32(_C.H4_MAX_VAR_DIMS)\n        status, sds_name, rank, data_type, n_attrs = \\\n                _C.SDgetinfo(self._id, buf)\n        _checkErr('info', status, \"cannot execute\")\n        dim_sizes = _array_to_ret(buf, rank)\n        return sds_name, rank, dim_sizes, data_type, n_attrs",
    "docstring": "Retrieves information about the dataset.\n\n        Args::\n\n          no argument\n\n        Returns::\n\n          5-element tuple holding:\n\n          - dataset name\n          - dataset rank (number of dimensions)\n          - dataset shape, that is a list giving the length of each\n            dataset dimension; if the first dimension is unlimited, then\n            the first value of the list gives the current length of the\n            unlimited dimension\n          - data type (one of the SDC.xxx values)\n          - number of attributes defined for the dataset\n\n        C library equivalent : SDgetinfo"
  },
  {
    "code": "async def _get_async(self, url, session):\n        data = None\n        async with session.get(url) as resp:\n            if resp.status == 200:\n                data = await resp.json()\n        return data",
    "docstring": "Asynchronous internal method used for GET requests\n\n        Args:\n            url (str): URL to fetch\n            session (obj): aiohttp client session for async loop\n\n        Returns:\n            data (obj): Individual URL request's response corountine"
  },
  {
    "code": "def fix_e711(self, result):\n        (line_index, offset, target) = get_index_offset_contents(result,\n                                                                 self.source)\n        right_offset = offset + 2\n        if right_offset >= len(target):\n            return []\n        left = target[:offset].rstrip()\n        center = target[offset:right_offset]\n        right = target[right_offset:].lstrip()\n        if not right.startswith('None'):\n            return []\n        if center.strip() == '==':\n            new_center = 'is'\n        elif center.strip() == '!=':\n            new_center = 'is not'\n        else:\n            return []\n        self.source[line_index] = ' '.join([left, new_center, right])",
    "docstring": "Fix comparison with None."
  },
  {
    "code": "def listify(generator_func):\n    def list_func(*args, **kwargs):\n        return degenerate(generator_func(*args, **kwargs))\n    return list_func",
    "docstring": "Converts generator functions into list returning functions.\n\n    @listify\n    def test():\n        yield 1\n    test()\n    # => [1]"
  },
  {
    "code": "def get_output_mode(output, mode):\n    if mode != 'auto':\n        try:\n            return switch_output_mode_auto[mode]\n        except KeyError:\n            raise ValueError('Mode \"{}\" is not supported.')\n    extension = output.split('.')[-1]\n    try:\n        return switch_output_mode[extension]\n    except KeyError:\n        return intermediary_to_schema",
    "docstring": "From the output name and the mode returns a the function that will transform the intermediary\n    representation to the output."
  },
  {
    "code": "def call_multiple_modules(module_gen):\n    for args_seq in module_gen:\n        module_name_or_path = args_seq[0]\n        with replace_sys_args(args_seq):\n            if re.match(VALID_PACKAGE_RE, module_name_or_path):\n                runpy.run_module(module_name_or_path,\n                                 run_name='__main__')\n            else:\n                runpy.run_path(module_name_or_path,\n                               run_name='__main__')",
    "docstring": "Call each module\n\n    module_gen should be a iterator"
  },
  {
    "code": "def abort(code, error=None, message=None):\n    if error is None:\n        flask_abort(code)\n    elif isinstance(error, Response):\n        error.status_code = code\n        flask_abort(code, response=error)\n    else:\n        body = {\n            \"status\": code,\n            \"error\": error,\n            \"message\": message\n        }\n        flask_abort(code, response=export(body, code))",
    "docstring": "Abort with suitable error response\n\n    Args:\n        code (int): status code\n        error (str): error symbol or flask.Response\n        message (str): error message"
  },
  {
    "code": "def annotation_spec_path(cls, project, location, dataset, annotation_spec):\n        return google.api_core.path_template.expand(\n            \"projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}\",\n            project=project,\n            location=location,\n            dataset=dataset,\n            annotation_spec=annotation_spec,\n        )",
    "docstring": "Return a fully-qualified annotation_spec string."
  },
  {
    "code": "def get_by_instance(self, instance):\n        for model, registry in self.items():\n            try:\n                instance_class = model._meta.get_field('instance').remote_field.model\n                if isinstance(instance, instance_class):\n                    return registry\n            except FieldDoesNotExist:\n                pass\n        return None",
    "docstring": "Return a preference registry using a model instance"
  },
  {
    "code": "def _addPeptide(self, sequence, proteinId, digestInfo):\n        stdSequence = self.getStdSequence(sequence)\n        if stdSequence not in self.peptides:\n            self.peptides[stdSequence] = PeptideEntry(\n                stdSequence, mc=digestInfo['missedCleavage']\n            )\n        if sequence not in self.peptides:\n            self.peptides[sequence] = self.peptides[stdSequence]\n        if proteinId not in self.peptides[stdSequence].proteins:\n            self.peptides[stdSequence].proteins.add(proteinId)\n            self.peptides[stdSequence].proteinPositions[proteinId] = (\n                                    digestInfo['startPos'], digestInfo['endPos']\n                                    )\n            self.proteins[proteinId].peptides.add(sequence)",
    "docstring": "Add a peptide to the protein database.\n\n        :param sequence: str, amino acid sequence\n        :param proteinId: str, proteinId\n        :param digestInfo: dict, contains information about the in silico digest\n            must contain the keys 'missedCleavage', 'startPos' and 'endPos'"
  },
  {
    "code": "def get(self, user_id):\n        user = db.User.find_one(User.user_id == user_id)\n        roles = db.Role.all()\n        if not user:\n            return self.make_response('Unable to find the user requested, might have been removed', HTTP.NOT_FOUND)\n        return self.make_response({\n            'user': user.to_json(),\n            'roles': roles\n        }, HTTP.OK)",
    "docstring": "Returns a specific user"
  },
  {
    "code": "def api_key_from_file(url):\n    path = os.path.expanduser('~/.config/python-bugzilla/bugzillarc')\n    cfg = SafeConfigParser()\n    cfg.read(path)\n    domain = urlparse(url)[1]\n    if domain not in cfg.sections():\n        return None\n    if not cfg.has_option(domain, 'api_key'):\n        return None\n    return cfg.get(domain, 'api_key')",
    "docstring": "Check bugzillarc for an API key for this Bugzilla URL."
  },
  {
    "code": "def start_end_from_segments(segment_file):\n    from glue.ligolw.ligolw import LIGOLWContentHandler as h; lsctables.use_in(h)\n    indoc = ligolw_utils.load_filename(segment_file, False, contenthandler=h)\n    segment_table  = table.get_table(indoc, lsctables.SegmentTable.tableName)\n    start = numpy.array(segment_table.getColumnByName('start_time'))\n    start_ns = numpy.array(segment_table.getColumnByName('start_time_ns'))\n    end = numpy.array(segment_table.getColumnByName('end_time'))\n    end_ns = numpy.array(segment_table.getColumnByName('end_time_ns'))\n    return start + start_ns * 1e-9, end + end_ns * 1e-9",
    "docstring": "Return the start and end time arrays from a segment file.\n\n    Parameters\n    ----------\n    segment_file: xml segment file\n\n    Returns\n    -------\n    start: numpy.ndarray\n    end: numpy.ndarray"
  },
  {
    "code": "def load_txt_to_sql(tbl_name, src_file_and_path, src_file, op_folder):\n    if op_folder == '':\n        pth = ''\n    else:\n        pth = op_folder + os.sep\n    fname_create_script = pth + 'CREATE_' + tbl_name + '.SQL'\n    fname_backout_file  = pth + 'BACKOUT_' + tbl_name + '.SQL'\n    fname_control_file  = pth + tbl_name + '.CTL'\n    cols = read_csv_cols_to_table_cols(src_file)\n    create_script_staging_table(fname_create_script, tbl_name, cols)    \n    create_file(fname_backout_file, 'DROP TABLE ' + tbl_name + ' CASCADE CONSTRAINTS;\\n')\n    create_CTL(fname_control_file, tbl_name, cols, 'TRUNCATE')",
    "docstring": "creates a SQL loader script to load a text file into a database\n    and then executes it.\n    Note that src_file is"
  },
  {
    "code": "def __calculate_always_decrease_rw_values(\n        table_name, read_units, provisioned_reads,\n        write_units, provisioned_writes):\n    if read_units <= provisioned_reads and write_units <= provisioned_writes:\n        return (read_units, write_units)\n    if read_units < provisioned_reads:\n        logger.info(\n            '{0} - Reads could be decreased, but we are waiting for '\n            'writes to get lower than the threshold before '\n            'scaling down'.format(table_name))\n        read_units = provisioned_reads\n    elif write_units < provisioned_writes:\n        logger.info(\n            '{0} - Writes could be decreased, but we are waiting for '\n            'reads to get lower than the threshold before '\n            'scaling down'.format(table_name))\n        write_units = provisioned_writes\n    return (read_units, write_units)",
    "docstring": "Calculate values for always-decrease-rw-together\n\n    This will only return reads and writes decreases if both reads and writes\n    are lower than the current provisioning\n\n\n    :type table_name: str\n    :param table_name: Name of the DynamoDB table\n    :type read_units: int\n    :param read_units: New read unit provisioning\n    :type provisioned_reads: int\n    :param provisioned_reads: Currently provisioned reads\n    :type write_units: int\n    :param write_units: New write unit provisioning\n    :type provisioned_writes: int\n    :param provisioned_writes: Currently provisioned writes\n    :returns: (int, int) -- (reads, writes)"
  },
  {
    "code": "def head(self, n=None):\n        if n is None:\n            rs = self.head(1)\n            return rs[0] if rs else None\n        return self.take(n)",
    "docstring": "Returns the first ``n`` rows.\n\n        .. note:: This method should only be used if the resulting array is expected\n            to be small, as all the data is loaded into the driver's memory.\n\n        :param n: int, default 1. Number of rows to return.\n        :return: If n is greater than 1, return a list of :class:`Row`.\n            If n is 1, return a single Row.\n\n        >>> df.head()\n        Row(age=2, name=u'Alice')\n        >>> df.head(1)\n        [Row(age=2, name=u'Alice')]"
  },
  {
    "code": "def translate(patterns, flags):\n    positive = []\n    negative = []\n    if isinstance(patterns, (str, bytes)):\n        patterns = [patterns]\n    flags |= _TRANSLATE\n    for pattern in patterns:\n        for expanded in expand_braces(pattern, flags):\n            (negative if is_negative(expanded, flags) else positive).append(\n                WcParse(expanded, flags & FLAG_MASK).parse()\n            )\n    if patterns and flags & REALPATH and negative and not positive:\n        positive.append(_compile(b'**' if isinstance(patterns[0], bytes) else '**', flags))\n    return positive, negative",
    "docstring": "Translate patterns."
  },
  {
    "code": "def value(self, raw_value):\n        try:\n            return base64.b64decode(bytes(raw_value, 'utf-8')).decode('utf-8')\n        except binascii.Error as err:\n            raise ValueError(str(err))",
    "docstring": "Decode param with Base64."
  },
  {
    "code": "def referenced_by(self):\n        href = fetch_entry_point('references_by_element')\n        return [Element.from_meta(**ref)\n                for ref in self.make_request(\n                    method='create',\n                    href=href,\n                    json={'value': self.href})]",
    "docstring": "Show all references for this element. A reference means that this\n        element is being used, for example, in a policy rule, as a member of\n        a group, etc.\n\n        :return: list referenced elements\n        :rtype: list(Element)"
  },
  {
    "code": "def get_intent(self,\n                   name,\n                   language_code=None,\n                   intent_view=None,\n                   retry=google.api_core.gapic_v1.method.DEFAULT,\n                   timeout=google.api_core.gapic_v1.method.DEFAULT,\n                   metadata=None):\n        if 'get_intent' not in self._inner_api_calls:\n            self._inner_api_calls[\n                'get_intent'] = google.api_core.gapic_v1.method.wrap_method(\n                    self.transport.get_intent,\n                    default_retry=self._method_configs['GetIntent'].retry,\n                    default_timeout=self._method_configs['GetIntent'].timeout,\n                    client_info=self._client_info,\n                )\n        request = intent_pb2.GetIntentRequest(\n            name=name,\n            language_code=language_code,\n            intent_view=intent_view,\n        )\n        return self._inner_api_calls['get_intent'](\n            request, retry=retry, timeout=timeout, metadata=metadata)",
    "docstring": "Retrieves the specified intent.\n\n        Example:\n            >>> import dialogflow_v2\n            >>>\n            >>> client = dialogflow_v2.IntentsClient()\n            >>>\n            >>> name = client.intent_path('[PROJECT]', '[INTENT]')\n            >>>\n            >>> response = client.get_intent(name)\n\n        Args:\n            name (str): Required. The name of the intent.\n                Format: ``projects/<Project ID>/agent/intents/<Intent ID>``.\n            language_code (str): Optional. The language to retrieve training phrases, parameters and rich\n                messages for. If not specified, the agent's default language is used.\n                [More than a dozen\n                languages](https://dialogflow.com/docs/reference/language) are supported.\n                Note: languages must be enabled in the agent, before they can be used.\n            intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent.\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.dialogflow_v2.types.Intent` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def load_addon_packages(self, config_data):\n        section_config = config_data.get(\"config\")\n        if not isinstance(section_config, dict):\n            if section_config is None:\n                return\n            raise ConfigurationError(\n                \"'config' is %s instead of dict\" % (\n                    type(section_config),\n                ),\n            )\n        section_addons = section_config.get(\"addons\", [])\n        if not isinstance(section_addons, list):\n            raise ConfigurationError(\n                \"'config.addons' is %s instead of list\" % (\n                    type(section_addons),\n                ),\n            )\n        for index, module_path in enumerate(section_addons):\n            if not isinstance(module_path, six.text_type):\n                raise ConfigurationError(\n                    \"Item %d in 'config.addons' is %s instead of string\" % (\n                        index,\n                        type(module_path),\n                    ),\n                )\n        self.addon_packages = list(section_addons)",
    "docstring": "Loads the module paths from which the configuration will attempt to\n        load sanitizers from. These must be stored as a list of strings under\n        \"config.addons\" section of the configuration data.\n\n        :param config_data: Already parsed configuration data, as dictionary.\n        :type config_data: dict[str,any]"
  },
  {
    "code": "def split_at_offsets(line, offsets):\n    result = []\n    previous_offset = 0\n    current_offset = 0\n    for current_offset in sorted(offsets):\n        if current_offset < len(line) and previous_offset != current_offset:\n            result.append(line[previous_offset:current_offset].strip())\n        previous_offset = current_offset\n    result.append(line[current_offset:])\n    return result",
    "docstring": "Split line at offsets.\n\n    Return list of strings."
  },
  {
    "code": "def prepare_time_micros(data, schema):\n    if isinstance(data, datetime.time):\n        return long(data.hour * MCS_PER_HOUR + data.minute * MCS_PER_MINUTE\n                    + data.second * MCS_PER_SECOND + data.microsecond)\n    else:\n        return data",
    "docstring": "Convert datetime.time to int timestamp with microseconds"
  },
  {
    "code": "def from_file(cls,\n                  source,\n                  distance_weights=None,\n                  merge_same_words=False,\n                  group_marker_opening='<<',\n                  group_marker_closing='>>'):\n        source_string = open(source, 'r').read()\n        return cls.from_string(source_string,\n                               distance_weights,\n                               merge_same_words,\n                               group_marker_opening=group_marker_opening,\n                               group_marker_closing=group_marker_closing)",
    "docstring": "Read a string from a file and derive a ``Graph`` from it.\n\n        This is a convenience function for opening a file and passing its\n        contents to ``Graph.from_string()`` (see that for more detail)\n\n        Args:\n            source (str): the file to read and derive the graph from\n            distance_weights (dict): dict of relative indices corresponding\n                with word weights. See ``Graph.from_string`` for more detail.\n            merge_same_words (bool): whether nodes which have the same value\n                should be merged or not.\n            group_marker_opening (str): The string used to mark the beginning\n                of word groups.\n            group_marker_closing (str): The string used to mark the end\n                of word groups.\n\n        Returns: Graph\n\n        Example:\n            >>> graph = Graph.from_file('cage.txt')            # doctest: +SKIP\n            >>> ' '.join(graph.pick().value for i in range(8)) # doctest: +SKIP\n            'poetry i have nothing to say and i'"
  },
  {
    "code": "def _get_vrf_name(self, ri):\n        router_id = ri.router_name()[:self.DEV_NAME_LEN]\n        is_multi_region_enabled = cfg.CONF.multi_region.enable_multi_region\n        if is_multi_region_enabled:\n            region_id = cfg.CONF.multi_region.region_id\n            vrf_name = \"%s-%s\" % (router_id, region_id)\n        else:\n            vrf_name = router_id\n        return vrf_name",
    "docstring": "overloaded method for generating a vrf_name that supports\n        region_id"
  },
  {
    "code": "def run(self):\n        pydocstyle.Error.explain = self.options['explain']\n        filename, source = load_file(self.filename)\n        for error in pydocstyle.PEP257Checker().check_source(source, filename):\n            if not hasattr(error, 'code') or ignore(error.code):\n                continue\n            lineno = error.line\n            offset = 0\n            explanation = error.explanation if pydocstyle.Error.explain else ''\n            text = '{0} {1}{2}'.format(error.code, error.message.split(': ', 1)[1], explanation)\n            yield lineno, offset, text, Main",
    "docstring": "Run analysis on a single file."
  },
  {
    "code": "def get_context_manager(self, default):\n        try:\n            self.stack.append(default)\n            yield default\n        finally:\n            if self.enforce_nesting:\n                if self.stack[-1] is not default:\n                    raise AssertionError(\n                        \"Nesting violated for default stack of %s objects\"\n                        % type(default))\n                self.stack.pop()\n            else:\n                self.stack.remove(default)",
    "docstring": "A context manager for manipulating a default stack."
  },
  {
    "code": "def list_sqs(region, filter_by_kwargs):\n    conn = boto.sqs.connect_to_region(region)\n    queues = conn.get_all_queues()\n    return lookup(queues, filter_by=filter_by_kwargs)",
    "docstring": "List all SQS Queues."
  },
  {
    "code": "def insert(self, index: int, item: object) -> None:\n        self._blueprints.insert(index, item)",
    "docstring": "The Abstract class `MutableSequence` leverages this insert method to\n        perform the `BlueprintGroup.append` operation.\n\n        :param index: Index to use for removing a new Blueprint item\n        :param item: New `Blueprint` object.\n        :return: None"
  },
  {
    "code": "def loaded(self, request, *args, **kwargs):\n        serializer = self.get_serializer(list(Pack.objects.all()),\n                                         many=True)\n        return Response(serializer.data)",
    "docstring": "Return a list of loaded Packs."
  },
  {
    "code": "def add_bucket(self, bucket, bucket_type=None):\n        if not riak.disable_list_exceptions:\n            raise riak.ListError()\n        self._input_mode = 'bucket'\n        if isinstance(bucket, riak.RiakBucket):\n            if bucket.bucket_type.is_default():\n                self._inputs = {'bucket': bucket.name}\n            else:\n                self._inputs = {'bucket': [bucket.bucket_type.name,\n                                           bucket.name]}\n        elif bucket_type is not None and bucket_type != \"default\":\n            self._inputs = {'bucket': [bucket_type, bucket]}\n        else:\n            self._inputs = {'bucket': bucket}\n        return self",
    "docstring": "Adds all keys in a bucket to the inputs.\n\n        :param bucket: the bucket\n        :type bucket: string\n        :param bucket_type: Optional name of a bucket type\n        :type bucket_type: string, None\n        :rtype: :class:`RiakMapReduce`"
  },
  {
    "code": "def get_summary(self, dataset_number=None, use_dfsummary_made=False):\n        dataset_number = self._validate_dataset_number(dataset_number)\n        if dataset_number is None:\n            self._report_empty_dataset()\n            return None\n        test = self.get_dataset(dataset_number)\n        if use_dfsummary_made:\n            dfsummary_made = test.dfsummary_made\n        else:\n            dfsummary_made = True\n        if not dfsummary_made:\n            warnings.warn(\"Summary is not made yet\")\n            return None\n        else:\n            self.logger.info(\"returning datasets[test_no].dfsummary\")\n            return test.dfsummary",
    "docstring": "Retrieve summary returned as a pandas DataFrame."
  },
  {
    "code": "def load_config(self, config):\n        self.config = copy_config(config, self.mutable_config_keys)\n        if 'cookiejar_cookies' in config['state']:\n            self.cookies = CookieManager.from_cookie_list(\n                config['state']['cookiejar_cookies'])",
    "docstring": "Configure grab instance with external config object."
  },
  {
    "code": "def addDtdEntity(self, name, type, ExternalID, SystemID, content):\n        ret = libxml2mod.xmlAddDtdEntity(self._o, name, type, ExternalID, SystemID, content)\n        if ret is None:raise treeError('xmlAddDtdEntity() failed')\n        __tmp = xmlEntity(_obj=ret)\n        return __tmp",
    "docstring": "Register a new entity for this document DTD external subset."
  },
  {
    "code": "def loadmat(path):\n    r\n    data = pkgutil.get_data('pygsp', 'data/' + path + '.mat')\n    data = io.BytesIO(data)\n    return scipy.io.loadmat(data)",
    "docstring": "r\"\"\"\n    Load a matlab data file.\n\n    Parameters\n    ----------\n    path : string\n        Path to the mat file from the data folder, without the .mat extension.\n\n    Returns\n    -------\n    data : dict\n        dictionary with variable names as keys, and loaded matrices as\n        values.\n\n    Examples\n    --------\n    >>> from pygsp import utils\n    >>> data = utils.loadmat('pointclouds/bunny')\n    >>> data['bunny'].shape\n    (2503, 3)"
  },
  {
    "code": "def resolve_reference(target_reference, project):\n    assert isinstance(target_reference, basestring)\n    assert isinstance(project, ProjectTarget)\n    split = _re_separate_target_from_properties.match (target_reference)\n    if not split:\n        raise BaseException (\"Invalid reference: '%s'\" % target_reference)\n    id = split.group (1)\n    sproperties = []\n    if split.group (3):\n        sproperties = property.create_from_strings(feature.split(split.group(3)))\n        sproperties = feature.expand_composites(sproperties)\n    target = project.find (id)\n    return (target, property_set.create(sproperties))",
    "docstring": "Given a target_reference, made in context of 'project',\n    returns the AbstractTarget instance that is referred to, as well\n    as properties explicitly specified for this reference."
  },
  {
    "code": "def handle_error(self, request, client_address):\n    del request\n    exc_info = sys.exc_info()\n    e = exc_info[1]\n    if isinstance(e, IOError) and e.errno == errno.EPIPE:\n      logger.warn('EPIPE caused by %s in HTTP serving' % str(client_address))\n    else:\n      logger.error('HTTP serving error', exc_info=exc_info)",
    "docstring": "Override to get rid of noisy EPIPE errors."
  },
  {
    "code": "def make_association_id(definedby, sub, pred, obj, attributes=None):\n        items_to_hash = [definedby, sub, pred, obj]\n        if attributes is not None and len(attributes) > 0:\n            items_to_hash += attributes\n        items_to_hash = [x for x in items_to_hash if x is not None]\n        assoc_id = ':'.join(('MONARCH', GraphUtils.digest_id('+'.join(items_to_hash))))\n        assert assoc_id is not None\n        return assoc_id",
    "docstring": "A method to create unique identifiers for OBAN-style associations,\n        based on all the parts of the association\n        If any of the items is empty or None, it will convert it to blank.\n        It effectively digests the  string of concatonated values.\n        Subclasses of Assoc can submit an additional array of attributes\n        that will be appeded to the ID.\n\n        Note this is equivalent to a RDF blank node\n\n        :param definedby: The (data) resource that provided the annotation\n        :param subject:\n        :param predicate:\n        :param object:\n        :param attributes:\n\n        :return:"
  },
  {
    "code": "def copy_selected_sources(cls, roi, source_names):\n        roi_new = cls.make_roi()\n        for source_name in source_names:\n            try:\n                src_cp = roi.copy_source(source_name)\n            except Exception:\n                continue\n            roi_new.load_source(src_cp, build_index=False)\n        return roi_new",
    "docstring": "Build and return a `fermipy.roi_model.ROIModel` object\n        by copying selected sources from another such object"
  },
  {
    "code": "def www_authenticate(self):\n        def on_update(www_auth):\n            if not www_auth and 'www-authenticate' in self.headers:\n                del self.headers['www-authenticate']\n            elif www_auth:\n                self.headers['WWW-Authenticate'] = www_auth.to_header()\n        header = self.headers.get('www-authenticate')\n        return parse_www_authenticate_header(header, on_update)",
    "docstring": "The `WWW-Authenticate` header in a parsed form."
  },
  {
    "code": "def torch_equals_ignore_index(tensor, tensor_other, ignore_index=None):\n    if ignore_index is not None:\n        assert tensor.size() == tensor_other.size()\n        mask_arr = tensor.ne(ignore_index)\n        tensor = tensor.masked_select(mask_arr)\n        tensor_other = tensor_other.masked_select(mask_arr)\n    return torch.equal(tensor, tensor_other)",
    "docstring": "Compute ``torch.equal`` with the optional mask parameter.\n\n    Args:\n        ignore_index (int, optional): Specifies a ``tensor`` index that is ignored.\n\n    Returns:\n        (bool) Returns ``True`` if target and prediction are equal."
  },
  {
    "code": "def gen_pdf(rst_content, style_text, header=None, footer=FOOTER):\n    out_file_obj = StringIO()\n    with NamedTemporaryFile() as f:\n        f.write(style_text)\n        f.flush()\n        pdf = _init_pdf(f.name, header, footer)\n    pdf.createPdf(text=rst_content, output=out_file_obj, compressed=True)\n    out_file_obj.seek(0)\n    return out_file_obj",
    "docstring": "Create PDF file from `rst_content` using `style_text` as style.\n\n    Optinally, add `header` or `footer`.\n\n    Args:\n        rst_content (str): Content of the PDF file in restructured text markup.\n        style_text (str): Style for the :mod:`rst2pdf` module.\n        header (str, default None): Header which will be rendered to each page.\n        footer (str, default FOOTER): Footer, which will be rendered to each\n               page. See :attr:`FOOTER` for details.\n\n    Returns:\n        obj: StringIO file instance containing PDF file."
  },
  {
    "code": "def raw_role_mentions(self):\n        return [int(x) for x in re.findall(r'<@&([0-9]+)>', self.content)]",
    "docstring": "A property that returns an array of role IDs matched with\n        the syntax of <@&role_id> in the message content."
  },
  {
    "code": "def start_request(self, headers, *, end_stream=False):\n        yield from _wait_for_events(self._resumed, self._stream_creatable)\n        stream_id = self._conn.get_next_available_stream_id()\n        self._priority.insert_stream(stream_id)\n        self._priority.block(stream_id)\n        self._conn.send_headers(stream_id, headers, end_stream=end_stream)\n        self._flush()\n        return stream_id",
    "docstring": "Start a request by sending given headers on a new stream, and return\n        the ID of the new stream.\n\n        This may block until the underlying transport becomes writable, and\n        the number of concurrent outbound requests (open outbound streams) is\n        less than the value of peer config MAX_CONCURRENT_STREAMS.\n\n        The completion of the call to this method does not mean the request is\n        successfully delivered - data is only correctly stored in a buffer to\n        be sent. There's no guarantee it is truly delivered.\n\n        :param headers: A list of key-value tuples as headers.\n        :param end_stream: To send a request without body, set `end_stream` to\n                           `True` (default `False`).\n        :return: Stream ID as a integer, used for further communication."
  },
  {
    "code": "def send_os_command(self, os_command_text, is_priority=False):\n        body = {'is-priority': is_priority,\n                'operating-system-command-text': os_command_text}\n        self.manager.session.post(\n            self.uri + '/operations/send-os-cmd', body)",
    "docstring": "Send a command to the operating system running in this partition.\n\n        Parameters:\n\n          os_command_text (string): The text of the operating system command.\n\n          is_priority (bool):\n            Boolean controlling whether this is a priority operating system\n            command, as follows:\n\n            * If `True`, this message is treated as a priority operating\n              system command.\n\n            * If `False`, this message is not treated as a priority\n              operating system command. The default.\n\n        Returns:\n\n          None\n\n        Raises:\n\n          :exc:`~zhmcclient.HTTPError`\n          :exc:`~zhmcclient.ParseError`\n          :exc:`~zhmcclient.AuthError`\n          :exc:`~zhmcclient.ConnectionError`"
  },
  {
    "code": "def end_day_to_datetime(end_day, config):\n    day_start_time = config['day_start']\n    day_end_time = get_day_end(config)\n    if day_start_time == datetime.time(0, 0, 0):\n        end = datetime.datetime.combine(end_day, day_end_time)\n    else:\n        end = datetime.datetime.combine(end_day, day_end_time) + datetime.timedelta(days=1)\n    return end",
    "docstring": "Convert a given end day to its proper datetime.\n\n    This is non trivial because of variable ``day_start``. We want to make sure\n    that even if an 'end day' is specified the actual point in time may reach into the following\n    day.\n\n    Args:\n        end (datetime.date): Raw end date that is to be adjusted.\n        config: Controller config containing information on when a workday starts.\n\n    Returns:\n        datetime.datetime: The endday as a adjusted datetime object.\n\n    Example:\n        Given a ``day_start`` of ``5:30`` and end date of ``2015-04-01`` we actually want to\n        consider even points in time up to ``2015-04-02 5:29``. That is to represent that a\n        *work day*\n        does not match *calendar days*.\n\n    Note:\n        An alternative implementation for the similar problem in legacy hamster:\n            ``hamster.storage.db.Storage.__get_todays_facts``."
  },
  {
    "code": "def insert_check(self, index, check_item):\n        self.checks.insert(index, check_item)\n        for other in self.others:\n            other.insert_check(index, check_item)",
    "docstring": "Inserts a check universally."
  },
  {
    "code": "def attach(self, num_name, write=0):\n        mode = write and 'w' or 'r'\n        if isinstance(num_name, str):\n            num = self.find(num_name)\n        else:\n            num = num_name\n        vd = _C.VSattach(self._hdf_inst._id, num, mode)\n        if vd < 0:\n            _checkErr('attach', vd, 'cannot attach vdata')\n        return VD(self, vd)",
    "docstring": "Locate an existing vdata or create a new vdata in the HDF file,\n        returning a VD instance.\n\n        Args::\n\n          num_name  Name or reference number of the vdata. An existing vdata\n                    can be specified either through its reference number or\n                    its name. Use -1 to create a new vdata.\n                    Note that uniqueness is not imposed on vdatas names,\n                    whereas refnums are guaranteed to be unique. Thus\n                    knowledge of its reference number may be the only way\n                    to get at a wanted vdata.\n\n          write     Set to 0 to open the vdata in read-only mode,\n                    set to 1 to open it in write mode\n\n\n        Returns::\n\n          VD instance representing the vdata\n\n        C library equivalent : VSattach\n\n        After creating a new vdata (num_name == -1), fields must be\n        defined using method fdefine() of the VD instance, and those\n        fields must be allocated to the vdata with method setfields().\n        Same results can be achieved, but more simply, by calling the\n        create() method of the VS instance."
  },
  {
    "code": "def get_posts(self) -> Iterator[Post]:\n        self._obtain_metadata()\n        yield from (Post(self._context, node, self) for node in\n                    self._context.graphql_node_list(\"472f257a40c653c64c666ce877d59d2b\",\n                                                    {'id': self.userid},\n                                                    'https://www.instagram.com/{0}/'.format(self.username),\n                                                    lambda d: d['data']['user']['edge_owner_to_timeline_media'],\n                                                    self._rhx_gis,\n                                                    self._metadata('edge_owner_to_timeline_media')))",
    "docstring": "Retrieve all posts from a profile."
  },
  {
    "code": "def release_references(self, keys):\n        keys = set(self.referenced_by) & set(keys)\n        for key in keys:\n            self.referenced_by.pop(key)",
    "docstring": "Non-recursively indicate that an iterable of _ReferenceKey no longer\n        exist. Unknown keys are ignored.\n\n        :param Iterable[_ReferenceKey] keys: The keys to drop."
  },
  {
    "code": "def _create_auth(team, timeout=None):\n    url = get_registry_url(team)\n    contents = _load_auth()\n    auth = contents.get(url)\n    if auth is not None:\n        if auth['expires_at'] < time.time() + 60:\n            try:\n                auth = _update_auth(team, auth['refresh_token'], timeout)\n            except CommandException as ex:\n                raise CommandException(\n                    \"Failed to update the access token (%s). Run `quilt login%s` again.\" %\n                    (ex, ' ' + team if team else '')\n                )\n            contents[url] = auth\n            _save_auth(contents)\n    return auth",
    "docstring": "Reads the credentials, updates the access token if necessary, and returns it."
  },
  {
    "code": "def save(self, *args, **kwargs):\n        from organizations.exceptions import OrganizationMismatch\n        if self.organization_user.organization.pk != self.organization.pk:\n            raise OrganizationMismatch\n        else:\n            super(AbstractBaseOrganizationOwner, self).save(*args, **kwargs)",
    "docstring": "Extends the default save method by verifying that the chosen\n        organization user is associated with the organization.\n\n        Method validates against the primary key of the organization because\n        when validating an inherited model it may be checking an instance of\n        `Organization` against an instance of `CustomOrganization`. Mutli-table\n        inheritence means the database keys will be identical though."
  },
  {
    "code": "def load_module_from_name(dotted_name, path=None, use_sys=True):\n    return load_module_from_modpath(dotted_name.split(\".\"), path, use_sys)",
    "docstring": "Load a Python module from its name.\n\n    :type dotted_name: str\n    :param dotted_name: python name of a module or package\n\n    :type path: list or None\n    :param path:\n      optional list of path where the module or package should be\n      searched (use sys.path if nothing or None is given)\n\n    :type use_sys: bool\n    :param use_sys:\n      boolean indicating whether the sys.modules dictionary should be\n      used or not\n\n\n    :raise ImportError: if the module or package is not found\n\n    :rtype: module\n    :return: the loaded module"
  },
  {
    "code": "def cdate_range(start=None, end=None, periods=None, freq='C', tz=None,\n                normalize=True, name=None, closed=None, **kwargs):\n    warnings.warn(\"cdate_range is deprecated and will be removed in a future \"\n                  \"version, instead use pd.bdate_range(..., freq='{freq}')\"\n                  .format(freq=freq), FutureWarning, stacklevel=2)\n    if freq == 'C':\n        holidays = kwargs.pop('holidays', [])\n        weekmask = kwargs.pop('weekmask', 'Mon Tue Wed Thu Fri')\n        freq = CDay(holidays=holidays, weekmask=weekmask)\n    return date_range(start=start, end=end, periods=periods, freq=freq,\n                      tz=tz, normalize=normalize, name=name,\n                      closed=closed, **kwargs)",
    "docstring": "Return a fixed frequency DatetimeIndex, with CustomBusinessDay as the\n    default frequency\n\n    .. deprecated:: 0.21.0\n\n    Parameters\n    ----------\n    start : string or datetime-like, default None\n        Left bound for generating dates\n    end : string or datetime-like, default None\n        Right bound for generating dates\n    periods : integer, default None\n        Number of periods to generate\n    freq : string or DateOffset, default 'C' (CustomBusinessDay)\n        Frequency strings can have multiples, e.g. '5H'\n    tz : string, default None\n        Time zone name for returning localized DatetimeIndex, for example\n        Asia/Beijing\n    normalize : bool, default False\n        Normalize start/end dates to midnight before generating date range\n    name : string, default None\n        Name of the resulting DatetimeIndex\n    weekmask : string, Default 'Mon Tue Wed Thu Fri'\n        weekmask of valid business days, passed to ``numpy.busdaycalendar``\n    holidays : list\n        list/array of dates to exclude from the set of valid business days,\n        passed to ``numpy.busdaycalendar``\n    closed : string, default None\n        Make the interval closed with respect to the given frequency to\n        the 'left', 'right', or both sides (None)\n\n    Notes\n    -----\n    Of the three parameters: ``start``, ``end``, and ``periods``, exactly two\n    must be specified.\n\n    To learn more about the frequency strings, please see `this link\n    <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.\n\n    Returns\n    -------\n    rng : DatetimeIndex"
  },
  {
    "code": "def get_ordered_children(self):\n        ordered_keys = self.element.ordered_children if self.element.ordered_children is not None else []\n        children = [self.indexes.get(k, None) for k in ordered_keys]\n        return children",
    "docstring": "Return the list of children ordered according to the element structure\n\n        :return: a list of :class:`Element <hl7apy.core.Element>`"
  },
  {
    "code": "def _ExtractYandexSearchQuery(self, url):\n    if 'text=' not in url:\n      return None\n    _, _, line = url.partition('text=')\n    before_and, _, _ = line.partition('&')\n    if not before_and:\n      return None\n    yandex_search_url = before_and.split()[0]\n    return yandex_search_url.replace('+', ' ')",
    "docstring": "Extracts a search query from a Yandex search URL.\n\n    Yandex: https://www.yandex.com/search/?text=query\n\n    Args:\n      url (str): URL.\n\n    Returns:\n      str: search query or None if no query was found."
  },
  {
    "code": "def noise_new(\n    dim: int,\n    h: float = NOISE_DEFAULT_HURST,\n    l: float = NOISE_DEFAULT_LACUNARITY,\n    random: Optional[tcod.random.Random] = None,\n) -> tcod.noise.Noise:\n    return tcod.noise.Noise(dim, hurst=h, lacunarity=l, seed=random)",
    "docstring": "Return a new Noise instance.\n\n    Args:\n        dim (int): Number of dimensions.  From 1 to 4.\n        h (float): The hurst exponent.  Should be in the 0.0-1.0 range.\n        l (float): The noise lacunarity.\n        random (Optional[Random]): A Random instance, or None.\n\n    Returns:\n        Noise: The new Noise instance."
  },
  {
    "code": "def appendSpacePadding(str, blocksize=AES_blocksize):\n  'Pad with spaces'\n  pad_len = paddingLength(len(str), blocksize)\n  padding = '\\0'*pad_len\n  return str + padding",
    "docstring": "Pad with spaces"
  },
  {
    "code": "def get_bin_admin_session(self):\n        if not self.supports_bin_admin():\n            raise errors.Unimplemented()\n        return sessions.BinAdminSession(runtime=self._runtime)",
    "docstring": "Gets the bin administrative session for creating, updating and deleteing bins.\n\n        return: (osid.resource.BinAdminSession) - a ``BinAdminSession``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_bin_admin()`` is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_bin_admin()`` is ``true``.*"
  },
  {
    "code": "def cmd(self, *args, **kwargs):\n        args = list(args)\n        if self.socket_name:\n            args.insert(0, '-L{0}'.format(self.socket_name))\n        if self.socket_path:\n            args.insert(0, '-S{0}'.format(self.socket_path))\n        if self.config_file:\n            args.insert(0, '-f{0}'.format(self.config_file))\n        if self.colors:\n            if self.colors == 256:\n                args.insert(0, '-2')\n            elif self.colors == 88:\n                args.insert(0, '-8')\n            else:\n                raise ValueError('Server.colors must equal 88 or 256')\n        return tmux_cmd(*args, **kwargs)",
    "docstring": "Execute tmux command and return output.\n\n        Returns\n        -------\n        :class:`common.tmux_cmd`\n\n        Notes\n        -----\n        .. versionchanged:: 0.8\n\n            Renamed from ``.tmux`` to ``.cmd``."
  },
  {
    "code": "def to_text(self):\n        message = ''\n        last_was_text = False\n        for m in self.message:\n            if last_was_text and not isinstance(m, Text):\n                message += '\\n'\n            message += m.to_text()\n            if isinstance(m, Text):\n                last_was_text = True\n            else:\n                message += '\\n'\n                last_was_text = False\n        return message",
    "docstring": "Render a MessageElement queue as plain text.\n\n        :returns: Plain text representation of the message.\n        :rtype: str"
  },
  {
    "code": "def _clear(self, wait):\n        i = 0\n        t1 = time.time()\n        for k in self.bucket.get_keys():\n            i += 1\n            self.bucket.get(k).delete()\n        print(\"\\nDELETION TOOK: %s\" % round(time.time() - t1, 2))\n        if wait:\n            while self._model_class.objects.count():\n                time.sleep(0.3)\n        return i",
    "docstring": "clear outs the all content of current bucket\n        only for development purposes"
  },
  {
    "code": "def send_to_contact(self, obj_id, contact_id):\n        response = self._client.session.post(\n            '{url}/{id}/send/contact/{contact_id}'.format(\n                url=self.endpoint_url, id=obj_id, contact_id=contact_id\n            )\n        )\n        return self.process_response(response)",
    "docstring": "Send email to a specific contact\n\n        :param obj_id: int\n        :param contact_id: int\n        :return: dict|str"
  },
  {
    "code": "def _get_representation_doc(self):\n        if not self.representation:\n            return 'N/A'\n        fields = {}\n        for name, field in self.representation.fields.items():\n            fields[name] = self._get_field_doc(field)\n        return fields",
    "docstring": "Return documentation for the representation of the resource."
  },
  {
    "code": "def root(self):\n        ret = self\n        while hasattr(ret, 'parent') and ret.parent:\n            ret = ret.parent\n        return ret if isinstance(ret, SchemaABC) else None",
    "docstring": "Reference to the `Schema` that this field belongs to even if it is buried in a `List`.\n        Return `None` for unbound fields."
  },
  {
    "code": "def get_event_list(config):\n    eventinstances = session_request(\n        config.session.post, device_event_url.format(\n            proto=config.web_proto, host=config.host, port=config.port),\n        auth=config.session.auth, headers=headers, data=request_xml)\n    raw_event_list = _prepare_event(eventinstances)\n    event_list = {}\n    for entry in MAP + METAMAP:\n        instance = raw_event_list\n        try:\n            for item in sum(entry[MAP_BASE].values(), []):\n                instance = instance[item]\n        except KeyError:\n            continue\n        event_list[entry[MAP_TYPE]] = instance\n    return event_list",
    "docstring": "Get a dict of supported events from device."
  },
  {
    "code": "def next(self):\n        msg = cr.Message()\n        msg.type = cr.NEXT\n        self.send_message(msg)",
    "docstring": "Sends a \"next\" command to the player."
  },
  {
    "code": "def regularization(variables, regtype, regcoef, name=\"regularization\"):\n        with tf.name_scope(name):\n            if regtype != 'none':\n                regs = tf.constant(0.0)\n                for v in variables:\n                    if regtype == 'l2':\n                        regs = tf.add(regs, tf.nn.l2_loss(v))\n                    elif regtype == 'l1':\n                        regs = tf.add(regs, tf.reduce_sum(tf.abs(v)))\n                return tf.multiply(regcoef, regs)\n            else:\n                return None",
    "docstring": "Compute the regularization tensor.\n\n        Parameters\n        ----------\n\n        variables : list of tf.Variable\n            List of model variables.\n\n        regtype : str\n            Type of regularization. Can be [\"none\", \"l1\", \"l2\"]\n\n        regcoef : float,\n            Regularization coefficient.\n\n        name : str, optional (default = \"regularization\")\n            Name for the regularization op.\n\n        Returns\n        -------\n\n        tf.Tensor : Regularization tensor."
  },
  {
    "code": "def base64_decodefile(instr, outfile):\n    r\n    encoded_f = StringIO(instr)\n    with salt.utils.files.fopen(outfile, 'wb') as f:\n        base64.decode(encoded_f, f)\n    return True",
    "docstring": "r'''\n    Decode a base64-encoded string and write the result to a file\n\n    .. versionadded:: 2016.3.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' hashutil.base64_decodefile instr='Z2V0IHNhbHRlZAo=' outfile='/path/to/binary_file'"
  },
  {
    "code": "def biLSTM(f_lstm, b_lstm, inputs, batch_size=None, dropout_x=0., dropout_h=0.):\n    for f, b in zip(f_lstm, b_lstm):\n        inputs = nd.Dropout(inputs, dropout_x, axes=[0])\n        fo, fs = f.unroll(length=inputs.shape[0], inputs=inputs, layout='TNC', merge_outputs=True)\n        bo, bs = b.unroll(length=inputs.shape[0], inputs=inputs.flip(axis=0), layout='TNC', merge_outputs=True)\n        f.reset(), b.reset()\n        inputs = nd.concat(fo, bo.flip(axis=0), dim=2)\n    return inputs",
    "docstring": "Feature extraction through BiLSTM\n\n    Parameters\n    ----------\n    f_lstm : VariationalDropoutCell\n        Forward cell\n    b_lstm : VariationalDropoutCell\n        Backward cell\n    inputs : NDArray\n        seq_len x batch_size\n    dropout_x : float\n        Variational dropout on inputs\n    dropout_h :\n        Not used\n\n    Returns\n    -------\n    outputs : NDArray\n        Outputs of BiLSTM layers, seq_len x 2 hidden_dims x batch_size"
  },
  {
    "code": "def run_all_evals(models, treebanks, out_file, check_parse, print_freq_tasks):\n    print_header = True\n    for tb_lang, treebank_list in treebanks.items():\n        print()\n        print(\"Language\", tb_lang)\n        for text_path in treebank_list:\n            print(\" Evaluating on\", text_path)\n            gold_path = text_path.parent / (text_path.stem + '.conllu')\n            print(\"  Gold data from \", gold_path)\n            try:\n                with gold_path.open(mode='r', encoding='utf-8') as gold_file:\n                    gold_ud = conll17_ud_eval.load_conllu(gold_file)\n                for nlp, nlp_loading_time, nlp_name in models[tb_lang]:\n                    try:\n                        print(\"   Benchmarking\", nlp_name)\n                        tmp_output_path = text_path.parent / str('tmp_' + nlp_name + '.conllu')\n                        run_single_eval(nlp, nlp_loading_time, nlp_name, text_path, gold_ud, tmp_output_path, out_file,\n                                        print_header, check_parse, print_freq_tasks)\n                        print_header = False\n                    except Exception as e:\n                        print(\"    Ran into trouble: \", str(e))\n            except Exception as e:\n                print(\"   Ran into trouble: \", str(e))",
    "docstring": "Run an evaluation for each language with its specified models and treebanks"
  },
  {
    "code": "def init_shell(self):\n        self.shell = PlayerTerminalInteractiveShell.instance(\n            commands=self.commands,\n            speed=self.speed,\n            parent=self,\n            display_banner=False,\n            profile_dir=self.profile_dir,\n            ipython_dir=self.ipython_dir,\n            user_ns=self.user_ns,\n        )\n        self.shell.configurables.append(self)",
    "docstring": "initialize the InteractiveShell instance"
  },
  {
    "code": "def set_evaluation_parameter(self, parameter_name, parameter_value):\n        if 'evaluation_parameters' not in self._expectations_config:\n            self._expectations_config['evaluation_parameters'] = {}\n        self._expectations_config['evaluation_parameters'].update(\n            {parameter_name: parameter_value})",
    "docstring": "Provide a value to be stored in the data_asset evaluation_parameters object and used to evaluate\n        parameterized expectations.\n\n        Args:\n            parameter_name (string): The name of the kwarg to be replaced at evaluation time\n            parameter_value (any): The value to be used"
  },
  {
    "code": "def buffer_read(self, frames=-1, dtype=None):\n        frames = self._check_frames(frames, fill_value=None)\n        ctype = self._check_dtype(dtype)\n        cdata = _ffi.new(ctype + '[]', frames * self.channels)\n        read_frames = self._cdata_io('read', cdata, ctype, frames)\n        assert read_frames == frames\n        return _ffi.buffer(cdata)",
    "docstring": "Read from the file and return data as buffer object.\n\n        Reads the given number of `frames` in the given data format\n        starting at the current read/write position.  This advances the\n        read/write position by the same number of frames.\n        By default, all frames from the current read/write position to\n        the end of the file are returned.\n        Use :meth:`.seek` to move the current read/write position.\n\n        Parameters\n        ----------\n        frames : int, optional\n            The number of frames to read. If `frames < 0`, the whole\n            rest of the file is read.\n        dtype : {'float64', 'float32', 'int32', 'int16'}\n            Audio data will be converted to the given data type.\n\n        Returns\n        -------\n        buffer\n            A buffer containing the read data.\n\n        See Also\n        --------\n        buffer_read_into, .read, buffer_write"
  },
  {
    "code": "def notify_slaves(self):\n        if self.disable_slave_notify is not None:\n            LOGGER.debug('Slave notifications disabled')\n            return False\n        if self.zone_data()['kind'] == 'Master':\n            response_code = self._put('/zones/' + self.domain + '/notify').status_code\n            if response_code == 200:\n                LOGGER.debug('Slave(s) notified')\n                return True\n            LOGGER.debug('Slave notification failed with code %i', response_code)\n        else:\n            LOGGER.debug('Zone type should be \\'Master\\' for slave notifications')\n        return False",
    "docstring": "Checks to see if slaves should be notified, and notifies them if needed"
  },
  {
    "code": "def project_sequence(s, permutation=None):\n    xs, ys = unzip([project_point(p, permutation=permutation) for p in s])\n    return xs, ys",
    "docstring": "Projects a point or sequence of points using `project_point` to lists xs, ys\n    for plotting with Matplotlib.\n\n    Parameters\n    ----------\n    s, Sequence-like\n        The sequence of points (3-tuples) to be projected.\n\n    Returns\n    -------\n    xs, ys: The sequence of projected points in coordinates as two lists"
  },
  {
    "code": "def _batch_norm_op(self, input_batch, mean, variance, use_batch_stats,\n                     stat_dtype):\n    if self._fused:\n      batch_norm_op, mean, variance = self._fused_batch_norm_op(\n          input_batch,\n          self._moving_mean, self._moving_variance, use_batch_stats)\n    else:\n      batch_norm_op = tf.nn.batch_normalization(\n          input_batch,\n          mean,\n          variance,\n          self._beta,\n          self._gamma,\n          self._eps,\n          name=\"batch_norm\")\n      if input_batch.dtype.base_dtype != stat_dtype:\n        mean = tf.cast(mean, stat_dtype)\n        variance = tf.cast(variance, stat_dtype)\n    return batch_norm_op, mean, variance",
    "docstring": "Creates a batch normalization op.\n\n    It uses the tf.nn.batch_normalization op by default and the\n    tf.nn.fused_batch_norm op to support fused batch normalization.\n\n    Args:\n      input_batch: A input Tensor of arbitrary dimension.\n      mean: A mean tensor, of the same dtype as `input_batch`.\n      variance: A variance tensor, of the same dtype as `input_batch`.\n      use_batch_stats: A bool value that indicates whether the operation should\n         use the batch statistics.\n      stat_dtype: TensorFlow datatype used for the moving mean and variance.\n\n    Returns:\n      A batch normalization operation.\n      The current mean tensor, of datatype `stat_dtype`.\n      The current variance tensor, of datatype `stat_dtype`."
  },
  {
    "code": "def close(self):\n        if not self.__closed:\n            self.__closed = True\n            self.pool.return_socket(self.sock)\n            self.sock, self.pool = None, None",
    "docstring": "Return this instance's socket to the connection pool."
  },
  {
    "code": "def _parse_hostname(self):\n        value = 'localhost'\n        match = re.search(r'^hostname ([^\\s]+)$', self.config, re.M)\n        if match:\n            value = match.group(1)\n        return dict(hostname=value)",
    "docstring": "Parses the global config and returns the hostname value\n\n        Returns:\n            dict: The configured value for hostname.  The returned dict\n                object is intended to be merged into the resource dict"
  },
  {
    "code": "def resolve_and_build(self):\n        pdebug(\"resolving and building task '%s'\" % self.name,\n                groups=[\"build_task\"])\n        indent_text(indent=\"++2\")\n        toret = self.build(**self.resolve_dependencies())\n        indent_text(indent=\"--2\")\n        return toret",
    "docstring": "resolves the dependencies of this build target and builds it"
  },
  {
    "code": "def filter_metadata(self, key):\n        filtered = [field[key] for field in self.metadata if key in field]\n        if len(filtered) == 0:\n            raise KeyError(\"Key not found in metadata\")\n        return filtered",
    "docstring": "Return a list of values for the metadata key from each field\n        of the project's metadata.\n\n        Parameters\n        ----------\n        key: str\n            A known key in the metadata structure\n\n        Returns\n        -------\n        filtered :\n            attribute list from each field"
  },
  {
    "code": "def pyobjc_method_signature(signature_str):\n        _objc_so.PyObjCMethodSignature_WithMetaData.restype = ctypes.py_object\n        return _objc_so.PyObjCMethodSignature_WithMetaData(ctypes.create_string_buffer(signature_str), None, False)",
    "docstring": "Return a PyObjCMethodSignature object for given signature string.\n\n        :param signature_str: A byte string containing the type encoding for the method signature\n        :return: A method signature object, assignable to attributes like __block_signature__\n        :rtype: <type objc._method_signature>"
  },
  {
    "code": "def disconnect_session(session_id):\n    try:\n        win32ts.WTSDisconnectSession(win32ts.WTS_CURRENT_SERVER_HANDLE, session_id, True)\n    except PyWinError as error:\n        _LOG.error('Error calling WTSDisconnectSession: %s', error)\n        return False\n    return True",
    "docstring": "Disconnect a session.\n\n    .. versionadded:: 2016.11.0\n\n    :param session_id: The numeric Id of the session.\n    :return: A boolean representing whether the disconnect succeeded.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rdp.disconnect_session session_id\n\n        salt '*' rdp.disconnect_session 99"
  },
  {
    "code": "def page(self, start_date=values.unset, end_date=values.unset,\n             identity=values.unset, tag=values.unset, page_token=values.unset,\n             page_number=values.unset, page_size=values.unset):\n        params = values.of({\n            'StartDate': serialize.iso8601_date(start_date),\n            'EndDate': serialize.iso8601_date(end_date),\n            'Identity': serialize.map(identity, lambda e: e),\n            'Tag': serialize.map(tag, lambda e: e),\n            'PageToken': page_token,\n            'Page': page_number,\n            'PageSize': page_size,\n        })\n        response = self._version.page(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return BindingPage(self._version, response, self._solution)",
    "docstring": "Retrieve a single page of BindingInstance records from the API.\n        Request is executed immediately\n\n        :param date start_date: Only include usage that has occurred on or after this date\n        :param date end_date: Only include usage that occurred on or before this date\n        :param unicode identity: The `identity` value of the resources to read\n        :param unicode tag: Only list Bindings that have all of the specified Tags\n        :param str page_token: PageToken provided by the API\n        :param int page_number: Page Number, this value is simply for client state\n        :param int page_size: Number of records to return, defaults to 50\n\n        :returns: Page of BindingInstance\n        :rtype: twilio.rest.notify.v1.service.binding.BindingPage"
  },
  {
    "code": "def without_extra_phrases(self):\n        name = re.sub(r'\\s*\\([^)]*\\)?\\s*$', '', self.name)\n        name = re.sub(r'(?i)\\s* formerly.*$', '', name)\n        name = re.sub(r'(?i)\\s*and its affiliates$', '', name)\n        name = re.sub(r'\\bet al\\b', '', name)\n        if \"-\" in name:\n            hyphen_parts = name.rsplit(\"-\", 1)\n            if len(hyphen_parts[1]) < len(hyphen_parts[0]) and re.search(r'(\\w{4,}|\\s+)$', hyphen_parts[0]) and not re.match(r'^([a-zA-Z]|[0-9]+)$', hyphen_parts[1]):\n                name = hyphen_parts[0].strip()\n        return name",
    "docstring": "Removes parenthethical and dashed phrases"
  },
  {
    "code": "def from_swagger(cls, pclass_for_definition, name, definition):\n        return cls(\n            name=name,\n            doc=definition.get(u\"description\", name),\n            attributes=cls._attributes_for_definition(\n                pclass_for_definition,\n                definition,\n            ),\n        )",
    "docstring": "Create a new ``_ClassModel`` from a single Swagger definition.\n\n        :param pclass_for_definition: A callable like\n            ``Swagger.pclass_for_definition`` which can be used to resolve\n            type references encountered in the definition.\n\n        :param unicode name: The name of the definition.\n\n        :param definition: The Swagger definition to model.  This will be a\n            value like the one found at ``spec[\"definitions\"][name]``.\n\n        :return: A new model for the given definition."
  },
  {
    "code": "def refresh_db(jail=None, chroot=None, root=None, force=False, **kwargs):\n    salt.utils.pkg.clear_rtag(__opts__)\n    cmd = _pkg(jail, chroot, root)\n    cmd.append('update')\n    if force:\n        cmd.append('-f')\n    return __salt__['cmd.retcode'](cmd, python_shell=False) == 0",
    "docstring": "Refresh PACKAGESITE contents\n\n    .. note::\n\n        This function can accessed using ``pkg.update`` in addition to\n        ``pkg.refresh_db``, to more closely match the CLI usage of ``pkg(8)``.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' pkg.refresh_db\n\n    jail\n        Refresh the pkg database within the specified jail\n\n    chroot\n        Refresh the pkg database within the specified chroot (ignored if\n        ``jail`` is specified)\n\n    root\n        Refresh the pkg database within the specified root (ignored if\n        ``jail`` is specified)\n\n    force\n        Force a full download of the repository catalog without regard to the\n        respective ages of the local and remote copies of the catalog.\n\n        CLI Example:\n\n        .. code-block:: bash\n\n            salt '*' pkg.refresh_db force=True"
  },
  {
    "code": "def get_trace(self):\n        tblist = traceback.extract_tb(sys.exc_info()[2])\n        tblist = [item for item in tblist if ('pexpect/__init__' not in item[0])\n                                           and ('pexpect/expect' not in item[0])]\n        tblist = traceback.format_list(tblist)\n        return ''.join(tblist)",
    "docstring": "This returns an abbreviated stack trace with lines that only concern\n        the caller. In other words, the stack trace inside the Pexpect module\n        is not included."
  },
  {
    "code": "async def push_transaction_async(self):\n        await self.connect_async(loop=self.loop)\n        depth = self.transaction_depth_async()\n        if not depth:\n            conn = await self._async_conn.acquire()\n            self._task_data.set('conn', conn)\n        self._task_data.set('depth', depth + 1)",
    "docstring": "Increment async transaction depth."
  },
  {
    "code": "def pretty_flags(flags):\n    names = []\n    result = \"0x%08x\" % flags\n    for i in range(32):\n        flag = 1 << i\n        if flags & flag:\n            names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag)))\n            flags ^= flag\n            if not flags:\n                break\n    else:\n        names.append(hex(flags))\n    names.reverse()\n    return \"%s (%s)\" % (result, \" | \".join(names))",
    "docstring": "Return pretty representation of code flags."
  },
  {
    "code": "def addSourceGroup(self, sourceGroupUri, weight):\n        assert isinstance(weight, (float, int)), \"weight value has to be a positive or negative integer\"\n        self.topicPage[\"sourceGroups\"].append({\"uri\": sourceGroupUri, \"wgt\": weight})",
    "docstring": "add a list of relevant sources by specifying a whole source group to the topic page\n        @param sourceGroupUri: uri of the source group to add\n        @param weight: importance of the provided list of sources (typically in range 1 - 50)"
  },
  {
    "code": "def output_best_scores(self, best_epoch_str: str) -> None:\n        BEST_SCORES_FILENAME = \"best_scores.txt\"\n        with open(os.path.join(self.exp_dir, BEST_SCORES_FILENAME),\n                  \"w\", encoding=ENCODING) as best_f:\n            print(best_epoch_str, file=best_f, flush=True)",
    "docstring": "Output best scores to the filesystem"
  },
  {
    "code": "def read_envvar_file(name, extension):\n    envvar_file = environ.get('{}_config_file'.format(name).upper())\n    if envvar_file:\n        return loadf(envvar_file)\n    else:\n        return NotConfigured",
    "docstring": "Read values from a file provided as a environment variable\n    ``NAME_CONFIG_FILE``.\n\n    :param name: environment variable prefix to look for (without the\n        ``_CONFIG_FILE``)\n    :param extension: *(unused)*\n    :return: a `.Configuration`, possibly `.NotConfigured`"
  },
  {
    "code": "def count_items(self):\n        soup_items = self.soup.findAll('item')\n        full_soup_items = self.full_soup.findAll('item')\n        return len(soup_items), len(full_soup_items)",
    "docstring": "Counts Items in full_soup and soup. For debugging"
  },
  {
    "code": "def retry_unpaid_invoices(self):\n\t\tself._sync_invoices()\n\t\tfor invoice in self.invoices.filter(paid=False, closed=False):\n\t\t\ttry:\n\t\t\t\tinvoice.retry()\n\t\t\texcept InvalidRequestError as exc:\n\t\t\t\tif str(exc) != \"Invoice is already paid\":\n\t\t\t\t\traise",
    "docstring": "Attempt to retry collecting payment on the customer's unpaid invoices."
  },
  {
    "code": "def _safe_str_cmp(a, b):\n    if len(a) != len(b):\n        return False\n    rv = 0\n    for x, y in zip(a, b):\n        rv |= ord(x) ^ ord(y)\n    return rv == 0",
    "docstring": "Internal function to efficiently iterate over the hashes\n    \n    Regular string compare will bail at the earliest opportunity\n    which allows timing attacks"
  },
  {
    "code": "def cause_repertoire(self, mechanism, purview):\n        return self.repertoire(Direction.CAUSE, mechanism, purview)",
    "docstring": "Return the cause repertoire."
  },
  {
    "code": "def get_context_data(self, **kwargs):\n        context = {'obj': self.object }\n        if 'queryset' in kwargs:\n            context['conf_msg'] = self.get_confirmation_message(kwargs['queryset'])\n        context.update(kwargs)\n        return context",
    "docstring": "Hook for adding arguments to the context."
  },
  {
    "code": "def _load_forms_and_lemmas(self):\r\n\t\trel_path = os.path.join(CLTK_DATA_DIR,\r\n                                'old_english',\r\n                                'model',\r\n                                'old_english_models_cltk',\r\n                                'data',\r\n                                'oe.lemmas')\r\n\t\tpath = os.path.expanduser(rel_path)\r\n\t\tself.lemma_dict = {}\r\n\t\twith open(path, 'r') as infile:\r\n\t\t\tlines = infile.read().splitlines()\r\n\t\t\tfor line in lines:\r\n\t\t\t\tforms = line.split('\\t')\r\n\t\t\t\tlemma = forms[0]\r\n\t\t\t\tfor form_seq in forms:\r\n\t\t\t\t\tindiv_forms = form_seq.split(',')\r\n\t\t\t\t\tfor form in indiv_forms:\r\n\t\t\t\t\t\tform = form.lower()\r\n\t\t\t\t\t\tlemma_list = self.lemma_dict.get(form, [])\r\n\t\t\t\t\t\tlemma_list.append(lemma)\r\n\t\t\t\t\t\tself.lemma_dict[form] = lemma_list\r\n\t\tfor form in self.lemma_dict.keys():\r\n\t\t\tself.lemma_dict[form] = list(set(self.lemma_dict[form]))",
    "docstring": "Load the dictionary of lemmas and forms from the OE models repository."
  },
  {
    "code": "def sliding_tensor(mv_time_series, width, step, order='F'):\n    D = mv_time_series.shape[1]\n    data = [sliding_window(mv_time_series[:, j], width, step, order) for j in range(D)]\n    return np.stack(data, axis=2)",
    "docstring": "segments multivariate time series with sliding window\n\n    Parameters\n    ----------\n    mv_time_series : array like shape [n_samples, n_variables]\n        multivariate time series or sequence\n    width : int > 0\n        segment width in samples\n    step : int > 0\n        stepsize for sliding in samples\n\n    Returns\n    -------\n    data : array like shape [n_segments, width, n_variables]\n        segmented multivariate time series data"
  },
  {
    "code": "def do_asg(self,args):\n        parser = CommandArgumentParser(\"asg\")\n        parser.add_argument(dest='asg',help='asg index or name');\n        args = vars(parser.parse_args(args))\n        print \"loading auto scaling group {}\".format(args['asg'])\n        try:\n            index = int(args['asg'])\n            asgSummary = self.wrappedStack['resourcesByTypeIndex']['AWS::AutoScaling::AutoScalingGroup'][index]\n        except:\n            asgSummary = self.wrappedStack['resourcesByTypeName']['AWS::AutoScaling::AutoScalingGroup'][args['asg']]\n        self.stackResource(asgSummary.stack_name,asgSummary.logical_id)",
    "docstring": "Go to the specified auto scaling group. asg -h for detailed help"
  },
  {
    "code": "def density_angle(rho0: Density, rho1: Density) -> bk.BKTensor:\n    return fubini_study_angle(rho0.vec, rho1.vec)",
    "docstring": "The Fubini-Study angle between density matrices"
  },
  {
    "code": "def auth_view(name, **kwargs):\n    ctx = Context(**kwargs)\n    ctx.execute_action('auth:group:view', **{\n        'storage': ctx.repo.create_secure_service('storage'),\n        'name': name,\n    })",
    "docstring": "Shows an authorization group's content."
  },
  {
    "code": "def transform_sparql_construct(rdf, construct_query):\n    logging.debug(\"performing SPARQL CONSTRUCT transformation\")\n    if construct_query[0] == '@':\n        construct_query = file(construct_query[1:]).read()\n    logging.debug(\"CONSTRUCT query: %s\", construct_query)\n    newgraph = Graph()\n    for triple in rdf.query(construct_query):\n        newgraph.add(triple)\n    return newgraph",
    "docstring": "Perform a SPARQL CONSTRUCT query on the RDF data and return a new graph."
  },
  {
    "code": "def send_webhook(config, payload):\n    try:\n        response = requests.post(\n            config['webhook_url'],\n            data=json.dumps(payload, cls=ModelJSONEncoder),\n            headers={config['api_key_header_name']: config['api_key']},\n        )\n    except Exception as e:\n        logger.warning('Unable to send webhook: ({1}) {2}'.format(\n            e.__class__.__name__,\n            e.message,\n        ))\n    else:\n        logger.debug('Webhook response: ({0}) {1}'.format(\n            response.status_code,\n            response.text,\n        ))",
    "docstring": "Sends a HTTP request to the configured server.\n\n    All exceptions are suppressed but emit a warning message in the log."
  },
  {
    "code": "def action(name, text, confirmation=None, icon=None, multiple=True, single=True):\n    def wrap(f):\n        f._action = (name, text, confirmation, icon, multiple, single)\n        return f\n    return wrap",
    "docstring": "Use this decorator to expose actions\n\n        :param name:\n            Action name\n        :param text:\n            Action text.\n        :param confirmation:\n            Confirmation text. If not provided, action will be executed\n            unconditionally.\n        :param icon:\n            Font Awesome icon name\n        :param multiple:\n            If true will display action on list view\n        :param single:\n            If true will display action on show view"
  },
  {
    "code": "def direction_to_nearest_place(feature, parent):\n    _ = feature, parent\n    layer = exposure_summary_layer()\n    if not layer:\n        return None\n    index = layer.fields().lookupField(\n        direction_field['field_name'])\n    if index < 0:\n        return None\n    feature = next(layer.getFeatures())\n    return feature[index]",
    "docstring": "If the impact layer has a distance field, it will return the direction\n    to the nearest place.\n\n    e.g. direction_to_nearest_place() -> NW"
  },
  {
    "code": "def dtw(x, y, dist=None):\n    x, y, dist = __prep_inputs(x, y, dist)\n    return __dtw(x, y, None, dist)",
    "docstring": "return the distance between 2 time series without approximation\n\n        Parameters\n        ----------\n        x : array_like\n            input array 1\n        y : array_like\n            input array 2\n        dist : function or int\n            The method for calculating the distance between x[i] and y[j]. If\n            dist is an int of value p > 0, then the p-norm will be used. If\n            dist is a function then dist(x[i], y[j]) will be used. If dist is\n            None then abs(x[i] - y[j]) will be used.\n\n        Returns\n        -------\n        distance : float\n            the approximate distance between the 2 time series\n        path : list\n            list of indexes for the inputs x and y\n\n        Examples\n        --------\n        >>> import numpy as np\n        >>> import fastdtw\n        >>> x = np.array([1, 2, 3, 4, 5], dtype='float')\n        >>> y = np.array([2, 3, 4], dtype='float')\n        >>> fastdtw.dtw(x, y)\n        (2.0, [(0, 0), (1, 0), (2, 1), (3, 2), (4, 2)])"
  },
  {
    "code": "def _flatten_list(x):\n    result = []\n    x = list(filter(None.__ne__, x))\n    for el in x:\n        x_is_iter = isinstance(x, collections.Iterable)\n        if x_is_iter and not isinstance(el, (str, tuple)):\n            result.extend(_flatten_list(el))\n        else:\n            result.append(el)\n    return result",
    "docstring": "Flatten an arbitrarily nested list into a new list.\n\n    This can be useful to select pandas DataFrame columns.\n\n    From https://stackoverflow.com/a/16176969/10581531\n\n    Examples\n    --------\n    >>> from pingouin.utils import _flatten_list\n    >>> x = ['X1', ['M1', 'M2'], 'Y1', ['Y2']]\n    >>> _flatten_list(x)\n    ['X1', 'M1', 'M2', 'Y1', 'Y2']\n\n    >>> x = ['Xaa', 'Xbb', 'Xcc']\n    >>> _flatten_list(x)\n    ['Xaa', 'Xbb', 'Xcc']"
  },
  {
    "code": "def reliability_curves(self, prob_thresholds):\n        all_rel_curves = {}\n        for model_name in self.model_names:\n            all_rel_curves[model_name] = {}\n            for size_threshold in self.size_thresholds:\n                all_rel_curves[model_name][size_threshold] = {}\n                for h, hour_window in enumerate(self.hour_windows):\n                    hour_range = (hour_window.start, hour_window.stop)\n                    all_rel_curves[model_name][size_threshold][hour_range] = \\\n                        DistributedReliability(prob_thresholds, 1)\n                    if self.obs_mask:\n                        all_rel_curves[model_name][size_threshold][hour_range].update(\n                            self.window_forecasts[model_name][size_threshold][h][\n                                self.window_obs[self.mask_variable][h] > 0],\n                            self.dilated_obs[size_threshold][h][self.window_obs[self.mask_variable][h] > 0]\n                        )\n                    else:\n                        all_rel_curves[model_name][size_threshold][hour_range].update(\n                            self.window_forecasts[model_name][size_threshold][h],\n                            self.dilated_obs[size_threshold][h]\n                        )\n        return all_rel_curves",
    "docstring": "Output reliability curves for each machine learning model, size threshold, and time window.\n\n        :param prob_thresholds:\n        :param dilation_radius:\n        :return:"
  },
  {
    "code": "def normalize_id(string):\n    if not isinstance(string, basestring):\n        fail(\"Type of argument must be string, found '{}'\"\n             .format(type(string)))\n    normalizer = getUtility(IIDNormalizer).normalize\n    return normalizer(string)",
    "docstring": "Normalize the id\n\n    :param string: A string to normalize\n    :type string: str\n    :returns: Normalized ID\n    :rtype: str"
  },
  {
    "code": "def _advance_params(self):\n        for p in ['x','y','direction']:\n            self.force_new_dynamic_value(p)\n        self.last_time = self.time_fn()",
    "docstring": "Explicitly generate new values for these parameters only\n        when appropriate."
  },
  {
    "code": "def create_river(self, river, river_name=None):\n        if isinstance(river, River):\n            body = river.serialize()\n            river_name = river.name\n        else:\n            body = river\n        return self._send_request('PUT', '/_river/%s/_meta' % river_name, body)",
    "docstring": "Create a river"
  },
  {
    "code": "def tmdb_search_movies(\n    api_key, title, year=None, adult=False, region=None, page=1, cache=True\n):\n    url = \"https://api.themoviedb.org/3/search/movie\"\n    try:\n        if year:\n            year = int(year)\n    except ValueError:\n        raise MapiProviderException(\"year must be numeric\")\n    parameters = {\n        \"api_key\": api_key,\n        \"query\": title,\n        \"page\": page,\n        \"include_adult\": adult,\n        \"region\": region,\n        \"year\": year,\n    }\n    status, content = _request_json(url, parameters, cache=cache)\n    if status == 401:\n        raise MapiProviderException(\"invalid API key\")\n    elif status != 200 or not any(content.keys()):\n        raise MapiNetworkException(\"TMDb down or unavailable?\")\n    elif status == 404 or status == 422 or not content.get(\"total_results\"):\n        raise MapiNotFoundException\n    return content",
    "docstring": "Search for movies using The Movie Database\n\n    Online docs: developers.themoviedb.org/3/search/search-movies"
  },
  {
    "code": "def rollback(self, path, pretend=False):\n        self._notes = []\n        migrations = self._repository.get_last()\n        if not migrations:\n            self._note('<info>Nothing to rollback.</info>')\n            return len(migrations)\n        for migration in migrations:\n            self._run_down(path, migration, pretend)\n        return len(migrations)",
    "docstring": "Rollback the last migration operation.\n\n        :param path: The path\n        :type path: str\n\n        :param pretend: Whether we execute the migrations as dry-run\n        :type pretend: bool\n\n        :rtype: int"
  },
  {
    "code": "def verify_time(self, now):\n        return now.time() >= self.start_time and now.time() <= self.end_time",
    "docstring": "Verify the time"
  },
  {
    "code": "def MultiOpenOrdered(self, urns, **kwargs):\n    precondition.AssertIterableType(urns, rdfvalue.RDFURN)\n    urn_filedescs = {}\n    for filedesc in self.MultiOpen(urns, **kwargs):\n      urn_filedescs[filedesc.urn] = filedesc\n    filedescs = []\n    for urn in urns:\n      try:\n        filedescs.append(urn_filedescs[urn])\n      except KeyError:\n        raise IOError(\"No associated AFF4 object for `%s`\" % urn)\n    return filedescs",
    "docstring": "Opens many URNs and returns handles in the same order.\n\n    `MultiOpen` can return file handles in arbitrary order. This makes it more\n    efficient and in most cases the order does not matter. However, there are\n    cases where order is important and this function should be used instead.\n\n    Args:\n      urns: A list of URNs to open.\n      **kwargs: Same keyword arguments as in `MultiOpen`.\n\n    Returns:\n      A list of file-like objects corresponding to the specified URNs.\n\n    Raises:\n      IOError: If one of the specified URNs does not correspond to the AFF4\n          object."
  },
  {
    "code": "def get_class_that_defined_method(meth):\n    if is_classmethod(meth):\n        return meth.__self__\n    if hasattr(meth, 'im_class'):\n        return meth.im_class\n    elif hasattr(meth, '__qualname__'):\n        try:\n            cls_names = meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0].split('.')\n            cls = inspect.getmodule(meth)\n            for cls_name in cls_names:\n                cls = getattr(cls, cls_name)\n            if isinstance(cls, type):\n                return cls\n        except AttributeError:\n            pass\n    raise ValueError(str(meth)+' is not a method.')",
    "docstring": "Determines the class owning the given method."
  },
  {
    "code": "def get_summary(self):\n        func_summaries = [f.get_summary() for f in self.functions]\n        modif_summaries = [f.get_summary() for f in self.modifiers]\n        return (self.name, [str(x) for x in self.inheritance], [str(x) for x in self.variables], func_summaries, modif_summaries)",
    "docstring": "Return the function summary\n\n        Returns:\n            (str, list, list, list, list): (name, inheritance, variables, fuction summaries, modifier summaries)"
  },
  {
    "code": "def toggle_standby(self, **kwargs):\n        trafficgroup = kwargs.pop('trafficgroup')\n        state = kwargs.pop('state')\n        if kwargs:\n            raise TypeError('Unexpected **kwargs: %r' % kwargs)\n        arguments = {'standby': state, 'traffic-group': trafficgroup}\n        return self.exec_cmd('run', **arguments)",
    "docstring": "Toggle the standby status of a traffic group.\n\n         WARNING: This method which used POST obtains json keys from the device\n         that are not available in the response to a GET against the same URI.\n\n         NOTE: This method method is deprecated and probably will be removed,\n               usage of exec_cmd is encouraged."
  },
  {
    "code": "def _per_file_event_handler(self):\n        file_event_handler = PatternMatchingEventHandler()\n        file_event_handler.on_created = self._on_file_created\n        file_event_handler.on_modified = self._on_file_modified\n        file_event_handler.on_moved = self._on_file_moved\n        file_event_handler._patterns = [\n            os.path.join(self._watch_dir, os.path.normpath('*'))]\n        file_event_handler._ignore_patterns = [\n            '*/.*',\n            '*.tmp',\n            os.path.join(self._run.dir, OUTPUT_FNAME)\n        ]\n        for glob in self._api.settings(\"ignore_globs\"):\n            file_event_handler._ignore_patterns.append(\n                os.path.join(self._run.dir, glob))\n        return file_event_handler",
    "docstring": "Create a Watchdog file event handler that does different things for every file"
  },
  {
    "code": "def set_status(self, trial, status):\n        trial.status = status\n        if status in [Trial.TERMINATED, Trial.ERROR]:\n            self.try_checkpoint_metadata(trial)",
    "docstring": "Sets status and checkpoints metadata if needed.\n\n        Only checkpoints metadata if trial status is a terminal condition.\n        PENDING, PAUSED, and RUNNING switches have checkpoints taken care of\n        in the TrialRunner.\n\n        Args:\n            trial (Trial): Trial to checkpoint.\n            status (Trial.status): Status to set trial to."
  },
  {
    "code": "def get_relations(self, database, schema):\n        schema = _lower(schema)\n        with self.lock:\n            results = [\n                r.inner for r in self.relations.values()\n                if (r.schema == _lower(schema) and\n                    r.database == _lower(database))\n            ]\n        if None in results:\n            dbt.exceptions.raise_cache_inconsistent(\n                'in get_relations, a None relation was found in the cache!'\n            )\n        return results",
    "docstring": "Case-insensitively yield all relations matching the given schema.\n\n        :param str schema: The case-insensitive schema name to list from.\n        :return List[BaseRelation]: The list of relations with the given\n            schema"
  },
  {
    "code": "def get_snapshot(nexus_url, repository, group_id, artifact_id, packaging, version, snapshot_version=None, target_dir='/tmp', target_file=None, classifier=None, username=None, password=None):\n    log.debug('======================== MODULE FUNCTION: nexus.get_snapshot(nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, version=%s, target_dir=%s, classifier=%s)',\n              nexus_url, repository, group_id, artifact_id, packaging, version, target_dir, classifier)\n    headers = {}\n    if username and password:\n        headers['Authorization'] = 'Basic {0}'.format(base64.encodestring('{0}:{1}'.format(username, password)).replace('\\n', ''))\n    snapshot_url, file_name = _get_snapshot_url(nexus_url=nexus_url, repository=repository, group_id=group_id, artifact_id=artifact_id, version=version, packaging=packaging, snapshot_version=snapshot_version, classifier=classifier, headers=headers)\n    target_file = __resolve_target_file(file_name, target_dir, target_file)\n    return __save_artifact(snapshot_url, target_file, headers)",
    "docstring": "Gets snapshot of the desired version of the artifact\n\n       nexus_url\n           URL of nexus instance\n       repository\n           Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots\n       group_id\n           Group Id of the artifact\n       artifact_id\n           Artifact Id of the artifact\n       packaging\n           Packaging type (jar,war,ear,etc)\n       version\n           Version of the artifact\n       target_dir\n           Target directory to download artifact to (default: /tmp)\n       target_file\n           Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging)\n       classifier\n           Artifact classifier name (ex: sources,javadoc,etc). Optional parameter.\n       username\n           nexus username. Optional parameter.\n       password\n           nexus password. Optional parameter."
  },
  {
    "code": "def delete_additional_charge(self, recurring_billing_id):\n        fmt = 'recurringBillItems/{}'.format(recurring_billing_id)\n        return self.client._delete(self.url + fmt, headers=self.get_headers())",
    "docstring": "Remove an extra charge from an invoice.\n\n        Args:\n            recurring_billing_id: Identifier of the additional charge.\n\n        Returns:"
  },
  {
    "code": "def has_next(self):\n        if self._result_cache:\n            return self._result_cache.has_next\n        return self.all().has_next",
    "docstring": "Return True if there are more values present"
  },
  {
    "code": "def _get_schema(cls, schema):\n        if isinstance(schema, string_types):\n            schema = cls._get_object_from_python_path(schema)\n        if isclass(schema):\n            schema = schema()\n        if not isinstance(schema, Schema):\n            raise TypeError(\"The schema must be a path to a Marshmallow \"\n                            \"schema or a Marshmallow schema.\")\n        return schema",
    "docstring": "Method that will fetch a Marshmallow schema flexibly.\n\n        Args:\n            schema (marshmallow.Schema|str): Either the schema class, an\n                instance of a schema, or a Python path to a schema.\n\n        Returns:\n            marshmallow.Schema: The desired schema.\n\n        Raises:\n            TypeError: This is raised if the provided object isn't\n                a Marshmallow schema."
  },
  {
    "code": "def get_cls_for_collection(self, collection):\n        for cls, params in self.classes.items():\n            if params['collection'] == collection:\n                return cls\n        raise AttributeError(\"Unknown collection: %s\" % collection)",
    "docstring": "Return the class for a given collection name.\n\n        :param collection: The name of the collection for which to return the class.\n\n        :returns: A reference to the class for the given collection name."
  },
  {
    "code": "def get_contract_data(self, contract_name):\n        contract_data_path = self.output_dir + '/{0}.json'.format(contract_name)\n        with open(contract_data_path, 'r') as contract_data_file:\n            contract_data = json.load(contract_data_file)\n        abi = contract_data['abi']\n        bytecode = contract_data['evm']['bytecode']['object']\n        return abi, bytecode",
    "docstring": "Returns the contract data for a given contract\n\n        Args:\n            contract_name (str): Name of the contract to return.\n\n        Returns:\n            str, str: ABI and bytecode of the contract"
  },
  {
    "code": "def is_proxy(elt):\n    if ismethod(elt):\n        elt = get_method_function(elt)\n    result = hasattr(elt, __PROXIFIED__)\n    return result",
    "docstring": "Return True if elt is a proxy.\n\n    :param elt: elt to check such as a proxy.\n    :return: True iif elt is a proxy.\n    :rtype: bool"
  },
  {
    "code": "def delete_attachment(request, link_field=None, uri=None):\n    if link_field is None:\n        link_field = \"record_uri\"\n    if uri is None:\n        uri = record_uri(request)\n    filters = [Filter(link_field, uri, core_utils.COMPARISON.EQ)]\n    storage = request.registry.storage\n    file_links, _ = storage.get_all(\"\", FILE_LINKS, filters=filters)\n    for link in file_links:\n        request.attachment.delete(link['location'])\n    storage.delete_all(\"\", FILE_LINKS, filters=filters, with_deleted=False)",
    "docstring": "Delete existing file and link."
  },
  {
    "code": "def Arrow(start=(0.,0.,0.), direction=(1.,0.,0.), tip_length=0.25,\n          tip_radius=0.1, shaft_radius=0.05, shaft_resolution=20):\n    arrow = vtk.vtkArrowSource()\n    arrow.SetTipLength(tip_length)\n    arrow.SetTipRadius(tip_radius)\n    arrow.SetShaftRadius(shaft_radius)\n    arrow.SetShaftResolution(shaft_resolution)\n    arrow.Update()\n    surf = PolyData(arrow.GetOutput())\n    translate(surf, start, direction)\n    return surf",
    "docstring": "Create a vtk Arrow\n\n    Parameters\n    ----------\n    start : np.ndarray\n        Start location in [x, y, z]\n\n    direction : list or np.ndarray\n        Direction the arrow points to in [x, y, z]\n\n    tip_length : float, optional\n        Length of the tip.\n\n    tip_radius : float, optional\n        Radius of the tip.\n\n    shaft_radius : float, optional\n        Radius of the shaft.\n\n    shaft_resolution : int, optional\n        Number of faces around the shaft\n\n    Returns\n    -------\n    arrow : vtki.PolyData\n        Arrow surface."
  },
  {
    "code": "def profile(self, frame, event, arg):\n        if (self.events == None) or (event in self.events):\n            frame_info = inspect.getframeinfo(frame)\n            cp = (frame_info[0], frame_info[2], frame_info[1])\n            if self.codepoint_included(cp):\n                objects = muppy.get_objects()\n                size = muppy.get_size(objects)\n                if cp not in self.memories:\n                    self.memories[cp] = [0,0,0,0]\n                    self.memories[cp][0] = 1\n                    self.memories[cp][1] = size\n                    self.memories[cp][2] = size\n                else:\n                    self.memories[cp][0] += 1\n                    if self.memories[cp][1] > size:\n                        self.memories[cp][1] = size\n                    if self.memories[cp][2] < size:\n                        self.memories[cp][2] = size",
    "docstring": "Profiling method used to profile matching codepoints and events."
  },
  {
    "code": "def plot_samples(self,prop,fig=None,label=True,\n                     histtype='step',bins=50,lw=3,\n                     **kwargs):\n        setfig(fig)\n        samples,stats = self.prop_samples(prop)\n        fig = plt.hist(samples,bins=bins,normed=True,\n                 histtype=histtype,lw=lw,**kwargs)\n        plt.xlabel(prop)\n        plt.ylabel('Normalized count')\n        if label:\n            med,lo,hi = stats\n            plt.annotate('$%.2f^{+%.2f}_{-%.2f}$' % (med,hi,lo),\n                         xy=(0.7,0.8),xycoords='axes fraction',fontsize=20)\n        return fig",
    "docstring": "Plots histogram of samples of desired property.\n\n        :param prop:\n            Desired property (must be legit column of samples)\n            \n        :param fig:\n              Argument for :func:`plotutils.setfig` (``None`` or int).\n\n        :param histtype, bins, lw:\n             Passed to :func:`plt.hist`.\n\n        :param **kwargs:\n            Additional keyword arguments passed to `plt.hist`\n\n        :return:\n            Figure object."
  },
  {
    "code": "def is_json(value,\n            schema = None,\n            json_serializer = None,\n            **kwargs):\n    try:\n        value = validators.json(value,\n                                schema = schema,\n                                json_serializer = json_serializer,\n                                **kwargs)\n    except SyntaxError as error:\n        raise error\n    except Exception:\n        return False\n    return True",
    "docstring": "Indicate whether ``value`` is a valid JSON object.\n\n    .. note::\n\n      ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the\n      meta-schema using a ``$schema`` property, the schema will be assumed to conform to\n      Draft 7.\n\n    :param value: The value to evaluate.\n\n    :param schema: An optional JSON schema against which ``value`` will be validated.\n    :type schema: :class:`dict <python:dict>` / :class:`str <python:str>` /\n      :obj:`None <python:None>`\n\n    :returns: ``True`` if ``value`` is valid, ``False`` if it is not.\n    :rtype: :class:`bool <python:bool>`\n\n    :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates\n      keyword parameters passed to the underlying validator"
  },
  {
    "code": "def list_by_instance(self, instance_id):\n        ports = port_list(self.request, device_id=instance_id)\n        sg_ids = []\n        for p in ports:\n            sg_ids += p.security_groups\n        return self._list(id=set(sg_ids)) if sg_ids else []",
    "docstring": "Gets security groups of an instance.\n\n        :returns: List of SecurityGroup objects associated with the instance"
  },
  {
    "code": "def _read_config_file(self):\n        try:\n            with open(self.config, 'r') as f:\n                config_data = json.load(f)\n        except FileNotFoundError:\n            config_data = {}\n        return config_data",
    "docstring": "read in the configuration file, a json file defined at self.config"
  },
  {
    "code": "def setup_model(x, y, model_type='random_forest', seed=None, **kwargs):\n    assert len(x) > 1 and len(y) > 1, 'Not enough data objects to train on (minimum is at least two, you have (x: {0}) and (y: {1}))'.format(len(x), len(y))\n    sets = namedtuple('Datasets', ['train', 'test'])\n    x_train, x_test, y_train, y_test = train_test_split(x,\n                                                        y,\n                                                        random_state=seed,\n                                                        shuffle=False)\n    x = sets(x_train, x_test)\n    y = sets(y_train, y_test)\n    if model_type == 'random_forest' or model_type == 'rf':\n        model = rf.RandomForest(x, y, random_state=seed, **kwargs)\n    elif model_type == 'deep_neural_network' or model_type == 'dnn':\n        model = dnn.DeepNeuralNetwork(x, y, **kwargs)\n    else:\n        raise ValueError('Invalid model type kwarg')\n    return model",
    "docstring": "Initializes a machine learning model\n\n    Args:\n        x: Pandas DataFrame, X axis of features\n        y: Pandas Series, Y axis of targets\n        model_type: Machine Learning model to use\n            Valid values: 'random_forest'\n        seed: Random state to use when splitting sets and creating the model\n        **kwargs: Scikit Learn's RandomForestClassifier kwargs\n\n    Returns:\n        Trained model instance of model_type"
  },
  {
    "code": "def _JRAxiIntegrand(r,E,L,pot):\n    return nu.sqrt(2.*(E-potentialAxi(r,pot))-L**2./r**2.)",
    "docstring": "The J_R integrand"
  },
  {
    "code": "def message_from_file(fp, *args, **kws):\n    from future.backports.email.parser import Parser\n    return Parser(*args, **kws).parse(fp)",
    "docstring": "Read a file and parse its contents into a Message object model.\n\n    Optional _class and strict are passed to the Parser constructor."
  },
  {
    "code": "def set_console(stream=STDOUT, foreground=None, background=None, style=None):\n    if foreground is None:\n        foreground = _default_foreground\n    if background is None:\n        background = _default_background\n    if style is None:\n        style = _default_style\n    attrs = get_attrs(foreground, background, style)\n    SetConsoleTextAttribute(stream, attrs)",
    "docstring": "Set console foreground and background attributes."
  },
  {
    "code": "def credentials_match(self, user_detail, key):\n        if user_detail:\n            creds = user_detail.get('auth')\n            try:\n                auth_encoder, creds_dict = \\\n                    swauth.authtypes.validate_creds(creds)\n            except ValueError as e:\n                self.logger.error('%s' % e.args[0])\n                return False\n        return user_detail and auth_encoder.match(key, creds, **creds_dict)",
    "docstring": "Returns True if the key is valid for the user_detail.\n        It will use auth_encoder type the password was encoded with,\n        to check for a key match.\n\n        :param user_detail: The dict for the user.\n        :param key: The key to validate for the user.\n        :returns: True if the key is valid for the user, False if not."
  },
  {
    "code": "def strip_el_text(el, max_depth=0, cur_depth=0):\n    el_text = strip_str(el.text if el.text is not None else \"\")\n    if cur_depth < max_depth:\n        for child in el:\n            el_text += \" \"+strip_el_text(child, max_depth=max_depth, cur_depth=cur_depth+1)\n    else:\n        children = list(el)\n        if children is not None and len(children) > 0:\n            if children[-1].tail is not None:\n                el_text += \" \"+strip_str(children[-1].tail)\n    if cur_depth > 0:\n        if el.tail is not None:\n            el_text += \" \"+strip_str(el.tail)\n    return strip_str(el_text)",
    "docstring": "Recursively strips the plain text out of the given XML etree element up to the desired depth.\n\n    Args:\n        el: The etree element to scan.\n        max_depth: The depth to which to recursively strip text (default: 0).\n        cur_depth: The current recursive depth to which we've scanned so far.\n\n    Returns:\n        The stripped, plain text from within the element."
  },
  {
    "code": "def _collect_derived_entries(state, traces, identifiers):\n    identifiers = set(identifiers)\n    if not identifiers:\n        return {}\n    entries = {}\n    extras = {}\n    for identifier, requirement in state.mapping.items():\n        routes = {trace[1] for trace in traces[identifier] if len(trace) > 1}\n        if identifier not in identifiers and not (identifiers & routes):\n            continue\n        name = requirement.normalized_name\n        if requirement.extras:\n            try:\n                extras[name].extend(requirement.extras)\n            except KeyError:\n                extras[name] = list(requirement.extras)\n        entries[name] = next(iter(requirement.as_pipfile().values()))\n    for name, ext in extras.items():\n        entries[name][\"extras\"] = ext\n    return entries",
    "docstring": "Produce a mapping containing all candidates derived from `identifiers`.\n\n    `identifiers` should provide a collection of requirement identifications\n    from a section (i.e. `packages` or `dev-packages`). This function uses\n    `trace` to filter out candidates in the state that are present because of\n    an entry in that collection."
  },
  {
    "code": "def send_example(self,\n                     *args,\n                     **kwargs\n                     ):\n        parse_result = kwargs.pop('parse_result', True)\n        line = self.make_line(*args, **kwargs)\n        result = self.send_line(line, parse_result=parse_result)\n        return result",
    "docstring": "Send a labeled or unlabeled example to the VW instance.\n        If 'parse_result' kwarg is False, ignore the result and return None.\n\n        All other parameters are passed to self.send_line().\n\n        Returns a VWResult object."
  },
  {
    "code": "def strp_isoformat(strg):\n    if isinstance(strg, datetime):\n        return strg\n    if len(strg) < 19 or len(strg) > 26:\n        if len(strg) > 30:\n            strg = strg[:30] + '...'\n        raise ValueError(\"Invalid ISO formatted time string '%s'\"%strg)\n    if strg.find(\".\") == -1:\n        strg += '.000000'\n    if sys.version[0:3] >= '2.6':\n        return datetime.strptime(strg, \"%Y-%m-%dT%H:%M:%S.%f\")\n    else:\n        dat, mis = strg.split(\".\")\n        dat = datetime.strptime(dat, \"%Y-%m-%dT%H:%M:%S\")\n        mis = int(float('.' + mis)*1000000)\n        return dat.replace(microsecond=mis)",
    "docstring": "Decode an ISO formatted string to a datetime object.\n    Allow a time-string without microseconds.\n\n    We handle input like: 2011-11-14T12:51:25.123456"
  },
  {
    "code": "def future(self, rev=None):\n        if rev is not None:\n            self.seek(rev)\n        return WindowDictFutureView(self._future)",
    "docstring": "Return a Mapping of items after the given revision.\n\n        Default revision is the last one looked up."
  },
  {
    "code": "def persistent_write(self, address, byte, refresh_config=False):\n        self._persistent_write(address, byte)\n        if refresh_config:\n            self.load_config(False)",
    "docstring": "Write a single byte to an address in persistent memory.\n\n        Parameters\n        ----------\n        address : int\n            Address in persistent memory (e.g., EEPROM).\n        byte : int\n            Value to write to address.\n        refresh_config : bool, optional\n            Is ``True``, :meth:`load_config()` is called afterward to refresh\n            the configuration settings."
  },
  {
    "code": "def sum(event_collection, target_property, timeframe=None, timezone=None, interval=None, filters=None,\n        group_by=None, order_by=None, max_age=None, limit=None):\n    _initialize_client_from_environment()\n    return _client.sum(event_collection=event_collection, timeframe=timeframe, timezone=timezone,\n                       interval=interval, filters=filters, group_by=group_by, order_by=order_by,\n                       target_property=target_property, max_age=max_age, limit=limit)",
    "docstring": "Performs a sum query\n\n    Adds the values of a target property for events that meet the given criteria.\n\n    :param event_collection: string, the name of the collection to query\n    :param target_property: string, the name of the event property you would like use\n    :param timeframe: string or dict, the timeframe in which the events\n    happened example: \"previous_7_days\"\n    :param timezone: int, the timezone you'd like to use for the timeframe\n    and interval in seconds\n    :param interval: string, the time interval used for measuring data over\n    time example: \"daily\"\n    :param filters: array of dict, contains the filters you'd like to apply to the data\n    example: [{\"property_name\":\"device\", \"operator\":\"eq\", \"property_value\":\"iPhone\"}]\n    :param group_by: string or array of strings, the name(s) of the properties you would\n    like to group you results by.  example: \"customer.id\" or [\"browser\",\"operating_system\"]\n    :param order_by: dictionary or list of dictionary objects containing the property_name(s)\n    to order by and the desired direction(s) of sorting.\n    Example: {\"property_name\":\"result\", \"direction\":keen.direction.DESCENDING}\n    May not be used without a group_by specified.\n    :param limit: positive integer limiting the displayed results of a query using order_by\n    :param max_age: an integer, greater than 30 seconds, the maximum 'staleness' you're\n    willing to trade for increased query performance, in seconds"
  },
  {
    "code": "def update_config(\n        self, filename=\"MAGTUNE_PYMAGICC.CFG\", top_level_key=\"nml_allcfgs\", **kwargs\n    ):\n        kwargs = self._format_config(kwargs)\n        fname = join(self.run_dir, filename)\n        if exists(fname):\n            conf = f90nml.read(fname)\n        else:\n            conf = {top_level_key: {}}\n        conf[top_level_key].update(kwargs)\n        f90nml.write(conf, fname, force=True)\n        return conf",
    "docstring": "Updates a configuration file for MAGICC\n\n        Updates the contents of a fortran namelist in the run directory,\n        creating a new namelist if none exists.\n\n        Parameters\n        ----------\n        filename : str\n            Name of configuration file to write\n\n        top_level_key : str\n            Name of namelist to be written in the\n            configuration file\n\n        kwargs\n            Other parameters to pass to the configuration file. No\n            validation on the parameters is performed.\n\n        Returns\n        -------\n        dict\n            The contents of the namelist which was written to file"
  },
  {
    "code": "def completedefault(self, text, line, begidx, endidx):\n        if self.argparser_completer and any((line.startswith(x) for x in self.argparse_names())):\n            self.argparser_completer.rl_complete(line, 0)\n            return [x[begidx:] for x in self.argparser_completer._rl_matches]\n        else:\n            return []",
    "docstring": "Accessing the argcompleter if available."
  },
  {
    "code": "def _get_raw_objects(self):\n        if not hasattr(self, '_raw_objects'):\n            result = self._client.get(type(self).api_endpoint, model=self)\n            self._raw_objects = result\n        return self._raw_objects",
    "docstring": "Helper function to populate the first page of raw objects for this tag.\n        This has the side effect of creating the ``_raw_objects`` attribute of\n        this object."
  },
  {
    "code": "async def info(self):\n        stat = self._items.stat()\n        return {'indx': self._items.index(), 'metrics': self._metrics.index(), 'stat': stat}",
    "docstring": "Returns information about the CryoTank instance.\n\n        Returns:\n            dict: A dict containing items and metrics indexes."
  },
  {
    "code": "def _format_value_element(lines, element, spacer=\"\"):\n    lines.append(spacer + element.definition())\n    _format_summary(lines, element)\n    _format_generic(lines, element, [\"summary\"])",
    "docstring": "Formats a member or parameter for full documentation output."
  },
  {
    "code": "def cluster_replicate(self, node_id):\n        fut = self.execute(b'CLUSTER', b'REPLICATE', node_id)\n        return wait_ok(fut)",
    "docstring": "Reconfigure a node as a slave of the specified master node."
  },
  {
    "code": "def should_stream(proxy_response):\n    content_type = proxy_response.headers.get('Content-Type')\n    if is_html_content_type(content_type):\n        return False\n    try:\n        content_length = int(proxy_response.headers.get('Content-Length', 0))\n    except ValueError:\n        content_length = 0\n    if not content_length or content_length > MIN_STREAMING_LENGTH:\n        return True\n    return False",
    "docstring": "Function to verify if the proxy_response must be converted into\n    a stream.This will be done by checking the proxy_response content-length\n    and verify if its length is bigger than one stipulated\n    by MIN_STREAMING_LENGTH.\n\n    :param proxy_response: An Instance of urllib3.response.HTTPResponse\n    :returns: A boolean stating if the proxy_response should\n              be treated as a stream"
  },
  {
    "code": "def instance_signals_and_handlers(cls, instance):\n        isignals = cls._signals.copy()\n        ihandlers = cls._build_instance_handler_mapping(\n            instance,\n             cls._signal_handlers\n        )\n        return isignals, ihandlers",
    "docstring": "Calculate per-instance signals and handlers."
  },
  {
    "code": "def count_rows_distinct(self, table, cols='*'):\n        return self.fetch('SELECT COUNT(DISTINCT {0}) FROM {1}'.format(join_cols(cols), wrap(table)))",
    "docstring": "Get the number distinct of rows in a particular table."
  },
  {
    "code": "def deps_used(self, pkg, used):\n        if find_package(pkg + self.meta.sp, self.meta.pkg_path):\n            if pkg not in self.deps_dict.values():\n                self.deps_dict[pkg] = used\n            else:\n                self.deps_dict[pkg] += used",
    "docstring": "Create dependencies dictionary"
  },
  {
    "code": "def read_gcvs(filename):\n    with open(filename, 'r') as fp:\n        parser = GcvsParser(fp)\n        for star in parser:\n            yield star",
    "docstring": "Reads variable star data in `GCVS format`_.\n\n    :param filename: path to GCVS data file (usually ``iii.dat``)\n\n    .. _`GCVS format`: http://www.sai.msu.su/gcvs/gcvs/iii/html/"
  },
  {
    "code": "def bech32_decode(bech):\n    if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or\n            (bech.lower() != bech and bech.upper() != bech)):\n        return None, None\n    bech = bech.lower()\n    pos = bech.rfind('1')\n    if pos < 1 or pos + 7 > len(bech) or len(bech) > 90:\n        return None, None\n    if not all(x in CHARSET for x in bech[pos+1:]):\n        return None, None\n    hrp = bech[:pos]\n    data = [CHARSET.find(x) for x in bech[pos+1:]]\n    if not bech32_verify_checksum(hrp, data):\n        return None, None\n    return hrp, data[:-6]",
    "docstring": "Validate a Bech32 string, and determine HRP and data."
  },
  {
    "code": "def get_reservations(self, email, date, timeout=None):\n        try:\n            resp = self._request(\"GET\", \"/1.1/space/bookings?email={}&date={}&limit=100\".format(email, date), timeout=timeout)\n        except resp.exceptions.HTTPError as error:\n            raise APIError(\"Server Error: {}\".format(error))\n        except requests.exceptions.ConnectTimeout:\n            raise APIError(\"Timeout Error\")\n        return resp.json()",
    "docstring": "Gets reservations for a given email.\n\n        :param email: the email of the user who's reservations are to be fetched\n        :type email: str"
  },
  {
    "code": "def score(text, *score_functions):\n    if not score_functions:\n        raise ValueError(\"score_functions must not be empty\")\n    return statistics.mean(func(text) for func in score_functions)",
    "docstring": "Score ``text`` using ``score_functions``.\n\n    Examples:\n        >>> score(\"abc\", function_a)\n        >>> score(\"abc\", function_a, function_b)\n\n    Args:\n        text (str): The text to score\n        *score_functions (variable length argument list): functions to score with\n\n    Returns:\n        Arithmetic mean of scores\n\n    Raises:\n        ValueError: If score_functions is empty"
  },
  {
    "code": "def exon_overlap(self,tx,multi_minover=10,multi_endfrac=0,multi_midfrac=0.8,single_minover=50,single_frac=0.5,multi_consec=True):\n    return ExonOverlap(self,tx,multi_minover,multi_endfrac,multi_midfrac,single_minover,single_frac,multi_consec=multi_consec)",
    "docstring": "Get a report on how mucht the exons overlap\n\n    :param tx:\n    :param multi_minover: multi-exons need to overlap by at lest this much to be considered overlapped (default 10)\n    :param multi_endfrac: multi-exons need an end fraction coverage of at least this by default (default 0)\n    :param multi_midfrac: multi-exons need (default 0.8) mutual coverage for internal exons\n    :parma single_minover: single-exons need at least this much shared overlap (default 50)\n    :param single_frac: at least this fraction of single exons must overlap (default 0.5)\n    :parma multi_consec: exons need to have multiexon consecutive mapping to consider it a match (default True)\n    :type tx:\n    :type multi_minover: int\n    :type multi_endfrac: float\n    :type multi_midfrac: float\n    :type single_minover: int\n    :type single_frac: float\n    :type multi_consec: bool\n    :return: ExonOverlap report\n    :rtype: Transcript.ExonOverlap"
  },
  {
    "code": "def _create_non_null_wrapper(name, t):\n    'creates type wrapper for non-null of given type'\n    def __new__(cls, json_data, selection_list=None):\n        if json_data is None:\n            raise ValueError(name + ' received null value')\n        return t(json_data, selection_list)\n    def __to_graphql_input__(value, indent=0, indent_string='  '):\n        return t.__to_graphql_input__(value, indent, indent_string)\n    return type(name, (t,), {\n        '__new__': __new__,\n        '_%s__auto_register' % name: False,\n        '__to_graphql_input__': __to_graphql_input__,\n    })",
    "docstring": "creates type wrapper for non-null of given type"
  },
  {
    "code": "def scores(self, text: str) -> Dict[str, float]:\n        values = extract(text)\n        input_fn = _to_func(([values], []))\n        prediction = self._classifier.predict_proba(input_fn=input_fn)\n        probabilities = next(prediction).tolist()\n        sorted_languages = sorted(self.languages)\n        return dict(zip(sorted_languages, probabilities))",
    "docstring": "A score for each language corresponding to the probability that\n        the text is written in the given language.\n        The score is a `float` value between 0.0 and 1.0\n\n        :param text: source code.\n        :return: language to score dictionary"
  },
  {
    "code": "def on_connected(self, connection):\n        log.info('PikaClient: connected to RabbitMQ')\n        self.connected = True\n        self.in_channel = self.connection.channel(self.on_channel_open)",
    "docstring": "AMQP connection callback.\n        Creates input channel.\n\n        Args:\n            connection: AMQP connection"
  },
  {
    "code": "async def reseed_apply(self) -> DIDInfo:\n        LOGGER.debug('Wallet.reseed_apply >>>')\n        if not self.handle:\n            LOGGER.debug('Wallet.reseed_init <!< Wallet %s is closed', self.name)\n            raise WalletState('Wallet {} is closed'.format(self.name))\n        await did.replace_keys_apply(self.handle, self.did)\n        self.verkey = await did.key_for_local_did(self.handle, self.did)\n        now = int(time())\n        rv = DIDInfo(self.did, self.verkey, {'anchor': True, 'since': now, 'modified': now})\n        await did.set_did_metadata(self.handle, self.did, json.dumps(rv.metadata))\n        LOGGER.info('Wallet %s set seed hash metadata for DID %s', self.name, self.did)\n        LOGGER.debug('Wallet.reseed_apply <<< %s', rv)\n        return rv",
    "docstring": "Replace verification key with new verification key from reseed operation.\n        Raise WalletState if wallet is closed.\n\n        :return: DIDInfo with new verification key and metadata for DID"
  },
  {
    "code": "def remove(self, key):\n        item = self.item_finder.pop(key)\n        item[-1] = None\n        self.removed_count += 1",
    "docstring": "remove the value found at key from the queue"
  },
  {
    "code": "def GetPossibleGroup(self):\n    this_method = self._call_queue.pop()\n    assert this_method == self\n    group = None\n    try:\n      group = self._call_queue[-1]\n    except IndexError:\n      pass\n    return group",
    "docstring": "Returns a possible group from the end of the call queue or None if no\n    other methods are on the stack."
  },
  {
    "code": "def _slopes_directions(self, data, dX, dY, method='tarboton'):\n        if method == 'tarboton':\n            return self._tarboton_slopes_directions(data, dX, dY)\n        elif method == 'central':\n            return self._central_slopes_directions(data, dX, dY)",
    "docstring": "Wrapper to pick between various algorithms"
  },
  {
    "code": "def peek(self):\n        try:\n            self._fetch()\n            pkt = self.pkt_queue[0]\n            return pkt\n        except IndexError:\n            raise StopIteration()",
    "docstring": "Get the current packet without consuming it."
  },
  {
    "code": "def close(self, file_des):\n        file_handle = self.filesystem.get_open_file(file_des)\n        file_handle.close()",
    "docstring": "Close a file descriptor.\n\n        Args:\n            file_des: An integer file descriptor for the file object requested.\n\n        Raises:\n            OSError: bad file descriptor.\n            TypeError: if file descriptor is not an integer."
  },
  {
    "code": "def rename_acquisition(self, plate_name, name, new_name):\n        logger.info(\n            'rename acquisistion \"%s\" of experiment \"%s\", plate \"%s\"',\n            name, self.experiment_name, plate_name\n        )\n        content = {'name': new_name}\n        acquisition_id = self._get_acquisition_id(plate_name, name)\n        url = self._build_api_url(\n            '/experiments/{experiment_id}/acquisitions/{acquisition_id}'.format(\n                experiment_id=self._experiment_id, acquisition_id=acquisition_id\n            )\n        )\n        res = self._session.put(url, json=content)\n        res.raise_for_status()",
    "docstring": "Renames an acquisition.\n\n        Parameters\n        ----------\n        plate_name: str\n            name of the parent plate\n        name: str\n            name of the acquisition that should be renamed\n        new_name: str\n            name that should be given to the acquisition\n\n        See also\n        --------\n        :func:`tmserver.api.acquisition.update_acquisition`\n        :class:`tmlib.models.acquisition.Acquisition`"
  },
  {
    "code": "def to_api_repr(self):\n        resource = copy.deepcopy(self._properties)\n        query_parameters = resource[\"query\"].get(\"queryParameters\")\n        if query_parameters:\n            if query_parameters[0].get(\"name\") is None:\n                resource[\"query\"][\"parameterMode\"] = \"POSITIONAL\"\n            else:\n                resource[\"query\"][\"parameterMode\"] = \"NAMED\"\n        return resource",
    "docstring": "Build an API representation of the query job config.\n\n        Returns:\n            dict: A dictionary in the format used by the BigQuery API."
  },
  {
    "code": "def gerrymanderNodeFilenames(self):\n        for node in self.all_nodes:\n            node.file_name = os.path.basename(node.file_name)\n            if node.kind == \"file\":\n                node.program_file = os.path.basename(node.program_file)",
    "docstring": "When creating nodes, the filename needs to be relative to ``conf.py``, so it\n        will include ``self.root_directory``.  However, when generating the API, the\n        file we are writing to is in the same directory as the generated node files so\n        we need to remove the directory path from a given ExhaleNode's ``file_name``\n        before we can ``include`` it or use it in a ``toctree``."
  },
  {
    "code": "def mark_flags_as_required(flag_names, flag_values=_flagvalues.FLAGS):\n  for flag_name in flag_names:\n    mark_flag_as_required(flag_name, flag_values)",
    "docstring": "Ensures that flags are not None during program execution.\n\n  Recommended usage:\n\n    if __name__ == '__main__':\n      flags.mark_flags_as_required(['flag1', 'flag2', 'flag3'])\n      app.run()\n\n  Args:\n    flag_names: Sequence[str], names of the flags.\n    flag_values: flags.FlagValues, optional FlagValues instance where the flags\n        are defined.\n  Raises:\n    AttributeError: If any of flag name has not already been defined as a flag."
  },
  {
    "code": "def first_name(anon, obj, field, val):\n    return anon.faker.first_name(field=field)",
    "docstring": "Returns a random first name"
  },
  {
    "code": "def dependencies(self, images):\n        for dep in self.commands.dependent_images:\n            if not isinstance(dep, six.string_types):\n                yield dep.name\n        for image, _ in self.dependency_images():\n            yield image",
    "docstring": "Yield just the dependency images"
  },
  {
    "code": "def geocode_address(self, address, **kwargs):\n        fields = \",\".join(kwargs.pop(\"fields\", []))\n        response = self._req(verb=\"geocode\", params={\"q\": address, \"fields\": fields})\n        if response.status_code != 200:\n            return error_response(response)\n        return Location(response.json())",
    "docstring": "Returns a Location dictionary with the components of the queried\n        address and the geocoded location.\n\n        >>> client = GeocodioClient('some_api_key')\n        >>> client.geocode(\"1600 Pennsylvania Ave, Washington DC\")\n        {\n        \"input\": {\n            \"address_components\": {\n                \"number\": \"1600\",\n                \"street\": \"Pennsylvania\",\n                \"suffix\": \"Ave\",\n                \"city\": \"Washington\",\n                \"state\": \"DC\"\n            },\n            \"formatted_address\": \"1600 Pennsylvania Ave, Washington DC\"\n        },\n        \"results\": [\n            {\n                \"address_components\": {\n                    \"number\": \"1600\",\n                    \"street\": \"Pennsylvania\",\n                    \"suffix\": \"Ave\",\n                    \"city\": \"Washington\",\n                    \"state\": \"DC\",\n                    \"zip\": \"20500\"\n                },\n                \"formatted_address\": \"1600 Pennsylvania Ave, Washington DC, 20500\",\n                \"location\": {\n                    \"lat\": 38.897700000000,\n                    \"lng\": -77.03650000000,\n                },\n                \"accuracy\": 1\n            },\n            {\n                \"address_components\": {\n                    \"number\": \"1600\",\n                    \"street\": \"Pennsylvania\",\n                    \"suffix\": \"Ave\",\n                    \"city\": \"Washington\",\n                    \"state\": \"DC\",\n                    \"zip\": \"20500\"\n                },\n                \"formatted_address\": \"1600 Pennsylvania Ave, Washington DC, 20500\",\n                \"location\": {\n                    \"lat\": 38.897700000000,\n                    \"lng\": -77.03650000000,\n                },\n                \"accuracy\": 0.8\n                }\n            ]\n        }"
  },
  {
    "code": "def compute_edge_reduction(self) -> float:\n        nb_init_edge = self.init_edge_number()\n        nb_poweredge = self.edge_number()\n        return (nb_init_edge - nb_poweredge) / (nb_init_edge)",
    "docstring": "Compute the edge reduction. Costly computation"
  },
  {
    "code": "def set_authorization_password(self, password):\n        self.authorization_password = password\n        self.changed_event.emit(self)",
    "docstring": "Changes the authorization password of the account.\n\n        :type  password: string\n        :param password: The new authorization password."
  },
  {
    "code": "def get(self, **url_params):\n        if url_params:\n            self.http_method_args[\"params\"].update(url_params)\n        return self.http_method(\"GET\")",
    "docstring": "Makes the HTTP GET to the url."
  },
  {
    "code": "def add_string_pairs_from_text_view_element(xib_file, results, text_view, special_ui_components_prefix):\n    text_view_entry_comment = extract_element_internationalized_comment(text_view)\n    if text_view_entry_comment is None:\n        return\n    if text_view.hasAttribute('usesAttributedText') and text_view.attributes['usesAttributedText'].value == 'YES':\n        add_string_pairs_from_attributed_ui_element(results, text_view, text_view_entry_comment)\n    else:\n        try:\n            text_view_entry_key = text_view.attributes['text'].value\n            results.append((text_view_entry_key, text_view_entry_comment + ' default text value'))\n        except KeyError:\n            pass\n    warn_if_element_not_of_class(text_view, 'TextView', special_ui_components_prefix)",
    "docstring": "Adds string pairs from a textview element.\n\n    Args:\n        xib_file (str): Path to the xib file.\n        results (list): The list to add the results to.\n        text_view(element): The textview element from the xib, to extract the string pairs from.\n        special_ui_components_prefix(str): A custom prefix for internationalize component to allow (default is only JT)"
  },
  {
    "code": "def parse_line(line):\n    line = line.rstrip()\n    line_type = _get_line_type(line)\n    return TabLine(\n        type=line_type,\n        data=_DATA_PARSERS[line_type](line),\n        original=line,\n    )",
    "docstring": "Parse a line into a `TabLine` object."
  },
  {
    "code": "def count(self):\n        if not self.query.store.autocommit:\n            self.query.store.checkpoint()\n        target = ', '.join([\n            tableClass.storeID.getColumnName(self.query.store)\n            for tableClass in self.query.tableClass ])\n        sql, args = self.query._sqlAndArgs(\n            'SELECT DISTINCT',\n            target)\n        sql = 'SELECT COUNT(*) FROM (' + sql + ')'\n        result = self.query.store.querySQL(sql, args)\n        assert len(result) == 1, 'more than one result: %r' % (result,)\n        return result[0][0] or 0",
    "docstring": "Count the number of distinct results of the wrapped query.\n\n        @return: an L{int} representing the number of distinct results."
  },
  {
    "code": "def get(self):\n        value = {}\n        for (elementname, elementvar) in self._elementvars.items():\n            value[elementname] = elementvar.get()\n        return value",
    "docstring": "Return a dictionary that represents the Tcl array"
  },
  {
    "code": "def assert_is_substring(substring, subject, message=None, extra=None):\n    assert (\n        (subject is not None)\n        and (substring is not None)\n        and (subject.find(substring) != -1)\n    ), _assert_fail_message(message, substring, subject, \"is not in\", extra)",
    "docstring": "Raises an AssertionError if substring is not a substring of subject."
  },
  {
    "code": "def badge_color(self):\n        if not self.thresholds:\n            return self.default_color\n        if self.value_type == str:\n            if self.value in self.thresholds:\n                return self.thresholds[self.value]\n            else:\n                return self.default_color\n        threshold_list = [[self.value_type(i[0]), i[1]] for i in self.thresholds.items()]\n        threshold_list.sort(key=lambda x: x[0])\n        color = None\n        for threshold, color in threshold_list:\n            if float(self.value) < float(threshold):\n                return color\n        if color and self.use_max_when_value_exceeds:\n            return color\n        else:\n            return self.default_color",
    "docstring": "Find the badge color based on the thresholds."
  },
  {
    "code": "def delete_user_login(self, id, user_id):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"user_id\"] = user_id\r\n        path[\"id\"] = id\r\n        self.logger.debug(\"DELETE /api/v1/users/{user_id}/logins/{id} with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"DELETE\", \"/api/v1/users/{user_id}/logins/{id}\".format(**path), data=data, params=params, no_data=True)",
    "docstring": "Delete a user login.\r\n\r\n        Delete an existing login."
  },
  {
    "code": "def detect_intent_texts(project_id, session_id, texts, language_code):\n    import dialogflow_v2 as dialogflow\n    session_client = dialogflow.SessionsClient()\n    session = session_client.session_path(project_id, session_id)\n    print('Session path: {}\\n'.format(session))\n    for text in texts:\n        text_input = dialogflow.types.TextInput(\n            text=text, language_code=language_code)\n        query_input = dialogflow.types.QueryInput(text=text_input)\n        response = session_client.detect_intent(\n            session=session, query_input=query_input)\n        print('=' * 20)\n        print('Query text: {}'.format(response.query_result.query_text))\n        print('Detected intent: {} (confidence: {})\\n'.format(\n            response.query_result.intent.display_name,\n            response.query_result.intent_detection_confidence))\n        print('Fulfillment text: {}\\n'.format(\n            response.query_result.fulfillment_text))",
    "docstring": "Returns the result of detect intent with texts as inputs.\n\n    Using the same `session_id` between requests allows continuation\n    of the conversation."
  },
  {
    "code": "def omega(self, structure, n, u):\n        l0 = np.dot(np.sum(structure.lattice.matrix, axis=0), n)\n        l0 *= 1e-10\n        weight = float(structure.composition.weight) * 1.66054e-27\n        vol = structure.volume * 1e-30\n        vel = (1e9 * self[0].einsum_sequence([n, u, n, u])\n               / (weight / vol)) ** 0.5\n        return vel / l0",
    "docstring": "Finds directional frequency contribution to the heat\n        capacity from direction and polarization\n\n        Args:\n            structure (Structure): Structure to be used in directional heat\n                capacity determination\n            n (3x1 array-like): direction for Cv determination\n            u (3x1 array-like): polarization direction, note that\n                no attempt for verification of eigenvectors is made"
  },
  {
    "code": "def and_yields(self, *values):\n        def generator():\n            for value in values:\n                yield value\n        self.__expect(Expectation, Invoke(generator))",
    "docstring": "Expects the return value of the expectation to be a generator of the\n        given values"
  },
  {
    "code": "def delif(self, iname):\n        _runshell([brctlexe, 'delif', self.name, iname],\n            \"Could not delete interface %s from %s.\" % (iname, self.name))",
    "docstring": "Delete an interface from the bridge."
  },
  {
    "code": "def parse_data(data, type, **kwargs):\n    suffixes = {\n        'xml': '.osm',\n        'pbf': '.pbf',\n    }\n    try:\n        suffix = suffixes[type]\n    except KeyError:\n        raise ValueError('Unknown data type \"%s\"' % type)\n    fd, filename = tempfile.mkstemp(suffix=suffix)\n    try:\n        os.write(fd, data)\n        os.close(fd)\n        return parse_file(filename, **kwargs)\n    finally:\n        os.remove(filename)",
    "docstring": "Return an OSM networkx graph from the input OSM data\n\n    Parameters\n    ----------\n    data : string\n    type : string ('xml' or 'pbf')\n\n    >>> graph = parse_data(data, 'xml')"
  },
  {
    "code": "def contrast(colour1, colour2):\n    r\n    colour_for_type = Colour()\n    if type(colour1) is type(colour_for_type):\n        mycolour1 = colour1\n    else:\n        try:\n            mycolour1 = Colour(colour1)\n        except:\n            raise TypeError(\"colour1 must be a colourettu.colour\")\n    if type(colour2) is type(colour_for_type):\n        mycolour2 = colour2\n    else:\n        try:\n            mycolour2 = Colour(colour2)\n        except:\n            raise TypeError(\"colour2 must be a colourettu.colour\")\n    lum1 = mycolour1.luminance()\n    lum2 = mycolour2.luminance()\n    minlum = min(lum1, lum2)\n    maxlum = max(lum1, lum2)\n    return (maxlum + 0.05) / (minlum + 0.05)",
    "docstring": "r\"\"\"Determines the contrast between two colours.\n\n    Args:\n        colour1 (colourettu.Colour): a colour\n        colour2 (colourettu.Colour): a second colour\n\n    Contrast the difference in (perceived) brightness between colours.\n    Values vary between 1:1 (a given colour on itself) and 21:1 (white on\n    black).\n\n    To compute contrast, two colours are required.\n\n    .. code:: pycon\n\n        >>> colourettu.contrast(\"#FFF\", \"#FFF\") # white on white\n        1.0\n        >>> colourettu.contrast(c1, \"#000\") # black on white\n        20.999999999999996\n        >>> colourettu.contrast(c4, c5)\n        4.363552233203198\n\n    ``contrast`` can also be called on an already existing colour, but a\n    second colour needs to be provided:\n\n    .. code:: pycon\n\n        >>> c4.contrast(c5)\n        4.363552233203198\n\n    .. note::\n\n        Uses the formula:\n\n        \\\\[ contrast = \\\\frac{lum_1 + 0.05}{lum_2 + 0.05} \\\\]\n\n    **Use of Contrast**\n\n    For Basic readability, the ANSI standard is a contrast of 3:1 between\n    the text and it's background. The W3C proposes this as a minimum\n    accessibility standard for regular text under 18pt and bold text under\n    14pt. This is referred to as the *A* standard. The W3C defines a higher\n    *AA* standard with a minimum contrast of 4.5:1. This is approximately\n    equivalent to 20/40 vision, and is common for those over 80. The W3C\n    define an even higher *AAA* standard with a 7:1 minimum contrast. This\n    would be equivalent to 20/80 vision. Generally, it is assumed that those\n    with vision beyond this would access the web with the use of assistive\n    technologies.\n\n    If needed, these constants are stored in the library.\n\n    .. code:: pycon\n\n        >>> colourettu.A_contrast\n        3.0\n        >>> colourettu.AA_contrast\n        4.5\n        >>> colourettu.AAA_contrast\n        7.0\n\n    I've also found mention that if the contrast is *too* great, this can\n    also cause readability problems when reading longer passages. This is\n    confirmed by personal experience, but I have been (yet) unable to find\n    any quantitative research to this effect."
  },
  {
    "code": "def _StructPackDecoder(wire_type, format):\n  value_size = struct.calcsize(format)\n  local_unpack = struct.unpack\n  def InnerDecode(buffer, pos):\n    new_pos = pos + value_size\n    result = local_unpack(format, buffer[pos:new_pos])[0]\n    return (result, new_pos)\n  return _SimpleDecoder(wire_type, InnerDecode)",
    "docstring": "Return a constructor for a decoder for a fixed-width field.\n\n  Args:\n      wire_type:  The field's wire type.\n      format:  The format string to pass to struct.unpack()."
  },
  {
    "code": "def natural_breaks(values, k=5):\n    values = np.array(values)\n    uv = np.unique(values)\n    uvk = len(uv)\n    if uvk < k:\n        Warn('Warning: Not enough unique values in array to form k classes',\n             UserWarning)\n        Warn('Warning: setting k to %d' % uvk, UserWarning)\n        k = uvk\n    kres = _kmeans(values, k)\n    sids = kres[-1]\n    fit = kres[-2]\n    class_ids = kres[0]\n    cuts = kres[1]\n    return (sids, class_ids, fit, cuts)",
    "docstring": "natural breaks helper function\n\n    Jenks natural breaks is kmeans in one dimension"
  },
  {
    "code": "def value(self):\n        choice = weighted_choice(self._responses)\n        if isinstance(choice, tuple):\n            return ''.join(map(str, choice)).strip()\n        return str(choice)",
    "docstring": "Fetch a random weighted choice"
  },
  {
    "code": "def create_impression_event(self, experiment, variation_id, user_id, attributes):\n    params = self._get_common_params(user_id, attributes)\n    impression_params = self._get_required_params_for_impression(experiment, variation_id)\n    params[self.EventParams.USERS][0][self.EventParams.SNAPSHOTS].append(impression_params)\n    return Event(self.EVENTS_URL,\n                 params,\n                 http_verb=self.HTTP_VERB,\n                 headers=self.HTTP_HEADERS)",
    "docstring": "Create impression Event to be sent to the logging endpoint.\n\n    Args:\n      experiment: Experiment for which impression needs to be recorded.\n      variation_id: ID for variation which would be presented to user.\n      user_id: ID for user.\n      attributes: Dict representing user attributes and values which need to be recorded.\n\n    Returns:\n      Event object encapsulating the impression event."
  },
  {
    "code": "def EMAIL_REQUIRED(self):\n        from allauth.account import app_settings as account_settings\n        return self._setting(\"EMAIL_REQUIRED\", account_settings.EMAIL_REQUIRED)",
    "docstring": "The user is required to hand over an e-mail address when signing up"
  },
  {
    "code": "def _load_sentence_list(self, path):\n        result = {}\n        for entry in textfile.read_separated_lines_generator(path, separator='\\t', max_columns=3):\n            if self.include_languages is None or entry[1] in self.include_languages:\n                result[entry[0]] = entry[1:]\n        return result",
    "docstring": "Load and filter the sentence list.\n\n        Args:\n            path (str): Path to the sentence list.\n\n        Returns:\n            dict: Dictionary of sentences (id : language, transcription)"
  },
  {
    "code": "def starmap_async(function, iterables, *args, **kwargs):\n    return _map_or_starmap_async(function, iterables, args, kwargs, \"starmap\")",
    "docstring": "This function is the multiprocessing.Pool.starmap_async version that\n       supports multiple arguments.\n\n            >>> return ([function(x1,x2,x3,..., args[0], args[1],...) for\n            >>>         (x1,x2,x3...) in iterable])\n\n       :param pm_parallel: Force parallelization on/off. If False, the\n                           function won't be asynchronous.\n       :type pm_parallel: bool\n       :param pm_chunksize: see  :py:class:`multiprocessing.pool.Pool`\n       :type pm_chunksize: int\n       :param pm_callback: see  :py:class:`multiprocessing.pool.Pool`\n       :type pm_callback: function\n       :param pm_error_callback: see  :py:class:`multiprocessing.pool.Pool`\n       :type pm_error_callback: function\n       :param pm_pool: Pass an existing pool.\n       :type pm_pool: multiprocessing.pool.Pool\n       :param pm_processes: Number of processes to use in the pool. See\n         :py:class:`multiprocessing.pool.Pool`\n       :type pm_processes: int"
  },
  {
    "code": "def get_boolean(self, input_string):\n        if input_string in ('--write_roc', '--plot', '--compare'):\n            try:\n                index = self.args.index(input_string) + 1\n            except ValueError:\n                return False\n            return True",
    "docstring": "Return boolean type user input"
  },
  {
    "code": "def get_param_values(self_,onlychanged=False):\n        self_or_cls = self_.self_or_cls\n        vals = []\n        for name,val in self_or_cls.param.objects('existing').items():\n            value = self_or_cls.param.get_value_generator(name)\n            if not onlychanged or not all_equal(value,val.default):\n                vals.append((name,value))\n        vals.sort(key=itemgetter(0))\n        return vals",
    "docstring": "Return a list of name,value pairs for all Parameters of this\n        object.\n\n        When called on an instance with onlychanged set to True, will\n        only return values that are not equal to the default value\n        (onlychanged has no effect when called on a class)."
  },
  {
    "code": "def closed(self):\n        for who, what, old, new in self.history():\n            if what == \"status\" and new == \"closed\":\n                return True\n        return False",
    "docstring": "True if ticket was closed in given time frame"
  },
  {
    "code": "def _fetch_features(self):\n        if self.next_page_url is None:\n            return\n        response = get_json(self.next_page_url, post_values=self.query, headers=self.gpd_session.session_headers)\n        self.features.extend(response['features'])\n        self.next_page_url = response['pagination']['next']\n        self.layer_size = response['pagination']['total']",
    "docstring": "Retrieves a new page of features from Geopedia"
  },
  {
    "code": "def ref_string_matches_ref_sequence(self, ref_sequence):\n        if self.POS < 0:\n            return False\n        end_pos = self.ref_end_pos()\n        if end_pos >= len(ref_sequence):\n            return False\n        return self.REF == ref_sequence[self.POS:end_pos + 1]",
    "docstring": "Returns true iff the REF string in the record agrees with\n        the given ref_sequence"
  },
  {
    "code": "def convert_to_nested_dict(dotted_dict):\n    nested_dict = {}\n    for k, v in iterate_flattened(dotted_dict):\n        set_by_dotted_path(nested_dict, k, v)\n    return nested_dict",
    "docstring": "Convert a dict with dotted path keys to corresponding nested dict."
  },
  {
    "code": "def write_string(self, s, codec):\n        for i in range(0, len(s), self.bufsize):\n            chunk = s[i:i + self.bufsize]\n            buf, consumed = codec.encode(chunk)\n            assert consumed == len(chunk)\n            self.write(buf)",
    "docstring": "Write string encoding it with codec into stream"
  },
  {
    "code": "def _create_eval_metric_composite(metric_names: List[str]) -> mx.metric.CompositeEvalMetric:\n        metrics = [EarlyStoppingTrainer._create_eval_metric(metric_name) for metric_name in metric_names]\n        return mx.metric.create(metrics)",
    "docstring": "Creates a composite EvalMetric given a list of metric names."
  },
  {
    "code": "def get_message(self, *parameters):\n        _, message_fields, header_fields = self._get_parameters_with_defaults(parameters)\n        return self._encode_message(message_fields, header_fields)",
    "docstring": "Get encoded message.\n\n        * Send Message -keywords are convenience methods, that will call this to\n        get the message object and then send it. Optional parameters are message\n        field values separated with colon.\n\n        Examples:\n        | ${msg} = | Get message |\n        | ${msg} = | Get message | field_name:value |"
  },
  {
    "code": "def libvlc_vlm_get_event_manager(p_instance):\n    f = _Cfunctions.get('libvlc_vlm_get_event_manager', None) or \\\n        _Cfunction('libvlc_vlm_get_event_manager', ((1,),), class_result(EventManager),\n                    ctypes.c_void_p, Instance)\n    return f(p_instance)",
    "docstring": "Get libvlc_event_manager from a vlm media.\n    The p_event_manager is immutable, so you don't have to hold the lock.\n    @param p_instance: a libvlc instance.\n    @return: libvlc_event_manager."
  },
  {
    "code": "def exists(self, table_id):\n        from google.api_core.exceptions import NotFound\n        table_ref = self.client.dataset(self.dataset_id).table(table_id)\n        try:\n            self.client.get_table(table_ref)\n            return True\n        except NotFound:\n            return False\n        except self.http_error as ex:\n            self.process_http_error(ex)",
    "docstring": "Check if a table exists in Google BigQuery\n\n        Parameters\n        ----------\n        table : str\n            Name of table to be verified\n\n        Returns\n        -------\n        boolean\n            true if table exists, otherwise false"
  },
  {
    "code": "def register_previewer(self, name, previewer):\n        if name in self.previewers:\n            assert name not in self.previewers, \\\n                \"Previewer with same name already registered\"\n        self.previewers[name] = previewer\n        if hasattr(previewer, 'previewable_extensions'):\n            self._previewable_extensions |= set(\n                previewer.previewable_extensions)",
    "docstring": "Register a previewer in the system."
  },
  {
    "code": "def search_project_root():\n        while True:\n            current = os.getcwd()\n            if pathlib.Path(\"Miragefile.py\").is_file() or pathlib.Path(\"Miragefile\").is_file():\n                return current\n            elif os.getcwd() == \"/\":\n                raise FileNotFoundError\n            else:\n                os.chdir(\"../\")",
    "docstring": "Search your Django project root.\n\n        returns:\n            - path:string  Django project root path"
  },
  {
    "code": "def manufacturer(self):\n        buf = ctypes.cast(self.sManu, ctypes.c_char_p).value\n        return buf.decode() if buf else None",
    "docstring": "Returns the name of the manufacturer of the device.\n\n        Args:\n          self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance\n\n        Returns:\n          Manufacturer name."
  },
  {
    "code": "def get_cfgdict_list_subset(cfgdict_list, keys):\n    r\n    import utool as ut\n    cfgdict_sublist_ = [ut.dict_subset(cfgdict, keys) for cfgdict in cfgdict_list]\n    cfgtups_sublist_ = [tuple(ut.dict_to_keyvals(cfgdict)) for cfgdict in cfgdict_sublist_]\n    cfgtups_sublist = ut.unique_ordered(cfgtups_sublist_)\n    cfgdict_sublist = list(map(dict, cfgtups_sublist))\n    return cfgdict_sublist",
    "docstring": "r\"\"\"\n    returns list of unique dictionaries only with keys specified in keys\n\n    Args:\n        cfgdict_list (list):\n        keys (list):\n\n    Returns:\n        list: cfglbl_list\n\n    CommandLine:\n        python -m utool.util_gridsearch --test-get_cfgdict_list_subset\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_gridsearch import *  # NOQA\n        >>> import utool as ut\n        >>> # build test data\n        >>> cfgdict_list = [\n        ...     {'K': 3, 'dcvs_clip_max': 0.1, 'p': 0.1},\n        ...     {'K': 5, 'dcvs_clip_max': 0.1, 'p': 0.1},\n        ...     {'K': 5, 'dcvs_clip_max': 0.1, 'p': 0.2},\n        ...     {'K': 3, 'dcvs_clip_max': 0.2, 'p': 0.1},\n        ...     {'K': 5, 'dcvs_clip_max': 0.2, 'p': 0.1},\n        ...     {'K': 3, 'dcvs_clip_max': 0.2, 'p': 0.1}]\n        >>> keys = ['K', 'dcvs_clip_max']\n        >>> # execute function\n        >>> cfgdict_sublist = get_cfgdict_list_subset(cfgdict_list, keys)\n        >>> # verify results\n        >>> result = ut.repr4(cfgdict_sublist)\n        >>> print(result)\n        [\n            {'K': 3, 'dcvs_clip_max': 0.1},\n            {'K': 5, 'dcvs_clip_max': 0.1},\n            {'K': 3, 'dcvs_clip_max': 0.2},\n            {'K': 5, 'dcvs_clip_max': 0.2},\n        ]"
  },
  {
    "code": "def write_byte_data(self, address, register, value):\n        LOGGER.debug(\"Writing byte data %s to register %s on device %s\",\n            bin(value), hex(register), hex(address))\n        return self.driver.write_byte_data(address, register, value)",
    "docstring": "Write a byte value to a device's register."
  },
  {
    "code": "def _generate_statistics(self, out_path, results_path):\n        if not os.path.exists(out_path):\n            report = StatisticsReport(self._corpus, self._tokenizer,\n                                      results_path)\n            report.generate_statistics()\n            with open(out_path, mode='w', encoding='utf-8', newline='') as fh:\n                report.csv(fh)",
    "docstring": "Writes a statistics report for the results at `results_path` to\n        `out_path`.\n\n        Reuses an existing statistics report if one exists at\n        `out_path`.\n\n        :param out_path: path to output statistics report to\n        :type out_path: `str`\n        :param results_path: path of results to generate statistics for\n        :type results_path: `str`"
  },
  {
    "code": "def step1c(self):\n        if self.ends(['y']) and self.vowel_in_stem():\n            self.b[self.k] = 'i'",
    "docstring": "turn terminal y into i if there's a vowel in stem"
  },
  {
    "code": "def replaceelement(oldelem, newelem):\n    parent = oldelem.getparent()\n    if parent is not None:\n        size = len(parent.getchildren())\n        for x in range(0, size):\n            if parent.getchildren()[x] == oldelem:\n                parent.remove(oldelem)\n                parent.insert(x, newelem)",
    "docstring": "Given a parent element, replace oldelem with newelem."
  },
  {
    "code": "def initial_dist_from_config(cp, variable_params):\n    r\n    if len(cp.get_subsections(\"initial\")):\n        logging.info(\"Using a different distribution for the starting points \"\n                     \"than the prior.\")\n        initial_dists = distributions.read_distributions_from_config(\n            cp, section=\"initial\")\n        constraints = distributions.read_constraints_from_config(\n            cp, constraint_section=\"initial_constraint\")\n        init_dist = distributions.JointDistribution(\n            variable_params, *initial_dists,\n            **{\"constraints\": constraints})\n    else:\n        init_dist = None\n    return init_dist",
    "docstring": "r\"\"\"Loads a distribution for the sampler start from the given config file.\n\n    A distribution will only be loaded if the config file has a [initial-\\*]\n    section(s).\n\n    Parameters\n    ----------\n    cp : Config parser\n        The config parser to try to load from.\n    variable_params : list of str\n        The variable parameters for the distribution.\n\n    Returns\n    -------\n    JointDistribution or None :\n        The initial distribution. If no [initial-\\*] section found in the\n        config file, will just return None."
  },
  {
    "code": "async def start(self):\n        if self._server_task is not None:\n            self._logger.debug(\"AsyncValidatingWSServer.start() called twice, ignoring\")\n            return\n        started_signal = self._loop.create_future()\n        self._server_task = self._loop.add_task(self._run_server_task(started_signal))\n        await started_signal\n        if self.port is None:\n            self.port = started_signal.result()",
    "docstring": "Start the websocket server.\n\n        When this method returns, the websocket server will be running and\n        the port property of this class will have its assigned port number.\n\n        This method should be called only once in the lifetime of the server\n        and must be paired with a call to stop() to cleanly release the\n        server's resources."
  },
  {
    "code": "def del_ns(self, namespace):\n        namespace = str(namespace)\n        attr_name = None\n        if hasattr(self, namespace):\n            delattr(self, namespace)",
    "docstring": "will remove a namespace ref from the manager. either Arg is\n        optional.\n\n        args:\n            namespace: prefix, string or Namespace() to remove"
  },
  {
    "code": "def _export_work_errors(self, work, output_file):\n    errors = set()\n    for v in itervalues(work.work):\n      if v['is_completed'] and v['error'] is not None:\n        errors.add(v['error'])\n    with open(output_file, 'w') as f:\n      for e in sorted(errors):\n        f.write(e)\n        f.write('\\n')",
    "docstring": "Saves errors for given work pieces into file.\n\n    Args:\n      work: instance of either AttackWorkPieces or DefenseWorkPieces\n      output_file: name of the output file"
  },
  {
    "code": "def clear_profiling_cookies(request, response):\n        if 'profile_page' in request.COOKIES:\n            path = request.path\n            response.set_cookie('profile_page', max_age=0, path=path)",
    "docstring": "Expire any cookie that initiated profiling request."
  },
  {
    "code": "def pattern_error(self, original, loc, value_var, check_var):\n        base_line = clean(self.reformat(getline(loc, original)))\n        line_wrap = self.wrap_str_of(base_line)\n        repr_wrap = self.wrap_str_of(ascii(base_line))\n        return (\n            \"if not \" + check_var + \":\\n\" + openindent\n            + match_err_var + ' = _coconut_MatchError(\"pattern-matching failed for \" '\n            + repr_wrap + ' \" in \" + _coconut.repr(_coconut.repr(' + value_var + \")))\\n\"\n            + match_err_var + \".pattern = \" + line_wrap + \"\\n\"\n            + match_err_var + \".value = \" + value_var\n            + \"\\nraise \" + match_err_var + \"\\n\" + closeindent\n        )",
    "docstring": "Construct a pattern-matching error message."
  },
  {
    "code": "def shutdown_instances(self):\n        self.min_size = 0\n        self.max_size = 0\n        self.desired_capacity = 0\n        self.update()",
    "docstring": "Convenience method which shuts down all instances associated with\n        this group."
  },
  {
    "code": "def get_attribute(self, reference):\n        prefix, _, name = reference.rpartition('.')\n        match = None\n        for attribute in self._contents:\n            if name == attribute.name and \\\n                    (not prefix or prefix == attribute.prefix):\n                if match:\n                    raise AttributeReferenceError(\n                        'Ambiguous attribute reference: {}.'.format(\n                            attribute.name))\n                else:\n                    match = attribute\n        if match:\n            return match\n        raise AttributeReferenceError(\n            'Attribute does not exist: {}'.format(reference))",
    "docstring": "Return the attribute that matches the reference. Raise an error if\n        the attribute cannot be found, or if there is more then one match."
  },
  {
    "code": "def _bare_name_matches(self, nodes):\n        count = 0\n        r = {}\n        done = False\n        max = len(nodes)\n        while not done and count < max:\n            done = True\n            for leaf in self.content:\n                if leaf[0].match(nodes[count], r):\n                    count += 1\n                    done = False\n                    break\n        r[self.name] = nodes[:count]\n        return count, r",
    "docstring": "Special optimized matcher for bare_name."
  },
  {
    "code": "def createDashboardOverlay(self, pchOverlayKey, pchOverlayFriendlyName):\n        fn = self.function_table.createDashboardOverlay\n        pMainHandle = VROverlayHandle_t()\n        pThumbnailHandle = VROverlayHandle_t()\n        result = fn(pchOverlayKey, pchOverlayFriendlyName, byref(pMainHandle), byref(pThumbnailHandle))\n        return result, pMainHandle, pThumbnailHandle",
    "docstring": "Creates a dashboard overlay and returns its handle"
  },
  {
    "code": "def warsaw_to_warsawmass(C, parameters=None, sectors=None):\n    p = default_parameters.copy()\n    if parameters is not None:\n        p.update(parameters)\n    C_out = C.copy()\n    C_rotate_u = ['uphi', 'uG', 'uW', 'uB']\n    for name in C_rotate_u:\n        _array = smeft_toarray(name, C)\n        V = ckmutil.ckm.ckm_tree(p[\"Vus\"], p[\"Vub\"], p[\"Vcb\"], p[\"delta\"])\n        UuL = V.conj().T\n        _array = UuL.conj().T @ _array\n        _dict = smeft_fromarray(name, _array)\n        C_out.update(_dict)\n    _array = smeft_toarray('llphiphi', C)\n    _array = np.diag(ckmutil.diag.msvd(_array)[1])\n    _dict = smeft_fromarray('llphiphi', _array)\n    C_out.update(_dict)\n    return C_out",
    "docstring": "Translate from the Warsaw basis to the 'Warsaw mass' basis.\n\n    Parameters used:\n    - `Vus`, `Vub`, `Vcb`, `gamma`: elements of the unitary CKM matrix (defined\n      as the mismatch between left-handed quark mass matrix diagonalization\n      matrices)."
  },
  {
    "code": "def _CheckCollation(cursor):\n  cur_collation_connection = _ReadVariable(\"collation_connection\", cursor)\n  if cur_collation_connection != COLLATION:\n    logging.warning(\"Require MySQL collation_connection of %s, got %s.\",\n                    COLLATION, cur_collation_connection)\n  cur_collation_database = _ReadVariable(\"collation_database\", cursor)\n  if cur_collation_database != COLLATION:\n    logging.warning(\n        \"Require MySQL collation_database of %s, got %s.\"\n        \" To create your database, use: %s\", COLLATION, cur_collation_database,\n        CREATE_DATABASE_QUERY)",
    "docstring": "Checks MySQL collation and warns if misconfigured."
  },
  {
    "code": "def list(self):\n        params = {'user': self.user_id}\n        response = self.session.get(self.url, params=params)\n        blocks = response.data['blocks']\n        return [Block(self, **block) for block in blocks]",
    "docstring": "List the users you have blocked.\n\n        :return: a list of :class:`~groupy.api.blocks.Block`'s\n        :rtype: :class:`list`"
  },
  {
    "code": "def ordered_list(text_array):\n    text_list = []\n    for number, item in enumerate(text_array):\n        text_list.append(\n            (esc_format(number + 1) + \".\").ljust(3) + \" \" + esc_format(item)\n        )\n    return \"\\n\".join(text_list)",
    "docstring": "Return an ordered list from an array.\n\n    >>> ordered_list([\"first\", \"second\", \"third\", \"fourth\"])\n    '1.  first\\\\n2.  second\\\\n3.  third\\\\n4.  fourth'"
  },
  {
    "code": "def words(ctx, input, output):\n    log.info('chemdataextractor.read.elements')\n    log.info('Reading %s' % input.name)\n    doc = Document.from_file(input)\n    for element in doc.elements:\n        if isinstance(element, Text):\n            for sentence in element.sentences:\n                output.write(u' '.join(sentence.raw_tokens))\n                output.write(u'\\n')",
    "docstring": "Read input document, and output words."
  },
  {
    "code": "def from_(cls, gsim):\n        ltbranch = N('logicTreeBranch', {'branchID': 'b1'},\n                     nodes=[N('uncertaintyModel', text=str(gsim)),\n                            N('uncertaintyWeight', text='1.0')])\n        lt = N('logicTree', {'logicTreeID': 'lt1'},\n               nodes=[N('logicTreeBranchingLevel', {'branchingLevelID': 'bl1'},\n                        nodes=[N('logicTreeBranchSet',\n                                 {'applyToTectonicRegionType': '*',\n                                  'branchSetID': 'bs1',\n                                  'uncertaintyType': 'gmpeModel'},\n                                 nodes=[ltbranch])])])\n        return cls(repr(gsim), ['*'], ltnode=lt)",
    "docstring": "Generate a trivial GsimLogicTree from a single GSIM instance."
  },
  {
    "code": "def node_mkdir(self, path=''):\n\t\t'Does not raise any errors if dir already exists.'\n\t\treturn self(path, data=dict(kind='directory'), encode='json', method='put')",
    "docstring": "Does not raise any errors if dir already exists."
  },
  {
    "code": "def _write(self, session, openFile, replaceParamFile):\n        if self.raster is not None:\n            converter = RasterConverter(session)\n            grassAsciiGrid = converter.getAsGrassAsciiRaster(rasterFieldName='raster',\n                                                             tableName=self.__tablename__,\n                                                             rasterIdFieldName='id',\n                                                             rasterId=self.id)\n            openFile.write(grassAsciiGrid)\n        elif self.rasterText is not None:\n            openFile.write(self.rasterText)",
    "docstring": "Raster Map File Write to File Method"
  },
  {
    "code": "def is_installed(self, pkgname):\n        return any(d for d in self.get_distributions() if d.project_name == pkgname)",
    "docstring": "Given a package name, returns whether it is installed in the environment\n\n        :param str pkgname: The name of a package\n        :return: Whether the supplied package is installed in the environment\n        :rtype: bool"
  },
  {
    "code": "def extract_user_id(self, request):\n        payload = self.extract_payload(request)\n        user_id_attribute = self.config.user_id()\n        return payload.get(user_id_attribute, None)",
    "docstring": "Extract a user id from a request object."
  },
  {
    "code": "def _get_type_name(type_):\n    name = repr(type_)\n    if name.startswith(\"<\"):\n        name = getattr(type_, \"__qualname__\", getattr(type_, \"__name__\", \"\"))\n    return name.rsplit(\".\", 1)[-1] or repr(type_)",
    "docstring": "Return a displayable name for the type.\n\n    Args:\n        type_: A class object.\n\n    Returns:\n        A string value describing the class name that can be used in a natural\n        language sentence."
  },
  {
    "code": "def sign_message(privkey_path, message, passphrase=None):\n    key = get_rsa_key(privkey_path, passphrase)\n    log.debug('salt.crypt.sign_message: Signing message.')\n    if HAS_M2:\n        md = EVP.MessageDigest('sha1')\n        md.update(salt.utils.stringutils.to_bytes(message))\n        digest = md.final()\n        return key.sign(digest)\n    else:\n        signer = PKCS1_v1_5.new(key)\n        return signer.sign(SHA.new(salt.utils.stringutils.to_bytes(message)))",
    "docstring": "Use Crypto.Signature.PKCS1_v1_5 to sign a message. Returns the signature."
  },
  {
    "code": "def _find_spelling_errors_in_chunks(chunks,\n                                    contents,\n                                    valid_words_dictionary=None,\n                                    technical_words_dictionary=None,\n                                    user_dictionary_words=None):\n    for chunk in chunks:\n        for error in spellcheck_region(chunk.data,\n                                       valid_words_dictionary,\n                                       technical_words_dictionary,\n                                       user_dictionary_words):\n            col_offset = _determine_character_offset(error.line_offset,\n                                                     error.column_offset,\n                                                     chunk.column)\n            msg = _SPELLCHECK_MESSAGES[error.error_type].format(error.word)\n            yield _populate_spelling_error(error.word,\n                                           error.suggestions,\n                                           contents,\n                                           error.line_offset +\n                                           chunk.line,\n                                           col_offset,\n                                           msg)",
    "docstring": "For each chunk and a set of valid and technical words, find errors."
  },
  {
    "code": "def metrics(self):\n        from vel.metrics.loss_metric import Loss\n        from vel.metrics.accuracy import Accuracy\n        return [Loss(), Accuracy()]",
    "docstring": "Set of metrics for this model"
  },
  {
    "code": "def file_hash(load, fnd):\n    if 'env' in load:\n        load.pop('env')\n    ret = {}\n    if 'saltenv' not in load:\n        return ret\n    if 'path' not in fnd or 'bucket' not in fnd or not fnd['path']:\n        return ret\n    cached_file_path = _get_cached_file_name(\n            fnd['bucket'],\n            load['saltenv'],\n            fnd['path'])\n    if os.path.isfile(cached_file_path):\n        ret['hsum'] = salt.utils.hashutils.get_hash(cached_file_path)\n        ret['hash_type'] = 'md5'\n    return ret",
    "docstring": "Return an MD5 file hash"
  },
  {
    "code": "def get_sigma_tables(self, imt, rctx, stddev_types):\n        output_tables = []\n        for stddev_type in stddev_types:\n            if imt.name in 'PGA PGV':\n                interpolator = interp1d(self.magnitudes,\n                                        self.sigma[stddev_type][imt.name],\n                                        axis=2)\n                output_tables.append(\n                    interpolator(rctx.mag).reshape(self.shape[0],\n                                                   self.shape[3]))\n            else:\n                interpolator = interp1d(numpy.log10(self.periods),\n                                        self.sigma[stddev_type][\"SA\"],\n                                        axis=1)\n                period_table = interpolator(numpy.log10(imt.period))\n                mag_interpolator = interp1d(self.magnitudes,\n                                            period_table,\n                                            axis=1)\n                output_tables.append(mag_interpolator(rctx.mag))\n        return output_tables",
    "docstring": "Returns modification factors for the standard deviations, given the\n        rupture and intensity measure type.\n\n        :returns:\n            List of standard deviation modification tables, each as an array\n            of [Number Distances, Number Levels]"
  },
  {
    "code": "def schema_file(self):\n        path = os.getcwd() + '/' + self.lazy_folder\n        return path + self.schema_filename",
    "docstring": "Gets the full path to the file in which to load configuration schema."
  },
  {
    "code": "def move_backward(self):\n        self.at(ardrone.at.pcmd, True, 0, self.speed, 0, 0)",
    "docstring": "Make the drone move backwards."
  },
  {
    "code": "def navigation(self, id=None):\n        def wrapper(f):\n            self.register_element(id or f.__name__, f)\n            return f\n        return wrapper",
    "docstring": "Function decorator for navbar registration.\n\n        Convenience function, calls :meth:`.register_element` with ``id`` and\n        the decorated function as ``elem``.\n\n        :param id: ID to pass on. If ``None``, uses the decorated functions\n                   name."
  },
  {
    "code": "def trace_read(self, offset, num_items):\n        buf_size = ctypes.c_uint32(num_items)\n        buf = (structs.JLinkTraceData * num_items)()\n        res = self._dll.JLINKARM_TRACE_Read(buf, int(offset), ctypes.byref(buf_size))\n        if (res == 1):\n            raise errors.JLinkException('Failed to read from trace buffer.')\n        return list(buf)[:int(buf_size.value)]",
    "docstring": "Reads data from the trace buffer and returns it.\n\n        Args:\n          self (JLink): the ``JLink`` instance.\n          offset (int): the offset from which to start reading from the trace\n            buffer.\n          num_items (int): number of items to read from the trace buffer.\n\n        Returns:\n          A list of ``JLinkTraceData`` instances corresponding to the items\n          read from the trace buffer.  Note that this list may have size less\n          than ``num_items`` in the event that there are not ``num_items``\n          items in the trace buffer.\n\n        Raises:\n          JLinkException: on error."
  },
  {
    "code": "def create(self, jti, aud=''):\n        return self.client.post(self.url, data={'jti': jti, 'aud': aud})",
    "docstring": "Adds a token to the blacklist.\n\n        Args:\n            jti (str): the jti of the JWT to blacklist.\n            aud (str, optional): The JWT's aud claim. The client_id of the\n                application for which it was issued.\n\n            body (dict):\n            \tSee: https://auth0.com/docs/api/management/v2#!/Blacklists/post_tokens"
  },
  {
    "code": "def override_start_requests(spider_cls, start_urls, callback=None, **attrs):\n    def start_requests():\n        for url in start_urls:\n            req = Request(url, dont_filter=True) if isinstance(url, six.string_types) else url\n            if callback is not None:\n                req.callback = callback\n            yield req\n    attrs['start_requests'] = staticmethod(start_requests)\n    return type(spider_cls.__name__, (spider_cls, ), attrs)",
    "docstring": "Returns a new spider class overriding the ``start_requests``.\n\n    This function is useful to replace the start requests of an existing spider\n    class on runtime.\n\n    Parameters\n    ----------\n    spider_cls : scrapy.Spider\n        Spider class to be used as base class.\n    start_urls : iterable\n        Iterable of URLs or ``Request`` objects.\n    callback : callable, optional\n        Callback for the start URLs.\n    attrs : dict, optional\n        Additional class attributes.\n\n    Returns\n    -------\n    out : class\n        A subclass of ``spider_cls`` with overrided ``start_requests`` method."
  },
  {
    "code": "def parseInt(self, words):\n        words = words.replace(\" and \", \" \").lower()\n        words = re.sub(r'(\\b)a(\\b)', '\\g<1>one\\g<2>', words)\n        def textToNumber(s):\n            a = re.split(r\"[\\s-]+\", s)\n            n = 0\n            g = 0\n            for w in a:\n                x = NumberService.__small__.get(w, None)\n                if x is not None:\n                    g += x\n                elif w == \"hundred\":\n                    g *= 100\n                else:\n                    x = NumberService.__magnitude__.get(w, None)\n                    if x is not None:\n                        n += g * x\n                        g = 0\n                    else:\n                        raise NumberService.NumberException(\n                            \"Unknown number: \" + w)\n            return n + g\n        return textToNumber(words)",
    "docstring": "Parses words to the integer they describe.\n\n        Args:\n            words (str): Description of the integer.\n\n        Returns:\n            An integer representation of the words."
  },
  {
    "code": "def publish(self):\n        with db.session.begin_nested():\n            deposit = self.deposit_class.create(self.metadata)\n            deposit['_deposit']['created_by'] = self.event.user_id\n            deposit['_deposit']['owners'] = [self.event.user_id]\n            for key, url in self.files:\n                deposit.files[key] = self.gh.api.session.get(\n                    url, stream=True).raw\n            deposit.publish()\n            recid, record = deposit.fetch_published()\n            self.model.recordmetadata = record.model",
    "docstring": "Publish GitHub release as record."
  },
  {
    "code": "def rlmb_ppo_base():\n  hparams = _rlmb_base()\n  ppo_params = dict(\n      base_algo=\"ppo\",\n      base_algo_params=\"ppo_original_params\",\n      real_batch_size=1,\n      simulated_batch_size=16,\n      eval_batch_size=32,\n      real_ppo_epochs_num=0,\n      ppo_epochs_num=1000,\n      ppo_epoch_length=hparams.simulated_rollout_length,\n      ppo_eval_every_epochs=0,\n      ppo_learning_rate_constant=1e-4,\n      real_ppo_epoch_length=16 * 200,\n      real_ppo_learning_rate_constant=1e-4,\n      real_ppo_effective_num_agents=16,\n      real_ppo_eval_every_epochs=0,\n      simulation_flip_first_random_for_beginning=True,\n  )\n  update_hparams(hparams, ppo_params)\n  return hparams",
    "docstring": "HParams for PPO base."
  },
  {
    "code": "def bcs_parameters(n_site, n_fermi, u, t) :\n    wave_num = np.linspace(0, 1, n_site, endpoint=False)\n    hop_erg = -2 * t * np.cos(2 * np.pi * wave_num)\n    fermi_erg = hop_erg[n_fermi // 2]\n    hop_erg = hop_erg - fermi_erg\n    def _bcs_gap(x):\n        s = 0.\n        for i in range(n_site):\n            s += 1. / np.sqrt(hop_erg[i] ** 2 + x ** 2)\n        return 1 + s * u / (2 * n_site)\n    delta = scipy.optimize.bisect(_bcs_gap, 0.01, 10000. * abs(u))\n    bcs_v = np.sqrt(0.5 * (1 - hop_erg / np.sqrt(hop_erg ** 2 + delta ** 2)))\n    bog_theta = np.arcsin(bcs_v)\n    return delta, bog_theta",
    "docstring": "Generate the parameters for the BCS ground state, i.e., the\n    superconducting gap and the rotational angles in the Bogoliubov\n    transformation.\n\n     Args:\n        n_site: the number of sites in the Hubbard model\n        n_fermi: the number of fermions\n        u: the interaction strength\n        t: the tunneling strength\n\n    Returns:\n        float delta, List[float] bog_theta"
  },
  {
    "code": "def is_vimball(fd):\n    fd.seek(0)\n    try:\n        header = fd.readline()\n    except UnicodeDecodeError:\n        return False\n    if re.match('^\" Vimball Archiver', header) is not None:\n        return True\n    return False",
    "docstring": "Test for vimball archive format compliance.\n\n    Simple check to see if the first line of the file starts with standard\n    vimball archive header."
  },
  {
    "code": "def create_invoice_from_ticket(pk, list_lines):\n        context = {}\n        if list_lines:\n            new_list_lines = [x[0] for x in SalesLineTicket.objects.values_list('line_order__pk').filter(pk__in=[int(x) for x in list_lines])]\n            if new_list_lines:\n                lo = SalesLineOrder.objects.values_list('order__pk').filter(pk__in=new_list_lines)[:1]\n                if lo and lo[0] and lo[0][0]:\n                    new_pk = lo[0][0]\n                    return GenLineProduct.create_invoice_from_order(new_pk, new_list_lines)\n                else:\n                    error = _('Pedido no encontrado')\n            else:\n                error = _('Lineas no relacionadas con pedido')\n        else:\n            error = _('Lineas no seleccionadas')\n        context['error'] = error\n        return context",
    "docstring": "la pk y list_lines son de ticket, necesitamos la info de las lineas de pedidos"
  },
  {
    "code": "def _parse_programs(self, string, parent, filepath=None):\n        moddocs = self.docparser.parse_docs(string)\n        matches = self.RE_PROGRAM.finditer(string)\n        result = []\n        for rmodule in matches:\n            name = rmodule.group(\"name\").lower()\n            contents = re.sub(\"&[ ]*\\n\", \"\", rmodule.group(\"contents\"))\n            module = self._process_module(name, contents, parent, rmodule, filepath)\n            if name in moddocs:                \n                module.docstring = self.docparser.to_doc(moddocs[name][0], name)\n                module.docstart, module.docend = module.absolute_charindex(string, moddocs[name][1],\n                                                                           moddocs[name][2])\n            result.append(module)\n        return result",
    "docstring": "Extracts a PROGRAM from the specified fortran code file."
  },
  {
    "code": "def enable_device(self):\n        cmd_response = self.__send_command(const.CMD_ENABLEDEVICE)\n        if cmd_response.get('status'):\n            self.is_enabled = True\n            return True\n        else:\n            raise ZKErrorResponse(\"Can't enable device\")",
    "docstring": "re-enable the connected device and allow user activity in device again\n\n        :return: bool"
  },
  {
    "code": "def updatePools(self,\n                    pool1,\n                    username1,\n                    password1,\n                    pool2=None,\n                    username2=None,\n                    password2=None,\n                    pool3=None,\n                    username3=None,\n                    password3=None):\n        return self.__post('/api/updatePools',\n                           data={\n                               'Pool1': pool1,\n                               'UserName1': username1,\n                               'Password1': password1,\n                               'Pool2': pool2,\n                               'UserName2': username2,\n                               'Password2': password2,\n                               'Pool3': pool3,\n                               'UserName3': username3,\n                               'Password3': password3,\n                           })",
    "docstring": "Change the pools of the miner. This call will restart cgminer."
  },
  {
    "code": "def get_callbacks(service):\n    callbacks = list(getattr(settings, 'MAMA_CAS_ATTRIBUTE_CALLBACKS', []))\n    if callbacks:\n        warnings.warn(\n            'The MAMA_CAS_ATTRIBUTE_CALLBACKS setting is deprecated. Service callbacks '\n            'should be configured using MAMA_CAS_SERVICES.', DeprecationWarning)\n    for backend in _get_backends():\n        try:\n            callbacks.extend(backend.get_callbacks(service))\n        except AttributeError:\n            raise NotImplementedError(\"%s.%s.get_callbacks() not implemented\" % (\n                backend.__class__.__module__, backend.__class__.__name__)\n            )\n    return callbacks",
    "docstring": "Get configured callbacks list for a given service identifier."
  },
  {
    "code": "def get_assessment_ids_by_bank(self, bank_id):\n        id_list = []\n        for assessment in self.get_assessments_by_bank(bank_id):\n            id_list.append(assessment.get_id())\n        return IdList(id_list)",
    "docstring": "Gets the list of ``Assessment``  ``Ids`` associated with a ``Bank``.\n\n        arg:    bank_id (osid.id.Id): ``Id`` of the ``Bank``\n        return: (osid.id.IdList) - list of related assessment ``Ids``\n        raise:  NotFound - ``bank_id`` is not found\n        raise:  NullArgument - ``bank_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "async def async_run(self) -> None:\n        self.main_task = self.loop.create_task(self.main())\n        await self.main_task",
    "docstring": "Asynchronously run the worker, does not close connections. Useful when testing."
  },
  {
    "code": "def output_metric(gandi, metrics, key, justify=10):\n    for metric in metrics:\n        key_name = metric[key].pop()\n        values = [point.get('value', 0) for point in metric['points']]\n        graph = sparks(values) if max(values) else ''\n        if sys.version_info < (2, 8):\n            graph = graph.encode('utf-8')\n        output_line(gandi, key_name, graph, justify)",
    "docstring": "Helper to output metrics."
  },
  {
    "code": "def substitute_filename(fn, variables):\n    for var, value in variables.items():\n        fn = fn.replace('+%s+' % var, str(value))\n    return fn",
    "docstring": "Substitute +variables+ in file directory names."
  },
  {
    "code": "def content_type(self, lst):\n        value = []\n        if isinstance(lst, str):\n            ct = defines.Content_types[lst]\n            self.add_content_type(ct)\n        elif isinstance(lst, list):\n            for ct in lst:\n                self.add_content_type(ct)",
    "docstring": "Set the CoRE Link Format ct attribute of the resource.\n\n        :param lst: the list of CoRE Link Format ct attribute of the resource"
  },
  {
    "code": "def get_klass(self):\n        klass_name = self.kwargs.get('klass', None)\n        klass = self.registry.get(klass_name, None)\n        if not klass:\n            raise Http404(\"Unknown autocomplete class `{}`\".format(klass_name))\n        return klass",
    "docstring": "Return the agnocomplete class to be used with the eventual query."
  },
  {
    "code": "def addError(self, test, err, capt=None):\n        exc_type, exc_val, tb = err\n        tb = ''.join(traceback.format_exception(\n            exc_type,\n            exc_val if isinstance(exc_val, exc_type) else exc_type(exc_val),\n            tb\n        ))\n        name = id_split(test.id())\n        group = self.report_data[name[0]]\n        if issubclass(err[0], SkipTest):\n            type = 'skipped'\n            self.stats['skipped'] += 1\n            group.stats['skipped'] += 1\n        else:\n            type = 'error'\n            self.stats['errors'] += 1\n            group.stats['errors'] += 1\n        group.tests.append({\n            'name': name[-1],\n            'failed': True,\n            'type': type,\n            'errtype': nice_classname(err[0]),\n            'message': exc_message(err),\n            'tb': tb,\n        })",
    "docstring": "Add error output to Xunit report."
  },
  {
    "code": "def peekView(self, newLength):\n        return memoryview(self.buf)[self.offset:self.offset + newLength]",
    "docstring": "Return a view of the next newLength bytes."
  },
  {
    "code": "def add_cors_headers(request, response):\n    response.headerlist.append(('Access-Control-Allow-Origin', '*'))\n    response.headerlist.append(\n        ('Access-Control-Allow-Methods', 'GET, OPTIONS'))\n    response.headerlist.append(\n        ('Access-Control-Allow-Headers',\n         ','.join(DEFAULT_ACCESS_CONTROL_ALLOW_HEADERS)))",
    "docstring": "Add cors headers needed for web app implementation."
  },
  {
    "code": "def _constraints_are_whitelisted(self, constraint_tuple):\n    if self._acceptable_interpreter_constraints == []:\n      return True\n    return all(version.parse(constraint) in self._acceptable_interpreter_constraints\n           for constraint in constraint_tuple)",
    "docstring": "Detect whether a tuple of compatibility constraints\n    matches constraints imposed by the merged list of the global\n    constraints from PythonSetup and a user-supplied whitelist."
  },
  {
    "code": "def is_program_installed(basename):\r\n    for path in os.environ[\"PATH\"].split(os.pathsep):\r\n        abspath = osp.join(path, basename)\r\n        if osp.isfile(abspath):\r\n            return abspath",
    "docstring": "Return program absolute path if installed in PATH.\r\n\r\n    Otherwise, return None"
  },
  {
    "code": "def declassify(to_remove, *args, **kwargs):\n    def argdecorate(fn):\n        @wraps(fn)\n        def declassed(*args, **kwargs):\n            ret = fn(*args, **kwargs)\n            try:\n                if type(ret) is list:\n                    return [r[to_remove] for r in ret]\n                return ret[to_remove]\n            except KeyError:\n                return ret\n        return declassed\n    return argdecorate",
    "docstring": "flatten the return values of the mite api."
  },
  {
    "code": "def assert_valid_schema(schema: GraphQLSchema) -> None:\n    errors = validate_schema(schema)\n    if errors:\n        raise TypeError(\"\\n\\n\".join(error.message for error in errors))",
    "docstring": "Utility function which asserts a schema is valid.\n\n    Throws a TypeError if the schema is invalid."
  },
  {
    "code": "def get_foreign_module(namespace):\n    if namespace not in _MODULES:\n        try:\n            module = importlib.import_module(\".\" + namespace, __package__)\n        except ImportError:\n            module = None\n        _MODULES[namespace] = module\n    module = _MODULES.get(namespace)\n    if module is None:\n        raise ForeignError(\"Foreign %r structs not supported\" % namespace)\n    return module",
    "docstring": "Returns the module or raises ForeignError"
  },
  {
    "code": "def validate(self, data):\n        validator = self._schema.validator(self._id)\n        validator.validate(data)",
    "docstring": "Validate the data against the schema."
  },
  {
    "code": "def tornado_combiner(configs, use_gevent=False, start=True, monkey_patch=None,\n                     Container=None, Server=None, threadpool=None):\n    servers = []\n    if monkey_patch is None:\n        monkey_patch = use_gevent\n    if use_gevent:\n        if monkey_patch:\n            from gevent import monkey\n            monkey.patch_all()\n    if threadpool is not None:\n        from multiprocessing.pool import ThreadPool\n        if not isinstance(threadpool, ThreadPool):\n            threadpool = ThreadPool(threadpool)\n    for config in configs:\n        app = config['app']\n        port = config.get('port', 5000)\n        address = config.get('address', '')\n        server = tornado_run(app, use_gevent=use_gevent, port=port,\n                             monkey_patch=False, address=address, start=False,\n                             Container=Container,\n                             Server=Server, threadpool=threadpool)\n        servers.append(server)\n    if start:\n        tornado_start()\n    return servers",
    "docstring": "Combine servers in one tornado event loop process\n\n    :param configs: [\n        {\n            'app': Microservice Application or another wsgi application, required\n            'port': int, default: 5000\n            'address': str, default: \"\"\n        },\n        { ... }\n    ]\n    :param use_gevent: if True, app.wsgi will be run in gevent.spawn\n    :param start: if True, will be call utils.tornado_start()\n    :param Container: your class, bases on tornado.wsgi.WSGIContainer, default: tornado.wsgi.WSGIContainer\n    :param Server: your class, bases on tornado.httpserver.HTTPServer, default: tornado.httpserver.HTTPServer\n    :param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: use_gevent\n    :return: list of tornado servers"
  },
  {
    "code": "def get_all_function_definitions(base_most_function):\n        return [base_most_function] + [function for derived_contract in base_most_function.contract.derived_contracts\n                                       for function in derived_contract.functions\n                                       if function.full_name == base_most_function.full_name]",
    "docstring": "Obtains all function definitions given a base-most function. This includes the provided function, plus any\n        overrides of that function.\n\n        Returns:\n            (list): Returns any the provided function and any overriding functions defined for it."
  },
  {
    "code": "def get_paths(folder, ignore_endswith=ignore_endswith):\n    folder = pathlib.Path(folder).resolve()\n    files = folder.rglob(\"*\")\n    for ie in ignore_endswith:\n        files = [ff for ff in files if not ff.name.endswith(ie)]\n    return sorted(files)",
    "docstring": "Return hologram file paths\n\n    Parameters\n    ----------\n    folder: str or pathlib.Path\n        Path to search folder\n    ignore_endswith: list\n        List of filename ending strings indicating which\n        files should be ignored."
  },
  {
    "code": "def get_id_n_version(ident_hash):\n    try:\n        id, version = split_ident_hash(ident_hash)\n    except IdentHashMissingVersion:\n        from pyramid.httpexceptions import HTTPNotFound\n        from cnxarchive.views.helpers import get_latest_version\n        try:\n            version = get_latest_version(ident_hash)\n        except HTTPNotFound:\n            raise NotFound(ident_hash)\n        id, version = split_ident_hash(join_ident_hash(ident_hash, version))\n    else:\n        verify_id_n_version(id, version)\n    return id, version",
    "docstring": "From the given ``ident_hash`` return the id and version."
  },
  {
    "code": "def fit(self, X, y=None):\n        X = self._validate_input(X)\n        if self.fill_value is None:\n            if X.dtype.kind in (\"i\", \"u\", \"f\"):\n                fill_value = 0\n            else:\n                fill_value = \"missing_value\"\n        else:\n            fill_value = self.fill_value\n        if (self.strategy == \"constant\" and\n                X.dtype.kind in (\"i\", \"u\", \"f\") and\n                not isinstance(fill_value, numbers.Real)):\n            raise ValueError(\"'fill_value'={0} is invalid. Expected a \"\n                             \"numerical value when imputing numerical \"\n                             \"data\".format(fill_value))\n        if sparse.issparse(X):\n            if self.missing_values == 0:\n                raise ValueError(\"Imputation not possible when missing_values \"\n                                 \"== 0 and input is sparse. Provide a dense \"\n                                 \"array instead.\")\n            else:\n                self.statistics_ = self._sparse_fit(X,\n                                                    self.strategy,\n                                                    self.missing_values,\n                                                    fill_value)\n        else:\n            self.statistics_ = self._dense_fit(X,\n                                               self.strategy,\n                                               self.missing_values,\n                                               fill_value)\n        return self",
    "docstring": "Fit the imputer on X.\n\n        Parameters\n        ----------\n        X : {array-like, sparse matrix}, shape (n_samples, n_features)\n            Input data, where ``n_samples`` is the number of samples and\n            ``n_features`` is the number of features.\n\n        Returns\n        -------\n        self : _SimpleImputer"
  },
  {
    "code": "def fromlalcache(cachefile, coltype = int):\n\treturn segments.segmentlist(lal.CacheEntry(l, coltype = coltype).segment for l in cachefile)",
    "docstring": "Construct a segmentlist representing the times spanned by the files\n\tidentified in the LAL cache contained in the file object file.  The\n\tsegmentlist will be created with segments whose boundaries are of\n\ttype coltype, which should raise ValueError if it cannot convert\n\tits string argument.\n\n\tExample:\n\n\t>>> from pycbc_glue.lal import LIGOTimeGPS\n\t>>> cache_seglists = fromlalcache(open(filename), coltype = LIGOTimeGPS).coalesce()\n\n\tSee also:\n\n\tpycbc_glue.lal.CacheEntry"
  },
  {
    "code": "def memoize(func):\n    cache = {}\n    @functools.wraps(func)\n    def wrapper(*args):\n        key = \"__\".join(str(arg) for arg in args)\n        if key not in cache:\n            cache[key] = func(*args)\n        return cache[key]\n    return wrapper",
    "docstring": "Classic memoize decorator for non-class methods"
  },
  {
    "code": "def read_match_config_from_file(match_config_path: Path) -> MatchConfig:\n    config_obj = create_bot_config_layout()\n    config_obj.parse_file(match_config_path, max_index=MAX_PLAYERS)\n    return parse_match_config(config_obj, match_config_path, {}, {})",
    "docstring": "Parse the rlbot.cfg file on disk into the python datastructure."
  },
  {
    "code": "def as_future(self, object_id, check_ready=True):\n        if not isinstance(object_id, ray.ObjectID):\n            raise TypeError(\"Input should be an ObjectID.\")\n        plain_object_id = plasma.ObjectID(object_id.binary())\n        fut = PlasmaObjectFuture(loop=self._loop, object_id=plain_object_id)\n        if check_ready:\n            ready, _ = ray.wait([object_id], timeout=0)\n            if ready:\n                if self._loop.get_debug():\n                    logger.debug(\"%s has been ready.\", plain_object_id)\n                self._complete_future(fut)\n                return fut\n        if plain_object_id not in self._waiting_dict:\n            linked_list = PlasmaObjectLinkedList(self._loop, plain_object_id)\n            linked_list.add_done_callback(self._unregister_callback)\n            self._waiting_dict[plain_object_id] = linked_list\n        self._waiting_dict[plain_object_id].append(fut)\n        if self._loop.get_debug():\n            logger.debug(\"%s added to the waiting list.\", fut)\n        return fut",
    "docstring": "Turn an object_id into a Future object.\n\n        Args:\n            object_id: A Ray's object_id.\n            check_ready (bool): If true, check if the object_id is ready.\n\n        Returns:\n            PlasmaObjectFuture: A future object that waits the object_id."
  },
  {
    "code": "def set_logging_settings(profile, setting, value, store='local'):\n    r\n    return salt.utils.win_lgpo_netsh.set_logging_settings(profile=profile,\n                                                          setting=setting,\n                                                          value=value,\n                                                          store=store)",
    "docstring": "r'''\n    Configure logging settings for the Windows firewall.\n\n    .. versionadded:: 2018.3.4\n    .. versionadded:: 2019.2.0\n\n    Args:\n\n        profile (str):\n            The firewall profile to configure. Valid options are:\n\n            - domain\n            - public\n            - private\n\n        setting (str):\n            The logging setting to configure. Valid options are:\n\n            - allowedconnections\n            - droppedconnections\n            - filename\n            - maxfilesize\n\n        value (str):\n            The value to apply to the setting. Valid values are dependent upon\n            the setting being configured. Valid options are:\n\n            allowedconnections:\n\n                - enable\n                - disable\n                - notconfigured\n\n            droppedconnections:\n\n                - enable\n                - disable\n                - notconfigured\n\n            filename:\n\n                - Full path and name of the firewall log file\n                - notconfigured\n\n            maxfilesize:\n\n                - 1 - 32767\n                - notconfigured\n\n            .. note::\n                ``notconfigured`` can only be used when using the lgpo store\n\n        store (str):\n            The store to use. This is either the local firewall policy or the\n            policy defined by local group policy. Valid options are:\n\n            - lgpo\n            - local\n\n            Default is ``local``\n\n    Returns:\n        bool: ``True`` if successful\n\n    Raises:\n        CommandExecutionError: If an error occurs\n        ValueError: If the parameters are incorrect\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        # Log allowed connections and set that in local group policy\n        salt * firewall.set_logging_settings domain allowedconnections enable lgpo\n\n        # Don't log dropped connections\n        salt * firewall.set_logging_settings profile=private setting=droppedconnections value=disable\n\n        # Set the location of the log file\n        salt * firewall.set_logging_settings domain filename C:\\windows\\logs\\firewall.log\n\n        # You can also use environment variables\n        salt * firewall.set_logging_settings domain filename %systemroot%\\system32\\LogFiles\\Firewall\\pfirewall.log\n\n        # Set the max file size of the log to 2048 Kb\n        salt * firewall.set_logging_settings domain maxfilesize 2048"
  },
  {
    "code": "def make_patch(self):\n        path = [self.arcs[0].start_point()]\n        for a in self.arcs:\n            if a.direction:\n                vertices = Path.arc(a.from_angle, a.to_angle).vertices\n            else:\n                vertices = Path.arc(a.to_angle, a.from_angle).vertices\n                vertices = vertices[np.arange(len(vertices) - 1, -1, -1)]\n            vertices = vertices * a.radius + a.center\n            path = path + list(vertices[1:])\n        codes = [1] + [4] * (len(path) - 1)\n        return PathPatch(Path(path, codes))",
    "docstring": "Retuns a matplotlib PathPatch representing the current region."
  },
  {
    "code": "def _opts_to_dict(*opts):\n\tret = {}\n\tfor key, val in opts:\n\t\tif key[:2] == '--':\n\t\t\tkey = key[2:]\n\t\telif key[:1] == '-':\n\t\t\tkey = key[1:]\n\t\tif val == '':\n\t\t\tval = True\n\t\tret[key.replace('-','_')] = val\n\treturn ret",
    "docstring": "Convert a tuple of options returned from getopt into a dictionary."
  },
  {
    "code": "def bed(args):\n    p = OptionParser(main.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(not p.print_help())\n    contigfile, = args\n    bedfile = contigfile.rsplit(\".\", 1)[0] + \".bed\"\n    fw = open(bedfile, \"w\")\n    c = ContigFile(contigfile)\n    for rec in c.iter_records():\n        for r in rec.reads:\n            print(r.bedline, file=fw)\n    logging.debug(\"File written to `{0}`.\".format(bedfile))\n    return bedfile",
    "docstring": "%prog bed contigfile\n\n    Prints out the contigs and their associated reads."
  },
  {
    "code": "def autoexec(pipe=None, name=None, exit_handler=None):\n    return pipeline(pipe=pipe, name=name, autoexec=True,\n                    exit_handler=exit_handler)",
    "docstring": "create a pipeline with a context that will automatically execute the\n    pipeline upon leaving the context if no exception was raised.\n\n    :param pipe:\n    :param name:\n    :return:"
  },
  {
    "code": "def hmsm_to_days(hour=0,min=0,sec=0,micro=0):\n    days = sec + (micro / 1.e6)\n    days = min + (days / 60.)\n    days = hour + (days / 60.)\n    return days / 24.",
    "docstring": "Convert hours, minutes, seconds, and microseconds to fractional days.\n\n    Parameters\n    ----------\n    hour : int, optional\n        Hour number. Defaults to 0.\n\n    min : int, optional\n        Minute number. Defaults to 0.\n\n    sec : int, optional\n        Second number. Defaults to 0.\n\n    micro : int, optional\n        Microsecond number. Defaults to 0.\n\n    Returns\n    -------\n    days : float\n        Fractional days.\n\n    Examples\n    --------\n    >>> hmsm_to_days(hour=6)\n    0.25"
  },
  {
    "code": "def xy2geom(x, y, t_srs=None):\n    geom_wkt = 'POINT({0} {1})'.format(x, y)\n    geom = ogr.CreateGeometryFromWkt(geom_wkt)\n    if t_srs is not None and not wgs_srs.IsSame(t_srs):\n        ct = osr.CoordinateTransformation(t_srs, wgs_srs)\n        geom.Transform(ct)\n        geom.AssignSpatialReference(t_srs)\n    return geom",
    "docstring": "Convert x and y point coordinates to geom"
  },
  {
    "code": "def smart_scrubb(df,col_name,error_rate = 0):\n    scrubbed = \"\"\n    while True:\n        valcounts = df[col_name].str[-len(scrubbed)-1:].value_counts()\n        if not len(valcounts):\n            break\n        if not valcounts[0] >= (1-error_rate) * _utils.rows(df):\n            break\n        scrubbed=valcounts.index[0]\n    if scrubbed == '':\n        return None\n    which = df[col_name].str.endswith(scrubbed)\n    _basics.col_scrubb(df,col_name,which,len(scrubbed),True)\n    if not which.all():\n        new_col_name = _basics.colname_gen(df,\"{}_sb-{}\".format(col_name,scrubbed))\n        df[new_col_name] = which\n    return scrubbed",
    "docstring": "Scrubs from the back of an 'object' column in a DataFrame\n    until the scrub would semantically alter the contents of the column. If only a \n    subset of the elements in the column are scrubbed, then a boolean array indicating which\n    elements have been scrubbed is appended to the dataframe. Returns the string that was scrubbed.\n    df - DataFrame\n        DataFrame to scrub\n    col_name - string\n        Name of column to scrub\n    error_rate - number, default 0\n        The maximum amount of values this function can ignore while scrubbing, expressed as a\n        fraction of the total amount of rows in the dataframe."
  },
  {
    "code": "def path(self) -> str:\n        return os.path.join(self.project_path, self.project.name)",
    "docstring": "We need to nest the git path inside the project path to make it easier\n        to create docker images."
  },
  {
    "code": "def send_message(self, options):\n        if not options.get(\"save_policy\"):\n            raise ValueError(\"Only configuring save_policy is supported\")\n        if self.socket:\n            self.socket.send(options)\n        elif self._jupyter_agent:\n            self._jupyter_agent.start()\n            self._jupyter_agent.rm.update_user_file_policy(\n                options[\"save_policy\"])\n        else:\n            wandb.termerror(\n                \"wandb.init hasn't been called, can't configure run\")",
    "docstring": "Sends a message to the wandb process changing the policy\n        of saved files.  This is primarily used internally by wandb.save"
  },
  {
    "code": "def word_matches(s1, s2, n=3):\n    return __matches(s1, s2, word_ngrams, n=n)",
    "docstring": "Word-level n-grams that match between two strings\n\n        Args:\n            s1: a string\n            s2: another string\n            n: an int for the n in n-gram\n\n        Returns:\n            set: the n-grams found in both strings"
  },
  {
    "code": "def _configure_connection(self, name, value):\n    self.update(\"pg_settings\", dict(setting=value), dict(name=name))",
    "docstring": "Sets a Postgres run-time connection configuration parameter.\n\n    :param name: the name of the parameter\n    :param value: a list of values matching the placeholders"
  },
  {
    "code": "def _left_click(self, event):\n        self.update_active()\n        iid = self.current_iid\n        if iid is None:\n            return\n        args = (iid, event.x_root, event.y_root)\n        self.call_callbacks(iid, \"left_callback\", args)",
    "docstring": "Function bound to left click event for marker canvas"
  },
  {
    "code": "def _subscribe_all(self):\n        for stream in (self.inbound_streams + self.outbound_streams):\n            for input_ in stream.inputs:\n                if not type(input_) is int and input_ is not None:\n                    self._subscribe(stream, input_)\n        for plugin in self.plugins:\n            for input_ in plugin.inputs:\n                self._subscribe(plugin, input_)\n            for output in plugin.outputs:\n                subscriber = next((x for x in self.outbound_streams\n                                  if x.name == output), None)\n                if subscriber is None:\n                    log.warn('The outbound stream {} does not '\n                             'exist so will not receive messages '\n                             'from {}'.format(output, plugin))\n                else:\n                    self._subscribe(subscriber, plugin.name)",
    "docstring": "Subscribes all streams to their input.\n        Subscribes all plugins to all their inputs.\n        Subscribes all plugin outputs to the plugin."
  },
  {
    "code": "def get_args(obj):\n    if inspect.isfunction(obj):\n        return inspect.getargspec(obj).args\n    elif inspect.ismethod(obj):\n        return inspect.getargspec(obj).args[1:]\n    elif inspect.isclass(obj):\n        return inspect.getargspec(obj.__init__).args[1:]\n    elif hasattr(obj, '__call__'):\n        return inspect.getargspec(obj.__call__).args[1:]\n    else:\n        raise TypeError(\"Can't inspect signature of '%s' object.\" % obj)",
    "docstring": "Get a list of argument names for a callable."
  },
  {
    "code": "def before_insert(mapper, conn, target):\n        if target.sequence_id is None:\n            from ambry.orm.exc import DatabaseError\n            raise DatabaseError('Must have sequence_id before insertion')\n        assert (target.name == 'id') == (target.sequence_id == 1), (target.name, target.sequence_id)\n        Column.before_update(mapper, conn, target)",
    "docstring": "event.listen method for Sqlalchemy to set the seqience_id for this\n        object and create an ObjectNumber value for the id_"
  },
  {
    "code": "def add_element_list(self, elt_list, **kwargs):\n        for e in elt_list:\n            self.add_element(Element(e, **kwargs))",
    "docstring": "Helper to add a list of similar elements to the current section.\n        Element names will be used as an identifier."
  },
  {
    "code": "def _make_scm(current_target):\n    tool_key = devpipeline_core.toolsupport.choose_tool_key(\n        current_target, devpipeline_scm._SCM_TOOL_KEYS\n    )\n    return devpipeline_core.toolsupport.tool_builder(\n        current_target.config, tool_key, devpipeline_scm.SCMS, current_target\n    )",
    "docstring": "Create an Scm for a component.\n\n    Arguments\n    component - The component being operated on."
  },
  {
    "code": "def enableEffect(self, name, **kwargs):\n        if name not in VALID_EFFECTS:\n            raise KeyError(\"KezMenu doesn't know an effect of type %s\" % name)\n        self.__getattribute__(\n            '_effectinit_{}'.format(name.replace(\"-\", \"_\"))\n        )(name, **kwargs)",
    "docstring": "Enable an effect in the KezMenu."
  },
  {
    "code": "def echo(self, variableName, verbose=False):\n        PARAMS={\"variableName\":variableName}\n        response=api(url=self.__url+\"/echo\", PARAMS=PARAMS, verbose=verbose)\n        return response",
    "docstring": "The echo command will display the value of the variable specified by the\n        variableName argument, or all variables if variableName is not provided.\n\n        :param variableName: The name of the variable or '*' to display the value of all variables.\n        :param verbose: print more"
  },
  {
    "code": "def save_model(self, fname, include_unsigned_edges=False):\n        sif_str = self.print_model(include_unsigned_edges)\n        with open(fname, 'wb') as fh:\n            fh.write(sif_str.encode('utf-8'))",
    "docstring": "Save the assembled model's SIF string into a file.\n\n        Parameters\n        ----------\n        fname : str\n            The name of the file to save the SIF into.\n        include_unsigned_edges : bool\n            If True, includes edges with an unknown activating/inactivating\n            relationship (e.g., most PTMs). Default is False."
  },
  {
    "code": "def _init_baremetal_trunk_interfaces(self, port_seg, segment):\n        list_to_init = []\n        inactive_switch = []\n        connections = self._get_baremetal_connections(\n                          port_seg, False, True)\n        for switch_ip, intf_type, port, is_native, _ in connections:\n            try:\n                nxos_db.get_switch_if_host_mappings(\n                    switch_ip,\n                    nexus_help.format_interface_name(intf_type, port))\n            except excep.NexusHostMappingNotFound:\n                if self.is_switch_active(switch_ip):\n                    list_to_init.append(\n                        (switch_ip, intf_type, port, is_native, 0))\n                else:\n                    inactive_switch.append(\n                        (switch_ip, intf_type, port, is_native, 0))\n        self.driver.initialize_baremetal_switch_interfaces(list_to_init)\n        host_id = port_seg.get('dns_name')\n        if host_id is None:\n            host_id = const.RESERVED_PORT_HOST_ID\n        list_to_init += inactive_switch\n        for switch_ip, intf_type, port, is_native, ch_grp in list_to_init:\n            nxos_db.add_host_mapping(\n                host_id,\n                switch_ip,\n                nexus_help.format_interface_name(intf_type, port),\n                ch_grp, False)",
    "docstring": "Initialize baremetal switch interfaces and DB entry.\n\n        With baremetal transactions, the interfaces are not\n        known during initialization so they must be initialized\n        when the transactions are received.\n        * Reserved switch entries are added if needed.\n        * Reserved port entries are added.\n        * Determine if port channel is configured on the\n          interface and store it so we know to create a port-channel\n          binding instead of that defined in the transaction.\n          In this case, the RESERVED binding is the ethernet interface\n          with port-channel stored in channel-group field.\n          When this channel-group is not 0, we know to create a port binding\n          as a port-channel instead of interface ethernet."
  },
  {
    "code": "def gen_shell(opts, **kwargs):\n    if kwargs['winrm']:\n        try:\n            import saltwinshell\n            shell = saltwinshell.Shell(opts, **kwargs)\n        except ImportError:\n            log.error('The saltwinshell library is not available')\n            sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n    else:\n        shell = Shell(opts, **kwargs)\n    return shell",
    "docstring": "Return the correct shell interface for the target system"
  },
  {
    "code": "def validate_redirect_uri(value):\n    sch, netloc, path, par, query, fra = urlparse(value)\n    if not (sch and netloc):\n        raise InvalidRedirectURIError()\n    if sch != 'https':\n        if ':' in netloc:\n            netloc, port = netloc.split(':', 1)\n        if not (netloc in ('localhost', '127.0.0.1') and sch == 'http'):\n            raise InsecureTransportError()",
    "docstring": "Validate a redirect URI.\n\n    Redirect URIs must be a valid URL and use https unless the host is\n    localhost for which http is accepted.\n\n    :param value: The redirect URI."
  },
  {
    "code": "def QueryFields(r, what, fields=None):\n    query = {}\n    if fields is not None:\n        query[\"fields\"] = \",\".join(fields)\n    return r.request(\"get\", \"/2/query/%s/fields\" % what, query=query)",
    "docstring": "Retrieves available fields for a resource.\n\n    @type what: string\n    @param what: Resource name, one of L{constants.QR_VIA_RAPI}\n    @type fields: list of string\n    @param fields: Requested fields\n\n    @rtype: string\n    @return: job id"
  },
  {
    "code": "def interactive_shell():\n    print('You should be able to read and update the \"counter[0]\" variable from this shell.')\n    try:\n        yield from embed(globals=globals(), return_asyncio_coroutine=True, patch_stdout=True)\n    except EOFError:\n        loop.stop()",
    "docstring": "Coroutine that starts a Python REPL from which we can access the global\n    counter variable."
  },
  {
    "code": "def place_analysis_summary_report(feature, parent):\n    _ = feature, parent\n    analysis_dir = get_analysis_dir(exposure_place['key'])\n    if analysis_dir:\n        return get_impact_report_as_string(analysis_dir)\n    return None",
    "docstring": "Retrieve an HTML place analysis table report from a multi exposure\n    analysis."
  },
  {
    "code": "def program_rtr(self, args, rout_id, namespace=None):\n        if namespace is None:\n            namespace = self.find_rtr_namespace(rout_id)\n        if namespace is None:\n            LOG.error(\"Unable to find namespace for router %s\", rout_id)\n            return False\n        final_args = ['ip', 'netns', 'exec', namespace] + args\n        try:\n            utils.execute(final_args, root_helper=self.root_helper)\n        except Exception as e:\n            LOG.error(\"Unable to execute %(cmd)s. \"\n                      \"Exception: %(exception)s\",\n                      {'cmd': final_args, 'exception': e})\n            return False\n        return True",
    "docstring": "Execute the command against the namespace."
  },
  {
    "code": "def get_logger_data(self):\n        return {\n            address : stream_capturer[0].dump_handler_config_data()\n            for address, stream_capturer in self._stream_capturers.iteritems()\n        }",
    "docstring": "Return data on managed loggers.\n\n        Returns a dictionary of managed logger configuration data. The format\n        is primarily controlled by the\n        :func:`SocketStreamCapturer.dump_handler_config_data` function::\n\n            {\n                <capture address>: <list of handler config for data capturers>\n            }"
  },
  {
    "code": "def hkdf(self, chaining_key, input_key_material, dhlen=64):\n        if len(chaining_key) != self.HASHLEN:\n            raise HashError(\"Incorrect chaining key length\")\n        if len(input_key_material) not in (0, 32, dhlen):\n            raise HashError(\"Incorrect input key material length\")\n        temp_key = self.hmac_hash(chaining_key, input_key_material)\n        output1 = self.hmac_hash(temp_key, b'\\x01')\n        output2 = self.hmac_hash(temp_key, output1 + b'\\x02')\n        return output1, output2",
    "docstring": "Hash-based key derivation function\n\n        Takes a ``chaining_key'' byte sequence of len HASHLEN, and an\n        ``input_key_material'' byte sequence with length either zero\n        bytes, 32 bytes or dhlen bytes.\n\n        Returns two byte sequences of length HASHLEN"
  },
  {
    "code": "def intersection(self, other, sort=False):\n        self._validate_sort_keyword(sort)\n        self._assert_can_do_setop(other)\n        other, result_names = self._convert_can_do_setop(other)\n        if self.equals(other):\n            return self\n        self_tuples = self._ndarray_values\n        other_tuples = other._ndarray_values\n        uniq_tuples = set(self_tuples) & set(other_tuples)\n        if sort is None:\n            uniq_tuples = sorted(uniq_tuples)\n        if len(uniq_tuples) == 0:\n            return MultiIndex(levels=self.levels,\n                              codes=[[]] * self.nlevels,\n                              names=result_names, verify_integrity=False)\n        else:\n            return MultiIndex.from_arrays(lzip(*uniq_tuples), sortorder=0,\n                                          names=result_names)",
    "docstring": "Form the intersection of two MultiIndex objects.\n\n        Parameters\n        ----------\n        other : MultiIndex or array / Index of tuples\n        sort : False or None, default False\n            Sort the resulting MultiIndex if possible\n\n            .. versionadded:: 0.24.0\n\n            .. versionchanged:: 0.24.1\n\n               Changed the default from ``True`` to ``False``, to match\n               behaviour from before 0.24.0\n\n        Returns\n        -------\n        Index"
  },
  {
    "code": "def check(self, return_code=0):\n        ret = self.call().return_code\n        ok = ret == return_code\n        if not ok:\n            raise EasyProcessError(\n                self, 'check error, return code is not {0}!'.format(return_code))\n        return self",
    "docstring": "Run command with arguments. Wait for command to complete. If the\n        exit code was as expected and there is no exception then return,\n        otherwise raise EasyProcessError.\n\n        :param return_code: int, expected return code\n        :rtype: self"
  },
  {
    "code": "def get_playback_callback(resampler, samplerate, params):\n    def callback(outdata, frames, time, _):\n        last_fmphase = getattr(callback, 'last_fmphase', 0)\n        df = params['fm_gain'] * resampler.read(frames)\n        df = np.pad(df, (0, frames - len(df)), mode='constant')\n        t = time.outputBufferDacTime + np.arange(frames) / samplerate\n        phase = 2 * np.pi * params['carrier_frequency'] * t\n        fmphase = last_fmphase + 2 * np.pi * np.cumsum(df) / samplerate\n        outdata[:, 0] = params['output_volume'] * np.cos(phase + fmphase)\n        callback.last_fmphase = fmphase[-1]\n    return callback",
    "docstring": "Return a sound playback callback.\n\n    Parameters\n    ----------\n    resampler\n        The resampler from which samples are read.\n    samplerate : float\n        The sample rate.\n    params : dict\n        Parameters for FM generation."
  },
  {
    "code": "def open(self):\n        if self.fd is not None:\n            raise self.AlreadyOpened()\n        logger.debug(\"Opening %s...\" % (TUN_KO_PATH, ))\n        self.fd = os.open(TUN_KO_PATH, os.O_RDWR)\n        logger.debug(\"Opening %s tunnel '%s'...\" % (self.mode_name.upper(), self.pattern, ))\n        try:\n            ret = fcntl.ioctl(self.fd, self.TUNSETIFF, struct.pack(\"16sH\", self.pattern, self.mode | self.no_pi))\n        except IOError, e:\n            if e.errno == 1:\n                logger.error(\"Cannot open a %s tunnel because the operation is not permitted.\" % (self.mode_name.upper(), ))\n                raise self.NotPermitted()\n            raise\n        self.name = ret[:16].strip(\"\\x00\")\n        logger.info(\"Tunnel '%s' opened.\" % (self.name, ))",
    "docstring": "Create the tunnel.\n            If the tunnel is already opened, the function will\n            raised an AlreadyOpened exception."
  },
  {
    "code": "def decode(self, data: bytes) -> bytes:\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            data = self._decode_content_transfer(data)\n        if CONTENT_ENCODING in self.headers:\n            return self._decode_content(data)\n        return data",
    "docstring": "Decodes data according the specified Content-Encoding\n        or Content-Transfer-Encoding headers value."
  },
  {
    "code": "def parse_url(url):\n    if not RE_PROTOCOL_SERVER.match(url):\n        raise Exception(\"URL should begin with `protocol://domain`\")\n    protocol, server, path, _, _, _ = urlparse.urlparse(url)\n    return protocol, server",
    "docstring": "Takes a URL string and returns its protocol and server"
  },
  {
    "code": "def calc_all_routes_info(self, npaths=3, real_time=True, stop_at_bounds=False, time_delta=0):\n        routes = self.get_route(npaths, time_delta)\n        results = {route['routeName']: self._add_up_route(route['results'], real_time=real_time, stop_at_bounds=stop_at_bounds) for route in routes}\n        route_time = [route[0] for route in results.values()]\n        route_distance = [route[1] for route in results.values()]\n        self.log.info('Time %.2f - %.2f minutes, distance %.2f - %.2f km.', min(route_time), max(route_time), min(route_distance), max(route_distance))\n        return results",
    "docstring": "Calculate all route infos."
  },
  {
    "code": "def _from_rest_ignore(model, props):\n    fields = model.all_fields\n    for prop in props.keys():\n        if prop not in fields:\n            del props[prop]",
    "docstring": "Purge fields that are completely unknown"
  },
  {
    "code": "def get_directorship_heads(self, val):\n        __ldap_group_ou__ = \"cn=groups,cn=accounts,dc=csh,dc=rit,dc=edu\"\n        res = self.__con__.search_s(\n                __ldap_group_ou__,\n                ldap.SCOPE_SUBTREE,\n                \"(cn=eboard-%s)\" % val,\n                ['member'])\n        ret = []\n        for member in res[0][1]['member']:\n            try:\n                ret.append(member.decode('utf-8'))\n            except UnicodeDecodeError:\n                ret.append(member)\n            except KeyError:\n                continue\n        return [CSHMember(self,\n                dn.split('=')[1].split(',')[0],\n                True)\n                for dn in ret]",
    "docstring": "Get the head of a directorship\n\n        Arguments:\n        val -- the cn of the directorship"
  },
  {
    "code": "def rolling_max(self, window_start, window_end, min_observations=None):\n        min_observations = self.__check_min_observations(min_observations)\n        agg_op = '__builtin__max__'\n        return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, min_observations))",
    "docstring": "Calculate a new SArray of the maximum value of different subsets over\n        this SArray.\n\n        The subset that the maximum is calculated over is defined as an\n        inclusive range relative to the position to each value in the SArray,\n        using `window_start` and `window_end`. For a better understanding of\n        this, see the examples below.\n\n        Parameters\n        ----------\n        window_start : int\n            The start of the subset to calculate the maximum relative to the\n            current value.\n\n        window_end : int\n            The end of the subset to calculate the maximum relative to the current\n            value. Must be greater than `window_start`.\n\n        min_observations : int\n            Minimum number of non-missing observations in window required to\n            calculate the maximum (otherwise result is None). None signifies that\n            the entire window must not include a missing value. A negative\n            number throws an error.\n\n        Returns\n        -------\n        out : SArray\n\n        Examples\n        --------\n        >>> import pandas\n        >>> sa = SArray([1,2,3,4,5])\n        >>> series = pandas.Series([1,2,3,4,5])\n\n        A rolling max with a window including the previous 2 entries including\n        the current:\n        >>> sa.rolling_max(-2,0)\n        dtype: int\n        Rows: 5\n        [None, None, 3, 4, 5]\n\n        Pandas equivalent:\n        >>> pandas.rolling_max(series, 3)\n        0   NaN\n        1   NaN\n        2     3\n        3     4\n        4     5\n        dtype: float64\n\n        Same rolling max operation, but 2 minimum observations:\n        >>> sa.rolling_max(-2,0,min_observations=2)\n        dtype: int\n        Rows: 5\n        [None, 2, 3, 4, 5]\n\n        Pandas equivalent:\n        >>> pandas.rolling_max(series, 3, min_periods=2)\n        0    NaN\n        1      2\n        2      3\n        3      4\n        4      5\n        dtype: float64\n\n        A rolling max with a size of 3, centered around the current:\n        >>> sa.rolling_max(-1,1)\n        dtype: int\n        Rows: 5\n        [None, 3, 4, 5, None]\n\n        Pandas equivalent:\n        >>> pandas.rolling_max(series, 3, center=True)\n        0   NaN\n        1     3\n        2     4\n        3     5\n        4   NaN\n        dtype: float64\n\n        A rolling max with a window including the current and the 2 entries\n        following:\n        >>> sa.rolling_max(0,2)\n        dtype: int\n        Rows: 5\n        [3, 4, 5, None, None]\n\n        A rolling max with a window including the previous 2 entries NOT\n        including the current:\n        >>> sa.rolling_max(-2,-1)\n        dtype: int\n        Rows: 5\n        [None, None, 2, 3, 4]"
  },
  {
    "code": "def wait_for_ready(self, instance_id, limit=14400, delay=10, pending=False):\n        now = time.time()\n        until = now + limit\n        mask = \"mask[id, lastOperatingSystemReload[id], activeTransaction, provisionDate]\"\n        instance = self.get_hardware(instance_id, mask=mask)\n        while now <= until:\n            if utils.is_ready(instance, pending):\n                return True\n            transaction = utils.lookup(instance, 'activeTransaction', 'transactionStatus', 'friendlyName')\n            snooze = min(delay, until - now)\n            LOGGER.info(\"%s - %d not ready. Auto retry in %ds\", transaction, instance_id, snooze)\n            time.sleep(snooze)\n            instance = self.get_hardware(instance_id, mask=mask)\n            now = time.time()\n        LOGGER.info(\"Waiting for %d expired.\", instance_id)\n        return False",
    "docstring": "Determine if a Server is ready.\n\n        A server is ready when no transactions are running on it.\n\n        :param int instance_id: The instance ID with the pending transaction\n        :param int limit: The maximum amount of seconds to wait.\n        :param int delay: The number of seconds to sleep before checks. Defaults to 10."
  },
  {
    "code": "def list_commands(self, ctx):\n        commands_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'commands')\n        command_list = [name for __, name, ispkg in pkgutil.iter_modules([commands_path]) if ispkg]\n        command_list.sort()\n        return command_list",
    "docstring": "List CLI commands\n        @type   ctx:    Context\n        @rtype: list"
  },
  {
    "code": "def extract_lzma(archive, compression, cmd, verbosity, interactive, outdir):\n    cmdlist = [util.shell_quote(cmd), '--format=lzma']\n    if verbosity > 1:\n        cmdlist.append('-v')\n    outfile = util.get_single_outfile(outdir, archive)\n    cmdlist.extend(['-c', '-d', '--', util.shell_quote(archive), '>',\n        util.shell_quote(outfile)])\n    return (cmdlist, {'shell': True})",
    "docstring": "Extract an LZMA archive."
  },
  {
    "code": "def del_windows_env_var(key):\n    if not isinstance(key, text_type):\n        raise TypeError(\"%r not of type %r\" % (key, text_type))\n    status = winapi.SetEnvironmentVariableW(key, None)\n    if status == 0:\n        raise ctypes.WinError()",
    "docstring": "Delete an env var.\n\n    Raises:\n        WindowsError"
  },
  {
    "code": "def process_array(elt, ascii=False):\n    del ascii\n    chld = elt.getchildren()\n    if len(chld) > 1:\n        raise ValueError()\n    chld = chld[0]\n    try:\n        name, current_type, scale = CASES[chld.tag](chld)\n        size = None\n    except ValueError:\n        name, current_type, size, scale = CASES[chld.tag](chld)\n    del name\n    myname = elt.get(\"name\") or elt.get(\"label\")\n    if elt.get(\"length\").startswith(\"$\"):\n        length = int(VARIABLES[elt.get(\"length\")[1:]])\n    else:\n        length = int(elt.get(\"length\"))\n    if size is not None:\n        return (myname, current_type, (length, ) + size, scale)\n    else:\n        return (myname, current_type, (length, ), scale)",
    "docstring": "Process an 'array' tag."
  },
  {
    "code": "def limit(self, limit):\n        clone = self._clone()\n        if isinstance(limit, int):\n            clone._limit = limit\n        return clone",
    "docstring": "Limit number of records"
  },
  {
    "code": "def _update_mask(self):\n        self._threshold_mask = self._data > self._theta\n        self._threshold_mask_v = self._data > self._theta/np.abs(self._v)",
    "docstring": "Pre-compute masks for speed."
  },
  {
    "code": "def read_csv(filename):\n    with open(filename, 'r') as f:\n        r = csv.reader(f)\n        next(r)\n        wm = list(r)\n    for i, row in enumerate(wm):\n        row[1:4] = map(int, row[1:4])\n        row[4] = float(row[4])\n    return wm",
    "docstring": "Read a list of week-matrices from a CSV file."
  },
  {
    "code": "def get_mount_targets(filesystemid=None,\n                      mounttargetid=None,\n                      keyid=None,\n                      key=None,\n                      profile=None,\n                      region=None,\n                      **kwargs):\n    result = None\n    client = _get_conn(key=key, keyid=keyid, profile=profile, region=region)\n    if filesystemid:\n        response = client.describe_mount_targets(FileSystemId=filesystemid)\n        result = response[\"MountTargets\"]\n        while \"NextMarker\" in response:\n            response = client.describe_mount_targets(FileSystemId=filesystemid,\n                                                 Marker=response[\"NextMarker\"])\n            result.extend(response[\"MountTargets\"])\n    elif mounttargetid:\n        response = client.describe_mount_targets(MountTargetId=mounttargetid)\n        result = response[\"MountTargets\"]\n    return result",
    "docstring": "Get all the EFS mount point properties for a specific filesystemid or\n    the properties for a specific mounttargetid. One or the other must be\n    specified\n\n    filesystemid\n        (string) - ID of the file system whose mount targets to list\n                   Must be specified if mounttargetid is not\n\n    mounttargetid\n        (string) - ID of the mount target to have its properties returned\n                   Must be specified if filesystemid is not\n\n    returns\n        (list[dict]) - list of all mount point properties\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'my-minion' boto_efs.get_mount_targets"
  },
  {
    "code": "def plot_scatter_matrix(self, freq=None, title=None,\n                            figsize=(10, 10), **kwargs):\n        if title is None:\n            title = self._get_default_plot_title(\n                freq, 'Return Scatter Matrix')\n        plt.figure()\n        ser = self._get_series(freq).to_returns().dropna()\n        pd.scatter_matrix(ser, figsize=figsize, **kwargs)\n        return plt.suptitle(title)",
    "docstring": "Wrapper around pandas' scatter_matrix.\n\n        Args:\n            * freq (str): Data frequency used for display purposes.\n                Refer to pandas docs for valid freq strings.\n            * figsize ((x,y)): figure size\n            * title (str): Title if default not appropriate\n            * kwargs: passed to pandas' scatter_matrix method"
  },
  {
    "code": "def cleanup():\n    to_stop = STARTED_TASKS.copy()\n    if to_stop:\n        print \"Cleaning up...\"\n    for task in to_stop:\n        try:\n            task.stop()\n        except:\n            etype, value, trace = sys.exc_info()\n            if not (isinstance(value, OSError) and value.errno == 3):\n                print ''.join(format_exception(etype, value, trace, None))\n            continue",
    "docstring": "Stop all started tasks on system exit.\n\n    Note: This only handles signals caught by the atexit module by default.\n    SIGKILL, for instance, will not be caught, so cleanup is not guaranteed in\n    all cases."
  },
  {
    "code": "def rename(self, oldkey, newkey):\n        if oldkey in self.scalars:\n            the_list = self.scalars\n        elif oldkey in self.sections:\n            the_list = self.sections\n        else:\n            raise KeyError('Key \"%s\" not found.' % oldkey)\n        pos = the_list.index(oldkey)\n        val = self[oldkey]\n        dict.__delitem__(self, oldkey)\n        dict.__setitem__(self, newkey, val)\n        the_list.remove(oldkey)\n        the_list.insert(pos, newkey)\n        comm = self.comments[oldkey]\n        inline_comment = self.inline_comments[oldkey]\n        del self.comments[oldkey]\n        del self.inline_comments[oldkey]\n        self.comments[newkey] = comm\n        self.inline_comments[newkey] = inline_comment",
    "docstring": "Change a keyname to another, without changing position in sequence.\n\n        Implemented so that transformations can be made on keys,\n        as well as on values. (used by encode and decode)\n\n        Also renames comments."
  },
  {
    "code": "def push_plugin(self, name):\n        url = self._url('/plugins/{0}/pull', name)\n        headers = {}\n        registry, repo_name = auth.resolve_repository_name(name)\n        header = auth.get_config_header(self, registry)\n        if header:\n            headers['X-Registry-Auth'] = header\n        res = self._post(url, headers=headers)\n        self._raise_for_status(res)\n        return self._stream_helper(res, decode=True)",
    "docstring": "Push a plugin to the registry.\n\n            Args:\n                name (string): Name of the plugin to upload. The ``:latest``\n                    tag is optional, and is the default if omitted.\n\n            Returns:\n                ``True`` if successful"
  },
  {
    "code": "def arcfour_drop(key, n=3072):\n\taf = arcfour(key)\n\t[af.next() for c in range(n)]\n\treturn af",
    "docstring": "Return a generator for the RC4-drop pseudorandom keystream given by \n\t   the key and number of bytes to drop passed as arguments. Dropped bytes\n\t   default to the more conservative 3072, NOT the SCAN default of 768."
  },
  {
    "code": "def get_context_data(self, **kwargs):\n        data = {}\n        if self._contextual_vals.current_level == 1 and self.max_levels > 1:\n            data['sub_menu_template'] = self.sub_menu_template.template.name\n        data.update(kwargs)\n        return super().get_context_data(**data)",
    "docstring": "Include the name of the sub menu template in the context. This is\n        purely for backwards compatibility. Any sub menus rendered as part of\n        this menu will call `sub_menu_template` on the original menu instance\n        to get an actual `Template`"
  },
  {
    "code": "def initialize_watcher(samples):\n    work_dir = dd.get_in_samples(samples, dd.get_work_dir)\n    ww = WorldWatcher(work_dir,\n                      is_on=any([dd.get_cwl_reporting(d[0]) for d in samples]))\n    ww.initialize(samples)\n    return ww",
    "docstring": "check to see if cwl_reporting is set for any samples,\n    and if so, initialize a WorldWatcher object from a set of samples,"
  },
  {
    "code": "def write_branch_data(self, file):\n        writer = self._get_writer(file)\n        writer.writerow(BRANCH_ATTRS)\n        for branch in self.case.branches:\n            writer.writerow([getattr(branch, a) for a in BRANCH_ATTRS])",
    "docstring": "Writes branch data as CSV."
  },
  {
    "code": "def _load_preset(self, path):\n        try:\n            with open(path, 'r') as f:\n                presetBody = json.load(f)\n        except IOError as e:\n            raise PresetException(\"IOError: \" + e.strerror)\n        except ValueError as e:\n            raise PresetException(\"JSON decoding error: \" + str(e))\n        except Exception as e:\n            raise PresetException(str(e))\n        try:\n            preset = Preset(presetBody)\n        except PresetException as e:\n            e.message = \"Bad format: \" + e.message\n            raise\n        if(preset.id in self.presets):\n            raise PresetException(\"Duplicate preset id: \" + preset.id)\n        else:\n            self.presets[preset.id] = preset",
    "docstring": "load, validate and store a single preset file"
  },
  {
    "code": "def timeit(hosts=None,\n           stmt=None,\n           warmup=30,\n           repeat=None,\n           duration=None,\n           concurrency=1,\n           output_fmt=None,\n           fail_if=None,\n           sample_mode='reservoir'):\n    num_lines = 0\n    log = Logger(output_fmt)\n    with Runner(hosts, concurrency, sample_mode) as runner:\n        version_info = aio.run(runner.client.get_server_version)\n        for line in as_statements(lines_from_stdin(stmt)):\n            runner.warmup(line, warmup)\n            timed_stats = runner.run(line, iterations=repeat, duration=duration)\n            r = Result(\n                version_info=version_info,\n                statement=line,\n                timed_stats=timed_stats,\n                concurrency=concurrency\n            )\n            log.result(r)\n            if fail_if:\n                eval_fail_if(fail_if, r)\n        num_lines += 1\n    if num_lines == 0:\n        raise SystemExit(\n            'No SQL statements provided. Use --stmt or provide statements via stdin')",
    "docstring": "Run the given statement a number of times and return the runtime stats\n\n    Args:\n        fail-if: An expression that causes cr8 to exit with a failure if it\n            evaluates to true.\n            The expression can contain formatting expressions for:\n                - runtime_stats\n                - statement\n                - meta\n                - concurrency\n                - bulk_size\n            For example:\n                --fail-if \"{runtime_stats.mean} > 1.34\""
  },
  {
    "code": "def load_config(filename, config_dir=None, copy_default_config=True):\n    if not config_dir:\n        config_file = os.path.join(get_default_config_path(), filename)\n    else:\n        config_file = os.path.join(config_dir, filename)\n        if not os.path.isfile(config_file):\n            if copy_default_config:\n                logger.info('Config file {} not found, I will create a '\n                            'default version'.format(config_file))\n                make_directory(config_dir)\n                shutil.copy(os.path.join(package_path, 'config', filename.\n                                         replace('.cfg', '_default.cfg')),\n                            config_file)\n            else:\n                message = 'Config file {} not found.'.format(config_file)\n                logger.error(message)\n                raise FileNotFoundError(message)\n    if len(cfg.read(config_file)) == 0:\n        message = 'Config file {} not found or empty.'.format(config_file)\n        logger.error(message)\n        raise FileNotFoundError(message)\n    global _loaded\n    _loaded = True",
    "docstring": "Loads the specified config file.\n\n    Parameters\n    -----------\n    filename : :obj:`str`\n        Config file name, e.g. 'config_grid.cfg'.\n    config_dir : :obj:`str`, optional\n        Path to config file. If None uses default edisgo config directory\n        specified in config file 'config_system.cfg' in section 'user_dirs'\n        by subsections 'root_dir' and 'config_dir'. Default: None.\n    copy_default_config : Boolean\n        If True copies a default config file into `config_dir` if the\n        specified config file does not exist. Default: True."
  },
  {
    "code": "def extract_cookies(self, response, request):\n        _debug(\"extract_cookies: %s\", response.info())\n        self._cookies_lock.acquire()\n        try:\n            self._policy._now = self._now = int(time.time())\n            for cookie in self.make_cookies(response, request):\n                if self._policy.set_ok(cookie, request):\n                    _debug(\" setting cookie: %s\", cookie)\n                    self.set_cookie(cookie)\n        finally:\n            self._cookies_lock.release()",
    "docstring": "Extract cookies from response, where allowable given the request."
  },
  {
    "code": "def nodes(self):\n        if self._nodes is None:\n            self._nodes = layout_nodes(self, only_nodes=True)\n        return self._nodes",
    "docstring": "Computes the node positions the first time they are requested\n        if no explicit node information was supplied."
  },
  {
    "code": "def data(self):\n        data = super(DynamicListSerializer, self).data\n        processed_data = ReturnDict(\n            SideloadingProcessor(self, data).data,\n            serializer=self\n        ) if self.child.envelope else ReturnList(\n            data,\n            serializer=self\n        )\n        processed_data = post_process(processed_data)\n        return processed_data",
    "docstring": "Get the data, after performing post-processing if necessary."
  },
  {
    "code": "def send_message(self, message):\n        with self._instance_lock:\n            if message is None:\n                Global.LOGGER.error(\"can't deliver a null messages\")\n                return\n            if message.sender is None:\n                Global.LOGGER.error(f\"can't deliver anonymous messages with body {message.body}\")\n                return\n            if message.receiver is None:\n                Global.LOGGER.error(\n                    f\"can't deliver message from {message.sender}: recipient not specified\")\n                return\n            if message.message is None:\n                Global.LOGGER.error(f\"can't deliver message with no body from {message.sender}\")\n                return\n            sender = \"*\" + message.sender + \"*\"\n            self.socket.send_multipart(\n                [bytes(sender, 'utf-8'), pickle.dumps(message)])\n            if Global.CONFIG_MANAGER.tracing_mode:\n                Global.LOGGER.debug(\"dispatched : \"\n                                    + message.sender\n                                    + \"-\"\n                                    + message.message\n                                    + \"-\"\n                                    + message.receiver)\n            self.dispatched = self.dispatched + 1",
    "docstring": "Dispatch a message using 0mq"
  },
  {
    "code": "def add_line(self, string):\n        self.code_strings.append(string)\n        code = ''\n        if len(self.code_strings) == 1:\n            code = '(setv result ' + self.code_strings[0] + ')'\n        if len(self.code_strings) > 1:\n            code = '(setv result (and ' + ' '.join(self.code_strings) + '))'\n        self._compiled_ast_and_expr = self.__compile_code(code_string=code)",
    "docstring": "Adds a line to the LISP code to execute\n\n        :param string: The line to add\n        :return: None"
  },
  {
    "code": "def _handle_progress(self, total, progress_callback):\n    current = 0\n    while True:\n      current += yield\n      try:\n        progress_callback(current, total)\n      except Exception:\n        _LOG.exception('Progress callback raised an exception. %s',\n                       progress_callback)\n        continue",
    "docstring": "Calls the callback with the current progress and total ."
  },
  {
    "code": "def resource_record_set(self, name, record_type, ttl, rrdatas):\n        return ResourceRecordSet(name, record_type, ttl, rrdatas, zone=self)",
    "docstring": "Construct a resource record set bound to this zone.\n\n        :type name: str\n        :param name: Name of the record set.\n\n        :type record_type: str\n        :param record_type: RR type\n\n        :type ttl: int\n        :param ttl: TTL for the RR, in seconds\n\n        :type rrdatas: list of string\n        :param rrdatas: resource data for the RR\n\n        :rtype: :class:`google.cloud.dns.resource_record_set.ResourceRecordSet`\n        :returns: a new ``ResourceRecordSet`` instance"
  },
  {
    "code": "def random_deinterleave(text, separator_symbol=\"X\"):\n  words = text.strip().split(\" \")\n  n = len(words)\n  if n <= 1:\n    return text, \"\"\n  cut = [False] * n\n  cut[0] = True\n  num_cuts = int(math.exp(random.uniform(0, math.log(n))))\n  for _ in range(num_cuts):\n    cut[random.randint(1, n -1)] = True\n  out = [[], []]\n  part = random.randint(0, 1)\n  for i in range(n):\n    if cut[i]:\n      out[part].append(separator_symbol)\n      part = 1 - part\n    out[part].append(words[i])\n  return \" \".join(out[0]), \" \".join(out[1])",
    "docstring": "Create a fill-in-the-blanks training example from text.\n\n  Split on spaces, then cut into segments at random points.  Alternate segments\n  are assigned to the two output strings. separator_symbol separates segments\n  within each of the outputs.\n\n  example:\n    text=\"The quick brown fox jumps over the lazy dog.\"\n    returns: (\"X quick brown X the lazy X\", \"The X fox jumps over X dog.\")\n\n  The two outputs can also be reversed to yield an instance of the same problem.\n\n  Args:\n    text: a string\n    separator_symbol: a string\n  Returns:\n    a pair of strings"
  },
  {
    "code": "def pubmed_citation(args=sys.argv[1:], out=sys.stdout):\n    parser = argparse.ArgumentParser(\n        description='Get a citation using a PubMed ID or PubMed URL')\n    parser.add_argument('query', help='PubMed ID or PubMed URL')\n    parser.add_argument(\n        '-m', '--mini', action='store_true', help='get mini citation')\n    parser.add_argument(\n        '-e', '--email', action='store', help='set user email', default='')\n    args = parser.parse_args(args=args)\n    lookup = PubMedLookup(args.query, args.email)\n    publication = Publication(lookup, resolve_doi=False)\n    if args.mini:\n        out.write(publication.cite_mini() + '\\n')\n    else:\n        out.write(publication.cite() + '\\n')",
    "docstring": "Get a citation via the command line using a PubMed ID or PubMed URL"
  },
  {
    "code": "def expanded_transform(self):\n        segments = self._expand_transform(self.transform)\n        if segments:\n            segments[0]['datatype'] = self.valuetype_class\n            for s in segments:\n                s['column'] = self\n        else:\n            segments = [self.make_xform_seg(datatype=self.valuetype_class, column=self)]\n        return segments",
    "docstring": "Expands the transform string into segments"
  },
  {
    "code": "def ReadFromFile(self, artifacts_reader, filename):\n    for artifact_definition in artifacts_reader.ReadFile(filename):\n      self.RegisterDefinition(artifact_definition)",
    "docstring": "Reads artifact definitions into the registry from a file.\n\n    Args:\n      artifacts_reader (ArtifactsReader): an artifacts reader.\n      filename (str): name of the file to read from."
  },
  {
    "code": "def encrypt_put_item(encrypt_method, crypto_config_method, write_method, **kwargs):\n    crypto_config, ddb_kwargs = crypto_config_method(**kwargs)\n    ddb_kwargs[\"Item\"] = encrypt_method(\n        item=ddb_kwargs[\"Item\"],\n        crypto_config=crypto_config.with_item(_item_transformer(encrypt_method)(ddb_kwargs[\"Item\"])),\n    )\n    return write_method(**ddb_kwargs)",
    "docstring": "Transparently encrypt an item before putting it to the table.\n\n    :param callable encrypt_method: Method to use to encrypt items\n    :param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig`\n    :param callable write_method: Method that writes to the table\n    :param **kwargs: Keyword arguments to pass to ``write_method``\n    :return: DynamoDB response\n    :rtype: dict"
  },
  {
    "code": "def close(self, response):\n        LOGGER.info('Closing [%s]', os.getpid())\n        if not self.database.is_closed():\n            self.database.close()\n        return response",
    "docstring": "Close connection to database."
  },
  {
    "code": "def _get_deployment_instance_diagnostics(awsclient, deployment_id, instance_id):\n    client_codedeploy = awsclient.get_client('codedeploy')\n    request = {\n        'deploymentId': deployment_id,\n        'instanceId': instance_id\n    }\n    response = client_codedeploy.get_deployment_instance(**request)\n    for i, event in enumerate(response['instanceSummary']['lifecycleEvents']):\n        if event['status'] == 'Failed':\n            return event['diagnostics']['errorCode'], \\\n                   event['diagnostics']['scriptName'], \\\n                   event['diagnostics']['message'], \\\n                   event['diagnostics']['logTail']\n    return None",
    "docstring": "Gets you the diagnostics details for the first 'Failed' event.\n\n    :param awsclient:\n    :param deployment_id:\n    :param instance_id:\n    return: None or (error_code, script_name, message, log_tail)"
  },
  {
    "code": "def onStopping(self):\n        if self.config.STACK_COMPANION == 1:\n            add_stop_time(self.ledger_dir, self.utc_epoch())\n        self.logstats()\n        self.reset()\n        for ledger in self.ledgers:\n            try:\n                ledger.stop()\n            except Exception as ex:\n                logger.exception('{} got exception while stopping ledger: {}'.format(self, ex))\n        self.nodestack.stop()\n        self.clientstack.stop()\n        self.closeAllKVStores()\n        self._info_tool.stop()\n        self.mode = None\n        self.execute_hook(NodeHooks.POST_NODE_STOPPED)",
    "docstring": "Actions to be performed on stopping the node.\n\n        - Close the UDP socket of the nodestack"
  },
  {
    "code": "def get(file_name, key):\n    db = XonoticDB.load_path(file_name)\n    value = db.get(key)\n    if value is None:\n        sys.exit(1)\n    else:\n        click.echo(value)",
    "docstring": "Print a value for the specified key. If key is not found xon_db exists with code 1."
  },
  {
    "code": "def get_user(request):\n    if not hasattr(request, '_cached_user'):\n        request._cached_user = auth_get_user(request)\n    return request._cached_user",
    "docstring": "Returns a cached copy of the user if it exists or calls `auth_get_user`\n    otherwise."
  },
  {
    "code": "def produce(self, *args, **kwargs):\n        new_plugins = []\n        for p in self._plugins:\n            r = p(*args, **kwargs)\n            new_plugins.append(r)\n        return PluginManager(new_plugins)",
    "docstring": "Produce a new set of plugins, treating the current set as plugin\n        factories."
  },
  {
    "code": "def add(addon, dev, interactive):\n    application = get_current_application()\n    application.add(\n        addon,\n        dev=dev,\n        interactive=interactive\n    )",
    "docstring": "Add a dependency.\n\n    Examples:\n\n    $ django add dynamic-rest==1.5.0\n\n    + dynamic-rest == 1.5.0"
  },
  {
    "code": "def call_api(self, table, column, value, **kwargs):\n        try:\n            output_format = kwargs.pop('output_format')\n        except KeyError:\n            output_format = self.output_format\n        url_list = [self.base_url, table, column,\n                    quote(value), 'rows']\n        rows_count = self._number_of_rows(**kwargs)\n        url_list.append(rows_count)\n        url_string = '/'.join(url_list)\n        xml_data = urlopen(url_string).read()\n        data = self._format_data(output_format, xml_data)\n        return data",
    "docstring": "Exposed method to connect and query the EPA's API."
  },
  {
    "code": "def get_embed_url(self, targeting=None, recirc=None):\n        url = getattr(settings, \"VIDEOHUB_EMBED_URL\", self.DEFAULT_VIDEOHUB_EMBED_URL)\n        url = url.format(self.id)\n        if targeting is not None:\n            for k, v in sorted(targeting.items()):\n                url += '&{0}={1}'.format(k, v)\n        if recirc is not None:\n            url += '&recirc={0}'.format(recirc)\n        return url",
    "docstring": "gets a canonical path to an embedded iframe of the video from the hub\n\n        :return: the path to create an embedded iframe of the video\n        :rtype: str"
  },
  {
    "code": "def visit_WhileStatement(self, node):\n        while self.visit(node.condition):\n            result = self.visit(node.compound)\n            if result is not None:\n                return result",
    "docstring": "Visitor for `WhileStatement` AST node."
  },
  {
    "code": "def extract_relationtypes(rs3_xml_tree):\n    return {rel.attrib['name']: rel.attrib['type']\n            for rel in rs3_xml_tree.iter('rel')\n            if 'type' in rel.attrib}",
    "docstring": "extracts the allowed RST relation names and relation types from\n    an RS3 XML file.\n\n    Parameters\n    ----------\n    rs3_xml_tree : lxml.etree._ElementTree\n        lxml ElementTree representation of an RS3 XML file\n\n    Returns\n    -------\n    relations : dict of (str, str)\n        Returns a dictionary with RST relation names as keys (str)\n        and relation types (either 'rst' or 'multinuc') as values\n        (str)."
  },
  {
    "code": "def __xinclude_lxml(target, source, env):\n    from lxml import etree\n    doc = etree.parse(str(source[0]))\n    doc.xinclude()\n    try:\n        doc.write(str(target[0]), xml_declaration=True, \n                  encoding=\"UTF-8\", pretty_print=True)\n    except:\n        pass\n    return None",
    "docstring": "Resolving XIncludes, using the lxml module."
  },
  {
    "code": "def get_version(self):\n        ptr = self._get_version_func(self.alpr_pointer)\n        version_number = ctypes.cast(ptr, ctypes.c_char_p).value\n        version_number = _convert_from_charp(version_number)\n        self._free_json_mem_func(ctypes.c_void_p(ptr))\n        return version_number",
    "docstring": "This gets the version of OpenALPR\n\n        :return: Version information"
  },
  {
    "code": "def read(self, b=None):\n        data = self.__wrapped__.read(b)\n        self.__tee.write(data)\n        return data",
    "docstring": "Reads data from source, copying it into ``tee`` before returning.\n\n        :param int b: number of bytes to read"
  },
  {
    "code": "def tuple(self, r):\n        m, m1 = self.args\n        r, z = divmod(r, m1)\n        r, k = divmod(r, 12)\n        u, w = divmod(r, m)\n        return u, w, k, z",
    "docstring": "Converts the linear_index `q` into an pegasus_index\n\n        Parameters\n        ----------\n        r : int\n            The linear_index node label\n\n        Returns\n        -------\n        q : tuple\n            The pegasus_index node label corresponding to r"
  },
  {
    "code": "def parse_to_ast(source_code: str) -> List[ast.stmt]:\n    class_types, reformatted_code = pre_parse(source_code)\n    if '\\x00' in reformatted_code:\n        raise ParserException('No null bytes (\\\\x00) allowed in the source code.')\n    parsed_ast = ast.parse(reformatted_code)\n    annotate_and_optimize_ast(parsed_ast, reformatted_code, class_types)\n    return parsed_ast.body",
    "docstring": "Parses the given vyper source code and returns a list of python AST objects\n    for all statements in the source.  Performs pre-processing of source code\n    before parsing as well as post-processing of the resulting AST.\n\n    :param source_code: The vyper source code to be parsed.\n    :return: The post-processed list of python AST objects for each statement in\n        ``source_code``."
  },
  {
    "code": "def after_request(self, response):\n        if response is not None and request is not None:\n            if request.endpoint in [None, \"static\"]:\n                return response\n        self.compile()\n        return response",
    "docstring": "after_request handler for compiling the compass projects with\n        each request."
  },
  {
    "code": "def launch():\n    if launched():\n        check_version()\n        os.chdir(ROOT)\n        return\n    if not os.path.exists(BIN_LORE):\n        missing = ' %s virtualenv is missing.' % APP\n        if '--launched' in sys.argv:\n            sys.exit(ansi.error() + missing + ' Please check for errors during:\\n $ lore install\\n')\n        else:\n            print(ansi.warning() + missing)\n            import lore.__main__\n            lore.__main__.install(None, None)\n    reboot('--env-launched')",
    "docstring": "Ensure that python is running from the Lore virtualenv past this point."
  },
  {
    "code": "def load(self, configuration):\n        try:\n            self.config = yaml.load(open(configuration, \"rb\"))\n        except IOError:\n            try:\n                self.config = yaml.load(configuration)\n            except ParserError, e:\n                raise ParserError('Error parsing config: %s' % e)\n        if isinstance(self.config, dict):\n            self.customer = self.config.get('customer', {})\n            self.instances_dict = self.config.get('instances', {})\n            self.web2py_dir = self.config.get('web2py', None)\n            self.api_type = self.config.get('api_type', 'jsonrpc')\n            self.valid = True\n        else:\n            self.customer = {}\n            self.instances_dict = {}\n            self.web2py_dir = None\n            self.valid = False",
    "docstring": "Load a YAML configuration file.\n\n        :param configuration: Configuration filename or YAML string"
  },
  {
    "code": "def evaluate_callables(data):\n    sequence = ((k, v() if callable(v) else v) for k, v in data.items())\n    return type(data)(sequence)",
    "docstring": "Call any callable values in the input dictionary;\n    return a new dictionary containing the evaluated results.\n    Useful for lazily evaluating default values in ``build`` methods.\n\n    >>> data = {\"spam\": \"ham\", \"eggs\": (lambda: 123)}\n    >>> result = evaluate_callables(data)\n    >>> result == {'eggs': 123, 'spam': 'ham'}\n    True"
  },
  {
    "code": "def extend (name, values):\n    assert isinstance(name, basestring)\n    assert is_iterable_typed(values, basestring)\n    name = add_grist (name)\n    __validate_feature (name)\n    feature = __all_features [name]\n    if feature.implicit:\n        for v in values:\n            if v in __implicit_features:\n                raise BaseException (\"'%s' is already associated with the feature '%s'\" % (v, __implicit_features [v]))\n            __implicit_features[v] = feature\n    if values and not feature.values and not(feature.free or feature.optional):\n        feature.set_default(values[0])\n    feature.add_values(values)",
    "docstring": "Adds the given values to the given feature."
  },
  {
    "code": "def EXCHANGE(classical_reg1, classical_reg2):\n    left = unpack_classical_reg(classical_reg1)\n    right = unpack_classical_reg(classical_reg2)\n    return ClassicalExchange(left, right)",
    "docstring": "Produce an EXCHANGE instruction.\n\n    :param classical_reg1: The first classical register, which gets modified.\n    :param classical_reg2: The second classical register, which gets modified.\n    :return: A ClassicalExchange instance."
  },
  {
    "code": "def upsert_sweep(self, config):\n        mutation = gql(\n)\n        def no_retry_400_or_404(e):\n            if not isinstance(e, requests.HTTPError):\n                return True\n            if e.response.status_code != 400 and e.response.status_code != 404:\n                return True\n            body = json.loads(e.response.content)\n            raise UsageError(body['errors'][0]['message'])\n        response = self.gql(mutation, variable_values={\n            'config': yaml.dump(config),\n            'description': config.get(\"description\"),\n            'entityName': self.settings(\"entity\"),\n            'projectName': self.settings(\"project\")},\n            check_retry_fn=no_retry_400_or_404)\n        return response['upsertSweep']['sweep']['name']",
    "docstring": "Upsert a sweep object.\n\n        Args:\n            config (str): sweep config (will be converted to yaml)"
  },
  {
    "code": "async def updateconfig(self):\n        \"Reload configurations, remove non-exist servers, add new servers, and leave others unchanged\"\n        exists = {}\n        for s in self.connections:\n            exists[(s.protocol.vhost, s.rawurl)] = s\n        self._createServers(self, '', exists = exists)\n        for _,v in exists.items():\n            await v.shutdown()\n            self.connections.remove(v)",
    "docstring": "Reload configurations, remove non-exist servers, add new servers, and leave others unchanged"
  },
  {
    "code": "def write_file(path, contents):\n\tos.makedirs(os.path.dirname(path), exist_ok=True)\n\twith open(path, \"w\") as file:\n\t\tfile.write(contents)",
    "docstring": "Write contents to a local file."
  },
  {
    "code": "def ext_from_filename(filename):\n    try:\n        base, ext = filename.lower().rsplit(\".\", 1)\n    except ValueError:\n        return ''\n    ext = \".{0}\".format(ext)\n    all_exts = [x.extension for x in chain(magic_header_array,\n                                           magic_footer_array)]\n    if base[-4:].startswith(\".\"):\n        long_ext = base[-4:] + ext\n        if long_ext in all_exts:\n            return long_ext\n    return ext",
    "docstring": "Scan a filename for it's extension.\n\n    :param filename: string of the filename\n    :return: the extension off the end (empty string if it can't find one)"
  },
  {
    "code": "def focus_last_child(self):\n        w, focuspos = self.get_focus()\n        child = self._tree.last_child_position(focuspos)\n        if child is not None:\n            self.set_focus(child)",
    "docstring": "move focus to last child of currently focussed one"
  },
  {
    "code": "def coef_(self):\n        coef = numpy.zeros(self.n_features_ + 1, dtype=float)\n        for estimator in self.estimators_:\n            coef[estimator.component] += self.learning_rate * estimator.coef_\n        return coef",
    "docstring": "Return the aggregated coefficients.\n\n        Returns\n        -------\n        coef_ : ndarray, shape = (n_features + 1,)\n            Coefficients of features. The first element denotes the intercept."
  },
  {
    "code": "def _fluent_params(self, fluents, ordering) -> FluentParamsList:\n        variables = []\n        for fluent_id in ordering:\n            fluent = fluents[fluent_id]\n            param_types = fluent.param_types\n            objects = ()\n            names = []\n            if param_types is None:\n                names = [fluent.name]\n            else:\n                objects = tuple(self.object_table[ptype]['objects'] for ptype in param_types)\n                for values in itertools.product(*objects):\n                    values = ','.join(values)\n                    var_name = '{}({})'.format(fluent.name, values)\n                    names.append(var_name)\n            variables.append((fluent_id, names))\n        return tuple(variables)",
    "docstring": "Returns the instantiated `fluents` for the given `ordering`.\n\n        For each fluent in `fluents`, it instantiates each parameter\n        type w.r.t. the contents of the object table.\n\n        Returns:\n            Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name\n            and a list of instantiated fluents represented as strings."
  },
  {
    "code": "def get_klass_parents(gi_name):\n    res = []\n    parents = __HIERARCHY_GRAPH.predecessors(gi_name)\n    if not parents:\n        return []\n    __get_parent_link_recurse(parents[0], res)\n    return res",
    "docstring": "Returns a sorted list of qualified symbols representing\n    the parents of the klass-like symbol named gi_name"
  },
  {
    "code": "def _add_widget(self, widget):\n        widgets = self.widgets()\n        widgets += [widget]\n        self._save_customization(widgets)",
    "docstring": "Add a widget to the customization.\n\n        Will save the widget to KE-chain.\n\n        :param widget: The widget (specific json dict) to be added\n        :type widget: dict"
  },
  {
    "code": "def request_callback_answer(\n        self,\n        chat_id: Union[int, str],\n        message_id: int,\n        callback_data: bytes\n    ):\n        return self.send(\n            functions.messages.GetBotCallbackAnswer(\n                peer=self.resolve_peer(chat_id),\n                msg_id=message_id,\n                data=callback_data\n            ),\n            retries=0,\n            timeout=10\n        )",
    "docstring": "Use this method to request a callback answer from bots.\n        This is the equivalent of clicking an inline button containing callback data.\n\n        Args:\n            chat_id (``int`` | ``str``):\n                Unique identifier (int) or username (str) of the target chat.\n                For your personal cloud (Saved Messages) you can simply use \"me\" or \"self\".\n                For a contact that exists in your Telegram address book you can use his phone number (str).\n\n            message_id (``int``):\n                The message id the inline keyboard is attached on.\n\n            callback_data (``bytes``):\n                Callback data associated with the inline button you want to get the answer from.\n\n        Returns:\n            The answer containing info useful for clients to display a notification at the top of the chat screen\n            or as an alert.\n\n        Raises:\n            :class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.\n            ``TimeoutError`` if the bot fails to answer within 10 seconds."
  },
  {
    "code": "def transform(row, table):\n    'Transform row \"link\" into full URL and add \"state\" based on \"name\"'\n    data = row._asdict()\n    data[\"link\"] = urljoin(\"https://pt.wikipedia.org\", data[\"link\"])\n    data[\"name\"], data[\"state\"] = regexp_city_state.findall(data[\"name\"])[0]\n    return data",
    "docstring": "Transform row \"link\" into full URL and add \"state\" based on \"name\""
  },
  {
    "code": "def check_type_declaration(parameter_names, parameter_types):\n    if len(parameter_names) != len(parameter_types):\n        raise Exception(\"Number of method parameters ({}) does not match number of \"\n                        \"declared types ({})\"\n                        .format(len(parameter_names), len(parameter_types)))\n    for parameter_name in parameter_names:\n        if parameter_name not in parameter_types:\n            raise Exception(\"Parameter '{}' does not have a declared type\".format(parameter_name))",
    "docstring": "Checks that exactly the given parameter names have declared types.\n\n    :param parameter_names: The names of the parameters in the method declaration\n    :type parameter_names: list[str]\n    :param parameter_types: Parameter type by name\n    :type parameter_types: dict[str, type]"
  },
  {
    "code": "def _set_group_selection(self):\n        grp = self.grouper\n        if not (self.as_index and\n                getattr(grp, 'groupings', None) is not None and\n                self.obj.ndim > 1 and\n                self._group_selection is None):\n            return\n        ax = self.obj._info_axis\n        groupers = [g.name for g in grp.groupings\n                    if g.level is None and g.in_axis]\n        if len(groupers):\n            self._group_selection = ax.difference(Index(groupers),\n                                                  sort=False).tolist()\n            self._reset_cache('_selected_obj')",
    "docstring": "Create group based selection.\n\n        Used when selection is not passed directly but instead via a grouper.\n\n        NOTE: this should be paired with a call to _reset_group_selection"
  },
  {
    "code": "def bin_stream(stream, content_type, status='200 OK',\n                   headers=None):\n        def_headers = [('Content-Type', content_type)]\n        if headers:\n            def_headers += headers\n        status_headers = StatusAndHeaders(status, def_headers)\n        return WbResponse(status_headers, value=stream)",
    "docstring": "Utility method for constructing a binary response.\n\n        :param Any stream: The response body stream\n        :param str content_type: The content-type of the response\n        :param str status: The HTTP status line\n        :param list[tuple[str, str]] headers: Additional headers for this response\n        :return: WbResponse that is a binary stream\n        :rtype: WbResponse"
  },
  {
    "code": "def hello_message(self, invert_hello=False):\n\t\tif invert_hello is False:\n\t\t\treturn self.__gouverneur_message\n\t\thello_message = []\n\t\tfor i in range(len(self.__gouverneur_message) - 1, -1, -1):\n\t\t\thello_message.append(self.__gouverneur_message[i])\n\t\treturn bytes(hello_message)",
    "docstring": "Return message header.\n\n\t\t:param invert_hello: whether to return the original header (in case of False value) or reversed \\\n\t\tone (in case of True value).\n\t\t:return: bytes"
  },
  {
    "code": "def load_tlds():\n    file = os.path.join(os.path.dirname(__file__),\n                        'assets',\n                        'tlds-alpha-by-domain.txt')\n    with open(file) as fobj:\n        return [elem for elem in fobj.read().lower().splitlines()[1:]\n                if \"--\" not in elem]",
    "docstring": "Load all legal TLD extensions from assets"
  },
  {
    "code": "def get_coordinate_system(self):\n        coordinate_list = ['specimen']\n        initial_coordinate = 'specimen'\n        for specimen in self.specimens:\n            if 'geographic' not in coordinate_list and self.Data[specimen]['zijdblock_geo']:\n                coordinate_list.append('geographic')\n                initial_coordinate = 'geographic'\n            if 'tilt-corrected' not in coordinate_list and self.Data[specimen]['zijdblock_tilt']:\n                coordinate_list.append('tilt-corrected')\n        return initial_coordinate, coordinate_list",
    "docstring": "Check self.Data for available coordinate systems.\n\n        Returns\n        ---------\n        initial_coordinate, coordinate_list : str, list\n        i.e., 'geographic', ['specimen', 'geographic']"
  },
  {
    "code": "def xpath(self, *args, **kwargs):\n        if \"smart_strings\" not in kwargs:\n            kwargs[\"smart_strings\"] = False\n        return self.resource.xpath(*args, **kwargs)",
    "docstring": "Perform XPath on the passage XML\n\n        :param args: Ordered arguments for etree._Element().xpath()\n        :param kwargs: Named arguments\n        :return: Result list\n        :rtype: list(etree._Element)"
  },
  {
    "code": "def read_ucs2(self, num_chars):\n        buf = readall(self, num_chars * 2)\n        return ucs2_codec.decode(buf)[0]",
    "docstring": "Reads num_chars UCS2 string from the stream"
  },
  {
    "code": "def get_cached_manylinux_wheel(self, package_name, package_version, disable_progress=False):\n        cached_wheels_dir = os.path.join(tempfile.gettempdir(), 'cached_wheels')\n        if not os.path.isdir(cached_wheels_dir):\n            os.makedirs(cached_wheels_dir)\n        wheel_file = '{0!s}-{1!s}-{2!s}'.format(package_name, package_version, self.manylinux_wheel_file_suffix)\n        wheel_path = os.path.join(cached_wheels_dir, wheel_file)\n        if not os.path.exists(wheel_path) or not zipfile.is_zipfile(wheel_path):\n            wheel_url = self.get_manylinux_wheel_url(package_name, package_version)\n            if not wheel_url:\n                return None\n            print(\" - {}=={}: Downloading\".format(package_name, package_version))\n            with open(wheel_path, 'wb') as f:\n                self.download_url_with_progress(wheel_url, f, disable_progress)\n            if not zipfile.is_zipfile(wheel_path):\n                return None\n        else:\n            print(\" - {}=={}: Using locally cached manylinux wheel\".format(package_name, package_version))\n        return wheel_path",
    "docstring": "Gets the locally stored version of a manylinux wheel. If one does not exist, the function downloads it."
  },
  {
    "code": "def no_spikes(tolerance):\n    def no_spikes(curve):\n        diff = np.abs(curve - curve.despike())\n        return np.count_nonzero(diff) < tolerance\n    return no_spikes",
    "docstring": "Arg ``tolerance`` is the number of spiky samples allowed."
  },
  {
    "code": "def _is_child(self, parent, child):\n        parent_parts = tuple(self._split_table_name(parent))\n        child_parts = tuple(self._split_table_name(child))\n        if parent_parts == child_parts:\n            return False\n        return parent_parts == child_parts[: len(parent_parts)]",
    "docstring": "Returns whether a key is strictly a child of another key.\n        AoT siblings are not considered children of one another."
  },
  {
    "code": "def nearest_intersection_idx(a, b):\n    difference = a - b\n    sign_change_idx, = np.nonzero(np.diff(np.sign(difference)))\n    return sign_change_idx",
    "docstring": "Determine the index of the point just before two lines with common x values.\n\n    Parameters\n    ----------\n    a : array-like\n        1-dimensional array of y-values for line 1\n    b : array-like\n        1-dimensional array of y-values for line 2\n\n    Returns\n    -------\n        An array of indexes representing the index of the values\n        just before the intersection(s) of the two lines."
  },
  {
    "code": "def table(tab):\n    global open_tables\n    if tab in open_tables:\n        yield open_tables[tab]\n    else:\n        open_tables[tab] = iptc.Table(tab)\n        open_tables[tab].refresh()\n        open_tables[tab].autocommit = False\n        yield open_tables[tab]\n        open_tables[tab].commit()\n        del open_tables[tab]",
    "docstring": "Access IPTables transactionally in a uniform way.\n\n    Ensures all access is done without autocommit and that only the outer\n    most task commits, and also ensures we refresh once and commit once."
  },
  {
    "code": "def finish(self):\n        for obj in self.current_tweens:\n            for tween in self.current_tweens[obj]:\n                tween.finish()\n        self.current_tweens = {}",
    "docstring": "jump the the last frame of all tweens"
  },
  {
    "code": "def add_key_value(self, key, value):\n        key = self._metadata_map.get(key, key)\n        if key in ['dateAdded', 'lastModified']:\n            self._indicator_data[key] = self._utils.format_datetime(\n                value, date_format='%Y-%m-%dT%H:%M:%SZ'\n            )\n        elif key == 'confidence':\n            self._indicator_data[key] = int(value)\n        elif key == 'rating':\n            self._indicator_data[key] = float(value)\n        else:\n            self._indicator_data[key] = value",
    "docstring": "Add custom field to Indicator object.\n\n        .. note:: The key must be the exact name required by the batch schema.\n\n        Example::\n\n            file_hash = tcex.batch.file('File', '1d878cdc391461e392678ba3fc9f6f32')\n            file_hash.add_key_value('size', '1024')\n\n        Args:\n            key (str): The field key to add to the JSON batch data.\n            value (str): The field value to add to the JSON batch data."
  },
  {
    "code": "def top_level_domain(self, tld_type: Optional[TLDType] = None) -> str:\n        key = self._validate_enum(item=tld_type, enum=TLDType)\n        return self.random.choice(TLD[key])",
    "docstring": "Return random top level domain.\n\n        :param tld_type: Enum object DomainType\n        :return: Top level domain.\n        :raises NonEnumerableError: if tld_type not in DomainType."
  },
  {
    "code": "def set_credentials(self, username, password=None, region=None,\n            tenant_id=None, authenticate=False):\n        self.username = username\n        self.password = password\n        self.tenant_id = tenant_id\n        if region:\n            self.region = region\n        if authenticate:\n            self.authenticate()",
    "docstring": "Sets the username and password directly."
  },
  {
    "code": "def assignrepr_values2(values, prefix):\n    lines = []\n    blanks = ' '*len(prefix)\n    for (idx, subvalues) in enumerate(values):\n        if idx == 0:\n            lines.append('%s%s,' % (prefix, repr_values(subvalues)))\n        else:\n            lines.append('%s%s,' % (blanks, repr_values(subvalues)))\n    lines[-1] = lines[-1][:-1]\n    return '\\n'.join(lines)",
    "docstring": "Return a prefixed and properly aligned string representation\n    of the given 2-dimensional value matrix using function |repr|.\n\n    >>> from hydpy.core.objecttools import assignrepr_values2\n    >>> import numpy\n    >>> print(assignrepr_values2(numpy.eye(3), 'test(') + ')')\n    test(1.0, 0.0, 0.0,\n         0.0, 1.0, 0.0,\n         0.0, 0.0, 1.0)\n\n    Functions |assignrepr_values2| works also on empty iterables:\n\n    >>> print(assignrepr_values2([[]], 'test(') + ')')\n    test()"
  },
  {
    "code": "def _determine_weights(self, other, settings):\n        first_is_used = settings['first']['required'] or \\\n            self.first and other.first\n        first_weight = settings['first']['weight'] if first_is_used else 0\n        middle_is_used = settings['middle']['required'] or \\\n            self.middle and other.middle\n        middle_weight = settings['middle']['weight'] if middle_is_used else 0\n        last_is_used = settings['last']['required'] or \\\n            self.last and other.last\n        last_weight = settings['last']['weight'] if last_is_used else 0\n        return first_weight, middle_weight, last_weight",
    "docstring": "Return weights of name components based on whether or not they were\n        omitted"
  },
  {
    "code": "def draw_flat_samples(**kwargs):\n    nsamples = kwargs.get('nsamples', 1)\n    min_mass = kwargs.get('min_mass', 1.)\n    max_mass = kwargs.get('max_mass', 2.)\n    m1 = np.random.uniform(min_mass, max_mass, nsamples)\n    m2 = np.random.uniform(min_mass, max_mass, nsamples)\n    return np.maximum(m1, m2), np.minimum(m1, m2)",
    "docstring": "Draw samples for uniform in mass\n\n        Parameters\n        ----------\n        **kwargs: string\n           Keyword arguments as model parameters and number of samples\n\n        Returns\n        -------\n        array\n           The first mass\n        array\n           The second mass"
  },
  {
    "code": "def verify(self):\n        self.init.verify()\n        self.sim.verify()\n        if self.init.firstdate > self.sim.firstdate:\n            raise ValueError(\n                f'The first date of the initialisation period '\n                f'({self.init.firstdate}) must not be later '\n                f'than the first date of the simulation period '\n                f'({self.sim.firstdate}).')\n        elif self.init.lastdate < self.sim.lastdate:\n            raise ValueError(\n                f'The last date of the initialisation period '\n                f'({self.init.lastdate}) must not be earlier '\n                f'than the last date of the simulation period '\n                f'({self.sim.lastdate}).')\n        elif self.init.stepsize != self.sim.stepsize:\n            raise ValueError(\n                f'The initialization stepsize ({self.init.stepsize}) '\n                f'must be identical with the simulation stepsize '\n                f'({self.sim.stepsize}).')\n        else:\n            try:\n                self.init[self.sim.firstdate]\n            except ValueError:\n                raise ValueError(\n                    'The simulation time grid is not properly '\n                    'alligned on the initialization time grid.')",
    "docstring": "Raise an |ValueError| it the different time grids are\n        inconsistent."
  },
  {
    "code": "def ensure_compatible_admin(view):\n    def wrapper(request, *args, **kwargs):\n        user_roles = request.user.user_data.get('roles', [])\n        if len(user_roles) != 1:\n            context = {\n                'message': 'I need to be able to manage user accounts. '\n                           'My username is %s' % request.user.username\n            }\n            return render(request, 'mtp_common/user_admin/incompatible-admin.html', context=context)\n        return view(request, *args, **kwargs)\n    return wrapper",
    "docstring": "Ensures that the user is in exactly one role.\n    Other checks could be added, such as requiring one prison if in prison-clerk role."
  },
  {
    "code": "def get_max(qs, field):\n    max_field = '%s__max' % field\n    num = qs.aggregate(Max(field))[max_field]\n    return num if num else 0",
    "docstring": "get max for queryset.\n\n    qs: queryset\n    field: The field name to max."
  },
  {
    "code": "def source_files(mongodb_path):\n    for root, dirs, files in os.walk(mongodb_path):\n        for filename in files:\n            if 'dbtests' in root:\n                continue\n            if filename.endswith(('.cpp', '.c', '.h')):\n                yield os.path.join(root, filename)",
    "docstring": "Find source files."
  },
  {
    "code": "def _col_widths2xls(self, worksheets):\n        xls_max_cols, xls_max_tabs = self.xls_max_cols, self.xls_max_tabs\n        dict_grid = self.code_array.dict_grid\n        for col, tab in dict_grid.col_widths:\n            if col < xls_max_cols and tab < xls_max_tabs:\n                pys_width = dict_grid.col_widths[(col, tab)]\n                xls_width = self.pys_width2xls_width(pys_width)\n                worksheets[tab].col(col).width = xls_width",
    "docstring": "Writes col_widths to xls file\n\n        Format: <col>\\t<tab>\\t<value>\\n"
  },
  {
    "code": "def partition(a, sz): \n    return [a[i:i+sz] for i in range(0, len(a), sz)]",
    "docstring": "splits iterables a in equal parts of size sz"
  },
  {
    "code": "def refresh_toc(self, refresh_done_callback, toc_cache):\n        self._useV2 = self.cf.platform.get_protocol_version() >= 4\n        toc_fetcher = TocFetcher(self.cf, ParamTocElement,\n                                 CRTPPort.PARAM, self.toc,\n                                 refresh_done_callback, toc_cache)\n        toc_fetcher.start()",
    "docstring": "Initiate a refresh of the parameter TOC."
  },
  {
    "code": "def silhouette(max_iters=100, optimize=True, plot=True):\n    try:import pods\n    except ImportError:\n        print('pods unavailable, see https://github.com/sods/ods for example datasets')\n        return\n    data = pods.datasets.silhouette()\n    m = GPy.models.GPRegression(data['X'], data['Y'])\n    if optimize:\n        m.optimize(messages=True, max_iters=max_iters)\n    print(m)\n    return m",
    "docstring": "Predict the pose of a figure given a silhouette. This is a task from Agarwal and Triggs 2004 ICML paper."
  },
  {
    "code": "def _open_ok(self, args):\n        self.known_hosts = args.read_shortstr()\n        AMQP_LOGGER.debug('Open OK! known_hosts [%s]' % self.known_hosts)\n        return None",
    "docstring": "signal that the connection is ready\n\n        This method signals to the client that the connection is ready\n        for use.\n\n        PARAMETERS:\n            known_hosts: shortstr"
  },
  {
    "code": "def on_trial_complete(self,\n                          trial_id,\n                          result=None,\n                          error=False,\n                          early_terminated=False):\n        ng_trial_info = self._live_trial_mapping.pop(trial_id)\n        if result:\n            self._nevergrad_opt.tell(ng_trial_info, -result[self._reward_attr])",
    "docstring": "Passes the result to Nevergrad unless early terminated or errored.\n\n        The result is internally negated when interacting with Nevergrad\n        so that Nevergrad Optimizers can \"maximize\" this value,\n        as it minimizes on default."
  },
  {
    "code": "def draw_char_screen(self):\n\t\tself.screen = Image.new(\"RGB\", (self.height, self.width))\n\t\tself.drawer = ImageDraw.Draw(self.screen)\n\t\tfor sy, line in enumerate(self.char_buffer):\n\t\t\tfor sx, tinfo in enumerate(line):\n\t\t\t\tself.drawer.text((sx * 6, sy * 9), tinfo[0], fill=tinfo[1:])\n\t\tself.output_device.interrupt()",
    "docstring": "Draws the output buffered in the char_buffer."
  },
  {
    "code": "def extract_attr_for_match(items, **kwargs):\n  query_arg = None\n  for arg, value in kwargs.items():\n    if value == -1:\n      assert query_arg is None, \"Only single query arg (-1 valued) is allowed\"\n      query_arg = arg\n  result = []\n  filterset = set(kwargs.keys())\n  for item in items:\n    match = True\n    assert filterset.issubset(\n      item.keys()), \"Filter set contained %s which was not in record %s\" % (\n      filterset.difference(item.keys()),\n      item)\n    for arg in item:\n      if arg == query_arg:\n        continue\n      if arg in kwargs:\n        if item[arg] != kwargs[arg]:\n          match = False\n          break\n    if match:\n      result.append(item[query_arg])\n  assert len(result) <= 1, \"%d values matched %s, only allow 1\" % (\n    len(result), kwargs)\n  if result:\n    return result[0]\n  return None",
    "docstring": "Helper method to get attribute value for an item matching some criterion.\n  Specify target criteria value as dict, with target attribute having value -1\n\n  Example:\n    to extract state of vpc matching given vpc id\n\n  response = [{'State': 'available', 'VpcId': 'vpc-2bb1584c'}]\n  extract_attr_for_match(response, State=-1, VpcId='vpc-2bb1584c') #=> 'available"
  },
  {
    "code": "def _cryptodome_cipher(key, iv):\n    return AES.new(key, AES.MODE_CFB, iv, segment_size=128)",
    "docstring": "Build a Pycryptodome AES Cipher object.\n\n    :param bytes key: Encryption key\n    :param bytes iv: Initialization vector\n    :returns: AES Cipher instance"
  },
  {
    "code": "def get_configs(__pkg: str, __name: str = 'config') -> List[str]:\n    dirs = [user_config(__pkg), ]\n    dirs.extend(path.expanduser(path.sep.join([d, __pkg]))\n                for d in getenv('XDG_CONFIG_DIRS', '/etc/xdg').split(':'))\n    configs = []\n    for dname in reversed(dirs):\n        test_path = path.join(dname, __name)\n        if path.exists(test_path):\n            configs.append(test_path)\n    return configs",
    "docstring": "Return all configs for given package.\n\n    Args:\n        __pkg: Package name\n        __name: Configuration file name"
  },
  {
    "code": "def from_datetime(self, dt):\n        global _last_timestamp\n        epoch = datetime(1970, 1, 1, tzinfo=dt.tzinfo)\n        offset = epoch.tzinfo.utcoffset(epoch).total_seconds() if epoch.tzinfo else 0\n        timestamp = (dt  - epoch).total_seconds() - offset\n        node = None\n        clock_seq = None\n        nanoseconds = int(timestamp * 1e9)\n        timestamp = int(nanoseconds // 100) + 0x01b21dd213814000\n        if clock_seq is None:\n            import random\n            clock_seq = random.randrange(1 << 14)\n        time_low = timestamp & 0xffffffff\n        time_mid = (timestamp >> 32) & 0xffff\n        time_hi_version = (timestamp >> 48) & 0x0fff\n        clock_seq_low = clock_seq & 0xff\n        clock_seq_hi_variant = (clock_seq >> 8) & 0x3f\n        if node is None:\n            node = getnode()\n        return pyUUID(fields=(time_low, time_mid, time_hi_version,\n                            clock_seq_hi_variant, clock_seq_low, node), version=1)",
    "docstring": "generates a UUID for a given datetime\n\n        :param dt: datetime\n        :type dt: datetime\n        :return:"
  },
  {
    "code": "def sinogram_as_rytov(uSin, u0=1, align=True):\n    r\n    ndims = len(uSin.shape)\n    phiR = np.angle(uSin / u0)\n    lna = np.log(np.absolute(uSin / u0))\n    if ndims == 2:\n        phiR[:] = np.unwrap(phiR, axis=-1)\n    else:\n        for ii in range(len(phiR)):\n            phiR[ii] = unwrap_phase(phiR[ii], seed=47)\n    if align:\n        align_unwrapped(phiR)\n    rytovSin = 1j * phiR + lna\n    return u0 * rytovSin",
    "docstring": "r\"\"\"Convert the complex wave field sinogram to the Rytov phase\n\n    This method applies the Rytov approximation to the\n    recorded complex wave sinogram. To achieve this, the following\n    filter is applied:\n\n    .. math::\n        u_\\mathrm{B}(\\mathbf{r}) = u_\\mathrm{0}(\\mathbf{r})\n            \\ln\\!\\left(\n            \\frac{u_\\mathrm{R}(\\mathbf{r})}{u_\\mathrm{0}(\\mathbf{r})}\n             +1 \\right)\n\n    This filter step effectively replaces the Born approximation\n    :math:`u_\\mathrm{B}(\\mathbf{r})` with the Rytov approximation\n    :math:`u_\\mathrm{R}(\\mathbf{r})`, assuming that the scattered\n    field is equal to\n    :math:`u(\\mathbf{r})\\approx u_\\mathrm{R}(\\mathbf{r})+\n    u_\\mathrm{0}(\\mathbf{r})`.\n\n\n    Parameters\n    ----------\n    uSin: 2d or 3d complex ndarray\n        The sinogram of the complex wave\n        :math:`u_\\mathrm{R}(\\mathbf{r}) + u_\\mathrm{0}(\\mathbf{r})`.\n        The first axis iterates through the angles :math:`\\phi_0`.\n    u0: ndarray of dimension as `uSin` or less, or int.\n        The incident plane wave\n        :math:`u_\\mathrm{0}(\\mathbf{r})` at the detector.\n        If `u0` is \"1\", it is assumed that the data is already\n        background-corrected (\n        `uSin` :math:`= \\frac{u_\\mathrm{R}(\\mathbf{r})}{\n        u_\\mathrm{0}(\\mathbf{r})} + 1`\n        ). Note that if the reconstruction distance :math:`l_\\mathrm{D}`\n        of the original experiment is non-zero and `u0` is set to 1,\n        then the reconstruction will be wrong; the field is not focused\n        to the center of the reconstruction volume.\n    align: bool\n        Tries to correct for a phase offset in the phase sinogram.\n\n    Returns\n    -------\n    uB: 2d or 3d real ndarray\n        The Rytov-filtered complex sinogram\n        :math:`u_\\mathrm{B}(\\mathbf{r})`.\n\n    See Also\n    --------\n    skimage.restoration.unwrap_phase: phase unwrapping"
  },
  {
    "code": "def equation_of_time(day):\n    day_of_year = day.toordinal() - date(day.year, 1, 1).toordinal()\n    A = EARTH_ORIBITAL_VELOCITY * (day_of_year + 10)\n    B = A + 1.914 * sin(radians(EARTH_ORIBITAL_VELOCITY * (day_of_year - 2)))\n    movement_on_equatorial_plane = degrees(\n        atan2(\n            tan(radians(B)),\n            cos(EARTH_AXIS_TILT)\n        )\n    )\n    eot_half_turns = (A - movement_on_equatorial_plane) / 180\n    result = 720 * (eot_half_turns - int(eot_half_turns + 0.5))\n    return radians(result)",
    "docstring": "Compute the equation of time for the given date.\n\n    Uses formula described at\n    https://en.wikipedia.org/wiki/Equation_of_time#Alternative_calculation\n\n    :param day: The datetime.date to compute the equation of time for\n    :returns: The angle, in radians, of the Equation of Time"
  },
  {
    "code": "def stylize_comment_block(lines):\n  normal, sep, in_code = range(3)\n  state = normal\n  for line in lines:\n    indented = line.startswith('    ')\n    empty_line = line.strip() == ''\n    if state == normal and empty_line:\n      state = sep\n    elif state in [sep, normal] and indented:\n      yield ''\n      if indented:\n        yield '.. code-block:: javascript'\n        yield ''\n        yield line\n        state = in_code\n      else:\n        state = normal\n    elif state == sep and not empty_line:\n      yield ''\n      yield line\n      state = normal\n    else:\n      yield line\n      if state == in_code and not (indented or empty_line):\n        sep = normal",
    "docstring": "Parse comment lines and make subsequent indented lines into a code block\n  block."
  },
  {
    "code": "def carmichael_of_ppower( pp ):\n  p, a = pp\n  if p == 2 and a > 2: return 2**(a-2)\n  else: return (p-1) * p**(a-1)",
    "docstring": "Carmichael function of the given power of the given prime."
  },
  {
    "code": "def clean_gff(gff, cleaned, add_chr=False, chroms_to_ignore=None,\n              featuretypes_to_ignore=None):\n    logger.info(\"Cleaning GFF\")\n    chroms_to_ignore = chroms_to_ignore or []\n    featuretypes_to_ignore = featuretypes_to_ignore or []\n    with open(cleaned, 'w') as fout:\n        for i in gffutils.iterators.DataIterator(gff):\n            if add_chr:\n                i.chrom = \"chr\" + i.chrom\n            if i.chrom in chroms_to_ignore:\n                continue\n            if i.featuretype in featuretypes_to_ignore:\n                continue\n            fout.write(str(i) + '\\n')\n    return cleaned",
    "docstring": "Cleans a GFF file by removing features on unwanted chromosomes and of\n    unwanted featuretypes.  Optionally adds \"chr\" to chrom names."
  },
  {
    "code": "def is_scipy_sparse(arr):\n    global _is_scipy_sparse\n    if _is_scipy_sparse is None:\n        try:\n            from scipy.sparse import issparse as _is_scipy_sparse\n        except ImportError:\n            _is_scipy_sparse = lambda _: False\n    return _is_scipy_sparse(arr)",
    "docstring": "Check whether an array-like is a scipy.sparse.spmatrix instance.\n\n    Parameters\n    ----------\n    arr : array-like\n        The array-like to check.\n\n    Returns\n    -------\n    boolean\n        Whether or not the array-like is a scipy.sparse.spmatrix instance.\n\n    Notes\n    -----\n    If scipy is not installed, this function will always return False.\n\n    Examples\n    --------\n    >>> from scipy.sparse import bsr_matrix\n    >>> is_scipy_sparse(bsr_matrix([1, 2, 3]))\n    True\n    >>> is_scipy_sparse(pd.SparseArray([1, 2, 3]))\n    False\n    >>> is_scipy_sparse(pd.SparseSeries([1, 2, 3]))\n    False"
  },
  {
    "code": "def _get_current_userprofile():\n    if current_user.is_anonymous:\n        return AnonymousUserProfile()\n    profile = g.get(\n        'userprofile',\n        UserProfile.get_by_userid(current_user.get_id()))\n    if profile is None:\n        profile = UserProfile(user_id=int(current_user.get_id()))\n        g.userprofile = profile\n    return profile",
    "docstring": "Get current user profile.\n\n    .. note:: If the user is anonymous, then a\n        :class:`invenio_userprofiles.models.AnonymousUserProfile` instance is\n        returned.\n\n    :returns: The :class:`invenio_userprofiles.models.UserProfile` instance."
  },
  {
    "code": "def head_object_async(self, path, **kwds):\n    return self.do_request_async(self.api_url + path, 'HEAD', **kwds)",
    "docstring": "HEAD an object.\n\n    Depending on request headers, HEAD returns various object properties,\n    e.g. Content-Length, Last-Modified, and ETag.\n\n    Note: No payload argument is supported."
  },
  {
    "code": "def RetrieveIP4Info(self, ip):\n    if ip.is_private:\n      return (IPInfo.INTERNAL, \"Internal IP address.\")\n    try:\n      res = socket.getnameinfo((str(ip), 0), socket.NI_NAMEREQD)\n      return (IPInfo.EXTERNAL, res[0])\n    except (socket.error, socket.herror, socket.gaierror):\n      return (IPInfo.EXTERNAL, \"Unknown IP address.\")",
    "docstring": "Retrieves information for an IP4 address."
  },
  {
    "code": "def get_abstract_dependencies(reqs, sources=None, parent=None):\n    deps = []\n    from .requirements import Requirement\n    for req in reqs:\n        if isinstance(req, pip_shims.shims.InstallRequirement):\n            requirement = Requirement.from_line(\n                \"{0}{1}\".format(req.name, req.specifier)\n            )\n            if req.link:\n                requirement.req.link = req.link\n                requirement.markers = req.markers\n                requirement.req.markers = req.markers\n                requirement.extras = req.extras\n                requirement.req.extras = req.extras\n        elif isinstance(req, Requirement):\n            requirement = copy.deepcopy(req)\n        else:\n            requirement = Requirement.from_line(req)\n        dep = AbstractDependency.from_requirement(requirement, parent=parent)\n        deps.append(dep)\n    return deps",
    "docstring": "Get all abstract dependencies for a given list of requirements.\n\n    Given a set of requirements, convert each requirement to an Abstract Dependency.\n\n    :param reqs: A list of Requirements\n    :type reqs: list[:class:`~requirementslib.models.requirements.Requirement`]\n    :param sources: Pipfile-formatted sources, defaults to None\n    :param sources: list[dict], optional\n    :param parent: The parent of this list of dependencies, defaults to None\n    :param parent: :class:`~requirementslib.models.requirements.Requirement`, optional\n    :return: A list of Abstract Dependencies\n    :rtype: list[:class:`~requirementslib.models.dependency.AbstractDependency`]"
  },
  {
    "code": "def add_config_opts_to_parser(parser):\n        parser.add_argument(\"--config-files\", type=str, nargs=\"+\",\n                            required=True,\n                            help=\"A file parsable by \"\n                                 \"pycbc.workflow.WorkflowConfigParser.\")\n        parser.add_argument(\"--config-overrides\", type=str, nargs=\"+\",\n                            default=None, metavar=\"SECTION:OPTION:VALUE\",\n                            help=\"List of section:option:value combinations \"\n                                 \"to add into the configuration file.\")",
    "docstring": "Adds options for configuration files to the given parser."
  },
  {
    "code": "def myanimelist(username):\n    params = {\n        \"u\": username,\n        \"status\": \"all\",\n        \"type\": \"anime\"\n    }\n    resp = requests.request(\"GET\", ENDPOINT_URLS.MYANIMELIST, params=params)\n    if resp.status_code == 429:\n        raise MALRateLimitExceededError(\"MAL rate limit exceeded\")\n    resp = bs4.BeautifulSoup(resp.content, \"xml\")\n    all_anime = resp.find_all(\"anime\")\n    if not len(all_anime):\n        raise InvalidUsernameError(\"User `{}` does not exist\"\n                                   .format(username))\n    scores = []\n    for anime in all_anime:\n        if anime.my_status.string == \"6\":\n            continue\n        id = anime.series_animedb_id.string\n        id = int(id)\n        score = anime.my_score.string\n        score = int(score)\n        if score > 0:\n            scores.append({\"id\": id, \"score\": score})\n    if not len(scores):\n        raise NoAffinityError(\"User `{}` hasn't rated any anime\"\n                              .format(username))\n    return scores",
    "docstring": "Retrieve a users' animelist scores from MAL.\n\n    Only anime scored > 0 will be returned, and all\n    PTW entries are ignored, even if they are scored.\n\n    :param str username: MAL username\n    :return: `id`, `score` pairs\n    :rtype: list"
  },
  {
    "code": "def solve_filter(expr, vars):\n    lhs_values, _ = __solve_for_repeated(expr.lhs, vars)\n    def lazy_filter():\n        for lhs_value in repeated.getvalues(lhs_values):\n            if solve(expr.rhs, __nest_scope(expr.lhs, vars, lhs_value)).value:\n                yield lhs_value\n    return Result(repeated.lazy(lazy_filter), ())",
    "docstring": "Filter values on the LHS by evaluating RHS with each value.\n\n    Returns any LHS values for which RHS evaluates to a true value."
  },
  {
    "code": "def walk_tree(self, top=None):\n        if top is None:\n            top = self.rootgrp\n        values = top.groups.values()\n        yield values\n        for value in top.groups.values():\n            for children in self.walk_tree(value):\n                yield children",
    "docstring": "Navigate all the groups in the file starting from top.\n        If top is None, the root group is used."
  },
  {
    "code": "def showpath(path):\n    if logger.verbose:\n        return os.path.abspath(path)\n    else:\n        path = os.path.relpath(path)\n        if path.startswith(os.curdir + os.sep):\n            path = path[len(os.curdir + os.sep):]\n        return path",
    "docstring": "Format a path for displaying."
  },
  {
    "code": "def parse_noaa_line(line):\n    station = {}\n    station['station_name'] = line[7:51].strip()\n    station['station_code'] = line[0:6]\n    station['CC'] = line[55:57]\n    station['ELEV(m)'] = int(line[73:78])\n    station['LAT'] = _mlat(line[58:64])\n    station['LON'] = _mlon(line[65:71])\n    station['ST'] = line[52:54]\n    return station",
    "docstring": "Parse NOAA stations.\n\n    This is an old list, the format is:\n\n    NUMBER NAME & STATE/COUNTRY                     LAT   LON     ELEV (meters)\n\n    010250 TROMSO                             NO  6941N 01855E    10"
  },
  {
    "code": "def write(self, magicc_input, filepath):\n        self._filepath = filepath\n        self.minput = deepcopy(magicc_input)\n        self.data_block = self._get_data_block()\n        output = StringIO()\n        output = self._write_header(output)\n        output = self._write_namelist(output)\n        output = self._write_datablock(output)\n        with open(\n            filepath, \"w\", encoding=\"utf-8\", newline=self._newline_char\n        ) as output_file:\n            output.seek(0)\n            copyfileobj(output, output_file)",
    "docstring": "Write a MAGICC input file from df and metadata\n\n        Parameters\n        ----------\n        magicc_input : :obj:`pymagicc.io.MAGICCData`\n            MAGICCData object which holds the data to write\n\n        filepath : str\n            Filepath of the file to write to."
  },
  {
    "code": "def bbox_horz_aligned(box1, box2):\n    if not (box1 and box2):\n        return False\n    box1_top = box1.top + 1.5\n    box2_top = box2.top + 1.5\n    box1_bottom = box1.bottom - 1.5\n    box2_bottom = box2.bottom - 1.5\n    return not (box1_top > box2_bottom or box2_top > box1_bottom)",
    "docstring": "Returns true if the vertical center point of either span is within the\n    vertical range of the other"
  },
  {
    "code": "def get_image(self, image_id, **kwargs):\n        if 'mask' not in kwargs:\n            kwargs['mask'] = IMAGE_MASK\n        return self.vgbdtg.getObject(id=image_id, **kwargs)",
    "docstring": "Get details about an image.\n\n        :param int image: The ID of the image.\n        :param dict \\\\*\\\\*kwargs: response-level options (mask, limit, etc.)"
  },
  {
    "code": "def remove_profile(name, s3=False):\n    user = os.path.expanduser(\"~\")\n    if s3:\n        f = os.path.join(user, S3_PROFILE_ID + name)\n    else:\n        f = os.path.join(user, DBPY_PROFILE_ID + name)\n    try:\n        try:\n            open(f)\n        except:\n            raise Exception(\"Profile '{0}' does not exist. Could not find file {1}\".format(name, f))\n        os.remove(f)\n    except Exception as e:\n        raise Exception(\"Could not remove profile {0}! Excpetion: {1}\".format(name, e))",
    "docstring": "Removes a profile from your config"
  },
  {
    "code": "def name_for(obj):\n    if isinstance(obj, str):\n        return obj\n    cls = obj if isclass(obj) else obj.__class__\n    if hasattr(cls, \"__alias__\"):\n        return underscore(cls.__alias__)\n    else:\n        return underscore(cls.__name__)",
    "docstring": "Get a name for something.\n\n    Allows overriding of default names using the `__alias__` attribute."
  },
  {
    "code": "def _height_and_width(self):\n        try:\n            return self._cache['height_and_width']\n        except KeyError:\n            handw = self._cache['height_and_width'] = super(Terminal, self)._height_and_width()\n            return handw",
    "docstring": "Override for blessings.Terminal._height_and_width\n        Adds caching"
  },
  {
    "code": "def WriteFileHash(self, path, hash_value):\n    string = '{0:s}\\t{1:s}\\n'.format(hash_value, path)\n    encoded_string = self._EncodeString(string)\n    self._file_object.write(encoded_string)",
    "docstring": "Writes the file path and hash to file.\n\n    Args:\n      path (str): path of the file.\n      hash_value (str): message digest hash calculated over the file data."
  },
  {
    "code": "def from_wif_hex(cls: Type[SigningKeyType], wif_hex: str) -> SigningKeyType:\n        wif_bytes = Base58Encoder.decode(wif_hex)\n        if len(wif_bytes) != 35:\n            raise Exception(\"Error: the size of WIF is invalid\")\n        checksum_from_wif = wif_bytes[-2:]\n        fi = wif_bytes[0:1]\n        seed = wif_bytes[1:-2]\n        seed_fi = wif_bytes[0:-2]\n        if fi != b\"\\x01\":\n            raise Exception(\"Error: bad format version, not WIF\")\n        checksum = libnacl.crypto_hash_sha256(libnacl.crypto_hash_sha256(seed_fi))[0:2]\n        if checksum_from_wif != checksum:\n            raise Exception(\"Error: bad checksum of the WIF\")\n        return cls(seed)",
    "docstring": "Return SigningKey instance from Duniter WIF in hexadecimal format\n\n        :param wif_hex: WIF string in hexadecimal format"
  },
  {
    "code": "def upgrade(self, using=None, **kwargs):\n        return self._get_connection(using).indices.upgrade(index=self._name, **kwargs)",
    "docstring": "Upgrade the index to the latest format.\n\n        Any additional keyword arguments will be passed to\n        ``Elasticsearch.indices.upgrade`` unchanged."
  },
  {
    "code": "def re_tab(s):\n    l = []\n    p = 0\n    for i in range(8, len(s), 8):\n        if s[i - 2:i] == \"  \":\n            l.append(s[p:i].rstrip() + \"\\t\")\n            p = i\n    if p == 0:\n        return s\n    else:\n        l.append(s[p:])\n        return \"\".join(l)",
    "docstring": "Return a tabbed string from an expanded one."
  },
  {
    "code": "def git_tag2eups_tag(git_tag):\n    eups_tag = git_tag\n    if re.match(r'\\d', eups_tag):\n        eups_tag = \"v{eups_tag}\".format(eups_tag=eups_tag)\n    eups_tag = eups_tag.translate(str.maketrans('.-', '__'))\n    return eups_tag",
    "docstring": "Convert git tag to an acceptable eups tag format\n\n    I.e., eups no likey semantic versioning markup, wants underscores\n\n    Parameters\n    ----------\n    git_tag: str\n        literal git tag string\n\n    Returns\n    -------\n    eups_tag: string\n        A string suitable for use as an eups tag name"
  },
  {
    "code": "def targets_by_file(self, targets):\n    targets_by_file = defaultdict(OrderedSet)\n    for target in targets:\n      for f in self.files_for_target(target):\n        targets_by_file[f].add(target)\n    return targets_by_file",
    "docstring": "Returns a map from abs path of source, class or jar file to an OrderedSet of targets.\n\n    The value is usually a singleton, because a source or class file belongs to a single target.\n    However a single jar may be provided (transitively or intransitively) by multiple JarLibrary\n    targets. But if there is a JarLibrary target that depends on a jar directly, then that\n    \"canonical\" target will be the first one in the list of targets."
  },
  {
    "code": "def evaluate_perceptron(ctx, model, corpus):\n    click.echo('chemdataextractor.pos.evaluate')\n    if corpus == 'wsj':\n        evaluation = wsj_evaluation\n        sents = list(evaluation.tagged_sents())\n        for i, wsj_sent in enumerate(sents):\n            sents[i] = [t for t in wsj_sent if not t[1] == u'-NONE-']\n    elif corpus == 'genia':\n        evaluation = genia_evaluation\n        sents = list(evaluation.tagged_sents())\n        for i, genia_sent in enumerate(sents):\n            for j, (token, tag) in enumerate(genia_sent):\n                if tag == u'(':\n                    sents[i][j] = (token, u'-LRB-')\n                elif tag == u')':\n                    sents[i][j] = (token, u'-RRB-')\n    else:\n        raise click.ClickException('Invalid corpus')\n    tagger = ChemApPosTagger(model=model)\n    accuracy = tagger.evaluate(sents)\n    click.echo('%s on %s: %s' % (model, evaluation, accuracy))",
    "docstring": "Evaluate performance of Averaged Perceptron POS Tagger."
  },
  {
    "code": "def remove_file(filename, recursive=False, force=False):\n    import os\n    try:\n        mode = os.stat(filename)[0]\n        if mode & 0x4000 != 0:\n            if recursive:\n                for file in os.listdir(filename):\n                    success = remove_file(filename + '/' + file, recursive, force)\n                    if not success and not force:\n                        return False\n                os.rmdir(filename)\n            else:\n                if not force:\n                    return False\n        else:\n            os.remove(filename)\n    except:\n        if not force:\n            return False\n    return True",
    "docstring": "Removes a file or directory."
  },
  {
    "code": "def to_pixel(self, wcs, mode='all'):\n        pixel_params = self._to_pixel_params(wcs, mode=mode)\n        return EllipticalAperture(**pixel_params)",
    "docstring": "Convert the aperture to an `EllipticalAperture` object defined\n        in pixel coordinates.\n\n        Parameters\n        ----------\n        wcs : `~astropy.wcs.WCS`\n            The world coordinate system (WCS) transformation to use.\n\n        mode : {'all', 'wcs'}, optional\n            Whether to do the transformation including distortions\n            (``'all'``; default) or only including only the core WCS\n            transformation (``'wcs'``).\n\n        Returns\n        -------\n        aperture : `EllipticalAperture` object\n            An `EllipticalAperture` object."
  },
  {
    "code": "def collect_video_streams(self):\n        rc = []\n        streams_by_id = {}\n        for t in self.all_tags_of_type(TagDefineVideoStream):\n            stream = [ t ]\n            streams_by_id[t.characterId] = stream\n            rc.append(stream)\n        for t in self.all_tags_of_type(TagVideoFrame):\n            assert t.streamId in streams_by_id\n            streams_by_id[t.streamId].append(t)\n        return rc",
    "docstring": "Return a list of video streams in this timeline and its children.\n        The streams are returned in order with respect to the timeline.\n\n        A stream is returned as a list: the first element is the tag\n        which introduced that stream; other elements are the tags\n        which made up the stream body (if any)."
  },
  {
    "code": "def copy_and_update(dictionary, update):\n    newdict = dictionary.copy()\n    newdict.update(update)\n    return newdict",
    "docstring": "Returns an updated copy of the dictionary without modifying the original"
  },
  {
    "code": "def cwd():\n    cwd = os.environ.get(\"BE_CWD\")\n    if cwd and not os.path.isdir(cwd):\n        sys.stderr.write(\"ERROR: %s is not a directory\" % cwd)\n        sys.exit(lib.USER_ERROR)\n    return cwd or os.getcwd().replace(\"\\\\\", \"/\")",
    "docstring": "Return the be current working directory"
  },
  {
    "code": "def get_aligned_adjacent_coords(x, y):\n    return [(x-1, y), (x-1, y-1), (x, y-1), (x+1, y-1), (x+1, y), (x+1, y+1), (x, y+1), (x-1, y+1)]",
    "docstring": "returns the nine clockwise adjacent coordinates on a keypad, where each row is vertically aligned."
  },
  {
    "code": "def disconnect(sid=None, namespace=None, silent=False):\n    socketio = flask.current_app.extensions['socketio']\n    sid = sid or flask.request.sid\n    namespace = namespace or flask.request.namespace\n    return socketio.server.disconnect(sid, namespace=namespace)",
    "docstring": "Disconnect the client.\n\n    This function terminates the connection with the client. As a result of\n    this call the client will receive a disconnect event. Example::\n\n        @socketio.on('message')\n        def receive_message(msg):\n            if is_banned(session['username']):\n                disconnect()\n            else:\n                # ...\n\n    :param sid: The session id of the client. If not provided, the client is\n                obtained from the request context.\n    :param namespace: The namespace for the room. If not provided, the\n                      namespace is obtained from the request context.\n    :param silent: this option is deprecated."
  },
  {
    "code": "def parse_exiobase1(path):\n    path = os.path.abspath(os.path.normpath(str(path)))\n    exio_files = get_exiobase_files(path)\n    if len(exio_files) == 0:\n        raise ParserError(\"No EXIOBASE files found at {}\".format(path))\n    system = _get_MRIO_system(path)\n    if not system:\n        logging.warning(\"Could not determine system (pxp or ixi)\"\n                        \" set system parameter manually\")\n    io = generic_exiobase12_parser(exio_files, system=system)\n    return io",
    "docstring": "Parse the exiobase1 raw data files.\n\n    This function works with\n\n    - pxp_ita_44_regions_coeff_txt\n    - ixi_fpa_44_regions_coeff_txt\n    - pxp_ita_44_regions_coeff_src_txt\n    - ixi_fpa_44_regions_coeff_src_txt\n\n    which can be found on www.exiobase.eu\n\n    The parser works with the compressed (zip) files as well as the unpacked\n    files.\n\n    Parameters\n    ----------\n    path : pathlib.Path or string\n        Path of the exiobase 1 data\n\n    Returns\n    -------\n    pymrio.IOSystem with exio1 data"
  },
  {
    "code": "def _generate_processed_key_name(process_to, upload_name):\n        timestamp = datetime.now().strftime('%Y%m%d%H%M%S%f')\n        name, extension = os.path.splitext(upload_name)\n        digest = md5(''.join([timestamp, upload_name])).hexdigest()\n        return os.path.join(process_to, '{0}.{1}'.format(digest, extension))",
    "docstring": "Returns a key name to use after processing based on timestamp and\n        upload key name."
  },
  {
    "code": "def recipients(self):\n        cc = self._cc or []\n        bcc = self._bcc or []\n        return self._to + cc + bcc",
    "docstring": "A list of all recipients for this message."
  },
  {
    "code": "def do_loadmacros(parser, token):\n    try:\n        tag_name, filename = token.split_contents()\n    except ValueError:\n        raise template.TemplateSyntaxError(\n            \"'{0}' tag requires exactly one argument (filename)\".format(\n                token.contents.split()[0]))\n    if filename[0] in ('\"', \"'\") and filename[-1] == filename[0]:\n        filename = filename[1:-1]\n    else:\n        raise template.TemplateSyntaxError(\n            \"Malformed argument to the {0} template tag.\"\n            \" Argument must be in quotes.\".format(tag_name)\n        )\n    t = get_template(filename)\n    try:\n        nodelist = t.template.nodelist\n    except AttributeError:\n        nodelist = t.nodelist\n    macros = nodelist.get_nodes_by_type(DefineMacroNode)\n    _setup_macros_dict(parser)\n    for macro in macros:\n        parser._macros[macro.name] = macro\n    return LoadMacrosNode(macros)",
    "docstring": "The function taking a parsed tag and returning\n    a LoadMacrosNode object, while also loading the macros\n    into the page."
  },
  {
    "code": "def _http_call(self, url, method, **kwargs):\n        logging.debug(\"Request[{0}]: {1}\".format(method, url))\n        start_time = datetime.datetime.now()\n        logging.debug(\"Header: {0}\".format(kwargs['headers']))\n        logging.debug(\"Params: {0}\".format(kwargs['data']))\n        response = requests.request(method, url, verify=False, **kwargs)\n        duration = datetime.datetime.now() - start_time\n        logging.debug(\"Response[{0:d}]: {1}, Duration: {2}.{3}s.\".format(\n            response.status_code, response.reason, duration.seconds,\n            duration.microseconds))\n        return response",
    "docstring": "Makes a http call. Logs response information."
  },
  {
    "code": "def _construct_timeseries(self, timeseries, constraints={}):\n        self.response_from(timeseries, constraints)\n        if self.response == None:\n            return None\n        return {'data':self.response['data'],\n                'period':self.response['period'],\n                'start time':datetime.datetime.fromtimestamp(self.response['start_time']),\n                'end time':datetime.datetime.fromtimestamp(self.response['end_time'])}",
    "docstring": "wraps response_from for timeseries calls, returns the resulting dict"
  },
  {
    "code": "def _to_span(x, idx=0):\n    if isinstance(x, Candidate):\n        return x[idx].context\n    elif isinstance(x, Mention):\n        return x.context\n    elif isinstance(x, TemporarySpanMention):\n        return x\n    else:\n        raise ValueError(f\"{type(x)} is an invalid argument type\")",
    "docstring": "Convert a Candidate, Mention, or Span to a span."
  },
  {
    "code": "def checksums(self, install):\n        check_md5(pkg_checksum(install, self.repo), self.tmp_path + install)",
    "docstring": "Checksums before install"
  },
  {
    "code": "def compress_array(str_list, withHC=LZ4_HIGH_COMPRESSION):\n    global _compress_thread_pool\n    if not str_list:\n        return str_list\n    do_compress = lz4_compressHC if withHC else lz4_compress\n    def can_parallelize_strlist(strlist):\n        return len(strlist) > LZ4_N_PARALLEL and len(strlist[0]) > LZ4_MINSZ_PARALLEL\n    use_parallel = (ENABLE_PARALLEL and withHC) or can_parallelize_strlist(str_list)\n    if BENCHMARK_MODE or use_parallel:\n        if _compress_thread_pool is None:\n            _compress_thread_pool = ThreadPool(LZ4_WORKERS)\n        return _compress_thread_pool.map(do_compress, str_list)\n    return [do_compress(s) for s in str_list]",
    "docstring": "Compress an array of strings\n\n    Parameters\n    ----------\n        str_list: `list[str]`\n            The input list of strings which need to be compressed.\n        withHC: `bool`\n            This flag controls whether lz4HC will be used.\n\n    Returns\n    -------\n    `list[str`\n    The list of the compressed strings."
  },
  {
    "code": "def to_records_(self) -> dict:\n        try:\n            dic = self.df.to_dict(orient=\"records\")\n            return dic\n        except Exception as e:\n            self.err(e, \"Can not convert data to records\")",
    "docstring": "Returns a list of dictionary records from the main dataframe\n\n        :return: a python dictionnary with the data\n        :rtype: str\n\n        :example: ``ds.to_records_()``"
  },
  {
    "code": "def set_center(self, lat, lon):\n        self.object_queue.put(SlipCenter((lat,lon)))",
    "docstring": "set center of view"
  },
  {
    "code": "def expand_image(image, shape):\n    if (shape[0] % image.shape[0]) or (shape[1] % image.shape[1]):\n        raise ValueError(\"Output shape must be an integer multiple of input \"\n                         \"image shape.\")\n    sx = shape[1] // image.shape[1]\n    sy = shape[0] // image.shape[0]\n    ox = (sx - 1.0) / (2.0 * sx)\n    oy = (sy - 1.0) / (2.0 * sy)\n    y, x = np.indices(shape, dtype=np.float)\n    x = x / sx - ox\n    y = y / sy - oy\n    return bilinear_interp(image, x, y)",
    "docstring": "Expand image from original shape to requested shape. Output shape\n    must be an integer multiple of input image shape for each axis."
  },
  {
    "code": "def quiver(\n    x,\n    y,\n    z,\n    u,\n    v,\n    w,\n    size=default_size * 10,\n    size_selected=default_size_selected * 10,\n    color=default_color,\n    color_selected=default_color_selected,\n    marker=\"arrow\",\n    **kwargs\n):\n    fig = gcf()\n    _grow_limits(x, y, z)\n    if 'vx' in kwargs or 'vy' in kwargs or 'vz' in kwargs:\n        raise KeyError('Please use u, v, w instead of vx, vy, vz')\n    s = ipv.Scatter(\n        x=x,\n        y=y,\n        z=z,\n        vx=u,\n        vy=v,\n        vz=w,\n        color=color,\n        size=size,\n        color_selected=color_selected,\n        size_selected=size_selected,\n        geo=marker,\n        **kwargs\n    )\n    fig.scatters = fig.scatters + [s]\n    return s",
    "docstring": "Create a quiver plot, which is like a scatter plot but with arrows pointing in the direction given by u, v and w.\n\n    :param x: {x}\n    :param y: {y}\n    :param z: {z}\n    :param u: {u_dir}\n    :param v: {v_dir}\n    :param w: {w_dir}\n    :param size: {size}\n    :param size_selected: like size, but for selected glyphs\n    :param color: {color}\n    :param color_selected: like color, but for selected glyphs\n    :param marker: (currently only 'arrow' would make sense)\n    :param kwargs: extra arguments passed on to the Scatter constructor\n    :return: :any:`Scatter`"
  },
  {
    "code": "def add_special_file(self, mask, path, from_quick_server, ctype=None):\n        full_path = path if not from_quick_server else os.path.join(\n            os.path.dirname(__file__), path)\n        def read_file(_req, _args):\n            with open(full_path, 'rb') as f_out:\n                return Response(f_out.read(), ctype=ctype)\n        self.add_text_get_mask(mask, read_file)\n        self.set_file_argc(mask, 0)",
    "docstring": "Adds a special file that might have a different actual path than\n           its address.\n\n        Parameters\n        ----------\n        mask : string\n            The URL that must be matched to perform this request.\n\n        path : string\n            The actual file path.\n\n        from_quick_server : bool\n            If set the file path is relative to *this* script otherwise it is\n            relative to the process.\n\n        ctype : string\n            Optional content type."
  },
  {
    "code": "def cmd_playtune(self, args):\n        if len(args) < 1:\n            print(\"Usage: playtune TUNE\")\n            return\n        tune = args[0]\n        str1 = tune[0:30]\n        str2 = tune[30:]\n        if sys.version_info.major >= 3 and not isinstance(str1, bytes):\n            str1 = bytes(str1, \"ascii\")\n        if sys.version_info.major >= 3 and not isinstance(str2, bytes):\n            str2 = bytes(str2, \"ascii\")\n        self.master.mav.play_tune_send(self.settings.target_system,\n                                       self.settings.target_component,\n                                       str1, str2)",
    "docstring": "send PLAY_TUNE message"
  },
  {
    "code": "def partial(__fn, *a, **kw):\n        return (PARTIAL, (__fn, a, tuple(kw.items())))",
    "docstring": "Wrap a note for injection of a partially applied function.\n\n        This allows for annotated functions to be injected for composition::\n\n            from jeni import annotate\n\n            @annotate('foo', bar=annotate.maybe('bar'))\n            def foobar(foo, bar=None):\n                return\n\n            @annotate('foo', annotate.partial(foobar))\n            def bazquux(foo, fn):\n                # fn: injector.partial(foobar)\n                return\n\n        Keyword arguments are treated as `maybe` when using partial, in order\n        to allow partial application of only the notes which can be provided,\n        where the caller could then apply arguments known to be unavailable in\n        the injector. Note that with Python 3 function annotations, all\n        annotations are injected as keyword arguments.\n\n        Injections on the partial function are lazy and not applied until the\n        injected partial function is called. See `eager_partial` to inject\n        eagerly."
  },
  {
    "code": "def image_save_buffer_fix(maxblock=1048576):\n    before = ImageFile.MAXBLOCK\n    ImageFile.MAXBLOCK = maxblock\n    try:\n        yield\n    finally:\n        ImageFile.MAXBLOCK = before",
    "docstring": "Contextmanager that change MAXBLOCK in ImageFile."
  },
  {
    "code": "def fit_offset_and_rotation(coords0, coords1):\n    coords0 = numpy.asarray(coords0)\n    coords1 = numpy.asarray(coords1)\n    cp = coords0.mean(axis=0)\n    cq = coords1.mean(axis=0)\n    p0 = coords0 - cp\n    q0 = coords1 - cq\n    crossvar = numpy.dot(numpy.transpose(p0), q0)\n    u, _, vt = linalg.svd(crossvar)\n    d = linalg.det(u) * linalg.det(vt)\n    if d < 0:\n        u[:, -1] = -u[:, -1]\n    rot = numpy.transpose(numpy.dot(u, vt))\n    off = -numpy.dot(rot, cp) + cq\n    return off, rot",
    "docstring": "Fit a rotation and a traslation between two sets points.\n\n    Fit a rotation matrix and a traslation bewtween two matched sets\n    consisting of M N-dimensional points\n\n    Parameters\n    ----------\n    coords0 : (M, N) array_like\n    coords1 : (M, N) array_lke\n\n    Returns\n    -------\n    offset : (N, ) array_like\n    rotation : (N, N) array_like\n\n    Notes\n    ------\n    Fit offset and rotation using Kabsch's algorithm [1]_ [2]_\n\n    .. [1] Kabsch algorithm: https://en.wikipedia.org/wiki/Kabsch_algorithm\n\n    .. [2] Also here: http://nghiaho.com/?page_id=671"
  },
  {
    "code": "def guard_handler(instance, transition_id):\n    if not instance:\n        return True\n    clazz_name = instance.portal_type\n    wf_module = _load_wf_module('{0}.guards'.format(clazz_name.lower()))\n    if not wf_module:\n        return True\n    key = 'guard_{0}'.format(transition_id)\n    guard = getattr(wf_module, key, False)\n    if not guard:\n        return True\n    return guard(instance)",
    "docstring": "Generic workflow guard handler that returns true if the transition_id\n    passed in can be performed to the instance passed in.\n\n    This function is called automatically by a Script (Python) located at\n    bika/lims/skins/guard_handler.py, which in turn is fired by Zope when an\n    expression like \"python:here.guard_handler('<transition_id>')\" is set to\n    any given guard (used by default in all bika's DC Workflow guards).\n\n    Walks through bika.lims.workflow.<obj_type>.guards and looks for a function\n    that matches with 'guard_<transition_id>'. If found, calls the function and\n    returns its value (true or false). If not found, returns True by default.\n\n    :param instance: the object for which the transition_id has to be evaluated\n    :param transition_id: the id of the transition\n    :type instance: ATContentType\n    :type transition_id: string\n    :return: true if the transition can be performed to the passed in instance\n    :rtype: bool"
  },
  {
    "code": "def intersectionlist_to_matrix(ilist, xterms, yterms):\n        z = [ [0] * len(xterms) for i1 in range(len(yterms)) ]\n        xmap = {}\n        xi = 0\n        for x in xterms:\n            xmap[x] = xi\n            xi = xi+1\n        ymap = {}\n        yi = 0\n        for y in yterms:\n            ymap[y] = yi\n            yi = yi+1\n        for i in ilist:\n            z[ymap[i['y']]][xmap[i['x']]] = i['j']\n        logging.debug(\"Z={}\".format(z))\n        return (z,xterms,yterms)",
    "docstring": "WILL BE DEPRECATED\n\n        Replace with method to return pandas dataframe"
  },
  {
    "code": "def set_selection(self, taskfile):\n        self.set_project(taskfile.task.project)\n        self.set_releasetype(taskfile.releasetype)\n        if taskfile.task.department.assetflag:\n            browser = self.assetbrws\n            verbrowser = self.assetverbrws\n            tabi = 0\n            rootobj = taskfile.task.element.atype\n        else:\n            browser = self.shotbrws\n            verbrowser = self.shotverbrws\n            tabi = 1\n            rootobj = taskfile.task.element.sequence\n        self.set_level(browser, 0, rootobj)\n        self.set_level(browser, 1, taskfile.task.element)\n        self.set_level(browser, 2, taskfile.task)\n        self.set_level(browser, 3, [taskfile.descriptor])\n        self.set_level(verbrowser, 0, taskfile)\n        self.selection_tabw.setCurrentIndex(tabi)",
    "docstring": "Set the selection to the given taskfile\n\n        :param taskfile: the taskfile to set the selection to\n        :type taskfile: :class:`djadapter.models.TaskFile`\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def subvolume_snapshot(source, dest=None, name=None, read_only=False):\n    if not dest and not name:\n        raise CommandExecutionError('Provide parameter dest, name, or both')\n    cmd = ['btrfs', 'subvolume', 'snapshot']\n    if read_only:\n        cmd.append('-r')\n    if dest and not name:\n        cmd.append(dest)\n    if dest and name:\n        name = os.path.join(dest, name)\n    if name:\n        cmd.append(name)\n    res = __salt__['cmd.run_all'](cmd)\n    salt.utils.fsutils._verify_run(res)\n    return True",
    "docstring": "Create a snapshot of a source subvolume\n\n    source\n        Source subvolume from where to create the snapshot\n\n    dest\n        If only dest is given, the subvolume will be named as the\n        basename of the source\n\n    name\n       Name of the snapshot\n\n    read_only\n        Create a read only snapshot\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' btrfs.subvolume_snapshot /var/volumes/tmp dest=/.snapshots\n        salt '*' btrfs.subvolume_snapshot /var/volumes/tmp name=backup"
  },
  {
    "code": "def extract_text_log_artifacts(job_log):\n    artifact_bc = ArtifactBuilderCollection(job_log.url)\n    artifact_bc.parse()\n    artifact_list = []\n    for name, artifact in artifact_bc.artifacts.items():\n        artifact_list.append({\n            \"job_guid\": job_log.job.guid,\n            \"name\": name,\n            \"type\": 'json',\n            \"blob\": json.dumps(artifact)\n        })\n    return artifact_list",
    "docstring": "Generate a set of artifacts by parsing from the raw text log."
  },
  {
    "code": "async def populate(self, agent_cls, *args, **kwargs):\n        n = self.gs[0] * self.gs[1]\n        tasks = []\n        for addr in self.addrs:\n            task = asyncio.ensure_future(self._populate_slave(addr, agent_cls,\n                                                              n, *args,\n                                                              **kwargs))\n            tasks.append(task)\n        rets = await asyncio.gather(*tasks)\n        return rets",
    "docstring": "Populate all the slave grid environments with agents. Assumes that\n        no agents have been spawned yet to the slave environment grids. This\n        excludes the slave environment managers as they are not in the grids.)"
  },
  {
    "code": "def import_package(name):\n    import zipimport\n    try:\n        mod = __import__(name)\n    except ImportError:\n        clear_zipimport_cache()\n        mod = __import__(name)\n    components = name.split('.')\n    for comp in components[1:]:\n        mod = getattr(mod, comp)\n    return mod",
    "docstring": "Given a package name like 'foo.bar.quux', imports the package\n    and returns the desired module."
  },
  {
    "code": "def PorodGuinier(q, a, alpha, Rg):\n    return PorodGuinierMulti(q, a, alpha, Rg)",
    "docstring": "Empirical Porod-Guinier scattering\n\n    Inputs:\n    -------\n        ``q``: independent variable\n        ``a``: factor of the power-law branch\n        ``alpha``: power-law exponent\n        ``Rg``: radius of gyration\n\n    Formula:\n    --------\n        ``G * exp(-q^2*Rg^2/3)`` if ``q>q_sep`` and ``a*q^alpha`` otherwise.\n        ``q_sep`` and ``G`` are determined from conditions of smoothness at\n        the cross-over.\n\n    Literature:\n    -----------\n        B. Hammouda: A new Guinier-Porod model. J. Appl. Crystallogr. (2010) 43,\n            716-719."
  },
  {
    "code": "def validate_config_file(cls, config_filepath):\n        is_file = os.path.isfile(config_filepath)\n        if not is_file and os.path.isabs(config_filepath):\n            raise IOError('File path %s is not a valid yml, ini or cfg file or does not exist' % config_filepath)\n        elif is_file:\n            if os.path.getsize(config_filepath) == 0:\n                raise IOError('File %s is empty' % config_filepath)\n        with open(config_filepath, 'r') as f:\n            if yaml.load(f) is None:\n                raise IOError('No YAML config was found in file %s' % config_filepath)",
    "docstring": "Validates the filepath to the config.  Detects whether it is a true YAML file + existance\n\n        :param config_filepath: str, file path to the config file to query\n        :return: None\n        :raises: IOError"
  },
  {
    "code": "def in6_addrtovendor(addr):\n    mac = in6_addrtomac(addr)\n    if mac is None or conf.manufdb is None:\n        return None\n    res = conf.manufdb._get_manuf(mac)\n    if len(res) == 17 and res.count(':') != 5:\n        res = \"UNKNOWN\"\n    return res",
    "docstring": "Extract the MAC address from a modified EUI-64 constructed IPv6\n    address provided and use the IANA oui.txt file to get the vendor.\n    The database used for the conversion is the one loaded by Scapy\n    from a Wireshark installation if discovered in a well-known\n    location. None is returned on error, \"UNKNOWN\" if the vendor is\n    unknown."
  },
  {
    "code": "def raw_secret_generator(plugin, secret_line, filetype):\n    for raw_secret in plugin.secret_generator(secret_line, filetype=filetype):\n        yield raw_secret\n    if issubclass(plugin.__class__, HighEntropyStringsPlugin):\n        with plugin.non_quoted_string_regex(strict=False):\n            for raw_secret in plugin.secret_generator(secret_line):\n                yield raw_secret",
    "docstring": "Generates raw secrets by re-scanning the line, with the specified plugin\n\n    :type plugin: BasePlugin\n    :type secret_line: str\n    :type filetype: FileType"
  },
  {
    "code": "def iter_series(self, workbook, row, col):\n        for series in self.__series:\n            series = dict(series)\n            series[\"values\"] = series[\"values\"].get_formula(workbook, row, col)\n            if \"categories\" in series:\n                series[\"categories\"] = series[\"categories\"].get_formula(workbook, row, col)\n            yield series",
    "docstring": "Yield series dictionaries with values resolved to the final excel formulas."
  },
  {
    "code": "def _stop_thread(self):\n        self._stopping_event.set()\n        queue_content = []\n        try:\n            while True:\n                queue_content.append(self._queue.get_nowait())\n        except Empty:\n            pass\n        self._enqueueing_thread.join()\n        try:\n            queue_content.append(self._queue.get_nowait())\n        except Empty:\n            pass\n        self._queue = Queue(max(len(queue_content), self._buffer_size))\n        for batch in queue_content:\n            self._queue.put(batch)",
    "docstring": "Stop the enqueueing thread. Keep the queue content and stream state."
  },
  {
    "code": "def get_page(self, path, return_content=True, return_html=True):\n        response = self._telegraph.method('getPage', path=path, values={\n            'return_content': return_content\n        })\n        if return_content and return_html:\n            response['content'] = nodes_to_html(response['content'])\n        return response",
    "docstring": "Get a Telegraph page\n\n        :param path: Path to the Telegraph page (in the format Title-12-31,\n                     i.e. everything that comes after https://telegra.ph/)\n\n        :param return_content: If true, content field will be returned\n        :param return_html: If true, returns HTML instead of Nodes list"
  },
  {
    "code": "def get_loss(self, logits: mx.sym.Symbol, labels: mx.sym.Symbol) -> mx.sym.Symbol:\n        if self.loss_config.normalization_type == C.LOSS_NORM_VALID:\n            normalization = \"valid\"\n        elif self.loss_config.normalization_type == C.LOSS_NORM_BATCH:\n            normalization = \"null\"\n        else:\n            raise ValueError(\"Unknown loss normalization type: %s\" % self.loss_config.normalization_type)\n        return mx.sym.SoftmaxOutput(data=logits,\n                                    label=labels,\n                                    ignore_label=self.ignore_label,\n                                    use_ignore=True,\n                                    normalization=normalization,\n                                    smooth_alpha=self.loss_config.label_smoothing,\n                                    name=self.name)",
    "docstring": "Returns loss symbol given logits and integer-coded labels.\n\n        :param logits: Shape: (batch_size * target_seq_len, target_vocab_size).\n        :param labels: Shape: (batch_size * target_seq_len,).\n        :return: List of loss symbols."
  },
  {
    "code": "def get(self,\n            resource_id=None,\n            resource_action=None,\n            resource_cls=None,\n            single_resource=False):\n        endpoint = self.endpoint\n        if not resource_cls:\n            resource_cls = self._cls\n        if resource_id:\n            endpoint = self._build_url(endpoint, resource_id)\n        if resource_action:\n            endpoint = self._build_url(endpoint, resource_action)\n        response = self.api.execute(\"GET\", endpoint)\n        if not response.ok:\n            raise Error.parse(response.json())\n        if resource_id or single_resource:\n            return resource_cls.parse(response.json())\n        return [resource_cls.parse(resource) for resource in response.json()]",
    "docstring": "Gets the details for one or more resources by ID\n\n        Args:\n            cls - gophish.models.Model - The resource class\n            resource_id - str - The endpoint (URL path) for the resource\n            resource_action - str - An action to perform on the resource\n            resource_cls - cls - A class to use for parsing, if different than\n                the base resource\n            single_resource - bool - An override to tell Gophish that even\n                though we aren't requesting a single resource, we expect a\n                single response object\n\n        Returns:\n            One or more instances of cls parsed from the returned JSON"
  },
  {
    "code": "def from_string(address):\n\t\taddress = address.split('.')\n\t\tif len(address) != WIPV4Address.octet_count:\n\t\t\traise ValueError('Invalid ip address: %s' % address)\n\t\tresult = WIPV4Address()\n\t\tfor i in range(WIPV4Address.octet_count):\n\t\t\tresult.__address[i] = WBinArray(int(address[i]), WFixedSizeByteArray.byte_size)\n\t\treturn result",
    "docstring": "Parse string for IPv4 address\n\n\t\t:param address: address to parse\n\t\t:return:"
  },
  {
    "code": "def _read_filepattern(filepattern, max_lines=None, split_on_newlines=True):\n  filenames = sorted(tf.gfile.Glob(filepattern))\n  lines_read = 0\n  for filename in filenames:\n    with tf.gfile.Open(filename) as f:\n      if split_on_newlines:\n        for line in f:\n          yield line.strip()\n          lines_read += 1\n          if max_lines and lines_read >= max_lines:\n            return\n      else:\n        if max_lines:\n          doc = []\n          for line in f:\n            doc.append(line)\n            lines_read += 1\n            if max_lines and lines_read >= max_lines:\n              yield \"\".join(doc)\n              return\n          yield \"\".join(doc)\n        else:\n          yield f.read()",
    "docstring": "Reads files matching a wildcard pattern, yielding the contents.\n\n  Args:\n    filepattern: A wildcard pattern matching one or more files.\n    max_lines: If set, stop reading after reading this many lines.\n    split_on_newlines: A boolean. If true, then split files by lines and strip\n        leading and trailing whitespace from each line. Otherwise, treat each\n        file as a single string.\n\n  Yields:\n    The contents of the files as lines, if split_on_newlines is True, or\n    the entire contents of each file if False."
  },
  {
    "code": "def _read_para_from(self, code, cbit, clen, *, desc, length, version):\n        if clen != 16:\n            raise ProtocolError(f'HIPv{version}: [Parano {code}] invalid format')\n        _addr = self._read_fileng(16)\n        from_ = dict(\n            type=desc,\n            critical=cbit,\n            length=clen,\n            ip=ipaddress.ip_address(_addr),\n        )\n        return from_",
    "docstring": "Read HIP FROM parameter.\n\n        Structure of HIP FROM parameter [RFC 8004]:\n             0                   1                   2                   3\n             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |             Type              |             Length            |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |                                                               |\n            |                             Address                           |\n            |                                                               |\n            |                                                               |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n            Octets      Bits        Name                            Description\n              0           0     from.type                       Parameter Type\n              1          15     from.critical                   Critical Bit\n              2          16     from.length                     Length of Contents\n              4          32     from.ip                         Address"
  },
  {
    "code": "def _create_style(name, family=None, **kwargs):\n    if family == 'paragraph' and 'marginbottom' not in kwargs:\n        kwargs['marginbottom'] = '.5cm'\n    style = Style(name=name, family=family)\n    kwargs_par = {}\n    keys = sorted(kwargs.keys())\n    for k in keys:\n        if 'margin' in k:\n            kwargs_par[k] = kwargs.pop(k)\n    style.addElement(TextProperties(**kwargs))\n    if kwargs_par:\n        style.addElement(ParagraphProperties(**kwargs_par))\n    return style",
    "docstring": "Helper function for creating a new style."
  },
  {
    "code": "def parameter_from_numpy(self, name, array):\n        p = self.params.get(name, shape=array.shape, init=mx.init.Constant(array))\n        return p",
    "docstring": "Create parameter with its value initialized according to a numpy tensor\n\n        Parameters\n        ----------\n        name : str\n            parameter name\n        array : np.ndarray\n            initiation value\n\n        Returns\n        -------\n        mxnet.gluon.parameter\n            a parameter object"
  },
  {
    "code": "async def append_messages(self, name: str,\n                              messages: Sequence[AppendMessage],\n                              selected: SelectedMailbox = None) \\\n            -> Tuple[AppendUid, Optional[SelectedMailbox]]:\n        ...",
    "docstring": "Appends a message to the end of the mailbox.\n\n        See Also:\n            `RFC 3502 6.3.11.\n            <https://tools.ietf.org/html/rfc3502#section-6.3.11>`_\n\n        Args:\n            name: The name of the mailbox.\n            messages: The messages to append.\n            selected: If applicable, the currently selected mailbox name.\n\n        Raises:\n            :class:`~pymap.exceptions.MailboxNotFound`\n            :class:`~pymap.exceptions.AppendFailure`"
  },
  {
    "code": "def _assign_posterior(self):\n        prior_centers = self.get_centers(self.local_prior)\n        posterior_centers = self.get_centers(self.local_posterior_)\n        posterior_widths = self.get_widths(self.local_posterior_)\n        cost = distance.cdist(prior_centers, posterior_centers, 'euclidean')\n        _, col_ind = linear_sum_assignment(cost)\n        self.set_centers(self.local_posterior_, posterior_centers[col_ind])\n        self.set_widths(self.local_posterior_, posterior_widths[col_ind])\n        return self",
    "docstring": "assign posterior to prior based on Hungarian algorithm\n\n        Returns\n        -------\n        TFA\n            Returns the instance itself."
  },
  {
    "code": "def clear_host_port(self):\n        if self.host_port:\n            self._adb.forward(['--remove', 'tcp:%d' % self.host_port])\n            self.host_port = None",
    "docstring": "Stops the adb port forwarding of the host port used by this client."
  },
  {
    "code": "def parse(self, request, source):\n        if source == \"body\":\n            req_scope = request.post_param(\"scope\")\n        elif source == \"query\":\n            req_scope = request.get_param(\"scope\")\n        else:\n            raise ValueError(\"Unknown scope source '\" + source + \"'\")\n        if req_scope is None:\n            if self.default is not None:\n                self.scopes = [self.default]\n                self.send_back = True\n                return\n            elif len(self.available_scopes) != 0:\n                raise OAuthInvalidError(\n                    error=\"invalid_scope\",\n                    explanation=\"Missing scope parameter in request\")\n            else:\n                return\n        req_scopes = req_scope.split(self.separator)\n        self.scopes = [scope for scope in req_scopes\n                       if scope in self.available_scopes]\n        if len(self.scopes) == 0 and self.default is not None:\n            self.scopes = [self.default]\n            self.send_back = True",
    "docstring": "Parses scope value in given request.\n\n        Expects the value of the \"scope\" parameter in request to be a string\n        where each requested scope is separated by a white space::\n\n            # One scope requested\n            \"profile_read\"\n\n            # Multiple scopes\n            \"profile_read profile_write\"\n\n        :param request: An instance of :class:`oauth2.web.Request`.\n        :param source: Where to read the scope from. Pass \"body\" in case of a\n                       application/x-www-form-urlencoded body and \"query\" in\n                       case the scope is supplied as a query parameter in the\n                       URL of a request."
  },
  {
    "code": "def matrix_rank(model):\n    s_matrix, _, _ = con_helpers.stoichiometry_matrix(\n        model.metabolites, model.reactions\n    )\n    return con_helpers.rank(s_matrix)",
    "docstring": "Return the rank of the model's stoichiometric matrix.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model under investigation."
  },
  {
    "code": "def _predict(self, features):\n        from sklearn.exceptions import NotFittedError\n        try:\n            prediction = self.kernel.predict_classes(features)[:, 0]\n        except NotFittedError:\n            raise NotFittedError(\n                \"{} is not fitted yet. Call 'fit' with appropriate \"\n                \"arguments before using this method.\".format(\n                    type(self).__name__\n                )\n            )\n        return prediction",
    "docstring": "Predict matches and non-matches.\n\n        Parameters\n        ----------\n        features : numpy.ndarray\n            The data to predict the class of.\n\n        Returns\n        -------\n        numpy.ndarray\n            The predicted classes."
  },
  {
    "code": "def restore_descriptor(self, converted_descriptor):\n        fields = []\n        for field in converted_descriptor['fields']:\n            field_type = self.restore_type(field['type'])\n            resfield = {\n                'name': field['name'],\n                'type': field_type,\n            }\n            if field.get('mode', 'NULLABLE') != 'NULLABLE':\n                resfield['constraints'] = {'required': True}\n            fields.append(resfield)\n        descriptor = {'fields': fields}\n        return descriptor",
    "docstring": "Restore descriptor rom BigQuery"
  },
  {
    "code": "def register_read_multiple(self, register_indices):\n        num_regs = len(register_indices)\n        buf = (ctypes.c_uint32 * num_regs)(*register_indices)\n        data = (ctypes.c_uint32 * num_regs)(0)\n        statuses = (ctypes.c_uint8 * num_regs)(0)\n        res = self._dll.JLINKARM_ReadRegs(buf, data, statuses, num_regs)\n        if res < 0:\n            raise errors.JLinkException(res)\n        return list(data)",
    "docstring": "Retrieves the values from the registers specified.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          register_indices (list): list of registers to read\n\n        Returns:\n          A list of values corresponding one-to-one for each of the given\n          register indices.  The returned list of values are the values in\n          order of which the indices were specified.\n\n        Raises:\n          JLinkException: if a given register is invalid or an error occurs."
  },
  {
    "code": "def duration_to_timedelta(obj):\n    matches = DURATION_PATTERN.search(obj)\n    matches = matches.groupdict(default=\"0\")\n    matches = {k: int(v) for k, v in matches.items()}\n    return timedelta(**matches)",
    "docstring": "Converts duration to timedelta\n\n    >>> duration_to_timedelta(\"10m\")\n    >>> datetime.timedelta(0, 600)"
  },
  {
    "code": "def truncate_database(self, database=None):\n        if database in self.databases and database is not self.database:\n            self.change_db(database)\n        tables = self.tables if isinstance(self.tables, list) else [self.tables]\n        if len(tables) > 0:\n            self.drop(tables)\n            self._printer('\\t' + str(len(tables)), 'tables truncated from', database)\n        return tables",
    "docstring": "Drop all tables in a database."
  },
  {
    "code": "def naive_request(self, url, method, **kwargs):\n        return self._internal_request(self.naive_session, url, method, **kwargs)",
    "docstring": "Makes a request to url using an without oauth authorization\n        session, but through a normal session\n\n        :param str url: url to send request to\n        :param str method: type of request (get/put/post/patch/delete)\n        :param kwargs: extra params to send to the request api\n        :return: Response of the request\n        :rtype: requests.Response"
  },
  {
    "code": "def camel_to_underscore(name):\n    output = []\n    for i, c in enumerate(name):\n        if i > 0:\n            pc = name[i - 1]\n            if c.isupper() and not pc.isupper() and pc != '_':\n                output.append('_')\n            elif i > 3 and not c.isupper():\n                previous = name[i - 3:i]\n                if previous.isalpha() and previous.isupper():\n                    output.insert(len(output) - 1, '_')\n        output.append(c.lower())\n    return ''.join(output)",
    "docstring": "Convert camel case style naming to underscore style naming\n\n    If there are existing underscores they will be collapsed with the\n    to-be-added underscores. Multiple consecutive capital letters will not be\n    split except for the last one.\n\n    >>> camel_to_underscore('SpamEggsAndBacon')\n    'spam_eggs_and_bacon'\n    >>> camel_to_underscore('Spam_and_bacon')\n    'spam_and_bacon'\n    >>> camel_to_underscore('Spam_And_Bacon')\n    'spam_and_bacon'\n    >>> camel_to_underscore('__SpamAndBacon__')\n    '__spam_and_bacon__'\n    >>> camel_to_underscore('__SpamANDBacon__')\n    '__spam_and_bacon__'"
  },
  {
    "code": "def unlock(path,\n           zk_hosts=None,\n           identifier=None,\n           max_concurrency=1,\n           ephemeral_lease=False,\n           scheme=None,\n           profile=None,\n           username=None,\n           password=None,\n           default_acl=None\n           ):\n    zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme,\n                      username=username, password=password, default_acl=default_acl)\n    if path not in __context__['semaphore_map']:\n        __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier,\n                                                        max_leases=max_concurrency,\n                                                        ephemeral_lease=ephemeral_lease)\n    if path in __context__['semaphore_map']:\n        __context__['semaphore_map'][path].release()\n        del __context__['semaphore_map'][path]\n        return True\n    else:\n        logging.error('Unable to find lease for path %s', path)\n        return False",
    "docstring": "Remove lease from semaphore\n\n    path\n        The path in zookeeper where the lock is\n\n    zk_hosts\n        zookeeper connect string\n\n    identifier\n        Name to identify this minion, if unspecified defaults to hostname\n\n    max_concurrency\n        Maximum number of lock holders\n\n    timeout\n        timeout to wait for the lock. A None timeout will block forever\n\n    ephemeral_lease\n        Whether the locks in zookeper should be ephemeral\n\n    Example:\n\n    .. code-block: bash\n\n        salt minion zk_concurrency.unlock /lock/path host1:1234,host2:1234"
  },
  {
    "code": "def run(self):\n        with self._run_lock:\n            while self.mounts:\n                for mount in self.mounts:\n                    try:\n                        next(mount)\n                    except StopIteration:\n                        self.mounts.remove(mount)",
    "docstring": "Start driving the chain, block until done"
  },
  {
    "code": "def draw(self, surf):\n        if self.shown:\n            for w in self.widgets:\n                surf.blit(w.image, self.convert_rect(w.rect))\n            for c in self.containers:\n                c.draw(surf)",
    "docstring": "Draw all widgets and sub-containers to @surf."
  },
  {
    "code": "def run_update_cat(_):\n    recs = MPost2Catalog.query_all().objects()\n    for rec in recs:\n        if rec.tag_kind != 'z':\n            print('-' * 40)\n            print(rec.uid)\n            print(rec.tag_id)\n            print(rec.par_id)\n            MPost2Catalog.update_field(rec.uid, par_id=rec.tag_id[:2] + \"00\")",
    "docstring": "Update the catagery."
  },
  {
    "code": "def terminate(self, force=False):\n        if not self.isalive():\n            return True\n        self.kill(signal.SIGINT)\n        time.sleep(self.delayafterterminate)\n        if not self.isalive():\n            return True\n        if force:\n            self.kill(signal.SIGKILL)\n            time.sleep(self.delayafterterminate)\n            if not self.isalive():\n                return True\n            else:\n                return False",
    "docstring": "This forces a child process to terminate."
  },
  {
    "code": "def clear(self):\n        for i in range(self.maxlevel):\n            self._head[2+i] = self._tail\n            self._tail[-1] = 0\n        self._level = 1",
    "docstring": "Remove all key-value pairs."
  },
  {
    "code": "def __put_slice_in_slim(slim, dataim, sh, i):\r\n    a, b = np.unravel_index(int(i), sh)\r\n    st0 = int(dataim.shape[0] * a)\r\n    st1 = int(dataim.shape[1] * b)\r\n    sp0 = int(st0 + dataim.shape[0])\r\n    sp1 = int(st1 + dataim.shape[1])\r\n    slim[\r\n    st0:sp0,\r\n    st1:sp1\r\n    ] = dataim\r\n    return slim",
    "docstring": "put one small slice as a tile in a big image"
  },
  {
    "code": "def request(self):\n        self._request.url = '{}/v2/{}'.format(self.tcex.default_args.tc_api_path, self._request_uri)\n        self._apply_filters()\n        self.tcex.log.debug(u'Resource URL: ({})'.format(self._request.url))\n        response = self._request.send(stream=self._stream)\n        data, status = self._request_process(response)\n        return {'data': data, 'response': response, 'status': status}",
    "docstring": "Send the request to the API.\n\n        This method will send the request to the API.  It will try to handle\n        all the types of responses and provide the relevant data when possible.\n        Some basic error detection and handling is implemented, but not all failure\n        cases will get caught.\n\n        Return:\n            (dictionary): Response/Results data."
  },
  {
    "code": "def get_facts_by_name(api_url=None, fact_name=None, verify=False, cert=list()):\n    return utils._make_api_request(api_url, '/facts/{0}'.format(fact_name), verify, cert)",
    "docstring": "Returns facts by name\n\n    :param api_url: Base PuppetDB API url\n    :param fact_name: Name of fact"
  },
  {
    "code": "def _next_class(cls):\n        return next(\n            class_\n            for class_ in cls.__mro__\n            if not issubclass(class_, Multi)\n        )",
    "docstring": "Multi-subclasses should use the parent class"
  },
  {
    "code": "def rpc(self, address, rpc_id):\n        if address in self.mock_rpcs and rpc_id in self.mock_rpcs[address]:\n            value = self.mock_rpcs[address][rpc_id]\n            return value\n        result = self._call_rpc(address, rpc_id, bytes())\n        if len(result) != 4:\n            self.warn(u\"RPC 0x%X on address %d: response had invalid length %d not equal to 4\" % (rpc_id, address, len(result)))\n        if len(result) < 4:\n            raise HardwareError(\"Response from RPC was not long enough to parse as an integer\", rpc_id=rpc_id, address=address, response_length=len(result))\n        if len(result) > 4:\n            result = result[:4]\n        res, = struct.unpack(\"<L\", result)\n        return res",
    "docstring": "Call an RPC and receive the result as an integer.\n\n        If the RPC does not properly return a 32 bit integer, raise a warning\n        unless it cannot be converted into an integer at all, in which case\n        a HardwareError is thrown.\n\n        Args:\n            address (int): The address of the tile we want to call the RPC\n                on\n            rpc_id (int): The id of the RPC that we want to call\n\n        Returns:\n            int: The result of the RPC call.  If the rpc did not succeed\n                an error is thrown instead."
  },
  {
    "code": "def extract_text(self, node):\n        if not isinstance(node, (list, tuple)):\n            node = [node]\n        pieces, self.pieces = self.pieces, ['']\n        for n in node:\n            for sn in n.childNodes:\n                self.parse(sn)\n        ret = ''.join(self.pieces)\n        self.pieces = pieces\n        return ret",
    "docstring": "Return the string representation of the node or list of nodes by parsing the\n        subnodes, but returning the result as a string instead of adding it to `self.pieces`.\n        Note that this allows extracting text even if the node is in the ignore list."
  },
  {
    "code": "def cdot(L, out=None):\n    r\n    L = asarray(L, float)\n    layout_error = \"Wrong matrix layout.\"\n    if L.ndim != 2:\n        raise ValueError(layout_error)\n    if L.shape[0] != L.shape[1]:\n        raise ValueError(layout_error)\n    if out is None:\n        out = empty((L.shape[0], L.shape[1]), float)\n    return einsum(\"ij,kj->ik\", L, L, out=out)",
    "docstring": "r\"\"\"Product of a Cholesky matrix with itself transposed.\n\n    Args:\n        L (array_like): Cholesky matrix.\n        out (:class:`numpy.ndarray`, optional): copy result to.\n\n    Returns:\n        :class:`numpy.ndarray`: :math:`\\mathrm L\\mathrm L^\\intercal`."
  },
  {
    "code": "def make_anchor_id(self):\n        result = re.sub(\n            '[^a-zA-Z0-9_]', '_', self.user + '_' + self.timestamp)\n        return result",
    "docstring": "Return string to use as URL anchor for this comment."
  },
  {
    "code": "def error(self, amplexception):\n        msg = '\\t'+str(amplexception).replace('\\n', '\\n\\t')\n        print('Error:\\n{:s}'.format(msg))\n        raise amplexception",
    "docstring": "Receives notification of an error."
  },
  {
    "code": "def flatten_once(iterable, check=is_iterable):\n    for value in iterable:\n        if check(value):\n            for item in value:\n                yield item\n        else:\n            yield value",
    "docstring": "Flattens only the first level."
  },
  {
    "code": "def _are_aligned_angles(self, b1, b2):\n        \"Are two boxes aligned according to their angle?\"\n        return abs(b1 - b2) <= self.angle_tol or abs(np.pi - abs(b1 - b2)) <= self.angle_tol",
    "docstring": "Are two boxes aligned according to their angle?"
  },
  {
    "code": "def decode_contents(self, contents, obj):\n        obj.siblings = [self.decode_content(c, RiakContent(obj))\n                        for c in contents]\n        if len(obj.siblings) > 1 and obj.resolver is not None:\n            obj.resolver(obj)\n        return obj",
    "docstring": "Decodes the list of siblings from the protobuf representation\n        into the object.\n\n        :param contents: a list of RpbContent messages\n        :type contents: list\n        :param obj: a RiakObject\n        :type obj: RiakObject\n        :rtype RiakObject"
  },
  {
    "code": "def install(self):\n        packages = self.packages()\n        if packages:\n            print(\"\")\n            for pkg in packages:\n                ver = SBoGrep(pkg).version()\n                prgnam = \"{0}-{1}\".format(pkg, ver)\n                if find_package(prgnam, self.meta.output):\n                    binary = slack_package(prgnam)\n                    PackageManager(binary).upgrade(flag=\"--install-new\")\n                else:\n                    print(\"\\nPackage {0} not found in the {1} for \"\n                          \"installation\\n\".format(prgnam, self.meta.output))\n        else:\n            print(\"\\nPackages not found in the queue for installation\\n\")\n            raise SystemExit(1)",
    "docstring": "Install packages from queue"
  },
  {
    "code": "def _low_level_exec_command(self, conn, cmd, tmp, sudoable=False, executable=None):\n        if executable is None:\n            executable = '/bin/sh'\n        sudo_user = self.sudo_user\n        rc, stdin, stdout, stderr = conn.exec_command(cmd, tmp, sudo_user, sudoable=sudoable, executable=executable)\n        if type(stdout) not in [ str, unicode ]:\n            out = ''.join(stdout.readlines())\n        else:\n            out = stdout\n        if type(stderr) not in [ str, unicode ]:\n            err = ''.join(stderr.readlines())\n        else:\n            err = stderr\n        if rc != None:\n            return dict(rc=rc, stdout=out, stderr=err )\n        else:\n            return dict(stdout=out, stderr=err )",
    "docstring": "execute a command string over SSH, return the output"
  },
  {
    "code": "def to_header(self, realm=''):\n        oauth_params = ((k, v) for k, v in self.items() \n                            if k.startswith('oauth_'))\n        stringy_params = ((k, escape(v)) for k, v in oauth_params)\n        header_params = ('%s=\"%s\"' % (k, v) for k, v in stringy_params)\n        params_header = ', '.join(header_params)\n        auth_header = 'OAuth realm=\"%s\"' % realm\n        if params_header:\n            auth_header = \"%s, %s\" % (auth_header, params_header)\n        return {'Authorization': auth_header}",
    "docstring": "Serialize as a header for an HTTPAuth request."
  },
  {
    "code": "def close(self):\n        if self._closed:\n            raise ValueError('scope is already marked as closed')\n        if self.parent:\n            for symbol, c in self.leaked_referenced_symbols.items():\n                self.parent.reference(symbol, c)\n        self._closed = True",
    "docstring": "Mark the scope as closed, i.e. all symbols have been declared,\n        and no further declarations should be done."
  },
  {
    "code": "def installed():\n        try:\n            path = ChromeCookies._getPath()\n            with open(path) as f: pass\n            return True\n        except Exception as e:\n            return False",
    "docstring": "Returns whether or not Google Chrome is installed\n        \n        Determines the application data path for Google Chrome\n        and checks if the path exists. If so, returns True, otherwise\n        it will return False.\n           \n        Returns\n           bool - True if Chrome is installed"
  },
  {
    "code": "def _build_models_query(self, query):\n        registered_models_ct = self.build_models_list()\n        if registered_models_ct:\n            restrictions = [xapian.Query('%s%s' % (TERM_PREFIXES[DJANGO_CT], model_ct))\n                            for model_ct in registered_models_ct]\n            limit_query = xapian.Query(xapian.Query.OP_OR, restrictions)\n            query = xapian.Query(xapian.Query.OP_AND, query, limit_query)\n        return query",
    "docstring": "Builds a query from `query` that filters to documents only from registered models."
  },
  {
    "code": "def col_apply(self, col, func, *args, **kwargs):\n        if col in self.data:\n            self.data[col] = self.data[col].apply(func, *args, **kwargs)\n        else:\n            self.meta[col] = self.meta[col].apply(func, *args, **kwargs)",
    "docstring": "Apply a function to a column\n\n        Parameters\n        ----------\n        col: string\n            column in either data or metadata\n        func: functional\n            function to apply"
  },
  {
    "code": "def _lib(self, name, only_if_have=False):\n        emit = True\n        if only_if_have:\n            emit = self.env.get('HAVE_LIB' + self.env_key(name))\n        if emit:\n            return '-l' + name\n        return ''",
    "docstring": "Specify a linker library.\n\n        Example:\n\n            LDFLAGS={{ lib(\"rt\") }} {{ lib(\"pthread\", True) }}\n\n        Will unconditionally add `-lrt` and check the environment if the key\n        `HAVE_LIBPTHREAD` is set to be true, then add `-lpthread`."
  },
  {
    "code": "def __unroll(self, rolled):\n        return np.array(np.concatenate([matrix.flatten() for matrix in rolled], axis=1)).reshape(-1)",
    "docstring": "Converts parameter matrices into an array."
  },
  {
    "code": "def to_fits(self, filename, wavelengths=None, flux_unit=None, area=None,\n                vegaspec=None, **kwargs):\n        w, y = self._get_arrays(wavelengths, flux_unit=flux_unit, area=area,\n                                vegaspec=vegaspec)\n        bkeys = {'tdisp1': 'G15.7', 'tdisp2': 'G15.7'}\n        if 'expr' in self.meta:\n            bkeys['expr'] = (self.meta['expr'], 'synphot expression')\n        if 'ext_header' in kwargs:\n            kwargs['ext_header'].update(bkeys)\n        else:\n            kwargs['ext_header'] = bkeys\n        specio.write_fits_spec(filename, w, y, **kwargs)",
    "docstring": "Write the spectrum to a FITS file.\n\n        Parameters\n        ----------\n        filename : str\n            Output filename.\n\n        wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`\n            Wavelength values for sampling.\n            If not a Quantity, assumed to be in Angstrom.\n            If `None`, ``self.waveset`` is used.\n\n        flux_unit : str or `~astropy.units.core.Unit` or `None`\n            Flux is converted to this unit before written out.\n            If not given, internal unit is used.\n\n        area, vegaspec\n            See :func:`~synphot.units.convert_flux`.\n\n        kwargs : dict\n            Keywords accepted by :func:`~synphot.specio.write_fits_spec`."
  },
  {
    "code": "def _capitalize_first_letter(word):\n    if word[0].isalpha():\n        if word[0].isupper():\n            return \"[\" + word[0].swapcase() + word[0] + \"]\" + word[1:]\n        else:\n            return \"[\" + word[0] + word[0].swapcase() + \"]\" + word[1:]\n    return word",
    "docstring": "Return a regex pattern with the first letter.\n\n    Accepts both lowercase and uppercase."
  },
  {
    "code": "def add_attributes(self, data, type):\n        for attr, ancestry in type.attributes():\n            name = '_%s' % attr.name\n            value = attr.get_default()\n            setattr(data, name, value)",
    "docstring": "add required attributes"
  },
  {
    "code": "def _timeout_thread(self, remain):\n        time.sleep(remain)\n        if not self._ended:\n            self._ended = True\n            self._release_all()",
    "docstring": "Timeout before releasing every thing, if nothing was returned"
  },
  {
    "code": "def get_user_pubkeys(users):\n    if not isinstance(users, list):\n        return {'Error': 'A list of users is expected'}\n    ret = {}\n    for user in users:\n        key_ids = []\n        if isinstance(user, dict):\n            tmp_user = next(six.iterkeys(user))\n            key_ids = user[tmp_user]\n            user = tmp_user\n        url = 'https://api.github.com/users/{0}/keys'.format(user)\n        result = salt.utils.http.query(\n            url,\n            'GET',\n            decode=False,\n            text=True,\n        )\n        keys = salt.utils.json.loads(result['text'])\n        ret[user] = {}\n        for key in keys:\n            if key_ids:\n                if six.text_type(key['id']) in key_ids:\n                    ret[user][key['id']] = key['key']\n            else:\n                ret[user][key['id']] = key['key']\n    return ret",
    "docstring": "Retrieve a set of public keys from GitHub for the specified list of users.\n    Expects input in list format. Optionally, a value in the list may be a dict\n    whose value is a list of key IDs to be returned. If this is not done, then\n    all keys will be returned.\n\n    Some example data structures that coupld be passed in would look like:\n\n    .. code_block:: yaml\n\n        ['user1', 'user2', 'user3']\n\n        [\n            'user1': [\n                '12345',\n                '67890',\n            ],\n            'user2',\n            'user3',\n        ]"
  },
  {
    "code": "def check_diag(self, jac, name):\n        system = self.system\n        pos = []\n        names = []\n        pairs = ''\n        size = jac.size\n        diag = jac[0:size[0] ** 2:size[0] + 1]\n        for idx in range(size[0]):\n            if abs(diag[idx]) <= 1e-8:\n                pos.append(idx)\n        for idx in pos:\n            names.append(system.varname.__dict__[name][idx])\n        if len(names) > 0:\n            for i, j in zip(pos, names):\n                pairs += '{0}: {1}\\n'.format(i, j)\n            logger.debug('Jacobian diagonal check:')\n            logger.debug(pairs)",
    "docstring": "Check matrix ``jac`` for diagonal elements that equals 0"
  },
  {
    "code": "def datatype2schemacls(\n        _datatype, _registry=None, _factory=None, _force=True,\n        _besteffort=True, **kwargs\n):\n    result = None\n    gdbt = getbydatatype if _registry is None else _registry.getbydatatype\n    result = gdbt(_datatype, besteffort=_besteffort)\n    if result is None:\n        gscls = getschemacls if _factory is None else _factory.getschemacls\n        result = gscls(_datatype, besteffort=_besteffort)\n    if result is None and _force:\n        _build = build if _factory is None else _factory.build\n        result = _build(_resource=_datatype, **kwargs)\n    return result",
    "docstring": "Get a schema class which has been associated to input data type by the\n    registry or the factory in this order.\n\n    :param type datatype: data type from where get associated schema.\n    :param SchemaRegisgry _registry: registry from where call the getbydatatype\n        . Default is the global registry.\n    :param SchemaFactory _factory: factory from where call the getschemacls if\n        getbydatatype returns None. Default is the global factory.\n    :param bool _force: if true (default), force the building of schema class\n        if no schema is associated to input data type.\n    :param bool _besteffort: if True (default), try to resolve schema by\n        inheritance.\n    :param dict kwargs: factory builder kwargs.\n    :rtype: type\n    :return: Schema associated to input registry or factory. None if no\n        association found."
  },
  {
    "code": "def get_batch_for_key(data):\n    batches = _get_batches(data, require_bam=False)\n    if len(batches) == 1:\n        return batches[0]\n    else:\n        return tuple(batches)",
    "docstring": "Retrieve batch information useful as a unique key for the sample."
  },
  {
    "code": "def get_operator(name):\n    sep = name.index('/')\n    provider_name = name[:sep]\n    operator_name = name[sep + 1:]\n    provider = OPERATOR_PROVIDERS[provider_name]\n    return provider[operator_name]",
    "docstring": "Get an operator class from a provider plugin.\n\n    Attrs:\n        name: The name of the operator class.\n\n    Returns: The operator *class object* (i.e. not an instance)."
  },
  {
    "code": "def etree(A):\n    assert isinstance(A,spmatrix), \"A must be a sparse matrix\"\n    assert A.size[0] == A.size[1], \"A must be a square matrix\"\n    n = A.size[0]\n    cp,ri,_ = A.CCS\n    parent = matrix(0,(n,1))\n    w = matrix(0,(n,1))\n    for k in range(n):\n        parent[k] = k\n        w[k] = -1\n        for p in range(cp[k],cp[k+1]):\n            i = ri[p]\n            while ((not i == -1) and (i < k)):\n                inext = w[i]\n                w[i] = k\n                if inext == -1: parent[i] = k\n                i = inext;\n    return parent",
    "docstring": "Compute elimination tree from upper triangle of A."
  },
  {
    "code": "def get_private_rooms(self, **kwargs):\n        return GetPrivateRooms(settings=self.settings, **kwargs).call(**kwargs)",
    "docstring": "Get a listing of all private rooms with their names and IDs"
  },
  {
    "code": "def plot_simseries(self, **kwargs: Any) -> None:\n        self.__plot_series([self.sequences.sim], kwargs)",
    "docstring": "Plot the |IOSequence.series| of the |Sim| sequence object.\n\n        See method |Node.plot_allseries| for further information."
  },
  {
    "code": "def add_item(self, item):\n        _idx = len(self.items)\n        self.items.update({\"item_\" + str(_idx + 1): item})",
    "docstring": "Updates the list of items in the current transaction"
  },
  {
    "code": "def container_present(name, profile):\n    containers = __salt__['libcloud_storage.list_containers'](profile)\n    match = [z for z in containers if z['name'] == name]\n    if match:\n        return state_result(True, \"Container already exists\", name, {})\n    else:\n        result = __salt__['libcloud_storage.create_container'](name, profile)\n        return state_result(True, \"Created new container\", name, result)",
    "docstring": "Ensures a container is present.\n\n    :param name: Container name\n    :type  name: ``str``\n\n    :param profile: The profile key\n    :type  profile: ``str``"
  },
  {
    "code": "def _render_round_init(self, horizon: int, non_fluents: NonFluents) -> None:\n        print('*********************************************************')\n        print('>>> ROUND INIT, horizon = {}'.format(horizon))\n        print('*********************************************************')\n        fluent_variables = self._compiler.rddl.non_fluent_variables\n        self._render_fluent_timestep('non-fluents', non_fluents, fluent_variables)",
    "docstring": "Prints round init information about `horizon` and `non_fluents`."
  },
  {
    "code": "def _new_type(cls, args):\n        fformat = [\"%r\" if f is None else \"%s=%%r\" % f for f in args]\n        fformat = \"(%s)\" % \", \".join(fformat)\n        class _ResultTuple(cls):\n            __slots__ = ()\n            _fformat = fformat\n            if args:\n                for i, a in enumerate(args):\n                    if a is not None:\n                        vars()[a] = property(itemgetter(i))\n                del i, a\n        return _ResultTuple",
    "docstring": "Creates a new class similar to namedtuple.\n\n        Pass a list of field names or None for no field name.\n\n        >>> x = ResultTuple._new_type([None, \"bar\"])\n        >>> x((1, 3))\n        ResultTuple(1, bar=3)"
  },
  {
    "code": "def reload_configuration(self, event):\n        if event.target == self.uniquename:\n            self.log('Reloading configuration')\n            self._read_config()",
    "docstring": "Event triggered configuration reload"
  },
  {
    "code": "def sign(self, msg, key):\n        if not isinstance(key, rsa.RSAPrivateKey):\n            raise TypeError(\n                \"The key must be an instance of rsa.RSAPrivateKey\")\n        sig = key.sign(msg, self.padding, self.hash)\n        return sig",
    "docstring": "Create a signature over a message as defined in RFC7515 using an\n        RSA key\n\n        :param msg: the message.\n        :type msg: bytes\n        :returns: bytes, the signature of data.\n        :rtype: bytes"
  },
  {
    "code": "def model_tree(name, model_cls, visited=None):\n    if not visited:\n        visited = set()\n    visited.add(model_cls)\n    mapper = class_mapper(model_cls)\n    columns = [column.key for column in mapper.column_attrs]\n    related = [model_tree(rel.key, rel.mapper.entity, visited)\n               for rel in mapper.relationships if rel.mapper.entity not in visited]\n    return {name: columns + related}",
    "docstring": "Create a simple tree of model's properties and its related models.\n\n    It traverse trough relations, but ignore any loops.\n\n    :param name: name of the model\n    :type name: str\n    :param model_cls: model class\n    :param visited: set of visited models\n    :type visited: list or None\n    :return: a dictionary where values are lists of string or other \\\n    dictionaries"
  },
  {
    "code": "def shutdown_host(port, username=None, password=None, authdb=None):\n    host = 'localhost:%i' % port\n    try:\n        mc = MongoConnection(host)\n        try:\n            if username and password and authdb:\n                if authdb != \"admin\":\n                    raise RuntimeError(\"given username/password is not for \"\n                                       \"admin database\")\n                else:\n                    try:\n                        mc.admin.authenticate(name=username, password=password)\n                    except OperationFailure:\n                        pass\n            mc.admin.command('shutdown', force=True)\n        except AutoReconnect:\n            pass\n        except OperationFailure:\n            print(\"Error: cannot authenticate to shut down %s.\" % host)\n            return\n    except ConnectionFailure:\n        pass\n    else:\n        mc.close()",
    "docstring": "Send the shutdown command to a mongod or mongos on given port.\n\n    This function can be called as a separate thread."
  },
  {
    "code": "def _ngrams(self, sequence, degree):\n        count = max(0, len(sequence) - degree + 1)\n        return [self._tokenizer.joiner.join(\n            self._tokenizer.joiner.join(sequence[i:i+degree]).split())\n                for i in range(count)]",
    "docstring": "Returns the n-grams generated from `sequence`.\n\n        Based on the ngrams function from the Natural Language\n        Toolkit.\n\n        Each n-gram in the returned list is a string with whitespace\n        removed.\n\n        :param sequence: the source data to be converted into n-grams\n        :type sequence: sequence\n        :param degree: the degree of the n-grams\n        :type degree: `int`\n        :rtype: `list` of `str`"
  },
  {
    "code": "def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False):\n    return [convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity) for bbox in bboxes]",
    "docstring": "Convert a list of bounding boxes from the format used by albumentations to a format, specified\n    in `target_format`.\n\n    Args:\n        bboxes (list): List of bounding box with coordinates in the format used by albumentations\n        target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'.\n        rows (int): image height\n        cols (int): image width\n        check_validity (bool): check if all boxes are valid boxes"
  },
  {
    "code": "def set_header_s(self, stream):\n        if self.argstreams[1].state == StreamState.init:\n            self.argstreams[1] = stream\n        else:\n            raise TChannelError(\n                \"Unable to change the header since the streaming has started\")",
    "docstring": "Set customized header stream.\n\n        Note: the header stream can only be changed before the stream\n        is consumed.\n\n        :param stream: InMemStream/PipeStream for header\n\n        :except TChannelError:\n            Raise TChannelError if the stream is being sent when you try\n            to change the stream."
  },
  {
    "code": "def get_complex_output(self, stderr=STDOUT):\n        proc = Popen(self.cmd, shell=True, stdout=PIPE, stderr=stderr)\n        return proc.stdout.readlines()",
    "docstring": "Executes a piped command and get the lines of the output in a list\n\n        :param stderr: where to put stderr\n        :return: output of command"
  },
  {
    "code": "def is_new_namespace_preorder( self, namespace_id_hash, lastblock=None ):\n        if lastblock is None:\n            lastblock = self.lastblock \n        preorder = namedb_get_namespace_preorder( self.db, namespace_id_hash, lastblock )\n        if preorder is not None:\n            return False \n        else:\n            return True",
    "docstring": "Given a namespace preorder hash, determine whether or not is is unseen before."
  },
  {
    "code": "def get_asset_content_form_for_update(self, asset_content_id=None):\n        if asset_content_id is None:\n            raise NullArgument()\n        asset = None\n        for a in AssetLookupSession(self._repository_id,\n                                    proxy=self._proxy,\n                                    runtime=self._runtime).get_assets():\n            for ac in a.get_asset_contents():\n                if ac.get_id() == asset_content_id:\n                    asset = a\n                    asset_content = ac\n        if asset is None:\n            raise NotFound()\n        asset_content_form = objects.AssetContentForm(asset_content._my_map, asset_id=asset.get_id())\n        self._forms[asset_content_form.get_id().get_identifier()] = not UPDATED\n        return asset_content_form",
    "docstring": "Gets the asset form for updating content for an existing asset.\n\n        A new asset content form should be requested for each update\n        transaction.\n\n        :param asset_content_id: the ``Id`` of the ``AssetContent``\n        :type asset_content_id: ``osid.id.Id``\n        :return: the asset content form\n        :rtype: ``osid.repository.AssetContentForm``\n        :raise: ``NotFound`` -- ``asset_content_id`` is not found\n        :raise: ``NullArgument`` -- ``asset_content_id`` is ``null``\n        :raise: ``OperationFailed`` -- unable to complete request\n\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def gen_oui_str(self, oui_list):\n        oui_str = []\n        for oui in oui_list:\n            oui_str.append('-c')\n            oui_str.append(oui)\n        return oui_str",
    "docstring": "Generate the OUI string for vdptool."
  },
  {
    "code": "def simplify_polynomial(polynomial, monomial_substitutions):\n    if isinstance(polynomial, (int, float, complex)):\n        return polynomial\n    polynomial = (1.0 * polynomial).expand(mul=True,\n                                           multinomial=True)\n    if is_number_type(polynomial):\n        return polynomial\n    if polynomial.is_Mul:\n        elements = [polynomial]\n    else:\n        elements = polynomial.as_coeff_mul()[1][0].as_coeff_add()[1]\n    new_polynomial = 0\n    for element in elements:\n        monomial, coeff = separate_scalar_factor(element)\n        monomial = apply_substitutions(monomial, monomial_substitutions)\n        new_polynomial += coeff * monomial\n    return new_polynomial",
    "docstring": "Simplify a polynomial for uniform handling later."
  },
  {
    "code": "def bottom(self):\n        if self.vMerge is not None:\n            tc_below = self._tc_below\n            if tc_below is not None and tc_below.vMerge == ST_Merge.CONTINUE:\n                return tc_below.bottom\n        return self._tr_idx + 1",
    "docstring": "The row index that marks the bottom extent of the vertical span of\n        this cell. This is one greater than the index of the bottom-most row\n        of the span, similar to how a slice of the cell's rows would be\n        specified."
  },
  {
    "code": "async def fire_sending(self,msg,num_repeats):\n        if num_repeats is None:\n            num_repeats = self.retry_count\n        sent_msg_count = 0\n        sleep_interval = 0.05\n        while(sent_msg_count < num_repeats):\n            if self.transport:\n                self.transport.sendto(msg.packed_message)\n            sent_msg_count += 1\n            await aio.sleep(sleep_interval)",
    "docstring": "Coroutine used to send message to the device when no response is needed.\n\n            :param msg: Message to send\n            :type msg: aiolifx.\n            :param num_repeats: number of times the message is to be sent.\n            :returns: The coroutine that can be scheduled to run\n            :rtype: coroutine"
  },
  {
    "code": "def set_group_conditions(self, group_id, conditions, trigger_mode=None):\n        data = self._serialize_object(conditions)\n        if trigger_mode is not None:\n            url = self._service_url(['triggers', 'groups', group_id, 'conditions', trigger_mode])\n        else:\n            url = self._service_url(['triggers', 'groups', group_id, 'conditions'])\n        response = self._put(url, data)\n        return Condition.list_to_object_list(response)",
    "docstring": "Set the group conditions.\n\n        This replaces any existing conditions on the group and member conditions for all trigger modes.\n\n        :param group_id: Group to be updated\n        :param conditions: New conditions to replace old ones\n        :param trigger_mode: Optional TriggerMode used\n        :type conditions: GroupConditionsInfo\n        :type trigger_mode: TriggerMode\n        :return: The new Group conditions"
  },
  {
    "code": "def _recurring_setExpressCheckout_adapter(self, params):\n        params['l_billingtype0'] = \"RecurringPayments\"\n        params['l_billingagreementdescription0'] = params['desc']\n        REMOVE = [\"billingfrequency\", \"billingperiod\", \"profilestartdate\", \"desc\"]\n        for k in params.keys():\n            if k in REMOVE:\n                del params[k]\n        return params",
    "docstring": "The recurring payment interface to SEC is different than the recurring payment\n        interface to ECP. This adapts a normal call to look like a SEC call."
  },
  {
    "code": "def _distribution_info(self):\n        print('Gathering information...')\n        system = platform.system()\n        system = 'cygwin' if 'CYGWIN' in system else system\n        processor = platform.processor()\n        machine = '64bit' if sys.maxsize > 2 ** 32 else '32bit'\n        print('SYSTEM:   ', system)\n        print('PROCESSOR:', processor)\n        print('MACHINE:  ', machine)\n        return self._dists[(system, machine)]",
    "docstring": "Creates the distribution name and the expected extension for the\n        CSPICE package and returns it.\n\n        :return (distribution, extension) tuple where distribution is the best\n                guess from the strings available within the platform_urls list\n                of strings, and extension is either \"zip\" or \"tar.Z\" depending\n                on whether we are dealing with a Windows platform or else.\n        :rtype: tuple (str, str)\n\n        :raises: KeyError if the (system, machine) tuple does not correspond\n                 to any of the supported SpiceyPy environments."
  },
  {
    "code": "def tropocollagen(\n            cls, aa=28, major_radius=5.0, major_pitch=85.0, auto_build=True):\n        instance = cls.from_parameters(\n            n=3, aa=aa, major_radius=major_radius, major_pitch=major_pitch,\n            phi_c_alpha=0.0, minor_helix_type='collagen', auto_build=False)\n        instance.major_handedness = ['r'] * 3\n        rpr_collagen = _helix_parameters['collagen'][1]\n        instance.z_shifts = [-rpr_collagen * 2, -rpr_collagen, 0.0]\n        instance.minor_repeats = [None] * 3\n        if auto_build:\n            instance.build()\n        return instance",
    "docstring": "Creates a model of a collagen triple helix.\n\n        Parameters\n        ----------\n        aa : int, optional\n            Number of amino acids per minor helix.\n        major_radius : float, optional\n            Radius of super helix.\n        major_pitch : float, optional\n            Pitch of super helix.\n        auto_build : bool, optional\n            If `True`, the model will be built as part of instantiation."
  },
  {
    "code": "def print_spans(spans, max_idx: int) -> None:\n    bel_spans = [\" \"] * (max_idx + 3)\n    for val, span in spans:\n        if val in [\"Nested\", \"NSArg\"]:\n            continue\n        for i in range(span[0], span[1] + 1):\n            bel_spans[i] = val[0]\n    bel_spans = [\" \"] * (max_idx + 3)\n    for val, span in spans:\n        if val not in [\"Nested\"]:\n            continue\n        for i in range(span[0], span[1] + 1):\n            bel_spans[i] = val[0]",
    "docstring": "Quick test to show how character spans match original BEL String\n\n    Mostly for debugging purposes"
  },
  {
    "code": "def get_graph(graph, conn, **kwargs):\n    sparql = render_without_request(\"sparqlGraphDataTemplate.rq\",\n                                    prefix=NSM.prefix(),\n                                    graph=graph)\n    return conn.query(sparql, **kwargs)",
    "docstring": "Returns all the triples for a specific are graph\n\n    args:\n        graph: the URI of the graph to retreive\n        conn: the rdfframework triplestore connection"
  },
  {
    "code": "def default_endpoint(ctx, param, value):\n    if ctx.resilient_parsing:\n        return\n    config = ctx.obj['config']\n    endpoint = default_endpoint_from_config(config, option=value)\n    if endpoint is None:\n        raise click.UsageError('No default endpoint found.')\n    return endpoint",
    "docstring": "Return default endpoint if specified."
  },
  {
    "code": "def serialize(self, o):\n        if isinstance(o, (list, tuple)):\n            return [self.serialize(i) for i in o]\n        if isinstance(o, dict):\n            return {k: self.serialize(v) for k, v in o.items()}\n        if isinstance(o, datetime):\n            return o.isoformat()\n        if isinstance(o, Result):\n            return self.serialize(o.serialize())\n        return o",
    "docstring": "Returns a safe serializable object that can be serialized into JSON.\n\n        @param o Python object to serialize"
  },
  {
    "code": "def get_host_health_data(self, data=None):\n        if not data or data and \"GET_EMBEDDED_HEALTH_DATA\" not in data:\n            data = self._execute_command(\n                'GET_EMBEDDED_HEALTH', 'SERVER_INFO', 'read')\n        return data",
    "docstring": "Request host health data of the server.\n\n        :param: the data to retrieve from the server, defaults to None.\n        :returns: the dictionary containing the embedded health data.\n        :raises: IloConnectionError if failed connecting to the iLO.\n        :raises: IloError, on an error from iLO."
  },
  {
    "code": "def cache_fake_input(cls, weld_input_id, fake_weld_input):\n        assert isinstance(weld_input_id, str)\n        assert isinstance(fake_weld_input, _FakeWeldInput)\n        Cache._cache[weld_input_id] = fake_weld_input",
    "docstring": "Cache the fake Weld input to be seen by LazyResult.evaluate\n\n        Parameters\n        ----------\n        weld_input_id : str\n            Generated when registering the fake_weld_input in WeldObject.update.\n        fake_weld_input : _FakeWeldInput\n            The fake Weld input previously generated by create_fake_array_input."
  },
  {
    "code": "def sky2px(wcs,ra,dec,dra,ddec,cell, beam):\n    dra = beam if dra<beam else dra\n    ddec = beam if ddec<beam else ddec\n    offsetDec = int((ddec/2.)/cell)\n    offsetRA = int((dra/2.)/cell)\n    if offsetDec%2==1:\n        offsetDec += 1\n    if offsetRA%2==1:\n        offsetRA += 1\n    raPix,decPix = map(int, wcs.wcs2pix(ra,dec))\n    return np.array([raPix-offsetRA,raPix+offsetRA,decPix-offsetDec,decPix+offsetDec])",
    "docstring": "convert a sky region to pixel positions"
  },
  {
    "code": "def EnqueueBreakpointUpdate(self, breakpoint):\n    with self._transmission_thread_startup_lock:\n      if self._transmission_thread is None:\n        self._transmission_thread = threading.Thread(\n            target=self._TransmissionThreadProc)\n        self._transmission_thread.name = 'Cloud Debugger transmission thread'\n        self._transmission_thread.daemon = True\n        self._transmission_thread.start()\n    self._transmission_queue.append((breakpoint, 0))\n    self._new_updates.set()",
    "docstring": "Asynchronously updates the specified breakpoint on the backend.\n\n    This function returns immediately. The worker thread is actually doing\n    all the work. The worker thread is responsible to retry the transmission\n    in case of transient errors.\n\n    Args:\n      breakpoint: breakpoint in either final or non-final state."
  },
  {
    "code": "def _initialize_logging():\n    if sys.stdout.isatty() or platform.system() in (\"Darwin\", \"Linux\"):\n        RuntimeGlobals.logging_console_handler = foundations.verbose.get_logging_console_handler()\n    RuntimeGlobals.logging_formatters = {\"Default\": foundations.verbose.LOGGING_DEFAULT_FORMATTER,\n                                         \"Extended\": foundations.verbose.LOGGING_EXTENDED_FORMATTER,\n                                         \"Standard\": foundations.verbose.LOGGING_STANDARD_FORMATTER}",
    "docstring": "Initializes the Application logging."
  },
  {
    "code": "def render(self, data, accepted_media_type=None, renderer_context=None):\n        if data is None:\n            return bytes()\n        renderer_context = renderer_context or {}\n        indent = self.get_indent(accepted_media_type, renderer_context)\n        if indent is None:\n            separators = SHORT_SEPARATORS if self.compact else LONG_SEPARATORS\n        else:\n            separators = INDENT_SEPARATORS\n        ret = json.dumps(\n            data, cls=self.encoder_class,\n            indent=indent, ensure_ascii=self.ensure_ascii,\n            separators=separators\n        )\n        if isinstance(ret, six.text_type):\n            ret = ret.replace('\\u2028', '\\\\u2028').replace('\\u2029', '\\\\u2029')\n            return bytes(ret.encode('utf-8'))\n        return ret",
    "docstring": "Render `data` into JSON, returning a bytestring."
  },
  {
    "code": "def make_shift_function(alphabet):\n    def shift_case_sensitive(shift, symbol):\n        case = [case for case in alphabet if symbol in case]\n        if not case:\n            return symbol\n        case = case[0]\n        index = case.index(symbol)\n        return case[(index - shift) % len(case)]\n    return shift_case_sensitive",
    "docstring": "Construct a shift function from an alphabet.\n\n    Examples:\n        Shift cases independently\n\n        >>> make_shift_function([string.ascii_uppercase, string.ascii_lowercase])\n        <function make_shift_function.<locals>.shift_case_sensitive>\n\n        Additionally shift punctuation characters\n\n        >>> make_shift_function([string.ascii_uppercase, string.ascii_lowercase, string.punctuation])\n        <function make_shift_function.<locals>.shift_case_sensitive>\n\n        Shift entire ASCII range, overflowing cases\n\n        >>> make_shift_function([''.join(chr(x) for x in range(32, 127))])\n        <function make_shift_function.<locals>.shift_case_sensitive>\n\n    Args:\n        alphabet (iterable): Ordered iterable of strings representing separate cases of an alphabet\n\n    Returns:\n        Function (shift, symbol)"
  },
  {
    "code": "def get_meta_graph_def(saved_model_dir, tag_set):\n  saved_model = reader.read_saved_model(saved_model_dir)\n  set_of_tags = set(tag_set.split(','))\n  for meta_graph_def in saved_model.meta_graphs:\n    if set(meta_graph_def.meta_info_def.tags) == set_of_tags:\n      return meta_graph_def\n  raise RuntimeError(\"MetaGraphDef associated with tag-set {0} could not be found in SavedModel\".format(tag_set))",
    "docstring": "Utility function to read a meta_graph_def from disk.\n\n  From `saved_model_cli.py <https://github.com/tensorflow/tensorflow/blob/8e0e8d41a3a8f2d4a6100c2ea1dc9d6c6c4ad382/tensorflow/python/tools/saved_model_cli.py#L186>`_\n\n  Args:\n    :saved_model_dir: path to saved_model.\n    :tag_set: list of string tags identifying the TensorFlow graph within the saved_model.\n\n  Returns:\n    A TensorFlow meta_graph_def, or raises an Exception otherwise."
  },
  {
    "code": "def validate_enum_attribute(fully_qualified_name: str, spec: Dict[str, Any], attribute: str,\n                            candidates: Set[Union[str, int, float]]) -> Optional[InvalidValueError]:\n    if attribute not in spec:\n        return\n    if spec[attribute] not in candidates:\n        return InvalidValueError(fully_qualified_name, spec, attribute, candidates)",
    "docstring": "Validates to ensure that the value of an attribute lies within an allowed set of candidates"
  },
  {
    "code": "def reverse_url(self, datatype, url, verb='GET', urltype='single', api_version=None):\n        api_version = api_version or 'v1'\n        templates = getattr(self, 'URL_TEMPLATES__%s' % api_version)\n        template_url = r\"https://(?P<api_host>.+)/services/api/(?P<api_version>.+)\"\n        template_url += re.sub(r'{([^}]+)}', r'(?P<\\1>.+)', templates[datatype][verb][urltype])\n        m = re.match(template_url, url or '')\n        if not m:\n            raise KeyError(\"No reverse match from '%s' to %s.%s.%s\" % (url, datatype, verb, urltype))\n        r = m.groupdict()\n        del r['api_host']\n        if r.pop('api_version') != api_version:\n            raise ValueError(\"API version mismatch\")\n        return r",
    "docstring": "Extracts parameters from a populated URL\n\n        :param datatype: a string identifying the data the url accesses.\n        :param url: the fully-qualified URL to extract parameters from.\n        :param verb: the HTTP verb needed for use with the url.\n        :param urltype: an adjective used to the nature of the request.\n        :return: dict"
  },
  {
    "code": "def finish(self, items=None, sort_methods=None, succeeded=True,\n               update_listing=False, cache_to_disc=True, view_mode=None):\n        if items:\n            self.add_items(items)\n        if sort_methods:\n            for sort_method in sort_methods:\n                if not isinstance(sort_method, basestring) and hasattr(sort_method, '__len__'):\n                    self.add_sort_method(*sort_method)\n                else:\n                    self.add_sort_method(sort_method)\n        if view_mode is not None:\n            try:\n                view_mode_id = int(view_mode)\n            except ValueError:\n                view_mode_id = self.get_view_mode_id(view_mode)\n            if view_mode_id is not None:\n                self.set_view_mode(view_mode_id)\n        self.end_of_directory(succeeded, update_listing, cache_to_disc)\n        return self.added_items",
    "docstring": "Adds the provided items to the XBMC interface.\n\n        :param items: an iterable of items where each item is either a\n            dictionary with keys/values suitable for passing to\n            :meth:`xbmcswift2.ListItem.from_dict` or an instance of\n            :class:`xbmcswift2.ListItem`.\n        :param sort_methods: a list of valid XBMC sort_methods. Each item in\n                             the list can either be a sort method or a tuple of\n                             ``sort_method, label2_mask``. See\n                             :meth:`add_sort_method` for\n                             more detail concerning valid sort_methods.\n\n                             Example call with sort_methods::\n\n                                sort_methods = ['label', 'title', ('date', '%D')]\n                                plugin.finish(items, sort_methods=sort_methods)\n\n        :param view_mode: can either be an integer (or parseable integer\n            string) corresponding to a view_mode or the name of a type of view.\n            Currrently the only view type supported is 'thumbnail'.\n        :returns: a list of all ListItems added to the XBMC interface."
  },
  {
    "code": "def get_instance(self, payload):\n        return WorkerInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], )",
    "docstring": "Build an instance of WorkerInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance\n        :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance"
  },
  {
    "code": "def client_new():\n    form = ClientForm(request.form)\n    if form.validate_on_submit():\n        c = Client(user_id=current_user.get_id())\n        c.gen_salt()\n        form.populate_obj(c)\n        db.session.add(c)\n        db.session.commit()\n        return redirect(url_for('.client_view', client_id=c.client_id))\n    return render_template(\n        'invenio_oauth2server/settings/client_new.html',\n        form=form,\n    )",
    "docstring": "Create new client."
  },
  {
    "code": "def _invokeWrite(self, fileIO, session, directory, filename, replaceParamFile):\n        instance = None\n        try:\n            instance = session.query(fileIO). \\\n                filter(fileIO.projectFile == self). \\\n                one()\n        except:\n            extension = filename.split('.')[1]\n            try:\n                instance = session.query(fileIO). \\\n                    filter(fileIO.projectFile == self). \\\n                    filter(fileIO.fileExtension == extension). \\\n                    one()\n            except NoResultFound:\n                log.warning('{0} listed as card in project file, but '\n                         'the file is not found in the database.'.format(filename))\n            except MultipleResultsFound:\n                self._invokeWriteForMultipleOfType(directory, extension, fileIO,\n                                                   filename, session,\n                                                   replaceParamFile=replaceParamFile)\n                return\n        if instance is not None:\n            instance.write(session=session, directory=directory, name=filename,\n                           replaceParamFile=replaceParamFile)",
    "docstring": "Invoke File Write Method on Other Files"
  },
  {
    "code": "def to_str(obj):\n    if not isinstance(obj, str) and PY3 and isinstance(obj, bytes):\n        obj = obj.decode('utf-8')\n    return obj if isinstance(obj, string_types) else str(obj)",
    "docstring": "Attempts to convert given object to a string object"
  },
  {
    "code": "def touch(ctx, key, policy, admin_pin, force):\n    controller = ctx.obj['controller']\n    old_policy = controller.get_touch(key)\n    if old_policy == TOUCH_MODE.FIXED:\n        ctx.fail('A FIXED policy cannot be changed!')\n    force or click.confirm('Set touch policy of {.name} key to {.name}?'.format(\n        key, policy), abort=True, err=True)\n    if admin_pin is None:\n        admin_pin = click.prompt('Enter admin PIN', hide_input=True, err=True)\n    controller.set_touch(key, policy, admin_pin.encode('utf8'))",
    "docstring": "Manage touch policy for OpenPGP keys.\n\n    \\b\n    KEY     Key slot to set (sig, enc or aut).\n    POLICY  Touch policy to set (on, off or fixed)."
  },
  {
    "code": "def delete_tag_for_component(user, c_id, tag_id):\n    query = _TABLE_TAGS.delete().where(_TABLE_TAGS.c.tag_id == tag_id and\n                                       _TABLE_TAGS.c.component_id == c_id)\n    try:\n        flask.g.db_conn.execute(query)\n    except sa_exc.IntegrityError:\n        raise dci_exc.DCICreationConflict(_TABLE_TAGS.c.tag_id, 'tag_id')\n    return flask.Response(None, 204, content_type='application/json')",
    "docstring": "Delete a tag on a specific component."
  },
  {
    "code": "def focus_prev_sibling(self):\n        mid = self.get_selected_mid()\n        localroot = self._sanitize_position((mid,))\n        if localroot == self.get_focus()[1]:\n            newpos = self._tree.prev_sibling_position(mid)\n            if newpos is not None:\n                newpos = self._sanitize_position((newpos,))\n        else:\n            newpos = localroot\n        if newpos is not None:\n            self.body.set_focus(newpos)",
    "docstring": "focus previous sibling of currently focussed message in thread tree"
  },
  {
    "code": "def get_row_data(self, row, name=None):\n        retdict = {}\n        for rowname, data in zip(self.get_DataFrame(),\n                                 self.get_DataFrame(data=True)):\n            retdict[rowname] = pd.DataFrame(data.ix[row])\n        if name:\n            retdict['name'] = name\n        return retdict",
    "docstring": "Returns a dict with all available data for a row in the extension\n\n        Parameters\n        ----------\n        row : tuple, list, string\n            A valid index for the extension DataFrames\n        name : string, optional\n            If given, adds a key 'name' with the given value to the dict. In\n            that case the dict can be\n            used directly to build a new extension.\n\n        Returns\n        -------\n        dict object with the data (pandas DataFrame)for the specific rows"
  },
  {
    "code": "def delegate_names(delegate, accessors, typ, overwrite=False):\n    def add_delegate_accessors(cls):\n        cls._add_delegate_accessors(delegate, accessors, typ,\n                                    overwrite=overwrite)\n        return cls\n    return add_delegate_accessors",
    "docstring": "Add delegated names to a class using a class decorator.  This provides\n    an alternative usage to directly calling `_add_delegate_accessors`\n    below a class definition.\n\n    Parameters\n    ----------\n    delegate : object\n        the class to get methods/properties & doc-strings\n    accessors : Sequence[str]\n        List of accessor to add\n    typ : {'property', 'method'}\n    overwrite : boolean, default False\n       overwrite the method/property in the target class if it exists\n\n    Returns\n    -------\n    callable\n        A class decorator.\n\n    Examples\n    --------\n    @delegate_names(Categorical, [\"categories\", \"ordered\"], \"property\")\n    class CategoricalAccessor(PandasDelegate):\n        [...]"
  },
  {
    "code": "def bench_report(results):\n    table = Table(names=['function', 'nest', 'nside', 'size',\n                         'time_healpy', 'time_self', 'ratio'],\n                  dtype=['S20', bool, int, int, float, float, float], masked=True)\n    for row in results:\n        table.add_row(row)\n    table['time_self'].format = '10.7f'\n    if HEALPY_INSTALLED:\n        table['ratio'] = table['time_self'] / table['time_healpy']\n        table['time_healpy'].format = '10.7f'\n        table['ratio'].format = '7.2f'\n    table.pprint(max_lines=-1)",
    "docstring": "Print a report for given benchmark results to the console."
  },
  {
    "code": "def build_specfile_header(spec):\n    str = \"\"\n    mandatory_header_fields = {\n        'NAME'           : '%%define name %s\\nName: %%{name}\\n',\n        'VERSION'        : '%%define version %s\\nVersion: %%{version}\\n',\n        'PACKAGEVERSION' : '%%define release %s\\nRelease: %%{release}\\n',\n        'X_RPM_GROUP'    : 'Group: %s\\n',\n        'SUMMARY'        : 'Summary: %s\\n',\n        'LICENSE'        : 'License: %s\\n', }\n    str = str + SimpleTagCompiler(mandatory_header_fields).compile( spec )\n    optional_header_fields = {\n        'VENDOR'              : 'Vendor: %s\\n',\n        'X_RPM_URL'           : 'Url: %s\\n',\n        'SOURCE_URL'          : 'Source: %s\\n',\n        'SUMMARY_'            : 'Summary(%s): %s\\n',\n        'X_RPM_DISTRIBUTION'  : 'Distribution: %s\\n',\n        'X_RPM_ICON'          : 'Icon: %s\\n',\n        'X_RPM_PACKAGER'      : 'Packager: %s\\n',\n        'X_RPM_GROUP_'        : 'Group(%s): %s\\n',\n        'X_RPM_REQUIRES'      : 'Requires: %s\\n',\n        'X_RPM_PROVIDES'      : 'Provides: %s\\n',\n        'X_RPM_CONFLICTS'     : 'Conflicts: %s\\n',\n        'X_RPM_BUILDREQUIRES' : 'BuildRequires: %s\\n',\n        'X_RPM_SERIAL'        : 'Serial: %s\\n',\n        'X_RPM_EPOCH'         : 'Epoch: %s\\n',\n        'X_RPM_AUTOREQPROV'   : 'AutoReqProv: %s\\n',\n        'X_RPM_EXCLUDEARCH'   : 'ExcludeArch: %s\\n',\n        'X_RPM_EXCLUSIVEARCH' : 'ExclusiveArch: %s\\n',\n        'X_RPM_PREFIX'        : 'Prefix: %s\\n',\n        'X_RPM_BUILDROOT'     : 'BuildRoot: %s\\n', }\n    if 'X_RPM_BUILDROOT' not in spec:\n        spec['X_RPM_BUILDROOT'] = '%{_tmppath}/%{name}-%{version}-%{release}'\n    str = str + SimpleTagCompiler(optional_header_fields, mandatory=0).compile( spec )\n    return str",
    "docstring": "Builds all sections but the %file of a rpm specfile"
  },
  {
    "code": "def find_elb_dns_zone_id(name='', env='dev', region='us-east-1'):\n    LOG.info('Find %s ELB DNS Zone ID in %s [%s].', name, env, region)\n    client = boto3.Session(profile_name=env).client('elb', region_name=region)\n    elbs = client.describe_load_balancers(LoadBalancerNames=[name])\n    return elbs['LoadBalancerDescriptions'][0]['CanonicalHostedZoneNameID']",
    "docstring": "Get an application's AWS elb dns zone id.\n\n    Args:\n        name (str): ELB name\n        env (str): Environment/account of ELB\n        region (str): AWS Region\n\n    Returns:\n        str: elb DNS zone ID"
  },
  {
    "code": "def _check_emphasis(numbers, emph):\n    \"Find index postions in list of numbers to be emphasized according to emph.\"\n    pat = '(\\w+)\\:(eq|gt|ge|lt|le)\\:(.+)'\n    emphasized = {}\n    for (i, n) in enumerate(numbers):\n        if n is None:\n            continue\n        for em in emph:\n            color, op, value = re.match(pat, em).groups()\n            value = float(value)\n            if op == 'eq' and n == value:\n                emphasized[i] = color\n            elif op == 'gt' and n > value:\n                emphasized[i] = color\n            elif op == 'ge' and n >= value:\n                emphasized[i] = color\n            elif op == 'lt' and n < value:\n                emphasized[i] = color\n            elif op == 'le' and n <= value:\n                emphasized[i] = color\n    return emphasized",
    "docstring": "Find index postions in list of numbers to be emphasized according to emph."
  },
  {
    "code": "def save(self, *args, **kwargs):\n        old_instance = None\n        if self.pk:\n            old_instance = self.__class__._default_manager.get(pk=self.pk)\n        self.slug = slugify(force_text(self.name), allow_unicode=True)\n        super().save(*args, **kwargs)\n        if old_instance and old_instance.parent != self.parent:\n            self.update_trackers()\n            signals.forum_moved.send(sender=self, previous_parent=old_instance.parent)",
    "docstring": "Saves the forum instance."
  },
  {
    "code": "def read_lamination_parameters(thickness, laminaprop, rho,\n                               xiA1, xiA2, xiA3, xiA4,\n                               xiB1, xiB2, xiB3, xiB4,\n                               xiD1, xiD2, xiD3, xiD4,\n                               xiE1, xiE2, xiE3, xiE4):\n    r\n    lam = Laminate()\n    lam.h = thickness\n    lam.matobj = read_laminaprop(laminaprop, rho)\n    lam.xiA = np.array([1, xiA1, xiA2, xiA3, xiA4], dtype=np.float64)\n    lam.xiB = np.array([0, xiB1, xiB2, xiB3, xiB4], dtype=np.float64)\n    lam.xiD = np.array([1, xiD1, xiD2, xiD3, xiD4], dtype=np.float64)\n    lam.xiE = np.array([1, xiE1, xiE2, xiE3, xiE4], dtype=np.float64)\n    lam.calc_ABDE_from_lamination_parameters()\n    return lam",
    "docstring": "r\"\"\"Calculates a laminate based on the lamination parameters.\n\n    The lamination parameters:\n    `\\xi_{A1} \\cdots \\xi_{A4}`,  `\\xi_{B1} \\cdots \\xi_{B4}`,\n    `\\xi_{C1} \\cdots \\xi_{C4}`,  `\\xi_{D1} \\cdots \\xi_{D4}`,\n    `\\xi_{E1} \\cdots \\xi_{E4}`\n\n    are used to calculate the laminate constitutive matrix.\n\n    Parameters\n    ----------\n    thickness : float\n        The total thickness of the laminate\n    laminaprop : tuple\n        The laminaprop tuple used to define the laminate material.\n    rho : float\n        Material density.\n    xiA1 to xiD4 : float\n        The 16 lamination parameters used to define the laminate.\n\n    Returns\n    -------\n    lam : Laminate\n        laminate with the ABD and ABDE matrices already calculated"
  },
  {
    "code": "def join(cls, splits):\n        segments = []\n        for split in splits:\n            segments.append('\"{}\",'.format(split))\n        if len(segments) > 0:\n            segments[-1] = segments[-1][:-1]\n        jsonString = '[{}]'.format(''.join(segments))\n        return jsonString",
    "docstring": "Join an array of ids into a compound id string"
  },
  {
    "code": "def init_params(self, initializer=Uniform(0.01), arg_params=None, aux_params=None,\n                    allow_missing=False, force_init=False, allow_extra=False):\n        pass",
    "docstring": "Initializes the parameters and auxiliary states. By default this function\n        does nothing. Subclass should override this method if contains parameters.\n\n        Parameters\n        ----------\n        initializer : Initializer\n            Called to initialize parameters if needed.\n        arg_params : dict\n            If not ``None``, should be a dictionary of existing `arg_params`. Initialization\n            will be copied from that.\n        aux_params : dict\n            If not ``None``, should be a dictionary of existing `aux_params`. Initialization\n            will be copied from that.\n        allow_missing : bool\n            If ``True``, params could contain missing values, and the initializer will be\n            called to fill those missing params.\n        force_init : bool\n            If ``True``, will force re-initialize even if already initialized.\n        allow_extra : boolean, optional\n            Whether allow extra parameters that are not needed by symbol.\n            If this is True, no error will be thrown when arg_params or aux_params\n            contain extra parameters that is not needed by the executor."
  },
  {
    "code": "def write_eof(self):\n        self._check_writable()\n        self._transport._can_write.wait()\n        self._transport.write_eof()",
    "docstring": "Close the write direction of the transport.\n\n        This method will block if the transport's write buffer is at capacity."
  },
  {
    "code": "def cf_encoder(variables, attributes):\n    new_vars = OrderedDict((k, encode_cf_variable(v, name=k))\n                           for k, v in variables.items())\n    return new_vars, attributes",
    "docstring": "A function which takes a dicts of variables and attributes\n    and encodes them to conform to CF conventions as much\n    as possible.  This includes masking, scaling, character\n    array handling, and CF-time encoding.\n\n    Decode a set of CF encoded variables and attributes.\n\n    See Also, decode_cf_variable\n\n    Parameters\n    ----------\n    variables : dict\n        A dictionary mapping from variable name to xarray.Variable\n    attributes : dict\n        A dictionary mapping from attribute name to value\n\n    Returns\n    -------\n    encoded_variables : dict\n        A dictionary mapping from variable name to xarray.Variable,\n    encoded_attributes : dict\n        A dictionary mapping from attribute name to value\n\n    See also: encode_cf_variable"
  },
  {
    "code": "def set_extra_info(self, username, extra_info):\n        url = self._get_extra_info_url(username)\n        make_request(url, method='PUT', body=extra_info, timeout=self.timeout)",
    "docstring": "Set extra info for the given user.\n\n        Raise a ServerError if an error occurs in the request process.\n\n        @param username The username for the user to update.\n        @param info The extra info as a JSON encoded string, or as a Python\n            dictionary like object."
  },
  {
    "code": "def flat_data(self):\n        def flat_field(value):\n            try:\n                value.flat_data()\n                return value\n            except AttributeError:\n                return value\n        modified_dict = self.__original_data__\n        modified_dict.update(self.__modified_data__)\n        self.__original_data__ = {k: flat_field(v)\n                                  for k, v in modified_dict.items()\n                                  if k not in self.__deleted_fields__}\n        self.clear_modified_data()",
    "docstring": "Pass all the data from modified_data to original_data"
  },
  {
    "code": "def sqlvm_aglistener_create(client, cmd, availability_group_listener_name, sql_virtual_machine_group_name,\n                            resource_group_name, availability_group_name, ip_address, subnet_resource_id,\n                            load_balancer_resource_id, probe_port, sql_virtual_machine_instances, port=1433,\n                            public_ip_address_resource_id=None):\n    if not is_valid_resource_id(subnet_resource_id):\n        raise CLIError(\"Invalid subnet resource id.\")\n    if not is_valid_resource_id(load_balancer_resource_id):\n        raise CLIError(\"Invalid load balancer resource id.\")\n    if public_ip_address_resource_id and not is_valid_resource_id(public_ip_address_resource_id):\n        raise CLIError(\"Invalid public IP address resource id.\")\n    for sqlvm in sql_virtual_machine_instances:\n        if not is_valid_resource_id(sqlvm):\n            raise CLIError(\"Invalid SQL virtual machine resource id.\")\n    private_ip_object = PrivateIPAddress(ip_address=ip_address,\n                                         subnet_resource_id=subnet_resource_id\n                                         if is_valid_resource_id(subnet_resource_id) else None)\n    load_balancer_object = LoadBalancerConfiguration(private_ip_address=private_ip_object,\n                                                     public_ip_address_resource_id=public_ip_address_resource_id,\n                                                     load_balancer_resource_id=load_balancer_resource_id,\n                                                     probe_port=probe_port,\n                                                     sql_virtual_machine_instances=sql_virtual_machine_instances)\n    ag_listener_object = AvailabilityGroupListener(availability_group_name=availability_group_name,\n                                                   load_balancer_configurations=load_balancer_object,\n                                                   port=port)\n    LongRunningOperation(cmd.cli_ctx)(sdk_no_wait(False, client.create_or_update, resource_group_name,\n                                                  sql_virtual_machine_group_name, availability_group_listener_name,\n                                                  ag_listener_object))\n    return client.get(resource_group_name, sql_virtual_machine_group_name, availability_group_listener_name)",
    "docstring": "Creates an availability group listener"
  },
  {
    "code": "def on_message(self, ws, message):\n        try:\n            data = json.loads(message)\n        except Exception:\n            self._set_error(message, \"decode message failed\")\n        else:\n            self._inbox.put(RTMMessage(data))",
    "docstring": "Websocket on_message event handler\n\n        Saves message as RTMMessage in self._inbox"
  },
  {
    "code": "def _geoid_radius(latitude: float) -> float:\n    lat = deg2rad(latitude)\n    return sqrt(1/(cos(lat) ** 2 / Rmax_WGS84 ** 2 + sin(lat) ** 2 / Rmin_WGS84 ** 2))",
    "docstring": "Calculates the GEOID radius at a given latitude\n\n    Parameters\n    ----------\n    latitude : float\n        Latitude (degrees)\n\n    Returns\n    -------\n    R : float\n        GEOID Radius (meters)"
  },
  {
    "code": "def _connect(self):\n        try:\n            if sys.version_info[:2] >= (2,6):\n                self._conn = telnetlib.Telnet(self._amihost, self._amiport, \n                                              connTimeout)\n            else:\n                self._conn = telnetlib.Telnet(self._amihost, self._amiport)\n        except:\n            raise Exception(\n                \"Connection to Asterisk Manager Interface on \"\n                \"host %s and port %s failed.\"\n                % (self._amihost, self._amiport)\n                )",
    "docstring": "Connect to Asterisk Manager Interface."
  },
  {
    "code": "def cdfNormal(z):\n    if (abs(z) < ERF_CODY_LIMIT1):\n        return 0.5 * (1.0 + (z / M_SQRT2) * _erfRationalHelperR3(0.5 * z * z))\n    elif (z < 0.0):\n        return np.exp(logPdfNormal(z)) * _erfRationalHelper(-z) / (-z)\n    else:\n        return 1.0 - np.exp(logPdfNormal(z)) * _erfRationalHelper(z) / z",
    "docstring": "Robust implementations of cdf of a standard normal.\n\n     @see [[https://github.com/mseeger/apbsint/blob/master/src/eptools/potentials/SpecfunServices.h original implementation]]\n     in C from Matthias Seeger.\n    */"
  },
  {
    "code": "def has_source_contents(self, src_id):\n        return bool(rustcall(_lib.lsm_view_has_source_contents,\n                             self._get_ptr(), src_id))",
    "docstring": "Checks if some sources exist."
  },
  {
    "code": "def parse_int_list(s):\n    result = []\n    for item in s.split(','):\n        item = item.strip().split('-')\n        if len(item) == 1:\n            result.append(int(item[0]))\n        elif len(item) == 2:\n            start, end = item\n            result.extend(range(int(start), int(end)+1))\n        else:\n            raise ValueError(\"invalid range: '{0}'\".format(s))\n    return result",
    "docstring": "Parse a comma-separated list of strings.\n    The list may additionally contain ranges such as \"1-5\",\n    which will be expanded into \"1,2,3,4,5\"."
  },
  {
    "code": "def read(handle, bytes):\n        return Zchunk(lib.zchunk_read(coerce_py_file(handle), bytes), True)",
    "docstring": "Read chunk from an open file descriptor"
  },
  {
    "code": "def index():\n    global productpage\n    table = json2html.convert(json = json.dumps(productpage),\n                              table_attributes=\"class=\\\"table table-condensed table-bordered table-hover\\\"\")\n    return render_template('index.html', serviceTable=table)",
    "docstring": "Display productpage with normal user and test user buttons"
  },
  {
    "code": "def _create_oracle(oracle_type, **kwargs):\n    if oracle_type == 'f':\n        return FO(**kwargs)\n    elif oracle_type == 'a':\n        return MO(**kwargs)\n    else:\n        return MO(**kwargs)",
    "docstring": "A routine for creating a factor oracle."
  },
  {
    "code": "def is_char_in_pairs(pos_char, pairs):\r\n        for pos_left, pos_right in pairs.items():\r\n            if pos_left < pos_char < pos_right:\r\n                return True\r\n        return False",
    "docstring": "Return True if the charactor is in pairs of brackets or quotes."
  },
  {
    "code": "def set_title(self, name):\n        self._set_attr(TIT2(encoding=3, text=name.decode('utf-8')))",
    "docstring": "Sets song's title\n\n        :param name: title"
  },
  {
    "code": "def pop(self, index=None):\n    if not self.items:\n        raise KeyError('Set is empty')\n    def remove_index(i):\n        elem = self.items[i]\n        del self.items[i]\n        del self.map[elem]\n        return elem\n    if index is None:\n        elem = remove_index(-1)\n    else:\n        size = len(self.items)\n        if index < 0:\n            index = size + index\n            if index < 0:\n                raise IndexError('assignement index out of range')\n        elif index >= size:\n            raise IndexError('assignement index out of range')\n        elem = remove_index(index)\n        for k, v in self.map.items():\n            if v >= index and v > 0:\n                self.map[k] = v - 1\n    return elem",
    "docstring": "Removes an element at the tail of the OrderedSet or at a dedicated\n    position.\n\n    This implementation is meant for the OrderedSet from the ordered_set\n    package only."
  },
  {
    "code": "def swipe(self, element, x, y, duration=None):\n        if not self.driver_wrapper.is_mobile_test():\n            raise Exception('Swipe method is not implemented in Selenium')\n        center = self.get_center(element)\n        initial_context = self.driver_wrapper.driver.current_context\n        if self.driver_wrapper.is_web_test() or initial_context != 'NATIVE_APP':\n            center = self.get_native_coords(center)\n        end_x = x if self.driver_wrapper.is_ios_test() else center['x'] + x\n        end_y = y if self.driver_wrapper.is_ios_test() else center['y'] + y\n        self.driver_wrapper.driver.swipe(center['x'], center['y'], end_x, end_y, duration)\n        if self.driver_wrapper.is_web_test() or initial_context != 'NATIVE_APP':\n            self.driver_wrapper.driver.switch_to.context(initial_context)",
    "docstring": "Swipe over an element\n\n        :param element: either a WebElement, PageElement or element locator as a tuple (locator_type, locator_value)\n        :param x: horizontal movement\n        :param y: vertical movement\n        :param duration: time to take the swipe, in ms"
  },
  {
    "code": "def get_object_closure(subject, object_category=None, **kwargs):\n    results = search_associations(subject=subject,\n                                  object_category=object_category,\n                                  select_fields=[],\n                                  facet_fields=[M.OBJECT_CLOSURE],\n                                  facet_limit=-1,\n                                  rows=0,\n                                  **kwargs)\n    return set(results['facet_counts'][M.OBJECT_CLOSURE].keys())",
    "docstring": "Find all terms used to annotate subject plus ancestors"
  },
  {
    "code": "def _django_to_es_field(self, field):\n        from django.db import models\n        prefix = \"\"\n        if field.startswith(\"-\"):\n            prefix = \"-\"\n            field = field.lstrip(\"-\")\n        if field in [\"id\", \"pk\"]:\n            return \"_id\", models.AutoField\n        try:\n            dj_field, _, _, _ = self.model._meta.get_field_by_name(field)\n            if isinstance(dj_field, models.ForeignKey):\n                return prefix + field + \"_id\", models.ForeignKey\n            else:\n                return prefix + field, dj_field\n        except models.FieldDoesNotExist:\n            pass\n        return prefix + field.replace(FIELD_SEPARATOR, \".\"), None",
    "docstring": "We use this function in value_list and ordering to get the correct fields name"
  },
  {
    "code": "def load_x509_certificates(buf):\n  if not isinstance(buf, basestring):\n    raise ValueError('`buf` should be an instance of `basestring` not `%s`' % type(buf))\n  for pem in re.findall('(-----BEGIN CERTIFICATE-----\\s(\\S+\\n*)+\\s-----END CERTIFICATE-----\\s)', buf):\n    yield load_certificate(crypto.FILETYPE_PEM, pem[0])",
    "docstring": "Load one or multiple X.509 certificates from a buffer.\n\n  :param str buf: A buffer is an instance of `basestring` and can contain multiple\n    certificates.\n  :return: An iterator that iterates over certificates in a buffer.\n  :rtype: list[:class:`OpenSSL.crypto.X509`]"
  },
  {
    "code": "def lemma(self):\n        if self._lemma is None:\n            lemmata = self._element.xpath('lemma/text()')\n            if len(lemmata) > 0:\n                self._lemma = lemmata[0]\n        return self._lemma",
    "docstring": "Lazy-loads the lemma for this word\n\n        :getter: Returns the plain string value of the word lemma\n        :type: str"
  },
  {
    "code": "def sas_logical_jbods(self):\n        if not self.__sas_logical_jbods:\n            self.__sas_logical_jbods = SasLogicalJbods(self.__connection)\n        return self.__sas_logical_jbods",
    "docstring": "Gets the SAS Logical JBODs API client.\n\n        Returns:\n            SasLogicalJbod:"
  },
  {
    "code": "def process_text(text, pmid=None, python2_path=None):\n    if python2_path is None:\n        for path in os.environ[\"PATH\"].split(os.pathsep):\n            proposed_python2_path = os.path.join(path, 'python2.7')\n            if os.path.isfile(proposed_python2_path):\n                python2_path = proposed_python2_path\n                print('Found python 2 interpreter at', python2_path)\n                break\n    if python2_path is None:\n        raise Exception('Could not find python2 in the directories ' +\n                        'listed in the PATH environment variable. ' +\n                        'Need python2 to run TEES.')\n    a1_text, a2_text, sentence_segmentations = run_on_text(text,\n                                                                python2_path)\n    tp = TEESProcessor(a1_text, a2_text, sentence_segmentations, pmid)\n    return tp",
    "docstring": "Processes the specified plain text with TEES and converts output to\n    supported INDRA statements. Check for the TEES installation is the\n    TEES_PATH environment variable, and configuration file; if not found,\n    checks candidate paths in tees_candidate_paths. Raises an exception if\n    TEES cannot be found in any of these places.\n\n    Parameters\n    ----------\n    text : str\n        Plain text to process with TEES\n    pmid : str\n        The PMID from which the paper comes from, to be stored in the Evidence\n        object of statements. Set to None if this is unspecified.\n    python2_path : str\n        TEES is only compatible with python 2. This processor invokes this\n        external python 2 interpreter so that the processor can be run in\n        either python 2 or python 3. If None, searches for an executible named\n        python2 in the PATH environment variable.\n\n    Returns\n    -------\n    tp : TEESProcessor\n        A TEESProcessor object which contains a list of INDRA statements\n        extracted from TEES extractions"
  },
  {
    "code": "def ns_whois(self, nameservers, limit=DEFAULT_LIMIT, offset=DEFAULT_OFFSET, sort_field=DEFAULT_SORT):\n        if not isinstance(nameservers, list):\n            uri = self._uris[\"whois_ns\"].format(nameservers)\n            params = {'limit': limit, 'offset': offset, 'sortField': sort_field}\n        else:\n            uri = self._uris[\"whois_ns\"].format('')\n            params = {'emailList' : ','.join(nameservers), 'limit': limit, 'offset': offset, 'sortField': sort_field}\n        resp_json = self.get_parse(uri, params=params)\n        return resp_json",
    "docstring": "Gets the domains that have been registered with a nameserver or\n        nameservers"
  },
  {
    "code": "def create_negotiate_message(self, domain_name=None, workstation=None):\n        self.negotiate_message = NegotiateMessage(self.negotiate_flags, domain_name, workstation)\n        return base64.b64encode(self.negotiate_message.get_data())",
    "docstring": "Create an NTLM NEGOTIATE_MESSAGE\n\n        :param domain_name: The domain name of the user account we are authenticating with, default is None\n        :param worksation: The workstation we are using to authenticate with, default is None\n        :return: A base64 encoded string of the NEGOTIATE_MESSAGE"
  },
  {
    "code": "def assertDateTimesFrequencyEqual(self, sequence, frequency, msg=None):\n        if not isinstance(sequence, collections.Iterable):\n            raise TypeError('First argument is not iterable')\n        if not isinstance(frequency, timedelta):\n            raise TypeError('Second argument is not a timedelta object')\n        standardMsg = 'unexpected frequencies found in %s' % sequence\n        s1 = pd.Series(sequence)\n        s2 = s1.shift(-1)\n        freq = s2 - s1\n        if not all(f == frequency for f in freq[:-1]):\n            self.fail(self._formatMessage(msg, standardMsg))",
    "docstring": "Fail if any elements in ``sequence`` aren't separated by\n        the expected ``fequency``.\n\n        Parameters\n        ----------\n        sequence : iterable\n        frequency : timedelta\n        msg : str\n            If not provided, the :mod:`marbles.mixins` or\n            :mod:`unittest` standard message will be used.\n\n        Raises\n        ------\n        TypeError\n            If ``sequence`` is not iterable.\n        TypeError\n            If ``frequency`` is not a timedelta object."
  },
  {
    "code": "def snap_install_requested():\n    origin = config('openstack-origin') or \"\"\n    if not origin.startswith('snap:'):\n        return False\n    _src = origin[5:]\n    if '/' in _src:\n        channel = _src.split('/')[1]\n    else:\n        channel = 'stable'\n    return valid_snap_channel(channel)",
    "docstring": "Determine if installing from snaps\n\n    If openstack-origin is of the form snap:track/channel[/branch]\n    and channel is in SNAPS_CHANNELS return True."
  },
  {
    "code": "def powerstring_by_border(u):\n    f = maximum_border_length(u)\n    n = len(u)\n    if n % (n - f[-1]) == 0:\n        return n // (n - f[-1])\n    return 1",
    "docstring": "Power string by Knuth-Morris-Pratt\n\n    :param x: string\n    :returns: largest k such that there is a string y with x = y^k\n    :complexity: O(len(x))"
  },
  {
    "code": "def filter(self, field_name, field_value):\n        self.filters.append((field_name, field_value))\n        return self",
    "docstring": "Add permanent filter on the collection\n\n        :param field_name: name of the field to filter on\n        :type field_name: str\n        :param field_value: value to filter on\n\n        :rtype: Collection"
  },
  {
    "code": "def provision_system_config(items, database_name, overwrite=False, clear=False, skip_user_check=False):\n    from hfos.provisions.base import provisionList\n    from hfos.database import objectmodels\n    default_system_config_count = objectmodels['systemconfig'].count({\n        'name': 'Default System Configuration'})\n    if default_system_config_count == 0 or (clear or overwrite):\n        provisionList([SystemConfiguration], 'systemconfig', overwrite, clear, skip_user_check)\n        hfoslog('Provisioning: System: Done.', emitter='PROVISIONS')\n    else:\n        hfoslog('Default system configuration already present.', lvl=warn,\n                emitter='PROVISIONS')",
    "docstring": "Provision a basic system configuration"
  },
  {
    "code": "def fold_enrichment(self):\n        expected = self.K * (self.n/float(self.N))\n        return self.k / expected",
    "docstring": "Returns the fold enrichment of the gene set.\n\n        Fold enrichment is defined as ratio between the observed and the\n        expected number of gene set genes present."
  },
  {
    "code": "def _initial_guess(self):\n        a, b, c = np.polyfit(self.volumes, self.energies, 2)\n        self.eos_params = [a, b, c]\n        v0 = -b/(2*a)\n        e0 = a*(v0**2) + b*v0 + c\n        b0 = 2 * a * v0\n        b1 = 4\n        vmin, vmax = min(self.volumes), max(self.volumes)\n        if not vmin < v0 and v0 < vmax:\n            raise EOSError('The minimum volume of a fitted parabola is '\n                           'not in the input volumes\\n.')\n        return e0, b0, b1, v0",
    "docstring": "Quadratic fit to get an initial guess for the parameters.\n\n        Returns:\n            tuple: (e0, b0, b1, v0)"
  },
  {
    "code": "def synchronize (lock, func, log_duration_secs=0):\n    def newfunc (*args, **kwargs):\n        t = time.time()\n        with lock:\n            duration = time.time() - t\n            if duration > log_duration_secs > 0:\n                print(\"WARN:\", func.__name__, \"locking took %0.2f seconds\" % duration, file=sys.stderr)\n            return func(*args, **kwargs)\n    return update_func_meta(newfunc, func)",
    "docstring": "Return synchronized function acquiring the given lock."
  },
  {
    "code": "def add_global_handler(self, event, handler, priority=0):\n        handler = PrioritizedHandler(priority, handler)\n        with self.mutex:\n            event_handlers = self.handlers.setdefault(event, [])\n            bisect.insort(event_handlers, handler)",
    "docstring": "Adds a global handler function for a specific event type.\n\n        Arguments:\n\n            event -- Event type (a string).  Check the values of\n                     numeric_events for possible event types.\n\n            handler -- Callback function taking 'connection' and 'event'\n                       parameters.\n\n            priority -- A number (the lower number, the higher priority).\n\n        The handler function is called whenever the specified event is\n        triggered in any of the connections.  See documentation for\n        the Event class.\n\n        The handler functions are called in priority order (lowest\n        number is highest priority).  If a handler function returns\n        \"NO MORE\", no more handlers will be called."
  },
  {
    "code": "def multipath_flush(device):\n    if not os.path.exists(device):\n        return '{0} does not exist'.format(device)\n    cmd = 'multipath -f {0}'.format(device)\n    return __salt__['cmd.run'](cmd).splitlines()",
    "docstring": "Device-Mapper Multipath flush\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' devmap.multipath_flush mpath1"
  },
  {
    "code": "def update_from_json(self, json_attributes, models=None, setter=None):\n        for k, v in json_attributes.items():\n            self.set_from_json(k, v, models, setter)",
    "docstring": "Updates the object's properties from a JSON attributes dictionary.\n\n        Args:\n            json_attributes: (JSON-dict) : attributes and values to update\n\n            models (dict or None, optional) :\n                Mapping of model ids to models (default: None)\n\n                This is needed in cases where the attributes to update also\n                have values that have references.\n\n            setter(ClientSession or ServerSession or None, optional) :\n                This is used to prevent \"boomerang\" updates to Bokeh apps.\n\n                In the context of a Bokeh server application, incoming updates\n                to properties will be annotated with the session that is\n                doing the updating. This value is propagated through any\n                subsequent change notifications that the update triggers.\n                The session can compare the event setter to itself, and\n                suppress any updates that originate from itself.\n\n        Returns:\n            None"
  },
  {
    "code": "def _prepdata(self):\n        if not self._data.get(\"bbox\"):\n            self.update_bbox()\n        if not self._data.get(\"crs\"):\n            self._data[\"crs\"] = {\"type\":\"name\",\n                               \"properties\":{\"name\":\"urn:ogc:def:crs:OGC:2:84\"}}",
    "docstring": "Adds potentially missing items to the geojson dictionary"
  },
  {
    "code": "def islice(self, start=None, stop=None, reverse=False):\n        _len = self._len\n        if not _len:\n            return iter(())\n        start, stop, step = self._slice(slice(start, stop))\n        if start >= stop:\n            return iter(())\n        _pos = self._pos\n        min_pos, min_idx = _pos(start)\n        if stop == _len:\n            max_pos = len(self._lists) - 1\n            max_idx = len(self._lists[-1])\n        else:\n            max_pos, max_idx = _pos(stop)\n        return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)",
    "docstring": "Returns an iterator that slices `self` from `start` to `stop` index,\n        inclusive and exclusive respectively.\n\n        When `reverse` is `True`, values are yielded from the iterator in\n        reverse order.\n\n        Both `start` and `stop` default to `None` which is automatically\n        inclusive of the beginning and end."
  },
  {
    "code": "def resolve(self, ref, document=None):\n        try:\n            url = self._urljoin_cache(self.resolution_scope, ref)\n            if document is None:\n                resolved = self._remote_cache(url)\n            else:\n                _, fragment = urldefrag(url)\n                resolved = self.resolve_fragment(document, fragment)\n        except jsonschema.RefResolutionError as e:\n            message = e.args[0]\n            if self._scopes_stack:\n                message = '{} (from {})'.format(\n                    message, self._format_stack(self._scopes_stack))\n            raise SchemaError(message)\n        if isinstance(resolved, dict) and '$ref' in resolved:\n            if url in self._scopes_stack:\n                raise SchemaError(\n                    'Circular reference in schema: {}'.format(\n                        self._format_stack(self._scopes_stack + [url])))\n            try:\n                self.push_scope(url)\n                return self.resolve(resolved['$ref'])\n            finally:\n                self.pop_scope()\n        else:\n            return url, resolved",
    "docstring": "Resolve a fragment within the schema.\n\n        If the resolved value contains a $ref, it will attempt to resolve that\n        as well, until it gets something that is not a reference. Circular\n        references will raise a SchemaError.\n\n        :param str ref: URI to resolve.\n        :param dict document: Optional schema in which to resolve the URI.\n        :returns: a tuple of the final, resolved URI (after any recursion) and\n            resolved value in the schema that the URI references.\n        :raises SchemaError:"
  },
  {
    "code": "def _validate_mandatory_keys(mandatory, validated, data, to_validate):\n    errors = []\n    for key, sub_schema in mandatory.items():\n        if key not in data:\n            errors.append('missing key: %r' % (key,))\n            continue\n        try:\n            validated[key] = sub_schema(data[key])\n        except NotValid as ex:\n            errors.extend(['%r: %s' % (key, arg) for arg in ex.args])\n        to_validate.remove(key)\n    return errors",
    "docstring": "Validate the manditory keys."
  },
  {
    "code": "async def unignore_all(self, ctx):\n        channels = [c for c in ctx.message.server.channels if c.type is discord.ChannelType.text]\n        await ctx.invoke(self.unignore, *channels)",
    "docstring": "Unignores all channels in this server from being processed.\n\n        To use this command you must have the Manage Channels permission or have the\n        Bot Admin role."
  },
  {
    "code": "def param_describe(params, quant=95, axis=0):\n    par = np.mean(params, axis=axis)\n    lo, up = perc(quant)\n    p_up = np.percentile(params, up, axis=axis)\n    p_lo = np.percentile(params, lo, axis=axis)\n    return par, p_lo, p_up",
    "docstring": "Get mean + quantile range from bootstrapped params."
  },
  {
    "code": "def appendDatastore(self, store):\n    if not isinstance(store, Datastore):\n      raise TypeError(\"stores must be of type %s\" % Datastore)\n    self._stores.append(store)",
    "docstring": "Appends datastore `store` to this collection."
  },
  {
    "code": "def chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2):\n    q = q_from_mass1_mass2(mass1, mass2)\n    a1 = 2 + 3 * q / 2\n    a2 = 2 + 3 / (2 * q)\n    return q**2 * a2 / a1 * xi2",
    "docstring": "Returns the in-plane spin from mass1, mass2, and xi2 for the\n    secondary mass."
  },
  {
    "code": "def tail(self, path, tail_length=1024, append=False):\n        if not path:\n            raise InvalidInputException(\"tail: no path given\")\n        block_size = self.serverdefaults()['blockSize']\n        if tail_length > block_size:\n            raise InvalidInputException(\"tail: currently supports length up to the block size (%d)\" % (block_size,))\n        if tail_length <= 0:\n            raise InvalidInputException(\"tail: tail_length cannot be less than or equal to zero\")\n        processor = lambda path, node: self._handle_tail(path, node, tail_length, append)\n        for item in self._find_items([path], processor, include_toplevel=True,\n                                     include_children=False, recurse=False):\n            if item:\n                yield item",
    "docstring": "Show the end of the file - default 1KB, supports up to the Hadoop block size.\n\n        :param path: Path to read\n        :type path: string\n        :param tail_length: The length to read from the end of the file - default 1KB, up to block size.\n        :type tail_length: int\n        :param append: Currently not implemented\n        :type append: bool\n        :returns: a generator that yields strings"
  },
  {
    "code": "def raw_command(self, lun, netfn, raw_bytes):\n        return self.interface.send_and_receive_raw(self.target, lun, netfn,\n                                                   raw_bytes)",
    "docstring": "Send the raw command data and return the raw response.\n\n        lun: the logical unit number\n        netfn: the network function\n        raw_bytes: the raw message as bytestring\n\n        Returns the response as bytestring."
  },
  {
    "code": "def admin_tools_render_menu_css(context, menu=None):\n    if menu is None:\n        menu = get_admin_menu(context)\n    context.update({\n        'template': 'admin_tools/menu/css.html',\n        'css_files': menu.Media.css,\n    })\n    return context",
    "docstring": "Template tag that renders the menu css files,, it takes an optional\n    ``Menu`` instance as unique argument, if not given, the menu will be\n    retrieved with the ``get_admin_menu`` function."
  },
  {
    "code": "def _tree_view_builder(self, indent=0, is_root=True):\n        def pad_text(indent):\n            return \"    \" * indent + \"|-- \"\n        lines = list()\n        if is_root:\n            lines.append(SP_DIR)\n        lines.append(\n            \"%s%s (%s)\" % (pad_text(indent), self.shortname, self.fullname)\n        )\n        indent += 1\n        for pkg in self.sub_packages.values():\n            lines.append(pkg._tree_view_builder(indent=indent, is_root=False))\n        lines.append(\n            \"%s%s (%s)\" % (\n                pad_text(indent), \"__init__.py\", self.fullname,\n            )\n        )\n        for mod in self.sub_modules.values():\n            lines.append(\n                \"%s%s (%s)\" % (\n                    pad_text(indent), mod.shortname + \".py\", mod.fullname,\n                )\n            )\n        return \"\\n\".join(lines)",
    "docstring": "Build a text to represent the package structure."
  },
  {
    "code": "def rename(args):\n    p = OptionParser(rename.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n    ingff3, switch = args\n    switch = DictFile(switch)\n    gff = Gff(ingff3)\n    for g in gff:\n        id, = g.attributes[\"ID\"]\n        newname = switch.get(id, id)\n        g.attributes[\"ID\"] = [newname]\n        if \"Parent\" in g.attributes:\n            parents = g.attributes[\"Parent\"]\n            g.attributes[\"Parent\"] = [switch.get(x, x) for x in parents]\n        g.update_attributes()\n        print(g)",
    "docstring": "%prog rename in.gff3 switch.ids > reindexed.gff3\n\n    Change the IDs within the gff3."
  },
  {
    "code": "def sort_values(expr, by, ascending=True):\n    if not isinstance(by, list):\n        by = [by, ]\n    by = [it(expr) if inspect.isfunction(it) else it for it in by]\n    return SortedCollectionExpr(expr, _sorted_fields=by, _ascending=ascending,\n                                _schema=expr._schema)",
    "docstring": "Sort the collection by values. `sort` is an alias name for `sort_values`\n\n    :param expr: collection\n    :param by: the sequence or sequences to sort\n    :param ascending: Sort ascending vs. descending. Sepecify list for multiple sort orders.\n                      If this is a list of bools, must match the length of the by\n    :return: Sorted collection\n\n    :Example:\n\n    >>> df.sort_values(['name', 'id'])  # 1\n    >>> df.sort(['name', 'id'], ascending=False)  # 2\n    >>> df.sort(['name', 'id'], ascending=[False, True])  # 3\n    >>> df.sort([-df.name, df.id])  # 4, equal to #3"
  },
  {
    "code": "def _get(self):\n        c = self.theLookahead\n        self.theLookahead = None\n        if c == None:\n            c = self.instream.read(1)\n        if c >= ' ' or c == '\\n':\n            return c\n        if c == '':\n            return '\\000'\n        if c == '\\r':\n            return '\\n'\n        return ' '",
    "docstring": "return the next character from stdin. Watch out for lookahead. If\n           the character is a control character, translate it to a space or\n           linefeed."
  },
  {
    "code": "def unwrap(self, value, session=None):\n        self.validate_unwrap(value)\n        ret = []\n        for field, value in izip(self.types, value):\n            ret.append(field.unwrap(value, session=session))\n        return tuple(ret)",
    "docstring": "Validate and then unwrap ``value`` for object creation.\n\n            :param value: list returned from the database."
  },
  {
    "code": "def _load_significant_pathways_file(path_to_file):\n    feature_pathway_df = pd.read_table(\n        path_to_file, header=0,\n        usecols=[\"feature\", \"side\", \"pathway\"])\n    feature_pathway_df = feature_pathway_df.sort_values(\n        by=[\"feature\", \"side\"])\n    return feature_pathway_df",
    "docstring": "Read in the significant pathways file as a\n    pandas.DataFrame."
  },
  {
    "code": "def policy_net(rng_key,\n               batch_observations_shape,\n               num_actions,\n               bottom_layers=None):\n  if bottom_layers is None:\n    bottom_layers = []\n  bottom_layers.extend([layers.Dense(num_actions), layers.LogSoftmax()])\n  net = layers.Serial(*bottom_layers)\n  return net.initialize(batch_observations_shape, rng_key), net",
    "docstring": "A policy net function."
  },
  {
    "code": "def _times_to_hours_after_local_midnight(times):\n    times = times.tz_localize(None)\n    hrs = 1 / NS_PER_HR * (\n        times.astype(np.int64) - times.normalize().astype(np.int64))\n    return np.array(hrs)",
    "docstring": "convert local pandas datetime indices to array of hours as floats"
  },
  {
    "code": "def on_open(self, info):\n        self.ip = info.ip\n        self.request = info\n        self.open()",
    "docstring": "sockjs-tornado on_open handler"
  },
  {
    "code": "def strip_ip_port(ip_address):\n    if '.' in ip_address:\n        cleaned_ip = ip_address.split(':')[0]\n    elif ']:' in ip_address:\n        cleaned_ip = ip_address.rpartition(':')[0][1:-1]\n    else:\n        cleaned_ip = ip_address\n    return cleaned_ip",
    "docstring": "Strips the port from an IPv4 or IPv6 address, returns a unicode object."
  },
  {
    "code": "def get_attribute(self):\n        attributes = ['dependencies', 'publics', 'members', \n                          'types', 'executables']\n        if self.context.el_type in [Function, Subroutine]:\n            attribute = attributes[4]\n        elif self.context.el_type == CustomType:\n            attribute = attributes[3]\n        else:\n            attribute = attributes[2]\n        return attribute",
    "docstring": "Gets the appropriate module attribute name for a collection \n        corresponding to the context's element type."
  },
  {
    "code": "def insert_text(self, s, from_undo=False):\n        return super().insert_text(\n            ''.join(c for c in s if c in '0123456789'),\n            from_undo\n        )",
    "docstring": "Natural numbers only."
  },
  {
    "code": "def currentSelected(self):\n        if self.commaRadioButton.isChecked():\n            return ','\n        elif self.semicolonRadioButton.isChecked():\n            return ';'\n        elif self.tabRadioButton.isChecked():\n            return '\\t'\n        elif self.otherRadioButton.isChecked():\n            return self.otherSeparatorLineEdit.text()\n        return",
    "docstring": "Returns the currently selected delimiter character.\n\n        Returns:\n            str: One of `,`, `;`, `\\t`, `*other*`."
  },
  {
    "code": "def cli(env):\n    manager = AccountManager(env.client)\n    summary = manager.get_summary()\n    env.fout(get_snapshot_table(summary))",
    "docstring": "Prints some various bits of information about an account"
  },
  {
    "code": "def process(self):\r\n        var_name = self.name_edt.text()\r\n        try:\r\n            self.var_name = str(var_name)\r\n        except UnicodeEncodeError:\r\n            self.var_name = to_text_string(var_name)\r\n        if self.text_widget.get_as_data():\r\n            self.clip_data = self._get_table_data()\r\n        elif self.text_widget.get_as_code():\r\n            self.clip_data = try_to_eval(\r\n                to_text_string(self._get_plain_text()))\r\n        else:\r\n            self.clip_data = to_text_string(self._get_plain_text())\r\n        self.accept()",
    "docstring": "Process the data from clipboard"
  },
  {
    "code": "def parts(self):\n        try:\n            return self._pparts\n        except AttributeError:\n            self._pparts = tuple(self._parts)\n            return self._pparts",
    "docstring": "An object providing sequence-like access to the\n        components in the filesystem path."
  },
  {
    "code": "def find_parent_split(node, orientation):\n    if (node and node.orientation == orientation\n        and len(node.children) > 1):\n        return node\n    if not node or node.type == \"workspace\":\n        return None\n    return find_parent_split(node.parent, orientation)",
    "docstring": "Find the first parent split relative to the given node\n    according to the desired orientation"
  },
  {
    "code": "def filtre(liste_base, criteres) -> groups.Collection:\n        def choisi(ac):\n            for cat, li in criteres.items():\n                v = ac[cat]\n                if not (v in li):\n                    return False\n            return True\n        return groups.Collection(a for a in liste_base if choisi(a))",
    "docstring": "Return a filter list, bases on criteres\n\n        :param liste_base: Acces list\n        :param criteres: Criteria { `attribut`:[valeurs,...] }"
  },
  {
    "code": "def _schemaPrepareInsert(self, store):\n        for name, atr in self.getSchema():\n            atr.prepareInsert(self, store)",
    "docstring": "Prepare each attribute in my schema for insertion into a given store,\n        either by upgrade or by creation.  This makes sure all references point\n        to this store and all relative paths point to this store's files\n        directory."
  },
  {
    "code": "def set(self, value: Optional[bool]):\n        prev_value = self._value\n        self._value = value\n        if self._value != prev_value:\n            for event in self._events:\n                event.set()",
    "docstring": "Sets current status of a check\n\n        :param value: ``True`` (healthy), ``False`` (unhealthy), or ``None``\n            (unknown)"
  },
  {
    "code": "def mapping(self):\n        return (\n            self._user_id_mapping,\n            self._user_feature_mapping,\n            self._item_id_mapping,\n            self._item_feature_mapping,\n        )",
    "docstring": "Return the constructed mappings.\n\n        Invert these to map internal indices to external ids.\n\n        Returns\n        -------\n\n        (user id map, user feature map, item id map, item id map): tuple of dictionaries"
  },
  {
    "code": "def pmag_angle(D1,D2):\n    D1 = numpy.array(D1)\n    if len(D1.shape) > 1:\n        D1 = D1[:,0:2]\n    else: D1 = D1[:2]\n    D2 = numpy.array(D2)\n    if len(D2.shape) > 1:\n        D2 = D2[:,0:2]\n    else: D2 = D2[:2]\n    X1 = dir2cart(D1)\n    X2 = dir2cart(D2)\n    angles = []\n    for k in range(X1.shape[0]):\n        angle = numpy.arccos(numpy.dot(X1[k],X2[k]))*180./numpy.pi\n        angle = angle%360.\n        angles.append(angle)\n    return numpy.array(angles)",
    "docstring": "finds the angle between lists of two directions D1,D2"
  },
  {
    "code": "def get_schema_type_name(node, context):\n    query_path = node.query_path\n    if query_path not in context.query_path_to_location_info:\n        raise AssertionError(\n            u'Unable to find type name for query path {} with context {}.'.format(\n                query_path, context))\n    location_info = context.query_path_to_location_info[query_path]\n    return location_info.type.name",
    "docstring": "Return the GraphQL type name of a node."
  },
  {
    "code": "def timedelta_to_days(td):\n    seconds_in_day = 24. * 3600.\n    days = td.days + (td.seconds + (td.microseconds * 10.e6)) / seconds_in_day\n    return days",
    "docstring": "Convert a `datetime.timedelta` object to a total number of days.\n\n    Parameters\n    ----------\n    td : `datetime.timedelta` instance\n\n    Returns\n    -------\n    days : float\n        Total number of days in the `datetime.timedelta` object.\n\n    Examples\n    --------\n    >>> td = datetime.timedelta(4.5)\n    >>> td\n    datetime.timedelta(4, 43200)\n    >>> timedelta_to_days(td)\n    4.5"
  },
  {
    "code": "def h5ToDict(h5, readH5pyDataset=True):\n    h = h5py.File(h5, \"r\")\n    ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset)\n    if readH5pyDataset: h.close()\n    return ret",
    "docstring": "Read a hdf5 file into a dictionary"
  },
  {
    "code": "def _is_valid_api_url(self, url):\n        data = {}\n        try:\n            r = requests.get(url, proxies=self.proxy_servers)\n            content = to_text_string(r.content, encoding='utf-8')\n            data = json.loads(content)\n        except Exception as error:\n            logger.error(str(error))\n        return data.get('ok', 0) == 1",
    "docstring": "Callback for is_valid_api_url."
  },
  {
    "code": "def pagerank_lazy_push(s, r, w_i, a_i, push_node, rho, lazy):\n    A = rho*r[push_node]\n    B = (1-rho)*(1 - lazy)*r[push_node]\n    C = (1-rho)*lazy*(r[push_node])\n    s[push_node] += A\n    r[push_node] = C\n    r[a_i] += B * w_i",
    "docstring": "Performs a random step with a self-loop.\n\n    Introduced in: Andersen, R., Chung, F., & Lang, K. (2006, October).\n                   Local graph partitioning using pagerank vectors.\n                   In Foundations of Computer Science, 2006. FOCS'06. 47th Annual IEEE Symposium on (pp. 475-486). IEEE."
  },
  {
    "code": "def compose(*functions):\n    return functools.reduce(lambda f, g: lambda x: f(g(x)), functions, identity)",
    "docstring": "Function composition on a series of functions.\n\n    Remember that function composition runs right-to-left: `f . g . h = f(g(h(x)))`. As a unix\n    pipeline, it would be written: `h | g | f`.\n\n    From https://mathieularose.com/function-composition-in-python/."
  },
  {
    "code": "def get_slice(self, thin_start=None, thin_interval=None, thin_end=None):\n        if thin_start is None:\n            thin_start = int(self.thin_start)\n        else:\n            thin_start = int(thin_start)\n        if thin_interval is None:\n            thin_interval = self.thin_interval\n        else:\n            thin_interval = int(numpy.ceil(thin_interval))\n        if thin_end is None:\n            thin_end = self.thin_end\n        else:\n            thin_end = int(thin_end)\n        return slice(thin_start, thin_end, thin_interval)",
    "docstring": "Formats a slice using the given arguments that can be used to\n        retrieve a thinned array from an InferenceFile.\n\n        Parameters\n        ----------\n        thin_start : int, optional\n            The starting index to use. If None, will use the ``thin_start``\n            attribute.\n        thin_interval : int, optional\n            The interval to use. If None, will use the ``thin_interval``\n            attribute.\n        thin_end : int, optional\n            The end index to use. If None, will use the ``thin_end`` attribute.\n\n        Returns\n        -------\n        slice :\n            The slice needed."
  },
  {
    "code": "def _request_address(self):\n        if not self._request_address_val:\n            template = (\n                'https://sb-ssl.google.com/safebrowsing/api/lookup'\n                '?client={0}&key={1}&appver={2}&pver={3}'\n            )\n            self._request_address_val = template.format(\n                self.client_name,\n                self.api_key,\n                self.app_version,\n                self.protocol_version\n            )\n        return self._request_address_val",
    "docstring": "Get address of a POST request to the service."
  },
  {
    "code": "def connect(self, timeout=None):\n        assert not self._running\n        maybe_timeout = future_timeout_manager(timeout)\n        self._logger.debug('Starting katcp client')\n        self.katcp_client.start()\n        try:\n            yield maybe_timeout(self.katcp_client.until_running())\n            self._logger.debug('Katcp client running')\n        except tornado.gen.TimeoutError:\n            self.katcp_client.stop()\n            raise\n        if timeout:\n            yield maybe_timeout(self.katcp_client.until_connected())\n        self._logger.debug('Katcp client connected')\n        self._running = True\n        self._state_loop()",
    "docstring": "Connect to KATCP interface, starting what is needed\n\n        Parameters\n        ----------\n        timeout : float, None\n            Time to wait until connected. No waiting if None.\n\n        Raises\n        ------\n\n        :class:`tornado.gen.TimeoutError` if the connect timeout expires"
  },
  {
    "code": "def _invert_all(self):\n        set = self._datastore.setbyte\n        get = self._datastore.getbyte\n        for p in xrange(self._datastore.byteoffset, self._datastore.byteoffset + self._datastore.bytelength):\n            set(p, 256 + ~get(p))",
    "docstring": "Invert every bit."
  },
  {
    "code": "def get_entry_text(self, fname):\n        if fname.split('.')[-1] == 'gz':\n            with gz.open(fname, 'rt') as f:\n                filetext = f.read()\n        else:\n            with codecs.open(fname, 'r') as f:\n                filetext = f.read()\n        return filetext",
    "docstring": "Retrieve the raw text from a file."
  },
  {
    "code": "def generate_megaman_data(sampling=2):\n    data = get_megaman_image()\n    x = np.arange(sampling * data.shape[1]) / float(sampling)\n    y = np.arange(sampling * data.shape[0]) / float(sampling)\n    X, Y = map(np.ravel, np.meshgrid(x, y))\n    C = data[np.floor(Y.max() - Y).astype(int),\n             np.floor(X).astype(int)]\n    return np.vstack([X, Y]).T, C",
    "docstring": "Generate 2D point data of the megaman image"
  },
  {
    "code": "def remove(self, workflow_id):\n        try:\n            db = self._client[self.database]\n            fs = GridFSProxy(GridFS(db.unproxied_object))\n            for grid_doc in fs.find({\"workflow_id\": workflow_id},\n                                    no_cursor_timeout=True):\n                fs.delete(grid_doc._id)\n            col = db[WORKFLOW_DATA_COLLECTION_NAME]\n            return col.delete_one({\"_id\": ObjectId(workflow_id)})\n        except ConnectionFailure:\n            raise DataStoreNotConnected()",
    "docstring": "Removes a document specified by its id from the data store.\n\n        All associated GridFs documents are deleted as well.\n\n        Args:\n            workflow_id (str): The id of the document that represents a workflow run.\n\n        Raises:\n            DataStoreNotConnected: If the data store is not connected to the server."
  },
  {
    "code": "def get_home_position(boatd=None):\n    if boatd is None:\n        boatd = Boatd()\n    content = boatd.get('/waypoints')\n    home = content.get('home', None)\n    if home is not None:\n        lat, lon = home\n        return Point(lat, lon)\n    else:\n        return None",
    "docstring": "Get the current home position from boatd.\n\n    :returns: The configured home position\n    :rtype: Points"
  },
  {
    "code": "def block_stat(self, multihash, **kwargs):\n        args = (multihash,)\n        return self._client.request('/block/stat', args,\n                                    decoder='json', **kwargs)",
    "docstring": "Returns a dict with the size of the block with the given hash.\n\n        .. code-block:: python\n\n            >>> c.block_stat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')\n            {'Key':  'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',\n             'Size': 258}\n\n        Parameters\n        ----------\n        multihash : str\n            The base58 multihash of an existing block to stat\n\n        Returns\n        -------\n            dict : Information about the requested block"
  },
  {
    "code": "def bootstrap_css():\n    rendered_urls = [render_link_tag(bootstrap_css_url())]\n    if bootstrap_theme_url():\n        rendered_urls.append(render_link_tag(bootstrap_theme_url()))\n    return mark_safe(\"\".join([url for url in rendered_urls]))",
    "docstring": "Return HTML for Bootstrap CSS.\n    Adjust url in settings. If no url is returned, we don't want this statement\n    to return any HTML.\n    This is intended behavior.\n\n    Default value: ``None``\n\n    This value is configurable, see Settings section\n\n    **Tag name**::\n\n        bootstrap_css\n\n    **Usage**::\n\n        {% bootstrap_css %}\n\n    **Example**::\n\n        {% bootstrap_css %}"
  },
  {
    "code": "def _convert_from(data):\n    try:\n        module, klass_name = data['__class__'].rsplit('.', 1)\n        klass = getattr(import_module(module), klass_name)\n    except (ImportError, AttributeError, KeyError):\n        return data\n    return deserialize(klass, data['__value__'])",
    "docstring": "Internal function that will be hooked to the native `json.loads`\n\n    Find the right deserializer for a given value, taking into account\n    the internal deserializer registry."
  },
  {
    "code": "def format_usage(self, usage):\n        msg = '\\nUsage: %s\\n' % self.indent_lines(textwrap.dedent(usage), \"  \")\n        return msg",
    "docstring": "Ensure there is only one newline between usage and the first heading\n        if there is no description."
  },
  {
    "code": "def set_is_valid_rss(self):\n        if self.title and self.link and self.description:\n            self.is_valid_rss = True\n        else:\n            self.is_valid_rss = False",
    "docstring": "Check to if this is actually a valid RSS feed"
  },
  {
    "code": "def execute(self, command):\n        pData = c_char_p(command)\n        cbData = DWORD(len(command) + 1)\n        hDdeData = DDE.ClientTransaction(pData, cbData, self._hConv, HSZ(), CF_TEXT, XTYP_EXECUTE, TIMEOUT_ASYNC, LPDWORD())\n        if not hDdeData:\n            raise DDEError(\"Unable to send command\", self._idInst)\n        DDE.FreeDataHandle(hDdeData)",
    "docstring": "Execute a DDE command."
  },
  {
    "code": "def inflect(self):\n        if self._inflect is None:\n            import inflect\n            self._inflect = inflect.engine()\n        return self._inflect",
    "docstring": "Return instance of inflect."
  },
  {
    "code": "def primitives():\n    z = randomZ(orderG1())\n    P,Q = randomG1(),randomG1()\n    R = generatorG1()\n    g1Add = P + Q\n    g1ScalarMultiply = z*P\n    g1GeneratorMultiply = z*R\n    g1Hash = hashG1(hash_in)\n    P,Q = randomG2(),randomG2()\n    R = generatorG2()\n    g2Add = P + Q\n    g2ScalarMultiply = z*P\n    g2GeneratorMultiply = z*R\n    g2hash = hashG2(hash_in)\n    P = randomGt()\n    Q = randomGt()\n    gtMult = P * Q\n    gtExp = P**z\n    x,y = (randomG1(), randomG2())\n    R = pair(x,y)",
    "docstring": "Perform primitive operations for profiling"
  },
  {
    "code": "def pipeline_name(self):\n        if 'pipeline_name' in self.data and self.data.pipeline_name:\n            return self.data.get('pipeline_name')\n        elif self.stage.pipeline is not None:\n            return self.stage.pipeline.data.name\n        else:\n            return self.stage.data.pipeline_name",
    "docstring": "Get pipeline name of current job instance.\n\n        Because instantiating job instance could be performed in different ways and those return different results,\n        we have to check where from to get name of the pipeline.\n\n        :return: pipeline name."
  },
  {
    "code": "def save(self, path):\n        with io.open(path, 'wb') as fout:\n            return pickle.dump(dict(self.weights), fout)",
    "docstring": "Save the pickled model weights."
  },
  {
    "code": "def _validate_edata(self, edata):\n        if edata is None:\n            return True\n        if not (isinstance(edata, dict) or _isiterable(edata)):\n            return False\n        edata = [edata] if isinstance(edata, dict) else edata\n        for edict in edata:\n            if (not isinstance(edict, dict)) or (\n                isinstance(edict, dict)\n                and (\n                    (\"field\" not in edict)\n                    or (\"field\" in edict and (not isinstance(edict[\"field\"], str)))\n                    or (\"value\" not in edict)\n                )\n            ):\n                return False\n        return True",
    "docstring": "Validate edata argument of raise_exception_if method."
  },
  {
    "code": "def lte(max_value):\n    def validate(value):\n        if value > max_value:\n            return e(\"{} is not less than or equal to {}\", value, max_value)\n    return validate",
    "docstring": "Validates that a field value is less than or equal to the\n    value given to this validator."
  },
  {
    "code": "def disconnect(self, func=None):\n        if func is None:\n            self._connections = []\n        else:\n            self._connections.remove(func)",
    "docstring": "Disconnect a function call to the signal. If None, all connections\n        are disconnected"
  },
  {
    "code": "def blend(self, other, percent=0.5):\n    dest = 1.0 - percent\n    rgb = tuple(((u * percent) + (v * dest) for u, v in zip(self.__rgb, other.__rgb)))\n    a = (self.__a * percent) + (other.__a * dest)\n    return Color(rgb, 'rgb', a, self.__wref)",
    "docstring": "blend this color with the other one.\n\n    Args:\n      :other:\n        the grapefruit.Color to blend with this one.\n\n    Returns:\n      A grapefruit.Color instance which is the result of blending\n      this color on the other one.\n\n    >>> c1 = Color.from_rgb(1, 0.5, 0, 0.2)\n    >>> c2 = Color.from_rgb(1, 1, 1, 0.6)\n    >>> c3 = c1.blend(c2)\n    >>> c3\n    Color(1.0, 0.75, 0.5, 0.4)"
  },
  {
    "code": "def in_chain(cls, client, chain_id, expiration_dates=[]):\n        request_url = \"https://api.robinhood.com/options/instruments/\"\n        params = {\n            \"chain_id\": chain_id,\n            \"expiration_dates\": \",\".join(expiration_dates)\n        }\n        data = client.get(request_url, params=params)\n        results = data['results']\n        while data['next']:\n            data = client.get(data['next'])\n            results.extend(data['results'])\n        return results",
    "docstring": "fetch all option instruments in an options chain\n        - expiration_dates = optionally scope"
  },
  {
    "code": "def _special_value_rows(em):\n    if em.tagName == 'textarea':\n        return convertToIntRange(em.getAttribute('rows', 2), minValue=1, maxValue=None, invalidDefault=2)\n    else:\n        return em.getAttribute('rows', '')",
    "docstring": "_special_value_rows - Handle \"rows\" special attribute, which differs if tagName is a textarea or frameset"
  },
  {
    "code": "def _constrain_L2_grad(op, grad):\n  inp = op.inputs[0]\n  inp_norm = tf.norm(inp)\n  unit_inp = inp / inp_norm\n  grad_projection = dot(unit_inp, grad)\n  parallel_grad = unit_inp * grad_projection\n  is_in_ball = tf.less_equal(inp_norm, 1)\n  is_pointed_inward = tf.less(grad_projection, 0)\n  allow_grad = tf.logical_or(is_in_ball, is_pointed_inward)\n  clip_grad = tf.logical_not(allow_grad)\n  clipped_grad = tf.cond(clip_grad, lambda: grad - parallel_grad, lambda: grad)\n  return clipped_grad",
    "docstring": "Gradient for constrained optimization on an L2 unit ball.\n\n  This function projects the gradient onto the ball if you are on the boundary\n  (or outside!), but leaves it untouched if you are inside the ball.\n\n  Args:\n    op: the tensorflow op we're computing the gradient for.\n    grad: gradient we need to backprop\n\n  Returns:\n    (projected if necessary) gradient."
  },
  {
    "code": "def thumbnail_url(source, alias):\n    try:\n        thumb = get_thumbnailer(source)[alias]\n    except Exception:\n        return ''\n    return thumb.url",
    "docstring": "Return the thumbnail url for a source file using an aliased set of\n    thumbnail options.\n\n    If no matching alias is found, returns an empty string.\n\n    Example usage::\n\n        <img src=\"{{ person.photo|thumbnail_url:'small' }}\" alt=\"\">"
  },
  {
    "code": "def load_weight(weight_file: str,\n                weight_name: str,\n                weight_file_cache: Dict[str, Dict]) -> mx.nd.NDArray:\n    logger.info('Loading input weight file: %s', weight_file)\n    if weight_file.endswith(\".npy\"):\n        return np.load(weight_file)\n    elif weight_file.endswith(\".npz\"):\n        if weight_file not in weight_file_cache:\n            weight_file_cache[weight_file] = np.load(weight_file)\n        return weight_file_cache[weight_file][weight_name]\n    else:\n        if weight_file not in weight_file_cache:\n            weight_file_cache[weight_file] = mx.nd.load(weight_file)\n        return weight_file_cache[weight_file]['arg:%s' % weight_name].asnumpy()",
    "docstring": "Load wight fron a file or the cache if it was loaded before.\n\n    :param weight_file: Weight file.\n    :param weight_name: Weight name.\n    :param weight_file_cache: Cache of loaded files.\n    :return: Loaded weight."
  },
  {
    "code": "def _getResourceClass(self):\n        if self.fromVirtualEnv:\n            subcls = VirtualEnvResource\n        elif os.path.isdir(self._resourcePath):\n            subcls = DirectoryResource\n        elif os.path.isfile(self._resourcePath):\n            subcls = FileResource\n        elif os.path.exists(self._resourcePath):\n            raise AssertionError(\"Neither a file or a directory: '%s'\" % self._resourcePath)\n        else:\n            raise AssertionError(\"No such file or directory: '%s'\" % self._resourcePath)\n        return subcls",
    "docstring": "Return the concrete subclass of Resource that's appropriate for auto-deploying this module."
  },
  {
    "code": "def merge_list_members(self, list_, record_data, merge_rule):\n        list_ = list_.get_soap_object(self.client)\n        record_data = record_data.get_soap_object(self.client)\n        merge_rule = merge_rule.get_soap_object(self.client)\n        return MergeResult(self.call('mergeListMembers', list_, record_data, merge_rule))",
    "docstring": "Responsys.mergeListMembers call\n\n        Accepts:\n            InteractObject list_\n            RecordData record_data\n            ListMergeRule merge_rule\n\n        Returns a MergeResult"
  },
  {
    "code": "def _doIdRes(self, message, endpoint, return_to):\n        self._idResCheckForFields(message)\n        if not self._checkReturnTo(message, return_to):\n            raise ProtocolError(\n                \"return_to does not match return URL. Expected %r, got %r\"\n                % (return_to, message.getArg(OPENID_NS, 'return_to')))\n        endpoint = self._verifyDiscoveryResults(message, endpoint)\n        logging.info(\"Received id_res response from %s using association %s\" %\n                    (endpoint.server_url,\n                     message.getArg(OPENID_NS, 'assoc_handle')))\n        self._idResCheckSignature(message, endpoint.server_url)\n        self._idResCheckNonce(message, endpoint)\n        signed_list_str = message.getArg(OPENID_NS, 'signed', no_default)\n        signed_list = signed_list_str.split(',')\n        signed_fields = [\"openid.\" + s for s in signed_list]\n        return SuccessResponse(endpoint, message, signed_fields)",
    "docstring": "Handle id_res responses that are not cancellations of\n        immediate mode requests.\n\n        @param message: the response paramaters.\n        @param endpoint: the discovered endpoint object. May be None.\n\n        @raises ProtocolError: If the message contents are not\n            well-formed according to the OpenID specification. This\n            includes missing fields or not signing fields that should\n            be signed.\n\n        @raises DiscoveryFailure: If the subject of the id_res message\n            does not match the supplied endpoint, and discovery on the\n            identifier in the message fails (this should only happen\n            when using OpenID 2)\n\n        @returntype: L{Response}"
  },
  {
    "code": "def remove(self, *values):\n        for value in objecttools.extract(values, (str, variabletools.Variable)):\n            try:\n                deleted_something = False\n                for fn2var in list(self._type2filename2variable.values()):\n                    for fn_, var in list(fn2var.items()):\n                        if value in (fn_, var):\n                            del fn2var[fn_]\n                            deleted_something = True\n                if not deleted_something:\n                    raise ValueError(\n                        f'`{repr(value)}` is neither a registered '\n                        f'filename nor a registered variable.')\n            except BaseException:\n                objecttools.augment_excmessage(\n                    f'While trying to remove the given object `{value}` '\n                    f'of type `{objecttools.classname(value)}` from the '\n                    f'actual Variable2AuxFile object')",
    "docstring": "Remove the defined variables.\n\n        The variables to be removed can be selected in two ways.  But the\n        first example shows that passing nothing or an empty iterable to\n        method |Variable2Auxfile.remove| does not remove any variable:\n\n        >>> from hydpy import dummies\n        >>> v2af = dummies.v2af\n        >>> v2af.remove()\n        >>> v2af.remove([])\n        >>> from hydpy import print_values\n        >>> print_values(v2af.filenames)\n        file1, file2\n        >>> print_values(v2af.variables, width=30)\n        eqb(5000.0), eqb(10000.0),\n        eqd1(100.0), eqd2(50.0),\n        eqi1(2000.0), eqi2(1000.0)\n\n        The first option is to pass auxiliary file names:\n\n        >>> v2af.remove('file1')\n        >>> print_values(v2af.filenames)\n        file2\n        >>> print_values(v2af.variables)\n        eqb(10000.0), eqd1(100.0), eqd2(50.0)\n\n        The second option is, to pass variables of the correct type\n        and value:\n\n        >>> v2af = dummies.v2af\n        >>> v2af.remove(v2af.eqb[0])\n        >>> print_values(v2af.filenames)\n        file1, file2\n        >>> print_values(v2af.variables)\n        eqb(10000.0), eqd1(100.0), eqd2(50.0), eqi1(2000.0), eqi2(1000.0)\n\n        One can pass multiple variables or iterables containing variables\n        at once:\n\n        >>> v2af = dummies.v2af\n        >>> v2af.remove(v2af.eqb, v2af.eqd1, v2af.eqd2)\n        >>> print_values(v2af.filenames)\n        file1\n        >>> print_values(v2af.variables)\n        eqi1(2000.0), eqi2(1000.0)\n\n        Passing an argument that equals neither a registered file name or a\n        registered variable results in the following exception:\n\n        >>> v2af.remove('test')\n        Traceback (most recent call last):\n        ...\n        ValueError: While trying to remove the given object `test` of type \\\n`str` from the actual Variable2AuxFile object, the following error occurred: \\\n`'test'` is neither a registered filename nor a registered variable."
  },
  {
    "code": "def add_effect(self, effect):\n        effect.register_scene(self._scene)\n        self._effects.append(effect)",
    "docstring": "Add an Effect to the Frame.\n\n        :param effect: The Effect to be added."
  },
  {
    "code": "def clear_repository_helper(reserve_fn, clear_fn, retry=5, reservation=None):\n    if reservation is None:\n        reservation = reserve_fn()\n    reservation = _clear_repository(reserve_fn, clear_fn,\n                                    INITIATE_ERASE, retry, reservation)\n    time.sleep(0.5)\n    reservation = _clear_repository(reserve_fn, clear_fn,\n                                    GET_ERASE_STATUS, retry, reservation)",
    "docstring": "Helper function to start repository erasure and wait until finish.\n    This helper is used by clear_sel and clear_sdr_repository."
  },
  {
    "code": "def wait_for_ajax_calls_to_complete(self, timeout=5):\n        from selenium.webdriver.support.ui import WebDriverWait\n        WebDriverWait(self.driver, timeout).until(lambda s: s.execute_script(\"return jQuery.active === 0\"))",
    "docstring": "Waits until there are no active or pending ajax requests.\n\n        Raises TimeoutException should silence not be had.\n\n        :param timeout: time to wait for silence (default: 5 seconds)\n        :return: None"
  },
  {
    "code": "def url_param(param, default=None):\n    if request.args.get(param):\n        return request.args.get(param, default)\n    if request.form.get('form_data'):\n        form_data = json.loads(request.form.get('form_data'))\n        url_params = form_data.get('url_params') or {}\n        return url_params.get(param, default)\n    return default",
    "docstring": "Read a url or post parameter and use it in your SQL Lab query\n\n    When in SQL Lab, it's possible to add arbitrary URL \"query string\"\n    parameters, and use those in your SQL code. For instance you can\n    alter your url and add `?foo=bar`, as in\n    `{domain}/superset/sqllab?foo=bar`. Then if your query is something like\n    SELECT * FROM foo = '{{ url_param('foo') }}', it will be parsed at\n    runtime and replaced by the value in the URL.\n\n    As you create a visualization form this SQL Lab query, you can pass\n    parameters in the explore view as well as from the dashboard, and\n    it should carry through to your queries.\n\n    :param param: the parameter to lookup\n    :type param: str\n    :param default: the value to return in the absence of the parameter\n    :type default: str"
  },
  {
    "code": "def sign_message(body: ByteString, secret: Text) -> Text:\n    return 'sha1={}'.format(\n        hmac.new(secret.encode(), body, sha1).hexdigest()\n    )",
    "docstring": "Compute a message's signature."
  },
  {
    "code": "def register_lookup_handler(lookup_type, handler_or_path):\n    handler = handler_or_path\n    if isinstance(handler_or_path, basestring):\n        handler = load_object_from_string(handler_or_path)\n    LOOKUP_HANDLERS[lookup_type] = handler\n    if type(handler) != type:\n        logger = logging.getLogger(__name__)\n        logger.warning(\"Registering lookup `%s`: Please upgrade to use the \"\n                       \"new style of Lookups.\" % lookup_type)\n        warnings.warn(\n            \"Lookup `%s`: Please upgrade to use the new style of Lookups\"\n            \".\" % lookup_type,\n            DeprecationWarning,\n            stacklevel=2,\n        )",
    "docstring": "Register a lookup handler.\n\n    Args:\n        lookup_type (str): Name to register the handler under\n        handler_or_path (OneOf[func, str]): a function or a path to a handler"
  },
  {
    "code": "def edit(self, layer, item, delete=False):\n        if hasattr(self, layer):\n            layer_obj = getattr(self, layer)\n        else:\n            raise AttributeError('missing layer: %s', layer)\n        if delete:\n            return layer_obj\n        for k, v in item.iteritems():\n            if k in layer_obj.layer:\n                layer_obj.edit(k, v)\n            else:\n                raise AttributeError('missing layer item: %s', k)\n            if k in self.model[layer]:\n                self.model[layer][k].update(v)\n            else:\n                raise AttributeError('missing model layer item: %s', k)",
    "docstring": "Edit model.\n\n        :param layer: Layer of model to edit\n        :type layer: str\n        :param item: Items to edit.\n        :type item: dict\n        :param delete: Flag to return\n            :class:`~simkit.core.layers.Layer` to delete item.\n        :type delete: bool"
  },
  {
    "code": "def delete(args):\n    with _catalog(args) as cat:\n        n = len(cat)\n        cat.delete(args.args[0])\n        args.log.info('{0} objects deleted'.format(n - len(cat)))\n        return n - len(cat)",
    "docstring": "cdstarcat delete OID\n\n    Delete an object specified by OID from CDSTAR."
  },
  {
    "code": "def find_executable(name):\n    for pt in os.environ.get('PATH', '').split(':'):\n        candidate = os.path.join(pt, name)\n        if os.path.exists(candidate):\n            return candidate",
    "docstring": "Finds the actual path to a named command.\n\n    The first one on $PATH wins."
  },
  {
    "code": "def _add_filestore_resources(self, filestore_resources, create_default_views, hxl_update):\n        for resource in filestore_resources:\n            for created_resource in self.data['resources']:\n                if resource['name'] == created_resource['name']:\n                    merge_two_dictionaries(resource.data, created_resource)\n                    del resource['url']\n                    resource.update_in_hdx()\n                    merge_two_dictionaries(created_resource, resource.data)\n                    break\n        self.init_resources()\n        self.separate_resources()\n        if create_default_views:\n            self.create_default_views()\n        if hxl_update:\n            self.hxl_update()",
    "docstring": "Helper method to create files in filestore by updating resources.\n\n        Args:\n            filestore_resources (List[hdx.data.Resource]): List of resources that use filestore (to be appended to)\n            create_default_views (bool): Whether to call package_create_default_resource_views.\n            hxl_update (bool): Whether to call package_hxl_update.\n\n        Returns:\n            None"
  },
  {
    "code": "def get_ploidy(items, region=None):\n    chrom = chromosome_special_cases(region[0] if isinstance(region, (list, tuple))\n                                     else None)\n    ploidy = _configured_ploidy(items)\n    sexes = _configured_genders(items)\n    if chrom == \"mitochondrial\":\n        return ploidy.get(\"mitochondrial\", 1)\n    elif chrom == \"X\":\n        if \"female\" in sexes or \"f\" in sexes:\n            return ploidy.get(\"female\", ploidy[\"default\"])\n        elif \"male\" in sexes or \"m\" in sexes:\n            return ploidy.get(\"male\", 1)\n        else:\n            return ploidy.get(\"female\", ploidy[\"default\"])\n    elif chrom == \"Y\":\n        return 1\n    else:\n        return ploidy[\"default\"]",
    "docstring": "Retrieve ploidy of a region, handling special cases."
  },
  {
    "code": "def custom_object_prefix_strict(instance):\n    if (instance['type'] not in enums.TYPES and\n            instance['type'] not in enums.RESERVED_OBJECTS and\n            not CUSTOM_TYPE_PREFIX_RE.match(instance['type'])):\n        yield JSONError(\"Custom object type '%s' should start with 'x-' \"\n                        \"followed by a source unique identifier (like a \"\n                        \"domain name with dots replaced by hyphens), a hyphen \"\n                        \"and then the name.\" % instance['type'],\n                        instance['id'], 'custom-prefix')",
    "docstring": "Ensure custom objects follow strict naming style conventions."
  },
  {
    "code": "def upsert(self, insert_index, val, fn=None):\n        fn = fn or (lambda current, passed: passed)\n        self._magnitude = 0\n        position = self.position_for_index(insert_index)\n        if position < len(self.elements) and self.elements[position] == insert_index:\n            self.elements[position + 1] = fn(self.elements[position + 1], val)\n        else:\n            self.elements.insert(position, val)\n            self.elements.insert(position, insert_index)",
    "docstring": "Inserts or updates an existing index within the vector.\n\n        Args:\n            - insert_index (int): The index at which the element should be\n                inserted.\n            - val (int|float): The value to be inserted into the vector.\n            - fn (callable, optional): An optional callable taking two\n                arguments, the current value and the passed value to generate\n                the final inserted value at the position in case of collision."
  },
  {
    "code": "def peek(self, session, address, width):\n        if width == 8:\n            return self.peek_8(session, address)\n        elif width == 16:\n            return self.peek_16(session, address)\n        elif width == 32:\n            return self.peek_32(session, address)\n        elif width == 64:\n            return self.peek_64(session, address)\n        raise ValueError('%s is not a valid size. Valid values are 8, 16, 32 or 64' % width)",
    "docstring": "Read an 8, 16, 32, or 64-bit value from the specified address.\n\n        Corresponds to viPeek* functions of the VISA library.\n\n        :param session: Unique logical identifier to a session.\n        :param address: Source address to read the value.\n        :param width: Number of bits to read.\n        :return: Data read from bus, return value of the library call.\n        :rtype: bytes, :class:`pyvisa.constants.StatusCode`"
  },
  {
    "code": "def _auth(url, user, passwd, realm):\n    basic = _HTTPBasicAuthHandler()\n    basic.add_password(realm=realm, uri=url, user=user, passwd=passwd)\n    digest = _HTTPDigestAuthHandler()\n    digest.add_password(realm=realm, uri=url, user=user, passwd=passwd)\n    return _build_opener(basic, digest)",
    "docstring": "returns a authentication handler."
  },
  {
    "code": "def process_alt(header, ref, alt_str):\n    if \"]\" in alt_str or \"[\" in alt_str:\n        return record.BreakEnd(*parse_breakend(alt_str))\n    elif alt_str[0] == \".\" and len(alt_str) > 0:\n        return record.SingleBreakEnd(record.FORWARD, alt_str[1:])\n    elif alt_str[-1] == \".\" and len(alt_str) > 0:\n        return record.SingleBreakEnd(record.REVERSE, alt_str[:-1])\n    elif alt_str[0] == \"<\" and alt_str[-1] == \">\":\n        inner = alt_str[1:-1]\n        return record.SymbolicAllele(inner)\n    else:\n        return process_sub(ref, alt_str)",
    "docstring": "Process alternative value using Header in ``header``"
  },
  {
    "code": "def isscalar(cls, dataset, dim):\n        if not dataset.data:\n            return True\n        ds = cls._inner_dataset_template(dataset)\n        isscalar = []\n        for d in dataset.data:\n            ds.data = d\n            isscalar.append(ds.interface.isscalar(ds, dim))\n        return all(isscalar)",
    "docstring": "Tests if dimension is scalar in each subpath."
  },
  {
    "code": "def get_requires(self, profile=None):\n        out = []\n        for req in self.requires:\n            if ((req.profile and not profile) or\n               (req.profile and profile and req.profile != profile)):\n                continue\n            out.append(req)\n        return out",
    "docstring": "Get filtered list of Require objects in this Feature\n\n        :param str profile: Return Require objects with this profile or None\n                            to return all Require objects.\n        :return: list of Require objects"
  },
  {
    "code": "def view_dupl_sources_time(token, dstore):\n    info = dstore['source_info']\n    items = sorted(group_array(info.value, 'source_id').items())\n    tbl = []\n    tot_time = 0\n    for source_id, records in items:\n        if len(records) > 1:\n            calc_time = records['calc_time'].sum()\n            tot_time += calc_time + records['split_time'].sum()\n            tbl.append((source_id, calc_time, len(records)))\n    if tbl and info.attrs.get('has_dupl_sources'):\n        tot = info['calc_time'].sum() + info['split_time'].sum()\n        percent = tot_time / tot * 100\n        m = '\\nTotal time in duplicated sources: %d/%d (%d%%)' % (\n            tot_time, tot, percent)\n        return rst_table(tbl, ['source_id', 'calc_time', 'num_dupl']) + m\n    else:\n        return 'There are no duplicated sources'",
    "docstring": "Display the time spent computing duplicated sources"
  },
  {
    "code": "def add_children(d, key, **kwarg):\n        if kwarg:\n            d[key] = {_meta: kwarg}\n        else:\n            d[key] = dict()",
    "docstring": "Add a children with key and attributes. If children already EXISTS, \n        OVERWRITE it.\n\n        Usage::\n\n            >>> from pprint import pprint as ppt\n            >>> DT.add_children(d, \"VA\", name=\"virginia\", population=100*1000)\n            >>> DT.add_children(d, \"MD\", name=\"maryland\", population=200*1000)\n            >>> ppt(d)\n            {'_meta': {'population': 27800000, '_rootname': 'US'},\n             'MD': {'_meta': {'name': 'maryland', 'population': 200000}},\n             'VA': {'_meta': {'name': 'virginia', 'population': 100000}}}\n\n            >>> DT.add_children(d[\"VA\"], \"arlington\", \n                    name=\"arlington county\", population=5000)\n            >>> DT.add_children(d[\"VA\"], \"vienna\", \n                    name=\"vienna county\", population=5000)\n            >>> DT.add_children(d[\"MD\"], \"bethesta\", \n                    name=\"montgomery country\", population=5800)\n            >>> DT.add_children(d[\"MD\"], \"germentown\", \n                    name=\"fredrick country\", population=1400)\n\n            >>> DT.add_children(d[\"VA\"][\"arlington\"], \"riverhouse\", \n                    name=\"RiverHouse 1400\", population=437)\n            >>> DT.add_children(d[\"VA\"][\"arlington\"], \"crystal plaza\", \n                    name=\"Crystal plaza South\", population=681)\n            >>> DT.add_children(d[\"VA\"][\"arlington\"], \"loft\", \n                    name=\"loft hotel\", population=216)\n\n            >>> ppt(d)\n            {'MD': {'_meta': {'name': 'maryland', 'population': 200000},\n                    'bethesta': {'_meta': {'name': 'montgomery country',\n                                           'population': 5800}},\n                    'germentown': {'_meta': {'name': 'fredrick country',\n                                             'population': 1400}}},\n             'VA': {'_meta': {'name': 'virginia', 'population': 100000},\n                    'arlington': {'_meta': {'name': 'arlington county',\n                                            'population': 5000},\n                                  'crystal plaza': {'_meta': {'name': 'Crystal plaza South',\n                                                              'population': 681}},\n                                  'loft': {'_meta': {'name': 'loft hotel',\n                                                     'population': 216}},\n                                  'riverhouse': {'_meta': {'name': 'RiverHouse 1400',\n                                                           'population': 437}}},\n                    'vienna': {'_meta': {'name': 'vienna county', 'population': 1500}}},\n             '_meta': {'_rootname': 'US', 'population': 27800000.0}}"
  },
  {
    "code": "def _responsify(api_spec, error, status):\n    result_json = api_spec.model_to_json(error)\n    r = jsonify(result_json)\n    r.status_code = status\n    return r",
    "docstring": "Take a bravado-core model representing an error, and return a Flask Response\n    with the given error code and error instance as body"
  },
  {
    "code": "def dbfpack(fn, usecols=None):\n    loadfunc = pulldbf.dbf_asdict\n    cp = ChannelPack(loadfunc)\n    cp.load(fn, usecols)\n    names = pulldbf.channel_names(fn, usecols)\n    cp.set_channel_names(names)\n    return cp",
    "docstring": "Return a ChannelPack instance loaded with dbf data file fn.\n\n    This is a lazy function to get a loaded instance, using pulldbf\n    module."
  },
  {
    "code": "def call(self, additional_fields, restriction, shape, depth, max_items, offset):\n        from .folders import Folder\n        roots = {f.root for f in self.folders}\n        if len(roots) != 1:\n            raise ValueError('FindFolder must be called with folders in the same root hierarchy (%r)' % roots)\n        root = roots.pop()\n        for elem in self._paged_call(payload_func=self.get_payload, max_items=max_items, **dict(\n            additional_fields=additional_fields,\n            restriction=restriction,\n            shape=shape,\n            depth=depth,\n            page_size=self.chunk_size,\n            offset=offset,\n        )):\n            if isinstance(elem, Exception):\n                yield elem\n                continue\n            yield Folder.from_xml(elem=elem, root=root)",
    "docstring": "Find subfolders of a folder.\n\n        :param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects\n        :param shape: The set of attributes to return\n        :param depth: How deep in the folder structure to search for folders\n        :param max_items: The maximum number of items to return\n        :param offset: the offset relative to the first item in the item collection. Usually 0.\n        :return: XML elements for the matching folders"
  },
  {
    "code": "def edit_block(object):\n    @functools.wraps(object)\n    def edit_block_wrapper(*args, **kwargs):\n        if args:\n            cursor = foundations.common.get_first_item(args).textCursor()\n            cursor.beginEditBlock()\n        value = None\n        try:\n            value = object(*args, **kwargs)\n        finally:\n            if args:\n                cursor.endEditBlock()\n            return value\n    return edit_block_wrapper",
    "docstring": "Handles edit blocks undo states.\n\n    :param object: Object to decorate.\n    :type object: object\n    :return: Object.\n    :rtype: object"
  },
  {
    "code": "def downsample_completeness_table(comp_table, sample_width=0.1, mmax=None):\n    new_comp_table = []\n    for i in range(comp_table.shape[0] - 1):\n        mvals = np.arange(comp_table[i, 1],\n                          comp_table[i + 1, 1], d_m)\n        new_comp_table.extend([[comp_table[i, 0], mval] for mval in mvals])\n    if mmax and (mmax > comp_table[-1, 1]):\n        new_comp_table.extend(\n            [[comp_table[-1, 0], mval]\n             for mval in np.arange(comp_table[-1, 1], mmax + d_m, d_m)])\n    return np.array(new_comp_table)",
    "docstring": "Re-sample the completeness table to a specified sample_width"
  },
  {
    "code": "def find_cuda():\n    for fldr in os.environ['PATH'].split(os.pathsep):\n        cuda_path = join(fldr, 'nvcc')\n        if os.path.exists(cuda_path):\n            cuda_path = os.path.dirname(os.path.dirname(cuda_path))\n            break\n        cuda_path = None\n    if cuda_path is None:\n        print 'w> nvcc compiler could not be found from the PATH!'\n        return None\n    lcuda_path = os.path.join(cuda_path, 'lib64')\n    if 'LD_LIBRARY_PATH' in os.environ.keys():\n        if lcuda_path in os.environ['LD_LIBRARY_PATH'].split(os.pathsep):\n            print 'i> found CUDA lib64 in LD_LIBRARY_PATH:   ', lcuda_path\n    elif os.path.isdir(lcuda_path):\n        print 'i> found CUDA lib64 in :   ', lcuda_path\n    else:\n        print 'w> folder for CUDA library (64-bit) could not be found!'\n    return cuda_path, lcuda_path",
    "docstring": "Locate the CUDA environment on the system."
  },
  {
    "code": "def _fail_early(message, **kwds):\n    import json\n    output = dict(kwds)\n    output.update({\n        'msg': message,\n        'failed': True,\n    })\n    print(json.dumps(output))\n    sys.exit(1)",
    "docstring": "The module arguments are dynamically generated based on the Opsview\n    version. This means that fail_json isn't available until after the module\n    has been properly initialized and the schemas have been loaded."
  },
  {
    "code": "def _search(self, limit, format):\n        url = self.QUERY_URL.format(requests.utils.quote(\"'{}'\".format(self.query)), min(50, limit), self.current_offset, format)\n        r = requests.get(url, auth=(\"\", self.api_key))\n        try:\n            json_results = r.json()\n        except ValueError as vE:\n            if not self.safe:\n                raise PyBingVideoException(\"Request returned with code %s, error msg: %s\" % (r.status_code, r.text))\n            else:\n                print (\"[ERROR] Request returned with code %s, error msg: %s. \\nContinuing in 5 seconds.\" % (r.status_code, r.text))\n                time.sleep(5)\n        packaged_results = [VideoResult(single_result_json) for single_result_json in json_results['d']['results']]\n        self.current_offset += min(50, limit, len(packaged_results))\n        return packaged_results",
    "docstring": "Returns a list of result objects, with the url for the next page bing search url."
  },
  {
    "code": "def presets_dir():\n    default_presets_dir = os.path.join(\n        os.path.expanduser(\"~\"), \".be\", \"presets\")\n    presets_dir = os.environ.get(BE_PRESETSDIR) or default_presets_dir\n    if not os.path.exists(presets_dir):\n        os.makedirs(presets_dir)\n    return presets_dir",
    "docstring": "Return presets directory"
  },
  {
    "code": "def build_reduce(function: Callable[[Any, Any], Any] = None, *,\n                 init: Any = NONE):\n    _init = init\n    def _build_reduce(function: Callable[[Any, Any], Any]):\n        @wraps(function)\n        def _wrapper(init=NONE) -> Reduce:\n            init = _init if init is NONE else init\n            if init is NONE:\n                raise TypeError('init argument has to be defined')\n            return Reduce(function, init=init)\n        return _wrapper\n    if function:\n        return _build_reduce(function)\n    return _build_reduce",
    "docstring": "Decorator to wrap a function to return a Reduce operator.\n\n    :param function: function to be wrapped\n    :param init: optional initialization for state"
  },
  {
    "code": "def get_servo_angle(self):\n        servoposition =  self.get_servo_position()\n        if (self.servomodel==0x06) or (self.servomodel == 0x04):\n            return scale(servoposition, 10627, 22129, -159.9, 159.6)\n        else:\n            return scale(servoposition, 21, 1002, -150, 150)",
    "docstring": "Gets the current angle of the servo in degrees\n\n        Args:\n            none\n        Returns:\n            int : the current servo angle"
  },
  {
    "code": "def rnd_date_list_high_performance(size, start=date(1970, 1, 1), end=None, **kwargs):\n    if end is None:\n        end = date.today()\n    start_days = to_ordinal(parser.parse_datetime(start))\n    end_days = to_ordinal(parser.parse_datetime(end))\n    _assert_correct_start_end(start_days, end_days)\n    if has_np:\n        return [\n            from_ordinal(days)\n            for days in np.random.randint(start_days, end_days, size)\n        ]\n    else:\n        return [\n            from_ordinal(random.randint(start_days, end_days))\n            for _ in range(size)\n        ]",
    "docstring": "Generate mass random date.\n\n    :param size: int, number of\n    :param start: date similar object, int / str / date / datetime\n    :param end: date similar object, int / str / date / datetime, default today's date\n    :param kwargs: args placeholder\n    :return: list of datetime.date"
  },
  {
    "code": "def start_event_stream(self):\n        if not self._stream:\n            self._stream = GerritStream(self, ssh_client=self._ssh_client)\n            self._stream.start()",
    "docstring": "Start streaming events from `gerrit stream-events`."
  },
  {
    "code": "def add_probe(self, probe):\n        if self.probes:\n            probe_last = self.probes[-1]\n            if not probe.ip:\n                probe.ip = probe_last.ip\n                probe.name = probe_last.name\n        self.probes.append(probe)",
    "docstring": "Adds a Probe instance to this hop's results."
  },
  {
    "code": "def compare_dicts(d1, d2):\n    a = json.dumps(d1, indent=4, sort_keys=True)\n    b = json.dumps(d2, indent=4, sort_keys=True)\n    diff = ('\\n' + '\\n'.join(difflib.ndiff(\n                   a.splitlines(),\n                   b.splitlines())))\n    return diff",
    "docstring": "Returns a diff string of the two dicts."
  },
  {
    "code": "def qpinfo():\n    parser = qpinfo_parser()\n    args = parser.parse_args()\n    path = pathlib.Path(args.path).resolve()\n    try:\n        ds = load_data(path)\n    except UnknownFileFormatError:\n        print(\"Unknown file format: {}\".format(path))\n        return\n    print(\"{} ({})\".format(ds.__class__.__doc__, ds.__class__.__name__))\n    print(\"- number of images: {}\".format(len(ds)))\n    for key in ds.meta_data:\n        print(\"- {}: {}\".format(key, ds.meta_data[key]))",
    "docstring": "Print information of a quantitative phase imaging dataset"
  },
  {
    "code": "def get_uuid(type=4):\n    import uuid\n    name = 'uuid'+str(type)\n    u = getattr(uuid, name)\n    return u().hex",
    "docstring": "Get uuid value"
  },
  {
    "code": "def write_to(self, f, version = None):\n        if not version:\n            version = self.version\n        if version == 1:\n            header = \"%(url)s %(ip_address)s %(date)s %(content_type)s %(length)s\"\n        elif version == 2:\n            header = \"%(url)s %(ip_address)s %(date)s %(content_type)s %(result_code)s %(checksum)s %(location)s %(offset)s %(filename)s %(length)s\"\n        header =  header%dict(url          = self['url'],\n                              ip_address   = self['ip_address'],\n                              date         = self['date'],\n                              content_type = self['content_type'],\n                              result_code  = self['result_code'],\n                              checksum     = self['checksum'],\n                              location     = self['location'],\n                              offset       = self['offset'],\n                              filename     = self['filename'],\n                              length       = self['length'])\n        f.write(header)",
    "docstring": "Writes out the arc header to the file like object `f`. \n\n        If the version field is 1, it writes out an arc v1 header,\n        otherwise (and this is default), it outputs a v2 header."
  },
  {
    "code": "def unique_file_name(base_name, extension=''):\n    idcount = 0\n    if extension and not extension.startswith('.'):\n        extension = '.%s' % extension\n    fname = base_name + extension\n    while os.path.exists(fname):\n        fname = \"%s-%d%s\" % (base_name, idcount, extension)\n        idcount += 1\n    return fname",
    "docstring": "Creates a unique file name based on the specified base name.\n\n    @base_name - The base name to use for the unique file name.\n    @extension - The file extension to use for the unique file name.\n\n    Returns a unique file string."
  },
  {
    "code": "def _log_every_n_to_logger(n, logger, level, message, *args):\n  logger = logger or logging.getLogger()\n  def _gen():\n    while True:\n      for _ in range(n):\n        yield False\n      logger.log(level, message, *args)\n      yield True\n  gen = _gen()\n  return lambda: six.next(gen)",
    "docstring": "Logs the given message every n calls to a logger.\n\n  Args:\n    n: Number of calls before logging.\n    logger: The logger to which to log.\n    level: The logging level (e.g. logging.INFO).\n    message: A message to log\n    *args: Any format args for the message.\n  Returns:\n    A method that logs and returns True every n calls."
  },
  {
    "code": "def _opening_bracket_index(self, text, bpair=('(', ')')):\n        level = 1\n        for i, char in enumerate(reversed(text[:-1])):\n            if char == bpair[1]:\n                level += 1\n            elif char == bpair[0]:\n                level -= 1\n            if level == 0:\n                return len(text) - i - 2",
    "docstring": "Return the index of the opening bracket that matches the closing bracket at the end of the text."
  },
  {
    "code": "def create_zone(zone, private=False, vpc_id=None, vpc_region=None, region=None,\n                key=None, keyid=None, profile=None):\n    if region is None:\n        region = 'universal'\n    if private:\n        if not vpc_id or not vpc_region:\n            msg = 'vpc_id and vpc_region must be specified for a private zone'\n            raise SaltInvocationError(msg)\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    _zone = conn.get_zone(zone)\n    if _zone:\n        return False\n    conn.create_zone(zone, private_zone=private, vpc_id=vpc_id,\n                     vpc_region=vpc_region)\n    return True",
    "docstring": "Create a Route53 hosted zone.\n\n    .. versionadded:: 2015.8.0\n\n    zone\n        DNS zone to create\n\n    private\n        True/False if the zone will be a private zone\n\n    vpc_id\n        VPC ID to associate the zone to (required if private is True)\n\n    vpc_region\n        VPC Region (required if private is True)\n\n    region\n        region endpoint to connect to\n\n    key\n        AWS key\n\n    keyid\n        AWS keyid\n\n    profile\n        AWS pillar profile\n\n    CLI Example::\n\n        salt myminion boto_route53.create_zone example.org"
  },
  {
    "code": "def word(cap=False):\n    syllables = []\n    for x in range(random.randint(2,3)):\n        syllables.append(_syllable())\n    word = \"\".join(syllables)\n    if cap: word = word[0].upper() + word[1:]\n    return word",
    "docstring": "This function generates a fake word by creating between two and three\n        random syllables and then joining them together."
  },
  {
    "code": "def pipe_exchangerate(context=None, _INPUT=None, conf=None, **kwargs):\n    offline = conf.get('offline', {}).get('value')\n    rate_data = get_offline_rate_data(err=False) if offline else get_rate_data()\n    rates = parse_request(rate_data)\n    splits = get_splits(_INPUT, conf, **cdicts(opts, kwargs))\n    parsed = utils.dispatch(splits, *get_dispatch_funcs())\n    _OUTPUT = starmap(partial(parse_result, rates=rates), parsed)\n    return _OUTPUT",
    "docstring": "A string module that retrieves the current exchange rate for a given\n    currency pair. Loopable.\n\n    Parameters\n    ----------\n    context : pipe2py.Context object\n    _INPUT : iterable of items or strings (base currency)\n    conf : {\n        'quote': {'value': <'USD'>},\n        'default': {'value': <'USD'>},\n        'offline': {'type': 'bool', 'value': '0'},\n    }\n\n    Returns\n    -------\n    _OUTPUT : generator of hashed strings"
  },
  {
    "code": "def to_cfn_resource_name(name):\n    if not name:\n        raise ValueError(\"Invalid name: %r\" % name)\n    word_separators = ['-', '_']\n    for word_separator in word_separators:\n        word_parts = [p for p in name.split(word_separator) if p]\n        name = ''.join([w[0].upper() + w[1:] for w in word_parts])\n    return re.sub(r'[^A-Za-z0-9]+', '', name)",
    "docstring": "Transform a name to a valid cfn name.\n\n    This will convert the provided name to a CamelCase name.\n    It's possible that the conversion to a CFN resource name\n    can result in name collisions.  It's up to the caller\n    to handle name collisions appropriately."
  },
  {
    "code": "def xmoe_2d():\n  hparams = xmoe_top_2()\n  hparams.decoder_layers = [\"att\", \"hmoe\"] * 4\n  hparams.mesh_shape = \"b0:2;b1:4\"\n  hparams.outer_batch_size = 4\n  hparams.layout = \"outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0\"\n  hparams.moe_num_experts = [4, 4]\n  return hparams",
    "docstring": "Two-dimensional hierarchical mixture of 16 experts."
  },
  {
    "code": "def get_experiment_from_id(self, experiment_id):\n    experiment = self.experiment_id_map.get(experiment_id)\n    if experiment:\n      return experiment\n    self.logger.error('Experiment ID \"%s\" is not in datafile.' % experiment_id)\n    self.error_handler.handle_error(exceptions.InvalidExperimentException(enums.Errors.INVALID_EXPERIMENT_KEY_ERROR))\n    return None",
    "docstring": "Get experiment for the provided experiment ID.\n\n    Args:\n      experiment_id: Experiment ID for which experiment is to be determined.\n\n    Returns:\n      Experiment corresponding to the provided experiment ID."
  },
  {
    "code": "def _send_ack(self, transaction):\n        ack = Message()\n        ack.type = defines.Types['ACK']\n        if not transaction.request.acknowledged and transaction.request.type == defines.Types[\"CON\"]:\n            ack = self._messageLayer.send_empty(transaction, transaction.request, ack)\n            self.send_datagram(ack)",
    "docstring": "Sends an ACK message for the request.\n\n        :param transaction: the transaction that owns the request"
  },
  {
    "code": "def are_equal(self, sp1, sp2):\n        set1 = set(sp1.elements)\n        set2 = set(sp2.elements)\n        return set1.issubset(set2) or set2.issubset(set1)",
    "docstring": "True if there is some overlap in composition between the species\n\n        Args:\n            sp1: First species. A dict of {specie/element: amt} as per the\n                definition in Site and PeriodicSite.\n            sp2: Second species. A dict of {specie/element: amt} as per the\n                definition in Site and PeriodicSite.\n\n        Returns:\n            True always"
  },
  {
    "code": "def _check_repos(self, repos):\n        self._checking_repos = []\n        self._valid_repos = []\n        for repo in repos:\n            worker = self.download_is_valid_url(repo)\n            worker.sig_finished.connect(self._repos_checked)\n            worker.repo = repo\n            self._checking_repos.append(repo)",
    "docstring": "Check if repodata urls are valid."
  },
  {
    "code": "def _resolve_dtype(data_type):\n    if isinstance(data_type, _FIXED_ATOMIC):\n        out = _get_atomic_dtype(data_type)\n    elif isinstance(data_type, _FLEXIBLE_ATOMIC):\n        out = (_get_atomic_dtype(data_type), data_type.length)\n    elif isinstance(data_type, Array):\n        shape = data_type.shape\n        if isinstance(shape, _SEQUENCE_TYPES) and len(shape) == 1:\n            shape = shape[0]\n        out = (_resolve_dtype(data_type.element_type), shape)\n    elif isinstance(data_type, Structure):\n        out = [(field.name, _resolve_dtype(field.type))\n               for field in data_type.fields]\n    return out",
    "docstring": "Retrieve the corresponding NumPy's `dtype` for a given data type."
  },
  {
    "code": "def find_key_by_subkey(self, subkey):\n        for key in self.list_keys():\n            for sub in key['subkeys']:\n                if sub[0] == subkey:\n                    return key\n        raise LookupError(\n            \"GnuPG public key for subkey %s not found!\" % subkey)",
    "docstring": "Find a key by a fingerprint of one of its subkeys.\n\n        :param str subkey: The fingerprint of the subkey to search for."
  },
  {
    "code": "def registry_key(self, key_name, value_name, value_type, **kwargs):\n        indicator_obj = RegistryKey(key_name, value_name, value_type, **kwargs)\n        return self._indicator(indicator_obj)",
    "docstring": "Add Registry Key data to Batch object.\n\n        Args:\n            key_name (str): The key_name value for this Indicator.\n            value_name (str): The value_name value for this Indicator.\n            value_type (str): The value_type value for this Indicator.\n            confidence (str, kwargs): The threat confidence for this Indicator.\n            date_added (str, kwargs): The date timestamp the Indicator was created.\n            last_modified (str, kwargs): The date timestamp the Indicator was last modified.\n            rating (str, kwargs): The threat rating for this Indicator.\n            xid (str, kwargs): The external id for this Indicator.\n\n        Returns:\n            obj: An instance of Registry Key."
  },
  {
    "code": "def load_module(module_name, module_path):\n    if sys.version_info >= (3,0):\n        import pyximport\n        pyximport.install()\n        sys.path.append(module_path)\n        return __import__(module_name)\n    else:\n        import imp\n        module_info = imp.find_module(module_name, [module_path])\n        return imp.load_module(module_name, *module_info)",
    "docstring": "Load the module named `module_name` from  `module_path`\n    independently of the Python version."
  },
  {
    "code": "def current(self):\n        top = super(Transaction, self).current()\n        if isinstance(top, Transaction):\n            return top",
    "docstring": "Return the topmost transaction.\n\n        .. note::\n\n            If the topmost element on the stack is not a transaction,\n            returns None.\n\n        :rtype: :class:`google.cloud.datastore.transaction.Transaction` or None\n        :returns: The current transaction (if any are active)."
  },
  {
    "code": "def _get_digit_list(alist: [str], from_index: int) -> ([str], [str]):\n    ret = []\n    alist.pop(from_index)\n    while len(alist) > from_index and alist[from_index].isdigit():\n        ret.append(alist.pop(from_index))\n    return alist, ret",
    "docstring": "Returns a list of items removed from a given list of strings\n    that are all digits from 'from_index' until hitting a non-digit item"
  },
  {
    "code": "def add_root_family(self, family_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.add_root_catalog(catalog_id=family_id)\n        return self._hierarchy_session.add_root(id_=family_id)",
    "docstring": "Adds a root family.\n\n        arg:    family_id (osid.id.Id): the ``Id`` of a family\n        raise:  AlreadyExists - ``family_id`` is already in hierarchy\n        raise:  NotFound - ``family_id`` not found\n        raise:  NullArgument - ``family_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def dim_reduce_data(data, d):\n    genes, cells = data.shape\n    distances = np.zeros((cells, cells))\n    for i in range(cells):\n        for j in range(cells):\n            distances[i,j] = poisson_dist(data[:,i], data[:,j])\n    proximity = distances**2\n    J = np.eye(cells) - 1./cells\n    B = -0.5*np.dot(J, np.dot(proximity, J))\n    e_val, e_vec = np.linalg.eigh(B)\n    lam = np.diag(e_val[-d:])[::-1]\n    E = e_vec[:,-d:][::-1]\n    X = np.dot(E, lam**0.5)\n    return X",
    "docstring": "Does a MDS on the data directly, not on the means.\n\n    Args:\n        data (array): genes x cells\n        d (int): desired dimensionality\n\n    Returns:\n        X, a cells x d matrix"
  },
  {
    "code": "def expand(directory: str) -> str:\n    temp1 = os.path.expanduser(directory)\n    return os.path.expandvars(temp1)",
    "docstring": "Apply expanduser and expandvars to directory to expand '~' and env vars."
  },
  {
    "code": "def iter(self, columnnames, order='', sort=True):\n        from .tableiter import tableiter\n        return tableiter(self, columnnames, order, sort)",
    "docstring": "Return a tableiter object.\n\n        :class:`tableiter` lets one iterate over a table by returning in each\n        iteration step a reference table containing equal values for the given\n        columns.\n        By default a sort is done on the given columns to get the correct\n        iteration order.\n\n        `order`\n          | 'ascending'  is iterate in ascending order (is the default).\n          | 'descending' is iterate in descending order.\n        `sort=False`\n          do not sort (because table is already in correct order).\n\n        For example, iterate by time through a measurementset table::\n\n          t = table('3c343.MS')\n          for ts in t.iter('TIME'):\n            print ts.nrows()"
  },
  {
    "code": "def _get_log_format(self, request):\n        user = getattr(request, 'user', None)\n        if not user:\n            return\n        if not request.user.is_authenticated:\n            return\n        method = request.method.upper()\n        if not (method in self.target_methods):\n            return\n        request_url = urlparse.unquote(request.path)\n        for rule in self._ignored_urls:\n            if rule.search(request_url):\n                return\n        return self.format",
    "docstring": "Return operation log format."
  },
  {
    "code": "def list_():\n    ret = {}\n    cmd = 'cpan -l'\n    out = __salt__['cmd.run'](cmd).splitlines()\n    for line in out:\n        comps = line.split()\n        ret[comps[0]] = comps[1]\n    return ret",
    "docstring": "List installed Perl modules, and the version installed\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' cpan.list"
  },
  {
    "code": "def _request(self, http_method, relative_url='', **kwargs):\n        relative_url = self._remove_leading_slash(relative_url)\n        new_kwargs = self.default_kwargs().copy()\n        custom_kwargs = self.before_request(\n            http_method,\n            relative_url,\n            kwargs.copy()\n        )\n        new_kwargs.update(custom_kwargs)\n        response = requests.request(\n            http_method,\n            self._join_url(relative_url),\n            **new_kwargs\n        )\n        return self.after_request(response)",
    "docstring": "Does actual HTTP request using requests library."
  },
  {
    "code": "def registerExitCall():\n  r\n  if state.isExitHooked:\n    return\n  state.isExitHooked = True\n  from atexit import register\n  register(core.start)",
    "docstring": "r\"\"\"Registers an exit call to start the core.\n\n    The core would be started after the main module is loaded. Ec would be exited from the core."
  },
  {
    "code": "def trim(self):\n\t\tif 0 < self.cutoff <= 0.5:\n\t\t\tpscore = self.raw_data['pscore']\n\t\t\tkeep = (pscore >= self.cutoff) & (pscore <= 1-self.cutoff)\n\t\t\tY_trimmed = self.raw_data['Y'][keep]\n\t\t\tD_trimmed = self.raw_data['D'][keep]\n\t\t\tX_trimmed = self.raw_data['X'][keep]\n\t\t\tself.raw_data = Data(Y_trimmed, D_trimmed, X_trimmed)\n\t\t\tself.raw_data._dict['pscore'] = pscore[keep]\n\t\t\tself.summary_stats = Summary(self.raw_data)\n\t\t\tself.strata = None\n\t\t\tself.estimates = Estimators()\n\t\telif self.cutoff == 0:\n\t\t\tpass\n\t\telse:\n\t\t\traise ValueError('Invalid cutoff.')",
    "docstring": "Trims data based on propensity score to create a subsample with\n\t\tbetter covariate balance.\n\t\t\n\t\tThe default cutoff value is set to 0.1. To set a custom cutoff\n\t\tvalue, modify the object attribute named cutoff directly.\n\n\t\tThis method should only be executed after the propensity score\n\t\thas been estimated."
  },
  {
    "code": "def generate_tensor_filename(self, field_name, file_num, compressed=True):\n        file_ext = TENSOR_EXT\n        if compressed:\n            file_ext = COMPRESSED_TENSOR_EXT\n        filename = os.path.join(self.filename, 'tensors', '%s_%05d%s' %(field_name, file_num, file_ext))\n        return filename",
    "docstring": "Generate a filename for a tensor."
  },
  {
    "code": "def deconstruct(self):\n        name, path, args, kwargs = super(CountryField, self).deconstruct()\n        kwargs.pop(\"choices\")\n        if self.multiple:\n            kwargs[\"multiple\"] = self.multiple\n        if self.countries is not countries:\n            kwargs[\"countries\"] = self.countries.__class__\n        return name, path, args, kwargs",
    "docstring": "Remove choices from deconstructed field, as this is the country list\n        and not user editable.\n\n        Not including the ``blank_label`` property, as this isn't database\n        related."
  },
  {
    "code": "def from_string(cls, string):\n    if string in units.UNITS_BY_ALL:\n      return cls(description=string, unit=units.Unit(string))\n    else:\n      return cls(description=string)",
    "docstring": "Convert a string into a Dimension"
  },
  {
    "code": "def _build_field_choices(self, fields):\n        return tuple(sorted(\n            [(fquery, capfirst(fname)) for fquery, fname in fields.items()],\n            key=lambda f: f[1].lower())\n        ) + self.FIELD_CHOICES",
    "docstring": "Iterate over passed model fields tuple and update initial choices."
  },
  {
    "code": "def longest_one_seg_prefix(self, word):\n        for i in range(self.longest_seg, 0, -1):\n            if word[:i] in self.seg_dict:\n                return word[:i]\n        return ''",
    "docstring": "Return longest Unicode IPA prefix of a word\n\n        Args:\n            word (unicode): input word as Unicode IPA string\n\n        Returns:\n            unicode: longest single-segment prefix of `word` in database"
  },
  {
    "code": "def check_password_confirm(self, form, trigger_action_group=None):\n        pwcol = self.options['password_column']\n        pwconfirmfield = pwcol + \"_confirm\"\n        if pwcol in form and pwconfirmfield in form and form[pwconfirmfield].data != form[pwcol].data:\n            if self.options[\"password_confirm_failed_message\"]:\n                flash(self.options[\"password_confirm_failed_message\"], \"error\")\n            current_context.exit(trigger_action_group=trigger_action_group)",
    "docstring": "Checks that the password and the confirm password match in\n        the provided form. Won't do anything if any of the password fields\n        are not in the form."
  },
  {
    "code": "def _setup_buffer(self):\n        if not self._buffer_cfg or not isinstance(self._buffer_cfg, dict):\n            return\n        buffer_name = list(self._buffer_cfg.keys())[0]\n        buffer_class = napalm_logs.buffer.get_interface(buffer_name)\n        log.debug('Setting up buffer interface \"%s\"', buffer_name)\n        if 'expire_time' not in self._buffer_cfg[buffer_name]:\n            self._buffer_cfg[buffer_name]['expire_time'] = CONFIG.BUFFER_EXPIRE_TIME\n        self._buffer = buffer_class(**self._buffer_cfg[buffer_name])",
    "docstring": "Setup the buffer subsystem."
  },
  {
    "code": "def _connect(self):\n        \"Create a Unix domain socket connection\"\n        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n        sock.settimeout(self.socket_timeout)\n        sock.connect(self.path)\n        return sock",
    "docstring": "Create a Unix domain socket connection"
  },
  {
    "code": "def truncate_rationale(rationale, max_length=MAX_RATIONALE_SIZE_IN_EVENT):\n    if isinstance(rationale, basestring) and max_length is not None and len(rationale) > max_length:\n        return rationale[0:max_length], True\n    else:\n        return rationale, False",
    "docstring": "Truncates the rationale for analytics event emission if necessary\n\n    Args:\n        rationale (string): the string value of the rationale\n        max_length (int): the max length for truncation\n\n    Returns:\n        truncated_value (string): the possibly truncated version of the rationale\n        was_truncated (bool): returns true if the rationale is truncated"
  },
  {
    "code": "def _get_module(self, line):\n        for sline in self._source:\n            if len(sline) > 0 and sline[0] != \"!\":\n                rmatch = self.RE_MODULE.match(sline)\n                if rmatch is not None:\n                    self.modulename = rmatch.group(\"name\")\n                    break\n        else:\n            return\n        self.parser.isense_parse(self._orig_path, self.modulename)\n        self.module = self.parser.modules[self.modulename]\n        if line > self.module.contains_index:\n            self.section = \"contains\"",
    "docstring": "Finds the name of the module and retrieves it from the parser cache."
  },
  {
    "code": "def nth_value(expr, nth, skip_nulls=False, sort=None, ascending=True):\n    return _cumulative_op(expr, NthValue, data_type=expr._data_type, sort=sort,\n                          ascending=ascending, _nth=nth, _skip_nulls=skip_nulls)",
    "docstring": "Get nth value of a grouped and sorted expression.\n\n    :param expr: expression for calculation\n    :param nth: integer position\n    :param skip_nulls: whether to skip null values, False by default\n    :param sort: name of the sort column\n    :param ascending: whether to sort in ascending order\n    :return: calculated column"
  },
  {
    "code": "def crypto_pwhash_str_alg(passwd, opslimit, memlimit, alg):\n    ensure(isinstance(opslimit, integer_types),\n           raising=TypeError)\n    ensure(isinstance(memlimit, integer_types),\n           raising=TypeError)\n    ensure(isinstance(passwd, bytes),\n           raising=TypeError)\n    _check_argon2_limits_alg(opslimit, memlimit, alg)\n    outbuf = ffi.new(\"char[]\", 128)\n    ret = lib.crypto_pwhash_str_alg(outbuf, passwd, len(passwd),\n                                    opslimit, memlimit, alg)\n    ensure(ret == 0, 'Unexpected failure in key derivation',\n           raising=exc.RuntimeError)\n    return ffi.string(outbuf)",
    "docstring": "Derive a cryptographic key using the ``passwd`` given as input\n    and a random ``salt``, returning a string representation which\n    includes the salt, the tuning parameters and the used algorithm.\n\n    :param passwd: The input password\n    :type passwd: bytes\n    :param opslimit: computational cost\n    :type opslimit: int\n    :param memlimit: memory cost\n    :type memlimit: int\n    :param alg: The algorithm to use\n    :type alg: int\n    :return: serialized derived key and parameters\n    :rtype: bytes"
  },
  {
    "code": "def WritePythonFile(file_descriptor, package, version, printer):\n    _WriteFile(file_descriptor, package, version,\n               _ProtoRpcPrinter(printer))",
    "docstring": "Write the given extended file descriptor to out."
  },
  {
    "code": "def init_config(self):\n        input_fpath = os.path.join(self.work_path, 'input.nml')\n        input_nml = f90nml.read(input_fpath)\n        if self.expt.counter == 0 or self.expt.repeat_run:\n            input_type = 'n'\n        else:\n            input_type = 'r'\n        input_nml['MOM_input_nml']['input_filename'] = input_type\n        f90nml.write(input_nml, input_fpath, force=True)",
    "docstring": "Patch input.nml as a new or restart run."
  },
  {
    "code": "def _compute_radii(self):\n        radii = self._get_user_components('radii')\n        if (radii is None):\n            centers = self.components_['centers']\n            n_centers = centers.shape[0]\n            max_dist = np.max(pairwise_distances(centers))\n            radii = np.ones(n_centers) * max_dist/sqrt(2.0 * n_centers)\n        self.components_['radii'] = radii",
    "docstring": "Generate RBF radii"
  },
  {
    "code": "def assert_visible(self, selector, testid=None, **kwargs):\n        self.info_log(\n            \"Assert visible selector(%s) testid(%s)\" % (selector, testid)\n        )\n        highlight = kwargs.get(\n            'highlight',\n            BROME_CONFIG['highlight']['highlight_on_assertion_success']\n        )\n        self.debug_log(\"effective highlight: %s\" % highlight)\n        wait_until_visible = kwargs.get(\n            'wait_until_visible',\n            BROME_CONFIG['proxy_driver']['wait_until_visible_before_assert_visible']\n        )\n        self.debug_log(\"effective wait_until_visible: %s\" % wait_until_visible)\n        if wait_until_visible:\n            self.wait_until_visible(selector, raise_exception=False)\n        element = self.find(\n            selector,\n            raise_exception=False,\n            wait_until_visible=False,\n            wait_until_present=False\n        )\n        if element and element.is_displayed(raise_exception=False):\n            if highlight:\n                element.highlight(\n                    style=BROME_CONFIG['highlight']['style_on_assertion_success']\n                )\n            if testid is not None:\n                self.create_test_result(testid, True)\n            return True\n        else:\n            if testid is not None:\n                self.create_test_result(testid, False)\n            return False",
    "docstring": "Assert that the element is visible in the dom\n\n        Args:\n            selector (str): the selector used to find the element\n            testid (str): the test_id or a str\n\n        Kwargs:\n            wait_until_visible (bool)\n            highlight (bool)\n\n        Returns:\n            bool: True is the assertion succeed; False otherwise."
  },
  {
    "code": "def toggle_value(request, name):\n    obj = service.system.namespace.get(name, None)\n    if not obj or service.read_only:\n        raise Http404\n    new_status = obj.status = not obj.status\n    if service.redirect_from_setters:\n        return HttpResponseRedirect(reverse('set_ready', args=(name, new_status)))\n    else:\n        return set_ready(request, name, new_status)",
    "docstring": "For manual shortcut links to perform toggle actions"
  },
  {
    "code": "def set_subnet_name(name):\n    cmd = 'systemsetup -setlocalsubnetname \"{0}\"'.format(name)\n    __utils__['mac_utils.execute_return_success'](cmd)\n    return __utils__['mac_utils.confirm_updated'](\n        name,\n        get_subnet_name,\n    )",
    "docstring": "Set the local subnet name\n\n    :param str name: The new local subnet name\n\n    .. note::\n       Spaces are changed to dashes. Other special characters are removed.\n\n    :return: True if successful, False if not\n    :rtype: bool\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        The following will be set as 'Mikes-Mac'\n        salt '*' system.set_subnet_name \"Mike's Mac\""
  },
  {
    "code": "def save(self):\n        kwargs = {}\n        if self.id3v23:\n            id3 = self.mgfile\n            if hasattr(id3, 'tags'):\n                id3 = id3.tags\n            id3.update_to_v23()\n            kwargs['v2_version'] = 3\n        mutagen_call('save', self.path, self.mgfile.save, **kwargs)",
    "docstring": "Write the object's tags back to the file. May\n        throw `UnreadableFileError`."
  },
  {
    "code": "def get(self, robj, r=None, pr=None, timeout=None, basic_quorum=None,\n            notfound_ok=None, head_only=False):\n        msg_code = riak.pb.messages.MSG_CODE_GET_REQ\n        codec = self._get_codec(msg_code)\n        msg = codec.encode_get(robj, r, pr,\n                               timeout, basic_quorum,\n                               notfound_ok, head_only)\n        resp_code, resp = self._request(msg, codec)\n        return codec.decode_get(robj, resp)",
    "docstring": "Serialize get request and deserialize response"
  },
  {
    "code": "def get_books(self):\n        if self.retrieved:\n            raise errors.IllegalState('List has already been retrieved.')\n        self.retrieved = True\n        return objects.BookList(self._results, runtime=self._runtime)",
    "docstring": "Gets the book list resulting from a search.\n\n        return: (osid.commenting.BookList) - the book list\n        raise:  IllegalState - list has already been retrieved\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def markdown(text, html=False, valid_tags=GFM_TAGS):\n    if text is None:\n        return None\n    if html:\n        return Markup(sanitize_html(markdown_convert_html(gfm(text)), valid_tags=valid_tags))\n    else:\n        return Markup(markdown_convert_text(gfm(text)))",
    "docstring": "Return Markdown rendered text using GitHub Flavoured Markdown,\n    with HTML escaped and syntax-highlighting enabled."
  },
  {
    "code": "def validate(self, value):\n        try:\n            if value:\n                v = float(value)\n                if (v != 0 and v < self.fmin) or v > self.fmax:\n                    return None\n                if abs(round(100000*v)-100000*v) > 1.e-12:\n                    return None\n            return value\n        except ValueError:\n            return None",
    "docstring": "This prevents setting any value more precise than 0.00001"
  },
  {
    "code": "def get(self, *args, **kwargs):\n        self.before_get(args, kwargs)\n        qs = QSManager(request.args, self.schema)\n        objects_count, objects = self.get_collection(qs, kwargs)\n        schema_kwargs = getattr(self, 'get_schema_kwargs', dict())\n        schema_kwargs.update({'many': True})\n        self.before_marshmallow(args, kwargs)\n        schema = compute_schema(self.schema,\n                                schema_kwargs,\n                                qs,\n                                qs.include)\n        result = schema.dump(objects).data\n        view_kwargs = request.view_args if getattr(self, 'view_kwargs', None) is True else dict()\n        add_pagination_links(result,\n                             objects_count,\n                             qs,\n                             url_for(self.view, _external=True, **view_kwargs))\n        result.update({'meta': {'count': objects_count}})\n        final_result = self.after_get(result)\n        return final_result",
    "docstring": "Retrieve a collection of objects"
  },
  {
    "code": "def latch_file_info(self, args):\n        self.file_dict.clear()\n        for key, val in self.file_args.items():\n            try:\n                file_path = args[key]\n                if file_path is None:\n                    continue\n                if key[0:4] == 'args':\n                    if isinstance(file_path, list):\n                        tokens = file_path\n                    elif isinstance(file_path, str):\n                        tokens = file_path.split()\n                    else:\n                        raise TypeError(\n                            \"Args has type %s, expect list or str\" % type(file_path))\n                    for token in tokens:\n                        self.file_dict[token.replace('.gz', '')] = val\n                else:\n                    self.file_dict[file_path.replace('.gz', '')] = val\n            except KeyError:\n                pass",
    "docstring": "Extract the file paths from a set of arguments"
  },
  {
    "code": "def conversations(self):\n        body = {\n            \"conversation_type\": self.conversation_type,\n            \"audience_definition\": self.audience_definition,\n            \"targeting_inputs\": self.targeting_inputs\n        }\n        return self.__get(account=self.account, client=self.account.client, params=json.dumps(body))",
    "docstring": "Get the conversation topics for an input targeting criteria"
  },
  {
    "code": "def OnCellBorderWidth(self, event):\n        with undo.group(_(\"Border width\")):\n            self.grid.actions.set_border_attr(\"borderwidth\",\n                                              event.width, event.borders)\n        self.grid.ForceRefresh()\n        self.grid.update_attribute_toolbar()\n        event.Skip()",
    "docstring": "Cell border width event handler"
  },
  {
    "code": "def account_xdr_object(self):\n        return Xdr.types.PublicKey(Xdr.const.KEY_TYPE_ED25519,\n                                   self.verifying_key.to_bytes())",
    "docstring": "Create PublicKey XDR object via public key bytes.\n\n        :return: Serialized XDR of PublicKey type."
  },
  {
    "code": "def dar_nombre_campo_dbf(clave, claves):\n    \"Reducir nombre de campo a 10 caracteres, sin espacios ni _, sin repetir\"\n    nombre = clave.replace(\"_\",\"\")[:10]\n    i = 0\n    while nombre in claves:\n        i += 1    \n        nombre = nombre[:9] + str(i)\n    return nombre.lower()",
    "docstring": "Reducir nombre de campo a 10 caracteres, sin espacios ni _, sin repetir"
  },
  {
    "code": "def get_all_trials(self):\n        response = requests.get(urljoin(self._path, \"trials\"))\n        return self._deserialize(response)",
    "docstring": "Returns a list of all trials' information."
  },
  {
    "code": "def check_config_options(_class, required_options, optional_options, options):\n    for opt in required_options:\n        if opt not in options:\n            msg = \"Required option missing: {0}\"\n            raise ConfigurationError(msg.format(opt))\n    for opt in options:\n        if opt not in (required_options + optional_options):\n            msg = \"Unknown config option to `{0}`: {1}\"\n            _logger.warn(msg.format(_class, opt))",
    "docstring": "Helper method to check options.\n\n    Arguments:\n    _class           -- the original class that takes received the options.\n    required_options -- the options that are required. If they are not\n                        present, a ConfigurationError is raised. Given as a\n                        tuple.\n    optional_options -- the options that are optional. Given options that are\n                        not present in `optional_options` nor in\n                        `required_options` will be logged as unrecognized.\n                        Given as a tuple.\n    options          -- a dictionary of given options.\n\n    Raises:\n    ConfigurationError -- if any required option is missing."
  },
  {
    "code": "def get_fieldset_index(fieldsets, index_or_name):\n    if isinstance(index_or_name, six.integer_types):\n        return index_or_name\n    for key, value in enumerate(fieldsets):\n        if value[0] == index_or_name:\n            return key\n    raise KeyError(\"Key not found: '{}'.\".format(index_or_name))",
    "docstring": "Return the index of a fieldset in the ``fieldsets`` list.\n\n    Args:\n        fieldsets (list): The original ``fieldsets`` list.\n        index_or_name (int or str): The value of the reference element, or directly its numeric index.\n\n    Returns:\n        (int) The index of the fieldset in the ``fieldsets`` list."
  },
  {
    "code": "def commandify(use_argcomplete=False, exit=True, *args, **kwargs):\n    parser = CommandifyArgumentParser(*args, **kwargs)\n    parser.setup_arguments()\n    if use_argcomplete:\n        try:\n            import argcomplete\n        except ImportError:\n            print('argcomplete not installed, please install it.')\n            parser.exit(status=2)\n        argcomplete.autocomplete(parser)\n    args = parser.parse_args()\n    if exit:\n        parser.dispatch_commands()\n        parser.exit(0)\n    else:\n        return parser.dispatch_commands()",
    "docstring": "Turns decorated functions into command line args\n\n    Finds the main_command and all commands and generates command line args\n    from these."
  },
  {
    "code": "def progress_task(name=None, t=INFO, max_value=100, *args, **kwargs):\n    return task(name=name, t=t, init_progress=True, max_value=max_value,\n                *args, **kwargs)",
    "docstring": "This decorator extends the basic @task decorator by allowing users to\n    display some form of progress on the console. The module can receive\n    an increment in the progress through \"tick_progress\"."
  },
  {
    "code": "def _write_index_file(data_dir):\n    cached_words = [\n        w\n        for w in _get_words(data_dir)\n        if data_dir.joinpath(\"translations/{}.html\".format(w)).is_file()\n    ]\n    content_str = _create_index_content(cached_words)\n    html_string = HTML_TEMPLATE.replace(\"{% word %}\", \"Index\")\n    html_string = html_string.replace(\"{% content %}\", content_str)\n    filename = data_dir.joinpath(\"index.html\")\n    save_file(filename, html_string, mk_parents=True)",
    "docstring": "Create index file of cached translations.\n\n    Parameters\n    ----------\n    data_dir : pathlib.Path\n        Cache directory location."
  },
  {
    "code": "def _parseImageNtHeaders(self, data, imageDosHeader):\n        inth = self._classes.IMAGE_NT_HEADERS.from_buffer(data, imageDosHeader.header.e_lfanew)\n        if inth.Signature != b'PE':\n            raise BinaryError('No valid PE/COFF file')\n        return ImageNtHeaderData(header=inth)",
    "docstring": "Returns the ImageNtHeaders"
  },
  {
    "code": "def print_settings(settings, depth=0):\n    if isinstance(settings, Setting):\n        settings = [settings]\n    for setting in settings:\n        cur = setting.currentValue\n        print(\n            \"%s* %s (%s, value: %s, type: %s)\"\n            % (\n                \" \" * depth,\n                setting.title,\n                setting.target,\n                click.style(cur, bold=True),\n                setting.type,\n            )\n        )\n        for opt in setting.candidate:\n            if not opt.isAvailable:\n                logging.debug(\"Unavailable setting %s\", opt)\n                continue\n            click.echo(\n                click.style(\n                    \"%s  - %s (%s)\" % (\" \" * depth, opt.title, opt.value),\n                    bold=opt.value == cur,\n                )\n            )",
    "docstring": "Print all available settings of the device."
  },
  {
    "code": "def add_screenshot(self, screenshot):\n        if screenshot in self.screenshots:\n            return\n        self.screenshots.append(screenshot)",
    "docstring": "Add a screenshot object if it does not already exist"
  },
  {
    "code": "def get_python_path(venv_path):\n    bin_path = get_bin_path(venv_path)\n    program_path = os.path.join(bin_path, 'python')\n    if sys.platform.startswith('win'):\n        program_path = program_path + '.exe'\n    return program_path",
    "docstring": "Get given virtual environment's `python` program path.\n\n    :param venv_path: Virtual environment directory path.\n\n    :return: `python` program path."
  },
  {
    "code": "def execute_sql(self, query):\n        c = self.con.cursor()\n        c.execute(query)\n        result = []\n        if c.rowcount > 0:\n            try:\n                result = c.fetchall()\n            except psycopg2.ProgrammingError:\n                pass\n        return result",
    "docstring": "Executes a given query string on an open postgres database."
  },
  {
    "code": "def minimise_tables(routing_tables, target_lengths,\n                    methods=(remove_default_entries, ordered_covering)):\n    if not isinstance(target_lengths, dict):\n        lengths = collections.defaultdict(lambda: target_lengths)\n    else:\n        lengths = target_lengths\n    new_tables = dict()\n    for chip, table in iteritems(routing_tables):\n        try:\n            new_table = minimise_table(table, lengths[chip], methods)\n        except MinimisationFailedError as exc:\n            exc.chip = chip\n            raise\n        if new_table:\n            new_tables[chip] = new_table\n    return new_tables",
    "docstring": "Utility function which attempts to minimises routing tables for multiple\n    chips.\n\n    For each routing table supplied, this function will attempt to use the\n    minimisation algorithms given (or some sensible default algorithms), trying\n    each sequentially until a target number of routing entries has been\n    reached.\n\n    Parameters\n    ----------\n    routing_tables : {(x, y): [\\\n            :py:class:`~rig.routing_table.RoutingTableEntry`, ...], ...}\n        Dictionary mapping chip co-ordinates to the routing tables associated\n        with that chip. NOTE: This is the data structure as returned by\n        :py:meth:`~rig.routing_table.routing_tree_to_tables`.\n    target_lengths : int or {(x, y): int or None, ...} or None\n        Maximum length of routing tables. If an integer this is assumed to be\n        the maximum length for any table; if a dictionary then it is assumed to\n        be a mapping from co-ordinate to maximum length (or None); if None then\n        tables will be minimised as far as possible.\n    methods :\n        Each method is tried in the order presented and the first to meet the\n        required target length for a given chip is used. Consequently less\n        computationally costly algorithms should be nearer the start of the\n        list. The defaults will try to remove default routes\n        (:py:meth:`rig.routing_table.remove_default_routes.minimise`) and then\n        fall back on the ordered covering algorithm\n        (:py:meth:`rig.routing_table.ordered_covering.minimise`).\n\n    Returns\n    -------\n    {(x, y): [:py:class:`~rig.routing_table.RoutingTableEntry`, ...], ...}\n        Minimised routing tables, guaranteed to be at least as small as the\n        table sizes specified by `target_lengths`.\n\n    Raises\n    ------\n    MinimisationFailedError\n        If no method can sufficiently minimise a table."
  },
  {
    "code": "def AddFXrefRead(self, method, classobj, field):\n        if field not in self._fields:\n            self._fields[field] = FieldClassAnalysis(field)\n        self._fields[field].AddXrefRead(classobj, method)",
    "docstring": "Add a Field Read to this class\n\n        :param method:\n        :param classobj:\n        :param field:\n        :return:"
  },
  {
    "code": "def rescale_taps(taps):\n    taps = np.array(taps)\n    cs = sum(taps)\n    for (i, x) in enumerate(taps):\n        taps[i] = x / cs\n    return taps.tolist()",
    "docstring": "Rescale taps in that way that their sum equals 1"
  },
  {
    "code": "def handle_simulation_end(self, data_portal):\n        log.info(\n            'Simulated {} trading days\\n'\n            'first open: {}\\n'\n            'last close: {}',\n            self._session_count,\n            self._trading_calendar.session_open(self._first_session),\n            self._trading_calendar.session_close(self._last_session),\n        )\n        packet = {}\n        self.end_of_simulation(\n            packet,\n            self._ledger,\n            self._trading_calendar,\n            self._sessions,\n            data_portal,\n            self._benchmark_source,\n        )\n        return packet",
    "docstring": "When the simulation is complete, run the full period risk report\n        and send it out on the results socket."
  },
  {
    "code": "def recarray_to_hdf5_group(ra, parent, name, **kwargs):\n    import h5py\n    h5f = None\n    if isinstance(parent, str):\n        h5f = h5py.File(parent, mode='a')\n        parent = h5f\n    try:\n        h5g = parent.require_group(name)\n        for n in ra.dtype.names:\n            array_to_hdf5(ra[n], h5g, n, **kwargs)\n        return h5g\n    finally:\n        if h5f is not None:\n            h5f.close()",
    "docstring": "Write each column in a recarray to a dataset in an HDF5 group.\n\n    Parameters\n    ----------\n    ra : recarray\n        Numpy recarray to store.\n    parent : string or h5py group\n        Parent HDF5 file or group. If a string, will be treated as HDF5 file\n        name.\n    name : string\n        Name or path of group to write data into.\n    kwargs : keyword arguments\n        Passed through to h5py require_dataset() function.\n\n    Returns\n    -------\n    h5g : h5py group"
  },
  {
    "code": "def get_subject_without_validation(jwt_bu64):\n    try:\n        jwt_dict = get_jwt_dict(jwt_bu64)\n    except JwtException as e:\n        return log_jwt_bu64_info(logging.error, str(e), jwt_bu64)\n    try:\n        return jwt_dict['sub']\n    except LookupError:\n        log_jwt_dict_info(logging.error, 'Missing \"sub\" key', jwt_dict)",
    "docstring": "Extract subject from the JWT without validating the JWT.\n\n    - The extracted subject cannot be trusted for authn or authz.\n\n    Args:\n      jwt_bu64: bytes\n        JWT, encoded using a a URL safe flavor of Base64.\n\n    Returns:\n      str: The subject contained in the JWT."
  },
  {
    "code": "def update_total(self, n=1):\n    with self._lock:\n      self._pbar.total += n\n      self.refresh()",
    "docstring": "Increment total pbar value."
  },
  {
    "code": "def find_and_refine_peaks(self, threshold, min_separation=1.0,\n                              use_cumul=False):\n        if use_cumul:\n            theMap = self._ts_cumul\n        else:\n            theMap = self._tsmap\n        peaks = find_peaks(theMap, threshold, min_separation)\n        for peak in peaks:\n            o, skydir = fit_error_ellipse(theMap, (peak['ix'], peak['iy']),\n                                          dpix=2)\n            peak['fit_loc'] = o\n            peak['fit_skydir'] = skydir\n            if o['fit_success']:\n                skydir = peak['fit_skydir']\n            else:\n                skydir = peak['skydir']\n        return peaks",
    "docstring": "Run a simple peak-finding algorithm, and fit the peaks to\n        paraboloids to extract their positions and error ellipses.\n\n        Parameters\n        ----------\n        threshold : float\n            Peak threshold in TS.\n\n        min_separation : float\n            Radius of region size in degrees.  Sets the minimum allowable\n            separation between peaks.\n\n        use_cumul : bool\n            If true, used the cumulative TS map (i.e., the TS summed\n            over the energy bins) instead of the TS Map from the fit\n            to and index=2 powerlaw.\n\n        Returns\n        -------\n        peaks    : list\n            List of dictionaries containing the location and amplitude of\n            each peak.  Output of `~fermipy.sourcefind.find_peaks`"
  },
  {
    "code": "def style_print(*values, **kwargs):\n    style = kwargs.pop(\"style\", None)\n    values = [style_format(value, style) for value in values]\n    print(*values, **kwargs)",
    "docstring": "A convenience function that applies style_format to text before printing"
  },
  {
    "code": "def convertstatsmethod(method_str):\n        if StringClass.string_match(method_str, 'Average'):\n            return 'ave'\n        elif StringClass.string_match(method_str, 'Maximum'):\n            return 'max'\n        elif StringClass.string_match(method_str, 'Minimum'):\n            return 'min'\n        elif method_str.lower() in ['ave', 'max', 'min']:\n            return method_str.lower()\n        else:\n            return 'ave'",
    "docstring": "Convert statistics method to ave, min, and max."
  },
  {
    "code": "def template(self):\n        if self._template:\n            return self._template\n        template_json = self.read_template(self.args.tmplname)\n        self._template = loads(template_json)\n        return self._template",
    "docstring": "Returns the template in JSON form"
  },
  {
    "code": "def enum_choice_list(data):\n    if not data:\n        return {}\n    try:\n        choices = [x.value for x in data]\n    except AttributeError:\n        choices = data\n    def _type(value):\n        return next((x for x in choices if x.lower() == value.lower()), value) if value else value\n    params = {\n        'choices': CaseInsensitiveList(choices),\n        'type': _type\n    }\n    return params",
    "docstring": "Creates the argparse choices and type kwargs for a supplied enum type or list of strings"
  },
  {
    "code": "def _register_update(self, method='isel', replot=False, dims={}, fmt={},\n                         force=False, todefault=False):\n        ArrayList._register_update(self, method=method, dims=dims)\n        InteractiveBase._register_update(self, fmt=fmt, todefault=todefault,\n                                         replot=bool(dims) or replot,\n                                         force=force)",
    "docstring": "Register new dimensions and formatoptions for updating\n\n        Parameters\n        ----------\n        %(InteractiveArray._register_update.parameters)s"
  },
  {
    "code": "async def turn_on(self, switch=None):\n        if switch is not None:\n            switch = codecs.decode(switch.rjust(2, '0'), 'hex')\n            packet = self.protocol.format_packet(b\"\\x10\" + switch + b\"\\x01\")\n        else:\n            packet = self.protocol.format_packet(b\"\\x0a\")\n        states = await self._send(packet)\n        return states",
    "docstring": "Turn on relay."
  },
  {
    "code": "def valid_conkey(self, conkey):\n        for prefix in _COND_PREFIXES:\n            trailing = conkey.lstrip(prefix)\n            if trailing == '' and conkey:\n                return True\n            try:\n                int(trailing)\n                return True\n            except ValueError:\n                pass\n        return False",
    "docstring": "Check that the conkey is a valid one. Return True if valid. A\n        condition key is valid if it is one in the _COND_PREFIXES\n        list. With the prefix removed, the remaining string must be\n        either a number or the empty string."
  },
  {
    "code": "def Expand(self, macro_ref_str):\n    match = _MACRO_RE.match(macro_ref_str)\n    if match is None or match.group(0) != macro_ref_str:\n      raise PDDMError('Failed to parse macro reference: \"%s\"' % macro_ref_str)\n    if match.group('name') not in self._macros:\n      raise PDDMError('No macro named \"%s\".' % match.group('name'))\n    return self._Expand(match, [], macro_ref_str)",
    "docstring": "Expands the macro reference.\n\n    Args:\n      macro_ref_str: String of a macro reference (i.e. foo(a, b)).\n\n    Returns:\n      The text from the expansion.\n\n    Raises:\n      PDDMError if there are any issues."
  },
  {
    "code": "def _print_registers(self, registers):\n        for reg, value in registers.items():\n            print(\"    %s : 0x%08x (%d)\" % (reg, value, value))",
    "docstring": "Print registers."
  },
  {
    "code": "def ctime(self, timezone=None):\n        if timezone is None:\n            timezone = self.timezone\n        return time.ctime(self.__timestamp__ - timezone)",
    "docstring": "Returns a ctime string.\n\n        :param timezone = self.timezone\n            The timezone (in seconds west of UTC) to return the value in. By\n            default, the timezone used when constructing the class is used\n            (local one by default). To use UTC, use timezone = 0. To use the\n            local tz, use timezone = chronyk.LOCALTZ."
  },
  {
    "code": "def param(self, name, default=None):\n        if not name in self.params:\n            return default\n        return self.params[name]",
    "docstring": "convenient function for returning an arbitrary MAVLink\n           parameter with a default"
  },
  {
    "code": "async def add(self, setname, ip, timeout=0):\n        args = ['add', '-exist', setname, ip, 'timeout', timeout]\n        return await self.start(__class__.CMD, *args)",
    "docstring": "Adds the given IP address to the given ipset.\n        \n        If a timeout is given, the IP will stay in the ipset for\n        the given duration. Else it's added forever.\n\n        The resulting command looks like this:\n\n        ``ipset add -exist ellis_blacklist4 192.0.2.10 timeout 14400``"
  },
  {
    "code": "def _pre_train(self,\n                   stop_param_updates,\n                   num_epochs,\n                   updates_epoch):\n        updates = {k: stop_param_updates.get(k, num_epochs) * updates_epoch\n                   for k, v in self.params.items()}\n        single_steps = {k: np.exp(-((1.0 - (1.0 / v)))\n                        * self.params[k]['factor'])\n                        for k, v in updates.items()}\n        constants = {k: np.exp(-self.params[k]['factor']) / v\n                     for k, v in single_steps.items()}\n        return constants",
    "docstring": "Set parameters and constants before training."
  },
  {
    "code": "def index_all_layers(self):\n    from hypermap.aggregator.models import Layer\n    if not settings.REGISTRY_SKIP_CELERY:\n        layers_cache = set(Layer.objects.filter(is_valid=True).values_list('id', flat=True))\n        deleted_layers_cache = set(Layer.objects.filter(is_valid=False).values_list('id', flat=True))\n        cache.set('layers', layers_cache)\n        cache.set('deleted_layers', deleted_layers_cache)\n    else:\n        for layer in Layer.objects.all():\n            index_layer(layer.id)",
    "docstring": "Index all layers in search engine."
  },
  {
    "code": "def load_from_file(cls, file_path):\n        data = None\n        if os.path.exists(file_path):\n            metadata_file = open(file_path)\n            data = json.loads(metadata_file.read())\n        return cls(initial=data)",
    "docstring": "Load the meta data given a file_path or empty meta data"
  },
  {
    "code": "def data_to_unicode(self, data):\n        if isinstance(data, dict):\n            return {self.to_unicode(k): self.to_unicode(v) for k, v in data.iteritems()}\n        if isinstance(data, list):\n            return [self.to_unicode(l) for l in data]\n        else:\n            return self.to_unicode(data)",
    "docstring": "Recursively convert a list or dictionary to unicode.\n\n        Args:\n            data: The data to be unicoded.\n\n        Returns:\n            Unicoded data."
  },
  {
    "code": "def get_fields(self):\n        columns = self.columns\n        model = self.model\n        fields = []\n        for col in columns:\n            if isinstance(col, (str, unicode)):\n                v = col.split('.')\n                if len(v) > 1:\n                    field = get_model(v[0], engine_name=self.model.get_engine_name(),\n                                      signal=False).properties(v[1])\n                else:\n                    field = model.properties[col]\n            elif isinstance(col, Column):\n                field = get_model(col.table.name, engine_name=self.model.get_engine_name(),\n                                  signal=False).properties[col.name]\n            else:\n                field = col\n            fields.append(field)\n        return fields",
    "docstring": "get property instance according self.columns"
  },
  {
    "code": "def _convert_args(handler, args):\n    args = list(args)\n    params = inspect.signature(handler).parameters\n    for i, (arg, name) in enumerate(zip(args, params)):\n        default = params[name].default\n        annotation = params[name].annotation\n        if annotation != inspect.Parameter.empty:\n            if isinstance(annotation, type) and annotation != str:\n                args[i] = annotation(arg)\n        elif default != inspect.Parameter.empty:\n            if default is not None and not isinstance(default, str):\n                args[i] = type(default)(arg)\n    return args",
    "docstring": "Convert a list of command arguments to types specified by the handler.\n\n    Args:\n      handler: a command handler function.\n      args: the list of string arguments to pass to handler.\n\n    Returns:\n      A new list containing `args` that have been converted to the expected type\n      for `handler`. For each function parameter of `handler` that has either an\n      explicit type annotation or a non-None default value, the corresponding\n      element in `args` is converted to that type."
  },
  {
    "code": "def nb_ll(data, P, R):\n    genes, cells = data.shape\n    clusters = P.shape[1]\n    lls = np.zeros((cells, clusters))\n    for c in range(clusters):\n        P_c = P[:,c].reshape((genes, 1))\n        R_c = R[:,c].reshape((genes, 1))\n        ll = gammaln(R_c + data) - gammaln(R_c)\n        ll += data*np.log(P_c) + xlog1py(R_c, -P_c)\n        lls[:,c] = ll.sum(0)\n    return lls",
    "docstring": "Returns the negative binomial log-likelihood of the data.\n\n    Args:\n        data (array): genes x cells\n        P (array): NB success probability param - genes x clusters\n        R (array): NB stopping param - genes x clusters\n\n    Returns:\n        cells x clusters array of log-likelihoods"
  },
  {
    "code": "def transform_df(self, df):\n        if (len(df) == 0) or (len(self) == 0):\n            return df\n        for sc in self:\n            df = sc.transform_df(df)\n        return df",
    "docstring": "Transform values in a dataframe.\n\n        Returns dataframe"
  },
  {
    "code": "def read_yaml(filename, add_constructor=None):\n    y = read_file(filename)\n    if add_constructor:\n        if not isinstance(add_constructor, list):\n            add_constructor = [add_constructor]\n        for a in add_constructor:\n            _yaml.add_constructor(*a)\n    if y:\n        return _yaml.load(y)",
    "docstring": "Reads YAML files\n\n    :param filename:\n        The full path to the YAML file\n    :param add_constructor:\n        A list of yaml constructors (loaders)\n    :returns:\n        Loaded YAML content as represented data structure\n\n    .. seealso::\n        :func:`util.structures.yaml_str_join`,\n        :func:`util.structures.yaml_loc_join`"
  },
  {
    "code": "def multi_platform_open(cmd):\n    if platform == \"linux\" or platform == \"linux2\":\n        cmd = ['xdg-open', cmd]\n    elif platform == \"darwin\":\n        cmd = ['open', cmd]\n    elif platform == \"win32\":\n        cmd = ['start', cmd]\n    subprocess.check_call(cmd)",
    "docstring": "Take the given command and use the OS to automatically open the appropriate\n    resource.  For instance, if a URL is provided, this will have the OS automatically\n    open the URL in the default web browser."
  },
  {
    "code": "def RtlGetVersion(os_version_info_struct):\n  rc = ctypes.windll.Ntdll.RtlGetVersion(ctypes.byref(os_version_info_struct))\n  if rc != 0:\n    raise OSError(\"Getting Windows version failed.\")",
    "docstring": "Wraps the lowlevel RtlGetVersion routine.\n\n  Args:\n    os_version_info_struct: instance of either a RTL_OSVERSIONINFOW structure\n                            or a RTL_OSVERSIONINFOEXW structure,\n                            ctypes.Structure-wrapped, with the\n                            dwOSVersionInfoSize field preset to\n                            ctypes.sizeof(self).\n\n  Raises:\n    OSError: if the underlaying routine fails.\n\n  See: https://msdn.microsoft.com/en-us/library/\n  windows/hardware/ff561910(v=vs.85).aspx ."
  },
  {
    "code": "def get_datasource(self, source_id, datasource_id):\n        target_url = self.client.get_url('DATASOURCE', 'GET', 'single', {'source_id': source_id, 'datasource_id': datasource_id})\n        return self.client.get_manager(Datasource)._get(target_url)",
    "docstring": "Get a Datasource object\n\n        :rtype: Datasource"
  },
  {
    "code": "def get_config(self, config_name, require_ready=True):\n        if require_ready:\n            self.bots.check_configs_ready()\n        else:\n            self.bots.check_bots_ready()\n        return self.configs.get(config_name.lower(), {})",
    "docstring": "Return the config with the given case-insensitive config_name.\n        Raise LookupError if no config exists with this name."
  },
  {
    "code": "def prod(x, axis=None, keepdims=False):\n    from .function_bases import prod as prod_base\n    if axis is None:\n        axis = range(x.ndim)\n    elif not hasattr(axis, '__iter__'):\n        axis = [axis]\n    return prod_base(x, axis, keepdims)",
    "docstring": "Reduction along axes with product operation.\n\n    Args:\n        x (Variable): An input variable.\n        axis (None, int or tuple of ints): Axis or axes along which product is\n            calculated. Passing the default value `None` will reduce all dimensions.\n        keepdims (bool): Flag whether the reduced axes are kept as a dimension with 1 element.\n\n    Returns:\n        ~nnabla.Variable: N-D array.\n\n    Note:\n        Backward computation is not accurate in a zero value input."
  },
  {
    "code": "def reassign_label(cls, destination_cluster, label):\n        conn = Qubole.agent(version=Cluster.api_version)\n        data = {\n                    \"destination_cluster\": destination_cluster,\n                    \"label\": label\n                }\n        return conn.put(cls.rest_entity_path + \"/reassign-label\", data)",
    "docstring": "Reassign a label from one cluster to another.\n\n        Args:\n            `destination_cluster`: id/label of the cluster to move the label to\n\n            `label`: label to be moved from the source cluster"
  },
  {
    "code": "def _add_parameter(self_, param_name,param_obj):\n        cls = self_.cls\n        type.__setattr__(cls,param_name,param_obj)\n        ParameterizedMetaclass._initialize_parameter(cls,param_name,param_obj)\n        try:\n            delattr(cls,'_%s__params'%cls.__name__)\n        except AttributeError:\n            pass",
    "docstring": "Add a new Parameter object into this object's class.\n\n        Supposed to result in a Parameter equivalent to one declared\n        in the class's source code."
  },
  {
    "code": "def logged_user(request):\n    dct = cookie_facade.retrive_cookie_data(request, USER_COOKIE_NAME).execute().result\n    if dct is None:\n        return Command()\n    return NodeSearch(dct['id'])",
    "docstring": "Returns a command that retrieves the current logged user based on secure cookie\n    If there is no logged user, the result from command is None"
  },
  {
    "code": "def get_slugignores(root, fname='.slugignore'):\n    try:\n        with open(os.path.join(root, fname)) as f:\n            return [l.rstrip('\\n') for l in f]\n    except IOError:\n        return []",
    "docstring": "Given a root path, read any .slugignore file inside and return a list of\n    patterns that should be removed prior to slug compilation.\n\n    Return empty list if file does not exist."
  },
  {
    "code": "async def _go_through_packets_from_fd(self, fd, packet_callback, packet_count=None):\n        packets_captured = 0\n        self._log.debug('Starting to go through packets')\n        psml_struct, data = await self._get_psml_struct(fd)\n        while True:\n            try:\n                packet, data = await self._get_packet_from_stream(fd, data, got_first_packet=packets_captured > 0,\n                                                                  psml_structure=psml_struct)\n            except EOFError:\n                self._log.debug('EOF reached')\n                break\n            if packet:\n                packets_captured += 1\n                try:\n                    packet_callback(packet)\n                except StopCapture:\n                    self._log.debug('User-initiated capture stop in callback')\n                    break\n            if packet_count and packets_captured >= packet_count:\n                break",
    "docstring": "A coroutine which goes through a stream and calls a given callback for each XML packet seen in it."
  },
  {
    "code": "def write_object(ctx, pin, management_key, object_id, data):\n    controller = ctx.obj['controller']\n    _ensure_authenticated(ctx, controller, pin, management_key)\n    def do_write_object(retry=True):\n        try:\n            controller.put_data(object_id, data.read())\n        except APDUError as e:\n            logger.debug('Failed writing object', exc_info=e)\n            if e.sw == SW.INCORRECT_PARAMETERS:\n                ctx.fail('Something went wrong, is the object id valid?')\n            raise\n    do_write_object()",
    "docstring": "Write an arbitrary PIV object.\n\n    Write a PIV object by providing the object id.\n    Yubico writable PIV objects are available in\n    the range 5f0000 - 5fffff.\n\n    \\b\n    OBJECT-ID       Id of PIV object in HEX.\n    DATA            File containing the data to be written. Use '-' to use stdin."
  },
  {
    "code": "def prune_builds(self):\n        url = self._url(\"/build/prune\")\n        return self._result(self._post(url), True)",
    "docstring": "Delete the builder cache\n\n        Returns:\n            (dict): A dictionary containing information about the operation's\n                    result. The ``SpaceReclaimed`` key indicates the amount of\n                    bytes of disk space reclaimed.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def to_binary_string(self):\n        timestamp = datetime_to_timestamp(self.when)\n        token = binascii.unhexlify(self.token)\n        return struct.pack(self.FORMAT_PREFIX + '{0}s'.format(len(token)),\n                           timestamp, len(token), token)",
    "docstring": "Pack the feedback to binary form and return it as string."
  },
  {
    "code": "def EnumerateInterfacesFromClient(args):\n  del args\n  pythoncom.CoInitialize()\n  for interface in (wmi.WMI().Win32_NetworkAdapterConfiguration() or []):\n    addresses = []\n    for ip_address in interface.IPAddress or []:\n      addresses.append(\n          rdf_client_network.NetworkAddress(human_readable_address=ip_address))\n    response = rdf_client_network.Interface(ifname=interface.Description)\n    if interface.MACAddress:\n      response.mac_address = binascii.unhexlify(\n          interface.MACAddress.replace(\":\", \"\"))\n    if addresses:\n      response.addresses = addresses\n    yield response",
    "docstring": "Enumerate all MAC addresses of all NICs.\n\n  Args:\n    args: Unused.\n\n  Yields:\n    `rdf_client_network.Interface` instances."
  },
  {
    "code": "def remove(self, email):\n        if email in self._collaborators:\n            if self._collaborators[email] == ShareRequestValue.Add:\n                del self._collaborators[email]\n            else:\n                self._collaborators[email] = ShareRequestValue.Remove\n        self._dirty = True",
    "docstring": "Remove a Collaborator.\n\n        Args:\n            str : Collaborator email address."
  },
  {
    "code": "def ticks(\n            cls, request,\n            length: (Ptypes.path, Integer('Duration of the stream, in seconds.')),\n            style: (Ptypes.path, String('Tick style.', enum=['compact', 'extended']))\n        ) -> [\n            (200, 'Ok', TickStream),\n            (400, 'Invalid parameters')\n        ]:\n        try:\n            length = int(length)\n            style = cls._styles[style]\n        except (ValueError, KeyError):\n            Respond(400)\n        def vetinari_clock():\n            start = time()\n            while time() - start <= length:\n                sleep(randint(25, 400) / 100)\n                yield strftime(style, localtime())\n        Respond(200, vetinari_clock())",
    "docstring": "A streaming Lord Vetinari clock..."
  },
  {
    "code": "def _runUnrealBuildTool(self, target, platform, configuration, args, capture=False):\n\t\tplatform = self._transformBuildToolPlatform(platform)\n\t\targuments = [self.getBuildScript(), target, platform, configuration] + args\n\t\tif capture == True:\n\t\t\treturn Utility.capture(arguments, cwd=self.getEngineRoot(), raiseOnError=True)\n\t\telse:\n\t\t\tUtility.run(arguments, cwd=self.getEngineRoot(), raiseOnError=True)",
    "docstring": "Invokes UnrealBuildTool with the specified parameters"
  },
  {
    "code": "def filter(self, endpoint, params):\n        params = self.parse_params(params)\n        params = urlencode(params)\n        path = '{0}?{1}'.format(endpoint, params)\n        return self.get(path)",
    "docstring": "Makes a get request by construction\n        the path from an endpoint and a dict\n        with filter query params\n\n        e.g.\n        params = {'category__in': [1,2]}\n        response = self.client.filter('/experiences/', params)"
  },
  {
    "code": "def reply(self, text, markup=None, parse_mode=None):\n        if markup is None:\n            markup = {}\n        return self.send_text(\n            text,\n            reply_to_message_id=self.message[\"message_id\"],\n            disable_web_page_preview=\"true\",\n            reply_markup=self.bot.json_serialize(markup),\n            parse_mode=parse_mode,\n        )",
    "docstring": "Reply to the message this `Chat` object is based on.\n\n        :param str text: Text of the message to send\n        :param dict markup: Markup options\n        :param str parse_mode: Text parsing mode (``\"Markdown\"``, ``\"HTML\"`` or\n            ``None``)"
  },
  {
    "code": "def get_kafka_producer(acks='all',\n                       value_serializer=lambda v: json.dumps(v).encode('utf-8')):\n    producer = KafkaProducer(\n        bootstrap_servers=get_kafka_brokers(),\n        security_protocol='SSL',\n        ssl_context=get_kafka_ssl_context(),\n        value_serializer=value_serializer,\n        acks=acks\n    )\n    return producer",
    "docstring": "Return a KafkaProducer that uses the SSLContext created with create_ssl_context."
  },
  {
    "code": "def __dynamic_expected_value(self, y):\n        return self.model.predict(self.data, np.ones(self.data.shape[0]) * y, output=self.model_output).mean(0)",
    "docstring": "This computes the expected value conditioned on the given label value."
  },
  {
    "code": "def _set_focused_item(self, item):\n        if not item:\n            return self._del_focused_item()\n        if item.model is not self._selection.focus:\n            self.queue_draw_item(self._focused_item, item)\n            self._selection.focus = item.model\n            self.emit('focus-changed', item)",
    "docstring": "Sets the focus to the passed item"
  },
  {
    "code": "def _mm(n_items, data, initial_params, alpha, max_iter, tol, mm_fun):\n    if initial_params is None:\n        params = np.zeros(n_items)\n    else:\n        params = initial_params\n    converged = NormOfDifferenceTest(tol=tol, order=1)\n    for _ in range(max_iter):\n        nums, denoms = mm_fun(n_items, data, params)\n        params = log_transform((nums + alpha) / (denoms + alpha))\n        if converged(params):\n            return params\n    raise RuntimeError(\"Did not converge after {} iterations\".format(max_iter))",
    "docstring": "Iteratively refine MM estimates until convergence.\n\n    Raises\n    ------\n    RuntimeError\n        If the algorithm does not converge after `max_iter` iterations."
  },
  {
    "code": "def sanitize_release_group(string):\n    if string is None:\n        return\n    string = re.sub(r'\\[\\w+\\]', '', string)\n    return string.strip().upper()",
    "docstring": "Sanitize a `release_group` string to remove content in square brackets.\n\n    :param str string: the release group to sanitize.\n    :return: the sanitized release group.\n    :rtype: str"
  },
  {
    "code": "def available_metadata(self):\n        url = self.base_url + 'metadata/types'\n        headers = {'Authorization': 'Bearer {}'.format(self.auth())}\n        r = requests.get(url, headers=headers)\n        return pd.read_json(r.content, orient='records')['name']",
    "docstring": "List all scenario metadata indicators available in the connected\n        data source"
  },
  {
    "code": "def zobrist_hash(board: chess.Board, *, _hasher: Callable[[chess.Board], int] = ZobristHasher(POLYGLOT_RANDOM_ARRAY)) -> int:\n    return _hasher(board)",
    "docstring": "Calculates the Polyglot Zobrist hash of the position.\n\n    A Zobrist hash is an XOR of pseudo-random values picked from\n    an array. Which values are picked is decided by features of the\n    position, such as piece positions, castling rights and en passant\n    squares."
  },
  {
    "code": "def search_channels(self, query, limit=25, offset=0):\n        r = self.kraken_request('GET', 'search/channels',\n                                params={'query': query,\n                                        'limit': limit,\n                                        'offset': offset})\n        return models.Channel.wrap_search(r)",
    "docstring": "Search for channels and return them\n\n        :param query: the query string\n        :type query: :class:`str`\n        :param limit: maximum number of results\n        :type limit: :class:`int`\n        :param offset: offset for pagination\n        :type offset: :class:`int`\n        :returns: A list of channels\n        :rtype: :class:`list` of :class:`models.Channel` instances\n        :raises: None"
  },
  {
    "code": "def _dispatch_rpc(self, address, rpc_id, arg_payload):\n        if self.emulator.is_tile_busy(address):\n            self._track_change('device.rpc_busy_response', (address, rpc_id, arg_payload, None, None), formatter=format_rpc)\n            raise BusyRPCResponse()\n        try:\n            resp = super(EmulatedDevice, self).call_rpc(address, rpc_id, arg_payload)\n            self._track_change('device.rpc_sent', (address, rpc_id, arg_payload, resp, None), formatter=format_rpc)\n            return resp\n        except AsynchronousRPCResponse:\n            self._track_change('device.rpc_started', (address, rpc_id, arg_payload, None, None), formatter=format_rpc)\n            raise\n        except Exception as exc:\n            self._track_change('device.rpc_exception', (address, rpc_id, arg_payload, None, exc), formatter=format_rpc)\n            raise",
    "docstring": "Background work queue handler to dispatch RPCs."
  },
  {
    "code": "def format_check(settings):\n    valid_keys = ['logs_folder', 'log_file', 'log_console', 'log_name',\n                  'log_filename', 'keep_osm_tags']\n    for key in list(settings.keys()):\n        assert key in valid_keys, \\\n            ('{} not found in list of valid configuation keys').format(key)\n        assert isinstance(key, str), ('{} must be a string').format(key)\n        if key == 'keep_osm_tags':\n            assert isinstance(settings[key], list), \\\n                ('{} must be a list').format(key)\n            for value in settings[key]:\n                assert all(isinstance(element, str) for element in value), \\\n                    'all elements must be a string'\n        if key == 'log_file' or key == 'log_console':\n            assert isinstance(settings[key], bool), \\\n                ('{} must be boolean').format(key)",
    "docstring": "Check the format of a osmnet_config object.\n\n    Parameters\n    ----------\n    settings : dict\n        osmnet_config as a dictionary\n    Returns\n    -------\n    Nothing"
  },
  {
    "code": "def activate(self, experiment_key, user_id, attributes=None):\n    if not self.is_valid:\n      self.logger.error(enums.Errors.INVALID_DATAFILE.format('activate'))\n      return None\n    if not validator.is_non_empty_string(experiment_key):\n      self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('experiment_key'))\n      return None\n    if not isinstance(user_id, string_types):\n      self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('user_id'))\n      return None\n    variation_key = self.get_variation(experiment_key, user_id, attributes)\n    if not variation_key:\n      self.logger.info('Not activating user \"%s\".' % user_id)\n      return None\n    experiment = self.config.get_experiment_from_key(experiment_key)\n    variation = self.config.get_variation_from_key(experiment_key, variation_key)\n    self.logger.info('Activating user \"%s\" in experiment \"%s\".' % (user_id, experiment.key))\n    self._send_impression_event(experiment, variation, user_id, attributes)\n    return variation.key",
    "docstring": "Buckets visitor and sends impression event to Optimizely.\n\n    Args:\n      experiment_key: Experiment which needs to be activated.\n      user_id: ID for user.\n      attributes: Dict representing user attributes and values which need to be recorded.\n\n    Returns:\n      Variation key representing the variation the user will be bucketed in.\n      None if user is not in experiment or if experiment is not Running."
  },
  {
    "code": "def request(method, url, **kwargs):\n    _set_content_type(kwargs)\n    if _content_type_is_json(kwargs) and kwargs.get('data') is not None:\n        kwargs['data'] = dumps(kwargs['data'])\n    _log_request(method, url, kwargs)\n    response = requests.request(method, url, **kwargs)\n    _log_response(response)\n    return response",
    "docstring": "A wrapper for ``requests.request``."
  },
  {
    "code": "def _compute_value(self, pkt):\n        fld, fval = pkt.getfield_and_val(self._length_of)\n        val = fld.i2len(pkt, fval)\n        ret = self._adjust(val)\n        assert(ret >= 0)\n        return ret",
    "docstring": "Computes the value of this field based on the provided packet and\n        the length_of field and the adjust callback\n\n        @param packet.Packet pkt: the packet from which is computed this field value.  # noqa: E501\n        @return int: the computed value for this field.\n        @raise KeyError: the packet nor its payload do not contain an attribute\n          with the length_of name.\n        @raise AssertionError\n        @raise KeyError if _length_of is not one of pkt fields"
  },
  {
    "code": "def list_():\n    cmd = 'pkgutil --pkgs'\n    ret = salt.utils.mac_utils.execute_return_result(cmd)\n    return ret.splitlines()",
    "docstring": "List the installed packages.\n\n    :return: A list of installed packages\n    :rtype: list\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' pkgutil.list"
  },
  {
    "code": "def upload_file(self, file_name, file_path):\n        request = urllib.request.Request(self.url + '/rest/v1/data/upload/job_input?name=' + file_name)\n        if self.authorization_header() is not None:\n            request.add_header('Authorization', self.authorization_header())\n        request.add_header('User-Agent', 'GenePatternRest')\n        with open(file_path, 'rb') as f:\n            data = f.read()\n        try:\n            response = urllib.request.urlopen(request, data)\n        except IOError:\n            print(\"authentication failed\")\n            return None\n        if response.getcode() != 201:\n            print(\"file upload failed, status code = %i\" % response.getcode())\n            return None\n        return GPFile(self, response.info().get('Location'))",
    "docstring": "Upload a file to a server\n\n        Attempts to upload a local file with path filepath, to the server, where it\n        will be named filename.\n\n        Args:\n            :param file_name: The name that the uploaded file will be called on the server.\n            :param file_path: The path of the local file to upload.\n\n        Returns:\n            :return: A GPFile object that wraps the URI of the uploaded file, or None if the upload fails."
  },
  {
    "code": "def get_cpu_info():\n\timport json\n\toutput = get_cpu_info_json()\n\toutput = json.loads(output, object_hook = _utf_to_str)\n\treturn output",
    "docstring": "Returns the CPU info by using the best sources of information for your OS.\n\tReturns the result in a dict"
  },
  {
    "code": "def send(self):\n        xml_request = self.get_xml_request()\n        if(self.connection._debug == 1):\n            print(xml_request)\n        Debug.warn('-' * 25)\n        Debug.warn(self._command)\n        Debug.dump(\"doc: \\n\", self._documents)\n        Debug.dump(\"cont: \\n\", self._content)\n        Debug.dump(\"nest cont \\n\", self._nested_content)\n        Debug.dump(\"Request: \\n\", xml_request)\n        response = _handle_response(self.connection._send_request(xml_request),\n                                         self._command, self.connection.document_id_xpath)\n        return response",
    "docstring": "Send an XML string version of content through the connection.\n\n        Returns:\n            Response object."
  },
  {
    "code": "def get_decode_format(flags):\n    c_flags = flags & FMT_COMMON_MASK\n    l_flags = flags & FMT_LEGACY_MASK\n    if c_flags:\n        if c_flags not in COMMON_FORMATS:\n            return FMT_BYTES, False\n        else:\n            return COMMON2UNIFIED[c_flags], True\n    else:\n        if not l_flags in LEGACY_FORMATS:\n            return FMT_BYTES, False\n        else:\n            return LEGACY2UNIFIED[l_flags], True",
    "docstring": "Returns a tuple of format, recognized"
  },
  {
    "code": "async def _setcolor(self, *, color : discord.Colour):\n        data = self.bot.config.get(\"meta\", {})\n        data['default_color'] = str(color)\n        await self.bot.config.put('meta', data)\n        await self.bot.responses.basic(message=\"The default color has been updated.\")",
    "docstring": "Sets the default color of embeds."
  },
  {
    "code": "def refresh(self, *args, **kwargs):\n        result = self.fetch(*args, **kwargs)\n        self.store(self.key(*args, **kwargs), self.expiry(*args, **kwargs), result)\n        return result",
    "docstring": "Fetch the result SYNCHRONOUSLY and populate the cache"
  },
  {
    "code": "def _find_new_additions(self):\n        for node, in_degree in self.graph.in_degree_iter():\n            if not self._already_known(node) and in_degree == 0:\n                self.inner.put((self._scores[node], node))\n                self.queued.add(node)",
    "docstring": "Find any nodes in the graph that need to be added to the internal\n        queue and add them.\n\n        Callers must hold the lock."
  },
  {
    "code": "def start_at(self, start_at):\n        if start_at is None:\n            raise ValueError(\"Invalid value for `start_at`, must not be `None`\")\n        if len(start_at) < 1:\n            raise ValueError(\"Invalid value for `start_at`, length must be greater than or equal to `1`\")\n        self._start_at = start_at",
    "docstring": "Sets the start_at of this Shift.\n        RFC 3339; shifted to location timezone + offset. Precision up to the minute is respected; seconds are truncated.\n\n        :param start_at: The start_at of this Shift.\n        :type: str"
  },
  {
    "code": "def _num_taylor_coefficients(n):\n    _assert(n < 193, 'Number of derivatives too large.  Must be less than 193')\n    correction = np.array([0, 0, 1, 3, 4, 7])[_get_logn(n)]\n    log2n = _get_logn(n - correction)\n    m = 2 ** (log2n + 3)\n    return m",
    "docstring": "Return number of taylor coefficients\n\n    Parameters\n    ----------\n    n : scalar integer\n        Wanted number of taylor coefficients\n\n    Returns\n    -------\n    m : scalar integer\n        Number of taylor coefficients calculated\n           8 if       n <= 6\n          16 if   6 < n <= 12\n          32 if  12 < n <= 25\n          64 if  25 < n <= 51\n         128 if  51 < n <= 103\n         256 if 103 < n <= 192"
  },
  {
    "code": "def delete(self, handle):\n        self._check_session()\n        self._rest.delete_request('objects', str(handle))",
    "docstring": "Delete the specified object.\n\n        Arguments:\n        handle -- Handle of object to delete."
  },
  {
    "code": "def amplify_gmfs(imts, vs30s, gmfs):\n    n = len(vs30s)\n    out = [amplify_ground_shaking(im.period, vs30s[i], gmfs[m * n + i])\n           for m, im in enumerate(imts) for i in range(n)]\n    return numpy.array(out)",
    "docstring": "Amplify the ground shaking depending on the vs30s"
  },
  {
    "code": "def flavor_create(self,\n                      name,\n                      flavor_id=0,\n                      ram=0,\n                      disk=0,\n                      vcpus=1,\n                      is_public=True):\n        nt_ks = self.compute_conn\n        nt_ks.flavors.create(\n            name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public\n        )\n        return {'name': name,\n                'id': flavor_id,\n                'ram': ram,\n                'disk': disk,\n                'vcpus': vcpus,\n                'is_public': is_public}",
    "docstring": "Create a flavor"
  },
  {
    "code": "def getDarkCurrentFunction(exposuretimes, imgs, **kwargs):\r\n    exposuretimes, imgs = getDarkCurrentAverages(exposuretimes, imgs)\r\n    offs, ascent, rmse = getLinearityFunction(exposuretimes, imgs, **kwargs)\r\n    return offs, ascent, rmse",
    "docstring": "get dark current function from given images and exposure times"
  },
  {
    "code": "def _maybe_download_corpora(tmp_dir):\n  mnli_filename = \"MNLI.zip\"\n  mnli_finalpath = os.path.join(tmp_dir, \"MNLI\")\n  if not tf.gfile.Exists(mnli_finalpath):\n    zip_filepath = generator_utils.maybe_download(\n        tmp_dir, mnli_filename, _MNLI_URL)\n    zip_ref = zipfile.ZipFile(zip_filepath, \"r\")\n    zip_ref.extractall(tmp_dir)\n    zip_ref.close()\n  return mnli_finalpath",
    "docstring": "Download corpora for multinli.\n\n  Args:\n    tmp_dir: a string\n  Returns:\n    a string"
  },
  {
    "code": "def deprecated (func):\n    def newfunc (*args, **kwargs):\n        warnings.warn(\"Call to deprecated function %s.\" % func.__name__,\n                      category=DeprecationWarning)\n        return func(*args, **kwargs)\n    return update_func_meta(newfunc, func)",
    "docstring": "A decorator which can be used to mark functions as deprecated.\n    It emits a warning when the function is called."
  },
  {
    "code": "def btc_make_p2sh_p2wsh_redeem_script( witness_script_hex ):\n    witness_script_hash = hashing.bin_sha256(witness_script_hex.decode('hex')).encode('hex')\n    redeem_script = btc_script_serialize(['0020' + witness_script_hash])\n    return redeem_script",
    "docstring": "Make the redeem script for a p2sh-p2wsh witness script"
  },
  {
    "code": "def get_type(t):\n    if isinstance(t, UserDefinedType):\n        if isinstance(t.type, Contract):\n            return 'address'\n    return str(t)",
    "docstring": "Convert a type to a str\n        If the instance is a Contract, return 'address' instead"
  },
  {
    "code": "def load_file_to_base64_str(f_path):\n    path = abs_path(f_path)\n    with io.open(path, 'rb') as f:\n        f_bytes = f.read()\n        base64_str = base64.b64encode(f_bytes).decode(\"utf-8\")\n        return base64_str",
    "docstring": "Loads the content of a file into a base64 string.\n\n    Args:\n        f_path: full path to the file including the file name.\n\n    Returns:\n        A base64 string representing the content of the file in utf-8 encoding."
  },
  {
    "code": "def on_remove(self, widget, data=None):\n        path_list = None\n        if self.view is not None:\n            model, path_list = self.tree_view.get_selection().get_selected_rows()\n        old_path = self.get_path()\n        models = [self.list_store[path][self.MODEL_STORAGE_ID] for path in path_list] if path_list else []\n        if models:\n            try:\n                self.remove_core_elements(models)\n            except AttributeError as e:\n                self._logger.warning(\"The respective core element of {1}.list_store couldn't be removed. -> {0}\"\n                                  \"\".format(e, self.__class__.__name__))\n            if len(self.list_store) > 0:\n                self.tree_view.set_cursor(min(old_path[0], len(self.list_store) - 1))\n            return True\n        else:\n            self._logger.warning(\"Please select an element to be removed.\")",
    "docstring": "Removes respective selected core elements and select the next one"
  },
  {
    "code": "def encompass(self, x):\n        self.validate_time_inversion()\n        x.validate_time_inversion()\n        return DateTimeRange(\n            start_datetime=min(self.start_datetime, x.start_datetime),\n            end_datetime=max(self.end_datetime, x.end_datetime),\n            start_time_format=self.start_time_format,\n            end_time_format=self.end_time_format,\n        )",
    "docstring": "Newly set a time range that encompasses\n        the input and the current time range.\n\n        :param DateTimeRange x:\n            Value to compute encompass with the current time range.\n\n        :Sample Code:\n            .. code:: python\n\n                from datetimerange import DateTimeRange\n                dtr0 = DateTimeRange(\"2015-03-22T10:00:00+0900\", \"2015-03-22T10:10:00+0900\")\n                dtr1 = DateTimeRange(\"2015-03-22T10:05:00+0900\", \"2015-03-22T10:15:00+0900\")\n                dtr0.encompass(dtr1)\n        :Output:\n            .. parsed-literal::\n\n                2015-03-22T10:00:00+0900 - 2015-03-22T10:15:00+0900"
  },
  {
    "code": "def complete_abstract_value(\n        self,\n        return_type: GraphQLAbstractType,\n        field_nodes: List[FieldNode],\n        info: GraphQLResolveInfo,\n        path: ResponsePath,\n        result: Any,\n    ) -> AwaitableOrValue[Any]:\n        resolve_type_fn = return_type.resolve_type or self.type_resolver\n        runtime_type = resolve_type_fn(result, info, return_type)\n        if isawaitable(runtime_type):\n            async def await_complete_object_value():\n                value = self.complete_object_value(\n                    self.ensure_valid_runtime_type(\n                        await runtime_type, return_type, field_nodes, info, result\n                    ),\n                    field_nodes,\n                    info,\n                    path,\n                    result,\n                )\n                if isawaitable(value):\n                    return await value\n                return value\n            return await_complete_object_value()\n        runtime_type = cast(Optional[Union[GraphQLObjectType, str]], runtime_type)\n        return self.complete_object_value(\n            self.ensure_valid_runtime_type(\n                runtime_type, return_type, field_nodes, info, result\n            ),\n            field_nodes,\n            info,\n            path,\n            result,\n        )",
    "docstring": "Complete an abstract value.\n\n        Complete a value of an abstract type by determining the runtime object type of\n        that value, then complete the value for that type."
  },
  {
    "code": "def role(self):\n        try:\n            self._role = c_char(\n                self.lib.iperf_get_test_role(self._test)\n            ).value.decode('utf-8')\n        except TypeError:\n            self._role = c_char(\n                chr(self.lib.iperf_get_test_role(self._test))\n            ).value.decode('utf-8')\n        return self._role",
    "docstring": "The iperf3 instance role\n\n        valid roles are 'c'=client and 's'=server\n\n        :rtype: 'c' or 's'"
  },
  {
    "code": "def do_list(self, args):\n        try:\n            resources = self.resource_manager.list_resources_info()\n        except Exception as e:\n            print(e)\n        else:\n            self.resources = []\n            for ndx, (resource_name, value) in enumerate(resources.items()):\n                if not args:\n                    print('({0:2d}) {1}'.format(ndx, resource_name))\n                    if value.alias:\n                        print('     alias: {}'.format(value.alias))\n                self.resources.append((resource_name, value.alias or None))",
    "docstring": "List all connected resources."
  },
  {
    "code": "def resolve_node_modules(self):\n        'import the modules specified in init'\n        if not self.resolved_node_modules:\n            try:\n                self.resolved_node_modules = [\n                    importlib.import_module(mod, self.node_package)\n                    for mod in self.node_modules\n                ]\n            except ImportError:\n                self.resolved_node_modules = []\n                raise\n        return self.resolved_node_modules",
    "docstring": "import the modules specified in init"
  },
  {
    "code": "def unlock(self):\n        if not unlockers.unlock(self, self._device.manufacturer):\n            raise errors.JLinkException('Failed to unlock device.')\n        return True",
    "docstring": "Unlocks the device connected to the J-Link.\n\n        Unlocking a device allows for access to read/writing memory, as well as\n        flash programming.\n\n        Note:\n          Unlock is not supported on all devices.\n\n        Supported Devices:\n          Kinetis\n\n        Returns:\n          ``True``.\n\n        Raises:\n          JLinkException: if the device fails to unlock."
  },
  {
    "code": "def get_email_confirmation_redirect_url(self, request):\n        if request.user.is_authenticated:\n            if app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL:\n                return  \\\n                    app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL\n            else:\n                return self.get_login_redirect_url(request)\n        else:\n            return app_settings.EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL",
    "docstring": "The URL to return to after successful e-mail confirmation."
  },
  {
    "code": "def memo_Y(f):\n    sub = {}\n    def Yf(*args):\n        hashable_args = tuple([repr(x) for x in args])\n        if args:\n            if hashable_args not in sub:\n                ret = sub[hashable_args] = f(Yf)(*args)\n            else:\n                ret = sub[hashable_args]\n            return ret\n        return f(Yf)()\n    return f(Yf)",
    "docstring": "Memoized Y combinator.\n\n    .. testsetup::\n\n        from proso.func import memo_Y\n\n    .. testcode::\n\n        @memo_Y\n        def fib(f):\n            def inner_fib(n):\n                if n > 1:\n                    return f(n - 1) + f(n - 2)\n                else:\n                    return n\n            return inner_fib\n\n        print(fib(100))\n\n    .. testoutput::\n\n        354224848179261915075"
  },
  {
    "code": "def _seqcluster_stats(data, out_dir):\n    name = dd.get_sample_name(data)\n    fn = data.get(\"seqcluster\", {}).get(\"stat_file\", None)\n    if not fn:\n        return None\n    out_file = os.path.join(out_dir, \"%s.txt\" % name)\n    df = pd.read_csv(fn, sep=\"\\t\", names = [\"reads\", \"sample\", \"type\"])\n    df_sample = df[df[\"sample\"] == name]\n    df_sample.to_csv(out_file, sep=\"\\t\")\n    return out_file",
    "docstring": "Parse seqcluster output"
  },
  {
    "code": "def load_state_dict(self, state_dict: Dict[str, Any]) -> None:\n        self.__dict__.update(state_dict)",
    "docstring": "Load the schedulers state.\n\n        Parameters\n        ----------\n        state_dict : ``Dict[str, Any]``\n            Scheduler state. Should be an object returned from a call to ``state_dict``."
  },
  {
    "code": "def to_string(self):\n        node = quote_if_necessary(self.obj_dict['name'])\n        node_attr = list()\n        for attr in sorted(self.obj_dict['attributes']):\n            value = self.obj_dict['attributes'][attr]\n            if value == '':\n                value = '\"\"'\n            if value is not None:\n                node_attr.append(\n                    '%s=%s' % (attr, quote_if_necessary(value) ) )\n            else:\n                node_attr.append( attr )\n        if node in ('graph', 'node', 'edge') and len(node_attr) == 0:\n            return ''\n        node_attr = ', '.join(node_attr)\n        if node_attr:\n            node += ' [' + node_attr + ']'\n        return node + ';'",
    "docstring": "Return string representation of node in DOT language."
  },
  {
    "code": "def extract_endpoint_arguments(endpoint):\n    ep_args = endpoint._arguments\n    if ep_args is None:\n        return None\n    arg_docs = { k: format_endpoint_argument_doc(a) \\\n            for k, a in ep_args.iteritems() }\n    return arg_docs",
    "docstring": "Extract the argument documentation from the endpoint."
  },
  {
    "code": "def remove_attribute(self, attribute: str) -> None:\n        attr_index = self.__attr_index(attribute)\n        if attr_index is not None:\n            self.yaml_node.value.pop(attr_index)",
    "docstring": "Remove an attribute from the node.\n\n        Use only if is_mapping() returns True.\n\n        Args:\n            attribute: The name of the attribute to remove."
  },
  {
    "code": "def relabel(self, qubits: Qubits) -> 'Gate':\n        gate = copy(self)\n        gate.vec = gate.vec.relabel(qubits)\n        return gate",
    "docstring": "Return a copy of this Gate with new qubits"
  },
  {
    "code": "def run_restore(self, snapshot: Dict[Union[str, Key], Any]) -> 'BaseItemCollection':\n        try:\n            for name, snap in snapshot.items():\n                if isinstance(name, Key):\n                    self._nested_items[name.group].run_restore(snap)\n                else:\n                    self._nested_items[name].run_restore(snap)\n            return self\n        except Exception as e:\n            raise SnapshotError('Error while restoring snapshot: {}'.format(self._snapshot)) from e",
    "docstring": "Restores the state of a collection from a snapshot"
  },
  {
    "code": "def window(preceding=None, following=None, group_by=None, order_by=None):\n    return Window(\n        preceding=preceding,\n        following=following,\n        group_by=group_by,\n        order_by=order_by,\n        how='rows',\n    )",
    "docstring": "Create a window clause for use with window functions.\n\n    This ROW window clause aggregates adjacent rows based on differences in row\n    number.\n\n    All window frames / ranges are inclusive.\n\n    Parameters\n    ----------\n    preceding : int, tuple, or None, default None\n        Specify None for unbounded, 0 to include current row tuple for\n        off-center window\n    following : int, tuple, or None, default None\n        Specify None for unbounded, 0 to include current row tuple for\n        off-center window\n    group_by : expressions, default None\n        Either specify here or with TableExpr.group_by\n    order_by : expressions, default None\n        For analytic functions requiring an ordering, specify here, or let Ibis\n        determine the default ordering (for functions like rank)\n\n    Returns\n    -------\n    Window"
  },
  {
    "code": "def from_file(self, vasprun_file):\n        vrun_obj = Vasprun(vasprun_file, parse_projected_eigen=True)\n        return VasprunLoader(vrun_obj)",
    "docstring": "Get a vasprun.xml file and return a VasprunLoader"
  },
  {
    "code": "def tmp_expr(self, tmp):\n        self.state._inspect('tmp_read', BP_BEFORE, tmp_read_num=tmp)\n        try:\n            v = self.temps[tmp]\n            if v is None:\n                raise SimValueError('VEX temp variable %d does not exist. This is usually the result of an incorrect '\n                                    'slicing.' % tmp)\n        except IndexError:\n            raise SimValueError(\"Accessing a temp that is illegal in this tyenv\")\n        self.state._inspect('tmp_read', BP_AFTER, tmp_read_expr=v)\n        return v",
    "docstring": "Returns the Claripy expression of a VEX temp value.\n\n        :param tmp: the number of the tmp\n        :param simplify: simplify the tmp before returning it\n        :returns: a Claripy expression of the tmp"
  },
  {
    "code": "def set(self, language: str, value: str):\n        self[language] = value\n        self.__dict__.update(self)\n        return self",
    "docstring": "Sets the value in the specified language.\n\n        Arguments:\n            language:\n                The language to set the value in.\n\n            value:\n                The value to set."
  },
  {
    "code": "def check_conflicts(self):\n\t\tshutit_global.shutit_global_object.yield_to_draw()\n\t\tcfg = self.cfg\n\t\tself.log('PHASE: conflicts', level=logging.DEBUG)\n\t\terrs = []\n\t\tself.pause_point('\\nNow checking for conflicts between modules', print_input=False, level=3)\n\t\tfor module_id in self.module_ids():\n\t\t\tif not cfg[module_id]['shutit.core.module.build']:\n\t\t\t\tcontinue\n\t\t\tconflicter = self.shutit_map[module_id]\n\t\t\tfor conflictee in conflicter.conflicts_with:\n\t\t\t\tconflictee_obj = self.shutit_map.get(conflictee)\n\t\t\t\tif conflictee_obj is None:\n\t\t\t\t\tcontinue\n\t\t\t\tif ((cfg[conflicter.module_id]['shutit.core.module.build'] or\n\t\t\t\t     self.is_to_be_built_or_is_installed(conflicter)) and\n\t\t\t\t    (cfg[conflictee_obj.module_id]['shutit.core.module.build'] or\n\t\t\t\t     self.is_to_be_built_or_is_installed(conflictee_obj))):\n\t\t\t\t\terrs.append(('conflicter module id: ' + conflicter.module_id + ' is configured to be built or is already built but conflicts with module_id: ' + conflictee_obj.module_id,))\n\t\treturn errs",
    "docstring": "Checks for any conflicts between modules configured to be built."
  },
  {
    "code": "def create_user_profile(sender, instance, created, **kwargs):\n    if created:\n        profile = UserProfile.objects.get_or_create(user=instance)[0]\n        profile.hash_pass = create_htpasswd(instance.hash_pass)\n        profile.save()\n    else:\n        try:\n            up = UserProfile.objects.get(user=instance.id)\n            up.hash_pass = create_htpasswd(instance.hash_pass)\n            up.save()\n        except AttributeError:\n            pass",
    "docstring": "Create the UserProfile when a new User is saved"
  },
  {
    "code": "def user(self):\n        if self._user is None:\n            url = \"%s/users/%s\" % (self.root, self._username)\n            self._user = CMPUser(url=url,\n                                 securityHandler=self._securityHandler,\n                                 proxy_port=self._proxy_port,\n                                 proxy_url=self._proxy_url,\n                                 initialize=False)\n        return self._user",
    "docstring": "gets the user properties"
  },
  {
    "code": "def adapt_timefield_value(self, value):\n        if value is None:\n            return None\n        if isinstance(value, string_types):\n            return datetime.datetime(*(time.strptime(value, '%H:%M:%S')[:6]))\n        return datetime.datetime(1900, 1, 1, value.hour, value.minute, value.second)",
    "docstring": "Transform a time value to an object compatible with what is expected\n        by the backend driver for time columns."
  },
  {
    "code": "def run_transaction(transactor, callback):\n    if isinstance(transactor, sqlalchemy.engine.Connection):\n        return _txn_retry_loop(transactor, callback)\n    elif isinstance(transactor, sqlalchemy.engine.Engine):\n        with transactor.connect() as connection:\n            return _txn_retry_loop(connection, callback)\n    elif isinstance(transactor, sqlalchemy.orm.sessionmaker):\n        session = transactor(autocommit=True)\n        return _txn_retry_loop(session, callback)\n    else:\n        raise TypeError(\"don't know how to run a transaction on %s\", type(transactor))",
    "docstring": "Run a transaction with retries.\n\n    ``callback()`` will be called with one argument to execute the\n    transaction. ``callback`` may be called more than once; it should have\n    no side effects other than writes to the database on the given\n    connection. ``callback`` should not call ``commit()` or ``rollback()``;\n    these will be called automatically.\n\n    The ``transactor`` argument may be one of the following types:\n    * `sqlalchemy.engine.Connection`: the same connection is passed to the callback.\n    * `sqlalchemy.engine.Engine`: a connection is created and passed to the callback.\n    * `sqlalchemy.orm.sessionmaker`: a session is created and passed to the callback."
  },
  {
    "code": "def expectRegion(self, filename, x, y, maxrms=0):\n        log.debug('expectRegion %s (%s, %s)', filename, x, y)\n        return self._expectFramebuffer(filename, x, y, maxrms)",
    "docstring": "Wait until a portion of the screen matches the target image\n\n            The region compared is defined by the box\n            (x, y), (x + image.width, y + image.height)"
  },
  {
    "code": "def casefold_parts(self, parts):\n        if self.filesystem.is_windows_fs:\n            return [p.lower() for p in parts]\n        return parts",
    "docstring": "Return the lower-case version of parts for a Windows filesystem."
  },
  {
    "code": "def map_sites(self, stmts):\n        valid_statements = []\n        mapped_statements = []\n        for stmt in stmts:\n            mapped_stmt = self.map_stmt_sites(stmt)\n            if mapped_stmt is not None:\n                mapped_statements.append(mapped_stmt)\n            else:\n                valid_statements.append(stmt)\n        return valid_statements, mapped_statements",
    "docstring": "Check a set of statements for invalid modification sites.\n\n        Statements are checked against Uniprot reference sequences to determine\n        if residues referred to by post-translational modifications exist at\n        the given positions.\n\n        If there is nothing amiss with a statement (modifications on any of the\n        agents, modifications made in the statement, etc.), then the statement\n        goes into the list of valid statements. If there is a problem with the\n        statement, the offending modifications are looked up in the site map\n        (:py:attr:`site_map`), and an instance of :py:class:`MappedStatement`\n        is added to the list of mapped statements.\n\n        Parameters\n        ----------\n        stmts : list of :py:class:`indra.statement.Statement`\n            The statements to check for site errors.\n\n        Returns\n        -------\n        tuple\n            2-tuple containing (valid_statements, mapped_statements). The first\n            element of the tuple is a list of valid statements\n            (:py:class:`indra.statement.Statement`) that were not found to\n            contain any site errors. The second element of the tuple is a list\n            of mapped statements (:py:class:`MappedStatement`) with information\n            on the incorrect sites and corresponding statements with correctly\n            mapped sites."
  },
  {
    "code": "def filter_grounded_only(stmts_in, **kwargs):\n    remove_bound = kwargs.get('remove_bound', False)\n    logger.info('Filtering %d statements for grounded agents...' % \n                len(stmts_in))\n    stmts_out = []\n    score_threshold = kwargs.get('score_threshold')\n    for st in stmts_in:\n        grounded = True\n        for agent in st.agent_list():\n            if agent is not None:\n                criterion = lambda x: _agent_is_grounded(x, score_threshold)\n                if not criterion(agent):\n                    grounded = False\n                    break\n                if not isinstance(agent, Agent):\n                    continue\n                if remove_bound:\n                    _remove_bound_conditions(agent, criterion)\n                elif _any_bound_condition_fails_criterion(agent, criterion):\n                    grounded = False\n                    break\n        if grounded:\n            stmts_out.append(st)\n    logger.info('%d statements after filter...' % len(stmts_out))\n    dump_pkl = kwargs.get('save')\n    if dump_pkl:\n        dump_statements(stmts_out, dump_pkl)\n    return stmts_out",
    "docstring": "Filter to statements that have grounded agents.\n\n    Parameters\n    ----------\n    stmts_in : list[indra.statements.Statement]\n        A list of statements to filter.\n    score_threshold : Optional[float]\n        If scored groundings are available in a list and the highest score\n        if below this threshold, the Statement is filtered out.\n    save : Optional[str]\n        The name of a pickle file to save the results (stmts_out) into.\n    remove_bound: Optional[bool]\n        If true, removes ungrounded bound conditions from a statement.\n        If false (default), filters out statements with ungrounded bound\n        conditions.\n\n    Returns\n    -------\n    stmts_out : list[indra.statements.Statement]\n        A list of filtered statements."
  },
  {
    "code": "def batch_row_ids(data_batch):\n    item = data_batch.data[0]\n    user = data_batch.data[1]\n    return {'user_weight': user.astype(np.int64),\n            'item_weight': item.astype(np.int64)}",
    "docstring": "Generate row ids based on the current mini-batch"
  },
  {
    "code": "def create_api_error_from_http_exception(e):\n    response = e.response\n    try:\n        explanation = response.json()['message']\n    except ValueError:\n        explanation = (response.content or '').strip()\n    cls = APIError\n    if response.status_code == 404:\n        if explanation and ('No such image' in str(explanation) or\n                            'not found: does not exist or no pull access'\n                            in str(explanation) or\n                            'repository does not exist' in str(explanation)):\n            cls = ImageNotFound\n        else:\n            cls = NotFound\n    raise cls(e, response=response, explanation=explanation)",
    "docstring": "Create a suitable APIError from requests.exceptions.HTTPError."
  },
  {
    "code": "def _check_for_degenerate_interesting_groups(items):\n    igkey = (\"algorithm\", \"bcbiornaseq\", \"interesting_groups\")\n    interesting_groups = tz.get_in(igkey, items[0], [])\n    if isinstance(interesting_groups, str):\n        interesting_groups = [interesting_groups]\n    for group in interesting_groups:\n        values = [tz.get_in((\"metadata\", group), x, None) for x in items]\n        if all(x is None for x in values):\n            raise ValueError(\"group %s is labelled as an interesting group, \"\n                             \"but does not appear in the metadata.\" % group)\n        if len(list(tz.unique(values))) == 1:\n            raise ValueError(\"group %s is marked as an interesting group, \"\n                             \"but all samples have the same value.\" % group)",
    "docstring": "Make sure interesting_groups specify existing metadata and that\n    the interesting_group is not all of the same for all of the samples"
  },
  {
    "code": "def new_symlink(self, vd, name, parent, rr_target, seqnum, rock_ridge,\n                    rr_name, xa):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('Directory Record already initialized')\n        self._new(vd, name, parent, seqnum, False, 0, xa)\n        if rock_ridge:\n            self._rr_new(rock_ridge, rr_name, rr_target, False, False, False,\n                         0o0120555)",
    "docstring": "Create a new symlink Directory Record.  This implies that the new\n        record will be Rock Ridge.\n\n        Parameters:\n         vd - The Volume Descriptor this record is part of.\n         name - The name for this directory record.\n         parent - The parent of this directory record.\n         rr_target - The symlink target for this directory record.\n         seqnum - The sequence number for this directory record.\n         rock_ridge - The version of Rock Ridge to use for this directory record.\n         rr_name - The Rock Ridge name for this directory record.\n         xa - True if this is an Extended Attribute record.\n        Returns:\n         Nothing."
  },
  {
    "code": "def translate_docs(self, ds, **kwargs):\n        for d in ds:\n            self.map_doc(d, {}, self.invert_subject_object)\n        return [self.translate_doc(d, **kwargs) for d in ds]",
    "docstring": "Translate a set of solr results"
  },
  {
    "code": "def projectSphereFilter(actor):\n    poly = actor.polydata()\n    psf = vtk.vtkProjectSphereFilter()\n    psf.SetInputData(poly)\n    psf.Update()\n    a = Actor(psf.GetOutput())\n    return a",
    "docstring": "Project a spherical-like object onto a plane.\n\n    .. hint:: |projectsphere| |projectsphere.py|_"
  },
  {
    "code": "def separate_words(text, acronyms=None):\n    words, _case, _sep = case_parse.parse_case(text, acronyms, preserve_case=True)\n    return ' '.join(words)",
    "docstring": "Return text in \"seperate words\" style.\n\n    Args:\n        text: input string to convert case\n        detect_acronyms: should attempt to detect acronyms\n        acronyms: a list of acronyms to detect\n\n    >>> separate_words(\"HELLO_WORLD\")\n    'HELLO WORLD'\n    >>> separate_words(\"helloHTMLWorld\", True, [\"HTML\"])\n    'hello HTML World'"
  },
  {
    "code": "def handle_scd(self, conn, args):\n        reply = {\n            (b'GETINFO', b'version'): self.version,\n        }.get(args)\n        if reply is None:\n            raise AgentError(b'ERR 100696144 No such device <SCD>')\n        keyring.sendline(conn, b'D ' + reply)",
    "docstring": "No support for smart-card device protocol."
  },
  {
    "code": "def idxmax(self, **kwargs):\n        if self._is_transposed:\n            kwargs[\"axis\"] = kwargs.get(\"axis\", 0) ^ 1\n            return self.transpose().idxmax(**kwargs)\n        axis = kwargs.get(\"axis\", 0)\n        index = self.index if axis == 0 else self.columns\n        def idxmax_builder(df, **kwargs):\n            if axis == 0:\n                df.index = index\n            else:\n                df.columns = index\n            return df.idxmax(**kwargs)\n        func = self._build_mapreduce_func(idxmax_builder, **kwargs)\n        return self._full_axis_reduce(axis, func)",
    "docstring": "Returns the first occurrence of the maximum over requested axis.\n\n        Returns:\n            A new QueryCompiler object containing the maximum of each column or axis."
  },
  {
    "code": "def section_exists(self, section):\n        if section in self.__sections:\n            LOGGER.debug(\"> '{0}' section exists in '{1}'.\".format(section, self))\n            return True\n        else:\n            LOGGER.debug(\"> '{0}' section doesn't exists in '{1}'.\".format(section, self))\n            return False",
    "docstring": "Checks if given section exists.\n\n        Usage::\n\n            >>> content = [\"[Section A]\\\\n\", \"; Comment.\\\\n\", \"Attribute 1 = \\\\\"Value A\\\\\"\\\\n\", \"\\\\n\", \\\n\"[Section B]\\\\n\", \"Attribute 2 = \\\\\"Value B\\\\\"\\\\n\"]\n            >>> sections_file_parser = SectionsFileParser()\n            >>> sections_file_parser.content = content\n            >>> sections_file_parser.parse()\n            <foundations.parsers.SectionsFileParser object at 0x845683844>\n            >>> sections_file_parser.section_exists(\"Section A\")\n            True\n            >>> sections_file_parser.section_exists(\"Section C\")\n            False\n\n        :param section: Section to check existence.\n        :type section: unicode\n        :return: Section existence.\n        :rtype: bool"
  },
  {
    "code": "def create_avg_psf(skydir, ltc, event_class, event_types, dtheta,\n                   egy, cth_bins, npts=None):\n    return create_avg_rsp(create_psf, skydir, ltc,\n                          event_class, event_types,\n                          dtheta, egy,  cth_bins, npts)",
    "docstring": "Generate model for exposure-weighted PSF averaged over incidence\n    angle.\n\n    Parameters\n    ----------\n    egy : `~numpy.ndarray`\n        Energies in MeV.\n\n    cth_bins : `~numpy.ndarray`\n        Bin edges in cosine of the incidence angle."
  },
  {
    "code": "def nameValue(name, value, valueType=str, quotes=False):\n    if valueType == bool:\n        if value:\n            return \"--%s\" % name\n        return \"\"\n    if value is None:\n        return \"\"\n    if quotes:\n        return \"--%s '%s'\" % (name, valueType(value))\n    return \"--%s %s\" % (name, valueType(value))",
    "docstring": "Little function to make it easier to make name value strings for commands."
  },
  {
    "code": "def set_iscsi_volume(self, port_id,\n                         initiator_iqn, initiator_dhcp=False,\n                         initiator_ip=None, initiator_netmask=None,\n                         target_dhcp=False, target_iqn=None, target_ip=None,\n                         target_port=3260, target_lun=0, boot_prio=1,\n                         chap_user=None, chap_secret=None,\n                         mutual_chap_secret=None):\n        initiator_netmask = (_convert_netmask(initiator_netmask)\n                             if initiator_netmask else None)\n        port_handler = _parse_physical_port_id(port_id)\n        iscsi_boot = _create_iscsi_boot(\n            initiator_iqn,\n            initiator_dhcp=initiator_dhcp,\n            initiator_ip=initiator_ip,\n            initiator_netmask=initiator_netmask,\n            target_dhcp=target_dhcp,\n            target_iqn=target_iqn,\n            target_ip=target_ip,\n            target_port=target_port,\n            target_lun=target_lun,\n            boot_prio=boot_prio,\n            chap_user=chap_user,\n            chap_secret=chap_secret,\n            mutual_chap_secret=mutual_chap_secret)\n        port = self._find_port(port_handler)\n        if port:\n            port_handler.set_iscsi_port(port, iscsi_boot)\n        else:\n            port = port_handler.create_iscsi_port(iscsi_boot)\n            self._add_port(port_handler, port)",
    "docstring": "Set iSCSI volume information to configuration.\n\n        :param port_id: Physical port ID.\n        :param initiator_iqn: IQN of initiator.\n        :param initiator_dhcp: True if DHCP is used in the iSCSI network.\n        :param initiator_ip: IP address of initiator. None if DHCP is used.\n        :param initiator_netmask: Netmask of initiator as integer. None if\n               DHCP is used.\n        :param target_dhcp: True if DHCP is used for iSCSI target.\n        :param target_iqn: IQN of target. None if DHCP is used.\n        :param target_ip: IP address of target. None if DHCP is used.\n        :param target_port: Port number of target.  None if DHCP is used.\n        :param target_lun: LUN number of target. None if DHCP is used,\n        :param boot_prio: Boot priority of the volume. 1 indicates the highest\n            priority."
  },
  {
    "code": "def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun):\n        device = '0.0.%s' % fcp\n        set_zfcp_conf = 'echo \"%(device)s %(wwpn)s %(lun)s\" >> /etc/zfcp.conf'\\\n                        % {'device': device, 'wwpn': target_wwpn,\n                           'lun': target_lun}\n        trigger_uevent = 'echo \"add\" >> /sys/bus/ccw/devices/%s/uevent\\n'\\\n                         % device\n        return '\\n'.join((set_zfcp_conf,\n                          trigger_uevent))",
    "docstring": "rhel6 set WWPN and LUN in configuration files"
  },
  {
    "code": "def prompt_config(sch, defaults=None, path=None):\n    out = {}\n    for name, attr in sch.attributes():\n        fullpath = name\n        if path:\n            fullpath = '{}.{}'.format(path, name)\n        if defaults is None:\n            defaults = {}\n        default = defaults.get(name)\n        if isinstance(attr, _schema.Schema):\n            value = prompt_config(attr, defaults=default, path=fullpath)\n        else:\n            if default is None:\n                default = attr.default\n            if default is None:\n                default = ''\n            value = prompt(fullpath, default)\n        out[name] = value\n    return sch.validate(out)",
    "docstring": "Utility function to recursively prompt for config values\n\n    Arguments:\n        - defaults<dict>: default values used for empty inputs\n        - path<str>: path to prepend to config keys (eg. \"path.keyname\")"
  },
  {
    "code": "def _type_single(self, value, _type):\n        ' apply type to the single value '\n        if value is None or _type in (None, NoneType):\n            pass\n        elif isinstance(value, _type):\n            value = dt2ts(value) if _type in [datetime, date] else value\n        else:\n            if _type in (datetime, date):\n                value = dt2ts(value)\n            elif _type in (unicode, str):\n                value = to_encoding(value)\n            else:\n                try:\n                    value = _type(value)\n                except Exception:\n                    value = to_encoding(value)\n                    logger.error(\"typecast failed: %s(value=%s)\" % (\n                        _type.__name__, value))\n                    raise\n        return value",
    "docstring": "apply type to the single value"
  },
  {
    "code": "def get_assets(cls, lat, lon, begin=None, end=None):\n        instance = cls('planetary/earth/assets')\n        filters = {\n            'lat': lat,\n            'lon': lon,\n            'begin': begin,\n            'end': end,\n        }\n        return instance.get_resource(**filters)",
    "docstring": "Returns date and ids of flyovers\n\n        Args:\n            lat: latitude float\n            lon: longitude float\n            begin: date instance\n            end: date instance\n\n        Returns:\n            json"
  },
  {
    "code": "def patterns(self):\n        all_patterns = []\n        for label, patterns in self.token_patterns.items():\n            for pattern in patterns:\n                all_patterns.append({\"label\": label, \"pattern\": pattern})\n        for label, patterns in self.phrase_patterns.items():\n            for pattern in patterns:\n                all_patterns.append({\"label\": label, \"pattern\": pattern.text})\n        return all_patterns",
    "docstring": "Get all patterns that were added to the entity ruler.\n\n        RETURNS (list): The original patterns, one dictionary per pattern.\n\n        DOCS: https://spacy.io/api/entityruler#patterns"
  },
  {
    "code": "def pad_release(release_to_pad, num_sections=4):\n    parts = release_to_pad.split('.')\n    if len(parts) > num_sections:\n        raise ValueError(\"Too many sections encountered ({found} > {num} in release string {rel}\".format(\n            found=len(parts), num=num_sections, rel=release_to_pad\n        ))\n    pad_count = num_sections - len(parts)\n    return \".\".join(parts[:-1] + ['0'] * pad_count + parts[-1:])",
    "docstring": "Pad out package and kernel release versions so that\n    ``LooseVersion`` comparisons will be correct.\n\n    Release versions with less than num_sections will\n    be padded in front of the last section with zeros.\n\n    For example ::\n\n        pad_release(\"390.el6\", 4)\n\n    will return ``390.0.0.el6`` and ::\n\n        pad_release(\"390.11.el6\", 4)\n\n    will return ``390.11.0.el6``.\n\n    If the number of sections of the release to be padded is\n    greater than num_sections, a ``ValueError`` will be raised."
  },
  {
    "code": "def low_frequency_cutoff_from_cli(opts):\n    instruments = opts.instruments if opts.instruments is not None else []\n    return {ifo: opts.low_frequency_cutoff for ifo in instruments}",
    "docstring": "Parses the low frequency cutoff from the given options.\n\n    Returns\n    -------\n    dict\n        Dictionary of instruments -> low frequency cutoff."
  },
  {
    "code": "def has_documented_fields(self, include_inherited_fields=False):\n        fields = self.all_fields if include_inherited_fields else self.fields\n        for field in fields:\n            if field.doc:\n                return True\n        return False",
    "docstring": "Returns whether at least one field is documented."
  },
  {
    "code": "def _make_schema_patterns(self) -> None:\n        self.schema_pattern = self._schema_pattern()\n        for dc in self.data_children():\n            if isinstance(dc, InternalNode):\n                dc._make_schema_patterns()",
    "docstring": "Build schema pattern for the receiver and its data descendants."
  },
  {
    "code": "def read(self, length=-1):\n        _complain_ifclosed(self.closed)\n        if length < 0:\n            length = self.size\n        chunks = []\n        while 1:\n            if length <= 0:\n                break\n            c = self.f.read(min(self.buff_size, length))\n            if c == b\"\":\n                break\n            chunks.append(c)\n            length -= len(c)\n        data = b\"\".join(chunks)\n        if self.__encoding:\n            return data.decode(self.__encoding, self.__errors)\n        else:\n            return data",
    "docstring": "Read ``length`` bytes from the file.  If ``length`` is negative or\n        omitted, read all data until EOF.\n\n        :type length: int\n        :param length: the number of bytes to read\n        :rtype: string\n        :return: the chunk of data read from the file"
  },
  {
    "code": "def set_idle_ttl(cls, pid, ttl):\n        with cls._lock:\n            cls._ensure_pool_exists(pid)\n            cls._pools[pid].set_idle_ttl(ttl)",
    "docstring": "Set the idle TTL for a pool, after which it will be destroyed.\n\n        :param str pid: The pool id\n        :param int ttl: The TTL for an idle pool"
  },
  {
    "code": "def check_exports(mod, specs, renamings):\n    functions = {renamings.get(k, k): v for k, v in specs.functions.items()}\n    mod_functions = {node.name: node for node in mod.body\n                     if isinstance(node, ast.FunctionDef)}\n    for fname, signatures in functions.items():\n        try:\n            fnode = mod_functions[fname]\n        except KeyError:\n            raise PythranSyntaxError(\n                \"Invalid spec: exporting undefined function `{}`\"\n                .format(fname))\n        for signature in signatures:\n            args_count = len(fnode.args.args)\n            if len(signature) > args_count:\n                raise PythranSyntaxError(\n                    \"Too many arguments when exporting `{}`\"\n                    .format(fname))\n            elif len(signature) < args_count - len(fnode.args.defaults):\n                raise PythranSyntaxError(\n                    \"Not enough arguments when exporting `{}`\"\n                    .format(fname))",
    "docstring": "Does nothing but raising PythranSyntaxError if specs\n    references an undefined global"
  },
  {
    "code": "def normalize_std_array(vector):\n  length = 1\n  n_samples = len(vector)\n  mean = numpy.ndarray((length,), 'float64')\n  std = numpy.ndarray((length,), 'float64')\n  mean.fill(0)\n  std.fill(0)\n  for array in vector:\n    x = array.astype('float64')\n    mean += x\n    std += (x ** 2)\n  mean /= n_samples\n  std /= n_samples\n  std -= (mean ** 2)\n  std = std ** 0.5\n  arrayset = numpy.ndarray(shape=(n_samples,mean.shape[0]), dtype=numpy.float64)\n  for i in range (0, n_samples):\n    arrayset[i,:] = (vector[i]-mean) / std\n  return arrayset",
    "docstring": "Applies a unit mean and variance normalization to an arrayset"
  },
  {
    "code": "def fields(self, fields):\n        if not isinstance(fields, list):\n            raise InvalidUsage('fields must be of type `list`')\n        self._sysparms['sysparm_fields'] = \",\".join(fields)",
    "docstring": "Sets `sysparm_fields` after joining the given list of `fields`\n\n        :param fields: List of fields to include in the response\n        :raise:\n            :InvalidUsage: if fields is of an unexpected type"
  },
  {
    "code": "def seek_to_beginning(self, *partitions):\n        if not all([isinstance(p, TopicPartition) for p in partitions]):\n            raise TypeError('partitions must be TopicPartition namedtuples')\n        if not partitions:\n            partitions = self._subscription.assigned_partitions()\n            assert partitions, 'No partitions are currently assigned'\n        else:\n            for p in partitions:\n                assert p in self._subscription.assigned_partitions(), 'Unassigned partition'\n        for tp in partitions:\n            log.debug(\"Seeking to beginning of partition %s\", tp)\n            self._subscription.need_offset_reset(tp, OffsetResetStrategy.EARLIEST)",
    "docstring": "Seek to the oldest available offset for partitions.\n\n        Arguments:\n            *partitions: Optionally provide specific TopicPartitions, otherwise\n                default to all assigned partitions.\n\n        Raises:\n            AssertionError: If any partition is not currently assigned, or if\n                no partitions are assigned."
  },
  {
    "code": "def _to_raw_pwm(self, values):\n        return [self._to_single_raw_pwm(values[i])\n                for i in range(len(self._pins))]",
    "docstring": "Convert uniform pwm values to raw, driver-specific values.\n\n        :param values: The uniform pwm values (0.0-1.0).\n        :return: Converted, driver-specific pwm values."
  },
  {
    "code": "def modify_classes():\n    import copy\n    from django.conf import settings\n    from django.contrib.admin.sites import site\n    from django.utils.importlib import import_module\n    from django.utils.module_loading import module_has_submodule\n    for app in settings.INSTALLED_APPS:\n        mod = import_module(app)\n        try:\n            before_import_registry = copy.copy(site._registry)\n            import_module('%s.class_modifiers' % app)\n        except:\n            site._registry = before_import_registry\n            if module_has_submodule(mod, 'class_modifiers'):\n                raise",
    "docstring": "Auto-discover INSTALLED_APPS class_modifiers.py modules and fail silently when\n    not present. This forces an import on them to modify any classes they\n    may want."
  },
  {
    "code": "def overwrite_workspace_config(namespace, workspace, cnamespace, configname, body):\n    headers = _fiss_agent_header({\"Content-type\": \"application/json\"})\n    uri = \"workspaces/{0}/{1}/method_configs/{2}/{3}\".format(namespace,\n                                        workspace, cnamespace, configname)\n    return __put(uri, headers=headers, json=body)",
    "docstring": "Add or overwrite method configuration in workspace.\n\n    Args:\n        namespace  (str): project to which workspace belongs\n        workspace  (str): Workspace name\n        cnamespace (str): Configuration namespace\n        configname (str): Configuration name\n        body      (json): new body (definition) of the method config\n\n    Swagger:\n        https://api.firecloud.org/#!/Method_Configurations/overwriteWorkspaceMethodConfig"
  },
  {
    "code": "def normalize_num_type(num_type):\n    if isinstance(num_type, tf.DType):\n        num_type = num_type.as_numpy_dtype.type\n    if num_type in [np.float32, np.float64]:\n        num_type = settings.float_type\n    elif num_type in [np.int16, np.int32, np.int64]:\n        num_type = settings.int_type\n    else:\n        raise ValueError('Unknown dtype \"{0}\" passed to normalizer.'.format(num_type))\n    return num_type",
    "docstring": "Work out what a sensible type for the array is. if the default type\n    is float32, downcast 64bit float to float32. For ints, assume int32"
  },
  {
    "code": "def delete_tree(self, key):\n        self.log.debug(\"Deleting tree: %r\", key)\n        names = [item[\"name\"] for item in self.list_path(key, with_metadata=False, deep=True)]\n        for name in names:\n            self.delete_key(name)",
    "docstring": "Delete all keys under given root key. Basic implementation works by just listing all available\n        keys and deleting them individually but storage providers can implement more efficient logic."
  },
  {
    "code": "def cleanup_dead_jobs():\n    from .models import WooeyJob\n    inspect = celery_app.control.inspect()\n    active_tasks = {task['id'] for worker, tasks in six.iteritems(inspect.active()) for task in tasks}\n    active_jobs = WooeyJob.objects.filter(status=WooeyJob.RUNNING)\n    to_disable = set()\n    for job in active_jobs:\n        if job.celery_id not in active_tasks:\n            to_disable.add(job.pk)\n    WooeyJob.objects.filter(pk__in=to_disable).update(status=WooeyJob.FAILED)",
    "docstring": "This cleans up jobs that have been marked as ran, but are not queue'd in celery. It is meant\n    to cleanup jobs that have been lost due to a server crash or some other reason a job is\n    in limbo."
  },
  {
    "code": "def install_python(python, runas=None):\n    python = re.sub(r'^python-', '', python)\n    env = None\n    env_list = []\n    if __grains__['os'] in ('FreeBSD', 'NetBSD', 'OpenBSD'):\n        env_list.append('MAKE=gmake')\n    if __salt__['config.option']('pyenv.build_env'):\n        env_list.append(__salt__['config.option']('pyenv.build_env'))\n    if env_list:\n        env = ' '.join(env_list)\n    ret = {}\n    ret = _pyenv_exec('install', python, env=env, runas=runas, ret=ret)\n    if ret['retcode'] == 0:\n        rehash(runas=runas)\n        return ret['stderr']\n    else:\n        uninstall_python(python, runas=runas)\n        return False",
    "docstring": "Install a python implementation.\n\n    python\n        The version of python to install, should match one of the\n        versions listed by pyenv.list\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' pyenv.install_python 2.0.0-p0"
  },
  {
    "code": "def on_key_down(self, event):\n        state = self.state\n        if self.mouse_pos:\n            latlon = self.coordinates(self.mouse_pos.x, self.mouse_pos.y)\n            selected = self.selected_objects(self.mouse_pos)\n            state.event_queue.put(SlipKeyEvent(latlon, event, selected))\n        c = event.GetUniChar()\n        if c == ord('+') or (c == ord('=') and event.ShiftDown()):\n            self.change_zoom(1.0/1.2)\n            event.Skip()\n        elif c == ord('-'):\n            self.change_zoom(1.2)\n            event.Skip()\n        elif c == ord('G'):\n            self.enter_position()\n            event.Skip()\n        elif c == ord('C'):\n            self.clear_thumbnails()\n            event.Skip()",
    "docstring": "handle keyboard input"
  },
  {
    "code": "def ms_contrast_restore(self, viewer, event, data_x, data_y, msg=True):\n        if self.cancmap and (event.state == 'down'):\n            self.restore_contrast(viewer, msg=msg)\n        return True",
    "docstring": "An interactive way to restore the colormap contrast settings after\n        a warp operation."
  },
  {
    "code": "def _get_any_translated_model(self, meta=None):\n        if meta is None:\n            meta = self._parler_meta.root\n        tr_model = meta.model\n        local_cache = self._translations_cache[tr_model]\n        if local_cache:\n            check_languages = [self._current_language] + self.get_fallback_languages()\n            try:\n                for fallback_lang in check_languages:\n                    trans = local_cache.get(fallback_lang, None)\n                    if trans and not is_missing(trans):\n                        return trans\n                return next(t for t in six.itervalues(local_cache) if not is_missing(t))\n            except StopIteration:\n                pass\n        try:\n            prefetch = self._get_prefetched_translations(meta=meta)\n            if prefetch is not None:\n                translation = prefetch[0]\n            else:\n                translation = self._get_translated_queryset(meta=meta)[0]\n        except IndexError:\n            return None\n        else:\n            local_cache[translation.language_code] = translation\n            _cache_translation(translation)\n            return translation",
    "docstring": "Return any available translation.\n        Returns None if there are no translations at all."
  },
  {
    "code": "def parse_all_arguments(func):\n    args = dict()\n    if sys.version_info < (3, 0):\n        func_args = inspect.getargspec(func)\n        if func_args.defaults is not None:\n            val = len(func_args.defaults)\n            for i, itm in enumerate(func_args.args[-val:]):\n                args[itm] = func_args.defaults[i]\n    else:\n        func_args = inspect.signature(func)\n        for itm in list(func_args.parameters)[1:]:\n            param = func_args.parameters[itm]\n            if param.default is not param.empty:\n                args[param.name] = param.default\n    return args",
    "docstring": "determine all positional and named arguments as a dict"
  },
  {
    "code": "def _to_json(uniq):\n        result_json = {}\n        depth, ipix = utils.uniq2orderipix(uniq)\n        min_depth = np.min(depth[0])\n        max_depth = np.max(depth[-1])\n        for d in range(min_depth, max_depth+1):\n            pix_index = np.where(depth == d)[0]\n            if pix_index.size:\n                ipix_depth = ipix[pix_index]\n                result_json[str(d)] = ipix_depth.tolist()\n        return result_json",
    "docstring": "Serializes a MOC to the JSON format.\n\n        Parameters\n        ----------\n        uniq : `~numpy.ndarray`\n            The array of HEALPix cells representing the MOC to serialize.\n\n        Returns\n        -------\n        result_json : {str : [int]}\n            A dictionary of HEALPix cell lists indexed by their depth."
  },
  {
    "code": "def permute_data(arrays, random_state=None):\n  if any(len(a) != len(arrays[0]) for a in arrays):\n    raise ValueError('All arrays must be the same length.')\n  if not random_state:\n    random_state = np.random\n  order = random_state.permutation(len(arrays[0]))\n  return [a[order] for a in arrays]",
    "docstring": "Permute multiple numpy arrays with the same order."
  },
  {
    "code": "def is_readable(path):\n    return os.access(os.path.abspath(path), os.R_OK)",
    "docstring": "Returns True if provided file or directory exists and can be read with the current user.\n    Returns False otherwise."
  },
  {
    "code": "def h5features_convert(self, infile):\n        with h5py.File(infile, 'r') as f:\n            groups = list(f.keys())\n        for group in groups:\n            self._writer.write(\n                Reader(infile, group).read(),\n                self.groupname, append=True)",
    "docstring": "Convert a h5features file to the latest h5features version."
  },
  {
    "code": "def inverse_mercator(xy):\n    lon = (xy[0] / 20037508.34) * 180\n    lat = (xy[1] / 20037508.34) * 180\n    lat = 180 / math.pi * \\\n        (2 * math.atan(math.exp(lat * math.pi / 180)) - math.pi / 2)\n    return (lon, lat)",
    "docstring": "Given coordinates in spherical mercator, return a lon,lat tuple."
  },
  {
    "code": "def _handle_io(self, args, file, result, passphrase=False, binary=False):\n        p = self._open_subprocess(args, passphrase)\n        if not binary:\n            stdin = codecs.getwriter(self._encoding)(p.stdin)\n        else:\n            stdin = p.stdin\n        if passphrase:\n            _util._write_passphrase(stdin, passphrase, self._encoding)\n        writer = _util._threaded_copy_data(file, stdin)\n        self._collect_output(p, result, writer, stdin)\n        return result",
    "docstring": "Handle a call to GPG - pass input data, collect output data."
  },
  {
    "code": "def spawn_worker(params):\n    setup_logging(params)\n    log.info(\"Adding worker: idx=%s\\tconcurrency=%s\\tresults=%s\", params.worker_index, params.concurrency,\n             params.report)\n    worker = Worker(params)\n    worker.start()\n    worker.join()",
    "docstring": "This method has to be module level function\n\n    :type params: Params"
  },
  {
    "code": "def DbAddDevice(self, argin):\n        self._log.debug(\"In DbAddDevice()\")\n        if len(argin) < 3:\n            self.warn_stream(\"DataBase::AddDevice(): incorrect number of input arguments \")\n            th_exc(DB_IncorrectArguments,\n                   \"incorrect no. of input arguments, needs at least 3 (server,device,class)\",\n                   \"DataBase::AddDevice()\")\n        self.info_stream(\"DataBase::AddDevice(): insert %s server with device %s\",argin[0],argin[1])\n        server_name, d_name, klass_name = argin[:3]\n        if len(argin) > 3:\n            alias = argin[3]\n        else:\n            alias = None\n        ret, dev_name, dfm = check_device_name(d_name)\n        if not ret:\n            th_exc(DB_IncorrectDeviceName,\n                  \"device name (\" + d_name + \") syntax error (should be [tango:][//instance/]domain/family/member)\",\n                  \"DataBase::AddDevice()\")\n        self.db.add_device(server_name, (dev_name, dfm) , klass_name, alias=alias)",
    "docstring": "Add a Tango class device to a specific device server\n\n        :param argin: Str[0] = Full device server process name\n        Str[1] = Device name\n        Str[2] = Tango class name\n        :type: tango.DevVarStringArray\n        :return:\n        :rtype: tango.DevVoid"
  },
  {
    "code": "def get_signature_params(func):\n    if is_cython(func):\n        attrs = [\n            \"__code__\", \"__annotations__\", \"__defaults__\", \"__kwdefaults__\"\n        ]\n        if all(hasattr(func, attr) for attr in attrs):\n            original_func = func\n            def func():\n                return\n            for attr in attrs:\n                setattr(func, attr, getattr(original_func, attr))\n        else:\n            raise TypeError(\"{!r} is not a Python function we can process\"\n                            .format(func))\n    return list(funcsigs.signature(func).parameters.items())",
    "docstring": "Get signature parameters\n\n    Support Cython functions by grabbing relevant attributes from the Cython\n    function and attaching to a no-op function. This is somewhat brittle, since\n    funcsigs may change, but given that funcsigs is written to a PEP, we hope\n    it is relatively stable. Future versions of Python may allow overloading\n    the inspect 'isfunction' and 'ismethod' functions / create ABC for Python\n    functions. Until then, it appears that Cython won't do anything about\n    compatability with the inspect module.\n\n    Args:\n        func: The function whose signature should be checked.\n\n    Raises:\n        TypeError: A type error if the signature is not supported"
  },
  {
    "code": "def _set_categories(self):\n        for column, _ in self._categories.items():\n            if column in self.columns:\n                self[column] = self[column].astype('category')",
    "docstring": "Inplace conversion from categories."
  },
  {
    "code": "def _pack(self):\n        data = ByteBuffer()\n        if not hasattr(self, '__fields__'):\n            return data.array\n        for field in self.__fields__:\n            field.encode(self, data)\n        return data.array",
    "docstring": "Pack the message and return an array."
  },
  {
    "code": "def _load_table(self, metadata_path, data_path):\n        metadata_dir = os.path.dirname(os.path.expanduser(metadata_path))\n        data_path = os.path.normpath(os.path.join(metadata_dir, data_path))\n        extension = data_path.split('.')[-1]\n        if extension == 'csv':\n            full_table = pd.read_csv(data_path, index_col=False)\n            table = _subset_table(full_table, self.subset)\n            self.meta, _ = _subset_meta(self.meta, self.subset)\n        elif extension in ['db', 'sql']:\n            table = self._get_db_table(data_path, extension)\n        else:\n            raise TypeError('Cannot process file of type %s' % extension)\n        return table",
    "docstring": "Load data table, taking subset if needed\n\n        Parameters\n        ----------\n        metadata_path : str\n            Path to metadata file\n        data_path : str\n            Path to data file, absolute or relative to metadata file\n\n        Returns\n        -------\n        dataframe\n            Table for analysis"
  },
  {
    "code": "def _add_interaction(int_type, **kwargs):\n    fig = kwargs.pop('figure', current_figure())\n    marks = kwargs.pop('marks', [_context['last_mark']])\n    for name, traitlet in int_type.class_traits().items():\n        dimension = traitlet.get_metadata('dimension')\n        if dimension is not None:\n            kwargs[name] = _get_context_scale(dimension)\n    kwargs['marks'] = marks\n    interaction = int_type(**kwargs)\n    if fig.interaction is not None:\n        fig.interaction.close()\n    fig.interaction = interaction\n    return interaction",
    "docstring": "Add the interaction for the specified type.\n\n    If a figure is passed using the key-word argument `figure` it is used. Else\n    the context figure is used.\n    If a list of marks are passed using the key-word argument `marks` it\n    is used. Else the latest mark that is passed is used as the only mark\n    associated with the selector.\n\n    Parameters\n    ----------\n    int_type: type\n        The type of interaction to be added."
  },
  {
    "code": "def H_donor_count(mol):\n    mol.require(\"Valence\")\n    return sum(1 for _, a in mol.atoms_iter() if a.H_donor)",
    "docstring": "Hydrogen bond donor count"
  },
  {
    "code": "def is_sparse_vector(x):\n    return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1",
    "docstring": "x is a 2D sparse matrix with it's first shape equal to 1."
  },
  {
    "code": "def get_default_config_file(rootdir=None):\n    if rootdir is None:\n        return DEFAULT_CONFIG_FILE\n    for path in CONFIG_FILES:\n        path = os.path.join(rootdir, path)\n        if os.path.isfile(path) and os.access(path, os.R_OK):\n            return path",
    "docstring": "Search for configuration file."
  },
  {
    "code": "def ppo_opt_step(i,\n                 opt_state,\n                 ppo_opt_update,\n                 policy_net_apply,\n                 old_policy_params,\n                 value_net_apply,\n                 value_net_params,\n                 padded_observations,\n                 padded_actions,\n                 padded_rewards,\n                 reward_mask,\n                 gamma=0.99,\n                 lambda_=0.95,\n                 epsilon=0.1):\n  new_policy_params = trax_opt.get_params(opt_state)\n  g = grad(\n      ppo_loss, argnums=1)(\n          policy_net_apply,\n          new_policy_params,\n          old_policy_params,\n          value_net_apply,\n          value_net_params,\n          padded_observations,\n          padded_actions,\n          padded_rewards,\n          reward_mask,\n          gamma=gamma,\n          lambda_=lambda_,\n          epsilon=epsilon)\n  return ppo_opt_update(i, g, opt_state)",
    "docstring": "PPO optimizer step."
  },
  {
    "code": "def from_dict(self, d):\n        self.sitting = d['sitting']\n        self.id = d.get('id', None)\n        return self",
    "docstring": "Set this person from dict\n\n        :param d: Dictionary representing a person ('sitting'[, 'id'])\n        :type d: dict\n        :rtype: Person\n        :raises KeyError: 'sitting' not set"
  },
  {
    "code": "def _ExportFileContent(self, aff4_object, result):\n    if self.options.export_files_contents:\n      try:\n        result.content = aff4_object.Read(self.MAX_CONTENT_SIZE)\n        result.content_sha256 = hashlib.sha256(result.content).hexdigest()\n      except (IOError, AttributeError) as e:\n        logging.warning(\"Can't read content of %s: %s\", aff4_object.urn, e)",
    "docstring": "Add file content from aff4_object to result."
  },
  {
    "code": "def cpu_frequency(self) -> str:\n        return '{}GHz'.format(\n            self.random.uniform(\n                a=1.5,\n                b=4.3,\n                precision=1,\n            ),\n        )",
    "docstring": "Get a random frequency of CPU.\n\n        :return: Frequency of CPU.\n\n        :Example:\n            4.0 GHz."
  },
  {
    "code": "def inspect(self, **kwargs):\n        scf_cycle = abiinspect.PhononScfCycle.from_file(self.output_file.path)\n        if scf_cycle is not None:\n            if \"title\" not in kwargs: kwargs[\"title\"] = str(self)\n            return scf_cycle.plot(**kwargs)",
    "docstring": "Plot the Phonon SCF cycle results with matplotlib.\n\n        Returns:\n            `matplotlib` figure, None if some error occurred."
  },
  {
    "code": "def debounce(self, wait, immediate=None):\n        wait = (float(wait) / float(1000))\n        def debounced(*args, **kwargs):\n            def call_it():\n                self.obj(*args, **kwargs)\n            try:\n                debounced.t.cancel()\n            except(AttributeError):\n                pass\n            debounced.t = Timer(wait, call_it)\n            debounced.t.start()\n        return self._wrap(debounced)",
    "docstring": "Returns a function, that, as long as it continues to be invoked,\n        will not be triggered. The function will be called after it stops\n        being called for N milliseconds. If `immediate` is passed, trigger\n        the function on the leading edge, instead of the trailing."
  },
  {
    "code": "def get_urls_from_onetab(onetab):\n    html = requests.get(onetab).text\n    soup = BeautifulSoup(html, 'lxml')\n    divs = soup.findAll('div', {'style': 'padding-left: 24px; '\n                                         'padding-top: 8px; '\n                                         'position: relative; '\n                                         'font-size: 13px;'})\n    return [div.find('a').attrs['href'] for div in divs]",
    "docstring": "Get video urls from a link to the onetab shared page.\n\n    Args:\n        onetab (str): Link to a onetab shared page.\n\n    Returns:\n        list: List of links to the videos."
  },
  {
    "code": "def decision(self, result, **values):\n\t\tdata = self.__getDecision(result, **values)\n\t\tdata = [data[value] for value in result]\n\t\tif len(data) == 1:\n\t\t\treturn data[0]\n\t\telse:\n\t\t\treturn data",
    "docstring": "The decision method with callback option. This method will find matching row, construct\n\t\ta dictionary and call callback with dictionary.\n\n\t\tArgs:\n\t\t\tcallback (function): Callback function will be called when decision will be finded.\n\t\t\tresult (array of str): Array of header string\n\t\t\t**values (dict): What should finder look for, (headerString : value).\n\n\t\tReturns:\n\t\t\tArrays of finded values strings\n\t\tExample:\n\t\t\t>>> table = DecisionTable('''\n\t\t\t>>>     header1 header2\n\t\t\t>>>     ===============\n\t\t\t>>>     value1 value2\n\t\t\t>>> ''')\n\t\t\t>>>\n\t\t\t>>> header1, header2 = table.decision(\n\t\t\t>>>     ['header1','header2'],\n\t\t\t>>>     header1='value1',\n\t\t\t>>>     header2='value2'\n\t\t\t>>> )\n\t\t\t>>> print(header1,header2)\n\t\t\t(value1 value2)"
  },
  {
    "code": "def dumps(self) -> str:\n        return json.dumps(self.data, sort_keys=True, indent=4)",
    "docstring": "Dumps the json content as a string"
  },
  {
    "code": "def clear_local_registration(self):\n        delete_registered_file()\n        delete_unregistered_file()\n        write_to_disk(constants.machine_id_file, delete=True)\n        logger.debug('Re-register set, forcing registration.')\n        logger.debug('New machine-id: %s', generate_machine_id(new=True))",
    "docstring": "Deletes dotfiles and machine-id for fresh registration"
  },
  {
    "code": "def callback(self):\n        self._callback(*self._args, **self._kwargs)\n        self._last_checked = time.time()",
    "docstring": "Run the callback"
  },
  {
    "code": "def model_resources(self):\n        response = jsonify({\n            'apiVersion': '0.1',\n            'swaggerVersion': '1.1',\n            'basePath': '%s%s' % (self.base_uri(), self.api.url_prefix),\n            'apis': self.get_model_resources()\n        })\n        response.headers.add('Cache-Control', 'max-age=0')\n        return response",
    "docstring": "Listing of all supported resources."
  },
  {
    "code": "def print_out(self, value, indent=None, format_options=None, asap=False):\n        if indent is None:\n            indent = '>   '\n        text = indent + str(value)\n        if format_options is None:\n            format_options = 'gray'\n        if self._style_prints and format_options:\n            if not isinstance(format_options, dict):\n                format_options = {'color_fg': format_options}\n            text = format_print_text(text, **format_options)\n        command = 'iprint' if asap else 'print'\n        self._set(command, text, multi=True)\n        return self",
    "docstring": "Prints out the given value.\n\n        :param value:\n\n        :param str|unicode indent:\n\n        :param dict|str|unicode format_options: text color\n\n        :param bool asap: Print as soon as possible."
  },
  {
    "code": "def shortlink_scanned(self, data):\n        self.logger.info(\"Received shortlink_scanned event\")\n        data = json.loads(data)\n        customer_token = str(data['object']['id'])\n        response = self.mapiclient.create_payment_request(\n            customer=customer_token,\n            currency=\"NOK\",\n            amount=\"20.00\",\n            allow_credit=True,\n            pos_id=self._pos_id,\n            pos_tid=str(uuid.uuid4()),\n            action='auth',\n            expires_in=90,\n            callback_uri=\"pusher:m-winterwarming-pos_callback_chan\",\n            text='Have some hot chocolate!')\n        self._tid = response['id']\n        print(str(self._tid))",
    "docstring": "Called when a shortlink_scanned event is received"
  },
  {
    "code": "def traverse_data(obj, key_target):\n    if isinstance(obj, str) and '.json' in str(obj):\n        obj = json.load(open(obj, 'r'))\n    if isinstance(obj, list):\n        queue = obj.copy()\n    elif isinstance(obj, dict):\n        queue = [obj.copy()]\n    else:\n        sys.exit('obj needs to be a list or dict')\n    count = 0\n    while not queue or count != 1000:\n        count += 1\n        curr_obj = queue.pop()\n        if isinstance(curr_obj, dict):\n            for key, value in curr_obj.items():\n                if key == key_target:\n                    return curr_obj\n                else:\n                    queue.append(curr_obj[key])\n        elif isinstance(curr_obj, list):\n            for co in curr_obj:\n                queue.append(co)\n    if count == 1000:\n        sys.exit('traverse_data needs to be updated...')\n    return False",
    "docstring": "will traverse nested list and dicts until key_target equals the current dict key"
  },
  {
    "code": "def add_route(enode, route, via, shell=None):\n    via = ip_address(via)\n    version = '-4'\n    if (via.version == 6) or \\\n            (route != 'default' and ip_network(route).version == 6):\n        version = '-6'\n    cmd = 'ip {version} route add {route} via {via}'.format(\n        version=version, route=route, via=via\n    )\n    response = enode(cmd, shell=shell)\n    assert not response",
    "docstring": "Add a new static route.\n\n    :param enode: Engine node to communicate with.\n    :type enode: topology.platforms.base.BaseNode\n    :param str route: Route to add, an IP in the form ``'192.168.20.20/24'``\n     or ``'2001::0/24'`` or ``'default'``.\n    :param str via: Via for the route as an IP in the form\n     ``'192.168.20.20/24'`` or ``'2001::0/24'``.\n    :param shell: Shell name to execute commands. If ``None``, use the Engine\n     Node default shell.\n    :type shell: str or None"
  },
  {
    "code": "def pad(text, length):\n    text_length = wcswidth(text)\n    if text_length < length:\n        return text + ' ' * (length - text_length)\n    return text",
    "docstring": "Pads text to given length, taking into account wide characters."
  },
  {
    "code": "def update(self, id, name, incident_preference):\n        data = {\n            \"policy\": {\n                \"name\": name,\n                \"incident_preference\": incident_preference\n            }\n        }\n        return self._put(\n            url='{0}alerts_policies/{1}.json'.format(self.URL, id),\n            headers=self.headers,\n            data=data\n        )",
    "docstring": "This API endpoint allows you to update an alert policy\n\n        :type id: integer\n        :param id: The id of the policy\n\n        :type name: str\n        :param name: The name of the policy\n\n        :type incident_preference: str\n        :param incident_preference: Can be PER_POLICY, PER_CONDITION or\n            PER_CONDITION_AND_TARGET\n\n        :rtype: dict\n        :return: The JSON response of the API\n\n        ::\n\n            {\n                \"policy\": {\n                    \"created_at\": \"time\",\n                    \"id\": \"integer\",\n                    \"incident_preference\": \"string\",\n                    \"name\": \"string\",\n                    \"updated_at\": \"time\"\n                }\n            }"
  },
  {
    "code": "def _format_lon(self, lon):\n        if self.ppd in [4, 16, 64, 128]:\n            return None\n        else:\n            return map(lambda x: \"{0:0>3}\".format(int(x)), self._map_center('long', lon))",
    "docstring": "Returned a formated longitude format for the file"
  },
  {
    "code": "def update_record_field(table, sys_id, field, value):\n    client = _get_client()\n    client.table = table\n    response = client.update({field: value}, sys_id)\n    return response",
    "docstring": "Update the value of a record's field in a servicenow table\n\n    :param table: The table name, e.g. sys_user\n    :type  table: ``str``\n\n    :param sys_id: The unique ID of the record\n    :type  sys_id: ``str``\n\n    :param field: The new value\n    :type  field: ``str``\n\n    :param value: The new value\n    :type  value: ``str``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion servicenow.update_record_field sys_user 2348234 first_name jimmy"
  },
  {
    "code": "def fix_file(input_file,\n             encoding=None,\n             *,\n             fix_entities='auto',\n             remove_terminal_escapes=True,\n             fix_encoding=True,\n             fix_latin_ligatures=True,\n             fix_character_width=True,\n             uncurl_quotes=True,\n             fix_line_breaks=True,\n             fix_surrogates=True,\n             remove_control_chars=True,\n             remove_bom=True,\n             normalization='NFC'):\n    entities = fix_entities\n    for line in input_file:\n        if isinstance(line, bytes):\n            if encoding is None:\n                line, encoding = guess_bytes(line)\n            else:\n                line = line.decode(encoding)\n        if fix_entities == 'auto' and '<' in line and '>' in line:\n            entities = False\n        yield fix_text_segment(\n            line,\n            fix_entities=entities,\n            remove_terminal_escapes=remove_terminal_escapes,\n            fix_encoding=fix_encoding,\n            fix_latin_ligatures=fix_latin_ligatures,\n            fix_character_width=fix_character_width,\n            uncurl_quotes=uncurl_quotes,\n            fix_line_breaks=fix_line_breaks,\n            fix_surrogates=fix_surrogates,\n            remove_control_chars=remove_control_chars,\n            remove_bom=remove_bom,\n            normalization=normalization\n        )",
    "docstring": "Fix text that is found in a file.\n\n    If the file is being read as Unicode text, use that. If it's being read as\n    bytes, then we hope an encoding was supplied. If not, unfortunately, we\n    have to guess what encoding it is. We'll try a few common encodings, but we\n    make no promises. See the `guess_bytes` function for how this is done.\n\n    The output is a stream of fixed lines of text."
  },
  {
    "code": "def declare_actor(self, actor):\n        self.emit_before(\"declare_actor\", actor)\n        self.declare_queue(actor.queue_name)\n        self.actors[actor.actor_name] = actor\n        self.emit_after(\"declare_actor\", actor)",
    "docstring": "Declare a new actor on this broker.  Declaring an Actor\n        twice replaces the first actor with the second by name.\n\n        Parameters:\n          actor(Actor): The actor being declared."
  },
  {
    "code": "def check_slice_perms(self, slice_id):\n    form_data, slc = get_form_data(slice_id, use_slice_data=True)\n    datasource_type = slc.datasource.type\n    datasource_id = slc.datasource.id\n    viz_obj = get_viz(\n        datasource_type=datasource_type,\n        datasource_id=datasource_id,\n        form_data=form_data,\n        force=False,\n    )\n    security_manager.assert_datasource_permission(viz_obj.datasource)",
    "docstring": "Check if user can access a cached response from slice_json.\n\n    This function takes `self` since it must have the same signature as the\n    the decorated method."
  },
  {
    "code": "def diff(self, other=diff.Diffable.Index, paths=None, create_patch=False, **kwargs):\n        if other is self.Index:\n            return diff.DiffIndex()\n        if isinstance(other, string_types):\n            other = self.repo.rev_parse(other)\n        if isinstance(other, Object):\n            cur_val = kwargs.get('R', False)\n            kwargs['R'] = not cur_val\n            return other.diff(self.Index, paths, create_patch, **kwargs)\n        if other is not None:\n            raise ValueError(\"other must be None, Diffable.Index, a Tree or Commit, was %r\" % other)\n        return super(IndexFile, self).diff(other, paths, create_patch, **kwargs)",
    "docstring": "Diff this index against the working copy or a Tree or Commit object\n\n        For a documentation of the parameters and return values, see\n        Diffable.diff\n\n        :note:\n            Will only work with indices that represent the default git index as\n            they have not been initialized with a stream."
  },
  {
    "code": "def instruction_ASR_memory(self, opcode, ea, m):\n        r = self.ASR(m)\n        return ea, r & 0xff",
    "docstring": "Arithmetic shift memory right"
  },
  {
    "code": "def produce_csv_output(filehandle: TextIO,\n                       fields: Sequence[str],\n                       values: Iterable[str]) -> None:\n    output_csv(filehandle, fields)\n    for row in values:\n        output_csv(filehandle, row)",
    "docstring": "Produce CSV output, without using ``csv.writer``, so the log can be used\n    for lots of things.\n\n    - ... eh? What was I talking about?\n    - POOR; DEPRECATED.\n\n    Args:\n        filehandle: file to write to\n        fields: field names\n        values: values"
  },
  {
    "code": "async def on_raw_313(self, message):\n        target, nickname = message.params[:2]\n        info = {\n            'oper': True\n        }\n        if nickname in self._pending['whois']:\n            self._whois_info[nickname].update(info)",
    "docstring": "WHOIS operator info."
  },
  {
    "code": "def _cl_gof3r(file_info, region):\n        command = [\"gof3r\", \"get\", \"--no-md5\",\n                   \"-k\", file_info.key,\n                   \"-b\", file_info.bucket]\n        if region != \"us-east-1\":\n            command += [\"--endpoint=s3-%s.amazonaws.com\" % region]\n        return (command, \"gof3r\")",
    "docstring": "Command line required for download using gof3r."
  },
  {
    "code": "def dragEnterEvent(self, event):\r\n        if mimedata2url(event.mimeData()):\r\n            event.accept()\r\n        else:\r\n            event.ignore()",
    "docstring": "Allow user to drag files"
  },
  {
    "code": "def explain_prediction(estimator, doc, **kwargs):\n    return Explanation(\n        estimator=repr(estimator),\n        error=\"estimator %r is not supported\" % estimator,\n    )",
    "docstring": "Return an explanation of an estimator prediction.\n\n    :func:`explain_prediction` is not doing any work itself, it dispatches\n    to a concrete implementation based on estimator type.\n\n    Parameters\n    ----------\n    estimator : object\n        Estimator instance. This argument must be positional.\n\n    doc : object\n        Example to run estimator on. Estimator makes a prediction for this\n        example, and :func:`explain_prediction` tries to show information\n        about this prediction. Pass a single element, not a one-element array:\n        if you fitted your estimator on ``X``, that would be ``X[i]`` for\n        most containers, and ``X.iloc[i]`` for ``pandas.DataFrame``.\n\n    top : int or (int, int) tuple, optional\n        Number of features to show. When ``top`` is int, ``top`` features with\n        a highest absolute values are shown. When it is (pos, neg) tuple,\n        no more than ``pos`` positive features and no more than ``neg``\n        negative features is shown. ``None`` value means no limit (default).\n\n        This argument may be supported or not, depending on estimator type.\n\n    top_targets : int, optional\n        Number of targets to show. When ``top_targets`` is provided,\n        only specified number of targets with highest scores are shown.\n        Negative value means targets with lowest scores are shown.\n        Must not be given with ``targets`` argument.\n        ``None`` value means no limit: all targets are shown (default).\n\n        This argument may be supported or not, depending on estimator type.\n\n    target_names : list[str] or {'old_name': 'new_name'} dict, optional\n        Names of targets or classes. This argument can be used to provide\n        human-readable class/target names for estimators which don't expose\n        clss names themselves. It can be also used to rename estimator-provided\n        classes before displaying them.\n\n        This argument may be supported or not, depending on estimator type.\n\n    targets : list, optional\n        Order of class/target names to show. This argument can be also used\n        to show information only for a subset of classes. It should be a list\n        of class / target names which match either names provided by\n        an estimator or names defined in ``target_names`` parameter.\n        Must not be given with ``top_targets`` argument.\n\n        In case of binary classification you can use this argument to\n        set the class which probability or score should be displayed, with\n        an appropriate explanation. By default a result for predicted class\n        is shown. For example, you can use ``targets=[True]`` to always show\n        result for a positive class, even if the predicted label is False.\n\n        This argument may be supported or not, depending on estimator type.\n\n    feature_names : list, optional\n        A list of feature names. It allows to specify feature\n        names when they are not provided by an estimator object.\n\n        This argument may be supported or not, depending on estimator type.\n\n    feature_re : str, optional\n        Only feature names which match ``feature_re`` regex are returned\n        (more precisely, ``re.search(feature_re, x)`` is checked).\n\n    feature_filter : Callable[[str, float], bool], optional\n        Only feature names for which ``feature_filter`` function returns True\n        are returned. It must accept feature name and feature value.\n        Missing features always have a NaN value.\n\n    **kwargs: dict\n        Keyword arguments. All keyword arguments are passed to\n        concrete explain_prediction... implementations.\n\n    Returns\n    -------\n    Explanation\n        :class:`~.Explanation` result. Use one of the formatting functions from\n        :mod:`eli5.formatters` to print it in a human-readable form.\n\n        Explanation instances have repr which works well with\n        IPython notebook, but it can be a better idea to use\n        :func:`eli5.show_prediction` instead of :func:`eli5.explain_prediction`\n        if you work with IPython: :func:`eli5.show_prediction` allows to\n        customize formatting without a need to import :mod:`eli5.formatters`\n        functions."
  },
  {
    "code": "def _document_by_attribute(self, kind, condition=None):\n        doc = self.document\n        if doc:\n            for attr in doc.attributes:\n                if isinstance(attr, kind):\n                    if not condition or condition(attr):\n                        return doc\n                    return None",
    "docstring": "Helper method to return the document only if it has an attribute\n        that's an instance of the given kind, and passes the condition."
  },
  {
    "code": "def batch_write(self, tablename, return_capacity=None,\n                    return_item_collection_metrics=NONE):\n        return_capacity = self._default_capacity(return_capacity)\n        return BatchWriter(self, tablename, return_capacity=return_capacity,\n                           return_item_collection_metrics=return_item_collection_metrics)",
    "docstring": "Perform a batch write on a table\n\n        Parameters\n        ----------\n        tablename : str\n            Name of the table to write to\n        return_capacity : {NONE, INDEXES, TOTAL}, optional\n            INDEXES will return the consumed capacity for indexes, TOTAL will\n            return the consumed capacity for the table and the indexes.\n            (default NONE)\n        return_item_collection_metrics : (NONE, SIZE), optional\n            SIZE will return statistics about item collections that were\n            modified.\n\n        Examples\n        --------\n        .. code-block:: python\n\n            with connection.batch_write('mytable') as batch:\n                batch.put({'id': 'id1', 'foo': 'bar'})\n                batch.delete({'id': 'oldid'})"
  },
  {
    "code": "def percolating_continua(target, phi_crit, tau,\n                         volume_fraction='pore.volume_fraction',\n                         bulk_property='pore.intrinsic_conductivity'):\n    r\n    sigma = target[bulk_property]\n    phi = target[volume_fraction]\n    diff_phi = _sp.clip(phi - phi_crit, a_min=0, a_max=_sp.inf)\n    sigma_eff = sigma*(diff_phi)**tau\n    return sigma_eff",
    "docstring": "r'''\n    Calculates the effective property of a continua using percolation theory\n\n    Parameters\n    ----------\n    target : OpenPNM Object\n        The object for which these values are being calculated.  This\n        controls the length of the calculated array, and also provides\n        access to other necessary thermofluid properties.\n\n    volume_fraction : string\n        The dictionary key in the Phase object containing the volume fraction\n        of the conducting component\n\n    bulk_property : string\n        The dictionary key in the Phase object containing the intrinsic\n        property of the conducting component\n\n    phi_crit : float\n        The volume fraction below which percolation does NOT occur\n\n    tau : float\n        The exponent of the percolation relationship\n\n    Notes\n    -----\n    This model uses the following standard percolation relationship:\n\n    .. math::\n\n        \\sigma_{effective}=\\sigma_{bulk}(\\phi - \\phi_{critical})^\\lambda"
  },
  {
    "code": "def variance_corrected_loss(loss, sigma_2=None):\n    with tf.variable_scope(\"variance_corrected_loss\"):\n        sigma_cost = 0\n        if sigma_2 is None:\n            sigma = tf.get_variable(name=\"sigma\", dtype=tf.float32, initializer=tf.constant(1.0), trainable=True)\n            sigma_2 = tf.pow(sigma, 2)\n            tf.summary.scalar(\"sigma2\", sigma_2)\n            sigma_cost = tf.log(sigma_2 + 1.0)\n        return 0.5 / sigma_2 * loss + sigma_cost",
    "docstring": "Create a variance corrected loss.\n\n    When summing variance corrected losses you get the same as multiloss.\n    This is especially usefull for keras where when having multiple losses they are summed by keras.\n    This multi-loss implementation is inspired by the Paper \"Multi-Task Learning Using Uncertainty to Weight Losses\n    for Scene Geometry and Semantics\" by Kendall, Gal and Cipolla.\n    :param loss: The loss that should be variance corrected.\n    :param sigma_2: Optional a variance (sigma squared) to use. If none is provided it is learned.\n    :return: The variance corrected loss."
  },
  {
    "code": "def url_for(**options):\n    url_parts = get_url_parts(**options)\n    image_hash = hashlib.md5(b(options['image_url'])).hexdigest()\n    url_parts.append(image_hash)\n    return \"/\".join(url_parts)",
    "docstring": "Returns the url for the specified options"
  },
  {
    "code": "def visit_SetComp(self, node: AST, dfltChaining: bool = True) -> str:\n        return f\"{{{self.visit(node.elt)} \" \\\n               f\"{' '.join(self.visit(gen) for gen in node.generators)}}}\"",
    "docstring": "Return `node`s representation as set comprehension."
  },
  {
    "code": "def privmsg(self, text):\n        if self.dcctype == 'chat':\n            text += '\\n'\n        return self.send_bytes(self.encode(text))",
    "docstring": "Send text to DCC peer.\n\n        The text will be padded with a newline if it's a DCC CHAT session."
  },
  {
    "code": "def _ProduceContent(self, mods, showprivate=False, showinh=False):\n        result = ''\n        nestedresult = ''\n        for mod in mods:\n            try:\n                all = mod[1].__all__\n            except AttributeError:\n                raise RuntimeError('Module (%s) MUST have `__all__` defined.' % mod[1].__name__)\n            if not showprivate and mod[0][0:1] == '_':\n                continue\n            if mod[0][0:2] == '__':\n                continue\n            result += self._ProduceSingleContent(mod, showprivate, showinh)\n        return result",
    "docstring": "An internal helper to create pages for several modules that do not have nested modules.\n        This will automatically generate the needed RSF to document each module module\n        and save the module to its own page appropriately.\n\n        Args:\n            mods (module): The modules to document that do not contain nested modules\n            showprivate (bool): A flag for whether or not to display private members\n\n        Returns:\n            str: The file names ready to be appended to a toctree"
  },
  {
    "code": "def from_yaml(cls, yaml_str=None, str_or_buffer=None):\n        cfg = yamlio.yaml_to_dict(yaml_str, str_or_buffer)\n        default_model_expr = cfg['default_config']['model_expression']\n        default_ytransform = cfg['default_config']['ytransform']\n        seg = cls(\n            cfg['segmentation_col'], cfg['fit_filters'],\n            cfg['predict_filters'], default_model_expr,\n            YTRANSFORM_MAPPING[default_ytransform], cfg['min_segment_size'],\n            cfg['name'])\n        if \"models\" not in cfg:\n            cfg[\"models\"] = {}\n        for name, m in cfg['models'].items():\n            m['model_expression'] = m.get(\n                'model_expression', default_model_expr)\n            m['ytransform'] = m.get('ytransform', default_ytransform)\n            m['fit_filters'] = None\n            m['predict_filters'] = None\n            reg = RegressionModel.from_yaml(yamlio.convert_to_yaml(m, None))\n            seg._group.add_model(reg)\n        logger.debug(\n            'loaded segmented regression model {} from yaml'.format(seg.name))\n        return seg",
    "docstring": "Create a SegmentedRegressionModel instance from a saved YAML\n        configuration. Arguments are mutally exclusive.\n\n        Parameters\n        ----------\n        yaml_str : str, optional\n            A YAML string from which to load model.\n        str_or_buffer : str or file like, optional\n            File name or buffer from which to load YAML.\n\n        Returns\n        -------\n        SegmentedRegressionModel"
  },
  {
    "code": "def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts):\n    r = get_ipv4_range(start_addr, end_addr, **api_opts)\n    if r:\n        return delete_object(r['_ref'], **api_opts)\n    else:\n        return True",
    "docstring": "Delete ip range.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12"
  },
  {
    "code": "def mon_status(conn, logger, hostname, args, silent=False):\n    mon = 'mon.%s' % hostname\n    try:\n        out = mon_status_check(conn, logger, hostname, args)\n        if not out:\n            logger.warning('monitor: %s, might not be running yet' % mon)\n            return False\n        if not silent:\n            logger.debug('*'*80)\n            logger.debug('status for monitor: %s' % mon)\n            for line in json.dumps(out, indent=2, sort_keys=True).split('\\n'):\n                logger.debug(line)\n            logger.debug('*'*80)\n        if out['rank'] >= 0:\n            logger.info('monitor: %s is running' % mon)\n            return True\n        if out['rank'] == -1 and out['state']:\n            logger.info('monitor: %s is currently at the state of %s' % (mon, out['state']))\n            return True\n        logger.info('monitor: %s is not running' % mon)\n        return False\n    except RuntimeError:\n        logger.info('monitor: %s is not running' % mon)\n        return False",
    "docstring": "run ``ceph daemon mon.`hostname` mon_status`` on the remote end and provide\n    not only the output, but be able to return a boolean status of what is\n    going on.\n    ``False`` represents a monitor that is not doing OK even if it is up and\n    running, while ``True`` would mean the monitor is up and running correctly."
  },
  {
    "code": "def rand_unicode(min_char=MIN_UNICHR, max_char=MAX_UNICHR, min_len=MIN_STRLEN,\n                 max_len=MAX_STRLEN, **kwargs):\n    from syn.five import unichr\n    return unicode(rand_str(min_char, max_char, min_len, max_len, unichr))",
    "docstring": "For values in the unicode range, regardless of Python version."
  },
  {
    "code": "def set_group_member_orphan(self, member_id):\n        self._put(self._service_url(['triggers', 'groups', 'members', member_id, 'orphan']), data=None, parse_json=False)",
    "docstring": "Make a non-orphan member trigger into an orphan.\n\n        :param member_id: Member Trigger id to be made an orphan."
  },
  {
    "code": "def convdicts():\n    pth = os.path.join(os.path.dirname(__file__), 'data', 'convdict.npz')\n    npz = np.load(pth)\n    cdd = {}\n    for k in list(npz.keys()):\n        cdd[k] = npz[k]\n    return cdd",
    "docstring": "Access a set of example learned convolutional dictionaries.\n\n    Returns\n    -------\n    cdd : dict\n      A dict associating description strings with dictionaries represented\n      as ndarrays\n\n    Examples\n    --------\n    Print the dict keys to obtain the identifiers of the available\n    dictionaries\n\n    >>> from sporco import util\n    >>> cd = util.convdicts()\n    >>> print(cd.keys())\n    ['G:12x12x72', 'G:8x8x16,12x12x32,16x16x48', ...]\n\n    Select a specific example dictionary using the corresponding identifier\n\n    >>> D = cd['G:8x8x96']"
  },
  {
    "code": "def get_binds(self, app=None):\n        app = self.get_app(app)\n        binds = [None] + list(app.config.get('SQLALCHEMY_BINDS') or ())\n        retval = {}\n        for bind in binds:\n            engine = self.get_engine(app, bind)\n            tables = self.get_tables_for_bind(bind)\n            retval.update(dict((table, engine) for table in tables))\n        return retval",
    "docstring": "Returns a dictionary with a table->engine mapping.\n\n        This is suitable for use of sessionmaker(binds=db.get_binds(app))."
  },
  {
    "code": "def get_domain_info(self, domain):\n        url = self.API_TEMPLATE + self.DOMAIN_INFO.format(domain=domain)\n        return self._get_json_from_response(url)",
    "docstring": "Get the GoDaddy supplied information about a specific domain.\n\n        :param domain: The domain to obtain info about.\n        :type domain: str\n\n        :return A JSON string representing the domain information"
  },
  {
    "code": "def clean_weights(self, cutoff=1e-4, rounding=5):\n        if not isinstance(rounding, int) or rounding < 1:\n            raise ValueError(\"rounding must be a positive integer\")\n        clean_weights = self.weights.copy()\n        clean_weights[np.abs(clean_weights) < cutoff] = 0\n        if rounding is not None:\n            clean_weights = np.round(clean_weights, rounding)\n        return dict(zip(self.tickers, clean_weights))",
    "docstring": "Helper method to clean the raw weights, setting any weights whose absolute\n        values are below the cutoff to zero, and rounding the rest.\n\n        :param cutoff: the lower bound, defaults to 1e-4\n        :type cutoff: float, optional\n        :param rounding: number of decimal places to round the weights, defaults to 5.\n                         Set to None if rounding is not desired.\n        :type rounding: int, optional\n        :return: asset weights\n        :rtype: dict"
  },
  {
    "code": "def get_component_attribute_name(component):\n        search = re.search(r\"(?P<category>\\w+)\\.(?P<name>\\w+)\", component)\n        if search:\n            name = \"{0}{1}{2}\".format(\n                search.group(\"category\"), search.group(\"name\")[0].upper(), search.group(\"name\")[1:])\n            LOGGER.debug(\"> Component name: '{0}' to attribute name Active_QLabel: '{1}'.\".format(component, name))\n        else:\n            name = component\n        return name",
    "docstring": "Gets given Component attribute name.\n\n        Usage::\n\n            >>> Manager.get_component_attribute_name(\"factory.components_manager_ui\")\n            u'factoryComponentsManagerUi'\n\n        :param component: Component to get the attribute name.\n        :type component: unicode\n        :return: Component attribute name.\n        :rtype: object"
  },
  {
    "code": "def to_array(self, dim='variable', name=None):\n        from .dataarray import DataArray\n        data_vars = [self.variables[k] for k in self.data_vars]\n        broadcast_vars = broadcast_variables(*data_vars)\n        data = duck_array_ops.stack([b.data for b in broadcast_vars], axis=0)\n        coords = dict(self.coords)\n        coords[dim] = list(self.data_vars)\n        dims = (dim,) + broadcast_vars[0].dims\n        return DataArray(data, coords, dims, attrs=self.attrs, name=name)",
    "docstring": "Convert this dataset into an xarray.DataArray\n\n        The data variables of this dataset will be broadcast against each other\n        and stacked along the first axis of the new array. All coordinates of\n        this dataset will remain coordinates.\n\n        Parameters\n        ----------\n        dim : str, optional\n            Name of the new dimension.\n        name : str, optional\n            Name of the new data array.\n\n        Returns\n        -------\n        array : xarray.DataArray"
  },
  {
    "code": "def load_object(obj) -> object:\n    if isinstance(obj, str):\n        if ':' in obj:\n            module_name, obj_name = obj.split(':')\n            if not module_name:\n                module_name = '.'\n        else:\n            module_name = obj\n        obj = importlib.import_module(module_name)\n        if obj_name:\n            attrs = obj_name.split('.')\n            for attr in attrs:\n                obj = getattr(obj, attr)\n    return obj",
    "docstring": "Load an object.\n\n    Args:\n        obj (str|object): Load the indicated object if this is a string;\n            otherwise, return the object as is.\n\n            To load a module, pass a dotted path like 'package.module';\n            to load an an object from a module pass a path like\n            'package.module:name'.\n\n    Returns:\n        object"
  },
  {
    "code": "def opts():\n    if __opts__.get('grain_opts', False) or \\\n            (isinstance(__pillar__, dict) and __pillar__.get('grain_opts', False)):\n        return __opts__\n    return {}",
    "docstring": "Return the minion configuration settings"
  },
  {
    "code": "def decompress(self, value):\n        if value:\n            return [value.get(field.name, None) for field in self.fields]\n        return [field.field.initial for field in self.fields]",
    "docstring": "Retreieve each field value or provide the initial values"
  },
  {
    "code": "def loadnetcdf(filename, copy=True):\n    filename = str(Path(filename).expanduser())\n    if copy:\n        dataarray = xr.open_dataarray(filename).copy()\n    else:\n        dataarray = xr.open_dataarray(filename, chunks={})\n    if dataarray.name is None:\n        dataarray.name = filename.rstrip('.nc')\n    for key, val in dataarray.coords.items():\n        if val.dtype.kind == 'S':\n            dataarray[key] = val.astype('U')\n        elif val.dtype == np.int32:\n            dataarray[key] = val.astype('i8')\n    return dataarray",
    "docstring": "Load a dataarray from a NetCDF file.\n\n    Args:\n        filename (str): Filename (*.nc).\n        copy (bool): If True, dataarray is copied in memory. Default is True.\n\n    Returns:\n        dataarray (xarray.DataArray): Loaded dataarray."
  },
  {
    "code": "def values(self):\n    return {n: getattr(self, n) for n in self._hparam_types.keys()}",
    "docstring": "Return the hyperparameter values as a Python dictionary.\n\n    Returns:\n      A dictionary with hyperparameter names as keys.  The values are the\n      hyperparameter values."
  },
  {
    "code": "def teardown_request(self, fn):\n        self._defer(lambda app: app.teardown_request(fn))\n        return fn",
    "docstring": "Register a function to be run at the end of each request,\n        regardless of whether there was an exception or not.  These functions\n        are executed when the request context is popped, even if not an\n        actual request was performed.\n\n        Example::\n\n            ctx = app.test_request_context()\n            ctx.push()\n            ...\n            ctx.pop()\n\n        When ``ctx.pop()`` is executed in the above example, the teardown\n        functions are called just before the request context moves from the\n        stack of active contexts.  This becomes relevant if you are using\n        such constructs in tests.\n\n        Generally teardown functions must take every necessary step to avoid\n        that they will fail.  If they do execute code that might fail they\n        will have to surround the execution of these code by try/except\n        statements and log occurring errors.\n\n        When a teardown function was called because of an exception it will\n        be passed an error object.\n\n        The return values of teardown functions are ignored.\n\n        .. admonition:: Debug Note\n\n           In debug mode Flask will not tear down a request on an exception\n           immediately.  Instead it will keep it alive so that the interactive\n           debugger can still access it.  This behavior can be controlled\n           by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable."
  },
  {
    "code": "def new_inner_member(self, name=None, params=None):\n        if name is None:\n            name = 'Generated_checkmodulation_%s' % uuid.uuid4()\n        if params is None:\n            params = {}\n        params['checkmodulation_name'] = name\n        checkmodulation = CheckModulation(params)\n        self.add_item(checkmodulation)",
    "docstring": "Create a CheckModulation object and add it to items\n\n        :param name: CheckModulation name\n        :type name: str\n        :param params: parameters to init CheckModulation\n        :type params: dict\n        :return: None\n        TODO: Remove this default mutable argument. Usually result in unexpected behavior"
  },
  {
    "code": "def get_user_activity(self, offset=None, limit=None):\n        args = {\n            'offset': offset,\n            'limit': limit,\n        }\n        return self._api_call('GET', 'v1.2/history', args=args)",
    "docstring": "Get activity about the user's lifetime activity with Uber.\n\n        Parameters\n            offset (int)\n                The integer offset for activity results. Default is 0.\n            limit (int)\n                Integer amount of results to return. Maximum is 50.\n                Default is 5.\n\n        Returns\n            (Response)\n                A Response object containing ride history."
  },
  {
    "code": "def pushd(cls, new_dir):\n        previous_dir = os.getcwd()\n        try:\n            new_ab_dir = None\n            if os.path.isabs(new_dir):\n                new_ab_dir = new_dir\n            else:\n                new_ab_dir = os.path.join(previous_dir, new_dir)\n            cls.cd(new_ab_dir)\n            yield\n        finally:\n            cls.cd(previous_dir)",
    "docstring": "Change directory, and back to previous directory.\n\n        It behaves like \"pushd directory; something; popd\"."
  },
  {
    "code": "def search_tags(self, tags):\n        qs = self.filter(tags__name__in=tags).order_by('file').distinct()\n        return qs",
    "docstring": "Search assets by passing a list of one or more tags."
  },
  {
    "code": "def _results_dir_path(self, key, stable):\n    return os.path.join(\n      self._results_dir_prefix,\n      key.id,\n      self._STABLE_DIR_NAME if stable else sha1(key.hash.encode('utf-8')).hexdigest()[:12]\n    )",
    "docstring": "Return a results directory path for the given key.\n\n    :param key: A CacheKey to generate an id for.\n    :param stable: True to use a stable subdirectory, false to use a portion of the cache key to\n      generate a path unique to the key."
  },
  {
    "code": "def editor_multi_agent_example():\n    agent_definitions = [\n        AgentDefinition(\"uav0\", agents.UavAgent, [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR]),\n        AgentDefinition(\"uav1\", agents.UavAgent, [Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR])\n    ]\n    env = HolodeckEnvironment(agent_definitions, start_world=False)\n    cmd0 = np.array([0, 0, -2, 10])\n    cmd1 = np.array([0, 0, 5, 10])\n    for i in range(10):\n        env.reset()\n        env.act(\"uav0\", cmd0)\n        env.act(\"uav1\", cmd1)\n        for _ in range(1000):\n            states = env.tick()\n            uav0_terminal = states[\"uav0\"][Sensors.TERMINAL]\n            uav1_reward = states[\"uav1\"][Sensors.REWARD]",
    "docstring": "This editor example shows how to interact with holodeck worlds that have multiple agents.\n    This is specifically for when working with UE4 directly and not a prebuilt binary."
  },
  {
    "code": "def execute ( self, conn, dataset, dataset_access_type, transaction=False ):\n        if not conn:\n            dbsExceptionHandler(\"dbsException-failed-connect2host\", \"Oracle/Dataset/UpdateType.  Expects db connection from upper layer.\", self.logger.exception)\n        binds = { \"dataset\" : dataset , \"dataset_access_type\" : dataset_access_type ,\"myuser\": dbsUtils().getCreateBy(), \"mydate\": dbsUtils().getTime() }\n        result = self.dbi.processData(self.sql, binds, conn, transaction)",
    "docstring": "for a given file"
  },
  {
    "code": "def _get_parents_from_parts(kwargs):\n    parent_builder = []\n    if kwargs['last_child_num'] is not None:\n        parent_builder.append('{type}/{name}/'.format(**kwargs))\n        for index in range(1, kwargs['last_child_num']):\n            child_namespace = kwargs.get('child_namespace_{}'.format(index))\n            if child_namespace is not None:\n                parent_builder.append('providers/{}/'.format(child_namespace))\n            kwargs['child_parent_{}'.format(index)] = ''.join(parent_builder)\n            parent_builder.append(\n                '{{child_type_{0}}}/{{child_name_{0}}}/'\n                .format(index).format(**kwargs))\n        child_namespace = kwargs.get('child_namespace_{}'.format(kwargs['last_child_num']))\n        if child_namespace is not None:\n            parent_builder.append('providers/{}/'.format(child_namespace))\n        kwargs['child_parent_{}'.format(kwargs['last_child_num'])] = ''.join(parent_builder)\n    kwargs['resource_parent'] = ''.join(parent_builder) if kwargs['name'] else None\n    return kwargs",
    "docstring": "Get the parents given all the children parameters."
  },
  {
    "code": "def getFeature(self, compoundId):\n        feature = self._getFeatureById(compoundId.featureId)\n        feature.id = str(compoundId)\n        return feature",
    "docstring": "find a feature and return ga4gh representation, use compoundId as\n        featureId"
  },
  {
    "code": "def handle_command_line(options):\n    options = merge(options, constants.DEFAULT_OPTIONS)\n    engine = plugins.ENGINES.get_engine(\n        options[constants.LABEL_TEMPLATE_TYPE],\n        options[constants.LABEL_TMPL_DIRS],\n        options[constants.LABEL_CONFIG_DIR],\n    )\n    if options[constants.LABEL_TEMPLATE] is None:\n        if options[constants.POSITIONAL_LABEL_TEMPLATE] is None:\n            raise exceptions.NoTemplate(constants.ERROR_NO_TEMPLATE)\n        else:\n            engine.render_string_to_file(\n                options[constants.POSITIONAL_LABEL_TEMPLATE],\n                options[constants.LABEL_CONFIG],\n                options[constants.LABEL_OUTPUT],\n            )\n    else:\n        engine.render_to_file(\n            options[constants.LABEL_TEMPLATE],\n            options[constants.LABEL_CONFIG],\n            options[constants.LABEL_OUTPUT],\n        )\n    engine.report()\n    HASH_STORE.save_hashes()\n    exit_code = reporter.convert_to_shell_exit_code(\n        engine.number_of_templated_files()\n    )\n    return exit_code",
    "docstring": "act upon command options"
  },
  {
    "code": "def tokenise(string, strict=False, replace=False,\n\t\t\t\t\t\tdiphtongs=False, tones=False, unknown=False, merge=None):\n\twords = string.strip().replace('_', ' ').split()\n\toutput = []\n\tfor word in words:\n\t\ttokens = tokenise_word(word, strict, replace, tones, unknown)\n\t\tif diphtongs:\n\t\t\ttokens = group(are_diphtong, tokens)\n\t\tif merge is not None:\n\t\t\ttokens = group(merge, tokens)\n\t\toutput.extend(tokens)\n\treturn output",
    "docstring": "Tokenise an IPA string into a list of tokens. Raise ValueError if there is\n\ta problem; if strict=True, this includes the string not being compliant to\n\tthe IPA spec.\n\n\tIf replace=True, replace some common non-IPA symbols with their IPA\n\tcounterparts. If diphtongs=True, try to group diphtongs into single tokens.\n\tIf tones=True, do not ignore tone symbols. If unknown=True, do not ignore\n\tsymbols that cannot be classified into a relevant category. If merge is not\n\tNone, use it for within-word token grouping.\n\n\tPart of ipatok's public API."
  },
  {
    "code": "def get_forecast_api(self, longitude: str, latitude: str) -> {}:\r\n        api_url = APIURL_TEMPLATE.format(longitude, latitude)\r\n        response = urlopen(api_url)\r\n        data = response.read().decode('utf-8')\r\n        json_data = json.loads(data)\r\n        return json_data",
    "docstring": "gets data from API"
  },
  {
    "code": "def add_exception_handler(self, exception_handler):\n        if exception_handler is None:\n            raise RuntimeConfigException(\n                \"Valid Exception Handler instance to be provided\")\n        if not isinstance(exception_handler, AbstractExceptionHandler):\n            raise RuntimeConfigException(\n                \"Input should be an ExceptionHandler instance\")\n        self.exception_handlers.append(exception_handler)",
    "docstring": "Register input to the exception handlers list.\n\n        :param exception_handler: Exception Handler instance to be\n            registered.\n        :type exception_handler: AbstractExceptionHandler\n        :return: None"
  },
  {
    "code": "def at(self, time_str):\n        assert self.unit in ('days', 'hours') or self.start_day\n        hour, minute = time_str.split(':')\n        minute = int(minute)\n        if self.unit == 'days' or self.start_day:\n            hour = int(hour)\n            assert 0 <= hour <= 23\n        elif self.unit == 'hours':\n            hour = 0\n        assert 0 <= minute <= 59\n        self.at_time = datetime.time(hour, minute)\n        return self",
    "docstring": "Schedule the job every day at a specific time.\n\n        Calling this is only valid for jobs scheduled to run\n        every N day(s).\n\n        :param time_str: A string in `XX:YY` format.\n        :return: The invoked job instance"
  },
  {
    "code": "def compare(self, path, prefixed_path, source_storage):\n        comparitor = getattr(self, 'compare_%s' % self.comparison_method, None)\n        if not comparitor:\n            comparitor = self._create_comparitor(self.comparison_method)\n        return comparitor(path, prefixed_path, source_storage)",
    "docstring": "Returns True if the file should be copied."
  },
  {
    "code": "def escape(self, text, quote = True):\n        if isinstance(text, bytes):\n            return escape_b(text, quote)\n        else:\n            return escape(text, quote)",
    "docstring": "Escape special characters in HTML"
  },
  {
    "code": "def GetClientVersion(client_id, token=None):\n  if data_store.RelationalDBEnabled():\n    sinfo = data_store.REL_DB.ReadClientStartupInfo(client_id=client_id)\n    if sinfo is not None:\n      return sinfo.client_info.client_version\n    else:\n      return config.CONFIG[\"Source.version_numeric\"]\n  else:\n    with aff4.FACTORY.Open(client_id, token=token) as client:\n      cinfo = client.Get(client.Schema.CLIENT_INFO)\n      if cinfo is not None:\n        return cinfo.client_version\n      else:\n        return config.CONFIG[\"Source.version_numeric\"]",
    "docstring": "Returns last known GRR version that the client used."
  },
  {
    "code": "def export(self, source=None):\n        uidentities = {}\n        uids = api.unique_identities(self.db, source=source)\n        for uid in uids:\n            enrollments = [rol.to_dict()\n                           for rol in api.enrollments(self.db, uuid=uid.uuid)]\n            u = uid.to_dict()\n            u['identities'].sort(key=lambda x: x['id'])\n            uidentities[uid.uuid] = u\n            uidentities[uid.uuid]['enrollments'] = enrollments\n        blacklist = [mb.excluded for mb in api.blacklist(self.db)]\n        obj = {'time': str(datetime.datetime.now()),\n               'source': source,\n               'blacklist': blacklist,\n               'organizations': {},\n               'uidentities': uidentities}\n        return json.dumps(obj, default=self._json_encoder,\n                          indent=4, separators=(',', ': '),\n                          sort_keys=True)",
    "docstring": "Export a set of unique identities.\n\n        Method to export unique identities from the registry. Identities schema\n        will follow Sorting Hat JSON format.\n\n        When source parameter is given, only those unique identities which have\n        one or more identities from the given source will be exported.\n\n        :param source: source of the identities to export\n\n        :returns: a JSON formatted str"
  },
  {
    "code": "def _x_start_ok(self, client_properties, mechanism, response, locale):\n        if self.server_capabilities.get('consumer_cancel_notify'):\n            if 'capabilities' not in client_properties:\n                client_properties['capabilities'] = {}\n            client_properties['capabilities']['consumer_cancel_notify'] = True\n        if self.server_capabilities.get('connection.blocked'):\n            if 'capabilities' not in client_properties:\n                client_properties['capabilities'] = {}\n            client_properties['capabilities']['connection.blocked'] = True\n        args = AMQPWriter()\n        args.write_table(client_properties)\n        args.write_shortstr(mechanism)\n        args.write_longstr(response)\n        args.write_shortstr(locale)\n        self._send_method((10, 11), args)",
    "docstring": "Select security mechanism and locale\n\n        This method selects a SASL security mechanism. ASL uses SASL\n        (RFC2222) to negotiate authentication and encryption.\n\n        PARAMETERS:\n            client_properties: table\n\n                client properties\n\n            mechanism: shortstr\n\n                selected security mechanism\n\n                A single security mechanisms selected by the client,\n                which must be one of those specified by the server.\n\n                RULE:\n\n                    The client SHOULD authenticate using the highest-\n                    level security profile it can handle from the list\n                    provided by the server.\n\n                RULE:\n\n                    The mechanism field MUST contain one of the\n                    security mechanisms proposed by the server in the\n                    Start method. If it doesn't, the server MUST close\n                    the socket.\n\n            response: longstr\n\n                security response data\n\n                A block of opaque data passed to the security\n                mechanism. The contents of this data are defined by\n                the SASL security mechanism.  For the PLAIN security\n                mechanism this is defined as a field table holding two\n                fields, LOGIN and PASSWORD.\n\n            locale: shortstr\n\n                selected message locale\n\n                A single message local selected by the client, which\n                must be one of those specified by the server."
  },
  {
    "code": "def oauth_request(self, url, method, **kwargs):\n        if self.session is None:\n            self.session = self.get_session()\n        return self._internal_request(self.session, url, method, **kwargs)",
    "docstring": "Makes a request to url using an oauth session\n\n        :param str url: url to send request to\n        :param str method: type of request (get/put/post/patch/delete)\n        :param kwargs: extra params to send to the request api\n        :return: Response of the request\n        :rtype: requests.Response"
  },
  {
    "code": "def UNEXPOSED(self, _cursor_type):\n        _decl = _cursor_type.get_declaration()\n        name = self.get_unique_name(_decl)\n        if self.is_registered(name):\n            obj = self.get_registered(name)\n        else:\n            obj = self.parse_cursor(_decl)\n        return obj",
    "docstring": "Handles unexposed types.\n        Returns the canonical type instead."
  },
  {
    "code": "def _get_cmap(kwargs: dict) -> colors.Colormap:\n    from matplotlib.colors import ListedColormap\n    cmap = kwargs.pop(\"cmap\", default_cmap)\n    if isinstance(cmap, list):\n        return ListedColormap(cmap)\n    if isinstance(cmap, str):\n        try:\n            cmap = plt.get_cmap(cmap)\n        except BaseException as exc:\n            try:\n                import seaborn as sns\n                sns_palette = sns.color_palette(cmap, n_colors=256)\n                cmap = ListedColormap(sns_palette, name=cmap)\n            except ImportError:\n                raise exc\n    return cmap",
    "docstring": "Get the colour map for plots that support it.\n\n    Parameters\n    ----------\n    cmap : str or colors.Colormap or list of colors\n        A map or an instance of cmap. This can also be a seaborn palette\n        (if seaborn is installed)."
  },
  {
    "code": "def polynomial_exp_mod( base, exponent, polymod, p ):\n  assert exponent < p\n  if exponent == 0: return [ 1 ]\n  G = base\n  k = exponent\n  if k%2 == 1: s = G\n  else:        s = [ 1 ]\n  while k > 1:\n    k = k // 2\n    G = polynomial_multiply_mod( G, G, polymod, p )\n    if k%2 == 1: s = polynomial_multiply_mod( G, s, polymod, p )\n  return s",
    "docstring": "Polynomial exponentiation modulo a polynomial over ints mod p.\n\n  Polynomials are represented as lists of coefficients\n  of increasing powers of x."
  },
  {
    "code": "def try_pick_piece_of_work(self, worker_id, submission_id=None):\n    client = self._datastore_client\n    unclaimed_work_ids = None\n    if submission_id:\n      unclaimed_work_ids = [\n          k for k, v in iteritems(self.work)\n          if is_unclaimed(v) and (v['submission_id'] == submission_id)\n      ]\n    if not unclaimed_work_ids:\n      unclaimed_work_ids = [k for k, v in iteritems(self.work)\n                            if is_unclaimed(v)]\n    if unclaimed_work_ids:\n      next_work_id = random.choice(unclaimed_work_ids)\n    else:\n      return None\n    try:\n      with client.transaction() as transaction:\n        work_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id,\n                              KIND_WORK, next_work_id)\n        work_entity = client.get(work_key, transaction=transaction)\n        if not is_unclaimed(work_entity):\n          return None\n        work_entity['claimed_worker_id'] = worker_id\n        work_entity['claimed_worker_start_time'] = get_integer_time()\n        transaction.put(work_entity)\n    except Exception:\n      return None\n    return next_work_id",
    "docstring": "Tries pick next unclaimed piece of work to do.\n\n    Attempt to claim work piece is done using Cloud Datastore transaction, so\n    only one worker can claim any work piece at a time.\n\n    Args:\n      worker_id: ID of current worker\n      submission_id: if not None then this method will try to pick\n        piece of work for this submission\n\n    Returns:\n      ID of the claimed work piece"
  },
  {
    "code": "def phases_with(self, **kwargs) -> [PhaseOutput]:\n        return [phase for phase in self.phases if\n                all([getattr(phase, key) == value for key, value in kwargs.items()])]",
    "docstring": "Filters phases. If no arguments are passed all phases are returned. Arguments must be key value pairs, with\n        phase, data or pipeline as the key.\n\n        Parameters\n        ----------\n        kwargs\n            Filters, e.g. pipeline=pipeline1"
  },
  {
    "code": "def generate_hotp(secret, counter=4):\n    msg = struct.pack('>Q', counter)\n    digest = hmac.new(to_bytes(secret), msg, hashlib.sha1).digest()\n    ob = digest[19]\n    if PY2:\n        ob = ord(ob)\n    pos = ob & 15\n    base = struct.unpack('>I', digest[pos:pos + 4])[0] & 0x7fffffff\n    token = base % 1000000\n    return token",
    "docstring": "Generate a HOTP code.\n\n    :param secret: A secret token for the authentication.\n    :param counter: HOTP is a counter based algorithm."
  },
  {
    "code": "def settled(self, block_identifier: BlockSpecification) -> bool:\n        return self.token_network.channel_is_settled(\n            participant1=self.participant1,\n            participant2=self.participant2,\n            block_identifier=block_identifier,\n            channel_identifier=self.channel_identifier,\n        )",
    "docstring": "Returns if the channel is settled."
  },
  {
    "code": "def get_perceval_params_from_url(cls, urls):\n        params = []\n        dparam = cls.get_arthur_params_from_url(urls)\n        params.append(dparam[\"url\"])\n        return params",
    "docstring": "Get the perceval params given the URLs for the data source"
  },
  {
    "code": "def _get_from_dapi_or_mirror(link):\n    exception = False\n    try:\n        req = requests.get(_api_url() + link, timeout=5)\n    except requests.exceptions.RequestException:\n        exception = True\n    attempts = 1\n    while exception or str(req.status_code).startswith('5'):\n        if attempts > 5:\n            raise DapiCommError('Could not connect to the API endpoint, sorry.')\n        exception = False\n        try:\n            req = requests.get(_api_url(attempts % 2) + link, timeout=5*attempts)\n        except requests.exceptions.RequestException:\n            exception = True\n        attempts += 1\n    return req",
    "docstring": "Tries to get the link form DAPI or the mirror"
  },
  {
    "code": "def bind(value, name):\n    if isinstance(value, Markup):\n        return value\n    elif requires_in_clause(value):\n        raise MissingInClauseException(\n)\n    else:\n        return _bind_param(_thread_local.bind_params, name, value)",
    "docstring": "A filter that prints %s, and stores the value \n    in an array, so that it can be bound using a prepared statement\n\n    This filter is automatically applied to every {{variable}} \n    during the lexing stage, so developers can't forget to bind"
  },
  {
    "code": "def log_warning(msg, logger=\"TaskLogger\"):\n    tasklogger = get_tasklogger(logger)\n    tasklogger.warning(msg)\n    return tasklogger",
    "docstring": "Log a WARNING message\n\n    Convenience function to log a message to the default Logger\n\n    Parameters\n    ----------\n    msg : str\n        Message to be logged\n    logger : str, optional (default: \"TaskLogger\")\n        Unique name of the logger to retrieve\n\n    Returns\n    -------\n    logger : TaskLogger"
  },
  {
    "code": "def sorted_source_files(self):\n        assert self.final, 'Call build() before using the graph.'\n        out = []\n        for node in nx.topological_sort(self.graph):\n            if isinstance(node, NodeSet):\n                out.append(node.nodes)\n            else:\n                out.append([node])\n        return list(reversed(out))",
    "docstring": "Returns a list of targets in topologically sorted order."
  },
  {
    "code": "def collapse_focussed(self):\n        if implementsCollapseAPI(self._tree):\n            w, focuspos = self.get_focus()\n            self._tree.collapse(focuspos)\n            self._walker.clear_cache()\n            self.refresh()",
    "docstring": "Collapse currently focussed position; works only if the underlying\n        tree allows it."
  },
  {
    "code": "def drive_enclosures(self):\n        if not self.__drive_enclures:\n            self.__drive_enclures = DriveEnclosures(self.__connection)\n        return self.__drive_enclures",
    "docstring": "Gets the Drive Enclosures API client.\n\n        Returns:\n            DriveEnclosures:"
  },
  {
    "code": "def get_language_database():\n    lang = None\n    language = get_language()\n    if language:\n        for x in settings.LANGUAGES_DATABASES:\n            if x.upper() == language.upper():\n                lang = language\n                break\n    if lang is None:\n        lang = settings.LANGUAGES_DATABASES[0]\n    return lang.lower()",
    "docstring": "Return the language to be used to search the database contents"
  },
  {
    "code": "def read_vpcs_stdout(self):\n        output = \"\"\n        if self._vpcs_stdout_file:\n            try:\n                with open(self._vpcs_stdout_file, \"rb\") as file:\n                    output = file.read().decode(\"utf-8\", errors=\"replace\")\n            except OSError as e:\n                log.warn(\"Could not read {}: {}\".format(self._vpcs_stdout_file, e))\n        return output",
    "docstring": "Reads the standard output of the VPCS process.\n        Only use when the process has been stopped or has crashed."
  },
  {
    "code": "def libvlc_media_duplicate(p_md):\n    f = _Cfunctions.get('libvlc_media_duplicate', None) or \\\n        _Cfunction('libvlc_media_duplicate', ((1,),), class_result(Media),\n                    ctypes.c_void_p, Media)\n    return f(p_md)",
    "docstring": "Duplicate a media descriptor object.\n    @param p_md: a media descriptor object."
  },
  {
    "code": "def get_port(self, adapter_number, port_number):\n        for port in self.ports:\n            if port.adapter_number == adapter_number and port.port_number == port_number:\n                return port\n        return None",
    "docstring": "Return the port for this adapter_number and port_number\n        or returns None if the port is not found"
  },
  {
    "code": "def _decref_dependencies_recursive(self, term, refcounts, garbage):\n        for parent, _ in self.graph.in_edges([term]):\n            refcounts[parent] -= 1\n            if refcounts[parent] == 0:\n                garbage.add(parent)\n                self._decref_dependencies_recursive(parent, refcounts, garbage)",
    "docstring": "Decrement terms recursively.\n\n        Notes\n        -----\n        This should only be used to build the initial workspace, after that we\n        should use:\n        :meth:`~zipline.pipeline.graph.TermGraph.decref_dependencies`"
  },
  {
    "code": "def register_migration(self, migration: 'Migration'):\n        if migration.from_ver >= migration.to_ver:\n            raise ValueError('Migration cannot downgrade verson')\n        if migration.from_ver != self._final_ver:\n            raise ValueError('Cannot register disjoint migration')\n        self._migrations[migration.from_ver] = migration\n        self._final_ver = migration.to_ver",
    "docstring": "Register a migration.\n\n        You can only register migrations in order.  For example, you can\n        register migrations from version 1 to 2, then 2 to 3, then 3 to\n        4.  You cannot register 1 to 2 followed by 3 to 4."
  },
  {
    "code": "def from_deformation(cls, deformation):\n        dfm = Deformation(deformation)\n        return cls(0.5 * (np.dot(dfm.trans, dfm) - np.eye(3)))",
    "docstring": "Factory method that returns a Strain object from a deformation\n        gradient\n\n        Args:\n            deformation (3x3 array-like):"
  },
  {
    "code": "def contains_point(self, p):\n        for iv in self.s_center:\n            if iv.contains_point(p):\n                return True\n        branch = self[p > self.x_center]\n        return branch and branch.contains_point(p)",
    "docstring": "Returns whether this node or a child overlaps p."
  },
  {
    "code": "def filter_query(self, query):\n        for filter_class in list(self.filter_classes):\n            query = filter_class().filter_query(self.request, query, self)\n        return query",
    "docstring": "Filter the given query using the filter classes specified on the view if any are specified."
  },
  {
    "code": "def sentiment(\n    text       = None,\n    confidence = False\n    ):\n    try:\n        words = text.split(\" \")\n        words = [word for word in words if word]\n        features = word_features(words)\n        classification = classifier.classify(features)\n        confidence_classification = classifier.prob_classify(features).prob(classification)\n    except:\n        classification = None\n        confidence_classification = None\n    if confidence:\n        return (\n            classification,\n            confidence_classification\n        )\n    else:\n        return classification",
    "docstring": "This function accepts a string text input. It calculates the sentiment of\n    the text, \"pos\" or \"neg\". By default, it returns this calculated sentiment.\n    If selected, it returns a tuple of the calculated sentiment and the\n    classificaton confidence."
  },
  {
    "code": "def get_patch_op(self, keypath, value, op='replace'):\n        if isinstance(value, bool):\n            value = str(value).lower()\n        return {'op': op, 'path': '/*/*/{}'.format(keypath), 'value': value}",
    "docstring": "Return an object that describes a change of configuration on the given staging.\n        Setting will be applied on all available HTTP methods."
  },
  {
    "code": "def drdpgr(body, lon, lat, alt, re, f):\n    body = stypes.stringToCharP(body)\n    lon = ctypes.c_double(lon)\n    lat = ctypes.c_double(lat)\n    alt = ctypes.c_double(alt)\n    re = ctypes.c_double(re)\n    f = ctypes.c_double(f)\n    jacobi = stypes.emptyDoubleMatrix()\n    libspice.drdpgr_c(body, lon, lat, alt, re, f, jacobi)\n    return stypes.cMatrixToNumpy(jacobi)",
    "docstring": "This routine computes the Jacobian matrix of the transformation\n    from planetographic to rectangular coordinates.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdpgr_c.html\n\n    :param body: Body with which coordinate system is associated.\n    :type body: str\n    :param lon: Planetographic longitude of a point (radians).\n    :type lon: float\n    :param lat: Planetographic latitude of a point (radians).\n    :type lat: float\n    :param alt: Altitude of a point above reference spheroid.\n    :type alt: float\n    :param re: Equatorial radius of the reference spheroid.\n    :type re: float\n    :param f: Flattening coefficient.\n    :type f: float\n    :return: Matrix of partial derivatives.\n    :rtype: 3x3-Element Array of floats"
  },
  {
    "code": "def templates_in(path):\n    ext = '.cpp'\n    return (\n        Template(f[0:-len(ext)], load_file(os.path.join(path, f)))\n        for f in os.listdir(path) if f.endswith(ext)\n    )",
    "docstring": "Enumerate the templates found in path"
  },
  {
    "code": "def on_batch_end(self, train, **kwargs):\n        \"Take the stored results and puts it in `self.stats`\"\n        if train: self.stats.append(self.hooks.stored)",
    "docstring": "Take the stored results and puts it in `self.stats`"
  },
  {
    "code": "def run_commands(commands,\n                 directory,\n                 env=None\n                ):\n    if env is None:\n        env = os.environ.copy()\n    for step in commands:\n        if isinstance(step, (list, six.string_types)):\n            execution_dir = directory\n            raw_command = step\n        elif step.get('command'):\n            execution_dir = os.path.join(directory,\n                                         step.get('cwd')) if step.get('cwd') else directory\n            raw_command = step['command']\n        else:\n            raise AttributeError(\"Invalid command step: %s\" % step)\n        command_list = raw_command.split(' ') if isinstance(raw_command, six.string_types) else raw_command\n        if platform.system().lower() == 'windows':\n            command_list = fix_windows_command_list(command_list)\n        with change_dir(execution_dir):\n            check_call(command_list, env=env)",
    "docstring": "Run list of commands."
  },
  {
    "code": "def apply_inverse(self, y):\n        self._recompute()\n        return self.solver.solve(self._process_input(y))",
    "docstring": "Apply the inverse of the covariance matrix to a vector or matrix\n\n        Solve ``K.x = y`` for ``x`` where ``K`` is the covariance matrix of\n        the GP with the white noise and ``yerr`` components included on the\n        diagonal.\n\n        Args:\n            y (array[n] or array[n, nrhs]): The vector or matrix ``y``\n            described above.\n\n        Returns:\n            array[n] or array[n, nrhs]: The solution to the linear system.\n            This will have the same shape as ``y``.\n\n        Raises:\n            ValueError: For mismatched dimensions."
  },
  {
    "code": "def _fetch_data(self):\n        r\n        with h5py.File(self.name + '.hdf5') as f:\n            for item in f.keys():\n                obj_name, propname = item.split('|')\n                propname = propname.split('_')\n                propname = propname[0] + '.' + '_'.join(propname[1:])\n                self[obj_name][propname] = f[item]",
    "docstring": "r\"\"\"\n        Retrieve data from an HDF5 file and place onto correct objects in the\n        project\n\n        See Also\n        --------\n        _dump_data\n\n        Notes\n        -----\n        In principle, after data is fetched from and HDF5 file, it should\n        physically stay there until it's called upon.  This let users manage\n        the data as if it's in memory, even though it isn't.  This behavior\n        has not been confirmed yet, which is why these functions are hidden."
  },
  {
    "code": "def _sync_reminders(self, reminders_json):\n        for reminder_json in reminders_json:\n            reminder_id = reminder_json['id']\n            task_id = reminder_json['item_id']\n            if task_id not in self.tasks:\n                continue\n            task = self.tasks[task_id]\n            self.reminders[reminder_id] = Reminder(reminder_json, task)",
    "docstring": "Populate the user's reminders from a JSON encoded list."
  },
  {
    "code": "def _count_relevant_tb_levels(tb):\n    length = contiguous_unittest_frames = 0\n    while tb:\n        length += 1\n        if _is_unittest_frame(tb):\n            contiguous_unittest_frames += 1\n        else:\n            contiguous_unittest_frames = 0\n        tb = tb.tb_next\n    return length - contiguous_unittest_frames",
    "docstring": "Return the number of frames in ``tb`` before all that's left is unittest frames.\n\n    Unlike its namesake in unittest, this doesn't bail out as soon as it hits a\n    unittest frame, which means we don't bail out as soon as somebody uses the\n    mock library, which defines ``__unittest``."
  },
  {
    "code": "def eglQueryString(display, name):\n    out = _lib.eglQueryString(display, name)\n    if not out:\n        raise RuntimeError('Could not query %s' % name)\n    return out",
    "docstring": "Query string from display"
  },
  {
    "code": "def check_account_address(address):\n    if address == 'treasury' or address == 'unallocated':\n        return True\n    if address.startswith('not_distributed_') and len(address) > len('not_distributed_'):\n        return True\n    if re.match(OP_C32CHECK_PATTERN, address):\n        try:\n            c32addressDecode(address)\n            return True\n        except:\n            pass\n    return check_address(address)",
    "docstring": "verify that a string is a valid account address.\n    Can be a b58-check address, a c32-check address, as well as the string \"treasury\" or \"unallocated\" or a string starting with 'not_distributed_'\n\n    >>> check_account_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg')\n    True\n    >>> check_account_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJh')\n    False\n    >>> check_account_address('treasury')\n    True\n    >>> check_account_address('unallocated')\n    True\n    >>> check_account_address('neither')\n    False\n    >>> check_account_address('not_distributed')\n    False\n    >>> check_account_address('not_distributed_')\n    False\n    >>> check_account_address('not_distributed_asdfasdfasdfasdf')\n    True\n    >>> check_account_address('SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7')\n    True\n    >>> check_account_address('SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ8')\n    False"
  },
  {
    "code": "def service_param_string(params):\r\n    p = []\r\n    k = []\r\n    for param in params:\r\n        name = fix_param_name(param['name'])\r\n        if 'required' in param and param['required'] is True:\r\n            p.append(name)\r\n        else:\r\n            if 'default' in param:\r\n                k.append('{name}={default}'.format(name=name, default=param['default']))\r\n            else:\r\n                k.append('{name}=None'.format(name=name))\r\n    p.sort(lambda a, b: len(a) - len(b))\r\n    k.sort()\r\n    a = p + k\r\n    return ', '.join(a)",
    "docstring": "Takes a param section from a metadata class and returns a param string for the service method"
  },
  {
    "code": "def get_finished_results(self):\n        task_and_results = []\n        for pending_result in self.pending_results:\n            if pending_result.ready():\n                ret = pending_result.get()\n                task_id, result = ret\n                task = self.task_id_to_task[task_id]\n                self.process_all_messages_in_queue()\n                task.after_run(result)\n                task_and_results.append((task, result))\n                self.pending_results.remove(pending_result)\n        return task_and_results",
    "docstring": "Go through pending results and retrieve the results if they are done.\n        Then start child tasks for the task that finished."
  },
  {
    "code": "def _hjoin_multiline(join_char, strings):\n    cstrings = [string.split(\"\\n\") for string in strings]\n    max_num_lines = max(len(item) for item in cstrings)\n    pp = []\n    for k in range(max_num_lines):\n        p = [cstring[k] for cstring in cstrings]\n        pp.append(join_char + join_char.join(p) + join_char)\n    return \"\\n\".join([p.rstrip() for p in pp])",
    "docstring": "Horizontal join of multiline strings"
  },
  {
    "code": "def compile_regex(self, pattern, flags=0):\n        pattern_re = regex.compile('(?P<substr>%\\{(?P<fullname>(?P<patname>\\w+)(?::(?P<subname>\\w+))?)\\})')\n        while 1:\n            matches = [md.groupdict() for md in pattern_re.finditer(pattern)]\n            if len(matches) == 0:\n                break\n            for md in matches:\n                if md['patname'] in self.pattern_dict:\n                    if md['subname']:\n                        if '(?P<' in self.pattern_dict[md['patname']]:\n                            repl = regex.sub('\\(\\?P<(\\w+)>', '(?P<%s>' % md['subname'],\n                                self.pattern_dict[md['patname']], 1)\n                        else:\n                            repl = '(?P<%s>%s)' % (md['subname'], \n                                self.pattern_dict[md['patname']])\n                    else:\n                        repl = self.pattern_dict[md['patname']]\n                    pattern = pattern.replace(md['substr'], repl)\n                else:\n                    return\n        return regex.compile(pattern, flags)",
    "docstring": "Compile regex from pattern and pattern_dict"
  },
  {
    "code": "def make_session(scraper):\n    cache_path = os.path.join(scraper.config.data_path, 'cache')\n    cache_policy = scraper.config.cache_policy\n    cache_policy = cache_policy.lower().strip()\n    session = ScraperSession()\n    session.scraper = scraper\n    session.cache_policy = cache_policy\n    adapter = CacheControlAdapter(\n        FileCache(cache_path),\n        cache_etags=True,\n        controller_class=PolicyCacheController\n    )\n    session.mount('http://', adapter)\n    session.mount('https://', adapter)\n    return session",
    "docstring": "Instantiate a session with the desired configuration parameters,\n    including the cache policy."
  },
  {
    "code": "def limit_inference(iterator, size):\n    yield from islice(iterator, size)\n    has_more = next(iterator, False)\n    if has_more is not False:\n        yield Uninferable\n        return",
    "docstring": "Limit inference amount.\n\n    Limit inference amount to help with performance issues with\n    exponentially exploding possible results.\n\n    :param iterator: Inference generator to limit\n    :type iterator: Iterator(NodeNG)\n\n    :param size: Maximum mount of nodes yielded plus an\n        Uninferable at the end if limit reached\n    :type size: int\n\n    :yields: A possibly modified generator\n    :rtype param: Iterable"
  },
  {
    "code": "def move_to(self, folder):\n        if isinstance(folder, Folder):\n            self.move_to(folder.id)\n        else:\n            self._move_to(folder)",
    "docstring": "Moves the email to the folder specified by the folder parameter.\n\n        Args:\n            folder: A string containing the folder ID the message should be moved to, or a Folder instance"
  },
  {
    "code": "def task_delete(self, **kw):\n        def validate(task):\n            if task['status'] == Status.DELETED:\n                raise ValueError(\"Task is already deleted.\")\n        return self._task_change_status(Status.DELETED, validate, **kw)",
    "docstring": "Marks a task as deleted, optionally specifying a completion\n        date with the 'end' argument."
  },
  {
    "code": "def email(self, name, to, from_addr, subject, body, header, owner=None, **kwargs):\n        return Email(self.tcex, name, to, from_addr, subject, body, header, owner=owner, **kwargs)",
    "docstring": "Create the Email TI object.\n\n        Args:\n            owner:\n            to:\n            from_addr:\n            name:\n            subject:\n            header:\n            body:\n            **kwargs:\n\n        Return:"
  },
  {
    "code": "def task_remove_user(self, *args, **kwargs):\n        if not self.cur_task:\n            return\n        i = self.task_user_tablev.currentIndex()\n        item = i.internalPointer()\n        if item:\n            user = item.internal_data()\n            self.cur_task.users.remove(user)\n            item.set_parent(None)",
    "docstring": "Remove the selected user from the task\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def _filter_by_statement(self, statement):\n        self.__class__._check_conditional_statement(statement, 1)\n        _filt_values, _filt_datetimes = [], []\n        for i, a in enumerate(self._values):\n            if eval(statement, {'a': a}):\n                _filt_values.append(a)\n                _filt_datetimes.append(self.datetimes[i])\n        return _filt_values, _filt_datetimes",
    "docstring": "Filter the data collection based on a conditional statement."
  },
  {
    "code": "def _maybe_append_formatted_extension(numobj, metadata, num_format, number):\n    if numobj.extension:\n        if num_format == PhoneNumberFormat.RFC3966:\n            return number + _RFC3966_EXTN_PREFIX + numobj.extension\n        else:\n            if metadata.preferred_extn_prefix is not None:\n                return number + metadata.preferred_extn_prefix + numobj.extension\n            else:\n                return number + _DEFAULT_EXTN_PREFIX + numobj.extension\n    return number",
    "docstring": "Appends the formatted extension of a phone number to formatted number,\n    if the phone number had an extension specified."
  },
  {
    "code": "def modify(self, **kwargs):\n        for key in kwargs:\n            if key not in ['email', 'cellphone', 'countrycode', 'countryiso',\n                           'defaultsmsprovider', 'directtwitter',\n                           'twitteruser', 'name']:\n                sys.stderr.write(\"'%s'\" % key + ' is not a valid argument ' +\n                                 'of <PingdomContact>.modify()\\n')\n        response = self.pingdom.request('PUT', 'notification_contacts/%s' % self.id, kwargs)\n        return response.json()['message']",
    "docstring": "Modify a contact.\n\n        Returns status message\n\n        Optional Parameters:\n\n            * name -- Contact name\n                    Type: String\n\n            * email -- Contact email address\n                    Type: String\n\n            * cellphone -- Cellphone number, without the country code part. In\n                some countries you are supposed to exclude leading zeroes.\n                (Requires countrycode and countryiso)\n                    Type: String\n\n            * countrycode -- Cellphone country code (Requires cellphone and\n                countryiso)\n                    Type: String\n\n            * countryiso -- Cellphone country ISO code. For example: US (USA),\n                GB (Britain) or SE (Sweden) (Requires cellphone and\n                countrycode)\n                    Type: String\n\n            * defaultsmsprovider -- Default SMS provider\n                    Type: String ['clickatell', 'bulksms', 'esendex',\n                                  'cellsynt']\n\n            * directtwitter -- Send tweets as direct messages\n                    Type: Boolean\n                    Default: True\n\n            * twitteruser -- Twitter user\n                    Type: String"
  },
  {
    "code": "def upload(self, file, path):\n        with open(file, \"rb\") as f:\n            resp = self._sendRequest(\"PUT\", path, data=f)\n            if resp.status_code != 201:\n                raise YaDiskException(resp.status_code, resp.content)",
    "docstring": "Upload file."
  },
  {
    "code": "def use_tsig(self, keyring, keyname=None, fudge=300,\n                 original_id=None, tsig_error=0, other_data='',\n                 algorithm=dns.tsig.default_algorithm):\n        self.keyring = keyring\n        if keyname is None:\n            self.keyname = self.keyring.keys()[0]\n        else:\n            if isinstance(keyname, (str, unicode)):\n                keyname = dns.name.from_text(keyname)\n            self.keyname = keyname\n        self.keyalgorithm = algorithm\n        self.fudge = fudge\n        if original_id is None:\n            self.original_id = self.id\n        else:\n            self.original_id = original_id\n        self.tsig_error = tsig_error\n        self.other_data = other_data",
    "docstring": "When sending, a TSIG signature using the specified keyring\n        and keyname should be added.\n\n        @param keyring: The TSIG keyring to use; defaults to None.\n        @type keyring: dict\n        @param keyname: The name of the TSIG key to use; defaults to None.\n        The key must be defined in the keyring.  If a keyring is specified\n        but a keyname is not, then the key used will be the first key in the\n        keyring.  Note that the order of keys in a dictionary is not defined,\n        so applications should supply a keyname when a keyring is used, unless\n        they know the keyring contains only one key.\n        @type keyname: dns.name.Name or string\n        @param fudge: TSIG time fudge; default is 300 seconds.\n        @type fudge: int\n        @param original_id: TSIG original id; defaults to the message's id\n        @type original_id: int\n        @param tsig_error: TSIG error code; default is 0.\n        @type tsig_error: int\n        @param other_data: TSIG other data.\n        @type other_data: string\n        @param algorithm: The TSIG algorithm to use; defaults to\n        dns.tsig.default_algorithm"
  },
  {
    "code": "def read_requirements(path,\n                      strict_bounds,\n                      conda_format=False,\n                      filter_names=None):\n    real_path = join(dirname(abspath(__file__)), path)\n    with open(real_path) as f:\n        reqs = _filter_requirements(f.readlines(), filter_names=filter_names,\n                                    filter_sys_version=not conda_format)\n        if not strict_bounds:\n            reqs = map(_with_bounds, reqs)\n        if conda_format:\n            reqs = map(_conda_format, reqs)\n        return list(reqs)",
    "docstring": "Read a requirements.txt file, expressed as a path relative to Zipline root.\n\n    Returns requirements with the pinned versions as lower bounds\n    if `strict_bounds` is falsey."
  },
  {
    "code": "def connect_array(self, address, connection_key, connection_type, **kwargs):\n        data = {\"management_address\": address,\n                \"connection_key\": connection_key,\n                \"type\": connection_type}\n        data.update(kwargs)\n        return self._request(\"POST\", \"array/connection\", data)",
    "docstring": "Connect this array with another one.\n\n        :param address: IP address or DNS name of other array.\n        :type address: str\n        :param connection_key: Connection key of other array.\n        :type connection_key: str\n        :param connection_type: Type(s) of connection desired.\n        :type connection_type: list\n        :param \\*\\*kwargs: See the REST API Guide on your array for the\n                           documentation on the request:\n                           **POST array/connection**\n        :type \\*\\*kwargs: optional\n\n        :returns: A dictionary describing the connection to the other array.\n        :rtype: ResponseDict\n\n        .. note::\n\n            Currently, the only type of connection is \"replication\".\n\n        .. note::\n\n            Requires use of REST API 1.2 or later."
  },
  {
    "code": "def _dump(self):\n        try:\n            self.temp.seek(0)\n            arr = np.fromfile(self.temp, self.dtype)\n            self.count_arr = arr['count']\n            self.elapsed_arr = arr['elapsed']\n            if self.calc_stats:\n                self.count_mean = np.mean(self.count_arr)\n                self.count_std = np.std(self.count_arr)\n                self.elapsed_mean = np.mean(self.elapsed_arr)\n                self.elapsed_std = np.std(self.elapsed_arr)\n            self._output()\n        finally:\n            self.temp.close()\n            self._cleanup()",
    "docstring": "dump data for an individual metric. For internal use only."
  },
  {
    "code": "def _avoid_duplicate_arrays(types):\n    arrays = [t for t in types if isinstance(t, dict) and t[\"type\"] == \"array\"]\n    others = [t for t in types if not (isinstance(t, dict) and t[\"type\"] == \"array\")]\n    if arrays:\n        items = set([])\n        for t in arrays:\n            if isinstance(t[\"items\"], (list, tuple)):\n                items |= set(t[\"items\"])\n            else:\n                items.add(t[\"items\"])\n        if len(items) == 1:\n            items = items.pop()\n        else:\n            items = sorted(list(items))\n        arrays = [{\"type\": \"array\", \"items\": items}]\n    return others + arrays",
    "docstring": "Collapse arrays when we have multiple types."
  },
  {
    "code": "def _collect_state_names(self, variable):\n        \"Return a list of states that the variable takes in the data\"\n        states = sorted(list(self.data.ix[:, variable].dropna().unique()))\n        return states",
    "docstring": "Return a list of states that the variable takes in the data"
  },
  {
    "code": "def build_simple_fault_source_node(fault_source):\n    source_nodes = [build_simple_fault_geometry(fault_source)]\n    source_nodes.extend(get_fault_source_nodes(fault_source))\n    return Node(\"simpleFaultSource\",\n                get_source_attributes(fault_source),\n                nodes=source_nodes)",
    "docstring": "Parses a simple fault source to a Node class\n\n    :param fault_source:\n        Simple fault source as instance of :class:\n        `openquake.hazardlib.source.simple_fault.SimpleFaultSource`\n    :returns:\n        Instance of :class:`openquake.baselib.node.Node`"
  },
  {
    "code": "def handle_activity_legacy(_: str, __: int, tokens: ParseResults) -> ParseResults:\n    legacy_cls = language.activity_labels[tokens[MODIFIER]]\n    tokens[MODIFIER] = ACTIVITY\n    tokens[EFFECT] = {\n        NAME: legacy_cls,\n        NAMESPACE: BEL_DEFAULT_NAMESPACE\n    }\n    log.log(5, 'upgraded legacy activity to %s', legacy_cls)\n    return tokens",
    "docstring": "Handle BEL 1.0 activities."
  },
  {
    "code": "def dump_limits(conf_file, limits_file, debug=False):\n    conf = config.Config(conf_file=conf_file)\n    db = conf.get_database()\n    limits_key = conf['control'].get('limits_key', 'limits')\n    lims = [limits.Limit.hydrate(db, msgpack.loads(lim))\n            for lim in db.zrange(limits_key, 0, -1)]\n    root = etree.Element('limits')\n    limit_tree = etree.ElementTree(root)\n    for idx, lim in enumerate(lims):\n        if debug:\n            print >>sys.stderr, \"Dumping limit index %d: %r\" % (idx, lim)\n        make_limit_node(root, lim)\n    if limits_file == '-':\n        limits_file = sys.stdout\n    if debug:\n        print >>sys.stderr, \"Dumping limits to file %r\" % limits_file\n    limit_tree.write(limits_file, xml_declaration=True, encoding='UTF-8',\n                     pretty_print=True)",
    "docstring": "Dump the current limits from the Redis database.\n\n    :param conf_file: Name of the configuration file, for connecting\n                      to the Redis database.\n    :param limits_file: Name of the XML file that the limits will be\n                        dumped to.  Use '-' to dump to stdout.\n    :param debug: If True, debugging messages are emitted while\n                  dumping the limits."
  },
  {
    "code": "def _cache_key_select_state(method, self, workflow_id, field_id, field_title):\n    key = update_timer(), workflow_id, field_id, field_title\n    return key",
    "docstring": "This function returns the key used to decide if select_state has to be recomputed"
  },
  {
    "code": "def iswc(name=None):\n    if name is None:\n        name = 'ISWC Field'\n    field = pp.Regex('T[0-9]{10}')\n    field.setName(name)\n    field.leaveWhitespace()\n    return field.setResultsName('iswc')",
    "docstring": "ISWC field.\n\n    A ISWC code written on a field follows the Pattern TNNNNNNNNNC.\n    This being:\n    - T: header, it is always T.\n    - N: numeric value.\n    - C: control digit.\n\n    So, for example, an ISWC code field can contain T0345246801.\n\n    :param name: name for the field\n    :return: a parser for the ISWC field"
  },
  {
    "code": "def check_valid_package(package,\n                        cyg_arch='x86_64',\n                        mirrors=None):\n    if mirrors is None:\n        mirrors = [{DEFAULT_MIRROR: DEFAULT_MIRROR_KEY}]\n    LOG.debug('Checking Valid Mirrors: %s', mirrors)\n    for mirror in mirrors:\n        for mirror_url, key in mirror.items():\n            if package in _get_all_packages(mirror_url, cyg_arch):\n                return True\n    return False",
    "docstring": "Check if the package is valid on the given mirrors.\n\n    Args:\n        package: The name of the package\n        cyg_arch: The cygwin architecture\n        mirrors: any mirrors to check\n\n    Returns (bool): True if Valid, otherwise False\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' cyg.check_valid_package <package name>"
  },
  {
    "code": "def _get_pdb_format_version(self):\n        if not self.format_version:\n            version = None\n            version_lines = None\n            try:\n                version_lines = [line for line in self.parsed_lines['REMARK'] if int(line[7:10]) == 4 and line[10:].strip()]\n            except: pass\n            if version_lines:\n                assert(len(version_lines) == 1)\n                version_line = version_lines[0]\n                version_regex = re.compile('.*?FORMAT V.(.*),')\n                mtch = version_regex.match(version_line)\n                if mtch and mtch.groups(0):\n                    try:\n                        version = float(mtch.groups(0)[0])\n                    except:\n                        pass\n            self.format_version = version",
    "docstring": "Remark 4 indicates the version of the PDB File Format used to generate the file."
  },
  {
    "code": "def _add_function(self, func, identify_observed):\n        key = self.make_key(func)\n        if key not in self.observers:\n            self.observers[key] = ObserverFunction(\n                func, identify_observed, (key, self.observers))\n            return True\n        else:\n            return False",
    "docstring": "Add a function as an observer.\n\n        Args:\n            func: The function to register as an observer.\n            identify_observed: See docstring for add_observer.\n\n        Returns:\n            True if the function is added, otherwise False."
  },
  {
    "code": "def list_formats(self, node, path=(), formats=None):\n        if formats == None:\n            formats = []\n        for child in node.children:\n            self.list_formats(child, path + (child.name,), formats)\n        path and formats.append(\".\".join(path))\n        return sorted(formats)",
    "docstring": "Lists the object formats in sorted order.\n\n        :param node: Root node to start listing the formats from.\n        :type node: AbstractCompositeNode\n        :param path: Walked paths.\n        :type path: tuple\n        :param formats: Formats.\n        :type formats: list\n        :return: Formats.\n        :rtype: list"
  },
  {
    "code": "def run(self):\n        salt.utils.process.appendproctitle(self.__class__.__name__)\n        self._post_fork_init()\n        last = int(time.time())\n        old_present = set()\n        while True:\n            now = int(time.time())\n            if (now - last) >= self.loop_interval:\n                salt.daemons.masterapi.clean_old_jobs(self.opts)\n                salt.daemons.masterapi.clean_expired_tokens(self.opts)\n                salt.daemons.masterapi.clean_pub_auth(self.opts)\n                salt.daemons.masterapi.clean_proc_dir(self.opts)\n            self.handle_git_pillar()\n            self.handle_schedule()\n            self.handle_key_cache()\n            self.handle_presence(old_present)\n            self.handle_key_rotate(now)\n            salt.utils.verify.check_max_open_files(self.opts)\n            last = now\n            time.sleep(self.loop_interval)",
    "docstring": "This is the general passive maintenance process controller for the Salt\n        master.\n\n        This is where any data that needs to be cleanly maintained from the\n        master is maintained."
  },
  {
    "code": "def delimit(delimiters, content):\n    if len(delimiters) != 2:\n        raise ValueError(\n            \"`delimiters` must be of length 2. Got %r\" % delimiters\n        )\n    return ''.join([delimiters[0], content, delimiters[1]])",
    "docstring": "Surround `content` with the first and last characters of `delimiters`.\n\n    >>> delimit('[]', \"foo\")  # doctest: +SKIP\n    '[foo]'\n    >>> delimit('\"\"', \"foo\")  # doctest: +SKIP\n    '\"foo\"'"
  },
  {
    "code": "def predict(fqdn, result, *argl, **argd):\n    out = None\n    if len(argl) > 0:\n        machine = argl[0]\n        if isclassifier(machine):\n            out = classify_predict(fqdn, result, None, *argl, **argd)\n        elif isregressor(machine):\n            out = regress_predict(fqdn, result, None, *argl, **argd)\n    return out",
    "docstring": "Analyzes the result of a generic predict operation performed by\n    `sklearn`.\n\n    Args:\n        fqdn (str): full-qualified name of the method that was called.\n        result: result of calling the method with `fqdn`.\n        argl (tuple): positional arguments passed to the method call.\n        argd (dict): keyword arguments passed to the method call."
  },
  {
    "code": "async def on_raw_error(self, message):\n        error = protocol.ServerError(' '.join(message.params))\n        await self.on_data_error(error)",
    "docstring": "Server encountered an error and will now close the connection."
  },
  {
    "code": "def dir_list(load):\n    ret = set()\n    files = file_list(load)\n    for f in files:\n        dirname = f\n        while dirname:\n            dirname = os.path.dirname(dirname)\n            if dirname:\n                ret.add(dirname)\n    return list(ret)",
    "docstring": "Return a list of all directories in a specified environment"
  },
  {
    "code": "def _path_is_executable_others(path):\n    prevpath = None\n    while path and path != prevpath:\n        try:\n            if not os.stat(path).st_mode & stat.S_IXOTH:\n                return False\n        except OSError:\n            return False\n        prevpath = path\n        path, _ = os.path.split(path)\n    return True",
    "docstring": "Check every part of path for executable permission"
  },
  {
    "code": "def _recursiveSetNodePath(self, nodePath):\n        self._nodePath = nodePath\n        for childItem in self.childItems:\n            childItem._recursiveSetNodePath(nodePath + '/' + childItem.nodeName)",
    "docstring": "Sets the nodePath property and updates it for all children."
  },
  {
    "code": "def set_iam_policy(self, policy, client=None):\n        client = self._require_client(client)\n        query_params = {}\n        if self.user_project is not None:\n            query_params[\"userProject\"] = self.user_project\n        resource = policy.to_api_repr()\n        resource[\"resourceId\"] = self.path\n        info = client._connection.api_request(\n            method=\"PUT\",\n            path=\"%s/iam\" % (self.path,),\n            query_params=query_params,\n            data=resource,\n            _target_object=None,\n        )\n        return Policy.from_api_repr(info)",
    "docstring": "Update the IAM policy for the bucket.\n\n        See\n        https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy\n\n        If :attr:`user_project` is set, bills the API request to that project.\n\n        :type policy: :class:`google.api_core.iam.Policy`\n        :param policy: policy instance used to update bucket's IAM policy.\n\n        :type client: :class:`~google.cloud.storage.client.Client` or\n                      ``NoneType``\n        :param client: Optional. The client to use.  If not passed, falls back\n                       to the ``client`` stored on the current bucket.\n\n        :rtype: :class:`google.api_core.iam.Policy`\n        :returns: the policy instance, based on the resource returned from\n                  the ``setIamPolicy`` API request."
  },
  {
    "code": "def iconGlyph(self):\n        if self._h5Dataset.attrs.get('CLASS', None) == b'DIMENSION_SCALE':\n            return RtiIconFactory.DIMENSION\n        else:\n            return RtiIconFactory.ARRAY",
    "docstring": "Shows an Array icon for regular datasets but a dimension icon for dimension scales"
  },
  {
    "code": "def add_handler(self, handler: Handler, group: int = 0):\n        if isinstance(handler, DisconnectHandler):\n            self.disconnect_handler = handler.callback\n        else:\n            self.dispatcher.add_handler(handler, group)\n        return handler, group",
    "docstring": "Use this method to register an update handler.\n\n        You can register multiple handlers, but at most one handler within a group\n        will be used for a single update. To handle the same update more than once, register\n        your handler using a different group id (lower group id == higher priority).\n\n        Args:\n            handler (``Handler``):\n                The handler to be registered.\n\n            group (``int``, *optional*):\n                The group identifier, defaults to 0.\n\n        Returns:\n            A tuple of (handler, group)"
  },
  {
    "code": "def extract_archive(client, archive_path, extract_path=None):\n    command = 'tar -xf {path}'.format(path=archive_path)\n    if extract_path:\n        command += ' -C {extract_path}'.format(extract_path=extract_path)\n    out = execute_ssh_command(client, command)\n    return out",
    "docstring": "Extract the archive in current path using the provided client.\n\n    If extract_path is provided extract the archive there."
  },
  {
    "code": "def _load_image_set_index(self, shuffle):\n        self.num_images = 0\n        for db in self.imdbs:\n            self.num_images += db.num_images\n        indices = list(range(self.num_images))\n        if shuffle:\n            random.shuffle(indices)\n        return indices",
    "docstring": "get total number of images, init indices\n\n        Parameters\n        ----------\n        shuffle : bool\n            whether to shuffle the initial indices"
  },
  {
    "code": "def substitute(self, var_map, cont=False, tag=None):\n        return self.apply(substitute, var_map=var_map, cont=cont, tag=tag)",
    "docstring": "Substitute sub-expressions both on the lhs and rhs\n\n        Args:\n            var_map (dict): Dictionary with entries of the form\n                ``{expr: substitution}``"
  },
  {
    "code": "def query(self, queryString):\n    self._setHeaders('query')\n    return self._sforce.service.query(queryString)",
    "docstring": "Executes a query against the specified object and returns data that matches\n    the specified criteria."
  },
  {
    "code": "def push_fbo(self, fbo, offset, csize):\n        self._fb_stack.append((fbo, offset, csize))\n        try:\n            fbo.activate()\n            h, w = fbo.color_buffer.shape[:2]\n            self.push_viewport((0, 0, w, h))\n        except Exception:\n            self._fb_stack.pop()\n            raise\n        self._update_transforms()",
    "docstring": "Push an FBO on the stack.\n        \n        This activates the framebuffer and causes subsequent rendering to be\n        written to the framebuffer rather than the canvas's back buffer. This\n        will also set the canvas viewport to cover the boundaries of the \n        framebuffer.\n\n        Parameters\n        ----------\n        fbo : instance of FrameBuffer\n            The framebuffer object .\n        offset : tuple\n            The location of the fbo origin relative to the canvas's framebuffer\n            origin.\n        csize : tuple\n            The size of the region in the canvas's framebuffer that should be \n            covered by this framebuffer object."
  },
  {
    "code": "def profile_remove(name, **kwargs):\n    ctx = Context(**kwargs)\n    ctx.execute_action('profile:remove', **{\n        'storage': ctx.repo.create_secure_service('storage'),\n        'name': name,\n    })",
    "docstring": "Remove profile from the storage."
  },
  {
    "code": "def add_group(self, group_attribs=None, parent=None):\n        if parent is None:\n            parent = self.tree.getroot()\n        elif not self.contains_group(parent):\n            warnings.warn('The requested group {0} does not belong to '\n                          'this Document'.format(parent))\n        if group_attribs is None:\n            group_attribs = {}\n        else:\n            group_attribs = group_attribs.copy()\n        return SubElement(parent, '{{{0}}}g'.format(\n            SVG_NAMESPACE['svg']), group_attribs)",
    "docstring": "Add an empty group element to the SVG."
  },
  {
    "code": "def get_image_format(filename):\n    image = None\n    bad_image = 1\n    image_format = NONE_FORMAT\n    sequenced = False\n    try:\n        bad_image = Image.open(filename).verify()\n        image = Image.open(filename)\n        image_format = image.format\n        sequenced = _is_image_sequenced(image)\n    except (OSError, IOError, AttributeError):\n        pass\n    if sequenced:\n        image_format = gif.SEQUENCED_TEMPLATE.format(image_format)\n    elif image is None or bad_image or image_format == NONE_FORMAT:\n        image_format = ERROR_FORMAT\n        comic_format = comic.get_comic_format(filename)\n        if comic_format:\n            image_format = comic_format\n        if (Settings.verbose > 1) and image_format == ERROR_FORMAT and \\\n                (not Settings.list_only):\n            print(filename, \"doesn't look like an image or comic archive.\")\n    return image_format",
    "docstring": "Get the image format."
  },
  {
    "code": "def get_minimum(self, other):\n        return Point(min(self.x, other.x), min(self.y, other.y))",
    "docstring": "Updates this vector so its components are the lower of its\n        current components and those of the given other value."
  },
  {
    "code": "def userdata_to_db(session, method='update', autocommit=False):\n    try:\n        folder = config['import']['folder']\n    except KeyError:\n        return\n    if folder:\n        folder_to_db(folder, session, method=method, autocommit=autocommit)",
    "docstring": "Add catchments from a user folder to the database.\n\n    The user folder is specified in the ``config.ini`` file like this::\n\n        [import]\n        folder = path/to/import/folder\n\n    If this configuration key does not exist this will be silently ignored.\n\n    :param session: database session to use, typically `floodestimation.db.Session()`\n    :type session: :class:`sqlalchemy.orm.session.Session`\n    :param method: - ``create``: only new catchments will be loaded, it must not already exist in the database.\n                   - ``update``: any existing catchment in the database will be updated. Otherwise it will be created.\n    :type method: str\n    :param autocommit: Whether to commit the database session immediately. Default: ``False``.\n    :type autocommit: bool"
  },
  {
    "code": "def InjectString(self, codestring, wait_for_completion=True):\n    if self.inferior.is_running and self.inferior.gdb.IsAttached():\n      try:\n        self.inferior.gdb.InjectString(\n            self.inferior.position,\n            codestring,\n            wait_for_completion=wait_for_completion)\n      except RuntimeError:\n        exc_type, exc_value, exc_traceback = sys.exc_info()\n        traceback.print_exception(exc_type, exc_value, exc_traceback)\n    else:\n      logging.error('Not attached to any process.')",
    "docstring": "Try to inject python code into current thread.\n\n    Args:\n      codestring: Python snippet to execute in inferior. (may contain newlines)\n      wait_for_completion: Block until execution of snippet has completed."
  },
  {
    "code": "def activation_done(self, *args, **kwargs):\n        if self._save:\n            self.save_task()\n        else:\n            super().activation_done(*args, **kwargs)",
    "docstring": "Complete the ``activation`` or save only, depending on form submit."
  },
  {
    "code": "def system_properties_absent(name, server=None):\n    ret = {'name': '', 'result': None, 'comment': None, 'changes': {}}\n    try:\n        data = __salt__['glassfish.get_system_properties'](server=server)\n    except requests.ConnectionError as error:\n        if __opts__['test']:\n            ret['changes'] = {'Name': name}\n            ret['result'] = None\n            return ret\n        else:\n            ret['error'] = \"Can't connect to the server\"\n            return ret\n    if name in data:\n        if not __opts__['test']:\n            try:\n                __salt__['glassfish.delete_system_properties'](name, server=server)\n                ret['result'] = True\n                ret['comment'] = 'System properties deleted'\n            except CommandExecutionError as error:\n                ret['comment'] = error\n                ret['result'] = False\n        else:\n            ret['result'] = None\n            ret['comment'] = 'System properties would have been deleted'\n        ret['changes'] = {'Name': name}\n    else:\n        ret['result'] = True\n        ret['comment'] = 'System properties are already absent'\n    return ret",
    "docstring": "Ensures that the system property doesn't exists\n\n    name\n        Name of the system property"
  },
  {
    "code": "def interpolate_where(self, condition):\n        raise NotImplementedError()\n        self[self < 0] = np.nan\n        return self.interpolate()",
    "docstring": "Remove then interpolate across"
  },
  {
    "code": "def get_collections_for_image(self, image_id):\n        result = []\n        for document in self.collection.find({'active' : True, 'images.identifier' : image_id}):\n            result.append(str(document['_id']))\n        return result",
    "docstring": "Get identifier of all collections that contain a given image.\n\n        Parameters\n        ----------\n        image_id : string\n            Unique identifierof image object\n\n        Returns\n        -------\n        List(string)\n            List of image collection identifier"
  },
  {
    "code": "def contigs_to_positions(contigs, binning=10000):\n    positions = np.zeros_like(contigs)\n    index = 0\n    for _, chunk in itertools.groubpy(contigs):\n        l = len(chunk)\n        positions[index : index + l] = np.arange(list(chunk)) * binning\n        index += l\n    return positions",
    "docstring": "Build positions from contig labels\n\n    From a list of contig labels and a binning parameter,\n    build a list of positions that's essentially a\n    concatenation of linspaces with step equal to the\n    binning.\n\n    Parameters\n    ----------\n    contigs : list or array_like\n        The list of contig labels, must be sorted.\n    binning : int, optional\n        The step for the list of positions. Default is 10000.    \n    \n    Returns\n    -------\n    positions : numpy.ndarray\n        The piece-wise sorted list of positions"
  },
  {
    "code": "def update_token_tempfile(token):\n    with open(tmp, 'w') as f:\n        f.write(json.dumps(token, indent=4))",
    "docstring": "Example of function for token update"
  },
  {
    "code": "def get_value(repo_directory, key, expect_type=None):\n    config = read_config(repo_directory)\n    value = config.get(key)\n    if expect_type and value is not None and not isinstance(value, expect_type):\n        raise ConfigSchemaError('Expected config variable %s to be type %s, got %s'\n            % (repr(key), repr(expect_type), repr(type(value))))\n    return value",
    "docstring": "Gets the value of the specified key in the config file."
  },
  {
    "code": "def max_substring(words, position=0, _last_letter=''):\n    try:\n        letter = [word[position] for word in words]\n    except IndexError:\n        return _last_letter\n    if all(l == letter[0] for l in letter) is True:\n        _last_letter += max_substring(words, position=position + 1,\n                                      _last_letter=letter[0])\n        return _last_letter\n    else:\n        return _last_letter",
    "docstring": "Finds max substring shared by all strings starting at position\n\n    Args:\n\n        words (list): list of unicode of all words to compare\n\n        position (int): starting position in each word to begin analyzing\n                        for substring\n\n        _last_letter (unicode): last common letter, only for use\n                                internally unless you really know what\n                                you are doing\n\n    Returns:\n        unicode: max str common to all words\n\n    Examples:\n        .. code-block:: Python\n\n            >>> max_substring(['aaaa', 'aaab', 'aaac'])\n            'aaa'\n            >>> max_substring(['abbb', 'bbbb', 'cbbb'], position=1)\n            'bbb'\n            >>> max_substring(['abc', 'bcd', 'cde'])\n            ''"
  },
  {
    "code": "def find_single(decl_matcher, decls, recursive=True):\n        answer = matcher.find(decl_matcher, decls, recursive)\n        if len(answer) == 1:\n            return answer[0]",
    "docstring": "Returns a reference to the declaration, that match `decl_matcher`\n        defined criteria.\n\n        if a unique declaration could not be found the method will return None.\n\n        :param decl_matcher: Python callable object, that takes one argument -\n            reference to a declaration\n        :param decls: the search scope, :class:declaration_t object or\n            :class:declaration_t objects list t\n        :param recursive: boolean, if True, the method will run `decl_matcher`\n            on the internal declarations too"
  },
  {
    "code": "def addIndividual(self, individual):\n        id_ = individual.getId()\n        self._individualIdMap[id_] = individual\n        self._individualIds.append(id_)\n        self._individualNameMap[individual.getName()] = individual",
    "docstring": "Adds the specified individual to this dataset."
  },
  {
    "code": "def cmdscale_fast(D, ndim):\n    tasklogger.log_debug(\"Performing classic MDS on {} of shape {}...\".format(\n        type(D).__name__, D.shape))\n    D = D**2\n    D = D - D.mean(axis=0)[None, :]\n    D = D - D.mean(axis=1)[:, None]\n    pca = PCA(n_components=ndim, svd_solver='randomized')\n    Y = pca.fit_transform(D)\n    return Y",
    "docstring": "Fast CMDS using random SVD\n\n    Parameters\n    ----------\n    D : array-like, input data [n_samples, n_dimensions]\n\n    ndim : int, number of dimensions in which to embed `D`\n\n    Returns\n    -------\n    Y : array-like, embedded data [n_sample, ndim]"
  },
  {
    "code": "def get_torrent(self, torrent_id):\n        params = {\n            'page': 'download',\n            'tid': torrent_id,\n        }\n        r = requests.get(self.base_url, params=params)\n        if r.headers.get('content-type') != 'application/x-bittorrent':\n            raise TorrentNotFoundError(TORRENT_NOT_FOUND_TEXT)\n        torrent_data = r.content\n        return Torrent(torrent_id, torrent_data)",
    "docstring": "Gets the `.torrent` data for the given `torrent_id`.\n\n        :param torrent_id: the ID of the torrent to download\n        :raises TorrentNotFoundError: if the torrent does not exist\n        :returns: :class:`Torrent` of the associated torrent"
  },
  {
    "code": "def invalidate(self, key, **kw):\n        self.impl.invalidate(key, **self._get_cache_kw(kw, None))",
    "docstring": "Invalidate a value in the cache.\n\n        :param key: the value's key.\n        :param \\**kw: cache configuration arguments.  The\n         backend is configured using these arguments upon first request.\n         Subsequent requests that use the same series of configuration\n         values will use that same backend."
  },
  {
    "code": "def type(self):\n        \"The type of elements stored in the mapping.\"\n        if self._type is None and len(self):\n            self._type = self.values()[0].__class__\n        return self._type",
    "docstring": "The type of elements stored in the mapping."
  },
  {
    "code": "def frame_to_latents(frame, hparams):\n  frame = preprocess_frame(frame)\n  glow_vals = glow_ops.encoder_decoder(\n      \"codec\", frame, hparams, eps=None, reverse=False)\n  z_top, _, level_eps, _, _ = glow_vals\n  return z_top, level_eps",
    "docstring": "Encode frames to latents."
  },
  {
    "code": "def _chooseBestSegmentPerColumn(cls, connections, matchingCells,\n                                  allMatchingSegments, potentialOverlaps,\n                                  cellsPerColumn):\n    candidateSegments = connections.filterSegmentsByCell(allMatchingSegments,\n                                                         matchingCells)\n    cellScores = potentialOverlaps[candidateSegments]\n    columnsForCandidates = (connections.mapSegmentsToCells(candidateSegments) /\n                            cellsPerColumn)\n    onePerColumnFilter = np2.argmaxMulti(cellScores, columnsForCandidates)\n    learningSegments = candidateSegments[onePerColumnFilter]\n    return learningSegments",
    "docstring": "For all the columns covered by 'matchingCells', choose the column's matching\n    segment with largest number of active potential synapses. When there's a\n    tie, the first segment wins.\n\n    @param connections (SparseMatrixConnections)\n    @param matchingCells (numpy array)\n    @param allMatchingSegments (numpy array)\n    @param potentialOverlaps (numpy array)"
  },
  {
    "code": "def zremrangebylex(self, key, min=b'-', max=b'+',\n                       include_min=True, include_max=True):\n        if not isinstance(min, bytes):\n            raise TypeError(\"min argument must be bytes\")\n        if not isinstance(max, bytes):\n            raise TypeError(\"max argument must be bytes\")\n        if not min == b'-':\n            min = (b'[' if include_min else b'(') + min\n        if not max == b'+':\n            max = (b'[' if include_max else b'(') + max\n        return self.execute(b'ZREMRANGEBYLEX', key, min, max)",
    "docstring": "Remove all members in a sorted set between the given\n        lexicographical range.\n\n        :raises TypeError: if min is not bytes\n        :raises TypeError: if max is not bytes"
  },
  {
    "code": "def list_assets_ddo(self):\n        return json.loads(self.requests_session.get(self.url).content)",
    "docstring": "List all the ddos registered in the aquarius instance.\n\n        :return: List of DDO instance"
  },
  {
    "code": "def _check_whitespace(string):\n    if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n        raise ValueError(INSTRUCTION_HAS_WHITESPACE)",
    "docstring": "Make sure thre is no whitespace in the given string. Will raise a\n    ValueError if whitespace is detected"
  },
  {
    "code": "def beacon(config):\n    ret = []\n    _refresh = False\n    pkgs = []\n    for config_item in config:\n        if 'pkgs' in config_item:\n            pkgs += config_item['pkgs']\n        if 'refresh' in config and config['refresh']:\n            _refresh = True\n    for pkg in pkgs:\n        _installed = __salt__['pkg.version'](pkg)\n        _latest = __salt__['pkg.latest_version'](pkg, refresh=_refresh)\n        if _installed and _latest:\n            _pkg = {'pkg': pkg,\n                    'version': _latest\n                    }\n            ret.append(_pkg)\n    return ret",
    "docstring": "Check if installed packages are the latest versions\n    and fire an event for those that have upgrades.\n\n    .. code-block:: yaml\n\n        beacons:\n          pkg:\n            - pkgs:\n                - zsh\n                - apache2\n            - refresh: True"
  },
  {
    "code": "def _handle_tag_module_refresh(self, tag, data):\n        self.module_refresh(\n            force_refresh=data.get('force_refresh', False),\n            notify=data.get('notify', False)\n        )",
    "docstring": "Handle a module_refresh event"
  },
  {
    "code": "def connect(self, id):\n        schema = ConnectionSchema()\n        resp = self.service.post(self.base+str(id)+'/connect/')\n        return self.service.decode(schema, resp)",
    "docstring": "Open proxy connection to a device's management interface.\n\n        :param id: Device ID as an int.\n        :return: :class:`devices.Connection <devices.Connection>` object\n        :rtype: devices.Connection"
  },
  {
    "code": "def result(self):\n        for _ in range(self.num_threads):\n            self.tasks_queue.put(None)\n        self.tasks_queue.join()\n        if not self.exceptions_queue.empty():\n            raise self.exceptions_queue.get()\n        return self.results_queue",
    "docstring": "Stop threads and return the result of all called tasks"
  },
  {
    "code": "def raftery_lewis(x, q, r, s=.95, epsilon=.001, verbose=1):\n    if np.ndim(x) > 1:\n        return [raftery_lewis(y, q, r, s, epsilon, verbose)\n                for y in np.transpose(x)]\n    output = nmin, kthin, nburn, nprec, kmind = flib.gibbmain(\n        x, q, r, s, epsilon)\n    if verbose:\n        print_(\"\\n========================\")\n        print_(\"Raftery-Lewis Diagnostic\")\n        print_(\"========================\")\n        print_()\n        print_(\n            \"%s iterations required (assuming independence) to achieve %s accuracy with %i percent probability.\" %\n            (nmin, r, 100 * s))\n        print_()\n        print_(\n            \"Thinning factor of %i required to produce a first-order Markov chain.\" %\n            kthin)\n        print_()\n        print_(\n            \"%i iterations to be discarded at the beginning of the simulation (burn-in).\" %\n            nburn)\n        print_()\n        print_(\"%s subsequent iterations required.\" % nprec)\n        print_()\n        print_(\n            \"Thinning factor of %i required to produce an independence chain.\" %\n            kmind)\n    return output",
    "docstring": "Return the number of iterations needed to achieve a given\n    precision.\n\n    :Parameters:\n        x : sequence\n            Sampled series.\n        q : float\n            Quantile.\n        r : float\n            Accuracy requested for quantile.\n        s (optional) : float\n            Probability of attaining the requested accuracy (defaults to 0.95).\n        epsilon (optional) : float\n             Half width of the tolerance interval required for the q-quantile (defaults to 0.001).\n        verbose (optional) : int\n            Verbosity level for output (defaults to 1).\n\n    :Return:\n        nmin : int\n            Minimum number of independent iterates required to achieve\n            the specified accuracy for the q-quantile.\n        kthin : int\n            Skip parameter sufficient to produce a first-order Markov\n            chain.\n        nburn : int\n            Number of iterations to be discarded at the beginning of the\n            simulation, i.e. the number of burn-in iterations.\n        nprec : int\n            Number of iterations not including the burn-in iterations which\n            need to be obtained in order to attain the precision specified\n            by the values of the q, r and s input parameters.\n        kmind : int\n            Minimum skip parameter sufficient to produce an independence\n            chain.\n\n    :Example:\n        >>> raftery_lewis(x, q=.025, r=.005)\n\n    :Reference:\n        Raftery, A.E. and Lewis, S.M. (1995).  The number of iterations,\n        convergence diagnostics and generic Metropolis algorithms.  In\n        Practical Markov Chain Monte Carlo (W.R. Gilks, D.J. Spiegelhalter\n        and S. Richardson, eds.). London, U.K.: Chapman and Hall.\n\n        See the fortran source file `gibbsit.f` for more details and references."
  },
  {
    "code": "def toFloatArray(img):\r\n    _D = {1: np.float32,\n          2: np.float32,\n          4: np.float64,\n          8: np.float64}\n    return img.astype(_D[img.itemsize])",
    "docstring": "transform an unsigned integer array into a\r\n    float array of the right size"
  },
  {
    "code": "def packageInfo(self):\n        url = \"%s/item.pkinfo\" % self.root\n        params = {'f' : 'json'}\n        result = self._get(url=url,\n                           param_dict=params,\n                           securityHandler=self._securityHandler,\n                           proxy_url=self._proxy_url,\n                           proxy_port=self._proxy_port,\n                           out_folder=tempfile.gettempdir())\n        return result",
    "docstring": "gets the item's package information file"
  },
  {
    "code": "def _image2array(filepath):\n    im = Pimage.open(filepath).convert('RGB')\n    (width, height) = im.size\n    _r = np.array(list(im.getdata(0)))/255.0\n    _g = np.array(list(im.getdata(1)))/255.0\n    _b = np.array(list(im.getdata(2)))/255.0\n    _r = _r.reshape((height, width))\n    _g = _g.reshape((height, width))\n    _b = _b.reshape((height, width))\n    return _r, _g, _b",
    "docstring": "Utility function that converts an image file in 3 np arrays\n    that can be fed into geo_image.GeoImage in order to generate\n    a PyTROLL GeoImage object."
  },
  {
    "code": "def defer(callable):\n    t = threading.Thread(target=callable)\n    t.start()\n    return t.join",
    "docstring": "Defers execution of the callable to a thread.\n\n    For example:\n\n        >>> def foo():\n        ...     print('bar')\n        >>> join = defer(foo)\n        >>> join()"
  },
  {
    "code": "def delete(args):\n  jm = setup(args)\n  if not args.local and 'executing' in args.status:\n    stop(args)\n  jm.delete(job_ids=get_ids(args.job_ids), array_ids=get_ids(args.array_ids), delete_logs=not args.keep_logs, delete_log_dir=not args.keep_log_dir, status=args.status)",
    "docstring": "Deletes the jobs from the job manager. If the jobs are still running in the grid, they are stopped."
  },
  {
    "code": "def extant_item(arg, arg_type):\n    if arg_type == \"file\":\n        if not os.path.isfile(arg):\n            raise argparse.ArgumentError(\n                None,\n                \"The file {arg} does not exist.\".format(arg=arg))\n        else:\n            return arg\n    elif arg_type == \"directory\":\n        if not os.path.isdir(arg):\n            raise argparse.ArgumentError(\n                None,\n                \"The directory {arg} does not exist.\".format(arg=arg))\n        else:\n            return arg",
    "docstring": "Determine if parser argument is an existing file or directory.\n\n    This technique comes from http://stackoverflow.com/a/11541450/95592\n    and from http://stackoverflow.com/a/11541495/95592\n\n    Args:\n        arg: parser argument containing filename to be checked\n        arg_type: string of either \"file\" or \"directory\"\n\n    Returns:\n        If the file exists, return the filename or directory.\n\n    Raises:\n        If the file does not exist, raise a parser error."
  },
  {
    "code": "def search_document_cache_key(self):\n        return \"elasticsearch_django:{}.{}.{}\".format(\n            self._meta.app_label, self._meta.model_name, self.pk\n        )",
    "docstring": "Key used for storing search docs in local cache."
  },
  {
    "code": "def shuffle_characters(s):\n    s = list(s)\n    random.shuffle(s)\n    s =''.join(s)\n    return s",
    "docstring": "Randomly shuffle the characters in a string"
  },
  {
    "code": "def text2sentences(text, labels):\n    sentence = ''\n    for i, label in enumerate(labels):\n        if label == '1':\n            if sentence:\n                yield sentence\n            sentence = ''\n        else:\n            sentence += text[i]\n    if sentence:\n        yield sentence",
    "docstring": "Splits given text at predicted positions from `labels`"
  },
  {
    "code": "def get_connections(self, id, connection_name, **args):\n        return self.request(\n            \"{0}/{1}/{2}\".format(self.version, id, connection_name), args\n        )",
    "docstring": "Fetches the connections for given object."
  },
  {
    "code": "def prjs_view_prj(self, *args, **kwargs):\n        i = self.prjs_tablev.currentIndex()\n        item = i.internalPointer()\n        if item:\n            prj = item.internal_data()\n            self.view_prj(prj)",
    "docstring": "View the, in the projects table view selected, project.\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def next(self):\n        outgoing_msg = self.outgoing_msg_list.pop_first()\n        if outgoing_msg is None:\n            self.outgoing_msg_event.clear()\n            self.outgoing_msg_event.wait()\n            outgoing_msg = self.outgoing_msg_list.pop_first()\n        return outgoing_msg",
    "docstring": "Pops and returns the first outgoing message from the list.\n\n        If message list currently has no messages, the calling thread will\n        be put to sleep until we have at-least one message in the list that\n        can be popped and returned."
  },
  {
    "code": "def inverse_deriv(self, z):\n        return np.power(z, (1 - self.power)/self.power) / self.power",
    "docstring": "Derivative of the inverse of the power transform\n\n        Parameters\n        ----------\n        z : array-like\n            `z` is usually the linear predictor for a GLM or GEE model.\n\n        Returns\n        -------\n        g^(-1)'(z) : array\n            The value of the derivative of the inverse of the power transform\n        function"
  },
  {
    "code": "def copy_without_prompts(self):\r\n        text = self.get_selected_text()\r\n        lines = text.split(os.linesep)\r\n        for index, line in enumerate(lines):\r\n            if line.startswith('>>> ') or line.startswith('... '):\r\n                lines[index] = line[4:]\r\n        text = os.linesep.join(lines)\r\n        QApplication.clipboard().setText(text)",
    "docstring": "Copy text to clipboard without prompts"
  },
  {
    "code": "def plot(self):\n        try:\n            import matplotlib.pyplot as plt\n        except ImportError:\n            from sys import stderr\n            print(\"ERROR: matplotlib.pyplot not found, matplotlib must be installed to use this function\", file=stderr)\n            raise\n        x_min = np.min(self.knot_vector)\n        x_max = np.max(self.knot_vector)\n        x = np.linspace(x_min, x_max, num=1000)\n        N = np.array([self(i) for i in x]).T\n        for n in N:\n            plt.plot(x,n)\n        return plt.show()",
    "docstring": "Plot basis functions over full range of knots.\n\n        Convenience function. Requires matplotlib."
  },
  {
    "code": "def _find_module_ptr(self, module_ptr):\n        ptr = cast(module_ptr, c_void_p).value\n        for module in self._modules:\n            if cast(module._ptr, c_void_p).value == ptr:\n                return module\n        return None",
    "docstring": "Find the ModuleRef corresponding to the given pointer."
  },
  {
    "code": "def _estimateCubicCurveLength(pt0, pt1, pt2, pt3, precision=10):\n    points = []\n    length = 0\n    step = 1.0 / precision\n    factors = range(0, precision + 1)\n    for i in factors:\n        points.append(_getCubicPoint(i * step, pt0, pt1, pt2, pt3))\n    for i in range(len(points) - 1):\n        pta = points[i]\n        ptb = points[i + 1]\n        length += _distance(pta, ptb)\n    return length",
    "docstring": "Estimate the length of this curve by iterating\n    through it and averaging the length of the flat bits."
  },
  {
    "code": "def write_to_screen(self, screen, mouse_handlers, write_position,\n                        parent_style, erase_bg, z_index):\n        \" Fill the whole area of write_position with dots. \"\n        default_char = Char(' ', 'class:background')\n        dot = Char('.', 'class:background')\n        ypos = write_position.ypos\n        xpos = write_position.xpos\n        for y in range(ypos, ypos + write_position.height):\n            row = screen.data_buffer[y]\n            for x in range(xpos, xpos + write_position.width):\n                row[x] = dot if (x + y) % 3 == 0 else default_char",
    "docstring": "Fill the whole area of write_position with dots."
  },
  {
    "code": "def strip_suffix(id):\n    suffix = get_suffix(id)\n    if not suffix:\n        return id\n    return re.split(suffix, id)[0]",
    "docstring": "Split off any suffix from ID\n\n    This mimics the old behavior of the Sample ID."
  },
  {
    "code": "def _credit_card_type(self, card_type=None):\n        if card_type is None:\n            card_type = self.random_element(self.credit_card_types.keys())\n        elif isinstance(card_type, CreditCard):\n            return card_type\n        return self.credit_card_types[card_type]",
    "docstring": "Returns a random credit card type instance."
  },
  {
    "code": "def get_collection(self, **kwargs):\n        list_of_contents = []\n        self.refresh(**kwargs)\n        if 'items' in self.__dict__:\n            for item in self.items:\n                if 'kind' not in item:\n                    list_of_contents.append(item)\n                    continue\n                kind = item['kind']\n                if kind in self._meta_data['attribute_registry']:\n                    instance = self._meta_data['attribute_registry'][kind](self)\n                    instance._local_update(item)\n                    instance._activate_URI(instance.selfLink)\n                    list_of_contents.append(instance)\n                else:\n                    error_message = '%r is not registered!' % kind\n                    raise UnregisteredKind(error_message)\n        return list_of_contents",
    "docstring": "Get an iterator of Python ``Resource`` objects that represent URIs.\n\n        The returned objects are Pythonic `Resource`s that map to the most\n        recently `refreshed` state of uris-resources published by the device.\n        In order to instantiate the correct types, the concrete subclass must\n        populate its registry with acceptable types, based on the `kind` field\n        returned by the REST server.\n\n        .. note::\n            This method implies a single REST transaction with the\n            Collection subclass URI.\n\n        :raises: UnregisteredKind\n        :returns: list of reference dicts and Python ``Resource`` objects"
  },
  {
    "code": "def required_arguments(func):\n    defaults = default_values_of(func)\n    args = arguments_of(func)\n    if defaults:\n        args = args[:-len(defaults)]\n    return args",
    "docstring": "Return all arguments of a function that do not have a default value."
  },
  {
    "code": "def create(cls, name, protocol_number, protocol_agent=None, comment=None):\n        json = {'name': name,\n                'protocol_number': protocol_number,\n                'protocol_agent_ref': element_resolver(protocol_agent) or None,\n                'comment': comment}\n        return ElementCreator(cls, json)",
    "docstring": "Create the IP Service\n\n        :param str name: name of ip-service\n        :param int protocol_number: ip proto number for this service\n        :param str,ProtocolAgent protocol_agent: optional protocol agent for\n            this service\n        :param str comment: optional comment\n        :raises CreateElementFailed: failure creating element with reason\n        :return: instance with meta\n        :rtype: IPService"
  },
  {
    "code": "def hget(self, key):\n        data = self.r.hget(self.hash, key)\n        if data is not None and not isinstance(data, str):\n            data = str(self.r.hget(self.hash, key), 'utf-8')\n        return data",
    "docstring": "Read data from Redis for the provided key.\n\n        Args:\n            key (string): The key to read in Redis.\n\n        Returns:\n            (any): The response data from Redis."
  },
  {
    "code": "def initialize_directories(self, root_dir):\n        if not root_dir:\n            root_dir = os.path.expanduser('~')\n        self.config_dir = os.path.join(root_dir, '.config/pueue')\n        if not os.path.exists(self.config_dir):\n            os.makedirs(self.config_dir)",
    "docstring": "Create all directories needed for logs and configs."
  },
  {
    "code": "def CheckRegistryKey(javaKey):\n\t\tfrom _winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx\n\t\tpath = None\n\t\ttry:\n\t\t\taReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)\n\t\t\trk = OpenKey(aReg, javaKey)\n\t\t\tfor i in range(1024):\n\t\t\t\tcurrentVersion = QueryValueEx(rk, \"CurrentVersion\")\n\t\t\t\tif currentVersion != None:\n\t\t\t\t\tkey = OpenKey(rk, currentVersion[0])\n\t\t\t\t\tif key != None:\n\t\t\t\t\t\tpath = QueryValueEx(key, \"JavaHome\")\n\t\t\t\t\t\treturn path[0]\n\t\texcept Exception, err:\n\t\t\tWriteUcsWarning(\"Not able to access registry.\")\n\t\t\treturn None",
    "docstring": "Method checks for the java in the registry entries."
  },
  {
    "code": "def reach_max_num(self):\n        if self.signal.get('reach_max_num'):\n            return True\n        if self.max_num > 0 and self.fetched_num >= self.max_num:\n            return True\n        else:\n            return False",
    "docstring": "Check if downloaded images reached max num.\n\n        Returns:\n            bool: if downloaded images reached max num."
  },
  {
    "code": "def default_working_dir():\n    import nameset.virtualchain_hooks as virtualchain_hooks\n    return os.path.expanduser('~/.{}'.format(virtualchain_hooks.get_virtual_chain_name()))",
    "docstring": "Get the default configuration directory for blockstackd"
  },
  {
    "code": "def build_request_include(include, params):\n    params = params or OrderedDict()\n    if include is not None:\n        params['include'] = ','.join([cls._resource_type() for cls in include])\n    return params",
    "docstring": "Augment request parameters with includes.\n\n    When one or all resources are requested an additional set of\n    resources can be requested as part of the request. This function\n    extends the given parameters for a request with a list of resource\n    types passed in as a list of :class:`Resource` subclasses.\n\n    Args:\n\n        include([Resource class]): A list of resource classes to include\n\n        params(dict): The (optional) dictionary of request parameters to extend\n\n    Returns:\n\n        An updated or new dictionary of parameters extended with an\n        include query parameter."
  },
  {
    "code": "def remove_leading_garbage_lines_from_reference_section(ref_sectn):\n    p_email = re.compile(ur'^\\s*e\\-?mail', re.UNICODE)\n    while ref_sectn and (ref_sectn[0].isspace() or p_email.match(ref_sectn[0])):\n        ref_sectn.pop(0)\n    return ref_sectn",
    "docstring": "Sometimes, the first lines of the extracted references are completely\n       blank or email addresses. These must be removed as they are not\n       references.\n       @param ref_sectn: (list) of strings - the reference section lines\n       @return: (list) of strings - the reference section without leading\n        blank lines or email addresses."
  },
  {
    "code": "def __conn_listener(self, state):\n        if state == KazooState.CONNECTED:\n            self.__online = True\n            if not self.__connected:\n                self.__connected = True\n                self._logger.info(\"Connected to ZooKeeper\")\n                self._queue.enqueue(self.on_first_connection)\n            else:\n                self._logger.warning(\"Re-connected to ZooKeeper\")\n                self._queue.enqueue(self.on_client_reconnection)\n        elif state == KazooState.SUSPENDED:\n            self._logger.warning(\"Connection suspended\")\n            self.__online = False\n        elif state == KazooState.LOST:\n            self.__online = False\n            self.__connected = False\n            if self.__stop:\n                self._logger.info(\"Disconnected from ZooKeeper (requested)\")\n            else:\n                self._logger.warning(\"Connection lost\")",
    "docstring": "Connection event listener\n\n        :param state: The new connection state"
  },
  {
    "code": "def get_pinned_version(ireq):\n    try:\n        specifier = ireq.specifier\n    except AttributeError:\n        raise TypeError(\"Expected InstallRequirement, not {}\".format(\n            type(ireq).__name__,\n        ))\n    if ireq.editable:\n        raise ValueError(\"InstallRequirement is editable\")\n    if not specifier:\n        raise ValueError(\"InstallRequirement has no version specification\")\n    if len(specifier._specs) != 1:\n        raise ValueError(\"InstallRequirement has multiple specifications\")\n    op, version = next(iter(specifier._specs))._spec\n    if op not in ('==', '===') or version.endswith('.*'):\n        raise ValueError(\"InstallRequirement not pinned (is {0!r})\".format(\n            op + version,\n        ))\n    return version",
    "docstring": "Get the pinned version of an InstallRequirement.\n\n    An InstallRequirement is considered pinned if:\n\n    - Is not editable\n    - It has exactly one specifier\n    - That specifier is \"==\"\n    - The version does not contain a wildcard\n\n    Examples:\n        django==1.8   # pinned\n        django>1.8    # NOT pinned\n        django~=1.8   # NOT pinned\n        django==1.*   # NOT pinned\n\n    Raises `TypeError` if the input is not a valid InstallRequirement, or\n    `ValueError` if the InstallRequirement is not pinned."
  },
  {
    "code": "def type_check(self, filename):\n        self.log.debug('type_check: in')\n        self.editor.clean_errors()\n        self.send_request(\n            {\"typehint\": \"TypecheckFilesReq\",\n             \"files\": [self.editor.path()]})",
    "docstring": "Update type checking when user saves buffer."
  },
  {
    "code": "def predict_from_design_matrix(self, design_matrix):\n        assert hasattr(self, 'betas'), 'no betas found, please run regression before prediction'\n        assert design_matrix.shape[0] == self.betas.shape[0], \\\n                    'designmatrix needs to have the same number of regressors as the betas already calculated'\n        prediction = np.dot(self.betas.astype(np.float32).T, design_matrix.astype(np.float32))\n        return prediction",
    "docstring": "predict_from_design_matrix predicts signals given a design matrix.\n\n            :param design_matrix: design matrix from which to predict a signal.\n            :type design_matrix: numpy array, (nr_samples x betas.shape)\n            :returns: predicted signal(s) \n            :rtype: numpy array (nr_signals x nr_samples)"
  },
  {
    "code": "def decr(name, value=1, rate=1, tags=None):\n    client().decr(name, value, rate, tags)",
    "docstring": "Decrement a metric by value.\n\n    >>> import statsdecor\n    >>> statsdecor.decr('my.metric')"
  },
  {
    "code": "def save(self, png_file):\n        with open(png_file, 'wb') as f:\n            f.write(self._repr_png_())",
    "docstring": "Save png to disk.\n\n        Parameters\n        ----------\n        png_file : path to file\n            file to write to\n\n        Notes\n        -----\n        It relies on _repr_png_, so fix issues there."
  },
  {
    "code": "def has(self, querypart_name, value=None):\n        querypart = self._queryparts.get(querypart_name)\n        if not querypart:\n            return False\n        if not querypart.is_set:\n            return False\n        if value:\n            return querypart.has(value)\n        return True",
    "docstring": "Returns True if `querypart_name` with `value` is set.\n\n        For example you can check if you already used condition by `sql.has('where')`.\n\n        If you want to check for more information, for example if that condition\n        also contain ID, you can do this by `sql.has('where', 'id')`."
  },
  {
    "code": "def get_next_invalid_day(self, timestamp):\n        if self.is_time_day_invalid(timestamp):\n            return timestamp\n        next_future_timerange_invalid = self.get_next_future_timerange_invalid(timestamp)\n        if next_future_timerange_invalid is None:\n            (start_time, end_time) = self.get_start_and_end_time(get_day(timestamp))\n        else:\n            (start_time, end_time) = self.get_start_and_end_time(timestamp)\n        if next_future_timerange_invalid is not None:\n            if start_time <= timestamp <= end_time:\n                return get_day(timestamp)\n            if start_time >= timestamp:\n                return get_day(start_time)\n        else:\n            return get_day(end_time + 1)\n        return None",
    "docstring": "Get next day where timerange is not active\n\n        :param timestamp: time we compute from\n        :type timestamp: int\n        :return: timestamp of the next invalid day (midnight) in LOCAL time.\n        :rtype: int | None"
  },
  {
    "code": "def steadystate(A, max_iter=100):\n    P = np.linalg.matrix_power(A, max_iter)\n    v = []\n    for i in range(len(P)):\n        if not np.any([np.allclose(P[i], vi, ) for vi in v]):\n            v.append(P[i])\n    return normalize(np.sum(v, axis=0))",
    "docstring": "Empirically determine the steady state probabilities from a stochastic matrix"
  },
  {
    "code": "def open(self):\n        self.startTime = datetime.datetime.now()\n        self.offset = 0\n        return self",
    "docstring": "Reset time and counts."
  },
  {
    "code": "def _on_connection_finished(self, result):\n        success, retval, context = self._parse_return(result)\n        conn_id = context['connection_id']\n        callback = context['callback']\n        if success is False:\n            callback(conn_id, self.id, False, 'Timeout opening connection')\n            with self.count_lock:\n                self.connecting_count -= 1\n            return\n        handle = retval['handle']\n        context['disconnect_handler'] = self._on_connection_failed\n        context['connect_time'] = time.time()\n        context['state'] = 'preparing'\n        self._connections[handle] = context\n        self.probe_services(handle, conn_id, self._probe_services_finished)",
    "docstring": "Callback when the connection attempt to a BLE device has finished\n\n        This function if called when a new connection is successfully completed\n\n        Args:\n            event (BGAPIPacket): Connection event"
  },
  {
    "code": "def predict_proba(self, X):\n        y_probas = []\n        bce_logits_loss = isinstance(\n            self.criterion_, torch.nn.BCEWithLogitsLoss)\n        for yp in self.forward_iter(X, training=False):\n            yp = yp[0] if isinstance(yp, tuple) else yp\n            if bce_logits_loss:\n                yp = torch.sigmoid(yp)\n            y_probas.append(to_numpy(yp))\n        y_proba = np.concatenate(y_probas, 0)\n        return y_proba",
    "docstring": "Where applicable, return probability estimates for\n        samples.\n\n        If the module's forward method returns multiple outputs as a\n        tuple, it is assumed that the first output contains the\n        relevant information and the other values are ignored. If all\n        values are relevant, consider using\n        :func:`~skorch.NeuralNet.forward` instead.\n\n        Parameters\n        ----------\n        X : input data, compatible with skorch.dataset.Dataset\n          By default, you should be able to pass:\n\n            * numpy arrays\n            * torch tensors\n            * pandas DataFrame or Series\n            * scipy sparse CSR matrices\n            * a dictionary of the former three\n            * a list/tuple of the former three\n            * a Dataset\n\n          If this doesn't work with your data, you have to pass a\n          ``Dataset`` that can deal with the data.\n\n        Returns\n        -------\n        y_proba : numpy ndarray"
  },
  {
    "code": "def kill_cursors(self, cursor_ids, address=None):\n        warnings.warn(\n            \"kill_cursors is deprecated.\",\n            DeprecationWarning,\n            stacklevel=2)\n        if not isinstance(cursor_ids, list):\n            raise TypeError(\"cursor_ids must be a list\")\n        self.__kill_cursors_queue.append((address, cursor_ids))",
    "docstring": "DEPRECATED - Send a kill cursors message soon with the given ids.\n\n        Raises :class:`TypeError` if `cursor_ids` is not an instance of\n        ``list``.\n\n        :Parameters:\n          - `cursor_ids`: list of cursor ids to kill\n          - `address` (optional): (host, port) pair of the cursor's server.\n            If it is not provided, the client attempts to close the cursor on\n            the primary or standalone, or a mongos server.\n\n        .. versionchanged:: 3.3\n           Deprecated.\n\n        .. versionchanged:: 3.0\n           Now accepts an `address` argument. Schedules the cursors to be\n           closed on a background thread instead of sending the message\n           immediately."
  },
  {
    "code": "def load(cls, path):\n        data = json.load(open(path))\n        weights = data['weights']\n        weights = np.asarray(weights, dtype=np.float64)\n        s = cls(data['num_neurons'],\n                data['data_dimensionality'],\n                data['params']['lr']['orig'],\n                neighborhood=data['params']['infl']['orig'],\n                valfunc=data['valfunc'],\n                argfunc=data['argfunc'],\n                lr_lambda=data['params']['lr']['factor'],\n                nb_lambda=data['params']['nb']['factor'])\n        s.weights = weights\n        s.trained = True\n        return s",
    "docstring": "Load a SOM from a JSON file saved with this package.\n\n        Parameters\n        ----------\n        path : str\n            The path to the JSON file.\n\n        Returns\n        -------\n        s : cls\n            A som of the specified class."
  },
  {
    "code": "def get_uri(endpoint_context, request, uri_type):\n    if uri_type in request:\n        verify_uri(endpoint_context, request, uri_type)\n        uri = request[uri_type]\n    else:\n        try:\n            _specs = endpoint_context.cdb[\n                str(request[\"client_id\"])][\"{}s\".format(uri_type)]\n        except KeyError:\n            raise ParameterError(\n                \"Missing {} and none registered\".format(uri_type))\n        else:\n            if len(_specs) > 1:\n                raise ParameterError(\n                    \"Missing {} and more than one registered\".format(uri_type))\n            else:\n                uri = join_query(*_specs[0])\n    return uri",
    "docstring": "verify that the redirect URI is reasonable\n\n    :param endpoint_context:\n    :param request: The Authorization request\n    :param uri_type: 'redirect_uri' or 'post_logout_redirect_uri'\n    :return: redirect_uri"
  },
  {
    "code": "def set_hparams_from_args(args):\n  if not args:\n    return\n  hp_prefix = \"--hp_\"\n  tf.logging.info(\"Found unparsed command-line arguments. Checking if any \"\n                  \"start with %s and interpreting those as hparams \"\n                  \"settings.\", hp_prefix)\n  pairs = []\n  i = 0\n  while i < len(args):\n    arg = args[i]\n    if arg.startswith(hp_prefix):\n      pairs.append((arg[len(hp_prefix):], args[i+1]))\n      i += 2\n    else:\n      tf.logging.warn(\"Found unknown flag: %s\", arg)\n      i += 1\n  as_hparams = \",\".join([\"%s=%s\" % (key, val) for key, val in pairs])\n  if FLAGS.hparams:\n    as_hparams = \",\" + as_hparams\n  FLAGS.hparams += as_hparams",
    "docstring": "Set hparams overrides from unparsed args list."
  },
  {
    "code": "def metadata(self, key=None, database=None, table=None, fallback=True):\n        assert not (database is None and table is not None), \\\n            \"Cannot call metadata() with table= specified but not database=\"\n        databases = self._metadata.get(\"databases\") or {}\n        search_list = []\n        if database is not None:\n            search_list.append(databases.get(database) or {})\n        if table is not None:\n            table_metadata = (\n                (databases.get(database) or {}).get(\"tables\") or {}\n            ).get(table) or {}\n            search_list.insert(0, table_metadata)\n        search_list.append(self._metadata)\n        if not fallback:\n            search_list = search_list[:1]\n        if key is not None:\n            for item in search_list:\n                if key in item:\n                    return item[key]\n            return None\n        else:\n            m = {}\n            for item in search_list:\n                m.update(item)\n            return m",
    "docstring": "Looks up metadata, cascading backwards from specified level.\n        Returns None if metadata value is not found."
  },
  {
    "code": "def main(self, *args, **kwargs):\n        try:\n            result = super().main(*args, **kwargs)\n            return result\n        except Exception:\n            if HAS_SENTRY:\n                self._handle_sentry()\n            if not (sys.stdin.isatty() and sys.stdout.isatty()):\n                raise\n            self._handle_github()",
    "docstring": "Catch all exceptions."
  },
  {
    "code": "def lease(self, items):\n        self._manager.leaser.add(items)\n        self._manager.maybe_pause_consumer()",
    "docstring": "Add the given messages to lease management.\n\n        Args:\n            items(Sequence[LeaseRequest]): The items to lease."
  },
  {
    "code": "def soft_error(self, message):\n        self.print_usage(sys.stderr)\n        args = {'prog': self.prog, 'message': message}\n        self._print_message(\n            _('%(prog)s: error: %(message)s\\n') % args, sys.stderr)",
    "docstring": "Same as error, without the dying in a fire part."
  },
  {
    "code": "def entryCheck(self, event = None, repair = True):\n        valupr = self.choice.get().upper()\n        if valupr.strip() == 'INDEF':\n            self.choice.set(valupr)\n        return EparOption.entryCheck(self, event, repair = repair)",
    "docstring": "Ensure any INDEF entry is uppercase, before base class behavior"
  },
  {
    "code": "def wrap(self, methodName, types, skip=2):\n        def handler(fields):\n            try:\n                args = [\n                    field if typ is str else\n                    int(field or 0) if typ is int else\n                    float(field or 0) if typ is float else\n                    bool(int(field or 0))\n                    for (typ, field) in zip(types, fields[skip:])]\n                method(*args)\n            except Exception:\n                self.logger.exception(f'Error for {methodName}:')\n        method = getattr(self.wrapper, methodName, None)\n        return handler if method else lambda *args: None",
    "docstring": "Create a message handler that invokes a wrapper method\n        with the in-order message fields as parameters, skipping over\n        the first ``skip`` fields, and parsed according to the ``types`` list."
  },
  {
    "code": "def vequ(v1):\n    v1 = stypes.toDoubleVector(v1)\n    vout = stypes.emptyDoubleVector(3)\n    libspice.vequ_c(v1, vout)\n    return stypes.cVectorToPython(vout)",
    "docstring": "Make one double precision 3-dimensional vector equal to another.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vequ_c.html\n\n    :param v1: 3-dimensional double precision vector. \n    :type v1: 3-Element Array of floats\n    :return: 3-dimensional double precision vector set equal to vin.\n    :rtype: 3-Element Array of floats"
  },
  {
    "code": "async def register(self):\n        url = '{}/Sessions'.format(self.construct_url(API_URL))\n        params = {'api_key': self._api_key}\n        reg = await self.api_request(url, params)\n        if reg is None:\n            self._registered = False\n            _LOGGER.error('Unable to register emby client.')\n        else:\n            self._registered = True\n            _LOGGER.info('Emby client registered!, Id: %s', self.unique_id)\n            self._sessions = reg\n            self.update_device_list(self._sessions)\n            asyncio.ensure_future(self.socket_connection(), loop=self._event_loop)",
    "docstring": "Register library device id and get initial device list."
  },
  {
    "code": "def determine_device(kal_out):\n    device = \"\"\n    while device == \"\":\n        for line in kal_out.splitlines():\n            if \"Using device \" in line:\n                device = str(line.split(' ', 2)[-1])\n        if device == \"\":\n            device = None\n    return device",
    "docstring": "Extract and return device from scan results."
  },
  {
    "code": "def wrap(self, availWidth, availHeight):\n        self.avWidth = availWidth\n        self.avHeight = availHeight\n        logger.debug(\"*** wrap (%f, %f)\", availWidth, availHeight)\n        if not self.text:\n            logger.debug(\"*** wrap (%f, %f) needed\", 0, 0)\n            return 0, 0\n        width = availWidth\n        self.splitIndex = self.text.splitIntoLines(width, availHeight)\n        self.width, self.height = availWidth, self.text.height\n        logger.debug(\"*** wrap (%f, %f) needed, splitIndex %r\", self.width, self.height, self.splitIndex)\n        return self.width, self.height",
    "docstring": "Determine the rectangle this paragraph really needs."
  },
  {
    "code": "def _http_get(self, url):\n        for try_number in range(self._http_retries + 1):\n            response = requests.get(url, timeout=self._http_timeout)\n            if response.status_code == 200:\n                return response\n            if (try_number >= self._http_retries or\n                    response.status_code not in (408, 500, 502, 503, 504)):\n                if response.status_code >= 500:\n                    raise PythonKCMeetupsMeetupDown(response, response.content)\n                if response.status_code == 400:\n                    try:\n                        data = json.loads(response.content)\n                        if data.get('code', None) == 'limit':\n                            raise PythonKCMeetupsRateLimitExceeded\n                    except:\n                        pass\n                raise PythonKCMeetupsBadResponse(response, response.content)",
    "docstring": "Make an HTTP GET request to the specified URL and return the response.\n\n        Retries\n        -------\n        The constructor of this class takes an argument specifying the number\n        of times to retry a GET. The statuses which are retried on are: 408,\n        500, 502, 503, and 504.\n\n        Returns\n        -------\n        An HTTP response, containing response headers and content.\n\n        Exceptions\n        ----------\n        * PythonKCMeetupsBadResponse\n        * PythonKCMeetupsMeetupDown\n        * PythonKCMeetupsRateLimitExceeded"
  },
  {
    "code": "def stop_running_tasks(self):\n\t\tfor task in self.__running_registry:\n\t\t\ttask.stop()\n\t\tself.__running_registry.clear()",
    "docstring": "Terminate all the running tasks\n\n\t\t:return: None"
  },
  {
    "code": "def list_vmss(access_token, subscription_id, resource_group):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/resourceGroups/', resource_group,\n                        '/providers/Microsoft.Compute/virtualMachineScaleSets',\n                        '?api-version=', COMP_API])\n    return do_get_next(endpoint, access_token)",
    "docstring": "List VM Scale Sets in a resource group.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n        resource_group (str): Azure resource group name.\n\n    Returns:\n        HTTP response. JSON body of a list of scale set model views."
  },
  {
    "code": "def to_indices(self, tokens):\n        to_reduce = False\n        if not isinstance(tokens, list):\n            tokens = [tokens]\n            to_reduce = True\n        indices = [self.token_to_idx[token] if token in self.token_to_idx\n                   else C.UNKNOWN_IDX for token in tokens]\n        return indices[0] if to_reduce else indices",
    "docstring": "Converts tokens to indices according to the vocabulary.\n\n\n        Parameters\n        ----------\n        tokens : str or list of strs\n            A source token or tokens to be converted.\n\n\n        Returns\n        -------\n        int or list of ints\n            A token index or a list of token indices according to the vocabulary."
  },
  {
    "code": "def is_autosomal(chrom):\n    try:\n        int(chrom)\n        return True\n    except ValueError:\n        try:\n            int(str(chrom.lower().replace(\"chr\", \"\").replace(\"_\", \"\").replace(\"-\", \"\")))\n            return True\n        except ValueError:\n            return False",
    "docstring": "Keep chromosomes that are a digit 1-22, or chr prefixed digit chr1-chr22"
  },
  {
    "code": "def next(self):\n        if self.r == self.repeats:\n            self.i = (self.i + 1) % self.lenght\n            self.r = 0\n        self.r += 1\n        if self.stopping and self.i == 0 and self.r == 1:\n            self.stopped = True\n        if self.i == 0 and self.stopped:\n            raise StopIteration\n        else:\n            iterator = self.iterators[self.i]\n            return iterator.next()",
    "docstring": "Returns the next element or raises ``StopIteration`` if stopped."
  },
  {
    "code": "def _get_hit(self, key):\n        try:\n            result = self.cache[key]\n            self.hits += 1\n            self._ref_key(key)\n            return result\n        except KeyError:\n            pass\n        result = self.weakrefs[key]\n        self.refhits += 1\n        self.cache[key] = result\n        self._ref_key(key)\n        return result",
    "docstring": "Try to do a value lookup from the existing cache entries."
  },
  {
    "code": "def encode_collection(collection):\r\n    tree = etree.Element('collection')\r\n    etree.SubElement(tree, 'source').text = collection.source\r\n    etree.SubElement(tree, 'date').text = collection.date\r\n    etree.SubElement(tree, 'key').text = collection.key\r\n    encode_infons(tree, collection.infons)\r\n    for doc in collection.documents:\r\n        tree.append(encode_document(doc))\r\n    return tree",
    "docstring": "Encode a single collection."
  },
  {
    "code": "def retrieve_api_token(self):\n        payload = self.oauth2_manager.get_access_token_params(\n            refresh_token=self.refresh_token\n        )\n        response = requests.post(\n            self.oauth2_manager.access_token_url, json=payload\n        )\n        response.raise_for_status()\n        response_json = json.loads(response.text)\n        return response_json['access_token']",
    "docstring": "Retrieve the access token from AVS.\n\n        This function is memoized, so the\n        value returned by the function will be remembered and returned by\n        subsequent calls until the memo expires. This is because the access\n        token lasts for one hour, then a new token needs to be requested.\n\n        Decorators:\n            helpers.expiring_memo\n\n        Returns:\n            str -- The access token for communicating with AVS"
  },
  {
    "code": "def http_basic_auth_login_required(func=None):\n    wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_authenticated])\n    if func is None:\n        return wrapper\n    return wrapper(func)",
    "docstring": "Decorator. Use it to specify a RPC method is available only to logged users"
  },
  {
    "code": "def nextComment(self, text, start=0):\n        m = min([self.lineComment(text, start),\n                 self.blockComment(text, start),\n                 self._emptylineregex.search(text, start)],\n                key=lambda m: m.start(0) if m else len(text))\n        return m",
    "docstring": "Return the next comment found in text starting at start."
  },
  {
    "code": "def _snap_exec(commands):\n    assert type(commands) == list\n    retry_count = 0\n    return_code = None\n    while return_code is None or return_code == SNAP_NO_LOCK:\n        try:\n            return_code = subprocess.check_call(['snap'] + commands,\n                                                env=os.environ)\n        except subprocess.CalledProcessError as e:\n            retry_count += + 1\n            if retry_count > SNAP_NO_LOCK_RETRY_COUNT:\n                raise CouldNotAcquireLockException(\n                    'Could not aquire lock after {} attempts'\n                    .format(SNAP_NO_LOCK_RETRY_COUNT))\n            return_code = e.returncode\n            log('Snap failed to acquire lock, trying again in {} seconds.'\n                .format(SNAP_NO_LOCK_RETRY_DELAY, level='WARN'))\n            sleep(SNAP_NO_LOCK_RETRY_DELAY)\n    return return_code",
    "docstring": "Execute snap commands.\n\n    :param commands: List commands\n    :return: Integer exit code"
  },
  {
    "code": "def guest_get_info(self, userid):\n        action = \"get info of guest '%s'\" % userid\n        with zvmutils.log_and_reraise_sdkbase_error(action):\n            return self._vmops.get_info(userid)",
    "docstring": "Get the status of a virtual machine.\n\n        :param str userid: the id of the virtual machine\n\n        :returns: Dictionary contains:\n                  power_state: (str) the running state, one of on | off\n                  max_mem_kb: (int) the maximum memory in KBytes allowed\n                  mem_kb: (int) the memory in KBytes used by the instance\n                  num_cpu: (int) the number of virtual CPUs for the instance\n                  cpu_time_us: (int) the CPU time used in microseconds"
  },
  {
    "code": "def tdSensor(self):\n        protocol = create_string_buffer(20)\n        model = create_string_buffer(20)\n        sid = c_int()\n        datatypes = c_int()\n        self._lib.tdSensor(protocol, sizeof(protocol), model, sizeof(model),\n                           byref(sid), byref(datatypes))\n        return {'protocol': self._to_str(protocol),\n                'model': self._to_str(model),\n                'id': sid.value, 'datatypes': datatypes.value}",
    "docstring": "Get the next sensor while iterating.\n\n        :return: a dict with the keys: protocol, model, id, datatypes."
  },
  {
    "code": "def _get_separated_values(self, secondary=False):\n        series = self.secondary_series if secondary else self.series\n        transposed = list(zip(*[serie.values for serie in series]))\n        positive_vals = [\n            sum([val for val in vals if val is not None and val >= self.zero])\n            for vals in transposed\n        ]\n        negative_vals = [\n            sum([val for val in vals if val is not None and val < self.zero])\n            for vals in transposed\n        ]\n        return positive_vals, negative_vals",
    "docstring": "Separate values between positives and negatives stacked"
  },
  {
    "code": "def supervised_to_dict(dataset, text2self):\n  def my_fn(inputs, targets):\n    if text2self:\n      return {\"targets\": targets}\n    else:\n      return {\"inputs\": inputs, \"targets\": targets}\n  return dataset.map(my_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)",
    "docstring": "Turns a supervised dataset into a dataset with a feature dictionary.\n\n  if text2self, then the features dictionary contains a \"targets\" key.\n  else, the features dictionary contains \"inputs\" and \"targets\" keys.\n\n  Args:\n    dataset: a tf.data.Dataset\n    text2self: a boolean\n  Returns:\n    a tf.data.Dataset"
  },
  {
    "code": "def decimal_precision(row):\n    try:\n        row = list(row)\n        for idx, x in enumerate(row):\n            x = str(x)\n            m = re.match(re_sci_notation, x)\n            if m:\n                _x2 = round(float(m.group(2)), 3)\n                x = m.group(1) + str(_x2)[1:] + m.group(3)\n            else:\n                try:\n                    x = round(float(x), 3)\n                except (ValueError, TypeError):\n                    x = x\n            row[idx] = x\n        row = tuple(row)\n    except Exception as e:\n        print(\"Error: Unable to fix the precision of values. File size may be larger than normal, {}\".format(e))\n    return row",
    "docstring": "Change the \"precision\" of values before writing to CSV. Each value is rounded to 3 numbers.\n\n    ex: 300 -> 300\n    ex: 300.123456 -> 300.123\n    ex: 3.123456e-25 - > 3.123e-25\n\n    :param tuple row: Row of numbers to process\n    :return list row: Processed row"
  },
  {
    "code": "def requirements(self, requires):\n        if requires:\n            if isinstance(requires, basestring) and \\\n               os.path.isfile(os.path.abspath(requires)):\n                self._requirements_file = os.path.abspath(requires)\n            else:\n                if isinstance(self._requirements, basestring):\n                    requires = requires.split()\n                self._requirements_file = None\n                self._requirements = requires\n        else:\n            if os.path.isfile(self._requirements_file):\n                return\n            self._requirements, self._requirements_file = None, None",
    "docstring": "Sets the requirements for the package.\n\n        It will take either a valid path to a requirements file or\n        a list of requirements."
  },
  {
    "code": "def add_subgraph(self, sgraph):\n        if not isinstance(sgraph, Subgraph) and not isinstance(sgraph, Cluster):\n            raise TypeError('add_subgraph() received a non subgraph class object:' + str(sgraph))\n        if self.obj_dict['subgraphs'].has_key(sgraph.get_name()):\n            sgraph_list = self.obj_dict['subgraphs'][ sgraph.get_name() ]\n            sgraph_list.append( sgraph.obj_dict )\n        else:\n            self.obj_dict['subgraphs'][ sgraph.get_name() ] = [ sgraph.obj_dict ]\n        sgraph.set_sequence( self.get_next_sequence_number() )\n        sgraph.set_parent_graph( self.get_parent_graph() )",
    "docstring": "Adds an subgraph object to the graph.\n        \n        It takes a subgraph object as its only argument and returns\n        None."
  },
  {
    "code": "def has_trivial_constructor(class_):\n    class_ = class_traits.get_declaration(class_)\n    trivial = find_trivial_constructor(class_)\n    if trivial and trivial.access_type == 'public':\n        return trivial",
    "docstring": "if class has public trivial constructor, this function will return\n    reference to it, None otherwise"
  },
  {
    "code": "def _reset_internal(self):\n        super()._reset_internal()\n        self.sim.data.qpos[self._ref_joint_pos_indexes] = self.mujoco_robot.init_qpos\n        if self.has_gripper_right:\n            self.sim.data.qpos[\n                self._ref_joint_gripper_right_actuator_indexes\n            ] = self.gripper_right.init_qpos\n        if self.has_gripper_left:\n            self.sim.data.qpos[\n                self._ref_joint_gripper_left_actuator_indexes\n            ] = self.gripper_left.init_qpos",
    "docstring": "Resets the pose of the arm and grippers."
  },
  {
    "code": "def _make_indices(self, Ns):\n        N_new = int(Ns * self.n_splits)\n        test = [np.full(N_new, False) for i in range(self.n_splits)]\n        for i in range(self.n_splits):\n            test[i][np.arange(Ns * i, Ns * (i + 1))] = True\n        train = [np.logical_not(test[i]) for i in range(self.n_splits)]\n        test = [np.arange(N_new)[test[i]] for i in range(self.n_splits)]\n        train = [np.arange(N_new)[train[i]] for i in range(self.n_splits)]\n        cv = list(zip(train, test))\n        return cv",
    "docstring": "makes indices for cross validation"
  },
  {
    "code": "def parseEvent(self, result, i):\n        fmt = '%Y-%m-%dT%H:%M:%SZ'\n        due = 0\n        delay = 0\n        real_time = 'n'\n        number = result['stopEvents'][i]['transportation']['number']\n        planned = datetime.strptime(result['stopEvents'][i]\n            ['departureTimePlanned'], fmt)\n        destination = result['stopEvents'][i]['transportation']['destination']['name']\n        mode = self.get_mode(result['stopEvents'][i]['transportation']['product']['class'])\n        estimated = planned\n        if 'isRealtimeControlled' in result['stopEvents'][i]:\n            real_time = 'y'\n            estimated = datetime.strptime(result['stopEvents'][i]\n                ['departureTimeEstimated'], fmt)\n        if estimated > datetime.utcnow():\n            due = self.get_due(estimated)\n            delay = self.get_delay(planned, estimated)\n            return[\n                number,\n                due,\n                delay,\n                planned,\n                estimated,\n                real_time,\n                destination,\n                mode\n                ]\n        else:\n            return None",
    "docstring": "Parse the current event and extract data."
  },
  {
    "code": "def ensure_connectable(self, nailgun):\n    attempt_count = 1\n    while 1:\n      try:\n        with closing(nailgun.try_connect()) as sock:\n          logger.debug('Verified new ng server is connectable at {}'.format(sock.getpeername()))\n          return\n      except nailgun.NailgunConnectionError:\n        if attempt_count >= self._connect_attempts:\n          logger.debug('Failed to connect to ng after {} attempts'.format(self._connect_attempts))\n          raise\n      attempt_count += 1\n      time.sleep(self.WAIT_INTERVAL_SEC)",
    "docstring": "Ensures that a nailgun client is connectable or raises NailgunError."
  },
  {
    "code": "def _get_userprofile_from_registry(user, sid):\n    profile_dir = __utils__['reg.read_value'](\n        'HKEY_LOCAL_MACHINE',\n        'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\ProfileList\\\\{0}'.format(sid),\n        'ProfileImagePath'\n    )['vdata']\n    log.debug(\n        'user %s with sid=%s profile is located at \"%s\"',\n        user, sid, profile_dir\n    )\n    return profile_dir",
    "docstring": "In case net user doesn't return the userprofile we can get it from the\n    registry\n\n    Args:\n        user (str): The user name, used in debug message\n\n        sid (str): The sid to lookup in the registry\n\n    Returns:\n        str: Profile directory"
  },
  {
    "code": "def number(self, p_todo):\n        if config().identifiers() == \"text\":\n            return self.uid(p_todo)\n        else:\n            return self.linenumber(p_todo)",
    "docstring": "Returns the line number or text ID of a todo (depends on the\n        configuration."
  },
  {
    "code": "def chunkreverse(integers, dtype='L'):\n    if dtype in ('B', 8):\n        return map(RBYTES.__getitem__, integers)\n    fmt = '{0:0%db}' % NBITS[dtype]\n    return (int(fmt.format(chunk)[::-1], 2) for chunk in integers)",
    "docstring": "Yield integers of dtype bit-length reverting their bit-order.\n\n    >>> list(chunkreverse([0b10000000, 0b11000000, 0b00000001], 'B'))\n    [1, 3, 128]\n\n    >>> list(chunkreverse([0x8000, 0xC000, 0x0001], 'H'))\n    [1, 3, 32768]"
  },
  {
    "code": "def keygrip_curve25519(vk):\n    return _compute_keygrip([\n        ['p', util.num2bytes(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED, size=32)],\n        ['a', b'\\x01\\xDB\\x41'],\n        ['b', b'\\x01'],\n        ['g', util.num2bytes(0x04000000000000000000000000000000000000000000000000000000000000000920ae19a1b8a086b4e01edd2c7748d14c923d4d7e6d7c61b229e9c5a27eced3d9, size=65)],\n        ['n', util.num2bytes(0x1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED, size=32)],\n        ['q', vk.to_bytes()],\n    ])",
    "docstring": "Compute keygrip for Curve25519 public keys."
  },
  {
    "code": "def search_uris(\n        self,\n        uri,\n        threat_types,\n        retry=google.api_core.gapic_v1.method.DEFAULT,\n        timeout=google.api_core.gapic_v1.method.DEFAULT,\n        metadata=None,\n    ):\n        if \"search_uris\" not in self._inner_api_calls:\n            self._inner_api_calls[\n                \"search_uris\"\n            ] = google.api_core.gapic_v1.method.wrap_method(\n                self.transport.search_uris,\n                default_retry=self._method_configs[\"SearchUris\"].retry,\n                default_timeout=self._method_configs[\"SearchUris\"].timeout,\n                client_info=self._client_info,\n            )\n        request = webrisk_pb2.SearchUrisRequest(uri=uri, threat_types=threat_types)\n        return self._inner_api_calls[\"search_uris\"](\n            request, retry=retry, timeout=timeout, metadata=metadata\n        )",
    "docstring": "This method is used to check whether a URI is on a given threatList.\n\n        Example:\n            >>> from google.cloud import webrisk_v1beta1\n            >>> from google.cloud.webrisk_v1beta1 import enums\n            >>>\n            >>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client()\n            >>>\n            >>> # TODO: Initialize `uri`:\n            >>> uri = ''\n            >>>\n            >>> # TODO: Initialize `threat_types`:\n            >>> threat_types = []\n            >>>\n            >>> response = client.search_uris(uri, threat_types)\n\n        Args:\n            uri (str): The URI to be checked for matches.\n            threat_types (list[~google.cloud.webrisk_v1beta1.types.ThreatType]): Required. The ThreatLists to search in.\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.webrisk_v1beta1.types.SearchUrisResponse` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def _get_triplet_value(self, graph, identity, rdf_type):\n        value = graph.value(subject=identity, predicate=rdf_type)\n        return value.toPython() if value is not None else value",
    "docstring": "Get a value from an RDF triple"
  },
  {
    "code": "def block_pop_back(self, timeout=10):\r\n        value = yield self.backend_structure().block_pop_back(timeout)\r\n        if value is not None:\r\n            yield self.value_pickler.loads(value)",
    "docstring": "Remove the last element from of the list. If no elements are\r\navailable, blocks for at least ``timeout`` seconds."
  },
  {
    "code": "def clear_queues(self, manager):\n        for queue in (self.to_q, self.from_q):\n            if queue is None:\n                continue\n            if not manager:\n                try:\n                    queue.close()\n                    queue.join_thread()\n                except AttributeError:\n                    pass\n        self.to_q = self.from_q = None",
    "docstring": "Release the resources associated to the queues of this instance\n\n        :param manager: Manager() object\n        :type manager: None | object\n        :return: None"
  },
  {
    "code": "def functions_factory(cls, coef, domain, kind, **kwargs):\n        basis_polynomial = cls._basis_polynomial_factory(kind)\n        return basis_polynomial(coef, domain)",
    "docstring": "Given some coefficients, return a certain kind of orthogonal polynomial\n        defined over a specific domain."
  },
  {
    "code": "def should_series_dispatch(left, right, op):\n    if left._is_mixed_type or right._is_mixed_type:\n        return True\n    if not len(left.columns) or not len(right.columns):\n        return False\n    ldtype = left.dtypes.iloc[0]\n    rdtype = right.dtypes.iloc[0]\n    if ((is_timedelta64_dtype(ldtype) and is_integer_dtype(rdtype)) or\n            (is_timedelta64_dtype(rdtype) and is_integer_dtype(ldtype))):\n        return True\n    if is_datetime64_dtype(ldtype) and is_object_dtype(rdtype):\n        return True\n    return False",
    "docstring": "Identify cases where a DataFrame operation should dispatch to its\n    Series counterpart.\n\n    Parameters\n    ----------\n    left : DataFrame\n    right : DataFrame\n    op : binary operator\n\n    Returns\n    -------\n    override : bool"
  },
  {
    "code": "def get_subtree(self, tree, xpath_str):\n        return tree.xpath(xpath_str, namespaces=self.namespaces)",
    "docstring": "Return a subtree given an lxml XPath."
  },
  {
    "code": "def fileupdate(self, data):\n        self.name = data[\"name\"]\n        add = self.__additional\n        add[\"filetype\"] = \"other\"\n        for filetype in (\"book\", \"image\", \"video\", \"audio\", \"archive\"):\n            if filetype in data:\n                add[\"filetype\"] = filetype\n                break\n        if add[\"filetype\"] in (\"image\", \"video\", \"audio\"):\n            add[\"thumb\"] = data.get(\"thumb\", dict())\n        add[\"checksum\"] = data[\"checksum\"]\n        add[\"expire_time\"] = data[\"expires\"] / 1000\n        add[\"size\"] = data[\"size\"]\n        add[\"info\"] = data.get(add[\"filetype\"], dict())\n        add[\"uploader\"] = data[\"user\"]\n        if self.room.admin:\n            add[\"info\"].update({\"room\": data.get(\"room\")})\n            add[\"info\"].update({\"uploader_ip\": data.get(\"uploader_ip\")})\n        self.updated = True",
    "docstring": "Method to update extra metadata fields with dict obtained\n        through `fileinfo`"
  },
  {
    "code": "def reshape_by_blocks(x, x_shape, memory_block_size):\n  x = tf.reshape(x, [\n      x_shape[0], x_shape[1], x_shape[2] // memory_block_size,\n      memory_block_size, x_shape[3]\n  ])\n  return x",
    "docstring": "Reshapes input by splitting its length over blocks of memory_block_size.\n\n  Args:\n    x: a Tensor with shape [batch, heads, length, depth]\n    x_shape: tf.TensorShape of x.\n    memory_block_size: Integer which divides length.\n\n  Returns:\n    Tensor with shape\n    [batch, heads, length // memory_block_size, memory_block_size, depth]."
  },
  {
    "code": "def set_cpu_property(self, property_p, value):\n        if not isinstance(property_p, CPUPropertyType):\n            raise TypeError(\"property_p can only be an instance of type CPUPropertyType\")\n        if not isinstance(value, bool):\n            raise TypeError(\"value can only be an instance of type bool\")\n        self._call(\"setCPUProperty\",\n                     in_p=[property_p, value])",
    "docstring": "Sets the virtual CPU boolean value of the specified property.\n\n        in property_p of type :class:`CPUPropertyType`\n            Property type to query.\n\n        in value of type bool\n            Property value.\n\n        raises :class:`OleErrorInvalidarg`\n            Invalid property."
  },
  {
    "code": "def analysis(self, analysis_id: int) -> models.Analysis:\n        return self.Analysis.query.get(analysis_id)",
    "docstring": "Get a single analysis."
  },
  {
    "code": "def copy_with_new_atts(self, **attributes):\n        return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes))\n                        for bfs in self.chunks])",
    "docstring": "Returns a new FmtStr with the same content but new formatting"
  },
  {
    "code": "def _get_hit_nearest_ref_start(self, hits):\n        nearest_to_start = hits[0]\n        for hit in hits[1:]:\n            if hit.ref_coords().start < nearest_to_start.ref_coords().start:\n                nearest_to_start = hit\n        return nearest_to_start",
    "docstring": "Returns the hit nearest to the start of the ref sequence from the input list of hits"
  },
  {
    "code": "def load(self, model):\n        self.perceptron.weights, self.tagdict, self.classes, self.clusters = load_model(model)\n        self.perceptron.classes = self.classes",
    "docstring": "Load pickled model."
  },
  {
    "code": "def preview(self):\n        msg = self.ui.trackview.model().verify()\n        if msg:\n            answer = QtGui.QMessageBox.warning(self, \"Bummer\", 'Problem: {}.'.format(msg))\n            return\n        stim_signal, atten, ovld = self.ui.trackview.model().signal()\n        fig = SpecWidget()\n        fig.setWindowModality(2)\n        fig.updateData(stim_signal, self.ui.trackview.model().samplerate())\n        fig.setTitle('Stimulus Preview')\n        fig.show()\n        self.previewFig = fig",
    "docstring": "Assemble the current components in the QStimulusModel and generate a spectrogram \n        plot in a separate window"
  },
  {
    "code": "def validate_request():\n        flask_request = request\n        request_data = flask_request.get_data()\n        if not request_data:\n            request_data = b'{}'\n        request_data = request_data.decode('utf-8')\n        try:\n            json.loads(request_data)\n        except ValueError as json_error:\n            LOG.debug(\"Request body was not json. Exception: %s\", str(json_error))\n            return LambdaErrorResponses.invalid_request_content(\n                \"Could not parse request body into json: No JSON object could be decoded\")\n        if flask_request.args:\n            LOG.debug(\"Query parameters are in the request but not supported\")\n            return LambdaErrorResponses.invalid_request_content(\"Query Parameters are not supported\")\n        request_headers = CaseInsensitiveDict(flask_request.headers)\n        log_type = request_headers.get('X-Amz-Log-Type', 'None')\n        if log_type != 'None':\n            LOG.debug(\"log-type: %s is not supported. None is only supported.\", log_type)\n            return LambdaErrorResponses.not_implemented_locally(\n                \"log-type: {} is not supported. None is only supported.\".format(log_type))\n        invocation_type = request_headers.get('X-Amz-Invocation-Type', 'RequestResponse')\n        if invocation_type != 'RequestResponse':\n            LOG.warning(\"invocation-type: %s is not supported. RequestResponse is only supported.\", invocation_type)\n            return LambdaErrorResponses.not_implemented_locally(\n                \"invocation-type: {} is not supported. RequestResponse is only supported.\".format(invocation_type))",
    "docstring": "Validates the incoming request\n\n        The following are invalid\n            1. The Request data is not json serializable\n            2. Query Parameters are sent to the endpoint\n            3. The Request Content-Type is not application/json\n            4. 'X-Amz-Log-Type' header is not 'None'\n            5. 'X-Amz-Invocation-Type' header is not 'RequestResponse'\n\n        Returns\n        -------\n        flask.Response\n            If the request is not valid a flask Response is returned\n\n        None:\n            If the request passes all validation"
  },
  {
    "code": "def levels(self):\n        ret = [[] for i in range(self.height)]\n        for node in self.subtree:\n            ret[node.level - self.level].append(node)\n        return ret",
    "docstring": "Return a list of lists of nodes.\n        The outer list is indexed by the level.\n        Each inner list contains the nodes at that level,\n        in DFS order.\n\n        :rtype: list of lists of :class:`~aeneas.tree.Tree`"
  },
  {
    "code": "def writeBib(self, fname = None, maxStringLength = 1000, wosMode = False, reducedOutput = False, niceIDs = True):\n        if fname:\n            f = open(fname, mode = 'w', encoding = 'utf-8')\n        else:\n            f = open(self.name[:200] + '.bib', mode = 'w', encoding = 'utf-8')\n        f.write(\"%This file was generated by the metaknowledge Python package.\\n%The contents have been automatically generated and are likely to not work with\\n%LaTeX without some human intervention. This file is meant for other automatic\\n%systems and not to be used directly for making citations\\n\")\n        for R in self:\n            try:\n                f.write('\\n\\n')\n                f.write(R.bibString(maxLength =  maxStringLength, WOSMode = wosMode, restrictedOutput = reducedOutput, niceID = niceIDs))\n            except BadWOSRecord:\n                pass\n            except AttributeError:\n                raise RecordsNotCompatible(\"The Record '{}', with ID '{}' does not support writing to bibtext files.\".format(R, R.id))\n        f.close()",
    "docstring": "Writes a bibTex entry to _fname_ for each `Record` in the collection.\n\n        If the Record is of a journal article (PT J) the bibtext type is set to `'article'`, otherwise it is set to `'misc'`. The ID of the entry is the WOS number and all the Record's fields are given as entries with their long names.\n\n        **Note** This is not meant to be used directly with LaTeX none of the special characters have been escaped and there are a large number of unnecessary fields provided. _niceID_ and _maxLength_ have been provided to make conversions easier only.\n\n        **Note** Record entries that are lists have their values separated with the string `' and '`, as this is the way bibTex understands\n\n        # Parameters\n\n        _fname_ : `optional [str]`\n\n        > Default `None`, The name of the file to be written. If not given one will be derived from the collection and the file will be written to .\n\n        _maxStringLength_ : `optional [int]`\n\n        > Default 1000, The max length for a continuous string. Most bibTex implementation only allow string to be up to 1000 characters ([source](https://www.cs.arizona.edu/~collberg/Teaching/07.231/BibTeX/bibtex.html)), this splits them up into substrings then uses the native string concatenation (the `'#'` character) to allow for longer strings\n\n        _WOSMode_ : `optional [bool]`\n\n        > Default `False`, if `True` the data produced will be unprocessed and use double curly braces. This is the style WOS produces bib files in and mostly macthes that.\n\n        _restrictedOutput_ : `optional [bool]`\n\n        > Default `False`, if `True` the tags output will be limited to: `'AF'`, `'BF'`, `'ED'`, `'TI'`, `'SO'`, `'LA'`, `'NR'`, `'TC'`, `'Z9'`, `'PU'`, `'J9'`, `'PY'`, `'PD'`, `'VL'`, `'IS'`, `'SU'`, `'PG'`, `'DI'`, `'D2'`, and `'UT'`\n\n        _niceID_ : `optional [bool]`\n\n        > Default `True`, if `True` the IDs used will be derived from the authors, publishing date and title, if `False` it will be the UT tag"
  },
  {
    "code": "def set_row_min_height(self, y: int, min_height: int):\n        if y < 0:\n            raise IndexError('y < 0')\n        self._min_heights[y] = min_height",
    "docstring": "Sets a minimum height for blocks in the row with coordinate y."
  },
  {
    "code": "def _get_context(center_idx, sentence_boundaries, window_size,\n                 random_window_size, seed):\n    random.seed(seed + center_idx)\n    sentence_index = np.searchsorted(sentence_boundaries, center_idx)\n    sentence_start, sentence_end = _get_sentence_start_end(\n        sentence_boundaries, sentence_index)\n    if random_window_size:\n        window_size = random.randint(1, window_size)\n    start_idx = max(sentence_start, center_idx - window_size)\n    end_idx = min(sentence_end, center_idx + window_size + 1)\n    if start_idx != center_idx and center_idx + 1 != end_idx:\n        context = np.concatenate((np.arange(start_idx, center_idx),\n                                  np.arange(center_idx + 1, end_idx)))\n    elif start_idx != center_idx:\n        context = np.arange(start_idx, center_idx)\n    elif center_idx + 1 != end_idx:\n        context = np.arange(center_idx + 1, end_idx)\n    else:\n        context = None\n    return context",
    "docstring": "Compute the context with respect to a center word in a sentence.\n\n    Takes an numpy array of sentences boundaries."
  },
  {
    "code": "def _init_update_po_files(self, domains):\n        for language in settings.TRANSLATIONS:\n            for domain, options in domains.items():\n                if language == options['default']: continue\n                if os.path.isfile(_po_path(language, domain)):\n                    self._update_po_file(language, domain, options['pot'])\n                else:\n                    self._init_po_file(language, domain, options['pot'])",
    "docstring": "Update or initialize the `.po` translation files"
  },
  {
    "code": "def get_data(self, size=None, addr=None):\n        if addr is None:\n            addr = self._mem_bytes\n        if size and self._mem_bytes < size:\n            raise ValueError('Size is too big')\n        if size is None:\n            return self._intf.read(self._conf['base_addr'] + self._spi_mem_offset + addr, self._mem_bytes)\n        else:\n            return self._intf.read(self._conf['base_addr'] + self._spi_mem_offset + addr, size)",
    "docstring": "Gets data for incoming stream"
  },
  {
    "code": "def reload(self):\n        self.read_notmuch_config(self._notmuchconfig.filename)\n        self.read_config(self._config.filename)",
    "docstring": "Reload notmuch and alot config files"
  },
  {
    "code": "def inve(env, command, *args, **kwargs):\n    with temp_environ():\n        os.environ['VIRTUAL_ENV'] = str(workon_home / env)\n        os.environ['PATH'] = compute_path(env)\n        unsetenv('PYTHONHOME')\n        unsetenv('__PYVENV_LAUNCHER__')\n        try:\n            return check_call([command] + list(args), shell=windows, **kwargs)\n        except OSError as e:\n            if e.errno == 2:\n                err('Unable to find', command)\n                return 2\n            else:\n                raise",
    "docstring": "Run a command in the given virtual environment.\n\n    Pass additional keyword arguments to ``subprocess.check_call()``."
  },
  {
    "code": "def exclude_items(items, any_all=any, ignore_case=False, normalize_values=False, **kwargs):\n\tif kwargs:\n\t\tmatch = functools.partial(\n\t\t\t_match_item, any_all=any_all, ignore_case=ignore_case, normalize_values=normalize_values, **kwargs\n\t\t)\n\t\treturn filterfalse(match, items)\n\telse:\n\t\treturn iter(items)",
    "docstring": "Exclude items by matching metadata.\n\n\tNote:\n\t\tMetadata values are lowercased when ``normalized_values`` is ``True``,\n\t\tso ``ignore_case`` is automatically set to ``True``.\n\n\tParameters:\n\t\titems (list): A list of item dicts or filepaths.\n\t\tany_all (callable): A callable to determine if any or all filters must match to exclude items.\n\t\t\tExpected values :obj:`any` (default) or :obj:`all`.\n\t\tignore_case (bool): Perform case-insensitive matching.\n\t\t\tDefault: ``False``\n\t\tnormalize_values (bool): Normalize metadata values to remove common differences between sources.\n\t\t\tDefault: ``False``\n\t\tkwargs (list): Lists of values to match the given metadata field.\n\n\tYields:\n\t\tdict: The next item to be included.\n\n\tExample:\n\t\t>>> from google_music_utils import exclude_items\n\t\t>>> list(exclude_items(song_list, any_all=all, ignore_case=True, normalize_values=True, artist=['Beck'], album=['Golden Feelings']))"
  },
  {
    "code": "def empirical_rate(data, sigma=3.0):\n        from scipy.ndimage.filters import gaussian_filter1d\n        return 0.001 + gaussian_filter1d(data.astype(np.float), sigma, axis=0)",
    "docstring": "Smooth count data to get an empirical rate"
  },
  {
    "code": "def try_url(url_name):\n    from warnings import warn\n    warn(\"try_url is deprecated, use the url tag with the 'as' arg instead.\")\n    try:\n        url = reverse(url_name)\n    except NoReverseMatch:\n        return \"\"\n    return url",
    "docstring": "Mimics Django's ``url`` template tag but fails silently. Used for\n    url names in admin templates as these won't resolve when admin\n    tests are running."
  },
  {
    "code": "def _depth_image_callback(self, image_msg):\n        encoding = image_msg.encoding\n        try:\n            depth_arr = self._bridge.imgmsg_to_cv2(image_msg, encoding)\n            import pdb; pdb.set_trace()\n        except CvBridgeError as e:\n            rospy.logerr(e)\n        depth = np.array(depth_arr*MM_TO_METERS, np.float32)\n        self._cur_depth_im = DepthImage(depth, self._frame)",
    "docstring": "subscribe to depth image topic and keep it up to date"
  },
  {
    "code": "def get_annotations(cls, __fn):\n        if hasattr(__fn, '__func__'):\n            __fn = __fn.__func__\n        if hasattr(__fn, '__notes__'):\n            return __fn.__notes__\n        raise AttributeError('{!r} does not have annotations'.format(__fn))",
    "docstring": "Get the annotations of a given callable."
  },
  {
    "code": "def finish(self, status):\n        retox_log.info(\"Completing %s with status %s\" % (self.name, status))\n        result = Screen.COLOUR_GREEN if not status else Screen.COLOUR_RED\n        self.palette['title'] = (Screen.COLOUR_WHITE, Screen.A_BOLD, result)\n        for item in list(self._task_view.options):\n            self._task_view.options.remove(item)\n            self._completed_view.options.append(item)\n        self.refresh()",
    "docstring": "Move laggard tasks over\n\n        :param activity: The virtualenv status\n        :type  activity: ``str``"
  },
  {
    "code": "def view_plugins(category=None):\n    if category is not None:\n        if category == 'parsers':\n            return {\n                name: {\"descript\": klass.plugin_descript,\n                       \"regex\": klass.file_regex}\n                for name, klass in _all_plugins[category].items()\n            }\n        return {\n            name: klass.plugin_descript\n            for name, klass in _all_plugins[category].items()\n        }\n    else:\n        return {cat: {name: klass.plugin_descript\n                      for name, klass in plugins.items()}\n                for cat, plugins in _all_plugins.items()}",
    "docstring": "return a view of the loaded plugin names and descriptions\n\n    Parameters\n    ----------\n    category : None or str\n        if str, apply for single plugin category\n\n    Examples\n    --------\n\n    >>> from pprint import pprint\n    >>> pprint(view_plugins())\n    {'decoders': {}, 'encoders': {}, 'parsers': {}}\n\n    >>> class DecoderPlugin(object):\n    ...     plugin_name = 'example'\n    ...     plugin_descript = 'a decoder for dicts containing _example_ key'\n    ...     dict_signature = ('_example_',)\n    ...\n    >>> errors = load_plugin_classes([DecoderPlugin])\n\n    >>> pprint(view_plugins())\n    {'decoders': {'example': 'a decoder for dicts containing _example_ key'},\n     'encoders': {},\n     'parsers': {}}\n\n    >>> view_plugins('decoders')\n    {'example': 'a decoder for dicts containing _example_ key'}\n\n    >>> unload_all_plugins()"
  },
  {
    "code": "async def pop_log(self):\n        self._check_receive_loop()\n        res = self.log_queue.get()\n        self._check_error(res)\n        return res",
    "docstring": "Get one log from the log queue."
  },
  {
    "code": "def calc_drm(skydir, ltc, event_class, event_types,\n             egy_bins, cth_bins, nbin=64):\n    npts = int(np.ceil(128. / bins_per_dec(egy_bins)))\n    egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts))\n    etrue_bins = 10**np.linspace(1.0, 6.5, nbin * 5.5 + 1)\n    egy = 10**utils.edge_to_center(np.log10(egy_bins))\n    egy_width = utils.edge_to_width(egy_bins)\n    etrue = 10**utils.edge_to_center(np.log10(etrue_bins))\n    edisp = create_avg_edisp(skydir, ltc, event_class, event_types,\n                             egy, etrue, cth_bins)\n    edisp = edisp * egy_width[:, None, None]\n    edisp = sum_bins(edisp, 0, npts)\n    return edisp",
    "docstring": "Calculate the detector response matrix."
  },
  {
    "code": "async def get_config(self):\n        config_facade = client.ModelConfigFacade.from_connection(\n            self.connection()\n        )\n        result = await config_facade.ModelGet()\n        config = result.config\n        for key, value in config.items():\n            config[key] = ConfigValue.from_json(value)\n        return config",
    "docstring": "Return the configuration settings for this model.\n\n        :returns: A ``dict`` mapping keys to `ConfigValue` instances,\n            which have `source` and `value` attributes."
  },
  {
    "code": "def create_snapshot(self, volume_id_or_uri, snapshot, timeout=-1):\n        uri = self.__build_volume_snapshot_uri(volume_id_or_uri)\n        return self._client.create(snapshot, uri=uri, timeout=timeout, default_values=self.DEFAULT_VALUES_SNAPSHOT)",
    "docstring": "Creates a snapshot for the specified volume.\n\n        Args:\n            volume_id_or_uri:\n                Can be either the volume ID or the volume URI.\n            snapshot (dict):\n                Object to create.\n            timeout:\n                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in\n                OneView, just stops waiting for its completion.\n\n        Returns:\n            dict: Storage volume."
  },
  {
    "code": "def undo(scm, verbose, fake, hard):\n    scm.fake = fake\n    scm.verbose = fake or verbose\n    scm.repo_check()\n    status_log(scm.undo, 'Last commit removed from history.', hard)",
    "docstring": "Removes the last commit from history."
  },
  {
    "code": "def current(self):\n        if not has_request_context():\n            return self.no_req_ctx_user_stack.top\n        user_stack = getattr(_request_ctx_stack.top, 'user_stack', None)\n        if user_stack and user_stack.top:\n            return user_stack.top\n        return _get_user()",
    "docstring": "Returns the current user"
  },
  {
    "code": "def verify_pubkey_sig(self, message, sig):\n        if self.opts['master_sign_key_name']:\n            path = os.path.join(self.opts['pki_dir'],\n                                self.opts['master_sign_key_name'] + '.pub')\n            if os.path.isfile(path):\n                res = verify_signature(path,\n                                       message,\n                                       binascii.a2b_base64(sig))\n            else:\n                log.error(\n                    'Verification public key %s does not exist. You need to '\n                    'copy it from the master to the minions pki directory',\n                    os.path.basename(path)\n                )\n                return False\n            if res:\n                log.debug(\n                    'Successfully verified signature of master public key '\n                    'with verification public key %s',\n                    self.opts['master_sign_key_name'] + '.pub'\n                )\n                return True\n            else:\n                log.debug('Failed to verify signature of public key')\n                return False\n        else:\n            log.error(\n                'Failed to verify the signature of the message because the '\n                'verification key-pairs name is not defined. Please make '\n                'sure that master_sign_key_name is defined.'\n            )\n            return False",
    "docstring": "Wraps the verify_signature method so we have\n        additional checks.\n\n        :rtype: bool\n        :return: Success or failure of public key verification"
  },
  {
    "code": "def get(self, *args, **kwargs):\n        self.set_status(self._status_response_code())\n        self.write(self._status_response())",
    "docstring": "Tornado RequestHandler GET request endpoint for reporting status\n\n        :param list args: positional args\n        :param  dict kwargs: keyword args"
  },
  {
    "code": "def destinations(stop):\n    from pyruter.api import Departures\n    async def get_destinations():\n        async with aiohttp.ClientSession() as session:\n            data = Departures(LOOP, stop, session=session)\n            result = await data.get_final_destination()\n            print(json.dumps(result, indent=4, sort_keys=True,\n                             ensure_ascii=False))\n    LOOP.run_until_complete(get_destinations())",
    "docstring": "Get destination information."
  },
  {
    "code": "def _parse_alt_url(html_chunk):\n    url_list = html_chunk.find(\"a\", fn=has_param(\"href\"))\n    url_list = map(lambda x: x.params[\"href\"], url_list)\n    url_list = filter(lambda x: not x.startswith(\"autori/\"), url_list)\n    if not url_list:\n        return None\n    return normalize_url(BASE_URL, url_list[0])",
    "docstring": "Parse URL from alternative location if not found where it should be.\n\n    Args:\n        html_chunk (obj): HTMLElement containing slice of the page with details.\n\n    Returns:\n        str: Book's URL."
  },
  {
    "code": "def wo_resp(self, resp):\n        if self._data is not None:\n            resp['res'] = self.to_str(self._data)\n        return self.wo_json(resp)",
    "docstring": "can override for other style"
  },
  {
    "code": "def on_open(self):\n        filename, filter = QtWidgets.QFileDialog.getOpenFileName(\n            self, _('Open'))\n        if filename:\n            self.open_file(filename)",
    "docstring": "Shows an open file dialog and open the file if the dialog was\n        accepted."
  },
  {
    "code": "def is_vector(inp):\n    inp = np.asarray(inp)\n    nr_dim = np.ndim(inp)\n    if nr_dim == 1:\n        return True\n    elif (nr_dim == 2) and (1 in inp.shape):\n        return True\n    else:\n        return False",
    "docstring": "Returns true if the input can be interpreted as a 'true' vector\n\n    Note\n    ----\n    Does only check dimensions, not if type is numeric\n\n    Parameters\n    ----------\n    inp : numpy.ndarray or something that can be converted into ndarray\n\n    Returns\n    -------\n    Boolean\n        True for vectors: ndim = 1 or ndim = 2 and shape of one axis = 1\n        False for all other arrays"
  },
  {
    "code": "def local():\n    logger.info(\"Loading requirements from local file.\")\n    with open(REQUIREMENTS_FILE, 'r') as f:\n        requirements = parse(f)\n        for r in requirements:\n            logger.debug(\"Creating new package: %r\", r)\n            create_package_version(r)",
    "docstring": "Load local requirements file."
  },
  {
    "code": "def from_df(cls, df):\n        t = cls()\n        labels = df.columns\n        for label in df.columns:\n            t.append_column(label, df[label])\n        return t",
    "docstring": "Convert a Pandas DataFrame into a Table."
  },
  {
    "code": "def default(self, line):\n        if any((line.startswith(x) for x in self.argparse_names())):\n            try:\n                args = self.argparser.parse_args(shlex.split(line))\n            except Exception:\n                pass\n            else:\n                args.func(args)\n        else:\n            cmd.Cmd.default(self, line)",
    "docstring": "Overriding default to get access to any argparse commands we have specified."
  },
  {
    "code": "def read_function(data, window, ij, g_args):\n    output = (data[0] > numpy.mean(data[0])).astype(data[0].dtype) * data[0].max()\n    return output",
    "docstring": "Takes an array, and sets any value above the mean to the max, the rest to 0"
  },
  {
    "code": "async def generate_license(self, title, avatar, badges=None, widgets=None):\n        if not isinstance(title, str):\n            raise TypeError(\"type of 'title' must be str.\")\n        if not isinstance(avatar, str):\n            raise TypeError(\"type of 'avatar' must be str.\")\n        if badges and not isinstance(badges, list):\n            raise TypeError(\"type of 'badges' must be list.\")\n        if widgets and not isinstance(widgets, list):\n            raise TypeError(\"type of 'widgets' must be list.\")\n        data = {\"title\": title, \"avatar\": avatar}\n        if badges and len(badges) <= 3:\n            data['badges'] = badges\n        if widgets and len(widgets) <= 3:\n            data['widgets'] = widgets\n        async with aiohttp.ClientSession() as session:\n            async with session.post(\"https://api.weeb.sh/auto-image/license\", headers=self.__headers, data=data) as resp:\n                if resp.status == 200:\n                    return await resp.read()\n                else:\n                    raise Exception((await resp.json())['message'])",
    "docstring": "Generate a license.\n\n        This function is a coroutine.\n\n        Parameters:\n            title: str - title of the license\n            avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image\n            badges: list - list of 1-3 direct image urls. Same requirements as avatar (optional)\n            widgets: list - list of 1-3 strings to fill the three boxes with (optional)\n\n        Return Type: image data"
  },
  {
    "code": "def write_calculations_to_csv(funcs, states, columns, path, headers, out_name,\n                              metaids=[], extension=\".xls\"):\n    if not isinstance(funcs, list):\n        funcs = [funcs] * len(headers)\n    if not isinstance(states, list):\n        states = [states] * len(headers)\n    if not isinstance(columns, list):\n        columns = [columns] * len(headers)\n    data_agg = []\n    for i in range(len(headers)):\n        ids, data = read_state_with_metafile(funcs[i], states[i], columns[i],\n                                             path, metaids, extension)\n        data_agg = np.append(data_agg, [data])\n    output = pd.DataFrame(data=np.vstack((ids, data_agg)).T,\n                          columns=[\"ID\"]+headers)\n    output.to_csv(out_name, sep='\\t')\n    return output",
    "docstring": "Writes each output of the given functions on the given states and data\n    columns to a new column in the specified output file.\n\n    Note: Column 0 is time. The first data column is column 1.\n\n    :param funcs: A function or list of functions which will be applied in order to the data. If only one function is given it is applied to all the states/columns\n    :type funcs: function or function list\n    :param states: The state ID numbers for which data should be extracted. List should be in order of calculation or if only one state is given then it will be used for all the calculations\n    :type states: string or string list\n    :param columns: The index of a column, the header of a column, a list of indexes, OR a list of headers of the column(s) that you want to apply calculations to\n    :type columns: int, string, int list, or string list\n    :param path: Path to your ProCoDA metafile (must be tab-delimited)\n    :type path: string\n    :param headers: List of the desired header for each calculation, in order\n    :type headers: string list\n    :param out_name: Desired name for the output file. Can include a relative path\n    :type out_name: string\n    :param metaids: A list of the experiment IDs you'd like to analyze from the metafile\n    :type metaids: string list, optional\n    :param extension: The file extension of the tab delimited file. Defaults to \".xls\" if no argument is passed in\n    :type extension: string, optional\n\n    :requires: funcs, states, columns, and headers are all of the same length if they are lists. Some being lists and some single values are okay.\n\n    :return: out_name.csv (CVS file) - A CSV file with the each column being a new calcuation and each row being a new experiment on which the calcuations were performed\n    :return: output (Pandas.DataFrame)- Pandas DataFrame holding the same data that was written to the output file"
  },
  {
    "code": "def process_request(self, request):\n        if not self.is_resource_protected(request):\n            return\n        if self.deny_access_condition(request):\n            return self.deny_access(request)",
    "docstring": "The actual middleware method, called on all incoming requests.\n\n        This default implementation will ignore the middleware (return None) if the\n        conditions specified in is_resource_protected aren't met. If they are, it then\n        tests to see if the user should be denied access via the denied_access_condition\n        method, and calls deny_access (which implements failure behaviour) if so."
  },
  {
    "code": "def user_pk_to_url_str(user):\n    User = get_user_model()\n    if issubclass(type(User._meta.pk), models.UUIDField):\n        if isinstance(user.pk, six.string_types):\n            return user.pk\n        return user.pk.hex\n    ret = user.pk\n    if isinstance(ret, six.integer_types):\n        ret = int_to_base36(user.pk)\n    return str(ret)",
    "docstring": "This should return a string."
  },
  {
    "code": "def compare_directory(self, directory):\n        return not self.folder_exclude_check.match(directory + self.sep if self.dir_pathname else directory)",
    "docstring": "Compare folder."
  },
  {
    "code": "def place_notes(self, notes, duration):\n        if hasattr(notes, 'notes'):\n            pass\n        elif hasattr(notes, 'name'):\n            notes = NoteContainer(notes)\n        elif type(notes) == str:\n            notes = NoteContainer(notes)\n        elif type(notes) == list:\n            notes = NoteContainer(notes)\n        if self.current_beat + 1.0 / duration <= self.length or self.length\\\n             == 0.0:\n            self.bar.append([self.current_beat, duration, notes])\n            self.current_beat += 1.0 / duration\n            return True\n        else:\n            return False",
    "docstring": "Place the notes on the current_beat.\n\n        Notes can be strings, Notes, list of strings, list of Notes or a\n        NoteContainer.\n\n        Raise a MeterFormatError if the duration is not valid.\n\n        Return True if succesful, False otherwise (ie. the Bar hasn't got\n        enough room for a note of that duration)."
  },
  {
    "code": "def update_status(self):\n        try:\n            self.update_connection_status()\n            self.max_stream_rate.set(self.get_stream_rate_str())\n            self.ip.set(self.status.external_ip)\n            self.uptime.set(self.status.str_uptime)\n            upstream, downstream = self.status.transmission_rate\n        except IOError:\n            pass\n        else:\n            if self.max_downstream > 0:\n                self.in_meter.set_fraction(\n                    1.0 * downstream / self.max_downstream)\n            if self.max_upstream > 0:\n                self.out_meter.set_fraction(1.0 * upstream / self.max_upstream)\n            self.update_traffic_info()\n        self.after(1000, self.update_status)",
    "docstring": "Update status informations in tkinter window."
  },
  {
    "code": "def local_2d_halo_exchange(k, v, num_h_blocks, h_dim,\n                           num_w_blocks, w_dim, mask_right):\n  for blocks_dim, block_size_dim, halo_size in [\n      (num_h_blocks, h_dim, h_dim.size),\n      (num_w_blocks, w_dim, w_dim.size)]:\n    if halo_size > 0:\n      if blocks_dim is not None:\n        if mask_right:\n          k = mtf.left_halo_exchange(k, blocks_dim, block_size_dim, halo_size)\n          v = mtf.left_halo_exchange(v, blocks_dim, block_size_dim, halo_size)\n        else:\n          k = mtf.halo_exchange(k, blocks_dim, block_size_dim, halo_size)\n          v = mtf.halo_exchange(v, blocks_dim, block_size_dim, halo_size)\n      else:\n        if mask_right:\n          k = mtf.pad(k, [halo_size, None], block_size_dim.name)\n          v = mtf.pad(v, [halo_size, None], block_size_dim.name)\n        else:\n          k = mtf.pad(k, [halo_size, halo_size], block_size_dim.name)\n          v = mtf.pad(v, [halo_size, halo_size], block_size_dim.name)\n  return k, v",
    "docstring": "Halo exchange for keys and values for Local 2D attention."
  },
  {
    "code": "def geometry(obj):\n    gf = vtk.vtkGeometryFilter()\n    gf.SetInputData(obj)\n    gf.Update()\n    return gf.GetOutput()",
    "docstring": "Apply ``vtkGeometryFilter``."
  },
  {
    "code": "def get_value(self, model, default=None):\n        if default is not None:\n            default = self._converter(default)\n        value = getattr(model, self.storage_name)\n        return value if value is not None else default",
    "docstring": "Return field's value.\n\n        :param DomainModel model:\n        :param object default:\n        :rtype object:"
  },
  {
    "code": "def _runhook(ui, repo, hooktype, filename, kwargs):\n    hname = hooktype + \".autohooks.\" + os.path.basename(filename)\n    if filename.lower().endswith(\".py\"):\n        try:\n            mod = mercurial.extensions.loadpath(filename,\n                \"hghook.%s\" % hname)\n        except Exception:\n            ui.write(_(\"loading %s hook failed:\\n\") % hname)\n            raise\n        return mercurial.hook._pythonhook(ui, repo, hooktype, hname,\n            getattr(mod, hooktype.replace(\"-\", \"_\")), kwargs, True)\n    elif filename.lower().endswith(\".sh\"):\n        return mercurial.hook._exthook(ui, repo, hname, filename, kwargs, True)\n    return False",
    "docstring": "Run the hook in `filename` and return its result."
  },
  {
    "code": "def mixed_use_of_local_and_run(self):\n        cxn = Connection(\"localhost\")\n        result = cxn.local(\"echo foo\", hide=True)\n        assert result.stdout == \"foo\\n\"\n        assert not cxn.is_connected\n        result = cxn.run(\"echo foo\", hide=True)\n        assert cxn.is_connected\n        assert result.stdout == \"foo\\n\"",
    "docstring": "Run command truly locally, and over SSH via localhost"
  },
  {
    "code": "def PythonTypeFromMetricValueType(value_type):\n  if value_type == rdf_stats.MetricMetadata.ValueType.INT:\n    return int\n  elif value_type == rdf_stats.MetricMetadata.ValueType.FLOAT:\n    return float\n  else:\n    raise ValueError(\"Unknown value type: %s\" % value_type)",
    "docstring": "Converts MetricMetadata.ValueType enums to corresponding Python types."
  },
  {
    "code": "def _file_prompt_quiet(f):\n        @functools.wraps(f)\n        def wrapper(self, *args, **kwargs):\n            if not self.prompt_quiet_configured:\n                if self.auto_file_prompt:\n                    self.device.send_config_set([\"file prompt quiet\"])\n                    self.prompt_quiet_changed = True\n                    self.prompt_quiet_configured = True\n                else:\n                    cmd = \"file prompt quiet\"\n                    show_cmd = \"show running-config | inc {}\".format(cmd)\n                    output = self.device.send_command_expect(show_cmd)\n                    if cmd in output:\n                        self.prompt_quiet_configured = True\n                    else:\n                        msg = (\n                            \"on-device file operations require prompts to be disabled. \"\n                            \"Configure 'file prompt quiet' or set 'auto_file_prompt=True'\"\n                        )\n                        raise CommandErrorException(msg)\n            return f(self, *args, **kwargs)\n        return wrapper",
    "docstring": "Decorator to toggle 'file prompt quiet' for methods that perform file operations."
  },
  {
    "code": "def _request(self, url, request_type='GET', **params):\n        try:\n            _LOGGER.debug('Request %s %s', url, params)\n            response = self.request(\n                request_type, url, timeout=TIMEOUT.seconds, **params)\n            response.raise_for_status()\n            _LOGGER.debug('Response %s %s %.200s', response.status_code,\n                          response.headers['content-type'], response.json())\n            response = response.json()\n            if 'error' in response:\n                raise OSError(response['error'])\n            return response\n        except OSError as error:\n            _LOGGER.warning('Failed request: %s', error)",
    "docstring": "Send a request to the Minut Point API."
  },
  {
    "code": "def _filter_matrix_rows(cls, matrix):\n        indexes_to_keep = []\n        for i in range(len(matrix)):\n            keep_row = False\n            for element in matrix[i]:\n                if element not in {'NA', 'no'}:\n                    keep_row = True\n                    break\n            if keep_row:\n                indexes_to_keep.append(i)\n        return [matrix[i] for i in indexes_to_keep]",
    "docstring": "matrix = output from _to_matrix"
  },
  {
    "code": "def create(cls, counter_user_alias, share_detail, status,\n               monetary_account_id=None, draft_share_invite_bank_id=None,\n               share_type=None, start_date=None, end_date=None,\n               custom_headers=None):\n        if custom_headers is None:\n            custom_headers = {}\n        request_map = {\n            cls.FIELD_COUNTER_USER_ALIAS: counter_user_alias,\n            cls.FIELD_DRAFT_SHARE_INVITE_BANK_ID: draft_share_invite_bank_id,\n            cls.FIELD_SHARE_DETAIL: share_detail,\n            cls.FIELD_STATUS: status,\n            cls.FIELD_SHARE_TYPE: share_type,\n            cls.FIELD_START_DATE: start_date,\n            cls.FIELD_END_DATE: end_date\n        }\n        request_map_string = converter.class_to_json(request_map)\n        request_map_string = cls._remove_field_for_request(request_map_string)\n        api_client = client.ApiClient(cls._get_api_context())\n        request_bytes = request_map_string.encode()\n        endpoint_url = cls._ENDPOINT_URL_CREATE.format(cls._determine_user_id(),\n                                                       cls._determine_monetary_account_id(\n                                                           monetary_account_id))\n        response_raw = api_client.post(endpoint_url, request_bytes,\n                                       custom_headers)\n        return BunqResponseInt.cast_from_bunq_response(\n            cls._process_for_id(response_raw)\n        )",
    "docstring": "Create a new share inquiry for a monetary account, specifying the\n        permission the other bunq user will have on it.\n\n        :type user_id: int\n        :type monetary_account_id: int\n        :param counter_user_alias: The pointer of the user to share with.\n        :type counter_user_alias: object_.Pointer\n        :param share_detail: The share details. Only one of these objects may be\n        passed.\n        :type share_detail: object_.ShareDetail\n        :param status: The status of the share. Can be PENDING, REVOKED (the\n        user deletes the share inquiry before it's accepted), ACCEPTED,\n        CANCELLED (the user deletes an active share) or CANCELLATION_PENDING,\n        CANCELLATION_ACCEPTED, CANCELLATION_REJECTED (for canceling mutual\n        connects).\n        :type status: str\n        :param draft_share_invite_bank_id: The id of the draft share invite\n        bank.\n        :type draft_share_invite_bank_id: int\n        :param share_type: The share type, either STANDARD or MUTUAL.\n        :type share_type: str\n        :param start_date: The start date of this share.\n        :type start_date: str\n        :param end_date: The expiration date of this share.\n        :type end_date: str\n        :type custom_headers: dict[str, str]|None\n\n        :rtype: BunqResponseInt"
  },
  {
    "code": "def OpenSourcePath(self, source_path):\n    source_path_spec = path_spec_factory.Factory.NewPathSpec(\n        definitions.TYPE_INDICATOR_OS, location=source_path)\n    self.AddScanNode(source_path_spec, None)",
    "docstring": "Opens the source path.\n\n    Args:\n      source_path (str): source path."
  },
  {
    "code": "def _validate_conn(self, conn):\n        super(HTTPSConnectionPool, self)._validate_conn(conn)\n        if not getattr(conn, 'sock', None):\n            conn.connect()\n        if not conn.is_verified:\n            warnings.warn((\n                'Unverified HTTPS request is being made. '\n                'Adding certificate verification is strongly advised. See: '\n                'https://urllib3.readthedocs.org/en/latest/security.html'),\n                InsecureRequestWarning)",
    "docstring": "Called right before a request is made, after the socket is created."
  },
  {
    "code": "def recordHostname(self, basedir):\n        \"Record my hostname in twistd.hostname, for user convenience\"\n        log.msg(\"recording hostname in twistd.hostname\")\n        filename = os.path.join(basedir, \"twistd.hostname\")\n        try:\n            hostname = os.uname()[1]\n        except AttributeError:\n            hostname = socket.getfqdn()\n        try:\n            with open(filename, \"w\") as f:\n                f.write(\"{0}\\n\".format(hostname))\n        except Exception:\n            log.msg(\"failed - ignoring\")",
    "docstring": "Record my hostname in twistd.hostname, for user convenience"
  },
  {
    "code": "def get(self, request, **kwargs):\n\t\tcustomer, _created = Customer.get_or_create(\n\t\t\tsubscriber=subscriber_request_callback(self.request)\n\t\t)\n\t\tserializer = SubscriptionSerializer(customer.subscription)\n\t\treturn Response(serializer.data)",
    "docstring": "Return the customer's valid subscriptions.\n\n\t\tReturns with status code 200."
  },
  {
    "code": "def flatten(self, shallow=None):\n        return self._wrap(self._flatten(self.obj, shallow))",
    "docstring": "Return a completely flattened version of an array."
  },
  {
    "code": "def toList(self):\n        slist = angle.toList(self.value)\n        slist[1] = slist[1] % 24\n        return slist",
    "docstring": "Returns time as signed list."
  },
  {
    "code": "def is_bool_dtype(arr_or_dtype):\n    if arr_or_dtype is None:\n        return False\n    try:\n        dtype = _get_dtype(arr_or_dtype)\n    except TypeError:\n        return False\n    if isinstance(arr_or_dtype, CategoricalDtype):\n        arr_or_dtype = arr_or_dtype.categories\n    if isinstance(arr_or_dtype, ABCIndexClass):\n        return (arr_or_dtype.is_object and\n                arr_or_dtype.inferred_type == 'boolean')\n    elif is_extension_array_dtype(arr_or_dtype):\n        dtype = getattr(arr_or_dtype, 'dtype', arr_or_dtype)\n        return dtype._is_boolean\n    return issubclass(dtype.type, np.bool_)",
    "docstring": "Check whether the provided array or dtype is of a boolean dtype.\n\n    Parameters\n    ----------\n    arr_or_dtype : array-like\n        The array or dtype to check.\n\n    Returns\n    -------\n    boolean\n        Whether or not the array or dtype is of a boolean dtype.\n\n    Notes\n    -----\n    An ExtensionArray is considered boolean when the ``_is_boolean``\n    attribute is set to True.\n\n    Examples\n    --------\n    >>> is_bool_dtype(str)\n    False\n    >>> is_bool_dtype(int)\n    False\n    >>> is_bool_dtype(bool)\n    True\n    >>> is_bool_dtype(np.bool)\n    True\n    >>> is_bool_dtype(np.array(['a', 'b']))\n    False\n    >>> is_bool_dtype(pd.Series([1, 2]))\n    False\n    >>> is_bool_dtype(np.array([True, False]))\n    True\n    >>> is_bool_dtype(pd.Categorical([True, False]))\n    True\n    >>> is_bool_dtype(pd.SparseArray([True, False]))\n    True"
  },
  {
    "code": "def wrap_uda(\n    hdfs_file,\n    inputs,\n    output,\n    update_fn,\n    init_fn=None,\n    merge_fn=None,\n    finalize_fn=None,\n    serialize_fn=None,\n    close_fn=None,\n    name=None,\n):\n    func = ImpalaUDA(\n        inputs,\n        output,\n        update_fn,\n        init_fn,\n        merge_fn,\n        finalize_fn,\n        serialize_fn=serialize_fn,\n        name=name,\n        lib_path=hdfs_file,\n    )\n    return func",
    "docstring": "Creates a callable aggregation function object. Must be created in Impala\n    to be used\n\n    Parameters\n    ----------\n    hdfs_file: .so file that contains relevant UDA\n    inputs: list of strings denoting ibis datatypes\n    output: string denoting ibis datatype\n    update_fn: string\n      Library symbol name for update function\n    init_fn: string, optional\n      Library symbol name for initialization function\n    merge_fn: string, optional\n      Library symbol name for merge function\n    finalize_fn: string, optional\n      Library symbol name for finalize function\n    serialize_fn : string, optional\n      Library symbol name for serialize UDA API function. Not required for all\n      UDAs; see documentation for more.\n    close_fn : string, optional\n    name: string, optional\n      Used internally to track function\n\n    Returns\n    -------\n    container : UDA object"
  },
  {
    "code": "def determine(chord, shorthand=False, no_inversions=False, no_polychords=False):\n    if chord == []:\n        return []\n    elif len(chord) == 1:\n        return chord\n    elif len(chord) == 2:\n        return [intervals.determine(chord[0], chord[1])]\n    elif len(chord) == 3:\n        return determine_triad(chord, shorthand, no_inversions, no_polychords)\n    elif len(chord) == 4:\n        return determine_seventh(chord, shorthand, no_inversions, no_polychords)\n    elif len(chord) == 5:\n        return determine_extended_chord5(chord, shorthand, no_inversions,\n                no_polychords)\n    elif len(chord) == 6:\n        return determine_extended_chord6(chord, shorthand, no_inversions,\n                no_polychords)\n    elif len(chord) == 7:\n        return determine_extended_chord7(chord, shorthand, no_inversions,\n                no_polychords)\n    else:\n        return determine_polychords(chord, shorthand)",
    "docstring": "Name a chord.\n\n    This function can determine almost every chord, from a simple triad to a\n    fourteen note polychord."
  },
  {
    "code": "def notify(self, n=1):\n        if not is_locked(self._lock):\n            raise RuntimeError('lock is not locked')\n        notified = [0]\n        def walker(switcher, predicate):\n            if not switcher.active:\n                return False\n            if predicate and not predicate():\n                return True\n            if n >= 0 and notified[0] >= n:\n                return True\n            switcher.switch()\n            notified[0] += 1\n            return False\n        walk_callbacks(self, walker)",
    "docstring": "Raise the condition and wake up fibers waiting on it.\n\n        The optional *n* parameter specifies how many fibers will be notified.\n        By default, one fiber is notified."
  },
  {
    "code": "def is_period_current(self):\n\t\treturn self.current_period_end > timezone.now() or (\n\t\t\tself.trial_end and self.trial_end > timezone.now()\n\t\t)",
    "docstring": "Returns True if this subscription's period is current, false otherwise."
  },
  {
    "code": "def ref(self):\n        sds_ref = _C.SDidtoref(self._id)\n        _checkErr('idtoref', sds_ref, 'illegal SDS identifier')\n        return sds_ref",
    "docstring": "Get the reference number of the dataset.\n\n        Args::\n\n          no argument\n\n        Returns::\n\n          dataset reference number\n\n        C library equivalent : SDidtoref"
  },
  {
    "code": "def get_subtask_fields(config_class):\n    from lsst.pex.config import ConfigurableField, RegistryField\n    def is_subtask_field(obj):\n        return isinstance(obj, (ConfigurableField, RegistryField))\n    return _get_alphabetical_members(config_class, is_subtask_field)",
    "docstring": "Get all configurable subtask fields from a Config class.\n\n    Parameters\n    ----------\n    config_class : ``lsst.pipe.base.Config``-type\n        The configuration class (not an instance) corresponding to a Task.\n\n    Returns\n    -------\n    subtask_fields : `dict`\n        Mapping where keys are the config attribute names and values are\n        subclasses of ``lsst.pex.config.ConfigurableField`` or\n        ``RegistryField``). The mapping is alphabetically ordered by\n        attribute name."
  },
  {
    "code": "def _on_ready_read(self):\n        while self.bytesAvailable():\n            if not self._header_complete:\n                self._read_header()\n            else:\n                self._read_payload()",
    "docstring": "Read bytes when ready read"
  },
  {
    "code": "def match(sel, obj, arr=None, bailout_fn=None):\n    if arr:\n        sel = interpolate(sel, arr)\n    sel = parse(sel)[1]\n    return _forEach(sel, obj, bailout_fn=bailout_fn)",
    "docstring": "Match a selector to an object, yielding the matched values.\n\n    Args:\n        sel: The JSONSelect selector to apply (a string)\n        obj: The object against which to apply the selector\n        arr: If sel contains ? characters, then the values in this array will\n             be safely interpolated into the selector.\n        bailout_fn: A callback which takes two parameters, |obj| and |matches|.\n             This will be called on every node in obj. If it returns True, the\n             search for matches will be aborted below that node. The |matches|\n             parameter indicates whether the node matched the selector. This is\n             intended to be used as a performance optimization."
  },
  {
    "code": "def update(self, forecasts, observations):\n        if len(observations.shape) == 1:\n            obs_cdfs = np.zeros((observations.size, self.thresholds.size))\n            for o, observation in enumerate(observations):\n                obs_cdfs[o, self.thresholds >= observation] = 1\n        else:\n            obs_cdfs = observations\n        self.errors[\"F_2\"] += np.sum(forecasts ** 2, axis=0)\n        self.errors[\"F_O\"] += np.sum(forecasts * obs_cdfs, axis=0)\n        self.errors[\"O_2\"] += np.sum(obs_cdfs ** 2, axis=0)\n        self.errors[\"O\"] += np.sum(obs_cdfs, axis=0)\n        self.num_forecasts += forecasts.shape[0]",
    "docstring": "Update the statistics with forecasts and observations.\n\n        Args:\n            forecasts: The discrete Cumulative Distribution Functions of\n            observations:"
  },
  {
    "code": "def typed_assign_stmt_handle(self, tokens):\n        if len(tokens) == 2:\n            if self.target_info >= (3, 6):\n                return tokens[0] + \": \" + self.wrap_typedef(tokens[1])\n            else:\n                return tokens[0] + \" = None\" + self.wrap_comment(\" type: \" + tokens[1])\n        elif len(tokens) == 3:\n            if self.target_info >= (3, 6):\n                return tokens[0] + \": \" + self.wrap_typedef(tokens[1]) + \" = \" + tokens[2]\n            else:\n                return tokens[0] + \" = \" + tokens[2] + self.wrap_comment(\" type: \" + tokens[1])\n        else:\n            raise CoconutInternalException(\"invalid variable type annotation tokens\", tokens)",
    "docstring": "Process Python 3.6 variable type annotations."
  },
  {
    "code": "def get_total_irradiance(surface_tilt, surface_azimuth,\n                         solar_zenith, solar_azimuth,\n                         dni, ghi, dhi, dni_extra=None, airmass=None,\n                         albedo=.25, surface_type=None,\n                         model='isotropic',\n                         model_perez='allsitescomposite1990', **kwargs):\n    r\n    poa_sky_diffuse = get_sky_diffuse(\n        surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,\n        dni, ghi, dhi, dni_extra=dni_extra, airmass=airmass, model=model,\n        model_perez=model_perez)\n    poa_ground_diffuse = get_ground_diffuse(surface_tilt, ghi, albedo,\n                                            surface_type)\n    aoi_ = aoi(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth)\n    irrads = poa_components(aoi_, dni, poa_sky_diffuse, poa_ground_diffuse)\n    return irrads",
    "docstring": "r\"\"\"\n    Determine total in-plane irradiance and its beam, sky diffuse and ground\n    reflected components, using the specified sky diffuse irradiance model.\n\n    .. math::\n\n       I_{tot} = I_{beam} + I_{sky diffuse} + I_{ground}\n\n    Sky diffuse models include:\n        * isotropic (default)\n        * klucher\n        * haydavies\n        * reindl\n        * king\n        * perez\n\n    Parameters\n    ----------\n    surface_tilt : numeric\n        Panel tilt from horizontal.\n    surface_azimuth : numeric\n        Panel azimuth from north.\n    solar_zenith : numeric\n        Solar zenith angle.\n    solar_azimuth : numeric\n        Solar azimuth angle.\n    dni : numeric\n        Direct Normal Irradiance\n    ghi : numeric\n        Global horizontal irradiance\n    dhi : numeric\n        Diffuse horizontal irradiance\n    dni_extra : None or numeric, default None\n        Extraterrestrial direct normal irradiance\n    airmass : None or numeric, default None\n        Airmass\n    albedo : numeric, default 0.25\n        Surface albedo\n    surface_type : None or String, default None\n        Surface type. See grounddiffuse.\n    model : String, default 'isotropic'\n        Irradiance model.\n    model_perez : String, default 'allsitescomposite1990'\n        Used only if model='perez'. See :py:func:`perez`.\n\n    Returns\n    -------\n    total_irrad : OrderedDict or DataFrame\n        Contains keys/columns ``'poa_global', 'poa_direct', 'poa_diffuse',\n        'poa_sky_diffuse', 'poa_ground_diffuse'``."
  },
  {
    "code": "def alpha(requestContext, seriesList, alpha):\n    for series in seriesList:\n        series.options['alpha'] = alpha\n    return seriesList",
    "docstring": "Assigns the given alpha transparency setting to the series. Takes a float\n    value between 0 and 1."
  },
  {
    "code": "async def set_topic(self, topic):\n        self.topic = topic\n        try:\n            if self.topicchannel:\n                await client.edit_channel(self.topicchannel, topic=topic)\n        except Exception as e:\n            logger.exception(e)",
    "docstring": "Sets the topic for the topic channel"
  },
  {
    "code": "def to_doc(self, xmllist, decorates):\n        result = []\n        for xitem in xmllist:\n            if xitem.tag != \"group\":\n                if \"name\" in list(xitem.keys()):\n                    names = re.split(\"[\\s,]+\", xitem.get(\"name\"))\n                    for name in names:                        \n                        docel = DocElement(xitem, self, decorates)\n                        docel.attributes[\"name\"] = name\n                        result.append(docel)\n                else:\n                    result.append(DocElement(xitem, self, decorates))\n            else:\n                docel = DocGroup(xitem, decorates)\n                result.append(docel)\n        return result",
    "docstring": "Converts the specified xml list to a list of docstring elements."
  },
  {
    "code": "def delete(self, url, callback, json=None):\n        return self.adapter.delete(url, callback, json=json)",
    "docstring": "Delete a URL.\n\n        Args:\n\n            url(string): URL for the request\n\n            callback(func): The response callback function\n\n        Keyword Args:\n\n            json(dict): JSON body for the request\n\n        Returns:\n\n            The result of the callback handling the resopnse from the\n                executed request"
  },
  {
    "code": "def disconnect(self):\n        if self.proto:\n            log.debug('%r Disconnecting from %r', self, self.proto.transport.getPeer())\n            self.proto.transport.loseConnection()",
    "docstring": "Disconnect from the Kafka broker.\n\n        This is used to implement disconnection on timeout as a workaround for\n        Kafka connections occasionally getting stuck on the server side under\n        load. Requests are not cancelled, so they will be retried."
  },
  {
    "code": "def load_all_from_directory(self, directory_path):\n        datas = []\n        for root, folders, files in os.walk(directory_path):\n            for f in files:\n                datas.append(self.load_from_file(os.path.join(root, f)))\n        return datas",
    "docstring": "Return a list of dict from a directory containing files"
  },
  {
    "code": "def fileToMD5(filename, block_size=256*128, binary=False):\n    md5 = hashlib.md5()\n    with open(filename,'rb') as f:\n        for chunk in iter(lambda: f.read(block_size), b''):\n             md5.update(chunk)\n    if not binary:\n        return md5.hexdigest()\n    return md5.digest()",
    "docstring": "A function that calculates the MD5 hash of a file.\n\n    Args:\n    -----\n        filename: Path to the file.\n        block_size: Chunks of suitable size. Block size directly depends on\n            the block size of your filesystem to avoid performances issues.\n            Blocks of 4096 octets (Default NTFS).\n        binary: A boolean representing whether the returned info is in binary\n            format or not.\n\n    Returns:\n    --------\n        string: The  MD5 hash of the file."
  },
  {
    "code": "def decodedFileID(self, cachedFilePath):\n        fileDir, fileName = os.path.split(cachedFilePath)\n        assert fileDir == self.localCacheDir, 'Can\\'t decode uncached file names'\n        return base64.urlsafe_b64decode(fileName.encode('utf-8')).decode('utf-8')",
    "docstring": "Decode a cached fileName back to a job store file ID.\n\n        :param str cachedFilePath: Path to the cached file\n        :return: The jobstore file ID associated with the file\n        :rtype: str"
  },
  {
    "code": "def get_screen_size_range(self):\n    return GetScreenSizeRange(\n        display=self.display,\n        opcode=self.display.get_extension_major(extname),\n        window=self,\n        )",
    "docstring": "Retrieve the range of possible screen sizes. The screen may be set to\n\tany size within this range."
  },
  {
    "code": "def fixed_legend_position(self, fixed_legend_position):\n        allowed_values = [\"RIGHT\", \"TOP\", \"LEFT\", \"BOTTOM\"]\n        if fixed_legend_position not in allowed_values:\n            raise ValueError(\n                \"Invalid value for `fixed_legend_position` ({0}), must be one of {1}\"\n                .format(fixed_legend_position, allowed_values)\n            )\n        self._fixed_legend_position = fixed_legend_position",
    "docstring": "Sets the fixed_legend_position of this ChartSettings.\n\n        Where the fixed legend should be displayed with respect to the chart  # noqa: E501\n\n        :param fixed_legend_position: The fixed_legend_position of this ChartSettings.  # noqa: E501\n        :type: str"
  },
  {
    "code": "def get_final_window_monitor(cls, settings, window):\n        screen = window.get_screen()\n        use_mouse = settings.general.get_boolean('mouse-display')\n        dest_screen = settings.general.get_int('display-n')\n        if use_mouse:\n            win, x, y, _ = screen.get_root_window().get_pointer()\n            dest_screen = screen.get_monitor_at_point(x, y)\n        n_screens = screen.get_n_monitors()\n        if dest_screen > n_screens - 1:\n            settings.general.set_boolean('mouse-display', False)\n            settings.general.set_int('display-n', dest_screen)\n            dest_screen = screen.get_primary_monitor()\n        if dest_screen == ALWAYS_ON_PRIMARY:\n            dest_screen = screen.get_primary_monitor()\n        return dest_screen",
    "docstring": "Gets the final screen number for the main window of guake."
  },
  {
    "code": "def all_nbrs(self, node):\n        l = dict.fromkeys( self.inc_nbrs(node) + self.out_nbrs(node) )\n        return list(l)",
    "docstring": "List of nodes connected by incoming and outgoing edges"
  },
  {
    "code": "def plot_cylinder(ax, start, end, start_radius, end_radius,\n                  color='black', alpha=1., linspace_count=_LINSPACE_COUNT):\n    assert not np.all(start == end), 'Cylinder must have length'\n    x, y, z = generate_cylindrical_points(start, end, start_radius, end_radius,\n                                          linspace_count=linspace_count)\n    ax.plot_surface(x, y, z, color=color, alpha=alpha)",
    "docstring": "plot a 3d cylinder"
  },
  {
    "code": "def rank(self, value):\n        i = 0\n        n = len(self._tree)\n        rank = 0\n        count = 0\n        while i < n:\n            cur = self._tree[i]\n            if value < cur:\n                i = 2 * i + 1\n                continue\n            elif value > cur:\n                rank += self._counts[i]\n                nexti = 2 * i + 2\n                if nexti < n:\n                    rank -= self._counts[nexti]\n                    i = nexti\n                    continue\n                else:\n                    return (rank, count)\n            else:\n                count = self._counts[i]\n                lefti = 2 * i + 1\n                if lefti < n:\n                    nleft = self._counts[lefti]\n                    count -= nleft\n                    rank += nleft\n                    righti = lefti + 1\n                    if righti < n:\n                        count -= self._counts[righti]\n                return (rank, count)\n        return (rank, count)",
    "docstring": "Returns the rank and count of the value in the btree."
  },
  {
    "code": "def transform(function):\n        def transform_fn(_, result):\n            if isinstance(result, Nothing):\n                return result\n            lgr.debug(\"Transforming %r with %r\", result, function)\n            try:\n                return function(result)\n            except:\n                exctype, value, tb = sys.exc_info()\n                try:\n                    new_exc = StyleFunctionError(function, exctype, value)\n                    new_exc.__cause__ = None\n                    six.reraise(StyleFunctionError, new_exc, tb)\n                finally:\n                    del tb\n        return transform_fn",
    "docstring": "Return a processor for a style's \"transform\" function."
  },
  {
    "code": "def send_explode(self):\n        self.send_struct('<B', 20)\n        self.player.own_ids.clear()\n        self.player.cells_changed()\n        self.ingame = False\n        self.subscriber.on_death()",
    "docstring": "In earlier versions of the game, sending this caused your cells\n        to split into lots of small cells and die."
  },
  {
    "code": "def plot(self, x, y, color=\"black\"):\n        p = Point(x, y)\n        p.fill(color)\n        p.draw(self)",
    "docstring": "Uses coordinant system."
  },
  {
    "code": "def pwm_min_score(self):\n        if self.min_score is None:\n            score = 0\n            for row in self.pwm:\n                score += log(min(row) / 0.25 + 0.01)\n            self.min_score = score\n        return self.min_score",
    "docstring": "Return the minimum PWM score.\n\n        Returns\n        -------\n        score : float\n            Minimum PWM score."
  },
  {
    "code": "def subscribe_account(self, username, password, service):\n        data = {\n            'service': service,\n            'username': username,\n            'password': password,\n        }\n        return self._perform_post_request(self.subscribe_account_endpoint, data, self.token_header)",
    "docstring": "Subscribe an account for a service."
  },
  {
    "code": "def post(self, resource):\n        response = self.api.execute(\n            \"POST\", self.endpoint, json=(resource.as_dict()))\n        if not response.ok:\n            raise Error.parse(response.json())\n        return self._cls.parse(response.json())",
    "docstring": "Creates a new instance of the resource.\n\n        Args:\n            resource - gophish.models.Model - The resource instance"
  },
  {
    "code": "def validate_unset_command(self, line: str, position: int, annotation: str) -> None:\n        if annotation not in self.annotations:\n            raise MissingAnnotationKeyWarning(self.get_line_number(), line, position, annotation)",
    "docstring": "Raise an exception when trying to ``UNSET X`` if ``X`` is not already set.\n\n        :raises: MissingAnnotationKeyWarning"
  },
  {
    "code": "def marshall_key(self, key):\n        if key in self.__keys:\n            return self.__keys[key]\n        skey = pickle.dumps(key, protocol = 0)\n        if self.compressKeys:\n            skey = zlib.compress(skey, zlib.Z_BEST_COMPRESSION)\n        if self.escapeKeys:\n            skey = skey.encode('hex')\n        if self.binaryKeys:\n            skey = buffer(skey)\n        self.__keys[key] = skey\n        return skey",
    "docstring": "Marshalls a Crash key to be used in the database.\n\n        @see: L{__init__}\n\n        @type  key: L{Crash} key.\n        @param key: Key to convert.\n\n        @rtype:  str or buffer\n        @return: Converted key."
  },
  {
    "code": "def get_unicodedata():\n    import unicodedata\n    fail = False\n    uver = unicodedata.unidata_version\n    path = os.path.join(os.path.dirname(__file__), 'tools')\n    fp, pathname, desc = imp.find_module('unidatadownload', [path])\n    try:\n        unidatadownload = imp.load_module('unidatadownload', fp, pathname, desc)\n        unidatadownload.get_unicodedata(uver, no_zip=True)\n    except Exception:\n        print(traceback.format_exc())\n        fail = True\n    finally:\n        fp.close()\n    assert not fail, \"Failed to obtain unicodedata!\"\n    return uver",
    "docstring": "Download the `unicodedata` version for the given Python version."
  },
  {
    "code": "def vm_info(vm_=None):\n    with _get_xapi_session() as xapi:\n        def _info(vm_):\n            vm_rec = _get_record_by_label(xapi, 'VM', vm_)\n            if vm_rec is False:\n                return False\n            vm_metrics_rec = _get_metrics_record(xapi, 'VM', vm_rec)\n            return {'cpu': vm_metrics_rec['VCPUs_number'],\n                    'maxCPU': _get_val(vm_rec, ['VCPUs_max']),\n                    'cputime': vm_metrics_rec['VCPUs_utilisation'],\n                    'disks': get_disks(vm_),\n                    'nics': get_nics(vm_),\n                    'maxMem': int(_get_val(vm_rec, ['memory_dynamic_max'])),\n                    'mem': int(vm_metrics_rec['memory_actual']),\n                    'state': _get_val(vm_rec, ['power_state'])\n                    }\n        info = {}\n        if vm_:\n            ret = _info(vm_)\n            if ret is not None:\n                info[vm_] = ret\n        else:\n            for vm_ in list_domains():\n                ret = _info(vm_)\n                if ret is not None:\n                    info[vm_] = _info(vm_)\n        return info",
    "docstring": "Return detailed information about the vms.\n\n    If you pass a VM name in as an argument then it will return info\n    for just the named VM, otherwise it will return all VMs.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' virt.vm_info"
  },
  {
    "code": "def load( self, stats ):\n        rows = self.rows\n        for func, raw in stats.iteritems():\n            try:\n                rows[func] = row = PStatRow( func,raw )\n            except ValueError, err:\n                log.info( 'Null row: %s', func )\n        for row in rows.itervalues():\n            row.weave( rows )\n        return self.find_root( rows )",
    "docstring": "Build a squaremap-compatible model from a pstats class"
  },
  {
    "code": "def error_count(self):\n        count = 0\n        for error_list in self.error_dict.values():\n            count += len(error_list)\n        return count",
    "docstring": "Returns the total number of validation errors for this row."
  },
  {
    "code": "def level(self):\n        res = len(self._scope_stack)\n        if self._parent is not None:\n            res += self._parent.level()\n        return res",
    "docstring": "Return the current scope level"
  },
  {
    "code": "def get_postcodedata(self, postcode, nr, addition=\"\", **params):\n        endpoint = 'rest/addresses/%s/%s' % (postcode, nr)\n        if addition:\n            endpoint += '/' + addition\n        retValue = self._API__request(endpoint, params=params)\n        if addition and addition.upper() not in \\\n           [a.upper() for a in retValue['houseNumberAdditions']]:\n            raise PostcodeError(\n                    \"ERRHouseNumberAdditionInvalid\",\n                    {\"exceptionId\": \"ERRHouseNumberAdditionInvalid\",\n                     \"exception\": \"Invalid housenumber addition: '%s'\" %\n                     retValue['houseNumberAddition'],\n                     \"validHouseNumberAdditions\":\n                     retValue['houseNumberAdditions']})\n        return retValue",
    "docstring": "get_postcodedata - fetch information for 'postcode'.\n\n        Parameters\n        ----------\n        postcode : string\n            The full (dutch) postcode\n\n        nr : int\n            The housenumber\n\n        addition : string (optional)\n            the extension to a housenumber\n\n        params : dict (optional)\n            a list of parameters to send with the request.\n\n        returns :\n            a response dictionary"
  },
  {
    "code": "def count_vocab_items(self, counter: Dict[str, Dict[str, int]]):\n        for field in self.fields.values():\n            field.count_vocab_items(counter)",
    "docstring": "Increments counts in the given ``counter`` for all of the vocabulary items in all of the\n        ``Fields`` in this ``Instance``."
  },
  {
    "code": "def __pkg_upgrade_flags(self, flags):\n        flag, skip = [], \"\"\n        if flags[0] in self.args:\n            for arg in self.args[3:]:\n                if arg.startswith(flags[1]):\n                    skip = Regex(arg.split(\"=\")[1]).get()\n                    self.args.remove(arg)\n                if arg in flags:\n                    flag.append(arg)\n                    if arg in self.args:\n                        self.args.remove(arg)\n        return flag, skip",
    "docstring": "Manage flags for package upgrade option"
  },
  {
    "code": "def FromData(cls, stream, json_data, http=None, auto_transfer=None,\n                 **kwds):\n        info = json.loads(json_data)\n        missing_keys = cls._REQUIRED_SERIALIZATION_KEYS - set(info.keys())\n        if missing_keys:\n            raise exceptions.InvalidDataError(\n                'Invalid serialization data, missing keys: %s' % (\n                    ', '.join(missing_keys)))\n        download = cls.FromStream(stream, **kwds)\n        if auto_transfer is not None:\n            download.auto_transfer = auto_transfer\n        else:\n            download.auto_transfer = info['auto_transfer']\n        setattr(download, '_Download__progress', info['progress'])\n        setattr(download, '_Download__total_size', info['total_size'])\n        download._Initialize(\n            http, info['url'])\n        return download",
    "docstring": "Create a new Download object from a stream and serialized data."
  },
  {
    "code": "def _set_attributes(self):\n        for parameter, data in self._data.items():\n            if isinstance(data, dict) or isinstance(data, OrderedDict):\n                field_names, field_values = zip(*data.items())\n                sorted_indices = np.argsort(field_names)\n                attr = namedtuple(\n                    parameter, [field_names[i] for i in sorted_indices]\n                )\n                setattr(\n                    self, parameter,\n                    attr(*[field_values[i] for i in sorted_indices])\n                )\n            else:\n                setattr(self, parameter, data)",
    "docstring": "Traverse the internal dictionary and set the getters"
  },
  {
    "code": "def decode_netloc(self):\n        rv = _decode_idna(self.host or '')\n        if ':' in rv:\n            rv = '[%s]' % rv\n        port = self.port\n        if port is not None:\n            rv = '%s:%d' % (rv, port)\n        auth = ':'.join(filter(None, [\n            _url_unquote_legacy(self.raw_username or '', '/:%@'),\n            _url_unquote_legacy(self.raw_password or '', '/:%@'),\n        ]))\n        if auth:\n            rv = '%s@%s' % (auth, rv)\n        return rv",
    "docstring": "Decodes the netloc part into a string."
  },
  {
    "code": "def current_task(self, args):\n        ctask = self.nice_name if self.nice_name is not None else self.name\n        if args is not None:\n            if args.update:\n                ctask = ctask.replace('%pre', 'Updating')\n            else:\n                ctask = ctask.replace('%pre', 'Loading')\n        return ctask",
    "docstring": "Name of current action for progress-bar output.\n\n        The specific task string is depends on the configuration via `args`.\n\n        Returns\n        -------\n        ctask : str\n            String representation of this task."
  },
  {
    "code": "def convert_feature_layers_to_dict(feature_layers):\n    features_by_layer = {}\n    for feature_layer in feature_layers:\n        layer_name = feature_layer['name']\n        features = feature_layer['features']\n        features_by_layer[layer_name] = features\n    return features_by_layer",
    "docstring": "takes a list of 'feature_layer' objects and converts to a dict\n       keyed by the layer name"
  },
  {
    "code": "def register_callback(self, key):\n        if self.pending_callbacks is None:\n            self.pending_callbacks = set()\n            self.results = {}\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)",
    "docstring": "Adds ``key`` to the list of callbacks."
  },
  {
    "code": "def log_error(self, callback, error=None):\n        print(\"Uncaught error during callback: {}\".format(callback))\n        print(\"Error: {}\".format(error))",
    "docstring": "Log the error that occurred when running the given callback."
  },
  {
    "code": "def mute(model: Model):\n    if not isinstance(model, Model):\n        raise TypeError(\"Expected a Model, not %r.\" % model)\n    restore = model.__dict__.get(\"_notify_model_views\")\n    model._notify_model_views = lambda e: None\n    try:\n        yield\n    finally:\n        if restore is None:\n            del model._notify_model_views\n        else:\n            model._notify_model_views = restore",
    "docstring": "Block a model's views from being notified.\n\n    All changes within a \"mute\" context will be blocked. No content is yielded to the\n    user as in :func:`hold`, and the views of the model are never notified that changes\n    took place.\n\n    Parameters:\n        mode: The model whose change events will be blocked.\n\n    Examples:\n\n        The view is never called due to the :func:`mute` context:\n\n        .. code-block:: python\n\n            from spectate import mvc\n\n            l = mvc.List()\n\n            @mvc.view(l)\n            def raises(events):\n                raise ValueError(\"Events occured!\")\n\n            with mvc.mute(l):\n                l.append(1)"
  },
  {
    "code": "def show_busy(self):\n        self.progress_bar.show()\n        self.parent.pbnNext.setEnabled(False)\n        self.parent.pbnBack.setEnabled(False)\n        self.parent.pbnCancel.setEnabled(False)\n        self.parent.repaint()\n        enable_busy_cursor()\n        QgsApplication.processEvents()",
    "docstring": "Lock buttons and enable the busy cursor."
  },
  {
    "code": "def findport(self, port):\n        for p in self.ports:\n            if p[0] == p:\n                return p\n        p = (port, [])\n        self.ports.append(p)\n        return p",
    "docstring": "Find and return a port tuple for the specified port.\n        Created and added when not found.\n        @param port: A port.\n        @type port: I{service.Port}\n        @return: A port tuple.\n        @rtype: (port, [method])"
  },
  {
    "code": "async def builds(self, *args, **kwargs):\n        return await self._makeApiCall(self.funcinfo[\"builds\"], *args, **kwargs)",
    "docstring": "List of Builds\n\n        A paginated list of builds that have been run in\n        Taskcluster. Can be filtered on various git-specific\n        fields.\n\n        This method gives output: ``v1/build-list.json#``\n\n        This method is ``experimental``"
  },
  {
    "code": "def config_dict(config):\n    return dict(\n        (key, getattr(config, key))\n        for key in config.values\n    )",
    "docstring": "Given a Sphinx config object, return a dictionary of config\n    values."
  },
  {
    "code": "def bundle_attacks_with_goal(sess, model, x, y, adv_x, attack_configs,\n                             run_counts,\n                             goal, report, report_path,\n                             attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE):\n  goal.start(run_counts)\n  _logger.info(\"Running criteria for new goal...\")\n  criteria = goal.get_criteria(sess, model, adv_x, y, batch_size=eval_batch_size)\n  assert 'correctness' in criteria\n  _logger.info(\"Accuracy: \" + str(criteria['correctness'].mean()))\n  assert 'confidence' in criteria\n  while not goal.is_satisfied(criteria, run_counts):\n    run_batch_with_goal(sess, model, x, y, adv_x, criteria, attack_configs,\n                        run_counts,\n                        goal, report, report_path,\n                        attack_batch_size=attack_batch_size)\n  report.completed = True\n  save(criteria, report, report_path, adv_x)",
    "docstring": "Runs attack bundling, working on one specific AttackGoal.\n  This function is mostly intended to be called by `bundle_attacks`.\n\n  Reference: https://openreview.net/forum?id=H1g0piA9tQ\n\n  :param sess: tf.session.Session\n  :param model: cleverhans.model.Model\n  :param x: numpy array containing clean example inputs to attack\n  :param y: numpy array containing true labels\n  :param adv_x: numpy array containing the adversarial examples made so far\n    by earlier work in the bundling process\n  :param attack_configs: list of AttackConfigs to run\n  :param run_counts: dict mapping AttackConfigs to numpy arrays specifying\n    how many times they have been run on each example\n  :param goal: AttackGoal to run\n  :param report: ConfidenceReport\n  :param report_path: str, the path the report will be saved to\n  :param attack_batch_size: int, batch size for generating adversarial examples\n  :param eval_batch_size: int, batch size for evaluating the model on adversarial examples"
  },
  {
    "code": "def _repr_mimebundle_(self, *args, **kwargs):\n        try:\n            if self.logo:\n                p = pn.Row(\n                    self.logo_panel,\n                    self.panel,\n                    margin=0)\n                return p._repr_mimebundle_(*args, **kwargs)\n            else:\n                return self.panel._repr_mimebundle_(*args, **kwargs)\n        except:\n            raise RuntimeError(\"Panel does not seem to be set up properly\")",
    "docstring": "Display in a notebook or a server"
  },
  {
    "code": "def general_setting(key, default=None, expected_type=None, qsettings=None):\n    if qsettings is None:\n        qsettings = QSettings()\n    try:\n        if isinstance(expected_type, type):\n            return qsettings.value(key, default, type=expected_type)\n        else:\n            return qsettings.value(key, default)\n    except TypeError as e:\n        LOGGER.debug('exception %s' % e)\n        LOGGER.debug('%s %s %s' % (key, default, expected_type))\n        return qsettings.value(key, default)",
    "docstring": "Helper function to get a value from settings.\n\n    :param key: Unique key for setting.\n    :type key: basestring\n\n    :param default: The default value in case of the key is not found or there\n        is an error.\n    :type default: basestring, None, boolean, int, float\n\n    :param expected_type: The type of object expected.\n    :type expected_type: type\n\n    :param qsettings: A custom QSettings to use. If it's not defined, it will\n        use the default one.\n    :type qsettings: qgis.PyQt.QtCore.QSettings\n\n    :returns: The value of the key in the setting.\n    :rtype: object\n\n    Note:\n    The API for QSettings to get a value is different for PyQt and Qt C++.\n    In PyQt we can specify the expected type.\n    See: http://pyqt.sourceforge.net/Docs/PyQt4/qsettings.html#value"
  },
  {
    "code": "def buildprior(self, prior, mopt=None, extend=False):\n        \" Extract the model's parameters from prior. \"\n        newprior = {}\n        intercept, slope = gv.get_dictkeys(\n            prior, [self.intercept, self.slope]\n            )\n        newprior[intercept] = prior[intercept]\n        if mopt is None:\n            newprior[slope] = prior[slope]\n        return newprior",
    "docstring": "Extract the model's parameters from prior."
  },
  {
    "code": "def find(self, collection, query):\n        obj = getattr(self.db, collection)\n        result = obj.find(query)\n        return result",
    "docstring": "Search a collection for the query provided. Just a raw interface to\n        mongo to do any query you want.\n\n        Args:\n            collection: The db collection. See main class documentation.\n            query: A mongo find query.\n        Returns:\n            pymongo Cursor object with the results."
  },
  {
    "code": "def get(self, request, *args, **kwargs):\n        self.get_layer()\n        nodes = self.get_nodes(request, *args, **kwargs)\n        return Response(nodes)",
    "docstring": "Retrieve list of nodes of the specified layer"
  },
  {
    "code": "def kde_peak(self, name, npoints=_npoints, **kwargs):\n        data = self.get(name,**kwargs)\n        return kde_peak(data,npoints)",
    "docstring": "Calculate peak of kernel density estimator"
  },
  {
    "code": "def create(self, permission):\n        parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', 'single', {'id': self.parent_object.id})\n        target_url = parent_url + self.client.get_url_path(self._URL_KEY, 'POST', 'single')\n        r = self.client.request('POST', target_url, json=permission._serialize())\n        return permission._deserialize(r.json(), self)",
    "docstring": "Create single permission for the given object.\n\n        :param Permission permission: A single Permission object to be set."
  },
  {
    "code": "def get_as_type_with_default(self, key, value_type, default_value):\n        value = self.get(key)\n        return TypeConverter.to_type_with_default(value_type, value, default_value)",
    "docstring": "Converts map element into a value defined by specied typecode.\n        If conversion is not possible it returns default value.\n\n        :param key: an index of element to get.\n\n        :param value_type: the TypeCode that defined the type of the result\n\n        :param default_value: the default value\n\n        :return: element value defined by the typecode or default value if conversion is not supported."
  },
  {
    "code": "def _get_cputemp_with_lmsensors(self, zone=None):\n        sensors = None\n        command = [\"sensors\"]\n        if zone:\n            try:\n                sensors = self.py3.command_output(command + [zone])\n            except self.py3.CommandError:\n                pass\n        if not sensors:\n            sensors = self.py3.command_output(command)\n        m = re.search(\"(Core 0|CPU Temp).+\\+(.+).+\\(.+\", sensors)\n        if m:\n            cpu_temp = float(m.groups()[1].strip()[:-2])\n        else:\n            cpu_temp = \"?\"\n        return cpu_temp",
    "docstring": "Tries to determine CPU temperature using the 'sensors' command.\n        Searches for the CPU temperature by looking for a value prefixed\n        by either \"CPU Temp\" or \"Core 0\" - does not look for or average\n        out temperatures of all codes if more than one."
  },
  {
    "code": "def preprocess(content, options):\n    lines_enum = enumerate(content.splitlines(), start=1)\n    lines_enum = join_lines(lines_enum)\n    lines_enum = ignore_comments(lines_enum)\n    lines_enum = skip_regex(lines_enum, options)\n    lines_enum = expand_env_variables(lines_enum)\n    return lines_enum",
    "docstring": "Split, filter, and join lines, and return a line iterator\n\n    :param content: the content of the requirements file\n    :param options: cli options"
  },
  {
    "code": "def create_results_dir(self):\n    self._current_results_dir = self._cache_manager._results_dir_path(self.cache_key, stable=False)\n    self._results_dir = self._cache_manager._results_dir_path(self.cache_key, stable=True)\n    if not self.valid:\n      safe_mkdir(self._current_results_dir, clean=True)\n    relative_symlink(self._current_results_dir, self._results_dir)\n    self.ensure_legal()",
    "docstring": "Ensure that the empty results directory and a stable symlink exist for these versioned targets."
  },
  {
    "code": "def is_installed(self, bug: Bug) -> bool:\n        return self.__installation.build.is_installed(bug.image)",
    "docstring": "Determines whether or not the Docker image for a given bug has been\n        installed onto this server.\n\n        See: `BuildManager.is_installed`"
  },
  {
    "code": "def get_paginator(\n        self,\n        dataset,\n        per_page,\n        orphans=0,\n        allow_empty_first_page=True,\n        **kwargs\n    ):\n        return IndefinitePaginator(\n            dataset,\n            per_page,\n            orphans=orphans,\n            allow_empty_first_page=allow_empty_first_page,\n            **kwargs\n        )",
    "docstring": "Return an instance of the paginator for this view."
  },
  {
    "code": "def guess_format(url):\n    import requests\n    from requests.exceptions import InvalidSchema\n    from rowgenerators import parse_url_to_dict\n    parts = parse_url_to_dict(url)\n    if parts.get('path'):\n        type, encoding = mimetypes.guess_type(url)\n    elif parts['scheme'] in ('http', 'https'):\n        type, encoding = 'text/html', None\n    else:\n        type, encoding = None, None\n    if type is None:\n        try:\n            r = requests.head(url, allow_redirects=False)\n            type = r.headers['Content-Type']\n            if ';' in type:\n                type, encoding = [e.strip() for e in type.split(';')]\n        except InvalidSchema:\n            pass\n    return type, mime_map.get(type)",
    "docstring": "Try to guess  the format of a resource, possibly with a HEAD request"
  },
  {
    "code": "async def get_friendly_name(self) -> Text:\n        if 'first_name' not in self._user:\n            user = await self._get_full_user()\n        else:\n            user = self._user\n        return user.get('first_name')",
    "docstring": "Let's use the first name of the user as friendly name. In some cases\n        the user object is incomplete, and in those cases the full user is\n        fetched."
  },
  {
    "code": "def wait_for_close(\n        raiden: 'RaidenService',\n        payment_network_id: PaymentNetworkID,\n        token_address: TokenAddress,\n        channel_ids: List[ChannelID],\n        retry_timeout: float,\n) -> None:\n    return wait_for_channel_in_states(\n        raiden=raiden,\n        payment_network_id=payment_network_id,\n        token_address=token_address,\n        channel_ids=channel_ids,\n        retry_timeout=retry_timeout,\n        target_states=CHANNEL_AFTER_CLOSE_STATES,\n    )",
    "docstring": "Wait until all channels are closed.\n\n    Note:\n        This does not time out, use gevent.Timeout."
  },
  {
    "code": "def calcTemperature(self):\n        try:\n            return eq.MeanPlanetTemp(self.albedo, self.star.T, self.star.R, self.a).T_p\n        except (ValueError, HierarchyError):\n            return np.nan",
    "docstring": "Calculates the temperature using which uses equations.MeanPlanetTemp, albedo assumption and potentially\n        equations.starTemperature.\n\n        issues\n        - you cant get the albedo assumption without temp but you need it to calculate the temp."
  },
  {
    "code": "def activate(self, resource=None, timeout=3, wait_for_finish=False):\n        return Task.execute(self, 'activate', json={'resource': resource},\n            timeout=timeout, wait_for_finish=wait_for_finish)",
    "docstring": "Activate this package on the SMC\n\n        :param list resource: node href's to activate on. Resource is only\n               required for software upgrades\n        :param int timeout: timeout between queries\n        :raises TaskRunFailed: failure during activation (downloading, etc)\n        :rtype: TaskOperationPoller"
  },
  {
    "code": "def lookup(instruction, instructions = None):\n    if instructions is None:\n        instructions = default_instructions\n    if isinstance(instruction, str):\n        return instructions[instruction]\n    elif hasattr(instruction, \"__call__\"):\n        rev = dict(((v,k) for (k,v) in instructions.items()))\n        return rev[instruction]\n    else:\n        raise errors.MachineError(KeyError(\"Unknown instruction: %s\" %\n            str(instruction)))",
    "docstring": "Looks up instruction, which can either be a function or a string.\n    If it's a string, returns the corresponding method.\n    If it's a function, returns the corresponding name."
  },
  {
    "code": "def place_items_in_square(items, t):\n    rows = [(t, y, []) for y in range(t)]\n    for item in items:\n        x = item % t\n        y = item // t\n        inverse_length, _, row_contents = rows[y]\n        heapq.heappush(row_contents, (x, item))\n        rows[y] = inverse_length - 1, y, row_contents\n    assert all(inv_len == t - len(rows) for inv_len, _, rows in rows)\n    heapq.heapify(rows)\n    return [row for row in rows if row[2]]",
    "docstring": "Returns a list of rows that are stored as a priority queue to be\n    used with heapq functions.\n\n    >>> place_items_in_square([1,5,7], 4)\n    [(2, 1, [(1, 5), (3, 7)]), (3, 0, [(1, 1)])]\n    >>> place_items_in_square([1,5,7], 3)\n    [(2, 0, [(1, 1)]), (2, 1, [(2, 5)]), (2, 2, [(1, 7)])]"
  },
  {
    "code": "def oldapi_request(self, method, endpoint, **kwargs):\n        headers = kwargs.setdefault('headers', {})\n        headers['Client-ID'] = CLIENT_ID\n        url = TWITCH_APIURL + endpoint\n        return self.request(method, url, **kwargs)",
    "docstring": "Make a request to one of the old api endpoints.\n\n        The url will be constructed of :data:`TWITCH_APIURL` and\n        the given endpoint.\n\n        :param method: the request method\n        :type method: :class:`str`\n        :param endpoint: the endpoint of the old api.\n                         The base url is automatically provided.\n        :type endpoint: :class:`str`\n        :param kwargs: keyword arguments of :meth:`requests.Session.request`\n        :returns: a resonse object\n        :rtype: :class:`requests.Response`\n        :raises: :class:`requests.HTTPError`"
  },
  {
    "code": "def correct_entry(self, entry):\n        entry.correction.update(self.get_correction(entry))\n        return entry",
    "docstring": "Corrects a single entry.\n\n        Args:\n            entry: A DefectEntry object.\n\n        Returns:\n            An processed entry.\n\n        Raises:\n            CompatibilityError if entry is not compatible."
  },
  {
    "code": "def partition(self, ref=None, **kwargs):\n        from .exc import NotFoundError\n        from six import text_type\n        if ref:\n            for p in self.partitions:\n                if (text_type(ref) == text_type(p.name) or text_type(ref) == text_type(p.id) or\n                            text_type(ref) == text_type(p.vid)):\n                    return p\n            raise NotFoundError(\"Failed to find partition for ref '{}' in dataset '{}'\".format(ref, self.name))\n        elif kwargs:\n            from ..identity import PartitionNameQuery\n            pnq = PartitionNameQuery(**kwargs)\n            return self._find_orm",
    "docstring": "Returns partition by ref."
  },
  {
    "code": "def _keys(self, pattern):\n        result = []\n        for client in self.redis_clients:\n            result.extend(list(client.scan_iter(match=pattern)))\n        return result",
    "docstring": "Execute the KEYS command on all Redis shards.\n\n        Args:\n            pattern: The KEYS pattern to query.\n\n        Returns:\n            The concatenated list of results from all shards."
  },
  {
    "code": "def _decorate_urlconf(urlpatterns, decorator=require_auth, *args, **kwargs):\n    if isinstance(urlpatterns, (list, tuple)):\n        for pattern in urlpatterns:\n            if getattr(pattern, 'callback', None):\n                pattern._callback = decorator(\n                    pattern.callback, *args, **kwargs)\n            if getattr(pattern, 'url_patterns', []):\n                _decorate_urlconf(\n                    pattern.url_patterns, decorator, *args, **kwargs)\n    else:\n        if getattr(urlpatterns, 'callback', None):\n            urlpatterns._callback = decorator(\n                urlpatterns.callback, *args, **kwargs)",
    "docstring": "Decorate all urlpatterns by specified decorator"
  },
  {
    "code": "def _remove(self, handler, send_event=True):\n        for event in self:\n            event.remove_handlers_bound_to_instance(handler)\n        self.handlers.remove(handler)\n        if send_event:\n            self.on_handler_remove(handler)",
    "docstring": "Remove handler instance and detach any methods bound to it from uninhibited.\n\n        :param object handler: handler instance\n        :return object: The handler you added is given back so this can be used as a decorator."
  },
  {
    "code": "def _parse_resource(resource):\n        resource = resource.strip() if resource else resource\n        if resource in {ME_RESOURCE, USERS_RESOURCE}:\n            return resource\n        elif '@' in resource and not resource.startswith(USERS_RESOURCE):\n            return '{}/{}'.format(USERS_RESOURCE, resource)\n        else:\n            return resource",
    "docstring": "Parses and completes resource information"
  },
  {
    "code": "def register(self, prefix, viewset, basename, factory=None, permission=None):\n        lookup = self.get_lookup(viewset)\n        routes = self.get_routes(viewset)\n        for route in routes:\n            mapping = self.get_method_map(viewset, route.mapping)\n            if not mapping:\n                continue\n            url = route.url.format(\n                prefix=prefix,\n                lookup=lookup,\n                trailing_slash=self.trailing_slash\n            )\n            view = viewset.as_view(mapping, **route.initkwargs)\n            name = route.name.format(basename=basename)\n            if factory:\n                self.configurator.add_route(name, url, factory=factory)\n            else:\n                self.configurator.add_route(name, url)\n            self.configurator.add_view(view, route_name=name, permission=permission)",
    "docstring": "Factory and permission are likely only going to exist until I have enough time\n        to write a permissions module for PRF.\n\n        :param prefix: the uri route prefix.\n        :param viewset: The ViewSet class to route.\n        :param basename: Used to name the route in pyramid.\n        :param factory: Optional, root factory to be used as the context to the route.\n        :param permission: Optional, permission to assign the route."
  },
  {
    "code": "def log(verbose=False):\n    terminal.log.config(verbose=verbose)\n    terminal.log.info('this is a info message')\n    terminal.log.verbose.info('this is a verbose message')",
    "docstring": "print a log test\n\n    :param verbose: show more logs"
  },
  {
    "code": "def _removeHeaderTag(header, tag):\n    if header.startswith(tag):\n        tagPresent = True\n        header = header[len(tag):]\n    else:\n        tagPresent = False\n    return header, tagPresent",
    "docstring": "Removes a tag from the beginning of a header string.\n\n    :param header: str\n    :param tag: str\n    :returns: (str, bool), header without the tag and a bool that indicates\n        wheter the tag was present."
  },
  {
    "code": "def flatten_dict(dict_obj, separator='.', flatten_lists=False):\n    reducer = _get_key_reducer(separator)\n    flat = {}\n    def _flatten_key_val(key, val, parent):\n        flat_key = reducer(parent, key)\n        try:\n            _flatten(val, flat_key)\n        except TypeError:\n            flat[flat_key] = val\n    def _flatten(d, parent=None):\n        try:\n            for key, val in d.items():\n                _flatten_key_val(key, val, parent)\n        except AttributeError:\n            if isinstance(d, (str, bytes)):\n                raise TypeError\n            for i, value in enumerate(d):\n                _flatten_key_val(str(i), value, parent)\n    _flatten(dict_obj)\n    return flat",
    "docstring": "Flattens the given dict into a single-level dict with flattend keys.\n\n    Parameters\n    ----------\n    dict_obj : dict\n        A possibly nested dict.\n    separator : str, optional\n        The character to use as a separator between keys. Defaults to '.'.\n    flatten_lists : bool, optional\n        If True, list values are also flattened. False by default.\n\n    Returns\n    -------\n    dict\n        A shallow dict, where no value is a dict in itself, and keys are\n        concatenations of original key paths separated with the given\n        separator.\n\n    Example\n    -------\n    >>> dicti = {'a': 1, 'b': {'g': 4, 'o': 9}, 'x': [4, 'd']}\n    >>> flat = flatten_dict(dicti)\n    >>> sorted(flat.items())\n    [('a', 1), ('b.g', 4), ('b.o', 9), ('x.0', 4), ('x.1', 'd')]"
  },
  {
    "code": "def convert_upsample(net, node, module, builder):\n    input_name, output_name = _get_input_output_name(net, node)\n    name = node['name']\n    param = _get_attr(node)\n    inputs = node['inputs']\n    args, _ = module.get_params()\n    scale = literal_eval(param['scale'])\n    if 'sample_type' in param.keys():\n        method = param['sample_type']\n        if method == 'nearest':\n            mode = 'NN'\n        elif method == '':\n            mode = 'BILINEAR'\n    builder.add_upsample(name, scaling_factor_h=scale, scaling_factor_w=scale,\n                         input_name=input_name, output_name=output_name, mode=mode)",
    "docstring": "Convert a UpSampling layer from mxnet to coreml.\n\n    Parameters\n    ----------\n    net: network\n        A mxnet network object.\n\n    node: layer\n        Node to convert.\n\n    module: module\n        An module for MXNet\n\n    builder: NeuralNetworkBuilder\n        A neural network builder object."
  },
  {
    "code": "def generate(self, **kwargs):\n        descriptions = []\n        subjs = self.layout.get_subjects(**kwargs)\n        kwargs = {k: v for k, v in kwargs.items() if k != 'subject'}\n        for sid in subjs:\n            descriptions.append(self._report_subject(subject=sid, **kwargs))\n        counter = Counter(descriptions)\n        print('Number of patterns detected: {0}'.format(len(counter.keys())))\n        print(utils.reminder())\n        return counter",
    "docstring": "Generate the methods section.\n\n        Parameters\n        ----------\n        task_converter : :obj:`dict`, optional\n            A dictionary with information for converting task names from BIDS\n            filename format to human-readable strings.\n\n        Returns\n        -------\n        counter : :obj:`collections.Counter`\n            A dictionary of unique descriptions across subjects in the dataset,\n            along with the number of times each pattern occurred. In cases\n            where all subjects underwent the same protocol, the most common\n            pattern is most likely the most complete. In cases where the\n            dataset contains multiple protocols, each pattern will need to be\n            inspected manually.\n\n        Examples\n        --------\n        >>> from os.path import join\n        >>> from bids.layout import BIDSLayout\n        >>> from bids.reports import BIDSReport\n        >>> from bids.tests import get_test_data_path\n        >>> layout = BIDSLayout(join(get_test_data_path(), 'synthetic'))\n        >>> report = BIDSReport(layout)\n        >>> counter = report.generate(session='01')\n        >>> counter.most_common()[0][0]"
  },
  {
    "code": "def add_user(self, name, password=None, read_only=None, db=None, **kwargs):\n        if db is None:\n            return self.get_connection().admin.add_user(\n                    name, password=password, read_only=read_only, **kwargs)\n        return self.get_connection()[db].add_user(\n                    name, password=password, read_only=read_only, **kwargs)",
    "docstring": "Adds a user that can be used for authentication"
  },
  {
    "code": "def __remove_temp_logging_handler():\n    if is_logging_configured():\n        return\n    __remove_null_logging_handler()\n    root_logger = logging.getLogger()\n    global LOGGING_TEMP_HANDLER\n    for handler in root_logger.handlers:\n        if handler is LOGGING_TEMP_HANDLER:\n            root_logger.removeHandler(LOGGING_TEMP_HANDLER)\n            LOGGING_TEMP_HANDLER = None\n            break\n    if sys.version_info >= (2, 7):\n        logging.captureWarnings(True)",
    "docstring": "This function will run once logging has been configured. It just removes\n    the temporary stream Handler from the logging handlers."
  },
  {
    "code": "def validate_input(self):\n        if self.vert[1] <= self.vert[0]:\n            raise ValueError(u'{} must be larger than {}'.format(self.vert[1], self.vert[0]))",
    "docstring": "Raise appropriate exception if gate was defined incorrectly."
  },
  {
    "code": "def as_partition(self, **kwargs):\n        return PartitionName(**dict(list(self.dict.items()) + list(kwargs.items())))",
    "docstring": "Return a PartitionName based on this name."
  },
  {
    "code": "def output_results(results, metric, options):\n    formatter = options['Formatter']\n    context = metric.copy()\n    try:\n        context['dimension'] = list(metric['Dimensions'].values())[0]\n    except AttributeError:\n        context['dimension'] = ''\n    for result in results:\n        stat_keys = metric['Statistics']\n        if not isinstance(stat_keys, list):\n            stat_keys = [stat_keys]\n        for statistic in stat_keys:\n            context['statistic'] = statistic\n            context['Unit'] = result['Unit']\n            metric_name = (formatter % context).replace('/', '.').lower()\n            line = '{0} {1} {2}\\n'.format(\n                metric_name,\n                result[statistic],\n                timegm(result['Timestamp'].timetuple()),\n            )\n            sys.stdout.write(line)",
    "docstring": "Output the results to stdout.\n\n    TODO: add AMPQ support for efficiency"
  },
  {
    "code": "def reduce_to_unit(divider):\n    for unit_size in range(1, len(divider) // 2 + 1):\n        length = len(divider)\n        unit = divider[:unit_size]\n        divider_item = divider[:unit_size * (length // unit_size)]\n        if unit * (length // unit_size) == divider_item:\n            return unit\n    return divider",
    "docstring": "Reduce a repeating divider to the smallest repeating unit possible.\n\n    Note: this function is used by make-div\n    :param divider: the divider\n    :return: smallest repeating unit possible\n    :rtype: str\n\n    :Example:\n    'XxXxXxX' -> 'Xx'"
  },
  {
    "code": "def Asyncme(func, n=None, interval=0, default_callback=None, loop=None):\n    return coros(n, interval, default_callback, loop)(func)",
    "docstring": "Wrap coro_function into the function return NewTask."
  },
  {
    "code": "def make_client(zhmc, userid=None, password=None):\n    global USERID, PASSWORD\n    USERID = userid or USERID or \\\n        six.input('Enter userid for HMC {}: '.format(zhmc))\n    PASSWORD = password or PASSWORD or \\\n        getpass.getpass('Enter password for {}: '.format(USERID))\n    session = zhmcclient.Session(zhmc, USERID, PASSWORD)\n    session.logon()\n    client = zhmcclient.Client(session)\n    print('Established logged-on session with HMC {} using userid {}'.\n          format(zhmc, USERID))\n    return client",
    "docstring": "Create a `Session` object for the specified HMC and log that on. Create a\n    `Client` object using that `Session` object, and return it.\n\n    If no userid and password are specified, and if no previous call to this\n    method was made, userid and password are interactively inquired.\n    Userid and password are saved in module-global variables for future calls\n    to this method."
  },
  {
    "code": "def create_local_arrays(reified_arrays, array_factory=None):\n    if array_factory is None:\n        array_factory = np.empty\n    return { n: array_factory(ra.shape, ra.dtype)\n        for n, ra in reified_arrays.iteritems() }",
    "docstring": "Function that creates arrays, given the definitions in\n    the reified_arrays dictionary and the array_factory\n    keyword argument.\n\n    Arguments\n    ---------\n        reified_arrays : dictionary\n            Dictionary keyed on array name and array definitions.\n            Can be obtained via cube.arrays(reify=True)\n\n    Keyword Arguments\n    -----------------\n        array_factory : function\n            A function used to create array objects. It's signature should\n            be array_factory(shape, dtype) and should return a constructed\n            array of the supplied shape and data type. If None,\n            numpy.empty will be used.\n\n    Returns\n    -------\n    A dictionary of array objects, keyed on array names"
  },
  {
    "code": "def isglove(filepath):\n    with ensure_open(filepath, 'r') as f:\n        header_line = f.readline()\n        vector_line = f.readline()\n    try:\n        num_vectors, num_dim = header_line.split()\n        return int(num_dim)\n    except (ValueError, TypeError):\n        pass\n    vector = vector_line.split()[1:]\n    if len(vector) % 10:\n        print(vector)\n        print(len(vector) % 10)\n        return False\n    try:\n        vector = np.array([float(x) for x in vector])\n    except (ValueError, TypeError):\n        return False\n    if np.all(np.abs(vector) < 12.):\n        return len(vector)\n    return False",
    "docstring": "Get the first word vector in a GloVE file and return its dimensionality or False if not a vector\n\n    >>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt'))\n    False"
  },
  {
    "code": "def append_to_circuit(self, circuit, simplify=True):\n        if simplify:\n            term = self.simplify()\n        else:\n            term = self\n        for op in term.ops[::-1]:\n            gate = op.op.lower()\n            if gate != \"i\":\n                getattr(circuit, gate)[op.n]",
    "docstring": "Append Pauli gates to `Circuit`."
  },
  {
    "code": "async def stop(self) -> None:\n        if not self._is_running:\n            raise SublemonRuntimeError(\n                'Attempted to stop an already-stopped `Sublemon` instance')\n        await self.block()\n        self._poll_task.cancel()\n        self._is_running = False\n        with suppress(asyncio.CancelledError):\n            await self._poll_task",
    "docstring": "Coroutine to stop execution of this server."
  },
  {
    "code": "def current_state_str(self):\n        if self.sample_ok:\n            msg = ''\n            temperature = self._get_value_opc_attr('temperature')\n            if temperature is not None:\n                msg += 'Temp: %s ºC, ' % temperature\n            humidity = self._get_value_opc_attr('humidity')\n            if humidity is not None:\n                msg += 'Humid: %s %%, ' % humidity\n            pressure = self._get_value_opc_attr('pressure')\n            if pressure is not None:\n                msg += 'Press: %s mb, ' % pressure\n            light_level = self._get_value_opc_attr('light_level')\n            if light_level is not None:\n                msg += 'Light: %s lux, ' % light_level\n            return msg[:-2]\n        else:\n            return \"Bad sample\"",
    "docstring": "Return string representation of the current state of the sensor."
  },
  {
    "code": "def activate(self, asset):\n        activate_url = asset['_links']['activate']\n        return self._get(activate_url, body_type=models.Body).get_body()",
    "docstring": "Request activation of the specified asset representation.\n\n        Asset representations are obtained from :py:meth:`get_assets`.\n\n        :param request dict: An asset representation from the API.\n        :returns: :py:class:`planet.api.models.Body` with no response content\n        :raises planet.api.exceptions.APIException: On API error."
  },
  {
    "code": "def count_children(obj, type=None):\n    if type is None:\n        return len(obj)\n    else:\n        return sum(1 for x in obj if obj.get(x, getclass=True) is type)",
    "docstring": "Return the number of children of obj, optionally restricting by class"
  },
  {
    "code": "def run_gdb_command(message):\n    controller = _state.get_controller_from_client_id(request.sid)\n    if controller is not None:\n        try:\n            cmd = message[\"cmd\"]\n            controller.write(cmd, read_response=False)\n        except Exception:\n            err = traceback.format_exc()\n            logger.error(err)\n            emit(\"error_running_gdb_command\", {\"message\": err})\n    else:\n        emit(\"error_running_gdb_command\", {\"message\": \"gdb is not running\"})",
    "docstring": "Endpoint for a websocket route.\n    Runs a gdb command.\n    Responds only if an error occurs when trying to write the command to\n    gdb"
  },
  {
    "code": "def get_value_from_set(self, key):\n        key = key.lower()\n        if self._remotelib:\n            while True:\n                value = self._remotelib.run_keyword('get_value_from_set',\n                                                    [key, self._my_id], {})\n                if value:\n                    return value\n                time.sleep(0.1)\n                logger.debug('waiting for a value')\n        else:\n            return _PabotLib.get_value_from_set(self, key, self._my_id)",
    "docstring": "Get a value from previously reserved value set."
  },
  {
    "code": "def _multiplexed_buffer_helper(self, response):\n        buf = self._result(response, binary=True)\n        buf_length = len(buf)\n        walker = 0\n        while True:\n            if buf_length - walker < STREAM_HEADER_SIZE_BYTES:\n                break\n            header = buf[walker:walker + STREAM_HEADER_SIZE_BYTES]\n            _, length = struct.unpack_from('>BxxxL', header)\n            start = walker + STREAM_HEADER_SIZE_BYTES\n            end = start + length\n            walker = end\n            yield buf[start:end]",
    "docstring": "A generator of multiplexed data blocks read from a buffered\n        response."
  },
  {
    "code": "def from_array(array):\n        if array is None or not array:\n            return None\n        assert_type_or_raise(array, dict, parameter_name=\"array\")\n        data = {}\n        data['source'] = u(array.get('source'))\n        data['type'] = u(array.get('type'))\n        data['file_hashes'] = PassportElementErrorFiles._builtin_from_array_list(required_type=unicode_type, value=array.get('file_hashes'), list_level=1)\n        data['message'] = u(array.get('message'))\n        instance = PassportElementErrorFiles(**data)\n        instance._raw = array\n        return instance",
    "docstring": "Deserialize a new PassportElementErrorFiles from a given dictionary.\n\n        :return: new PassportElementErrorFiles instance.\n        :rtype: PassportElementErrorFiles"
  },
  {
    "code": "def start(self, blocking=True):\n        self.setup_zmq()\n        if blocking:\n            self.serve()\n        else:\n            eventlet.spawn(self.serve)\n            eventlet.sleep(0)",
    "docstring": "Start the producer.  This will eventually fire the ``server_start``\n        and ``running`` events in sequence, which signify that the incoming\n        TCP request socket is running and the workers have been forked,\n        respectively.  If ``blocking`` is False, control ."
  },
  {
    "code": "def unzoom(self, full=False, delay_draw=False):\n        if full:\n            self.zoom_lims = self.zoom_lims[:1]\n            self.zoom_lims = []\n        elif len(self.zoom_lims) > 0:\n            self.zoom_lims.pop()\n        self.set_viewlimits()\n        if not delay_draw:\n            self.canvas.draw()",
    "docstring": "unzoom display 1 level or all the way"
  },
  {
    "code": "def node2bracket(docgraph, node_id, child_str=''):\n    node_attrs = docgraph.node[node_id]\n    if istoken(docgraph, node_id):\n        pos_str = node_attrs.get(docgraph.ns+':pos', '')\n        token_str = node_attrs[docgraph.ns+':token']\n        return u\"({pos}{space1}{token}{space2}{child})\".format(\n            pos=pos_str, space1=bool(pos_str)*' ', token=token_str,\n            space2=bool(child_str)*' ', child=child_str)\n    label_str = node_attrs.get('label', '')\n    return u\"({label}{space}{child})\".format(\n        label=label_str, space=bool(label_str and child_str)*' ',\n        child=child_str)",
    "docstring": "convert a docgraph node into a PTB-style string."
  },
  {
    "code": "def compose_object(self, file_list, destination_file, content_type):\n    xml_setting_list = ['<ComposeRequest>']\n    for meta_data in file_list:\n      xml_setting_list.append('<Component>')\n      for key, val in meta_data.iteritems():\n        xml_setting_list.append('<%s>%s</%s>' % (key, val, key))\n      xml_setting_list.append('</Component>')\n    xml_setting_list.append('</ComposeRequest>')\n    xml = ''.join(xml_setting_list)\n    if content_type is not None:\n      headers = {'Content-Type': content_type}\n    else:\n      headers = None\n    status, resp_headers, content = self.put_object(\n        api_utils._quote_filename(destination_file) + '?compose',\n        payload=xml,\n        headers=headers)\n    errors.check_status(status, [200], destination_file, resp_headers,\n                        body=content)",
    "docstring": "COMPOSE multiple objects together.\n\n    Using the given list of files, calls the put object with the compose flag.\n    This call merges all the files into the destination file.\n\n    Args:\n      file_list: list of dicts with the file name.\n      destination_file: Path to the destination file.\n      content_type: Content type for the destination file."
  },
  {
    "code": "def get_screenshot_as_png(obj, driver=None, timeout=5, **kwargs):\n    Image = import_required('PIL.Image',\n                            'To use bokeh.io.export_png you need pillow ' +\n                            '(\"conda install pillow\" or \"pip install pillow\")')\n    with _tmp_html() as tmp:\n        html = get_layout_html(obj, **kwargs)\n        with io.open(tmp.path, mode=\"w\", encoding=\"utf-8\") as file:\n            file.write(decode_utf8(html))\n        web_driver = driver if driver is not None else webdriver_control.get()\n        web_driver.get(\"file:///\" + tmp.path)\n        web_driver.maximize_window()\n        web_driver.execute_script(\"document.body.style.width = '100%';\")\n        wait_until_render_complete(web_driver, timeout)\n        png = web_driver.get_screenshot_as_png()\n        b_rect = web_driver.execute_script(_BOUNDING_RECT_SCRIPT)\n    image = Image.open(io.BytesIO(png))\n    cropped_image = _crop_image(image, **b_rect)\n    return cropped_image",
    "docstring": "Get a screenshot of a ``LayoutDOM`` object.\n\n    Args:\n        obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget\n            object or Document to export.\n\n        driver (selenium.webdriver) : a selenium webdriver instance to use\n            to export the image.\n\n        timeout (int) : the maximum amount of time to wait for initialization.\n            It will be used as a timeout for loading Bokeh, then when waiting for\n            the layout to be rendered.\n\n    Returns:\n        cropped_image (PIL.Image.Image) : a pillow image loaded from PNG.\n\n    .. warning::\n        Responsive sizing_modes may generate layouts with unexpected size and\n        aspect ratios. It is recommended to use the default ``fixed`` sizing mode."
  },
  {
    "code": "def to_date(value, ctx):\n    if isinstance(value, str):\n        temporal = ctx.get_date_parser().auto(value)\n        if temporal is not None:\n            return to_date(temporal, ctx)\n    elif type(value) == datetime.date:\n        return value\n    elif isinstance(value, datetime.datetime):\n        return value.date()\n    raise EvaluationError(\"Can't convert '%s' to a date\" % str(value))",
    "docstring": "Tries conversion of any value to a date"
  },
  {
    "code": "def bitbucket(branch: str):\n    assert os.environ.get('BITBUCKET_BRANCH') == branch\n    assert not os.environ.get('BITBUCKET_PR_ID')",
    "docstring": "Performs necessary checks to ensure that the bitbucket build is one\n    that should create releases.\n\n    :param branch: The branch the environment should be running against."
  },
  {
    "code": "def get_contract(firma, pravni_forma, sidlo, ic, dic, zastoupen):\n    contract_fn = _resource_context(\n        \"Licencni_smlouva_o_dodavani_elektronickych_publikaci\"\n        \"_a_jejich_uziti.rst\"\n    )\n    with open(contract_fn) as f:\n        contract = f.read()\n    firma = firma.strip()\n    firma = firma + \"\\n\" + ((len(firma) + 1) * \"-\")\n    contract = Template(contract).substitute(\n        firma=firma,\n        pravni_forma=pravni_forma.strip(),\n        sidlo=sidlo.strip(),\n        ic=ic.strip(),\n        dic=dic.strip(),\n        zastoupen=zastoupen.strip(),\n        resources_path=RES_PATH\n    )\n    return gen_pdf(\n        contract,\n        open(_resource_context(\"style.json\")).read(),\n    )",
    "docstring": "Compose contract and create PDF.\n\n    Args:\n        firma (str): firma\n        pravni_forma (str): pravni_forma\n        sidlo (str): sidlo\n        ic (str): ic\n        dic (str): dic\n        zastoupen (str): zastoupen\n\n    Returns:\n        obj: StringIO file instance containing PDF file."
  },
  {
    "code": "def post(request):\n    res = Result()\n    data = request.POST or json.loads(request.body)['body']\n    name = data.get('name', None)\n    if not name:\n        res.isError = True\n        res.message = \"No name given\"\n        return JsonResponse(res.asDict())\n    tag = Tag.objects.get_or_create(name=name.lower())[0]\n    res.append(tag.json())\n    return JsonResponse(res.asDict())",
    "docstring": "Creates a tag object\n\n    :param name: Name for tag\n    :type name: str\n    :returns: json"
  },
  {
    "code": "def command_u2a(string, vargs):\n    try:\n        l = ARPABETMapper().map_unicode_string(\n            unicode_string=string,\n            ignore=vargs[\"ignore\"],\n            single_char_parsing=vargs[\"single_char_parsing\"],\n            return_as_list=True\n        )\n        print(vargs[\"separator\"].join(l))\n    except ValueError as exc:\n        print_error(str(exc))",
    "docstring": "Print the ARPABEY ASCII string corresponding to the given Unicode IPA string. \n\n    :param str string: the string to act upon\n    :param dict vargs: the command line arguments"
  },
  {
    "code": "def process_contents(self, contents, fname=None):\n        self.stack = []\n        self.dispatch_table = self.default_table.copy()\n        self.current_file = fname\n        self.tuples = self.tupleize(contents)\n        self.initialize_result(fname)\n        while self.tuples:\n            t = self.tuples.pop(0)\n            self.dispatch_table[t[0]](t)\n        return self.finalize_result(fname)",
    "docstring": "Pre-processes a file contents.\n\n        This is the main internal entry point."
  },
  {
    "code": "def _init_optional_attrs(optional_attrs):\n        if optional_attrs is None:\n            return None\n        opts = OboOptionalAttrs.get_optional_attrs(optional_attrs)\n        if opts:\n            return OboOptionalAttrs(opts)",
    "docstring": "Create OboOptionalAttrs or return None."
  },
  {
    "code": "def print_splits(cliques, next_cliques):\n    splits = 0\n    for i, clique in enumerate(cliques):\n        parent, _ = clique\n        if parent in next_cliques:\n            if len(next_cliques[parent]) > 1:\n                print_split(i + splits, len(cliques) + splits)\n                splits += 1",
    "docstring": "Print shifts for new forks."
  },
  {
    "code": "def _findlinestarts(code_object):\n        byte_increments = [c for c in code_object.co_lnotab[0::2]]\n        line_increments = [c for c in code_object.co_lnotab[1::2]]\n        lineno = code_object.co_firstlineno\n        addr = 0\n        for byte_incr, line_incr in zip(byte_increments, line_increments):\n            if byte_incr:\n                yield (addr, lineno)\n                addr += byte_incr\n            lineno += line_incr\n        yield (addr, lineno)",
    "docstring": "Find the offsets in a byte code which are the start of source lines.\n\n        Generate pairs (offset, lineno) as described in Python/compile.c.\n\n        This is a modified version of dis.findlinestarts. This version allows\n        multiple \"line starts\" with the same line number. (The dis version\n        conditions its yield on a test \"if lineno != lastlineno\".)\n\n        FYI: code.co_lnotab is a byte array with one pair of bytes for each\n        effective source line number in the bytecode. An effective line is\n        one that generates code: not blank or comment lines. The first actual\n        line number, typically the number of the \"def\" statement, is in\n        code.co_firstlineno.\n\n        An even byte of co_lnotab is the offset to the bytecode generated\n        from the next effective line number. The following odd byte is an\n        increment on the previous line's number to the next line's number.\n        Thus co_firstlineno+co_lnotab[1] is the first effective line's\n        number, and co_lnotab[0] is the number of bytes it generated.\n\n        Note that an effective line number generates code by definition,\n        hence the even byte cannot be zero; and as line numbers are\n        monotonically increasing, the odd byte cannot be zero either.\n\n        But what, the curious reader might ask, does Python do if a source\n        line generates more than 255 bytes of code? In that *highly* unlikely\n        case compile.c generates multiple pairs of (255,0) until it has\n        accounted for all the generated code, then a final pair of\n        (offset%256, lineincr).\n\n        Oh, but what, the curious reader asks, do they do if there is a gap\n        of more than 255 between effective line numbers? It is not unheard of\n        to find blocks of comments larger than 255 lines (like this one?).\n        Then compile.c generates pairs of (0, 255) until it has accounted for\n        the line number difference and a final pair of (offset,lineincr%256).\n\n        Uh, but...? Yes, what now, annoying reader? Well, does the following\n        code handle these special cases of (255,0) and (0,255) properly?\n        It handles the (0,255) case correctly, because of the \"if byte_incr\"\n        test which skips the yield() but increments lineno. It does not handle\n        the case of (255,0) correctly; it will yield false pairs (255,0).\n        Fortunately that will only arise e.g. when disassembling some\n        \"obfuscated\" code where most newlines are replaced with semicolons.\n\n        Oh, and yes, the to_code() method does properly handle generation\n        of the (255,0) and (0,255) entries correctly."
  },
  {
    "code": "def htmlSaveFileFormat(self, filename, encoding, format):\n        ret = libxml2mod.htmlSaveFileFormat(filename, self._o, encoding, format)\n        return ret",
    "docstring": "Dump an HTML document to a file using a given encoding."
  },
  {
    "code": "def items(self, start=None, stop=None):\n        if start is None:\n            node = self._head[2]\n        else:\n            self._find_lt(start)\n            node = self._path[0][2]\n        while node is not self._tail and (stop is None or node[0] < stop):\n            yield (node[0], node[1])\n            node = node[2]",
    "docstring": "Return an iterator yielding pairs.\n\n        If *start* is specified, iteration starts at the first pair with a key\n        that is larger than or equal to *start*. If not specified, iteration\n        starts at the first pair in the list.\n\n        If *stop* is specified, iteration stops at the last pair that is\n        smaller than *stop*. If not specified, iteration end with the last pair\n        in the list."
  },
  {
    "code": "def uint8sc(im):\n    im = np.asarray(im)\n    immin = im.min()\n    immax = im.max()\n    imrange = immax - immin\n    return cv2.convertScaleAbs(im - immin, alpha=255 / imrange)",
    "docstring": "Scale the image to uint8\n\n    Parameters:\n    -----------\n    im: 2d array\n        The image\n\n    Returns:\n    --------\n    im: 2d array (dtype uint8)\n        The scaled image to uint8"
  },
  {
    "code": "def add_efac(psr, efac=1.0, flagid=None, flags=None, seed=None):\n    if seed is not None:\n        N.random.seed(seed)\n    efacvec = N.ones(psr.nobs)\n    if flags is None:\n        if not N.isscalar(efac):\n            raise ValueError('ERROR: If flags is None, efac must be a scalar')\n        else:\n            efacvec = N.ones(psr.nobs) * efac\n    if flags is not None and flagid is not None and not N.isscalar(efac):\n        if len(efac) == len(flags):\n            for ct, flag in enumerate(flags):\n                ind = flag == N.array(psr.flagvals(flagid))\n                efacvec[ind] = efac[ct]\n    psr.stoas[:] += efacvec * psr.toaerrs * (1e-6 / day) * N.random.randn(psr.nobs)",
    "docstring": "Add nominal TOA errors, multiplied by `efac` factor.\n    Optionally take a pseudorandom-number-generator seed."
  },
  {
    "code": "def contains(self, expected):\n        return self._encode_invoke(atomic_reference_contains_codec,\n                                   expected=self._to_data(expected))",
    "docstring": "Checks if the reference contains the value.\n\n        :param expected: (object), the value to check (is allowed to be ``None``).\n        :return: (bool), ``true`` if the value is found, ``false`` otherwise."
  },
  {
    "code": "def disable(self):\n        w.ActButton.disable(self)\n        g = get_root(self).globals\n        if self._expert:\n            self.config(bg=g.COL['start'])\n        else:\n            self.config(bg=g.COL['startD'])",
    "docstring": "Disable the button, if in non-expert mode."
  },
  {
    "code": "def _table_to_csv(table_):\n    f = cStringIO.StringIO()\n    try:\n        _write_csv(f, table_)\n        return f.getvalue()\n    finally:\n        f.close()",
    "docstring": "Return the given table converted to a CSV string.\n\n    :param table: the table to convert\n    :type table: list of OrderedDicts each with the same keys in the same\n        order\n\n    :rtype: UTF8-encoded, CSV-formatted string"
  },
  {
    "code": "def enable(instrumentation_key, *args, **kwargs):\n    if not instrumentation_key:\n        raise Exception('Instrumentation key was required but not provided')\n    global original_excepthook\n    global telemetry_channel\n    telemetry_channel = kwargs.get('telemetry_channel')\n    if not original_excepthook:\n        original_excepthook = sys.excepthook\n        sys.excepthook = intercept_excepthook\n    if instrumentation_key not in enabled_instrumentation_keys:\n        enabled_instrumentation_keys.append(instrumentation_key)",
    "docstring": "Enables the automatic collection of unhandled exceptions. Captured exceptions will be sent to the Application\n    Insights service before being re-thrown. Multiple calls to this function with different instrumentation keys result\n    in multiple instances being submitted, one for each key.\n\n    .. code:: python\n\n        from applicationinsights.exceptions import enable\n\n        # set up exception capture\n        enable('<YOUR INSTRUMENTATION KEY GOES HERE>')\n\n        # raise an exception (this will be sent to the Application Insights service as an exception telemetry object)\n        raise Exception('Boom!')\n\n    Args:\n        instrumentation_key (str). the instrumentation key to use while sending telemetry to the service."
  },
  {
    "code": "def fuzzy_match(self, other):\n        magic, fuzzy = False, False\n        try:\n            magic = self.alias == other.magic\n        except AttributeError:\n            pass\n        if '.' in self.alias:\n            major = self.alias.split('.')[0]\n            fuzzy = major == other.alias\n        return magic or fuzzy",
    "docstring": "Given another token, see if either the major alias identifier\n        matches the other alias, or if magic matches the alias."
  },
  {
    "code": "def save_to_files(self, directory: str) -> None:\n        os.makedirs(directory, exist_ok=True)\n        if os.listdir(directory):\n            logging.warning(\"vocabulary serialization directory %s is not empty\", directory)\n        with codecs.open(os.path.join(directory, NAMESPACE_PADDING_FILE), 'w', 'utf-8') as namespace_file:\n            for namespace_str in self._non_padded_namespaces:\n                print(namespace_str, file=namespace_file)\n        for namespace, mapping in self._index_to_token.items():\n            with codecs.open(os.path.join(directory, namespace + '.txt'), 'w', 'utf-8') as token_file:\n                num_tokens = len(mapping)\n                start_index = 1 if mapping[0] == self._padding_token else 0\n                for i in range(start_index, num_tokens):\n                    print(mapping[i].replace('\\n', '@@NEWLINE@@'), file=token_file)",
    "docstring": "Persist this Vocabulary to files so it can be reloaded later.\n        Each namespace corresponds to one file.\n\n        Parameters\n        ----------\n        directory : ``str``\n            The directory where we save the serialized vocabulary."
  },
  {
    "code": "def _shorten_render(renderer, max_len):\n    def short_renderer(expr):\n        res = renderer(expr)\n        if len(res) > max_len:\n            return '...'\n        else:\n            return res\n    return short_renderer",
    "docstring": "Return a modified that returns the representation of expr, or '...' if\n    that representation is longer than `max_len`"
  },
  {
    "code": "def executable_path(conn, executable):\n    executable_path = conn.remote_module.which(executable)\n    if not executable_path:\n        raise ExecutableNotFound(executable, conn.hostname)\n    return executable_path",
    "docstring": "Remote validator that accepts a connection object to ensure that a certain\n    executable is available returning its full path if so.\n\n    Otherwise an exception with thorough details will be raised, informing the\n    user that the executable was not found."
  },
  {
    "code": "def match_case_tokens(loc, tokens, check_var, top):\n    if len(tokens) == 2:\n        matches, stmts = tokens\n        cond = None\n    elif len(tokens) == 3:\n        matches, cond, stmts = tokens\n    else:\n        raise CoconutInternalException(\"invalid case match tokens\", tokens)\n    matching = Matcher(loc, check_var)\n    matching.match(matches, match_to_var)\n    if cond:\n        matching.add_guard(cond)\n    return matching.build(stmts, set_check_var=top)",
    "docstring": "Build code for matching the given case."
  },
  {
    "code": "def bytes_to_string(raw_data: bytes, prefix: bool = False) -> str:\n        prefix_string = ''\n        if prefix:\n            prefix_string = '0x'\n        suffix = ''.join([format(c, \"02x\") for c in raw_data])\n        return prefix_string + suffix.upper()",
    "docstring": "Convert a byte array to a hex string."
  },
  {
    "code": "def list_releases():\n    response = requests.get(PYPI_URL.format(package=PYPI_PACKAGE_NAME))\n    if response:\n        data = response.json()\n        releases_dict = data.get('releases', {})\n        if releases_dict:\n            for version, release in releases_dict.items():\n                release_formats = []\n                published_on_date = None\n                for fmt in release:\n                    release_formats.append(fmt.get('packagetype'))\n                    published_on_date = fmt.get('upload_time')\n                release_formats = ' | '.join(release_formats)\n                print('{:<10}{:>15}{:>25}'.format(version, published_on_date, release_formats))\n        else:\n            print('No releases found for {}'.format(PYPI_PACKAGE_NAME))\n    else:\n        print('Package \"{}\" not found on Pypi.org'.format(PYPI_PACKAGE_NAME))",
    "docstring": "Lists all releases published on pypi."
  },
  {
    "code": "def make_hmap(pmap, imtls, poes):\n    M, P = len(imtls), len(poes)\n    hmap = probability_map.ProbabilityMap.build(M, P, pmap, dtype=F32)\n    if len(pmap) == 0:\n        return hmap\n    for i, imt in enumerate(imtls):\n        curves = numpy.array([pmap[sid].array[imtls(imt), 0]\n                              for sid in pmap.sids])\n        data = compute_hazard_maps(curves, imtls[imt], poes)\n        for sid, value in zip(pmap.sids, data):\n            array = hmap[sid].array\n            for j, val in enumerate(value):\n                array[i, j] = val\n    return hmap",
    "docstring": "Compute the hazard maps associated to the passed probability map.\n\n    :param pmap: hazard curves in the form of a ProbabilityMap\n    :param imtls: DictArray with M intensity measure types\n    :param poes: P PoEs where to compute the maps\n    :returns: a ProbabilityMap with size (N, M, P)"
  },
  {
    "code": "def alter_poms(pom_dir, additional_params, repo_url=None, mvn_repo_local=None):\n    work_dir = os.getcwd()\n    os.chdir(pom_dir)\n    try:\n        if repo_url:\n            settings_filename = create_mirror_settings(repo_url)\n        else:\n            settings_filename = None\n        args = [\"mvn\", \"clean\"]\n        if mvn_repo_local:\n            args.extend([\"-s\", settings_filename])\n        if mvn_repo_local:\n            args.append(\"-Dmaven.repo.local=%s\" % mvn_repo_local)\n        param_list = additional_params.split(\" \")\n        args.extend(param_list)\n        logging.debug(\"Running command: %s\", \" \".join(args))\n        command = Popen(args, stdout=PIPE, stderr=STDOUT)\n        stdout = command.communicate()[0]\n        if command.returncode:\n            logging.error(\"POM manipulation failed. Output:\\n%s\" % stdout)\n        else:\n            logging.debug(\"POM manipulation succeeded. Output:\\n%s\" % stdout)\n    finally:\n        os.chdir(work_dir)",
    "docstring": "Runs mvn clean command with provided additional parameters to perform pom updates by pom-manipulation-ext."
  },
  {
    "code": "def render(self, hosts, vars={}):\n        if self.tpl_file.endswith(\".tpl\"):\n            return self._render_mako(hosts, vars)\n        elif self.tpl_file.endswith(\".py\"):\n            return self._render_py(hosts, vars)\n        else:\n            raise ValueError(\"Don't know how to handle '{0}'\".format(self.tpl_file))",
    "docstring": "Render a mako or .py file."
  },
  {
    "code": "def dump_database(id):\n    tmp_dir = tempfile.mkdtemp()\n    current_dir = os.getcwd()\n    os.chdir(tmp_dir)\n    FNULL = open(os.devnull, \"w\")\n    heroku_app = HerokuApp(dallinger_uid=id, output=FNULL)\n    heroku_app.backup_capture()\n    heroku_app.backup_download()\n    for filename in os.listdir(tmp_dir):\n        if filename.startswith(\"latest.dump\"):\n            os.rename(filename, \"database.dump\")\n    os.chdir(current_dir)\n    return os.path.join(tmp_dir, \"database.dump\")",
    "docstring": "Dump the database to a temporary directory."
  },
  {
    "code": "def _normalize_words(words, acronyms):\n    for i, _ in enumerate(words):\n        if words[i].upper() in acronyms:\n            words[i] = words[i].upper()\n        else:\n            if not words[i].isupper():\n                words[i] = words[i].capitalize()\n    return words",
    "docstring": "Normalize case of each word to PascalCase."
  },
  {
    "code": "def find_path_package_name(thepath):\n    module_found = False\n    last_module_found = None\n    continue_ = True\n    while continue_:\n        module_found = is_path_python_module(thepath)\n        next_path = path.dirname(thepath)\n        if next_path == thepath:\n            continue_ = False\n        if module_found:\n            init_names = ['__init__%s' % suffix.lower() for suffix in _py_suffixes]\n            if path.basename(thepath).lower() in init_names:\n                last_module_found = path.basename(path.dirname(thepath))\n            else:\n                last_module_found = path.basename(thepath)\n        if last_module_found and not module_found:\n            continue_ = False\n        thepath = next_path\n    return last_module_found",
    "docstring": "Takes a file system path and returns the name of the python package\n        the said path belongs to.  If the said path can not be determined, it\n        returns None."
  },
  {
    "code": "def bodc2s(code, lenout=_default_len_out):\n    code = ctypes.c_int(code)\n    name = stypes.stringToCharP(\" \" * lenout)\n    lenout = ctypes.c_int(lenout)\n    libspice.bodc2s_c(code, lenout, name)\n    return stypes.toPythonString(name)",
    "docstring": "Translate a body ID code to either the corresponding name or if no\n    name to ID code mapping exists, the string representation of the\n    body ID value.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodc2s_c.html\n\n    :param code: Integer ID code to translate to a string.\n    :type code: int\n    :param lenout: Maximum length of output name.\n    :type lenout: int\n    :return: String corresponding to 'code'.\n    :rtype: str"
  },
  {
    "code": "def excel_key(index):\n    X = lambda n: ~n and X((n // 26)-1) + chr(65 + (n % 26)) or ''\n    return X(int(index))",
    "docstring": "create a key for index by converting index into a base-26 number, using A-Z as the characters."
  },
  {
    "code": "def save_summaries(frames, keys, selected_summaries, batch_dir, batch_name):\n    if not frames:\n        logger.info(\"Could save summaries - no summaries to save!\")\n        logger.info(\"You have no frames - aborting\")\n        return None\n    if not keys:\n        logger.info(\"Could save summaries - no summaries to save!\")\n        logger.info(\"You have no keys - aborting\")\n        return None\n    selected_summaries_dict = create_selected_summaries_dict(selected_summaries)\n    summary_df = pd.concat(frames, keys=keys, axis=1)\n    for key, value in selected_summaries_dict.items():\n        _summary_file_name = os.path.join(batch_dir, \"summary_%s_%s.csv\" % (\n        key, batch_name))\n        _summary_df = summary_df.iloc[:,\n                      summary_df.columns.get_level_values(1) == value]\n        _header = _summary_df.columns\n        _summary_df.to_csv(_summary_file_name, sep=\";\")\n        logger.info(\n            \"saved summary (%s) to:\\n       %s\" % (key, _summary_file_name))\n    logger.info(\"finished saving summaries\")\n    return summary_df",
    "docstring": "Writes the summaries to csv-files\n\n    Args:\n        frames: list of ``cellpy`` summary DataFrames\n        keys: list of indexes (typically run-names) for the different runs\n        selected_summaries: list defining which summary data to save\n        batch_dir: directory to save to\n        batch_name: the batch name (will be used for making the file-name(s))\n\n    Returns: a pandas DataFrame with your selected summaries."
  },
  {
    "code": "def write_to_file(path, contents, file_type='text'):\n    FILE_TYPES = ('json', 'text', 'binary')\n    if file_type not in FILE_TYPES:\n        raise ScriptWorkerException(\"Unknown file_type {} not in {}!\".format(file_type, FILE_TYPES))\n    if file_type == 'json':\n        contents = format_json(contents)\n    if file_type == 'binary':\n        with open(path, 'wb') as fh:\n            fh.write(contents)\n    else:\n        with open(path, 'w') as fh:\n            print(contents, file=fh, end=\"\")",
    "docstring": "Write ``contents`` to ``path`` with optional formatting.\n\n    Small helper function to write ``contents`` to ``file`` with optional formatting.\n\n    Args:\n        path (str): the path to write to\n        contents (str, object, or bytes): the contents to write to the file\n        file_type (str, optional): the type of file. Currently accepts\n            ``text`` or ``binary`` (contents are unchanged) or ``json`` (contents\n            are formatted). Defaults to ``text``.\n\n    Raises:\n        ScriptWorkerException: with an unknown ``file_type``\n        TypeError: if ``file_type`` is ``json`` and ``contents`` isn't JSON serializable"
  },
  {
    "code": "def register_writer(klass):\n    if not callable(klass):\n        raise ValueError(\"Can only register callables as engines\")\n    engine_name = klass.engine\n    _writers[engine_name] = klass",
    "docstring": "Add engine to the excel writer registry.io.excel.\n\n    You must use this method to integrate with ``to_excel``.\n\n    Parameters\n    ----------\n    klass : ExcelWriter"
  },
  {
    "code": "def add_path_to_sys_path(self):\r\n        for path in reversed(self.get_spyder_pythonpath()):\r\n            sys.path.insert(1, path)",
    "docstring": "Add Spyder path to sys.path"
  },
  {
    "code": "def zero(self):\n        def zero_vec(x, out=None, **kwargs):\n            if is_valid_input_meshgrid(x, self.domain.ndim):\n                scalar_out_shape = out_shape_from_meshgrid(x)\n            elif is_valid_input_array(x, self.domain.ndim):\n                scalar_out_shape = out_shape_from_array(x)\n            else:\n                raise TypeError('invalid input type')\n            out_shape = self.out_shape + scalar_out_shape\n            if out is None:\n                return np.zeros(out_shape, dtype=self.scalar_out_dtype)\n            else:\n                fill_value = np.zeros(1, dtype=self.scalar_out_dtype)[0]\n                out.fill(fill_value)\n        return self.element_type(self, zero_vec)",
    "docstring": "Function mapping anything to zero."
  },
  {
    "code": "def transform(self, raw_X, y=None):\n        return [self._extract_features(sequence1, sequence2) for sequence1, sequence2 in raw_X]",
    "docstring": "Transform sequence pairs to feature arrays that can be used as input to `Hacrf` models.\n\n        Parameters\n        ----------\n        raw_X : List of (sequence1_n, sequence2_n) pairs, one for each training example n.\n        y : (ignored)\n\n        Returns\n        -------\n         X : List of numpy ndarrays, each with shape = (I_n, J_n, K), where I_n is the length of sequence1_n, J_n is the\n            length of sequence2_n, and K is the number of features.\n            Feature matrix list, for use with estimators or further transformers."
  },
  {
    "code": "def set_nsxcontroller_port(self, **kwargs):\n        name = kwargs.pop('name')\n        port = str(kwargs.pop('port'))\n        port_args = dict(name=name, port=port)\n        method_name = 'nsx_controller_connection_addr_port'\n        method_class = self._brocade_tunnels\n        nsxcontroller_attr = getattr(method_class, method_name)\n        config = nsxcontroller_attr(**port_args)\n        output = self._callback(config)\n        return output",
    "docstring": "Set Nsx Controller pot on the switch\n\n        Args:\n            port (int): 1 to 65535.\n            callback (function): A function executed upon completion of the\n                 method.\n\n        Returns:\n           Return value of `callback`.\n\n        Raises:\n            None"
  },
  {
    "code": "def rms(self, stride=1):\n        stridesamp = int(stride * self.sample_rate.value)\n        nsteps = int(self.size // stridesamp)\n        data = numpy.zeros(nsteps)\n        for step in range(nsteps):\n            idx = int(stridesamp * step)\n            idx_end = idx + stridesamp\n            stepseries = self[idx:idx_end]\n            rms_ = numpy.sqrt(numpy.mean(numpy.abs(stepseries.value)**2))\n            data[step] = rms_\n        name = '%s %.2f-second RMS' % (self.name, stride)\n        return self.__class__(data, channel=self.channel, t0=self.t0,\n                              name=name, sample_rate=(1/float(stride)))",
    "docstring": "Calculate the root-mean-square value of this `TimeSeries`\n        once per stride.\n\n        Parameters\n        ----------\n        stride : `float`\n            stride (seconds) between RMS calculations\n\n        Returns\n        -------\n        rms : `TimeSeries`\n            a new `TimeSeries` containing the RMS value with dt=stride"
  },
  {
    "code": "def confirm_push(self, coord, version):\n    if not self.get_options().prompt:\n      return True\n    try:\n      isatty = os.isatty(sys.stdin.fileno())\n    except ValueError:\n      isatty = False\n    if not isatty:\n      return True\n    push = input('\\nPublish {} with revision {} ? [y|N] '.format(\n      coord, version\n    ))\n    print('\\n')\n    return push.strip().lower() == 'y'",
    "docstring": "Ask the user if a push should be done for a particular version of a\n       particular coordinate.   Return True if the push should be done"
  },
  {
    "code": "def save_plots(self, directory, format=\"png\", recommended_only=False):\n        for i, session in enumerate(self):\n            session.save_plots(\n                directory, prefix=str(i), format=format, recommended_only=recommended_only\n            )",
    "docstring": "Save images of dose-response curve-fits for each model.\n\n        Parameters\n        ----------\n        directory : str\n            Directory where the PNG files will be saved.\n        format : str, optional\n            Image output format. Valid options include: png, pdf, svg, ps, eps\n        recommended_only : bool, optional\n            If True, only recommended models for each session are included. If\n            no model is recommended, then a row with it's ID will be included,\n            but all fields will be null.\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def lower_comparisons_to_between(match_query):\n    new_match_traversals = []\n    for current_match_traversal in match_query.match_traversals:\n        new_traversal = []\n        for step in current_match_traversal:\n            if step.where_block:\n                expression = step.where_block.predicate\n                new_where_block = Filter(_lower_expressions_to_between(expression))\n                new_traversal.append(step._replace(where_block=new_where_block))\n            else:\n                new_traversal.append(step)\n        new_match_traversals.append(new_traversal)\n    return match_query._replace(match_traversals=new_match_traversals)",
    "docstring": "Return a new MatchQuery, with all eligible comparison filters lowered to between clauses."
  },
  {
    "code": "def reload(self, r=None, pr=None, timeout=None, basic_quorum=None,\n               notfound_ok=None, head_only=False):\n        self.client.get(self, r=r, pr=pr, timeout=timeout, head_only=head_only)\n        return self",
    "docstring": "Reload the object from Riak. When this operation completes, the\n        object could contain new metadata and a new value, if the object\n        was updated in Riak since it was last retrieved.\n\n        .. note:: Even if the key is not found in Riak, this will\n           return a :class:`RiakObject`. Check the :attr:`exists`\n           property to see if the key was found.\n\n        :param r: R-Value, wait for this many partitions to respond\n         before returning to client.\n        :type r: integer\n        :param pr: PR-value, require this many primary partitions to\n                   be available before performing the read that\n                   precedes the put\n        :type pr: integer\n        :param timeout: a timeout value in milliseconds\n        :type timeout: int\n        :param basic_quorum: whether to use the \"basic quorum\" policy\n           for not-founds\n        :type basic_quorum: bool\n        :param notfound_ok: whether to treat not-found responses as successful\n        :type notfound_ok: bool\n        :param head_only: whether to fetch without value, so only metadata\n           (only available on PB transport)\n        :type head_only: bool\n        :rtype: :class:`RiakObject`"
  },
  {
    "code": "def rename_with_num(self, prefix=\"\", new_path=None, remove_desc=True):\n        if new_path is None: numbered = self.__class__(new_temp_path())\n        else:                numbered = self.__class__(new_path)\n        def numbered_iterator():\n            for i,read in enumerate(self):\n                read.id  = prefix + str(i)\n                read.seq = read.seq.upper()\n                if remove_desc: read.description = \"\"\n                yield read\n        numbered.write(numbered_iterator())\n        numbered.close()\n        if new_path is None:\n            os.remove(self.path)\n            shutil.move(numbered, self.path)\n        return numbered",
    "docstring": "Rename every sequence based on a prefix and a number."
  },
  {
    "code": "def _get_ann(dbs, features):\n    value = \"\"\n    for db, feature in zip(dbs, features):\n        value += db + \":\" + feature\n    return value",
    "docstring": "Gives format to annotation for html table output"
  },
  {
    "code": "def help(self, *args):\n        if len(args) == 0:\n            return help_msg\n        which = args[0].lower()\n        if which == 'ginga':\n            method = args[1]\n            _method = getattr(self.fv, method)\n            return _method.__doc__\n        elif which == 'channel':\n            chname = args[1]\n            method = args[2]\n            chinfo = self.fv.get_channel(chname)\n            _method = getattr(chinfo.viewer, method)\n            return _method.__doc__\n        else:\n            return (\"Please use 'help ginga <method>' or \"\n                    \"'help channel <chname> <method>'\")",
    "docstring": "Get help for a remote interface method.\n\n        Examples\n        --------\n        help('ginga', `method`)\n            name of the method for which you want help\n\n        help('channel', `chname`, `method`)\n            name of the method in the channel for which you want help\n\n        Returns\n        -------\n        help : string\n            a help message"
  },
  {
    "code": "def get_attribute_references(instring):\n    parsed = ConditionGrammar().conditions.parseString(instring)\n    result = parsed if isinstance(parsed[0], str) else parsed[0]\n    return result.attribute_reference.asList() if result.attribute_reference else []",
    "docstring": "Return a list of attribute references in the condition expression.\n\n    attribute_reference ::= relation_name \".\" attribute_name | attribute_name\n\n    :param instring: a condition expression.\n    :return: a list of attribute references."
  },
  {
    "code": "def update(self, fmt={}, replot=False, auto_update=False, draw=None,\n               force=False, todefault=False, **kwargs):\n        if self.disabled:\n            return\n        fmt = dict(fmt)\n        if kwargs:\n            fmt.update(kwargs)\n        if not self._initialized:\n            for key, val in six.iteritems(fmt):\n                self[key] = val\n            return\n        self._register_update(fmt=fmt, replot=replot, force=force,\n                              todefault=todefault)\n        if not self.no_auto_update or auto_update:\n            self.start_update(draw=draw)",
    "docstring": "Update the formatoptions and the plot\n\n        If the :attr:`data` attribute of this plotter is None, the plotter is\n        updated like a usual dictionary (see :meth:`dict.update`). Otherwise\n        the update is registered and the plot is updated if `auto_update` is\n        True or if the :meth:`start_update` method is called (see below).\n\n        Parameters\n        ----------\n        %(Plotter._register_update.parameters)s\n        %(InteractiveBase.start_update.parameters)s\n        %(InteractiveBase.update.parameters.auto_update)s\n        ``**kwargs``\n            Any other formatoption that shall be updated (additionally to those\n            in `fmt`)\n\n        Notes\n        -----\n        %(InteractiveBase.update.notes)s"
  },
  {
    "code": "def __metadata_helper(json_path):\n    url = shakedown.dcos_url_path('dcos-metadata/{}'.format(json_path))\n    try:\n        response = dcos.http.request('get', url)\n        if response.status_code == 200:\n            return response.json()\n    except:\n        pass\n    return None",
    "docstring": "Returns json for specific cluster metadata.  Important to realize that\n        this was introduced in dcos-1.9.  Clusters prior to 1.9 and missing metadata\n        will return None"
  },
  {
    "code": "def get_required_kwonly_args(argspecs):\n    try:\n        kwonly = argspecs.kwonlyargs\n        if argspecs.kwonlydefaults is None:\n            return kwonly\n        res = []\n        for name in kwonly:\n            if not name in argspecs.kwonlydefaults:\n                res.append(name)\n        return res\n    except AttributeError:\n        return []",
    "docstring": "Determines whether given argspecs implies required keywords-only args\n    and returns them as a list. Returns empty list if no such args exist."
  },
  {
    "code": "def insert(self, tag, identifier, parent, data):\n        if self.global_plate_definitions.contains(identifier):\n            raise KeyError(\"Identifier {} already exists in tree\".format(identifier))\n        self.global_plate_definitions.create_node(tag=tag, identifier=identifier, parent=parent, data=data)\n        with switch_db(MetaDataModel, 'hyperstream'):\n            meta_data = MetaDataModel(tag=tag, parent=parent, data=data)\n            meta_data.save()\n        logging.info(\"Meta data {} inserted\".format(identifier))",
    "docstring": "Insert the given meta data into the database\n\n        :param tag: The tag (equates to meta_data_id)\n        :param identifier: The identifier (a combination of the meta_data_id and the plate value)\n        :param parent: The parent plate identifier\n        :param data: The data (plate value)\n        :return: None"
  },
  {
    "code": "def RunWMIQuery(query, baseobj=r\"winmgmts:\\root\\cimv2\"):\n  pythoncom.CoInitialize()\n  wmi_obj = win32com.client.GetObject(baseobj)\n  wmi_obj.Security_.Privileges.AddAsString(\"SeDebugPrivilege\")\n  try:\n    query_results = wmi_obj.ExecQuery(query)\n  except pythoncom.com_error as e:\n    raise RuntimeError(\"Failed to run WMI query \\'%s\\' err was %s\" % (query, e))\n  try:\n    for result in query_results:\n      response = rdf_protodict.Dict()\n      properties = (\n          list(result.Properties_) +\n          list(getattr(result, \"SystemProperties_\", [])))\n      for prop in properties:\n        if prop.Name not in IGNORE_PROPS:\n          response.SetItem(prop.Name, prop.Value, raise_on_error=False)\n      yield response\n  except pythoncom.com_error as e:\n    raise RuntimeError(\"WMI query data error on query \\'%s\\' err was %s\" %\n                       (e, query))",
    "docstring": "Run a WMI query and return a result.\n\n  Args:\n    query: the WMI query to run.\n    baseobj: the base object for the WMI query.\n\n  Yields:\n    rdf_protodict.Dicts containing key value pairs from the resulting COM\n    objects."
  },
  {
    "code": "def condense(input_string):\n    try:\n        assert isinstance(input_string, basestring)\n    except AssertionError:\n        raise TypeError\n    removed_leading_whitespace = re.sub('>\\s+', '>', input_string).strip()\n    removed_trailing_whitespace = re.sub('\\s+<', '<', removed_leading_whitespace).strip()\n    return removed_trailing_whitespace",
    "docstring": "Trims leadings and trailing whitespace between tags in an html document\n\n    Args:\n        input_string: A (possible unicode) string representing HTML.\n\n    Returns:\n        A (possibly unicode) string representing HTML.\n\n    Raises:\n        TypeError: Raised if input_string isn't a unicode string or string."
  },
  {
    "code": "def remove_if_same(self, key, value):\n        check_not_none(key, \"key can't be None\")\n        check_not_none(value, \"value can't be None\")\n        key_data = self._to_data(key)\n        value_data = self._to_data(value)\n        return self._remove_if_same_internal_(key_data, value_data)",
    "docstring": "Removes the entry for a key only if it is currently mapped to a given value.\n\n        This is equivalent to:\n            >>> if map.contains_key(key) and map.get(key).equals(value):\n            >>>     map.remove(key)\n            >>>     return true\n            >>> else:\n            >>>     return false\n        except that the action is performed atomically.\n\n        **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations\n        of __hash__ and __eq__ defined in key's class.**\n\n        :param key: (object), the specified key.\n        :param value: (object), remove the key if it has this value.\n        :return: (bool), ``true`` if the value was removed."
  },
  {
    "code": "def get_offset_topic_partition_count(kafka_config):\n    metadata = get_topic_partition_metadata(kafka_config.broker_list)\n    if CONSUMER_OFFSET_TOPIC not in metadata:\n        raise UnknownTopic(\"Consumer offset topic is missing.\")\n    return len(metadata[CONSUMER_OFFSET_TOPIC])",
    "docstring": "Given a kafka cluster configuration, return the number of partitions\n    in the offset topic. It will raise an UnknownTopic exception if the topic\n    cannot be found."
  },
  {
    "code": "def patch(self, path, data, **options):\n        data, options = self._update_request(data, options)\n        return self.request('patch', path, data=data, **options)",
    "docstring": "Parses PATCH request options and dispatches a request"
  },
  {
    "code": "def minute_to_session(column, close_locs, data, out):\n    if column == 'open':\n        _minute_to_session_open(close_locs, data, out)\n    elif column == 'high':\n        _minute_to_session_high(close_locs, data, out)\n    elif column == 'low':\n        _minute_to_session_low(close_locs, data, out)\n    elif column == 'close':\n        _minute_to_session_close(close_locs, data, out)\n    elif column == 'volume':\n        _minute_to_session_volume(close_locs, data, out)\n    return out",
    "docstring": "Resample an array with minute data into an array with session data.\n\n    This function assumes that the minute data is the exact length of all\n    minutes in the sessions in the output.\n\n    Parameters\n    ----------\n    column : str\n        The `open`, `high`, `low`, `close`, or `volume` column.\n    close_locs : array[intp]\n        The locations in `data` which are the market close minutes.\n    data : array[float64|uint32]\n        The minute data to be sampled into session data.\n        The first value should align with the market open of the first session,\n        containing values for all minutes for all sessions. With the last value\n        being the market close of the last session.\n    out : array[float64|uint32]\n        The output array into which to write the sampled sessions."
  },
  {
    "code": "def nn_getsockopt(socket, level, option, value):\n    if memoryview(value).readonly:\n        raise TypeError('Writable buffer is required')\n    size_t_size = ctypes.c_size_t(len(value))\n    rtn = _nn_getsockopt(socket, level, option, ctypes.addressof(value),\n                         ctypes.byref(size_t_size))\n    return (rtn, size_t_size.value)",
    "docstring": "retrieve a socket option\n\n    socket - socket number\n    level - option level\n    option - option\n    value - a writable byte buffer (e.g. a bytearray) which the option value\n    will be copied to\n    returns - number of bytes copied or on error nunber < 0"
  },
  {
    "code": "def _start_connection_setup(self):\n        logger.info('We are connected[%s], request connection setup',\n                    self.link_uri)\n        self.platform.fetch_platform_informations(self._platform_info_fetched)",
    "docstring": "Start the connection setup by refreshing the TOCs"
  },
  {
    "code": "def validate_json_schema(data, schema, name=\"task\"):\n    try:\n        jsonschema.validate(data, schema)\n    except jsonschema.exceptions.ValidationError as exc:\n        raise ScriptWorkerTaskException(\n            \"Can't validate {} schema!\\n{}\".format(name, str(exc)),\n            exit_code=STATUSES['malformed-payload']\n        )",
    "docstring": "Given data and a jsonschema, let's validate it.\n\n    This happens for tasks and chain of trust artifacts.\n\n    Args:\n        data (dict): the json to validate.\n        schema (dict): the jsonschema to validate against.\n        name (str, optional): the name of the json, for exception messages.\n            Defaults to \"task\".\n\n    Raises:\n        ScriptWorkerTaskException: on failure"
  },
  {
    "code": "def _stripslashes(s):\n  r = re.sub(r\"\\\\(n|r)\", \"\\n\", s)\n  r = re.sub(r\"\\\\\", \"\", r)\n  return r",
    "docstring": "Removes trailing and leading backslashes from string"
  },
  {
    "code": "def insert(self, row, ensure=None, types=None):\n        row = self._sync_columns(row, ensure, types=types)\n        res = self.db.executable.execute(self.table.insert(row))\n        if len(res.inserted_primary_key) > 0:\n            return res.inserted_primary_key[0]\n        return True",
    "docstring": "Add a ``row`` dict by inserting it into the table.\n\n        If ``ensure`` is set, any of the keys of the row are not\n        table columns, they will be created automatically.\n\n        During column creation, ``types`` will be checked for a key\n        matching the name of a column to be created, and the given\n        SQLAlchemy column type will be used. Otherwise, the type is\n        guessed from the row value, defaulting to a simple unicode\n        field.\n        ::\n\n            data = dict(title='I am a banana!')\n            table.insert(data)\n\n        Returns the inserted row's primary key."
  },
  {
    "code": "def search(self, **kwargs):\n        return super(ApiV4Neighbor, self).get(self.prepare_url(\n            'api/v4/neighbor/', kwargs))",
    "docstring": "Method to search neighbors based on extends search.\n\n        :param search: Dict containing QuerySets to find neighbors.\n        :param include: Array containing fields to include on response.\n        :param exclude: Array containing fields to exclude on response.\n        :param fields:  Array containing fields to override default fields.\n        :param kind: Determine if result will be detailed ('detail') or basic ('basic').\n        :return: Dict containing neighbors"
  },
  {
    "code": "def register(id, url=None):\n    bucket = registration_s3_bucket()\n    key = registration_key(id)\n    obj = bucket.Object(key)\n    obj.put(Body=url or \"missing\")\n    return _generate_s3_url(bucket, key)",
    "docstring": "Register a UUID key in the global S3 bucket."
  },
  {
    "code": "def base_url(self, base_url=None):\n        if base_url:\n            if urlparse(base_url).scheme != 'https':\n                raise ValueError(\n\t\t    '`base_url`s need to be over `https`. Update your '\n                    '`base_url`.'\n\t\t)\n            self._base_url = base_url\n        else:\n            return self._base_url",
    "docstring": "Return or set `base_url`.\n\n        Args:\n            base_url (str, optional): If set, updates the `base_url`. Otherwise\n                returns current `base_url`.\n\n        Note:\n            This does not update the `username` attribute. Separately update\n            the username with ``Credentials.username`` or update `base_url` and\n            `username` at the same time with ``Credentials.set``.\n\n        Example:\n\n            .. code::\n\n                >>> from cartoframes import Credentials\n                # load credentials saved in previous session\n                >>> creds = Credentials()\n                # returns current base_url\n                >>> creds.base_url()\n                'https://eschbacher.carto.com/'\n                # updates base_url with new value\n                >>> creds.base_url('new_base_url')"
  },
  {
    "code": "def meth_wdl(args):\n    r = fapi.get_repository_method(args.namespace, args.method,\n                                   args.snapshot_id, True)\n    fapi._check_response_code(r, 200)\n    return r.text",
    "docstring": "Retrieve WDL for given version of a repository method"
  },
  {
    "code": "def __generate_really (self, prop_set):\n        assert isinstance(prop_set, property_set.PropertySet)\n        best_alternative = self.__select_alternatives (prop_set, debug=0)\n        self.best_alternative = best_alternative\n        if not best_alternative:\n            self.manager_.errors()(\n                \"No best alternative for '%s'.\\n\"\n                  % (self.full_name(),))\n        result = best_alternative.generate (prop_set)\n        return result",
    "docstring": "Generates the main target with the given property set\n            and returns a list which first element is property_set object\n            containing usage_requirements of generated target and with\n            generated virtual target in other elements. It's possible\n            that no targets are generated."
  },
  {
    "code": "def scroll_deck_x(self, decknum, scroll_x):\n        if decknum >= len(self.decks):\n            raise IndexError(\"I have no deck at {}\".format(decknum))\n        if decknum >= len(self.deck_x_hint_offsets):\n            self.deck_x_hint_offsets = list(self.deck_x_hint_offsets) + [0] * (\n                decknum - len(self.deck_x_hint_offsets) + 1\n            )\n        self.deck_x_hint_offsets[decknum] += scroll_x\n        self._trigger_layout()",
    "docstring": "Move a deck left or right."
  },
  {
    "code": "def wait_for_states(self, timeout=40, *states):\n        state = self.get_attribute('state')\n        for _ in range(timeout):\n            if state in states:\n                return\n            time.sleep(1)\n            state = self.get_attribute('state')\n        raise TgnError('Failed to reach states {}, port state is {} after {} seconds'.format(states, state, timeout))",
    "docstring": "Wait until port reaches one of the requested states.\n\n        :param timeout: max time to wait for requested port states."
  },
  {
    "code": "def create_user(self, projects=None, tasks=None):\n        projects = projects or []\n        tasks = tasks or []\n        dialog = UserCreatorDialog(projects=projects, tasks=tasks, parent=self)\n        dialog.exec_()\n        user = dialog.user\n        if user:\n            userdata = djitemdata.UserItemData(user)\n            treemodel.TreeItem(userdata, self.users_model.root)\n        return user",
    "docstring": "Create and return a new user\n\n        :param projects: the projects for the user\n        :type projects: list of :class:`jukeboxcore.djadapter.models.Project`\n        :param tasks: the tasks for the user\n        :type tasks: list of :class:`jukeboxcore.djadapter.models.Task`\n        :returns: The created user or None\n        :rtype: None | :class:`jukeboxcore.djadapter.models.User`\n        :raises: None"
  },
  {
    "code": "def get_all_tags(self, filters=None, max_records=None, next_token=None):\n        params = {}\n        if max_records:\n            params['MaxRecords'] = max_records\n        if next_token:\n            params['NextToken'] = next_token\n        return self.get_list('DescribeTags', params,\n                             [('member', Tag)])",
    "docstring": "Lists the Auto Scaling group tags.\n\n        This action supports pagination by returning a token if there are more\n        pages to retrieve. To get the next page, call this action again with             the returned token as the NextToken parameter.\n\n        :type filters: dict\n        :param filters: The value of the filter type used to identify\n            the tags to be returned.  NOT IMPLEMENTED YET.\n\n        :type max_records: int\n        :param max_records: Maximum number of tags to return.\n\n        :rtype: list\n        :returns: List of :class:`boto.ec2.autoscale.tag.Tag`\n            instances."
  },
  {
    "code": "def from_extension(extension):\n    if not extension.startswith('.'):\n        raise ValueError(\"Extensions must begin with a period.\")\n    try:\n        return EXTENSION_TO_TYPE[extension.lower()]\n    except KeyError:\n        raise UnknownExtensionError(\n            \"seqmagick does not know how to handle \" +\n            \"files with extensions like this: \" + extension)",
    "docstring": "Look up the BioPython file type corresponding with input extension.\n\n    Look up is case insensitive."
  },
  {
    "code": "def find(self, datum):\n        if isinstance(datum.value, dict) and self.expressions:\n            return datum\n        if isinstance(datum.value, dict) or isinstance(datum.value, list):\n            key = (functools.cmp_to_key(self._compare)\n                   if self.expressions else None)\n            return [jsonpath_rw.DatumInContext.wrap(\n                [value for value in sorted(datum.value, key=key)])]\n        return datum",
    "docstring": "Return sorted value of This if list or dict."
  },
  {
    "code": "def run_script_with_context(script_path, cwd, context):\n    _, extension = os.path.splitext(script_path)\n    contents = io.open(script_path, 'r', encoding='utf-8').read()\n    with tempfile.NamedTemporaryFile(\n        delete=False,\n        mode='wb',\n        suffix=extension\n    ) as temp:\n        env = StrictEnvironment(\n            context=context,\n            keep_trailing_newline=True,\n        )\n        template = env.from_string(contents)\n        output = template.render(**context)\n        temp.write(output.encode('utf-8'))\n    run_script(temp.name, cwd)",
    "docstring": "Execute a script after rendering it with Jinja.\n\n    :param script_path: Absolute path to the script to run.\n    :param cwd: The directory to run the script from.\n    :param context: Cookiecutter project template context."
  },
  {
    "code": "def process_allow_action(processors, action, argument):\n    for processor in processors:\n        processor(action, argument)\n    db.session.commit()",
    "docstring": "Process allow action."
  },
  {
    "code": "def shape(self) -> Tuple[int, int]:\n        return self.sort_timeplaceentries(\n            len(hydpy.pub.timegrids.init), len(self.sequences))",
    "docstring": "Required shape of |NetCDFVariableAgg.array|.\n\n        For the default configuration, the first axis corresponds to the\n        number of devices, and the second one to the number of timesteps.\n        We show this for the 1-dimensional input sequence |lland_fluxes.NKor|:\n\n        >>> from hydpy.core.examples import prepare_io_example_1\n        >>> nodes, elements = prepare_io_example_1()\n        >>> from hydpy.core.netcdftools import NetCDFVariableAgg\n        >>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=False, timeaxis=1)\n        >>> for element in elements:\n        ...     ncvar.log(element.model.sequences.fluxes.nkor, None)\n        >>> ncvar.shape\n        (3, 4)\n\n        When using the first axis as the \"timeaxis\", the order of |tuple|\n        entries turns:\n\n        >>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=False, timeaxis=0)\n        >>> for element in elements:\n        ...     ncvar.log(element.model.sequences.fluxes.nkor, None)\n        >>> ncvar.shape\n        (4, 3)"
  },
  {
    "code": "def find_pattern(search_base, pattern='*.rpm'):\n    if (not os.path.isdir(search_base)) and os.path.exists(search_base):\n        yield search_base\n    else:\n        for root, dirs, files in os.walk(search_base):\n            for filename in fnmatch.filter(files, pattern):\n                yield os.path.join(root, filename)",
    "docstring": "`search_base` - The directory to begin walking down.\n    `pattern` - File pattern to match for.\n\n    This is a generator which yields the full path to files (one at a\n    time) which match the given glob (`pattern`)."
  },
  {
    "code": "async def peers(self):\n        response = await self._api.get(\"/v1/status/peers\")\n        if response.status == 200:\n            return set(response.body)",
    "docstring": "Returns the current Raft peer set\n\n        Returns:\n            Collection: addresses of peers\n\n        This endpoint retrieves the Raft peers for the datacenter in which\n        the agent is running. It returns a collection of addresses, such as::\n\n            [\n               \"10.1.10.12:8300\",\n               \"10.1.10.11:8300\",\n               \"10.1.10.10:8300\"\n            ]\n\n        This list of peers is strongly consistent and can be useful in\n        determining when a given server has successfully joined the cluster."
  },
  {
    "code": "def name_replace(self, to_replace, replacement):\n        self.name = self.name.replace(to_replace, replacement)",
    "docstring": "Replaces part of tag name with new value"
  },
  {
    "code": "def list_qos_policies(self, retrieve_all=True, **_params):\n        return self.list('policies', self.qos_policies_path,\n                         retrieve_all, **_params)",
    "docstring": "Fetches a list of all qos policies for a project."
  },
  {
    "code": "def _retrieve_tag(self, text):\n        if self.tagger == 'tag_ngram_123_backoff':\n            tags = POSTag('latin').tag_ngram_123_backoff(text.lower())\n            return [(tag[0], tag[1]) for tag in tags]\n        elif self.tagger == 'tag_tnt':\n            tags = POSTag('latin').tag_tnt(text.lower())\n            return [(tag[0], tag[1]) for tag in tags]\n        elif self.tagger == 'tag_crf':\n            tags = POSTag('latin').tag_crf(text.lower())\n            return [(tag[0], tag[1]) for tag in tags]",
    "docstring": "Tag text with chosen tagger and clean tags.\n\n        Tag format: [('word', 'tag')]\n\n        :param text: string\n        :return: list of tuples, with each tuple containing the word and its pos tag\n        :rtype : list"
  },
  {
    "code": "def CreateAllStaticECMWFRAPIDFiles(in_drainage_line,\n                                   river_id,\n                                   length_id,\n                                   slope_id,\n                                   next_down_id,\n                                   in_catchment,\n                                   catchment_river_id,\n                                   rapid_output_folder,\n                                   kfac_celerity=1000.0/3600.0,\n                                   kfac_formula_type=3,\n                                   kfac_length_units=\"km\",\n                                   lambda_k=0.35,\n                                   x_value=0.3,\n                                   nhdplus=False,\n                                   taudem_network_connectivity_tree_file=None,\n                                   file_geodatabase=None):\n    CreateAllStaticRAPIDFiles(in_drainage_line,\n                              river_id,\n                              length_id,\n                              slope_id,\n                              next_down_id,\n                              rapid_output_folder,\n                              kfac_celerity,\n                              kfac_formula_type,\n                              kfac_length_units,\n                              lambda_k,\n                              x_value,\n                              nhdplus,\n                              taudem_network_connectivity_tree_file,\n                              file_geodatabase)\n    rapid_connect_file = os.path.join(rapid_output_folder, 'rapid_connect.csv')\n    CreateAllStaticECMWFFiles(in_catchment,\n                              catchment_river_id,\n                              rapid_output_folder,\n                              rapid_connect_file,\n                              file_geodatabase)",
    "docstring": "This creates all of the static RAPID files and ECMWF grid weight tables.\n\n    Parameters\n    ----------\n    in_drainage_line: str\n        Path to the stream network (i.e. Drainage Line) shapefile.\n    river_id: str\n        The name of the field with the river ID\n        (Ex. 'HydroID', 'COMID', or 'LINKNO').\n    length_id: str\n        The field name containging the length of the river segment\n        (Ex. 'LENGTHKM' or 'Length').\n    slope_id: str\n        The field name containging the slope of the river segment\n        (Ex. 'Avg_Slope' or 'Slope').\n    next_down_id: str\n        The name of the field with the river ID of the next downstream\n        river segment (Ex. 'NextDownID' or 'DSLINKNO').\n    in_catchment: str\n        Path to the Catchment shapefile.\n    catchment_river_id: str\n        The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').\n    rapid_output_folder: str\n        The path to the folder where all of the RAPID output will be generated.\n    kfac_celerity: float, optional\n        The flow wave celerity for the watershed in meters per second.\n        1 km/hr or 1000.0/3600.0 m/s is a reasonable value if unknown.\n    kfac_formula_type: int, optional\n        An integer representing the formula type to use when calculating kfac.\n        Default is 3.\n    kfac_length_units: str, optional\n        The units for the length_id field. Supported types are \"m\" for meters\n        and \"km\" for kilometers. Default is \"km\".\n    lambda_k: float, optional\n        The value for lambda given from RAPID after the calibration process.\n        Default is 0.35.\n    x_value: float, optional\n        Value for the muskingum X parameter [0-0.5].Default is 0.3.\n    nhdplus: bool, optional\n        If True, the drainage line is from the NHDPlus dataset with the\n        VAA fields COMID, FROMNODE, TONODE, and DIVERGENCE. Default is False.\n    taudem_network_connectivity_tree_file: str, optional\n        If set, the connectivity file will be generated from the\n        TauDEM connectivity tree file.\n    file_geodatabase: str, optional\n        Path to the file geodatabase. If you use this option,\n        in_drainage_line is the name of the stream network feature class\n        (WARNING: Not always stable with GDAL).\n\n\n    Example::\n\n        from RAPIDpy.gis.workflow import CreateAllStaticECMWFRAPIDFiles\n\n        CreateAllStaticECMWFRAPIDFiles(\n            in_drainage_line=\"/path/to/drainage_line.shp\",\n            river_id=\"HydroID\",\n            length_id=\"LENGTHKM\",\n            slope_id=\"SLOPE\",\n            next_down_id=\"NextDownID\",\n            in_catchment=\"/path/to/catchment.shp\",\n            catchment_river_id=\"DrainLnID\",\n            rapid_output_folder=\"/path/to/rapid/output\",\n        )"
  },
  {
    "code": "def recv_from_app(timeout=_default_timeout):\n        try:\n            return ApplicationLayer._from_app.get(timeout=timeout)\n        except Empty:\n            pass\n        raise NoPackets()",
    "docstring": "Called by a network stack implementer to receive application-layer\n        data for sending on to a remote location.  \n\n        Can optionally take a timeout value.  If no data are available,\n        raises NoPackets exception.\n\n        Returns a 2-tuple: flowaddr and data.\n        The flowaddr consists of 5 items: protocol, localaddr, localport, \n        remoteaddr, remoteport."
  },
  {
    "code": "def _write_html_file(word, translations, data_dir, native=False):\n    content_str = _create_html_file_content(translations)\n    html_string = HTML_TEMPLATE.replace(\"{% word %}\", word)\n    html_string = html_string.replace(\"{% content %}\", content_str)\n    trans_dir = \"translations\"\n    if native:\n        trans_dir += \"_native\"\n    translations_dir = data_dir.joinpath(trans_dir)\n    fname = translations_dir.joinpath(\"{word}.html\".format(word=word))\n    save_file(fname, html_string, mk_parents=True)",
    "docstring": "Create html file of word translations.\n\n    Parameters\n    ----------\n    word : str\n        Word that was translated.\n    tralnslations : dict\n        Dictionary of word translations.\n    data_dir : pathlib.Path\n        Location where html files are saved."
  },
  {
    "code": "def createUser(self, localpart, domain, password=None):\n        loginSystem = self.browser.store.parent.findUnique(userbase.LoginSystem)\n        if password is None:\n            password = u''.join([random.choice(string.ascii_letters + string.digits) for i in xrange(8)])\n        loginSystem.addAccount(localpart, domain, password)",
    "docstring": "Create a new, blank user account with the given name and domain and, if\n        specified, with the given password.\n\n        @type localpart: C{unicode}\n        @param localpart: The local portion of the username.  ie, the\n        C{'alice'} in C{'alice@example.com'}.\n\n        @type domain: C{unicode}\n        @param domain: The domain portion of the username.  ie, the\n        C{'example.com'} in C{'alice@example.com'}.\n\n        @type password: C{unicode} or C{None}\n        @param password: The password to associate with the new account.  If\n        C{None}, generate a new password automatically."
  },
  {
    "code": "def update_dns(self, new_ip):\n        headers = None\n        if self.auth_type == 'T':\n            api_call_url = self._base_url.format(hostname=self.hostname,\n                                                 token=self.auth.token,\n                                                 ip=new_ip)\n        else:\n            api_call_url = self._base_url.format(hostname=self.hostname,\n                                                 ip=new_ip)\n            headers = {\n                'Authorization': \"Basic %s\" %\n                                 self.auth.base64key.decode('utf-8'),\n                'User-Agent': \"%s/%s %s\" % (__title__, __version__, __email__)\n            }\n        r = requests.get(api_call_url, headers=headers)\n        self.last_ddns_response = str(r.text).strip()\n        return r.status_code, r.text",
    "docstring": "Call No-IP API based on dict login_info and return the status code."
  },
  {
    "code": "def _add_edge(self, layer, input_id, output_id):\n        if layer in self.layer_to_id:\n            layer_id = self.layer_to_id[layer]\n            if input_id not in self.layer_id_to_input_node_ids[layer_id]:\n                self.layer_id_to_input_node_ids[layer_id].append(input_id)\n            if output_id not in self.layer_id_to_output_node_ids[layer_id]:\n                self.layer_id_to_output_node_ids[layer_id].append(output_id)\n        else:\n            layer_id = len(self.layer_list)\n            self.layer_list.append(layer)\n            self.layer_to_id[layer] = layer_id\n            self.layer_id_to_input_node_ids[layer_id] = [input_id]\n            self.layer_id_to_output_node_ids[layer_id] = [output_id]\n        self.adj_list[input_id].append((output_id, layer_id))\n        self.reverse_adj_list[output_id].append((input_id, layer_id))",
    "docstring": "Add a new layer to the graph. The nodes should be created in advance."
  },
  {
    "code": "def _updateToDeleted(self,directory,fn,dentry,db,service):\n        if fn not in db:\n            print(\"%s - rm: not in DB, skipping!\"%(fn))\n            return\n        services=self.sman.GetServices(fn)\n        if (not services):\n            print(\"%s - no manger of this file type found\"%(fn))\n            return\n        if service:\n            if db[fn]['services'].has_key(service):\n                db[fn]['services'][service]['status']=self.ST_DELETED\n            else:\n                print(\"%s - Service %s doesn't exist, can't delete\"%(fn,service))\n            return\n        for service in db[fn]['services']:\n            db[fn]['services'][service]['status']=self.ST_DELETED\n        return",
    "docstring": "Changes to status to 'D' as long as a handler exists,\n        directory - DIR where stuff is happening\n        fn - File name to be added\n        dentry - dictionary entry as returned by GetStatus for this file\n        db - pusher DB for this directory\n        service - service to delete, None means all"
  },
  {
    "code": "def _logfile_sigterm_handler(*_):\n    logging.error('Received SIGTERM.')\n    write_logfile()\n    print('Received signal. Please see the log file for more information.',\n          file=sys.stderr)\n    sys.exit(signal)",
    "docstring": "Handle exit signals and write out a log file.\n\n    Raises:\n        SystemExit: Contains the signal as the return code."
  },
  {
    "code": "def _ensure_product_string(cls, product):\n        if isinstance(product, str):\n            return product\n        if isinstance(product, list):\n            return os.path.join(*product)\n        raise DataError(\"Unknown object (not str or list) specified as a component product\", product=product)",
    "docstring": "Ensure that all product locations are strings.\n\n        Older components specify paths as lists of path components.  Join\n        those paths into a normal path string."
  },
  {
    "code": "def read_mesh(fname):\n    fmt = op.splitext(fname)[1].lower()\n    if fmt == '.gz':\n        fmt = op.splitext(op.splitext(fname)[0])[1].lower()\n    if fmt in ('.obj'):\n        return WavefrontReader.read(fname)\n    elif not format:\n        raise ValueError('read_mesh needs could not determine format.')\n    else:\n        raise ValueError('read_mesh does not understand format %s.' % fmt)",
    "docstring": "Read mesh data from file.\n\n    Parameters\n    ----------\n    fname : str\n        File name to read. Format will be inferred from the filename.\n        Currently only '.obj' and '.obj.gz' are supported.\n\n    Returns\n    -------\n    vertices : array\n        Vertices.\n    faces : array | None\n        Triangle face definitions.\n    normals : array\n        Normals for the mesh.\n    texcoords : array | None\n        Texture coordinates."
  },
  {
    "code": "def from_config(cls, name, config):\n        cls.validate_config(config)\n        instance = cls()\n        if not instance.name:\n            instance.name = config.get(\"name\", name)\n        instance.apply_config(config)\n        return instance",
    "docstring": "Returns a Configurable instance with the given name and config.\n\n        By default this is a simple matter of calling the constructor, but\n        subclasses that are also `Pluggable` instances override this in order\n        to check that the plugin is installed correctly first."
  },
  {
    "code": "def get_resource(self, path):\n        response = self._http_request(path)\n        try:\n            return response.json()\n        except ValueError:\n            raise exception.ServiceException(\"Invalid service response.\")",
    "docstring": "Getting the required information from the API."
  },
  {
    "code": "def redirect_stream(system_stream, target_stream):\n        if target_stream is None:\n            target_fd = os.open(os.devnull, os.O_RDWR)\n        else:\n            target_fd = target_stream.fileno()\n        os.dup2(target_fd, system_stream.fileno())",
    "docstring": "Redirect a system stream to a specified file.\n            `system_stream` is a standard system stream such as\n            ``sys.stdout``. `target_stream` is an open file object that\n            should replace the corresponding system stream object.\n            If `target_stream` is ``None``, defaults to opening the\n            operating system's null device and using its file descriptor."
  },
  {
    "code": "def get_clouds(wxdata: [str]) -> ([str], list):\n    clouds = []\n    for i, item in reversed(list(enumerate(wxdata))):\n        if item[:3] in CLOUD_LIST or item[:2] == 'VV':\n            cloud = wxdata.pop(i)\n            clouds.append(make_cloud(cloud))\n    return wxdata, sorted(clouds, key=lambda cloud: (cloud.altitude, cloud.type))",
    "docstring": "Returns the report list and removed list of split cloud layers"
  },
  {
    "code": "def get_time(self, force_uptime=False):\n        if force_uptime:\n            return self.uptime\n        time = self.uptime + self.time_offset\n        if self.is_utc:\n            time |= (1 << 31)\n        return time",
    "docstring": "Get the current UTC time or uptime.\n\n        By default, this method will return UTC time if possible and fall back\n        to uptime if not.  If you specify, force_uptime=True, it will always\n        return uptime even if utc time is available.\n\n        Args:\n            force_uptime (bool): Always return uptime, defaults to False.\n\n        Returns:\n            int: The current uptime or encoded utc time."
  },
  {
    "code": "def started_tasks(self, task_registry_id=None, task_cls=None):\n\t\tif task_registry_id is not None:\n\t\t\ttask = None\n\t\t\tfor registered_task in self.__started:\n\t\t\t\tif registered_task.__registry_tag__ == task_registry_id:\n\t\t\t\t\ttask = registered_task\n\t\t\tif task_cls is not None and task is not None:\n\t\t\t\tif isinstance(task, task_cls) is True:\n\t\t\t\t\treturn task\n\t\t\t\treturn None\n\t\t\treturn task\n\t\tresult = filter(lambda x: x is not None, self.__started)\n\t\tif task_cls is not None:\n\t\t\tresult = filter(lambda x: isinstance(x, task_cls), result)\n\t\treturn tuple(result)",
    "docstring": "Return tasks that was started. Result way be filtered by the given arguments.\n\n\t\t:param task_registry_id: if it is specified, then try to return single task which id is the same as \\\n\t\tthis value.\n\t\t:param task_cls: if it is specified then result will be consists of this subclass only\n\n\t\t:return: None or WTask or tuple of WTask"
  },
  {
    "code": "def parse_unifrac_v1_8(unifrac, file_data):\n    for line in file_data:\n        if line == \"\":\n            break\n        line = line.split(\"\\t\")\n        unifrac[\"pcd\"][line[0]] = [float(e) for e in line[1:]]\n    unifrac[\"eigvals\"] = [float(entry) for entry in file_data[-2].split(\"\\t\")[1:]]\n    unifrac[\"varexp\"] = [float(entry) for entry in file_data[-1].split(\"\\t\")[1:]]\n    return unifrac",
    "docstring": "Function to parse data from older version of unifrac file obtained from Qiime version\n    1.8 and earlier.\n\n    :type unifrac: dict\n    :param unifracFN: The path to the unifrac results file\n\n    :type file_data: list\n    :param file_data: Unifrac data lines after stripping whitespace characters."
  },
  {
    "code": "def server_document(url=\"default\", relative_urls=False, resources=\"default\", arguments=None):\n    url = _clean_url(url)\n    app_path = _get_app_path(url)\n    elementid = make_id()\n    src_path = _src_path(url, elementid)\n    src_path += _process_app_path(app_path)\n    src_path += _process_relative_urls(relative_urls, url)\n    src_path += _process_resources(resources)\n    src_path += _process_arguments(arguments)\n    tag = AUTOLOAD_TAG.render(\n        src_path  = src_path,\n        app_path  = app_path,\n        elementid = elementid,\n    )\n    return encode_utf8(tag)",
    "docstring": "Return a script tag that embeds content from a Bokeh server.\n\n    Bokeh apps embedded using these methods will NOT set the browser window title.\n\n    Args:\n        url (str, optional) :\n            A URL to a Bokeh application on a Bokeh server (default: \"default\")\n\n            If ``\"default\"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used.\n\n        relative_urls (bool, optional) :\n            Whether to use relative URLs for resources.\n\n            If ``True`` the links generated for resources such a BokehJS\n            JavaScript and CSS will be relative links.\n\n            This should normally be set to ``False``, but must be set to\n            ``True`` in situations where only relative URLs will work. E.g.\n            when running the Bokeh behind reverse-proxies under certain\n            configurations\n\n        resources (str) : A string specifying what resources need to be loaded\n            along with the document.\n\n            If ``default`` then the default JS/CSS bokeh files will be loaded.\n\n            If None then none of the resource files will be loaded. This is\n            useful if you prefer to serve those resource files via other means\n            (e.g. from a caching server). Be careful, however, that the resource\n            files you'll load separately are of the same version as that of the\n            server's, otherwise the rendering may not work correctly.\n\n       arguments (dict[str, str], optional) :\n            A dictionary of key/values to be passed as HTTP request arguments\n            to Bokeh application code (default: None)\n\n    Returns:\n        A ``<script>`` tag that will embed content from a Bokeh Server."
  },
  {
    "code": "def tag_myself(project='cwc', **other_tags):\n    base_url = \"http://169.254.169.254\"\n    try:\n        resp = requests.get(base_url + \"/latest/meta-data/instance-id\")\n    except requests.exceptions.ConnectionError:\n        logger.warning(\"Could not connect to service. Note this should only \"\n                       \"be run from within a batch job.\")\n        return\n    instance_id = resp.text\n    tag_instance(instance_id, project=project, **other_tags)\n    return",
    "docstring": "Function run when indra is used in an EC2 instance to apply tags."
  },
  {
    "code": "def extract_xz(archive, compression, cmd, verbosity, interactive, outdir):\n    return _extract(archive, compression, cmd, 'xz', verbosity, outdir)",
    "docstring": "Extract an XZ archive with the lzma Python module."
  },
  {
    "code": "def percent_records_missing_location(user, method=None):\n    if len(user.records) == 0:\n        return 0.\n    missing_locations = sum([1 for record in user.records if record.position._get_location(user) is None])\n    return float(missing_locations) / len(user.records)",
    "docstring": "Return the percentage of records missing a location parameter."
  },
  {
    "code": "def construct_user_list(raw_users=None):\n        users = Users(oktypes=User)\n        for user_dict in raw_users:\n            public_keys = None\n            if user_dict.get('public_keys'):\n                public_keys = [PublicKey(b64encoded=x, raw=None)\n                               for x in user_dict.get('public_keys')]\n            users.append(User(name=user_dict.get('name'),\n                              passwd=user_dict.get('passwd'),\n                              uid=user_dict.get('uid'),\n                              gid=user_dict.get('gid'),\n                              home_dir=user_dict.get('home_dir'),\n                              gecos=user_dict.get('gecos'),\n                              shell=user_dict.get('shell'),\n                              public_keys=public_keys,\n                              sudoers_entry=user_dict.get('sudoers_entry')))\n        return users",
    "docstring": "Construct a list of User objects from a list of dicts."
  },
  {
    "code": "def has_variantcalls(data):\n    analysis = get_analysis(data).lower()\n    variant_pipeline = analysis.startswith((\"standard\", \"variant\", \"variant2\"))\n    variantcaller = get_variantcaller(data)\n    return variant_pipeline or variantcaller",
    "docstring": "returns True if the data dictionary is configured for variant calling"
  },
  {
    "code": "def validate_ok_for_replace(replacement):\n    validate_is_mapping(\"replacement\", replacement)\n    if replacement and not isinstance(replacement, RawBSONDocument):\n        first = next(iter(replacement))\n        if first.startswith('$'):\n            raise ValueError('replacement can not include $ operators')",
    "docstring": "Validate a replacement document."
  },
  {
    "code": "def batch_delete_intents(self,\n                             parent,\n                             intents,\n                             retry=google.api_core.gapic_v1.method.DEFAULT,\n                             timeout=google.api_core.gapic_v1.method.DEFAULT,\n                             metadata=None):\n        if 'batch_delete_intents' not in self._inner_api_calls:\n            self._inner_api_calls[\n                'batch_delete_intents'] = google.api_core.gapic_v1.method.wrap_method(\n                    self.transport.batch_delete_intents,\n                    default_retry=self._method_configs[\n                        'BatchDeleteIntents'].retry,\n                    default_timeout=self._method_configs['BatchDeleteIntents']\n                    .timeout,\n                    client_info=self._client_info,\n                )\n        request = intent_pb2.BatchDeleteIntentsRequest(\n            parent=parent,\n            intents=intents,\n        )\n        operation = self._inner_api_calls['batch_delete_intents'](\n            request, retry=retry, timeout=timeout, metadata=metadata)\n        return google.api_core.operation.from_gapic(\n            operation,\n            self.transport._operations_client,\n            empty_pb2.Empty,\n            metadata_type=struct_pb2.Struct,\n        )",
    "docstring": "Deletes intents in the specified agent.\n\n        Operation <response: ``google.protobuf.Empty``>\n\n        Example:\n            >>> import dialogflow_v2\n            >>>\n            >>> client = dialogflow_v2.IntentsClient()\n            >>>\n            >>> parent = client.project_agent_path('[PROJECT]')\n            >>>\n            >>> # TODO: Initialize ``intents``:\n            >>> intents = []\n            >>>\n            >>> response = client.batch_delete_intents(parent, intents)\n            >>>\n            >>> def callback(operation_future):\n            ...     # Handle result.\n            ...     result = operation_future.result()\n            >>>\n            >>> response.add_done_callback(callback)\n            >>>\n            >>> # Handle metadata.\n            >>> metadata = response.metadata()\n\n        Args:\n            parent (str): Required. The name of the agent to delete all entities types for. Format:\n                ``projects/<Project ID>/agent``.\n            intents (list[Union[dict, ~google.cloud.dialogflow_v2.types.Intent]]): Required. The collection of intents to delete. Only intent ``name`` must be\n                filled in.\n                If a dict is provided, it must be of the same form as the protobuf\n                message :class:`~google.cloud.dialogflow_v2.types.Intent`\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.dialogflow_v2.types._OperationFuture` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def merge(self, df: pd.DataFrame, on: str, how: str=\"outer\", **kwargs):\n        try:\n            df = pd.merge(self.df, df, on=on, how=how, **kwargs)\n            self.df = df\n        except Exception as e:\n            self.err(e, self.merge, \"Can not merge dataframes\")",
    "docstring": "Set the main dataframe from the current dataframe and the passed\n        dataframe\n\n        :param df: the pandas dataframe to merge\n        :type df: pd.DataFrame\n        :param on: param for ``pd.merge``\n        :type on: str\n        :param how: param for ``pd.merge``, defaults to \"outer\"\n        :type how: str, optional\n        :param kwargs: keyword arguments for ``pd.merge``"
  },
  {
    "code": "def get_cached_element_by_path(data_tree, path):\n    if not isinstance(data_tree, ArTree):\n        logger.warning(\"%s not called with ArTree, return None\", get_cached_element_by_path.__name__)\n        return None\n    ptr = data_tree\n    for name in path.split('/'):\n        if ptr is None:\n            return None\n        if name.strip():\n            ptr = ptr.get_child_by_name(name)\n    return ptr.ref if ptr else None",
    "docstring": "Get element from ArTree by path."
  },
  {
    "code": "def isin(self, values):\n        if not isinstance(values, list):\n            raise TypeError(\"Input should be a string. {} was provided\".format(type(values)))\n        if not (self.name.startswith(\"(\") and self.name.endswith(\")\")):\n            first = True\n            new_condition = None\n            for v in values:\n                if first:\n                    first = False\n                    new_condition = self.__eq__(v)\n                else:\n                    new_condition = new_condition.__or__(self.__eq__(v))\n            return new_condition\n        else:\n            raise SyntaxError(\"You cannot use 'isin' with a complex condition\")",
    "docstring": "Selects the samples having the metadata attribute between the values provided\n        as input\n\n        :param values: a list of elements\n        :return a new complex condition"
  },
  {
    "code": "def _check_transition_target(self, transition):\n        to_state_id = transition.to_state\n        to_outcome_id = transition.to_outcome\n        if to_state_id == self.state_id:\n            if to_outcome_id not in self.outcomes:\n                return False, \"to_outcome is not existing\"\n        else:\n            if to_state_id not in self.states:\n                return False, \"to_state is not existing\"\n            if to_outcome_id is not None:\n                return False, \"to_outcome must be None as transition goes to child state\"\n        return True, \"valid\"",
    "docstring": "Checks the validity of a transition target\n\n        Checks whether the transition target is valid.\n\n        :param rafcon.core.transition.Transition transition: The transition to be checked\n        :return bool validity, str message: validity is True, when the transition is valid, False else. message gives\n            more information especially if the transition is not valid"
  },
  {
    "code": "def blob(\n        self,\n        blob_name,\n        chunk_size=None,\n        encryption_key=None,\n        kms_key_name=None,\n        generation=None,\n    ):\n        return Blob(\n            name=blob_name,\n            bucket=self,\n            chunk_size=chunk_size,\n            encryption_key=encryption_key,\n            kms_key_name=kms_key_name,\n            generation=generation,\n        )",
    "docstring": "Factory constructor for blob object.\n\n        .. note::\n          This will not make an HTTP request; it simply instantiates\n          a blob object owned by this bucket.\n\n        :type blob_name: str\n        :param blob_name: The name of the blob to be instantiated.\n\n        :type chunk_size: int\n        :param chunk_size: The size of a chunk of data whenever iterating\n                           (in bytes). This must be a multiple of 256 KB per\n                           the API specification.\n\n        :type encryption_key: bytes\n        :param encryption_key:\n            Optional 32 byte encryption key for customer-supplied encryption.\n\n        :type kms_key_name: str\n        :param kms_key_name:\n            Optional resource name of KMS key used to encrypt blob's content.\n\n        :type generation: long\n        :param generation: Optional. If present, selects a specific revision of\n                           this object.\n\n        :rtype: :class:`google.cloud.storage.blob.Blob`\n        :returns: The blob object created."
  },
  {
    "code": "def load(self):\n        if not git:\n            raise EnvironmentError(MISSING_GIT_ERROR)\n        if os.path.exists(self.path):\n            if not config.CACHE_DISABLE:\n                return\n            shutil.rmtree(self.path, ignore_errors=True)\n        with files.remove_on_exception(self.path):\n            url = self.GIT_URL.format(**vars(self))\n            repo = git.Repo.clone_from(\n                url=url, to_path=self.path, b=self.branch)\n            if self.commit:\n                repo.head.reset(self.commit, index=True, working_tree=True)",
    "docstring": "Load the library."
  },
  {
    "code": "def _parse_message(self, data):\n        try:\n            header, values = data.split(':')\n            address, channel, value = values.split(',')\n            self.address = int(address)\n            self.channel = int(channel)\n            self.value = int(value)\n        except ValueError:\n            raise InvalidMessageError('Received invalid message: {0}'.format(data))\n        if header == '!EXP':\n            self.type = ExpanderMessage.ZONE\n        elif header == '!REL':\n            self.type = ExpanderMessage.RELAY\n        else:\n            raise InvalidMessageError('Unknown expander message header: {0}'.format(data))",
    "docstring": "Parse the raw message from the device.\n\n        :param data: message data\n        :type data: string\n\n        :raises: :py:class:`~alarmdecoder.util.InvalidMessageError`"
  },
  {
    "code": "def n_pitche_classes_used(pianoroll):\n    _validate_pianoroll(pianoroll)\n    chroma = _to_chroma(pianoroll)\n    return np.count_nonzero(np.any(chroma, 0))",
    "docstring": "Return the number of unique pitch classes used in a pianoroll."
  },
  {
    "code": "def sample_random(self):\n        if self.sampling_mode['volume']:  \n            if self.leafnode:\n                return self.sample_bounds()\n            else:\n                split_ratio = ((self.split_value - self.bounds_x[0,self.split_dim]) / \n                               (self.bounds_x[1,self.split_dim] - self.bounds_x[0,self.split_dim]))\n                if split_ratio > np.random.random():\n                    return self.lower.sample(sampling_mode=['random'])\n                else:\n                    return self.greater.sample(sampling_mode=['random'])\n        else: \n            return np.random.choice(self.get_leaves()).sample_bounds()",
    "docstring": "Sample a point in a random leaf."
  },
  {
    "code": "def from_pandas(cls, index):\n        from pandas import Index as PandasIndex\n        check_type(index, PandasIndex)\n        return Index(index.values,\n                     index.dtype,\n                     index.name)",
    "docstring": "Create baloo Index from pandas Index.\n\n        Parameters\n        ----------\n        index : pandas.base.Index\n\n        Returns\n        -------\n        Index"
  },
  {
    "code": "def json_format(out, graph):\n    steps = {}\n    for step, deps in each_step(graph):\n        steps[step.name] = {}\n        steps[step.name][\"deps\"] = [dep.name for dep in deps]\n    json.dump({\"steps\": steps}, out, indent=4)\n    out.write(\"\\n\")",
    "docstring": "Outputs the graph in a machine readable JSON format."
  },
  {
    "code": "def _request(self, proxy, timeout):\n        return request.WPToolsRequest(self.flags['silent'],\n                                      self.flags['verbose'],\n                                      proxy, timeout)",
    "docstring": "Returns WPToolsRequest object"
  },
  {
    "code": "def showMessageOverlay(self, pchText, pchCaption, pchButton0Text, pchButton1Text, pchButton2Text, pchButton3Text):\n        fn = self.function_table.showMessageOverlay\n        result = fn(pchText, pchCaption, pchButton0Text, pchButton1Text, pchButton2Text, pchButton3Text)\n        return result",
    "docstring": "Show the message overlay. This will block and return you a result."
  },
  {
    "code": "def overlay(im1, im2, c):\n    r\n    shape = im2.shape\n    for ni in shape:\n        if ni % 2 == 0:\n            raise Exception(\"Structuring element must be odd-voxeled...\")\n    nx, ny, nz = [(ni - 1) // 2 for ni in shape]\n    cx, cy, cz = c\n    im1[cx-nx:cx+nx+1, cy-ny:cy+ny+1, cz-nz:cz+nz+1] += im2\n    return im1",
    "docstring": "r\"\"\"\n    Overlays ``im2`` onto ``im1``, given voxel coords of center of ``im2``\n    in ``im1``.\n\n    Parameters\n    ----------\n    im1 : ND-array\n        Original voxelated image\n    im2 : ND-array\n        Template voxelated image\n    c : array_like\n        [x, y, z] coordinates in ``im1`` where ``im2`` will be centered\n\n    Returns\n    -------\n    image : ND-array\n        A modified version of ``im1``, with ``im2`` overlaid at the specified\n        location"
  },
  {
    "code": "def _get_stack_info_for_trace(\n        self,\n        frames,\n        library_frame_context_lines=None,\n        in_app_frame_context_lines=None,\n        with_locals=True,\n        locals_processor_func=None,\n    ):\n        return list(\n            iterate_with_template_sources(\n                frames,\n                with_locals=with_locals,\n                library_frame_context_lines=library_frame_context_lines,\n                in_app_frame_context_lines=in_app_frame_context_lines,\n                include_paths_re=self.include_paths_re,\n                exclude_paths_re=self.exclude_paths_re,\n                locals_processor_func=locals_processor_func,\n            )\n        )",
    "docstring": "If the stacktrace originates within the elasticapm module, it will skip\n        frames until some other module comes up."
  },
  {
    "code": "def act_on_droplets(self, **data):\n        r\n        api = self.doapi_manager\n        return map(api._action, api.request('/v2/droplets/actions', method='POST', params={\"tag_name\": self.name}, data=data)[\"actions\"])",
    "docstring": "r\"\"\"\n        Perform an arbitrary action on all of the droplets to which the tag is\n        applied.  ``data`` will be serialized as JSON and POSTed to the proper\n        API endpoint.  All currently-documented actions require the POST body\n        to be a JSON object containing, at a minimum, a ``\"type\"`` field.\n\n        :return: a generator of `Action`\\ s representing the in-progress\n            operations on the droplets\n        :rtype: generator of `Action`\\ s\n        :raises DOAPIError: if the API endpoint replies with an error"
  },
  {
    "code": "def get_zone(self, id=None, name=None):\n        log.info(\"Picking zone: %s (%s)\" % (name, id))\n        return self.zones[id or name]",
    "docstring": "Get zone object by name or id."
  },
  {
    "code": "def parse(self, node):\n        self._attrs = {}\n        vals = []\n        yielded = False\n        for x in self._read_parts(node):\n            if isinstance(x, Field):\n                yielded = True\n                x.attrs = self._attrs\n                yield x\n            else:\n                vals.append(ustr(x).strip(' \\n\\t'))\n        joined = ' '.join([ x for x in vals if x ])\n        if joined:\n            yielded = True\n            yield Field(node, guess_type(joined), self._attrs)\n        if not yielded:\n            yield Field(node, \"\", self._attrs)",
    "docstring": "Return generator yielding Field objects for a given node"
  },
  {
    "code": "def generic_find_fk_constraint_names(table, columns, referenced, insp):\n    names = set()\n    for fk in insp.get_foreign_keys(table):\n        if fk['referred_table'] == referenced and set(fk['referred_columns']) == columns:\n            names.add(fk['name'])\n    return names",
    "docstring": "Utility to find foreign-key constraint names in alembic migrations"
  },
  {
    "code": "def get_all(self, start=0, count=-1, sort=''):\n        return self._helper.get_all(start, count, sort=sort)",
    "docstring": "Gets a list of logical interconnects based on optional sorting and filtering and is constrained by start\n        and count parameters.\n\n        Args:\n            start:\n                The first item to return, using 0-based indexing.\n                If not specified, the default is 0 - start with the first available item.\n            count:\n                The number of resources to return. A count of -1 requests all items.\n                The actual number of items in the response might differ from the requested\n                count if the sum of start and count exceeds the total number of items.\n            sort:\n                The sort order of the returned data set. By default, the sort order is based\n                on create time with the oldest entry first.\n\n        Returns:\n            list: A list of logical interconnects."
  },
  {
    "code": "def validate(self, guide):\n        if is_string(guide):\n            guide = Registry['guide_{}'.format(guide)]()\n        if not isinstance(guide, guide_class):\n            raise PlotnineError(\n                \"Unknown guide: {}\".format(guide))\n        return guide",
    "docstring": "Validate guide object"
  },
  {
    "code": "def after_object(eng, objects, obj):\n        super(InvenioProcessingFactory, InvenioProcessingFactory)\\\n            .after_object(eng, objects, obj)\n        obj.save(\n            status=obj.known_statuses.COMPLETED,\n            id_workflow=eng.model.uuid\n        )\n        db.session.commit()",
    "docstring": "Take action once the proccessing of an object completes."
  },
  {
    "code": "def _string_parser(strip_whitespace):\n    def _parse_string_value(element_text, _state):\n        if element_text is None:\n            value = ''\n        elif strip_whitespace:\n            value = element_text.strip()\n        else:\n            value = element_text\n        return value\n    return _parse_string_value",
    "docstring": "Return a parser function for parsing string values."
  },
  {
    "code": "def build(\n        documentPath,\n        outputUFOFormatVersion=3,\n        roundGeometry=True,\n        verbose=True,\n        logPath=None,\n        progressFunc=None,\n        processRules=True,\n        logger=None,\n        useVarlib=False,\n        ):\n    import os, glob\n    if os.path.isdir(documentPath):\n        todo = glob.glob(os.path.join(documentPath, \"*.designspace\"))\n    else:\n        todo = [documentPath]\n    results = []\n    for path in todo:\n        document = DesignSpaceProcessor(ufoVersion=outputUFOFormatVersion)\n        document.useVarlib = useVarlib\n        document.roundGeometry = roundGeometry\n        document.read(path)\n        try:\n            r = document.generateUFO(processRules=processRules)\n            results.append(r)\n        except:\n            if logger:\n                logger.exception(\"ufoProcessor error\")\n        reader = None\n    return results",
    "docstring": "Simple builder for UFO designspaces."
  },
  {
    "code": "def setFDs(self):\n        self.childFDs = {0: 0, 1: 1, 2: 2}\n        self.fds = {}\n        for name in self.servers:\n            self.port = self.hendrix.get_port(name)\n            fd = self.port.fileno()\n            self.childFDs[fd] = fd\n            self.fds[name] = fd",
    "docstring": "Iterator for file descriptors.\n        Seperated from launchworkers for clarity and readability."
  },
  {
    "code": "def get_available_languages(self, obj):\n        return obj.available_languages if obj is not None else self.model.objects.none()",
    "docstring": "Returns available languages for current object."
  },
  {
    "code": "def delete(self):\n        if not self.id:\n            return\n        self.collection.remove({'_id': self._id})\n        self.on_delete(self)",
    "docstring": "Remove from database."
  },
  {
    "code": "def _getInterfaces(self):\n        interfaces = {}\n        interfacesPath = os.path.join(\"application\", \"interface\")\n        interfaceList = os.listdir(interfacesPath)\n        for file in interfaceList:\n            interfaceDirectoryPath = os.path.join(interfacesPath, file)\n            if not os.path.isdir(interfaceDirectoryPath) or file.startswith(\"__\") or file.startswith(\".\"):\n                continue\n            interfaceName = ntpath.basename(interfaceDirectoryPath)\n            interfacePath = os.path.join(interfaceDirectoryPath, interfaceName) + \".py\"\n            if not os.path.isfile(interfacePath):\n                continue\n            interfaceSpec = importlib.util.spec_from_file_location(\n                interfaceName,\n                interfacePath\n            )\n            interface = importlib.util.module_from_spec(interfaceSpec)\n            interfaceSpec.loader.exec_module(interface)\n            if hasattr(interface, \"Service\"):\n                interfaceInstance = interface.Service(self)\n                interfaces[interfaceName] = interfaceInstance\n        return interfaces",
    "docstring": "Load application communication interfaces.\n\n        :return: <dict>"
  },
  {
    "code": "def trust(self, scope, vk):\n        self.data['verifiers'].append({'scope': scope, 'vk': vk})\n        return self",
    "docstring": "Start trusting a particular key for given scope."
  },
  {
    "code": "def check_static_vars(self, node):\n        if self.static_vars == \"\" and hasattr(self, \"template\"):\n            self.static_vars = {\n                'upy_context': {\n                    'template_name': u\"{}/{}\".format(self.template.app_name, self.template.file_name)\n                }\n            }\n        elif hasattr(self, \"template\"):\n            self.static_vars = literal_eval(self.static_vars)\n            self.static_vars['upy_context']['template_name'] = u\"{}/{}\".format(\n                self.template.app_name, self.template.file_name\n            )\n        self.static_vars['upy_context']['NODE'] = node\n        self.static_vars['upy_context']['PAGE'] = self",
    "docstring": "This function check if a Page has static vars"
  },
  {
    "code": "def _waiting_expect(self):\n        if self._expect_sent is None:\n            if self.environ.get('HTTP_EXPECT', '').lower() == '100-continue':\n                return True\n            self._expect_sent = ''\n        return False",
    "docstring": "``True`` when the client is waiting for 100 Continue."
  },
  {
    "code": "def rename_categories(self, new_categories, inplace=False):\n        inplace = validate_bool_kwarg(inplace, 'inplace')\n        cat = self if inplace else self.copy()\n        if isinstance(new_categories, ABCSeries):\n            msg = (\"Treating Series 'new_categories' as a list-like and using \"\n                   \"the values. In a future version, 'rename_categories' will \"\n                   \"treat Series like a dictionary.\\n\"\n                   \"For dict-like, use 'new_categories.to_dict()'\\n\"\n                   \"For list-like, use 'new_categories.values'.\")\n            warn(msg, FutureWarning, stacklevel=2)\n            new_categories = list(new_categories)\n        if is_dict_like(new_categories):\n            cat.categories = [new_categories.get(item, item)\n                              for item in cat.categories]\n        elif callable(new_categories):\n            cat.categories = [new_categories(item) for item in cat.categories]\n        else:\n            cat.categories = new_categories\n        if not inplace:\n            return cat",
    "docstring": "Rename categories.\n\n        Parameters\n        ----------\n        new_categories : list-like, dict-like or callable\n\n           * list-like: all items must be unique and the number of items in\n             the new categories must match the existing number of categories.\n\n           * dict-like: specifies a mapping from\n             old categories to new. Categories not contained in the mapping\n             are passed through and extra categories in the mapping are\n             ignored.\n\n             .. versionadded:: 0.21.0\n\n           * callable : a callable that is called on all items in the old\n             categories and whose return values comprise the new categories.\n\n             .. versionadded:: 0.23.0\n\n           .. warning::\n\n              Currently, Series are considered list like. In a future version\n              of pandas they'll be considered dict-like.\n\n        inplace : bool, default False\n           Whether or not to rename the categories inplace or return a copy of\n           this categorical with renamed categories.\n\n        Returns\n        -------\n        cat : Categorical or None\n           With ``inplace=False``, the new categorical is returned.\n           With ``inplace=True``, there is no return value.\n\n        Raises\n        ------\n        ValueError\n            If new categories are list-like and do not have the same number of\n            items than the current categories or do not validate as categories\n\n        See Also\n        --------\n        reorder_categories\n        add_categories\n        remove_categories\n        remove_unused_categories\n        set_categories\n\n        Examples\n        --------\n        >>> c = pd.Categorical(['a', 'a', 'b'])\n        >>> c.rename_categories([0, 1])\n        [0, 0, 1]\n        Categories (2, int64): [0, 1]\n\n        For dict-like ``new_categories``, extra keys are ignored and\n        categories not in the dictionary are passed through\n\n        >>> c.rename_categories({'a': 'A', 'c': 'C'})\n        [A, A, b]\n        Categories (2, object): [A, b]\n\n        You may also provide a callable to create the new categories\n\n        >>> c.rename_categories(lambda x: x.upper())\n        [A, A, B]\n        Categories (2, object): [A, B]"
  },
  {
    "code": "def create_container(container_name, profile, **libcloud_kwargs):\n    conn = _get_driver(profile=profile)\n    libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs)\n    container = conn.create_container(container_name, **libcloud_kwargs)\n    return {\n        'name': container.name,\n        'extra': container.extra\n        }",
    "docstring": "Create a container in the cloud\n\n    :param container_name: Container name\n    :type  container_name: ``str``\n\n    :param profile: The profile key\n    :type  profile: ``str``\n\n    :param libcloud_kwargs: Extra arguments for the driver's create_container method\n    :type  libcloud_kwargs: ``dict``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion libcloud_storage.create_container MyFolder profile1"
  },
  {
    "code": "def _update_activities(self):\n        self._activities = self._activities_request()\n        _LOGGER.debug(\"Device Activities Response: %s\", self._activities)\n        if not self._activities:\n            self._activities = []\n        elif not isinstance(self._activities, (list, tuple)):\n            self._activities = [self._activities]\n        self._update_events()",
    "docstring": "Update stored activities and update caches as required."
  },
  {
    "code": "def XYZ_to_xyY(cobj, *args, **kwargs):\n    xyz_sum = cobj.xyz_x + cobj.xyz_y + cobj.xyz_z\n    if xyz_sum == 0.0:\n        xyy_x = 0.0\n        xyy_y = 0.0\n    else:\n        xyy_x = cobj.xyz_x / xyz_sum\n        xyy_y = cobj.xyz_y / xyz_sum\n    xyy_Y = cobj.xyz_y\n    return xyYColor(\n        xyy_x, xyy_y, xyy_Y, observer=cobj.observer, illuminant=cobj.illuminant)",
    "docstring": "Convert from XYZ to xyY."
  },
  {
    "code": "def sort_values(self, by=None, axis=0, ascending=True, inplace=False,\n                    kind='quicksort', na_position='last'):\n        raise NotImplementedError(\"sort_values has not been implemented \"\n                                  \"on Panel or Panel4D objects.\")",
    "docstring": "Sort by the values along either axis.\n\n        Parameters\n        ----------%(optional_by)s\n        axis : %(axes_single_arg)s, default 0\n             Axis to be sorted.\n        ascending : bool or list of bool, default True\n             Sort ascending vs. descending. Specify list for multiple sort\n             orders.  If this is a list of bools, must match the length of\n             the by.\n        inplace : bool, default False\n             If True, perform operation in-place.\n        kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'\n             Choice of sorting algorithm. See also ndarray.np.sort for more\n             information.  `mergesort` is the only stable algorithm. For\n             DataFrames, this option is only applied when sorting on a single\n             column or label.\n        na_position : {'first', 'last'}, default 'last'\n             Puts NaNs at the beginning if `first`; `last` puts NaNs at the\n             end.\n\n        Returns\n        -------\n        sorted_obj : DataFrame or None\n            DataFrame with sorted values if inplace=False, None otherwise.\n\n        Examples\n        --------\n        >>> df = pd.DataFrame({\n        ...     'col1': ['A', 'A', 'B', np.nan, 'D', 'C'],\n        ...     'col2': [2, 1, 9, 8, 7, 4],\n        ...     'col3': [0, 1, 9, 4, 2, 3],\n        ... })\n        >>> df\n            col1 col2 col3\n        0   A    2    0\n        1   A    1    1\n        2   B    9    9\n        3   NaN  8    4\n        4   D    7    2\n        5   C    4    3\n\n        Sort by col1\n\n        >>> df.sort_values(by=['col1'])\n            col1 col2 col3\n        0   A    2    0\n        1   A    1    1\n        2   B    9    9\n        5   C    4    3\n        4   D    7    2\n        3   NaN  8    4\n\n        Sort by multiple columns\n\n        >>> df.sort_values(by=['col1', 'col2'])\n            col1 col2 col3\n        1   A    1    1\n        0   A    2    0\n        2   B    9    9\n        5   C    4    3\n        4   D    7    2\n        3   NaN  8    4\n\n        Sort Descending\n\n        >>> df.sort_values(by='col1', ascending=False)\n            col1 col2 col3\n        4   D    7    2\n        5   C    4    3\n        2   B    9    9\n        0   A    2    0\n        1   A    1    1\n        3   NaN  8    4\n\n        Putting NAs first\n\n        >>> df.sort_values(by='col1', ascending=False, na_position='first')\n            col1 col2 col3\n        3   NaN  8    4\n        4   D    7    2\n        5   C    4    3\n        2   B    9    9\n        0   A    2    0\n        1   A    1    1"
  },
  {
    "code": "def parse_function(\n        name: str,\n        target: typing.Callable\n) -> typing.Union[None, dict]:\n    if not hasattr(target, '__code__'):\n        return None\n    lines = get_doc_entries(target)\n    docs = ' '.join(filter(lambda line: not line.startswith(':'), lines))\n    params = parse_params(target, lines)\n    returns = parse_returns(target, lines)\n    return dict(\n        name=getattr(target, '__name__'),\n        doc=docs,\n        params=params,\n        returns=returns\n    )",
    "docstring": "Parses the documentation for a function, which is specified by the name of\n    the function and the function itself.\n\n    :param name:\n        Name of the function to parse\n    :param target:\n        The function to parse into documentation\n    :return:\n        A dictionary containing documentation for the specified function, or\n        None if the target was not a function."
  },
  {
    "code": "def on_created(self, event):\n        for delegate in self.delegates:\n            if hasattr(delegate, \"on_created\"):\n                delegate.on_created(event)",
    "docstring": "On created method"
  },
  {
    "code": "def cmd_all(args):\n    for penlist in penStore.data:\n        puts(penlist)\n        with indent(4, '  -'):\n            for penfile in penStore.data[penlist]:\n                puts(penfile)",
    "docstring": "List everything recursively"
  },
  {
    "code": "def execPluginsDialog(self):\n        pluginsDialog = PluginsDialog(parent=self,\n                                inspectorRegistry=self.argosApplication.inspectorRegistry,\n                                rtiRegistry=self.argosApplication.rtiRegistry)\n        pluginsDialog.exec_()",
    "docstring": "Shows the plugins dialog with the registered plugins"
  },
  {
    "code": "def make_temp(suffix=\"\", prefix=\"tmp\", dir=None):\n    temporary = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)\n    os.close(temporary[0])\n    try:\n        yield temporary[1]\n    finally:\n        os.remove(temporary[1])",
    "docstring": "Creates a temporary file with a closed stream and deletes it when done.\n\n    :return: A contextmanager retrieving the file path."
  },
  {
    "code": "def split(text: str) -> List[str]:\n    return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]",
    "docstring": "Split a text into a list of tokens.\n\n    :param text: the text to split\n    :return: tokens"
  },
  {
    "code": "def asyncPipeStrreplace(context=None, _INPUT=None, conf=None, **kwargs):\n    splits = yield asyncGetSplits(_INPUT, conf['RULE'], **kwargs)\n    parsed = yield asyncDispatch(splits, *get_async_dispatch_funcs())\n    _OUTPUT = yield asyncStarMap(asyncParseResult, parsed)\n    returnValue(iter(_OUTPUT))",
    "docstring": "A string module that asynchronously replaces text. Loopable.\n\n    Parameters\n    ----------\n    context : pipe2py.Context object\n    _INPUT : twisted Deferred iterable of items or strings\n    conf : {\n        'RULE': [\n            {\n                'param': {'value': <match type: 1=first, 2=last, 3=every>},\n                'find': {'value': <text to find>},\n                'replace': {'value': <replacement>}\n            }\n        ]\n    }\n\n    Returns\n    -------\n    _OUTPUT : twisted.internet.defer.Deferred generator of replaced strings"
  },
  {
    "code": "def augment_pipeline(pl, head_pipe=None, tail_pipe=None):\n    for k, v in iteritems(pl):\n        if v and len(v) > 0:\n            if head_pipe and k != 'source':\n                v.insert(0, head_pipe)\n            if tail_pipe:\n                v.append(tail_pipe)",
    "docstring": "Augment the pipeline by adding a new pipe section to each stage that has one or more pipes. Can be used for debugging\n\n    :param pl:\n    :param DebugPipe:\n    :return:"
  },
  {
    "code": "def stringify(data):\n    if isinstance(data, dict):\n        for key, value in data.items():\n            data[key] = stringify(value)\n    elif isinstance(data, list):\n        return [stringify(item) for item in data]\n    else:\n        return smart_text(data)\n    return data",
    "docstring": "Turns all dictionary values into strings"
  },
  {
    "code": "def build_header(dtype):\n    header = _build_header(dtype, ())\n    h = []\n    for col in header:\n        name = '~'.join(col[:-2])\n        numpytype = col[-2]\n        shape = col[-1]\n        coldescr = name\n        if numpytype != 'float32' and not numpytype.startswith('|S'):\n            coldescr += ':' + numpytype\n        if shape:\n            coldescr += ':' + ':'.join(map(str, shape))\n        h.append(coldescr)\n    return h",
    "docstring": "Convert a numpy nested dtype into a list of strings suitable as header\n    of csv file.\n\n    >>> imt_dt = numpy.dtype([('PGA', numpy.float32, 3),\n    ...                       ('PGV', numpy.float32, 4)])\n    >>> build_header(imt_dt)\n    ['PGA:3', 'PGV:4']\n    >>> gmf_dt = numpy.dtype([('A', imt_dt), ('B', imt_dt),\n    ...                       ('idx', numpy.uint32)])\n    >>> build_header(gmf_dt)\n    ['A~PGA:3', 'A~PGV:4', 'B~PGA:3', 'B~PGV:4', 'idx:uint32']"
  },
  {
    "code": "def run(self):\n        try:\n            self.loader.find_and_load_step_definitions()\n        except StepLoadingError, e:\n            print \"Error loading step definitions:\\n\", e\n            return\n        results = []\n        if self.explicit_features:\n            features_files = self.explicit_features\n        else:\n            features_files = self.loader.find_feature_files()\n        if self.random:\n            random.shuffle(features_files)\n        if not features_files:\n            self.output.print_no_features_found(self.loader.base_dir)\n            return\n        processes = Pool(processes=self.parallelization)\n        test_results_it = processes.imap_unordered(\n            worker_process, [(self, filename) for filename in features_files]\n        )\n        all_total = ParallelTotalResult()\n        for result in test_results_it:\n            all_total += result['total']\n            sys.stdout.write(result['stdout'])\n            sys.stderr.write(result['stderr'])\n        return all_total",
    "docstring": "Find and load step definitions, and them find and load\n        features under `base_path` specified on constructor"
  },
  {
    "code": "def merge(self, dct=None, **kwargs):\n        if dct is None:\n            dct = {}\n        if kwargs:\n            dct.update(**kwargs)\n        for key, value in dct.items():\n            if all((\n                    isinstance(value, dict),\n                    isinstance(self.get(key), Configuration),\n                    getattr(self.get(key), \"__merge__\", True),\n            )):\n                self[key].merge(value)\n            elif isinstance(value, list) and isinstance(self.get(key), list):\n                self[key] += value\n            else:\n                self[key] = value",
    "docstring": "Recursively merge a dictionary or kwargs into the current dict."
  },
  {
    "code": "def to_header(self, timestamp=None):\n        rv = [(\"sentry_key\", self.public_key), (\"sentry_version\", self.version)]\n        if timestamp is not None:\n            rv.append((\"sentry_timestamp\", str(to_timestamp(timestamp))))\n        if self.client is not None:\n            rv.append((\"sentry_client\", self.client))\n        if self.secret_key is not None:\n            rv.append((\"sentry_secret\", self.secret_key))\n        return u\"Sentry \" + u\", \".join(\"%s=%s\" % (key, value) for key, value in rv)",
    "docstring": "Returns the auth header a string."
  },
  {
    "code": "def save_form(self, request, form, change):\n        obj = form.save(commit=False)\n        if obj.user_id is None:\n            obj.user = request.user\n        return super(OwnableAdmin, self).save_form(request, form, change)",
    "docstring": "Set the object's owner as the logged in user."
  },
  {
    "code": "def unlock(arguments):\n    import redis\n    u = coil.utils.ask(\"Redis URL\", \"redis://localhost:6379/0\")\n    db = redis.StrictRedis.from_url(u)\n    db.set('site:lock', 0)\n    print(\"Database unlocked.\")\n    return 0",
    "docstring": "Unlock the database."
  },
  {
    "code": "async def open(self) -> 'Tails':\n        LOGGER.debug('Tails.open >>>')\n        self._reader_handle = await blob_storage.open_reader('default', self._tails_config_json)\n        LOGGER.debug('Tails.open <<<')\n        return self",
    "docstring": "Open reader handle and return current object.\n\n        :return: current object"
  },
  {
    "code": "def get_observatory_status(self, observatory_id, status_time=None):\n        if status_time is None:\n            response = requests.get(\n                self.base_url + '/obstory/{0}/statusdict'.format(observatory_id))\n        else:\n            response = requests.get(\n                self.base_url + '/obstory/{0}/statusdict/{1}'.format(observatory_id, str(status_time)))\n        if response.status_code == 200:\n            d = safe_load(response.text)\n            if 'status' in d:\n                return d['status']\n        return None",
    "docstring": "Get details of the specified camera's status\n\n        :param string observatory_id:\n            a observatory ID, as returned by list_observatories()\n        :param float status_time:\n            optional, if specified attempts to get the status for the given camera at a particular point in time\n            specified as a datetime instance. This is useful if you want to retrieve the status of the camera at the\n            time a given event or file was produced. If this is None or not specified the time is 'now'.\n        :return:\n            a dictionary, or None if there was either no observatory found."
  },
  {
    "code": "def _determine_current_dimension_size(self, dim_name, max_size):\n        if self.dimensions[dim_name] is not None:\n            return max_size\n        def _find_dim(h5group, dim):\n            if dim not in h5group:\n                return _find_dim(h5group.parent, dim)\n            return h5group[dim]\n        dim_variable = _find_dim(self._h5group, dim_name)\n        if \"REFERENCE_LIST\" not in dim_variable.attrs:\n            return max_size\n        root = self._h5group[\"/\"]\n        for ref, _ in dim_variable.attrs[\"REFERENCE_LIST\"]:\n            var = root[ref]\n            for i, var_d in enumerate(var.dims):\n                name = _name_from_dimension(var_d)\n                if name == dim_name:\n                    max_size = max(var.shape[i], max_size)\n        return max_size",
    "docstring": "Helper method to determine the current size of a dimension."
  },
  {
    "code": "def token(self):\n        \" Get token when needed.\"\n        if hasattr(self, '_token'):\n            return getattr(self, '_token')\n        data = json.dumps({'customer_name': self.customer,\n                           'user_name': self.username,\n                           'password': self.password})\n        response = requests.post(\n            'https://api2.dynect.net/REST/Session/', data=data,\n            headers={'Content-Type': 'application/json'})\n        content = json.loads(response.content)\n        if response.status_code != 200:\n            if self.check_error(content, 'failure', 'INVALID_DATA'):\n                raise self.CredentialsError(\n                    self.response_message(content, 'ERROR'))\n            raise self.Failure(self.response_message(content, 'ERROR'),\n                               'Unhandled failure')\n        if 'data' in content and 'token' in content['data']:\n            token = content['data']['token']\n        else:\n            raise self.AuthenticationError(response)\n        setattr(self, '_token', token)\n        return token",
    "docstring": "Get token when needed."
  },
  {
    "code": "def ProduceEventTag(self, event_tag):\n    self._storage_writer.AddEventTag(event_tag)\n    self.number_of_produced_event_tags += 1\n    self.last_activity_timestamp = time.time()",
    "docstring": "Produces an event tag.\n\n    Args:\n      event_tag (EventTag): event tag."
  },
  {
    "code": "def t_escaped_BACKSPACE_CHAR(self, t):\n        r'\\x62'\n        t.lexer.pop_state()\n        t.value = unichr(0x0008)\n        return t",
    "docstring": "r'\\x62"
  },
  {
    "code": "def all(self, array, role = None):\n        return self.reduce(array, reducer = np.logical_and, neutral_element = True, role = role)",
    "docstring": "Return ``True`` if ``array`` is ``True`` for all members of the entity.\n\n            ``array`` must have the dimension of the number of persons in the simulation\n\n            If ``role`` is provided, only the entity member with the given role are taken into account.\n\n            Example:\n\n            >>> salaries = household.members('salary', '2018-01')  # e.g. [2000, 1500, 0, 0, 0]\n            >>> household.all(salaries >= 1800)\n            >>> array([False])"
  },
  {
    "code": "def create_source(self, datapusher=True):\n        task.create_source(self.target, self._preload_image(), datapusher)",
    "docstring": "Populate ckan directory from preloaded image and copy\n        who.ini and schema.xml info conf directory"
  },
  {
    "code": "def create_stream_subscription(self, stream, on_data, timeout=60):\n        options = rest_pb2.StreamSubscribeRequest()\n        options.stream = stream\n        manager = WebSocketSubscriptionManager(\n            self._client, resource='stream', options=options)\n        subscription = WebSocketSubscriptionFuture(manager)\n        wrapped_callback = functools.partial(\n            _wrap_callback_parse_stream_data, subscription, on_data)\n        manager.open(wrapped_callback, instance=self._instance)\n        subscription.reply(timeout=timeout)\n        return subscription",
    "docstring": "Create a new stream subscription.\n\n        :param str stream: The name of the stream.\n        :param on_data: Function that gets called with  :class:`.StreamData`\n                        updates.\n        :param float timeout: The amount of seconds to wait for the request\n                              to complete.\n        :return: Future that can be used to manage the background websocket\n                 subscription\n        :rtype: .WebSocketSubscriptionFuture"
  },
  {
    "code": "def subcommand(self, command_name=None):\n        def wrapper(decorated):\n            cmd_name = command_name or decorated.__name__\n            subparser = self.subparsers.add_parser(cmd_name,\n                                                   description=decorated.__doc__)\n            for args, kwargs in describe_arguments(decorated):\n                subparser.add_argument(*args, **kwargs)\n            subparser.set_defaults(func=decorated)\n            return decorated\n        return wrapper",
    "docstring": "Decorate a function as a subcommand. Use its arguments as the\n        command-line arguments"
  },
  {
    "code": "async def handle_client_get_queue(self, client_addr, _: ClientGetQueue):\n        jobs_running = list()\n        for backend_job_id, content in self._job_running.items():\n            jobs_running.append((content[1].job_id, backend_job_id[0] == client_addr, self._registered_agents[content[0]],\n                                 content[1].course_id+\"/\"+content[1].task_id,\n                                 content[1].launcher, int(content[2]), int(content[2])+content[1].time_limit))\n        jobs_waiting = list()\n        for job_client_addr, msg in self._waiting_jobs.items():\n            if isinstance(msg, ClientNewJob):\n                jobs_waiting.append((msg.job_id, job_client_addr[0] == client_addr, msg.course_id+\"/\"+msg.task_id, msg.launcher,\n                                     msg.time_limit))\n        await ZMQUtils.send_with_addr(self._client_socket, client_addr, BackendGetQueue(jobs_running, jobs_waiting))",
    "docstring": "Handles a ClientGetQueue message. Send back info about the job queue"
  },
  {
    "code": "def is_serializable(obj):\n    if inspect.isclass(obj):\n      return Serializable.is_serializable_type(obj)\n    return isinstance(obj, Serializable) or hasattr(obj, '_asdict')",
    "docstring": "Return `True` if the given object conforms to the Serializable protocol.\n\n    :rtype: bool"
  },
  {
    "code": "def create_cells(headers, schema_fields, values=None, row_number=None):\n    fillvalue = '_fillvalue'\n    is_header_row = (values is None)\n    cells = []\n    iterator = zip_longest(headers, schema_fields, values or [], fillvalue=fillvalue)\n    for column_number, (header, field, value) in enumerate(iterator, start=1):\n        if header == fillvalue:\n            header = None\n        elif is_header_row:\n            value = header\n        if field == fillvalue:\n            field = None\n        if value == fillvalue:\n            value = None\n        elif value is None:\n            value = ''\n        cell = create_cell(header, value, field, column_number, row_number)\n        cells.append(cell)\n    return cells",
    "docstring": "Create list of cells from headers, fields and values.\n\n    Args:\n        headers (List[str]): The headers values.\n        schema_fields (List[tableschema.field.Field]): The tableschema\n            fields.\n        values (List[Any], optional): The cells values. If not specified,\n            the created cells will have the same values as their\n            corresponding headers. This is useful for specifying headers\n            cells.\n            If the list has any `None` values, as is the case on empty\n            cells, the resulting Cell will have an empty string value. If\n            the `values` list has a different length than the `headers`,\n            the resulting Cell will have value `None`.\n        row_number (int, optional): The row number.\n\n    Returns:\n        List[dict]: List of cells."
  },
  {
    "code": "def parameters(self):\n        parameters = []\n        for k, v in self.__dict__.items():\n            if k.startswith(\"_\"):\n                continue\n            is_function = False\n            is_set = False\n            if callable(v):\n                value = pickle.dumps(func_dump(v))\n                is_function = True\n            elif isinstance(v, set):\n                value = list(v)\n                is_set = True\n            else:\n                value = v\n            parameters.append(dict(\n                key=k,\n                value=value,\n                is_function=is_function,\n                is_set=is_set\n            ))\n        return parameters",
    "docstring": "Get the tool parameters\n\n        :return: The tool parameters along with additional information (whether they are functions or sets)"
  },
  {
    "code": "def downloadArchiveAction(self, request, queryset):\n        output = io.BytesIO()\n        z = zipfile.ZipFile(output, 'w')\n        for sub in queryset:\n            sub.add_to_zipfile(z)\n        z.close()\n        output.seek(0)\n        response = HttpResponse(\n            output, content_type=\"application/x-zip-compressed\")\n        response['Content-Disposition'] = 'attachment; filename=submissions.zip'\n        return response",
    "docstring": "Download selected submissions as archive, for targeted correction."
  },
  {
    "code": "def _add_missing_jwt_permission_classes(self, view_class):\n        view_permissions = list(getattr(view_class, 'permission_classes', []))\n        permission_classes = []\n        classes_to_add = []\n        while view_permissions:\n            permission = view_permissions.pop()\n            if not hasattr(permission, 'perms_or_conds'):\n                permission_classes.append(permission)\n            else:\n                for child in getattr(permission, 'perms_or_conds', []):\n                    view_permissions.append(child)\n        for perm_class in self._required_permission_classes:\n            if not self._includes_base_class(permission_classes, perm_class):\n                log.warning(\n                    u\"The view %s allows Jwt Authentication but needs to include the %s permission class (adding it for you)\",\n                    view_class.__name__,\n                    perm_class.__name__,\n                )\n                classes_to_add.append(perm_class)\n        if classes_to_add:\n            view_class.permission_classes += tuple(classes_to_add)",
    "docstring": "Adds permissions classes that should exist for Jwt based authentication,\n        if needed."
  },
  {
    "code": "def show_all_categories(call=None):\n    if call == 'action':\n        raise SaltCloudSystemExit(\n            'The show_all_categories function must be called with -f or --function.'\n        )\n    conn = get_conn(service='SoftLayer_Product_Package')\n    categories = []\n    for category in conn.getCategories(id=50):\n        categories.append(category['categoryCode'])\n    return {'category_codes': categories}",
    "docstring": "Return a dict of all available categories on the cloud provider.\n\n    .. versionadded:: 2016.3.0"
  },
  {
    "code": "def batch_update(self, values, w=1):\n        for x in values:\n            self.update(x, w)\n        self.compress()\n        return",
    "docstring": "Update the t-digest with an iterable of values. This assumes all points have the\n        same weight."
  },
  {
    "code": "def _extract_header(time_series):\n    return TimeSeries(\n        metric=time_series.metric,\n        resource=time_series.resource,\n        metric_kind=time_series.metric_kind,\n        value_type=time_series.value_type,\n    )",
    "docstring": "Return a copy of time_series with the points removed."
  },
  {
    "code": "def validate_wrap(self, value):\n        if not isinstance(value, self.type):\n            self._fail_validation_type(value, self.type)",
    "docstring": "Checks that ``value`` is an instance of ``DocumentField.type``.\n            if it is, then validation on its fields has already been done and\n            no further validation is needed."
  },
  {
    "code": "def _apply_memory_config(config_spec, memory):\n    log.trace('Configuring virtual machine memory '\n              'settings memory=%s', memory)\n    if 'size' in memory and 'unit' in memory:\n        try:\n            if memory['unit'].lower() == 'kb':\n                memory_mb = memory['size'] / 1024\n            elif memory['unit'].lower() == 'mb':\n                memory_mb = memory['size']\n            elif memory['unit'].lower() == 'gb':\n                memory_mb = int(float(memory['size']) * 1024)\n        except (TypeError, ValueError):\n            memory_mb = int(memory['size'])\n        config_spec.memoryMB = memory_mb\n    if 'reservation_max' in memory:\n        config_spec.memoryReservationLockedToMax = memory['reservation_max']\n    if 'hotadd' in memory:\n        config_spec.memoryHotAddEnabled = memory['hotadd']",
    "docstring": "Sets memory size to the given value\n\n    config_spec\n        vm.ConfigSpec object\n\n    memory\n        Memory size and unit"
  },
  {
    "code": "def make_sequence(content, error=None, version=None, mode=None, mask=None,\n                  encoding=None, boost_error=True, symbol_count=None):\n    return QRCodeSequence(map(QRCode,\n                              encoder.encode_sequence(content, error=error,\n                                                      version=version,\n                                                      mode=mode, mask=mask,\n                                                      encoding=encoding,\n                                                      boost_error=boost_error,\n                                                      symbol_count=symbol_count)))",
    "docstring": "\\\n    Creates a sequence of QR Codes.\n\n    If the content fits into one QR Code and neither ``version`` nor\n    ``symbol_count`` is provided, this function may return a sequence with\n    one QR Code which does not use the Structured Append mode. Otherwise a\n    sequence of 2 .. n  (max. n = 16) QR Codes is returned which use the\n    Structured Append mode.\n\n    The Structured Append mode allows to split the content over a number\n    (max. 16) QR Codes.\n\n    The Structured Append mode isn't available for Micro QR Codes, therefor\n    the returned sequence contains QR Codes, only.\n\n    Since this function returns an iterable object, it may be used as follows:\n\n    .. code-block:: python\n\n        for i, qrcode in enumerate(segno.make_sequence(data, symbol_count=2)):\n             qrcode.save('seq-%d.svg' % i, scale=10, color='darkblue')\n\n    The returned number of QR Codes is determined by the `version` or\n    `symbol_count` parameter\n\n    See :py:func:`make` for a description of the other parameters.\n\n    :param int symbol_count: Number of symbols.\n    :rtype: QRCodeSequence"
  },
  {
    "code": "def to_networkx(cyjs, directed=True):\n    if directed:\n        g = nx.MultiDiGraph()\n    else:\n        g = nx.MultiGraph()\n    network_data = cyjs[DATA]\n    if network_data is not None:\n        for key in network_data.keys():\n            g.graph[key] = network_data[key]\n    nodes = cyjs[ELEMENTS][NODES]\n    edges = cyjs[ELEMENTS][EDGES]\n    for node in nodes:\n        data = node[DATA]\n        g.add_node(data[ID], attr_dict=data)\n    for edge in edges:\n        data = edge[DATA]\n        source = data[SOURCE]\n        target = data[TARGET]\n        g.add_edge(source, target, attr_dict=data)\n    return g",
    "docstring": "Convert Cytoscape.js-style JSON object into NetworkX object.\n\n    By default, data will be handles as a directed graph."
  },
  {
    "code": "def cli(obj, environment, service, resource, event, group, tags, customer, start, duration, text, delete):\n    client = obj['client']\n    if delete:\n        client.delete_blackout(delete)\n    else:\n        if not environment:\n            raise click.UsageError('Missing option \"--environment\" / \"-E\".')\n        try:\n            blackout = client.create_blackout(\n                environment=environment,\n                service=service,\n                resource=resource,\n                event=event,\n                group=group,\n                tags=tags,\n                customer=customer,\n                start=start,\n                duration=duration,\n                text=text\n            )\n        except Exception as e:\n            click.echo('ERROR: {}'.format(e))\n            sys.exit(1)\n        click.echo(blackout.id)",
    "docstring": "Suppress alerts for specified duration based on alert attributes."
  },
  {
    "code": "def head(self, uuid):\n        url = \"%(base)s/%(uuid)s\" % {\n            'base': self.local_base_url,\n            'uuid': uuid\n        }\n        return self.core.head(url)",
    "docstring": "Get one thread."
  },
  {
    "code": "def ReplaceTrigger(self, trigger_link, trigger, options=None):\n        if options is None:\n            options = {}\n        CosmosClient.__ValidateResource(trigger)\n        trigger = trigger.copy()\n        if trigger.get('serverScript'):\n            trigger['body'] = str(trigger['serverScript'])\n        elif trigger.get('body'):\n            trigger['body'] = str(trigger['body'])\n        path = base.GetPathFromLink(trigger_link)\n        trigger_id = base.GetResourceIdOrFullNameFromLink(trigger_link)\n        return self.Replace(trigger,\n                            path,\n                            'triggers',\n                            trigger_id,\n                            None,\n                            options)",
    "docstring": "Replaces a trigger and returns it.\n\n        :param str trigger_link:\n            The link to the trigger.\n        :param dict trigger:\n        :param dict options:\n            The request options for the request.\n\n        :return:\n            The replaced Trigger.\n        :rtype:\n            dict"
  },
  {
    "code": "def remove_udp_port(self, port):\n        if port in self._used_udp_ports:\n            self._used_udp_ports.remove(port)",
    "docstring": "Removes an associated UDP port number from this project.\n\n        :param port: UDP port number"
  },
  {
    "code": "def deleteEdge(self, edge, waitForSync = False) :\n        url = \"%s/edge/%s\" % (self.URL, edge._id)\n        r = self.connection.session.delete(url, params = {'waitForSync' : waitForSync})\n        if r.status_code == 200 or r.status_code == 202 :\n            return True\n        raise DeletionError(\"Unable to delete edge, %s\" % edge._id, r.json())",
    "docstring": "removes an edge from the graph"
  },
  {
    "code": "def to_file_object(self, name, out_dir):\n        make_analysis_dir(out_dir)\n        file_ref = File('ALL', name, self.get_times_covered_by_files(),\n                             extension='.pkl', directory=out_dir)\n        self.dump(file_ref.storage_path)\n        return file_ref",
    "docstring": "Dump to a pickle file and return an File object reference of this list\n\n        Parameters\n        ----------\n        name : str\n            An identifier of this file. Needs to be unique.\n        out_dir : path\n            path to place this file\n\n        Returns\n        -------\n        file : AhopeFile"
  },
  {
    "code": "def get_closest_points(self, max_distance=None, origin_index=0, origin_raw=None):\n        if not self.dict_response['distance']['value']:\n            self.get_distance_values()\n        if origin_raw:\n            origin = copy.deepcopy(self.dict_response['distance']['value'][origin_raw])\n        else:\n            origin = copy.deepcopy(self.dict_response['distance']['value'][self.origins[origin_index]])\n        tmp_origin = copy.deepcopy(origin)\n        if max_distance is not None:\n            for k, v in tmp_origin.iteritems():\n                if v > max_distance or v == 'ZERO_RESULTS':\n                    del(origin[k])\n        return origin",
    "docstring": "Get closest points to a given origin. Returns a list of 2 element tuples where first element is the destination and the second is the distance."
  },
  {
    "code": "def set_power_state(self, is_on, bulb=ALL_BULBS, timeout=None):\n        with _blocking(self.lock, self.power_state, self.light_state_event,\n                       timeout):\n            self.send(REQ_SET_POWER_STATE,\n                      bulb, '2s', '\\x00\\x01' if is_on else '\\x00\\x00')\n            self.send(REQ_GET_LIGHT_STATE, ALL_BULBS, '')\n        return self.power_state",
    "docstring": "Sets the power state of one or more bulbs."
  },
  {
    "code": "def delete(self, ids):\n        url = build_uri_with_ids('api/v3/object-group-perm-general/%s/', ids)\n        return super(ApiObjectGroupPermissionGeneral, self).delete(url)",
    "docstring": "Method to delete object group permissions general by their ids\n\n        :param ids: Identifiers of object group permissions general\n        :return: None"
  },
  {
    "code": "def get_manager_cmd(self):\n        cmd = os.path.abspath(os.path.join(os.path.dirname(__file__), \"server\", \"notebook_daemon.py\"))\n        assert os.path.exists(cmd)\n        return cmd",
    "docstring": "Get our daemon script path."
  },
  {
    "code": "def _flatten_mesh(self, Xs, term):\n        n = Xs[0].size\n        if self.terms[term].istensor:\n            terms = self.terms[term]\n        else:\n            terms = [self.terms[term]]\n        X = np.zeros((n, self.statistics_['m_features']))\n        for term_, x in zip(terms, Xs):\n            X[:, term_.feature] = x.ravel()\n        return X",
    "docstring": "flatten the mesh and distribute into a feature matrix"
  },
  {
    "code": "def create_room(self, alias=None, is_public=False, invitees=None):\n        response = self.api.create_room(alias=alias,\n                                        is_public=is_public,\n                                        invitees=invitees)\n        return self._mkroom(response[\"room_id\"])",
    "docstring": "Create a new room on the homeserver.\n\n        Args:\n            alias (str): The canonical_alias of the room.\n            is_public (bool):  The public/private visibility of the room.\n            invitees (str[]): A set of user ids to invite into the room.\n\n        Returns:\n            Room\n\n        Raises:\n            MatrixRequestError"
  },
  {
    "code": "def get_datarect(self):\n        x1, y1, x2, y2 = self._org_x1, self._org_y1, self._org_x2, self._org_y2\n        return (x1, y1, x2, y2)",
    "docstring": "Get the approximate bounding box of the displayed image.\n\n        Returns\n        -------\n        rect : tuple\n            Bounding box in data coordinates in the form of\n            ``(x1, y1, x2, y2)``."
  },
  {
    "code": "def findLinksRel(link_attrs_list, target_rel):\n    matchesTarget = lambda attrs: linkHasRel(attrs, target_rel)\n    return list(filter(matchesTarget, link_attrs_list))",
    "docstring": "Filter the list of link attributes on whether it has target_rel\n    as a relationship."
  },
  {
    "code": "def _parse_node_data(self, data):\n        data = data or ''\n        if self.numbermode == 'basic':\n            return self._try_parse_basic_number(data)\n        elif self.numbermode == 'decimal':\n            return self._try_parse_decimal(data)\n        else:\n            return data",
    "docstring": "Parse the value of a node. Override to provide your own parsing."
  },
  {
    "code": "def get_avatar_upload_to(self, filename):\n        dummy, ext = os.path.splitext(filename)\n        return os.path.join(\n            machina_settings.PROFILE_AVATAR_UPLOAD_TO,\n            '{id}{ext}'.format(id=str(uuid.uuid4()).replace('-', ''), ext=ext),\n        )",
    "docstring": "Returns the path to upload the associated avatar to."
  },
  {
    "code": "def add(self, spec):\n        for limit in spec.limit_to:\n            if limit not in self.limit_to:\n                self.limit_to.append(limit)",
    "docstring": "Add limitations of given spec to self's.\n\n        Args:\n            spec (PackageSpec): another spec."
  },
  {
    "code": "def _do_cross_validation(self, clf, data, task):\n        time1 = time.time()\n        if isinstance(clf, sklearn.svm.SVC) and clf.kernel == 'precomputed'\\\n                and self.use_multiprocessing:\n            inlist = [(clf, i + task[0], self.num_folds, data[i, :, :],\n                       self.labels) for i in range(task[1])]\n            with multiprocessing.Pool(self.process_num) as pool:\n                results = list(pool.starmap(_cross_validation_for_one_voxel,\n                                            inlist))\n        else:\n            results = []\n            for i in range(task[1]):\n                result = _cross_validation_for_one_voxel(clf, i + task[0],\n                                                         self.num_folds,\n                                                         data[i, :, :],\n                                                         self.labels)\n                results.append(result)\n        time2 = time.time()\n        logger.debug(\n            'cross validation for %d voxels, takes %.2f s' %\n            (task[1], (time2 - time1))\n        )\n        return results",
    "docstring": "Run voxelwise cross validation based on correlation vectors.\n\n        clf: classification function\n            the classifier to be used in cross validation\n        data: 3D numpy array\n            If using sklearn.svm.SVC with precomputed kernel,\n            it is in shape [num_processed_voxels, num_epochs, num_epochs];\n            otherwise it is the input argument corr,\n            in shape [num_processed_voxels, num_epochs, num_voxels]\n        task: tuple (start_voxel_id, num_processed_voxels)\n            depicting the voxels assigned to compute\n\n        Returns\n        -------\n        results: list of tuple (voxel_id, accuracy)\n            the accuracy numbers of all voxels, in accuracy descending order\n            the length of array equals the number of assigned voxels"
  },
  {
    "code": "def read_vocab_file(file_path):\n  with file_io.FileIO(file_path, 'r') as f:\n    vocab_pd = pd.read_csv(\n        f,\n        header=None,\n        names=['vocab', 'count'],\n        dtype=str,\n        na_filter=False)\n  vocab = vocab_pd['vocab'].tolist()\n  ex_count = vocab_pd['count'].astype(int).tolist()\n  return vocab, ex_count",
    "docstring": "Reads a vocab file to memeory.\n\n  Args:\n    file_path: Each line of the vocab is in the form \"token,example_count\"\n\n  Returns:\n    Two lists, one for the vocab, and one for just the example counts."
  },
  {
    "code": "def load_minters_entry_point_group(self, entry_point_group):\n        for ep in pkg_resources.iter_entry_points(group=entry_point_group):\n            self.register_minter(ep.name, ep.load())",
    "docstring": "Load minters from an entry point group.\n\n        :param entry_point_group: The entrypoint group."
  },
  {
    "code": "def addTextErr(self, text):\n        self._currentColor = self._red\n        self.addText(text)",
    "docstring": "add red text"
  },
  {
    "code": "def _at(self, t):\n        rITRF, vITRF, error = self.ITRF_position_velocity_error(t)\n        rGCRS, vGCRS = ITRF_to_GCRS2(t, rITRF, vITRF)\n        return rGCRS, vGCRS, rGCRS, error",
    "docstring": "Compute this satellite's GCRS position and velocity at time `t`."
  },
  {
    "code": "def genTopLevelDirCMakeListsFile(self, working_path, subdirs, files, cfg):\n        fnameOut = os.path.join(working_path, 'CMakeLists.txt')\n        template = self.envJinja.get_template(self.TOP_LEVEL_CMAKELISTS_JINJA2_TEMPLATE)\n        fcontent = template.render({'project_name':os.path.basename(os.path.abspath(working_path)),\n                                    'subdirs': subdirs,\n                                    'files': files,\n                                    'cfg': cfg})\n        with open(fnameOut, 'w') as f:\n            f.write(fcontent)\n        return fnameOut",
    "docstring": "Generate top level CMakeLists.txt.\n\n        :param working_path: current working directory\n        :param subdirs: a list of subdirectories of current working directory.\n        :param files: a list of files in current working directory.\n        :return: the full path name of generated CMakeLists.txt."
  },
  {
    "code": "def _dirint_coeffs(times, kt_prime, solar_zenith, w, delta_kt_prime):\n    kt_prime_bin, zenith_bin, w_bin, delta_kt_prime_bin = \\\n        _dirint_bins(times, kt_prime, solar_zenith, w, delta_kt_prime)\n    coeffs = _get_dirint_coeffs()\n    dirint_coeffs = coeffs[kt_prime_bin-1, zenith_bin-1,\n                           delta_kt_prime_bin-1, w_bin-1]\n    dirint_coeffs = np.where((kt_prime_bin == 0) | (zenith_bin == 0) |\n                             (w_bin == 0) | (delta_kt_prime_bin == 0),\n                             np.nan, dirint_coeffs)\n    return dirint_coeffs",
    "docstring": "Determine the DISC to DIRINT multiplier `dirint_coeffs`.\n\n    dni = disc_out['dni'] * dirint_coeffs\n\n    Parameters\n    ----------\n    times : pd.DatetimeIndex\n    kt_prime : Zenith-independent clearness index\n    solar_zenith : Solar zenith angle\n    w : precipitable water estimated from surface dew-point temperature\n    delta_kt_prime : stability index\n\n    Returns\n    -------\n    dirint_coeffs : array-like"
  },
  {
    "code": "def success(self, cmd, desc=''):\n        return self._label_desc(cmd, desc, self.success_color)",
    "docstring": "Style for a success message."
  },
  {
    "code": "def get_instance_assignment(self, ctx):\n        if ctx is None:\n            return None\n        visitor = ExprVisitor(self.compiler)\n        expr = visitor.visit(ctx.expr())\n        expr = expressions.AssignmentCast(self.compiler.env, SourceRef.from_antlr(ctx.op), expr, int)\n        expr.predict_type()\n        return expr",
    "docstring": "Gets the integer expression in any of the four instance assignment\n        operators ('=' '@' '+=' '%=')"
  },
  {
    "code": "def download_as_string(self, client=None, start=None, end=None):\n        string_buffer = BytesIO()\n        self.download_to_file(string_buffer, client=client, start=start, end=end)\n        return string_buffer.getvalue()",
    "docstring": "Download the contents of this blob as a string.\n\n        If :attr:`user_project` is set on the bucket, bills the API request\n        to that project.\n\n        :type client: :class:`~google.cloud.storage.client.Client` or\n                      ``NoneType``\n        :param client: Optional. The client to use.  If not passed, falls back\n                       to the ``client`` stored on the blob's bucket.\n\n        :type start: int\n        :param start: Optional, the first byte in a range to be downloaded.\n\n        :type end: int\n        :param end: Optional, The last byte in a range to be downloaded.\n\n        :rtype: bytes\n        :returns: The data stored in this blob.\n        :raises: :class:`google.cloud.exceptions.NotFound`"
  },
  {
    "code": "def get_state_machine_selection(self):\n        if self._selected_sm_model:\n            return self._selected_sm_model.selection, self._selected_sm_model.selection.states\n        else:\n            return None, set()",
    "docstring": "Getter state machine selection\n\n        :return: selection object, filtered set of selected states\n        :rtype: rafcon.gui.selection.Selection, set"
  },
  {
    "code": "def get_title(self):\n        try:\n            return extract_literal(self.meta_kwargs['title'])\n        except KeyError:\n            slot = self.get_slot()\n            if slot is not None:\n                return slot.replace('_', ' ').title()\n            return None",
    "docstring": "Return the string literal that is used in the template.\n        The title is used in the admin screens."
  },
  {
    "code": "def open(\n        bucket_id,\n        key_id,\n        mode,\n        buffer_size=DEFAULT_BUFFER_SIZE,\n        min_part_size=DEFAULT_MIN_PART_SIZE,\n        session=None,\n        resource_kwargs=None,\n        multipart_upload_kwargs=None,\n        ):\n    logger.debug('%r', locals())\n    if mode not in MODES:\n        raise NotImplementedError('bad mode: %r expected one of %r' % (mode, MODES))\n    if resource_kwargs is None:\n        resource_kwargs = {}\n    if multipart_upload_kwargs is None:\n        multipart_upload_kwargs = {}\n    if mode == READ_BINARY:\n        fileobj = SeekableBufferedInputBase(\n            bucket_id,\n            key_id,\n            buffer_size=buffer_size,\n            session=session,\n            resource_kwargs=resource_kwargs,\n        )\n    elif mode == WRITE_BINARY:\n        fileobj = BufferedOutputBase(\n            bucket_id,\n            key_id,\n            min_part_size=min_part_size,\n            session=session,\n            multipart_upload_kwargs=multipart_upload_kwargs,\n            resource_kwargs=resource_kwargs,\n        )\n    else:\n        assert False, 'unexpected mode: %r' % mode\n    return fileobj",
    "docstring": "Open an S3 object for reading or writing.\n\n    Parameters\n    ----------\n    bucket_id: str\n        The name of the bucket this object resides in.\n    key_id: str\n        The name of the key within the bucket.\n    mode: str\n        The mode for opening the object.  Must be either \"rb\" or \"wb\".\n    buffer_size: int, optional\n        The buffer size to use when performing I/O.\n    min_part_size: int, optional\n        The minimum part size for multipart uploads.  For writing only.\n    session: object, optional\n        The S3 session to use when working with boto3.\n    resource_kwargs: dict, optional\n        Keyword arguments to use when accessing the S3 resource for reading or writing.\n    multipart_upload_kwargs: dict, optional\n        Additional parameters to pass to boto3's initiate_multipart_upload function.\n        For writing only."
  },
  {
    "code": "def nl_pad(self, value):\n        self.bytearray[self._get_slicers(1)] = bytearray(c_ushort(value or 0))",
    "docstring": "Pad setter."
  },
  {
    "code": "def log(self, level, msg=None, *args, **kwargs):\n        return self._log(level, msg, args, kwargs)",
    "docstring": "Writes log out at any arbitray level."
  },
  {
    "code": "def complete(self):\n        if not self._techniques:\n            return False\n        if not any(tech._is_overriden('complete') for tech in self._techniques):\n            return False\n        return self.completion_mode(tech.complete(self) for tech in self._techniques if tech._is_overriden('complete'))",
    "docstring": "Returns whether or not this manager has reached a \"completed\" state."
  },
  {
    "code": "def enable_memcache(source=None, release=None, package=None):\n    _release = None\n    if release:\n        _release = release\n    else:\n        _release = os_release(package, base='icehouse')\n    if not _release:\n        _release = get_os_codename_install_source(source)\n    return CompareOpenStackReleases(_release) >= 'mitaka'",
    "docstring": "Determine if memcache should be enabled on the local unit\n\n    @param release: release of OpenStack currently deployed\n    @param package: package to derive OpenStack version deployed\n    @returns boolean Whether memcache should be enabled"
  },
  {
    "code": "def _on_capacity_data(self, conn, command, kwargs, response, capacity):\n        if self._analyzing:\n            self.consumed_capacities.append((command, capacity))\n        if self._query_rate_limit is not None:\n            self._query_rate_limit.on_capacity(\n                conn, command, kwargs, response, capacity\n            )\n        elif self.rate_limit is not None:\n            self.rate_limit.callback = self._on_throttle\n            self.rate_limit.on_capacity(conn, command, kwargs, response, capacity)",
    "docstring": "Log the received consumed capacity data"
  },
  {
    "code": "def _one_q_sic_prep(index, qubit):\n    if index == 0:\n        return Program()\n    theta = 2 * np.arccos(1 / np.sqrt(3))\n    zx_plane_rotation = Program([\n        RX(-pi / 2, qubit),\n        RZ(theta - pi, qubit),\n        RX(-pi / 2, qubit),\n    ])\n    if index == 1:\n        return zx_plane_rotation\n    elif index == 2:\n        return zx_plane_rotation + RZ(-2 * pi / 3, qubit)\n    elif index == 3:\n        return zx_plane_rotation + RZ(2 * pi / 3, qubit)\n    raise ValueError(f'Bad SIC index: {index}')",
    "docstring": "Prepare the index-th SIC basis state."
  },
  {
    "code": "def auto_unit(self, number,\n                  low_precision=False,\n                  min_symbol='K'\n                  ):\n        symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')\n        if min_symbol in symbols:\n            symbols = symbols[symbols.index(min_symbol):]\n        prefix = {\n            'Y': 1208925819614629174706176,\n            'Z': 1180591620717411303424,\n            'E': 1152921504606846976,\n            'P': 1125899906842624,\n            'T': 1099511627776,\n            'G': 1073741824,\n            'M': 1048576,\n            'K': 1024\n        }\n        for symbol in reversed(symbols):\n            value = float(number) / prefix[symbol]\n            if value > 1:\n                decimal_precision = 0\n                if value < 10:\n                    decimal_precision = 2\n                elif value < 100:\n                    decimal_precision = 1\n                if low_precision:\n                    if symbol in 'MK':\n                        decimal_precision = 0\n                    else:\n                        decimal_precision = min(1, decimal_precision)\n                elif symbol in 'K':\n                    decimal_precision = 0\n                return '{:.{decimal}f}{symbol}'.format(\n                    value, decimal=decimal_precision, symbol=symbol)\n        return '{!s}'.format(number)",
    "docstring": "Make a nice human-readable string out of number.\n\n        Number of decimal places increases as quantity approaches 1.\n        CASE: 613421788        RESULT:       585M low_precision:       585M\n        CASE: 5307033647       RESULT:      4.94G low_precision:       4.9G\n        CASE: 44968414685      RESULT:      41.9G low_precision:      41.9G\n        CASE: 838471403472     RESULT:       781G low_precision:       781G\n        CASE: 9683209690677    RESULT:      8.81T low_precision:       8.8T\n        CASE: 1073741824       RESULT:      1024M low_precision:      1024M\n        CASE: 1181116006       RESULT:      1.10G low_precision:       1.1G\n\n        :low_precision: returns less decimal places potentially (default is False)\n                        sacrificing precision for more readability.\n        :min_symbol: Do not approache if number < min_symbol (default is K)"
  },
  {
    "code": "def write_directory (zfile, directory):\n    for dirpath, dirnames, filenames in os.walk(directory):\n        zfile.write(dirpath)\n        for filename in filenames:\n            zfile.write(os.path.join(dirpath, filename))",
    "docstring": "Write recursively all directories and filenames to zipfile instance."
  },
  {
    "code": "def attributes(self):\n        attr = {\n            'name': self.name,\n            'id': self.sync_id,\n            'network_id': self.network_id,\n            'serial': self.serial,\n            'status': self.status,\n            'region': self.region,\n            'region_id': self.region_id,\n        }\n        return attr",
    "docstring": "Return sync attributes."
  },
  {
    "code": "def center(self):\n        try:\n            return self._center\n        except AttributeError:\n            pass\n        self._center = Point()\n        return self._center",
    "docstring": "Center point of the ellipse, equidistant from foci, Point class.\\n\n        Defaults to the origin."
  },
  {
    "code": "def from_file(filename, mime=False):\n    m = _get_magic_type(mime)\n    return m.from_file(filename)",
    "docstring": "Accepts a filename and returns the detected filetype.  Return\n    value is the mimetype if mime=True, otherwise a human readable\n    name.\n\n    >>> magic.from_file(\"testdata/test.pdf\", mime=True)\n    'application/pdf'"
  },
  {
    "code": "def get_all_coeffs():\n    coeffs = {}\n    for platform in URLS.keys():\n        if platform not in coeffs:\n            coeffs[platform] = {}\n        for chan in URLS[platform].keys():\n            url = URLS[platform][chan]\n            print url\n            page = get_page(url)\n            coeffs[platform][chan] = get_coeffs(page)\n    return coeffs",
    "docstring": "Get all available calibration coefficients for the satellites."
  },
  {
    "code": "def update_hit_count_ajax(request, *args, **kwargs):\n    warnings.warn(\n        \"hitcount.views.update_hit_count_ajax is deprecated. \"\n        \"Use hitcount.views.HitCountJSONView instead.\",\n        RemovedInHitCount13Warning\n    )\n    view = HitCountJSONView.as_view()\n    return view(request, *args, **kwargs)",
    "docstring": "Deprecated in 1.2. Use hitcount.views.HitCountJSONView instead."
  },
  {
    "code": "def calc_paired_insert_stats(in_bam, nsample=1000000):\n    dists = []\n    n = 0\n    with pysam.Samfile(in_bam, \"rb\") as in_pysam:\n        for read in in_pysam:\n            if read.is_proper_pair and read.is_read1:\n                n += 1\n                dists.append(abs(read.isize))\n                if n >= nsample:\n                    break\n    return insert_size_stats(dists)",
    "docstring": "Retrieve statistics for paired end read insert distances."
  },
  {
    "code": "def get_admin_ids(self):\r\n        admins = self.json_response.get(\"admin_list\", None)\r\n        admin_ids = [admin_id for admin_id in admins[\"userid\"]]\r\n        return admin_ids",
    "docstring": "Method to get the administrator id list."
  },
  {
    "code": "def install(self, param, author=None, constraints=None, origin=''):\n        if isinstance(param, SkillEntry):\n            skill = param\n        else:\n            skill = self.find_skill(param, author)\n        entry = build_skill_entry(skill.name, origin, skill.is_beta)\n        try:\n            skill.install(constraints)\n            entry['installed'] = time.time()\n            entry['installation'] = 'installed'\n            entry['status'] = 'active'\n            entry['beta'] = skill.is_beta\n        except AlreadyInstalled:\n            entry = None\n            raise\n        except MsmException as e:\n            entry['installation'] = 'failed'\n            entry['status'] = 'error'\n            entry['failure_message'] = repr(e)\n            raise\n        finally:\n            if entry:\n                self.skills_data['skills'].append(entry)",
    "docstring": "Install by url or name"
  },
  {
    "code": "def silent_popen(args, **kwargs):\n    return subprocess.Popen(args,\n                            stderr=subprocess.STDOUT,\n                            stdout=subprocess.PIPE, **kwargs).communicate()[0]",
    "docstring": "Wrapper for subprocess.Popen with suppressed output.\n\n    STERR is redirected to STDOUT which is piped back to the\n    calling process and returned as the result."
  },
  {
    "code": "def reftrack_alien_data(rt, role):\n    alien = rt.alien()\n    if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:\n        if alien:\n            return \"Yes\"\n        else:\n            return \"No\"",
    "docstring": "Return the data for the alien status\n\n    :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data\n    :type rt: :class:`jukeboxcore.reftrack.Reftrack`\n    :param role: item data role\n    :type role: QtCore.Qt.ItemDataRole\n    :returns: data for the alien status\n    :rtype: depending on role\n    :raises: None"
  },
  {
    "code": "def _GetValueAsObject(self, property_value):\n    if property_value.type == pyolecf.value_types.BOOLEAN:\n      return property_value.data_as_boolean\n    if property_value.type in self._INTEGER_TYPES:\n      return property_value.data_as_integer\n    if property_value.type in self._STRING_TYPES:\n      return property_value.data_as_string\n    try:\n      data = property_value.data\n    except IOError:\n      data = None\n    return data",
    "docstring": "Retrieves the property value as a Python object.\n\n    Args:\n      property_value (pyolecf.property_value): OLECF property value.\n\n    Returns:\n      object: property value as a Python object."
  },
  {
    "code": "def set_window_size_callback(window, cbfun):\n    window_addr = ctypes.cast(ctypes.pointer(window),\n                              ctypes.POINTER(ctypes.c_long)).contents.value\n    if window_addr in _window_size_callback_repository:\n        previous_callback = _window_size_callback_repository[window_addr]\n    else:\n        previous_callback = None\n    if cbfun is None:\n        cbfun = 0\n    c_cbfun = _GLFWwindowsizefun(cbfun)\n    _window_size_callback_repository[window_addr] = (cbfun, c_cbfun)\n    cbfun = c_cbfun\n    _glfw.glfwSetWindowSizeCallback(window, cbfun)\n    if previous_callback is not None and previous_callback[0] != 0:\n        return previous_callback[0]",
    "docstring": "Sets the size callback for the specified window.\n\n    Wrapper for:\n        GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun);"
  },
  {
    "code": "def events_for_secretreveal(\n        transfers_pair: List[MediationPairState],\n        secret: Secret,\n        pseudo_random_generator: random.Random,\n) -> List[Event]:\n    events: List[Event] = list()\n    for pair in reversed(transfers_pair):\n        payee_knows_secret = pair.payee_state in STATE_SECRET_KNOWN\n        payer_knows_secret = pair.payer_state in STATE_SECRET_KNOWN\n        is_transfer_pending = pair.payer_state == 'payer_pending'\n        should_send_secret = (\n            payee_knows_secret and\n            not payer_knows_secret and\n            is_transfer_pending\n        )\n        if should_send_secret:\n            message_identifier = message_identifier_from_prng(pseudo_random_generator)\n            pair.payer_state = 'payer_secret_revealed'\n            payer_transfer = pair.payer_transfer\n            revealsecret = SendSecretReveal(\n                recipient=payer_transfer.balance_proof.sender,\n                channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE,\n                message_identifier=message_identifier,\n                secret=secret,\n            )\n            events.append(revealsecret)\n    return events",
    "docstring": "Reveal the secret off-chain.\n\n    The secret is revealed off-chain even if there is a pending transaction to\n    reveal it on-chain, this allows the unlock to happen off-chain, which is\n    faster.\n\n    This node is named N, suppose there is a mediated transfer with two refund\n    transfers, one from B and one from C:\n\n        A-N-B...B-N-C..C-N-D\n\n    Under normal operation N will first learn the secret from D, then reveal to\n    C, wait for C to inform the secret is known before revealing it to B, and\n    again wait for B before revealing the secret to A.\n\n    If B somehow sent a reveal secret before C and D, then the secret will be\n    revealed to A, but not C and D, meaning the secret won't be propagated\n    forward. Even if D sent a reveal secret at about the same time, the secret\n    will only be revealed to B upon confirmation from C.\n\n    If the proof doesn't arrive in time and the lock's expiration is at risk, N\n    won't lose tokens since it knows the secret can go on-chain at any time."
  },
  {
    "code": "def quote_identifier(identifier: str,\n                     mixed: Union[SQLCompiler, Engine, Dialect]) -> str:\n    return get_preparer(mixed).quote(identifier)",
    "docstring": "Converts an SQL identifier to a quoted version, via the SQL dialect in\n    use.\n\n    Args:\n        identifier: the identifier to be quoted\n        mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or\n            :class:`Dialect` object\n\n    Returns:\n        the quoted identifier"
  },
  {
    "code": "def date_range_builder(self, start='2013-02-11', end=None):\n        if not end:\n            end = time.strftime('%Y-%m-%d')\n        return 'acquisitionDate:[%s+TO+%s]' % (start, end)",
    "docstring": "Builds date range query.\n\n        :param start:\n            Date string. format: YYYY-MM-DD\n        :type start:\n            String\n        :param end:\n            date string. format: YYYY-MM-DD\n        :type end:\n            String\n\n        :returns:\n            String"
  },
  {
    "code": "def _handle_browse(self, relpath, params):\n    abspath = os.path.normpath(os.path.join(self._root, relpath))\n    if not abspath.startswith(self._root):\n      raise ValueError\n    if os.path.isdir(abspath):\n      self._serve_dir(abspath, params)\n    elif os.path.isfile(abspath):\n      self._serve_file(abspath, params)",
    "docstring": "Handle requests to browse the filesystem under the build root."
  },
  {
    "code": "def set_cookie_if_ok(self, cookie, request):\n        self._cookies_lock.acquire()\n        try:\n            self._policy._now = self._now = int(time.time())\n            if self._policy.set_ok(cookie, request):\n                self.set_cookie(cookie)\n        finally:\n            self._cookies_lock.release()",
    "docstring": "Set a cookie if policy says it's OK to do so."
  },
  {
    "code": "def get_advanced_foreign_key_options_sql(self, foreign_key):\n        query = \"\"\n        if self.supports_foreign_key_on_update() and foreign_key.has_option(\n            \"on_update\"\n        ):\n            query += \" ON UPDATE %s\" % self.get_foreign_key_referential_action_sql(\n                foreign_key.get_option(\"on_update\")\n            )\n        if foreign_key.has_option(\"on_delete\"):\n            query += \" ON DELETE %s\" % self.get_foreign_key_referential_action_sql(\n                foreign_key.get_option(\"on_delete\")\n            )\n        return query",
    "docstring": "Returns the FOREIGN KEY query section dealing with non-standard options\n        as MATCH, INITIALLY DEFERRED, ON UPDATE, ...\n\n        :param foreign_key: The foreign key\n        :type foreign_key: ForeignKeyConstraint\n\n        :rtype: str"
  },
  {
    "code": "def lock(self, resource_id, region, account_id=None):\n        account_id = self.get_account_id(account_id)\n        return self.http.post(\n            \"%s/%s/locks/%s/lock\" % (self.endpoint, account_id, resource_id),\n            json={'region': region},\n            auth=self.get_api_auth())",
    "docstring": "Lock a given resource"
  },
  {
    "code": "def _workdir(self, line):\n        workdir = self._setup('WORKDIR', line)\n        line = \"cd %s\" %(''.join(workdir))\n        self.install.append(line)",
    "docstring": "A Docker WORKDIR command simply implies to cd to that location\n\n           Parameters\n           ==========\n           line: the line from the recipe file to parse for WORKDIR"
  },
  {
    "code": "def report_status_to_github(self,\n                                state: str,\n                                description: str,\n                                context: str,\n                                target_url: Optional[str] = None):\n        if state not in ['error', 'failure', 'pending', 'success']:\n            raise ValueError('Unrecognized state: {!r}'.format(state))\n        if self.repository is None or self.repository.access_token is None:\n            return\n        print(repr(('report_status',\n                    context,\n                    state,\n                    description,\n                    target_url)), file=sys.stderr)\n        payload = {\n            'state': state,\n            'description': description,\n            'context': context,\n        }\n        if target_url is not None:\n            payload['target_url'] = target_url\n        url = (\n            \"https://api.github.com/repos/{}/{}/statuses/{}?access_token={}\"\n            .format(self.repository.organization,\n                    self.repository.name,\n                    self.actual_commit_id,\n                    self.repository.access_token))\n        response = requests.post(url, json=payload)\n        if response.status_code != 201:\n            raise IOError('Request failed. Code: {}. Content: {}.'.format(\n                response.status_code, response.content))",
    "docstring": "Sets a commit status indicator on github.\n\n        If not running from a pull request (i.e. repository is None), then this\n        just prints to stderr.\n\n        Args:\n            state: The state of the status indicator.\n                Must be 'error', 'failure', 'pending', or 'success'.\n            description: A summary of why the state is what it is,\n                e.g. '5 lint errors' or 'tests passed!'.\n            context: The name of the status indicator, e.g. 'pytest' or 'lint'.\n            target_url: Optional location where additional details about the\n                status can be found, e.g. an online test results page.\n\n        Raises:\n            ValueError: Not one of the allowed states.\n            IOError: The HTTP post request failed, or the response didn't have\n                a 201 code indicating success in the expected way."
  },
  {
    "code": "def descendants(self, start, generations=None):\n        visited = self.vertex_set()\n        visited.add(start)\n        to_visit = deque([(start, 0)])\n        while to_visit:\n            vertex, depth = to_visit.popleft()\n            if depth == generations:\n                continue\n            for child in self.children(vertex):\n                if child not in visited:\n                    visited.add(child)\n                    to_visit.append((child, depth+1))\n        return self.full_subgraph(visited)",
    "docstring": "Return the subgraph of all nodes reachable\n        from the given start vertex, including that vertex.\n\n        If specified, the optional `generations` argument specifies how\n        many generations to limit to."
  },
  {
    "code": "def remove(self, uids: Iterable[int]) -> None:\n        for uid in uids:\n            self._recent.discard(uid)\n            self._flags.pop(uid, None)",
    "docstring": "Remove any session flags for the given message.\n\n        Args:\n            uids: The message UID values."
  },
  {
    "code": "def transform_external(self, external_url):\n        return filestack.models.Transform(apikey=self.apikey, security=self.security, external_url=external_url)",
    "docstring": "Turns an external URL into a Filestack Transform object\n\n        *returns* [Filestack.Transform]\n\n        ```python\n        from filestack import Client, Filelink\n\n        client = Client(\"API_KEY\")\n        transform = client.transform_external('http://www.example.com')\n        ```"
  },
  {
    "code": "def object_to_dict(cls, obj):\n        dict_obj = dict()\n        if obj is not None:\n            if type(obj) == list:\n                dict_list = []\n                for inst in obj:\n                    dict_list.append(cls.object_to_dict(inst))\n                dict_obj[\"list\"] = dict_list\n            elif not cls.is_primitive(obj):\n                for key in obj.__dict__:\n                    if type(obj.__dict__[key]) == list:\n                        dict_list = []\n                        for inst in obj.__dict__[key]:\n                            dict_list.append(cls.object_to_dict(inst))\n                        dict_obj[key] = dict_list\n                    elif not cls.is_primitive(obj.__dict__[key]):\n                        temp_dict = cls.object_to_dict(obj.__dict__[key])\n                        dict_obj[key] = temp_dict\n                    else:\n                        dict_obj[key] = obj.__dict__[key]\n            elif cls.is_primitive(obj):\n                return obj\n        return dict_obj",
    "docstring": "This function converts Objects into Dictionary"
  },
  {
    "code": "def stop_consuming(self):\n        if self._channel:\n            logger.debug('Sending a Basic.Cancel RPC command to RabbitMQ')\n            self._channel.basic_cancel(self.on_cancelok, self._consumer_tag)",
    "docstring": "Tell RabbitMQ that we would like to stop consuming."
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'aggregations' in _dict:\n            args['aggregations'] = [\n                MetricTokenAggregation._from_dict(x)\n                for x in (_dict.get('aggregations'))\n            ]\n        return cls(**args)",
    "docstring": "Initialize a MetricTokenResponse object from a json dictionary."
  },
  {
    "code": "def get_decimal_time(self):\n        return decimal_time(self.data['year'],\n                            self.data['month'],\n                            self.data['day'],\n                            self.data['hour'],\n                            self.data['minute'],\n                            self.data['second'])",
    "docstring": "Returns the time of the catalogue as a decimal"
  },
  {
    "code": "def dotted_parts(s):\n    idx = -1\n    while s:\n        idx = s.find('.', idx+1)\n        if idx == -1:\n            yield s\n            break\n        yield s[:idx]",
    "docstring": "For a string \"a.b.c\", yields \"a\", \"a.b\", \"a.b.c\"."
  },
  {
    "code": "def object_path(collection, id):\n    _logger.debug(type(id))\n    _logger.debug(id)\n    if isinstance(id, dict) and 'id' in id:\n        id = id['id']\n    normalized_id = normalize_text(str(id), lcase=False)\n    return os.path.join(_basepath, collection,\n        '%s.%s' % (normalized_id, _ext))",
    "docstring": "Returns path to the backing file of the object\n    with the given ``id`` in the given ``collection``.\n    Note that the ``id`` is made filesystem-safe by\n    \"normalizing\" its string representation."
  },
  {
    "code": "def initialize_params(self, preload_data=True) -> None:\n        params = ''\n        if preload_data:\n            params = self.request('get', param_url)\n        self.params = Params(params, self.request)",
    "docstring": "Load device parameters and initialize parameter management.\n\n        Preload data can be disabled to selectively load params afterwards."
  },
  {
    "code": "def _get_subcats(self, recurse=False):\n        if recurse:\n            return sorted([Category(e) for e in self._subcats_recursive],\n                          key=lambda c: c.sort_breadcrumb)\n        parts = len(self.path.split('/')) + 1 if self.path else 1\n        subcats = [c.split('/')[:parts] for c in self._subcats_recursive]\n        subcats = {'/'.join(c) for c in subcats}\n        return sorted([Category(c) for c in subcats], key=lambda c: c.sort_name or c.name)",
    "docstring": "Get the subcategories of this category\n\n        recurse -- whether to include their subcategories as well"
  },
  {
    "code": "def find_root(self):\n        self.find_parents()\n        index = 0\n        while len(self.vertices[index].parents)>0:\n            index = self.vertices[index].parents[0]\n        return index",
    "docstring": "Finds the index of the root node of the tree."
  },
  {
    "code": "def _probe_lock_file(self, reported_mtime):\r\n        delta = reported_mtime - self.lock_data[\"lock_time\"]\r\n        self.server_time_ofs = delta\r\n        if self.get_option(\"verbose\", 3) >= 4:\r\n            write(\"Server time offset: {:.2f} seconds.\".format(delta))",
    "docstring": "Called by get_dir"
  },
  {
    "code": "def reset_defaults(self):\n        self.save_login.setChecked(False)\n        self.save_password.setChecked(False)\n        self.save_url.setChecked(False)\n        set_setting(GEONODE_USER, '')\n        set_setting(GEONODE_PASSWORD, '')\n        set_setting(GEONODE_URL, '')\n        self.login.setText('')\n        self.password.setText('')\n        self.url.setText('')",
    "docstring": "Reset login and password in QgsSettings."
  },
  {
    "code": "def get_item_by_key(passed_list, key, value):\r\n    if value in [None, '']:\r\n        return\r\n    if type(passed_list) in [QuerySet, PolymorphicQuerySet]:\r\n        sub_list = passed_list.filter(**{key: value})\r\n    else:\r\n        sub_list = [x for x in passed_list if x.get(key) == value]\r\n    if len(sub_list) == 1:\r\n        return sub_list[0]\r\n    return sub_list",
    "docstring": "This one allows us to get one or more items from a list of\r\n    dictionaries based on the value of a specified key, where\r\n    both the key and the value can be variable names.  Does\r\n    not work with None or null string passed values."
  },
  {
    "code": "def _to_reddit_list(arg):\n    if (isinstance(arg, six.string_types) or not (\n            hasattr(arg, \"__getitem__\") or hasattr(arg, \"__iter__\"))):\n        return six.text_type(arg)\n    else:\n        return ','.join(six.text_type(a) for a in arg)",
    "docstring": "Return an argument converted to a reddit-formatted list.\n\n    The returned format is a comma deliminated list. Each element is a string\n    representation of an object. Either given as a string or as an object that\n    is then converted to its string representation."
  },
  {
    "code": "def flux(self, photon_energy, distance=1 * u.kpc):\n        spec = self._spectrum(photon_energy)\n        if distance != 0:\n            distance = validate_scalar(\n                \"distance\", distance, physical_type=\"length\"\n            )\n            spec /= 4 * np.pi * distance.to(\"cm\") ** 2\n            out_unit = \"1/(s cm2 eV)\"\n        else:\n            out_unit = \"1/(s eV)\"\n        return spec.to(out_unit)",
    "docstring": "Differential flux at a given distance from the source.\n\n        Parameters\n        ----------\n        photon_energy : :class:`~astropy.units.Quantity` float or array\n            Photon energy array.\n\n        distance : :class:`~astropy.units.Quantity` float, optional\n            Distance to the source. If set to 0, the intrinsic differential\n            luminosity will be returned. Default is 1 kpc."
  },
  {
    "code": "def _get_xref(self, line):\n        mtch = self.attr2cmp['xref'].match(line)\n        return mtch.group(1).replace(' ', '')",
    "docstring": "Given line, return optional attribute xref value in a dict of sets."
  },
  {
    "code": "def compile(manager, path, allow_naked_names, allow_nested, disallow_unqualified_translocations,\n            no_identifier_validation, no_citation_clearing, required_annotations, skip_tqdm, verbose):\n    if verbose:\n        logging.basicConfig(level=logging.DEBUG)\n        log.setLevel(logging.DEBUG)\n        log.debug('using connection: %s', manager.engine.url)\n    click.secho('Compilation', fg='red', bold=True)\n    if skip_tqdm:\n        click.echo('```')\n    graph = from_path(\n        path,\n        manager=manager,\n        use_tqdm=(not (skip_tqdm or verbose)),\n        allow_nested=allow_nested,\n        allow_naked_names=allow_naked_names,\n        disallow_unqualified_translocations=disallow_unqualified_translocations,\n        citation_clearing=(not no_citation_clearing),\n        required_annotations=required_annotations,\n        no_identifier_validation=no_identifier_validation,\n        allow_definition_failures=True,\n    )\n    if skip_tqdm:\n        click.echo('```')\n    to_pickle(graph, get_corresponding_pickle_path(path))\n    click.echo('')\n    _print_summary(graph, ticks=skip_tqdm)\n    sys.exit(0 if 0 == graph.number_of_warnings() else 1)",
    "docstring": "Compile a BEL script to a graph."
  },
  {
    "code": "def gam_in_biomass(model, reaction):\n    id_of_main_compartment = helpers.find_compartment_id_in_model(model, 'c')\n    try:\n        left = {\n            helpers.find_met_in_model(\n                model, \"MNXM3\", id_of_main_compartment)[0],\n            helpers.find_met_in_model(\n                model, \"MNXM2\", id_of_main_compartment)[0]\n        }\n        right = {\n            helpers.find_met_in_model(\n                model, \"MNXM7\", id_of_main_compartment)[0],\n            helpers.find_met_in_model(\n                model, \"MNXM1\", id_of_main_compartment)[0],\n            helpers.find_met_in_model(\n                model, \"MNXM9\", id_of_main_compartment)[0]\n        }\n    except RuntimeError:\n        return False\n    return (\n        left.issubset(set(reaction.reactants)) and\n        right.issubset(set(reaction.products)))",
    "docstring": "Return boolean if biomass reaction includes growth-associated maintenance.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model under investigation.\n    reaction : cobra.core.reaction.Reaction\n        The biomass reaction of the model under investigation.\n\n    Returns\n    -------\n    boolean\n        True if the biomass reaction includes ATP and H2O as reactants and ADP,\n        Pi and H as products, False otherwise."
  },
  {
    "code": "def serialize(self) -> str:\n        return {\n            '@context': DIDDoc.CONTEXT,\n            'id': canon_ref(self.did, self.did),\n            'publicKey': [pubkey.to_dict() for pubkey in self.pubkey.values()],\n            'authentication': [{\n                'type': pubkey.type.authn_type,\n                'publicKey': canon_ref(self.did, pubkey.id)\n            } for pubkey in self.pubkey.values() if pubkey.authn],\n            'service': [service.to_dict() for service in self.service.values()]\n        }",
    "docstring": "Dump current object to a JSON-compatible dictionary.\n\n        :return: dict representation of current DIDDoc"
  },
  {
    "code": "def post(self, uri, body=None, **kwargs):\n        return self.fetch('post', uri, kwargs.pop(\"query\", {}), body, **kwargs)",
    "docstring": "make a POST request"
  },
  {
    "code": "def run_all(logdir, steps, thresholds, verbose=False):\n  run_name = 'colors'\n  if verbose:\n    print('--- Running: %s' % run_name)\n  start_runs(\n      logdir=logdir,\n      steps=steps,\n      run_name=run_name,\n      thresholds=thresholds)\n  run_name = 'mask_every_other_prediction'\n  if verbose:\n    print('--- Running: %s' % run_name)\n  start_runs(\n      logdir=logdir,\n      steps=steps,\n      run_name=run_name,\n      thresholds=thresholds,\n      mask_every_other_prediction=True)",
    "docstring": "Generate PR curve summaries.\n\n  Arguments:\n    logdir: The directory into which to store all the runs' data.\n    steps: The number of steps to run for.\n    verbose: Whether to print the names of runs into stdout during execution.\n    thresholds: The number of thresholds to use for PR curves."
  },
  {
    "code": "def _condense(self, data):\n    if data:\n      return reduce(operator.ior, data.values())\n    return set()",
    "docstring": "Condense by or-ing all of the sets."
  },
  {
    "code": "def ListingBox(listing, *args, **kwargs):\n    \" Delegate the boxing to the target's Box class. \"\n    obj = listing.publishable\n    return obj.box_class(obj, *args, **kwargs)",
    "docstring": "Delegate the boxing to the target's Box class."
  },
  {
    "code": "def add(self, entry):\n        c = self.conn.cursor()\n        c.execute(\"INSERT INTO oath (key, aead, nonce, key_handle, oath_C, oath_T) VALUES (?, ?, ?, ?, ?, ?)\",\n                  (entry.data[\"key\"], \\\n                       entry.data[\"aead\"], \\\n                       entry.data[\"nonce\"], \\\n                       entry.data[\"key_handle\"], \\\n                       entry.data[\"oath_C\"], \\\n                       entry.data[\"oath_T\"],))\n        self.conn.commit()\n        return c.rowcount == 1",
    "docstring": "Add entry to database."
  },
  {
    "code": "async def dump_variant(obj, elem, elem_type=None, params=None, field_archiver=None):\n    field_archiver = field_archiver if field_archiver else dump_field\n    if isinstance(elem, x.VariantType) or elem_type.WRAPS_VALUE:\n        return {\n            elem.variant_elem: await field_archiver(None, getattr(elem, elem.variant_elem), elem.variant_elem_type)\n        }\n    else:\n        fdef = elem_type.find_fdef(elem_type.f_specs(), elem)\n        return {\n            fdef[0]: await field_archiver(None, elem, fdef[1])\n        }",
    "docstring": "Transform variant to the popo object representation.\n\n    :param obj:\n    :param elem:\n    :param elem_type:\n    :param params:\n    :param field_archiver:\n    :return:"
  },
  {
    "code": "def LookupCirrusAmi(ec2, instance_type, ubuntu_release_name, mapr_version, role,\n                    ami_release_name,\n                    ami_owner_id):  \n  if not role in valid_instance_roles:\n    raise RuntimeError('Specified role (%s) not a valid role: %s' % (role, \n                       valid_instance_roles))\n  virtualization_type = 'paravirtual'\n  if IsHPCInstanceType(instance_type):\n    virtualization_type = 'hvm'\n  assert(ami_owner_id)  \n  images = ec2.get_all_images(owners=[ami_owner_id])\n  ami = None\n  ami_name = AmiName(ami_release_name, ubuntu_release_name, virtualization_type,\n                     mapr_version, role)\n  for image in images:\n    if image.name == ami_name:\n        ami = image\n        break\n  return ami",
    "docstring": "Returns AMI satisfying provided constraints."
  },
  {
    "code": "def cache_file(self, template):\n        saltpath = salt.utils.url.create(template)\n        self.file_client().get_file(saltpath, '', True, self.saltenv)",
    "docstring": "Cache a file from the salt master"
  },
  {
    "code": "def make_middleware(app=None, *args, **kw):\n    app = iWSGIMiddleware(app, *args, **kw)\n    return app",
    "docstring": "Given an app, return that app wrapped in iWSGIMiddleware"
  },
  {
    "code": "def get_earth_radii(self):\n        earth_model = self.prologue['GeometricProcessing']['EarthModel']\n        a = earth_model['EquatorialRadius'] * 1000\n        b = (earth_model['NorthPolarRadius'] +\n             earth_model['SouthPolarRadius']) / 2.0 * 1000\n        return a, b",
    "docstring": "Get earth radii from prologue\n\n        Returns:\n            Equatorial radius, polar radius [m]"
  },
  {
    "code": "def _check_sample(in_bam, rgnames):\n    with pysam.Samfile(in_bam, \"rb\") as bamfile:\n        rg = bamfile.header.get(\"RG\", [{}])\n    msgs = []\n    warnings = []\n    if len(rg) > 1:\n        warnings.append(\"Multiple read groups found in input BAM. Expect single RG per BAM.\")\n    if len(rg) == 0:\n        msgs.append(\"No read groups found in input BAM. Expect single RG per BAM.\")\n    if len(rg) > 0 and any(x.get(\"SM\") != rgnames[\"sample\"] for x in rg):\n        msgs.append(\"Read group sample name (SM) does not match configuration `description`: %s vs %s\"\n                    % (rg[0].get(\"SM\"), rgnames[\"sample\"]))\n    if len(msgs) > 0:\n        raise ValueError(\"Problems with pre-aligned input BAM file: %s\\n\" % (in_bam)\n                         + \"\\n\".join(msgs) +\n                         \"\\nSetting `bam_clean: fixrg`\\n\"\n                         \"in the configuration can often fix this issue.\")\n    if warnings:\n        print(\"*** Potential problems in input BAM compared to reference:\\n%s\\n\" %\n              \"\\n\".join(warnings))",
    "docstring": "Ensure input sample name matches expected run group names."
  },
  {
    "code": "def replace_policy(self, scaling_group, policy, name,\n            policy_type, cooldown, change=None, is_percent=False,\n            desired_capacity=None, args=None):\n        policy_id = utils.get_id(policy)\n        group_id = utils.get_id(scaling_group)\n        uri = \"/%s/%s/policies/%s\" % (self.uri_base, group_id, policy_id)\n        body = self._create_policy_body(name=name, policy_type=policy_type,\n                cooldown=cooldown, change=change, is_percent=is_percent,\n                desired_capacity=desired_capacity, args=args)\n        resp, resp_body = self.api.method_put(uri, body=body)",
    "docstring": "Replace an existing policy. All of the attributes must be specified. If\n        you wish to delete any of the optional attributes, pass them in as\n        None."
  },
  {
    "code": "def reset_spent_time(self, **kwargs):\n        path = '%s/%s/reset_spent_time' % (self.manager.path, self.get_id())\n        return self.manager.gitlab.http_post(path, **kwargs)",
    "docstring": "Resets the time spent working on the object.\n\n        Args:\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabTimeTrackingError: If the time tracking update cannot be done"
  },
  {
    "code": "def resample(samples, oldsr, newsr):\n    backends = [\n        _resample_samplerate,\n        _resample_scikits,\n        _resample_nnresample,\n        _resample_obspy,\n        _resample_scipy\n    ]\n    for backend in backends:\n        newsamples = backend(samples, oldsr, newsr)\n        if newsamples is not None:\n            return newsamples",
    "docstring": "Resample `samples` with given samplerate `sr` to new samplerate `newsr`\n\n    samples: mono or multichannel frames\n    oldsr  : original samplerate\n    newsr  : new sample rate\n\n    Returns: the new samples"
  },
  {
    "code": "def categorize(self, categories, default=None):\n        return dim(self, categorize, categories=categories, default=default)",
    "docstring": "Replaces discrete values with supplied categories\n\n        Replaces discrete values in input array into a fixed set of\n        categories defined either as a list or dictionary.\n\n        Args:\n            categories: List or dict of categories to map inputs to\n            default: Default value to assign if value not in categories"
  },
  {
    "code": "def fetchref(self, ref):\n        log.debug('[%s] Fetching ref: %s', self.name, ref)\n        fetch_info = self.repo.remotes.origin.fetch(ref).pop()\n        return fetch_info.ref",
    "docstring": "Fetch a particular git ref."
  },
  {
    "code": "def set_global(cls, user_agent=None, user_agent_config_yaml=None,\n                   user_agent_lookup=None, **kwargs):\n        cls.user_agent = cls._create(user_agent, user_agent_config_yaml, user_agent_lookup, **kwargs)",
    "docstring": "Set global user agent string\n\n        Args:\n            user_agent (Optional[str]): User agent string. HDXPythonLibrary/X.X.X- is prefixed.\n            user_agent_config_yaml (Optional[str]): Path to YAML user agent configuration. Ignored if user_agent supplied. Defaults to ~/.useragent.yml.\n            user_agent_lookup (Optional[str]): Lookup key for YAML. Ignored if user_agent supplied.\n\n        Returns:\n            None"
  },
  {
    "code": "def appndd(item, cell):\n    assert isinstance(cell, stypes.SpiceCell)\n    if hasattr(item, \"__iter__\"):\n        for d in item:\n            libspice.appndd_c(ctypes.c_double(d), cell)\n    else:\n        item = ctypes.c_double(item)\n        libspice.appndd_c(item, cell)",
    "docstring": "Append an item to a double precision cell.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndd_c.html\n\n    :param item: The item to append.\n    :type item: Union[float,Iterable[float]]\n    :param cell: The cell to append to.\n    :type cell: spiceypy.utils.support_types.SpiceCell"
  },
  {
    "code": "def Save(session, filename=None):\n    if not filename:\n        filename = \"androguard_session_{:%Y-%m-%d_%H%M%S}.ag\".format(datetime.datetime.now())\n    if os.path.isfile(filename):\n        log.warning(\"{} already exists, overwriting!\")\n    reclimit = sys.getrecursionlimit()\n    sys.setrecursionlimit(50000)\n    saved = False\n    try:\n        with open(filename, \"wb\") as fd:\n            pickle.dump(session, fd)\n        saved = True\n    except RecursionError:\n        log.exception(\"Recursion Limit hit while saving. \"\n                      \"Current Recursion limit: {}. \"\n                      \"Please report this error!\".format(sys.getrecursionlimit()))\n        os.unlink(filename)\n    sys.setrecursionlimit(reclimit)\n    return filename if saved else None",
    "docstring": "save your session to use it later.\n\n    Returns the filename of the written file.\n    If not filename is given, a file named `androguard_session_<DATE>.ag` will\n    be created in the current working directory.\n    `<DATE>` is a timestamp with the following format: `%Y-%m-%d_%H%M%S`.\n\n    This function will overwrite existing files without asking.\n\n    If the file could not written, None is returned.\n\n    example::\n\n        s = session.Session()\n        session.Save(s, \"msession.ag\")\n\n    :param session: A Session object to save\n    :param filename: output filename to save the session\n    :type filename: string"
  },
  {
    "code": "def _monomers(self):\n        for stmt in self.statements:\n            if _is_whitelisted(stmt):\n                self._dispatch(stmt, 'monomers', self.agent_set)",
    "docstring": "Calls the appropriate monomers method based on policies."
  },
  {
    "code": "def pipe_truncate(context=None, _INPUT=None, conf=None, **kwargs):\n    funcs = get_splits(None, conf, **cdicts(opts, kwargs))\n    pieces, _pass = funcs[0](), funcs[2]()\n    if _pass:\n        _OUTPUT = _INPUT\n    else:\n        try:\n            start = int(pieces.start)\n        except AttributeError:\n            start = 0\n        stop = start + int(pieces.count)\n        _OUTPUT = islice(_INPUT, start, stop)\n    return _OUTPUT",
    "docstring": "An operator that returns a specified number of items from the top of a\n    feed. Not loopable.\n\n    Parameters\n    ----------\n    context : pipe2py.Context object\n    _INPUT : pipe2py.modules pipe like object (iterable of items)\n    kwargs -- terminal, if the truncation value is wired in\n    conf : {\n        'start': {'type': 'number', value': <starting location>}\n        'count': {'type': 'number', value': <desired feed length>}\n    }\n\n    Returns\n    -------\n    _OUTPUT : generator of items"
  },
  {
    "code": "def _family_notes_path(family, data_dir):\n    data_dir = fix_data_dir(data_dir)\n    family = family.lower()\n    if not family in get_families(data_dir):\n        raise RuntimeError(\"Family '{}' does not exist\".format(family))\n    file_name = 'NOTES.' + family.lower()\n    file_path = os.path.join(data_dir, file_name)\n    return file_path",
    "docstring": "Form a path to the notes for a family"
  },
  {
    "code": "def cgv2el(center, vec1, vec2):\n    center = stypes.toDoubleVector(center)\n    vec1 = stypes.toDoubleVector(vec1)\n    vec2 = stypes.toDoubleVector(vec2)\n    ellipse = stypes.Ellipse()\n    libspice.cgv2el_c(center, vec1, vec2, ctypes.byref(ellipse))\n    return ellipse",
    "docstring": "Form a SPICE ellipse from a center vector and two generating vectors.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cgv2el_c.html\n\n    :param center: Center Vector\n    :type center: 3-Element Array of floats\n    :param vec1: Vector 1\n    :type vec1: 3-Element Array of floats\n    :param vec2: Vector 2\n    :type vec2: 3-Element Array of floats\n    :return: Ellipse\n    :rtype: spiceypy.utils.support_types.Ellipse"
  },
  {
    "code": "def metaclass(*metaclasses):\n    def _inner(cls):\n        metabases = tuple(\n            collections.OrderedDict(\n                (c, None) for c in (metaclasses + (type(cls),))\n            ).keys()\n        )\n        _Meta = metabases[0]\n        for base in metabases[1:]:\n            class _Meta(base, _Meta):\n                pass\n        return six.add_metaclass(_Meta)(cls)\n    return _inner",
    "docstring": "Create the class using all metaclasses.\n\n    Args:\n        metaclasses: A tuple of metaclasses that will be used to generate and\n            replace a specified class.\n\n    Returns:\n        A decorator that will recreate the class using the specified\n        metaclasses."
  },
  {
    "code": "def add_resource(mt_file, ref, cache):\n    if isinstance(mt_file, MetapackDoc):\n        doc = mt_file\n    else:\n        doc = MetapackDoc(mt_file)\n    if not 'Resources' in doc:\n        doc.new_section('Resources')\n    doc['Resources'].args = [e for e in set(doc['Resources'].args + ['Name', 'StartLine', 'HeaderLines', 'Encoding']) if\n                             e]\n    seen_names = set()\n    u = parse_app_url(ref)\n    if u.proto == 'file':\n        entries = u.list()\n    else:\n        entries = [ssu for su in u.list() for ssu in su.list()]\n    errors = []\n    for e in entries:\n        if not add_single_resource(doc, e, cache=cache, seen_names=seen_names):\n            errors.append(e)\n    if errors:\n        prt()\n        warn(\"Found, but failed to add these urls:\")\n        for e in errors:\n            print('    ', e)\n    write_doc(doc, mt_file)",
    "docstring": "Add a resources entry, downloading the intuiting the file, replacing entries with\n    the same reference"
  },
  {
    "code": "def symlink_to_bin(self, name, path):\n        self.__symlink_dir(\"bin\", name, path)\n        os.chmod(os.path.join(self.root_dir, \"bin\", name), os.stat(path).st_mode | stat.S_IXUSR | stat.S_IRUSR)",
    "docstring": "Symlink an object at path to name in the bin folder."
  },
  {
    "code": "def do_grep(self, params):\n        self.grep(params.path, params.content, 0, params.show_matches)",
    "docstring": "\\x1b[1mNAME\\x1b[0m\n        grep - Prints znodes with a value matching the given text\n\n\\x1b[1mSYNOPSIS\\x1b[0m\n        grep [path] <content> [show_matches]\n\n\\x1b[1mOPTIONS\\x1b[0m\n        * path: the path (default: cwd)\n        * show_matches: show the content that matched (default: false)\n\n\\x1b[1mEXAMPLES\\x1b[0m\n        > grep / unbound true\n        /passwd: unbound:x:992:991:Unbound DNS resolver:/etc/unbound:/sbin/nologin\n        /copy/passwd: unbound:x:992:991:Unbound DNS resolver:/etc/unbound:/sbin/nologin"
  },
  {
    "code": "def sqlalchemy_escape(val, escape_char, special_chars):\n    if sys.version_info[:2] >= (3, 0):\n        assert isinstance(val, str)\n    else:\n        assert isinstance(val, basestring)\n    result = []\n    for c in val:\n        if c in special_chars + escape_char:\n            result.extend(escape_char + c)\n        else:\n            result.extend(c)\n    return ''.join(result)",
    "docstring": "Escape a string according for use in LIKE operator\n\n    >>> sqlalchemy_escape(\"text_table\", \"\\\\\", \"%_\")\n    'text\\_table'"
  },
  {
    "code": "def init_logging(\n    log_dir=tempfile.gettempdir(),\n    format=\"[%(asctime)s][%(levelname)s] %(name)s:%(lineno)s - %(message)s\",\n    level=logging.INFO,\n):\n    if not Meta.log_path:\n        dt = datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n        log_path = os.path.join(log_dir, dt)\n        if not os.path.exists(log_path):\n            os.makedirs(log_path)\n        logging.basicConfig(\n            format=format,\n            level=level,\n            handlers=[\n                logging.FileHandler(os.path.join(log_path, \"fonduer.log\")),\n                logging.StreamHandler(),\n            ],\n        )\n        logger.info(f\"Setting logging directory to: {log_path}\")\n        Meta.log_path = log_path\n    else:\n        logger.info(\n            f\"Logging was already initialized to use {Meta.log_path}.  \"\n            \"To configure logging manually, call fonduer.init_logging before \"\n            \"initialiting Meta.\"\n        )",
    "docstring": "Configures logging to output to the provided log_dir.\n\n    Will use a nested directory whose name is the current timestamp.\n\n    :param log_dir: The directory to store logs in.\n    :type log_dir: str\n    :param format: The logging format string to use.\n    :type format: str\n    :param level: The logging level to use, e.g., logging.INFO."
  },
  {
    "code": "def getitem(self, index):\n        if index >= getattr(self.tree, self.size):\n            raise IndexError(index)\n        if self.__cache_objects and index in self.__cache:\n            return self.__cache[index]\n        obj = self.tree_object_cls(self.tree, self.name, self.prefix, index)\n        if self.__cache_objects:\n            self.__cache[index] = obj\n        return obj",
    "docstring": "direct access without going through self.selection"
  },
  {
    "code": "def set_kill_on_exit_mode(bKillOnExit = False):\n        try:\n            win32.DebugSetProcessKillOnExit(bKillOnExit)\n        except (AttributeError, WindowsError):\n            return False\n        return True",
    "docstring": "Defines the behavior of the debugged processes when the debugging\n        thread dies. This method only affects the calling thread.\n\n        Works on the following platforms:\n\n         - Microsoft Windows XP and above.\n         - Wine (Windows Emulator).\n\n        Fails on the following platforms:\n\n         - Microsoft Windows 2000 and below.\n         - ReactOS.\n\n        @type  bKillOnExit: bool\n        @param bKillOnExit: C{True} to automatically kill processes when the\n            debugger thread dies. C{False} to automatically detach from\n            processes when the debugger thread dies.\n\n        @rtype:  bool\n        @return: C{True} on success, C{False} on error.\n\n        @note:\n            This call will fail if a debug port was not created. That is, if\n            the debugger isn't attached to at least one process. For more info\n            see: U{http://msdn.microsoft.com/en-us/library/ms679307.aspx}"
  },
  {
    "code": "def reply_to(self) -> Optional[Sequence[AddressHeader]]:\n        try:\n            return cast(Sequence[AddressHeader], self[b'reply-to'])\n        except KeyError:\n            return None",
    "docstring": "The ``Reply-To`` header."
  },
  {
    "code": "def cut_across_axis(self, dim, minval=None, maxval=None):\n        vertex_mask = np.ones((len(self.v),), dtype=bool)\n        if minval is not None:\n            predicate = self.v[:, dim] >= minval\n            vertex_mask = np.logical_and(vertex_mask, predicate)\n        if maxval is not None:\n            predicate = self.v[:, dim] <= maxval\n            vertex_mask = np.logical_and(vertex_mask, predicate)\n        vertex_indices = np.flatnonzero(vertex_mask)\n        self.keep_vertices(vertex_indices)\n        return vertex_indices",
    "docstring": "Cut the mesh by a plane, discarding vertices that lie behind that\n        plane. Or cut the mesh by two parallel planes, discarding vertices\n        that lie outside them.\n\n        The region to keep is defined by an axis of perpendicularity,\n        specified by `dim`: 0 means x, 1 means y, 2 means z. `minval`\n        and `maxval` indicate the portion of that axis to keep.\n\n        Return the original indices of the kept vertices."
  },
  {
    "code": "def _maybe_decompress_body(self):\n        if self.content_encoding:\n            if self.content_encoding in self._CODEC_MAP.keys():\n                module_name = self._CODEC_MAP[self.content_encoding]\n                self.logger.debug('Decompressing with %s', module_name)\n                module = self._maybe_import(module_name)\n                return module.decompress(self._message.body)\n            self.logger.debug('Unsupported content-encoding: %s',\n                              self.content_encoding)\n        return self._message.body",
    "docstring": "Attempt to decompress the message body passed in using the named\n        compression module, if specified.\n\n        :rtype: bytes"
  },
  {
    "code": "def methods(method_list):\n    assert isinstance(method_list, list) and len(method_list) > 0\n    def deco(handler):\n        d = _HandleRequestDict()\n        for m in method_list:\n            d[m.upper()] = handler\n        return d\n    return deco",
    "docstring": "A decorator to mark HTTP methods a resource can handle.\n\n    For example::\n\n        class SomeRes(UrlResource):\n            ...\n            @methods(['GET', 'HEAD'])\n            def handle_request(self, req):\n                ...\n            @handle_request.methods(['POST'])\n            def handle_post(self, req):\n                ...\n\n    In this case, GET and HEAD requests will be dispatched to\n    ``handle_request``, and POST requests will be dispatched to\n    ``handle_post``. All other request methods will cause a\n    *501 Not Implemented* error."
  },
  {
    "code": "def get_field_schema_validations(field: Field) -> Dict[str, Any]:\n    f_schema: Dict[str, Any] = {}\n    if lenient_issubclass(field.type_, (str, bytes)):\n        for attr_name, t, keyword in _str_types_attrs:\n            attr = getattr(field.schema, attr_name, None)\n            if isinstance(attr, t):\n                f_schema[keyword] = attr\n    if lenient_issubclass(field.type_, numeric_types) and not issubclass(field.type_, bool):\n        for attr_name, t, keyword in _numeric_types_attrs:\n            attr = getattr(field.schema, attr_name, None)\n            if isinstance(attr, t):\n                f_schema[keyword] = attr\n    schema = cast('Schema', field.schema)\n    if schema.extra:\n        f_schema.update(schema.extra)\n    return f_schema",
    "docstring": "Get the JSON Schema validation keywords for a ``field`` with an annotation of\n    a Pydantic ``Schema`` with validation arguments."
  },
  {
    "code": "def map_keys_to_values(l: List[Any], d: Dict[Any, Any], default: Any = None,\n                       raise_if_missing: bool = False,\n                       omit_if_missing: bool = False) -> List[Any]:\n    result = []\n    for k in l:\n        if raise_if_missing and k not in d:\n            raise ValueError(\"Missing key: \" + repr(k))\n        if omit_if_missing and k not in d:\n            continue\n        result.append(d.get(k, default))\n    return result",
    "docstring": "The ``d`` dictionary contains a ``key -> value`` mapping.\n\n    We start with a list of potential keys in ``l``, and return a list of\n    corresponding values -- substituting ``default`` if any are missing,\n    or raising :exc:`KeyError` if ``raise_if_missing`` is true, or omitting the\n    entry if ``omit_if_missing`` is true."
  },
  {
    "code": "def do_watch(self, *args):\n        tables = []\n        if not self.engine.cached_descriptions:\n            self.engine.describe_all()\n        all_tables = list(self.engine.cached_descriptions)\n        for arg in args:\n            candidates = set((t for t in all_tables if fnmatch(t, arg)))\n            for t in sorted(candidates):\n                if t not in tables:\n                    tables.append(t)\n        mon = Monitor(self.engine, tables)\n        mon.start()",
    "docstring": "Watch Dynamo tables consumed capacity"
  },
  {
    "code": "def from_iothub_connection_string(cls, conn_str, **kwargs):\n        address, policy, key, _ = _parse_conn_str(conn_str)\n        hub_name = address.split('.')[0]\n        username = \"{}@sas.root.{}\".format(policy, hub_name)\n        password = _generate_sas_token(address, policy, key)\n        client = cls(\"amqps://\" + address, username=username, password=password, **kwargs)\n        client._auth_config = {\n            'iot_username': policy,\n            'iot_password': key,\n            'username': username,\n            'password': password}\n        return client",
    "docstring": "Create an EventHubClient from an IoTHub connection string.\n\n        :param conn_str: The connection string.\n        :type conn_str: str\n        :param debug: Whether to output network trace logs to the logger. Default\n         is `False`.\n        :type debug: bool\n        :param http_proxy: HTTP proxy settings. This must be a dictionary with the following\n         keys: 'proxy_hostname' (str value) and 'proxy_port' (int value).\n         Additionally the following keys may also be present: 'username', 'password'.\n        :type http_proxy: dict[str, Any]\n        :param auth_timeout: The time in seconds to wait for a token to be authorized by the service.\n         The default value is 60 seconds. If set to 0, no timeout will be enforced from the client.\n        :type auth_timeout: int"
  },
  {
    "code": "def send_key(self, key):\n        if isinstance(key, Keys):\n            key = key.value\n        params = '<X_KeyEvent>{}</X_KeyEvent>'.format(key)\n        self.soap_request(URL_CONTROL_NRC, URN_REMOTE_CONTROL,\n                          'X_SendKey', params)",
    "docstring": "Send a key command to the TV."
  },
  {
    "code": "def update_repository_method_acl(namespace, method, snapshot_id, acl_updates):\n    uri = \"methods/{0}/{1}/{2}/permissions\".format(namespace,method,snapshot_id)\n    return __post(uri, json=acl_updates)",
    "docstring": "Set method permissions.\n\n    The method should exist in the methods repository.\n\n    Args:\n        namespace (str): Methods namespace\n        method (str): method name\n        snapshot_id (int): snapshot_id of the method\n        acl_updates (list(dict)): List of access control updates\n\n    Swagger:\n        https://api.firecloud.org/#!/Method_Repository/setMethodACL"
  },
  {
    "code": "def load_feedback():\n    result = {}\n    if os.path.exists(_feedback_file):\n        f = open(_feedback_file, 'r')\n        cont = f.read()\n        f.close()\n    else:\n        cont = '{}'\n    try:\n        result = json.loads(cont) if cont else {}\n    except ValueError as e:\n        result = {\"result\":\"crash\", \"text\":\"Feedback file has been modified by user !\"}\n    return result",
    "docstring": "Open existing feedback file"
  },
  {
    "code": "def without(self, other):\n        if not (self.maxdepth == other.maxdepth): raise AssertionError(\"Regions must have the same maxdepth\")\n        self._demote_all()\n        opd = set(other.get_demoted())\n        self.pixeldict[self.maxdepth].difference_update(opd)\n        self._renorm()\n        return",
    "docstring": "Subtract another Region by performing a difference operation on their pixlists.\n\n        Requires both regions to have the same maxdepth.\n\n        Parameters\n        ----------\n        other : :class:`AegeanTools.regions.Region`\n            The region to be combined."
  },
  {
    "code": "def fingerprint_target(self, target):\n    fingerprint = self.compute_fingerprint(target)\n    if fingerprint:\n      return '{fingerprint}-{name}'.format(fingerprint=fingerprint, name=type(self).__name__)\n    else:\n      return None",
    "docstring": "Consumers of subclass instances call this to get a fingerprint labeled with the name"
  },
  {
    "code": "def apply_ir_heuristics(irs, node):\n    irs = integrate_value_gas(irs)\n    irs = propagate_type_and_convert_call(irs, node)\n    irs = remove_unused(irs)\n    find_references_origin(irs)\n    return irs",
    "docstring": "Apply a set of heuristic to improve slithIR"
  },
  {
    "code": "def insert_entry(self, entry, taxids):\n        entry_dict = entry.attrib\n        entry_dict['created'] = datetime.strptime(entry_dict['created'], '%Y-%m-%d')\n        entry_dict['modified'] = datetime.strptime(entry_dict['modified'], '%Y-%m-%d')\n        taxid = self.get_taxid(entry)\n        if taxids is None or taxid in taxids:\n            entry_dict = self.update_entry_dict(entry, entry_dict, taxid)\n            entry_obj = models.Entry(**entry_dict)\n            del entry_dict\n            self.session.add(entry_obj)",
    "docstring": "Insert UniProt entry\"\n\n        :param entry: XML node entry\n        :param taxids: Optional[iter[int]] taxids: NCBI taxonomy IDs"
  },
  {
    "code": "def process_ticket(self):\n        try:\n            auth_req = self.root.getchildren()[1].getchildren()[0]\n            ticket = auth_req.getchildren()[0].text\n            ticket = models.Ticket.get(ticket)\n            if ticket.service != self.target:\n                raise SamlValidateError(\n                    u'AuthnFailed',\n                    u'TARGET %s does not match ticket service' % self.target\n                )\n            return ticket\n        except (IndexError, KeyError):\n            raise SamlValidateError(u'VersionMismatch')\n        except Ticket.DoesNotExist:\n            raise SamlValidateError(\n                    u'AuthnFailed',\n                    u'ticket %s should begin with PT- or ST-' % ticket\n            )\n        except (ServiceTicket.DoesNotExist, ProxyTicket.DoesNotExist):\n            raise SamlValidateError(u'AuthnFailed', u'ticket %s not found' % ticket)",
    "docstring": "validate ticket from SAML XML body\n\n            :raises: SamlValidateError: if the ticket is not found or not valid, or if we fail\n                to parse the posted XML.\n            :return: a ticket object\n            :rtype: :class:`models.Ticket<cas_server.models.Ticket>`"
  },
  {
    "code": "def group(requestContext, *seriesLists):\n    seriesGroup = []\n    for s in seriesLists:\n        seriesGroup.extend(s)\n    return seriesGroup",
    "docstring": "Takes an arbitrary number of seriesLists and adds them to a single\n    seriesList. This is used to pass multiple seriesLists to a function which\n    only takes one."
  },
  {
    "code": "def save(self, notes=None):\n        if notes:\n            self._changes['notes'] = notes\n        super(Issue, self).save()",
    "docstring": "Save all changes back to Redmine with optional notes."
  },
  {
    "code": "def get_tile_properties_by_layer(self, layer):\n        try:\n            assert (int(layer) >= 0)\n            layer = int(layer)\n        except (TypeError, AssertionError):\n            msg = \"Layer must be a positive integer.  Got {0} instead.\"\n            logger.debug(msg.format(type(layer)))\n            raise ValueError\n        p = product(range(self.width), range(self.height))\n        layergids = set(self.layers[layer].data[y][x] for x, y in p)\n        for gid in layergids:\n            try:\n                yield gid, self.tile_properties[gid]\n            except KeyError:\n                continue",
    "docstring": "Get the tile properties of each GID in layer\n\n        :param layer: layer number\n        :rtype: iterator of (gid, properties) tuples"
  },
  {
    "code": "def get_single_int_autoincrement_colname(table_: Table) -> Optional[str]:\n    n_autoinc = 0\n    int_autoinc_names = []\n    for col in table_.columns:\n        if col.autoincrement:\n            n_autoinc += 1\n            if is_sqlatype_integer(col.type):\n                int_autoinc_names.append(col.name)\n    if n_autoinc > 1:\n        log.warning(\"Table {!r} has {} autoincrement columns\",\n                    table_.name, n_autoinc)\n    if n_autoinc == 1 and len(int_autoinc_names) == 1:\n        return int_autoinc_names[0]\n    return None",
    "docstring": "If a table has a single integer ``AUTOINCREMENT`` column, this will\n    return its name; otherwise, ``None``.\n\n    - It's unlikely that a database has >1 ``AUTOINCREMENT`` field anyway, but\n      we should check.\n    - SQL Server's ``IDENTITY`` keyword is equivalent to MySQL's\n      ``AUTOINCREMENT``.\n    - Verify against SQL Server:\n\n      .. code-block:: sql\n\n        SELECT table_name, column_name\n        FROM information_schema.columns\n        WHERE COLUMNPROPERTY(OBJECT_ID(table_schema + '.' + table_name),\n                             column_name,\n                             'IsIdentity') = 1\n        ORDER BY table_name;\n\n      ... http://stackoverflow.com/questions/87747\n\n    - Also:\n\n      .. code-block:: sql\n\n        sp_columns 'tablename';\n\n      ... which is what SQLAlchemy does (``dialects/mssql/base.py``, in\n      :func:`get_columns`)."
  },
  {
    "code": "def get_target_from_spec(self, spec, relative_to=''):\n    return self.get_target(Address.parse(spec, relative_to=relative_to))",
    "docstring": "Converts `spec` into an address and returns the result of `get_target`\n\n    :API: public"
  },
  {
    "code": "def ftp_walk(ftpconn: FTP, rootpath=''):\n    current_directory = rootpath\n    try:\n        directories, files = directory_listing(ftpconn, current_directory)\n    except ftplib.error_perm:\n        return\n    yield current_directory, directories, files\n    for name in directories:\n        new_path = os.path.join(current_directory, name)\n        for entry in ftp_walk(ftpconn, rootpath=new_path):\n            yield entry\n    else:\n        return",
    "docstring": "Recursively traverse an ftp directory to discovery directory listing."
  },
  {
    "code": "def noisy_wrap(__func: Callable) -> Callable:\n    def wrapper(*args, **kwargs):\n        DebugPrint.enable()\n        try:\n            __func(*args, **kwargs)\n        finally:\n            DebugPrint.disable()\n    return wrapper",
    "docstring": "Decorator to enable DebugPrint for a given function.\n\n    Args:\n        __func: Function to wrap\n    Returns:\n        Wrapped function"
  },
  {
    "code": "def shrank(self, block=None, percent_diff=0, abs_diff=1):\n        if block is None:\n            block = self.block\n        cur_nets = len(block.logic)\n        net_goal = self.prev_nets * (1 - percent_diff) - abs_diff\n        less_nets = (cur_nets <= net_goal)\n        self.prev_nets = cur_nets\n        return less_nets",
    "docstring": "Returns whether a block has less nets than before\n\n        :param Block block: block to check (if changed)\n        :param Number percent_diff: percentage difference threshold\n        :param int abs_diff: absolute difference threshold\n        :return: boolean\n\n        This function checks whether the change in the number of\n        nets is greater than the percentage and absolute difference\n        thresholds."
  },
  {
    "code": "def advance(self):\n        self.cursor += 1\n        if self.cursor >= len(self.raw):\n            self.char = None\n        else:\n            self.char = self.raw[self.cursor]",
    "docstring": "Increments the cursor position."
  },
  {
    "code": "def insert_tile(self, tile_info):\n        for i, tile in enumerate(self.registered_tiles):\n            if tile.slot == tile_info.slot:\n                self.registered_tiles[i] = tile_info\n                return\n        self.registered_tiles.append(tile_info)",
    "docstring": "Add or replace an entry in the tile cache.\n\n        Args:\n            tile_info (TileInfo): The newly registered tile."
  },
  {
    "code": "def loglevel(level):\n    if isinstance(level, str):\n        level = getattr(logging, level.upper())\n    elif isinstance(level, int):\n        pass\n    else:\n        raise ValueError('{0!r} is not a proper log level.'.format(level))\n    return level",
    "docstring": "Convert any representation of `level` to an int appropriately.\n\n    :type level: int or str\n    :rtype: int\n\n    >>> loglevel('DEBUG') == logging.DEBUG\n    True\n    >>> loglevel(10)\n    10\n    >>> loglevel(None)\n    Traceback (most recent call last):\n      ...\n    ValueError: None is not a proper log level."
  },
  {
    "code": "def write_port(self, port, value):\n        if port == 'A':\n            self.GPIOA = value\n        elif port == 'B':\n            self.GPIOB = value\n        else:\n            raise AttributeError('Port {} does not exist, use A or B'.format(port))\n        self.sync()",
    "docstring": "Use a whole port as a bus and write a byte to it.\n\n        :param port: Name of the port ('A' or 'B')\n        :param value: Value to write (0-255)"
  },
  {
    "code": "def GetRequestFormatMode(request, method_metadata):\n  if request.path.startswith(\"/api/v2/\"):\n    return JsonMode.PROTO3_JSON_MODE\n  if request.args.get(\"strip_type_info\", \"\"):\n    return JsonMode.GRR_TYPE_STRIPPED_JSON_MODE\n  for http_method, unused_url, options in method_metadata.http_methods:\n    if (http_method == request.method and\n        options.get(\"strip_root_types\", False)):\n      return JsonMode.GRR_ROOT_TYPES_STRIPPED_JSON_MODE\n  return JsonMode.GRR_JSON_MODE",
    "docstring": "Returns JSON format mode corresponding to a given request and method."
  },
  {
    "code": "def read_ncstream_err(fobj):\n    err = read_proto_object(fobj, stream.Error)\n    raise RuntimeError(err.message)",
    "docstring": "Handle reading an NcStream error from a file-like object and raise as error."
  },
  {
    "code": "def kill_all_processes(self, check_alive=True, allow_graceful=False):\n        if ray_constants.PROCESS_TYPE_RAYLET in self.all_processes:\n            self._kill_process_type(\n                ray_constants.PROCESS_TYPE_RAYLET,\n                check_alive=check_alive,\n                allow_graceful=allow_graceful)\n        for process_type in list(self.all_processes.keys()):\n            self._kill_process_type(\n                process_type,\n                check_alive=check_alive,\n                allow_graceful=allow_graceful)",
    "docstring": "Kill all of the processes.\n\n        Note that This is slower than necessary because it calls kill, wait,\n        kill, wait, ... instead of kill, kill, ..., wait, wait, ...\n\n        Args:\n            check_alive (bool): Raise an exception if any of the processes were\n                already dead."
  },
  {
    "code": "def _validate_jpx_compatibility(self, boxes, compatibility_list):\n        JPX_IDS = ['asoc', 'nlst']\n        jpx_cl = set(compatibility_list)\n        for box in boxes:\n            if box.box_id in JPX_IDS:\n                if len(set(['jpx ', 'jpxb']).intersection(jpx_cl)) == 0:\n                    msg = (\"A JPX box requires that either 'jpx ' or 'jpxb' \"\n                           \"be present in the ftype compatibility list.\")\n                    raise RuntimeError(msg)\n            if hasattr(box, 'box') != 0:\n                self._validate_jpx_compatibility(box.box, compatibility_list)",
    "docstring": "If there is a JPX box then the compatibility list must also contain\n        'jpx '."
  },
  {
    "code": "def send_multipart(self, *args, **kwargs):\n        self.__in_send_multipart = True\n        try:\n            msg = super(GreenSocket, self).send_multipart(*args, **kwargs)\n        finally:\n            self.__in_send_multipart = False\n            self.__state_changed()\n        return msg",
    "docstring": "wrap send_multipart to prevent state_changed on each partial send"
  },
  {
    "code": "def SetExpression(self, expression):\n    if isinstance(expression, lexer.Expression):\n      self.args = [expression]\n    else:\n      raise errors.ParseError(\n          'Expected expression, got {0:s}.'.format(expression))",
    "docstring": "Set the expression."
  },
  {
    "code": "def _read_config(correlation_id, path, parameters):\n        value = YamlConfigReader(path)._read_object(correlation_id, parameters)\n        return ConfigParams.from_value(value)",
    "docstring": "Reads configuration from a file, parameterize it with given values and returns a new ConfigParams object.\n\n        :param correlation_id: (optional) transaction id to trace execution through call chain.\n\n        :param path: a path to configuration file.\n\n        :param parameters: values to parameters the configuration.\n\n        :return: ConfigParams configuration."
  },
  {
    "code": "def show_instance(name, call=None):\n    if call != 'action':\n        raise SaltCloudSystemExit(\n            'The show_instance action must be called with -a or --action.'\n        )\n    items = query(action='ve', command=name)\n    ret = {}\n    for item in items:\n        if 'text' in item.__dict__:\n            ret[item.tag] = item.text\n        else:\n            ret[item.tag] = item.attrib\n        if item._children:\n            ret[item.tag] = {}\n            children = item._children\n            for child in children:\n                ret[item.tag][child.tag] = child.attrib\n    __utils__['cloud.cache_node'](ret, __active_provider_name__, __opts__)\n    return ret",
    "docstring": "Show the details from Parallels concerning an instance"
  },
  {
    "code": "def view_pmap(token, dstore):\n    grp = token.split(':')[1]\n    pmap = {}\n    rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()\n    pgetter = getters.PmapGetter(dstore, rlzs_assoc)\n    pmap = pgetter.get_mean(grp)\n    return str(pmap)",
    "docstring": "Display the mean ProbabilityMap associated to a given source group name"
  },
  {
    "code": "def ll(self, folder=\"\", begin_from_file=\"\", num=-1, all_grant_data=False):\n        return self.ls(folder=folder, begin_from_file=begin_from_file, num=num, get_grants=True, all_grant_data=all_grant_data)",
    "docstring": "Get the list of files and permissions from S3.\n\n        This is similar to LL (ls -lah) in Linux: List of files with permissions.\n\n        Parameters\n        ----------\n\n        folder : string\n            Path to file on S3\n\n        num: integer, optional\n            number of results to return, by default it returns all results.\n\n        begin_from_file : string, optional\n            which file to start from on S3.\n            This is usedful in case you are iterating over lists of files and you need to page the result by\n            starting listing from a certain file and fetching certain num (number) of files.\n\n        all_grant_data : Boolean, optional\n            More detailed file permission data will be returned.\n\n        Examples\n        --------\n\n            >>> from s3utils import S3utils\n            >>> s3utils = S3utils(\n            ... AWS_ACCESS_KEY_ID = 'your access key',\n            ... AWS_SECRET_ACCESS_KEY = 'your secret key',\n            ... AWS_STORAGE_BUCKET_NAME = 'your bucket name',\n            ... S3UTILS_DEBUG_LEVEL = 1,  #change it to 0 for less verbose\n            ... )\n            >>> import json\n            >>> # We use json.dumps to print the results more readable:\n            >>> my_folder_stuff = s3utils.ll(\"/test/\")\n            >>> print(json.dumps(my_folder_stuff, indent=2))\n            {\n              \"test/myfolder/\": [\n                {\n                  \"name\": \"owner's name\",\n                  \"permission\": \"FULL_CONTROL\"\n                }\n              ],\n              \"test/myfolder/em/\": [\n                {\n                  \"name\": \"owner's name\",\n                  \"permission\": \"FULL_CONTROL\"\n                }\n              ],\n              \"test/myfolder/hoho/\": [\n                {\n                  \"name\": \"owner's name\",\n                  \"permission\": \"FULL_CONTROL\"\n                }\n              ],\n              \"test/myfolder/hoho/.DS_Store\": [\n                {\n                  \"name\": \"owner's name\",\n                  \"permission\": \"FULL_CONTROL\"\n                },\n                {\n                  \"name\": null,\n                  \"permission\": \"READ\"\n                }\n              ],\n              \"test/myfolder/hoho/haha/\": [\n                {\n                  \"name\": \"owner's name\",\n                  \"permission\": \"FULL_CONTROL\"\n                }\n              ],\n              \"test/myfolder/hoho/haha/ff\": [\n                {\n                  \"name\": \"owner's name\",\n                  \"permission\": \"FULL_CONTROL\"\n                },\n                {\n                  \"name\": null,\n                  \"permission\": \"READ\"\n                }\n              ],\n              \"test/myfolder/hoho/photo.JPG\": [\n                {\n                  \"name\": \"owner's name\",\n                  \"permission\": \"FULL_CONTROL\"\n                },\n                {\n                  \"name\": null,\n                  \"permission\": \"READ\"\n                }\n              ],\n            }"
  },
  {
    "code": "def fd_sine_gaussian(amp, quality, central_frequency, fmin, fmax, delta_f):\n    kmin = int(round(fmin / delta_f))\n    kmax = int(round(fmax / delta_f))\n    f = numpy.arange(kmin, kmax) * delta_f\n    tau = quality / 2 / numpy.pi / central_frequency\n    A = amp * numpy.pi ** 0.5 / 2 * tau\n    d = A * numpy.exp(-(numpy.pi  * tau  * (f - central_frequency))**2.0)\n    d *= (1 + numpy.exp(-quality ** 2.0 * f / central_frequency))\n    v = numpy.zeros(kmax, dtype=numpy.complex128)\n    v[kmin:kmax] = d[:]\n    return pycbc.types.FrequencySeries(v, delta_f=delta_f)",
    "docstring": "Generate a Fourier domain sine-Gaussian\n\n    Parameters\n    ----------\n    amp: float\n        Amplitude of the sine-Gaussian\n    quality: float\n        The quality factor\n    central_frequency: float\n        The central frequency of the sine-Gaussian\n    fmin: float\n        The minimum frequency to generate the sine-Gaussian. This determines\n        the length of the output vector.\n    fmax: float\n        The maximum frequency to generate the sine-Gaussian\n    delta_f: float\n        The size of the frequency step\n\n    Returns\n    -------\n    sg: pycbc.types.Frequencyseries\n        A Fourier domain sine-Gaussian"
  },
  {
    "code": "def from_xmldict(cls, xml_dict):\n        name = xml_dict['creatorName']\n        kwargs = {}\n        if 'affiliation' in xml_dict:\n            kwargs['affiliation'] = xml_dict['affiliation']\n        return cls(name, **kwargs)",
    "docstring": "Create an `Author` from a datacite3 metadata converted by\n        `xmltodict`.\n\n        Parameters\n        ----------\n        xml_dict : :class:`collections.OrderedDict`\n            A `dict`-like object mapping XML content for a single record (i.e.,\n            the contents of the ``record`` tag in OAI-PMH XML). This dict is\n            typically generated from :mod:`xmltodict`."
  },
  {
    "code": "def plot_pauli_transfer_matrix(ptransfermatrix, ax, labels, title):\n    im = ax.imshow(ptransfermatrix, interpolation=\"nearest\", cmap=rigetti_3_color_cm, vmin=-1,\n                   vmax=1)\n    dim = len(labels)\n    plt.colorbar(im, ax=ax)\n    ax.set_xticks(range(dim))\n    ax.set_xlabel(\"Input Pauli Operator\", fontsize=20)\n    ax.set_yticks(range(dim))\n    ax.set_ylabel(\"Output Pauli Operator\", fontsize=20)\n    ax.set_title(title, fontsize=25)\n    ax.set_xticklabels(labels, rotation=45)\n    ax.set_yticklabels(labels)\n    ax.grid(False)\n    return ax",
    "docstring": "Visualize the Pauli Transfer Matrix of a process.\n\n    :param numpy.ndarray ptransfermatrix: The Pauli Transfer Matrix\n    :param ax: The matplotlib axes.\n    :param labels: The labels for the operator basis states.\n    :param title: The title for the plot\n    :return: The modified axis object.\n    :rtype: AxesSubplot"
  },
  {
    "code": "def cardinality(self):\n\t\tnum_strings = {}\n\t\tdef get_num_strings(state):\n\t\t\tif self.islive(state):\n\t\t\t\tif state in num_strings:\n\t\t\t\t\tif num_strings[state] is None:\n\t\t\t\t\t\traise OverflowError(state)\n\t\t\t\t\treturn num_strings[state]\n\t\t\t\tnum_strings[state] = None\n\t\t\t\tn = 0\n\t\t\t\tif state in self.finals:\n\t\t\t\t\tn += 1\n\t\t\t\tif state in self.map:\n\t\t\t\t\tfor symbol in self.map[state]:\n\t\t\t\t\t\tn += get_num_strings(self.map[state][symbol])\n\t\t\t\tnum_strings[state] = n\n\t\t\telse:\n\t\t\t\tnum_strings[state] = 0\n\t\t\treturn num_strings[state]\n\t\treturn get_num_strings(self.initial)",
    "docstring": "Consider the FSM as a set of strings and return the cardinality of that\n\t\t\tset, or raise an OverflowError if there are infinitely many"
  },
  {
    "code": "def get_data_source_bulk_request(self, rids, limit=5):\n        headers = {\n                'User-Agent': self.user_agent(),\n                'Content-Type': self.content_type()\n        }\n        headers.update(self.headers())\n        r = requests.get(   self.portals_url()\n                            +'/data-sources/['\n                            +\",\".join(rids)\n                            +']/data?limit='+str(limit),\n                            headers=headers, auth=self.auth())\n        if HTTP_STATUS.OK == r.status_code:\n            return r.json()\n        else:\n            print(\"Something went wrong: <{0}>: {1}\".format(\n                        r.status_code, r.reason))\n            return {}",
    "docstring": "This grabs each datasource and its multiple datapoints for a particular device."
  },
  {
    "code": "def json_dumps(self, data, **options):\n        params = {'sort_keys': True, 'indent': 2}\n        params.update(options)\n        if json.__version__.split('.') >= ['2', '1', '3']:\n            params.update({'use_decimal': False})\n        return json.dumps(data, cls=DjangoJSONEncoder, **params)",
    "docstring": "Wrapper around `json.dumps` that uses a special JSON encoder."
  },
  {
    "code": "def error(code, message, **kwargs):\n        assert code in Logger._error_code_to_exception\n        exc_type, domain = Logger._error_code_to_exception[code]\n        exc = exc_type(message, **kwargs)\n        Logger._log(code, exc.message, ERROR, domain)\n        raise exc",
    "docstring": "Call this to raise an exception and have it stored in the journal"
  },
  {
    "code": "def _get_elements(self, site):\n        try:\n            if isinstance(site.specie, Element):\n                return [site.specie]\n            return [Element(site.specie)]\n        except:\n            return site.species.elements",
    "docstring": "Get the list of elements for a Site\n\n        Args:\n             site (Site): Site to assess\n        Returns:\n            [Element]: List of elements"
  },
  {
    "code": "def yaml_dump_hook(cfg, text: bool=False):\n    data = cfg.config.dump()\n    if not text:\n        yaml.dump(data, cfg.fd, Dumper=cfg.dumper, default_flow_style=False)\n    else:\n        return yaml.dump(data, Dumper=cfg.dumper, default_flow_style=False)",
    "docstring": "Dumps all the data into a YAML file."
  },
  {
    "code": "def user_exists(self, username):\n        path = \"/users/{}\".format(username)\n        return self._get(path).ok",
    "docstring": "Returns whether a user with username ``username`` exists.\n\n        :param str username: username of user\n        :return: whether a user with the specified username exists\n        :rtype: bool\n        :raises NetworkFailure: if there is an error communicating with the server\n        :return:"
  },
  {
    "code": "def create_url(artist, song):\n    return (__BASE_URL__ +\n            '/wiki/{artist}:{song}'.format(artist=urlize(artist),\n                                           song=urlize(song)))",
    "docstring": "Create the URL in the LyricWikia format"
  },
  {
    "code": "def detach(self):\n        if self.parent is not None:\n            if self in self.parent.children:\n                self.parent.children.remove(self)\n            self.parent = None\n        return self",
    "docstring": "Detach from parent.\n        @return: This element removed from its parent's\n            child list and I{parent}=I{None}\n        @rtype: L{Element}"
  },
  {
    "code": "def abort(self):\n    if self.id == ApiCommand.SYNCHRONOUS_COMMAND_ID:\n      return self\n    path = self._path() + '/abort'\n    resp = self._get_resource_root().post(path)\n    return ApiCommand.from_json_dict(resp, self._get_resource_root())",
    "docstring": "Abort a running command.\n\n    @return: A new ApiCommand object with the updated information."
  },
  {
    "code": "def get_squares(self, player=None):\n        if player:\n            return [k for k, v in enumerate(self.squares) if v == player]\n        else:\n            return self.squares",
    "docstring": "squares that belong to a player"
  },
  {
    "code": "def __fetch_heatmap_data_from_profile(self):\n        with open(self.pyfile.path, \"r\") as file_to_read:\n            for line in file_to_read:\n                self.pyfile.lines.append(\"  \" + line.strip(\"\\n\"))\n        self.pyfile.length = len(self.pyfile.lines)\n        line_profiles = self.__get_line_profile_data()\n        arr = []\n        for line_num in range(1, self.pyfile.length + 1):\n            if line_num in line_profiles:\n                line_times = [\n                    ltime for _, ltime in line_profiles[line_num].values()\n                ]\n                arr.append([sum(line_times)])\n            else:\n                arr.append([0.0])\n        self.pyfile.data = np.array(arr)",
    "docstring": "Method to create heatmap data from profile information."
  },
  {
    "code": "def create_set(self, set_id, etype, entities):\n        if etype not in {\"sample\", \"pair\", \"participant\"}:\n            raise ValueError(\"Unsupported entity type:\" + str(etype))\n        payload = \"membership:\" + etype + \"_set_id\\t\" + etype + \"_id\\n\"\n        for e in entities:\n            if e.etype != etype:\n                msg =  \"Entity type '\" + e.etype + \"' does not match \"\n                msg += \"set type '\" + etype + \"'\"\n                raise ValueError(msg)\n            payload += set_id + '\\t' + e.entity_id + '\\n'\n        r = fapi.upload_entities(self.namespace, self.name,\n                                    payload, self.api_url)\n        fapi._check_response_code(r, 201)",
    "docstring": "Create a set of entities and upload to FireCloud.\n\n        Args\n            etype (str): one of {\"sample, \"pair\", \"participant\"}\n            entities: iterable of firecloud.Entity objects."
  },
  {
    "code": "def _to_unicode(self, data, encoding, errors='strict'):\n    if (len(data) >= 4) and (data[:2] == '\\xfe\\xff') and (data[2:4] != '\\x00\\x00'):\n        encoding = 'utf-16be'\n        data = data[2:]\n    elif (len(data) >= 4) and (data[:2] == '\\xff\\xfe') and (data[2:4] != '\\x00\\x00'):\n        encoding = 'utf-16le'\n        data = data[2:]\n    elif data[:3] == '\\xef\\xbb\\xbf':\n        encoding = 'utf-8'\n        data = data[3:]\n    elif data[:4] == '\\x00\\x00\\xfe\\xff':\n        encoding = 'utf-32be'\n        data = data[4:]\n    elif data[:4] == '\\xff\\xfe\\x00\\x00':\n        encoding = 'utf-32le'\n        data = data[4:]\n    newdata = unicode(data, encoding, errors)\n    return newdata",
    "docstring": "Given a string and its encoding, decodes the string into Unicode.\n    %encoding is a string recognized by encodings.aliases"
  },
  {
    "code": "def get_collection(source, name, collection_format, default):\n    if collection_format in COLLECTION_SEP:\n        separator = COLLECTION_SEP[collection_format]\n        value = source.get(name, None)\n        if value is None:\n            return default\n        return value.split(separator)\n    if collection_format == 'brackets':\n        return source.getall(name + '[]', default)\n    else:\n        return source.getall(name, default)",
    "docstring": "get collection named `name` from the given `source` that\n    formatted accordingly to `collection_format`."
  },
  {
    "code": "def close(self):\n        if self.is_worker():\n            return\n        for worker in self.workers:\n            self.comm.send(None, worker, 0)",
    "docstring": "Tell all the workers to quit."
  },
  {
    "code": "def get_param_names(cls):\n        return [m[0] for m in inspect.getmembers(cls) \\\n            if type(m[1]) == property]",
    "docstring": "Returns a list of plottable CBC parameter variables"
  },
  {
    "code": "def getWifiState(self):\n        result = self.device.shell('dumpsys wifi')\n        if result:\n            state = result.splitlines()[0]\n            if self.WIFI_IS_ENABLED_RE.match(state):\n                return self.WIFI_STATE_ENABLED\n            elif self.WIFI_IS_DISABLED_RE.match(state):\n                return self.WIFI_STATE_DISABLED\n        print >> sys.stderr, \"UNKNOWN WIFI STATE:\", state\n        return self.WIFI_STATE_UNKNOWN",
    "docstring": "Gets the Wi-Fi enabled state.\n\n        @return: One of WIFI_STATE_DISABLED, WIFI_STATE_DISABLING, WIFI_STATE_ENABLED, WIFI_STATE_ENABLING, WIFI_STATE_UNKNOWN"
  },
  {
    "code": "def register(model, fields, restrict_to=None, manager=None, properties=None, contexts=None):\n    if not contexts:\n        contexts = {}\n    global _REGISTRY\n    _REGISTRY[model] = {\n        'fields': fields,\n        'contexts': contexts,\n        'restrict_to': restrict_to,\n        'manager': manager,\n        'properties': properties,\n    }\n    for field in fields:\n        setattr(model, field, VinaigretteDescriptor(field, contexts.get(field, None)))\n    model.untranslated = lambda self, fieldname: self.__dict__[fieldname]\n    pre_save.connect(_vinaigrette_pre_save, sender=model)\n    post_save.connect(_vinaigrette_post_save, sender=model)",
    "docstring": "Tell vinaigrette which fields on a Django model should be translated.\n\n    Arguments:\n    model -- The relevant model class\n    fields -- A list or tuple of field names. e.g. ['name', 'nickname']\n    restrict_to -- Optional. A django.db.models.Q object representing the subset\n        of objects to collect translation strings from.\n    manager -- Optional. A reference to a manager -- e.g. Person.objects -- to use\n        when collecting translation strings.\n    properties -- A dictionary of \"read only\" properties that are composed by more that one field\n                  e.g. {'full_name': ['first_name', 'last_name']}\n    contexts -- A dictionary including any (pgettext) context that may need\n                to be applied to each field.\n                e.g. {'name': 'db category name', 'description': 'db detailed category description'}\n\n    Note that both restrict_to and manager are only used when collecting translation\n    strings. Gettext lookups will always be performed on relevant fields for all\n    objects on registered models."
  },
  {
    "code": "def open(filename, frame='unspecified'):\n        data = BagOfPoints.load_data(filename)\n        return Point(data, frame)",
    "docstring": "Create a Point from data saved in a file.\n\n        Parameters\n        ----------\n        filename : :obj:`str`\n            The file to load data from.\n\n        frame : :obj:`str`\n            The frame to apply to the created point.\n\n        Returns\n        -------\n        :obj:`Point`\n            A point created from the data in the file."
  },
  {
    "code": "def _normalize_number_values(self, parameters):\n        for key, value in parameters.items():\n            if isinstance(value, (int, float)):\n                parameters[key] = str(Decimal(value).normalize(self._context))",
    "docstring": "Assures equal precision for all number values"
  },
  {
    "code": "def get_index_line(self,lnum):\n    if lnum < 1:\n      sys.stderr.write(\"ERROR: line number should be greater than zero\\n\")\n      sys.exit()\n    elif lnum > len(self._lines):\n      sys.stderr.write(\"ERROR: too far this line nuber is not in index\\n\")\n      sys.exit()\n    return self._lines[lnum-1]",
    "docstring": "Take the 1-indexed line number and return its index information"
  },
  {
    "code": "def get_parent_device(self):\r\n        if not self.parent_instance_id:\r\n            return \"\"\r\n        dev_buffer_type = winapi.c_tchar * MAX_DEVICE_ID_LEN\r\n        dev_buffer = dev_buffer_type()\r\n        try:\r\n            if winapi.CM_Get_Device_ID(self.parent_instance_id, byref(dev_buffer),\r\n                    MAX_DEVICE_ID_LEN, 0) == 0:\n                return dev_buffer.value\r\n            return \"\"\r\n        finally:\r\n            del dev_buffer\r\n            del dev_buffer_type",
    "docstring": "Retreive parent device string id"
  },
  {
    "code": "def auth_password(self, username, password, event=None, fallback=True):\n        if (not self.active) or (not self.initial_kex_done):\n            raise SSHException(\"No existing session\")\n        if event is None:\n            my_event = threading.Event()\n        else:\n            my_event = event\n        self.auth_handler = AuthHandler(self)\n        self.auth_handler.auth_password(username, password, my_event)\n        if event is not None:\n            return []\n        try:\n            return self.auth_handler.wait_for_response(my_event)\n        except BadAuthenticationType as e:\n            if not fallback or (\"keyboard-interactive\" not in e.allowed_types):\n                raise\n            try:\n                def handler(title, instructions, fields):\n                    if len(fields) > 1:\n                        raise SSHException(\"Fallback authentication failed.\")\n                    if len(fields) == 0:\n                        return []\n                    return [password]\n                return self.auth_interactive(username, handler)\n            except SSHException:\n                raise e",
    "docstring": "Authenticate to the server using a password.  The username and password\n        are sent over an encrypted link.\n\n        If an ``event`` is passed in, this method will return immediately, and\n        the event will be triggered once authentication succeeds or fails.  On\n        success, `is_authenticated` will return ``True``.  On failure, you may\n        use `get_exception` to get more detailed error information.\n\n        Since 1.1, if no event is passed, this method will block until the\n        authentication succeeds or fails.  On failure, an exception is raised.\n        Otherwise, the method simply returns.\n\n        Since 1.5, if no event is passed and ``fallback`` is ``True`` (the\n        default), if the server doesn't support plain password authentication\n        but does support so-called \"keyboard-interactive\" mode, an attempt\n        will be made to authenticate using this interactive mode.  If it fails,\n        the normal exception will be thrown as if the attempt had never been\n        made.  This is useful for some recent Gentoo and Debian distributions,\n        which turn off plain password authentication in a misguided belief\n        that interactive authentication is \"more secure\".  (It's not.)\n\n        If the server requires multi-step authentication (which is very rare),\n        this method will return a list of auth types permissible for the next\n        step.  Otherwise, in the normal case, an empty list is returned.\n\n        :param str username: the username to authenticate as\n        :param basestring password: the password to authenticate with\n        :param .threading.Event event:\n            an event to trigger when the authentication attempt is complete\n            (whether it was successful or not)\n        :param bool fallback:\n            ``True`` if an attempt at an automated \"interactive\" password auth\n            should be made if the server doesn't support normal password auth\n        :return:\n            list of auth types permissible for the next stage of\n            authentication (normally empty)\n\n        :raises:\n            `.BadAuthenticationType` -- if password authentication isn't\n            allowed by the server for this user (and no event was passed in)\n        :raises:\n            `.AuthenticationException` -- if the authentication failed (and no\n            event was passed in)\n        :raises: `.SSHException` -- if there was a network error"
  },
  {
    "code": "def _discover(self):\n        for ep in pkg_resources.iter_entry_points('yamlsettings10'):\n            ext = ep.load()\n            if callable(ext):\n                ext = ext()\n            self.add(ext)",
    "docstring": "Find and install all extensions"
  },
  {
    "code": "def by_email_address(cls, email):\n        return DBSession.query(cls).filter_by(email_address=email).first()",
    "docstring": "Return the user object whose email address is ``email``."
  },
  {
    "code": "def LogLikelihood(self, data):\n        m = len(data)\n        if self.n < m:\n            return float('-inf')\n        x = self.Random()\n        y = numpy.log(x[:m]) * data\n        return y.sum()",
    "docstring": "Computes the log likelihood of the data.\n\n        Selects a random vector of probabilities from this distribution.\n\n        Returns: float log probability"
  },
  {
    "code": "def safe_translation_getter(self, field, default=None, language_code=None, any_language=False):\n        meta = self._parler_meta._get_extension_by_field(field)\n        if language_code and language_code != self._current_language:\n            try:\n                tr_model = self._get_translated_model(language_code, meta=meta, use_fallback=True)\n                return getattr(tr_model, field)\n            except TranslationDoesNotExist:\n                pass\n        else:\n            try:\n                return getattr(self, field)\n            except TranslationDoesNotExist:\n                pass\n        if any_language:\n            translation = self._get_any_translated_model(meta=meta)\n            if translation is not None:\n                try:\n                    return getattr(translation, field)\n                except KeyError:\n                    pass\n        if callable(default):\n            return default()\n        else:\n            return default",
    "docstring": "Fetch a translated property, and return a default value\n        when both the translation and fallback language are missing.\n\n        When ``any_language=True`` is used, the function also looks\n        into other languages to find a suitable value. This feature can be useful\n        for \"title\" attributes for example, to make sure there is at least something being displayed.\n        Also consider using ``field = TranslatedField(any_language=True)`` in the model itself,\n        to make this behavior the default for the given field.\n\n        .. versionchanged 1.5:: The *default* parameter may also be a callable."
  },
  {
    "code": "def str2hashalgo(description):\n    algo = getattr(hashlib, description.lower(), None)\n    if not callable(algo):\n        raise ValueError('Unknown hash algorithm %s' % description)\n    return algo",
    "docstring": "Convert the name of a hash algorithm as described in the OATH\n       specifications, to a python object handling the digest algorithm\n       interface, PEP-xxx.\n\n       :param description\n           the name of the hash algorithm, example\n       :rtype: a hash algorithm class constructor"
  },
  {
    "code": "def get_or_create_candidate_election(\n        self, row, election, candidate, party\n    ):\n        return election.update_or_create_candidate(\n            candidate, party.aggregate_candidates, row[\"uncontested\"]\n        )",
    "docstring": "For a given election, this function updates or creates the\n        CandidateElection object using the model method on the election."
  },
  {
    "code": "def get_cameras_rules(self):\n        resource = \"rules\"\n        rules_event = self.publish_and_get_event(resource)\n        if rules_event:\n            return rules_event.get('properties')\n        return None",
    "docstring": "Return the camera rules."
  },
  {
    "code": "def recursive(self):\n        for m in self.members.values():\n            if m.kind is not None and m.kind.lower() == self.name.lower():\n                return True\n        else:\n            return False",
    "docstring": "When True, this CustomType has at least one member that is of the same\n        type as itself."
  },
  {
    "code": "def ip(addr, version=None):\n    addr_obj = IPAddress(addr)\n    if version and addr_obj.version != version:\n        raise ValueError(\"{} is not an ipv{} address\".format(addr, version))\n    return py23_compat.text_type(addr_obj)",
    "docstring": "Converts a raw string to a valid IP address. Optional version argument will detect that \\\n    object matches specified version.\n\n    Motivation: the groups of the IP addreses may contain leading zeros. IPv6 addresses can \\\n    contain sometimes uppercase characters. E.g.: 2001:0dB8:85a3:0000:0000:8A2e:0370:7334 has \\\n    the same logical value as 2001:db8:85a3::8a2e:370:7334. However, their values as strings are \\\n    not the same.\n\n    :param raw: the raw string containing the value of the IP Address\n    :param version: (optional) insist on a specific IP address version.\n    :type version: int.\n    :return: a string containing the IP Address in a standard format (no leading zeros, \\\n    zeros-grouping, lowercase)\n\n    Example:\n\n    .. code-block:: python\n\n        >>> ip('2001:0dB8:85a3:0000:0000:8A2e:0370:7334')\n        u'2001:db8:85a3::8a2e:370:7334'"
  },
  {
    "code": "def _try_convert_to_int_index(cls, data, copy, name, dtype):\n        from .numeric import Int64Index, UInt64Index\n        if not is_unsigned_integer_dtype(dtype):\n            try:\n                res = data.astype('i8', copy=False)\n                if (res == data).all():\n                    return Int64Index(res, copy=copy, name=name)\n            except (OverflowError, TypeError, ValueError):\n                pass\n        try:\n            res = data.astype('u8', copy=False)\n            if (res == data).all():\n                return UInt64Index(res, copy=copy, name=name)\n        except (OverflowError, TypeError, ValueError):\n            pass\n        raise ValueError",
    "docstring": "Attempt to convert an array of data into an integer index.\n\n        Parameters\n        ----------\n        data : The data to convert.\n        copy : Whether to copy the data or not.\n        name : The name of the index returned.\n\n        Returns\n        -------\n        int_index : data converted to either an Int64Index or a\n                    UInt64Index\n\n        Raises\n        ------\n        ValueError if the conversion was not successful."
  },
  {
    "code": "def dist_calc(loc1, loc2):\n    R = 6371.009\n    dlat = np.radians(abs(loc1[0] - loc2[0]))\n    dlong = np.radians(abs(loc1[1] - loc2[1]))\n    ddepth = abs(loc1[2] - loc2[2])\n    mean_lat = np.radians((loc1[0] + loc2[0]) / 2)\n    dist = R * np.sqrt(dlat ** 2 + (np.cos(mean_lat) * dlong) ** 2)\n    dist = np.sqrt(dist ** 2 + ddepth ** 2)\n    return dist",
    "docstring": "Function to calculate the distance in km between two points.\n\n    Uses the flat Earth approximation. Better things are available for this,\n    like `gdal <http://www.gdal.org/>`_.\n\n    :type loc1: tuple\n    :param loc1: Tuple of lat, lon, depth (in decimal degrees and km)\n    :type loc2: tuple\n    :param loc2: Tuple of lat, lon, depth (in decimal degrees and km)\n\n    :returns: Distance between points in km.\n    :rtype: float"
  },
  {
    "code": "def export_subprocess_info(bpmn_diagram, subprocess_params, output_element):\n        output_element.set(consts.Consts.triggered_by_event, subprocess_params[consts.Consts.triggered_by_event])\n        if consts.Consts.default in subprocess_params and subprocess_params[consts.Consts.default] is not None:\n            output_element.set(consts.Consts.default, subprocess_params[consts.Consts.default])\n        subprocess_id = subprocess_params[consts.Consts.id]\n        nodes = bpmn_diagram.get_nodes_list_by_process_id(subprocess_id)\n        for node in nodes:\n            node_id = node[0]\n            params = node[1]\n            BpmnDiagramGraphExport.export_node_data(bpmn_diagram, node_id, params, output_element)\n        flows = bpmn_diagram.get_flows_list_by_process_id(subprocess_id)\n        for flow in flows:\n            params = flow[2]\n            BpmnDiagramGraphExport.export_flow_process_data(params, output_element)",
    "docstring": "Adds Subprocess node attributes to exported XML element\n\n        :param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram,\n        :param subprocess_params: dictionary with given subprocess parameters,\n        :param output_element: object representing BPMN XML 'subprocess' element."
  },
  {
    "code": "def load_csv(path, delimiter=','):\n    try:\n        with open(path, 'rb') as csvfile:\n            reader = DictReader(csvfile, delimiter=delimiter)\n            for row in reader:\n                yield row\n    except (OSError, IOError):\n        raise ClientException(\"File not found: {}\".format(path))",
    "docstring": "Load CSV file from path and yield CSV rows\n\n    Usage:\n\n    for row in load_csv('/path/to/file'):\n        print(row)\n    or\n    list(load_csv('/path/to/file'))\n\n    :param path: file path\n    :param delimiter: CSV delimiter\n    :return: a generator where __next__ is a row of the CSV"
  },
  {
    "code": "def set_servers(self, servers):\n        if isinstance(servers, six.string_types):\n            servers = [servers]\n        assert servers, \"No memcached servers supplied\"\n        self._servers = [Protocol(\n            server=server,\n            username=self.username,\n            password=self.password,\n            compression=self.compression,\n            socket_timeout=self.socket_timeout,\n            pickle_protocol=self.pickle_protocol,\n            pickler=self.pickler,\n            unpickler=self.unpickler,\n        ) for server in servers]",
    "docstring": "Iter to a list of servers and instantiate Protocol class.\n\n        :param servers: A list of servers\n        :type servers: list\n        :return: Returns nothing\n        :rtype: None"
  },
  {
    "code": "def _create_extractors(col_params):\n  result = []\n  for col_param in col_params:\n    result.append(_create_extractor(col_param))\n  return result",
    "docstring": "Creates extractors to extract properties corresponding to 'col_params'.\n\n  Args:\n    col_params: List of ListSessionGroupsRequest.ColParam protobufs.\n  Returns:\n    A list of extractor functions. The ith element in the\n    returned list extracts the column corresponding to the ith element of\n    _request.col_params"
  },
  {
    "code": "def _cont_norm_running_quantile_regions_mp(wl, fluxes, ivars, q, delta_lambda,\n                                           ranges, n_proc=2, verbose=False):\n    print(\"contnorm.py: continuum norm using running quantile\")\n    print(\"Taking spectra in %s chunks\" % len(ranges))\n    nchunks = len(ranges)\n    norm_fluxes = np.zeros(fluxes.shape)\n    norm_ivars = np.zeros(ivars.shape)\n    for i in xrange(nchunks):\n        chunk = ranges[i, :]\n        start = chunk[0]\n        stop = chunk[1]\n        if verbose:\n            print('@Bo Zhang: Going to normalize Chunk [%d/%d], pixel:[%d, %d] ...'\n                  % (i+1, nchunks, start, stop))\n        output = _cont_norm_running_quantile_mp(\n            wl[start:stop], fluxes[:, start:stop],\n            ivars[:, start:stop], q, delta_lambda,\n            n_proc=n_proc, verbose=verbose)\n        norm_fluxes[:, start:stop] = output[0]\n        norm_ivars[:, start:stop] = output[1]\n    return norm_fluxes, norm_ivars",
    "docstring": "Perform continuum normalization using running quantile, for spectrum\n    that comes in chunks.\n\n    The same as _cont_norm_running_quantile_regions(),\n    but using multi-processing.\n\n    Bo Zhang (NAOC)"
  },
  {
    "code": "def load_labeled_events(filename, delimiter=r'\\s+'):\n    r\n    events, labels = load_delimited(filename, [float, str], delimiter)\n    events = np.array(events)\n    try:\n        util.validate_events(events)\n    except ValueError as error:\n        warnings.warn(error.args[0])\n    return events, labels",
    "docstring": "r\"\"\"Import labeled time-stamp events from an annotation file.  The file should\n    consist of two columns; the first having numeric values corresponding to\n    the event times and the second having string labels for each event.  This\n    is primarily useful for processing labeled events which lack duration, such\n    as beats with metric beat number or onsets with an instrument label.\n\n    Parameters\n    ----------\n    filename : str\n        Path to the annotation file\n    delimiter : str\n        Separator regular expression.\n        By default, lines will be split by any amount of whitespace.\n\n    Returns\n    -------\n    event_times : np.ndarray\n        array of event times (float)\n    labels : list of str\n        list of labels"
  },
  {
    "code": "def load_profile(self, profile):\n        profile_path = os.path.join(\n            self.root_directory, 'minimum_needs', profile + '.json')\n        self.read_from_file(profile_path)",
    "docstring": "Load a specific profile into the current minimum needs.\n\n        :param profile: The profile's name\n        :type profile: basestring, str"
  },
  {
    "code": "def _mapping(self):\n        return (self.__search_client.get(\n                    \"/unstable/index/{}/mapping\".format(mdf_toolbox.translate_index(self.index)))\n                [\"mappings\"])",
    "docstring": "Fetch the entire mapping for the specified index.\n\n        Returns:\n            dict: The full mapping for the index."
  },
  {
    "code": "def route_to_alt_domain(request, url):\n    alternative_domain = request.registry.settings.get(\"pyramid_notebook.alternative_domain\", \"\").strip()\n    if alternative_domain:\n        url = url.replace(request.host_url, alternative_domain)\n    return url",
    "docstring": "Route URL to a different subdomain.\n\n    Used to rewrite URLs to point to websocket serving domain."
  },
  {
    "code": "def terminate(library, session, degree, job_id):\n    return library.viTerminate(session, degree, job_id)",
    "docstring": "Requests a VISA session to terminate normal execution of an operation.\n\n    Corresponds to viTerminate function of the VISA library.\n\n    :param library: the visa library wrapped by ctypes.\n    :param session: Unique logical identifier to a session.\n    :param degree: Constants.NULL\n    :param job_id: Specifies an operation identifier.\n    :return: return value of the library call.\n    :rtype: :class:`pyvisa.constants.StatusCode`"
  },
  {
    "code": "def _handleSelectAllAxes(self, evt):\n        if len(self._axisId) == 0:\n            return\n        for i in range(len(self._axisId)):\n            self._menu.Check(self._axisId[i], True)\n        self._toolbar.set_active(self.getActiveAxes())\n        evt.Skip()",
    "docstring": "Called when the 'select all axes' menu item is selected."
  },
  {
    "code": "def find_model(model_name, apps=settings.INSTALLED_APPS, fuzziness=0):\n    if '/' in model_name:\n        return model_name\n    if not apps and isinstance(model_name, basestring) and '.' in model_name:\n        apps = [model_name.split('.')[0]]\n    apps = util.listify(apps or settings.INSTALLED_APPS)\n    for app in apps:\n        model = get_model(model=model_name, app=app, fuzziness=fuzziness)\n        if model:\n            return model\n    return None",
    "docstring": "Find model_name among indicated Django apps and return Model class\n\n    Examples:\n        To find models in an app called \"miner\":\n\n        >>> find_model('WikiItem', 'miner')\n        >>> find_model('Connection', 'miner')\n        >>> find_model('InvalidModelName')"
  },
  {
    "code": "def get_files(conn, aid: int) -> AnimeFiles:\n    with conn:\n        cur = conn.cursor().execute(\n            'SELECT anime_files FROM cache_anime WHERE aid=?',\n            (aid,))\n        row = cur.fetchone()\n        if row is None:\n            raise ValueError('No cached files')\n        return AnimeFiles.from_json(row[0])",
    "docstring": "Get cached files for anime."
  },
  {
    "code": "def set_info_page(self):\r\n        if self.info_page is not None:\r\n            self.infowidget.setHtml(\r\n                self.info_page,\r\n                QUrl.fromLocalFile(self.css_path)\r\n            )",
    "docstring": "Set current info_page."
  },
  {
    "code": "def register(klass):\n        assert(isinstance(klass, type))\n        name = klass.__name__.lower()\n        if name in Optimizer.opt_registry:\n            warnings.warn('WARNING: New optimizer %s.%s is overriding '\n                          'existing optimizer %s.%s' %\n                          (klass.__module__, klass.__name__,\n                           Optimizer.opt_registry[name].__module__,\n                           Optimizer.opt_registry[name].__name__))\n        Optimizer.opt_registry[name] = klass\n        return klass",
    "docstring": "Registers a new optimizer.\n\n        Once an optimizer is registered, we can create an instance of this\n        optimizer with `create_optimizer` later.\n\n        Examples\n        --------\n\n        >>> @mx.optimizer.Optimizer.register\n        ... class MyOptimizer(mx.optimizer.Optimizer):\n        ...     pass\n        >>> optim = mx.optimizer.Optimizer.create_optimizer('MyOptimizer')\n        >>> print(type(optim))\n        <class '__main__.MyOptimizer'>"
  },
  {
    "code": "def create_frvect(timeseries):\n    dims = frameCPP.Dimension(\n        timeseries.size, timeseries.dx.value,\n        str(timeseries.dx.unit), 0)\n    vect = frameCPP.FrVect(\n        timeseries.name or '', FRVECT_TYPE_FROM_NUMPY[timeseries.dtype.type],\n        1, dims, str(timeseries.unit))\n    vect.GetDataArray()[:] = numpy.require(timeseries.value,\n                                           requirements=['C'])\n    return vect",
    "docstring": "Create a `~frameCPP.FrVect` from a `TimeSeries`\n\n    This method is primarily designed to make writing data to GWF files a\n    bit easier.\n\n    Parameters\n    ----------\n    timeseries : `TimeSeries`\n        the input `TimeSeries`\n\n    Returns\n    -------\n    frvect : `~frameCPP.FrVect`\n        the output `FrVect`"
  },
  {
    "code": "def file(ctx, data_dir, data_file):\n    if not ctx.file:\n        ctx.data_file = data_file\n    if not ctx.data_dir:\n        ctx.data_dir = data_dir\n    ctx.type = 'file'",
    "docstring": "Use the File SWAG Backend"
  },
  {
    "code": "def calc_temp(Data_ref, Data):\n    T = 300 * ((Data.A * Data_ref.Gamma) / (Data_ref.A * Data.Gamma))\n    Data.T = T\n    return T",
    "docstring": "Calculates the temperature of a data set relative to a reference.\n    The reference is assumed to be at 300K.\n\n    Parameters\n    ----------\n    Data_ref : DataObject\n        Reference data set, assumed to be 300K\n    Data : DataObject\n        Data object to have the temperature calculated for\n\n    Returns\n    -------\n    T : uncertainties.ufloat\n        The temperature of the data set"
  },
  {
    "code": "def powered_up(self):\n\t\tif not self.data.scripts.powered_up:\n\t\t\treturn False\n\t\tfor script in self.data.scripts.powered_up:\n\t\t\tif not script.check(self):\n\t\t\t\treturn False\n\t\treturn True",
    "docstring": "Returns True whether the card is \"powered up\"."
  },
  {
    "code": "def factors(number):\n    if not (isinstance(number, int)):\n        raise TypeError(\n            \"Incorrect number type provided. Only integers are accepted.\")\n    factors = []\n    for i in range(1, number + 1):\n        if number % i == 0:\n            factors.append(i)\n    return factors",
    "docstring": "Find all of the factors of a number and return it as a list.\n\n    :type number: integer\n    :param number: The number to find the factors for."
  },
  {
    "code": "def transcode(text, input=PREFERRED_ENCODING, output=PREFERRED_ENCODING):\r\n    try:\r\n        return text.decode(\"cp437\").encode(\"cp1252\")\r\n    except UnicodeError:\r\n        try:\r\n            return text.decode(\"cp437\").encode(output)\r\n        except UnicodeError:\r\n            return text",
    "docstring": "Transcode a text string"
  },
  {
    "code": "def cons(f, mindepth):\n    C = ClustFile(f)\n    for data in C:\n        names, seqs, nreps = zip(*data)\n        total_nreps = sum(nreps)\n        if total_nreps < mindepth:\n            continue\n        S = []\n        for name, seq, nrep in data:\n            S.append([seq, nrep])\n        res = stack(S)\n        yield [x[:4] for x in res if sum(x[:4]) >= mindepth]",
    "docstring": "Makes a list of lists of reads at each site"
  },
  {
    "code": "def __get_time_range(self, startDate, endDate):\n        today = date.today()\n        start_date = today - timedelta(days=today.weekday(), weeks=1)\n        end_date = start_date + timedelta(days=4)\n        startDate = startDate if startDate else str(start_date)\n        endDate = endDate if endDate else str(end_date)\n        return startDate, endDate",
    "docstring": "Return time range"
  },
  {
    "code": "def welcome_message():\n    message = m.Message()\n    message.add(m.Brand())\n    message.add(heading())\n    message.add(content())\n    return message",
    "docstring": "Welcome message for first running users.\n\n    .. versionadded:: 4.3.0\n\n    :returns: A message object containing helpful information.\n    :rtype: messaging.message.Message"
  },
  {
    "code": "def setdefault(obj, field, default):\n    setattr(obj, field, getattr(obj, field, default))",
    "docstring": "Set an object's field to default if it doesn't have a value"
  },
  {
    "code": "def user_list(**connection_args):\n    dbc = _connect(**connection_args)\n    if dbc is None:\n        return []\n    cur = dbc.cursor(MySQLdb.cursors.DictCursor)\n    try:\n        qry = 'SELECT User,Host FROM mysql.user'\n        _execute(cur, qry)\n    except MySQLdb.OperationalError as exc:\n        err = 'MySQL Error {0}: {1}'.format(*exc.args)\n        __context__['mysql.error'] = err\n        log.error(err)\n        return []\n    results = cur.fetchall()\n    log.debug(results)\n    return results",
    "docstring": "Return a list of users on a MySQL server\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' mysql.user_list"
  },
  {
    "code": "def get_beamarea_deg2(self, ra, dec):\n        beam = self.get_beam(ra, dec)\n        if beam is None:\n            return 0\n        return beam.a * beam.b * np.pi",
    "docstring": "Calculate the area of the beam in square degrees.\n\n        Parameters\n        ----------\n        ra, dec : float\n            The sky position (degrees).\n\n        Returns\n        -------\n        area : float\n            The area of the beam in square degrees."
  },
  {
    "code": "def add_fields(self, **fields):\n        self.__class__ = type(self.__class__.__name__,\n                            (self.__class__,), fields)\n        for k, v in fields.items():\n            v.init_inst(self)",
    "docstring": "Add new data fields to this struct instance"
  },
  {
    "code": "def from_json(cls, data: str, force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T:\n        return cls.from_dict(util.load_json(data),\n                             force_snake_case=force_snake_case,\n                             force_cast=force_cast,\n                             restrict=restrict)",
    "docstring": "From json string to instance\n\n        :param data: Json string\n        :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True\n        :param force_cast: Cast forcibly if True\n        :param restrict: Prohibit extra parameters if True\n        :return: Instance\n\n        Usage:\n\n            >>> from owlmixin.samples import Human\n            >>> human: Human = Human.from_json('''{\n            ...     \"id\": 1,\n            ...     \"name\": \"Tom\",\n            ...     \"favorites\": [\n            ...         {\"name\": \"Apple\", \"names_by_lang\": {\"en\": \"Apple\", \"de\": \"Apfel\"}},\n            ...         {\"name\": \"Orange\"}\n            ...     ]\n            ... }''')\n            >>> human.id\n            1\n            >>> human.name\n            'Tom'\n            >>> human.favorites[0].names_by_lang.get()[\"de\"]\n            'Apfel'"
  },
  {
    "code": "def open_image(fname_or_instance: Union[str, IO[bytes]]):\n    if isinstance(fname_or_instance, Image.Image):\n        return fname_or_instance\n    return Image.open(fname_or_instance)",
    "docstring": "Opens a Image and returns it.\n\n    :param fname_or_instance: Can either be the location of the image as a\n                              string or the Image.Image instance itself."
  },
  {
    "code": "def findHTMLMeta(stream):\n    parser = YadisHTMLParser()\n    chunks = []\n    while 1:\n        chunk = stream.read(CHUNK_SIZE)\n        if not chunk:\n            break\n        chunks.append(chunk)\n        try:\n            parser.feed(chunk)\n        except HTMLParseError, why:\n            chunks.append(stream.read())\n            break\n        except ParseDone, why:\n            uri = why[0]\n            if uri is None:\n                chunks.append(stream.read())\n                break\n            else:\n                return uri\n    content = ''.join(chunks)\n    raise MetaNotFound(content)",
    "docstring": "Look for a meta http-equiv tag with the YADIS header name.\n\n    @param stream: Source of the html text\n    @type stream: Object that implements a read() method that works\n        like file.read\n\n    @return: The URI from which to fetch the XRDS document\n    @rtype: str\n\n    @raises MetaNotFound: raised with the content that was\n        searched as the first parameter."
  },
  {
    "code": "def run(self):\n        self.started_queue.put('STARTED')\n        while True:\n            event = self.publisher_queue.get()\n            if event == POISON_PILL:\n                return\n            else:\n                self.dispatch(event)",
    "docstring": "Start the exchange"
  },
  {
    "code": "def get_edited_object(self, request):\n        resolvermatch = urls.resolve(request.path_info)\n        if resolvermatch.namespace == 'admin' and resolvermatch.url_name and resolvermatch.url_name.endswith('_change'):\n            match = RE_CHANGE_URL.match(resolvermatch.url_name)\n            if not match:\n                return None\n            try:\n                object_id = resolvermatch.kwargs['object_id']\n            except KeyError:\n                object_id = resolvermatch.args[0]\n            return self.get_object_by_natural_key(match.group(1), match.group(2), object_id)\n        return None",
    "docstring": "Return the object which is currently being edited.\n        Returns ``None`` if the match could not be made."
  },
  {
    "code": "def _process_hist(self, hist):\n        edges, hvals, widths, lims, isdatetime = super(SideHistogramPlot, self)._process_hist(hist)\n        offset = self.offset * lims[3]\n        hvals *= 1-self.offset\n        hvals += offset\n        lims = lims[0:3] + (lims[3] + offset,)\n        return edges, hvals, widths, lims, isdatetime",
    "docstring": "Subclassed to offset histogram by defined amount."
  },
  {
    "code": "def _prep(e):\n        if 'lastupdate' in e:\n            e['lastupdate'] = datetime.datetime.fromtimestamp(int(e['lastupdate']))\n        for k in ['farm', 'server', 'id', 'secret']:\n            if not k in e:\n                return e\n        e[\"url\"] = \"https://farm%s.staticflickr.com/%s/%s_%s_b.jpg\" % (e[\"farm\"], e[\"server\"], e[\"id\"], e[\"secret\"])\n        return e",
    "docstring": "Normalizes lastupdate to a timestamp, and constructs a URL from the embedded attributes."
  },
  {
    "code": "def cli(env):\n    table = formatting.Table([\n        'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id'\n    ])\n    table.align['Name'] = 'l'\n    table.align['Package Name'] = 'r'\n    table.align['Package Id'] = 'l'\n    manager = ordering.OrderingManager(env.client)\n    items = manager.get_quotes()\n    for item in items:\n        package = item['order']['items'][0]['package']\n        table.add_row([\n            item.get('id'),\n            item.get('name'),\n            clean_time(item.get('createDate')),\n            clean_time(item.get('modifyDate')),\n            item.get('status'),\n            package.get('keyName'),\n            package.get('id')\n        ])\n    env.fout(table)",
    "docstring": "List all active quotes on an account"
  },
  {
    "code": "def scroll_mouse(self, mouse_x: int):\n        scrollbar = self.horizontalScrollBar()\n        if mouse_x - self.view_rect().x() > self.view_rect().width():\n            scrollbar.setValue(scrollbar.value() + 5)\n        elif mouse_x < self.view_rect().x():\n            scrollbar.setValue(scrollbar.value() - 5)",
    "docstring": "Scrolls the mouse if ROI Selection reaches corner of view\n\n        :param mouse_x:\n        :return:"
  },
  {
    "code": "def format_index_array_attrs(series):\n    attrs = {}\n    for i, axis in zip(range(series.ndim), ('x', 'y')):\n        unit = '{}unit'.format(axis)\n        origin = '{}0'.format(axis)\n        delta = 'd{}'.format(axis)\n        aunit = getattr(series, unit)\n        attrs.update({\n            unit: str(aunit),\n            origin: getattr(series, origin).to(aunit).value,\n            delta: getattr(series, delta).to(aunit).value,\n        })\n    return attrs",
    "docstring": "Format metadata attributes for and indexed array\n\n    This function is used to provide the necessary metadata to meet\n    the (proposed) LIGO Common Data Format specification for series data\n    in HDF5."
  },
  {
    "code": "def _builder_connect_signals(self, _dict):\n        assert not self.builder_connected, \"Gtk.Builder not already connected\"\n        if _dict and not self.builder_pending_callbacks:\n            GLib.idle_add(self.__builder_connect_pending_signals)\n        for n, v in _dict.items():\n            if n not in self.builder_pending_callbacks:\n                _set = set()\n                self.builder_pending_callbacks[n] = _set\n            else:\n                _set = self.builder_pending_callbacks[n]\n            _set.add(v)",
    "docstring": "Called by controllers which want to autoconnect their\n        handlers with signals declared in internal Gtk.Builder.\n\n        This method accumulates handlers, and books signal\n        autoconnection later on the idle of the next occurring gtk\n        loop. After the autoconnection is done, this method cannot be\n        called anymore."
  },
  {
    "code": "def sendRequest(self, extraHeaders=\"\"):\n        self.addParam('src', 'mc-python')\n        params = urlencode(self._params)\n        url = self._url\n        if 'doc' in self._file.keys():\n            headers = {}\n            if (extraHeaders is not None) and (extraHeaders is dict):\n                headers = headers.update(extraHeaders)\n            result = requests.post(url=url, data=self._params, files=self._file, headers=headers)\n            result.encoding = 'utf-8'\n            return result\n        else:\n            headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n            if (extraHeaders is not None) and (extraHeaders is dict):\n                headers = headers.update(extraHeaders)\n            result = requests.request(\"POST\", url=url, data=params, headers=headers)\n            result.encoding = 'utf-8'\n            return result",
    "docstring": "Sends a request to the URL specified and returns a response only if the HTTP code returned is OK\n\n        :param extraHeaders:\n             Allows to configure additional headers in the request\n        :return:\n            Response object set to None if there is an error"
  },
  {
    "code": "def pexpire(self, key, timeout):\n        if not isinstance(timeout, int):\n            raise TypeError(\"timeout argument must be int, not {!r}\"\n                            .format(timeout))\n        fut = self.execute(b'PEXPIRE', key, timeout)\n        return wait_convert(fut, bool)",
    "docstring": "Set a milliseconds timeout on key.\n\n        :raises TypeError: if timeout is not int"
  },
  {
    "code": "def append_with_data(url, data):\n        if data is None:\n            return url\n        url_parts = list(urlparse(url))\n        query = OrderedDict(parse_qsl(url_parts[4], keep_blank_values=True))\n        query.update(data)\n        url_parts[4] = URLHelper.query_dict_to_string(query)\n        return urlunparse(url_parts)",
    "docstring": "Append the given URL with the given data OrderedDict.\n\n        Args:\n            url (str): The URL to append.\n            data (obj): The key value OrderedDict to append to the URL.\n\n        Returns:\n            str: The new URL."
  },
  {
    "code": "def open_datasets(path, backend_kwargs={}, no_warn=False, **kwargs):\n    if not no_warn:\n        warnings.warn(\"open_datasets is an experimental API, DO NOT RELY ON IT!\", FutureWarning)\n    fbks = []\n    datasets = []\n    try:\n        datasets.append(open_dataset(path, backend_kwargs=backend_kwargs, **kwargs))\n    except DatasetBuildError as ex:\n        fbks.extend(ex.args[2])\n    for fbk in fbks:\n        bks = backend_kwargs.copy()\n        bks['filter_by_keys'] = fbk\n        datasets.extend(open_datasets(path, backend_kwargs=bks, no_warn=True, **kwargs))\n    return datasets",
    "docstring": "Open a GRIB file groupping incompatible hypercubes to different datasets via simple heuristics."
  },
  {
    "code": "def main(args=None):\n    if args is None:\n        args = tag.cli.parser().parse_args()\n    assert args.cmd in mains\n    mainmethod = mains[args.cmd]\n    mainmethod(args)",
    "docstring": "Entry point for the tag CLI.\n\n    Isolated as a method so that the CLI can be called by other Python code\n    (e.g. for testing), in which case the arguments are passed to the function.\n    If no arguments are passed to the function, parse them from the command\n    line."
  },
  {
    "code": "def reset_tasks(self, request, context):\n        _log_request(request, context)\n        self.listener.memory.clear_tasks()\n        return clearly_pb2.Empty()",
    "docstring": "Resets all captured tasks."
  },
  {
    "code": "def pauli_expansion(\n    val: Any,\n    *,\n    default: Union[value.LinearDict[str], TDefault]\n        = RaiseTypeErrorIfNotProvided,\n    atol: float = 1e-9\n) -> Union[value.LinearDict[str], TDefault]:\n    method = getattr(val, '_pauli_expansion_', None)\n    expansion = NotImplemented if method is None else method()\n    if expansion is not NotImplemented:\n        return expansion.clean(atol=atol)\n    matrix = unitary(val, default=None)\n    if matrix is None:\n        if default is RaiseTypeErrorIfNotProvided:\n            raise TypeError('No Pauli expansion for object {} of type {}'\n                    .format(val, type(val)))\n        return default\n    num_qubits = matrix.shape[0].bit_length() - 1\n    basis = operator_spaces.kron_bases(operator_spaces.PAULI_BASIS,\n                                       repeat=num_qubits)\n    expansion = operator_spaces.expand_matrix_in_orthogonal_basis(matrix, basis)\n    return expansion.clean(atol=atol)",
    "docstring": "Returns coefficients of the expansion of val in the Pauli basis.\n\n    Args:\n        val: The value whose Pauli expansion is to returned.\n        default: Determines what happens when `val` does not have methods that\n            allow Pauli expansion to be obtained (see below). If set, the value\n            is returned in that case. Otherwise, TypeError is raised.\n        atol: Ignore coefficients whose absolute value is smaller than this.\n\n    Returns:\n        If `val` has a _pauli_expansion_ method, then its result is returned.\n        Otherwise, if `val` has a small unitary then that unitary is expanded\n        in the Pauli basis and coefficients are returned. Otherwise, if default\n        is set to None or other value then default is returned. Otherwise,\n        TypeError is raised.\n\n    Raises:\n        TypeError if `val` has none of the methods necessary to obtain its Pauli\n        expansion and no default value has been provided."
  },
  {
    "code": "def get_validation_errors(data, schema=None):\n    schema = _load_schema_for_record(data, schema)\n    errors = Draft4Validator(\n        schema,\n        resolver=LocalRefResolver.from_schema(schema),\n        format_checker=inspire_format_checker\n    )\n    return errors.iter_errors(data)",
    "docstring": "Validation errors for a given record.\n\n    Args:\n        data (dict): record to validate.\n        schema (Union[dict, str]): schema to validate against. If it is a\n            string, it is intepreted as the name of the schema to load (e.g.\n            ``authors`` or ``jobs``). If it is ``None``, the schema is taken\n            from ``data['$schema']``. If it is a dictionary, it is used\n            directly.\n    Yields:\n        jsonschema.exceptions.ValidationError: validation errors.\n\n    Raises:\n        SchemaNotFound: if the given schema was not found.\n        SchemaKeyNotFound: if ``schema`` is ``None`` and no ``$schema`` key was\n            found in ``data``.\n        jsonschema.SchemaError: if the schema is invalid."
  },
  {
    "code": "def get(self, uri, query=None, **kwargs):\n        return self.fetch('get', uri, query, **kwargs)",
    "docstring": "make a GET request"
  },
  {
    "code": "def export(self, directory, revision=None):\n        directory = os.path.abspath(directory)\n        self.create()\n        timer = Timer()\n        revision = revision or self.default_revision\n        logger.info(\"Exporting revision '%s' in %s to %s ..\", revision, format_path(self.local), directory)\n        self.context.execute('mkdir', '-p', directory)\n        self.context.execute(*self.get_export_command(directory, revision))\n        logger.debug(\"Took %s to pull changes from remote %s repository.\", timer, self.friendly_name)",
    "docstring": "Export the complete tree from the local version control repository.\n\n        :param directory: The directory where the tree should be exported\n                          (a string).\n        :param revision: The revision to export (a string or :data:`None`,\n                         defaults to :attr:`default_revision`)."
  },
  {
    "code": "def _do_get(self, uri, **kwargs):\n        scaleioapi_get_headers = {'Content-type':'application/json','Version':'1.0'}\n        self.logger.debug(\"_do_get() \" + \"{}/{}\".format(self._api_url,uri))\n        if kwargs:\n            for key, value in kwargs.iteritems():\n                if key == 'headers':\n                    scaleio_get_headersvalue = value\n        try:\n            response = self._im_session.get(\"{}/{}\".format(self._api_url, uri), **kwargs).json()\n            if response.status_code == requests.codes.ok:\n                return response\n            else:\n                raise RuntimeError(\"_do_get() - HTTP response error\" + response.status_code)\n        except:\n            raise RuntimeError(\"_do_get() - Communication error with ScaleIO gateway\")\n        return response",
    "docstring": "Convinient method for GET requests\n        Returns http request status value from a POST request"
  },
  {
    "code": "def q(self, val):\n        self._q = np.asarray(val)\n        self.Q = cumsum(val)",
    "docstring": "Setter method for q."
  },
  {
    "code": "def _num_values(self, vdr_dict):\n        values = 1\n        for x in range(0, vdr_dict['num_dims']):\n            if (vdr_dict['dim_vary'][x] != 0):\n                values = values * vdr_dict['dim_sizes'][x]\n        return values",
    "docstring": "Returns the number of values in a record, using a given VDR\n        dictionary. Multiplies the dimension sizes of each dimension,\n        if it is varying."
  },
  {
    "code": "def mmGetPermanencesPlot(self, title=None):\n    plot = Plot(self, title)\n    data = numpy.zeros((self.getNumColumns(), self.getNumInputs()))\n    for i in xrange(self.getNumColumns()):\n      self.getPermanence(i, data[i])\n    plot.add2DArray(data, xlabel=\"Permanences\", ylabel=\"Column\")\n    return plot",
    "docstring": "Returns plot of column permanences.\n    @param title an optional title for the figure\n    @return (Plot) plot"
  },
  {
    "code": "def name_inner_event(cls):\n    if hasattr(cls, 'Event'):\n        cls.Event._event_name = '{}.Event'.format(cls.__name__)\n    else:\n        warnings.warn('Class {} does not have a inner Event'.format(cls))\n    return cls",
    "docstring": "Decorator to rename cls.Event 'Event' as 'cls.Event"
  },
  {
    "code": "def jsonl(self, jsonl_file):\n        if isinstance(jsonl_file, str):\n            file_open = get_read_function(jsonl_file, self.disable_compression)\n            input_file = file_open(jsonl_file)\n        else:\n            input_file = jsonl_file\n        return self(input_file).map(jsonapi.loads).cache(delete_lineage=True)",
    "docstring": "Reads and parses the input of a jsonl file stream or file.\n\n        Jsonl formatted files must have a single valid json value on each line which is parsed by\n        the python json module.\n\n        >>> seq.jsonl('examples/chat_logs.jsonl').first()\n        {u'date': u'10/09', u'message': u'hello anyone there?', u'user': u'bob'}\n\n        :param jsonl_file: path or file containing jsonl content\n        :return: Sequence wrapping jsonl file"
  },
  {
    "code": "def sub(value, arg):\n    try:\n        nvalue, narg = handle_float_decimal_combinations(\n            valid_numeric(value), valid_numeric(arg), '-')\n        return nvalue - narg\n    except (ValueError, TypeError):\n        try:\n            return value - arg\n        except Exception:\n            return ''",
    "docstring": "Subtract the arg from the value."
  },
  {
    "code": "def new_remove_attribute_transaction(self, ont_id: str, pub_key: str or bytes, attrib_key: str,\n                                         b58_payer_address: str, gas_limit: int, gas_price: int):\n        if isinstance(pub_key, str):\n            bytes_pub_key = bytes.fromhex(pub_key)\n        elif isinstance(pub_key, bytes):\n            bytes_pub_key = pub_key\n        else:\n            raise SDKException(ErrorCode.params_type_error('a bytes or str type of public key is required.'))\n        args = dict(ontid=ont_id.encode('utf-8'), attrib_key=attrib_key.encode('utf-8'), pk=bytes_pub_key)\n        tx = self.__generate_transaction('removeAttribute', args, b58_payer_address, gas_limit, gas_price)\n        return tx",
    "docstring": "This interface is used to generate a Transaction object which is used to remove attribute.\n\n        :param ont_id: OntId.\n        :param pub_key: the hexadecimal public key in the form of string.\n        :param attrib_key: a string which is used to indicate which attribute we want to remove.\n        :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction.\n        :param gas_limit: an int value that indicate the gas limit.\n        :param gas_price: an int value that indicate the gas price.\n        :return: a Transaction object which is used to remove attribute."
  },
  {
    "code": "def rest_del(self, url, params=None, session=None, verify=True, cert=None):\n        res = session.delete(url, params=params, verify=verify, cert=cert)\n        return res.text, res.status_code",
    "docstring": "Perform a DELETE request to url with requests.session"
  },
  {
    "code": "def decode_keys(store, encoding='utf-8'):\n    keys = store.keys()\n    for key in keys:\n        if hasattr(key, 'decode'):\n            decoded = key.decode(encoding)\n            if key != decoded:\n                store[key.decode(encoding)] = store[key]\n                store.pop(key)\n    return store",
    "docstring": "If a dictionary has keys that are bytes decode them to a str.\n\n    Parameters\n    ---------\n    store : dict\n      Dictionary with data\n\n    Returns\n    ---------\n    result : dict\n      Values are untouched but keys that were bytes\n      are converted to ASCII strings.\n\n    Example\n    -----------\n    In [1]: d\n    Out[1]: {1020: 'nah', b'hi': 'stuff'}\n\n    In [2]: trimesh.util.decode_keys(d)\n    Out[2]: {1020: 'nah', 'hi': 'stuff'}"
  },
  {
    "code": "def linkorcopy(src, dst):\n    if not os.path.isfile(src):\n        raise error.ButcherError('linkorcopy called with non-file source. '\n                                 '(src: %s  dst: %s)' % src, dst)\n    elif os.path.isdir(dst):\n        dst = os.path.join(dst, os.path.basename(src))\n    elif os.path.exists(dst):\n        os.unlink(dst)\n    elif not os.path.exists(os.path.dirname(dst)):\n        os.makedirs(os.path.dirname(dst))\n    try:\n        os.link(src, dst)\n        log.debug('Hardlinked: %s -> %s', src, dst)\n    except OSError:\n        shutil.copy2(src, dst)\n        log.debug('Couldn\\'t hardlink. Copied: %s -> %s', src, dst)",
    "docstring": "Hardlink src file to dst if possible, otherwise copy."
  },
  {
    "code": "def get_application_groups():\n    groups = []\n    for title, groupdict in appsettings.FLUENT_DASHBOARD_APP_GROUPS:\n        module_kwargs = groupdict.copy()\n        if '*' in groupdict['models']:\n            default_module = appsettings.FLUENT_DASHBOARD_DEFAULT_MODULE\n            module_kwargs['exclude'] = ALL_KNOWN_APPS + list(module_kwargs.get('exclude', []))\n            del module_kwargs['models']\n        else:\n            default_module = 'CmsAppIconList'\n        module = groupdict.get('module', default_module)\n        if module in MODULE_ALIASES:\n            module = MODULE_ALIASES[module]\n        module_kwargs['module'] = module\n        groups.append((title, module_kwargs),)\n    return groups",
    "docstring": "Return the applications of the system, organized in various groups.\n\n    These groups are not connected with the application names,\n    but rather with a pattern of applications."
  },
  {
    "code": "def namedb_is_history_snapshot( history_snapshot ):\n    missing = []\n    assert 'op' in history_snapshot.keys(), \"BUG: no op given\"\n    opcode = op_get_opcode_name( history_snapshot['op'] )\n    assert opcode is not None, \"BUG: unrecognized op '%s'\" % history_snapshot['op']\n    consensus_fields = op_get_consensus_fields( opcode )\n    for field in consensus_fields:\n        if field not in history_snapshot.keys():\n            missing.append( field )\n    assert len(missing) == 0, (\"BUG: operation '%s' is missing the following fields: %s\" % (opcode, \",\".join(missing)))\n    return True",
    "docstring": "Given a dict, verify that it is a history snapshot.\n    It must have all consensus fields.\n    Return True if so.\n    Raise an exception of it doesn't."
  },
  {
    "code": "def _forceRefreshAutoRange(self):\n        enabled = self.autoRangeCti and self.autoRangeCti.configValue\n        self.rangeMinCti.enabled = not enabled\n        self.rangeMaxCti.enabled = not enabled\n        self.model.emitDataChanged(self)",
    "docstring": "The min and max config items will be disabled if auto range is on."
  },
  {
    "code": "def SmartUnicode(string):\n  if isinstance(string, Text):\n    return string\n  if isinstance(string, bytes):\n    return string.decode(\"utf-8\", \"ignore\")\n  if compatibility.PY2:\n    return str(string).__native__()\n  else:\n    return str(string)",
    "docstring": "Returns a unicode object.\n\n  This function will always return a unicode object. It should be used to\n  guarantee that something is always a unicode object.\n\n  Args:\n    string: The string to convert.\n\n  Returns:\n    a unicode object."
  },
  {
    "code": "def update_footer(self):\n        field_item = self.field_list.currentItem()\n        if not field_item:\n            self.footer_label.setText('')\n            return\n        field_name = field_item.data(Qt.UserRole)\n        field = self.layer.fields().field(field_name)\n        index = self.layer.fields().lookupField(field_name)\n        unique_values = list(self.layer.uniqueValues(index))\n        pretty_unique_values = ', '.join([str(v) for v in unique_values[:10]])\n        footer_text = tr('Field type: {0}\\n').format(field.typeName())\n        footer_text += tr('Unique values: {0}').format(pretty_unique_values)\n        self.footer_label.setText(footer_text)",
    "docstring": "Update footer when the field list change."
  },
  {
    "code": "def un(byts):\n    return msgpack.loads(byts, use_list=False, raw=False, unicode_errors='surrogatepass')",
    "docstring": "Use msgpack to de-serialize a python object.\n\n    Args:\n        byts (bytes): The bytes to de-serialize\n\n    Notes:\n        String objects are decoded using utf8 encoding.  In order to handle\n        potentially malformed input, ``unicode_errors='surrogatepass'`` is set\n        to allow decoding bad input strings.\n\n    Returns:\n        obj: The de-serialized object"
  },
  {
    "code": "async def traverse(self, func):\n        async_executor = self\n        if inspect.isasyncgenfunction(func):\n            async for result in func(*async_executor.args):\n                yield result\n        else:\n            yield await func(*async_executor.args)",
    "docstring": "Traverses an async function or generator, yielding each result.\n\n        This function is private. The class should be used as an iterator instead of using this method."
  },
  {
    "code": "def _replication_request(command, host=None, core_name=None, params=None):\n    params = [] if params is None else params\n    extra = [\"command={0}\".format(command)] + params\n    url = _format_url('replication', host=host, core_name=core_name,\n                      extra=extra)\n    return _http_request(url)",
    "docstring": "PRIVATE METHOD\n    Performs the requested replication command and returns a dictionary with\n    success, errors and data as keys. The data object will contain the JSON\n    response.\n\n    command : str\n        The replication command to execute.\n    host : str (None)\n        The solr host to query. __opts__['host'] is default\n    core_name: str (None)\n        The name of the solr core if using cores. Leave this blank if you are\n        not using cores or if you want to check all cores.\n    params : list<str> ([])\n        Any additional parameters you want to send. Should be a lsit of\n        strings in name=value format. e.g. ['name=value']\n\n    Return: dict<str, obj>::\n\n        {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}"
  },
  {
    "code": "def template_thinning(self, inj_filter_rejector):\n        if not inj_filter_rejector.enabled or \\\n                inj_filter_rejector.chirp_time_window is None:\n            return\n        injection_parameters = inj_filter_rejector.injection_params.table\n        fref = inj_filter_rejector.f_lower\n        threshold = inj_filter_rejector.chirp_time_window\n        m1= self.table['mass1']\n        m2= self.table['mass2']\n        tau0_temp, _ = pycbc.pnutils.mass1_mass2_to_tau0_tau3(m1, m2, fref)\n        indices = []\n        for inj in injection_parameters:\n            tau0_inj, _ = \\\n                pycbc.pnutils.mass1_mass2_to_tau0_tau3(inj.mass1, inj.mass2,\n                                                       fref)\n            inj_indices = np.where(abs(tau0_temp - tau0_inj) <= threshold)[0]\n            indices.append(inj_indices)\n            indices_combined = np.concatenate(indices)\n        indices_unique= np.unique(indices_combined)\n        self.table = self.table[indices_unique]",
    "docstring": "Remove templates from bank that are far from all injections."
  },
  {
    "code": "def create_logger(self):\n        name = \"bors\"\n        if hasattr(self, \"name\"):\n            name = self.name\n        self.log = logging.getLogger(name)\n        try:\n            lvl = self.conf.get_log_level()\n        except AttributeError:\n            lvl = self.context.get(\"log_level\", None)\n        self.log.setLevel(getattr(logging, lvl, logging.INFO))",
    "docstring": "Generates a logger instance from the singleton"
  },
  {
    "code": "def _legacy_pkcs1_v1_5_encode_md5_sha1(M, emLen):\n    M = bytes_encode(M)\n    md5_hash = hashes.Hash(_get_hash(\"md5\"), backend=default_backend())\n    md5_hash.update(M)\n    sha1_hash = hashes.Hash(_get_hash(\"sha1\"), backend=default_backend())\n    sha1_hash.update(M)\n    H = md5_hash.finalize() + sha1_hash.finalize()\n    if emLen < 36 + 11:\n        warning(\"pkcs_emsa_pkcs1_v1_5_encode: \"\n                \"intended encoded message length too short\")\n        return None\n    PS = b'\\xff' * (emLen - 36 - 3)\n    return b'\\x00' + b'\\x01' + PS + b'\\x00' + H",
    "docstring": "Legacy method for PKCS1 v1.5 encoding with MD5-SHA1 hash."
  },
  {
    "code": "def close_config(self):\n        try:\n            self.dev.rpc.close_configuration()\n        except Exception as err:\n            print err",
    "docstring": "Closes the exiting opened configuration\n\n        Example:\n\n        .. code-block:: python\n\n            from pyJunosManager import JunosDevice\n\n            dev = JunosDevice(host=\"1.2.3.4\",username=\"root\",password=\"Juniper\")\n            dev.open()\n            dev.open_config()\n            dev.close_config()\n            dev.close()"
  },
  {
    "code": "def create(self,\n               access_tokens,\n               days_requested,\n               options=None):\n        options = options or {}\n        return self.client.post('/asset_report/create', {\n            'access_tokens': access_tokens,\n            'days_requested': days_requested,\n            'options': options,\n        })",
    "docstring": "Create an asset report.\n\n        :param  [str]   access_tokens:  A list of access tokens, one token for\n                                        each Item to be included in the Asset\n                                        Report.\n        :param  int     days_requested: Days of transaction history requested\n                                        to be included in the Asset Report.\n        :param  dict    options:        An optional dictionary. For more\n                                        information on the options object, see\n                                        the documentation site listed above."
  },
  {
    "code": "def read_varnames(self, path=\"/\"):\n        if path == \"/\":\n            return self.rootgrp.variables.keys()\n        else:\n            group = self.path2group[path]\n            return group.variables.keys()",
    "docstring": "List of variable names stored in the group specified by path."
  },
  {
    "code": "def set_list_attribute(self, other, trigger_klass, property_name):\n        if isinstance(other, trigger_klass):\n            if not hasattr(self, property_name):\n                raise AttributeError(\"%s has no property %s\" % (self.__class__.__name__, property_name))\n            val = getattr(self, property_name, [])\n            if other in val:\n                raise ValueError(\"%s already exists in %s\" % (other.__class__.__name__, self.__class__.__name__))\n            else:\n                val.append(other)\n                setattr(self, property_name, val)",
    "docstring": "Used to set guard the setting of a list attribute, ensuring the same element is not added twice."
  },
  {
    "code": "def pickle(self) -> None:\n        pickle_path = self.tgt_dir / \"corpus.p\"\n        logger.debug(\"pickling %r object and saving it to path %s\", self, pickle_path)\n        with pickle_path.open(\"wb\") as f:\n            pickle.dump(self, f)",
    "docstring": "Pickles the Corpus object in a file in tgt_dir."
  },
  {
    "code": "def linkUserToMostRecentCustomer(sender,**kwargs):\n    email_address = kwargs.get('email_address',None)\n    if not email_address or not email_address.primary or not email_address.verified:\n        return\n    user = email_address.user\n    if not hasattr(user, 'customer'):\n        last_reg = Registration.objects.filter(\n            customer__email=email_address.email,\n            customer__user__isnull=True,\n            dateTime__isnull=False\n        ).order_by('-dateTime').first()\n        if last_reg:\n            customer = last_reg.customer\n            customer.user = user\n            customer.save()\n            if not user.first_name and not user.last_name:\n                user.first_name = customer.first_name\n                user.last_name = customer.last_name\n                user.save()",
    "docstring": "If a new primary email address has just been confirmed, check if the user\n    associated with that email has an associated customer object yet.  If not,\n    then look for the customer with that email address who most recently\n    registered for something and that is not associated with another user.\n    Automatically associate the User with with Customer, and if missing, fill in\n    the user's name information with the Customer's name.  This way, when a new\n    or existing customer creates a user account, they are seamlessly linked to\n    their most recent existing registration at the time they verify their email\n    address."
  },
  {
    "code": "def get_output_file(self, in_file, instance, field, **kwargs):\n        return NamedTemporaryFile(mode='rb', suffix='_%s_%s%s' % (\n            get_model_name(instance), field.name, self.get_ext()), delete=False)",
    "docstring": "Creates a temporary file. With regular `FileSystemStorage` it does not \n        need to be deleted, instaed file is safely moved over. With other cloud\n        based storage it is a good idea to set `delete=True`."
  },
  {
    "code": "def reset_password(token):\n    expired, invalid, user = reset_password_token_status(token)\n    if not user or invalid:\n        invalid = True\n        do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN'))\n    if expired:\n        send_reset_password_instructions(user)\n        do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email,\n                              within=_security.reset_password_within))\n    if invalid or expired:\n        return redirect(url_for('forgot_password'))\n    form = _security.reset_password_form()\n    if form.validate_on_submit():\n        after_this_request(_commit)\n        update_password(user, form.password.data)\n        do_flash(*get_message('PASSWORD_RESET'))\n        return redirect(get_url(_security.post_reset_view) or\n                        get_url(_security.login_url))\n    return _security.render_template(\n        config_value('RESET_PASSWORD_TEMPLATE'),\n        reset_password_form=form,\n        reset_password_token=token,\n        **_ctx('reset_password')\n    )",
    "docstring": "View function that handles a reset password request."
  },
  {
    "code": "def serial_assimilate(self, rootpath):\n        valid_paths = []\n        for (parent, subdirs, files) in os.walk(rootpath):\n            valid_paths.extend(self._drone.get_valid_paths((parent, subdirs,\n                                                            files)))\n        data = []\n        count = 0\n        total = len(valid_paths)\n        for path in valid_paths:\n            newdata = self._drone.assimilate(path)\n            self._data.append(newdata)\n            count += 1\n            logger.info('{}/{} ({:.2f}%) done'.format(count, total,\n                                                      count / total * 100))\n        for d in data:\n            self._data.append(json.loads(d, cls=MontyDecoder))",
    "docstring": "Assimilate the entire subdirectory structure in rootpath serially."
  },
  {
    "code": "def process_data(data, models):\n        pdata = gvar.BufferDict()\n        for m in MultiFitter.flatten_models(models):\n            pdata[m.datatag] = (\n                m.builddata(data) if m.ncg <= 1 else\n                MultiFitter.coarse_grain(m.builddata(data), ncg=m.ncg)\n                )\n        return pdata",
    "docstring": "Convert ``data`` to processed data using ``models``.\n\n        Data from dictionary ``data`` is processed by each model\n        in list ``models``, and the results collected into a new\n        dictionary ``pdata`` for use in :meth:`MultiFitter.lsqfit`\n        and :meth:`MultiFitter.chained_lsqft`."
  },
  {
    "code": "def add_escape(self, idx, char):\n        self.fmt.append_text(self.fmt._unescape.get(\n            self.format[self.str_begin:idx], char))",
    "docstring": "Translates and adds the escape sequence.\n\n        :param idx: Provides the ending index of the escape sequence.\n        :param char: The actual character that was escaped."
  },
  {
    "code": "def hash_folder(folder, regex='[!_]*'):\n    file_hashes = {}\n    for path in glob.glob(os.path.join(folder, regex)):\n        if not os.path.isfile(path):\n            continue\n        with open(path, 'r') as fileP:\n            md5_hash = hashlib.md5(fileP.read()).digest()\n        file_name = os.path.basename(path)\n        file_hashes[file_name] = urlsafe_b64encode(md5_hash)\n    return file_hashes",
    "docstring": "Get the md5 sum of each file in the folder and return to the user\n\n    :param folder: the folder to compute the sums over\n    :param regex: an expression to limit the files we match\n    :return:\n\n    Note: by default we will hash every file in the folder\n\n    Note: we will not match anything that starts with an underscore"
  },
  {
    "code": "def _match_excluded(self, filename, patterns):\n        return _wcparse._match_real(\n            filename, patterns._include, patterns._exclude, patterns._follow, self.symlinks\n        )",
    "docstring": "Call match real directly to skip unnecessary `exists` check."
  },
  {
    "code": "def xpointerNewRangeNodes(self, end):\n        if end is None: end__o = None\n        else: end__o = end._o\n        ret = libxml2mod.xmlXPtrNewRangeNodes(self._o, end__o)\n        if ret is None:raise treeError('xmlXPtrNewRangeNodes() failed')\n        return xpathObjectRet(ret)",
    "docstring": "Create a new xmlXPathObjectPtr of type range using 2 nodes"
  },
  {
    "code": "def get_tags_of_invoice_per_page(self, invoice_id, per_page=1000, page=1):\n        return self._get_resource_per_page(\n            resource=INVOICE_TAGS,\n            per_page=per_page,\n            page=page,\n            params={'invoice_id': invoice_id},\n        )",
    "docstring": "Get tags of invoice per page\n\n        :param invoice_id: the invoice id\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :return: list"
  },
  {
    "code": "def reflect_table(conn, table_name, schema='public'):\n    column_meta = list(get_column_metadata(conn, table_name, schema=schema))\n    primary_key_columns = list(get_primary_keys(conn, table_name, schema=schema))\n    columns = [Column(**column_data) for column_data in column_meta]\n    primary_key = PrimaryKey(primary_key_columns)\n    return Table(table_name, columns, primary_key, schema=schema)",
    "docstring": "Reflect basic table attributes."
  },
  {
    "code": "def set_states(self, states):\n        states = pickle.loads(states)\n        if isinstance(states, tuple) and len(states) == 2:\n            self.states, self.optimizer = states\n        else:\n            self.states = states\n        self.states_synced = dict.fromkeys(self.states.keys(), False)",
    "docstring": "Sets updater states."
  },
  {
    "code": "def require_server(fn):\n    @wraps(fn)\n    def wrapper(*args, **kwargs):\n        if env.machine is None:\n            abort(red('ERROR: You must provide a server name to call this'\n                      ' task!'))\n        return fn(*args, **kwargs)\n    return wrapper",
    "docstring": "Checks if the user has called the task with a server name.\n\n    Fabric tasks decorated with this decorator must be called like so::\n\n        fab <server name> <task name>\n\n    If no server name is given, the task will not be executed."
  },
  {
    "code": "def exception_message():\n    exc_type, exc_value, exc_tb = exc_info = sys.exc_info()\n    return {'exception': {'type': exc_type,\n                          'value': exc_value,\n                          'traceback': exc_tb},\n            'traceback': traceback.format_exception(*exc_info)}",
    "docstring": "Create a message with details on the exception."
  },
  {
    "code": "def msvc14_get_vc_env(plat_spec):\n    try:\n        return get_unpatched(msvc14_get_vc_env)(plat_spec)\n    except distutils.errors.DistutilsPlatformError:\n        pass\n    try:\n        return EnvironmentInfo(plat_spec, vc_min_ver=14.0).return_env()\n    except distutils.errors.DistutilsPlatformError as exc:\n        _augment_exception(exc, 14.0)\n        raise",
    "docstring": "Patched \"distutils._msvccompiler._get_vc_env\" for support extra\n    compilers.\n\n    Set environment without use of \"vcvarsall.bat\".\n\n    Known supported compilers\n    -------------------------\n    Microsoft Visual C++ 14.0:\n        Microsoft Visual C++ Build Tools 2015 (x86, x64, arm)\n        Microsoft Visual Studio 2017 (x86, x64, arm, arm64)\n        Microsoft Visual Studio Build Tools 2017 (x86, x64, arm, arm64)\n\n    Parameters\n    ----------\n    plat_spec: str\n        Target architecture.\n\n    Return\n    ------\n    environment: dict"
  },
  {
    "code": "def dropColumnsFromRabaObjTable(self, name, lstFieldsToKeep) :\n\t\t\"Removes columns from a RabaObj table. lstFieldsToKeep should not contain raba_id or json fileds\"\n\t\tif len(lstFieldsToKeep) == 0 :\n\t\t\traise ValueError(\"There are no fields to keep\")\n\t\tcpy = name+'_copy'\n\t\tsqlFiledsStr = ', '.join(lstFieldsToKeep)\n\t\tself.createTable(cpy, 'raba_id INTEGER PRIMARY KEY AUTOINCREMENT, json, %s' % (sqlFiledsStr))\n\t\tsql = \"INSERT INTO %s SELECT %s FROM %s;\" % (cpy, 'raba_id, json, %s' % sqlFiledsStr, name)\n\t\tself.execute(sql)\n\t\tself.dropTable(name)\n\t\tself.renameTable(cpy, name)",
    "docstring": "Removes columns from a RabaObj table. lstFieldsToKeep should not contain raba_id or json fileds"
  },
  {
    "code": "def _dstationarystate(self, k, param):\n        if self._distributionmodel:\n            return self.model.dstationarystate(k, param)\n        else:\n            return self.model.dstationarystate(param)",
    "docstring": "Returns the dstationarystate ."
  },
  {
    "code": "def calc_effective_permeability(self, inlets=None, outlets=None,\n                                    domain_area=None, domain_length=None):\n        r\n        phase = self.project.phases()[self.settings['phase']]\n        d_normal = self._calc_eff_prop(inlets=inlets, outlets=outlets,\n                                       domain_area=domain_area,\n                                       domain_length=domain_length)\n        K = d_normal * sp.mean(phase['pore.viscosity'])\n        return K",
    "docstring": "r\"\"\"\n        This calculates the effective permeability in this linear transport\n        algorithm.\n\n        Parameters\n        ----------\n        inlets : array_like\n            The pores where the inlet pressure boundary conditions were\n            applied.  If not given an attempt is made to infer them from the\n            algorithm.\n\n        outlets : array_like\n            The pores where the outlet pressure boundary conditions were\n            applied.  If not given an attempt is made to infer them from the\n            algorithm.\n\n        domain_area : scalar, optional\n            The area of the inlet (and outlet) boundary faces.  If not given\n            then an attempt is made to estimate it, but it is usually\n            underestimated.\n\n        domain_length : scalar, optional\n            The length of the domain between the inlet and outlet boundary\n            faces.  If not given then an attempt is made to estimate it, but it\n            is usually underestimated.\n\n        Notes\n        -----\n        The area and length of the domain are found using the bounding box\n        around the inlet and outlet pores which do not necessarily lie on the\n        edge of the domain, resulting in underestimation of sizes."
  },
  {
    "code": "def encode_basic_auth(username, password):\n    return \"Basic {}\".format(\n        b64encode(\n            \"{}:{}\".format(\n                username,\n                password,\n            ).encode(\"utf-8\")\n        ).decode(\"utf-8\")\n    )",
    "docstring": "Encode basic auth credentials."
  },
  {
    "code": "def load(self, path: str, k: Optional[int] = None):\n        load_time_start = time.time()\n        with open(path, 'rb') as inp:\n            _lex = np.load(inp)\n        loaded_k = _lex.shape[1]\n        if k is not None:\n            top_k = min(k, loaded_k)\n            if k > loaded_k:\n                logger.warning(\"Can not load top-%d translations from lexicon that \"\n                               \"contains at most %d entries per source.\", k, loaded_k)\n        else:\n            top_k = loaded_k\n        self.lex = np.zeros((len(self.vocab_source), top_k), dtype=_lex.dtype)\n        for src_id, trg_ids in enumerate(_lex):\n            self.lex[src_id, :] = np.sort(trg_ids[:top_k])\n        load_time = time.time() - load_time_start\n        logger.info(\"Loaded top-%d lexicon from \\\"%s\\\" in %.4fs.\", top_k, path, load_time)",
    "docstring": "Load lexicon from Numpy array file. The top-k target ids will be sorted by increasing target id.\n\n        :param path: Path to Numpy array file.\n        :param k: Optionally load less items than stored in path."
  },
  {
    "code": "def get_ancestor_id_names(mention):\n    span = _to_span(mention)\n    id_names = []\n    i = _get_node(span.sentence)\n    while i is not None:\n        id_names.insert(0, str(i.get(\"id\")))\n        i = i.getparent()\n    return id_names",
    "docstring": "Return the HTML id's of the Mention's ancestors.\n\n    If a candidate is passed in, only the ancestors of its first Mention are\n    returned.\n\n    :param mention: The Mention to evaluate\n    :rtype: list of strings"
  },
  {
    "code": "def update_lun(self, add_luns=None, remove_luns=None):\n        if not add_luns and not remove_luns:\n            log.debug(\"Empty add_luns and remove_luns passed in, \"\n                      \"skip update_lun.\")\n            return RESP_OK\n        lun_add = self._prepare_luns_add(add_luns)\n        lun_remove = self._prepare_luns_remove(remove_luns, True)\n        return self.modify(lun_add=lun_add, lun_remove=lun_remove)",
    "docstring": "Updates the LUNs in CG, adding the ones in `add_luns` and removing\n        the ones in `remove_luns`"
  },
  {
    "code": "def install(replace_existing=False):\n    bunch = AutoBunch()\n    bunch.name = 'DAPA'\n    bunch.protocol = 'dapa'\n    bunch.force = 'true'\n    install_programmer('dapa', bunch, replace_existing=replace_existing)",
    "docstring": "install dapa programmer."
  },
  {
    "code": "def BuildFindSpecs(self, artifact_filter_names, environment_variables=None):\n    find_specs = []\n    for name in artifact_filter_names:\n      definition = self._artifacts_registry.GetDefinitionByName(name)\n      if not definition:\n        logger.debug('undefined artifact definition: {0:s}'.format(name))\n        continue\n      logger.debug('building find spec from artifact definition: {0:s}'.format(\n          name))\n      artifact_find_specs = self._BuildFindSpecsFromArtifact(\n          definition, environment_variables)\n      find_specs.extend(artifact_find_specs)\n    for find_spec in find_specs:\n      if isinstance(find_spec, file_system_searcher.FindSpec):\n        self.file_system_find_specs.append(find_spec)\n      elif isinstance(find_spec, registry_searcher.FindSpec):\n        self.registry_find_specs.append(find_spec)\n      else:\n        logger.warning('Unsupported find specification type: {0:s}'.format(\n            type(find_spec)))",
    "docstring": "Builds find specifications from artifact definitions.\n\n    Args:\n      artifact_filter_names (list[str]): names of artifact definitions that are\n          used for filtering file system and Windows Registry key paths.\n      environment_variables (Optional[list[EnvironmentVariableArtifact]]):\n          environment variables."
  },
  {
    "code": "def _create_thumbnail(self, model_instance, thumbnail, image_name):\n        thumbnail = self._do_resize(thumbnail, self.thumbnail_size)\n        full_image_name = self.generate_filename(model_instance, image_name)\n        thumbnail_filename = _get_thumbnail_filename(full_image_name)\n        thumb = self._get_simple_uploaded_file(thumbnail, thumbnail_filename)\n        self.storage.save(thumbnail_filename, thumb)",
    "docstring": "Resizes and saves the thumbnail image"
  },
  {
    "code": "def set(self, key, value):\n        if key == \"tags\":\n            self._set_tag(tags=value)\n        else:\n            if isinstance(value, dict) and key in self._requirements and isinstance(\n                    self._requirements[key], dict):\n                self._requirements[key] = merge(self._requirements[key], value)\n            else:\n                self._requirements[key] = value",
    "docstring": "Sets the value for a specific requirement.\n\n        :param key: Name of requirement to be set\n        :param value: Value to set for requirement key\n        :return: Nothing, modifies requirement"
  },
  {
    "code": "def _start_new_worker_process(self, server_socket):\n        from multiprocessing import Process\n        p = Process(target=forked_child, args=self._get_child_args(server_socket))\n        p.start()\n        return p",
    "docstring": "Start a new child worker process which will listen on the given\n        socket and return a reference to the new process."
  },
  {
    "code": "def _reverse_transform_column(self, table, metadata, table_name):\n        column_name = metadata['name']\n        if column_name not in table:\n            return\n        null_name = '?' + column_name\n        content = pd.DataFrame(columns=[column_name], index=table.index)\n        transformer = self.transformers[(table_name, column_name)]\n        content[column_name] = transformer.reverse_transform(table[column_name].to_frame())\n        if self.missing and null_name in table[column_name]:\n            content[null_name] = table.pop(null_name)\n            null_transformer = transformers.NullTransformer(metadata)\n            content[column_name] = null_transformer.reverse_transform(content)\n        return content",
    "docstring": "Reverses the transformtion on a column from table using the given parameters.\n\n        Args:\n            table (pandas.DataFrame): Dataframe containing column to transform.\n            metadata (dict): Metadata for given column.\n            table_name (str): Name of table in original dataset.\n\n        Returns:\n            pandas.DataFrame: Dataframe containing the transformed column. If self.missing=True,\n                              it will contain a second column containing 0 and 1 marking if that\n                              value was originally null or not.\n                              It will return None in the case the column is not in the table."
  },
  {
    "code": "def get_new_members(self, results):\n        for member in results:\n            guid = member.pop('guid')\n            yield Member(self.manager, self.group_id, **member)\n            member['guid'] = guid",
    "docstring": "Return the newly added members.\n\n        :param results: the results of a membership request check\n        :type results: :class:`list`\n        :return: the successful requests, as :class:`~groupy.api.memberships.Members`\n        :rtype: generator"
  },
  {
    "code": "def change_customer_nc_users_quota(sender, structure, user, role, signal, **kwargs):\n    assert signal in (signals.structure_role_granted, signals.structure_role_revoked), \\\n        'Handler \"change_customer_nc_users_quota\" has to be used only with structure_role signals'\n    assert sender in (Customer, Project), \\\n        'Handler \"change_customer_nc_users_quota\" works only with Project and Customer models'\n    if sender == Customer:\n        customer = structure\n    elif sender == Project:\n        customer = structure.customer\n    customer_users = customer.get_users()\n    customer.set_quota_usage(Customer.Quotas.nc_user_count, customer_users.count())",
    "docstring": "Modify nc_user_count quota usage on structure role grant or revoke"
  },
  {
    "code": "def bounds(self):\n        corners = [self.image_corner(corner) for corner in self.corner_types()]\n        return Polygon([[corner.x, corner.y] for corner in corners])",
    "docstring": "Return image rectangle in pixels, as shapely.Polygon."
  },
  {
    "code": "def grab_literal(template, l_del):\n    global _CURRENT_LINE\n    try:\n        literal, template = template.split(l_del, 1)\n        _CURRENT_LINE += literal.count('\\n')\n        return (literal, template)\n    except ValueError:\n        return (template, '')",
    "docstring": "Parse a literal from the template"
  },
  {
    "code": "def _get_scalexy(self, ims_width, ims_height):\n        cell_attributes = self.code_array.cell_attributes[self.key]\n        angle = cell_attributes[\"angle\"]\n        if abs(angle) == 90:\n            scale_x = self.rect[3] / float(ims_width)\n            scale_y = self.rect[2] / float(ims_height)\n        else:\n            scale_x = self.rect[2] / float(ims_width)\n            scale_y = self.rect[3] / float(ims_height)\n        return scale_x, scale_y",
    "docstring": "Returns scale_x, scale_y for bitmap display"
  },
  {
    "code": "def sign_nonce(key, nonce):\n    return Cryptodome.Hash.HMAC.new(key, nonce, digestmod=Cryptodome.Hash.SHA256).digest()",
    "docstring": "sign the server nonce from the WWW-Authenticate header with an authKey"
  },
  {
    "code": "def nn_allocmsg(size, type):\n    \"allocate a message\"\n    pointer = _nn_allocmsg(size, type)\n    if pointer is None:\n        return None\n    return _create_message(pointer, size)",
    "docstring": "allocate a message"
  },
  {
    "code": "def file_iterator(filehandle, verbose=False):\n  if type(filehandle).__name__ == \"str\":\n    filehandle = open(filehandle)\n  if verbose:\n    try:\n      pind = ProgressIndicator(totalToDo=os.path.getsize(filehandle.name),\n                               messagePrefix=\"completed\",\n                               messageSuffix=\"of processing \" +\n                                             filehandle.name)\n    except AttributeError:\n      sys.stderr.write(\"BEDIterator -- warning: \" +\n                       \"unable to show progress for stream\")\n      verbose = False\n  for line in filehandle:\n    line = line.rstrip('\\n')\n    if verbose:\n      pind.done = filehandle.tell()\n      pind.showProgress()\n    if line == \"\":\n      continue\n    yield line",
    "docstring": "Iterate over a file and yield stripped lines. Optionally show progress."
  },
  {
    "code": "def install_client_interceptors(client_interceptors=()):\n    if not _valid_args(client_interceptors):\n        raise ValueError('client_interceptors argument must be a list')\n    from ..http_client import ClientInterceptors\n    for client_interceptor in client_interceptors:\n        logging.info('Loading client interceptor %s', client_interceptor)\n        interceptor_class = _load_symbol(client_interceptor)\n        logging.info('Adding client interceptor %s', client_interceptor)\n        ClientInterceptors.append(interceptor_class())",
    "docstring": "Install client interceptors for the patchers.\n\n    :param client_interceptors: a list of client interceptors to install.\n        Should be a list of classes"
  },
  {
    "code": "def wait_for_at_least_one_message(self, channel):\n        unpacker = msgpack.Unpacker(encoding='utf-8')\n        while True:\n            try:\n                start = time.time()\n                chunk = self.ssh_channel[channel].recv(1024)\n                end = time.time()\n                self.read_speeds.append( len(chunk) / (end-start) )\n                if len(self.read_speeds) > 20:\n                    self.read_speeds = self.read_speeds[10:]\n                if chunk == b'':\n                    self.connection_error(channel, 'Connection broken w')\n                    return False\n            except Exception as error:\n                self.connection_error(channel, error)\n                raise\n            unpacker.feed(chunk)\n            messages = [m for m in unpacker]\n            if messages:\n                return messages",
    "docstring": "Reads until we receive at least one message we can unpack. Return all found messages."
  },
  {
    "code": "def branch_exists(self, branch):\n        try:\n            git(self.gitdir, self.gitwd, \"rev-parse\", branch)\n        except sh.ErrorReturnCode:\n            return False\n        return True",
    "docstring": "Returns true or false depending on if a branch exists"
  },
  {
    "code": "def RunOnce(self):\n    if config.CONFIG[\"Cron.active\"]:\n      self.cron_worker = CronWorker()\n      self.cron_worker.RunAsync()",
    "docstring": "Main CronHook method."
  },
  {
    "code": "def update_letter_comment(self, letter_comment_id, letter_comment_dict):\n        return self._create_put_request(\n            resource=LETTER_COMMENTS,\n            billomat_id=letter_comment_id,\n            send_data=letter_comment_dict\n        )",
    "docstring": "Updates a letter comment\n\n        :param letter_comment_id: the letter command id\n        :param letter_comment_dict: dict\n        :return: dict"
  },
  {
    "code": "def set_colour(self, r, g, b):\n        if not 0 <= r <= 255:\n            raise ValueError(\"The value for red needs to be between 0 and 255.\")\n        if not 0 <= g <= 255:\n            raise ValueError(\"The value for green needs to be between 0 and 255.\")\n        if not 0 <= b <= 255:\n            raise ValueError(\"The value for blue needs to be between 0 and 255.\")\n        hexvalue = BulbDevice._rgb_to_hexvalue(r, g, b)\n        payload = self.generate_payload(SET, {\n            self.DPS_INDEX_MODE: self.DPS_MODE_COLOUR,\n            self.DPS_INDEX_COLOUR: hexvalue})\n        data = self._send_receive(payload)\n        return data",
    "docstring": "Set colour of an rgb bulb.\n\n        Args:\n            r(int): Value for the colour red as int from 0-255.\n            g(int): Value for the colour green as int from 0-255.\n            b(int): Value for the colour blue as int from 0-255."
  },
  {
    "code": "def new_stats_exporter(options=None, interval=None):\n    if options is None:\n        _, project_id = google.auth.default()\n        options = Options(project_id=project_id)\n    if str(options.project_id).strip() == \"\":\n        raise ValueError(ERROR_BLANK_PROJECT_ID)\n    ci = client_info.ClientInfo(client_library_version=get_user_agent_slug())\n    client = monitoring_v3.MetricServiceClient(client_info=ci)\n    exporter = StackdriverStatsExporter(client=client, options=options)\n    transport.get_exporter_thread(stats.stats, exporter, interval=interval)\n    return exporter",
    "docstring": "Get a stats exporter and running transport thread.\n\n    Create a new `StackdriverStatsExporter` with the given options and start\n    periodically exporting stats to stackdriver in the background.\n\n    Fall back to default auth if `options` is null. This will raise\n    `google.auth.exceptions.DefaultCredentialsError` if default credentials\n    aren't configured.\n\n    See `opencensus.metrics.transport.get_exporter_thread` for details on the\n    transport thread.\n\n    :type options: :class:`Options`\n    :param exporter: Options to pass to the exporter\n\n    :type interval: int or float\n    :param interval: Seconds between export calls.\n\n    :rtype: :class:`StackdriverStatsExporter`\n    :return: The newly-created exporter."
  },
  {
    "code": "def start_event_loop(self, timeout=0):\n        if hasattr(self, '_event_loop'):\n            raise RuntimeError(\"Event loop already running\")\n        id = wx.NewId()\n        timer = wx.Timer(self, id=id)\n        if timeout > 0:\n            timer.Start(timeout*1000, oneShot=True)\n            bind(self, wx.EVT_TIMER, self.stop_event_loop, id=id)\n        self._event_loop = wx.EventLoop()\n        self._event_loop.Run()\n        timer.Stop()",
    "docstring": "Start an event loop.  This is used to start a blocking event\n        loop so that interactive functions, such as ginput and\n        waitforbuttonpress, can wait for events.  This should not be\n        confused with the main GUI event loop, which is always running\n        and has nothing to do with this.\n\n        Call signature::\n\n        start_event_loop(self,timeout=0)\n\n        This call blocks until a callback function triggers\n        stop_event_loop() or *timeout* is reached.  If *timeout* is\n        <=0, never timeout.\n\n        Raises RuntimeError if event loop is already running."
  },
  {
    "code": "def set_parameters(self, **args):\n        for k, v in self.PARAMETERS.items():\n            new_value = args.get(k)\n            if new_value != None:\n                if not _same_type(new_value, v):\n                    raise Exception(\n                        \"On processor {0}, argument {1} takes something like {2}, but {3} was given\".format(self, k, v,\n                                                                                                            new_value))\n                setattr(self, k, new_value)\n        not_used = set(args.keys()).difference(set(self.PARAMETERS.keys()))\n        not_given = set(self.PARAMETERS.keys()).difference(set(args.keys()))\n        return not_used, not_given",
    "docstring": "sets the processor stored parameters"
  },
  {
    "code": "def visit_FunctionDef(self, node):\n        node = self.get_function_node(node)\n        if node is not None:\n            node._async = False",
    "docstring": "Visit a function node."
  },
  {
    "code": "def help(self):\n        message = m.Message()\n        message.add(m.Brand())\n        message.add(self.help_heading())\n        message.add(self.help_content())\n        return message",
    "docstring": "Return full help message for the step wizard.\n\n        :returns: A message object contains help text.\n        :rtype: m.Message"
  },
  {
    "code": "def read_welcome_message(self):\n        reply = yield from self._control_stream.read_reply()\n        self.raise_if_not_match(\n            'Server ready', ReplyCodes.service_ready_for_new_user, reply)",
    "docstring": "Read the welcome message.\n\n        Coroutine."
  },
  {
    "code": "def segment_pofiles(configuration, locale):\n    files_written = set()\n    for filename, segments in configuration.segment.items():\n        filename = configuration.get_messages_dir(locale) / filename\n        files_written.update(segment_pofile(filename, segments))\n    return files_written",
    "docstring": "Segment all the pofiles for `locale`.\n\n    Returns a set of filenames, all the segment files written."
  },
  {
    "code": "def load(self, filepath):\n        with open(filepath, 'rb') as fd:\n            num_keys = struct.unpack(\">i\", fd.read(4))[0]\n            for i in range(num_keys):\n                row, value, kind = struct.unpack('>ifb', fd.read(9))\n                self.keys.append(TrackKey(row, value, kind))",
    "docstring": "Load the track file"
  },
  {
    "code": "def rdirichlet(theta, size=1):\n    gammas = np.vstack([rgamma(theta, 1) for i in xrange(size)])\n    if size > 1 and np.size(theta) > 1:\n        return (gammas.T / gammas.sum(1))[:-1].T\n    elif np.size(theta) > 1:\n        return (gammas[0] / gammas[0].sum())[:-1]\n    else:\n        return 1.",
    "docstring": "Dirichlet random variates."
  },
  {
    "code": "def newline(self):\n        self.write_str(self.eol)\n        self.room = self.maxlinelen",
    "docstring": "Write eol, then start new line."
  },
  {
    "code": "def _reformat(p, buf):\n    if numpy.ndim(buf) != 1:\n        raise ValueError(\"Buffer ``buf`` must be 1-d.\")\n    if hasattr(p, 'keys'):\n        ans = _gvar.BufferDict(p)\n        if ans.size != len(buf):\n            raise ValueError(\n                \"p, buf size mismatch: %d, %d\"%(ans.size, len(buf)))\n        ans = _gvar.BufferDict(ans, buf=buf)\n    else:\n        if numpy.size(p) != len(buf):\n            raise ValueError(\n                \"p, buf size mismatch: %d, %d\"%(numpy.size(p), len(buf)))\n        ans = numpy.array(buf).reshape(numpy.shape(p))\n    return ans",
    "docstring": "Apply format of ``p`` to data in 1-d array ``buf``."
  },
  {
    "code": "def _get(self, key, identity='image'):\n        value = self._get_raw(add_prefix(key, identity))\n        if not value:\n            return None\n        if identity == 'image':\n            return deserialize_image_file(value)\n        return deserialize(value)",
    "docstring": "Deserializing, prefix wrapper for _get_raw"
  },
  {
    "code": "def depth_first_iter(self, self_first=True):\n        if self_first:\n            yield self\n        for child in list(self.children):\n            for i in child.depth_first_iter(self_first):\n                yield i\n        if not self_first:\n            yield self",
    "docstring": "Iterate over nodes below this node, optionally yielding children before\n        self."
  },
  {
    "code": "def get_primary_text(self, item_url):\n        c = self.conn.cursor()\n        c.execute(\"SELECT * FROM primary_texts WHERE item_url=?\",\n                      (str(item_url),))\n        row = c.fetchone()\n        c.close()\n        if row is None:\n            raise ValueError(\"Item not present in cache\")\n        return row[1]",
    "docstring": "Retrieve the primary text for the given item from the cache.\n\n        :type item_url: String or Item\n        :param item_url: the URL of the item, or an Item object\n\n        :rtype: String\n        :returns: the primary text\n\n        :raises: ValueError if the primary text is not in the cache"
  },
  {
    "code": "def yahoo(base, target):\n    api_url = 'http://download.finance.yahoo.com/d/quotes.csv'\n    resp = requests.get(\n        api_url,\n        params={\n            'e': '.csv',\n            'f': 'sl1d1t1',\n            's': '{0}{1}=X'.format(base, target)\n        },\n        timeout=1,\n    )\n    value = resp.text.split(',', 2)[1]\n    return decimal.Decimal(value)",
    "docstring": "Parse data from Yahoo."
  },
  {
    "code": "def check_status(self):\n        for task in self:\n            if task.status in (task.S_OK, task.S_LOCKED): continue\n            task.check_status()\n        for task in self:\n            if task.status == task.S_LOCKED: continue\n            if task.status < task.S_SUB and all(status == task.S_OK for status in task.deps_status):\n                task.set_status(task.S_READY, \"Status set to Ready\")",
    "docstring": "Check the status of the tasks."
  },
  {
    "code": "def fileids(self):\n        return [os.path.join(self.path,i) for i in os.listdir(self.path)]",
    "docstring": "Returns files from SemEval2007 Coarse-grain All-words WSD task."
  },
  {
    "code": "def convert(model, input_features, output_features):\n    if not(_HAS_SKLEARN):\n        raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')\n    _sklearn_util.check_expected_type(model, Normalizer)\n    _sklearn_util.check_fitted(model, lambda m: hasattr(m, 'norm'))\n    spec = _Model_pb2.Model()\n    spec.specificationVersion = SPECIFICATION_VERSION\n    spec = _set_transform_interface_params(spec, input_features, output_features)\n    _normalizer_spec = spec.normalizer\n    if model.norm == 'l1':\n        _normalizer_spec.normType = _proto__normalizer.L1\n    elif model.norm == 'l2':\n        _normalizer_spec.normType = _proto__normalizer.L2\n    elif model.norm == 'max':\n        _normalizer_spec.normType = _proto__normalizer.LMax\n    return _MLModel(spec)",
    "docstring": "Convert a normalizer model to the protobuf spec.\n\n    Parameters\n    ----------\n    model: Normalizer\n        A Normalizer.\n\n    input_features: str\n        Name of the input column.\n\n    output_features: str\n        Name of the output column.\n\n    Returns\n    -------\n    model_spec: An object of type Model_pb.\n        Protobuf representation of the model"
  },
  {
    "code": "def load_pascal(image_set, year, devkit_path, shuffle=False):\n    image_set = [y.strip() for y in image_set.split(',')]\n    assert image_set, \"No image_set specified\"\n    year = [y.strip() for y in year.split(',')]\n    assert year, \"No year specified\"\n    if len(image_set) > 1 and len(year) == 1:\n        year = year * len(image_set)\n    if len(image_set) == 1 and len(year) > 1:\n        image_set = image_set * len(year)\n    assert len(image_set) == len(year), \"Number of sets and year mismatch\"\n    imdbs = []\n    for s, y in zip(image_set, year):\n        imdbs.append(PascalVoc(s, y, devkit_path, shuffle, is_train=True))\n    if len(imdbs) > 1:\n        return ConcatDB(imdbs, shuffle)\n    else:\n        return imdbs[0]",
    "docstring": "wrapper function for loading pascal voc dataset\n\n    Parameters:\n    ----------\n    image_set : str\n        train, trainval...\n    year : str\n        2007, 2012 or combinations splitted by comma\n    devkit_path : str\n        root directory of dataset\n    shuffle : bool\n        whether to shuffle initial list\n\n    Returns:\n    ----------\n    Imdb"
  },
  {
    "code": "def get_icon_for(self, brain_or_object):\n        portal_types = api.get_tool(\"portal_types\")\n        fti = portal_types.getTypeInfo(api.get_portal_type(brain_or_object))\n        icon = fti.getIcon()\n        if not icon:\n            return \"\"\n        icon_big = icon.replace(\".png\", \"_big.png\")\n        if self.context.restrictedTraverse(icon_big, None) is None:\n            icon_big = None\n        portal_url = api.get_url(api.get_portal())\n        title = api.get_title(brain_or_object)\n        html_tag = \"<img title='{}' src='{}/{}' width='16' />\".format(\n            title, portal_url, icon_big or icon)\n        logger.info(\"Generated Icon Tag for {}: {}\".format(\n            api.get_path(brain_or_object), html_tag))\n        return html_tag",
    "docstring": "Get the navigation portlet icon for the brain or object\n\n        The cache key ensures that the lookup is done only once per domain name"
  },
  {
    "code": "def platform_from_version(major, minor):\n    v = (major, minor)\n    for low, high, name in _platforms:\n        if low <= v <= high:\n            return name\n    return None",
    "docstring": "returns the minimum platform version that can load the given class\n    version indicated by major.minor or None if no known platforms\n    match the given version"
  },
  {
    "code": "def crval(self):\n        try:\n            return self.wcs.crval1, self.wcs.crval2\n        except Exception as ex:\n            logging.debug(\"Couldn't get CRVAL from WCS: {}\".format(ex))\n            logging.debug(\"Trying RA/DEC values\")\n        try:\n            return (float(self['RA-DEG']),\n                    float(self['DEC-DEG']))\n        except KeyError as ke:\n            KeyError(\"Can't build CRVAL1/2 missing keyword: {}\".format(ke.args[0]))",
    "docstring": "Get the world coordinate of the reference pixel.\n\n        @rtype: float, float"
  },
  {
    "code": "def get_datetime_issue_in_progress(self, issue):\n        histories = issue.changelog.histories\n        for history in reversed(histories):\n            history_items = history.items\n            for item in history_items:\n                if item.field == 'status' and item.toString == \"In Progress\":\n                    return dateutil.parser.parse(history.created)",
    "docstring": "If the issue is in progress, gets that most recent time that the issue became 'In Progress'"
  },
  {
    "code": "def detachAcceptMsOriginating():\n    a = TpPd(pd=0x3)\n    b = MessageType(mesType=0x6)\n    c = ForceToStandbyAndSpareHalfOctets()\n    packet = a / b / c\n    return packet",
    "docstring": "DETACH ACCEPT Section 9.4.6.2"
  },
  {
    "code": "def targetMed(self):\n        med_byte = None\n        if self.target.addr is not None and self._messageFlags.isBroadcast:\n            med_byte = self.target.bytes[1]\n        return med_byte",
    "docstring": "Return the middle byte of the target message property.\n\n        Used in All-Link Cleanup message types."
  },
  {
    "code": "def get_proxies_from_environ():\n    proxies = {}\n    http_proxy = os.getenv('http_proxy') or os.getenv('HTTP_PROXY')\n    https_proxy = os.getenv('https_proxy') or os.getenv('HTTPS_PROXY')\n    if http_proxy:\n        proxies['http'] = http_proxy\n    if https_proxy:\n        proxies['https'] = https_proxy\n    return proxies",
    "docstring": "Get proxies from os.environ."
  },
  {
    "code": "def build_output_table(cls, name='inputTableName', output_name='output'):\n        obj = cls(name)\n        obj.exporter = 'get_output_table_name'\n        obj.output_name = output_name\n        return obj",
    "docstring": "Build an output table parameter\n\n        :param name: parameter name\n        :type name: str\n        :param output_name: bind input port name\n        :type output_name: str\n        :return: output description\n        :rtype: ParamDef"
  },
  {
    "code": "def lookup(self, label):\n        if self.is_child:\n            try:\n                return self._children[label]\n            except KeyError:\n                self._children[label] = ChildFieldPicklist(self.parent, \n                                                           label, \n                                                           self.field_name) \n                return self._children[label]\n        else:\n            return get_label_value(label, self._picklist)",
    "docstring": "take a field_name_label and return the id"
  },
  {
    "code": "def queue_ramp_dicts(ramp_dict_list, server_ip_and_port):\n    client = server.ClientForServer(server.BECServer, server_ip_and_port)\n    for dct in ramp_dict_list:\n        client.queue_ramp(dct)\n    client.start({})",
    "docstring": "Simple utility function to queue up a list of dictionaries."
  },
  {
    "code": "def setup(app):\n    \"Setup function for Sphinx Extension\"\n    app.add_config_value(\"sphinx_to_github\", True, '')\n    app.add_config_value(\"sphinx_to_github_verbose\", True, '')\n    app.connect(\"build-finished\", sphinx_extension)",
    "docstring": "Setup function for Sphinx Extension"
  },
  {
    "code": "def makeCubiccFunc(self,mNrm,cNrm):\n        EndOfPrdvPP = self.DiscFacEff*self.Rfree*self.Rfree*self.PermGroFac**(-self.CRRA-1.0)* \\\n                      np.sum(self.PermShkVals_temp**(-self.CRRA-1.0)*\n                             self.vPPfuncNext(self.mNrmNext)*self.ShkPrbs_temp,axis=0)\n        dcda        = EndOfPrdvPP/self.uPP(np.array(cNrm[1:]))\n        MPC         = dcda/(dcda+1.)\n        MPC         = np.insert(MPC,0,self.MPCmaxNow)\n        cFuncNowUnc = CubicInterp(mNrm,cNrm,MPC,self.MPCminNow*self.hNrmNow,self.MPCminNow)\n        return cFuncNowUnc",
    "docstring": "Makes a cubic spline interpolation of the unconstrained consumption\n        function for this period.\n\n        Parameters\n        ----------\n        mNrm : np.array\n            Corresponding market resource points for interpolation.\n        cNrm : np.array\n            Consumption points for interpolation.\n\n        Returns\n        -------\n        cFuncUnc : CubicInterp\n            The unconstrained consumption function for this period."
  },
  {
    "code": "def add_object(self, obj):\n        state = self.state\n        if not obj.layer in state.layers:\n            state.layers[obj.layer] = {}\n        state.layers[obj.layer][obj.key] = obj\n        state.need_redraw = True",
    "docstring": "add an object to a later"
  },
  {
    "code": "def update_assessment(self, assessment_form):\n        collection = JSONClientValidated('assessment',\n                                         collection='Assessment',\n                                         runtime=self._runtime)\n        if not isinstance(assessment_form, ABCAssessmentForm):\n            raise errors.InvalidArgument('argument type is not an AssessmentForm')\n        if not assessment_form.is_for_update():\n            raise errors.InvalidArgument('the AssessmentForm is for update only, not create')\n        try:\n            if self._forms[assessment_form.get_id().get_identifier()] == UPDATED:\n                raise errors.IllegalState('assessment_form already used in an update transaction')\n        except KeyError:\n            raise errors.Unsupported('assessment_form did not originate from this session')\n        if not assessment_form.is_valid():\n            raise errors.InvalidArgument('one or more of the form elements is invalid')\n        collection.save(assessment_form._my_map)\n        self._forms[assessment_form.get_id().get_identifier()] = UPDATED\n        return objects.Assessment(\n            osid_object_map=assessment_form._my_map,\n            runtime=self._runtime,\n            proxy=self._proxy)",
    "docstring": "Updates an existing assessment.\n\n        arg:    assessment_form (osid.assessment.AssessmentForm): the\n                form containing the elements to be updated\n        raise:  IllegalState - ``assessment_form`` already used in an\n                update transaction\n        raise:  InvalidArgument - the form contains an invalid value\n        raise:  NullArgument - ``assessment_form`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        raise:  Unsupported - ``assessment_form did not originate from\n                get_assessment_form_for_update()``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def reset(self):\n        logger.debug('resetting dongle state')\n        self._clear()\n        if self.api is not None:\n            self._set_state(Dongle._STATE_RESET)\n            self.api.ble_cmd_gap_set_mode(gap_discoverable_mode['gap_non_discoverable'], gap_connectable_mode['gap_non_connectable'])\n            self._wait_for_state(self._STATE_RESET)\n            for i in range(self.supported_connections):\n                self._set_conn_state(i, self._STATE_DISCONNECTING)\n                self.api.ble_cmd_connection_disconnect(i)\t\n                self._wait_for_conn_state(i, self._STATE_DISCONNECTING)\n        logger.debug('reset completed')",
    "docstring": "Attempts to reset the dongle to a known state.\n\n        When called, this method will reset the internal state of the object, and\n        disconnect any active connections."
  },
  {
    "code": "def get_user(uid, channel=14, **kwargs):\n    name = get_user_name(uid, **kwargs)\n    access = get_user_access(uid, channel, **kwargs)\n    data = {'name': name, 'uid': uid, 'channel': channel, 'access': access['access']}\n    return data",
    "docstring": "Get user from uid and access on channel\n\n    :param uid: user number [1:16]\n    :param channel: number [1:7]\n    :param kwargs:\n        - api_host=127.0.0.1\n        - api_user=admin\n        - api_pass=example\n        - api_port=623\n        - api_kg=None\n\n    Return Data\n\n    .. code-block:: none\n\n        name: (str)\n        uid: (int)\n        channel: (int)\n        access:\n            - callback (bool)\n            - link_auth (bool)\n            - ipmi_msg (bool)\n            - privilege_level: (str)[callback, user, operatorm administrator,\n                                    proprietary, no_access]\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt-call ipmi.get_user uid=2"
  },
  {
    "code": "def _nominal_kernel(x, y, out):\n    for i in range(x.shape[0]):\n        for j in range(y.shape[0]):\n            out[i, j] += (x[i, :] == y[j, :]).sum()\n    return out",
    "docstring": "Number of features that match exactly"
  },
  {
    "code": "def policy(self):\n        policies = VNXIOPolicy.get(cli=self._cli)\n        ret = None\n        for policy in policies:\n            contained = policy.ioclasses.name\n            if self._get_name() in contained:\n                ret = VNXIOPolicy.get(name=policy.name, cli=self._cli)\n                break\n        return ret",
    "docstring": "Returns policy which contains this ioclass."
  },
  {
    "code": "def clients(self):\n        clients_response = self.get_request('clients/')\n        return [Client(self, cjson['client']) for cjson in clients_response]",
    "docstring": "Generates a list of all Clients."
  },
  {
    "code": "def ls_dir(base_dir):\n    return [\n        os.path.join(dirpath.replace(base_dir, '', 1), f)\n        for (dirpath, dirnames, files) in os.walk(base_dir)\n        for f in files\n    ]",
    "docstring": "List files recursively."
  },
  {
    "code": "def get_strategy(name_or_cls):\n    if isinstance(name_or_cls, six.string_types):\n        if name_or_cls not in STRATS:\n            raise MutationError(\"strat is not defined\")\n        return STRATS[name_or_cls]()\n    return name_or_cls()",
    "docstring": "Return the strategy identified by its name. If ``name_or_class`` is a class,\n    it will be simply returned."
  },
  {
    "code": "def _get_dependencies_from_cache(ireq):\n    if os.environ.get(\"PASSA_IGNORE_LOCAL_CACHE\"):\n        return\n    if ireq.editable:\n        return\n    try:\n        deps = DEPENDENCY_CACHE[ireq]\n        pyrq = REQUIRES_PYTHON_CACHE[ireq]\n    except KeyError:\n        return\n    try:\n        packaging.specifiers.SpecifierSet(pyrq)\n        ireq_name = packaging.utils.canonicalize_name(ireq.name)\n        if any(_is_cache_broken(line, ireq_name) for line in deps):\n            broken = True\n        else:\n            broken = False\n    except Exception:\n        broken = True\n    if broken:\n        print(\"dropping broken cache for {0}\".format(ireq.name))\n        del DEPENDENCY_CACHE[ireq]\n        del REQUIRES_PYTHON_CACHE[ireq]\n        return\n    return deps, pyrq",
    "docstring": "Retrieves dependencies for the requirement from the dependency cache."
  },
  {
    "code": "def missing_property_names(self):\n        propname = lambda x: self.__prop_names__[x]\n        missing = []\n        for x in self.__required__:\n            propinfo = self.propinfo(propname(x))\n            null_type = False\n            if 'type' in propinfo:\n                type_info = propinfo['type']\n                null_type = (type_info == 'null'\n                             or isinstance(type_info, (list, tuple))\n                             and 'null' in type_info)\n            elif 'oneOf' in propinfo:\n                for o in propinfo['oneOf']:\n                    type_info = o.get('type')\n                    if type_info and type_info == 'null' \\\n                            or isinstance(type_info, (list, tuple)) \\\n                            and 'null' in type_info:\n                        null_type = True\n                        break\n            if (propname(x) not in self._properties and null_type) or \\\n                    (self._properties[propname(x)] is None and not null_type):\n                missing.append(x)\n        return missing",
    "docstring": "Returns a list of properties which are required and missing.\n\n        Properties are excluded from this list if they are allowed to be null.\n\n        :return: list of missing properties."
  },
  {
    "code": "def to_struct_file(self, f):\n        if isinstance(f, str):\n            f = open(f,'w')\n        f.write(\"STRUCTURE {0}\\n\".format(self.name))\n        f.write(\"  NUGGET {0}\\n\".format(self.nugget))\n        f.write(\"  NUMVARIOGRAM {0}\\n\".format(len(self.variograms)))\n        for v in self.variograms:\n            f.write(\"  VARIOGRAM {0} {1}\\n\".format(v.name,v.contribution))\n        f.write(\"  TRANSFORM {0}\\n\".format(self.transform))\n        f.write(\"END STRUCTURE\\n\\n\")\n        for v in self.variograms:\n            v.to_struct_file(f)",
    "docstring": "write a PEST-style structure file\n\n        Parameters\n        ----------\n        f : (str or file handle)\n            file to write the GeoStruct information to"
  },
  {
    "code": "def get_proj(geom, proj_list=None):\n    out_srs = None\n    if proj_list is None:\n        proj_list = gen_proj_list()\n    for projbox in proj_list:\n        if projbox.geom.Intersects(geom):\n            out_srs = projbox.srs\n            break\n    if out_srs is None:\n        out_srs = getUTMsrs(geom)\n    return out_srs",
    "docstring": "Determine best projection for input geometry"
  },
  {
    "code": "def size(self, units=\"MiB\"):\n        self.open()\n        size = lvm_vg_get_size(self.handle)\n        self.close()\n        return size_convert(size, units)",
    "docstring": "Returns the volume group size in the given units. Default units are  MiB.\n\n        *Args:*\n\n        *       units (str):    Unit label ('MiB', 'GiB', etc...). Default is MiB."
  },
  {
    "code": "def guest_resize_mem(self, userid, size):\n        action = \"resize guest '%s' to have '%s' memory\" % (userid, size)\n        LOG.info(\"Begin to %s\" % action)\n        with zvmutils.log_and_reraise_sdkbase_error(action):\n            self._vmops.resize_memory(userid, size)\n        LOG.info(\"%s successfully.\" % action)",
    "docstring": "Resize memory of guests.\n\n        :param userid: (str) the userid of the guest to be resized\n        :param size: (str) The memory size that the guest should have\n               defined in user directory after resize.\n               The value should be specified by 1-4 bits of number suffixed by\n               either M (Megabytes) or G (Gigabytes). And the number should be\n               an integer."
  },
  {
    "code": "def _load(self):\n        data = get_data(self.endpoint, self.id_, force_lookup=self.__force_lookup)\n        for key, val in data.items():\n            if key == 'location_area_encounters' \\\n                    and self.endpoint == 'pokemon':\n                params = val.split('/')[-3:]\n                ep, id_, subr = params\n                encounters = get_data(ep, int(id_), subr)\n                data[key] = [_make_obj(enc) for enc in encounters]\n                continue\n            if isinstance(val, dict):\n                data[key] = _make_obj(val)\n            elif isinstance(val, list):\n                data[key] = [_make_obj(i) for i in val]\n        self.__dict__.update(data)\n        return None",
    "docstring": "Function to collect reference data and connect it to the instance as\n         attributes.\n\n         Internal function, does not usually need to be called by the user, as\n         it is called automatically when an attribute is requested.\n\n        :return None"
  },
  {
    "code": "def external_metadata(self, datasource_type=None, datasource_id=None):\n        if datasource_type == 'druid':\n            datasource = ConnectorRegistry.get_datasource(\n                datasource_type, datasource_id, db.session)\n        elif datasource_type == 'table':\n            database = (\n                db.session\n                .query(Database)\n                .filter_by(id=request.args.get('db_id'))\n                .one()\n            )\n            Table = ConnectorRegistry.sources['table']\n            datasource = Table(\n                database=database,\n                table_name=request.args.get('table_name'),\n                schema=request.args.get('schema') or None,\n            )\n        external_metadata = datasource.external_metadata()\n        return self.json_response(external_metadata)",
    "docstring": "Gets column info from the source system"
  },
  {
    "code": "def element(cls, name, parent=None, interleave=None, occur=0):\n        node = cls(\"element\", parent, interleave=interleave)\n        node.attr[\"name\"] = name\n        node.occur = occur\n        return node",
    "docstring": "Create an element node."
  },
  {
    "code": "def _do_register(cls, code, name, hash_name=None, hash_new=None):\n        cls._func_from_name[name.replace('-', '_')] = code\n        cls._func_from_name[name.replace('_', '-')] = code\n        if hash_name:\n            cls._func_from_hash[hash_name] = code\n        cls._func_hash[code] = cls._hash(hash_name, hash_new)",
    "docstring": "Add hash function data to the registry without checks."
  },
  {
    "code": "def add_fabfile():\n    fabfile_src  = os.path.join(PACKAGE_ROOT, 'fabfile.py')\n    fabfile_dest = os.path.join(os.getcwd(), 'fabfile_deployer.py')\n    if os.path.exists(fabfile_dest):\n        print \"`fabfile.py` exists in the current directory. \" \\\n              \"Please remove or rename it and try again.\"\n        return\n    shutil.copyfile(fabfile_src, fabfile_dest)",
    "docstring": "Copy the base fabfile.py to the current working directory."
  },
  {
    "code": "def text_concat(*args, **kwargs):\n    separator = text_value(kwargs.get(\"separator\", \"\"))\n    values = filter(None, [text_value(v) for v in args])\n    return separator.join(values)",
    "docstring": "Concatenate several values as a text string with an optional separator"
  },
  {
    "code": "def parse_xml(data, handle_units):\n    root = ET.fromstring(data)\n    return squish(parse_xml_dataset(root, handle_units))",
    "docstring": "Parse XML data returned by NCSS."
  },
  {
    "code": "def release(self):\n        lock = vars(self).pop('lock', missing)\n        lock is not missing and self._release(lock)",
    "docstring": "Release the lock and cleanup"
  },
  {
    "code": "def _configure_injector(self, modules):\n        self._register()\n        self._create_injector()\n        self._bind_core()\n        self._bind_modules(modules)\n        self.logger.debug(\"Injector configuration with modules {0}.\".format(modules))\n        self._dependencies_initialized = True",
    "docstring": "Create the injector and install the modules.\n\n        There is a necessary order of calls. First we have to bind `Config` and\n        `Zsl`, then we need to register the app into the global stack and then\n        we can install all other modules, which can use `Zsl` and `Config`\n        injection.\n\n        :param modules: list of injection modules\n        :type modules: list"
  },
  {
    "code": "def cudaMallocPitch(pitch, rows, cols, elesize):\n    ptr = ctypes.c_void_p()\n    status = _libcudart.cudaMallocPitch(ctypes.byref(ptr),\n                                        ctypes.c_size_t(pitch), cols*elesize,\n                                        rows)\n    cudaCheckStatus(status)\n    return ptr, pitch",
    "docstring": "Allocate pitched device memory.\n\n    Allocate pitched memory on the device associated with the current active\n    context.\n\n    Parameters\n    ----------\n    pitch : int\n        Pitch for allocation.\n    rows : int\n        Requested pitched allocation height.\n    cols : int\n        Requested pitched allocation width.\n    elesize : int\n        Size of memory element.\n\n    Returns\n    -------\n    ptr : ctypes pointer\n        Pointer to allocated device memory."
  },
  {
    "code": "def array(data, tcoords=None, chcoords=None, scalarcoords=None, datacoords=None, attrs=None, name=None):\n    array = xr.DataArray(data, dims=('t', 'ch'), attrs=attrs, name=name)\n    array.dca._initcoords()\n    if tcoords is not None:\n        array.coords.update({key: ('t', tcoords[key]) for key in tcoords})\n    if chcoords is not None:\n        array.coords.update({key: ('ch', chcoords[key]) for key in chcoords})\n    if scalarcoords is not None:\n        array.coords.update(scalarcoords)\n    if datacoords is not None:\n        array.coords.update({key: (('t', 'ch'), datacoords[key]) for key in datacoords})\n    return array",
    "docstring": "Create an array as an instance of xarray.DataArray with Decode accessor.\n\n    Args:\n        data (numpy.ndarray): 2D (time x channel) array.\n        tcoords (dict, optional): Dictionary of arrays that label time axis.\n        chcoords (dict, optional): Dictionary of arrays that label channel axis.\n        scalarcoords (dict, optional): Dictionary of values that don't label any axes (point-like).\n        datacoords (dict, optional): Dictionary of arrays that label time and channel axes.\n        attrs (dict, optional): Dictionary of attributes to add to the instance.\n        name (str, optional): String that names the instance.\n\n    Returns:\n        array (decode.array): Deode array."
  },
  {
    "code": "def get_repository_form(self, *args, **kwargs):\n        if isinstance(args[-1], list) or 'repository_record_types' in kwargs:\n            return self.get_repository_form_for_create(*args, **kwargs)\n        else:\n            return self.get_repository_form_for_update(*args, **kwargs)",
    "docstring": "Pass through to provider RepositoryAdminSession.get_repository_form_for_update"
  },
  {
    "code": "def infer_type(data):\n    if isinstance(data, (type(None), numbers.Number)):\n        return 'scalar'\n    if isinstance(data, SummaryStats):\n        return 'summarystats'\n    if hasattr(data, \"__len__\"):\n        data = [x for x in data if x is not None]\n        if len(data) == 0 or isinstance(data[0], numbers.Number):\n            return 'distribution_scalar'\n        if isinstance(data[0], SummaryStats):\n            return 'distribution_summarystats'\n        raise TypeError(\n            \"{} is not a valid input. It should be a number, a SummaryStats \"\n            \"object, or None\".format(data[0]))\n    raise TypeError(\n        \"{} is not a valid input. It should be a number, a SummaryStats \"\n        \"object, or a list\".format(data))",
    "docstring": "Infer the type of objects returned by indicators.\n\n    infer_type returns:\n     - 'scalar' for a number or None,\n     - 'summarystats' for a SummaryStats object,\n     - 'distribution_scalar' for a list of scalars,\n     - 'distribution_summarystats' for a list of SummaryStats objects"
  },
  {
    "code": "def cf_tokenize(s):\n    t = []\n    parts = split_re.split(s)\n    for part in parts:\n        cf_func = replace_re.search(part)\n        if cf_func:\n            args = [a.strip(\"'\\\" \") for a in cf_func.group(\"args\").split(\",\")]\n            t.append(HELPERS[cf_func.group(\"helper\")](*args).data)\n        else:\n            t.append(part)\n    return t",
    "docstring": "Parses UserData for Cloudformation helper functions.\n\n    http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html\n    http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html\n    http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-cloudformation.html#scenario-userdata-base64\n\n    It breaks apart the given string at each recognized function (see HELPERS)\n    and instantiates the helper function objects in place of those.\n\n    Returns a list of parts as a result. Useful when used with Join() and\n    Base64() CloudFormation functions to produce user data.\n\n    ie: Base64(Join('', cf_tokenize(userdata_string)))"
  },
  {
    "code": "def convert_softmax(node, **kwargs):\n    name, input_nodes, attrs = get_inputs(node, kwargs)\n    axis = int(attrs.get(\"axis\", -1))\n    softmax_node = onnx.helper.make_node(\n        \"Softmax\",\n        input_nodes,\n        [name],\n        axis=axis,\n        name=name\n    )\n    return [softmax_node]",
    "docstring": "Map MXNet's softmax operator attributes to onnx's Softmax operator\n    and return the created node."
  },
  {
    "code": "def notify(self, instance, old, new):\n        if self._disabled.get(instance, False):\n            return\n        for cback in self._callbacks.get(instance, []):\n            cback(new)\n        for cback in self._2arg_callbacks.get(instance, []):\n            cback(old, new)",
    "docstring": "Call all callback functions with the current value\n\n        Each callback will either be called using\n        callback(new) or callback(old, new) depending\n        on whether ``echo_old`` was set to `True` when calling\n        :func:`~echo.add_callback`\n\n        Parameters\n        ----------\n        instance\n            The instance to consider\n        old\n            The old value of the property\n        new\n            The new value of the property"
  },
  {
    "code": "def remove_editor(self, username, *args, **kwargs):\n        return self.add_editor(username=username, _delete=True, *args,\n                               **kwargs)",
    "docstring": "Remove an editor from this wiki page.\n\n        :param username: The name or Redditor object of the user to remove.\n\n        This method points to :meth:`add_editor` with _delete=True.\n\n        Additional parameters are are passed to :meth:`add_editor` and\n        subsequently into :meth:`~praw.__init__.BaseReddit.request_json`."
  },
  {
    "code": "def set_batch(self, data):\n    rows = self.bucket.view(\"_all_docs\", keys=data.keys(), include_docs=True)\n    existing = {}\n    for row in rows:\n      key = row.id\n      if key and not data[key].has_key(\"_rev\"):\n        data[key][\"_rev\"] = row.doc[\"_rev\"]\n    for id,item in data.items():\n      data[id][\"_id\"] = id\n    revs = {}\n    for success, docid, rev_or_exc in self.bucket.update(data.values()):\n      if not success and self.logger:\n        self.logger.error(\"Document update conflict (batch) '%s', %s\" % (docid, rev_or_exc))\n      elif success:\n        revs[docid] = rev_or_exc\n    return revs",
    "docstring": "Store multiple documents\n    \n    Args\n\n    data <dict> data to store, use document ids as keys\n\n    Returns\n\n    revs <dict> dictionary of new revisions indexed by document ids"
  },
  {
    "code": "def compute_cheby_coeff(f, m=30, N=None, *args, **kwargs):\n    r\n    G = f.G\n    i = kwargs.pop('i', 0)\n    if not N:\n        N = m + 1\n    a_arange = [0, G.lmax]\n    a1 = (a_arange[1] - a_arange[0]) / 2\n    a2 = (a_arange[1] + a_arange[0]) / 2\n    c = np.zeros(m + 1)\n    tmpN = np.arange(N)\n    num = np.cos(np.pi * (tmpN + 0.5) / N)\n    for o in range(m + 1):\n        c[o] = 2. / N * np.dot(f._kernels[i](a1 * num + a2),\n                               np.cos(np.pi * o * (tmpN + 0.5) / N))\n    return c",
    "docstring": "r\"\"\"\n    Compute Chebyshev coefficients for a Filterbank.\n\n    Parameters\n    ----------\n    f : Filter\n        Filterbank with at least 1 filter\n    m : int\n        Maximum order of Chebyshev coeff to compute\n        (default = 30)\n    N : int\n        Grid order used to compute quadrature\n        (default = m + 1)\n    i : int\n        Index of the Filterbank element to compute\n        (default = 0)\n\n    Returns\n    -------\n    c : ndarray\n        Matrix of Chebyshev coefficients"
  },
  {
    "code": "def _write_report(report, file_path):\n        with open(file_path, mode='wb') as f:\n            if not isinstance(report, binary_type):\n                report = report.encode('utf-8')\n            f.write(report)",
    "docstring": "Write report to the given file path."
  },
  {
    "code": "def stop_process(self, process, timeout=None):\n        process[\"terminate\"] = True\n        if timeout is not None:\n            process[\"terminate_at\"] = time.time() + timeout\n        process[\"subprocess\"].send_signal(signal.SIGINT)",
    "docstring": "Initiates a graceful stop of one process"
  },
  {
    "code": "def insert_arguments_into_sql_query(compilation_result, arguments):\n    if compilation_result.language != SQL_LANGUAGE:\n        raise AssertionError(u'Unexpected query output language: {}'.format(compilation_result))\n    base_query = compilation_result.query\n    return base_query.params(**arguments)",
    "docstring": "Insert the arguments into the compiled SQL query to form a complete query.\n\n    Args:\n        compilation_result: CompilationResult, compilation result from the GraphQL compiler.\n        arguments: Dict[str, Any], parameter name -> value, for every parameter the query expects.\n\n    Returns:\n        SQLAlchemy Selectable, a executable SQL query with parameters bound."
  },
  {
    "code": "def _get_default_tempdir():\n    namer = _RandomNameSequence()\n    dirlist = _candidate_tempdir_list()\n    for dir in dirlist:\n        if dir != _os.curdir:\n            dir = _os.path.abspath(dir)\n        for seq in range(100):\n            name = next(namer)\n            filename = _os.path.join(dir, name)\n            try:\n                fd = _os.open(filename, _bin_openflags, 0o600)\n                try:\n                    try:\n                        with _io.open(fd, 'wb', closefd=False) as fp:\n                            fp.write(b'blat')\n                    finally:\n                        _os.close(fd)\n                finally:\n                    _os.unlink(filename)\n                return dir\n            except FileExistsError:\n                pass\n            except OSError:\n                break\n    raise FileNotFoundError(_errno.ENOENT,\n                            \"No usable temporary directory found in %s\" %\n                            dirlist)",
    "docstring": "Calculate the default directory to use for temporary files.\n    This routine should be called exactly once.\n\n    We determine whether or not a candidate temp dir is usable by\n    trying to create and write to a file in that directory.  If this\n    is successful, the test file is deleted.  To prevent denial of\n    service, the name of the test file must be randomized."
  },
  {
    "code": "def toggle(self, event=None):\n        if self.choice.get() == \"yes\":\n            self.rbno.select()\n        else:\n            self.rbyes.select()\n        self.widgetEdited()",
    "docstring": "Toggle value between Yes and No"
  },
  {
    "code": "def stop(self) -> None:\n        self._shutdown = True\n        self._protocol.close()\n        self.cancel_pending_tasks()",
    "docstring": "Stop monitoring the base unit."
  },
  {
    "code": "def clone_rtcpath_update_rt_as(path, new_rt_as):\n    assert path and new_rt_as\n    if not path or path.route_family != RF_RTC_UC:\n        raise ValueError('Expected RT_NLRI path')\n    old_nlri = path.nlri\n    new_rt_nlri = RouteTargetMembershipNLRI(new_rt_as, old_nlri.route_target)\n    return RtcPath(path.source, new_rt_nlri, path.source_version_num,\n                   pattrs=path.pathattr_map, nexthop=path.nexthop,\n                   is_withdraw=path.is_withdraw)",
    "docstring": "Clones given RT NLRI `path`, and updates it with new RT_NLRI AS.\n\n        Parameters:\n            - `path`: (Path) RT_NLRI path\n            - `new_rt_as`: AS value of cloned paths' RT_NLRI"
  },
  {
    "code": "def load_tag(corpus, path):\n        tag_idx = os.path.basename(path)\n        data_path = os.path.join(path, 'by_book')\n        tag_utt_ids = []\n        for gender_path in MailabsReader.get_folders(data_path):\n            if os.path.basename(gender_path) == 'mix':\n                utt_ids = MailabsReader.load_books_of_speaker(corpus,\n                                                              gender_path,\n                                                              None)\n                tag_utt_ids.extend(utt_ids)\n            else:\n                for speaker_path in MailabsReader.get_folders(gender_path):\n                    speaker = MailabsReader.load_speaker(corpus, speaker_path)\n                    utt_ids = MailabsReader.load_books_of_speaker(corpus,\n                                                                  speaker_path,\n                                                                  speaker)\n                    tag_utt_ids.extend(utt_ids)\n        filter = subset.MatchingUtteranceIdxFilter(\n            utterance_idxs=set(tag_utt_ids)\n        )\n        subview = subset.Subview(corpus, filter_criteria=[filter])\n        corpus.import_subview(tag_idx, subview)",
    "docstring": "Iterate over all speakers on load them.\n        Collect all utterance-idx and create a subset of them."
  },
  {
    "code": "def validatePage(self):\r\n        widgets = self.propertyWidgetMap()\r\n        failed = ''\r\n        for prop, widget in widgets.items():\r\n            val, success = projexui.widgetValue(widget)\r\n            if success:\r\n                if not val and not (prop.type == 'bool' and val is False):\r\n                    if prop.default:\r\n                        val = prop.default\r\n                    elif prop.required:\r\n                        msg = '{0} is a required value'.format(prop.label)\r\n                        failed = msg\r\n                        break\r\n                elif prop.regex and not re.match(prop.regex, nativestring(val)):\r\n                    msg = '{0} needs to be in the format {1}'.format(prop.label,\r\n                                                                 prop.regex)\r\n                    failed = msg\r\n                    break\r\n                prop.value = val\r\n            else:\r\n                msg = 'Failed to get a proper value for {0}'.format(prop.label)\r\n                failed = msg\r\n                break\r\n        if failed:\r\n            QtGui.QMessageBox.warning(None, 'Properties Failed', failed)\r\n            return False\r\n        return True",
    "docstring": "Validates the page against the scaffold information, setting the\r\n        values along the way."
  },
  {
    "code": "def check_instance_folder(self, create=False):\n        path = Path(self.instance_path)\n        err = None\n        eno = 0\n        if not path.exists():\n            if create:\n                logger.info(\"Create instance folder: %s\", path)\n                path.mkdir(0o775, parents=True)\n            else:\n                err = \"Instance folder does not exists\"\n                eno = errno.ENOENT\n        elif not path.is_dir():\n            err = \"Instance folder is not a directory\"\n            eno = errno.ENOTDIR\n        elif not os.access(str(path), os.R_OK | os.W_OK | os.X_OK):\n            err = 'Require \"rwx\" access rights, please verify permissions'\n            eno = errno.EPERM\n        if err:\n            raise OSError(eno, err, str(path))",
    "docstring": "Verify instance folder exists, is a directory, and has necessary\n        permissions.\n\n        :param:create: if `True`, creates directory hierarchy\n\n        :raises: OSError with relevant errno if something is wrong."
  },
  {
    "code": "def _get_active_contract_at_offset(self, root_symbol, dt, offset):\n        oc = self.asset_finder.get_ordered_contracts(root_symbol)\n        session = self.trading_calendar.minute_to_session_label(dt)\n        front = oc.contract_before_auto_close(session.value)\n        back = oc.contract_at_offset(front, 1, dt.value)\n        if back is None:\n            return front\n        primary = self._active_contract(oc, front, back, session)\n        return oc.contract_at_offset(primary, offset, session.value)",
    "docstring": "For the given root symbol, find the contract that is considered active\n        on a specific date at a specific offset."
  },
  {
    "code": "def version_to_evr(verstring):\n    if verstring in [None, '']:\n        return '0', '', ''\n    idx_e = verstring.find(':')\n    if idx_e != -1:\n        try:\n            epoch = six.text_type(int(verstring[:idx_e]))\n        except ValueError:\n            epoch = '0'\n    else:\n        epoch = '0'\n    idx_r = verstring.find('-')\n    if idx_r != -1:\n        version = verstring[idx_e + 1:idx_r]\n        release = verstring[idx_r + 1:]\n    else:\n        version = verstring[idx_e + 1:]\n        release = ''\n    return epoch, version, release",
    "docstring": "Split the package version string into epoch, version and release.\n    Return this as tuple.\n\n    The epoch is always not empty. The version and the release can be an empty\n    string if such a component could not be found in the version string.\n\n    \"2:1.0-1.2\" => ('2', '1.0', '1.2)\n    \"1.0\" => ('0', '1.0', '')\n    \"\" => ('0', '', '')"
  },
  {
    "code": "def run(self, stash='active', n=None, until=None, **kwargs):\n        for _ in (itertools.count() if n is None else range(0, n)):\n            if not self.complete() and self._stashes[stash]:\n                self.step(stash=stash, **kwargs)\n                if not (until and until(self)):\n                    continue\n            break\n        return self",
    "docstring": "Run until the SimulationManager has reached a completed state, according to\n        the current exploration techniques. If no exploration techniques that define a completion\n        state are being used, run until there is nothing left to run.\n\n        :param stash:       Operate on this stash\n        :param n:           Step at most this many times\n        :param until:       If provided, should be a function that takes a SimulationManager and\n                            returns True or False. Stepping will terminate when it is True.\n\n        :return:            The simulation manager, for chaining.\n        :rtype:             SimulationManager"
  },
  {
    "code": "def bs_progress_bar(*args, **kwargs):\n    bars = []\n    contexts = kwargs.get(\n        'contexts',\n        ['', 'success', 'info', 'warning', 'danger']\n    )\n    for ndx, arg in enumerate(args):\n        bars.append(\n            dict(percent=arg,\n                 context=kwargs.get('context', contexts[ndx % len(contexts)]))\n        )\n    return {\n        'bars': bars,\n        'text': kwargs.pop('text', False),\n        'striped': kwargs.pop('striped', False),\n        'animated': kwargs.pop('animated', False),\n        'min_val': kwargs.pop('min_val', 0),\n        'max_val': kwargs.pop('max_val', 100),\n    }",
    "docstring": "A Standard Bootstrap Progress Bar.\n\n    http://getbootstrap.com/components/#progress\n\n    param args (Array of Numbers: 0-100): Percent of Progress Bars\n    param context (String): Adds 'progress-bar-{context} to the class attribute\n    param contexts (Array of Strings): Cycles through contexts for stacked bars\n    param text (String): True: shows value within the bar, False: uses sr span\n    param striped (Boolean): Adds 'progress-bar-striped' to the class attribute\n    param animated (Boolean): Adds 'active' to the class attribute if striped\n    param min_val (0): Used for the aria-min value\n    param max_val (0): Used for the aria-max value"
  },
  {
    "code": "def _get_tunnel_context_mask(address_translations=False,\n                             internal_subnets=False,\n                             remote_subnets=False,\n                             static_subnets=False,\n                             service_subnets=False):\n    entries = ['id',\n               'accountId',\n               'advancedConfigurationFlag',\n               'createDate',\n               'customerPeerIpAddress',\n               'modifyDate',\n               'name',\n               'friendlyName',\n               'internalPeerIpAddress',\n               'phaseOneAuthentication',\n               'phaseOneDiffieHellmanGroup',\n               'phaseOneEncryption',\n               'phaseOneKeylife',\n               'phaseTwoAuthentication',\n               'phaseTwoDiffieHellmanGroup',\n               'phaseTwoEncryption',\n               'phaseTwoKeylife',\n               'phaseTwoPerfectForwardSecrecy',\n               'presharedKey']\n    if address_translations:\n        entries.append('addressTranslations[internalIpAddressRecord[ipAddress],'\n                       'customerIpAddressRecord[ipAddress]]')\n    if internal_subnets:\n        entries.append('internalSubnets')\n    if remote_subnets:\n        entries.append('customerSubnets')\n    if static_subnets:\n        entries.append('staticRouteSubnets')\n    if service_subnets:\n        entries.append('serviceSubnets')\n    return '[mask[{}]]'.format(','.join(entries))",
    "docstring": "Yields a mask object for a tunnel context.\n\n    All exposed properties on the tunnel context service are included in\n    the constructed mask. Additional joins may be requested.\n\n    :param bool address_translations: Whether to join the context's address\n           translation entries.\n    :param bool internal_subnets: Whether to join the context's internal\n           subnet associations.\n    :param bool remote_subnets: Whether to join the context's remote subnet\n           associations.\n    :param bool static_subnets: Whether to join the context's statically\n           routed subnet associations.\n    :param bool service_subnets: Whether to join the SoftLayer service\n           network subnets.\n    :return string: Encoding for the requested mask object."
  },
  {
    "code": "def start(controller_class):\n    args = parser.parse()\n    obj = controller_class(args, platform.operating_system())\n    if args.foreground:\n        try:\n            obj.start()\n        except KeyboardInterrupt:\n            obj.stop()\n    else:\n        try:\n            with platform.Daemon(obj) as daemon:\n                daemon.start()\n        except (OSError, ValueError) as error:\n            sys.stderr.write('\\nError starting %s: %s\\n\\n' %\n                             (sys.argv[0], error))\n            sys.exit(1)",
    "docstring": "Start the Helper controller either in the foreground or as a daemon\n    process.\n\n    :param controller_class: The controller class handle to create and run\n    :type controller_class: callable"
  },
  {
    "code": "def database(connection_string, db_class=SimplDB):\n    if not hasattr(database, \"singletons\"):\n        database.singletons = {}\n    if connection_string not in database.singletons:\n        instance = db_class(connection_string)\n        database.singletons[connection_string] = instance\n    return database.singletons[connection_string]",
    "docstring": "Return database singleton instance.\n\n    This function will always return the same database instance for the same\n    connection_string. It stores instances in a dict saved as an attribute of\n    this function."
  },
  {
    "code": "def read_batch_from_datastore(self, class_batch_id):\n    client = self._datastore_client\n    key = client.key(KIND_CLASSIFICATION_BATCH, class_batch_id)\n    result = client.get(key)\n    if result is not None:\n      return dict(result)\n    else:\n      raise KeyError(\n          'Key {0} not found in the datastore'.format(key.flat_path))",
    "docstring": "Reads and returns single batch from the datastore."
  },
  {
    "code": "def run(self):\n        while True:\n            self.open_lock.acquire()\n            if self.stopped():\n                return\n            self.__open()\n            self.open_lock.release()",
    "docstring": "This override threading.Thread to open socket and wait for messages."
  },
  {
    "code": "def from_uncharted_json_file(cls, file):\n        with open(file, \"r\") as f:\n            _dict = json.load(f)\n        return cls.from_uncharted_json_serialized_dict(_dict)",
    "docstring": "Construct an AnalysisGraph object from a file containing INDRA\n        statements serialized exported by Uncharted's CauseMos webapp."
  },
  {
    "code": "def prepare_authorization_request(self, authorization_url, state=None,\n                                      redirect_url=None, scope=None, **kwargs):\n        if not is_secure_transport(authorization_url):\n            raise InsecureTransportError()\n        self.state = state or self.state_generator()\n        self.redirect_url = redirect_url or self.redirect_url\n        self.scope = scope or self.scope\n        auth_url = self.prepare_request_uri(\n            authorization_url, redirect_uri=self.redirect_url,\n            scope=self.scope, state=self.state, **kwargs)\n        return auth_url, FORM_ENC_HEADERS, ''",
    "docstring": "Prepare the authorization request.\n\n        This is the first step in many OAuth flows in which the user is\n        redirected to a certain authorization URL. This method adds\n        required parameters to the authorization URL.\n\n        :param authorization_url: Provider authorization endpoint URL.\n\n        :param state: CSRF protection string. Will be automatically created if\n        not provided. The generated state is available via the ``state``\n        attribute. Clients should verify that the state is unchanged and\n        present in the authorization response. This verification is done\n        automatically if using the ``authorization_response`` parameter\n        with ``prepare_token_request``.\n\n        :param redirect_url: Redirect URL to which the user will be returned\n        after authorization. Must be provided unless previously setup with\n        the provider. If provided then it must also be provided in the\n        token request.\n\n        :param scope:\n\n        :param kwargs: Additional parameters to included in the request.\n\n        :returns: The prepared request tuple with (url, headers, body)."
  },
  {
    "code": "def meantsubpool(d, data_read):\n    logger.info('Subtracting mean visibility in time...')\n    data_read = numpyview(data_read_mem, 'complex64', datashape(d))\n    tsubpart = partial(rtlib.meantsub, data_read)\n    blranges = [(d['nbl'] * t/d['nthread'], d['nbl']*(t+1)/d['nthread']) for t in range(d['nthread'])]\n    with closing(mp.Pool(1, initializer=initreadonly, initargs=(data_read_mem,))) as tsubpool:\n        tsubpool.map(tsubpart, blr)",
    "docstring": "Wrapper for mean visibility subtraction in time.\n    Doesn't work when called from pipeline using multiprocessing pool."
  },
  {
    "code": "def _build_index(maf_strm, ref_spec):\n  idx_strm = StringIO.StringIO()\n  bound_iter = functools.partial(genome_alignment_iterator,\n                                 reference_species=ref_spec)\n  hash_func = JustInTimeGenomeAlignmentBlock.build_hash\n  idx = IndexedFile(maf_strm, bound_iter, hash_func)\n  idx.write_index(idx_strm)\n  idx_strm.seek(0)\n  return idx_strm",
    "docstring": "Build an index for a MAF genome alig file and return StringIO of it."
  },
  {
    "code": "def _outer_error_is_decreasing(self):\n        is_decreasing, self._last_outer_error = self._error_is_decreasing(self._last_outer_error)\n        return is_decreasing",
    "docstring": "True if outer iteration error is decreasing."
  },
  {
    "code": "def _make_wildcard_attr_map():\n    _xmap = {}\n    for wc in OpenflowWildcard:\n        if not wc.name.endswith('All') and \\\n            not wc.name.endswith('Mask'):\n            translated = ''\n            for ch in wc.name:\n                if ch.isupper():\n                    translated += '_' \n                    translated += ch.lower()\n                else:\n                    translated += ch\n            _xmap[translated] = wc\n    return _xmap",
    "docstring": "Create a dictionary that maps an attribute name\n    in OpenflowMatch with a non-prefix-related wildcard\n    bit from the above OpenflowWildcard enumeration."
  },
  {
    "code": "def do_exit(self, arg_list: List[str]) -> bool:\n        if arg_list:\n            try:\n                self.exit_code = int(arg_list[0])\n            except ValueError:\n                self.perror(\"{} isn't a valid integer exit code\".format(arg_list[0]))\n                self.exit_code = -1\n        self._should_quit = True\n        return self._STOP_AND_EXIT",
    "docstring": "Exit the application with an optional exit code.\n\nUsage:  exit [exit_code]\n    Where:\n        * exit_code - integer exit code to return to the shell"
  },
  {
    "code": "def create_schema_from_xsd_directory(directory, version):\n    schema = Schema(version)\n    for f in _get_xsd_from_directory(directory):\n        logger.info(\"Loading schema %s\" % f)\n        fill_schema_from_xsd_file(f, schema)\n    return schema",
    "docstring": "Create and fill the schema from a directory which contains xsd\n    files. It calls fill_schema_from_xsd_file for each xsd file\n    found."
  },
  {
    "code": "def read(address, length):\n        arr = create_string_buffer(length)\n        return i2c_msg(\n            addr=address, flags=I2C_M_RD, len=length,\n            buf=arr)",
    "docstring": "Prepares an i2c read transaction.\n\n        :param address: Slave address.\n        :type: address: int\n        :param length: Number of bytes to read.\n        :type: length: int\n        :return: New :py:class:`i2c_msg` instance for read operation.\n        :rtype: :py:class:`i2c_msg`"
  },
  {
    "code": "def on_log(request, page_name):\n    page = Page.query.filter_by(name=page_name).first()\n    if page is None:\n        return page_missing(request, page_name, False)\n    return Response(generate_template(\"action_log.html\", page=page))",
    "docstring": "Show the list of recent changes."
  },
  {
    "code": "def thresholdcoloring(coloring, names):\n    for key in coloring.keys():\n        if len([k for k in coloring[key] if k in names]) == 0:\n            coloring.pop(key)\n        else:\n            coloring[key] = utils.uniqify([k for k in coloring[key] if k in \n                                           names])\n    return coloring",
    "docstring": "Threshold a coloring dictionary for a given list of column names.\n\n    Threshold `coloring` based on `names`, a list of strings in::\n\n        coloring.values()\n\n    **Parameters**\n\n        **coloring** :  dictionary\n\n            Hierarchical structure on the columns given in the header of the \n            file; an attribute of tabarrays.\n\n            See :func:`tabular.tab.tabarray.__new__` for more information about \n            coloring.\n\n        **names** :  list of strings\n\n            List of strings giving column names.\n\n    **Returns**\n\n        **newcoloring** :  dictionary\n\n            The thresholded coloring dictionary."
  },
  {
    "code": "def index_exists(index, hosts=None, profile=None):\n    es = _get_instance(hosts, profile)\n    try:\n        return es.indices.exists(index=index)\n    except elasticsearch.exceptions.NotFoundError:\n        return False\n    except elasticsearch.TransportError as e:\n        raise CommandExecutionError(\"Cannot retrieve index {0}, server returned code {1} with message {2}\".format(index, e.status_code, e.error))",
    "docstring": "Return a boolean indicating whether given index exists\n\n    index\n        Index name\n\n    CLI example::\n\n        salt myminion elasticsearch.index_exists testindex"
  },
  {
    "code": "def update_warning(self):\r\n        widget = self._button_warning\r\n        if not self.is_valid():\r\n            tip = _('Array dimensions not valid')\r\n            widget.setIcon(ima.icon('MessageBoxWarning'))\r\n            widget.setToolTip(tip)\r\n            QToolTip.showText(self._widget.mapToGlobal(QPoint(0, 5)), tip)\r\n        else:\r\n            self._button_warning.setToolTip('')",
    "docstring": "Updates the icon and tip based on the validity of the array content."
  },
  {
    "code": "def init_atom_feed(self, feed):\n        atom_feed = FeedGenerator()\n        atom_feed.id(id=self.request.route_url(self.get_atom_feed_url, id=feed.id))\n        atom_feed.link(href=self.request.route_url(self.get_atom_feed_url, id=feed.id), rel='self')\n        atom_feed.language('nl-BE')\n        self.link_to_sibling(feed, 'previous', atom_feed)\n        self.link_to_sibling(feed, 'next', atom_feed)\n        return atom_feed",
    "docstring": "Initializing an atom feed `feedgen.feed.FeedGenerator` given a feed object\n\n        :param feed: a feed object\n        :return: an atom feed `feedgen.feed.FeedGenerator`"
  },
  {
    "code": "def add(self, properties):\n        new_hba = super(FakedHbaManager, self).add(properties)\n        partition = self.parent\n        assert 'hba-uris' in partition.properties\n        partition.properties['hba-uris'].append(new_hba.uri)\n        if 'device-number' not in new_hba.properties:\n            devno = partition.devno_alloc()\n            new_hba.properties['device-number'] = devno\n        if 'wwpn' not in new_hba.properties:\n            wwpn = partition.wwpn_alloc()\n            new_hba.properties['wwpn'] = wwpn\n        return new_hba",
    "docstring": "Add a faked HBA resource.\n\n        Parameters:\n\n          properties (dict):\n            Resource properties.\n\n            Special handling and requirements for certain properties:\n\n            * 'element-id' will be auto-generated with a unique value across\n              all instances of this resource type, if not specified.\n            * 'element-uri' will be auto-generated based upon the element ID,\n              if not specified.\n            * 'class' will be auto-generated to 'hba',\n              if not specified.\n            * 'adapter-port-uri' identifies the backing FCP port for this HBA\n              and is required to be specified.\n            * 'device-number' will be auto-generated with a unique value\n              within the partition in the range 0x8000 to 0xFFFF, if not\n              specified.\n\n            This method also updates the 'hba-uris' property in the parent\n            faked Partition resource, by adding the URI for the faked HBA\n            resource.\n\n        Returns:\n          :class:`~zhmcclient_mock.FakedHba`: The faked HBA resource.\n\n        Raises:\n          :exc:`zhmcclient_mock.InputError`: Some issue with the input\n            properties."
  },
  {
    "code": "def get_mr_filters(data_shape, opt='', coarse=False):\n    data_shape = np.array(data_shape)\n    data_shape += data_shape % 2 - 1\n    fake_data = np.zeros(data_shape)\n    fake_data[tuple(zip(data_shape // 2))] = 1\n    mr_filters = call_mr_transform(fake_data, opt=opt)\n    if coarse:\n        return mr_filters\n    else:\n        return mr_filters[:-1]",
    "docstring": "Get mr_transform filters\n\n    This method obtains wavelet filters by calling mr_transform\n\n    Parameters\n    ----------\n    data_shape : tuple\n        2D data shape\n    opt : list, optional\n        List of additonal mr_transform options\n    coarse : bool, optional\n        Option to keep coarse scale (default is 'False')\n\n    Returns\n    -------\n    np.ndarray 3D array of wavelet filters"
  },
  {
    "code": "def _get_magnitude_scaling_term(self, C, mag):\n        if mag < 6.75:\n            return C[\"a1_lo\"] + C[\"a2_lo\"] * mag + C[\"a3\"] *\\\n                ((8.5 - mag) ** 2.0)\n        else:\n            return C[\"a1_hi\"] + C[\"a2_hi\"] * mag + C[\"a3\"] *\\\n                ((8.5 - mag) ** 2.0)",
    "docstring": "Returns the magnitude scaling term defined in equation 3"
  },
  {
    "code": "def quantize(image, nlevels):\n    tmp = np.array(image // (1.0 / nlevels), dtype='i1')\n    return tmp.clip(0, nlevels - 1)",
    "docstring": "Quantize an image into integers 0, 1, ..., nlevels - 1.\n\n    image   -- a numpy array of type float, range [0, 1]\n    nlevels -- an integer"
  },
  {
    "code": "def apply_upstring(upstring, component_list):\n    assert len(upstring) == len(component_list)\n    def add_up_key(comp_dict, up_indicator):\n        assert up_indicator == 'U' or up_indicator == \"_\"\n        comp_dict['up'] = up_indicator == 'U'\n    for comp_dict, up_indicator in zip(component_list, upstring):\n        add_up_key(comp_dict, up_indicator)",
    "docstring": "Update the dictionaries resulting from ``parse_array_start`` with\n    the \"up\" key based on the upstring returned from ``parse_upstring``.\n\n    The function assumes that the upstring and component_list parameters\n    passed in are from the same device array stanza of a\n    ``/proc/mdstat`` file.\n\n    The function modifies component_list in place, adding or updating\n    the value of the \"up\" key to True if there is a corresponding ``U``\n    in the upstring string, or to False if there is a corresponding\n    ``_``.\n\n    If there the number of rows in component_list does not match the\n    number of characters in upstring, an ``AssertionError`` is raised.\n\n    Parameters\n    ----------\n\n    upstring : str\n        String sequence of ``U``s and ``_``s as determined by the\n        ``parse_upstring`` method\n\n    component_list : list\n        List of dictionaries output from the ``parse_array_start`` method."
  },
  {
    "code": "def table_schema(self):\n        if self.__dict__.get('_table_schema') is None:\n            self._table_schema = None\n            table_schema = {}\n            for row in self.query_schema():\n                name, default, dtype = self.db().lexicon.column_info(row)\n                if isinstance(default, str):\n                    json_matches = re.findall(r\"^\\'(.*)\\'::jsonb$\", default)\n                    if len(json_matches) > 0:\n                        default = json.loads(json_matches[0])\n                if name == self.primary_key:\n                    default = None\n                table_schema[name] = {'default': default, 'type': dtype}\n            if len(table_schema):\n                self._table_schema = table_schema\n        return self._table_schema",
    "docstring": "Returns the table schema.\n\n        :returns: dict"
  },
  {
    "code": "def _write_config(self, cfg, slot):\n        old_pgm_seq = self._status.pgm_seq\n        frame = cfg.to_frame(slot=slot)\n        self._debug(\"Writing %s frame :\\n%s\\n\" % \\\n                        (yubikey_config.command2str(frame.command), cfg))\n        self._write(frame)\n        self._waitfor_clear(yubikey_defs.SLOT_WRITE_FLAG)\n        self.status()\n        self._debug(\"Programmed slot %i, sequence %i -> %i\\n\" % (slot, old_pgm_seq, self._status.pgm_seq))\n        cfgs = self._status.valid_configs()\n        if not cfgs and self._status.pgm_seq == 0:\n            return\n        if self._status.pgm_seq == old_pgm_seq + 1:\n            return\n        raise YubiKeyUSBHIDError('YubiKey programming failed (seq %i not increased (%i))' % \\\n                                    (old_pgm_seq, self._status.pgm_seq))",
    "docstring": "Write configuration to YubiKey."
  },
  {
    "code": "def show_yticklabels_for_all(self, row_column_list=None):\n        if row_column_list is None:\n            for subplot in self.subplots:\n                subplot.show_yticklabels()\n        else:\n            for row, column in row_column_list:\n                self.show_yticklabels(row, column)",
    "docstring": "Show the y-axis tick labels for all specified subplots.\n\n        :param row_column_list: a list containing (row, column) tuples to\n            specify the subplots, or None to indicate *all* subplots.\n        :type row_column_list: list or None"
  },
  {
    "code": "def delete_directories(paths):\n    for path in paths:\n        if os.path.exists(path):\n            shutil.rmtree(path)",
    "docstring": "Delete directories.\n\n        If the directory is exist, It will delete it including files.\n\n        :type paths: Array of string or string\n        :param paths: the location of directory"
  },
  {
    "code": "def get(self, key):\n        keystr = str(key)\n        res = None\n        try:\n            res = self.ctx[keystr]\n        except KeyError:\n            for k, v in self.ctx.items():\n                if \"name\" in v and v[\"name\"].lower() == keystr.lower():\n                    res = v\n                    break\n        return res",
    "docstring": "Returns context data for a given app, can be an ID or a case insensitive name"
  },
  {
    "code": "def sendhello(self):\r\n        try:\r\n            cli_hello_msg = \"<hello>\\n\" +\\\r\n                            \"  <capabilities>\\n\" +\\\r\n                            \"    <capability>urn:ietf:params:netconf:base:1.0</capability>\\n\" +\\\r\n                            \"  </capabilities>\\n\" +\\\r\n                            \"</hello>\\n\"\r\n            self._cParams.set('cli_hello', cli_hello_msg)\r\n            self._hConn.sendmsg(cli_hello_msg)\r\n            ser_hello_msg = self._hConn.recvmsg()\r\n            self._cParams.set('ser_hello', ser_hello_msg)\r\n        except:\r\n            print 'BNClient: Call sendhello fail'\r\n            sys.exit()\r",
    "docstring": "end of function exchgcaps"
  },
  {
    "code": "def get_user(self, user_id, expand=False):\n        url = urljoin(self.user_url, F\"{user_id}.json\")\n        response = self._get_sync(url)\n        if not response:\n            raise InvalidUserID\n        user = User(response)\n        if expand and user.submitted:\n            items = self.get_items_by_ids(user.submitted)\n            user_opt = {\n                'stories': 'story',\n                'comments': 'comment',\n                'jobs': 'job',\n                'polls': 'poll',\n                'pollopts': 'pollopt'\n            }\n            for key, value in user_opt.items():\n                setattr(\n                    user,\n                    key,\n                    [i for i in items if i.item_type == value]\n                )\n        return user",
    "docstring": "Returns Hacker News `User` object.\n\n        Fetches data from the url:\n            https://hacker-news.firebaseio.com/v0/user/<user_id>.json\n\n        e.g. https://hacker-news.firebaseio.com/v0/user/pg.json\n\n        Args:\n            user_id (string): unique user id of a Hacker News user.\n            expand (bool): Flag to indicate whether to\n                transform all IDs into objects.\n\n        Returns:\n            `User` object representing a user on Hacker News.\n\n        Raises:\n          InvalidUserID: If no such user exists on Hacker News."
  },
  {
    "code": "def get_compression_type(self, file_name):\n        ext = os.path.splitext(file_name)[1]\n        if ext == '.gz':\n            self.ctype = 'gzip'\n        elif ext == '.bz2':\n            self.ctype = 'bzip2'\n        elif ext in ('.xz', '.lzma'):\n            self.ctype = 'lzma'\n        else:\n            self.ctype = None",
    "docstring": "Determine compression type for a given file using its extension.\n\n            :param file_name: a given file name\n            :type file_name: str"
  },
  {
    "code": "def get_all_spot_instance_requests(self, request_ids=None,\n                                       filters=None):\n        params = {}\n        if request_ids:\n            self.build_list_params(params, request_ids, 'SpotInstanceRequestId')\n        if filters:\n            if 'launch.group-id' in filters:\n                lgid = filters.get('launch.group-id')\n                if not lgid.startswith('sg-') or len(lgid) != 11:\n                    warnings.warn(\n                        \"The 'launch.group-id' filter now requires a security \"\n                        \"group id (sg-*) and no longer supports filtering by \"\n                        \"group name. Please update your filters accordingly.\",\n                        UserWarning)\n            self.build_filter_params(params, filters)\n        return self.get_list('DescribeSpotInstanceRequests', params,\n                             [('item', SpotInstanceRequest)], verb='POST')",
    "docstring": "Retrieve all the spot instances requests associated with your account.\n\n        :type request_ids: list\n        :param request_ids: A list of strings of spot instance request IDs\n\n        :type filters: dict\n        :param filters: Optional filters that can be used to limit\n                        the results returned.  Filters are provided\n                        in the form of a dictionary consisting of\n                        filter names as the key and filter values\n                        as the value.  The set of allowable filter\n                        names/values is dependent on the request\n                        being performed.  Check the EC2 API guide\n                        for details.\n\n        :rtype: list\n        :return: A list of\n                 :class:`boto.ec2.spotinstancerequest.SpotInstanceRequest`"
  },
  {
    "code": "def execute(self, input_data):\n        raw_bytes = input_data['sample']['raw_bytes']\n        zipfile_output = zipfile.ZipFile(StringIO(raw_bytes))\n        payload_md5s = []\n        for name in zipfile_output.namelist():\n            filename = os.path.basename(name)\n            payload_md5s.append(self.workbench.store_sample(zipfile_output.read(name), name, 'unknown'))\n        return {'payload_md5s': payload_md5s}",
    "docstring": "Execute the Unzip worker"
  },
  {
    "code": "def get(cont=None, path=None, local_file=None, return_bin=False, profile=None):\n    swift_conn = _auth(profile)\n    if cont is None:\n        return swift_conn.get_account()\n    if path is None:\n        return swift_conn.get_container(cont)\n    if return_bin is True:\n        return swift_conn.get_object(cont, path, return_bin)\n    if local_file is not None:\n        return swift_conn.get_object(cont, path, local_file)\n    return False",
    "docstring": "List the contents of a container, or return an object from a container. Set\n    return_bin to True in order to retrieve an object wholesale. Otherwise,\n    Salt will attempt to parse an XML response.\n\n    CLI Example to list containers:\n\n    .. code-block:: bash\n\n        salt myminion swift.get\n\n    CLI Example to list the contents of a container:\n\n    .. code-block:: bash\n\n        salt myminion swift.get mycontainer\n\n    CLI Example to return the binary contents of an object:\n\n    .. code-block:: bash\n\n        salt myminion swift.get mycontainer myfile.png return_bin=True\n\n    CLI Example to save the binary contents of an object to a local file:\n\n    .. code-block:: bash\n\n        salt myminion swift.get mycontainer myfile.png local_file=/tmp/myfile.png"
  },
  {
    "code": "def sample(self, wavelength):\n        wave = self.waveunits.Convert(wavelength, 'angstrom')\n        return self(wave)",
    "docstring": "Input wavelengths assumed to be in user unit."
  },
  {
    "code": "def add_sip_to_fc(fc, tfidf, limit=40):\n    if 'bowNP' not in fc:\n        return\n    if tfidf is None:\n        return\n    sips = features.sip_noun_phrases(tfidf, fc['bowNP'].keys(), limit=limit)\n    fc[u'bowNP_sip'] = StringCounter(sips)",
    "docstring": "add \"bowNP_sip\" to `fc` using `tfidf` data"
  },
  {
    "code": "def register(self, peer):\n        assert isinstance(peer, beans.Peer)\n        with self.__lock:\n            peer_id = peer.peer_id\n            if peer_id in self.peers:\n                raise KeyError(\"Already known peer: {0}\".format(peer))\n            self.peers[peer_id] = peer\n            for name in peer.groups:\n                self.groups.setdefault(name, set()).add(peer_id)",
    "docstring": "Registers a peer according to its description\n\n        :param peer: A Peer description bean\n        :raise KeyError:"
  },
  {
    "code": "def CreateFlowArgs(self, flow_name=None):\n    if not self._flow_descriptors:\n      self._flow_descriptors = {}\n      result = self._context.SendRequest(\"ListFlowDescriptors\", None)\n      for item in result.items:\n        self._flow_descriptors[item.name] = item\n    try:\n      flow_descriptor = self._flow_descriptors[flow_name]\n    except KeyError:\n      raise UnknownFlowName(flow_name)\n    return utils.CopyProto(utils.UnpackAny(flow_descriptor.default_args))",
    "docstring": "Creates flow arguments object for a flow with a given name."
  },
  {
    "code": "def get_events(maximum=10):\n    events = []\n    for ev in range(0, maximum):\n        try:\n            if CONTROLLER.queue.empty():\n                break\n            else:\n                events.append(CONTROLLER.queue.get_nowait())\n        except NameError:\n            print('PyMLGame is not initialized correctly. Use pymlgame.init() first.')\n            events = False\n            break\n    return events",
    "docstring": "Get all events since the last time you asked for them. You can define a maximum which is 10 by default.\n\n    :param maximum: Maximum number of events\n    :type maximum: int\n    :return: List of events\n    :rtype: list"
  },
  {
    "code": "def GET_parameteritemvalues(self) -> None:\n        for item in state.parameteritems:\n            self._outputs[item.name] = item.value",
    "docstring": "Get the values of all |ChangeItem| objects handling |Parameter|\n        objects."
  },
  {
    "code": "def _login(self, password):\n        self.smtp = self.connection(self.host, self.port, **self.kwargs)\n        self.smtp.set_debuglevel(self.debuglevel)\n        if self.starttls:\n            self.smtp.ehlo()\n            if self.starttls is True:\n                self.smtp.starttls()\n            else:\n                self.smtp.starttls(**self.starttls)\n            self.smtp.ehlo()\n        self.is_closed = False\n        if not self.smtp_skip_login:\n            password = self.handle_password(self.user, password)\n            self.smtp.login(self.user, password)\n        self.log.info(\"Connected to SMTP @ %s:%s as %s\", self.host, self.port, self.user)",
    "docstring": "Login to the SMTP server using password. `login` only needs to be manually run when the\n        connection to the SMTP server was closed by the user."
  },
  {
    "code": "def add_controller(self, key, controller):\n        assert isinstance(controller, ExtendedController)\n        controller.parent = self\n        self.__child_controllers[key] = controller\n        if self.__shortcut_manager is not None and controller not in self.__action_registered_controllers:\n            controller.register_actions(self.__shortcut_manager)\n            self.__action_registered_controllers.append(controller)",
    "docstring": "Add child controller\n\n        The passed controller is registered as child of self. The register_actions method of the child controller is\n        called, allowing the child controller to register shortcut callbacks.\n\n        :param key: Name of the controller (unique within self), to later access it again\n        :param ExtendedController controller: Controller to be added as child"
  },
  {
    "code": "def get(self, filename):\n        timer = Timer()\n        self.check_prerequisites()\n        with PatchedBotoConfig():\n            raw_key = self.get_cache_key(filename)\n            logger.info(\"Checking if distribution archive is available in S3 bucket: %s\", raw_key)\n            key = self.s3_bucket.get_key(raw_key)\n            if key is None:\n                logger.debug(\"Distribution archive is not available in S3 bucket.\")\n            else:\n                logger.info(\"Downloading distribution archive from S3 bucket ..\")\n                file_in_cache = os.path.join(self.config.binary_cache, filename)\n                makedirs(os.path.dirname(file_in_cache))\n                with AtomicReplace(file_in_cache) as temporary_file:\n                    key.get_contents_to_filename(temporary_file)\n                logger.debug(\"Finished downloading distribution archive from S3 bucket in %s.\", timer)\n                return file_in_cache",
    "docstring": "Download a distribution archive from the configured Amazon S3 bucket.\n\n        :param filename: The filename of the distribution archive (a string).\n        :returns: The pathname of a distribution archive on the local file\n                  system or :data:`None`.\n        :raises: :exc:`.CacheBackendError` when any underlying method fails."
  },
  {
    "code": "def get_config(self, name, default=_MISSING):\n        val = self._config.get(name, default)\n        if val is _MISSING:\n            raise ArgumentError(\"DeviceAdapter config {} did not exist and no default\".format(name))\n        return val",
    "docstring": "Get a configuration setting from this DeviceAdapter.\n\n        See :meth:`AbstractDeviceAdapter.get_config`."
  },
  {
    "code": "def version():\n    def linux_version():\n        try:\n            with salt.utils.files.fopen('/proc/version', 'r') as fp_:\n                return salt.utils.stringutils.to_unicode(fp_.read()).strip()\n        except IOError:\n            return {}\n    def bsd_version():\n        return __salt__['cmd.run']('sysctl -n kern.version')\n    get_version = {\n        'Linux': linux_version,\n        'FreeBSD': bsd_version,\n        'OpenBSD': bsd_version,\n        'AIX': lambda: __salt__['cmd.run']('oslevel -s'),\n    }\n    errmsg = 'This method is unsupported on the current operating system!'\n    return get_version.get(__grains__['kernel'], lambda: errmsg)()",
    "docstring": "Return the system version for this minion\n\n    .. versionchanged:: 2016.11.4\n        Added support for AIX\n\n    .. versionchanged:: 2018.3.0\n        Added support for OpenBSD\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' status.version"
  },
  {
    "code": "def match_subselectors(self, el, selectors):\n        match = True\n        for sel in selectors:\n            if not self.match_selectors(el, sel):\n                match = False\n        return match",
    "docstring": "Match selectors."
  },
  {
    "code": "def connectionLost(self, reason=protocol.connectionDone):\n        self.connected = 0\n        for pending in self._queue.values():\n            pending.errback(reason)\n        self._queue.clear()\n        if self._stopped:\n            result = self if reason.check(error.ConnectionDone) else reason\n            self._stopped.callback(result)\n            self._stopped = None\n        else:\n            reason.raiseException()",
    "docstring": "Check whether termination was intended and invoke the deferred.\n\n        If the connection terminated unexpectedly, reraise the failure.\n\n        @type reason: L{twisted.python.failure.Failure}"
  },
  {
    "code": "def angSepVincenty(ra1, dec1, ra2, dec2):\n    ra1_rad = np.radians(ra1)\n    dec1_rad = np.radians(dec1)\n    ra2_rad = np.radians(ra2)\n    dec2_rad = np.radians(dec2)\n    sin_dec1, cos_dec1 = np.sin(dec1_rad), np.cos(dec1_rad)\n    sin_dec2, cos_dec2 = np.sin(dec2_rad), np.cos(dec2_rad)\n    delta_ra = ra2_rad - ra1_rad\n    cos_delta_ra, sin_delta_ra = np.cos(delta_ra), np.sin(delta_ra)\n    diffpos = np.arctan2(np.sqrt((cos_dec2 * sin_delta_ra) ** 2 +\n                         (cos_dec1 * sin_dec2 -\n                          sin_dec1 * cos_dec2 * cos_delta_ra) ** 2),\n                          sin_dec1 * sin_dec2 + cos_dec1 * cos_dec2 * cos_delta_ra)\n    return np.degrees(diffpos)",
    "docstring": "Vincenty formula for distances on a sphere"
  },
  {
    "code": "def rosen_nesterov(self, x, rho=100):\n        f = 0.25 * (x[0] - 1)**2\n        f += rho * sum((x[1:] - 2 * x[:-1]**2 + 1)**2)\n        return f",
    "docstring": "needs exponential number of steps in a non-increasing f-sequence.\n\n        x_0 = (-1,1,...,1)\n        See Jarre (2011) \"On Nesterov's Smooth Chebyshev-Rosenbrock Function\""
  },
  {
    "code": "def set_input(self, p_name, value):\n        name = self.python_names.get(p_name)\n        if p_name is None or name not in self.get_input_names():\n            raise ValueError('Invalid input \"{}\"'.format(p_name))\n        self.step_inputs[name] = value",
    "docstring": "Set a Step's input variable to a certain value.\n\n        The value comes either from a workflow input or output of a previous\n            step.\n\n        Args:\n            name (str): the name of the Step input\n            value (str): the name of the output variable that provides the\n                value for this input.\n\n        Raises:\n            ValueError: The name provided is not a valid input name for this\n                Step."
  },
  {
    "code": "def do_file_show(client, args):\n    for src_uri in args.uris:\n        client.download_file(src_uri, sys.stdout.buffer)\n    return True",
    "docstring": "Output file contents to stdout"
  },
  {
    "code": "def normalize_time(timestamp):\n    offset = timestamp.utcoffset()\n    if offset is None:\n        return timestamp\n    return timestamp.replace(tzinfo=None) - offset",
    "docstring": "Normalize time in arbitrary timezone to UTC naive object."
  },
  {
    "code": "def find_network_by_label(self, label):\n        networks = self.list()\n        match = [network for network in networks\n                if network.label == label]\n        if not match:\n            raise exc.NetworkNotFound(\"No network with the label '%s' exists\" %\n                    label)\n        elif len(match) > 1:\n            raise exc.NetworkLabelNotUnique(\"There were %s matches for the label \"\n                    \"'%s'.\" % (len(match), label))\n        return match[0]",
    "docstring": "This is inefficient; it gets all the networks and then filters on\n        the client side to find the matching name."
  },
  {
    "code": "def _decode_data(self, data, charset):\n        try:\n            return smart_unicode(data, charset)\n        except UnicodeDecodeError:\n            raise errors.BadRequest('wrong charset')",
    "docstring": "Decode string data.\n\n        :returns: unicode string"
  },
  {
    "code": "def split_denovos(denovo_path, temp_dir):\n    with open(denovo_path, \"r\") as handle:\n        lines = handle.readlines()\n        header = lines.pop(0)\n    basename = os.path.basename(denovo_path)\n    counts = count_missense_per_gene(lines)\n    counts = dict((k, v) for k, v in counts.items() if v > 1 )\n    genes = set([])\n    for line in sorted(lines):\n        gene = line.split(\"\\t\")[0]\n        if gene not in genes and gene in counts:\n            genes.add(gene)\n            path = os.path.join(temp_dir, \"tmp.{}.txt\".format(len(genes)))\n            output = open(path, \"w\")\n            output.write(header)\n        if gene in counts:\n            output.write(line)\n    return len(genes)",
    "docstring": "split de novos from an input file into files, one for each gene"
  },
  {
    "code": "def get_cf_distribution_class():\n    if LooseVersion(troposphere.__version__) == LooseVersion('2.4.0'):\n        cf_dist = cloudfront.Distribution\n        cf_dist.props['DistributionConfig'] = (DistributionConfig, True)\n        return cf_dist\n    return cloudfront.Distribution",
    "docstring": "Return the correct troposphere CF distribution class."
  },
  {
    "code": "def reflection_matrix(point, normal):\n    normal = unit_vector(normal[:3])\n    M = np.identity(4)\n    M[:3, :3] -= 2.0 * np.outer(normal, normal)\n    M[:3, 3] = (2.0 * np.dot(point[:3], normal)) * normal\n    return M",
    "docstring": "Return matrix to mirror at plane defined by point and normal vector.\n\n    >>> v0 = np.random.random(4) - 0.5\n    >>> v0[3] = 1.\n    >>> v1 = np.random.random(3) - 0.5\n    >>> R = reflection_matrix(v0, v1)\n    >>> np.allclose(2, np.trace(R))\n    True\n    >>> np.allclose(v0, np.dot(R, v0))\n    True\n    >>> v2 = v0.copy()\n    >>> v2[:3] += v1\n    >>> v3 = v0.copy()\n    >>> v2[:3] -= v1\n    >>> np.allclose(v2, np.dot(R, v3))\n    True"
  },
  {
    "code": "def _get_grain(name, proxy=None):\n    grains = _retrieve_grains_cache(proxy=proxy)\n    if grains.get('result', False) and grains.get('out', {}):\n        return grains.get('out').get(name)",
    "docstring": "Retrieves the grain value from the cached dictionary."
  },
  {
    "code": "def tokens(self):\n        if self._tokens is None:\n            self._tokens = TokenList(self._version, account_sid=self._solution['sid'], )\n        return self._tokens",
    "docstring": "Access the tokens\n\n        :returns: twilio.rest.api.v2010.account.token.TokenList\n        :rtype: twilio.rest.api.v2010.account.token.TokenList"
  },
  {
    "code": "def autoencoder_residual():\n  hparams = autoencoder_autoregressive()\n  hparams.optimizer = \"Adafactor\"\n  hparams.clip_grad_norm = 1.0\n  hparams.learning_rate_constant = 0.5\n  hparams.learning_rate_warmup_steps = 500\n  hparams.learning_rate_schedule = \"constant * linear_warmup * rsqrt_decay\"\n  hparams.num_hidden_layers = 5\n  hparams.hidden_size = 64\n  hparams.max_hidden_size = 1024\n  hparams.add_hparam(\"num_residual_layers\", 2)\n  hparams.add_hparam(\"residual_kernel_height\", 3)\n  hparams.add_hparam(\"residual_kernel_width\", 3)\n  hparams.add_hparam(\"residual_filter_multiplier\", 2.0)\n  hparams.add_hparam(\"residual_dropout\", 0.2)\n  hparams.add_hparam(\"residual_use_separable_conv\", int(True))\n  hparams.add_hparam(\"kl_beta\", 1.0)\n  return hparams",
    "docstring": "Residual autoencoder model."
  },
  {
    "code": "def remote(ctx):\n    with command():\n        m = RepoManager(ctx.obj['agile'])\n        click.echo(m.github_repo().repo_path)",
    "docstring": "Display repo github path"
  },
  {
    "code": "def create_notification_plan(self, label=None, name=None,\n            critical_state=None, ok_state=None, warning_state=None):\n        return self._notification_plan_manager.create(label=label, name=name,\n                critical_state=critical_state, ok_state=ok_state,\n                warning_state=warning_state)",
    "docstring": "Creates a notification plan to be executed when a monitoring check\n        triggers an alarm."
  },
  {
    "code": "def put(\n        self, item: _T, timeout: Union[float, datetime.timedelta] = None\n    ) -> \"Future[None]\":\n        future = Future()\n        try:\n            self.put_nowait(item)\n        except QueueFull:\n            self._putters.append((item, future))\n            _set_timeout(future, timeout)\n        else:\n            future.set_result(None)\n        return future",
    "docstring": "Put an item into the queue, perhaps waiting until there is room.\n\n        Returns a Future, which raises `tornado.util.TimeoutError` after a\n        timeout.\n\n        ``timeout`` may be a number denoting a time (on the same\n        scale as `tornado.ioloop.IOLoop.time`, normally `time.time`), or a\n        `datetime.timedelta` object for a deadline relative to the\n        current time."
  },
  {
    "code": "def vertex_normals(vertices, faces):\n    def normalize_v3(arr):\n        lens = np.sqrt(arr[:, 0]**2 + arr[:, 1]**2 + arr[:, 2]**2)\n        arr /= lens[:, np.newaxis]\n    tris = vertices[faces]\n    facenorms = np.cross(tris[::, 1] - tris[::, 0], tris[::, 2] - tris[::, 0])\n    normalize_v3(facenorms)\n    norm = np.zeros(vertices.shape, dtype=vertices.dtype)\n    norm[faces[:, 0]] += facenorms\n    norm[faces[:, 1]] += facenorms\n    norm[faces[:, 2]] += facenorms\n    normalize_v3(norm)\n    return norm",
    "docstring": "Calculates the normals of a triangular mesh"
  },
  {
    "code": "def export(self, outFormat=\"shp\", outFolder=None):\n        export_formats = {'shp':\".zip\", 'kml':'.kml', 'geojson':\".geojson\",'csv': '.csv'}\n        url = \"%s/%s%s\" % (self._url, self._itemId, export_formats[outFormat])\n        results =  self._get(url=url,\n                    securityHandler=self._securityHandler,\n                    out_folder=outFolder)\n        if 'status' in results:\n            self.time.sleep(7)\n            results = self.export(outFormat=outFormat, outFolder=outFolder)\n        return results",
    "docstring": "exports a dataset t"
  },
  {
    "code": "def color_prompt(self):\n        prompt = '[' + colorize('psiTurk', 'bold')\n        server_string = ''\n        server_status = self.server.is_server_running()\n        if server_status == 'yes':\n            server_string = colorize('on', 'green')\n        elif server_status == 'no':\n            server_string = colorize('off', 'red')\n        elif server_status == 'maybe':\n            server_string = colorize('unknown', 'yellow')\n        elif server_status == 'blocked':\n            server_string = colorize('blocked', 'red')\n        prompt += ' server:' + server_string\n        prompt += ' mode:' + colorize('cabin', 'bold')\n        prompt += ']$ '\n        self.prompt = prompt",
    "docstring": "Construct psiTurk shell prompt"
  },
  {
    "code": "def include_theme_files(self, fragment):\n        theme = self.get_theme()\n        if not theme or 'package' not in theme:\n            return\n        theme_package, theme_files = theme.get('package', None), theme.get('locations', [])\n        resource_loader = ResourceLoader(theme_package)\n        for theme_file in theme_files:\n            fragment.add_css(resource_loader.load_unicode(theme_file))",
    "docstring": "Gets theme configuration and renders theme css into fragment"
  },
  {
    "code": "def _setup_logging(args):\n    log_conf = getattr(args, 'logging', None)\n    if log_conf:\n        logging.config.fileConfig(log_conf)\n    else:\n        logging.basicConfig()",
    "docstring": "Set up logging for the script, based on the configuration\n    specified by the 'logging' attribute of the command line\n    arguments.\n\n    :param args: A Namespace object containing a 'logging' attribute\n                 specifying the name of a logging configuration file\n                 to use.  If not present or not given, a basic logging\n                 configuration will be set."
  },
  {
    "code": "def add_thesis(\n        self,\n        defense_date=None,\n        degree_type=None,\n        institution=None,\n        date=None\n    ):\n        self.record.setdefault('thesis_info', {})\n        thesis_item = {}\n        for key in ('defense_date', 'date'):\n            if locals()[key] is not None:\n                thesis_item[key] = locals()[key]\n        if degree_type is not None:\n            thesis_item['degree_type'] = degree_type.lower()\n        if institution is not None:\n            thesis_item['institutions'] = [{'name': institution}]\n        self.record['thesis_info'] = thesis_item",
    "docstring": "Add thesis info.\n\n        :param defense_date: defense date for the current thesis\n        :type defense_date: string. A formatted date is required (yyyy-mm-dd)\n\n        :param degree_type: degree type for the current thesis\n        :type degree_type: string\n\n        :param institution: author's affiliation for the current thesis\n        :type institution: string\n\n        :param date: publication date for the current thesis\n        :type date: string. A formatted date is required (yyyy-mm-dd)"
  },
  {
    "code": "def partition(self):\n        if not self.partitions:\n            return None\n        if len(self.partitions) > 1:\n            raise ValueError(\n                \"Can't use this method when there is more than one partition\")\n        return list(self.partitions.values())[0]",
    "docstring": "Convenience function for accessing the first partition in the\n        partitions list, when there is only one."
  },
  {
    "code": "def resolution(self):\n        geo_coords = self.to_geographic()\n        resolution = abs(_initialresolution * math.cos(geo_coords.lat * _pi_180) / (2**self.zoom))\n        return resolution",
    "docstring": "Get the tile resolution at the current position.\n\n        The scale in WG84 depends on\n            * the zoom level (obviously)\n            * the latitude\n            * the tile size\n\n        References:\n            * http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Resolution_and_Scale\n            * http://gis.stackexchange.com/questions/7430/what-ratio-scales-do-google-maps-zoom-levels-correspond-to\n\n        Returns:\n            float: meters per pixel"
  },
  {
    "code": "def remove_too_short(utterances: List[Utterance],\n                     _winlen=25, winstep=10) -> List[Utterance]:\n    def is_too_short(utterance: Utterance) -> bool:\n        charlen = len(utterance.text)\n        if (duration(utterance) / winstep) < charlen:\n            return True\n        else:\n            return False\n    return [utter for utter in utterances if not is_too_short(utter)]",
    "docstring": "Removes utterances that will probably have issues with CTC because of\n    the number of frames being less than the number of tokens in the\n    transcription. Assuming char tokenization to minimize false negatives."
  },
  {
    "code": "def _netstat_route_sunos():\n    ret = []\n    cmd = 'netstat -f inet -rn | tail +5'\n    out = __salt__['cmd.run'](cmd, python_shell=True)\n    for line in out.splitlines():\n        comps = line.split()\n        ret.append({\n            'addr_family': 'inet',\n            'destination': comps[0],\n            'gateway': comps[1],\n            'netmask': '',\n            'flags': comps[2],\n            'interface': comps[5] if len(comps) >= 6 else ''})\n    cmd = 'netstat -f inet6 -rn | tail +5'\n    out = __salt__['cmd.run'](cmd, python_shell=True)\n    for line in out.splitlines():\n        comps = line.split()\n        ret.append({\n            'addr_family': 'inet6',\n            'destination': comps[0],\n            'gateway': comps[1],\n            'netmask': '',\n            'flags': comps[2],\n            'interface': comps[5] if len(comps) >= 6 else ''})\n    return ret",
    "docstring": "Return netstat routing information for SunOS"
  },
  {
    "code": "def _push_render(self):\n        bokeh.io.push_notebook(handle=self.handle)\n        self.last_update = time.time()",
    "docstring": "Render the plot with bokeh.io and push to notebook."
  },
  {
    "code": "def print_raw_data(raw_data, start_index=0, limit=200, flavor='fei4b', index_offset=0, select=None, tdc_trig_dist=False, trigger_data_mode=0):\n    if not select:\n        select = ['DH', 'TW', \"AR\", \"VR\", \"SR\", \"DR\", 'TDC', 'UNKNOWN FE WORD', 'UNKNOWN WORD']\n    total_words = 0\n    for index in range(start_index, raw_data.shape[0]):\n        dw = FEI4Record(raw_data[index], chip_flavor=flavor, tdc_trig_dist=tdc_trig_dist, trigger_data_mode=trigger_data_mode)\n        if dw in select:\n            print index + index_offset, '{0:12d} {1:08b} {2:08b} {3:08b} {4:08b}'.format(raw_data[index], (raw_data[index] & 0xFF000000) >> 24, (raw_data[index] & 0x00FF0000) >> 16, (raw_data[index] & 0x0000FF00) >> 8, (raw_data[index] & 0x000000FF) >> 0), dw\n            total_words += 1\n            if limit and total_words >= limit:\n                break\n    return total_words",
    "docstring": "Printing FEI4 raw data array for debugging."
  },
  {
    "code": "def _calculateGlyph(self, targetGlyphObject, instanceLocationObject, glyphMasters):\n        sources = None\n        items = []\n        for item in glyphMasters:\n            locationObject = item['location']\n            fontObject = item['font']\n            glyphName = item['glyphName']\n            if not glyphName in fontObject:\n                continue\n            glyphObject = MathGlyph(fontObject[glyphName])\n            items.append((locationObject, glyphObject))\n        bias, m = buildMutator(items, axes=self.axes)\n        instanceObject = m.makeInstance(instanceLocationObject)\n        if self.roundGeometry:\n            try:\n                instanceObject = instanceObject.round()\n            except AttributeError:\n                if self.verbose and self.logger:\n                    self.logger.info(\"MathGlyph object missing round() method.\")\n        try:\n            instanceObject.extractGlyph(targetGlyphObject, onlyGeometry=True)\n        except TypeError:\n            pPen = targetGlyphObject.getPointPen()\n            targetGlyphObject.clear()\n            instanceObject.drawPoints(pPen)\n            targetGlyphObject.width = instanceObject.width",
    "docstring": "Build a Mutator object for this glyph.\n\n        *   name:   glyphName\n        *   location:   Location object\n        *   glyphMasters:    dict with font objects."
  },
  {
    "code": "def cos_distance(t1, t2, epsilon=1e-12, name=None):\n  with tf.name_scope(name, 'cos_distance', [t1, t2]) as scope:\n    t1 = tf.convert_to_tensor(t1, name='t1')\n    t2 = tf.convert_to_tensor(t2, name='t2')\n    x_inv_norm = tf.rsqrt(tf.maximum(length_squared(t1) * length_squared(t2),\n                                     epsilon))\n    return tf.subtract(1.0, dot_product(t1, t2) * x_inv_norm, name=scope)",
    "docstring": "Cos distance between t1 and t2 and caps the gradient of the Square Root.\n\n  Args:\n    t1: A tensor\n    t2: A tensor that can be multiplied by t1.\n    epsilon: A lower bound value for the distance. The square root is used as\n      the normalizer.\n    name: Optional name for this op.\n  Returns:\n    The cos distance between t1 and t2."
  },
  {
    "code": "def get_DID_subdomain(did, db_path=None, zonefiles_dir=None, atlasdb_path=None, check_pending=False):\n    opts = get_blockstack_opts()\n    if not is_subdomains_enabled(opts):\n        log.warn(\"Subdomain support is disabled\")\n        return None\n    if db_path is None:\n        db_path = opts['subdomaindb_path']\n    if zonefiles_dir is None:\n        zonefiles_dir = opts['zonefiles']\n    if atlasdb_path is None:\n        atlasdb_path = opts['atlasdb_path']\n    db = SubdomainDB(db_path, zonefiles_dir)\n    try:\n        subrec = db.get_DID_subdomain(did)\n    except Exception as e:\n        if BLOCKSTACK_DEBUG:\n            log.exception(e)\n        log.warn(\"Failed to load subdomain for {}\".format(did))\n        return None\n    if check_pending:\n        subrec.pending = db.subdomain_check_pending(subrec, atlasdb_path)\n    return subrec",
    "docstring": "Static method for resolving a DID to a subdomain\n    Return the subdomain record on success\n    Return None on error"
  },
  {
    "code": "def get_json(session, url, params: dict = None):\n    res = session.get(url, params=params)\n    if res.status_code >= 400:\n        raise parse_error(res)\n    return res.json()",
    "docstring": "Get JSON from a Forest endpoint."
  },
  {
    "code": "def _full_pipeline(self):\n        options = self._pipeline_options()\n        full_pipeline = [{'$changeStream': options}]\n        full_pipeline.extend(self._pipeline)\n        return full_pipeline",
    "docstring": "Return the full aggregation pipeline for this ChangeStream."
  },
  {
    "code": "def is_complete(self):\n        try:\n            [t for t in self.tokens]\n            ret = True\n            logger.debug('CallString [{}] is complete'.format(self.strip()))\n        except tokenize.TokenError:\n            logger.debug('CallString [{}] is NOT complete'.format(self.strip()))\n            ret = False\n        return ret",
    "docstring": "Return True if this call string is complete, meaning it has a function\n        name and balanced parens"
  },
  {
    "code": "def inject_environment_variables(self, d):\n        if not d:\n            return d\n        if isinstance(d, six.string_types):\n            return os.path.expandvars(d)\n        for k, v in d.items():\n            if isinstance(v, six.string_types):\n                d[k] = os.path.expandvars(v)\n            elif isinstance(v, dict):\n                d[k] = self.inject_environment_variables(v)\n            elif isinstance(v, list):\n                d[k] = [self.inject_environment_variables(e) for e in v]\n        return d",
    "docstring": "Recursively injects environment variables into TOML values"
  },
  {
    "code": "def containers(self) -> list:\n        all_containers: List = list()\n        for slot in self:\n            all_containers += slot.get_children_list()\n        for container in all_containers:\n            if getattr(container, 'stackable', False):\n                all_containers += container.get_children_list()\n        return all_containers",
    "docstring": "Returns all containers on a deck as a list"
  },
  {
    "code": "async def delete(self):\n        return await self.bot.delete_message(self.chat.id, self.message_id)",
    "docstring": "Delete this message\n\n        :return: bool"
  },
  {
    "code": "def get_frequencies_with_eigenvectors(self, q):\n        self._set_dynamical_matrix()\n        if self._dynamical_matrix is None:\n            msg = (\"Dynamical matrix has not yet built.\")\n            raise RuntimeError(msg)\n        self._dynamical_matrix.set_dynamical_matrix(q)\n        dm = self._dynamical_matrix.get_dynamical_matrix()\n        frequencies = []\n        eigvals, eigenvectors = np.linalg.eigh(dm)\n        frequencies = []\n        for eig in eigvals:\n            if eig < 0:\n                frequencies.append(-np.sqrt(-eig))\n            else:\n                frequencies.append(np.sqrt(eig))\n        return np.array(frequencies) * self._factor, eigenvectors",
    "docstring": "Calculate phonon frequencies and eigenvectors at a given q-point\n\n        Parameters\n        ----------\n        q: array_like\n            A q-vector.\n            shape=(3,)\n\n        Returns\n        -------\n        (frequencies, eigenvectors)\n\n        frequencies: ndarray\n            Phonon frequencies\n            shape=(bands, ), dtype='double', order='C'\n        eigenvectors: ndarray\n            Phonon eigenvectors\n            shape=(bands, bands), dtype='complex', order='C'"
  },
  {
    "code": "def bulk_upsert(self, docs, namespace, timestamp):\n        for doc in docs:\n            self.upsert(doc, namespace, timestamp)",
    "docstring": "Upsert each document in a set of documents.\n\n        This method may be overridden to upsert many documents at once."
  },
  {
    "code": "def title(self):\n        return (u'[{}] {}>>'.format(\n            os.path.split(os.path.abspath('.'))[-1],\n            u' '.join(self.command))).encode('utf8')",
    "docstring": "Returns the UTF-8 encoded title"
  },
  {
    "code": "def tohexstring(self):\n        val = self.tostring()\n        st = \"{0:0x}\".format(int(val, 2))\n        return st.zfill(len(self.bitmap)*2)",
    "docstring": "Returns a hexadecimal string"
  },
  {
    "code": "def wrap_count(method):\n    number = 0\n    while hasattr(method, '__aspects_orig'):\n        number += 1\n        method = method.__aspects_orig\n    return number",
    "docstring": "Returns number of wraps around given method."
  },
  {
    "code": "def volume_list(self, search_opts=None):\n        if self.volume_conn is None:\n            raise SaltCloudSystemExit('No cinder endpoint available')\n        nt_ks = self.volume_conn\n        volumes = nt_ks.volumes.list(search_opts=search_opts)\n        response = {}\n        for volume in volumes:\n            response[volume.display_name] = {\n                'name': volume.display_name,\n                'size': volume.size,\n                'id': volume.id,\n                'description': volume.display_description,\n                'attachments': volume.attachments,\n                'status': volume.status\n            }\n        return response",
    "docstring": "List all block volumes"
  },
  {
    "code": "def searchsorted(arr, N, x):\n    L = 0\n    R = N-1\n    done = False\n    m = (L+R)//2\n    while not done:\n        if arr[m] < x:\n            L = m + 1\n        elif arr[m] > x:\n            R = m - 1\n        elif arr[m] == x:\n            done = True\n        m = (L+R)//2\n        if L>R:\n            done = True\n    return L",
    "docstring": "N is length of arr"
  },
  {
    "code": "def import_name_or_class(name):\n    \" Import an obect as either a fully qualified, dotted name, \"\n    if isinstance(name, str):\n        module_name, object_name = name.rsplit('.',1)\n        mod = __import__(module_name)\n        components = name.split('.')\n        for comp in components[1:]:\n            mod = getattr(mod, comp)\n        return mod\n    else:\n        return name",
    "docstring": "Import an obect as either a fully qualified, dotted name,"
  },
  {
    "code": "def _lock_fxn(direction, lock_mode, xact):\n  if direction == \"unlock\" or lock_mode == LockMode.wait:\n    try_mode = \"\"\n  else:\n    try_mode = \"_try\"\n  if direction == \"lock\" and xact:\n    xact_mode = \"_xact\"\n  else:\n    xact_mode = \"\"\n  return \"pg{}_advisory{}_{}\".format(try_mode, xact_mode, direction)",
    "docstring": "Builds a pg advisory lock function name based on various options.\n\n  :direction: one of \"lock\" or \"unlock\"\n  :lock_mode: a member of the LockMode enum\n  :xact: a boolean, if True the lock will be automatically released at the end\n         of the transaction and cannot be manually released."
  },
  {
    "code": "def _get_instance_repo(self, namespace):\n        self._validate_namespace(namespace)\n        if namespace not in self.instances:\n            self.instances[namespace] = []\n        return self.instances[namespace]",
    "docstring": "Returns the instance repository for the specified CIM namespace\n        within the mock repository. This is the original instance variable,\n        so any modifications will change the mock repository.\n\n        Validates that the namespace exists in the mock repository.\n\n        If the instance repository does not contain the namespace yet, it is\n        added.\n\n        Parameters:\n\n          namespace(:term:`string`): Namespace name. Must not be `None`.\n\n        Returns:\n\n          list of CIMInstance: Instance repository.\n\n        Raises:\n\n          :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does\n            not exist."
  },
  {
    "code": "def hookScreenshot(self, numTypes):\n        fn = self.function_table.hookScreenshot\n        pSupportedTypes = EVRScreenshotType()\n        result = fn(byref(pSupportedTypes), numTypes)\n        return result, pSupportedTypes",
    "docstring": "Called by the running VR application to indicate that it\n         wishes to be in charge of screenshots.  If the\n         application does not call this, the Compositor will only\n         support VRScreenshotType_Stereo screenshots that will be\n         captured without notification to the running app.\n         Once hooked your application will receive a\n         VREvent_RequestScreenshot event when the user presses the\n         buttons to take a screenshot."
  },
  {
    "code": "def set_consistent(self, consistent_config):\n        self.topology._add_job_control_plane()\n        self.oport.operator.consistent(consistent_config)\n        return self._make_placeable()",
    "docstring": "Indicates that the stream is the start of a consistent region.\n\n        Args:\n            consistent_config(consistent.ConsistentRegionConfig): the configuration of the consistent region.\n\n        Returns:\n            Stream: Returns this stream.\n\n        .. versionadded:: 1.11"
  },
  {
    "code": "def nltides_gw_phase_diff_isco(f_low, f0, amplitude, n, m1, m2):\n    f0, amplitude, n, m1, m2, input_is_array = ensurearray(\n        f0, amplitude, n, m1, m2)\n    f_low = numpy.zeros(m1.shape) + f_low\n    phi_l = nltides_gw_phase_difference(\n                f_low, f0, amplitude, n, m1, m2)\n    f_isco = f_schwarzchild_isco(m1+m2)\n    phi_i = nltides_gw_phase_difference(\n                f_isco, f0, amplitude, n, m1, m2)\n    return formatreturn(phi_i - phi_l, input_is_array)",
    "docstring": "Calculate the gravitational-wave phase shift bwtween\n    f_low and f_isco due to non-linear tides.\n\n    Parameters\n    ----------\n    f_low: float\n        Frequency from which to compute phase. If the other\n        arguments are passed as numpy arrays then the value\n        of f_low is duplicated for all elements in the array\n    f0: float or numpy.array\n        Frequency that NL effects switch on\n    amplitude: float or numpy.array\n        Amplitude of effect\n    n: float or numpy.array\n        Growth dependence of effect\n    m1: float or numpy.array\n        Mass of component 1\n    m2: float or numpy.array\n        Mass of component 2\n\n    Returns\n    -------\n    delta_phi: float or numpy.array\n        Phase in radians"
  },
  {
    "code": "def grad_log_q(self,z):\n        param_count = 0\n        grad = np.zeros((np.sum(self.approx_param_no),self.sims))\n        for core_param in range(len(self.q)):\n            for approx_param in range(self.q[core_param].param_no):\n                grad[param_count] = self.q[core_param].vi_score(z[core_param],approx_param)        \n                param_count += 1\n        return grad",
    "docstring": "The gradients of the approximating distributions"
  },
  {
    "code": "def update(self, params):\n        dev_info = self.json_state.get('deviceInfo')\n        dev_info.update({k: params[k] for k in params if dev_info.get(k)})",
    "docstring": "Update the dev_info data from a dictionary.\n\n        Only updates if it already exists in the device."
  },
  {
    "code": "def prepare(self, inputstring, strip=False, nl_at_eof_check=False, **kwargs):\n        if self.strict and nl_at_eof_check and inputstring and not inputstring.endswith(\"\\n\"):\n            end_index = len(inputstring) - 1 if inputstring else 0\n            raise self.make_err(CoconutStyleError, \"missing new line at end of file\", inputstring, end_index)\n        original_lines = inputstring.splitlines()\n        if self.keep_lines:\n            self.original_lines = original_lines\n        inputstring = \"\\n\".join(original_lines)\n        if strip:\n            inputstring = inputstring.strip()\n        return inputstring",
    "docstring": "Prepare a string for processing."
  },
  {
    "code": "def delete(self, *names):\n        names = [self.redis_key(n) for n in names]\n        with self.pipe as pipe:\n            return pipe.delete(*names)",
    "docstring": "Remove the key from redis\n\n        :param names: tuple of strings - The keys to remove from redis.\n        :return: Future()"
  },
  {
    "code": "def to_dict(self):\n        return {\n            \"total\": self.total,\n            \"subtotal\": self.subtotal,\n            \"items\": self.items,\n            \"extra_amount\": self.extra_amount\n        }",
    "docstring": "Attribute values to dict"
  },
  {
    "code": "def setup():\n    l_mitogen = logging.getLogger('mitogen')\n    l_mitogen_io = logging.getLogger('mitogen.io')\n    l_ansible_mitogen = logging.getLogger('ansible_mitogen')\n    for logger in l_mitogen, l_mitogen_io, l_ansible_mitogen:\n        logger.handlers = [Handler(display.vvv)]\n        logger.propagate = False\n    if display.verbosity > 2:\n        l_ansible_mitogen.setLevel(logging.DEBUG)\n        l_mitogen.setLevel(logging.DEBUG)\n    else:\n        l_mitogen.setLevel(logging.ERROR)\n        l_ansible_mitogen.setLevel(logging.ERROR)\n    if display.verbosity > 3:\n        l_mitogen_io.setLevel(logging.DEBUG)",
    "docstring": "Install handlers for Mitogen loggers to redirect them into the Ansible\n    display framework. Ansible installs its own logging framework handlers when\n    C.DEFAULT_LOG_PATH is set, therefore disable propagation for our handlers."
  },
  {
    "code": "def _selectView( self ):\r\n        scene = self.uiGanttVIEW.scene()\r\n        scene.blockSignals(True)\r\n        scene.clearSelection()\r\n        for item in self.uiGanttTREE.selectedItems():\r\n            item.viewItem().setSelected(True)\r\n        scene.blockSignals(False)\r\n        curr_item = self.uiGanttTREE.currentItem()\r\n        vitem = curr_item.viewItem()\r\n        if vitem:\r\n            self.uiGanttVIEW.centerOn(vitem)",
    "docstring": "Matches the view selection to the trees selection."
  },
  {
    "code": "def append(self, pipeline):\n        for stage in pipeline.pipe:\n            self._pipe.append(stage)\n        return self",
    "docstring": "Append a pipeline to this pipeline.\n\n        :param pipeline: Pipeline to append.\n        :returns: This pipeline."
  },
  {
    "code": "def query(key, value=None, service=None, profile=None):\n    comps = key.split('?')\n    key = comps[0]\n    key_vars = {}\n    for pair in comps[1].split('&'):\n        pair_key, pair_val = pair.split('=')\n        key_vars[pair_key] = pair_val\n    renderer = __opts__.get('renderer', 'jinja|yaml')\n    rend = salt.loader.render(__opts__, {})\n    blacklist = __opts__.get('renderer_blacklist')\n    whitelist = __opts__.get('renderer_whitelist')\n    url = compile_template(\n        ':string:',\n        rend,\n        renderer,\n        blacklist,\n        whitelist,\n        input_data=profile[key]['url'],\n        **key_vars\n    )\n    extras = {}\n    for item in profile[key]:\n        if item not in ('backend', 'url'):\n            extras[item] = profile[key][item]\n    result = http.query(\n        url,\n        decode=True,\n        **extras\n    )\n    return result['dict']",
    "docstring": "Get a value from the REST interface"
  },
  {
    "code": "async def trigger_all(self, *args, **kwargs):\n        tasks = []\n        for a in self.get_agents(addr=False, include_manager=False):\n            task = asyncio.ensure_future(self.trigger_act\n                                         (*args, agent=a, **kwargs))\n            tasks.append(task)\n        rets = await asyncio.gather(*tasks)\n        return rets",
    "docstring": "Trigger all agents in the environment to act asynchronously.\n\n        :returns: A list of agents' :meth:`act` return values.\n\n        Given arguments and keyword arguments are passed down to each agent's\n        :meth:`creamas.core.agent.CreativeAgent.act`.\n\n        .. note::\n\n            By design, the environment's manager agent, i.e. if the environment\n            has :attr:`manager`, is excluded from acting."
  },
  {
    "code": "def _expand_json(self, j):\n        decompressed_json = copy.copy(j)\n        decompressed_json.pop('blob', None)\n        compressed_data = base64.b64decode(j['blob'])\n        original_json = zlib.decompress(compressed_data).decode('utf-8')\n        decompressed_json['users'] = json.loads(original_json)\n        return decompressed_json",
    "docstring": "Decompress the BLOB portion of the usernotes.\n\n        Arguments:\n            j: the JSON returned from the wiki page (dict)\n\n        Returns a Dict with the 'blob' key removed and a 'users' key added"
  },
  {
    "code": "def serv(args):\n    if not args.no_debug:\n        tornado.autoreload.start()\n    extra = []\n    if sys.stdout.isatty():\n        sys.stdout.write('\\x1b]2;rw: {}\\x07'.format(' '.join(sys.argv[2:])))\n    if args.cfg:\n        extra.append(os.path.abspath(args.cfg))\n    listen = (int(args.port), args.address)\n    ioloop = tornado.ioloop.IOLoop.instance()\n    setup_app(app=args.MODULE, extra_configs=extra,\n              ioloop=ioloop, listen=listen)\n    ioloop.start()",
    "docstring": "Serve a rueckenwind application"
  },
  {
    "code": "def subdivide(self):\n        r\n        nodes_a, nodes_b, nodes_c, nodes_d = _surface_helpers.subdivide_nodes(\n            self._nodes, self._degree\n        )\n        return (\n            Surface(nodes_a, self._degree, _copy=False),\n            Surface(nodes_b, self._degree, _copy=False),\n            Surface(nodes_c, self._degree, _copy=False),\n            Surface(nodes_d, self._degree, _copy=False),\n        )",
    "docstring": "r\"\"\"Split the surface into four sub-surfaces.\n\n        Does so by taking the unit triangle (i.e. the domain\n        of the surface) and splitting it into four sub-triangles\n\n        .. image:: ../../images/surface_subdivide1.png\n           :align: center\n\n        Then the surface is re-parameterized via the map to / from the\n        given sub-triangles and the unit triangle.\n\n        For example, when a degree two surface is subdivided:\n\n        .. image:: ../../images/surface_subdivide2.png\n           :align: center\n\n        .. doctest:: surface-subdivide\n           :options: +NORMALIZE_WHITESPACE\n\n           >>> nodes = np.asfortranarray([\n           ...     [-1.0, 0.5, 2.0, 0.25, 2.0, 0.0],\n           ...     [ 0.0, 0.5, 0.0, 1.75, 3.0, 4.0],\n           ... ])\n           >>> surface = bezier.Surface(nodes, degree=2)\n           >>> _, sub_surface_b, _, _ = surface.subdivide()\n           >>> sub_surface_b\n           <Surface (degree=2, dimension=2)>\n           >>> sub_surface_b.nodes\n           array([[ 1.5 ,  0.6875, -0.125 , 1.1875, 0.4375, 0.5  ],\n                  [ 2.5 ,  2.3125,  1.875 , 1.3125, 1.3125, 0.25 ]])\n\n        .. testcleanup:: surface-subdivide\n\n           import make_images\n           make_images.surface_subdivide1()\n           make_images.surface_subdivide2(surface, sub_surface_b)\n\n        Returns:\n            Tuple[Surface, Surface, Surface, Surface]: The lower left, central,\n            lower right and upper left sub-surfaces (in that order)."
  },
  {
    "code": "def ReadAllClientActionRequests(self, client_id):\n    res = []\n    for key, orig_request in iteritems(self.client_action_requests):\n      request_client_id, _, _ = key\n      if request_client_id != client_id:\n        continue\n      request = orig_request.Copy()\n      current_lease = self.client_action_request_leases.get(key)\n      request.ttl = db.Database.CLIENT_MESSAGES_TTL\n      if current_lease is not None:\n        request.leased_until, request.leased_by, leased_count = current_lease\n        request.ttl -= leased_count\n      else:\n        request.leased_until = None\n        request.leased_by = None\n      res.append(request)\n    return res",
    "docstring": "Reads all client action requests available for a given client_id."
  },
  {
    "code": "def search_range(self, value):\n        if value == 0 or not value % 16:\n            self._search_range = value\n        else:\n            raise InvalidSearchRangeError(\"Search range must be a multiple of \"\n                                          \"16.\")\n        self._replace_bm()",
    "docstring": "Set private ``_search_range`` and reset ``_block_matcher``."
  },
  {
    "code": "def find(self, target, relation):\n        query = 'select ob1.code from objects as ob1, objects as ob2, relations where relations.dst=ob1.id and relations.name=? and relations.src=ob2.id and ob2.code=?'\n        for i in self._execute(query, (relation, self.serialize(target))):\n            yield self.deserialize(i[0])",
    "docstring": "returns back all elements the target has a relation to"
  },
  {
    "code": "def _water(cls, T, P):\n        water = IAPWS95(P=P, T=T)\n        prop = {}\n        prop[\"g\"] = water.h-T*water.s\n        prop[\"gt\"] = -water.s\n        prop[\"gp\"] = 1./water.rho\n        prop[\"gtt\"] = -water.cp/T\n        prop[\"gtp\"] = water.betas*water.cp/T\n        prop[\"gpp\"] = -1e6/(water.rho*water.w)**2-water.betas**2*1e3*water.cp/T\n        prop[\"gs\"] = 0\n        prop[\"gsp\"] = 0\n        prop[\"thcond\"] = water.k\n        return prop",
    "docstring": "Get properties of pure water, Table4 pag 8"
  },
  {
    "code": "def Setup():\n    if not os.path.exists(os.path.join(EVEREST_DAT, 'k2', 'cbv')):\n        os.makedirs(os.path.join(EVEREST_DAT, 'k2', 'cbv'))\n    GetK2Stars(clobber=False)",
    "docstring": "Called when the code is installed. Sets up directories and downloads\n    the K2 catalog."
  },
  {
    "code": "def associate_ipv6(self, id_equip, id_ipv6):\n        if not is_valid_int_param(id_equip):\n            raise InvalidParameterError(\n                u'The identifier of equipment is invalid or was not informed.')\n        if not is_valid_int_param(id_ipv6):\n            raise InvalidParameterError(\n                u'The identifier of ip is invalid or was not informed.')\n        url = 'ipv6/' + str(id_ipv6) + '/equipment/' + str(id_equip) + '/'\n        code, xml = self.submit(None, 'PUT', url)\n        return self.response(code, xml)",
    "docstring": "Associates an IPv6 to a equipament.\n\n        :param id_equip: Identifier of the equipment. Integer value and greater than zero.\n        :param id_ipv6: Identifier of the ip. Integer value and greater than zero.\n\n        :return: Dictionary with the following structure:\n            {'ip_equipamento': {'id': < id_ip_do_equipamento >}}\n\n        :raise EquipamentoNaoExisteError: Equipment is not registered.\n        :raise IpNaoExisteError: IP not registered.\n        :raise IpError: IP is already associated with the equipment.\n        :raise InvalidParameterError:  Identifier of the equipment and/or IP is null or invalid.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def run_license_checker(config_path):\n    whitelist_licenses = _get_whitelist_licenses(config_path)\n    table = PrintTable(ROW_HEADERS)\n    warnings = []\n    for pkg in _get_packages():\n        allowed = pkg.license in whitelist_licenses\n        table.add_row((pkg.name, pkg.version, pkg.license, str(allowed)))\n        if not allowed:\n            warnings.append(pkg)\n    print(table)\n    print('{} RESTRICTED LICENSES DETECTED'.format(len(warnings)))",
    "docstring": "Generate table of installed packages and check for license\n    warnings based off user defined restricted license values.\n\n    :param config_path: str\n    :return:"
  },
  {
    "code": "def create_milestones(self, project_id, milestones):\n        path = '/projects/%u/milestones/create' % project_id\n        req = ET.Element('request')\n        for milestone in milestones:\n            req.append(self._create_milestone_elem(*milestone))\n        return self._request(path, req)",
    "docstring": "With this function you can create multiple milestones in a single\n        request. See the \"create\" function for a description of the individual\n        fields in the milestone."
  },
  {
    "code": "def traverse_preorder(self, leaves=True, internal=True):\n        s = deque(); s.append(self)\n        while len(s) != 0:\n            n = s.pop()\n            if (leaves and n.is_leaf()) or (internal and not n.is_leaf()):\n                yield n\n            s.extend(n.children)",
    "docstring": "Perform a preorder traversal starting at this ``Node`` object\n\n        Args:\n            ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``\n\n            ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``"
  },
  {
    "code": "def get_histograms_in_list(filename: str, list_name: str = None) -> Dict[str, Any]:\n    hists: dict = {}\n    with RootOpen(filename = filename, mode = \"READ\") as fIn:\n        if list_name is not None:\n            hist_list = fIn.Get(list_name)\n        else:\n            hist_list = [obj.ReadObj() for obj in fIn.GetListOfKeys()]\n        if not hist_list:\n            fIn.ls()\n            fIn.Close()\n            raise ValueError(f\"Could not find list with name \\\"{list_name}\\\". Possible names are listed above.\")\n        for obj in hist_list:\n            _retrieve_object(hists, obj)\n    return hists",
    "docstring": "Get histograms from the file and make them available in a dict.\n\n    Lists are recursively explored, with all lists converted to dictionaries, such that the return\n    dictionaries which only contains hists and dictionaries of hists (ie there are no ROOT ``TCollection``\n    derived objects).\n\n    Args:\n        filename: Filename of the ROOT file containing the list.\n        list_name: Name of the list to retrieve.\n    Returns:\n        Contains hists with keys as their names. Lists are recursively added, mirroring\n            the structure under which the hists were stored.\n    Raises:\n        ValueError: If the list could not be found in the given file."
  },
  {
    "code": "def remove_existing_links(root_dir):\n    logger = logging.getLogger(__name__)\n    for name in os.listdir(root_dir):\n        full_name = os.path.join(root_dir, name)\n        if os.path.islink(full_name):\n            logger.debug('Deleting existing symlink {0}'.format(full_name))\n            os.remove(full_name)",
    "docstring": "Delete any symlinks present at the root of a directory.\n\n    Parameters\n    ----------\n    root_dir : `str`\n        Directory that might contain symlinks.\n\n    Notes\n    -----\n    This function is used to remove any symlinks created by `link_directories`.\n    Running ``remove_existing_links`` at the beginning of a build ensures that\n    builds are isolated. For example, if a package is un-setup it won't\n    re-appear in the documentation because its symlink still exists."
  },
  {
    "code": "def shutdown(self):\n        self.socket.shutdown()\n        if scoop:\n            if scoop.DEBUG:\n                from scoop import _debug\n                _debug.writeWorkerDebug(\n                    scoop._control.debug_stats,\n                    scoop._control.QueueLength,\n                )",
    "docstring": "Shutdown the ressources used by the queue"
  },
  {
    "code": "def remove_media(files):\n    for filename in files:\n        os.remove(os.path.join(settings.MEDIA_ROOT, filename))",
    "docstring": "Delete file from media dir"
  },
  {
    "code": "def _check_times(self, min_times, max_times, step):\n        kassert.is_int(min_times)\n        kassert.is_int(max_times)\n        kassert.is_int(step)\n        if not((min_times >= 0) and (max_times > 0) and (max_times >= min_times) and (step > 0)):\n            raise KittyException('one of the checks failed: min_times(%d)>=0, max_times(%d)>0, max_times>=min_times, step > 0' % (min_times, max_times))",
    "docstring": "Make sure that the arguments are valid\n\n        :raises: KittyException if not valid"
  },
  {
    "code": "def browse_dailydeviations(self):\n        response = self._req('/browse/dailydeviations')\n        deviations = []\n        for item in response['results']:\n            d = Deviation()\n            d.from_dict(item)\n            deviations.append(d)\n        return deviations",
    "docstring": "Retrieves Daily Deviations"
  },
  {
    "code": "def timeseries_to_matrix( image, mask=None ):\n    temp = utils.ndimage_to_list( image )\n    if mask is None:\n        mask = temp[0]*0 + 1\n    return image_list_to_matrix( temp, mask )",
    "docstring": "Convert a timeseries image into a matrix.\n\n    ANTsR function: `timeseries2matrix`\n\n    Arguments\n    ---------\n    image : image whose slices we convert to a matrix. E.g. a 3D image of size\n           x by y by z will convert to a z by x*y sized matrix\n\n    mask : ANTsImage (optional)\n        image containing binary mask. voxels in the mask are placed in the matrix\n\n    Returns\n    -------\n    ndarray\n        array with a row for each image\n        shape = (N_IMAGES, N_VOXELS)\n\n    Example\n    -------\n    >>> import ants\n    >>> img = ants.make_image( (10,10,10,5 ) )\n    >>> mat = ants.timeseries_to_matrix( img )"
  },
  {
    "code": "def get_steps_branch_len(self, length):\n        return log(length/self.length, min(self.branches[0][0]))",
    "docstring": "Get, how much steps will needed for a given branch length.\n\n        Returns:\n            float: The age the tree must achieve to reach the given branch length."
  },
  {
    "code": "def remove_lock(self):\n        key = '%s_lock' % self.scheduler_key\n        if self._lock_acquired:\n            self.connection.delete(key)",
    "docstring": "Remove acquired lock."
  },
  {
    "code": "def getFailedJobIDs(self, extraLapse = TYPICAL_LAPSE):\n\t\tscriptsRun = self.scriptsRun\n\t\tfailedJobTimestamps = []\n\t\tnodata = []\n\t\tfor name, details in sorted(scriptsRun.iteritems()):\n\t\t\tif details[\"lastSuccess\"] and expectedScripts.get(name):\n\t\t\t\tif not expectedScripts.check(name, details[\"lastSuccess\"], extraLapse): \n\t\t\t\t\tif details[\"lastRun\"]:\n\t\t\t\t\t\tfailedJobTimestamps.append(details[\"lastRun\"])\n\t\t\t\t\telse:\n\t\t\t\t\t\tnodata.append(name)\n\t\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tif details[\"lastRun\"]:\n\t\t\t\t\tfailedJobTimestamps.append(details[\"lastRun\"])\n\t\t\t\telse:\n\t\t\t\t\tnodata.append(name)\n\t\t\t\tcontinue\n\t\t\tif details[\"status\"] & RETROSPECT_FAIL:\n\t\t\t\tfailedJobTimestamps.append(details[\"lastRun\"])\n\t\t\telif details[\"status\"] & RETROSPECT_WARNING:\n\t\t\t\tfailedJobTimestamps.append(details[\"lastRun\"])\n\t\treturn failedJobTimestamps, nodata",
    "docstring": "Returns a list of which identify failed jobs in the scriptsRun table.\n\t\t\tIf a time stamp for a job can be found, we return this. The time stamp can be used to index the log.\n\t\t\tIf no time stamp was found, return the name of the script instead."
  },
  {
    "code": "def remove_stream(self, ssrc):\n        _srtp_assert(lib.srtp_remove_stream(self._srtp[0], htonl(ssrc)))",
    "docstring": "Remove the stream with the given `ssrc` from the SRTP session.\n\n        :param ssrc: :class:`int`"
  },
  {
    "code": "def _ensure_array(self, key, value):\n        if key not in self._json_dict:\n            self._json_dict[key] = []\n            self._size += 2\n            self._ensure_field(key)\n        if len(self._json_dict[key]) > 0:\n            self._size += 2\n        if isinstance(value, str):\n            self._size += 2\n        self._size += len(str(value))\n        self._json_dict[key].append(value)",
    "docstring": "Ensure an array field"
  },
  {
    "code": "def indent(lines, spaces=4):\n    if isinstance(lines, str):\n        text = [lines]\n    text = '\\n'.join(lines)\n    return textwrap.indent(text, ' ' * spaces)",
    "docstring": "Indent `lines` by `spaces` spaces.\n\n    Parameters\n    ----------\n    lines : Union[str, List[str]]\n        A string or list of strings to indent\n    spaces : int\n        The number of spaces to indent `lines`\n\n    Returns\n    -------\n    indented_lines : str"
  },
  {
    "code": "def visit_Dict(self, node: ast.Dict) -> Dict[Any, Any]:\n        recomputed_dict = dict()\n        for key, val in zip(node.keys, node.values):\n            recomputed_dict[self.visit(node=key)] = self.visit(node=val)\n        self.recomputed_values[node] = recomputed_dict\n        return recomputed_dict",
    "docstring": "Visit keys and values and assemble a dictionary with the results."
  },
  {
    "code": "def find_bucket(self, bucketing_id, parent_id, traffic_allocations):\n    bucketing_key = BUCKETING_ID_TEMPLATE.format(bucketing_id=bucketing_id, parent_id=parent_id)\n    bucketing_number = self._generate_bucket_value(bucketing_key)\n    self.config.logger.debug('Assigned bucket %s to user with bucketing ID \"%s\".' % (\n      bucketing_number,\n      bucketing_id\n    ))\n    for traffic_allocation in traffic_allocations:\n      current_end_of_range = traffic_allocation.get('endOfRange')\n      if bucketing_number < current_end_of_range:\n        return traffic_allocation.get('entityId')\n    return None",
    "docstring": "Determine entity based on bucket value and traffic allocations.\n\n    Args:\n      bucketing_id: ID to be used for bucketing the user.\n      parent_id: ID representing group or experiment.\n      traffic_allocations: Traffic allocations representing traffic allotted to experiments or variations.\n\n    Returns:\n      Entity ID which may represent experiment or variation."
  },
  {
    "code": "def get_graph_metadata(self, graph):\n        _params = set()\n        for tensor_vals in graph.initializer:\n            _params.add(tensor_vals.name)\n        input_data = []\n        for graph_input in graph.input:\n            if graph_input.name not in _params:\n                shape = [val.dim_value for val in graph_input.type.tensor_type.shape.dim]\n                input_data.append((graph_input.name, tuple(shape)))\n        output_data = []\n        for graph_out in graph.output:\n            shape = [val.dim_value for val in graph_out.type.tensor_type.shape.dim]\n            output_data.append((graph_out.name, tuple(shape)))\n        metadata = {'input_tensor_data' : input_data,\n                    'output_tensor_data' : output_data\n                   }\n        return metadata",
    "docstring": "Get the model metadata from a given onnx graph."
  },
  {
    "code": "def encode(self, name, as_map_key=False):\n        if name in self.key_to_value:\n            return self.key_to_value[name]\n        return self.encache(name) if is_cacheable(name, as_map_key) else name",
    "docstring": "Returns the name the first time and the key after that"
  },
  {
    "code": "def commiter_factory(config: dict) -> BaseCommitizen:\n    name: str = config[\"name\"]\n    try:\n        _cz = registry[name](config)\n    except KeyError:\n        msg_error = (\n            \"The commiter has not been found in the system.\\n\\n\"\n            f\"Try running 'pip install {name}'\\n\"\n        )\n        out.error(msg_error)\n        raise SystemExit(NO_COMMITIZEN_FOUND)\n    else:\n        return _cz",
    "docstring": "Return the correct commitizen existing in the registry."
  },
  {
    "code": "def mcscanq(args):\n    p = OptionParser(mcscanq.__doc__)\n    p.add_option(\"--color\", help=\"Add color highlight, used in plotting\")\n    p.add_option(\"--invert\", default=False, action=\"store_true\",\n                 help=\"Invert query and subject [default: %default]\")\n    opts, args = p.parse_args(args)\n    if len(args) < 2:\n        sys.exit(not p.print_help())\n    qids, blocksfile = args\n    b = BlockFile(blocksfile)\n    fp = open(qids)\n    for gene in fp:\n        gene = gene.strip()\n        for line in b.query_gene(gene, color=opts.color, invert=opts.invert):\n            print(line)",
    "docstring": "%prog mcscanq query.ids blocksfile\n\n    Query multiple synteny blocks to get the closest alignment feature. Mostly\n    used for 'highlighting' the lines in the synteny plot, drawn by\n    graphics.karyotype and graphics.synteny."
  },
  {
    "code": "def score(package_path):\n    python_files = find_files(package_path, '*.py')\n    total_counter = Counter()\n    for python_file in python_files:\n        output = run_pylint(python_file)\n        counter = parse_pylint_output(output)\n        total_counter += counter\n    score_value = 0\n    for count, stat in enumerate(total_counter):\n        score_value += SCORING_VALUES[stat] * count\n    return score_value / 5",
    "docstring": "Runs pylint on a package and returns a score\n    Lower score is better\n\n    :param package_path: path of the package to score\n    :return: number of score"
  },
  {
    "code": "def deploy(remote, assets_to_s3):\n    header(\"Deploying...\")\n    if assets_to_s3:\n        for mod in get_deploy_assets2s3_list(CWD):\n            _assets2s3(mod)\n    remote_name = remote or \"ALL\"\n    print(\"Pushing application's content to remote: %s \" % remote_name)\n    hosts = get_deploy_hosts_list(CWD, remote or None)\n    git_push_to_master(cwd=CWD, hosts=hosts, name=remote_name)\n    print(\"Done!\")",
    "docstring": "To DEPLOY your application"
  },
  {
    "code": "def refresh_items(self):\n        items = []\n        if self.condition:\n            for nodes, key, f_locals in self.pattern_nodes:\n                with new_scope(key, f_locals):\n                    for node in nodes:\n                        child = node(None)\n                        if isinstance(child, list):\n                            items.extend(child)\n                        else:\n                            items.append(child)\n        for old in self.items:\n            if not old.is_destroyed:\n                old.destroy()\n        self.items = items",
    "docstring": "Refresh the items of the pattern.\n        This method destroys the old items and creates and initializes\n        the new items.\n\n        It is overridden to NOT insert the children to the parent. The Fragment\n        adapter handles this."
  },
  {
    "code": "def main():\n    args = parse_input()\n    args.lock = True\n    args.question = []\n    args.all = False\n    args.timeout = 0\n    args.verbose = False\n    args.interactive = False\n    try:\n        assign = assignment.load_assignment(args.config, args)\n        msgs = messages.Messages()\n        lock.protocol(args, assign).run(msgs)\n    except (ex.LoadingException, ex.SerializeException) as e:\n        log.warning('Assignment could not instantiate', exc_info=True)\n        print('Error: ' + str(e).strip())\n        exit(1)\n    except (KeyboardInterrupt, EOFError):\n        log.info('Quitting...')\n    else:\n        assign.dump_tests()",
    "docstring": "Run the LockingProtocol."
  },
  {
    "code": "def iter_languages(self):\n        default_lang = self.babel.default_locale.language\n        default_title = self.babel.default_locale.get_display_name(\n            default_lang)\n        yield (default_lang, default_title)\n        for l, title in current_app.config.get('I18N_LANGUAGES', []):\n            yield l, title",
    "docstring": "Iterate over list of languages."
  },
  {
    "code": "def to_result(self, iface_name, func_name, resp):\n        if resp.has_key(\"error\"):\n            e = resp[\"error\"]\n            data = None\n            if e.has_key(\"data\"):\n                data = e[\"data\"]\n            raise RpcException(e[\"code\"], e[\"message\"], data)\n        result = resp[\"result\"]\n        if self.validate_resp:\n            self.contract.validate_response(iface_name, func_name, result)\n        return result",
    "docstring": "Takes a JSON-RPC response and checks for an \"error\" slot. If it exists,\n        a RpcException is raised.  If no \"error\" slot exists, the \"result\" slot is \n        returned.\n\n        If validate_response==True on the Client constructor, the result is validated\n        against the expected return type for the function and a RpcException raised if it is\n        invalid.\n\n        :Parameters:\n          iface_name\n            Interface name that was called\n          func_name\n            Function that was called on the interface\n          resp\n            Dict formatted as a JSON-RPC response"
  },
  {
    "code": "def _polarDecomposeInterpolationTransformation(matrix1, matrix2, value):\n    m1 = MathTransform(matrix1)\n    m2 = MathTransform(matrix2)\n    return tuple(m1.interpolate(m2, value))",
    "docstring": "Interpolate using the MathTransform method."
  },
  {
    "code": "def stop(context):\n    config = context.obj[\"config\"]\n    pidfile = select(config, \"application.pidfile\", DEFAULT_PIDFILE)\n    daemon_stop(pidfile)",
    "docstring": "Stop application server."
  },
  {
    "code": "def post(self, request, key):\n        email = request.POST.get('email')\n        user_id = request.POST.get('user')\n        if not email:\n            return http.HttpResponseBadRequest()\n        try:\n            EmailAddressValidation.objects.create(address=email,\n                                                  user_id=user_id)\n        except IntegrityError:\n            return http.HttpResponse(status=409)\n        return http.HttpResponse(status=201)",
    "docstring": "Create new email address that will wait for validation"
  },
  {
    "code": "def keypair_field_data(request, include_empty_option=False):\n    keypair_list = []\n    try:\n        keypairs = api.nova.keypair_list(request)\n        keypair_list = [(kp.name, kp.name) for kp in keypairs]\n    except Exception:\n        exceptions.handle(request, _('Unable to retrieve key pairs.'))\n    if not keypair_list:\n        if include_empty_option:\n            return [(\"\", _(\"No key pairs available\")), ]\n        return []\n    if include_empty_option:\n        return [(\"\", _(\"Select a key pair\")), ] + keypair_list\n    return keypair_list",
    "docstring": "Returns a list of tuples of all keypairs.\n\n    Generates a list of keypairs available to the user (request). And returns\n    a list of (id, name) tuples.\n\n    :param request: django http request object\n    :param include_empty_option: flag to include a empty tuple in the front of\n        the list\n    :return: list of (id, name) tuples"
  },
  {
    "code": "def _merge_bee(self, bee):\n        random_dimension = randint(0, len(self._value_ranges) - 1)\n        second_bee = randint(0, self._num_employers - 1)\n        while (bee.id == self._employers[second_bee].id):\n            second_bee = randint(0, self._num_employers - 1)\n        new_bee = deepcopy(bee)\n        new_bee.values[random_dimension] = self.__onlooker.calculate_positions(\n            new_bee.values[random_dimension],\n            self._employers[second_bee].values[random_dimension],\n            self._value_ranges[random_dimension]\n        )\n        fitness_score = new_bee.get_score(self._fitness_fxn(\n            new_bee.values,\n            **self._args\n        ))\n        return (fitness_score, new_bee.values, new_bee.error)",
    "docstring": "Shifts a random value for a supplied bee with in accordance with\n        another random bee's value\n\n        Args:\n            bee (EmployerBee): supplied bee to merge\n\n        Returns:\n            tuple: (score of new position, values of new position, fitness\n                function return value of new position)"
  },
  {
    "code": "def breakpoints_by_caller(bed_files):\n    merged = concat(bed_files)\n    if not merged:\n        return []\n    grouped_start = merged.groupby(g=[1, 2, 2], c=4, o=[\"distinct\"]).filter(lambda r: r.end > r.start).saveas()\n    grouped_end = merged.groupby(g=[1, 3, 3], c=4, o=[\"distinct\"]).filter(lambda r: r.end > r.start).saveas()\n    together = concat([grouped_start, grouped_end])\n    if together:\n        final = together.expand(c=4)\n        final = final.sort()\n        return final",
    "docstring": "given a list of BED files of the form\n    chrom start end caller\n    return a BedTool of breakpoints as each line with\n    the fourth column the caller with evidence for the breakpoint\n    chr1 1 10 caller1 -> chr1 1 1 caller1\n    chr1 1 20 caller2    chr1 1 1 caller2\n                         chr1 10 10 caller1\n                         chr1 20 20 caller2"
  },
  {
    "code": "def skip():\n\tif not settings.platformCompatible():\n\t\treturn False\n\t(output, error) = subprocess.Popen([\"osascript\", \"-e\", SKIP], stdout=subprocess.PIPE).communicate()",
    "docstring": "Tell iTunes to skip a song"
  },
  {
    "code": "def _overlay_for_saml_metadata(self, config, co_name):\n        for co in self.config[self.KEY_CO]:\n            if co[self.KEY_ENCODEABLE_NAME] == co_name:\n                break\n        key = self.KEY_ORGANIZATION\n        if key in co:\n            if key not in config:\n                config[key] = {}\n            for org_key in self.KEY_ORGANIZATION_KEYS:\n                if org_key in co[key]:\n                    config[key][org_key] = co[key][org_key]\n        key = self.KEY_CONTACT_PERSON\n        if key in co:\n            config[key] = co[key]\n        return config",
    "docstring": "Overlay configuration details like organization and contact person\n        from the front end configuration onto the IdP configuration to\n        support SAML metadata generation.\n\n        :type config: satosa.satosa_config.SATOSAConfig\n        :type co_name: str\n        :rtype: satosa.satosa_config.SATOSAConfig\n\n        :param config: satosa proxy config\n        :param co_name: CO name\n\n        :return: config with updated details for SAML metadata"
  },
  {
    "code": "def _approximate_unkown_bond_lengths(self):\n        dataset = self.lengths[BOND_SINGLE]\n        for n1 in periodic.iter_numbers():\n            for n2 in periodic.iter_numbers():\n                if n1 <= n2:\n                    pair = frozenset([n1, n2])\n                    atom1 = periodic[n1]\n                    atom2 = periodic[n2]\n                    if (pair not in dataset) and (atom1.covalent_radius is not None) and (atom2.covalent_radius is not None):\n                        dataset[pair] = (atom1.covalent_radius + atom2.covalent_radius)",
    "docstring": "Completes the bond length database with approximations based on VDW radii"
  },
  {
    "code": "def getRoutes(self):\n        routes = []\n        try:\n            out = subprocess.Popen([routeCmd, \"-n\"], \n                                   stdout=subprocess.PIPE).communicate()[0]\n        except:\n            raise Exception('Execution of command %s failed.' % ipCmd)\n        lines = out.splitlines()\n        if len(lines) > 1:\n            headers = [col.lower() for col in lines[1].split()]\n            for line in lines[2:]:\n                routes.append(dict(zip(headers, line.split())))\n        return routes",
    "docstring": "Get routing table.\n        \n        @return: List of routes."
  },
  {
    "code": "def iso8601interval(value, argument='argument'):\n    try:\n        start, end = _parse_interval(value)\n        if end is None:\n            end = _expand_datetime(start, value)\n        start, end = _normalize_interval(start, end, value)\n    except ValueError:\n        raise ValueError(\n            \"Invalid {arg}: {value}. {arg} must be a valid ISO8601 \"\n            \"date/time interval.\".format(arg=argument, value=value),\n        )\n    return start, end",
    "docstring": "Parses ISO 8601-formatted datetime intervals into tuples of datetimes.\n\n    Accepts both a single date(time) or a full interval using either start/end\n    or start/duration notation, with the following behavior:\n\n    - Intervals are defined as inclusive start, exclusive end\n    - Single datetimes are translated into the interval spanning the\n      largest resolution not specified in the input value, up to the day.\n    - The smallest accepted resolution is 1 second.\n    - All timezones are accepted as values; returned datetimes are\n      localized to UTC. Naive inputs and date inputs will are assumed UTC.\n\n    Examples::\n\n        \"2013-01-01\" -> datetime(2013, 1, 1), datetime(2013, 1, 2)\n        \"2013-01-01T12\" -> datetime(2013, 1, 1, 12), datetime(2013, 1, 1, 13)\n        \"2013-01-01/2013-02-28\" -> datetime(2013, 1, 1), datetime(2013, 2, 28)\n        \"2013-01-01/P3D\" -> datetime(2013, 1, 1), datetime(2013, 1, 4)\n        \"2013-01-01T12:00/PT30M\" -> datetime(2013, 1, 1, 12), datetime(2013, 1, 1, 12, 30)\n        \"2013-01-01T06:00/2013-01-01T12:00\" -> datetime(2013, 1, 1, 6), datetime(2013, 1, 1, 12)\n\n    :param str value: The ISO8601 date time as a string\n    :return: Two UTC datetimes, the start and the end of the specified interval\n    :rtype: A tuple (datetime, datetime)\n    :raises: ValueError, if the interval is invalid."
  },
  {
    "code": "def transform_pip_requirement_set(self, requirement_set):\n        filtered_requirements = []\n        for requirement in requirement_set.requirements.values():\n            if requirement.satisfied_by:\n                continue\n            if requirement.constraint:\n                continue\n            filtered_requirements.append(requirement)\n            self.reported_requirements.append(requirement)\n        return sorted([Requirement(self.config, r) for r in filtered_requirements],\n                      key=lambda r: r.name.lower())",
    "docstring": "Transform pip's requirement set into one that `pip-accel` can work with.\n\n        :param requirement_set: The :class:`pip.req.RequirementSet` object\n                                reported by pip.\n        :returns: A list of :class:`pip_accel.req.Requirement` objects.\n\n        This function converts the :class:`pip.req.RequirementSet` object\n        reported by pip into a list of :class:`pip_accel.req.Requirement`\n        objects."
  },
  {
    "code": "def clear_instance_cache(cls, func):\n        @functools.wraps(func)\n        def func_wrapper(*args, **kwargs):\n            if not args:\n                raise ValueError('`self` is not available.')\n            else:\n                the_self = args[0]\n            cls.clear_self_cache(the_self)\n            return func(*args, **kwargs)\n        return func_wrapper",
    "docstring": "clear the instance cache\n\n        Decorate a method of a class, the first parameter is\n        supposed to be `self`.\n        It clear all items cached by the `instance_cache` decorator.\n        :param func: function to decorate"
  },
  {
    "code": "def _HostPrefix(client_id):\n  if not client_id:\n    return \"\"\n  hostname = None\n  if data_store.RelationalDBEnabled():\n    client_snapshot = data_store.REL_DB.ReadClientSnapshot(client_id)\n    if client_snapshot:\n      hostname = client_snapshot.knowledge_base.fqdn\n  else:\n    client_fd = aff4.FACTORY.Open(client_id, mode=\"rw\")\n    hostname = client_fd.Get(client_fd.Schema.FQDN) or \"\"\n  if hostname:\n    return \"%s: \" % hostname\n  else:\n    return \"\"",
    "docstring": "Build a host prefix for a notification message based on a client id."
  },
  {
    "code": "def _get_appoptics(options):\n    conn = appoptics_metrics.connect(\n        options.get('api_token'),\n        sanitizer=appoptics_metrics.sanitize_metric_name,\n        hostname=options.get('api_url'))\n    log.info(\"Connected to appoptics.\")\n    return conn",
    "docstring": "Return an appoptics connection object."
  },
  {
    "code": "def get_output_fields(self):\n        emit_fields = list(i.lower() for i in re.sub(r\"[^_A-Z]+\", ' ', self.format_item(None)).split())\n        result = []\n        for name in emit_fields[:]:\n            if name not in engine.FieldDefinition.FIELDS:\n                self.LOG.warn(\"Omitted unknown name '%s' from statistics and output format sorting\" % name)\n            else:\n                result.append(name)\n        return result",
    "docstring": "Get field names from output template."
  },
  {
    "code": "def _check_algorithm_values(item):\n    problems = []\n    for k, v in item.get(\"algorithm\", {}).items():\n        if v is True and k not in ALG_ALLOW_BOOLEANS:\n            problems.append(\"%s set as true\" % k)\n        elif v is False and (k not in ALG_ALLOW_BOOLEANS and k not in ALG_ALLOW_FALSE):\n            problems.append(\"%s set as false\" % k)\n    if len(problems) > 0:\n        raise ValueError(\"Incorrect settings in 'algorithm' section for %s:\\n%s\"\n                         \"\\nSee configuration documentation for supported options:\\n%s\\n\"\n                         % (item[\"description\"], \"\\n\".join(problems), ALG_DOC_URL))",
    "docstring": "Check for misplaced inputs in the algorithms.\n\n    - Identify incorrect boolean values where a choice is required."
  },
  {
    "code": "def set(self, hue):\n        x = hue / 360. * self.winfo_width()\n        self.coords('cursor', x, 0, x, self.winfo_height())\n        self._variable.set(hue)",
    "docstring": "Set cursor position on the color corresponding to the hue value."
  },
  {
    "code": "def read_time(self, content):\n        if get_class_name(content) in self.content_type_supported:\n            if hasattr(content, 'readtime'):\n                return None\n            default_lang_conf = self.lang_settings['default']\n            lang_conf = self.lang_settings.get(content.lang, default_lang_conf)\n            avg_reading_wpm = lang_conf['wpm']\n            num_words = len(content._content.split())\n            minutes = num_words // avg_reading_wpm\n            seconds = int((num_words / avg_reading_wpm * 60) - (minutes * 60))\n            minutes_str = self.pluralize(\n                minutes,\n                lang_conf['min_singular'],\n                lang_conf['min_plural']\n            )\n            seconds_str = self.pluralize(\n                seconds,\n                lang_conf['sec_singular'],\n                lang_conf['sec_plural']\n            )\n            content.readtime = minutes\n            content.readtime_string = minutes_str\n            content.readtime_with_seconds = (minutes, seconds,)\n            content.readtime_string_with_seconds = \"{}, {}\".format(\n                minutes_str, seconds_str)",
    "docstring": "Core function used to generate the read_time for content.\n\n        Parameters:\n            :param content: Instance of pelican.content.Content\n\n        Returns:\n            None"
  },
  {
    "code": "def to_unicode_string(string):\n    if string is None:\n        return None\n    if is_unicode_string(string):\n        return string\n    if PY2:\n        return unicode(string, encoding=\"utf-8\")\n    return string.decode(encoding=\"utf-8\")",
    "docstring": "Return a Unicode string out of the given string.\n    \n    On Python 2, it calls ``unicode`` with ``utf-8`` encoding.\n    On Python 3, it just returns the given string.\n\n    Return ``None`` if ``string`` is ``None``.\n\n    :param str string: the string to convert to Unicode\n    :rtype: (Unicode) str"
  },
  {
    "code": "def request_video_count(blink):\n    url = \"{}/api/v2/videos/count\".format(blink.urls.base_url)\n    return http_get(blink, url)",
    "docstring": "Request total video count."
  },
  {
    "code": "def repackage_var(h):\n    if IS_TORCH_04: return h.detach() if type(h) == torch.Tensor else tuple(repackage_var(v) for v in h)\n    else: return Variable(h.data) if type(h) == Variable else tuple(repackage_var(v) for v in h)",
    "docstring": "Wraps h in new Variables, to detach them from their history."
  },
  {
    "code": "def limit(self, limit):\n        if limit is None:\n            raise ValueError(\"Invalid value for `limit`, must not be `None`\")\n        if limit > 200:\n            raise ValueError(\"Invalid value for `limit`, must be a value less than or equal to `200`\")\n        if limit < 1:\n            raise ValueError(\"Invalid value for `limit`, must be a value greater than or equal to `1`\")\n        self._limit = limit",
    "docstring": "Sets the limit of this ListEmployeeWagesRequest.\n        Maximum number of Employee Wages to return per page. Can range between 1 and 200. The default is the maximum at 200.\n\n        :param limit: The limit of this ListEmployeeWagesRequest.\n        :type: int"
  },
  {
    "code": "def close(self, cancelled=False):\n        self._on_close(cancelled)\n        self._scene.remove_effect(self)",
    "docstring": "Close this temporary pop-up.\n\n        :param cancelled: Whether the pop-up was cancelled (e.g. by pressing Esc)."
  },
  {
    "code": "def push_pv(self, tokens):\n        logger.debug(\"Pushing PV data: %s\" % tokens)\n        bus = self.case.buses[tokens[\"bus_no\"]-1]\n        g = Generator(bus)\n        g.p = tokens[\"p\"]\n        g.q_max = tokens[\"q_max\"]\n        g.q_min = tokens[\"q_min\"]\n        self.case.generators.append(g)",
    "docstring": "Creates and Generator object, populates it with data, finds its Bus\n        and adds it."
  },
  {
    "code": "def save(self, file, contents, name=None, overwrite=False):\n        if name is None:\n            name = self.format_from_extension(op.splitext(file)[1])\n        file_format = self.file_type(name)\n        if file_format == 'text':\n            _write_text(file, contents)\n        elif file_format == 'json':\n            _write_json(file, contents)\n        else:\n            write_function = self._formats[name].get('save', None)\n            if write_function is None:\n                raise IOError(\"The format must declare a file type or \"\n                              \"load/save functions.\")\n            if op.exists(file) and not overwrite:\n                print(\"The file already exists, please use overwrite=True.\")\n                return\n            write_function(file, contents)",
    "docstring": "Save contents into a file. The format name can be specified\n        explicitly or inferred from the file extension."
  },
  {
    "code": "def re_normalize_flux(self, kwargs_ps, norm_factor):\n        for i, model in enumerate(self.point_source_type_list):\n            if model == 'UNLENSED':\n                kwargs_ps[i]['point_amp'] *= norm_factor\n            elif model in ['LENSED_POSITION', 'SOURCE_POSITION']:\n                if self._fixed_magnification_list[i] is True:\n                    kwargs_ps[i]['source_amp'] *= norm_factor\n                else:\n                    kwargs_ps[i]['point_amp'] *= norm_factor\n        return kwargs_ps",
    "docstring": "renormalizes the point source amplitude keywords by a factor\n\n        :param kwargs_ps_updated:\n        :param norm_factor:\n        :return:"
  },
  {
    "code": "def vecs_to_datmesh(x, y):\n    x, y = meshgrid(x, y)\n    out = zeros(x.shape + (2,), dtype=float)\n    out[:, :, 0] = x\n    out[:, :, 1] = y\n    return out",
    "docstring": "Converts input arguments x and y to a 2d meshgrid,\n    suitable for calling Means, Covariances and Realizations."
  },
  {
    "code": "def get_success_url(self):\n        slugs = '+'.join(self.metric_slugs)\n        url = reverse('redis_metric_aggregate_detail', args=[slugs])\n        return url.replace(\"%2B\", \"+\")",
    "docstring": "Reverses the ``redis_metric_aggregate_detail`` URL using\n        ``self.metric_slugs`` as an argument."
  },
  {
    "code": "def _symlink_or_copy_grabix(in_file, out_file, data):\n    if cwlutils.is_cwl_run(data):\n        if utils.file_exists(in_file + \".gbi\"):\n            out_file = in_file\n        else:\n            utils.copy_plus(in_file, out_file)\n    else:\n        utils.symlink_plus(in_file, out_file)\n    return out_file",
    "docstring": "We cannot symlink in CWL, but may be able to use inputs or copy"
  },
  {
    "code": "def _format_count_file(count_file, data):\n    COUNT_COLUMN = 5\n    out_file = os.path.splitext(count_file)[0] + \".fixed.counts\"\n    if file_exists(out_file):\n        return out_file\n    df = pd.io.parsers.read_table(count_file, sep=\"\\t\", index_col=0, header=1)\n    df_sub = df.ix[:, COUNT_COLUMN]\n    with file_transaction(data, out_file) as tx_out_file:\n        df_sub.to_csv(tx_out_file, sep=\"\\t\", index_label=\"id\", header=False)\n    return out_file",
    "docstring": "this cuts the count file produced from featureCounts down to\n    a two column file of gene ids and number of reads mapping to\n    each gene"
  },
  {
    "code": "def filter_by_transcript_expression(\n            self,\n            transcript_expression_dict,\n            min_expression_value=0.0):\n        return self.filter_above_threshold(\n            key_fn=lambda effect: effect.transcript_id,\n            value_dict=transcript_expression_dict,\n            threshold=min_expression_value)",
    "docstring": "Filters effects to those which have an associated transcript whose\n        expression value in the transcript_expression_dict argument is greater\n        than min_expression_value.\n\n        Parameters\n        ----------\n        transcript_expression_dict : dict\n            Dictionary mapping Ensembl transcript IDs to expression estimates\n            (either FPKM or TPM)\n\n        min_expression_value : float\n            Threshold above which we'll keep an effect in the result collection"
  },
  {
    "code": "def back_bfs(self, start, end=None):\n        return [node for node, step in self._iterbfs(start, end, forward=False)]",
    "docstring": "Returns a list of nodes in some backward BFS order.\n\n        Starting from the start node the breadth first search proceeds along\n        incoming edges."
  },
  {
    "code": "def drop_dims(self, drop_dims):\n        if utils.is_scalar(drop_dims):\n            drop_dims = [drop_dims]\n        missing_dimensions = [d for d in drop_dims if d not in self.dims]\n        if missing_dimensions:\n            raise ValueError('Dataset does not contain the dimensions: %s'\n                             % missing_dimensions)\n        drop_vars = set(k for k, v in self._variables.items()\n                        for d in v.dims if d in drop_dims)\n        variables = OrderedDict((k, v) for k, v in self._variables.items()\n                                if k not in drop_vars)\n        coord_names = set(k for k in self._coord_names if k in variables)\n        return self._replace_with_new_dims(variables, coord_names)",
    "docstring": "Drop dimensions and associated variables from this dataset.\n\n        Parameters\n        ----------\n        drop_dims : str or list\n            Dimension or dimensions to drop.\n\n        Returns\n        -------\n        obj : Dataset\n            The dataset without the given dimensions (or any variables\n            containing those dimensions)"
  },
  {
    "code": "def save_sequence_rule_enabler(self, sequence_rule_enabler_form, *args, **kwargs):\n        if sequence_rule_enabler_form.is_for_update():\n            return self.update_sequence_rule_enabler(sequence_rule_enabler_form, *args, **kwargs)\n        else:\n            return self.create_sequence_rule_enabler(sequence_rule_enabler_form, *args, **kwargs)",
    "docstring": "Pass through to provider SequenceRuleEnablerAdminSession.update_sequence_rule_enabler"
  },
  {
    "code": "def _check_periodic(periodic):\n    periodic = np.array(periodic)\n    if len(periodic.shape) == 2:\n        assert periodic.shape[0] == periodic.shape[1], 'periodic shoud be a square matrix or a flat array'\n        return np.diag(periodic)\n    elif len(periodic.shape) == 1:\n        return periodic\n    else:\n        raise ValueError(\"periodic argument can be either a 3x3 matrix or a shape 3 array.\")",
    "docstring": "Validate periodic input"
  },
  {
    "code": "def get_ip_Minv_B(self):\n        if not isinstance(self.M, utils.IdentityLinearOperator):\n            if isinstance(self.Minv, utils.IdentityLinearOperator):\n                raise utils.ArgumentError(\n                    'Minv has to be provided for the evaluation of the inner '\n                    'product that is implicitly defined by M.')\n            if isinstance(self.ip_B, utils.LinearOperator):\n                return self.Minv*self.ip_B\n            else:\n                return lambda x, y: self.ip_B(x, self.Minv*y)\n        return self.ip_B",
    "docstring": "Returns the inner product that is implicitly used with the positive\n        definite preconditioner ``M``."
  },
  {
    "code": "def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id)\n        log.info('Route table %s was reassociated with association id %s',\n                 route_table_id, association_id)\n        return {'replaced': True, 'association_id': association_id}\n    except BotoServerError as e:\n        return {'replaced': False, 'error': __utils__['boto.get_error'](e)}",
    "docstring": "Replaces a route table association.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d'"
  },
  {
    "code": "def super_terms(self):\n        if self.doc and self.doc.super_terms:\n            return self.doc.super_terms\n        return  {k.lower(): v['inheritsfrom'].lower()\n                         for k, v in self._declared_terms.items() if 'inheritsfrom' in v}",
    "docstring": "Return a dictionary mapping term names to their super terms"
  },
  {
    "code": "def delete(self, uri):\n        try:\n            self.connect(uri, method='DELETE')\n            return True\n        except urllib.error.HTTPError:\n            return False",
    "docstring": "Method deletes a Fedora Object in the repository\n\n        Args:\n            uri(str): URI of Fedora Object"
  },
  {
    "code": "def _do_watch_progress(filename, sock, handler):\n    connection, client_address = sock.accept()\n    data = b''\n    try:\n        while True:\n            more_data = connection.recv(16)\n            if not more_data:\n                break\n            data += more_data\n            lines = data.split(b'\\n')\n            for line in lines[:-1]:\n                line = line.decode()\n                parts = line.split('=')\n                key = parts[0] if len(parts) > 0 else None\n                value = parts[1] if len(parts) > 1 else None\n                handler(key, value)\n            data = lines[-1]\n    finally:\n        connection.close()",
    "docstring": "Function to run in a separate gevent greenlet to read progress\n    events from a unix-domain socket."
  },
  {
    "code": "def _assemble_and_send_validation_request(self):\n        return self.client.service.validateShipment(\n                WebAuthenticationDetail=self.WebAuthenticationDetail,\n                ClientDetail=self.ClientDetail,\n                TransactionDetail=self.TransactionDetail,\n                Version=self.VersionId,\n                RequestedShipment=self.RequestedShipment)",
    "docstring": "Fires off the Fedex shipment validation request.\n        \n        @warning: NEVER CALL THIS METHOD DIRECTLY. CALL \n            send_validation_request(), WHICH RESIDES ON FedexBaseService \n            AND IS INHERITED."
  },
  {
    "code": "def query_file(self, path, fetchall=False, **params):\n        if not os.path.exists(path):\n            raise IOError(\"File '{}' not found!\".format(path))\n        if os.path.isdir(path):\n            raise IOError(\"'{}' is a directory!\".format(path))\n        with open(path) as f:\n            query = f.read()\n        return self.query(query=query, fetchall=fetchall, **params)",
    "docstring": "Like Connection.query, but takes a filename to load a query from."
  },
  {
    "code": "def _report_lint_error(error, file_path):\n    line = error[1].line\n    code = error[0]\n    description = error[1].description\n    sys.stdout.write(\"{0}:{1} [{2}] {3}\\n\".format(file_path,\n                                                  line,\n                                                  code,\n                                                  description))",
    "docstring": "Report a linter error."
  },
  {
    "code": "def get_minimum_span(low, high, span):\n    if is_number(low) and low == high:\n        if isinstance(low, np.datetime64):\n            span = span * np.timedelta64(1, 's')\n        low, high = low-span, high+span\n    return low, high",
    "docstring": "If lower and high values are equal ensures they are separated by\n    the defined span."
  },
  {
    "code": "def checkMarkovInputs(self):\n        StateCount = self.MrkvArray[0].shape[0]\n        assert self.Rfree.shape      == (StateCount,),'Rfree not the right shape!'\n        for MrkvArray_t in self.MrkvArray:\n            assert MrkvArray_t.shape  == (StateCount,StateCount),'MrkvArray not the right shape!'\n        for LivPrb_t in self.LivPrb:\n            assert LivPrb_t.shape == (StateCount,),'Array in LivPrb is not the right shape!'\n        for PermGroFac_t in self.LivPrb:\n            assert PermGroFac_t.shape == (StateCount,),'Array in PermGroFac is not the right shape!'\n        for IncomeDstn_t in self.IncomeDstn:\n            assert len(IncomeDstn_t) == StateCount,'List in IncomeDstn is not the right length!'",
    "docstring": "Many parameters used by MarkovConsumerType are arrays.  Make sure those arrays are the\n        right shape.\n\n        Parameters\n        ----------\n        None\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def add_history(self, line):\r\n        u\r\n        if not hasattr(line, \"get_line_text\"):\r\n            line = lineobj.ReadLineTextBuffer(line)\r\n        if not line.get_line_text():\r\n            pass\r\n        elif len(self.history) > 0 and self.history[-1].get_line_text() == line.get_line_text():\r\n            pass\r\n        else:\r\n            self.history.append(line)\r\n        self.history_cursor = len(self.history)",
    "docstring": "u'''Append a line to the history buffer, as if it was the last line typed."
  },
  {
    "code": "def fill_rect(self, rect):\n        check_int_err(lib.SDL_RenderFillRect(self._ptr, rect._ptr))",
    "docstring": "Fill a rectangle on the current rendering target with the drawing color.\n\n        Args:\n            rect (Rect): The destination rectangle, or None to fill the entire rendering target.\n\n        Raises:\n            SDLError: If an error is encountered."
  },
  {
    "code": "def insert(python_data: LdapObject, database: Optional[Database] = None) -> LdapObject:\n    assert isinstance(python_data, LdapObject)\n    table: LdapObjectClass = type(python_data)\n    empty_data = table()\n    changes = changeset(empty_data, python_data.to_dict())\n    return save(changes, database)",
    "docstring": "Insert a new python_data object in the database."
  },
  {
    "code": "def usingCurl():\n    fetcher = getDefaultFetcher()\n    if isinstance(fetcher, ExceptionWrappingFetcher):\n        fetcher = fetcher.fetcher\n    return isinstance(fetcher, CurlHTTPFetcher)",
    "docstring": "Whether the currently set HTTP fetcher is a Curl HTTP fetcher."
  },
  {
    "code": "def command_gen(self, *names):\n        if not names:\n            sys.exit('Please provide generator names')\n        for name in names:\n            name, count = name, 0\n            if ':' in name:\n                name, count = name.split(':', 1)\n            count = int(count)\n            create = self.generators[name]\n            print('Generating `{0}` count={1}'.format(name, count))\n            create(self.session, count)\n            self.session.commit()",
    "docstring": "Runs generator functions.\n\n        Run `docs` generator function::\n\n            ./manage.py sqla:gen docs\n\n        Run `docs` generator function with `count=10`::\n\n            ./manage.py sqla:gen docs:10"
  },
  {
    "code": "def add_parser(self, *args, **kwargs):\n        command_name = args[0]\n        new_kwargs = kwargs.copy()\n        new_kwargs['configman_subparsers_option'] = self._configman_option\n        new_kwargs['subparser_name'] = command_name\n        subparsers = self._configman_option.foreign_data.argparse.subparsers\n        a_subparser = super(ConfigmanSubParsersAction, self).add_parser(\n            *args,\n            **new_kwargs\n        )\n        subparsers[command_name] = DotDict({\n            \"args\": args,\n            \"kwargs\": new_kwargs,\n            \"subparser\": a_subparser\n        })\n        return a_subparser",
    "docstring": "each time a subparser action is used to create a new parser object\n        we must save the original args & kwargs.  In a later phase of\n        configman, we'll need to reproduce the subparsers exactly without\n        resorting to copying.  We save the args & kwargs in the 'foreign_data'\n        section of the configman option that corresponds with the subparser\n        action."
  },
  {
    "code": "def add_field(self, name, label, field_type, *args, **kwargs):\n        if name in self._dyn_fields:\n            raise AttributeError('Field already added to the form.')\n        else:\n            self._dyn_fields[name] = {'label': label, 'type': field_type,\n                                      'args': args, 'kwargs': kwargs}",
    "docstring": "Add the field to the internal configuration dictionary."
  },
  {
    "code": "def start(self, on_exit_callback=None):\n        for service in self.services.keys():\n            self.services[service] = self.services[service]()\n        self.server.start(on_exit_callback)",
    "docstring": "Start the Engel application by initializing all registered services and starting an Autobahn IOLoop.\n\n        :param on_exit_callback: Callback triggered on application exit"
  },
  {
    "code": "def revision(self, message):\n        alembic.command.revision(self.alembic_config(), message=message)",
    "docstring": "Create a new revision file\n\n        :param message:"
  },
  {
    "code": "def _bulk_op(self, record_id_iterator, op_type, index=None, doc_type=None):\n        with self.create_producer() as producer:\n            for rec in record_id_iterator:\n                producer.publish(dict(\n                    id=str(rec),\n                    op=op_type,\n                    index=index,\n                    doc_type=doc_type\n                ))",
    "docstring": "Index record in Elasticsearch asynchronously.\n\n        :param record_id_iterator: Iterator that yields record UUIDs.\n        :param op_type: Indexing operation (one of ``index``, ``create``,\n            ``delete`` or ``update``).\n        :param index: The Elasticsearch index. (Default: ``None``)\n        :param doc_type: The Elasticsearch doc_type. (Default: ``None``)"
  },
  {
    "code": "def create_initial(self, address_values):\n        with self._lock:\n            for add, val in address_values:\n                self._state[add] = _ContextFuture(address=add, result=val)",
    "docstring": "Create futures from inputs with the current value for that address\n        at the start of that context.\n\n        Args:\n            address_values (list of tuple): The tuple is string, bytes of the\n                address and value."
  },
  {
    "code": "def asdict(self):\n        return {\n            \"methods\": {m.name: m.asdict() for m in self.methods},\n            \"protocols\": self.protocols,\n            \"notifications\": {n.name: n.asdict() for n in self.notifications},\n        }",
    "docstring": "Return dict presentation of this service.\n\n        Useful for dumping the device information into JSON."
  },
  {
    "code": "def _setup_master(self):\n        self.broker = mitogen.master.Broker(install_watcher=False)\n        self.router = mitogen.master.Router(\n            broker=self.broker,\n            max_message_size=4096 * 1048576,\n        )\n        self._setup_responder(self.router.responder)\n        mitogen.core.listen(self.broker, 'shutdown', self.on_broker_shutdown)\n        mitogen.core.listen(self.broker, 'exit', self.on_broker_exit)\n        self.listener = mitogen.unix.Listener(\n            router=self.router,\n            path=self.unix_listener_path,\n            backlog=C.DEFAULT_FORKS,\n        )\n        self._enable_router_debug()\n        self._enable_stack_dumps()",
    "docstring": "Construct a Router, Broker, and mitogen.unix listener"
  },
  {
    "code": "def combine_last_two_dimensions(x):\n  x_shape = common_layers.shape_list(x)\n  a, b = x_shape[-2:]\n  return tf.reshape(x, x_shape[:-2] + [a * b])",
    "docstring": "Reshape x so that the last two dimension become one.\n\n  Args:\n    x: a Tensor with shape [..., a, b]\n\n  Returns:\n    a Tensor with shape [..., ab]"
  },
  {
    "code": "def _build_con_add_cmd(ssid: str, security_type: SECURITY_TYPES,\n                       psk: Optional[str], hidden: bool,\n                       eap_args: Optional[Dict[str, Any]]) -> List[str]:\n    configure_cmd = ['connection', 'add',\n                     'save', 'yes',\n                     'autoconnect', 'yes',\n                     'ifname', 'wlan0',\n                     'type', 'wifi',\n                     'con-name', ssid,\n                     'wifi.ssid', ssid]\n    if hidden:\n        configure_cmd += ['wifi.hidden', 'true']\n    if security_type == SECURITY_TYPES.WPA_PSK:\n        configure_cmd += ['wifi-sec.key-mgmt', security_type.value]\n        if psk is None:\n            raise ValueError('wpa-psk security type requires psk')\n        configure_cmd += ['wifi-sec.psk', psk]\n    elif security_type == SECURITY_TYPES.WPA_EAP:\n        if eap_args is None:\n            raise ValueError('wpa-eap security type requires eap_args')\n        configure_cmd += _add_eap_args(eap_args)\n    elif security_type == SECURITY_TYPES.NONE:\n        pass\n    else:\n        raise ValueError(\"Bad security_type {}\".format(security_type))\n    return configure_cmd",
    "docstring": "Build the nmcli connection add command to configure the new network.\n\n    The parameters are the same as configure but without the defaults; this\n    should be called only by configure."
  },
  {
    "code": "def relevant_part(self, original, pos, sep=' '):\n        start = original.rfind(sep, 0, pos) + 1\n        end = original.find(sep, pos - 1)\n        if end == -1:\n            end = len(original)\n        return original[start:end], start, end, pos - start",
    "docstring": "calculates the subword in a `sep`-splitted list of substrings of\n        `original` that `pos` is ia.n"
  },
  {
    "code": "def pad_position_l(self, i):\n        if i >= self.n_pads_l:\n            raise ModelError(\"pad index out-of-bounds\")\n        return (self.length - self.pad_length) / (self.n_pads_l - 1) * i + self.pad_length / 2",
    "docstring": "Determines the position of the ith pad in the length direction.\n        Assumes equally spaced pads.\n\n        :param i: ith number of pad in length direction (0-indexed)\n        :return:"
  },
  {
    "code": "def _handle_command(self, connection, sender, target, command, payload):\n        try:\n            handler = getattr(self, \"cmd_{0}\".format(command))\n        except AttributeError:\n            self.safe_send(connection, target, \"Unknown command: %s\",\n                            command)\n        else:\n            try:\n                logging.info(\"! Handling command: %s\", command)\n                handler(connection, sender, target, payload)\n            except Exception as ex:\n                logging.exception(\"Error calling command handler: %s\", ex)",
    "docstring": "Handles a command, if any"
  },
  {
    "code": "def lifetimes(self, dates, include_start_date, country_codes):\n        if isinstance(country_codes, string_types):\n            raise TypeError(\n                \"Got string {!r} instead of an iterable of strings in \"\n                \"AssetFinder.lifetimes.\".format(country_codes),\n            )\n        country_codes = frozenset(country_codes)\n        lifetimes = self._asset_lifetimes.get(country_codes)\n        if lifetimes is None:\n            self._asset_lifetimes[country_codes] = lifetimes = (\n                self._compute_asset_lifetimes(country_codes)\n            )\n        raw_dates = as_column(dates.asi8)\n        if include_start_date:\n            mask = lifetimes.start <= raw_dates\n        else:\n            mask = lifetimes.start < raw_dates\n        mask &= (raw_dates <= lifetimes.end)\n        return pd.DataFrame(mask, index=dates, columns=lifetimes.sid)",
    "docstring": "Compute a DataFrame representing asset lifetimes for the specified date\n        range.\n\n        Parameters\n        ----------\n        dates : pd.DatetimeIndex\n            The dates for which to compute lifetimes.\n        include_start_date : bool\n            Whether or not to count the asset as alive on its start_date.\n\n            This is useful in a backtesting context where `lifetimes` is being\n            used to signify \"do I have data for this asset as of the morning of\n            this date?\"  For many financial metrics, (e.g. daily close), data\n            isn't available for an asset until the end of the asset's first\n            day.\n        country_codes : iterable[str]\n            The country codes to get lifetimes for.\n\n        Returns\n        -------\n        lifetimes : pd.DataFrame\n            A frame of dtype bool with `dates` as index and an Int64Index of\n            assets as columns.  The value at `lifetimes.loc[date, asset]` will\n            be True iff `asset` existed on `date`.  If `include_start_date` is\n            False, then lifetimes.loc[date, asset] will be false when date ==\n            asset.start_date.\n\n        See Also\n        --------\n        numpy.putmask\n        zipline.pipeline.engine.SimplePipelineEngine._compute_root_mask"
  },
  {
    "code": "def add_external_reference(self,ext_ref):\n        ext_refs_node = self.node.find('externalReferences')\n        if ext_refs_node is None:\n            ext_refs_obj = CexternalReferences()\n            self.node.append(ext_refs_obj.get_node())\n        else:\n            ext_refs_obj = CexternalReferences(ext_refs_node)\n        ext_refs_obj.add_external_reference(ext_ref)",
    "docstring": "Adds an external reference object to the markable\n        @type ext_ref: L{CexternalReference}\n        @param ext_ref: an external reference object"
  },
  {
    "code": "def _check_array(self, X):\n        if isinstance(X, da.Array):\n            if X.ndim == 2 and X.numblocks[1] > 1:\n                logger.debug(\"auto-rechunking 'X'\")\n                if not np.isnan(X.chunks[0]).any():\n                    X = X.rechunk({0: \"auto\", 1: -1})\n                else:\n                    X = X.rechunk({1: -1})\n        return X",
    "docstring": "Validate an array for post-fit tasks.\n\n        Parameters\n        ----------\n        X : Union[Array, DataFrame]\n\n        Returns\n        -------\n        same type as 'X'\n\n        Notes\n        -----\n        The following checks are applied.\n\n        - Ensure that the array is blocked only along the samples."
  },
  {
    "code": "def new_product(self, name):\n        n = self._product_cls(self, name, summary_cls=self._summary_cls)\n        self.graph.add_node(n)\n        self.products.append(n)\n        return n",
    "docstring": "Create a new product.\n\n        Args:\n          name: name of the new product.\n\n        Returns:\n          A new product instance."
  },
  {
    "code": "def delete(network):\n    try:\n        network.destroy()\n    except libvirt.libvirtError as error:\n        raise RuntimeError(\"Unable to destroy network: {}\".format(error))",
    "docstring": "libvirt network cleanup.\n\n    @raise: libvirt.libvirtError."
  },
  {
    "code": "def pull(path, service_names=None):\n    project = __load_project(path)\n    if isinstance(project, dict):\n        return project\n    else:\n        try:\n            project.pull(service_names)\n        except Exception as inst:\n            return __handle_except(inst)\n    return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',\n                                None, None)",
    "docstring": "Pull image for containers in the docker-compose file, service_names is a\n    python list, if omitted pull all images\n\n    path\n        Path where the docker-compose file is stored on the server\n    service_names\n        If specified will pull only the image for the specified services\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion dockercompose.pull /path/where/docker-compose/stored\n        salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'"
  },
  {
    "code": "def load_from_file(module_path):\n    from imp import load_module, PY_SOURCE\n    imported = None\n    if module_path:\n        with open(module_path, 'r') as openfile:\n            imported = load_module('mod', openfile, module_path, ('imported', 'r', PY_SOURCE))\n    return imported",
    "docstring": "Load a python module from its absolute filesystem path\n\n    Borrowed from django-cms"
  },
  {
    "code": "def _get_thumbnail_url(image):\n    lhs, rhs = splitext(image.url)\n    lhs += THUMB_EXT\n    thumb_url = f'{lhs}{rhs}'\n    return thumb_url",
    "docstring": "Given a large image, return the thumbnail url"
  },
  {
    "code": "def number_of_states(dtrajs):\n    r\n    nmax = 0\n    for dtraj in dtrajs:\n        nmax = max(nmax, np.max(dtraj))\n    return nmax + 1",
    "docstring": "r\"\"\"\n    Determine the number of states from a set of discrete trajectories\n\n    Parameters\n    ----------\n    dtrajs : list of int-arrays\n        discrete trajectories"
  },
  {
    "code": "def community(self):\n        return _community.Community(url=self._url + \"/community\",\n                                    securityHandler=self._securityHandler,\n                                    proxy_url=self._proxy_url,\n                                    proxy_port=self._proxy_port)",
    "docstring": "The portal community root covers user and group resources and\n        operations."
  },
  {
    "code": "def wrap_options(self, data, renderer_context):\n        request = renderer_context.get(\"request\", None)\n        method = request and getattr(request, 'method')\n        if method != 'OPTIONS':\n            raise WrapperNotApplicable(\"Request method must be OPTIONS\")\n        wrapper = self.dict_class()\n        wrapper[\"meta\"] = data\n        return wrapper",
    "docstring": "Wrap OPTIONS data as JSON API meta value"
  },
  {
    "code": "def TRUE(classical_reg):\n    warn(\"`TRUE a` has been deprecated. Use `MOVE a 1` instead.\")\n    if isinstance(classical_reg, int):\n        classical_reg = Addr(classical_reg)\n    return MOVE(classical_reg, 1)",
    "docstring": "Produce a TRUE instruction.\n\n    :param classical_reg: A classical register to modify.\n    :return: An instruction object representing the equivalent MOVE."
  },
  {
    "code": "def connect(self, event_handler):\n\t\tcontext = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)\n\t\tif not self.options['verify']:\n\t\t\tcontext.verify_mode = ssl.CERT_NONE\n\t\tscheme = 'wss://'\n\t\tif self.options['scheme'] != 'https':\n\t\t\tscheme = 'ws://'\n\t\t\tcontext = None\n\t\turl = '{scheme:s}{url:s}:{port:s}{basepath:s}/websocket'.format(\n\t\t\tscheme=scheme,\n\t\t\turl=self.options['url'],\n\t\t\tport=str(self.options['port']),\n\t\t\tbasepath=self.options['basepath']\n\t\t)\n\t\twebsocket = yield from websockets.connect(\n\t\t\turl,\n\t\t\tssl=context,\n\t\t)\n\t\tyield from self._authenticate_websocket(websocket, event_handler)\n\t\tyield from self._start_loop(websocket, event_handler)",
    "docstring": "Connect to the websocket and authenticate it.\n\t\tWhen the authentication has finished, start the loop listening for messages,\n\t\tsending a ping to the server to keep the connection alive.\n\n\t\t:param event_handler: Every websocket event will be passed there. Takes one argument.\n\t\t:type event_handler: Function(message)\n\t\t:return:"
  },
  {
    "code": "def run_job(args):\n  jm = setup(args)\n  job_id = int(os.environ['JOB_ID'])\n  array_id = int(os.environ['SGE_TASK_ID']) if os.environ['SGE_TASK_ID'] != 'undefined' else None\n  jm.run_job(job_id, array_id)",
    "docstring": "Starts the wrapper script to execute a job, interpreting the JOB_ID and SGE_TASK_ID keywords that are set by the grid or by us."
  },
  {
    "code": "def watch_statuses(self, observer, batch_ids):\n        with self._lock:\n            statuses = self.get_statuses(batch_ids)\n            if self._has_no_pendings(statuses):\n                observer.notify_batches_finished(statuses)\n            else:\n                self._observers[observer] = statuses",
    "docstring": "Allows a component to register to be notified when a set of\n        batches is no longer PENDING. Expects to be able to call the\n        \"notify_batches_finished\" method on the registered component, sending\n        the statuses of the batches.\n\n        Args:\n            observer (object): Must implement \"notify_batches_finished\" method\n            batch_ids (list of str): The ids of the batches to watch"
  },
  {
    "code": "def results_from_cli(opts, load_samples=True, **kwargs):\n    fp_all = []\n    samples_all = []\n    input_files = opts.input_file\n    if isinstance(input_files, str):\n        input_files = [input_files]\n    for input_file in input_files:\n        logging.info(\"Reading input file %s\", input_file)\n        fp = loadfile(input_file, \"r\")\n        if load_samples:\n            logging.info(\"Loading samples\")\n            file_parameters, ts = _transforms.get_common_cbc_transforms(\n                opts.parameters, fp.variable_params)\n            samples = fp.samples_from_cli(opts, parameters=file_parameters, **kwargs)\n            logging.info(\"Using {} samples\".format(samples.size))\n            samples = _transforms.apply_transforms(samples, ts)\n        else:\n            samples = None\n        if len(input_files) > 1:\n            fp_all.append(fp)\n            samples_all.append(samples)\n        else:\n            fp_all = fp\n            samples_all = samples\n    return fp_all, opts.parameters, opts.parameters_labels, samples_all",
    "docstring": "Loads an inference result file along with any labels associated with it\n    from the command line options.\n\n    Parameters\n    ----------\n    opts : ArgumentParser options\n        The options from the command line.\n    load_samples : bool, optional\n        Load the samples from the file.\n\n    Returns\n    -------\n    fp_all : (list of) BaseInferenceFile type\n        The result file as an hdf file. If more than one input file,\n        then it returns a list.\n    parameters : list of str\n        List of the parameters to use, parsed from the parameters option.\n    labels : dict\n        Dictionary of labels to associate with the parameters.\n    samples_all : (list of) FieldArray(s) or None\n        If load_samples, the samples as a FieldArray; otherwise, None.\n        If more than one input file, then it returns a list.\n    \\**kwargs :\n        Any other keyword arguments that are passed to read samples using\n        samples_from_cli"
  },
  {
    "code": "def set_cookie_prefix(self, cookie_prefix=None):\n        if (cookie_prefix is None):\n            self.cookie_prefix = \"%06d_\" % int(random.random() * 1000000)\n        else:\n            self.cookie_prefix = cookie_prefix",
    "docstring": "Set a random cookie prefix unless one is specified.\n\n        In order to run multiple demonstration auth services on the\n        same server we need to have different cookie names for each\n        auth domain. Unless cookie_prefix is set, generate a random\n        one."
  },
  {
    "code": "def get_linked_properties(cli_ctx, app, resource_group, read_properties=None, write_properties=None):\n    roles = {\n        \"ReadTelemetry\": \"api\",\n        \"WriteAnnotations\": \"annotations\",\n        \"AuthenticateSDKControlChannel\": \"agentconfig\"\n    }\n    sub_id = get_subscription_id(cli_ctx)\n    tmpl = '/subscriptions/{}/resourceGroups/{}/providers/microsoft.insights/components/{}'.format(\n        sub_id,\n        resource_group,\n        app\n    )\n    linked_read_properties, linked_write_properties = [], []\n    if isinstance(read_properties, list):\n        propLen = len(read_properties)\n        linked_read_properties = ['{}/{}'.format(tmpl, roles[read_properties[i]]) for i in range(propLen)]\n    else:\n        linked_read_properties = ['{}/{}'.format(tmpl, roles[read_properties])]\n    if isinstance(write_properties, list):\n        propLen = len(write_properties)\n        linked_write_properties = ['{}/{}'.format(tmpl, roles[write_properties[i]]) for i in range(propLen)]\n    else:\n        linked_write_properties = ['{}/{}'.format(tmpl, roles[write_properties])]\n    return linked_read_properties, linked_write_properties",
    "docstring": "Maps user-facing role names to strings used to identify them on resources."
  },
  {
    "code": "def new_log_filepath(self):\n        lastlog_filename = os.path.join(self.dataflash_dir,'LASTLOG.TXT')\n        if os.path.exists(lastlog_filename) and os.stat(lastlog_filename).st_size != 0:\n            fh = open(lastlog_filename,'rb')\n            log_cnt = int(fh.read()) + 1\n            fh.close()\n        else:\n            log_cnt = 1\n        self.lastlog_file = open(lastlog_filename,'w+b')\n        self.lastlog_file.write(log_cnt.__str__())\n        self.lastlog_file.close()\n        return os.path.join(self.dataflash_dir, '%u.BIN' % (log_cnt,));",
    "docstring": "returns a filepath to a log which does not currently exist and is suitable for DF logging"
  },
  {
    "code": "def get_victoria_day(self, year):\n        may_24th = date(year, 5, 24)\n        shift = may_24th.weekday() or 7\n        victoria_day = may_24th - timedelta(days=shift)\n        return (victoria_day, \"Victoria Day\")",
    "docstring": "Return Victoria Day for Edinburgh.\n\n        Set to the Monday strictly before May 24th. It means that if May 24th\n        is a Monday, it's shifted to the week before."
  },
  {
    "code": "def OnMerge(self, event):\n        with undo.group(_(\"Merge cells\")):\n            self.grid.actions.merge_selected_cells(self.grid.selection)\n        self.grid.ForceRefresh()\n        self.grid.update_attribute_toolbar()",
    "docstring": "Merge cells event handler"
  },
  {
    "code": "def setOverlayDualAnalogTransform(self, ulOverlay, eWhich, fRadius):\n        fn = self.function_table.setOverlayDualAnalogTransform\n        pvCenter = HmdVector2_t()\n        result = fn(ulOverlay, eWhich, byref(pvCenter), fRadius)\n        return result, pvCenter",
    "docstring": "Sets the analog input to Dual Analog coordinate scale for the specified overlay."
  },
  {
    "code": "def asDict( self ):\n        if PY_3:\n            item_fn = self.items\n        else:\n            item_fn = self.iteritems\n        def toItem(obj):\n            if isinstance(obj, ParseResults):\n                if obj.haskeys():\n                    return obj.asDict()\n                else:\n                    return [toItem(v) for v in obj]\n            else:\n                return obj\n        return dict((k,toItem(v)) for k,v in item_fn())",
    "docstring": "Returns the named parse results as a nested dictionary.\n\n        Example::\n\n            integer = Word(nums)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            result = date_str.parseString('12/31/1999')\n            print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})\n\n            result_dict = result.asDict()\n            print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}\n\n            # even though a ParseResults supports dict-like access, sometime you just need to have a dict\n            import json\n            print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable\n            print(json.dumps(result.asDict())) # -> {\"month\": \"31\", \"day\": \"1999\", \"year\": \"12\"}"
  },
  {
    "code": "def status(self):\n\t\ttry:\n\t\t\tpf = file(self.pidfile,'r')\n\t\t\tpid = int(pf.read().strip())\n\t\t\tpf.close()\n\t\texcept IOError:\n\t\t\tpid = None\n\t\tif not pid:\n\t\t\treturn False\n\t\ttry:\n\t\t\treturn os.path.exists(\"/proc/{0}\".format(pid))\n\t\texcept OSError:\n\t\t\treturn False",
    "docstring": "Check if the daemon is currently running.\n\t\tRequires procfs, so it will only work on POSIX compliant OS'."
  },
  {
    "code": "def run_bafRegress(filenames, out_prefix, extract_filename, freq_filename,\n                   options):\n    command = [\n        \"bafRegress.py\",\n        \"estimate\",\n        \"--freqfile\", freq_filename,\n        \"--freqcol\", \"2,5\",\n        \"--extract\", extract_filename,\n        \"--colsample\", options.colsample,\n        \"--colmarker\", options.colmarker,\n        \"--colbaf\", options.colbaf,\n        \"--colab1\", options.colab1,\n        \"--colab2\", options.colab2,\n    ]\n    command.extend(filenames)\n    output = None\n    try:\n        output = subprocess.check_output(command, stderr=subprocess.STDOUT,\n                                         shell=False)\n    except subprocess.CalledProcessError as exc:\n        raise ProgramError(\"bafRegress.py: couldn't run \"\n                           \"bafRegress.py\\n{}\".format(exc.output))\n    try:\n        with open(out_prefix + \".bafRegress\", \"w\") as o_file:\n            o_file.write(output)\n    except IOError:\n        raise ProgramError(\"{}: cannot write file\".format(\n            out_prefix + \".bafRegress\",\n        ))",
    "docstring": "Runs the bafRegress function.\n\n    :param filenames: the set of all sample files.\n    :param out_prefix: the output prefix.\n    :param extract_filename: the name of the markers to extract.\n    :param freq_filename: the name of the file containing the frequency.\n    :param options: the other options.\n\n    :type filenames: set\n    :type out_prefix: str\n    :type extract_filename: str\n    :type freq_filename: str\n    :type options: argparse.Namespace"
  },
  {
    "code": "def next_frame_savp():\n  hparams = sv2p_params.next_frame_sv2p()\n  hparams.add_hparam(\"z_dim\", 8)\n  hparams.add_hparam(\"num_discriminator_filters\", 32)\n  hparams.add_hparam(\"use_vae\", True)\n  hparams.add_hparam(\"use_gan\", False)\n  hparams.add_hparam(\"use_spectral_norm\", True)\n  hparams.add_hparam(\"gan_loss\", \"cross_entropy\")\n  hparams.add_hparam(\"gan_loss_multiplier\", 0.01)\n  hparams.add_hparam(\"gan_vae_loss_multiplier\", 0.01)\n  hparams.add_hparam(\"gan_optimization\", \"joint\")\n  hparams.bottom = {\n      \"inputs\": modalities.video_raw_bottom,\n      \"targets\": modalities.video_raw_targets_bottom,\n  }\n  hparams.loss = {\n      \"targets\": modalities.video_l1_raw_loss,\n  }\n  hparams.top = {\n      \"targets\": modalities.video_raw_top,\n  }\n  hparams.latent_loss_multiplier_schedule = \"linear\"\n  hparams.upsample_method = \"bilinear_upsample_conv\"\n  hparams.internal_loss = False\n  hparams.reward_prediction = False\n  hparams.anneal_end = 100000\n  hparams.num_iterations_1st_stage = 0\n  hparams.num_iterations_2nd_stage = 50000\n  return hparams",
    "docstring": "SAVP model hparams."
  },
  {
    "code": "def _open_ds_from_store(fname, store_mod=None, store_cls=None, **kwargs):\n    if isinstance(fname, xr.Dataset):\n        return fname\n    if not isstring(fname):\n        try:\n            fname[0]\n        except TypeError:\n            pass\n        else:\n            if store_mod is not None and store_cls is not None:\n                if isstring(store_mod):\n                    store_mod = repeat(store_mod)\n                if isstring(store_cls):\n                    store_cls = repeat(store_cls)\n                fname = [_open_store(sm, sc, f)\n                         for sm, sc, f in zip(store_mod, store_cls, fname)]\n                kwargs['engine'] = None\n                kwargs['lock'] = False\n                return open_mfdataset(fname, **kwargs)\n    if store_mod is not None and store_cls is not None:\n        fname = _open_store(store_mod, store_cls, fname)\n    return open_dataset(fname, **kwargs)",
    "docstring": "Open a dataset and return it"
  },
  {
    "code": "def _ParsePage(self, parser_mediator, file_offset, page_data):\n    page_header_map = self._GetDataTypeMap('binarycookies_page_header')\n    try:\n      page_header = self._ReadStructureFromByteStream(\n          page_data, file_offset, page_header_map)\n    except (ValueError, errors.ParseError) as exception:\n      raise errors.ParseError((\n          'Unable to map page header data at offset: 0x{0:08x} with error: '\n          '{1!s}').format(file_offset, exception))\n    for record_offset in page_header.offsets:\n      if parser_mediator.abort:\n        break\n      self._ParseRecord(parser_mediator, page_data, record_offset)",
    "docstring": "Parses a page.\n\n    Args:\n      parser_mediator (ParserMediator): parser mediator.\n      file_offset (int): offset of the data relative from the start of\n          the file-like object.\n      page_data (bytes): page data.\n\n    Raises:\n      ParseError: when the page cannot be parsed."
  },
  {
    "code": "def make_action(self, fn, schema_parser, meta):\n        validate_input = validate_output = None\n        if \"$input\" in meta:\n            with MarkKey(\"$input\"):\n                validate_input = schema_parser.parse(meta[\"$input\"])\n        if \"$output\" in meta:\n            with MarkKey(\"$output\"):\n                validate_output = schema_parser.parse(meta[\"$output\"])\n        def action(data):\n            if validate_input:\n                try:\n                    data = validate_input(data)\n                except Invalid as ex:\n                    return abort(400, \"InvalidData\", str(ex))\n                if isinstance(data, dict):\n                    rv = fn(**data)\n                else:\n                    rv = fn(data)\n            else:\n                rv = fn()\n            rv, status, headers = unpack(rv)\n            if validate_output:\n                try:\n                    rv = validate_output(rv)\n                except Invalid as ex:\n                    return abort(500, \"ServerError\", str(ex))\n            return rv, status, headers\n        return action",
    "docstring": "Make resource's method an action\n\n        Validate input, output by schema in meta.\n        If no input schema, call fn without params.\n        If no output schema, will not validate return value.\n\n        Args:\n            fn: resource's method\n            schema_parser: for parsing schema in meta\n            meta: meta data of the action"
  },
  {
    "code": "def _tag_ec2(self, conn, role):\n        tags = {'Role': role}\n        conn.create_tags([self.instance_id], tags)",
    "docstring": "tag the current EC2 instance with a cluster role"
  },
  {
    "code": "def set_plain_text_font(self, font, color_scheme=None):\r\n        self.plain_text.set_font(font, color_scheme=color_scheme)",
    "docstring": "Set plain text mode font"
  },
  {
    "code": "def ngram_count(self, ngram):\n        query = \"SELECT count FROM _{0}_gram\".format(len(ngram))\n        query += self._build_where_clause(ngram)\n        query += \";\"\n        result = self.execute_sql(query)\n        return self._extract_first_integer(result)",
    "docstring": "Gets the count for a given ngram from the database.\n\n        Parameters\n        ----------\n        ngram : iterable of str\n            A list, set or tuple of strings.\n\n        Returns\n        -------\n        count : int\n            The count of the ngram."
  },
  {
    "code": "def detectIphoneOrIpod(self):\n        return UAgentInfo.deviceIphone in self.__userAgent \\\n            or UAgentInfo.deviceIpod in self.__userAgent",
    "docstring": "Return detection of an iPhone or iPod Touch\n\n        Detects if the current device is an iPhone or iPod Touch."
  },
  {
    "code": "def _encode_regex(name, value, dummy0, dummy1):\n    flags = value.flags\n    if flags == 0:\n        return b\"\\x0B\" + name + _make_c_string_check(value.pattern) + b\"\\x00\"\n    elif flags == re.UNICODE:\n        return b\"\\x0B\" + name + _make_c_string_check(value.pattern) + b\"u\\x00\"\n    else:\n        sflags = b\"\"\n        if flags & re.IGNORECASE:\n            sflags += b\"i\"\n        if flags & re.LOCALE:\n            sflags += b\"l\"\n        if flags & re.MULTILINE:\n            sflags += b\"m\"\n        if flags & re.DOTALL:\n            sflags += b\"s\"\n        if flags & re.UNICODE:\n            sflags += b\"u\"\n        if flags & re.VERBOSE:\n            sflags += b\"x\"\n        sflags += b\"\\x00\"\n        return b\"\\x0B\" + name + _make_c_string_check(value.pattern) + sflags",
    "docstring": "Encode a python regex or bson.regex.Regex."
  },
  {
    "code": "def get_camera_imageseries(self, number_of_imageseries=10, offset=0):\n        response = None\n        try:\n            response = requests.get(\n                urls.get_imageseries(self._giid),\n                headers={\n                    'Accept': 'application/json, text/javascript, */*; q=0.01',\n                    'Cookie': 'vid={}'.format(self._vid)},\n                params={\n                    \"numberOfImageSeries\": int(number_of_imageseries),\n                    \"offset\": int(offset),\n                    \"fromDate\": \"\",\n                    \"toDate\": \"\",\n                    \"onlyNotViewed\": \"\",\n                    \"_\": self._giid})\n        except requests.exceptions.RequestException as ex:\n            raise RequestError(ex)\n        _validate_response(response)\n        return json.loads(response.text)",
    "docstring": "Get smartcam image series\n\n        Args:\n            number_of_imageseries (int): number of image series to get\n            offset (int): skip offset amount of image series"
  },
  {
    "code": "def json_requested():\n    best = request.accept_mimetypes.best_match(\n        ['application/json', 'text/html'])\n    return (best == 'application/json' and\n            request.accept_mimetypes[best] >\n            request.accept_mimetypes['text/html'])",
    "docstring": "Check if json is the preferred output format for the request."
  },
  {
    "code": "def to_ubyte_array(barray):\n    bs = (ctypes.c_ubyte * len(barray))()\n    pack_into('%ds' % len(barray), bs, 0, barray)\n    return bs",
    "docstring": "Returns a c_ubyte_array filled with the given data of a bytearray or bytes"
  },
  {
    "code": "def subtract_days(self, days: int) -> datetime:\n        self.value = self.value - relativedelta(days=days)\n        return self.value",
    "docstring": "Subtracts dates from the given value"
  },
  {
    "code": "def switch_state(context, ain):\n    context.obj.login()\n    actor = context.obj.get_actor_by_ain(ain)\n    if actor:\n        click.echo(\"State for {} is: {}\".format(ain,'ON' if actor.get_state() else 'OFF'))\n    else:\n        click.echo(\"Actor not found: {}\".format(ain))",
    "docstring": "Get an actor's power state"
  },
  {
    "code": "def joinMeiUyir(mei_char, uyir_char):\n    if not mei_char: return uyir_char\n    if not uyir_char: return mei_char\n    if not isinstance(mei_char, PYTHON3 and str or unicode):\n        raise ValueError(u\"Passed input mei character '%s' must be unicode, not just string\" % mei_char)\n    if not isinstance(uyir_char, PYTHON3 and str or unicode) and uyir_char != None:\n        raise ValueError(u\"Passed input uyir character '%s' must be unicode, not just string\" % uyir_char)\n    if mei_char not in grantha_mei_letters:\n        raise ValueError(u\"Passed input character '%s' is not a tamil mei character\" % mei_char)\n    if uyir_char not in uyir_letters:\n        raise ValueError(u\"Passed input character '%s' is not a tamil uyir character\" % uyir_char)\n    if uyir_char:\n        uyiridx = uyir_letters.index(uyir_char)\n    else:\n        return mei_char\n    meiidx = grantha_mei_letters.index(mei_char)\n    uyirmeiidx = meiidx*12 + uyiridx\n    return grantha_uyirmei_letters[uyirmeiidx]",
    "docstring": "This function join mei character and uyir character, and retuns as\n    compound uyirmei unicode character.\n\n    Inputs:\n        mei_char : It must be unicode tamil mei char.\n        uyir_char : It must be unicode tamil uyir char.\n\n    Written By : Arulalan.T\n    Date : 22.09.2014"
  },
  {
    "code": "def _get_secret_with_context(\n    filename,\n    secret,\n    plugin_settings,\n    lines_of_context=5,\n    force=False,\n):\n    snippet = CodeSnippetHighlighter().get_code_snippet(\n        filename,\n        secret['line_number'],\n        lines_of_context=lines_of_context,\n    )\n    try:\n        raw_secret_value = get_raw_secret_value(\n            snippet.target_line,\n            secret,\n            plugin_settings,\n            filename,\n        )\n        snippet.highlight_line(raw_secret_value)\n    except SecretNotFoundOnSpecifiedLineError:\n        if not force:\n            raise\n        snippet.target_line = colorize(\n            snippet.target_line,\n            AnsiColor.BOLD,\n        )\n    return snippet.add_line_numbers()",
    "docstring": "Displays the secret, with surrounding lines of code for better context.\n\n    :type filename: str\n    :param filename: filename where secret resides in\n\n    :type secret: dict, PotentialSecret.json() format\n    :param secret: the secret listed in baseline\n\n    :type plugin_settings: list\n    :param plugin_settings: plugins used to create baseline.\n\n    :type lines_of_context: int\n    :param lines_of_context: number of lines displayed before and after\n        secret.\n\n    :type force: bool\n    :param force: if True, will print the lines of code even if it doesn't\n        find the secret expected\n\n    :raises: SecretNotFoundOnSpecifiedLineError"
  },
  {
    "code": "def _get_registry_auth(registry_url, config_path):\n        username = None\n        password = None\n        try:\n            docker_config = json.load(open(config_path))\n        except ValueError:\n            return username, password\n        if docker_config.get('auths'):\n            docker_config = docker_config['auths']\n        auth_key = docker_config.get(registry_url, {}).get('auth', None)\n        if auth_key:\n            username, password = base64.b64decode(auth_key).split(':', 1)\n        return username, password",
    "docstring": "Retrieve from the config file the current authentication for a given URL, and\n        return the username, password"
  },
  {
    "code": "def source_range_slices(start, end, nr_var_dict):\n    return OrderedDict((k, slice(s,e,1))\n        for k, (s, e)\n        in source_range_tuple(start, end, nr_var_dict).iteritems())",
    "docstring": "Given a range of source numbers, as well as a dictionary\n    containing the numbers of each source, returns a dictionary\n    containing slices for each source variable type."
  },
  {
    "code": "def _get_stddevs(self, coeffs, stddev_types, num_sites):\n        stddevs = []\n        for stddev_type in stddev_types:\n            assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n            stddevs.append(coeffs['sigma'] + np.zeros(num_sites))\n        return np.array(stddevs)",
    "docstring": "Return total sigma as reported in Table 2, p. 1202."
  },
  {
    "code": "def state(self, value):\n        if value.upper() == ON:\n            return self.SOAPAction('SetSocketSettings', 'SetSocketSettingsResult', self.controlParameters(\"1\", \"true\"))\n        elif value.upper() == OFF:\n            return self.SOAPAction('SetSocketSettings', 'SetSocketSettingsResult', self.controlParameters(\"1\", \"false\"))\n        else:\n            raise TypeError(\"State %s is not valid.\" % str(value))",
    "docstring": "Set device state.\n\n        :type value: str\n        :param value: Future state (either ON or OFF)"
  },
  {
    "code": "def _fast_write(self, outfile, value):\n        outfile.truncate(0)\n        outfile.write(str(int(value)))\n        outfile.flush()",
    "docstring": "Function for fast writing to motor files."
  },
  {
    "code": "def retrieveAcknowledge():\n    a = TpPd(pd=0x3)\n    b = MessageType(mesType=0x1d)\n    packet = a / b\n    return packet",
    "docstring": "RETRIEVE ACKNOWLEDGE Section 9.3.21"
  },
  {
    "code": "def uuid_constructor(loader, node):\n    value = loader.construct_scalar(node)\n    return uuid.UUID(value)",
    "docstring": "Construct a uuid.UUID object form a scalar YAML node.\n\n    Tests:\n        >>> yaml.add_constructor(\"!uuid\", uuid_constructor, Loader=yaml.SafeLoader)\n        >>> yaml.safe_load(\"{'test': !uuid 'cc3702ca-699a-4aa6-8226-4c938f294d9b'}\")\n        {'test': UUID('cc3702ca-699a-4aa6-8226-4c938f294d9b')}"
  },
  {
    "code": "def _check(user, topic):\n    if topic['export_control']:\n        product = v1_utils.verify_existence_and_get(topic['product_id'],\n                                                    models.PRODUCTS)\n        return (user.is_in_team(product['team_id']) or\n                product['team_id'] in user.parent_teams_ids)\n    return False",
    "docstring": "If the topic has it's export_control set to True then all the teams\n    under the product team can access to the topic's resources.\n\n    :param user:\n    :param topic:\n    :return: True if check is ok, False otherwise"
  },
  {
    "code": "def status(self):\n        if not self.created:\n            return None\n        self.inner().reload()\n        return self.inner().status",
    "docstring": "Get the container's current status from Docker.\n\n        If the container does not exist (before creation and after removal),\n        the status is ``None``."
  },
  {
    "code": "def _create_pax_generic_header(cls, pax_headers, type=tarfile.XHDTYPE):\n    records = []\n    for keyword, value in pax_headers.iteritems():\n        try:\n            keyword = keyword.encode(\"utf8\")\n        except Exception:\n            pass\n        try:\n            value = value.encode(\"utf8\")\n        except Exception:\n            pass\n        l = len(keyword) + len(value) + 3\n        n = p = 0\n        while True:\n            n = l + len(str(p))\n            if n == p:\n                break\n            p = n\n        records.append(\"%d %s=%s\\n\" % (p, keyword, value))\n    records = \"\".join(records)\n    info = {}\n    info[\"name\"] = \"././@PaxHeader\"\n    info[\"type\"] = type\n    info[\"size\"] = len(records)\n    info[\"magic\"] = tarfile.POSIX_MAGIC\n    return cls._create_header(info, tarfile.USTAR_FORMAT) + \\\n        cls._create_payload(records)",
    "docstring": "Return a POSIX.1-2001 extended or global header sequence\n       that contains a list of keyword, value pairs. The values\n       must be unicode objects."
  },
  {
    "code": "def _best_res_pixels(self):\n        factor = 2 * (AbstractMOC.HPY_MAX_NORDER - self.max_order)\n        pix_l = []\n        for iv in self._interval_set._intervals:\n            for val in range(iv[0] >> factor, iv[1] >> factor):\n                pix_l.append(val)\n        return np.asarray(pix_l)",
    "docstring": "Returns a numpy array of all the HEALPix indexes contained in the MOC at its max order.\n\n        Returns\n        -------\n        result : `~numpy.ndarray`\n            The array of HEALPix at ``max_order``"
  },
  {
    "code": "def colors(self, value):\n        if isinstance(value, str):\n            from .palettes import PALETTES\n            if value not in PALETTES:\n                raise YellowbrickValueError(\n                    \"'{}' is not a registered color palette\".format(value)\n                )\n            self._colors = copy(PALETTES[value])\n        elif isinstance(value, list):\n            self._colors = value\n        else:\n            self._colors = list(value)",
    "docstring": "Converts color strings into a color listing."
  },
  {
    "code": "def dr( self, cell_lengths ):\n        half_cell_lengths = cell_lengths / 2.0\n        this_dr = self.final_site.r - self.initial_site.r\n        for i in range( 3 ):\n            if this_dr[ i ] > half_cell_lengths[ i ]:\n                this_dr[ i ] -= cell_lengths[ i ]\n            if this_dr[ i ] < -half_cell_lengths[ i ]:\n                this_dr[ i ] += cell_lengths[ i ]\n        return this_dr",
    "docstring": "Particle displacement vector for this jump\n\n        Args:\n            cell_lengths (np.array(x,y,z)): Cell lengths for the orthogonal simulation cell.\n\n        Returns\n            (np.array(x,y,z)): dr"
  },
  {
    "code": "def ask_bool(question: str, default: bool = True) -> bool:\n    default_q = \"Y/n\" if default else \"y/N\"\n    answer = input(\"{0} [{1}]: \".format(question, default_q))\n    lower = answer.lower()\n    if not lower:\n        return default\n    return lower == \"y\"",
    "docstring": "Asks a question yes no style"
  },
  {
    "code": "def collections(self):\n        iterator = self._firestore_api.list_collection_ids(\n            self._database_string, metadata=self._rpc_metadata\n        )\n        iterator.client = self\n        iterator.item_to_value = _item_to_collection_ref\n        return iterator",
    "docstring": "List top-level collections of the client's database.\n\n        Returns:\n            Sequence[~.firestore_v1beta1.collection.CollectionReference]:\n                iterator of subcollections of the current document."
  },
  {
    "code": "def get_parent_ids(self):\n        id_list = []\n        from ..id.objects import IdList\n        for parent_node in self._my_map['parentNodes']:\n            id_list.append(str(parent_node.ident))\n        return IdList(id_list)",
    "docstring": "Gets the parents of this node.\n\n        return: (osid.id.IdList) - the parents of this node\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def ping(self):\n        self.last_ping = time.time()\n        try:\n            self.send_message({MESSAGE_TYPE: TYPE_PING})\n        except NotConnected:\n            self._socket_client.logger.error(\"Chromecast is disconnected. \" +\n                                             \"Cannot ping until reconnected.\")",
    "docstring": "Send a ping message."
  },
  {
    "code": "def _is_nmrstar(string):\n        if (string[0:5] == u\"data_\" and u\"save_\" in string) or (string[0:5] == b\"data_\" and b\"save_\" in string):\n            return string\n        return False",
    "docstring": "Test if input string is in NMR-STAR format.\n\n        :param string: Input string.\n        :type string: :py:class:`str` or :py:class:`bytes`\n        :return: Input string if in NMR-STAR format or False otherwise.\n        :rtype: :py:class:`str` or :py:obj:`False`"
  },
  {
    "code": "def pdf(self, mu):\n        if self.transform is not None:\n            mu = self.transform(mu)                \n        return ss.expon.pdf(mu, self.lmd0)",
    "docstring": "PDF for Exponential prior\n\n        Parameters\n        ----------\n        mu : float\n            Latent variable for which the prior is being formed over\n\n        Returns\n        ----------\n        - p(mu)"
  },
  {
    "code": "def get_data_for_notifications(self, contact, notif, host_ref):\n        if not host_ref:\n            return [self, contact, notif]\n        return [host_ref, self, contact, notif]",
    "docstring": "Get data for a notification\n\n        :param contact: The contact to return\n        :type contact:\n        :param notif: the notification to return\n        :type notif:\n        :return: list containing the service, the host and the given parameters\n        :rtype: list"
  },
  {
    "code": "def owner(self, owner):\n        if owner is None:\n            raise ValueError(\"Invalid value for `owner`, must not be `None`\")\n        if owner is not None and not re.search('[a-z0-9](?:-(?!-)|[a-z0-9])+[a-z0-9]', owner):\n            raise ValueError(\"Invalid value for `owner`, must be a follow pattern or equal to `/[a-z0-9](?:-(?!-)|[a-z0-9])+[a-z0-9]/`\")\n        self._owner = owner",
    "docstring": "Sets the owner of this LinkedDatasetCreateOrUpdateRequest.\n        User name and unique identifier of the creator of the dataset.\n\n        :param owner: The owner of this LinkedDatasetCreateOrUpdateRequest.\n        :type: str"
  },
  {
    "code": "def visit_classdef(self, node, parent, newstyle=None):\n        node, doc = self._get_doc(node)\n        newnode = nodes.ClassDef(node.name, doc, node.lineno, node.col_offset, parent)\n        metaclass = None\n        if PY3:\n            for keyword in node.keywords:\n                if keyword.arg == \"metaclass\":\n                    metaclass = self.visit(keyword, newnode).value\n                    break\n        if node.decorator_list:\n            decorators = self.visit_decorators(node, newnode)\n        else:\n            decorators = None\n        newnode.postinit(\n            [self.visit(child, newnode) for child in node.bases],\n            [self.visit(child, newnode) for child in node.body],\n            decorators,\n            newstyle,\n            metaclass,\n            [\n                self.visit(kwd, newnode)\n                for kwd in node.keywords\n                if kwd.arg != \"metaclass\"\n            ]\n            if PY3\n            else [],\n        )\n        return newnode",
    "docstring": "visit a ClassDef node to become astroid"
  },
  {
    "code": "def _get_config_files():\n    config_paths = []\n    if os.environ.get('FEDMSG_CONFIG'):\n        config_location = os.environ['FEDMSG_CONFIG']\n    else:\n        config_location = '/etc/fedmsg.d'\n    if os.path.isfile(config_location):\n        config_paths.append(config_location)\n    elif os.path.isdir(config_location):\n        possible_config_files = [os.path.join(config_location, p)\n                                 for p in os.listdir(config_location) if p.endswith('.py')]\n        for p in possible_config_files:\n            if os.path.isfile(p):\n                config_paths.append(p)\n    if not config_paths:\n        _log.info('No configuration files found in %s', config_location)\n    return config_paths",
    "docstring": "Load the list of file paths for fedmsg configuration files.\n\n    Returns:\n        list: List of files containing fedmsg configuration."
  },
  {
    "code": "def _get_cache_plus_key(self):\n        key = getattr(self, '_cache_key', self.key_from_query())\n        return self._cache.cache, key",
    "docstring": "Return a cache region plus key."
  },
  {
    "code": "def tomorrow(date=None):\n    if not date:\n        return _date + datetime.timedelta(days=1)\n    else:\n        current_date = parse(date)\n        return current_date + datetime.timedelta(days=1)",
    "docstring": "tomorrow is another day"
  },
  {
    "code": "def add_account_to_group(self, account, group):\n        lgroup: OpenldapGroup = self._get_group(group.name)\n        person: OpenldapAccount = self._get_account(account.username)\n        changes = changeset(lgroup, {})\n        changes = lgroup.add_member(changes, person)\n        save(changes, database=self._database)",
    "docstring": "Add account to group."
  },
  {
    "code": "def calc_observable_fraction(self,distance_modulus):\n        observable_fraction = self.isochrone.observableFraction(self.mask,distance_modulus)\n        if not observable_fraction.sum() > 0:\n            msg = \"No observable fraction\"\n            msg += (\"\\n\"+str(self.source.params))\n            logger.error(msg)\n            raise ValueError(msg)\n        return observable_fraction",
    "docstring": "Calculated observable fraction within each pixel of the target region."
  },
  {
    "code": "def _guess_vc(self):\n        if self.vc_ver <= 14.0:\n            return\n        default = r'VC\\Tools\\MSVC'\n        guess_vc = os.path.join(self.VSInstallDir, default)\n        try:\n            vc_exact_ver = os.listdir(guess_vc)[-1]\n            return os.path.join(guess_vc, vc_exact_ver)\n        except (OSError, IOError, IndexError):\n            pass",
    "docstring": "Locate Visual C for 2017"
  },
  {
    "code": "def create_client(addr, port):\n    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    sock.connect_ex((addr, port))\n    spin = Spin(sock)\n    Client(spin)\n    spin.add_map(CONNECT, install_basic_handles)\n    spin.add_map(CONNECT_ERR, lambda con, err: lose(con))\n    return spin",
    "docstring": "Set up a TCP client and installs the basic handles Stdin, Stdout.\n\n    def send_data(client):\n        client.dump('GET / HTTP/1.1\\r\\n')\n        xmap(client, LOAD, iostd.put)\n\n    client = create_client('www.google.com.br', 80)\n    xmap(client, CONNECT, send_data)"
  },
  {
    "code": "def rustcall(func, *args):\n    lib.semaphore_err_clear()\n    rv = func(*args)\n    err = lib.semaphore_err_get_last_code()\n    if not err:\n        return rv\n    msg = lib.semaphore_err_get_last_message()\n    cls = exceptions_by_code.get(err, SemaphoreError)\n    exc = cls(decode_str(msg))\n    backtrace = decode_str(lib.semaphore_err_get_backtrace())\n    if backtrace:\n        exc.rust_info = backtrace\n    raise exc",
    "docstring": "Calls rust method and does some error handling."
  },
  {
    "code": "def generate_json_docs(module, pretty_print=False, user=None):\n    indent = None\n    separators = (',', ':')\n    if pretty_print:\n        indent = 4\n        separators = (',', ': ')\n    module_doc_dict = generate_doc_dict(module, user)\n    json_str = json.dumps(module_doc_dict,\n            indent=indent,\n            separators=separators)\n    return json_str",
    "docstring": "Return a JSON string format of a Pale module's documentation.\n\n    This string can either be printed out, written to a file, or piped to some\n    other tool.\n\n    This method is a shorthand for calling `generate_doc_dict` and passing\n    it into a json serializer.\n\n    The user argument is optional. If included, it expects the user to be an object with an \"is_admin\"\n    boolean attribute. Any endpoint protected with a \"@requires_permission\" decorator will require\n    user.is_admin == True to display documentation on that endpoint."
  },
  {
    "code": "def error(self, error):\n        if self.direction not in ['x', 'y', 'z'] and error is not None:\n            raise ValueError(\"error only accepted for x, y, z dimensions\")\n        if isinstance(error, u.Quantity):\n            error = error.to(self.unit).value\n        self._error = error",
    "docstring": "set the error"
  },
  {
    "code": "def prettify(amount, separator=','):\n    orig = str(amount)\n    new = re.sub(\"^(-?\\d+)(\\d{3})\", \"\\g<1>{0}\\g<2>\".format(separator), str(amount))\n    if orig == new:\n        return new\n    else:\n        return prettify(new)",
    "docstring": "Separate with predefined separator."
  },
  {
    "code": "def expand(self):\n        if self.slurm:\n            self._introspect_slurm_cluster()\n        self.network.nodes = self._expand_nodes(self.network.nodes)\n        self._expand_tags()",
    "docstring": "Perform node expansion of network section."
  },
  {
    "code": "def timezone(self, value):\n        self._timezone = (value if isinstance(value, datetime.tzinfo)\n                          else tz.gettz(value))",
    "docstring": "Set the timezone."
  },
  {
    "code": "def get_device_model(self) -> str:\n        output, _ = self._execute(\n            '-s', self.device_sn, 'shell', 'getprop', 'ro.product.model')\n        return output.strip()",
    "docstring": "Show device model."
  },
  {
    "code": "def validate(self):\n        has_more_nodes = True\n        visited = set()\n        to_visit = [self]\n        index = 0\n        while has_more_nodes:\n            has_more_nodes = False\n            next_nodes = []\n            for node in to_visit:\n                if node is None:\n                    next_nodes.extend((None, None))\n                else:\n                    if node in visited:\n                        raise NodeReferenceError(\n                            'cyclic node reference at index {}'.format(index))\n                    if not isinstance(node, Node):\n                        raise NodeTypeError(\n                            'invalid node instance at index {}'.format(index))\n                    if not isinstance(node.value, numbers.Number):\n                        raise NodeValueError(\n                            'invalid node value at index {}'.format(index))\n                    if node.left is not None or node.right is not None:\n                        has_more_nodes = True\n                    visited.add(node)\n                    next_nodes.extend((node.left, node.right))\n                index += 1\n            to_visit = next_nodes",
    "docstring": "Check if the binary tree is malformed.\n\n        :raise binarytree.exceptions.NodeReferenceError: If there is a\n            cyclic reference to a node in the binary tree.\n        :raise binarytree.exceptions.NodeTypeError: If a node is not an\n            instance of :class:`binarytree.Node`.\n        :raise binarytree.exceptions.NodeValueError: If a node value is not a\n            number (e.g. int, float).\n\n        **Example**:\n\n        .. doctest::\n\n            >>> from binarytree import Node\n            >>>\n            >>> root = Node(1)\n            >>> root.left = Node(2)\n            >>> root.right = root  # Cyclic reference to root\n            >>>\n            >>> root.validate()  # doctest: +IGNORE_EXCEPTION_DETAIL\n            Traceback (most recent call last):\n             ...\n            NodeReferenceError: cyclic node reference at index 0"
  },
  {
    "code": "async def parse_get_revoc_reg_response(get_revoc_reg_response: str) -> (str, str, int):\n    logger = logging.getLogger(__name__)\n    logger.debug(\"parse_get_revoc_reg_response: >>> get_revoc_reg_response: %r\", get_revoc_reg_response)\n    if not hasattr(parse_get_revoc_reg_response, \"cb\"):\n        logger.debug(\"parse_get_revoc_reg_response: Creating callback\")\n        parse_get_revoc_reg_response.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_char_p, c_char_p, c_uint64))\n    c_get_revoc_reg_response = c_char_p(get_revoc_reg_response.encode('utf-8'))\n    (revoc_reg_def_id, revoc_reg_json, timestamp) = await do_call('indy_parse_get_revoc_reg_response',\n                                                                  c_get_revoc_reg_response,\n                                                                  parse_get_revoc_reg_response.cb)\n    res = (revoc_reg_def_id.decode(), revoc_reg_json.decode(), timestamp)\n    logger.debug(\"parse_get_revoc_reg_response: <<< res: %r\", res)\n    return res",
    "docstring": "Parse a GET_REVOC_REG response to get Revocation Registry in the format compatible with Anoncreds API.\n\n    :param get_revoc_reg_response: response of GET_REVOC_REG request.\n    :return: Revocation Registry Definition Id, Revocation Registry json and Timestamp.\n      {\n          \"value\": Registry-specific data {\n              \"accum\": string - current accumulator value.\n          },\n          \"ver\": string - version revocation registry json\n      }"
  },
  {
    "code": "def _write(self, session, openFile, replaceParamFile):\n        openFile.write('GRIDPIPEFILE\\n')\n        openFile.write('PIPECELLS %s\\n' % self.pipeCells)\n        for cell in self.gridPipeCells:\n            openFile.write('CELLIJ    %s  %s\\n' % (cell.cellI, cell.cellJ))\n            openFile.write('NUMPIPES  %s\\n' % cell.numPipes)\n            for node in cell.gridPipeNodes:\n                openFile.write('SPIPE     %s  %s  %.6f\\n' % (\n                    node.linkNumber,\n                    node.nodeNumber,\n                    node.fractPipeLength))",
    "docstring": "Grid Pipe File Write to File Method"
  },
  {
    "code": "def swap_yaml_string(file_path, swaps):\n    original_file = file_to_string(file_path)\n    new_file = original_file\n    changed = False\n    for item in swaps:\n        match = re.compile(r'(?<={0}: )([\"\\']?)(.*)\\1'.format(item[0]),\n                           re.MULTILINE)\n        new_file = re.sub(match, item[1], new_file)\n    if new_file != original_file:\n        changed = True\n    string_to_file(file_path, new_file)\n    return (new_file, changed)",
    "docstring": "Swap a string in a yaml file without touching the existing formatting."
  },
  {
    "code": "def CompressStream(in_stream, length=None, compresslevel=2,\n                   chunksize=16777216):\n    in_read = 0\n    in_exhausted = False\n    out_stream = StreamingBuffer()\n    with gzip.GzipFile(mode='wb',\n                       fileobj=out_stream,\n                       compresslevel=compresslevel) as compress_stream:\n        while not length or out_stream.length < length:\n            data = in_stream.read(chunksize)\n            data_length = len(data)\n            compress_stream.write(data)\n            in_read += data_length\n            if data_length < chunksize:\n                in_exhausted = True\n                break\n    return out_stream, in_read, in_exhausted",
    "docstring": "Compresses an input stream into a file-like buffer.\n\n    This reads from the input stream until either we've stored at least length\n    compressed bytes, or the input stream has been exhausted.\n\n    This supports streams of unknown size.\n\n    Args:\n        in_stream: The input stream to read from.\n        length: The target number of compressed bytes to buffer in the output\n            stream. If length is none, the input stream will be compressed\n            until it's exhausted.\n\n            The actual length of the output buffer can vary from the target.\n            If the input stream is exhaused, the output buffer may be smaller\n            than expected. If the data is incompressible, the maximum length\n            can be exceeded by can be calculated to be:\n\n              chunksize + 5 * (floor((chunksize - 1) / 16383) + 1) + 17\n\n            This accounts for additional header data gzip adds. For the default\n            16MiB chunksize, this results in the max size of the output buffer\n            being:\n\n              length + 16Mib + 5142 bytes\n\n        compresslevel: Optional, defaults to 2. The desired compression level.\n        chunksize: Optional, defaults to 16MiB. The chunk size used when\n            reading data from the input stream to write into the output\n            buffer.\n\n    Returns:\n        A file-like output buffer of compressed bytes, the number of bytes read\n        from the input stream, and a flag denoting if the input stream was\n        exhausted."
  },
  {
    "code": "def _range(self, xloc, cache):\n        uloc = numpy.zeros((2, len(self)))\n        for dist in evaluation.sorted_dependencies(self, reverse=True):\n            if dist not in self.inverse_map:\n                continue\n            idx = self.inverse_map[dist]\n            xloc_ = xloc[idx].reshape(1, -1)\n            uloc[:, idx] = evaluation.evaluate_bound(\n                dist, xloc_, cache=cache).flatten()\n        return uloc",
    "docstring": "Special handle for finding bounds on constrained dists.\n\n        Example:\n            >>> d0 = chaospy.Uniform()\n            >>> dist = chaospy.J(d0, d0+chaospy.Uniform())\n            >>> print(dist.range())\n            [[0. 0.]\n             [1. 2.]]"
  },
  {
    "code": "def burst_range_spectrum(psd, snr=8, energy=1e-2):\n    a = (constants.G * energy * constants.M_sun * 0.4 /\n         (pi**2 * constants.c))**(1/2.)\n    dspec = psd ** (-1/2.) * a / (snr * psd.frequencies)\n    rspec = dspec.to('Mpc')\n    if rspec.f0.value == 0.0:\n        rspec[0] = 0.0\n    return rspec",
    "docstring": "Calculate the frequency-dependent GW burst range from a strain PSD\n\n    Parameters\n    ----------\n    psd : `~gwpy.frequencyseries.FrequencySeries`\n        the instrumental power-spectral-density data\n\n    snr : `float`, optional\n        the signal-to-noise ratio for which to calculate range,\n        default: `8`\n\n    energy : `float`, optional\n        the relative energy output of the GW burst,\n        default: `0.01` (GRB-like burst)\n\n    Returns\n    -------\n    rangespec : `~gwpy.frequencyseries.FrequencySeries`\n        the burst range `FrequencySeries` [Mpc (default)]"
  },
  {
    "code": "def thumb(self, size=BIGTHUMB):\n        if not self.is_image():\n            return None\n        if not size in (self.BIGTHUMB, self.MEDIUMTHUMB, self.SMALLTHUMB, self.XLTHUMB):\n            raise JFSError('Invalid thumbnail size: %s for image %s' % (size, self.path))\n        return self.jfs.raw(url=self.path,\n                            params={'mode':'thumb', 'ts':size})",
    "docstring": "Get a thumbnail as string or None if the file isnt an image\n\n        size would be one of JFSFile.BIGTHUMB, .MEDIUMTHUMB, .SMALLTHUMB or .XLTHUMB"
  },
  {
    "code": "def getpeptides(self, chain):\n        all_from_chain = [o for o in pybel.ob.OBResidueIter(\n            self.proteincomplex.OBMol) if o.GetChain() == chain]\n        if len(all_from_chain) == 0:\n            return None\n        else:\n            non_water = [o for o in all_from_chain if not o.GetResidueProperty(9)]\n            ligand = self.extract_ligand(non_water)\n            return ligand",
    "docstring": "If peptide ligand chains are defined via the command line options,\n        try to extract the underlying ligand formed by all residues in the\n        given chain without water"
  },
  {
    "code": "def select(self, names):\n        return PolicyCollection(\n            [p for p in self.policies if p.name in names], self.options)",
    "docstring": "return the named subset of policies"
  },
  {
    "code": "def getMonitorByName(self, monitorFriendlyName):\n        url = self.baseUrl\n        url += \"getMonitors?apiKey=%s\" % self.apiKey\n        url += \"&noJsonCallback=1&format=json\"\n        success, response = self.requestApi(url)\n        if success:\n            monitors = response.get('monitors').get('monitor')\n            for i in range(len(monitors)):\n                monitor = monitors[i]\n                if monitor.get('friendlyname') == monitorFriendlyName:\n                    status = monitor.get('status')\n                    alltimeuptimeratio = monitor.get('alltimeuptimeratio')\n                    return status, alltimeuptimeratio\n        return None, None",
    "docstring": "Returns monitor status and alltimeuptimeratio for a MonitorFriendlyName."
  },
  {
    "code": "def add(self, *args, **kwargs):\n        for arg in args:\n            if isinstance(arg, str):\n                self._operations.append(self._from_str(arg))\n            else:\n                self._operations.append(arg)\n        if kwargs:\n            self._operations.append(kwargs)",
    "docstring": "Add new mapping from args and kwargs\n\n        >>> om = OperationIdMapping()\n        >>> om.add(\n        ...     OperationIdMapping(),\n        ...     'aiohttp_apiset.swagger.operations',  # any module\n        ...     getPets='mymod.handler',\n        ...     getPet='mymod.get_pet',\n        ... )\n        >>> om['getPets']\n        'mymod.handler'\n\n        :param args: str, Mapping, module or obj\n        :param kwargs: operationId='handler' or operationId=handler"
  },
  {
    "code": "def add_string(self, s):\n        self.add_int(len(s))\n        self.packet.write(s)\n        return self",
    "docstring": "Add a string to the stream.\n        \n        @param s: string to add\n        @type s: str"
  },
  {
    "code": "async def result(self, timeout: Optional[float] = None, *, pole_delay: float = 0.5) -> Any:\n        async for delay in poll(pole_delay):\n            info = await self.result_info()\n            if info:\n                result = info.result\n                if info.success:\n                    return result\n                else:\n                    raise result\n            if timeout is not None and delay > timeout:\n                raise asyncio.TimeoutError()",
    "docstring": "Get the result of the job, including waiting if it's not yet available. If the job raised an exception,\n        it will be raised here.\n\n        :param timeout: maximum time to wait for the job result before raising ``TimeoutError``, will wait forever\n        :param pole_delay: how often to poll redis for the job result"
  },
  {
    "code": "def disaggregate_wind(self, method='equal'):\n        self.data_disagg.wind = melodist.disaggregate_wind(self.data_daily.wind, method=method, **self.statistics.wind)",
    "docstring": "Disaggregate wind speed.\n\n        Parameters\n        ----------\n        method : str, optional\n            Disaggregation method.\n\n            ``equal``\n                Mean daily wind speed is duplicated for the 24 hours of the day. (Default)\n\n            ``cosine``\n                Distributes daily mean wind speed using a cosine function derived from hourly\n                observations.\n\n            ``random``\n                Draws random numbers to distribute wind speed (usually not conserving the\n                daily average)."
  },
  {
    "code": "def normalizeIdentifier(value):\n    if value is None:\n        return value\n    if not isinstance(value, basestring):\n        raise TypeError(\"Identifiers must be strings, not %s.\"\n                        % type(value).__name__)\n    if len(value) == 0:\n        raise ValueError(\"The identifier string is empty.\")\n    if len(value) > 100:\n        raise ValueError(\"The identifier string has a length (%d) greater \"\n                         \"than the maximum allowed (100).\" % len(value))\n    for c in value:\n        v = ord(c)\n        if v < 0x20 or v > 0x7E:\n            raise ValueError(\"The identifier string ('%s') contains a \"\n                             \"character out size of the range 0x20 - 0x7E.\"\n                             % value)\n    return unicode(value)",
    "docstring": "Normalizes identifier.\n\n    * **value** must be an :ref:`type-string` or `None`.\n    * **value** must not be longer than 100 characters.\n    * **value** must not contain a character out the range of 0x20 - 0x7E.\n    * Returned value is an unencoded ``unicode`` string."
  },
  {
    "code": "def register(self, cls):\n        doc_type = cls.search_objects.mapping.doc_type\n        self.all_models[doc_type] = cls\n        base_class = cls.get_base_class()\n        if base_class not in self.families:\n            self.families[base_class] = {}\n        self.families[base_class][doc_type] = cls\n        if cls.search_objects.mapping.index not in self.indexes:\n            self.indexes[cls.search_objects.mapping.index] = []\n        self.indexes[cls.search_objects.mapping.index].append(cls)",
    "docstring": "Adds a new PolymorphicIndexable to the registry."
  },
  {
    "code": "def taf(data: TafData, units: Units) -> str:\n    try:\n        month = data.start_time.dt.strftime(r'%B')\n        day = ordinal(data.start_time.dt.day)\n        ret = f\"Starting on {month} {day} - \"\n    except AttributeError:\n        ret = ''\n    return ret + '. '.join([taf_line(line, units) for line in data.forecast])",
    "docstring": "Convert TafData into a string for text-to-speech"
  },
  {
    "code": "def remove(text, what, count=None, strip=False):\n    return replace(text, what, '', count=count, strip=strip)",
    "docstring": "Like ``replace``, where ``new`` replacement is an empty string."
  },
  {
    "code": "def param_set(name, value, retries=3):\n    name = name.upper()\n    return mpstate.mav_param.mavset(mpstate.master(), name, value, retries=retries)",
    "docstring": "set a parameter"
  },
  {
    "code": "def _dns_lookup(name, rdtype, nameservers=None):\n        rrset = dns.rrset.from_text(name, 0, 1, rdtype)\n        try:\n            resolver = dns.resolver.Resolver()\n            resolver.lifetime = 1\n            if nameservers:\n                resolver.nameservers = nameservers\n            rrset = resolver.query(name, rdtype)\n            for rdata in rrset:\n                LOGGER.debug('DNS Lookup => %s %s %s %s',\n                             rrset.name.to_text(), dns.rdataclass.to_text(rrset.rdclass),\n                             dns.rdatatype.to_text(rrset.rdtype), rdata.to_text())\n        except dns.exception.DNSException as error:\n            LOGGER.debug('DNS Lookup => %s', error)\n        return rrset",
    "docstring": "Looks on specified or default system domain nameservers to resolve record type\n        & name and returns record set. The record set is empty if no propagated\n        record found."
  },
  {
    "code": "def list_azure_containers(config_fpath):\n    config_content = _get_config_dict_from_file(config_fpath)\n    az_container_names = []\n    for key in config_content.keys():\n        if key.startswith(AZURE_KEY_PREFIX):\n            name = key[len(AZURE_KEY_PREFIX):]\n            az_container_names.append(name)\n    return sorted(az_container_names)",
    "docstring": "List the azure storage containers in the config file.\n\n    :param config_fpath: path to the dtool config file\n    :returns: the list of azure storage container names"
  },
  {
    "code": "def get_random_url(ltd=\"com\"):\n        url = [\n            \"https://\",\n            RandomInputHelper.get_random_value(8, [string.ascii_lowercase]),\n            \".\",\n            ltd\n        ]\n        return \"\".join(url)",
    "docstring": "Get a random url with the given ltd.\n\n        Args:\n            ltd (str): The ltd to use (e.g. com).\n\n        Returns:\n            str: The random url."
  },
  {
    "code": "def _convert_to_lexicon(self, record):\n        name = record['Name']\n        if self.domain not in name:\n            name = \"{}.{}\".format(name, self.domain)\n        processed_record = {\n            'type': record['Type'],\n            'name': '{0}.{1}'.format(record['Name'], self.domain),\n            'ttl': record['TTL'],\n            'content': record['Address'],\n            'id': record['HostId']\n        }\n        return processed_record",
    "docstring": "converts from namecheap raw record format to lexicon format record"
  },
  {
    "code": "def strip_column_names(cols, keep_paren_contents=True):\n    new_cols = [\n        _strip_column_name(col, keep_paren_contents=keep_paren_contents)\n        for col in cols]\n    if len(new_cols) != len(set(new_cols)):\n        warn_str = 'Warning: strip_column_names (if run) would introduce duplicate names.'\n        warn_str += ' Reverting column names to the original.'\n        warnings.warn(warn_str, Warning)\n        print('Warning: strip_column_names would introduce duplicate names. Please fix & try again.')\n        return dict(zip(cols, cols))\n    return dict(zip(cols, new_cols))",
    "docstring": "Utility script for renaming pandas columns to patsy-friendly names.\n\n    Revised names have been:\n        - stripped of all punctuation and whitespace (converted to text or `_`)\n        - converted to lower case\n\n    Takes a list of column names, returns a dict mapping\n    names to revised names.\n\n    If there are any concerns with the conversion, this will\n    print a warning & return original column names.\n\n    Parameters\n    ----------\n\n    cols (list): list of strings containing column names\n    keep_paren_contents (logical):\n        controls behavior of within-paren elements of text\n         - if True, (the default) all text within parens retained\n         - if False, text within parens will be removed from the field name\n\n    Returns\n    -------\n\n    dict mapping col_names -> new_col_names\n\n    Example\n    -------\n\n    > df = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),\n      'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']),\n      'PD L1 (value)': pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']),\n      'PD L1 (>1)': pd.Series([0., 1., 1., 0.], index=['a', 'b', 'c', 'd']),\n      }\n    > df = pd.DataFrame(df)\n    > df = df.rename(columns = strip_column_names(df.columns))\n\n    ## observe, by comparison\n    > df2 = df.rename(columns = strip_column_names(df.columns,\n        keep_paren_contents=False))"
  },
  {
    "code": "def parse(log_file):\n    with io.open(os.path.expanduser(log_file), encoding=\"utf-8\") as input_file:\n        for line in input_file:\n            if \"Starting import of XUnit results\" in line:\n                obj = XUnitParser\n                break\n            elif \"Starting import of test cases\" in line:\n                obj = TestcasesParser\n                break\n            elif \"Starting import of requirements\" in line:\n                obj = RequirementsParser\n                break\n        else:\n            raise Dump2PolarionException(\n                \"No valid data found in the log file '{}'\".format(log_file)\n            )\n        return obj(input_file, log_file).parse()",
    "docstring": "Parse log file."
  },
  {
    "code": "def dispatch_sockets(self, timeout=None):\n        for sock in self.select_sockets(timeout=timeout):\n            if sock is self.listener:\n                listener = sock\n                sock, addr = listener.accept()\n                self.connected(sock)\n            else:\n                try:\n                    sock.recv(1)\n                except socket.error as exc:\n                    if exc.errno != ECONNRESET:\n                        raise\n                self.disconnected(sock)",
    "docstring": "Dispatches incoming sockets."
  },
  {
    "code": "def translate(self, package, into=None):\n    if not package.local:\n      raise ValueError('BinaryTranslator cannot translate remote packages.')\n    if not isinstance(package, self._package_type):\n      return None\n    if not package.compatible(self._supported_tags):\n      TRACER.log('Target package %s is not compatible with %s' % (\n          package, self._supported_tags))\n      return None\n    into = into or safe_mkdtemp()\n    target_path = os.path.join(into, package.filename)\n    safe_copy(package.local_path, target_path)\n    return DistributionHelper.distribution_from_path(target_path)",
    "docstring": "From a binary package, translate to a local binary distribution."
  },
  {
    "code": "def change_status(request, page_id):\n    perm = request.user.has_perm('pages.change_page')\n    if perm and request.method == 'POST':\n        page = Page.objects.get(pk=page_id)\n        page.status = int(request.POST['status'])\n        page.invalidate()\n        page.save()\n        return HttpResponse(str(page.status))\n    raise Http404",
    "docstring": "Switch the status of a page."
  },
  {
    "code": "def get_consumer_cfg(config, only, qty):\n        consumers = dict(config.application.Consumers or {})\n        if only:\n            for key in list(consumers.keys()):\n                if key != only:\n                    del consumers[key]\n            if qty:\n                consumers[only]['qty'] = qty\n        return consumers",
    "docstring": "Get the consumers config, possibly filtering the config if only\n        or qty is set.\n\n        :param config: The consumers config section\n        :type config: helper.config.Config\n        :param str only: When set, filter to run only this consumer\n        :param int qty: When set, set the consumer qty to this value\n        :rtype: dict"
  },
  {
    "code": "def _add_action(self, notification, action, label, callback, *args):\n        on_action_click = run_bg(lambda *_: callback(*args))\n        try:\n            notification.add_action(action, label, on_action_click, None)\n        except TypeError:\n            notification.add_action(action, label, on_action_click, None, None)\n        notification.connect('closed', self._notifications.remove)\n        self._notifications.append(notification)",
    "docstring": "Show an action button button in mount notifications.\n\n        Note, this only works with some libnotify services."
  },
  {
    "code": "def match(self, name):\n        if self.method == Ex.Method.PREFIX:\n            return name.startswith(self.value)\n        elif self.method == Ex.Method.SUFFIX:\n            return name.endswith(self.value)\n        elif self.method == Ex.Method.CONTAINS:\n            return self.value in name\n        elif self.method == Ex.Method.EXACT:\n            return self.value == name\n        elif self.method == Ex.Method.REGEX:\n            return re.search(self.value, name)\n        return False",
    "docstring": "Check if given name matches.\n\n        Args:\n            name (str): name to check.\n\n        Returns:\n            bool: matches name."
  },
  {
    "code": "def _process_file_continue_ftp_response(self, response: FTPResponse):\n        if response.request.restart_value and response.restart_value:\n            self.open_file(self._filename, response, mode='ab+')\n        else:\n            self._raise_cannot_continue_error()",
    "docstring": "Process a restarted content response."
  },
  {
    "code": "def uninstall(self):\n        if self.is_installed():\n            installed = self.installed_dir()\n            if installed.is_symlink():\n                installed.unlink()\n            else:\n                shutil.rmtree(str(installed))",
    "docstring": "Delete code inside NApp directory, if existent."
  },
  {
    "code": "def preassemble(self, filters=None, grounding_map=None):\n        stmts = self.get_statements()\n        stmts = ac.filter_no_hypothesis(stmts)\n        if grounding_map is not None:\n            stmts = ac.map_grounding(stmts, grounding_map=grounding_map)\n        else:\n            stmts = ac.map_grounding(stmts)\n        if filters and ('grounding' in filters):\n            stmts = ac.filter_grounded_only(stmts)\n        stmts = ac.map_sequence(stmts)\n        if filters and 'human_only' in filters:\n            stmts = ac.filter_human_only(stmts)\n        stmts = ac.run_preassembly(stmts, return_toplevel=False)\n        stmts = self._relevance_filter(stmts, filters)\n        self.assembled_stmts = stmts",
    "docstring": "Preassemble the Statements collected in the model.\n\n        Use INDRA's GroundingMapper, Preassembler and BeliefEngine\n        on the IncrementalModel and save the unique statements and\n        the top level statements in class attributes.\n\n        Currently the following filter options are implemented:\n        - grounding: require that all Agents in statements are grounded\n        - human_only: require that all proteins are human proteins\n        - prior_one: require that at least one Agent is in the prior model\n        - prior_all: require that all Agents are in the prior model\n\n        Parameters\n        ----------\n        filters : Optional[list[str]]\n            A list of filter options to apply when choosing the statements.\n            See description above for more details. Default: None\n        grounding_map : Optional[dict]\n            A user supplied grounding map which maps a string to a\n            dictionary of database IDs (in the format used by Agents'\n            db_refs)."
  },
  {
    "code": "def write_report(self, session, filename):\n        if not self.__report:\n            session.write_line(\"No report to write down\")\n            return\n        try:\n            with open(filename, \"w+\") as out_file:\n                out_file.write(self.to_json(self.__report))\n        except IOError as ex:\n            session.write_line(\"Error writing to file: {0}\", ex)",
    "docstring": "Writes the report in JSON format to the given file"
  },
  {
    "code": "def _create_record(self, rtype, name, content):\n        opts = {'domain': self._domain, 'type': rtype.upper(),\n                'name': self._full_name(name), 'content': content}\n        if self._get_lexicon_option('ttl'):\n            opts['ttl'] = self._get_lexicon_option('ttl')\n        opts.update(self._auth)\n        response = self._api.nameserver.createRecord(opts)\n        self._validate_response(\n            response=response, message='Failed to create record',\n            exclude_code=2302)\n        return True",
    "docstring": "create a record\n        does nothing if the record already exists\n\n        :param str rtype: type of record\n        :param str name: name of record\n        :param mixed content: value of record\n        :return bool: success status\n        :raises Exception: on error"
  },
  {
    "code": "def reduce_memory_demand(self):\n        prev_gwmem = int(self.get_inpvar(\"gwmem\", default=11))\n        first_dig, second_dig = prev_gwmem // 10, prev_gwmem % 10\n        if second_dig == 1:\n            self.set_vars(gwmem=\"%.2d\" % (10 * first_dig))\n            return True\n        if first_dig == 1:\n            self.set_vars(gwmem=\"%.2d\" % 00)\n            return True\n        return False",
    "docstring": "Method that can be called by the scheduler to decrease the memory demand of a specific task.\n        Returns True in case of success, False in case of Failure."
  },
  {
    "code": "def _get_conn(ret=None):\n    _options = _get_options(ret)\n    database = _options.get('database')\n    timeout = _options.get('timeout')\n    if not database:\n        raise Exception(\n                'sqlite3 config option \"sqlite3.database\" is missing')\n    if not timeout:\n        raise Exception(\n                'sqlite3 config option \"sqlite3.timeout\" is missing')\n    log.debug('Connecting the sqlite3 database: %s timeout: %s', database, timeout)\n    conn = sqlite3.connect(database, timeout=float(timeout))\n    return conn",
    "docstring": "Return a sqlite3 database connection"
  },
  {
    "code": "def connect(self,\n                fedora_url,\n                data=None,\n                method='Get'):\n        if data is None:\n            data = {}\n        if not fedora_url.startswith(\"http\"):\n            fedora_url = urllib.parse.urljoin(self.base_url, fedora_url)\n        request = urllib.request.Request(fedora_url,\n                                         method=method)\n        request.add_header('Accept', 'text/turtle')\n        request.add_header('Content-Type', 'text/turtle')\n        if len(data) > 0:\n            request.data = data\n        try:\n            response = urllib.request.urlopen(request)\n        except urllib.error.URLError as err:\n            if hasattr(err, 'reason'):\n                print(\"failed to reach server at {} with {} method\".format(\n                    fedora_url,\n                    request.method))\n                print(\"Reason: \", err.reason)\n                print(\"Data: \", data)\n            elif hasattr(err, 'code'):\n                print(\"Server error {}\".format(err.code))\n            raise err\n        return response",
    "docstring": "Method attempts to connect to REST servers of the Fedora\n        Commons repository using optional data parameter.\n\n        Args:\n            fedora_url(string): Fedora URL\n            data(dict): Data to through to REST endpoint\n            method(str): REST Method, defaults to GET\n\n        Returns:\n            result(string): Response string from Fedora"
  },
  {
    "code": "def _granule_identifier_to_xml_name(granule_identifier):\n    changed_item_type = re.sub(\"_MSI_\", \"_MTD_\", granule_identifier)\n    split_by_underscores = changed_item_type.split(\"_\")\n    del split_by_underscores[-1]\n    cleaned = str()\n    for i in split_by_underscores:\n        cleaned += (i + \"_\")\n    out_xml = cleaned[:-1] + \".xml\"\n    return out_xml",
    "docstring": "Very ugly way to convert the granule identifier.\n\n    e.g.\n    From\n    Granule Identifier:\n    S2A_OPER_MSI_L1C_TL_SGS__20150817T131818_A000792_T28QBG_N01.03\n    To\n    Granule Metadata XML name:\n    S2A_OPER_MTD_L1C_TL_SGS__20150817T131818_A000792_T28QBG.xml"
  },
  {
    "code": "def normalize_genotypes(genotypes):\n    genotypes = genotypes.genotypes\n    return (genotypes - np.nanmean(genotypes)) / np.nanstd(genotypes)",
    "docstring": "Normalize the genotypes.\n\n    Args:\n        genotypes (Genotypes): The genotypes to normalize.\n\n    Returns:\n        numpy.array: The normalized genotypes."
  },
  {
    "code": "def irafconvert(iraffilename):\n    convertdict = CONVERTDICT\n    if not iraffilename.lower().startswith(('http', 'ftp')):\n        iraffilename = os.path.normpath(iraffilename)\n    if iraffilename.startswith('$'):\n        pat = re.compile(r'\\$(\\w*)')\n        match = re.match(pat, iraffilename)\n        dirname = match.group(1)\n        unixdir = os.environ[dirname]\n        basename = iraffilename[match.end() + 1:]\n        unixfilename = os.path.join(unixdir, basename)\n        return unixfilename\n    elif '$' in iraffilename:\n        irafdir, basename = iraffilename.split('$')\n        if irafdir == 'synphot':\n            return get_data_filename(os.path.basename(basename))\n        unixdir = convertdict[irafdir]\n        unixfilename = os.path.join(unixdir, basename)\n        return unixfilename\n    else:\n        return iraffilename",
    "docstring": "Convert the IRAF file name to its Unix equivalent.\n\n    Input can be in ``directory$file`` or ``$directory/file`` format.\n    If ``'$'`` is not found in the input string, it is returned as-is.\n\n    Parameters\n    ----------\n    iraffilename : str\n        Filename in IRAF format.\n\n    Returns\n    -------\n    unixfilename : str\n        Filename in Unix format.\n\n    Raises\n    ------\n    AttributeError\n        Input is not a string."
  },
  {
    "code": "def get_body_encoding(self):\n        assert self.body_encoding != SHORTEST\n        if self.body_encoding == QP:\n            return 'quoted-printable'\n        elif self.body_encoding == BASE64:\n            return 'base64'\n        else:\n            return encode_7or8bit",
    "docstring": "Return the content-transfer-encoding used for body encoding.\n\n        This is either the string `quoted-printable' or `base64' depending on\n        the encoding used, or it is a function in which case you should call\n        the function with a single argument, the Message object being\n        encoded.  The function should then set the Content-Transfer-Encoding\n        header itself to whatever is appropriate.\n\n        Returns \"quoted-printable\" if self.body_encoding is QP.\n        Returns \"base64\" if self.body_encoding is BASE64.\n        Returns conversion function otherwise."
  },
  {
    "code": "def not0(a):\n    return matrix(list(map(lambda x: 1 if x == 0 else x, a)), a.size)",
    "docstring": "Return u if u!= 0, return 1 if u == 0"
  },
  {
    "code": "def attention_bias_prepend_inputs_full_attention(padding):\n  in_target = tf.cumsum(padding, axis=1, exclusive=True)\n  target_pos = tf.cumsum(in_target, axis=1)\n  illegal_connections = tf.greater(\n      tf.expand_dims(target_pos, 1), tf.expand_dims(target_pos, 2))\n  bias = tf.to_float(illegal_connections) * -1e9\n  bias = tf.expand_dims(bias, 1)\n  return bias",
    "docstring": "Create a bias tensor for prepend_mode=\"prepend_inputs_full_attention\".\n\n  See prepend_inputs in common_hparams.py.\n\n  Produces a bias tensor to be used in self-attention.\n\n  This bias tensor allows for full connectivity in the \"inputs\" part of\n  the sequence and masked connectivity in the targets part.\n\n  Args:\n    padding: a float `Tensor` with shape [batch, length] with\n      ones in positions corresponding to padding.  In each row, a single\n      padding position separates the input part from the target part.\n\n  Returns:\n    a `Tensor` with shape [batch, 1, length, length]."
  },
  {
    "code": "def xpathRegisterNs(self, prefix, ns_uri):\n        ret = libxml2mod.xmlXPathRegisterNs(self._o, prefix, ns_uri)\n        return ret",
    "docstring": "Register a new namespace. If @ns_uri is None it unregisters\n           the namespace"
  },
  {
    "code": "def get_tab_tip(self, filename, is_modified=None, is_readonly=None):\r\n        text = u\"%s — %s\"\r\n        text = self.__modified_readonly_title(text,\r\n                                              is_modified, is_readonly)\r\n        if self.tempfile_path is not None\\\r\n           and filename == encoding.to_unicode_from_fs(self.tempfile_path):\r\n            temp_file_str = to_text_string(_(\"Temporary file\"))\r\n            return text % (temp_file_str, self.tempfile_path)\r\n        else:\r\n            return text % (osp.basename(filename), osp.dirname(filename))",
    "docstring": "Return tab menu title"
  },
  {
    "code": "def _make_tuple(self, env):\n    t = runtime.Tuple(self, env, dict2tuple)\n    schema = schema_spec_from_tuple(t)\n    t.attach_schema(schema)\n    return t",
    "docstring": "Instantiate the Tuple based on this TupleNode."
  },
  {
    "code": "def getDirSizeRecursively(dirPath):\n    return int(subprocess.check_output(['du', '-s', dirPath],\n                                       env=dict(os.environ, BLOCKSIZE='512')).decode('utf-8').split()[0]) * 512",
    "docstring": "This method will return the cumulative number of bytes occupied by the files\n    on disk in the directory and its subdirectories.\n\n    This method will raise a 'subprocess.CalledProcessError' if it is unable to\n    access a folder or file because of insufficient permissions.  Therefore this\n    method should only be called on the jobStore, and will alert the user if some\n    portion is inaccessible.  Everything in the jobStore should have appropriate\n    permissions as there is no way to read the filesize without permissions.\n\n    The environment variable 'BLOCKSIZE'='512' is set instead of the much cleaner\n    --block-size=1 because Apple can't handle it.\n\n    :param str dirPath: A valid path to a directory or file.\n    :return: Total size, in bytes, of the file or directory at dirPath."
  },
  {
    "code": "def delete(self, *args, **kwargs):\n        try:\n            os.remove(self.file.file.name)\n        except (OSError, IOError):\n            pass\n        super(Image, self).delete(*args, **kwargs)",
    "docstring": "delete image when an image record is deleted"
  },
  {
    "code": "def write_empty(self, size):\n        if size < 1:\n            return\n        self._fh.seek(size-1, 1)\n        self._fh.write(b'\\x00')",
    "docstring": "Append size bytes to file. Position must be at end of file."
  },
  {
    "code": "def fetch(self, only_ref=False):\n        if self.ref:\n            reply = self.connector.get_object(\n                self.ref, return_fields=self.return_fields)\n            if reply:\n                self.update_from_dict(reply)\n                return True\n        search_dict = self.to_dict(search_fields='update')\n        return_fields = [] if only_ref else self.return_fields\n        reply = self.connector.get_object(self.infoblox_type,\n                                          search_dict,\n                                          return_fields=return_fields)\n        if reply:\n            self.update_from_dict(reply[0], only_ref=only_ref)\n            return True\n        return False",
    "docstring": "Fetch object from NIOS by _ref or searchfields\n\n        Update existent object with fields returned from NIOS\n        Return True on successful object fetch"
  },
  {
    "code": "def extern_store_bool(self, context_handle, b):\n    c = self._ffi.from_handle(context_handle)\n    return c.to_value(b)",
    "docstring": "Given a context and _Bool, return a new Handle to represent the _Bool."
  },
  {
    "code": "def unixtimestamp(datetime):\n    epoch = UTC.localize(datetime.utcfromtimestamp(0))\n    if not datetime.tzinfo:\n        dt = UTC.localize(datetime)\n    else:\n        dt = UTC.normalize(datetime)\n    delta = dt - epoch\n    return total_seconds(delta)",
    "docstring": "Get unix time stamp from that given datetime. If datetime\n    is not tzaware then it's assumed that it is UTC"
  },
  {
    "code": "def snapshot_name_to_id(name, snap_name, strict=False, runas=None):\n    name = salt.utils.data.decode(name)\n    snap_name = salt.utils.data.decode(snap_name)\n    info = prlctl('snapshot-list', name, runas=runas)\n    snap_ids = _find_guids(info)\n    named_ids = []\n    for snap_id in snap_ids:\n        if snapshot_id_to_name(name, snap_id, runas=runas) == snap_name:\n            named_ids.append(snap_id)\n    if not named_ids:\n        raise SaltInvocationError(\n            'No snapshots for VM \"{0}\" have name \"{1}\"'.format(name, snap_name)\n        )\n    elif len(named_ids) == 1:\n        return named_ids[0]\n    else:\n        multi_msg = ('Multiple snapshots for VM \"{0}\" have name '\n                     '\"{1}\"'.format(name, snap_name))\n        if strict:\n            raise SaltInvocationError(multi_msg)\n        else:\n            log.warning(multi_msg)\n        return named_ids",
    "docstring": "Attempt to convert a snapshot name to a snapshot ID.  If the name is not\n    found an empty string is returned.  If multiple snapshots share the same\n    name, a list will be returned\n\n    :param str name:\n        Name/ID of VM whose snapshots are inspected\n\n    :param str snap_name:\n        Name of the snapshot\n\n    :param bool strict:\n        Raise an exception if multiple snapshot IDs are found\n\n    :param str runas:\n        The user that the prlctl command will be run as\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' parallels.snapshot_id_to_name macvm original runas=macdev"
  },
  {
    "code": "def sg_lookup(tensor, opt):\n    r\n    assert opt.emb is not None, 'emb is mandatory.'\n    return tf.nn.embedding_lookup(opt.emb, tensor, name=opt.name)",
    "docstring": "r\"\"\"Looks up the `tensor`, which is the embedding matrix.\n\n    Args:\n        tensor: A tensor ( automatically given by chain )\n        opt:\n          emb: A 2-D `Tensor`. An embedding matrix.\n          name: If provided, replace current tensor's name.\n\n    Returns:\n        A `Tensor`."
  },
  {
    "code": "def remove_supervisor_app(app_name):\n    app = u'/etc/supervisor/conf.d/%s.conf' % app_name\n    if files.exists(app):\n        sudo(u'rm %s' % app)\n        supervisor_command(u'update')",
    "docstring": "Remove Supervisor app configuration."
  },
  {
    "code": "def copytree(src, dst, symlinks=False, ignore=None):\n    if not os.path.exists(dst):\n        os.mkdir(dst)\n    try:\n        for item in os.listdir(src):\n            s = os.path.join(src, item)\n            d = os.path.join(dst, item)\n            if os.path.isdir(s):\n                shutil.copytree(s, d, symlinks, ignore)\n            else:\n                shutil.copy2(s, d)\n    except Exception as e:\n        raise FolderExistsError(\"Folder already exists in %s\" % dst)",
    "docstring": "Function recursively copies from directory to directory.\n\n    Args\n    ----\n    src (string): the full path of source directory\n    dst (string): the full path of destination directory\n    symlinks (boolean): the switch for tracking symlinks\n    ignore (list): the ignore list"
  },
  {
    "code": "def bin_b64_type(arg):\n\ttry:\n\t\targ = base64.standard_b64decode(arg)\n\texcept (binascii.Error, TypeError):\n\t\traise argparse.ArgumentTypeError(\"{0} is invalid base64 data\".format(repr(arg)))\n\treturn arg",
    "docstring": "An argparse type representing binary data encoded in base64."
  },
  {
    "code": "def user_default_loader(self, pk):\n        try:\n            obj = User.objects.get(pk=pk)\n        except User.DoesNotExist:\n            return None\n        else:\n            self.user_default_add_related_pks(obj)\n            return obj",
    "docstring": "Load a User from the database."
  },
  {
    "code": "def columns(self):\n        fields = [f.label for f in self.form_fields\n                  if self.cleaned_data[\"field_%s_export\" % f.id]]\n        if self.cleaned_data[\"field_0_export\"]:\n            fields.append(self.entry_time_name)\n        return fields",
    "docstring": "Returns the list of selected column names."
  },
  {
    "code": "def readPlistFromString(data):\n    try:\n        plistData = buffer(data)\n    except TypeError, err:\n        raise NSPropertyListSerializationException(err)\n    dataObject, dummy_plistFormat, error = (\n        NSPropertyListSerialization.\n        propertyListFromData_mutabilityOption_format_errorDescription_(\n            plistData, NSPropertyListMutableContainers, None, None))\n    if dataObject is None:\n        if error:\n            error = error.encode('ascii', 'ignore')\n        else:\n            error = \"Unknown error\"\n        raise NSPropertyListSerializationException(error)\n    else:\n        return dataObject",
    "docstring": "Read a plist data from a string. Return the root object."
  },
  {
    "code": "def new_bundle(name, scriptmap, filemap=None):\n    if name in BUNDLEMAP:\n        logger.warn('overwriting bundle %s' % name)\n    BUNDLEMAP[name] = Bundle(scriptmap, filemap)",
    "docstring": "Create a bundle and add to available bundles"
  },
  {
    "code": "def as_txt(self):\n        s = \"IIIF Image Server Error\\n\\n\"\n        s += self.text if (self.text) else 'UNKNOWN_ERROR'\n        s += \"\\n\\n\"\n        if (self.parameter):\n            s += \"parameter=%s\\n\" % self.parameter\n        if (self.code):\n            s += \"code=%d\\n\\n\" % self.code\n        for header in sorted(self.headers):\n            s += \"header %s=%s\\n\" % (header, self.headers[header])\n        return s",
    "docstring": "Text rendering of error response.\n\n        Designed for use with Image API version 1.1 and above where the\n        error response is suggested to be text or html but not otherwise\n        specified. Intended to provide useful information for debugging."
  },
  {
    "code": "def heating_values(self):\n        heating_dict = {\n            'level': self.heating_level,\n            'target': self.target_heating_level,\n            'active': self.now_heating,\n            'remaining': self.heating_remaining,\n            'last_seen': self.last_seen,\n        }\n        return heating_dict",
    "docstring": "Return a dict of all the current heating values."
  },
  {
    "code": "def _update_redundancy_router_interfaces(self, context, router,\n                                             port, modified_port_data,\n                                             redundancy_router_ids=None,\n                                             ha_settings_db=None):\n        router_id = router['id']\n        if ha_settings_db is None:\n            ha_settings_db = self._get_ha_settings_by_router_id(context,\n                                                                router_id)\n        if ha_settings_db is None:\n            return\n        e_context = context.elevated()\n        rr_ids = self._get_redundancy_router_ids(e_context, router_id)\n        port_info_list = self._core_plugin.get_ports(\n            e_context, filters={'device_id': rr_ids,\n                                'network_id': [port['network_id']]},\n            fields=['device_id', 'id'])\n        for port_info in port_info_list:\n            self._core_plugin.update_port(e_context, port_info['id'],\n                                          modified_port_data)\n        self._update_hidden_port(e_context, port['id'], modified_port_data)",
    "docstring": "To be called when the router interfaces are updated,\n        like in the case of change in port admin_state_up status"
  },
  {
    "code": "def _get_page_elements(self):\n        page_elements = []\n        for attribute, value in list(self.__dict__.items()) + list(self.__class__.__dict__.items()):\n            if attribute != 'parent' and isinstance(value, CommonObject):\n                page_elements.append(value)\n        return page_elements",
    "docstring": "Return page elements and page objects of this page object\n\n        :returns: list of page elements and page objects"
  },
  {
    "code": "def remove(self, expr):\n        self._assert_supports_contents()\n        index = self._contents.index(expr)\n        self._contents.remove(expr)\n        return index",
    "docstring": "Remove a provided expression from its list of contents.\n\n        :param Union[TexExpr,str] expr: Content to add\n        :return: index of the expression removed\n        :rtype: int\n\n        >>> expr = TexExpr('textbf', ('hello',))\n        >>> expr.remove('hello')\n        0\n        >>> expr\n        TexExpr('textbf', [])"
  },
  {
    "code": "def handle_symbol_search(self, call_id, payload):\n        self.log.debug('handle_symbol_search: in %s', Pretty(payload))\n        syms = payload[\"syms\"]\n        qfList = []\n        for sym in syms:\n            p = sym.get(\"pos\")\n            if p:\n                item = self.editor.to_quickfix_item(str(p[\"file\"]),\n                                                    p[\"line\"],\n                                                    str(sym[\"name\"]),\n                                                    \"info\")\n                qfList.append(item)\n        self.editor.write_quickfix_list(qfList, \"Symbol Search\")",
    "docstring": "Handler for symbol search results"
  },
  {
    "code": "def _compute_valid(self):\n        r\n        if self._dimension != 2:\n            raise NotImplementedError(\"Validity check only implemented in R^2\")\n        poly_sign = None\n        if self._degree == 1:\n            first_deriv = self._nodes[:, 1:] - self._nodes[:, :-1]\n            poly_sign = _SIGN(np.linalg.det(first_deriv))\n        elif self._degree == 2:\n            bernstein = _surface_helpers.quadratic_jacobian_polynomial(\n                self._nodes\n            )\n            poly_sign = _surface_helpers.polynomial_sign(bernstein, 2)\n        elif self._degree == 3:\n            bernstein = _surface_helpers.cubic_jacobian_polynomial(self._nodes)\n            poly_sign = _surface_helpers.polynomial_sign(bernstein, 4)\n        else:\n            raise _helpers.UnsupportedDegree(self._degree, supported=(1, 2, 3))\n        return poly_sign == 1",
    "docstring": "r\"\"\"Determines if the current surface is \"valid\".\n\n        Does this by checking if the Jacobian of the map from the\n        reference triangle is everywhere positive.\n\n        Returns:\n            bool: Flag indicating if the current surface is valid.\n\n        Raises:\n            NotImplementedError: If the surface is in a dimension other\n                than :math:`\\mathbf{R}^2`.\n            .UnsupportedDegree: If the degree is not 1, 2 or 3."
  },
  {
    "code": "def convert_cmus_output(self, cmus_output):\n        cmus_output = cmus_output.split('\\n')\n        cmus_output = [x.replace('tag ', '') for x in cmus_output if not x in '']\n        cmus_output = [x.replace('set ', '') for x in cmus_output]\n        status = {}\n        partitioned = (item.partition(' ') for item in cmus_output)\n        status = {item[0]: item[2] for item in partitioned}\n        status['duration'] = self.convert_time(status['duration'])\n        status['position'] = self.convert_time(status['position'])\n        return status",
    "docstring": "Change the newline separated string of output data into\n        a dictionary which can then be used to replace the strings in the config\n        format.\n\n        cmus_output: A string with information about cmus that is newline\n        seperated. Running cmus-remote -Q in a terminal will show you what\n        you're dealing with."
  },
  {
    "code": "def metadata(self):\n        resp = self.r_session.get(self.database_url)\n        resp.raise_for_status()\n        return response_to_json_dict(resp)",
    "docstring": "Retrieves the remote database metadata dictionary.\n\n        :returns: Dictionary containing database metadata details"
  },
  {
    "code": "def obfn_fvarf(self):\n        return self.Xf if self.opt['fEvalX'] else \\\n            sl.rfftn(self.Y, None, self.cri.axisN)",
    "docstring": "Variable to be evaluated in computing data fidelity term,\n        depending on 'fEvalX' option value."
  },
  {
    "code": "def rhochange(self):\n        self.lu, self.piv = sl.lu_factor(self.Z, self.rho)\n        self.lu = np.asarray(self.lu, dtype=self.dtype)",
    "docstring": "Re-factorise matrix when rho changes"
  },
  {
    "code": "def connect_service(service, credentials, region_name = None, config = None, silent = False):\n    api_client = None\n    try:\n        client_params = {}\n        client_params['service_name'] = service.lower()\n        session_params = {}\n        session_params['aws_access_key_id'] = credentials['AccessKeyId']\n        session_params['aws_secret_access_key'] = credentials['SecretAccessKey']\n        session_params['aws_session_token'] = credentials['SessionToken']\n        if region_name:\n            client_params['region_name'] = region_name\n            session_params['region_name'] = region_name\n        if config:\n            client_params['config'] = config\n        aws_session = boto3.session.Session(**session_params)\n        if not silent:\n            infoMessage = 'Connecting to AWS %s' % service\n            if region_name:\n                infoMessage = infoMessage + ' in %s' % region_name\n            printInfo('%s...' % infoMessage)\n        api_client = aws_session.client(**client_params)\n    except Exception as e:\n        printException(e)\n    return api_client",
    "docstring": "Instantiates an AWS API client\n\n    :param service:\n    :param credentials:\n    :param region_name:\n    :param config:\n    :param silent:\n\n    :return:"
  },
  {
    "code": "def seed(vault_client, opt):\n    if opt.thaw_from:\n        opt.secrets = tempfile.mkdtemp('aomi-thaw')\n        auto_thaw(vault_client, opt)\n    Context.load(get_secretfile(opt), opt) \\\n           .fetch(vault_client) \\\n           .sync(vault_client, opt)\n    if opt.thaw_from:\n        rmtree(opt.secrets)",
    "docstring": "Will provision vault based on the definition within a Secretfile"
  },
  {
    "code": "def find_anomalies(errors, index, z_range=(0, 10)):\n    threshold = find_threshold(errors, z_range)\n    sequences = find_sequences(errors, threshold)\n    anomalies = list()\n    denominator = errors.mean() + errors.std()\n    for start, stop in sequences:\n        max_error = errors[start:stop + 1].max()\n        score = (max_error - threshold) / denominator\n        anomalies.append([index[start], index[stop], score])\n    return np.asarray(anomalies)",
    "docstring": "Find sequences of values that are anomalous.\n\n    We first find the ideal threshold for the set of errors that we have,\n    and then find the sequences of values that are above this threshold.\n\n    Lastly, we compute a score proportional to the maximum error in the\n    sequence, and finally return the index pairs that correspond to\n    each sequence, along with its score."
  },
  {
    "code": "def contains_bad_glyph(glyph_data, data):\n    def check_glyph(char):\n        for cmap in glyph_data[\"cmap\"].tables:\n            if cmap.isUnicode():\n                if char in cmap.cmap:\n                    return True\n        return False\n    for part in data:\n        text = part.get(\"full_text\", \"\")\n        try:\n            text = text.decode(\"utf8\")\n        except AttributeError:\n            pass\n        for char in text:\n            if not check_glyph(ord(char)):\n                print(u\"%s (%s) missing\" % (char, ord(char)))\n                return True\n    return False",
    "docstring": "Pillow only looks for glyphs in the font used so we need to make sure our\n    font has the glygh.  Although we could substitute a glyph from another font\n    eg symbola but this adds more complexity and is of limited value."
  },
  {
    "code": "def set_cols_valign(self, array):\n        self._check_row_size(array)\n        self._valign = array\n        return self",
    "docstring": "Set the desired columns vertical alignment\n\n        - the elements of the array should be either \"t\", \"m\" or \"b\":\n\n            * \"t\": column aligned on the top of the cell\n            * \"m\": column aligned on the middle of the cell\n            * \"b\": column aligned on the bottom of the cell"
  },
  {
    "code": "def stringize(\n        self,\n        rnf_profile=RnfProfile(),\n    ):\n        sorted_segments = sorted(self.segments,\n         key=lambda x: (\n          x.genome_id * (10 ** 23) +\n          x.chr_id * (10 ** 21) +\n          (x.left + (int(x.left == 0) * x.right - 1)) * (10 ** 11) +\n          x.right * (10 ** 1) +\n          int(x.direction == \"F\")\n         )\n        )\n        segments_strings = [x.stringize(rnf_profile) for x in sorted_segments]\n        read_tuple_name = \"__\".join(\n            [\n                self.prefix,\n                format(self.read_tuple_id, 'x').zfill(rnf_profile.read_tuple_id_width),\n                \",\".join(segments_strings),\n                self.suffix,\n            ]\n        )\n        return read_tuple_name",
    "docstring": "Create RNF representation of this read.\n\n\t\tArgs:\n\t\t\tread_tuple_id_width (int): Maximal expected string length of read tuple ID.\n\t\t\tgenome_id_width (int): Maximal expected string length of genome ID.\n\t\t\tchr_id_width (int): Maximal expected string length of chromosome ID.\n\t\t\tcoor_width (int): Maximal expected string length of a coordinate."
  },
  {
    "code": "def server_receives_binary_from(self, name=None, timeout=None, connection=None, label=None):\n        server, name = self._servers.get_with_name(name)\n        msg, ip, port = server.receive_from(timeout=timeout, alias=connection)\n        self._register_receive(server, label, name, connection=connection)\n        return msg, ip, port",
    "docstring": "Receive raw binary message. Returns message, ip, and port.\n\n        If server `name` is not given, uses the latest server. Optional message\n        `label` is shown on logs.\n\n        Examples:\n        | ${binary} | ${ip} | ${port} = | Server receives binary from |\n        | ${binary} | ${ip} | ${port} = | Server receives binary from | Server1 | connection=my_connection | timeout=5 |"
  },
  {
    "code": "def pull(self, arm_id, success, failure):\n        self.__beta_dist_dict[arm_id].observe(success, failure)",
    "docstring": "Pull arms.\n\n        Args:\n            arm_id:     Arms master id.\n            success:    The number of success.\n            failure:    The number of failure."
  },
  {
    "code": "def _new_page(self):\n        self._current_page = Drawing(*self._pagesize)\n        if self._bgimage:\n            self._current_page.add(self._bgimage)\n        self._pages.append(self._current_page)\n        self.page_count += 1\n        self._position = [1, 0]",
    "docstring": "Helper function to start a new page. Not intended for external use."
  },
  {
    "code": "def pull_release(self, name, version, destfolder=\".\", force=False):\n        unique_id = name.replace('/', '_')\n        depdict = {\n            'name': name,\n            'unique_id': unique_id,\n            'required_version': version,\n            'required_version_string': str(version)\n        }\n        destdir = os.path.join(destfolder, unique_id)\n        if os.path.exists(destdir):\n            if not force:\n                raise ExternalError(\"Output directory exists and force was not specified, aborting\",\n                                    output_directory=destdir)\n            shutil.rmtree(destdir)\n        result = self.update_dependency(None, depdict, destdir)\n        if result != \"installed\":\n            raise ArgumentError(\"Could not find component to satisfy name/version combination\")",
    "docstring": "Download and unpack a released iotile component by name and version range\n\n        If the folder that would be created already exists, this command fails unless\n        you pass force=True\n\n        Args:\n            name (string): The name of the component to download\n            version (SemanticVersionRange): The valid versions of the component to fetch\n            destfolder (string): The folder into which to unpack the result, defaults to\n                the current working directory\n            force (bool): Forcibly overwrite whatever is currently in the folder that would\n                be fetched.\n\n        Raises:\n            ExternalError: If the destination folder exists and force is not specified\n            ArgumentError: If the specified component could not be found with the required version"
  },
  {
    "code": "def getVersion(data):\n    data = data.splitlines()\n    return next((\n        v\n        for v, u in zip(data, data[1:])\n        if len(v) == len(u) and allSame(u) and hasDigit(v) and \".\" in v\n    ))",
    "docstring": "Parse version from changelog written in RST format."
  },
  {
    "code": "def consume_socket_output(frames, demux=False):\n    if demux is False:\n        return six.binary_type().join(frames)\n    out = [None, None]\n    for frame in frames:\n        assert frame != (None, None)\n        if frame[0] is not None:\n            if out[0] is None:\n                out[0] = frame[0]\n            else:\n                out[0] += frame[0]\n        else:\n            if out[1] is None:\n                out[1] = frame[1]\n            else:\n                out[1] += frame[1]\n    return tuple(out)",
    "docstring": "Iterate through frames read from the socket and return the result.\n\n    Args:\n\n        demux (bool):\n            If False, stdout and stderr are multiplexed, and the result is the\n            concatenation of all the frames. If True, the streams are\n            demultiplexed, and the result is a 2-tuple where each item is the\n            concatenation of frames belonging to the same stream."
  },
  {
    "code": "def _req(self, method=\"get\", verb=None, headers={}, params={}, data={}):\n        url = self.BASE_URL.format(verb=verb)\n        request_headers = {\"content-type\": \"application/json\"}\n        request_params = {\"api_key\": self.API_KEY}\n        request_headers.update(headers)\n        request_params.update(params)\n        return getattr(requests, method)(\n            url, params=request_params, headers=request_headers, data=data\n        )",
    "docstring": "Method to wrap all request building\n\n        :return: a Response object based on the specified method and request values."
  },
  {
    "code": "def is_org_admin(self, organisation_id):\n        return (self._has_role(organisation_id, self.roles.administrator) or\n                self.is_admin())",
    "docstring": "Is the user authorized to administrate the organisation"
  },
  {
    "code": "def decipher_all(decipher, objid, genno, x):\n    if isinstance(x, str):\n        return decipher(objid, genno, x)\n    if isinstance(x, list):\n        x = [decipher_all(decipher, objid, genno, v) for v in x]\n    elif isinstance(x, dict):\n        for (k, v) in x.iteritems():\n            x[k] = decipher_all(decipher, objid, genno, v)\n    return x",
    "docstring": "Recursively deciphers the given object."
  },
  {
    "code": "def clear_jobs(self, recursive=True):\n        if recursive:\n            for link in self._links.values():\n                link.clear_jobs(recursive)\n        self.jobs.clear()",
    "docstring": "Clear a dictionary with all the jobs\n\n        If recursive is True this will include jobs from all internal `Link`"
  },
  {
    "code": "def _match_serializers_by_query_arg(self, serializers):\n        arg_name = current_app.config.get('REST_MIMETYPE_QUERY_ARG_NAME')\n        if arg_name:\n            arg_value = request.args.get(arg_name, None)\n            if arg_value is None:\n                return None\n            try:\n                return serializers[\n                    self.serializers_query_aliases[arg_value]]\n            except KeyError:\n                return None\n        return None",
    "docstring": "Match serializer by query arg."
  },
  {
    "code": "def copy_user_agent_from_driver(self):\n        selenium_user_agent = self.driver.execute_script(\"return navigator.userAgent;\")\n        self.headers.update({\"user-agent\": selenium_user_agent})",
    "docstring": "Updates requests' session user-agent with the driver's user agent\n\n        This method will start the browser process if its not already running."
  },
  {
    "code": "def install(source,\n            venv=None,\n            requirement_files=None,\n            upgrade=False,\n            ignore_platform=False,\n            install_args=''):\n    requirement_files = requirement_files or []\n    logger.info('Installing %s', source)\n    processed_source = get_source(source)\n    metadata = _get_metadata(processed_source)\n    def raise_unsupported_platform(machine_platform):\n        raise WagonError(\n            'Platform unsupported for wagon ({0})'.format(\n                machine_platform))\n    try:\n        supported_platform = metadata['supported_platform']\n        if not ignore_platform and supported_platform != ALL_PLATFORMS_TAG:\n            logger.debug(\n                'Validating Platform %s is supported...', supported_platform)\n            machine_platform = get_platform()\n            if not _is_platform_supported(\n                    supported_platform, machine_platform):\n                raise_unsupported_platform(machine_platform)\n        wheels_path = os.path.join(processed_source, DEFAULT_WHEELS_PATH)\n        install_package(\n            metadata['package_name'],\n            wheels_path,\n            venv,\n            requirement_files,\n            upgrade,\n            install_args)\n    finally:\n        if processed_source != source:\n            shutil.rmtree(os.path.dirname(\n                processed_source), ignore_errors=True)",
    "docstring": "Install a Wagon archive.\n\n    This can install in a provided `venv` or in the current\n    virtualenv in case one is currently active.\n\n    `upgrade` is merely pip's upgrade.\n\n    `ignore_platform` will allow to ignore the platform check, meaning\n    that if an archive was created for a specific platform (e.g. win32),\n    and the current platform is different, it will still attempt to\n    install it.\n\n    Platform check will fail on the following:\n\n    If not linux and no platform match (e.g. win32 vs. darwin)\n    If linux and:\n        architecture doesn't match (e.g. manylinux1_x86_64 vs. linux_i686)\n        wheel not manylinux and no platform match (linux_x86_64 vs. linux_i686)"
  },
  {
    "code": "def station(self, station_id, *, num_songs=25, recently_played=None):\n\t\tstation_info = {\n\t\t\t'station_id': station_id,\n\t\t\t'num_entries': num_songs,\n\t\t\t'library_content_only': False\n\t\t}\n\t\tif recently_played is not None:\n\t\t\tstation_info['recently_played'] = recently_played\n\t\tresponse = self._call(\n\t\t\tmc_calls.RadioStationFeed,\n\t\t\tstation_infos=[station_info]\n\t\t)\n\t\tstation_feed = response.body.get('data', {}).get('stations', [])\n\t\ttry:\n\t\t\tstation = station_feed[0]\n\t\texcept IndexError:\n\t\t\tstation = {}\n\t\treturn station",
    "docstring": "Get information about a station.\n\n\t\tParameters:\n\t\t\tstation_id (str): A station ID. Use 'IFL' for I'm Feeling Lucky.\n\t\t\tnum_songs (int, Optional): The maximum number of songs to return from the station.\n\t\t\t\tDefault: ``25``\n\t\t\trecently_played (list, Optional): A list of dicts in the form of {'id': '', 'type'}\n\t\t\t\twhere ``id`` is a song ID and ``type`` is 0 for a library song and 1 for a store song.\n\n\t\tReturns:\n\t\t\tdict: Station information."
  },
  {
    "code": "def trace(self, urls=None, **overrides):\n        if urls is not None:\n            overrides['urls'] = urls\n        return self.where(accept='TRACE', **overrides)",
    "docstring": "Sets the acceptable HTTP method to TRACE"
  },
  {
    "code": "def rng_annotation(self, stmt, p_elem):\n        ext = stmt.i_extension\n        prf, extkw = stmt.raw_keyword\n        (modname,rev)=stmt.i_module.i_prefixes[prf]\n        prefix = self.add_namespace(\n            statements.modulename_to_module(self.module,modname,rev))\n        eel = SchemaNode(prefix + \":\" + extkw, p_elem)\n        argst = ext.search_one(\"argument\")\n        if argst:\n            if argst.search_one(\"yin-element\", \"true\"):\n                SchemaNode(prefix + \":\" + argst.arg, eel, stmt.arg)\n            else:\n                eel.attr[argst.arg] = stmt.arg\n        self.handle_substmts(stmt, eel)",
    "docstring": "Append YIN representation of extension statement `stmt`."
  },
  {
    "code": "def FilterRange(self, start_time=None, stop_time=None):\n    start_time = self._NormalizeTime(start_time)\n    stop_time = self._NormalizeTime(stop_time)\n    self.data = [\n        p for p in self.data\n        if (start_time is None or p[1] >= start_time) and\n        (stop_time is None or p[1] < stop_time)\n    ]",
    "docstring": "Filter the series to lie between start_time and stop_time.\n\n    Removes all values of the series which are outside of some time range.\n\n    Args:\n      start_time: If set, timestamps before start_time will be dropped.\n      stop_time: If set, timestamps at or past stop_time will be dropped."
  },
  {
    "code": "def quic_graph_lasso(X, num_folds, metric):\n    print(\"QuicGraphicalLasso + GridSearchCV with:\")\n    print(\"   metric: {}\".format(metric))\n    search_grid = {\n        \"lam\": np.logspace(np.log10(0.01), np.log10(1.0), num=100, endpoint=True),\n        \"init_method\": [\"cov\"],\n        \"score_metric\": [metric],\n    }\n    model = GridSearchCV(QuicGraphicalLasso(), search_grid, cv=num_folds, refit=True)\n    model.fit(X)\n    bmodel = model.best_estimator_\n    print(\"   len(cv_lams): {}\".format(len(search_grid[\"lam\"])))\n    print(\"   cv-lam: {}\".format(model.best_params_[\"lam\"]))\n    print(\"   lam_scale_: {}\".format(bmodel.lam_scale_))\n    print(\"   lam_: {}\".format(bmodel.lam_))\n    return bmodel.covariance_, bmodel.precision_, bmodel.lam_",
    "docstring": "Run QuicGraphicalLasso with mode='default' and use standard scikit\n    GridSearchCV to find the best lambda.\n\n    Primarily demonstrates compatibility with existing scikit tooling."
  },
  {
    "code": "def load_calibration(labware: Labware):\n    calibration_path = CONFIG['labware_calibration_offsets_dir_v4']\n    labware_offset_path = calibration_path/'{}.json'.format(labware._id)\n    if labware_offset_path.exists():\n        calibration_data = _read_file(str(labware_offset_path))\n        offset_array = calibration_data['default']['offset']\n        offset = Point(x=offset_array[0], y=offset_array[1], z=offset_array[2])\n        labware.set_calibration(offset)\n        if 'tipLength' in calibration_data.keys():\n            tip_length = calibration_data['tipLength']['length']\n            labware.tip_length = tip_length",
    "docstring": "Look up a calibration if it exists and apply it to the given labware."
  },
  {
    "code": "def _detect_categorical_columns(self,data):\n        numeric_cols = set(data._get_numeric_data().columns.values)\n        date_cols = set(data.select_dtypes(include=[np.datetime64]).columns)\n        likely_cat = set(data.columns) - numeric_cols\n        likely_cat = list(likely_cat - date_cols)\n        for var in data._get_numeric_data().columns:\n            likely_flag = 1.0 * data[var].nunique()/data[var].count() < 0.05\n            if likely_flag:\n                 likely_cat.append(var)\n        return likely_cat",
    "docstring": "Detect categorical columns if they are not specified.\n\n        Parameters\n        ----------\n            data : pandas DataFrame\n                The input dataset.\n\n        Returns\n        ----------\n            likely_cat : list\n                List of variables that appear to be categorical."
  },
  {
    "code": "def delete_genelist(list_id, case_id=None):\n    if case_id:\n        case_obj = app.db.case(case_id)\n        app.db.remove_genelist(list_id, case_obj=case_obj)\n        return redirect(request.referrer)\n    else:\n        app.db.remove_genelist(list_id)\n        return redirect(url_for('.index'))",
    "docstring": "Delete a whole gene list with links to cases or a link."
  },
  {
    "code": "def parse_string(self, xmlstr, initialize=True):\n        try:\n            domtree = minidom.parseString(xmlstr)\n        except xml.parsers.expat.ExpatError, e:\n            raise ManifestXMLParseError(e)\n        self.load_dom(domtree, initialize)",
    "docstring": "Load manifest from XML string"
  },
  {
    "code": "def get_items_by_id(self, jid, node, ids):\n        iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET)\n        iq.payload = pubsub_xso.Request(\n            pubsub_xso.Items(node)\n        )\n        iq.payload.payload.items = [\n            pubsub_xso.Item(id_)\n            for id_ in ids\n        ]\n        if not iq.payload.payload.items:\n            raise ValueError(\"ids must not be empty\")\n        return (yield from self.client.send(iq))",
    "docstring": "Request specific items by their IDs from a node.\n\n        :param jid: Address of the PubSub service.\n        :type jid: :class:`aioxmpp.JID`\n        :param node: Name of the PubSub node to query.\n        :type node: :class:`str`\n        :param ids: The item IDs to return.\n        :type ids: :class:`~collections.abc.Iterable` of :class:`str`\n        :raises aioxmpp.errors.XMPPError: as returned by the service\n        :return: The response from the service\n        :rtype: :class:`.xso.Request`\n\n        `ids` must be an iterable of :class:`str` of the IDs of the items to\n        request from the pubsub node. If the iterable is empty,\n        :class:`ValueError` is raised (as otherwise, the request would be\n        identical to calling :meth:`get_items` without `max_items`).\n\n        Return the :class:`.xso.Request` object, which has a\n        :class:`~.xso.Items` :attr:`~.xso.Request.payload`."
  },
  {
    "code": "def parse_key_curve(value=None):\n    if isinstance(value, ec.EllipticCurve):\n        return value\n    if value is None:\n        return ca_settings.CA_DEFAULT_ECC_CURVE\n    curve = getattr(ec, value.strip(), type)\n    if not issubclass(curve, ec.EllipticCurve):\n        raise ValueError('%s: Not a known Eliptic Curve' % value)\n    return curve()",
    "docstring": "Parse an elliptic curve value.\n\n    This function uses a value identifying an elliptic curve to return an\n    :py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` instance. The name must match a\n    class name of one of the classes named under \"Elliptic Curves\" in\n    :any:`cg:hazmat/primitives/asymmetric/ec`.\n\n    For convenience, passing ``None`` will return the value of :ref:`CA_DEFAULT_ECC_CURVE\n    <settings-ca-default-ecc-curve>`, and passing an\n    :py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` will return that instance\n    unchanged.\n\n    Example usage::\n\n        >>> parse_key_curve('SECP256R1')  # doctest: +ELLIPSIS\n        <cryptography.hazmat.primitives.asymmetric.ec.SECP256R1 object at ...>\n        >>> parse_key_curve('SECP384R1')  # doctest: +ELLIPSIS\n        <cryptography.hazmat.primitives.asymmetric.ec.SECP384R1 object at ...>\n        >>> parse_key_curve(ec.SECP256R1())  # doctest: +ELLIPSIS\n        <cryptography.hazmat.primitives.asymmetric.ec.SECP256R1 object at ...>\n        >>> parse_key_curve()  # doctest: +ELLIPSIS\n        <cryptography.hazmat.primitives.asymmetric.ec.SECP256R1 object at ...>\n\n    Parameters\n    ----------\n\n    value : str, otional\n        The name of the curve or ``None`` to return the default curve.\n\n    Returns\n    -------\n\n    curve\n        An :py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` instance.\n\n    Raises\n    ------\n\n    ValueError\n        If the named curve is not supported."
  },
  {
    "code": "def _get_snapshot(name, suffix, array):\n    snapshot = name + '.' + suffix\n    try:\n        for snap in array.get_volume(name, snap=True):\n            if snap['name'] == snapshot:\n                return snapshot\n    except purestorage.PureError:\n        return None",
    "docstring": "Private function to check snapshot"
  },
  {
    "code": "def corr_dw_v1(self):\n    con = self.parameters.control.fastaccess\n    der = self.parameters.derived.fastaccess\n    flu = self.sequences.fluxes.fastaccess\n    old = self.sequences.states.fastaccess_old\n    new = self.sequences.states.fastaccess_new\n    idx = der.toy[self.idx_sim]\n    if (con.maxdw[idx] > 0.) and ((old.w-new.w) > con.maxdw[idx]):\n        new.w = old.w-con.maxdw[idx]\n        self.interp_v()\n        flu.qa = flu.qz+(old.v-new.v)/der.seconds",
    "docstring": "Adjust the water stage drop to the highest value allowed and correct\n    the associated fluxes.\n\n    Note that method |corr_dw_v1| calls the method `interp_v` of the\n    respective application model.  Hence the requirements of the actual\n    `interp_v` need to be considered additionally.\n\n    Required control parameter:\n      |MaxDW|\n\n    Required derived parameters:\n      |llake_derived.TOY|\n      |Seconds|\n\n    Required flux sequence:\n      |QZ|\n\n    Updated flux sequence:\n      |llake_fluxes.QA|\n\n    Updated state sequences:\n      |llake_states.W|\n      |llake_states.V|\n\n    Basic Restriction:\n      :math:`W_{old} - W_{new} \\\\leq MaxDW`\n\n    Examples:\n\n        In preparation for the following examples, define a short simulation\n        time period with a simulation step size of 12 hours and initialize\n        the required model object:\n\n        >>> from hydpy import pub\n        >>> pub.timegrids = '2000.01.01', '2000.01.04', '12h'\n        >>> from hydpy.models.llake import *\n        >>> parameterstep('1d')\n        >>> derived.toy.update()\n        >>> derived.seconds.update()\n\n        Select the first half of the second day of January as the simulation\n        step relevant for the following examples:\n\n        >>> model.idx_sim = pub.timegrids.init['2000.01.02']\n\n        The following tests are based on method |interp_v_v1| for the\n        interpolation of the stored water volume based on the corrected\n        water stage:\n\n        >>> model.interp_v = model.interp_v_v1\n\n        For the sake of simplicity, the underlying `w`-`v` relationship is\n        assumed to be linear:\n\n        >>> n(2.)\n        >>> w(0., 1.)\n        >>> v(0., 1e6)\n\n        The maximum drop in water stage for the first half of the second\n        day of January is set to 0.4 m/d.  Note that, due to the difference\n        between the parameter step size and the simulation step size, the\n        actual value used for calculation is 0.2 m/12h:\n\n        >>> maxdw(_1_1_18=.1,\n        ...       _1_2_6=.4,\n        ...       _1_2_18=.1)\n        >>> maxdw\n        maxdw(toy_1_1_18_0_0=0.1,\n              toy_1_2_6_0_0=0.4,\n              toy_1_2_18_0_0=0.1)\n        >>> from hydpy import round_\n        >>> round_(maxdw.value[2])\n        0.2\n\n        Define old and new water stages and volumes in agreement with the\n        given linear relationship:\n\n        >>> states.w.old = 1.\n        >>> states.v.old = 1e6\n        >>> states.w.new = .9\n        >>> states.v.new = 9e5\n\n        Also define an inflow and an outflow value.  Note the that the latter\n        is set to zero, which is inconsistent with the actual water stage drop\n        defined above, but done for didactic reasons:\n\n        >>> fluxes.qz = 1.\n        >>> fluxes.qa = 0.\n\n        Calling the |corr_dw_v1| method does not change the values of\n        either of following sequences, as the actual drop (0.1 m/12h) is\n        smaller than the allowed drop (0.2 m/12h):\n\n        >>> model.corr_dw_v1()\n        >>> states.w\n        w(0.9)\n        >>> states.v\n        v(900000.0)\n        >>> fluxes.qa\n        qa(0.0)\n\n        Note that the values given above are not recalculated, which can\n        clearly be seen for the lake outflow, which is still zero.\n\n        Through setting the new value of the water stage to 0.6 m, the actual\n        drop (0.4 m/12h) exceeds the allowed drop (0.2 m/12h). Hence the\n        water stage is trimmed and the other values are recalculated:\n\n        >>> states.w.new = .6\n        >>> model.corr_dw_v1()\n        >>> states.w\n        w(0.8)\n        >>> states.v\n        v(800000.0)\n        >>> fluxes.qa\n        qa(5.62963)\n\n        Through setting the maximum water stage drop to zero, method\n        |corr_dw_v1| is effectively disabled.  Regardless of the actual\n        change in water stage, no trimming or recalculating is performed:\n\n        >>> maxdw.toy_01_02_06 = 0.\n        >>> states.w.new = .6\n        >>> model.corr_dw_v1()\n        >>> states.w\n        w(0.6)\n        >>> states.v\n        v(800000.0)\n        >>> fluxes.qa\n        qa(5.62963)"
  },
  {
    "code": "def get_initial_centroids(self):\n        if self.seed is not None:\n            np.random.seed(self.seed)\n        n = self.data.shape[0]\n        rand_indices = np.random.randint(0, n, self.k)\n        centroids = self.data[rand_indices,:].toarray()\n        self.centroids=centroids\n        return centroids",
    "docstring": "Randomly choose k data points as initial centroids"
  },
  {
    "code": "def bind(self, func: Callable[[Any], 'Writer']) -> 'Writer':\n        a, w = self.run()\n        b, w_ = func(a).run()\n        if isinstance(w_, Monoid):\n            w__ = cast(Monoid, w).append(w_)\n        else:\n            w__ = w + w_\n        return Writer(b, w__)",
    "docstring": "Flat is better than nested.\n\n        Haskell:\n        (Writer (x, v)) >>= f = let\n            (Writer (y, v')) = f x in Writer (y, v `append` v')"
  },
  {
    "code": "def _reset (self):\n        self.entries = []\n        self.default_entry = None\n        self.disallow_all = False\n        self.allow_all = False\n        self.last_checked = 0\n        self.sitemap_urls = []",
    "docstring": "Reset internal flags and entry lists."
  },
  {
    "code": "def cosine_similarity(evaluated_model, reference_model):\n    if not (isinstance(evaluated_model, TfModel) and isinstance(reference_model, TfModel)):\n        raise ValueError(\n            \"Arguments has to be instances of 'sumy.models.TfDocumentModel'\")\n    terms = frozenset(evaluated_model.terms) | frozenset(reference_model.terms)\n    numerator = 0.0\n    for term in terms:\n        numerator += evaluated_model.term_frequency(term) * reference_model.term_frequency(term)\n    denominator = evaluated_model.magnitude * reference_model.magnitude\n    if denominator == 0.0:\n        raise ValueError(\"Document model can't be empty. Given %r & %r\" % (\n            evaluated_model, reference_model))\n    return numerator / denominator",
    "docstring": "Computes cosine similarity of two text documents. Each document\n    has to be represented as TF model of non-empty document.\n\n    :returns float:\n        0 <= cos <= 1, where 0 means independence and 1 means\n        exactly the same."
  },
  {
    "code": "def make_regression(func, n_samples=100, n_features=1, bias=0.0, noise=0.0,\n                    random_state=None):\n    generator = check_random_state(random_state)\n    X = generator.randn(n_samples, n_features)\n    y = func(*X.T) + bias\n    if noise > 0.0:\n        y += generator.normal(scale=noise, size=y.shape)\n    return X, y",
    "docstring": "Make dataset for a regression problem.\n\n    Examples\n    --------\n    >>> f = lambda x: 0.5*x + np.sin(2*x)\n    >>> X, y = make_regression(f, bias=.5, noise=1., random_state=1)\n    >>> X.shape\n    (100, 1)\n    >>> y.shape\n    (100,)\n    >>> X[:5].round(2)\n    array([[ 1.62],\n           [-0.61],\n           [-0.53],\n           [-1.07],\n           [ 0.87]])\n    >>> y[:5].round(2)\n    array([ 0.76,  0.48, -0.23, -0.28,  0.83])"
  },
  {
    "code": "def download(url, target_file, chunk_size=4096):\n    r = requests.get(url, stream=True)\n    with open(target_file, 'w+') as out:\n        with click.progressbar(r.iter_content(chunk_size=chunk_size),\n                               int(r.headers['Content-Length'])/chunk_size,\n                               label='Downloading...') as chunks:\n            for chunk in chunks:\n                out.write(chunk)",
    "docstring": "Simple requests downloader"
  },
  {
    "code": "def numlistbetween(num1, num2, option='list', listoption='string'):\n    if option == 'list':\n        if listoption == 'string':\n            output = ''\n            output += str(num1)\n            for currentnum in range(num1 + 1, num2 + 1):\n                output += ','\n                output += str(currentnum)\n        elif listoption == 'list':\n            output = []\n            for currentnum in range(num1, num2 + 1):\n                output.append(str(currentnum))\n            return output\n    elif option == 'count':\n        return num2 - num1",
    "docstring": "List Or Count The Numbers Between Two Numbers"
  },
  {
    "code": "def diffusion_mds(means, weights, d, diffusion_rounds=10):\n    for i in range(diffusion_rounds):\n        weights = weights*weights\n        weights = weights/weights.sum(0)\n    X = dim_reduce(means, weights, d)\n    if X.shape[0]==2:\n        return X.dot(weights)\n    else:\n        return X.T.dot(weights)",
    "docstring": "Dimensionality reduction using MDS, while running diffusion on W.\n\n    Args:\n        means (array): genes x clusters\n        weights (array): clusters x cells\n        d (int): desired dimensionality\n\n    Returns:\n        W_reduced (array): array of shape (d, cells)"
  },
  {
    "code": "def pkdecrypt(self, conn):\n        for msg in [b'S INQUIRE_MAXLEN 4096', b'INQUIRE CIPHERTEXT']:\n            keyring.sendline(conn, msg)\n        line = keyring.recvline(conn)\n        assert keyring.recvline(conn) == b'END'\n        remote_pubkey = parse_ecdh(line)\n        identity = self.get_identity(keygrip=self.keygrip)\n        ec_point = self.client.ecdh(identity=identity, pubkey=remote_pubkey)\n        keyring.sendline(conn, b'D ' + _serialize_point(ec_point))",
    "docstring": "Handle decryption using ECDH."
  },
  {
    "code": "def _get_go2nt(self, goids):\n        go2nt_all = self.grprobj.go2nt\n        return {go:go2nt_all[go] for go in goids}",
    "docstring": "Get go2nt for given goids."
  },
  {
    "code": "def import_obj(clsname, default_module=None):\n    if default_module is not None:\n        if not clsname.startswith(default_module + '.'):\n            clsname = '{0}.{1}'.format(default_module, clsname)\n    mod, clsname = clsname.rsplit('.', 1)\n    mod = importlib.import_module(mod)\n    try:\n        obj = getattr(mod, clsname)\n    except AttributeError:\n        raise ImportError('Cannot import {0} from {1}'.format(clsname, mod))\n    return obj",
    "docstring": "Import the object given by clsname.\n    If default_module is specified, import from this module."
  },
  {
    "code": "def schema_from_table(table, schema=None):\n    schema = schema if schema is not None else {}\n    pairs = []\n    for name, column in table.columns.items():\n        if name in schema:\n            dtype = dt.dtype(schema[name])\n        else:\n            dtype = dt.dtype(\n                getattr(table.bind, 'dialect', SQLAlchemyDialect()),\n                column.type,\n                nullable=column.nullable,\n            )\n        pairs.append((name, dtype))\n    return sch.schema(pairs)",
    "docstring": "Retrieve an ibis schema from a SQLAlchemy ``Table``.\n\n    Parameters\n    ----------\n    table : sa.Table\n\n    Returns\n    -------\n    schema : ibis.expr.datatypes.Schema\n        An ibis schema corresponding to the types of the columns in `table`."
  },
  {
    "code": "def _record(self):\n        return struct.pack(self.FMT, 1, self.platform_id, 0, self.id_string,\n                           self.checksum, 0x55, 0xaa)",
    "docstring": "An internal method to generate a string representing this El Torito\n        Validation Entry.\n\n        Parameters:\n         None.\n        Returns:\n         String representing this El Torito Validation Entry."
  },
  {
    "code": "def _get_retrier(self, receiver: Address) -> _RetryQueue:\n        if receiver not in self._address_to_retrier:\n            retrier = _RetryQueue(transport=self, receiver=receiver)\n            self._address_to_retrier[receiver] = retrier\n            retrier.start()\n        return self._address_to_retrier[receiver]",
    "docstring": "Construct and return a _RetryQueue for receiver"
  },
  {
    "code": "def _limited_iterator(self):\n        i = 0\n        while True:\n            for crash_id in self._basic_iterator():\n                if self._filter_disallowed_values(crash_id):\n                    continue\n                if crash_id is None:\n                    yield crash_id\n                    continue\n                if i == int(self.config.number_of_submissions):\n                    break\n                i += 1\n                yield crash_id\n            if i == int(self.config.number_of_submissions):\n                break",
    "docstring": "this is the iterator for the case when \"number_of_submissions\" is\n        set to an integer.  It goes through the innermost iterator exactly the\n        number of times specified by \"number_of_submissions\"  To do that, it\n        might run the innermost iterator to exhaustion.  If that happens, that\n        innermost iterator is called again to start over.  It is up to the\n        implementation of the innermost iteration to define what starting\n        over means.  Some iterators may repeat exactly what they did before,\n        while others may iterate over new values"
  },
  {
    "code": "def get_hash(self):\n        depencency_hashes = [dep.get_hash() for dep in self.dep()]\n        sl = inspect.getsourcelines\n        hash_sources = [sl(self.__class__), self.args,\n                        self.kwargs, *depencency_hashes]\n        hash_input = pickle.dumps(hash_sources)\n        return hashlib.md5(hash_input).hexdigest()",
    "docstring": "Retruns a hash based on the the current table code and kwargs.\n        Also changes based on dependent tables."
  },
  {
    "code": "def _serialize_items(self, serializer, kind, items):\n        if self.request and self.request.query_params.get('hydrate_{}'.format(kind), False):\n            serializer = serializer(items, many=True, read_only=True)\n            serializer.bind(kind, self)\n            return serializer.data\n        else:\n            return [item.id for item in items]",
    "docstring": "Return serialized items or list of ids, depending on `hydrate_XXX` query param."
  },
  {
    "code": "def render_configuration(self, configuration=None):\n        if configuration is None:\n            configuration = self.environment\n        if isinstance(configuration, dict):\n            return {k: self.render_configuration(v) for k, v in configuration.items()}\n        elif isinstance(configuration, list):\n            return [self.render_configuration(x) for x in configuration]\n        elif isinstance(configuration, Variable):\n            return configuration.resolve(self.parameters)\n        else:\n            return configuration",
    "docstring": "Render variables in configuration object but don't instantiate anything"
  },
  {
    "code": "def packages(self, login=None, platform=None, package_type=None,\n                 type_=None, access=None):\n        logger.debug('')\n        method = self._anaconda_client_api.user_packages\n        return self._create_worker(method, login=login, platform=platform,\n                                   package_type=package_type,\n                                   type_=type_, access=access)",
    "docstring": "Return all the available packages for a given user.\n\n        Parameters\n        ----------\n        type_: Optional[str]\n            Only find packages that have this conda `type`, (i.e. 'app').\n        access : Optional[str]\n            Only find packages that have this access level (e.g. 'private',\n            'authenticated', 'public')."
  },
  {
    "code": "def check_errors(self, response, data):\n        if \"error_id\" in data:\n            error_id = data[\"error_id\"]\n            if error_id in self.error_ids:\n                raise self.error_ids[error_id](response)\n        if \"error_code\" in data:\n            error_code = data[\"error_code\"]\n            if error_code in self.error_codes:\n                raise self.error_codes[error_code](response)\n        if \"error_code\" in data or \"error_id\" in data:\n            raise AppNexusException(response)",
    "docstring": "Check for errors and raise an appropriate error if needed"
  },
  {
    "code": "def update(self):\n        from .link import Link\n        diff = self.diff()\n        status = {\n            'added': 'active',\n            'removed': 'disconnected',\n            'changed': 'active'\n        }\n        for section in ['added', 'removed', 'changed']:\n            if not diff[section]:\n                continue\n            for link_dict in diff[section]['links']:\n                try:\n                    link = Link.get_or_create(source=link_dict['source'],\n                                              target=link_dict['target'],\n                                              cost=link_dict['cost'],\n                                              topology=self)\n                except (LinkDataNotFound, ValidationError) as e:\n                    msg = 'Exception while updating {0}'.format(self.__repr__())\n                    logger.exception(msg)\n                    print('{0}\\n{1}\\n'.format(msg, e))\n                    continue\n                link.ensure(status=status[section],\n                            cost=link_dict['cost'])",
    "docstring": "Updates topology\n        Links are not deleted straightaway but set as \"disconnected\""
  },
  {
    "code": "def auto_detect(self, args):\n        suffixes = [\n            \".tgz\",\n            \".txz\",\n            \".tbz\",\n            \".tlz\"\n        ]\n        if (not args[0].startswith(\"-\") and args[0] not in self.commands and\n                args[0].endswith(tuple(suffixes))):\n            packages, not_found = [], []\n            for pkg in args:\n                if pkg.endswith(tuple(suffixes)):\n                    if os.path.isfile(pkg):\n                        packages.append(pkg)\n                    else:\n                        not_found.append(pkg)\n            if packages:\n                Auto(packages).select()\n            if not_found:\n                for ntf in not_found:\n                    self.msg.pkg_not_found(\"\", ntf, \"Not installed\", \"\")\n            raise SystemExit()",
    "docstring": "Check for already Slackware binary packages exist"
  },
  {
    "code": "def find_spec(self, fullname, path, target=None):\n        if fullname.startswith(self.package_prefix):\n            for path in self._get_paths(fullname):\n                if os.path.exists(path):\n                    return ModuleSpec(\n                        name=fullname,\n                        loader=self.loader_class(fullname, path),\n                        origin=path,\n                        is_package=(path.endswith('__init__.ipynb') or path.endswith('__init__.py')),\n                    )",
    "docstring": "Claims modules that are under ipynb.fs"
  },
  {
    "code": "def parse_numtuple(s,intype,length=2,scale=1):\n    if intype == int:\n        numrx = intrx_s;\n    elif intype == float:\n        numrx = fltrx_s;\n    else:\n        raise NotImplementedError(\"Not implemented for type: {}\".format(\n            intype));\n    if parse_utuple(s, numrx, length=length) is None:\n        raise ValueError(\"{} is not a valid number tuple.\".format(s));\n    return [x*scale for x in evalt(s)];",
    "docstring": "parse a string into a list of numbers of a type"
  },
  {
    "code": "def get_choices(self):\n        if 'choiceInfo' not in self.dto[self.name]:\n            raise GPException('not a choice parameter')\n        if self.get_choice_status()[1] == \"NOT_INITIALIZED\":\n            print(self.get_choice_status())\n            print(\"choice status not initialized\")\n            request = urllib.request.Request(self.get_choice_href())\n            if self.task.server_data.authorization_header() is not None:\n                request.add_header('Authorization', self.task.server_data.authorization_header())\n            request.add_header('User-Agent', 'GenePatternRest')\n            response = urllib.request.urlopen(request)\n            self.dto[self.name]['choiceInfo'] = json.loads(response.read().decode('utf-8'))\n        return self.dto[self.name]['choiceInfo']['choices']",
    "docstring": "Returns a list of dictionary objects, one dictionary object per choice.\n\n        Each object has two keys defined: 'value', 'label'.\n        The 'label' entry is what should be displayed on the UI, the 'value' entry\n        is what is written into GPJobSpec."
  },
  {
    "code": "def run_parallel(self):\n        try:\n            self.start_parallel()\n            result = self.empty_result(*self.context)\n            while self.num_processes > 0:\n                r = self.result_queue.get()\n                self.maybe_put_task()\n                if r is POISON_PILL:\n                    self.num_processes -= 1\n                elif isinstance(r, ExceptionWrapper):\n                    r.reraise()\n                else:\n                    result = self.process_result(r, result)\n                    self.progress.update(1)\n                    if self.done:\n                        self.complete.set()\n            self.finish_parallel()\n        except Exception:\n            raise\n        finally:\n            log.debug('Removing progress bar')\n            self.progress.close()\n        return result",
    "docstring": "Perform the computation in parallel, reading results from the output\n        queue and passing them to ``process_result``."
  },
  {
    "code": "def parent(self):\n        family = self.repository.get_parent_package_family(self.resource)\n        return PackageFamily(family) if family else None",
    "docstring": "Get the parent package family.\n\n        Returns:\n            `PackageFamily`."
  },
  {
    "code": "def _get_application(self, subdomain):\n        with self.lock:\n            app = self.instances.get(subdomain)\n            if app is None:\n                app = self.create_application(subdomain=subdomain)\n                self.instances[subdomain] = app\n            return app",
    "docstring": "Return a WSGI application for subdomain.  The subdomain is\n        passed to the create_application constructor as a keyword argument.\n\n        :param subdomain: Subdomain to get or create an application with"
  },
  {
    "code": "def add_ui(self, klass, *args, **kwargs):\n        ui = klass(self.widget, *args, **kwargs)\n        self.widget.uis.append(ui)\n        return ui",
    "docstring": "Add an UI element for the current scene. The approach is\n        the same as renderers.\n\n        .. warning:: The UI api is not yet finalized"
  },
  {
    "code": "def i2c_monitor_read(self):\n        data = array.array('H', (0,) * self.BUFFER_SIZE)\n        ret = api.py_aa_i2c_monitor_read(self.handle, self.BUFFER_SIZE,\n                data)\n        _raise_error_if_negative(ret)\n        del data[ret:]\n        return data.tolist()",
    "docstring": "Retrieved any data fetched by the monitor.\n\n        This function has an integrated timeout mechanism. You should use\n        :func:`poll` to determine if there is any data available.\n\n        Returns a list of data bytes and special symbols. There are three\n        special symbols: `I2C_MONITOR_NACK`, I2C_MONITOR_START and\n        I2C_MONITOR_STOP."
  },
  {
    "code": "def command_exists(command, noop_invocation, exc_msg):\n    try:\n        found = bool(shutil.which(command))\n    except AttributeError:\n        try:\n            p = subprocess.Popen(noop_invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n        except OSError:\n            found = False\n        else:\n            stdout, stderr = p.communicate()\n            found = p.returncode == 0\n            if not found:\n                logger.error(\"`%s` exited with a non-zero return code (%s)\",\n                             noop_invocation, p.returncode)\n                logger.error(\"command stdout = %s\", stdout)\n                logger.error(\"command stderr = %s\", stderr)\n    if not found:\n        raise CommandDoesNotExistException(exc_msg)\n    return True",
    "docstring": "Verify that the provided command exists. Raise CommandDoesNotExistException in case of an\n    error or if the command does not exist.\n\n    :param command: str, command to check (python 3 only)\n    :param noop_invocation: list of str, command to check (python 2 only)\n    :param exc_msg: str, message of exception when command does not exist\n    :return: bool, True if everything's all right (otherwise exception is thrown)"
  },
  {
    "code": "def createLinkToSelf(self, new_zone, callback=None, errback=None,\n                         **kwargs):\n        zone = Zone(self.config, new_zone)\n        kwargs['link'] = self.data['zone']\n        return zone.create(callback=callback, errback=errback, **kwargs)",
    "docstring": "Create a new linked zone, linking to ourselves. All records in this\n        zone will then be available as \"linked records\" in the new zone.\n\n        :param str new_zone: the new zone name to link to this one\n        :return: new Zone"
  },
  {
    "code": "def _process_underscores(self, tokens):\n        \"Strip underscores to make sure the number is correct after join\"\n        groups = [[str(''.join(el))] if b else list(el)\n                  for (b,el) in itertools.groupby(tokens, lambda k: k=='_')]\n        flattened = [el for group in groups for el in group]\n        processed = []\n        for token in flattened:\n            if token == '_':  continue\n            if token.startswith('_'):\n                token = str(token[1:])\n            if token.endswith('_'):\n                token = str(token[:-1])\n            processed.append(token)\n        return processed",
    "docstring": "Strip underscores to make sure the number is correct after join"
  },
  {
    "code": "def linkify(self, timeperiods):\n        new_exclude = []\n        if hasattr(self, 'exclude') and self.exclude != []:\n            logger.debug(\"[timeentry::%s] have excluded %s\", self.get_name(), self.exclude)\n            excluded_tps = self.exclude\n            for tp_name in excluded_tps:\n                timepriod = timeperiods.find_by_name(tp_name.strip())\n                if timepriod is not None:\n                    new_exclude.append(timepriod.uuid)\n                else:\n                    msg = \"[timeentry::%s] unknown %s timeperiod\" % (self.get_name(), tp_name)\n                    self.add_error(msg)\n        self.exclude = new_exclude",
    "docstring": "Will make timeperiod in exclude with id of the timeperiods\n\n        :param timeperiods: Timeperiods object\n        :type timeperiods:\n        :return: None"
  },
  {
    "code": "def is_read_only(cls,\n                     db: DATABASE_SUPPORTER_FWD_REF,\n                     logger: logging.Logger = None) -> bool:\n        def convert_enums(row_):\n            return [True if x == 'Y' else (False if x == 'N' else None)\n                    for x in row_]\n        try:\n            sql =\n            rows = db.fetchall(sql)\n            for row in rows:\n                dbname = row[0]\n                prohibited = convert_enums(row[1:])\n                if any(prohibited):\n                    if logger:\n                        logger.debug(\n                            \"MySQL.is_read_only(): FAIL: database privileges \"\n                            \"wrong: dbname={}, prohibited={}\".format(\n                                dbname, prohibited\n                            )\n                        )\n                    return False\n        except mysql.OperationalError:\n            pass\n        try:\n            sql =\n            rows = db.fetchall(sql)\n            if not rows or len(rows) > 1:\n                return False\n            prohibited = convert_enums(rows[0])\n            if any(prohibited):\n                if logger:\n                    logger.debug(\n                        \"MySQL.is_read_only(): FAIL: GLOBAL privileges \"\n                        \"wrong: prohibited={}\".format(prohibited))\n                return False\n        except mysql.OperationalError:\n            pass\n        return True",
    "docstring": "Do we have read-only access?"
  },
  {
    "code": "def get_disk_quota(username, machine_name=None):\n    try:\n        ua = Account.objects.get(\n            username=username,\n            date_deleted__isnull=True)\n    except Account.DoesNotExist:\n        return 'Account not found'\n    result = ua.get_disk_quota()\n    if result is None:\n        return False\n    return result * 1048576",
    "docstring": "Returns disk quota for username in KB"
  },
  {
    "code": "def get_file_name(url):\n  return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'",
    "docstring": "Returns file name of file at given url."
  },
  {
    "code": "def ls(self):\n        if self.isfile():\n            raise NotDirectoryError('Cannot ls() on non-directory node: {path}'.format(path=self._pyerarchy_path))\n        return os.listdir(self._pyerarchy_path)",
    "docstring": "List the children entities of the directory.\n\n        Raises exception if the object is a file.\n\n        :return:"
  },
  {
    "code": "def set_all_attribute_values(self, value):\n        for attribute_name, type_instance in inspect.getmembers(self):\n            if attribute_name.startswith('__') or inspect.ismethod(type_instance):\n                continue\n            if isinstance(type_instance, bool):\n                self.__dict__[attribute_name] = value\n            elif isinstance(type_instance, self.__class__):\n                type_instance.set_all_attribute_values(value)",
    "docstring": "sets all the attribute values to the value and propagate to any children"
  },
  {
    "code": "def query_unbound_ong(self, base58_address: str) -> int:\n        contract_address = self.get_asset_address('ont')\n        unbound_ong = self.__sdk.rpc.get_allowance(\"ong\", Address(contract_address).b58encode(), base58_address)\n        return int(unbound_ong)",
    "docstring": "This interface is used to query the amount of account's unbound ong.\n\n        :param base58_address: a base58 encode address which indicate which account's unbound ong we want to query.\n        :return: the amount of unbound ong in the form of int."
  },
  {
    "code": "def parse_networking_file():\n    pairs = dict()\n    allocated_subnets = []\n    try:\n        with open(VMWARE_NETWORKING_FILE, \"r\", encoding=\"utf-8\") as f:\n            version = f.readline()\n            for line in f.read().splitlines():\n                try:\n                    _, key, value = line.split(' ', 3)\n                    key = key.strip()\n                    value = value.strip()\n                    pairs[key] = value\n                    if key.endswith(\"HOSTONLY_SUBNET\"):\n                        allocated_subnets.append(value)\n                except ValueError:\n                    raise SystemExit(\"Error while parsing {}\".format(VMWARE_NETWORKING_FILE))\n    except OSError as e:\n        raise SystemExit(\"Cannot open {}: {}\".format(VMWARE_NETWORKING_FILE, e))\n    return version, pairs, allocated_subnets",
    "docstring": "Parse the VMware networking file."
  },
  {
    "code": "def pprint_tree_differences(self, missing_pys, missing_docs):\n        if missing_pys:\n            print('The following Python files appear to be missing:')\n            for pyfile in missing_pys:\n                print(pyfile)\n            print('\\n')\n        if missing_docs:\n            print('The following documentation files appear to be missing:')\n            for docfiile in missing_docs:\n                print(docfiile)\n            print('\\n')",
    "docstring": "Pprint the missing files of each given set.\n\n        :param set missing_pys: The set of missing Python files.\n        :param set missing_docs: The set of missing documentation files.\n        :rtype: None"
  },
  {
    "code": "def circular_gaussian_kernel(sd,radius):\n    i,j = np.mgrid[-radius:radius+1,-radius:radius+1].astype(float) / radius\n    mask = i**2 + j**2 <= 1\n    i = i * radius / sd\n    j = j * radius / sd\n    kernel = np.zeros((2*radius+1,2*radius+1))\n    kernel[mask] = np.e ** (-(i[mask]**2+j[mask]**2) /\n                            (2 * sd **2))\n    kernel = kernel / np.sum(kernel)\n    return kernel",
    "docstring": "Create a 2-d Gaussian convolution kernel\n    \n    sd     - standard deviation of the gaussian in pixels\n    radius - build a circular kernel that convolves all points in the circle\n             bounded by this radius"
  },
  {
    "code": "def get_edge_schema_element_or_raise(self, edge_classname):\n        schema_element = self.get_element_by_class_name_or_raise(edge_classname)\n        if not schema_element.is_edge:\n            raise InvalidClassError(u'Non-edge class provided: {}'.format(edge_classname))\n        return schema_element",
    "docstring": "Return the schema element with the given name, asserting that it's of edge type."
  },
  {
    "code": "def _write(self, text):\n        spaces = ' ' * (self.indent * self.indentlevel)\n        t = spaces + text.strip() + '\\n'\n        if hasattr(t, 'encode'):\n            t = t.encode(self.encoding, 'xmlcharrefreplace')\n        self.stream.write(t)",
    "docstring": "Write text by respecting the current indentlevel"
  },
  {
    "code": "def source_lines(self, filename):\n        with self.filesystem.open(filename) as f:\n            return f.readlines()",
    "docstring": "Return a list for source lines of file `filename`."
  },
  {
    "code": "def label_const(self, const:Any=0, label_cls:Callable=None, **kwargs)->'LabelList':\n        \"Label every item with `const`.\"\n        return self.label_from_func(func=lambda o: const, label_cls=label_cls, **kwargs)",
    "docstring": "Label every item with `const`."
  },
  {
    "code": "def calc_avr_uvr_v1(self):\n    con = self.parameters.control.fastaccess\n    der = self.parameters.derived.fastaccess\n    flu = self.sequences.fluxes.fastaccess\n    for i in range(2):\n        if flu.h <= (con.hm+der.hv[i]):\n            flu.avr[i] = 0.\n            flu.uvr[i] = 0.\n        else:\n            flu.avr[i] = (flu.h-(con.hm+der.hv[i]))**2*con.bnvr[i]/2.\n            flu.uvr[i] = (flu.h-(con.hm+der.hv[i]))*(1.+con.bnvr[i]**2)**.5",
    "docstring": "Calculate the flown through area and the wetted perimeter of both\n    outer embankments.\n\n    Note that each outer embankment lies beyond its foreland and that all\n    water flowing exactly above the a embankment is added to |AVR|.\n    The theoretical surface seperating water above the foreland from water\n    above its embankment is not contributing to |UVR|.\n\n    Required control parameters:\n      |HM|\n      |BNVR|\n\n    Required derived parameter:\n      |HV|\n\n    Required flux sequence:\n      |H|\n\n    Calculated flux sequence:\n      |AVR|\n      |UVR|\n\n    Examples:\n\n        Generally, right trapezoids are assumed.  Here, for simplicity, both\n        forelands are assumed to be symmetrical.  Their smaller bases (bottoms)\n        hava a length of 2 meters, their non-vertical legs show an inclination\n        of 1 meter per 4 meters, and their height (depths) is 1 meter.  Both\n        forelands lie 1 meter above the main channels bottom.\n\n        Generally, a triangles are assumed, with the vertical side\n        seperating the foreland from its outer embankment.  Here, for\n        simplicity, both forelands are assumed to be symmetrical.  Their\n        inclinations are 1 meter per 4 meters and their lowest point is\n        1 meter above the forelands bottom and 2 meters above the main\n        channels bottom:\n\n        >>> from hydpy.models.lstream import *\n        >>> parameterstep()\n        >>> hm(1.0)\n        >>> bnvr(4.0)\n        >>> derived.hv(1.0)\n\n        The first example deals with moderate high flow conditions, where\n        water flows over the forelands, but not over their outer embankments\n        (|HM| < |H| < (|HM| + |HV|)):\n\n        >>> fluxes.h = 1.5\n        >>> model.calc_avr_uvr_v1()\n        >>> fluxes.avr\n        avr(0.0, 0.0)\n        >>> fluxes.uvr\n        uvr(0.0, 0.0)\n\n        The second example deals with extreme high flow conditions, where\n        water flows over the both foreland and their outer embankments\n        ((|HM| + |HV|) < |H|):\n\n        >>> fluxes.h = 2.5\n        >>> model.calc_avr_uvr_v1()\n        >>> fluxes.avr\n        avr(0.5, 0.5)\n        >>> fluxes.uvr\n        uvr(2.061553, 2.061553)"
  },
  {
    "code": "def is_user_valid(self, userID):\n        cur = self.conn.cursor()\n        cur.execute('SELECT * FROM users WHERE id=? LIMIT 1', [userID])\n        results = cur.fetchall()\n        cur.close()\n        return len(results) > 0",
    "docstring": "Check if this User ID is valid."
  },
  {
    "code": "def pre_validate(self, form):\n        for preprocessor in self._preprocessors:\n            preprocessor(form, self)\n        super(FieldHelper, self).pre_validate(form)",
    "docstring": "Calls preprocessors before pre_validation"
  },
  {
    "code": "def identify(file_elements):\n    if not file_elements:\n        return\n    _validate_file_elements(file_elements)\n    iterator = PeekableIterator((element_i, element) for (element_i, element) in enumerate(file_elements)\n                                if element.type != elements.TYPE_METADATA)\n    try:\n        _, first_element = iterator.peek()\n        if isinstance(first_element, TableElement):\n            iterator.next()\n            yield AnonymousTable(first_element)\n    except KeyError:\n        pass\n    except StopIteration:\n        return\n    for element_i, element in iterator:\n        if not isinstance(element, TableHeaderElement):\n            continue\n        if not element.is_array_of_tables:\n            table_element_i, table_element = next(iterator)\n            yield Table(names=element.names, table_element=table_element)\n        else:\n            table_element_i, table_element = next(iterator)\n            yield ArrayOfTables(names=element.names, table_element=table_element)",
    "docstring": "Outputs an ordered sequence of instances of TopLevel types.\n\n    Elements start with an optional TableElement, followed by zero or more pairs of (TableHeaderElement, TableElement)."
  },
  {
    "code": "def _OpenPathSpec(self, path_specification, ascii_codepage='cp1252'):\n    if not path_specification:\n      return None\n    file_entry = self._file_system.GetFileEntryByPathSpec(path_specification)\n    if file_entry is None:\n      return None\n    file_object = file_entry.GetFileObject()\n    if file_object is None:\n      return None\n    registry_file = dfwinreg_regf.REGFWinRegistryFile(\n        ascii_codepage=ascii_codepage)\n    try:\n      registry_file.Open(file_object)\n    except IOError as exception:\n      logger.warning(\n          'Unable to open Windows Registry file with error: {0!s}'.format(\n              exception))\n      file_object.close()\n      return None\n    return registry_file",
    "docstring": "Opens the Windows Registry file specified by the path specification.\n\n    Args:\n      path_specification (dfvfs.PathSpec): path specification.\n      ascii_codepage (Optional[str]): ASCII string codepage.\n\n    Returns:\n      WinRegistryFile: Windows Registry file or None."
  },
  {
    "code": "def get_help_msg(self,\n                     dotspace_ending=False,\n                     **kwargs):\n        context = self.get_context_for_help_msgs(kwargs)\n        if self.help_msg is not None and len(self.help_msg) > 0:\n            context = copy(context)\n            try:\n                help_msg = self.help_msg\n                variables = re.findall(\"{\\S+}\", help_msg)\n                for v in set(variables):\n                    v = v[1:-1]\n                    if v in context and len(str(context[v])) > self.__max_str_length_displayed__:\n                        new_name = '@@@@' + v + '@@@@'\n                        help_msg = help_msg.replace('{' + v + '}', '{' + new_name + '}')\n                        context[new_name] = \"(too big for display)\"\n                help_msg = help_msg.format(**context)\n            except KeyError as e:\n                raise HelpMsgFormattingException(self.help_msg, e, context)\n            if dotspace_ending:\n                return end_with_dot_space(help_msg)\n            else:\n                return help_msg\n        else:\n            return ''",
    "docstring": "The method used to get the formatted help message according to kwargs. By default it returns the 'help_msg'\n        attribute, whether it is defined at the instance level or at the class level.\n\n        The help message is formatted according to help_msg.format(**kwargs), and may be terminated with a dot\n        and a space if dotspace_ending is set to True.\n\n        :param dotspace_ending: True will append a dot and a space at the end of the message if it is not\n        empty (default is False)\n        :param kwargs: keyword arguments to format the help message\n        :return: the formatted help message"
  },
  {
    "code": "def extern_drop_handles(self, context_handle, handles_ptr, handles_len):\n    c = self._ffi.from_handle(context_handle)\n    handles = self._ffi.unpack(handles_ptr, handles_len)\n    c.drop_handles(handles)",
    "docstring": "Drop the given Handles."
  },
  {
    "code": "def get_subgroupiteminsertion(\n            cls, itemgroup, model, subgroup, indent) -> str:\n        blanks1 = ' ' * (indent * 4)\n        blanks2 = ' ' * ((indent+5) * 4 + 1)\n        subs = [\n            f'{blanks1}<element name=\"{subgroup.name}\"',\n            f'{blanks1}         minOccurs=\"0\"',\n            f'{blanks1}         maxOccurs=\"unbounded\">',\n            f'{blanks1}    <complexType>',\n            f'{blanks1}        <sequence>',\n            f'{blanks1}            <element ref=\"hpcb:selections\"',\n            f'{blanks1}                     minOccurs=\"0\"/>',\n            f'{blanks1}            <element ref=\"hpcb:devices\"',\n            f'{blanks1}                     minOccurs=\"0\"/>']\n        seriesflags = (False,) if subgroup.name == 'control' else (False, True)\n        for variable in subgroup:\n            for series in seriesflags:\n                name = f'{variable.name}.series' if series else variable.name\n                subs.append(f'{blanks1}            <element name=\"{name}\"')\n                if itemgroup == 'setitems':\n                    subs.append(f'{blanks2}type=\"hpcb:setitemType\"')\n                elif itemgroup == 'getitems':\n                    subs.append(f'{blanks2}type=\"hpcb:getitemType\"')\n                else:\n                    subs.append(\n                        f'{blanks2}type=\"hpcb:{model.name}_mathitemType\"')\n                subs.append(f'{blanks2}minOccurs=\"0\"')\n                subs.append(f'{blanks2}maxOccurs=\"unbounded\"/>')\n        subs.extend([\n            f'{blanks1}        </sequence>',\n            f'{blanks1}    </complexType>',\n            f'{blanks1}</element>'])\n        return '\\n'.join(subs)",
    "docstring": "Return a string defining the required types for the given\n        combination of an exchange item group and a specific variable\n        subgroup of an application model or class |Node|.\n\n        Note that for `setitems` and `getitems` `setitemType` and\n        `getitemType` are referenced, respectively, and for all others\n        the model specific `mathitemType`:\n\n        >>> from hydpy import prepare_model\n        >>> model = prepare_model('hland_v1')\n        >>> from hydpy.auxs.xmltools import XSDWriter\n        >>> print(XSDWriter.get_subgroupiteminsertion(    # doctest: +ELLIPSIS\n        ...     'setitems', model, model.parameters.control, 1))\n            <element name=\"control\"\n                     minOccurs=\"0\"\n                     maxOccurs=\"unbounded\">\n                <complexType>\n                    <sequence>\n                        <element ref=\"hpcb:selections\"\n                                 minOccurs=\"0\"/>\n                        <element ref=\"hpcb:devices\"\n                                 minOccurs=\"0\"/>\n                        <element name=\"area\"\n                                 type=\"hpcb:setitemType\"\n                                 minOccurs=\"0\"\n                                 maxOccurs=\"unbounded\"/>\n                        <element name=\"nmbzones\"\n        ...\n                    </sequence>\n                </complexType>\n            </element>\n\n        >>> print(XSDWriter.get_subgroupiteminsertion(    # doctest: +ELLIPSIS\n        ...     'getitems', model, model.parameters.control, 1))\n            <element name=\"control\"\n        ...\n                        <element name=\"area\"\n                                 type=\"hpcb:getitemType\"\n                                 minOccurs=\"0\"\n                                 maxOccurs=\"unbounded\"/>\n        ...\n\n        >>> print(XSDWriter.get_subgroupiteminsertion(    # doctest: +ELLIPSIS\n        ...     'additems', model, model.parameters.control, 1))\n            <element name=\"control\"\n        ...\n                        <element name=\"area\"\n                                 type=\"hpcb:hland_v1_mathitemType\"\n                                 minOccurs=\"0\"\n                                 maxOccurs=\"unbounded\"/>\n        ...\n\n        For sequence classes, additional \"series\" elements are added:\n\n        >>> print(XSDWriter.get_subgroupiteminsertion(    # doctest: +ELLIPSIS\n        ...     'setitems', model, model.sequences.fluxes, 1))\n            <element name=\"fluxes\"\n        ...\n                        <element name=\"tmean\"\n                                 type=\"hpcb:setitemType\"\n                                 minOccurs=\"0\"\n                                 maxOccurs=\"unbounded\"/>\n                        <element name=\"tmean.series\"\n                                 type=\"hpcb:setitemType\"\n                                 minOccurs=\"0\"\n                                 maxOccurs=\"unbounded\"/>\n                        <element name=\"tc\"\n        ...\n                    </sequence>\n                </complexType>\n            </element>"
  },
  {
    "code": "def _maybe_restore_index_levels(self, result):\n        names_to_restore = []\n        for name, left_key, right_key in zip(self.join_names,\n                                             self.left_on,\n                                             self.right_on):\n            if (self.orig_left._is_level_reference(left_key) and\n                    self.orig_right._is_level_reference(right_key) and\n                    name not in result.index.names):\n                names_to_restore.append(name)\n        if names_to_restore:\n            result.set_index(names_to_restore, inplace=True)",
    "docstring": "Restore index levels specified as `on` parameters\n\n        Here we check for cases where `self.left_on` and `self.right_on` pairs\n        each reference an index level in their respective DataFrames. The\n        joined columns corresponding to these pairs are then restored to the\n        index of `result`.\n\n        **Note:** This method has side effects. It modifies `result` in-place\n\n        Parameters\n        ----------\n        result: DataFrame\n            merge result\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def validate(self):\n        super().validate()\n        message_dsm = 'Matrix at [%s:%s] is not an instance of '\\\n                      'DesignStructureMatrix or MultipleDomainMatrix.'\n        message_ddm = 'Matrix at [%s:%s] is not an instance of '\\\n                      'DomainMappingMatrix or MultipleDomainMatrix.'\n        messages = []\n        for i, row in enumerate(self.data):\n            for j, cell in enumerate(row):\n                if i == j:\n                    if not isinstance(cell, (\n                            DesignStructureMatrix, MultipleDomainMatrix)):\n                        messages.append(message_dsm % (i, j))\n                elif not isinstance(cell, (\n                        DomainMappingMatrix, MultipleDomainMatrix)):\n                    messages.append(message_ddm % (i, j))\n        if messages:\n            raise self.error('\\n'.join(messages))",
    "docstring": "Base validation + each cell is instance of DSM or MDM."
  },
  {
    "code": "def wv45(msg):\n    d = hex2bin(data(msg))\n    if d[12] == '0':\n        return None\n    ws = bin2int(d[13:15])\n    return ws",
    "docstring": "Wake vortex.\n\n    Args:\n        msg (String): 28 bytes hexadecimal message string\n\n    Returns:\n        int: Wake vortex level. 0=NIL, 1=Light, 2=Moderate, 3=Severe"
  },
  {
    "code": "def isPlantOrigin(taxid):\n    assert isinstance(taxid, int)\n    t = TaxIDTree(taxid)\n    try:\n        return \"Viridiplantae\" in str(t)\n    except AttributeError:\n        raise ValueError(\"{0} is not a valid ID\".format(taxid))",
    "docstring": "Given a taxid, this gets the expanded tree which can then be checked to\n    see if the organism is a plant or not\n\n    >>> isPlantOrigin(29760)\n    True"
  },
  {
    "code": "def serialize(self, content):\n        content = super(JSONPTemplateEmitter, self).serialize(content)\n        callback = self.request.GET.get('callback', 'callback')\n        return '%s(%s)' % (callback, content)",
    "docstring": "Move rendered content to callback.\n\n        :return string: JSONP"
  },
  {
    "code": "def bech32_hrp_expand(hrp):\n    return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]",
    "docstring": "Expand the HRP into values for checksum computation."
  },
  {
    "code": "def load_videos(template, video_length, frame_shape):\n  filenames = tf.gfile.Glob(template)\n  if not filenames:\n    raise ValueError(\"no files found.\")\n  filenames = sorted(filenames)\n  dataset_len = len(filenames)\n  filenames = tf.constant(filenames)\n  dataset = tf.data.Dataset.from_tensor_slices(filenames)\n  dataset = dataset.apply(tf.data.experimental.map_and_batch(\n      lambda filename: load_image_map_function(filename, frame_shape),\n      video_length, drop_remainder=True))\n  return dataset, dataset_len",
    "docstring": "Loads videos from files.\n\n  Args:\n    template: template string for listing the image files.\n    video_length: length of the video.\n    frame_shape: shape of each frame.\n\n  Returns:\n    dataset: the tf dataset frame by frame.\n    dataset_len: number of the items which is the number of image files.\n\n  Raises:\n    ValueError: if no files found."
  },
  {
    "code": "def setter(self, fset):\n        self.fset = fset\n        if self.attr_write == AttrWriteType.READ:\n            if getattr(self, 'fget', None):\n                self.attr_write = AttrWriteType.READ_WRITE\n            else:\n                self.attr_write = AttrWriteType.WRITE\n        return self",
    "docstring": "To be used as a decorator. Will define the decorated method\n        as a write attribute method to be called when client writes\n        the attribute"
  },
  {
    "code": "def time_window_cutoff(sw_time, time_cutoff):\n    sw_time = np.array(\n        [(time_cutoff / DAYS) if x > (time_cutoff / DAYS)\n            else x for x in sw_time])\n    return(sw_time)",
    "docstring": "Allows for cutting the declustering time window at a specific time, outside\n    of which an event of any magnitude is no longer identified as a cluster"
  },
  {
    "code": "def json(self):\n    if self.board_data:\n      board_dict = json.loads(self.board_data)\n      board_dict['id'] = self.id\n      del board_dict['__version__']\n    else:\n      board_dict = {\n        'id': self.id,\n        'title': '',\n        'panels': []\n      }\n    return board_dict",
    "docstring": "A JSON-encoded description of this board.\n\n    Format:\n    {'id': board_id,\n     'title': 'The title of the board',\n     'panels': [{\n       'title': 'The title of the panel'\n       'data_source': {\n         'source_type': PanelSource.TYPE,\n         'refresh_seconds': 600,\n         ...source_specific_details...\n       },\n       'display': {\n         'display_type': PanelDisplay.TYPE,\n         ...display_specific_details...\n       }, ...]}"
  },
  {
    "code": "def install_excepthook(hook_type=\"color\", **kwargs):\n    try:\n        from IPython.core import ultratb\n    except ImportError:\n        import warnings\n        warnings.warn(\n            \"Cannot install excepthook, IPyhon.core.ultratb not available\")\n        return 1\n    hook = dict(\n        color=ultratb.ColorTB,\n        verbose=ultratb.VerboseTB,\n    ).get(hook_type.lower(), None)\n    if hook is None:\n        return 2\n    import sys\n    sys.excepthook = hook(**kwargs)\n    return 0",
    "docstring": "This function replaces the original python traceback with an improved\n    version from Ipython. Use `color` for colourful traceback formatting,\n    `verbose` for Ka-Ping Yee's \"cgitb.py\" version kwargs are the keyword\n    arguments passed to the constructor. See IPython.core.ultratb.py for more\n    info.\n\n    Return:\n        0 if hook is installed successfully."
  },
  {
    "code": "def make_nxml_from_text(text):\n    text = _escape_xml(text)\n    header = '<?xml version=\"1.0\" encoding=\"UTF-8\" ?>' + \\\n        '<OAI-PMH><article><body><sec id=\"s1\"><p>'\n    footer = '</p></sec></body></article></OAI-PMH>'\n    nxml_str = header + text + footer\n    return nxml_str",
    "docstring": "Return raw text wrapped in NXML structure.\n\n    Parameters\n    ----------\n    text : str\n        The raw text content to be wrapped in an NXML structure.\n\n    Returns\n    -------\n    nxml_str : str\n        The NXML string wrapping the raw text input."
  },
  {
    "code": "def send_media_file(self, filename):\n        cache_timeout = self.get_send_file_max_age(filename)\n        return send_from_directory(self.config['MEDIA_FOLDER'], filename,\n                                   cache_timeout=cache_timeout)",
    "docstring": "Function used to send media files from the media folder to the browser."
  },
  {
    "code": "def extract_value(self, data):\n        errors = []\n        if 'id' not in data:\n            errors.append('Must have an `id` field')\n        if 'type' not in data:\n            errors.append('Must have a `type` field')\n        elif data['type'] != self.type_:\n            errors.append('Invalid `type` specified')\n        if errors:\n            raise ValidationError(errors)\n        if 'attributes' in data and self.__schema:\n            result = self.schema.load({'data': data, 'included': self.root.included_data})\n            return result.data if _MARSHMALLOW_VERSION_INFO[0] < 3 else result\n        id_value = data.get('id')\n        if self.__schema:\n            id_value = self.schema.fields['id'].deserialize(id_value)\n        return id_value",
    "docstring": "Extract the id key and validate the request structure."
  },
  {
    "code": "def _parse_canonical_int64(doc):\n    l_str = doc['$numberLong']\n    if len(doc) != 1:\n        raise TypeError('Bad $numberLong, extra field(s): %s' % (doc,))\n    return Int64(l_str)",
    "docstring": "Decode a JSON int64 to bson.int64.Int64."
  },
  {
    "code": "def is_multisig_script(script, blockchain='bitcoin', **blockchain_opts):\n    if blockchain == 'bitcoin':\n        return btc_is_multisig_script(script, **blockchain_opts)\n    else:\n        raise ValueError('Unknown blockchain \"{}\"'.format(blockchain))",
    "docstring": "Is the given script a multisig script?"
  },
  {
    "code": "def set_wm_wallpaper(img):\n    if shutil.which(\"feh\"):\n        util.disown([\"feh\", \"--bg-fill\", img])\n    elif shutil.which(\"nitrogen\"):\n        util.disown([\"nitrogen\", \"--set-zoom-fill\", img])\n    elif shutil.which(\"bgs\"):\n        util.disown([\"bgs\", \"-z\", img])\n    elif shutil.which(\"hsetroot\"):\n        util.disown([\"hsetroot\", \"-fill\", img])\n    elif shutil.which(\"habak\"):\n        util.disown([\"habak\", \"-mS\", img])\n    elif shutil.which(\"display\"):\n        util.disown([\"display\", \"-backdrop\", \"-window\", \"root\", img])\n    else:\n        logging.error(\"No wallpaper setter found.\")\n        return",
    "docstring": "Set the wallpaper for non desktop environments."
  },
  {
    "code": "def _apply_cond(self, apply_fn, grad, var, *args, **kwargs):\n    grad_acc = self.get_slot(var, \"grad_acc\")\n    def apply_adam(grad_acc, apply_fn, grad, var, *args, **kwargs):\n      total_grad = (grad_acc + grad) / tf.cast(self._n_t, grad.dtype)\n      adam_op = apply_fn(total_grad, var, *args, **kwargs)\n      with tf.control_dependencies([adam_op]):\n        grad_acc_to_zero_op = grad_acc.assign(tf.zeros_like(grad_acc),\n                                              use_locking=self._use_locking)\n      return tf.group(adam_op, grad_acc_to_zero_op)\n    def accumulate_gradient(grad_acc, grad):\n      assign_op = tf.assign_add(grad_acc, grad, use_locking=self._use_locking)\n      return tf.group(assign_op)\n    return tf.cond(\n        tf.equal(self._get_iter_variable(), 0),\n        lambda: apply_adam(grad_acc, apply_fn, grad, var, *args, **kwargs),\n        lambda: accumulate_gradient(grad_acc, grad))",
    "docstring": "Apply conditionally if counter is zero."
  },
  {
    "code": "def subp(cmd):\n    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n                            stderr=subprocess.PIPE)\n    out, err = proc.communicate()\n    return ReturnTuple(proc.returncode, stdout=out, stderr=err)",
    "docstring": "Run a command as a subprocess.\n    Return a triple of return code, standard out, standard err."
  },
  {
    "code": "def _findExpressionStart(self, block):\n        expEndBlock, expEndColumn = self._findExpressionEnd(block)\n        text = expEndBlock.text()[:expEndColumn + 1]\n        if text.endswith(')'):\n            try:\n                return self.findBracketBackward(expEndBlock, expEndColumn, '(')\n            except ValueError:\n                raise UserWarning()\n        else:\n            return expEndBlock, len(text) - len(self._lastWord(text))",
    "docstring": "Find start of not finished expression\n        Raise UserWarning, if not found"
  },
  {
    "code": "def excmessage_decorator(description) -> Callable:\n    @wrapt.decorator\n    def wrapper(wrapped, instance, args, kwargs):\n        try:\n            return wrapped(*args, **kwargs)\n        except BaseException:\n            info = kwargs.copy()\n            info['self'] = instance\n            argnames = inspect.getfullargspec(wrapped).args\n            if argnames[0] == 'self':\n                argnames = argnames[1:]\n            for argname, arg in zip(argnames, args):\n                info[argname] = arg\n            for argname in argnames:\n                if argname not in info:\n                    info[argname] = '?'\n            message = eval(\n                f\"f'While trying to {description}'\", globals(), info)\n            augment_excmessage(message)\n    return wrapper",
    "docstring": "Wrap a function with |augment_excmessage|.\n\n    Function |excmessage_decorator| is a means to apply function\n    |augment_excmessage| more efficiently.  Suppose you would apply\n    function |augment_excmessage| in a function that adds and returns\n    to numbers:\n\n    >>> from  hydpy.core import objecttools\n    >>> def add(x, y):\n    ...     try:\n    ...         return x + y\n    ...     except BaseException:\n    ...         objecttools.augment_excmessage(\n    ...             'While trying to add `x` and `y`')\n\n    This works as excepted...\n\n    >>> add(1, 2)\n    3\n    >>> add(1, [])\n    Traceback (most recent call last):\n    ...\n    TypeError: While trying to add `x` and `y`, the following error \\\noccurred: unsupported operand type(s) for +: 'int' and 'list'\n\n    ...but can be achieved with much less code using |excmessage_decorator|:\n\n    >>> @objecttools.excmessage_decorator(\n    ...     'add `x` and `y`')\n    ... def add(x, y):\n    ...     return x+y\n\n    >>> add(1, 2)\n    3\n\n    >>> add(1, [])\n    Traceback (most recent call last):\n    ...\n    TypeError: While trying to add `x` and `y`, the following error \\\noccurred: unsupported operand type(s) for +: 'int' and 'list'\n\n    Additionally, exception messages related to wrong function calls\n    are now also augmented:\n\n    >>> add(1)\n    Traceback (most recent call last):\n    ...\n    TypeError: While trying to add `x` and `y`, the following error \\\noccurred: add() missing 1 required positional argument: 'y'\n\n    |excmessage_decorator| evaluates the given string like an f-string,\n    allowing to mention the argument values of the called function and\n    to make use of all string modification functions provided by modules\n    |objecttools|:\n\n    >>> @objecttools.excmessage_decorator(\n    ...     'add `x` ({repr_(x, 2)}) and `y` ({repr_(y, 2)})')\n    ... def add(x, y):\n    ...     return x+y\n\n    >>> add(1.1111, 'wrong')\n    Traceback (most recent call last):\n    ...\n    TypeError: While trying to add `x` (1.11) and `y` (wrong), the following \\\nerror occurred: unsupported operand type(s) for +: 'float' and 'str'\n    >>> add(1)\n    Traceback (most recent call last):\n    ...\n    TypeError: While trying to add `x` (1) and `y` (?), the following error \\\noccurred: add() missing 1 required positional argument: 'y'\n    >>> add(y=1)\n    Traceback (most recent call last):\n    ...\n    TypeError: While trying to add `x` (?) and `y` (1), the following error \\\noccurred: add() missing 1 required positional argument: 'x'\n\n    Apply |excmessage_decorator| on methods also works fine:\n\n    >>> class Adder:\n    ...     def __init__(self):\n    ...         self.value = 0\n    ...     @objecttools.excmessage_decorator(\n    ...         'add an instance of class `{classname(self)}` with value '\n    ...         '`{repr_(other, 2)}` of type `{classname(other)}`')\n    ...     def __iadd__(self, other):\n    ...         self.value += other\n    ...         return self\n\n    >>> adder = Adder()\n    >>> adder += 1\n    >>> adder.value\n    1\n    >>> adder += 'wrong'\n    Traceback (most recent call last):\n    ...\n    TypeError: While trying to add an instance of class `Adder` with value \\\n`wrong` of type `str`, the following error occurred: unsupported operand \\\ntype(s) for +=: 'int' and 'str'\n\n    It is made sure that no information of the decorated function is lost:\n\n    >>> add.__name__\n    'add'"
  },
  {
    "code": "def validate_with_schema(self, model=None, context=None):\n        if self._schema is None or model is None:\n            return\n        result = self._schema.validate(\n            model=model,\n            context=context if self.use_context else None\n        )\n        return result",
    "docstring": "Perform model validation with schema"
  },
  {
    "code": "def classifierPredict(testVector, storedVectors):\n  numClasses = storedVectors.shape[0]\n  output = np.zeros((numClasses,))\n  for i in range(numClasses):\n    output[i] = np.sum(np.minimum(testVector, storedVectors[i, :]))\n  return output",
    "docstring": "Return overlap of the testVector with stored representations for each object."
  },
  {
    "code": "def get_urls(htmlDoc, limit=200):\n    soup = BeautifulSoup( htmlDoc )\n    anchors = soup.findAll( 'a' )\n    urls = {}\n    counter = 0\n    for i,v in enumerate( anchors ):\n        href = anchors[i].get( 'href' )\n        if ('dots' in href and counter < limit):\n            href = href.split('/')[2]\n            text = anchors[i].text.split(' ')[0].replace('/', '_')\n            urls[ text ] = href\n            counter += 1\n    return urls",
    "docstring": "takes in html document as string, returns links to dots"
  },
  {
    "code": "def run(image, name=None, command=None, environment=None, ports=None, volumes=None):\n    if ports and not name:\n        abort('The ports flag currently only works if you specify a container name')\n    if ports:\n        ports = [parse_port_spec(p) for p in ports.split(',')]\n    else:\n        ports = None\n    if environment:\n        environment = dict([x.split('=') for x in environment.split(',')])\n    else:\n        environment = None\n    if volumes:\n        volumes = dict([x.split(':') for x in volumes.split(',')])\n    else:\n        volumes = None\n    run_container(\n        image=image,\n        name=name,\n        command=command,\n        ports=ports,\n        environment=environment,\n        volumes=volumes,\n    )",
    "docstring": "Run a docker container.\n\n    Args:\n        * image: Docker image to run, e.g. orchardup/redis, quay.io/hello/world\n        * name=None: Container name\n        * command=None: Command to execute\n        * environment: Comma separated environment variables in the format NAME=VALUE\n        * ports=None: Comma separated port specs in the format CONTAINER_PORT[:EXPOSED_PORT][/PROTOCOL]\n        * volumes=None: Comma separated volumes in the format HOST_DIR:CONTAINER_DIR\n\n    Examples:\n        * fab docker.run:orchardup/redis,name=redis,ports=6379\n        * fab docker.run:quay.io/hello/world,name=hello,ports=\"80:8080,1000/udp\",volumes=\"/docker/hello/log:/var/log\"\n        * fab docker.run:andreasjansson/redis,environment=\"MAX_MEMORY=4G,FOO=bar\",ports=6379"
  },
  {
    "code": "def normalize(value, series, offset=0):\n    r\n    if not _isreal(value):\n        raise RuntimeError(\"Argument `value` is not valid\")\n    if not _isreal(offset):\n        raise RuntimeError(\"Argument `offset` is not valid\")\n    try:\n        smin = float(min(series))\n        smax = float(max(series))\n    except:\n        raise RuntimeError(\"Argument `series` is not valid\")\n    value = float(value)\n    offset = float(offset)\n    if not 0 <= offset <= 1:\n        raise ValueError(\"Argument `offset` has to be in the [0.0, 1.0] range\")\n    if not smin <= value <= smax:\n        raise ValueError(\n            \"Argument `value` has to be within the bounds of argument `series`\"\n        )\n    return offset + ((1.0 - offset) * (value - smin) / (smax - smin))",
    "docstring": "r\"\"\"\n    Scale a value to the range defined by a series.\n\n    :param value: Value to normalize\n    :type  value: number\n\n    :param series: List of numbers that defines the normalization range\n    :type  series: list\n\n    :param offset: Normalization offset, i.e. the returned value will be in\n                   the range [**offset**, 1.0]\n    :type  offset: number\n\n    :rtype: number\n\n    :raises:\n     * RuntimeError (Argument \\`offset\\` is not valid)\n\n     * RuntimeError (Argument \\`series\\` is not valid)\n\n     * RuntimeError (Argument \\`value\\` is not valid)\n\n     * ValueError (Argument \\`offset\\` has to be in the [0.0, 1.0] range)\n\n     * ValueError (Argument \\`value\\` has to be within the bounds of the\n       argument \\`series\\`)\n\n    For example::\n\n        >>> import pmisc\n        >>> pmisc.normalize(15, [10, 20])\n        0.5\n        >>> pmisc.normalize(15, [10, 20], 0.5)\n        0.75"
  },
  {
    "code": "def get_actions(self, request):\n        actions = super(EntryAdmin, self).get_actions(request)\n        if not actions:\n            return actions\n        if (not request.user.has_perm('zinnia.can_change_author') or\n                not request.user.has_perm('zinnia.can_view_all')):\n            del actions['make_mine']\n        if not request.user.has_perm('zinnia.can_change_status'):\n            del actions['make_hidden']\n            del actions['make_published']\n        if not settings.PING_DIRECTORIES:\n            del actions['ping_directories']\n        return actions",
    "docstring": "Define actions by user's permissions."
  },
  {
    "code": "def parse_json(json_file):\n    if not os.path.exists(json_file):\n        return None\n    try:\n        with open(json_file, \"r\") as f:\n            info_str = f.readlines()\n            info_str = \"\".join(info_str)\n            json_info = json.loads(info_str)\n            return unicode2str(json_info)\n    except BaseException as e:\n        logging.error(e.message)\n        return None",
    "docstring": "Parse a whole json record from the given file.\n\n    Return None if the json file does not exists or exception occurs.\n\n    Args:\n        json_file (str): File path to be parsed.\n\n    Returns:\n        A dict of json info."
  },
  {
    "code": "def search(self, category, term='', index=0, count=100):\n        search_category = self._get_search_prefix_map().get(category, None)\n        if search_category is None:\n            raise MusicServiceException(\n                \"%s does not support the '%s' search category\" % (\n                    self.service_name, category))\n        response = self.soap_client.call(\n            'search',\n            [\n                ('id', search_category), ('term', term), ('index', index),\n                ('count', count)])\n        return parse_response(self, response, category)",
    "docstring": "Search for an item in a category.\n\n        Args:\n            category (str): The search category to use. Standard Sonos search\n                categories are 'artists', 'albums', 'tracks', 'playlists',\n                'genres', 'stations', 'tags'. Not all are available for each\n                music service. Call available_search_categories for a list for\n                this service.\n            term (str): The term to search for.\n            index (int): The starting index. Default 0.\n            count (int): The maximum number of items to return. Default 100.\n\n        Returns:\n            ~collections.OrderedDict: The search results, or `None`.\n\n        See also:\n            The Sonos `search API <http://musicpartners.sonos.com/node/86>`_"
  },
  {
    "code": "def set_folder_names(self, folder_names):\r\n        assert self.root_path is not None\r\n        path_list = [osp.join(self.root_path, dirname)\r\n                     for dirname in folder_names]\r\n        self.proxymodel.setup_filter(self.root_path, path_list)",
    "docstring": "Set folder names"
  },
  {
    "code": "def add_to_inventory(self):\n        if not self.server_attrs:\n            return\n        for addy in self.server_attrs[A.server.PUBLIC_IPS]:\n            self.stack.add_host(addy, self.groups, self.hostvars)",
    "docstring": "Adds host to stack inventory"
  },
  {
    "code": "def binop_return_dtype(op, left, right):\n    if is_comparison(op):\n        if left != right:\n            raise TypeError(\n                \"Don't know how to compute {left} {op} {right}.\\n\"\n                \"Comparisons are only supported between Factors of equal \"\n                \"dtypes.\".format(left=left, op=op, right=right)\n            )\n        return bool_dtype\n    elif left != float64_dtype or right != float64_dtype:\n        raise TypeError(\n            \"Don't know how to compute {left} {op} {right}.\\n\"\n            \"Arithmetic operators are only supported between Factors of \"\n            \"dtype 'float64'.\".format(\n                left=left.name,\n                op=op,\n                right=right.name,\n            )\n        )\n    return float64_dtype",
    "docstring": "Compute the expected return dtype for the given binary operator.\n\n    Parameters\n    ----------\n    op : str\n        Operator symbol, (e.g. '+', '-', ...).\n    left : numpy.dtype\n        Dtype of left hand side.\n    right : numpy.dtype\n        Dtype of right hand side.\n\n    Returns\n    -------\n    outdtype : numpy.dtype\n        The dtype of the result of `left <op> right`."
  },
  {
    "code": "def headers(self):\n        if self._headers is None:\n            query = CellQuery()\n            query.max_row = '1'\n            feed = self._service.GetCellsFeed(self._ss.id, self.id,\n                                              query=query)\n            self._headers = feed.entry\n        return [normalize_header(h.cell.text) for h in self._headers]",
    "docstring": "Return the name of all headers currently defined for the\n        table."
  },
  {
    "code": "def get_instances(self, state_filter=None):\n    instances = []\n    for instance in self._get_instances(self._get_cluster_group_name(), \n                                        state_filter):\n      instances.append(Instance(instance.id, instance.dns_name, \n                                instance.private_dns_name, \n                                instance.private_ip_address))\n    return instances",
    "docstring": "Get all the instances filtered by state.\n    \n    @param state_filter: the state that the instance should be in\n      (e.g. \"running\"), or None for all states"
  },
  {
    "code": "def manage_signal(self, sig, frame):\n        if sig in [signal.SIGINT, signal.SIGTERM]:\n            logger.info(\"received a signal: %s\", SIGNALS_TO_NAMES_DICT[sig])\n            self.kill_request = True\n            self.kill_timestamp = time.time()\n            logger.info(\"request to stop in progress\")\n        else:\n            Daemon.manage_signal(self, sig, frame)",
    "docstring": "Manage signals caught by the process\n        Specific behavior for the arbiter when it receives a sigkill or sigterm\n\n        :param sig: signal caught by the process\n        :type sig: str\n        :param frame: current stack frame\n        :type frame:\n        :return: None"
  },
  {
    "code": "def get_price(ctx, currency):\n    appid = ctx.obj['appid']\n    title = ctx.obj['title']\n    item_ = Item(appid, title)\n    item_.get_price_data(currency)\n    click.secho('Lowest price: %s %s' % (item_.price_lowest, item_.price_currency), fg='green')",
    "docstring": "Prints out market item price."
  },
  {
    "code": "def create_audit_student_enrollment(self, course_id):\n        audit_enrollment = {\n            \"mode\": \"audit\",\n            \"course_details\": {\"course_id\": course_id}\n        }\n        resp = self.requester.post(\n            urljoin(self.base_url, self.enrollment_url),\n            json=audit_enrollment\n        )\n        resp.raise_for_status()\n        return Enrollment(resp.json())",
    "docstring": "Creates an audit enrollment for the user in a given course\n\n        Args:\n            course_id (str): an edX course id\n\n        Returns:\n            Enrollment: object representing the student enrollment in the provided course"
  },
  {
    "code": "def from_json_file(cls, json_file):\n        with open(json_file, \"r\", encoding=\"utf-8\") as reader:\n            text = reader.read()\n        return cls.from_dict(json.loads(text))",
    "docstring": "Constructs a `GPT2Config` from a json file of parameters."
  },
  {
    "code": "def merge(self, commit_message='', sha=None):\n        parameters = {'commit_message': commit_message}\n        if sha:\n            parameters['sha'] = sha\n        url = self._build_url('merge', base_url=self._api)\n        json = self._json(self._put(url, data=dumps(parameters)), 200)\n        self.merge_commit_sha = json['sha']\n        return json['merged']",
    "docstring": "Merge this pull request.\n\n        :param str commit_message: (optional), message to be used for the\n            merge commit\n        :returns: bool"
  },
  {
    "code": "def asStructTime(self, tzinfo=None):\n        dtime = self.asDatetime(tzinfo)\n        if tzinfo is None:\n            return dtime.utctimetuple()\n        else:\n            return dtime.timetuple()",
    "docstring": "Return this time represented as a time.struct_time.\n\n        tzinfo is a datetime.tzinfo instance coresponding to the desired\n        timezone of the output. If is is the default None, UTC is assumed."
  },
  {
    "code": "async def populate_projects(self, force=False):\n        if force or not self.projects:\n            with tempfile.TemporaryDirectory() as tmpdirname:\n                self.projects = await load_json_or_yaml_from_url(\n                    self, self.config['project_configuration_url'],\n                    os.path.join(tmpdirname, 'projects.yml')\n                )",
    "docstring": "Download the ``projects.yml`` file and populate ``self.projects``.\n\n        This only sets it once, unless ``force`` is set.\n\n        Args:\n            force (bool, optional): Re-run the download, even if ``self.projects``\n                is already defined. Defaults to False."
  },
  {
    "code": "def update_from_yaml(self, path=join('config', 'hdx_dataset_static.yml')):\n        super(Dataset, self).update_from_yaml(path)\n        self.separate_resources()",
    "docstring": "Update dataset metadata with static metadata from YAML file\n\n        Args:\n            path (str): Path to YAML dataset metadata. Defaults to config/hdx_dataset_static.yml.\n\n        Returns:\n            None"
  },
  {
    "code": "def close(self):\n        self._wr_lock.acquire()\n        self._rd_lock.acquire()\n        try:\n            self._running.clear()\n            if self.socket:\n                self._close_socket()\n            if self._inbound_thread:\n                self._inbound_thread.join(timeout=self._parameters['timeout'])\n            self._inbound_thread = None\n            self.poller = None\n            self.socket = None\n        finally:\n            self._wr_lock.release()\n            self._rd_lock.release()",
    "docstring": "Close Socket.\n\n        :return:"
  },
  {
    "code": "def min_pos(self):\n        if self.__len__() == 0:\n            return ArgumentError('empty set has no minimum positive value.')\n        if self.contains(0):\n            return None\n        positive = [interval for interval in self.intervals\n                    if interval.left > 0]\n        if len(positive) == 0:\n            return None\n        return numpy.min(list(map(lambda i: i.left, positive)))",
    "docstring": "Returns minimal positive value or None."
  },
  {
    "code": "def longest_one_seg_prefix(self, word):\n        match = self.seg_regex.match(word)\n        if match:\n            return match.group(0)\n        else:\n            return ''",
    "docstring": "Return longest IPA Unicode prefix of `word`\n\n        Args:\n            word (unicode): word as IPA string\n\n        Returns:\n            unicode: longest single-segment prefix of `word`"
  },
  {
    "code": "def colors(self):\n        try:\n            return get_console_info(self._kernel32, self._stream_handle)[:2]\n        except OSError:\n            return WINDOWS_CODES['white'], WINDOWS_CODES['black']",
    "docstring": "Return the current foreground and background colors."
  },
  {
    "code": "def memoize_by_args(func):\n    memory = {}\n    @functools.wraps(func)\n    def memoized(*args):\n        if args not in memory.keys():\n            value = func(*args)\n            memory[args] = value\n        return memory[args]\n    return memoized",
    "docstring": "Memoizes return value of a func based on args."
  },
  {
    "code": "def ifusergroup(parser, token):\n    try:\n        tokensp = token.split_contents()\n        groups = []\n        groups+=tokensp[1:]\n    except ValueError:\n        raise template.TemplateSyntaxError(\"Tag 'ifusergroup' requires at least 1 argument.\")\n    nodelist_true = parser.parse(('else', 'endifusergroup'))\n    token = parser.next_token()\n    if token.contents == 'else':\n        nodelist_false = parser.parse(tuple(['endifusergroup',]))\n        parser.delete_first_token()\n    else:\n        nodelist_false = NodeList()\n    return GroupCheckNode(groups, nodelist_true, nodelist_false)",
    "docstring": "Check to see if the currently logged in user belongs to a specific\n    group. Requires the Django authentication contrib app and middleware.\n\n    Usage: {% ifusergroup Admins %} ... {% endifusergroup %}, or\n           {% ifusergroup Admins Clients Sellers %} ... {% else %} ... {% endifusergroup %}"
  },
  {
    "code": "def feedback_form(context):\n    user = None\n    url = None\n    if context.get('request'):\n        url = context['request'].path\n        if context['request'].user.is_authenticated():\n            user = context['request'].user\n    return {\n        'form': FeedbackForm(url=url, user=user),\n        'background_color': FEEDBACK_FORM_COLOR,\n        'text_color': FEEDBACK_FORM_TEXTCOLOR,\n        'text': FEEDBACK_FORM_TEXT,\n    }",
    "docstring": "Template tag to render a feedback form."
  },
  {
    "code": "def gauge(self, slug, current_value):\n        k = self._gauge_key(slug)\n        self.r.sadd(self._gauge_slugs_key, slug)\n        self.r.set(k, current_value)",
    "docstring": "Set the value for a Gauge.\n\n        * ``slug`` -- the unique identifier (or key) for the Gauge\n        * ``current_value`` -- the value that the gauge should display"
  },
  {
    "code": "def update(self, observable, handlers):\n        addedreaders, removedreaders = handlers\n        for reader in addedreaders:\n            item = self.Append(str(reader))\n            self.SetClientData(item, reader)\n        for reader in removedreaders:\n            item = self.FindString(str(reader))\n            if wx.NOT_FOUND != item:\n                self.Delete(item)\n        selection = self.GetSelection()",
    "docstring": "Toolbar ReaderObserver callback that is notified when\n        readers are added or removed."
  },
  {
    "code": "def failure_line_summary(formatter, failure_line):\n    if failure_line.action == \"test_result\":\n        action = \"test_status\" if failure_line.subtest is not None else \"test_end\"\n    elif failure_line.action == \"truncated\":\n        return\n    else:\n        action = failure_line.action\n    try:\n        mozlog_func = getattr(formatter, action)\n    except AttributeError:\n        logger.warning('Unknown mozlog function \"%s\"', action)\n        return\n    formatted_log = mozlog_func(failure_line.to_mozlog_format())\n    split_log = first(formatted_log.split(\"\\n\", 1))\n    if not split_log:\n        logger.debug('Failed to split log', formatted_log)\n        return\n    return split_log.strip()",
    "docstring": "Create a mozlog formatted error summary string from the given failure_line.\n\n    Create a string which can be compared to a TextLogError.line string to see\n    if they match."
  },
  {
    "code": "def header(header_text: str, level: int = 1, expand_full: bool = False):\n    r = _get_report()\n    r.append_body(render.header(\n        header_text,\n        level=level,\n        expand_full=expand_full\n    ))",
    "docstring": "Adds a text header to the display with the specified level.\n\n    :param header_text:\n        The text to display in the header.\n    :param level:\n        The level of the header, which corresponds to the html header\n        levels, such as <h1>, <h2>, ...\n    :param expand_full:\n        Whether or not the header will expand to fill the width of the entire\n        notebook page, or be constrained by automatic maximum page width. The\n        default value of False lines the header up with text displays."
  },
  {
    "code": "def create(self, key, value):\n        base64_key = _encode(key)\n        base64_value = _encode(value)\n        txn = {\n            'compare': [{\n                'key': base64_key,\n                'result': 'EQUAL',\n                'target': 'CREATE',\n                'create_revision': 0\n            }],\n            'success': [{\n                'request_put': {\n                    'key': base64_key,\n                    'value': base64_value,\n                }\n            }],\n            'failure': []\n        }\n        result = self.transaction(txn)\n        if 'succeeded' in result:\n            return result['succeeded']\n        return False",
    "docstring": "Atomically create the given key only if the key doesn't exist.\n\n        This verifies that the create_revision of a key equales to 0, then\n        creates the key with the value.\n        This operation takes place in a transaction.\n\n        :param key: key in etcd to create\n        :param value: value of the key\n        :type value: bytes or string\n        :returns: status of transaction, ``True`` if the create was\n                  successful, ``False`` otherwise\n        :rtype: bool"
  },
  {
    "code": "def filepath(self, filename):\n        return os.path.join(self.node.full_path, filename)",
    "docstring": "The full path to a file"
  },
  {
    "code": "def _get_representative_batch(merged):\n    out = {}\n    for mgroup in merged:\n        mgroup = sorted(list(mgroup))\n        for x in mgroup:\n            out[x] = mgroup[0]\n    return out",
    "docstring": "Prepare dictionary matching batch items to a representative within a group."
  },
  {
    "code": "def set_s3_prefix(self, region, name):\n        ct = self.session.client('cloudtrail', region_name=region)\n        ct.update_trail(Name=name, S3KeyPrefix=self.account.account_name)\n        auditlog(\n            event='cloudtrail.set_s3_prefix',\n            actor=self.ns,\n            data={\n                'account': self.account.account_name,\n                'region': region\n            }\n        )\n        self.log.info('Updated S3KeyPrefix to {0} for {0}/{1}'.format(\n            self.account.account_name,\n            region\n        ))",
    "docstring": "Sets the S3 prefix for a CloudTrail Trail\n\n        Args:\n            region (`str`): Name of the AWS region\n            name (`str`): Name of the CloudTrail Trail\n\n        Returns:\n            `None`"
  },
  {
    "code": "def to_text(self):\n        if self.text is None:\n            return\n        level = '*' * self.level\n        return '%s%s\\n' % (level, self.text)",
    "docstring": "Render a Heading MessageElement as plain text\n\n        :returns: The plain text representation of the Heading MessageElement."
  },
  {
    "code": "def _process(self, name):\n        if self.token.nature == name:\n            self.token = self.lexer.next_token()\n        else:\n            self._error()",
    "docstring": "Process the current token."
  },
  {
    "code": "def _parse_filter_string(filter_string):\n    assert \"=\" in filter_string, \"filter string requires an '=', got {0}\".format(filter_string)\n    split_values = filter_string.split('=')\n    assert len(split_values) == 2, \"more than one equals found in filter string {0}!\".format(filter_string)\n    return split_values",
    "docstring": "parse a filter string into a key-value pair"
  },
  {
    "code": "def get_range_info(array, component):\n    r = array.GetRange(component)\n    comp_range = {}\n    comp_range['min'] = r[0]\n    comp_range['max'] = r[1]\n    comp_range['component'] = array.GetComponentName(component)\n    return comp_range",
    "docstring": "Get the data range of the array's component"
  },
  {
    "code": "def jarsign(storepass, keypass, keystore, source, alias, path=None):\n  cmd = [\n    'jarsigner',\n    '-verbose',\n    '-storepass',\n    storepass,\n    '-keypass',\n    keypass,\n    '-keystore',\n    keystore,\n    source,\n    alias\n  ]\n  common.run_cmd(cmd, log='jarsign.log', cwd=path)",
    "docstring": "Uses Jarsign to sign an apk target file using the provided keystore information.\n\n  :param storepass(str) - keystore storepass\n  :param keypass(str) - keystore keypass\n  :param keystore(str) - keystore file path\n  :param source(str) - apk path\n  :param alias(str) - keystore alias\n  :param path(str) - basedir to run the command"
  },
  {
    "code": "def labels_to_indices(self, labels: Sequence[str]) -> List[int]:\n        return [self.LABEL_TO_INDEX[label] for label in labels]",
    "docstring": "Converts a sequence of labels into their corresponding indices."
  },
  {
    "code": "def find_ca_bundle():\n    extant_cert_paths = filter(os.path.isfile, cert_paths)\n    return (\n        get_win_certfile()\n        or next(extant_cert_paths, None)\n        or _certifi_where()\n    )",
    "docstring": "Return an existing CA bundle path, or None"
  },
  {
    "code": "def _handle_template(self, token):\n        params = []\n        default = 1\n        self._push()\n        while self._tokens:\n            token = self._tokens.pop()\n            if isinstance(token, tokens.TemplateParamSeparator):\n                if not params:\n                    name = self._pop()\n                param = self._handle_parameter(default)\n                params.append(param)\n                if not param.showkey:\n                    default += 1\n            elif isinstance(token, tokens.TemplateClose):\n                if not params:\n                    name = self._pop()\n                return Template(name, params)\n            else:\n                self._write(self._handle_token(token))\n        raise ParserError(\"_handle_template() missed a close token\")",
    "docstring": "Handle a case where a template is at the head of the tokens."
  },
  {
    "code": "def write(self, b):\n\t\tself.__buffer += bytes(b)\n\t\tbytes_written = 0\n\t\twhile len(self.__buffer) >= self.__cipher_block_size:\n\t\t\tio.BufferedWriter.write(self, self.__cipher.encrypt_block(self.__buffer[:self.__cipher_block_size]))\n\t\t\tself.__buffer = self.__buffer[self.__cipher_block_size:]\n\t\t\tbytes_written += self.__cipher_block_size\n\t\treturn len(b)",
    "docstring": "Encrypt and write data\n\n\t\t:param b: data to encrypt and write\n\n\t\t:return: None"
  },
  {
    "code": "def _method_url(self, method_name):\n        return \"{base_url}/api/{api}/{method}\".format(\n            base_url=self._base_url(),\n            api=self.api_version,\n            method=method_name\n        )",
    "docstring": "Generate the URL for the requested method\n\n        Args:\n            method_name (str): Name of the method\n\n        Returns:\n            A string containing the URL of the method"
  },
  {
    "code": "def get_sv_chroms(items, exclude_file):\n    exclude_regions = {}\n    for region in pybedtools.BedTool(exclude_file):\n        if int(region.start) == 0:\n            exclude_regions[region.chrom] = int(region.end)\n    out = []\n    with pysam.Samfile(dd.get_align_bam(items[0]) or dd.get_work_bam(items[0]))as pysam_work_bam:\n        for chrom, length in zip(pysam_work_bam.references, pysam_work_bam.lengths):\n            exclude_length = exclude_regions.get(chrom, 0)\n            if exclude_length < length:\n                out.append(chrom)\n    return out",
    "docstring": "Retrieve chromosomes to process on, avoiding extra skipped chromosomes."
  },
  {
    "code": "def transpose(self):\n        java_transposed_matrix = self._java_matrix_wrapper.call(\"transpose\")\n        return BlockMatrix(java_transposed_matrix, self.colsPerBlock, self.rowsPerBlock)",
    "docstring": "Transpose this BlockMatrix. Returns a new BlockMatrix\n        instance sharing the same underlying data. Is a lazy operation.\n\n        >>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),\n        ...                          ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))])\n        >>> mat = BlockMatrix(blocks, 3, 2)\n\n        >>> mat_transposed = mat.transpose()\n        >>> mat_transposed.toLocalMatrix()\n        DenseMatrix(2, 6, [1.0, 4.0, 2.0, 5.0, 3.0, 6.0, 7.0, 10.0, 8.0, 11.0, 9.0, 12.0], 0)"
  },
  {
    "code": "def mv_files(src, dst):\n    files = os.listdir(src)\n    for file in files:\n        shutil.move(os.path.join(src, file), os.path.join(dst, file))\n    return",
    "docstring": "Move all files from one directory to another\n\n    :param str src: Source directory\n    :param str dst: Destination directory\n    :return none:"
  },
  {
    "code": "def add_number_widget(self, ref, x=1, value=1):\n        if ref not in self.widgets:\n            widget = widgets.NumberWidget(screen=self, ref=ref, x=x, value=value)\n            self.widgets[ref] = widget\n            return self.widgets[ref]",
    "docstring": "Add Number Widget"
  },
  {
    "code": "def time_entry(self, prompt, message=None, formats=['%X', '%H:%M', '%I:%M', '%H.%M',\n        '%I.%M'], show_example=False, rofi_args=None, **kwargs):\n        def time_validator(text):\n            for format in formats:\n                try:\n                    dt = datetime.strptime(text, format)\n                except ValueError:\n                    continue\n                else:\n                    return (dt.time(), None)\n            return (None, 'Please enter a valid time.')\n        if show_example:\n            message = message or \"\"\n            message += \"Current time in the correct format: \" + datetime.now().strftime(formats[0])\n        return self.generic_entry(prompt, time_validator, message, rofi_args=None, **kwargs)",
    "docstring": "Prompt the user to enter a time.\n\n        Parameters\n        ----------\n        prompt: string\n            Prompt to display to the user.\n        message: string, optional\n            Message to display under the entry line.\n        formats: list of strings, optional\n            The formats that the user can enter times in. These should be\n            format strings as accepted by the datetime.datetime.strptime()\n            function from the standard library. They are tried in order, and\n            the first that returns a time object without error is selected.\n            Note that the '%X' in the default list is the current locale's time\n            representation.\n        show_example: Boolean\n            If True, the current time in the first format given is appended to\n            the message.\n\n        Returns\n        -------\n        datetime.time, or None if the dialog is cancelled."
  },
  {
    "code": "def flush(self):\n        self._check_open_file()\n        if self.allow_update and not self.is_stream:\n            contents = self._io.getvalue()\n            if self._append:\n                self._sync_io()\n                old_contents = (self.file_object.byte_contents\n                                if is_byte_string(contents) else\n                                self.file_object.contents)\n                contents = old_contents + contents[self._flush_pos:]\n                self._set_stream_contents(contents)\n                self.update_flush_pos()\n            else:\n                self._io.flush()\n            if self.file_object.set_contents(contents, self._encoding):\n                if self._filesystem.is_windows_fs:\n                    self._changed = True\n                else:\n                    current_time = time.time()\n                    self.file_object.st_ctime = current_time\n                    self.file_object.st_mtime = current_time\n            self._file_epoch = self.file_object.epoch\n            if not self.is_stream:\n                self._flush_related_files()",
    "docstring": "Flush file contents to 'disk'."
  },
  {
    "code": "def generate_random_schema(valid):\n    schema_type = choice(['literal', 'type'])\n    if schema_type == 'literal':\n        type, gen = generate_random_type(valid)\n        value = next(gen)\n        return value, (value if valid else None for i in itertools.count())\n    elif schema_type == 'type':\n        return generate_random_type(valid)\n    else:\n        raise AssertionError('!')",
    "docstring": "Generate a random plain schema, and a sample generation function.\n\n    :param valid: Generate valid samples?\n    :type valid: bool\n    :returns: schema, sample-generator\n    :rtype: *, generator"
  },
  {
    "code": "def as_unit(self, unit, location='suffix', *args, **kwargs):\n        f = Formatter(\n            as_unit(unit, location=location),\n            args,\n            kwargs\n        )\n        return self._add_formatter(f)",
    "docstring": "Format subset as with units\n\n        :param unit: string to use as unit\n        :param location: prefix or suffix\n        :param subset: Pandas subset"
  },
  {
    "code": "def resolve_relative_rst_links(text: str, base_link: str):\n    document = parse_rst(text)\n    visitor = SimpleRefCounter(document)\n    document.walk(visitor)\n    for target in visitor.references:\n        name = target.attributes['name']\n        uri = target.attributes['refuri']\n        new_link = '`{} <{}{}>`_'.format(name, base_link, uri)\n        if name == uri:\n            text = text.replace('`<{}>`_'.format(uri), new_link)\n        else:\n            text = text.replace('`{} <{}>`_'.format(name, uri), new_link)\n    return text",
    "docstring": "Resolve all relative links in a given RST document.\n\n    All links of form `link`_ become `link <base_link/link>`_."
  },
  {
    "code": "def address_reencode(address, blockchain='bitcoin', **blockchain_opts):\n    if blockchain == 'bitcoin':\n        return btc_address_reencode(address, **blockchain_opts)\n    else:\n        raise ValueError(\"Unknown blockchain '{}'\".format(blockchain))",
    "docstring": "Reencode an address"
  },
  {
    "code": "def convert(isbn, code='978'):\n    isbn = _isbn_cleanse(isbn)\n    if len(isbn) == 10:\n        isbn = code + isbn[:-1]\n        return isbn + calculate_checksum(isbn)\n    else:\n        if isbn.startswith('978'):\n            return isbn[3:-1] + calculate_checksum(isbn[3:-1])\n        else:\n            raise IsbnError('Only ISBN-13s with 978 Bookland code can be '\n                            'converted to ISBN-10.')",
    "docstring": "Convert ISBNs between ISBN-10 and ISBN-13.\n\n    Note:\n        No attempt to hyphenate converted ISBNs is made, because the\n        specification requires that *any* hyphenation must be correct but\n        allows ISBNs without hyphenation.\n\n    Args:\n        isbn (str): SBN, ISBN-10 or ISBN-13\n        code (str): EAN Bookland code\n\n    Returns:\n        ``str``: Converted ISBN-10 or ISBN-13\n\n    Raise:\n        IsbnError: When ISBN-13 isn't convertible to an ISBN-10"
  },
  {
    "code": "def load(self, container_name, slot, label=None, share=False):\n        if share:\n            raise NotImplementedError(\"Sharing not supported\")\n        try:\n            name = self.LW_TRANSLATION[container_name]\n        except KeyError:\n            if container_name in self.LW_NO_EQUIVALENT:\n                raise NotImplementedError(\"Labware {} is not supported\"\n                                          .format(container_name))\n            elif container_name in ('magdeck', 'tempdeck'):\n                raise NotImplementedError(\"Module load not yet implemented\")\n            else:\n                name = container_name\n        return self._ctx.load_labware_by_name(name, slot, label)",
    "docstring": "Load a piece of labware by specifying its name and position.\n\n        This method calls :py:meth:`.ProtocolContext.load_labware_by_name`;\n        see that documentation for more information on arguments and return\n        values. Calls to this function should be replaced with calls to\n        :py:meth:`.Protocolcontext.load_labware_by_name`.\n\n        In addition, this function contains translations between old\n        labware names and new labware names."
  },
  {
    "code": "def can_proceed(bound_method, check_conditions=True):\n    if not hasattr(bound_method, '_django_fsm'):\n        im_func = getattr(bound_method, 'im_func', getattr(bound_method, '__func__'))\n        raise TypeError('%s method is not transition' % im_func.__name__)\n    meta = bound_method._django_fsm\n    im_self = getattr(bound_method, 'im_self', getattr(bound_method, '__self__'))\n    current_state = meta.field.get_state(im_self)\n    return meta.has_transition(current_state) and (\n        not check_conditions or meta.conditions_met(im_self, current_state))",
    "docstring": "Returns True if model in state allows to call bound_method\n\n    Set ``check_conditions`` argument to ``False`` to skip checking\n    conditions."
  },
  {
    "code": "def check_empty_locations(self, locations=None):\n        if locations is None:\n            locations = self.locations\n        if not locations:\n            err_exit('mkrelease: option -d is required\\n%s' % USAGE)",
    "docstring": "Fail if 'locations' is empty."
  },
  {
    "code": "def save_model(self, model_filename):\n        line = \"save_{}|\".format(model_filename)\n        self.vw_process.sendline(line)",
    "docstring": "Pass a \"command example\" to the VW subprocess requesting\n        that the current model be serialized to model_filename immediately."
  },
  {
    "code": "def from_soup_tag(tag):\n        \"Returns an instance from a given soup tag.\"\n        periods = []\n        notes = []\n        for elem in tag.findAll(recursive=False):\n            if elem.name not in ('period', 'note'):\n                raise TypeError(\"Unknown tag found: \" + str(elem))\n            if elem.name == 'note':\n                notes.append(elem.string.strip())\n            elif elem.name == 'period':\n                periods.append(Period.from_soup_tag(elem))\n        return Section(\n            tag['crn'], tag['num'], tag['students'], tag['seats'],\n            periods, notes\n        )",
    "docstring": "Returns an instance from a given soup tag."
  },
  {
    "code": "def _get_implicit_requirements(\n        self,\n        fields,\n        requirements\n    ):\n        for name, field in six.iteritems(fields):\n            source = field.source\n            requires = getattr(field, 'requires', None) or [source]\n            for require in requires:\n                if not require:\n                    continue\n                requirement = require.split('.')\n                if requirement[-1] == '':\n                    requirement[-1] = '*'\n                requirements.insert(requirement, TreeMap(), update=True)",
    "docstring": "Extract internal prefetch requirements from serializer fields."
  },
  {
    "code": "def _wait_for_connection_state(self, state=Stateful.OPEN, rpc_timeout=30):\n        start_time = time.time()\n        while self.current_state != state:\n            self.check_for_errors()\n            if time.time() - start_time > rpc_timeout:\n                raise AMQPConnectionError('Connection timed out')\n            sleep(IDLE_WAIT)",
    "docstring": "Wait for a Connection state.\n\n        :param int state: State that we expect\n\n        :raises AMQPConnectionError: Raises if we are unable to establish\n                                     a connection to RabbitMQ.\n\n        :return:"
  },
  {
    "code": "def get_response(self):\n        user_input = self.usr_input.get()\n        self.usr_input.delete(0, tk.END)\n        response = self.chatbot.get_response(user_input)\n        self.conversation['state'] = 'normal'\n        self.conversation.insert(\n            tk.END, \"Human: \" + user_input + \"\\n\" + \"ChatBot: \" + str(response.text) + \"\\n\"\n        )\n        self.conversation['state'] = 'disabled'\n        time.sleep(0.5)",
    "docstring": "Get a response from the chatbot and display it."
  },
  {
    "code": "def HiResHDU(model):\n    cards = model._mission.HDUCards(model.meta, hdu=5)\n    cards.append(('COMMENT', '************************'))\n    cards.append(('COMMENT', '*     EVEREST INFO     *'))\n    cards.append(('COMMENT', '************************'))\n    cards.append(('MISSION', model.mission, 'Mission name'))\n    cards.append(('VERSION', EVEREST_MAJOR_MINOR, 'EVEREST pipeline version'))\n    cards.append(('SUBVER', EVEREST_VERSION, 'EVEREST pipeline subversion'))\n    cards.append(('DATE', strftime('%Y-%m-%d'),\n                  'EVEREST file creation date (YYYY-MM-DD)'))\n    header = pyfits.Header(cards=cards)\n    if model.hires is not None:\n        hdu = pyfits.ImageHDU(\n            data=model.hires, header=header, name='HI RES IMAGE')\n    else:\n        hdu = pyfits.ImageHDU(data=np.empty(\n            (0, 0), dtype=float), header=header, name='HI RES IMAGE')\n    return hdu",
    "docstring": "Construct the HDU containing the hi res image of the target."
  },
  {
    "code": "def scripts(cls, pkg, metadata, paths=[], **kwargs):\n        for path in paths:\n            try:\n                fP = pkg_resources.resource_filename(pkg, path)\n            except ImportError:\n                cls.log.warning(\n                    \"No package called {}\".format(pkg)\n                )\n            else:\n                if not os.path.isfile(fP):\n                    cls.log.warning(\n                        \"No script file at {}\".format(os.path.join(*pkg.split(\".\") + [path]))\n                    )\n                else:\n                    yield cls(fP, metadata)",
    "docstring": "This class method is the preferred way to create SceneScript objects.\n\n        :param str pkg: The dotted name of the package containing the scripts.\n        :param metadata: A mapping or data object. This parameter permits searching among\n            scripts against particular criteria. Its use is application specific.\n        :param list(str) paths: A sequence of file paths to the scripts relative to the package.\n\n        You can satisfy all parameter requirements by passing in a\n        :py:class:`~turberfield.dialogue.model.SceneScript.Folder` object\n        like this::\n\n            SceneScript.scripts(**folder._asdict())\n\n        The method generates a sequence of\n        :py:class:`~turberfield.dialogue.model.SceneScript` objects."
  },
  {
    "code": "def _on_delete(self, builder):\n        column = self._get_deleted_at_column(builder)\n        return builder.update({column: builder.get_model().fresh_timestamp()})",
    "docstring": "The delete replacement function.\n\n        :param builder: The query builder\n        :type builder: orator.orm.builder.Builder"
  },
  {
    "code": "def write_elec_file(filename, mesh):\n    elecs = []\n    electrodes = np.loadtxt(filename)\n    for i in electrodes:\n        for nr, j in enumerate(mesh['nodes']):\n            if np.isclose(j[1], i[0]) and np.isclose(j[2], i[1]):\n                elecs.append(nr + 1)\n    fid = open('elec.dat', 'w')\n    fid.write('{0}\\n'.format(len(elecs)))\n    for i in elecs:\n        fid.write('{0}\\n'.format(i))\n    fid.close()",
    "docstring": "Read in the electrode positions and return the indices of the electrodes\n\n    # TODO: Check if you find all electrodes"
  },
  {
    "code": "def load_hooks():\n    hooks = {}\n    for entrypoint in pkg_resources.iter_entry_points(ENTRYPOINT):\n        name = str(entrypoint).split('=')[0].strip()\n        try:\n            hook = entrypoint.load()\n        except Exception as e:\n            write_message('failed to load entry-point %r (error=\"%s\")' % (name, e), 'yellow')\n        else:\n            hooks[name] = hook\n    return hooks",
    "docstring": "Load the exposed hooks.\n\n    Returns a dict of hooks where the keys are the name of the hook and the\n    values are the actual hook functions."
  },
  {
    "code": "def translate_filenames(filenames):\n    if is_windows():\n        return filenames\n    for index, filename in enumerate(filenames):\n        filenames[index] = vboxsf_to_windows(filename)",
    "docstring": "Convert filenames from Linux to Windows."
  },
  {
    "code": "def get_timestamp_column(expression, column_name):\n        if expression:\n            return expression\n        elif column_name.lower() != column_name:\n            return f'\"{column_name}\"'\n        return column_name",
    "docstring": "Postgres is unable to identify mixed case column names unless they\n        are quoted."
  },
  {
    "code": "def comment_from_tag(tag):\n    if not tag:\n        return None\n    comment = Comment(name=tag.name,\n                      meta={'description': tag.description},\n                      annotations=tag.annotations)\n    return comment",
    "docstring": "Convenience function to create a full-fledged comment for a\n    given tag, for example it is convenient to assign a Comment\n    to a ReturnValueSymbol."
  },
  {
    "code": "def fit(self, X, y=None):\n        ttype = type_of_target(y)\n        if ttype.startswith(MULTICLASS):\n            self.target_type_ = MULTICLASS\n            self.estimator = OneVsRestClassifier(self.estimator)\n            self._target_labels = np.unique(y)\n            Y = label_binarize(y, classes=self._target_labels)\n        elif ttype.startswith(BINARY):\n            self.target_type_ = BINARY\n            Y = y\n        else:\n            raise YellowbrickValueError((\n                \"{} does not support target type '{}', \"\n                \"please provide a binary or multiclass single-output target\"\n            ).format(\n                self.__class__.__name__, ttype\n            ))\n        return super(PrecisionRecallCurve, self).fit(X, Y)",
    "docstring": "Fit the classification model; if y is multi-class, then the estimator\n        is adapted with a OneVsRestClassifier strategy, otherwise the estimator\n        is fit directly."
  },
  {
    "code": "def check_installation(cur_file):\n  cur_dir = os.path.split(os.path.dirname(os.path.abspath(cur_file)))[0]\n  ch_dir = os.path.split(cleverhans.__path__[0])[0]\n  if cur_dir != ch_dir:\n    warnings.warn(\"It appears that you have at least two versions of \"\n                  \"cleverhans installed, one at %s and one at\"\n                  \" %s. You are running the tutorial script from the \"\n                  \"former but python imported the library module from the \"\n                  \"latter. This may cause errors, for example if the tutorial\"\n                  \" version is newer than the library version and attempts to\"\n                  \" call new features.\" % (cur_dir, ch_dir))",
    "docstring": "Warn user if running cleverhans from a different directory than tutorial."
  },
  {
    "code": "def estimate_gaussian(X):\n    mean = np.mean(X,0)\n    variance = np.var(X,0)\n    return Gaussian(mean,variance)",
    "docstring": "Returns the mean and the variance of a data set of X points assuming that \n    the points come from a gaussian distribution X."
  },
  {
    "code": "def sound_mode(self):\n        sound_mode_matched = self._parent_avr.match_sound_mode(\n            self._parent_avr.sound_mode_raw)\n        return sound_mode_matched",
    "docstring": "Return the matched current sound mode as a string."
  },
  {
    "code": "def encode(self, s):\n    sentence = s\n    tokens = sentence.strip().split()\n    if self._replace_oov is not None:\n      tokens = [t if t in self._token_to_id else self._replace_oov\n                for t in tokens]\n    ret = [self._token_to_id[tok] for tok in tokens]\n    return ret[::-1] if self._reverse else ret",
    "docstring": "Converts a space-separated string of tokens to a list of ids."
  },
  {
    "code": "def map_property_instances(original_part, new_part):\n    get_mapping_dictionary()[original_part.id] = new_part\n    for prop_original in original_part.properties:\n        get_mapping_dictionary()[prop_original.id] = [prop_new for prop_new in new_part.properties if\n                                                      get_mapping_dictionary()[prop_original._json_data['model']].id ==\n                                                      prop_new._json_data['model']][0]",
    "docstring": "Map the id of the original part with the `Part` object of the newly created one.\n\n    Updated the singleton `mapping dictionary` with the new mapping table values.\n\n    :param original_part: `Part` object to be copied/moved\n    :type original_part: :class:`Part`\n    :param new_part: `Part` object copied/moved\n    :type new_part: :class:`Part`\n    :return: None"
  },
  {
    "code": "def unlock(self):\n        success = self.set_status(CONST.STATUS_LOCKOPEN_INT)\n        if success:\n            self._json_state['status'] = CONST.STATUS_LOCKOPEN\n        return success",
    "docstring": "Unlock the device."
  },
  {
    "code": "def send_request(self, request, callback=None, timeout=None, no_response=False):\n        if callback is not None:\n            thread = threading.Thread(target=self._thread_body, args=(request, callback))\n            thread.start()\n        else:\n            self.protocol.send_message(request)\n            if no_response:\n                return\n            try:\n                response = self.queue.get(block=True, timeout=timeout)\n            except Empty:\n                response = None\n            return response",
    "docstring": "Send a request to the remote server.\n\n        :param request: the request to send\n        :param callback: the callback function to invoke upon response\n        :param timeout: the timeout of the request\n        :return: the response"
  },
  {
    "code": "async def update(\n        self,\n        service_id: str,\n        version: str,\n        *,\n        image: str = None,\n        rollback: bool = False\n    ) -> bool:\n        if image is None and rollback is False:\n            raise ValueError(\"You need to specify an image.\")\n        inspect_service = await self.inspect(service_id)\n        spec = inspect_service[\"Spec\"]\n        if image is not None:\n            spec[\"TaskTemplate\"][\"ContainerSpec\"][\"Image\"] = image\n        params = {\"version\": version}\n        if rollback is True:\n            params[\"rollback\"] = \"previous\"\n        data = json.dumps(clean_map(spec))\n        await self.docker._query_json(\n            \"services/{service_id}/update\".format(service_id=service_id),\n            method=\"POST\",\n            data=data,\n            params=params,\n        )\n        return True",
    "docstring": "Update a service.\n        If rollback is True image will be ignored.\n\n        Args:\n            service_id: ID or name of the service.\n            version: Version of the service that you want to update.\n            rollback: Rollback the service to the previous service spec.\n\n        Returns:\n            True if successful."
  },
  {
    "code": "def get_master_url(request, image_id):\n    im = get_object_or_404(MasterImage, pk=image_id)\n    return JsonResponse({'url': im.get_master_url()})",
    "docstring": "get image's master url\n\n    ...\n\n    :param request: http GET request /renderer/master/url/<image_id>/\n    :param image_id: the master image primary key\n    :return: master url in a json dictionary"
  },
  {
    "code": "def GET(self, *args, **kwargs):\n        if self.user_manager.session_logged_in():\n            if not self.user_manager.session_username() and not self.__class__.__name__ == \"ProfilePage\":\n                raise web.seeother(\"/preferences/profile\")\n            if not self.is_lti_page and self.user_manager.session_lti_info() is not None:\n                self.user_manager.disconnect_user()\n                return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), False)\n            return self.GET_AUTH(*args, **kwargs)\n        else:\n            return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), False)",
    "docstring": "Checks if user is authenticated and calls GET_AUTH or performs logout.\n        Otherwise, returns the login template."
  },
  {
    "code": "def record_command(self, cmd, prg=''):\n        self._log(self.logFileCommand , force_to_string(cmd), prg)",
    "docstring": "record the command passed - this is usually the name of the program\n        being run or task being run"
  },
  {
    "code": "def build_from_generator(cls,\n                           generator,\n                           target_size,\n                           max_subtoken_length=None,\n                           reserved_tokens=None):\n    token_counts = collections.defaultdict(int)\n    for item in generator:\n      for tok in tokenizer.encode(native_to_unicode(item)):\n        token_counts[tok] += 1\n    encoder = cls.build_to_target_size(\n        target_size, token_counts, 1, 1e3,\n        max_subtoken_length=max_subtoken_length,\n        reserved_tokens=reserved_tokens)\n    return encoder",
    "docstring": "Builds a SubwordTextEncoder from the generated text.\n\n    Args:\n      generator: yields text.\n      target_size: int, approximate vocabulary size to create.\n      max_subtoken_length: Maximum length of a subtoken. If this is not set,\n        then the runtime and memory use of creating the vocab is quadratic in\n        the length of the longest token. If this is set, then it is instead\n        O(max_subtoken_length * length of longest token).\n      reserved_tokens: List of reserved tokens. The global variable\n        `RESERVED_TOKENS` must be a prefix of `reserved_tokens`. If this\n        argument is `None`, it will use `RESERVED_TOKENS`.\n\n    Returns:\n      SubwordTextEncoder with `vocab_size` approximately `target_size`."
  },
  {
    "code": "def open_links(self):\n        if self._is_open:\n            raise Exception('Already opened')\n        try:\n            self.parallel_safe(lambda scf: scf.open_link())\n            self._is_open = True\n        except Exception as e:\n            self.close_links()\n            raise e",
    "docstring": "Open links to all individuals in the swarm"
  },
  {
    "code": "def getConfigurableParent(cls):\n        for p in cls.__bases__:\n            if isinstance(p, Configurable) and p is not Configurable:\n                return p\n        return None",
    "docstring": "Return the parent from which this class inherits configurations"
  },
  {
    "code": "def CreateTaskStart(self):\n    task_start = TaskStart()\n    task_start.identifier = self.identifier\n    task_start.session_identifier = self.session_identifier\n    task_start.timestamp = self.start_time\n    return task_start",
    "docstring": "Creates a task start.\n\n    Returns:\n      TaskStart: task start attribute container."
  },
  {
    "code": "def bgseq(code):\n    if isinstance(code, str):\n        code = nametonum(code)\n    if code == -1:\n        return \"\"\n    s = termcap.get('setab', code) or termcap.get('setb', code)\n    return s",
    "docstring": "Returns the background color terminal escape sequence for the given color code number."
  },
  {
    "code": "def to_source(node, indentation=' ' * 4):\n  if isinstance(node, gast.AST):\n    node = gast.gast_to_ast(node)\n  generator = SourceWithCommentGenerator(indentation, False,\n                                         astor.string_repr.pretty_string)\n  generator.visit(node)\n  generator.result.append('\\n')\n  return astor.source_repr.pretty_source(generator.result).lstrip()",
    "docstring": "Return source code of a given AST."
  },
  {
    "code": "def is_comparable_type(var, type_):\n    other_types = COMPARABLE_TYPES.get(type_, type_)\n    return isinstance(var, other_types)",
    "docstring": "Check to see if `var` is an instance of known compatible types for `type_`\n\n    Args:\n        var (?):\n        type_ (?):\n\n    Returns:\n        bool:\n\n    CommandLine:\n        python -m utool.util_type is_comparable_type --show\n\n    Example:\n        >>> # DISABLE_DOCTEST\n        >>> from utool.util_type import *  # NOQA\n        >>> import utool as ut\n        >>> flags = []\n        >>> flags += [is_comparable_type(0, float)]\n        >>> flags += [is_comparable_type(0, np.float32)]\n        >>> flags += [is_comparable_type(0, np.int32)]\n        >>> flags += [is_comparable_type(0, int)]\n        >>> flags += [is_comparable_type(0.0, int)]\n        >>> result = ut.repr2(flags)\n        >>> print(result)\n        [True, True, True, True, False]"
  },
  {
    "code": "def get_version_from_file(path):\n    filename = os.path.join(path, VERSION_FILE)\n    if not os.path.isfile(filename):\n        filename = os.path.join(os.path.dirname(path), VERSION_FILE)\n        if not os.path.isfile(filename):\n            filename = ''\n    if filename:\n        with open(filename) as fh:\n            version = fh.readline().strip()\n            if version:\n                return version",
    "docstring": "Find the VERSION_FILE and return its contents.\n\n    Returns\n    -------\n    version : string or None"
  },
  {
    "code": "def solid(self, x, y):\n        if not(0 <= x < self.xsize) or not(0 <= y < self.ysize):\n            return False\n        if self.data[x, y] == 0:\n            return False\n        return True",
    "docstring": "Determine whether the pixel x,y is nonzero\n\n        Parameters\n        ----------\n        x, y : int\n            The pixel of interest.\n\n        Returns\n        -------\n        solid : bool\n            True if the pixel is not zero."
  },
  {
    "code": "def set_statics(self):\n        if not os.path.exists(self.results_dir):\n            return None\n        try:\n            shutil.copytree(os.path.join(self.templates_dir, 'css'), os.path.join(self.results_dir, 'css'))\n            shutil.copytree(os.path.join(self.templates_dir, 'scripts'), os.path.join(self.results_dir, 'scripts'))\n            shutil.copytree(os.path.join(self.templates_dir, 'fonts'), os.path.join(self.results_dir, 'fonts'))\n        except OSError as e:\n            if e.errno == 17:\n                print(\"WARNING : existing output directory for static files, will not replace them\")\n            else:\n                raise\n        try:\n            shutil.copytree(os.path.join(self.templates_dir, 'img'), os.path.join(self.results_dir, 'img'))\n        except OSError as e:\n            pass",
    "docstring": "Create statics directory and copy files in it"
  },
  {
    "code": "def randint(self, a: int, b: int, n: Optional[int] = None) -> Union[List[int], int]:\n        max_n = self.config.MAX_NUMBER_OF_INTEGERS\n        return self._generate_randoms(self._request_randints, max_n=max_n, a=a, b=b, n=n)",
    "docstring": "Generate n numbers as a list or a single one if no n is given.\n\n        n is used to minimize the number of requests made and return type changes to be compatible\n        with :py:mod:`random`'s interface"
  },
  {
    "code": "def cmdline(argv, flags):\n    rules = dict([(flag, {'flags': [\"--%s\" % flag]}) for flag in flags])\n    return parse(argv, rules)",
    "docstring": "A cmdopts wrapper that takes a list of flags and builds the\n       corresponding cmdopts rules to match those flags."
  },
  {
    "code": "def available_packages(*args, **kwargs):\n    try:\n        plugin_packages_info_json = ch.conda_exec('search', '--json',\n                                                  '^microdrop\\.', verbose=False)\n        return json.loads(plugin_packages_info_json)\n    except RuntimeError, exception:\n        if 'CondaHTTPError' in str(exception):\n            logger.warning('Could not connect to Conda server.')\n        else:\n            logger.warning('Error querying available MicroDrop plugins.',\n                           exc_info=True)\n    except Exception, exception:\n        logger.warning('Error querying available MicroDrop plugins.',\n                       exc_info=True)\n    return {}",
    "docstring": "Query available plugin packages based on specified Conda channels.\n\n    Parameters\n    ----------\n    *args\n        Extra arguments to pass to Conda ``search`` command.\n\n    Returns\n    -------\n    dict\n        .. versionchanged:: 0.24\n            All Conda packages beginning with ``microdrop.`` prefix from all\n            configured channels.\n\n        Each *key* corresponds to a package name.\n\n        Each *value* corresponds to a ``list`` of dictionaries, each\n        corresponding to an available version of the respective package.\n\n        For example:\n\n            {\n              \"microdrop.dmf-device-ui-plugin\": [\n                ...\n                {\n                  ...\n                  \"build_number\": 0,\n                  \"channel\": \"microdrop-plugins\",\n                  \"installed\": true,\n                  \"license\": \"BSD\",\n                  \"name\": \"microdrop.dmf-device-ui-plugin\",\n                  \"size\": 62973,\n                  \"version\": \"2.1.post2\",\n                  ...\n                },\n                ...],\n                ...\n            }"
  },
  {
    "code": "def sub_hmm(self, states):\n        r\n        pi_sub = self._Pi[states]\n        pi_sub /= pi_sub.sum()\n        P_sub = self._Tij[states, :][:, states]\n        assert np.all(P_sub.sum(axis=1) > 0), \\\n            'Illegal sub_hmm request: transition matrix cannot be normalized on ' + str(states)\n        P_sub /= P_sub.sum(axis=1)[:, None]\n        out_sub = self.output_model.sub_output_model(states)\n        return HMM(pi_sub, P_sub, out_sub, lag=self.lag)",
    "docstring": "r\"\"\" Returns HMM on a subset of states\n\n        Returns the HMM restricted to the selected subset of states.\n        Will raise exception if the hidden transition matrix cannot be normalized on this subset"
  },
  {
    "code": "def update_record(cls, fqdn, name, type, value, ttl, content):\n        data = {\n            \"rrset_name\": name,\n            \"rrset_type\": type,\n            \"rrset_values\": value,\n        }\n        if ttl:\n            data['rrset_ttl'] = int(ttl)\n        meta = cls.get_fqdn_info(fqdn)\n        if content:\n            url = meta['domain_records_href']\n            kwargs = {'headers': {'Content-Type': 'text/plain'},\n                      'data': content}\n            return cls.json_put(url, **kwargs)\n        url = '%s/domains/%s/records/%s/%s' % (cls.api_url, fqdn, name, type)\n        return cls.json_put(url, data=json.dumps(data))",
    "docstring": "Update all records for a domain."
  },
  {
    "code": "def updateJoin(self):\r\n        text = self.uiJoinSBTN.currentAction().text()\r\n        if text == 'AND':\r\n            joiner = QueryCompound.Op.And\r\n        else:\r\n            joiner = QueryCompound.Op.Or\r\n        self._containerWidget.setCurrentJoiner(self.joiner())",
    "docstring": "Updates the joining method used by the system."
  },
  {
    "code": "def get_action(self, action=None):\n        if action:\n            self.action = action\n        if self.action not in AjaxResponseAction.choices:\n            raise ValueError(\n                \"Invalid action selected: '{}'\".format(self.action))\n        return self.action",
    "docstring": "Returns action to take after call"
  },
  {
    "code": "def _filter(self, criteria: Q, db):\n        negated = criteria.negated\n        input_db = None\n        if criteria.connector == criteria.AND:\n            input_db = db\n            for child in criteria.children:\n                if isinstance(child, Q):\n                    input_db = self._filter(child, input_db)\n                else:\n                    input_db = self.provider._evaluate_lookup(child[0], child[1],\n                                                              negated, input_db)\n        else:\n            input_db = {}\n            for child in criteria.children:\n                if isinstance(child, Q):\n                    results = self._filter(child, db)\n                else:\n                    results = self.provider._evaluate_lookup(child[0], child[1], negated, db)\n                input_db = {**input_db, **results}\n        return input_db",
    "docstring": "Recursive function to filter items from dictionary"
  },
  {
    "code": "def put_file(buffer, modified_file):\n    import mimetypes\n    import boto3\n    file_type, _ = mimetypes.guess_type(modified_file)\n    s3 = boto3.resource('s3')\n    bucket_name, object_key = _parse_s3_file(modified_file)\n    extra_args = {\n        'ACL': 'public-read',\n        'ContentType': file_type\n    }\n    bucket = s3.Bucket(bucket_name)\n    logger.info(\"Uploading {0} to {1}\".format(object_key, bucket_name))\n    bucket.upload_fileobj(buffer, object_key, ExtraArgs=extra_args)",
    "docstring": "write the buffer to modified_file.\n\n    modified_file should be in the format 's3://bucketname/path/to/file.txt'"
  },
  {
    "code": "def is_valid_single_address(self, single_address):\n    if not isinstance(single_address, SingleAddress):\n      raise TypeError(\n        'Parameter \"{}\" is of type {}, expecting type {}.'.format(\n          single_address, type(single_address), SingleAddress))\n    try:\n      return bool(self.scan_specs([single_address]))\n    except AddressLookupError:\n      return False",
    "docstring": "Check if a potentially ambiguous single address spec really exists.\n\n    :param single_address: A SingleAddress spec.\n    :return: True if given spec exists, False otherwise."
  },
  {
    "code": "def _remove_bound_conditions(agent, keep_criterion):\n    new_bc = []\n    for ind in range(len(agent.bound_conditions)):\n        if keep_criterion(agent.bound_conditions[ind].agent):\n            new_bc.append(agent.bound_conditions[ind])\n    agent.bound_conditions = new_bc",
    "docstring": "Removes bound conditions of agent such that keep_criterion is False.\n\n    Parameters\n    ----------\n    agent: Agent\n        The agent whose bound conditions we evaluate\n    keep_criterion: function\n        Evaluates removal_criterion(a) for each agent a in a bound condition\n        and if it evaluates to False, removes a from agent's bound_conditions"
  },
  {
    "code": "def process_superclass(self, entity: List[dict]) -> List[dict]:\n        superclass = entity.pop('superclass')\n        label = entity['label']\n        if not superclass.get('ilx_id'):\n            raise self.SuperClassDoesNotExistError(\n                f'Superclass not given an interlex ID for label: {label}')\n        superclass_data = self.get_entity(superclass['ilx_id'])\n        if not superclass_data['id']:\n            raise self.SuperClassDoesNotExistError(\n                'Superclass ILX ID: ' + superclass['ilx_id'] + ' does not exist in SciCrunch')\n        entity['superclasses'] = [{'superclass_tid': superclass_data['id']}]\n        return entity",
    "docstring": "Replaces ILX ID with superclass ID"
  },
  {
    "code": "def safe_print(ustring, errors='replace', **kwargs):\n    encoding = sys.stdout.encoding or 'utf-8'\n    if sys.version_info[0] == 3:\n        print(ustring, **kwargs)\n    else:\n        bytestr = ustring.encode(encoding, errors=errors)\n        print(bytestr, **kwargs)",
    "docstring": "Safely print a unicode string"
  },
  {
    "code": "def buildEXPmask(self, chip, dqarr):\n        log.info(\"Applying EXPTIME weighting to DQ mask for chip %s\" %\n                 chip)\n        exparr = self._image[self.scienceExt,chip]._exptime\n        expmask = exparr*dqarr\n        return expmask.astype(np.float32)",
    "docstring": "Builds a weight mask from an input DQ array and the exposure time\n        per pixel for this chip."
  },
  {
    "code": "def copy(self, extra=None):\n        if extra is None:\n            extra = dict()\n        bestModel = self.bestModel.copy(extra)\n        avgMetrics = self.avgMetrics\n        subModels = self.subModels\n        return CrossValidatorModel(bestModel, avgMetrics, subModels)",
    "docstring": "Creates a copy of this instance with a randomly generated uid\n        and some extra params. This copies the underlying bestModel,\n        creates a deep copy of the embedded paramMap, and\n        copies the embedded and extra parameters over.\n        It does not copy the extra Params into the subModels.\n\n        :param extra: Extra parameters to copy to the new instance\n        :return: Copy of this instance"
  },
  {
    "code": "def get_variables_path(export_dir):\n  return os.path.join(\n      tf.compat.as_bytes(export_dir),\n      tf.compat.as_bytes(tf_v1.saved_model.constants.VARIABLES_DIRECTORY),\n      tf.compat.as_bytes(tf_v1.saved_model.constants.VARIABLES_FILENAME))",
    "docstring": "Returns the path for storing variables checkpoints."
  },
  {
    "code": "def get_require_by_kind(self, kind, value):\n        for r in self.requires:\n            if r.kind == kind and r.value == value:\n                return r\n        return None",
    "docstring": "Returns a requires object of a specific value"
  },
  {
    "code": "def _is_substitute_element(head, sub):\n    if not isinstance(head, ElementDeclaration) or not isinstance(sub, ElementDeclaration):\n        return False\n    try:\n        group = sub.substitutionGroup \n    except (AttributeError, TypeError):\n        return False\n    ged = GED(*group)\n    print (head.nspname == ged.nspname and head.pname == ged.pname)\n    if head is ged or not (head.nspname == ged.nspname and head.pname == ged.pname):\n        return False\n    return True",
    "docstring": "if head and sub are both GEDs, and sub declares \n    head as its substitutionGroup then return True.\n\n    head -- Typecode instance\n    sub  -- Typecode instance"
  },
  {
    "code": "def wait(self, timeout=None):\n        if self._thread is None:\n            return\n        self._thread.join(timeout=timeout)",
    "docstring": "Blocking wait for task status."
  },
  {
    "code": "def color(self):\n        return self.tty_stream if self.options.color is None \\\n            else self.options.color",
    "docstring": "Whether or not color should be output"
  },
  {
    "code": "def create_logger():\n    global logger\n    formatter = logging.Formatter('%(asctime)s|%(levelname)s|%(message)s')\n    handler = TimedRotatingFileHandler(log_file, when=\"midnight\", interval=1)\n    handler.setFormatter(formatter)\n    handler.setLevel(log_level)\n    handler.suffix = \"%Y-%m-%d\"\n    logger = logging.getLogger(\"sacplus\")\n    logger.setLevel(log_level)\n    logger.addHandler(handler)",
    "docstring": "Initial the global logger variable"
  },
  {
    "code": "def create_estimation_obj(model_obj,\n                          init_vals,\n                          mappings=None,\n                          ridge=None,\n                          constrained_pos=None,\n                          weights=None):\n    mapping_matrices =\\\n        model_obj.get_mappings_for_fit() if mappings is None else mappings\n    zero_vector = np.zeros(init_vals.shape[0])\n    internal_model_name = display_name_to_model_type[model_obj.model_type]\n    estimator_class, current_split_func =\\\n        (model_type_to_resources[internal_model_name]['estimator'],\n         model_type_to_resources[internal_model_name]['split_func'])\n    estimation_obj = estimator_class(model_obj,\n                                     mapping_matrices,\n                                     ridge,\n                                     zero_vector,\n                                     current_split_func,\n                                     constrained_pos,\n                                     weights=weights)\n    return estimation_obj",
    "docstring": "Should return a model estimation object corresponding to the model type of\n    the `model_obj`.\n\n    Parameters\n    ----------\n    model_obj : an instance or sublcass of the MNDC class.\n    init_vals : 1D ndarray.\n        The initial values to start the estimation process with. In the\n        following order, there should be one value for each nest coefficient,\n        shape parameter, outside intercept parameter, or index coefficient that\n        is being estimated.\n    mappings : OrderedDict or None, optional.\n        Keys will be `[\"rows_to_obs\", \"rows_to_alts\", \"chosen_row_to_obs\",\n        \"rows_to_nests\"]`. The value for `rows_to_obs` will map the rows of\n        the `long_form` to the unique observations (on the columns) in\n        their order of appearance. The value for `rows_to_alts` will map\n        the rows of the `long_form` to the unique alternatives which are\n        possible in the dataset (on the columns), in sorted order--not\n        order of appearance. The value for `chosen_row_to_obs`, if not\n        None, will map the rows of the `long_form` that contain the chosen\n        alternatives to the specific observations those rows are associated\n        with (denoted by the columns). The value of `rows_to_nests`, if not\n        None, will map the rows of the `long_form` to the nest (denoted by\n        the column) that contains the row's alternative. Default == None.\n    ridge : int, float, long, or None, optional.\n        Determines whether or not ridge regression is performed. If a\n        scalar is passed, then that scalar determines the ridge penalty for\n        the optimization. The scalar should be greater than or equal to\n        zero. Default `== None`.\n    constrained_pos : list or None, optional.\n        Denotes the positions of the array of estimated parameters that are\n        not to change from their initial values. If a list is passed, the\n        elements are to be integers where no such integer is greater than\n        `init_vals.size.` Default == None.\n    weights : 1D ndarray.\n        Should contain the weights for each corresponding observation for each\n        row of the long format data."
  },
  {
    "code": "def from_dict(d):\n    if isinstance(d, str):\n        return from_json(d)\n    if not isinstance(d, dict):\n        raise TypeError(\"argument must be of type dict\")\n    if 'nparray' not in d.keys():\n        raise ValueError(\"input dictionary missing 'nparray' entry\")\n    classname = d.pop('nparray').title()\n    return getattr(_wrappers, classname)(**d)",
    "docstring": "load an nparray object from a dictionary\n\n    @parameter str d: dictionary representing the nparray object"
  },
  {
    "code": "def _find_base_version_ids(self, symbol, version_ids):\n        cursor = self._versions.find({'symbol': symbol,\n                                      '_id': {'$nin': version_ids},\n                                      'base_version_id': {'$exists': True},\n                                      },\n                                     projection={'base_version_id': 1})\n        return [version[\"base_version_id\"] for version in cursor]",
    "docstring": "Return all base_version_ids for a symbol that are not bases of version_ids"
  },
  {
    "code": "def create_post(self, path, **kw):\n        content = kw.pop('content', None)\n        onefile = kw.pop('onefile', False)\n        kw.pop('is_page', False)\n        metadata = {}\n        metadata.update(self.default_metadata)\n        metadata.update(kw)\n        makedirs(os.path.dirname(path))\n        if not content.endswith('\\n'):\n            content += '\\n'\n        with io.open(path, \"w+\", encoding=\"utf8\") as fd:\n            if onefile:\n                fd.write(write_metadata(metadata, comment_wrap=False, site=self.site, compiler=self))\n            fd.write(content)",
    "docstring": "Create a new post."
  },
  {
    "code": "def data_type_to_numpy(datatype, unsigned=False):\n    basic_type = _dtypeLookup[datatype]\n    if datatype in (stream.STRING, stream.OPAQUE):\n        return np.dtype(basic_type)\n    if unsigned:\n        basic_type = basic_type.replace('i', 'u')\n    return np.dtype('=' + basic_type)",
    "docstring": "Convert an ncstream datatype to a numpy one."
  },
  {
    "code": "def private(self):\n        req = self.request(self.mist_client.uri+'/keys/'+self.id+\"/private\")\n        private = req.get().json()\n        return private",
    "docstring": "Return the private ssh-key\n\n        :returns: The private ssh-key as string"
  },
  {
    "code": "def format_help(self):\n        formatter = self._get_formatter()\n        formatter.add_usage(self.usage, self._actions,\n                            self._mutually_exclusive_groups)\n        formatter.add_text(self.description)\n        for action_group in self._action_groups:\n            if is_subparser(action_group):\n                continue\n            formatter.start_section(action_group.title)\n            formatter.add_text(action_group.description)\n            formatter.add_arguments(action_group._group_actions)\n            formatter.end_section()\n        formatter.add_text(self.epilog)\n        return formatter.format_help()",
    "docstring": "Overrides format_help to not print subparsers"
  },
  {
    "code": "def POST(self, id):\n        id = int(id)\n        model.del_todo(id)\n        raise web.seeother('/')",
    "docstring": "Delete based on ID"
  },
  {
    "code": "def stop_refresh(self):\n        self.logger.debug(\"stopping timed refresh\")\n        self.rf_flags['done'] = True\n        self.rf_timer.clear()",
    "docstring": "Stop redrawing the canvas at the previously set timed interval."
  },
  {
    "code": "def get_email_context(self, activation_key):\n        scheme = 'https' if self.request.is_secure() else 'http'\n        return {\n            'scheme': scheme,\n            'activation_key': activation_key,\n            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,\n            'site': get_current_site(self.request)\n        }",
    "docstring": "Build the template context used for the activation email."
  },
  {
    "code": "def _key(self, additional_key: Any=None) -> str:\n        return '_'.join([self.key, str(self.clock()), str(additional_key), str(self.seed)])",
    "docstring": "Construct a hashable key from this object's state.\n\n        Parameters\n        ----------\n        additional_key :\n            Any additional information used to seed random number generation.\n\n        Returns\n        -------\n        str\n            A key to seed random number generation."
  },
  {
    "code": "def _make_parser(streamer, the_struct):\n    \"Return a function that parses the given structure into a dict\"\n    struct_items = [s.split(\":\") for s in the_struct.split()]\n    names = [s[0] for s in struct_items]\n    types = ''.join(s[1] for s in struct_items)\n    def f(message_stream):\n        return streamer.parse_as_dict(names, types, message_stream)\n    return f",
    "docstring": "Return a function that parses the given structure into a dict"
  },
  {
    "code": "def _fit_stage_componentwise(X, residuals, sample_weight, **fit_params):\n    n_features = X.shape[1]\n    base_learners = []\n    error = numpy.empty(n_features)\n    for component in range(n_features):\n        learner = ComponentwiseLeastSquares(component).fit(X, residuals, sample_weight)\n        l_pred = learner.predict(X)\n        error[component] = squared_norm(residuals - l_pred)\n        base_learners.append(learner)\n    best_component = numpy.nanargmin(error)\n    best_learner = base_learners[best_component]\n    return best_learner",
    "docstring": "Fit component-wise weighted least squares model"
  },
  {
    "code": "def check(self, data):\n        if isinstance(data, Iterable):\n            data = \"\".join(str(x) for x in data)\n        try:\n            data = str(data)\n        except UnicodeDecodeError:\n            return False\n        return bool(data and self.__regexp.match(data))",
    "docstring": "returns True if any match any regexp"
  },
  {
    "code": "def codes_get_string_array(handle, key, size, length=None):\n    if length is None:\n        length = codes_get_string_length(handle, key)\n    values_keepalive = [ffi.new('char[]', length) for _ in range(size)]\n    values = ffi.new('char*[]', values_keepalive)\n    size_p = ffi.new('size_t *', size)\n    _codes_get_string_array(handle, key.encode(ENC), values, size_p)\n    return [ffi.string(values[i]).decode(ENC) for i in range(size_p[0])]",
    "docstring": "Get string array values from a key.\n\n    :param bytes key: the keyword whose value(s) are to be extracted\n\n    :rtype: T.List[bytes]"
  },
  {
    "code": "def manifestation_model_factory(*, validator=validators.is_manifestation_model,\n                                ld_type='CreativeWork', **kwargs):\n    return _model_factory(validator=validator, ld_type=ld_type, **kwargs)",
    "docstring": "Generate a Manifestation model.\n\n    Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and\n    ``ld_context`` as keyword arguments."
  },
  {
    "code": "def _on_cancelok(self, cancel_frame):\n        _log.info(\"Consumer canceled; returning all unprocessed messages to the queue\")\n        self._channel.basic_nack(delivery_tag=0, multiple=True, requeue=True)",
    "docstring": "Called when the server acknowledges a cancel request.\n\n        Args:\n            cancel_frame (pika.spec.Basic.CancelOk): The cancelok frame from\n                the server."
  },
  {
    "code": "def put(self, measurementId):\n        json = request.get_json()\n        try:\n            start = self._calculateStartTime(json)\n        except ValueError:\n            return 'invalid date format in request', 400\n        duration = json['duration'] if 'duration' in json else 10\n        if start is None:\n            return 'no start time', 400\n        else:\n            scheduled, message = self._measurementController.schedule(measurementId, duration, start,\n                                                                      description=json.get('description'))\n            return message, 200 if scheduled else 400",
    "docstring": "Initiates a new measurement. Accepts a json payload with the following attributes;\n\n        * duration: in seconds\n        * startTime OR delay: a date in YMD_HMS format or a delay in seconds\n        * description: some free text information about the measurement\n\n        :return:"
  },
  {
    "code": "def verification_events(self):\n        queued = self._assemble_event('Verifier_Queued')\n        started = self._assemble_event('Verifier_Started')\n        return [x for x in [queued, started] if x]",
    "docstring": "Events related to command verification.\n\n        :type: List[:class:`.CommandHistoryEvent`]"
  },
  {
    "code": "def shell_command(class_path):\n    loader = ClassLoader(*class_path)\n    shell.start_shell(local_ns={\n        'ClassFile': ClassFile,\n        'loader': loader,\n        'constants': importlib.import_module('jawa.constants'),\n    })",
    "docstring": "Drop into a debugging shell."
  },
  {
    "code": "def cleanup(self):\n        shutil.rmtree(self.temp_tagdir)\n        parentdir = os.path.dirname(self.temp_tagdir)\n        if os.path.basename(parentdir).startswith(self.package):\n            os.rmdir(parentdir)\n        os.chdir(self.start_directory)",
    "docstring": "Clean up temporary tag checkout dir."
  },
  {
    "code": "def add_if_unique(self, name):\n        with self.lock:\n            if name not in self.names:\n                self.names.append(name)\n                return True\n        return False",
    "docstring": "Returns ``True`` on success.\n\n        Returns ``False`` if the name already exists in the namespace."
  },
  {
    "code": "def get_cmd_out(command):\n\tif isinstance(command, list):\n\t\tresult = sp.check_output(command)\n\telse:\n\t\tresult = sp.check_output(command, shell=True)\n\treturn result.decode('utf-8').rstrip()",
    "docstring": "Get the output of a command.\n\n\tGets a nice Unicode no-extra-whitespace string of the ``stdout`` of a given command.\n\n\tArgs:\n\t\t\tcommand (str or list): A string of the command, or a list of the arguments (as would be used in :class:`subprocess.Popen`).\n\n\tNote:\n\t\t\tIf ``command`` is a ``str``, it will be evaluated with ``shell=True`` i.e. in the default shell (for example, bash).\n\n\tReturns:\n\t\t\tstr: The ``stdout`` of the command."
  },
  {
    "code": "def new_action(self, method='GET', **kwargs):\n        if method not in self.methods:\n            raise TypeError('{} not in valid method(s): {}.'.format(method, self.methods))\n        return Action(self, method, **kwargs)",
    "docstring": "Create a new Action linked to this endpoint with the given args."
  },
  {
    "code": "def search_index_advanced(self, index, query):\n        request = self.session\n        url = 'http://%s:%s/%s/_search' % (self.host, self.port, index)\n        if self.params:\n            content = dict(query=query, **self.params)\n        else:\n            content = dict(query=query)\n        if self.verbose:\n            print content\n        response = request.post(url,content)\n        return response",
    "docstring": "Advanced search query against an entire index\n\n        > query = ElasticQuery().query_string(query='imchi')\n        > search = ElasticSearch()"
  },
  {
    "code": "def pop_choice(self, key: str, choices: List[Any], default_to_first_choice: bool = False) -> Any:\n        default = choices[0] if default_to_first_choice else self.DEFAULT\n        value = self.pop(key, default)\n        if value not in choices:\n            key_str = self.history + key\n            message = '%s not in acceptable choices for %s: %s' % (value, key_str, str(choices))\n            raise ConfigurationError(message)\n        return value",
    "docstring": "Gets the value of ``key`` in the ``params`` dictionary, ensuring that the value is one of\n        the given choices. Note that this `pops` the key from params, modifying the dictionary,\n        consistent with how parameters are processed in this codebase.\n\n        Parameters\n        ----------\n        key: str\n            Key to get the value from in the param dictionary\n        choices: List[Any]\n            A list of valid options for values corresponding to ``key``.  For example, if you're\n            specifying the type of encoder to use for some part of your model, the choices might be\n            the list of encoder classes we know about and can instantiate.  If the value we find in\n            the param dictionary is not in ``choices``, we raise a ``ConfigurationError``, because\n            the user specified an invalid value in their parameter file.\n        default_to_first_choice: bool, optional (default=False)\n            If this is ``True``, we allow the ``key`` to not be present in the parameter\n            dictionary.  If the key is not present, we will use the return as the value the first\n            choice in the ``choices`` list.  If this is ``False``, we raise a\n            ``ConfigurationError``, because specifying the ``key`` is required (e.g., you `have` to\n            specify your model class when running an experiment, but you can feel free to use\n            default settings for encoders if you want)."
  },
  {
    "code": "def deprecated(fun_name=None, msg=\"\"):\n    def _deprecated(fun):\n        @wraps(fun)\n        def _wrapper(*args, **kwargs):\n            name = fun_name if fun_name is not None else fun.__name__\n            _warn_deprecated('Call to deprecated function %s. %s' % (name, msg))\n            return fun(*args, **kwargs)\n        return _wrapper\n    return _deprecated",
    "docstring": "Issue a deprecation warning for a function"
  },
  {
    "code": "def services_resolved(self):\n        self._disconnect_service_signals()\n        services_regex = re.compile(self._device_path + '/service[0-9abcdef]{4}$')\n        managed_services = [\n            service for service in self._object_manager.GetManagedObjects().items()\n            if services_regex.match(service[0])]\n        self.services = [Service(\n            device=self,\n            path=service[0],\n            uuid=service[1]['org.bluez.GattService1']['UUID']) for service in managed_services]\n        self._connect_service_signals()",
    "docstring": "Called when all device's services and characteristics got resolved."
  },
  {
    "code": "def bind_key_name(self, function, object_name):\r\n        for funcname, name in self.name_map.items():\r\n            if funcname == function:\r\n                self.name_map[\r\n                    funcname] = object_name",
    "docstring": "Bind a key to an object name"
  },
  {
    "code": "def _get_openscm_var_from_filepath(filepath):\n    reader = determine_tool(filepath, \"reader\")(filepath)\n    openscm_var = convert_magicc7_to_openscm_variables(\n        convert_magicc6_to_magicc7_variables(reader._get_variable_from_filepath())\n    )\n    return openscm_var",
    "docstring": "Determine the OpenSCM variable from a filepath.\n\n    Uses MAGICC's internal, implicit, filenaming conventions.\n\n    Parameters\n    ----------\n    filepath : str\n        Filepath from which to determine the OpenSCM variable.\n\n    Returns\n    -------\n    str\n        The OpenSCM variable implied by the filepath."
  },
  {
    "code": "def true_range(close_data, period):\n    catch_errors.check_for_period_error(close_data, period)\n    tr = [np.max([np.max(close_data[idx+1-period:idx+1]) -\n                np.min(close_data[idx+1-period:idx+1]),\n                abs(np.max(close_data[idx+1-period:idx+1]) -\n                close_data[idx-1]),\n                abs(np.min(close_data[idx+1-period:idx+1]) -\n                close_data[idx-1])]) for idx in range(period-1, len(close_data))]\n    tr = fill_for_noncomputable_vals(close_data, tr)\n    return tr",
    "docstring": "True Range.\n\n    Formula:\n    TRt = MAX(abs(Ht - Lt), abs(Ht - Ct-1), abs(Lt - Ct-1))"
  },
  {
    "code": "def _poll_once(self, timeout_ms, max_records):\n        self._coordinator.poll()\n        if not self._subscription.has_all_fetch_positions():\n            self._update_fetch_positions(self._subscription.missing_fetch_positions())\n        records, partial = self._fetcher.fetched_records(max_records)\n        if records:\n            if not partial:\n                self._fetcher.send_fetches()\n            return records\n        self._fetcher.send_fetches()\n        timeout_ms = min(timeout_ms, self._coordinator.time_to_next_poll() * 1000)\n        self._client.poll(timeout_ms=timeout_ms)\n        if self._coordinator.need_rejoin():\n            return {}\n        records, _ = self._fetcher.fetched_records(max_records)\n        return records",
    "docstring": "Do one round of polling. In addition to checking for new data, this does\n        any needed heart-beating, auto-commits, and offset updates.\n\n        Arguments:\n            timeout_ms (int): The maximum time in milliseconds to block.\n\n        Returns:\n            dict: Map of topic to list of records (may be empty)."
  },
  {
    "code": "def type_name(value):\n    if inspect.isclass(value):\n        cls = value\n    else:\n        cls = value.__class__\n    if cls.__module__ in set(['builtins', '__builtin__']):\n        return cls.__name__\n    return '%s.%s' % (cls.__module__, cls.__name__)",
    "docstring": "Returns a user-readable name for the type of an object\n\n    :param value:\n        A value to get the type name of\n\n    :return:\n        A unicode string of the object's type name"
  },
  {
    "code": "def get_download_link(self):\n        url = None\n        if not self.get(\"downloadable\"):\n            try:\n                url = self.client.get_location(\n                    self.client.STREAM_URL % self.get(\"id\"))\n            except serror as e:\n                print(e)\n        if not url:\n            try:\n                url = self.client.get_location(\n                    self.client.DOWNLOAD_URL % self.get(\"id\"))\n            except serror as e:\n                print(e)\n        return url",
    "docstring": "Get direct download link with soudcloud's redirect system."
  },
  {
    "code": "def delete_rule(self, rule_id):\n        if rule_id not in self.rules:\n            LOG.error(\"No Rule id present for deleting %s\", rule_id)\n            return\n        del self.rules[rule_id]\n        self.rule_cnt -= 1",
    "docstring": "Delete the specific Rule from dictionary indexed by rule id."
  },
  {
    "code": "def create_new(cls, mapreduce_id, shard_number):\n    shard_id = cls.shard_id_from_number(mapreduce_id, shard_number)\n    state = cls(key_name=shard_id,\n                mapreduce_id=mapreduce_id)\n    return state",
    "docstring": "Create new shard state.\n\n    Args:\n      mapreduce_id: unique mapreduce id as string.\n      shard_number: shard number for which to create shard state.\n\n    Returns:\n      new instance of ShardState ready to put into datastore."
  },
  {
    "code": "def _default_next_colour(particle):\n        return particle.colours[\n            (len(particle.colours) - 1) * particle.time // particle.life_time]",
    "docstring": "Default next colour implementation - linear progression through\n        each colour tuple."
  },
  {
    "code": "def to_dict(self, index=True, ordered=False):\n        result = OrderedDict() if ordered else dict()\n        if index:\n            result.update({self._index_name: self._index})\n        if ordered:\n            data_dict = [(self._data_name, self._data)]\n        else:\n            data_dict = {self._data_name: self._data}\n        result.update(data_dict)\n        return result",
    "docstring": "Returns a dict where the keys are the data and index names and the values are list of the data and index.\n\n        :param index: If True then include the index in the dict with the index_name as the key\n        :param ordered: If True then return an OrderedDict() to preserve the order of the columns in the Series\n        :return: dict or OrderedDict()"
  },
  {
    "code": "def _load_from_tar(self, dtype_out_time, dtype_out_vert=False):\n        path = os.path.join(self.dir_tar_out, 'data.tar')\n        utils.io.dmget([path])\n        with tarfile.open(path, 'r') as data_tar:\n            ds = xr.open_dataset(\n                data_tar.extractfile(self.file_name[dtype_out_time])\n            )\n            return ds[self.name]",
    "docstring": "Load data save in tarball form on the file system."
  },
  {
    "code": "async def build(self, building: UnitTypeId, near: Union[Point2, Point3], max_distance: int=20, unit: Optional[Unit]=None, random_alternative: bool=True, placement_step: int=2):\n        if isinstance(near, Unit):\n            near = near.position.to2\n        elif near is not None:\n            near = near.to2\n        else:\n            return\n        p = await self.find_placement(building, near.rounded, max_distance, random_alternative, placement_step)\n        if p is None:\n            return ActionResult.CantFindPlacementLocation\n        unit = unit or self.select_build_worker(p)\n        if unit is None or not self.can_afford(building):\n            return ActionResult.Error\n        return await self.do(unit.build(building, p))",
    "docstring": "Build a building."
  },
  {
    "code": "def hello(event, context):\n    body = {\n        \"message\": \"Go Serverless v1.0! Your function executed successfully!\",\n        \"input\": event\n    }\n    response = {\n        \"statusCode\": 200,\n        \"body\": json.dumps(body)\n    }\n    return response",
    "docstring": "Return Serverless Hello World."
  },
  {
    "code": "def MergeAllSummaries(period=0, run_alone=False, key=None):\n    if key is None:\n        key = tf.GraphKeys.SUMMARIES\n    period = int(period)\n    if run_alone:\n        return MergeAllSummaries_RunAlone(period, key)\n    else:\n        return MergeAllSummaries_RunWithOp(period, key)",
    "docstring": "This callback is enabled by default.\n    Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs.\n\n    Args:\n        period (int): by default the callback summarizes once every epoch.\n            This option (if not set to 0) makes it additionally summarize every ``period`` steps.\n        run_alone (bool): whether to evaluate the summaries alone.\n            If True, summaries will be evaluated after each epoch alone.\n            If False, summaries will be evaluated together with the\n            `sess.run` calls, in the last step of each epoch.\n            For :class:`SimpleTrainer`, it needs to be False because summary may\n            depend on inputs.\n        key (str): the collection of summary tensors. Same as in ``tf.summary.merge_all``.\n            Default is ``tf.GraphKeys.SUMMARIES``."
  },
  {
    "code": "def links(self):\n        headers = self.headers or {}\n        header = headers.get('link')\n        li = {}\n        if header:\n            links = parse_header_links(header)\n            for link in links:\n                key = link.get('rel') or link.get('url')\n                li[key] = link\n        return li",
    "docstring": "Returns the parsed header links of the response, if any"
  },
  {
    "code": "def _check_repo_sign_utils_support(name):\n    if salt.utils.path.which(name):\n        return True\n    else:\n        raise CommandExecutionError(\n            'utility \\'{0}\\' needs to be installed or made available in search path'.format(name)\n        )",
    "docstring": "Check for specified command name in search path"
  },
  {
    "code": "def close_connection(self):\n        self._logger.info('Closing connection')\n        self._closing = True\n        self._connection.close()",
    "docstring": "This method closes the connection to RabbitMQ."
  },
  {
    "code": "def ISIs(self,time_dimension=0,units=None,min_t=None,max_t=None):\n        units = self._default_units(units)\n        converted_dimension,st = self.spike_times.get_converted(time_dimension,units)\n        if min_t is None:\n            min_t = converted_dimension.min\n        if max_t is None:\n            max_t = converted_dimension.max\n        return np.diff(sorted(st[(st>min_t) * (st <max_t)]))",
    "docstring": "returns the Inter Spike Intervals\n\n                `time_dimension`: which dimension contains the spike times (by default the first)\n\n                `units`,`min_t`,`max_t`: define the units of the output and the range of spikes that should be considered"
  },
  {
    "code": "def remove(self, id_filter):\n        if not is_valid_int_param(id_filter):\n            raise InvalidParameterError(\n                u'The identifier of Filter is invalid or was not informed.')\n        url = 'filter/' + str(id_filter) + '/'\n        code, xml = self.submit(None, 'DELETE', url)\n        return self.response(code, xml)",
    "docstring": "Remove Filter by the identifier.\n\n        :param id_filter: Identifier of the Filter. Integer value and greater than zero.\n\n        :return: None\n\n        :raise InvalidParameterError: Filter identifier is null and invalid.\n        :raise FilterNotFoundError: Filter not registered.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def write(self, data: bytes) -> None:\n        if self.finished():\n            if self._exc:\n                raise self._exc\n            raise WriteAfterFinishedError\n        if not data:\n            return\n        try:\n            self._delegate.write_data(data, finished=False)\n        except BaseWriteException as e:\n            self._finished.set()\n            if self._exc is None:\n                self._exc = e\n            raise",
    "docstring": "Write the data."
  },
  {
    "code": "def static_singleton(*args, **kwargs):\n    def __static_singleton_wrapper(cls):\n        if cls not in __singleton_instances:\n            __singleton_instances[cls] = cls(*args, **kwargs)\n        return __singleton_instances[cls]\n    return __static_singleton_wrapper",
    "docstring": "STATIC Singleton Design Pattern Decorator\n    Class is initialized with arguments passed into the decorator.\n\n    :Usage: \n     >>> @static_singleton('yop')\n        class Bob(Person):\n            def __init__(arg1):\n                self.info = arg1\n            def says(self):\n                print self.info\n        b1 = Bob #note that we call it by the name of the class, no instance created here, kind of static linking to an instance\n        b2 = Bob #here b1 is the same object as b2\n        Bob.says() # it will display 'yop'"
  },
  {
    "code": "def domain(self, default):\n        inferred = infer_domain(self._output_terms)\n        if inferred is GENERIC and self._domain is GENERIC:\n            return default\n        elif inferred is GENERIC and self._domain is not GENERIC:\n            return self._domain\n        elif inferred is not GENERIC and self._domain is GENERIC:\n            return inferred\n        else:\n            if inferred is not self._domain:\n                raise ValueError(\n                    \"Conflicting domains in Pipeline. Inferred {}, but {} was \"\n                    \"passed at construction.\".format(inferred, self._domain)\n                )\n            return inferred",
    "docstring": "Get the domain for this pipeline.\n\n        - If an explicit domain was provided at construction time, use it.\n        - Otherwise, infer a domain from the registered columns.\n        - If no domain can be inferred, return ``default``.\n\n        Parameters\n        ----------\n        default : zipline.pipeline.Domain\n            Domain to use if no domain can be inferred from this pipeline by\n            itself.\n\n        Returns\n        -------\n        domain : zipline.pipeline.Domain\n            The domain for the pipeline.\n\n        Raises\n        ------\n        AmbiguousDomain\n        ValueError\n            If the terms in ``self`` conflict with self._domain."
  },
  {
    "code": "def capture(self):\n\t\tcaptured_charge = self.api_retrieve().capture()\n\t\treturn self.__class__.sync_from_stripe_data(captured_charge)",
    "docstring": "Capture the payment of an existing, uncaptured, charge.\n\t\tThis is the second half of the two-step payment flow, where first you\n\t\tcreated a charge with the capture option set to False.\n\n\t\tSee https://stripe.com/docs/api#capture_charge"
  },
  {
    "code": "def send_request(self, request):\n        logger.debug(\"send_request - \" + str(request))\n        assert isinstance(request, Request)\n        try:\n            host, port = request.destination\n        except AttributeError:\n            return\n        request.timestamp = time.time()\n        transaction = Transaction(request=request, timestamp=request.timestamp)\n        if transaction.request.type is None:\n            transaction.request.type = defines.Types[\"CON\"]\n        if transaction.request.mid is None:\n            transaction.request.mid = self.fetch_mid()\n        key_mid = str_append_hash(host, port, request.mid)\n        self._transactions[key_mid] = transaction\n        key_token = str_append_hash(host, port, request.token)\n        self._transactions_token[key_token] = transaction\n        return self._transactions[key_mid]",
    "docstring": "Create the transaction and fill it with the outgoing request.\n\n        :type request: Request\n        :param request: the request to send\n        :rtype : Transaction\n        :return: the created transaction"
  },
  {
    "code": "def fetch(\n            self,\n            url,\n            filename=None,\n            decompress=False,\n            force=False,\n            timeout=None,\n            use_wget_if_available=True):\n        key = (url, decompress)\n        if not force and key in self._local_paths:\n            path = self._local_paths[key]\n            if exists(path):\n                return path\n            else:\n                del self._local_paths[key]\n        path = download.fetch_file(\n            url,\n            filename=filename,\n            decompress=decompress,\n            subdir=self.subdir,\n            force=force,\n            timeout=timeout,\n            use_wget_if_available=use_wget_if_available)\n        self._local_paths[key] = path\n        return path",
    "docstring": "Return the local path to the downloaded copy of a given URL.\n        Don't download the file again if it's already present,\n        unless `force` is True."
  },
  {
    "code": "def _get_revision(self):\n        assert self._revisions, \"no migration revision exist\"\n        revision = self._rev or self._revisions[-1]\n        assert revision in self._revisions, \"invalid revision specified\"\n        return revision",
    "docstring": "Validate and return the revision to use for current command"
  },
  {
    "code": "def fromovl(args):\n    p = OptionParser(fromovl.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n    ovlfile, fastafile = args\n    ovl = OVL(ovlfile)\n    g = ovl.graph\n    fw = open(\"contained.ids\", \"w\")\n    print(\"\\n\".join(sorted(ovl.contained)), file=fw)\n    graph_to_agp(g, ovlfile, fastafile, exclude=ovl.contained, verbose=False)",
    "docstring": "%prog graph nucmer2ovl.ovl fastafile\n\n    Build overlap graph from ovl file which is converted using NUCMER2OVL."
  },
  {
    "code": "def getcolors(spec, n, cmap=None, value=None):\n    if cmap is not None and spec is not None:\n        from matplotlib.colors import LinearSegmentedColormap\n        from matplotlib.cm import get_cmap\n        if isinstance(cmap, LinearSegmentedColormap):\n            return cmap(value)[:, 0:3]\n        if isinstance(cmap, str):\n            return get_cmap(cmap, n)(value)[:, 0:3]\n    if isinstance(spec, str):\n        return [getcolor(spec) for i in range(n)]\n    elif isinstance(spec, list) and isinstance(spec[0], str):\n        return [getcolor(s) for s in spec]\n    elif (isinstance(spec, list) or isinstance(spec, ndarray)) and asarray(spec).shape == (3,):\n        return [spec for i in range(n)]\n    else:\n        return spec",
    "docstring": "Turn list of color specs into list of arrays."
  },
  {
    "code": "def kill_pid(pid, signal=15):\n    try:\n        psutil.Process(pid).send_signal(signal)\n        return True\n    except psutil.NoSuchProcess:\n        return False",
    "docstring": "Kill a process by PID.\n\n    .. code-block:: bash\n\n        salt 'minion' ps.kill_pid pid [signal=signal_number]\n\n    pid\n        PID of process to kill.\n\n    signal\n        Signal to send to the process. See manpage entry for kill\n        for possible values. Default: 15 (SIGTERM).\n\n    **Example:**\n\n    Send SIGKILL to process with PID 2000:\n\n    .. code-block:: bash\n\n        salt 'minion' ps.kill_pid 2000 signal=9"
  },
  {
    "code": "def all_points_mutual_reachability(X, labels, cluster_id,\n                                   metric='euclidean', d=None, **kwd_args):\n    if metric == 'precomputed':\n        if d is None:\n            raise ValueError('If metric is precomputed a '\n                             'd value must be provided!')\n        distance_matrix = X[labels == cluster_id, :][:, labels == cluster_id]\n    else:\n        subset_X = X[labels == cluster_id, :]\n        distance_matrix = pairwise_distances(subset_X, metric=metric,\n                                             **kwd_args)\n        d = X.shape[1]\n    core_distances = all_points_core_distance(distance_matrix.copy(), d=d)\n    core_dist_matrix = np.tile(core_distances, (core_distances.shape[0], 1))\n    result = np.dstack(\n        [distance_matrix, core_dist_matrix, core_dist_matrix.T]).max(axis=-1)\n    return result, core_distances",
    "docstring": "Compute the all-points-mutual-reachability distances for all the points of\n    a cluster.\n\n    If metric is 'precomputed' then assume X is a distance matrix for the full\n    dataset. Note that in this case you must pass in 'd' the dimension of the\n    dataset.\n\n    Parameters\n    ----------\n    X : array (n_samples, n_features) or (n_samples, n_samples)\n        The input data of the clustering. This can be the data, or, if\n        metric is set to `precomputed` the pairwise distance matrix used\n        for the clustering.\n\n    labels : array (n_samples)\n        The label array output by the clustering, providing an integral\n        cluster label to each data point, with -1 for noise points.\n\n    cluster_id : integer\n        The cluster label for which to compute the all-points\n        mutual-reachability (which should be done on a cluster\n        by cluster basis).\n\n    metric : string\n        The metric used to compute distances for the clustering (and\n        to be re-used in computing distances for mr distance). If\n        set to `precomputed` then X is assumed to be the precomputed\n        distance matrix between samples.\n\n    d : integer (or None)\n        The number of features (dimension) of the dataset. This need only\n        be set in the case of metric being set to `precomputed`, where\n        the ambient dimension of the data is unknown to the function.\n\n    **kwd_args :\n        Extra arguments to pass to the distance computation for other\n        metrics, such as minkowski, Mahanalobis etc.\n\n    Returns\n    -------\n\n    mutual_reachaibility : array (n_samples, n_samples)\n        The pairwise mutual reachability distances between all points in `X`\n        with `label` equal to `cluster_id`.\n\n    core_distances : array (n_samples,)\n        The all-points-core_distance of all points in `X` with `label` equal\n        to `cluster_id`.\n\n    References\n    ----------\n    Moulavi, D., Jaskowiak, P.A., Campello, R.J., Zimek, A. and Sander, J.,\n    2014. Density-Based Clustering Validation. In SDM (pp. 839-847)."
  },
  {
    "code": "def get_capacity_grav(self, min_voltage=None, max_voltage=None,\n                          use_overall_normalization=True):\n        pairs_in_range = self._select_in_voltage_range(min_voltage,\n                                                       max_voltage)\n        normalization_mass = self.normalization_mass \\\n            if use_overall_normalization or len(pairs_in_range) == 0 \\\n            else pairs_in_range[-1].mass_discharge\n        return sum([pair.mAh for pair in pairs_in_range]) / normalization_mass",
    "docstring": "Get the gravimetric capacity of the electrode.\n\n        Args:\n            min_voltage (float): The minimum allowable voltage for a given\n                step.\n            max_voltage (float): The maximum allowable voltage allowable for a\n                given step.\n            use_overall_normalization (booL): If False, normalize by the\n                discharged state of only the voltage pairs matching the voltage\n                criteria. if True, use default normalization of the full\n                electrode path.\n\n        Returns:\n            Gravimetric capacity in mAh/g across the insertion path (a subset\n            of the path can be chosen by the optional arguments)."
  },
  {
    "code": "def connect(self):\n        connection_method = 'SMTP_SSL' if self.ssl else 'SMTP'\n        self._logger.debug('Trying to connect via {}'.format(connection_method))\n        smtp = getattr(smtplib, connection_method)\n        if self.port:\n            self._smtp = smtp(self.address, self.port)\n        else:\n            self._smtp = smtp(self.address)\n        self._smtp.ehlo()\n        if self.tls:\n            self._smtp.starttls()\n            self._smtp.ehlo()\n        self._logger.info('Got smtp connection')\n        if self.username and self.password:\n            self._logger.info('Logging in')\n            self._smtp.login(self.username, self.password)\n        self._connected = True",
    "docstring": "Initializes a connection to the smtp server\n\n        :return: True on success, False otherwise"
  },
  {
    "code": "def attach_log_stream(self):\n        if self.has_api_logs:\n            self.log_stream = self.attach(stdout=True, stderr=True, stream=True)",
    "docstring": "A log stream can only be attached if the container uses a json-file\n        log driver."
  },
  {
    "code": "def _iter_dimensions(self):\n        return (\n            Dimension(raw_dimension.dimension_dict, raw_dimension.dimension_type)\n            for raw_dimension in self._raw_dimensions\n        )",
    "docstring": "Generate Dimension object for each dimension dict."
  },
  {
    "code": "def build(self):\n        p = self.do_build()\n        p += self.build_padding()\n        p = self.build_done(p)\n        return p",
    "docstring": "Create the current layer\n\n        :return: string of the packet with the payload"
  },
  {
    "code": "def add_assertions(self, *assertions):\n        for assertion in assertions:\n            if isinstance(assertion, IndependenceAssertion):\n                self.independencies.append(assertion)\n            else:\n                try:\n                    self.independencies.append(IndependenceAssertion(assertion[0], assertion[1], assertion[2]))\n                except IndexError:\n                    self.independencies.append(IndependenceAssertion(assertion[0], assertion[1]))",
    "docstring": "Adds assertions to independencies.\n\n        Parameters\n        ----------\n        assertions: Lists or Tuples\n                Each assertion is a list or tuple of variable, independent_of and given.\n\n        Examples\n        --------\n        >>> from pgmpy.independencies import Independencies\n        >>> independencies = Independencies()\n        >>> independencies.add_assertions(['X', 'Y', 'Z'])\n        >>> independencies.add_assertions(['a', ['b', 'c'], 'd'])"
  },
  {
    "code": "def create(cls, tokens:Tokens, max_vocab:int, min_freq:int) -> 'Vocab':\n        \"Create a vocabulary from a set of `tokens`.\"\n        freq = Counter(p for o in tokens for p in o)\n        itos = [o for o,c in freq.most_common(max_vocab) if c >= min_freq]\n        for o in reversed(defaults.text_spec_tok):\n            if o in itos: itos.remove(o)\n            itos.insert(0, o)\n        return cls(itos)",
    "docstring": "Create a vocabulary from a set of `tokens`."
  },
  {
    "code": "def create_page(cls, webdriver=None, **kwargs):\n        if not webdriver:\n            webdriver = WTF_WEBDRIVER_MANAGER.get_driver()\n        return PageFactory.create_page(cls, webdriver=webdriver, **kwargs)",
    "docstring": "Class method short cut to call PageFactory on itself.  Use it to instantiate \n        this PageObject using a webdriver.\n\n        Args:\n            webdriver (Webdriver): Instance of Selenium Webdriver.\n\n        Returns:\n            PageObject\n\n        Raises:\n            InvalidPageError"
  },
  {
    "code": "def __search(self, value, type_attribute):\n        results = []\n        if not value:\n            raise EmptySearchtermError\n        for idx, connection in enumerate(self.misp_connections):\n            misp_response = connection.search(type_attribute=type_attribute, values=value)\n            if isinstance(self.misp_name, list):\n                name = self.misp_name[idx]\n            else:\n                name = self.misp_name\n            results.append({'url': connection.root_url,\n                            'name': name,\n                            'result': self.__clean(misp_response)})\n        return results",
    "docstring": "Search method call wrapper.\n\n        :param value: value to search for.\n        :type value: str\n        :param type_attribute: attribute types to search for.\n        :type type_attribute: [list, none]"
  },
  {
    "code": "def accuracy_thresh_expand(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True)->Rank0Tensor:\n    \"Compute accuracy after expanding `y_true` to the size of `y_pred`.\"\n    if sigmoid: y_pred = y_pred.sigmoid()\n    return ((y_pred>thresh)==y_true[:,None].expand_as(y_pred).byte()).float().mean()",
    "docstring": "Compute accuracy after expanding `y_true` to the size of `y_pred`."
  },
  {
    "code": "def devices():\n    out = __salt__['cmd.run_all'](\"blkid -o export\")\n    salt.utils.fsutils._verify_run(out)\n    return salt.utils.fsutils._blkid_output(out['stdout'], fs_type='btrfs')",
    "docstring": "Get known BTRFS formatted devices on the system.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' btrfs.devices"
  },
  {
    "code": "def is_default(self):\n        for field in self._fields:\n            if not field.is_default():\n                return False\n        return super(Container, self).is_default()",
    "docstring": "Checks if the field is in its default form\n\n        :return: True if field is in default form"
  },
  {
    "code": "def attrib(self):\n        return dict([\n            ('id', str(self.id)),\n            ('name', str(self.name)),\n            ('tectonicRegion', str(self.trt)),\n        ])",
    "docstring": "General XML element attributes for a seismic source, as a dict."
  },
  {
    "code": "def to_json(self):\n        return {\n            'resourceType': self.resource.resource_type_id,\n            'resourceId': self.id,\n            'accountId': self.resource.account_id,\n            'account': self.account,\n            'location': self.resource.location,\n            'properties': {to_camelcase(prop.name): prop.value for prop in self.resource.properties},\n            'tags': [{'key': t.key, 'value': t.value} for t in self.resource.tags]\n        }",
    "docstring": "Return a `dict` representation of the resource, including all properties and tags\n\n        Returns:\n            `dict`"
  },
  {
    "code": "def find_patches(modules, recursive=True):\n    out = []\n    modules = (module\n               for package in modules\n               for module in _module_iterator(package, recursive=recursive))\n    for module in modules:\n        members = _get_members(module, filter=None)\n        for _, value in members:\n            base = _get_base(value)\n            decorator_data = get_decorator_data(base)\n            if decorator_data is None:\n                continue\n            out.extend(decorator_data.patches)\n    return out",
    "docstring": "Find all the patches created through decorators.\n\n    Parameters\n    ----------\n    modules : list of module\n        Modules and/or packages to search the patches in.\n    recursive : bool\n        ``True`` to search recursively in subpackages.\n\n    Returns\n    -------\n    list of gorilla.Patch\n        Patches found.\n\n    Raises\n    ------\n    TypeError\n        The input is not a valid package or module.\n\n    See Also\n    --------\n    :func:`patch`, :func:`patches`."
  },
  {
    "code": "def _parse_geometry(self, geom):\n        atoms = []\n        for i, line in enumerate(geom.splitlines()):\n           sym, atno, x, y, z = line.split()\n           atoms.append(Atom(sym, [float(x), float(y), float(z)], id=i))\n        return Molecule(atoms)",
    "docstring": "Parse a geometry string and return Molecule object from\n        it."
  },
  {
    "code": "def finish(self):\n        chunks = []\n        while lib.BrotliEncoderIsFinished(self._encoder) == lib.BROTLI_FALSE:\n            chunks.append(self._compress(b'', lib.BROTLI_OPERATION_FINISH))\n        return b''.join(chunks)",
    "docstring": "Finish the compressor. This will emit the remaining output data and\n        transition the compressor to a completed state. The compressor cannot\n        be used again after this point, and must be replaced."
  },
  {
    "code": "def fill_masked(self, value=-1, copy=True):\n        if self.mask is None:\n            raise ValueError('no mask is set')\n        data = np.array(self.values, copy=copy)\n        data[self.mask, ...] = value\n        if copy:\n            out = type(self)(data)\n            out.is_phased = self.is_phased\n        else:\n            out = self\n            out.mask = None\n        return out",
    "docstring": "Fill masked genotype calls with a given value.\n\n        Parameters\n        ----------\n        value : int, optional\n            The fill value.\n        copy : bool, optional\n            If False, modify the array in place.\n\n        Returns\n        -------\n        g : GenotypeArray\n\n        Examples\n        --------\n\n        >>> import allel\n        >>> g = allel.GenotypeArray([[[0, 0], [0, 1]],\n        ...                          [[0, 1], [1, 1]],\n        ...                          [[0, 2], [-1, -1]]], dtype='i1')\n        >>> mask = [[True, False], [False, True], [False, False]]\n        >>> g.mask = mask\n        >>> g.fill_masked().values\n        array([[[-1, -1],\n                [ 0,  1]],\n               [[ 0,  1],\n                [-1, -1]],\n               [[ 0,  2],\n                [-1, -1]]], dtype=int8)"
  },
  {
    "code": "def _generate_autoscaling_metadata(self, cls, args):\n        assert isinstance(args, Mapping)\n        init_config = self._create_instance(\n            cloudformation.InitConfig,\n            args['AWS::CloudFormation::Init']['config'])\n        init = self._create_instance(\n            cloudformation.Init, {'config': init_config})\n        auth = None\n        if 'AWS::CloudFormation::Authentication' in args:\n            auth_blocks = {}\n            for k in args['AWS::CloudFormation::Authentication']:\n                auth_blocks[k] = self._create_instance(\n                    cloudformation.AuthenticationBlock,\n                    args['AWS::CloudFormation::Authentication'][k],\n                    k)\n            auth = self._create_instance(\n                cloudformation.Authentication, auth_blocks)\n        return cls(init, auth)",
    "docstring": "Provides special handling for the autoscaling.Metadata object"
  },
  {
    "code": "def proxy_global(name, no_expand_macro=False, fname='func', args=()):\n    if no_expand_macro:\n        @property\n        def gSomething_no_func(self):\n            glob = self(getattr(ROOT, name))\n            def func():\n                return glob\n            glob.func = func\n            return glob\n        return gSomething_no_func\n    @property\n    def gSomething(self):\n        obj_func = getattr(getattr(ROOT, name), fname)\n        try:\n            obj = obj_func(*args)\n        except ReferenceError:\n            return None\n        return self(obj)\n    return gSomething",
    "docstring": "Used to automatically asrootpy ROOT's thread local variables"
  },
  {
    "code": "def _clamp_value(value, minimum, maximum):\n    if maximum < minimum:\n        raise ValueError\n    if value < minimum:\n        return minimum\n    elif value > maximum:\n        return maximum\n    else:\n        return value",
    "docstring": "Clamp a value to fit between a minimum and a maximum.\n\n    * If ``value`` is between ``minimum`` and ``maximum``, return ``value``\n    * If ``value`` is below ``minimum``, return ``minimum``\n    * If ``value is above ``maximum``, return ``maximum``\n\n    Args:\n        value (float or int): The number to clamp\n        minimum (float or int): The lowest allowed return value\n        maximum (float or int): The highest allowed return value\n\n    Returns:\n        float or int: the clamped value\n\n    Raises:\n        ValueError: if maximum < minimum\n\n    Example:\n        >>> _clamp_value(3, 5, 10)\n        5\n        >>> _clamp_value(11, 5, 10)\n        10\n        >>> _clamp_value(8, 5, 10)\n        8"
  },
  {
    "code": "def findfile(self, old, new):\n    if exists(old):\n      return old\n    elif exists(new):\n      return new\n    else:\n      debug(\"broken patch from Google Code, stripping prefixes..\")\n      if old.startswith(b'a/') and new.startswith(b'b/'):\n        old, new = old[2:], new[2:]\n        debug(\"   %s\" % old)\n        debug(\"   %s\" % new)\n        if exists(old):\n          return old\n        elif exists(new):\n          return new\n      return None",
    "docstring": "return name of file to be patched or None"
  },
  {
    "code": "def write_short_bytes(b):\n    if b is None:\n        return _NULL_SHORT_STRING\n    if not isinstance(b, bytes):\n        raise TypeError('{!r} is not bytes'.format(b))\n    elif len(b) > 32767:\n        raise struct.error(len(b))\n    else:\n        return struct.pack('>h', len(b)) + b",
    "docstring": "Encode a Kafka short string which contains arbitrary bytes. A short string\n    is limited to 32767 bytes in length by the signed 16-bit length prefix.\n    A length prefix of -1 indicates ``null``, represented as ``None`` in\n    Python.\n\n    :param bytes b:\n        No more than 32767 bytes, or ``None`` for the null encoding.\n    :return: length-prefixed `bytes`\n    :raises:\n        `struct.error` for strings longer than 32767 characters"
  },
  {
    "code": "def _hash_comparison(self):\n        def hash_then_or(hash_name):\n            return chain([hash_name], repeat('    or'))\n        lines = []\n        for hash_name, expecteds in iteritems(self.allowed):\n            prefix = hash_then_or(hash_name)\n            lines.extend(('        Expected %s %s' % (next(prefix), e))\n                         for e in expecteds)\n            lines.append('             Got        %s\\n' %\n                         self.gots[hash_name].hexdigest())\n            prefix = '    or'\n        return '\\n'.join(lines)",
    "docstring": "Return a comparison of actual and expected hash values.\n\n        Example::\n\n               Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n                            or 123451234512345123451234512345123451234512345\n                    Got        bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef"
  },
  {
    "code": "def set_person(self, what, rep):\n        if rep is None:\n            if what in self._person:\n                del self._person[what]\n        self._person[what] = rep",
    "docstring": "Set a person substitution.\n\n        Equivalent to ``! person`` in RiveScript code.\n\n        :param str what: The original text to replace.\n        :param str rep: The text to replace it with.\n            Set this to ``None`` to delete the substitution."
  },
  {
    "code": "def sample(self, bqm, **kwargs):\n        tkw = self._truncate_kwargs\n        if self._aggregate:\n            return self.child.sample(bqm, **kwargs).aggregate().truncate(**tkw)\n        else:\n            return self.child.sample(bqm, **kwargs).truncate(**tkw)",
    "docstring": "Sample from the problem provided by bqm and truncate output.\n\n        Args:\n            bqm (:obj:`dimod.BinaryQuadraticModel`):\n                Binary quadratic model to be sampled from.\n\n            **kwargs:\n                Parameters for the sampling method, specified by the child\n                sampler.\n\n        Returns:\n            :obj:`dimod.SampleSet`"
  },
  {
    "code": "def get_match_names(match):\n    names = []\n    if \"paren\" in match:\n        (match,) = match\n        names += get_match_names(match)\n    elif \"var\" in match:\n        (setvar,) = match\n        if setvar != wildcard:\n            names.append(setvar)\n    elif \"trailer\" in match:\n        match, trailers = match[0], match[1:]\n        for i in range(0, len(trailers), 2):\n            op, arg = trailers[i], trailers[i + 1]\n            if op == \"as\":\n                names.append(arg)\n        names += get_match_names(match)\n    return names",
    "docstring": "Gets keyword names for the given match."
  },
  {
    "code": "def length_range(string, minimum, maximum):\n    int_range(len(string), minimum, maximum)\n    return string",
    "docstring": "Requires values' length to be in a certain range.\n\n    :param string: Value to validate\n    :param minimum: Minimum length to accept\n    :param maximum: Maximum length to accept\n    :type string: str\n    :type minimum: int\n    :type maximum: int"
  },
  {
    "code": "def remove(self, event, subscriber):\n        subs = self._subscribers\n        if event not in subs:\n            raise ValueError('No subscribers: %r' % event)\n        subs[event].remove(subscriber)",
    "docstring": "Remove a subscriber for an event.\n\n        :param event: The name of an event.\n        :param subscriber: The subscriber to be removed."
  },
  {
    "code": "def default_aux_file_paths(self, primary_path):\n        return dict((n, primary_path[:-len(self.ext)] + ext)\n                    for n, ext in self.aux_files.items())",
    "docstring": "Get the default paths for auxiliary files relative to the path of the\n        primary file, i.e. the same name as the primary path with a different\n        extension\n\n        Parameters\n        ----------\n        primary_path : str\n            Path to the primary file in the fileset\n\n        Returns\n        -------\n        aux_paths : dict[str, str]\n            A dictionary of auxiliary file names and default paths"
  },
  {
    "code": "def add_store(source, store, saltenv='base'):\n    cert_file = __salt__['cp.cache_file'](source, saltenv)\n    cmd = \"certutil.exe -addstore {0} {1}\".format(store, cert_file)\n    return __salt__['cmd.run'](cmd)",
    "docstring": "Add the given cert into the given Certificate Store\n\n    source\n        The source certificate file this can be in the form\n        salt://path/to/file\n\n    store\n        The certificate store to add the certificate to\n\n    saltenv\n        The salt environment to use this is ignored if the path\n        is local\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' certutil.add_store salt://cert.cer TrustedPublisher"
  },
  {
    "code": "def get_title(self):\n        if self.title:\n            return self.title\n        return self.get_model_class()._meta.verbose_name_plural",
    "docstring": "Get page title"
  },
  {
    "code": "def union(left, right, distinct=False):\n    left, right = _make_different_sources(left, right)\n    return UnionCollectionExpr(_lhs=left, _rhs=right, _distinct=distinct)",
    "docstring": "Union two collections.\n\n    :param left: left collection\n    :param right: right collection\n    :param distinct:\n    :return: collection\n\n    :Example:\n    >>> df['name', 'id'].union(df2['id', 'name'])"
  },
  {
    "code": "def _sendMessage(self, msg):\n        if not msg:\n            return\n        msg = self._collapseMsg(msg)\n        self.sendStatus(msg)",
    "docstring": "Collapse and send msg to the master"
  },
  {
    "code": "def non_decreasing(values):\n    return all(x <= y for x, y in zip(values, values[1:]))",
    "docstring": "True if values are not decreasing."
  },
  {
    "code": "def _get_bios_boot_resource(self, data):\n        try:\n            boot_uri = data['links']['Boot']['href']\n        except KeyError:\n            msg = ('Boot resource not found.')\n            raise exception.IloCommandNotSupportedError(msg)\n        status, headers, boot_settings = self._rest_get(boot_uri)\n        if status != 200:\n            msg = self._get_extended_error(boot_settings)\n            raise exception.IloError(msg)\n        return boot_settings",
    "docstring": "Get the Boot resource like BootSources.\n\n        :param data: Existing Bios settings of the server.\n        :returns: boot settings.\n        :raises: IloCommandNotSupportedError, if resource is not found.\n        :raises: IloError, on an error from iLO."
  },
  {
    "code": "def run_report_from_console(output_file_name, callback):\n    print(\"The report uses a read-only access to the book.\")\n    print(\"Now enter the data or ^Z to continue:\")\n    result = callback()\n    output = save_to_temp(result, output_file_name)\n    webbrowser.open(output)",
    "docstring": "Runs the report from the command line. Receives the book url from the console."
  },
  {
    "code": "def _parse_key(key):\n    splt = key.split(\"\\\\\")\n    hive = splt.pop(0)\n    key = '\\\\'.join(splt)\n    return hive, key",
    "docstring": "split the hive from the key"
  },
  {
    "code": "def bound_elems(elems):\n    group_x0 = min(map(lambda l: l.x0, elems))\n    group_y0 = min(map(lambda l: l.y0, elems))\n    group_x1 = max(map(lambda l: l.x1, elems))\n    group_y1 = max(map(lambda l: l.y1, elems))\n    return (group_x0, group_y0, group_x1, group_y1)",
    "docstring": "Finds the minimal bbox that contains all given elems"
  },
  {
    "code": "def get_or_create_element(self, ns, name):\n        if len(self._node.xpath('%s:%s' % (ns, name), namespaces=SLDNode._nsmap)) == 1:\n            return getattr(self, name)\n        return self.create_element(ns, name)",
    "docstring": "Attempt to get the only child element from this SLDNode. If the node\n        does not exist, create the element, attach it to the DOM, and return\n        the class object that wraps the node.\n\n        @type    ns: string\n        @param   ns: The namespace of the new element.\n        @type  name: string\n        @param name: The name of the new element.\n        @rtype: L{SLDNode}\n        @return: The wrapped node, in the parent's property class. This will\n                 always be a descendent of SLDNode."
  },
  {
    "code": "def method(self, symbol):\n        assert issubclass(symbol, SymbolBase)\n        def wrapped(fn):\n            setattr(symbol, fn.__name__, fn)\n        return wrapped",
    "docstring": "Symbol decorator."
  },
  {
    "code": "def removeHandler(self, event_name):\n        if event_name not in self.handlers:\n            raise ValueError('{} is not a valid event'.format(event_name))\n        self.handlers[event_name] = None",
    "docstring": "Remove handler for given event."
  },
  {
    "code": "def get_gdns_publisher(config, metrics, **kwargs):\n    builder = gdns_publisher.GDNSPublisherBuilder(\n        config, metrics, **kwargs)\n    return builder.build_publisher()",
    "docstring": "Get a GDNSPublisher client.\n\n    A factory function that validates configuration and returns a\n    publisher client (:interface:`gordon.interfaces.IMessageHandler`)\n    provider.\n\n    Args:\n        config (dict): Google Cloud DNS API related configuration.\n        metrics (obj): :interface:`IMetricRelay` implementation.\n        kwargs (dict): Additional keyword arguments to pass to the\n            publisher.\n    Returns:\n        A :class:`GDNSPublisher` instance."
  },
  {
    "code": "def _decode_config(conf_str):\n    conf_str = conf_str.strip()\n    conf = map(\n        lambda x: True if x.upper() == \"T\" else False,\n        list(conf_str)\n    )\n    return dict(zip(settings._ALLOWED_MERGES, conf))",
    "docstring": "Decode string to configuration dict.\n\n    Only values defined in settings._ALLOWED_MERGES can be redefined."
  },
  {
    "code": "def was_installed_by_pip(pkg):\n    try:\n        dist = pkg_resources.get_distribution(pkg)\n        return (dist.has_metadata('INSTALLER') and\n                'pip' in dist.get_metadata_lines('INSTALLER'))\n    except pkg_resources.DistributionNotFound:\n        return False",
    "docstring": "Checks whether pkg was installed by pip\n\n    This is used not to display the upgrade message when pip is in fact\n    installed by system package manager, such as dnf on Fedora."
  },
  {
    "code": "def cd(path):\n    old_dir = os.getcwd()\n    try:\n        os.makedirs(path)\n    except OSError:\n        pass\n    os.chdir(path)\n    try:\n        yield\n    finally:\n        os.chdir(old_dir)",
    "docstring": "Creates the path if it doesn't exist"
  },
  {
    "code": "def _fft_convolve_numpy(data, h, plan = None,\n                        kernel_is_fft = False,\n                        kernel_is_fftshifted = False):\n    if data.shape != h.shape:\n        raise ValueError(\"data and kernel must have same size! %s vs %s \"%(str(data.shape),str(h.shape)))\n    data_g = OCLArray.from_array(data.astype(np.complex64))\n    if not kernel_is_fftshifted:\n        h = np.fft.fftshift(h)\n    h_g = OCLArray.from_array(h.astype(np.complex64))\n    res_g = OCLArray.empty_like(data_g)\n    _fft_convolve_gpu(data_g,h_g,res_g = res_g,\n                      plan = plan,\n                      kernel_is_fft = kernel_is_fft)\n    res =  abs(res_g.get())\n    del data_g\n    del h_g\n    del res_g\n    return res",
    "docstring": "convolving via opencl fft for numpy arrays\n\n    data and h must have the same size"
  },
  {
    "code": "def run(\n    main,\n    argv=None,\n    flags_parser=parse_flags_with_usage,\n):\n  try:\n    args = _run_init(\n        sys.argv if argv is None else argv,\n        flags_parser,\n    )\n    while _init_callbacks:\n      callback = _init_callbacks.popleft()\n      callback()\n    try:\n      _run_main(main, args)\n    except UsageError as error:\n      usage(shorthelp=True, detailed_error=error, exitcode=error.exitcode)\n    except:\n      if FLAGS.pdb_post_mortem:\n        traceback.print_exc()\n        pdb.post_mortem()\n      raise\n  except Exception as e:\n    _call_exception_handlers(e)\n    raise",
    "docstring": "Begins executing the program.\n\n  Args:\n    main: The main function to execute. It takes an single argument \"argv\",\n        which is a list of command line arguments with parsed flags removed.\n        If it returns an integer, it is used as the process's exit code.\n    argv: A non-empty list of the command line arguments including program name,\n        sys.argv is used if None.\n    flags_parser: Callable[[List[Text]], Any], the function used to parse flags.\n        The return value of this function is passed to `main` untouched.\n        It must guarantee FLAGS is parsed after this function is called.\n  - Parses command line flags with the flag module.\n  - If there are any errors, prints usage().\n  - Calls main() with the remaining arguments.\n  - If main() raises a UsageError, prints usage and the error message."
  },
  {
    "code": "def _send_splunk(event, index_override=None, sourcetype_override=None):\n    opts = _get_options()\n    log.info(str('Options: %s'),\n             salt.utils.json.dumps(opts))\n    http_event_collector_key = opts['token']\n    http_event_collector_host = opts['indexer']\n    splunk_event = http_event_collector(http_event_collector_key, http_event_collector_host)\n    payload = {}\n    if index_override is None:\n        payload.update({\"index\": opts['index']})\n    else:\n        payload.update({\"index\": index_override})\n    if sourcetype_override is None:\n        payload.update({\"sourcetype\": opts['sourcetype']})\n    else:\n        payload.update({\"index\": sourcetype_override})\n    payload.update({\"event\": event})\n    log.info(str('Payload: %s'),\n             salt.utils.json.dumps(payload))\n    splunk_event.sendEvent(payload)\n    return True",
    "docstring": "Send the results to Splunk.\n    Requires the Splunk HTTP Event Collector running on port 8088.\n    This is available on Splunk Enterprise version 6.3 or higher."
  },
  {
    "code": "def source_statement(self):\n        if self._has_alias():\n            return 'import %s as %s' % (self.fullName, self.name)\n        else:\n            return 'import %s' % self.fullName",
    "docstring": "Generate a source statement equivalent to the import."
  },
  {
    "code": "def disassemble_capstone(self, target_id=0, address=None, count=None):\n        target = self._target(target_id)\n        if not address:\n            pc_name, address = self.pc()\n        mem = self.memory(address, count * 16, target_id=target_id)\n        md = capstone.Cs(*self.cs_archs[target['arch']])\n        output = []\n        for idx, i in enumerate(md.disasm(mem, address)):\n            if idx >= count:\n                break\n            output.append(\"0x%x:\\t%s\\t%s\" % (i.address, i.mnemonic, i.op_str))\n        return '\\n'.join(output)",
    "docstring": "Disassemble with capstone."
  },
  {
    "code": "def _handle_event(self, sid, namespace, id, data):\n        namespace = namespace or '/'\n        self.logger.info('received event \"%s\" from %s [%s]', data[0], sid,\n                         namespace)\n        if self.async_handlers:\n            self.start_background_task(self._handle_event_internal, self, sid,\n                                       data, namespace, id)\n        else:\n            self._handle_event_internal(self, sid, data, namespace, id)",
    "docstring": "Handle an incoming client event."
  },
  {
    "code": "def cleanup(self):\n        if self.sock is not None:\n            self.sock.close()\n        if self.outfile is not None:\n            self.outfile.close()\n        if self.bar is not None:\n            self.update_progress(complete=True)",
    "docstring": "Release resources used during memory capture"
  },
  {
    "code": "def remove_not_allowed_chars(savepath):\n        split_savepath = os.path.splitdrive(savepath)\n        savepath_without_invalid_chars = re.sub(r'<|>|:|\\\"|\\||\\?|\\*', '_',\n                                                split_savepath[1])\n        return split_savepath[0] + savepath_without_invalid_chars",
    "docstring": "Removes invalid filepath characters from the savepath.\n\n        :param str savepath: the savepath to work on\n        :return str: the savepath without invalid filepath characters"
  },
  {
    "code": "def probe_enable(cls, resource):\n        oper = cls.call('hosting.rproxy.probe.enable', cls.usable_id(resource))\n        cls.echo('Activating probe on %s' % resource)\n        cls.display_progress(oper)\n        cls.echo('The probe have been activated')\n        return oper",
    "docstring": "Activate a probe on a webaccelerator"
  },
  {
    "code": "def fg(color):\n    ansi_code = [getattr(colorama.Fore, color.upper()), colorama.Fore.RESET]\n    return lambda msg: msg.join(ansi_code)",
    "docstring": "Foreground color formatter function factory.\n\n    Each function casts from a unicode string to a colored bytestring\n    with the respective foreground color and foreground reset ANSI\n    escape codes. You can also use the ``fg.color`` or ``fg[color]``\n    directly as attributes/items.\n\n    The colors are the names of the ``colorama.Fore`` attributes\n    (case insensitive). For more information, see:\n\n    https://pypi.python.org/pypi/colorama\n\n    https://en.wikipedia.org/wiki/ANSI_escape_code#Colors"
  },
  {
    "code": "def reqPnL(self, account: str, modelCode: str = '') -> PnL:\n        key = (account, modelCode)\n        assert key not in self.wrapper.pnlKey2ReqId\n        reqId = self.client.getReqId()\n        self.wrapper.pnlKey2ReqId[key] = reqId\n        pnl = PnL(account, modelCode)\n        self.wrapper.pnls[reqId] = pnl\n        self.client.reqPnL(reqId, account, modelCode)\n        return pnl",
    "docstring": "Start a subscription for profit and loss events.\n\n        Returns a :class:`.PnL` object that is kept live updated.\n        The result can also be queried from :meth:`.pnl`.\n\n        https://interactivebrokers.github.io/tws-api/pnl.html\n\n        Args:\n            account: Subscribe to this account.\n            modelCode: If specified, filter for this account model."
  },
  {
    "code": "async def _retrieve_messages_around_strategy(self, retrieve):\n        if self.around:\n            around = self.around.id if self.around else None\n            data = await self.logs_from(self.channel.id, retrieve, around=around)\n            self.around = None\n            return data\n        return []",
    "docstring": "Retrieve messages using around parameter."
  },
  {
    "code": "def pdf(self, mu):\n        return ss.cauchy.pdf(mu, self.loc0, self.scale0)",
    "docstring": "PDF for Cauchy prior\n\n        Parameters\n        ----------\n        mu : float\n            Latent variable for which the prior is being formed over\n\n        Returns\n        ----------\n        - p(mu)"
  },
  {
    "code": "def get_learner_stats(grad_info):\n    if LEARNER_STATS_KEY in grad_info:\n        return grad_info[LEARNER_STATS_KEY]\n    multiagent_stats = {}\n    for k, v in grad_info.items():\n        if type(v) is dict:\n            if LEARNER_STATS_KEY in v:\n                multiagent_stats[k] = v[LEARNER_STATS_KEY]\n    return multiagent_stats",
    "docstring": "Return optimization stats reported from the policy graph.\n\n    Example:\n        >>> grad_info = evaluator.learn_on_batch(samples)\n        >>> print(get_stats(grad_info))\n        {\"vf_loss\": ..., \"policy_loss\": ...}"
  },
  {
    "code": "def _format_value(self, val):\n        name = self.name + \":\"\n        if not self.multiline or \"\\n\" not in val:\n            val = u\"{0} {1}\".format(name.ljust(self._text_prefix_len), val)\n        else:\n            spacer = \"\\n\" + \" \" * (self._text_prefix_len + 1)\n            val = u\"{0}{1}{2}\".format(name, spacer, spacer.join(val.split(\"\\n\")))\n        return val",
    "docstring": "formats a value to be good for textmode printing\n        val must be unicode"
  },
  {
    "code": "def make_graph(node, inputs):\n        initializer = []\n        tensor_input_info = []\n        tensor_output_info = []\n        for index in range(len(node.input)):\n            tensor_input_info.append(\n                helper.make_tensor_value_info(str(node.input[index]), TensorProto.FLOAT, [1]))\n            if node.input[index] == 'W':\n                dim = inputs[index].shape\n                param_tensor = helper.make_tensor(\n                    name=node.input[index],\n                    data_type=TensorProto.FLOAT,\n                    dims=dim,\n                    vals=inputs[index].flatten())\n                initializer.append(param_tensor)\n        for index in range(len(node.output)):\n            tensor_output_info.append(\n                helper.make_tensor_value_info(str(node.output[index]), TensorProto.FLOAT, [1]))\n        graph_proto = helper.make_graph(\n            [node],\n            \"test\",\n            tensor_input_info,\n            tensor_output_info,\n            initializer=initializer)\n        return graph_proto",
    "docstring": "Created ONNX GraphProto from node"
  },
  {
    "code": "def _simulate_coef_from_bootstraps(\n            self, n_draws, coef_bootstraps, cov_bootstraps):\n        random_bootstrap_indices = np.random.choice(\n            np.arange(len(coef_bootstraps)), size=n_draws, replace=True)\n        bootstrap_index_to_draw_indices = defaultdict(list)\n        for draw_index, bootstrap_index in enumerate(random_bootstrap_indices):\n            bootstrap_index_to_draw_indices[bootstrap_index].append(draw_index)\n        coef_draws = np.empty((n_draws, len(self.coef_)))\n        for bootstrap, draw_indices in bootstrap_index_to_draw_indices.items():\n            coef_draws[draw_indices] = np.random.multivariate_normal(\n                coef_bootstraps[bootstrap], cov_bootstraps[bootstrap],\n                size=len(draw_indices))\n        return coef_draws",
    "docstring": "Simulate coefficients using bootstrap samples."
  },
  {
    "code": "def data_from_stream(self, stream):\n        parser = self._make_representation_parser(stream, self.resource_class,\n                                                  self._mapping)\n        return parser.run()",
    "docstring": "Creates a data element reading a representation from the given stream.\n\n        :returns: object implementing\n            :class:`everest.representers.interfaces.IExplicitDataElement`"
  },
  {
    "code": "def find_side(ls, side):\n    minx, miny, maxx, maxy = ls.bounds\n    points = {'left': [(minx, miny), (minx, maxy)],\n              'right': [(maxx, miny), (maxx, maxy)],\n              'bottom': [(minx, miny), (maxx, miny)],\n              'top': [(minx, maxy), (maxx, maxy)],}\n    return sgeom.LineString(points[side])",
    "docstring": "Given a shapely LineString which is assumed to be rectangular, return the\n    line corresponding to a given side of the rectangle."
  },
  {
    "code": "def _find_impl(cls, role, interface):\n        module = _relation_module(role, interface)\n        if not module:\n            return None\n        return cls._find_subclass(module)",
    "docstring": "Find relation implementation based on its role and interface."
  },
  {
    "code": "def is_eighth_sponsor(self):\n        from ..eighth.models import EighthSponsor\n        return EighthSponsor.objects.filter(user=self).exists()",
    "docstring": "Determine whether the given user is associated with an.\n\n        :class:`intranet.apps.eighth.models.EighthSponsor` and, therefore, should view activity\n        sponsoring information."
  },
  {
    "code": "def _precheck(self, curtailment_timeseries, feedin_df, curtailment_key):\n        if not feedin_df.empty:\n            feedin_selected_sum = feedin_df.sum(axis=1)\n            diff = feedin_selected_sum - curtailment_timeseries\n            diff[diff.between(-1, 0)] = 0\n            if not (diff >= 0).all():\n                bad_time_steps = [_ for _ in diff.index\n                                  if diff[_] < 0]\n                message = 'Curtailment demand exceeds total feed-in in time ' \\\n                          'steps {}.'.format(bad_time_steps)\n                logging.error(message)\n                raise ValueError(message)\n        else:\n            bad_time_steps = [_ for _ in curtailment_timeseries.index\n                              if curtailment_timeseries[_] > 0]\n            if bad_time_steps:\n                message = 'Curtailment given for time steps {} but there ' \\\n                          'are no generators to meet the curtailment target ' \\\n                          'for {}.'.format(bad_time_steps, curtailment_key)\n                logging.error(message)\n                raise ValueError(message)",
    "docstring": "Raises an error if the curtailment at any time step exceeds the\n        total feed-in of all generators curtailment can be distributed among\n        at that time.\n\n        Parameters\n        -----------\n        curtailment_timeseries : :pandas:`pandas.Series<series>`\n            Curtailment time series in kW for the technology (and weather\n            cell) specified in `curtailment_key`.\n        feedin_df : :pandas:`pandas.Series<series>`\n            Feed-in time series in kW for all generators of type (and in\n            weather cell) specified in `curtailment_key`.\n        curtailment_key : :obj:`str` or :obj:`tuple` with :obj:`str`\n            Technology (and weather cell) curtailment is given for."
  },
  {
    "code": "def round_sig(x, sig):\n    return round(x, sig - int(floor(log10(abs(x)))) - 1)",
    "docstring": "Round the number to the specified number of significant figures"
  },
  {
    "code": "def create_link(id_link, post_data):\n        if MLink.get_by_uid(id_link):\n            return False\n        try:\n            the_order = int(post_data['order'])\n        except:\n            the_order = 999\n        TabLink.create(name=post_data['name'],\n                       link=post_data['link'],\n                       order=the_order,\n                       logo=post_data['logo'] if 'logo' in post_data else '',\n                       uid=id_link)\n        return id_link",
    "docstring": "Add record in link."
  },
  {
    "code": "def y_select_cb(self, w, index):\n        try:\n            self.y_col = self.cols[index]\n        except IndexError as e:\n            self.logger.error(str(e))\n        else:\n            self.plot_two_columns(reset_ylimits=True)",
    "docstring": "Callback to set Y-axis column."
  },
  {
    "code": "def read(self, filehandle):\n        return self.__import(json.load(filehandle, **self.kwargs))",
    "docstring": "Read JSON from `filehandle`."
  },
  {
    "code": "def group_id(self, value):\n        if isinstance(value, GroupId):\n            self._group_id = value\n        else:\n            self._group_id = GroupId(value)",
    "docstring": "The unsubscribe group to associate with this email.\n\n        :param value: ID of an unsubscribe group\n        :type value: GroupId, int, required"
  },
  {
    "code": "def to_array(self):\n        array = super(Audio, self).to_array()\n        array['file_id'] = u(self.file_id)\n        array['duration'] = int(self.duration)\n        if self.performer is not None:\n            array['performer'] = u(self.performer)\n        if self.title is not None:\n            array['title'] = u(self.title)\n        if self.mime_type is not None:\n            array['mime_type'] = u(self.mime_type)\n        if self.file_size is not None:\n            array['file_size'] = int(self.file_size)\n        if self.thumb is not None:\n            array['thumb'] = self.thumb.to_array()\n        return array",
    "docstring": "Serializes this Audio to a dictionary.\n\n        :return: dictionary representation of this object.\n        :rtype: dict"
  },
  {
    "code": "def _create_minimum_needs_action(self):\n        icon = resources_path('img', 'icons', 'show-minimum-needs.svg')\n        self.action_minimum_needs = QAction(\n            QIcon(icon),\n            self.tr('Minimum Needs Calculator'), self.iface.mainWindow())\n        self.action_minimum_needs.setStatusTip(self.tr(\n            'Open InaSAFE minimum needs calculator'))\n        self.action_minimum_needs.setWhatsThis(self.tr(\n            'Open InaSAFE minimum needs calculator'))\n        self.action_minimum_needs.triggered.connect(self.show_minimum_needs)\n        self.add_action(\n            self.action_minimum_needs, add_to_toolbar=self.full_toolbar)",
    "docstring": "Create action for minimum needs dialog."
  },
  {
    "code": "def visualize(tree, max_level=100, node_width=10, left_padding=5):\n    height = min(max_level, tree.height()-1)\n    max_width = pow(2, height)\n    per_level = 1\n    in_level  = 0\n    level     = 0\n    for node in level_order(tree, include_all=True):\n        if in_level == 0:\n            print()\n            print()\n            print(' '*left_padding, end=' ')\n        width = int(max_width*node_width/per_level)\n        node_str = (str(node.data) if node else '').center(width)\n        print(node_str, end=' ')\n        in_level += 1\n        if in_level == per_level:\n            in_level   = 0\n            per_level *= 2\n            level     += 1\n        if level > height:\n            break\n    print()\n    print()",
    "docstring": "Prints the tree to stdout"
  },
  {
    "code": "def get_by(cls, field, value):\n        redis = cls.get_redis()\n        key = cls.cls_key()+':index_'+field\n        id = redis.hget(key, value)\n        if id:\n            return cls.get(debyte_string(id))\n        return None",
    "docstring": "Tries to retrieve an isinstance of this model from the database\n        given a value for a defined index. Return None in case of failure"
  },
  {
    "code": "def from_file(filename=None, io='auto', prefix_dir=None,\n                  omit_facets=False):\n        if isinstance(filename, Mesh):\n            return filename\n        if io == 'auto':\n            if filename is None:\n                output( 'filename or io must be specified!' )\n                raise ValueError\n            else:\n                io = MeshIO.any_from_filename(filename, prefix_dir=prefix_dir)\n        output('reading mesh (%s)...' % (io.filename))\n        tt = time.clock()\n        trunk = io.get_filename_trunk()\n        mesh = Mesh(trunk)\n        mesh = io.read(mesh, omit_facets=omit_facets)\n        output('...done in %.2f s' % (time.clock() - tt))\n        mesh._set_shape_info()\n        return mesh",
    "docstring": "Read a mesh from a file.\n\n        Parameters\n        ----------\n        filename : string or function or MeshIO instance or Mesh instance\n            The name of file to read the mesh from. For convenience, a\n            mesh creation function or a MeshIO instance or directly a Mesh\n            instance can be passed in place of the file name.\n        io : *MeshIO instance\n            Passing *MeshIO instance has precedence over filename.\n        prefix_dir : str\n            If not None, the filename is relative to that directory.\n        omit_facets : bool\n            If True, do not read cells of lower dimension than the space\n            dimension (faces and/or edges). Only some MeshIO subclasses\n            support this!"
  },
  {
    "code": "def gsignal(name, *args, **kwargs):\n    frame = sys._getframe(1)\n    try:\n        locals = frame.f_locals\n    finally:\n        del frame\n    dict = locals.setdefault('__gsignals__', {})\n    if args and args[0] == 'override':\n        dict[name] = 'override'\n    else:\n        retval = kwargs.get('retval', None)\n        if retval is None:\n            default_flags = gobject.SIGNAL_RUN_FIRST\n        else:\n            default_flags = gobject.SIGNAL_RUN_LAST\n        flags = kwargs.get('flags', default_flags)\n        if retval is not None and flags != gobject.SIGNAL_RUN_LAST:\n            raise TypeError(\n                \"You cannot use a return value without setting flags to \"\n                \"gobject.SIGNAL_RUN_LAST\")\n        dict[name] = (flags, retval, args)",
    "docstring": "Add a GObject signal to the current object.\n\n    It current supports the following types:\n        - str, int, float, long, object, enum\n\n    :param name: name of the signal\n    :param args: types for signal parameters,\n        if the first one is a string 'override', the signal will be\n        overridden and must therefor exists in the parent GObject.\n\n    .. note:: flags: A combination of;\n\n      - gobject.SIGNAL_RUN_FIRST\n      - gobject.SIGNAL_RUN_LAST\n      - gobject.SIGNAL_RUN_CLEANUP\n      - gobject.SIGNAL_NO_RECURSE\n      - gobject.SIGNAL_DETAILED\n      - gobject.SIGNAL_ACTION\n      - gobject.SIGNAL_NO_HOOKS"
  },
  {
    "code": "def fetch_timeline_history_files(self, max_timeline):\n        while max_timeline > 1:\n            self.c.execute(\"TIMELINE_HISTORY {}\".format(max_timeline))\n            timeline_history = self.c.fetchone()\n            history_filename = timeline_history[0]\n            history_data = timeline_history[1].tobytes()\n            self.log.debug(\"Received timeline history: %s for timeline %r\",\n                           history_filename, max_timeline)\n            compression_event = {\n                \"type\": \"CLOSE_WRITE\",\n                \"compress_to_memory\": True,\n                \"delete_file_after_compression\": False,\n                \"input_data\": BytesIO(history_data),\n                \"full_path\": history_filename,\n                \"site\": self.site,\n            }\n            self.compression_queue.put(compression_event)\n            max_timeline -= 1",
    "docstring": "Copy all timeline history files found on the server without\n           checking if we have them or not. The history files are very small\n           so reuploading them should not matter."
  },
  {
    "code": "def _sort_by_unique_fields(model, model_objs, unique_fields):\n    unique_fields = [\n        field for field in model._meta.fields\n        if field.attname in unique_fields\n    ]\n    def sort_key(model_obj):\n        return tuple(\n            field.get_db_prep_save(getattr(model_obj, field.attname),\n                                   connection)\n            for field in unique_fields\n        )\n    return sorted(model_objs, key=sort_key)",
    "docstring": "Sort a list of models by their unique fields.\n\n    Sorting models in an upsert greatly reduces the chances of deadlock\n    when doing concurrent upserts"
  },
  {
    "code": "def refresh_products(self, **kwargs):\n        for product in self.product_get(**kwargs):\n            updated = False\n            for current in self._cache.products[:]:\n                if (current.get(\"id\", -1) != product.get(\"id\", -2) and\n                    current.get(\"name\", -1) != product.get(\"name\", -2)):\n                    continue\n                _nested_update(current, product)\n                updated = True\n                break\n            if not updated:\n                self._cache.products.append(product)",
    "docstring": "Refresh a product's cached info. Basically calls product_get\n        with the passed arguments, and tries to intelligently update\n        our product cache.\n\n        For example, if we already have cached info for product=foo,\n        and you pass in names=[\"bar\", \"baz\"], the new cache will have\n        info for products foo, bar, baz. Individual product fields are\n        also updated."
  },
  {
    "code": "def exp(x, context=None):\n    return _apply_function_in_current_context(\n        BigFloat,\n        mpfr.mpfr_exp,\n        (BigFloat._implicit_convert(x),),\n        context,\n    )",
    "docstring": "Return the exponential of x."
  },
  {
    "code": "def needs_reboot():\n    with salt.utils.winapi.Com():\n        obj_sys = win32com.client.Dispatch('Microsoft.Update.SystemInfo')\n    return salt.utils.data.is_true(obj_sys.RebootRequired)",
    "docstring": "Determines if the system needs to be rebooted.\n\n    Returns:\n\n        bool: True if the system requires a reboot, False if not\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        import salt.utils.win_update\n\n        salt.utils.win_update.needs_reboot()"
  },
  {
    "code": "def delete(cont, path=None, profile=None):\n    swift_conn = _auth(profile)\n    if path is None:\n        return swift_conn.delete_container(cont)\n    else:\n        return swift_conn.delete_object(cont, path)",
    "docstring": "Delete a container, or delete an object from a container.\n\n    CLI Example to delete a container::\n\n        salt myminion swift.delete mycontainer\n\n    CLI Example to delete an object from a container::\n\n        salt myminion swift.delete mycontainer remoteobject"
  },
  {
    "code": "def migrate(*argv) -> bool:\n    wf('Applying migrations... ', False)\n    execute_from_command_line(['./manage.py', 'migrate'] + list(argv))\n    wf('[+]\\n')\n    return True",
    "docstring": "Runs Django migrate command.\n\n    :return: always ``True``"
  },
  {
    "code": "def load(self, optional_cfg_files=None):\n        optional_cfg_files = optional_cfg_files or []\n        if self._loaded:\n            raise RuntimeError(\"INTERNAL ERROR: Attempt to load configuration twice!\")\n        try:\n            namespace = {}\n            self._set_defaults(namespace, optional_cfg_files)\n            self._load_ini(namespace, os.path.join(self.config_dir, self.CONFIG_INI))\n            for cfg_file in optional_cfg_files:\n                if not os.path.isabs(cfg_file):\n                    cfg_file = os.path.join(self.config_dir, cfg_file)\n                if os.path.exists(cfg_file):\n                    self._load_ini(namespace, cfg_file)\n            self._validate_namespace(namespace)\n            self._load_py(namespace, namespace[\"config_script\"])\n            self._validate_namespace(namespace)\n            for callback in namespace[\"config_validator_callbacks\"]:\n                callback()\n        except ConfigParser.ParsingError as exc:\n            raise error.UserError(exc)\n        self._loaded = True",
    "docstring": "Actually load the configuation from either the default location or the given directory."
  },
  {
    "code": "def clause_annotations(self):\n        if not self.is_tagged(CLAUSE_ANNOTATION):\n            self.tag_clause_annotations()\n        return [word.get(CLAUSE_ANNOTATION, None) for word in self[WORDS]]",
    "docstring": "The list of clause annotations in ``words`` layer."
  },
  {
    "code": "def bridge_to_vlan(br):\n    cmd = 'ovs-vsctl br-to-vlan {0}'.format(br)\n    result = __salt__['cmd.run_all'](cmd)\n    if result['retcode'] != 0:\n        return False\n    return int(result['stdout'])",
    "docstring": "Returns the VLAN ID of a bridge.\n\n    Args:\n        br: A string - bridge name\n\n    Returns:\n        VLAN ID of the bridge. The VLAN ID is 0 if the bridge is not a fake\n        bridge.  If the bridge does not exist, False is returned.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' openvswitch.bridge_to_parent br0"
  },
  {
    "code": "def check_links_status(self,\n                           fail_running=False,\n                           fail_pending=False):\n        status_vector = JobStatusVector()\n        for link in self._links.values():\n            key = JobDetails.make_fullkey(link.full_linkname)\n            link_status = link.check_job_status(key,\n                                                fail_running=fail_running,\n                                                fail_pending=fail_pending)\n            status_vector[link_status] += 1\n        return status_vector.get_status()",
    "docstring": "Check the status of all the jobs run from the\n        `Link` objects in this `Chain` and return a status\n        flag that summarizes that.\n\n        Parameters\n        ----------\n\n        fail_running : `bool`\n            If True, consider running jobs as failed\n\n        fail_pending : `bool`\n            If True, consider pending jobs as failed\n\n        Returns\n        -------\n        status : `JobStatus`\n            Job status flag that summarizes the status of all the jobs,"
  },
  {
    "code": "def set_thumbnail_size(self, width, height):\n        cairo.cairo_pdf_surface_set_thumbnail_size(\n            self._pointer, width, height)",
    "docstring": "Set thumbnail image size for the current and all subsequent pages.\n\n        Setting a width or height of 0 disables thumbnails for the current and\n        subsequent pages.\n\n        :param width: thumbnail width.\n        :param height: thumbnail height.\n\n        *New in cairo 1.16.*\n\n        *New in cairocffi 0.9.*"
  },
  {
    "code": "def resync_package(ctx, opts, owner, repo, slug, skip_errors):\n    click.echo(\n        \"Resynchonising the %(slug)s package ... \"\n        % {\"slug\": click.style(slug, bold=True)},\n        nl=False,\n    )\n    context_msg = \"Failed to resynchronise package!\"\n    with handle_api_exceptions(\n        ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors\n    ):\n        with maybe_spinner(opts):\n            api_resync_package(owner=owner, repo=repo, identifier=slug)\n    click.secho(\"OK\", fg=\"green\")",
    "docstring": "Resynchronise a package."
  },
  {
    "code": "def origin(self):\n        libfn = utils.get_lib_fn('getOrigin%s'%self._libsuffix)\n        return libfn(self.pointer)",
    "docstring": "Get image origin\n\n        Returns\n        -------\n        tuple"
  },
  {
    "code": "def set_version(old_version, new_version):\n        try:\n            if APISettings.DEBUG:\n                Shell.debug('* ' + old_version + ' --> ' + new_version)\n                return True\n            for line in fileinput.input(os.path.abspath(APISettings.VERSION_FILE), inplace=True):\n                print(line.replace(old_version, new_version), end='')\n            Shell.success('* ' + old_version + ' --> ' + new_version)\n        except FileNotFoundError:\n            Shell.warn('File not found!')",
    "docstring": "Write new version into VERSION_FILE"
  },
  {
    "code": "def wrap_lons(lons, base, period):\n    lons = lons.astype(np.float64)\n    return ((lons - base + period * 2) % period) + base",
    "docstring": "Wrap longitude values into the range between base and base+period."
  },
  {
    "code": "def _help():\n\tfor task in sorted(TASKS, key=lambda x: (x.ns or '000') + x.name):\n\t\ttags = ''\n\t\tif task is DEFAULT:\n\t\t\ttags += '*'\n\t\tif task is SETUP:\n\t\t\ttags += '+'\n\t\tif task is TEARDOWN:\n\t\t\ttags += '-'\n\t\tprint LOCALE['help_command'].format(task, tags, task.help)\n\t\tif task.aliases:\n\t\t\tprint LOCALE['help_aliases'].format(task.aliasstr())\n\t\tif task.reqs:\n\t\t\tprint LOCALE['help_reqs'].format(task.reqstr())\n\t\tif task.gens:\n\t\t\tprint LOCALE['help_gens'].format(task.gens)\n\t\tif task.args or task.defaults:\n\t\t\tprint LOCALE['help_args'].format(task.ns + task.name, task.kwargstr(), task.argstr())",
    "docstring": "Print all available tasks and descriptions."
  },
  {
    "code": "def inline(self) -> str:\n        return \"{0}:{1}\".format(self.index, ' '.join([str(p) for p in self.parameters]))",
    "docstring": "Return inline string format of the instance\n\n        :return:"
  },
  {
    "code": "def set_fft_params(func):\n    @wraps(func)\n    def wrapped_func(series, method_func, *args, **kwargs):\n        if isinstance(series, tuple):\n            data = series[0]\n        else:\n            data = series\n        normalize_fft_params(data, kwargs=kwargs, func=method_func)\n        return func(series, method_func, *args, **kwargs)\n    return wrapped_func",
    "docstring": "Decorate a method to automatically convert quantities to samples"
  },
  {
    "code": "def get_field_context(self, bound_field):\n        widget = bound_field.field.widget\n        widget_class_name = widget.__class__.__name__.lower()\n        field_id = widget.attrs.get('id') or bound_field.auto_id\n        if field_id:\n            field_id = widget.id_for_label(field_id)\n        return {\n            'form': self,\n            'field': bound_field,\n            'field_id': field_id,\n            'field_name': bound_field.name,\n            'errors': bound_field.errors,\n            'required': bound_field.field.required,\n            'label': bound_field.label,\n            'label_css_class': self.get_field_label_css_class(bound_field),\n            'help_text': mark_safe(bound_field.help_text) if bound_field.help_text else None,\n            'container_css_class': self.get_field_container_css_class(bound_field),\n            'widget_class_name': widget_class_name,\n            'widget_input_type': getattr(widget, 'input_type', None) or widget_class_name\n        }",
    "docstring": "Returns the context which is used when rendering a form field to HTML.\n\n        The generated template context will contain the following variables:\n\n        * form: `Form` instance\n        * field: `BoundField` instance of the field\n        * field_id: Field ID to use in `<label for=\"..\">`\n        * field_name: Name of the form field to render\n        * errors: `ErrorList` instance with errors of the field\n        * required: Boolean flag to signal if the field is required or not\n        * label: The label text of the field\n        * label_css_class: The optional label CSS class, might be `None`\n        * help_text: Optional help text for the form field. Might be `None`\n        * container_css_class: The CSS class for the field container.\n        * widget_class_name: Lowercased version of the widget class name (e.g. 'textinput')\n        * widget_input_type: `input_type` property of the widget instance,\n          falls back to `widget_class_name` if not available.\n\n        :return: Template context for field rendering."
  },
  {
    "code": "def wait_for_a_future(futures, print_traceback=False):\n    while True:\n        try:\n            future = next(concurrent.futures.as_completed(futures, timeout=THREAD_TIMEOUT_MAX))\n            break\n        except concurrent.futures.TimeoutError:\n            pass\n        except KeyboardInterrupt:\n            if print_traceback:\n                traceback.print_stack()\n            else:\n                print('')\n            os._exit(os.EX_IOERR)\n    return future",
    "docstring": "Return the next future that completes.  If a KeyboardInterrupt is\n    received, then the entire process is exited immediately.  See\n    wait_for_all_futures for more notes."
  },
  {
    "code": "def submit_reading(basename, pmid_list_filename, readers, start_ix=None,\n                   end_ix=None, pmids_per_job=3000, num_tries=2,\n                   force_read=False, force_fulltext=False, project_name=None):\n    sub = PmidSubmitter(basename, readers, project_name)\n    sub.set_options(force_read, force_fulltext)\n    sub.submit_reading(pmid_list_filename, start_ix, end_ix, pmids_per_job,\n                       num_tries)\n    return sub.job_list",
    "docstring": "Submit an old-style pmid-centered no-database s3 only reading job.\n\n    This function is provided for the sake of backward compatibility. It is\n    preferred that you use the object-oriented PmidSubmitter and the\n    submit_reading job going forward."
  },
  {
    "code": "def reset(self):\n        with self._cond:\n            if self._count > 0:\n                if self._state == 0:\n                    self._state = -1\n                elif self._state == -2:\n                    self._state = -1\n            else:\n                self._state = 0\n            self._cond.notify_all()",
    "docstring": "Reset the barrier to the initial state.\n\n        Any threads currently waiting will get the BrokenBarrier exception\n        raised."
  },
  {
    "code": "def get_media_urls(tweet):\n    media = get_media_entities(tweet)\n    urls = [m.get(\"media_url_https\") for m in media] if media else []\n    return urls",
    "docstring": "Gets the https links to each media entity in the tweet.\n\n    Args:\n        tweet (Tweet or dict): tweet\n\n    Returns:\n        list: list of urls. Will be an empty list if there are no urls present.\n\n    Example:\n        >>> from tweet_parser.getter_methods.tweet_entities import get_media_urls\n        >>> tweet = {'created_at': '2017-21-23T15:21:21.000Z',\n        ...          'entities': {'user_mentions': [{'id': 2382763597,\n        ...          'id_str': '2382763597',\n        ...          'indices': [14, 26],\n        ...          'name': 'Fiona',\n        ...          'screen_name': 'notFromShrek'}]},\n        ...          'extended_entities': {'media': [{'display_url': 'pic.twitter.com/something',\n        ...          'expanded_url': 'https://twitter.com/something',\n        ...          'id': 4242,\n        ...          'id_str': '4242',\n        ...          'indices': [88, 111],\n        ...          'media_url': 'http://pbs.twimg.com/media/something.jpg',\n        ...          'media_url_https': 'https://pbs.twimg.com/media/something.jpg',\n        ...          'sizes': {'large': {'h': 1065, 'resize': 'fit', 'w': 1600},\n        ...          'medium': {'h': 799, 'resize': 'fit', 'w': 1200},\n        ...          'small': {'h': 453, 'resize': 'fit', 'w': 680},\n        ...          'thumb': {'h': 150, 'resize': 'crop', 'w': 150}},\n        ...          'type': 'photo',\n        ...          'url': 'https://t.co/something'},\n        ...          {'display_url': 'pic.twitter.com/something_else',\n        ...          'expanded_url': 'https://twitter.com/user/status/something/photo/1',\n        ...          'id': 4243,\n        ...          'id_str': '4243',\n        ...          'indices': [88, 111],\n        ...          'media_url': 'http://pbs.twimg.com/media/something_else.jpg',\n        ...          'media_url_https': 'https://pbs.twimg.com/media/something_else.jpg',\n        ...          'sizes': {'large': {'h': 1065, 'resize': 'fit', 'w': 1600},\n        ...          'medium': {'h': 799, 'resize': 'fit', 'w': 1200},\n        ...          'small': {'h': 453, 'resize': 'fit', 'w': 680},\n        ...          'thumb': {'h': 150, 'resize': 'crop', 'w': 150}},\n        ...          'type': 'photo',\n        ...          'url': 'https://t.co/something_else'}]}\n        ...         }\n        >>> get_media_urls(tweet)\n        ['https://pbs.twimg.com/media/something.jpg', 'https://pbs.twimg.com/media/something_else.jpg']"
  },
  {
    "code": "def row_to_dict(row):\n    o = {}\n    for colname in row.colnames:\n        if isinstance(row[colname], np.string_) and row[colname].dtype.kind in ['S', 'U']:\n            o[colname] = str(row[colname])\n        else:\n            o[colname] = row[colname]\n    return o",
    "docstring": "Convert a table row to a dictionary."
  },
  {
    "code": "def get_compression_extension(self):\n        build_request = BuildRequest(build_json_store=self.os_conf.get_build_json_store())\n        inner = build_request.inner_template\n        postbuild_plugins = inner.get('postbuild_plugins', [])\n        for plugin in postbuild_plugins:\n            if plugin.get('name') == 'compress':\n                args = plugin.get('args', {})\n                method = args.get('method', 'gzip')\n                if method == 'gzip':\n                    return '.gz'\n                elif method == 'lzma':\n                    return '.xz'\n                raise OsbsValidationException(\"unknown compression method '%s'\"\n                                              % method)\n        return None",
    "docstring": "Find the filename extension for the 'docker save' output, which\n        may or may not be compressed.\n\n        Raises OsbsValidationException if the extension cannot be\n        determined due to a configuration error.\n\n        :returns: str including leading dot, or else None if no compression"
  },
  {
    "code": "def add_argument_to(self, parser):\n        from devassistant.cli.devassistant_argparse import DefaultIffUsedActionFactory\n        if isinstance(self.kwargs.get('action', ''), list):\n            if self.kwargs['action'][0] == 'default_iff_used':\n                self.kwargs['action'] = DefaultIffUsedActionFactory.generate_action(\n                    self.kwargs['action'][1])\n        self.kwargs.pop('preserved', None)\n        try:\n            parser.add_argument(*self.flags, **self.kwargs)\n        except Exception as ex:\n            problem = \"Error while adding argument '{name}': {error}\".\\\n                format(name=self.name, error=repr(ex))\n            raise exceptions.ExecutionException(problem)",
    "docstring": "Used by cli to add this as an argument to argparse parser.\n\n        Args:\n            parser: parser to add this argument to"
  },
  {
    "code": "def prepare_ec(oo, sizes, M):\n    tour = range(len(oo))\n    tour_sizes = np.array([sizes.sizes[x] for x in oo])\n    tour_M = M[oo, :][:, oo]\n    return tour, tour_sizes, tour_M",
    "docstring": "This prepares EC and converts from contig_id to an index."
  },
  {
    "code": "def operator_si(u):\n    global _aux\n    if np.ndim(u) == 2:\n        P = _P2\n    elif np.ndim(u) == 3:\n        P = _P3\n    else:\n        raise ValueError(\"u has an invalid number of dimensions \"\n                         \"(should be 2 or 3)\")\n    if u.shape != _aux.shape[1:]:\n        _aux = np.zeros((len(P),) + u.shape)\n    for _aux_i, P_i in zip(_aux, P):\n        _aux_i[:] = binary_erosion(u, P_i)\n    return _aux.max(0)",
    "docstring": "operator_si operator."
  },
  {
    "code": "def do_size(self, w, h):\n        if (w is None):\n            self.sw = self.rw\n            self.sh = self.rh\n        else:\n            self.sw = w\n            self.sh = h\n        image = Image.new(\"RGB\", (self.sw, self.sh), self.gen.background_color)\n        for y in range(0, self.sh):\n            for x in range(0, self.sw):\n                ix = int((x * self.rw) // self.sw + self.rx)\n                iy = int((y * self.rh) // self.sh + self.ry)\n                color = self.gen.pixel(ix, iy)\n                if (color is not None):\n                    image.putpixel((x, y), color)\n        self.image = image",
    "docstring": "Record size."
  },
  {
    "code": "def copyNamespace(self):\n        ret = libxml2mod.xmlCopyNamespace(self._o)\n        if ret is None:raise treeError('xmlCopyNamespace() failed')\n        __tmp = xmlNs(_obj=ret)\n        return __tmp",
    "docstring": "Do a copy of the namespace."
  },
  {
    "code": "def get_activity_ids_by_objective_banks(self, objective_bank_ids):\n        id_list = []\n        for activity in self.get_activities_by_objective_banks(objective_bank_ids):\n            id_list.append(activity.get_id())\n        return IdList(id_list)",
    "docstring": "Gets the list of ``Activity Ids`` corresponding to a list of ``ObjectiveBanks``.\n\n        arg:    objective_bank_ids (osid.id.IdList): list of objective\n                bank ``Ids``\n        return: (osid.id.IdList) - list of activity ``Ids``\n        raise:  NullArgument - ``objective_bank_ids`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def dprintx(passeditem, special=False):\n    if DEBUGALL:\n        if special:\n            from pprint import pprint\n            pprint(passeditem)\n        else:\n            print(\"%s%s%s\" % (C_TI, passeditem, C_NORM))",
    "docstring": "Print Text if DEBUGALL set, optionally with PrettyPrint.\n\n    Args:\n        passeditem (str): item to print\n        special (bool): determines if item prints with PrettyPrint\n                        or regular print."
  },
  {
    "code": "def get_fake(locale=None):\n        if locale is None:\n            locale = Faker.default_locale\n        if not hasattr(Maker, '_fake_' + locale):\n            Faker._fake = faker.Factory.create(locale)\n        return Faker._fake",
    "docstring": "Return a shared faker factory used to generate fake data"
  },
  {
    "code": "def _kill_managed_threads(self):\n        num_threads = len(self._managed_threads)\n        if num_threads:\n            _log.warning('killing %s managed thread(s)', num_threads)\n            for gt, identifier in list(self._managed_threads.items()):\n                _log.warning('killing managed thread `%s`', identifier)\n                gt.kill()",
    "docstring": "Kill any currently executing managed threads.\n\n        See :meth:`ServiceContainer.spawn_managed_thread`"
  },
  {
    "code": "def run_dynamic_structure_factor(self,\n                                     Qpoints,\n                                     T,\n                                     atomic_form_factor_func=None,\n                                     scattering_lengths=None,\n                                     freq_min=None,\n                                     freq_max=None):\n        self.init_dynamic_structure_factor(\n            Qpoints,\n            T,\n            atomic_form_factor_func=atomic_form_factor_func,\n            scattering_lengths=scattering_lengths,\n            freq_min=freq_min,\n            freq_max=freq_max)\n        self._dynamic_structure_factor.run()",
    "docstring": "Run dynamic structure factor calculation\n\n        See the detail of parameters at\n        Phonopy.init_dynamic_structure_factor()."
  },
  {
    "code": "def sam_list(sam):\n\tlist = []\n\tfor file in sam:\n\t\tfor line in file:\n\t\t\tif line.startswith('@') is False:\n\t\t\t\tline = line.strip().split()\n\t\t\t\tid, map = line[0], int(line[1])\n\t\t\t\tif map != 4 and map != 8:\n\t\t\t\t\tlist.append(id)\n\treturn set(list)",
    "docstring": "get a list of mapped reads"
  },
  {
    "code": "def fill_between(self, canvas, X, lower, upper, color=None, label=None, **kwargs):\n        raise NotImplementedError(\"Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library\")",
    "docstring": "Fill along the xaxis between lower and upper.\n        \n        the kwargs are plotting library specific kwargs!"
  },
  {
    "code": "def _generate_password():\n    uuid_str = six.text_type(uuid.uuid4()).encode(\"UTF-8\")\n    return hashlib.sha1(uuid_str).hexdigest()",
    "docstring": "Create a random password\n\n    The password is made by taking a uuid and passing it though sha1sum.\n    We may change this in future to gain more entropy.\n\n    This is based on the tripleo command os-make-password"
  },
  {
    "code": "def run(self):\n        self.find_new()\n        for n in self.news:\n            print(\"{0}\".format(n))\n        print(\"\")\n        self.msg.template(78)\n        print(\"| Installed {0} new configuration files:\".format(\n            len(self.news)))\n        self.msg.template(78)\n        self.choices()",
    "docstring": "print .new configuration files"
  },
  {
    "code": "def scramble_date(self, value, format='%d %b %Y'):\n        if value == '':\n            end_date = 'now'\n            start_date = '-1y'\n        else:\n            end_date = datetime.datetime.strptime(value, format).date()\n            start_date = end_date - datetime.timedelta(days=365)\n        fake_date = fake.date_time_between(start_date=start_date,\n                                           end_date=end_date).strftime(format).upper()\n        return fake_date",
    "docstring": "Return random date"
  },
  {
    "code": "def report_privilege_information():\n    \"Report all privilege information assigned to the current process.\"\n    privileges = get_privilege_information()\n    print(\"found {0} privileges\".format(privileges.count))\n    tuple(map(print, privileges))",
    "docstring": "Report all privilege information assigned to the current process."
  },
  {
    "code": "def is_hidden(path):\n    hidden = False\n    f = os.path.basename(path)\n    if f[:1] in ('.', b'.'):\n        hidden = True\n    elif _PLATFORM == 'windows':\n        FILE_ATTRIBUTE_HIDDEN = 0x2\n        if PY35:\n            results = os.lstat(path)\n            hidden = bool(results.st_file_attributes & FILE_ATTRIBUTE_HIDDEN)\n        else:\n            if isinstance(path, bytes):\n                attrs = ctypes.windll.kernel32.GetFileAttributesA(path)\n            else:\n                attrs = ctypes.windll.kernel32.GetFileAttributesW(path)\n            hidden = attrs != -1 and attrs & FILE_ATTRIBUTE_HIDDEN\n    elif _PLATFORM == \"osx\":\n        results = os.lstat(path)\n        hidden = bool(results.st_flags & stat.UF_HIDDEN)\n    return hidden",
    "docstring": "Check if file is hidden."
  },
  {
    "code": "def read(self, timeout=None):\n        if not hasattr(self, '_sock'):\n            return None\n        if timeout:\n            if self._heartbeat_timeout:\n                self._heartbeat_timeout.delete()\n            self._heartbeat_timeout = \\\n                event.timeout(timeout, self._sock_read_cb, self._sock)\n        elif self._heartbeat_timeout:\n            self._heartbeat_timeout.delete()\n            self._heartbeat_timeout = None\n        return self._sock.read()",
    "docstring": "Read from the transport. If no data is available, should return None.\n        The timeout is ignored as this returns only data that has already\n        been buffered locally."
  },
  {
    "code": "def convert_context_to_csv(self, context):\n        content = []\n        date_headers = context['date_headers']\n        headers = ['Name']\n        headers.extend([date.strftime('%m/%d/%Y') for date in date_headers])\n        headers.append('Total')\n        content.append(headers)\n        summaries = context['summaries']\n        summary = summaries.get(self.export, [])\n        for rows, totals in summary:\n            for name, user_id, hours in rows:\n                data = [name]\n                data.extend(hours)\n                content.append(data)\n            total = ['Totals']\n            total.extend(totals)\n            content.append(total)\n        return content",
    "docstring": "Convert the context dictionary into a CSV file."
  },
  {
    "code": "def add_header(self, key, value, **params):\n        key = self.escape(key)\n        ci_key = key.casefold()\n        def quoted_params(items):\n            for p in items:\n                param_name = self.escape(p[0])\n                param_val = self.de_quote(self.escape(p[1]))\n                yield param_name, param_val\n        sorted_items = sorted(params.items())\n        quoted_iter = ('%s=\"%s\"' % p for p in quoted_params(sorted_items))\n        param_str = ' '.join(quoted_iter)\n        if param_str:\n            value = \"%s; %s\" % (value, param_str)\n        self._header_data[ci_key] = (key, value)",
    "docstring": "Add a header to the collection, including potential parameters.\n\n        Args:\n            key (str): The name of the header\n            value (str): The value to store under that key\n            params: Option parameters to be appended to the value,\n                automatically formatting them in a standard way"
  },
  {
    "code": "def wrap_handler(cls, handler, protocol, **kwargs):\n        def _wrapper(request, *args, **kwargs):\n            instance = cls(request=request, **kwargs)\n            if protocol == Resource.Protocol.http:\n                return instance._wrap_http(handler, request=request, **kwargs)\n            elif protocol == Resource.Protocol.websocket:\n                return instance._wrap_ws(handler, request=request, **kwargs)\n            elif protocol == Resource.Protocol.amqp:\n                return instance._wrap_amqp(view_type, *args, **kwargs)\n            else:\n                raise Exception('Communication protocol not specified')\n        return _wrapper",
    "docstring": "Wrap a request handler with the matching protocol handler"
  },
  {
    "code": "def node_is_subclass(cls, *subclass_names):\n    if not isinstance(cls, (ClassDef, Instance)):\n        return False\n    for base_cls in cls.bases:\n        try:\n            for inf in base_cls.inferred():\n                if inf.qname() in subclass_names:\n                    return True\n                if inf != cls and node_is_subclass(\n                        inf, *subclass_names):\n                    return True\n        except InferenceError:\n            continue\n    return False",
    "docstring": "Checks if cls node has parent with subclass_name."
  },
  {
    "code": "def create_partitions(self, topic_partitions, timeout_ms=None, validate_only=False):\n        version = self._matching_api_version(CreatePartitionsRequest)\n        timeout_ms = self._validate_timeout(timeout_ms)\n        if version == 0:\n            request = CreatePartitionsRequest[version](\n                topic_partitions=[self._convert_create_partitions_request(topic_name, new_partitions) for topic_name, new_partitions in topic_partitions.items()],\n                timeout=timeout_ms,\n                validate_only=validate_only\n            )\n        else:\n            raise NotImplementedError(\n                \"Support for CreatePartitions v{} has not yet been added to KafkaAdminClient.\"\n                .format(version))\n        return self._send_request_to_controller(request)",
    "docstring": "Create additional partitions for an existing topic.\n\n        :param topic_partitions: A map of topic name strings to NewPartition objects.\n        :param timeout_ms: Milliseconds to wait for new partitions to be\n            created before the broker returns.\n        :param validate_only: If True, don't actually create new partitions.\n            Default: False\n        :return: Appropriate version of CreatePartitionsResponse class."
  },
  {
    "code": "def show_graph(self, format='svg'):\n        g = self.to_simple_graph(AssetExists())\n        if format == 'svg':\n            return g.svg\n        elif format == 'png':\n            return g.png\n        elif format == 'jpeg':\n            return g.jpeg\n        else:\n            raise AssertionError(\"Unknown graph format %r.\" % format)",
    "docstring": "Render this Pipeline as a DAG.\n\n        Parameters\n        ----------\n        format : {'svg', 'png', 'jpeg'}\n            Image format to render with.  Default is 'svg'."
  },
  {
    "code": "def run_init_tables(*args):\n    print('--')\n    create_table(TabPost)\n    create_table(TabTag)\n    create_table(TabMember)\n    create_table(TabWiki)\n    create_table(TabLink)\n    create_table(TabEntity)\n    create_table(TabPostHist)\n    create_table(TabWikiHist)\n    create_table(TabCollect)\n    create_table(TabPost2Tag)\n    create_table(TabRel)\n    create_table(TabEvaluation)\n    create_table(TabUsage)\n    create_table(TabReply)\n    create_table(TabUser2Reply)\n    create_table(TabRating)\n    create_table(TabEntity2User)\n    create_table(TabLog)",
    "docstring": "Run to init tables."
  },
  {
    "code": "def validate(self, proxy_ip, client_ip):\n        if self.pseudo_proxy:\n            proxy = self.pseudo_proxy\n        elif proxy_ip not in self.proxies:\n            return False\n        else:\n            proxy = self.proxies[proxy_ip]\n        return client_ip in proxy",
    "docstring": "Looks up the proxy identified by its IP, then verifies that\n        the given client IP may be introduced by that proxy.\n\n        :param proxy_ip: The IP address of the proxy.\n        :param client_ip: The IP address of the supposed client.\n\n        :returns: True if the proxy is permitted to introduce the\n                  client; False if the proxy doesn't exist or isn't\n                  permitted to introduce the client."
  },
  {
    "code": "def ifft(a, n=None, axis=-1, norm=None):\n    unitary = _unitary(norm)\n    output = mkl_fft.ifft(a, n, axis)\n    if unitary:\n        output *= sqrt(output.shape[axis])\n    return output",
    "docstring": "Compute the one-dimensional inverse discrete Fourier Transform.\n\n    This function computes the inverse of the one-dimensional *n*-point\n    discrete Fourier transform computed by `fft`.  In other words,\n    ``ifft(fft(a)) == a`` to within numerical accuracy.\n    For a general description of the algorithm and definitions,\n    see `numpy.fft`.\n\n    The input should be ordered in the same way as is returned by `fft`,\n    i.e.,\n\n    * ``a[0]`` should contain the zero frequency term,\n    * ``a[1:n//2]`` should contain the positive-frequency terms,\n    * ``a[n//2 + 1:]`` should contain the negative-frequency terms, in\n      increasing order starting from the most negative frequency.\n\n    Parameters\n    ----------\n    a : array_like\n        Input array, can be complex.\n    n : int, optional\n        Length of the transformed axis of the output.\n        If `n` is smaller than the length of the input, the input is cropped.\n        If it is larger, the input is padded with zeros.  If `n` is not given,\n        the length of the input along the axis specified by `axis` is used.\n        See notes about padding issues.\n    axis : int, optional\n        Axis over which to compute the inverse DFT.  If not given, the last\n        axis is used.\n    norm : {None, \"ortho\"}, optional\n        .. versionadded:: 1.10.0\n        Normalization mode (see `numpy.fft`). Default is None.\n\n    Returns\n    -------\n    out : complex ndarray\n        The truncated or zero-padded input, transformed along the axis\n        indicated by `axis`, or the last one if `axis` is not specified.\n\n    Raises\n    ------\n    IndexError\n        If `axes` is larger than the last axis of `a`.\n\n    See Also\n    --------\n    numpy.fft : An introduction, with definitions and general explanations.\n    fft : The one-dimensional (forward) FFT, of which `ifft` is the inverse\n    ifft2 : The two-dimensional inverse FFT.\n    ifftn : The n-dimensional inverse FFT.\n\n    Notes\n    -----\n    If the input parameter `n` is larger than the size of the input, the input\n    is padded by appending zeros at the end.  Even though this is the common\n    approach, it might lead to surprising results.  If a different padding is\n    desired, it must be performed before calling `ifft`.\n\n    Examples\n    --------\n    >>> np.fft.ifft([0, 4, 0, 0])\n    array([ 1.+0.j,  0.+1.j, -1.+0.j,  0.-1.j])\n\n    Create and plot a band-limited signal with random phases:\n\n    >>> import matplotlib.pyplot as plt\n    >>> t = np.arange(400)\n    >>> n = np.zeros((400,), dtype=complex)\n    >>> n[40:60] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20,)))\n    >>> s = np.fft.ifft(n)\n    >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--')\n    ...\n    >>> plt.legend(('real', 'imaginary'))\n    ...\n    >>> plt.show()"
  },
  {
    "code": "def add_source(self, source):\n        geocode_service = self._get_service_by_name(source[0])\n        self._sources.append(geocode_service(**source[1]))",
    "docstring": "Add a geocoding service to this instance."
  },
  {
    "code": "def _get_specifications(specifications):\n    if not specifications or specifications is object:\n        raise ValueError(\"No specifications given\")\n    elif inspect.isclass(specifications):\n        if Provides.USE_MODULE_QUALNAME:\n            if sys.version_info < (3, 3, 0):\n                raise ValueError(\n                    \"Qualified name capability requires Python 3.3+\"\n                )\n            if not specifications.__module__:\n                return [specifications.__qualname__]\n            return [\n                \"{0}.{1}\".format(\n                    specifications.__module__, specifications.__qualname__\n                )\n            ]\n        else:\n            return [specifications.__name__]\n    elif is_string(specifications):\n        specifications = specifications.strip()\n        if not specifications:\n            raise ValueError(\"Empty specification given\")\n        return [specifications]\n    elif isinstance(specifications, (list, tuple)):\n        results = []\n        for specification in specifications:\n            results.extend(_get_specifications(specification))\n        return results\n    else:\n        raise ValueError(\n            \"Unhandled specifications type : {0}\".format(\n                type(specifications).__name__\n            )\n        )",
    "docstring": "Computes the list of strings corresponding to the given specifications\n\n    :param specifications: A string, a class or a list of specifications\n    :return: A list of strings\n    :raise ValueError: Invalid specification found"
  },
  {
    "code": "def filter_and_date(local_root, conf_rel_paths, commits):\n    dates_paths = dict()\n    for commit in commits:\n        if commit in dates_paths:\n            continue\n        command = ['git', 'ls-tree', '--name-only', '-r', commit] + conf_rel_paths\n        try:\n            output = run_command(local_root, command)\n        except CalledProcessError as exc:\n            raise GitError('Git ls-tree failed on {0}'.format(commit), exc.output)\n        if output:\n            dates_paths[commit] = [None, output.splitlines()[0].strip()]\n    command_prefix = ['git', 'show', '--no-patch', '--pretty=format:%ct']\n    for commits_group in chunk(dates_paths, 50):\n        command = command_prefix + commits_group\n        output = run_command(local_root, command)\n        timestamps = [int(i) for i in RE_UNIX_TIME.findall(output)]\n        for i, commit in enumerate(commits_group):\n            dates_paths[commit][0] = timestamps[i]\n    return dates_paths",
    "docstring": "Get commit Unix timestamps and first matching conf.py path. Exclude commits with no conf.py file.\n\n    :raise CalledProcessError: Unhandled git command failure.\n    :raise GitError: A commit SHA has not been fetched.\n\n    :param str local_root: Local path to git root directory.\n    :param iter conf_rel_paths: List of possible relative paths (to git root) of Sphinx conf.py (e.g. docs/conf.py).\n    :param iter commits: List of commit SHAs.\n\n    :return: Commit time (seconds since Unix epoch) for each commit and conf.py path. SHA keys and [int, str] values.\n    :rtype: dict"
  },
  {
    "code": "def ec2_table(instances):\n    t = prettytable.PrettyTable(['ID', 'State', 'Monitored', 'Image', 'Name', 'Type', 'SSH key', 'DNS'])\n    t.align = 'l'\n    for i in instances:\n        name = i.tags.get('Name', '')\n        t.add_row([i.id, i.state, i.monitored, i.image_id, name, i.instance_type, i.key_name, i.dns_name])\n    return t",
    "docstring": "Print nice looking table of information from list of instances"
  },
  {
    "code": "def read_until_done(self, command, timeout=None):\n    message = self.read_message(timeout)\n    while message.command != 'DONE':\n      message.assert_command_is(command)\n      yield message\n      message = self.read_message(timeout)",
    "docstring": "Yield messages read until we receive a 'DONE' command.\n\n    Read messages of the given command until we receive a 'DONE' command.  If a\n    command different than the requested one is received, an AdbProtocolError\n    is raised.\n\n    Args:\n      command: The command to expect, like 'DENT' or 'DATA'.\n      timeout: The timeouts.PolledTimeout to use for this operation.\n\n    Yields:\n      Messages read, of type self.RECV_MSG_TYPE, see read_message().\n\n    Raises:\n      AdbProtocolError: If an unexpected command is read.\n      AdbRemoteError: If a 'FAIL' message is read."
  },
  {
    "code": "def _pname_and_metadata(in_file):\n    if os.path.isfile(in_file):\n        with open(in_file) as in_handle:\n            md, global_vars = _parse_metadata(in_handle)\n        base = os.path.splitext(os.path.basename(in_file))[0]\n        md_file = in_file\n    elif objectstore.is_remote(in_file):\n        with objectstore.open_file(in_file) as in_handle:\n            md, global_vars = _parse_metadata(in_handle)\n        base = os.path.splitext(os.path.basename(in_file))[0]\n        md_file = None\n    else:\n        if in_file.endswith(\".csv\"):\n            raise ValueError(\"Did not find input metadata file: %s\" % in_file)\n        base, md, global_vars = _safe_name(os.path.splitext(os.path.basename(in_file))[0]), {}, {}\n        md_file = None\n    return _safe_name(base), md, global_vars, md_file",
    "docstring": "Retrieve metadata and project name from the input metadata CSV file.\n\n    Uses the input file name for the project name and for back compatibility,\n    accepts the project name as an input, providing no metadata."
  },
  {
    "code": "def get_current_user_info(anchore_auth):\n    user_url = anchore_auth['client_info_url'] + '/' + anchore_auth['username']\n    user_timeout = 60\n    retries = 3\n    result = requests.get(user_url, headers={'x-anchore-password': anchore_auth['password']})\n    if result.status_code == 200:\n        user_data = json.loads(result.content)\n    else:\n        raise requests.HTTPError('Error response from service: {}'.format(result.status_code))\n    return user_data",
    "docstring": "Return the metadata about the current user as supplied by the anchore.io service. Includes permissions and tier access.\n\n    :return: Dict of user metadata"
  },
  {
    "code": "def Random(self):\n        if len(self.d) == 0:\n            raise ValueError('Pmf contains no values.')\n        target = random.random()\n        total = 0.0\n        for x, p in self.d.iteritems():\n            total += p\n            if total >= target:\n                return x\n        assert False",
    "docstring": "Chooses a random element from this PMF.\n\n        Returns:\n            float value from the Pmf"
  },
  {
    "code": "def inv(self):\n        self.x, self.y = self.y, self.x\n        self._x_, self._y_ = self._y_, self._x_\n        self.xfac, self.yfac = 1 / self.yfac, 1 / self.xfac\n        self._xfac_, self._yfac_ = 1 / self._yfac_, 1 / self._xfac_\n        self._u = 1 / self._u.conj()",
    "docstring": "Invert the transform.\n\n        After calling this method, calling the instance will do the inverse\n        transform. Calling this twice return the instance to the original\n        transform."
  },
  {
    "code": "def read_parameters(self):\n        param_fname = join(self.out_dir, \"PARAMETERS.OUT\")\n        if not exists(param_fname):\n            raise FileNotFoundError(\"No PARAMETERS.OUT found\")\n        with open(param_fname) as nml_file:\n            parameters = dict(f90nml.read(nml_file))\n            for group in [\"nml_years\", \"nml_allcfgs\", \"nml_outputcfgs\"]:\n                parameters[group] = dict(parameters[group])\n                for k, v in parameters[group].items():\n                    parameters[group][k] = _clean_value(v)\n                parameters[group.replace(\"nml_\", \"\")] = parameters.pop(group)\n            self.config = parameters\n        return parameters",
    "docstring": "Read a parameters.out file\n\n        Returns\n        -------\n        dict\n            A dictionary containing all the configuration used by MAGICC"
  },
  {
    "code": "def get_last_doc(self):\n        try:\n            result = self.solr.search('*:*', sort='_ts desc', rows=1)\n        except ValueError:\n            return None\n        for r in result:\n            r['_id'] = r.pop(self.unique_key)\n            return r",
    "docstring": "Returns the last document stored in the Solr engine."
  },
  {
    "code": "def _create_symlink_cygwin(self, initial_path, final_path):\n        symlink_cmd = [os.path.join(self._cygwin_bin_location, \"ln.exe\"),\n                       \"-s\", self._get_cygwin_path(initial_path),\n                       self._get_cygwin_path(final_path)]\n        process = Popen(symlink_cmd,\n                        stdout=PIPE, stderr=PIPE, shell=False)\n        out, err = process.communicate()\n        if err:\n            print(err)\n            raise Exception(err)\n        return out.strip()",
    "docstring": "Use cygqin to generate symbolic link"
  },
  {
    "code": "def _create_ema_callback(self):\n        with self.cached_name_scope():\n            size = tf.cast(self.queue.size(), tf.float32, name='queue_size')\n        size_ema_op = add_moving_summary(size, collection=None, decay=0.5)[0].op\n        ret = RunOp(\n            lambda: size_ema_op,\n            run_before=False,\n            run_as_trigger=False,\n            run_step=True)\n        ret.name_scope = \"InputSource/EMA\"\n        return ret",
    "docstring": "Create a hook-only callback which maintain EMA of the queue size.\n        Also tf.summary.scalar the EMA."
  },
  {
    "code": "def error(msg, log_file=None):\n        UtilClass.print_msg(msg + os.linesep)\n        if log_file is not None:\n            UtilClass.writelog(log_file, msg, 'append')\n        raise RuntimeError(msg)",
    "docstring": "Print, output error message and raise RuntimeError."
  },
  {
    "code": "def expand_factor_conditions(s, env):\n    try:\n        factor, value = re.split(r'\\s*\\:\\s*', s)\n    except ValueError:\n        return s\n    if matches_factor_conditions(factor, env):\n        return value\n    else:\n        return ''",
    "docstring": "If env matches the expanded factor then return value else return ''.\n\n    Example\n    -------\n    >>> s = 'py{33,34}: docformatter'\n    >>> expand_factor_conditions(s, Env(name=\"py34\", ...))\n    \"docformatter\"\n    >>> expand_factor_conditions(s, Env(name=\"py26\", ...))\n    \"\""
  },
  {
    "code": "def creator_type(self, creator_type):\n        allowed_values = [\"USER\", \"ALERT\", \"SYSTEM\"]\n        if not set(creator_type).issubset(set(allowed_values)):\n            raise ValueError(\n                \"Invalid values for `creator_type` [{0}], must be a subset of [{1}]\"\n                .format(\", \".join(map(str, set(creator_type) - set(allowed_values))),\n                        \", \".join(map(str, allowed_values)))\n            )\n        self._creator_type = creator_type",
    "docstring": "Sets the creator_type of this Event.\n\n\n        :param creator_type: The creator_type of this Event.  # noqa: E501\n        :type: list[str]"
  },
  {
    "code": "def duplicate_txn_id(ipn_obj):\n    similars = (ipn_obj.__class__._default_manager\n                .filter(txn_id=ipn_obj.txn_id)\n                .exclude(id=ipn_obj.id)\n                .exclude(flag=True)\n                .order_by('-created_at')[:1])\n    if len(similars) > 0:\n        return similars[0].payment_status == ipn_obj.payment_status\n    return False",
    "docstring": "Returns True if a record with this transaction id exists and its\n    payment_status has not changed.\n    This function has been completely changed from its previous implementation\n    where it used to specifically only check for a Pending->Completed\n    transition."
  },
  {
    "code": "def get_uri(source):\n    import gst\n    src_info = source_info(source)\n    if src_info['is_file']:\n        return get_uri(src_info['uri'])\n    elif gst.uri_is_valid(source):\n        uri_protocol = gst.uri_get_protocol(source)\n        if gst.uri_protocol_is_supported(gst.URI_SRC, uri_protocol):\n            return source\n        else:\n            raise IOError('Invalid URI source for Gstreamer')\n    else:\n        raise IOError('Failed getting uri for path %s: no such file' % source)",
    "docstring": "Check a media source as a valid file or uri and return the proper uri"
  },
  {
    "code": "def is_same_service(self, endpoint):\n        return (\n            self.get_framework_uuid() == endpoint.get_framework_uuid()\n            and self.get_service_id() == endpoint.get_service_id()\n        )",
    "docstring": "Tests if this endpoint and the given one have the same framework UUID\n        and service ID\n\n        :param endpoint: Another endpoint\n        :return: True if both endpoints represent the same remote service"
  },
  {
    "code": "def get_tuple_type_str_parts(s: str) -> Optional[Tuple[str, Optional[str]]]:\n    match = TUPLE_TYPE_STR_RE.match(s)\n    if match is not None:\n        tuple_prefix = match.group(1)\n        tuple_dims = match.group(2)\n        return tuple_prefix, tuple_dims\n    return None",
    "docstring": "Takes a JSON ABI type string.  For tuple type strings, returns the separated\n    prefix and array dimension parts.  For all other strings, returns ``None``."
  },
  {
    "code": "def _verifyDiscoveryResults(self, resp_msg, endpoint=None):\n        if resp_msg.getOpenIDNamespace() == OPENID2_NS:\n            return self._verifyDiscoveryResultsOpenID2(resp_msg, endpoint)\n        else:\n            return self._verifyDiscoveryResultsOpenID1(resp_msg, endpoint)",
    "docstring": "Extract the information from an OpenID assertion message and\n        verify it against the original\n\n        @param endpoint: The endpoint that resulted from doing discovery\n        @param resp_msg: The id_res message object\n\n        @returns: the verified endpoint"
  },
  {
    "code": "def __exists_row_not_too_old(self, row):\n        if row is None:\n            return False\n        record_time = dateutil.parser.parse(row[2])\n        now = datetime.datetime.now(dateutil.tz.gettz())\n        age = (record_time - now).total_seconds()\n        if age > self.max_age:\n            return False\n        return True",
    "docstring": "Check if the given row exists and is not too old"
  },
  {
    "code": "def get_host_map(root):\n  hosts_map = {}\n  for host in root.get_all_hosts():\n    hosts_map[host.hostId] = {\"hostname\": NAGIOS_HOSTNAME_FORMAT % (host.hostname,),\n                              \"address\": host.ipAddress}\n  for cluster in root.get_all_clusters():\n    hosts_map[cluster.name] = {\"hostname\": cluster.name,\n                               \"address\": quote(cluster.name)}\n  hosts_map[CM_DUMMY_HOST] = {\"hostname\": CM_DUMMY_HOST,\n                              \"address\": CM_DUMMY_HOST}\n  return hosts_map",
    "docstring": "Gets a mapping between CM hostId and Nagios host information\n\n      The key is the CM hostId\n      The value is an object containing the Nagios hostname and host address"
  },
  {
    "code": "def table_dataset_database_table(\n    table              = None,\n    include_attributes = None,\n    rows_limit         = None,\n    print_progress     = False,\n    ):\n    if print_progress:\n        import shijian\n        progress = shijian.Progress()\n        progress.engage_quick_calculation_mode()\n        number_of_rows = len(table)\n    if include_attributes:\n        columns = include_attributes\n    else:\n        columns = table.columns\n    table_contents = [columns]\n    for index_row, row in enumerate(table):\n        if rows_limit is not None:\n            if index_row >= rows_limit:\n                break\n        row_contents = []\n        for column in columns:\n            try:\n                string_representation = str(row[column])\n            except:\n                string_representation = str(row[column].encode(\"utf-8\"))\n            row_contents.append(string_representation)\n        table_contents.append(row_contents)\n        if print_progress:\n            print(progress.add_datum(\n                fraction = float(index_row) / float(number_of_rows))\n            )\n    return table_contents",
    "docstring": "Create a pyprel table contents list from a database table of the module\n    dataset. Attributes to be included in the table can be specified; by\n    default, all attributes are included. A limit on the number of rows included\n    can be specified. Progress on building the table can be reported."
  },
  {
    "code": "def _mark_in_progress(self, node_id):\n        self.queued.remove(node_id)\n        self.in_progress.add(node_id)",
    "docstring": "Mark the node as 'in progress'.\n\n        Callers must hold the lock.\n\n        :param str node_id: The node ID to mark as in progress."
  },
  {
    "code": "def exchange_oauth2_member(access_token, base_url=OH_BASE_URL,\n                           all_files=False):\n    url = urlparse.urljoin(\n        base_url,\n        '/api/direct-sharing/project/exchange-member/?{}'.format(\n            urlparse.urlencode({'access_token': access_token})))\n    member_data = get_page(url)\n    returned = member_data.copy()\n    if all_files:\n        while member_data['next']:\n            member_data = get_page(member_data['next'])\n            returned['data'] = returned['data'] + member_data['data']\n    logging.debug('JSON data: {}'.format(returned))\n    return returned",
    "docstring": "Returns data for a specific user, including shared data files.\n\n    :param access_token: This field is the user specific access_token.\n    :param base_url: It is this URL `https://www.openhumans.org`."
  },
  {
    "code": "def _get_blob(self):\n        if not self.__blob:\n            self.__blob = self.repo.get_object(self.id)\n        return self.__blob",
    "docstring": "read blob on access only because get_object is slow"
  },
  {
    "code": "def _init_forms(self):\n        super(BaseCRUDView, self)._init_forms()\n        conv = GeneralModelConverter(self.datamodel)\n        if not self.add_form:\n            self.add_form = conv.create_form(\n                self.label_columns,\n                self.add_columns,\n                self.description_columns,\n                self.validators_columns,\n                self.add_form_extra_fields,\n                self.add_form_query_rel_fields,\n            )\n        if not self.edit_form:\n            self.edit_form = conv.create_form(\n                self.label_columns,\n                self.edit_columns,\n                self.description_columns,\n                self.validators_columns,\n                self.edit_form_extra_fields,\n                self.edit_form_query_rel_fields,\n            )",
    "docstring": "Init forms for Add and Edit"
  },
  {
    "code": "def _aggregrate_scores(its,tss,num_sentences):\n    final = []\n    for i,el in enumerate(its):\n        for j, le in enumerate(tss):\n            if el[2] == le[2]:\n                assert el[1] == le[1]\n                final.append((el[1],i+j,el[2]))\n    _final = sorted(final, key = lambda tup: tup[1])[:num_sentences]\n    return sorted(_final, key = lambda tup: tup[0])",
    "docstring": "rerank the two vectors by\n    min aggregrate rank, reorder"
  },
  {
    "code": "def purge(name, delete_key=True):\n    ret = {}\n    client = salt.client.get_local_client(__opts__['conf_file'])\n    data = vm_info(name, quiet=True)\n    if not data:\n        __jid_event__.fire_event({'error': 'Failed to find VM {0} to purge'.format(name)}, 'progress')\n        return 'fail'\n    host = next(six.iterkeys(data))\n    try:\n        cmd_ret = client.cmd_iter(\n                host,\n                'virt.purge',\n                [name, True],\n                timeout=600)\n    except SaltClientError as client_error:\n        return 'Virtual machine {0} could not be purged: {1}'.format(name, client_error)\n    for comp in cmd_ret:\n        ret.update(comp)\n    if delete_key:\n        log.debug('Deleting key %s', name)\n        skey = salt.key.Key(__opts__)\n        skey.delete_key(name)\n    __jid_event__.fire_event({'message': 'Purged VM {0}'.format(name)}, 'progress')\n    return 'good'",
    "docstring": "Destroy the named VM"
  },
  {
    "code": "def _sane_version_list(version):\n    v0 = str(version[0])\n    if v0:\n        try:\n            v0 = v0.lstrip(\"v\").lstrip(\"V\")\n            v0 = int(v0)\n        except ValueError:\n            v0 = None\n    if v0 is None:\n        version = [0, 0] + version\n    else:\n        version[0] = v0\n    try:\n        version[1] = int(version[1])\n    except ValueError:\n        version = [version[0], 0] + version[1:]\n    return version",
    "docstring": "Ensure the major and minor are int.\n\n    Parameters\n    ----------\n    version: list\n        Version components\n\n    Returns\n    -------\n    version: list\n        List of components where first two components has been sanitised"
  },
  {
    "code": "def is_service_selected(self, service):\n        service_uid = api.get_uid(service)\n        for arnum in range(self.ar_count):\n            analyses = self.fieldvalues.get(\"Analyses-{}\".format(arnum))\n            if not analyses:\n                continue\n            service_uids = map(self.get_service_uid_from, analyses)\n            if service_uid in service_uids:\n                return True\n        return False",
    "docstring": "Checks if the given service is selected by one of the ARs.\n        This is used to make the whole line visible or not."
  },
  {
    "code": "def trim(self):\n        overlay_data_offset = self.get_overlay_data_start_offset()\n        if overlay_data_offset is not None:\n            return self.__data__[ : overlay_data_offset ]\n        return self.__data__[:]",
    "docstring": "Return the just data defined by the PE headers, removing any overlayed data."
  },
  {
    "code": "def scan_elements(self):\n        for x in self.redis.sscan_iter(self.key):\n            yield self._unpickle(x)",
    "docstring": "Yield each of the elements from the collection, without pulling them\n        all into memory.\n\n        .. warning::\n            This method is not available on the set collections provided\n            by Python.\n\n            This method may return the element multiple times.\n            See the `Redis SCAN documentation\n            <http://redis.io/commands/scan#scan-guarantees>`_ for details."
  },
  {
    "code": "def could_scope_out(self):\n        return not self.waiting_for or \\\n               isinstance(self.waiting_for, callable.EndOfStory) or \\\n               self.is_breaking_a_loop()",
    "docstring": "could bubble up from current scope\n\n        :return:"
  },
  {
    "code": "def iter_predict(self, eval_data, num_batch=None, reset=True, sparse_row_id_fn=None):\n        assert self.binded and self.params_initialized\n        if reset:\n            eval_data.reset()\n        for nbatch, eval_batch in enumerate(eval_data):\n            if num_batch is not None and nbatch == num_batch:\n                break\n            self.prepare(eval_batch, sparse_row_id_fn=sparse_row_id_fn)\n            self.forward(eval_batch, is_train=False)\n            pad = eval_batch.pad\n            outputs = [out[0:out.shape[0]-pad] for out in self.get_outputs()]\n            yield (outputs, nbatch, eval_batch)",
    "docstring": "Iterates over predictions.\n\n        Examples\n        --------\n        >>> for pred, i_batch, batch in module.iter_predict(eval_data):\n        ...     # pred is a list of outputs from the module\n        ...     # i_batch is a integer\n        ...     # batch is the data batch from the data iterator\n\n        Parameters\n        ----------\n        eval_data : DataIter\n            Evaluation data to run prediction on.\n        num_batch : int\n            Default is ``None``, indicating running all the batches in the data iterator.\n        reset : bool\n            Default is ``True``, indicating whether we should reset the data iter before start\n            doing prediction.\n        sparse_row_id_fn : A callback function\n            The function  takes `data_batch` as an input and returns a dict of\n            str -> NDArray. The resulting dict is used for pulling row_sparse\n            parameters from the kvstore, where the str key is the name of the param,\n            and the value is the row id of the param to pull."
  },
  {
    "code": "def setuptools_entry(dist, keyword, value):\n    if not value:\n        return\n    version = get_version()\n    if dist.metadata.version is not None:\n        s = \"Ignoring explicit version='{0}' in setup.py, using '{1}' instead\"\n        warnings.warn(s.format(dist.metadata.version, version))\n    dist.metadata.version = version\n    ExistingCustomBuildPy = dist.cmdclass.get('build_py', object)\n    class KatVersionBuildPy(AddVersionToInitBuildPy, ExistingCustomBuildPy):\n    dist.cmdclass['build_py'] = KatVersionBuildPy\n    ExistingCustomSdist = dist.cmdclass.get('sdist', object)\n    class KatVersionSdist(AddVersionToInitSdist, ExistingCustomSdist):\n    dist.cmdclass['sdist'] = KatVersionSdist",
    "docstring": "Setuptools entry point for setting version and baking it into package."
  },
  {
    "code": "def _extract(self, path, outdir, filter_func=None):\n    with open_zip(path) as archive_file:\n      for name in archive_file.namelist():\n        if name.startswith('/') or name.startswith('..'):\n          raise ValueError('Zip file contains unsafe path: {}'.format(name))\n        if (not filter_func or filter_func(name)):\n          archive_file.extract(name, outdir)",
    "docstring": "Extract from a zip file, with an optional filter.\n\n    :param function filter_func: optional filter with the filename as the parameter.  Returns True\n                                 if the file should be extracted."
  },
  {
    "code": "def after_epoch(self, epoch_data: EpochData, **kwargs) -> None:\n        self._save_stats(epoch_data)\n        super().after_epoch(epoch_data=epoch_data, **kwargs)",
    "docstring": "Compute the specified aggregations and save them to the given epoch data.\n\n        :param epoch_data: epoch data to be processed"
  },
  {
    "code": "def __diff_internal(self):\n        assert self.p > 0, \"order of Bspline must be > 0\"\n        t    = self.knot_vector\n        p    = self.p\n        Bi   = Bspline( t[:-1], p-1 )\n        Bip1 = Bspline( t[1:],  p-1 )\n        numer1 = +p\n        numer2 = -p\n        denom1 = t[p:-1]   - t[:-(p+1)]\n        denom2 = t[(p+1):] - t[1:-p]\n        with np.errstate(divide='ignore', invalid='ignore'):\n            ci   = np.where(denom1 != 0., (numer1 / denom1), 0.)\n            cip1 = np.where(denom2 != 0., (numer2 / denom2), 0.)\n        return ( (ci,Bi), (cip1,Bip1) )",
    "docstring": "Differentiate a B-spline once, and return the resulting coefficients and Bspline objects.\n\nThis preserves the Bspline object nature of the data, enabling recursive implementation\nof higher-order differentiation (see `diff`).\n\nThe value of the first derivative of `B` at a point `x` can be obtained as::\n\n    def diff1(B, x):\n        terms = B.__diff_internal()\n        return sum( ci*Bi(x) for ci,Bi in terms )\n\nReturns:\n    tuple of tuples, where each item is (coefficient, Bspline object).\n\nSee:\n    `diff`: differentiation of any order >= 0"
  },
  {
    "code": "def _connect_mitogen_su(spec):\n    return {\n        'method': 'su',\n        'kwargs': {\n            'username': spec.remote_user(),\n            'password': spec.password(),\n            'python_path': spec.python_path(),\n            'su_path': spec.become_exe(),\n            'connect_timeout': spec.timeout(),\n            'remote_name': get_remote_name(spec),\n        }\n    }",
    "docstring": "Return ContextService arguments for su as a first class connection."
  },
  {
    "code": "def load(self, definitions):\n        url = self.location\n        log.debug('importing (%s)', url)\n        if '://' not in url:\n            url = urljoin(definitions.url, url)\n        options = definitions.options\n        d = Definitions(url, options)\n        if d.root.match(Definitions.Tag, wsdlns):\n            self.import_definitions(definitions, d)\n            return\n        if d.root.match(Schema.Tag, Namespace.xsdns):\n            self.import_schema(definitions, d)\n            return\n        raise Exception('document at \"%s\" is unknown' % url)",
    "docstring": "Load the object by opening the URL"
  },
  {
    "code": "def in1d_events(ar1, ar2):\n    ar1 = np.ascontiguousarray(ar1)\n    ar2 = np.ascontiguousarray(ar2)\n    tmp = np.empty_like(ar1, dtype=np.uint8)\n    return analysis_functions.get_in1d_sorted(ar1, ar2, tmp)",
    "docstring": "Does the same than np.in1d but uses the fact that ar1 and ar2 are sorted and the c++ library. Is therefore much much faster."
  },
  {
    "code": "def _check_dependencies(string):\n    opener, closer = '(', ')'\n    _check_enclosing_characters(string, opener, closer)\n    if opener in string:\n        if string[0] != opener:\n            raise ValueError(DEPENDENCIES_NOT_FIRST)\n        ret = True\n    else:\n        ret = False\n    return ret",
    "docstring": "Checks the dependencies constructor. Looks to make sure that the\n    dependencies are the first things defined"
  },
  {
    "code": "def make_wsgi_app(matching, not_found_app=not_found_app):\n    def wsgi_app(environ, start_response):\n        environ['matcha.matching'] = matching\n        try:\n            matched_case, matched_dict = matching(environ)\n        except NotMatched:\n            return not_found_app(environ, start_response)\n        else:\n            environ['matcha.matched_dict'] = matched_dict\n            return matched_case(environ, start_response)\n    return wsgi_app",
    "docstring": "Making a WSGI application from Matching object\n    registered other WSGI applications on each 'case' argument."
  },
  {
    "code": "def sge(self, other):\n        self._check_match(other)\n        return self.to_sint() >= other.to_sint()",
    "docstring": "Compares two equal-sized BinWords, treating them as signed\n        integers, and returning True if the first is bigger or equal."
  },
  {
    "code": "def get_step_by(self, **kwargs):\n        if not kwargs:\n            return None\n        for index, step in enumerate(self.steps.values()):\n            extended_step = dict(step.serialize(), index=index)\n            if all(item in extended_step.items() for item in kwargs.items()):\n                return step\n        return None",
    "docstring": "Get the first step that matches all the passed named arguments.\n\n        Has special argument index not present in the real step.\n\n        Usage:\n            config.get_step_by(name='not found')\n            config.get_step_by(index=0)\n            config.get_step_by(name=\"greeting\", command='echo HELLO MORDOR')\n\n        :param kwargs:\n        :return: Step object or None\n        :rtype: valohai_yaml.objs.Step|None"
  },
  {
    "code": "def bookmark_show(bookmark_id_or_name):\n    client = get_client()\n    res = resolve_id_or_name(client, bookmark_id_or_name)\n    formatted_print(\n        res,\n        text_format=FORMAT_TEXT_RECORD,\n        fields=(\n            (\"ID\", \"id\"),\n            (\"Name\", \"name\"),\n            (\"Endpoint ID\", \"endpoint_id\"),\n            (\"Path\", \"path\"),\n        ),\n        simple_text=(\n            \"{}:{}\".format(res[\"endpoint_id\"], res[\"path\"])\n            if not is_verbose()\n            else None\n        ),\n    )",
    "docstring": "Executor for `globus bookmark show`"
  },
  {
    "code": "def correct_rytov_sc_input(radius_sc, sphere_index_sc, medium_index,\n                           radius_sampling):\n    params = get_params(radius_sampling)\n    na = params[\"na\"]\n    nb = params[\"nb\"]\n    prefac = medium_index / (2 * na)\n    sm = 2 * na - nb - 1\n    rt = nb**2 - 4 * na + 2 * nb + 1 + 4 / medium_index * na * sphere_index_sc\n    sphere_index = prefac * (sm + np.sqrt(rt))\n    x = sphere_index / medium_index - 1\n    radius = radius_sc / (params[\"ra\"] * x**2\n                          + params[\"rb\"] * x\n                          + params[\"rc\"])\n    return radius, sphere_index",
    "docstring": "Inverse correction of refractive index and radius for Rytov\n\n    This method returns the inverse of :func:`correct_rytov_output`.\n\n    Parameters\n    ----------\n    radius_sc: float\n        Systematically corrected radius of the sphere [m]\n    sphere_index_sc: float\n        Systematically corrected refractive index of the sphere\n    medium_index: float\n        Refractive index of the surrounding medium\n    radius_sampling: int\n        Number of pixels used to sample the sphere radius when\n        computing the Rytov field.\n\n    Returns\n    -------\n    radius: float\n        Fitted radius of the sphere [m]\n    sphere_index: float\n        Fitted refractive index of the sphere\n\n    See Also\n    --------\n    correct_rytov_output: the inverse of this method"
  },
  {
    "code": "def set_using_network_time(enable):\n    state = salt.utils.mac_utils.validate_enabled(enable)\n    cmd = 'systemsetup -setusingnetworktime {0}'.format(state)\n    salt.utils.mac_utils.execute_return_success(cmd)\n    return state == salt.utils.mac_utils.validate_enabled(\n        get_using_network_time())",
    "docstring": "Set whether network time is on or off.\n\n    :param enable: True to enable, False to disable. Can also use 'on' or 'off'\n    :type: str bool\n\n    :return: True if successful, False if not\n    :rtype: bool\n\n    :raises: CommandExecutionError on failure\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' timezone.set_using_network_time True"
  },
  {
    "code": "def fetch_rrlyrae_lc_params(**kwargs):\n    save_loc = _get_download_or_cache('table2.dat.gz', **kwargs)\n    dtype = [('id', 'i'), ('type', 'S2'), ('P', 'f'),\n             ('uA', 'f'), ('u0', 'f'), ('uE', 'f'), ('uT', 'f'),\n             ('gA', 'f'), ('g0', 'f'), ('gE', 'f'), ('gT', 'f'),\n             ('rA', 'f'), ('r0', 'f'), ('rE', 'f'), ('rT', 'f'),\n             ('iA', 'f'), ('i0', 'f'), ('iE', 'f'), ('iT', 'f'),\n             ('zA', 'f'), ('z0', 'f'), ('zE', 'f'), ('zT', 'f')]\n    return np.loadtxt(save_loc, dtype=dtype)",
    "docstring": "Fetch data from table 2 of Sesar 2010\n\n    This table includes observationally-derived parameters for all the\n    Sesar 2010 lightcurves."
  },
  {
    "code": "def calc_pident_ignore_gaps(a, b):\n    m = 0\n    mm = 0\n    for A, B in zip(list(a), list(b)):\n        if A == '-' or A == '.' or B == '-' or B == '.':\n            continue\n        if A == B:\n            m += 1\n        else:\n            mm += 1\n    try:\n        return float(float(m)/float((m + mm))) * 100\n    except:\n        return 0",
    "docstring": "calculate percent identity"
  },
  {
    "code": "def field_data(self, field_data):\n        warnings.warn(\"Runtime.field_data is deprecated\", FieldDataDeprecationWarning, stacklevel=2)\n        self._deprecated_per_instance_field_data = field_data",
    "docstring": "Set field_data.\n\n        Deprecated in favor of a 'field-data' service."
  },
  {
    "code": "def _update_url_map(self):\n        if HAS_WEBSOCKETS:\n            self.url_map.update({\n                'ws': WebsocketEndpoint,\n            })\n        self.url_map.update({\n            self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook,\n        })\n        self.url_map.update({\n            self.apiopts.get('app_path', 'app').lstrip('/'): App,\n        })",
    "docstring": "Assemble any dynamic or configurable URLs"
  },
  {
    "code": "def setUp(self):\n        if self.__class__ is HarnessCase:\n            return\n        logger.info('Setting up')\n        logger.info('Deleting all .pdf')\n        os.system('del /q \"%HOMEDRIVE%%HOMEPATH%\\\\Downloads\\\\NewPdf_*.pdf\"')\n        logger.info('Deleting all .xlsx')\n        os.system('del /q \"%HOMEDRIVE%%HOMEPATH%\\\\Downloads\\\\ExcelReport*.xlsx\"')\n        logger.info('Deleting all .pcapng')\n        os.system('del /q \"%s\\\\Captures\\\\*.pcapng\"' % settings.HARNESS_HOME)\n        logger.info('Empty files in temps')\n        os.system('del /q \"%s\\\\Thread_Harness\\\\temp\\\\*.*\"' % settings.HARNESS_HOME)\n        os.system('mkdir %s' % self.result_dir)\n        self._init_harness()\n        self._init_devices()\n        self._init_dut()\n        self._init_rf_shield()",
    "docstring": "Prepare to run test case.\n\n        Start harness service, init golden devices, reset DUT and open browser."
  },
  {
    "code": "def addTable(D):\n    _swap = {\n        \"1\": \"measurement\",\n        \"2\": \"summary\",\n        \"3\": \"ensemble\",\n        \"4\": \"distribution\"\n    }\n    print(\"What type of table would you like to add?\\n\"\n          \"1: measurement\\n\"\n          \"2: summary\\n\"\n          \"3: ensemble (under development)\\n\"\n          \"4: distribution (under development)\\n\"\n          \"\\n Note: if you want to add a whole model, use the addModel() function\")\n    _ans = input(\">\")\n    if _ans in [\"3\", \"4\"]:\n        print(\"I don't know how to do that yet.\")\n    elif _ans in [\"1\", \"2\"]:\n        print(\"Locate the CSV file with the values for this table: \")\n        _path, _files = browse_dialog_file()\n        _path = _confirm_file_path(_files)\n        _values = read_csv_from_file(_path)\n        _table = _build_table(_values)\n        _placement = _prompt_placement(D, _swap[_ans])\n        D = _put_table(D, _placement, _table)\n    else:\n        print(\"That's not a valid option\")\n    return D",
    "docstring": "Add any table type to the given dataset. Use prompts to determine index locations and table type.\n\n    :param dict D: Metadata (dataset)\n    :param dict dat: Metadata (table)\n    :return dict D: Metadata (dataset)"
  },
  {
    "code": "def get_messages(self):\n        cs = self.data[\"comments\"][\"data\"]\n        res = [] \n        for c in cs:\n            res.append(Message(c,self))\n        return res",
    "docstring": "Returns list of Message objects which represents messages being transported."
  },
  {
    "code": "def get_version(self, layer_id, version_id, expand=[]):\n        target_url = self.client.get_url('VERSION', 'GET', 'single', {'layer_id': layer_id, 'version_id': version_id})\n        return self._get(target_url, expand=expand)",
    "docstring": "Get a specific version of a layer."
  },
  {
    "code": "def read_configuration(\n        filepath, find_others=False, ignore_option_errors=False):\n    from setuptools.dist import Distribution, _Distribution\n    filepath = os.path.abspath(filepath)\n    if not os.path.isfile(filepath):\n        raise DistutilsFileError(\n            'Configuration file %s does not exist.' % filepath)\n    current_directory = os.getcwd()\n    os.chdir(os.path.dirname(filepath))\n    try:\n        dist = Distribution()\n        filenames = dist.find_config_files() if find_others else []\n        if filepath not in filenames:\n            filenames.append(filepath)\n        _Distribution.parse_config_files(dist, filenames=filenames)\n        handlers = parse_configuration(\n            dist, dist.command_options,\n            ignore_option_errors=ignore_option_errors)\n    finally:\n        os.chdir(current_directory)\n    return configuration_to_dict(handlers)",
    "docstring": "Read given configuration file and returns options from it as a dict.\n\n    :param str|unicode filepath: Path to configuration file\n        to get options from.\n\n    :param bool find_others: Whether to search for other configuration files\n        which could be on in various places.\n\n    :param bool ignore_option_errors: Whether to silently ignore\n        options, values of which could not be resolved (e.g. due to exceptions\n        in directives such as file:, attr:, etc.).\n        If False exceptions are propagated as expected.\n\n    :rtype: dict"
  },
  {
    "code": "def is_job_complete(job_id, conn=None):\n    result = False\n    job = RBJ.get(job_id).run(conn)\n    if job and job.get(STATUS_FIELD) in COMPLETED:\n        result = job\n    return result",
    "docstring": "is_job_done function checks to if Brain.Jobs Status is Completed\n\n    Completed is defined in statics as Done|Stopped|Error\n\n    :param job_id: <str> id for the job\n    :param conn: (optional)<connection> to run on\n    :return: <dict> if job is done <false> if"
  },
  {
    "code": "def get_volume(self):\n        log.debug(\"getting volumne...\")\n        cmd, url = DEVICE_URLS[\"get_volume\"]\n        return self._exec(cmd, url)",
    "docstring": "returns the current volume"
  },
  {
    "code": "def complete_query(\n        self,\n        name,\n        query,\n        page_size,\n        language_codes=None,\n        company_name=None,\n        scope=None,\n        type_=None,\n        retry=google.api_core.gapic_v1.method.DEFAULT,\n        timeout=google.api_core.gapic_v1.method.DEFAULT,\n        metadata=None,\n    ):\n        if \"complete_query\" not in self._inner_api_calls:\n            self._inner_api_calls[\n                \"complete_query\"\n            ] = google.api_core.gapic_v1.method.wrap_method(\n                self.transport.complete_query,\n                default_retry=self._method_configs[\"CompleteQuery\"].retry,\n                default_timeout=self._method_configs[\"CompleteQuery\"].timeout,\n                client_info=self._client_info,\n            )\n        request = completion_service_pb2.CompleteQueryRequest(\n            name=name,\n            query=query,\n            page_size=page_size,\n            language_codes=language_codes,\n            company_name=company_name,\n            scope=scope,\n            type=type_,\n        )\n        return self._inner_api_calls[\"complete_query\"](\n            request, retry=retry, timeout=timeout, metadata=metadata\n        )",
    "docstring": "Completes the specified prefix with keyword suggestions.\n        Intended for use by a job search auto-complete search box.\n\n        Example:\n            >>> from google.cloud import talent_v4beta1\n            >>>\n            >>> client = talent_v4beta1.CompletionClient()\n            >>>\n            >>> name = client.project_path('[PROJECT]')\n            >>>\n            >>> # TODO: Initialize `query`:\n            >>> query = ''\n            >>>\n            >>> # TODO: Initialize `page_size`:\n            >>> page_size = 0\n            >>>\n            >>> response = client.complete_query(name, query, page_size)\n\n        Args:\n            name (str): Required.\n\n                Resource name of project the completion is performed within.\n\n                The format is \"projects/{project\\_id}\", for example,\n                \"projects/api-test-project\".\n            query (str): Required.\n\n                The query used to generate suggestions.\n\n                The maximum number of allowed characters is 255.\n            page_size (int): Required.\n\n                Completion result count.\n\n                The maximum allowed page size is 10.\n            language_codes (list[str]): Optional.\n\n                The list of languages of the query. This is the BCP-47 language code,\n                such as \"en-US\" or \"sr-Latn\". For more information, see `Tags for\n                Identifying Languages <https://tools.ietf.org/html/bcp47>`__.\n\n                For ``CompletionType.JOB_TITLE`` type, only open jobs with the same\n                ``language_codes`` are returned.\n\n                For ``CompletionType.COMPANY_NAME`` type, only companies having open\n                jobs with the same ``language_codes`` are returned.\n\n                For ``CompletionType.COMBINED`` type, only open jobs with the same\n                ``language_codes`` or companies having open jobs with the same\n                ``language_codes`` are returned.\n\n                The maximum number of allowed characters is 255.\n            company_name (str): Optional.\n\n                If provided, restricts completion to specified company.\n\n                The format is \"projects/{project\\_id}/companies/{company\\_id}\", for\n                example, \"projects/api-test-project/companies/foo\".\n            scope (~google.cloud.talent_v4beta1.types.CompletionScope): Optional.\n\n                The scope of the completion. The defaults is ``CompletionScope.PUBLIC``.\n            type_ (~google.cloud.talent_v4beta1.types.CompletionType): Optional.\n\n                The completion topic. The default is ``CompletionType.COMBINED``.\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.talent_v4beta1.types.CompleteQueryResponse` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def _get_stddev_deep_soil(self, mag, imt):\n        if mag > 7:\n            mag = 7\n        C = self.COEFFS_SOIL[imt]\n        return C['sigma0'] + C['magfactor'] * mag",
    "docstring": "Calculate and return total standard deviation for deep soil sites.\n\n        Implements formulae from the last column of table 4."
  },
  {
    "code": "def device_status(self):\n        return {\n            'active': self.device['active'],\n            'offline': self.device['offline'],\n            'last_update': self.last_update,\n            'battery_level': self.battery_level,\n        }",
    "docstring": "Status of device."
  },
  {
    "code": "def _add_data(self, plotter_cls, *args, **kwargs):\n        return plotter_cls(self._da, *args, **kwargs)",
    "docstring": "Visualize this data array\n\n        Parameters\n        ----------\n        %(Plotter.parameters.no_data)s\n\n        Returns\n        -------\n        psyplot.plotter.Plotter\n            The plotter that visualizes the data"
  },
  {
    "code": "def easybake(css_in, html_in=sys.stdin, html_out=sys.stdout, last_step=None,\n             coverage_file=None, use_repeatable_ids=False):\n    html_doc = etree.parse(html_in)\n    oven = Oven(css_in, use_repeatable_ids)\n    oven.bake(html_doc, last_step)\n    print(etree.tostring(html_doc, method=\"xml\").decode('utf-8'),\n          file=html_out)\n    if coverage_file:\n        print('SF:{}'.format(css_in.name), file=coverage_file)\n        print(oven.get_coverage_report(), file=coverage_file)\n        print('end_of_record', file=coverage_file)",
    "docstring": "Process the given HTML file stream with the css stream."
  },
  {
    "code": "def write(self, session, directory, name, replaceParamFile=None, **kwargs):\n        if self.raster is not None or self.rasterText is not None:\n            super(RasterMapFile, self).write(session, directory, name, replaceParamFile, **kwargs)",
    "docstring": "Wrapper for GsshaPyFileObjectBase write method"
  },
  {
    "code": "def _authenticate(self):\n        opts = {'domain': self._domain}\n        opts.update(self._auth)\n        response = self._api.domain.info(opts)\n        self._validate_response(\n            response=response, message='Failed to authenticate')\n        self.domain_id = 1\n        return True",
    "docstring": "run any request against the API just to make sure the credentials\n        are valid\n\n        :return bool: success status\n        :raises Exception: on error"
  },
  {
    "code": "def unhook_symbol(self, symbol_name):\n        sym = self.loader.find_symbol(symbol_name)\n        if sym is None:\n            l.warning(\"Could not find symbol %s\", symbol_name)\n            return False\n        if sym.owner is self.loader._extern_object:\n            l.warning(\"Refusing to unhook external symbol %s, replace it with another hook if you want to change it\",\n                      symbol_name)\n            return False\n        hook_addr, _ = self.simos.prepare_function_symbol(symbol_name, basic_addr=sym.rebased_addr)\n        self.unhook(hook_addr)\n        return True",
    "docstring": "Remove the hook on a symbol.\n        This function will fail if the symbol is provided by the extern object, as that would result in a state where\n        analysis would be unable to cope with a call to this symbol."
  },
  {
    "code": "def delete(self, json=None):\n        return self._call('delete', url=self.endpoint, json=json)",
    "docstring": "Send a DELETE request and return the JSON decoded result.\n\n        Args:\n            json (dict, optional): Object to encode and send in request.\n\n        Returns:\n            mixed: JSON decoded response data."
  },
  {
    "code": "def fill_altgoids(go2obj):\n    alt2obj = {altgo:goobj for goobj in go2obj.values() for altgo in goobj.alt_ids}\n    for goid, goobj in alt2obj.items():\n        go2obj[goid] = goobj",
    "docstring": "Given a go2obj containing key GO IDs, fill with all alternate GO IDs."
  },
  {
    "code": "def additional_cleanup(self):\n        cmd.remove('not alt \"\"+A')\n        cmd.hide('labels', 'Interactions')\n        cmd.disable('%sCartoon' % self.protname)\n        cmd.hide('everything', 'hydrogens')",
    "docstring": "Cleanup of various representations"
  },
  {
    "code": "def getHidden(self):\n        if self.getHiddenManually():\n            return self.getField('Hidden').get(self)\n        request = self.getRequest()\n        if request:\n            service_uid = self.getServiceUID()\n            ar_settings = request.getAnalysisServiceSettings(service_uid)\n            return ar_settings.get('hidden', False)\n        return False",
    "docstring": "Returns whether if the analysis must be displayed in results\n        reports or not, as well as in analyses view when the user logged in\n        is a Client Contact.\n\n        If the value for the field HiddenManually is set to False, this function\n        will delegate the action to the method getAnalysisServiceSettings() from\n        the Analysis Request.\n\n        If the value for the field HiddenManually is set to True, this function\n        will return the value of the field Hidden.\n        :return: true or false\n        :rtype: bool"
  },
  {
    "code": "def asrgb(self, *args, **kwargs):\n        if self._keyframe is None:\n            raise RuntimeError('keyframe not set')\n        kwargs['validate'] = False\n        return TiffPage.asrgb(self, *args, **kwargs)",
    "docstring": "Read image data from file and return RGB image as numpy array."
  },
  {
    "code": "def _new_list(self, size, name):\n        self._message_stack.append(ListTemplate(size, name, self._current_container))",
    "docstring": "Defines a new list to template of `size` and with `name`.\n\n        List type must be given after this keyword by defining one field. Then\n        the list definition has to be closed using `End List`.\n\n        Special value '*' in size means that list will decode values as long as\n        data is available. This free length value is not supported on encoding.\n\n        Examples:\n        | New list | 5 | myIntList |\n        | u16 |\n        | End List |\n\n        | u8 | listLength |\n        | New list | listLength | myIntList |\n        | u16 |\n        | End List |\n\n        | New list | * | myIntList |\n        | u16 |\n        | End List |"
  },
  {
    "code": "def get_sections_2dnt(self, sec2d_go):\n        return [(nm, self.get_ntgos_sorted(gos)) for nm, gos in sec2d_go]",
    "docstring": "Return a sections list containing sorted lists of namedtuples."
  },
  {
    "code": "def get_instance(self, payload):\n        return YearlyInstance(self._version, payload, account_sid=self._solution['account_sid'], )",
    "docstring": "Build an instance of YearlyInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.api.v2010.account.usage.record.yearly.YearlyInstance\n        :rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyInstance"
  },
  {
    "code": "def switch(self, gen_mode:bool=None):\n        \"Switch the model, if `gen_mode` is provided, in the desired mode.\"\n        self.gen_mode = (not self.gen_mode) if gen_mode is None else gen_mode\n        self.opt.opt = self.opt_gen.opt if self.gen_mode else self.opt_critic.opt\n        self._set_trainable()\n        self.model.switch(gen_mode)\n        self.loss_func.switch(gen_mode)",
    "docstring": "Switch the model, if `gen_mode` is provided, in the desired mode."
  },
  {
    "code": "def is_pg_at_least_nine_two(self):\n        if self._is_pg_at_least_nine_two is None:\n            results = self.version()\n            regex = re.compile(\"PostgreSQL (\\d+\\.\\d+\\.\\d+) on\")\n            matches = regex.match(results[0].version)\n            version = matches.groups()[0]\n            if version > '9.2.0':\n                self._is_pg_at_least_nine_two = True\n            else:\n                self._is_pg_at_least_nine_two = False\n        return self._is_pg_at_least_nine_two",
    "docstring": "Some queries have different syntax depending what version of postgres\n        we are querying against.\n\n        :returns: boolean"
  },
  {
    "code": "def statistics(self):\n        try:\n            return self._local.statistics\n        except AttributeError:\n            self._local.statistics = {}\n            return self._local.statistics",
    "docstring": "Return a dictionary of runtime statistics.\n\n        This dictionary will be empty when the controller has never been\n        ran. When it is running or has ran previously it should have (but\n        may not) have useful and/or informational keys and values when\n        running is underway and/or completed.\n\n        .. warning:: The keys in this dictionary **should** be some what\n                     stable (not changing), but there existence **may**\n                     change between major releases as new statistics are\n                     gathered or removed so before accessing keys ensure that\n                     they actually exist and handle when they do not.\n\n        .. note:: The values in this dictionary are local to the thread\n                  running call (so if multiple threads share the same retrying\n                  object - either directly or indirectly) they will each have\n                  there own view of statistics they have collected (in the\n                  future we may provide a way to aggregate the various\n                  statistics from each thread)."
  },
  {
    "code": "def _load_cwr_defaults(self):\n        if self._cwr_defaults is None:\n            self._cwr_defaults = self._reader.read_yaml_file(\n                self._file_defaults)\n        return self._cwr_defaults",
    "docstring": "Loads the CWR default values file, creating a matrix from it, and then\n        returns this data.\n\n        The file will only be loaded once.\n\n        :return: the CWR default values matrix"
  },
  {
    "code": "def initialize(self, configfile=None):\n        method = \"initialize\"\n        A = None\n        metadata = {method: configfile}\n        send_array(self.socket, A, metadata)\n        A, metadata = recv_array(\n            self.socket, poll=self.poll, poll_timeout=self.poll_timeout,\n            flags=self.zmq_flags)",
    "docstring": "Initialize the module"
  },
  {
    "code": "def write_block_data(self, cmd, block):\n        self.bus.write_i2c_block_data(self.address, cmd, block)\n        self.log.debug(\n            \"write_block_data: Wrote [%s] to command register 0x%02X\" % (\n                ', '.join(['0x%02X' % x for x in block]),\n                cmd\n            )\n        )",
    "docstring": "Writes a block of bytes to the bus using I2C format to the specified\n        command register"
  },
  {
    "code": "async def terminate(self) -> None:\n        await asyncio.sleep(config.shutdown_wait)\n        if not is_connected():\n            stop_server(self.application.server)\n            self.application.loop.stop()",
    "docstring": "Terminate server if no more connection exists."
  },
  {
    "code": "def copy_rec(source, dest):\n    if os.path.isdir(source):\n        for child in os.listdir(source):\n            new_dest = os.path.join(dest, child)\n            os.makedirs(new_dest, exist_ok=True)\n            copy_rec(os.path.join(source, child), new_dest)\n    elif os.path.isfile(source):\n        logging.info(' Copy \"{}\" to \"{}\"'.format(source, dest))\n        shutil.copy(source, dest)\n    else:\n        logging.info(' Ignoring \"{}\"'.format(source))",
    "docstring": "Copy files between diferent directories.\n\n    Copy one or more files to an existing directory. This function is\n    recursive, if the source is a directory, all its subdirectories are created\n    in the destination. Existing files in destination are overwrited without\n    any warning.\n\n    Args:\n        source (str): File or directory name.\n        dest (str): Directory name.\n\n    Raises:\n        FileNotFoundError: Destination directory doesn't exist."
  },
  {
    "code": "def connect_db(Repo, database=\":memory:\"):\n        Repo.db = sqlite3.connect(database,\n                                  detect_types=sqlite3.PARSE_DECLTYPES)\n        return Repo.db",
    "docstring": "Connect Repo to a database with path +database+ so all instances can\n        interact with the database."
  },
  {
    "code": "def reading_order(e1, e2):\n    b1 = e1.bbox\n    b2 = e2.bbox\n    if round(b1[y0]) == round(b2[y0]) or round(b1[y1]) == round(b2[y1]):\n        return float_cmp(b1[x0], b2[x0])\n    return float_cmp(b1[y0], b2[y0])",
    "docstring": "A comparator to sort bboxes from top to bottom, left to right"
  },
  {
    "code": "def update(self, data):\n        if data is None:\n            return\n        for key, value in sorted(data.items()):\n            if key.startswith('/'):\n                name = key.lstrip('/')\n                match = re.search(\"([^/]+)(/.*)\", name)\n                if match:\n                    name = match.groups()[0]\n                    value = {match.groups()[1]: value}\n                self.child(name, value)\n            else:\n                self.data[key] = value\n        log.debug(\"Data for '{0}' updated.\".format(self))\n        log.data(pretty(self.data))",
    "docstring": "Update metadata, handle virtual hierarchy"
  },
  {
    "code": "def maybe_get_fig_ax(*args, **kwargs):\n    if 'ax' in kwargs:\n        ax = kwargs.pop('ax')\n        if 'fig' in kwargs:\n            fig = kwargs.pop('fig')\n        else:\n            fig = plt.gcf()\n    elif len(args) == 0:\n        fig = plt.gcf()\n        ax = plt.gca()\n    elif isinstance(args[0], mpl.figure.Figure) and \\\n            isinstance(args[1], mpl.axes.Axes):\n        fig = args[0]\n        ax = args[1]\n        args = args[2:]\n    else:\n        fig, ax = plt.subplots(1)\n    return fig, ax, args, dict(kwargs)",
    "docstring": "It used to be that the first argument of prettyplotlib had to be the 'ax'\n    object, but that's not the case anymore. This is specially made for\n    pcolormesh.\n\n    @param args:\n    @type args:\n    @param kwargs:\n    @type kwargs:\n    @return:\n    @rtype:"
  },
  {
    "code": "def add_sched_block_instance(self, config_dict):\n        schema = self._get_schema()\n        LOG.debug('Adding SBI with config: %s', config_dict)\n        validate(config_dict, schema)\n        updated_block = self._add_status(config_dict)\n        scheduling_block_data, processing_block_data = \\\n            self._split_sched_block_instance(updated_block)\n        name = \"scheduling_block:\" + updated_block[\"id\"]\n        self._db.set_specified_values(name, scheduling_block_data)\n        self._db.push_event(self.scheduling_event_name,\n                            updated_block[\"status\"],\n                            updated_block[\"id\"])\n        for value in processing_block_data:\n            name = (\"scheduling_block:\" + updated_block[\"id\"] +\n                    \":processing_block:\" + value['id'])\n            self._db.set_specified_values(name, value)\n            self._db.push_event(self.processing_event_name,\n                                value[\"status\"],\n                                value[\"id\"])",
    "docstring": "Add Scheduling Block to the database.\n\n        Args:\n            config_dict (dict): SBI configuration"
  },
  {
    "code": "def lookup_cc_partner(nu_pid):\n    neutrino_type = math.fabs(nu_pid)\n    assert neutrino_type in [12, 14, 16]\n    cc_partner = neutrino_type - 1\n    cc_partner = math.copysign(\n        cc_partner, nu_pid)\n    cc_partner = int(cc_partner)\n    return cc_partner",
    "docstring": "Lookup the charge current partner\n\n    Takes as an input neutrino nu_pid is a PDG code, then returns\n    the charged lepton partner.  So 12 (nu_e) returns 11.  Keeps sign"
  },
  {
    "code": "def instructions(self):\n        if self._instructions is None:\n            if self.statements is None:\n                self._instructions = 0\n            else:\n                self._instructions = len([s for s in self.statements if type(s) is stmt.IMark])\n        return self._instructions",
    "docstring": "The number of instructions in this block"
  },
  {
    "code": "def convert_time_stamp_to_date(content):\n    start_time_stamp = content.get('startTime')\n    end_time_stamp = content.get('endTime')\n    if start_time_stamp:\n        start_time = datetime.datetime.utcfromtimestamp(start_time_stamp // 1000).strftime(\"%Y/%m/%d %H:%M:%S\")\n        content['startTime'] = str(start_time)\n    if end_time_stamp:\n        end_time = datetime.datetime.utcfromtimestamp(end_time_stamp // 1000).strftime(\"%Y/%m/%d %H:%M:%S\")\n        content['endTime'] = str(end_time)\n    return content",
    "docstring": "Convert time stamp to date time format"
  },
  {
    "code": "def exit_full_screen(self):\n        self.tk.attributes(\"-fullscreen\", False)\n        self._full_screen = False\n        self.events.remove_event(\"<FullScreen.Escape>\")",
    "docstring": "Change from full screen to windowed mode and remove key binding"
  },
  {
    "code": "def OnItemSelected(self, event):\n        value = event.m_itemIndex\n        self.startIndex = value\n        self.switching = True\n        post_command_event(self, self.GridActionTableSwitchMsg, newtable=value)\n        self.switching = False\n        event.Skip()",
    "docstring": "Item selection event handler"
  },
  {
    "code": "def reduce(x, op='sum'):\n    import warnings\n    warnings.warn(\n        \"Deprecated API. Use ``sum`` or ``mean`` instead.\", DeprecationWarning)\n    from .function_bases import reduce_sum, reduce_mean\n    if op == 'sum':\n        return reduce_sum(x)\n    elif op == 'mean':\n        return reduce_mean(x)\n    raise ValueError()",
    "docstring": "Reduction function with given operation.\n\n    Args:\n        x (Variable): An input.\n        op (str): 'sum' or 'mean'.\n\n    Note:\n        This is deprecated. Use ``mean`` or ``sum`` instead."
  },
  {
    "code": "def unset_role(username, role, **kwargs):\n    role_line = 'no username {0} role {1}'.format(username, role)\n    return config(role_line, **kwargs)",
    "docstring": "Remove role from username.\n\n    username\n        Username for role removal\n\n    role\n        Role to remove\n\n    no_save_config\n        If True, don't save configuration commands to startup configuration.\n        If False, save configuration to startup configuration.\n        Default: False\n\n    .. code-block:: bash\n\n        salt '*' nxos.cmd unset_role username=daniel role=vdc-admin"
  },
  {
    "code": "def get_version(root):\n    version_json = os.path.join(root, 'version.json')\n    if os.path.exists(version_json):\n        with open(version_json, 'r') as version_json_file:\n            return json.load(version_json_file)\n    return None",
    "docstring": "Load and return the contents of version.json.\n\n    :param root: The root path that the ``version.json`` file will be opened\n    :type root: str\n    :returns: Content of ``version.json`` or None\n    :rtype: dict or None"
  },
  {
    "code": "def in_labelset(xmrs, nodeids, label=None):\n    nodeids = set(nodeids)\n    if label is None:\n        label = xmrs.ep(next(iter(nodeids))).label\n    return nodeids.issubset(xmrs._vars[label]['refs']['LBL'])",
    "docstring": "Test if all nodeids share a label.\n\n    Args:\n        nodeids: iterable of nodeids\n        label (str, optional): the label that all nodeids must share\n    Returns:\n        bool: `True` if all nodeids share a label, otherwise `False`"
  },
  {
    "code": "def _insert(self, namespace, stream, events, configuration):\n    index = self.index_manager.get_index(namespace)\n    start_dts_to_add = set()\n    def actions():\n      for _id, event in events:\n        dt = kronos_time_to_datetime(uuid_to_kronos_time(_id))\n        start_dts_to_add.add(_round_datetime_down(dt))\n        event['_index'] = index\n        event['_type'] = stream\n        event[LOGSTASH_TIMESTAMP_FIELD] = dt.isoformat()\n        yield event\n    list(es_helpers.streaming_bulk(self.es, actions(), chunk_size=1000,\n                                   refresh=self.force_refresh))\n    self.index_manager.add_aliases(namespace,\n                                   index,\n                                   start_dts_to_add)",
    "docstring": "`namespace` acts as db for different streams\n    `stream` is the name of a stream and `events` is a list of events to\n    insert."
  },
  {
    "code": "def _Open(self, path_spec=None, mode='rb'):\n    if not self._file_object_set_in_init and not path_spec:\n      raise ValueError('Missing path specification.')\n    if not self._file_object_set_in_init:\n      if not path_spec.HasParent():\n        raise errors.PathSpecError(\n            'Unsupported path specification without parent.')\n      self._encryption_method = getattr(path_spec, 'encryption_method', None)\n      if self._encryption_method is None:\n        raise errors.PathSpecError(\n            'Path specification missing encryption method.')\n      self._file_object = resolver.Resolver.OpenFileObject(\n          path_spec.parent, resolver_context=self._resolver_context)\n    self._path_spec = path_spec",
    "docstring": "Opens the file-like object.\n\n    Args:\n      path_spec (Optional[PathSpec]): path specification.\n      mode (Optional[str]): file access mode.\n\n    Raises:\n      AccessError: if the access to open the file was denied.\n      IOError: if the file-like object could not be opened.\n      OSError: if the file-like object could not be opened.\n      PathSpecError: if the path specification is incorrect.\n      ValueError: if the path specification is invalid."
  },
  {
    "code": "def _get_ericscript_path(self):\n        es = utils.which(os.path.join(utils.get_bcbio_bin(), self.EXECUTABLE))\n        return os.path.dirname(os.path.realpath(es))",
    "docstring": "Retrieve PATH to the isolated eriscript anaconda environment."
  },
  {
    "code": "async def findArtifactFromTask(self, *args, **kwargs):\n        return await self._makeApiCall(self.funcinfo[\"findArtifactFromTask\"], *args, **kwargs)",
    "docstring": "Get Artifact From Indexed Task\n\n        Find a task by index path and redirect to the artifact on the most recent\n        run with the given `name`.\n\n        Note that multiple calls to this endpoint may return artifacts from differen tasks\n        if a new task is inserted into the index between calls. Avoid using this method as\n        a stable link to multiple, connected files if the index path does not contain a\n        unique identifier.  For example, the following two links may return unrelated files:\n        * https://tc.example.com/api/index/v1/task/some-app.win64.latest.installer/artifacts/public/installer.exe`\n        * https://tc.example.com/api/index/v1/task/some-app.win64.latest.installer/artifacts/public/debug-symbols.zip`\n\n        This problem be remedied by including the revision in the index path or by bundling both\n        installer and debug symbols into a single artifact.\n\n        If no task exists for the given index path, this API end-point responds with 404.\n\n        This method is ``stable``"
  },
  {
    "code": "def genetic(problem, population_size=100, mutation_chance=0.1,\n            iterations_limit=0, viewer=None):\n    return _local_search(problem,\n                         _create_genetic_expander(problem, mutation_chance),\n                         iterations_limit=iterations_limit,\n                         fringe_size=population_size,\n                         random_initial_states=True,\n                         stop_when_no_better=iterations_limit==0,\n                         viewer=viewer)",
    "docstring": "Genetic search.\n\n    population_size specifies the size of the population (ORLY).\n    mutation_chance specifies the probability of a mutation on a child,\n    varying from 0 to 1.\n    If iterations_limit is specified, the algorithm will end after that\n    number of iterations. Else, it will continue until it can't find a\n    better node than the current one.\n    Requires: SearchProblem.generate_random_state, SearchProblem.crossover,\n    SearchProblem.mutate and SearchProblem.value."
  },
  {
    "code": "def peak_generation(self):\n        if self._peak_generation is None:\n            self._peak_generation = sum(\n                [gen.nominal_capacity\n                 for gen in self.generators])\n        return self._peak_generation",
    "docstring": "Cumulative peak generation capacity of generators of this grid\n\n        Returns\n        -------\n        float\n            Ad-hoc calculated or cached peak generation capacity"
  },
  {
    "code": "def prepend_note(self, player, text):\n        note = self._find_note(player)\n        note.text = text + note.text",
    "docstring": "Prepend text to an already existing note."
  },
  {
    "code": "def get_service(self, factory, svc_registration):\n        svc_ref = svc_registration.get_reference()\n        if svc_ref.is_prototype():\n            return self._get_from_prototype(factory, svc_registration)\n        return self._get_from_factory(factory, svc_registration)",
    "docstring": "Returns the service required by the bundle. The Service Factory is\n        called only when necessary while the Prototype Service Factory is\n        called each time\n\n        :param factory: The service factory\n        :param svc_registration: The ServiceRegistration object\n        :return: The requested service instance (created if necessary)"
  },
  {
    "code": "def load_transcript_fpkm_dict_from_gtf(\n        gtf_path,\n        transcript_id_column_name=\"reference_id\",\n        fpkm_column_name=\"FPKM\",\n        feature_column_name=\"feature\"):\n    df = gtfparse.read_gtf(\n        gtf_path,\n        column_converters={fpkm_column_name: float})\n    transcript_ids = _get_gtf_column(transcript_id_column_name, gtf_path, df)\n    fpkm_values = _get_gtf_column(fpkm_column_name, gtf_path, df)\n    features = _get_gtf_column(feature_column_name, gtf_path, df)\n    logging.info(\"Loaded %d rows from %s\" % (len(transcript_ids), gtf_path))\n    logging.info(\"Found %s transcript entries\" % sum(\n        feature == \"transcript\" for feature in features))\n    result = {\n        transcript_id: float(fpkm)\n        for (transcript_id, fpkm, feature)\n        in zip(transcript_ids, fpkm_values, features)\n        if (\n            (transcript_id is not None) and\n            (len(transcript_id) > 0) and\n            (feature == \"transcript\")\n        )\n    }\n    logging.info(\"Keeping %d transcript rows with reference IDs\" % (\n        len(result),))\n    return result",
    "docstring": "Load a GTF file generated by StringTie which contains transcript-level\n    quantification of abundance. Returns a dictionary mapping Ensembl\n    IDs of transcripts to FPKM values."
  },
  {
    "code": "def _is_gs_folder(cls, result):\n        return (cls.is_key(result) and\n                result.size == 0 and\n                result.name.endswith(cls._gs_folder_suffix))",
    "docstring": "Return ``True`` if GS standalone folder object.\n\n        GS will create a 0 byte ``<FOLDER NAME>_$folder$`` key as a\n        pseudo-directory place holder if there are no files present."
  },
  {
    "code": "def with_class(self, cls):\n        rcls = []\n        for key, value in self._classification.items():\n            if value[0] == cls:\n                rcls.append(key)\n        return rcls",
    "docstring": "Return functions with the class"
  },
  {
    "code": "def search(self, user, since, until, target_type, action_name):\n        if not self.user:\n            self.user = self.get_user(user)\n        if not self.events:\n            self.events = self.user_events(self.user['id'], since, until)\n        result = []\n        for event in self.events:\n            created_at = dateutil.parser.parse(event['created_at']).date()\n            if (event['target_type'] == target_type and\n                    event['action_name'] == action_name and\n                    since.date <= created_at and until.date >= created_at):\n                result.append(event)\n        log.debug(\"Result: {0} fetched\".format(listed(len(result), \"item\")))\n        return result",
    "docstring": "Perform GitLab query"
  },
  {
    "code": "def check_resource(resource):\n    linkchecker_type = resource.extras.get('check:checker')\n    LinkChecker = get_linkchecker(linkchecker_type)\n    if not LinkChecker:\n        return {'error': 'No linkchecker configured.'}, 503\n    if is_ignored(resource):\n        return dummy_check_response()\n    result = LinkChecker().check(resource)\n    if not result:\n        return {'error': 'No response from linkchecker'}, 503\n    elif result.get('check:error'):\n        return {'error': result['check:error']}, 500\n    elif not result.get('check:status'):\n        return {'error': 'No status in response from linkchecker'}, 503\n    previous_status = resource.extras.get('check:available')\n    check_keys = _get_check_keys(result, resource, previous_status)\n    resource.extras.update(check_keys)\n    resource.save(signal_kwargs={'ignores': ['post_save']})\n    return result",
    "docstring": "Check a resource availability against a linkchecker backend\n\n    The linkchecker used can be configured on a resource basis by setting\n    the `resource.extras['check:checker']` attribute with a key that points\n    to a valid `udata.linkcheckers` entrypoint. If not set, it will\n    fallback on the default linkchecker defined by the configuration variable\n    `LINKCHECKING_DEFAULT_LINKCHECKER`.\n\n    Returns\n    -------\n    dict or (dict, int)\n        Check results dict and status code (if error)."
  },
  {
    "code": "def putcolslice(self, columnname, value, blc, trc, inc=[],\n                    startrow=0, nrow=-1, rowincr=1):\n        self._putcolslice(columnname, value, blc, trc, inc,\n                          startrow, nrow, rowincr)",
    "docstring": "Put into a slice in a table column holding arrays.\n\n        Its arguments are the same as for getcolslice and putcellslice."
  },
  {
    "code": "def get(self, uid):\n        r = requests.get(self.apiurl + \"/users/{}\".format(uid), headers=self.header)\n        if r.status_code != 200:\n            raise ServerError\n        jsd = r.json()\n        if jsd['data']:\n            return jsd['data']\n        else:\n            return None",
    "docstring": "Get a user's information by their id.\n\n        :param uid str: User ID\n        :return: The user's information or None\n        :rtype: Dictionary or None"
  },
  {
    "code": "def handle_cluster_request(self, tsn, command_id, args):\n        if command_id == 0:\n            if self._timer_handle:\n                self._timer_handle.cancel()\n            loop = asyncio.get_event_loop()\n            self._timer_handle = loop.call_later(30, self._turn_off)",
    "docstring": "Handle the cluster command."
  },
  {
    "code": "def _norm_cmap(values, cmap, normalize, cm, vmin=None, vmax=None):\n    mn = min(values) if vmin is None else vmin\n    mx = max(values) if vmax is None else vmax\n    norm = normalize(vmin=mn, vmax=mx)\n    n_cmap = cm.ScalarMappable(norm=norm, cmap=cmap)\n    return n_cmap",
    "docstring": "Normalize and set colormap. Taken from geopandas@0.2.1 codebase, removed in geopandas@0.3.0."
  },
  {
    "code": "def pipe_uniq(context=None, _INPUT=None, conf=None, **kwargs):\n    funcs = get_splits(None, conf, **cdicts(opts, kwargs))\n    pieces, _pass = funcs[0](), funcs[2]()\n    _OUTPUT = _INPUT if _pass else unique_items(_INPUT, pieces.field)\n    return _OUTPUT",
    "docstring": "An operator that filters out non unique items according to the specified\n    field. Not loopable.\n\n    Parameters\n    ----------\n    context : pipe2py.Context object\n    _INPUT : pipe2py.modules pipe like object (iterable of items)\n    kwargs -- other inputs, e.g. to feed terminals for rule values\n    conf : {'field': {'type': 'text', 'value': <field to be unique>}}\n\n    Returns\n    -------\n    _OUTPUT : generator of unique items"
  },
  {
    "code": "def category(self, category):\n        self.url.category = category\n        self.url.set_page(1)\n        return self",
    "docstring": "Change category of current search and return self"
  },
  {
    "code": "def assemble_concatenated_meta(concated_meta_dfs, remove_all_metadata_fields):\n    if remove_all_metadata_fields:\n        for df in concated_meta_dfs:\n            df.drop(df.columns, axis=1, inplace=True)\n    all_concated_meta_df = pd.concat(concated_meta_dfs, axis=0)\n    n_rows = all_concated_meta_df.shape[0]\n    logger.debug(\"all_concated_meta_df.shape[0]: {}\".format(n_rows))\n    n_rows_cumulative = sum([df.shape[0] for df in concated_meta_dfs])\n    assert n_rows == n_rows_cumulative\n    all_concated_meta_df_sorted = all_concated_meta_df.sort_index(axis=0).sort_index(axis=1)\n    return all_concated_meta_df_sorted",
    "docstring": "Assemble the concatenated metadata dfs together. For example,\n    if horizontally concatenating, the concatenated metadata dfs are the\n    column metadata dfs. Both indices are sorted.\n\n    Args:\n        concated_meta_dfs (list of pandas dfs)\n\n    Returns:\n        all_concated_meta_df_sorted (pandas df)"
  },
  {
    "code": "def _pwr_optfcn(df, loc):\n    I = _lambertw_i_from_v(df['r_sh'], df['r_s'],\n                           df['nNsVth'], df[loc], df['i_0'], df['i_l'])\n    return I * df[loc]",
    "docstring": "Function to find power from ``i_from_v``."
  },
  {
    "code": "def channels(self):\n        return types.MappingProxyType({\n            ch.name: ch for ch in self._refs.values()\n            if not ch.is_pattern})",
    "docstring": "Read-only channels dict."
  },
  {
    "code": "def get_all_patches(self, dont_use_cache=False):\n        if not dont_use_cache and self._all_patches_cache is not None:\n            return self._all_patches_cache\n        print(\n            'Computing full change list (since you specified a percentage)...'\n        ),\n        sys.stdout.flush()\n        endless_query = self.clone()\n        endless_query.start_position = endless_query.end_position = None\n        self._all_patches_cache = list(endless_query.generate_patches())\n        return self._all_patches_cache",
    "docstring": "Computes a list of all patches matching this query, though ignoreing\n        self.start_position and self.end_position.\n\n        @param dont_use_cache   If False, and get_all_patches has been called\n                                before, compute the list computed last time."
  },
  {
    "code": "def send_task(self, request, response):\n        from bettercache.tasks import GeneratePage\n        try:\n            GeneratePage.apply_async((strip_wsgi(request),))\n        except:\n            logger.error(\"failed to send celery task\")\n        self.set_cache(request, response)",
    "docstring": "send off a celery task for the current page and recache"
  },
  {
    "code": "def out(*output, **kwargs):\n    output = ' '.join([str(o) for o in output])\n    if kwargs.get('wrap') is not False:\n        output = '\\n'.join(wrap(output, kwargs.get('indent', '')))\n    elif kwargs.get('indent'):\n        indent = kwargs['indent']\n        output = indent + ('\\n' + indent).join(output.splitlines())\n    sys.stdout.write(output + '\\n')",
    "docstring": "Writes output to stdout.\n\n    :arg wrap: If you set ``wrap=False``, then ``out`` won't textwrap\n        the output."
  },
  {
    "code": "def default_subsystem_for_plugin(plugin_type):\n  if not issubclass(plugin_type, CheckstylePlugin):\n    raise ValueError('Can only create a default plugin subsystem for subclasses of {}, given: {}'\n                     .format(CheckstylePlugin, plugin_type))\n  return type(str('{}Subsystem'.format(plugin_type.__name__)),\n              (PluginSubsystemBase,),\n              {\n                str('options_scope'): 'pycheck-{}'.format(plugin_type.name()),\n                str('plugin_type'): classmethod(lambda cls: plugin_type),\n                str('register_plugin_options'): classmethod(lambda cls, register: None),\n              })",
    "docstring": "Create a singleton PluginSubsystemBase subclass for the given plugin type.\n\n  The singleton enforcement is useful in cases where dependent Tasks are installed multiple times,\n  to avoid creating duplicate types which would have option scope collisions.\n\n  :param plugin_type: A CheckstylePlugin subclass.\n  :type: :class:`pants.contrib.python.checks.checker.common.CheckstylePlugin`\n  :rtype: :class:`pants.contrib.python.checks.tasks.checkstyle.plugin_subsystem_base.PluginSubsystemBase`"
  },
  {
    "code": "def schedule_messages(messages, recipients=None, sender=None, priority=None):\n    if not is_iterable(messages):\n        messages = (messages,)\n    results = []\n    for message in messages:\n        if isinstance(message, six.string_types):\n            message = PlainTextMessage(message)\n        resulting_priority = message.priority\n        if priority is not None:\n            resulting_priority = priority\n        results.append(message.schedule(sender=sender, recipients=recipients, priority=resulting_priority))\n    return results",
    "docstring": "Schedules a message or messages.\n\n    :param MessageBase|str|list messages: str or MessageBase heir or list - use str to create PlainTextMessage.\n    :param list|None recipients: recipients addresses or Django User model heir instances\n        If `None` Dispatches should be created before send using `prepare_dispatches()`.\n    :param User|None sender: User model heir instance\n    :param int priority: number describing message priority. If set overrides priority provided with message type.\n    :return: list of tuples - (message_model, dispatches_models)\n    :rtype: list"
  },
  {
    "code": "def is_field_method(node):\n    name = node.attrname\n    parent = node.last_child()\n    inferred = safe_infer(parent)\n    if not inferred:\n        return False\n    for cls_name, inst in FIELD_TYPES.items():\n        if node_is_instance(inferred, cls_name) and hasattr(inst, name):\n            return True\n    return False",
    "docstring": "Checks if a call to a field instance method is valid. A call is\n    valid if the call is a method of the underlying type. So, in a StringField\n    the methods from str are valid, in a ListField the methods from list are\n    valid and so on..."
  },
  {
    "code": "def variableMissingValue(ncVar):\n    attributes = ncVarAttributes(ncVar)\n    if not attributes:\n        return None\n    for key in ('missing_value', 'MissingValue', 'missingValue', 'FillValue', '_FillValue'):\n        if key in attributes:\n            missingDataValue = attributes[key]\n            return missingDataValue\n    return None",
    "docstring": "Returns the missingData given a NetCDF variable\n\n        Looks for one of the following attributes: _FillValue, missing_value, MissingValue,\n        missingValue. Returns None if these attributes are not found."
  },
  {
    "code": "def storage(self):\n        annotation = get_portal_annotation()\n        if annotation.get(NUMBER_STORAGE) is None:\n            annotation[NUMBER_STORAGE]  = OIBTree()\n        return annotation[NUMBER_STORAGE]",
    "docstring": "get the counter storage"
  },
  {
    "code": "def __run_delta_py(self, delta):\n        self.__run_py_file(delta.get_file(), delta.get_name())\n        self.__update_upgrades_table(delta)",
    "docstring": "Execute the delta py file"
  },
  {
    "code": "def select_point(action, action_space, select_point_act, screen):\n  select = spatial(action, action_space).unit_selection_point\n  screen.assign_to(select.selection_screen_coord)\n  select.type = select_point_act",
    "docstring": "Select a unit at a point."
  },
  {
    "code": "def create_data(step: 'projects.ProjectStep') -> STEP_DATA:\n    return STEP_DATA(\n        name=step.definition.name,\n        status=step.status(),\n        has_error=False,\n        body=None,\n        data=dict(),\n        includes=[],\n        cauldron_version=list(environ.version_info),\n        file_writes=[]\n    )",
    "docstring": "Creates the data object that stores the step information in the notebook\n    results JavaScript file.\n\n    :param step:\n        Project step for which to create the data\n    :return:\n        Step data tuple containing scaffold data structure for the step output.\n        The dictionary must then be populated with data from the step to\n        correctly reflect the current state of the step.\n\n        This is essentially a \"blank\" step dictionary, which is what the step\n        would look like if it had not yet run"
  },
  {
    "code": "def image(self, data, cmap='cubehelix', clim='auto', fg_color=None):\n        self._configure_2d(fg_color)\n        image = scene.Image(data, cmap=cmap, clim=clim)\n        self.view.add(image)\n        self.view.camera.aspect = 1\n        self.view.camera.set_range()\n        return image",
    "docstring": "Show an image\n\n        Parameters\n        ----------\n        data : ndarray\n            Should have shape (N, M), (N, M, 3) or (N, M, 4).\n        cmap : str\n            Colormap name.\n        clim : str | tuple\n            Colormap limits. Should be ``'auto'`` or a two-element tuple of\n            min and max values.\n        fg_color : Color or None\n            Sets the plot foreground color if specified.\n\n        Returns\n        -------\n        image : instance of Image\n            The image.\n\n        Notes\n        -----\n        The colormap is only used if the image pixels are scalars."
  },
  {
    "code": "def draw_help(self, surf):\n    if not self._help:\n      return\n    def write(loc, text):\n      surf.write_screen(self._font_large, colors.black, loc, text)\n    surf.surf.fill(colors.white * 0.8)\n    write((1, 1), \"Shortcuts:\")\n    max_len = max(len(s) for s, _ in self.shortcuts)\n    for i, (hotkey, description) in enumerate(self.shortcuts, start=2):\n      write((2, i), hotkey)\n      write((3 + max_len * 0.7, i), description)",
    "docstring": "Draw the help dialog."
  },
  {
    "code": "def rename(self, container, name):\n        url = self._url(\"/containers/{0}/rename\", container)\n        params = {'name': name}\n        res = self._post(url, params=params)\n        self._raise_for_status(res)",
    "docstring": "Rename a container. Similar to the ``docker rename`` command.\n\n        Args:\n            container (str): ID of the container to rename\n            name (str): New name for the container\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def check_children(self):\n        if self._restart_processes is True:\n            for pid, mapping in six.iteritems(self._process_map):\n                if not mapping['Process'].is_alive():\n                    log.trace('Process restart of %s', pid)\n                    self.restart_process(pid)",
    "docstring": "Check the children once"
  },
  {
    "code": "def split(self, verbose=None, end_in_new_line=None):\n        elapsed_time = self.get_elapsed_time()\n        self.split_elapsed_time.append(elapsed_time)\n        self._cumulative_elapsed_time += elapsed_time\n        self._elapsed_time = datetime.timedelta()\n        if verbose is None:\n            verbose = self.verbose_end\n        if verbose:\n            if end_in_new_line is None:\n                end_in_new_line = self.end_in_new_line\n            if end_in_new_line:\n                self.log(\"{} done in {}\".format(self.description, elapsed_time))\n            else:\n                self.log(\" done in {}\".format(elapsed_time))\n        self._start_time = datetime.datetime.now()",
    "docstring": "Save the elapsed time of the current split and restart the stopwatch.\n\n        The current elapsed time will be appended to :attr:`split_elapsed_time`.\n        If the stopwatch is paused, then it will remain paused.\n        Otherwise, it will continue running.\n\n        Parameters\n        ----------\n        verbose : Optional[bool]\n            Wether to log. If `None`, use `verbose_end` set during initialization.\n        end_in_new_line : Optional[bool]]\n            Wether to log the `description`. If `None`, use `end_in_new_line` set during\n            initialization."
  },
  {
    "code": "def get_node(self, path):\n        with self._mutex:\n            if path[0] == self._name:\n                if len(path) == 1:\n                    return self\n                elif path[1] in self._children:\n                    return self._children[path[1]].get_node(path[1:])\n                else:\n                    return None\n            else:\n                return None",
    "docstring": "Get a child node of this node, or this node, based on a path.\n\n        @param path A list of path elements pointing to a node in the tree.\n                    For example, ['/', 'localhost', 'dir.host']. The first\n                    element in this path should be this node's name.\n        @return The node pointed to by @ref path, or None if the path does not\n                point to a node in the tree below this node.\n\n        Example:\n        >>> c1 = TreeNode(name='c1')\n        >>> c2 = TreeNode(name='c2')\n        >>> p = TreeNode(name='p', children={'c1':c1, 'c2':c2})\n        >>> c1._parent = p\n        >>> c2._parent = p\n        >>> p.get_node(['p', 'c1']) == c1\n        True\n        >>> p.get_node(['p', 'c2']) == c2\n        True"
  },
  {
    "code": "def rotate_root_iam_credentials(self, mount_point=DEFAULT_MOUNT_POINT):\n        api_path = '/v1/{mount_point}/config/rotate-root'.format(mount_point=mount_point)\n        response = self._adapter.post(\n            url=api_path,\n        )\n        return response.json()",
    "docstring": "Rotate static root IAM credentials.\n\n        When you have configured Vault with static credentials, you can use this endpoint to have Vault rotate the\n        access key it used. Note that, due to AWS eventual consistency, after calling this endpoint, subsequent calls\n        from Vault to AWS may fail for a few seconds until AWS becomes consistent again.\n\n        In order to call this endpoint, Vault's AWS access key MUST be the only access key on the IAM user; otherwise,\n        generation of a new access key will fail. Once this method is called, Vault will now be the only entity that\n        knows the AWS secret key is used to access AWS.\n\n        Supported methods:\n            POST: /{mount_point}/config/rotate-root. Produces: 200 application/json\n\n        :return: The JSON response of the request.\n        :rtype: dict"
  },
  {
    "code": "def validate(self, data=None):\n        errors = {}\n        data = self._getData(data)\n        for name, field in self.fields.items():\n            try:\n                field.clean(data.get(name))\n            except ValidationError, e:\n                errors[name] = e.messages\n            except AttributeError, e:\n                raise ValidationError('data should be of type dict but is %s' % (type(data),))\n        extras = set(data.keys()) - set(self.fields.keys())\n        if extras:\n            errors[', '.join(extras)] = ['field(s) not allowed']\n        if errors:\n            raise ValidationError(errors)",
    "docstring": "Validate the data\n\n        Check also that no extra properties are present.\n\n        :raises: ValidationError if the data is not valid."
  },
  {
    "code": "def init_static_field(state, field_class_name, field_name, field_type):\n        field_ref = SimSootValue_StaticFieldRef.get_ref(state, field_class_name,\n                                                        field_name, field_type)\n        field_val = SimSootValue_ThisRef.new_object(state, field_type)\n        state.memory.store(field_ref, field_val)",
    "docstring": "Initialize the static field with an allocated, but not initialized,\n        object of the given type.\n\n        :param state: State associated to the field.\n        :param field_class_name: Class containing the field.\n        :param field_name: Name of the field.\n        :param field_type: Type of the field and the new object."
  },
  {
    "code": "def remove_watcher(self, issue, watcher):\n        url = self._get_url('issue/' + str(issue) + '/watchers')\n        params = {'username': watcher}\n        result = self._session.delete(url, params=params)\n        return result",
    "docstring": "Remove a user from an issue's watch list.\n\n        :param issue: ID or key of the issue affected\n        :param watcher: username of the user to remove from the watchers list\n        :rtype: Response"
  },
  {
    "code": "def get_milestone(self, title):\n        if not title:\n            return GithubObject.NotSet\n        if not hasattr(self, '_milestones'):\n            self._milestones = {m.title: m for m in self.repo.get_milestones()}\n        milestone = self._milestones.get(title)\n        if not milestone:\n            milestone = self.repo.create_milestone(title=title)\n        return milestone",
    "docstring": "given the title as str, looks for an existing milestone or create a new one,\n        and return the object"
  },
  {
    "code": "def scale_degree_to_bitmap(scale_degree, modulo=False, length=BITMAP_LENGTH):\n    sign = 1\n    if scale_degree.startswith(\"*\"):\n        sign = -1\n        scale_degree = scale_degree.strip(\"*\")\n    edit_map = [0] * length\n    sd_idx = scale_degree_to_semitone(scale_degree)\n    if sd_idx < length or modulo:\n        edit_map[sd_idx % length] = sign\n    return np.array(edit_map)",
    "docstring": "Create a bitmap representation of a scale degree.\n\n    Note that values in the bitmap may be negative, indicating that the\n    semitone is to be removed.\n\n    Parameters\n    ----------\n    scale_degree : str\n        Spelling of a relative scale degree, e.g. 'b3', '7', '#5'\n    modulo : bool, default=True\n        If a scale degree exceeds the length of the bit-vector, modulo the\n        scale degree back into the bit-vector; otherwise it is discarded.\n    length : int, default=12\n        Length of the bit-vector to produce\n\n    Returns\n    -------\n    bitmap : np.ndarray, in [-1, 0, 1], len=`length`\n        Bitmap representation of this scale degree."
  },
  {
    "code": "def rename(self, old_task_name, new_task_name):\n        if not old_task_name or old_task_name.startswith('-'):\n            raise ValueError('Old task name is invalid')\n        if not new_task_name or new_task_name.startswith('-'):\n            raise ValueError('New new task name is invalid')\n        if old_task_name == new_task_name:\n            raise ValueError('Cannot rename task to itself')\n        try:\n            old_task_dir = self._get_task_dir(old_task_name)\n            if not self.exists(old_task_dir):\n                raise errors.TaskNotFound(old_task_name)\n            new_task_dir = self._get_task_dir(new_task_name)\n            if self.exists(new_task_dir):\n                raise errors.TaskExists(new_task_name)\n            os.rename(old_task_dir, new_task_dir)\n            return True\n        except OSError:\n            return False",
    "docstring": "Renames an existing task directory.\n\n            `old_task_name`\n                Current task name.\n            `new_task_name`\n                New task name.\n\n            Returns ``True`` if rename successful."
  },
  {
    "code": "def get(self, request, *args, **kwargs):\n        try:\n            context = self.get_context_data(**kwargs)\n        except exceptions.NotAvailable:\n            exceptions.handle(request)\n        self.set_workflow_step_errors(context)\n        return self.render_to_response(context)",
    "docstring": "Handler for HTTP GET requests."
  },
  {
    "code": "def refresh(path=None):\n    global GIT_OK\n    GIT_OK = False\n    if not Git.refresh(path=path):\n        return\n    if not FetchInfo.refresh():\n        return\n    GIT_OK = True",
    "docstring": "Convenience method for setting the git executable path."
  },
  {
    "code": "def removeRnaQuantificationSet(self, rnaQuantificationSet):\n        q = models.Rnaquantificationset.delete().where(\n            models.Rnaquantificationset.id == rnaQuantificationSet.getId())\n        q.execute()",
    "docstring": "Removes the specified rnaQuantificationSet from this repository. This\n        performs a cascading removal of all items within this\n        rnaQuantificationSet."
  },
  {
    "code": "def _roots_to_targets(self, build_graph, target_roots):\n    with self._run_tracker.new_workunit(name='parse', labels=[WorkUnitLabel.SETUP]):\n      return [\n        build_graph.get_target(address)\n        for address\n        in build_graph.inject_roots_closure(target_roots, self._fail_fast)\n      ]",
    "docstring": "Populate the BuildGraph and target list from a set of input TargetRoots."
  },
  {
    "code": "def package_version(self, prefix=None, name=None, pkg=None, build=False):\n        package_versions = {}\n        if name and prefix:\n            raise TypeError(\"Exactly one of 'name' or 'prefix' is required.\")\n        if name:\n            prefix = self.get_prefix_envname(name)\n        if self.environment_exists(prefix=prefix):\n            for package in self.linked(prefix):\n                if pkg in package:\n                    n, v, b = self.split_canonical_name(package)\n                    if build:\n                        package_versions[n] = '{0}={1}'.format(v, b)\n                    else:\n                        package_versions[n] = v\n        return package_versions.get(pkg)",
    "docstring": "Get installed package version in a given env."
  },
  {
    "code": "def handle_document(self, line: str, position: int, tokens: ParseResults) -> ParseResults:\n        key = tokens['key']\n        value = tokens['value']\n        if key not in DOCUMENT_KEYS:\n            raise InvalidMetadataException(self.get_line_number(), line, position, key, value)\n        norm_key = DOCUMENT_KEYS[key]\n        if norm_key in self.document_metadata:\n            log.warning('Tried to overwrite metadata: %s', key)\n            return tokens\n        self.document_metadata[norm_key] = value\n        if norm_key == METADATA_VERSION:\n            self.raise_for_version(line, position, value)\n        return tokens",
    "docstring": "Handle statements like ``SET DOCUMENT X = \"Y\"``.\n\n        :raises: InvalidMetadataException\n        :raises: VersionFormatWarning"
  },
  {
    "code": "def run(self, batch: Batch, train: bool=False, stream: StreamWrapper=None) -> Batch:\n        if train:\n            raise ValueError('Ensemble model cannot be trained.')\n        self._load_models()\n        current_batch = dict(copy.deepcopy(batch))\n        for model in self._models:\n            current_batch.update(model.run(current_batch, False, None))\n        return {key: current_batch[key] for key in self.output_names}",
    "docstring": "Run all the models in-order and return accumulated outputs.\n\n        N-th model is fed with the original inputs and outputs of all the models that were run before it.\n\n        .. warning::\n            :py:class:`Sequence` model can not be trained.\n\n        :param batch: batch to be processed\n        :param train: ``True`` if this batch should be used for model update, ``False`` otherwise\n        :param stream: stream wrapper (useful for precise buffer management)\n        :return: accumulated model outputs\n        :raise ValueError: if the ``train`` flag is set to ``True``"
  },
  {
    "code": "def release(self, subnets):\n        if isinstance(subnets, str) or isinstance(subnets, IPNetwork):\n            subnets = [subnets]\n        subnets_iter = (\n            str(subnet) if isinstance(subnet, IPNetwork) else subnet\n            for subnet in subnets\n        )\n        try:\n            with self._create_lock():\n                for subnet in subnets_iter:\n                    self._release(self.create_lease_object_from_subnet(subnet))\n        except (utils.TimerException, IOError):\n            raise LagoSubnetLeaseLockException(self.path)",
    "docstring": "Free the lease of the given subnets\n\n        Args:\n            subnets (list of str or netaddr.IPAddress): dotted ipv4 subnet in\n                CIDR notation (for example ```192.168.200.0/24```) or IPAddress\n                object.\n\n        Raises:\n            LagoSubnetLeaseException: If subnet is a str and can't be parsed\n            LagoSubnetLeaseLockException:\n                If the lock to self.path can't be acquired."
  },
  {
    "code": "def split_n(string, seps, reg=False):\n    r\n    deep = len(seps)\n    if not deep:\n        return string\n    return [split_n(i, seps[1:]) for i in _re_split_mixin(string, seps[0], reg=reg)]",
    "docstring": "r\"\"\"Split strings into n-dimensional list.\n\n    ::\n\n        from torequests.utils import split_n\n\n        ss = '''a b c  d e f  1 2 3  4 5 6\n        a b c  d e f  1 2 3  4 5 6\n        a b c  d e f  1 2 3  4 5 6'''\n\n        print(split_n(ss, ('\\n', '  ', ' ')))\n        # [[['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3'], ['4', '5', '6']], [['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3'], ['4', '5', '6']], [['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3'], ['4', '5', '6']]]\n        print(split_n(ss, ['\\s+'], reg=1))\n        # ['a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', 'a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', 'a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6']"
  },
  {
    "code": "def update_form_labels(self, request=None, obj=None, form=None):\n        for form_label in self.custom_form_labels:\n            if form_label.field in form.base_fields:\n                label = form_label.get_form_label(\n                    request=request, obj=obj, model=self.model, form=form\n                )\n                if label:\n                    form.base_fields[form_label.field].label = mark_safe(label)\n        return form",
    "docstring": "Returns a form obj after modifying form labels\n        referred to in custom_form_labels."
  },
  {
    "code": "def encode(self, encoding=None):\n        r\n        try:\n            fc = self.func.value\n        except AttributeError:\n            fc = self.func\n        mhash = bytes([fc, len(self.digest)]) + self.digest\n        if encoding:\n            mhash = CodecReg.get_encoder(encoding)(mhash)\n        return mhash",
    "docstring": "r\"\"\"Encode into a multihash-encoded digest.\n\n        If `encoding` is `None`, a binary digest is produced:\n\n        >>> mh = Multihash(0x01, b'TEST')\n        >>> mh.encode()\n        b'\\x01\\x04TEST'\n\n        If the name of an `encoding` is specified, it is used to encode the\n        binary digest before returning it (see `CodecReg` for supported\n        codecs).\n\n        >>> mh.encode('base64')\n        b'AQRURVNU'\n\n        If the `encoding` is not available, a `KeyError` is raised."
  },
  {
    "code": "def read_headers(rfile, hdict=None):\n    if hdict is None:\n        hdict = {}\n    while True:\n        line = rfile.readline()\n        if not line:\n            raise ValueError(\"Illegal end of headers.\")\n        if line == CRLF:\n            break\n        if not line.endswith(CRLF):\n            raise ValueError(\"HTTP requires CRLF terminators\")\n        if line[0] in ' \\t':\n            v = line.strip()\n        else:\n            try:\n                k, v = line.split(\":\", 1)\n            except ValueError:\n                raise ValueError(\"Illegal header line.\")\n            k = k.strip().title()\n            v = v.strip()\n            hname = k\n        if k in comma_separated_headers:\n            existing = hdict.get(hname)\n            if existing:\n                v = \", \".join((existing, v))\n        hdict[hname] = v\n    return hdict",
    "docstring": "Read headers from the given stream into the given header dict.\n    \n    If hdict is None, a new header dict is created. Returns the populated\n    header dict.\n    \n    Headers which are repeated are folded together using a comma if their\n    specification so dictates.\n    \n    This function raises ValueError when the read bytes violate the HTTP spec.\n    You should probably return \"400 Bad Request\" if this happens."
  },
  {
    "code": "def _clone_reverses(self, old_reverses):\n        for ctype, reverses in old_reverses.items():\n            for parts in reverses.values():\n                sub_objs = parts[1]\n                field_name = parts[0]\n                attrs = {}\n                for sub_obj in sub_objs:\n                    if ctype != 'm2m' and not attrs:\n                        field = sub_obj._meta.get_field(field_name)\n                        attrs = {\n                            field.column: getattr(self, field.rel.field_name)\n                        }\n                    sub_obj._clone(**attrs)\n                if ctype == 'm2m':\n                    setattr(self, field_name, sub_objs)",
    "docstring": "Clones all the objects that were previously gathered."
  },
  {
    "code": "def get_all_tables(self, dataset_id, project_id=None):\n        tables_data = self._get_all_tables_for_dataset(dataset_id, project_id)\n        tables = []\n        for table in tables_data.get('tables', []):\n            table_name = table.get('tableReference', {}).get('tableId')\n            if table_name:\n                tables.append(table_name)\n        return tables",
    "docstring": "Retrieve a list of tables for the dataset.\n\n        Parameters\n        ----------\n        dataset_id : str\n            The dataset to retrieve table data for.\n        project_id: str\n            Unique ``str`` identifying the BigQuery project contains the dataset\n\n        Returns\n        -------\n        A ``list`` with all table names"
  },
  {
    "code": "def _emit_error(cls, message):\n        sys.stderr.write('ERROR: {message}\\n'.format(message=message))\n        sys.stderr.flush()",
    "docstring": "Print an error message to STDERR."
  },
  {
    "code": "def club(self,cid):\n        headers = {\"Content-type\": \"application/x-www-form-urlencoded\",\"Accept\": \"text/plain\",'Referer': 'http://'+self.domain+'/',\"User-Agent\": user_agent}\n        req = self.session.get('http://'+self.domain+'/clubInfo.phtml?cid='+cid,headers=headers).content\n        soup = BeautifulSoup(req)\n        plist = []\n        for i in soup.find('table',cellpadding=2).find_all('tr')[1:]:\n            plist.append('%s\\t%s\\t%s\\t%s\\t%s'%(i.find_all('td')[0].text,i.find_all('td')[1].text,i.find_all('td')[2].text,i.find_all('td')[3].text,i.find_all('td')[4].text))\n        return soup.title.text,plist",
    "docstring": "Get info by real team using a ID\n        @return: name,[player list]"
  },
  {
    "code": "def is_available(self):\n        if self.scheme in NOOP_PROTOCOLS:\n            return True\n        if not self.port:\n            raise RuntimeError('port is required')\n        s = socket.socket()\n        try:\n            s.connect((self.host, self.port))\n        except Exception:\n            return False\n        else:\n            return True",
    "docstring": "Return True if the connection to the host and port is successful.\n\n        @return: bool"
  },
  {
    "code": "def serve(handler, sock_path, timeout=UNIX_SOCKET_TIMEOUT):\n    ssh_version = subprocess.check_output(['ssh', '-V'],\n                                          stderr=subprocess.STDOUT)\n    log.debug('local SSH version: %r', ssh_version)\n    environ = {'SSH_AUTH_SOCK': sock_path, 'SSH_AGENT_PID': str(os.getpid())}\n    device_mutex = threading.Lock()\n    with server.unix_domain_socket_server(sock_path) as sock:\n        sock.settimeout(timeout)\n        quit_event = threading.Event()\n        handle_conn = functools.partial(server.handle_connection,\n                                        handler=handler,\n                                        mutex=device_mutex)\n        kwargs = dict(sock=sock,\n                      handle_conn=handle_conn,\n                      quit_event=quit_event)\n        with server.spawn(server.server_thread, kwargs):\n            try:\n                yield environ\n            finally:\n                log.debug('closing server')\n                quit_event.set()",
    "docstring": "Start the ssh-agent server on a UNIX-domain socket.\n\n    If no connection is made during the specified timeout,\n    retry until the context is over."
  },
  {
    "code": "def InternalSend(self, cmd, payload):\n    length_to_send = len(payload)\n    max_payload = self.packet_size - 7\n    first_frame = payload[0:max_payload]\n    first_packet = UsbHidTransport.InitPacket(self.packet_size, self.cid, cmd,\n                                              len(payload), first_frame)\n    del payload[0:max_payload]\n    length_to_send -= len(first_frame)\n    self.InternalSendPacket(first_packet)\n    seq = 0\n    while length_to_send > 0:\n      max_payload = self.packet_size - 5\n      next_frame = payload[0:max_payload]\n      del payload[0:max_payload]\n      length_to_send -= len(next_frame)\n      next_packet = UsbHidTransport.ContPacket(self.packet_size, self.cid, seq,\n                                               next_frame)\n      self.InternalSendPacket(next_packet)\n      seq += 1",
    "docstring": "Sends a message to the device, including fragmenting it."
  },
  {
    "code": "def class_details(self, title=None):\n        if title is None:\n            return javabridge.call(\n                self.jobject, \"toClassDetailsString\", \"()Ljava/lang/String;\")\n        else:\n            return javabridge.call(\n                self.jobject, \"toClassDetailsString\", \"(Ljava/lang/String;)Ljava/lang/String;\", title)",
    "docstring": "Generates the class details.\n\n        :param title: optional title\n        :type title: str\n        :return: the details\n        :rtype: str"
  },
  {
    "code": "def debugDumpAttr(self, output, depth):\n        libxml2mod.xmlDebugDumpAttr(output, self._o, depth)",
    "docstring": "Dumps debug information for the attribute"
  },
  {
    "code": "def create_reference_server_flask_app(cfg):\n    app = Flask(__name__)\n    Flask.secret_key = \"SECRET_HERE\"\n    app.debug = cfg.debug\n    client_prefixes = dict()\n    for api_version in cfg.api_versions:\n        handler_config = Config(cfg)\n        handler_config.api_version = api_version\n        handler_config.klass_name = 'pil'\n        handler_config.auth_type = 'none'\n        handler_config.prefix = \"api/image/%s/example/reference\" % (api_version)\n        handler_config.client_prefix = handler_config.prefix\n        add_handler(app, handler_config)\n    return app",
    "docstring": "Create referece server Flask application with one or more IIIF handlers."
  },
  {
    "code": "def _exact_match(response, matches, insensitive, fuzzy):\n    for match in matches:\n        if response == match:\n            return match\n        elif insensitive and response.lower() == match.lower():\n            return match\n        elif fuzzy and _exact_fuzzy_match(response, match, insensitive):\n            return match\n    else:\n        return None",
    "docstring": "returns an exact match, if it exists, given parameters\n    for the match"
  },
  {
    "code": "def GetGtfsFactory(self):\n    if self._gtfs_factory is None:\n      from . import gtfsfactory\n      self._gtfs_factory = gtfsfactory.GetGtfsFactory()\n    return self._gtfs_factory",
    "docstring": "Return the object's GTFS Factory.\n\n    Returns:\n        The GTFS Factory that was set for this object. If none was explicitly\n        set, it first sets the object's factory to transitfeed's GtfsFactory\n        and returns it"
  },
  {
    "code": "def from_message_and_data(cls,\n                              message: str,\n                              data: Dict[str, Any]\n                              ) -> 'BugZooException':\n        return cls(message)",
    "docstring": "Reproduces an exception from the message and data contained in its\n        dictionary-based description."
  },
  {
    "code": "def get_current_term():\n    url = \"{}/current.json\".format(term_res_url_prefix)\n    term = _json_to_term_model(get_resource(url))\n    if datetime.now() > term.grade_submission_deadline:\n        return get_next_term()\n    return term",
    "docstring": "Returns a uw_sws.models.Term object,\n    for the current term."
  },
  {
    "code": "def fRD( a, M):\n    f = (lal.C_SI**3.0 / (2.0*lal.PI*lal.G_SI*M*lal.MSUN_SI)) * (1.5251 - 1.1568*(1.0-a)**0.1292)\n    return f",
    "docstring": "Calculate the ring-down frequency for the final Kerr BH. Using Eq. 5.5 of Main paper"
  },
  {
    "code": "def non_neighbors(graph, node, t=None):\n    if graph.is_directed():\n        values = chain(graph.predecessors(node, t=t), graph.successors(node, t=t))\n    else:\n        values = graph.neighbors(node, t=t)\n    nbors = set(values) | {node}\n    return (nnode for nnode in graph if nnode not in nbors)",
    "docstring": "Returns the non-neighbors of the node in the graph at time t.\n\n        Parameters\n        ----------\n        graph : DyNetx graph\n            Graph to find neighbors.\n\n        node : node\n            The node whose neighbors will be returned.\n\n        t : snapshot id (default=None)\n            If None the non-neighbors are identified on the flattened graph.\n\n\n        Returns\n        -------\n        non_neighbors : iterator\n            Iterator of nodes in the graph that are not neighbors of the node."
  },
  {
    "code": "def _build(value, property_path=None):\n    if not property_path:\n        property_path = []\n    if is_config_type(value):\n        return _build_config(value, property_path=property_path)\n    elif is_config_var(value):\n        return _build_var(value, property_path=property_path)\n    elif is_builtin_type(value):\n        return _build_type(value, value, property_path=property_path)\n    elif is_regex_type(value):\n        return _build_type(str, value, property_path=property_path)\n    elif is_typing_type(value):\n        return _build_type(value, value, property_path=property_path)\n    return _build_type(type(value), value, property_path=property_path)",
    "docstring": "The generic schema definition build method.\n\n    :param value: The value to build a schema definition for\n    :param List[str] property_path: The property path of the current type,\n        defaults to None, optional\n    :return: The built schema definition\n    :rtype: Dict[str, Any]"
  },
  {
    "code": "def advertiseBrokerWorkerDown(exctype, value, traceback):\n    if not scoop.SHUTDOWN_REQUESTED:\n        execQueue.shutdown()\n    sys.__excepthook__(exctype, value, traceback)",
    "docstring": "Hook advertizing the broker if an impromptu shutdown is occuring."
  },
  {
    "code": "def getchild(self, name, parent):\n        if name.startswith('@'):\n            return parent.get_attribute(name[1:])\n        else:\n            return parent.get_child(name)",
    "docstring": "get a child by name"
  },
  {
    "code": "def loadTargetPatterns(self, filename, cols = None, everyNrows = 1,\n                            delim = ' ', checkEven = 1):\n        self.loadTargetPatternssFromFile(filename, cols, everyNrows,\n                                         delim, checkEven)",
    "docstring": "Loads targets as patterns from file."
  },
  {
    "code": "def natural_neighbor_to_points(points, values, xi):\n    r\n    tri = Delaunay(points)\n    members, triangle_info = geometry.find_natural_neighbors(tri, xi)\n    img = np.empty(shape=(xi.shape[0]), dtype=values.dtype)\n    img.fill(np.nan)\n    for ind, (grid, neighbors) in enumerate(members.items()):\n        if len(neighbors) > 0:\n            points_transposed = np.array(points).transpose()\n            img[ind] = natural_neighbor_point(points_transposed[0], points_transposed[1],\n                                              values, xi[grid], tri, neighbors, triangle_info)\n    return img",
    "docstring": "r\"\"\"Generate a natural neighbor interpolation to the given points.\n\n    This assigns values to the given interpolation points using the Liang and Hale\n    [Liang2010]_. approach.\n\n    Parameters\n    ----------\n    points: array_like, shape (n, 2)\n        Coordinates of the data points.\n    values: array_like, shape (n,)\n        Values of the data points.\n    xi: array_like, shape (M, 2)\n        Points to interpolate the data onto.\n\n    Returns\n    -------\n    img: (M,) ndarray\n        Array representing the interpolated values for each input point in `xi`\n\n    See Also\n    --------\n    natural_neighbor_to_grid"
  },
  {
    "code": "def bures_angle(rho0: Density, rho1: Density) -> float:\n    return np.arccos(np.sqrt(fidelity(rho0, rho1)))",
    "docstring": "Return the Bures angle between mixed quantum states\n\n    Note: Bures angle cannot be calculated within the tensor backend."
  },
  {
    "code": "def write_svg(self):\n        import plantuml\n        puml = self.write_puml()\n        server = plantuml.PlantUML(url=self.url)\n        svg = server.processes(puml)\n        return svg",
    "docstring": "Returns PUML from the system as a SVG image. Requires plantuml library."
  },
  {
    "code": "def _calc_mask(self):\n    mask = []\n    for row in self._constraints:\n      mask.append(tuple(x is None for x in row))\n    return tuple(mask)",
    "docstring": "Computes a boolean mask from the user defined constraints."
  },
  {
    "code": "def align_file_position(f, size):\n    align = (size - 1) - (f.tell() % size)\n    f.seek(align, 1)",
    "docstring": "Align the position in the file to the next block of specified size"
  },
  {
    "code": "def _verify_query(self, query_params):\n        error_message = None\n        if self.state_token is not False:\n            received_state_token = query_params.get('state')\n            if received_state_token is None:\n                error_message = 'Bad Request. Missing state parameter.'\n                raise UberIllegalState(error_message)\n            if self.state_token != received_state_token:\n                error_message = 'CSRF Error. Expected {}, got {}'\n                error_message = error_message.format(\n                    self.state_token,\n                    received_state_token,\n                )\n                raise UberIllegalState(error_message)\n        error = query_params.get('error')\n        authorization_code = query_params.get(auth.CODE_RESPONSE_TYPE)\n        if error and authorization_code:\n            error_message = (\n                'Code and Error query params code and error '\n                'can not both be set.'\n            )\n            raise UberIllegalState(error_message)\n        if error is None and authorization_code is None:\n            error_message = 'Neither query parameter code or error is set.'\n            raise UberIllegalState(error_message)\n        if error:\n            raise UberIllegalState(error)\n        return authorization_code",
    "docstring": "Verify response from the Uber Auth server.\n\n        Parameters\n            query_params (dict)\n                Dictionary of query parameters attached to your redirect URL\n                after user approved your app and was redirected.\n\n        Returns\n            authorization_code (str)\n                Code received when user grants your app access. Use this code\n                to request an access token.\n\n        Raises\n            UberIllegalState (ApiError)\n                Thrown if the redirect URL was missing parameters or if the\n                given parameters were not valid."
  },
  {
    "code": "def apply_dict_of_variables_vfunc(\n    func, *args, signature, join='inner', fill_value=None\n):\n    args = [_as_variables_or_variable(arg) for arg in args]\n    names = join_dict_keys(args, how=join)\n    grouped_by_name = collect_dict_values(args, names, fill_value)\n    result_vars = OrderedDict()\n    for name, variable_args in zip(names, grouped_by_name):\n        result_vars[name] = func(*variable_args)\n    if signature.num_outputs > 1:\n        return _unpack_dict_tuples(result_vars, signature.num_outputs)\n    else:\n        return result_vars",
    "docstring": "Apply a variable level function over dicts of DataArray, DataArray,\n    Variable and ndarray objects."
  },
  {
    "code": "def truth(val, context):\n    try:\n        0 + val\n    except TypeError:\n        lower_val = val.lower()\n        if lower_val in TRUE:\n            return True\n        elif lower_val in FALSE:\n            return False\n        else:\n            raise FilterError(\"Bad boolean value %r in %r (expected one of '%s', or '%s')\" % (\n                val, context, \"' '\".join(TRUE), \"' '\".join(FALSE)\n            ))\n    else:\n        return bool(val)",
    "docstring": "Convert truth value in \"val\" to a boolean."
  },
  {
    "code": "def _set_current_options(self, options):\n        opts = self._get_current_options()\n        opts.update(options)\n        response = self.__proxy__.set_current_options(opts)\n        return response",
    "docstring": "Set current options for a model.\n\n        Parameters\n        ----------\n        options : dict\n            A dictionary of the desired option settings. The key should be the name\n            of the option and each value is the desired value of the option."
  },
  {
    "code": "def axis_updated(self, event: InputEvent, prefix=None):\n        if prefix is not None:\n            axis = self.axes_by_code.get(prefix + str(event.code))\n        else:\n            axis = self.axes_by_code.get(event.code)\n        if axis is not None:\n            axis.receive_device_value(event.value)\n        else:\n            logger.debug('Unknown axis code {} ({}), value {}'.format(event.code, prefix, event.value))",
    "docstring": "Called to process an absolute axis event from evdev, this is called internally by the controller implementations\n\n        :internal:\n\n        :param event:\n            The evdev event to process\n        :param prefix:\n            If present, a named prefix that should be applied to the event code when searching for the axis"
  },
  {
    "code": "def _build_one(self, req, output_dir, python_tag=None):\n        with req.build_env:\n            return self._build_one_inside_env(req, output_dir,\n                                              python_tag=python_tag)",
    "docstring": "Build one wheel.\n\n        :return: The filename of the built wheel, or None if the build failed."
  },
  {
    "code": "def Detach(self):\n    if not self.IsAttached():\n      return None\n    pid = gdb.selected_inferior().pid\n    self.Interrupt([pid, None, None])\n    self.Continue([pid, None, None])\n    result = gdb.execute('detach', to_string=True)\n    if not result:\n      return None\n    return result",
    "docstring": "Detaches from the inferior. If not attached, this is a no-op."
  },
  {
    "code": "def public_keys_as_files(self):\n        if not self.public_keys_tempfiles:\n            for pk in self.public_keys():\n                f = tempfile.NamedTemporaryFile(prefix='trezor-ssh-pubkey-', mode='w')\n                f.write(pk)\n                f.flush()\n                self.public_keys_tempfiles.append(f)\n        return self.public_keys_tempfiles",
    "docstring": "Store public keys as temporary SSH identity files."
  },
  {
    "code": "def envs(backend=None, sources=False):\n    fileserver = salt.fileserver.Fileserver(__opts__)\n    return sorted(fileserver.envs(back=backend, sources=sources))",
    "docstring": "Return the available fileserver environments. If no backend is provided,\n    then the environments for all configured backends will be returned.\n\n    backend\n        Narrow fileserver backends to a subset of the enabled ones.\n\n        .. versionchanged:: 2015.5.0\n            If all passed backends start with a minus sign (``-``), then these\n            backends will be excluded from the enabled backends. However, if\n            there is a mix of backends with and without a minus sign (ex:\n            ``backend=-roots,git``) then the ones starting with a minus\n            sign will be disregarded.\n\n            Additionally, fileserver backends can now be passed as a\n            comma-separated list. In earlier versions, they needed to be passed\n            as a python list (ex: ``backend=\"['roots', 'git']\"``)\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-run fileserver.envs\n        salt-run fileserver.envs backend=roots,git\n        salt-run fileserver.envs git"
  },
  {
    "code": "def _structure_list(self, obj, cl):\n        if is_bare(cl) or cl.__args__[0] is Any:\n            return [e for e in obj]\n        else:\n            elem_type = cl.__args__[0]\n            return [\n                self._structure_func.dispatch(elem_type)(e, elem_type)\n                for e in obj\n            ]",
    "docstring": "Convert an iterable to a potentially generic list."
  },
  {
    "code": "def _has_ipv6(host):\n    sock = None\n    has_ipv6 = False\n    if _appengine_environ.is_appengine_sandbox():\n        return False\n    if socket.has_ipv6:\n        try:\n            sock = socket.socket(socket.AF_INET6)\n            sock.bind((host, 0))\n            has_ipv6 = True\n        except Exception:\n            pass\n    if sock:\n        sock.close()\n    return has_ipv6",
    "docstring": "Returns True if the system can bind an IPv6 address."
  },
  {
    "code": "def get(self, url):\n        self._query()\n        return Enclosure(self._resp.get(url), url)",
    "docstring": "Get the response for the given enclosure URL"
  },
  {
    "code": "def _call(self, x):\n        y = np.bincount(self._indices_flat, weights=x,\n                        minlength=self.range.size)\n        out = y.reshape(self.range.shape)\n        if self.variant == 'dirac':\n            weights = getattr(self.range, 'cell_volume', 1.0)\n        elif self.variant == 'char_fun':\n            weights = 1.0\n        else:\n            raise RuntimeError('The variant \"{!r}\" is not yet supported'\n                               ''.format(self.variant))\n        if weights != 1.0:\n            out /= weights\n        return out",
    "docstring": "Sum all values if indices are given multiple times."
  },
  {
    "code": "def set_data_from_iterable(self, frames, values, labels=None):\n        if not isinstance(frames, collections.Iterable):\n            raise TypeError, \"frames must be an iterable\"\n        if not isinstance(values, collections.Iterable):\n            raise TypeError, \"values must be an iterable\"\n        assert(len(frames) == len(values))\n        self.frames = frames\n        self.values = values\n        if labels is None:\n            self.label2int['New Point'] = 0\n            self.int2label[0] = 'New Point'\n            self.labels = [0 for i in xrange(len(frames))]\n        else:\n            if not isinstance(labels, collections.Iterable):\n                raise TypeError, \"labels must be an iterable\"\n            for l in labels:\n                if l not in self.label2int:\n                    self.label2int[l] = len(self.label2int)\n                    self.int2label[len(self.int2label)] = l\n                self.labels.append(self.label2int[l])",
    "docstring": "Initialize a dataset structure from iterable parameters\n\n        :param x: The temporal indices of the dataset\n        :param y: The values of the dataset\n        :type x: iterable\n        :type y: iterable"
  },
  {
    "code": "def search(self):\n        params = self.solr_params()\n        logging.info(\"PARAMS=\" + str(params))\n        results = self.solr.search(**params)\n        logging.info(\"Docs found: {}\".format(results.hits))\n        return self._process_search_results(results)",
    "docstring": "Execute solr search query"
  },
  {
    "code": "def __bytes_to_share_data(self, payload):\n        rbytes = payload[P_DATA]\n        mime = payload[P_MIME]\n        if mime is None or not self.__auto_encode_decode:\n            return rbytes, mime\n        mime = expand_idx_mimetype(mime).lower()\n        try:\n            if mime == 'application/ubjson':\n                return ubjloadb(rbytes), None\n            elif mime == 'text/plain; charset=utf8':\n                return rbytes.decode('utf-8'), None\n            else:\n                return rbytes, mime\n        except:\n            logger.warning('auto-decode failed, returning bytes', exc_info=DEBUG_ENABLED)\n            return rbytes, mime",
    "docstring": "Attempt to auto-decode data"
  },
  {
    "code": "def _return_feature(self, feature_type, feature_name, new_feature_name=...):\r\n        if self.new_names:\r\n            return feature_type, feature_name, (self.rename_function(feature_name) if new_feature_name is ... else\r\n                                                new_feature_name)\r\n        return feature_type, feature_name",
    "docstring": "Helping function of `get_features`"
  },
  {
    "code": "def usufyToTextExport(d, fPath=None):\n    if d == []:\n        return \"+------------------+\\n| No data found... |\\n+------------------+\"\n    import pyexcel as pe\n    import pyexcel.ext.text as text\n    if fPath == None:\n        isTerminal = True\n    else:\n        isTerminal = False\n    try:\n        oldData = get_data(fPath)\n    except:\n        oldData = {\"OSRFramework\":[]}\n    tabularData = _generateTabularData(d, {\"OSRFramework\":[[]]}, True, canUnicode=False)\n    sheet = pe.Sheet(tabularData[\"OSRFramework\"])\n    sheet.name = \"Profiles recovered (\" + getCurrentStrDatetime() +\").\"\n    sheet.name_columns_by_row(0)\n    text.TABLEFMT = \"grid\"\n    try:\n        with open(fPath, \"w\") as oF:\n            oF.write(str(sheet))\n    except Exception as e:\n        return unicode(sheet)",
    "docstring": "Workaround to export to a .txt file or to show the information.\n\n    Args:\n    -----\n        d: Data to export.\n        fPath: File path for the output file. If None was provided, it will\n            assume that it has to print it.\n\n    Returns:\n    --------\n        unicode: It sometimes returns a unicode representation of the Sheet\n            received."
  },
  {
    "code": "def return_dat(self, chan, begsam, endsam):\n        assert begsam < endsam\n        dat = empty((len(chan), endsam - begsam))\n        dat.fill(NaN)\n        with self.filename.open('rb') as f:\n            for i_dat, blk, i_blk in _select_blocks(self.blocks, begsam, endsam):\n                dat_in_rec = self._read_record(f, blk, chan)\n                dat[:, i_dat[0]:i_dat[1]] = dat_in_rec[:, i_blk[0]:i_blk[1]]\n        dat = ((dat.astype('float64') - self.dig_min[chan, newaxis]) *\n               self.gain[chan, newaxis] + self.phys_min[chan, newaxis])\n        return dat",
    "docstring": "Read data from an EDF file.\n\n        Reads channel by channel, and adjusts the values by calibration.\n\n        Parameters\n        ----------\n        chan : list of int\n            index (indices) of the channels to read\n        begsam : int\n            index of the first sample\n        endsam : int\n            index of the last sample\n\n        Returns\n        -------\n        numpy.ndarray\n            A 2d matrix, where the first dimension is the channels and the\n            second dimension are the samples."
  },
  {
    "code": "def set(self, option, value):\n        if self.config is None:\n            self.config = {}\n        self.config[option] = value",
    "docstring": "Sets an option to a value."
  },
  {
    "code": "def parse_rst(text: str) -> docutils.nodes.document:\n    parser = docutils.parsers.rst.Parser()\n    components = (docutils.parsers.rst.Parser,)\n    settings = docutils.frontend.OptionParser(components=components).get_default_values()\n    document = docutils.utils.new_document('<rst-doc>', settings=settings)\n    parser.parse(text, document)\n    return document",
    "docstring": "Parse text assuming it's an RST markup."
  },
  {
    "code": "def initialize_repo(self):\n        logging.info('Repo {} doesn\\'t exist. Cloning...'.format(self.repo_dir))\n        clone_args = ['git', 'clone']\n        if self.depth and self.depth > 0:\n            clone_args.extend(['--depth', str(self.depth)])\n        clone_args.extend(['--branch', self.branch_name])\n        clone_args.extend([self.git_url, self.repo_dir])\n        yield from execute_cmd(clone_args)\n        yield from execute_cmd(['git', 'config', 'user.email', 'nbgitpuller@example.com'], cwd=self.repo_dir)\n        yield from execute_cmd(['git', 'config', 'user.name', 'nbgitpuller'], cwd=self.repo_dir)\n        logging.info('Repo {} initialized'.format(self.repo_dir))",
    "docstring": "Clones repository & sets up usernames."
  },
  {
    "code": "def _load_sets(self,directory):\n        _sets=[]\n        try:\n            fullfile=os.path.join(directory,SET_FILE)\n            lsets=open(fullfile).readline().split(',')\n            for tag in lsets:\n                _sets.append(tag.strip())\n        except:\n            logger.error(\"No sets found in %s, FB needs an album name (%s)\"\\\n                    %(directory,SET_FILE))\n            sys.exit(1)\n        return _sets",
    "docstring": "Loads sets from set file and return\n        as list of strings"
  },
  {
    "code": "def source_cmd(args, stdin=None):\n    args = list(args)\n    fpath = locate_binary(args[0])\n    args[0] = fpath if fpath else args[0]\n    if not os.path.isfile(args[0]):\n        raise RuntimeError(\"Command not found: %s\" % args[0])\n    prevcmd = 'call '\n    prevcmd += ' '.join([argvquote(arg, force=True) for arg in args])\n    prevcmd = escape_windows_cmd_string(prevcmd)\n    args.append('--prevcmd={}'.format(prevcmd))\n    args.insert(0, 'cmd')\n    args.append('--interactive=0')\n    args.append('--sourcer=call')\n    args.append('--envcmd=set')\n    args.append('--seterrpostcmd=if errorlevel 1 exit 1')\n    args.append('--use-tmpfile=1')\n    return source_foreign(args, stdin=stdin)",
    "docstring": "Simple cmd.exe-specific wrapper around source-foreign.\n\n    returns a dict to be used as a new environment"
  },
  {
    "code": "def semiyearly(date=datetime.date.today()):\n    return datetime.date(date.year, 1 if date.month < 7 else 7, 1)",
    "docstring": "Twice a year."
  },
  {
    "code": "def clean_blobstore_cache(self):\n        url = self.api_url + self.blobstores_builpack_cache_url\n        resp, rcode = self.request('DELETE', url)\n        if rcode != 202:\n            raise CFException(resp, rcode)\n        return resp",
    "docstring": "Deletes all of the existing buildpack caches in the blobstore"
  },
  {
    "code": "def _render_reward(self, r: np.float32) -> None:\n        print(\"reward = {:.4f}\".format(float(r)))\n        print()",
    "docstring": "Prints reward `r`."
  },
  {
    "code": "def _tune(self, args):\n        client_heartbeat = self.client_heartbeat or 0\n        self.channel_max = args.read_short() or self.channel_max\n        self.frame_max = args.read_long() or self.frame_max\n        self.method_writer.frame_max = self.frame_max\n        self.server_heartbeat = args.read_short() or 0\n        if self.server_heartbeat == 0 or client_heartbeat == 0:\n            self.heartbeat = max(self.server_heartbeat, client_heartbeat)\n        else:\n            self.heartbeat = min(self.server_heartbeat, client_heartbeat)\n        if not self.client_heartbeat:\n            self.heartbeat = 0\n        self._x_tune_ok(self.channel_max, self.frame_max, self.heartbeat)",
    "docstring": "Propose connection tuning parameters\n\n        This method proposes a set of connection configuration values\n        to the client.  The client can accept and/or adjust these.\n\n        PARAMETERS:\n            channel_max: short\n\n                proposed maximum channels\n\n                The maximum total number of channels that the server\n                allows per connection. Zero means that the server does\n                not impose a fixed limit, but the number of allowed\n                channels may be limited by available server resources.\n\n            frame_max: long\n\n                proposed maximum frame size\n\n                The largest frame size that the server proposes for\n                the connection. The client can negotiate a lower\n                value.  Zero means that the server does not impose any\n                specific limit but may reject very large frames if it\n                cannot allocate resources for them.\n\n                RULE:\n\n                    Until the frame-max has been negotiated, both\n                    peers MUST accept frames of up to 4096 octets\n                    large. The minimum non-zero value for the frame-\n                    max field is 4096.\n\n            heartbeat: short\n\n                desired heartbeat delay\n\n                The delay, in seconds, of the connection heartbeat\n                that the server wants.  Zero means the server does not\n                want a heartbeat."
  },
  {
    "code": "def make_mutant_tuples(example_protos, original_feature, index_to_mutate,\n                       viz_params):\n  mutant_features = make_mutant_features(original_feature, index_to_mutate,\n                                         viz_params)\n  mutant_examples = []\n  for example_proto in example_protos:\n    for mutant_feature in mutant_features:\n      copied_example = copy.deepcopy(example_proto)\n      feature_name = mutant_feature.original_feature.feature_name\n      try:\n        feature_list = proto_value_for_feature(copied_example, feature_name)\n        if index_to_mutate is None:\n          new_values = mutant_feature.mutant_value\n        else:\n          new_values = list(feature_list)\n          new_values[index_to_mutate] = mutant_feature.mutant_value\n        del feature_list[:]\n        feature_list.extend(new_values)\n        mutant_examples.append(copied_example)\n      except (ValueError, IndexError):\n        mutant_examples.append(copied_example)\n  return mutant_features, mutant_examples",
    "docstring": "Return a list of `MutantFeatureValue`s and a list of mutant Examples.\n\n  Args:\n    example_protos: The examples to mutate.\n    original_feature: A `OriginalFeatureList` that encapsulates the feature to\n      mutate.\n    index_to_mutate: The index of the int64_list or float_list to mutate.\n    viz_params: A `VizParams` object that contains the UI state of the request.\n\n  Returns:\n    A list of `MutantFeatureValue`s and a list of mutant examples."
  },
  {
    "code": "def _mass_from_knownmass_eta(known_mass, eta, known_is_secondary=False,\n                            force_real=True):\n    r\n    roots = numpy.roots([eta, (2*eta - 1)*known_mass, eta*known_mass**2.])\n    if force_real:\n        roots = numpy.real(roots)\n    if known_is_secondary:\n        return roots[roots.argmax()]\n    else:\n        return roots[roots.argmin()]",
    "docstring": "r\"\"\"Returns the other component mass given one of the component masses\n    and the symmetric mass ratio.\n\n    This requires finding the roots of the quadratic equation:\n\n    .. math::\n        \\eta m_2^2 + (2\\eta - 1)m_1 m_2 + \\eta m_1^2 = 0.\n\n    This has two solutions which correspond to :math:`m_1` being the heavier\n    mass or it being the lighter mass. By default, `known_mass` is assumed to\n    be the heavier (primary) mass, and the smaller solution is returned. Use\n    the `other_is_secondary` to invert.\n\n    Parameters\n    ----------\n    known_mass : float\n        The known component mass.\n    eta : float\n        The symmetric mass ratio.\n    known_is_secondary : {False, bool}\n        Whether the known component mass is the primary or the secondary. If\n        True, `known_mass` is assumed to be the secondary (lighter) mass and\n        the larger solution is returned. Otherwise, the smaller solution is\n        returned. Default is False.\n    force_real : {True, bool}\n        Force the returned mass to be real.\n\n    Returns\n    -------\n    float\n        The other component mass."
  },
  {
    "code": "def decrypt_file(file, key):\n    if not file.endswith('.enc'):\n        raise ValueError(\"%s does not end with .enc\" % file)\n    fer = Fernet(key)\n    with open(file, 'rb') as f:\n        decrypted_file = fer.decrypt(f.read())\n    with open(file[:-4], 'wb') as f:\n        f.write(decrypted_file)\n    os.chmod(file[:-4], 0o600)",
    "docstring": "Decrypts the file ``file``.\n\n    The encrypted file is assumed to end with the ``.enc`` extension. The\n    decrypted file is saved to the same location without the ``.enc``\n    extension.\n\n    The permissions on the decrypted file are automatically set to 0o600.\n\n    See also :func:`doctr.local.encrypt_file`."
  },
  {
    "code": "def cms_check(migrate_cmd=False):\n    from django.core.management import call_command\n    try:\n        import cms\n        _create_db(migrate_cmd)\n        call_command('cms', 'check')\n    except ImportError:\n        print('cms_check available only if django CMS is installed')",
    "docstring": "Runs the django CMS ``cms check`` command"
  },
  {
    "code": "def month_days(year, month):\n    if month > 13:\n        raise ValueError(\"Incorrect month index\")\n    if month in (IYYAR, TAMMUZ, ELUL, TEVETH, VEADAR):\n        return 29\n    if month == ADAR and not leap(year):\n        return 29\n    if month == HESHVAN and (year_days(year) % 10) != 5:\n        return 29\n    if month == KISLEV and (year_days(year) % 10) == 3:\n        return 29\n    return 30",
    "docstring": "How many days are in a given month of a given year"
  },
  {
    "code": "def _move_file_with_sizecheck(tx_file, final_file):\n    tmp_file = final_file + \".bcbiotmp\"\n    open(tmp_file, 'wb').close()\n    want_size = utils.get_size(tx_file)\n    shutil.move(tx_file, final_file)\n    transfer_size = utils.get_size(final_file)\n    assert want_size == transfer_size, (\n        'distributed.transaction.file_transaction: File copy error: '\n        'file or directory on temporary storage ({}) size {} bytes '\n        'does not equal size of file or directory after transfer to '\n        'shared storage ({}) size {} bytes'.format(\n            tx_file, want_size, final_file, transfer_size)\n    )\n    utils.remove_safe(tmp_file)",
    "docstring": "Move transaction file to final location,\n       with size checks avoiding failed transfers.\n\n       Creates an empty file with '.bcbiotmp' extention in the destination\n       location, which serves as a flag. If a file like that is present,\n       it means that transaction didn't finish successfully."
  },
  {
    "code": "def get_hierarchy_design_session_for_hierarchy(self, hierarchy_id, proxy):\n        if not self.supports_hierarchy_design():\n            raise errors.Unimplemented()\n        return sessions.HierarchyDesignSession(hierarchy_id, proxy, self._runtime)",
    "docstring": "Gets the ``OsidSession`` associated with the topology design service using for the given hierarchy.\n\n        arg:    hierarchy_id (osid.id.Id): the ``Id`` of the hierarchy\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.hierarchy.HierarchyDesignSession) - a\n                ``HierarchyDesignSession``\n        raise:  NotFound - ``hierarchy_id`` is not found\n        raise:  NullArgument - ``hierarchy_id`` or ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_hierarchy_design()`` or\n                ``supports_visible_federation()`` is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_hierarchy_design()`` and\n        ``supports_visible_federation()`` are ``true``.*"
  },
  {
    "code": "def destroy(self, request, project, pk=None):\n        job_id, bug_id = map(int, pk.split(\"-\"))\n        job = Job.objects.get(repository__name=project, id=job_id)\n        BugJobMap.objects.filter(job=job, bug_id=bug_id).delete()\n        return Response({\"message\": \"Bug job map deleted\"})",
    "docstring": "Delete bug-job-map entry. pk is a composite key in the form\n        bug_id-job_id"
  },
  {
    "code": "def mirror_pull(self, **kwargs):\n        path = '/projects/%s/mirror/pull' % self.get_id()\n        self.manager.gitlab.http_post(path, **kwargs)",
    "docstring": "Start the pull mirroring process for the project.\n\n        Args:\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabCreateError: If the server failed to perform the request"
  },
  {
    "code": "def dict2dzn(\n    objs, declare=False, assign=True, declare_enums=True, wrap=True, fout=None\n):\n    log = logging.getLogger(__name__)\n    vals = []\n    enums = set()\n    for key, val in objs.items():\n        if _is_enum(val) and declare_enums:\n            enum_type = type(val)\n            enum_name = enum_type.__name__\n            if enum_name not in enums:\n                enum_stmt = stmt2enum(\n                    enum_type, declare=declare, assign=assign, wrap=wrap\n                )\n                vals.append(enum_stmt)\n                enums.add(enum_name)\n        stmt = stmt2dzn(key, val, declare=declare, assign=assign, wrap=wrap)\n        vals.append(stmt)\n    if fout:\n        log.debug('Writing file: {}'.format(fout))\n        with open(fout, 'w') as f:\n            for val in vals:\n                f.write('{}\\n\\n'.format(val))\n    return vals",
    "docstring": "Serializes the objects in input and produces a list of strings encoding\n    them into dzn format. Optionally, the produced dzn is written on a file.\n\n    Supported types of objects include: ``str``, ``int``, ``float``, ``set``,\n    ``list`` or ``dict``. List and dict are serialized into dzn\n    (multi-dimensional) arrays. The key-set of a dict is used as index-set of\n    dzn arrays. The index-set of a list is implicitly set to ``1 .. len(list)``.\n\n    Parameters\n    ----------\n    objs : dict\n        A dictionary containing the objects to serialize, the keys are the names\n        of the variables.\n    declare : bool\n        Whether to include the declaration of the variable in the statements or\n        just the assignment. Default is ``False``.\n    assign : bool\n        Whether to include assignment of the value in the statements or just the\n        declaration.\n    declare_enums : bool\n        Whether to declare the enums found as types of the objects to serialize.\n        Default is ``True``.\n    wrap : bool\n        Whether to wrap the serialized values.\n    fout : str\n        Path to the output file, if None no output file is written.\n\n    Returns\n    -------\n    list\n        List of strings containing the dzn-encoded objects."
  },
  {
    "code": "def _software_params_to_argparse(parameters):\n    argparse = ArgumentParser()\n    boolean_defaults = {}\n    for parameter in parameters:\n        arg_desc = {\"dest\": parameter.name, \"required\": parameter.required, \"help\": \"\"}\n        if parameter.type == \"Boolean\":\n            default = _to_bool(parameter.defaultParamValue)\n            arg_desc[\"action\"] = \"store_true\" if not default else \"store_false\"\n            boolean_defaults[parameter.name] = default\n        else:\n            python_type = _convert_type(parameter.type)\n            arg_desc[\"type\"] = python_type\n            arg_desc[\"default\"] = None if parameter.defaultParamValue is None else python_type(parameter.defaultParamValue)\n        argparse.add_argument(*_cytomine_parameter_name_synonyms(parameter.name), **arg_desc)\n    argparse.set_defaults(**boolean_defaults)\n    return argparse",
    "docstring": "Converts a SoftwareParameterCollection into an ArgumentParser object.\n\n    Parameters\n    ----------\n    parameters: SoftwareParameterCollection\n        The software parameters\n    Returns\n    -------\n    argparse: ArgumentParser\n        An initialized argument parser"
  },
  {
    "code": "def _get_oauth_params(self, req_kwargs):\n        oauth_params = {}\n        oauth_params['oauth_consumer_key'] = self.consumer_key\n        oauth_params['oauth_nonce'] = sha1(\n            str(random()).encode('ascii')).hexdigest()\n        oauth_params['oauth_signature_method'] = self.signature.NAME\n        oauth_params['oauth_timestamp'] = int(time())\n        if self.access_token is not None:\n            oauth_params['oauth_token'] = self.access_token\n        oauth_params['oauth_version'] = self.VERSION\n        self._parse_optional_params(oauth_params, req_kwargs)\n        return oauth_params",
    "docstring": "Prepares OAuth params for signing."
  },
  {
    "code": "def plotMatches2(listofNValues, errors,\n                 listOfScales, scaleErrors,\n                 fileName = \"images/scalar_matches.pdf\"):\n  w, h = figaspect(0.4)\n  fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(w,h))\n  plotMatches(listofNValues, errors, fileName=None, fig=fig, ax=ax1)\n  plotScaledMatches(listOfScales, scaleErrors, fileName=None, fig=fig, ax=ax2)\n  plt.savefig(fileName)\n  plt.close()",
    "docstring": "Plot two figures side by side in an aspect ratio appropriate for the paper."
  },
  {
    "code": "def iscan(self, *, match=None, count=None):\n        return _ScanIter(lambda cur: self.scan(cur,\n                                               match=match, count=count))",
    "docstring": "Incrementally iterate the keys space using async for.\n\n        Usage example:\n\n        >>> async for key in redis.iscan(match='something*'):\n        ...     print('Matched:', key)"
  },
  {
    "code": "def use(self, tube: str) -> None:\n        self._send_cmd(b'use %b' % tube.encode('ascii'), b'USING')",
    "docstring": "Changes the currently used tube.\n\n        :param tube: The tube to use."
  },
  {
    "code": "def add_package(self, check_name, package):\n        self._package_set.add(package)\n        package_data = self._packages[package.name]\n        self._checks_deps[check_name].append(package)\n        if package.version:\n            versions = package_data['versions']\n            versions[package.version].append(check_name)\n        if package.marker:\n            markers = package_data['markers']\n            markers[package.marker].append(check_name)",
    "docstring": "Add a Package to the catalog for the given check"
  },
  {
    "code": "def features(self):\n        if self._features is None:\n            metadata = self.metadata()\n            if \"features\" in metadata:\n                self._features = metadata[\"features\"]\n            else:\n                self._features = []\n        return self._features",
    "docstring": "lazy fetch and cache features"
  },
  {
    "code": "def enum_models(self, assumptions=[]):\n        if self.glucose:\n            done = False\n            while not done:\n                if self.use_timer:\n                    start_time = time.clock()\n                self.status = pysolvers.glucose41_solve(self.glucose, assumptions)\n                if self.use_timer:\n                    self.call_time = time.clock() - start_time\n                    self.accu_time += self.call_time\n                model = self.get_model()\n                if model:\n                    self.add_clause([-l for l in model])\n                    yield model\n                else:\n                    done = True",
    "docstring": "Iterate over models of the internal formula."
  },
  {
    "code": "def template_substitute(text, **kwargs):\n    for name, value in kwargs.items():\n        placeholder_pattern = \"{%s}\" % name\n        if placeholder_pattern in text:\n            text = text.replace(placeholder_pattern, value)\n    return text",
    "docstring": "Replace placeholders in text by using the data mapping.\n    Other placeholders that is not represented by data is left untouched.\n\n    :param text:   Text to search and replace placeholders.\n    :param data:   Data mapping/dict for placeholder key and values.\n    :return: Potentially modified text with replaced placeholders."
  },
  {
    "code": "def create_new_attachment_by_content_id(self, content_id, attachments, callback=None):\n        if isinstance(attachments, list):\n            assert all(isinstance(at, dict) and \"file\" in list(at.keys()) for at in attachments)\n        elif isinstance(attachments, dict):\n            assert \"file\" in list(attachments.keys())\n        else:\n            assert False\n        return self._service_post_request(\"rest/api/content/{id}/child/attachment\".format(id=content_id),\n                                          headers={\"X-Atlassian-Token\": \"nocheck\"}, files=attachments,\n                                          callback=callback)",
    "docstring": "Add one or more attachments to a Confluence Content entity, with optional comments.\n\n        Comments are optional, but if included there must be as many comments as there are files, and the comments must\n        be in the same order as the files.\n        :param content_id (string): A string containing the id of the attachments content container.\n        :param attachments (list of dicts or dict): This is a list of dictionaries or a dictionary.\n                                                    Each dictionary must have the key\n                                                    \"file\" with a value that is I/O like (file, StringIO, etc.), and\n                                                    may also have a key \"comment\" with a string for file comments.\n        :param callback: OPTIONAL: The callback to execute on the resulting data, before the method returns.\n                         Default: None (no callback, raw data returned).\n        :return: The JSON data returned from the content/{id}/child/attachment endpoint,\n                 or the results of the callback. Will raise requests.HTTPError on bad input, potentially."
  },
  {
    "code": "def _broks(self, broker_name):\n        with self.app.broks_lock:\n            res = self.app.get_broks()\n        return serialize(res, True)",
    "docstring": "Get the broks from the daemon\n\n        This is used by the brokers to get the broks list of a daemon\n\n        :return: Brok list serialized\n        :rtype: dict"
  },
  {
    "code": "def human_readable_number(number, suffix=\"\"):\n    for unit in [\"\", \"K\", \"M\", \"G\", \"T\", \"P\", \"E\", \"Z\"]:\n        if abs(number) < 1024.0:\n            return \"%3.1f%s%s\" % (number, unit, suffix)\n        number /= 1024.0\n    return \"%.1f%s%s\" % (number, \"Y\", suffix)",
    "docstring": "Format the given number into a human-readable string.\n\n    Code adapted from http://stackoverflow.com/a/1094933\n\n    :param variant number: the number (int or float)\n    :param string suffix: the unit of the number\n    :rtype: string"
  },
  {
    "code": "def console_progress_callback(current, maximum, message=None):\n        if maximum > 1000 and current % 1000 != 0 and current != maximum:\n            return\n        if message is not None:\n            LOGGER.info(message['description'])\n        LOGGER.info('Task progress: %i of %i' % (current, maximum))",
    "docstring": "Simple console based callback implementation for tests.\n\n        :param current: Current progress.\n        :type current: int\n\n        :param maximum: Maximum range (point at which task is complete.\n        :type maximum: int\n\n        :param message: Optional message dictionary to containing content\n            we can display to the user. See safe.definitions.analysis_steps\n            for an example of the expected format\n        :type message: dict"
  },
  {
    "code": "def save_auxiliary_files(self, layer, destination):\n        enable_busy_cursor()\n        auxiliary_files = ['xml', 'json']\n        for auxiliary_file in auxiliary_files:\n            source_basename = os.path.splitext(layer.source())[0]\n            source_file = \"%s.%s\" % (source_basename, auxiliary_file)\n            destination_basename = os.path.splitext(destination)[0]\n            destination_file = \"%s.%s\" % (destination_basename, auxiliary_file)\n            try:\n                if os.path.isfile(source_file):\n                    shutil.copy(source_file, destination_file)\n            except (OSError, IOError):\n                display_critical_message_bar(\n                    title=self.tr('Error while saving'),\n                    message=self.tr(\n                        'The destination location must be writable.'),\n                    iface_object=self.iface\n                )\n            except Exception:\n                display_critical_message_bar(\n                    title=self.tr('Error while saving'),\n                    message=self.tr('Something went wrong.'),\n                    iface_object=self.iface\n                )\n        disable_busy_cursor()",
    "docstring": "Save auxiliary files when using the 'save as' function.\n\n        If some auxiliary files (.xml, .json) exist, this function will\n        copy them when the 'save as' function is used on the layer.\n\n        :param layer: The layer which has been saved as.\n        :type layer: QgsMapLayer\n\n        :param destination: The new filename of the layer.\n        :type destination: str"
  },
  {
    "code": "def description(self):\n        if self._description is None:\n            if 'payloadBase64' not in self._properties:\n                self._properties = self.taskqueue.get_task(id=self.id)._properties\n            self._description = base64.b64decode(self._properties.get('payloadBase64', b'')).decode(\"ascii\")\n        return self._description",
    "docstring": "The description for this task.\n\n        See: https://cloud.google.com/appengine/docs/python/taskqueue/rest/tasks\n\n        :rtype: string\n        :returns: The description for this task."
  },
  {
    "code": "def credentials(self):\n        if self.filename:\n            db_filename = os.path.join(os.getcwd(), self.filename)\n        else:\n            db_filename = None\n        return {\n            \"username\": self.username,\n            \"password\": self.password,\n            \"hostname\": self.hostname,\n            \"port\": self.port,\n            \"filename\": db_filename,\n            \"dbname\": self.dbname,\n            \"dbtype\": self.dbtype,\n            \"schemas\": self.schemas,\n            \"limit\": self.limit,\n            \"keys_per_column\": self.keys_per_column,\n        }",
    "docstring": "Dict representation of all credentials for the database."
  },
  {
    "code": "def reference_of(selector: shapeLabel, cntxt: Union[Context, ShExJ.Schema] ) -> Optional[ShExJ.shapeExpr]:\n    schema = cntxt.schema if isinstance(cntxt, Context) else cntxt\n    if selector is START:\n        return schema.start\n    for expr in schema.shapes:\n        if not isinstance(expr, ShExJ.ShapeExternal) and expr.id == selector:\n            return expr\n    return schema.start if schema.start is not None and schema.start.id == selector else None",
    "docstring": "Return the shape expression in the schema referenced by selector, if any\n\n    :param cntxt: Context node or ShEx Schema\n    :param selector: identifier of element to select within the schema\n    :return:"
  },
  {
    "code": "def angledependentairtransmission_errorprop(twotheta, dtwotheta, mu_air,\n                                            dmu_air, sampletodetectordistance,\n                                            dsampletodetectordistance):\n    return (np.exp(mu_air * sampletodetectordistance / np.cos(twotheta)),\n            np.sqrt(dmu_air ** 2 * sampletodetectordistance ** 2 *\n                    np.exp(2 * mu_air * sampletodetectordistance / np.cos(twotheta))\n                    / np.cos(twotheta) ** 2 + dsampletodetectordistance ** 2 *\n                    mu_air ** 2 * np.exp(2 * mu_air * sampletodetectordistance /\n                                         np.cos(twotheta)) /\n                    np.cos(twotheta) ** 2 + dtwotheta ** 2 * mu_air ** 2 *\n                    sampletodetectordistance ** 2 *\n                    np.exp(2 * mu_air * sampletodetectordistance / np.cos(twotheta))\n                     * np.sin(twotheta) ** 2 / np.cos(twotheta) ** 4)\n            )",
    "docstring": "Correction for the angle dependent absorption of air in the scattered\n    beam path, with error propagation\n\n    Inputs:\n            twotheta: matrix of two-theta values\n            dtwotheta: absolute error matrix of two-theta\n            mu_air: the linear absorption coefficient of air\n            dmu_air: error of the linear absorption coefficient of air\n            sampletodetectordistance: sample-to-detector distance\n            dsampletodetectordistance: error of the sample-to-detector distance\n\n    1/mu_air and sampletodetectordistance should have the same dimension\n\n    The scattering intensity matrix should be multiplied by the resulting\n    correction matrix."
  },
  {
    "code": "def tags(self, where, archiver=\"\", timeout=DEFAULT_TIMEOUT):\n        return self.query(\"select * where {0}\".format(where), archiver, timeout).get('metadata',{})",
    "docstring": "Retrieves tags for all streams matching the given WHERE clause\n\n        Arguments:\n        [where]: the where clause (e.g. 'path like \"keti\"', 'SourceName = \"TED Main\"')\n        [archiver]: if specified, this is the archiver to use. Else, it will run on the first archiver passed\n                    into the constructor for the client\n        [timeout]: time in seconds to wait for a response from the archiver"
  },
  {
    "code": "def show_event_handlers(self, stream=sys.stdout, verbose=0):\n        lines = [\"List of event handlers installed:\"]\n        for handler in self.event_handlers:\n            if verbose:\n                lines.extend(handler.__class__.cls2str().split(\"\\n\"))\n            else:\n                lines.extend(str(handler).split(\"\\n\"))\n        stream.write(\"\\n\".join(lines))\n        stream.write(\"\\n\")",
    "docstring": "Print to `stream` the event handlers installed for this flow."
  },
  {
    "code": "def buy(ctx, buy_amount, buy_asset, price, sell_asset, order_expiration, account):\n    amount = Amount(buy_amount, buy_asset)\n    price = Price(\n        price, base=sell_asset, quote=buy_asset, bitshares_instance=ctx.bitshares\n    )\n    print_tx(\n        price.market.buy(price, amount, account=account, expiration=order_expiration)\n    )",
    "docstring": "Buy a specific asset at a certain rate against a base asset"
  },
  {
    "code": "def set_attributes(self, **attributes):\n        auto_set = IxeObject.get_auto_set()\n        IxeObject.set_auto_set(False)\n        for name, value in attributes.items():\n            setattr(self, name, value)\n        if auto_set:\n            self.ix_set()\n        IxeObject.set_auto_set(auto_set)",
    "docstring": "Set group of attributes without calling set between attributes regardless of global auto_set.\n\n        Set will be called only after all attributes are set based on global auto_set.\n\n        :param attributes: dictionary of <attribute, value> to set."
  },
  {
    "code": "def share_with_names(self):\n        for container in self.share_with:\n            if isinstance(container, six.string_types):\n                yield container\n            else:\n                yield container.container_name",
    "docstring": "The names of the containers that we share with the running container"
  },
  {
    "code": "def migrate_autoload_details(autoload_details, shell_name, shell_type):\n    mapping = {}\n    for resource in autoload_details.resources:\n        resource.model = \"{shell_name}.{model}\".format(shell_name=shell_name, model=resource.model)\n        mapping[resource.relative_address] = resource.model\n    for attribute in autoload_details.attributes:\n        if not attribute.relative_address:\n            attribute.attribute_name = \"{shell_type}.{attr_name}\".format(shell_type=shell_type,\n                                                                         attr_name=attribute.attribute_name)\n        else:\n            attribute.attribute_name = \"{model}.{attr_name}\".format(model=mapping[attribute.relative_address],\n                                                                    attr_name=attribute.attribute_name)\n    return autoload_details",
    "docstring": "Migrate autoload details. Add namespace for attributes\n\n    :param autoload_details:\n    :param shell_name:\n    :param shell_type:\n    :return:"
  },
  {
    "code": "def interleave_longest(*iterables):\n    i = chain.from_iterable(zip_longest(*iterables, fillvalue=_marker))\n    return (x for x in i if x is not _marker)",
    "docstring": "Return a new iterable yielding from each iterable in turn,\n    skipping any that are exhausted.\n\n        >>> list(interleave_longest([1, 2, 3], [4, 5], [6, 7, 8]))\n        [1, 4, 6, 2, 5, 7, 3, 8]\n\n    This function produces the same output as :func:`roundrobin`, but may\n    perform better for some inputs (in particular when the number of iterables\n    is large)."
  },
  {
    "code": "def get(self):\n        return {k:v for k,v in list(self.options.items()) if k in self._allowed_layout}",
    "docstring": "Get layout options."
  },
  {
    "code": "def _init_threads(self):\n        if self._io_thread is None:\n            self._io_thread = Thread(target=self._select)\n            self._io_thread.start()\n        if self._writer_thread is None:\n            self._writer_thread = Thread(target=self._writer)\n            self._writer_thread.start()",
    "docstring": "Initializes the IO and Writer threads"
  },
  {
    "code": "def _absolute(self, path):\n        path = FilePath(path)\n        if isabs(path):\n            return path\n        else:\n            return self.WorkingDir + path",
    "docstring": "Convert a filename to an absolute path"
  },
  {
    "code": "def highlight_multi_regex(str_, pat_to_color, reflags=0):\n    colored = str_\n    to_replace = []\n    for pat, color in pat_to_color.items():\n        matches = list(re.finditer(pat, str_, flags=reflags))\n        for match in matches:\n            start = match.start()\n            end = match.end()\n            to_replace.append((end, start, color))\n    for tup in reversed(sorted(to_replace)):\n        end, start, color = tup\n        colored_part = color_text(colored[start:end], color)\n        colored = colored[:start] + colored_part + colored[end:]\n    return colored",
    "docstring": "FIXME Use pygments instead. must be mututally exclusive"
  },
  {
    "code": "def get_instance(self, payload):\n        return ExecutionStepInstance(\n            self._version,\n            payload,\n            flow_sid=self._solution['flow_sid'],\n            execution_sid=self._solution['execution_sid'],\n        )",
    "docstring": "Build an instance of ExecutionStepInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance\n        :rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance"
  },
  {
    "code": "def stmt_type(obj, mk=True):\n    if isinstance(obj, Statement) and mk:\n        return type(obj)\n    else:\n        return type(obj).__name__",
    "docstring": "Return standardized, backwards compatible object type String.\n\n    This is a temporary solution to make sure type comparisons and\n    matches keys of Statements and related classes are backwards\n    compatible."
  },
  {
    "code": "def iterate_specific_packet_range():\n    now = datetime.utcnow()\n    start = now - timedelta(hours=1)\n    total = 0\n    for packet in archive.list_packets(start=start, stop=now):\n        total += 1\n    print('Found', total, 'packets in range')",
    "docstring": "Count the number of packets in a specific range."
  },
  {
    "code": "def AsDict(self, dt=True):\n        data = {}\n        if self.name:\n            data['name'] = self.name\n            data['mlkshk_url'] = self.mlkshk_url\n        if self.profile_image_url:\n            data['profile_image_url'] = self.profile_image_url\n        if self.id:\n            data['id'] = self.id\n        if self.about:\n            data['about'] = self.about\n        if self.website:\n            data['website'] = self.website\n        if self.shakes:\n            data['shakes'] = [shk.AsDict(dt=dt) for shk in self.shakes]\n        data['shake_count'] = self.shake_count\n        return data",
    "docstring": "A dict representation of this User instance.\n\n        The return value uses the same key names as the JSON representation.\n\n        Args:\n            dt (bool): If True, return dates as python datetime objects. If\n            False, return dates as ISO strings.\n\n        Return:\n            A dict representing this User instance"
  },
  {
    "code": "def delete_note(self, note_id):\n        note, status = self.trash_note(note_id)\n        if (status == -1):\n            return note, status\n        params = '/i/%s' % (str(note_id))\n        request = Request(url=DATA_URL+params, method='DELETE')\n        request.add_header(self.header, self.get_token())\n        try:\n            response = urllib2.urlopen(request)\n        except IOError as e:\n            return e, -1\n        except HTTPError as e:\n            if e.code == 401:\n                raise SimplenoteLoginFailed('Login to Simplenote API failed! Check Token.')\n            else:\n                return e, -1\n        return {}, 0",
    "docstring": "Method to permanently delete a note\n\n        Arguments:\n            - note_id (string): key of the note to trash\n\n        Returns:\n            A tuple `(note, status)`\n\n            - note (dict): an empty dict or an error message\n            - status (int): 0 on success and -1 otherwise"
  },
  {
    "code": "def click(self, locator, params=None, timeout=None):\n        self._click(locator, params, timeout)",
    "docstring": "Click web element.\n\n        :param locator: locator tuple or WebElement instance\n        :param params: (optional) locator parameters\n        :param timeout: (optional) time to wait for element\n        :return: None"
  },
  {
    "code": "def delete(self, interface, vrid):\n        vrrp_str = \"no vrrp %d\" % vrid\n        return self.configure_interface(interface, vrrp_str)",
    "docstring": "Deletes a vrrp instance from an interface\n\n        Note:\n            This method will attempt to delete the vrrp from the node's\n            operational config. If the vrrp does not exist on the\n            interface then this method will not perform any changes\n            but still return True\n\n        Args:\n            interface (string): The interface to configure.\n            vrid (integer): The vrid number for the vrrp to be deleted.\n\n        Returns:\n            True if the vrrp could be deleted otherwise False (see Node)"
  },
  {
    "code": "def swap(self, c2):\n        inv = False\n        c1 = self\n        if c1.order > c2.order:\n            ct = c1\n            c1 = c2\n            c2 = ct\n            inv = True\n        return inv, c1, c2",
    "docstring": "put the order of currencies as market standard"
  },
  {
    "code": "def _namespace_requested(self, namespace):\n        if namespace is None:\n            return False\n        namespace_tuple = self._tuplefy_namespace(namespace)\n        if namespace_tuple[0] in IGNORE_DBS:\n            return False\n        elif namespace_tuple[1] in IGNORE_COLLECTIONS:\n            return False\n        else:\n            return self._tuple_requested(namespace_tuple)",
    "docstring": "Checks whether the requested_namespaces contain the provided\n            namespace"
  },
  {
    "code": "def get_templatetag_module(cls):\n        if cls not in CacheTag._templatetags_modules:\n            all_tags = cls.get_all_tags_and_filters_by_function()['tags']\n            CacheTag._templatetags_modules[cls] = all_tags[CacheTag._templatetags[cls]['cache']][0]\n        return CacheTag._templatetags_modules[cls]",
    "docstring": "Return the templatetags module name for which the current class is used.\n        It's used to render the nocache blocks by loading the correct module"
  },
  {
    "code": "def create_api_network_ipv4(self):\n        return ApiNetworkIPv4(\n            self.networkapi_url,\n            self.user,\n            self.password,\n            self.user_ldap)",
    "docstring": "Get an instance of Api Networkv4 services facade."
  },
  {
    "code": "def swap(ctx):\n    controller = ctx.obj['controller']\n    click.echo('Swapping slots...')\n    try:\n        controller.swap_slots()\n    except YkpersError as e:\n        _failed_to_write_msg(ctx, e)",
    "docstring": "Swaps the two slot configurations."
  },
  {
    "code": "def _check_field_names(self, field_names):\n        if field_names:\n            for field_name in field_names:\n                try:\n                    self.column[field_name]\n                except KeyError:\n                    raise InvalidIndexError('Trying to use non indexed field \"%s\"' % field_name)",
    "docstring": "Raises InvalidIndexError if any of a field_name in field_names is\n        not indexed."
  },
  {
    "code": "def _set_or_check_remote_id(self, remote_id):\n    if not self.remote_id:\n      assert self.closed_state == self.ClosedState.PENDING, 'Bad ClosedState!'\n      self.remote_id = remote_id\n      self.closed_state = self.ClosedState.OPEN\n    elif self.remote_id != remote_id:\n      raise usb_exceptions.AdbProtocolError(\n          '%s remote-id change to %s', self, remote_id)",
    "docstring": "Set or check the remote id."
  },
  {
    "code": "def local_machine_uuid():\n    result = subprocess.check_output(\n        'hal-get-property --udi '\n        '/org/freedesktop/Hal/devices/computer '\n        '--key system.hardware.uuid'.split()\n        ).strip()\n    return uuid.UUID(hex=result)",
    "docstring": "Return local machine unique identifier.\n\n    >>> uuid = local_machine_uuid()"
  },
  {
    "code": "def get_mean_masked_features_distance(mean_features_0,\n                                      mean_features_1,\n                                      mean_masks_0,\n                                      mean_masks_1,\n                                      n_features_per_channel=None,\n                                      ):\n    assert n_features_per_channel > 0\n    mu_0 = mean_features_0.ravel()\n    mu_1 = mean_features_1.ravel()\n    omeg_0 = mean_masks_0\n    omeg_1 = mean_masks_1\n    omeg_0 = np.repeat(omeg_0, n_features_per_channel)\n    omeg_1 = np.repeat(omeg_1, n_features_per_channel)\n    d_0 = mu_0 * omeg_0\n    d_1 = mu_1 * omeg_1\n    return np.linalg.norm(d_0 - d_1)",
    "docstring": "Compute the distance between the mean masked features."
  },
  {
    "code": "def _assert_valid_categorical_missing_value(value):\n    label_types = LabelArray.SUPPORTED_SCALAR_TYPES\n    if not isinstance(value, label_types):\n        raise TypeError(\n            \"Categorical terms must have missing values of type \"\n            \"{types}.\".format(\n                types=' or '.join([t.__name__ for t in label_types]),\n            )\n        )",
    "docstring": "Check that value is a valid categorical missing_value.\n\n    Raises a TypeError if the value is cannot be used as the missing_value for\n    a categorical_dtype Term."
  },
  {
    "code": "def create(self):\n        headers = dict()\n        if self.tfa_token:\n            headers[\"X-GitHub-OTP\"] = self.tfa_token\n        token_name = self.app_name + platform.node()\n        payload = dict(note=token_name, scopes=self.scopes)\n        response = requests.post(\n                self.api_url + \"authorizations\", auth=(self.user, self.password),\n                headers=headers, json=payload\n        )\n        if response.status_code == 401 and \"required\" in response.headers.get(\"X-GitHub-OTP\", \"\"):\n            raise TFARequired(\"TFA required for the user\")\n        if response.status_code == 422:\n            raise AlreadyExistsError(\"APP already exists. Please delete {} token\".format(token_name))\n        if response.status_code == 401:\n            raise BadPassword(\"Bad User/Password\")\n        response.raise_for_status()\n        return response.json()[\"token\"]",
    "docstring": "Creates a token\n\n        It uses the app_name as the notes and the scopes are\n        the permissions required by the application. See those\n        in github when configuring an app token\n\n        Raises a TFARequired if a two factor is required after\n        the atempt to create it without having call tfa before"
  },
  {
    "code": "def which(program):\n    \" Check program is exists. \"\n    head, _ = op.split(program)\n    if head:\n        if is_exe(program):\n            return program\n    else:\n        for path in environ[\"PATH\"].split(pathsep):\n            exe_file = op.join(path, program)\n            if is_exe(exe_file):\n                return exe_file\n    return None",
    "docstring": "Check program is exists."
  },
  {
    "code": "def __insert_data(postid, userid, rating):\n        uid = tools.get_uuid()\n        TabRating.create(\n            uid=uid,\n            post_id=postid,\n            user_id=userid,\n            rating=rating,\n            timestamp=tools.timestamp(),\n        )\n        return uid",
    "docstring": "Inert new record."
  },
  {
    "code": "def exhaustive_iri_check( self,\n                              ontology:pd.DataFrame,\n                              iri_predicate:str,\n                              diff:bool=True, ) -> Tuple[list]:\n        inside, outside = [], []\n        header = ['Index'] + list(ontology.columns)\n        for row in ontology.itertuples():\n            row = {header[i]:val for i, val in enumerate(row)}\n            entity_iri = row[iri_predicate]\n            if isinstance(entity_iri, list):\n                if len(entity_iri) != 0:\n                    exit('Need to have only 1 iri in the cell from the onotology.')\n                else:\n                    entity_iri = entity_iri[0]\n            ilx_row = self.iri2row.get(entity_iri)\n            if ilx_row:\n                inside.append({\n                    'external_ontology_row': row,\n                    'ilx_rows': [ilx_row],\n                })\n            else:\n                outside.append(row)\n        if diff:\n            diff = self.__exhaustive_diff(inside)\n            return inside, outside, diff\n        return inside, outside",
    "docstring": "All entities with conflicting iris gets a full diff to see if they belong\n\n            Args:\n                ontology: pandas DataFrame created from an ontology where the colnames are predicates\n                    and if classes exist it is also thrown into a the colnames.\n                iri_predicate: usually in qname form and is the colname of the DataFrame for iri\n                    Default is \"iri\" for graph2pandas module\n                diff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2\n            Returns:\n                inside: entities that are inside of InterLex\n                outside: entities NOT in InterLex\n                diff (optional): List[List[dict]]... so complicated but usefull diff between matches only"
  },
  {
    "code": "def numRegisteredForRoleName(event, roleName):\r\n    if not isinstance(event, Event):\r\n        return None\r\n    try:\r\n        role = DanceRole.objects.get(name=roleName)\r\n    except ObjectDoesNotExist:\r\n        return None\r\n    return event.numRegisteredForRole(role)",
    "docstring": "This tag allows one to access the number of registrations\r\n    for any dance role using only the role's name."
  },
  {
    "code": "def parse_section_packages__find(self, section_options):\n        section_data = self._parse_section_to_dict(\n            section_options, self._parse_list)\n        valid_keys = ['where', 'include', 'exclude']\n        find_kwargs = dict(\n            [(k, v) for k, v in section_data.items() if k in valid_keys and v])\n        where = find_kwargs.get('where')\n        if where is not None:\n            find_kwargs['where'] = where[0]\n        return find_kwargs",
    "docstring": "Parses `packages.find` configuration file section.\n\n        To be used in conjunction with _parse_packages().\n\n        :param dict section_options:"
  },
  {
    "code": "def fromkeys(cls, iterable, value, **kwargs):\n        return cls(((k, value) for k in iterable), **kwargs)",
    "docstring": "Return a new pqict mapping keys from an iterable to the same value."
  },
  {
    "code": "def authorize_security_group_egress(self,\n                                        group_id,\n                                        ip_protocol,\n                                        from_port=None,\n                                        to_port=None,\n                                        src_group_id=None,\n                                        cidr_ip=None):\n        params = {\n            'GroupId': group_id,\n            'IpPermissions.1.IpProtocol': ip_protocol\n        }\n        if from_port is not None:\n            params['IpPermissions.1.FromPort'] = from_port\n        if to_port is not None:\n            params['IpPermissions.1.ToPort'] = to_port\n        if src_group_id is not None:\n            params['IpPermissions.1.Groups.1.GroupId'] = src_group_id\n        if cidr_ip is not None:\n            params['IpPermissions.1.IpRanges.1.CidrIp'] = cidr_ip\n        return self.get_status('AuthorizeSecurityGroupEgress',\n                               params, verb='POST')",
    "docstring": "The action adds one or more egress rules to a VPC security\n        group. Specifically, this action permits instances in a\n        security group to send traffic to one or more destination\n        CIDR IP address ranges, or to one or more destination\n        security groups in the same VPC."
  },
  {
    "code": "def _ParseKeysFromFindSpecs(self, parser_mediator, win_registry, find_specs):\n    searcher = dfwinreg_registry_searcher.WinRegistrySearcher(win_registry)\n    for registry_key_path in iter(searcher.Find(find_specs=find_specs)):\n      if parser_mediator.abort:\n        break\n      registry_key = searcher.GetKeyByPath(registry_key_path)\n      self._ParseKey(parser_mediator, registry_key)",
    "docstring": "Parses the Registry keys from FindSpecs.\n\n    Args:\n      parser_mediator (ParserMediator): parser mediator.\n      win_registry (dfwinreg.WinRegistryKey): root Windows Registry key.\n      find_specs (dfwinreg.FindSpecs): Keys to search for."
  },
  {
    "code": "def get_token(self):\n        signed_headers = self._get_v4_signed_headers()\n        for header in self.HEADERS:\n            signed_headers[header] = self.HEADERS[header]\n        resp = post_with_retry(self.cerberus_url + '/v2/auth/sts-identity', headers=signed_headers)\n        throw_if_bad_response(resp)\n        token = resp.json()['client_token']\n        iam_principal_arn = resp.json()['metadata']['aws_iam_principal_arn']\n        if self.verbose:\n            print('Successfully authenticated with Cerberus as {}'.format(iam_principal_arn), file=sys.stderr)\n        logger.info('Successfully authenticated with Cerberus as {}'.format(iam_principal_arn))\n        return token",
    "docstring": "Returns a client token from Cerberus"
  },
  {
    "code": "def assert_boolean_false(expr, msg_fmt=\"{msg}\"):\n    if expr is not False:\n        msg = \"{!r} is not False\".format(expr)\n        fail(msg_fmt.format(msg=msg, expr=expr))",
    "docstring": "Fail the test unless the expression is the constant False.\n\n    >>> assert_boolean_false(False)\n    >>> assert_boolean_false(0)\n    Traceback (most recent call last):\n        ...\n    AssertionError: 0 is not False\n\n    The following msg_fmt arguments are supported:\n    * msg - the default error message\n    * expr - tested expression"
  },
  {
    "code": "def _git_config(cwd, user, password, output_encoding=None):\n    contextkey = 'git.config.' + cwd\n    if contextkey not in __context__:\n        git_dir = rev_parse(cwd,\n                            opts=['--git-dir'],\n                            user=user,\n                            password=password,\n                            ignore_retcode=True,\n                            output_encoding=output_encoding)\n        if not os.path.isabs(git_dir):\n            paths = (cwd, git_dir, 'config')\n        else:\n            paths = (git_dir, 'config')\n        __context__[contextkey] = os.path.join(*paths)\n    return __context__[contextkey]",
    "docstring": "Helper to retrieve git config options"
  },
  {
    "code": "def random_walk(self, path_length, alpha=0, rand=random.Random(), start=None):\n    G = self\n    if start:\n      path = [start]\n    else:\n      path = [rand.choice(list(G.keys()))]\n    while len(path) < path_length:\n      cur = path[-1]\n      if len(G[cur]) > 0:\n        if rand.random() >= alpha:\n          path.append(rand.choice(G[cur]))\n        else:\n          path.append(path[0])\n      else:\n        break\n    return [str(node) for node in path]",
    "docstring": "Returns a truncated random walk.\n\n        path_length: Length of the random walk.\n        alpha: probability of restarts.\n        start: the start node of the random walk."
  },
  {
    "code": "def _output(cls, fluents: Sequence[FluentPair]) -> Sequence[tf.Tensor]:\n        return tuple(cls._dtype(t) for t in cls._tensors(fluents))",
    "docstring": "Returns output tensors for `fluents`."
  },
  {
    "code": "def pdf(self, x_test):\n\t\tN,D = self.data.shape\n\t\tx_test = np.asfortranarray(x_test)\n\t\tx_test = x_test.reshape([-1, D])\n\t\tpdfs = self._individual_pdfs(x_test)\n\t\tif self.fully_dimensional:\n\t\t\tpdfs = np.sum(np.prod(pdfs, axis=-1)*self.weights[None, :], axis=-1)\n\t\telse:\n\t\t\tpdfs = np.prod(np.sum(pdfs*self.weights[None,:,None], axis=-2), axis=-1)\n\t\treturn(pdfs)",
    "docstring": "Computes the probability density function at all x_test"
  },
  {
    "code": "def reload(self, client=None):\n        path = self.reload_path\n        client = self._require_client(client)\n        query_params = {}\n        if self.user_project is not None:\n            query_params[\"userProject\"] = self.user_project\n        self.entities.clear()\n        found = client._connection.api_request(\n            method=\"GET\", path=path, query_params=query_params\n        )\n        self.loaded = True\n        for entry in found.get(\"items\", ()):\n            self.add_entity(self.entity_from_dict(entry))",
    "docstring": "Reload the ACL data from Cloud Storage.\n\n        If :attr:`user_project` is set, bills the API request to that project.\n\n        :type client: :class:`~google.cloud.storage.client.Client` or\n                      ``NoneType``\n        :param client: Optional. The client to use.  If not passed, falls back\n                       to the ``client`` stored on the ACL's parent."
  },
  {
    "code": "def stats_for(self, dt):\n        if not isinstance(dt, datetime):\n            raise TypeError('stats_for requires a datetime object!')\n        return self._client.get('{}/stats/'.format(dt.strftime('%Y/%m')))",
    "docstring": "Returns stats for the month containing the given datetime"
  },
  {
    "code": "def _get_dialog_title(self):\n        title_filetype = self.filetype[0].upper() + self.filetype[1:]\n        if self.filetype == \"print\":\n            title_export = \"\"\n        else:\n            title_export = \" export\"\n        return _(\"{filetype}{export} options\").format(filetype=title_filetype,\n                                                      export=title_export)",
    "docstring": "Returns title string"
  },
  {
    "code": "def set_centralized_assembled_rows_cols(self, irn, jcn):\n        if self.myid != 0:\n            return\n        assert irn.size == jcn.size\n        self._refs.update(irn=irn, jcn=jcn)\n        self.id.nz = irn.size\n        self.id.irn = self.cast_array(irn)\n        self.id.jcn = self.cast_array(jcn)",
    "docstring": "Set assembled matrix indices on processor 0.\n\n        The row and column indices (irn & jcn) should be one based."
  },
  {
    "code": "def create_pre_execute(task_params, parameter_map):\n    gp_params = [_PRE_EXECUTE_INIT_TEMPLATE]\n    for task_param in task_params:\n        if task_param['direction'].upper() == 'OUTPUT':\n            continue\n        data_type = task_param['type'].upper()\n        if 'dimensions' in task_param:\n            data_type += 'ARRAY'\n        if data_type in parameter_map:\n            gp_params.append(parameter_map[data_type].pre_execute().substitute(task_param))\n    gp_params.append(_PRE_EXECUTE_CLEANUP_TEMPLATE)\n    return ''.join(gp_params)",
    "docstring": "Builds the code block for the GPTool Execute method before the job is\n    submitted based on the input task_params.\n\n    :param task_params: A list of task parameters from the task info structure.\n    :return: A string representing the code block to the GPTool Execute method."
  },
  {
    "code": "def get_cfg(ast_func):\n    cfg_func = cfg.Function()\n    for ast_var in ast_func.input_variable_list:\n        cfg_var = cfg_func.get_variable(ast_var.name)\n        cfg_func.add_input_variable(cfg_var)\n    for ast_var in ast_func.output_variable_list:\n        cfg_var = cfg_func.get_variable(ast_var.name)\n        cfg_func.add_output_variable(cfg_var)\n    bb_start  = cfg.BasicBlock()\n    cfg_func.add_basic_block(bb_start)\n    for stmt in ast_func.body:\n        bb_temp = bb_start\n        bb_temp = process_cfg(stmt, bb_temp, cfg_func)\n    cfg_func.clean_up()\n    cfg_func.add_summary(ast_func.summary)\n    return cfg_func",
    "docstring": "Traverses the AST and returns the corresponding CFG\n\n    :param ast_func: The AST representation of function\n    :type ast_func: ast.Function\n\n    :returns: The CFG representation of the function\n    :rtype: cfg.Function"
  },
  {
    "code": "def find_next_word_beginning(self, count=1, WORD=False):\n        if count < 0:\n            return self.find_previous_word_beginning(count=-count, WORD=WORD)\n        regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE\n        iterator = regex.finditer(self.text_after_cursor)\n        try:\n            for i, match in enumerate(iterator):\n                if i == 0 and match.start(1) == 0:\n                    count += 1\n                if i + 1 == count:\n                    return match.start(1)\n        except StopIteration:\n            pass",
    "docstring": "Return an index relative to the cursor position pointing to the start\n        of the next word. Return `None` if nothing was found."
  },
  {
    "code": "def _did_create_child(self, connection):\n        response = connection.response\n        try:\n            connection.user_info['nurest_object'].from_dict(response.data[0])\n        except Exception:\n            pass\n        return self._did_perform_standard_operation(connection)",
    "docstring": "Callback called after adding a new child nurest_object"
  },
  {
    "code": "def walk(self, top, topdown=True, onerror=None, **kwargs):\n        try:\n            listing = self.list_status(top, **kwargs)\n        except HdfsException as e:\n            if onerror is not None:\n                onerror(e)\n            return\n        dirnames, filenames = [], []\n        for f in listing:\n            if f.type == 'DIRECTORY':\n                dirnames.append(f.pathSuffix)\n            elif f.type == 'FILE':\n                filenames.append(f.pathSuffix)\n            else:\n                raise AssertionError(\"Unexpected type {}\".format(f.type))\n        if topdown:\n            yield top, dirnames, filenames\n        for name in dirnames:\n            new_path = posixpath.join(top, name)\n            for x in self.walk(new_path, topdown, onerror, **kwargs):\n                yield x\n        if not topdown:\n            yield top, dirnames, filenames",
    "docstring": "See ``os.walk`` for documentation"
  },
  {
    "code": "def smallest_flagged(heap, row):\n    ind = heap[0, row]\n    dist = heap[1, row]\n    flag = heap[2, row]\n    min_dist = np.inf\n    result_index = -1\n    for i in range(ind.shape[0]):\n        if flag[i] == 1 and dist[i] < min_dist:\n            min_dist = dist[i]\n            result_index = i\n    if result_index >= 0:\n        flag[result_index] = 0.0\n        return int(ind[result_index])\n    else:\n        return -1",
    "docstring": "Search the heap for the smallest element that is\n    still flagged.\n\n    Parameters\n    ----------\n    heap: array of shape (3, n_samples, n_neighbors)\n        The heaps to search\n\n    row: int\n        Which of the heaps to search\n\n    Returns\n    -------\n    index: int\n        The index of the smallest flagged element\n        of the ``row``th heap, or -1 if no flagged\n        elements remain in the heap."
  },
  {
    "code": "def impute(self, M_c, X_L, X_D, Y, Q, seed, n):\n        get_next_seed = make_get_next_seed(seed)\n        e = su.impute(M_c, X_L, X_D, Y, Q, n, get_next_seed)\n        return e",
    "docstring": "Impute values from predictive distribution of the given latent state.\n\n        :param Y: A list of constraints to apply when sampling.  Each constraint\n            is a triplet of (r,d,v): r is the row index, d is the column\n            index and v is the value of the constraint\n        :type Y: list of lists\n        :param Q: A list of values to sample.  Each value is doublet of (r, d):\n                  r is the row index, d is the column index\n        :type Q: list of lists\n        :param n: the number of samples to use in the imputation\n        :type n: int\n\n        :returns: list of floats -- imputed values in the same order as\n            specified by Q"
  },
  {
    "code": "def check_cores(cores):\n    cores = min(multiprocessing.cpu_count(), cores)\n    if six.PY3:\n        log = logging.getLogger(\"Aegean\")\n        log.info(\"Multi-cores not supported in python 3+, using one core\")\n        return 1\n    try:\n        queue = pprocess.Queue(limit=cores, reuse=1)\n    except:\n        cores = 1\n    else:\n        try:\n            _ = queue.manage(pprocess.MakeReusable(fix_shape))\n        except:\n            cores = 1\n    return cores",
    "docstring": "Determine how many cores we are able to use.\n    Return 1 if we are not able to make a queue via pprocess.\n\n    Parameters\n    ----------\n    cores : int\n        The number of cores that are requested.\n\n    Returns\n    -------\n    cores : int\n        The number of cores available."
  },
  {
    "code": "def _contained_parameters(expression):\n    if isinstance(expression, BinaryExp):\n        return _contained_parameters(expression.op1) | _contained_parameters(expression.op2)\n    elif isinstance(expression, Function):\n        return _contained_parameters(expression.expression)\n    elif isinstance(expression, Parameter):\n        return {expression}\n    else:\n        return set()",
    "docstring": "Determine which parameters are contained in this expression.\n\n    :param Expression expression: expression involving parameters\n    :return: set of parameters contained in this expression\n    :rtype: set"
  },
  {
    "code": "def digest(dna, restriction_enzyme):\n    pattern = restriction_enzyme.recognition_site\n    located = dna.locate(pattern)\n    if not located[0] and not located[1]:\n        return [dna]\n    pattern_len = len(pattern)\n    r_indices = [len(dna) - index - pattern_len for index in\n                 located[1]]\n    if pattern.is_palindrome():\n        r_indices = [index for index in r_indices if index not in\n                     located[0]]\n    cut_sites = sorted(located[0] + r_indices)\n    current = [dna]\n    for cut_site in cut_sites[::-1]:\n        new = _cut(current, cut_site, restriction_enzyme)\n        current.append(new[1])\n        current.append(new[0])\n    current.reverse()\n    if dna.circular:\n        current[0] = current.pop() + current[0]\n    return current",
    "docstring": "Restriction endonuclease reaction.\n\n    :param dna: DNA template to digest.\n    :type dna: coral.DNA\n    :param restriction_site: Restriction site to use.\n    :type restriction_site: RestrictionSite\n    :returns: list of digested DNA fragments.\n    :rtype: coral.DNA list"
  },
  {
    "code": "def _init_grad(self):\n        if self.grad_req == 'null':\n            self._grad = None\n            return\n        self._grad = [ndarray.zeros(shape=i.shape, dtype=i.dtype, ctx=i.context,\n                                    stype=self._grad_stype) for i in self._data]\n        autograd.mark_variables(self._check_and_get(self._data, list),\n                                self._grad, self.grad_req)",
    "docstring": "Initialize grad buffers."
  },
  {
    "code": "def enableSync(self, url, definition = None):\n        adminFS = AdminFeatureService(url=url, securityHandler=self._securityHandler)\n        cap = str(adminFS.capabilities)\n        existingDef = {}\n        enableResults = 'skipped'\n        if 'Sync' in cap:\n            return \"Sync is already enabled\"\n        else:\n            capItems = cap.split(',')\n            capItems.append('Sync')\n            existingDef['capabilities'] = ','.join(capItems)\n            enableResults = adminFS.updateDefinition(json_dict=existingDef)\n            if 'error' in enableResults:\n                return enableResults['error']\n        adminFS = None\n        del adminFS\n        return enableResults",
    "docstring": "Enables Sync capability for an AGOL feature service.\n\n        Args:\n            url (str): The URL of the feature service.\n            definition (dict): A dictionary containing valid definition values. Defaults to ``None``.\n        Returns:\n            dict: The result from :py:func:`arcrest.hostedservice.service.AdminFeatureService.updateDefinition`."
  },
  {
    "code": "def handle(self, sock, read_data, path, headers):\n        \"Just waits, and checks for other actions to replace us\"\n        for i in range(self.timeout // self.check_interval):\n            eventlet.sleep(self.check_interval)\n            action = self.balancer.resolve_host(self.host)\n            if not isinstance(action, Spin):\n                return action.handle(sock, read_data, path, headers)\n        action = Static(self.balancer, self.host, self.matched_host, type=\"timeout\")\n        return action.handle(sock, read_data, path, headers)",
    "docstring": "Just waits, and checks for other actions to replace us"
  },
  {
    "code": "def face_adjacency_angles(self):\n        pairs = self.face_normals[self.face_adjacency]\n        angles = geometry.vector_angle(pairs)\n        return angles",
    "docstring": "Return the angle between adjacent faces\n\n        Returns\n        --------\n        adjacency_angle : (n,) float\n          Angle between adjacent faces\n          Each value corresponds with self.face_adjacency"
  },
  {
    "code": "def get_banks_by_query(self, bank_query):\n        if self._catalog_session is not None:\n            return self._catalog_session.get_catalogs_by_query(bank_query)\n        query_terms = dict(bank_query._query_terms)\n        collection = JSONClientValidated('assessment',\n                                         collection='Bank',\n                                         runtime=self._runtime)\n        result = collection.find(query_terms).sort('_id', DESCENDING)\n        return objects.BankList(result, runtime=self._runtime)",
    "docstring": "Gets a list of ``Bank`` objects matching the given bank query.\n\n        arg:    bank_query (osid.assessment.BankQuery): the bank query\n        return: (osid.assessment.BankList) - the returned ``BankList``\n        raise:  NullArgument - ``bank_query`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        raise:  Unsupported - ``bank_query`` is not of this service\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def read_relative_file(filename):\n    path = join(dirname(abspath(__file__)), filename)\n    with io.open(path, encoding='utf-8') as f:\n        return f.read()",
    "docstring": "Return the contents of the given file.\n\n    Its path is supposed relative to this module."
  },
  {
    "code": "def find_tor_binary(globs=('/usr/sbin/', '/usr/bin/',\n                           '/Applications/TorBrowser_*.app/Contents/MacOS/'),\n                    system_tor=True):\n    if system_tor:\n        try:\n            proc = subprocess.Popen(\n                ('which tor'),\n                stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n                shell=True\n            )\n        except OSError:\n            pass\n        else:\n            stdout, _ = proc.communicate()\n            if proc.poll() == 0 and stdout != '':\n                return stdout.strip()\n    for pattern in globs:\n        for path in glob.glob(pattern):\n            torbin = os.path.join(path, 'tor')\n            if is_executable(torbin):\n                return torbin\n    return None",
    "docstring": "Tries to find the tor executable using the shell first or in in the\n    paths whose glob-patterns is in the given 'globs'-tuple.\n\n    :param globs:\n        A tuple of shell-style globs of directories to use to find tor\n        (TODO consider making that globs to actual tor binary?)\n\n    :param system_tor:\n        This controls whether bash is used to seach for 'tor' or\n        not. If False, we skip that check and use only the 'globs'\n        tuple."
  },
  {
    "code": "def clear_cached(self):\n        _TABLE_CACHE.pop(self.name, None)\n        for col in _columns_for_table(self.name).values():\n            col.clear_cached()\n        logger.debug('cleared cached columns for table {!r}'.format(self.name))",
    "docstring": "Remove cached results from this table's computed columns."
  },
  {
    "code": "def htseq_stats_table(self):\n        headers = OrderedDict()\n        headers['percent_assigned'] = {\n            'title': '% Assigned',\n            'description': '% Assigned reads',\n            'max': 100,\n            'min': 0,\n            'suffix': '%',\n            'scale': 'RdYlGn'\n        }\n        headers['assigned'] = {\n            'title': '{} Assigned'.format(config.read_count_prefix),\n            'description': 'Assigned Reads ({})'.format(config.read_count_desc),\n            'min': 0,\n            'scale': 'PuBu',\n            'modify': lambda x: float(x) * config.read_count_multiplier,\n            'shared_key': 'read_count'\n        }\n        self.general_stats_addcols(self.htseq_data, headers)",
    "docstring": "Take the parsed stats from the HTSeq Count report and add them to the\n        basic stats table at the top of the report"
  },
  {
    "code": "def toggle_word_wrap(self):\n        self.setWordWrapMode(not self.wordWrapMode() and QTextOption.WordWrap or QTextOption.NoWrap)\n        return True",
    "docstring": "Toggles document word wrap.\n\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def _ConvertToCanonicalSqlDict(self, schema, raw_dict, prefix=\"\"):\n    flattened_dict = {}\n    for k, v in iteritems(raw_dict):\n      if isinstance(v, dict):\n        flattened_dict.update(\n            self._ConvertToCanonicalSqlDict(\n                schema, v, prefix=\"%s%s.\" % (prefix, k)))\n      else:\n        field_name = prefix + k\n        flattened_dict[field_name] = schema[field_name].convert_fn(v)\n    return flattened_dict",
    "docstring": "Converts a dict of RDF values into a SQL-ready form."
  },
  {
    "code": "def _group_by_batches(samples, check_fn):\n    batch_groups = collections.defaultdict(list)\n    extras = []\n    for data in [x[0] for x in samples]:\n        if check_fn(data):\n            batch_groups[multi.get_batch_for_key(data)].append(data)\n        else:\n            extras.append([data])\n    return batch_groups, extras",
    "docstring": "Group calls by batches, processing families together during ensemble calling."
  },
  {
    "code": "def index_bams(job, config):\n    job.fileStore.logToMaster('Indexed sample BAMS: ' + config.uuid)\n    disk = '1G' if config.ci_test else '20G'\n    config.normal_bai = job.addChildJobFn(run_samtools_index, config.normal_bam, cores=1, disk=disk).rv()\n    config.tumor_bai = job.addChildJobFn(run_samtools_index, config.tumor_bam, cores=1, disk=disk).rv()\n    job.addFollowOnJobFn(preprocessing_declaration, config)",
    "docstring": "Convenience job for handling bam indexing to make the workflow declaration cleaner\n\n    :param JobFunctionWrappingJob job: passed automatically by Toil\n    :param Namespace config: Argparse Namespace object containing argument inputs"
  },
  {
    "code": "async def _retreive_websocket_info(self):\n        if self._web_client is None:\n            self._web_client = WebClient(\n                token=self.token,\n                base_url=self.base_url,\n                ssl=self.ssl,\n                proxy=self.proxy,\n                run_async=True,\n                loop=self._event_loop,\n                session=self._session,\n            )\n        self._logger.debug(\"Retrieving websocket info.\")\n        if self.connect_method in [\"rtm.start\", \"rtm_start\"]:\n            resp = await self._web_client.rtm_start()\n        else:\n            resp = await self._web_client.rtm_connect()\n        url = resp.get(\"url\")\n        if url is None:\n            msg = \"Unable to retreive RTM URL from Slack.\"\n            raise client_err.SlackApiError(message=msg, response=resp)\n        return url, resp.data",
    "docstring": "Retreives the WebSocket info from Slack.\n\n        Returns:\n            A tuple of websocket information.\n            e.g.\n            (\n                \"wss://...\",\n                {\n                    \"self\": {\"id\": \"U01234ABC\",\"name\": \"robotoverlord\"},\n                    \"team\": {\n                        \"domain\": \"exampledomain\",\n                        \"id\": \"T123450FP\",\n                        \"name\": \"ExampleName\"\n                    }\n                }\n            )\n\n        Raises:\n            SlackApiError: Unable to retreive RTM URL from Slack."
  },
  {
    "code": "def send_key(self, key):\n        cmd = struct.pack(\">BBBBBBH\", 4, 1, 0, 0, 0, 0, key)\n        self.con.send(cmd)\n        cmd = struct.pack(\">BBBBBBH\", 4, 0, 0, 0, 0, 0, key)\n        self.con.send(cmd)",
    "docstring": "Send a key to the Horizon box."
  },
  {
    "code": "def _find_alphas_param(self):\n        for attr in (\"cv_alphas_\", \"alphas_\", \"alphas\",):\n            try:\n                return getattr(self.estimator, attr)\n            except AttributeError:\n                continue\n        raise YellowbrickValueError(\n            \"could not find alphas param on {} estimator\".format(\n                self.estimator.__class__.__name__\n            )\n        )",
    "docstring": "Searches for the parameter on the estimator that contains the array of\n        alphas that was used to produce the error selection. If it cannot find\n        the parameter then a YellowbrickValueError is raised."
  },
  {
    "code": "def get_name_from_path(full_path, root_path):\n    relative_image_path = os.path.relpath(full_path, root_path)\n    return \"_\".join(relative_image_path.split('.')[:-1]).replace('/', '_')\\\n        .replace(';', '').replace(':', '')",
    "docstring": "Create a filename by merging path after root directory."
  },
  {
    "code": "async def getArtifact(self, *args, **kwargs):\n        return await self._makeApiCall(self.funcinfo[\"getArtifact\"], *args, **kwargs)",
    "docstring": "Get Artifact from Run\n\n        Get artifact by `<name>` from a specific run.\n\n        **Public Artifacts**, in-order to get an artifact you need the scope\n        `queue:get-artifact:<name>`, where `<name>` is the name of the artifact.\n        But if the artifact `name` starts with `public/`, authentication and\n        authorization is not necessary to fetch the artifact.\n\n        **API Clients**, this method will redirect you to the artifact, if it is\n        stored externally. Either way, the response may not be JSON. So API\n        client users might want to generate a signed URL for this end-point and\n        use that URL with an HTTP client that can handle responses correctly.\n\n        **Downloading artifacts**\n        There are some special considerations for those http clients which download\n        artifacts.  This api endpoint is designed to be compatible with an HTTP 1.1\n        compliant client, but has extra features to ensure the download is valid.\n        It is strongly recommend that consumers use either taskcluster-lib-artifact (JS),\n        taskcluster-lib-artifact-go (Go) or the CLI written in Go to interact with\n        artifacts.\n\n        In order to download an artifact the following must be done:\n\n        1. Obtain queue url.  Building a signed url with a taskcluster client is\n        recommended\n        1. Make a GET request which does not follow redirects\n        1. In all cases, if specified, the\n        x-taskcluster-location-{content,transfer}-{sha256,length} values must be\n        validated to be equal to the Content-Length and Sha256 checksum of the\n        final artifact downloaded. as well as any intermediate redirects\n        1. If this response is a 500-series error, retry using an exponential\n        backoff.  No more than 5 retries should be attempted\n        1. If this response is a 400-series error, treat it appropriately for\n        your context.  This might be an error in responding to this request or\n        an Error storage type body.  This request should not be retried.\n        1. If this response is a 200-series response, the response body is the artifact.\n        If the x-taskcluster-location-{content,transfer}-{sha256,length} and\n        x-taskcluster-location-content-encoding are specified, they should match\n        this response body\n        1. If the response type is a 300-series redirect, the artifact will be at the\n        location specified by the `Location` header.  There are multiple artifact storage\n        types which use a 300-series redirect.\n        1. For all redirects followed, the user must verify that the content-sha256, content-length,\n        transfer-sha256, transfer-length and content-encoding match every further request.  The final\n        artifact must also be validated against the values specified in the original queue response\n        1. Caching of requests with an x-taskcluster-artifact-storage-type value of `reference`\n        must not occur\n        1. A request which has x-taskcluster-artifact-storage-type value of `blob` and does not\n        have x-taskcluster-location-content-sha256 or x-taskcluster-location-content-length\n        must be treated as an error\n\n        **Headers**\n        The following important headers are set on the response to this method:\n\n        * location: the url of the artifact if a redirect is to be performed\n        * x-taskcluster-artifact-storage-type: the storage type.  Example: blob, s3, error\n\n        The following important headers are set on responses to this method for Blob artifacts\n\n        * x-taskcluster-location-content-sha256: the SHA256 of the artifact\n        *after* any content-encoding is undone.  Sha256 is hex encoded (e.g. [0-9A-Fa-f]{64})\n        * x-taskcluster-location-content-length: the number of bytes *after* any content-encoding\n        is undone\n        * x-taskcluster-location-transfer-sha256: the SHA256 of the artifact\n        *before* any content-encoding is undone.  This is the SHA256 of what is sent over\n        the wire.  Sha256 is hex encoded (e.g. [0-9A-Fa-f]{64})\n        * x-taskcluster-location-transfer-length: the number of bytes *after* any content-encoding\n        is undone\n        * x-taskcluster-location-content-encoding: the content-encoding used.  It will either\n        be `gzip` or `identity` right now.  This is hardcoded to a value set when the artifact\n        was created and no content-negotiation occurs\n        * x-taskcluster-location-content-type: the content-type of the artifact\n\n        **Caching**, artifacts may be cached in data centers closer to the\n        workers in-order to reduce bandwidth costs. This can lead to longer\n        response times. Caching can be skipped by setting the header\n        `x-taskcluster-skip-cache: true`, this should only be used for resources\n        where request volume is known to be low, and caching not useful.\n        (This feature may be disabled in the future, use is sparingly!)\n\n        This method is ``stable``"
  },
  {
    "code": "def validate_tls(self, hostname):\n        self._validate_path()\n        validate_tls_hostname(self._context, self._certificate, hostname)\n        return self._path",
    "docstring": "Validates the certificate path, that the certificate is valid for\n        the hostname provided and that the certificate is valid for the purpose\n        of a TLS connection.\n\n        :param hostname:\n            A unicode string of the TLS server hostname\n\n        :raises:\n            certvalidator.errors.PathValidationError - when an error occurs validating the path\n            certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked\n            certvalidator.errors.InvalidCertificateError - when the certificate is not valid for TLS or the hostname\n\n        :return:\n            A certvalidator.path.ValidationPath object of the validated\n            certificate validation path"
  },
  {
    "code": "def on_welcome(self, c, e):\n        self.backoff = 1\n        if self.nickserv:\n            if Utilities.isNotEmpty(self.nickserv_pass):\n                self.identify(c, e, self.nickserv_pass)\n                time.sleep(3)\n            else:\n                logger.error('If nickserv is enabled, you must supply'\n                             ' a password')\n        if self.nickserv is False and self.nickserv_pass is not None:\n            logger.warn('It appears you provided a nickserv password but '\n                        'did not enable nickserv authentication')\n        for channel in self.my_channels:\n            logger.debug('Attempting to join {0!s}'.format(channel))\n            c.join(channel)",
    "docstring": "This function runs when the bot successfully connects to the IRC server"
  },
  {
    "code": "def _entry_allocated_bitmap(self, entry_number):\n    index, offset = divmod(entry_number, 8)\n    return bool(self._bitmap[index] & (1 << offset))",
    "docstring": "Checks if a particular index is allocated.\n\n    Args:\n        entry_number (int): Index to verify\n\n    Returns:\n        bool: True if it is allocated, False otherwise."
  },
  {
    "code": "def load_corpus(*data_file_paths):\n    for file_path in data_file_paths:\n        corpus = []\n        corpus_data = read_corpus(file_path)\n        conversations = corpus_data.get('conversations', [])\n        corpus.extend(conversations)\n        categories = corpus_data.get('categories', [])\n        yield corpus, categories, file_path",
    "docstring": "Return the data contained within a specified corpus."
  },
  {
    "code": "def subspace_index(self, little_endian_bits_int: int\n                       ) -> Tuple[Union[slice, int, 'ellipsis'], ...]:\n        return linalg.slice_for_qubits_equal_to(self.axes,\n                                                little_endian_bits_int)",
    "docstring": "An index for the subspace where the target axes equal a value.\n\n        Args:\n            little_endian_bits_int: The desired value of the qubits at the\n                targeted `axes`, packed into an integer. The least significant\n                bit of the integer is the desired bit for the first axis, and\n                so forth in increasing order.\n\n        Returns:\n            A value that can be used to index into `target_tensor` and\n            `available_buffer`, and manipulate only the part of Hilbert space\n            corresponding to a given bit assignment.\n\n        Example:\n            If `target_tensor` is a 4 qubit tensor and `axes` is `[1, 3]` and\n            then this method will return the following when given\n            `little_endian_bits=0b01`:\n\n                `(slice(None), 0, slice(None), 1, Ellipsis)`\n\n            Therefore the following two lines would be equivalent:\n\n                args.target_tensor[args.subspace_index(0b01)] += 1\n\n                args.target_tensor[:, 0, :, 1] += 1"
  },
  {
    "code": "def success_response(self, message=None):\n        return self.render(self.request,\n                           redirect_url=self.get_success_url(),\n                           obj=self.object,\n                           message=message,\n                           collect_render_data=False)",
    "docstring": "Returns a 'render redirect' to the result of the\n        `get_success_url` method."
  },
  {
    "code": "def registered(self, driver, executorInfo, frameworkInfo, agentInfo):\n        self.id = executorInfo.executor_id.get('value', None)\n        log.debug(\"Registered executor %s with framework\", self.id)\n        self.address = socket.gethostbyname(agentInfo.hostname)\n        nodeInfoThread = threading.Thread(target=self._sendFrameworkMessage, args=[driver])\n        nodeInfoThread.daemon = True\n        nodeInfoThread.start()",
    "docstring": "Invoked once the executor driver has been able to successfully connect with Mesos."
  },
  {
    "code": "def SetField(cls, default=NOTHING, required=True, repr=False, key=None):\n    default = _init_fields.init_default(required, default, set())\n    converter = converters.to_set_field(cls)\n    validator = _init_fields.init_validator(required, types.TypedSet)\n    return attrib(default=default, converter=converter, validator=validator,\n                  repr=repr, metadata=dict(key=key))",
    "docstring": "Create new set field on a model.\n\n    :param cls: class (or name) of the model to be related in Set.\n    :param default: any TypedSet or set\n    :param bool required: whether or not the object is invalid if not provided.\n    :param bool repr: include this field should appear in object's repr.\n    :param bool cmp: include this field in generated comparison.\n    :param string key: override name of the value when converted to dict."
  },
  {
    "code": "def make_lines_texture(num_lines=10, resolution=50):\n    x, y = np.meshgrid(\n        np.hstack([np.linspace(0, 1, resolution), np.nan]),\n        np.linspace(0, 1, num_lines),\n    )\n    y[np.isnan(x)] = np.nan\n    return x.flatten(), y.flatten()",
    "docstring": "Makes a texture consisting of a given number of horizontal lines.\n\n    Args:\n        num_lines (int): the number of lines to draw\n        resolution (int): the number of midpoints on each line\n\n    Returns:\n        A texture."
  },
  {
    "code": "def prepare_data(problem, hparams, params, config):\n  input_fn = problem.make_estimator_input_fn(\n      tf.estimator.ModeKeys.EVAL, hparams, force_repeat=True)\n  dataset = input_fn(params, config)\n  features, _ = dataset.make_one_shot_iterator().get_next()\n  inputs, labels = features[\"targets\"], features[\"inputs\"]\n  inputs = tf.to_float(inputs)\n  input_shape = inputs.shape.as_list()\n  inputs = tf.reshape(inputs, [hparams.batch_size] + input_shape[1:])\n  labels = tf.reshape(labels, [hparams.batch_size])\n  return inputs, labels, features",
    "docstring": "Construct input pipeline."
  },
  {
    "code": "def update(\n        self,\n        filename=None,\n        batch_id=None,\n        prev_batch_id=None,\n        producer=None,\n        count=None,\n    ):\n        if not filename:\n            raise BatchHistoryError(\"Invalid filename. Got None\")\n        if not batch_id:\n            raise BatchHistoryError(\"Invalid batch_id. Got None\")\n        if not prev_batch_id:\n            raise BatchHistoryError(\"Invalid prev_batch_id. Got None\")\n        if not producer:\n            raise BatchHistoryError(\"Invalid producer. Got None\")\n        if self.exists(batch_id=batch_id):\n            raise IntegrityError(\"Duplicate batch_id\")\n        try:\n            obj = self.model.objects.get(batch_id=batch_id)\n        except self.model.DoesNotExist:\n            obj = self.model(\n                filename=filename,\n                batch_id=batch_id,\n                prev_batch_id=prev_batch_id,\n                producer=producer,\n                total=count,\n            )\n            obj.transaction_file.name = filename\n            obj.save()\n        return obj",
    "docstring": "Creates an history model instance."
  },
  {
    "code": "def update_value(self, offset, value):\n        if offset + len(value) > self.total_size:\n            return Error.INPUT_BUFFER_TOO_LONG\n        if len(self.current_value) < offset:\n            self.current_value += bytearray(offset - len(self.current_value))\n        if len(self.current_value) > offset:\n            self.current_value = self.current_value[:offset]\n        self.current_value += bytearray(value)\n        return 0",
    "docstring": "Update the binary value currently stored for this config value.\n\n        Returns:\n            int: An opaque error code that can be returned from a set_config rpc"
  },
  {
    "code": "def validate_gpg_sig(self, path, sig=None):\n        logger.debug(\"Verifying GPG signature of Insights configuration\")\n        if sig is None:\n            sig = path + \".asc\"\n        command = (\"/usr/bin/gpg --no-default-keyring \"\n                   \"--keyring \" + constants.pub_gpg_path +\n                   \" --verify \" + sig + \" \" + path)\n        if not six.PY3:\n            command = command.encode('utf-8', 'ignore')\n        args = shlex.split(command)\n        logger.debug(\"Executing: %s\", args)\n        proc = Popen(\n            args, shell=False, stdout=PIPE, stderr=STDOUT, close_fds=True)\n        stdout, stderr = proc.communicate()\n        logger.debug(\"STDOUT: %s\", stdout)\n        logger.debug(\"STDERR: %s\", stderr)\n        logger.debug(\"Status: %s\", proc.returncode)\n        if proc.returncode:\n            logger.error(\"ERROR: Unable to validate GPG signature: %s\", path)\n            return False\n        else:\n            logger.debug(\"GPG signature verified\")\n            return True",
    "docstring": "Validate the collection rules"
  },
  {
    "code": "def _agent_notification(self, context, method, hosting_devices, operation):\n        admin_context = context.is_admin and context or context.elevated()\n        for hosting_device in hosting_devices:\n            agents = self._dmplugin.get_cfg_agents_for_hosting_devices(\n                admin_context, hosting_device['id'], admin_state_up=True,\n                schedule=True)\n            for agent in agents:\n                LOG.debug('Notify %(agent_type)s at %(topic)s.%(host)s the '\n                          'message %(method)s',\n                          {'agent_type': agent.agent_type,\n                           'topic': agent.topic,\n                           'host': agent.host,\n                           'method': method})\n                cctxt = self.client.prepare(server=agent.host)\n                cctxt.cast(context, method)",
    "docstring": "Notify individual Cisco cfg agents."
  },
  {
    "code": "def compare_enums(autogen_context, upgrade_ops, schema_names):\n    to_add = set()\n    for schema in schema_names:\n        default = autogen_context.dialect.default_schema_name\n        if schema is None:\n            schema = default\n        defined = get_defined_enums(autogen_context.connection, schema)\n        declared = get_declared_enums(autogen_context.metadata, schema, default)\n        for name, new_values in declared.items():\n            old_values = defined.get(name)\n            if name in defined and new_values.difference(old_values):\n                to_add.add((schema, name, old_values, new_values))\n    for schema, name, old_values, new_values in sorted(to_add):\n        op = SyncEnumValuesOp(schema, name, old_values, new_values)\n        upgrade_ops.ops.append(op)",
    "docstring": "Walk the declared SQLAlchemy schema for every referenced Enum, walk the PG\n    schema for every definde Enum, then generate SyncEnumValuesOp migrations\n    for each defined enum that has grown new entries when compared to its\n    declared version.\n\n    Enums that don't exist in the database yet are ignored, since\n    SQLAlchemy/Alembic will create them as part of the usual migration process."
  },
  {
    "code": "def insertCallSet(self, callSet):\n        try:\n            models.Callset.create(\n                id=callSet.getId(),\n                name=callSet.getLocalId(),\n                variantsetid=callSet.getParentContainer().getId(),\n                biosampleid=callSet.getBiosampleId(),\n                attributes=json.dumps(callSet.getAttributes()))\n        except Exception as e:\n            raise exceptions.RepoManagerException(e)",
    "docstring": "Inserts a the specified callSet into this repository."
  },
  {
    "code": "def compare(self, vertex0, vertex1, subject_graph):\n        return (\n            self.pattern_graph.vertex_fingerprints[vertex0] ==\n            subject_graph.vertex_fingerprints[vertex1]\n        ).all()",
    "docstring": "Returns true when the two vertices are of the same kind"
  },
  {
    "code": "def set_nr_track(self, nr_track):\n        self._set_attr(TRCK(encoding=3, text=str(nr_track)))",
    "docstring": "Sets song's track numb\n\n        :param nr_track: of track"
  },
  {
    "code": "def move_mission(self, key, selection_index):\n        idx = self.selection_index_to_idx(key, selection_index)\n        self.moving_wp = idx\n        print(\"Moving wp %u\" % idx)",
    "docstring": "move a mission point"
  },
  {
    "code": "def get_imported_namespaces(self,\n                                must_have_imported_data_type=False,\n                                consider_annotations=False,\n                                consider_annotation_types=False):\n        imported_namespaces = []\n        for imported_namespace, reason in self._imported_namespaces.items():\n            if must_have_imported_data_type and not reason.data_type:\n                continue\n            if (not consider_annotations) and not (\n                    reason.data_type or reason.alias or reason.annotation_type\n            ):\n                continue\n            if (not consider_annotation_types) and not (\n                    reason.data_type or reason.alias or reason.annotation\n            ):\n                continue\n            imported_namespaces.append(imported_namespace)\n        imported_namespaces.sort(key=lambda n: n.name)\n        return imported_namespaces",
    "docstring": "Returns a list of Namespace objects. A namespace is a member of this\n        list if it is imported by the current namespace and a data type is\n        referenced from it. Namespaces are in ASCII order by name.\n\n        Args:\n            must_have_imported_data_type (bool): If true, result does not\n                include namespaces that were not imported for data types.\n            consider_annotations (bool): If false, result does not include\n                namespaces that were only imported for annotations\n            consider_annotation_types (bool): If false, result does not\n                include namespaces that were only imported for annotation types.\n\n        Returns:\n            List[Namespace]: A list of imported namespaces."
  },
  {
    "code": "def _nics_equal(nic1, nic2):\n    def _filter_nic(nic):\n        return {\n            'type': nic.attrib['type'],\n            'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None,\n            'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None,\n            'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None,\n        }\n    return _filter_nic(nic1) == _filter_nic(nic2)",
    "docstring": "Test if two interface elements should be considered like the same device"
  },
  {
    "code": "def source_url(farm, server, id, secret, size):\n    if size == 'small':\n        img_size = 'n'\n    elif size == 'medium':\n        img_size = 'c'\n    elif size == 'large':\n        img_size = 'b'\n    return 'https://farm{}.staticflickr.com/{}/{}_{}_{}.jpg'.format(\n        farm, server, id, secret, img_size)",
    "docstring": "Url for direct jpg use."
  },
  {
    "code": "def rationalize_file(item_f, charset, mode='rb', lock=False):\n    if hasattr(item_f, 'fileno'):\n        n_fd = os.dup(item_f.fileno())\n        try:\n            _lock(n_fd, lock)\n            del item_f\n            return os.fdopen(n_fd)\n        except Exception, e:\n            os.close(n_fd)\n            raise e\n    elif hasattr(item_f, 'readline'):\n        return item_f\n    elif isinstance(item_f, numbers.Integral):\n        n_fd = os.dup(item_f)\n        try:\n            _lock(n_fd, lock)\n            return os.fdopen(n_fd)\n        except Exception, e:\n            os.close(n_fd)\n            raise e\n    f = open(coerce_unicode(item_f, charset), mode, 1)\n    try:\n        _lock(f.fileno(), lock)\n        return f\n    except Exception, e:\n        f.close()\n        raise e",
    "docstring": "FSQ attempts to treat all file-like things as line-buffered as an\n       optimization to the average case.  rationalize_file will handle file\n       objects, buffers, raw file-descriptors, sockets, and string\n       file-addresses, and will return a file object that can be safely closed\n       in FSQ scope without closing the file in the bounding caller."
  },
  {
    "code": "def state_dict(self) -> Dict[str, Any]:\n        return {\n                \"best_so_far\": self._best_so_far,\n                \"patience\": self._patience,\n                \"epochs_with_no_improvement\": self._epochs_with_no_improvement,\n                \"is_best_so_far\": self._is_best_so_far,\n                \"should_decrease\": self._should_decrease,\n                \"best_epoch_metrics\": self.best_epoch_metrics,\n                \"epoch_number\": self._epoch_number,\n                \"best_epoch\": self.best_epoch\n        }",
    "docstring": "A ``Trainer`` can use this to serialize the state of the metric tracker."
  },
  {
    "code": "def find_val(self, eq, val):\n        if eq not in ('f', 'g', 'q'):\n            return\n        elif eq in ('f', 'q'):\n            key = 'unamex'\n        elif eq == 'g':\n            key = 'unamey'\n        idx = 0\n        for m, n in zip(self.system.varname.__dict__[key], self.__dict__[eq]):\n            if n == val:\n                return m, idx\n            idx += 1\n        return",
    "docstring": "Return the name of the equation having the given value"
  },
  {
    "code": "def parse_tect_region_dict_to_tuples(region_dict):\n    output_region_dict = []\n    tuple_keys = ['Displacement_Length_Ratio', 'Shear_Modulus']\n    for region in region_dict:\n        for val_name in tuple_keys:\n            region[val_name] = weight_list_to_tuple(region[val_name],\n                                                    val_name)\n        region['Magnitude_Scaling_Relation'] = weight_list_to_tuple(\n            region['Magnitude_Scaling_Relation'],\n            'Magnitude Scaling Relation')\n        output_region_dict.append(region)\n    return output_region_dict",
    "docstring": "Parses the tectonic regionalisation dictionary attributes to tuples"
  },
  {
    "code": "def frequency_app(parser, cmd, args):\n    parser.add_argument('value', help='the value to analyse, read from stdin if omitted', nargs='?')\n    args = parser.parse_args(args)\n    data = frequency(six.iterbytes(pwnypack.main.binary_value_or_stdin(args.value)))\n    return '\\n'.join(\n        '0x%02x (%c): %d' % (key, chr(key), value)\n        if key >= 32 and chr(key) in string.printable else\n        '0x%02x ---: %d' % (key, value)\n        for key, value in data.items()\n    )",
    "docstring": "perform frequency analysis on a value."
  },
  {
    "code": "def set_text_color(self, r,g=-1,b=-1):\n        \"Set color for text\"\n        if((r==0 and g==0 and b==0) or g==-1):\n            self.text_color=sprintf('%.3f g',r/255.0)\n        else:\n            self.text_color=sprintf('%.3f %.3f %.3f rg',r/255.0,g/255.0,b/255.0)\n        self.color_flag=(self.fill_color!=self.text_color)",
    "docstring": "Set color for text"
  },
  {
    "code": "def set_continue(self, name, action, seqno, value=None, default=False,\n                     disable=False):\n        commands = ['route-map %s %s %s' % (name, action, seqno)]\n        if default:\n            commands.append('default continue')\n        elif disable:\n            commands.append('no continue')\n        else:\n            if not str(value).isdigit() or value < 1:\n                raise ValueError('seqno must be a positive integer unless '\n                                 'default or disable is specified')\n            commands.append('continue %s' % value)\n        return self.configure(commands)",
    "docstring": "Configures the routemap continue value\n\n        Args:\n            name (string): The full name of the routemap.\n            action (string): The action to take for this routemap clause.\n            seqno (integer): The sequence number for the routemap clause.\n            value (integer): The value to configure for the routemap continue\n            default (bool): Specifies to default the routemap continue value\n            disable (bool): Specifies to negate the routemap continue value\n\n        Returns:\n            True if the operation succeeds otherwise False is returned"
  },
  {
    "code": "def ping_external_urls_handler(sender, **kwargs):\n    entry = kwargs['instance']\n    if entry.is_visible and settings.SAVE_PING_EXTERNAL_URLS:\n        ExternalUrlsPinger(entry)",
    "docstring": "Ping externals URLS when an entry is saved."
  },
  {
    "code": "def add_document(self, question, answer):\n        question = question.strip()\n        answer = answer.strip()\n        session = self.Session()\n        if session.query(Document) \\\n                .filter_by(text=question, answer=answer).count():\n            logger.info('Already here: {0} -> {1}'.format(question, answer))\n            return\n        logger.info('add document: {0} -> {1}'.format(question, answer))\n        grams = self._get_grams(session, question, make=True)\n        doc = Document(question, answer)\n        doc.grams = list(grams)\n        self._recalc_idfs(session, grams)\n        session.add(doc)\n        session.commit()",
    "docstring": "Add question answer set to DB.\n\n        :param question: A question to an answer\n        :type question: :class:`str`\n\n        :param answer: An answer to a question\n        :type answer: :class:`str`"
  },
  {
    "code": "def b(self):\n        b = Point(self.center)\n        if self.xAxisIsMinor:\n            b.x += self.minorRadius\n        else:\n            b.y += self.minorRadius\n        return b",
    "docstring": "Positive antipodal point on the minor axis, Point class."
  },
  {
    "code": "def write(self, tid, data, offset, fh):\n        if tid[1] == \" next\":\n            d = True\n        elif tid[1] == \" prev\":\n            d = False\n        else:\n            raise FuseOSError(errno.EPERM)\n        try:\n            self.searches[tid[0]].updateResults(d)\n        except KeyError:\n            raise FuseOSError(errno.EINVAL)\n        except ConnectionError:\n            raise FuseOSError(errno.ENETDOWN)\n        return len(data)",
    "docstring": "Write operation. Applicable only for control files - updateResults is called.\n\n        Parameters\n        ----------\n        tid : str\n            Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator.\n        data : bytes\n            Ignored.\n        offset : int\n            Ignored.\n        fh : int\n            File descriptor.\n\n        Returns\n        -------\n        int\n            Length of data written."
  },
  {
    "code": "def obj_from_file(filename='annotation.yaml', filetype='auto'):\n    if filetype == 'auto':\n        _, ext = os.path.splitext(filename)\n        filetype = ext[1:]\n    if filetype in ('yaml', 'yml'):\n        from ruamel.yaml import YAML\n        yaml = YAML(typ=\"unsafe\")\n        with open(filename, encoding=\"utf-8\") as f:\n            obj = yaml.load(f)\n        if obj is None:\n            obj = {}\n    elif filetype in ('pickle', 'pkl', 'pklz', 'picklezip'):\n        fcontent = read_pkl_and_pklz(filename)\n        if sys.version_info[0] < 3:\n            import cPickle as pickle\n        else:\n            import _pickle as pickle\n        if sys.version_info.major == 2:\n            obj = pickle.loads(fcontent)\n        else:\n            obj = pickle.loads(fcontent, encoding=\"latin1\")\n    else:\n        logger.error('Unknown filetype ' + filetype)\n    return obj",
    "docstring": "Read object from file"
  },
  {
    "code": "def can_user_update_settings(request, view, obj=None):\n        if obj is None:\n            return\n        if obj.customer and not obj.shared:\n            return permissions.is_owner(request, view, obj)\n        else:\n            return permissions.is_staff(request, view, obj)",
    "docstring": "Only staff can update shared settings, otherwise user has to be an owner of the settings."
  },
  {
    "code": "def key_exists(self, key):\n        assert isinstance(key, str)\n        self._close()\n        try:\n            return self._unsafe_key_exists(key)\n        finally:\n            self._open()",
    "docstring": "Check if key has previously been added to this store.\n\n        This function makes a linear search through the log file and is very\n        slow.\n\n        Returns True if the event has previously been added, False otherwise."
  },
  {
    "code": "def _find_by(self, key):\n        by_path = glob.glob('/dev/input/by-{key}/*-event-*'.format(key=key))\n        for device_path in by_path:\n            self._parse_device_path(device_path)",
    "docstring": "Find devices."
  },
  {
    "code": "def get_section(section_name, cfg_file=cfg_file):\n    parser = get_parser(cfg_file=cfg_file)\n    options = parser.options(section_name)\n    result = {}\n    for option in options:\n        result[option] = parser.get(section=section_name, option=option)\n    return result",
    "docstring": "Returns a dictionary of an entire section"
  },
  {
    "code": "def can_receive_messages(self):\n        with self.lock:\n            return not self._state.is_waiting_for_start() and \\\n                not self._state.is_connection_closed()",
    "docstring": "Whether tihs communication is ready to receive messages.]\n\n        :rtype: bool\n\n        .. code:: python\n\n            assert not communication.can_receive_messages()\n            communication.start()\n            assert communication.can_receive_messages()\n            communication.stop()\n            assert not communication.can_receive_messages()"
  },
  {
    "code": "def from_api(cls, api):\n        ux = TodoUX(api)\n        from .pseudorpc import PseudoRpc\n        rpc = PseudoRpc(api)\n        return cls({ViaAPI: api, ViaUX: ux, ViaRPC: rpc})",
    "docstring": "create an application description for the todo app,\n        that based on the api can use either tha api or the ux for interaction"
  },
  {
    "code": "def get_groups_dict(self) -> Dict:\n        return {\n            k: deserializer.inventory.InventoryElement.serialize(v).dict()\n            for k, v in self.groups.items()\n        }",
    "docstring": "Returns serialized dictionary of groups from inventory"
  },
  {
    "code": "def login_required(self, fresh=False, redirect_to=None):\n        if not self.logged_in() or (fresh and not self.login_manager.login_fresh()):\n            if redirect_to:\n                resp = redirect(redirect_to)\n            else:\n                resp = self.login_manager.unauthorized()\n            current_context.exit(resp, trigger_action_group=\"missing_user\")",
    "docstring": "Ensures that a user is authenticated"
  },
  {
    "code": "def get_privkey_address(privkey_info, blockchain='bitcoin', **blockchain_opts):\n    if blockchain == 'bitcoin':\n        return btc_get_privkey_address(privkey_info, **blockchain_opts)\n    else:\n        raise ValueError('Unknown blockchain \"{}\"'.format(blockchain))",
    "docstring": "Get the address from a private key bundle"
  },
  {
    "code": "async def rewrite_middleware(server, request):\n    if singletons.settings.SECURITY is not None:\n        security_class = singletons.settings.load('SECURITY')\n    else:\n        security_class = DummySecurity\n    security = security_class()\n    try:\n        new_path = await security.rewrite(request)\n    except SecurityException as e:\n        msg = ''\n        if DEBUG:\n            msg = str(e)\n        return server.response.text(msg, status=400)\n    request.path = new_path",
    "docstring": "Sanic middleware that utilizes a security class's \"rewrite\" method to\n    check"
  },
  {
    "code": "def dict_to_pendulum(d: Dict[str, Any],\n                     pendulum_class: ClassType) -> DateTime:\n    return pendulum.parse(d['iso'])",
    "docstring": "Converts a ``dict`` object back to a ``Pendulum``."
  },
  {
    "code": "def attach(self, listener):\n        if listener not in self.listeners:\n            self.listeners.append(listener)",
    "docstring": "Attach an object that should be notified of events.\n\n        The object should have a notify(msg_type, param_dict) function."
  },
  {
    "code": "def select(select, tag, namespaces=None, limit=0, flags=0, **kwargs):\n    return compile(select, namespaces, flags, **kwargs).select(tag, limit)",
    "docstring": "Select the specified tags."
  },
  {
    "code": "def build_info(self):\n        if 'build_info' not in self._memo:\n            self._memo['build_info'] = _get_url(self.artifact_url('json')).json()\n        return self._memo['build_info']",
    "docstring": "Return the build's info"
  },
  {
    "code": "def __expand_limits(ax, limits, which='x'):\n    if which == 'x':\n        getter, setter = ax.get_xlim, ax.set_xlim\n    elif which == 'y':\n        getter, setter = ax.get_ylim, ax.set_ylim\n    else:\n        raise ValueError('invalid axis: {}'.format(which))\n    old_lims = getter()\n    new_lims = list(limits)\n    if np.isfinite(old_lims[0]):\n        new_lims[0] = min(old_lims[0], limits[0])\n    if np.isfinite(old_lims[1]):\n        new_lims[1] = max(old_lims[1], limits[1])\n    setter(new_lims)",
    "docstring": "Helper function to expand axis limits"
  },
  {
    "code": "def get_es_mappings(self):\r\n        es_mappings = json.loads(requests.get(self.mapping_url).text)\r\n        es_mappings = {\"_\".join(key.split(\"_\")[:-1]): value['mappings'] \\\r\n                       for key, value in es_mappings.items()}\r\n        return es_mappings",
    "docstring": "Returns the mapping defitions presetn in elasticsearh"
  },
  {
    "code": "def backprop(self, input_data, targets, cache=None):\n        df_input = gpuarray.zeros_like(input_data)\n        if cache is None: cache = self.n_tasks * [None]\n        gradients = []\n        for targets_task, cache_task, task, task_weight  in \\\n          izip(targets, cache, self.tasks, self.task_weights):\n            gradients_task, df_input_task = \\\n              task.backprop(input_data, targets_task,\n                            cache_task)\n            df_input = df_input.mul_add(1., df_input_task, task_weight)\n            gradients.extend(gradients_task)\n        return gradients, df_input",
    "docstring": "Compute gradients for each task and combine the results.\n\n        **Parameters:**\n\n        input_data : ``GPUArray``\n            Inpute data to compute activations for.\n\n        targets : ``GPUArray``\n            The target values of the units.\n\n        cache : list of ``GPUArray``\n            Cache obtained from forward pass. If the cache is\n            provided, then the activations are not recalculated.\n\n        **Returns:**\n\n        gradients : list\n            Gradients with respect to the weights and biases for each task\n\n        df_input : ``GPUArray``\n            Gradients with respect to the input, obtained by adding\n            the gradients with respect to the inputs from each task,\n            weighted by ``MultitaskTopLayer.task_weights``."
  },
  {
    "code": "def post(self, request, *args, **kwargs):\n        versions = self._get_versions()\n        url = self.get_done_url()\n        msg = None\n        try:\n            vid = int(request.POST.get('version', ''))\n            version = versions.get(vid=vid)\n            if request.POST.get('revert'):\n                object_url = self.get_object_url()\n                msg = self.revert(version, object_url)\n            elif request.POST.get('delete'):\n                msg = self.delete(version)\n                url = self.request.build_absolute_uri()\n        except (ValueError, versions.model.DoesNotExist):\n            pass\n        return self.render(request, redirect_url=url,\n                   message=msg,\n                   obj=self.object,\n                   collect_render_data=False)",
    "docstring": "Method for handling POST requests.\n        Expects the 'vid' of the version to act on\n        to be passed as in the POST variable 'version'.\n\n        If a POST variable 'revert' is present this will\n        call the revert method and then return a 'render\n        redirect' to the result of the `get_done_url` method.\n\n        If a POST variable 'delete' is present this will\n        call the delete method and return a 'render redirect'\n        to the result of the `get_done_url` method.\n\n        If this method receives unexpected input, it will\n        silently redirect to the result of the `get_done_url`\n        method."
  },
  {
    "code": "def splitext(path):\n    parent_path, pathname = split(path)\n    if pathname.startswith(\".\") and pathname.count(\".\") == 1:\n        return path, \"\"\n    if \".\" not in pathname:\n        return path, \"\"\n    pathname, ext = pathname.rsplit(\".\", 1)\n    path = join(parent_path, pathname)\n    return path, \".\" + ext",
    "docstring": "Split the extension from the path.\n\n    Arguments:\n        path (str): A path to split.\n\n    Returns:\n        (str, str): A tuple containing the path and the extension.\n\n    Example:\n        >>> splitext('baz.txt')\n        ('baz', '.txt')\n        >>> splitext('foo/bar/baz.txt')\n        ('foo/bar/baz', '.txt')\n        >>> splitext('foo/bar/.foo')\n        ('foo/bar/.foo', '')"
  },
  {
    "code": "def is_compatible(self, other):\n        super(Array2D, self).is_compatible(other)\n        if isinstance(other, type(self)):\n            try:\n                if not self.dy == other.dy:\n                    raise ValueError(\"%s sample sizes do not match: \"\n                                     \"%s vs %s.\" % (type(self).__name__,\n                                                    self.dy, other.dy))\n            except AttributeError:\n                raise ValueError(\"Series with irregular y-indexes cannot \"\n                                 \"be compatible\")\n        return True",
    "docstring": "Check whether this array and ``other`` have compatible metadata"
  },
  {
    "code": "def set_config(self, data=None, **kwargs):\n        config = self.bot.config['server_config']\n        for opt in data.split(' '):\n            if '=' in opt:\n                opt, value = opt.split('=', 1)\n            else:\n                value = True\n            if opt.isupper():\n                config[opt] = value",
    "docstring": "Store server config"
  },
  {
    "code": "def qhull_cmd(cmd, options, points):\n    prep_str = [str(len(points[0])), str(len(points))]\n    prep_str.extend([' '.join(map(repr, row)) for row in points])\n    output = getattr(hull, cmd)(options, \"\\n\".join(prep_str))\n    return list(map(str.strip, output.strip().split(\"\\n\")))",
    "docstring": "Generalized helper method to perform a qhull based command.\n\n    Args:\n        cmd:\n            Command to perform. Supported commands are qconvex,\n            qdelaunay and qvoronoi.\n        options:\n            Options to be provided for qhull command. See specific methods for\n            info on supported options. Up to two options separated by spaces\n            are supported.\n        points:\n            Sequence of points as input to qhull command.\n\n     Returns:\n        Output as a list of strings. E.g., ['4', '0 2', '1 0', '2 3 ', '3 1']"
  },
  {
    "code": "def get_filename_by_suffixes(dir_src, suffixes):\n        list_files = os.listdir(dir_src)\n        re_files = list()\n        if is_string(suffixes):\n            suffixes = [suffixes]\n        if not isinstance(suffixes, list):\n            return None\n        for i, suf in enumerate(suffixes):\n            if len(suf) >= 1 and suf[0] != '.':\n                suffixes[i] = '.' + suf\n        for f in list_files:\n            name, ext = os.path.splitext(f)\n            if StringClass.string_in_list(ext, suffixes):\n                re_files.append(f)\n        return re_files",
    "docstring": "get file names with the given suffixes in the given directory\n\n        Args:\n            dir_src: directory path\n            suffixes: wanted suffixes list, the suffix in suffixes can with or without '.'\n\n        Returns:\n            file names with the given suffixes as list"
  },
  {
    "code": "def attributes():\n    attribute_classes = get_attribute_classes()\n    for name, class_ in attribute_classes.items():\n        click.echo(\n            u'{name} - Added in: {ai} ({cv})'.format(\n                name=click.style(name, fg='green'),\n                ai=click.style(class_.ADDED_IN, fg='yellow'),\n                cv=click.style(\n                    ClassVersion(*class_.MINIMUM_CLASS_VERSION).human,\n                    fg='yellow'\n                )\n            )\n        )",
    "docstring": "List enabled Attributes.\n\n    Prints a list of all enabled ClassFile Attributes."
  },
  {
    "code": "def init_pool(self):\n        if self.pool is None:\n            if self.nproc > 1:\n                self.pool = mp.Pool(processes=self.nproc)\n            else:\n                self.pool = None\n        else:\n            print('pool already initialized?')",
    "docstring": "Initialize multiprocessing pool if necessary."
  },
  {
    "code": "def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):\n    cmds = []\n    if to_install:\n        cmd = copy.deepcopy(cmd_prefix)\n        cmd.extend(to_install)\n        cmds.append(cmd)\n    if to_downgrade:\n        cmd = copy.deepcopy(cmd_prefix)\n        cmd.append('--force-downgrade')\n        cmd.extend(to_downgrade)\n        cmds.append(cmd)\n    if to_reinstall:\n        cmd = copy.deepcopy(cmd_prefix)\n        cmd.append('--force-reinstall')\n        cmd.extend(to_reinstall)\n        cmds.append(cmd)\n    return cmds",
    "docstring": "Builds a list of install commands to be executed in sequence in order to process\n    each of the to_install, to_downgrade, and to_reinstall lists."
  },
  {
    "code": "def reflected_binary_operator(op):\n    assert not is_comparison(op)\n    @with_name(method_name_for_op(op, commute=True))\n    @coerce_numbers_to_my_dtype\n    def reflected_binary_operator(self, other):\n        if isinstance(self, NumericalExpression):\n            self_expr, other_expr, new_inputs = self.build_binary_op(\n                op, other\n            )\n            return NumExprFactor(\n                \"({left}) {op} ({right})\".format(\n                    left=other_expr,\n                    right=self_expr,\n                    op=op,\n                ),\n                new_inputs,\n                dtype=binop_return_dtype(op, other.dtype, self.dtype)\n            )\n        elif isinstance(other, Number):\n            return NumExprFactor(\n                \"{constant} {op} x_0\".format(op=op, constant=other),\n                binds=(self,),\n                dtype=binop_return_dtype(op, other.dtype, self.dtype),\n            )\n        raise BadBinaryOperator(op, other, self)\n    return reflected_binary_operator",
    "docstring": "Factory function for making binary operator methods on a Factor.\n\n    Returns a function, \"reflected_binary_operator\" suitable for implementing\n    functions like __radd__."
  },
  {
    "code": "def create_default_config():\n    config = configparser.RawConfigParser()\n    config.add_section('global')\n    config.set('global', 'env_source_rc', False)\n    config.add_section('shell')\n    config.set('shell', 'bash', \"true\")\n    config.set('shell', 'zsh', \"true\")\n    config.set('shell', 'gui', \"true\")\n    return config",
    "docstring": "Create a default configuration object, with all parameters filled"
  },
  {
    "code": "def plotSkymapCatalog(lon,lat,**kwargs):\n    fig = plt.figure()\n    ax = plt.subplot(111,projection=projection)\n    drawSkymapCatalog(ax,lon,lat,**kwargs)",
    "docstring": "Plot a catalog of coordinates on a full-sky map."
  },
  {
    "code": "def _callable_func(self, func, axis, *args, **kwargs):\n        def callable_apply_builder(df, axis=0):\n            if not axis:\n                df.index = index\n                df.columns = pandas.RangeIndex(len(df.columns))\n            else:\n                df.columns = index\n                df.index = pandas.RangeIndex(len(df.index))\n            result = df.apply(func, axis=axis, *args, **kwargs)\n            return result\n        index = self.index if not axis else self.columns\n        func_prepared = self._build_mapreduce_func(callable_apply_builder, axis=axis)\n        result_data = self._map_across_full_axis(axis, func_prepared)\n        return self._post_process_apply(result_data, axis)",
    "docstring": "Apply callable functions across given axis.\n\n        Args:\n            func: The functions to apply.\n            axis: Target axis to apply the function along.\n\n        Returns:\n            A new PandasQueryCompiler."
  },
  {
    "code": "def render_label(self, cairo_context, shape_id, text=None, label_scale=.9):\n        text = shape_id if text is None else text\n        shape = self.canvas.df_bounding_shapes.ix[shape_id]\n        shape_center = self.canvas.df_shape_centers.ix[shape_id]\n        font_size, text_shape = \\\n            aspect_fit_font_size(text, shape * label_scale,\n                                 cairo_context=cairo_context)\n        cairo_context.set_font_size(font_size)\n        cairo_context.move_to(shape_center[0] - .5 * text_shape.width,\n                              shape_center[1] + .5 * text_shape.height)\n        cairo_context.show_text(text)",
    "docstring": "Draw label on specified shape.\n\n        Parameters\n        ----------\n        cairo_context : cairo.Context\n            Cairo context to draw text width.  Can be preconfigured, for\n            example, to set font style, etc.\n        shape_id : str\n            Shape identifier.\n        text : str, optional\n            Label text.  If not specified, shape identifier is used.\n        label_scale : float, optional\n            Fraction of limiting dimension of shape bounding box to scale text\n            to."
  },
  {
    "code": "def archive(cls):\n    req = datastore.BeginTransactionRequest()\n    resp = datastore.begin_transaction(req)\n    tx = resp.transaction\n    req = datastore.RunQueryRequest()\n    req.read_options.transaction = tx\n    q = req.query\n    set_kind(q, kind='Todo')\n    add_projection(q, '__key__')\n    set_composite_filter(q.filter,\n                         datastore.CompositeFilter.AND,\n                         set_property_filter(\n                             datastore.Filter(),\n                             'done', datastore.PropertyFilter.EQUAL, True),\n                         set_property_filter(\n                             datastore.Filter(),\n                             '__key__', datastore.PropertyFilter.HAS_ANCESTOR,\n                             default_todo_list.key))\n    resp = datastore.run_query(req)\n    req = datastore.CommitRequest()\n    req.transaction = tx\n    for result in resp.batch.entity_results:\n      req.mutations.add().delete.CopyFrom(result.entity.key)\n    resp = datastore.commit(req)\n    return ''",
    "docstring": "Delete all Todo items that are done."
  },
  {
    "code": "def ignore_path(path, ignore_list=None, whitelist=None):\n    if ignore_list is None:\n        return True\n    should_ignore = matches_glob_list(path, ignore_list)\n    if whitelist is None:\n        return should_ignore\n    return should_ignore and not matches_glob_list(path, whitelist)",
    "docstring": "Returns a boolean indicating if a path should be ignored given an\n    ignore_list and a whitelist of glob patterns."
  },
  {
    "code": "def language(self, language):\n        if language is None:\n            raise ValueError(\"Invalid value for `language`, must not be `None`\")\n        allowed_values = [\"python\", \"r\", \"rmarkdown\"]\n        if language not in allowed_values:\n            raise ValueError(\n                \"Invalid value for `language` ({0}), must be one of {1}\"\n                .format(language, allowed_values)\n            )\n        self._language = language",
    "docstring": "Sets the language of this KernelPushRequest.\n\n        The language that the kernel is written in  # noqa: E501\n\n        :param language: The language of this KernelPushRequest.  # noqa: E501\n        :type: str"
  },
  {
    "code": "def sg_max(tensor, opt):\n    r\n    return tf.reduce_max(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name)",
    "docstring": "r\"\"\"Computes the maximum of elements across axis of a tensor.\n\n    See `tf.reduce_max()` in tensorflow.\n\n    Args:\n      tensor: A `Tensor` (automatically given by chain).\n      opt:\n        axis : A tuple/list of integers or an integer. The axis to reduce.\n        keep_dims: If true, retains reduced dimensions with length 1.\n        name: If provided, replace current tensor's name.\n\n    Returns:\n      A `Tensor`."
  },
  {
    "code": "def bellman_ford(graph, weight, source=0):\n    n = len(graph)\n    dist = [float('inf')] * n\n    prec = [None] * n\n    dist[source] = 0\n    for nb_iterations in range(n):\n        changed = False\n        for node in range(n):\n            for neighbor in graph[node]:\n                alt = dist[node] + weight[node][neighbor]\n                if alt < dist[neighbor]:\n                    dist[neighbor] = alt\n                    prec[neighbor] = node\n                    changed = True\n        if not changed:\n            return dist, prec, False\n    return dist, prec, True",
    "docstring": "Single source shortest paths by Bellman-Ford\n\n    :param graph: directed graph in listlist or listdict format\n    :param weight: can be negative.\n                   in matrix format or same listdict graph\n    :returns: distance table, precedence table, bool\n    :explanation: bool is True if a negative circuit is\n                  reachable from the source, circuits\n                  can have length 2.\n    :complexity: `O(|V|*|E|)`"
  },
  {
    "code": "def subjects_download(self, subject_id):\n        subject = self.subjects_get(subject_id)\n        if subject is None:\n            return None\n        else:\n            return FileInfo(\n                subject.data_file,\n                subject.properties[datastore.PROPERTY_MIMETYPE],\n                subject.properties[datastore.PROPERTY_FILENAME]\n            )",
    "docstring": "Get data file for subject with given identifier.\n\n        Parameters\n        ----------\n        subject_id : string\n            Unique subject identifier\n\n        Returns\n        -------\n        FileInfo\n            Information about subject's data file on disk or None if identifier\n            is unknown"
  },
  {
    "code": "async def end(self):\n        try:\n            await self.proc.wait()\n        finally:\n            for temporary_file in self.temporary_files:\n                temporary_file.close()\n            self.temporary_files = []\n        return self.proc.returncode",
    "docstring": "End process execution."
  },
  {
    "code": "def set_annotation(self):\n        assert self.pending_symbol is not None\n        assert not self.value\n        annotations = (_as_symbol(self.pending_symbol, is_symbol_value=False),)\n        self.annotations = annotations if not self.annotations else self.annotations + annotations\n        self.ion_type = None\n        self.pending_symbol = None\n        self.quoted_text = False\n        self.line_comment = False\n        self.is_self_delimiting = False\n        return self",
    "docstring": "Appends the context's ``pending_symbol`` to its ``annotations`` sequence."
  },
  {
    "code": "def start_patching(name=None):\n    global _factory_map, _patchers, _mocks\n    if _patchers and name is None:\n        warnings.warn('start_patching() called again, already patched')\n    _pre_import()\n    if name is not None:\n        factory = _factory_map[name]\n        items = [(name, factory)]\n    else:\n        items = _factory_map.items()\n    for name, factory in items:\n        patcher = mock.patch(name, new=factory())\n        mocked = patcher.start()\n        _patchers[name] = patcher\n        _mocks[name] = mocked",
    "docstring": "Initiate mocking of the functions listed in `_factory_map`.\n\n    For this to work reliably all mocked helper functions should be imported\n    and used like this:\n\n        import dp_paypal.client as paypal\n        res = paypal.do_paypal_express_checkout(...)\n\n    (i.e. don't use `from dp_paypal.client import x` import style)\n\n    Kwargs:\n        name (Optional[str]): if given, only patch the specified path, else all\n            defined default mocks"
  },
  {
    "code": "def get_utm_epsg(longitude, latitude, crs=None):\n    if crs is None or crs.authid() == 'EPSG:4326':\n        epsg = 32600\n        if latitude < 0.0:\n            epsg += 100\n        epsg += get_utm_zone(longitude)\n        return epsg\n    else:\n        epsg_4326 = QgsCoordinateReferenceSystem('EPSG:4326')\n        transform = QgsCoordinateTransform(\n            crs, epsg_4326, QgsProject.instance())\n        geom = QgsGeometry.fromPointXY(QgsPointXY(longitude, latitude))\n        geom.transform(transform)\n        point = geom.asPoint()\n        return get_utm_epsg(point.x(), point.y())",
    "docstring": "Return epsg code of the utm zone according to X, Y coordinates.\n\n    By default, the CRS is EPSG:4326. If the CRS is provided, first X,Y will\n    be reprojected from the input CRS to WGS84.\n\n    The code is based on the code:\n    http://gis.stackexchange.com/questions/34401\n\n    :param longitude: The longitude.\n    :type longitude: float\n\n    :param latitude: The latitude.\n    :type latitude: float\n\n    :param crs: The coordinate reference system of the latitude, longitude.\n    :type crs: QgsCoordinateReferenceSystem"
  },
  {
    "code": "def rows_above_layout(self):\n        if self._in_alternate_screen:\n            return 0\n        elif self._min_available_height > 0:\n            total_rows = self.output.get_size().rows\n            last_screen_height = self._last_screen.height if self._last_screen else 0\n            return total_rows - max(self._min_available_height, last_screen_height)\n        else:\n            raise HeightIsUnknownError('Rows above layout is unknown.')",
    "docstring": "Return the number of rows visible in the terminal above the layout."
  },
  {
    "code": "def get_resource_form(self, *args, **kwargs):\n        if isinstance(args[-1], list) or 'resource_record_types' in kwargs:\n            return self.get_resource_form_for_create(*args, **kwargs)\n        else:\n            return self.get_resource_form_for_update(*args, **kwargs)",
    "docstring": "Pass through to provider ResourceAdminSession.get_resource_form_for_update"
  },
  {
    "code": "def dataSetUnit(h5Dataset):\n    attributes = h5Dataset.attrs\n    if not attributes:\n        return ''\n    for key in ('unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'):\n        if key in attributes:\n            return to_string(attributes[key])\n    return ''",
    "docstring": "Returns the unit of the h5Dataset by looking in the attributes.\n\n        It searches in the attributes for one of the following keys:\n        'unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'. If these are not found, the empty\n        string is returned.\n\n        Always returns a string"
  },
  {
    "code": "def parseLayoutFeatures(font):\n    featxt = tounicode(font.features.text or \"\", \"utf-8\")\n    if not featxt:\n        return ast.FeatureFile()\n    buf = UnicodeIO(featxt)\n    ufoPath = font.path\n    if ufoPath is not None:\n        buf.name = ufoPath\n    glyphNames = set(font.keys())\n    try:\n        parser = Parser(buf, glyphNames)\n        doc = parser.parse()\n    except IncludedFeaNotFound as e:\n        if ufoPath and os.path.exists(os.path.join(ufoPath, e.args[0])):\n            logger.warning(\n                \"Please change the file name in the include(...); \"\n                \"statement to be relative to the UFO itself, \"\n                \"instead of relative to the 'features.fea' file \"\n                \"contained in it.\"\n            )\n        raise\n    return doc",
    "docstring": "Parse OpenType layout features in the UFO and return a\n    feaLib.ast.FeatureFile instance."
  },
  {
    "code": "def blackbox_and_coarse_grain(blackbox, coarse_grain):\n    if blackbox is None:\n        return\n    for box in blackbox.partition:\n        outputs = set(box) & set(blackbox.output_indices)\n        if coarse_grain is None and len(outputs) > 1:\n            raise ValueError(\n                'A blackboxing with multiple outputs per box must be '\n                'coarse-grained.')\n        if (coarse_grain and not any(outputs.issubset(part)\n                                     for part in coarse_grain.partition)):\n            raise ValueError(\n                'Multiple outputs from a blackbox must be partitioned into '\n                'the same macro-element of the coarse-graining')",
    "docstring": "Validate that a coarse-graining properly combines the outputs of a\n    blackboxing."
  },
  {
    "code": "def loadhex(self, fobj):\n        if getattr(fobj, \"read\", None) is None:\n            fobj = open(fobj, \"r\")\n            fclose = fobj.close\n        else:\n            fclose = None\n        self._offset = 0\n        line = 0\n        try:\n            decode = self._decode_record\n            try:\n                for s in fobj:\n                    line += 1\n                    decode(s, line)\n            except _EndOfFile:\n                pass\n        finally:\n            if fclose:\n                fclose()",
    "docstring": "Load hex file into internal buffer. This is not necessary\n        if object was initialized with source set. This will overwrite\n        addresses if object was already initialized.\n\n        @param  fobj        file name or file-like object"
  },
  {
    "code": "def set_xlabels(self, label=None, **kwargs):\n        if label is None:\n            label = label_from_attrs(self.data[self._x_var])\n        for ax in self._bottom_axes:\n            ax.set_xlabel(label, **kwargs)\n        return self",
    "docstring": "Label the x axis on the bottom row of the grid."
  },
  {
    "code": "def update_record(self, record, data=None, priority=None,\n            ttl=None, comment=None):\n        return self.manager.update_record(self, record, data=data,\n            priority=priority, ttl=ttl, comment=comment)",
    "docstring": "Modifies an existing record for this domain."
  },
  {
    "code": "def get_minimum_size(self, data):\n        size = self.element.get_minimum_size(data)\n        return datatypes.Point(\n            max(size.x, self.min_width),\n            max(size.y, self.min_height)\n            )",
    "docstring": "Returns the minimum size of the managed element, as long as\n        it is larger than any manually set minima."
  },
  {
    "code": "def get_serializer_class(self):\n        klass = None\n        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field\n        if lookup_url_kwarg in self.kwargs:\n            klass = self.get_object().__class__\n        elif \"doctype\" in self.request.REQUEST:\n            base = self.model.get_base_class()\n            doctypes = indexable_registry.families[base]\n            try:\n                klass = doctypes[self.request.REQUEST[\"doctype\"]]\n            except KeyError:\n                raise Http404\n        if hasattr(klass, \"get_serializer_class\"):\n            return klass.get_serializer_class()\n        return super(ContentViewSet, self).get_serializer_class()",
    "docstring": "gets the class type of the serializer\n\n        :return: `rest_framework.Serializer`"
  },
  {
    "code": "def get_switched_form_field_attrs(self, prefix, input_type, name):\n        attributes = {'class': 'switched', 'data-switch-on': prefix + 'field'}\n        attributes['data-' + prefix + 'field-' + input_type] = name\n        return attributes",
    "docstring": "Creates attribute dicts for the switchable theme form"
  },
  {
    "code": "def remove_hash_prefix_indices(self, threat_list, indices):\n        batch_size = 40\n        q =\n        prefixes_to_remove = self.get_hash_prefix_values_to_remove(threat_list, indices)\n        with self.get_cursor() as dbc:\n            for i in range(0, len(prefixes_to_remove), batch_size):\n                remove_batch = prefixes_to_remove[i:(i + batch_size)]\n                params = [\n                    threat_list.threat_type,\n                    threat_list.platform_type,\n                    threat_list.threat_entry_type\n                ] + [sqlite3.Binary(b) for b in remove_batch]\n                dbc.execute(q.format(','.join(['?'] * len(remove_batch))), params)",
    "docstring": "Remove records matching idices from a lexicographically-sorted local threat list."
  },
  {
    "code": "def do_IHaveRequest(self, apdu):\n        if _debug: WhoHasIHaveServices._debug(\"do_IHaveRequest %r\", apdu)\n        if apdu.deviceIdentifier is None:\n            raise MissingRequiredParameter(\"deviceIdentifier required\")\n        if apdu.objectIdentifier is None:\n            raise MissingRequiredParameter(\"objectIdentifier required\")\n        if apdu.objectName is None:\n            raise MissingRequiredParameter(\"objectName required\")",
    "docstring": "Respond to a I-Have request."
  },
  {
    "code": "def on_delivery(self, name, channel, method, properties, body):\n        message = data.Message(name, channel, method, properties, body)\n        if self.is_processing:\n            return self.pending.append(message)\n        self.invoke_consumer(message)",
    "docstring": "Process a message from Rabbit\n\n        :param str name: The connection name\n        :param pika.channel.Channel channel: The message's delivery channel\n        :param pika.frames.MethodFrame method: The method frame\n        :param pika.spec.BasicProperties properties: The message properties\n        :param str body: The message body"
  },
  {
    "code": "def complete_node(arg):\n    try:\n        cmd = cfg.get('global', 'complete_node_cmd')\n    except configparser.NoOptionError:\n        return [ '', ]\n    cmd = re.sub('%search_string%', pipes.quote(arg), cmd)\n    args = shlex.split(cmd)\n    p = subprocess.Popen(args, stdout=subprocess.PIPE)\n    res, err = p.communicate()\n    nodes = res.split('\\n')\n    return nodes",
    "docstring": "Complete node hostname\n\n        This function is currently a bit special as it looks in the config file\n        for a command to use to complete a node hostname from an external\n        system.\n\n        It is configured by setting the config attribute \"complete_node_cmd\" to\n        a shell command. The string \"%search_string%\" in the command will be\n        replaced by the current search string."
  },
  {
    "code": "def patch_string(s):\n    res = ''\n    it = PeekIterator(s)\n    for c in it:\n        if (ord(c) >> 10) == 0b110110:\n            n = it.peek()\n            if n and (ord(n) >> 10) == 0b110111:\n                res += chr(((ord(c) & 0x3ff) << 10 | (ord(n) & 0x3ff)) + 0x10000)\n                next(it)\n            else:\n                res += \"\\\\u{:04x}\".format(ord(c))\n        elif (ord(c) >> 10) == 0b110111:\n            res += \"\\\\u{:04x}\".format(ord(c))\n        else:\n            res += c\n    return res",
    "docstring": "Reorganize a String in such a way that surrogates are printable\n    and lonely surrogates are escaped.\n\n    :param s: input string\n    :return: string with escaped lonely surrogates and 32bit surrogates"
  },
  {
    "code": "def get_part_filenames(num_parts=None, start_num=0):\n    if num_parts is None:\n        num_parts = get_num_part_files()\n    return ['PART{0}.html'.format(i) for i in range(start_num+1, num_parts+1)]",
    "docstring": "Get numbered PART.html filenames."
  },
  {
    "code": "def _shuffle_single(fname, extra_fn=None):\n  records = read_records(fname)\n  random.shuffle(records)\n  if extra_fn is not None:\n    records = extra_fn(records)\n  out_fname = fname.replace(UNSHUFFLED_SUFFIX, \"\")\n  write_records(records, out_fname)\n  tf.gfile.Remove(fname)",
    "docstring": "Shuffle a single file of records.\n\n  Args:\n    fname: a string\n    extra_fn: an optional function from list of TFRecords to list of TFRecords\n      to be called after shuffling."
  },
  {
    "code": "def KL_divergence(P,Q):\n    assert(P.keys()==Q.keys())\n    distance = 0\n    for k in P.keys():\n        distance += P[k] * log(P[k]/Q[k])\n    return distance",
    "docstring": "Compute the KL divergence between distributions P and Q\n    \n    P and Q should be dictionaries linking symbols to probabilities.\n    the keys to P and Q should be the same."
  },
  {
    "code": "def export_event_based_gateway_info(node_params, output_element):\n        output_element.set(consts.Consts.gateway_direction, node_params[consts.Consts.gateway_direction])\n        output_element.set(consts.Consts.instantiate, node_params[consts.Consts.instantiate])\n        output_element.set(consts.Consts.event_gateway_type, node_params[consts.Consts.event_gateway_type])",
    "docstring": "Adds EventBasedGateway node attributes to exported XML element\n\n        :param node_params: dictionary with given event based gateway parameters,\n        :param output_element: object representing BPMN XML 'eventBasedGateway' element."
  },
  {
    "code": "def init(self):\n        self.url = self.url.format(host=self.host, port=self.port,\n                                   api_key=self.api_key)",
    "docstring": "Initialize the URL used to connect to SABnzbd."
  },
  {
    "code": "def import_submodules(package):\n    if isinstance(package, str):\n        package = importlib.import_module(package)\n    results = {}\n    for _, full_name, is_pkg in pkgutil.walk_packages(package.__path__, package.__name__ + '.'):\n        results[full_name] = importlib.import_module(full_name)\n        if is_pkg:\n            results.update(import_submodules(full_name))\n    return results",
    "docstring": "Return list of imported module instances from beneath root_package"
  },
  {
    "code": "def dump_commands(self, commands):\n        directory = os.path.join(os.path.dirname(self.sql_script), 'fails')\n        fname = os.path.basename(self.sql_script.rsplit('.')[0])\n        return dump_commands(commands, directory, fname)",
    "docstring": "Dump commands wrapper for external access."
  },
  {
    "code": "def get_manhole_factory(namespace, **passwords):\n    realm = manhole_ssh.TerminalRealm()\n    realm.chainedProtocolFactory.protocolFactory = (\n        lambda _: EnhancedColoredManhole(namespace)\n    )\n    p = portal.Portal(realm)\n    p.registerChecker(\n        checkers.InMemoryUsernamePasswordDatabaseDontUse(**passwords)\n    )\n    return manhole_ssh.ConchFactory(p)",
    "docstring": "Get a Manhole Factory"
  },
  {
    "code": "def load_modules_from_python(self, route_list):\n        for name, modpath in route_list:\n            if ':' in modpath:\n                path, attr = modpath.split(':', 1)\n            else:\n                path, attr = modpath, None\n            self.commands[name] = ModuleLoader(path, attr=attr)",
    "docstring": "Load modules from the native python source."
  },
  {
    "code": "def validate(obj, schema):\n  if not framework.EvaluationContext.current().validate:\n    return obj\n  if hasattr(obj, 'tuple_schema'):\n    obj.tuple_schema.validate(obj)\n  if schema:\n    schema.validate(obj)\n  return obj",
    "docstring": "Validate an object according to its own AND an externally imposed schema."
  },
  {
    "code": "def flat_model(tree):\n    names = []\n    for columns in viewvalues(tree):\n        for col in columns:\n            if isinstance(col, dict):\n                col_name = list(col)[0]\n                names += [col_name + '__' + c for c in flat_model(col)]\n            else:\n                names.append(col)\n    return names",
    "docstring": "Flatten the tree into a list of properties adding parents as prefixes."
  },
  {
    "code": "def layer(self, layer_name):\n        uri = self.layer_uri(layer_name)\n        layer = QgsVectorLayer(uri, layer_name, 'ogr')\n        if not layer.isValid():\n            layer = QgsRasterLayer(uri, layer_name)\n            if not layer.isValid():\n                return False\n        monkey_patch_keywords(layer)\n        return layer",
    "docstring": "Get QGIS layer.\n\n        :param layer_name: The name of the layer to fetch.\n        :type layer_name: str\n\n        :return: The QGIS layer.\n        :rtype: QgsMapLayer\n\n        .. versionadded:: 4.0"
  },
  {
    "code": "def iter_halfs_bend(graph):\n    for atom2 in range(graph.num_vertices):\n        neighbors = list(graph.neighbors[atom2])\n        for index1, atom1 in enumerate(neighbors):\n            for atom3 in neighbors[index1+1:]:\n                try:\n                    affected_atoms = graph.get_halfs(atom2, atom1)[0]\n                    yield affected_atoms, (atom1, atom2, atom3)\n                    continue\n                except GraphError:\n                    pass\n                try:\n                    affected_atoms = graph.get_halfs(atom2, atom3)[0]\n                    yield affected_atoms, (atom3, atom2, atom1)\n                except GraphError:\n                    pass",
    "docstring": "Select randomly two consecutive bonds that divide the molecule in two"
  },
  {
    "code": "def update_global_secondary_index(table_name, global_indexes, region=None,\n                                  key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    table = Table(table_name, connection=conn)\n    return table.update_global_secondary_index(global_indexes)",
    "docstring": "Updates the throughput of the given global secondary indexes.\n\n    CLI Example:\n    .. code-block:: bash\n\n        salt myminion boto_dynamodb.update_global_secondary_index table_name /\n        indexes"
  },
  {
    "code": "def _add(self, error: \"Err\"):\n        if self.trace_errs is True:\n            self.errors.append(error)",
    "docstring": "Adds an error to the trace if required"
  },
  {
    "code": "def format_py3o_val(value):\n    value = force_unicode(value)\n    value = escape(value)\n    value = value.replace(u'\\n', u'<text:line-break/>')\n    return Markup(value)",
    "docstring": "format a value to fit py3o's context\n\n    * Handle linebreaks"
  },
  {
    "code": "def page(self, number, **context):\n        size = max(0, self.context(**context).pageSize)\n        if not size:\n            return self.copy()\n        else:\n            return self.copy(page=number, pageSize=size)",
    "docstring": "Returns the records for the current page, or the specified page number.\n        If a page size is not specified, then this record sets page size will\n        be used.\n\n        :param      pageno   | <int>\n                    pageSize | <int>\n\n        :return     <orb.RecordSet>"
  },
  {
    "code": "def _handle_child(\n            self, node: SchemaNode, stmt: Statement, sctx: SchemaContext) -> None:\n        if not sctx.schema_data.if_features(stmt, sctx.text_mid):\n            return\n        node.name = stmt.argument\n        node.ns = sctx.default_ns\n        node._get_description(stmt)\n        self._add_child(node)\n        node._handle_substatements(stmt, sctx)",
    "docstring": "Add child node to the receiver and handle substatements."
  },
  {
    "code": "def desc(self) -> str:\n        kind, value = self.kind.value, self.value\n        return f\"{kind} {value!r}\" if value else kind",
    "docstring": "A helper property to describe a token as a string for debugging"
  },
  {
    "code": "def _deserialize(self, value, attr, obj):\n        if not self.context.get('convert_dates', True) or not value:\n            return value\n        value = super(PendulumField, self)._deserialize(value, attr, value)\n        timezone = self.get_field_value('timezone')\n        target = pendulum.instance(value)\n        if (timezone and (text_type(target) !=\n                          text_type(target.in_timezone(timezone)))):\n            raise ValidationError(\n                \"The provided datetime is not in the \"\n                \"{} timezone.\".format(timezone)\n            )\n        return target",
    "docstring": "Deserializes a string into a Pendulum object."
  },
  {
    "code": "def rule(self, key):\n        def register(f):\n            self.rules[key] = f\n            return f\n        return register",
    "docstring": "Decorate as a rule for a key in top level JSON."
  },
  {
    "code": "def repair(self, volume_id_or_uri, timeout=-1):\n        data = {\n            \"type\": \"ExtraManagedStorageVolumePaths\",\n            \"resourceUri\": self._client.build_uri(volume_id_or_uri)\n        }\n        custom_headers = {'Accept-Language': 'en_US'}\n        uri = self.URI + '/repair'\n        return self._client.create(data, uri=uri, timeout=timeout, custom_headers=custom_headers)",
    "docstring": "Removes extra presentations from a specified volume on the storage system.\n\n        Args:\n            volume_id_or_uri:\n                Can be either the volume id or the volume uri.\n            timeout:\n                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in\n                OneView, just stops waiting for its completion.\n\n        Returns:\n            dict: Storage volume."
  },
  {
    "code": "def install_middleware(middleware_name, lookup_names=None):\n    if lookup_names is None:\n        lookup_names = (middleware_name,)\n    middleware_attr = 'MIDDLEWARE' if getattr(settings,\n                                              'MIDDLEWARE',\n                                              None) is not None \\\n        else 'MIDDLEWARE_CLASSES'\n    middleware = getattr(settings, middleware_attr, ()) or ()\n    if set(lookup_names).isdisjoint(set(middleware)):\n        setattr(settings,\n                middleware_attr,\n                type(middleware)((middleware_name,)) + middleware)",
    "docstring": "Install specified middleware"
  },
  {
    "code": "def mouseDoubleClickEvent(self, event):\r\n        if self.rename_tabs is True and \\\r\n                event.buttons() == Qt.MouseButtons(Qt.LeftButton):\r\n            index = self.tabAt(event.pos())\r\n            if index >= 0:\r\n                self.tab_name_editor.edit_tab(index)\r\n        else:\r\n            QTabBar.mouseDoubleClickEvent(self, event)",
    "docstring": "Override Qt method to trigger the tab name editor."
  },
  {
    "code": "async def recv_message(self):\n        if not self._recv_initial_metadata_done:\n            await self.recv_initial_metadata()\n        with self._wrapper:\n            message = await recv_message(self._stream, self._codec,\n                                         self._recv_type)\n            self._recv_message_count += 1\n            message, = await self._dispatch.recv_message(message)\n            return message",
    "docstring": "Coroutine to receive incoming message from the server.\n\n        If server sends UNARY response, then you can call this coroutine only\n        once. If server sends STREAM response, then you should call this\n        coroutine several times, until it returns None. To simplify you code in\n        this case, :py:class:`Stream` implements async iterations protocol, so\n        you can use it like this:\n\n        .. code-block:: python3\n\n            async for massage in stream:\n                do_smth_with(message)\n\n        or even like this:\n\n        .. code-block:: python3\n\n            messages = [msg async for msg in stream]\n\n        HTTP/2 has flow control mechanism, so client will acknowledge received\n        DATA frames as a message only after user consumes this coroutine.\n\n        :returns: message"
  },
  {
    "code": "def set_source_variable(self, source_id, variable, value):\n        source_id = int(source_id)\n        return self._send_cmd(\"SET S[%d].%s=\\\"%s\\\"\" % (\n            source_id, variable, value))",
    "docstring": "Change the value of a source variable."
  },
  {
    "code": "def _create_and_add_parameters(params):\n    global _current_parameter\n    if _is_simple_type(params):\n        _current_parameter = SimpleParameter(params)\n        _current_option.add_parameter(_current_parameter)\n    else:\n        for i in params:\n            if _is_simple_type(i):\n                _current_parameter = SimpleParameter(i)\n            else:\n                _current_parameter = TypedParameter()\n                _parse_typed_parameter(i)\n            _current_option.add_parameter(_current_parameter)",
    "docstring": "Parses the configuration and creates Parameter instances."
  },
  {
    "code": "def simulate(self, ts_length=100, random_state=None):\n        r\n        random_state = check_random_state(random_state)\n        x0 = multivariate_normal(self.mu_0.flatten(), self.Sigma_0)\n        w = random_state.randn(self.m, ts_length-1)\n        v = self.C.dot(w)\n        x = simulate_linear_model(self.A, x0, v, ts_length)\n        if self.H is not None:\n            v = random_state.randn(self.l, ts_length)\n            y = self.G.dot(x) + self.H.dot(v)\n        else:\n            y = self.G.dot(x)\n        return x, y",
    "docstring": "r\"\"\"\n        Simulate a time series of length ts_length, first drawing\n\n        .. math::\n\n            x_0 \\sim N(\\mu_0, \\Sigma_0)\n\n        Parameters\n        ----------\n        ts_length : scalar(int), optional(default=100)\n            The length of the simulation\n        random_state : int or np.random.RandomState, optional\n            Random seed (integer) or np.random.RandomState instance to set\n            the initial state of the random number generator for\n            reproducibility. If None, a randomly initialized RandomState is\n            used.\n\n        Returns\n        -------\n        x : array_like(float)\n            An n x ts_length array, where the t-th column is :math:`x_t`\n        y : array_like(float)\n            A k x ts_length array, where the t-th column is :math:`y_t`"
  },
  {
    "code": "def _check_time_fn(self, time_instance=False):\n        if time_instance and not isinstance(self.time_fn, param.Time):\n            raise AssertionError(\"%s requires a Time object\"\n                                 % self.__class__.__name__)\n        if self.time_dependent:\n            global_timefn = self.time_fn is param.Dynamic.time_fn\n            if global_timefn and not param.Dynamic.time_dependent:\n                raise AssertionError(\"Cannot use Dynamic.time_fn as\"\n                                     \" parameters are ignoring time.\")",
    "docstring": "If time_fn is the global time function supplied by\n        param.Dynamic.time_fn, make sure Dynamic parameters are using\n        this time function to control their behaviour.\n\n        If time_instance is True, time_fn must be a param.Time instance."
  },
  {
    "code": "def on(self, year, month, day):\n        return self.set(year=int(year), month=int(month), day=int(day))",
    "docstring": "Returns a new instance with the current date set to a different date.\n\n        :param year: The year\n        :type year: int\n\n        :param month: The month\n        :type month: int\n\n        :param day: The day\n        :type day: int\n\n        :rtype: DateTime"
  },
  {
    "code": "def _get_rom_firmware_version(self, data):\n        firmware_details = self._get_firmware_embedded_health(data)\n        if firmware_details:\n            try:\n                rom_firmware_version = (\n                    firmware_details['HP ProLiant System ROM'])\n                return {'rom_firmware_version': rom_firmware_version}\n            except KeyError:\n                return None",
    "docstring": "Gets the rom firmware version for server capabilities\n\n        Parse the get_host_health_data() to retreive the firmware\n        details.\n\n        :param data: the output returned by get_host_health_data()\n        :returns: a dictionary of rom firmware version."
  },
  {
    "code": "def accept_line(self, logevent):\n        if (\"is now in state\" in logevent.line_str and\n                logevent.split_tokens[-1] in self.states):\n            return True\n        if (\"replSet\" in logevent.line_str and\n                logevent.thread == \"rsMgr\" and\n                logevent.split_tokens[-1] in self.states):\n            return True\n        return False",
    "docstring": "Return True on match.\n\n        Only match log lines containing 'is now in state' (reflects other\n        node's state changes) or of type \"[rsMgr] replSet PRIMARY\" (reflects\n        own state changes)."
  },
  {
    "code": "def intcomma(value):\n    try:\n        if isinstance(value, compat.string_types):\n            float(value.replace(',', ''))\n        else:\n            float(value)\n    except (TypeError, ValueError):\n        return value\n    orig = str(value)\n    new = re.sub(\"^(-?\\d+)(\\d{3})\", '\\g<1>,\\g<2>', orig)\n    if orig == new:\n        return new\n    else:\n        return intcomma(new)",
    "docstring": "Converts an integer to a string containing commas every three digits.\n    For example, 3000 becomes '3,000' and 45000 becomes '45,000'.  To maintain\n    some compatability with Django's intcomma, this function also accepts\n    floats."
  },
  {
    "code": "def disaggregate_wind(wind_daily, method='equal', a=None, b=None, t_shift=None):\n    assert method in ('equal', 'cosine', 'random'), 'Invalid method'\n    wind_eq = melodist.distribute_equally(wind_daily)\n    if method == 'equal':\n        wind_disagg = wind_eq\n    elif method == 'cosine':\n        assert None not in (a, b, t_shift)\n        wind_disagg = _cosine_function(np.array([wind_eq.values, wind_eq.index.hour]), a, b, t_shift)\n    elif method == 'random':\n        wind_disagg = wind_eq * (-np.log(np.random.rand(len(wind_eq))))**0.3\n    return wind_disagg",
    "docstring": "general function for windspeed disaggregation\n\n    Args:\n        wind_daily: daily values\n        method: keyword specifying the disaggregation method to be used\n        a: parameter a for the cosine function\n        b: parameter b for the cosine function\n        t_shift: parameter t_shift for the cosine function\n        \n    Returns:\n        Disaggregated hourly values of windspeed."
  },
  {
    "code": "def is_unix(name=None):\n        name = name or sys.platform\n        return Platform.is_darwin(name) or Platform.is_linux(name) or Platform.is_freebsd(name)",
    "docstring": "Return true if the platform is a unix, False otherwise."
  },
  {
    "code": "def pop(self):\n        if self.stack:\n            val = self.stack[0]\n            self.stack = self.stack[1:]\n            return val\n        else:\n            raise StackError('Stack empty')",
    "docstring": "Pops a value off the top of the stack.\n\n        @return: Value popped off the stack.\n        @rtype: *\n\n        @raise StackError: Raised when there is a stack underflow."
  },
  {
    "code": "def encode_offset_commit_request(cls, client_id, correlation_id,\n                                     group, payloads):\n        grouped_payloads = group_by_topic_and_partition(payloads)\n        message = []\n        message.append(cls._encode_message_header(client_id, correlation_id,\n                                                  KafkaProtocol.OFFSET_COMMIT_KEY))\n        message.append(write_short_string(group))\n        message.append(struct.pack('>i', len(grouped_payloads)))\n        for topic, topic_payloads in grouped_payloads.items():\n            message.append(write_short_string(topic))\n            message.append(struct.pack('>i', len(topic_payloads)))\n            for partition, payload in topic_payloads.items():\n                message.append(struct.pack('>iq', partition, payload.offset))\n                message.append(write_short_string(payload.metadata))\n        msg = b''.join(message)\n        return struct.pack('>i%ds' % len(msg), len(msg), msg)",
    "docstring": "Encode some OffsetCommitRequest structs\n\n        Arguments:\n            client_id: string\n            correlation_id: int\n            group: string, the consumer group you are committing offsets for\n            payloads: list of OffsetCommitRequest"
  },
  {
    "code": "def at_block_number(block_number: BlockNumber, chain: MiningChain) -> MiningChain:\n    if not isinstance(chain, MiningChain):\n        raise ValidationError(\"`at_block_number` may only be used with 'MiningChain\")\n    at_block = chain.get_canonical_block_by_number(block_number)\n    db = chain.chaindb.db\n    chain_at_block = type(chain)(db, chain.create_header_from_parent(at_block.header))\n    return chain_at_block",
    "docstring": "Rewind the chain back to the given block number.  Calls to things like\n    ``get_canonical_head`` will still return the canonical head of the chain,\n    however, you can use ``mine_block`` to mine fork chains."
  },
  {
    "code": "def unlock_password(self, ID, reason):\n        log.info('Unlock password %s, Reason: %s' % (ID, reason))\n        self.unlock_reason = reason\n        self.put('passwords/%s/unlock.json' % ID)",
    "docstring": "Unlock a password."
  },
  {
    "code": "def set_iscsi_info(self, target_name, lun, ip_address,\n                       port='3260', auth_method=None, username=None,\n                       password=None):\n        if(self._is_boot_mode_uefi()):\n            iscsi_info = {}\n            iscsi_info['iSCSITargetName'] = target_name\n            iscsi_info['iSCSILUN'] = lun\n            iscsi_info['iSCSITargetIpAddress'] = ip_address\n            iscsi_info['iSCSITargetTcpPort'] = int(port)\n            iscsi_info['iSCSITargetInfoViaDHCP'] = False\n            iscsi_info['iSCSIConnection'] = 'Enabled'\n            if (auth_method == 'CHAP'):\n                iscsi_info['iSCSIAuthenticationMethod'] = 'Chap'\n                iscsi_info['iSCSIChapUsername'] = username\n                iscsi_info['iSCSIChapSecret'] = password\n            self._change_iscsi_target_settings(iscsi_info)\n        else:\n            msg = 'iSCSI boot is not supported in the BIOS boot mode'\n            raise exception.IloCommandNotSupportedInBiosError(msg)",
    "docstring": "Set iSCSI details of the system in UEFI boot mode.\n\n        The initiator system is set with the target details like\n        IQN, LUN, IP, Port etc.\n        :param target_name: Target Name for iSCSI.\n        :param lun: logical unit number.\n        :param ip_address: IP address of the target.\n        :param port: port of the target.\n        :param auth_method : either None or CHAP.\n        :param username: CHAP Username for authentication.\n        :param password: CHAP secret.\n        :raises: IloCommandNotSupportedInBiosError, if the system is\n                 in the bios boot mode."
  },
  {
    "code": "def expandf(m, format):\n    _assert_expandable(format, True)\n    return _apply_replace_backrefs(m, format, flags=FORMAT)",
    "docstring": "Expand the string using the format replace pattern or function."
  },
  {
    "code": "def set_viewbox(self, x, y, w, h):\n        self.attributes['viewBox'] = \"%s %s %s %s\" % (x, y, w, h)\n        self.attributes['preserveAspectRatio'] = 'none'",
    "docstring": "Sets the origin and size of the viewbox, describing a virtual view area.\n\n        Args:\n            x (int): x coordinate of the viewbox origin\n            y (int): y coordinate of the viewbox origin\n            w (int): width of the viewbox\n            h (int): height of the viewbox"
  },
  {
    "code": "def anchor(args):\n    from jcvi.formats.blast import bed\n    p = OptionParser(anchor.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n    mapbed, blastfile = args\n    bedfile = bed([blastfile])\n    markersbed = Bed(bedfile)\n    markers = markersbed.order\n    mapbed = Bed(mapbed, sorted=False)\n    for b in mapbed:\n        m = b.accn\n        if m not in markers:\n            continue\n        i, mb = markers[m]\n        new_accn = \"{0}:{1}-{2}\".format(mb.seqid, mb.start, mb.end)\n        b.accn = new_accn\n        print(b)",
    "docstring": "%prog anchor map.bed markers.blast > anchored.bed\n\n    Anchor scaffolds based on map."
  },
  {
    "code": "def getServiceRequest(self, request, target):\n        try:\n            return self._request_class(\n                request.envelope, self.services[target], None)\n        except KeyError:\n            pass\n        try:\n            sp = target.split('.')\n            name, meth = '.'.join(sp[:-1]), sp[-1]\n            return self._request_class(\n                request.envelope, self.services[name], meth)\n        except (ValueError, KeyError):\n            pass\n        raise UnknownServiceError(\"Unknown service %s\" % target)",
    "docstring": "Returns a service based on the message.\n\n        @raise UnknownServiceError: Unknown service.\n        @param request: The AMF request.\n        @type request: L{Request<pyamf.remoting.Request>}\n        @rtype: L{ServiceRequest}"
  },
  {
    "code": "def add_port_forward_rule(self, is_ipv6, rule_name, proto, host_ip, host_port, guest_ip, guest_port):\n        if not isinstance(is_ipv6, bool):\n            raise TypeError(\"is_ipv6 can only be an instance of type bool\")\n        if not isinstance(rule_name, basestring):\n            raise TypeError(\"rule_name can only be an instance of type basestring\")\n        if not isinstance(proto, NATProtocol):\n            raise TypeError(\"proto can only be an instance of type NATProtocol\")\n        if not isinstance(host_ip, basestring):\n            raise TypeError(\"host_ip can only be an instance of type basestring\")\n        if not isinstance(host_port, baseinteger):\n            raise TypeError(\"host_port can only be an instance of type baseinteger\")\n        if not isinstance(guest_ip, basestring):\n            raise TypeError(\"guest_ip can only be an instance of type basestring\")\n        if not isinstance(guest_port, baseinteger):\n            raise TypeError(\"guest_port can only be an instance of type baseinteger\")\n        self._call(\"addPortForwardRule\",\n                     in_p=[is_ipv6, rule_name, proto, host_ip, host_port, guest_ip, guest_port])",
    "docstring": "Protocol handled with the rule.\n\n        in is_ipv6 of type bool\n\n        in rule_name of type str\n\n        in proto of type :class:`NATProtocol`\n            Protocol handled with the rule.\n\n        in host_ip of type str\n            IP of the host interface to which the rule should apply.\n            An empty ip address is acceptable, in which case the NAT engine\n            binds the handling socket to any interface.\n\n        in host_port of type int\n            The port number to listen on.\n\n        in guest_ip of type str\n            The IP address of the guest which the NAT engine will forward\n            matching packets to. An empty IP address is not acceptable.\n\n        in guest_port of type int\n            The port number to forward."
  },
  {
    "code": "def _tot_unhandled_hosts_by_state(self, state):\n        return sum(1 for h in self.hosts if h.state == state and h.state_type == u'HARD' and\n                   h.is_problem and not h.problem_has_been_acknowledged)",
    "docstring": "Generic function to get the number of unhandled problem hosts in the specified state\n\n        :param state: state to filter on\n        :type state:\n        :return: number of host in state *state* and which are not acknowledged problems\n        :rtype: int"
  },
  {
    "code": "def _apply_key_type(self, keys):\n        typed_key = ()\n        for dim, key in zip(self.kdims, keys):\n            key_type = dim.type\n            if key_type is None:\n                typed_key += (key,)\n            elif isinstance(key, slice):\n                sl_vals = [key.start, key.stop, key.step]\n                typed_key += (slice(*[key_type(el) if el is not None else None\n                                      for el in sl_vals]),)\n            elif key is Ellipsis:\n                typed_key += (key,)\n            elif isinstance(key, list):\n                typed_key += ([key_type(k) for k in key],)\n            else:\n                typed_key += (key_type(key),)\n        return typed_key",
    "docstring": "If a type is specified by the corresponding key dimension,\n        this method applies the type to the supplied key."
  },
  {
    "code": "def get_archive(self, archive_name):\n        try:\n            spec = self._get_archive_spec(archive_name)\n            return spec\n        except KeyError:\n            raise KeyError('Archive \"{}\" not found'.format(archive_name))",
    "docstring": "Get a data archive given an archive name\n\n        Returns\n        -------\n        archive_specification : dict\n            archive_name: name of the archive to be retrieved\n            authority: name of the archive's authority\n            archive_path: service path of archive"
  },
  {
    "code": "def is_config_container(v):\n    cls = type(v)\n    return (\n        issubclass(cls, list) or\n        issubclass(cls, dict) or\n        issubclass(cls, Config)\n    )",
    "docstring": "checks whether v is of type list,dict or Config"
  },
  {
    "code": "def declare_queue(self, queue_name):\n        attempts = 1\n        while True:\n            try:\n                if queue_name not in self.queues:\n                    self.emit_before(\"declare_queue\", queue_name)\n                    self._declare_queue(queue_name)\n                    self.queues.add(queue_name)\n                    self.emit_after(\"declare_queue\", queue_name)\n                    delayed_name = dq_name(queue_name)\n                    self._declare_dq_queue(queue_name)\n                    self.delay_queues.add(delayed_name)\n                    self.emit_after(\"declare_delay_queue\", delayed_name)\n                    self._declare_xq_queue(queue_name)\n                break\n            except (pika.exceptions.AMQPConnectionError,\n                    pika.exceptions.AMQPChannelError) as e:\n                del self.channel\n                del self.connection\n                attempts += 1\n                if attempts > MAX_DECLARE_ATTEMPTS:\n                    raise ConnectionClosed(e) from None\n                self.logger.debug(\n                    \"Retrying declare due to closed connection. [%d/%d]\",\n                    attempts, MAX_DECLARE_ATTEMPTS,\n                )",
    "docstring": "Declare a queue.  Has no effect if a queue with the given\n        name already exists.\n\n        Parameters:\n          queue_name(str): The name of the new queue.\n\n        Raises:\n          ConnectionClosed: If the underlying channel or connection\n            has been closed."
  },
  {
    "code": "def _get_thumbnail_filename(filename, append_text=\"-thumbnail\"):\n    name, ext = os.path.splitext(filename)\n    return ''.join([name, append_text, ext])",
    "docstring": "Returns a thumbnail version of the file name."
  },
  {
    "code": "def types_of_specie(self):\n        if not self.is_ordered:\n            raise TypeError(\n)\n        types = []\n        for site in self:\n            if site.specie not in types:\n                types.append(site.specie)\n        return types",
    "docstring": "List of types of specie. Only works for ordered structures.\n        Disordered structures will raise TypeError."
  },
  {
    "code": "def get_SZ_orient(self):\n        tm_outdated = self._tm_signature != (self.radius, self.radius_type, \n            self.wavelength, self.m, self.axis_ratio, self.shape, self.ddelt, \n            self.ndgs)\n        scatter_outdated = self._scatter_signature != (self.thet0, self.thet, \n            self.phi0, self.phi, self.alpha, self.beta, self.orient)\n        orient_outdated = self._orient_signature != \\\n            (self.orient, self.or_pdf, self.n_alpha, self.n_beta)\n        if orient_outdated:\n            self._init_orient()\n        outdated = tm_outdated or scatter_outdated or orient_outdated\n        if outdated:\n            (self._S_orient, self._Z_orient) = self.orient(self)\n            self._set_scatter_signature()\n        return (self._S_orient, self._Z_orient)",
    "docstring": "Get the S and Z matrices using the specified orientation averaging."
  },
  {
    "code": "def load_structure_path(self, structure_path, file_type):\n        if not file_type:\n            raise ValueError('File type must be specified')\n        self.file_type = file_type\n        self.structure_dir = op.dirname(structure_path)\n        self.structure_file = op.basename(structure_path)",
    "docstring": "Load a structure file and provide pointers to its location\n\n        Args:\n            structure_path (str): Path to structure file\n            file_type (str): Type of structure file"
  },
  {
    "code": "async def oauth2_request(\n        self,\n        url: str,\n        access_token: str = None,\n        post_args: Dict[str, Any] = None,\n        **args: Any\n    ) -> Any:\n        all_args = {}\n        if access_token:\n            all_args[\"access_token\"] = access_token\n            all_args.update(args)\n        if all_args:\n            url += \"?\" + urllib.parse.urlencode(all_args)\n        http = self.get_auth_http_client()\n        if post_args is not None:\n            response = await http.fetch(\n                url, method=\"POST\", body=urllib.parse.urlencode(post_args)\n            )\n        else:\n            response = await http.fetch(url)\n        return escape.json_decode(response.body)",
    "docstring": "Fetches the given URL auth an OAuth2 access token.\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        Example usage:\n\n        ..testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.FacebookGraphMixin):\n                @tornado.web.authenticated\n                async def get(self):\n                    new_entry = await self.oauth2_request(\n                        \"https://graph.facebook.com/me/feed\",\n                        post_args={\"message\": \"I am posting from my Tornado application!\"},\n                        access_token=self.current_user[\"access_token\"])\n\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        await self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        .. versionadded:: 4.3\n\n        .. versionchanged::: 6.0\n\n           The ``callback`` argument was removed. Use the returned awaitable object instead."
  },
  {
    "code": "def addJsonDirectory(self, directory, test=None):\n    for filename in os.listdir(directory):\n      try:\n        fullPath = os.path.join(directory, filename)\n        if not test or test(filename, fullPath):\n          with open(fullPath) as f:\n            jsonData = json.load(f)\n            name, _ = os.path.splitext(filename)\n            self.addSource(name, jsonData)\n      except ValueError:\n        continue",
    "docstring": "Adds data from json files in the given directory."
  },
  {
    "code": "def update_tasks(self):\n        for task in self.task_manager.timeout_tasks():\n            self.task_manager.task_done(\n                task.id, TimeoutError(\"Task timeout\", task.timeout))\n            self.worker_manager.stop_worker(task.worker_id)\n        for task in self.task_manager.cancelled_tasks():\n            self.task_manager.task_done(\n                task.id, CancelledError())\n            self.worker_manager.stop_worker(task.worker_id)",
    "docstring": "Handles timing out Tasks."
  },
  {
    "code": "def add_logging_args(parser: argparse.ArgumentParser, patch: bool = True,\n                     erase_args: bool = True) -> None:\n    parser.add_argument(\"--log-level\", default=\"INFO\", choices=logging._nameToLevel,\n                        help=\"Logging verbosity.\")\n    parser.add_argument(\"--log-structured\", action=\"store_true\",\n                        help=\"Enable structured logging (JSON record per line).\")\n    parser.add_argument(\"--log-config\",\n                        help=\"Path to the file which sets individual log levels of domains.\")\n    def _patched_parse_args(args=None, namespace=None) -> argparse.Namespace:\n        args = parser._original_parse_args(args, namespace)\n        setup(args.log_level, args.log_structured, args.log_config)\n        if erase_args:\n            for log_arg in (\"log_level\", \"log_structured\", \"log_config\"):\n                delattr(args, log_arg)\n        return args\n    if patch and not hasattr(parser, \"_original_parse_args\"):\n        parser._original_parse_args = parser.parse_args\n        parser.parse_args = _patched_parse_args",
    "docstring": "Add command line flags specific to logging.\n\n    :param parser: `argparse` parser where to add new flags.\n    :param erase_args: Automatically remove logging-related flags from parsed args.\n    :param patch: Patch parse_args() to automatically setup logging."
  },
  {
    "code": "def register(cls, name: str, plugin: Type[ConnectionPlugin]) -> None:\n        existing_plugin = cls.available.get(name)\n        if existing_plugin is None:\n            cls.available[name] = plugin\n        elif existing_plugin != plugin:\n            raise ConnectionPluginAlreadyRegistered(\n                f\"Connection plugin {plugin.__name__} can't be registered as \"\n                f\"{name!r} because plugin {existing_plugin.__name__} \"\n                f\"was already registered under this name\"\n            )",
    "docstring": "Registers a connection plugin with a specified name\n\n        Args:\n            name: name of the connection plugin to register\n            plugin: defined connection plugin class\n\n        Raises:\n            :obj:`nornir.core.exceptions.ConnectionPluginAlreadyRegistered` if\n                another plugin with the specified name was already registered"
  },
  {
    "code": "def save_list(key, *values):\n    return json.dumps({key: [_get_json(value) for value in values]})",
    "docstring": "Convert the given list of parameters to a JSON object.\n\n    JSON object is of the form:\n    { key: [values[0], values[1], ... ] },\n    where values represent the given list of parameters."
  },
  {
    "code": "def spec(self):\n        pspec = {}\n        pspec['name'] = self.NAME\n        pspec['version'] = self.VERSION\n        pspec['description'] = self.DESCRIPTION\n        components = [sys.argv[0], self.NAME]\n        if self.USE_ARGUMENTS: components.append('$(arguments)')\n        pspec['exe_command'] = self.COMMAND or ' '.join(components)\n        pspec['inputs'] = [ inp.spec for inp in self.INPUTS ]\n        pspec['outputs'] = [ out.spec for out in self.OUTPUTS ]\n        pspec['parameters'] = [ param.spec for param in self.PARAMETERS ]\n        if hasattr(self, 'test') and callable(self.test):\n            pspec['has_test'] = True\n        return pspec",
    "docstring": "Generate spec for the processor as a Python dictionary.\n\n        A spec is a standard way to describe a MountainLab processor in a way\n        that is easy to process, yet still understandable by humans.\n        This method generates a Python dictionary that complies with a spec\n        definition."
  },
  {
    "code": "def clone(self, substitutions, commit=True, **kwargs):\n        return self.store.clone(substitutions, **kwargs)",
    "docstring": "Clone a DAG, optionally skipping the commit."
  },
  {
    "code": "def _env_filenames(filenames, env):\n    env_filenames = []\n    for filename in filenames:\n        filename_parts = filename.split('.')\n        filename_parts.insert(1, env)\n        env_filenames.extend([filename, '.'.join(filename_parts)])\n    return env_filenames",
    "docstring": "Extend filenames with ennv indication of environments.\n\n    :param list filenames: list of strings indicating filenames\n    :param str env: environment indicator\n\n    :returns: list of filenames extended with environment version\n    :rtype: list"
  },
  {
    "code": "def get_p2o_params_from_url(cls, url):\n        if PRJ_JSON_FILTER_SEPARATOR not in url:\n            return {\"url\": url}\n        params = {'url': url.split(' ', 1)[0]}\n        tokens = url.split(PRJ_JSON_FILTER_SEPARATOR)[1:]\n        if len(tokens) > 1:\n            cause = \"Too many filters defined for %s, only the first one is considered\" % url\n            logger.warning(cause)\n        token = tokens[0]\n        filter_tokens = token.split(PRJ_JSON_FILTER_OP_ASSIGNMENT)\n        if len(filter_tokens) != 2:\n            cause = \"Too many tokens after splitting for %s in %s\" % (token, url)\n            logger.error(cause)\n            raise ELKError(cause=cause)\n        fltr_name = filter_tokens[0].strip()\n        fltr_value = filter_tokens[1].strip()\n        params['filter-' + fltr_name] = fltr_value\n        return params",
    "docstring": "Get the p2o params given a URL for the data source"
  },
  {
    "code": "def init_threads(t=None, s=None):\n    global THREAD, SIGNAL\n    THREAD = t or dummyThread\n    SIGNAL = s or dummySignal",
    "docstring": "Should define dummyThread class and dummySignal class"
  },
  {
    "code": "def accounts(self):\n        response = self.graph.get('%s/accounts' % self.id)\n        accounts = []\n        for item in response['data']:\n            account = Structure(\n                page = Page(\n                    id = item['id'],\n                    name = item['name'],\n                    category = item['category']\n                ),\n                access_token = item['access_token'],\n                permissions = item['perms']\n            )\n            accounts.append(account)\n        return accounts",
    "docstring": "A list of structures describing apps and pages owned by this user."
  },
  {
    "code": "def get_valid_kwargs(func, potential_kwargs):\n    kwargs = {}\n    for name in get_kwarg_names(func):\n        with suppress(KeyError):\n            kwargs[name] = potential_kwargs[name]\n    return kwargs",
    "docstring": "Return valid kwargs to function func"
  },
  {
    "code": "def _readXput(self, fileCards, directory, session, spatial=False, spatialReferenceID=4236, replaceParamFile=None):\n        for card in self.projectCards:\n            if (card.name in fileCards) and self._noneOrNumValue(card.value) and fileCards[card.name]:\n                fileIO = fileCards[card.name]\n                filename = card.value.strip('\"')\n                self._invokeRead(fileIO=fileIO,\n                                 directory=directory,\n                                 filename=filename,\n                                 session=session,\n                                 spatial=spatial,\n                                 spatialReferenceID=spatialReferenceID,\n                                 replaceParamFile=replaceParamFile)",
    "docstring": "GSSHAPY Project Read Files from File Method"
  },
  {
    "code": "def join(self):\n        while True:\n            for consumer in self.consumers.values():\n                consumer.delay_queue.join()\n            self.work_queue.join()\n            for consumer in self.consumers.values():\n                if consumer.delay_queue.unfinished_tasks:\n                    break\n            else:\n                if self.work_queue.unfinished_tasks:\n                    continue\n                return",
    "docstring": "Wait for this worker to complete its work in progress.\n        This method is useful when testing code."
  },
  {
    "code": "def loads(self, param):\n        if isinstance(param, ProxyRef):\n            try:\n                return self.lookup_url(param.url, param.klass, param.module)\n            except HostError:\n                print \"Can't lookup for the actor received with the call. \\\n                    It does not exist or the url is unreachable.\", param\n                raise HostError(param)\n        elif isinstance(param, list):\n            return [self.loads(elem) for elem in param]\n        elif isinstance(param, tuple):\n            return tuple([self.loads(elem) for elem in param])\n        elif isinstance(param, dict):\n            new_dict = param\n            for key in new_dict.keys():\n                new_dict[key] = self.loads(new_dict[key])\n            return new_dict\n        else:\n            return param",
    "docstring": "Checks the return parameters generating new proxy instances to\n        avoid query concurrences from shared proxies and creating\n        proxies for actors from another host."
  },
  {
    "code": "def child(self, path):\n        if self._shareID is not None:\n            self = url.URL.child(self, self._shareID)\n            self._shareID = None\n        return url.URL.child(self, path)",
    "docstring": "Override the base implementation to inject the share ID our\n        constructor was passed."
  },
  {
    "code": "def remove_duplicate_faces(self):\n        unique, inverse = grouping.unique_rows(np.sort(self.faces, axis=1))\n        self.update_faces(unique)",
    "docstring": "On the current mesh remove any faces which are duplicates.\n\n        Alters\n        ----------\n        self.faces : removes duplicates"
  },
  {
    "code": "def cublasSsymm(handle, side, uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc):\n    status = _libcublas.cublasSsymm_v2(handle,\n                                       _CUBLAS_SIDE_MODE[side], \n                                       _CUBLAS_FILL_MODE[uplo], \n                                       m, n, ctypes.byref(ctypes.c_float(alpha)),\n                                       int(A), lda, int(B), ldb, \n                                       ctypes.byref(ctypes.c_float(beta)), \n                                       int(C), ldc)\n    cublasCheckStatus(status)",
    "docstring": "Matrix-matrix product for symmetric matrix."
  },
  {
    "code": "def main_production(self):\n        for rule in self.productions:\n            if rule.leftside[0] == self._initialsymbol:\n                return rule\n        raise IndexError",
    "docstring": "Returns main rule"
  },
  {
    "code": "def get_upper_triangle(correlation_matrix):\n    upper_triangle = correlation_matrix.where(np.triu(np.ones(correlation_matrix.shape), k=1).astype(np.bool))\n    upper_tri_df = upper_triangle.stack().reset_index(level=1)\n    upper_tri_df.columns = ['rid', 'corr']\n    upper_tri_df.reset_index(level=0, inplace=True)\n    upper_tri_df['corr'] = upper_tri_df['corr'].clip(lower=0)\n    return upper_tri_df.round(rounding_precision)",
    "docstring": "Extract upper triangle from a square matrix. Negative values are\n    set to 0.\n\n    Args:\n    correlation_matrix (pandas df): Correlations between all replicates\n\n    Returns:\n    upper_tri_df (pandas df): Upper triangle extracted from\n        correlation_matrix; rid is the row index, cid is the column index,\n        corr is the extracted correlation value"
  },
  {
    "code": "def labels(self):\n        return [\n            name for name in os.listdir(self.root)\n            if os.path.isdir(os.path.join(self.root, name))\n        ]",
    "docstring": "Return the unique labels assigned to the documents."
  },
  {
    "code": "def _run_task(task, start_message, finished_message):\n    env.hosts = fabconf['EC2_INSTANCES']\n    start = time.time()\n    if env.hosts == []:\n        print(\"There are EC2 instances defined in project_conf.py, please add some instances and try again\")\n        print(\"or run 'fab spawn_instance' to create an instance\")\n        return\n    print(_yellow(start_message))\n    for item in task:\n        try:\n            print(_yellow(item['message']))\n        except KeyError:\n            pass\n        globals()[\"_\" + item['action']](item['params'])\n    print(_yellow(\"%s in %.2fs\" % (finished_message, time.time() - start)))",
    "docstring": "Tasks a task from tasks.py and runs through the commands on the server"
  },
  {
    "code": "def asksaveasfile(mode=\"w\", **options):\n    \"Ask for a filename to save as, and returned the opened file\"\n    filename = asksaveasfilename(**options)\n    if filename:\n        return open(filename, mode)\n    return None",
    "docstring": "Ask for a filename to save as, and returned the opened file"
  },
  {
    "code": "def unique_(self, col):\n        try:\n            df = self.df.drop_duplicates(subset=[col], inplace=False)\n            return list(df[col])\n        except Exception as e:\n            self.err(e, \"Can not select unique data\")",
    "docstring": "Returns unique values in a column"
  },
  {
    "code": "def _validate_storage(storage, service_name, add_error):\n    if storage is None:\n        return\n    if not isdict(storage):\n        msg = 'service {} has invalid storage constraints {}'.format(\n            service_name, storage)\n        add_error(msg)",
    "docstring": "Lazily validate the storage constraints, ensuring that they are a dict.\n\n    Use the given add_error callable to register validation error."
  },
  {
    "code": "def cache_path(self):\n        cache_path = os.path.join(os.path.dirname(__file__), '..', 'cache')\n        if not os.path.exists(cache_path):\n            os.mkdir(cache_path)\n        return cache_path",
    "docstring": "make a directory to store all caches\n\n        Returns:\n        ---------\n            cache path"
  },
  {
    "code": "def get_user_token():\n    if not hasattr(stack.top, 'current_user'):\n        return ''\n    current_user = stack.top.current_user\n    return current_user.get('token', '')",
    "docstring": "Return the authenticated user's auth token"
  },
  {
    "code": "def zrank(self, name, value):\n        with self.pipe as pipe:\n            value = self.valueparse.encode(value)\n            return pipe.zrank(self.redis_key(name), value)",
    "docstring": "Returns the rank of the element.\n\n        :param name: str     the name of the redis key\n        :param value: the element in the sorted set"
  },
  {
    "code": "def escape(url):\n    if salt.utils.platform.is_windows():\n        return url\n    scheme = urlparse(url).scheme\n    if not scheme:\n        if url.startswith('|'):\n            return url\n        else:\n            return '|{0}'.format(url)\n    elif scheme == 'salt':\n        path, saltenv = parse(url)\n        if path.startswith('|'):\n            return create(path, saltenv)\n        else:\n            return create('|{0}'.format(path), saltenv)\n    else:\n        return url",
    "docstring": "add escape character `|` to `url`"
  },
  {
    "code": "def set_destination_ip_responded(self, last_hop):\n        if not self.destination_address:\n            return\n        for packet in last_hop.packets:\n            if packet.origin and \\\n                    self.destination_address == packet.origin:\n                self.destination_ip_responded = True\n                break",
    "docstring": "Sets the flag if destination IP responded."
  },
  {
    "code": "def pitch_shifter(self, chunk, shift):\n        freq = numpy.fft.rfft(chunk)\n        N = len(freq)\n        shifted_freq = numpy.zeros(N, freq.dtype)\n        S = numpy.round(shift if shift > 0 else N + shift, 0)\n        s = N - S\n        shifted_freq[:S] = freq[s:]\n        shifted_freq[S:] = freq[:s]\n        shifted_chunk = numpy.fft.irfft(shifted_freq)\n        return shifted_chunk.astype(chunk.dtype)",
    "docstring": "Pitch-Shift the given chunk by shift semi-tones."
  },
  {
    "code": "def generation(self):\n        if not self.parent:\n            return 0\n        elif self.parent.is_dict:\n            return 1 + self.parent.generation\n        else:\n            return self.parent.generation",
    "docstring": "Returns the number of ancestors that are dictionaries"
  },
  {
    "code": "def extract(self, reads_to_extract, database_fasta_file, output_file):\n        cmd = \"fxtract -XH -f /dev/stdin '%s' > %s\" % (\n            database_fasta_file, output_file)\n        extern.run(cmd, stdin='\\n'.join(reads_to_extract))",
    "docstring": "Extract the reads_to_extract from the database_fasta_file and put them in\n        output_file.\n\n        Parameters\n        ----------\n        reads_to_extract: Iterable of str\n            IDs of reads to be extracted\n        database_fasta_file: str\n            path the fasta file that containing the reads\n        output_file: str\n            path to the file where they are put\n\n        Returns\n        -------\n        Nothing"
  },
  {
    "code": "def _parse_abbreviation(uri_link):\n    abbr = re.sub(r'/[0-9]+\\..*htm.*', '', uri_link('a').attr('href'))\n    abbr = re.sub(r'/.*/schools/', '', abbr)\n    abbr = re.sub(r'/teams/', '', abbr)\n    return abbr.upper()",
    "docstring": "Returns a team's abbreviation.\n\n    A school or team's abbreviation is generally embedded in a URI link which\n    contains other relative link information. For example, the URI for the\n    New England Patriots for the 2017 season is \"/teams/nwe/2017.htm\". This\n    function strips all of the contents before and after \"nwe\" and converts it\n    to uppercase and returns \"NWE\".\n\n    Parameters\n    ----------\n    uri_link : string\n        A URI link which contains a team's abbreviation within other link\n        contents.\n\n    Returns\n    -------\n    string\n        The shortened uppercase abbreviation for a given team."
  },
  {
    "code": "def isAuxilied(self):\n        benefics = [const.VENUS, const.JUPITER]\n        return self.__sepApp(benefics, aspList=[0, 60, 120])",
    "docstring": "Returns if the object is separating and applying to \n        a benefic considering good aspects."
  },
  {
    "code": "def from_json(cls, key):\n        obj = cls()\n        try:\n            jkey = json_decode(key)\n        except Exception as e:\n            raise InvalidJWKValue(e)\n        obj.import_key(**jkey)\n        return obj",
    "docstring": "Creates a RFC 7517 JWK from the standard JSON format.\n\n        :param key: The RFC 7517 representation of a JWK."
  },
  {
    "code": "def dispatch(self, request, *args, **kwargs):\n        conf = IdPConfig()\n        try:\n            conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))\n            self.IDP = Server(config=conf)\n        except Exception as e:\n            return self.handle_error(request, exception=e)\n        return super(IdPHandlerViewMixin, self).dispatch(request, *args, **kwargs)",
    "docstring": "Construct IDP server with config from settings dict"
  },
  {
    "code": "def interpolate(self, traj, ti, k=3, der=0, ext=2):\n        r\n        u = traj[:, 0]\n        n = traj.shape[1]\n        x = [traj[:, i] for i in range(1, n)]\n        tck, t = interpolate.splprep(x, u=u, k=k, s=0)\n        out = interpolate.splev(ti, tck, der, ext)\n        interp_traj = np.hstack((ti[:, np.newaxis], np.array(out).T))\n        return interp_traj",
    "docstring": "r\"\"\"\n        Parametric B-spline interpolation in N-dimensions.\n\n        Parameters\n        ----------\n        traj : array_like (float)\n            Solution trajectory providing the data points for constructing the\n            B-spline representation.\n        ti : array_like (float)\n            Array of values for the independent variable at which to\n            interpolate the value of the B-spline.\n        k : int, optional(default=3)\n            Degree of the desired B-spline. Degree must satisfy\n            :math:`1 \\le k \\le 5`.\n        der : int, optional(default=0)\n            The order of derivative of the spline to compute (must be less\n            than or equal to `k`).\n        ext : int, optional(default=2) Controls the value of returned elements\n            for outside the original knot sequence provided by traj. For\n            extrapolation, set `ext=0`; `ext=1` returns zero; `ext=2` raises a\n            `ValueError`.\n\n        Returns\n        -------\n        interp_traj: ndarray (float)\n            The interpolated trajectory."
  },
  {
    "code": "def _merge_a_into_b_simple(self, a, b):\n        for k, v in a.items():\n            b[k] = v\n        return b",
    "docstring": "Merge config dictionary a into config dictionary b, clobbering the\n        options in b whenever they are also specified in a. Do not do any checking."
  },
  {
    "code": "def migrations_to_run(self):\n        assert self.database_current_migration is not None\n        db_current_migration = self.database_current_migration\n        return [\n            (migration_number, migration_func)\n            for migration_number, migration_func in self.sorted_migrations\n            if migration_number > db_current_migration]",
    "docstring": "Get a list of migrations to run still, if any.\n\n        Note that this will fail if there's no migration record for\n        this class!"
  },
  {
    "code": "def _read_header(self):\n        self._header = self.cdmrf.fetch_header()\n        self.load_from_stream(self._header)",
    "docstring": "Get the needed header information to initialize dataset."
  },
  {
    "code": "def validate(self, instance, value):\n        if getattr(value, '__valid__', False):\n            return value\n        if isinstance(value, png.Image):\n            pass\n        else:\n            value = super(ImagePNG, self).validate(instance, value)\n            try:\n                png.Reader(value).validate_signature()\n            except png.FormatError:\n                self.error(instance, value, extra='Open file is not PNG.')\n            value.seek(0)\n        output = BytesIO()\n        output.name = self.filename\n        output.__valid__ = True\n        if isinstance(value, png.Image):\n            value.save(output)\n        else:\n            fid = value\n            fid.seek(0)\n            output.write(fid.read())\n            fid.close()\n        output.seek(0)\n        return output",
    "docstring": "Checks if value is an open PNG file, valid filename, or png.Image\n\n        Returns an open bytestream of the image"
  },
  {
    "code": "def read_json_file(path):\n    with open(path, 'r', encoding='utf-8') as f:\n        data = json.load(f)\n    return data",
    "docstring": "Reads and return the data from the json file at the given path.\n\n    Parameters:\n        path (str): Path to read\n\n    Returns:\n        dict,list: The read json as dict/list."
  },
  {
    "code": "def delete(self):\n        self.query.filter_by(id=self.id).delete()\n        return self",
    "docstring": "Delete a file instance.\n\n        The file instance can be deleted if it has no references from other\n        objects. The caller is responsible to test if the file instance is\n        writable and that the disk file can actually be removed.\n\n        .. note::\n\n           Normally you should use the Celery task to delete a file instance,\n           as this method will not remove the file on disk."
  },
  {
    "code": "def float_format(self, value):\n        if isinstance(value, str):\n            '{0:{1}}'.format(1.23, value)\n            self._float_format = value\n        else:\n            raise TypeError('Floating point format code must be a string.')",
    "docstring": "Validate and set the upper case flag."
  },
  {
    "code": "def resource_references(self, resource) -> Mapping[str, List[Any]]:\n        references = dict()\n        for reference_label in resource.props.references:\n            references[reference_label] = []\n            for target_label in resource.props.references.get(reference_label):\n                target = self.get_reference(reference_label, target_label)\n                references[reference_label].append(target)\n        return references",
    "docstring": "Resolve and return reference resources pointed to by object\n\n         Fields in resource.props can flag that they are references by\n         using the references type. This method scans the model,\n         finds any fields that are references, and returns the\n         reference resources pointed to by those references.\n\n         Note that we shouldn't get to the point of dangling references.\n         Our custom Sphinx event should raise a references error\n         during the build process (though maybe it is just a warning?)"
  },
  {
    "code": "def _get_alphanumeric_index(query_string):\n        try:\n            return [int(query_string), 'int']\n        except ValueError:\n            if len(query_string) == 1:\n                if query_string.isupper():\n                    return [string.ascii_uppercase.index(query_string), 'char_hi']\n                elif query_string.islower():\n                    return [string.ascii_lowercase.index(query_string), 'char_lo']\n            else:\n                raise IOError('The input is a string longer than one character')",
    "docstring": "Given an input string of either int or char, returns what index in the alphabet and case it is\n\n        :param query_string: str, query string\n        :return: (int, str), list of the index and type"
  },
  {
    "code": "def insert_ordered(value, array):\n    index = 0\n    for n in range(0,len(array)):\n        if value >= array[n]: index = n+1\n    array.insert(index, value)\n    return index",
    "docstring": "This will insert the value into the array, keeping it sorted, and returning the\n    index where it was inserted"
  },
  {
    "code": "def socketBinaryStream(self, hostname, port, length):\n        deserializer = TCPDeserializer(self._context)\n        tcp_binary_stream = TCPBinaryStream(length)\n        tcp_binary_stream.listen(port, hostname)\n        self._on_stop_cb.append(tcp_binary_stream.stop)\n        return DStream(tcp_binary_stream, self, deserializer)",
    "docstring": "Create a TCP socket server for binary input.\n\n        .. warning::\n            This is not part of the PySpark API.\n\n        :param string hostname: Hostname of TCP server.\n        :param int port: Port of TCP server.\n        :param length:\n            Message length. Length in bytes or a format string for\n            ``struct.unpack()``.\n\n            For variable length messages where the message length is sent right\n            before the message itself, ``length`` is\n            a format string that can be passed to ``struct.unpack()``.\n            For example, use ``length='<I'`` for a little-endian\n            (standard on x86) 32-bit unsigned int.\n        :rtype: DStream"
  },
  {
    "code": "def get_live_scores(self, use_12_hour_format):\n        req = requests.get(RequestHandler.LIVE_URL)\n        if req.status_code == requests.codes.ok:\n            scores_data = []\n            scores = req.json()\n            if len(scores[\"games\"]) == 0:\n                click.secho(\"No live action currently\", fg=\"red\", bold=True)\n                return\n            for score in scores['games']:\n                d = {}\n                d['homeTeam'] = {'name': score['homeTeamName']}\n                d['awayTeam'] = {'name': score['awayTeamName']}\n                d['score'] = {'fullTime': {'homeTeam': score['goalsHomeTeam'],\n                                           'awayTeam': score['goalsAwayTeam']}}\n                d['league'] = score['league']\n                d['time'] = score['time']\n                scores_data.append(d)\n            self.writer.live_scores(scores_data)\n        else:\n            click.secho(\"There was problem getting live scores\", fg=\"red\", bold=True)",
    "docstring": "Gets the live scores"
  },
  {
    "code": "def nose_selector(test):\n    address = test_address(test)\n    if address:\n        file, module, rest = address\n        if module:\n            if rest:\n                try:\n                    return '%s:%s%s' % (module, rest, test.test.arg or '')\n                except AttributeError:\n                    return '%s:%s' % (module, rest)\n            else:\n                return module\n    return 'Unknown test'",
    "docstring": "Return the string you can pass to nose to run `test`, including argument\n    values if the test was made by a test generator.\n\n    Return \"Unknown test\" if it can't construct a decent path."
  },
  {
    "code": "def _save_image(image, filename, return_img=None):\n        if not image.size:\n            raise Exception('Empty image.  Have you run plot() first?')\n        if isinstance(filename, str):\n            if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename):\n                filename = os.path.join(vtki.FIGURE_PATH, filename)\n            if not return_img:\n                return imageio.imwrite(filename, image)\n            imageio.imwrite(filename, image)\n        return image",
    "docstring": "Internal helper for saving a NumPy image array"
  },
  {
    "code": "def brightness(sequence_number, brightness):\n        return MessageWriter().string(\"brightness\").uint64(sequence_number).uint8(int(brightness*255)).get()",
    "docstring": "Create a brightness message"
  },
  {
    "code": "def reset_state(self):\n        self.last_helo_response = (None, None)\n        self.last_ehlo_response = (None, None)\n        self.supports_esmtp = False\n        self.esmtp_extensions = {}\n        self.auth_mechanisms = []\n        self.ssl_context = False\n        self.reader = None\n        self.writer = None\n        self.transport = None",
    "docstring": "Resets some attributes to their default values.\n\n        This is especially useful when initializing a newly created\n        :class:`SMTP` instance and when closing an existing SMTP session.\n\n        It allows us to use the same SMTP instance and connect several times."
  },
  {
    "code": "def get_redirect_location(self):\n        if self.status in self.REDIRECT_STATUSES:\n            return self.headers.get('location')\n        return False",
    "docstring": "Should we redirect and where to?\n\n        :returns: Truthy redirect location string if we got a redirect status\n            code and valid location. ``None`` if redirect status and no\n            location. ``False`` if not a redirect status code."
  },
  {
    "code": "def process_next_position(data, cgi_input, header, reference, var_only):\n    if data[2] == \"all\" or data[1] == \"1\":\n        out = process_full_position(data=data, header=header, var_only=var_only)\n    else:\n        assert data[2] == \"1\"\n        out = process_split_position(\n            data=data, cgi_input=cgi_input, header=header, reference=reference, var_only=var_only)\n    if out:\n        vcf_lines = [vcf_line(input_data=l, reference=reference) for l in out\n                     if l['chrom'] != 'chrM']\n        return [vl for vl in vcf_lines if not\n               (var_only and vl.rstrip().endswith('./.'))]",
    "docstring": "Determine appropriate processing to get data, then convert it to VCF\n\n    There are two types of lines in the var file:\n    - \"full position\": single allele (hemizygous) or all-allele line\n        All alleles at this position are represented in this line.\n        This is handled with \"process_full_position\".\n    - \"split position\": each of two alleles is reported separately. There will\n        be at least two lines, one for each allele (but potentially more).\n        This is handled with \"process_split_position\".\n\n    Because the number of lines used for separately reported alleles is\n    unknown, process_split_position will always read ahead to the next\n    \"full position\" and return that as well.\n\n    So the returned line formats are consistent, process_next_position\n    returns an array, even if there's only one line."
  },
  {
    "code": "def get_imported_modules(self, module):\n    for name, member in inspect.getmembers(module):\n      if inspect.ismodule(member):\n        yield name, member",
    "docstring": "Returns the list of modules imported from `module`."
  },
  {
    "code": "def failed_update(self, exception):\n        f = None\n        with self._lock:\n            if self._future:\n                f = self._future\n                self._future = None\n        if f:\n            f.failure(exception)\n        self._last_refresh_ms = time.time() * 1000",
    "docstring": "Update cluster state given a failed MetadataRequest."
  },
  {
    "code": "def clone(self, callable=None, **overrides):\n        old = {k: v for k, v in self.get_param_values()\n               if k not in ['callable', 'name']}\n        params = dict(old, **overrides)\n        callable = self.callable if callable is None else callable\n        return self.__class__(callable, **params)",
    "docstring": "Clones the Callable optionally with new settings\n\n        Args:\n            callable: New callable function to wrap\n            **overrides: Parameter overrides to apply\n\n        Returns:\n            Cloned Callable object"
  },
  {
    "code": "def option_vip_by_environmentvip(self, environment_vip_id):\n        uri = 'api/v3/option-vip/environment-vip/%s/' % environment_vip_id\n        return super(ApiVipRequest, self).get(uri)",
    "docstring": "List Option Vip by Environment Vip\n\n        param environment_vip_id: Id of Environment Vip"
  },
  {
    "code": "def process_file(self, path, dryrun):\n        if dryrun:\n            return path\n        ret = []\n        with open(path, \"r\") as infile:\n            for line in infile:\n                if re.search(self.__exp, line):\n                    ret.append(line)\n        return ret if len(ret) > 0 else None",
    "docstring": "Print files path."
  },
  {
    "code": "def stop_recording(self):\n        self._stop_recording.set()\n        with self._source_lock:\n            self._source.stop()\n        self._recording = False",
    "docstring": "Stop recording from the audio source."
  },
  {
    "code": "def save(self, key, kw):\n        if key not in self:\n            obj = hdf5.LiteralAttrs()\n        else:\n            obj = self[key]\n        vars(obj).update(kw)\n        self[key] = obj\n        self.flush()",
    "docstring": "Update the object associated to `key` with the `kw` dictionary;\n        works for LiteralAttrs objects and automatically flushes."
  },
  {
    "code": "def GetRouterForUser(self, username):\n    for index, router in enumerate(self.routers):\n      router_id = str(index)\n      if self.auth_manager.CheckPermissions(username, router_id):\n        logging.debug(\"Matched router %s to user %s\", router.__class__.__name__,\n                      username)\n        return router\n    logging.debug(\"No router ACL rule match for user %s. Using default \"\n                  \"router %s\", username, self.default_router.__class__.__name__)\n    return self.default_router",
    "docstring": "Returns a router corresponding to a given username."
  },
  {
    "code": "def uninstalled(name):\n    ret = {'name': name,\n           'changes': {},\n           'result': False,\n           'comment': ''}\n    if not __salt__['wusa.is_installed'](name):\n        ret['result'] = True\n        ret['comment'] = '{0} already uninstalled'.format(name)\n        return ret\n    if __opts__['test'] is True:\n        ret['result'] = None\n        ret['comment'] = '{0} would be uninstalled'.format(name)\n        ret['result'] = None\n        return ret\n    __salt__['wusa.uninstall'](name)\n    if not __salt__['wusa.is_installed'](name):\n        ret['comment'] = '{0} was uninstalled'.format(name)\n        ret['changes'] = {'old': True, 'new': False}\n        ret['result'] = True\n    else:\n        ret['comment'] = '{0} failed to uninstall'.format(name)\n    return ret",
    "docstring": "Ensure an update is uninstalled from the minion\n\n    Args:\n\n        name(str):\n            Name of the Windows KB (\"KB123456\")\n\n    Example:\n\n    .. code-block:: yaml\n\n        KB123456:\n          wusa.uninstalled"
  },
  {
    "code": "def set_num_special_tokens(self, num_special_tokens):\n        \" Update input embeddings with new embedding matrice if needed \"\n        if self.config.n_special == num_special_tokens:\n            return\n        self.config.n_special = num_special_tokens\n        old_embed = self.tokens_embed\n        self.tokens_embed = nn.Embedding(self.config.total_tokens_embeddings, self.config.n_embd)\n        self.tokens_embed.to(old_embed.weight.device)\n        self.init_weights(self.tokens_embed)\n        self.tokens_embed.weight.data[:self.config.vocab_size, :] = old_embed.weight.data[:self.config.vocab_size, :]",
    "docstring": "Update input embeddings with new embedding matrice if needed"
  },
  {
    "code": "def _translate(unistr, table):\n    if type(unistr) is str:\n        try:\n            unistr = unistr.decode('utf-8')\n        except AttributeError:\n            pass\n    try:\n        if type(unistr) is not unicode:\n            return unistr\n    except NameError:\n        pass\n    chars = []\n    for c in unistr:\n        replacement = table.get(c)\n        chars.append(replacement if replacement else c)\n    return u''.join(chars)",
    "docstring": "Replace characters using a table."
  },
  {
    "code": "def merge(self, ontologies):\n        if self.xref_graph is None:\n            self.xref_graph = nx.MultiGraph()\n        logger.info(\"Merging source: {} xrefs: {}\".format(self, len(self.xref_graph.edges())))\n        for ont in ontologies:\n            logger.info(\"Merging {} into {}\".format(ont, self))\n            g = self.get_graph()\n            srcg = ont.get_graph()\n            for n in srcg.nodes():\n                g.add_node(n, **srcg.node[n])\n            for (o,s,m) in srcg.edges(data=True):\n                g.add_edge(o,s,**m)\n            if ont.xref_graph is not None:\n                for (o,s,m) in ont.xref_graph.edges(data=True):\n                    self.xref_graph.add_edge(o,s,**m)",
    "docstring": "Merges specified ontology into current ontology"
  },
  {
    "code": "def reference_source_point(self):\n        xref = isinstance(self.xref, Quantity) and self.xref.value or self.xref\n        yref = isinstance(self.yref, Quantity) and self.yref.value or self.yref\n        return xref + self.x_ref_offset, yref + self.y_ref_offset",
    "docstring": "The location of the source in the reference image, in terms of the\n        current image coordinates."
  },
  {
    "code": "def _add_ssh_key(ret):\n    priv = None\n    if __opts__.get('ssh_use_home_key') and os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):\n        priv = os.path.expanduser('~/.ssh/id_rsa')\n    else:\n        priv = __opts__.get(\n            'ssh_priv',\n            os.path.abspath(os.path.join(\n                __opts__['pki_dir'],\n                'ssh',\n                'salt-ssh.rsa'\n            ))\n        )\n    if priv and os.path.isfile(priv):\n        ret['priv'] = priv",
    "docstring": "Setups the salt-ssh minion to be accessed with salt-ssh default key"
  },
  {
    "code": "def _get_time_override(self):\n        if callable(self.time_override):\n            time_override = self.time_override()\n        else:\n            time_override = self.time_override\n        if not isinstance(time_override, datetime_time):\n            raise ValueError(\n                'Invalid type. Must be a datetime.time instance.'\n            )\n        return time_override",
    "docstring": "Retrieves the datetime.time or None from the `time_override` attribute."
  },
  {
    "code": "def _get_proxy_info(self, _=None):\n        (target_host, target_port, target_path) = self._endpoint_to_target(self._endpoint)\n        sock = None\n        if target_path:\n            sock = self._ssh_tunnel.forward_unix(path=target_path)\n        else:\n            sock = self._ssh_tunnel.forward_tcp(target_host, port=target_port)\n        return SSHTunnelProxyInfo(sock=sock)",
    "docstring": "Generate a ProxyInfo class from a connected SSH transport\n\n        Args:\n            _ (None): Ignored.  This is just here as the ProxyInfo spec requires it.\n\n\n        Returns:\n            SSHTunnelProxyInfo: A ProxyInfo with an active socket tunneled through SSH"
  },
  {
    "code": "def run(self, realm, users):\n\t\texisting_users = []\n\t\tfor user in users:\n\t\t\tlogging.debug('Probing user %s' % user)\n\t\t\treq = KerberosUserEnum.construct_tgt_req(realm, user)\n\t\t\trep = self.ksoc.sendrecv(req.dump(), throw = False)\n\t\t\tif rep.name != 'KRB_ERROR':\t\n\t\t\t\texisting_users.append(user)\n\t\t\telif rep.native['error-code'] != KerberosErrorCode.KDC_ERR_PREAUTH_REQUIRED.value:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\texisting_users.append(user)\n\t\treturn existing_users",
    "docstring": "Requests a TGT in the name of the users specified in users. \n\t\tReturns a list of usernames that are in the domain.\n\n\t\trealm: kerberos realm (domain name of the corp)\n\t\tusers: list : list of usernames to test"
  },
  {
    "code": "def is_executable(exe_name):\n    if not isinstance(exe_name, str):\n        raise TypeError('Executable name must be a string.')\n    def is_exe(fpath):\n        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n    fpath, fname = os.path.split(exe_name)\n    if not fpath:\n        res = any([is_exe(os.path.join(path, exe_name)) for path in\n                   os.environ[\"PATH\"].split(os.pathsep)])\n    else:\n        res = is_exe(exe_name)\n    if not res:\n        raise IOError('{} does not appear to be a valid executable on this '\n                      'system.'.format(exe_name))",
    "docstring": "Check if Input is Executable\n\n    This methid checks if the input executable exists.\n\n    Parameters\n    ----------\n    exe_name : str\n        Executable name\n\n    Returns\n    -------\n    Bool result of test\n\n    Raises\n    ------\n    TypeError\n        For invalid input type"
  },
  {
    "code": "def b64_hmac_md5(key, data):\n    bdigest = base64.b64encode(hmac.new(key, data, _md5).digest()).strip().decode(\"utf-8\")\n    return re.sub('=+$', '', bdigest)",
    "docstring": "return base64-encoded HMAC-MD5 for key and data, with trailing '='\n    stripped."
  },
  {
    "code": "def check_venv(self):\n        if self.zappa:\n            venv = self.zappa.get_current_venv()\n        else:\n            venv = Zappa.get_current_venv()\n        if not venv:\n            raise ClickException(\n                click.style(\"Zappa\", bold=True) + \" requires an \" + click.style(\"active virtual environment\", bold=True, fg=\"red\") + \"!\\n\" +\n                \"Learn more about virtual environments here: \" + click.style(\"http://docs.python-guide.org/en/latest/dev/virtualenvs/\", bold=False, fg=\"cyan\"))",
    "docstring": "Ensure we're inside a virtualenv."
  },
  {
    "code": "def signal_terminate(on_terminate):\n    for i in [signal.SIGINT, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2, signal.SIGTERM]:\n        signal.signal(i, on_terminate)",
    "docstring": "a common case program termination signal"
  },
  {
    "code": "def endpoint_check(\n    first, node_first, s, second, node_second, t, intersections\n):\n    r\n    if _helpers.vector_close(node_first, node_second):\n        orig_s = (1 - s) * first.start + s * first.end\n        orig_t = (1 - t) * second.start + t * second.end\n        add_intersection(orig_s, orig_t, intersections)",
    "docstring": "r\"\"\"Check if curve endpoints are identical.\n\n    .. note::\n\n       This is a helper for :func:`tangent_bbox_intersection`. These\n       functions are used (directly or indirectly) by\n       :func:`_all_intersections` exclusively, and that function has a\n       Fortran equivalent.\n\n    Args:\n        first (SubdividedCurve): First curve being intersected (assumed in\n            :math:\\mathbf{R}^2`).\n        node_first (numpy.ndarray): 1D ``2``-array, one of the endpoints\n            of ``first``.\n        s (float): The parameter corresponding to ``node_first``, so\n             expected to be one of ``0.0`` or ``1.0``.\n        second (SubdividedCurve): Second curve being intersected (assumed in\n            :math:\\mathbf{R}^2`).\n        node_second (numpy.ndarray): 1D ``2``-array, one of the endpoints\n            of ``second``.\n        t (float): The parameter corresponding to ``node_second``, so\n             expected to be one of ``0.0`` or ``1.0``.\n        intersections (list): A list of already encountered\n            intersections. If these curves intersect at their tangency,\n            then those intersections will be added to this list."
  },
  {
    "code": "def calculate_moment(psd_f, psd_amp, fmin, fmax, f0, funct,\n                     norm=None, vary_fmax=False, vary_density=None):\n    psd_x = psd_f / f0\n    deltax = psd_x[1] - psd_x[0]\n    mask = numpy.logical_and(psd_f > fmin, psd_f < fmax)\n    psdf_red = psd_f[mask]\n    comps_red = psd_x[mask] ** (-7./3.) * funct(psd_x[mask], f0) * deltax / \\\n                psd_amp[mask]\n    moment = {}\n    moment[fmax] = comps_red.sum()\n    if norm:\n        moment[fmax] = moment[fmax] / norm[fmax]\n    if vary_fmax:\n        for t_fmax in numpy.arange(fmin + vary_density, fmax, vary_density):\n            moment[t_fmax] = comps_red[psdf_red < t_fmax].sum()\n            if norm:\n                moment[t_fmax] = moment[t_fmax] / norm[t_fmax]\n    return moment",
    "docstring": "Function for calculating one of the integrals used to construct a template\n    bank placement metric. The integral calculated will be\n\n    \\int funct(x) * (psd_x)**(-7./3.) * delta_x / PSD(x)\n\n    where x = f / f0. The lower frequency cutoff is given by fmin, see\n    the parameters below for details on how the upper frequency cutoff is\n    chosen\n\n    Parameters\n    -----------\n    psd_f : numpy.array\n       numpy array holding the set of evenly spaced frequencies used in the PSD\n    psd_amp : numpy.array\n       numpy array holding the PSD values corresponding to the psd_f\n       frequencies\n    fmin : float\n        The lower frequency cutoff used in the calculation of the integrals\n        used to obtain the metric.\n    fmax : float\n        The upper frequency cutoff used in the calculation of the integrals\n        used to obtain the metric. This can be varied (see the vary_fmax\n        option below).\n    f0 : float\n        This is an arbitrary scaling factor introduced to avoid the potential\n        for numerical overflow when calculating this. Generally the default\n        value (70) is safe here. **IMPORTANT, if you want to calculate the\n        ethinca metric components later this MUST be set equal to f_low.**\n    funct : Lambda function\n        The function to use when computing the integral as described above.\n    norm : Dictionary of floats\n        If given then moment[f_cutoff] will be divided by norm[f_cutoff]\n    vary_fmax : boolean, optional (default False)\n        If set to False the metric and rotations are calculated once, for the\n        full range of frequency [f_low,f_upper).\n        If set to True the metric and rotations are calculated multiple times,\n        for frequency ranges [f_low,f_low + i*vary_density), where i starts at\n        1 and runs up until f_low + (i+1)*vary_density > f_upper.\n        Thus values greater than f_upper are *not* computed.\n        The calculation for the full range [f_low,f_upper) is also done.\n    vary_density : float, optional\n        If vary_fmax is True, this will be used in computing the frequency\n        ranges as described for vary_fmax.\n\n    Returns\n    --------\n    moment : Dictionary of floats\n        moment[f_cutoff] will store the value of the moment at the frequency\n        cutoff given by f_cutoff."
  },
  {
    "code": "def pdf(self, mu):\n        if self.transform is not None:\n            mu = self.transform(mu)    \n        if mu < self.lower and self.lower is not None:\n            return 0.0\n        elif mu > self.upper and self.upper is not None:\n            return 0.0       \n        else:\n            return (1/float(self.sigma0))*np.exp(-(0.5*(mu-self.mu0)**2)/float(self.sigma0**2))",
    "docstring": "PDF for Truncated Normal prior\n\n        Parameters\n        ----------\n        mu : float\n            Latent variable for which the prior is being formed over\n\n        Returns\n        ----------\n        - p(mu)"
  },
  {
    "code": "def on_directory_button_tool_clicked(self):\n        input_path = self.layer.currentLayer().source()\n        input_directory, self.output_filename = os.path.split(input_path)\n        file_extension = os.path.splitext(self.output_filename)[1]\n        self.output_filename = os.path.splitext(self.output_filename)[0]\n        output_path, __ = QtWidgets.QFileDialog.getSaveFileName(\n            self,\n            self.tr('Output file'),\n            '%s_multi_buffer%s' % (\n                os.path.join(input_directory, self.output_filename),\n                file_extension),\n            'GeoJSON (*.geojson);;Shapefile (*.shp)')\n        self.output_form.setText(output_path)",
    "docstring": "Autoconnect slot activated when directory button is clicked."
  },
  {
    "code": "def cidr_netmask(cidr):\n    ips = netaddr.IPNetwork(cidr)\n    return six.text_type(ips.netmask)",
    "docstring": "Get the netmask address associated with a CIDR address.\n\n    CLI example::\n\n        salt myminion netaddress.cidr_netmask 192.168.0.0/20"
  },
  {
    "code": "def parse_second_row(row, url):\n        tags = row.findall('./td')\n        category, subcategory, quality, language = Parser.parse_torrent_properties(tags[0])\n        user_info = tags[1].find('./a')\n        user = user_info.text_content()\n        user_url = url.combine(user_info.get('href'))\n        torrent_link = Parser.parse_torrent_link(tags[2])\n        size = tags[3].text\n        comments = tags[4].text\n        times_completed = tags[5].text\n        seeders = tags[6].text\n        leechers = tags[7].text\n        return [category, subcategory, quality, language, user, user_url, torrent_link,\n                size, comments, times_completed, seeders, leechers]",
    "docstring": "Static method that parses a given table row element by using helper methods `Parser.parse_category_subcategory_and_or_quality`,\n        `Parser.parse_torrent_link` and scrapping torrent's category, subcategory, quality, language, user, user url, torrent link, size,\n        comments, times completed, seeders and leechers. Used specifically with a torrent's second table row.\n\n        :param lxml.HtmlElement row: row to parse\n        :param urls.Url url_instance: Url used to combine base url's with scrapped links from tr\n        :return: scrapped category, subcategory, quality, language, user, user url, torrent link, size, comments, times completed,\n         seeders and leechers\n        :rtype: list"
  },
  {
    "code": "def get_prices(self) -> List[PriceModel]:\n        from pricedb.dal import Price\n        pricedb = PriceDbApplication()\n        repo = pricedb.get_price_repository()\n        query = (repo.query(Price)\n            .filter(Price.namespace == self.security.namespace)\n            .filter(Price.symbol == self.security.mnemonic)\n            .orderby_desc(Price.date)\n        )\n        return query.all()",
    "docstring": "Returns all available prices for security"
  },
  {
    "code": "def GetClientConfig(filename):\n  config_lib.SetPlatformArchContext()\n  config_lib.ParseConfigCommandLine()\n  context = list(grr_config.CONFIG.context)\n  context.append(\"Client Context\")\n  deployer = build.ClientRepacker()\n  config_data = deployer.GetClientConfig(\n      context, validate=True, deploy_timestamp=False)\n  builder = build.ClientBuilder()\n  with open(filename, \"w\") as fd:\n    fd.write(config_data)\n    builder.WriteBuildYaml(fd, build_timestamp=False)",
    "docstring": "Write client config to filename."
  },
  {
    "code": "def _round_half_hour(record):\n    k = record.datetime + timedelta(minutes=-(record.datetime.minute % 30))\n    return datetime(k.year, k.month, k.day, k.hour, k.minute, 0)",
    "docstring": "Round a time DOWN to half nearest half-hour."
  },
  {
    "code": "def corpora(self, full=False):\n        url = self.base_url + self.CORPORA_PAGE\n        class_ = Corpus\n        results = self._retrieve_resources(url, class_, full)\n        return results",
    "docstring": "Return list of corpora owned by user.\n\n        If `full=True`, it'll download all pages returned by the HTTP server"
  },
  {
    "code": "def make(parser):\n    s = parser.add_subparsers(\n        title='commands',\n        metavar='COMMAND',\n        help='description',\n        )\n    def create_manila_db_f(args):\n        create_manila_db(args)\n    create_manila_db_parser = create_manila_db_subparser(s)\n    create_manila_db_parser.set_defaults(func=create_manila_db_f)\n    def create_service_credentials_f(args):\n        create_service_credentials(args)\n    create_service_credentials_parser = create_service_credentials_subparser(s)\n    create_service_credentials_parser.set_defaults(func=create_service_credentials_f)\n    def install_f(args):\n        install(args)\n    install_parser = install_subparser(s)\n    install_parser.set_defaults(func=install_f)",
    "docstring": "provison Manila with HA"
  },
  {
    "code": "def skip(type_name, filename):\n    report = ['Skipping {} file: {}'.format(type_name, filename)]\n    report_stats = ReportStats(filename, report=report)\n    return report_stats",
    "docstring": "Provide reporting statistics for a skipped file."
  },
  {
    "code": "def component_offsetvectors(offsetvectors, n):\n\tdelta_sets = {}\n\tfor vect in offsetvectors:\n\t\tfor instruments in iterutils.choices(sorted(vect), n):\n\t\t\tdelta_sets.setdefault(instruments, set()).add(tuple(vect[instrument] - vect[instruments[0]] for instrument in instruments))\n\treturn [offsetvector(zip(instruments, deltas)) for instruments, delta_set in delta_sets.items() for deltas in delta_set]",
    "docstring": "Given an iterable of offset vectors, return the shortest list of\n\tthe unique n-instrument offset vectors from which all the vectors\n\tin the input iterable can be constructed.  This can be used to\n\tdetermine the minimal set of n-instrument coincs required to\n\tconstruct all of the coincs for all of the requested instrument and\n\toffset combinations in a set of offset vectors.\n\n\tIt is assumed that the coincs for the vector {\"H1\": 0, \"H2\": 10,\n\t\"L1\": 20} can be constructed from the coincs for the vectors {\"H1\":\n\t0, \"H2\": 10} and {\"H2\": 0, \"L1\": 10}, that is only the relative\n\toffsets are significant in determining if two events are\n\tcoincident, not the absolute offsets.  This assumption is not true\n\tfor the standard inspiral pipeline, where the absolute offsets are\n\tsignificant due to the periodic wrapping of triggers around rings."
  },
  {
    "code": "def analyse_text(text):\n        result = 0.0\n        lines = text.split('\\n')\n        if len(lines) > 0:\n            if JclLexer._JOB_HEADER_PATTERN.match(lines[0]):\n                result = 1.0\n        assert 0.0 <= result <= 1.0\n        return result",
    "docstring": "Recognize JCL job by header."
  },
  {
    "code": "def uri_query(self):\n        value = []\n        for option in self.options:\n            if option.number == defines.OptionRegistry.URI_QUERY.number:\n                value.append(str(option.value))\n        return \"&\".join(value)",
    "docstring": "Get the Uri-Query of a request.\n\n        :return: the Uri-Query\n        :rtype : String\n        :return: the Uri-Query string"
  },
  {
    "code": "def escape_filename_sh(name):\n    for ch in name:\n        if ord(ch) < 32:\n            return escape_filename_sh_ansic(name)\n    name.replace('\\\\','\\\\\\\\')\n    name.replace('\"','\\\\\"')\n    name.replace('`','\\\\`')\n    name.replace('$','\\\\$')\n    return '\"'+name+'\"'",
    "docstring": "Return a hopefully safe shell-escaped version of a filename."
  },
  {
    "code": "def parse_journal_file(journal_file):\n    counter = count()\n    for block in read_next_block(journal_file):\n        block = remove_nullchars(block)\n        while len(block) > MIN_RECORD_SIZE:\n            header = RECORD_HEADER.unpack_from(block)\n            size = header[0]\n            try:\n                yield parse_record(header, block[:size])\n                next(counter)\n            except RuntimeError:\n                yield CorruptedUsnRecord(next(counter))\n            finally:\n                block = remove_nullchars(block[size:])\n        journal_file.seek(- len(block), 1)",
    "docstring": "Iterates over the journal's file taking care of paddings."
  },
  {
    "code": "def https_proxy(self):\n    if os.getenv('HTTPS_PROXY'):\n      return os.getenv('HTTPS_PROXY')\n    if os.getenv('https_proxy'):\n      return os.getenv('https_proxy')\n    return self.get_options().https_proxy",
    "docstring": "Set ivy to use an https proxy.\n\n    Expects a string of the form http://<host>:<port>"
  },
  {
    "code": "def get(self, path_segment=\"\", owner=None, app=None, sharing=None, **query):\n        if path_segment.startswith('/'):\n            path = path_segment\n        else:\n            path = self.service._abspath(self.path + path_segment, owner=owner,\n                                         app=app, sharing=sharing)\n        return self.service.get(path,\n                                owner=owner, app=app, sharing=sharing,\n                                **query)",
    "docstring": "Performs a GET operation on the path segment relative to this endpoint.\n\n        This method is named to match the HTTP method. This method makes at least\n        one roundtrip to the server, one additional round trip for\n        each 303 status returned, plus at most two additional round\n        trips if\n        the ``autologin`` field of :func:`connect` is set to ``True``.\n\n        If *owner*, *app*, and *sharing* are omitted, this method takes a\n        default namespace from the :class:`Service` object for this :class:`Endpoint`.\n        All other keyword arguments are included in the URL as query parameters.\n\n        :raises AuthenticationError: Raised when the ``Service`` is not logged in.\n        :raises HTTPError: Raised when an error in the request occurs.\n        :param path_segment: A path segment relative to this endpoint.\n        :type path_segment: ``string``\n        :param owner: The owner context of the namespace (optional).\n        :type owner: ``string``\n        :param app: The app context of the namespace (optional).\n        :type app: ``string``\n        :param sharing: The sharing mode for the namespace (optional).\n        :type sharing: \"global\", \"system\", \"app\", or \"user\"\n        :param query: All other keyword arguments, which are used as query\n            parameters.\n        :type query: ``string``\n        :return: The response from the server.\n        :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``,\n                and ``status``\n\n        **Example**::\n\n            import splunklib.client\n            s = client.service(...)\n            apps = s.apps\n            apps.get() == \\\\\n                {'body': ...a response reader object...,\n                 'headers': [('content-length', '26208'),\n                             ('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'),\n                             ('server', 'Splunkd'),\n                             ('connection', 'close'),\n                             ('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'),\n                             ('date', 'Fri, 11 May 2012 16:30:35 GMT'),\n                             ('content-type', 'text/xml; charset=utf-8')],\n                 'reason': 'OK',\n                 'status': 200}\n            apps.get('nonexistant/path') # raises HTTPError\n            s.logout()\n            apps.get() # raises AuthenticationError"
  },
  {
    "code": "def make_hop_info_from_url(url, verify_reachability=None):\n    parsed = urlparse(url)\n    username = None if parsed.username is None else unquote(parsed.username)\n    password = None if parsed.password is None else unquote(parsed.password)\n    try:\n        enable_password = parse_qs(parsed.query)[\"enable_password\"][0]\n    except KeyError:\n        enable_password = None\n    hop_info = HopInfo(\n        parsed.scheme,\n        parsed.hostname,\n        username,\n        password,\n        parsed.port,\n        enable_password,\n        verify_reachability=verify_reachability\n    )\n    if hop_info.is_valid():\n        return hop_info\n    raise InvalidHopInfoError",
    "docstring": "Build HopInfo object from url.\n\n    It allows only telnet and ssh as a valid protocols.\n\n    Args:\n        url (str): The url string describing the node. i.e.\n            telnet://username@1.1.1.1. The protocol, username and address\n            portion of url is mandatory. Port and password is optional.\n            If port is missing the standard protocol -> port mapping is done.\n            The password is optional i.e. for TS access directly to console\n            ports.\n            The path part is treated as additional password required for some\n            systems, i.e. enable password for IOS devices.:\n            telnet://<username>:<password>@<host>:<port>/<enable_password>\n            <enable_password> is optional\n\n        verify_reachability: This is optional callable returning boolean\n            if node is reachable. It can be used to verify reachability\n            of the node before making a connection. It can speedup the\n            connection process when node not reachable especially with\n            telnet having long timeout.\n\n    Returns:\n        HopInfo object or None if url is invalid or protocol not supported"
  },
  {
    "code": "def report_server_init_errors(address=None, port=None, **kwargs):\n    try:\n        yield\n    except EnvironmentError as e:\n        if e.errno == errno.EADDRINUSE:\n            log.critical(\"Cannot start Bokeh server, port %s is already in use\", port)\n        elif e.errno == errno.EADDRNOTAVAIL:\n            log.critical(\"Cannot start Bokeh server, address '%s' not available\", address)\n        else:\n            codename = errno.errorcode[e.errno]\n            log.critical(\"Cannot start Bokeh server [%s]: %r\", codename, e)\n        sys.exit(1)",
    "docstring": "A context manager to help print more informative error messages when a\n    ``Server`` cannot be started due to a network problem.\n\n    Args:\n        address (str) : network address that the server will be listening on\n\n        port (int) : network address that the server will be listening on\n\n    Example:\n\n        .. code-block:: python\n\n            with report_server_init_errors(**server_kwargs):\n                server = Server(applications, **server_kwargs)\n\n        If there are any errors (e.g. port or address in already in use) then a\n        critical error will be logged and the process will terminate with a\n        call to ``sys.exit(1)``"
  },
  {
    "code": "def computeDistortion(self, eEye, fU, fV):\n        fn = self.function_table.computeDistortion\n        pDistortionCoordinates = DistortionCoordinates_t()\n        result = fn(eEye, fU, fV, byref(pDistortionCoordinates))\n        return result, pDistortionCoordinates",
    "docstring": "Gets the result of the distortion function for the specified eye and input UVs. UVs go from 0,0 in \n        the upper left of that eye's viewport and 1,1 in the lower right of that eye's viewport.\n        Returns true for success. Otherwise, returns false, and distortion coordinates are not suitable."
  },
  {
    "code": "def _call_method_from_namespace(obj, method_name, namespace):\n    method = getattr(obj, method_name)\n    method_parser = method.parser\n    arg_names = _get_args_name_from_parser(method_parser)\n    if method_name == \"__init__\":\n        return _call(obj, arg_names, namespace)\n    return _call(method, arg_names, namespace)",
    "docstring": "Call the method, retrieved from obj, with the correct arguments via\n    the namespace\n\n    Args:\n        obj: any kind of object\n        method_name: method to be called\n        namespace: an argparse.Namespace object containing parsed command\n        line arguments"
  },
  {
    "code": "def _set_config(c):\n    glfw.glfwWindowHint(glfw.GLFW_RED_BITS, c['red_size'])\n    glfw.glfwWindowHint(glfw.GLFW_GREEN_BITS, c['green_size'])\n    glfw.glfwWindowHint(glfw.GLFW_BLUE_BITS, c['blue_size'])\n    glfw.glfwWindowHint(glfw.GLFW_ALPHA_BITS, c['alpha_size'])\n    glfw.glfwWindowHint(glfw.GLFW_ACCUM_RED_BITS, 0)\n    glfw.glfwWindowHint(glfw.GLFW_ACCUM_GREEN_BITS, 0)\n    glfw.glfwWindowHint(glfw.GLFW_ACCUM_BLUE_BITS, 0)\n    glfw.glfwWindowHint(glfw.GLFW_ACCUM_ALPHA_BITS, 0)\n    glfw.glfwWindowHint(glfw.GLFW_DEPTH_BITS, c['depth_size'])\n    glfw.glfwWindowHint(glfw.GLFW_STENCIL_BITS, c['stencil_size'])\n    glfw.glfwWindowHint(glfw.GLFW_SAMPLES, c['samples'])\n    glfw.glfwWindowHint(glfw.GLFW_STEREO, c['stereo'])\n    if not c['double_buffer']:\n        raise RuntimeError('GLFW must double buffer, consider using a '\n                           'different backend, or using double buffering')",
    "docstring": "Set gl configuration for GLFW"
  },
  {
    "code": "def lookup_zone_exception(self, callsign, timestamp=datetime.utcnow().replace(tzinfo=UTC)):\n        callsign = callsign.strip().upper()\n        if self._lookuptype == \"clublogxml\":\n            return self._check_zone_exception_for_date(callsign, timestamp, self._zone_exceptions, self._zone_exceptions_index)\n        elif self._lookuptype == \"redis\":\n            data_dict, index = self._get_dicts_from_redis(\"_zone_ex_\", \"_zone_ex_index_\", self._redis_prefix, callsign)\n            return self._check_zone_exception_for_date(callsign, timestamp, data_dict, index)\n        raise KeyError",
    "docstring": "Returns a CQ Zone if an exception exists for the given callsign\n\n        Args:\n        callsign (string): Amateur radio callsign\n        timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)\n\n        Returns:\n            int: Value of the the CQ Zone exception which exists for this callsign (at the given time)\n\n        Raises:\n            KeyError: No matching callsign found\n            APIKeyMissingError: API Key for Clublog missing or incorrect\n\n        Example:\n           The following code checks the Clublog XML database if a CQ Zone exception exists for the callsign DP0GVN.\n\n           >>> from pyhamtools import LookupLib\n           >>> my_lookuplib = LookupLib(lookuptype=\"clublogxml\", apikey=\"myapikey\")\n           >>> print my_lookuplib.lookup_zone_exception(\"DP0GVN\")\n           38\n\n           The prefix \"DP\" It is assigned to Germany, but the station is located in Antarctica, and therefore\n           in CQ Zone 38\n\n        Note:\n            This method is available for\n\n            - clublogxml\n            - redis"
  },
  {
    "code": "def readView(self, newLength=None):\n        if newLength is None:\n            newLength = self.len\n        result = self.peekView(newLength)\n        self.skip(newLength)\n        return result",
    "docstring": "Return a view of the next newLength bytes, and skip it."
  },
  {
    "code": "def error2str(e):\n    out = StringIO()\n    traceback.print_exception(None, e, e.__traceback__, file=out)\n    out.seek(0)\n    return out.read()",
    "docstring": "returns the formatted stacktrace of the exception `e`.\n\n    :param BaseException e: an exception to format into str\n    :rtype: str"
  },
  {
    "code": "def db_restore(self, block_number=None):\n        restored = False\n        if block_number is not None:\n            try:\n                self.backup_restore(block_number, self.impl, self.working_dir)\n                restored = True\n            except AssertionError:\n                log.error(\"Failed to restore state from {}\".format(block_number))\n                return False\n        else:\n            backup_blocks = self.get_backup_blocks(self.impl, self.working_dir)\n            for block_number in reversed(sorted(backup_blocks)):\n                try:\n                    self.backup_restore(block_number, self.impl, self.working_dir)\n                    restored = True\n                    log.debug(\"Restored state from {}\".format(block_number))\n                    break\n                except AssertionError:\n                    log.debug(\"Failed to restore state from {}\".format(block_number))\n                    continue\n            if not restored:\n                log.error(\"Failed to restore state from {}\".format(','.join(backup_blocks)))\n                return False\n        self.db_set_indexing(False, self.impl, self.working_dir)\n        return self.db_setup()",
    "docstring": "Restore the database and clear the indexing lockfile.\n        Restore to a given block if given; otherwise use the most recent valid backup.\n\n        Return True on success\n        Return False if there is no state to restore\n        Raise exception on error"
  },
  {
    "code": "def get_assessment_query_session_for_bank(self, bank_id, proxy):\n        if not self.supports_assessment_query():\n            raise errors.Unimplemented()\n        return sessions.AssessmentQuerySession(bank_id, proxy, self._runtime)",
    "docstring": "Gets the ``OsidSession`` associated with the assessment query service for the given bank.\n\n        arg:    bank_id (osid.id.Id): the ``Id`` of the bank\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.assessment.AssessmentQuerySession) - ``an\n                _assessment_query_session``\n        raise:  NotFound - ``bank_id`` not found\n        raise:  NullArgument - ``bank_id`` or ``proxy`` is ``null``\n        raise:  OperationFailed - ``unable to complete request``\n        raise:  Unimplemented - ``supports_assessment_query()`` or\n                ``supports_visible_federation()`` is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_assessment_query()`` and\n        ``supports_visible_federation()`` are ``true``.*"
  },
  {
    "code": "def raise_for_response(self, responses):\n        exception_messages = [self.client.format_exception_message(response) for response in responses]\n        if len(exception_messages) == 1:\n            message = exception_messages[0]\n        else:\n            message = \"[%s]\" % \", \".join(exception_messages)\n        raise PostmarkerException(message)",
    "docstring": "Constructs appropriate exception from list of responses and raises it."
  },
  {
    "code": "def _call_custom_creator(self, config):\n        creator = self._custom_creators[config['driver']](config)\n        if isinstance(creator, Store):\n            creator = self.repository(creator)\n        if not isinstance(creator, Repository):\n            raise RuntimeError('Custom creator should return a Repository instance.')\n        return creator",
    "docstring": "Call a custom driver creator.\n\n        :param config: The driver configuration\n        :type config: dict\n\n        :rtype: Repository"
  },
  {
    "code": "def bucket(self, bucket_name, user_project=None):\n        return Bucket(client=self, name=bucket_name, user_project=user_project)",
    "docstring": "Factory constructor for bucket object.\n\n        .. note::\n          This will not make an HTTP request; it simply instantiates\n          a bucket object owned by this client.\n\n        :type bucket_name: str\n        :param bucket_name: The name of the bucket to be instantiated.\n\n        :type user_project: str\n        :param user_project: (Optional) the project ID to be billed for API\n                             requests made via the bucket.\n\n        :rtype: :class:`google.cloud.storage.bucket.Bucket`\n        :returns: The bucket object created."
  },
  {
    "code": "def retrieve_request(self, url):\n        try:\n            data = urlopen(url)\n        except:\n            print(\"Error Retrieving Data from Steam\")\n            sys.exit(2)\n        return data.read().decode('utf-8')",
    "docstring": "Open the given url and decode and return the response\n\n        url: The url to open."
  },
  {
    "code": "def delete_file(self, instance, sender, **kwargs):\n        file_ = getattr(instance, self.attname)\n        query = Q(**{self.name: file_.name}) & ~Q(pk=instance.pk)\n        qs = sender._default_manager.filter(query)\n        if (file_ and file_.name != self.default and not qs):\n            default.backend.delete(file_)\n        elif file_:\n            file_.close()",
    "docstring": "Adds deletion of thumbnails and key value store references to the\n        parent class implementation. Only called in Django < 1.2.5"
  },
  {
    "code": "def load(self, model, value):\n        try:\n            return self._cattrs_converter.structure(value, model)\n        except (ValueError, TypeError) as e:\n            raise SerializationException(str(e))",
    "docstring": "Converts unstructured data into structured data, recursively."
  },
  {
    "code": "def build_key_from_values(self, schema, hash_key, range_key=None):\n        dynamodb_key = {}\n        dynamodb_value = self.dynamize_value(hash_key)\n        if dynamodb_value.keys()[0] != schema.hash_key_type:\n            msg = 'Hashkey must be of type: %s' % schema.hash_key_type\n            raise TypeError(msg)\n        dynamodb_key['HashKeyElement'] = dynamodb_value\n        if range_key is not None:\n            dynamodb_value = self.dynamize_value(range_key)\n            if dynamodb_value.keys()[0] != schema.range_key_type:\n                msg = 'RangeKey must be of type: %s' % schema.range_key_type\n                raise TypeError(msg)\n            dynamodb_key['RangeKeyElement'] = dynamodb_value\n        return dynamodb_key",
    "docstring": "Build a Key structure to be used for accessing items\n        in Amazon DynamoDB.  This method takes the supplied hash_key\n        and optional range_key and validates them against the\n        schema.  If there is a mismatch, a TypeError is raised.\n        Otherwise, a Python dict version of a Amazon DynamoDB Key\n        data structure is returned.\n\n        :type hash_key: int, float, str, or unicode\n        :param hash_key: The hash key of the item you are looking for.\n            The type of the hash key should match the type defined in\n            the schema.\n\n        :type range_key: int, float, str or unicode\n        :param range_key: The range key of the item your are looking for.\n            This should be supplied only if the schema requires a\n            range key.  The type of the range key should match the\n            type defined in the schema."
  },
  {
    "code": "def copy(self):\n        geometry = {n: g.copy() for n, g in self.geometry.items()}\n        copied = Scene(geometry=geometry,\n                       graph=self.graph.copy())\n        return copied",
    "docstring": "Return a deep copy of the current scene\n\n        Returns\n        ----------\n        copied : trimesh.Scene\n          Copy of the current scene"
  },
  {
    "code": "def concept(self, cid, **kwargs):\n        if cid not in self.__concept_map:\n            if 'default' in kwargs:\n                return kwargs['default']\n            else:\n                raise KeyError(\"Invalid cid\")\n        else:\n            return self.__concept_map[cid]",
    "docstring": "Get concept by concept ID"
  },
  {
    "code": "def create_user(username, key, session):\n    try:\n        user = um.User(username=username)\n        session.add(user)\n        session.commit()\n    except Exception as e:\n        session.rollback()\n        session.flush()\n        raise e\n    try:\n        ukey = um.UserKey(key=key, keytype='public', user_id=user.id)\n        session.add(ukey)\n        session.commit()\n    except Exception as e:\n        session.rollback()\n        session.flush()\n        session.delete(user)\n        session.commit()\n        raise e\n    return user",
    "docstring": "Create a User and UserKey record in the session provided.\n    Will rollback both records if any issues are encountered.\n    After rollback, Exception is re-raised.\n\n    :param username: The username for the User\n    :param key: The public key to associate with this User\n    :param session: The sqlalchemy session to use\n    :rtype: User\n    :return: the new User record"
  },
  {
    "code": "def total_cycles(self) -> int:\n        return sum((int(re.sub(r'\\D', '', op)) for op in self.tokens))",
    "docstring": "The number of total number of cycles in the structure."
  },
  {
    "code": "def from_neighbor_pores(target, pore_prop='pore.seed', mode='min'):\n    r\n    prj = target.project\n    network = prj.network\n    throats = network.map_throats(target.throats(), target)\n    P12 = network.find_connected_pores(throats)\n    lookup = prj.find_full_domain(target)\n    pvalues = lookup[pore_prop][P12]\n    if mode == 'min':\n        value = np.amin(pvalues, axis=1)\n    if mode == 'max':\n        value = np.amax(pvalues, axis=1)\n    if mode == 'mean':\n        value = np.mean(pvalues, axis=1)\n    return value",
    "docstring": "r\"\"\"\n    Adopt a value based on the values in neighboring pores\n\n    Parameters\n    ----------\n    target : OpenPNM Object\n        The object which this model is associated with. This controls the\n        length of the calculated array, and also provides access to other\n        necessary properties.\n\n    pore_prop : string\n        The dictionary key to the array containing the pore property to be\n        used in the calculation.  Default is 'pore.seed'.\n\n    mode : string\n        Controls how the throat property is calculated.  Options are 'min',\n        'max' and 'mean'."
  },
  {
    "code": "def pack(self, remaining_size):\n        arguments_count, payload = self.pack_data(remaining_size - self.header_size)\n        payload_length = len(payload)\n        if payload_length % 8 != 0:\n            payload += b\"\\x00\" * (8 - payload_length % 8)\n        self.header = PartHeader(self.kind, self.attribute, arguments_count, self.bigargumentcount,\n                                 payload_length, remaining_size)\n        hdr = self.header_struct.pack(*self.header)\n        if pyhdb.tracing:\n            self.trace_header = humanhexlify(hdr, 30)\n            self.trace_payload = humanhexlify(payload, 30)\n        return hdr + payload",
    "docstring": "Pack data of part into binary format"
  },
  {
    "code": "def _get_user_hash(self):\n        if request:\n            user_hash = '{ip}-{ua}'.format(ip=request.remote_addr,\n                                           ua=self._get_user_agent())\n            alg = hashlib.md5()\n            alg.update(user_hash.encode('utf8'))\n            return alg.hexdigest()\n        return None",
    "docstring": "Calculate a digest based on request's User-Agent and IP address."
  },
  {
    "code": "def add_exec_permission_to(target_file):\n    mode = os.stat(target_file).st_mode\n    os.chmod(target_file, mode | stat.S_IXUSR)",
    "docstring": "Add executable permissions to the file\n\n    :param target_file: the target file whose permission to be changed"
  },
  {
    "code": "def tupleize(element, ignore_types=(str, bytes)):\n    if hasattr(element, '__iter__') and not isinstance(element, ignore_types):\n        return element\n    else:\n        return tuple((element,))",
    "docstring": "Cast a single element to a tuple."
  },
  {
    "code": "def get_cell_boundary_variables(ds):\n    boundary_variables = []\n    has_bounds = ds.get_variables_by_attributes(bounds=lambda x: x is not None)\n    for var in has_bounds:\n        if var.bounds in ds.variables:\n            boundary_variables.append(var.bounds)\n    return boundary_variables",
    "docstring": "Returns a list of variable names for variables that represent cell\n    boundaries through the `bounds` attribute\n\n    :param netCDF4.Dataset nc: netCDF dataset"
  },
  {
    "code": "def upgrade_available(name, **kwargs):\n    saltenv = kwargs.get('saltenv', 'base')\n    refresh = salt.utils.data.is_true(kwargs.get('refresh', True))\n    return latest_version(name, saltenv=saltenv, refresh=refresh) != ''",
    "docstring": "Check whether or not an upgrade is available for a given package\n\n    Args:\n        name (str): The name of a single package\n\n    Kwargs:\n        refresh (bool): Refresh package metadata. Default ``True``\n        saltenv (str): The salt environment. Default ``base``\n\n    Returns:\n        bool: True if new version available, otherwise False\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' pkg.upgrade_available <package name>"
  },
  {
    "code": "def _parse(self):\n        cur_ver = None\n        cur_line = None\n        for line in self.content:\n            m = re.match('[^ ]+ \\(([0-9]+\\.[0-9]+\\.[0-9]+)-[0-9]+\\) [^ ]+; urgency=[^ ]+', line)\n            if m:\n                cur_ver = m.group(1)\n                self.versions.append(cur_ver)\n                self.entries[cur_ver] = []\n                cur_entry = self.entries[cur_ver]\n                if self.latest_version is None or StrictVersion(cur_ver) > StrictVersion(self.latest_version):\n                    self.latest_version = m.group(1)\n            elif cur_ver:\n                m = re.match('  \\* (.*)', line)\n                if m:\n                    cur_entry.append(m.group(1).strip())\n                elif not re.match('$', line) and re.match(' *[^$]+', line):\n                    cur_entry[-1] += \" \" + line.strip()",
    "docstring": "Parse content of DCH file"
  },
  {
    "code": "def create_archaius(self):\n        utils.banner(\"Creating S3\")\n        s3.init_properties(env=self.env, app=self.app)",
    "docstring": "Create S3 bucket for Archaius."
  },
  {
    "code": "def cleanup(self):\n        with LogTask('Stop prefix'):\n            self.stop()\n        with LogTask(\"Tag prefix as uninitialized\"):\n            os.unlink(self.paths.prefix_lagofile())",
    "docstring": "Stops any running entities in the prefix and uninitializes it, usually\n        you want to do this if you are going to remove the prefix afterwards\n\n        Returns:\n            None"
  },
  {
    "code": "def send_file_to_host(src_filename, dst_file, filesize):\n    import sys\n    import ubinascii\n    try:\n        with open(src_filename, 'rb') as src_file:\n            bytes_remaining = filesize\n            if HAS_BUFFER:\n                buf_size = BUFFER_SIZE\n            else:\n                buf_size = BUFFER_SIZE // 2\n            while bytes_remaining > 0:\n                read_size = min(bytes_remaining, buf_size)\n                buf = src_file.read(read_size)\n                if HAS_BUFFER:\n                    sys.stdout.buffer.write(buf)\n                else:\n                    sys.stdout.write(ubinascii.hexlify(buf))\n                bytes_remaining -= read_size\n                while True:\n                    char = sys.stdin.read(1)\n                    if char:\n                        if char == '\\x06':\n                            break\n                        sys.stdout.write(char)\n        return True\n    except:\n        return False",
    "docstring": "Function which runs on the pyboard. Matches up with recv_file_from_remote."
  },
  {
    "code": "async def connect(self):\n        PYVLXLOG.warning(\"Connecting to KLF 200.\")\n        await self.connection.connect()\n        login = Login(pyvlx=self, password=self.config.password)\n        await login.do_api_call()\n        if not login.success:\n            raise PyVLXException(\"Login to KLF 200 failed, check credentials\")",
    "docstring": "Connect to KLF 200."
  },
  {
    "code": "def start(self, fork=True):\n        if not fork:\n            distributed_logger.info('Starting metrics aggregator, not forking')\n            _registry_aggregator(self.reporter, self.socket_addr)\n        else:\n            distributed_logger.info('Starting metrics aggregator, forking')\n            p = Process(target=_registry_aggregator, args=(self.reporter, self.socket_addr, ))\n            p.start()\n            distributed_logger.info('Started metrics aggregator as PID %s', p.pid)\n            self.process = p",
    "docstring": "Starts the registry aggregator.\n\n        :param fork: whether to fork a process; if ``False``, blocks and stays in the existing process"
  },
  {
    "code": "def sdiffstore(self, dest, keys, *args):\n        result = self.sdiff(keys, *args)\n        self.redis[self._encode(dest)] = result\n        return len(result)",
    "docstring": "Emulate sdiffstore."
  },
  {
    "code": "def one_batch(self, ds_type:DatasetType=DatasetType.Train, detach:bool=True, denorm:bool=True, cpu:bool=True)->Collection[Tensor]:\n        \"Get one batch from the data loader of `ds_type`. Optionally `detach` and `denorm`.\"\n        dl = self.dl(ds_type)\n        w = self.num_workers\n        self.num_workers = 0\n        try:     x,y = next(iter(dl))\n        finally: self.num_workers = w\n        if detach: x,y = to_detach(x,cpu=cpu),to_detach(y,cpu=cpu)\n        norm = getattr(self,'norm',False)\n        if denorm and norm:\n            x = self.denorm(x)\n            if norm.keywords.get('do_y',False): y = self.denorm(y, do_x=True)\n        return x,y",
    "docstring": "Get one batch from the data loader of `ds_type`. Optionally `detach` and `denorm`."
  },
  {
    "code": "def strip_ansi_escape_codes(self, string_buffer):\n        output = re.sub(r\"\\x00\", \"\", string_buffer)\n        return super(DellIsilonSSH, self).strip_ansi_escape_codes(output)",
    "docstring": "Remove Null code"
  },
  {
    "code": "def _enum_generator(descriptor):\n    'Helper to create protobuf enums'\n    vals = descriptor.enum_type.values_by_number.keys()\n    return gen.IterValueGenerator(descriptor.name, vals)",
    "docstring": "Helper to create protobuf enums"
  },
  {
    "code": "def run_async(\n        stream_spec, cmd='ffmpeg', pipe_stdin=False, pipe_stdout=False, pipe_stderr=False,\n        quiet=False, overwrite_output=False):\n    args = compile(stream_spec, cmd, overwrite_output=overwrite_output)\n    stdin_stream = subprocess.PIPE if pipe_stdin else None\n    stdout_stream = subprocess.PIPE if pipe_stdout or quiet else None\n    stderr_stream = subprocess.PIPE if pipe_stderr or quiet else None\n    return subprocess.Popen(\n        args, stdin=stdin_stream, stdout=stdout_stream, stderr=stderr_stream)",
    "docstring": "Asynchronously invoke ffmpeg for the supplied node graph.\n\n    Args:\n        pipe_stdin: if True, connect pipe to subprocess stdin (to be\n            used with ``pipe:`` ffmpeg inputs).\n        pipe_stdout: if True, connect pipe to subprocess stdout (to be\n            used with ``pipe:`` ffmpeg outputs).\n        pipe_stderr: if True, connect pipe to subprocess stderr.\n        quiet: shorthand for setting ``capture_stdout`` and\n            ``capture_stderr``.\n        **kwargs: keyword-arguments passed to ``get_args()`` (e.g.\n            ``overwrite_output=True``).\n\n    Returns:\n        A `subprocess Popen`_ object representing the child process.\n\n    Examples:\n        Run and stream input::\n\n            process = (\n                ffmpeg\n                .input('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(width, height))\n                .output(out_filename, pix_fmt='yuv420p')\n                .overwrite_output()\n                .run_async(pipe_stdin=True)\n            )\n            process.communicate(input=input_data)\n\n        Run and capture output::\n\n            process = (\n                ffmpeg\n                .input(in_filename)\n                .output('pipe':, format='rawvideo', pix_fmt='rgb24')\n                .run_async(pipe_stdout=True, pipe_stderr=True)\n            )\n            out, err = process.communicate()\n\n        Process video frame-by-frame using numpy::\n\n            process1 = (\n                ffmpeg\n                .input(in_filename)\n                .output('pipe:', format='rawvideo', pix_fmt='rgb24')\n                .run_async(pipe_stdout=True)\n            )\n\n            process2 = (\n                ffmpeg\n                .input('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(width, height))\n                .output(out_filename, pix_fmt='yuv420p')\n                .overwrite_output()\n                .run_async(pipe_stdin=True)\n            )\n\n            while True:\n                in_bytes = process1.stdout.read(width * height * 3)\n                if not in_bytes:\n                    break\n                in_frame = (\n                    np\n                    .frombuffer(in_bytes, np.uint8)\n                    .reshape([height, width, 3])\n                )\n                out_frame = in_frame * 0.3\n                process2.stdin.write(\n                    frame\n                    .astype(np.uint8)\n                    .tobytes()\n                )\n\n            process2.stdin.close()\n            process1.wait()\n            process2.wait()\n\n    .. _subprocess Popen: https://docs.python.org/3/library/subprocess.html#popen-objects"
  },
  {
    "code": "def load_config(self):\n        logger.debug('loading config file: %s', self.config_file)\n        if os.path.exists(self.config_file):\n            with open(self.config_file) as file_handle:\n                return json.load(file_handle)\n        else:\n            logger.error('configuration file is required for eventify')\n        logger.error('unable to load configuration for service')\n        raise EventifyConfigError(\n            'Configuration is required! Missing: %s' % self.config_file\n        )",
    "docstring": "Load configuration for the service\n\n        Args:\n            config_file: Configuration file path"
  },
  {
    "code": "def run(self):\n        self.modnames_to_reload = []\n        for modname, module in list(sys.modules.items()):\n            if modname not in self.previous_modules:\n                if self.is_module_reloadable(module, modname):\n                    self.modnames_to_reload.append(modname)\n                    del sys.modules[modname]\n                else:\n                    continue\n        if self.verbose and self.modnames_to_reload:\n            modnames = self.modnames_to_reload\n            _print(\"\\x1b[4;33m%s\\x1b[24m%s\\x1b[0m\"\\\n                   % (\"Reloaded modules\", \": \"+\", \".join(modnames)))",
    "docstring": "Delete user modules to force Python to deeply reload them\n\n        Do not del modules which are considered as system modules, i.e.\n        modules installed in subdirectories of Python interpreter's binary\n        Do not del C modules"
  },
  {
    "code": "def iter_lines(self, warn_only=False):\n        remain = \"\"\n        for data in self.iter_content(LINE_CHUNK_SIZE, warn_only=True):\n            line_break_found = data[-1] in (b\"\\n\", b\"\\r\")\n            lines = data.decode(self.codec).splitlines()\n            lines[0] = remain + lines[0]\n            if not line_break_found:\n                remain = lines.pop()\n            for line in lines:\n                yield line\n        if remain:\n            yield remain\n        self._state = FINISHED\n        if not warn_only:\n            self.raise_for_error()",
    "docstring": "yields stdout text, line by line."
  },
  {
    "code": "def render(file):\n    with file.open() as fp:\n        encoding = detect_encoding(fp, default='utf-8')\n        file_content = fp.read().decode(encoding)\n        parsed_xml = xml.dom.minidom.parseString(file_content)\n        return parsed_xml.toprettyxml(indent='  ', newl='')",
    "docstring": "Pretty print the XML file for rendering."
  },
  {
    "code": "def get_readable_tasks(self, course):\n        course_fs = self._filesystem.from_subfolder(course.get_id())\n        tasks = [\n            task[0:len(task)-1]\n            for task in course_fs.list(folders=True, files=False, recursive=False)\n            if self._task_file_exists(course_fs.from_subfolder(task))]\n        return tasks",
    "docstring": "Returns the list of all available tasks in a course"
  },
  {
    "code": "def ClaimNotificationsForCollection(cls,\n                                      token=None,\n                                      start_time=None,\n                                      lease_time=200,\n                                      collection=None):\n    class CollectionFilter(object):\n      def __init__(self, collection):\n        self.collection = collection\n      def FilterRecord(self, notification):\n        if self.collection is None:\n          self.collection = notification.result_collection_urn\n        return self.collection != notification.result_collection_urn\n    f = CollectionFilter(collection)\n    results = []\n    with aff4.FACTORY.OpenWithLock(\n        RESULT_NOTIFICATION_QUEUE,\n        aff4_type=HuntResultQueue,\n        lease_time=300,\n        blocking=True,\n        blocking_sleep_interval=15,\n        blocking_lock_timeout=600,\n        token=token) as queue:\n      for record in queue.ClaimRecords(\n          record_filter=f.FilterRecord,\n          start_time=start_time,\n          timeout=lease_time,\n          limit=100000):\n        results.append(record)\n    return (f.collection, results)",
    "docstring": "Return unclaimed hunt result notifications for collection.\n\n    Args:\n      token: The security token to perform database operations with.\n      start_time: If set, an RDFDateTime indicating at what point to start\n        claiming notifications. Only notifications with a timestamp after this\n        point will be claimed.\n      lease_time: How long to claim the notifications for.\n      collection: The urn of the collection to find notifications for. If unset,\n        the earliest (unclaimed) notification will determine the collection.\n\n    Returns:\n      A pair (collection, results) where collection is the collection\n      that notifications were retrieved for and results is a list of\n      Record objects which identify GrrMessage within the result\n      collection."
  },
  {
    "code": "def create_issue(title, body, repo, token):\n    owner, name = repo.split('/')\n    url = 'https://api.github.com/repos/%s/%s/issues' % (owner, name)\n    data = {'title': title, 'body': body }\n    headers = { \"Authorization\": \"token %s\" % token,\n                \"Accept\": \"application/vnd.github.symmetra-preview+json\" }\n    response = requests.post(url, data=json.dumps(data), headers=headers)\n    if response.status_code in [201, 202]:\n        url = response.json()['html_url']\n        bot.info(url)\n        return url\n    elif response.status_code == 404:\n        bot.error('Cannot create issue. Does your token have scope repo?')\n        sys.exit(1)\n    else:\n        bot.error('Cannot create issue %s' %title)\n        bot.error(response.content)\n        sys.exit(1)",
    "docstring": "create a Github issue, given a title, body, repo, and token.\n\n       Parameters\n       ==========\n       title: the issue title\n       body: the issue body\n       repo: the full name of the repo\n       token: the user's personal Github token"
  },
  {
    "code": "def _ensureHtmlAttribute(self):\n        tag = self.tag\n        if tag:\n            styleDict = self._styleDict\n            tagAttributes = tag._attributes\n            if not issubclass(tagAttributes.__class__, SpecialAttributesDict):\n                return\n            if not styleDict:\n                tagAttributes._direct_del('style')\n            else:\n                tagAttributes._direct_set('style', self)",
    "docstring": "_ensureHtmlAttribute - INTERNAL METHOD. \n                                    Ensure the \"style\" attribute is present in the html attributes when\n                                        is has a value, and absent when it does not.\n\n              This requires special linkage."
  },
  {
    "code": "def filter(self, run_counts, criteria):\n    correctness = criteria['correctness']\n    assert correctness.dtype == np.bool\n    filtered_counts = deep_copy(run_counts)\n    for key in filtered_counts:\n      filtered_counts[key] = filtered_counts[key][correctness]\n    return filtered_counts",
    "docstring": "Return run counts only for examples that are still correctly classified"
  },
  {
    "code": "def build_src(ctx, dest=None):\n    if dest:\n        if not dest.startswith('/'):\n            dest = os.path.join(os.getcwd(), dest)\n        os.chdir(PROJECT_DIR)\n        ctx.run('python setup.py sdist --dist-dir {0}'.format(dest))\n    else:\n        os.chdir(PROJECT_DIR)\n        ctx.run('python setup.py sdist')",
    "docstring": "build source archive"
  },
  {
    "code": "def request_sensor_sampling_clear(self, req):\n        f = Future()\n        @gen.coroutine\n        def _clear_strategies():\n            self.clear_strategies(req.client_connection)\n            raise gen.Return(('ok',))\n        self.ioloop.add_callback(lambda: chain_future(_clear_strategies(), f))\n        return f",
    "docstring": "Set all sampling strategies for this client to none.\n\n        Returns\n        -------\n        success : {'ok', 'fail'}\n            Whether sending the list of devices succeeded.\n\n        Examples\n        --------\n        ?sensor-sampling-clear\n        !sensor-sampling-clear ok"
  },
  {
    "code": "def encrypt(self, password):\n        if not password or not self._crypter:\n            return password or b''\n        return self._crypter.encrypt(password)",
    "docstring": "Encrypt the password."
  },
  {
    "code": "def run(self, *coros: CoroWrapper):\n        if not self.running:\n            raise RuntimeError(\"not running!\")\n        async def wrapper():\n            results = []\n            for coro in coros:\n                try:\n                    if inspect.isawaitable(coro):\n                        results.append(await coro)\n                    elif inspect.isfunction(coro):\n                        res = coro()\n                        if inspect.isawaitable(res):\n                            results.append(await res)\n                        else:\n                            results.append(res)\n                    else:\n                        raise RuntimeError(\n                            \"don't know how to run {}\".format(coro))\n                except Exception as ex:\n                    logger.error(\"Error while running coroutine {}: {}\".format(coro.__name__, ex.__repr__()))\n                    raise ex\n            if len(results) == 1:\n                return results[0]\n            return results\n        if coros:\n            what = wrapper()\n        else:\n            what = self.runFut\n        return self.loop.run_until_complete(what)",
    "docstring": "Runs an arbitrary list of coroutines in order and then quits the loop,\n        if not running as a context manager."
  },
  {
    "code": "def create_token(self, *, holder_name, card_number, credit_card_cvv, expiration_date, token_type='credit_card',\n                     identity_document=None, billing_address=None, additional_details=None):\n        headers = self.client._get_public_headers()\n        payload = {\n            \"token_type\": token_type,\n            \"credit_card_cvv\": credit_card_cvv,\n            \"card_number\": card_number,\n            \"expiration_date\": expiration_date,\n            \"holder_name\": holder_name,\n            \"identity_document\": identity_document,\n            \"billing_address\": billing_address,\n            \"additional_details\": additional_details,\n        }\n        endpoint = '/tokens'\n        return self.client._post(self.client.URL_BASE + endpoint, json=payload, headers=headers)",
    "docstring": "When creating a Token, remember to use the public-key header instead of the private-key header,\n        and do not include the app-id header.\n\n        Args:\n            holder_name: Name of the credit card holder.\n            card_number: Credit card number.\n            credit_card_cvv: The CVV number on the card (3 or 4 digits) to be encrypted.\n            expiration_date: Credit card expiration date. Possible formats: mm-yyyy, mm-yy, mm.yyyy,\n            mm.yy, mm/yy, mm/yyyy, mm yyyy, or mm yy.\n            token_type: The type of token\n            billing_address: Address.\n            identity_document: National identity document of the card holder.\n            additional_details: Optional additional data stored with your token in key/value pairs.\n\n        Returns:"
  },
  {
    "code": "def run():\n    Settings.pool = multiprocessing.Pool(Settings.jobs)\n    record_dirs, bytes_in, bytes_out, nag_about_gifs, errors = \\\n        _walk_all_files()\n    Settings.pool.close()\n    Settings.pool.join()\n    for filename in record_dirs:\n        timestamp.record_timestamp(filename)\n    stats.report_totals(bytes_in, bytes_out, nag_about_gifs, errors)",
    "docstring": "Use preconfigured settings to optimize files."
  },
  {
    "code": "def keys(self, pattern, *, encoding=_NOTSET):\n        return self.execute(b'KEYS', pattern, encoding=encoding)",
    "docstring": "Returns all keys matching pattern."
  },
  {
    "code": "def path(self, target, args, kw):\n        if type(target) in string_types:\n            if ':' in target:\n                prefix, rest = target.split(':', 1)\n                route = self.named_routes[prefix]\n                prefix_params = route._pop_params(args, kw)\n                prefix_path = route.path([], prefix_params)\n                next_mapper = route.resource\n                return prefix_path + next_mapper.path(rest, args, kw)\n            else:\n                return self.named_routes[target].path(args, kw)\n        elif isinstance(target, Route):\n            for route in self.routes:\n                if route is target:\n                    return route.path(args, kw)\n            raise InvalidArgumentError(\"Route '%s' not found in this %s object.\" % (target, self.__class__.__name__))\n        else:\n            target_id = id(target)\n            if target_id in self._lookup:\n                return self._lookup[target_id].path(args, kw)\n            raise InvalidArgumentError(\"No Route found for target '%s' in this %s object.\" % (target, self.__class__.__name__))",
    "docstring": "Build a URL path fragment for a resource or route.\n\n        Possible values for `target`:\n\n        A string that does not start with a '.' and does not contain ':'.\n          : Looks up the route of the same name on this mapper and returns it's\n            path.\n\n        A string of the form 'a:b', 'a:b:c', etc.\n          : Follows the route to nested mappers by splitting off consecutive\n            segments. Returns the path of the route found by looking up the\n            final segment on the last mapper.\n\n        A `Route` object\n          : Returns the path for the route.\n\n        A resource that was added previously\n          : Looks up the first route that points to this resource and\n            returns its path."
  },
  {
    "code": "def clear_url(self):\n        if (self.get_url_metadata().is_read_only() or\n                self.get_url_metadata().is_required()):\n            raise errors.NoAccess()\n        self._my_map['url'] = self._url_default",
    "docstring": "Removes the url.\n\n        raise:  NoAccess - ``Metadata.isRequired()`` is ``true`` or\n                ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_point_from_bins_and_idx(self, chi1_bin, chi2_bin, idx):\n        mass1 = self.massbank[chi1_bin][chi2_bin]['mass1s'][idx]\n        mass2 = self.massbank[chi1_bin][chi2_bin]['mass2s'][idx]\n        spin1z = self.massbank[chi1_bin][chi2_bin]['spin1s'][idx]\n        spin2z = self.massbank[chi1_bin][chi2_bin]['spin2s'][idx]\n        return mass1, mass2, spin1z, spin2z",
    "docstring": "Find masses and spins given bin numbers and index.\n\n        Given the chi1 bin, chi2 bin and an index, return the masses and spins\n        of the point at that index. Will fail if no point exists there.\n\n        Parameters\n        -----------\n        chi1_bin : int\n            The bin number for chi1.\n        chi2_bin : int\n            The bin number for chi2.\n        idx : int\n            The index within the chi1, chi2 bin.\n\n        Returns\n        --------\n        mass1 : float\n            Mass of heavier body.\n        mass2 : float\n            Mass of lighter body.\n        spin1z : float\n            Spin of heavier body.\n        spin2z : float\n            Spin of lighter body."
  },
  {
    "code": "def xline(self):\n        if self.unstructured:\n            raise ValueError(self._unstructured_errmsg)\n        if self._xline is not None:\n            return self._xline\n        self._xline = Line(self,\n                           self.xlines,\n                           self._xline_length,\n                           self._xline_stride,\n                           self.offsets,\n                           'crossline',\n                          )\n        return self._xline",
    "docstring": "Interact with segy in crossline mode\n\n        Returns\n        -------\n        xline : Line or None\n\n        Raises\n        ------\n        ValueError\n            If the file is unstructured\n\n        Notes\n        -----\n        .. versionadded:: 1.1"
  },
  {
    "code": "def _normalize(self, metric_name, submit_method, prefix):\n        metric_prefix = \"mongodb.\" if not prefix else \"mongodb.{0}.\".format(prefix)\n        metric_suffix = \"ps\" if submit_method == RATE else \"\"\n        for pattern, repl in iteritems(self.CASE_SENSITIVE_METRIC_NAME_SUFFIXES):\n            metric_name = re.compile(pattern).sub(repl, metric_name)\n        return u\"{metric_prefix}{normalized_metric_name}{metric_suffix}\".format(\n            normalized_metric_name=self.normalize(metric_name.lower()),\n            metric_prefix=metric_prefix,\n            metric_suffix=metric_suffix,\n        )",
    "docstring": "Replace case-sensitive metric name characters, normalize the metric name,\n        prefix and suffix according to its type."
  },
  {
    "code": "def tupleize_version(version):\n    if version is None:\n        return ((\"unknown\",),)\n    if version.startswith(\"<unknown\"):\n        return ((\"unknown\",),)\n    split = re.split(\"(?:\\.|(-))\", version)\n    parsed = tuple(try_fix_num(x) for x in split if x)\n    def is_dash(s):\n        return s == \"-\"\n    grouped = groupby(parsed, is_dash)\n    return tuple(tuple(group) for dash, group in grouped if not dash)",
    "docstring": "Split ``version`` into a lexicographically comparable tuple.\n\n    \"1.0.3\" -> ((1, 0, 3),)\n    \"1.0.3-dev\" -> ((1, 0, 3), (\"dev\",))\n    \"1.0.3-rc-5\" -> ((1, 0, 3), (\"rc\",), (5,))"
  },
  {
    "code": "def enforce_drop(self):\n        ub = self.ubnd\n        lb = self.lbnd\n        drop = []\n        for id in self.index:\n            if (ub - self.loc[id,:]).min() < 0.0 or\\\n                            (lb - self.loc[id,:]).max() > 0.0:\n                drop.append(id)\n        self.loc[drop,:] = np.NaN\n        self.dropna(inplace=True)",
    "docstring": "enforce parameter bounds on the ensemble by dropping\n        violating realizations"
  },
  {
    "code": "def parse(self, line):\n        tree = list(self.parser.raw_parse(line))[0]\n        tree = tree[0]\n        return tree",
    "docstring": "Returns tree objects from a sentence\n\n        Args:\n            line: Sentence to be parsed into a tree\n\n        Returns:\n            Tree object representing parsed sentence\n            None if parse fails"
  },
  {
    "code": "def _relative_name(self, record_name):\n        if not record_name:\n            return None\n        subdomain = super(Provider, self)._relative_name(record_name)\n        return subdomain if subdomain else None",
    "docstring": "Returns sub-domain of a domain name"
  },
  {
    "code": "def set_gene_name(self,name):\n    self._options = self._options._replace(gene_name = name)",
    "docstring": "assign a gene name\n\n    :param name: name\n    :type name: string"
  },
  {
    "code": "def binary(self, name):\n    if not isinstance(name, str):\n      raise ValueError('name must be a binary name, given {} of type {}'.format(name, type(name)))\n    self.validate()\n    return self._validated_executable(name)",
    "docstring": "Returns the path to the command of the given name for this distribution.\n\n    For example: ::\n\n        >>> d = Distribution()\n        >>> jar = d.binary('jar')\n        >>> jar\n        '/usr/bin/jar'\n        >>>\n\n    If this distribution has no valid command of the given name raises Distribution.Error.\n    If this distribution is a JDK checks both `bin` and `jre/bin` for the binary."
  },
  {
    "code": "def rectify_ajax_form_data(self, data):\n        for name, field in self.base_fields.items():\n            try:\n                data[name] = field.convert_ajax_data(data.get(name, {}))\n            except AttributeError:\n                pass\n        return data",
    "docstring": "If a widget was converted and the Form data was submitted through an Ajax request,\n        then these data fields must be converted to suit the Django Form validation"
  },
  {
    "code": "def clean_message(message: Message, topmost: bool = False) -> Message:\n    if message.is_multipart():\n        if message.get_content_type() != 'message/external-body':\n            parts = message.get_payload()\n            parts[:] = map(clean_message, parts)\n    elif message_is_binary(message):\n        if not topmost:\n            message = gut_message(message)\n    return message",
    "docstring": "Clean a message of all its binary parts.\n\n    This guts all binary attachments, and returns the message itself for\n    convenience."
  },
  {
    "code": "def translate_stringlist(val):\n    if not isinstance(val, list):\n        try:\n            val = split(val)\n        except AttributeError:\n            val = split(six.text_type(val))\n    for idx in range(len(val)):\n        if not isinstance(val[idx], six.string_types):\n            val[idx] = six.text_type(val[idx])\n    return val",
    "docstring": "On the CLI, these are passed as multiple instances of a given CLI option.\n    In Salt, we accept these as a comma-delimited list but the API expects a\n    Python list. This function accepts input and returns it back as a Python\n    list of strings. If the input is a string which is a comma-separated list\n    of items, split that string and return it."
  },
  {
    "code": "def getString(t):\n    slen = c_int()\n    s = c_char_p()\n    if PL_get_string_chars(t, byref(s), byref(slen)):\n        return s.value\n    else:\n        raise InvalidTypeError(\"string\")",
    "docstring": "If t is of type string, return it, otherwise raise InvalidTypeError."
  },
  {
    "code": "def normalize_url(url):\n    if not url or len(url) == 0:\n        return '/'\n    if not url.startswith('/'):\n        url = '/' + url\n    if len(url) > 1 and url.endswith('/'):\n        url = url[0:len(url) - 1]\n    return url",
    "docstring": "Return a normalized url with trailing and without leading slash.\n\n     >>> normalize_url(None)\n     '/'\n     >>> normalize_url('/')\n     '/'\n     >>> normalize_url('/foo/bar')\n     '/foo/bar'\n     >>> normalize_url('foo/bar')\n     '/foo/bar'\n     >>> normalize_url('/foo/bar/')\n     '/foo/bar'"
  },
  {
    "code": "def add(self, namespace_uri):\n        alias = self.namespace_to_alias.get(namespace_uri)\n        if alias is not None:\n            return alias\n        i = 0\n        while True:\n            alias = 'ext' + str(i)\n            try:\n                self.addAlias(namespace_uri, alias)\n            except KeyError:\n                i += 1\n            else:\n                return alias\n        assert False, \"Not reached\"",
    "docstring": "Add this namespace URI to the mapping, without caring what\n        alias it ends up with"
  },
  {
    "code": "def _return_assoc_tuple(self, objects):\n        if objects:\n            result = [(u'OBJECTPATH', {}, obj) for obj in objects]\n            return self._make_tuple(result)\n        return None",
    "docstring": "Create the property tuple for _imethod return of references,\n        referencenames, associators, and associatornames methods.\n\n        This is different than the get/enum imethod return tuples. It creates an\n        OBJECTPATH for each object in the return list.\n\n        _imethod call returns None when there are zero objects rather\n        than a tuple with empty object path"
  },
  {
    "code": "def folders(self):\n        for directory in self.directory:\n            for path in os.listdir(directory):\n                full_path = os.path.join(directory, path)\n                if os.path.isdir(full_path):\n                    if not path.startswith('.'):\n                        self.filepaths.append(full_path)\n        return self._get_filepaths()",
    "docstring": "Return list of folders in root directory"
  },
  {
    "code": "def update(self, read, write, manage):\n        data = values.of({'Read': read, 'Write': write, 'Manage': manage, })\n        payload = self._version.update(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return SyncListPermissionInstance(\n            self._version,\n            payload,\n            service_sid=self._solution['service_sid'],\n            list_sid=self._solution['list_sid'],\n            identity=self._solution['identity'],\n        )",
    "docstring": "Update the SyncListPermissionInstance\n\n        :param bool read: Read access.\n        :param bool write: Write access.\n        :param bool manage: Manage access.\n\n        :returns: Updated SyncListPermissionInstance\n        :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance"
  },
  {
    "code": "def concatenate(ctx, *text):\n    result = ''\n    for arg in text:\n        result += conversions.to_string(arg, ctx)\n    return result",
    "docstring": "Joins text strings into one text string"
  },
  {
    "code": "def post_message(plugin, polled_time, identity, message):\n    user = plugin.build_identifier(identity)\n    return plugin.send(user, message)",
    "docstring": "Post single message\n\n    :type plugin: errbot.BotPlugin\n    :type polled_time: datetime.datetime\n    :type identity: str\n    :type message: str"
  },
  {
    "code": "def export(self, private_key=True):\n        if private_key is True:\n            return self._export_all()\n        else:\n            return self.export_public()",
    "docstring": "Exports the key in the standard JSON format.\n        Exports the key regardless of type, if private_key is False\n        and the key is_symmetric an exceptionis raised.\n\n        :param private_key(bool): Whether to export the private key.\n                                  Defaults to True."
  },
  {
    "code": "def run(self, redirects = []):\n        if not isinstance(redirects, redir.Redirects):\n            redirects = redir.Redirects(self._env._redirects, *redirects)\n        with copy.copy_session() as sess:\n            self = copy.deepcopy(self)\n            processes = self._run(redirects, sess)\n        pipeline = RunningPipeline(processes, self)\n        self._env.last_pipeline = pipeline\n        return pipeline",
    "docstring": "Runs the pipelines with the specified redirects and returns\n        a RunningPipeline instance."
  },
  {
    "code": "def add_edge(self, source, target, interaction='-', directed=True, dataframe=True):\n        new_edge = {\n            'source': source,\n            'target': target,\n            'interaction': interaction,\n            'directed': directed\n        }\n        return self.add_edges([new_edge], dataframe=dataframe)",
    "docstring": "Add a single edge from source to target."
  },
  {
    "code": "def close_authenticator(self):\n        _logger.info(\"Shutting down CBS session on connection: %r.\", self._connection.container_id)\n        try:\n            _logger.debug(\"Unlocked CBS to close on connection: %r.\", self._connection.container_id)\n            self._cbs_auth.destroy()\n            _logger.info(\"Auth closed, destroying session on connection: %r.\", self._connection.container_id)\n            self._session.destroy()\n        finally:\n            _logger.info(\"Finished shutting down CBS session on connection: %r.\", self._connection.container_id)",
    "docstring": "Close the CBS auth channel and session."
  },
  {
    "code": "def parents(self):\n        parents = []\n        if self.parent is None:\n            return []\n        category = self\n        while category.parent is not None:\n            parents.append(category.parent)\n            category = category.parent\n        return parents[::-1]",
    "docstring": "Returns a list of all the current category's parents."
  },
  {
    "code": "def _get_version_mode(self, mode=None):\n        version_mode = self._version_modes.get(mode)\n        if not version_mode:\n            version_mode = self._version_modes[mode] = VersionMode(name=mode)\n        return version_mode",
    "docstring": "Return a VersionMode for a mode name.\n\n        When the mode is None, we are working with the 'base' mode."
  },
  {
    "code": "def parse_auth_token_from_request(self, auth_header):\n        if not auth_header:\n            raise falcon.HTTPUnauthorized(\n                description='Missing Authorization Header')\n        try:\n            auth_header_prefix, _ = auth_header.split(' ', 1)\n        except ValueError:\n            raise falcon.HTTPUnauthorized(\n                description='Invalid Authorization Header: Missing Scheme or Parameters')\n        if auth_header_prefix.lower() != self.auth_header_prefix.lower():\n            raise falcon.HTTPUnauthorized(\n                description='Invalid Authorization Header: '\n                            'Must start with {0}'.format(self.auth_header_prefix))\n        return auth_header",
    "docstring": "Parses and returns the Hawk Authorization header if it is present and well-formed.\n        Raises `falcon.HTTPUnauthoried exception` with proper error message"
  },
  {
    "code": "def dispatch(self,request,*args,**kwargs):\n        lessonSession = request.session.get(PRIVATELESSON_VALIDATION_STR,{})\n        try:\n            self.lesson = PrivateLessonEvent.objects.get(id=lessonSession.get('lesson'))\n        except (ValueError, ObjectDoesNotExist):\n            messages.error(request,_('Invalid lesson identifier passed to sign-up form.'))\n            return HttpResponseRedirect(reverse('bookPrivateLesson'))\n        expiry = parse_datetime(lessonSession.get('expiry',''),)\n        if not expiry or expiry < timezone.now():\n            messages.info(request,_('Your registration session has expired. Please try again.'))\n            return HttpResponseRedirect(reverse('bookPrivateLesson'))\n        self.payAtDoor = lessonSession.get('payAtDoor',False)\n        return super(PrivateLessonStudentInfoView,self).dispatch(request,*args,**kwargs)",
    "docstring": "Handle the session data passed by the prior view."
  },
  {
    "code": "def _make_query_from_terms(self, terms):\n        expanded_terms = self._expand_terms(terms)\n        cterms = ''\n        if expanded_terms['doc']:\n            cterms = self.backend._or_join(expanded_terms['doc'])\n        keywords = expanded_terms['keywords']\n        frm_to = self._from_to_as_term(expanded_terms['from'], expanded_terms['to'])\n        if frm_to:\n            keywords.append(frm_to)\n        if keywords:\n            if cterms:\n                cterms = self.backend._and_join(\n                    [cterms, self.backend._field_term('keywords', expanded_terms['keywords'])])\n            else:\n                cterms = self.backend._field_term('keywords', expanded_terms['keywords'])\n        logger.debug('partition terms conversion: `{}` terms converted to `{}` query.'.format(terms, cterms))\n        return cterms",
    "docstring": "returns a FTS query for partition created from decomposed search terms.\n\n        args:\n            terms (dict or str):\n\n        returns:\n            str containing fts query."
  },
  {
    "code": "def inserir(self, type, description):\n        script_type_map = dict()\n        script_type_map['type'] = type\n        script_type_map['description'] = description\n        code, xml = self.submit(\n            {'script_type': script_type_map}, 'POST', 'scripttype/')\n        return self.response(code, xml)",
    "docstring": "Inserts a new Script Type and returns its identifier.\n\n        :param type: Script Type type. String with a minimum 3 and maximum of 40 characters\n        :param description: Script Type description. String with a minimum 3 and maximum of 100 characters\n\n        :return: Dictionary with the following structure:\n\n        ::\n\n            {'script_type': {'id': < id_script_type >}}\n\n        :raise InvalidParameterError: Type or description is null and invalid.\n        :raise NomeTipoRoteiroDuplicadoError: Type script already registered with informed.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def ddtodms(self, dd):\n        negative = dd < 0\n        dd = abs(dd)\n        minutes,seconds = divmod(dd*3600,60)\n        degrees,minutes = divmod(minutes,60)\n        if negative:\n            if degrees > 0:\n                degrees = -degrees\n            elif minutes > 0:\n                minutes = -minutes\n            else:\n                seconds = -seconds\n        return (degrees,minutes,seconds)",
    "docstring": "Take in dd string and convert to dms"
  },
  {
    "code": "def _init_get_dict():\n        get_dict = {'main chain': PandasPdb._get_mainchain,\n                    'hydrogen': PandasPdb._get_hydrogen,\n                    'c-alpha': PandasPdb._get_calpha,\n                    'carbon': PandasPdb._get_carbon,\n                    'heavy': PandasPdb._get_heavy}\n        return get_dict",
    "docstring": "Initialize dictionary for filter operations."
  },
  {
    "code": "def shutdown_waits_for(coro, loop=None):\n    loop = loop or get_event_loop()\n    fut = loop.create_future()\n    async def coro_proxy():\n        try:\n            result = await coro\n        except (CancelledError, Exception) as e:\n            set_fut_done = partial(fut.set_exception, e)\n        else:\n            set_fut_done = partial(fut.set_result, result)\n        if not fut.cancelled():\n            set_fut_done()\n    new_coro = coro_proxy()\n    _DO_NOT_CANCEL_COROS.add(new_coro)\n    loop.create_task(new_coro)\n    async def inner():\n        return await fut\n    return inner()",
    "docstring": "Prevent coro from being cancelled during the shutdown sequence.\n\n    The trick here is that we add this coro to the global\n    \"DO_NOT_CANCEL\" collection, and then later during the shutdown\n    sequence we make sure that the task that wraps this coro will NOT\n    be cancelled.\n\n    To make this work, we have to create a super-secret task, below, that\n    communicates with the caller (which \"awaits\" us) via a Future. Using\n    a Future in this way allows us to avoid awaiting the Task, which\n    decouples the Task from the normal exception propagation which would\n    normally happen when the outer Task gets cancelled.  We get the\n    result of coro back to the caller via Future.set_result.\n\n    NOTE that during the shutdown sequence, the caller WILL NOT be able\n    to receive a result, since the caller will likely have been\n    cancelled.  So you should probably not rely on capturing results\n    via this function."
  },
  {
    "code": "def new(self, attribute, operation=ChainOperator.AND):\n        if isinstance(operation, str):\n            operation = ChainOperator(operation)\n        self._chain = operation\n        self._attribute = self._get_mapping(attribute) if attribute else None\n        self._negation = False\n        return self",
    "docstring": "Combine with a new query\n\n        :param str attribute: attribute of new query\n        :param ChainOperator operation: operation to combine to new query\n        :rtype: Query"
  },
  {
    "code": "def visit_Bytes(self, node: ast.Bytes) -> bytes:\n        result = node.s\n        self.recomputed_values[node] = result\n        return node.s",
    "docstring": "Recompute the value as the bytes at the node."
  },
  {
    "code": "def from_name(cls, relation_name, conversations=None):\n        if relation_name is None:\n            return None\n        relation_class = cls._cache.get(relation_name)\n        if relation_class:\n            return relation_class(relation_name, conversations)\n        role, interface = hookenv.relation_to_role_and_interface(relation_name)\n        if role and interface:\n            relation_class = cls._find_impl(role, interface)\n            if relation_class:\n                cls._cache[relation_name] = relation_class\n                return relation_class(relation_name, conversations)\n        return None",
    "docstring": "Find relation implementation in the current charm, based on the\n        name of the relation.\n\n        :return: A Relation instance, or None"
  },
  {
    "code": "def CaptureFrameLocals(self, frame):\n    variables = {n: self.CaptureNamedVariable(n, v, 1,\n                                              self.default_capture_limits)\n                 for n, v in six.viewitems(frame.f_locals)}\n    nargs = frame.f_code.co_argcount\n    if frame.f_code.co_flags & inspect.CO_VARARGS: nargs += 1\n    if frame.f_code.co_flags & inspect.CO_VARKEYWORDS: nargs += 1\n    frame_arguments = []\n    for argname in frame.f_code.co_varnames[:nargs]:\n      if argname in variables: frame_arguments.append(variables.pop(argname))\n    return (frame_arguments, list(six.viewvalues(variables)))",
    "docstring": "Captures local variables and arguments of the specified frame.\n\n    Args:\n      frame: frame to capture locals and arguments.\n\n    Returns:\n      (arguments, locals) tuple."
  },
  {
    "code": "def replace_pyof_version(module_fullname, version):\n        module_version = MetaStruct.get_pyof_version(module_fullname)\n        if not module_version or module_version == version:\n            return None\n        return module_fullname.replace(module_version, version)",
    "docstring": "Replace the OF Version of a module fullname.\n\n        Get's a module name (eg. 'pyof.v0x01.common.header') and returns it on\n        a new 'version' (eg. 'pyof.v0x02.common.header').\n\n        Args:\n            module_fullname (str): The fullname of the module\n                                   (e.g.: pyof.v0x01.common.header)\n            version (str): The version to be 'inserted' on the module fullname.\n\n        Returns:\n            str: module fullname\n                 The new module fullname, with the replaced version,\n                 on the format \"pyof.v0x01.common.header\". If the requested\n                 version is the same as the one of the module_fullname or if\n                 the module_fullname is not a 'OF version' specific module,\n                 returns None."
  },
  {
    "code": "def status(config='root', num_pre=None, num_post=None):\n    try:\n        pre, post = _get_num_interval(config, num_pre, num_post)\n        snapper.CreateComparison(config, int(pre), int(post))\n        files = snapper.GetFiles(config, int(pre), int(post))\n        status_ret = {}\n        SUBVOLUME = list_configs()[config]['SUBVOLUME']\n        for file in files:\n            _filepath = file[0][len(SUBVOLUME):] if file[0].startswith(SUBVOLUME) else file[0]\n            status_ret[os.path.normpath(SUBVOLUME + _filepath)] = {'status': status_to_string(file[1])}\n        return status_ret\n    except dbus.DBusException as exc:\n        raise CommandExecutionError(\n            'Error encountered while listing changed files: {0}'\n            .format(_dbus_exception_to_reason(exc, locals()))\n        )",
    "docstring": "Returns a comparison between two snapshots\n\n    config\n        Configuration name.\n\n    num_pre\n        first snapshot ID to compare. Default is last snapshot\n\n    num_post\n        last snapshot ID to compare. Default is 0 (current state)\n\n    CLI example:\n\n    .. code-block:: bash\n\n        salt '*' snapper.status\n        salt '*' snapper.status num_pre=19 num_post=20"
  },
  {
    "code": "def _send_mail(subject_or_message: Optional[Union[str, Message]] = None,\n               to: Optional[Union[str, List[str]]] = None,\n               template: Optional[str] = None,\n               **kwargs):\n    subject_or_message = subject_or_message or kwargs.pop('subject')\n    to = to or kwargs.pop('recipients', [])\n    msg = make_message(subject_or_message, to, template, **kwargs)\n    with mail.connect() as connection:\n        connection.send(msg)",
    "docstring": "The default function used for sending emails.\n\n    :param subject_or_message: A subject string, or for backwards compatibility with\n                               stock Flask-Mail, a :class:`~flask_mail.Message` instance\n    :param to: An email address, or a list of email addresses\n    :param template: Which template to render.\n    :param kwargs: Extra kwargs to pass on to :class:`~flask_mail.Message`"
  },
  {
    "code": "def get_commit_log(from_rev=None):\n    check_repo()\n    rev = None\n    if from_rev:\n        rev = '...{from_rev}'.format(from_rev=from_rev)\n    for commit in repo.iter_commits(rev):\n        yield (commit.hexsha, commit.message)",
    "docstring": "Yields all commit messages from last to first."
  },
  {
    "code": "def from_file(cls, filename, source):\n        _logger.info('Loading theme %s', filename)\n        try:\n            config = configparser.ConfigParser()\n            config.optionxform = six.text_type\n            with codecs.open(filename, encoding='utf-8') as fp:\n                config.readfp(fp)\n        except configparser.ParsingError as e:\n            raise ConfigError(e.message)\n        if not config.has_section('theme'):\n            raise ConfigError(\n                'Error loading {0}:\\n'\n                '    missing [theme] section'.format(filename))\n        theme_name = os.path.basename(filename)\n        theme_name, _ = os.path.splitext(theme_name)\n        elements = {}\n        for element, line in config.items('theme'):\n            if element not in cls.DEFAULT_ELEMENTS:\n                _logger.info('Skipping element %s', element)\n                continue\n            elements[element] = cls._parse_line(element, line, filename)\n        return cls(name=theme_name, source=source, elements=elements)",
    "docstring": "Load a theme from the specified configuration file.\n\n        Parameters:\n            filename: The name of the filename to load.\n            source: A description of where the theme was loaded from."
  },
  {
    "code": "def get_game_logs(self):\n        logs = self.response.json()['resultSets'][0]['rowSet']\n        headers = self.response.json()['resultSets'][0]['headers']\n        df = pd.DataFrame(logs, columns=headers)\n        df.GAME_DATE = pd.to_datetime(df.GAME_DATE)\n        return df",
    "docstring": "Returns team game logs as a pandas DataFrame"
  },
  {
    "code": "def options(self, **options):\n        for k in options:\n            self._jreader = self._jreader.option(k, to_str(options[k]))\n        return self",
    "docstring": "Adds input options for the underlying data source.\n\n        You can set the following option(s) for reading files:\n            * ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps\n                in the JSON/CSV datasources or partition values.\n                If it isn't set, it uses the default value, session local timezone."
  },
  {
    "code": "def encode_http_params(**kw):\n    try:\n        _fo = lambda k, v: '{name}={value}'.format(\n            name=k, value=to_basestring(quote(v)))\n    except:\n        _fo = lambda k, v: '%s=%s' % (k, to_basestring(quote(v)))\n    _en = utf8\n    return '&'.join([_fo(k, _en(v)) for k, v in kw.items() if not is_empty(v)])",
    "docstring": "url paremeter encode"
  },
  {
    "code": "def validate_source_dir(script, directory):\n    if directory:\n        if not os.path.isfile(os.path.join(directory, script)):\n            raise ValueError('No file named \"{}\" was found in directory \"{}\".'.format(script, directory))\n    return True",
    "docstring": "Validate that the source directory exists and it contains the user script\n\n    Args:\n        script (str):  Script filename.\n        directory (str): Directory containing the source file.\n\n    Raises:\n        ValueError: If ``directory`` does not exist, is not a directory, or does not contain ``script``."
  },
  {
    "code": "def _uniqueid(n=30):\n    return ''.join(random.SystemRandom().choice(\n                   string.ascii_uppercase + string.ascii_lowercase)\n                   for _ in range(n))",
    "docstring": "Return a unique string with length n.\n\n    :parameter int N: number of character in the uniqueid\n    :return: the uniqueid\n    :rtype: str"
  },
  {
    "code": "def master_ref(self):\n        return ReferencesDataFrame(self._engine_dataframe.getReferences().getHEAD(),\n                                   self._session, self._implicits)",
    "docstring": "Filters the current DataFrame references to only contain those rows whose reference is master.\n\n        >>> master_df = repos_df.master_ref\n\n        :rtype: ReferencesDataFrame"
  },
  {
    "code": "def _normalize_helper(number, replacements, remove_non_matches):\n    normalized_number = []\n    for char in number:\n        new_digit = replacements.get(char.upper(), None)\n        if new_digit is not None:\n            normalized_number.append(new_digit)\n        elif not remove_non_matches:\n            normalized_number.append(char)\n    return U_EMPTY_STRING.join(normalized_number)",
    "docstring": "Normalizes a string of characters representing a phone number by\n    replacing all characters found in the accompanying map with the values\n    therein, and stripping all other characters if remove_non_matches is true.\n\n    Arguments:\n    number -- a string representing a phone number\n    replacements -- a mapping of characters to what they should be replaced\n              by in the normalized version of the phone number\n    remove_non_matches -- indicates whether characters that are not able to be\n              replaced should be stripped from the number. If this is False,\n              they will be left unchanged in the number.\n\n    Returns the normalized string version of the phone number."
  },
  {
    "code": "def global_unlock_percent(self):\n        percent = CRef.cfloat()\n        result = self._iface.get_ach_progress(self.name, percent)\n        if not result:\n            return 0.0\n        return float(percent)",
    "docstring": "Global achievement unlock percent.\n\n        :rtype: float"
  },
  {
    "code": "def get_index2latex(model_description):\n    index2latex = {}\n    translation_csv = os.path.join(get_project_root(),\n                                   model_description[\"data-source\"],\n                                   \"index2formula_id.csv\")\n    with open(translation_csv) as csvfile:\n        csvreader = csv.DictReader(csvfile, delimiter=',', quotechar='\"')\n        for row in csvreader:\n            index2latex[int(row['index'])] = row['latex']\n    return index2latex",
    "docstring": "Get a dictionary that maps indices to LaTeX commands.\n\n    Parameters\n    ----------\n    model_description : string\n        A model description file that points to a feature folder where an\n        `index2formula_id.csv` has to be.\n\n    Returns\n    -------\n    dictionary :\n        Maps indices to LaTeX commands"
  },
  {
    "code": "def series64bitto32bit(s):\n    if s.dtype == np.float64:\n        return s.astype('float32')\n    elif s.dtype == np.int64:\n        return s.astype('int32')\n    return s",
    "docstring": "Convert a Pandas series from 64 bit types to 32 bit types to save\n    memory or disk space.\n\n    Parameters\n    ----------\n    s : The series to convert\n\n    Returns\n    -------\n    The converted series"
  },
  {
    "code": "def present(self, path, timeout=0):\n        ret, data = self.sendmess(MSG_PRESENCE, str2bytez(path),\n                                  timeout=timeout)\n        assert ret <= 0 and not data, (ret, data)\n        if ret < 0:\n            return False\n        else:\n            return True",
    "docstring": "returns True if there is an entity at path"
  },
  {
    "code": "def set_priority(self, priority):\n        if priority in [\"hidden\", \"background\", \"info\", \"foreground\", \"alert\", \"input\"]:\n            self.priority = priority\n            self.server.request(\"screen_set %s priority %s\" % (self.ref, self.priority))",
    "docstring": "Set Screen Priority Class"
  },
  {
    "code": "def load_zae(file_obj, resolver=None, **kwargs):\n    archive = util.decompress(file_obj,\n                              file_type='zip')\n    file_name = next(i for i in archive.keys()\n                     if i.lower().endswith('.dae'))\n    resolver = visual.resolvers.ZipResolver(archive)\n    loaded = load_collada(archive[file_name],\n                          resolver=resolver,\n                          **kwargs)\n    return loaded",
    "docstring": "Load a ZAE file, which is just a zipped DAE file.\n\n    Parameters\n    -------------\n    file_obj : file object\n      Contains ZAE data\n    resolver : trimesh.visual.Resolver\n      Resolver to load additional assets\n    kwargs : dict\n      Passed to load_collada\n\n    Returns\n    ------------\n    loaded : dict\n      Results of loading"
  },
  {
    "code": "def op_get_mutate_fields( op_name ):\n    global MUTATE_FIELDS\n    if op_name not in MUTATE_FIELDS.keys():\n        raise Exception(\"No such operation '%s'\" % op_name)\n    fields = MUTATE_FIELDS[op_name][:]\n    return fields",
    "docstring": "Get the names of the fields that will change\n    when this operation gets applied to a record."
  },
  {
    "code": "def _create_payload(payload):\n        blocks, remainder = divmod(len(payload), BLOCKSIZE)\n        if remainder > 0:\n            payload += (BLOCKSIZE - remainder) * NUL\n        return payload",
    "docstring": "Return the string payload filled with zero bytes\n           up to the next 512 byte border."
  },
  {
    "code": "def version_cmd(argv):\n    import pkg_resources\n    try:\n        __version__ = pkg_resources.get_distribution('pew').version\n    except pkg_resources.DistributionNotFound:\n        __version__ = 'unknown'\n        print('Setuptools has some issues here, failed to get our own package.', file=sys.stderr)\n    print(__version__)",
    "docstring": "Prints current pew version"
  },
  {
    "code": "def get_assessments_taken(self):\n        collection = JSONClientValidated('assessment',\n                                         collection='AssessmentTaken',\n                                         runtime=self._runtime)\n        result = collection.find(self._view_filter()).sort('_id', DESCENDING)\n        return objects.AssessmentTakenList(result, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets all ``AssessmentTaken`` elements.\n\n        In plenary mode, the returned list contains all known\n        assessments taken or an error results. Otherwise, the returned\n        list may contain only those assessments taken that are\n        accessible through this session.\n\n        return: (osid.assessment.AssessmentTakenList) - a list of\n                ``AssessmentTaken`` elements\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_cell_content(self):\n        try:\n            if self.code_array.cell_attributes[self.key][\"button_cell\"]:\n                return\n        except IndexError:\n            return\n        try:\n            return self.code_array[self.key]\n        except IndexError:\n            pass",
    "docstring": "Returns cell content"
  },
  {
    "code": "def draw_graph(G: nx.DiGraph, filename: str):\n    A = to_agraph(G)\n    A.graph_attr[\"rankdir\"] = \"LR\"\n    A.draw(filename, prog=\"dot\")",
    "docstring": "Draw a networkx graph with Pygraphviz."
  },
  {
    "code": "def merge_and_fit(self, track, pairings):\n        for (self_seg_index, track_seg_index, _) in pairings:\n            self_s = self.segments[self_seg_index]\n            ss_start = self_s.points[0]\n            track_s = track.segments[track_seg_index]\n            tt_start = track_s.points[0]\n            tt_end = track_s.points[-1]\n            d_start = ss_start.distance(tt_start)\n            d_end = ss_start.distance(tt_end)\n            if d_start > d_end:\n                track_s = track_s.copy()\n                track_s.points = list(reversed(track_s.points))\n            self_s.merge_and_fit(track_s)\n        return self",
    "docstring": "Merges another track with this one, ordering the points based on a\n            distance heuristic\n\n        Args:\n            track (:obj:`Track`): Track to merge with\n            pairings\n        Returns:\n            :obj:`Segment`: self"
  },
  {
    "code": "def get_completions(self, candidates):\n        queryset = BlockCompletion.user_course_completion_queryset(self._user, self._course_key).filter(\n            block_key__in=candidates\n        )\n        completions = BlockCompletion.completion_by_block_key(queryset)\n        candidates_with_runs = [candidate.replace(course_key=self._course_key) for candidate in candidates]\n        for candidate in candidates_with_runs:\n            if candidate not in completions:\n                completions[candidate] = 0.0\n        return completions",
    "docstring": "Given an iterable collection of block_keys in the course, returns a\n        mapping of the block_keys to the present completion values of their\n        associated blocks.\n\n        If a completion is not found for a given block in the current course,\n        0.0 is returned.  The service does not attempt to verify that the block\n        exists within the course.\n\n        Parameters:\n\n            candidates: collection of BlockKeys within the current course.\n            Note: Usage keys may not have the course run filled in for old mongo courses.\n            This method checks for completion records against a set of BlockKey candidates with the course run\n            filled in from self._course_key.\n\n        Return value:\n\n            dict[BlockKey] -> float: Mapping blocks to their completion value."
  },
  {
    "code": "def filter_by_gene_expression(\n            self,\n            gene_expression_dict,\n            min_expression_value=0.0):\n        return self.filter_any_above_threshold(\n            multi_key_fn=lambda effect: effect.gene_ids,\n            value_dict=gene_expression_dict,\n            threshold=min_expression_value)",
    "docstring": "Filters variants down to those which have overlap a gene whose\n        expression value in the transcript_expression_dict argument is greater\n        than min_expression_value.\n\n        Parameters\n        ----------\n        gene_expression_dict : dict\n            Dictionary mapping Ensembl gene IDs to expression estimates\n            (either FPKM or TPM)\n\n        min_expression_value : float\n            Threshold above which we'll keep an effect in the result collection"
  },
  {
    "code": "def transform_feature_names(transformer, in_names=None):\n    if hasattr(transformer, 'get_feature_names'):\n        return transformer.get_feature_names()\n    raise NotImplementedError('transform_feature_names not available for '\n                              '{}'.format(transformer))",
    "docstring": "Get feature names for transformer output as a function of input names.\n\n    Used by :func:`explain_weights` when applied to a scikit-learn Pipeline,\n    this ``singledispatch`` should be registered with custom name\n    transformations for each class of transformer.\n    \n    If there is no ``singledispatch`` handler registered for a transformer \n    class, ``transformer.get_feature_names()`` method is called; if there is\n    no such method then feature names are not supported and \n    this function raises an exception.\n\n    Parameters\n    ----------\n    transformer : scikit-learn-compatible transformer\n    in_names : list of str, optional\n        Names for features input to transformer.transform().\n        If not provided, the implementation may generate default feature names\n        if the number of input features is known.\n\n    Returns\n    -------\n    feature_names : list of str"
  },
  {
    "code": "def findSequenceOnDisk(cls, pattern, strictPadding=False):\n        seq = cls(pattern)\n        if seq.frameRange() == '' and seq.padding() == '':\n            if os.path.isfile(pattern):\n                return seq\n        patt = seq.format('{dirname}{basename}*{extension}')\n        ext = seq.extension()\n        basename = seq.basename()\n        pad = seq.padding()\n        globbed = iglob(patt)\n        if pad and strictPadding:\n            globbed = cls._filterByPaddingNum(globbed, seq.zfill())\n            pad = cls.conformPadding(pad)\n        matches = cls.yield_sequences_in_list(globbed)\n        for match in matches:\n            if match.basename() == basename and match.extension() == ext:\n                if pad and strictPadding:\n                    match.setPadding(pad)\n                return match\n        msg = 'no sequence found on disk matching {0}'\n        raise FileSeqException(msg.format(pattern))",
    "docstring": "Search for a specific sequence on disk.\n\n        The padding characters used in the `pattern` are used to filter the\n        frame values of the files on disk (if `strictPadding` is True).\n\n        Examples:\n            Find sequence matching basename and extension, and a wildcard for\n            any frame.\n            returns bar.1.exr bar.10.exr, bar.100.exr, bar.1000.exr, inclusive\n\n            >>> findSequenceOnDisk(\"seq/bar@@@@.exr\")\n\n            Find exactly 4-padded sequence, i.e. seq/bar1-100#.exr\n            returns only frames bar1000.exr through bar9999.exr\n\n            >>> findSequenceOnDisk(\"seq/bar#.exr\", strictPadding=True)\n\n        Args:\n            pattern (str): the sequence pattern being searched for\n            strictPadding (bool): if True, ignore files with padding length different from `pattern`\n\n        Returns:\n            str:\n\n        Raises:\n            :class:`.FileSeqException`: if no sequence is found on disk"
  },
  {
    "code": "def mag_calibration(self):\n        self.calibration_state = self.CAL_MAG\n        self.mag_dialog = SK8MagDialog(self.sk8.get_imu(self.spinIMU.value()), self)\n        if self.mag_dialog.exec_() == QDialog.Rejected:\n            return\n        self.calculate_mag_calibration(self.mag_dialog.samples)",
    "docstring": "Perform magnetometer calibration for current IMU."
  },
  {
    "code": "def printable(sequence):\n    return ''.join(list(\n        map(lambda c: c if c in PRINTABLE else '.', sequence)\n    ))",
    "docstring": "Return a printable string from the input ``sequence``\n\n    :param sequence: byte or string sequence\n\n    >>> print(printable('\\\\x1b[1;34mtest\\\\x1b[0m'))\n    .[1;34mtest.[0m\n    >>> printable('\\\\x00\\\\x01\\\\x02\\\\x03\\\\x04\\\\x05\\\\x06\\\\x06') == '........'\n    True\n\n    >>> print(printable('12345678'))\n    12345678\n    >>> print(printable('testing\\\\n'))\n    testing."
  },
  {
    "code": "def get_user_vault_instance_or_none(self, user):\n        qset = self.filter(user=user)\n        if not qset:\n            return None\n        if qset.count() > 1:\n            raise Exception('This app does not currently support multiple vault ids')\n        return qset.get()",
    "docstring": "Returns a vault_id string or None"
  },
  {
    "code": "def sample_statements(stmts, seed=None):\n    if seed:\n        numpy.random.seed(seed)\n    new_stmts = []\n    r = numpy.random.rand(len(stmts))\n    for i, stmt in enumerate(stmts):\n        if r[i] < stmt.belief:\n            new_stmts.append(stmt)\n    return new_stmts",
    "docstring": "Return statements sampled according to belief.\n\n    Statements are sampled independently according to their\n    belief scores. For instance, a Staement with a belief\n    score of 0.7 will end up in the returned Statement list\n    with probability 0.7.\n\n    Parameters\n    ----------\n    stmts : list[indra.statements.Statement]\n        A list of INDRA Statements to sample.\n    seed : Optional[int]\n        A seed for the random number generator used for sampling.\n\n    Returns\n    -------\n    new_stmts : list[indra.statements.Statement]\n        A list of INDRA Statements that were chosen by random sampling\n        according to their respective belief scores."
  },
  {
    "code": "def move(self, point: Point) -> 'Location':\n        return self._replace(point=self.point + point)",
    "docstring": "Alter the point stored in the location while preserving the labware.\n\n        This returns a new Location and does not alter the current one. It\n        should be used like\n\n        .. code-block:: python\n\n            >>> loc = Location(Point(1, 1, 1), 'Hi')\n            >>> new_loc = loc.move(Point(1, 1, 1))\n            >>> assert loc_2.point == Point(2, 2, 2)  # True\n            >>> assert loc.point == Point(1, 1, 1)  # True"
  },
  {
    "code": "def send_verification_email(self):\n        url = (self._imgur._base_url + \"/3/account/{0}\"\n               \"/verifyemail\".format(self.name))\n        self._imgur._send_request(url, needs_auth=True, method='POST')",
    "docstring": "Send verification email to this users email address.\n\n        Remember that the verification email may end up in the users spam\n        folder."
  },
  {
    "code": "def _did_count(self, connection):\n        self.current_connection = connection\n        response = connection.response\n        count = 0\n        callback = None\n        if 'X-Nuage-Count' in response.headers:\n            count = int(response.headers['X-Nuage-Count'])\n        if 'remote' in connection.callbacks:\n            callback = connection.callbacks['remote']\n        if connection.async:\n            if callback:\n                callback(self, self.parent_object, count)\n                self.current_connection.reset()\n                self.current_connection = None\n        else:\n            if connection.response.status_code >= 400 and BambouConfig._should_raise_bambou_http_error:\n                raise BambouHTTPError(connection=connection)\n            return (self, self.parent_object, count)",
    "docstring": "Called when count if finished"
  },
  {
    "code": "def array2tree(arr, name='tree', tree=None):\n    import ROOT\n    if tree is not None:\n        if not isinstance(tree, ROOT.TTree):\n            raise TypeError(\"tree must be a ROOT.TTree\")\n        incobj = ROOT.AsCObject(tree)\n    else:\n        incobj = None\n    cobj = _librootnumpy.array2tree_toCObj(arr, name=name, tree=incobj)\n    return ROOT.BindObject(cobj, 'TTree')",
    "docstring": "Convert a numpy structured array into a ROOT TTree.\n\n    Fields of basic types, strings, and fixed-size subarrays of basic types are\n    supported. ``np.object`` and ``np.float16`` are currently not supported.\n\n    Parameters\n    ----------\n    arr : array\n        A numpy structured array\n    name : str (optional, default='tree')\n        Name of the created ROOT TTree if ``tree`` is None.\n    tree : ROOT TTree (optional, default=None)\n        An existing ROOT TTree to be extended by the numpy array. Any branch\n        with the same name as a field in the numpy array will be extended as\n        long as the types are compatible, otherwise a TypeError is raised. New\n        branches will be created and filled for all new fields.\n\n    Returns\n    -------\n    root_tree : a ROOT TTree\n\n    Notes\n    -----\n    When using the ``tree`` argument to extend and/or add new branches to an\n    existing tree, note that it is possible to create branches of different\n    lengths. This will result in a warning from ROOT when root_numpy calls the\n    tree's ``SetEntries()`` method. Beyond that, the tree should still be\n    usable. While it might not be generally recommended to create branches with\n    differing lengths, this behaviour could be required in certain situations.\n    root_numpy makes no attempt to prevent such behaviour as this would be more\n    strict than ROOT itself. Also see the note about converting trees that have\n    branches of different lengths into numpy arrays in the documentation of\n    :func:`tree2array`.\n\n    See Also\n    --------\n    array2root\n    root2array\n    tree2array\n\n    Examples\n    --------\n\n    Convert a numpy array into a tree:\n\n    >>> from root_numpy import array2tree\n    >>> import numpy as np\n    >>>\n    >>> a = np.array([(1, 2.5, 3.4),\n    ...               (4, 5, 6.8)],\n    ...              dtype=[('a', np.int32),\n    ...                     ('b', np.float32),\n    ...                     ('c', np.float64)])\n    >>> tree = array2tree(a)\n    >>> tree.Scan()\n    ************************************************\n    *    Row   *         a *         b *         c *\n    ************************************************\n    *        0 *         1 *       2.5 *       3.4 *\n    *        1 *         4 *         5 *       6.8 *\n    ************************************************\n\n    Add new branches to an existing tree (continuing from the example above):\n\n    >>> b = np.array([(4, 10),\n    ...               (3, 5)],\n    ...              dtype=[('d', np.int32),\n    ...                     ('e', np.int32)])\n    >>> array2tree(b, tree=tree)\n    <ROOT.TTree object (\"tree\") at 0x1449970>\n    >>> tree.Scan()\n    ************************************************************************\n    *    Row   *         a *         b *         c *         d *         e *\n    ************************************************************************\n    *        0 *         1 *       2.5 *       3.4 *         4 *        10 *\n    *        1 *         4 *         5 *       6.8 *         3 *         5 *\n    ************************************************************************"
  },
  {
    "code": "def list(gandi, fqdn, name, sort, type, rrset_type, text):\n    domains = gandi.dns.list()\n    domains = [domain['fqdn'] for domain in domains]\n    if fqdn not in domains:\n        gandi.echo('Sorry domain %s does not exist' % fqdn)\n        gandi.echo('Please use one of the following: %s' % ', '.join(domains))\n        return\n    output_keys = ['name', 'ttl', 'type', 'values']\n    result = gandi.dns.records(fqdn, sort_by=sort, text=text)\n    if text:\n        gandi.echo(result)\n        return result\n    for num, rec in enumerate(result):\n        if type and rec['rrset_type'] != type:\n            continue\n        if rrset_type and rec['rrset_type'] != rrset_type:\n            continue\n        if name and rec['rrset_name'] != name:\n            continue\n        if num:\n            gandi.separator_line()\n        output_dns_records(gandi, rec, output_keys)\n    return result",
    "docstring": "Display records for a domain."
  },
  {
    "code": "def tilt_model(params, shape):\n    mx = params[\"mx\"].value\n    my = params[\"my\"].value\n    off = params[\"off\"].value\n    bg = np.zeros(shape, dtype=float) + off\n    x = np.arange(bg.shape[0]) - bg.shape[0] // 2\n    y = np.arange(bg.shape[1]) - bg.shape[1] // 2\n    x = x.reshape(-1, 1)\n    y = y.reshape(1, -1)\n    bg += mx * x + my * y\n    return bg",
    "docstring": "lmfit tilt model"
  },
  {
    "code": "def _collapse_attributes(self, line, header, indexes):\n        names = []\n        vals = []\n        pat = re.compile(\"[\\W]+\")\n        for i in indexes:\n            names.append(pat.sub(\"_\", self._clean_header(header[i])))\n            vals.append(line[i])\n        Attrs = collections.namedtuple('Attrs', names)\n        return Attrs(*vals)",
    "docstring": "Combine attributes in multiple columns into single named tuple."
  },
  {
    "code": "def load_objects(self, addr, num_bytes, ret_on_segv=False):\n        result = []\n        end = addr + num_bytes\n        for page_addr in self._containing_pages(addr, end):\n            try:\n                page = self._get_page(page_addr // self._page_size)\n            except KeyError:\n                if self.allow_segv:\n                    if ret_on_segv:\n                        break\n                    raise SimSegfaultError(addr, 'read-miss')\n                else:\n                    continue\n            if self.allow_segv and not page.concrete_permissions & DbgPage.PROT_READ:\n                if ret_on_segv:\n                    break\n                raise SimSegfaultError(addr, 'non-readable')\n            result.extend(page.load_slice(self.state, addr, end))\n        return result",
    "docstring": "Load memory objects from paged memory.\n\n        :param addr: Address to start loading.\n        :param num_bytes: Number of bytes to load.\n        :param bool ret_on_segv: True if you want load_bytes to return directly when a SIGSEV is triggered, otherwise\n                                 a SimSegfaultError will be raised.\n        :return: list of tuples of (addr, memory_object)\n        :rtype: tuple"
  },
  {
    "code": "def to_det_oid(self, det_id_or_det_oid):\n        try:\n            int(det_id_or_det_oid)\n        except ValueError:\n            return det_id_or_det_oid\n        else:\n            return self.get_det_oid(det_id_or_det_oid)",
    "docstring": "Convert det OID or ID to det OID"
  },
  {
    "code": "def build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True):\n    param_keys = set()\n    param_str = []\n    for key, type_info, desc in zip(arg_names, arg_types, arg_descs):\n        if key in param_keys and remove_dup:\n            continue\n        if key == 'num_args':\n            continue\n        param_keys.add(key)\n        ret = '%s : %s' % (key, type_info)\n        if len(desc) != 0:\n            ret += '\\n    ' + desc\n        param_str.append(ret)\n    doc_str = ('Parameters\\n' +\n               '----------\\n' +\n               '%s\\n')\n    doc_str = doc_str % ('\\n'.join(param_str))\n    return doc_str",
    "docstring": "Build argument docs in python style.\n\n    arg_names : list of str\n        Argument names.\n\n    arg_types : list of str\n        Argument type information.\n\n    arg_descs : list of str\n        Argument description information.\n\n    remove_dup : boolean, optional\n        Whether remove duplication or not.\n\n    Returns\n    -------\n    docstr : str\n        Python docstring of parameter sections."
  },
  {
    "code": "def Run(self):\n    if not self.executable:\n      logging.error('Could not locate \"%s\"' % self.long_name)\n      return 0\n    finfo = os.stat(self.executable)\n    self.date = time.localtime(finfo[stat.ST_MTIME])\n    logging.info('Running: %s %s </dev/null 2>&1'\n                 % (self.executable, FLAGS.help_flag))\n    (child_stdin, child_stdout_and_stderr) = os.popen4(\n      [self.executable, FLAGS.help_flag])\n    child_stdin.close()\n    self.output = child_stdout_and_stderr.readlines()\n    child_stdout_and_stderr.close()\n    if len(self.output) < _MIN_VALID_USAGE_MSG:\n      logging.error('Error: \"%s %s\" returned only %d lines: %s'\n                    % (self.name, FLAGS.help_flag,\n                       len(self.output), self.output))\n      return 0\n    return 1",
    "docstring": "Run it and collect output.\n\n    Returns:\n      1 (true)   If everything went well.\n      0 (false)  If there were problems."
  },
  {
    "code": "def getOverlayTransformAbsolute(self, ulOverlayHandle):\n        fn = self.function_table.getOverlayTransformAbsolute\n        peTrackingOrigin = ETrackingUniverseOrigin()\n        pmatTrackingOriginToOverlayTransform = HmdMatrix34_t()\n        result = fn(ulOverlayHandle, byref(peTrackingOrigin), byref(pmatTrackingOriginToOverlayTransform))\n        return result, peTrackingOrigin, pmatTrackingOriginToOverlayTransform",
    "docstring": "Gets the transform if it is absolute. Returns an error if the transform is some other type."
  },
  {
    "code": "def main():\n    features = os.environ.get('APE_PREPEND_FEATURES', '').split()\n    inline_features = os.environ.get('PRODUCT_EQUATION', '').split()\n    if inline_features:\n        features += inline_features\n    else:\n        feature_file = os.environ.get('PRODUCT_EQUATION_FILENAME', '')\n        if feature_file:\n            features += get_features_from_equation_file(feature_file)\n        else:\n            if not features:\n                raise EnvironmentIncomplete(\n                    'Error running ape:\\n'\n                    'Either the PRODUCT_EQUATION or '\n                    'PRODUCT_EQUATION_FILENAME environment '\n                    'variable needs to be set!'\n                )\n    run(sys.argv, features=features)",
    "docstring": "Entry point when used via command line.\n\n    Features are given using the environment variable ``PRODUCT_EQUATION``.\n    If it is not set, ``PRODUCT_EQUATION_FILENAME`` is tried: if it points\n    to an existing equation file that selection is used.\n\n    (if ``APE_PREPEND_FEATURES`` is given, those features are prepended)\n\n    If the list of features is empty, ``ape.EnvironmentIncomplete`` is raised."
  },
  {
    "code": "def write_index(self):\n        self.fileobj.seek(self.last_offset)\n        index = index_header.build(dict(entries=self.entries))\n        self.fileobj.write(index)\n        self.filesize = self.fileobj.tell()",
    "docstring": "Write the index of all our files to the MAR file."
  },
  {
    "code": "def _pys2code(self, line):\n        row, col, tab, code = self._split_tidy(line, maxsplit=3)\n        key = self._get_key(row, col, tab)\n        self.code_array.dict_grid[key] = unicode(code, encoding='utf-8')",
    "docstring": "Updates code in pys code_array"
  },
  {
    "code": "def setup_session(endpoint_context, areq, uid, client_id='', acr='', salt='salt',\n                  authn_event=None):\n    if authn_event is None and acr:\n        authn_event = AuthnEvent(uid=uid, salt=salt, authn_info=acr,\n                                 authn_time=time.time())\n    if not client_id:\n        client_id = areq['client_id']\n    sid = endpoint_context.sdb.create_authz_session(authn_event, areq,\n                                                    client_id=client_id,\n                                                    uid=uid)\n    endpoint_context.sdb.do_sub(sid, uid, '')\n    return sid",
    "docstring": "Setting up a user session\n\n    :param endpoint_context:\n    :param areq:\n    :param uid:\n    :param acr:\n    :param client_id:\n    :param salt:\n    :param authn_event: A already made AuthnEvent\n    :return:"
  },
  {
    "code": "def set_metadata(self, metadata, utf8):\n        cairo.cairo_pdf_surface_set_metadata(\n            self._pointer, metadata, _encode_string(utf8))\n        self._check_status()",
    "docstring": "Sets document metadata.\n\n        The ``PDF_METADATA_CREATE_DATE`` and ``PDF_METADATA_MOD_DATE``\n        values must be in ISO-8601 format: YYYY-MM-DDThh:mm:ss. An optional\n        timezone of the form \"[+/-]hh:mm\" or \"Z\" for UTC time can be appended.\n        All other metadata values can be any UTF-8 string.\n\n        :param metadata: the metadata item to set.\n        :param utf8: metadata value.\n\n        *New in cairo 1.16.*\n\n        *New in cairocffi 0.9.*"
  },
  {
    "code": "def request_set_status(self, text: str) -> dict:\n        method_params = {'text': text}\n        response = self.session.send_method_request('status.set',\n                                                    method_params)\n        self.check_for_errors('status.set', method_params, response)\n        return response",
    "docstring": "Method to set user status"
  },
  {
    "code": "def to_json(self):\n        capsule = {}\n        capsule[\"Hierarchy\"] = []\n        for (\n            dying,\n            (persistence, surviving, saddle),\n        ) in self.merge_sequence.items():\n            capsule[\"Hierarchy\"].append(\n                {\n                    \"Dying\": dying,\n                    \"Persistence\": persistence,\n                    \"Surviving\": surviving,\n                    \"Saddle\": saddle,\n                }\n            )\n        capsule[\"Partitions\"] = []\n        base = np.array([None, None] * len(self.Y)).reshape(-1, 2)\n        for (min_index, max_index), items in self.base_partitions.items():\n            base[items, :] = [min_index, max_index]\n        capsule[\"Partitions\"] = base.tolist()\n        return json.dumps(capsule)",
    "docstring": "Writes the complete Morse-Smale merge hierarchy to a string\n            object.\n            @ Out, a string object storing the entire merge hierarchy of\n            all minima and maxima."
  },
  {
    "code": "def set_default(self, val, force=False):\n        if self.default is None or force:\n            self.default = val\n            self.set_value(val)\n            self.has_changed = True\n        else:\n            raise OptionError(\n                \"cannot override existing default without using the 'force' \"\n                \"option\"\n            )",
    "docstring": "this function allows a default to be set on an option that dosen't\n        have one.  It is used when a base class defines an Option for use in\n        derived classes but cannot predict what value would useful to the\n        derived classes.  This gives the derived classes the opportunity to\n        set a logical default appropriate for the derived class' context.\n\n        For example:\n\n            class A(RequiredConfig):\n                required_config = Namespace()\n                required_config.add_option(\n                  'x',\n                  default=None\n                )\n\n            class B(A):\n                A.required_config.x.set_default(68)\n\n        parameters:\n            val - the value for the default\n            force - normally this function only works on Options that have not\n                    had a default set (default is None).  This boolean allows\n                    you to override an existing default."
  },
  {
    "code": "def unique(self, e, **kwargs):\n        if not isinstance(e, claripy.ast.Base):\n            return True\n        if o.SYMBOLIC not in self.state.options and self.symbolic(e):\n            return False\n        r = self.eval_upto(e, 2, **kwargs)\n        if len(r) == 1:\n            self.add(e == r[0])\n            return True\n        elif len(r) == 0:\n            raise SimValueError(\"unsatness during uniqueness check(ness)\")\n        else:\n            return False",
    "docstring": "Returns True if the expression `e` has only one solution by querying\n        the constraint solver. It does also add that unique solution to the\n        solver's constraints."
  },
  {
    "code": "def instance(self, skip_exist_test=False):\n        model = self.database._models[self.related_to]\n        meth = model.lazy_connect if skip_exist_test else model\n        return meth(self.proxy_get())",
    "docstring": "Returns the instance of the related object linked by the field."
  },
  {
    "code": "def validate_value_string (f, value_string):\n    assert isinstance(f, Feature)\n    assert isinstance(value_string, basestring)\n    if f.free or value_string in f.values:\n        return\n    values = [value_string]\n    if f.subfeatures:\n        if not value_string in f.values and \\\n               not value_string in f.subfeatures:\n            values = value_string.split('-')\n    if not values[0] in f.values and \\\n           (values[0] or not f.optional):\n        raise InvalidValue (\"'%s' is not a known value of feature '%s'\\nlegal values: '%s'\" % (values [0], f.name, f.values))\n    for v in values [1:]:\n        implied_subfeature(f, v, values[0])",
    "docstring": "Checks that value-string is a valid value-string for the given feature."
  },
  {
    "code": "def add_device_override(self, addr, cat, subcat, firmware=None):\n        self.plm.devices.add_override(addr, 'cat', cat)\n        self.plm.devices.add_override(addr, 'subcat', subcat)\n        if firmware:\n            self.plm.devices.add_override(addr, 'firmware', firmware)",
    "docstring": "Add a device override to the PLM."
  },
  {
    "code": "def directory(name, profile=None, **kwargs):\n    created = False\n    rtn = {\n        'name': name,\n        'comment': 'Directory exists',\n        'result': True,\n        'changes': {}\n    }\n    current = __salt__['etcd.get'](name, profile=profile, recurse=True, **kwargs)\n    if not current:\n        created = True\n    result = __salt__['etcd.set'](name, None, directory=True, profile=profile, **kwargs)\n    if result and result != current:\n        if created:\n            rtn['comment'] = 'New directory created'\n            rtn['changes'] = {\n                name: 'Created'\n            }\n    return rtn",
    "docstring": "Create a directory in etcd.\n\n    name\n        The etcd directory name, for example: ``/foo/bar/baz``.\n    profile\n        Optional, defaults to ``None``. Sets the etcd profile to use which has\n        been defined in the Salt Master config.\n\n        .. code-block:: yaml\n\n            my_etd_config:\n              etcd.host: 127.0.0.1\n              etcd.port: 4001"
  },
  {
    "code": "def pseudolocalize(self, s):\n        if not s:\n            return u\"\"\n        if not isinstance(s, six.text_type):\n            raise TypeError(\"String to pseudo-localize must be of type '{0}'.\".format(six.text_type.__name__))\n        if not self.transforms:\n            return s\n        fmt_spec = re.compile(\n            r\n, re.VERBOSE)\n        if not fmt_spec.search(s):\n            result = s\n            for munge in self.transforms:\n                result = munge(result)\n        else:\n            substrings = fmt_spec.split(s)\n            for munge in self.transforms:\n                if munge in transforms._transliterations:\n                    for idx in range(len(substrings)):\n                        if not fmt_spec.match(substrings[idx]):\n                            substrings[idx] = munge(substrings[idx])\n                    else:\n                        continue\n                else:\n                    continue\n            result = u\"\".join(substrings)\n            for munge in self.transforms:\n                if munge not in transforms._transliterations:\n                    result = munge(result)\n        return result",
    "docstring": "Performs pseudo-localization on a string.  The specific transforms to be\n        applied to the string is defined in the transforms field of the object.\n\n        :param s: String to pseudo-localize.\n        :returns: Copy of the string s with the transforms applied.  If the input\n                  string is an empty string or None, an empty string is returned."
  },
  {
    "code": "def __highlight_occurence(self, file, occurence):\n        if not self.__container.get_editor(file):\n            cache_data = self.__files_cache.get_content(file)\n            if cache_data:\n                document = cache_data.document or self.__get_document(cache_data.content)\n                self.__container.load_document(document, file)\n                self.__uncache(file)\n            else:\n                self.__container.load_file(file)\n        else:\n            self.__container.set_current_editor(file)\n        if not occurence:\n            return\n        cursor = self.__container.get_current_editor().textCursor()\n        cursor.setPosition(occurence.position, QTextCursor.MoveAnchor)\n        cursor.setPosition(occurence.position + occurence.length, QTextCursor.KeepAnchor)\n        self.__container.get_current_editor().setTextCursor(cursor)",
    "docstring": "Highlights given file occurence.\n\n        :param file: File containing the occurence.\n        :type file: unicode\n        :param occurence: Occurence to highlight.\n        :type occurence: Occurence or SearchOccurenceNode"
  },
  {
    "code": "def _save_config(section, token, value):\n    cmd = NIRTCFG_PATH\n    cmd += ' --set section={0},token=\\'{1}\\',value=\\'{2}\\''.format(section, token, value)\n    if __salt__['cmd.run_all'](cmd)['retcode'] != 0:\n        exc_msg = 'Error: could not set {} to {} for {}\\n'.format(token, value, section)\n        raise salt.exceptions.CommandExecutionError(exc_msg)",
    "docstring": "Helper function to persist a configuration in the ini file"
  },
  {
    "code": "def validate(self, raw_data, **kwargs):\n        try:\n            converted_data = int(raw_data)\n            return super(IntegerField, self).validate(converted_data)\n        except ValueError:\n            raise ValidationException(self.messages['invalid'], repr(raw_data))",
    "docstring": "Convert the raw_data to an integer."
  },
  {
    "code": "def add(self, factory, component, properties=None):\n        with self.__lock:\n            if component in self.__names:\n                raise ValueError(\n                    \"Component name already queued: {0}\".format(component)\n                )\n            if properties is None:\n                properties = {}\n            self.__names[component] = factory\n            self.__queue.setdefault(factory, {})[component] = properties\n            try:\n                with use_ipopo(self.__context) as ipopo:\n                    self._try_instantiate(ipopo, factory, component)\n            except BundleException:\n                pass",
    "docstring": "Enqueues the instantiation of the given component\n\n        :param factory: Factory name\n        :param component: Component name\n        :param properties: Component properties\n        :raise ValueError: Component name already reserved in the queue\n        :raise Exception: Error instantiating the component"
  },
  {
    "code": "def key_sign(rsakey, message, digest):\n    padding = _asymmetric.padding.PKCS1v15()\n    signature = rsakey.sign(message, padding, digest)\n    return signature",
    "docstring": "Sign the given message with the RSA key."
  },
  {
    "code": "def charge_series(seq, granularity=0.1):\n    if 'X' in seq:\n        warnings.warn(_nc_warning_str, NoncanonicalWarning)\n    ph_range = numpy.arange(1, 13, granularity)\n    charge_at_ph = [sequence_charge(seq, ph) for ph in ph_range]\n    return ph_range, charge_at_ph",
    "docstring": "Calculates the charge for pH 1-13.\n\n    Parameters\n    ----------\n    seq : str\n        Sequence of amino acids.\n    granularity : float, optional\n        Granularity of pH values i.e. if 0.1 pH = [1.0, 1.1, 1.2...]"
  },
  {
    "code": "def properties(self):\n        properties = _get_tree_properties(self)\n        properties.update({\n            'is_bst': _is_bst(self),\n            'is_balanced': _is_balanced(self) >= 0\n        })\n        return properties",
    "docstring": "Return various properties of the binary tree.\n\n        :return: Binary tree properties.\n        :rtype: dict\n\n        **Example**:\n\n        .. doctest::\n\n            >>> from binarytree import Node\n            >>>\n            >>> root = Node(1)\n            >>> root.left = Node(2)\n            >>> root.right = Node(3)\n            >>> root.left.left = Node(4)\n            >>> root.left.right = Node(5)\n            >>> props = root.properties\n            >>>\n            >>> props['height']         # equivalent to root.height\n            2\n            >>> props['size']           # equivalent to root.size\n            5\n            >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth\n            2\n            >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth\n            1\n            >>> props['max_node_value'] # equivalent to root.max_node_value\n            5\n            >>> props['min_node_value'] # equivalent to root.min_node_value\n            1\n            >>> props['leaf_count']     # equivalent to root.leaf_count\n            3\n            >>> props['is_balanced']    # equivalent to root.is_balanced\n            True\n            >>> props['is_bst']         # equivalent to root.is_bst\n            False\n            >>> props['is_complete']    # equivalent to root.is_complete\n            True\n            >>> props['is_max_heap']    # equivalent to root.is_max_heap\n            False\n            >>> props['is_min_heap']    # equivalent to root.is_min_heap\n            True\n            >>> props['is_perfect']     # equivalent to root.is_perfect\n            False\n            >>> props['is_strict']      # equivalent to root.is_strict\n            True"
  },
  {
    "code": "def explained_variance(returns, values):\n    exp_var = 1 - torch.var(returns - values) / torch.var(returns)\n    return exp_var.item()",
    "docstring": "Calculate how much variance in returns do the values explain"
  },
  {
    "code": "def unsubscribe(self, sid):\n        if sid not in self.observers:\n            raise KeyError(\n                'Cannot disconnect a observer does not connected to subject'\n            )\n        del self.observers[sid]",
    "docstring": "Disconnect an observer from this subject"
  },
  {
    "code": "def fit(self, sequences, y=None):\n        check_iter_of_sequences(sequences, allow_trajectory=self._allow_trajectory)\n        super(MultiSequenceClusterMixin, self).fit(self._concat(sequences))\n        if hasattr(self, 'labels_'):\n            self.labels_ = self._split(self.labels_)\n        return self",
    "docstring": "Fit the  clustering on the data\n\n        Parameters\n        ----------\n        sequences : list of array-like, each of shape [sequence_length, n_features]\n            A list of multivariate timeseries. Each sequence may have\n            a different length, but they all must have the same number\n            of features.\n\n        Returns\n        -------\n        self"
  },
  {
    "code": "def table(\n        data_frame,\n        scale: float = 0.7,\n        include_index: bool = False,\n        max_rows: int = 500\n):\n    r = _get_report()\n    r.append_body(render.table(\n        data_frame=data_frame,\n        scale=scale,\n        include_index=include_index,\n        max_rows=max_rows\n    ))\n    r.stdout_interceptor.write_source('[ADDED] Table\\n')",
    "docstring": "Adds the specified data frame to the display in a nicely formatted\n    scrolling table.\n\n    :param data_frame:\n        The pandas data frame to be rendered to a table.\n    :param scale:\n        The display scale with units of fractional screen height. A value\n        of 0.5 constrains the output to a maximum height equal to half the\n        height of browser window when viewed. Values below 1.0 are usually\n        recommended so the entire output can be viewed without scrolling.\n    :param include_index:\n        Whether or not the index column should be included in the displayed\n        output. The index column is not included by default because it is\n        often unnecessary extra information in the display of the data.\n    :param max_rows:\n        This argument exists to prevent accidentally writing very large data\n        frames to a table, which can cause the notebook display to become\n        sluggish or unresponsive. If you want to display large tables, you need\n        only increase the value of this argument."
  },
  {
    "code": "def get_assessment_form_for_create(self, assessment_record_types):\n        for arg in assessment_record_types:\n            if not isinstance(arg, ABCType):\n                raise errors.InvalidArgument('one or more argument array elements is not a valid OSID Type')\n        if assessment_record_types == []:\n            obj_form = objects.AssessmentForm(\n                bank_id=self._catalog_id,\n                runtime=self._runtime,\n                effective_agent_id=self.get_effective_agent_id(),\n                proxy=self._proxy)\n        else:\n            obj_form = objects.AssessmentForm(\n                bank_id=self._catalog_id,\n                record_types=assessment_record_types,\n                runtime=self._runtime,\n                effective_agent_id=self.get_effective_agent_id(),\n                proxy=self._proxy)\n        self._forms[obj_form.get_id().get_identifier()] = not CREATED\n        return obj_form",
    "docstring": "Gets the assessment form for creating new assessments.\n\n        A new form should be requested for each create transaction.\n\n        arg:    assessment_record_types (osid.type.Type[]): array of\n                assessment record types to be included in the create\n                operation or an empty list if none\n        return: (osid.assessment.AssessmentForm) - the assessment form\n        raise:  NullArgument - ``assessment_record_types`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        raise:  Unsupported - unable to get form for requested record\n                types\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def find_missing_env(self):\n        missing = []\n        for e in self.env:\n            if e.default_val is None and e.set_val is None:\n                if e.env_name not in os.environ:\n                    missing.append(e.env_name)\n        if missing:\n            raise BadOption(\"Some environment variables aren't in the current environment\", missing=missing)",
    "docstring": "Find any missing environment variables"
  },
  {
    "code": "def shift(self, periods, freq=None):\n        result = self._data._time_shift(periods, freq=freq)\n        return type(self)(result, name=self.name)",
    "docstring": "Shift index by desired number of time frequency increments.\n\n        This method is for shifting the values of datetime-like indexes\n        by a specified time increment a given number of times.\n\n        Parameters\n        ----------\n        periods : int\n            Number of periods (or increments) to shift by,\n            can be positive or negative.\n\n            .. versionchanged:: 0.24.0\n\n        freq : pandas.DateOffset, pandas.Timedelta or string, optional\n            Frequency increment to shift by.\n            If None, the index is shifted by its own `freq` attribute.\n            Offset aliases are valid strings, e.g., 'D', 'W', 'M' etc.\n\n        Returns\n        -------\n        pandas.DatetimeIndex\n            Shifted index.\n\n        See Also\n        --------\n        Index.shift : Shift values of Index.\n        PeriodIndex.shift : Shift values of PeriodIndex."
  },
  {
    "code": "def server_close(self):\n        self.log.debug(\"Closing the socket server connection.\")\n        TCPServer.server_close(self)\n        self.queue_manager.close()\n        self.topic_manager.close()\n        if hasattr(self.authenticator, 'close'):\n            self.authenticator.close()\n        self.shutdown()",
    "docstring": "Closes the socket server and any associated resources."
  },
  {
    "code": "def savepoint(cr):\n    if hasattr(cr, 'savepoint'):\n        with cr.savepoint():\n            yield\n    else:\n        name = uuid.uuid1().hex\n        cr.execute('SAVEPOINT \"%s\"' % name)\n        try:\n            yield\n            cr.execute('RELEASE SAVEPOINT \"%s\"' % name)\n        except:\n            cr.execute('ROLLBACK TO SAVEPOINT \"%s\"' % name)",
    "docstring": "return a context manager wrapping postgres savepoints"
  },
  {
    "code": "def print_maps_by_type(map_type, number=None):\n    map_type = map_type.lower().capitalize()\n    if map_type not in MAP_TYPES:\n        s = 'Invalid map type, must be one of {0}'.format(MAP_TYPES)\n        raise ValueError(s)\n    print(map_type)\n    map_keys = sorted(COLOR_MAPS[map_type].keys())\n    format_str = '{0:8}  :  {1}'\n    for mk in map_keys:\n        num_keys = sorted(COLOR_MAPS[map_type][mk].keys(), key=int)\n        if not number or str(number) in num_keys:\n            num_str = '{' + ', '.join(num_keys) + '}'\n            print(format_str.format(mk, num_str))",
    "docstring": "Print all available maps of a given type.\n\n    Parameters\n    ----------\n    map_type : {'Sequential', 'Diverging', 'Qualitative'}\n        Select map type to print.\n    number : int, optional\n        Filter output by number of defined colors. By default there is\n        no numeric filtering."
  },
  {
    "code": "def offline_plotly_data(data, filename=None, config=None, validate=True,\n                        default_width='100%', default_height=525, global_requirejs=False):\n    r\n    config_default = dict(DEFAULT_PLOTLY_CONFIG)\n    if config is not None:\n        config_default.update(config)\n    with open(os.path.join(DATA_PATH, 'plotly.js.min'), 'rt') as f:\n        js = f.read()\n    html, divid, width, height = _plot_html(\n        data,\n        config=config_default,\n        validate=validate,\n        default_width=default_width, default_height=default_height,\n        global_requirejs=global_requirejs)\n    html = PLOTLY_HTML.format(plotlyjs=js, plotlyhtml=html)\n    if filename and isinstance(filename, str):\n        with open(filename, 'wt') as f:\n            f.write(html)\n    return html",
    "docstring": "r\"\"\" Write a plotly scatter plot to HTML file that doesn't require server\n\n    >>> from nlpia.loaders import get_data\n    >>> df = get_data('etpinard')  # pd.read_csv('https://plot.ly/~etpinard/191.csv')\n    >>> df.columns = [eval(c) if c[0] in '\"\\'' else str(c) for c in df.columns]\n    >>> data = {'data': [\n    ...          Scatter(x=df[continent+', x'],\n    ...                  y=df[continent+', y'],\n    ...                  text=df[continent+', text'],\n    ...                  marker=Marker(size=df[continent+', size'].fillna(10000), sizemode='area', sizeref=131868,),\n    ...                  mode='markers',\n    ...                  name=continent) for continent in ['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']\n    ...      ],\n    ...      'layout': Layout(xaxis=XAxis(title='Life Expectancy'), yaxis=YAxis(title='GDP per Capita', type='log'))\n    ... }\n    >>> html = offline_plotly_data(data, filename=None)"
  },
  {
    "code": "def arp_suppression(self, **kwargs):\n        name = kwargs.pop('name')\n        enable = kwargs.pop('enable', True)\n        get = kwargs.pop('get', False)\n        callback = kwargs.pop('callback', self._callback)\n        method_class = self._interface\n        arp_args = dict(name=name)\n        if name:\n            if not pynos.utilities.valid_vlan_id(name):\n                raise InvalidVlanId(\"`name` must be between `1` and `8191`\")\n        arp_suppression = getattr(method_class,\n                                  'interface_vlan_interface_vlan_suppress_'\n                                  'arp_suppress_arp_enable')\n        config = arp_suppression(**arp_args)\n        if get:\n            return callback(config, handler='get_config')\n        if not enable:\n                config.find('.//*suppress-arp').set('operation', 'delete')\n        return callback(config)",
    "docstring": "Enable Arp Suppression on a Vlan.\n\n        Args:\n            name:Vlan name on which the Arp suppression needs to be enabled.\n            enable (bool): If arp suppression should be enabled\n                or disabled.Default:``True``.\n            get (bool) : Get config instead of editing config. (True, False)\n            callback (function): A function executed upon completion of the\n               method.  The only parameter passed to `callback` will be the\n                ``ElementTree`` `config`.\n        Returns:\n            Return value of `callback`.\n        Raises:\n            KeyError: if `name` is not passed.\n            ValueError: if `name` is invalid.\n           output2 = dev.interface.arp_suppression(name='89')\n        Examples:\n            >>> import pynos.device\n            >>> switches = ['10.24.39.211', '10.24.39.203']\n            >>> auth = ('admin', 'password')\n            >>> for switch in switches:\n            ...     conn = (switch, '22')\n            ...     with pynos.device.Device(conn=conn, auth=auth) as dev:\n            ...         output = dev.interface.arp_suppression(\n            ...         name='89')\n            ...         output = dev.interface.arp_suppression(\n            ...         get=True,name='89')\n            ...         output = dev.interface.arp_suppression(\n            ...         enable=False,name='89')\n            ...         # doctest: +IGNORE_EXCEPTION_DETAIL\n            Traceback (most recent call last):\n            KeyError"
  },
  {
    "code": "def load_module(self, loader):\n        modfile, pathname, description = loader.info\n        module = imp.load_module(\n            loader.fullname,\n            modfile,\n            pathname,\n            description\n        )\n        sys.modules[loader.fullname] = module\n        self.__loaded_modules.add(loader.fullname)\n        autodecorator.decorate_module(module, decorator=self.__decorator)\n        return module",
    "docstring": "Load the module. Required for the Python meta-loading mechanism."
  },
  {
    "code": "def deal_with_changeset_stack_policy(self, fqn, stack_policy):\n        if stack_policy:\n            kwargs = generate_stack_policy_args(stack_policy)\n            kwargs[\"StackName\"] = fqn\n            logger.debug(\"Setting stack policy on %s.\", fqn)\n            self.cloudformation.set_stack_policy(**kwargs)",
    "docstring": "Set a stack policy when using changesets.\n\n        ChangeSets don't allow you to set stack policies in the same call to\n        update them. This sets it before executing the changeset if the\n        stack policy is passed in.\n\n        Args:\n            stack_policy (:class:`stacker.providers.base.Template`): A template\n                object representing a stack policy."
  },
  {
    "code": "def pkg_upgrade(repo, skip, flag):\n    Msg().checking()\n    PACKAGES_TXT = RepoInit(repo).fetch()[0]\n    pkgs_for_upgrade = []\n    data = repo_data(PACKAGES_TXT, repo, flag=\"\")\n    for pkg in installed():\n        status(0.0005)\n        inst_pkg = split_package(pkg)\n        for name in data[0]:\n            if name:\n                repo_pkg = split_package(name[:-4])\n            if (repo_pkg[0] == inst_pkg[0] and\n                LooseVersion(repo_pkg[1]) > LooseVersion(inst_pkg[1]) and\n                repo_pkg[3] >= inst_pkg[3] and\n                    inst_pkg[0] not in skip and\n                    repo_pkg[1] != \"blacklist\"):\n                pkgs_for_upgrade.append(repo_pkg[0])\n    Msg().done()\n    if \"--checklist\" in flag:\n        pkgs_for_upgrade = choose_upg(pkgs_for_upgrade)\n    return pkgs_for_upgrade",
    "docstring": "Checking packages for upgrade"
  },
  {
    "code": "def create(cls, name, abr_type='cisco', auto_cost_bandwidth=100,\n               deprecated_algorithm=False, initial_delay=200,\n               initial_hold_time=1000, max_hold_time=10000,\n               shutdown_max_metric_lsa=0, startup_max_metric_lsa=0):\n        json = {'name': name,\n                'abr_type': abr_type,\n                'auto_cost_bandwidth': auto_cost_bandwidth,\n                'deprecated_algorithm': deprecated_algorithm,\n                'initial_delay': initial_delay,\n                'initial_hold_time': initial_hold_time,\n                'max_hold_time': max_hold_time,\n                'shutdown_max_metric_lsa': shutdown_max_metric_lsa,\n                'startup_max_metric_lsa': startup_max_metric_lsa}\n        return ElementCreator(cls, json)",
    "docstring": "Create custom Domain Settings\n\n        Domain settings are referenced by an OSPFProfile\n\n        :param str name: name of custom domain settings\n        :param str abr_type: cisco|shortcut|standard\n        :param int auto_cost_bandwidth: Mbits/s\n        :param bool deprecated_algorithm: RFC 1518 compatibility\n        :param int initial_delay: in milliseconds\n        :param int initial_hold_type: in milliseconds\n        :param int max_hold_time: in milliseconds\n        :param int shutdown_max_metric_lsa: in seconds\n        :param int startup_max_metric_lsa: in seconds\n        :raises CreateElementFailed: create failed with reason\n        :return: instance with meta\n        :rtype: OSPFDomainSetting"
  },
  {
    "code": "def tidy_eggs_list(eggs_list):\n    tmp = []\n    for line in eggs_list:\n        line = line.lstrip().rstrip()\n        line = line.replace('\\'', '')\n        line = line.replace(',', '')\n        if line.endswith('site-packages'):\n            continue\n        tmp.append(line)\n    return tmp",
    "docstring": "Tidy the given eggs list"
  },
  {
    "code": "def get_tracks(self):\n        return _extract_tracks(\n            self._request(self.ws_prefix + \".getInfo\", cacheable=True), self.network\n        )",
    "docstring": "Returns the list of Tracks on this album."
  },
  {
    "code": "async def _set_whitelist(self):\n        page = self.settings()\n        if 'whitelist' in page:\n            await self._send_to_messenger_profile(page, {\n                'whitelisted_domains': page['whitelist'],\n            })\n            logger.info('Whitelisted %s for page %s',\n                        page['whitelist'],\n                        page['page_id'])",
    "docstring": "Whitelist domains for the messenger extensions"
  },
  {
    "code": "def SXTB(self, params):\n        Ra, Rb = self.get_two_parameters(r'\\s*([^\\s,]*),\\s*([^\\s,]*)(,\\s*[^\\s,]*)*\\s*', params)\n        self.check_arguments(low_registers=(Ra, Rb))\n        def SXTB_func():\n            if self.register[Rb] & (1 << 7):\n                self.register[Ra] = 0xFFFFFF00 + (self.register[Rb] & 0xFF)\n            else:\n                self.register[Ra] = (self.register[Rb] & 0xFF)\n        return SXTB_func",
    "docstring": "STXB Ra, Rb\n\n        Sign extend the byte in Rb and store the result in Ra"
  },
  {
    "code": "def ensure_contiguity_in_observation_rows(obs_id_vector):\n    contiguity_check_array = (obs_id_vector[1:] - obs_id_vector[:-1]) >= 0\n    if not contiguity_check_array.all():\n        problem_ids = obs_id_vector[np.where(~contiguity_check_array)]\n        msg_1 = \"All rows pertaining to a given choice situation must be \"\n        msg_2 = \"contiguous. \\nRows pertaining to the following observation \"\n        msg_3 = \"id's are not contiguous: \\n{}\"\n        raise ValueError(msg_1 + msg_2 + msg_3.format(problem_ids.tolist()))\n    else:\n        return None",
    "docstring": "Ensures that all rows pertaining to a given choice situation are located\n    next to one another. Raises a helpful ValueError otherwise. This check is\n    needed because the hessian calculation function requires the design matrix\n    to have contiguity in rows with the same observation id.\n\n    Parameters\n    ----------\n    rows_to_obs : 2D scipy sparse array.\n        Should map each row of the long format dataferame to the unique\n        observations in the dataset.\n    obs_id_vector : 1D ndarray of ints.\n        Should contain the id (i.e. a unique integer) that corresponds to each\n        choice situation in the dataset.\n\n    Returns\n    -------\n    None."
  },
  {
    "code": "def dropna(self):\n        not_nas = [v.notna() for v in self.values]\n        and_filter = reduce(lambda x, y: x & y, not_nas)\n        return self[and_filter]",
    "docstring": "Returns MultiIndex without any rows containing null values according to Baloo's convention.\n\n        Returns\n        -------\n        MultiIndex\n            MultiIndex with no null values."
  },
  {
    "code": "def _emiss_ee(self, Eph):\n        if self.weight_ee == 0.0:\n            return np.zeros_like(Eph)\n        gam = np.vstack(self._gam)\n        emiss = c.cgs * trapz_loglog(\n            np.vstack(self._nelec) * self._sigma_ee(gam, Eph),\n            self._gam,\n            axis=0,\n        )\n        return emiss",
    "docstring": "Electron-electron bremsstrahlung emissivity per unit photon energy"
  },
  {
    "code": "def parse(self, argv):\n        kwargs, args = self.parse_args(argv)\n        self.result['args'] += args\n        for dest in self.dests:\n            value = getattr(kwargs, dest)\n            if value is not None:\n                self.result['kwargs'][dest] = value\n        return self",
    "docstring": "Parse the given argument vector."
  },
  {
    "code": "def run_command(args, asynchronous=False):\n    logging.info(\"Executing %s command %s.\",\n                 asynchronous and 'asynchronous' or 'synchronous', args)\n    process = subprocess.Popen(args,\n                               shell=True,\n                               stdout=subprocess.PIPE,\n                               stderr=subprocess.STDOUT)\n    try:\n        timeout = asynchronous and 1 or None\n        output = process.communicate(timeout=timeout)[0].decode('utf8')\n    except subprocess.TimeoutExpired:\n        pass\n    if asynchronous:\n        return PopenOutput(None, 'Asynchronous call.')\n    else:\n        return PopenOutput(process.returncode, output)",
    "docstring": "Executes a command returning its exit code and output."
  },
  {
    "code": "def mul(a, b):\n    if a is None:\n        if b is None:\n            return None\n        else:\n            return b\n    elif b is None:\n        return a\n    return a * b",
    "docstring": "Multiply two values, ignoring None"
  },
  {
    "code": "def save_list(lst, path):\n    with open(path, 'wb') as out:\n        lines = []\n        for item in lst:\n            if isinstance(item, (six.text_type, six.binary_type)):\n                lines.append(make_str(item))\n            else:\n                lines.append(make_str(json.dumps(item)))\n        out.write(b'\\n'.join(lines) + b'\\n')",
    "docstring": "Save items from list to the file."
  },
  {
    "code": "def _load_pickle(self, filename):\n        with open(filename, 'rb') as file_handle:\n            self._sensors.update(pickle.load(file_handle))",
    "docstring": "Load sensors from pickle file."
  },
  {
    "code": "def addToCommits(self, commit: Commit, sender: str):\n        self._bls_bft_replica.process_commit(commit, sender)\n        self.commits.addVote(commit, sender)\n        self.tryOrder(commit)",
    "docstring": "Add the specified COMMIT to this replica's list of received\n        commit requests.\n\n        :param commit: the COMMIT to add to the list\n        :param sender: the name of the node that sent the COMMIT"
  },
  {
    "code": "def SelectFieldPrompt(field_name, context_str, *options):\n    option_format_str = '[ {} ] \"{}\"'\n    option_dict = {}\n    print(context_str)\n    print('Please select one of the following options for field \"{}\"'.format(\n        field_name)\n    )\n    for cnt, option in enumerate(options):\n        option_dict['{}'.format(cnt + 1)] = option\n        if not callable(option):\n            print(option_format_str.format(cnt + 1, u(str(option))))\n        else:\n            print(option_format_str.format(cnt + 1, option.__name__))\n    choice = None\n    while choice not in option_dict:\n        choice = input('option> ').strip()\n    new_value = option_dict[choice]\n    if callable(new_value):\n        return new_value()\n    else:\n        return new_value",
    "docstring": "Prompts user to pick from provided options.\n\n    It is possible to provide a function as an option although it is\n    not yet tested.  This could allow a user to be prompted to provide\n    their own value rather than the listed options.\n\n    Args:\n      field_name (string): Name of the field.\n      context_str (string): Printed to give the user context.\n      options: Variable arguments, should be vobject Components\n          in a list. As retrieved from a vCard.contents dictionary.\n\n    Returns:\n        One of the options passed in.  Ideally always a list."
  },
  {
    "code": "def fit_var(self):\n        if self.activations_ is None:\n            raise RuntimeError(\"VAR fitting requires source activations (run do_mvarica first)\")\n        self.var_.fit(data=self.activations_[self.trial_mask_, :, :])\n        self.connectivity_ = Connectivity(self.var_.coef, self.var_.rescov, self.nfft_)\n        return self",
    "docstring": "Fit a VAR model to the source activations.\n\n        Returns\n        -------\n        self : Workspace\n            The Workspace object.\n\n        Raises\n        ------\n        RuntimeError\n            If the :class:`Workspace` instance does not contain source activations."
  },
  {
    "code": "def get_config(key):\n    key = 'AVATAR_{0}'.format(key.upper())\n    local_config = current_app.config.get(key)\n    return local_config or getattr(theme.current, key, DEFAULTS[key])",
    "docstring": "Get an identicon configuration parameter.\n\n    Precedance order is:\n        - application config (`udata.cfg`)\n        - theme config\n        - default"
  },
  {
    "code": "def _render_serializable(self, list_of_objs, context):\n        output = []\n        for obj in list_of_objs:\n            if obj is not None:\n                item = self._item_resource._render_serializable(obj, context)\n                output.append(item)\n        return output",
    "docstring": "Iterates through the passed in `list_of_objs` and calls the\n        `_render_serializable` method of each object's Resource type.\n\n        This will probably support heterogeneous types at some point (hence\n        the `item_types` initialization, as opposed to just item_type), but\n        that might be better suited to something else like a ResourceDict.\n\n        This method returns a JSON-serializable list of JSON-serializable\n        dicts."
  },
  {
    "code": "def copy(self):\n        o = SimLibrary()\n        o.procedures = dict(self.procedures)\n        o.non_returning = set(self.non_returning)\n        o.prototypes = dict(self.prototypes)\n        o.default_ccs = dict(self.default_ccs)\n        o.names = list(self.names)\n        return o",
    "docstring": "Make a copy of this SimLibrary, allowing it to be mutated without affecting the global version.\n\n        :return:    A new SimLibrary object with the same library references but different dict/list references"
  },
  {
    "code": "def public_decrypt(pub, message):\n    if HAS_M2:\n        return pub.public_decrypt(message, salt.utils.rsax931.RSA_X931_PADDING)\n    else:\n        verifier = salt.utils.rsax931.RSAX931Verifier(pub.exportKey('PEM'))\n        return verifier.verify(message)",
    "docstring": "Verify an M2Crypto-compatible signature\n\n    :param Crypto.PublicKey.RSA._RSAobj key: The RSA public key object\n    :param str message: The signed message to verify\n    :rtype: str\n    :return: The message (or digest) recovered from the signature, or an\n        empty string if the verification failed"
  },
  {
    "code": "def deleteResourceFile(self, pid, filename):\n        url = \"{url_base}/resource/{pid}/files/{filename}\".format(url_base=self.url_base,\n                                                                  pid=pid,\n                                                                  filename=filename)\n        r = self._request('DELETE', url)\n        if r.status_code != 200:\n            if r.status_code == 403:\n                raise HydroShareNotAuthorized(('DELETE', url))\n            elif r.status_code == 404:\n                raise HydroShareNotFound((pid, filename))\n            else:\n                raise HydroShareHTTPException((url, 'DELETE', r.status_code))\n        response = r.json()\n        assert(response['resource_id'] == pid)\n        return response['resource_id']",
    "docstring": "Delete a resource file\n\n        :param pid: The HydroShare ID of the resource\n        :param filename: String representing the name of the resource file to delete\n\n        :return: Dictionary containing 'resource_id' the ID of the resource from which the file was deleted, and\n            'file_name' the filename of the file deleted.\n\n        :raises: HydroShareNotAuthorized if user is not authorized to perform action.\n        :raises: HydroShareNotFound if the resource or resource file was not found.\n        :raises: HydroShareHTTPException if an unexpected HTTP response code is encountered."
  },
  {
    "code": "def get_coi(self, params_dict):\n        lat = str(params_dict['lat'])\n        lon = str(params_dict['lon'])\n        start = params_dict['start']\n        interval = params_dict['interval']\n        if start is None:\n            timeref = 'current'\n        else:\n            if interval is None:\n                timeref = self._trim_to(timeformatutils.to_date(start), 'year')\n            else:\n                timeref = self._trim_to(timeformatutils.to_date(start), interval)\n        fixed_url = '%s/%s,%s/%s.json' % (CO_INDEX_URL, lat, lon, timeref)\n        uri = http_client.HttpClient.to_url(fixed_url, self._API_key, None)\n        _, json_data = self._client.cacheable_get_json(uri)\n        return json_data",
    "docstring": "Invokes the CO Index endpoint\n\n        :param params_dict: dict of parameters\n        :returns: a string containing raw JSON data\n        :raises: *ValueError*, *APICallError*"
  },
  {
    "code": "def deploy(self, initial_instance_count, instance_type, accelerator_type=None, endpoint_name=None, **kwargs):\n        endpoint_name = endpoint_name or self.best_training_job()\n        best_estimator = self.estimator.attach(self.best_training_job(),\n                                               sagemaker_session=self.estimator.sagemaker_session)\n        return best_estimator.deploy(initial_instance_count, instance_type,\n                                     accelerator_type=accelerator_type,\n                                     endpoint_name=endpoint_name, **kwargs)",
    "docstring": "Deploy the best trained or user specified model to an Amazon SageMaker endpoint and return a\n        ``sagemaker.RealTimePredictor`` object.\n\n        For more information: http://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-training.html\n\n        Args:\n            initial_instance_count (int): Minimum number of EC2 instances to deploy to an endpoint for prediction.\n            instance_type (str): Type of EC2 instance to deploy to an endpoint for prediction,\n                for example, 'ml.c4.xlarge'.\n            accelerator_type (str): Type of Elastic Inference accelerator to attach to an endpoint for model loading\n                and inference, for example, 'ml.eia1.medium'. If not specified, no Elastic Inference accelerator\n                will be attached to the endpoint.\n                For more information: https://docs.aws.amazon.com/sagemaker/latest/dg/ei.html\n            endpoint_name (str): Name to use for creating an Amazon SageMaker endpoint. If not specified,\n                the name of the training job is used.\n            **kwargs: Other arguments needed for deployment. Please refer to the ``create_model()`` method of\n                the associated estimator to see what other arguments are needed.\n\n        Returns:\n            sagemaker.predictor.RealTimePredictor: A predictor that provides a ``predict()`` method,\n                which can be used to send requests to the Amazon SageMaker endpoint and obtain inferences."
  },
  {
    "code": "def _FilterOutPathInfoDuplicates(path_infos):\n  pi_dict = {}\n  for pi in path_infos:\n    path_key = (pi.path_type, pi.GetPathID())\n    pi_dict.setdefault(path_key, []).append(pi)\n  def _SortKey(pi):\n    return (\n        pi.stat_entry.st_ctime,\n        pi.stat_entry.st_mtime,\n        pi.stat_entry.st_atime,\n        pi.stat_entry.st_ino,\n    )\n  for pi_values in pi_dict.values():\n    if len(pi_values) > 1:\n      pi_values.sort(key=_SortKey, reverse=True)\n  return [v[0] for v in pi_dict.values()]",
    "docstring": "Filters out duplicates from passed PathInfo objects.\n\n  Args:\n    path_infos: An iterable with PathInfo objects.\n\n  Returns:\n    A list of PathInfo objects with duplicates removed. Duplicates are\n    removed following this logic: they're sorted by (ctime, mtime, atime,\n    inode number) in the descending order and then the first one is taken\n    and the others are dropped."
  },
  {
    "code": "def entry_point_name_to_identifier(entry_point_name):\n    try:\n        entry_point_name.encode('ascii')\n        ascii_name = entry_point_name\n    except UnicodeEncodeError:\n        ascii_name = entry_point_name.encode('punycode').decode('ascii')\n    return ''.join(char for char in ascii_name\n                   if char in string.ascii_lowercase + string.digits)",
    "docstring": "Transform an entry point name into an identifier suitable for inclusion\n    in a PyPI package name."
  },
  {
    "code": "def validate_experimental(context, param, value):\n    if value is None:\n        return\n    config = ExperimentConfiguration(value)\n    config.validate()\n    return config",
    "docstring": "Load and validate an experimental data configuration."
  },
  {
    "code": "def update_version(self, service_id, version_number, **kwargs):\n\t\tbody = self._formdata(kwargs, FastlyVersion.FIELDS)\n\t\tcontent = self._fetch(\"/service/%s/version/%d/\" % (service_id, version_number), method=\"PUT\", body=body)\n\t\treturn FastlyVersion(self, content)",
    "docstring": "Update a particular version for a particular service."
  },
  {
    "code": "def assume(self, other):\n        self._arch = other._arch\n        self._bits = other._bits\n        self._endian = other._endian\n        self._mode = other._mode",
    "docstring": "Assume the identity of another target. This can be useful to make the\n        global target assume the identity of an ELF executable.\n\n        Arguments:\n            other(:class:`Target`): The target whose identity to assume.\n\n        Example:\n            >>> from pwny import *\n            >>> target.assume(ELF('my-executable'))"
  },
  {
    "code": "def unpickle_file(picklefile, **kwargs):\n    with open(picklefile, 'rb') as f:\n        return pickle.load(f, **kwargs)",
    "docstring": "Helper function to unpickle data from `picklefile`."
  },
  {
    "code": "async def send_rpc_command(self, short_name, rpc_id, payload, sender_client, timeout=1.0):\n        rpc_tag = str(uuid.uuid4())\n        self.rpc_results.declare(rpc_tag)\n        if short_name in self.services and short_name in self.agents:\n            agent_tag = self.agents[short_name]\n            rpc_message = {\n                'rpc_id': rpc_id,\n                'payload': payload,\n                'response_uuid': rpc_tag\n            }\n            self.in_flight_rpcs[rpc_tag] = InFlightRPC(sender_client, short_name,\n                                                       monotonic(), timeout)\n            await self._notify_update(short_name, 'rpc_command', rpc_message, directed_client=agent_tag)\n        else:\n            response = dict(result='service_not_found', response=b'')\n            self.rpc_results.set(rpc_tag, response)\n        return rpc_tag",
    "docstring": "Send an RPC to a service using its registered agent.\n\n        Args:\n            short_name (str): The name of the service we would like to send\n                and RPC to\n            rpc_id (int): The rpc id that we would like to call\n            payload (bytes): The raw bytes that we would like to send as an\n                argument\n            sender_client (str): The uuid of the sending client\n            timeout (float): The maximum number of seconds before we signal a timeout\n                of the RPC\n\n        Returns:\n            str: A unique id that can used to identify the notified response of this\n                RPC."
  },
  {
    "code": "def add(self, original_index, operation):\n        self.index_map.append(original_index)\n        self.ops.append(operation)",
    "docstring": "Add an operation to this Run instance.\n\n        :Parameters:\n          - `original_index`: The original index of this operation\n            within a larger bulk operation.\n          - `operation`: The operation document."
  },
  {
    "code": "def _convert_to_indexer(self, obj, axis=None, is_setter=False):\n        if axis is None:\n            axis = self.axis or 0\n        if isinstance(obj, slice):\n            return self._convert_slice_indexer(obj, axis)\n        elif is_float(obj):\n            return self._convert_scalar_indexer(obj, axis)\n        try:\n            self._validate_key(obj, axis)\n            return obj\n        except ValueError:\n            raise ValueError(\"Can only index by location with \"\n                             \"a [{types}]\".format(types=self._valid_types))",
    "docstring": "much simpler as we only have to deal with our valid types"
  },
  {
    "code": "def request_network_status(blink, network):\n    url = \"{}/network/{}\".format(blink.urls.base_url, network)\n    return http_get(blink, url)",
    "docstring": "Request network information.\n\n    :param blink: Blink instance.\n    :param network: Sync module network id."
  },
  {
    "code": "def refill_main_wallet(self, from_address, to_address, nfees, ntokens, password, min_confirmations=6, sync=False):\n        path, from_address = from_address\n        unsigned_tx = self._t.simple_transaction(from_address,\n                                                 [(to_address, self.fee)] * nfees + [(to_address, self.token)] * ntokens,\n                                                 min_confirmations=min_confirmations)\n        signed_tx = self._t.sign_transaction(unsigned_tx, password)\n        txid = self._t.push(signed_tx)\n        return txid",
    "docstring": "Refill the Federation wallet with tokens and fees. This keeps the federation wallet clean.\n        Dealing with exact values simplifies the transactions. No need to calculate change. Easier to keep track of the\n        unspents and prevent double spends that would result in transactions being rejected by the bitcoin network.\n\n        Args:\n\n            from_address (Tuple[str]): Refill wallet address. Refills the federation wallet with tokens and fees\n            to_address (str): Federation wallet address\n            nfees (int): Number of fees to transfer. Each fee is 10000 satoshi. Used to pay for the transactions\n            ntokens (int): Number of tokens to transfer. Each token is 600 satoshi. Used to register hashes in the blockchain\n            password (str): Password for the Refill wallet. Used to sign the transaction\n            min_confirmations (int): Number of confirmations when chosing the inputs of the transaction. Defaults to 6\n            sync (bool): Perform the transaction in synchronous mode, the call to the function will block until there is at\n                least on confirmation on the blockchain. Defaults to False\n\n        Returns:\n            str: transaction id"
  },
  {
    "code": "def get_split_adjusted_asof_idx(self, dates):\n        split_adjusted_asof_idx = dates.searchsorted(\n            self._split_adjusted_asof\n        )\n        if split_adjusted_asof_idx == len(dates):\n            split_adjusted_asof_idx = len(dates) - 1\n        elif self._split_adjusted_asof < dates[0].tz_localize(None):\n            split_adjusted_asof_idx = -1\n        return split_adjusted_asof_idx",
    "docstring": "Compute the index in `dates` where the split-adjusted-asof-date\n        falls. This is the date up to which, and including which, we will\n        need to unapply all adjustments for and then re-apply them as they\n        come in. After this date, adjustments are applied as normal.\n\n        Parameters\n        ----------\n        dates : pd.DatetimeIndex\n            The calendar dates over which the Pipeline is being computed.\n\n        Returns\n        -------\n        split_adjusted_asof_idx : int\n            The index in `dates` at which the data should be split."
  },
  {
    "code": "def get_channel_node_from_json(json_tree):\n    channel = ChannelNode(\n        title=json_tree['title'],\n        description=json_tree['description'],\n        source_domain=json_tree['source_domain'],\n        source_id=json_tree['source_id'],\n        language=json_tree['language'],\n        thumbnail=json_tree.get('thumbnail', None),\n    )\n    return channel",
    "docstring": "Build `ChannelNode` from json data provided in `json_tree`."
  },
  {
    "code": "def specfn_quant_generator(specfiles, quantfiles, tag, ignore_tags):\n    for specfn, qfn in zip(specfiles, quantfiles):\n        for quant_el in basereader.generate_xmltags(qfn, tag, ignore_tags):\n            yield os.path.basename(specfn), quant_el",
    "docstring": "Generates tuples of specfile and quant element for general formats"
  },
  {
    "code": "def clean_value(self, value):\n    if self._clean_value:\n      return self._clean_value(value)\n    else:\n      return self.reduce_value(value)",
    "docstring": "Cleans a value, using either the user provided clean_value, or cls.reduce_value."
  },
  {
    "code": "def create_organization(self, auth, owner_name, org_name, full_name=None, description=None,\n                            website=None, location=None):\n        data = {\n            \"username\": org_name,\n            \"full_name\": full_name,\n            \"description\": description,\n            \"website\": website,\n            \"location\": location\n        }\n        url = \"/admin/users/{u}/orgs\".format(u=owner_name)\n        response = self.post(url, auth=auth, data=data)\n        return GogsOrg.from_json(response.json())",
    "docstring": "Creates a new organization, and returns the created organization.\n\n        :param auth.Authentication auth: authentication object, must be admin-level\n        :param str owner_name: Username of organization owner\n        :param str org_name: Organization name\n        :param str full_name: Full name of organization \n        :param str description: Description of the organization\n        :param str website: Official website\n        :param str location: Organization location\n        :return: a representation of the created organization\n        :rtype: GogsOrg\n        :raises NetworkFailure: if there is an error communicating with the server\n        :raises ApiFailure: if the request cannot be serviced"
  },
  {
    "code": "def chunk(self, maxSize):\n        chunks = []\n        currentSize = maxSize + 1\n        for i in self:\n            if currentSize >= maxSize:\n                currentSize = 0\n                chunks.append(type(self)({i}, name = 'Chunk-{}-of-{}'.format(len(chunks), self.name), quietStart = True))\n            else:\n                chunks[-1].add(i)\n            currentSize += 1\n        return chunks",
    "docstring": "Splits the `Collection` into _maxSize_ size or smaller `Collections`\n\n        # Parameters\n\n        _maxSize_ : `int`\n\n        > The maximum number of elements in a retuned `Collection`\n\n\n        # Returns\n\n        `list [Collection]`\n\n        > A list of `Collections` that if all merged (`|` operator) would create the original"
  },
  {
    "code": "def from_string(input_str) -> 'MissionTime':\n        match = RE_INPUT_STRING.match(input_str)\n        if not match:\n            raise ValueError(f'badly formatted date/time: {input_str}')\n        return MissionTime(\n            datetime.datetime(\n                int(match.group('year')),\n                int(match.group('month')),\n                int(match.group('day')),\n                int(match.group('hour')),\n                int(match.group('minute')),\n                int(match.group('second')),\n            )\n        )",
    "docstring": "Creates a MissionTime instance from a string\n\n        Format: YYYYMMDDHHMMSS\n\n        Args:\n            input_str: string to parse\n\n        Returns: MissionTime instance"
  },
  {
    "code": "def collection_names(self, callback):\n        callback = partial(self._collection_names_result, callback)\n        self[\"system.namespaces\"].find(_must_use_master=True, callback=callback)",
    "docstring": "Get a list of all the collection names in selected database"
  },
  {
    "code": "def setup(self):\n        self.radiation_count = 0\n        self.noise_count = 0\n        self.count = 0\n        self.count_history = [0] * HISTORY_LENGTH\n        self.history_index = 0\n        self.previous_time = millis()\n        self.previous_history_time = millis()\n        self.duration = 0\n        GPIO.setup(self.radiation_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n        GPIO.setup(self.noise_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n        GPIO.add_event_detect(\n            self.radiation_pin, GPIO.FALLING, callback=self._on_radiation\n        )\n        GPIO.add_event_detect(self.noise_pin, GPIO.FALLING, callback=self._on_noise)\n        self._enable_timer()\n        return self",
    "docstring": "Initialize the driver by setting up GPIO interrupts\n        and periodic statistics processing."
  },
  {
    "code": "def load_pyfile(self, path):\n        with open(path) as config_file:\n            contents = config_file.read()\n            try:\n                exec(compile(contents, path, 'exec'), self)\n            except Exception as e:\n                raise MalformedConfig(path, six.text_type(e))",
    "docstring": "Load python file as config.\n\n        Args:\n            path (string): path to the python file"
  },
  {
    "code": "def apply_patch(self, patch):\n        history_file = File(self.__history_file)\n        patches_history = history_file.cache() and [line.strip() for line in history_file.content] or []\n        if patch.uid not in patches_history:\n            LOGGER.debug(\"> Applying '{0}' patch!\".format(patch.name))\n            if patch.apply():\n                history_file.content = [\"{0}\\n\".format(patch.uid)]\n                history_file.append()\n            else:\n                raise umbra.exceptions.PatchApplyError(\"{0} | '{1}' patch failed to apply!\".format(\n                    self.__class__.__name__, patch.path))\n        else:\n            LOGGER.debug(\"> '{0}' patch is already applied!\".format(patch.name))\n        return True",
    "docstring": "Applies given patch.\n\n        :param patch: Patch.\n        :type patch: Patch\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def debug(self, msg):\n        if self.__debug is not False:\n            if self.__debug is None:\n                debug_filename = getattr(settings, \"AD_DEBUG_FILE\", None)\n                if debug_filename:\n                    self.__debug = open(settings.AD_DEBUG_FILE, 'a')\n                else:\n                    self.__debug = False\n            if self.__debug:\n                self.__debug.write(\"{}\\n\".format(msg))\n                self.__debug.flush()",
    "docstring": "Handle the debugging to a file"
  },
  {
    "code": "def _tuplefy_namespace(self, namespace):\n        namespace_split = namespace.split('.', 1)\n        if len(namespace_split) is 1:\n            namespace_tuple = ('*', namespace_split[0])\n        elif len(namespace_split) is 2:\n            namespace_tuple = (namespace_split[0],namespace_split[1])\n        else:\n            return None\n        return namespace_tuple",
    "docstring": "Converts a mongodb namespace to a db, collection tuple"
  },
  {
    "code": "def stop(self):\n        with self.__receiver_thread_exit_condition:\n            while not self.__receiver_thread_exited and self.is_connected():\n                self.__receiver_thread_exit_condition.wait()",
    "docstring": "Stop the connection. Performs a clean shutdown by waiting for the\n        receiver thread to exit."
  },
  {
    "code": "def get_splits_query(self):\n        query = (\n            self.book.session.query(Split)\n            .filter(Split.transaction_guid == self.transaction.guid)\n        )\n        return query",
    "docstring": "Returns the query for related splits"
  },
  {
    "code": "def used_args(self):\n        values = []\n        for idx, c in enumerate(self.words[1:]):\n            if c.startswith('-'):\n                continue\n            option_str = self.words[1:][idx - 1]\n            option = self.get_option(option_str)\n            if option is None or not option.need_value:\n                values.append((c, c == self.document.get_word_before_cursor(WORD=True)))\n        logger.debug(\"Found args values %s\" % values)\n        for arg in self.cmd.args.values():\n            if not values:\n                raise StopIteration\n            if arg.is_multiple:\n                values = []\n                yield arg\n            elif type(arg.nargs) is int:\n                for _ in range(arg.nargs):\n                    value = values.pop(0)\n                    if value[1] is False:\n                        yield arg\n                    if not values:\n                        raise StopIteration",
    "docstring": "Return args already used in the\n        command line\n\n        rtype: command.Arg generator"
  },
  {
    "code": "def ensure_newline(self):\n        DECTCEM_SHOW = '\\033[?25h'\n        AT_END = DECTCEM_SHOW + '\\n'\n        if not self._cursor_at_newline:\n            self.write(AT_END)\n            self._cursor_at_newline = True",
    "docstring": "use before any custom printing when using the progress iter to ensure\n        your print statement starts on a new line instead of at the end of a\n        progress line"
  },
  {
    "code": "def listLastFires(self, *args, **kwargs):\n        return self._makeApiCall(self.funcinfo[\"listLastFires\"], *args, **kwargs)",
    "docstring": "Get information about recent hook fires\n\n        This endpoint will return information about the the last few times this hook has been\n        fired, including whether the hook was fired successfully or not\n\n        This method gives output: ``v1/list-lastFires-response.json#``\n\n        This method is ``experimental``"
  },
  {
    "code": "def _is_container_excluded(self, container):\n        container_name = DockerUtil.container_name_extractor(container)[0]\n        return container_name in self._filtered_containers",
    "docstring": "Check if a container is excluded according to the filter rules.\n\n        Requires _filter_containers to run first."
  },
  {
    "code": "def get_site_t2g_eg_resolved_dos(self, site):\n        t2g_dos = []\n        eg_dos = []\n        for s, atom_dos in self.pdos.items():\n            if s == site:\n                for orb, pdos in atom_dos.items():\n                    if orb in (Orbital.dxy, Orbital.dxz, Orbital.dyz):\n                        t2g_dos.append(pdos)\n                    elif orb in (Orbital.dx2, Orbital.dz2):\n                        eg_dos.append(pdos)\n        return {\"t2g\": Dos(self.efermi, self.energies,\n                           functools.reduce(add_densities, t2g_dos)),\n                \"e_g\": Dos(self.efermi, self.energies,\n                           functools.reduce(add_densities, eg_dos))}",
    "docstring": "Get the t2g, eg projected DOS for a particular site.\n\n        Args:\n            site: Site in Structure associated with CompleteDos.\n\n        Returns:\n            A dict {\"e_g\": Dos, \"t2g\": Dos} containing summed e_g and t2g DOS\n            for the site."
  },
  {
    "code": "def _type_digest(self, config: bool) -> Dict[str, Any]:\n        res = {\"base\": self.yang_type()}\n        if self.name is not None:\n            res[\"derived\"] = self.name\n        return res",
    "docstring": "Return receiver's type digest.\n\n        Args:\n            config: Specifies whether the type is on a configuration node."
  },
  {
    "code": "def get_defs(self, position=None):\n        if position is None:\n            position = self.position\n        return self.checkdefs[position][1]",
    "docstring": "Gets the defs at the position."
  },
  {
    "code": "def unit_of_work(metadata=None, timeout=None):\n    def wrapper(f):\n        def wrapped(*args, **kwargs):\n            return f(*args, **kwargs)\n        wrapped.metadata = metadata\n        wrapped.timeout = timeout\n        return wrapped\n    return wrapper",
    "docstring": "This function is a decorator for transaction functions that allows\n    extra control over how the transaction is carried out.\n\n    For example, a timeout (in seconds) may be applied::\n\n        @unit_of_work(timeout=25.0)\n        def count_people(tx):\n            return tx.run(\"MATCH (a:Person) RETURN count(a)\").single().value()"
  },
  {
    "code": "def scheduled_sample_count(ground_truth_x,\n                           generated_x,\n                           batch_size,\n                           scheduled_sample_var):\n  num_ground_truth = scheduled_sample_var\n  idx = tf.random_shuffle(tf.range(batch_size))\n  ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth))\n  generated_idx = tf.gather(idx, tf.range(num_ground_truth, batch_size))\n  ground_truth_examps = tf.gather(ground_truth_x, ground_truth_idx)\n  generated_examps = tf.gather(generated_x, generated_idx)\n  output = tf.dynamic_stitch([ground_truth_idx, generated_idx],\n                             [ground_truth_examps, generated_examps])\n  if isinstance(batch_size, int):\n    output.set_shape([batch_size] + common_layers.shape_list(output)[1:])\n  return output",
    "docstring": "Sample batch with specified mix of groundtruth and generated data points.\n\n  Args:\n    ground_truth_x: tensor of ground-truth data points.\n    generated_x: tensor of generated data points.\n    batch_size: batch size\n    scheduled_sample_var: number of ground-truth examples to include in batch.\n  Returns:\n    New batch with num_ground_truth sampled from ground_truth_x and the rest\n    from generated_x."
  },
  {
    "code": "def get_permission_usage(self, permission, apilevel=None):\n        permmap = load_api_specific_resource_module('api_permission_mappings', apilevel)\n        if not permmap:\n            raise ValueError(\"No permission mapping found! Is one available? \"\n                             \"The requested API level was '{}'\".format(apilevel))\n        apis = {k for k, v in permmap.items() if permission in v}\n        if not apis:\n            raise ValueError(\"No API methods could be found which use the permission. \"\n                             \"Does the permission exists? You requested: '{}'\".format(permission))\n        for cls in self.get_external_classes():\n            for meth_analysis in cls.get_methods():\n                meth = meth_analysis.get_method()\n                if meth.permission_api_name in apis:\n                    yield meth_analysis",
    "docstring": "Find the usage of a permission inside the Analysis.\n\n        example::\n            from androguard.misc import AnalyzeAPK\n            a, d, dx = AnalyzeAPK(\"somefile.apk\")\n\n            for meth in dx.get_permission_usage('android.permission.SEND_SMS', a.get_effective_target_sdk_version()):\n                print(\"Using API method {}\".format(meth))\n                print(\"used in:\")\n                for _, m, _ in meth.get_xref_from():\n                    print(m.full_name)\n\n        .. note::\n            The permission mappings might be incomplete! See also :meth:`get_permissions`.\n\n        :param permission: the name of the android permission (usually 'android.permission.XXX')\n        :param apilevel: the requested API level or None for default\n        :return: yields :class:`MethodClassAnalysis` objects for all using API methods"
  },
  {
    "code": "def match(tgt, opts=None):\n    if not opts:\n        opts = __opts__\n    try:\n        if ',' + opts['id'] + ',' in tgt \\\n                or tgt.startswith(opts['id'] + ',') \\\n                or tgt.endswith(',' + opts['id']):\n            return True\n        return opts['id'] == tgt\n    except (AttributeError, TypeError):\n        try:\n            return opts['id'] in tgt\n        except Exception:\n            return False\n    log.warning(\n        'List matcher unexpectedly did not return, for target %s, '\n        'this is probably a bug.', tgt\n    )\n    return False",
    "docstring": "Determines if this host is on the list"
  },
  {
    "code": "def __list_fields(cls):\n        for name in cls._doc_type.mapping:\n            field = cls._doc_type.mapping[name]\n            yield name, field, False\n        if hasattr(cls.__class__, '_index'):\n            if not cls._index._mapping:\n                return\n            for name in cls._index._mapping:\n                if name in cls._doc_type.mapping:\n                    continue\n                field = cls._index._mapping[name]\n                yield name, field, True",
    "docstring": "Get all the fields defined for our class, if we have an Index, try\n        looking at the index mappings as well, mark the fields from Index as\n        optional."
  },
  {
    "code": "def dsort(self, order):\n        r\n        order = order if isinstance(order, list) else [order]\n        norder = [{item: \"A\"} if not isinstance(item, dict) else item for item in order]\n        self._in_header([list(item.keys())[0] for item in norder])\n        clist = []\n        for nitem in norder:\n            for key, value in nitem.items():\n                clist.append(\n                    (\n                        key\n                        if isinstance(key, int)\n                        else self._header_upper.index(key.upper()),\n                        value.upper() == \"D\",\n                    )\n                )\n        for (cindex, rvalue) in reversed(clist):\n            fpointer = operator.itemgetter(cindex)\n            self._data.sort(key=fpointer, reverse=rvalue)",
    "docstring": "r\"\"\"\n        Sort rows.\n\n        :param order: Sort order\n        :type  order: :ref:`CsvColFilter`\n\n        .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]]\n        .. Auto-generated exceptions documentation for\n        .. pcsv.csv_file.CsvFile.dsort\n\n        :raises:\n         * RuntimeError (Argument \\`order\\` is not valid)\n\n         * RuntimeError (Invalid column specification)\n\n         * ValueError (Column *[column_identifier]* not found)\n\n        .. [[[end]]]"
  },
  {
    "code": "def med_filt(x, k=201):\n    if x.ndim > 1:\n        x = np.squeeze(x)\n    med = np.median(x)\n    assert k % 2 == 1, \"Median filter length must be odd.\"\n    assert x.ndim == 1, \"Input must be one-dimensional.\"\n    k2 = (k - 1) // 2\n    y = np.zeros((len(x), k), dtype=x.dtype)\n    y[:, k2] = x\n    for i in range(k2):\n        j = k2 - i\n        y[j:, i] = x[:-j]\n        y[:j, i] = x[0]\n        y[:-j, -(i + 1)] = x[j:]\n        y[-j:, -(i + 1)] = med\n    return np.median(y, axis=1)",
    "docstring": "Apply a length-k median filter to a 1D array x.\n    Boundaries are extended by repeating endpoints."
  },
  {
    "code": "def lons(self, degrees=True):\n        if degrees is False:\n            return _np.radians(self._lons())\n        else:\n            return self._lons()",
    "docstring": "Return the longitudes of each column of the gridded data.\n\n        Usage\n        -----\n        lons = x.get_lon([degrees])\n\n        Returns\n        -------\n        lons : ndarray, shape (nlon)\n            1-D numpy array of size nlon containing the longitude of each row\n            of the gridded data.\n\n        Parameters\n        -------\n        degrees : bool, optional, default = True\n            If True, the output will be in degrees. If False, the output will\n            be in radians."
  },
  {
    "code": "def merge_segments(segments, exif=b\"\"):\n    if segments[1][0:2] == b\"\\xff\\xe0\" and \\\n       segments[2][0:2] == b\"\\xff\\xe1\" and \\\n       segments[2][4:10] == b\"Exif\\x00\\x00\":\n        if exif:\n            segments[2] = exif\n            segments.pop(1)\n        elif exif is None:\n            segments.pop(2)\n        else:\n            segments.pop(1)\n    elif segments[1][0:2] == b\"\\xff\\xe0\":\n        if exif:\n            segments[1] = exif\n    elif segments[1][0:2] == b\"\\xff\\xe1\" and \\\n         segments[1][4:10] == b\"Exif\\x00\\x00\":\n        if exif:\n            segments[1] = exif\n        elif exif is None:\n            segments.pop(1)\n    else:\n        if exif:\n            segments.insert(1, exif)\n    return b\"\".join(segments)",
    "docstring": "Merges Exif with APP0 and APP1 manipulations."
  },
  {
    "code": "def _proc_accept_header(self, request, result):\n        if result:\n            return\n        try:\n            accept = request.headers['accept']\n        except KeyError:\n            return\n        ctype, params = best_match(accept, self.types.keys())\n        if ctype not in self.types:\n            return\n        mapped_ctype, mapped_version = self.types[ctype](params)\n        if mapped_ctype:\n            result.set_ctype(mapped_ctype, ctype)\n        if mapped_version:\n            result.set_version(mapped_version)",
    "docstring": "Process the Accept header rules for the request.  Both the\n        desired API version and content type can be determined from\n        those rules.\n\n        :param request: The Request object provided by WebOb.\n        :param result: The Result object to store the results in."
  },
  {
    "code": "def send_stun(self, message, addr):\n        logger.debug('%s > %s %s', self, addr, message)\n        self._send(bytes(message))",
    "docstring": "Send a STUN message to the TURN server."
  },
  {
    "code": "def cdna_codon_sequence_after_insertion_frameshift(\n        sequence_from_start_codon,\n        cds_offset_before_insertion,\n        inserted_nucleotides):\n    coding_sequence_after_insertion = \\\n        sequence_from_start_codon[cds_offset_before_insertion + 1:]\n    if cds_offset_before_insertion % 3 == 2:\n        mutated_codon_index = cds_offset_before_insertion // 3 + 1\n        nucleotides_before = \"\"\n    elif cds_offset_before_insertion % 3 == 1:\n        mutated_codon_index = cds_offset_before_insertion // 3\n        nucleotides_before = sequence_from_start_codon[\n            cds_offset_before_insertion - 1:cds_offset_before_insertion + 1]\n    elif cds_offset_before_insertion % 3 == 0:\n        mutated_codon_index = cds_offset_before_insertion // 3\n        nucleotides_before = sequence_from_start_codon[cds_offset_before_insertion]\n    sequence_from_mutated_codon = (\n        nucleotides_before +\n        inserted_nucleotides +\n        coding_sequence_after_insertion)\n    return mutated_codon_index, sequence_from_mutated_codon",
    "docstring": "Returns index of mutated codon and nucleotide sequence starting at the first\n    mutated codon."
  },
  {
    "code": "def uuid(self, **params):\n        digest = str(uuidlib.uuid4()).replace('-', '')\n        return self.humanize(digest, **params), digest",
    "docstring": "Generate a UUID with a human-readable representation.\n\n        Returns `(human_repr, full_digest)`. Accepts the same keyword arguments\n        as :meth:`humanize` (they'll be passed straight through)."
  },
  {
    "code": "def add_done_callback(self, fn):\n        with self._condition:\n            if self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]:\n                self._done_callbacks.append(fn)\n                return\n        fn(self)",
    "docstring": "Attaches a callable that will be called when the future finishes.\n\n        Args:\n            fn: A callable that will be called with this future as its only\n                argument when the future completes or is cancelled. The callable\n                will always be called by a thread in the same process in which\n                it was added. If the future has already completed or been\n                cancelled then the callable will be called immediately. These\n                callables are called in the order that they were added."
  },
  {
    "code": "def model_vis(self, context):\n        column = self._vis_column\n        msshape = None\n        try:\n            coldesc = self._manager.column_descriptors[column]\n        except KeyError as e:\n            coldesc = None\n        if coldesc is not None:\n            try:\n                msshape = [-1] + coldesc['shape'].tolist()\n            except KeyError as e:\n                msshape = None\n        if msshape is None:\n            guessed_shape = [self._manager._nchan, 4]\n            montblanc.log.warn(\"Could not obtain 'shape' from the '{c}' \"\n                \"column descriptor. Guessing it is '{gs}'.\".format(\n                    c=column, gs=guessed_shape))\n            msshape = [-1] + guessed_shape\n        lrow, urow = MS.row_extents(context)\n        self._manager.ordered_main_table.putcol(column,\n            context.data.reshape(msshape),\n            startrow=lrow, nrow=urow-lrow)",
    "docstring": "model visibility data sink"
  },
  {
    "code": "def __create_profile(self, profile, uuid, verbose):\n        kw = profile.to_dict()\n        kw['country_code'] = profile.country_code\n        kw.pop('uuid')\n        kw.pop('country')\n        api.edit_profile(self.db, uuid, **kw)\n        self.log(\"-- profile %s updated\" % uuid, verbose)",
    "docstring": "Create profile information from a profile object"
  },
  {
    "code": "def save_save_state(self, data_dict: Dict[str, LinkItem]):\n        json_data = json_format.MessageToJson(self._create_save_state(data_dict).to_protobuf())\n        with self._save_state_file.open(mode='w', encoding=\"utf8\") as writer:\n            writer.write(json_data)",
    "docstring": "Save meta data about the downloaded things and the plugin to file.\n\n        :param data_dict: data\n        :type data_dict: Dict[link, ~unidown.plugin.link_item.LinkItem]"
  },
  {
    "code": "def verifyZeroInteractions(*objs):\n    for obj in objs:\n        theMock = _get_mock_or_raise(obj)\n        if len(theMock.invocations) > 0:\n            raise VerificationError(\n                \"\\nUnwanted interaction: %s\" % theMock.invocations[0])",
    "docstring": "Verify that no methods have been called on given objs.\n\n    Note that strict mocks usually throw early on unexpected, unstubbed\n    invocations. Partial mocks ('monkeypatched' objects or modules) do not\n    support this functionality at all, bc only for the stubbed invocations\n    the actual usage gets recorded. So this function is of limited use,\n    nowadays."
  },
  {
    "code": "def scard(incard, cell):\n    assert isinstance(cell, stypes.SpiceCell)\n    incard = ctypes.c_int(incard)\n    libspice.scard_c(incard, ctypes.byref(cell))\n    return cell",
    "docstring": "Set the cardinality of a SPICE cell of any data type.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scard_c.html\n\n    :param incard: Cardinality of (number of elements in) the cell.\n    :type incard: int\n    :param cell: The cell.\n    :type cell: spiceypy.utils.support_types.SpiceCell\n    :return: The updated Cell.\n    :rtype: spiceypy.utils.support_types.SpiceCell"
  },
  {
    "code": "def delete_namespace(parsed_xml):\n    if parsed_xml.getroot().tag.startswith('{'):\n        root = parsed_xml.getroot().tag\n        end_ns = root.find('}')\n        remove_namespace(parsed_xml, root[1:end_ns])\n    return parsed_xml",
    "docstring": "Identifies the namespace associated with the root node of a XML document\n    and removes that names from the document.\n\n    :param parsed_xml: lxml.Etree object.\n    :return: Returns the sources document with the namespace removed."
  },
  {
    "code": "def show_firewall(self, firewall, **_params):\n        return self.get(self.firewall_path % (firewall), params=_params)",
    "docstring": "Fetches information of a certain firewall."
  },
  {
    "code": "def print_tally(self):\n        self.update_count = self.upload_count - self.create_count\n        if self.test_run:\n            print(\"Test run complete with the following results:\")\n        print(\"Skipped {0}. Created {1}. Updated {2}. Deleted {3}.\".format(\n            self.skip_count, self.create_count, self.update_count, self.delete_count))",
    "docstring": "Prints the final tally to stdout."
  },
  {
    "code": "def getOverlaySortOrder(self, ulOverlayHandle):\n        fn = self.function_table.getOverlaySortOrder\n        punSortOrder = c_uint32()\n        result = fn(ulOverlayHandle, byref(punSortOrder))\n        return result, punSortOrder.value",
    "docstring": "Gets the sort order of the overlay. See SetOverlaySortOrder for how this works."
  },
  {
    "code": "def distance_color_labels(labels):\n    colors = color_labels(labels, True)\n    rlabels = labels.ravel()\n    order = np.lexsort((rlabels, colors.ravel()))\n    different = np.hstack([[rlabels[order[0]] > 0],\n                           rlabels[order[1:]] != rlabels[order[:-1]]])\n    rcolor = colors.ravel()\n    rcolor[order] = np.cumsum(different).astype(colors.dtype)\n    return rcolor.reshape(colors.shape).astype(labels.dtype)",
    "docstring": "Recolor a labels matrix so that adjacent labels have distant numbers"
  },
  {
    "code": "def get_cytoband_map(name):\n    fn = pkg_resources.resource_filename(\n        __name__, _data_path_fmt.format(name=name))\n    return json.load(gzip.open(fn, mode=\"rt\", encoding=\"utf-8\"))",
    "docstring": "Fetch one cytoband map by name\n\n    >>> map = get_cytoband_map(\"ucsc-hg38\")\n    >>> map[\"1\"][\"p32.2\"]\n    [55600000, 58500000, 'gpos50']"
  },
  {
    "code": "def email_embed_image(email, img_content_id, img_data):\n    img = MIMEImage(img_data)\n    img.add_header('Content-ID', '<%s>' % img_content_id)\n    img.add_header('Content-Disposition', 'inline')\n    email.attach(img)",
    "docstring": "email is a django.core.mail.EmailMessage object"
  },
  {
    "code": "def _get_common_params(self, user_id, attributes):\n    commonParams = {}\n    commonParams[self.EventParams.PROJECT_ID] = self._get_project_id()\n    commonParams[self.EventParams.ACCOUNT_ID] = self._get_account_id()\n    visitor = {}\n    visitor[self.EventParams.END_USER_ID] = user_id\n    visitor[self.EventParams.SNAPSHOTS] = []\n    commonParams[self.EventParams.USERS] = []\n    commonParams[self.EventParams.USERS].append(visitor)\n    commonParams[self.EventParams.USERS][0][self.EventParams.ATTRIBUTES] = self._get_attributes(attributes)\n    commonParams[self.EventParams.SOURCE_SDK_TYPE] = 'python-sdk'\n    commonParams[self.EventParams.ENRICH_DECISIONS] = True\n    commonParams[self.EventParams.SOURCE_SDK_VERSION] = version.__version__\n    commonParams[self.EventParams.ANONYMIZE_IP] = self._get_anonymize_ip()\n    commonParams[self.EventParams.REVISION] = self._get_revision()\n    return commonParams",
    "docstring": "Get params which are used same in both conversion and impression events.\n\n    Args:\n      user_id: ID for user.\n      attributes: Dict representing user attributes and values which need to be recorded.\n\n    Returns:\n     Dict consisting of parameters common to both impression and conversion events."
  },
  {
    "code": "def fprint(self, obj, stream=None, **kwargs):\n        if stream is None:\n            stream = sys.stdout\n        options = self.options\n        options.update(kwargs)\n        if isinstance(obj, dimod.SampleSet):\n            self._print_sampleset(obj, stream, **options)\n            return\n        raise TypeError(\"cannot format type {}\".format(type(obj)))",
    "docstring": "Prints the formatted representation of the object on stream"
  },
  {
    "code": "def view_class2(self, fatherid=''):\n        if self.is_admin():\n            pass\n        else:\n            return False\n        kwd = {'class1str': self.format_class2(fatherid),\n               'parentid': '0',\n               'parentlist': MCategory.get_parent_list()}\n        if fatherid.endswith('00'):\n            self.render('misc/publish/publish2.html',\n                        userinfo=self.userinfo,\n                        kwd=kwd)\n        else:\n            catinfo = MCategory.get_by_uid(fatherid)\n            self.redirect('/{1}/_cat_add/{0}'.format(fatherid, router_post[catinfo.kind]))",
    "docstring": "Publishing from 2ed range category."
  },
  {
    "code": "def _download_from_s3(bucket, key, version=None):\n        s3 = boto3.client('s3')\n        extra_args = {}\n        if version:\n            extra_args[\"VersionId\"] = version\n        with tempfile.TemporaryFile() as fp:\n            try:\n                s3.download_fileobj(\n                    bucket, key, fp,\n                    ExtraArgs=extra_args)\n                fp.seek(0)\n                return fp.read()\n            except botocore.exceptions.ClientError:\n                LOG.error(\"Unable to download Swagger document from S3 Bucket=%s Key=%s Version=%s\",\n                          bucket, key, version)\n                raise",
    "docstring": "Download a file from given S3 location, if available.\n\n        Parameters\n        ----------\n        bucket : str\n            S3 Bucket name\n\n        key : str\n            S3 Bucket Key aka file path\n\n        version : str\n            Optional Version ID of the file\n\n        Returns\n        -------\n        str\n            Contents of the file that was downloaded\n\n        Raises\n        ------\n        botocore.exceptions.ClientError if we were unable to download the file from S3"
  },
  {
    "code": "def _get_row_tag(row, tag):\n        is_empty = True\n        data = []\n        for column_label in row.find_all(tag):\n            data.append(\n                String(column_label.text).strip_bad_html()\n            )\n            if data[-1]:\n                is_empty = False\n        if not is_empty:\n            return data\n        return None",
    "docstring": "Parses row and gets columns matching tag\n\n        :param row: HTML row\n        :param tag: tag to get\n        :return: list of labels in row"
  },
  {
    "code": "def set_mode_manual(self):\n        if self.mavlink10():\n            self.mav.command_long_send(self.target_system, self.target_component,\n                                       mavlink.MAV_CMD_DO_SET_MODE, 0,\n                                       mavlink.MAV_MODE_MANUAL_ARMED,\n                                       0, 0, 0, 0, 0, 0)\n        else:\n            MAV_ACTION_SET_MANUAL = 12\n            self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_SET_MANUAL)",
    "docstring": "enter MANUAL mode"
  },
  {
    "code": "def decrease_poolsize(self):\n        if self._session_pool_size <= 1:\n            raise SessionPoolMinSizeReached('Session pool size cannot be decreased further')\n        with self._session_pool_lock:\n            if self._session_pool_size <= 1:\n                log.debug('Session pool size was decreased in another thread')\n                return\n            log.warning('Lowering session pool size from %s to %s', self._session_pool_size,\n                        self._session_pool_size - 1)\n            self.get_session().close()\n            self._session_pool_size -= 1",
    "docstring": "Decreases the session pool size in response to error messages from the server requesting to rate-limit\n        requests. We decrease by one session per call."
  },
  {
    "code": "def sha1_hash(string):\n    hasher = sha1()\n    hasher.update(string.encode())\n    return hasher.hexdigest()",
    "docstring": "Return the SHA1 of the input string."
  },
  {
    "code": "def lemmatize(self):\n        for unit in self.unit_list:\n            if lemmatizer.lemmatize(unit.text) in self.lemmas:\n                    unit.text = lemmatizer.lemmatize(unit.text)",
    "docstring": "Lemmatize all Units in self.unit_list.\n\n        Modifies:\n            - self.unit_list: converts the .text property into its lemmatized form.\n\n        This method lemmatizes all inflected variants of permissible words to\n        those words' respective canonical forms. This is done to ensure that\n        each instance of a permissible word will correspond to a term vector with\n        which semantic relatedness to other words' term vectors can be computed.\n        (Term vectors were derived from a corpus in which inflected words were\n        similarly lemmatized, meaning that , e.g., 'dogs' will not have a term\n        vector to use for semantic relatedness computation.)"
  },
  {
    "code": "def synchronize_simultaneous(self, node_ip):\r\n        for candidate in self.factory.candidates[node_ip]:\r\n            if not candidate[\"con\"].connected:\r\n                continue\r\n            if candidate[\"time\"] -\\\r\n                    self.factory.nodes[\"simultaneous\"][node_ip][\"time\"] >\\\r\n                    self.challege_timeout:\r\n                msg = \"RECONNECT\"\r\n                self.factory.nodes[\"simultaneous\"][node_ip][\"con\"].\\\r\n                    send_line(msg)\r\n                return\r\n        self.cleanup_candidates(node_ip)\r\n        self.propogate_candidates(node_ip)",
    "docstring": "Because adjacent mappings for certain NAT types can\r\n        be stolen by other connections, the purpose of this\r\n        function is to ensure the last connection by a passive\r\n        simultaneous node is recent compared to the time for\r\n        a candidate to increase the chance that the precited\r\n        mappings remain active for the TCP hole punching\r\n        attempt."
  },
  {
    "code": "def create_thread(self, body):\n        self.add_comment(body, allow_create=True)\n        the_response = Response()\n        the_response.code = \"OK\"\n        the_response.status_code = 200",
    "docstring": "Implement create_thread as required by parent.\n\n        This basically just calls add_comment with allow_create=True\n        and then builds a response object to indicate everything is fine."
  },
  {
    "code": "def has_perm(self, user, perm, obj=None, *args, **kwargs):\n        try:\n            if not self._obj_ok(obj):\n                if hasattr(obj, 'get_permissions_object'):\n                    obj = obj.get_permissions_object(perm)\n                else:\n                    raise InvalidPermissionObjectException\n            return user.permset_tree.allow(Action(perm), obj)\n        except ObjectDoesNotExist:\n            return False",
    "docstring": "Test user permissions for a single action and object.\n\n        :param user: The user to test.\n        :type user: ``User``\n        :param perm: The action to test.\n        :type perm: ``str``\n        :param obj: The object path to test.\n        :type obj: ``tutelary.engine.Object``\n        :returns: ``bool`` -- is the action permitted?"
  },
  {
    "code": "def on_train_end(self, **kwargs: Any) -> None:  \n        \"Store the notebook and stop run\"\n        self.client.log_artifact(run_id=self.run, local_path=self.nb_path)\n        self.client.set_terminated(run_id=self.run)",
    "docstring": "Store the notebook and stop run"
  },
  {
    "code": "def blockgen(bytes, block_size=16):\n    for i in range(0, len(bytes), block_size):\n        block = bytes[i:i + block_size]\n        block_len = len(block)\n        if block_len > 0:\n            yield block\n        if block_len < block_size:\n            break",
    "docstring": "a block generator for pprp"
  },
  {
    "code": "def install_ui_colorscheme(self, name, style_dict):\n        assert isinstance(name, six.text_type)\n        assert isinstance(style_dict, dict)\n        self.ui_styles[name] = style_dict",
    "docstring": "Install a new UI color scheme."
  },
  {
    "code": "def find_seq_id(block, name, case_sensitive=True):\n    rec = find_seq_rec(block, name, case_sensitive)\n    return rec['id']",
    "docstring": "Given part of a sequence ID, find the first actual ID that contains it.\n\n    Example::\n\n        >>> find_seq_id(block, '2QG5')\n        'gi|158430190|pdb|2QG5|A'\n\n    Raise a ValueError if no matching key is found."
  },
  {
    "code": "def backfill_unk_emb(self, E, filled_words):\n        unk_emb = E[self[self._unk]]\n        for i, word in enumerate(self):\n            if word not in filled_words:\n                E[i] = unk_emb",
    "docstring": "Backfills an embedding matrix with the embedding for the unknown token.\n\n        :param E: original embedding matrix of dimensions `(vocab_size, emb_dim)`.\n        :param filled_words: these words will not be backfilled with unk.\n\n        NOTE: this function is for internal use."
  },
  {
    "code": "def get_layout(self):\n        if self.request.is_ajax():\n            layout = ['modal', ]\n        else:\n            layout = ['static_page', ]\n        if self.workflow_class.wizard:\n            layout += ['wizard', ]\n        return layout",
    "docstring": "Returns classes for the workflow element in template.\n\n        The returned classes are determied based on\n        the workflow characteristics."
  },
  {
    "code": "def token(cls: Type[SIGType], pubkey: str) -> SIGType:\n        sig = cls()\n        sig.pubkey = pubkey\n        return sig",
    "docstring": "Return SIG instance from pubkey\n\n        :param pubkey: Public key of the signature issuer\n        :return:"
  },
  {
    "code": "def color_format():\n    str_format = BASE_COLOR_FORMAT if supports_color() else BASE_FORMAT\n    color_format = color_message(str_format)\n    return ColoredFormatter(color_format)",
    "docstring": "Main entry point to get a colored formatter, it will use the\n    BASE_FORMAT by default and fall back to no colors if the system\n    does not support it"
  },
  {
    "code": "def request(self, url, method, body=None, headers=None, **kwargs):\n        content_type = kwargs.pop('content_type', None) or 'application/json'\n        headers = headers or {}\n        headers.setdefault('Accept', content_type)\n        if body:\n            headers.setdefault('Content-Type', content_type)\n        headers['User-Agent'] = self.USER_AGENT\n        resp = requests.request(\n            method,\n            url,\n            data=body,\n            headers=headers,\n            verify=self.verify_cert,\n            timeout=self.timeout,\n            **kwargs)\n        return resp, resp.text",
    "docstring": "Request without authentication."
  },
  {
    "code": "def name(self):\n        return ffi.string(lib.EnvGetDefruleName(self._env, self._rule)).decode()",
    "docstring": "Rule name."
  },
  {
    "code": "def run(user, port=4242):\n    owd = os.getcwd()\n    dir = export(user)\n    os.chdir(dir)\n    Handler = SimpleHTTPServer.SimpleHTTPRequestHandler\n    try:\n        httpd = SocketServer.TCPServer((\"\", port), Handler)\n        print(\"Serving bandicoot visualization at http://0.0.0.0:%i\" % port)\n        httpd.serve_forever()\n    except KeyboardInterrupt:\n        print(\"^C received, shutting down the web server\")\n        httpd.server_close()\n    finally:\n        os.chdir(owd)",
    "docstring": "Build a temporary directory with a visualization and serve it over HTTP.\n\n    Examples\n    --------\n\n        >>> bandicoot.visualization.run(U)\n        Successfully exported the visualization to /tmp/tmpsIyncS\n        Serving bandicoot visualization at http://0.0.0.0:4242"
  },
  {
    "code": "def initialize_segment_register_x64(self, state, concrete_target):\n        _l.debug(\"Synchronizing gs segment register\")\n        state.regs.gs = self._read_gs_register_x64(concrete_target)",
    "docstring": "Set the gs register in the angr to the value of the fs register in the concrete process\n\n        :param state:               state which will be modified\n        :param concrete_target:     concrete target that will be used to read the fs register\n        :return: None"
  },
  {
    "code": "def authenticate(self, request):\n        from doac.middleware import AuthenticationMiddleware\n        try:\n            response = AuthenticationMiddleware().process_request(request)\n        except:\n            raise exceptions.AuthenticationFailed(\"Invalid handler\")\n        if not hasattr(request, \"user\") or not request.user.is_authenticated():\n            return None\n        if not hasattr(request, \"access_token\"):\n            raise exceptions.AuthenticationFailed(\"Access token was not valid\")\n        return request.user, request.access_token",
    "docstring": "Send the request through the authentication middleware that\n        is provided with DOAC and grab the user and token from it."
  },
  {
    "code": "def get_rows(self):\n        possible_dataframes = ['F', 'FY', 'M', 'S',\n                               'D_cba', 'D_pba',  'D_imp', 'D_exp',\n                               'D_cba_reg', 'D_pba_reg',\n                               'D_imp_reg', 'D_exp_reg',\n                               'D_cba_cap', 'D_pba_cap',\n                               'D_imp_cap', 'D_exp_cap', ]\n        for df in possible_dataframes:\n            if (df in self.__dict__) and (getattr(self, df) is not None):\n                return getattr(self, df).index.get_values()\n        else:\n            logging.warn(\"No attributes available to get row names\")\n            return None",
    "docstring": "Returns the name of the rows of the extension"
  },
  {
    "code": "def _get_mine(fun):\n    if fun in _CACHE and _CACHE[fun]:\n        return _CACHE[fun]\n    net_runner_opts = _get_net_runner_opts()\n    _CACHE[fun] = __salt__['mine.get'](net_runner_opts.get('target'),\n                                       fun,\n                                       tgt_type=net_runner_opts.get('expr_form'))\n    return _CACHE[fun]",
    "docstring": "Return the mine function from all the targeted minions.\n    Just a small helper to avoid redundant pieces of code."
  },
  {
    "code": "def read_fwf(self, *args, **kwargs):\n        import pandas\n        t = self.resolved_url.get_resource().get_target()\n        return pandas.read_fwf(t.fspath, *args, **kwargs)",
    "docstring": "Fetch the target and pass through to pandas.read_fwf.\n\n        Don't provide the first argument of read_fwf(); it is supplied internally."
  },
  {
    "code": "def delete_entity(self, entity_id, mount_point=DEFAULT_MOUNT_POINT):\n        api_path = '/v1/{mount_point}/entity/id/{id}'.format(\n            mount_point=mount_point,\n            id=entity_id,\n        )\n        return self._adapter.delete(\n            url=api_path,\n        )",
    "docstring": "Delete an entity and all its associated aliases.\n\n        Supported methods:\n            DELETE: /{mount_point}/entity/id/:id. Produces: 204 (empty body)\n\n        :param entity_id: Identifier of the entity.\n        :type entity_id: str\n        :param mount_point: The \"path\" the secret engine was mounted on.\n        :type mount_point: str | unicode\n        :return: The response of the request.\n        :rtype: requests.Response"
  },
  {
    "code": "def add(self, data_bytes):\n        try:\n            if isinstance(data_bytes, basestring):\n                data_bytes = map(ord, data_bytes)\n        except NameError:\n            if isinstance(data_bytes, str):\n                data_bytes = map(ord, data_bytes)\n        for b in data_bytes:\n            self._crc ^= (b << 56) & Signature.MASK64\n            for _ in range(8):\n                if self._crc & (1 << 63):\n                    self._crc = ((self._crc << 1) & Signature.MASK64) ^ Signature.POLY\n                else:\n                    self._crc <<= 1",
    "docstring": "Feed ASCII string or bytes to the signature function"
  },
  {
    "code": "def change_password(self, new_password):\n        self.set_password(new_password)\n        self.save()\n        password_changed.send(sender=self.__class__, user=self)",
    "docstring": "Changes password and sends a signal"
  },
  {
    "code": "def split_volume_from_journal(citation_elements):\n    for el in citation_elements:\n        if el['type'] == 'JOURNAL' and ';' in el['title']:\n            el['title'], series = el['title'].rsplit(';', 1)\n            el['volume'] = series + el['volume']\n    return citation_elements",
    "docstring": "Split volume from journal title\n\n    We need this because sometimes the volume is attached to the journal title\n    instead of the volume. In those cases we move it here from the title to the\n    volume"
  },
  {
    "code": "def _get_item_class(self, url):\n        if '/layers/' in url:\n            return Layer\n        elif '/tables/' in url:\n            return Table\n        elif '/sets/' in url:\n            return Set\n        else:\n            raise NotImplementedError(\"No support for catalog results of type %s\" % url)",
    "docstring": "Return the model class matching a URL"
  },
  {
    "code": "def trash(self, request, **kwargs):\n        content = self.get_object()\n        content.indexed = False\n        content.save()\n        LogEntry.objects.log(request.user, content, \"Trashed\")\n        return Response({\"status\": \"Trashed\"})",
    "docstring": "Psuedo-deletes a `Content` instance and removes it from the ElasticSearch index\n\n        Content is not actually deleted, merely hidden by deleted from ES index.import\n\n        :param request: a WSGI request object\n        :param kwargs: keyword arguments (optional)\n        :return: `rest_framework.response.Response`"
  },
  {
    "code": "def dump_img(fname):\n    img = Image.open(fname)\n    width, _ = img.size\n    txt = ''\n    pixels = list(img.getdata())\n    for col in range(width):\n        txt += str(pixels[col:col+width])\n    return txt",
    "docstring": "output the image as text"
  },
  {
    "code": "def model_post_delete(sender, instance, **kwargs):\n    if sender._meta.app_label == 'rest_framework_reactive':\n        return\n    def notify():\n        table = sender._meta.db_table\n        notify_observers(table, ORM_NOTIFY_KIND_DELETE, instance.pk)\n    transaction.on_commit(notify)",
    "docstring": "Signal emitted after any model is deleted via Django ORM.\n\n    :param sender: Model class that was deleted\n    :param instance: The actual instance that was removed"
  },
  {
    "code": "def random_string(length=6, alphabet=string.ascii_letters+string.digits):\n    return ''.join([random.choice(alphabet) for i in xrange(length)])",
    "docstring": "Return a random string of given length and alphabet.\n\n    Default alphabet is url-friendly (base62)."
  },
  {
    "code": "def remove(self, iterable, data=None, index=0):\n        if index == len(iterable):\n            if self.is_terminal:\n                if data:\n                    self.data.remove(data)\n                    if len(self.data) == 0:\n                        self.is_terminal = False\n                else:\n                    self.data.clear()\n                    self.is_terminal = False\n                return True\n            else:\n                return False\n        elif iterable[index] in self.children:\n            return self.children[iterable[index]].remove(iterable, index=index+1, data=data)\n        else:\n            return False",
    "docstring": "Remove an element from the trie\n\n        Args\n            iterable(hashable): key used to find what is to be removed\n            data(object): data associated with the key\n            index(int): index of what is to me removed\n\n        Returns:\n        bool:\n            True: if it was removed\n            False: if it was not removed"
  },
  {
    "code": "def order_limit_buy(self, timeInForce=TIME_IN_FORCE_GTC, **params):\n        params.update({\n            'side': self.SIDE_BUY,\n        })\n        return self.order_limit(timeInForce=timeInForce, **params)",
    "docstring": "Send in a new limit buy order\n\n        Any order with an icebergQty MUST have timeInForce set to GTC.\n\n        :param symbol: required\n        :type symbol: str\n        :param quantity: required\n        :type quantity: decimal\n        :param price: required\n        :type price: str\n        :param timeInForce: default Good till cancelled\n        :type timeInForce: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param stopPrice: Used with stop orders\n        :type stopPrice: decimal\n        :param icebergQty: Used with iceberg orders\n        :type icebergQty: decimal\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        See order endpoint for full response options\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException"
  },
  {
    "code": "def is_valid_short_number_for_region(short_numobj, region_dialing_from):\n    if not _region_dialing_from_matches_number(short_numobj, region_dialing_from):\n        return False\n    metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from)\n    if metadata is None:\n        return False\n    short_number = national_significant_number(short_numobj)\n    general_desc = metadata.general_desc\n    if not _matches_possible_number_and_national_number(short_number, general_desc):\n        return False\n    short_number_desc = metadata.short_code\n    if short_number_desc.national_number_pattern is None:\n        return False\n    return _matches_possible_number_and_national_number(short_number, short_number_desc)",
    "docstring": "Tests whether a short number matches a valid pattern in a region.\n\n    Note that this doesn't verify the number is actually in use, which is\n    impossible to tell by just looking at the number itself.\n\n    Arguments:\n    short_numobj -- the short number to check as a PhoneNumber object.\n    region_dialing_from -- the region from which the number is dialed\n\n    Return whether the short number matches a valid pattern"
  },
  {
    "code": "def setPriority(self, queue, priority):\n        q = self.queueindex[queue]\n        self.queues[q[0]].removeSubQueue(q[1])\n        newPriority = self.queues.setdefault(priority, CBQueue.MultiQueue(self, priority))\n        q[0] = priority\n        newPriority.addSubQueue(q[1])",
    "docstring": "Set priority of a sub-queue"
  },
  {
    "code": "def cancel(self):\n        if self.status > COMPLETED:\n            return\n        cmd = self.backend.cmd_cancel(self)\n        self._run_cmd(cmd, self.remote, ignore_exit_code=True, ssh=self.ssh)\n        self._status = CANCELLED\n        self.dump()",
    "docstring": "Instruct the cluster to cancel the running job. Has no effect if\n        job is not running"
  },
  {
    "code": "def has_property(obj, name):\n        if obj == None:\n            raise Exception(\"Object cannot be null\")\n        if name == None:\n            raise Exception(\"Property name cannot be null\")\n        name = name.lower()\n        for property_name in dir(obj): \n            if property_name.lower() != name:\n                continue\n            property = getattr(obj, property_name)\n            if PropertyReflector._is_property(property, property_name):\n                return True\n        return False",
    "docstring": "Checks if object has a property with specified name.\n\n        :param obj: an object to introspect.\n\n        :param name: a name of the property to check.\n\n        :return: true if the object has the property and false if it doesn't."
  },
  {
    "code": "def get_playlists(self, search, start=0, max_items=100):\n        return self.get_music_service_information('playlists', search, start,\n                                                  max_items)",
    "docstring": "Search for playlists.\n\n        See get_music_service_information for details on the arguments.\n\n        Note:\n\n            Un-intuitively this method returns MSAlbumList items. See\n            note in class doc string for details."
  },
  {
    "code": "def _should_run(het_file):\n    has_hets = False\n    with open(het_file) as in_handle:\n        for i, line in enumerate(in_handle):\n            if i > 1:\n                has_hets = True\n                break\n    return has_hets",
    "docstring": "Check for enough input data to proceed with analysis."
  },
  {
    "code": "def cancel(self):\n        logger.debug(\"Running cancel hooks: {}\".format(self))\n        if not self.cancelled:\n            logger.debug(\"Cancelling {}\".format(self))\n            self.cancelled = True\n        self.save()",
    "docstring": "Cancel an EighthScheduledActivity.\n\n        This does nothing besides set the cancelled flag and save the\n        object."
  },
  {
    "code": "def end_request(self):\n        if not self._chunked:\n            return\n        trailers = [(n, get_header(self._headers, n)) for n in self._trailer] \\\n                        if self._trailer else None\n        ending = create_chunked_body_end(trailers)\n        self._protocol.writer.write(ending)",
    "docstring": "End the request body."
  },
  {
    "code": "def next_token(self):\n        if self.lookahead:\n            self.current_token = self.lookahead.popleft()\n            return self.current_token\n        self.current_token = self._parse_next_token()\n        return self.current_token",
    "docstring": "Returns the next logical token, advancing the tokenizer."
  },
  {
    "code": "def lincc(x, y):\n    covar = cov(x, y) * (len(x) - 1) / float(len(x))\n    xvar = var(x) * (len(x) - 1) / float(len(x))\n    yvar = var(y) * (len(y) - 1) / float(len(y))\n    lincc = (2 * covar) / ((xvar + yvar) + ((mean(x) - mean(y)) ** 2))\n    return lincc",
    "docstring": "Calculates Lin's concordance correlation coefficient.\n\nUsage:   alincc(x,y)    where x, y are equal-length arrays\nReturns: Lin's CC"
  },
  {
    "code": "def draw(self, painter, options, widget):\n        self.declaration.draw(painter, options, widget)",
    "docstring": "Handle the draw event for the widget."
  },
  {
    "code": "def lookup(self, hostname):\n        matches = [x for x in self._config if fnmatch.fnmatch(hostname, x['host'])]\n        _star = matches.pop(0)\n        matches.append(_star)\n        ret = {}\n        for m in matches:\n            for k,v in m.iteritems():\n                if not k in ret:\n                    ret[k] = v\n        ret = self._expand_variables(ret, hostname)\n        del ret['host']\n        return ret",
    "docstring": "Return a dict of config options for a given hostname.\n\n        The host-matching rules of OpenSSH's C{ssh_config} man page are used,\n        which means that all configuration options from matching host\n        specifications are merged, with more specific hostmasks taking\n        precedence. In other words, if C{\"Port\"} is set under C{\"Host *\"}\n        and also C{\"Host *.example.com\"}, and the lookup is for\n        C{\"ssh.example.com\"}, then the port entry for C{\"Host *.example.com\"}\n        will win out.\n\n        The keys in the returned dict are all normalized to lowercase (look for\n        C{\"port\"}, not C{\"Port\"}. No other processing is done to the keys or\n        values.\n\n        @param hostname: the hostname to lookup\n        @type hostname: str"
  },
  {
    "code": "def cross_entropy_calc(TOP, P, POP):\n    try:\n        result = 0\n        for i in TOP.keys():\n            reference_likelihood = P[i] / POP[i]\n            response_likelihood = TOP[i] / POP[i]\n            if response_likelihood != 0 and reference_likelihood != 0:\n                result += reference_likelihood * \\\n                    math.log(response_likelihood, 2)\n        return -result\n    except Exception:\n        return \"None\"",
    "docstring": "Calculate cross entropy.\n\n    :param TOP: test outcome positive\n    :type TOP : dict\n    :param P: condition positive\n    :type P : dict\n    :param POP: population\n    :type POP : dict\n    :return: cross entropy as float"
  },
  {
    "code": "def conv1d_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):\n  return conv_block_internal(conv1d, inputs, filters,\n                             dilation_rates_and_kernel_sizes, **kwargs)",
    "docstring": "A block of standard 1d convolutions."
  },
  {
    "code": "def force_rerun(flag, outfile):\n    if flag:\n        return True\n    elif not flag and not op.exists(outfile):\n        return True\n    elif not flag and not is_non_zero_file(outfile):\n        return True\n    else:\n        return False",
    "docstring": "Check if we should force rerunning of a command if an output file exists.\n\n    Args:\n        flag (bool): Flag to force rerun.\n        outfile (str): Path to output file which may already exist.\n\n    Returns:\n        bool: If we should force rerunning of a command\n\n    Examples:\n        >>> force_rerun(flag=True, outfile='/not/existing/file.txt')\n        True\n\n        >>> force_rerun(flag=False, outfile='/not/existing/file.txt')\n        True\n\n        >>> force_rerun(flag=True, outfile='./utils.py')\n        True\n\n        >>> force_rerun(flag=False, outfile='./utils.py')\n        False"
  },
  {
    "code": "def md5hash(self):\n        digest = hashlib.md5(self.content).digest()\n        return b64_string(digest)",
    "docstring": "Return the MD5 hash string of the file content"
  },
  {
    "code": "def _indent(indent=0, quote='', indent_char=' '):\n    if indent > 0:\n        indent_string = ''.join((\n            str(quote),\n            (indent_char * (indent - len(quote)))\n        ))\n    else:\n        indent_string = ''.join((\n            ('\\x08' * (-1 * (indent - len(quote)))),\n            str(quote))\n        )\n    if len(indent_string):\n        INDENT_STRINGS.append(indent_string)",
    "docstring": "Indent util function, compute new indent_string"
  },
  {
    "code": "def parse_memory_value(s):\n    number, unit = split_number_and_unit(s)\n    if not unit or unit == 'B':\n        return number\n    elif unit == 'kB':\n        return number * _BYTE_FACTOR\n    elif unit == 'MB':\n        return number * _BYTE_FACTOR * _BYTE_FACTOR\n    elif unit == 'GB':\n        return number * _BYTE_FACTOR * _BYTE_FACTOR * _BYTE_FACTOR\n    elif unit == 'TB':\n        return number * _BYTE_FACTOR * _BYTE_FACTOR * _BYTE_FACTOR * _BYTE_FACTOR\n    else:\n        raise ValueError('unknown unit: {} (allowed are B, kB, MB, GB, and TB)'.format(unit))",
    "docstring": "Parse a string that contains a number of bytes, optionally with a unit like MB.\n    @return the number of bytes encoded by the string"
  },
  {
    "code": "def take_at_most_n_seconds(time_s, func, *args, **kwargs):\n  thread = threading.Thread(target=func, args=args, kwargs=kwargs)\n  thread.start()\n  thread.join(time_s)\n  if thread.is_alive():\n    return False\n  return True",
    "docstring": "A function that returns whether a function call took less than time_s.\n\n  NOTE: The function call is not killed and will run indefinitely if hung.\n\n  Args:\n    time_s: Maximum amount of time to take.\n    func: Function to call.\n    *args: Arguments to call the function with.\n    **kwargs: Keyword arguments to call the function with.\n  Returns:\n    True if the function finished in less than time_s seconds."
  },
  {
    "code": "def _validate(self, value):\n        if value is None:\n            raise ValueError('The pk for %s is not \"auto-increment\", you must fill it' %\n                            self._model.__name__)\n        value = self.normalize(value)\n        if self.exists(value):\n            raise UniquenessError('PKField %s already exists for model %s)' %\n                                  (value, self._instance.__class__))\n        return value",
    "docstring": "Validate that a given new pk to set is always set, and return it.\n        The returned value should be normalized, and will be used without check."
  },
  {
    "code": "def to_json(self, *args, **kwargs):\n        return json.dumps(self.to_schema(), *args, **kwargs)",
    "docstring": "Generate a schema and convert it directly to serialized JSON.\n\n        :rtype: ``str``"
  },
  {
    "code": "def SetLowerTimestamp(cls, timestamp):\n    if not hasattr(cls, '_lower'):\n      cls._lower = timestamp\n      return\n    if timestamp < cls._lower:\n      cls._lower = timestamp",
    "docstring": "Sets the lower bound timestamp."
  },
  {
    "code": "def visit_rule(self, node, rule):\n        label, equals, expression = rule\n        expression.name = label\n        return expression",
    "docstring": "Assign a name to the Expression and return it."
  },
  {
    "code": "def _write_to_uaa_cache(self, new_item):\n        data = self._read_uaa_cache()\n        if self.uri not in data:\n            data[self.uri] = []\n        for client in data[self.uri]:\n            if new_item['id'] == client['id']:\n                data[self.uri].remove(client)\n                continue\n            if 'expires' in client:\n                expires = dateutil.parser.parse(client['expires'])\n                if expires < datetime.datetime.now():\n                    data[self.uri].remove(client)\n                    continue\n        data[self.uri].append(new_item)\n        with open(self._cache_path, 'w') as output:\n            output.write(json.dumps(data, sort_keys=True, indent=4))",
    "docstring": "Cache the client details into a cached file on disk."
  },
  {
    "code": "def _warning(self, msg, duration=None, results=None):\n        logger.warning(\n            \"{} ({})\".format(msg, self._get_logging_id()),\n            extra=self._get_logging_extra(duration=duration, results=results),\n        )",
    "docstring": "Log warnings."
  },
  {
    "code": "def AddLabel(self, label):\n    if not isinstance(label, py2to3.STRING_TYPES):\n      raise TypeError('label is not a string type. Is {0:s}'.format(\n          type(label)))\n    if not self._VALID_LABEL_REGEX.match(label):\n      raise ValueError((\n          'Unsupported label: \"{0:s}\". A label must only consist of '\n          'alphanumeric characters or underscores.').format(label))\n    if label not in self.labels:\n      self.labels.append(label)",
    "docstring": "Adds a label to the event tag.\n\n    Args:\n      label (str): label.\n\n    Raises:\n      TypeError: if the label provided is not a string.\n      ValueError: if a label is malformed."
  },
  {
    "code": "def from_file(cls, path, directory=None, modules=None, active=None):\n        name = basename(path)\n        if name.endswith('.rpp'):\n            name = name[:-4]\n        lines = _repp_lines(path)\n        directory = dirname(path) if directory is None else directory\n        r = cls(name=name, modules=modules, active=active)\n        _parse_repp(lines, r, directory)\n        return r",
    "docstring": "Instantiate a REPP from a `.rpp` file.\n\n        The *path* parameter points to the top-level module. Submodules\n        are loaded from *directory*. If *directory* is not given, it is\n        the directory part of *path*.\n\n        A REPP module may utilize external submodules, which may be\n        defined in two ways. The first method is to map a module name\n        to an instantiated REPP instance in *modules*. The second\n        method assumes that an external group call `>abc` corresponds\n        to a file `abc.rpp` in *directory* and loads that file. The\n        second method only happens if the name (e.g., `abc`) does not\n        appear in *modules*. Only one module may define a tokenization\n        pattern.\n\n        Args:\n            path (str): the path to the base REPP file to load\n            directory (str, optional): the directory in which to search\n                for submodules\n            modules (dict, optional): a mapping from identifiers to\n                REPP modules\n            active (iterable, optional): an iterable of default module\n                activations"
  },
  {
    "code": "def open_console(self, client=None):\r\n        if not client:\r\n            client = self.get_current_client()\r\n        if self.ipyconsole is not None:\r\n            kernel_id = client.get_kernel_id()\r\n            if not kernel_id:\r\n                QMessageBox.critical(\r\n                    self, _('Error opening console'),\r\n                    _('There is no kernel associated to this notebook.'))\r\n                return\r\n            self.ipyconsole._create_client_for_kernel(kernel_id, None, None,\r\n                                                      None)\r\n            ipyclient = self.ipyconsole.get_current_client()\r\n            ipyclient.allow_rename = False\r\n            self.ipyconsole.rename_client_tab(ipyclient,\r\n                                              client.get_short_name())",
    "docstring": "Open an IPython console for the given client or the current one."
  },
  {
    "code": "def renamecol(self, old, new):\n        spreadsheet.renamecol(self,old,new)\n        for x in self.coloring.keys():\n            if old in self.coloring[x]:\n                ind = self.coloring[x].index(old)\n                self.coloring[x][ind] = new",
    "docstring": "Rename column or color in-place.\n\n        Method wraps::\n\n                tabular.spreadsheet.renamecol(self, old, new)"
  },
  {
    "code": "def P(value, bits=None, endian=None, target=None):\n    return globals()['P%d' % _get_bits(bits, target)](value, endian=endian, target=target)",
    "docstring": "Pack an unsigned pointer for a given target.\n\n    Args:\n        value(int): The value to pack.\n        bits(:class:`~pwnypack.target.Target.Bits`): Override the default\n            word size. If ``None`` it will look at the word size of\n            ``target``.\n        endian(:class:`~pwnypack.target.Target.Endian`): Override the default\n            byte order. If ``None``, it will look at the byte order of\n            the ``target`` argument.\n        target(:class:`~pwnypack.target.Target`): Override the default byte\n            order. If ``None``, it will look at the byte order of\n            the global :data:`~pwnypack.target.target`."
  },
  {
    "code": "def _target_id_from_htm(self, line):\n        m = re.search(\"\\\\?code=([a-fA-F0-9]+)\", line)\n        if m:\n            result = m.groups()[0]\n            return result\n        m = re.search(\"\\\\?auth=([a-fA-F0-9]+)\", line)\n        if m:\n            result = m.groups()[0]\n            return result\n        return None",
    "docstring": "! Extract Target id from htm line.\n        @return Target id or None"
  },
  {
    "code": "def decorate_class(self, klass, *decorator_args, **decorator_kwargs):\n        raise RuntimeError(\"decorator {} does not support class decoration\".format(self.__class__.__name__))\n        return klass",
    "docstring": "override this in a child class with your own logic, it must return a\n        function that returns klass or the like\n\n        :param klass: the class object that is being decorated\n        :param decorator_args: tuple -- the arguments passed into the decorator (eg, @dec(1, 2))\n        :param decorator_kwargs: dict -- the named args passed into the decorator (eg, @dec(foo=1))\n        :returns: the wrapped class"
  },
  {
    "code": "def dom_id(self):\n        parameter = 'DOMID'\n        if parameter not in self._by:\n            self._populate(by=parameter)\n        return self._by[parameter]",
    "docstring": "A dict of CLBs with DOM ID as key"
  },
  {
    "code": "def _evaluate(self):\n        if self._elements:\n            for element in self._elements:\n                yield element\n        else:\n            for page in itertools.count():\n                raw_elements = self._retrieve_raw_elements(page)\n                for raw_element in raw_elements:\n                    element = self._parse_raw_element(raw_element)\n                    self._elements.append(element)\n                    yield element\n                    if self.__limit and len(self._elements) >= self.__limit:\n                        break\n                if any([\n                    len(raw_elements) < self.page_size,\n                    (self.__limit and len(self._elements) >= self.__limit)\n                ]):\n                    break",
    "docstring": "Lazily retrieve and paginate report results and build Record instances from returned data"
  },
  {
    "code": "def clear_optimizer(self):\n        self._optimized = False\n        self._type2decls = {}\n        self._type2name2decls = {}\n        self._type2decls_nr = {}\n        self._type2name2decls_nr = {}\n        self._all_decls = None\n        self._all_decls_not_recursive = None\n        for decl in self.declarations:\n            if isinstance(decl, scopedef_t):\n                decl.clear_optimizer()",
    "docstring": "Cleans query optimizer state"
  },
  {
    "code": "def declallfuncs(self):\n        for f in self.body:\n            if (hasattr(f, '_ctype')\n                    and isinstance(f._ctype, FuncType)):\n                yield f",
    "docstring": "generator on all declaration of function"
  },
  {
    "code": "def fit(self, train_X, train_Y, val_X=None, val_Y=None, graph=None):\n        if len(train_Y.shape) != 1:\n            num_classes = train_Y.shape[1]\n        else:\n            raise Exception(\"Please convert the labels with one-hot encoding.\")\n        g = graph if graph is not None else self.tf_graph\n        with g.as_default():\n            self.build_model(train_X.shape[1], num_classes)\n            with tf.Session() as self.tf_session:\n                summary_objs = tf_utils.init_tf_ops(self.tf_session)\n                self.tf_merged_summaries = summary_objs[0]\n                self.tf_summary_writer = summary_objs[1]\n                self.tf_saver = summary_objs[2]\n                self._train_model(train_X, train_Y, val_X, val_Y)\n                self.tf_saver.save(self.tf_session, self.model_path)",
    "docstring": "Fit the model to the data.\n\n        Parameters\n        ----------\n\n        train_X : array_like, shape (n_samples, n_features)\n            Training data.\n\n        train_Y : array_like, shape (n_samples, n_classes)\n            Training labels.\n\n        val_X : array_like, shape (N, n_features) optional, (default = None).\n            Validation data.\n\n        val_Y : array_like, shape (N, n_classes) optional, (default = None).\n            Validation labels.\n\n        graph : tf.Graph, optional (default = None)\n            Tensorflow Graph object.\n\n        Returns\n        -------"
  },
  {
    "code": "def add_input_variable(self, var):\n        assert(isinstance(var, Variable))\n        self.input_variable_list.append(var)",
    "docstring": "Adds the argument variable as one of the input variable"
  },
  {
    "code": "def chomp_protocol(url):\n        if '+' in url:\n            url = url.split('+', 1)[1]\n        scheme, netloc, path, query, frag = urlparse.urlsplit(url)\n        rev = None\n        if '@' in path:\n            path, rev = path.rsplit('@', 1)\n        url = urlparse.urlunsplit((scheme, netloc, path, query, ''))\n        if url.startswith('ssh://git@github.com/'):\n            url = url.replace('ssh://', 'git+ssh://')\n        elif '://' not in url:\n            assert 'file:' not in url\n            url = url.replace('git+', 'git+ssh://')\n            url = url.replace('ssh://', '')\n        return url",
    "docstring": "Return clean VCS url from RFC-style url\n\n        :param url: url\n        :type url: str\n        :rtype: str\n        :returns: url as VCS software would accept it\n        :seealso: #14"
  },
  {
    "code": "def main():\n    sys.path.append(\".\")\n    oz.initialize()\n    retr = optfn.run(list(oz._actions.values()))\n    if retr == optfn.ERROR_RETURN_CODE:\n        sys.exit(-1)\n    elif retr == None:\n        sys.exit(0)\n    elif isinstance(retr, int):\n        sys.exit(retr)\n    else:\n        raise Exception(\"Unexpected return value from action: %s\" % retr)",
    "docstring": "Main entry-point for oz's cli"
  },
  {
    "code": "def command(self, ns, raw, **kw):\n        try:\n            dbname = raw['ns'].split('.', 1)[0]\n            self.dest[dbname].command(raw['o'], check=True)\n        except OperationFailure, e:\n            logging.warning(e)",
    "docstring": "Executes command.\n\n            { \"op\" : \"c\",\n              \"ns\" : \"testdb.$cmd\",\n              \"o\" : { \"drop\" : \"fs.files\"}\n            }"
  },
  {
    "code": "def init(opts):\n    if 'host' not in opts['proxy']:\n        log.critical('No \"host\" key found in pillar for this proxy')\n        return False\n    DETAILS['host'] = opts['proxy']['host']\n    (username, password) = find_credentials()",
    "docstring": "This function gets called when the proxy starts up.\n    We check opts to see if a fallback user and password are supplied.\n    If they are present, and the primary credentials don't work, then\n    we try the backup before failing.\n\n    Whichever set of credentials works is placed in the persistent\n    DETAILS dictionary and will be used for further communication with the\n    chassis."
  },
  {
    "code": "async def enable_user(self, username):\n        user_facade = client.UserManagerFacade.from_connection(\n            self.connection())\n        entity = client.Entity(tag.user(username))\n        return await user_facade.EnableUser([entity])",
    "docstring": "Re-enable a previously disabled user."
  },
  {
    "code": "def get_unread_messages(self,\n                            include_me=False,\n                            include_notifications=False):\n        return list(self.driver.get_unread_messages_in_chat(\n            self.id,\n            include_me,\n            include_notifications\n        ))",
    "docstring": "I fetch unread messages.\n\n        :param include_me: if user's messages are to be included\n        :type  include_me: bool\n\n        :param include_notifications: if events happening on chat are to be included\n        :type  include_notifications: bool\n\n        :return: list of unread messages\n        :rtype: list"
  },
  {
    "code": "def btc_tx_witness_strip( tx_serialized ):\n    if not btc_tx_is_segwit(tx_serialized):\n        return tx_serialized\n    tx = btc_tx_deserialize(tx_serialized)\n    for inp in tx['ins']:\n        del inp['witness_script']\n    tx_stripped = btc_tx_serialize(tx)\n    return tx_stripped",
    "docstring": "Strip the witness information from a serialized transaction"
  },
  {
    "code": "def search(self, **kwargs):\n        return super(ApiEnvironmentVip, self).get(\n            self.prepare_url('api/v3/environment-vip/', kwargs))",
    "docstring": "Method to search environments vip based on extends search.\n\n        :param search: Dict containing QuerySets to find environments vip.\n        :param include: Array containing fields to include on response.\n        :param exclude: Array containing fields to exclude on response.\n        :param fields: Array containing fields to override default fields.\n        :param kind: Determine if result will be detailed ('detail')\n                     or basic ('basic').\n        :return: Dict containing environments vip"
  },
  {
    "code": "def _date_from_match(match_object):\n    year = int(match_object.group(\"year\"))\n    month = int(match_object.group(\"month\"))\n    day = int(match_object.group(\"day\"))\n    return datetime.date(year, month, day)",
    "docstring": "Create a date object from a regular expression match.\n\n    The regular expression match is expected to be from _RE_DATE or\n    _RE_DATETIME.\n\n    @param match_object: The regular expression match.\n    @type match_object: B{re}.I{MatchObject}\n    @return: A date object.\n    @rtype: B{datetime}.I{date}"
  },
  {
    "code": "def get_account(self, address, token_type):\n        cur = self.db.cursor()\n        return namedb_get_account(cur, address, token_type)",
    "docstring": "Get the state of an account for a given token type"
  },
  {
    "code": "def make_spondaic(self, scansion: str) -> str:\n        mark_list = string_utils.mark_list(scansion)\n        vals = list(scansion.replace(\" \", \"\"))\n        new_vals = self.SPONDAIC_PENTAMETER[:-1] + vals[-1]\n        corrected = \"\".join(new_vals)\n        new_line = list(\" \" * len(scansion))\n        for idx, car in enumerate(corrected):\n            new_line[mark_list[idx]] = car\n        return \"\".join(new_line)",
    "docstring": "If a pentameter line has 12 syllables, then it must start with double spondees.\n\n        :param scansion: a string of scansion patterns\n        :return: a scansion pattern string starting with two spondees\n\n        >>> print(PentameterScanner().make_spondaic(\"U  U  U  U  U  U  U  U  U  U  U  U\"))\n        -  -  -  -  -  -  U  U  -  U  U  U"
  },
  {
    "code": "def imagej_metadata(self):\n        if not self.is_imagej:\n            return None\n        page = self.pages[0]\n        result = imagej_description_metadata(page.is_imagej)\n        if 'IJMetadata' in page.tags:\n            try:\n                result.update(page.tags['IJMetadata'].value)\n            except Exception:\n                pass\n        return result",
    "docstring": "Return consolidated ImageJ metadata as dict."
  },
  {
    "code": "def _import(func):\n        func_name = func.__name__\n        if func_name in globals():\n            return func_name\n        module_name = func.__module__\n        submodules = module_name.split('.')\n        if submodules[0] in globals():\n            return module_name + '.' + func_name\n        for i in range(len(submodules)):\n            m = submodules[i]\n            if m in globals():\n                return '.'.join(submodules[i:]) + '.' + func_name\n        module_ref = sys.modules[func.__module__]\n        all_globals = globals()\n        for n in all_globals:\n            if all_globals[n] == module_ref:\n                return n + '.' + func_name\n        return func_name",
    "docstring": "Return the namespace path to the function"
  },
  {
    "code": "def connect(dsn=None, turbodbc_options=None, connection_string=None, **kwargs):\n    if turbodbc_options is None:\n        turbodbc_options = make_options()\n    if connection_string is not None and (dsn is not None or len(kwargs) > 0):\n        raise ParameterError(\"Both connection_string and dsn or kwargs specified\")\n    if connection_string is None:\n        connection_string = _make_connection_string(dsn, **kwargs)\n    connection = Connection(intern_connect(connection_string,\n                                           turbodbc_options))\n    return connection",
    "docstring": "Create a connection with the database identified by the ``dsn`` or the ``connection_string``.\n\n    :param dsn: Data source name as given in the (unix) odbc.ini file\n           or (Windows) ODBC Data Source Administrator tool.\n    :param turbodbc_options: Options that control how turbodbc interacts with the database.\n           Create such a struct with `turbodbc.make_options()` or leave this blank to take the defaults.\n    :param connection_string: Preformatted ODBC connection string.\n           Specifying this and dsn or kwargs at the same time raises ParameterError.\n    :param \\**kwargs: You may specify additional options as you please. These options will go into\n           the connection string that identifies the database. Valid options depend on the specific database you\n           would like to connect with (e.g. `user` and `password`, or `uid` and `pwd`)\n    :return: A connection to your database"
  },
  {
    "code": "def _send_and_receive(self, target, lun, netfn, cmdid, payload):\n        self._inc_sequence_number()\n        header = IpmbHeaderReq()\n        header.netfn = netfn\n        header.rs_lun = lun\n        header.rs_sa = target.ipmb_address\n        header.rq_seq = self.next_sequence_number\n        header.rq_lun = 0\n        header.rq_sa = self.slave_address\n        header.cmd_id = cmdid\n        retries = 0\n        while retries < self.max_retries:\n            try:\n                self._send_raw(header, payload)\n                rx_data = self._receive_raw(header)\n                break\n            except IpmiTimeoutError:\n                log().warning('I2C transaction timed out'),\n            retries += 1\n        else:\n            raise IpmiTimeoutError()\n        return rx_data.tostring()[5:-1]",
    "docstring": "Send and receive data using aardvark interface.\n\n        target:\n        lun:\n        netfn:\n        cmdid:\n        payload: IPMI message payload as bytestring\n\n        Returns the received data as bytestring"
  },
  {
    "code": "def all_simple_bb_paths(self, start_address, end_address):\n        bb_start = self._find_basic_block(start_address)\n        bb_end = self._find_basic_block(end_address)\n        paths = networkx.all_simple_paths(self._graph, source=bb_start.address, target=bb_end.address)\n        return ([self._bb_by_addr[addr] for addr in path] for path in paths)",
    "docstring": "Return a list of path between start and end address."
  },
  {
    "code": "def _formatNumbers(self, line):\n        if sys.version_info < (2, 7):\n            return line\n        last_index = 0\n        try:\n            last_index = (line.rindex('}') + 1)\n            end = line[last_index:]\n        except ValueError:\n            return line\n        else:\n            splitted = re.split(\"(\\d+)\", end)\n            for index, val in enumerate(splitted):\n                converted = 0\n                try:\n                    converted = int(val)\n                except ValueError:\n                    pass\n                else:\n                    if converted > 1000:\n                        splitted[index] = format(converted, \",d\")\n            return line[:last_index] + (\"\").join(splitted)",
    "docstring": "Format the numbers so that there are commas inserted.\n\n        For example: 1200300 becomes 1,200,300."
  },
  {
    "code": "def authorize_role(self, role, protocol, from_port, to_port, cidr_ip):\n    if (protocol != 'tcp' and protocol != 'udp'):\n      raise RuntimeError('error: expected protocol to be tcp or udp '\\\n                         'but got %s' % (protocol))\n    self._check_role_name(role)\n    role_group_name = self._group_name_for_role(role)\n    self.ec2.revoke_security_group(role_group_name,\n                                             ip_protocol=protocol,\n                                             from_port=from_port,\n                                             to_port=to_port, cidr_ip=cidr_ip)\n    self.ec2.authorize_security_group(role_group_name,\n                                                ip_protocol=protocol,\n                                                from_port=from_port,\n                                                to_port=to_port,\n                                                cidr_ip=cidr_ip)",
    "docstring": "Authorize access to machines in a given role from a given network."
  },
  {
    "code": "def comments(self, extra_params=None):\n        params = {\n            'per_page': settings.MAX_PER_PAGE,\n        }\n        if extra_params:\n            params.update(extra_params)\n        return self.api._get_json(\n            TicketComment,\n            space=self,\n            rel_path=self.space._build_rel_path(\n                'tickets/%s/ticket_comments' % self['number']\n            ),\n            extra_params=params,\n            get_all=True,\n        )",
    "docstring": "All Comments in this Ticket"
  },
  {
    "code": "def print_virt_table(self, data):\n        table = prettytable.PrettyTable()\n        keys = sorted(data.keys())\n        table.add_column('Keys', keys)\n        table.add_column('Values', [data.get(i) for i in keys])\n        for tbl in table.align.keys():\n            table.align[tbl] = 'l'\n        self.printer(table)",
    "docstring": "Print a vertical pretty table from data."
  },
  {
    "code": "def start(nick, host, port=6667, username=None, password=None, channels=None, use_ssl=False, use_sasl=False,\n          char='!', allow_hosts=False, allow_nicks=False, disable_query=True):\n    client = IRCClient(nick, host, port, username, password, channels or [], use_ssl, use_sasl, char,\n                       allow_hosts, allow_nicks, disable_query)\n    client.io_loop.start()",
    "docstring": "IRC Bot for interacting with salt.\n\n    nick\n        Nickname of the connected Bot.\n\n    host\n        irc server (example - chat.freenode.net).\n\n    port\n        irc port.  Default: 6667\n\n    password\n        password for authenticating.  If not provided, user will not authenticate on the irc server.\n\n    channels\n        channels to join.\n\n    use_ssl\n        connect to server using ssl. Default: False\n\n    use_sasl\n        authenticate using sasl, instead of messaging NickServ. Default: False\n\n        .. note:: This will allow the bot user to be fully authenticated before joining any channels\n\n    char\n        command character to look for. Default: !\n\n    allow_hosts\n        hostmasks allowed to use commands on the bot.  Default: False\n        True to allow all\n        False to allow none\n        List of regexes to allow matching\n\n    allow_nicks\n        Nicks that are allowed to use commands on the bot.  Default: False\n        True to allow all\n        False to allow none\n        List of regexes to allow matching\n\n    disable_query\n        Disable commands from being sent through private queries.  Require they be sent to a channel, so that all\n        communication can be controlled by access to the channel. Default: True\n\n    .. warning:: Unauthenticated Access to event stream\n\n        This engine sends events calls to the event stream without authenticating them in salt.  Authentication will\n        need to be configured and enforced on the irc server or enforced in the irc channel.  The engine only accepts\n        commands from channels, so non authenticated users could be banned or quieted in the channel.\n\n        /mode +q $~a  # quiet all users who are not authenticated\n        /mode +r      # do not allow unauthenticated users into the channel\n\n        It would also be possible to add a password to the irc channel, or only allow invited users to join."
  },
  {
    "code": "def new(self, rr_name):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('NM record already initialized!')\n        self.posix_name = rr_name\n        self.posix_name_flags = 0\n        self._initialized = True",
    "docstring": "Create a new Rock Ridge Alternate Name record.\n\n        Parameters:\n         rr_name - The name for the new record.\n        Returns:\n         Nothing."
  },
  {
    "code": "def _scatter(sequence, n):\n  chunklen = int(math.ceil(float(len(sequence)) / float(n)))\n  return [\n    sequence[ i*chunklen : (i+1)*chunklen ] for i in range(n)\n  ]",
    "docstring": "Scatters elements of ``sequence`` into ``n`` blocks."
  },
  {
    "code": "def _ancestors(\n            self, qname: Union[QualName, bool] = None) -> List[InstanceNode]:\n        return self.up()._ancestors(qname)",
    "docstring": "XPath - return the list of receiver's ancestors."
  },
  {
    "code": "def _update_loaded_modules(self):\n        system_modules = sys.modules.keys()\n        for module in list(self.loaded_modules):\n            if module not in system_modules:\n                self.processed_filepaths.pop(module)\n                self.loaded_modules.remove(module)",
    "docstring": "Updates the loaded modules by checking if they are still in sys.modules"
  },
  {
    "code": "def generate_documentation(self, app_name, **kwargs):\n        output_file = kwargs.get('output_file_name')\n        encoding = kwargs.get('encoding', 'utf-8')\n        doc_string = generate_markdown_doc(app_name, self)\n        if output_file:\n            with open(output_file, 'w', encoding=encoding) as doc_file:\n                doc_file.write(doc_string)\n        return doc_string",
    "docstring": "Generate documentation for this specification.\n\n        Documentation is generated in Markdown format. An example\n        of the generated documentation can be found at:\n\n        https://github.com/loganasherjones/yapconf/blob/master/example/doc.md\n\n        Args:\n            app_name (str): The name of your application.\n\n        Keyword Args:\n            output_file_name (str): If provided, will write to this file.\n            encoding (str): The encoding to use for the output file. Default\n            is utf-8.\n\n        Returns:\n            A string representation of the documentation."
  },
  {
    "code": "def list_orgs(self):\n        orgs = list(self.orgs.keys())\n        orgs.sort()\n        return orgs",
    "docstring": "list the orgs configured in the keychain"
  },
  {
    "code": "def cli(ctx, board, scons, project_dir, sayyes):\n    if scons:\n        Project().create_sconstruct(project_dir, sayyes)\n    elif board:\n        Project().create_ini(board, project_dir, sayyes)\n    else:\n        click.secho(ctx.get_help())",
    "docstring": "Manage apio projects."
  },
  {
    "code": "def extract_wav(datafile, target=None):\n    if datafile.endswith(\".wav\"):\n        return datafile\n    target = target or os.path.dirname(datafile) \n    if os.path.isdir(target):\n        target = os.path.join(target, os.path.splitext(os.path.basename(datafile))[0] + \".wav\")\n    if datafile.endswith(\".flac\"):\n        cmd = [config.CMD_FLAC, \"--silent\", \"--decode\", \"--force\", \"-o\", target, datafile]\n    else:\n        cmd = [config.CMD_FFMPEG, \"-v\", \"0\", \"-y\", \"-i\", datafile, \"-acodec\", \"pcm_s16le\", \"-ac\", \"2\", target]\n    subprocess.check_call(cmd, stdout=open(os.devnull, \"wb\"), stderr=subprocess.STDOUT)\n    return target",
    "docstring": "Get LPCM 16bit audio stream from mediafile.\n    \n        If `target` is a directory, create a .wav with the same basename as the input.\n        If target is empty, write to the directory of the source file. Otherwise, use it \n        directly as the target filename."
  },
  {
    "code": "def wait(self, timeout=-1):\n        if self._process is None:\n            raise RuntimeError('no child process')\n        if timeout == -1:\n            timeout = self._timeout\n        if not self._child_exited.wait(timeout):\n            raise Timeout('timeout waiting for child to exit')\n        return self.returncode",
    "docstring": "Wait for the child to exit.\n\n        Wait for at most *timeout* seconds, or indefinitely if *timeout* is\n        None. Return the value of the :attr:`returncode` attribute."
  },
  {
    "code": "def define_vol_xml_str(xml, **kwargs):\n    poolname = __salt__['config.get']('libvirt:storagepool', None)\n    if poolname is not None:\n        salt.utils.versions.warn_until(\n            'Sodium',\n            '\\'libvirt:storagepool\\' has been deprecated in favor of '\n            '\\'virt:storagepool\\'. \\'libvirt:storagepool\\' will stop '\n            'being used in {version}.'\n        )\n    else:\n        poolname = __salt__['config.get']('virt:storagepool', 'default')\n    conn = __get_conn(**kwargs)\n    pool = conn.storagePoolLookupByName(six.text_type(poolname))\n    ret = pool.createXML(xml, 0) is not None\n    conn.close()\n    return ret",
    "docstring": "Define a volume based on the XML passed to the function\n\n    :param xml: libvirt XML definition of the storage volume\n    :param connection: libvirt connection URI, overriding defaults\n\n        .. versionadded:: 2019.2.0\n    :param username: username to connect with, overriding defaults\n\n        .. versionadded:: 2019.2.0\n    :param password: password to connect with, overriding defaults\n\n        .. versionadded:: 2019.2.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' virt.define_vol_xml_str <XML in string format>\n\n    The storage pool where the disk image will be defined is ``default``\n    unless changed with a configuration like this:\n\n    .. code-block:: yaml\n\n        virt:\n            storagepool: mine"
  },
  {
    "code": "def on_packet(self, packet_type):\n        def _wrapper(fn):\n            return self.callbacks.register(packet_type, fn)\n        return _wrapper",
    "docstring": "Registers a function to be called when packet data is received with a\n        specific type."
  },
  {
    "code": "def ask(question):\n    while True:\n        ans = input(question)\n        al = ans.lower()\n        if match('^y(es)?$', al):\n            return True\n        elif match('^n(o)?$', al):\n            return False\n        elif match('^q(uit)?$', al):\n            stdout.write(CYAN)\n            print(\"\\nGoodbye.\\n\")\n            stdout.write(RESET)\n            quit()\n        else:\n            stdout.write(RED)\n            print(\"%s is invalid. Enter (y)es, (n)o or (q)uit.\" % ans)\n            stdout.write(RESET)",
    "docstring": "Infinite loop to get yes or no answer or quit the script."
  },
  {
    "code": "def auto_memoize(func):\n    @wraps(func)\n    def wrapper(*args):\n        inst = args[0]\n        inst._memoized_values = getattr(inst, '_memoized_values', {})\n        key = (func, args[1:])\n        if key not in inst._memoized_values:\n            inst._memoized_values[key] = func(*args)\n        return inst._memoized_values[key]\n    return wrapper",
    "docstring": "Based on django.util.functional.memoize. Automatically memoizes instace methods for the lifespan of an object.\n    Only works with methods taking non-keword arguments. Note that the args to the function must be usable as\n    dictionary keys. Also, the first argument MUST be self. This decorator will not work for functions or class\n    methods, only object methods."
  },
  {
    "code": "def is_pointer(self, address):\n        try:\n            mbi = self.mquery(address)\n        except WindowsError:\n            e = sys.exc_info()[1]\n            if e.winerror == win32.ERROR_INVALID_PARAMETER:\n                return False\n            raise\n        return mbi.has_content()",
    "docstring": "Determines if an address is a valid code or data pointer.\n\n        That is, the address must be valid and must point to code or data in\n        the target process.\n\n        @type  address: int\n        @param address: Memory address to query.\n\n        @rtype:  bool\n        @return: C{True} if the address is a valid code or data pointer.\n\n        @raise WindowsError: An exception is raised on error."
  },
  {
    "code": "def _set_data(self, action):\n        data = self._load_response(action)\n        self._handle_continuations(data, 'category')\n        if action == 'category':\n            members = data.get('query').get('categorymembers')\n            if members:\n                self._add_members(members)\n        if action == 'random':\n            rand = data['query']['random'][0]\n            data = {'pageid': rand.get('id'),\n                    'title': rand.get('title')}\n            self.data.update(data)\n            self.params.update(data)",
    "docstring": "Set category member data from API response"
  },
  {
    "code": "def save_ical(self, ical_location):\n        data = self.cal.to_ical()\n        with open(ical_location, 'w') as ical_file:\n            ical_file.write(data.decode('utf-8'))",
    "docstring": "Save the calendar instance to a file"
  },
  {
    "code": "def create_site(sitename):\n    sitepath = os.path.join(CWD, sitename)\n    if os.path.isdir(sitepath):\n        print(\"Site directory '%s' exists already!\" % sitename)\n    else:\n        print(\"Creating site: %s...\" % sitename)\n        os.makedirs(sitepath)\n        copy_resource(\"skel/\", sitepath)\n        stamp_yass_current_version(sitepath)\n        print(\"Site created successfully!\")\n        print(\"CD into '%s' and run 'yass serve' to view the site\" % sitename)\n    footer()",
    "docstring": "Create a new site directory and init Yass"
  },
  {
    "code": "def output(self):\n        if self._timeseries is None:\n            self.compute()\n        output = self._timeseries[:, self.system.output_vars]\n        if isinstance(self.system, NetworkModel):\n            return self.system._reshape_output(output)\n        else:\n            return output",
    "docstring": "Simulated model output"
  },
  {
    "code": "def rebase(upstream, branch=None):\n    rebase_branch = branch and branch or current_branch()\n    with git_continuer(run, 'rebase --continue', no_edit=True):\n        stdout = run('rebase %s %s' % (upstream, rebase_branch))\n        return 'Applying' in stdout",
    "docstring": "Rebase branch onto upstream\n\n    If branch is empty, use current branch"
  },
  {
    "code": "def num_plates_ET(q_plant, W_chan):\n    num_plates = np.ceil(np.sqrt(q_plant / (design.ent_tank.CENTER_PLATE_DIST.magnitude\n                                            * W_chan * design.ent_tank.CAPTURE_BOD_VEL.magnitude * np.sin(\n                design.ent_tank.PLATE_ANGLE.to(u.rad).magnitude))))\n    return num_plates",
    "docstring": "Return the number of plates in the entrance tank.\n\n    This number minimizes the total length of the plate settler unit.\n\n    Parameters\n    ----------\n    q_plant: float\n        Plant flow rate\n\n    W_chan: float\n        Width of channel\n\n    Returns\n    -------\n    float\n        ?\n\n    Examples\n    --------\n    >>> from aguaclara.play import*\n    >>> num_plates_ET(20*u.L/u.s,2*u.m)\n    1.0"
  },
  {
    "code": "def start_waiting(self):\n        if not self.waiting:\n            self.waiting = True\n            wait_msg = \"Waiting for project to become ready for {}\".format(self.msg_verb)\n            self.progress_bar.show_waiting(wait_msg)",
    "docstring": "Show waiting progress bar until done_waiting is called.\n        Only has an effect if we are in waiting state."
  },
  {
    "code": "def shard_id(self):\n        count = self._state.shard_count\n        if count is None:\n            return None\n        return (self.id >> 22) % count",
    "docstring": "Returns the shard ID for this guild if applicable."
  },
  {
    "code": "def add_op_create_erasure_pool(self, name, erasure_profile=None,\n                                   weight=None, group=None, app_name=None,\n                                   max_bytes=None, max_objects=None):\n        self.ops.append({'op': 'create-pool', 'name': name,\n                         'pool-type': 'erasure',\n                         'erasure-profile': erasure_profile,\n                         'weight': weight,\n                         'group': group, 'app-name': app_name,\n                         'max-bytes': max_bytes, 'max-objects': max_objects})",
    "docstring": "Adds an operation to create a erasure coded pool.\n\n        :param name: Name of pool to create\n        :type name: str\n        :param erasure_profile: Name of erasure code profile to use.  If not\n                                set the ceph-mon unit handling the broker\n                                request will set its default value.\n        :type erasure_profile: str\n        :param weight: The percentage of data that is expected to be contained\n                       in the pool from the total available space on the OSDs.\n        :type weight: float\n        :param group: Group to add pool to\n        :type group: str\n        :param app_name: (Optional) Tag pool with application name.  Note that\n                         there is certain protocols emerging upstream with\n                         regard to meaningful application names to use.\n                         Examples are ``rbd`` and ``rgw``.\n        :type app_name: str\n        :param max_bytes: Maximum bytes quota to apply\n        :type max_bytes: int\n        :param max_objects: Maximum objects quota to apply\n        :type max_objects: int"
  },
  {
    "code": "def stop(self):\n        self._done()\n        if self._server:\n            self._server.stop()\n            self._server = None\n        log.info('Stop!')",
    "docstring": "Stop all tasks, and the local proxy server if it's running."
  },
  {
    "code": "def get_var_properties(self):\n        from spyder_kernels.utils.nsview import get_remote_data\n        settings = self.namespace_view_settings\n        if settings:\n            ns = self._get_current_namespace()\n            data = get_remote_data(ns, settings, mode='editable',\n                                   more_excluded_names=EXCLUDED_NAMES)\n            properties = {}\n            for name, value in list(data.items()):\n                properties[name] = {\n                    'is_list':  isinstance(value, (tuple, list)),\n                    'is_dict':  isinstance(value, dict),\n                    'is_set': isinstance(value, set),\n                    'len': self._get_len(value),\n                    'is_array': self._is_array(value),\n                    'is_image': self._is_image(value),\n                    'is_data_frame': self._is_data_frame(value),\n                    'is_series': self._is_series(value),\n                    'array_shape': self._get_array_shape(value),\n                    'array_ndim': self._get_array_ndim(value)\n                }\n            return repr(properties)\n        else:\n            return repr(None)",
    "docstring": "Get some properties of the variables in the current\n        namespace"
  },
  {
    "code": "def local_bind_hosts(self):\n        self._check_is_started()\n        return [_server.local_host for _server in self._server_list if\n                _server.local_host is not None]",
    "docstring": "Return a list containing the IP addresses listening for the tunnels"
  },
  {
    "code": "def get_signature_names(self):\n        signature_expr = re.compile(\"^(META-INF/)(.*)(\\.RSA|\\.EC|\\.DSA)$\")\n        signatures = []\n        for i in self.get_files():\n            if signature_expr.search(i):\n                signatures.append(i)\n        if len(signatures) > 0:\n            return signatures\n        return None",
    "docstring": "Return a list of the signature file names."
  },
  {
    "code": "def batch_stream(buff, stream, size=DEFAULT_BATCH_SIZE):\n    buff.truncate(0)\n    for _ in xrange(size):\n        if hasattr(stream, 'readline'):\n            line = stream.readline()\n        else:\n            try:\n                line = next(stream)\n            except StopIteration:\n                line = ''\n        if line == '':\n            buff.seek(0)\n            return True\n        buff.write(line)\n    buff.seek(0)\n    return False",
    "docstring": "Writes a batch of `size` lines to `buff`.\n\n    Returns boolean of whether the stream has been exhausted."
  },
  {
    "code": "def _setattr_default(obj, attr, value, default):\n    if value is None:\n        setattr(obj, attr, default)\n    else:\n        setattr(obj, attr, value)",
    "docstring": "Set an attribute of an object to a value or default value."
  },
  {
    "code": "def replace_markdown_cells(src, dst):\n    if len(src['cells']) != len(dst['cells']):\n        raise ValueError('notebooks do not have the same number of cells')\n    for n in range(len(src['cells'])):\n        if src['cells'][n]['cell_type'] != dst['cells'][n]['cell_type']:\n            raise ValueError('cell number %d of different type in src and dst')\n        if src['cells'][n]['cell_type'] == 'markdown':\n            dst['cells'][n]['source'] = src['cells'][n]['source']",
    "docstring": "Overwrite markdown cells in notebook object `dst` with corresponding\n    cells in notebook object `src`."
  },
  {
    "code": "def transitive_reduction(G):\n    H = G.copy()\n    for a, b, w in G.edges_iter(data=True):\n        H.remove_edge(a, b)\n        if not nx.has_path(H, a, b):\n            H.add_edge(a, b, w)\n    return H",
    "docstring": "Returns a transitive reduction of a graph.  The original graph\n    is not modified.\n\n    A transitive reduction H of G has a path from x to y if and\n    only if there was a path from x to y in G.  Deleting any edge\n    of H destroys this property.  A transitive reduction is not\n    unique in general.  A transitive reduction has the same\n    transitive closure as the original graph.\n\n    A transitive reduction of a complete graph is a tree.  A\n    transitive reduction of a tree is itself.\n\n    >>> G = nx.DiGraph([(1, 2), (1, 3), (2, 3), (2, 4), (3, 4)])\n    >>> H = transitive_reduction(G)\n    >>> H.edges()\n    [(1, 2), (2, 3), (3, 4)]"
  },
  {
    "code": "def save_initial_state(self):\n        paths = self.paths\n        self.initial_widget = self.get_widget()\n        self.initial_cursors = {}\n        for i, editor in enumerate(self.widgets):\n            if editor is self.initial_widget:\n                self.initial_path = paths[i]\n            try:\n                self.initial_cursors[paths[i]] = editor.textCursor()\n            except AttributeError:\n                pass",
    "docstring": "Save initial cursors and initial active widget."
  },
  {
    "code": "def extract_backup_bundle(self, resource, timeout=-1):\n        return self._client.update(resource, uri=self.BACKUP_ARCHIVE_PATH, timeout=timeout)",
    "docstring": "Extracts the existing backup bundle on the appliance and creates all the artifacts.\n\n        Args:\n            resource (dict): Deployment Group to extract.\n            timeout:\n                Timeout in seconds. Waits for task completion by default. The timeout does not abort the operation in\n                OneView, it just stops waiting for its completion.\n\n        Returns:\n            dict: A Deployment Group associated with the Artifact Bundle backup."
  },
  {
    "code": "def _dispatch_handler(args, cell, parser, handler, cell_required=False,\n                      cell_prohibited=False):\n  if cell_prohibited:\n    if cell and len(cell.strip()):\n      parser.print_help()\n      raise Exception(\n          'Additional data is not supported with the %s command.' % parser.prog)\n    return handler(args)\n  if cell_required and not cell:\n    parser.print_help()\n    raise Exception('The %s command requires additional data' % parser.prog)\n  return handler(args, cell)",
    "docstring": "Makes sure cell magics include cell and line magics don't, before\n    dispatching to handler.\n\n  Args:\n    args: the parsed arguments from the magic line.\n    cell: the contents of the cell, if any.\n    parser: the argument parser for <cmd>; used for error message.\n    handler: the handler to call if the cell present/absent check passes.\n    cell_required: True for cell magics, False for line magics that can't be\n      cell magics.\n    cell_prohibited: True for line magics, False for cell magics that can't be\n      line magics.\n  Returns:\n    The result of calling the handler.\n  Raises:\n    Exception if the invocation is not valid."
  },
  {
    "code": "def create(\n    name,\n    create_file,\n    open_file,\n    remove_file,\n    create_directory,\n    list_directory,\n    remove_empty_directory,\n    temporary_directory,\n    stat,\n    lstat,\n    link,\n    readlink,\n    realpath=_realpath,\n    remove=_recursive_remove,\n):\n    methods = dict(\n        create=create_file,\n        open=lambda fs, path, mode=\"r\": open_file(\n            fs=fs, path=path, mode=mode,\n        ),\n        remove_file=remove_file,\n        create_directory=create_directory,\n        list_directory=list_directory,\n        remove_empty_directory=remove_empty_directory,\n        temporary_directory=temporary_directory,\n        get_contents=_get_contents,\n        set_contents=_set_contents,\n        create_with_contents=_create_with_contents,\n        remove=remove,\n        removing=_removing,\n        stat=stat,\n        lstat=lstat,\n        link=link,\n        readlink=readlink,\n        realpath=realpath,\n        exists=_exists,\n        is_dir=_is_dir,\n        is_file=_is_file,\n        is_link=_is_link,\n        touch=_touch,\n        children=_children,\n        glob_children=_glob_children,\n    )\n    return attr.s(hash=True)(type(name, (object,), methods))",
    "docstring": "Create a new kind of filesystem."
  },
  {
    "code": "def vrfs_get(self, subcommand='routes', route_dist=None,\n                 route_family='all', format='json'):\n        show = {\n            'format': format,\n        }\n        if route_family in SUPPORTED_VRF_RF:\n            assert route_dist is not None\n            show['params'] = ['vrf', subcommand, route_dist, route_family]\n        else:\n            show['params'] = ['vrf', subcommand, 'all']\n        return call('operator.show', **show)",
    "docstring": "This method returns the existing vrfs.\n\n        ``subcommand`` specifies one of the following.\n\n        - 'routes': shows routes present for vrf\n        - 'summary': shows configuration and summary of vrf\n\n        ``route_dist`` specifies a route distinguisher value.\n        If route_family is not 'all', this value must be specified.\n\n        ``route_family`` specifies route family of the VRF.\n        This parameter must be one of the following.\n\n        - RF_VPN_V4  = 'ipv4'\n        - RF_VPN_V6  = 'ipv6'\n        - RF_L2_EVPN = 'evpn'\n        - 'all' (default)\n\n        ``format`` specifies the format of the response.\n        This parameter must be one of the following.\n\n        - 'json' (default)\n        - 'cli'"
  },
  {
    "code": "def _before_request(self):\n        if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):\n            return\n        try:\n            span_context = self.propagator.from_headers(flask.request.headers)\n            tracer = tracer_module.Tracer(\n                span_context=span_context,\n                sampler=self.sampler,\n                exporter=self.exporter,\n                propagator=self.propagator)\n            span = tracer.start_span()\n            span.span_kind = span_module.SpanKind.SERVER\n            span.name = '[{}]{}'.format(\n                flask.request.method,\n                flask.request.url)\n            tracer.add_attribute_to_current_span(\n                HTTP_METHOD, flask.request.method)\n            tracer.add_attribute_to_current_span(\n                HTTP_URL, str(flask.request.url))\n            execution_context.set_opencensus_attr(\n                'blacklist_hostnames',\n                self.blacklist_hostnames)\n        except Exception:\n            log.error('Failed to trace request', exc_info=True)",
    "docstring": "A function to be run before each request.\n\n        See: http://flask.pocoo.org/docs/0.12/api/#flask.Flask.before_request"
  },
  {
    "code": "def atmospheric_station_pressure(self, value=999999):\n        if value is not None:\n            try:\n                value = int(value)\n            except ValueError:\n                raise ValueError(\n                    'value {} need to be of type int '\n                    'for field `atmospheric_station_pressure`'.format(value))\n            if value <= 31000:\n                raise ValueError('value need to be greater 31000 '\n                                 'for field `atmospheric_station_pressure`')\n            if value >= 120000:\n                raise ValueError('value need to be smaller 120000 '\n                                 'for field `atmospheric_station_pressure`')\n        self._atmospheric_station_pressure = value",
    "docstring": "Corresponds to IDD Field `atmospheric_station_pressure`\n\n        Args:\n            value (int): value for IDD Field `atmospheric_station_pressure`\n                Unit: Pa\n                value > 31000\n                value < 120000\n                Missing value: 999999\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def _loadSources(self):\n        self.confstems = {}\n        self.sourceDict = newtrigdict.Trigdict()\n        for fName in self.authorityFiles:\n            self._loadOneSource(fName)\n        for stem in self.sourceDict.values():\n            cleanStem = stem.replace(\".\", \"\").upper()\n            self._addPub(stem, cleanStem)",
    "docstring": "creates a trigdict and populates it with data from self.autorityFiles"
  },
  {
    "code": "async def set_state(self, parameter):\n        command_send = CommandSend(pyvlx=self.pyvlx, node_id=self.node_id, parameter=parameter)\n        await command_send.do_api_call()\n        if not command_send.success:\n            raise PyVLXException(\"Unable to send command\")\n        self.parameter = parameter\n        await self.after_update()",
    "docstring": "Set switch to desired state."
  },
  {
    "code": "def get_handlerecord_indices_for_key(self, key, list_of_entries):\n        LOGGER.debug('get_handlerecord_indices_for_key...')\n        indices = []\n        for entry in list_of_entries:\n            if entry['type'] == key:\n                indices.append(entry['index'])\n        return indices",
    "docstring": "Finds the Handle entry indices of all entries that have a specific\n        type.\n\n        *Important:* It finds the Handle System indices! These are not\n        the python indices of the list, so they can not be used for\n        iteration.\n\n        :param key: The key (Handle Record type)\n        :param list_of_entries: A list of the existing entries in which to find\n            the indices.\n        :return: A list of strings, the indices of the entries of type \"key\" in\n            the given handle record."
  },
  {
    "code": "def exclude_package(cls, package_name=None, recursive=False):\n    if not package_name:\n      return Shading.create_exclude('**' if recursive else '*')\n    return Shading.create_exclude_package(package_name, recursive=recursive)",
    "docstring": "Excludes the given fully qualified package name from shading.\n\n    :param unicode package_name: A fully qualified package_name; eg: `org.pantsbuild`; `None` for\n                                the java default (root) package.\n    :param bool recursive: `True` to exclude any package with `package_name` as a proper prefix;\n                           `False` by default.\n    :returns: A `Shader.Rule` describing the shading exclusion."
  },
  {
    "code": "def du(*components, **kwargs):\n    human_readable = kwargs.get(\"human_readable\", True)\n    _path = path(*components)\n    if not exists(_path):\n        raise Error(\"file '{}' not found\".format(_path))\n    size = os.stat(_path).st_size\n    if human_readable:\n        return naturalsize(size)\n    else:\n        return size",
    "docstring": "Get the size of a file in bytes or as a human-readable string.\n\n    Arguments:\n\n        *components (str[]): Path to file.\n        **kwargs: If \"human_readable\" is True, return a formatted string,\n          e.g. \"976.6 KiB\" (default True)\n\n    Returns:\n        int or str: If \"human_readble\" kwarg is True, return str, else int."
  },
  {
    "code": "def anchorCompute(self, anchorInput, learn):\n    if learn:\n      self._anchorComputeLearningMode(anchorInput)\n    else:\n      overlaps = self.anchorConnections.computeActivity(\n        anchorInput, self.connectedPermanence)\n      self.activeSegments = np.where(overlaps >= self.activationThreshold)[0]\n      self.activeCells = np.unique(\n        self.anchorConnections.mapSegmentsToCells(self.activeSegments))",
    "docstring": "Compute the\n      \"sensor's location relative to a specific object\"\n    from the feature-location pair.\n\n    @param anchorInput (numpy array)\n    Active cells in the feature-location pair layer\n\n    @param learn (bool)\n    If true, maintain current cell activity and learn this input on the\n    currently active cells"
  },
  {
    "code": "def value_to_bytes(self, obj, value, default_endianness=DEFAULT_ENDIANNESS):\n        return struct.pack(str(self.endianness or default_endianness) + self.struct_format, value)",
    "docstring": "Converts the given value to an appropriately encoded string of bytes that represents it.\n\n        :param obj: The parent :class:`.PebblePacket` of this field\n        :type obj: .PebblePacket\n        :param value: The python value to serialise.\n        :param default_endianness: The default endianness of the value. Used if ``endianness`` was not passed to the\n                                   :class:`Field` constructor.\n        :type default_endianness: str\n        :return: The serialised value\n        :rtype: bytes"
  },
  {
    "code": "def resolve(self, key, is_local):\n        try:\n            if is_local:\n                return self.scope[key]\n            if self.has_resolvers:\n                return self.resolvers[key]\n            assert not is_local and not self.has_resolvers\n            return self.scope[key]\n        except KeyError:\n            try:\n                return self.temps[key]\n            except KeyError:\n                raise compu.ops.UndefinedVariableError(key, is_local)",
    "docstring": "Resolve a variable name in a possibly local context\n\n        Parameters\n        ----------\n        key : str\n            A variable name\n        is_local : bool\n            Flag indicating whether the variable is local or not (prefixed with\n            the '@' symbol)\n\n        Returns\n        -------\n        value : object\n            The value of a particular variable"
  },
  {
    "code": "def _GetCurrentControlSet(self, key_path_suffix):\n    select_key_path = 'HKEY_LOCAL_MACHINE\\\\System\\\\Select'\n    select_key = self.GetKeyByPath(select_key_path)\n    if not select_key:\n      return None\n    control_set = None\n    for value_name in ('Current', 'Default', 'LastKnownGood'):\n      value = select_key.GetValueByName(value_name)\n      if not value or not value.DataIsInteger():\n        continue\n      control_set = value.GetDataAsObject()\n      if control_set > 0 or control_set <= 999:\n        break\n    if not control_set or control_set <= 0 or control_set > 999:\n      return None\n    control_set_path = 'HKEY_LOCAL_MACHINE\\\\System\\\\ControlSet{0:03d}'.format(\n        control_set)\n    key_path = ''.join([control_set_path, key_path_suffix])\n    return self.GetKeyByPath(key_path)",
    "docstring": "Virtual key callback to determine the current control set.\n\n    Args:\n      key_path_suffix (str): current control set Windows Registry key path\n          suffix with leading path separator.\n\n    Returns:\n      WinRegistryKey: the current control set Windows Registry key or None\n          if not available."
  },
  {
    "code": "def notebook_authenticate(cmd_args, force=False, silent=True):\n    server = server_url(cmd_args)\n    network.check_ssl()\n    access_token = None\n    if not force:\n        try:\n            access_token = refresh_local_token(server)\n        except OAuthException as e:\n            if not silent:\n                raise e\n            return notebook_authenticate(cmd_args, force=True, silent=False)\n    if not access_token:\n        access_token = perform_oauth(\n            get_code_via_terminal,\n            cmd_args,\n            copy_msg=NOTEBOOK_COPY_MESSAGE,\n            paste_msg=NOTEBOOK_PASTE_MESSAGE)\n    email = display_student_email(cmd_args, access_token)\n    if email is None and not force:\n        return notebook_authenticate(cmd_args, force=True)\n    elif email is None:\n        log.warning('Could not get login email. You may have been logged out. '\n                    ' Try logging in again.')\n    return access_token",
    "docstring": "Similiar to authenticate but prints student emails after\n    all calls and uses a different way to get codes. If SILENT is True,\n    it will suppress the error message and redirect to FORCE=True"
  },
  {
    "code": "def strip_glob(string, split_str=' '):\n    string = _GLOB_PORTION_RE.sub(split_str, string)\n    return string.strip()",
    "docstring": "Strip glob portion in `string`.\n\n    >>> strip_glob('*glob*like')\n    'glob like'\n    >>> strip_glob('glob?')\n    'glo'\n    >>> strip_glob('glob[seq]')\n    'glob'\n    >>> strip_glob('glob[!seq]')\n    'glob'\n\n    :type string: str\n    :rtype: str"
  },
  {
    "code": "def _add(self, name, *args, **kw):\n        argname = list(self.argdict)[self._argno]\n        if argname != name:\n            raise NameError(\n                'Setting argument %s, but it should be %s' % (name, argname))\n        self._group.add_argument(*args, **kw)\n        self.all_arguments.append((args, kw))\n        self.names.append(name)\n        self._argno += 1",
    "docstring": "Add an argument to the underlying parser and grow the list\n        .all_arguments and the set .names"
  },
  {
    "code": "def eval_facet_vars(data, vars, env):\n    def I(value):\n        return value\n    env = env.with_outer_namespace({'I': I})\n    facet_vals = pd.DataFrame(index=data.index)\n    for name in vars:\n        if name in data:\n            res = data[name]\n        elif str.isidentifier(name):\n            continue\n        else:\n            try:\n                res = env.eval(name, inner_namespace=data)\n            except NameError:\n                continue\n        facet_vals[name] = res\n    return facet_vals",
    "docstring": "Evaluate facet variables\n\n    Parameters\n    ----------\n    data : DataFrame\n        Factet dataframe\n    vars : list\n        Facet variables\n    env : environment\n        Plot environment\n\n    Returns\n    -------\n    facet_vals : DataFrame\n        Facet values that correspond to the specified\n        variables."
  },
  {
    "code": "def resize_to_contents(self):\r\n        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))\r\n        self.resizeColumnsToContents()\r\n        self.model().fetch_more(columns=True)\r\n        self.resizeColumnsToContents()\r\n        QApplication.restoreOverrideCursor()",
    "docstring": "Resize cells to contents"
  },
  {
    "code": "def random_dois(self, sample = 10, **kwargs):\n        res = request(self.mailto, self.base_url, \"/works/\", None,\n            None, None, None, None, sample, None,\n            None, None, None, True, None, None, None, **kwargs)\n        return [ z['DOI'] for z in res['message']['items'] ]",
    "docstring": "Get a random set of DOIs\n\n        :param sample: [Fixnum] Number of random DOIs to return. Default: 10. Max: 100\n        :param kwargs: additional named arguments passed on to `requests.get`, e.g., field\n            queries (see examples)\n\n        :return: [Array] of DOIs\n\n        Usage::\n\n            from habanero import Crossref\n            cr = Crossref()\n            cr.random_dois(1)\n            cr.random_dois(10)\n            cr.random_dois(50)\n            cr.random_dois(100)"
  },
  {
    "code": "def readlink(path):\n    if sys.getwindowsversion().major < 6:\n        raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')\n    try:\n        return salt.utils.path.readlink(path)\n    except OSError as exc:\n        if exc.errno == errno.EINVAL:\n            raise CommandExecutionError('{0} is not a symbolic link'.format(path))\n        raise CommandExecutionError(exc.__str__())\n    except Exception as exc:\n        raise CommandExecutionError(exc)",
    "docstring": "Return the path that a symlink points to\n\n    This is only supported on Windows Vista or later.\n\n    Inline with Unix behavior, this function will raise an error if the path is\n    not a symlink, however, the error raised will be a SaltInvocationError, not\n    an OSError.\n\n    Args:\n        path (str): The path to the symlink\n\n    Returns:\n        str: The path that the symlink points to\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' file.readlink /path/to/link"
  },
  {
    "code": "def check_schedule():\n    all_items = prefetch_schedule_items()\n    for validator, _type, _msg in SCHEDULE_ITEM_VALIDATORS:\n        if validator(all_items):\n            return False\n    all_slots = prefetch_slots()\n    for validator, _type, _msg in SLOT_VALIDATORS:\n        if validator(all_slots):\n            return False\n    return True",
    "docstring": "Helper routine to easily test if the schedule is valid"
  },
  {
    "code": "def delist(values):\n    assert isinstance(values, list)\n    if not values:\n        return None\n    elif len(values) == 1:\n        return values[0]\n    return values",
    "docstring": "Reduce lists of zero or one elements to individual values."
  },
  {
    "code": "def render(self):\n        return Markup(env.get_template('form.html').render(form=self,\n                                                           render_open_tag=True,\n                                                           render_close_tag=True,\n                                                           render_before=True,\n                                                           render_sections=True,\n                                                           render_after=True,\n                                                           generate_csrf_token=None if self.disable_csrf else _csrf_generation_function))",
    "docstring": "Render the form and all sections to HTML"
  },
  {
    "code": "async def items(self):\n        accumulator = Accumulator()\n        for graft in load_grafts():\n            accumulator.spawn(graft())\n        response = await accumulator.join()\n        return response.items()",
    "docstring": "Expose all grafts."
  },
  {
    "code": "def query(self, value):\n        if not isinstance(value, Q):\n            raise Exception('Must only be passed a Django (Q)uery object')\n        s = QSerializer(base64=True)\n        self.b64_query = s.dumps(value)",
    "docstring": "Serialize an ORM query, Base-64 encode it and set it to\n        the b64_query field"
  },
  {
    "code": "def power_chisq_at_points_from_precomputed(corr, snr, snr_norm, bins, indices):\n    num_bins = len(bins) - 1\n    chisq = shift_sum(corr, indices, bins)\n    return (chisq * num_bins - (snr.conj() * snr).real) * (snr_norm ** 2.0)",
    "docstring": "Calculate the chisq timeseries from precomputed values for only select points.\n\n    This function calculates the chisq at each point by explicitly time shifting\n    and summing each bin. No FFT is involved.\n\n    Parameters\n    ----------\n    corr: FrequencySeries\n        The product of the template and data in the frequency domain.\n    snr: numpy.ndarray\n        The unnormalized array of snr values at only the selected points in `indices`.\n    snr_norm: float\n        The normalization of the snr (EXPLAINME : refer to Findchirp paper?)\n    bins: List of integers\n        The edges of the equal power bins\n    indices: Array\n        The indices where we will calculate the chisq. These must be relative\n        to the given `corr` series.\n\n    Returns\n    -------\n    chisq: Array\n        An array containing only the chisq at the selected points."
  },
  {
    "code": "def end_output (self, **kwargs):\n        if self.has_part(\"stats\"):\n            self.write_stats()\n        if self.has_part(\"outro\"):\n            self.write_outro()\n        self.close_fileoutput()",
    "docstring": "Write end of checking info as HTML."
  },
  {
    "code": "def get_cdn_log_retention(self, container):\n        resp, resp_body = self.api.cdn_request(\"/%s\" %\n                utils.get_name(container), method=\"HEAD\")\n        return resp.headers.get(\"x-log-retention\").lower() == \"true\"",
    "docstring": "Returns the status of the setting for CDN log retention for the\n        specified container."
  },
  {
    "code": "def haarpsi_weight_map(img1, img2, axis):\n    r\n    impl = 'pyfftw' if PYFFTW_AVAILABLE else 'numpy'\n    dec_lo_lvl3 = np.repeat([np.sqrt(2), np.sqrt(2)], 4)\n    dec_hi_lvl3 = np.repeat([-np.sqrt(2), np.sqrt(2)], 4)\n    if axis == 0:\n        fh_lvl3 = dec_hi_lvl3\n        fv_lvl3 = dec_lo_lvl3\n    elif axis == 1:\n        fh_lvl3 = dec_lo_lvl3\n        fv_lvl3 = dec_hi_lvl3\n    else:\n        raise ValueError('`axis` out of the valid range 0 -> 1')\n    img1_lvl3 = filter_image_sep2d(img1, fh_lvl3, fv_lvl3, impl=impl)\n    img2_lvl3 = filter_image_sep2d(img2, fh_lvl3, fv_lvl3, impl=impl)\n    np.abs(img1_lvl3, out=img1_lvl3)\n    np.abs(img2_lvl3, out=img2_lvl3)\n    return np.maximum(img1_lvl3, img2_lvl3)",
    "docstring": "r\"\"\"Weighting map for directional features along an axis.\n\n    Parameters\n    ----------\n    img1, img2 : array-like\n        The images to compare. They must have equal shape.\n    axis : {0, 1}\n        Direction in which to look for edge similarities.\n\n    Returns\n    -------\n    weight_map : `numpy.ndarray`\n        The pointwise weight map. See Notes for details.\n\n    Notes\n    -----\n    The pointwise weight map of associated with input images :math:`f_1, f_2`\n    and axis :math:`k` is defined\n    as\n\n    .. math::\n        \\mathrm{W}_{f_1, f_2}^{(k)}(x) =\n        \\max \\left\\{\n            \\left|g_3^{(k)} \\ast f_1 \\right|(x),\n            \\left|g_3^{(k)} \\ast f_2 \\right|(x)\n        \\right\\},\n\n    see `[Rei+2016] <https://arxiv.org/abs/1607.06140>`_ equations (11)\n    and (13).\n\n    Here, :math:`g_3^{(k)}` is a Haar wavelet filter for scaling level 3\n    that performs high-pass filtering in axis :math:`k` and low-pass\n    filtering in the other axes. Such a filter can be computed as ::\n\n        f_lo_level1 = [np.sqrt(2), np.sqrt(2)] # low-pass Haar filter\n        f_hi_level1 = [-np.sqrt(2), np.sqrt(2)] # high-pass Haar filter\n        f_lo_level3 = np.repeat(f_lo_level1, 4)\n        f_hi_level3 = np.repeat(f_hi_level1, 4)\n\n    References\n    ----------\n    [Rei+2016] Reisenhofer, R, Bosse, S, Kutyniok, G, and Wiegand, T.\n    *A Haar Wavelet-Based Perceptual Similarity Index for Image Quality\n    Assessment*. arXiv:1607.06140 [cs], Jul. 2016."
  },
  {
    "code": "def body(self, **kwargs):\n        text_content, html_content = None, None\n        if self.plain:\n            text_content = mold.cast(self.plain, **kwargs)\n        if self.html:\n            html_content = mold.cast(self.html, **kwargs)\n        return text_content, html_content",
    "docstring": "Return the plain and html versions of our contents.\n\n        Return: tuple\n        Exceptions: None"
  },
  {
    "code": "def block(self, **kwargs):\n        path = '/users/%s/block' % self.id\n        server_data = self.manager.gitlab.http_post(path, **kwargs)\n        if server_data is True:\n            self._attrs['state'] = 'blocked'\n        return server_data",
    "docstring": "Block the user.\n\n        Args:\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabBlockError: If the user could not be blocked\n\n        Returns:\n            bool: Whether the user status has been changed"
  },
  {
    "code": "def getProcessor(self, request):\n        if request.target == 'null' or not request.target:\n            from pyamf.remoting import amf3\n            return amf3.RequestProcessor(self)\n        else:\n            from pyamf.remoting import amf0\n            return amf0.RequestProcessor(self)",
    "docstring": "Returns request processor.\n\n        @param request: The AMF message.\n        @type request: L{Request<remoting.Request>}"
  },
  {
    "code": "def pep423_name(name):\n    name = name.lower()\n    if any(i not in name for i in (VCS_LIST + SCHEME_LIST)):\n        return name.replace(\"_\", \"-\")\n    else:\n        return name",
    "docstring": "Normalize package name to PEP 423 style standard."
  },
  {
    "code": "def handle_request_parsing_error(err, req, schema, error_status_code, error_headers):\n    abort(error_status_code, errors=err.messages)",
    "docstring": "webargs error handler that uses Flask-RESTful's abort function to return\n    a JSON error response to the client."
  },
  {
    "code": "def _prepare_version(self):\n        if config.VERSION not in self._config:\n            self._config[config.VERSION] = __version__",
    "docstring": "Setup the application version"
  },
  {
    "code": "def add_section(self, section_name):\n        self.section_headings.append(section_name)\n        if section_name in self.sections:\n            raise ValueError(\"Section %s already exists.\" % section_name)\n        self.sections[section_name] = []\n        return",
    "docstring": "Create a section of the report, to be headed by section_name\n\n        Text and images can be added by using the `section` argument of the\n        `add_text` and `add_image` methods. Sections can also be ordered by\n        using the `set_section_order` method.\n\n        By default, text and images that have no section will be placed after\n        all the sections, in the order they were added. This behavior may be\n        altered using the `sections_first` attribute of the `make_report`\n        method."
  },
  {
    "code": "def get_pias_script(environ=None):\n    if os.path.basename(sys.argv[0]) == \"pias\":\n        return sys.argv[0]\n    filepath = find_executable(\"pias\", environ)\n    if filepath is not None:\n        return filepath\n    filepath = os.path.join(os.path.dirname(__file__), \"__main__.py\")\n    if os.path.exists(filepath):\n        return filepath\n    raise RuntimeError(\"Could not locate the pias script.\")",
    "docstring": "Get the path to the playitagainsam command-line script."
  },
  {
    "code": "def _add_punctuation_spacing(self, input):\n        for replacement in punct_spacing:\n            input = re.sub(replacement[0], replacement[1], input)\n        return input",
    "docstring": "Adds additional spacing to punctuation characters. For example,\n        this puts an extra space after a fullwidth full stop."
  },
  {
    "code": "def _translate_page_into(page, language, default=None):\n    if page.language == language:\n        return page\n    translations = dict((t.language, t) for t in page.available_translations())\n    translations[page.language] = page\n    if language in translations:\n        return translations[language]\n    else:\n        if hasattr(default, '__call__'):\n            return default(page=page)\n        return default",
    "docstring": "Return the translation for a given page"
  },
  {
    "code": "def oc_attr_isdefault(o):\n    if not o._changed() and not o.default():\n        return True\n    if o == o.default():\n        return True\n    return False",
    "docstring": "Return wether an OC attribute has been defined or not."
  },
  {
    "code": "def cmd(send, *_):\n    thread_names = []\n    for x in sorted(threading.enumerate(), key=lambda k: k.name):\n        res = re.match(r'Thread-(\\d+$)', x.name)\n        if res:\n            tid = int(res.group(1))\n            if x._target.__name__ == '_worker':\n                thread_names.append((tid, \"%s running server thread\" % x.name))\n            elif x._target.__module__ == 'multiprocessing.pool':\n                thread_names.append((tid, \"%s running multiprocessing pool worker thread\" % x.name))\n        else:\n            res = re.match(r'Thread-(\\d+)', x.name)\n            tid = 0\n            if res:\n                tid = int(res.group(1))\n            thread_names.append((tid, x.name))\n    for x in sorted(thread_names, key=lambda k: k[0]):\n        send(x[1])",
    "docstring": "Enumerate threads.\n\n    Syntax: {command}"
  },
  {
    "code": "def task_class(self):\n        from scenario_player.tasks.base import get_task_class_for_type\n        root_task_type, _ = self.task\n        task_class = get_task_class_for_type(root_task_type)\n        return task_class",
    "docstring": "Return the Task class type configured for the scenario."
  },
  {
    "code": "def wrap_prompts_class(Klass):\n    try:\n        from prompt_toolkit.token import ZeroWidthEscape\n    except ImportError:\n        return Klass\n    class ITerm2IPythonPrompt(Klass):\n        def in_prompt_tokens(self, cli=None):\n            return  [\n                     (ZeroWidthEscape, last_status(self.shell)+BEFORE_PROMPT),\n                    ]+\\\n                    super(ITerm2IPythonPrompt, self).in_prompt_tokens(cli)+\\\n                    [(ZeroWidthEscape, AFTER_PROMPT)]\n    return ITerm2IPythonPrompt",
    "docstring": "Wrap an IPython's Prompt class\n\n    This is needed in order for Prompt to inject the correct escape sequences\n    at the right positions for shell integrations."
  },
  {
    "code": "def Contains(self, other):\n        if other is None:\n            raise ValueError(\"other is None.\")\n        if isinstance(other, Range):\n            if other.low >= self.low and other.high <= self.high:\n                return True\n            return False\n        else:\n            return self.Contains(Range(other, other))",
    "docstring": "Checks if the passed parameter is in the range of this object."
  },
  {
    "code": "def send_message_batch(self, queue, messages):\n        params = {}\n        for i, msg in enumerate(messages):\n            p_name = 'SendMessageBatchRequestEntry.%i.Id' % (i+1)\n            params[p_name] = msg[0]\n            p_name = 'SendMessageBatchRequestEntry.%i.MessageBody' % (i+1)\n            params[p_name] = msg[1]\n            p_name = 'SendMessageBatchRequestEntry.%i.DelaySeconds' % (i+1)\n            params[p_name] = msg[2]\n        return self.get_object('SendMessageBatch', params, BatchResults,\n                               queue.id, verb='POST')",
    "docstring": "Delivers up to 10 messages to a queue in a single request.\n\n        :type queue: A :class:`boto.sqs.queue.Queue` object.\n        :param queue: The Queue to which the messages will be written.\n\n        :type messages: List of lists.\n        :param messages: A list of lists or tuples.  Each inner\n            tuple represents a single message to be written\n            and consists of and ID (string) that must be unique\n            within the list of messages, the message body itself\n            which can be a maximum of 64K in length, and an\n            integer which represents the delay time (in seconds)\n            for the message (0-900) before the message will\n            be delivered to the queue."
  },
  {
    "code": "def keyReleaseEvent(self, event):\r\n        if self.isVisible():\r\n            qsc = get_shortcut(context='Editor', name='Go to next file')\r\n            for key in qsc.split('+'):\r\n                key = key.lower()\r\n                if ((key == 'ctrl' and event.key() == Qt.Key_Control) or\r\n                   (key == 'alt' and event.key() == Qt.Key_Alt)):\r\n                        self.item_selected()\r\n        event.accept()",
    "docstring": "Reimplement Qt method.\r\n\r\n        Handle \"most recent used\" tab behavior,\r\n        When ctrl is released and tab_switcher is visible, tab will be changed."
  },
  {
    "code": "def info(self, req) -> ResponseInfo:\n        r = ResponseInfo()\n        r.version = \"1.0\"\n        r.last_block_height = 0\n        r.last_block_app_hash = b''\n        return r",
    "docstring": "Since this will always respond with height=0, Tendermint\n        will resync this app from the begining"
  },
  {
    "code": "def factorset_product(*factorsets_list):\n    r\n    if not all(isinstance(factorset, FactorSet) for factorset in factorsets_list):\n        raise TypeError(\"Input parameters must be FactorSet instances\")\n    return reduce(lambda x, y: x.product(y, inplace=False), factorsets_list)",
    "docstring": "r\"\"\"\n    Base method used for product of factor sets.\n\n    Suppose :math:`\\vec\\phi_1` and :math:`\\vec\\phi_2` are two factor sets then their product is a another factors set\n    :math:`\\vec\\phi_3 = \\vec\\phi_1 \\cup \\vec\\phi_2`.\n\n    Parameters\n    ----------\n    factorsets_list: FactorSet1, FactorSet2, ..., FactorSetn\n        All the factor sets to be multiplied\n\n    Returns\n    -------\n    Product of factorset in factorsets_list\n\n    Examples\n    --------\n    >>> from pgmpy.factors import FactorSet\n    >>> from pgmpy.factors.discrete import DiscreteFactor\n    >>> from pgmpy.factors import factorset_product\n    >>> phi1 = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12))\n    >>> phi2 = DiscreteFactor(['x3', 'x4', 'x1'], [2, 2, 2], range(8))\n    >>> factor_set1 = FactorSet(phi1, phi2)\n    >>> phi3 = DiscreteFactor(['x5', 'x6', 'x7'], [2, 2, 2], range(8))\n    >>> phi4 = DiscreteFactor(['x5', 'x7', 'x8'], [2, 2, 2], range(8))\n    >>> factor_set2 = FactorSet(phi3, phi4)\n    >>> factor_set3 = factorset_product(factor_set1, factor_set2)\n    >>> print(factor_set3)\n    set([<DiscreteFactor representing phi(x1:2, x2:3, x3:2) at 0x7fb3a1933e90>,\n         <DiscreteFactor representing phi(x5:2, x7:2, x8:2) at 0x7fb3a1933f10>,\n         <DiscreteFactor representing phi(x5:2, x6:2, x7:2) at 0x7fb3a1933f90>,\n         <DiscreteFactor representing phi(x3:2, x4:2, x1:2) at 0x7fb3a1933e10>])"
  },
  {
    "code": "def apply_transaction(self,\n                          transaction: BaseTransaction\n                          ) -> Tuple[BaseBlock, Receipt, BaseComputation]:\n        vm = self.get_vm(self.header)\n        base_block = vm.block\n        receipt, computation = vm.apply_transaction(base_block.header, transaction)\n        header_with_receipt = vm.add_receipt_to_header(base_block.header, receipt)\n        vm.state.persist()\n        new_header = header_with_receipt.copy(state_root=vm.state.state_root)\n        transactions = base_block.transactions + (transaction, )\n        receipts = base_block.get_receipts(self.chaindb) + (receipt, )\n        new_block = vm.set_block_transactions(base_block, new_header, transactions, receipts)\n        self.header = new_block.header\n        return new_block, receipt, computation",
    "docstring": "Applies the transaction to the current tip block.\n\n        WARNING: Receipt and Transaction trie generation is computationally\n        heavy and incurs significant performance overhead."
  },
  {
    "code": "def reversed(self):\n        new_cub = CubicBezier(self.end, self.control2, self.control1,\n                              self.start)\n        if self._length_info['length']:\n            new_cub._length_info = self._length_info\n            new_cub._length_info['bpoints'] = (\n                self.end, self.control2, self.control1, self.start)\n        return new_cub",
    "docstring": "returns a copy of the CubicBezier object with its orientation\n        reversed."
  },
  {
    "code": "def execute(self, conn, data_tier_name='', transaction = False, cache=None):\n\tif cache:\n            ret=cache.get(\"DATA_TIERS\")\n            if not ret==None:\n                return ret\n        sql = self.sql\n\tbinds={}\n\tif data_tier_name:\n            op = ('=', 'like')['%' in data_tier_name]\n\t    sql += \"WHERE DT.DATA_TIER_NAME %s :datatier\" %op \n\t    binds = {\"datatier\":data_tier_name}\n        result = self.dbi.processData(sql, binds, conn, transaction)\n        plist = self.formatDict(result)\n        return plist",
    "docstring": "returns id for a given datatier name"
  },
  {
    "code": "def _check_type_and_load_cert(self, msg, key_type, cert_type):\n        key_types = key_type\n        cert_types = cert_type\n        if isinstance(key_type, string_types):\n            key_types = [key_types]\n        if isinstance(cert_types, string_types):\n            cert_types = [cert_types]\n        if msg is None:\n            raise SSHException(\"Key object may not be empty\")\n        msg.rewind()\n        type_ = msg.get_text()\n        if type_ in key_types:\n            pass\n        elif type_ in cert_types:\n            self.load_certificate(Message(msg.asbytes()))\n            msg.get_string()\n        else:\n            err = \"Invalid key (class: {}, data type: {}\"\n            raise SSHException(err.format(self.__class__.__name__, type_))",
    "docstring": "Perform message type-checking & optional certificate loading.\n\n        This includes fast-forwarding cert ``msg`` objects past the nonce, so\n        that the subsequent fields are the key numbers; thus the caller may\n        expect to treat the message as key material afterwards either way.\n\n        The obtained key type is returned for classes which need to know what\n        it was (e.g. ECDSA.)"
  },
  {
    "code": "def export_stl_ascii(mesh):\n    blob = np.zeros((len(mesh.faces), 4, 3))\n    blob[:, 0, :] = mesh.face_normals\n    blob[:, 1:, :] = mesh.triangles\n    format_string = 'facet normal {} {} {}\\nouter loop\\n'\n    format_string += 'vertex {} {} {}\\n' * 3\n    format_string += 'endloop\\nendfacet\\n'\n    format_string *= len(mesh.faces)\n    export = 'solid \\n'\n    export += format_string.format(*blob.reshape(-1))\n    export += 'endsolid'\n    return export",
    "docstring": "Convert a Trimesh object into an ASCII STL file.\n\n    Parameters\n    ---------\n    mesh : trimesh.Trimesh\n\n    Returns\n    ---------\n    export : str\n        Mesh represented as an ASCII STL file"
  },
  {
    "code": "def build_graph(formula):\n    graph = {}\n    for clause in formula:\n        for (lit, _) in clause:\n            for neg in [False, True]:\n                graph[(lit, neg)] = []\n    for ((a_lit, a_neg), (b_lit, b_neg)) in formula:\n        add_edge(graph, (a_lit, a_neg), (b_lit, not b_neg))\n        add_edge(graph, (b_lit, b_neg), (a_lit, not a_neg))\n    return graph",
    "docstring": "Builds the implication graph from the formula"
  },
  {
    "code": "def create_hparams_from_json(json_path, hparams=None):\n  tf.logging.info(\"Loading hparams from existing json %s\" % json_path)\n  with tf.gfile.Open(json_path, \"r\") as f:\n    hparams_values = json.load(f)\n    hparams_values.pop(\"bottom\", None)\n    hparams_values.pop(\"loss\", None)\n    hparams_values.pop(\"name\", None)\n    hparams_values.pop(\"top\", None)\n    hparams_values.pop(\"weights_fn\", None)\n    new_hparams = hparam.HParams(**hparams_values)\n    if hparams:\n      for key in sorted(new_hparams.values().keys()):\n        if hasattr(hparams, key):\n          value = getattr(hparams, key)\n          new_value = getattr(new_hparams, key)\n          if value != new_value:\n            tf.logging.info(\"Overwrite key %s: %s -> %s\" % (\n                key, value, new_value))\n            setattr(hparams, key, new_value)\n    else:\n      hparams = new_hparams\n  return hparams",
    "docstring": "Loading hparams from json; can also start from hparams if specified."
  },
  {
    "code": "def point(self, pos):\n        return ((1 - pos) ** 3 * self.start) + \\\n               (3 * (1 - pos) ** 2 * pos * self.control1) + \\\n               (3 * (1 - pos) * pos ** 2 * self.control2) + \\\n               (pos ** 3 * self.end)",
    "docstring": "Calculate the x,y position at a certain position of the path"
  },
  {
    "code": "def expand(self, flm, nmax=None):\n        if nmax is None:\n            nmax = (self.lmax+1)**2\n        elif nmax is not None and nmax > (self.lmax+1)**2:\n            raise ValueError(\n                \"nmax must be less than or equal to (lmax+1)**2 \" +\n                \"where lmax is {:s}. Input value is {:s}\"\n                .format(repr(self.lmax), repr(nmax))\n                )\n        coeffsin = flm.to_array(normalization='4pi', csphase=1, lmax=self.lmax)\n        return self._expand(coeffsin, nmax)",
    "docstring": "Return the Slepian expansion coefficients of the input function.\n\n        Usage\n        -----\n        s = x.expand(flm, [nmax])\n\n        Returns\n        -------\n        s : SlepianCoeff class instance\n            The Slepian expansion coefficients of the input function.\n\n        Parameters\n        ----------\n        flm : SHCoeffs class instance\n            The input function to expand in Slepian functions.\n        nmax : int, optional, default = (x.lmax+1)**2\n            The number of Slepian expansion coefficients to compute.\n\n        Description\n        -----------\n        The global function f is input using its spherical harmonic\n        expansion coefficients flm. The expansion coefficients of the function\n        f using Slepian functions g is given by\n        \n        f_alpha = sum_{lm}^{lmax} f_lm g(alpha)_lm"
  },
  {
    "code": "def backwards(apps, schema_editor):\n    RecurrenceRule = apps.get_model('icekit_events', 'RecurrenceRule')\n    descriptions = [d for d, rr in RULES]\n    RecurrenceRule.objects.filter(description__in=descriptions).delete()",
    "docstring": "Delete initial recurrence rules."
  },
  {
    "code": "def get_campaign(self, campaign_id):\n        api = self._get_api(update_service.DefaultApi)\n        return Campaign(api.update_campaign_retrieve(campaign_id))",
    "docstring": "Get existing update campaign.\n\n        :param str campaign_id: Campaign ID to retrieve (Required)\n        :return: Update campaign object matching provided ID\n        :rtype: Campaign"
  },
  {
    "code": "def _prepare_lsm_gag(self):\n        lsm_required_vars = (self.lsm_precip_data_var,\n                             self.lsm_precip_type)\n        return self.lsm_input_valid and (None not in lsm_required_vars)",
    "docstring": "Determines whether to prepare gage data from LSM"
  },
  {
    "code": "def to_rgba(color, alpha):\n    if type(color) == tuple:\n        color, alpha = color\n    color = color.lower()\n    if 'rgba' in color:\n        cl = list(eval(color.replace('rgba', '')))\n        if alpha:\n            cl[3] = alpha\n        return 'rgba' + str(tuple(cl))\n    elif 'rgb' in color:\n        r, g, b = eval(color.replace('rgb', ''))\n        return 'rgba' + str((r, g, b, alpha))\n    else:\n        return to_rgba(hex_to_rgb(color), alpha)",
    "docstring": "Converts from hex|rgb to rgba\n\n    Parameters:\n    -----------\n            color : string\n                    Color representation on hex or rgb\n            alpha : float\n                    Value from 0 to 1.0 that represents the \n                    alpha value.\n\n    Example:\n            to_rgba('#E1E5ED',0.6)\n            to_rgba('#f03',0.7)\n            to_rgba('rgb(23,23,23)',.5)"
  },
  {
    "code": "def ls(ctx, name):\n    session = create_session(ctx.obj['AWS_PROFILE_NAME'])\n    client = session.client('emr')\n    results = client.list_clusters(\n        ClusterStates=['RUNNING', 'STARTING', 'BOOTSTRAPPING', 'WAITING']\n    )\n    for cluster in results['Clusters']:\n        click.echo(\"{0}\\t{1}\\t{2}\".format(cluster['Id'], cluster['Name'], cluster['Status']['State']))",
    "docstring": "List EMR instances"
  },
  {
    "code": "def _get_candidate_names():\n    global _name_sequence\n    if _name_sequence is None:\n        _once_lock.acquire()\n        try:\n            if _name_sequence is None:\n                _name_sequence = _RandomNameSequence()\n        finally:\n            _once_lock.release()\n    return _name_sequence",
    "docstring": "Common setup sequence for all user-callable interfaces."
  },
  {
    "code": "def reply(self, message: typing.Union[int, types.Message]):\n        setattr(self, 'reply_to_message_id', message.message_id if isinstance(message, types.Message) else message)\n        return self",
    "docstring": "Reply to message\n\n        :param message: :obj:`int` or  :obj:`types.Message`\n        :return: self"
  },
  {
    "code": "def infer_config_base_dir() -> Path:\n    if 'OT_API_CONFIG_DIR' in os.environ:\n        return Path(os.environ['OT_API_CONFIG_DIR'])\n    elif IS_ROBOT:\n        return Path('/data')\n    else:\n        search = (Path.cwd(),\n                  Path.home()/'.opentrons')\n        for path in search:\n            if (path/_CONFIG_FILENAME).exists():\n                return path\n        else:\n            return search[-1]",
    "docstring": "Return the directory to store data in.\n\n    Defaults are ~/.opentrons if not on a pi; OT_API_CONFIG_DIR is\n    respected here.\n\n    When this module is imported, this function is called automatically\n    and the result stored in :py:attr:`APP_DATA_DIR`.\n\n    This directory may not exist when the module is imported. Even if it\n    does exist, it may not contain data, or may require data to be moved\n    to it.\n\n    :return pathlib.Path: The path to the desired root settings dir."
  },
  {
    "code": "def _decode_addr_key(self, obj_dict):\n        key = b'Addr'\n        if key in obj_dict:\n            try:\n                ip_addr = socket.inet_ntop(socket.AF_INET6, obj_dict[key])\n                if ip_addr.startswith('::ffff:'):\n                    ip_addr = ip_addr.lstrip('::ffff:')\n                obj_dict[key] = ip_addr.encode('utf-8')\n            except ValueError:\n                ip_addr = socket.inet_ntop(socket.AF_INET, obj_dict[key])\n                obj_dict[key] = ip_addr.encode('utf-8')\n        return obj_dict",
    "docstring": "Callback function to handle the decoding of the 'Addr' field.\n\n        Serf msgpack 'Addr' as an IPv6 address, and the data needs to be unpack\n        using socket.inet_ntop().\n\n        See: https://github.com/KushalP/serfclient-py/issues/20\n\n        :param obj_dict: A dictionary containing the msgpack map.\n        :return: A dictionary with the correct 'Addr' format."
  },
  {
    "code": "def _validate_signal(self, sig):\n        if not isinstance(sig, int):\n            raise TypeError('sig must be an int, not {!r}'.format(sig))\n        if signal is None:\n            raise RuntimeError('Signals are not supported')\n        if not (1 <= sig < signal.NSIG):\n            raise ValueError('sig {} out of range(1, {})'.format(sig, signal.NSIG))\n        if sys.platform == 'win32':\n            raise RuntimeError('Signals are not really supported on Windows')",
    "docstring": "Internal helper to validate a signal.\n\n        Raise ValueError if the signal number is invalid or uncatchable.\n        Raise RuntimeError if there is a problem setting up the handler."
  },
  {
    "code": "def wb010(self, value=None):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type float '\n                                 'for field `wb010`'.format(value))\n        self._wb010 = value",
    "docstring": "Corresponds to IDD Field `wb010`\n        Wet-bulb temperature corresponding to 1.0% annual cumulative frequency of occurrence\n\n        Args:\n            value (float): value for IDD Field `wb010`\n                Unit: C\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def d2Ibr_dV2(Ybr, V, lam):\n    nb = len(V)\n    diaginvVm = spdiag(div(matrix(1.0, (nb, 1)), abs(V)))\n    Haa = spdiag(mul(-(Ybr.T * lam), V))\n    Hva = -1j * Haa * diaginvVm\n    Hav = Hva\n    Hvv = spmatrix([], [], [], (nb, nb))\n    return Haa, Hav, Hva, Hvv",
    "docstring": "Computes 2nd derivatives of complex branch current w.r.t. voltage."
  },
  {
    "code": "def make(parser):\n    mgr_parser = parser.add_subparsers(dest='subcommand')\n    mgr_parser.required = True\n    mgr_create = mgr_parser.add_parser(\n        'create',\n        help='Deploy Ceph MGR on remote host(s)'\n    )\n    mgr_create.add_argument(\n        'mgr',\n        metavar='HOST[:NAME]',\n        nargs='+',\n        type=colon_separated,\n        help='host (and optionally the daemon name) to deploy on',\n        )\n    parser.set_defaults(\n        func=mgr,\n        )",
    "docstring": "Ceph MGR daemon management"
  },
  {
    "code": "def getConst(name, timeout=0.1):\n    from . import _control\n    import time\n    timeStamp = time.time()\n    while True:\n        _control.execQueue.socket.pumpInfoSocket()\n        constants = dict(reduce(\n            lambda x, y: x + list(y.items()),\n            elements.values(),\n            []\n        ))\n        timeoutHappened = time.time() - timeStamp > timeout\n        if constants.get(name) is not None or timeoutHappened:\n            return constants.get(name)\n        time.sleep(0.01)",
    "docstring": "Get a shared constant.\n\n    :param name: The name of the shared variable to retrieve.\n    :param timeout: The maximum time to wait in seconds for the propagation of\n        the constant.\n\n    :returns: The shared object.\n\n    Usage: value = getConst('name')"
  },
  {
    "code": "def _seed(self, seed=-1):\n        if seed != -1:\n          self._random = np.random.RandomState(seed)\n        else:\n          self._random = np.random.RandomState()",
    "docstring": "Initialize the random seed"
  },
  {
    "code": "def get_components(self, uri):\n        try:\n            component_definition = self._components[uri]\n        except KeyError:\n            return False\n        sorted_sequences = sorted(component_definition.sequence_annotations,\n                                  key=attrgetter('first_location'))\n        return [c.component for c in sorted_sequences]",
    "docstring": "Get components from a component definition in order"
  },
  {
    "code": "def report_status(self):\n        current_status = {\n            'current_track': self.core.playback.current_track.get(),\n            'state': self.core.playback.state.get(),\n            'time_position': self.core.playback.time_position.get(),\n        }\n        send_webhook(self.config, {'status_report': current_status})\n        self.report_again(current_status)",
    "docstring": "Get status of player from mopidy core and send webhook."
  },
  {
    "code": "def create_archive(\n            self,\n            archive_name,\n            authority_name,\n            archive_path,\n            versioned,\n            raise_on_err=True,\n            metadata=None,\n            user_config=None,\n            tags=None,\n            helper=False):\n        archive_metadata = self._create_archive_metadata(\n            archive_name=archive_name,\n            authority_name=authority_name,\n            archive_path=archive_path,\n            versioned=versioned,\n            raise_on_err=raise_on_err,\n            metadata=metadata,\n            user_config=user_config,\n            tags=tags,\n            helper=helper)\n        if raise_on_err:\n            self._create_archive(\n                archive_name,\n                archive_metadata)\n        else:\n            self._create_if_not_exists(\n                archive_name,\n                archive_metadata)\n        return self.get_archive(archive_name)",
    "docstring": "Create a new data archive\n\n        Returns\n        -------\n        archive : object\n            new :py:class:`~datafs.core.data_archive.DataArchive` object"
  },
  {
    "code": "def _find_last_good_run(build):\n    run_name = request.form.get('run_name', type=str)\n    utils.jsonify_assert(run_name, 'run_name required')\n    last_good_release = (\n        models.Release.query\n        .filter_by(\n            build_id=build.id,\n            status=models.Release.GOOD)\n        .order_by(models.Release.created.desc())\n        .first())\n    last_good_run = None\n    if last_good_release:\n        logging.debug('Found last good release for: build_id=%r, '\n                      'release_name=%r, release_number=%d',\n                      build.id, last_good_release.name,\n                      last_good_release.number)\n        last_good_run = (\n            models.Run.query\n            .filter_by(release_id=last_good_release.id, name=run_name)\n            .first())\n        if last_good_run:\n            logging.debug('Found last good run for: build_id=%r, '\n                          'release_name=%r, release_number=%d, '\n                          'run_name=%r',\n                          build.id, last_good_release.name,\n                          last_good_release.number, last_good_run.name)\n    return last_good_release, last_good_run",
    "docstring": "Finds the last good release and run for a build."
  },
  {
    "code": "def transformFromNative(obj):\n        if obj.value and type(obj.value[0]) == datetime.date:\n            obj.isNative = False\n            obj.value_param = 'DATE'\n            obj.value = ','.join([dateToString(val) for val in obj.value])\n            return obj\n        else:\n            if obj.isNative:\n                obj.isNative = False\n                transformed = []\n                tzid = None\n                for val in obj.value:\n                    if tzid is None and type(val) == datetime.datetime:\n                        tzid = TimezoneComponent.registerTzinfo(val.tzinfo)\n                        if tzid is not None:\n                            obj.tzid_param = tzid\n                    transformed.append(dateTimeToString(val))\n                obj.value = ','.join(transformed)\n            return obj",
    "docstring": "Replace the date, datetime or period tuples in obj.value with\n        appropriate strings."
  },
  {
    "code": "def fax(self):\n        if self._fax is None:\n            from twilio.rest.fax import Fax\n            self._fax = Fax(self)\n        return self._fax",
    "docstring": "Access the Fax Twilio Domain\n\n        :returns: Fax Twilio Domain\n        :rtype: twilio.rest.fax.Fax"
  },
  {
    "code": "def add_user_js(self, js_list):\n        if isinstance(js_list, string_types):\n            js_list = [js_list]\n        for js_path in js_list:\n            if js_path and js_path not in self.user_js:\n                if js_path.startswith(\"http:\"):\n                    self.user_js.append({\n                        'path_url': js_path,\n                        'contents': '',\n                    })\n                elif not os.path.exists(js_path):\n                    raise IOError('%s user js file not found' % (js_path,))\n                else:\n                    with codecs.open(js_path,\n                                     encoding=self.encoding) as js_file:\n                        self.user_js.append({\n                            'path_url': utils.get_path_url(js_path,\n                                                           self.relative),\n                            'contents': js_file.read(),\n                        })",
    "docstring": "Adds supplementary user javascript files to the presentation. The\n            ``js_list`` arg can be either a ``list`` or a string."
  },
  {
    "code": "def unlink_rich_menu_from_user(self, user_id, timeout=None):\n        self._delete(\n            '/v2/bot/user/{user_id}/richmenu'.format(user_id=user_id),\n            timeout=timeout\n        )",
    "docstring": "Call unlink rich menu from user API.\n\n        https://developers.line.me/en/docs/messaging-api/reference/#unlink-rich-menu-from-user\n\n        :param str user_id: ID of the user\n        :param timeout: (optional) How long to wait for the server\n            to send data before giving up, as a float,\n            or a (connect timeout, read timeout) float tuple.\n            Default is self.http_client.timeout\n        :type timeout: float | tuple(float, float)"
  },
  {
    "code": "def _init_itemid2name(self):\n        if not hasattr(self.args, 'id2sym'):\n            return None\n        fin_id2sym = self.args.id2sym\n        if fin_id2sym is not None and os.path.exists(fin_id2sym):\n            id2sym = {}\n            cmpl = re.compile(r'^\\s*(\\S+)[\\s,;]+(\\S+)')\n            with open(fin_id2sym) as ifstrm:\n                for line in ifstrm:\n                    mtch = cmpl.search(line)\n                    if mtch:\n                        id2sym[mtch.group(1)] = mtch.group(2)\n            return id2sym",
    "docstring": "Print gene symbols instead of gene IDs, if provided."
  },
  {
    "code": "def gamma_coag(ConcClay, ConcAluminum, coag, material,\n               DiamTube, RatioHeightDiameter):\n    return (1 - np.exp((\n                       (-frac_vol_floc_initial(ConcAluminum, 0*u.kg/u.m**3, coag, material)\n                         * material.Diameter)\n                        / (frac_vol_floc_initial(0*u.kg/u.m**3, ConcClay, coag, material)\n                           * coag.Diameter))\n                       * (1 / np.pi)\n                       * (ratio_area_clay_total(ConcClay, material,\n                                                DiamTube, RatioHeightDiameter)\n                          / ratio_clay_sphere(RatioHeightDiameter))\n                       ))",
    "docstring": "Return the coverage of clay with nanoglobs.\n\n    This function accounts for loss to the tube flocculator walls\n    and a poisson distribution on the clay given random hits by the\n    nanoglobs. The poisson distribution results in the coverage only\n    gradually approaching full coverage as coagulant dose increases.\n\n    :param ConcClay: Concentration of clay in suspension\n    :type ConcClay: float\n    :param ConcAluminum: Concentration of aluminum in solution\n    :type ConcAluminum: float\n    :param coag: Type of coagulant in solution, e.g. floc_model.PACl\n    :type coag: floc_model.Material\n    :param material: Type of clay in suspension, e.g. floc_model.Clay\n    :type material: floc_model.Material\n    :param DiamTube: Diameter of flocculator tube (assumes tube flocculator for calculation of reactor surface area)\n    :type DiamTube: float\n    :param RatioHeightDiameter: Dimensionless ratio of clay height to clay diameter\n    :type RatioHeightDiameter: float\n\n    :return: Fraction of the clay surface area that is coated with coagulant precipitates\n    :rtype: float"
  },
  {
    "code": "def _verify_signature(self, message, signature):\n        if self.negotiate_flags & NegotiateFlags.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n            actual_checksum = signature[4:12]\n            actual_seq_num = struct.unpack(\"<I\", signature[12:16])[0]\n        else:\n            actual_checksum = signature[8:12]\n            actual_seq_num = struct.unpack(\"<I\", signature[12:16])[0]\n        expected_signature = calc_signature(message, self.negotiate_flags, self.incoming_signing_key, self.incoming_seq_num, self.incoming_handle)\n        expected_checksum = expected_signature.checksum\n        expected_seq_num = struct.unpack(\"<I\", expected_signature.seq_num)[0]\n        if actual_checksum != expected_checksum:\n            raise Exception(\"The signature checksum does not match, message has been altered\")\n        if actual_seq_num != expected_seq_num:\n            raise Exception(\"The signature sequence number does not match up, message not received in the correct sequence\")\n        self.incoming_seq_num += 1",
    "docstring": "Will verify that the signature received from the server matches up with the expected signature\n        computed locally. Will throw an exception if they do not match\n\n        @param message: The message data that is received from the server\n        @param signature: The signature of the message received from the server"
  },
  {
    "code": "def _create_table_xml_file(self, data, fname=None):\n        content = self._xml_pretty_print(data)\n        if not fname:\n            fname = self.name\n        with open(fname+\".xml\", 'w') as f:\n            f.write(content)",
    "docstring": "Creates a xml file of the table"
  },
  {
    "code": "def _is_related(parent_entry, child_entry):\n        if parent_entry.header.mft_record == child_entry.header.base_record_ref and \\\n           parent_entry.header.seq_number == child_entry.header.base_record_seq:\n            return True\n        else:\n            return False",
    "docstring": "This function checks if a child entry is related to the parent entry.\n        This is done by comparing the reference and sequence numbers."
  },
  {
    "code": "def decodeMotorInput(self, motorInputPattern):\n    key = self.motorEncoder.decode(motorInputPattern)[0].keys()[0]\n    motorCommand = self.motorEncoder.decode(motorInputPattern)[0][key][1][0]\n    return motorCommand",
    "docstring": "Decode motor command from bit vector.\n\n    @param motorInputPattern (1D numpy.array)\n        Encoded motor command.\n\n    @return                  (1D numpy.array)\n        Decoded motor command."
  },
  {
    "code": "def generate_seed(seed):\n    if seed is None:\n        random.seed()\n        seed = random.randint(0, sys.maxsize)\n    random.seed(a=seed)\n    return seed",
    "docstring": "Generate seed for random number generator"
  },
  {
    "code": "def main(filename):\n    if filename:\n        if not os.path.exists(filename):\n            logger.error(\"'%s' doesn't exists!\" % filename)\n            sys.stderr.write(\"'%s' doesn't exists!\\n\" % filename)\n            sys.exit(1)\n        logger.info(\"Processing '%s'\" % filename)\n        for ir in process_log(sh.tail(\"-f\", filename, _iter=True)):\n            print ir\n    else:\n        logger.info(\"Processing stdin.\")\n        for ir in process_log(_read_stdin()):\n            print ir",
    "docstring": "Open `filename` and start processing it line by line. If `filename` is\n    none, process lines from `stdin`."
  },
  {
    "code": "def buttonDown(self, button=mouse.LEFT):\n        self._lock.acquire()\n        mouse.press(button)\n        self._lock.release()",
    "docstring": "Holds down the specified mouse button.\n\n        Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT"
  },
  {
    "code": "def pandas_df_to_biopython_seqrecord(\n    df,\n    id_col='uid',\n    sequence_col='sequence',\n    extra_data=None,\n    alphabet=None,\n    ):\n    seq_records = []\n    for i, row in df.iterrows():\n        try:\n            seq = Seq(row[sequence_col], alphabet=alphabet)\n            id = row[id_col]\n            description = \"\"\n            if extra_data is not None:\n                description = \" \".join([row[key] for key in extra_data])\n            record = SeqRecord(\n                seq=seq,\n                id=id,\n                description=description,\n            )\n            seq_records.append(record)\n        except TypeError:\n            pass\n    return seq_records",
    "docstring": "Convert pandas dataframe to biopython seqrecord for easy writing.\n\n    Parameters\n    ----------\n    df : Dataframe\n        Pandas dataframe to convert\n\n    id_col : str\n        column in dataframe to use as sequence label\n\n    sequence_col str:\n        column in dataframe to use as sequence data\n\n    extra_data : list\n        extra columns to use in sequence description line\n\n    alphabet :\n        biopython Alphabet object\n\n    Returns\n    -------\n    seq_records :\n        List of biopython seqrecords."
  },
  {
    "code": "def run(self):\n        try:\n            if self._target:\n                return_value = self._target(*self._args, **self._kwargs)\n                if return_value is not None:\n                    self._exception = OrphanedReturn(self, return_value)\n        except BaseException as err:\n            self._exception = err\n        finally:\n            del self._target, self._args, self._kwargs",
    "docstring": "Modified ``run`` that captures return value and exceptions from ``target``"
  },
  {
    "code": "def init_logger(cls, log_level):\n        logger = logging.getLogger(\"AutoMLBoard\")\n        handler = logging.StreamHandler()\n        formatter = logging.Formatter(\"[%(levelname)s %(asctime)s] \"\n                                      \"%(filename)s: %(lineno)d  \"\n                                      \"%(message)s\")\n        handler.setFormatter(formatter)\n        logger.setLevel(log_level)\n        logger.addHandler(handler)\n        return logger",
    "docstring": "Initialize logger settings."
  },
  {
    "code": "def to_float(self, col: str, **kwargs):\n        try:\n            self.df[col] = self.df[col].astype(np.float64, **kwargs)\n            self.ok(\"Converted column values to float\")\n        except Exception as e:\n            self.err(e, \"Error converting to float\")",
    "docstring": "Convert colums values to float\n\n        :param col: name of the colum\n        :type col: str, at least one\n        :param \\*\\*kwargs: keyword arguments for ``df.astype``\n        :type \\*\\*kwargs: optional\n\n        :example: ``ds.to_float(\"mycol1\")``"
  },
  {
    "code": "def connect(self):\n        logger.debug(\"Opening connection to %s:%s\", self.url.hostname, self.url.port)\n        try:\n            self.connection = httplib.HTTPConnection(self.url.hostname, self.url.port)\n            self.connection.connect()\n        except (httplib.HTTPException, socket.error) as e:\n            raise errors.InterfaceError('Unable to connect to the specified service', e)",
    "docstring": "Opens a HTTP connection to the RPC server."
  },
  {
    "code": "async def load_tracks(self, query) -> LoadResult:\n        self.__check_node_ready()\n        url = self._uri + quote(str(query))\n        data = await self._get(url)\n        if isinstance(data, dict):\n            return LoadResult(data)\n        elif isinstance(data, list):\n            modified_data = {\n                \"loadType\": LoadType.V2_COMPAT,\n                \"tracks\": data\n            }\n            return LoadResult(modified_data)",
    "docstring": "Executes a loadtracks request. Only works on Lavalink V3.\n\n        Parameters\n        ----------\n        query : str\n\n        Returns\n        -------\n        LoadResult"
  },
  {
    "code": "def _clean():\n    LOGGER.info('Cleaning project directory...')\n    folders_to_cleanup = [\n        '.eggs',\n        'build',\n        f'{config.PACKAGE_NAME()}.egg-info',\n    ]\n    for folder in folders_to_cleanup:\n        if os.path.exists(folder):\n            LOGGER.info('\\tremoving: %s', folder)\n            shutil.rmtree(folder)",
    "docstring": "Cleans up build dir"
  },
  {
    "code": "def load(cls, database, doc_id):\n        doc = database.get(doc_id)\n        if doc is None:\n            return None\n        return cls.wrap(doc)",
    "docstring": "Load a specific document from the given database.\n\n        :param database: the `Database` object to retrieve the document from\n        :param doc_id: the document ID\n        :return: the `Document` instance, or `None` if no document with the\n                 given ID was found"
  },
  {
    "code": "def load_backends(self):\n    for name, backend_settings in settings.storage.iteritems():\n      backend_path = backend_settings['backend']\n      backend_module, backend_cls = backend_path.rsplit('.', 1)\n      backend_module = import_module(backend_module)\n      backend_constructor = getattr(backend_module, backend_cls)\n      self.backends[name] = backend_constructor(name,\n                                                self.namespaces,\n                                                **backend_settings)",
    "docstring": "Loads all the backends setup in settings.py."
  },
  {
    "code": "def auto(cls, func):\n        @functools.wraps(func)\n        def auto_claim_handle(*args, **kwargs):\n            with cls():\n                return func(*args, **kwargs)\n        return auto_claim_handle",
    "docstring": "The ``auto`` decorator wraps ``func`` in a context manager so that a handle is obtained.\n\n        .. note::\n           Please note, that most functions require the handle to continue being alive for future calls to data\n           retrieved from the function. In such cases, it's advisable to use the `requires_refcount` decorator, and\n           force the program using the library with obtaining a handle (and keeping it active.)"
  },
  {
    "code": "def types(self, *args):\n        return ', '.join(['{0}({1})'.format(type(arg).__name__, arg) for arg in args])",
    "docstring": "Used for debugging, returns type of each arg.\n            TYPES,ARG_1,...,ARG_N\n\n        %{TYPES:A,...,10} -> 'str(A) str(B) ... int(10)'"
  },
  {
    "code": "def redirect_stream(system, target):\n    if target is None:\n        target_fd = os.open(os.devnull, os.O_RDWR)\n    else:\n        target_fd = target.fileno()\n    try:\n        os.dup2(target_fd, system.fileno())\n    except OSError as err:\n        raise DaemonError('Could not redirect {0} to {1}: {2}'\n                          .format(system, target, err))",
    "docstring": "Redirect Unix streams\n\n    If None, redirect Stream to /dev/null, else redirect to target.\n\n    :param system: ether sys.stdin, sys.stdout, or sys.stderr\n    :type system: file object\n\n    :param target: File like object, or None\n    :type target: None, File Object\n\n    :return: None\n    :raise: DaemonError"
  },
  {
    "code": "def compilearg(self):\n        if isinstance(self.value,list):\n            value = self.delimiter.join(self.value)\n        else:\n            value = self.value\n        if value.find(\" \") >= 0:\n            value = '\"' + value + '\"'\n        if self.paramflag and self.paramflag[-1] == '=' or self.nospace:\n            sep = ''\n        elif self.paramflag:\n            sep = ' '\n        else:\n            return str(value)\n        return self.paramflag + sep + str(value)",
    "docstring": "This method compiles the parameter into syntax that can be used on the shell, such as -paramflag=value"
  },
  {
    "code": "def qcktrc(tracelen=_default_len_out):\n    tracestr = stypes.stringToCharP(tracelen)\n    tracelen = ctypes.c_int(tracelen)\n    libspice.qcktrc_c(tracelen, tracestr)\n    return stypes.toPythonString(tracestr)",
    "docstring": "Return a string containing a traceback.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/qcktrc_c.html\n\n    :param tracelen: Maximum length of output traceback string.\n    :type tracelen: int\n    :return: A traceback string.\n    :rtype: str"
  },
  {
    "code": "def read_data(self, dstart=None, dend=None, swap_axes=True):\n        data = super(FileReaderMRC, self).read_data(dstart, dend)\n        data = data.reshape(self.data_shape, order='F')\n        if swap_axes:\n            data = np.transpose(data, axes=self.data_axis_order)\n            assert data.shape == self.data_shape\n        return data",
    "docstring": "Read the data from `file` and return it as Numpy array.\n\n        Parameters\n        ----------\n        dstart : int, optional\n            Offset in bytes of the data field. By default, it is equal\n            to ``header_size``. Backwards indexing with negative values\n            is also supported.\n            Use a value larger than the header size to extract a data subset.\n        dend : int, optional\n            End position in bytes until which data is read (exclusive).\n            Backwards indexing with negative values is also supported.\n            Use a value different from the file size to extract a data subset.\n        swap_axes : bool, optional\n            If ``True``, use `data_axis_order` to swap the axes in the\n            returned array. In that case, the shape of the array may no\n            longer agree with `data_storage_shape`.\n\n        Returns\n        -------\n        data : `numpy.ndarray`\n            The data read from `file`."
  },
  {
    "code": "def _handle_satosa_authentication_error(self, error):\n        context = Context()\n        context.state = error.state\n        frontend = self.module_router.frontend_routing(context)\n        return frontend.handle_backend_error(error)",
    "docstring": "Sends a response to the requester about the error\n\n        :type error: satosa.exception.SATOSAAuthenticationError\n        :rtype: satosa.response.Response\n\n        :param error: The exception\n        :return: response"
  },
  {
    "code": "def create(self, dbsecgroup_id, source_cidr, port=3306):\n        body = {\n                \"security_group_rule\": {\n                    \"security_group_id\": dbsecgroup_id,\n                    \"cidr\": source_cidr,\n                    \"from_port\": port,\n                    \"to_port\": port,\n                    }\n                }\n        return self._create(\"/security-group-rules\", body,\n                \"security_group_rule\")",
    "docstring": "Creates a security group rule.\n\n        :param str dbsecgroup_id:  The ID of the security group in which this\n            rule should be created.\n        :param str source_cidr:  The source IP address range from which access\n            should be allowed.\n        :param int port:  The port number used by db clients to connect to the\n            db server.  This would have been specified at db instance creation\n            time.\n\n        :rtype:  :class:`DBSecurityGroupRule`."
  },
  {
    "code": "def default(self, value):\n        if isinstance(value, ObjectId):\n            return str(value)\n        return super(ElasticJSONSerializer, self).default(value)",
    "docstring": "Convert mongo.ObjectId."
  },
  {
    "code": "def _server_connect(self, s):\n        self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        self._socket.setblocking(0)\n        self._socket.settimeout(1.0)\n        if self.options[\"tcp_nodelay\"]:\n            self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)\n        self.io = tornado.iostream.IOStream(self._socket,\n            max_buffer_size=self._max_read_buffer_size,\n            max_write_buffer_size=self._max_write_buffer_size,\n            read_chunk_size=self._read_chunk_size)\n        future = self.io.connect((s.uri.hostname, s.uri.port))\n        yield tornado.gen.with_timeout(\n            timedelta(seconds=self.options[\"connect_timeout\"]), future)\n        self.io.set_close_callback(self._process_op_err)",
    "docstring": "Sets up a TCP connection to the server."
  },
  {
    "code": "def getUtilities(self, decision, orderVector):\n        scoringVector = self.getScoringVector(orderVector)\n        utilities = []\n        for alt in decision:\n            altPosition = orderVector.index(alt)\n            utility = float(scoringVector[altPosition])\n            if self.isLoss == True:\n                utility = -1*utility\n            utilities.append(utility)\n        return utilities",
    "docstring": "Returns a floats that contains the utilities of every candidate in the decision.\n\n        :ivar list<int> decision: Contains a list of integer representations of candidates in the \n            current decision.\n        :ivar list<int> orderVector: A list of integer representations for each candidate ordered\n            from most preferred to least."
  },
  {
    "code": "def computer(self, base_dn, samaccountname, attributes=()):\n        computers = self.computers(base_dn, samaccountnames=[samaccountname], attributes=attributes)\n        try:\n            return computers[0]\n        except IndexError:\n            logging.info(\"%s - unable to retrieve object from AD by sAMAccountName\", samaccountname)",
    "docstring": "Produces a single, populated ADComputer object through the object factory.\n        Does not populate attributes for the caller instance.\n\n        :param str base_dn: The base DN to search within\n        :param str samaccountname: The computer's sAMAccountName\n        :param list attributes: Object attributes to populate, defaults to all\n\n        :return: A populated ADComputer object\n        :rtype: ADComputer"
  },
  {
    "code": "def _lookup_in_all_namespaces(self, symbol):\n        namespace = self.namespaces\n        namespace_stack = []\n        for current in symbol.namespace_stack:\n            namespace = namespace.get(current)\n            if namespace is None or not isinstance(namespace, dict):\n                break\n            namespace_stack.append(namespace)\n        for namespace in reversed(namespace_stack):\n            try:\n                return self._lookup_namespace(symbol, namespace)\n            except Error:\n                pass\n        return None",
    "docstring": "Helper for lookup_symbol that looks for symbols in all namespaces.\n\n        Args:\n          symbol: Symbol"
  },
  {
    "code": "def version(self):\n        branches = self.branches()\n        if self.info['branch'] == branches.sandbox:\n            try:\n                return self.software_version()\n            except Exception as exc:\n                raise utils.CommandError(\n                    'Could not obtain repo version, do you have a makefile '\n                    'with version entry?\\n%s' % exc\n                )\n        else:\n            branch = self.info['branch'].lower()\n            branch = re.sub('[^a-z0-9_-]+', '-', branch)\n            return f\"{branch}-{self.info['head']['id'][:8]}\"",
    "docstring": "Software version of the current repository"
  },
  {
    "code": "def is_scaled_full_image(self):\n        return(self.region_full and\n               self.size_wh[0] is not None and\n               self.size_wh[1] is not None and\n               not self.size_bang and\n               self.rotation_deg == 0.0 and\n               self.quality == self.default_quality and\n               self.format == 'jpg')",
    "docstring": "True if this request is for a scaled full image.\n\n        To be used to determine whether this request should be used\n        in the set of `sizes` specificed in the Image Information."
  },
  {
    "code": "def validate(cls):\n        if cls.get_dict():\n            cls.show_error(False)\n            return True\n        cls.show_error(True)\n        return False",
    "docstring": "Make sure, that conspect element is properly selected. If not, show\n        error."
  },
  {
    "code": "def compute_partition_size(result, processes):\n    try:\n        return max(math.ceil(len(result) / processes), 1)\n    except TypeError:\n        return 1",
    "docstring": "Attempts to compute the partition size to evenly distribute work across processes. Defaults to\n    1 if the length of result cannot be determined.\n\n    :param result: Result to compute on\n    :param processes: Number of processes to use\n    :return: Best partition size"
  },
  {
    "code": "async def listWorkerTypes(self, *args, **kwargs):\n        return await self._makeApiCall(self.funcinfo[\"listWorkerTypes\"], *args, **kwargs)",
    "docstring": "See the list of worker types which are known to be managed\n\n        This method is only for debugging the ec2-manager\n\n        This method gives output: ``v1/list-worker-types.json#``\n\n        This method is ``experimental``"
  },
  {
    "code": "def uptodate():\n    DETAILS = _load_state()\n    for p in DETAILS['packages']:\n        version_float = float(DETAILS['packages'][p])\n        version_float = version_float + 1.0\n        DETAILS['packages'][p] = six.text_type(version_float)\n    return DETAILS['packages']",
    "docstring": "Call the REST endpoint to see if the packages on the \"server\" are up to date."
  },
  {
    "code": "def set_legend(self, legend):\n        assert(isinstance(legend, list) or isinstance(legend, tuple) or\n            legend is None)\n        if legend:\n            self.legend = [quote(a) for a in legend]\n        else:\n            self.legend = None",
    "docstring": "legend needs to be a list, tuple or None"
  },
  {
    "code": "def change_port_speed(self, instance_id, public, speed):\n        if public:\n            return self.client.call('Virtual_Guest', 'setPublicNetworkInterfaceSpeed',\n                                    speed, id=instance_id)\n        else:\n            return self.client.call('Virtual_Guest', 'setPrivateNetworkInterfaceSpeed',\n                                    speed, id=instance_id)",
    "docstring": "Allows you to change the port speed of a virtual server's NICs.\n\n        Example::\n\n            #change the Public interface to 10Mbps on instance 12345\n            result = mgr.change_port_speed(instance_id=12345,\n                                        public=True, speed=10)\n            # result will be True or an Exception\n\n        :param int instance_id: The ID of the VS\n        :param bool public: Flag to indicate which interface to change.\n                            True (default) means the public interface.\n                            False indicates the private interface.\n        :param int speed: The port speed to set.\n\n        .. warning::\n            A port speed of 0 will disable the interface."
  },
  {
    "code": "def release(self):\n        self.parent.send(('release-account', self.account_hash))\n        response = self.parent.recv()\n        if isinstance(response, Exception):\n            raise response\n        if response != 'ok':\n            raise ValueError('unexpected response: ' + repr(response))",
    "docstring": "Unlocks the account."
  },
  {
    "code": "def pi_revision():\n    with open('/proc/cpuinfo', 'r') as infile:\n        for line in infile:\n            match = re.match('Revision\\s+:\\s+.*(\\w{4})$', line, flags=re.IGNORECASE)\n            if match and match.group(1) in ['0000', '0002', '0003']:\n                return 1\n            elif match:\n                return 2\n        raise RuntimeError('Could not determine Raspberry Pi revision.')",
    "docstring": "Detect the revision number of a Raspberry Pi, useful for changing\n    functionality like default I2C bus based on revision."
  },
  {
    "code": "def set_stats(stats, value):\n    stats[\"total_count\"] += 1\n    stats[\"value\"] += value\n    stats[\"average\"] = stats[\"value\"] / stats[\"total_count\"]\n    if value > stats[\"max\"]:\n        stats[\"max\"] = value\n    if value < stats[\"min\"] or stats[\"min\"] == 0:\n        stats[\"min\"] = value",
    "docstring": "Updates the stats with the value passed in.\n\n    :param stats: :class: `dict`\n    :param value: :class: `int`"
  },
  {
    "code": "def access_storage_edit(name, cid, uid, perm, **kwargs):\n    ctx = Context(**kwargs)\n    ctx.execute_action('access:storage:edit', **{\n        'storage': ctx.repo.create_secure_service('storage'),\n        'name': name,\n        'cids': cid,\n        'uids': uid,\n        'perm': perm,\n    })",
    "docstring": "Edits ACL for the specified collection.\n\n    Creates if necessary."
  },
  {
    "code": "def copy(self, new_path, replace=False):\n        if replace or not get_file(new_path).exists():\n            self.key.copy(self.key.bucket, new_path)\n            return True\n        return False",
    "docstring": "Uses boto to copy the file to the new path instead of uploading another file to the new key"
  },
  {
    "code": "def visit_for(self, node):\n        fors = \"for %s in %s:\\n%s\" % (\n            node.target.accept(self),\n            node.iter.accept(self),\n            self._stmt_list(node.body),\n        )\n        if node.orelse:\n            fors = \"%s\\nelse:\\n%s\" % (fors, self._stmt_list(node.orelse))\n        return fors",
    "docstring": "return an astroid.For node as string"
  },
  {
    "code": "def transform_generator(fn):\n    if six.PY2:\n        fn.func_dict['is_transform_generator'] = True\n    else:\n        fn.__dict__['is_transform_generator'] = True\n    return fn",
    "docstring": "A decorator that marks transform pipes that should be called to create the real transform"
  },
  {
    "code": "def get_plugin_apps(self):\n    return {\n        _ACK_ROUTE: self._serve_ack,\n        _COMM_ROUTE: self._serve_comm,\n        _DEBUGGER_GRPC_HOST_PORT_ROUTE: self._serve_debugger_grpc_host_port,\n        _DEBUGGER_GRAPH_ROUTE: self._serve_debugger_graph,\n        _GATED_GRPC_ROUTE: self._serve_gated_grpc,\n        _TENSOR_DATA_ROUTE: self._serve_tensor_data,\n        _SOURCE_CODE_ROUTE: self._serve_source_code,\n    }",
    "docstring": "Obtains a mapping between routes and handlers.\n\n    This function also starts a debugger data server on separate thread if the\n    plugin has not started one yet.\n\n    Returns:\n      A mapping between routes and handlers (functions that respond to\n      requests)."
  },
  {
    "code": "def preserve_namespace(newns=None):\n    ns = cmds.namespaceInfo(an=True)\n    try:\n        cmds.namespace(set=newns)\n        yield\n    finally:\n        cmds.namespace(set=ns)",
    "docstring": "Contextmanager that will restore the current namespace\n\n    :param newns: a name of namespace that should be set in the beginning. the original namespace will be restored afterwards.\n                  If None, does not set a namespace.\n    :type newns: str | None\n    :returns: None\n    :rtype: None\n    :raises: None"
  },
  {
    "code": "def make_dir_structure(base_dir):\n    def maybe_makedir(*args):\n        p = join(base_dir, *args)\n        if exists(p) and not isdir(p):\n            raise IOError(\"File '{}' exists but is not a directory \".format(p))\n        if not exists(p):\n            makedirs(p)\n    maybe_makedir(DOWNLOAD_DIR)\n    maybe_makedir(PACKAGE_DIR)\n    maybe_makedir(OLD_DIR)",
    "docstring": "Make the build directory structure."
  },
  {
    "code": "def paste(self):\r\n        html = QApplication.clipboard().text()\r\n        if not self.isRichTextEditEnabled():\r\n            self.insertPlainText(projex.text.toAscii(html))\r\n        else:\r\n            super(XTextEdit, self).paste()",
    "docstring": "Pastes text from the clipboard into this edit."
  },
  {
    "code": "def download_image(self, handle, dest):\n        shutil.copyfile(self._prefixed(handle), dest)",
    "docstring": "Copies over the handl to the destination\n\n        Args:\n            handle (str): path to copy over\n            dest (str): path to copy to\n\n        Returns:\n            None"
  },
  {
    "code": "def get_job_id_from_name(self, job_name):\n        jobs = self._client.list_jobs(jobQueue=self._queue, jobStatus='RUNNING')['jobSummaryList']\n        matching_jobs = [job for job in jobs if job['jobName'] == job_name]\n        if matching_jobs:\n            return matching_jobs[0]['jobId']",
    "docstring": "Retrieve the first job ID matching the given name"
  },
  {
    "code": "def filter_options(cls, kwargs, keys):\n        return dict((k, v) for k, v in filter_kwargs(keys, kwargs))",
    "docstring": "Make optional kwargs valid and optimized for each template engines.\n\n        :param kwargs: keyword arguements to process\n        :param keys: optional argument names\n\n        >>> Engine.filter_options(dict(aaa=1, bbb=2), (\"aaa\", ))\n        {'aaa': 1}\n        >>> Engine.filter_options(dict(bbb=2), (\"aaa\", ))\n        {}"
  },
  {
    "code": "async def _request(self, method, *args, **kwargs):\n        if not self.open:\n            await self._connect()\n        while self.waiting:\n            await asyncio.sleep(0.1)\n        if self.client.protocol is None or not self.client.protocol.connected:\n            raise TimeoutError(\"Not connected to device.\")\n        try:\n            future = getattr(self.client.protocol, method)(*args, **kwargs)\n        except AttributeError:\n            raise TimeoutError(\"Not connected to device.\")\n        self.waiting = True\n        try:\n            return await asyncio.wait_for(future, timeout=self.timeout)\n        except asyncio.TimeoutError as e:\n            if self.open:\n                if hasattr(self, 'modbus'):\n                    self.client.protocol_lost_connection(self.modbus)\n                self.open = False\n            raise TimeoutError(e)\n        except pymodbus.exceptions.ConnectionException as e:\n            raise ConnectionError(e)\n        finally:\n            self.waiting = False",
    "docstring": "Send a request to the device and awaits a response.\n\n        This mainly ensures that requests are sent serially, as the Modbus\n        protocol does not allow simultaneous requests (it'll ignore any\n        request sent while it's processing something). The driver handles this\n        by assuming there is only one client instance. If other clients\n        exist, other logic will have to be added to either prevent or manage\n        race conditions."
  },
  {
    "code": "def get_all_pipelines(app=''):\n    url = '{host}/applications/{app}/pipelineConfigs'.format(host=API_URL, app=app)\n    response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)\n    assert response.ok, 'Could not retrieve Pipelines for {0}.'.format(app)\n    pipelines = response.json()\n    LOG.debug('Pipelines:\\n%s', pipelines)\n    return pipelines",
    "docstring": "Get a list of all the Pipelines in _app_.\n\n    Args:\n        app (str): Name of Spinnaker Application.\n\n    Returns:\n        requests.models.Response: Response from Gate containing Pipelines."
  },
  {
    "code": "def set_cookie(response, name, value, expiry_seconds=None, secure=False):\n    if expiry_seconds is None:\n        expiry_seconds = 90 * 24 * 60 * 60\n    expires = datetime.strftime(datetime.utcnow() +\n                                timedelta(seconds=expiry_seconds),\n                                \"%a, %d-%b-%Y %H:%M:%S GMT\")\n    try:\n        response.set_cookie(name, value, expires=expires, secure=secure)\n    except (KeyError, TypeError):\n        response.set_cookie(name.encode('utf-8'), value, expires=expires,\n                            secure=secure)",
    "docstring": "Set cookie wrapper that allows number of seconds to be given as the\n    expiry time, and ensures values are correctly encoded."
  },
  {
    "code": "def _extra_stats(self):\n        return ['loglr'] + \\\n               ['{}_optimal_snrsq'.format(det) for det in self._data] + \\\n               ['{}_matchedfilter_snrsq'.format(det) for det in self._data]",
    "docstring": "Adds ``loglr``, ``optimal_snrsq`` and matched filter snrsq in each\n        detector to the default stats."
  },
  {
    "code": "def histogram(title, title_x, title_y,\n              x, bins_x):\n    plt.figure()\n    plt.hist(x, bins_x)\n    plt.xlabel(title_x)\n    plt.ylabel(title_y)\n    plt.title(title)",
    "docstring": "Plot a basic histogram."
  },
  {
    "code": "def add_node_from_data(self, node: BaseEntity) -> BaseEntity:\n        assert isinstance(node, BaseEntity)\n        if node in self:\n            return node\n        self.add_node(node)\n        if VARIANTS in node:\n            self.add_has_variant(node.get_parent(), node)\n        elif MEMBERS in node:\n            for member in node[MEMBERS]:\n                self.add_has_component(node, member)\n        elif PRODUCTS in node and REACTANTS in node:\n            for reactant_tokens in node[REACTANTS]:\n                self.add_has_reactant(node, reactant_tokens)\n            for product_tokens in node[PRODUCTS]:\n                self.add_has_product(node, product_tokens)\n        return node",
    "docstring": "Add an entity to the graph."
  },
  {
    "code": "def state_dict(self) -> Dict[str, Any]:\n        return {key: value for key, value in self.__dict__.items() if key != 'optimizer'}",
    "docstring": "Returns the state of the scheduler as a ``dict``."
  },
  {
    "code": "def wiggleFileHandleToProtocol(self, fileHandle):\n        for line in fileHandle:\n            self.readWiggleLine(line)\n        return self._data",
    "docstring": "Return a continuous protocol object satsifiying the given query\n        parameters from the given wiggle file handle."
  },
  {
    "code": "def conv2d(self, x_in: Connection, w_in: Connection, receptive_field_size, filters_number, stride=1, padding=1,\n               name=\"\"):\n        x_cols = self.tensor_3d_to_cols(x_in, receptive_field_size, stride=stride, padding=padding)\n        mul = self.transpose(self.matrix_multiply(x_cols, w_in), 0, 2, 1)\n        output = self.reshape(mul, (-1, filters_number, receptive_field_size, receptive_field_size))\n        output.name = name\n        return output",
    "docstring": "Computes a 2-D convolution given 4-D input and filter tensors."
  },
  {
    "code": "def url_add_params(url, **kwargs):\n    parsed_url = urlparse.urlsplit(url)\n    params = urlparse.parse_qsl(parsed_url.query)\n    parsed_url = list(parsed_url)\n    for pair in kwargs.iteritems():\n        params.append(pair)\n    parsed_url[3] = urllib.urlencode(params)\n    return urlparse.urlunsplit(parsed_url)",
    "docstring": "Add parameters to an url\n\n    >>> url_add_params('http://example.com/', a=1, b=3)\n    'http://example.com/?a=1&b=3'\n    >>> url_add_params('http://example.com/?c=8', a=1, b=3)\n    'http://example.com/?c=8&a=1&b=3'\n    >>> url_add_params('http://example.com/#/irock', a=1, b=3)\n    'http://example.com/?a=1&b=3#/irock'\n    >>> url_add_params('http://example.com/?id=10#/irock', a=1, b=3)\n    'http://example.com/?id=10&a=1&b=3#/irock'"
  },
  {
    "code": "def name(self):\n        return ffi.string(\n            lib.EnvGetDeftemplateName(self._env, self._tpl)).decode()",
    "docstring": "Template name."
  },
  {
    "code": "def get_cert_serial(cert_file):\n    cmd = \"certutil.exe -silent -verify {0}\".format(cert_file)\n    out = __salt__['cmd.run'](cmd)\n    matches = re.search(r\":\\s*(\\w*)\\r\\n\\r\\n\", out)\n    if matches is not None:\n        return matches.groups()[0].strip()\n    else:\n        return None",
    "docstring": "Get the serial number of a certificate file\n\n    cert_file\n        The certificate file to find the serial for\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' certutil.get_cert_serial <certificate name>"
  },
  {
    "code": "def cut_references(text_lines):\n    ref_sect_start = find_reference_section(text_lines)\n    if ref_sect_start is not None:\n        start = ref_sect_start[\"start_line\"]\n        end = find_end_of_reference_section(text_lines, start,\n                                            ref_sect_start[\"marker\"],\n                                            ref_sect_start[\"marker_pattern\"])\n        del text_lines[start:end + 1]\n    else:\n        current_app.logger.warning(\"Found no references to remove.\")\n        return text_lines\n    return text_lines",
    "docstring": "Return the text lines with the references cut."
  },
  {
    "code": "def _check_iscsi_rest_patch_allowed(self):\n        headers, bios_uri, bios_settings = self._check_bios_resource()\n        if('links' in bios_settings and 'iScsi' in bios_settings['links']):\n            iscsi_uri = bios_settings['links']['iScsi']['href']\n            status, headers, settings = self._rest_get(iscsi_uri)\n            if status != 200:\n                msg = self._get_extended_error(settings)\n                raise exception.IloError(msg)\n            if not self._operation_allowed(headers, 'PATCH'):\n                headers, iscsi_uri, settings = (\n                    self._get_iscsi_settings_resource(settings))\n                self._validate_if_patch_supported(headers, iscsi_uri)\n            return iscsi_uri\n        else:\n            msg = ('\"links/iScsi\" section in bios'\n                   ' does not exist')\n            raise exception.IloCommandNotSupportedError(msg)",
    "docstring": "Checks if patch is supported on iscsi.\n\n        :returns: iscsi url.\n        :raises: IloError, on an error from iLO.\n        :raises: IloCommandNotSupportedError, if the command is not supported\n                 on the server."
  },
  {
    "code": "def cwise(tf_fn, xs, output_dtype=None, grad_function=None, name=None):\n  return slicewise(\n      tf_fn, xs, output_dtype=output_dtype, splittable_dims=xs[0].shape.dims,\n      grad_function=grad_function, name=name or \"cwise\")",
    "docstring": "Component-wise operation with no broadcasting.\n\n  Args:\n    tf_fn: a component-wise function taking n tf.Tensor inputs and producing\n      a tf.Tensor output\n    xs: n Tensors\n    output_dtype: an optional dtype\n    grad_function: an optional python function\n    name: an optional string\n\n  Returns:\n    a Tensor"
  },
  {
    "code": "def encode_conjure_union_type(cls, obj):\n        encoded = {}\n        encoded[\"type\"] = obj.type\n        for attr, field_definition in obj._options().items():\n            if field_definition.identifier == obj.type:\n                attribute = attr\n                break\n        else:\n            raise ValueError(\n                \"could not find attribute for union \" +\n                \"member {0} of type {1}\".format(obj.type, obj.__class__)\n            )\n        defined_field_definition = obj._options()[attribute]\n        encoded[defined_field_definition.identifier] = cls.do_encode(\n            getattr(obj, attribute)\n        )\n        return encoded",
    "docstring": "Encodes a conjure union into json"
  },
  {
    "code": "def handle_message(self, msg):\n        self._messages.append({\n            'type': msg.category,\n            'module': msg.module,\n            'obj': msg.obj,\n            'line': msg.line,\n            'column': msg.column,\n            'path': msg.path,\n            'symbol': msg.symbol,\n            'message': str(msg.msg) or '',\n            'message-id': msg.msg_id,\n        })",
    "docstring": "Store new message for later use.\n\n        .. seealso:: :meth:`~JsonExtendedReporter.on_close`"
  },
  {
    "code": "def save(self):\n        for name in self.mutedGlyphsNames:\n            if name not in self.font: continue\n            if self.logger:\n                self.logger.info(\"removing muted glyph %s\", name)\n            del self.font[name]\n        directory = os.path.dirname(os.path.normpath(self.path))\n        if directory and not os.path.exists(directory):\n            os.makedirs(directory)\n        try:\n            self.font.save(os.path.abspath(self.path), self.ufoVersion)\n        except defcon.DefconError as error:\n            if self.logger:\n                self.logger.exception(\"Error generating.\")\n            return False, error.report\n        return True, None",
    "docstring": "Save the UFO."
  },
  {
    "code": "def to_dict(self):\n        task_desc_as_dict = {\n            'uid': self._uid,\n            'name': self._name,\n            'state': self._state,\n            'state_history': self._state_history,\n            'pre_exec': self._pre_exec,\n            'executable': self._executable,\n            'arguments': self._arguments,\n            'post_exec': self._post_exec,\n            'cpu_reqs': self._cpu_reqs,\n            'gpu_reqs': self._gpu_reqs,\n            'lfs_per_process': self._lfs_per_process,\n            'upload_input_data': self._upload_input_data,\n            'copy_input_data': self._copy_input_data,\n            'link_input_data': self._link_input_data,\n            'move_input_data': self._move_input_data,\n            'copy_output_data': self._copy_output_data,\n            'move_output_data': self._move_output_data,\n            'download_output_data': self._download_output_data,\n            'stdout': self._stdout,\n            'stderr': self._stderr,\n            'exit_code': self._exit_code,\n            'path': self._path,\n            'tag': self._tag,\n            'parent_stage': self._p_stage,\n            'parent_pipeline': self._p_pipeline,\n        }\n        return task_desc_as_dict",
    "docstring": "Convert current Task into a dictionary\n\n        :return: python dictionary"
  },
  {
    "code": "def add_component_definition(self, definition):\n        if definition.identity not in self._components.keys():\n            self._components[definition.identity] = definition\n        else:\n            raise ValueError(\"{} has already been defined\".format(definition.identity))",
    "docstring": "Add a ComponentDefinition to the document"
  },
  {
    "code": "def featureclass_to_json(fc):\n    if arcpyFound == False:\n        raise Exception(\"ArcPy is required to use this function\")\n    desc = arcpy.Describe(fc)\n    if desc.dataType == \"Table\" or desc.dataType == \"TableView\":\n        return recordset_to_json(table=fc)\n    else:\n        return arcpy.FeatureSet(fc).JSON",
    "docstring": "converts a feature class to JSON"
  },
  {
    "code": "def format_ret(return_set, as_json=False):\n    ret_list = list()\n    for item in return_set:\n        d = {\"ip\": item}\n        ret_list.append(d)\n    if as_json:\n        return json.dumps(ret_list)\n    return ret_list",
    "docstring": "decouple, allow for modifications to return type\n        returns a list of ip addresses in object or json form"
  },
  {
    "code": "def from_content(cls, content):\n        if \"An internal error has occurred\" in content:\n            return None\n        parsed_content = parse_tibiacom_content(content)\n        try:\n            name_header = parsed_content.find('h1')\n            guild = Guild(name_header.text.strip())\n        except AttributeError:\n            raise InvalidContent(\"content does not belong to a Tibia.com guild page.\")\n        if not guild._parse_logo(parsed_content):\n            raise InvalidContent(\"content does not belong to a Tibia.com guild page.\")\n        info_container = parsed_content.find(\"div\", id=\"GuildInformationContainer\")\n        guild._parse_guild_info(info_container)\n        guild._parse_application_info(info_container)\n        guild._parse_guild_homepage(info_container)\n        guild._parse_guild_guildhall(info_container)\n        guild._parse_guild_disband_info(info_container)\n        guild._parse_guild_members(parsed_content)\n        if guild.guildhall and guild.members:\n            guild.guildhall.owner = guild.members[0].name\n        return guild",
    "docstring": "Creates an instance of the class from the HTML content of the guild's page.\n\n        Parameters\n        -----------\n        content: :class:`str`\n            The HTML content of the page.\n\n        Returns\n        ----------\n        :class:`Guild`\n            The guild contained in the page or None if it doesn't exist.\n\n        Raises\n        ------\n        InvalidContent\n            If content is not the HTML of a guild's page."
  },
  {
    "code": "def _get_dbt_columns_from_bq_table(self, table):\n        \"Translates BQ SchemaField dicts into dbt BigQueryColumn objects\"\n        columns = []\n        for col in table.schema:\n            dtype = self.Column.translate_type(col.field_type)\n            column = self.Column(\n                col.name, dtype, col.fields, col.mode)\n            columns.append(column)\n        return columns",
    "docstring": "Translates BQ SchemaField dicts into dbt BigQueryColumn objects"
  },
  {
    "code": "def _accumulate_random(count, found, oldthing, newthing):\n    if randint(1, count + found) <= found:\n        return count + found, newthing\n    else:\n        return count + found, oldthing",
    "docstring": "This performs on-line random selection.\n\n    We have a stream of objects\n\n        o_1,c_1; o_2,c_2; ...\n\n    where there are c_i equivalent objects like o_1.  We'd like to pick\n    a random object o uniformly at random from the list\n\n        [o_1]*c_1 + [o_2]*c_2 + ...\n\n    (actually, this algorithm allows arbitrary positive weights, not\n    necessarily integers)  without spending the time&space to actually\n    create that list.  Luckily, the following works:\n\n        thing = None\n        c_tot\n        for o_n, c_n in things:\n            c_tot += c_n\n            if randint(1,c_tot) <= c_n:\n                thing = o_n\n\n    This function is written in an accumulator format, so it can be\n    used one call at a time:\n\n    EXAMPLE:\n        > thing = None\n        > count = 0\n        > for i in range(10):\n        >     c = 10-i\n        >     count, thing = accumulate_random(count,c,thing,i)\n\n\n    INPUTS:\n        count: integer, sum of weights found before newthing\n        found: integer, weight for newthing\n        oldthing: previously selected object (will never be selected\n                  if count == 0)\n        newthing: incoming object\n\n    OUTPUT:\n        (newcount, pick): newcount is count+found, pick is the newly\n                          selected object."
  },
  {
    "code": "def load(cls, filename, gzipped, byteorder='big'):\r\n        open_file = gzip.open if gzipped else open\r\n        with open_file(filename, 'rb') as buff:\r\n            return cls.from_buffer(buff, byteorder)",
    "docstring": "Read, parse and return the file at the specified location.\r\n\r\n        The `gzipped` argument is used to indicate if the specified\r\n        file is gzipped. The `byteorder` argument lets you specify\r\n        whether the file is big-endian or little-endian."
  },
  {
    "code": "def dfs_recursive(graph, node, seen):\n    seen[node] = True\n    for neighbor in graph[node]:\n        if not seen[neighbor]:\n            dfs_recursive(graph, neighbor, seen)",
    "docstring": "DFS, detect connected component, recursive implementation\n\n    :param graph: directed graph in listlist or listdict format\n    :param int node: to start graph exploration\n    :param boolean-table seen: will be set true for the connected component\n          containing node.\n    :complexity: `O(|V|+|E|)`"
  },
  {
    "code": "def init_app(self, app):\n        if not hasattr(app, 'extensions'):\n            app.extensions = {}\n        app.extensions['flask-jwt-simple'] = self\n        self._set_default_configuration_options(app)\n        self._set_error_handler_callbacks(app)\n        app.config['PROPAGATE_EXCEPTIONS'] = True",
    "docstring": "Register this extension with the flask app\n\n        :param app: A flask application"
  },
  {
    "code": "def construct_ctcp(*parts):\n    message = ' '.join(parts)\n    message = message.replace('\\0', CTCP_ESCAPE_CHAR + '0')\n    message = message.replace('\\n', CTCP_ESCAPE_CHAR + 'n')\n    message = message.replace('\\r', CTCP_ESCAPE_CHAR + 'r')\n    message = message.replace(CTCP_ESCAPE_CHAR, CTCP_ESCAPE_CHAR + CTCP_ESCAPE_CHAR)\n    return CTCP_DELIMITER + message + CTCP_DELIMITER",
    "docstring": "Construct CTCP message."
  },
  {
    "code": "def _worker_status(target,\n                   worker,\n                   activation,\n                   profile='default',\n                   tgt_type='glob'):\n    ret = {\n        'result': True,\n        'errors': [],\n        'wrong_state': [],\n    }\n    args = [worker, profile]\n    status = __salt__['publish.publish'](\n        target, 'modjk.worker_status', args, tgt_type\n    )\n    if not status:\n        ret['result'] = False\n        return ret\n    for balancer in status:\n        if not status[balancer]:\n            ret['errors'].append(balancer)\n        elif status[balancer]['activation'] != activation:\n            ret['wrong_state'].append(balancer)\n    return ret",
    "docstring": "Check if the worker is in `activation` state in the targeted load balancers\n\n    The function will return the following dictionary:\n        result - False if no server returned from the published command\n        errors - list of servers that couldn't find the worker\n        wrong_state - list of servers that the worker was in the wrong state\n                      (not activation)"
  },
  {
    "code": "def to_chords(progression, key='C'):\n    if type(progression) == str:\n        progression = [progression]\n    result = []\n    for chord in progression:\n        (roman_numeral, acc, suffix) = parse_string(chord)\n        if roman_numeral not in numerals:\n            return []\n        if suffix == '7' or suffix == '':\n            roman_numeral += suffix\n            r = chords.__dict__[roman_numeral](key)\n        else:\n            r = chords.__dict__[roman_numeral](key)\n            r = chords.chord_shorthand[suffix](r[0])\n        while acc < 0:\n            r = map(notes.diminish, r)\n            acc += 1\n        while acc > 0:\n            r = map(notes.augment, r)\n            acc -= 1\n        result.append(r)\n    return result",
    "docstring": "Convert a list of chord functions or a string to a list of chords.\n\n    Examples:\n    >>> to_chords(['I', 'V7'])\n    [['C', 'E', 'G'], ['G', 'B', 'D', 'F']]\n    >>> to_chords('I7')\n    [['C', 'E', 'G', 'B']]\n\n    Any number of accidentals can be used as prefix to augment or diminish;\n    for example: bIV or #I.\n    \n    All the chord abbreviations in the chord module can be used as suffixes;\n    for example: Im7, IVdim7, etc.\n    \n    You can combine prefixes and suffixes to manage complex progressions:\n    #vii7, #iidim7, iii7, etc.\n    \n    Using 7 as suffix is ambiguous, since it is classicly used to denote the\n    seventh chord when talking about progressions instead of just the\n    dominant seventh chord. We have taken the classic route; I7 will get\n    you a major seventh chord. If you specifically want a dominanth seventh,\n    use Idom7."
  },
  {
    "code": "def _validate_open_msg(self, open_msg):\n        assert open_msg.type == BGP_MSG_OPEN\n        opt_param_cap_map = open_msg.opt_param_cap_map\n        remote_as = open_msg.my_as\n        cap4as = opt_param_cap_map.get(BGP_CAP_FOUR_OCTET_AS_NUMBER, None)\n        if cap4as is None:\n            if remote_as == AS_TRANS:\n                raise bgp.BadPeerAs()\n            self.cap_four_octet_as_number = False\n        else:\n            remote_as = cap4as.as_number\n            self.cap_four_octet_as_number = True\n        if remote_as != self._peer.remote_as:\n            raise bgp.BadPeerAs()\n        if open_msg.version != BGP_VERSION_NUM:\n            raise bgp.UnsupportedVersion(BGP_VERSION_NUM)",
    "docstring": "Validates BGP OPEN message according from application context.\n\n        Parsing modules takes care of validating OPEN message that need no\n        context. But here we validate it according to current application\n        settings. RTC or RR/ERR are MUST capability if peer does not support\n        either one of them we have to end session."
  },
  {
    "code": "def makepipebranch(idf, bname):\n    pname = \"%s_pipe\" % (bname,)\n    apipe = makepipecomponent(idf, pname)\n    abranch = idf.newidfobject(\"BRANCH\", Name=bname)\n    abranch.Component_1_Object_Type = 'Pipe:Adiabatic'\n    abranch.Component_1_Name = pname\n    abranch.Component_1_Inlet_Node_Name = apipe.Inlet_Node_Name\n    abranch.Component_1_Outlet_Node_Name = apipe.Outlet_Node_Name\n    abranch.Component_1_Branch_Control_Type = \"Bypass\"\n    return abranch",
    "docstring": "make a branch with a pipe\n    use standard inlet outlet names"
  },
  {
    "code": "def pad(a, desiredlength):\n    if len(a) >= desiredlength:\n        return a\n    islist = isinstance(a, list)\n    a = np.array(a)\n    diff = desiredlength - len(a)\n    shape = list(a.shape)\n    shape[0] = diff\n    padded = np.concatenate([a, np.zeros(shape, dtype=a.dtype)])\n    return padded.tolist() if islist else padded",
    "docstring": "Pad an n-dimensional numpy array with zeros along the zero-th dimension\n    so that it is the desired length.  Return it unchanged if it is greater\n    than or equal to the desired length"
  },
  {
    "code": "def check_dependee_exists(self, depender, dependee, dependee_id):\n\t\tshutit_global.shutit_global_object.yield_to_draw()\n\t\tif dependee is None:\n\t\t\treturn 'module: \\n\\n' + dependee_id + '\\n\\nnot found in paths: ' + str(self.host['shutit_module_path']) + ' but needed for ' + depender.module_id + '\\nCheck your --shutit_module_path setting and ensure that all modules configured to be built are in that path setting, eg \"--shutit_module_path /path/to/other/module/:.\"\\n\\nAlso check that the module is configured to be built with the correct module id in that module\\'s configs/build.cnf file.\\n\\nSee also help.'\n\t\treturn ''",
    "docstring": "Checks whether a depended-on module is available."
  },
  {
    "code": "def build_current_graph():\n    graph = SQLStateGraph()\n    for app_name, config in apps.app_configs.items():\n        try:\n            module = import_module(\n                '.'.join((config.module.__name__, SQL_CONFIG_MODULE)))\n            sql_items = module.sql_items\n        except (ImportError, AttributeError):\n            continue\n        for sql_item in sql_items:\n            graph.add_node((app_name, sql_item.name), sql_item)\n            for dep in sql_item.dependencies:\n                graph.add_lazy_dependency((app_name, sql_item.name), dep)\n    graph.build_graph()\n    return graph",
    "docstring": "Read current state of SQL items from the current project state.\n\n    Returns:\n        (SQLStateGraph) Current project state graph."
  },
  {
    "code": "def attach_protocol(self, proto):\n        if self._protocol is not None:\n            raise RuntimeError(\"Already have a protocol.\")\n        self.save()\n        self.__dict__['_protocol'] = proto\n        del self.__dict__['_accept_all_']\n        self.__dict__['post_bootstrap'] = defer.Deferred()\n        if proto.post_bootstrap:\n            proto.post_bootstrap.addCallback(self.bootstrap)\n        return self.__dict__['post_bootstrap']",
    "docstring": "returns a Deferred that fires once we've set this object up to\n        track the protocol. Fails if we already have a protocol."
  },
  {
    "code": "def to_line_protocol(self):\n        tags = self.get_output_tags()\n        return u\"{0}{1} {2}{3}\".format(\n            self.get_output_measurement(),\n            \",\" + tags if tags else '',\n            self.get_output_values(),\n            self.get_output_timestamp()\n        )",
    "docstring": "Converts the given metrics as a single line of InfluxDB line protocol"
  },
  {
    "code": "def do_tagg(self, arglist: List[str]):\n        if len(arglist) >= 2:\n            tag = arglist[0]\n            content = arglist[1:]\n            self.poutput('<{0}>{1}</{0}>'.format(tag, ' '.join(content)))\n        else:\n            self.perror(\"tagg requires at least 2 arguments\")",
    "docstring": "version of creating an html tag using arglist instead of argparser"
  },
  {
    "code": "def parseFASTAFilteringCommandLineOptions(args, reads):\n    keepSequences = (\n        parseRangeString(args.keepSequences, convertToZeroBased=True)\n        if args.keepSequences else None)\n    removeSequences = (\n        parseRangeString(args.removeSequences, convertToZeroBased=True)\n        if args.removeSequences else None)\n    return reads.filter(\n        minLength=args.minLength, maxLength=args.maxLength,\n        whitelist=set(args.whitelist) if args.whitelist else None,\n        blacklist=set(args.blacklist) if args.blacklist else None,\n        whitelistFile=args.whitelistFile, blacklistFile=args.blacklistFile,\n        titleRegex=args.titleRegex,\n        negativeTitleRegex=args.negativeTitleRegex,\n        keepSequences=keepSequences, removeSequences=removeSequences,\n        head=args.head, removeDuplicates=args.removeDuplicates,\n        removeDuplicatesById=args.removeDuplicatesById,\n        randomSubset=args.randomSubset, trueLength=args.trueLength,\n        sampleFraction=args.sampleFraction,\n        sequenceNumbersFile=args.sequenceNumbersFile)",
    "docstring": "Examine parsed FASTA filtering command-line options and return filtered\n    reads.\n\n    @param args: An argparse namespace, as returned by the argparse\n        C{parse_args} function.\n    @param reads: A C{Reads} instance to filter.\n    @return: The filtered C{Reads} instance."
  },
  {
    "code": "def wait(self, *, timeout=None):\n        for _ in self.get_results(block=True, timeout=timeout):\n            pass",
    "docstring": "Block until all the jobs in the group have finished or\n        until the timeout expires.\n\n        Parameters:\n          timeout(int): The maximum amount of time, in ms, to wait.\n            Defaults to 10 seconds."
  },
  {
    "code": "def _hack_namedtuple(cls):\n    name = cls.__name__\n    fields = cls._fields\n    def __reduce__(self):\n        return (_restore, (name, fields, tuple(self)))\n    cls.__reduce__ = __reduce__\n    cls._is_namedtuple_ = True\n    return cls",
    "docstring": "Make class generated by namedtuple picklable"
  },
  {
    "code": "def get_gravatar(email, size=80, rating='g', default=None,\n                 protocol=PROTOCOL):\n    gravatar_protocols = {'http': 'http://www',\n                          'https': 'https://secure'}\n    url = '%s.gravatar.com/avatar/%s' % (\n        gravatar_protocols[protocol],\n        md5(email.strip().lower().encode('utf-8')).hexdigest())\n    options = {'s': size, 'r': rating}\n    if default:\n        options['d'] = default\n    url = '%s?%s' % (url, urlencode(options))\n    return url.replace('&', '&amp;')",
    "docstring": "Return url for a Gravatar."
  },
  {
    "code": "def get_authenticity_token(self, url=_SIGNIN_URL):\n        res = self.client._get(url=url, expected_status_code=200)\n        soup = BeautifulSoup(res.text, _DEFAULT_BEAUTIFULSOUP_PARSER)\n        selection = soup.select(_AUTHENTICITY_TOKEN_SELECTOR)\n        try:\n            authenticity_token = selection[0].get(\"content\")\n        except:\n            raise ValueError(\n                \"authenticity_token not found in {} with {}\\n{}\".format(\n                 _SIGNIN_URL, _AUTHENTICITY_TOKEN_SELECTOR, res.text))\n        return authenticity_token",
    "docstring": "Returns an authenticity_token, mandatory for signing in"
  },
  {
    "code": "def _updateEndpoints(self,*args,**kwargs):\n        sender = self.sender()\n        if not self.ignoreEvents:\n            self.ignoreEvents = True\n            for binding in self.bindings.values():\n                if binding.instanceId == id(sender):\n                    continue\n                if args: \n                    binding.setter(*args,**kwargs)\n                else:\n                    binding.setter(self.bindings[id(sender)].getter())\n            self.ignoreEvents = False",
    "docstring": "Updates all endpoints except the one from which this slot was called.\n\n        Note: this method is probably not complete threadsafe. Maybe a lock is needed when setter self.ignoreEvents"
  },
  {
    "code": "def _generateGUID(slnfile, name):\n    m = hashlib.md5()\n    m.update(bytearray(ntpath.normpath(str(slnfile)) + str(name),'utf-8'))\n    solution = m.hexdigest().upper()\n    solution = \"{\" + solution[:8] + \"-\" + solution[8:12] + \"-\" + solution[12:16] + \"-\" + solution[16:20] + \"-\" + solution[20:32] + \"}\"\n    return solution",
    "docstring": "This generates a dummy GUID for the sln file to use.  It is\n    based on the MD5 signatures of the sln filename plus the name of\n    the project.  It basically just needs to be unique, and not\n    change with each invocation."
  },
  {
    "code": "def visit_constant(self, node, parent):\n        return nodes.Const(\n            node.value,\n            getattr(node, \"lineno\", None),\n            getattr(node, \"col_offset\", None),\n            parent,\n        )",
    "docstring": "visit a Constant node by returning a fresh instance of Const"
  },
  {
    "code": "def mid(self, value):\n        if not isinstance(value, int) or value > 65536:\n            raise AttributeError\n        self._mid = value",
    "docstring": "Sets the MID of the message.\n\n        :type value: Integer\n        :param value: the MID\n        :raise AttributeError: if value is not int or cannot be represented on 16 bits."
  },
  {
    "code": "def update_room(self, stream_id, room_definition):\n        req_hook = 'pod/v2/room/' + str(stream_id) + '/update'\n        req_args = json.dumps(room_definition)\n        status_code, response = self.__rest__.POST_query(req_hook, req_args)\n        self.logger.debug('%s: %s' % (status_code, response))\n        return status_code, response",
    "docstring": "update a room definition"
  },
  {
    "code": "def coerce(cls, key, value):\n        if not isinstance(value, MutationDict):\n            if isinstance(value, dict):\n                return MutationDict(value)\n            return Mutable.coerce(key, value)\n        else:\n            return value",
    "docstring": "Convert plain dictionaries to MutationDict."
  },
  {
    "code": "def get_screenshot_as_file(self, filename):\n        if not filename.lower().endswith('.png'):\n            warnings.warn(\"name used for saved screenshot does not match file \"\n                          \"type. It should end with a `.png` extension\", UserWarning)\n        png = self.get_screenshot_as_png()\n        try:\n            with open(filename, 'wb') as f:\n                f.write(png)\n        except IOError:\n            return False\n        finally:\n            del png\n        return True",
    "docstring": "Saves a screenshot of the current window to a PNG image file. Returns\n           False if there is any IOError, else returns True. Use full paths in\n           your filename.\n\n        :Args:\n         - filename: The full path you wish to save your screenshot to. This\n           should end with a `.png` extension.\n\n        :Usage:\n            ::\n\n                driver.get_screenshot_as_file('/Screenshots/foo.png')"
  },
  {
    "code": "def _get_lonely_contract(self):\n        contracts = {}\n        try:\n            raw_res = yield from self._session.get(MAIN_URL,\n                                                   timeout=self._timeout)\n        except OSError:\n            raise PyHydroQuebecError(\"Can not get main page\")\n        content = yield from raw_res.text()\n        soup = BeautifulSoup(content, 'html.parser')\n        info_node = soup.find(\"div\", {\"class\": \"span3 contrat\"})\n        if info_node is None:\n            raise PyHydroQuebecError(\"Can not found contract\")\n        research = re.search(\"Contrat ([0-9]{4} [0-9]{5})\", info_node.text)\n        if research is not None:\n            contracts[research.group(1).replace(\" \", \"\")] = None\n        if contracts == {}:\n            raise PyHydroQuebecError(\"Can not found contract\")\n        return contracts",
    "docstring": "Get contract number when we have only one contract."
  },
  {
    "code": "def unit_vector(self):\n        return Point2D( self.x / self.magnitude, self.y / self.magnitude )",
    "docstring": "Return the unit vector."
  },
  {
    "code": "def _open_for_read(self):\n        ownerid, datasetid = parse_dataset_key(self._dataset_key)\n        response = requests.get(\n            '{}/file_download/{}/{}/{}'.format(\n                self._query_host, ownerid, datasetid, self._file_name),\n            headers={\n                'User-Agent': self._user_agent,\n                'Authorization': 'Bearer {}'.format(\n                    self._config.auth_token)\n            }, stream=True)\n        try:\n            response.raise_for_status()\n        except Exception as e:\n            raise RestApiError(cause=e)\n        self._read_response = response",
    "docstring": "open the file in read mode"
  },
  {
    "code": "def resizeToContents(self):\r\n        if self._toolbar.isVisible():\r\n            doc = self.document()\r\n            h = doc.documentLayout().documentSize().height()\r\n            offset = 34\r\n            edit = self._attachmentsEdit\r\n            if self._attachments:\r\n                edit.move(2, self.height() - edit.height() - 31)\r\n                edit.setTags(sorted(self._attachments.keys()))\r\n                edit.show()\r\n                offset = 34 + edit.height()\r\n            else:\r\n                edit.hide()\r\n                offset = 34\r\n            self.setFixedHeight(h + offset)\r\n            self._toolbar.move(2, self.height() - 32)\r\n        else:\r\n            super(XCommentEdit, self).resizeToContents()",
    "docstring": "Resizes this toolbar based on the contents of its text."
  },
  {
    "code": "def _get_all_merges(routing_table):\n    considered_entries = set()\n    for i, entry in enumerate(routing_table):\n        if i in considered_entries:\n            continue\n        merge = set([i])\n        merge.update(\n            j for j, other_entry in enumerate(routing_table[i+1:], start=i+1)\n            if entry.route == other_entry.route\n        )\n        considered_entries.update(merge)\n        if len(merge) > 1:\n            yield _Merge(routing_table, merge)",
    "docstring": "Get possible sets of entries to merge.\n\n    Yields\n    ------\n    :py:class:`~.Merge`"
  },
  {
    "code": "def _prepare_errcheck():\n    def errcheck(result, *args):\n        global _exc_info_from_callback\n        if _exc_info_from_callback is not None:\n            exc = _exc_info_from_callback\n            _exc_info_from_callback = None\n            _reraise(exc[1], exc[2])\n        return result\n    for symbol in dir(_glfw):\n        if symbol.startswith('glfw'):\n            getattr(_glfw, symbol).errcheck = errcheck\n    _globals = globals()\n    for symbol in _globals:\n        if symbol.startswith('_GLFW') and symbol.endswith('fun'):\n            def wrapper_cfunctype(func, cfunctype=_globals[symbol]):\n                return cfunctype(_callback_exception_decorator(func))\n            _globals[symbol] = wrapper_cfunctype",
    "docstring": "This function sets the errcheck attribute of all ctypes wrapped functions\n    to evaluate the _exc_info_from_callback global variable and re-raise any\n    exceptions that might have been raised in callbacks.\n    It also modifies all callback types to automatically wrap the function\n    using the _callback_exception_decorator."
  },
  {
    "code": "def parseSetEnv(l):\n    d = dict()\n    for i in l:\n        try:\n            k, v = i.split('=', 1)\n        except ValueError:\n            k, v = i, None\n        if not k:\n            raise ValueError('Empty name')\n        d[k] = v\n    return d",
    "docstring": "Parses a list of strings of the form \"NAME=VALUE\" or just \"NAME\" into a dictionary. Strings\n    of the latter from will result in dictionary entries whose value is None.\n\n    :type l: list[str]\n    :rtype: dict[str,str]\n\n    >>> parseSetEnv([])\n    {}\n    >>> parseSetEnv(['a'])\n    {'a': None}\n    >>> parseSetEnv(['a='])\n    {'a': ''}\n    >>> parseSetEnv(['a=b'])\n    {'a': 'b'}\n    >>> parseSetEnv(['a=a', 'a=b'])\n    {'a': 'b'}\n    >>> parseSetEnv(['a=b', 'c=d'])\n    {'a': 'b', 'c': 'd'}\n    >>> parseSetEnv(['a=b=c'])\n    {'a': 'b=c'}\n    >>> parseSetEnv([''])\n    Traceback (most recent call last):\n    ...\n    ValueError: Empty name\n    >>> parseSetEnv(['=1'])\n    Traceback (most recent call last):\n    ...\n    ValueError: Empty name"
  },
  {
    "code": "def CommitAll(close=None):\n    if close:\n        warnings.simplefilter('default')\n        warnings.warn(\"close parameter will not need at all.\", DeprecationWarning)\n    for k, v in engine_manager.items():\n        session = v.session(create=False)\n        if session:\n            session.commit()",
    "docstring": "Commit all transactions according Local.conn"
  },
  {
    "code": "def get_config(self):\n        if 'rmq_port' in self.config:\n            self.rmq_port = int(self.config['rmq_port'])\n        if 'rmq_user' in self.config:\n            self.rmq_user = self.config['rmq_user']\n        if 'rmq_password' in self.config:\n            self.rmq_password = self.config['rmq_password']\n        if 'rmq_vhost' in self.config:\n            self.rmq_vhost = self.config['rmq_vhost']\n        if 'rmq_exchange_type' in self.config:\n            self.rmq_exchange_type = self.config['rmq_exchange_type']\n        if 'rmq_durable' in self.config:\n            self.rmq_durable = bool(self.config['rmq_durable'])\n        if 'rmq_heartbeat_interval' in self.config:\n            self.rmq_heartbeat_interval = int(\n                self.config['rmq_heartbeat_interval'])",
    "docstring": "Get and set config options from config file"
  },
  {
    "code": "def get_string(string):\n   truestring = string\n   if string is not None:\n      if '/' in string:\n         if os.path.isfile(string):\n            try:\n               with open_(string,'r') as f:\n                  truestring = ' '.join(line.strip() for line in f)\n            except: pass\n      if truestring.strip() == '': truestring = None\n   return truestring",
    "docstring": "This function checks if a path was given as string, and tries to read the\n       file and return the string."
  },
  {
    "code": "def set_default_decoder_parameters():\n    ARGTYPES = [ctypes.POINTER(DecompressionParametersType)]\n    OPENJP2.opj_set_default_decoder_parameters.argtypes = ARGTYPES\n    OPENJP2.opj_set_default_decoder_parameters.restype = ctypes.c_void_p\n    dparams = DecompressionParametersType()\n    OPENJP2.opj_set_default_decoder_parameters(ctypes.byref(dparams))\n    return dparams",
    "docstring": "Wraps openjp2 library function opj_set_default_decoder_parameters.\n\n    Sets decoding parameters to default values.\n\n    Returns\n    -------\n    dparam : DecompressionParametersType\n        Decompression parameters."
  },
  {
    "code": "def _safe_minmax(values):\n    isfinite = np.isfinite(values)\n    if np.any(isfinite):\n        values = values[isfinite]\n    minval = np.min(values)\n    maxval = np.max(values)\n    return minval, maxval",
    "docstring": "Calculate min and max of array with guards for nan and inf."
  },
  {
    "code": "def commit_api(api):\n    if api == QT_API_PYSIDE:\n        ID.forbid('PyQt4')\n        ID.forbid('PyQt5')\n    else:\n        ID.forbid('PySide')",
    "docstring": "Commit to a particular API, and trigger ImportErrors on subsequent\n       dangerous imports"
  },
  {
    "code": "def setdefault(self, key, value):\n        with self.lock:\n            if key in self:\n                return self.getitem(key)\n            else:\n                self.setitem(key, value)\n                return value",
    "docstring": "Atomic store conditional.  Stores _value_ into dictionary\n        at _key_, but only if _key_ does not already exist in the dictionary.\n        Returns the old value found or the new value."
  },
  {
    "code": "def release(self):\n        self.monitor.acquire()\n        if self.rwlock < 0:\n            self.rwlock = 0\n        else:\n            self.rwlock -= 1\n        wake_writers = self.writers_waiting and self.rwlock == 0\n        wake_readers = self.writers_waiting == 0\n        self.monitor.release()\n        if wake_writers:\n            self.writers_ok.acquire()\n            self.writers_ok.notify()\n            self.writers_ok.release()\n        elif wake_readers:\n            self.readers_ok.acquire()\n            self.readers_ok.notifyAll()\n            self.readers_ok.release()",
    "docstring": "Release a lock, whether read or write."
  },
  {
    "code": "def wrap(cls, meth):\n        async def inner(*args, **kwargs):\n            sock = await meth(*args, **kwargs)\n            return cls(sock)\n        return inner",
    "docstring": "Wraps a connection opening method in this class."
  },
  {
    "code": "def get_all_changes(self, *args, **kwds):\n        result = []\n        for project, refactoring in zip(self.projects, self.refactorings):\n            args, kwds = self._resources_for_args(project, args, kwds)\n            result.append((project, refactoring.get_changes(*args, **kwds)))\n        return result",
    "docstring": "Get a project to changes dict"
  },
  {
    "code": "def invite_user(self, user_id):\n        try:\n            self.client.api.invite_user(self.room_id, user_id)\n            return True\n        except MatrixRequestError:\n            return False",
    "docstring": "Invite a user to this room.\n\n        Returns:\n            boolean: Whether invitation was sent."
  },
  {
    "code": "def add(self, key):\n        if key not in self.map:\n            self.map[key] = len(self.items)\n            self.items.append(key)\n        return self.map[key]",
    "docstring": "Add `key` as an item to this OrderedSet, then return its index.\n\n        If `key` is already in the OrderedSet, return the index it already\n        had."
  },
  {
    "code": "def learningCurve(expPath, suite):\n  print(\"\\nLEARNING CURVE ================\",expPath,\"=====================\")\n  try:\n    headers=[\"testerror\",\"totalCorrect\",\"elapsedTime\",\"entropy\"]\n    result = suite.get_value(expPath, 0, headers, \"all\")\n    info = []\n    for i,v in enumerate(zip(result[\"testerror\"],result[\"totalCorrect\"],\n                             result[\"elapsedTime\"],result[\"entropy\"])):\n      info.append([i, v[0], v[1], int(v[2]), v[3]])\n    headers.insert(0,\"iteration\")\n    print(tabulate(info, headers=headers, tablefmt=\"grid\"))\n  except:\n    print(\"Couldn't load experiment\",expPath)",
    "docstring": "Print the test and overall noise errors from each iteration of this experiment"
  },
  {
    "code": "def decompile(input_, file_, output, format_, jar, limit, decompiler):\n    from androguard import session\n    if file_ and input_:\n        print(\"Can not give --input and positional argument! \"\n              \"Please use only one of them!\", file=sys.stderr)\n        sys.exit(1)\n    if not input_ and not file_:\n        print(\"Give one file to decode!\", file=sys.stderr)\n        sys.exit(1)\n    if input_:\n        fname = input_\n    else:\n        fname = file_\n    s = session.Session()\n    with open(fname, \"rb\") as fd:\n        s.add(fname, fd.read())\n    export_apps_to_format(fname, s, output, limit,\n                          jar, decompiler, format_)",
    "docstring": "Decompile an APK and create Control Flow Graphs.\n\n    Example:\n\n    \\b\n        $ androguard resources.arsc"
  },
  {
    "code": "def update(self):\n        pixels = len(self.matrix)\n        for x in range(self.width):\n            for y in range(self.height):\n                pixel = y * self.width * 3 + x * 3\n                if pixel < pixels:\n                    pygame.draw.circle(self.screen,\n                                       (self.matrix[pixel], self.matrix[pixel + 1], self.matrix[pixel + 2]),\n                                       (x * self.dotsize + self.dotsize / 2, y * self.dotsize + self.dotsize / 2), self.dotsize / 2, 0)",
    "docstring": "Generate the output from the matrix."
  },
  {
    "code": "def _mark_lines(lines, sender):\n    global EXTRACTOR\n    candidate = get_signature_candidate(lines)\n    markers = list('t' * len(lines))\n    for i, line in reversed(list(enumerate(candidate))):\n        j = len(lines) - len(candidate) + i\n        if not line.strip():\n            markers[j] = 'e'\n        elif is_signature_line(line, sender, EXTRACTOR):\n            markers[j] = 's'\n    return \"\".join(markers)",
    "docstring": "Mark message lines with markers to distinguish signature lines.\n\n    Markers:\n\n    * e - empty line\n    * s - line identified as signature\n    * t - other i.e. ordinary text line\n\n    >>> mark_message_lines(['Some text', '', 'Bob'], 'Bob')\n    'tes'"
  },
  {
    "code": "def extract_root_meta(cls, serializer, resource):\n        many = False\n        if hasattr(serializer, 'child'):\n            many = True\n            serializer = serializer.child\n        data = {}\n        if getattr(serializer, 'get_root_meta', None):\n            json_api_meta = serializer.get_root_meta(resource, many)\n            assert isinstance(json_api_meta, dict), 'get_root_meta must return a dict'\n            data.update(json_api_meta)\n        return data",
    "docstring": "Calls a `get_root_meta` function on a serializer, if it exists."
  },
  {
    "code": "def find_range_ix_in_section_list(start, end, section_list):\n    if start > section_list[-1] or end < section_list[0]:\n        return [0, 0]\n    if start < section_list[0]:\n        start_section = section_list[0]\n    else:\n        start_section = find_point_in_section_list(start, section_list)\n    if end > section_list[-1]:\n        end_section = section_list[-2]\n    else:\n        end_section = find_point_in_section_list(end, section_list)\n    return [\n        section_list.index(start_section), section_list.index(end_section)+1]",
    "docstring": "Returns the index range all sections belonging to the given range.\n\n    The given list is assumed to contain start points of consecutive\n    sections, except for the final point, assumed to be the end point of the\n    last section. For example, the list [5, 8, 30, 31] is interpreted as the\n    following list of sections: [5-8), [8-30), [30-31]. As such, this function\n    will return [5,8] for the range (7,9) and [5,8,30] while for (7, 30).\n\n    Parameters\n    ---------\n    start : float\n        The start of the desired range.\n    end : float\n        The end of the desired range.\n    section_list : sortedcontainers.SortedList\n        A list of start points of consecutive sections.\n\n    Returns\n    -------\n    iterable\n        The index range of all sections belonging to the given range.\n\n    Example\n    -------\n    >>> from sortedcontainers import SortedList\n    >>> seclist = SortedList([5, 8, 30, 31])\n    >>> find_range_ix_in_section_list(3, 4, seclist)\n    [0, 0]\n    >>> find_range_ix_in_section_list(6, 7, seclist)\n    [0, 1]\n    >>> find_range_ix_in_section_list(7, 9, seclist)\n    [0, 2]\n    >>> find_range_ix_in_section_list(7, 30, seclist)\n    [0, 3]\n    >>> find_range_ix_in_section_list(7, 321, seclist)\n    [0, 3]\n    >>> find_range_ix_in_section_list(4, 321, seclist)\n    [0, 3]"
  },
  {
    "code": "def calculate(price, to_code, **kwargs):\n    qs = kwargs.get('qs', get_active_currencies_qs())\n    kwargs['qs'] = qs\n    default_code = qs.default().code\n    return convert(price, default_code, to_code, **kwargs)",
    "docstring": "Converts a price in the default currency to another currency"
  },
  {
    "code": "def query(self, sql, args=None, many=None, as_dict=False):\n        con = self.pool.pop()\n        c = None\n        try:\n            c = con.cursor(as_dict)\n            LOGGER.debug(\"Query sql: \" + sql + \" args:\" + str(args))\n            c.execute(sql, args)\n            if many and many > 0:\n                return self._yield(con, c, many)\n            else:\n                return c.fetchall()\n        except Exception as e:\n            LOGGER.error(\"Error Qeury on %s\", str(e))\n            raise DBError(e.args[0], e.args[1])\n        finally:\n            many or (c and c.close())\n            many or (con and self.pool.push(con))",
    "docstring": "The connection raw sql query,  when select table,  show table\n            to fetch records, it is compatible the dbi execute method.\n\n\n        :param sql string: the sql stamtement like 'select * from %s'\n        :param args  list: Wen set None, will use dbi execute(sql), else\n            dbi execute(sql, args), the args keep the original rules, it shuld be tuple or list of list\n        :param many  int: when set, the query method will return genarate an iterate\n        :param as_dict bool: when is true, the type of row will be dict, otherwise is tuple"
  },
  {
    "code": "def rotation(self):\n        if self.screen_rotation in range(4):\n            return self.screen_rotation\n        return self.adb_device.rotation() or self.info['displayRotation']",
    "docstring": "Rotaion of the phone\n\n        0: normal\n        1: home key on the right\n        2: home key on the top\n        3: home key on the left"
  },
  {
    "code": "def push(self, message, device=None, title=None, url=None, url_title=None,\n             priority=None, timestamp=None, sound=None):\n        api_url = 'https://api.pushover.net/1/messages.json'\n        payload = {\n            'token': self.api_token,\n            'user': self.user,\n            'message': message,\n            'device': device,\n            'title': title,\n            'url': url,\n            'url_title': url_title,\n            'priority': priority,\n            'timestamp': timestamp,\n            'sound': sound\n        }\n        return requests.post(api_url, params=payload)",
    "docstring": "Pushes the notification, returns the Requests response.\n\n        Arguments:\n            message -- your message\n\n        Keyword arguments:\n            device -- your user's device name to send the message directly to\n                that device, rather than all of the user's devices\n            title -- your message's title, otherwise your app's name is used\n            url -- a supplementary URL to show with your message\n            url_title -- a title for your supplementary URL, otherwise just the\n                URL is shown\n            priority -- send as --1 to always send as a quiet notification, 1\n                to display as high--priority and bypass the user's quiet hours,\n                or 2 to also require confirmation from the user\n            timestamp -- a Unix timestamp of your message's date and time to\n                display to the user, rather than the time your message is\n                received by our API\n            sound -- the name of one of the sounds supported by device clients\n                to override the user's default sound choice."
  },
  {
    "code": "def mail_partial_json(self):\n        if self.mail_partial.get(\"date\"):\n            self._mail_partial[\"date\"] = self.date.isoformat()\n        return json.dumps(self.mail_partial, ensure_ascii=False, indent=2)",
    "docstring": "Return the JSON of mail parsed partial"
  },
  {
    "code": "def download_next_song_cache(self):\n        if len(self.queue) == 0:\n            return\n        cache_ydl_opts = dict(ydl_opts)\n        cache_ydl_opts[\"outtmpl\"] = self.output_format_next\n        with youtube_dl.YoutubeDL(cache_ydl_opts) as ydl:\n            try:\n                url = self.queue[0][0]\n                ydl.download([url])\n            except:\n                pass",
    "docstring": "Downloads the next song in the queue to the cache"
  },
  {
    "code": "def _has_valid_token(self):\n        return bool(self.token and (self.expires > datetime.datetime.now()))",
    "docstring": "This only checks the token's existence and expiration. If it has been\n        invalidated on the server, this method may indicate that the token is\n        valid when it might actually not be."
  },
  {
    "code": "def build_branch(self):\n        if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None):\n            return self.dutinformation.get(0).build.branch\n        return None",
    "docstring": "get build branch.\n\n        :return: build branch or None if not found"
  },
  {
    "code": "def check_validity(self):\n        if not isinstance(self.pianoroll, np.ndarray):\n            raise TypeError(\"`pianoroll` must be a numpy array.\")\n        if not (np.issubdtype(self.pianoroll.dtype, np.bool_)\n                or np.issubdtype(self.pianoroll.dtype, np.number)):\n            raise TypeError(\"The data type of `pianoroll` must be np.bool_ or \"\n                            \"a subdtype of np.number.\")\n        if self.pianoroll.ndim != 2:\n            raise ValueError(\"`pianoroll` must have exactly two dimensions.\")\n        if self.pianoroll.shape[1] != 128:\n            raise ValueError(\"The length of the second axis of `pianoroll` \"\n                             \"must be 128.\")\n        if not isinstance(self.program, int):\n            raise TypeError(\"`program` must be int.\")\n        if self.program < 0 or self.program > 127:\n            raise ValueError(\"`program` must be in between 0 to 127.\")\n        if not isinstance(self.is_drum, bool):\n            raise TypeError(\"`is_drum` must be bool.\")\n        if not isinstance(self.name, string_types):\n            raise TypeError(\"`name` must be a string.\")",
    "docstring": "Raise error if any invalid attribute found."
  },
  {
    "code": "def get_identities(self, identity=None, attrs=None):\n        resp = self.request('GetIdentities')\n        if 'identity' in resp:\n            identities = resp['identity']\n            if type(identities) != list:\n                identities = [identities]\n            if identity or attrs:\n                wanted_identities = []\n                for u_identity in [\n                        zobjects.Identity.from_dict(i) for i in identities]:\n                    if identity:\n                        if isinstance(identity, zobjects.Identity):\n                            if u_identity.name == identity.name:\n                                return [u_identity]\n                        else:\n                            if u_identity.name == identity:\n                                return [u_identity]\n                    elif attrs:\n                        for attr, value in attrs.items():\n                            if (attr in u_identity._a_tags and\n                                    u_identity._a_tags[attr] == value):\n                                wanted_identities.append(u_identity)\n                return wanted_identities\n            else:\n                return [zobjects.Identity.from_dict(i) for i in identities]\n        else:\n            return []",
    "docstring": "Get identities matching name and attrs\n        of the user, as a list\n\n        :param: zobjects.Identity or identity name (string)\n        :param: attrs dict of attributes to return only identities matching\n        :returns: list of zobjects.Identity"
  },
  {
    "code": "def GetSubFileEntryByName(self, name, case_sensitive=True):\n    name_lower = name.lower()\n    matching_sub_file_entry = None\n    for sub_file_entry in self.sub_file_entries:\n      if sub_file_entry.name == name:\n        return sub_file_entry\n      if not case_sensitive and sub_file_entry.name.lower() == name_lower:\n        if not matching_sub_file_entry:\n          matching_sub_file_entry = sub_file_entry\n    return matching_sub_file_entry",
    "docstring": "Retrieves a sub file entry by name.\n\n    Args:\n      name (str): name of the file entry.\n      case_sensitive (Optional[bool]): True if the name is case sensitive.\n\n    Returns:\n      FileEntry: a file entry or None if not available."
  },
  {
    "code": "def _full_axis_reduce(self, axis, func, alternate_index=None):\n        result = self.data.map_across_full_axis(axis, func)\n        if axis == 0:\n            columns = alternate_index if alternate_index is not None else self.columns\n            return self.__constructor__(result, index=[\"__reduced__\"], columns=columns)\n        else:\n            index = alternate_index if alternate_index is not None else self.index\n            return self.__constructor__(result, index=index, columns=[\"__reduced__\"])",
    "docstring": "Applies map that reduce Manager to series but require knowledge of full axis.\n\n        Args:\n            func: Function to reduce the Manager by. This function takes in a Manager.\n            axis: axis to apply the function to.\n            alternate_index: If the resulting series should have an index\n                different from the current query_compiler's index or columns.\n\n        Return:\n            Pandas series containing the reduced data."
  },
  {
    "code": "def _has_bad_coords(root, stream):\n    if stream == \"com.dc3/dc3.broker\":\n        return True\n    if not stream.split('/')[0] == 'nasa.gsfc.gcn':\n        return False\n    toplevel_params = vp.get_toplevel_params(root)\n    if \"Coords_String\" in toplevel_params:\n        if (toplevel_params[\"Coords_String\"]['value'] ==\n                \"unavailable/inappropriate\"):\n            return True\n    return False",
    "docstring": "Predicate function encapsulating 'data clean up' filter code.\n\n    Currently minimal, but these sort of functions tend to grow over time.\n\n    Problem 1:\n        Some of the GCN packets have an RA /Dec equal to (0,0) in the WhereWhen,\n        and a flag in the What signifying that those are actually dummy co-ords.\n        (This is used for time-stamping an event which is not localised).\n        So, we don't load those positions, to avoid muddying the database\n        corpus.\n    Problem 2:\n        com.dc3/dc3.broker#BrokerTest packets have dummy RA/Dec values,\n        with no units specified.\n        (They're also marked role=test, so it's not such a big deal,\n        but it generates a lot of debug-log churn.)"
  },
  {
    "code": "def check_existing_filename (filename, onlyfiles=True):\n    if not os.path.exists(filename):\n        raise PatoolError(\"file `%s' was not found\" % filename)\n    if not os.access(filename, os.R_OK):\n        raise PatoolError(\"file `%s' is not readable\" % filename)\n    if onlyfiles and not os.path.isfile(filename):\n        raise PatoolError(\"`%s' is not a file\" % filename)",
    "docstring": "Ensure that given filename is a valid, existing file."
  },
  {
    "code": "def do_create(marfile, files, compress, productversion=None, channel=None,\n              signing_key=None, signing_algorithm=None):\n    with open(marfile, 'w+b') as f:\n        with MarWriter(f, productversion=productversion, channel=channel,\n                       signing_key=signing_key,\n                       signing_algorithm=signing_algorithm,\n                       ) as m:\n            for f in files:\n                m.add(f, compress=compress)",
    "docstring": "Create a new MAR file."
  },
  {
    "code": "def interfaces_info():\n    def replace(value):\n        if value == netifaces.AF_LINK:\n            return 'link'\n        if value == netifaces.AF_INET:\n            return 'ipv4'\n        if value == netifaces.AF_INET6:\n            return 'ipv6'\n        return value\n    results = {}\n    for iface in netifaces.interfaces():\n        addrs = netifaces.ifaddresses(iface)\n        results[iface] = {replace(k): v for k, v in addrs.items()}\n    return results",
    "docstring": "Returns interfaces data."
  },
  {
    "code": "def start(self):\n        Global.LOGGER.info(\"starting the flow manager\")\n        self._start_actions()\n        self._start_message_fetcher()\n        Global.LOGGER.debug(\"flow manager started\")",
    "docstring": "Start all the processes"
  },
  {
    "code": "def tabs_or_spaces(physical_line, indent_char):\n    indent = indent_match(physical_line).group(1)\n    for offset, char in enumerate(indent):\n        if char != indent_char:\n            return offset, \"E101 indentation contains mixed spaces and tabs\"",
    "docstring": "Never mix tabs and spaces.\n\n    The most popular way of indenting Python is with spaces only.  The\n    second-most popular way is with tabs only.  Code indented with a mixture\n    of tabs and spaces should be converted to using spaces exclusively.  When\n    invoking the Python command line interpreter with the -t option, it issues\n    warnings about code that illegally mixes tabs and spaces.  When using -tt\n    these warnings become errors.  These options are highly recommended!"
  },
  {
    "code": "def mode(self, mode):\n        modes = self.available_modes\n        if (not modes) or (mode not in modes):\n            return\n        self.publish(\n            action='set',\n            resource='modes' if mode != 'schedule' else 'schedule',\n            mode=mode,\n            publish_response=True)\n        self.update()",
    "docstring": "Set Arlo camera mode.\n\n        :param mode: arm, disarm"
  },
  {
    "code": "def request(self):\n        headers = {'Accept': 'application/json'}\n        if self.api_key:\n            headers['X-API-KEY'] = self.api_key\n            return requests,headers\n        else:\n            if self.token:\n                return OAuth2Session(self.client_id, token=self.token),headers\n            else:\n                raise APIError(\"No API key and no OAuth session available\")",
    "docstring": "Returns an OAuth2 Session to be used to make requests.\n        Returns None if a token hasn't yet been received."
  },
  {
    "code": "def filterAcceptsRow(self, source_row, source_parent):\n        source_index = self.sourceModel().index(source_row, 0, source_parent)\n        item = self.sourceModel().dataItem(source_index)\n        if item.metaObject().className() not in [\n                'QgsPGRootItem',\n                'QgsPGConnectionItem',\n                'QgsPGSchemaItem',\n                'QgsPGLayerItem',\n                'QgsFavoritesItem',\n                'QgsDirectoryItem',\n                'QgsLayerItem',\n                'QgsGdalLayerItem',\n                'QgsOgrLayerItem']:\n            return False\n        if item.path().endswith('.xml'):\n            return False\n        return True",
    "docstring": "The filter method\n\n        .. note:: This filter hides top-level items of unsupported branches\n                  and also leaf items containing xml files.\n\n           Enabled root items: QgsDirectoryItem, QgsFavouritesItem,\n           QgsPGRootItem.\n\n           Disabled root items: QgsMssqlRootItem, QgsSLRootItem,\n           QgsOWSRootItem, QgsWCSRootItem, QgsWFSRootItem, QgsWMSRootItem.\n\n           Disabled leaf items: QgsLayerItem and QgsOgrLayerItem with path\n           ending with '.xml'\n\n        :param source_row: Parent widget of the model\n        :type source_row: int\n\n        :param source_parent: Parent item index\n        :type source_parent: QModelIndex\n\n        :returns: Item validation result\n        :rtype: bool"
  },
  {
    "code": "def clean_form_template(self):\n        form_template = self.cleaned_data.get('form_template', '')\n        if form_template:\n            try:\n                get_template(form_template)\n            except TemplateDoesNotExist:\n                msg = _('Selected Form Template does not exist.')\n                raise forms.ValidationError(msg)\n        return form_template",
    "docstring": "Check if template exists"
  },
  {
    "code": "def solar_zenith(self, dateandtime, latitude, longitude):\n        return 90.0 - self.solar_elevation(dateandtime, latitude, longitude)",
    "docstring": "Calculates the solar zenith angle.\n\n        :param dateandtime: The date and time for which to calculate\n                            the angle.\n        :type dateandtime: :class:`~datetime.datetime`\n        :param latitude:   Latitude - Northern latitudes should be positive\n        :type latitude:    float\n        :param longitude:  Longitude - Eastern longitudes should be positive\n        :type longitude:   float\n\n        :return: The zenith angle in degrees from vertical.\n        :rtype: float\n\n        If `dateandtime` is a naive Python datetime then it is assumed to be\n        in the UTC timezone."
  },
  {
    "code": "def transform_annotation(self, ann, duration):\n        _, values = ann.to_interval_values()\n        vector = np.asarray(values[0], dtype=self.dtype)\n        if len(vector) != self.dimension:\n            raise DataError('vector dimension({:0}) '\n                            '!= self.dimension({:1})'\n                            .format(len(vector), self.dimension))\n        return {'vector': vector}",
    "docstring": "Apply the vector transformation.\n\n        Parameters\n        ----------\n        ann : jams.Annotation\n            The input annotation\n\n        duration : number > 0\n            The duration of the track\n\n        Returns\n        -------\n        data : dict\n            data['vector'] : np.ndarray, shape=(dimension,)\n\n        Raises\n        ------\n        DataError\n            If the input dimension does not match"
  },
  {
    "code": "def is_imap(self, model):\n        from pgmpy.models import BayesianModel\n        if not isinstance(model, BayesianModel):\n            raise TypeError(\"model must be an instance of BayesianModel\")\n        factors = [cpd.to_factor() for cpd in model.get_cpds()]\n        factor_prod = six.moves.reduce(mul, factors)\n        JPD_fact = DiscreteFactor(self.variables, self.cardinality, self.values)\n        if JPD_fact == factor_prod:\n            return True\n        else:\n            return False",
    "docstring": "Checks whether the given BayesianModel is Imap of JointProbabilityDistribution\n\n        Parameters\n        -----------\n        model : An instance of BayesianModel Class, for which you want to\n            check the Imap\n\n        Returns\n        --------\n        boolean : True if given bayesian model is Imap for Joint Probability Distribution\n                False otherwise\n        Examples\n        --------\n        >>> from pgmpy.models import BayesianModel\n        >>> from pgmpy.factors.discrete import TabularCPD\n        >>> from pgmpy.factors.discrete import JointProbabilityDistribution\n        >>> bm = BayesianModel([('diff', 'grade'), ('intel', 'grade')])\n        >>> diff_cpd = TabularCPD('diff', 2, [[0.2], [0.8]])\n        >>> intel_cpd = TabularCPD('intel', 3, [[0.5], [0.3], [0.2]])\n        >>> grade_cpd = TabularCPD('grade', 3,\n        ...                        [[0.1,0.1,0.1,0.1,0.1,0.1],\n        ...                         [0.1,0.1,0.1,0.1,0.1,0.1],\n        ...                         [0.8,0.8,0.8,0.8,0.8,0.8]],\n        ...                        evidence=['diff', 'intel'],\n        ...                        evidence_card=[2, 3])\n        >>> bm.add_cpds(diff_cpd, intel_cpd, grade_cpd)\n        >>> val = [0.01, 0.01, 0.08, 0.006, 0.006, 0.048, 0.004, 0.004, 0.032,\n                   0.04, 0.04, 0.32, 0.024, 0.024, 0.192, 0.016, 0.016, 0.128]\n        >>> JPD = JointProbabilityDistribution(['diff', 'intel', 'grade'], [2, 3, 3], val)\n        >>> JPD.is_imap(bm)\n        True"
  },
  {
    "code": "def assertFileSizeLess(self, filename, size, msg=None):\n        fsize = self._get_file_size(filename)\n        self.assertLess(fsize, size, msg=msg)",
    "docstring": "Fail if ``filename``'s size is not less than ``size`` as\n        determined by the '<' operator.\n\n        Parameters\n        ----------\n        filename : str, bytes, file-like\n        size : int, float\n        msg : str\n            If not provided, the :mod:`marbles.mixins` or\n            :mod:`unittest` standard message will be used.\n\n        Raises\n        ------\n        TypeError\n            If ``filename`` is not a str or bytes object and is not\n            file-like."
  },
  {
    "code": "def remove(self, row_or_row_indices):\n        if not row_or_row_indices:\n            return\n        if isinstance(row_or_row_indices, int):\n            rows_remove = [row_or_row_indices]\n        else:\n            rows_remove = row_or_row_indices\n        for col in self._columns:\n            self._columns[col] = [elem for i, elem in enumerate(self[col]) if i not in rows_remove]\n        return self",
    "docstring": "Removes a row or multiple rows of a table in place."
  },
  {
    "code": "def zoom_out(self):\n        zoom = self.grid.grid_renderer.zoom\n        target_zoom = zoom * (1 - config[\"zoom_factor\"])\n        if target_zoom > config[\"minimum_zoom\"]:\n            self.zoom(target_zoom)",
    "docstring": "Zooms out by zoom factor"
  },
  {
    "code": "def shellfilter(value):\n    replacements = {'\\\\': '\\\\\\\\',\n                    '`': '\\\\`',\n                    \"'\": \"\\\\'\",\n                    '\"': '\\\\\"'}\n    for search, repl in replacements.items():\n        value = value.replace(search, repl)\n    return safestring.mark_safe(value)",
    "docstring": "Replace HTML chars for shell usage."
  },
  {
    "code": "def debugObject(object, cat, format, *args):\n    doLog(DEBUG, object, cat, format, args)",
    "docstring": "Log a debug message in the given category."
  },
  {
    "code": "def _to_args(x):\n    if not isinstance(x, (list, tuple, np.ndarray)):\n        x = [x]\n    return x",
    "docstring": "Convert to args representation"
  },
  {
    "code": "def delete_network(self, tenant_name, network):\n        seg_id = network.segmentation_id\n        network_info = {\n            'organizationName': tenant_name,\n            'partitionName': self._part_name,\n            'segmentId': seg_id,\n        }\n        LOG.debug(\"Deleting %s network in DCNM.\", network_info)\n        res = self._delete_network(network_info)\n        if res and res.status_code in self._resp_ok:\n            LOG.debug(\"Deleted %s network in DCNM.\", network_info)\n        else:\n            LOG.error(\"Failed to delete %s network in DCNM.\",\n                      network_info)\n            raise dexc.DfaClientRequestFailed(reason=res)",
    "docstring": "Delete network on the DCNM.\n\n        :param tenant_name: name of tenant the network belongs to\n        :param network: object that contains network parameters"
  },
  {
    "code": "def coalesce(*series):\n    series = [pd.Series(s) for s in series]\n    coalescer = pd.concat(series, axis=1)\n    min_nonna = np.argmin(pd.isnull(coalescer).values, axis=1)\n    min_nonna = [coalescer.columns[i] for i in min_nonna]\n    return coalescer.lookup(np.arange(coalescer.shape[0]), min_nonna)",
    "docstring": "Takes the first non-NaN value in order across the specified series,\n    returning a new series. Mimics the coalesce function in dplyr and SQL.\n\n    Args:\n        *series: Series objects, typically represented in their symbolic form\n            (like X.series).\n\n    Example:\n        df = pd.DataFrame({\n            'a':[1,np.nan,np.nan,np.nan,np.nan],\n            'b':[2,3,np.nan,np.nan,np.nan],\n            'c':[np.nan,np.nan,4,5,np.nan],\n            'd':[6,7,8,9,np.nan]\n        })\n        df >> transmute(coal=coalesce(X.a, X.b, X.c, X.d))\n\n             coal\n        0       1\n        1       3\n        2       4\n        3       5\n        4  np.nan"
  },
  {
    "code": "def register_recipe(cls, recipe):\n    recipe_name = recipe.contents['name']\n    cls._recipe_classes[recipe_name] = (\n        recipe.contents, recipe.args, recipe.__doc__)",
    "docstring": "Registers a dftimewolf recipe.\n\n    Args:\n      recipe: imported python module representing the recipe."
  },
  {
    "code": "def add_sample(a_float, dist):\n    dist_type, _ = _detect_bucket_option(dist)\n    if dist_type == u'exponentialBuckets':\n        _update_general_statistics(a_float, dist)\n        _update_exponential_bucket_count(a_float, dist)\n    elif dist_type == u'linearBuckets':\n        _update_general_statistics(a_float, dist)\n        _update_linear_bucket_count(a_float, dist)\n    elif dist_type == u'explicitBuckets':\n        _update_general_statistics(a_float, dist)\n        _update_explicit_bucket_count(a_float, dist)\n    else:\n        _logger.error(u'Could not determine bucket option type for %s', dist)\n        raise ValueError(u'Unknown bucket option type')",
    "docstring": "Adds `a_float` to `dist`, updating its existing buckets.\n\n    Args:\n      a_float (float): a new value\n      dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):\n        the Distribution being updated\n\n    Raises:\n      ValueError: if `dist` does not have known bucket options defined\n      ValueError: if there are not enough bucket count fields in `dist`"
  },
  {
    "code": "def _sounds_re(include_erhua=False):\n    tone = '[1-5]'\n    optional_final_erhua = '|r\\\\b' if include_erhua else ''\n    pattern = '({}{}{})'.format(_joined_syllables_re(), tone, optional_final_erhua)\n    return re.compile(pattern, re.IGNORECASE)",
    "docstring": "Sounds are syllables + tones"
  },
  {
    "code": "def _folder_item_uncertainty(self, analysis_brain, item):\n        item[\"Uncertainty\"] = \"\"\n        if not self.has_permission(ViewResults, analysis_brain):\n            return\n        result = analysis_brain.getResult\n        obj = self.get_object(analysis_brain)\n        formatted = format_uncertainty(obj, result, decimalmark=self.dmk,\n                                       sciformat=int(self.scinot))\n        if formatted:\n            item[\"Uncertainty\"] = formatted\n        else:\n            item[\"Uncertainty\"] = obj.getUncertainty(result)\n        if self.is_uncertainty_edition_allowed(analysis_brain):\n            item[\"allow_edit\"].append(\"Uncertainty\")",
    "docstring": "Fills the analysis' uncertainty to the item passed in.\n\n        :param analysis_brain: Brain that represents an analysis\n        :param item: analysis' dictionary counterpart that represents a row"
  },
  {
    "code": "def _execute_config_show(self, show_command, delay_factor=.1):\n        rpc_command = '<CLI><Configuration>{show_command}</Configuration></CLI>'.format(\n            show_command=escape_xml(show_command)\n        )\n        response = self._execute_rpc(rpc_command, delay_factor=delay_factor)\n        raw_response = response.xpath('.//CLI/Configuration')[0].text\n        return raw_response.strip() if raw_response else ''",
    "docstring": "Executes a configuration show-type command."
  },
  {
    "code": "def example_splits(url_file, all_files):\n  def generate_hash(inp):\n    h = hashlib.sha1()\n    h.update(inp)\n    return h.hexdigest()\n  all_files_map = {f.split(\"/\")[-1]: f for f in all_files}\n  urls = [line.strip().encode(\"utf-8\") for line in tf.gfile.Open(url_file)]\n  filelist = []\n  for url in urls:\n    url_hash = generate_hash(url)\n    filename = url_hash + \".story\"\n    if filename not in all_files_map:\n      tf.logging.info(\"Missing file: %s\" % url)\n      continue\n    filelist.append(all_files_map[filename])\n  tf.logging.info(\"Found %d examples\" % len(filelist))\n  return filelist",
    "docstring": "Generate splits of the data."
  },
  {
    "code": "def compile(source, ezo):\n        try:\n            compiled = compile_source(source)\n            compiled_list = []\n            for name in compiled:\n                c = Contract(name, ezo)\n                interface = compiled[name]\n                c.abi = interface['abi']\n                c.bin = interface['bin']\n                compiled_list.append(c)\n        except Exception as e:\n            return None, e\n        return compiled_list, None",
    "docstring": "compiles the source code\n\n        :param source: (string) - contract source code\n        :param ezo: - ezo reference for Contract object creation\n        :return: (list) compiled source"
  },
  {
    "code": "def register(self, key, value):\n        self._actions[key] = value\n        if key in self._cache:\n            del self._cache[key]",
    "docstring": "Registers a callable with the specified key.\n\n            `key`\n                String key to identify a callable.\n            `value`\n                Callable object."
  },
  {
    "code": "def get_energy_management_properties(self):\n        result = self.manager.session.get(self.uri + '/energy-management-data')\n        em_list = result['objects']\n        if len(em_list) != 1:\n            uris = [em_obj['object-uri'] for em_obj in em_list]\n            raise ParseError(\"Energy management data returned for no resource \"\n                             \"or for more than one resource: %r\" % uris)\n        em_cpc_obj = em_list[0]\n        if em_cpc_obj['object-uri'] != self.uri:\n            raise ParseError(\"Energy management data returned for an \"\n                             \"unexpected resource: %r\" %\n                             em_cpc_obj['object-uri'])\n        if em_cpc_obj['error-occurred']:\n            raise ParseError(\"Errors occurred when retrieving energy \"\n                             \"management data for CPC. Operation result: %r\" %\n                             result)\n        cpc_props = em_cpc_obj['properties']\n        return cpc_props",
    "docstring": "Return the energy management properties of the CPC.\n\n        The returned energy management properties are a subset of the\n        properties of the CPC resource, and are also available as normal\n        properties of the CPC resource. In so far, there is no new data\n        provided by this method. However, because only a subset of the\n        properties is returned, this method is faster than retrieving the\n        complete set of CPC properties (e.g. via\n        :meth:`~zhmcclient.BaseResource.pull_full_properties`).\n\n        This method performs the HMC operation \"Get CPC Energy Management\n        Data\", and returns only the energy management properties for this CPC\n        from the operation result. Note that in non-ensemble mode of a CPC, the\n        HMC operation result will only contain data for the CPC alone.\n\n        It requires that the feature \"Automate/advanced management suite\"\n        (FC 0020) is installed and enabled, and returns empty values for most\n        properties, otherwise.\n\n        Authorization requirements:\n\n        * Object-access permission to this CPC.\n\n        Returns:\n\n          dict: A dictionary of properties of the CPC that are related to\n          energy management. For details, see section \"Energy management\n          related additional properties\" in the data model for the CPC\n          resource in the :term:`HMC API` book.\n\n        Raises:\n\n          :exc:`~zhmcclient.HTTPError`: See the HTTP status and reason codes of\n            operation \"Get CPC Energy Management Data\" in the :term:`HMC API`\n            book.\n          :exc:`~zhmcclient.ParseError`: Also raised by this method when the\n            JSON response could be parsed but contains inconsistent data.\n          :exc:`~zhmcclient.AuthError`\n          :exc:`~zhmcclient.ConnectionError`"
  },
  {
    "code": "def upsert(self):\n        if not self.jenkins_host.has_job(self.name):\n            LOGGER.info(\"creating {0}...\".format(self.name))\n            self.jenkins_host.create_job(self.name, self.config_xml)\n        else:\n            jenkins_job = self.jenkins_host[self.name]\n            LOGGER.info(\"updating {0}...\".format(self.name))\n            jenkins_job.update_config(self.config_xml)",
    "docstring": "create or update the jenkins job"
  },
  {
    "code": "def marker_(self, lat, long, text, pmap, color=None, icon=None):\n        try:\n            xmap = self._marker(lat, long, text, pmap, color, icon)\n            return xmap\n        except Exception as e:\n            self.err(e, self.marker_, \"Can not get marker\")",
    "docstring": "Returns the map with a marker to the default map"
  },
  {
    "code": "def size_to_content(self, get_font_metrics_fn):\n        new_sizing = self.copy_sizing()\n        new_sizing.minimum_width = 0\n        new_sizing.maximum_width = 0\n        axes = self.__axes\n        if axes and axes.is_valid:\n            font = \"{0:d}px\".format(self.font_size)\n            max_width = 0\n            y_range = axes.calibrated_data_max - axes.calibrated_data_min\n            label = axes.y_ticker.value_label(axes.calibrated_data_max + y_range * 5)\n            max_width = max(max_width, get_font_metrics_fn(font, label).width)\n            label = axes.y_ticker.value_label(axes.calibrated_data_min - y_range * 5)\n            max_width = max(max_width, get_font_metrics_fn(font, label).width)\n            new_sizing.minimum_width = max_width\n            new_sizing.maximum_width = max_width\n        self.update_sizing(new_sizing)",
    "docstring": "Size the canvas item to the proper width, the maximum of any label."
  },
  {
    "code": "def query_ids(self, ids):\n        results = self._get_repo_filter(Layer.objects).filter(uuid__in=ids).all()\n        if len(results) == 0:\n            results = self._get_repo_filter(Service.objects).filter(uuid__in=ids).all()\n        return results",
    "docstring": "Query by list of identifiers"
  },
  {
    "code": "def save(self, filename, wildcard='*', verbose=False):\n        f = open(filename, mode='w')\n        k = list(self.keys())\n        k.sort()\n        count = 0\n        for p in k:\n            if p and fnmatch.fnmatch(str(p).upper(), wildcard.upper()):\n                f.write(\"%-16.16s %f\\n\" % (p, self.__getitem__(p)))\n                count += 1\n        f.close()\n        if verbose:\n            print(\"Saved %u parameters to %s\" % (count, filename))",
    "docstring": "save parameters to a file"
  },
  {
    "code": "def make_api_method(func):\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        args[0]._extra_params = kwargs.pop(\"extra_params\", None)\n        result = func(*args, **kwargs)\n        try:\n            del args[0]._extra_params\n        except AttributeError:\n            pass\n        return result\n    return wrapper",
    "docstring": "Provides a single entry point for modifying all API methods.\n    For now this is limited to allowing the client object to be modified\n    with an `extra_params` keyword arg to each method, that is then used\n    as the params for each web service request.\n\n    Please note that this is an unsupported feature for advanced use only.\n    It's also currently incompatibile with multiple threads, see GH #160."
  },
  {
    "code": "def validate_args(args):\n    if not any([args.environment, args.stage, args.account]):\n        sys.exit(NO_ACCT_OR_ENV_ERROR)\n    if args.environment and args.account:\n        sys.exit(ENV_AND_ACCT_ERROR)\n    if args.environment and args.role:\n        sys.exit(ENV_AND_ROLE_ERROR)",
    "docstring": "Validate command-line arguments."
  },
  {
    "code": "def filter(self, order_by=None, limit=0, **kwargs):\n        with rconnect() as conn:\n            if len(kwargs) == 0:\n                raise ValueError\n            try:\n                query = self._base()\n                query = query.filter(kwargs)\n                if order_by is not None:\n                    query = self._order_by(query, order_by)\n                if limit > 0:\n                    query = self._limit(query, limit)\n                log.debug(query)\n                rv = query.run(conn)\n            except ReqlOpFailedError as e:\n                log.warn(e)\n                raise\n            except Exception as e:\n                log.warn(e)\n                raise\n            else:\n                data = [self._model(_) for _ in rv]\n                return data",
    "docstring": "Fetch a list of instances.\n\n            :param order_by: column on which to order the results. \\\n            To change the sort, prepend with < or >.\n            :param limit: How many rows to fetch.\n            :param kwargs: keyword args on which to filter, column=value"
  },
  {
    "code": "def get_all_handleable_roots(self):\n        nodes = self.get_device_tree()\n        return [node.device\n                for node in sorted(nodes.values(), key=DevNode._sort_key)\n                if not node.ignored and node.device\n                and (node.root == '/' or nodes[node.root].ignored)]",
    "docstring": "Get list of all handleable devices, return only those that represent\n        root nodes within the filtered device tree."
  },
  {
    "code": "def _get_resource_type(self, name):\n        extension = self._get_file_extension(name)\n        if extension is None:\n            return self.RESOURCE_TYPE\n        elif extension in app_settings.STATIC_IMAGES_EXTENSIONS:\n            return RESOURCE_TYPES['IMAGE']\n        elif extension in app_settings.STATIC_VIDEOS_EXTENSIONS:\n            return RESOURCE_TYPES['VIDEO']\n        else:\n            return self.RESOURCE_TYPE",
    "docstring": "Implemented as static files can be of different resource types.\n        Because web developers are the people who control those files, we can distinguish them\n        simply by looking at their extensions, we don't need any content based validation."
  },
  {
    "code": "def send_query(query_dict):\n    query = query_dict['query']\n    params = query_dict['params']\n    url = 'https://www.ebi.ac.uk/chembl/api/data/' + query + '.json'\n    r = requests.get(url, params=params)\n    r.raise_for_status()\n    js = r.json()\n    return js",
    "docstring": "Query ChEMBL API\n\n    Parameters\n    ----------\n    query_dict : dict\n        'query' : string of the endpoint to query\n        'params' : dict of params for the query\n\n    Returns\n    -------\n    js : dict\n        dict parsed from json that is unique to the submitted query"
  },
  {
    "code": "def _prepack(self):\n        current = self\n        while current is not None:\n            current._parser.prepack(current, skip_self = True)\n            current = getattr(current, '_sub', None)\n        current = self\n        while current is not None:\n            current._parser.prepack(current, skip_sub = True)\n            current = getattr(current, '_sub', None)",
    "docstring": "Prepack stage. For parser internal use."
  },
  {
    "code": "def get_sns_topic_arn(topic_name, account, region):\n    if topic_name.count(':') == 5 and topic_name.startswith('arn:aws:sns:'):\n        return topic_name\n    session = boto3.Session(profile_name=account, region_name=region)\n    sns_client = session.client('sns')\n    topics = sns_client.list_topics()['Topics']\n    matched_topic = None\n    for topic in topics:\n        topic_arn = topic['TopicArn']\n        if topic_name == topic_arn.split(':')[-1]:\n            matched_topic = topic_arn\n            break\n    else:\n        LOG.critical(\"No topic with name %s found.\", topic_name)\n        raise SNSTopicNotFound('No topic with name {0} found'.format(topic_name))\n    return matched_topic",
    "docstring": "Get SNS topic ARN.\n\n    Args:\n        topic_name (str): Name of the topic to lookup.\n        account (str): Environment, e.g. dev\n        region (str): Region name, e.g. us-east-1\n\n    Returns:\n        str: ARN for requested topic name"
  },
  {
    "code": "def marshal(self) :\n        \"serializes this Message into the wire protocol format and returns a bytes object.\"\n        buf = ct.POINTER(ct.c_ubyte)()\n        nr_bytes = ct.c_int()\n        if not dbus.dbus_message_marshal(self._dbobj, ct.byref(buf), ct.byref(nr_bytes)) :\n            raise CallFailed(\"dbus_message_marshal\")\n        result = bytearray(nr_bytes.value)\n        ct.memmove \\\n          (\n            ct.addressof((ct.c_ubyte * nr_bytes.value).from_buffer(result)),\n            buf,\n            nr_bytes.value\n          )\n        dbus.dbus_free(buf)\n        return \\\n            result",
    "docstring": "serializes this Message into the wire protocol format and returns a bytes object."
  },
  {
    "code": "def find_group(self, star, starlist):\n        star_distance = np.hypot(star['x_0'] - starlist['x_0'],\n                                 star['y_0'] - starlist['y_0'])\n        distance_criteria = star_distance < self.crit_separation\n        return np.asarray(starlist[distance_criteria]['id'])",
    "docstring": "Find the ids of those stars in ``starlist`` which are at a\n        distance less than ``crit_separation`` from ``star``.\n\n        Parameters\n        ----------\n        star : `~astropy.table.Row`\n            Star which will be either the head of a cluster or an\n            isolated one.\n        starlist : `~astropy.table.Table`\n            List of star positions. Columns named as ``x_0`` and\n            ``y_0``, which corresponds to the centroid coordinates of\n            the sources, must be provided.\n\n        Returns\n        -------\n        Array containing the ids of those stars which are at a distance less\n        than ``crit_separation`` from ``star``."
  },
  {
    "code": "def public_key(self):\n        if self._public_key is None:\n            self._public_key = PublicKeyList(self._version, )\n        return self._public_key",
    "docstring": "Access the public_key\n\n        :returns: twilio.rest.accounts.v1.credential.public_key.PublicKeyList\n        :rtype: twilio.rest.accounts.v1.credential.public_key.PublicKeyList"
  },
  {
    "code": "def get_configuration(self, uri):\n        req_headers = {\n            'Accept': 'application/vnd.onshape.v1+json',\n            'Content-Type': 'application/json'\n        }\n        return self._api.request('get', '/api/partstudios/d/' + uri[\"did\"] + '/' + uri[\"wvm_type\"] + '/' + uri[\"wvm\"] + '/e/' + uri[\"eid\"] + '/configuration', headers=req_headers)",
    "docstring": "get the configuration of a PartStudio\n\n        Args:\n            - uri (dict): points to a particular element\n\n        Returns:\n            - requests.Response: Onshape response data"
  },
  {
    "code": "def toBlockMatrix(self, rowsPerBlock=1024, colsPerBlock=1024):\n        java_block_matrix = self._java_matrix_wrapper.call(\"toBlockMatrix\",\n                                                           rowsPerBlock,\n                                                           colsPerBlock)\n        return BlockMatrix(java_block_matrix, rowsPerBlock, colsPerBlock)",
    "docstring": "Convert this matrix to a BlockMatrix.\n\n        :param rowsPerBlock: Number of rows that make up each block.\n                             The blocks forming the final rows are not\n                             required to have the given number of rows.\n        :param colsPerBlock: Number of columns that make up each block.\n                             The blocks forming the final columns are not\n                             required to have the given number of columns.\n\n        >>> rows = sc.parallelize([IndexedRow(0, [1, 2, 3]),\n        ...                        IndexedRow(6, [4, 5, 6])])\n        >>> mat = IndexedRowMatrix(rows).toBlockMatrix()\n\n        >>> # This IndexedRowMatrix will have 7 effective rows, due to\n        >>> # the highest row index being 6, and the ensuing\n        >>> # BlockMatrix will have 7 rows as well.\n        >>> print(mat.numRows())\n        7\n\n        >>> print(mat.numCols())\n        3"
  },
  {
    "code": "def _find_recorder(recorder, tokens, index):\n    if recorder is None:\n        for recorder_factory in _RECORDERS:\n            recorder = recorder_factory.maybe_start_recording(tokens,\n                                                              index)\n            if recorder is not None:\n                return recorder\n    return recorder",
    "docstring": "Given a current recorder and a token index, try to find a recorder."
  },
  {
    "code": "def server(addr):\n        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        sock.bind(addr)\n        sock.listen(1)\n        conn, addr = sock.accept()\n        talk = SocketTalk(conn)\n        return talk",
    "docstring": "Return a SocketTalk server."
  },
  {
    "code": "def immediate_postdominators(self, end, target_graph=None):\n        return self._immediate_dominators(end, target_graph=target_graph, reverse_graph=True)",
    "docstring": "Get all immediate postdominators of sub graph from given node upwards.\n\n        :param str start: id of the node to navigate forwards from.\n        :param networkx.classes.digraph.DiGraph target_graph: graph to analyse, default is self.graph.\n\n        :return: each node of graph as index values, with element as respective node's immediate dominator.\n        :rtype: dict"
  },
  {
    "code": "def send_username_changed_email(self, user):\n        if not self.user_manager.USER_ENABLE_EMAIL: return\n        if not self.user_manager.USER_SEND_USERNAME_CHANGED_EMAIL: return\n        user_or_user_email_object = self.user_manager.db_manager.get_primary_user_email_object(user)\n        email = user_or_user_email_object.email\n        self._render_and_send_email(\n            email,\n            user,\n            self.user_manager.USER_USERNAME_CHANGED_EMAIL_TEMPLATE,\n        )",
    "docstring": "Send the 'username has changed' notification email."
  },
  {
    "code": "def generate_pydenticon(identifier, size):\n    blocks_size = get_internal_config('size')\n    foreground = get_internal_config('foreground')\n    background = get_internal_config('background')\n    generator = pydenticon.Generator(blocks_size, blocks_size,\n                                     digest=hashlib.sha1,\n                                     foreground=foreground,\n                                     background=background)\n    padding = int(round(get_internal_config('padding') * size / 100.))\n    size = size - 2 * padding\n    padding = (padding, ) * 4\n    return generator.generate(identifier, size, size,\n                              padding=padding,\n                              output_format='png')",
    "docstring": "Use pydenticon to generate an identicon image.\n    All parameters are extracted from configuration."
  },
  {
    "code": "def get_option(self, key, subkey, in_path_none=False):\n        key, subkey = _lower_keys(key, subkey)\n        _entry_must_exist(self.gc, key, subkey)\n        df = self.gc[(self.gc[\"k1\"] == key) & (self.gc[\"k2\"] == subkey)]\n        if df[\"type\"].values[0] == \"bool\":\n            return bool(df[\"value\"].values[0])\n        elif df[\"type\"].values[0] == \"int\":\n            return int(df[\"value\"].values[0])\n        elif df[\"type\"].values[0] == \"path_in\":\n            if df[\"value\"].values[0] is None and not in_path_none:\n                raise ValueError('Unspecified path for {0}.{1}'.format(key,\n                                                                       subkey))\n            return df[\"value\"].values[0]\n        else:\n            return df[\"value\"].values[0]",
    "docstring": "Get the current value of the option.\n\n        :param str key: First identifier of the option.\n        :param str subkey: Second identifier of the option.\n        :param bool in_path_none: Allows for ``in_path`` values of\n            :data:`None` to be retrieved.\n\n        :return: Current value of the option (type varies).\n\n        :raise:\n            :NotRegisteredError: If ``key`` or ``subkey`` do not define\n                any option.\n            :ValueError: If a ``in_path`` type with :data:`None` value is\n                requested."
  },
  {
    "code": "def rget(self, key, replica_index=None, quiet=None):\n        if replica_index is not None:\n            return _Base._rgetix(self, key, replica=replica_index, quiet=quiet)\n        else:\n            return _Base._rget(self, key, quiet=quiet)",
    "docstring": "Get an item from a replica node\n\n        :param string key: The key to fetch\n        :param int replica_index: The replica index to fetch.\n            If this is ``None`` then this method will return once any\n            replica responds. Use :attr:`configured_replica_count` to\n            figure out the upper bound for this parameter.\n\n            The value for this parameter must be a number between 0 and\n            the value of :attr:`configured_replica_count`-1.\n        :param boolean quiet: Whether to suppress errors when the key is\n            not found\n\n        This method (if `replica_index` is not supplied) functions like\n        the :meth:`get` method that has been passed the `replica`\n        parameter::\n\n            c.get(key, replica=True)\n\n        .. seealso:: :meth:`get` :meth:`rget_multi`"
  },
  {
    "code": "def read_message(self):\n        with self.__class__.__locker:\n            result = self.__passive_read(4)\n            if result is None:\n                return None\n            (four_bytes, last_buffer_index, updates1) = result\n            (length,) = unpack('>I', four_bytes)\n            result = self.__passive_read(length, last_buffer_index)\n            if result is None:\n                return None\n            (data, last_buffer_index, updates2) = result\n            for updates in (updates1, updates2):\n                for update in updates:\n                    (buffer_index, buffer_, length_consumed) = update\n                    self.__buffers[buffer_index] = buffer_ if buffer_ else ''\n                    self.__length -= length_consumed\n            self.__read_buffer_index = last_buffer_index\n            self.__hits += 1\n            if self.__hits >= self.__class__.__cleanup_interval:\n                self.__cleanup()\n                self.__hits = 0\n        return data",
    "docstring": "Try to read a message from the buffered data. A message is defined \n        as a 32-bit integer size, followed that number of bytes. First we try\n        to non-destructively read the integer. Then, we try to non-\n        destructively read the remaining bytes. If both are successful, we then\n        go back to remove the span from the front of the buffers."
  },
  {
    "code": "def logo_url(self):\n        if self.logo_ext:\n            return '/api/files/{bucket}/{key}'.format(\n                bucket=current_app.config['COMMUNITIES_BUCKET_UUID'],\n                key='{0}/logo.{1}'.format(self.id, self.logo_ext),\n            )\n        return None",
    "docstring": "Get URL to collection logo.\n\n        :returns: Path to community logo.\n        :rtype: str"
  },
  {
    "code": "def GrabObject(self, identifier):\n    if identifier not in self._values:\n      raise KeyError('Missing cached object for identifier: {0:s}'.format(\n          identifier))\n    cache_value = self._values[identifier]\n    if not cache_value:\n      raise RuntimeError('Missing cache value for identifier: {0:s}'.format(\n          identifier))\n    cache_value.IncrementReferenceCount()",
    "docstring": "Grabs a cached object based on the identifier.\n\n    This method increments the cache value reference count.\n\n    Args:\n      identifier (str): VFS object identifier.\n\n    Raises:\n      KeyError: if the VFS object is not found in the cache.\n      RuntimeError: if the cache value is missing."
  },
  {
    "code": "def rename_feature(self, mapobject_type_name, name, new_name):\n        logger.info(\n            'rename feature \"%s\" of experiment \"%s\", mapobject type \"%s\"',\n            name, self.experiment_name, mapobject_type_name\n        )\n        content = {\n            'name': new_name,\n        }\n        feature_id = self._get_feature_id(mapobject_type_name, name)\n        url = self._build_api_url(\n            '/experiments/{experiment_id}/features/{feature_id}'.format(\n                experiment_id=self._experiment_id, feature_id=feature_id\n            )\n        )\n        res = self._session.put(url, json=content)\n        res.raise_for_status()",
    "docstring": "Renames a feature.\n\n        Parameters\n        ----------\n        mapobject_type_name: str\n            name of the segmented objects type\n        name: str\n            name of the feature that should be renamed\n        new_name: str\n            name that should be given to the feature\n\n        See also\n        --------\n        :func:`tmserver.api.feature.update_feature`\n        :class:`tmlib.models.feature.Feature`"
  },
  {
    "code": "def write(self, bytes):\n        if self.address + len(bytes) > self._end_address:\n            n_bytes = self._end_address - self.address\n            warnings.warn(\"write truncated from {} to {} bytes\".format(\n                len(bytes), n_bytes), TruncationWarning, stacklevel=3)\n            bytes = bytes[:n_bytes]\n        if len(bytes) == 0:\n            return 0\n        self._parent._perform_write(self.address, bytes)\n        self._offset += len(bytes)\n        return len(bytes)",
    "docstring": "Write data to the memory.\n\n        .. note::\n            Writes beyond the specified memory range will be truncated and a\n            :py:exc:`.TruncationWarning` is produced. These warnings can be\n            converted into exceptions using :py:func:`warnings.simplefilter`::\n\n                >>> import warnings\n                >>> from rig.machine_control.machine_controller \\\\\n                ...     import TruncationWarning\n                >>> warnings.simplefilter('error', TruncationWarning)\n\n        Parameters\n        ----------\n        bytes : :py:class:`bytes`\n            Data to write to the memory as a bytestring.\n\n        Returns\n        -------\n        int\n            Number of bytes written."
  },
  {
    "code": "def get_go2sectiontxt(self):\n        go2txt = {}\n        _get_secs = self.hdrobj.get_sections\n        hdrgo2sectxt = {h:\" \".join(_get_secs(h)) for h in self.get_hdrgos()}\n        usrgo2hdrgo = self.get_usrgo2hdrgo()\n        for goid, ntgo in self.go2nt.items():\n            hdrgo = ntgo.GO if ntgo.is_hdrgo else usrgo2hdrgo[ntgo.GO]\n            go2txt[goid] = hdrgo2sectxt[hdrgo]\n        return go2txt",
    "docstring": "Return a dict with actual header and user GO IDs as keys and their sections as values."
  },
  {
    "code": "def removeblanklines(astr):\n    lines = astr.splitlines()\n    lines = [line for line in lines if line.strip() != \"\"]\n    return \"\\n\".join(lines)",
    "docstring": "remove the blank lines in astr"
  },
  {
    "code": "def add(self, key, value, expire=0, noreply=None):\n        if noreply is None:\n            noreply = self.default_noreply\n        return self._store_cmd(b'add', {key: value}, expire, noreply)[key]",
    "docstring": "The memcached \"add\" command.\n\n        Args:\n          key: str, see class docs for details.\n          value: str, see class docs for details.\n          expire: optional int, number of seconds until the item is expired\n                  from the cache, or zero for no expiry (the default).\n          noreply: optional bool, True to not wait for the reply (defaults to\n                   self.default_noreply).\n\n        Returns:\n          If noreply is True, the return value is always True. Otherwise the\n          return value is True if the value was stored, and False if it was\n          not (because the key already existed)."
  },
  {
    "code": "def _variants_dtype(fields, dtypes, arities, filter_ids, flatten_filter,\n                    info_types):\n    dtype = list()\n    for f, n, vcf_type in zip(fields, arities, info_types):\n        if f == 'FILTER' and flatten_filter:\n            for flt in filter_ids:\n                nm = 'FILTER_' + flt\n                dtype.append((nm, 'b1'))\n        elif f == 'FILTER' and not flatten_filter:\n            t = [(flt, 'b1') for flt in filter_ids]\n            dtype.append((f, t))\n        else:\n            if dtypes is not None and f in dtypes:\n                t = dtypes[f]\n            elif f in config.STANDARD_VARIANT_FIELDS:\n                t = config.DEFAULT_VARIANT_DTYPE[f]\n            elif f in config.DEFAULT_INFO_DTYPE:\n                t = config.DEFAULT_INFO_DTYPE[f]\n            else:\n                t = config.DEFAULT_TYPE_MAP[vcf_type]\n            if n == 1:\n                dtype.append((f, t))\n            else:\n                dtype.append((f, t, (n,)))\n    return dtype",
    "docstring": "Utility function to build a numpy dtype for a variants array,\n    given user arguments and information available from VCF header."
  },
  {
    "code": "def make_response(self, data, *args, **kwargs):\n        default_mediatype = kwargs.pop('fallback_mediatype', None) or self.default_mediatype\n        mediatype = request.accept_mimetypes.best_match(\n            self.representations,\n            default=default_mediatype,\n        )\n        if mediatype is None:\n            raise NotAcceptable()\n        if mediatype in self.representations:\n            resp = self.representations[mediatype](data, *args, **kwargs)\n            resp.headers['Content-Type'] = mediatype\n            return resp\n        elif mediatype == 'text/plain':\n            resp = original_flask_make_response(str(data), *args, **kwargs)\n            resp.headers['Content-Type'] = 'text/plain'\n            return resp\n        else:\n            raise InternalServerError()",
    "docstring": "Looks up the representation transformer for the requested media\n        type, invoking the transformer to create a response object. This\n        defaults to default_mediatype if no transformer is found for the\n        requested mediatype. If default_mediatype is None, a 406 Not\n        Acceptable response will be sent as per RFC 2616 section 14.1\n\n        :param data: Python object containing response data to be transformed"
  },
  {
    "code": "def getdirs(self, section, option, raw=False, vars=None, fallback=[]):\n        globs = self.getlist(section, option, fallback=[])\n        return [f for g in globs for f in glob.glob(g) if os.path.isdir(f)]",
    "docstring": "A convenience method which coerces the option in the specified section to a list of directories."
  },
  {
    "code": "def _compute_am_i_owner(self):\n        for rec in self:\n            rec.am_i_owner = (rec.create_uid == self.env.user)",
    "docstring": "Check if current user is the owner"
  },
  {
    "code": "def _compute_dynamic_properties(self, builder):\n    splits = self.splits\n    for split_info in utils.tqdm(\n        splits.values(), desc=\"Computing statistics...\", unit=\" split\"):\n      try:\n        split_name = split_info.name\n        dataset_feature_statistics, schema = get_dataset_feature_statistics(\n            builder, split_name)\n        split_info.statistics.CopyFrom(dataset_feature_statistics)\n        self.as_proto.schema.CopyFrom(schema)\n      except tf.errors.InvalidArgumentError:\n        logging.error((\"%s's info() property specifies split %s, but it \"\n                       \"doesn't seem to have been generated. Please ensure \"\n                       \"that the data was downloaded for this split and re-run \"\n                       \"download_and_prepare.\"), self.name, split_name)\n        raise\n    self._set_splits(splits)",
    "docstring": "Update from the DatasetBuilder."
  },
  {
    "code": "def parse(self, kv):\n        key, val = kv.split(self.kv_sep, 1)\n        keys = key.split(self.keys_sep)\n        for k in reversed(keys):\n            val = {k: val}\n        return val",
    "docstring": "Parses key value string into dict\n\n        Examples:\n            >> parser.parse('test1.test2=value')\n            {'test1': {'test2': 'value'}}\n\n            >> parser.parse('test=value')\n            {'test': 'value'}"
  },
  {
    "code": "def get_list(self, name, default=None):\n        if name not in self:\n            if default is not None:\n                return default\n            raise EnvironmentError.not_found(self._prefix, name)\n        return list(self[name])",
    "docstring": "Retrieves an environment variable as a list.\n\n        Note that while implicit access of environment variables\n        containing tuples will return tuples, using this method will\n        coerce tuples to lists.\n\n        Args:\n            name (str): The case-insensitive, unprefixed variable name.\n            default: If provided, a default value will be returned\n                instead of throwing ``EnvironmentError``.\n\n        Returns:\n            list: The environment variable's value as a list.\n\n        Raises:\n            EnvironmentError: If the environment variable does not\n                exist, and ``default`` was not provided.\n            ValueError: If the environment variable value is not an\n                integer with base 10."
  },
  {
    "code": "def get_abs_path_static(savepath, relative_to_path):\n        if os.path.isabs(savepath):\n            return os.path.abspath(savepath)\n        else:\n            return os.path.abspath(\n                os.path.join(relative_to_path, (savepath))\n            )",
    "docstring": "Figures out the savepath's absolute version.\n\n        :param str savepath: the savepath to return an absolute version of\n        :param str relative_to_path: the file path this savepath should be\n                                     relative to\n        :return str: absolute version of savepath"
  },
  {
    "code": "def _match_lhs(cp, rules):\n    rule_matches = []\n    for rule in rules:\n        reactant_pattern = rule.rule_expression.reactant_pattern\n        for rule_cp in reactant_pattern.complex_patterns:\n            if _cp_embeds_into(rule_cp, cp):\n                rule_matches.append(rule)\n                break\n    return rule_matches",
    "docstring": "Get rules with a left-hand side matching the given ComplexPattern."
  },
  {
    "code": "def spsolve(A, b):\n    x = UmfpackLU(A).solve(b)\n    if b.ndim == 2 and b.shape[1] == 1:\n        return x.ravel()\n    else:\n        return x",
    "docstring": "Solve the sparse linear system Ax=b, where b may be a vector or a matrix.\n\n    Parameters\n    ----------\n    A : ndarray or sparse matrix\n        The square matrix A will be converted into CSC or CSR form\n    b : ndarray or sparse matrix\n        The matrix or vector representing the right hand side of the equation.\n\n    Returns\n    -------\n    x : ndarray or sparse matrix\n        the solution of the sparse linear equation.\n        If b is a vector, then x is a vector of size A.shape[0]\n        If b is a matrix, then x is a matrix of size (A.shape[0],)+b.shape[1:]"
  },
  {
    "code": "def remove_hook(self, key_name, hook_name):\n        kf = self.dct[key_name]\n        if 'hooks' in kf:\n            if hook_name in kf['hooks']:\n                return kf['hooks'].pop(hook_name)",
    "docstring": "Remove hook from the keyframe key_name."
  },
  {
    "code": "def request_length(self):\n        remainder = self.stop_at - self.offset\n        return self.chunk_size if remainder > self.chunk_size else remainder",
    "docstring": "Return length of next chunk upload."
  },
  {
    "code": "def has_concluded(self, bigchain, current_votes=[]):\n        if self.has_validator_set_changed(bigchain):\n            return False\n        election_pk = self.to_public_key(self.id)\n        votes_committed = self.get_commited_votes(bigchain, election_pk)\n        votes_current = self.count_votes(election_pk, current_votes)\n        total_votes = sum(output.amount for output in self.outputs)\n        if (votes_committed < (2/3) * total_votes) and \\\n                (votes_committed + votes_current >= (2/3)*total_votes):\n            return True\n        return False",
    "docstring": "Check if the election can be concluded or not.\n\n        * Elections can only be concluded if the validator set has not changed\n          since the election was initiated.\n        * Elections can be concluded only if the current votes form a supermajority.\n\n        Custom elections may override this function and introduce additional checks."
  },
  {
    "code": "def runcmd(self, cmd, args):\n        dof = getattr(self, 'do_' + cmd, None)\n        if dof is None:\n            return self.default(' '.join([cmd] + args))\n        argf = getattr(self, 'args_' + cmd, None)\n        if argf is not None:\n            parser = argparse.ArgumentParser(\n                prog=cmd,\n                description=getattr(dof, '__doc__', None))\n            argf(parser)\n            argl = parser.parse_args(args)\n        else:\n            argl = ' '.join(args)\n        return dof(argl)",
    "docstring": "Run a single command from pre-parsed arguments.\n\n        This is intended to be run from :meth:`main` or somewhere else\n        \"at the top level\" of the program.  It may raise\n        :exc:`exceptions.SystemExit` if an argument such as ``--help``\n        that normally causes execution to stop is encountered."
  },
  {
    "code": "def get_block_statistics(cls, block_id):\n        if not os.environ.get(\"BLOCKSTACK_TEST\"):\n            raise Exception(\"This method is only available in the test framework\")\n        global STATISTICS\n        return STATISTICS.get(block_id)",
    "docstring": "Get block statistics.\n        Only works in test mode."
  },
  {
    "code": "def update_safety_check(first_dict: MutableMapping[K, V],\n                        second_dict: Mapping[K, V],\n                        compat: Callable[[V, V], bool] = equivalent) -> None:\n    for k, v in second_dict.items():\n        if k in first_dict and not compat(v, first_dict[k]):\n            raise ValueError('unsafe to merge dictionaries without '\n                             'overriding values; conflicting key %r' % k)",
    "docstring": "Check the safety of updating one dictionary with another.\n\n    Raises ValueError if dictionaries have non-compatible values for any key,\n    where compatibility is determined by identity (they are the same item) or\n    the `compat` function.\n\n    Parameters\n    ----------\n    first_dict, second_dict : dict-like\n        All items in the second dictionary are checked against for conflicts\n        against items in the first dictionary.\n    compat : function, optional\n        Binary operator to determine if two values are compatible. By default,\n        checks for equivalence."
  },
  {
    "code": "def find(self, obj, filter_to_class=Ingredient, constructor=None):\n        if callable(constructor):\n            obj = constructor(obj, shelf=self)\n        if isinstance(obj, basestring):\n            set_descending = obj.startswith('-')\n            if set_descending:\n                obj = obj[1:]\n            if obj not in self:\n                raise BadRecipe(\"{} doesn't exist on the shelf\".format(obj))\n            ingredient = self[obj]\n            if not isinstance(ingredient, filter_to_class):\n                raise BadRecipe('{} is not a {}'.format(obj, filter_to_class))\n            if set_descending:\n                ingredient.ordering = 'desc'\n            return ingredient\n        elif isinstance(obj, filter_to_class):\n            return obj\n        else:\n            raise BadRecipe('{} is not a {}'.format(obj, filter_to_class))",
    "docstring": "Find an Ingredient, optionally using the shelf.\n\n        :param obj: A string or Ingredient\n        :param filter_to_class: The Ingredient subclass that obj must be an\n         instance of\n        :param constructor: An optional callable for building Ingredients\n         from obj\n        :return: An Ingredient of subclass `filter_to_class`"
  },
  {
    "code": "def Account(self):\n\t\treturn(clc.v2.Account(alias=self.alias,session=self.session))",
    "docstring": "Return account object for account containing this server.\n\n\t\t>>> clc.v2.Server(\"CA3BTDICNTRLM01\").Account()\n\t\t<clc.APIv2.account.Account instance at 0x108789878>\n\t\t>>> print _\n\t\tBTDI"
  },
  {
    "code": "def _filehandle(self):\n        if not self._fh or self._is_closed():\n            filename = self._rotated_logfile or self.filename\n            if filename.endswith('.gz'):\n                self._fh = gzip.open(filename, 'r')\n            else:\n                self._fh = open(filename, \"r\", 1)\n            if self.read_from_end and not exists(self._offset_file):\n                self._fh.seek(0, os.SEEK_END)\n            else:\n                self._fh.seek(self._offset)\n        return self._fh",
    "docstring": "Return a filehandle to the file being tailed, with the position set\n        to the current offset."
  },
  {
    "code": "def _fnop_style(schema, op, name):\n        if is_common(schema):\n            if name in op.params:\n                del op.params[name]\n            return\n        if _is_pending(schema):\n            ntp = 'pending'\n        elif schema.style is tuple:\n            ntp = 'tuple'\n        elif schema.style is _spl_dict:\n            ntp = 'dict'\n        elif _is_namedtuple(schema.style) and hasattr(schema.style, '_splpy_namedtuple'):\n            ntp = 'namedtuple:' + schema.style._splpy_namedtuple\n        else:\n            return\n        op.params[name] = ntp",
    "docstring": "Set an operator's parameter representing the style of this schema."
  },
  {
    "code": "def bucket(things, key):\n    ret = defaultdict(list)\n    for thing in things:\n        ret[key(thing)].append(thing)\n    return ret",
    "docstring": "Return a map of key -> list of things."
  },
  {
    "code": "def clear(self, tag=None):\n        if tag is None:\n            del self.jobs[:]\n        else:\n            self.jobs[:] = (job for job in self.jobs if tag not in job.tags)",
    "docstring": "Deletes scheduled jobs marked with the given tag, or all jobs\n        if tag is omitted.\n\n        :param tag: An identifier used to identify a subset of\n                    jobs to delete"
  },
  {
    "code": "def trigger(self, event: str, *args: T.Any, **kw: T.Any) -> bool:\n        callbacks = list(self._events.get(event, []))\n        if not callbacks:\n            return False\n        for callback in callbacks:\n            callback(*args, **kw)\n        return True",
    "docstring": "Triggers all handlers which are subscribed to an event.\n        Returns True when there were callbacks to execute, False otherwise."
  },
  {
    "code": "def _applytfms(args):\n    import nibabel as nb\n    from nipype.utils.filemanip import fname_presuffix\n    from niworkflows.interfaces.fixes import FixHeaderApplyTransforms as ApplyTransforms\n    in_file, in_xform, ifargs, index, newpath = args\n    out_file = fname_presuffix(in_file, suffix='_xform-%05d' % index,\n                               newpath=newpath, use_ext=True)\n    copy_dtype = ifargs.pop('copy_dtype', False)\n    xfm = ApplyTransforms(\n        input_image=in_file, transforms=in_xform, output_image=out_file, **ifargs)\n    xfm.terminal_output = 'allatonce'\n    xfm.resource_monitor = False\n    runtime = xfm.run().runtime\n    if copy_dtype:\n        nii = nb.load(out_file)\n        in_dtype = nb.load(in_file).get_data_dtype()\n        if in_dtype != nii.get_data_dtype():\n            nii.set_data_dtype(in_dtype)\n            nii.to_filename(out_file)\n    return (out_file, runtime.cmdline)",
    "docstring": "Applies ANTs' antsApplyTransforms to the input image.\n    All inputs are zipped in one tuple to make it digestible by\n    multiprocessing's map"
  },
  {
    "code": "def atleast_1d(*arrs):\n    r\n    mags = [a.magnitude if hasattr(a, 'magnitude') else a for a in arrs]\n    orig_units = [a.units if hasattr(a, 'units') else None for a in arrs]\n    ret = np.atleast_1d(*mags)\n    if len(mags) == 1:\n        if orig_units[0] is not None:\n            return units.Quantity(ret, orig_units[0])\n        else:\n            return ret\n    return [units.Quantity(m, u) if u is not None else m for m, u in zip(ret, orig_units)]",
    "docstring": "r\"\"\"Convert inputs to arrays with at least one dimension.\n\n    Scalars are converted to 1-dimensional arrays, whilst other\n    higher-dimensional inputs are preserved. This is a thin wrapper\n    around `numpy.atleast_1d` to preserve units.\n\n    Parameters\n    ----------\n    arrs : arbitrary positional arguments\n        Input arrays to be converted if necessary\n\n    Returns\n    -------\n    `pint.Quantity`\n        A single quantity or a list of quantities, matching the number of inputs."
  },
  {
    "code": "def set_default_backend(name: str):\n    global _default_backend\n    if name == \"bokeh\":\n        raise RuntimeError(\"Support for bokeh has been discontinued. At some point, we may return to support holoviews.\")\n    if not name in backends:\n        raise RuntimeError(\"Backend {0} is not supported and cannot be set as default.\".format(name))\n    _default_backend = name",
    "docstring": "Choose a default backend."
  },
  {
    "code": "def lint(relative_path_to_file,\n         contents,\n         linter_functions,\n         **kwargs):\n    r\n    lines = contents.splitlines(True)\n    errors = list()\n    for (code, info) in linter_functions.items():\n        error = info.function(relative_path_to_file, lines, kwargs)\n        if error:\n            if isinstance(error, list):\n                errors.extend([(code, e) for e in error])\n            else:\n                errors.append((code, error))\n    errors = [e for e in errors if not _error_is_suppressed(e[1], e[0], lines)]\n    return sorted(errors, key=lambda e: e[1].line)",
    "docstring": "r\"\"\"Actually lints some file contents.\n\n    relative_path_to_file should contain the relative path to the file being\n    linted from the root source directory. Contents should be a raw string\n    with \\n's."
  },
  {
    "code": "def register_ignore(self, origins, destination):\n        if not isinstance(origins, list):\n            origins = [origins]\n        self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins])\n        self.regenerate_routes()\n        return self.ignore_regexes[destination]",
    "docstring": "Add routes to the ignore dictionary\n\n        :param origins: a number of origins to register\n        :type origins: :py:class:`str` or iterable of :py:class:`str`\n        :param destination: where the origins should point to\n        :type destination: :py:class:`str`\n\n        Ignore dictionary takes the following form::\n\n            {'node_a': set(['node_b', 'node_c']),\n             'node_b': set(['node_d'])}"
  },
  {
    "code": "def launch_browser(attempt_launch_browser=True):\n    _DISPLAY_VARIABLES = ['DISPLAY', 'WAYLAND_DISPLAY', 'MIR_SOCKET']\n    _WEBBROWSER_NAMES_BLACKLIST = [\n        'www-browser', 'lynx', 'links', 'elinks', 'w3m']\n    import webbrowser\n    launch_browser = attempt_launch_browser\n    if launch_browser:\n        if ('linux' in sys.platform and\n                not any(os.getenv(var) for var in _DISPLAY_VARIABLES)):\n            launch_browser = False\n        try:\n            browser = webbrowser.get()\n            if (hasattr(browser, 'name')\n                    and browser.name in _WEBBROWSER_NAMES_BLACKLIST):\n                launch_browser = False\n        except webbrowser.Error:\n            launch_browser = False\n    return launch_browser",
    "docstring": "Decide if we should launch a browser"
  },
  {
    "code": "def get_bind_data(zone_id, profile):\n    conn = _get_driver(profile=profile)\n    zone = conn.get_zone(zone_id)\n    return conn.export_zone_to_bind_format(zone)",
    "docstring": "Export Zone to the BIND compatible format.\n\n    :param zone_id: Zone to export.\n    :type  zone_id: ``str``\n\n    :param profile: The profile key\n    :type  profile: ``str``\n\n    :return: Zone data in BIND compatible format.\n    :rtype: ``str``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion libcloud_dns.get_bind_data google.com profile1"
  },
  {
    "code": "def print_most_common(counter, number=5, tab=1):\n    for key, count in counter.most_common(number):\n        print \"{0}{1} - {2}\".format('\\t'*tab, key, count)",
    "docstring": "print the most common elements of a counter"
  },
  {
    "code": "def delete(self, item):\n        uri = \"/%s/%s\" % (self.uri_base, utils.get_id(item))\n        return self._delete(uri)",
    "docstring": "Deletes the specified item."
  },
  {
    "code": "def on(self):\n        assert spotifyconnect._session_instance.player.num_listeners(\n            spotifyconnect.PlayerEvent.MUSIC_DELIVERY) == 0\n        spotifyconnect._session_instance.player.on(\n            spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery)",
    "docstring": "Turn on the alsa_sink sink.\n\n        This is done automatically when the sink is instantiated, so you'll\n        only need to call this method if you ever call :meth:`off` and want to\n        turn the sink back on."
  },
  {
    "code": "def is_address_in_network(network, address):\n    try:\n        network = netaddr.IPNetwork(network)\n    except (netaddr.core.AddrFormatError, ValueError):\n        raise ValueError(\"Network (%s) is not in CIDR presentation format\" %\n                         network)\n    try:\n        address = netaddr.IPAddress(address)\n    except (netaddr.core.AddrFormatError, ValueError):\n        raise ValueError(\"Address (%s) is not in correct presentation format\" %\n                         address)\n    if address in network:\n        return True\n    else:\n        return False",
    "docstring": "Determine whether the provided address is within a network range.\n\n    :param network (str): CIDR presentation format. For example,\n        '192.168.1.0/24'.\n    :param address: An individual IPv4 or IPv6 address without a net\n        mask or subnet prefix. For example, '192.168.1.1'.\n    :returns boolean: Flag indicating whether address is in network."
  },
  {
    "code": "def get_class(import_path=None):\n    from django.core.exceptions import ImproperlyConfigured\n    if import_path is None:\n        raise ImproperlyConfigured('No class path specified.')\n    try:\n        dot = import_path.rindex('.')\n    except ValueError:\n        raise ImproperlyConfigured(\"%s isn't a module.\" % import_path)\n    module, classname = import_path[:dot], import_path[dot+1:]\n    try:\n        mod = import_module(module)\n    except ImportError as e:\n        raise ImproperlyConfigured('Error importing module %s: \"%s\"' % (module, e))\n    try:\n        return getattr(mod, classname)\n    except AttributeError:\n        raise ImproperlyConfigured('Module \"%s\" does not define a \"%s\" class.' % (module, classname))",
    "docstring": "Largely based on django.core.files.storage's get_storage_class"
  },
  {
    "code": "def prt_line_detail(self, prt, line):\n        values = line.split('\\t')\n        self._prt_line_detail(prt, values)",
    "docstring": "Print line header and values in a readable format."
  },
  {
    "code": "def mount(self):\n        if not self.is_mounted():\n            if not is_osx():\n                if not os.path.exists(self.connection[\"mount_point\"]):\n                    os.mkdir(self.connection[\"mount_point\"])\n            self._mount()",
    "docstring": "Mount the repository."
  },
  {
    "code": "def is_background_knowledge(stmt):\n    any_background = False\n    for ev in stmt.evidence:\n        epi = ev.epistemics\n        if epi is not None:\n            sec = epi.get('section_type')\n            if sec is not None and sec not in background_secs:\n                return False\n            elif sec in background_secs:\n                any_background = True\n    return any_background",
    "docstring": "Return True if Statement is only supported by background knowledge."
  },
  {
    "code": "def register_blueprint(self, blueprint, **options):\n        first_registration = False\n        if blueprint.name in self.blueprints:\n            assert self.blueprints[blueprint.name] is blueprint, \\\n                'A blueprint\\'s name collision occurred between %r and ' \\\n                '%r.  Both share the same name \"%s\".  Blueprints that ' \\\n                'are created on the fly need unique names.' % \\\n                (blueprint, self.blueprints[blueprint.name], blueprint.name)\n        else:\n            self.blueprints[blueprint.name] = blueprint\n            first_registration = True\n        blueprint.register(self, options, first_registration)",
    "docstring": "Registers a blueprint on the WebSockets."
  },
  {
    "code": "def _tree(domain, tld=False):\n    domain = domain.rstrip('.')\n    assert '.' in domain, 'Provide a decent domain'\n    if not tld:\n        if HAS_TLDEXTRACT:\n            tld = tldextract.extract(domain).suffix\n        else:\n            tld = re.search(r'((?:(?:ac|biz|com?|info|edu|gov|mil|name|net|n[oi]m|org)\\.)?[^.]+)$', domain).group()\n            log.info('Without tldextract, dns.util resolves the TLD of %s to %s',\n                     domain, tld)\n    res = [domain]\n    while True:\n        idx = domain.find('.')\n        if idx < 0:\n            break\n        domain = domain[idx + 1:]\n        if domain == tld:\n            break\n        res.append(domain)\n    return res",
    "docstring": "Split out a domain in its parents\n\n    Leverages tldextract to take the TLDs from publicsuffix.org\n    or makes a valiant approximation of that\n\n    :param domain: dc2.ams2.example.com\n    :param tld: Include TLD in list\n    :return: [ 'dc2.ams2.example.com', 'ams2.example.com', 'example.com']"
  },
  {
    "code": "def image_upload_to(self, filename):\n        now = timezone.now()\n        filename, extension = os.path.splitext(filename)\n        return os.path.join(\n            UPLOAD_TO,\n            now.strftime('%Y'),\n            now.strftime('%m'),\n            now.strftime('%d'),\n            '%s%s' % (slugify(filename), extension))",
    "docstring": "Compute the upload path for the image field."
  },
  {
    "code": "def create(self, identity_id, service, token):\n        params = {'service': service, 'token': token}\n        return self.request.post(str(identity_id) + '/token', params)",
    "docstring": "Create the token\n\n            :param identity_id: The ID of the identity to retrieve\n            :param service: The service that the token is linked to\n            :param token: The token provided by the the service\n            :param expires_at: Set an expiry for this token\n            :return: dict of REST API output with headers attached\n            :rtype: :class:`~datasift.request.DictResponse`\n            :raises: :class:`~datasift.exceptions.DataSiftApiException`,\n                :class:`requests.exceptions.HTTPError`"
  },
  {
    "code": "def log_exception(fn_name, exception, retry_count, **kwargs):\n    _log_exception_hook(fn_name, exception, retry_count, **kwargs)",
    "docstring": "External exception logging hook."
  },
  {
    "code": "def load_config(self, config_path=None):\n        self.loaded = True\n        config = copy.deepcopy(DEFAULTS)\n        if config_path is None:\n            if \"FEDORA_MESSAGING_CONF\" in os.environ:\n                config_path = os.environ[\"FEDORA_MESSAGING_CONF\"]\n            else:\n                config_path = \"/etc/fedora-messaging/config.toml\"\n        if os.path.exists(config_path):\n            _log.info(\"Loading configuration from {}\".format(config_path))\n            with open(config_path) as fd:\n                try:\n                    file_config = toml.load(fd)\n                    for key in file_config:\n                        config[key.lower()] = file_config[key]\n                except toml.TomlDecodeError as e:\n                    msg = \"Failed to parse {}: error at line {}, column {}: {}\".format(\n                        config_path, e.lineno, e.colno, e.msg\n                    )\n                    raise exceptions.ConfigurationException(msg)\n        else:\n            _log.info(\"The configuration file, {}, does not exist.\".format(config_path))\n        self.update(config)\n        self._validate()\n        return self",
    "docstring": "Load application configuration from a file and merge it with the default\n        configuration.\n\n        If the ``FEDORA_MESSAGING_CONF`` environment variable is set to a\n        filesystem path, the configuration will be loaded from that location.\n        Otherwise, the path defaults to ``/etc/fedora-messaging/config.toml``."
  },
  {
    "code": "def get_density(self, compound='', element=''):\n        _stack = self.stack\n        if compound == '':\n            _list_compounds = _stack.keys()\n            list_all_dict = {}\n            for _compound in _list_compounds:\n                _list_element = _stack[_compound]['elements']\n                list_all_dict[_compound] = {}\n                for _element in _list_element:\n                    list_all_dict[_compound][_element] = self.get_density(\n                        compound=_compound,\n                        element=_element)\n            return list_all_dict\n        list_compounds = _stack.keys()\n        if compound not in list_compounds:\n            list_compounds_joined = ', '.join(list_compounds)\n            raise ValueError(\"Compound '{}' could not be find in {}\".format(compile, list_compounds_joined))\n        if element == '':\n            element = compound\n        list_element = _stack[compound].keys()\n        if element not in list_element:\n            list_element_joined = ', '.join(list_element)\n            raise ValueError(\"Element '{}' should be any of those elements: {}\".format(element, list_element_joined))\n        return _stack[compound][element]['density']['value']",
    "docstring": "returns the list of isotopes for the element of the compound defined with their density\n\n        Parameters:\n        ===========\n        compound: string (default is empty). If empty, all the stoichiometric will be displayed\n        element: string (default is same as compound).\n\n        Raises:\n        =======\n        ValueError if element is not defined in the stack"
  },
  {
    "code": "def connect(self, host, port):\n        self._connected = False\n        self._host = \"%s:%d\" % (host, port)\n        self._closed = False\n        self._close_info = {\n            'reply_code': 0,\n            'reply_text': 'failed to connect to %s' % (self._host),\n            'class_id': 0,\n            'method_id': 0\n        }\n        self._transport.connect((host, port))\n        self._transport.write(PROTOCOL_HEADER)\n        self._last_octet_time = time.time()\n        if self._synchronous_connect:\n            self._channels[0].add_synchronous_cb(self._channels[0]._recv_start)\n            while not self._connected:\n                self.read_frames()",
    "docstring": "Connect to a host and port."
  },
  {
    "code": "def getReaderNames(self):\n        hresult, pcscreaders = SCardListReaders(self.hcontext, [])\n        if 0 != hresult and SCARD_E_NO_READERS_AVAILABLE != hresult:\n            raise ListReadersException(hresult)\n        readers = []\n        if None == self.readersAsked:\n            readers = pcscreaders\n        else:\n            for reader in self.readersAsked:\n                if not isinstance(reader, type(\"\")):\n                    reader = str(reader)\n                if reader in pcscreaders:\n                    readers = readers + [reader]\n        return readers",
    "docstring": "Returns the list or PCSC readers on which to wait for cards."
  },
  {
    "code": "def _prep_smooth(t, y, dy, span, t_out, span_out, period):\n    if period:\n        t = t % period\n        if t_out is not None:\n            t_out = t_out % period\n    t, y, dy = validate_inputs(t, y, dy, sort_by=t)\n    if span_out is not None:\n        if t_out is None:\n            raise ValueError(\"Must specify t_out when span_out is given\")\n        if span is not None:\n            raise ValueError(\"Must specify only one of span, span_out\")\n        span, t_out = np.broadcast_arrays(span_out, t_out)\n        indices = np.searchsorted(t, t_out)\n    elif span is None:\n        raise ValueError(\"Must specify either span_out or span\")\n    else:\n        indices = None\n    return t, y, dy, span, t_out, span_out, indices",
    "docstring": "Private function to prepare & check variables for smooth utilities"
  },
  {
    "code": "def cleanup():\n    if _output_dir and os.path.exists(_output_dir):\n        log.msg_warn(\"Cleaning up output directory at '{output_dir}' ...\"\n                     .format(output_dir=_output_dir))\n        if not _dry_run:\n            shutil.rmtree(_output_dir)",
    "docstring": "Cleanup the output directory"
  },
  {
    "code": "def _get_level_values(self, level, unique=False):\n        values = self.levels[level]\n        level_codes = self.codes[level]\n        if unique:\n            level_codes = algos.unique(level_codes)\n        filled = algos.take_1d(values._values, level_codes,\n                               fill_value=values._na_value)\n        values = values._shallow_copy(filled)\n        return values",
    "docstring": "Return vector of label values for requested level,\n        equal to the length of the index\n\n        **this is an internal method**\n\n        Parameters\n        ----------\n        level : int level\n        unique : bool, default False\n            if True, drop duplicated values\n\n        Returns\n        -------\n        values : ndarray"
  },
  {
    "code": "def encode_events(self, duration, events, values, dtype=np.bool):\n        frames = time_to_frames(events, sr=self.sr,\n                                hop_length=self.hop_length)\n        n_total = int(time_to_frames(duration, sr=self.sr,\n                                     hop_length=self.hop_length))\n        n_alloc = n_total\n        if np.any(frames):\n            n_alloc = max(n_total, 1 + int(frames.max()))\n        target = np.empty((n_alloc, values.shape[1]),\n                          dtype=dtype)\n        target.fill(fill_value(dtype))\n        values = values.astype(dtype)\n        for column, event in zip(values, frames):\n            target[event] += column\n        return target[:n_total]",
    "docstring": "Encode labeled events as a time-series matrix.\n\n        Parameters\n        ----------\n        duration : number\n            The duration of the track\n\n        events : ndarray, shape=(n,)\n            Time index of the events\n\n        values : ndarray, shape=(n, m)\n            Values array.  Must have the same first index as `events`.\n\n        dtype : numpy data type\n\n        Returns\n        -------\n        target : ndarray, shape=(n_frames, n_values)"
  },
  {
    "code": "def downgrade(engine, desired_version):\n    with engine.begin() as conn:\n        metadata = sa.MetaData(conn)\n        metadata.reflect()\n        version_info_table = metadata.tables['version_info']\n        starting_version = sa.select((version_info_table.c.version,)).scalar()\n        if starting_version < desired_version:\n            raise AssetDBImpossibleDowngrade(db_version=starting_version,\n                                             desired_version=desired_version)\n        if starting_version == desired_version:\n            return\n        ctx = MigrationContext.configure(conn)\n        op = Operations(ctx)\n        downgrade_keys = range(desired_version, starting_version)[::-1]\n        _pragma_foreign_keys(conn, False)\n        for downgrade_key in downgrade_keys:\n            _downgrade_methods[downgrade_key](op, conn, version_info_table)\n        _pragma_foreign_keys(conn, True)",
    "docstring": "Downgrades the assets db at the given engine to the desired version.\n\n    Parameters\n    ----------\n    engine : Engine\n        An SQLAlchemy engine to the assets database.\n    desired_version : int\n        The desired resulting version for the assets database."
  },
  {
    "code": "def run_linter(self, linter) -> None:\n        self.current = linter.name\n        if (linter.name not in self.parser[\"all\"].as_list(\"linters\")\n                or linter.base_pyversion > sys.version_info):\n            return\n        if any(x not in self.installed for x in linter.requires_install):\n            raise ModuleNotInstalled(linter.requires_install)\n        linter.add_output_hook(self.out_func)\n        linter.set_config(self.fn, self.parser[linter.name])\n        linter.run(self.files)\n        self.status_code = self.status_code or linter.status_code",
    "docstring": "Run a checker class"
  },
  {
    "code": "def on_menu(self, event):\n        state = self.state\n        ret = self.menu.find_selected(event)\n        if ret is None:\n            return\n        ret.call_handler()\n        state.child_pipe_send.send(ret)",
    "docstring": "handle menu selections"
  },
  {
    "code": "def accumulate(a_generator, cooperator=None):\n    if cooperator:\n        own_cooperate = cooperator.cooperate\n    else:\n        own_cooperate = cooperate\n    spigot = ValueBucket()\n    items = stream_tap((spigot,), a_generator)\n    d = own_cooperate(items).whenDone()\n    d.addCallback(accumulation_handler, spigot)\n    return d",
    "docstring": "Start a Deferred whose callBack arg is a deque of the accumulation\n    of the values yielded from a_generator.\n\n    :param a_generator: An iterator which yields some not None values.\n    :return: A Deferred to which the next callback will be called with\n     the yielded contents of the generator function."
  },
  {
    "code": "def uniform_crossover(random, mom, dad, args):\n    ux_bias = args.setdefault('ux_bias', 0.5)\n    crossover_rate = args.setdefault('crossover_rate', 1.0)\n    children = []\n    if random.random() < crossover_rate:\n        bro = copy.copy(dad)\n        sis = copy.copy(mom)\n        for i, (m, d) in enumerate(zip(mom, dad)):\n            if random.random() < ux_bias:\n                bro[i] = m\n                sis[i] = d\n        children.append(bro)\n        children.append(sis)\n    else:\n        children.append(mom)\n        children.append(dad)\n    return children",
    "docstring": "Return the offspring of uniform crossover on the candidates.\n\n    This function performs uniform crossover (UX). For each element \n    of the parents, a biased coin is flipped to determine whether \n    the first offspring gets the 'mom' or the 'dad' element. An \n    optional keyword argument in args, ``ux_bias``, determines the bias.\n\n    .. Arguments:\n       random -- the random number generator object\n       mom -- the first parent candidate\n       dad -- the second parent candidate\n       args -- a dictionary of keyword arguments\n\n    Optional keyword arguments in args:\n    \n    - *crossover_rate* -- the rate at which crossover is performed \n      (default 1.0)\n    - *ux_bias* -- the bias toward the first candidate in the crossover \n      (default 0.5)"
  },
  {
    "code": "def _initialize_applicationUiFile():\n    RuntimeGlobals.ui_file = umbra.ui.common.get_resource_path(UiConstants.ui_file)\n    if not foundations.common.path_exists(RuntimeGlobals.ui_file):\n        raise foundations.exceptions.FileExistsError(\"'{0}' ui file is not available, {1} will now close!\".format(\n            UiConstants.ui_file, Constants.application_name))",
    "docstring": "Initializes the Application ui file."
  },
  {
    "code": "async def run_async(self):\n        try:\n            await self.run_loop_async()\n        except Exception as err:\n            _logger.error(\"Run loop failed %r\", err)\n        try:\n            _logger.info(\"Shutting down all pumps %r\", self.host.guid)\n            await self.remove_all_pumps_async(\"Shutdown\")\n        except Exception as err:\n            raise Exception(\"Failed to remove all pumps {!r}\".format(err))",
    "docstring": "Starts the run loop and manages exceptions and cleanup."
  },
  {
    "code": "def create(cls, job_id, spider, workflow, results=None,\n               logs=None, status=JobStatus.PENDING):\n        obj = cls(\n            job_id=job_id,\n            spider=spider,\n            workflow=workflow,\n            results=results,\n            logs=logs,\n            status=status,\n        )\n        db.session.add(obj)\n        return obj",
    "docstring": "Create a new entry for a scheduled crawler job."
  },
  {
    "code": "def reparse(self, unsaved_files=None, options=0):\n        if unsaved_files is None:\n            unsaved_files = []\n        unsaved_files_array = 0\n        if len(unsaved_files):\n            unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()\n            for i,(name,value) in enumerate(unsaved_files):\n                if not isinstance(value, str):\n                    value = value.read()\n                    print(value)\n                if not isinstance(value, str):\n                    raise TypeError('Unexpected unsaved file contents.')\n                unsaved_files_array[i].name = name\n                unsaved_files_array[i].contents = value\n                unsaved_files_array[i].length = len(value)\n        ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),\n                unsaved_files_array, options)",
    "docstring": "Reparse an already parsed translation unit.\n\n        In-memory contents for files can be provided by passing a list of pairs\n        as unsaved_files, the first items should be the filenames to be mapped\n        and the second should be the contents to be substituted for the\n        file. The contents may be passed as strings or file objects."
  },
  {
    "code": "def create_pairwise_bilateral(sdims, schan, img, chdim=-1):\n    if chdim == -1:\n        im_feat = img[np.newaxis].astype(np.float32)\n    else:\n        im_feat = np.rollaxis(img, chdim).astype(np.float32)\n    if isinstance(schan, Number):\n        im_feat /= schan\n    else:\n        for i, s in enumerate(schan):\n            im_feat[i] /= s\n    cord_range = [range(s) for s in im_feat.shape[1:]]\n    mesh = np.array(np.meshgrid(*cord_range, indexing='ij'), dtype=np.float32)\n    for i, s in enumerate(sdims):\n        mesh[i] /= s\n    feats = np.concatenate([mesh, im_feat])\n    return feats.reshape([feats.shape[0], -1])",
    "docstring": "Util function that create pairwise bilateral potentials. This works for\n    all image dimensions. For the 2D case does the same as\n    `DenseCRF2D.addPairwiseBilateral`.\n\n    Parameters\n    ----------\n    sdims: list or tuple\n        The scaling factors per dimension. This is referred to `sxy` in\n        `DenseCRF2D.addPairwiseBilateral`.\n    schan: list or tuple\n        The scaling factors per channel in the image. This is referred to\n        `srgb` in `DenseCRF2D.addPairwiseBilateral`.\n    img: numpy.array\n        The input image.\n    chdim: int, optional\n        This specifies where the channel dimension is in the image. For\n        example `chdim=2` for a RGB image of size (240, 300, 3). If the\n        image has no channel dimension (e.g. it has only one channel) use\n        `chdim=-1`."
  },
  {
    "code": "def GetValidHostsForCert(cert):\n  if 'subjectAltName' in cert:\n    return [x[1] for x in cert['subjectAltName'] if x[0].lower() == 'dns']\n  else:\n    return [x[0][1] for x in cert['subject']\n            if x[0][0].lower() == 'commonname']",
    "docstring": "Returns a list of valid host globs for an SSL certificate.\n\n  Args:\n    cert: A dictionary representing an SSL certificate.\n  Returns:\n    list: A list of valid host globs."
  },
  {
    "code": "def configure(self, options=None, attribute_options=None):\n        self._mapping.update(options=options,\n                             attribute_options=attribute_options)",
    "docstring": "Configures the options and attribute options of the mapping associated\n        with this representer with the given dictionaries.\n\n        :param dict options: configuration options for the mapping associated\n          with this representer.\n        :param dict attribute_options: attribute options for the mapping\n          associated with this representer."
  },
  {
    "code": "def xor_app(parser, cmd, args):\n    parser.add_argument(\n        '-d', '--dec',\n        help='interpret the key as a decimal integer',\n        dest='type',\n        action='store_const',\n        const=int\n    )\n    parser.add_argument(\n        '-x', '--hex',\n        help='interpret the key as an hexadecimal integer',\n        dest='type',\n        action='store_const',\n        const=lambda v: int(v, 16)\n    )\n    parser.add_argument('key', help='the key to xor the value with')\n    parser.add_argument('value', help='the value to xor, read from stdin if omitted', nargs='?')\n    args = parser.parse_args(args)\n    if args.type is not None:\n        args.key = args.type(args.key)\n    return xor(args.key, pwnypack.main.binary_value_or_stdin(args.value))",
    "docstring": "Xor a value with a key."
  },
  {
    "code": "def make(class_name, base, schema):\n    return type(class_name, (base,), dict(SCHEMA=schema))",
    "docstring": "Create a new schema aware type."
  },
  {
    "code": "def iterpws(self, n):\n        for _id in np.argsort(self._freq_list)[::-1][:n]:\n            pw = self._T.restore_key(_id)\n            if self._min_pass_len <= len(pw) <= self._max_pass_len:\n                yield _id, pw, self._freq_list[_id]",
    "docstring": "Returns passwords in order of their frequencies.\n        @n: The numebr of passwords to return\n        Return: pwid, password, frequency\n        Every password is assigned an uniq id, for efficient access."
  },
  {
    "code": "def InitializeUpload(self, http_request, http=None, client=None):\n        if self.strategy is None:\n            raise exceptions.UserError(\n                'No upload strategy set; did you call ConfigureRequest?')\n        if http is None and client is None:\n            raise exceptions.UserError('Must provide client or http.')\n        if self.strategy != RESUMABLE_UPLOAD:\n            return\n        http = http or client.http\n        if client is not None:\n            http_request.url = client.FinalizeTransferUrl(http_request.url)\n        self.EnsureUninitialized()\n        http_response = http_wrapper.MakeRequest(http, http_request,\n                                                 retries=self.num_retries)\n        if http_response.status_code != http_client.OK:\n            raise exceptions.HttpError.FromResponse(http_response)\n        self.__server_chunk_granularity = http_response.info.get(\n            'X-Goog-Upload-Chunk-Granularity')\n        url = http_response.info['location']\n        if client is not None:\n            url = client.FinalizeTransferUrl(url)\n        self._Initialize(http, url)\n        if self.auto_transfer:\n            return self.StreamInChunks()\n        return http_response",
    "docstring": "Initialize this upload from the given http_request."
  },
  {
    "code": "def parse(cls, backend, ik, spk, spk_signature, otpks):\n        ik = backend.decodePublicKey(ik)[0]\n        spk[\"key\"] = backend.decodePublicKey(spk[\"key\"])[0]\n        otpks = list(map(lambda otpk: {\n            \"key\" : backend.decodePublicKey(otpk[\"key\"])[0],\n            \"id\"  : otpk[\"id\"]\n        }, otpks))\n        return cls(ik, spk, spk_signature, otpks)",
    "docstring": "Use this method when creating a bundle from data you retrieved directly from some\n        PEP node. This method applies an additional decoding step to the public keys in\n        the bundle. Pass the same structure as the constructor expects."
  },
  {
    "code": "def update_state(self, state):\n        if not isinstance(state, MachineState):\n            raise TypeError(\"state can only be an instance of type MachineState\")\n        self._call(\"updateState\",\n                     in_p=[state])",
    "docstring": "Updates the VM state.\n        \n        This operation will also update the settings file with the correct\n        information about the saved state file and delete this file from disk\n        when appropriate.\n\n        in state of type :class:`MachineState`"
  },
  {
    "code": "def full_rule(self):\n        return join(self.bp_prefix, self.rule, trailing_slash=self.rule.endswith('/'))",
    "docstring": "The full url rule for this route, including any blueprint prefix."
  },
  {
    "code": "def collect(self):\n        def traverse(d, metric_name=''):\n            for key, value in d.iteritems():\n                if isinstance(value, dict):\n                    if metric_name == '':\n                        metric_name_next = key\n                    else:\n                        metric_name_next = metric_name + '.' + key\n                    traverse(value, metric_name_next)\n                else:\n                    metric_name_finished = metric_name + '.' + key\n                    self.publish_gauge(\n                        name=metric_name_finished,\n                        value=value,\n                        precision=1\n                    )\n        md_state = self._parse_mdstat()\n        traverse(md_state, '')",
    "docstring": "Publish all mdstat metrics."
  },
  {
    "code": "def convert_to_str(d):\n    d2 = {}\n    for k, v in d.items():\n        k = str(k)\n        if type(v) in [list, tuple]:\n            d2[k] = [str(a) for a in v]\n        elif type(v) is dict:\n            d2[k] = convert_to_str(v)\n        else:\n            d2[k] = str(v)\n    return d2",
    "docstring": "Recursively convert all values in a dictionary to strings\n\n    This is required because setup() does not like unicode in\n    the values it is supplied."
  },
  {
    "code": "def add_force_flaky_options(add_option):\n        add_option(\n            '--force-flaky',\n            action=\"store_true\",\n            dest=\"force_flaky\",\n            default=False,\n            help=\"If this option is specified, we will treat all tests as \"\n                 \"flaky.\"\n        )\n        add_option(\n            '--max-runs',\n            action=\"store\",\n            dest=\"max_runs\",\n            type=int,\n            default=2,\n            help=\"If --force-flaky is specified, we will run each test at \"\n                 \"most this many times (unless the test has its own flaky \"\n                 \"decorator).\"\n        )\n        add_option(\n            '--min-passes',\n            action=\"store\",\n            dest=\"min_passes\",\n            type=int,\n            default=1,\n            help=\"If --force-flaky is specified, we will run each test at \"\n                 \"least this many times (unless the test has its own flaky \"\n                 \"decorator).\"\n        )",
    "docstring": "Add options to the test runner that force all tests to be flaky.\n\n        :param add_option:\n            A function that can add an option to the test runner.\n            Its argspec should equal that of argparse.add_option.\n        :type add_option:\n            `callable`"
  },
  {
    "code": "def get_calling_namespaces():\n    try: 1//0\n    except ZeroDivisionError:\n        frame = sys.exc_info()[2].tb_frame.f_back\n    while frame.f_globals.get(\"__name__\") == __name__:\n        frame = frame.f_back\n    return frame.f_locals, frame.f_globals",
    "docstring": "Return the locals and globals for the function that called\n    into this module in the current call stack."
  },
  {
    "code": "def all(self, archived=False, limit=None, page=None):\n        path = partial(_path, self.adapter)\n        if not archived:\n            path = _path(self.adapter)\n        else:\n            path = _path(self.adapter, 'archived')\n        return self._get(path, limit=limit, page=page)",
    "docstring": "get all adapter data."
  },
  {
    "code": "def render_crispy_form(form, helper=None, context=None):\n    from crispy_forms.templatetags.crispy_forms_tags import CrispyFormNode\n    if helper is not None:\n        node = CrispyFormNode('form', 'helper')\n    else:\n        node = CrispyFormNode('form', None)\n    node_context = Context(context)\n    node_context.update({\n        'form': form,\n        'helper': helper\n    })\n    return node.render(node_context)",
    "docstring": "Renders a form and returns its HTML output.\n\n    This function wraps the template logic in a function easy to use in a Django view."
  },
  {
    "code": "def streamify(self, state, frame):\n        pieces = frame.split(self.prefix)\n        return '%s%s%s%s%s' % (self.prefix, self.begin,\n                               (self.prefix + self.nop).join(pieces),\n                               self.prefix, self.end)",
    "docstring": "Prepare frame for output as a byte-stuffed stream."
  },
  {
    "code": "def _stop(self):\n        self._pause()\n        self._cmds_q.put((\"stop\",))\n        try:\n            self._recorder.terminate()\n        except Exception:\n            pass\n        self._recording = False",
    "docstring": "Stops recording. Returns all recorded data and their timestamps. Destroys recorder process."
  },
  {
    "code": "def get_connection(self, command, args=()):\n        command = command.upper().strip()\n        is_pubsub = command in _PUBSUB_COMMANDS\n        if is_pubsub and self._pubsub_conn:\n            if not self._pubsub_conn.closed:\n                return self._pubsub_conn, self._pubsub_conn.address\n            self._pubsub_conn = None\n        for i in range(self.freesize):\n            conn = self._pool[0]\n            self._pool.rotate(1)\n            if conn.closed:\n                continue\n            if conn.in_pubsub:\n                continue\n            if is_pubsub:\n                self._pubsub_conn = conn\n                self._pool.remove(conn)\n                self._used.add(conn)\n            return conn, conn.address\n        return None, self._address",
    "docstring": "Get free connection from pool.\n\n        Returns connection."
  },
  {
    "code": "def setup_benchbuild():\n    LOG.debug(\"Setting up Benchbuild...\")\n    venv_dir = local.path(\"/benchbuild\")\n    prefixes = CFG[\"container\"][\"prefixes\"].value\n    prefixes.append(venv_dir)\n    CFG[\"container\"][\"prefixes\"] = prefixes\n    src_dir = str(CFG[\"source_dir\"])\n    have_src = src_dir is not None\n    if have_src:\n        __mount_source(src_dir)\n    benchbuild = find_benchbuild()\n    if benchbuild and not requires_update(benchbuild):\n        if have_src:\n            __upgrade_from_source(venv_dir, with_deps=False)\n        return\n    setup_virtualenv(venv_dir)\n    if have_src:\n        __upgrade_from_source(venv_dir)\n    else:\n        __upgrade_from_pip(venv_dir)",
    "docstring": "Setup benchbuild inside a container.\n\n    This will query a for an existing installation of benchbuild and\n    try to upgrade it to the latest version, if possible."
  },
  {
    "code": "def api_headers_tween_factory(handler, registry):\n    def api_headers_tween(request):\n        response = handler(request)\n        set_version(request, response)\n        set_req_guid(request, response)\n        return response\n    return api_headers_tween",
    "docstring": "This tween provides necessary API headers"
  },
  {
    "code": "def unrecord(plugin_or_specs, filename):\n    plugin, filename = normalize_migration(plugin_or_specs, filename)\n    migration = get_migration(plugin, filename)\n    if migration:\n        log.info('Removing migration %s:%s', plugin, filename)\n        db = get_db()\n        db.eval(UNRECORD_WRAPPER, migration['_id'])\n    else:\n        log.error('Migration not found %s:%s', plugin, filename)",
    "docstring": "Remove a database migration record.\n\n    \\b\n    A record can be expressed with the following syntaxes:\n     - plugin filename\n     - plugin fliename.js\n     - plugin:filename\n     - plugin:fliename.js"
  },
  {
    "code": "def load_diagram_from_csv(filepath, bpmn_diagram):\n        sequence_flows = bpmn_diagram.sequence_flows\n        process_elements_dict = bpmn_diagram.process_elements\n        diagram_attributes = bpmn_diagram.diagram_attributes\n        plane_attributes = bpmn_diagram.plane_attributes\n        process_dict = BpmnDiagramGraphCSVImport.import_csv_file_as_dict(filepath)\n        BpmnDiagramGraphCSVImport.populate_diagram_elements_dict(diagram_attributes)\n        BpmnDiagramGraphCSVImport.populate_process_elements_dict(process_elements_dict, process_dict)\n        BpmnDiagramGraphCSVImport.populate_plane_elements_dict(plane_attributes)\n        BpmnDiagramGraphCSVImport.import_nodes(process_dict, bpmn_diagram, sequence_flows)\n        BpmnDiagramGraphCSVImport.representation_adjustment(process_dict, bpmn_diagram, sequence_flows)",
    "docstring": "Reads an CSV file from given filepath and maps it into inner representation of BPMN diagram.\n        Returns an instance of BPMNDiagramGraph class.\n\n        :param filepath: string with output filepath,\n        :param bpmn_diagram: an instance of BpmnDiagramGraph class."
  },
  {
    "code": "def frontiers_style():\n    inchpercm = 2.54\n    frontierswidth=8.5 \n    textsize = 5\n    titlesize = 7\n    plt.rcdefaults()\n    plt.rcParams.update({\n        'figure.figsize' : [frontierswidth/inchpercm, frontierswidth/inchpercm],\n        'figure.dpi' : 160,\n        'xtick.labelsize' : textsize,\n        'ytick.labelsize' : textsize,\n        'font.size' : textsize,\n        'axes.labelsize' : textsize,\n        'axes.titlesize' : titlesize,\n        'axes.linewidth': 0.75,\n        'lines.linewidth': 0.75,\n        'legend.fontsize' : textsize,\n    })\n    return None",
    "docstring": "Figure styles for frontiers"
  },
  {
    "code": "def absolute_urls(html):\n    from bs4 import BeautifulSoup\n    from yacms.core.request import current_request\n    request = current_request()\n    if request is not None:\n        dom = BeautifulSoup(html, \"html.parser\")\n        for tag, attr in ABSOLUTE_URL_TAGS.items():\n            for node in dom.findAll(tag):\n                url = node.get(attr, \"\")\n                if url:\n                    node[attr] = request.build_absolute_uri(url)\n        html = str(dom)\n    return html",
    "docstring": "Converts relative URLs into absolute URLs. Used for RSS feeds to\n    provide more complete HTML for item descriptions, but could also\n    be used as a general richtext filter."
  },
  {
    "code": "def realtime_comment_classifier(sender, instance, created, **kwargs):\n    if created:\n        moderator_settings = getattr(settings, 'MODERATOR', None)\n        if moderator_settings:\n            if 'REALTIME_CLASSIFICATION' in moderator_settings:\n                if not moderator_settings['REALTIME_CLASSIFICATION']:\n                    return\n        if not getattr(instance, 'is_reply_comment', False):\n            from moderator.utils import classify_comment\n            classify_comment(instance)",
    "docstring": "Classifies a comment after it has been created.\n\n    This behaviour is configurable by the REALTIME_CLASSIFICATION MODERATOR,\n    default behaviour is to classify(True)."
  },
  {
    "code": "def assoc(objects, sitecol, assoc_dist, mode, asset_refs=()):\n    if isinstance(objects, numpy.ndarray) or hasattr(objects, 'lons'):\n        return _GeographicObjects(objects).assoc(sitecol, assoc_dist, mode)\n    else:\n        return _GeographicObjects(sitecol).assoc2(\n            objects, assoc_dist, mode, asset_refs)",
    "docstring": "Associate geographic objects to a site collection.\n\n    :param objects:\n        something with .lons, .lats or ['lon'] ['lat'], or a list of lists\n        of objects with a .location attribute (i.e. assets_by_site)\n    :param assoc_dist:\n        the maximum distance for association\n    :param mode:\n        if 'strict' fail if at least one site is not associated\n        if 'error' fail if all sites are not associated\n    :returns: (filtered site collection, filtered objects)"
  },
  {
    "code": "def prj_remove_user(self, *args, **kwargs):\n        if not self.cur_prj:\n            return\n        i = self.prj_user_tablev.currentIndex()\n        item = i.internalPointer()\n        if item:\n            user = item.internal_data()\n            log.debug(\"Removing user %s.\", user.username)\n            item.set_parent(None)\n            self.cur_prj.users.remove(user)",
    "docstring": "Remove the, in the user table view selected, user.\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def get_bpf_pointer(tcpdump_lines):\n    if conf.use_pypy:\n        return _legacy_bpf_pointer(tcpdump_lines)\n    size = int(tcpdump_lines[0])\n    bpf_insn_a = bpf_insn * size\n    bip = bpf_insn_a()\n    tcpdump_lines = tcpdump_lines[1:]\n    i = 0\n    for line in tcpdump_lines:\n        values = [int(v) for v in line.split()]\n        bip[i].code = c_ushort(values[0])\n        bip[i].jt = c_ubyte(values[1])\n        bip[i].jf = c_ubyte(values[2])\n        bip[i].k = c_uint(values[3])\n        i += 1\n    return bpf_program(size, bip)",
    "docstring": "Create a BPF Pointer for TCPDump filter"
  },
  {
    "code": "def wait(self, timeout=None):\n        if timeout is None:\n            timeout = self._timeout\n        with self._cond:\n            self._enter()\n            index = self._count\n            self._count += 1\n            try:\n                if index + 1 == self._parties:\n                    self._release()\n                else:\n                    self._wait(timeout)\n                return index\n            finally:\n                self._count -= 1\n                self._exit()",
    "docstring": "Wait for the barrier.\n\n        When the specified number of threads have started waiting, they are all\n        simultaneously awoken. If an 'action' was provided for the barrier, one\n        of the threads will have executed that callback prior to returning.\n        Returns an individual index number from 0 to 'parties-1'."
  },
  {
    "code": "def save_xml(self, doc, element):\n        super(TargetExecutionContext, self).save_xml(doc, element)\n        element.setAttributeNS(RTS_NS, RTS_NS_S + 'id', self.id)",
    "docstring": "Save this target execution context into an xml.dom.Element\n        object."
  },
  {
    "code": "def request_slot(client,\n                 service: JID,\n                 filename: str,\n                 size: int,\n                 content_type: str):\n    payload = Request(filename, size, content_type)\n    return (yield from client.send(IQ(\n        type_=IQType.GET,\n        to=service,\n        payload=payload\n    )))",
    "docstring": "Request an HTTP upload slot.\n\n    :param client: The client to request the slot with.\n    :type client: :class:`aioxmpp.Client`\n    :param service: Address of the HTTP upload service.\n    :type service: :class:`~aioxmpp.JID`\n    :param filename: Name of the file (without path), may be used by the server\n        to generate the URL.\n    :type filename: :class:`str`\n    :param size: Size of the file in bytes\n    :type size: :class:`int`\n    :param content_type: The MIME type of the file\n    :type content_type: :class:`str`\n    :return: The assigned upload slot.\n    :rtype: :class:`.xso.Slot`\n\n    Sends a :xep:`363` slot request to the XMPP service to obtain HTTP\n    PUT and GET URLs for a file upload.\n\n    The upload slot is returned as a :class:`~.xso.Slot` object."
  },
  {
    "code": "def _handle_calls(self, alts, format_, format_str, arr):\n        if format_str not in self._format_cache:\n            self._format_cache[format_str] = list(map(self.header.get_format_field_info, format_))\n        calls = []\n        for sample, raw_data in zip(self.samples.names, arr[9:]):\n            if self.samples.is_parsed(sample):\n                data = self._parse_calls_data(format_, self._format_cache[format_str], raw_data)\n                call = record.Call(sample, data)\n                self._format_checker.run(call, len(alts))\n                self._check_filters(call.data.get(\"FT\"), \"FORMAT/FT\", call.sample)\n                calls.append(call)\n            else:\n                calls.append(record.UnparsedCall(sample, raw_data))\n        return calls",
    "docstring": "Handle FORMAT and calls columns, factored out of parse_line"
  },
  {
    "code": "def check(self, action, page=None, lang=None, method=None):\n        if self.user.is_superuser:\n            return True\n        if action == 'change':\n            return self.has_change_permission(page, lang, method)\n        if action == 'delete':\n            if not self.delete_page():\n                return False\n            return True\n        if action == 'add':\n            if not self.add_page():\n                return False\n            return True\n        if action == 'freeze':\n            perm = self.user.has_perm('pages.can_freeze')\n            if perm:\n                return True\n            return False\n        if action == 'publish':\n            perm = self.user.has_perm('pages.can_publish')\n            if perm:\n                return True\n            return False\n        return False",
    "docstring": "Return ``True`` if the current user has permission on the page."
  },
  {
    "code": "def _get_cl_dependency_code(self):\n        code = ''\n        for d in self._dependencies:\n            code += d.get_cl_code() + \"\\n\"\n        return code",
    "docstring": "Get the CL code for all the CL code for all the dependencies.\n\n        Returns:\n            str: The CL code with the actual code."
  },
  {
    "code": "def warning(self):\n        signals, docs, overs = self.expandedStim()\n        if np.any(np.array(overs) > 0):\n            msg = 'Stimuli in this test are over the maximum allowable \\\n                voltage output. They will be rescaled with a maximum \\\n                undesired attenuation of {:.2f}dB.'.format(np.amax(overs))\n            return msg\n        return 0",
    "docstring": "Checks Stimulus for any warning conditions\n\n        :returns: str -- warning message, if any, 0 otherwise"
  },
  {
    "code": "def openall(self, title=None):\n        spreadsheet_files = self.list_spreadsheet_files()\n        return [\n            Spreadsheet(self, dict(title=x['name'], **x))\n            for x in spreadsheet_files\n        ]",
    "docstring": "Opens all available spreadsheets.\n\n        :param title: (optional) If specified can be used to filter\n                      spreadsheets by title.\n        :type title: str\n\n        :returns: a list of :class:`~gspread.models.Spreadsheet` instances."
  },
  {
    "code": "def enterabs(self, time, priority, action, argument=(), kwargs=_sentinel):\n        if kwargs is _sentinel:\n            kwargs = {}\n        event = Event(time, priority, action, argument, kwargs)\n        with self._lock:\n            heapq.heappush(self._queue, event)\n        return event",
    "docstring": "Enter a new event in the queue at an absolute time.\n\n        Returns an ID for the event which can be used to remove it,\n        if necessary."
  },
  {
    "code": "def from_json(cls, json_data):\n        new_instance = cls()\n        for field_name, field_obj in cls._get_fields().items():\n            if isinstance(field_obj, NestedDocumentField):\n                if field_name in json_data:\n                    nested_field = field_obj.__get__(new_instance, new_instance.__class__)\n                    if not nested_field:\n                        nested_field = field_obj.nested_klass()\n                    nested_document = nested_field.from_json(json_data[field_name])\n                    field_obj.__set__(new_instance, nested_document)\n            elif isinstance(field_obj, BaseField):\n                if field_name in json_data:\n                    value = field_obj.from_json(json_data[field_name])\n                    field_obj.__set__(new_instance, value)\n            else:\n                continue\n        return new_instance",
    "docstring": "Converts json data to a new document instance"
  },
  {
    "code": "def min_weighted_vertex_cover(G, weight=None, sampler=None, **sampler_args):\n    indep_nodes = set(maximum_weighted_independent_set(G, weight, sampler, **sampler_args))\n    return [v for v in G if v not in indep_nodes]",
    "docstring": "Returns an approximate minimum weighted vertex cover.\n\n    Defines a QUBO with ground states corresponding to a minimum weighted\n    vertex cover and uses the sampler to sample from it.\n\n    A vertex cover is a set of vertices such that each edge of the graph\n    is incident with at least one vertex in the set. A minimum weighted\n    vertex cover is the vertex cover of minimum total node weight.\n\n    Parameters\n    ----------\n    G : NetworkX graph\n\n    weight : string, optional (default None)\n        If None, every node has equal weight. If a string, use this node\n        attribute as the node weight. A node without this attribute is\n        assumed to have max weight.\n\n    sampler\n        A binary quadratic model sampler. A sampler is a process that\n        samples from low energy states in models defined by an Ising\n        equation or a Quadratic Unconstrained Binary Optimization\n        Problem (QUBO). A sampler is expected to have a 'sample_qubo'\n        and 'sample_ising' method. A sampler is expected to return an\n        iterable of samples, in order of increasing energy. If no\n        sampler is provided, one must be provided using the\n        `set_default_sampler` function.\n\n    sampler_args\n        Additional keyword parameters are passed to the sampler.\n\n    Returns\n    -------\n    vertex_cover : list\n       List of nodes that the form a the minimum weighted vertex cover, as\n       determined by the given sampler.\n\n    Notes\n    -----\n    Samplers by their nature may not return the optimal solution. This\n    function does not attempt to confirm the quality of the returned\n    sample.\n\n    https://en.wikipedia.org/wiki/Vertex_cover\n\n    https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization\n\n    References\n    ----------\n    Based on the formulation presented in [AL]_"
  },
  {
    "code": "def _fit_m(D, a0, logp, tol=1e-7, maxiter=1000):\n    N,K = D.shape\n    s = a0.sum()\n    for i in xrange(maxiter):\n        m = a0 / s\n        a1 = _ipsi(logp + (m*(psi(a0) - logp)).sum())\n        a1 = a1/a1.sum() * s\n        if norm(a1 - a0) < tol:\n            return a1\n        a0 = a1\n    raise Exception('Failed to converge after {} iterations, s is {}'\n            .format(maxiter, s))",
    "docstring": "With fixed precision s, maximize mean m"
  },
  {
    "code": "def isosurface_from_data(data, isolevel, origin, spacing):\n    spacing = np.array(extent/resolution)\n    if isolevel >= 0:\n        triangles = marching_cubes(data, isolevel)\n    else:\n        triangles = marching_cubes(-data, -isolevel)\n    faces = []\n    verts = []\n    for i, t in enumerate(triangles):\n       faces.append([i * 3, i * 3 +1, i * 3 + 2])\n       verts.extend(t)\n    faces = np.array(faces)\n    verts = origin + spacing/2 + np.array(verts)*spacing\n    return verts, faces",
    "docstring": "Small wrapper to get directly vertices and faces to feed into programs"
  },
  {
    "code": "def get_guts(self, last_build, missing='missing or bad'):\n        try:\n            data = _load_data(self.out)\n        except:\n            logger.info(\"building because %s %s\", os.path.basename(self.out), missing)\n            return None\n        if len(data) != len(self.GUTS):\n            logger.info(\"building because %s is bad\", self.outnm)\n            return None\n        for i, (attr, func) in enumerate(self.GUTS):\n            if func is None:\n                continue\n            if func(attr, data[i], getattr(self, attr), last_build):\n                return None\n        return data",
    "docstring": "returns None if guts have changed"
  },
  {
    "code": "def itemgetter_handle(tokens):\n    internal_assert(len(tokens) == 2, \"invalid implicit itemgetter args\", tokens)\n    op, args = tokens\n    if op == \"[\":\n        return \"_coconut.operator.itemgetter(\" + args + \")\"\n    elif op == \"$[\":\n        return \"_coconut.functools.partial(_coconut_igetitem, index=\" + args + \")\"\n    else:\n        raise CoconutInternalException(\"invalid implicit itemgetter type\", op)",
    "docstring": "Process implicit itemgetter partials."
  },
  {
    "code": "def plot(self, xmin, xmax, idx_input=0, idx_output=0, points=100,\n             **kwargs) -> None:\n        for toy, ann_ in self:\n            ann_.plot(xmin, xmax,\n                      idx_input=idx_input, idx_output=idx_output,\n                      points=points,\n                      label=str(toy),\n                      **kwargs)\n        pyplot.legend()",
    "docstring": "Call method |anntools.ANN.plot| of all |anntools.ANN| objects\n        handled by the actual |anntools.SeasonalANN| object."
  },
  {
    "code": "def release(self, connection):\n        \"Releases the connection back to the pool.\"\n        self._checkpid()\n        if connection.pid != self.pid:\n            return\n        try:\n            self.pool.put_nowait(connection)\n        except Full:\n            pass",
    "docstring": "Releases the connection back to the pool."
  },
  {
    "code": "def generated_passphrase_entropy(self) -> float:\n        if (\n                self.amount_w is None\n                or self.amount_n is None\n                or not self.wordlist\n        ):\n            raise ValueError(\"Can't calculate the passphrase entropy: \"\n                             \"wordlist is empty or amount_n or \"\n                             \"amount_w isn't set\")\n        if self.amount_n == 0 and self.amount_w == 0:\n            return 0.0\n        entropy_n = self.entropy_bits((self.randnum_min, self.randnum_max))\n        entropy_w = self._wordlist_entropy_bits \\\n            if self._wordlist_entropy_bits \\\n            else self.entropy_bits(self.wordlist)\n        return calc_passphrase_entropy(\n            self.amount_w,\n            entropy_w,\n            entropy_n,\n            self.amount_n\n        )",
    "docstring": "Calculate the entropy of a passphrase that would be generated."
  },
  {
    "code": "def less(environment, opts):\n    require_extra_image(LESSC_IMAGE)\n    print 'Converting .less files to .css...'\n    for log in environment.compile_less():\n        print log",
    "docstring": "Recompiles less files in an environment.\n\nUsage:\n  datacats less [ENVIRONMENT]\n\nENVIRONMENT may be an environment name or a path to an environment directory.\nDefault: '.'"
  },
  {
    "code": "def panic(self, *args):\n        self._err(\"fatal\", *args)\n        if self.test_errs_mode is False:\n            sys.exit(1)",
    "docstring": "Creates a fatal error and exit"
  },
  {
    "code": "def iter_work_specs(self, limit=None, start=None):\n        count = 0\n        ws_list, start = self.list_work_specs(limit, start)\n        while True:\n            for name_spec in ws_list:\n                yield name_spec[1]\n                count += 1\n                if (limit is not None) and (count >= limit):\n                    break\n            if not start:\n                break\n            if limit is not None:\n                limit -= count\n            ws_list, start = self.list_work_specs(limit, start)",
    "docstring": "yield work spec dicts"
  },
  {
    "code": "def set_defaults(self):\n        rfields, sfields = self.get_write_fields()\n        for f in rfields:\n            self.set_default(f)\n        for f in sfields:\n            self.set_default(f)",
    "docstring": "Set defaults for fields needed to write the header if they have\n        defaults.\n\n        Notes\n        -----\n        - This is NOT called by `rdheader`. It is only automatically\n          called by the gateway `wrsamp` for convenience.\n        - This is also not called by `wrheader` since it is supposed to\n          be an explicit function.\n        - This is not responsible for initializing the attributes. That\n          is done by the constructor.\n\n        See also `set_p_features` and `set_d_features`."
  },
  {
    "code": "def gregorian_to_julian(day):\n    before_march = 1 if day.month < MARCH else 0\n    month_index = day.month + MONTHS_PER_YEAR * before_march - MARCH\n    years_elapsed = day.year - JULIAN_START_YEAR - before_march\n    total_days_in_previous_months = (153 * month_index + 2) // 5\n    total_days_in_previous_years = 365 * years_elapsed\n    total_leap_days = (\n        (years_elapsed // 4) -\n        (years_elapsed // 100) +\n        (years_elapsed // 400)\n    )\n    return sum([\n        day.day,\n        total_days_in_previous_months,\n        total_days_in_previous_years,\n        total_leap_days,\n        -32045,\n    ])",
    "docstring": "Convert a datetime.date object to its corresponding Julian day.\n\n    :param day: The datetime.date to convert to a Julian day\n    :returns: A Julian day, as an integer"
  },
  {
    "code": "async def enable_analog_reporting(self, pin):\n        command = [PrivateConstants.REPORT_ANALOG + pin,\n                   PrivateConstants.REPORTING_ENABLE]\n        await self._send_command(command)",
    "docstring": "Enables analog reporting. By turning reporting on for a single pin,\n\n        :param pin: Analog pin number. For example for A0, the number is 0.\n\n        :returns: No return value"
  },
  {
    "code": "def get_module_classes(node):\n    return [\n        child\n        for child in ast.walk(node)\n        if isinstance(child, ast.ClassDef)\n    ]",
    "docstring": "Return classes associated with a given module"
  },
  {
    "code": "def write8(self, offset, value):\n        if not isinstance(offset, (int, long)):\n            raise TypeError(\"Invalid offset type, should be integer.\")\n        if not isinstance(value, (int, long)):\n            raise TypeError(\"Invalid value type, should be integer.\")\n        if value < 0 or value > 0xff:\n            raise ValueError(\"Value out of bounds.\")\n        offset = self._adjust_offset(offset)\n        self._validate_offset(offset, 1)\n        self.mapping[offset:offset + 1] = struct.pack(\"B\", value)",
    "docstring": "Write 8-bits to the specified `offset` in bytes, relative to the\n        base physical address of the MMIO region.\n\n        Args:\n            offset (int, long): offset from base physical address, in bytes.\n            value (int, long): 8-bit value to write.\n\n        Raises:\n            TypeError: if `offset` or `value` type are invalid.\n            ValueError: if `offset` or `value` are out of bounds."
  },
  {
    "code": "def delete_job(name=None):\n    if not name:\n        raise SaltInvocationError('Required parameter \\'name\\' is missing')\n    server = _connect()\n    if not job_exists(name):\n        raise CommandExecutionError('Job \\'{0}\\' does not exist'.format(name))\n    try:\n        server.delete_job(name)\n    except jenkins.JenkinsException as err:\n        raise CommandExecutionError(\n            'Encountered error deleting job \\'{0}\\': {1}'.format(name, err)\n        )\n    return True",
    "docstring": "Return true is job is deleted successfully.\n\n    :param name: The name of the job to delete.\n    :return: Return true if job is deleted successfully.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' jenkins.delete_job jobname"
  },
  {
    "code": "def iters(cls, batch_size=32, bptt_len=35, device=0, root='.data',\n              vectors=None, **kwargs):\n        TEXT = data.Field()\n        train, val, test = cls.splits(TEXT, root=root, **kwargs)\n        TEXT.build_vocab(train, vectors=vectors)\n        return data.BPTTIterator.splits(\n            (train, val, test), batch_size=batch_size, bptt_len=bptt_len,\n            device=device)",
    "docstring": "Create iterator objects for splits of the WikiText-2 dataset.\n\n        This is the simplest way to use the dataset, and assumes common\n        defaults for field, vocabulary, and iterator parameters.\n\n        Arguments:\n            batch_size: Batch size.\n            bptt_len: Length of sequences for backpropagation through time.\n            device: Device to create batches on. Use -1 for CPU and None for\n                the currently active GPU device.\n            root: The root directory that the dataset's zip archive will be\n                expanded into; therefore the directory in whose wikitext-2\n                subdirectory the data files will be stored.\n            wv_dir, wv_type, wv_dim: Passed to the Vocab constructor for the\n                text field. The word vectors are accessible as\n                train.dataset.fields['text'].vocab.vectors.\n            Remaining keyword arguments: Passed to the splits method."
  },
  {
    "code": "def get_postgame(self):\n        if self._cache['postgame'] is not None:\n            return self._cache['postgame']\n        self._handle.seek(0)\n        try:\n            self._cache['postgame'] = parse_postgame(self._handle, self.size)\n            return self._cache['postgame']\n        except IOError:\n            self._cache['postgame'] = False\n            return None\n        finally:\n            self._handle.seek(self.body_position)",
    "docstring": "Get postgame structure."
  },
  {
    "code": "def versions(self):\n        versions = []\n        for v, _ in self.restarts:\n            if len(versions) == 0 or v != versions[-1]:\n                versions.append(v)\n        return versions",
    "docstring": "Return all version changes."
  },
  {
    "code": "def applyReq(self, request: Request, cons_time: int):\n        self.execute_hook(NodeHooks.PRE_REQUEST_APPLICATION, request=request,\n                          cons_time=cons_time)\n        req_handler = self.get_req_handler(txn_type=request.operation[TXN_TYPE])\n        seq_no, txn = req_handler.apply(request, cons_time)\n        ledger_id = self.ledger_id_for_request(request)\n        self.execute_hook(NodeHooks.POST_REQUEST_APPLICATION, request=request,\n                          cons_time=cons_time, ledger_id=ledger_id,\n                          seq_no=seq_no, txn=txn)",
    "docstring": "Apply request to appropriate ledger and state. `cons_time` is the\n        UTC epoch at which consensus was reached."
  },
  {
    "code": "def nova_services_up(self):\n        required = set(['nova-conductor', 'nova-cert', 'nova-scheduler',\n                       'nova-compute'])\n        try:\n            services = self._nclient.services.list()\n        except Exception as e:\n            LOG.error('Failure determining running Nova services: %s', e)\n            return False\n        return not bool(required.difference(\n            [service.binary for service in services\n             if service.status == 'enabled' and service.state == 'up']))",
    "docstring": "Checks if required Nova services are up and running.\n\n        returns: True if all needed Nova services are up, False otherwise"
  },
  {
    "code": "def warn(self, cmd, desc=''):\n        return self._label_desc(cmd, desc, self.warn_color)",
    "docstring": "Style for warning message."
  },
  {
    "code": "def triangle_area(e1, e2, e3):\n    e1_length = numpy.sqrt(numpy.sum(e1 * e1, axis=-1))\n    e2_length = numpy.sqrt(numpy.sum(e2 * e2, axis=-1))\n    e3_length = numpy.sqrt(numpy.sum(e3 * e3, axis=-1))\n    s = (e1_length + e2_length + e3_length) / 2.0\n    return numpy.sqrt(s * (s - e1_length) * (s - e2_length) * (s - e3_length))",
    "docstring": "Get the area of triangle formed by three vectors.\n\n    Parameters are three three-dimensional numpy arrays representing\n    vectors of triangle's edges in Cartesian space.\n\n    :returns:\n        Float number, the area of the triangle in squared units of coordinates,\n        or numpy array of shape of edges with one dimension less.\n\n    Uses Heron formula, see http://mathworld.wolfram.com/HeronsFormula.html."
  },
  {
    "code": "def _temp_filename(contents):\n    fp = tempfile.NamedTemporaryFile(\n        prefix='codequalitytmp', delete=False)\n    name = fp.name\n    fp.write(contents)\n    fp.close()\n    _files_to_cleanup.append(name)\n    return name",
    "docstring": "Make a temporary file with `contents`.\n\n    The file will be cleaned up on exit."
  },
  {
    "code": "def yield_for_all_futures(result):\n    while True:\n        if result is None:\n            break\n        try:\n            future = gen.convert_yielded(result)\n        except gen.BadYieldError:\n            break\n        else:\n            result = yield future\n    raise gen.Return(result)",
    "docstring": "Converts result into a Future by collapsing any futures inside result.\n\n    If result is a Future we yield until it's done, then if the value inside\n    the Future is another Future we yield until it's done as well, and so on."
  },
  {
    "code": "def collections(self, values):\n        if self.cache:\n            self.cache.set(\n                self.app.config['COLLECTIONS_CACHE_KEY'], values)",
    "docstring": "Set list of collections."
  },
  {
    "code": "def _bse_cli_list_ref_formats(args):\n    all_refformats = api.get_reference_formats()\n    if args.no_description:\n        liststr = all_refformats.keys()\n    else:\n        liststr = format_columns(all_refformats.items())\n    return '\\n'.join(liststr)",
    "docstring": "Handles the list-ref-formats subcommand"
  },
  {
    "code": "def dump_part(part, total_segments=None):\n    try:\n        connection = Connection(host=config['host'], region=config['region'])\n        filename = \".\".join([config['table_name'], str(part), \"dump\"])\n        if config['compress']:\n            opener = gzip.GzipFile\n            filename += \".gz\"\n        else:\n            opener = open\n        dumper = BatchDumper(connection, config['table_name'], config['capacity'], part, total_segments)\n        with opener(filename, 'w') as output:\n            while dumper.has_items:\n                items = dumper.get_items()\n                for item in items:\n                    output.write(json.dumps(item))\n                    output.write(\"\\n\")\n                output.flush()\n                config['queue'].put(len(items))\n        config['queue'].put('complete')\n    except Exception as e:\n        print('Unhandled exception: {0}'.format(e))",
    "docstring": "'part' may be the hash_key if we are dumping just a few hash_keys - else\n    it will be the segment number"
  },
  {
    "code": "def all_editable_exts():\r\n    exts = []\r\n    for (language, extensions) in languages.ALL_LANGUAGES.items():\r\n        exts.extend(list(extensions))\r\n    return ['.' + ext for ext in exts]",
    "docstring": "Return a list of all editable extensions"
  },
  {
    "code": "def is_running(self) -> bool:\n        return (\n            self._has_started and\n            self.is_alive() or\n            self.completed_at is None or\n            (datetime.utcnow() - self.completed_at).total_seconds() < 0.5\n        )",
    "docstring": "Specifies whether or not the thread is running"
  },
  {
    "code": "def create_snapshot(self, snapshot_size, snapshot_suffix):\n\t\tsize_extent = math.ceil(self.extents_count() * snapshot_size)\n\t\tsize_kb = self.volume_group().extent_size() * size_extent\n\t\tsnapshot_name = self.volume_name() + snapshot_suffix\n\t\tlvcreate_cmd = ['sudo'] if self.lvm_command().sudo() is True else []\n\t\tlvcreate_cmd.extend([\n\t\t\t'lvcreate', '-L', '%iK' % size_kb, '-s', '-n', snapshot_name, '-p', 'r', self.volume_path()\n\t\t])\n\t\tsubprocess.check_output(lvcreate_cmd, timeout=self.__class__.__lvm_snapshot_create_cmd_timeout__)\n\t\treturn WLogicalVolume(self.volume_path() + snapshot_suffix, sudo=self.lvm_command().sudo())",
    "docstring": "Create snapshot for this logical volume.\n\n\t\t:param snapshot_size: size of newly created snapshot volume. This size is a fraction of the source \\\n\t\tlogical volume space (of this logical volume)\n\t\t:param snapshot_suffix: suffix for logical volume name (base part is the same as the original volume \\\n\t\tname)\n\n\t\t:return: WLogicalVolume"
  },
  {
    "code": "def unsubscribe_all(self):\n        topics = list(self.topics.keys())\n        for topic in topics:\n            self.unsubscribe(topic)",
    "docstring": "Unsubscribe from all topics."
  },
  {
    "code": "def transpose_list(list_of_dicts):\n    res = {}\n    for d in list_of_dicts:\n        for k, v in d.items():\n            if k in res:\n                res[k].append(v)\n            else:\n                res[k] = [v]\n    return res",
    "docstring": "Transpose a list of dicts to a dict of lists\n\n    :param list_of_dicts: to transpose, as in the output from a parse call\n    :return: Dict of lists"
  },
  {
    "code": "def firmware_version(self):\n        buf = (ctypes.c_char * self.MAX_BUF_SIZE)()\n        self._dll.JLINKARM_GetFirmwareString(buf, self.MAX_BUF_SIZE)\n        return ctypes.string_at(buf).decode()",
    "docstring": "Returns a firmware identification string of the connected J-Link.\n\n        It consists of the following:\n          - Product Name (e.g. J-Link)\n          - The string: compiled\n          - Compile data and time.\n          - Optional additional information.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n\n        Returns:\n          Firmware identification string."
  },
  {
    "code": "def _get_num_pass(data, n):\n    numpass = tz.get_in([\"config\", \"algorithm\", \"ensemble\", \"numpass\"], data)\n    if numpass:\n        return int(numpass)\n    trusted_pct = tz.get_in([\"config\", \"algorithm\", \"ensemble\", \"trusted_pct\"], data)\n    if trusted_pct:\n        return int(math.ceil(float(trusted_pct) * n))\n    return 2",
    "docstring": "Calculate the number of samples needed to pass ensemble calling."
  },
  {
    "code": "def _create_ip_report(self):\n        try:\n            ip_report_name = os.path.join(self.report_dir, \"%s-ip.csv\" % self.session)\n            self.logger.con_out('Creating IP Report - %s', ip_report_name)\n            ip_report = open(ip_report_name, 'wt')\n            ip_report.write('Obfuscated IP,Original IP\\n')\n            for k,v in self.ip_db.items():\n                ip_report.write('%s,%s\\n' %(self._int2ip(k),self._int2ip(v)))\n            ip_report.close()\n            self.logger.info('Completed IP Report')\n            self.ip_report = ip_report_name\n        except Exception as e:\n            self.logger.exception(e)\n            raise Exception('CreateReport Error: Error Creating IP Report')",
    "docstring": "this will take the obfuscated ip and hostname databases and output csv files"
  },
  {
    "code": "def namespace_for_prefix(self, prefix):\n        try:\n            ni = self.__lookup_prefix(prefix)\n        except PrefixNotFoundError:\n            return None\n        else:\n            return ni.uri",
    "docstring": "Get the namespace the given prefix maps to.\n\n        Args:\n            prefix (str): The prefix\n\n        Returns:\n            str: The namespace, or None if the prefix isn't mapped to\n                anything in this set."
  },
  {
    "code": "def generate(env):\n    try:\n        bld = env['BUILDERS']['Rpm']\n    except KeyError:\n        bld = RpmBuilder\n        env['BUILDERS']['Rpm'] = bld\n    env.SetDefault(RPM          = 'LC_ALL=C rpmbuild')\n    env.SetDefault(RPMFLAGS     = SCons.Util.CLVar('-ta'))\n    env.SetDefault(RPMCOM       = rpmAction)\n    env.SetDefault(RPMSUFFIX    = '.rpm')",
    "docstring": "Add Builders and construction variables for rpm to an Environment."
  },
  {
    "code": "def info(self, account_id, resource_id, parent_id):\n        resource = self.record(account_id, resource_id)\n        if resource is None and not parent_id:\n            return {'ResourceId': resource_id,\n                    'LockStatus': self.STATE_UNLOCKED}\n        elif resource is None:\n            parent = self.record(account_id, parent_id)\n            if parent is None:\n                return {'ResourceId': resource_id,\n                        'ParentId': parent_id,\n                        'LockStatus': self.STATE_UNLOCKED}\n            parent['ResourceId'] = resource_id\n            parent['ParentId'] = parent_id\n            parent['LockType'] = 'parent'\n            return parent\n        if resource['ResourceId'].startswith('vpc-'):\n            return resource\n        if resource['ResourceId'].startswith('sg-'):\n            return resource",
    "docstring": "Check if a resource is locked.\n\n        If a resource has an explicit status we use that, else\n        we defer to the parent resource lock status."
  },
  {
    "code": "def upload(self, filename, **kwargs):\n        kwargs['index'] = self.name\n        path = 'data/inputs/oneshot'\n        self.service.post(path, name=filename, **kwargs)\n        return self",
    "docstring": "Uploads a file for immediate indexing.\n\n        **Note**: The file must be locally accessible from the server.\n\n        :param filename: The name of the file to upload. The file can be a\n            plain, compressed, or archived file.\n        :type filename: ``string``\n        :param kwargs: Additional arguments (optional). For more about the\n            available parameters, see `Index parameters <http://dev.splunk.com/view/SP-CAAAEE6#indexparams>`_ on Splunk Developer Portal.\n        :type kwargs: ``dict``\n\n        :return: The :class:`Index`."
  },
  {
    "code": "def _require_bucket(self, bucket_name):\n        if not self.exists(bucket_name) and not self.claim_bucket(bucket_name):\n            raise OFSException(\"Invalid bucket: %s\" % bucket_name)\n        return self._get_bucket(bucket_name)",
    "docstring": "Also try to create the bucket."
  },
  {
    "code": "def rescan_images(registry):\n    with Session() as session:\n        try:\n            result = session.Image.rescanImages(registry)\n        except Exception as e:\n            print_error(e)\n            sys.exit(1)\n        if result['ok']:\n            print(\"kernel image metadata updated\")\n        else:\n            print(\"rescanning failed: {0}\".format(result['msg']))",
    "docstring": "Update the kernel image metadata from all configured docker registries."
  },
  {
    "code": "def auto_batch_size(sequence_length,\n                    mesh_shape,\n                    layout_rules,\n                    tokens_per_split=2048):\n  num_splits = mtf.tensor_dim_to_mesh_dim_size(\n      layout_rules, mesh_shape, mtf.Dimension(\"batch\", 0))\n  ret = max(1, tokens_per_split // sequence_length) * num_splits\n  tf.logging.info(\n      \"AUTO_BATCH_SIZE tokens_per_split=%s num_splits=%s\"\n      \" sequence_length=%s batch_size=%s\"\n      % (tokens_per_split, num_splits, sequence_length, ret))\n  return ret",
    "docstring": "Automatically compute batch size.\n\n  Args:\n    sequence_length: an integer\n    mesh_shape: an input to mtf.convert_to_shape()\n    layout_rules: an input to mtf.convert_to_layout_rules()\n    tokens_per_split: an integer\n  Returns:\n    an integer"
  },
  {
    "code": "def get_current_line(self):\n        if not self.has_space():\n            return None\n        pos = self.pos - self.col\n        string = self.string\n        end = self.length\n        output = []\n        while pos < len(string) and string[pos] != '\\n':\n            output.append(string[pos])\n            pos += 1\n            if pos == end:\n                break\n        else:\n            output.append(string[pos])\n        if not output:\n            return None\n        return SourceLine(''.join(output), self.row)",
    "docstring": "Return a SourceLine of the current line."
  },
  {
    "code": "def get_json_files(files, recursive=False):\n    json_files = []\n    if not files:\n        return json_files\n    for fn in files:\n        if os.path.isdir(fn):\n            children = list_json_files(fn, recursive)\n            json_files.extend(children)\n        elif is_json(fn):\n            json_files.append(fn)\n        else:\n            continue\n    if not json_files:\n        raise NoJSONFileFoundError(\"No JSON files found!\")\n    return json_files",
    "docstring": "Return a list of files to validate from `files`. If a member of `files`\n    is a directory, its children with a ``.json`` extension will be added to\n    the return value.\n\n    Args:\n        files: A list of file paths and/or directory paths.\n        recursive: If ``true``, this will descend into any subdirectories\n            of input directories.\n\n    Returns:\n        A list of file paths to validate."
  },
  {
    "code": "def new(self, log_block_size):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('This Version Volume Descriptor is already initialized')\n        self._data = b'\\x00' * log_block_size\n        self._initialized = True",
    "docstring": "Create a new Version Volume Descriptor.\n\n        Parameters:\n         log_block_size - The size of one extent.\n        Returns:\n         Nothing."
  },
  {
    "code": "def reset(self):\n        \"If your convolutional window is greater than 1 and you save previous xs, you must reset at the beginning of each new sequence.\"\n        for layer in self.layers:     layer.reset()\n        if self.bidirectional:\n            for layer in self.layers_bwd: layer.reset()",
    "docstring": "If your convolutional window is greater than 1 and you save previous xs, you must reset at the beginning of each new sequence."
  },
  {
    "code": "def right(self, speed=1):\n        self.left_motor.forward(speed)\n        self.right_motor.backward(speed)",
    "docstring": "Make the robot turn right by running the left motor forward and right\n        motor backward.\n\n        :param float speed:\n            Speed at which to drive the motors, as a value between 0 (stopped)\n            and 1 (full speed). The default is 1."
  },
  {
    "code": "def _GenerateCRCTable():\n        poly = 0xedb88320\n        table = [0] * 256\n        for i in range(256):\n            crc = i\n            for j in range(8):\n                if crc & 1:\n                    crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly\n                else:\n                    crc = ((crc >> 1) & 0x7FFFFFFF)\n            table[i] = crc\n        return table",
    "docstring": "Generate a CRC-32 table.\n\n        ZIP encryption uses the CRC32 one-byte primitive for scrambling some\n        internal keys. We noticed that a direct implementation is faster than\n        relying on binascii.crc32()."
  },
  {
    "code": "def fetch(self):\n        params = values.of({})\n        payload = self._version.fetch(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return TaskQueueInstance(\n            self._version,\n            payload,\n            workspace_sid=self._solution['workspace_sid'],\n            sid=self._solution['sid'],\n        )",
    "docstring": "Fetch a TaskQueueInstance\n\n        :returns: Fetched TaskQueueInstance\n        :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance"
  },
  {
    "code": "def update_port(self, port_information, id_or_uri, timeout=-1):\n        uri = self._client.build_uri(id_or_uri) + \"/ports\"\n        return self._client.update(port_information, uri, timeout)",
    "docstring": "Updates an interconnect port.\n\n        Args:\n            id_or_uri: Can be either the interconnect id or the interconnect uri.\n            port_information (dict): object to update\n            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n                in OneView; it just stops waiting for its completion.\n\n        Returns:\n            dict: The interconnect."
  },
  {
    "code": "def masktorgb(mask, color='lightgreen', alpha=1.0):\n    mask = np.asarray(mask)\n    if mask.ndim != 2:\n        raise ValueError('ndim={0} is not supported'.format(mask.ndim))\n    ht, wd = mask.shape\n    r, g, b = colors.lookup_color(color)\n    rgbobj = RGBImage(data_np=np.zeros((ht, wd, 4), dtype=np.uint8))\n    rc = rgbobj.get_slice('R')\n    gc = rgbobj.get_slice('G')\n    bc = rgbobj.get_slice('B')\n    ac = rgbobj.get_slice('A')\n    ac[:] = 0\n    rc[mask] = int(r * 255)\n    gc[mask] = int(g * 255)\n    bc[mask] = int(b * 255)\n    ac[mask] = int(alpha * 255)\n    return rgbobj",
    "docstring": "Convert boolean mask to RGB image object for canvas overlay.\n\n    Parameters\n    ----------\n    mask : ndarray\n        Boolean mask to overlay. 2D image only.\n\n    color : str\n        Color name accepted by Ginga.\n\n    alpha : float\n        Opacity. Unmasked data are always transparent.\n\n    Returns\n    -------\n    rgbobj : RGBImage\n        RGB image for canvas Image object.\n\n    Raises\n    ------\n    ValueError\n        Invalid mask dimension."
  },
  {
    "code": "def do_genesis_block_audit(genesis_block_path=None, key_id=None):\n    signing_keys = GENESIS_BLOCK_SIGNING_KEYS\n    if genesis_block_path is not None:\n        genesis_block_load(genesis_block_path)\n    if key_id is not None:\n        gpg2_path = find_gpg2()\n        assert gpg2_path, 'You need to install gpg2'\n        p = subprocess.Popen([gpg2_path, '-a', '--export', key_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n        out, err = p.communicate()\n        if p.returncode != 0:\n            log.error('Failed to load key {}\\n{}'.format(key_id, err))\n            return False\n        signing_keys = { key_id: out.strip() }\n    res = genesis_block_audit(get_genesis_block_stages(), key_bundle=signing_keys)\n    if not res:\n        log.error('Genesis block is NOT signed by {}'.format(', '.join(signing_keys.keys())))\n        return False\n    return True",
    "docstring": "Loads and audits the genesis block, optionally using an alternative key"
  },
  {
    "code": "def save_pdf(self, save_model=True):\n        from django_afip.views import ReceiptPDFView\n        if not self.receipt.is_validated:\n            raise exceptions.DjangoAfipException(\n                _('Cannot generate pdf for non-authorized receipt')\n            )\n        self.pdf_file = File(BytesIO(), name='{}.pdf'.format(uuid.uuid4().hex))\n        render_pdf(\n            template='receipts/code_{}.html'.format(\n                self.receipt.receipt_type.code,\n            ),\n            file_=self.pdf_file,\n            context=ReceiptPDFView.get_context_for_pk(self.receipt_id),\n        )\n        if save_model:\n            self.save()",
    "docstring": "Save the receipt as a PDF related to this model.\n\n        The related :class:`~.Receipt` should be validated first, of course.\n\n        :param bool save_model: If True, immediately save this model instance."
  },
  {
    "code": "def start(self, timeout=None):\n        if self._handler_thread and self._handler_thread.isAlive():\n            raise RuntimeError('Message handler thread already started')\n        self._server.start(timeout)\n        self.ioloop = self._server.ioloop\n        if self._handler_thread:\n            self._handler_thread.set_ioloop(self.ioloop)\n            self._handler_thread.start(timeout)",
    "docstring": "Start the server in a new thread.\n\n        Parameters\n        ----------\n        timeout : float or None, optional\n            Time in seconds to wait for server thread to start."
  },
  {
    "code": "def add_term_occurrence(self, term, document):\n        if document not in self._documents:\n            self._documents[document] = 0\n        if term not in self._terms:\n            if self._freeze:\n                return\n            else:\n                self._terms[term] = collections.Counter()\n        if document not in self._terms[term]:\n            self._terms[term][document] = 0\n        self._documents[document] += 1\n        self._terms[term][document] += 1",
    "docstring": "Adds an occurrence of the term in the specified document."
  },
  {
    "code": "def change_score_for(self, member, delta, member_data=None):\n        self.change_score_for_member_in(self.leaderboard_name, member, delta, member_data)",
    "docstring": "Change the score for a member in the leaderboard by a score delta which can be positive or negative.\n\n        @param member [String] Member name.\n        @param delta [float] Score change.\n        @param member_data [String] Optional member data."
  },
  {
    "code": "def setValues(self, values):\n        if isinstance(values, (list, set)):\n            if any(isinstance(value, basestring) for value in values):\n                values = list(map(str, values))\n                self._impl.setValuesStr(values, len(values))\n            elif all(isinstance(value, Real) for value in values):\n                values = list(map(float, values))\n                self._impl.setValuesDbl(values, len(values))\n            elif all(isinstance(value, tuple) for value in values):\n                self._impl.setValues(Utils.toTupleArray(values), len(values))\n            else:\n                raise TypeError\n        else:\n            if np is not None and isinstance(values, np.ndarray):\n                self.setValues(DataFrame.fromNumpy(values).toList())\n                return\n            Entity.setValues(self, values)",
    "docstring": "Set the tuples in this set. Valid only for non-indexed sets.\n\n        Args:\n            values: A list of tuples or a :class:`~amplpy.DataFrame`.\n\n        In the case of a :class:`~amplpy.DataFrame`, the number of indexing\n        columns of the must be equal to the arity of the set. In the case of\n        a list of tuples, the arity of each tuple must be equal to the arity\n        of the set.\n\n        For example, considering the following AMPL entities and corresponding\n        Python objects:\n\n        .. code-block:: ampl\n\n            set A := 1..2;\n            param p{i in A} := i+10;\n            set AA;\n\n        The following is valid:\n\n        .. code-block:: python\n\n            A, AA = ampl.getSet('A'), ampl.getSet('AA')\n            AA.setValues(A.getValues())  # AA has now the members {1, 2}"
  },
  {
    "code": "def shutdown(self):\n        vm = self.get_vm_failfast(self.config['name'])\n        if vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOff:\n            print(\"%s already poweredOff\" % vm.name)\n        else:\n            if self.guestToolsRunning(vm):\n                timeout_minutes = 10\n                print(\"waiting for %s to shutdown \"\n                      \"(%s minutes before forced powerOff)\" % (\n                          vm.name,\n                          str(timeout_minutes)\n                      ))\n                vm.ShutdownGuest()\n                if self.WaitForVirtualMachineShutdown(vm,\n                                                      timeout_minutes * 60):\n                    print(\"shutdown complete\")\n                    print(\"%s poweredOff\" % vm.name)\n                else:\n                    print(\"%s has not shutdown after %s minutes:\"\n                          \"will powerOff\" % (vm.name, str(timeout_minutes)))\n                    self.powerOff()\n            else:\n                print(\"GuestTools not running or not installed: will powerOff\")\n                self.powerOff()",
    "docstring": "Shutdown guest\n        fallback to power off if guest tools aren't installed"
  },
  {
    "code": "def _x_get_physical_path(self):\n        path = self.context.getPath()\n        portal_path = api.get_path(api.get_portal())\n        if portal_path not in path:\n            return \"{}/{}\".format(portal_path, path)\n        return path",
    "docstring": "Generate the physical path"
  },
  {
    "code": "def get(self, run_id):\n        id = self._parse_id(run_id)\n        run = self.generic_dao.find_record(self.collection_name,\n                                           {\"_id\": id})\n        if run is None:\n            raise NotFoundError(\"Run %s not found.\" % run_id)\n        return run",
    "docstring": "Get a single run from the database.\n\n        :param run_id: The ID of the run.\n        :return: The whole object from the database.\n        :raise NotFoundError when not found"
  },
  {
    "code": "def _validate_date_like_dtype(dtype):\n    try:\n        typ = np.datetime_data(dtype)[0]\n    except ValueError as e:\n        raise TypeError('{error}'.format(error=e))\n    if typ != 'generic' and typ != 'ns':\n        msg = '{name!r} is too specific of a frequency, try passing {type!r}'\n        raise ValueError(msg.format(name=dtype.name, type=dtype.type.__name__))",
    "docstring": "Check whether the dtype is a date-like dtype. Raises an error if invalid.\n\n    Parameters\n    ----------\n    dtype : dtype, type\n        The dtype to check.\n\n    Raises\n    ------\n    TypeError : The dtype could not be casted to a date-like dtype.\n    ValueError : The dtype is an illegal date-like dtype (e.g. the\n                 the frequency provided is too specific)"
  },
  {
    "code": "def access_list(package):\n    team, owner, pkg = parse_package(package)\n    session = _get_session(team)\n    lookup_url = \"{url}/api/access/{owner}/{pkg}/\".format(url=get_registry_url(team), owner=owner, pkg=pkg)\n    response = session.get(lookup_url)\n    data = response.json()\n    users = data['users']\n    print('\\n'.join(users))",
    "docstring": "Print list of users who can access a package."
  },
  {
    "code": "def translations(self, lang):\n        key = self._get_translations_cache_key(lang)\n        trans_dict = cache.get(key, {})\n        if self.translatable_slug is not None:\n            if self.translatable_slug not in self.translatable_fields:\n                self.translatable_fields = self.translatable_fields + (self.translatable_slug,)\n        if not trans_dict:\n            for field in self.translatable_fields:\n                trans_dict[field] = self.get_translation(lang, field)\n            cache.set(key, trans_dict)\n        return trans_dict",
    "docstring": "Return the list of translation strings of a Translatable\n        instance in a dictionary form\n\n        @type lang: string\n        @param lang: a string with the name of the language\n\n        @rtype: python Dictionary\n        @return: Returns a all fieldname / translations (key / value)"
  },
  {
    "code": "def _parse_error_tree(error):\n    errinf = ErrorInfo(error.get('id'), None)\n    if error.text is not None:\n        errinf.message = error.text\n    else:\n        desc = error.find('./desc')\n        if desc is not None:\n            errinf.message = desc.text\n    return errinf",
    "docstring": "Parse an error ElementTree Node to create an ErrorInfo object\n\n    :param error: The ElementTree error node\n    :return: An ErrorInfo object containing the error ID and the message."
  },
  {
    "code": "def commit_config(self):\n        if self.loaded:\n            if self.ssh_connection is False:\n                self._open_ssh()\n            try:\n                self.ssh_device.commit()\n                time.sleep(3)\n                self.loaded = False\n                self.changed = True\n            except:\n                if self.merge_config:\n                    raise MergeConfigException('Error while commiting config')\n                else:\n                    raise ReplaceConfigException('Error while commiting config')\n        else:\n            raise ReplaceConfigException('No config loaded.')",
    "docstring": "Netmiko is being used to commit the configuration because it takes\n        a better care of results compared to pan-python."
  },
  {
    "code": "def _handle_result(self):\n        result = self.inbox.get()\n        if result.success:\n            if self._verbosity >= VERB_PROGRESS:\n                sys.stderr.write(\"\\nuploaded chunk {} \\n\".format(result.index))\n            self.results.append((result.index, result.md5))\n            self._pending_chunks -= 1\n        else:\n            raise result.traceback",
    "docstring": "Process one result. Block untill one is available"
  },
  {
    "code": "def list(self, count=10):\n    import IPython\n    data = []\n    for _, model in zip(range(count), self.get_iterator()):\n      element = {'name': model['name']}\n      if 'defaultVersion' in model:\n        version_short_name = model['defaultVersion']['name'].split('/')[-1]\n        element['defaultVersion'] = version_short_name\n      data.append(element)\n    IPython.display.display(\n        datalab.utils.commands.render_dictionary(data, ['name', 'defaultVersion']))",
    "docstring": "List models under the current project in a table view.\n\n    Args:\n      count: upper limit of the number of models to list.\n    Raises:\n      Exception if it is called in a non-IPython environment."
  },
  {
    "code": "def require(predicate):\n    def decorator(method):\n        @functools.wraps(method)\n        def wrapper(*args, **kwargs):\n            if predicate():\n                return method(*args, **kwargs)\n            return None\n        return wrapper\n    return decorator",
    "docstring": "Decorator factory for methods requiring a predicate. If the\n    predicate is not fulfilled during a method call, the method call\n    is skipped and None is returned.\n\n    :param predicate: A callable returning a truth value\n    :returns: Method decorator\n\n    .. seealso::\n\n        :py:class:`internet`"
  },
  {
    "code": "def set_nodelay(self, value: bool) -> None:\n        assert self.ws_connection is not None\n        self.ws_connection.set_nodelay(value)",
    "docstring": "Set the no-delay flag for this stream.\n\n        By default, small messages may be delayed and/or combined to minimize\n        the number of packets sent.  This can sometimes cause 200-500ms delays\n        due to the interaction between Nagle's algorithm and TCP delayed\n        ACKs.  To reduce this delay (at the expense of possibly increasing\n        bandwidth usage), call ``self.set_nodelay(True)`` once the websocket\n        connection is established.\n\n        See `.BaseIOStream.set_nodelay` for additional details.\n\n        .. versionadded:: 3.1"
  },
  {
    "code": "def _GetDictFromStringsTable(self, parser_mediator, table):\n    if not table:\n      return {}\n    record_values = {}\n    for record in table.records:\n      if parser_mediator.abort:\n        break\n      if record.get_number_of_values() != 2:\n        continue\n      identification = self._GetRecordValue(record, 0)\n      filename = self._GetRecordValue(record, 1)\n      if not identification:\n        continue\n      record_values[identification] = filename\n    return record_values",
    "docstring": "Build a dictionary of the value in the strings table.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      table (pyesedb.table): strings table.\n\n    Returns:\n      dict[str,object]: values per column name."
  },
  {
    "code": "def Wp(self):\n        Wp = trapz_loglog(self._Ep * self._J, self._Ep) * u.GeV\n        return Wp.to(\"erg\")",
    "docstring": "Total energy in protons"
  },
  {
    "code": "def check_qt():\r\n    qt_infos = dict(pyqt5=(\"PyQt5\", \"5.6\"))\r\n    try:\r\n        import qtpy\r\n        package_name, required_ver = qt_infos[qtpy.API]\r\n        actual_ver = qtpy.PYQT_VERSION\r\n        if LooseVersion(actual_ver) < LooseVersion(required_ver):\r\n            show_warning(\"Please check Spyder installation requirements:\\n\"\r\n                         \"%s %s+ is required (found v%s).\"\r\n                         % (package_name, required_ver, actual_ver))\r\n    except ImportError:\r\n        show_warning(\"Failed to import qtpy.\\n\"\r\n                     \"Please check Spyder installation requirements:\\n\\n\"\r\n                     \"qtpy 1.2.0+ and\\n\"\r\n                     \"%s %s+\\n\\n\"\r\n                     \"are required to run Spyder.\"\r\n                     % (qt_infos['pyqt5']))",
    "docstring": "Check Qt binding requirements"
  },
  {
    "code": "def make_as(self, klass, name, **attributes):\n        return self.of(klass, name).make(**attributes)",
    "docstring": "Create an instance of the given model and type.\n\n        :param klass: The class\n        :type klass: class\n\n        :param name: The type\n        :type name: str\n\n        :param attributes: The instance attributes\n        :type attributes: dict\n\n        :return: mixed"
  },
  {
    "code": "def fetchChildren(self):\n        assert self._canFetchChildren, \"canFetchChildren must be True\"\n        try:\n            childItems = self._fetchAllChildren()\n        finally:\n            self._canFetchChildren = False\n        return childItems",
    "docstring": "Fetches children.\n\n            The actual work is done by _fetchAllChildren. Descendant classes should typically\n            override that method instead of this one."
  },
  {
    "code": "def lock(self, back=None, remote=None):\n        back = self.backends(back)\n        locked = []\n        errors = []\n        for fsb in back:\n            fstr = '{0}.lock'.format(fsb)\n            if fstr in self.servers:\n                msg = 'Setting update lock for {0} remotes'.format(fsb)\n                if remote:\n                    if not isinstance(remote, six.string_types):\n                        errors.append(\n                            'Badly formatted remote pattern \\'{0}\\''\n                            .format(remote)\n                        )\n                        continue\n                    else:\n                        msg += ' matching {0}'.format(remote)\n                log.debug(msg)\n                good, bad = self.servers[fstr](remote=remote)\n                locked.extend(good)\n                errors.extend(bad)\n        return locked, errors",
    "docstring": "``remote`` can either be a dictionary containing repo configuration\n        information, or a pattern. If the latter, then remotes for which the URL\n        matches the pattern will be locked."
  },
  {
    "code": "def count_by_tag(stack, descriptor):\n    ec2_conn = boto.ec2.connection.EC2Connection()\n    resses = ec2_conn.get_all_instances(\n                    filters={\n                        'tag:stack': stack,\n                        'tag:descriptor': descriptor\n                    })\n    instance_list_raw = list()\n    [[instance_list_raw.append(x) for x in res.instances] for res in resses]\n    instance_list = [x for x in instance_list_raw if state_filter(x)]\n    instances = len(instance_list)\n    return instances",
    "docstring": "Returns the count of currently running or pending instances\n    that match the given stack and deployer combo"
  },
  {
    "code": "def clear(self):\n        self.root = None\n        for leaf in self.leaves:\n            leaf.p, leaf.sib, leaf.side = (None, ) * 3",
    "docstring": "Clears the Merkle Tree by releasing the Merkle root and each leaf's references, the rest\n        should be garbage collected.  This may be useful for situations where you want to take an existing\n        tree, make changes to the leaves, but leave it uncalculated for some time, without node\n        references that are no longer correct still hanging around. Usually it is better just to make\n        a new tree."
  },
  {
    "code": "def template(self):\n        r = fapi.get_config_template(self.namespace, self.name,\n                                        self.snapshot_id, self.api_url)\n        fapi._check_response_code(r, 200)\n        return r.json()",
    "docstring": "Return a method template for this method."
  },
  {
    "code": "def cmd_serve(self, *args):\n        try:\n            from http.server import SimpleHTTPRequestHandler\n            from socketserver import TCPServer\n        except ImportError:\n            from SimpleHTTPServer import SimpleHTTPRequestHandler\n            from SocketServer import TCPServer\n        os.chdir(self.bin_dir)\n        handler = SimpleHTTPRequestHandler\n        httpd = TCPServer((\"\", SIMPLE_HTTP_SERVER_PORT), handler)\n        print(\"Serving via HTTP at port {}\".format(SIMPLE_HTTP_SERVER_PORT))\n        print(\"Press Ctrl+c to quit serving.\")\n        httpd.serve_forever()",
    "docstring": "Serve the bin directory via SimpleHTTPServer"
  },
  {
    "code": "def build_arch(self, arch):\n        self.ctx.hostpython = '/usr/bin/false'\n        sub_build_dir = join(self.get_build_dir(), 'build')\n        shprint(sh.mkdir, '-p', sub_build_dir)\n        python3crystax = self.get_recipe('python3crystax', self.ctx)\n        system_python = sh.which(\"python\" + python3crystax.version)\n        if system_python is None:\n            raise OSError(\n                ('Trying to use python3crystax=={} but this Python version '\n                 'is not installed locally.').format(python3crystax.version))\n        link_dest = join(self.get_build_dir(), 'hostpython')\n        shprint(sh.ln, '-sf', system_python, link_dest)",
    "docstring": "Creates expected build and symlinks system Python version."
  },
  {
    "code": "def ResolveClientFlowURN(self, client_id, token=None):\n    if not self._value:\n      raise ValueError(\"Can't call ResolveClientFlowURN on an empty client id.\")\n    components = self.Split()\n    if len(components) == 1:\n      return self._FlowIdToUrn(self._value, client_id)\n    else:\n      root_urn = self._FlowIdToUrn(components[0], client_id)\n      try:\n        flow_symlink = aff4.FACTORY.Open(\n            root_urn,\n            aff4_type=aff4.AFF4Symlink,\n            follow_symlinks=False,\n            token=token)\n        return flow_symlink.Get(flow_symlink.Schema.SYMLINK_TARGET).Add(\n            \"/\".join(components[1:]))\n      except aff4.InstantiationError:\n        return self._FlowIdToUrn(self._value, client_id)",
    "docstring": "Resolve a URN of a flow with this id belonging to a given client.\n\n    Note that this may need a roundtrip to the datastore. Resolving algorithm\n    is the following:\n    1.  If the flow id doesn't contain slashes (flow is not nested), we just\n        append it to the <client id>/flows.\n    2.  If the flow id has slashes (flow is nested), we check if the root\n        flow pointed to by <client id>/flows/<flow id> is a symlink.\n    2a. If it's a symlink, we append the rest of the flow id to the symlink\n        target.\n    2b. If it's not a symlink, we just append the whole id to\n        <client id>/flows (meaning we do the same as in 1).\n\n    Args:\n      client_id: Id of a client where this flow is supposed to be found on.\n      token: Credentials token.\n\n    Returns:\n      RDFURN pointing to a flow identified by this flow id and client id.\n    Raises:\n      ValueError: if this flow id is not initialized."
  },
  {
    "code": "def extract_consensus_op(self, opcode, op_data, processed_op_data, current_block_number):\n        ret = {}\n        consensus_fields = op_get_consensus_fields(opcode)\n        quirk_fields = op_get_quirk_fields(opcode)\n        for field in consensus_fields + quirk_fields:\n            try:\n                assert field in processed_op_data, 'Missing consensus field \"{}\"'.format(field)\n            except Exception as e:\n                log.exception(e)\n                log.error(\"FATAL: BUG: missing consensus field {}\".format(field))\n                log.error(\"op_data:\\n{}\".format(json.dumps(op_data, indent=4, sort_keys=True)))\n                log.error(\"processed_op_data:\\n{}\".format(json.dumps(op_data, indent=4, sort_keys=True)))\n                os.abort()\n            ret[field] = processed_op_data[field]\n        return ret",
    "docstring": "Using the operation data extracted from parsing the virtualchain operation (@op_data),\n        and the checked, processed operation (@processed_op_data), return a dict that contains\n        (1) all of the consensus fields to snapshot this operation, and\n        (2) all of the data fields that we need to store for the name record (i.e. quirk fields)"
  },
  {
    "code": "def all_control_flow_elements_count(bpmn_graph):\n    gateway_counts = get_gateway_counts(bpmn_graph)\n    events_counts = get_events_counts(bpmn_graph)\n    control_flow_elements_counts = gateway_counts.copy()\n    control_flow_elements_counts.update(events_counts)\n    return sum([\n                   count for name, count in control_flow_elements_counts.items()\n                   ])",
    "docstring": "Returns the total count of all control flow elements\n    in the BPMNDiagramGraph instance.\n    \n\n    :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model.\n    :return: total count of the control flow elements in the BPMNDiagramGraph instance"
  },
  {
    "code": "def prefix(*kinds):\n    def wrap(fn):\n        try:\n            fn.prefix_kinds.extend(kinds)\n        except AttributeError:\n            fn.prefix_kinds = list(kinds)\n        return fn\n    return wrap",
    "docstring": "Decorate a method as handling prefix tokens of the given kinds"
  },
  {
    "code": "def get_filter_value(self, column_name):\n        for flt, value in zip(self.filters, self.values):\n            if flt.column_name == column_name:\n                return value",
    "docstring": "Returns the filtered value for a certain column\n\n            :param column_name: The name of the column that we want the value from\n            :return: the filter value of the column"
  },
  {
    "code": "def can_use_cached_output(self, contentitem):\n        plugin = contentitem.plugin\n        return appsettings.FLUENT_CONTENTS_CACHE_OUTPUT and plugin.cache_output and contentitem.pk",
    "docstring": "Tell whether the code should try reading cached output"
  },
  {
    "code": "def get_camera_info(self, camera_id):\n        response = api.request_camera_info(self.blink,\n                                           self.network_id,\n                                           camera_id)\n        try:\n            return response['camera'][0]\n        except (TypeError, KeyError):\n            _LOGGER.error(\"Could not extract camera info: %s\",\n                          response,\n                          exc_info=True)\n            return []",
    "docstring": "Retrieve camera information."
  },
  {
    "code": "def _detect(self):\n        results = []\n        for c in self.contracts:\n            functions = self.detect_suicidal(c)\n            for func in functions:\n                txt = \"{}.{} ({}) allows anyone to destruct the contract\\n\"\n                info = txt.format(func.contract.name,\n                                  func.name,\n                                  func.source_mapping_str)\n                json = self.generate_json_result(info)\n                self.add_function_to_json(func, json)\n                results.append(json)\n        return results",
    "docstring": "Detect the suicidal functions"
  },
  {
    "code": "def _base_type(self):\n        type_class = self._dimension_dict[\"type\"][\"class\"]\n        if type_class == \"categorical\":\n            return \"categorical\"\n        if type_class == \"enum\":\n            subclass = self._dimension_dict[\"type\"][\"subtype\"][\"class\"]\n            return \"enum.%s\" % subclass\n        raise NotImplementedError(\"unexpected dimension type class '%s'\" % type_class)",
    "docstring": "Return str like 'enum.numeric' representing dimension type.\n\n        This string is a 'type.subclass' concatenation of the str keys\n        used to identify the dimension type in the cube response JSON.\n        The '.subclass' suffix only appears where a subtype is present."
  },
  {
    "code": "def collection_get_options(collection_name, **kwargs):\n    cluster = cluster_status(**kwargs)\n    options = {\n        \"collection.configName\": cluster[\"collections\"][collection_name][\"configName\"],\n        \"router.name\": cluster[\"collections\"][collection_name][\"router\"][\"name\"],\n        \"replicationFactor\": int(cluster[\"collections\"][collection_name][\"replicationFactor\"]),\n        \"maxShardsPerNode\": int(cluster[\"collections\"][collection_name][\"maxShardsPerNode\"]),\n        \"autoAddReplicas\": cluster[\"collections\"][collection_name][\"autoAddReplicas\"] is True\n    }\n    if 'rule' in cluster[\"collections\"][collection_name]:\n        options['rule'] = cluster[\"collections\"][collection_name]['rule']\n    if 'snitch' in cluster[\"collections\"][collection_name]:\n        options['snitch'] = cluster[\"collections\"][collection_name]['rule']\n    return options",
    "docstring": "Get collection options\n\n    Additional parameters (kwargs) may be passed, they will be proxied to http.query\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' solrcloud.collection_get_options collection_name"
  },
  {
    "code": "def read(fname):\n    file_path = os.path.join(SETUP_DIRNAME, fname)\n    with codecs.open(file_path, encoding='utf-8') as rfh:\n        return rfh.read()",
    "docstring": "Read a file from the directory where setup.py resides"
  },
  {
    "code": "def retry_on_ec2_error(self, func, *args, **kwargs):\n        exception_retry_count = 6\n        while True:\n            try:\n                return func(*args, **kwargs)\n            except (boto.exception.EC2ResponseError, ssl.SSLError) as msg:\n                exception_retry_count -= 1\n                if exception_retry_count <= 0:\n                    raise msg\n                time.sleep(5)",
    "docstring": "Call the given method with the given arguments, retrying if the call\n        failed due to an EC2ResponseError. This method will wait at most 30\n        seconds and perform up to 6 retries. If the method still fails, it will\n        propagate the error.\n\n        :param func: Function to call\n        :type func: function"
  },
  {
    "code": "def ext_pillar(minion_id,\n               pillar,\n               conf):\n    vs = varstack.Varstack(config_filename=conf)\n    return vs.evaluate(__grains__)",
    "docstring": "Parse varstack data and return the result"
  },
  {
    "code": "def view_modifier(parser, token):\n    try:\n        tag_name, view_modifier = token.split_contents()\n    except ValueError:\n        raise template.TemplateSyntaxError('view_modifier tag requires 1 argument (view_modifier), %s given' % (len(token.split_contents()) - 1))\n    return ViewModifierNode(view_modifier)",
    "docstring": "Output view modifier."
  },
  {
    "code": "def default_values_of(func):\n    signature = inspect.signature(func)\n    return [k\n            for k, v in signature.parameters.items()\n            if v.default is not inspect.Parameter.empty or\n            v.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD]",
    "docstring": "Return the defaults of the function `func`."
  },
  {
    "code": "def sign(self, request, authheaders, response_body, secret):\n        if \"nonce\" not in authheaders or authheaders[\"nonce\"] == '':\n            raise KeyError(\"nonce required in authorization headers.\")\n        if request.get_header('x-authorization-timestamp') == '':\n            raise KeyError(\"X-Authorization-Timestamp is required.\")\n        try:\n            mac = hmac.HMAC(base64.b64decode(secret.encode('utf-8'), validate=True), digestmod=self.digest)\n        except TypeError:\n            s = secret.encode('utf-8')\n            if not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):\n                raise binascii.Error('Non-base64 digit found')\n            mac = hmac.HMAC(base64.b64decode(s), digestmod=self.digest)\n        mac.update(self.signable(request, authheaders, response_body).encode('utf-8'))\n        digest = mac.digest()\n        return base64.b64encode(digest).decode('utf-8')",
    "docstring": "Returns the response signature for the response to the request.\n\n        Keyword arguments:\n        request -- A request object which can be consumed by this API.\n        authheaders -- A string-indexable object which contains the headers appropriate for this signature version.\n        response_body -- A string or bytes-like object which represents the body of the response.\n        secret -- The base64-encoded secret key for the HMAC authorization."
  },
  {
    "code": "def zscore(arr):\n    arr = arr - np.mean(arr)\n    std = np.std(arr)\n    if std != 0:\n        arr /= std\n    return arr",
    "docstring": "Return arr normalized with mean 0 and unit variance.\n\n    If the input has 0 variance, the result will also have 0 variance.\n\n    Parameters\n    ----------\n    arr : array-like\n\n    Returns\n    -------\n    zscore : array-like\n\n    Examples\n    --------\n    Compute the z score for a small array:\n\n    >>> result = zscore([1, 0])\n    >>> result\n    array([ 1., -1.])\n    >>> np.mean(result)\n    0.0\n    >>> np.std(result)\n    1.0\n\n    Does not re-scale in case the input is constant (has 0 variance):\n\n    >>> zscore([1, 1])\n    array([ 0., 0.])"
  },
  {
    "code": "def main():\n    import sys\n    from bokeh.command.bootstrap import main as _main\n    _main(sys.argv)",
    "docstring": "Execute the \"bokeh\" command line program."
  },
  {
    "code": "def toil_get_file(file_store, index, existing, file_store_id):\n    if not file_store_id.startswith(\"toilfs:\"):\n        return file_store.jobStore.getPublicUrl(file_store.jobStore.importFile(file_store_id))\n    src_path = file_store.readGlobalFile(file_store_id[7:])\n    index[src_path] = file_store_id\n    existing[file_store_id] = src_path\n    return schema_salad.ref_resolver.file_uri(src_path)",
    "docstring": "Get path to input file from Toil jobstore."
  },
  {
    "code": "def configure_root(self, config, incremental=False):\n        root = logging.getLogger()\n        self.common_logger_config(root, config, incremental)",
    "docstring": "Configure a root logger from a dictionary."
  },
  {
    "code": "def return_obj(cols, df, return_cols=False):\n        df_holder = DataFrameHolder(cols=cols, df=df)\n        return df_holder.return_self(return_cols=return_cols)",
    "docstring": "Construct a DataFrameHolder and then return either that or the DataFrame."
  },
  {
    "code": "def solve(self):\n        start = time.time()\n        root_dependency = Dependency(self._root.name, self._root.version)\n        root_dependency.is_root = True\n        self._add_incompatibility(\n            Incompatibility([Term(root_dependency, False)], RootCause())\n        )\n        try:\n            next = self._root.name\n            while next is not None:\n                self._propagate(next)\n                next = self._choose_package_version()\n            return self._result()\n        except Exception:\n            raise\n        finally:\n            self._log(\n                \"Version solving took {:.3f} seconds.\\n\"\n                \"Tried {} solutions.\".format(\n                    time.time() - start, self._solution.attempted_solutions\n                )\n            )",
    "docstring": "Finds a set of dependencies that match the root package's constraints,\n        or raises an error if no such set is available."
  },
  {
    "code": "def add_module(self, module):\n        for key, value in module.__dict__.iteritems():\n            if key[0:2] != '__':\n                self.__setattr__(attr=key, value=value)",
    "docstring": "Adds configuration parameters from a Python module."
  },
  {
    "code": "def get_create_security_group_commands(self, sg_id, sg_rules):\n        cmds = []\n        in_rules, eg_rules = self._format_rules_for_eos(sg_rules)\n        cmds.append(\"ip access-list %s dynamic\" %\n                    self._acl_name(sg_id, n_const.INGRESS_DIRECTION))\n        for in_rule in in_rules:\n            cmds.append(in_rule)\n        cmds.append(\"exit\")\n        cmds.append(\"ip access-list %s dynamic\" %\n                    self._acl_name(sg_id, n_const.EGRESS_DIRECTION))\n        for eg_rule in eg_rules:\n            cmds.append(eg_rule)\n        cmds.append(\"exit\")\n        return cmds",
    "docstring": "Commands for creating ACL"
  },
  {
    "code": "def image_info(call=None, kwargs=None):\n    if call != 'function':\n        raise SaltCloudSystemExit(\n            'The image_info function must be called with -f or --function.'\n        )\n    if kwargs is None:\n        kwargs = {}\n    name = kwargs.get('name', None)\n    image_id = kwargs.get('image_id', None)\n    if image_id:\n        if name:\n            log.warning(\n                'Both the \\'image_id\\' and \\'name\\' arguments were provided. '\n                '\\'image_id\\' will take precedence.'\n            )\n    elif name:\n        image_id = get_image_id(kwargs={'name': name})\n    else:\n        raise SaltCloudSystemExit(\n            'The image_info function requires either a \\'name or an \\'image_id\\' '\n            'to be provided.'\n        )\n    server, user, password = _get_xml_rpc()\n    auth = ':'.join([user, password])\n    info = {}\n    response = server.one.image.info(auth, int(image_id))[1]\n    tree = _get_xml(response)\n    info[tree.find('NAME').text] = _xml_to_dict(tree)\n    return info",
    "docstring": "Retrieves information for a given image. Either a name or an image_id must be\n    supplied.\n\n    .. versionadded:: 2016.3.0\n\n    name\n        The name of the image for which to gather information. Can be used instead\n        of ``image_id``.\n\n    image_id\n        The ID of the image for which to gather information. Can be used instead of\n        ``name``.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -f image_info opennebula name=my-image\n        salt-cloud --function image_info opennebula image_id=5"
  },
  {
    "code": "def generate_anomaly(self, input_word, list_of_dict_words, num):\n        results = []\n        for i in range(0,num):\n            index = randint(0,len(list_of_dict_words)-1)\n            name = list_of_dict_words[index]\n            if name != input_word and name not in results:\n                results.append(PataLib().strip_underscore(name))\n            else:\n                i = i +1\n        results = {'input' : input_word, 'results' : results, 'category' : 'anomaly'} \n        return results",
    "docstring": "Generate an anomaly. This is done\n        via a Psuedo-random number generator."
  },
  {
    "code": "def addUrlScheme(self, url):\n        if not isinstance(url, str):\n            raise TypeError('url must be a string value')\n        if not url in self._urlSchemes:\n            self._urlSchemes[url] = OEmbedUrlScheme(url)",
    "docstring": "Add a url scheme to this endpoint. It takes a url string and create\n        the OEmbedUrlScheme object internally.\n\n        Args:\n            url: The url string that represents a url scheme to add."
  },
  {
    "code": "def add(self, source_id, auth, validate=True):\n        params = {'id': source_id, 'auth': auth, 'validate': validate}\n        return self.request.post('add', params)",
    "docstring": "Add one or more sets of authorization credentials to a Managed Source\n\n            Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceauthadd\n\n            :param source_id: target Source ID\n            :type source_id: str\n            :param auth: An array of the source-specific authorization credential sets that you're adding.\n            :type auth: array of strings\n            :param validate: Allows you to suppress the validation of the authorization credentials, defaults to true.\n            :type validate: bool\n            :return: dict of REST API output with headers attached\n            :rtype: :class:`~datasift.request.DictResponse`\n            :raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`"
  },
  {
    "code": "def doSolve(fitsfn: Path, args: str=None):\n    opts = args.split(' ') if args else []\n    cmd = ['solve-field', '--overwrite', str(fitsfn)]\n    cmd += opts\n    print('\\n', ' '.join(cmd), '\\n')\n    ret = subprocess.check_output(cmd, universal_newlines=True)\n    print(ret)\n    if 'Did not solve' in ret:\n        raise RuntimeError(f'could not solve {fitsfn}')\n    print('\\n\\n *** done with astrometry.net ***\\n ')",
    "docstring": "Astrometry.net from at least version 0.67 is OK with Python 3."
  },
  {
    "code": "def top_charts(self):\n\t\tresponse = self._call(mc_calls.BrowseTopChart)\n\t\ttop_charts = response.body\n\t\treturn top_charts",
    "docstring": "Get a listing of the default top charts."
  },
  {
    "code": "def get_metadata(self, lcid):\n        if self._metadata is None:\n            self._metadata = fetch_rrlyrae_lc_params()\n        i = np.where(self._metadata['id'] == lcid)[0]\n        if len(i) == 0:\n            raise ValueError(\"invalid lcid: {0}\".format(lcid))\n        return self._metadata[i[0]]",
    "docstring": "Get the parameters derived from the fit for the given id.\n        This is table 2 of Sesar 2010"
  },
  {
    "code": "def _validate_num_units(num_units, service_name, add_error):\n    if num_units is None:\n        return 0\n    try:\n        num_units = int(num_units)\n    except (TypeError, ValueError):\n        add_error(\n            'num_units for service {} must be a digit'.format(service_name))\n        return\n    if num_units < 0:\n        add_error(\n            'num_units {} for service {} must be a positive digit'\n            ''.format(num_units, service_name))\n        return\n    return num_units",
    "docstring": "Check that the given num_units is valid.\n\n    Use the given service name to describe possible errors.\n    Use the given add_error callable to register validation error.\n\n    If no errors are encountered, return the number of units as an integer.\n    Return None otherwise."
  },
  {
    "code": "def top_parent(self):\n        parent = self.parent\n        while parent is not None:\n            if parent.parent is None:\n                return parent\n            else:\n                parent = parent.parent\n        return self",
    "docstring": "Reference to top parent declaration.\n\n           @type: declaration_t"
  },
  {
    "code": "def controller(url_prefix_or_controller_cls: Union[str, Type[Controller]],\n               controller_cls: Optional[Type[Controller]] = None,\n               *,\n               rules: Optional[Iterable[Union[Route, RouteGenerator]]] = None,\n               ) -> RouteGenerator:\n    url_prefix, controller_cls = _normalize_args(\n        url_prefix_or_controller_cls, controller_cls, _is_controller_cls)\n    url_prefix = url_prefix or controller_cls.Meta.url_prefix\n    routes = []\n    controller_routes = getattr(controller_cls, CONTROLLER_ROUTES_ATTR)\n    if rules is None:\n        routes = controller_routes.values()\n    else:\n        for route in _reduce_routes(rules):\n            existing = controller_routes.get(route.method_name)\n            if existing:\n                routes.append(_inherit_route_options(route, existing[0]))\n            else:\n                routes.append(route)\n    yield from _normalize_controller_routes(routes, controller_cls,\n                                            url_prefix=url_prefix)",
    "docstring": "This function is used to register a controller class's routes.\n\n    Example usage::\n\n        routes = lambda: [\n            controller(SiteController),\n        ]\n\n    Or with the optional prefix argument::\n\n        routes = lambda: [\n            controller('/products', ProductController),\n        ]\n\n    Specify ``rules`` to only include those routes from the controller::\n\n        routes = lambda: [\n            controller(SecurityController, rules=[\n               rule('/login', SecurityController.login),\n               rule('/logout', SecurityController.logout),\n               rule('/sign-up', SecurityController.register),\n            ]),\n        ]\n\n    :param url_prefix_or_controller_cls: The controller class, or a url prefix for\n                                         all of the rules from the controller class\n                                         passed as the second argument\n    :param controller_cls: If a url prefix was given as the first argument, then\n                           the controller class must be passed as the second argument\n    :param rules: An optional list of rules to limit/customize the routes included\n                  from the controller"
  },
  {
    "code": "def makePublicDir(dirName):\n    if not os.path.exists(dirName):\n        os.mkdir(dirName)\n        os.chmod(dirName, 0o777)\n    return dirName",
    "docstring": "Makes a given subdirectory if it doesn't already exist, making sure it is public."
  },
  {
    "code": "def extract_aiml(path='aiml-en-us-foundation-alice.v1-9'):\n    path = find_data_path(path) or path\n    if os.path.isdir(path):\n        paths = os.listdir(path)\n        paths = [os.path.join(path, p) for p in paths]\n    else:\n        zf = zipfile.ZipFile(path)\n        paths = []\n        for name in zf.namelist():\n            if '.hg/' in name:\n                continue\n            paths.append(zf.extract(name, path=BIGDATA_PATH))\n    return paths",
    "docstring": "Extract an aiml.zip file if it hasn't been already and return a list of aiml file paths"
  },
  {
    "code": "def export(user, directory=None, warnings=True):\n    current_file = os.path.realpath(__file__)\n    current_path = os.path.dirname(current_file)\n    dashboard_path = os.path.join(current_path, 'dashboard_src')\n    if directory:\n        dirpath = directory\n    else:\n        dirpath = tempfile.mkdtemp()\n    copy_tree(dashboard_path + '/public', dirpath, update=1)\n    data = user_data(user)\n    bc.io.to_json(data, dirpath + '/data/bc_export.json', warnings=False)\n    if warnings:\n        print(\"Successfully exported the visualization to %s\" % dirpath)\n    return dirpath",
    "docstring": "Build a temporary directory with the visualization.\n    Returns the local path where files have been written.\n\n    Examples\n    --------\n\n        >>> bandicoot.visualization.export(U)\n        Successfully exported the visualization to /tmp/tmpsIyncS"
  },
  {
    "code": "def history(ctx, archive_name):\n    _generate_api(ctx)\n    var = ctx.obj.api.get_archive(archive_name)\n    click.echo(pprint.pformat(var.get_history()))",
    "docstring": "Get archive history"
  },
  {
    "code": "def bids_to_you(self):\n        headers = {\"Content-type\": \"application/x-www-form-urlencoded\",\"Accept\": \"text/plain\",'Referer': 'http://'+self.domain+'/team_news.phtml',\"User-Agent\": user_agent}\n        req = self.session.get('http://'+self.domain+'/exchangemarket.phtml?viewoffers_x=',headers=headers).content\n        soup = BeautifulSoup(req)\n        table = []\n        for i in soup.find('table',{'class','tablecontent03'}).find_all('tr')[1:]:\n            player,owner,team,price,bid_date,trans_date,status = self._parse_bid_table(i)\n            table.append([player,owner,team,price,bid_date,trans_date,status])\n        return table",
    "docstring": "Get bids made to you\n        @return: [[player,owner,team,money,date,datechange,status],]"
  },
  {
    "code": "def bits_to_dict(bits):\n    cleaned_bits = [bit[:-1] if bit.endswith(',') else bit for bit in bits]\n    options = dict(bit.split('=') for bit in cleaned_bits)\n    for key in options:\n        if options[key] == \"'true'\" or options[key] == \"'false'\":\n            options[key] = options[key].title()\n        options[key] = ast.literal_eval(options[key])\n    return options",
    "docstring": "Convert a Django template tag's kwargs into a dictionary of Python types.\n\n    The only necessary types are number, boolean, list, and string.\n    http://pygments.org/docs/formatters/#HtmlFormatter\n\n    from: [\"style='monokai'\", \"cssclass='cssclass',\", \"boolean='true',\", 'num=0,', \"list='[]'\"]\n      to: {'style': 'monokai', 'cssclass': 'cssclass', 'boolean': True, 'num': 0, 'list': [],}"
  },
  {
    "code": "def tco_return_handle(tokens):\n    internal_assert(len(tokens) == 2, \"invalid tail-call-optimizable return statement tokens\", tokens)\n    if tokens[1].startswith(\"()\"):\n        return \"return _coconut_tail_call(\" + tokens[0] + \")\" + tokens[1][2:]\n    else:\n        return \"return _coconut_tail_call(\" + tokens[0] + \", \" + tokens[1][1:]",
    "docstring": "Process tail-call-optimizable return statements."
  },
  {
    "code": "def get_class(class_string):\n    split_string = class_string.encode('ascii').split('.')\n    import_path = '.'.join(split_string[:-1])\n    class_name = split_string[-1]\n    if class_name:\n        try:\n            if import_path:\n                mod = __import__(import_path, globals(), {}, [class_name])\n                cls = getattr(mod, class_name)\n            else:\n                cls = __import__(class_name, globals(), {})\n            if cls:\n                return cls\n        except (ImportError, AttributeError):\n            pass\n    return None",
    "docstring": "Get a class from a dotted string"
  },
  {
    "code": "def reply(self, messageId, *messageParts):\n        routingInfo = self._routingInfo.pop(messageId)\n        self.send(routingInfo + [messageId, b''] + list(messageParts))",
    "docstring": "Send reply to request with specified ``messageId``.\n\n        :param messageId: message uuid\n        :type messageId: str\n        :param messageParts: message data\n        :type messageParts: list"
  },
  {
    "code": "def _getFieldsInDB(self, tablename):\n\t\tSQL = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME=\"%s\"' % tablename\n\t\tarray_data = self.execQuery(SQL)\n\t\treturn [x[0] for x in array_data]",
    "docstring": "get all the fields from a specific table"
  },
  {
    "code": "def open_assignments(self):\n        qs = Assignment.objects.filter(hard_deadline__gt=timezone.now(\n        )) | Assignment.objects.filter(hard_deadline__isnull=True)\n        if not self.can_see_future():\n            qs = qs.filter(publish_at__lt=timezone.now())\n        qs = qs.filter(course__in=self.user_courses())\n        qs = qs.order_by('soft_deadline', '-gradingScheme', 'title')\n        waiting_for_action = [subm.assignment for subm in self.user.authored.all(\n        ).exclude(state=Submission.WITHDRAWN)]\n        qs_without_soft_deadline = qs.filter(soft_deadline__isnull=True)\n        qs_with_soft_deadline = qs.filter(soft_deadline__isnull=False)\n        ass_list = [\n            ass for ass in qs_without_soft_deadline if ass not in waiting_for_action]\n        ass_list += [\n            ass for ass in qs_with_soft_deadline if ass not in waiting_for_action]\n        return ass_list",
    "docstring": "Returns the list of open assignments from the\n            viewpoint of this user."
  },
  {
    "code": "def load_config(cls, opts, path=None, profile=None):\n        if path and os.path.exists(path):\n            if os.path.isdir(path):\n                cls.config_searchpath.insert(0, path)\n            else:\n                cls.config_files.insert(0, path)\n        config = cls.read_config()\n        values = config.get(\"default\", {})\n        cls._load_values_into_opts(opts, values)\n        if profile and profile != \"default\":\n            values = config.get(\"profile:%s\" % profile, {})\n            cls._load_values_into_opts(opts, values)\n        return values",
    "docstring": "Load a configuration file into an options object."
  },
  {
    "code": "def prep_image(image, tile_size):\n    w, h = image.size\n    x_tiles = w / tile_size\n    y_tiles = h / tile_size\n    new_w = x_tiles * tile_size\n    new_h = y_tiles * tile_size\n    if new_w == w and new_h == h:\n        return image\n    else:\n        crop_bounds = (0, 0, new_w, new_h)\n        return image.crop(crop_bounds)",
    "docstring": "Takes an image and a tile size and returns a possibly cropped version\n    of the image that is evenly divisible in both dimensions by the tile size."
  },
  {
    "code": "def stop(self):\n        if self._outstanding:\n            _LOGGER.warning('There were %d outstanding requests',\n                            len(self._outstanding))\n        self._initial_message_sent = False\n        self._outstanding = {}\n        self._one_shots = {}\n        self.connection.close()",
    "docstring": "Disconnect from device."
  },
  {
    "code": "def queryset(self, request, queryset):\n        form = self.get_form(request)\n        self.form = form\n        start_date = form.start_date()\n        end_date = form.end_date()\n        if form.is_valid() and (start_date or end_date):\n            args = self.__get_filterargs(\n                start=start_date,\n                end=end_date,\n            )\n            return queryset.filter(**args)",
    "docstring": "That's the trick - we create self.form when django tries to get our queryset.\n        This allows to create unbount and bound form in the single place."
  },
  {
    "code": "def _nonzero_intersection(m, m_hat):\n    n_features, _ = m.shape\n    m_no_diag = m.copy()\n    m_no_diag[np.diag_indices(n_features)] = 0\n    m_hat_no_diag = m_hat.copy()\n    m_hat_no_diag[np.diag_indices(n_features)] = 0\n    m_hat_nnz = len(np.nonzero(m_hat_no_diag.flat)[0])\n    m_nnz = len(np.nonzero(m_no_diag.flat)[0])\n    intersection_nnz = len(\n        np.intersect1d(np.nonzero(m_no_diag.flat)[0], np.nonzero(m_hat_no_diag.flat)[0])\n    )\n    return m_nnz, m_hat_nnz, intersection_nnz",
    "docstring": "Count the number of nonzeros in and between m and m_hat.\n\n    Returns\n    ----------\n    m_nnz :  number of nonzeros in m (w/o diagonal)\n\n    m_hat_nnz : number of nonzeros in m_hat (w/o diagonal)\n\n    intersection_nnz : number of nonzeros in intersection of m/m_hat\n                      (w/o diagonal)"
  },
  {
    "code": "def grad_dot(dy, x1, x2):\n  if len(numpy.shape(x1)) == 1:\n    dy = numpy.atleast_2d(dy)\n  elif len(numpy.shape(x2)) == 1:\n    dy = numpy.transpose(numpy.atleast_2d(dy))\n    x2 = numpy.transpose(numpy.atleast_2d(x2))\n  x2_t = numpy.transpose(numpy.atleast_2d(\n      numpy.sum(x2, axis=tuple(numpy.arange(numpy.ndim(x2) - 2)))))\n  dy_x2 = numpy.sum(dy, axis=tuple(-numpy.arange(numpy.ndim(x2) - 2) - 2))\n  return numpy.reshape(numpy.dot(dy_x2, x2_t), numpy.shape(x1))",
    "docstring": "Gradient of NumPy dot product w.r.t. to the left hand side.\n\n  Args:\n    dy: The gradient with respect to the output.\n    x1: The left hand side of the `numpy.dot` function.\n    x2: The right hand side\n\n  Returns:\n    The gradient with respect to `x1` i.e. `x2.dot(dy.T)` with all the\n    broadcasting involved."
  },
  {
    "code": "def get_staged_files():\n    proc = subprocess.Popen(('git', 'status', '--porcelain'),\n                            stdout=subprocess.PIPE,\n                            stderr=subprocess.PIPE)\n    out, _ = proc.communicate()\n    staged_files = modified_re.findall(out)\n    return staged_files",
    "docstring": "Get all files staged for the current commit."
  },
  {
    "code": "def save_headers(cls, filename: str, response: HTTPResponse):\n        new_filename = filename + '-new'\n        with open('wb') as new_file:\n            new_file.write(response.header())\n            with wpull.util.reset_file_offset(response.body):\n                response.body.seek(0)\n                shutil.copyfileobj(response.body, new_file)\n        os.remove(filename)\n        os.rename(new_filename, filename)",
    "docstring": "Prepend the HTTP response header to the file.\n\n        Args:\n            filename: The path of the file\n            response: Response"
  },
  {
    "code": "def get_cash_asset_class(self) -> AssetClass:\n        for ac in self.asset_classes:\n            if ac.name.lower() == \"cash\":\n                return ac\n        return None",
    "docstring": "Find the cash asset class by name."
  },
  {
    "code": "def run(\n    target,\n    target_type,\n    tags=None,\n    ruleset_name=None,\n    ruleset_file=None,\n    ruleset=None,\n    logging_level=logging.WARNING,\n    checks_paths=None,\n    pull=None,\n    insecure=False,\n    skips=None,\n    timeout=None,\n):\n    _set_logging(level=logging_level)\n    logger.debug(\"Checking started.\")\n    target = Target.get_instance(\n        target=target,\n        logging_level=logging_level,\n        pull=pull,\n        target_type=target_type,\n        insecure=insecure,\n    )\n    checks_to_run = _get_checks(\n        target_type=target.__class__,\n        tags=tags,\n        ruleset_name=ruleset_name,\n        ruleset_file=ruleset_file,\n        ruleset=ruleset,\n        checks_paths=checks_paths,\n        skips=skips,\n    )\n    result = go_through_checks(target=target, checks=checks_to_run, timeout=timeout)\n    return result",
    "docstring": "Runs the sanity checks for the target.\n\n    :param timeout: timeout per-check (in seconds)\n    :param skips: name of checks to skip\n    :param target: str (image name, ostree or dockertar)\n                    or ImageTarget\n                    or path/file-like object for dockerfile\n    :param target_type: string, either image, dockerfile, dockertar\n    :param tags: list of str (if not None, the checks will be filtered by tags.)\n    :param ruleset_name: str (e.g. fedora; if None, default would be used)\n    :param ruleset_file: fileobj instance holding ruleset configuration\n    :param ruleset: dict, content of a ruleset file\n    :param logging_level: logging level (default logging.WARNING)\n    :param checks_paths: list of str, directories where the checks are present\n    :param pull: bool, pull the image from registry\n    :param insecure: bool, pull from an insecure registry (HTTP/invalid TLS)\n    :return: Results instance"
  },
  {
    "code": "def from_request(request=None) -> dict:\n    request = request if request else flask_request\n    try:\n        json_args = request.get_json(silent=True)\n    except Exception:\n        json_args = None\n    try:\n        get_args = request.values\n    except Exception:\n        get_args = None\n    arg_sources = list(filter(\n        lambda arg: arg is not None,\n        [json_args, get_args, {}]\n    ))\n    return arg_sources[0]",
    "docstring": "Fetches the arguments for the current Flask application request"
  },
  {
    "code": "def preview(ident):\n    source = get_source(ident)\n    cls = backends.get(current_app, source.backend)\n    max_items = current_app.config['HARVEST_PREVIEW_MAX_ITEMS']\n    backend = cls(source, dryrun=True, max_items=max_items)\n    return backend.harvest()",
    "docstring": "Preview an harvesting for a given source"
  },
  {
    "code": "def step(self, step_size: Timedelta=None):\n        old_step_size = self.clock.step_size\n        if step_size is not None:\n            if not isinstance(step_size, type(self.clock.step_size)):\n                raise ValueError(f\"Provided time must be an instance of {type(self.clock.step_size)}\")\n            self.clock._step_size = step_size\n        super().step()\n        self.clock._step_size = old_step_size",
    "docstring": "Advance the simulation one step.\n\n        Parameters\n        ----------\n        step_size\n            An optional size of step to take. Must be the same type as the\n            simulation clock's step size (usually a pandas.Timedelta)."
  },
  {
    "code": "def are_none(sequences: Sequence[Sized]) -> bool:\n    if not sequences:\n        return True\n    return all(s is None for s in sequences)",
    "docstring": "Returns True if all sequences are None."
  },
  {
    "code": "def save_state(self):\n        set_setting('lastSourceDir', self.source_directory.text())\n        set_setting('lastOutputDir', self.output_directory.text())\n        set_setting(\n            'useDefaultOutputDir', self.scenario_directory_radio.isChecked())",
    "docstring": "Save current state of GUI to configuration file."
  },
  {
    "code": "def derive_value(self, value):\n        return IonEvent(\n            self.event_type,\n            self.ion_type,\n            value,\n            self.field_name,\n            self.annotations,\n            self.depth\n        )",
    "docstring": "Derives a new event from this one setting the ``value`` attribute.\n\n        Args:\n            value: (any):\n                The value associated with the derived event.\n\n        Returns:\n            IonEvent: The newly generated non-thunk event."
  },
  {
    "code": "def draw_rect(grid, attr, dc, rect):\n\tdc.SetBrush(wx.Brush(wx.Colour(15, 255, 127), wx.SOLID))\n\tdc.SetPen(wx.Pen(wx.BLUE, 1, wx.SOLID))\n\tdc.DrawRectangleRect(rect)",
    "docstring": "Draws a rect"
  },
  {
    "code": "def remove_user_permission(rid, uid, action='full'):\n    rid = rid.replace('/', '%252F')\n    try:\n        acl_url = urljoin(_acl_url(), 'acls/{}/users/{}/{}'.format(rid, uid, action))\n        r = http.delete(acl_url)\n        assert r.status_code == 204\n    except DCOSHTTPException as e:\n        if e.response.status_code != 400:\n            raise",
    "docstring": "Removes user permission on a given resource.\n\n        :param uid: user id\n        :type uid: str\n        :param rid: resource ID\n        :type rid: str\n        :param action: read, write, update, delete or full\n        :type action: str"
  },
  {
    "code": "def disconnect_all(self):\r\n        if not self.__connected:\r\n            return\n        self.__disconnecting = True\r\n        try:\r\n            for signal in self.__signals:\r\n                signal.disconnect(self.__signalReceived)\r\n            if self.__slot is not None:\r\n                self.__sigDelayed.disconnect(self.__slot)\r\n            self.__connected = False\r\n        finally:\r\n            self.__disconnecting = False",
    "docstring": "Disconnects all signals and slots.\r\n\r\n        If already in \"disconnected\" state, ignores the call."
  },
  {
    "code": "def depth(self) -> int:\n        if len(self.children):\n            return 1 + max([child.depth for child in self.children])\n        else:\n            return 1",
    "docstring": "Depth of the citation scheme\n\n        .. example:: If we have a Book, Poem, Line system, and the citation we are looking at is Poem, depth is 1\n\n\n        :rtype: int\n        :return: Depth of the citation scheme"
  },
  {
    "code": "def add_bid(self, bid):\n        self._bids[bid[0]] = float(bid[1])\n        if bid[1] == \"0.00000000\":\n            del self._bids[bid[0]]",
    "docstring": "Add a bid to the cache\n\n        :param bid:\n        :return:"
  },
  {
    "code": "def rekey(self, key, nonce=None, recovery_key=False):\n        params = {\n            'key': key,\n        }\n        if nonce is not None:\n            params['nonce'] = nonce\n        api_path = '/v1/sys/rekey/update'\n        if recovery_key:\n            api_path = '/v1/sys/rekey-recovery-key/update'\n        response = self._adapter.put(\n            url=api_path,\n            json=params,\n        )\n        return response.json()",
    "docstring": "Enter a single recovery key share to progress the rekey of the Vault.\n\n        If the threshold number of recovery key shares is reached, Vault will complete the rekey. Otherwise, this API\n        must be called multiple times until that threshold is met. The rekey nonce operation must be provided with each\n        call.\n\n        Supported methods:\n            PUT: /sys/rekey/update. Produces: 200 application/json\n            PUT: /sys/rekey-recovery-key/update. Produces: 200 application/json\n\n        :param key: Specifies a single recovery share key.\n        :type key: str | unicode\n        :param nonce: Specifies the nonce of the rekey operation.\n        :type nonce: str | unicode\n        :param recovery_key: If true, send requests to \"rekey-recovery-key\" instead of \"rekey\" api path.\n        :type recovery_key: bool\n        :return: The JSON response of the request.\n        :rtype: dict"
  },
  {
    "code": "def element_data_str(z, eldata):\n    sym = lut.element_sym_from_Z(z, True)\n    cs = contraction_string(eldata)\n    if cs == '':\n        cs = '(no electron shells)'\n    s = '\\nElement: {} : {}\\n'.format(sym, cs)\n    if 'electron_shells' in eldata:\n        for shellidx, shell in enumerate(eldata['electron_shells']):\n            s += electron_shell_str(shell, shellidx) + '\\n'\n    if 'ecp_potentials' in eldata:\n        s += 'ECP: Element: {}   Number of electrons: {}\\n'.format(sym, eldata['ecp_electrons'])\n        for pot in eldata['ecp_potentials']:\n            s += ecp_pot_str(pot) + '\\n'\n    return s",
    "docstring": "Return a string with all data for an element\n\n    This includes shell and ECP potential data\n\n    Parameters\n    ----------\n    z : int or str\n        Element Z-number\n    eldata: dict\n        Data for the element to be printed"
  },
  {
    "code": "def merge_close(events, min_interval, merge_to_longer=False):\n    half_iv = min_interval / 2\n    merged = []\n    for higher in events:\n        if not merged:\n            merged.append(higher)\n        else:\n            lower = merged[-1]\n            if higher['start'] - half_iv <= lower['end'] + half_iv:\n                if merge_to_longer and (higher['end'] - higher['start'] >\n                lower['end'] - lower['start']):\n                    start = min(lower['start'], higher['start'])\n                    higher.update({'start': start})\n                    merged[-1] = higher\n                else:\n                    end = max(lower['end'], higher['end'])\n                    merged[-1].update({'end': end})\n            else:\n                merged.append(higher)\n    return merged",
    "docstring": "Merge events that are separated by a less than a minimum interval.\n\n    Parameters\n    ----------\n    events : list of dict\n        events with 'start' and 'end' times, from one or several channels.\n        **Events must be sorted by their start time.**\n    min_interval : float\n        minimum delay between consecutive events, in seconds\n    merge_to_longer : bool (default: False)\n        If True, info (chan, peak, etc.) from the longer of the 2 events is\n        kept. Otherwise, info from the earlier onset spindle is kept.\n\n    Returns\n    -------\n    list of dict\n        original events list with close events merged."
  },
  {
    "code": "def track_list(self,*args):\r\n        noargs = len(args) == 0\r\n        return np.unique(self.track) if noargs else np.unique(self.track.compress(args[0]))",
    "docstring": "return the list of tracks contained if the dataset"
  },
  {
    "code": "def build_vrt(source_file, destination_file, **kwargs):\n    with rasterio.open(source_file) as src:\n        vrt_doc = boundless_vrt_doc(src, **kwargs).tostring()\n        with open(destination_file, 'wb') as dst:\n            dst.write(vrt_doc)\n    return destination_file",
    "docstring": "Make a VRT XML document and write it in file.\n\n    Parameters\n    ----------\n    source_file : str, file object or pathlib.Path object\n        Source file.\n    destination_file : str\n        Destination file.\n    kwargs : optional\n        Additional arguments passed to rasterio.vrt._boundless_vrt_doc\n\n    Returns\n    -------\n    out : str\n        The path to the destination file."
  },
  {
    "code": "def set_auth_request(self, interface_id, address=None):\n        self.interface.set_auth_request(interface_id, address)\n        self._engine.update()",
    "docstring": "Set the authentication request field for the specified\n        engine."
  },
  {
    "code": "def parse_kegg_gene_metadata(infile):\n    metadata = defaultdict(str)\n    with open(infile) as mf:\n        kegg_parsed = bs_kegg.parse(mf.read())\n    if 'DBLINKS' in kegg_parsed.keys():\n        if 'UniProt' in kegg_parsed['DBLINKS']:\n            unis = str(kegg_parsed['DBLINKS']['UniProt']).split(' ')\n            if isinstance(unis, list):\n                metadata['uniprot'] = unis[0]\n            else:\n                metadata['uniprot'] = unis\n        if 'NCBI-ProteinID' in kegg_parsed['DBLINKS']:\n            metadata['refseq'] = str(kegg_parsed['DBLINKS']['NCBI-ProteinID'])\n    if 'STRUCTURE' in kegg_parsed.keys():\n        metadata['pdbs'] = str(kegg_parsed['STRUCTURE']['PDB']).split(' ')\n    else:\n        metadata['pdbs'] = None\n    if 'ORGANISM' in kegg_parsed.keys():\n        metadata['taxonomy'] = str(kegg_parsed['ORGANISM'])\n    return metadata",
    "docstring": "Parse the KEGG flatfile and return a dictionary of metadata.\n\n    Dictionary keys are:\n        refseq\n        uniprot\n        pdbs\n        taxonomy\n\n    Args:\n        infile: Path to KEGG flatfile\n\n    Returns:\n        dict: Dictionary of metadata"
  },
  {
    "code": "def _int2coord(x, y, dim):\n    assert dim >= 1\n    assert x < dim\n    assert y < dim\n    lng = x / dim * 360 - 180\n    lat = y / dim * 180 - 90\n    return lng, lat",
    "docstring": "Convert x, y values in dim x dim-grid coordinate system into lng, lat values.\n\n    Parameters:\n        x: int        x value of point [0, dim); corresponds to longitude\n        y: int        y value of point [0, dim); corresponds to latitude\n        dim: int      Number of coding points each x, y value can take.\n                      Corresponds to 2^level of the hilbert curve.\n\n    Returns:\n        Tuple[float, float]: (lng, lat)\n            lng    longitude value of coordinate [-180.0, 180.0]; corresponds to X axis\n            lat    latitude value of coordinate [-90.0, 90.0]; corresponds to Y axis"
  },
  {
    "code": "def create_cache_settings(self, \n\t\tservice_id, \n\t\tversion_number, \n\t\tname,\n\t\taction,\n\t\tttl=None,\n\t\tstale_ttl=None,\n\t\tcache_condition=None):\n\t\tbody = self._formdata({\n\t\t\t\"name\": name,\n\t\t\t\"action\": action,\n\t\t\t\"ttl\": ttl,\n\t\t\t\"stale_ttl\": stale_ttl,\n\t\t\t\"cache_condition\": cache_condition,\n\t\t}, FastlyCacheSettings.FIELDS)\n\t\tcontent = self._fetch(\"/service/%s/version/%d/cache_settings\" % (service_id, version_number), method=\"POST\", body=body)\n\t\treturn FastlyCacheSettings(self, content)",
    "docstring": "Create a new cache settings object."
  },
  {
    "code": "def partition(self, ref=None, **kwargs):\n        from ambry.orm.exc import NotFoundError\n        from sqlalchemy.orm.exc import NoResultFound\n        if not ref and not kwargs:\n            return None\n        if ref:\n            for p in self.partitions:\n                if ref == p.name or ref == p.vname or ref == p.vid or ref == p.id:\n                  p._bundle = self\n                  return p\n            raise NotFoundError(\"No partition found for '{}' (a)\".format(ref))\n        elif kwargs:\n            from ..identity import PartitionNameQuery\n            pnq = PartitionNameQuery(**kwargs)\n            try:\n                p = self.partitions._find_orm(pnq).one()\n                if p:\n                    p._bundle = self\n                    return p\n            except NoResultFound:\n                raise NotFoundError(\"No partition found for '{}' (b)\".format(kwargs))",
    "docstring": "Return a partition in this bundle for a vid reference or name parts"
  },
  {
    "code": "def vhat(v1):\n    v1 = stypes.toDoubleVector(v1)\n    vout = stypes.emptyDoubleVector(3)\n    libspice.vhat_c(v1, vout)\n    return stypes.cVectorToPython(vout)",
    "docstring": "Find the unit vector along a double precision 3-dimensional vector.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vhat_c.html\n\n    :param v1: Vector to be unitized. \n    :type v1: 3-Element Array of floats\n    :return: Unit vector v / abs(v).\n    :rtype: 3-Element Array of floats"
  },
  {
    "code": "def qteEmulateKeypresses(self, keysequence):\n        keysequence = QtmacsKeysequence(keysequence)\n        key_list = keysequence.toQKeyEventList()\n        if len(key_list) > 0:\n            for event in key_list:\n                self._qteKeyEmulationQueue.append(event)",
    "docstring": "Emulate the Qt key presses that define ``keysequence``.\n\n        The method will put the keys into a queue and process them one\n        by one once the event loop is idle, ie. the event loop\n        executes all signals and macros associated with the emulated\n        key press first before the next one is emulated.\n\n        |Args|\n\n        * ``keysequence`` (**QtmacsKeysequence**): the key sequence to\n          emulate.\n\n        |Returns|\n\n        * **None**\n\n        |Raises|\n\n        * **QtmacsArgumentError** if at least one argument has an invalid type."
  },
  {
    "code": "def _init_cursor(self):\n        if hasattr(curses, 'noecho'):\n            curses.noecho()\n        if hasattr(curses, 'cbreak'):\n            curses.cbreak()\n        self.set_cursor(0)",
    "docstring": "Init cursors."
  },
  {
    "code": "def calculate_affinity(self, username):\n        scores = self.comparison(username)\n        if len(scores) <= 10:\n            raise NoAffinityError(\"Shared rated anime count between \"\n                                  \"`{}` and `{}` is less than eleven\"\n                                  .format(self._base_user, username))\n        values = scores.values()\n        scores1, scores2 = list(zip(*values))\n        pearson = calcs.pearson(scores1, scores2)\n        pearson *= 100\n        if self._round is not False:\n            pearson = round(pearson, self._round)\n        return models.Affinity(affinity=pearson, shared=len(scores))",
    "docstring": "Get the affinity between the \"base user\" and ``username``.\n\n        .. note:: The data returned will be a namedtuple, with the affinity\n                  and shared rated anime. This can easily be separated\n                  as follows (using the user ``Luna`` as ``username``):\n\n                  .. code-block:: python\n\n                      affinity, shared = ma.calculate_affinity(\"Luna\")\n\n                  Alternatively, the following also works:\n\n                  .. code-block:: python\n\n                      affinity = ma.calculate_affinity(\"Luna\")\n\n                  with the affinity and shared available as\n                  ``affinity.affinity`` and ``affinity.shared`` respectively.\n\n        .. note:: The final affinity value may or may not be rounded,\n                  depending on the value of :attr:`._round`, set at\n                  class initialisation.\n\n        :param str username: The username to calculate affinity with\n        :return: (float affinity, int shared)\n        :rtype: tuple"
  },
  {
    "code": "def _operator_handling(self, cursor):\n        values = self._literal_handling(cursor)\n        retval = ''.join([str(val) for val in values])\n        return retval",
    "docstring": "Returns a string with the literal that are part of the operation."
  },
  {
    "code": "def remove_notes(data):\n    has_text = data.iloc[:, 0].astype(str).str.contains('(?!e-)[a-zA-Z]')\n    text_rows = list(has_text.index[has_text])\n    return data.drop(text_rows)",
    "docstring": "Omit notes from a DataFrame object, where notes are identified as rows with non-numerical entries in the first column.\n\n    :param data: DataFrame object to remove notes from\n    :type data: Pandas.DataFrame\n\n    :return: DataFrame object with no notes\n    :rtype: Pandas.DataFrame"
  },
  {
    "code": "def plot_fit(self, **kwargs):\n        import matplotlib.pyplot as plt\n        import seaborn as sns\n        figsize = kwargs.get('figsize',(10,7))\n        plt.figure(figsize=figsize)\n        date_index = self.index[self.ar:self.data.shape[0]]\n        mu, Y = self._model(self.latent_variables.get_z_values())\n        plt.plot(date_index,Y,label='Data')\n        plt.plot(date_index,mu,label='Filter',c='black')\n        plt.title(self.data_name)\n        plt.legend(loc=2)   \n        plt.show()",
    "docstring": "Plots the fit of the model against the data"
  },
  {
    "code": "def add(self, opener):\n        index = len(self.openers)\n        self.openers[index] = opener\n        for name in opener.names:\n            self.registry[name] = index",
    "docstring": "Adds an opener to the registry\n\n        :param opener: Opener object\n        :type opener: Opener inherited object"
  },
  {
    "code": "def _setSampleSizeBytes(self):\n        self.sampleSizeBytes = self.getPacketSize()\n        if self.sampleSizeBytes > 0:\n            self.maxBytesPerFifoRead = (32 // self.sampleSizeBytes)",
    "docstring": "updates the current record of the packet size per sample and the relationship between this and the fifo reads."
  },
  {
    "code": "def is_null(*symbols):\n    from symbols.symbol_ import Symbol\n    for sym in symbols:\n        if sym is None:\n            continue\n        if not isinstance(sym, Symbol):\n            return False\n        if sym.token == 'NOP':\n            continue\n        if sym.token == 'BLOCK':\n            if not is_null(*sym.children):\n                return False\n            continue\n        return False\n    return True",
    "docstring": "True if no nodes or all the given nodes are either\n    None, NOP or empty blocks. For blocks this applies recursively"
  },
  {
    "code": "def dumps(self):\n        old_stream = self.stream\n        try:\n            self.stream = six.StringIO()\n            self.write_table()\n            tabular_text = self.stream.getvalue()\n        finally:\n            self.stream = old_stream\n        return tabular_text",
    "docstring": "Get rendered tabular text from the table data.\n\n        Only available for text format table writers.\n\n        Returns:\n            str: Rendered tabular text."
  },
  {
    "code": "def list(ctx, show_hidden, oath_type, period):\n    ensure_validated(ctx)\n    controller = ctx.obj['controller']\n    creds = [cred\n             for cred in controller.list()\n             if show_hidden or not cred.is_hidden\n             ]\n    creds.sort()\n    for cred in creds:\n        click.echo(cred.printable_key, nl=False)\n        if oath_type:\n            click.echo(u', {}'.format(cred.oath_type.name), nl=False)\n        if period:\n            click.echo(', {}'.format(cred.period), nl=False)\n        click.echo()",
    "docstring": "List all credentials.\n\n    List all credentials stored on your YubiKey."
  },
  {
    "code": "def result(retn):\n    ok, valu = retn\n    if ok:\n        return valu\n    name, info = valu\n    ctor = getattr(s_exc, name, None)\n    if ctor is not None:\n        raise ctor(**info)\n    info['errx'] = name\n    raise s_exc.SynErr(**info)",
    "docstring": "Return a value or raise an exception from a retn tuple."
  },
  {
    "code": "def from_scanner(self, x, y, z):\n        if self.transform is None:\n            raise ValueError(\"No transform set for MRSData object {}\".format(self))\n        transformed_point = numpy.linalg.inv(self.transform) * numpy.matrix([x, y, z, 1]).T\n        return numpy.squeeze(numpy.asarray(transformed_point))[0:3]",
    "docstring": "Converts a 3d position in the scanner reference frame to the MRSData space\n\n        :param x:\n        :param y:\n        :param z:\n        :return:"
  },
  {
    "code": "def create_heroku_connect_schema(using=DEFAULT_DB_ALIAS):\n    connection = connections[using]\n    with connection.cursor() as cursor:\n        cursor.execute(_SCHEMA_EXISTS_QUERY, [settings.HEROKU_CONNECT_SCHEMA])\n        schema_exists = cursor.fetchone()[0]\n        if schema_exists:\n            return False\n        cursor.execute(\"CREATE SCHEMA %s;\", [AsIs(settings.HEROKU_CONNECT_SCHEMA)])\n    with connection.schema_editor() as editor:\n        for model in get_heroku_connect_models():\n            editor.create_model(model)\n        editor.execute('CREATE EXTENSION IF NOT EXISTS \"hstore\";')\n        from heroku_connect.models import (TriggerLog, TriggerLogArchive)\n        for cls in [TriggerLog, TriggerLogArchive]:\n            editor.create_model(cls)\n    return True",
    "docstring": "Create Heroku Connect schema.\n\n    Note:\n        This function is only meant to be used for local development.\n        In a production environment the schema will be created by\n        Heroku Connect.\n\n    Args:\n        using (str): Alias for database connection.\n\n    Returns:\n        bool: ``True`` if the schema was created, ``False`` if the\n            schema already exists."
  },
  {
    "code": "def _proc_cyclic(self):\n        main_axis, rot = max(self.rot_sym, key=lambda v: v[1])\n        self.sch_symbol = \"C{}\".format(rot)\n        mirror_type = self._find_mirror(main_axis)\n        if mirror_type == \"h\":\n            self.sch_symbol += \"h\"\n        elif mirror_type == \"v\":\n            self.sch_symbol += \"v\"\n        elif mirror_type == \"\":\n            if self.is_valid_op(SymmOp.rotoreflection(main_axis,\n                                                      angle=180 / rot)):\n                self.sch_symbol = \"S{}\".format(2 * rot)",
    "docstring": "Handles cyclic group molecules."
  },
  {
    "code": "def matching(self, packages):\n        print(\"\\nNot found package with the name [ {0}{1}{2} ]. \"\n              \"Matching packages:\\nNOTE: Not dependenc\"\n              \"ies are resolved\\n\".format(self.meta.color[\"CYAN\"],\n                                          \"\".join(packages),\n                                          self.meta.color[\"ENDC\"]))",
    "docstring": "Message for matching packages"
  },
  {
    "code": "def _client_allowed(self):\n    client_ip = self._client_address[0]\n    if not client_ip in self._settings.allowed_clients and \\\n       not 'ALL' in self._settings.allowed_clients:\n      content = 'Access from host {} forbidden.'.format(client_ip).encode('utf-8')\n      self._send_content(content, 'text/html')\n      return False\n    return True",
    "docstring": "Check if client is allowed to connect to this server."
  },
  {
    "code": "def com_google_fonts_check_metadata_subsets_order(family_metadata):\n  expected = list(sorted(family_metadata.subsets))\n  if list(family_metadata.subsets) != expected:\n    yield FAIL, (\"METADATA.pb subsets are not sorted \"\n                 \"in alphabetical order: Got ['{}']\"\n                 \" and expected ['{}']\").format(\"', '\".join(family_metadata.subsets),\n                                                \"', '\".join(expected))\n  else:\n    yield PASS, \"METADATA.pb subsets are sorted in alphabetical order.\"",
    "docstring": "METADATA.pb subsets should be alphabetically ordered."
  },
  {
    "code": "def get_decision_trees_bulk(self, payload, version=DEFAULT_DECISION_TREE_VERSION):\n    headers = self._headers.copy()\n    headers[\"x-craft-ai-tree-version\"] = version\n    valid_indices, invalid_indices, invalid_dts = self._check_agent_id_bulk(payload)\n    if self._config[\"decisionTreeRetrievalTimeout\"] is False:\n      return self._get_decision_trees_bulk(payload,\n                                           valid_indices,\n                                           invalid_indices,\n                                           invalid_dts)\n    start = current_time_ms()\n    while True:\n      now = current_time_ms()\n      if now - start > self._config[\"decisionTreeRetrievalTimeout\"]:\n        raise CraftAiLongRequestTimeOutError()\n      try:\n        return self._get_decision_trees_bulk(payload,\n                                             valid_indices,\n                                             invalid_indices,\n                                             invalid_dts)\n      except CraftAiLongRequestTimeOutError:\n        continue",
    "docstring": "Get a group of decision trees.\n\n    :param list payload: contains the informations necessary for getting\n    the trees. It's in the form [{\"id\": agent_id, \"timestamp\": timestamp}]\n    With id a str containing only characters in \"a-zA-Z0-9_-\" and must be\n    between 1 and 36 characters. It must referenced an existing agent.\n    With timestamp an positive and not null integer.\n    :param version: version of the tree to get.\n    :type version: str or int.\n    :default version: default version of the tree.\n\n    :return: Decision trees.\n    :rtype: list of dict.\n\n    :raises CraftAiBadRequestError: if all of the ids are invalid or\n    referenced non existing agents or all of the timestamp are invalid.\n    :raises CraftAiLongRequestTimeOutError: if the API doesn't get\n    the tree in the time given by the configuration."
  },
  {
    "code": "def vectors(self, failed=False):\n        if failed not in [\"all\", False, True]:\n            raise ValueError(\"{} is not a valid vector failed\".format(failed))\n        if failed == \"all\":\n            return Vector.query.filter_by(network_id=self.id).all()\n        else:\n            return Vector.query.filter_by(network_id=self.id, failed=failed).all()",
    "docstring": "Get vectors in the network.\n\n        failed = { False, True, \"all\" }\n        To get the vectors to/from to a specific node, see Node.vectors()."
  },
  {
    "code": "def alive(opts):\n    dev = conn()\n    thisproxy['conn'].connected = ping()\n    if not dev.connected:\n        __salt__['event.fire_master']({}, 'junos/proxy/{}/stop'.format(\n            opts['proxy']['host']))\n    return dev.connected",
    "docstring": "Validate and return the connection status with the remote device.\n\n    .. versionadded:: 2018.3.0"
  },
  {
    "code": "def sam_list_paired(sam):\n\tlist = []\n\tpair = ['1', '2']\n\tprev = ''\n\tfor file in sam:\n\t\tfor line in file:\n\t\t\tif line.startswith('@') is False:\n\t\t\t\tline = line.strip().split()\n\t\t\t\tid, map = line[0], int(line[1])\n\t\t\t\tif map != 4 and map != 8:\n\t\t\t\t\tread = id.rsplit('/')[0]\n\t\t\t\t\tif read == prev:\n\t\t\t\t\t\tlist.append(read)\n\t\t\t\t\tprev = read\n\treturn set(list)",
    "docstring": "get a list of mapped reads\n\trequire that both pairs are mapped in the sam file in order to remove the reads"
  },
  {
    "code": "def publish(self, message):\n        message_data = self._to_data(message)\n        self._encode_invoke(topic_publish_codec, message=message_data)",
    "docstring": "Publishes the message to all subscribers of this topic\n\n        :param message: (object), the message to be published."
  },
  {
    "code": "def cleanTempDirs(job):\n    if job is CWLJob and job._succeeded:\n        for tempDir in job.openTempDirs:\n            if os.path.exists(tempDir):\n                shutil.rmtree(tempDir)\n        job.openTempDirs = []",
    "docstring": "Remove temporarly created directories."
  },
  {
    "code": "def _parse_pg_lscluster(output):\n    cluster_dict = {}\n    for line in output.splitlines():\n        version, name, port, status, user, datadir, log = (\n            line.split())\n        cluster_dict['{0}/{1}'.format(version, name)] = {\n            'port': int(port),\n            'status': status,\n            'user': user,\n            'datadir': datadir,\n            'log': log}\n    return cluster_dict",
    "docstring": "Helper function to parse the output of pg_lscluster"
  },
  {
    "code": "def ensure_permissions(path, user, group, permissions, maxdepth=-1):\n    if not os.path.exists(path):\n        log(\"File '%s' does not exist - cannot set permissions\" % (path),\n            level=WARNING)\n        return\n    _user = pwd.getpwnam(user)\n    os.chown(path, _user.pw_uid, grp.getgrnam(group).gr_gid)\n    os.chmod(path, permissions)\n    if maxdepth == 0:\n        log(\"Max recursion depth reached - skipping further recursion\",\n            level=DEBUG)\n        return\n    elif maxdepth > 0:\n        maxdepth -= 1\n    if os.path.isdir(path):\n        contents = glob.glob(\"%s/*\" % (path))\n        for c in contents:\n            ensure_permissions(c, user=user, group=group,\n                               permissions=permissions, maxdepth=maxdepth)",
    "docstring": "Ensure permissions for path.\n\n    If path is a file, apply to file and return. If path is a directory,\n    apply recursively (if required) to directory contents and return.\n\n    :param user: user name\n    :param group: group name\n    :param permissions: octal permissions\n    :param maxdepth: maximum recursion depth. A negative maxdepth allows\n                     infinite recursion and maxdepth=0 means no recursion.\n    :returns: None"
  },
  {
    "code": "def _handle_delete_file(self, data):\n        file = self.room.filedict.get(data)\n        if file:\n            self.room.filedict = data, None\n            self.conn.enqueue_data(\"delete_file\", file)",
    "docstring": "Handle files being removed"
  },
  {
    "code": "def previous_layout(pymux, variables):\n    \" Select previous layout. \"\n    pane = pymux.arrangement.get_active_window()\n    if pane:\n        pane.select_previous_layout()",
    "docstring": "Select previous layout."
  },
  {
    "code": "def samefile(a: str, b: str) -> bool:\n    try:\n        return os.path.samefile(a, b)\n    except OSError:\n        return os.path.normpath(a) == os.path.normpath(b)",
    "docstring": "Check if two pathes represent the same file."
  },
  {
    "code": "def _create_tmp_file(config):\n        tmp_dir = tempfile.gettempdir()\n        rand_fname = py23_compat.text_type(uuid.uuid4())\n        filename = os.path.join(tmp_dir, rand_fname)\n        with open(filename, 'wt') as fobj:\n            fobj.write(config)\n        return filename",
    "docstring": "Write temp file and for use with inline config and SCP."
  },
  {
    "code": "def create(verbose):\n    click.secho('Creating all tables!', fg='yellow', bold=True)\n    with click.progressbar(_db.metadata.sorted_tables) as bar:\n        for table in bar:\n            if verbose:\n                click.echo(' Creating table {0}'.format(table))\n            table.create(bind=_db.engine, checkfirst=True)\n    create_alembic_version_table()\n    click.secho('Created all tables!', fg='green')",
    "docstring": "Create tables."
  },
  {
    "code": "def data(self):\n        for pkg in self.installed:\n            if os.path.isfile(self.meta.pkg_path + pkg):\n                name = split_package(pkg)[0]\n                for log in self.logs:\n                    deps = Utils().read_file(self.dep_path + log)\n                    for dep in deps.splitlines():\n                        if name == dep:\n                            if name not in self.dmap.keys():\n                                self.dmap[name] = [log]\n                                if not self.count_pkg:\n                                    self.count_pkg = 1\n                            else:\n                                self.dmap[name] += [log]\n        self.count_packages()",
    "docstring": "Check all installed packages and create\n        dictionary database"
  },
  {
    "code": "def _GetPathSegmentIndexForOccurrenceWeights(\n      self, occurrence_weights, value_weights):\n    largest_weight = occurrence_weights.GetLargestWeight()\n    if largest_weight > 0:\n      occurrence_weight_indexes = occurrence_weights.GetIndexesForWeight(\n          largest_weight)\n      number_of_occurrence_indexes = len(occurrence_weight_indexes)\n    else:\n      number_of_occurrence_indexes = 0\n    path_segment_index = None\n    if number_of_occurrence_indexes == 0:\n      path_segment_index = self._GetPathSegmentIndexForValueWeights(\n          value_weights)\n    elif number_of_occurrence_indexes == 1:\n      path_segment_index = occurrence_weight_indexes[0]\n    else:\n      largest_weight = 0\n      for occurrence_index in occurrence_weight_indexes:\n        value_weight = value_weights.GetWeightForIndex(occurrence_index)\n        if not path_segment_index or largest_weight < value_weight:\n          largest_weight = value_weight\n          path_segment_index = occurrence_index\n    return path_segment_index",
    "docstring": "Retrieves the index of the path segment based on occurrence weights.\n\n    Args:\n      occurrence_weights: the occurrence weights object (instance of\n                          _PathSegmentWeights).\n      value_weights: the value weights object (instance of _PathSegmentWeights).\n\n    Returns:\n      An integer containing the path segment index."
  },
  {
    "code": "def get_algorithm_config(xs):\n    if isinstance(xs, dict):\n        xs = [xs]\n    for x in xs:\n        if is_std_config_arg(x):\n            return x[\"algorithm\"]\n        elif is_nested_config_arg(x):\n            return x[\"config\"][\"algorithm\"]\n        elif isinstance(x, (list, tuple)) and is_nested_config_arg(x[0]):\n            return x[0][\"config\"][\"algorithm\"]\n    raise ValueError(\"Did not find algorithm configuration in items: {0}\"\n                     .format(pprint.pformat(xs)))",
    "docstring": "Flexibly extract algorithm configuration for a sample from any function arguments."
  },
  {
    "code": "def file_crc32(filename, chunksize=_CHUNKSIZE):\n    check = 0\n    with open(filename, 'rb') as fd:\n        for data in iter(lambda: fd.read(chunksize), \"\"):\n            check = crc32(data, check)\n    return check",
    "docstring": "calculate the CRC32 of the contents of filename"
  },
  {
    "code": "def _ancestors_or_self(\n            self, qname: Union[QualName, bool] = None) -> List[InstanceNode]:\n        res = [] if qname and self.qual_name != qname else [self]\n        return res + self.up()._ancestors(qname)",
    "docstring": "XPath - return the list of receiver's ancestors including itself."
  },
  {
    "code": "def make_workspace(measurement, channel=None, name=None, silence=False):\n    context = silence_sout_serr if silence else do_nothing\n    with context():\n        hist2workspace = ROOT.RooStats.HistFactory.HistoToWorkspaceFactoryFast(\n            measurement)\n        if channel is not None:\n            workspace = hist2workspace.MakeSingleChannelModel(\n                measurement, channel)\n        else:\n            workspace = hist2workspace.MakeCombinedModel(measurement)\n    workspace = asrootpy(workspace)\n    keepalive(workspace, measurement)\n    if name is not None:\n        workspace.SetName('workspace_{0}'.format(name))\n    return workspace",
    "docstring": "Create a workspace containing the model for a measurement\n\n    If `channel` is None then include all channels in the model\n\n    If `silence` is True, then silence HistFactory's output on\n    stdout and stderr."
  },
  {
    "code": "def thread_stopped(self):\n\t\tif self.__task is not None:\n\t\t\tif self.__task.stop_event().is_set() is False:\n\t\t\t\tself.__task.stop()\n\t\t\tself.__task = None",
    "docstring": "Stop scheduled task beacuse of watchdog stop\n\n\t\t:return: None"
  },
  {
    "code": "def get_boxes_and_lines(ax, labels):\n    labels_u, labels_u_line = get_labels(labels)\n    boxes = ax.findobj(mpl.text.Annotation)\n    lines = ax.findobj(mpl.lines.Line2D)\n    lineid_boxes = []\n    lineid_lines = []\n    for box in boxes:\n        l = box.get_label()\n        try:\n            loc = labels_u.index(l)\n        except ValueError:\n            continue\n        lineid_boxes.append(box)\n    for line in lines:\n        l = line.get_label()\n        try:\n            loc = labels_u_line.index(l)\n        except ValueError:\n            continue\n        lineid_lines.append(line)\n    return lineid_boxes, lineid_lines",
    "docstring": "Get boxes and lines using labels as id."
  },
  {
    "code": "def encode(self, cube_dimensions):\n        return np.asarray([getattr(cube_dimensions[d], s)\n            for d in self._dimensions\n            for s in self._schema],\n                dtype=np.int32)",
    "docstring": "Produces a numpy array of integers which encode\n        the supplied cube dimensions."
  },
  {
    "code": "def process_exception(self, request, exception):\n        log_format = self._get_log_format(request)\n        if log_format is None:\n            return\n        params = self._get_parameters_from_request(request, True)\n        params['message'] = exception\n        params['http_status'] = '-'\n        self.OPERATION_LOG.info(log_format, params)",
    "docstring": "Log error info when exception occurred."
  },
  {
    "code": "def show_instances(server, cim_class):\n    if cim_class == 'CIM_RegisteredProfile':\n        for inst in server.profiles:\n            print(inst.tomof())\n        return\n    for ns in server.namespaces:\n        try:\n            insts = server.conn.EnumerateInstances(cim_class, namespace=ns)\n            if len(insts):\n                print('INSTANCES OF %s ns=%s' % (cim_class, ns))\n                for inst in insts:\n                    print(inst.tomof())\n        except pywbem.Error as er:\n            if er.status_code != pywbem.CIM_ERR_INVALID_CLASS:\n                print('%s namespace %s Enumerate failed for conn=%s\\n'\n                      'exception=%s'\n                      % (cim_class, ns, server, er))",
    "docstring": "Display the instances of the CIM_Class defined by cim_class. If the\n    namespace is None, use the interop namespace. Search all namespaces for\n    instances except for CIM_RegisteredProfile"
  },
  {
    "code": "def authorize(login, password, scopes, note='', note_url='', client_id='',\n              client_secret='', two_factor_callback=None):\n    gh = GitHub()\n    gh.login(two_factor_callback=two_factor_callback)\n    return gh.authorize(login, password, scopes, note, note_url, client_id,\n                        client_secret)",
    "docstring": "Obtain an authorization token for the GitHub API.\n\n    :param str login: (required)\n    :param str password: (required)\n    :param list scopes: (required), areas you want this token to apply to,\n        i.e., 'gist', 'user'\n    :param str note: (optional), note about the authorization\n    :param str note_url: (optional), url for the application\n    :param str client_id: (optional), 20 character OAuth client key for which\n        to create a token\n    :param str client_secret: (optional), 40 character OAuth client secret for\n        which to create the token\n    :param func two_factor_callback: (optional), function to call when a\n        Two-Factor Authentication code needs to be provided by the user.\n    :returns: :class:`Authorization <Authorization>`"
  },
  {
    "code": "def _set_subset_indices(self, y_min, y_max, x_min, x_max):\n        y_coords, x_coords = self.xd.lsm.coords\n        dx = self.xd.lsm.dx\n        dy = self.xd.lsm.dy\n        lsm_y_indices_from_y, lsm_x_indices_from_y = \\\n            np.where((y_coords >= (y_min - 2*dy)) &\n                     (y_coords <= (y_max + 2*dy)))\n        lsm_y_indices_from_x, lsm_x_indices_from_x = \\\n            np.where((x_coords >= (x_min - 2*dx)) &\n                     (x_coords <= (x_max + 2*dx)))\n        lsm_y_indices = np.intersect1d(lsm_y_indices_from_y,\n                                       lsm_y_indices_from_x)\n        lsm_x_indices = np.intersect1d(lsm_x_indices_from_y,\n                                       lsm_x_indices_from_x)\n        self.xslice = slice(np.amin(lsm_x_indices),\n                            np.amax(lsm_x_indices)+1)\n        self.yslice = slice(np.amin(lsm_y_indices),\n                            np.amax(lsm_y_indices)+1)",
    "docstring": "load subset based on extent"
  },
  {
    "code": "def deduce_helpful_msg(req):\n    msg = \"\"\n    if os.path.exists(req):\n        msg = \" It does exist.\"\n        try:\n            with open(req, 'r') as fp:\n                next(parse_requirements(fp.read()))\n                msg += \" The argument you provided \" + \\\n                    \"(%s) appears to be a\" % (req) + \\\n                    \" requirements file. If that is the\" + \\\n                    \" case, use the '-r' flag to install\" + \\\n                    \" the packages specified within it.\"\n        except RequirementParseError:\n            logger.debug(\"Cannot parse '%s' as requirements \\\n            file\" % (req), exc_info=True)\n    else:\n        msg += \" File '%s' does not exist.\" % (req)\n    return msg",
    "docstring": "Returns helpful msg in case requirements file does not exist,\n    or cannot be parsed.\n\n    :params req: Requirements file path"
  },
  {
    "code": "def _register_opt(parser, *args, **kwargs):\n        try:\n            parser.add_option(*args, **kwargs)\n        except (optparse.OptionError, TypeError):\n            parse_from_config = kwargs.pop('parse_from_config', False)\n            option = parser.add_option(*args, **kwargs)\n            if parse_from_config:\n                parser.config_options.append(option.get_opt_string().lstrip('-'))",
    "docstring": "Handler to register an option for both Flake8 3.x and 2.x.\n\n        This is based on:\n        https://github.com/PyCQA/flake8/blob/3.0.0b2/docs/source/plugin-development/cross-compatibility.rst#option-handling-on-flake8-2-and-3\n\n        It only supports `parse_from_config` from the original function and it\n        uses the `Option` object returned to get the string."
  },
  {
    "code": "def get_path_modified_time(path):\n        return float(foundations.common.get_first_item(str(os.path.getmtime(path)).split(\".\")))",
    "docstring": "Returns given path modification time.\n\n        :param path: Path.\n        :type path: unicode\n        :return: Modification time.\n        :rtype: int"
  },
  {
    "code": "def chmod(path, mode, recursive=False):\n    log = logging.getLogger(mod_logger + '.chmod')\n    if not isinstance(path, basestring):\n        msg = 'path argument is not a string'\n        log.error(msg)\n        raise CommandError(msg)\n    if not isinstance(mode, basestring):\n        msg = 'mode argument is not a string'\n        log.error(msg)\n        raise CommandError(msg)\n    if not os.path.exists(path):\n        msg = 'Item not found: {p}'.format(p=path)\n        log.error(msg)\n        raise CommandError(msg)\n    command = ['chmod']\n    if recursive:\n        command.append('-R')\n    command.append(mode)\n    command.append(path)\n    try:\n        result = run_command(command)\n    except CommandError:\n        raise\n    log.info('chmod command exited with code: {c}'.format(c=result['code']))\n    return result['code']",
    "docstring": "Emulates bash chmod command\n\n    This method sets the file permissions to the specified mode.\n\n    :param path: (str) Full path to the file or directory\n    :param mode: (str) Mode to be set (e.g. 0755)\n    :param recursive: (bool) Set True to make a recursive call\n    :return: int exit code of the chmod command\n    :raises CommandError"
  },
  {
    "code": "def areas_of_code(git_enrich, in_conn, out_conn, block_size=100):\n    aoc = AreasOfCode(in_connector=in_conn, out_connector=out_conn, block_size=block_size,\n                      git_enrich=git_enrich)\n    ndocs = aoc.analyze()\n    return ndocs",
    "docstring": "Build and index for areas of code from a given Perceval RAW index.\n\n    :param block_size: size of items block.\n    :param git_enrich: GitEnrich object to deal with SortingHat affiliations.\n    :param in_conn: ESPandasConnector to read from.\n    :param out_conn: ESPandasConnector to write to.\n    :return: number of documents written in ElasticSearch enriched index."
  },
  {
    "code": "def range_as_mono(self, start_sample, end_sample):\n        tmp_current = self.current_frame\n        self.current_frame = start_sample\n        tmp_frames = self.read_frames(end_sample - start_sample)\n        if self.channels == 2:\n            frames = np.mean(tmp_frames, axis=1)\n        elif self.channels == 1:\n            frames = tmp_frames\n        else:\n            raise IOError(\"Input audio must have either 1 or 2 channels\")\n        self.current_frame = tmp_current\n        return frames",
    "docstring": "Get a range of frames as 1 combined channel\n\n        :param integer start_sample: First frame in range\n        :param integer end_sample: Last frame in range (exclusive)\n        :returns: Track frames in range as 1 combined channel\n        :rtype: 1d numpy array of length ``end_sample - start_sample``"
  },
  {
    "code": "def get_contact(self, email):\n        contacts = self.get_contacts()\n        for contact in contacts:\n            if contact['email'] == email:\n                return contact\n        msg = 'No contact with email: \"{email}\" found.'\n        raise FMBaseError(msg.format(email=email))",
    "docstring": "Get Filemail contact based on email.\n\n        :param email: address of contact\n        :type email: ``str``, ``unicode``\n        :rtype: ``dict`` with contact information"
  },
  {
    "code": "def sasqc(self) -> 'SASqc':\n        if not self._loaded_macros:\n            self._loadmacros()\n            self._loaded_macros = True\n        return SASqc(self)",
    "docstring": "This methods creates a SASqc object which you can use to run various analytics. See the sasqc.py module.\n\n        :return: sasqc object"
  },
  {
    "code": "def get_field_visibility_mode(self, field):\n        fallback_mode = (\"hidden\", \"hidden\")\n        widget = field.widget\n        layout = widget.isVisible(self.context, \"header_table\")\n        if layout in [\"invisible\", \"hidden\"]:\n            return fallback_mode\n        if field.checkPermission(\"edit\", self.context):\n            mode = \"edit\"\n            sm = getSecurityManager()\n            if not sm.checkPermission(ModifyPortalContent, self.context):\n                logger.warn(\"Permission '{}' granted for the edition of '{}', \"\n                            \"but 'Modify portal content' not granted\"\n                            .format(field.write_permission, field.getName()))\n        elif field.checkPermission(\"view\", self.context):\n            mode = \"view\"\n        else:\n            return fallback_mode\n        if widget.isVisible(self.context, mode, field=field) != \"visible\":\n            if mode == \"view\":\n                return fallback_mode\n            mode = \"view\"\n            if widget.isVisible(self.context, mode, field=field) != \"visible\":\n                return fallback_mode\n        return (mode, layout)",
    "docstring": "Returns \"view\" or \"edit\" modes, together with the place within where\n        this field has to be rendered, based on the permissions the current\n        user has for the context and the field passed in"
  },
  {
    "code": "def fields_equal(self, instance, fields_to_ignore=(\"id\", \"change_date\", \"changed_by\")):\n        for field in self._meta.get_fields():\n            if not field.many_to_many and field.name not in fields_to_ignore:\n                if getattr(instance, field.name) != getattr(self, field.name):\n                    return False\n        return True",
    "docstring": "Compares this instance's fields to the supplied instance to test for equality.\n        This will ignore any fields in `fields_to_ignore`.\n\n        Note that this method ignores many-to-many fields.\n\n        Args:\n            instance: the model instance to compare\n            fields_to_ignore: List of fields that should not be compared for equality. By default\n            includes `id`, `change_date`, and `changed_by`.\n\n        Returns: True if the checked fields are all equivalent, else False"
  },
  {
    "code": "def transform_request(self, orig_request, params, method_config):\n    method_params = method_config.get('request', {}).get('parameters', {})\n    request = self.transform_rest_request(orig_request, params, method_params)\n    request.path = method_config.get('rosyMethod', '')\n    return request",
    "docstring": "Transforms orig_request to apiserving request.\n\n    This method uses orig_request to determine the currently-pending request\n    and returns a new transformed request ready to send to the backend.  This\n    method accepts a rest-style or RPC-style request.\n\n    Args:\n      orig_request: An ApiRequest, the original request from the user.\n      params: A dictionary containing path parameters for rest requests, or\n        None for an RPC request.\n      method_config: A dict, the API config of the method to be called.\n\n    Returns:\n      An ApiRequest that's a copy of the current request, modified so it can\n      be sent to the backend.  The path is updated and parts of the body or\n      other properties may also be changed."
  },
  {
    "code": "def _headers(self, **kwargs):\n        headers = BASE_HEADERS.copy()\n        if self._token:\n            headers['X-Plex-Token'] = self._token\n        headers.update(kwargs)\n        return headers",
    "docstring": "Returns dict containing base headers for all requests to the server."
  },
  {
    "code": "def is_topic_tail(self):\n        return self.topic.last_post.id == self.id if self.topic.last_post else False",
    "docstring": "Returns ``True`` if the post is the last post of the topic."
  },
  {
    "code": "def plot_time_series(sdat, lovs):\n    sovs = misc.set_of_vars(lovs)\n    tseries = {}\n    times = {}\n    metas = {}\n    for tvar in sovs:\n        series, time, meta = get_time_series(\n            sdat, tvar, conf.time.tstart, conf.time.tend)\n        tseries[tvar] = series\n        metas[tvar] = meta\n        if time is not None:\n            times[tvar] = time\n    tseries['t'] = get_time_series(\n        sdat, 't', conf.time.tstart, conf.time.tend)[0]\n    _plot_time_list(sdat, lovs, tseries, metas, times)",
    "docstring": "Plot requested time series.\n\n    Args:\n        sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.\n        lovs (nested list of str): nested list of series names such as\n            the one produced by :func:`stagpy.misc.list_of_vars`.\n\n    Other Parameters:\n        conf.time.tstart: the starting time.\n        conf.time.tend: the ending time."
  },
  {
    "code": "def det_optimal_snrsq(self, det):\n        try:\n            return getattr(self._current_stats, '{}_optimal_snrsq'.format(det))\n        except AttributeError:\n            self._loglr()\n            return getattr(self._current_stats, '{}_optimal_snrsq'.format(det))",
    "docstring": "Returns the opitmal SNR squared in the given detector.\n\n        Parameters\n        ----------\n        det : str\n            The name of the detector.\n\n        Returns\n        -------\n        float :\n            The opimtal SNR squared."
  },
  {
    "code": "def send_figure(self, fig, caption=''):\n        if not self.is_token_set:\n            raise ValueError('TelepythClient: Access token is not set!')\n        figure = BytesIO()\n        fig.savefig(figure, format='png')\n        figure.seek(0)\n        parts = [ContentDisposition('caption', caption),\n                 ContentDisposition('figure', figure, filename=\"figure.png\",\n                                    content_type='image/png')]\n        form = MultipartFormData(*parts)\n        content_type = 'multipart/form-data; boundary=%s' % form.boundary\n        url = self.base_url + self.access_token\n        req = Request(url, method='POST')\n        req.add_header('Content-Type', content_type)\n        req.add_header('User-Agent', __user_agent__ + '/' + __version__)\n        req.data = form().read()\n        res = urlopen(req)\n        return res.getcode()",
    "docstring": "Render matplotlib figure into temporary bytes buffer and then send\n        it to telegram user.\n\n        :param fig: matplotlib figure object.\n        :param caption: text caption of picture.\n        :return: status code on error."
  },
  {
    "code": "def is_in_file_tree(fpath, folder):\n    file_folder, _ = os.path.split(fpath)\n    other_folder = os.path.join(folder, \"\")\n    return other_folder.startswith(file_folder)",
    "docstring": "Determine whether a file is in a folder.\n\n    :param str fpath: filepath to investigate\n    :param folder: path to folder to query\n    :return bool: whether the path indicated is in the folder indicated"
  },
  {
    "code": "def retrier(*, max_attempts, sleeptime, max_sleeptime, sleepscale=1.5, jitter=0.2):\n  assert(max_attempts > 1)\n  assert(sleeptime >= 0)\n  assert(0 <= jitter <= sleeptime)\n  assert(sleepscale >= 1)\n  cur_sleeptime = min(max_sleeptime, sleeptime)\n  for attempt in range(max_attempts):\n    cur_jitter = random.randint(int(-jitter * 1000), int(jitter * 1000)) / 1000\n    yield max(0, cur_sleeptime + cur_jitter)\n    cur_sleeptime = min(max_sleeptime, cur_sleeptime * sleepscale)",
    "docstring": "Generator yielding time to wait for, after the attempt, if it failed."
  },
  {
    "code": "def changed(self, src, path, dest):\n        try:\n            mtime = os.path.getmtime(os.path.join(src, path))\n            self._build(src, path, dest, mtime)\n        except EnvironmentError as e:\n            logging.error(\"{0} is inaccessible: {1}\".format(\n                termcolor.colored(path, \"yellow\", attrs=[\"bold\"]),\n                e.args[0]\n            ))",
    "docstring": "Called whenever `path` is changed in the source folder `src`. `dest`\n        is the output folder. The default implementation calls `build` after\n        determining that the input file is newer than any of the outputs, or\n        any of the outputs does not exist."
  },
  {
    "code": "def _POUpdateBuilderWrapper(env, target=None, source=_null, **kw):\n  if source is _null:\n    if 'POTDOMAIN' in kw:\n      domain = kw['POTDOMAIN']\n    elif 'POTDOMAIN' in env and env['POTDOMAIN']:\n      domain = env['POTDOMAIN']\n    else:\n      domain = 'messages'\n    source = [ domain ]\n  return env._POUpdateBuilder(target, source, **kw)",
    "docstring": "Wrapper for `POUpdate` builder - make user's life easier"
  },
  {
    "code": "def _report_line_to_dict(cls, line):\n        data = line.split('\\t')\n        if len(data) != len(report.columns):\n            return None\n        d = dict(zip(report.columns, data))\n        for key in report.int_columns:\n            try:\n                d[key] = int(d[key])\n            except:\n                assert d[key] == '.'\n        for key in report.float_columns:\n            try:\n                d[key] = float(d[key])\n            except:\n                assert d[key] == '.'\n        d['flag'] = flag.Flag(int(d['flag']))\n        return d",
    "docstring": "Takes report line string as input. Returns a dict of column name -> value in line"
  },
  {
    "code": "def _get_id_token_user(token, issuers, audiences, allowed_client_ids, time_now, cache):\n  for issuer_key, issuer in issuers.items():\n    issuer_cert_uri = convert_jwks_uri(issuer.jwks_uri)\n    try:\n      parsed_token = _verify_signed_jwt_with_certs(\n          token, time_now, cache, cert_uri=issuer_cert_uri)\n    except Exception:\n      _logger.debug(\n          'id_token verification failed for issuer %s', issuer_key, exc_info=True)\n      continue\n    issuer_values = _listlike_guard(issuer.issuer, 'issuer', log_warning=False)\n    if isinstance(audiences, _Mapping):\n      audiences = audiences[issuer_key]\n    if _verify_parsed_token(\n        parsed_token, issuer_values, audiences, allowed_client_ids,\n        is_legacy_google_auth=(issuer.issuer == _ISSUERS)):\n      email = parsed_token['email']\n      return users.User(email)",
    "docstring": "Get a User for the given id token, if the token is valid.\n\n  Args:\n    token: The id_token to check.\n    issuers: dict of Issuers\n    audiences: List of audiences that are acceptable.\n    allowed_client_ids: List of client IDs that are acceptable.\n    time_now: The current time as a long (eg. long(time.time())).\n    cache: Cache to use (eg. the memcache module).\n\n  Returns:\n    A User if the token is valid, None otherwise."
  },
  {
    "code": "def black_tophat(image, radius=None, mask=None, footprint=None):\n    final_image = closing(image, radius, mask, footprint) - image \n    if not mask is None:\n        not_mask = np.logical_not(mask)\n        final_image[not_mask] = image[not_mask]\n    return final_image",
    "docstring": "Black tophat filter an image using a circular structuring element\n    \n    image - image in question\n    radius - radius of the circular structuring element. If no radius, use\n             an 8-connected structuring element.\n    mask  - mask of significant pixels in the image. Points outside of\n            the mask will not participate in the morphological operations"
  },
  {
    "code": "async def open_websocket(url: str,\n                         headers: Optional[list] = None,\n                         subprotocols: Optional[list] = None):\n    ws = await create_websocket(\n        url, headers=headers, subprotocols=subprotocols)\n    try:\n        yield ws\n    finally:\n        await ws.close()",
    "docstring": "Opens a websocket."
  },
  {
    "code": "def filter(self, intersects):\n        try:\n            crs = self.crs\n            vector = intersects.geometry if isinstance(intersects, GeoFeature) else intersects\n            prepared_shape = prep(vector.get_shape(crs))\n            hits = []\n            for feature in self:\n                target_shape = feature.geometry.get_shape(crs)\n                if prepared_shape.overlaps(target_shape) or prepared_shape.intersects(target_shape):\n                    hits.append(feature)\n        except IndexError:\n            hits = []\n        return FeatureCollection(hits)",
    "docstring": "Filter results that intersect a given GeoFeature or Vector."
  },
  {
    "code": "def build_exception_map(cls, tokens):\n    exception_ranges = defaultdict(list)\n    for token in tokens:\n      token_type, _, token_start, token_end = token[0:4]\n      if token_type in (tokenize.COMMENT, tokenize.STRING):\n        if token_start[0] == token_end[0]:\n          exception_ranges[token_start[0]].append((token_start[1], token_end[1]))\n        else:\n          exception_ranges[token_start[0]].append((token_start[1], sys.maxsize))\n          for line in range(token_start[0] + 1, token_end[0]):\n            exception_ranges[line].append((0, sys.maxsize))\n          exception_ranges[token_end[0]].append((0, token_end[1]))\n    return exception_ranges",
    "docstring": "Generates a set of ranges where we accept trailing slashes, specifically within comments\n       and strings."
  },
  {
    "code": "def attribute_name(self, attribute_name):\n        if attribute_name is None:\n            raise ValueError(\"Invalid value for `attribute_name`, must not be `None`\")\n        if len(attribute_name) < 1:\n            raise ValueError(\"Invalid value for `attribute_name`, length must be greater than or equal to `1`\")\n        self._attribute_name = attribute_name",
    "docstring": "Sets the attribute_name of this CatalogQueryRange.\n        The name of the attribute to be searched.\n\n        :param attribute_name: The attribute_name of this CatalogQueryRange.\n        :type: str"
  },
  {
    "code": "def to_lookup(self, key_selector=identity, value_selector=identity):\n        if self.closed():\n            raise ValueError(\"Attempt to call to_lookup() on a closed Queryable.\")\n        if not is_callable(key_selector):\n            raise TypeError(\"to_lookup() parameter key_selector={key_selector} is not callable\".format(\n                    key_selector=repr(key_selector)))\n        if not is_callable(value_selector):\n            raise TypeError(\"to_lookup() parameter value_selector={value_selector} is not callable\".format(\n                    value_selector=repr(value_selector)))\n        key_value_pairs = self.select(lambda item: (key_selector(item), value_selector(item)))\n        lookup = Lookup(key_value_pairs)\n        return lookup",
    "docstring": "Returns a Lookup object, using the provided selector to generate a\n        key for each item.\n\n        Note: This method uses immediate execution."
  },
  {
    "code": "def read_prototxt(fname):\n    proto = caffe_pb2.NetParameter()\n    with open(fname, 'r') as f:\n        text_format.Merge(str(f.read()), proto)\n    return proto",
    "docstring": "Return a caffe_pb2.NetParameter object that defined in a prototxt file"
  },
  {
    "code": "def XanyKX(self):\n        result = np.empty((self.P,self.F_any.shape[1],self.dof), order='C')\n        for p in range(self.P):\n            FanyD = self.Fstar_any * self.D[:,p:p+1]\n            start = 0\n            for term in range(self.len):\n                stop = start + self.F[term].shape[1]*self.A[term].shape[0]\n                result[p,:,start:stop] = self.XanyKX2_single_p_single_term(p=p, F1=FanyD, F2=self.Fstar[term], A2=self.Astar[term])\n                start = stop\n        return result",
    "docstring": "compute cross covariance for any and rest"
  },
  {
    "code": "def rcfile(appname, args={}, strip_dashes=True, module_name=None):\n    if strip_dashes:\n        for k in args.keys():\n            args[k.lstrip('-')] = args.pop(k)\n    environ = get_environment(appname)\n    if not module_name:\n        module_name = appname\n    config = get_config(appname, module_name, args.get('config', ''))\n    return merge(merge(args, config), environ)",
    "docstring": "Read environment variables and config files and return them merged with predefined list of arguments.\n\n        Arguments:\n            appname - application name, used for config files and environemnt variable names.\n            args - arguments from command line (optparse, docopt, etc).\n            strip_dashes - strip dashes prefixing key names from args dict.\n\n        Returns:\n            dict containing the merged variables of environment variables, config files and args.\n\n        Environment variables are read if they start with appname in uppercase with underscore, for example:\n\n            TEST_VAR=1\n\n        Config files compatible with ConfigParser are read and the section name appname is read, example:\n\n            [appname]\n            var=1\n\n        Files are read from: /etc/appname/config, /etc/appfilerc, ~/.config/appname/config, ~/.config/appname,\n            ~/.appname/config, ~/.appnamerc, .appnamerc, file provided by config variable in args.\n\n        Example usage with docopt:\n\n            args = rcfile(__name__, docopt(__doc__, version=__version__))"
  },
  {
    "code": "def do_startInstance(self,args):\n        parser = CommandArgumentParser(\"startInstance\")\n        parser.add_argument(dest='instance',help='instance index or name');\n        args = vars(parser.parse_args(args))\n        instanceId = args['instance']\n        force = args['force']\n        try:\n            index = int(instanceId)\n            instances = self.scalingGroupDescription['AutoScalingGroups'][0]['Instances']\n            instanceId = instances[index]\n        except ValueError:\n            pass\n        client = AwsConnectionFactory.getEc2Client()\n        client.start_instances(InstanceIds=[instanceId['InstanceId']])",
    "docstring": "Start specified instance"
  },
  {
    "code": "def execute_specific(self, p_todo):\n        self._handle_recurrence(p_todo)\n        self.execute_specific_core(p_todo)\n        printer = PrettyPrinter()\n        self.out(self.prefix() + printer.print_todo(p_todo))",
    "docstring": "Actions specific to this command."
  },
  {
    "code": "def getNewQuery(connection = None, commitOnEnd=False, *args, **kargs):\n\tif connection is None:\n\t\treturn query.PySQLQuery(getNewConnection(*args, **kargs), commitOnEnd = commitOnEnd)\n\telse:\n\t\treturn query.PySQLQuery(connection, commitOnEnd = commitOnEnd)",
    "docstring": "Create a new PySQLQuery Class\n\t\n\t@param PySQLConnectionObj: Connection Object representing your connection string\n\t@param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a one time auto commit\n\t@author: Nick Verbeck\n\t@since: 5/12/2008\n\t@updated: 7/19/2008 - Added commitOnEnd support"
  },
  {
    "code": "def export_img(visio_filename, image_filename, pagenum=None, pagename=None):\n    image_pathname = os.path.abspath(image_filename)\n    if not os.path.isdir(os.path.dirname(image_pathname)):\n        msg = 'Could not write image file: %s' % image_filename\n        raise IOError(msg)\n    with VisioFile.Open(visio_filename) as visio:\n        pages = filter_pages(visio.pages, pagenum, pagename)\n        try:\n            if len(pages) == 1:\n                pages[0].Export(image_pathname)\n            else:\n                digits = int(log(len(pages), 10)) + 1\n                basename, ext = os.path.splitext(image_pathname)\n                filename_format = \"%s%%0%dd%s\" % (basename, digits, ext)\n                for i, page in enumerate(pages):\n                    filename = filename_format % (i + 1)\n                    page.Export(filename)\n        except Exception:\n            raise IOError('Could not write image: %s' % image_pathname)",
    "docstring": "Exports images from visio file"
  },
  {
    "code": "def _unfocus(self, event):\n        w = self.focus_get()\n        if w != self and 'spinbox' not in str(w) and 'entry' not in str(w):\n            self.focus_set()",
    "docstring": "Unfocus palette items when click on bar or square."
  },
  {
    "code": "def generate(self, x, **kwargs):\n    assert self.sess is not None, \\\n        'Cannot use `generate` when no `sess` was provided'\n    self.parse_params(**kwargs)\n    labels, nb_classes = self.get_or_guess_labels(x, kwargs)\n    attack = CWL2(self.sess, self.model, self.batch_size, self.confidence,\n                  'y_target' in kwargs, self.learning_rate,\n                  self.binary_search_steps, self.max_iterations,\n                  self.abort_early, self.initial_const, self.clip_min,\n                  self.clip_max, nb_classes,\n                  x.get_shape().as_list()[1:])\n    def cw_wrap(x_val, y_val):\n      return np.array(attack.attack(x_val, y_val), dtype=self.np_dtype)\n    wrap = tf.py_func(cw_wrap, [x, labels], self.tf_dtype)\n    wrap.set_shape(x.get_shape())\n    return wrap",
    "docstring": "Return a tensor that constructs adversarial examples for the given\n    input. Generate uses tf.py_func in order to operate over tensors.\n\n    :param x: A tensor with the inputs.\n    :param kwargs: See `parse_params`"
  },
  {
    "code": "def dump_edn_val(v):\n  \" edn simple value dump\"\n  if isinstance(v, (str, unicode)): \n    return json.dumps(v)\n  elif isinstance(v, E):            \n    return unicode(v)\n  else:                             \n    return dumps(v)",
    "docstring": "edn simple value dump"
  },
  {
    "code": "def _MakeFileDescriptorProto(proto_file_name, full_name, field_items):\n  package, name = full_name.rsplit('.', 1)\n  file_proto = descriptor_pb2.FileDescriptorProto()\n  file_proto.name = os.path.join(package.replace('.', '/'), proto_file_name)\n  file_proto.package = package\n  desc_proto = file_proto.message_type.add()\n  desc_proto.name = name\n  for f_number, (f_name, f_type) in enumerate(field_items, 1):\n    field_proto = desc_proto.field.add()\n    field_proto.name = f_name\n    field_proto.number = f_number\n    field_proto.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL\n    field_proto.type = f_type\n  return file_proto",
    "docstring": "Populate FileDescriptorProto for MessageFactory's DescriptorPool."
  },
  {
    "code": "def export_distributions(region=None, key=None, keyid=None, profile=None):\n    results = OrderedDict()\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    try:\n        for name, distribution in _list_distributions(\n            conn,\n            region=region,\n            key=key,\n            keyid=keyid,\n            profile=profile,\n        ):\n            config = distribution['distribution']['DistributionConfig']\n            tags = distribution['tags']\n            distribution_sls_data = [\n                {'name': name},\n                {'config': config},\n                {'tags': tags},\n            ]\n            results['Manage CloudFront distribution {0}'.format(name)] = {\n                'boto_cloudfront.present': distribution_sls_data,\n            }\n    except botocore.exceptions.ClientError as err:\n        raise err\n    dumper = __utils__['yaml.get_dumper']('IndentedSafeOrderedDumper')\n    return __utils__['yaml.dump'](\n        results,\n        default_flow_style=False,\n        Dumper=dumper,\n    )",
    "docstring": "Get details of all CloudFront distributions.\n    Produces results that can be used to create an SLS file.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-call boto_cloudfront.export_distributions --out=txt |\\\n            sed \"s/local: //\" > cloudfront_distributions.sls"
  },
  {
    "code": "def prepare_model(self, sess, allow_initialize=True):\n    if self._follower:\n      self.wait_for_initialization()\n    else:\n      self._init_model(sess, allow_initialize)\n    if sess is not self._sess:\n      if self.threads:\n        raise ValueError('You must call stop_queues() before '\n                         'starting a new session with QueueRunners.')\n      self._sess = sess\n    self._start_threads(sess)",
    "docstring": "Initialize the model and if necessary launch the queue runners."
  },
  {
    "code": "def delete_instance(self, uid):\n        uri = \"%s/%s\" % (self.uri, uid)\n        response, instance = self.request(\"DELETE\", uri)\n        return response.status == 204",
    "docstring": "Delete an ObjectModel via a DELETE request\n\n        :param int uid: Unique id for the Model resource"
  },
  {
    "code": "def system_image_type(self, system_image_type):\n        allowed_values = [\"DOCKER_IMAGE\", \"VIRTUAL_MACHINE_RAW\", \"VIRTUAL_MACHINE_QCOW2\", \"LOCAL_WORKSPACE\"]\n        if system_image_type not in allowed_values:\n            raise ValueError(\n                \"Invalid value for `system_image_type` ({0}), must be one of {1}\"\n                .format(system_image_type, allowed_values)\n            )\n        self._system_image_type = system_image_type",
    "docstring": "Sets the system_image_type of this BuildEnvironmentRest.\n\n        :param system_image_type: The system_image_type of this BuildEnvironmentRest.\n        :type: str"
  },
  {
    "code": "def press_by_tooltip(self, tooltip):\n    for button in find_by_tooltip(world.browser, tooltip):\n        try:\n            button.click()\n            break\n        except:\n            pass\n    else:\n        raise AssertionError(\"No button with tooltip '{0}' found\"\n                             .format(tooltip))",
    "docstring": "Click on a HTML element with a given tooltip.\n\n    This is very useful if you're clicking on icon buttons, etc."
  },
  {
    "code": "def retrieve(self, id) :\n        _, _, lead = self.http_client.get(\"/leads/{id}\".format(id=id))\n        return lead",
    "docstring": "Retrieve a single lead\n\n        Returns a single lead available to the user, according to the unique lead ID provided\n        If the specified lead does not exist, this query returns an error\n\n        :calls: ``get /leads/{id}``\n        :param int id: Unique identifier of a Lead.\n        :return: Dictionary that support attriubte-style access and represent Lead resource.\n        :rtype: dict"
  },
  {
    "code": "def update_config(self, config):\n        lock = Lock()\n        with lock:\n            config_responses = self.client.Config(\n                self.generate_config_request(config))\n            agent_config = next(config_responses)\n            return agent_config",
    "docstring": "Sends TraceConfig to the agent and gets agent's config in reply.\n\n        :type config: `~opencensus.proto.trace.v1.TraceConfig`\n        :param config: Trace config with sampling and other settings\n\n        :rtype: `~opencensus.proto.trace.v1.TraceConfig`\n        :returns: Trace config from agent."
  },
  {
    "code": "def describe_role(name, region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    try:\n        info = conn.get_role(name)\n        if not info:\n            return False\n        role = info.get_role_response.get_role_result.role\n        role['assume_role_policy_document'] = salt.utils.json.loads(_unquote(\n            role.assume_role_policy_document\n        ))\n        for policy_key, policy in role['assume_role_policy_document'].items():\n            if policy_key == 'Statement':\n                for val in policy:\n                    if 'Sid' in val and not val['Sid']:\n                        del val['Sid']\n        return role\n    except boto.exception.BotoServerError as e:\n        log.debug(e)\n        log.error('Failed to get %s information.', name)\n        return False",
    "docstring": "Get information for a role.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_iam.describe_role myirole"
  },
  {
    "code": "def jx_type(column):\n    if column.es_column.endswith(EXISTS_TYPE):\n        return EXISTS\n    return es_type_to_json_type[column.es_type]",
    "docstring": "return the jx_type for given column"
  },
  {
    "code": "def _write_json(obj, path):\n    with open(path, 'w') as f:\n        json.dump(obj, f)",
    "docstring": "Writes a serializeable object as a JSON file"
  },
  {
    "code": "def update(self):\n        reqs = self.build_requests()\n        for r in reqs:\n            r.block = self.block\n        results = self.send_requests(*reqs)\n        self.callback(results)",
    "docstring": "Update the display"
  },
  {
    "code": "def logloss(y, p):\n    p[p < EPS] = EPS\n    p[p > 1 - EPS] = 1 - EPS\n    return log_loss(y, p)",
    "docstring": "Bounded log loss error.\n\n    Args:\n        y (numpy.array): target\n        p (numpy.array): prediction\n\n    Returns:\n        bounded log loss error"
  },
  {
    "code": "def load_dic28():\n    dataset_path = _load('dic28')\n    X = _load_csv(dataset_path, 'data')\n    y = X.pop('label').values\n    graph1 = nx.Graph(nx.read_gml(os.path.join(dataset_path, 'graph1.gml')))\n    graph2 = nx.Graph(nx.read_gml(os.path.join(dataset_path, 'graph2.gml')))\n    graph = graph1.copy()\n    graph.add_nodes_from(graph2.nodes(data=True))\n    graph.add_edges_from(graph2.edges)\n    graph.add_edges_from(X[['graph1', 'graph2']].values)\n    graphs = {\n        'graph1': graph1,\n        'graph2': graph2,\n    }\n    return Dataset(load_dic28.__doc__, X, y, accuracy_score,\n                   stratify=True, graph=graph, graphs=graphs)",
    "docstring": "DIC28 Dataset from Pajek.\n\n    This network represents connections among English words in a dictionary.\n    It was generated from Knuth's dictionary. Two words are connected by an\n    edge if we can reach one from the other by\n    - changing a single character (e. g., work - word)\n    - adding / removing a single character (e. g., ever - fever).\n\n    There exist 52,652 words (vertices in a network) having 2 up to 8 characters\n    in the dictionary. The obtained network has 89038 edges."
  },
  {
    "code": "def has_device_info(self, key):\n        if _debug: DeviceInfoCache._debug(\"has_device_info %r\", key)\n        return key in self.cache",
    "docstring": "Return true iff cache has information about the device."
  },
  {
    "code": "async def list(self, *, filters: Mapping = None) -> List[Mapping]:\n        params = {\"filters\": clean_filters(filters)}\n        response = await self.docker._query_json(\n            \"services\", method=\"GET\", params=params\n        )\n        return response",
    "docstring": "Return a list of services\n\n        Args:\n            filters: a dict with a list of filters\n\n        Available filters:\n            id=<service id>\n            label=<service label>\n            mode=[\"replicated\"|\"global\"]\n            name=<service name>"
  },
  {
    "code": "def invenio_query_factory(parser=None, walkers=None):\n    parser = parser or Main\n    walkers = walkers or [PypegConverter()]\n    walkers.append(ElasticSearchDSL())\n    def invenio_query(pattern):\n        query = pypeg2.parse(pattern, parser, whitespace=\"\")\n        for walker in walkers:\n            query = query.accept(walker)\n        return query\n    return invenio_query",
    "docstring": "Create a parser returning Elastic Search DSL query instance."
  },
  {
    "code": "def update(self, typ, id, **kwargs):\n        return self._load(self._request(typ, id=id, method='PUT', data=kwargs))",
    "docstring": "update just fields sent by keyword args"
  },
  {
    "code": "def create_actions(MAIN):\n    actions = MAIN.action\n    actions['open_settings'] = QAction(QIcon(ICON['settings']), 'Settings',\n                                       MAIN)\n    actions['open_settings'].triggered.connect(MAIN.show_settings)\n    actions['close_wndw'] = QAction(QIcon(ICON['quit']), 'Quit', MAIN)\n    actions['close_wndw'].triggered.connect(MAIN.close)\n    actions['about'] = QAction('About WONAMBI', MAIN)\n    actions['about'].triggered.connect(MAIN.about)\n    actions['aboutqt'] = QAction('About Qt', MAIN)\n    actions['aboutqt'].triggered.connect(lambda: QMessageBox.aboutQt(MAIN))",
    "docstring": "Create all the possible actions."
  },
  {
    "code": "def fixcode(**kwargs):\n    repo_dir = Path(__file__).parent.absolute()\n    source_dir = Path(repo_dir, package.__name__)\n    if source_dir.exists():\n        print(\"Source code locate at: '%s'.\" % source_dir)\n        print(\"Auto pep8 all python file ...\")\n        source_dir.autopep8(**kwargs)\n    else:\n        print(\"Source code directory not found!\")\n    unittest_dir = Path(repo_dir, \"tests\")\n    if unittest_dir.exists():\n        print(\"Unittest code locate at: '%s'.\" % unittest_dir)\n        print(\"Auto pep8 all python file ...\")\n        unittest_dir.autopep8(**kwargs)\n    else:\n        print(\"Unittest code directory not found!\")\n    print(\"Complete!\")",
    "docstring": "auto pep8 format all python file in ``source code`` and ``tests`` dir."
  },
  {
    "code": "def item_length(self):\n        if (self.dtype not in [list, dict, array.array]):\n            raise TypeError(\"item_length() is only applicable for SArray of type list, dict and array.\")\n        with cython_context():\n            return SArray(_proxy = self.__proxy__.item_length())",
    "docstring": "Length of each element in the current SArray.\n\n        Only works on SArrays of dict, array, or list type. If a given element\n        is a missing value, then the output elements is also a missing value.\n        This function is equivalent to the following but more performant:\n\n            sa_item_len =  sa.apply(lambda x: len(x) if x is not None else None)\n\n        Returns\n        -------\n        out_sf : SArray\n            A new SArray, each element in the SArray is the len of the corresponding\n            items in original SArray.\n\n        Examples\n        --------\n        >>> sa = SArray([\n        ...  {\"is_restaurant\": 1, \"is_electronics\": 0},\n        ...  {\"is_restaurant\": 1, \"is_retail\": 1, \"is_electronics\": 0},\n        ...  {\"is_restaurant\": 0, \"is_retail\": 1, \"is_electronics\": 0},\n        ...  {\"is_restaurant\": 0},\n        ...  {\"is_restaurant\": 1, \"is_electronics\": 1},\n        ...  None])\n        >>> sa.item_length()\n        dtype: int\n        Rows: 6\n        [2, 3, 3, 1, 2, None]"
  },
  {
    "code": "def close(self):\n        if self.session is not None:\n            self.session.cookies.clear()\n            self.session.close()\n            self.session = None",
    "docstring": "Close the current session, if still open."
  },
  {
    "code": "def delete_by_ids(self, ids):\n        try:\n            self.filter(id__in=ids).delete()\n            return True\n        except self.model.DoesNotExist:\n            return False",
    "docstring": "Delete objects by ids.\n\n        :param ids: list of objects ids to delete.\n        :return: True if objects were deleted.  Otherwise, return False if no\n                objects were found or the delete was not successful."
  },
  {
    "code": "def get_overall_services_health(self) -> str:\n        services_health_status = self.get_services_health()\n        health_status = all(status == \"Healthy\" for status in\n                            services_health_status.values())\n        if health_status:\n            overall_status = \"Healthy\"\n        else:\n            overall_status = \"Unhealthy\"\n        return overall_status",
    "docstring": "Get the overall health of all the services.\n\n        Returns:\n            str, overall health status"
  },
  {
    "code": "def main(guess_a=1., guess_b=0., power=3, savetxt='None', verbose=False):\n    x, sol = solve(guess_a, guess_b, power)\n    assert sol.success\n    if savetxt != 'None':\n        np.savetxt(x, savetxt)\n    else:\n        if verbose:\n            print(sol)\n        else:\n            print(x)",
    "docstring": "Example demonstrating how to solve a system of non-linear equations defined as SymPy expressions.\n\n    The example shows how a non-linear problem can be given a command-line interface which may be\n    preferred by end-users who are not familiar with Python."
  },
  {
    "code": "def IsPipe(self):\n    if self._stat_object is None:\n      self._stat_object = self._GetStat()\n    if self._stat_object is not None:\n      self.entry_type = self._stat_object.type\n    return self.entry_type == definitions.FILE_ENTRY_TYPE_PIPE",
    "docstring": "Determines if the file entry is a pipe.\n\n    Returns:\n      bool: True if the file entry is a pipe."
  },
  {
    "code": "def ekfind(query, lenout=_default_len_out):\n    query = stypes.stringToCharP(query)\n    lenout = ctypes.c_int(lenout)\n    nmrows = ctypes.c_int()\n    error = ctypes.c_int()\n    errmsg = stypes.stringToCharP(lenout)\n    libspice.ekfind_c(query, lenout, ctypes.byref(nmrows), ctypes.byref(error),\n                      errmsg)\n    return nmrows.value, error.value, stypes.toPythonString(errmsg)",
    "docstring": "Find E-kernel data that satisfy a set of constraints.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekfind_c.html\n\n    :param query: Query specifying data to be found.\n    :type query: str\n    :param lenout: Declared length of output error message string.\n    :type lenout: int\n    :return:\n            Number of matching rows,\n            Flag indicating whether query parsed correctly,\n            Parse error description.\n    :rtype: tuple"
  },
  {
    "code": "def css(self, mapping=None):\n        css = self._css\n        if mapping is None:\n            return css\n        elif isinstance(mapping, Mapping):\n            if css is None:\n                self._extra['css'] = css = {}\n            css.update(mapping)\n            return self\n        else:\n            return css.get(mapping) if css else None",
    "docstring": "Update the css dictionary if ``mapping`` is a dictionary, otherwise\n        return the css value at ``mapping``.\n\n        If ``mapping`` is not given, return the whole ``css`` dictionary\n        if available."
  },
  {
    "code": "def trading_dates(start, end, calendar='US'):\n    kw = dict(start=pd.Timestamp(start, tz='UTC').date(), end=pd.Timestamp(end, tz='UTC').date())\n    us_cal = getattr(sys.modules[__name__], f'{calendar}TradingCalendar')()\n    return pd.bdate_range(**kw).drop(us_cal.holidays(**kw))",
    "docstring": "Trading dates for given exchange\n\n    Args:\n        start: start date\n        end: end date\n        calendar: exchange as string\n\n    Returns:\n        pd.DatetimeIndex: datetime index\n\n    Examples:\n        >>> bus_dates = ['2018-12-24', '2018-12-26', '2018-12-27']\n        >>> trd_dates = trading_dates(start='2018-12-23', end='2018-12-27')\n        >>> assert len(trd_dates) == len(bus_dates)\n        >>> assert pd.Series(trd_dates == pd.DatetimeIndex(bus_dates)).all()"
  },
  {
    "code": "def delete(self, path):\n        path = sanitize_mount(path)\n        val = None\n        if path.startswith('cubbyhole'):\n            self.token = self.initial_token\n            val = super(Client, self).delete(path)\n            self.token = self.operational_token\n        else:\n            super(Client, self).delete(path)\n        return val",
    "docstring": "Wrap the hvac delete call, using the right token for\n        cubbyhole interactions."
  },
  {
    "code": "def expect_handshake(self, headers):\n        init_req = yield self.reader.get()\n        if init_req.message_type != Types.INIT_REQ:\n            raise errors.UnexpectedError(\n                \"You need to shake my hand first. Got %s\" % repr(init_req)\n            )\n        self._extract_handshake_headers(init_req)\n        self._handshake_performed = True\n        self.writer.put(\n            messages.InitResponseMessage(\n                PROTOCOL_VERSION, headers, init_req.id),\n        )\n        self._loop()\n        raise tornado.gen.Return(init_req)",
    "docstring": "Expect a handshake from the remote host.\n\n        :param headers:\n            Headers to respond with\n        :returns:\n            A future that resolves (with a value of None) when the handshake\n            is complete."
  },
  {
    "code": "def _print_memory(self, memory):\n        for addr, value in memory.items():\n            print(\"    0x%08x : 0x%08x (%d)\" % (addr, value, value))",
    "docstring": "Print memory."
  },
  {
    "code": "def evaluate(self, x, y, flux, x_0, y_0):\n        x = (x - x_0 + 0.5 + self.prf_shape[1] // 2).astype('int')\n        y = (y - y_0 + 0.5 + self.prf_shape[0] // 2).astype('int')\n        y_sub, x_sub = subpixel_indices((y_0, x_0), self.subsampling)\n        x_bound = np.logical_or(x < 0, x >= self.prf_shape[1])\n        y_bound = np.logical_or(y < 0, y >= self.prf_shape[0])\n        out_of_bounds = np.logical_or(x_bound, y_bound)\n        x[x_bound] = 0\n        y[y_bound] = 0\n        result = flux * self._prf_array[int(y_sub), int(x_sub)][y, x]\n        result[out_of_bounds] = 0\n        return result",
    "docstring": "Discrete PRF model evaluation.\n\n        Given a certain position and flux the corresponding image of\n        the PSF is chosen and scaled to the flux. If x and y are\n        outside the boundaries of the image, zero will be returned.\n\n        Parameters\n        ----------\n        x : float\n            x coordinate array in pixel coordinates.\n        y : float\n            y coordinate array in pixel coordinates.\n        flux : float\n            Model flux.\n        x_0 : float\n            x position of the center of the PRF.\n        y_0 : float\n            y position of the center of the PRF."
  },
  {
    "code": "def get(cls, issue_type):\n        if isinstance(issue_type, str):\n            obj = getattr(db, cls.__name__).find_one(cls.issue_type == issue_type)\n        elif isinstance(issue_type, int):\n            obj = getattr(db, cls.__name__).find_one(cls.issue_type_id == issue_type)\n        elif isinstance(issue_type, cls):\n            return issue_type\n        else:\n            obj = None\n        if not obj:\n            obj = cls()\n            obj.issue_type = issue_type\n            db.session.add(obj)\n            db.session.commit()\n            db.session.refresh(obj)\n        return obj",
    "docstring": "Returns the IssueType object for `issue_type`. If no existing object was found, a new type will\n        be created in the database and returned\n\n        Args:\n            issue_type (str,int,IssueType): Issue type name, id or class\n\n        Returns:\n            :obj:`IssueType`"
  },
  {
    "code": "def reverse_transform_table(self, table, table_meta, missing=None):\n        if missing is None:\n            missing = self.missing\n        else:\n            self.missing = missing\n            warnings.warn(\n                DEPRECATION_MESSAGE.format('reverse_transform_table'), DeprecationWarning)\n        result = pd.DataFrame(index=table.index)\n        table_name = table_meta['name']\n        for field in table_meta['fields']:\n            new_column = self._reverse_transform_column(table, field, table_name)\n            if new_column is not None:\n                result[field['name']] = new_column\n        return result",
    "docstring": "Transform a `table` back to its original format.\n\n        Args:\n            table(pandas.DataFrame):     Contents of the table to be transformed.\n\n            table_meta(dict):   Metadata for the given table.\n\n            missing(bool):      Wheter or not use NullTransformer to handle missing values.\n\n        Returns:\n            pandas.DataFrame: Table in original format."
  },
  {
    "code": "def triple(subject, relation, obj):\n    return And([Group(subject)(SUBJECT), relation(RELATION), Group(obj)(OBJECT)])",
    "docstring": "Build a simple triple in PyParsing that has a ``subject relation object`` format."
  },
  {
    "code": "def _classify_load_constant(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):\n        matches = []\n        for dst_reg, dst_val in regs_fini.items():\n            if dst_reg not in written_regs:\n                continue\n            if dst_val == regs_init[dst_reg]:\n                continue\n            dst_val_ir = ReilImmediateOperand(dst_val, self._arch_regs_size[dst_reg])\n            dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])\n            matches.append({\n                \"src\": [dst_val_ir],\n                \"dst\": [dst_reg_ir]\n            })\n        return matches",
    "docstring": "Classify load-constant gadgets."
  },
  {
    "code": "def parse_reaction_equation_string(equation, default_compartment):\n    def _translate_compartments(reaction, compartment):\n        left = (((c.in_compartment(compartment), v)\n                 if c.compartment is None else (c, v))\n                for c, v in reaction.left)\n        right = (((c.in_compartment(compartment), v)\n                  if c.compartment is None else (c, v))\n                 for c, v in reaction.right)\n        return Reaction(reaction.direction, left, right)\n    eq = _REACTION_PARSER.parse(equation).normalized()\n    return _translate_compartments(eq, default_compartment)",
    "docstring": "Parse a string representation of a reaction equation.\n\n    Converts undefined compartments to the default compartment."
  },
  {
    "code": "def _lookup(self, timestamp):\n        idx = search_greater(self._values, timestamp)\n        if (idx < len(self._values)\n                and math.fabs(self._values[idx][0] - timestamp) < self.EPSILON):\n            return idx\n        return None",
    "docstring": "Return the index of the value associated with \"timestamp\" if any, else\n        None. Since the timestamps are floating-point values, they are\n        considered equal if their absolute difference is smaller than\n        self.EPSILON"
  },
  {
    "code": "def lcm( *a ):\n  if len( a ) > 1: return reduce( lcm2, a )\n  if hasattr( a[0], \"__iter__\" ): return reduce( lcm2, a[0] )\n  return a[0]",
    "docstring": "Least common multiple.\n\n  Usage: lcm( [ 3, 4, 5 ] )\n  or:    lcm( 3, 4, 5 )"
  },
  {
    "code": "def do_min(environment, value, case_sensitive=False, attribute=None):\n    return _min_or_max(environment, value, min, case_sensitive, attribute)",
    "docstring": "Return the smallest item from the sequence.\n\n    .. sourcecode:: jinja\n\n        {{ [1, 2, 3]|min }}\n            -> 1\n\n    :param case_sensitive: Treat upper and lower case strings as distinct.\n    :param attribute: Get the object with the max value of this attribute."
  },
  {
    "code": "def remove_non_magic_cols_from_table(self, ignore_cols=()):\n        unrecognized_cols = self.get_non_magic_cols()\n        for col in ignore_cols:\n            if col in unrecognized_cols:\n                unrecognized_cols.remove(col)\n        if unrecognized_cols:\n            print('-I- Removing non-MagIC column names from {}:'.format(self.dtype), end=' ')\n            for col in unrecognized_cols:\n                self.df.drop(col, axis='columns', inplace=True)\n                print(col, end=' ')\n            print(\"\\n\")\n        return unrecognized_cols",
    "docstring": "Remove all non-magic columns from self.df.\n        Changes in place.\n\n        Parameters\n        ----------\n        ignore_cols : list-like\n            columns not to remove, whether they are proper\n            MagIC columns or not\n\n        Returns\n        ---------\n        unrecognized_cols : list\n            any columns that were removed"
  },
  {
    "code": "def write_jobfile(self, task, **kwargs):\n        script = self.qadapter.get_script_str(\n            job_name=task.name,\n            launch_dir=task.workdir,\n            executable=task.executable,\n            qout_path=task.qout_file.path,\n            qerr_path=task.qerr_file.path,\n            stdin=task.files_file.path,\n            stdout=task.log_file.path,\n            stderr=task.stderr_file.path,\n            exec_args=kwargs.pop(\"exec_args\", []),\n        )\n        with open(task.job_file.path, \"w\") as fh:\n            fh.write(script)\n            task.job_file.chmod(0o740)\n            return task.job_file.path",
    "docstring": "Write the submission script. Return the path of the script\n\n        ================  ============================================\n        kwargs            Meaning\n        ================  ============================================\n        exec_args         List of arguments passed to task.executable.\n                          Default: no arguments.\n\n        ================  ============================================"
  },
  {
    "code": "def _set_archive_name(package_name,\n                      package_version,\n                      python_versions,\n                      platform,\n                      build_tag=''):\n    package_name = package_name.replace('-', '_')\n    python_versions = '.'.join(python_versions)\n    archive_name_tags = [\n        package_name,\n        package_version,\n        python_versions,\n        'none',\n        platform,\n    ]\n    if build_tag:\n        archive_name_tags.insert(2, build_tag)\n    archive_name = '{0}.wgn'.format('-'.join(archive_name_tags))\n    return archive_name",
    "docstring": "Set the format of the output archive file.\n\n    We should aspire for the name of the archive to be\n    as compatible as possible with the wheel naming convention\n    described here:\n    https://www.python.org/dev/peps/pep-0491/#file-name-convention,\n    as we're basically providing a \"wheel\" of our package."
  },
  {
    "code": "def _start_lock_renewer(self):\n        if self._lock_renewal_thread is not None:\n            raise AlreadyStarted(\"Lock refresh thread already started\")\n        logger.debug(\n            \"Starting thread to refresh lock every %s seconds\",\n            self._lock_renewal_interval\n        )\n        self._lock_renewal_stop = threading.Event()\n        self._lock_renewal_thread = threading.Thread(\n            group=None,\n            target=self._lock_renewer,\n            kwargs={'lockref': weakref.ref(self),\n                    'interval': self._lock_renewal_interval,\n                    'stop': self._lock_renewal_stop}\n        )\n        self._lock_renewal_thread.setDaemon(True)\n        self._lock_renewal_thread.start()",
    "docstring": "Starts the lock refresher thread."
  },
  {
    "code": "def get_codeblock(language, text):\n    rst = \"\\n\\n.. code-block:: \" + language + \"\\n\\n\"\n    for line in text.splitlines():\n        rst += \"\\t\" + line + \"\\n\"\n    rst += \"\\n\"\n    return rst",
    "docstring": "Generates rst codeblock for given text and language"
  },
  {
    "code": "def interpolate_to_isosurface(level_var, interp_var, level, **kwargs):\n    r\n    bottom_up_search = kwargs.pop('bottom_up_search', True)\n    above, below, good = metpy.calc.find_bounding_indices(level_var, [level], axis=0,\n                                                          from_below=bottom_up_search)\n    interp_level = (((level - level_var[above]) / (level_var[below] - level_var[above]))\n                    * (interp_var[below] - interp_var[above])) + interp_var[above]\n    interp_level[~good] = np.nan\n    minvar = (np.min(level_var, axis=0) >= level)\n    maxvar = (np.max(level_var, axis=0) <= level)\n    interp_level[0][minvar] = interp_var[-1][minvar]\n    interp_level[0][maxvar] = interp_var[0][maxvar]\n    return interp_level.squeeze()",
    "docstring": "r\"\"\"Linear interpolation of a variable to a given vertical level from given values.\n\n    This function assumes that highest vertical level (lowest pressure) is zeroth index.\n    A classic use of this function would be to compute the potential temperature on the\n    dynamic tropopause (2 PVU surface).\n\n    Parameters\n    ----------\n    level_var: array_like (P, M, N)\n        Level values in 3D grid on common vertical coordinate (e.g., PV values on\n        isobaric levels). Assumes height dimension is highest to lowest in atmosphere.\n    interp_var: array_like (P, M, N)\n        Variable on 3D grid with same vertical coordinate as level_var to interpolate to\n        given level (e.g., potential temperature on isobaric levels)\n    level: int or float\n        Desired interpolated level (e.g., 2 PVU surface)\n\n    Other Parameters\n    ----------------\n    bottom_up_search : bool, optional\n        Controls whether to search for levels bottom-up, or top-down. Defaults to\n        True, which is bottom-up search.\n\n    Returns\n    -------\n    interp_level: (M, N) ndarray\n        The interpolated variable (e.g., potential temperature) on the desired level (e.g.,\n        2 PVU surface)\n\n    Notes\n    -----\n    This function implements a linear interpolation to estimate values on a given surface.\n    The prototypical example is interpolation of potential temperature to the dynamic\n    tropopause (e.g., 2 PVU surface)"
  },
  {
    "code": "def nofollow_callback(attrs, new=False):\n    parsed_url = urlparse(attrs[(None, 'href')])\n    if parsed_url.netloc in ('', current_app.config['SERVER_NAME']):\n        attrs[(None, 'href')] = '{scheme}://{netloc}{path}'.format(\n            scheme='https' if request.is_secure else 'http',\n            netloc=current_app.config['SERVER_NAME'],\n            path=parsed_url.path)\n        return attrs\n    else:\n        rel = [x for x in attrs.get((None, 'rel'), '').split(' ') if x]\n        if 'nofollow' not in [x.lower() for x in rel]:\n            rel.append('nofollow')\n        attrs[(None, 'rel')] = ' '.join(rel)\n        return attrs",
    "docstring": "Turn relative links into external ones and avoid `nofollow` for us,\n\n    otherwise add `nofollow`.\n    That callback is not splitted in order to parse the URL only once."
  },
  {
    "code": "def _all_spec(self):\n        base = self._mod_spec\n        for spec in self.basic_spec:\n            base[spec] = self.basic_spec[spec]\n        return base",
    "docstring": "All specifiers and their lengths."
  },
  {
    "code": "def stream(self, code):\n        self._say(\"Streaming code.\")\n        if type(code) in [str, text_type]:\n            code = code.split(\"\\n\")\n        self._parse(\"stream()\", code)",
    "docstring": "Stream in RiveScript source code dynamically.\n\n        :param code: Either a string containing RiveScript code or an array of\n            lines of RiveScript code."
  },
  {
    "code": "def get_repository(name):\n    cmd = 'Get-PSRepository \"{0}\"'.format(name)\n    no_ret = _pshell(cmd)\n    return name not in list_modules()",
    "docstring": "Get the details of a local PSGet repository\n\n    :param  name: Name of the repository\n    :type   name: ``str``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'win01' psget.get_repository MyRepo"
  },
  {
    "code": "def get_enum_labels(enum_cls):\n    if not issubclass(enum_cls, enum.Enum):\n        raise EnumTypeError(\"Input class '%s' must be derived from enum.Enum\"\n                            % enum_cls)\n    try:\n        enum.unique(enum_cls)\n    except ValueError as exc:\n        raise EnumTypeError(\"Input class '%s' must be unique - %s\"\n                            % (enum_cls, exc))\n    values = [member.value for member in enum_cls]\n    if not values:\n        raise EnumTypeError(\"Input class '%s' has no members!\" % enum_cls)\n    expected_value = 0\n    for value in values:\n        if value != expected_value:\n            raise EnumTypeError(\"Enum values for '%s' must start at 0 and \"\n                                \"increment by 1.  Values: %s\"\n                                % (enum_cls, values))\n        expected_value += 1\n    return [member.name for member in enum_cls]",
    "docstring": "Return list of enumeration labels from Enum class.\n\n    The list is useful when creating an attribute, for the\n    `enum_labels` parameter.  The enumeration values are checked\n    to ensure they are unique, start at zero, and increment by one.\n\n    :param enum_cls: the Enum class to be inspected\n    :type enum_cls: :py:obj:`enum.Enum`\n\n    :return: List of label strings\n    :rtype: :py:obj:`list`\n\n    :raises EnumTypeError: in case the given class is invalid"
  },
  {
    "code": "def snake_to_camel(s: str) -> str:\n    fragments = s.split('_')\n    return fragments[0] + ''.join(x.title() for x in fragments[1:])",
    "docstring": "Convert string from snake case to camel case."
  },
  {
    "code": "def __is_gsi_maintenance_window(table_name, gsi_name, maintenance_windows):\n    maintenance_window_list = []\n    for window in maintenance_windows.split(','):\n        try:\n            start, end = window.split('-', 1)\n        except ValueError:\n            logger.error(\n                '{0} - GSI: {1} - '\n                'Malformatted maintenance window'.format(table_name, gsi_name))\n            return False\n        maintenance_window_list.append((start, end))\n    now = datetime.datetime.utcnow().strftime('%H%M')\n    for maintenance_window in maintenance_window_list:\n        start = ''.join(maintenance_window[0].split(':'))\n        end = ''.join(maintenance_window[1].split(':'))\n        if now >= start and now <= end:\n            return True\n    return False",
    "docstring": "Checks that the current time is within the maintenance window\n\n    :type table_name: str\n    :param table_name: Name of the DynamoDB table\n    :type gsi_name: str\n    :param gsi_name: Name of the GSI\n    :type maintenance_windows: str\n    :param maintenance_windows: Example: '00:00-01:00,10:00-11:00'\n    :returns: bool -- True if within maintenance window"
  },
  {
    "code": "def write_temporary_file(content, prefix='', suffix=''):\n    temp = tempfile.NamedTemporaryFile(prefix=prefix, suffix=suffix, mode='w+t', delete=False)\n    temp.writelines(content)\n    temp.close()\n    return temp.name",
    "docstring": "Generating a temporary file with content.\n\n    Args:\n        content (str): file content (usually a script, Dockerfile, playbook or config file)\n        prefix (str): the filename starts with this prefix (default: no prefix)\n        suffix (str): the filename ends with this suffix (default: no suffix)\n\n    Returns:\n        str: name of the temporary file\n\n    Note:\n        You are responsible for the deletion of the file."
  },
  {
    "code": "def get_vmconfig(vmid, node=None, node_type='openvz'):\n    if node is None:\n        for host_name, host_details in six.iteritems(avail_locations()):\n            for item in query('get', 'nodes/{0}/{1}'.format(host_name, node_type)):\n                if item['vmid'] == vmid:\n                    node = host_name\n    data = query('get', 'nodes/{0}/{1}/{2}/config'.format(node, node_type, vmid))\n    return data",
    "docstring": "Get VM configuration"
  },
  {
    "code": "def open(self, name, *mode):\n        return self.file_factory(self.file_path(name), *mode)",
    "docstring": "Return an open file object for a file in the reference package."
  },
  {
    "code": "def instruction_LD8(self, opcode, m, register):\n        register.set(m)\n        self.clear_NZV()\n        self.update_NZ_8(m)",
    "docstring": "Loads the contents of memory location M into the designated register.\n\n        source code forms: LDA P; LDB P\n\n        CC bits \"HNZVC\": -aa0-"
  },
  {
    "code": "def lookup_symbols(self,\n                       symbols,\n                       as_of_date,\n                       fuzzy=False,\n                       country_code=None):\n        if not symbols:\n            return []\n        multi_country = country_code is None\n        if fuzzy:\n            f = self._lookup_symbol_fuzzy\n            mapping = self._choose_fuzzy_symbol_ownership_map(country_code)\n        else:\n            f = self._lookup_symbol_strict\n            mapping = self._choose_symbol_ownership_map(country_code)\n        if mapping is None:\n            raise SymbolNotFound(symbol=symbols[0])\n        memo = {}\n        out = []\n        append_output = out.append\n        for sym in symbols:\n            if sym in memo:\n                append_output(memo[sym])\n            else:\n                equity = memo[sym] = f(\n                    mapping,\n                    multi_country,\n                    sym,\n                    as_of_date,\n                )\n                append_output(equity)\n        return out",
    "docstring": "Lookup a list of equities by symbol.\n\n        Equivalent to::\n\n            [finder.lookup_symbol(s, as_of, fuzzy) for s in symbols]\n\n        but potentially faster because repeated lookups are memoized.\n\n        Parameters\n        ----------\n        symbols : sequence[str]\n            Sequence of ticker symbols to resolve.\n        as_of_date : pd.Timestamp\n            Forwarded to ``lookup_symbol``.\n        fuzzy : bool, optional\n            Forwarded to ``lookup_symbol``.\n        country_code : str or None, optional\n            The country to limit searches to. If not provided, the search will\n            span all countries which increases the likelihood of an ambiguous\n            lookup.\n\n        Returns\n        -------\n        equities : list[Equity]"
  },
  {
    "code": "def find_actual_effect(self, mechanism, purviews=False):\n        return self.find_causal_link(Direction.EFFECT, mechanism, purviews)",
    "docstring": "Return the actual effect of a mechanism."
  },
  {
    "code": "def convert_type(self, type):\n        mapping = {\n            'any': 'STRING',\n            'array': None,\n            'boolean': 'BOOLEAN',\n            'date': 'DATE',\n            'datetime': 'DATETIME',\n            'duration': None,\n            'geojson': None,\n            'geopoint': None,\n            'integer': 'INTEGER',\n            'number': 'FLOAT',\n            'object': None,\n            'string': 'STRING',\n            'time': 'TIME',\n            'year': 'INTEGER',\n            'yearmonth': None,\n        }\n        if type not in mapping:\n            message = 'Type %s is not supported' % type\n            raise tableschema.exceptions.StorageError(message)\n        return mapping[type]",
    "docstring": "Convert type to BigQuery"
  },
  {
    "code": "def format_atomic(value):\n    if isinstance(value, str):\n        if any(r in value for r in record.RESERVED_CHARS):\n            for k, v in record.ESCAPE_MAPPING:\n                value = value.replace(k, v)\n    if value is None:\n        return \".\"\n    else:\n        return str(value)",
    "docstring": "Format atomic value\n\n    This function also takes care of escaping the value in case one of the\n    reserved characters occurs in the value."
  },
  {
    "code": "def _format_dict(self, info_dict):\n        for key, value in info_dict.items():\n            if not value:\n                info_dict[key] = \"NA\"\n        return info_dict",
    "docstring": "Replaces empty content with 'NA's"
  },
  {
    "code": "def lastLogged(self):\n        d = copy.deepcopy(self.__lastLogged)\n        d.pop(-1, None)\n        return d",
    "docstring": "Get a dictionary of last logged messages.\n        Keys are log types and values are the the last messages."
  },
  {
    "code": "def add_server(self, name, ip, port):\n        new_server = {\n            'key': name,\n            'name': name.split(':')[0],\n            'ip': ip,\n            'port': port,\n            'username': 'glances',\n            'password': '',\n            'status': 'UNKNOWN',\n            'type': 'DYNAMIC'}\n        self._server_list.append(new_server)\n        logger.debug(\"Updated servers list (%s servers): %s\" %\n                     (len(self._server_list), self._server_list))",
    "docstring": "Add a new server to the list."
  },
  {
    "code": "def median_images(images):\n        images_data = np.array([image.data for image in images])\n        median_image_data = np.median(images_data, axis=0)\n        an_image = images[0]\n        return type(an_image)(\n            median_image_data.astype(\n                an_image.data.dtype),\n            an_image.frame)",
    "docstring": "Create a median Image from a list of Images.\n\n        Parameters\n        ----------\n        :obj:`list` of :obj:`Image`\n            A list of Image objects.\n\n        Returns\n        -------\n        :obj:`Image`\n            A new Image of the same type whose data is the median of all of\n            the images' data."
  },
  {
    "code": "def iterqueue(queue, expected):\n    while expected > 0:\n        for item in iter(queue.get, EXIT):\n            yield item\n        expected -= 1",
    "docstring": "Iterate all value from the queue until the ``expected`` number of EXIT elements is\n    received"
  },
  {
    "code": "def attrfindrows(self, groupname, attrname, value):\n        values = self.attrgetcol(groupname, attrname)\n        return [i for i in range(len(values)) if values[i] == value]",
    "docstring": "Get the row numbers of all rows where the attribute matches the given value."
  },
  {
    "code": "def is_valid(self):\n        assert self._bundle_context\n        assert self._container_props is not None\n        assert self._get_distribution_provider()\n        assert self.get_config_name()\n        assert self.get_namespace()\n        return True",
    "docstring": "Checks if the component is valid\n\n        :return: Always True if it doesn't raise an exception\n        :raises AssertionError: Invalid properties"
  },
  {
    "code": "def update(self, *args, **kwargs):\n        for next_dict in chain(args, (kwargs, )):\n            for k, v in next_dict.items():\n                self[k] = v",
    "docstring": "Equivalent to the python dict update method.\n\n        Update the dictionary with the key/value pairs from other, overwriting\n        existing keys.\n\n        Args:\n            other (dict): The source of key value pairs to add to headers\n        Keyword Args:\n            All keyword arguments are stored in header directly\n\n        Returns:\n            None"
  },
  {
    "code": "def log_to_json(log):\n    return [log.timestamp.isoformat()[:22],\n            log.level, log.process, log.message]",
    "docstring": "Convert a log record into a list of strings"
  },
  {
    "code": "def validate_one_of(values):\n    def one_of_validator(field, data):\n        if field.value is None:\n            return\n        options = values\n        if callable(options):\n            options = options()\n        if field.value not in options:\n            raise ValidationError('one_of', choices=', '.join(map(str, options)))\n    return one_of_validator",
    "docstring": "Validate that a field is in one of the given values.\n\n    :param values: Iterable of valid values.\n    :raises: ``ValidationError('one_of')``"
  },
  {
    "code": "def _resample_grid(stations, nodes, lags, mindepth, maxdepth, corners):\n    resamp_nodes = []\n    resamp_lags = []\n    for i, node in enumerate(nodes):\n        if mindepth < float(node[2]) < maxdepth and\\\n           corners.contains_point(node[0:2]):\n                resamp_nodes.append(node)\n                resamp_lags.append([lags[:, i]])\n    print(np.shape(resamp_lags))\n    resamp_lags = np.reshape(resamp_lags, (len(resamp_lags), len(stations))).T\n    print(' '.join(['Grid now has ', str(len(resamp_nodes)), 'nodes']))\n    return stations, resamp_nodes, resamp_lags",
    "docstring": "Resample the lagtime grid to a given volume.\n\n    For use if the grid from Grid2Time is too large or you want to run a\n    faster, downsampled scan.\n\n    :type stations: list\n    :param stations:\n        List of station names from in the form where stations[i] refers to\n        nodes[i][:] and lags[i][:]\n    :type nodes: list\n    :param nodes:\n        List of node points where nodes[i] referes to stations[i] and\n        nodes[:][:][0] is latitude in degrees, nodes[:][:][1] is longitude in\n        degrees, nodes[:][:][2] is depth in km.\n    :type lags: numpy.ndarray\n    :param lags:\n        Array of arrays where lags[i][:] refers to stations[i]. lags[i][j]\n        should be the delay to the nodes[i][j] for stations[i] in seconds.\n    :type mindepth: float\n    :param mindepth: Upper limit of volume\n    :type maxdepth: float\n    :param maxdepth: Lower limit of volume\n    :type corners: matplotlib.path.Path\n    :param corners:\n        matplotlib Path of the corners for the 2D polygon to cut to in lat and\n        lon.\n\n    :returns: Stations\n    :rtype: list\n    :returns: List of lists of tuples of node locations\n    :rtype: list\n    :returns: Array of lags.\n    :rtype: :class:`numpy.ndarray`\n\n    .. note::\n        **Output:**\n\n        station[1] refers to nodes[1] and lags[1] nodes[1][1] refers\n        to station[1] and lags[1][1] nodes[n][n] is a tuple of latitude,\n        longitude and depth."
  },
  {
    "code": "def decrypt(self, encrypted):\n        fernet = Fernet(self.decryption_cipher_key)\n        return fernet.decrypt(encrypted)",
    "docstring": "decrypts the encrypted message using Fernet\n\n        :param encrypted: the encrypted message\n        :returns: the decrypted, serialized identifier collection"
  },
  {
    "code": "def view_vector(self, vector, viewup=None):\n        focal_pt = self.center\n        if viewup is None:\n            viewup = rcParams['camera']['viewup']\n        cpos = [vector + np.array(focal_pt),\n                focal_pt, viewup]\n        self.camera_position = cpos\n        return self.reset_camera()",
    "docstring": "Point the camera in the direction of the given vector"
  },
  {
    "code": "def _handle_packet(self, packet):\n        events = packet_events(packet)\n        for event in events:\n            if self.ignore_event(event['id']):\n                log.debug('ignoring event with id: %s', event)\n                continue\n            log.debug('got event: %s', event)\n            if self.event_callback:\n                self.event_callback(event)\n            else:\n                self.handle_event(event)",
    "docstring": "Event specific packet handling logic.\n\n        Break packet into events and fires configured event callback or\n        nicely prints events for console."
  },
  {
    "code": "def _data_keys(self):\n        return [name for name, child in iteritems(self._children) if not isinstance(child, GroupNode)]",
    "docstring": "every child key referencing a dataframe"
  },
  {
    "code": "def update(old, new, collection, sneaky_update_filter=None):\n    need_save = False\n    locked_fields = old.get('_locked_fields', [])\n    for key, value in new.items():\n        if key in locked_fields:\n            continue\n        if old.get(key) != value:\n            if sneaky_update_filter and key in sneaky_update_filter:\n                if sneaky_update_filter[key](old[key], value):\n                    old[key] = value\n                    need_save = True\n            else:\n                old[key] = value\n                need_save = True\n        plus_key = '+%s' % key\n        if plus_key in old:\n            del old[plus_key]\n            need_save = True\n    if need_save:\n        old['updated_at'] = datetime.datetime.utcnow()\n        collection.save(old, safe=True)\n    return need_save",
    "docstring": "update an existing object with a new one, only saving it and\n        setting updated_at if something has changed\n\n        old\n            old object\n        new\n            new object\n        collection\n            collection to save changed object to\n        sneaky_update_filter\n            a filter for updates to object that should be ignored\n            format is a dict mapping field names to a comparison function\n            that returns True iff there is a change"
  },
  {
    "code": "def _GetTimeValue(self, name):\n    timestamp = getattr(self._tsk_file.info.meta, name, None)\n    if self._file_system_type in self._TSK_HAS_NANO_FS_TYPES:\n      name_fragment = '{0:s}_nano'.format(name)\n      fraction_of_second = getattr(\n          self._tsk_file.info.meta, name_fragment, None)\n    else:\n      fraction_of_second = None\n    return TSKTime(timestamp=timestamp, fraction_of_second=fraction_of_second)",
    "docstring": "Retrieves a date and time value.\n\n    Args:\n      name (str): name of the date and time value, for example \"atime\" or\n          \"mtime\".\n\n    Returns:\n      dfdatetime.DateTimeValues: date and time value or None if not available."
  },
  {
    "code": "def publish_json(self, channel, obj):\n        return self.publish(channel, json.dumps(obj))",
    "docstring": "Post a JSON-encoded message to channel."
  },
  {
    "code": "def _get_array_serializer(self):\n        if not self._items:\n            raise ValueError('Must specify \\'items\\' for \\'array\\' type')\n        field = SchemaField(self._items)\n        def encode(value, field=field):\n            if not isinstance(value, list):\n                value = [value]\n            return [field.encode(i) for i in value]\n        def decode(value, field=field):\n            return [field.decode(i) for i in value]\n        return (encode, decode)",
    "docstring": "Gets the encoder and decoder for an array. Uses the 'items' key to\n        build the encoders and decoders for the specified type."
  },
  {
    "code": "def is_one_of(obj, types):\n    for type_ in types:\n        if isinstance(obj, type_):\n            return True\n    return False",
    "docstring": "Return true iff obj is an instance of one of the types."
  },
  {
    "code": "def write_krona_plot(self, sample_names, read_taxonomies, output_krona_filename):\n        tempfiles = []\n        for n in sample_names:\n            tempfiles.append(tempfile.NamedTemporaryFile(prefix='GraftMkronaInput', suffix=n))\n        delim=u'\\t'\n        for _, tax, counts in self._iterate_otu_table_rows(read_taxonomies):\n            for i, c in enumerate(counts):\n                if c != 0:\n                    tempfiles[i].write(delim.join((str(c),\n                                                  delim.join(tax)\n                                                  ))+\"\\n\")\n        for t in tempfiles:\n            t.flush()\n        cmd = [\"ktImportText\",'-o',output_krona_filename]\n        for i, tmp in enumerate(tempfiles):\n            cmd.append(','.join([tmp.name,sample_names[i]]))\n        cmd = ' '.join(cmd)\n        extern.run(cmd)\n        for t in tempfiles:\n            t.close()",
    "docstring": "Creates krona plot at the given location. Assumes the krona executable\n        ktImportText is available on the shell PATH"
  },
  {
    "code": "def reinitialize_all_clients(self):\n        for language in self.clients:\n            language_client = self.clients[language]\n            if language_client['status'] == self.RUNNING:\n                folder = self.get_root_path(language)\n                instance = language_client['instance']\n                instance.folder = folder\n                instance.initialize()",
    "docstring": "Send a new initialize message to each LSP server when the project\n        path has changed so they can update the respective server root paths."
  },
  {
    "code": "def asRFC2822(self, tzinfo=None, includeDayOfWeek=True):\n        dtime = self.asDatetime(tzinfo)\n        if tzinfo is None:\n            rfcoffset = '-0000'\n        else:\n            rfcoffset = '%s%02i%02i' % _timedeltaToSignHrMin(dtime.utcoffset())\n        rfcstring = ''\n        if includeDayOfWeek:\n            rfcstring += self.rfc2822Weekdays[dtime.weekday()] + ', '\n        rfcstring += '%i %s %4i %02i:%02i:%02i %s' % (\n            dtime.day,\n            self.rfc2822Months[dtime.month - 1],\n            dtime.year,\n            dtime.hour,\n            dtime.minute,\n            dtime.second,\n            rfcoffset)\n        return rfcstring",
    "docstring": "Return this Time formatted as specified in RFC 2822.\n\n        RFC 2822 specifies the format of email messages.\n\n        RFC 2822 says times in email addresses should reflect the local\n        timezone. If tzinfo is a datetime.tzinfo instance, the returned\n        formatted string will reflect that timezone. Otherwise, the timezone\n        will be '-0000', which RFC 2822 defines as UTC, but with an unknown\n        local timezone.\n\n        RFC 2822 states that the weekday is optional. The parameter\n        includeDayOfWeek indicates whether or not to include it."
  },
  {
    "code": "def __get_query_agg_cardinality(cls, field, agg_id=None):\n        if not agg_id:\n            agg_id = cls.AGGREGATION_ID\n        query_agg = A(\"cardinality\", field=field, precision_threshold=cls.ES_PRECISION)\n        return (agg_id, query_agg)",
    "docstring": "Create an es_dsl aggregation object for getting the approximate count of distinct values of a field.\n\n        :param field: field from which the get count of distinct values\n        :return: a tuple with the aggregation id and es_dsl aggregation object. Ex:\n                {\n                    \"cardinality\": {\n                        \"field\": <field>,\n                        \"precision_threshold\": 3000\n                }"
  },
  {
    "code": "def toggle_state(self, state, active=TOGGLE):\n        if active is TOGGLE:\n            active = not self.is_state(state)\n        if active:\n            self.set_state(state)\n        else:\n            self.remove_state(state)",
    "docstring": "Toggle the given state for this conversation.\n\n        The state will be set ``active`` is ``True``, otherwise the state will be removed.\n\n        If ``active`` is not given, it will default to the inverse of the current state\n        (i.e., ``False`` if the state is currently set, ``True`` if it is not; essentially\n        toggling the state).\n\n        For example::\n\n            conv.toggle_state('{relation_name}.foo', value=='foo')\n\n        This will set the state if ``value`` is equal to ``foo``."
  },
  {
    "code": "def attrs(self, dynamizer):\n        ret = {\n            self.key: {\n                'Action': self.action,\n            }\n        }\n        if not is_null(self.value):\n            ret[self.key]['Value'] = dynamizer.encode(self.value)\n        return ret",
    "docstring": "Get the attributes for the update"
  },
  {
    "code": "def decorator_of_context_manager(ctxt):\n    def decorator_fn(*outer_args, **outer_kwargs):\n        def decorator(fn):\n            @functools.wraps(fn)\n            def wrapper(*args, **kwargs):\n                with ctxt(*outer_args, **outer_kwargs):\n                    return fn(*args, **kwargs)\n            return wrapper\n        return decorator\n    if getattr(ctxt, \"__doc__\", None) is None:\n        msg = \"Decorator that runs the inner function in the context of %s\"\n        decorator_fn.__doc__ = msg % ctxt\n    else:\n        decorator_fn.__doc__ = ctxt.__doc__\n    return decorator_fn",
    "docstring": "Converts a context manager into a decorator.\n\n    This decorator will run the decorated function in the context of the\n    manager.\n\n    :param ctxt: Context to run the function in.\n    :return: Wrapper around the original function."
  },
  {
    "code": "def _parse_date(date):\n        result = ''.join(re.findall('\\d', date))\n        l = len(result)\n        if l in (2, 3, 4):\n            year = str(datetime.today().year)\n            return year + result\n        if l in (6, 7, 8):\n            return result\n        return ''",
    "docstring": "Parse from the user input `date`.\n\n        e.g. current year 2016:\n           input 6-26, 626, ... return 2016626\n           input 2016-6-26, 2016/6/26, ... retrun 2016626\n\n        This fn wouldn't check the date, it only gather the number as a string."
  },
  {
    "code": "def count_many(self, views, include=None):\n        return self._get(self._build_url(self.endpoint(count_many=views, include=include)))",
    "docstring": "Return many ViewCounts.\n\n        :param include: list of objects to sideload. `Side-loading API Docs \n            <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.\n        :param views: iterable of View or view ids"
  },
  {
    "code": "def get_app_template(name):\n    app_name, template_name = name.split(':')\n    return get_lookups()[app_name].get_template(template_name)",
    "docstring": "Getter function of templates for each applications.\n\n    Argument `name` will be interpreted as colon separated, the left value\n    means application name, right value means a template name.\n\n        get_app_template('blog:dashboarb.mako')\n\n    It will return a template for dashboard page of `blog` application."
  },
  {
    "code": "def get_contributors(self, subreddit, *args, **kwargs):\n        def get_contributors_helper(self, subreddit):\n            url = self.config['contributors'].format(\n                subreddit=six.text_type(subreddit))\n            return self._get_userlist(url, user_only=True, *args, **kwargs)\n        if self.is_logged_in():\n            if not isinstance(subreddit, objects.Subreddit):\n                subreddit = self.get_subreddit(subreddit)\n            if subreddit.subreddit_type == \"public\":\n                decorator = decorators.restrict_access(scope='read', mod=True)\n                return decorator(get_contributors_helper)(self, subreddit)\n        return get_contributors_helper(self, subreddit)",
    "docstring": "Return a get_content generator of contributors for the given subreddit.\n\n        If it's a public subreddit, then authentication as a\n        moderator of the subreddit is required. For protected/private\n        subreddits only access is required. See issue #246."
  },
  {
    "code": "def get_rml_processors(es_defs):\n    proc_defs = es_defs.get(\"kds_esRmlProcessor\", [])\n    if proc_defs:\n        new_defs = []\n        for proc in proc_defs:\n            params = proc['kds_rmlProcessorParams'][0]\n            proc_kwargs = {}\n            if params.get(\"kds_rtn_format\"):\n                proc_kwargs[\"rtn_format\"] = params.get(\"kds_rtn_format\")[0]\n            new_def = dict(name=proc['rdfs_label'][0],\n                           subj=params[\"kds_subjectKwarg\"][0],\n                           proc_kwargs=proc_kwargs,\n                           force=proc.get('kds_forceNested',[False])[0],\n                           processor=CFG.rml.get_processor(\\\n                                proc['rdfs_label'][0],\n                                proc['kds_esRmlMapping'],\n                                proc['rdf_type'][0]))\n            new_defs.append(new_def)\n        es_defs['kds_esRmlProcessor'] = new_defs\n    return es_defs",
    "docstring": "Returns the es_defs with the instaniated rml_processor\n\n    Args:\n    -----\n        es_defs: the rdf_class elacticsearch defnitions\n        cls_name: the name of the tied class"
  },
  {
    "code": "def compiled_hash_func(self):\n        def get_primary_key_str(pkey_name):\n            return \"str(self.{})\".format(pkey_name)\n        hash_str = \"+ \".join([get_primary_key_str(n) for n in self.primary_keys])\n        return ALCHEMY_TEMPLATES.hash_function.safe_substitute(concated_primary_key_strs=hash_str)",
    "docstring": "Returns compiled hash function based on hash of stringified primary_keys.\n        This isn't the most efficient way"
  },
  {
    "code": "def is_period_arraylike(arr):\n    if isinstance(arr, (ABCPeriodIndex, ABCPeriodArray)):\n        return True\n    elif isinstance(arr, (np.ndarray, ABCSeries)):\n        return is_period_dtype(arr.dtype)\n    return getattr(arr, 'inferred_type', None) == 'period'",
    "docstring": "Check whether an array-like is a periodical array-like or PeriodIndex.\n\n    Parameters\n    ----------\n    arr : array-like\n        The array-like to check.\n\n    Returns\n    -------\n    boolean\n        Whether or not the array-like is a periodical array-like or\n        PeriodIndex instance.\n\n    Examples\n    --------\n    >>> is_period_arraylike([1, 2, 3])\n    False\n    >>> is_period_arraylike(pd.Index([1, 2, 3]))\n    False\n    >>> is_period_arraylike(pd.PeriodIndex([\"2017-01-01\"], freq=\"D\"))\n    True"
  },
  {
    "code": "def _all_tables_present(self, txn):\n        conn = txn.connect()\n        for table_name in asset_db_table_names:\n            if txn.dialect.has_table(conn, table_name):\n                return True\n        return False",
    "docstring": "Checks if any tables are present in the current assets database.\n\n        Parameters\n        ----------\n        txn : Transaction\n            The open transaction to check in.\n\n        Returns\n        -------\n        has_tables : bool\n            True if any tables are present, otherwise False."
  },
  {
    "code": "def load_script(filename):\n    path, module_name, ext = _extract_script_components(filename)\n    add_search_path(path)\n    return _load_module(module_name)",
    "docstring": "Loads a python script as a module.\n\n    This function is provided to allow applications to load a Python module by its file name.\n\n    :param string filename:\n        Name of the python file to be loaded as a module.\n\n    :return:\n        A |Python|_ module loaded from the specified file."
  },
  {
    "code": "def _save_token_on_disk(self):\n        token = self._token.copy()\n        token.update(client_secret=self._client_secret)\n        with codecs.open(config.TOKEN_FILE_PATH, 'w', 'utf8') as f:\n            json.dump(\n                token, f,\n                ensure_ascii=False,\n                sort_keys=True,\n                indent=4,\n            )",
    "docstring": "Helper function that saves the token on disk"
  },
  {
    "code": "def clean(self):\n        with self.mutex:\n            now = time.time()\n            if self.last_clean_time + self.CLEAN_INTERVAL < now:\n                to_remove = []\n                for (host, pool) in self.host_to_pool.items():\n                    pool.clean()\n                    if pool.size() == 0:\n                        to_remove.append(host)\n                for host in to_remove:\n                    del self.host_to_pool[host]\n                self.last_clean_time = now",
    "docstring": "Clean up the stale connections in all of the pools, and then\n        get rid of empty pools.  Pools clean themselves every time a\n        connection is fetched; this cleaning takes care of pools that\n        aren't being used any more, so nothing is being gotten from\n        them."
  },
  {
    "code": "def reboot(name, conn=None):\n    if not conn:\n        conn = get_conn()\n    node = get_node(conn, name)\n    if node is None:\n        log.error('Unable to find the VM %s', name)\n    log.info('Rebooting VM: %s', name)\n    ret = conn.reboot_node(node)\n    if ret:\n        log.info('Rebooted VM: %s', name)\n        __utils__['cloud.fire_event'](\n            'event',\n            '{0} has been rebooted'.format(name), 'salt-cloud'\n            'salt/cloud/{0}/rebooting'.format(name),\n            args={'name': name},\n            sock_dir=__opts__['sock_dir'],\n            transport=__opts__['transport']\n        )\n        return True\n    log.error('Failed to reboot VM: %s', name)\n    return False",
    "docstring": "Reboot a single VM"
  },
  {
    "code": "def add_child(self, valid_policy, qualifier_set, expected_policy_set):\n        child = PolicyTreeNode(valid_policy, qualifier_set, expected_policy_set)\n        child.parent = self\n        self.children.append(child)",
    "docstring": "Creates a new PolicyTreeNode as a child of this node\n\n        :param valid_policy:\n            A unicode string of a policy name or OID\n\n        :param qualifier_set:\n            An instance of asn1crypto.x509.PolicyQualifierInfos\n\n        :param expected_policy_set:\n            A set of unicode strings containing policy names or OIDs"
  },
  {
    "code": "def parent(self):\n        if self._parent is None:\n            if self.pid is not None:\n                self._parent = self.api._load_directory(self.pid)\n        return self._parent",
    "docstring": "Parent directory that holds this directory"
  },
  {
    "code": "def do_HEAD(self):\n        self.do_initial_operations()\n        coap_response = self.client.get(self.coap_uri.path)\n        self.client.stop()\n        logger.info(\"Server response: %s\", coap_response.pretty_print())\n        self.set_http_header(coap_response)",
    "docstring": "Perform a HEAD request"
  },
  {
    "code": "def visit_SetComp(self, node: ast.SetComp) -> Any:\n        result = self._execute_comprehension(node=node)\n        for generator in node.generators:\n            self.visit(generator.iter)\n        self.recomputed_values[node] = result\n        return result",
    "docstring": "Compile the set comprehension as a function and call it."
  },
  {
    "code": "def _import_module(self, module_path):\n        LOGGER.debug('Importing %s', module_path)\n        try:\n            return __import__(module_path)\n        except ImportError as error:\n            LOGGER.critical('Could not import %s: %s', module_path, error)\n            return None",
    "docstring": "Dynamically import a module returning a handle to it.\n\n        :param str module_path: The module path\n        :rtype: module"
  },
  {
    "code": "def _GetRelPath(self, filename):\n\t\tassert filename.startswith(self.subdir), (filename, self.subdir)\n\t\treturn filename[len(self.subdir):].lstrip(r\"\\/\")",
    "docstring": "Get relative path of a file according to the current directory,\n\t\tgiven its logical path in the repo."
  },
  {
    "code": "def reduce_multiline(string):\n    string = str(string)\n    return \" \".join([item.strip()\n                     for item in string.split(\"\\n\")\n                     if item.strip()])",
    "docstring": "reduces a multiline string to a single line of text.\n\n\n    args:\n        string: the text to reduce"
  },
  {
    "code": "def _get_update_fn(strategy):\n    if strategy is None:\n        strategy = MS_DICTS\n    try:\n        return _MERGE_FNS[strategy]\n    except KeyError:\n        if callable(strategy):\n            return strategy\n        raise ValueError(\"Wrong merge strategy: %r\" % strategy)",
    "docstring": "Select dict-like class based on merge strategy and orderness of keys.\n\n    :param merge: Specify strategy from MERGE_STRATEGIES of how to merge dicts.\n    :return: Callable to update objects"
  },
  {
    "code": "def MigrateArtifacts():\n  artifacts = data_store.REL_DB.ReadAllArtifacts()\n  if artifacts:\n    logging.info(\"Deleting %d artifacts from REL_DB.\", len(artifacts))\n    for artifact in data_store.REL_DB.ReadAllArtifacts():\n      data_store.REL_DB.DeleteArtifact(Text(artifact.name))\n  else:\n    logging.info(\"No artifacts found in REL_DB.\")\n  artifacts = artifact_registry.REGISTRY.GetArtifacts(\n      reload_datastore_artifacts=True)\n  logging.info(\"Found %d artifacts in AFF4.\", len(artifacts))\n  artifacts = list(filter(_IsCustom, artifacts))\n  logging.info(\"Migrating %d user-created artifacts.\", len(artifacts))\n  for artifact in artifacts:\n    _MigrateArtifact(artifact)",
    "docstring": "Migrates Artifacts from AFF4 to REL_DB."
  },
  {
    "code": "def check_keypoints(keypoints, rows, cols):\n    for kp in keypoints:\n        check_keypoint(kp, rows, cols)",
    "docstring": "Check if keypoints boundaries are in range [0, 1)"
  },
  {
    "code": "def date_elem(ind_days, ind_minutes):\n    def inner(seq):\n        return nexrad_to_datetime(seq[ind_days], seq[ind_minutes] * 60 * 1000)\n    return inner",
    "docstring": "Create a function to parse a datetime from the product-specific blocks."
  },
  {
    "code": "def fresh(t, non_generic):\n    mappings = {}\n    def freshrec(tp):\n        p = prune(tp)\n        if isinstance(p, TypeVariable):\n            if is_generic(p, non_generic):\n                if p not in mappings:\n                    mappings[p] = TypeVariable()\n                return mappings[p]\n            else:\n                return p\n        elif isinstance(p, dict):\n            return p\n        elif isinstance(p, Collection):\n            return Collection(*[freshrec(x) for x in p.types])\n        elif isinstance(p, Scalar):\n            return Scalar([freshrec(x) for x in p.types])\n        elif isinstance(p, TypeOperator):\n            return TypeOperator(p.name, [freshrec(x) for x in p.types])\n        elif isinstance(p, MultiType):\n            return MultiType([freshrec(x) for x in p.types])\n        else:\n            assert False, \"missing freshrec case {}\".format(type(p))\n    return freshrec(t)",
    "docstring": "Makes a copy of a type expression.\n\n    The type t is copied. The generic variables are duplicated and the\n    non_generic variables are shared.\n\n    Args:\n        t: A type to be copied.\n        non_generic: A set of non-generic TypeVariables"
  },
  {
    "code": "def overrules(self, other):\n        if other.is_primary():\n            return False\n        elif self.is_simple_index() and other.is_unique():\n            return False\n        same_columns = self.spans_columns(other.get_columns())\n        if (\n            same_columns\n            and (self.is_primary() or self.is_unique())\n            and self.same_partial_index(other)\n        ):\n            return True\n        return False",
    "docstring": "Detects if the other index is a non-unique, non primary index\n        that can be overwritten by this one.\n\n        :param other: The other index\n        :type other: Index\n\n        :rtype: bool"
  },
  {
    "code": "def finalcallback(request, **kwargs):\n    default_provider.load_services()\n    service_name = kwargs.get('service_name')\n    service_object = default_provider.get_service(service_name)\n    lets_callback = getattr(service_object, 'callback')\n    return render_to_response(lets_callback(request))",
    "docstring": "let's do the callback of the related service after\n        the auth request from UserServiceCreateView"
  },
  {
    "code": "def _ReadEncryptedData(self, read_size):\n    encrypted_data = self._file_object.read(read_size)\n    read_count = len(encrypted_data)\n    self._encrypted_data = b''.join([self._encrypted_data, encrypted_data])\n    self._decrypted_data, self._encrypted_data = (\n        self._decrypter.Decrypt(self._encrypted_data))\n    self._decrypted_data_size = len(self._decrypted_data)\n    return read_count",
    "docstring": "Reads encrypted data from the file-like object.\n\n    Args:\n      read_size (int): number of bytes of encrypted data to read.\n\n    Returns:\n      int: number of bytes of encrypted data read."
  },
  {
    "code": "def _check_radians(value, max_radians=2 * np.pi):\n    try:\n        value = value.to('radians').m\n    except AttributeError:\n        pass\n    if np.greater(np.nanmax(np.abs(value)), max_radians):\n        warnings.warn('Input over {} radians. '\n                      'Ensure proper units are given.'.format(max_radians))\n    return value",
    "docstring": "Input validation of values that could be in degrees instead of radians.\n\n    Parameters\n    ----------\n    value : `pint.Quantity`\n        The input value to check.\n\n    max_radians : float\n        Maximum absolute value of radians before warning.\n\n    Returns\n    -------\n    `pint.Quantity`\n        The input value"
  },
  {
    "code": "async def stderr(self) -> AsyncGenerator[str, None]:\n        await self.wait_running()\n        async for line in self._subprocess.stderr:\n            yield line",
    "docstring": "Asynchronous generator for lines from subprocess stderr."
  },
  {
    "code": "def render_block_to_string(template_name, block_name, context=None):\n    if isinstance(template_name, (tuple, list)):\n        t = loader.select_template(template_name)\n    else:\n        t = loader.get_template(template_name)\n    context = context or {}\n    if isinstance(t, DjangoTemplate):\n        return django_render_block(t, block_name, context)\n    elif isinstance(t, Jinja2Template):\n        from render_block.jinja2 import jinja2_render_block\n        return jinja2_render_block(t, block_name, context)\n    else:\n        raise UnsupportedEngine(\n            'Can only render blocks from the Django template backend.')",
    "docstring": "Loads the given template_name and renders the given block with the given\n    dictionary as context. Returns a string.\n\n        template_name\n            The name of the template to load and render. If it's a list of\n            template names, Django uses select_template() instead of\n            get_template() to find the template."
  },
  {
    "code": "def cli(env, sortby, datacenter):\n    block_manager = SoftLayer.BlockStorageManager(env.client)\n    mask = \"mask[serviceResource[datacenter[name]],\"\\\n           \"replicationPartners[serviceResource[datacenter[name]]]]\"\n    block_volumes = block_manager.list_block_volumes(datacenter=datacenter,\n                                                     mask=mask)\n    datacenters = dict()\n    for volume in block_volumes:\n        service_resource = volume['serviceResource']\n        if 'datacenter' in service_resource:\n            datacenter_name = service_resource['datacenter']['name']\n            if datacenter_name not in datacenters.keys():\n                datacenters[datacenter_name] = 1\n            else:\n                datacenters[datacenter_name] += 1\n    table = formatting.KeyValueTable(DEFAULT_COLUMNS)\n    table.sortby = sortby\n    for datacenter_name in datacenters:\n        table.add_row([datacenter_name, datacenters[datacenter_name]])\n    env.fout(table)",
    "docstring": "List number of block storage volumes per datacenter."
  },
  {
    "code": "def indication(self, apdu):\n        if _debug: ServerSSM._debug(\"indication %r\", apdu)\n        if self.state == IDLE:\n            self.idle(apdu)\n        elif self.state == SEGMENTED_REQUEST:\n            self.segmented_request(apdu)\n        elif self.state == AWAIT_RESPONSE:\n            self.await_response(apdu)\n        elif self.state == SEGMENTED_RESPONSE:\n            self.segmented_response(apdu)\n        else:\n            if _debug: ServerSSM._debug(\"    - invalid state\")",
    "docstring": "This function is called for each downstream packet related to\n        the transaction."
  },
  {
    "code": "def save(self):\n        active_language = get_language()\n        for (name, value) in self.cleaned_data.items():\n            if name not in registry:\n                name, code = name.rsplit('_modeltranslation_', 1)\n            else:\n                code = None\n            setting_obj, created = Setting.objects.get_or_create(name=name)\n            if settings.USE_MODELTRANSLATION:\n                if registry[name][\"translatable\"]:\n                    try:\n                        activate(code)\n                    except:\n                        pass\n                    finally:\n                        setting_obj.value = value\n                        activate(active_language)\n                else:\n                    for code in OrderedDict(settings.LANGUAGES):\n                        setattr(setting_obj,\n                                build_localized_fieldname('value', code),\n                                value)\n            else:\n                setting_obj.value = value\n            setting_obj.save()",
    "docstring": "Save each of the settings to the DB."
  },
  {
    "code": "def drug_names_to_generic(drugs: List[str],\n                          unknown_to_default: bool = False,\n                          default: str = None,\n                          include_categories: bool = False) -> List[str]:\n    return [\n        drug_name_to_generic(drug,\n                             unknown_to_default=unknown_to_default,\n                             default=default,\n                             include_categories=include_categories)\n        for drug in drugs\n    ]",
    "docstring": "Converts a list of drug names to their generic equivalents.\n\n    The arguments are as for :func:`drug_name_to_generic` but this function\n    handles a list of drug names rather than a single one.\n\n    Note in passing the following conversion of blank-type representations from\n    R via ``reticulate``, when using e.g. the ``default`` parameter and storing\n    results in a ``data.table()`` character column:\n\n    .. code-block:: none\n\n        ------------------------------  ----------------\n        To Python                       Back from Python\n        ------------------------------  ----------------\n        [not passed, so Python None]    \"NULL\"\n        NULL                            \"NULL\"\n        NA_character_                   \"NA\"\n        NA                              TRUE (logical)\n        ------------------------------  ----------------"
  },
  {
    "code": "def _split_op(\n            self, identifier, hs_label=None, dagger=False, args=None):\n        if self._isinstance(identifier, 'SymbolicLabelBase'):\n            identifier = QnetAsciiDefaultPrinter()._print_SCALAR_TYPES(\n                identifier.expr)\n        name, total_subscript = self._split_identifier(identifier)\n        total_superscript = ''\n        if (hs_label not in [None, '']):\n            if self._settings['show_hs_label'] == 'subscript':\n                if len(total_subscript) == 0:\n                    total_subscript = '(' + hs_label + ')'\n                else:\n                    total_subscript += ',(' + hs_label + ')'\n            else:\n                total_superscript += '(' + hs_label + ')'\n        if dagger:\n            total_superscript += self._dagger_sym\n        args_str = ''\n        if (args is not None) and (len(args) > 0):\n            args_str = (self._parenth_left +\n                        \",\".join([self.doprint(arg) for arg in args]) +\n                        self._parenth_right)\n        return name, total_subscript, total_superscript, args_str",
    "docstring": "Return `name`, total `subscript`, total `superscript` and\n        `arguments` str. All of the returned strings are fully rendered.\n\n        Args:\n            identifier (str or SymbolicLabelBase): A (non-rendered/ascii)\n                identifier that may include a subscript. The output `name` will\n                be the `identifier` without any subscript\n            hs_label (str): The rendered label for the Hilbert space of the\n                operator, or None. Returned unchanged.\n            dagger (bool): Flag to indicate whether the operator is daggered.\n                If True, :attr:`dagger_sym` will be included in the\n                `superscript` (or  `subscript`, depending on the settings)\n            args (list or None): List of arguments (expressions). Each element\n                will be rendered with :meth:`doprint`. The total list of args\n                will then be joined with commas, enclosed\n                with :attr:`_parenth_left` and :attr:`parenth_right`, and\n                returnd as the `arguments` string"
  },
  {
    "code": "def run(path, tasks):\n\treadable_path = make_readable_path(path)\n\tif not os.path.isfile(path):\n\t\tlogger.log(logger.red(\"Can't read pylpfile \"), logger.magenta(readable_path))\n\t\tsys.exit(-1)\n\telse:\n\t\tlogger.log(\"Using pylpfile \", logger.magenta(readable_path))\n\ttry:\n\t\trunpy.run_path(path, None, \"pylpfile\")\n\texcept Exception as e:\n\t\ttraceback.print_exc(file=sys.stdout)\n\t\tlogger.log(logger.red(\"\\nAn error has occurred during the execution of the pylpfile\"))\n\t\tsys.exit(-1)\n\tfor name in tasks:\n\t\tpylp.start(name)\n\tloop = asyncio.get_event_loop()\n\tloop.run_until_complete(wait_and_quit(loop))",
    "docstring": "Run a pylpfile."
  },
  {
    "code": "def assignLeafRegisters(inodes, registerMaker):\n    leafRegisters = {}\n    for node in inodes:\n        key = node.key()\n        if key in leafRegisters:\n            node.reg = leafRegisters[key]\n        else:\n            node.reg = leafRegisters[key] = registerMaker(node)",
    "docstring": "Assign new registers to each of the leaf nodes."
  },
  {
    "code": "def complete_use(self, text, *_):\n        return [t + \" \" for t in REGIONS if t.startswith(text)]",
    "docstring": "Autocomplete for use"
  },
  {
    "code": "def compile_state_cpfs(self,\n                           scope: Dict[str, TensorFluent],\n                           batch_size: Optional[int] = None,\n                           noise: Optional[Noise] = None) -> List[CPFPair]:\n        next_state_fluents = []\n        with self.graph.as_default():\n            with tf.name_scope('state_cpfs'):\n                for cpf in self.rddl.domain.state_cpfs:\n                    cpf_noise = noise.get(cpf.name, None) if noise is not None else None\n                    name_scope = utils.identifier(cpf.name)\n                    with tf.name_scope(name_scope):\n                        t = self._compile_expression(cpf.expr, scope, batch_size, cpf_noise)\n                    next_state_fluents.append((cpf.name, t))\n                key = lambda f: self.rddl.domain.next_state_fluent_ordering.index(f[0])\n                next_state_fluents = sorted(next_state_fluents, key=key)\n        return next_state_fluents",
    "docstring": "Compiles the next state fluent CPFs given the current `state` and `action` scope.\n\n        Args:\n            scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): The fluent scope for CPF evaluation.\n            batch_size (Optional[int]): The batch size.\n\n        Returns:\n            A list of state fluent CPFs compiled to :obj:`rddl2tf.fluent.TensorFluent`."
  },
  {
    "code": "def loads(s, encoding=None, cls=JSONTreeDecoder, object_hook=None,\n         parse_float=None, parse_int=None, parse_constant=None,\n         object_pairs_hook=None, **kargs):\n    return json.loads(s, encoding, cls, object_hook,\n         parse_float, parse_int, parse_constant,\n         object_pairs_hook, **kargs)",
    "docstring": "JSON load from string function that defaults the loading class to be\n    JSONTreeDecoder"
  },
  {
    "code": "def traverse_levelorder(self, leaves=True, internal=True):\n        q = deque(); q.append(self)\n        while len(q) != 0:\n            n = q.popleft()\n            if (leaves and n.is_leaf()) or (internal and not n.is_leaf()):\n                yield n\n            q.extend(n.children)",
    "docstring": "Perform a levelorder traversal starting at this ``Node`` object\n\n        Args:\n            ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``\n\n            ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``"
  },
  {
    "code": "def do_init(argdict):\n    site = make_site_obj(argdict)\n    try:\n        site.init_structure()\n        print \"Initialized directory.\"\n        if argdict['randomsite']:\n            for i in range(1,argdict['numpages']+1):\n                p = site.random_page()\n                p.set_published()\n                p.write()\n                print \"added page \",p.slug\n    except ValueError:\n        print \"Cannot create structure. You're already within an s2 \\\ntree, or the directory is not empty or it is not writeable. \"",
    "docstring": "Create the structure of a s2site."
  },
  {
    "code": "def refresh(self, **kwargs):\n        self.resource.refresh(**kwargs)\n        self.rdict = self.resource.entries\n        self._update_stats()",
    "docstring": "Refreshes stats attached to an object"
  },
  {
    "code": "def star_assign_item_check(self, original, loc, tokens):\n        return self.check_py(\"3\", \"starred assignment (add 'match' to front to produce universal code)\", original, loc, tokens)",
    "docstring": "Check for Python 3 starred assignment."
  },
  {
    "code": "def getCoeffStr(self):\r\n        txt = ''\r\n        for key, val in self.coeffs.items():\r\n            txt += '%s = %s\\n' % (key, val)\r\n        return txt",
    "docstring": "get the distortion coeffs in a formated string"
  },
  {
    "code": "def list(ctx):\n    log.debug('chemdataextractor.config.list')\n    for k in config:\n        click.echo('%s : %s' % (k, config[k]))",
    "docstring": "List all config values."
  },
  {
    "code": "def _draw_ellipse(data, obj, draw_options):\n    if isinstance(obj, mpl.patches.Circle):\n        return _draw_circle(data, obj, draw_options)\n    x, y = obj.center\n    ff = data[\"float format\"]\n    if obj.angle != 0:\n        fmt = \"rotate around={{\" + ff + \":(axis cs:\" + ff + \",\" + ff + \")}}\"\n        draw_options.append(fmt.format(obj.angle, x, y))\n    cont = (\n        \"\\\\draw[{}] (axis cs:\"\n        + ff\n        + \",\"\n        + ff\n        + \") ellipse (\"\n        + ff\n        + \" and \"\n        + ff\n        + \");\\n\"\n    ).format(\",\".join(draw_options), x, y, 0.5 * obj.width, 0.5 * obj.height)\n    return data, cont",
    "docstring": "Return the PGFPlots code for ellipses."
  },
  {
    "code": "def _resume_with_session_ticket(\n            self,\n            server_info: ServerConnectivityInfo,\n            ssl_version_to_use: OpenSslVersionEnum,\n    ) -> TslSessionTicketSupportEnum:\n        try:\n            session1 = self._resume_ssl_session(server_info, ssl_version_to_use, should_enable_tls_ticket=True)\n        except SslHandshakeRejected:\n            if server_info.highest_ssl_version_supported >= OpenSslVersionEnum.TLSV1_3:\n                return TslSessionTicketSupportEnum.FAILED_ONLY_TLS_1_3_SUPPORTED\n            else:\n                raise\n        try:\n            session1_tls_ticket = self._extract_tls_session_ticket(session1)\n        except IndexError:\n            return TslSessionTicketSupportEnum.FAILED_TICKET_NOT_ASSIGNED\n        session2 = self._resume_ssl_session(server_info, ssl_version_to_use, session1, should_enable_tls_ticket=True)\n        try:\n            session2_tls_ticket = self._extract_tls_session_ticket(session2)\n        except IndexError:\n            return TslSessionTicketSupportEnum.FAILED_TICKET_NOT_ASSIGNED\n        if session1_tls_ticket != session2_tls_ticket:\n            return TslSessionTicketSupportEnum.FAILED_TICKED_IGNORED\n        return TslSessionTicketSupportEnum.SUCCEEDED",
    "docstring": "Perform one session resumption using TLS Session Tickets."
  },
  {
    "code": "def error(message, *args, **kwargs):\n    print('[!] ' + message.format(*args, **kwargs))\n    sys.exit(1)",
    "docstring": "print an error message"
  },
  {
    "code": "def deactivate(self):\n        try:\n            self.phase = PHASE.DEACTIVATE\n            self.logger.info(\"Deactivating environment %s...\" % self.namespace)\n            self.directory.rewrite_config = False\n            self.instantiate_features()\n            self._specialize()\n            for feature in self.features.run_order:\n                self.logger.info(\"Deactivating %s...\" % feature[0])\n                self.run_action(feature, 'deactivate')\n            self.clear_all()\n            self._finalize()\n        except Exception:\n            self.logger.debug(\"\", exc_info=sys.exc_info())\n            et, ei, tb = sys.exc_info()\n            reraise(et, ei, tb)",
    "docstring": "deactivate the environment"
  },
  {
    "code": "def get_project(self, project_short_name):\n        project = pbclient.find_project(short_name=project_short_name,\n                                        all=self.all)\n        if (len(project) == 1):\n            return project[0]\n        else:\n            raise ProjectNotFound(project_short_name)",
    "docstring": "Return project object."
  },
  {
    "code": "def __filename(self, id):\n        suffix = self.fnsuffix()\n        filename = \"%s-%s.%s\" % (self.fnprefix, id, suffix)\n        return os.path.join(self.location, filename)",
    "docstring": "Return the cache file name for an entry with a given id."
  },
  {
    "code": "def _der_to_pem(der_key, marker):\n    pem_key_chunks = [('-----BEGIN %s-----' % marker).encode('utf-8')]\n    for chunk_start in range(0, len(der_key), 48):\n        pem_key_chunks.append(b64encode(der_key[chunk_start:chunk_start + 48]))\n    pem_key_chunks.append(('-----END %s-----' % marker).encode('utf-8'))\n    return b'\\n'.join(pem_key_chunks)",
    "docstring": "Perform a simple DER to PEM conversion."
  },
  {
    "code": "def handle_json_GET_neareststops(self, params):\n    schedule = self.server.schedule\n    lat = float(params.get('lat'))\n    lon = float(params.get('lon'))\n    limit = int(params.get('limit'))\n    stops = schedule.GetNearestStops(lat=lat, lon=lon, n=limit)\n    return [StopToTuple(s) for s in stops]",
    "docstring": "Return a list of the nearest 'limit' stops to 'lat', 'lon"
  },
  {
    "code": "def get_method(self, name, arg_types=()):\n        arg_types = tuple(arg_types)\n        for m in self.get_methods_by_name(name):\n            if (((not m.is_bridge()) and\n                 m.get_arg_type_descriptors() == arg_types)):\n                return m\n        return None",
    "docstring": "searches for the method matching the name and having argument type\n        descriptors matching those in arg_types.\n\n        Parameters\n        ==========\n        arg_types : sequence of strings\n          each string is a parameter type, in the non-pretty format.\n\n        Returns\n        =======\n        method : `JavaMemberInfo` or `None`\n          the single matching, non-bridging method of matching name\n          and parameter types."
  },
  {
    "code": "def update_aliases(self):\n        try:\n            response = self.client.api.get_room_state(self.room_id)\n            for chunk in response:\n                if \"content\" in chunk and \"aliases\" in chunk[\"content\"]:\n                    if chunk[\"content\"][\"aliases\"] != self.aliases:\n                        self.aliases = chunk[\"content\"][\"aliases\"]\n                        return True\n                    else:\n                        return False\n        except MatrixRequestError:\n            return False",
    "docstring": "Get aliases information from room state.\n\n        Returns:\n            boolean: True if the aliases changed, False if not"
  },
  {
    "code": "def record_ce_entries(self):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not yet initialized')\n        return self._record(self.ce_entries)",
    "docstring": "Return a string representing the Rock Ridge entries in the Continuation Entry.\n\n        Parameters:\n         None.\n        Returns:\n         A string representing the Rock Ridge entry."
  },
  {
    "code": "def network_profiles(self):\n        profiles = self._wifi_ctrl.network_profiles(self._raw_obj)\n        if self._logger.isEnabledFor(logging.INFO):\n            for profile in profiles:\n                self._logger.info(\"Get profile:\")\n                self._logger.info(\"\\tssid: %s\", profile.ssid)\n                self._logger.info(\"\\tauth: %s\", profile.auth)\n                self._logger.info(\"\\takm: %s\", profile.akm)\n                self._logger.info(\"\\tcipher: %s\", profile.cipher)\n        return profiles",
    "docstring": "Get all the AP profiles."
  },
  {
    "code": "def get_src_builders(self, env):\n        memo_key = id(env)\n        try:\n            memo_dict = self._memo['get_src_builders']\n        except KeyError:\n            memo_dict = {}\n            self._memo['get_src_builders'] = memo_dict\n        else:\n            try:\n                return memo_dict[memo_key]\n            except KeyError:\n                pass\n        builders = []\n        for bld in self.src_builder:\n            if SCons.Util.is_String(bld):\n                try:\n                    bld = env['BUILDERS'][bld]\n                except KeyError:\n                    continue\n            builders.append(bld)\n        memo_dict[memo_key] = builders\n        return builders",
    "docstring": "Returns the list of source Builders for this Builder.\n\n        This exists mainly to look up Builders referenced as\n        strings in the 'BUILDER' variable of the construction\n        environment and cache the result."
  },
  {
    "code": "def is_owner(package, abspath):\n    try:\n        files = package['files']\n        location = package['location']\n    except KeyError:\n        return False\n    paths = (os.path.abspath(os.path.join(location, f))\n             for f in files)\n    return abspath in paths",
    "docstring": "Determine whether `abspath` belongs to `package`."
  },
  {
    "code": "def clear(self):\n        self.erase()\n        output = self.output\n        output.erase_screen()\n        output.cursor_goto(0, 0)\n        output.flush()\n        self.request_absolute_cursor_position()",
    "docstring": "Clear screen and go to 0,0"
  },
  {
    "code": "def num_data(self):\n        if self.handle is not None:\n            ret = ctypes.c_int()\n            _safe_call(_LIB.LGBM_DatasetGetNumData(self.handle,\n                                                   ctypes.byref(ret)))\n            return ret.value\n        else:\n            raise LightGBMError(\"Cannot get num_data before construct dataset\")",
    "docstring": "Get the number of rows in the Dataset.\n\n        Returns\n        -------\n        number_of_rows : int\n            The number of rows in the Dataset."
  },
  {
    "code": "def rebuild_config_cache(self, config_filepath):\n        self.validate_config_file(config_filepath)\n        config_data = None\n        try:\n            with open(config_filepath, 'r') as f:\n                config_data = yaml.load(f)\n            items = list(iteritems(config_data))\n        except AttributeError:\n            items = list(config_data)\n        self.config_file_contents = OrderedDict(sorted(items, key=lambda x: x[0], reverse=True))\n        self.config_filepath = config_filepath",
    "docstring": "Loads from file and caches all data from the config file in the form of an OrderedDict to self.data\n\n        :param config_filepath: str, the full filepath to the config file\n        :return: bool, success status"
  },
  {
    "code": "def get_all_credit_notes(self, params=None):\n        if not params:\n            params = {}\n        return self._iterate_through_pages(self.get_credit_notes_per_page, resource=CREDIT_NOTES, **{'params': params})",
    "docstring": "Get all credit notes\n        This will iterate over all pages until it gets all elements.\n        So if the rate limit exceeded it will throw an Exception and you will get nothing\n\n        :param params: search params\n        :return: list"
  },
  {
    "code": "def _StartMonitoringProcess(self, process):\n    if process is None:\n      raise ValueError('Missing process.')\n    pid = process.pid\n    if pid in self._process_information_per_pid:\n      raise KeyError(\n          'Already monitoring process (PID: {0:d}).'.format(pid))\n    if pid in self._rpc_clients_per_pid:\n      raise KeyError(\n          'RPC client (PID: {0:d}) already exists'.format(pid))\n    rpc_client = plaso_xmlrpc.XMLProcessStatusRPCClient()\n    rpc_port = process.rpc_port.value\n    time_waited_for_process = 0.0\n    while not rpc_port:\n      time.sleep(0.1)\n      rpc_port = process.rpc_port.value\n      time_waited_for_process += 0.1\n      if time_waited_for_process >= self._RPC_SERVER_TIMEOUT:\n        raise IOError(\n            'RPC client unable to determine server (PID: {0:d}) port.'.format(\n                pid))\n    hostname = 'localhost'\n    if not rpc_client.Open(hostname, rpc_port):\n      raise IOError((\n          'RPC client unable to connect to server (PID: {0:d}) '\n          'http://{1:s}:{2:d}').format(pid, hostname, rpc_port))\n    self._rpc_clients_per_pid[pid] = rpc_client\n    self._process_information_per_pid[pid] = process_info.ProcessInfo(pid)",
    "docstring": "Starts monitoring a process.\n\n    Args:\n      process (MultiProcessBaseProcess): process.\n\n    Raises:\n      IOError: if the RPC client cannot connect to the server.\n      KeyError: if the process is not registered with the engine or\n          if the process is already being monitored.\n      OSError: if the RPC client cannot connect to the server.\n      ValueError: if the process is missing."
  },
  {
    "code": "def _claim_in_progress_and_claim_channels(self, grpc_channel, channels):\n        payments = self._call_GetListInProgress(grpc_channel)\n        if (len(payments) > 0):\n            self._printout(\"There are %i payments in 'progress' (they haven't been claimed in blockchain). We will claim them.\"%len(payments))\n            self._blockchain_claim(payments)\n        payments = self._start_claim_channels(grpc_channel, channels)\n        self._blockchain_claim(payments)",
    "docstring": "Claim all 'pending' payments in progress and after we claim given channels"
  },
  {
    "code": "def doc_params(**kwds):\n    def dec(obj):\n        obj.__doc__ = dedent(obj.__doc__).format(**kwds)\n        return obj\n    return dec",
    "docstring": "\\\n    Docstrings should start with \"\\\" in the first line for proper formatting."
  },
  {
    "code": "def init_logger(self):\n        if not self.result_logger:\n            if not os.path.exists(self.local_dir):\n                os.makedirs(self.local_dir)\n            if not self.logdir:\n                self.logdir = tempfile.mkdtemp(\n                    prefix=\"{}_{}\".format(\n                        str(self)[:MAX_LEN_IDENTIFIER], date_str()),\n                    dir=self.local_dir)\n            elif not os.path.exists(self.logdir):\n                os.makedirs(self.logdir)\n            self.result_logger = UnifiedLogger(\n                self.config,\n                self.logdir,\n                upload_uri=self.upload_dir,\n                loggers=self.loggers,\n                sync_function=self.sync_function)",
    "docstring": "Init logger."
  },
  {
    "code": "def _send_register_payload(self, websocket):\n        file = os.path.join(os.path.dirname(__file__), HANDSHAKE_FILE_NAME)\n        data = codecs.open(file, 'r', 'utf-8')\n        raw_handshake = data.read()\n        handshake = json.loads(raw_handshake)\n        handshake['payload']['client-key'] = self.client_key\n        yield from websocket.send(json.dumps(handshake))\n        raw_response = yield from websocket.recv()\n        response = json.loads(raw_response)\n        if response['type'] == 'response' and \\\n                        response['payload']['pairingType'] == 'PROMPT':\n            raw_response = yield from websocket.recv()\n            response = json.loads(raw_response)\n            if response['type'] == 'registered':\n                self.client_key = response['payload']['client-key']\n                self.save_key_file()",
    "docstring": "Send the register payload."
  },
  {
    "code": "def to_grayscale(cv2im):\n    grayscale_im = np.sum(np.abs(cv2im), axis=0)\n    im_max = np.percentile(grayscale_im, 99)\n    im_min = np.min(grayscale_im)\n    grayscale_im = np.clip((grayscale_im - im_min) / (im_max - im_min), 0, 1)\n    grayscale_im = np.expand_dims(grayscale_im, axis=0)\n    return grayscale_im",
    "docstring": "Convert gradients to grayscale. This gives a saliency map."
  },
  {
    "code": "def compact(text, **kw):\n    return '\\n\\n'.join(' '.join(p.split()) for p in text.split('\\n\\n')).format(**kw)",
    "docstring": "Compact whitespace in a string and format any keyword arguments into the string.\n\n    :param text: The text to compact (a string).\n    :param kw: Any keyword arguments to apply using :func:`str.format()`.\n    :returns: The compacted, formatted string.\n\n    The whitespace compaction preserves paragraphs."
  },
  {
    "code": "def set_current_session(session_id) -> bool:\r\n        try:\r\n            g.session_id = session_id\r\n            return True\r\n        except (Exception, BaseException) as error:\r\n            if current_app.config['DEBUG']:\r\n                print(error)\r\n            return False",
    "docstring": "Add session_id to flask globals for current request"
  },
  {
    "code": "def _check_inclusions(self, f, domains=None):\n        filename = f if isinstance(f, six.string_types) else f.path\n        if domains is None:\n            domains = list(self.domains.values())\n        domains = list(domains)\n        domains.insert(0, self)\n        for dom in domains:\n            if dom.include:\n                for regex in dom.include:\n                    if re.search(regex, filename):\n                        return True\n                return False\n            else:\n                for regex in dom.exclude:\n                    if re.search(regex, filename, flags=re.UNICODE):\n                        return False\n        return True",
    "docstring": "Check file or directory against regexes in config to determine if\n            it should be included in the index"
  },
  {
    "code": "def select(self, fields=['rowid', '*'], offset=None, limit=None):\n        SQL = 'SELECT %s FROM %s' % (','.join(fields), self._table)\n        if self._selectors:\n            SQL = ' '.join([SQL, 'WHERE', self._selectors]).strip()\n        if self._modifiers:\n            SQL = ' '.join([SQL, self._modifiers])\n        if limit is not None and isinstance(limit, int):\n            SQL = ' '.join((SQL, 'LIMIT %s' % limit))\n        if (limit is not None) and (offset is not None) and isinstance(offset, int):\n            SQL = ' '.join((SQL, 'OFFSET %s' % offset))\n        return ''.join((SQL, ';'))",
    "docstring": "return SELECT SQL"
  },
  {
    "code": "def noise_uniform(self, lower_bound, upper_bound):\n        assert upper_bound > lower_bound\n        nu = self.sym.sym('nu_{:d}'.format(len(self.scope['nu'])))\n        self.scope['nu'].append(nu)\n        return lower_bound + nu*(upper_bound - lower_bound)",
    "docstring": "Create a uniform noise variable"
  },
  {
    "code": "def init_runner(self, parser, tracers, projinfo):\r\n        self.parser = parser\r\n        self.tracers = tracers\r\n        self.proj_info = projinfo",
    "docstring": "initial some instances for preparing to run test case\r\n        @note:  should not override\r\n        @param parser: instance of TestCaseParser\r\n        @param tracers: dict type for the instance of Tracer. Such as {\"\":tracer_obj} or {\"192.168.0.1:5555\":tracer_obj1, \"192.168.0.2:5555\":tracer_obj2} \r\n        @param proj_info: dict type of test case.  use like:  self.proj_info[\"module\"], self.proj_info[\"name\"]\r\n            yaml case like: \r\n                - project:\r\n                    name: xxx\r\n                    module: xxxx\r\n            dict case like:\r\n                {\"project\": {\"name\": xxx, \"module\": xxxx}}"
  },
  {
    "code": "def nearby(self, expand=50):\n        return Region(\n            self.x-expand,\n            self.y-expand,\n            self.w+(2*expand),\n            self.h+(2*expand)).clipRegionToScreen()",
    "docstring": "Returns a new Region that includes the nearby neighbourhood of the the current region.\n\n        The new region is defined by extending the current region's dimensions\n        all directions by range number of pixels. The center of the new region remains the\n        same."
  },
  {
    "code": "def parse_target(target_expression):\n    match = TARGET_REX.match(target_expression)\n    if not match:\n        log.warning('Unable to parse target \"%s\"', target_expression)\n        ret = {\n            'engine': None,\n            'delimiter': None,\n            'pattern': target_expression,\n        }\n    else:\n        ret = match.groupdict()\n    return ret",
    "docstring": "Parse `target_expressing` splitting it into `engine`, `delimiter`,\n     `pattern` - returns a dict"
  },
  {
    "code": "def create_symbol(self, *args, **kwargs):\n        if not kwargs.get('project_name'):\n            kwargs['project_name'] = self.project.project_name\n        sym = self.app.database.create_symbol(*args, **kwargs)\n        if sym:\n            if type(sym) != Symbol:\n                self._created_symbols[sym.filename].add(sym.unique_name)\n        return sym",
    "docstring": "Extensions that discover and create instances of `symbols.Symbol`\n        should do this through this method, as it will keep an index\n        of these which can be used when generating a \"naive index\".\n\n        See `database.Database.create_symbol` for more\n        information.\n\n        Args:\n            args: see `database.Database.create_symbol`\n            kwargs: see `database.Database.create_symbol`\n\n        Returns:\n            symbols.Symbol: the created symbol, or `None`."
  },
  {
    "code": "def _get_benchmark_handler(self, last_trade, freq='minutely'):\n        return LiveBenchmark(\n            last_trade, frequency=freq).surcharge_market_data \\\n            if utils.is_live(last_trade) else None",
    "docstring": "Setup a custom benchmark handler or let zipline manage it"
  },
  {
    "code": "def getRandomSequence(length=500):\n    fastaHeader = \"\"\n    for i in xrange(int(random.random()*100)):\n        fastaHeader = fastaHeader + random.choice([ 'A', 'C', '0', '9', ' ', '\\t' ])\n    return (fastaHeader, \\\n            \"\".join([ random.choice([ 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'N' ]) for i in xrange((int)(random.random() * length))]))",
    "docstring": "Generates a random name and sequence."
  },
  {
    "code": "def spkcpo(target, et, outref, refloc, abcorr, obspos, obsctr, obsref):\n    target = stypes.stringToCharP(target)\n    et = ctypes.c_double(et)\n    outref = stypes.stringToCharP(outref)\n    refloc = stypes.stringToCharP(refloc)\n    abcorr = stypes.stringToCharP(abcorr)\n    obspos = stypes.toDoubleVector(obspos)\n    obsctr = stypes.stringToCharP(obsctr)\n    obsref = stypes.stringToCharP(obsref)\n    state = stypes.emptyDoubleVector(6)\n    lt = ctypes.c_double()\n    libspice.spkcpo_c(target, et, outref, refloc, abcorr, obspos, obsctr,\n                      obsref, state, ctypes.byref(lt))\n    return stypes.cVectorToPython(state), lt.value",
    "docstring": "Return the state of a specified target relative to an \"observer,\"\n    where the observer has constant position in a specified reference\n    frame. The observer's position is provided by the calling program\n    rather than by loaded SPK files.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkcpo_c.html\n\n    :param target: Name of target ephemeris object.\n    :type target: str\n    :param et: Observation epoch.\n    :type et: float\n    :param outref: Reference frame of output state.\n    :type outref: str\n    :param refloc: Output reference frame evaluation locus.\n    :type refloc: str\n    :param abcorr: Aberration correction.\n    :type abcorr: str\n    :param obspos: Observer position relative to center of motion.\n    :type obspos: 3-Element Array of floats\n    :param obsctr: Center of motion of observer.\n    :type obsctr: str\n    :param obsref: Frame of observer position.\n    :type obsref: str\n    :return:\n            State of target with respect to observer,\n            One way light time between target and observer.\n    :rtype: tuple"
  },
  {
    "code": "def loadSharedResource(self, pchResourceName, pchBuffer, unBufferLen):\n        fn = self.function_table.loadSharedResource\n        result = fn(pchResourceName, pchBuffer, unBufferLen)\n        return result",
    "docstring": "Loads the specified resource into the provided buffer if large enough.\n        Returns the size in bytes of the buffer required to hold the specified resource."
  },
  {
    "code": "def validate_document(self, definition):\n        initial_document = {}\n        try:\n            initial_document = Loader.load(definition)\n        except RuntimeError as exception:\n            self.logger.error(str(exception))\n            sys.exit(1)\n        document = Validator().validate(initial_document)\n        if document is None:\n            self.logger.info(\"Schema validation for '%s' has failed\", definition)\n            sys.exit(1)\n        self.logger.info(\"Schema validation for '%s' succeeded\", definition)\n        return document",
    "docstring": "Validate given pipeline document.\n\n        The method is trying to load, parse and validate the spline document.\n        The validator verifies the Python structure B{not} the file format.\n\n        Args:\n            definition (str): path and filename of a yaml file containing a valid spline definition.\n\n        Returns:\n            dict: loaded and validated spline document.\n\n        Note:\n            if validation fails the application does exit!\n\n        See Also:\n            spline.validation.Validator"
  },
  {
    "code": "def boards(self, startAt=0, maxResults=50, type=None, name=None, projectKeyOrID=None):\n        params = {}\n        if type:\n            params['type'] = type\n        if name:\n            params['name'] = name\n        if projectKeyOrID:\n            params['projectKeyOrId'] = projectKeyOrID\n        if self._options['agile_rest_path'] == GreenHopperResource.GREENHOPPER_REST_PATH:\n            if startAt or maxResults or params:\n                warnings.warn('Old private GreenHopper API is used, all parameters will be ignored.', Warning)\n            r_json = self._get_json('rapidviews/list', base=self.AGILE_BASE_URL)\n            boards = [Board(self._options, self._session, raw_boards_json) for raw_boards_json in r_json['views']]\n            return ResultList(boards, 0, len(boards), len(boards), True)\n        else:\n            return self._fetch_pages(Board, 'values', 'board', startAt, maxResults, params, base=self.AGILE_BASE_URL)",
    "docstring": "Get a list of board resources.\n\n        :param startAt: The starting index of the returned boards. Base index: 0.\n        :param maxResults: The maximum number of boards to return per page. Default: 50\n        :param type: Filters results to boards of the specified type. Valid values: scrum, kanban.\n        :param name: Filters results to boards that match or partially match the specified name.\n        :param projectKeyOrID: Filters results to boards that match the specified project key or ID.\n        :rtype: ResultList[Board]\n\n        When old GreenHopper private API is used, paging is not enabled and all parameters are ignored."
  },
  {
    "code": "def _synthesize_multiple_subprocess(self, text_file, output_file_path, quit_after=None, backwards=False):\n        self.log(u\"Synthesizing multiple via subprocess...\")\n        ret = self._synthesize_multiple_generic(\n            helper_function=self._synthesize_single_subprocess_helper,\n            text_file=text_file,\n            output_file_path=output_file_path,\n            quit_after=quit_after,\n            backwards=backwards\n        )\n        self.log(u\"Synthesizing multiple via subprocess... done\")\n        return ret",
    "docstring": "Synthesize multiple fragments via ``subprocess``.\n\n        :rtype: tuple (result, (anchors, current_time, num_chars))"
  },
  {
    "code": "def get_decode_value(self):\n        if self._store_type == PUBLIC_KEY_STORE_TYPE_HEX:\n            value = bytes.fromhex(self._value)\n        elif self._store_type == PUBLIC_KEY_STORE_TYPE_BASE64:\n            value = b64decode(self._value)\n        elif self._store_type == PUBLIC_KEY_STORE_TYPE_BASE85:\n            value = b85decode(self._value)\n        elif self._store_type == PUBLIC_KEY_STORE_TYPE_JWK:\n            raise NotImplementedError\n        else:\n            value = self._value\n        return value",
    "docstring": "Return the key value based on it's storage type."
  },
  {
    "code": "def find_project_file(start_dir, basename):\n    prefix = os.path.abspath(start_dir)\n    while True:\n        candidate = os.path.join(prefix, basename)\n        if os.path.isfile(candidate):\n            return candidate\n        if os.path.exists(candidate):\n            raise PrintableError(\n                \"Found {}, but it's not a file.\".format(candidate))\n        if os.path.dirname(prefix) == prefix:\n            raise PrintableError(\"Can't find \" + basename)\n        prefix = os.path.dirname(prefix)",
    "docstring": "Walk up the directory tree until we find a file of the given name."
  },
  {
    "code": "def np_lst_sq(vecMdl, aryFuncChnk):\n    aryTmpBts, vecTmpRes = np.linalg.lstsq(vecMdl,\n                                           aryFuncChnk,\n                                           rcond=-1)[:2]\n    return aryTmpBts, vecTmpRes",
    "docstring": "Least squares fitting in numpy without cross-validation.\n\n    Notes\n    -----\n    This is just a wrapper function for np.linalg.lstsq to keep piping\n    consistent."
  },
  {
    "code": "def load_configuration(self, **kwargs):\n        for key in settings.ACTIVE_URL_KWARGS:\n            kwargs.setdefault(key, settings.ACTIVE_URL_KWARGS[key])\n        self.css_class = kwargs['css_class']\n        self.parent_tag = kwargs['parent_tag']\n        self.menu = kwargs['menu']\n        self.ignore_params = kwargs['ignore_params']",
    "docstring": "load configuration, merge with default settings"
  },
  {
    "code": "def _init_contoh(self, makna_label):\n        indeks = makna_label.text.find(': ')\n        if indeks != -1:\n            contoh = makna_label.text[indeks + 2:].strip()\n            self.contoh = contoh.split('; ')\n        else:\n            self.contoh = []",
    "docstring": "Memproses contoh yang ada dalam makna.\n\n        :param makna_label: BeautifulSoup untuk makna yang ingin diproses.\n        :type makna_label: BeautifulSoup"
  },
  {
    "code": "def save_json(object, handle, indent=2):\n    obj_json = json.dumps(object, indent=indent, cls=NumpyJSONEncoder)\n    handle.write(obj_json)",
    "docstring": "Save object as json on CNS."
  },
  {
    "code": "def check(self, triggers, data_reader):\n        if len(triggers['snr']) == 0:\n            return None\n        i = triggers['snr'].argmax()\n        rchisq = triggers['chisq'][i]\n        nsnr = ranking.newsnr(triggers['snr'][i], rchisq)\n        dur = triggers['template_duration'][i]\n        if nsnr > self.newsnr_threshold and \\\n                rchisq < self.reduced_chisq_threshold and \\\n                dur > self.duration_threshold:\n            fake_coinc = {'foreground/%s/%s' % (self.ifo, k): triggers[k][i]\n                          for k in triggers}\n            fake_coinc['foreground/stat'] = nsnr\n            fake_coinc['foreground/ifar'] = self.fixed_ifar\n            fake_coinc['HWINJ'] = data_reader.near_hwinj()\n            return fake_coinc\n        return None",
    "docstring": "Look for a single detector trigger that passes the thresholds in\n        the current data."
  },
  {
    "code": "def parse_config(args=sys.argv):\n    parser = argparse.ArgumentParser(\n        description='Read in the config file')\n    parser.add_argument(\n        'config_file',\n        help='Configuration file.',\n        metavar='FILE', type=extant_file)\n    return parser.parse_args(args[1:])",
    "docstring": "Parse the args using the config_file pattern\n\n    Args:\n        args: sys.argv\n\n    Returns:\n        The populated namespace object from parser.parse_args().\n\n    Raises:\n        TBD"
  },
  {
    "code": "def add_child(parent, tag, text=None):\n    elem = ET.SubElement(parent, tag)\n    if text is not None:\n        elem.text = text\n    return elem",
    "docstring": "Add a child element of specified tag type to parent.\n    The new child element is returned."
  },
  {
    "code": "def update(self, *objs):\n        keys = self.keys()\n        new_keys = get_objs_columns(objs, self.realfieldb)\n        modified = False\n        for v in new_keys:\n            if v in keys:\n                keys.remove(v)\n            else:\n                d = {self.fielda:self.valuea, self.fieldb:v}\n                if self.before_save:\n                    self.before_save(d)\n                if self.through_model:\n                    obj = self.through_model(**d)\n                    obj.save()\n                else:\n                    self.do_(self.table.insert().values(**d))\n                modified = True\n        if keys:\n            self.clear(*keys)\n            modified = True\n        setattr(self.instance, self.store_key, new_keys)\n        return modified",
    "docstring": "Update the third relationship table, but not the ModelA or ModelB"
  },
  {
    "code": "def start_to(self, ip, tcpport=102):\n        if tcpport != 102:\n            logger.info(\"setting server TCP port to %s\" % tcpport)\n            self.set_param(snap7.snap7types.LocalPort, tcpport)\n        assert re.match(ipv4, ip), '%s is invalid ipv4' % ip\n        logger.info(\"starting server to %s:102\" % ip)\n        return self.library.Srv_Start(self.pointer, ip)",
    "docstring": "start server on a specific interface."
  },
  {
    "code": "def _col_name(index):\n    for exp in itertools.count(1):\n        limit = 26 ** exp\n        if index < limit:\n            return ''.join(chr(ord('A') + index // (26 ** i) % 26) for i in range(exp-1, -1, -1))\n        index -= limit",
    "docstring": "Converts a column index to a column name.\n\n    >>> _col_name(0)\n    'A'\n    >>> _col_name(26)\n    'AA'"
  },
  {
    "code": "def propget(self, prop, rev, path=None):\n        rev, prefix = self._maprev(rev)\n        if path is None:\n            return self._propget(prop, str(rev), None)\n        else:\n            path = type(self).cleanPath(_join(prefix, path))\n            return self._propget(prop, str(rev), path)",
    "docstring": "Get Subversion property value of the path"
  },
  {
    "code": "def get_index(self):\n        ifreq = struct.pack('16si', self.name, 0)\n        res = fcntl.ioctl(sockfd, SIOCGIFINDEX, ifreq)\n        return struct.unpack(\"16si\", res)[1]",
    "docstring": "Convert an interface name to an index value."
  },
  {
    "code": "def set_pixel(self,x,y,state):\n\tself.send_cmd(\"P\"+str(x+1)+\",\"+str(y+1)+\",\"+state)",
    "docstring": "Set pixel at \"x,y\" to \"state\" where state can be one of \"ON\", \"OFF\"\n\tor \"TOGGLE\""
  },
  {
    "code": "def get_stock_dividends(self, sid, trading_days):\n        if self._adjustment_reader is None:\n            return []\n        if len(trading_days) == 0:\n            return []\n        start_dt = trading_days[0].value / 1e9\n        end_dt = trading_days[-1].value / 1e9\n        dividends = self._adjustment_reader.conn.execute(\n            \"SELECT * FROM stock_dividend_payouts WHERE sid = ? AND \"\n            \"ex_date > ? AND pay_date < ?\", (int(sid), start_dt, end_dt,)).\\\n            fetchall()\n        dividend_info = []\n        for dividend_tuple in dividends:\n            dividend_info.append({\n                \"declared_date\": dividend_tuple[1],\n                \"ex_date\": pd.Timestamp(dividend_tuple[2], unit=\"s\"),\n                \"pay_date\": pd.Timestamp(dividend_tuple[3], unit=\"s\"),\n                \"payment_sid\": dividend_tuple[4],\n                \"ratio\": dividend_tuple[5],\n                \"record_date\": pd.Timestamp(dividend_tuple[6], unit=\"s\"),\n                \"sid\": dividend_tuple[7]\n            })\n        return dividend_info",
    "docstring": "Returns all the stock dividends for a specific sid that occur\n        in the given trading range.\n\n        Parameters\n        ----------\n        sid: int\n            The asset whose stock dividends should be returned.\n\n        trading_days: pd.DatetimeIndex\n            The trading range.\n\n        Returns\n        -------\n        list: A list of objects with all relevant attributes populated.\n        All timestamp fields are converted to pd.Timestamps."
  },
  {
    "code": "def rerank(self, hypotheses: Dict[str, Any], reference: str) -> Dict[str, Any]:\n        scores = [self.scoring_function(hypothesis, reference) for hypothesis in hypotheses['translations']]\n        ranking = list(np.argsort(scores, kind='mergesort')[::-1])\n        reranked_hypotheses = self._sort_by_ranking(hypotheses, ranking)\n        if self.return_score:\n            reranked_hypotheses['scores'] = [scores[i] for i in ranking]\n        return reranked_hypotheses",
    "docstring": "Reranks a set of hypotheses that belong to one single reference\n        translation. Uses stable sorting.\n\n        :param hypotheses: Nbest translations.\n        :param reference: A single string with the actual reference translation.\n        :return: Nbest translations sorted by reranking scores."
  },
  {
    "code": "def abort(self):\n        resp = make_response(render_template('error.html', error=self.code, message=self.message), self.code)\n        return resp",
    "docstring": "Return an HTML Response representation of the exception."
  },
  {
    "code": "def clear_public_domain(self):\n        if (self.get_public_domain_metadata().is_read_only() or\n                self.get_public_domain_metadata().is_required()):\n            raise errors.NoAccess()\n        self._my_map['publicDomain'] = self._public_domain_default",
    "docstring": "Removes the public domain status.\n\n        raise:  NoAccess - ``Metadata.isRequired()`` is ``true`` or\n                ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_children(self,node):\n    if self.find_cycle() or self.__directionless:\n      sys.stderr.write(\"ERROR: do cannot find a branch when there are cycles in the graph\\n\")\n      sys.exit()\n    v = self.__get_children(node.id)\n    return [self.__nodes[i] for i in v]",
    "docstring": "Find all the children of a node.  must be a undirectional graph with no cycles\n\n    :param node:\n    :type node: Node\n    :returns: list of nodes\n    :rtype: Node[]"
  },
  {
    "code": "def _query_zendesk(self, endpoint, object_type, *endpoint_args, **endpoint_kwargs):\n        _id = endpoint_kwargs.get('id', None)\n        if _id:\n            item = self.cache.get(object_type, _id)\n            if item:\n                return item\n            else:\n                return self._get(url=self._build_url(endpoint(*endpoint_args, **endpoint_kwargs)))\n        elif 'ids' in endpoint_kwargs:\n            cached_objects = []\n            for _id in endpoint_kwargs['ids']:\n                obj = self.cache.get(object_type, _id)\n                if not obj:\n                    return self._get(self._build_url(endpoint=endpoint(*endpoint_args, **endpoint_kwargs)))\n                cached_objects.append(obj)\n            return ZendeskResultGenerator(self, {}, response_objects=cached_objects, object_type=object_type)\n        else:\n            return self._get(self._build_url(endpoint=endpoint(*endpoint_args, **endpoint_kwargs)))",
    "docstring": "Query Zendesk for items. If an id or list of ids are passed, attempt to locate these items\n         in the relevant cache. If they cannot be found, or no ids are passed, execute a call to Zendesk\n         to retrieve the items.\n\n        :param endpoint: target endpoint.\n        :param object_type: object type we are expecting.\n        :param endpoint_args: args for endpoint\n        :param endpoint_kwargs: kwargs for endpoint\n\n        :return: either a ResultGenerator or a Zenpy object."
  },
  {
    "code": "def combine(self, pubkeys):\n        assert len(pubkeys) > 0\n        outpub = ffi.new('secp256k1_pubkey *')\n        for item in pubkeys:\n            assert ffi.typeof(item) is ffi.typeof('secp256k1_pubkey *')\n        res = lib.secp256k1_ec_pubkey_combine(\n            self.ctx, outpub, pubkeys, len(pubkeys))\n        if not res:\n            raise Exception('failed to combine public keys')\n        self.public_key = outpub\n        return outpub",
    "docstring": "Add a number of public keys together."
  },
  {
    "code": "def set_bytes_at_rva(self, rva, data):\n        if not isinstance(data, bytes):\n            raise TypeError('data should be of type: bytes')\n        offset = self.get_physical_by_rva(rva)\n        if not offset:\n            return False\n        return self.set_bytes_at_offset(offset, data)",
    "docstring": "Overwrite, with the given string, the bytes at the file offset corresponding to the given RVA.\n\n        Return True if successful, False otherwise. It can fail if the\n        offset is outside the file's boundaries."
  },
  {
    "code": "def need_ext():\n    sys.stdout.write(\"{0}\\next_mods\\n\".format(OPTIONS.delimiter))\n    sys.exit(EX_MOD_DEPLOY)",
    "docstring": "Signal that external modules need to be deployed."
  },
  {
    "code": "def _parse_boolean(value):\n    value = value.lower()\n    if value in _true_strings:\n        return True\n    elif value in _false_strings:\n        return False\n    else:\n        return None",
    "docstring": "Coerce value into an bool.\n\n    :param str value: Value to parse.\n    :returns: bool or None if the value is not a boolean string."
  },
  {
    "code": "def create_swagger_json_handler(app, **kwargs):\n    spec = get_swagger_spec(app)\n    _add_blueprint_specs(app, spec)\n    spec_dict = spec.swagger_definition(**kwargs)\n    encoded_spec = json.dumps(spec_dict).encode(\"UTF-8\")\n    async def swagger(request):\n        return HTTPResponse(\n            body_bytes=encoded_spec,\n            headers={\n                \"Access-Control-Allow-Origin\": \"*\"\n            },\n            content_type=\"application/json\",\n        )\n    return swagger",
    "docstring": "Create a handler that returns the swagger definition\n    for an application.\n    This method assumes the application is using the\n    TransmuteUrlDispatcher as the router."
  },
  {
    "code": "def update_policy(self,defaultHeaders):\n\t\tif self.inputs is not None:\n\t\t\tfor k,v in defaultHeaders.items():\n\t\t\t\tif k not in self.inputs:\n\t\t\t\t\tself.inputs[k] = v\n\t\t\treturn self.inputs\n\t\telse:\n\t\t\treturn self.inputs",
    "docstring": "if policy in default but not input still return"
  },
  {
    "code": "async def async_fetch(url: str, **kwargs) -> Selector:\n    kwargs.setdefault('headers', DEFAULT_HEADERS)\n    async with aiohttp.ClientSession(**kwargs) as ses:\n        async with ses.get(url, **kwargs) as res:\n            html = await res.text()\n            tree = Selector(text=html)\n            return tree",
    "docstring": "Do the fetch in an async style.\n\n    Args:\n        url (str): The url of the site.\n\n    Returns:\n        Selector: allows you to select parts of HTML text using CSS or XPath expressions."
  },
  {
    "code": "def save_binary(self, filename):\n        _safe_call(_LIB.LGBM_DatasetSaveBinary(\n            self.construct().handle,\n            c_str(filename)))\n        return self",
    "docstring": "Save Dataset to a binary file.\n\n        Parameters\n        ----------\n        filename : string\n            Name of the output file.\n\n        Returns\n        -------\n        self : Dataset\n            Returns self."
  },
  {
    "code": "def get_pages(parser, token):\n    try:\n        tag_name, args = token.contents.split(None, 1)\n    except ValueError:\n        var_name = 'pages'\n    else:\n        args = args.split()\n        if len(args) == 2 and args[0] == 'as':\n            var_name = args[1]\n        else:\n            msg = 'Invalid arguments for %r tag' % tag_name\n            raise template.TemplateSyntaxError(msg)\n    return GetPagesNode(var_name)",
    "docstring": "Add to context the list of page links.\n\n    Usage:\n\n    .. code-block:: html+django\n\n        {% get_pages %}\n\n    This is mostly used for Digg-style pagination.\n    This call inserts in the template context a *pages* variable, as a sequence\n    of page links. You can use *pages* in different ways:\n\n    - just print *pages.get_rendered* and you will get Digg-style pagination displayed:\n\n    .. code-block:: html+django\n\n        {{ pages.get_rendered }}\n\n    - display pages count:\n\n    .. code-block:: html+django\n\n        {{ pages|length }}\n\n    - check if the page list contains more than one page:\n\n    .. code-block:: html+django\n\n        {{ pages.paginated }}\n        {# the following is equivalent #}\n        {{ pages|length > 1 }}\n\n    - get a specific page:\n\n    .. code-block:: html+django\n\n        {# the current selected page #}\n        {{ pages.current }}\n\n        {# the first page #}\n        {{ pages.first }}\n\n        {# the last page #}\n        {{ pages.last }}\n\n        {# the previous page (or nothing if you are on first page) #}\n        {{ pages.previous }}\n\n        {# the next page (or nothing if you are in last page) #}\n        {{ pages.next }}\n\n        {# the third page #}\n        {{ pages.3 }}\n        {# this means page.1 is the same as page.first #}\n\n        {# the 1-based index of the first item on the current page #}\n        {{ pages.current_start_index }}\n\n        {# the 1-based index of the last item on the current page #}\n        {{ pages.current_end_index }}\n\n        {# the total number of objects, across all pages #}\n        {{ pages.total_count }}\n\n        {# the first page represented as an arrow #}\n        {{ pages.first_as_arrow }}\n\n        {# the last page represented as an arrow #}\n        {{ pages.last_as_arrow }}\n\n    - iterate over *pages* to get all pages:\n\n    .. code-block:: html+django\n\n        {% for page in pages %}\n            {# display page link #}\n            {{ page.render_link}}\n\n            {# the page url (beginning with \"?\") #}\n            {{ page.url }}\n\n            {# the page path #}\n            {{ page.path }}\n\n            {# the page number #}\n            {{ page.number }}\n\n            {# a string representing the page (commonly the page number) #}\n            {{ page.label }}\n\n            {# check if the page is the current one #}\n            {{ page.is_current }}\n\n            {# check if the page is the first one #}\n            {{ page.is_first }}\n\n            {# check if the page is the last one #}\n            {{ page.is_last }}\n        {% endfor %}\n\n    You can change the variable name, e.g.:\n\n    .. code-block:: html+django\n\n        {% get_pages as page_links %}\n\n    Must be called after ``{% paginate objects %}``."
  },
  {
    "code": "def stream(self):\n        if not hasattr(self, '_stream'):\n            self._stream = zmq.eventloop.zmqstream.ZMQStream(self._socket, io_loop=self.io_loop)\n        return self._stream",
    "docstring": "Return the current zmqstream, creating one if necessary"
  },
  {
    "code": "def from_mapping(cls, mapping):\n\t\tout = cls()\n\t\tfor elem, count in mapping.items():\n\t\t\tout._set_count(elem, count)\n\t\treturn out",
    "docstring": "Create a bag from a dict of elem->count.\n\n\t\tEach key in the dict is added if the value is > 0.\n\n\t\tRaises:\n\t\t\tValueError: If any count is < 0."
  },
  {
    "code": "def _descriptor_names(self):\n        descriptor_names = []\n        for name in dir(self):\n            try:\n                attr = getattr(type(self), name)\n                if isinstance(attr, DJANGO_RELATED_FIELD_DESCRIPTOR_CLASSES):\n                    descriptor_names.append(name)\n            except AttributeError:\n                pass\n        return descriptor_names",
    "docstring": "Attributes which are Django descriptors. These represent a field\n        which is a one-to-many or many-to-many relationship that is\n        potentially defined in another model, and doesn't otherwise appear\n        as a field on this model."
  },
  {
    "code": "def activate_in_ec(self, ec_index):\n        with self._mutex:\n            if ec_index >= len(self.owned_ecs):\n                ec_index -= len(self.owned_ecs)\n                if ec_index >= len(self.participating_ecs):\n                    raise exceptions.BadECIndexError(ec_index)\n                ec = self.participating_ecs[ec_index]\n            else:\n                ec = self.owned_ecs[ec_index]\n            ec.activate_component(self._obj)",
    "docstring": "Activate this component in an execution context.\n\n        @param ec_index The index of the execution context to activate in.\n                        This index is into the total array of contexts, that\n                        is both owned and participating contexts. If the value\n                        of ec_index is greater than the length of\n                        @ref owned_ecs, that length is subtracted from\n                        ec_index and the result used as an index into\n                        @ref participating_ecs."
  },
  {
    "code": "def get_callable_name(c):\n    if hasattr(c, 'name'):\n        return six.text_type(c.name)\n    elif hasattr(c, '__name__'):\n        return six.text_type(c.__name__) + u'()'\n    else:\n        return six.text_type(c)",
    "docstring": "Get a human-friendly name for the given callable.\n\n    :param c: The callable to get the name for\n    :type c: callable\n    :rtype: unicode"
  },
  {
    "code": "def free_parameters(self):\n        self._update_parameters()\n        free_parameters_dictionary = collections.OrderedDict()\n        for parameter_name, parameter in self._parameters.iteritems():\n            if parameter.free:\n                free_parameters_dictionary[parameter_name] = parameter\n        return free_parameters_dictionary",
    "docstring": "Get a dictionary with all the free parameters in this model\n\n        :return: dictionary of free parameters"
  },
  {
    "code": "def verifyExpanded(self, samplerate):\n        results = self.expandFunction(self.verifyComponents, args=(samplerate,))\n        msg = [x for x in results if x]\n        if len(msg) > 0:\n            return msg[0]\n        else:\n            return 0",
    "docstring": "Checks the expanded parameters for invalidating conditions\n\n        :param samplerate: generation samplerate (Hz), passed on to component verification\n        :type samplerate: int\n        :returns: str -- error message, if any, 0 otherwise"
  },
  {
    "code": "def get_configs(args, command_args, ansible_args=()):\n    configs = [\n        config.Config(\n            molecule_file=util.abs_path(c),\n            args=args,\n            command_args=command_args,\n            ansible_args=ansible_args,\n        ) for c in glob.glob(MOLECULE_GLOB)\n    ]\n    _verify_configs(configs)\n    return configs",
    "docstring": "Glob the current directory for Molecule config files, instantiate config\n    objects, and returns a list.\n\n    :param args: A dict of options, arguments and commands from the CLI.\n    :param command_args: A dict of options passed to the subcommand from\n     the CLI.\n    :param ansible_args: An optional tuple of arguments provided to the\n     `ansible-playbook` command.\n    :return: list"
  },
  {
    "code": "def __run_delta_sql(self, delta):\n        self.__run_sql_file(delta.get_file())\n        self.__update_upgrades_table(delta)",
    "docstring": "Execute the delta sql file on the database"
  },
  {
    "code": "def option(*args, **kwargs):\n    def decorate_sub_command(method):\n        if not hasattr(method, \"optparser\"):\n            method.optparser = SubCmdOptionParser()\n        method.optparser.add_option(*args, **kwargs)\n        return method\n    def decorate_class(klass):\n        assert _forgiving_issubclass(klass, Cmdln)\n        _inherit_attr(klass, \"toplevel_optparser_options\", [], cp=lambda l: l[:])\n        klass.toplevel_optparser_options.append( (args, kwargs) )\n        return klass\n    def decorate(obj):\n        if _forgiving_issubclass(obj, Cmdln):\n            return decorate_class(obj)\n        else:\n            return decorate_sub_command(obj)\n    return decorate",
    "docstring": "Decorator to add an option to the optparser argument of a Cmdln\n    subcommand\n\n    To add a toplevel option, apply the decorator on the class itself. (see\n    p4.py for an example)\n    \n    Example:\n        @cmdln.option(\"-E\", dest=\"environment_path\")\n        class MyShell(cmdln.Cmdln):\n            @cmdln.option(\"-f\", \"--force\", help=\"force removal\")\n            def do_remove(self, subcmd, opts, *args):\n                #..."
  },
  {
    "code": "def continuous_frequency(self, data_frame):\n        tap_timestamps = data_frame.td[data_frame.action_type==1]\n        cont_freq = 1.0/(np.array(tap_timestamps[1:-1])-np.array(tap_timestamps[0:-2]))\n        duration = math.ceil(data_frame.td[-1])\n        return cont_freq, duration",
    "docstring": "This method returns continuous frequency\n\n            :param data_frame: the data frame\n            :type data_frame: pandas.DataFrame\n            :return cont_freq: frequency\n            :rtype cont_freq: float"
  },
  {
    "code": "def tree_queryset(value):\n    from django.db.models.query import QuerySet\n    from copy import deepcopy\n    if not isinstance(value, QuerySet):\n        return value\n    qs = value\n    qs2 = deepcopy(qs)\n    is_filtered = bool(qs.query.where.children)\n    if is_filtered:\n        include_pages = set()\n        for p in qs2.order_by('rght').iterator():\n            if p.parent_id and p.parent_id not in include_pages and p.id not in include_pages:\n                ancestor_id_list = p.get_ancestors().values_list('id', flat=True)\n                include_pages.update(ancestor_id_list)\n        if include_pages:\n            qs = qs | qs.model._default_manager.filter(id__in=include_pages)\n        qs = qs.distinct()\n    return qs",
    "docstring": "Converts a normal queryset from an MPTT model to include all the ancestors\n    so a filtered subset of items can be formatted correctly"
  },
  {
    "code": "def is_newer_b(a, bfiles):\n    if isinstance(bfiles, basestring):\n        bfiles = [bfiles]\n    if not op.exists(a): return False\n    if not all(op.exists(b) for b in bfiles): return False\n    atime = os.stat(a).st_mtime\n    for b in bfiles:\n        if atime > os.stat(b).st_mtime:\n            return False\n    return True",
    "docstring": "check that all b files have been modified more recently than a"
  },
  {
    "code": "def add_page(self, title=None, content=None, old_url=None,\n                 tags=None, old_id=None, old_parent_id=None):\n        if not title:\n            text = decode_entities(strip_tags(content)).replace(\"\\n\", \" \")\n            title = text.split(\". \")[0]\n        if tags is None:\n            tags = []\n        self.pages.append({\n            \"title\": title,\n            \"content\": content,\n            \"tags\": tags,\n            \"old_url\": old_url,\n            \"old_id\": old_id,\n            \"old_parent_id\": old_parent_id,\n        })",
    "docstring": "Adds a page to the list of pages to be imported - used by the\n        Wordpress importer."
  },
  {
    "code": "def _sub_nat(self):\n        result = np.zeros(len(self), dtype=np.int64)\n        result.fill(iNaT)\n        return result.view('timedelta64[ns]')",
    "docstring": "Subtract pd.NaT from self"
  },
  {
    "code": "def relaxNGNewMemParserCtxt(buffer, size):\n    ret = libxml2mod.xmlRelaxNGNewMemParserCtxt(buffer, size)\n    if ret is None:raise parserError('xmlRelaxNGNewMemParserCtxt() failed')\n    return relaxNgParserCtxt(_obj=ret)",
    "docstring": "Create an XML RelaxNGs parse context for that memory buffer\n       expected to contain an XML RelaxNGs file."
  },
  {
    "code": "def _unzip_file(self, zip_file, out_folder):\n        try:\n            zf = zipfile.ZipFile(zip_file, 'r')\n            zf.extractall(path=out_folder)\n            zf.close()\n            del zf\n            return True\n        except:\n            return False",
    "docstring": "unzips a file to a given folder"
  },
  {
    "code": "def make_ui(self, path='hgwebdir.config'):\n    sections = [\n                'alias',\n                'auth',\n                'decode/encode',\n                'defaults',\n                'diff',\n                'email',\n                'extensions',\n                'format',\n                'merge-patterns',\n                'merge-tools',\n                'hooks',\n                'http_proxy',\n                'smtp',\n                'patch',\n                'paths',\n                'profiling',\n                'server',\n                'trusted',\n                'ui',\n                'web',\n                ]\n    repos = path\n    baseui = ui.ui()\n    cfg = config.config()\n    cfg.read(repos)\n    self.paths = cfg.items('paths')\n    self.base_path = self.paths[0][1].replace('*', '')\n    self.check_repo_dir(self.paths)\n    self.set_statics(cfg)\n    for section in sections:\n        for k, v in cfg.items(section):\n            baseui.setconfig(section, k, v)\n    return baseui",
    "docstring": "A funcion that will read python rc files and make an ui from read options\n\n    :param path: path to mercurial config file"
  },
  {
    "code": "def _conv_shape_tuple(self, lhs_shape, rhs_shape, strides, pads):\n    if isinstance(pads, str):\n      pads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)\n    if len(pads) != len(lhs_shape) - 2:\n      msg = 'Wrong number of explicit pads for conv: expected {}, got {}.'\n      raise TypeError(msg.format(len(lhs_shape) - 2, len(pads)))\n    lhs_padded = onp.add(lhs_shape[2:], onp.add(*zip(*pads)))\n    out_space = onp.floor_divide(\n        onp.subtract(lhs_padded, rhs_shape[2:]), strides) + 1\n    out_space = onp.maximum(0, out_space)\n    out_shape = (lhs_shape[0], rhs_shape[0]) + tuple(out_space)\n    return tuple(out_shape)",
    "docstring": "Compute the shape of a conv given input shapes in canonical order."
  },
  {
    "code": "def _swclock_to_hwclock():\n    res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False)\n    if res['retcode'] != 0:\n        msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr'])\n        raise CommandExecutionError(msg)\n    return True",
    "docstring": "Set hardware clock to value of software clock."
  },
  {
    "code": "def rt_update(self, statement, linenum, mode, xparser):\n        section = self.find_section(self.module.charindex(linenum, 1))\n        if section == \"body\":\n            xparser.parse_line(statement, self, mode)\n        elif section == \"signature\":\n            if mode == \"insert\":\n                xparser.parse_signature(statement, self)",
    "docstring": "Uses the specified line parser to parse the given line.\n\n        :arg statement: a string of lines that are part of a single statement.\n        :arg linenum: the line number of the first line in the list relative to\n          the entire module contents.\n        arg mode: either 'insert', 'replace' or 'delete'\n        :arg xparser: an instance of the executable parser from the real\n          time update module's line parser."
  },
  {
    "code": "def close(self):\n        if self.error_log and not self.quiet:\n            print(\"\\nErrors occured:\", file=sys.stderr)\n            for err in self.error_log:\n                print(err, file=sys.stderr)\n        self._session.close()",
    "docstring": "Print error log and close session"
  },
  {
    "code": "def contains_opposite_color_piece(self, square, position):\n        return not position.is_square_empty(square) and \\\n            position.piece_at_square(square).color != self.color",
    "docstring": "Finds if square on the board is occupied by a ``Piece``\n        belonging to the opponent.\n\n        :type: square: Location\n        :type: position: Board\n        :rtype: bool"
  },
  {
    "code": "def _delete_element(name, element_type, data, server=None):\n    _api_delete('{0}/{1}'.format(element_type, quote(name, safe='')), data, server)\n    return name",
    "docstring": "Delete an element"
  },
  {
    "code": "def _get_register_size(self, reg_offset):\n        if reg_offset in self.project.arch.register_names:\n            reg_name = self.project.arch.register_names[reg_offset]\n            reg_size = self.project.arch.registers[reg_name][1]\n            return reg_size\n        l.warning(\"_get_register_size(): unsupported register offset %d. Assum size 1. \"\n                  \"More register name mappings should be implemented in archinfo.\", reg_offset)\n        return 1",
    "docstring": "Get the size of a register.\n\n        :param int reg_offset: Offset of the register.\n        :return: Size in bytes.\n        :rtype: int"
  },
  {
    "code": "def scaledBy(self, scale):\n        scaled = deepcopy(self)\n        for test in scaled.elements[0].tests:\n            if type(test.value) in (int, float):\n                if test.property == 'scale-denominator':\n                    test.value /= scale\n                elif test.property == 'zoom':\n                    test.value += log(scale)/log(2)\n        return scaled",
    "docstring": "Return a new Selector with scale denominators scaled by a number."
  },
  {
    "code": "def get_child_ids(self, parent_alias):\n        self._cache_init()\n        return self._cache_get_entry(self.CACHE_NAME_PARENTS, parent_alias, [])",
    "docstring": "Returns child IDs of the given parent category\n\n        :param str parent_alias: Parent category alias\n        :rtype: list\n        :return: a list of child IDs"
  },
  {
    "code": "def get_instance(self, payload):\n        return ActivityInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], )",
    "docstring": "Build an instance of ActivityInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance\n        :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityInstance"
  },
  {
    "code": "def get_seqs_fasta(seqs, names, out_fa):\n    with open(out_fa, 'w') as fa_handle:\n        for s, n in itertools.izip(seqs, names):\n            print(\">cx{1}-{0}\\n{0}\".format(s, n), file=fa_handle)\n    return out_fa",
    "docstring": "get fasta from sequences"
  },
  {
    "code": "def python_zip(file_list, gallery_path, extension='.py'):\n    zipname = os.path.basename(os.path.normpath(gallery_path))\n    zipname += '_python' if extension == '.py' else '_jupyter'\n    zipname = os.path.join(gallery_path, zipname + '.zip')\n    zipname_new = zipname + '.new'\n    with zipfile.ZipFile(zipname_new, mode='w') as zipf:\n        for fname in file_list:\n            file_src = os.path.splitext(fname)[0] + extension\n            zipf.write(file_src, os.path.relpath(file_src, gallery_path))\n    _replace_md5(zipname_new)\n    return zipname",
    "docstring": "Stores all files in file_list into an zip file\n\n    Parameters\n    ----------\n    file_list : list\n        Holds all the file names to be included in zip file\n    gallery_path : str\n        path to where the zipfile is stored\n    extension : str\n        '.py' or '.ipynb' In order to deal with downloads of python\n        sources and jupyter notebooks the file extension from files in\n        file_list will be removed and replace with the value of this\n        variable while generating the zip file\n    Returns\n    -------\n    zipname : str\n        zip file name, written as `target_dir_{python,jupyter}.zip`\n        depending on the extension"
  },
  {
    "code": "def files(self, request, id):\n        gist = self.send(request, id).json()\n        return gist['files']",
    "docstring": "Returns a list of files in the gist\n\n        Arguments:\n            request: an initial request object\n            id:      the gist identifier\n\n        Returns:\n            A list of the files"
  },
  {
    "code": "def combine(self, *others):\n        p = self.clone()\n        for other in others:\n            p.hooks.extend(other.hooks)\n        return p",
    "docstring": "Combine other Panglers into this Pangler.\n\n        Returns a copy of this Pangler with all of the hooks from the provided\n        Panglers added to it as well. The new Pangler will be bound to the same\n        instance and have the same `id`, but new hooks will not be shared with\n        this Pangler or any provided Panglers."
  },
  {
    "code": "def check_serializable(cls):\n    if is_named_tuple(cls):\n        return\n    if not hasattr(cls, \"__new__\"):\n        print(\"The class {} does not have a '__new__' attribute and is \"\n              \"probably an old-stye class. Please make it a new-style class \"\n              \"by inheriting from 'object'.\")\n        raise RayNotDictionarySerializable(\"The class {} does not have a \"\n                                           \"'__new__' attribute and is \"\n                                           \"probably an old-style class. We \"\n                                           \"do not support this. Please make \"\n                                           \"it a new-style class by \"\n                                           \"inheriting from 'object'.\"\n                                           .format(cls))\n    try:\n        obj = cls.__new__(cls)\n    except Exception:\n        raise RayNotDictionarySerializable(\"The class {} has overridden \"\n                                           \"'__new__', so Ray may not be able \"\n                                           \"to serialize it efficiently.\"\n                                           .format(cls))\n    if not hasattr(obj, \"__dict__\"):\n        raise RayNotDictionarySerializable(\"Objects of the class {} do not \"\n                                           \"have a '__dict__' attribute, so \"\n                                           \"Ray cannot serialize it \"\n                                           \"efficiently.\".format(cls))\n    if hasattr(obj, \"__slots__\"):\n        raise RayNotDictionarySerializable(\"The class {} uses '__slots__', so \"\n                                           \"Ray may not be able to serialize \"\n                                           \"it efficiently.\".format(cls))",
    "docstring": "Throws an exception if Ray cannot serialize this class efficiently.\n\n    Args:\n        cls (type): The class to be serialized.\n\n    Raises:\n        Exception: An exception is raised if Ray cannot serialize this class\n            efficiently."
  },
  {
    "code": "def rar3_s2k(psw, salt):\n    if not isinstance(psw, unicode):\n        psw = psw.decode('utf8')\n    seed = bytearray(psw.encode('utf-16le') + salt)\n    h = Rar3Sha1(rarbug=True)\n    iv = EMPTY\n    for i in range(16):\n        for j in range(0x4000):\n            cnt = S_LONG.pack(i * 0x4000 + j)\n            h.update(seed)\n            h.update(cnt[:3])\n            if j == 0:\n                iv += h.digest()[19:20]\n    key_be = h.digest()[:16]\n    key_le = pack(\"<LLLL\", *unpack(\">LLLL\", key_be))\n    return key_le, iv",
    "docstring": "String-to-key hash for RAR3."
  },
  {
    "code": "def numberwang(random=random, *args, **kwargs):\n    n = random.randint(2, 150)\n    return inflectify.number_to_words(n)",
    "docstring": "Return a number that is spelled out.\n\n    >>> numberwang(random=mock_random)\n    'two'\n    >>> numberwang(random=mock_random, capitalize=True)\n    'Two'\n    >>> numberwang(random=mock_random, slugify=True)\n    'two'"
  },
  {
    "code": "def badge_label(self, badge):\n        kind = badge.kind if isinstance(badge, Badge) else badge\n        return self.__badges__[kind]",
    "docstring": "Display the badge label for a given kind"
  },
  {
    "code": "def onSelectRow(self, event):\n        grid = self.grid\n        row = event.Row\n        default = (255, 255, 255, 255)\n        highlight = (191, 216, 216, 255)\n        cell_color = grid.GetCellBackgroundColour(row, 0)\n        attr = wx.grid.GridCellAttr()\n        if cell_color == default:\n            attr.SetBackgroundColour(highlight)\n            self.selected_rows.add(row)\n        else:\n            attr.SetBackgroundColour(default)\n            try:\n                self.selected_rows.remove(row)\n            except KeyError:\n                pass\n        if self.selected_rows and self.deleteRowButton:\n            self.deleteRowButton.Enable()\n        else:\n            self.deleteRowButton.Disable()\n        grid.SetRowAttr(row, attr)\n        grid.Refresh()",
    "docstring": "Highlight or unhighlight a row for possible deletion."
  },
  {
    "code": "def download_data():\n    with urlopen(_retrieve_download_url()) as f:\n        with open(os.path.join(CACHE_FOLDER, CACHE_ZIP), \"wb\") as local_file:\n            local_file.write(f.read())",
    "docstring": "Downloads complete station dataset including catchment descriptors and amax records. And saves it into a cache\n    folder."
  },
  {
    "code": "def make_veto_table(workflow, out_dir, vetodef_file=None, tags=None):\n    if vetodef_file is None:\n        vetodef_file = workflow.cp.get_opt_tags(\"workflow-segments\",\n                                           \"segments-veto-definer-file\", [])\n        file_url = urlparse.urljoin('file:',\n                                    urllib.pathname2url(vetodef_file))\n        vdf_file = File(workflow.ifos, 'VETO_DEFINER',\n                        workflow.analysis_time, file_url=file_url)\n        vdf_file.PFN(file_url, site='local')\n    else:\n        vdf_file = vetodef_file\n    if tags is None: tags = []\n    makedir(out_dir)\n    node = PlotExecutable(workflow.cp, 'page_vetotable', ifos=workflow.ifos,\n                    out_dir=out_dir, tags=tags).create_node()\n    node.add_input_opt('--veto-definer-file', vdf_file)\n    node.new_output_file_opt(workflow.analysis_time, '.html', '--output-file')\n    workflow += node\n    return node.output_files[0]",
    "docstring": "Creates a node in the workflow for writing the veto_definer\n    table. Returns a File instances for the output file."
  },
  {
    "code": "def push_doc(self, document):\n        msg = self._protocol.create('PUSH-DOC', document)\n        reply = self._send_message_wait_for_reply(msg)\n        if reply is None:\n            raise RuntimeError(\"Connection to server was lost\")\n        elif reply.header['msgtype'] == 'ERROR':\n            raise RuntimeError(\"Failed to push document: \" + reply.content['text'])\n        else:\n            return reply",
    "docstring": "Push a document to the server, overwriting any existing server-side doc.\n\n        Args:\n            document : (Document)\n                A Document to push to the server\n\n        Returns:\n            The server reply"
  },
  {
    "code": "def send_hid_event(use_page, usage, down):\n    message = create(protobuf.SEND_HID_EVENT_MESSAGE)\n    event = message.inner()\n    abstime = binascii.unhexlify(b'438922cf08020000')\n    data = use_page.to_bytes(2, byteorder='big')\n    data += usage.to_bytes(2, byteorder='big')\n    data += (1 if down else 0).to_bytes(2, byteorder='big')\n    event.hidEventData = abstime + \\\n        binascii.unhexlify(b'00000000000000000100000000000000020' +\n                           b'00000200000000300000001000000000000') + \\\n        data + \\\n        binascii.unhexlify(b'0000000000000001000000')\n    return message",
    "docstring": "Create a new SEND_HID_EVENT_MESSAGE."
  },
  {
    "code": "def value(self, cell):\n        if self._value is not None:\n            return self._value(cell)\n        else:\n            return cell.value",
    "docstring": "Extract the value of ``cell``, ready to be rendered.\n\n        If this Column was instantiated with a ``value`` attribute, it\n        is called here to provide the value. (For example, to provide a\n        calculated value.) Otherwise, ``cell.value`` is returned."
  },
  {
    "code": "def _rel_import(module, tgt):\n    try:\n        exec(\"from .\" + module + \" import \" + tgt, globals(), locals())\n    except SyntaxError:\n        exec(\"from \" + module + \" import \" + tgt, globals(), locals())\n    except (ValueError, SystemError):\n        exec(\"from \" + module + \" import \" + tgt, globals(), locals())\n    return eval(tgt)",
    "docstring": "Using relative import in both Python 2 and Python 3"
  },
  {
    "code": "def getLiftOps(self, valu, cmpr='='):\n        if valu is None:\n            iops = (('pref', b''),)\n            return (\n                ('indx', ('byprop', self.pref, iops)),\n            )\n        if cmpr == '~=':\n            return (\n                ('form:re', (self.name, valu, {})),\n            )\n        lops = self.type.getLiftOps('form', cmpr, (None, self.name, valu))\n        if lops is not None:\n            return lops\n        iops = self.type.getIndxOps(valu, cmpr)\n        return (\n            ('indx', ('byprop', self.pref, iops)),\n        )",
    "docstring": "Get a set of lift operations for use with an Xact."
  },
  {
    "code": "def paths_for_shell(paths, separator=' '):\n    paths = filter(None, paths)\n    paths = map(shlex.quote, paths)\n    if separator is None:\n        return paths\n    return separator.join(paths)",
    "docstring": "Converts a list of paths for use in shell commands"
  },
  {
    "code": "def _apply_options(self, token):\n        if token.is_punct and self.remove_punct:\n            return None\n        if token.is_stop and self.remove_stop_words:\n            return None\n        if token.is_digit and self.remove_digits:\n            return None\n        if token.is_oov and self.exclude_oov:\n            return None\n        if token.pos_ in self.exclude_pos_tags:\n            return None\n        if token.ent_type_ in self.exclude_entities:\n            return None\n        if self.lemmatize:\n            return token.lemma_\n        if self.lower:\n            return token.lower_\n        return token.orth_",
    "docstring": "Applies various filtering and processing options on token.\n\n        Returns:\n            The processed token. None if filtered."
  },
  {
    "code": "def alpha_senders(self):\n        if self._alpha_senders is None:\n            self._alpha_senders = AlphaSenderList(self._version, service_sid=self._solution['sid'], )\n        return self._alpha_senders",
    "docstring": "Access the alpha_senders\n\n        :returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderList\n        :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderList"
  },
  {
    "code": "def execute_job(job, app=Injected, task_router=Injected):\n    app.logger.info(\"Job fetched, preparing the task '{0}'.\".format(job.path))\n    task, task_callable = task_router.route(job.path)\n    jc = JobContext(job, task, task_callable)\n    app.logger.info(\"Executing task.\")\n    result = jc.task_callable(jc.task_data)\n    app.logger.info(\"Task {0} executed successfully.\".format(job.path))\n    return {'task_name': job.path, 'data': result}",
    "docstring": "Execute a job.\n\n    :param job: job to execute\n    :type job: Job\n    :param app: service application instance, injected\n    :type app: ServiceApplication\n    :param task_router: task router instance, injected\n    :type task_router: TaskRouter\n    :return: task result\n    :rtype: dict"
  },
  {
    "code": "def _get_package_status(package):\n    status = package[\"status_str\"] or \"Unknown\"\n    stage = package[\"stage_str\"] or \"Unknown\"\n    if stage == \"Fully Synchronised\":\n        return status\n    return \"%(status)s / %(stage)s\" % {\"status\": status, \"stage\": stage}",
    "docstring": "Get the status for a package."
  },
  {
    "code": "def input_variables(self, exclude_specials=True):\n        def has_write_access(accesses):\n            return any(acc for acc in accesses if acc.access_type == 'write')\n        def has_read_access(accesses):\n            return any(acc for acc in accesses if acc.access_type == 'read')\n        input_variables = [ ]\n        for variable, accesses in self._variable_accesses.items():\n            if not has_write_access(accesses) and has_read_access(accesses):\n                if not exclude_specials or not variable.category:\n                    input_variables.append(variable)\n        return input_variables",
    "docstring": "Get all variables that have never been written to.\n\n        :return: A list of variables that are never written to."
  },
  {
    "code": "def peek_64(library, session, address):\n    value_64 = ViUInt64()\n    ret = library.viPeek64(session, address, byref(value_64))\n    return value_64.value, ret",
    "docstring": "Read an 64-bit value from the specified address.\n\n    Corresponds to viPeek64 function of the VISA library.\n\n    :param library: the visa library wrapped by ctypes.\n    :param session: Unique logical identifier to a session.\n    :param address: Source address to read the value.\n    :return: Data read from bus, return value of the library call.\n    :rtype: bytes, :class:`pyvisa.constants.StatusCode`"
  },
  {
    "code": "def register_processor(self, processor):\n        if not callable(processor):\n            raise ValueError('Processor %s is not callable.' % processor.__class__.__name__)\n        else:\n            self.processors.append(processor)",
    "docstring": "Register a new processor.\n\n        Note that processors are called in the order that they are registered."
  },
  {
    "code": "def PWS_stack(streams, weight=2, normalize=True):\n    Linstack = linstack(streams)\n    instaphases = []\n    print(\"Computing instantaneous phase\")\n    for stream in streams:\n        instaphase = stream.copy()\n        for tr in instaphase:\n            analytic = hilbert(tr.data)\n            envelope = np.sqrt(np.sum((np.square(analytic),\n                                       np.square(tr.data)), axis=0))\n            tr.data = analytic / envelope\n        instaphases.append(instaphase)\n    print(\"Computing the phase stack\")\n    Phasestack = linstack(instaphases, normalize=normalize)\n    for tr in Phasestack:\n        tr.data = Linstack.select(station=tr.stats.station)[0].data *\\\n            np.abs(tr.data ** weight)\n    return Phasestack",
    "docstring": "Compute the phase weighted stack of a series of streams.\n\n    .. note:: It is recommended to align the traces before stacking.\n\n    :type streams: list\n    :param streams: List of :class:`obspy.core.stream.Stream` to stack.\n    :type weight: float\n    :param weight: Exponent to the phase stack used for weighting.\n    :type normalize: bool\n    :param normalize: Normalize traces before stacking.\n\n    :return: Stacked stream.\n    :rtype: :class:`obspy.core.stream.Stream`"
  },
  {
    "code": "def _parse_command_line():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        '--portserver_static_pool',\n        type=str,\n        default='15000-24999',\n        help='Comma separated N-P Range(s) of ports to manage (inclusive).')\n    parser.add_argument(\n        '--portserver_unix_socket_address',\n        type=str,\n        default='@unittest-portserver',\n        help='Address of AF_UNIX socket on which to listen (first @ is a NUL).')\n    parser.add_argument('--verbose',\n                        action='store_true',\n                        default=False,\n                        help='Enable verbose messages.')\n    parser.add_argument('--debug',\n                        action='store_true',\n                        default=False,\n                        help='Enable full debug messages.')\n    return parser.parse_args(sys.argv[1:])",
    "docstring": "Configure and parse our command line flags."
  },
  {
    "code": "def command_line(argv):\n    arguments = parse_command_line(argv)\n    if arguments.generate:\n        generate_fixer_file(arguments.generate)\n    paths = edit_files(arguments.patterns,\n                       expressions=arguments.expressions,\n                       functions=arguments.functions,\n                       executables=arguments.executables,\n                       start_dirs=arguments.start_dirs,\n                       max_depth=arguments.max_depth,\n                       dry_run=arguments.dry_run,\n                       output=arguments.output,\n                       encoding=arguments.encoding,\n                       newline=arguments.newline)\n    is_sys = arguments.output in [sys.stdout, sys.stderr]\n    if not is_sys and isinstance(arguments.output, io.IOBase):\n        arguments.output.close()\n    return paths",
    "docstring": "Instantiate an editor and process arguments.\n\n    Optional argument:\n      - processed_paths: paths processed are appended to the list."
  },
  {
    "code": "def get_weights_fn(modality_type, value=None):\n  if modality_type in (ModalityType.CTC_SYMBOL,\n                       ModalityType.IDENTITY_SYMBOL,\n                       ModalityType.MULTI_LABEL,\n                       ModalityType.SYMBOL,\n                       ModalityType.SYMBOL_ONE_HOT):\n    return common_layers.weights_nonzero\n  elif modality_type in ModalityType.get_choices():\n    return common_layers.weights_all\n  return value",
    "docstring": "Gets default weights function; if none available, return value."
  },
  {
    "code": "def parse_from_parent(\n            self,\n            parent,\n            state\n    ):\n        parsed_dict = self._dictionary.parse_from_parent(parent, state)\n        return self._converter.from_dict(parsed_dict)",
    "docstring": "Parse the aggregate from the provided parent XML element."
  },
  {
    "code": "def pipe(cmd, txt):\n    return Popen(\n        cmd2args(cmd),\n        stdout=subprocess.PIPE,\n        stdin=subprocess.PIPE,\n        shell=win32\n    ).communicate(txt)[0]",
    "docstring": "Pipe `txt` into the command `cmd` and return the output."
  },
  {
    "code": "def resolve_nodes(self, nodes):\n        if not nodes:\n            return []\n        resolved = []\n        for node in nodes:\n            if node in resolved:\n                continue\n            self.resolve_node(node, resolved)\n        return resolved",
    "docstring": "Resolve a given set of nodes.\n\n        Dependencies of the nodes, even if they are not in the given list will\n        also be resolved!\n\n        :param list nodes: List of nodes to be resolved\n        :return: A list of resolved nodes"
  },
  {
    "code": "def validate(bo, error_level: str = \"WARNING\") -> Tuple[bool, List[Tuple[str, str]]]:\n    if bo.ast:\n        bo = validate_functions(bo.ast, bo)\n        if error_level == \"WARNING\":\n            bo = validate_arg_values(bo.ast, bo)\n    else:\n        bo.validation_messages.append((\"ERROR\", \"Invalid BEL Statement - cannot parse\"))\n    for msg in bo.validation_messages:\n        if msg[0] == \"ERROR\":\n            bo.parse_valid = False\n            break\n    return bo",
    "docstring": "Semantically validate BEL AST\n\n    Add errors and warnings to bel_obj.validation_messages\n\n    Error Levels are similar to log levels - selecting WARNING includes both\n    WARNING and ERROR, selecting ERROR just includes ERROR\n\n    Args:\n        bo: main BEL language object\n        error_level: return ERRORs only or also WARNINGs\n\n    Returns:\n        Tuple[bool, List[Tuple[str, str]]]: (is_valid, messages)"
  },
  {
    "code": "def cancel(self):\n        with self._lock:\n            if self._state not in (self.S_PENDING, self.S_RUNNING):\n                return False\n            self._result = Cancelled('cancelled by Future.cancel()')\n            self._state = self.S_EXCEPTION\n            self._done.set()\n            return True",
    "docstring": "Cancel the execution of the async function, if possible.\n\n        This method marks the future as done and sets the :class:`Cancelled`\n        exception.\n\n        A future that is not running can always be cancelled. However when a\n        future is running, the ability to cancel it depends on the pool\n        implementation. For example, a fiber pool can cancel running fibers but\n        a thread pool cannot.\n\n        Return ``True`` if the future could be cancelled, ``False`` otherwise."
  },
  {
    "code": "def cli(env, **args):\n    create_args = _parse_create_args(env.client, args)\n    create_args['primary_disk'] = args.get('primary_disk')\n    manager = CapacityManager(env.client)\n    capacity_id = args.get('capacity_id')\n    test = args.get('test')\n    result = manager.create_guest(capacity_id, test, create_args)\n    env.fout(_build_receipt(result, test))",
    "docstring": "Allows for creating a virtual guest in a reserved capacity."
  },
  {
    "code": "def attr_category_postprocess(get_attr_category_func):\n    @functools.wraps(get_attr_category_func)\n    def wrapped(\n        name: str, attr: Any, obj: Any\n    ) -> Tuple[AttrCategory, ...]:\n        category = get_attr_category_func(name, attr, obj)\n        category = list(category) if isinstance(category, tuple) else [category]\n        if is_slotted_attr(obj, name):\n            category.append(AttrCategory.SLOT)\n        return tuple(category)\n    return wrapped",
    "docstring": "Unifies attr_category to a tuple, add AttrCategory.SLOT if needed."
  },
  {
    "code": "def generate_id(self, agreement_id, types, values):\n        values_hash = utils.generate_multi_value_hash(types, values)\n        return utils.generate_multi_value_hash(\n            ['bytes32', 'address', 'bytes32'],\n            [agreement_id, self.address, values_hash]\n        )",
    "docstring": "Generate id for the condition.\n\n        :param agreement_id: id of the agreement, hex str\n        :param types: list of types\n        :param values: list of values\n        :return: id, str"
  },
  {
    "code": "def index_by(self, column_or_label):\n        column = self._get_column(column_or_label)\n        index = {}\n        for key, row in zip(column, self.rows):\n            index.setdefault(key, []).append(row)\n        return index",
    "docstring": "Return a dict keyed by values in a column that contains lists of\n        rows corresponding to each value."
  },
  {
    "code": "def cmd(send, *_):\n    a = [\"primary\", \"secondary\", \"tertiary\", \"hydraulic\", \"compressed\", \"required\", \"pseudo\", \"intangible\", \"flux\"]\n    b = [\n        \"compressor\", \"engine\", \"lift\", \"elevator\", \"irc bot\", \"stabilizer\", \"computer\", \"fwilson\", \"csl\", \"4506\", \"router\", \"switch\", \"thingy\",\n        \"capacitor\"\n    ]\n    c = [\n        \"broke\", \"exploded\", \"corrupted\", \"melted\", \"froze\", \"died\", \"reset\", \"was seen by the godofskies\", \"burned\", \"corroded\", \"reversed polarity\",\n        \"was accidentallied\", \"nuked\"\n    ]\n    send(\"because %s %s %s\" % ((choice(a), choice(b), choice(c))))",
    "docstring": "Gives a reason for something.\n\n    Syntax: {command}"
  },
  {
    "code": "def resolve_filenames(all_expr):\n        files = []\n        for expr in all_expr.split(','):\n            expr = expr.strip()\n            files += fs.get_fs(expr).resolve_filenames(expr)\n        log.debug('Filenames: {0}'.format(files))\n        return files",
    "docstring": "resolve expression for a filename\n\n        :param all_expr:\n            A comma separated list of expressions. The expressions can contain\n            the wildcard characters ``*`` and ``?``. It also resolves Spark\n            datasets to the paths of the individual partitions\n            (i.e. ``my_data`` gets resolved to\n            ``[my_data/part-00000, my_data/part-00001]``).\n\n        :returns: A list of file names.\n        :rtype: list"
  },
  {
    "code": "def is_outlier(df, item_id, segment_id, price):\n    if (segment_id, item_id) not in df.index:\n        return False\n    mean = df.loc[(segment_id, item_id)]['mean']\n    std = df.loc[(segment_id, item_id)]['std']\n    return gaussian_outlier.is_outlier(\n        x=price, mean=mean, standard_deviation=std\n    )",
    "docstring": "Verify if a item is an outlier compared to the\n    other occurrences of the same item, based on his price.\n\n    Args:\n        item_id: idPlanilhaItens\n        segment_id: idSegmento\n        price: VlUnitarioAprovado"
  },
  {
    "code": "def getDetectorClassConstructors(detectors):\n  detectorConstructors = {\n  d : globals()[detectorNameToClass(d)] for d in detectors}\n  return detectorConstructors",
    "docstring": "Takes in names of detectors. Collects class names that correspond to those\n  detectors and returns them in a dict. The dict maps detector name to class\n  names. Assumes the detectors have been imported."
  },
  {
    "code": "def file_contents(file_name):\n    curr_dir = os.path.abspath(os.path.dirname(__file__))\n    with open(os.path.join(curr_dir, file_name)) as the_file:\n        contents = the_file.read()\n    return contents",
    "docstring": "Given a file name to a valid file returns the file object."
  },
  {
    "code": "def run(self, funcs):\n    funcs = [f if callable(f) else functools.partial(*f) for f in funcs]\n    if len(funcs) == 1:\n      return [funcs[0]()]\n    if len(funcs) > self._workers:\n      self.shutdown()\n      self._workers = len(funcs)\n      self._executor = futures.ThreadPoolExecutor(self._workers)\n    futs = [self._executor.submit(f) for f in funcs]\n    done, not_done = futures.wait(futs, self._timeout, futures.FIRST_EXCEPTION)\n    for f in done:\n      if not f.cancelled() and f.exception() is not None:\n        if not_done:\n          for nd in not_done:\n            nd.cancel()\n          self.shutdown(False)\n        raise f.exception()\n    return [f.result(timeout=0) for f in futs]",
    "docstring": "Run a set of functions in parallel, returning their results.\n\n    Make sure any function you pass exits with a reasonable timeout. If it\n    doesn't return within the timeout or the result is ignored due an exception\n    in a separate thread it will continue to stick around until it finishes,\n    including blocking process exit.\n\n    Args:\n      funcs: An iterable of functions or iterable of args to functools.partial.\n\n    Returns:\n      A list of return values with the values matching the order in funcs.\n\n    Raises:\n      Propagates the first exception encountered in one of the functions."
  },
  {
    "code": "def set_unit_desired_state(self, unit, desired_state):\n        if desired_state not in self._STATES:\n            raise ValueError('state must be one of: {0}'.format(\n                self._STATES\n            ))\n        if isinstance(unit, Unit):\n            unit = unit.name\n        else:\n            unit = str(unit)\n        self._single_request('Units.Set', unitName=unit, body={\n            'desiredState': desired_state\n        })\n        return self.get_unit(unit)",
    "docstring": "Update the desired state of a unit running in the cluster\n\n        Args:\n            unit (str, Unit): The Unit, or name of the unit to update\n\n            desired_state: State the user wishes the Unit to be in\n                          (\"inactive\", \"loaded\", or \"launched\")\n        Returns:\n            Unit: The unit that was updated\n\n        Raises:\n            fleet.v1.errors.APIError: Fleet returned a response code >= 400\n            ValueError: An invalid value was provided for ``desired_state``"
  },
  {
    "code": "def get_view_name(view_cls, suffix=None):\n    name = view_cls.__name__\n    name = formatting.remove_trailing_string(name, 'View')\n    name = formatting.remove_trailing_string(name, 'ViewSet')\n    name = formatting.camelcase_to_spaces(name)\n    if suffix:\n        name += ' ' + suffix\n    return name",
    "docstring": "Given a view class, return a textual name to represent the view.\n    This name is used in the browsable API, and in OPTIONS responses.\n\n    This function is the default for the `VIEW_NAME_FUNCTION` setting."
  },
  {
    "code": "def list_presets(cfg, out=sys.stdout):\n    for section in cfg.sections():\n        if section.startswith(\"preset:\"):\n            out.write((section.replace(\"preset:\", \"\")) + os.linesep)\n            for k, v in cfg.items(section):\n                out.write(\"\\t%s = %s\" % (k, v) + os.linesep)",
    "docstring": "Write a human readable list of available presets to out.\n\n    :param cfg: ConfigParser instance\n    :param out: file object to write to"
  },
  {
    "code": "def _normalize_batch(b:Tuple[Tensor,Tensor], mean:FloatTensor, std:FloatTensor, do_x:bool=True, do_y:bool=False)->Tuple[Tensor,Tensor]:\n    \"`b` = `x`,`y` - normalize `x` array of imgs and `do_y` optionally `y`.\"\n    x,y = b\n    mean,std = mean.to(x.device),std.to(x.device)\n    if do_x: x = normalize(x,mean,std)\n    if do_y and len(y.shape) == 4: y = normalize(y,mean,std)\n    return x,y",
    "docstring": "`b` = `x`,`y` - normalize `x` array of imgs and `do_y` optionally `y`."
  },
  {
    "code": "def getKey(self, namespace, ns_key):\n        namespace = self._fixNS(namespace)\n        if namespace == BARE_NS:\n            return ns_key\n        ns_alias = self.namespaces.getAlias(namespace)\n        if ns_alias is None:\n            return None\n        if ns_alias == NULL_NAMESPACE:\n            tail = ns_key\n        else:\n            tail = '%s.%s' % (ns_alias, ns_key)\n        return 'openid.' + tail",
    "docstring": "Get the key for a particular namespaced argument"
  },
  {
    "code": "def _hierarchy_bounds(intervals_hier):\n    boundaries = list(itertools.chain(*list(itertools.chain(*intervals_hier))))\n    return min(boundaries), max(boundaries)",
    "docstring": "Compute the covered time range of a hierarchical segmentation.\n\n    Parameters\n    ----------\n    intervals_hier : list of ndarray\n        A hierarchical segmentation, encoded as a list of arrays of segment\n        intervals.\n\n    Returns\n    -------\n    t_min : float\n    t_max : float\n        The minimum and maximum times spanned by the annotation"
  },
  {
    "code": "def strip_keys(d, nones=False, depth=0):\n    r\n    ans = type(d)((str(k).strip(), v) for (k, v) in viewitems(OrderedDict(d))\n                  if (not nones or (str(k).strip() and str(k).strip() != 'None')))\n    if int(depth) < 1:\n        return ans\n    if int(depth) > strip_keys.MAX_DEPTH:\n        warnings.warn(RuntimeWarning(\"Maximum recursion depth allowance (%r) exceeded.\" % strip_keys.MAX_DEPTH))\n    for k, v in viewitems(ans):\n        if isinstance(v, Mapping):\n            ans[k] = strip_keys(v, nones=nones, depth=int(depth) - 1)\n    return ans",
    "docstring": "r\"\"\"Strip whitespace from all dictionary keys, to the depth indicated\n\n    >>> strip_keys({' a': ' a', ' b\\t c ': {'d e  ': 'd e  '}}) == {'a': ' a', 'b\\t c': {'d e  ': 'd e  '}}\n    True\n    >>> strip_keys({' a': ' a', ' b\\t c ': {'d e  ': 'd e  '}}, depth=100) == {'a': ' a', 'b\\t c': {'d e': 'd e  '}}\n    True"
  },
  {
    "code": "def tyn_calus_scaling(target, DABo, To, mu_o, viscosity='pore.viscosity',\n                      temperature='pore.temperature'):\n    r\n    Ti = target[temperature]\n    mu_i = target[viscosity]\n    value = DABo*(Ti/To)*(mu_o/mu_i)\n    return value",
    "docstring": "r\"\"\"\n    Uses Tyn_Calus model to adjust a diffusion coeffciient for liquids from\n    reference conditions to conditions of interest\n\n    Parameters\n    ----------\n    target : OpenPNM Object\n        The object for which these values are being calculated.  This\n        controls the length of the calculated array, and also provides\n        access to other necessary thermofluid properties.\n\n    DABo : float, array_like\n        Diffusion coefficient at reference conditions\n\n    mu_o, To : float, array_like\n        Viscosity & temperature at reference conditions, respectively\n\n    pressure : string\n        The dictionary key containing the pressure values in Pascals (Pa)\n\n    temperature : string\n        The dictionary key containing the temperature values in Kelvin (K)"
  },
  {
    "code": "def channel_state_until_state_change(\n        raiden,\n        canonical_identifier: CanonicalIdentifier,\n        state_change_identifier: int,\n) -> typing.Optional[NettingChannelState]:\n    wal = restore_to_state_change(\n        transition_function=node.state_transition,\n        storage=raiden.wal.storage,\n        state_change_identifier=state_change_identifier,\n    )\n    msg = 'There is a state change, therefore the state must not be None'\n    assert wal.state_manager.current_state is not None, msg\n    chain_state = wal.state_manager.current_state\n    channel_state = views.get_channelstate_by_canonical_identifier(\n        chain_state=chain_state,\n        canonical_identifier=canonical_identifier,\n    )\n    if not channel_state:\n        raise RaidenUnrecoverableError(\n            f\"Channel was not found before state_change {state_change_identifier}\",\n        )\n    return channel_state",
    "docstring": "Go through WAL state changes until a certain balance hash is found."
  },
  {
    "code": "def local_regon(self):\n        regon_digits = [int(digit) for digit in list(self.regon())]\n        for _ in range(4):\n            regon_digits.append(self.random_digit())\n        regon_digits.append(local_regon_checksum(regon_digits))\n        return ''.join(str(digit) for digit in regon_digits)",
    "docstring": "Returns 14 character Polish National Business Registry Number,\n        local entity number.\n\n        https://pl.wikipedia.org/wiki/REGON"
  },
  {
    "code": "def _bg(self, coro: coroutine) -> asyncio.Task:\n        async def runner():\n            try:\n                await coro\n            except:\n                self._log.exception(\"async: Coroutine raised exception\")\n        return asyncio.ensure_future(runner())",
    "docstring": "Run coro in background, log errors"
  },
  {
    "code": "def center_kernel(kernel, iterations=20):\n    kernel = kernel_norm(kernel)\n    nx, ny = np.shape(kernel)\n    if nx %2 == 0:\n        raise ValueError(\"kernel needs odd number of pixels\")\n    x_grid, y_grid = util.make_grid(nx, deltapix=1, left_lower=False)\n    x_w = np.sum(kernel * util.array2image(x_grid))\n    y_w = np.sum(kernel * util.array2image(y_grid))\n    kernel_centered = de_shift_kernel(kernel, shift_x=-x_w, shift_y=-y_w, iterations=iterations)\n    return kernel_norm(kernel_centered)",
    "docstring": "given a kernel that might not be perfectly centered, this routine computes its light weighted center and then\n    moves the center in an iterative process such that it is centered\n\n    :param kernel: 2d array (odd numbers)\n    :param iterations: int, number of iterations\n    :return: centered kernel"
  },
  {
    "code": "def inject(function):\n    try:\n        bindings = _infer_injected_bindings(function)\n    except _BindingNotYetAvailable:\n        bindings = 'deferred'\n    return method_wrapper(function, bindings)",
    "docstring": "Decorator declaring parameters to be injected.\n\n    eg.\n\n    >>> Sizes = Key('sizes')\n    >>> Names = Key('names')\n    >>>\n    >>> class A:\n    ...     @inject\n    ...     def __init__(self, number: int, name: str, sizes: Sizes):\n    ...         print([number, name, sizes])\n    ...\n    >>> def configure(binder):\n    ...     binder.bind(A)\n    ...     binder.bind(int, to=123)\n    ...     binder.bind(str, to='Bob')\n    ...     binder.bind(Sizes, to=[1, 2, 3])\n\n    Use the Injector to get a new instance of A:\n\n    >>> a = Injector(configure).get(A)\n    [123, 'Bob', [1, 2, 3]]\n\n    .. note::\n\n        This decorator is to be used on class constructors. Using it on non-constructor\n        methods worked in the past but it was an implementation detail rather than\n        a design decision.\n\n        Third party libraries may, however, provide support for injecting dependencies\n        into non-constructor methods or free functions in one form or another."
  },
  {
    "code": "def sendToViewChanger(self, msg, frm):\n        if (isinstance(msg, InstanceChange) or\n                self.msgHasAcceptableViewNo(msg, frm)):\n            logger.debug(\"{} sending message to view changer: {}\".\n                         format(self, (msg, frm)))\n            self.msgsToViewChanger.append((msg, frm))",
    "docstring": "Send the message to the intended view changer.\n\n        :param msg: the message to send\n        :param frm: the name of the node which sent this `msg`"
  },
  {
    "code": "def callable_validator(instance, attribute, value):\n    if not callable(value):\n        raise TypeError('\"{name}\" value \"{value}\" must be callable'.format(name=attribute.name, value=value))",
    "docstring": "Validate that an attribute value is callable.\n\n    :raises TypeError: if ``value`` is not callable"
  },
  {
    "code": "def create(self, ttl=values.unset):\n        data = values.of({'Ttl': ttl, })\n        payload = self._version.create(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return TokenInstance(self._version, payload, account_sid=self._solution['account_sid'], )",
    "docstring": "Create a new TokenInstance\n\n        :param unicode ttl: The duration in seconds the credentials are valid\n\n        :returns: Newly created TokenInstance\n        :rtype: twilio.rest.api.v2010.account.token.TokenInstance"
  },
  {
    "code": "def _depth_event(self, msg):\n        if 'e' in msg and msg['e'] == 'error':\n            self.close()\n            if self._callback:\n                self._callback(None)\n        if self._last_update_id is None:\n            self._depth_message_buffer.append(msg)\n        else:\n            self._process_depth_message(msg)",
    "docstring": "Handle a depth event\n\n        :param msg:\n        :return:"
  },
  {
    "code": "def _dict_raise_on_duplicates(ordered_pairs):\n    d = {}\n    for k, v in ordered_pairs:\n        if k in d:\n           raise ValueError(\"duplicate key: %r\" % (k,))\n        else:\n           d[k] = v\n    return d",
    "docstring": "Reject duplicate keys."
  },
  {
    "code": "def _sort_dd_skips(configs, dd_indices_all):\n    config_current_skips = np.abs(configs[:, 1] - configs[:, 0])\n    if np.all(np.isnan(config_current_skips)):\n        return {0: []}\n    available_skips_raw = np.unique(config_current_skips)\n    available_skips = available_skips_raw[\n        ~np.isnan(available_skips_raw)\n    ].astype(int)\n    dd_configs_sorted = {}\n    for skip in available_skips:\n        indices = np.where(config_current_skips == skip)[0]\n        dd_configs_sorted[skip - 1] = dd_indices_all[indices]\n    return dd_configs_sorted",
    "docstring": "Given a set of dipole-dipole configurations, sort them according to\n    their current skip.\n\n    Parameters\n    ----------\n    configs: Nx4 numpy.ndarray\n        Dipole-Dipole configurations\n\n    Returns\n    -------\n    dd_configs_sorted: dict\n        dictionary with the skip as keys, and arrays/lists with indices to\n        these skips."
  },
  {
    "code": "def detect_events(self, max_attempts=3):\n        for _ in xrange(max_attempts):\n            try:\n                with KindleCloudReaderAPI\\\n                        .get_instance(self.uname, self.pword) as kcr:\n                    self.books = kcr.get_library_metadata()\n                    self.progress = kcr.get_library_progress()\n            except KindleAPIError:\n                continue\n            else:\n                break\n        else:\n            return None\n        progress_map = {book.asin: self.progress[book.asin].locs[1]\n                                                for book in self.books}\n        new_events = self._snapshot.calc_update_events(progress_map)\n        update_event = UpdateEvent(datetime.now().replace(microsecond=0))\n        new_events.append(update_event)\n        self._event_buf.extend(new_events)\n        return new_events",
    "docstring": "Returns a list of `Event`s detected from differences in state\n        between the current snapshot and the Kindle Library.\n\n        `books` and `progress` attributes will be set with the latest API\n        results upon successful completion of the function.\n\n        Returns:\n            If failed to retrieve progress, None\n            Else, the list of `Event`s"
  },
  {
    "code": "def rev_reg_id2cred_def_id(rr_id: str) -> str:\n    if ok_rev_reg_id(rr_id):\n        return ':'.join(rr_id.split(':')[2:-2])\n    raise BadIdentifier('Bad revocation registry identifier {}'.format(rr_id))",
    "docstring": "Given a revocation registry identifier, return its corresponding credential definition identifier.\n    Raise BadIdentifier if input is not a revocation registry identifier.\n\n    :param rr_id: revocation registry identifier\n    :return: credential definition identifier"
  },
  {
    "code": "def _file_md5(file_):\n    md5 = hashlib.md5()\n    chunk_size = 128 * md5.block_size\n    for chunk in iter(lambda: file_.read(chunk_size), b''):\n        md5.update(chunk)\n    file_.seek(0)\n    byte_digest = md5.digest()\n    return base64.b64encode(byte_digest).decode()",
    "docstring": "Compute the md5 digest of a file in base64 encoding."
  },
  {
    "code": "def _connect(self):\n        if self._connParams:\n            self._conn = psycopg2.connect(**self._connParams)\n        else:\n            self._conn = psycopg2.connect('')\n        try:\n            ver_str = self._conn.get_parameter_status('server_version')\n        except AttributeError:\n            ver_str = self.getParam('server_version')\n        self._version = util.SoftwareVersion(ver_str)",
    "docstring": "Establish connection to PostgreSQL Database."
  },
  {
    "code": "def status_set(workload_state, message):\n    valid_states = ['maintenance', 'blocked', 'waiting', 'active']\n    if workload_state not in valid_states:\n        raise ValueError(\n            '{!r} is not a valid workload state'.format(workload_state)\n        )\n    cmd = ['status-set', workload_state, message]\n    try:\n        ret = subprocess.call(cmd)\n        if ret == 0:\n            return\n    except OSError as e:\n        if e.errno != errno.ENOENT:\n            raise\n    log_message = 'status-set failed: {} {}'.format(workload_state,\n                                                    message)\n    log(log_message, level='INFO')",
    "docstring": "Set the workload state with a message\n\n    Use status-set to set the workload state with a message which is visible\n    to the user via juju status. If the status-set command is not found then\n    assume this is juju < 1.23 and juju-log the message unstead.\n\n    workload_state -- valid juju workload state.\n    message        -- status update message"
  },
  {
    "code": "def _get_method(self, request):\n        methodname = request.method.lower()\n        method = getattr(self, methodname, None)\n        if not method or not callable(method):\n            raise errors.MethodNotAllowed()\n        return method",
    "docstring": "Figure out the requested method and return the callable."
  },
  {
    "code": "def pprint(self, num=10):\n        def pprint_map(time_, rdd):\n            print('>>> Time: {}'.format(time_))\n            data = rdd.take(num + 1)\n            for d in data[:num]:\n                py_pprint.pprint(d)\n            if len(data) > num:\n                print('...')\n            print('')\n        self.foreachRDD(pprint_map)",
    "docstring": "Print the first ``num`` elements of each RDD.\n\n        :param int num: Set number of elements to be printed."
  },
  {
    "code": "def extract_stream(source, dest, stream_id):\n    if not os.path.isfile(source):\n        raise IOError('No such file: ' + source)\n    subprocess.check_output([\n        'ffmpeg',\n        '-i', source,\n        '-y',\n        '-nostats',\n        '-loglevel', '0',\n        '-codec', 'copy',\n        '-map', '0:' + str(stream_id),\n        '-f', 'rawvideo',\n        dest,\n    ])",
    "docstring": "Get the data out of the file using ffmpeg\n    @param filename: mp4 filename"
  },
  {
    "code": "def Q(self):\n        N = self.N\n        tig_to_idx = self.tig_to_idx\n        signs = self.signs\n        Q = np.ones((N, N, BB), dtype=int) * -1\n        for (at, bt), k in self.contacts_oriented.items():\n            if not (at in tig_to_idx and bt in tig_to_idx):\n                continue\n            ai = tig_to_idx[at]\n            bi = tig_to_idx[bt]\n            ao = signs[ai]\n            bo = signs[bi]\n            Q[ai, bi] = k[(ao, bo)]\n        return Q",
    "docstring": "Contact frequency matrix when contigs are already oriented. This is s a\n        similar matrix as M, but rather than having the number of links in the\n        cell, it points to an array that has the actual distances."
  },
  {
    "code": "def from_iterable(cls, target_types, address_mapper, adaptor_iter):\n    inst = cls(target_types, address_mapper)\n    all_valid_addresses = set()\n    for target_adaptor in adaptor_iter:\n      inst._inject_target(target_adaptor)\n      all_valid_addresses.add(target_adaptor.address)\n    inst._validate(all_valid_addresses)\n    return inst",
    "docstring": "Create a new DependentGraph from an iterable of TargetAdaptor subclasses."
  },
  {
    "code": "def post_comment(self, message):\n        report_url = (\n            'https://api.github.com/repos/%s/issues/%s/comments'\n            % (self.repo_name, self.pr_number)\n        )\n        result = self.requester.post(report_url, {'body': message})\n        if result.status_code >= 400:\n            log.error(\"Error posting comment to github. %s\", result.json())\n        return result",
    "docstring": "Comments on an issue, not on a particular line."
  },
  {
    "code": "def get_file_for_id(_id, language=DEFAULT_LANG):\n        file_start = '%s-' % _id\n        json_path = DBVuln.get_json_path(language=language)\n        for _file in os.listdir(json_path):\n            if _file.startswith(file_start):\n                return os.path.join(json_path, _file)\n        raise NotFoundException('No data for ID %s' % _id)",
    "docstring": "Given _id, search the DB for the file which contains the data\n\n        :param _id: The id to search (int)\n        :param language: The user's language (en, es, etc.)\n        :return: The filename"
  },
  {
    "code": "def exists(Name,\n           region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        conn.get_trail_status(Name=Name)\n        return {'exists': True}\n    except ClientError as e:\n        err = __utils__['boto3.get_error'](e)\n        if e.response.get('Error', {}).get('Code') == 'TrailNotFoundException':\n            return {'exists': False}\n        return {'error': err}",
    "docstring": "Given a trail name, check to see if the given trail exists.\n\n    Returns True if the given trail exists and returns False if the given\n    trail does not exist.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_cloudtrail.exists mytrail"
  },
  {
    "code": "def get_storage(self, hex_contract_address: str, hex_key: str, is_full: bool = False) -> str:\n        payload = self.generate_json_rpc_payload(RpcMethod.GET_STORAGE, [hex_contract_address, hex_key, 1])\n        response = self.__post(self.__url, payload)\n        if is_full:\n            return response\n        return response['result']",
    "docstring": "This interface is used to get the corresponding stored value\n        based on hexadecimal contract address and stored key.\n\n        :param hex_contract_address: hexadecimal contract address.\n        :param hex_key: a hexadecimal stored key.\n        :param is_full:\n        :return: the information of contract storage."
  },
  {
    "code": "def training_status_renderer_context(exercise_names: List[str], renderman: RenderingManager):\n    renderer = TrainingStatusRenderer(exercise_names, renderman)\n    try:\n        yield renderer\n    finally:\n        renderer.clear_screen()",
    "docstring": "Ensures that the screen is always cleared, even on fatal errors in code\n    that uses this renderer."
  },
  {
    "code": "def summary(self):\n        return {\n            'bestScore': self.bestHsp().score.score,\n            'coverage': self.coverage(),\n            'hspCount': self.hspCount(),\n            'medianScore': self.medianScore(),\n            'readCount': self.readCount(),\n            'subjectLength': self.subjectLength,\n            'subjectTitle': self.subjectTitle,\n        }",
    "docstring": "Summarize the alignments for this subject.\n\n        @return: A C{dict} with C{str} keys:\n            bestScore: The C{float} best score of the matching reads.\n            coverage: The C{float} fraction of the subject genome that is\n                matched by at least one read.\n            hspCount: The C{int} number of hsps that match the subject.\n            medianScore: The C{float} median score of the matching reads.\n            readCount: The C{int} number of reads that match the subject.\n            subjectLength: The C{int} length of the subject.\n            subjectTitle: The C{str} title of the subject."
  },
  {
    "code": "def date_in_range(date1, date2, range):\n    date_obj1 = convert_date(date1)\n    date_obj2 = convert_date(date2)\n    return (date_obj2 - date_obj1).days <= range",
    "docstring": "Check if two date objects are within a specific range"
  },
  {
    "code": "def convert_filename(txtfilename, outdir='.'):\n    return os.path.join(outdir, os.path.basename(txtfilename)).rsplit('.', 1)[0] + '.th'",
    "docstring": "Convert a .TXT filename to a Therion .TH filename"
  },
  {
    "code": "def transition_matrix_non_reversible(C):\n    r\n    rowsums = 1.0 * np.sum(C, axis=1)\n    if np.min(rowsums) <= 0:\n        raise ValueError(\n            \"Transition matrix has row sum of \" + str(np.min(rowsums)) + \". Must have strictly positive row sums.\")\n    return np.divide(C, rowsums[:, np.newaxis])",
    "docstring": "r\"\"\"\n    Estimates a non-reversible transition matrix from count matrix C\n\n    T_ij = c_ij / c_i where c_i = sum_j c_ij\n\n    Parameters\n    ----------\n    C: ndarray, shape (n,n)\n        count matrix\n\n    Returns\n    -------\n    T: Estimated transition matrix"
  },
  {
    "code": "def apply(instance, func, path=None):\n    path = path or os.path.sep\n    if isinstance(instance, list):\n        return [apply(item, func, os.path.join(path, str(i))) for i, item in enumerate(instance)]\n    elif isinstance(instance, dict):\n        return {key: apply(value, func, os.path.join(path, key)) for key, value in instance.items()}\n    return func(instance, path)",
    "docstring": "Apply `func` to all fundamental types of `instance`.\n\n    Parameters\n    ----------\n    instance : dict\n        instance to apply functions to\n    func : callable\n        function with two arguments (instance, path) to apply to all fundamental types recursively\n    path : str\n        path in the document (defaults to '/')\n\n    Returns\n    -------\n    instance : dict\n        instance after applying `func` to fundamental types"
  },
  {
    "code": "def hybrid_forward(self, F, a, b):\n        tilde_a = self.f(a)\n        tilde_b = self.f(b)\n        e = F.batch_dot(tilde_a, tilde_b, transpose_b=True)\n        beta = F.batch_dot(e.softmax(), tilde_b)\n        alpha = F.batch_dot(e.transpose([0, 2, 1]).softmax(), tilde_a)\n        feature1 = self.g(F.concat(tilde_a, beta, dim=2))\n        feature2 = self.g(F.concat(tilde_b, alpha, dim=2))\n        feature1 = feature1.sum(axis=1)\n        feature2 = feature2.sum(axis=1)\n        yhat = self.h(F.concat(feature1, feature2, dim=1))\n        return yhat",
    "docstring": "Forward of Decomposable Attention layer"
  },
  {
    "code": "def draw(self):\r\n        if not self.visible:\r\n            return\r\n        if self.isEnabled:\r\n            if self.mouseIsDown and self.lastMouseDownOverButton and self.mouseOverButton:\r\n                if self.value:\r\n                    self.window.blit(self.surfaceOnDown, self.loc)\r\n                else:\r\n                    self.window.blit(self.surfaceOffDown, self.loc)\r\n            else:\r\n                if self.value:\r\n                    self.window.blit(self.surfaceOn, self.loc)\r\n                else:\r\n                    self.window.blit(self.surfaceOff, self.loc)\r\n        else:\r\n            if self.value:\r\n                self.window.blit(self.surfaceOnDisabled, self.loc)\r\n            else:\r\n                self.window.blit(self.surfaceOffDisabled, self.loc)",
    "docstring": "Draws the checkbox."
  },
  {
    "code": "def valid_replay(info, ping):\n  if (info.HasField(\"error\") or\n      info.base_build != ping.base_build or\n      info.game_duration_loops < 1000 or\n      len(info.player_info) != 2):\n    return False\n  for p in info.player_info:\n    if p.player_apm < 10 or p.player_mmr < 1000:\n      return False\n  return True",
    "docstring": "Make sure the replay isn't corrupt, and is worth looking at."
  },
  {
    "code": "def restore_watched(plex, opts):\n    with open(opts.filepath, 'r') as handle:\n        source = json.load(handle)\n    differences = defaultdict(lambda: dict())\n    for section in _iter_sections(plex, opts):\n        print('Finding differences in %s..' % section.title)\n        skey = section.title.lower()\n        for item in _iter_items(section):\n            ikey = _item_key(item)\n            sval = source.get(skey,{}).get(ikey)\n            if sval is None:\n                raise SystemExit('%s not found' % ikey)\n            if (sval is not None and item.isWatched != sval) and (not opts.watchedonly or sval):\n                differences[skey][ikey] = {'isWatched':sval, 'item':item}\n    print('Applying %s differences to destination' % len(differences))\n    import pprint; pprint.pprint(differences)",
    "docstring": "Restore watched status from the specified filepath."
  },
  {
    "code": "def set_event(self,\n                  simulation_start=None,\n                  simulation_duration=None,\n                  simulation_end=None,\n                  rain_intensity=2,\n                  rain_duration=timedelta(seconds=30*60),\n                  event_type='EVENT',\n                 ):\n        if event_type == 'LONG_TERM':\n            self.event = LongTermMode(self.project_manager,\n                                      self.db_session,\n                                      self.project_directory,\n                                      simulation_start=simulation_start,\n                                      simulation_end=simulation_end,\n                                      simulation_duration=simulation_duration,\n                                     )\n        else:\n            self.event = EventMode(self.project_manager,\n                                   self.db_session,\n                                   self.project_directory,\n                                   simulation_start=simulation_start,\n                                   simulation_duration=simulation_duration,\n                                   )\n            self.event.add_uniform_precip_event(intensity=rain_intensity,\n                                                duration=rain_duration)",
    "docstring": "Initializes event for GSSHA model"
  },
  {
    "code": "def python_to_jupyter_cli(args=None, namespace=None):\n    from . import gen_gallery\n    parser = argparse.ArgumentParser(\n        description='Sphinx-Gallery Notebook converter')\n    parser.add_argument('python_src_file', nargs='+',\n                        help='Input Python file script to convert. '\n                        'Supports multiple files and shell wildcards'\n                        ' (e.g. *.py)')\n    args = parser.parse_args(args, namespace)\n    for src_file in args.python_src_file:\n        file_conf, blocks = split_code_and_text_blocks(src_file)\n        print('Converting {0}'.format(src_file))\n        gallery_conf = copy.deepcopy(gen_gallery.DEFAULT_GALLERY_CONF)\n        example_nb = jupyter_notebook(blocks, gallery_conf)\n        save_notebook(example_nb, replace_py_ipynb(src_file))",
    "docstring": "Exposes the jupyter notebook renderer to the command line\n\n    Takes the same arguments as ArgumentParser.parse_args"
  },
  {
    "code": "def rm_auth_key_from_file(user,\n                          source,\n                          config='.ssh/authorized_keys',\n                          saltenv='base',\n                          fingerprint_hash_type=None):\n    lfile = __salt__['cp.cache_file'](source, saltenv)\n    if not os.path.isfile(lfile):\n        raise CommandExecutionError(\n            'Failed to pull key file from salt file server'\n        )\n    s_keys = _validate_keys(lfile, fingerprint_hash_type)\n    if not s_keys:\n        err = (\n            'No keys detected in {0}. Is file properly formatted?'.format(\n                source\n            )\n        )\n        log.error(err)\n        __context__['ssh_auth.error'] = err\n        return 'fail'\n    else:\n        rval = ''\n        for key in s_keys:\n            rval += rm_auth_key(\n                user,\n                key,\n                config=config,\n                fingerprint_hash_type=fingerprint_hash_type\n            )\n        if 'Key not removed' in rval:\n            return 'Key not removed'\n        elif 'Key removed' in rval:\n            return 'Key removed'\n        else:\n            return 'Key not present'",
    "docstring": "Remove an authorized key from the specified user's authorized key file,\n    using a file as source\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' ssh.rm_auth_key_from_file <user> salt://ssh_keys/<user>.id_rsa.pub"
  },
  {
    "code": "def on_pubmsg(self, connection, event):\n        for message in event.arguments():\n            nickname = self.get_nickname(event)\n            nickname_color = self.nicknames[nickname]\n            self.namespace.emit(\"message\", nickname, message, nickname_color)",
    "docstring": "Messages received in the channel - send them to the WebSocket."
  },
  {
    "code": "def _starting_consonants_only(self, letters: list) -> list:\n        for idx, letter in enumerate(letters):\n            if not self._contains_vowels(letter) and self._contains_consonants(letter):\n                return [idx]\n            if self._contains_vowels(letter):\n                return []\n            if self._contains_vowels(letter) and self._contains_consonants(letter):\n                return []\n        return []",
    "docstring": "Return a list of starting consonant positions."
  },
  {
    "code": "def stdlib(self):\n        if self.module == 'pkg_resources' or self.module.startswith('pkg_resources.'):\n            return False\n        elif self.filename.startswith(SITE_PACKAGES_PATHS):\n            return False\n        elif self.filename.startswith(SYS_PREFIX_PATHS):\n            return True\n        else:\n            return False",
    "docstring": "A boolean flag. ``True`` if frame is in stdlib.\n\n        :type: bool"
  },
  {
    "code": "def write(self, message):\n        try:\n            self.socket.send(message.encode('utf-8') + b'\\0')\n        except socket.error:\n            if not self._closed:\n                raise BrokenPipeError\n        return Future.succeed(None)",
    "docstring": "Coroutine that writes the next packet."
  },
  {
    "code": "def build_if_needed(self):\n        if self._need_build:\n            self._build()\n            self._need_build = False\n        self.update_variables()",
    "docstring": "Reset shader source if necesssary."
  },
  {
    "code": "def emit_metadata_for_region_py(self, region, region_filename, module_prefix):\n        terrobj = self.territory[region]\n        with open(region_filename, \"w\") as outfile:\n            prnt(_REGION_METADATA_PROLOG % {'region': terrobj.identifier(), 'module': module_prefix}, file=outfile)\n            prnt(\"PHONE_METADATA_%s = %s\" % (terrobj.identifier(), terrobj), file=outfile)",
    "docstring": "Emit Python code generating the metadata for the given region"
  },
  {
    "code": "def has_callback(obj, handle):\n    callbacks = obj._callbacks\n    if not callbacks:\n        return False\n    if isinstance(callbacks, Node):\n        return handle is callbacks\n    else:\n        return handle in callbacks",
    "docstring": "Return whether a callback is currently registered for an object."
  },
  {
    "code": "def get_children_metadata(self):\n        metadata = dict(self._mdata['children'])\n        metadata.update({'existing_children_values': self._my_map['childIds']})\n        return Metadata(**metadata)",
    "docstring": "Gets the metadata for children.\n\n        return: (osid.Metadata) - metadata for the children\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def add_inverse_query(self, key_val={}):\n        q = Q(\"match\", **key_val)\n        self.search = self.search.query(~q)\n        return self",
    "docstring": "Add an es_dsl inverse query object to the es_dsl Search object\n\n        :param key_val: a key-value pair(dict) containing the query to be added to the search object\n        :returns: self, which allows the method to be chainable with the other methods"
  },
  {
    "code": "def has_family_notes(family, data_dir=None):\n    file_path = _family_notes_path(family, data_dir)\n    return os.path.isfile(file_path)",
    "docstring": "Check if notes exist for a given family\n\n    Returns True if they exist, false otherwise"
  },
  {
    "code": "def patch():\n    if hasattr(aiobotocore.client, '_xray_enabled'):\n        return\n    setattr(aiobotocore.client, '_xray_enabled', True)\n    wrapt.wrap_function_wrapper(\n        'aiobotocore.client',\n        'AioBaseClient._make_api_call',\n        _xray_traced_aiobotocore,\n    )\n    wrapt.wrap_function_wrapper(\n        'aiobotocore.endpoint',\n        'AioEndpoint.prepare_request',\n        inject_header,\n    )",
    "docstring": "Patch aiobotocore client so it generates subsegments\n    when calling AWS services."
  },
  {
    "code": "def set(self, logicalId, resource):\n        resource_dict = resource\n        if isinstance(resource, SamResource):\n            resource_dict = resource.to_dict()\n        self.resources[logicalId] = resource_dict",
    "docstring": "Adds the resource to dictionary with given logical Id. It will overwrite, if the logicalId is already used.\n\n        :param string logicalId: Logical Id to set to\n        :param SamResource or dict resource: The actual resource data"
  },
  {
    "code": "def _unsigned_bounds(self):\n        ssplit = self._ssplit()\n        if len(ssplit) == 1:\n            lb = ssplit[0].lower_bound\n            ub = ssplit[0].upper_bound\n            return [ (lb, ub) ]\n        elif len(ssplit) == 2:\n            lb_1 = ssplit[0].lower_bound\n            ub_1 = ssplit[0].upper_bound\n            lb_2 = ssplit[1].lower_bound\n            ub_2 = ssplit[1].upper_bound\n            return [ (lb_1, ub_1), (lb_2, ub_2) ]\n        else:\n            raise Exception('WTF')",
    "docstring": "Get lower bound and upper bound for `self` in unsigned arithmetic.\n\n        :return: a list of (lower_bound, upper_bound) tuples."
  },
  {
    "code": "def smooth_rectangle(x, y, rec_w, rec_h, gaussian_width_x, gaussian_width_y):\n    gaussian_x_coord = abs(x)-rec_w/2.0\n    gaussian_y_coord = abs(y)-rec_h/2.0\n    box_x=np.less(gaussian_x_coord,0.0)\n    box_y=np.less(gaussian_y_coord,0.0)\n    sigmasq_x=gaussian_width_x*gaussian_width_x\n    sigmasq_y=gaussian_width_y*gaussian_width_y\n    with float_error_ignore():\n        falloff_x=x*0.0 if sigmasq_x==0.0 else \\\n            np.exp(np.divide(-gaussian_x_coord*gaussian_x_coord,2*sigmasq_x))\n        falloff_y=y*0.0 if sigmasq_y==0.0 else \\\n            np.exp(np.divide(-gaussian_y_coord*gaussian_y_coord,2*sigmasq_y))\n    return np.minimum(np.maximum(box_x,falloff_x), np.maximum(box_y,falloff_y))",
    "docstring": "Rectangle with a solid central region, then Gaussian fall-off at the edges."
  },
  {
    "code": "def astype(self, dtype):\n        dtype = np.dtype(dtype)\n        filters = []\n        if self._filters:\n            filters.extend(self._filters)\n        filters.insert(0, AsType(encode_dtype=self._dtype, decode_dtype=dtype))\n        return self.view(filters=filters, dtype=dtype, read_only=True)",
    "docstring": "Returns a view that does on the fly type conversion of the underlying data.\n\n        Parameters\n        ----------\n        dtype : string or dtype\n            NumPy dtype.\n\n        Notes\n        -----\n        This method returns a new Array object which is a view on the same\n        underlying chunk data. Modifying any data via the view is currently\n        not permitted and will result in an error. This is an experimental\n        feature and its behavior is subject to change in the future.\n\n        See Also\n        --------\n        Array.view\n\n        Examples\n        --------\n\n        >>> import zarr\n        >>> import numpy as np\n        >>> data = np.arange(100, dtype=np.uint8)\n        >>> a = zarr.array(data, chunks=10)\n        >>> a[:]\n        array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,\n               16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,\n               32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,\n               48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,\n               64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,\n               80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,\n               96, 97, 98, 99], dtype=uint8)\n        >>> v = a.astype(np.float32)\n        >>> v.is_view\n        True\n        >>> v[:]\n        array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,\n                10.,  11.,  12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,\n                20.,  21.,  22.,  23.,  24.,  25.,  26.,  27.,  28.,  29.,\n                30.,  31.,  32.,  33.,  34.,  35.,  36.,  37.,  38.,  39.,\n                40.,  41.,  42.,  43.,  44.,  45.,  46.,  47.,  48.,  49.,\n                50.,  51.,  52.,  53.,  54.,  55.,  56.,  57.,  58.,  59.,\n                60.,  61.,  62.,  63.,  64.,  65.,  66.,  67.,  68.,  69.,\n                70.,  71.,  72.,  73.,  74.,  75.,  76.,  77.,  78.,  79.,\n                80.,  81.,  82.,  83.,  84.,  85.,  86.,  87.,  88.,  89.,\n                90.,  91.,  92.,  93.,  94.,  95.,  96.,  97.,  98.,  99.],\n              dtype=float32)"
  },
  {
    "code": "def ping(host, timeout=False, return_boolean=False):\n    if timeout:\n        if __grains__['kernel'] == 'SunOS':\n            cmd = 'ping -c 4 {1} {0}'.format(timeout, salt.utils.network.sanitize_host(host))\n        else:\n            cmd = 'ping -W {0} -c 4 {1}'.format(timeout, salt.utils.network.sanitize_host(host))\n    else:\n        cmd = 'ping -c 4 {0}'.format(salt.utils.network.sanitize_host(host))\n    if return_boolean:\n        ret = __salt__['cmd.run_all'](cmd)\n        if ret['retcode'] != 0:\n            return False\n        else:\n            return True\n    else:\n        return __salt__['cmd.run'](cmd)",
    "docstring": "Performs an ICMP ping to a host\n\n    .. versionchanged:: 2015.8.0\n        Added support for SunOS\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' network.ping archlinux.org\n\n    .. versionadded:: 2015.5.0\n\n    Return a True or False instead of ping output.\n\n    .. code-block:: bash\n\n        salt '*' network.ping archlinux.org return_boolean=True\n\n    Set the time to wait for a response in seconds.\n\n    .. code-block:: bash\n\n        salt '*' network.ping archlinux.org timeout=3"
  },
  {
    "code": "def _mkdir_for_config(cfg_file=cfg_file):\n    dirname, filename = os.path.split(cfg_file)\n    try:\n        os.makedirs(dirname)\n    except OSError as exc:\n        if exc.errno == errno.EEXIST and os.path.isdir(dirname):\n            pass\n        else:\n            raise",
    "docstring": "Given a path to a filename, make sure the directory exists"
  },
  {
    "code": "def remove_data_item(self, data_item: DataItem.DataItem, *, safe: bool=False) -> typing.Optional[typing.Sequence]:\n        return self.__cascade_delete(data_item, safe=safe)",
    "docstring": "Remove data item from document model.\n\n        This method is NOT threadsafe."
  },
  {
    "code": "def identity_factor(self):\n        return DiscreteFactor(self.variables, self.cardinality, np.ones(self.values.size))",
    "docstring": "Returns the identity factor.\n\n        Def: The identity factor of a factor has the same scope and cardinality as the original factor,\n             but the values for all the assignments is 1. When the identity factor is multiplied with\n             the factor it returns the factor itself.\n\n        Returns\n        -------\n        DiscreteFactor: The identity factor.\n\n        Examples\n        --------\n        >>> from pgmpy.factors.discrete import DiscreteFactor\n        >>> phi = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12))\n        >>> phi_identity = phi.identity_factor()\n        >>> phi_identity.variables\n        ['x1', 'x2', 'x3']\n        >>> phi_identity.values\n        array([[[ 1.,  1.],\n                [ 1.,  1.],\n                [ 1.,  1.]],\n\n               [[ 1.,  1.],\n                [ 1.,  1.],\n                [ 1.,  1.]]])"
  },
  {
    "code": "def find_cards(self, source=None, **filters):\n\t\tif not filters:\n\t\t\tnew_filters = self.filters.copy()\n\t\telse:\n\t\t\tnew_filters = filters.copy()\n\t\tfor k, v in new_filters.items():\n\t\t\tif isinstance(v, LazyValue):\n\t\t\t\tnew_filters[k] = v.evaluate(source)\n\t\tfrom .. import cards\n\t\treturn cards.filter(**new_filters)",
    "docstring": "Generate a card pool with all cards matching specified filters"
  },
  {
    "code": "def create_api_call(func, settings):\n    def base_caller(api_call, _, *args):\n        return api_call(*args)\n    def inner(request, options=None):\n        this_options = _merge_options_metadata(options, settings)\n        this_settings = settings.merge(this_options)\n        if this_settings.retry and this_settings.retry.retry_codes:\n            api_call = gax.retry.retryable(\n                func, this_settings.retry, **this_settings.kwargs)\n        else:\n            api_call = gax.retry.add_timeout_arg(\n                func, this_settings.timeout, **this_settings.kwargs)\n        api_call = _catch_errors(api_call, gax.config.API_ERRORS)\n        return api_caller(api_call, this_settings, request)\n    if settings.page_descriptor:\n        if settings.bundler and settings.bundle_descriptor:\n            raise ValueError('The API call has incompatible settings: '\n                             'bundling and page streaming')\n        api_caller = _page_streamable(settings.page_descriptor)\n    elif settings.bundler and settings.bundle_descriptor:\n        api_caller = _bundleable(settings.bundle_descriptor)\n    else:\n        api_caller = base_caller\n    return inner",
    "docstring": "Converts an rpc call into an API call governed by the settings.\n\n    In typical usage, ``func`` will be a callable used to make an rpc request.\n    This will mostly likely be a bound method from a request stub used to make\n    an rpc call.\n\n    The result is created by applying a series of function decorators defined\n    in this module to ``func``.  ``settings`` is used to determine which\n    function decorators to apply.\n\n    The result is another callable which for most values of ``settings`` has\n    has the same signature as the original. Only when ``settings`` configures\n    bundling does the signature change.\n\n    Args:\n      func (Callable[Sequence[object], object]): is used to make a bare rpc\n        call.\n      settings (_CallSettings): provides the settings for this call\n\n    Returns:\n      Callable[Sequence[object], object]: a bound method on a request stub used\n        to make an rpc call\n\n    Raises:\n       ValueError: if ``settings`` has incompatible values, e.g, if bundling\n         and page_streaming are both configured"
  },
  {
    "code": "def set_user_password(self, username, password):\n        text = \"SET PASSWORD FOR {0} = {1}\".format(\n            quote_ident(username), quote_literal(password))\n        self.query(text)",
    "docstring": "Change the password of an existing user.\n\n        :param username: the username who's password is being changed\n        :type username: str\n        :param password: the new password for the user\n        :type password: str"
  },
  {
    "code": "def run(self):\n    while not self._abort:\n      hashes = self._GetHashes(self._hash_queue, self.hashes_per_batch)\n      if hashes:\n        time_before_analysis = time.time()\n        hash_analyses = self.Analyze(hashes)\n        current_time = time.time()\n        self.seconds_spent_analyzing += current_time - time_before_analysis\n        self.analyses_performed += 1\n        for hash_analysis in hash_analyses:\n          self._hash_analysis_queue.put(hash_analysis)\n          self._hash_queue.task_done()\n        time.sleep(self.wait_after_analysis)\n      else:\n        time.sleep(self.EMPTY_QUEUE_WAIT_TIME)",
    "docstring": "The method called by the threading library to start the thread."
  },
  {
    "code": "def retrieve(self, id) :\n        _, _, note = self.http_client.get(\"/notes/{id}\".format(id=id))\n        return note",
    "docstring": "Retrieve a single note\n\n        Returns a single note available to the user, according to the unique note ID provided\n        If the note ID does not exist, this request will return an error\n\n        :calls: ``get /notes/{id}``\n        :param int id: Unique identifier of a Note.\n        :return: Dictionary that support attriubte-style access and represent Note resource.\n        :rtype: dict"
  },
  {
    "code": "def on_frame(self, frame_in):\n        LOGGER.debug('Frame Received: %s', frame_in.name)\n        if frame_in.name == 'Heartbeat':\n            return\n        elif frame_in.name == 'Connection.Close':\n            self._close_connection(frame_in)\n        elif frame_in.name == 'Connection.CloseOk':\n            self._close_connection_ok()\n        elif frame_in.name == 'Connection.Blocked':\n            self._blocked_connection(frame_in)\n        elif frame_in.name == 'Connection.Unblocked':\n            self._unblocked_connection()\n        elif frame_in.name == 'Connection.OpenOk':\n            self._set_connection_state(Stateful.OPEN)\n        elif frame_in.name == 'Connection.Start':\n            self.server_properties = frame_in.server_properties\n            self._send_start_ok(frame_in)\n        elif frame_in.name == 'Connection.Tune':\n            self._send_tune_ok(frame_in)\n            self._send_open_connection()\n        else:\n            LOGGER.error('[Channel0] Unhandled Frame: %s', frame_in.name)",
    "docstring": "Handle frames sent to Channel0.\n\n        :param frame_in: Amqp frame.\n        :return:"
  },
  {
    "code": "def add_mismatch(self, entity, *traits):\n        for trait in traits:\n            self.index[trait].add(entity)",
    "docstring": "Add a mismatching entity to the index.\n\n        We do this by simply adding the mismatch to the index.\n\n        :param collections.Hashable entity: an object to be mismatching the values of `traits_indexed_by`\n        :param list traits: a list of hashable traits to index the entity with"
  },
  {
    "code": "def device_configuration(self, pending=False, use_included=False):\n        device_configs = self.device_configurations(use_included=use_included)\n        for device_config in device_configs:\n            if device_config.is_loaded() is not pending:\n                return device_config\n        return None",
    "docstring": "Get a specific device configuration.\n\n        A device can have at most one loaded and one pending device\n        configuration. This returns that device_configuration based on\n        a given flag.\n\n        Keyword Args:\n\n            pending(bool): Fetch the pending configuration or return\n                the loaded one.\n\n            use_included(bool): Use included resources in this device\n                configuration.\n\n        Returns:\n\n            The requested loaded or pending configuration or None if\n            no device configuration is found."
  },
  {
    "code": "def add_new_header_groups(self, groups):\n        already_present = []\n        for group in groups:\n            col_names = self.dm[self.dm['group'] == group].index\n            for col in col_names:\n                if col not in self.grid.col_labels:\n                    col_number = self.grid.add_col(col)\n                    if col in self.contribution.vocab.vocabularies:\n                        self.drop_down_menu.add_drop_down(col_number, col)\n                    elif col in self.contribution.vocab.suggested:\n                        self.drop_down_menu.add_drop_down(col_number, col)\n                    elif col in ['specimen', 'sample', 'site', 'location',\n                                 'specimens', 'samples', 'sites']:\n                        self.drop_down_menu.add_drop_down(col_number, col)\n                    elif col == 'experiments':\n                        self.drop_down_menu.add_drop_down(col_number, col)\n                    if col == \"method_codes\":\n                        self.drop_down_menu.add_method_drop_down(col_number, col)\n                else:\n                    already_present.append(col)\n        return already_present",
    "docstring": "compile list of all headers belonging to all specified groups\n        eliminate all headers that are already included\n        add any req'd drop-down menus\n        return errors"
  },
  {
    "code": "def tube(self, name):\n        tube = self.tubes.get(name)\n        if tube is None:\n            tube = Tube(self, name)\n            self.tubes[name] = tube\n        return tube",
    "docstring": "Create tube object, if not created before.\n\n        Returns `Tube` object."
  },
  {
    "code": "def hash_user_id(self, user_id: str) -> str:\n        h = sha256()\n        h.update(user_id.encode())\n        return h.hexdigest()",
    "docstring": "As per the law, anonymize user identifier before sending it."
  },
  {
    "code": "def is_not_empty(value, **kwargs):\n    try:\n        value = validators.not_empty(value, **kwargs)\n    except SyntaxError as error:\n        raise error\n    except Exception:\n        return False\n    return True",
    "docstring": "Indicate whether ``value`` is empty.\n\n    :param value: The value to evaluate.\n\n    :returns: ``True`` if ``value`` is empty, ``False`` if it is not.\n    :rtype: :class:`bool <python:bool>`\n\n    :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates\n      keyword parameters passed to the underlying validator"
  },
  {
    "code": "def adjust_level(logger, level):\n    level = level_to_number(level)\n    if logger.getEffectiveLevel() > level:\n        logger.setLevel(level)",
    "docstring": "Increase a logger's verbosity up to the requested level.\n\n    :param logger: The logger to change (a :class:`~logging.Logger` object).\n    :param level: The log level to enable (a string or number).\n\n    This function is used by functions like :func:`install()`,\n    :func:`increase_verbosity()` and :func:`.enable_system_logging()` to adjust\n    a logger's level so that log messages up to the requested log level are\n    propagated to the configured output handler(s).\n\n    It uses :func:`logging.Logger.getEffectiveLevel()` to check whether\n    `logger` propagates or swallows log messages of the requested `level` and\n    sets the logger's level to the requested level if it would otherwise\n    swallow log messages.\n\n    Effectively this function will \"widen the scope of logging\" when asked to\n    do so but it will never \"narrow the scope of logging\". This is because I am\n    convinced that filtering of log messages should (primarily) be decided by\n    handlers."
  },
  {
    "code": "def _patch_resource(self, method):\n        resource = self.client.get_resource(\"\", self.resource.path, method)\n        if not resource:\n            raise UnsupportedResourceMethodError(self.resource.path, method)\n        self.resource = resource",
    "docstring": "Patch the current RAML ResourceNode by the resource with the\n            correct method if it exists\n\n            If the resource with the specified method does not exist\n            an exception is raised.\n\n            :param str method: the method of the resource\n\n            :raises UnsupportedResourceMethodError: if resource does not support the method"
  },
  {
    "code": "def updatepLvlNextFunc(self):\n        orig_time = self.time_flow\n        self.timeFwd()\n        pLvlNextFunc = []\n        pLogMean = self.pLvlInitMean\n        for t in range(self.T_cycle):\n            pLvlNextFunc.append(pLvlFuncAR1(pLogMean,self.PermGroFac[t],self.PrstIncCorr))\n            pLogMean += np.log(self.PermGroFac[t])\n        self.pLvlNextFunc = pLvlNextFunc\n        self.addToTimeVary('pLvlNextFunc')\n        if not orig_time:\n            self.timeRev()",
    "docstring": "A method that creates the pLvlNextFunc attribute as a sequence of\n        AR1-style functions.  Draws on the attributes PermGroFac and PrstIncCorr.\n        If cycles=0, the product of PermGroFac across all periods must be 1.0,\n        otherwise this method is invalid.\n\n        Parameters\n        ----------\n        None\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def wxcode(code: str) -> str:\n    if not code:\n        return ''\n    ret = ''\n    if code[0] == '+':\n        ret = 'Heavy '\n        code = code[1:]\n    elif code[0] == '-':\n        ret = 'Light '\n        code = code[1:]\n    if len(code) not in [2, 4, 6]:\n        return code\n    for _ in range(len(code) // 2):\n        if code[:2] in WX_TRANSLATIONS:\n            ret += WX_TRANSLATIONS[code[:2]] + ' '\n        else:\n            ret += code[:2]\n        code = code[2:]\n    return ret.strip()",
    "docstring": "Translates weather codes into readable strings\n\n    Returns translated string of variable length"
  },
  {
    "code": "def DEFINE_point(name, default, help):\n  flags.DEFINE(PointParser(), name, default, help)",
    "docstring": "Registers a flag whose value parses as a point."
  },
  {
    "code": "def qteGetAppletFromWidget(widgetObj):\n    if widgetObj is None:\n        return None\n    if hasattr(widgetObj, '_qteAdmin'):\n        return widgetObj._qteAdmin.qteApplet\n    visited = [widgetObj]\n    wid = widgetObj.parent()\n    while wid not in visited:\n        if hasattr(wid, '_qteAdmin'):\n            return wid._qteAdmin.qteApplet\n        elif wid is None:\n            return None\n        else:\n            visited.append(wid)\n            wid = wid.parent()\n    return None",
    "docstring": "Return the parent applet of ``widgetObj``.\n\n    |Args|\n\n    * ``widgetObj`` (**QWidget**): widget (if any) for which the\n      containing applet is requested.\n\n    |Returns|\n\n    * **QtmacsApplet**: the applet containing ``widgetObj`` or **None**.\n\n    |Raises|\n\n    * **None**"
  },
  {
    "code": "def write_without_mac(self, data, block):\n        assert len(data) == 16 and type(block) is int\n        log.debug(\"write 1 block without mac\".format())\n        sc_list = [tt3.ServiceCode(0, 0b001001)]\n        bc_list = [tt3.BlockCode(block)]\n        self.write_without_encryption(sc_list, bc_list, data)",
    "docstring": "Write a data block without integrity check.\n\n        This is the standard write method for a FeliCa Lite. The\n        16-byte string or bytearray *data* is written to the numbered\n        *block* in service 0x0009 (NDEF write service). ::\n\n            data = bytearray(range(16)) # 0x00, 0x01, ... 0x0F\n            try: tag.write_without_mac(data, 5) # write block 5\n            except nfc.tag.TagCommandError:\n                print(\"something went wrong\")\n\n        Tag command errors raise :exc:`~nfc.tag.TagCommandError`."
  },
  {
    "code": "def _umask(self):\n        if self.filesystem.is_windows_fs:\n            return 0\n        if sys.platform == 'win32':\n            return 0o002\n        else:\n            mask = os.umask(0)\n            os.umask(mask)\n            return mask",
    "docstring": "Return the current umask."
  },
  {
    "code": "def _SetPath(self, path):\n    old_path = self._path\n    if old_path and not io_wrapper.IsCloudPath(old_path):\n      try:\n        size = tf.io.gfile.stat(old_path).length\n        logger.debug('Setting latest size of %s to %d', old_path, size)\n        self._finalized_sizes[old_path] = size\n      except tf.errors.OpError as e:\n        logger.error('Unable to get size of %s: %s', old_path, e)\n    self._path = path\n    self._loader = self._loader_factory(path)",
    "docstring": "Sets the current path to watch for new events.\n\n    This also records the size of the old path, if any. If the size can't be\n    found, an error is logged.\n\n    Args:\n      path: The full path of the file to watch."
  },
  {
    "code": "def plot_vxx(self, colorbar=True, cb_orientation='vertical',\n                 cb_label=None, ax=None, show=True, fname=None, **kwargs):\n        if cb_label is None:\n            cb_label = self._vxx_label\n        if ax is None:\n            fig, axes = self.vxx.plot(colorbar=colorbar,\n                                      cb_orientation=cb_orientation,\n                                      cb_label=cb_label, show=False, **kwargs)\n            if show:\n                fig.show()\n            if fname is not None:\n                fig.savefig(fname)\n            return fig, axes\n        else:\n            self.vxx.plot(colorbar=colorbar, cb_orientation=cb_orientation,\n                          cb_label=cb_label, ax=ax, **kwargs)",
    "docstring": "Plot the Vxx component of the tensor.\n\n        Usage\n        -----\n        x.plot_vxx([tick_interval, xlabel, ylabel, ax, colorbar,\n                    cb_orientation, cb_label, show, fname])\n\n        Parameters\n        ----------\n        tick_interval : list or tuple, optional, default = [30, 30]\n            Intervals to use when plotting the x and y ticks. If set to None,\n            ticks will not be plotted.\n        xlabel : str, optional, default = 'longitude'\n            Label for the longitude axis.\n        ylabel : str, optional, default = 'latitude'\n            Label for the latitude axis.\n        ax : matplotlib axes object, optional, default = None\n            A single matplotlib axes object where the plot will appear.\n        colorbar : bool, optional, default = False\n            If True, plot a colorbar.\n        cb_orientation : str, optional, default = 'vertical'\n            Orientation of the colorbar: either 'vertical' or 'horizontal'.\n        cb_label : str, optional, default = '$V_{xx}$'\n            Text label for the colorbar..\n        show : bool, optional, default = True\n            If True, plot the image to the screen.\n        fname : str, optional, default = None\n            If present, and if axes is not specified, save the image to the\n            specified file.\n        kwargs : optional\n            Keyword arguements that will be sent to the SHGrid.plot()\n            and plt.imshow() methods."
  },
  {
    "code": "def register_host():\n    pyblish.api.register_host(\"hython\")\n    pyblish.api.register_host(\"hpython\")\n    pyblish.api.register_host(\"houdini\")",
    "docstring": "Register supported hosts"
  },
  {
    "code": "def run(\n        project: 'projects.Project',\n        step: 'projects.ProjectStep'\n) -> dict:\n    with open(step.source_path, 'r') as f:\n        code = f.read()\n    try:\n        cauldron.display.markdown(code, **project.shared.fetch(None))\n        return {'success': True}\n    except Exception as err:\n        return dict(\n            success=False,\n            html_message=templating.render_template(\n                'markdown-error.html',\n                error=err\n            )\n        )",
    "docstring": "Runs the markdown file and renders the contents to the notebook display\n\n    :param project:\n    :param step:\n    :return:\n        A run response dictionary containing"
  },
  {
    "code": "def parse(input, identifier: str = None, use_cache=False, clear_cache=True, pattern=\"*.qface\", profile=EProfile.FULL):\n        inputs = input if isinstance(input, (list, tuple)) else [input]\n        logger.debug('parse input={0}'.format(inputs))\n        identifier = 'system' if not identifier else identifier\n        system = System()\n        cache = None\n        if use_cache:\n            cache = shelve.open('qface.cache')\n            if identifier in cache and clear_cache:\n                del cache[identifier]\n            if identifier in cache:\n                system = cache[identifier]\n        for input in inputs:\n            path = Path.getcwd() / str(input)\n            if path.isfile():\n                FileSystem.parse_document(path, system)\n            else:\n                for document in path.walkfiles(pattern):\n                    FileSystem.parse_document(document, system)\n        if use_cache:\n            cache[identifier] = system\n        return system",
    "docstring": "Input can be either a file or directory or a list of files or directory.\n        A directory will be parsed recursively. The function returns the resulting system.\n        Stores the result of the run in the domain cache named after the identifier.\n\n        :param path: directory to parse\n        :param identifier: identifies the parse run. Used to name the cache\n        :param clear_cache: clears the domain cache (defaults to true)"
  },
  {
    "code": "def can_process(self, statement):\n        response = self.process(statement)\n        self.cache[statement.text] = response\n        return response.confidence == 1",
    "docstring": "Determines whether it is appropriate for this\n        adapter to respond to the user input."
  },
  {
    "code": "def qr(self,text):\n        qr_code = qrcode.QRCode(version=4, box_size=4, border=1)\n        qr_code.add_data(text)\n        qr_code.make(fit=True)\n        qr_img = qr_code.make_image()\n        im = qr_img._img.convert(\"RGB\")\n        self._convert_image(im)",
    "docstring": "Print QR Code for the provided string"
  },
  {
    "code": "def xpath(self, xpath):\n    return [self.get_node_factory().create(node_id)\n            for node_id in self._get_xpath_ids(xpath).split(\",\")\n            if node_id]",
    "docstring": "Finds another node by XPath originating at the current node."
  },
  {
    "code": "def grid_select(self, grid, clear_selection=True):\n        if clear_selection:\n            grid.ClearSelection()\n        for (tl, br) in zip(self.block_tl, self.block_br):\n            grid.SelectBlock(tl[0], tl[1], br[0], br[1], addToSelected=True)\n        for row in self.rows:\n            grid.SelectRow(row, addToSelected=True)\n        for col in self.cols:\n            grid.SelectCol(col, addToSelected=True)\n        for cell in self.cells:\n            grid.SelectBlock(cell[0], cell[1], cell[0], cell[1],\n                             addToSelected=True)",
    "docstring": "Selects cells of grid with selection content"
  },
  {
    "code": "def getSuccessors(jobGraph, alreadySeenSuccessors, jobStore):\n        successors = set()\n        def successorRecursion(jobGraph):\n            for successorList in jobGraph.stack:\n                for successorJobNode in successorList:\n                    if successorJobNode.jobStoreID not in alreadySeenSuccessors:\n                        successors.add(successorJobNode.jobStoreID)\n                        alreadySeenSuccessors.add(successorJobNode.jobStoreID)\n                        if jobStore.exists(successorJobNode.jobStoreID):\n                            successorRecursion(jobStore.load(successorJobNode.jobStoreID))\n        successorRecursion(jobGraph)\n        return successors",
    "docstring": "Gets successors of the given job by walking the job graph recursively.\n        Any successor in alreadySeenSuccessors is ignored and not traversed.\n        Returns the set of found successors. This set is added to alreadySeenSuccessors."
  },
  {
    "code": "def compare_version(a, b):\n  aa = string.split(a, \".\")\n  bb = string.split(b, \".\")\n  for i in range(0, 4):\n    if aa[i] != bb[i]:\n      return cmp(int(aa[i]), int(bb[i]))\n  return 0",
    "docstring": "Compare two version number strings of the form W.X.Y.Z.\n\n  The numbers are compared most-significant to least-significant.\n  For example, 12.345.67.89 > 2.987.88.99.\n\n  Args:\n    a: First version number string to compare\n    b: Second version number string to compare\n\n  Returns:\n    0 if the numbers are identical, a positive number if 'a' is larger, and\n    a negative number if 'b' is larger."
  },
  {
    "code": "def sort_filenames(filenames):\n    basenames = [os.path.basename(x) for x in filenames]\n    indexes = [i[0] for i in sorted(enumerate(basenames), key=lambda x:x[1])]\n    return [filenames[x] for x in indexes]",
    "docstring": "sort a list of files by filename only, ignoring the directory names"
  },
  {
    "code": "def save_ready(self, service_name):\n        self._load_ready_file()\n        self._ready.add(service_name)\n        self._save_ready_file()",
    "docstring": "Save an indicator that the given service is now data_ready."
  },
  {
    "code": "def _invite(self, name, method, email, uuid, event, password=\"\"):\n        props = {\n            'uuid': std_uuid(),\n            'status': 'Open',\n            'name': name,\n            'method': method,\n            'email': email,\n            'password': password,\n            'timestamp': std_now()\n        }\n        enrollment = objectmodels['enrollment'](props)\n        enrollment.save()\n        self.log('Enrollment stored', lvl=debug)\n        self._send_invitation(enrollment, event)\n        packet = {\n            'component': 'hfos.enrol.enrolmanager',\n            'action': 'invite',\n            'data': [True, email]\n        }\n        self.fireEvent(send(uuid, packet))",
    "docstring": "Actually invite a given user"
  },
  {
    "code": "def bin_hex_type(arg):\n\tif re.match(r'^[a-f0-9]{2}(:[a-f0-9]{2})+$', arg, re.I):\n\t\targ = arg.replace(':', '')\n\telif re.match(r'^(\\\\x[a-f0-9]{2})+$', arg, re.I):\n\t\targ = arg.replace('\\\\x', '')\n\ttry:\n\t\targ = binascii.a2b_hex(arg)\n\texcept (binascii.Error, TypeError):\n\t\traise argparse.ArgumentTypeError(\"{0} is invalid hex data\".format(repr(arg)))\n\treturn arg",
    "docstring": "An argparse type representing binary data encoded in hex."
  },
  {
    "code": "def makedirs(p):\n    try:\n        os.makedirs(p, settings.FILE_UPLOAD_PERMISSIONS)\n    except OSError:\n        if not os.path.isdir(p):\n            raise",
    "docstring": "A makedirs that avoids a race conditions for multiple processes attempting to create the same directory."
  },
  {
    "code": "def output(self):\n        return ElasticsearchTarget(\n            host=self.host,\n            port=self.port,\n            http_auth=self.http_auth,\n            index=self.index,\n            doc_type=self.doc_type,\n            update_id=self.update_id(),\n            marker_index_hist_size=self.marker_index_hist_size,\n            timeout=self.timeout,\n            extra_elasticsearch_args=self.extra_elasticsearch_args\n        )",
    "docstring": "Returns a ElasticsearchTarget representing the inserted dataset.\n\n        Normally you don't override this."
  },
  {
    "code": "def regexpExec(self, content):\n        ret = libxml2mod.xmlRegexpExec(self._o, content)\n        return ret",
    "docstring": "Check if the regular expression generates the value"
  },
  {
    "code": "def path(self):\n        names = []\n        obj = self\n        while obj:\n            names.insert(0, obj.name)\n            obj = obj.parent_dir\n        sep = self.filesystem._path_separator(self.name)\n        if names[0] == sep:\n            names.pop(0)\n            dir_path = sep.join(names)\n            is_drive = names and len(names[0]) == 2 and names[0][1] == ':'\n            if not is_drive:\n                dir_path = sep + dir_path\n        else:\n            dir_path = sep.join(names)\n        dir_path = self.filesystem.absnormpath(dir_path)\n        return dir_path",
    "docstring": "Return the full path of the current object."
  },
  {
    "code": "def _full_path(self, path_info):\n        full_path = self.root + path_info\n        if path.exists(full_path):\n            return full_path\n        else:\n            for magic in self.magics:\n                if path.exists(magic.new_path(full_path)):\n                    return magic.new_path(full_path)\n            else:\n                return full_path",
    "docstring": "Return the full path from which to read."
  },
  {
    "code": "def validate(src, **kwargs):\n    resolver = Resolver()\n    validator = OcrdZipValidator(resolver, src)\n    report = validator.validate(**kwargs)\n    print(report)\n    if not report.is_valid:\n        sys.exit(1)",
    "docstring": "Validate OCRD-ZIP\n\n    SRC must exist an be an OCRD-ZIP, either a ZIP file or a directory."
  },
  {
    "code": "def create_role(*_, **kwargs):\n    click.echo(green('\\nCreating new role:'))\n    click.echo(green('-' * 40))\n    with get_app().app_context():\n        role = Role(**kwargs)\n        result = role_service.save(role)\n        if not isinstance(result, Role):\n            print_validation_errors(result)\n        click.echo(green('Created: ') + str(role) + '\\n')",
    "docstring": "Create user role"
  },
  {
    "code": "def spawn(f):\n    def fun(pipe,x):\n        pipe.send(f(x))\n        pipe.close()\n    return fun",
    "docstring": "Function for parallel evaluation of the acquisition function"
  },
  {
    "code": "def prj_add_user(self, *args, **kwargs):\n        if not self.cur_prj:\n            return\n        dialog = UserAdderDialog(project=self.cur_prj)\n        dialog.exec_()\n        users = dialog.users\n        for user in users:\n            userdata = djitemdata.UserItemData(user)\n            treemodel.TreeItem(userdata, self.prj_user_model.root)\n        self.cur_prj.save()",
    "docstring": "Add more users to the project.\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def blend(self, blend_recipe, join_base, join_blend):\n        assert isinstance(blend_recipe, Recipe)\n        self.blend_recipes.append(blend_recipe)\n        self.blend_types.append('inner')\n        self.blend_criteria.append((join_base, join_blend))\n        self.dirty = True\n        return self.recipe",
    "docstring": "Blend a recipe into the base recipe.\n        This performs an inner join of the blend_recipe to the\n        base recipe's SQL."
  },
  {
    "code": "def _formatVals(self, val_list):\n        vals = []\n        for (name, val) in val_list:\n            if val is not None:\n                if isinstance(val, float):\n                    vals.append(\"%s.value %f\" % (name, val))\n                else:\n                    vals.append(\"%s.value %s\" % (name, val))\n            else:\n                vals.append(\"%s.value U\" % (name,))\n        return \"\\n\".join(vals)",
    "docstring": "Formats value list from Munin Graph and returns multi-line value\n        entries for the plugin fetch cycle.\n        \n        @param val_list: List of name-value pairs. \n        @return:         Multi-line text."
  },
  {
    "code": "def example_generator(all_files, urls_path, sum_token):\n  def fix_run_on_sents(line):\n    if u\"@highlight\" in line:\n      return line\n    if not line:\n      return line\n    if line[-1] in END_TOKENS:\n      return line\n    return line + u\".\"\n  filelist = example_splits(urls_path, all_files)\n  story_summary_split_token = u\" <summary> \" if sum_token else \" \"\n  for story_file in filelist:\n    story = []\n    summary = []\n    reading_highlights = False\n    for line in tf.gfile.Open(story_file, \"rb\"):\n      line = text_encoder.to_unicode_utf8(line.strip())\n      line = fix_run_on_sents(line)\n      if not line:\n        continue\n      elif line.startswith(u\"@highlight\"):\n        if not story:\n          break\n        reading_highlights = True\n      elif reading_highlights:\n        summary.append(line)\n      else:\n        story.append(line)\n    if (not story) or not summary:\n      continue\n    yield \" \".join(story) + story_summary_split_token + \" \".join(summary)",
    "docstring": "Generate examples."
  },
  {
    "code": "def get(self, request):\n        sections_list = self.generate_sections()\n        p = Paginator(sections_list, 25)\n        page = request.GET.get('page')\n        try:\n            sections = p.page(page)\n        except PageNotAnInteger:\n            sections = p.page(1)\n        except EmptyPage:\n            sections = p.page(p.num_pages)\n        context = {\n            'sections': sections,\n            'page_title': self.generate_page_title(),\n            'browse_type': self.browse_type\n        }\n        return render(\n            request,\n            self.template_path,\n            context\n        )",
    "docstring": "Handle HTTP GET request.\n\n        Returns template and context from generate_page_title and\n        generate_sections to populate template."
  },
  {
    "code": "def get_matching(self, source_id):\n        value = self._accessor.get_by_id(source_id)\n        if not value is None:\n            reg = get_current_registry()\n            prx_fac = reg.getUtility(IDataTraversalProxyFactory)\n            prx = prx_fac.make_proxy(value,\n                                     self._accessor,\n                                     self.relationship_direction,\n                                     self.relation_operation)\n        else:\n            prx = None\n        return prx",
    "docstring": "Returns a matching target object for the given source ID."
  },
  {
    "code": "def float16_activations_var_getter(getter, *args, **kwargs):\n  requested_dtype = kwargs[\"dtype\"]\n  if requested_dtype == tf.float16:\n    kwargs[\"dtype\"] = tf.float32\n  if requested_dtype == tf.float32:\n    requested_dtype = tf.float16\n  var = getter(*args, **kwargs)\n  if var.dtype.base_dtype != requested_dtype:\n    var = tf.cast(var, requested_dtype)\n  return var",
    "docstring": "A custom getter function for float32 parameters and float16 activations.\n\n  This function ensures the following:\n    1. All variables requested with type fp16 are stored as type fp32.\n    2. All variables requested with type fp32 are returned as type fp16.\n  See https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/\n  #training_tensorflow for more information on this strategy.\n\n  Args:\n    getter: custom getter\n    *args: arguments\n    **kwargs: keyword arguments\n\n  Returns:\n    variables with the correct dtype.\n\n  Raises:\n    KeyError: if \"dtype\" is not provided as a kwarg."
  },
  {
    "code": "def unicode(self, s, encoding=None):\n        if isinstance(s, unicode):\n            return unicode(s)\n        return self.to_unicode(s, encoding)",
    "docstring": "Convert a string to unicode using the given encoding, and return it.\n\n        This function uses the underlying to_unicode attribute.\n\n        Arguments:\n\n          s: a basestring instance to convert to unicode.  Unlike Python's\n            built-in unicode() function, it is okay to pass unicode strings\n            to this function.  (Passing a unicode string to Python's unicode()\n            with the encoding argument throws the error, \"TypeError: decoding\n            Unicode is not supported.\")\n\n          encoding: the encoding to pass to the to_unicode attribute.\n            Defaults to None."
  },
  {
    "code": "def fetch_data(self):\n        yield from self._get_httpsession()\n        yield from self._post_login_page()\n        token_uuid = yield from self._get_token()\n        account_number = yield from self._get_account_number(*token_uuid)\n        self._phone_numbers = yield from self._list_phone_numbers(account_number)\n        balance = yield from self._get_balance(account_number)\n        self._data['balance'] = balance\n        for number in self._phone_numbers:\n            fido_dollar = yield from self._get_fido_dollar(account_number,\n                                                           number)\n            self._data[number]= {'fido_dollar': fido_dollar}\n        for number in self._phone_numbers:\n            usage = yield from self._get_usage(account_number, number)\n            self._data[number].update(usage)",
    "docstring": "Fetch the latest data from Fido."
  },
  {
    "code": "def main_hrun():\r\n    parser = argparse.ArgumentParser(description=\"Tools for http(s) test. Base on rtsf.\")\r\n    parser.add_argument(\r\n        '--log-level', default='INFO',\r\n        help=\"Specify logging level, default is INFO.\")\r\n    parser.add_argument(\r\n        '--log-file',\r\n        help=\"Write logs to specified file path.\")\r\n    parser.add_argument(\r\n        'case_file', \r\n        help=\"yaml testcase file\")\r\n    color_print(\"httpdriver {}\".format(__version__), \"GREEN\")\r\n    args = parser.parse_args()\r\n    logger.setup_logger(args.log_level, args.log_file)    \r\n    runner = TestRunner(runner = HttpDriver).run(args.case_file)\r\n    html_report = runner.gen_html_report()\r\n    color_print(\"report: {}\".format(html_report))",
    "docstring": "parse command line options and run commands."
  },
  {
    "code": "def _get_encoding_opt(synchronizer, extra_opts, default):\n    encoding = default\n    if extra_opts and \"encoding\" in extra_opts:\n        encoding = extra_opts.get(\"encoding\")\n    if encoding:\n        encoding = codecs.lookup(encoding).name\n    return encoding or None",
    "docstring": "Helper to figure out encoding setting inside constructors."
  },
  {
    "code": "def add_component(self, component, temporary=False):\n        tile = IOTile(component)\n        value = os.path.normpath(os.path.abspath(component))\n        if temporary is True:\n            self._component_overlays[tile.name] = value\n        else:\n            self.kvstore.set(tile.name, value)",
    "docstring": "Register a component with ComponentRegistry.\n\n        Component must be a buildable object with a module_settings.json file\n        that describes its name and the domain that it is part of.  By\n        default, this component is saved in the permanent registry associated\n        with this environment and will remain registered for future CoreTools\n        invocations.\n\n        If you only want this component to be temporarily registered during\n        this program's session, you can pass temporary=True and the component\n        will be stored in RAM only, not persisted to the underlying key-value\n        store.\n\n        Args:\n            component (str): The path to a component that should be registered.\n            temporary (bool): Optional flag to only temporarily register the\n                component for the duration of this program invocation."
  },
  {
    "code": "def __query(domain, limit=100):\n    s = check_output(['{}'.format(os.path.join(os.path.dirname(__file__), 'whois.sh')), '--limit {} {}'.format(limit, domain)], universal_newlines=True)\n    return s",
    "docstring": "Using the shell script to query pdns.cert.at is a hack, but python raises an error every time using subprocess\n    functions to call whois. So this hack is avoiding calling whois directly. Ugly, but works.\n\n    :param domain: The domain pdns is queried with.\n    :type domain: str\n    :param limit: Maximum number of results\n    :type limit: int\n    :returns: str -- Console output from whois call.\n    :rtype: str"
  },
  {
    "code": "def print_modified_files(opts, anchors):\n    print(\"Files with modifications:\")\n    for file_path in anchors:\n        print(\"  \" + strip_prefix(file_path, opts.abs_input))\n    print(\"--------------------\")\n    print(str(len(anchors)) + \" total\\n\")",
    "docstring": "Prints out which files were modified amongst those looked at\n\n    :param anchors: Dictionary mapping file path strings to dictionaries\n        containing AnchorHub tag/generated header key-value pairs"
  },
  {
    "code": "def remove_server_data(server_id):\n    logger.debug(\"Removing server from serverdata\")\n    data = datatools.get_data()\n    if server_id in data[\"discord\"][\"servers\"]:\n        data[\"discord\"][\"servers\"].pop(server_id)\n        datatools.write_data(data)",
    "docstring": "Remove a server from the server data\n\n    Args:\n        server_id (int): The server to remove from the server data"
  },
  {
    "code": "def _set_class_parser(self, init_parser, methods_to_parse, cls):\n        top_level_parents = [init_parser] if init_parser else []\n        description = self._description or cls.__doc__\n        top_level_parser = argparse.ArgumentParser(description=description,\n                                                   parents=top_level_parents,\n                                                   add_help=False,\n                                                   conflict_handler=\"resolve\")\n        top_level_parser.add_argument(\"-h\", \"--help\", action=FullHelpAction,\n                                      help=\"Display this help message\")\n        parser_to_method = self._add_sub_parsers(top_level_parser,\n                                                 methods_to_parse,\n                                                 cls.__name__)\n        if init_parser:\n            parser_to_method[\"__init__\"] = \"__init__\"\n        top_level_parser.call = self._get_parser_call_method(parser_to_method)\n        cls.parser = top_level_parser",
    "docstring": "Creates the complete argument parser for the decorated class.\n\n        Args:\n            init_parser: argument parser for the __init__ method or None\n            methods_to_parse: dict of method name pointing to their associated\n            argument parser\n            cls: the class we are decorating\n\n        Returns:\n            The decorated class with an added attribute 'parser'"
  },
  {
    "code": "def csv(self):\n        output = StringIO.StringIO()\n        fieldnames = ['id',\n                      'name',\n                      'description',\n                      'rules_direction',\n                      'rules_ip_protocol',\n                      'rules_from_port',\n                      'rules_to_port',\n                      'rules_grants_group_id',\n                      'rules_grants_name',\n                      'rules_grants_cidr_ip',\n                      'rules_description']\n        writer = csv.DictWriter(output, fieldnames=fieldnames)\n        writer.writeheader()\n        for fr in self.rules:\n            writer.writerow(fr.as_dict())\n        csv_content = output.getvalue()\n        stripped_csv_content = csv_content.strip()\n        return stripped_csv_content",
    "docstring": "Returns the security rules as a CSV.\n\n        CSV format:\n        - id\n        - name\n        - description\n        - rules_direction\n        - rules_ip_protocol\n        - rules_from_port\n        - rules_to_port\n        - rules_grants_group_id\n        - rules_grants_name\n        - rules_grants_cidr_ip\n        - rules_description\n\n        Returns:\n            str"
  },
  {
    "code": "def wiki_versions_list(self, page_id, updater_id):\n        params = {\n            'earch[updater_id]': updater_id,\n            'search[wiki_page_id]': page_id\n            }\n        return self._get('wiki_page_versions.json', params)",
    "docstring": "Return a list of wiki page version.\n\n        Parameters:\n            page_id (int):\n            updater_id (int):"
  },
  {
    "code": "def download_with_progress(url, chunk_size, **progress_kwargs):\n    resp = requests.get(url, stream=True)\n    resp.raise_for_status()\n    total_size = int(resp.headers['content-length'])\n    data = BytesIO()\n    with progressbar(length=total_size, **progress_kwargs) as pbar:\n        for chunk in resp.iter_content(chunk_size=chunk_size):\n            data.write(chunk)\n            pbar.update(len(chunk))\n    data.seek(0)\n    return data",
    "docstring": "Download streaming data from a URL, printing progress information to the\n    terminal.\n\n    Parameters\n    ----------\n    url : str\n        A URL that can be understood by ``requests.get``.\n    chunk_size : int\n        Number of bytes to read at a time from requests.\n    **progress_kwargs\n        Forwarded to click.progressbar.\n\n    Returns\n    -------\n    data : BytesIO\n        A BytesIO containing the downloaded data."
  },
  {
    "code": "def dict2orderedlist(dic, order_list, default='', **kwargs):\n    result = []\n    for key_order in order_list:\n        value = get_element(dic, key_order, **kwargs)\n        result.append(value if value is not None else default)\n    return result",
    "docstring": "Return a list with dict values ordered by a list of key passed in args."
  },
  {
    "code": "def configure_box(self, boxsize, root_nx=1, root_ny=1, root_nz=1):\n        clibrebound.reb_configure_box(byref(self), c_double(boxsize), c_int(root_nx), c_int(root_ny), c_int(root_nz))\n        return",
    "docstring": "Initialize the simulation box.\n\n        This function only needs to be called it boundary conditions other than \"none\"\n        are used. In such a case the boxsize must be known and is set with this function.\n\n        Parameters\n        ----------\n        boxsize : float, optional\n            The size of one root box.\n        root_nx, root_ny, root_nz : int, optional\n            The number of root boxes in each direction. The total size of the simulation box\n            will be ``root_nx * boxsize``, ``root_ny * boxsize`` and ``root_nz * boxsize``.\n            By default there will be exactly one root box in each direction."
  },
  {
    "code": "def timeseries_from_mat(filename, varname=None, fs=1.0):\n    import scipy.io as sio\n    if varname is None:\n        mat_dict = sio.loadmat(filename)\n        if len(mat_dict) > 1:\n            raise ValueError('Must specify varname: file contains '\n                             'more than one variable. ')\n    else:\n        mat_dict = sio.loadmat(filename, variable_names=(varname,))\n        array = mat_dict.popitem()[1]\n    return Timeseries(array, fs=fs)",
    "docstring": "load a multi-channel Timeseries from a MATLAB .mat file\n\n    Args:\n      filename (str): .mat file to load\n      varname (str): variable name. only needed if there is more than one\n        variable saved in the .mat file\n      fs (scalar): sample rate of timeseries in Hz. (constant timestep assumed)\n\n    Returns:\n      Timeseries"
  },
  {
    "code": "def fields(self):\n        if 'feature' in self._dict:\n            self._attributes = self._dict['feature']['attributes']\n        else:\n            self._attributes = self._dict['attributes']\n        return self._attributes.keys()",
    "docstring": "returns a list of feature fields"
  },
  {
    "code": "def _delLocalOwnerRole(self, username):\n        parent = self.getParent()\n        if parent.portal_type == \"Client\":\n            parent.manage_delLocalRoles([username])\n            self._recursive_reindex_object_security(parent)",
    "docstring": "Remove local owner role from parent object"
  },
  {
    "code": "def _nodemap_changed(self, data, stat):\n        if not stat:\n            raise EnvironmentNotFoundException(self.nodemap_path)\n        try:\n            conf_path = self._deserialize_nodemap(data)[self.hostname]\n        except KeyError:\n            conf_path = '/services/%s/conf' % self.service\n        self.config_watcher = DataWatch(\n            self.zk, conf_path,\n            self._config_changed\n        )",
    "docstring": "Called when the nodemap changes."
  },
  {
    "code": "def plot(self, lax=None, proj='all', element='PIBsBvV',\n             dP=None, dI=_def.TorId, dBs=_def.TorBsd, dBv=_def.TorBvd,\n             dVect=_def.TorVind, dIHor=_def.TorITord, dBsHor=_def.TorBsTord,\n             dBvHor=_def.TorBvTord, Lim=None, Nstep=_def.TorNTheta,\n             dLeg=_def.TorLegd, indices=False,\n             draw=True, fs=None, wintit=None, Test=True):\n        kwdargs = locals()\n        lout = ['self']\n        for k in lout:\n            del kwdargs[k]\n        return _plot.Struct_plot(self, **kwdargs)",
    "docstring": "Plot the polygon defining the vessel, in chosen projection\n\n        Generic method for plotting the Ves object\n        The projections to be plotted, the elements to plot can be specified\n        Dictionaries of properties for each elements can also be specified\n        If an ax is not provided a default one is created.\n\n        Parameters\n        ----------\n        Lax :       list or plt.Axes\n            The axes to be used for plotting\n            Provide a list of 2 axes if proj='All'\n            If None a new figure with axes is created\n        proj :      str\n            Flag specifying the kind of projection\n                - 'Cross' : cross-section projection\n                - 'Hor' : horizontal projection\n                - 'All' : both\n                - '3d' : a 3d matplotlib plot\n        element :   str\n            Flag specifying which elements to plot\n            Each capital letter corresponds to an element:\n                * 'P': polygon\n                * 'I': point used as a reference for impact parameters\n                * 'Bs': (surfacic) center of mass\n                * 'Bv': (volumic) center of mass for Tor type\n                * 'V': vector pointing inward perpendicular to each segment\n        dP :        dict / None\n            Dict of properties for plotting the polygon\n            Fed to plt.Axes.plot() or plt.plot_surface() if proj='3d'\n        dI :        dict / None\n            Dict of properties for plotting point 'I' in Cross-section projection\n        dIHor :     dict / None\n            Dict of properties for plotting point 'I' in horizontal projection\n        dBs :       dict / None\n            Dict of properties for plotting point 'Bs' in Cross-section projection\n        dBsHor :    dict / None\n            Dict of properties for plotting point 'Bs' in horizontal projection\n        dBv :       dict / None\n            Dict of properties for plotting point 'Bv' in Cross-section projection\n        dBvHor :    dict / None\n            Dict of properties for plotting point 'Bv' in horizontal projection\n        dVect :     dict / None\n            Dict of properties for plotting point 'V' in cross-section projection\n        dLeg :      dict / None\n            Dict of properties for plotting the legend, fed to plt.legend()\n            The legend is not plotted if None\n        Lim :       list or tuple\n            Array of a lower and upper limit of angle (rad.) or length for\n            plotting the '3d' proj\n        Nstep :     int\n            Number of points for sampling in ignorable coordinate (toroidal angle or length)\n        draw :      bool\n            Flag indicating whether the fig.canvas.draw() shall be called automatically\n        a4 :        bool\n            Flag indicating whether the figure should be plotted in a4 dimensions for printing\n        Test :      bool\n            Flag indicating whether the inputs should be tested for conformity\n\n        Returns\n        -------\n        La          list / plt.Axes\n            Handles of the axes used for plotting (list if several axes where used)"
  },
  {
    "code": "def resolve_remote(self, uri):\n        if uri.startswith('file://'):\n            try:\n                path = uri[7:]\n                with open(path, 'r') as schema_file:\n                    result = yaml.load(schema_file)\n                if self.cache_remote:\n                    self.store[uri] = result\n                return result\n            except yaml.parser.ParserError as e:\n                logging.debug('Error parsing {!r} as YAML: {}'.format(\n                    uri, e))\n        return super(SchemaRefResolver, self).resolve_remote(uri)",
    "docstring": "Add support to load YAML files.\n\n        This will attempt to load a YAML file first, and then go back to the\n        default behavior.\n\n        :param str uri: the URI to resolve\n        :returns: the retrieved document"
  },
  {
    "code": "def _request_process_json_bulk(self, response_data):\n        status = 'Failure'\n        data = response_data.get(self.request_entity, [])\n        if data:\n            status = 'Success'\n        return data, status",
    "docstring": "Handle bulk JSON response\n\n        Return:\n            (string): The response data\n            (string): The response status"
  },
  {
    "code": "def close(self):\n        self._closeIfNotUpdatedTimer.stop()\n        self._qpart.removeEventFilter(self)\n        self._qpart.cursorPositionChanged.disconnect(self._onCursorPositionChanged)\n        QListView.close(self)",
    "docstring": "Explicitly called destructor.\n        Removes widget from the qpart"
  },
  {
    "code": "def set_bucket_policy(self, bucket_name, policy):\n        is_valid_policy_type(policy)\n        is_valid_bucket_name(bucket_name)\n        headers = {\n            'Content-Length': str(len(policy)),\n            'Content-Md5': get_md5_base64digest(policy)\n        }\n        content_sha256_hex = get_sha256_hexdigest(policy)\n        self._url_open(\"PUT\",\n                        bucket_name=bucket_name,\n                        query={\"policy\": \"\"},\n                        headers=headers,\n                        body=policy,\n                        content_sha256=content_sha256_hex)",
    "docstring": "Set bucket policy of given bucket name.\n\n        :param bucket_name: Bucket name.\n        :param policy: Access policy/ies in string format."
  },
  {
    "code": "def parse_xml_node(self, node):\n        self.name = node.getAttributeNS(RTS_NS, 'name')\n        self.comment = node.getAttributeNS(RTS_EXT_NS, 'comment')\n        if node.hasAttributeNS(RTS_EXT_NS, 'visible'):\n            visible = node.getAttributeNS(RTS_EXT_NS, 'visible')\n            if visible.lower() == 'true' or visible == '1':\n                self.visible = True\n            else:\n                self.visible = False\n        for c in get_direct_child_elements_xml(node, prefix=RTS_EXT_NS,\n                                               local_name='Properties'):\n            name, value = parse_properties_xml(c)\n            self._properties[name] = value\n        return self",
    "docstring": "Parse an xml.dom Node object representing a data port into this\n        object."
  },
  {
    "code": "def fill(self, value=b'\\xff'):\n        previous_segment_maximum_address = None\n        fill_segments = []\n        for address, data in self._segments:\n            maximum_address = address + len(data)\n            if previous_segment_maximum_address is not None:\n                fill_size = address - previous_segment_maximum_address\n                fill_size_words = fill_size // self.word_size_bytes\n                fill_segments.append(_Segment(\n                    previous_segment_maximum_address,\n                    previous_segment_maximum_address + fill_size,\n                    value * fill_size_words,\n                    self.word_size_bytes))\n            previous_segment_maximum_address = maximum_address\n        for segment in fill_segments:\n            self._segments.add(segment)",
    "docstring": "Fill all empty space between segments with given value `value`."
  },
  {
    "code": "def diff(self, plot):\n        if self.fig == 'auto':\n            figure_format = self.params('fig').objects[0]\n        else:\n            figure_format = self.fig\n        return self.html(plot, figure_format)",
    "docstring": "Returns the latest plot data to update an existing plot."
  },
  {
    "code": "def load_umls():\n    dataset_path = _load('umls')\n    X = _load_csv(dataset_path, 'data')\n    y = X.pop('label').values\n    graph = nx.Graph(nx.read_gml(os.path.join(dataset_path, 'graph.gml')))\n    return Dataset(load_umls.__doc__, X, y, accuracy_score, stratify=True, graph=graph)",
    "docstring": "UMLs Dataset.\n\n    The data consists of information about a 135 Graph and the relations between\n    their nodes given as a DataFrame with three columns, source, target and type,\n    indicating which nodes are related and with which type of link. The target is\n    a 1d numpy binary integer array indicating whether the indicated link exists\n    or not."
  },
  {
    "code": "def which(executable):\n    locations = (\n        '/usr/local/bin',\n        '/bin',\n        '/usr/bin',\n        '/usr/local/sbin',\n        '/usr/sbin',\n        '/sbin',\n    )\n    for location in locations:\n        executable_path = os.path.join(location, executable)\n        if os.path.exists(executable_path) and os.path.isfile(executable_path):\n            return executable_path",
    "docstring": "find the location of an executable"
  },
  {
    "code": "def get_templates(self, limit=100, offset=0):\n        url = self.TEMPLATES_URL + \"?limit=%s&offset=%s\" % (limit, offset)\n        connection = Connection(self.token)\n        connection.set_url(self.production, url)\n        return connection.get_request()",
    "docstring": "Get all account templates"
  },
  {
    "code": "def bundle_visualization_url(self, bundle_id, channel=None):\n        url = '{}/{}/diagram.svg'.format(self.url, _get_path(bundle_id))\n        return _add_channel(url, channel)",
    "docstring": "Generate the path to the visualization for bundles.\n\n        @param charm_id The ID of the bundle.\n        @param channel Optional channel name.\n        @return The url to the visualization."
  },
  {
    "code": "def compute_and_cache_missing_buckets(self, start_time, end_time,\n                                        untrusted_time, force_recompute=False):\n    if untrusted_time and not untrusted_time.tzinfo:\n      untrusted_time = untrusted_time.replace(tzinfo=tzutc())\n    events = self._compute_buckets(start_time, end_time, compute_missing=True,\n                                   cache=True, untrusted_time=untrusted_time,\n                                   force_recompute=force_recompute)\n    for event in events:\n      yield event",
    "docstring": "Return the results for `query_function` on every `bucket_width`\n    time period between `start_time` and `end_time`.  Look for\n    previously cached results to avoid recomputation.  For any buckets\n    where all events would have occurred before `untrusted_time`,\n    cache the results.\n\n    :param start_time: A datetime for the beginning of the range,\n    aligned with `bucket_width`.\n    :param end_time: A datetime for the end of the range, aligned with\n    `bucket_width`.\n    :param untrusted_time: A datetime after which to not trust that\n    computed data is stable.  Any buckets that overlap with or follow\n    this untrusted_time will not be cached.\n    :param force_recompute: A boolean that, if True, will force\n    recompute and recaching of even previously cached data."
  },
  {
    "code": "def pack_msg(method, msg, pickle_protocol=PICKLE_PROTOCOL):\n    dump = io.BytesIO()\n    pickle.dump(msg, dump, pickle_protocol)\n    size = dump.tell()\n    return (struct.pack(METHOD_STRUCT_FORMAT, method) +\n            struct.pack(SIZE_STRUCT_FORMAT, size) + dump.getvalue())",
    "docstring": "Packs a method and message."
  },
  {
    "code": "def to_masked_array(self, copy=True):\n        isnull = pd.isnull(self.values)\n        return np.ma.MaskedArray(data=self.values, mask=isnull, copy=copy)",
    "docstring": "Convert this array into a numpy.ma.MaskedArray\n\n        Parameters\n        ----------\n        copy : bool\n            If True (default) make a copy of the array in the result. If False,\n            a MaskedArray view of DataArray.values is returned.\n\n        Returns\n        -------\n        result : MaskedArray\n            Masked where invalid values (nan or inf) occur."
  },
  {
    "code": "def eval(e, amplitude, e_0, alpha, beta):\n        ee = e / e_0\n        eeponent = -alpha - beta * np.log(ee)\n        return amplitude * ee ** eeponent",
    "docstring": "One dimenional log parabola model function"
  },
  {
    "code": "def get_sites(self, entry):\n        try:\n            index_url = reverse('zinnia:entry_archive_index')\n        except NoReverseMatch:\n            index_url = ''\n        return format_html_join(\n            ', ', '<a href=\"{}://{}{}\" target=\"blank\">{}</a>',\n            [(settings.PROTOCOL, site.domain, index_url,\n              conditional_escape(site.name)) for site in entry.sites.all()])",
    "docstring": "Return the sites linked in HTML."
  },
  {
    "code": "def process_response(self, response):\n        if response.status_code != 200:\n            raise TwilioException('Unable to fetch page', response)\n        return json.loads(response.text)",
    "docstring": "Load a JSON response.\n\n        :param Response response: The HTTP response.\n        :return dict: The JSON-loaded content."
  },
  {
    "code": "def design_create(self, name, ddoc, use_devmode=True, syncwait=0):\n        name = self._cb._mk_devmode(name, use_devmode)\n        fqname = \"_design/{0}\".format(name)\n        if not isinstance(ddoc, dict):\n            ddoc = json.loads(ddoc)\n        ddoc = ddoc.copy()\n        ddoc['_id'] = fqname\n        ddoc = json.dumps(ddoc)\n        existing = None\n        if syncwait:\n            try:\n                existing = self.design_get(name, use_devmode=False)\n            except CouchbaseError:\n                pass\n        ret = self._cb._http_request(\n            type=_LCB.LCB_HTTP_TYPE_VIEW, path=fqname,\n            method=_LCB.LCB_HTTP_METHOD_PUT, post_data=ddoc,\n            content_type=\"application/json\")\n        self._design_poll(name, 'add', existing, syncwait,\n                          use_devmode=use_devmode)\n        return ret",
    "docstring": "Store a design document\n\n        :param string name: The name of the design\n        :param ddoc: The actual contents of the design document\n\n        :type ddoc: string or dict\n            If ``ddoc`` is a string, it is passed, as-is, to the server.\n            Otherwise it is serialized as JSON, and its ``_id`` field is set to\n            ``_design/{name}``.\n\n        :param bool use_devmode:\n            Whether a *development* mode view should be used. Development-mode\n            views are less resource demanding with the caveat that by default\n            they only operate on a subset of the data. Normally a view will\n            initially be created in 'development mode', and then published\n            using :meth:`design_publish`\n\n        :param float syncwait:\n            How long to poll for the action to complete. Server side design\n            operations are scheduled and thus this function may return before\n            the operation is actually completed. Specifying the timeout here\n            ensures the client polls during this interval to ensure the\n            operation has completed.\n\n        :raise: :exc:`couchbase.exceptions.TimeoutError` if ``syncwait`` was\n            specified and the operation could not be verified within the\n            interval specified.\n\n        :return: An :class:`~couchbase.result.HttpResult` object.\n\n        .. seealso:: :meth:`design_get`, :meth:`design_delete`,\n            :meth:`design_publish`"
  },
  {
    "code": "def get_real_field(model, field_name):\n    parts = field_name.split('__')\n    field = model._meta.get_field(parts[0])\n    if len(parts) == 1:\n        return model._meta.get_field(field_name)\n    elif isinstance(field, models.ForeignKey):\n        return get_real_field(field.rel.to, '__'.join(parts[1:]))\n    else:\n        raise Exception('Unhandled field: %s' % field_name)",
    "docstring": "Get the real field from a model given its name.\n\n    Handle nested models recursively (aka. ``__`` lookups)"
  },
  {
    "code": "def get(self, channel_sid):\n        return UserChannelContext(\n            self._version,\n            service_sid=self._solution['service_sid'],\n            user_sid=self._solution['user_sid'],\n            channel_sid=channel_sid,\n        )",
    "docstring": "Constructs a UserChannelContext\n\n        :param channel_sid: The SID of the Channel that has the User Channel to fetch\n\n        :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext\n        :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext"
  },
  {
    "code": "def get_left_right(seq):\n    cseq = seq.strip(GAPS)\n    leftjust = seq.index(cseq[0])\n    rightjust = seq.rindex(cseq[-1])\n    return leftjust, rightjust",
    "docstring": "Find position of the first and last base"
  },
  {
    "code": "def get(self, timeout):\n        if self._first:\n            self._first = False\n            return (\"ping\", PingStats.get(), {})\n        try:\n            (action, msg, kwargs) = yield from asyncio.wait_for(super().get(), timeout)\n        except asyncio.futures.TimeoutError:\n            return (\"ping\", PingStats.get(), {})\n        return (action, msg, kwargs)",
    "docstring": "When timeout is expire we send a ping notification with server information"
  },
  {
    "code": "def _fast_read(self, infile):\n        infile.seek(0)\n        return(int(infile.read().decode().strip()))",
    "docstring": "Function for fast reading from sensor files."
  },
  {
    "code": "def decode(self,\n             dataset_split=None,\n             decode_from_file=False,\n             checkpoint_path=None):\n    if decode_from_file:\n      decoding.decode_from_file(self._estimator,\n                                self._decode_hparams.decode_from_file,\n                                self._hparams,\n                                self._decode_hparams,\n                                self._decode_hparams.decode_to_file)\n    else:\n      decoding.decode_from_dataset(\n          self._estimator,\n          self._hparams.problem.name,\n          self._hparams,\n          self._decode_hparams,\n          dataset_split=dataset_split,\n          checkpoint_path=checkpoint_path)",
    "docstring": "Decodes from dataset or file."
  },
  {
    "code": "def install(pkg, target='LocalSystem', store=False, allow_untrusted=False):\n    if '*.' not in pkg:\n        pkg = _quote(pkg)\n    target = _quote(target)\n    cmd = 'installer -pkg {0} -target {1}'.format(pkg, target)\n    if store:\n        cmd += ' -store'\n    if allow_untrusted:\n        cmd += ' -allowUntrusted'\n    python_shell = False\n    if '*.' in cmd:\n        python_shell = True\n    return __salt__['cmd.run_all'](cmd, python_shell=python_shell)",
    "docstring": "Install a pkg file\n\n    Args:\n        pkg (str): The package to install\n        target (str): The target in which to install the package to\n        store (bool): Should the package be installed as if it was from the\n                      store?\n        allow_untrusted (bool): Allow the installation of untrusted packages?\n\n    Returns:\n        dict: A dictionary containing the results of the installation\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' macpackage.install test.pkg"
  },
  {
    "code": "def attach_template(self, _template, _key, **unbound_var_values):\n    if _key in unbound_var_values:\n      raise ValueError('%s specified twice.' % _key)\n    unbound_var_values[_key] = self\n    return _template.as_layer().construct(**unbound_var_values)",
    "docstring": "Attaches the template to this such that _key=this layer.\n\n    Note: names were chosen to avoid conflicts with any likely unbound_var keys.\n\n    Args:\n      _template: The template to construct.\n      _key: The key that this layer should replace.\n      **unbound_var_values: The values for the unbound_vars.\n    Returns:\n      A new layer with operation applied.\n    Raises:\n      ValueError: If _key is specified twice or there is a problem computing the\n        template."
  },
  {
    "code": "def ctypes2buffer(cptr, length):\n    if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)):\n        raise RuntimeError('expected char pointer')\n    res = bytearray(length)\n    rptr = (ctypes.c_char * length).from_buffer(res)\n    if not ctypes.memmove(rptr, cptr, length):\n        raise RuntimeError('memmove failed')\n    return res",
    "docstring": "Convert ctypes pointer to buffer type."
  },
  {
    "code": "def get_location(conn, vm_):\n    locations = conn.list_locations()\n    loc = config.get_cloud_config_value('location', vm_, __opts__, default=2)\n    for location in locations:\n        if six.text_type(loc) in (six.text_type(location.id), six.text_type(location.name)):\n            return location",
    "docstring": "Return the node location to use"
  },
  {
    "code": "def logout(request):\n    request.response.headers.extend(forget(request))\n    return {'redirect': request.POST.get('came_from', '/')}",
    "docstring": "View to forget the user"
  },
  {
    "code": "def parse_institution_address(address, city, state_province,\n                              country, postal_code, country_code):\n    address_list = force_list(address)\n    state_province = match_us_state(state_province) or state_province\n    postal_code = force_list(postal_code)\n    country = force_list(country)\n    country_code = match_country_code(country_code)\n    if isinstance(postal_code, (tuple, list)):\n        postal_code = ', '.join(postal_code)\n    if isinstance(country, (tuple, list)):\n        country = ', '.join(set(country))\n    if not country_code and country:\n        country_code = match_country_name_to_its_code(country)\n    if not country_code and state_province and state_province in us_state_to_iso_code.values():\n        country_code = 'US'\n    return {\n        'cities': force_list(city),\n        'country_code': country_code,\n        'postal_address': address_list,\n        'postal_code': postal_code,\n        'state': state_province,\n    }",
    "docstring": "Parse an institution address."
  },
  {
    "code": "def _on_mode_change(self, mode):\n        if isinstance(mode, (tuple, list)):\n            mode = mode[0]\n        if mode is None:\n            _LOGGER.warning(\"Mode change event with no mode.\")\n            return\n        if not mode or mode.lower() not in CONST.ALL_MODES:\n            _LOGGER.warning(\"Mode change event with unknown mode: %s\", mode)\n            return\n        _LOGGER.debug(\"Alarm mode change event to: %s\", mode)\n        alarm_device = self._abode.get_alarm(refresh=True)\n        alarm_device._json_state['mode']['area_1'] = mode\n        for callback in self._device_callbacks.get(alarm_device.device_id, ()):\n            _execute_callback(callback, alarm_device)",
    "docstring": "Mode change broadcast from Abode SocketIO server."
  },
  {
    "code": "def remote_access(self, service=None, use_xarray=None):\n        if service is None:\n            service = 'CdmRemote' if 'CdmRemote' in self.access_urls else 'OPENDAP'\n        if service not in (CaseInsensitiveStr('CdmRemote'), CaseInsensitiveStr('OPENDAP')):\n            raise ValueError(service + ' is not a valid service for remote_access')\n        return self.access_with_service(service, use_xarray)",
    "docstring": "Access the remote dataset.\n\n        Open the remote dataset and get a netCDF4-compatible `Dataset` object providing\n        index-based subsetting capabilities.\n\n        Parameters\n        ----------\n        service : str, optional\n            The name of the service to use for access to the dataset, either\n            'CdmRemote' or 'OPENDAP'. Defaults to 'CdmRemote'.\n\n        Returns\n        -------\n        Dataset\n            Object for netCDF4-like access to the dataset"
  },
  {
    "code": "def request_name(self, name):\n        while name in self._blacklist:\n            name += \"_\"\n        self._blacklist.add(name)\n        return name",
    "docstring": "Request a name, might return the name or a similar one if already\n        used or reserved"
  },
  {
    "code": "def _load_meta(self, meta):\n        meta = yaml.load(meta, Loader=Loader)\n        if 'version' in meta:\n            meta['version'] = str(meta['version'])\n        return meta",
    "docstring": "Load data from meta.yaml to a dictionary"
  },
  {
    "code": "def _get_model(self, lookup_keys, session):\n        try:\n            return self.queryset(session).filter_by(**lookup_keys).one()\n        except NoResultFound:\n            raise NotFoundException('No model of type {0} was found using '\n                                    'lookup_keys {1}'.format(self.model.__name__, lookup_keys))",
    "docstring": "Gets the sqlalchemy Model instance associated with\n        the lookup keys.\n\n        :param dict lookup_keys: A dictionary of the keys\n            and their associated values.\n        :param Session session: The sqlalchemy session\n        :return: The sqlalchemy orm model instance."
  },
  {
    "code": "def successors(self):\n        if not self.children:\n            return\n        for part in self.children:\n            yield part\n            for subpart in part.successors():\n                yield subpart",
    "docstring": "Yield Compounds below self in the hierarchy.\n\n        Yields\n        -------\n        mb.Compound\n            The next Particle below self in the hierarchy"
  },
  {
    "code": "def get_contact_method(self, id, **kwargs):\n        endpoint = '{0}/{1}/contact_methods/{2}'.format(\n            self.endpoint,\n            self['id'],\n            id,\n        )\n        result = self.request('GET', endpoint=endpoint, query_params=kwargs)\n        return result['contact_method']",
    "docstring": "Get a contact method for this user."
  },
  {
    "code": "def _infer_binary_operation(left, right, binary_opnode, context, flow_factory):\n    context, reverse_context = _get_binop_contexts(context, left, right)\n    left_type = helpers.object_type(left)\n    right_type = helpers.object_type(right)\n    methods = flow_factory(\n        left, left_type, binary_opnode, right, right_type, context, reverse_context\n    )\n    for method in methods:\n        try:\n            results = list(method())\n        except AttributeError:\n            continue\n        except exceptions.AttributeInferenceError:\n            continue\n        except exceptions.InferenceError:\n            yield util.Uninferable\n            return\n        else:\n            if any(result is util.Uninferable for result in results):\n                yield util.Uninferable\n                return\n            if all(map(_is_not_implemented, results)):\n                continue\n            not_implemented = sum(\n                1 for result in results if _is_not_implemented(result)\n            )\n            if not_implemented and not_implemented != len(results):\n                yield util.Uninferable\n                return\n            yield from results\n            return\n    yield util.BadBinaryOperationMessage(left_type, binary_opnode.op, right_type)",
    "docstring": "Infer a binary operation between a left operand and a right operand\n\n    This is used by both normal binary operations and augmented binary\n    operations, the only difference is the flow factory used."
  },
  {
    "code": "def show(context,\n         log,\n         results_file,\n         verbose,\n         item):\n    history_log = context.obj['history_log']\n    no_color = context.obj['no_color']\n    if not results_file:\n        try:\n            with open(history_log, 'r') as f:\n                lines = f.readlines()\n            history = lines[len(lines) - item]\n        except IndexError:\n            echo_style(\n                'History result at index %s does not exist.' % item,\n                no_color,\n                fg='red'\n            )\n            sys.exit(1)\n        except Exception:\n            echo_style(\n                'Unable to retrieve results history, '\n                'provide results file or re-run test.',\n                no_color,\n                fg='red'\n            )\n            sys.exit(1)\n        log_file = get_log_file_from_item(history)\n        if log:\n            echo_log(log_file, no_color)\n        else:\n            echo_results_file(\n                log_file.rsplit('.', 1)[0] + '.results',\n                no_color,\n                verbose\n            )\n    elif log:\n        echo_log(results_file, no_color)\n    else:\n        echo_results_file(results_file, no_color, verbose)",
    "docstring": "Print test results info from provided results json file.\n\n    If no results file is supplied echo results from most recent\n    test in history if it exists.\n\n    If verbose option selected, echo all test cases.\n\n    If log option selected echo test log."
  },
  {
    "code": "def _process_infohash_list(infohash_list):\n        if isinstance(infohash_list, list):\n            data = {'hashes': '|'.join([h.lower() for h in infohash_list])}\n        else:\n            data = {'hashes': infohash_list.lower()}\n        return data",
    "docstring": "Method to convert the infohash_list to qBittorrent API friendly values.\n\n        :param infohash_list: List of infohash."
  },
  {
    "code": "def around(A, decimals=0):\n    if isinstance(A, Poly):\n        B = A.A.copy()\n        for key in A.keys:\n            B[key] = around(B[key], decimals)\n        return Poly(B, A.dim, A.shape, A.dtype)\n    return numpy.around(A, decimals)",
    "docstring": "Evenly round to the given number of decimals.\n\n    Args:\n        A (Poly, numpy.ndarray):\n            Input data.\n        decimals (int):\n            Number of decimal places to round to (default: 0).  If decimals is\n            negative, it specifies the number of positions to the left of the\n            decimal point.\n\n    Returns:\n        (Poly, numpy.ndarray):\n            Same type as A.\n\n    Examples:\n        >>> P = chaospy.prange(3)*2**-numpy.arange(0, 6, 2, float)\n        >>> print(P)\n        [1.0, 0.25q0, 0.0625q0^2]\n        >>> print(chaospy.around(P))\n        [1.0, 0.0, 0.0]\n        >>> print(chaospy.around(P, 2))\n        [1.0, 0.25q0, 0.06q0^2]"
  },
  {
    "code": "def delete(self, cascade=False, delete_shares=False):\n        if self.id:\n            self.connection.post('delete_video', video_id=self.id,\n                cascade=cascade, delete_shares=delete_shares)\n            self.id = None",
    "docstring": "Deletes the video."
  },
  {
    "code": "def expand(fn, col, inputtype=pd.DataFrame):\n    if inputtype == pd.DataFrame:\n        if isinstance(col, int):\n            def _wrapper(*args, **kwargs):\n                return fn(args[0].iloc[:, col], *args[1:], **kwargs)\n            return _wrapper\n        def _wrapper(*args, **kwargs):\n            return fn(args[0].loc[:, col], *args[1:], **kwargs)\n        return _wrapper\n    elif inputtype == np.ndarray:\n        def _wrapper(*args, **kwargs):\n            return fn(args[0][:, col], *args[1:], **kwargs)\n        return _wrapper\n    raise TypeError(\"invalid input type\")",
    "docstring": "Wrap a function applying to a single column to make a function\n    applying to a multi-dimensional dataframe or ndarray\n\n    Parameters\n    ----------\n    fn : function\n        Function that applies to a series or vector.\n\n    col : str or int\n        Index of column to which to apply `fn`.\n\n    inputtype : class or type\n        Type of input to be expected by the wrapped function.\n        Normally pd.DataFrame or np.ndarray. Defaults to pd.DataFrame.\n\n    Returns\n    ----------\n    wrapped : function\n        Function that takes an input of type `inputtype` and applies\n        `fn` to the specified `col`."
  },
  {
    "code": "def existing_config_files():\n    global _ETC_PATHS\n    global _MAIN_CONFIG_FILE\n    global _CONFIG_VAR_INCLUDE\n    global _CONFIG_FILTER\n    config_files = []\n    for possible in _ETC_PATHS:\n        config_files = config_files + glob.glob(\"%s%s\" % (possible, _MAIN_CONFIG_FILE))\n    if _CONFIG_VAR_INCLUDE != \"\":\n        main_config = Configuration(\"general\", {\n            _CONFIG_VAR_INCLUDE:\"\"\n        }, _MAIN_CONFIG_FILE)\n        if main_config.CONFIG_DIR != \"\":\n            for possible in _ETC_PATHS:\n                config_files = config_files + glob.glob(\"%s%s/%s\" % (possible, main_config.CONFIG_DIR, _CONFIG_FILTER))\n    return config_files",
    "docstring": "Method that calculates all the configuration files that are valid, according to the\n        'set_paths' and other methods for this module."
  },
  {
    "code": "def get_attribute_id(self, attribute_key):\n    attribute = self.attribute_key_map.get(attribute_key)\n    has_reserved_prefix = attribute_key.startswith(RESERVED_ATTRIBUTE_PREFIX)\n    if attribute:\n      if has_reserved_prefix:\n        self.logger.warning(('Attribute %s unexpectedly has reserved prefix %s; using attribute ID '\n                             'instead of reserved attribute name.' % (attribute_key, RESERVED_ATTRIBUTE_PREFIX)))\n      return attribute.id\n    if has_reserved_prefix:\n      return attribute_key\n    self.logger.error('Attribute \"%s\" is not in datafile.' % attribute_key)\n    self.error_handler.handle_error(exceptions.InvalidAttributeException(enums.Errors.INVALID_ATTRIBUTE_ERROR))\n    return None",
    "docstring": "Get attribute ID for the provided attribute key.\n\n    Args:\n      attribute_key: Attribute key for which attribute is to be fetched.\n\n    Returns:\n      Attribute ID corresponding to the provided attribute key."
  },
  {
    "code": "def set_idlemax(self, idlemax):\n        is_running = yield from self.is_running()\n        if is_running:\n            yield from self._hypervisor.send('vm set_idle_max \"{name}\" 0 {idlemax}'.format(name=self._name, idlemax=idlemax))\n        log.info('Router \"{name}\" [{id}]: idlemax updated from {old_idlemax} to {new_idlemax}'.format(name=self._name,\n                                                                                                      id=self._id,\n                                                                                                      old_idlemax=self._idlemax,\n                                                                                                      new_idlemax=idlemax))\n        self._idlemax = idlemax",
    "docstring": "Sets CPU idle max value\n\n        :param idlemax: idle max value (integer)"
  },
  {
    "code": "def _getaddrinfo(self, host: str, family: int=socket.AF_UNSPEC) \\\n            -> List[tuple]:\n        event_loop = asyncio.get_event_loop()\n        query = event_loop.getaddrinfo(host, 0, family=family,\n                                       proto=socket.IPPROTO_TCP)\n        if self._timeout:\n            query = asyncio.wait_for(query, self._timeout)\n        try:\n            results = yield from query\n        except socket.error as error:\n            if error.errno in (\n                    socket.EAI_FAIL,\n                    socket.EAI_NODATA,\n                    socket.EAI_NONAME):\n                raise DNSNotFound(\n                    'DNS resolution failed: {error}'.format(error=error)\n                ) from error\n            else:\n                raise NetworkError(\n                    'DNS resolution error: {error}'.format(error=error)\n                ) from error\n        except asyncio.TimeoutError as error:\n            raise NetworkError('DNS resolve timed out.') from error\n        else:\n            return results",
    "docstring": "Query DNS using system resolver.\n\n        Coroutine."
  },
  {
    "code": "def explicit_start_marker(self, source):\n        if not self.use_cell_markers:\n            return False\n        if self.metadata:\n            return True\n        if self.cell_marker_start:\n            start_code_re = re.compile('^' + self.comment + r'\\s*' + self.cell_marker_start + r'\\s*(.*)$')\n            end_code_re = re.compile('^' + self.comment + r'\\s*' + self.cell_marker_end + r'\\s*$')\n            if start_code_re.match(source[0]) or end_code_re.match(source[0]):\n                return False\n        if all([line.startswith(self.comment) for line in self.source]):\n            return True\n        if LightScriptCellReader(self.fmt).read(source)[1] < len(source):\n            return True\n        return False",
    "docstring": "Does the python representation of this cell requires an explicit\n        start of cell marker?"
  },
  {
    "code": "def lock(self, name, ttl=60):\n        return locks.Lock(name, ttl=ttl, etcd_client=self)",
    "docstring": "Create a new lock.\n\n        :param name: name of the lock\n        :type name: string or bytes\n        :param ttl: length of time for the lock to live for in seconds. The\n                    lock will be released after this time elapses, unless\n                    refreshed\n        :type ttl: int\n        :returns: new lock\n        :rtype: :class:`.Lock`"
  },
  {
    "code": "def get_session_data(ctx, username, password, salt, server_public, private, preset):\n    session = SRPClientSession(\n        SRPContext(username, password, prime=preset[0], generator=preset[1]),\n        private=private)\n    session.process(server_public, salt, base64=True)\n    click.secho('Client session key: %s' % session.key_b64)\n    click.secho('Client session key proof: %s' % session.key_proof_b64)\n    click.secho('Client session key hash: %s' % session.key_proof_hash_b64)",
    "docstring": "Print out client session data."
  },
  {
    "code": "def _parse_vrf_query(self, query_str):\n        sp = smart_parsing.VrfSmartParser()\n        query = sp.parse(query_str)\n        return query",
    "docstring": "Parse a smart search query for VRFs\n\n            This is a helper function to smart_search_vrf for easier unit\n            testing of the parser."
  },
  {
    "code": "def add_detector(self, detector_cls):\n        if not issubclass(detector_cls, detectors.base.Detector):\n            raise TypeError((\n                '\"%(detector_cls)s\" is not a subclass of Detector'\n            ) % locals())\n        name = detector_cls.filth_cls.type\n        if name in self._detectors:\n            raise KeyError((\n                'can not add Detector \"%(name)s\"---it already exists. '\n                'Try removing it first.'\n            ) % locals())\n        self._detectors[name] = detector_cls()",
    "docstring": "Add a ``Detector`` to scrubadub"
  },
  {
    "code": "def sort(self):\n        self.sorted_commits = []\n        if not self.commits:\n            return self.sorted_commits\n        prev_commit = self.commits.pop(0)\n        prev_line = prev_commit.line_number\n        prev_uuid = prev_commit.uuid\n        for commit in self.commits:\n            if (commit.uuid != prev_uuid or\n                    commit.line_number != (prev_line + 1)):\n                prev_commit.lines = self.line_range(prev_commit.line_number,\n                                                    prev_line)\n                self.sorted_commits.append(prev_commit)\n                prev_commit = commit\n            prev_line = commit.line_number\n            prev_uuid = commit.uuid\n        prev_commit.lines = self.line_range(prev_commit.line_number, prev_line)\n        self.sorted_commits.append(prev_commit)\n        return self.sorted_commits",
    "docstring": "Consolidate adjacent lines, if same commit ID.\n\n        Will modify line number to be a range, when two or more lines with the\n        same commit ID."
  },
  {
    "code": "def clean(self):\n        super().clean()\n        if self.group:\n            self.groupname = self.group.name\n        elif not self.groupname:\n            raise ValidationError({\n                'groupname': _NOT_BLANK_MESSAGE,\n                'group': _NOT_BLANK_MESSAGE\n            })",
    "docstring": "automatically sets groupname"
  },
  {
    "code": "def old_values(self):\n        def get_old_values_and_key(item):\n            values = item.old_values\n            values.update({self._key: item.past_dict[self._key]})\n            return values\n        return [get_old_values_and_key(el)\n                for el in self._get_recursive_difference('all')\n                if el.diffs and el.past_dict]",
    "docstring": "Returns the old values from the diff"
  },
  {
    "code": "def send_key(self, key):\n        _LOGGER.info('Queueing key %s', key)\n        frame = self._get_key_event_frame(key)\n        self._send_queue.put({'frame': frame})",
    "docstring": "Sends a key."
  },
  {
    "code": "def get(self, sid):\n        return FunctionVersionContext(\n            self._version,\n            service_sid=self._solution['service_sid'],\n            function_sid=self._solution['function_sid'],\n            sid=sid,\n        )",
    "docstring": "Constructs a FunctionVersionContext\n\n        :param sid: The sid\n\n        :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext\n        :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext"
  },
  {
    "code": "def validate_sum(parameter_container, validation_message, **kwargs):\n    parameters = parameter_container.get_parameters(False)\n    values = []\n    for parameter in parameters:\n        if parameter.selected_option_type() in [SINGLE_DYNAMIC, STATIC]:\n            values.append(parameter.value)\n    sum_threshold = kwargs.get('max', 1)\n    if None in values:\n        clean_value = [x for x in values if x is not None]\n        values.remove(None)\n        if sum(clean_value) > sum_threshold:\n            return {\n                'valid': False,\n                'message': validation_message\n            }\n    else:\n        if sum(values) > sum_threshold:\n            return {\n                'valid': False,\n                'message': validation_message\n            }\n    return {\n        'valid': True,\n        'message': ''\n    }",
    "docstring": "Validate the sum of parameter value's.\n\n    :param parameter_container: The container that use this validator.\n    :type parameter_container: ParameterContainer\n\n    :param validation_message: The message if there is validation error.\n    :type validation_message: str\n\n    :param kwargs: Keywords Argument.\n    :type kwargs: dict\n\n    :returns: Dictionary of valid and message.\n    :rtype: dict\n\n    Note: The code is not the best I wrote, since there are two alternatives.\n    1. If there is no None, the sum must be equal to 1\n    2. If there is no None, the sum must be less than 1"
  },
  {
    "code": "def parse_osm_node(response):\n    try:\n        point = Point(response['lon'], response['lat'])\n        poi = {\n            'osmid': response['id'],\n            'geometry': point\n        }\n        if 'tags' in response:\n            for tag in response['tags']:\n                poi[tag] = response['tags'][tag]\n    except Exception:\n        log('Point has invalid geometry: {}'.format(response['id']))\n    return poi",
    "docstring": "Parse points from OSM nodes.\n\n    Parameters\n    ----------\n    response : JSON \n        Nodes from OSM response.  \n\n    Returns\n    -------\n    Dict of vertex IDs and their lat, lon coordinates."
  },
  {
    "code": "def start_processing(self, message, steps=0, warning=True):\n        if self.__is_processing:\n            warning and LOGGER.warning(\n                \"!> {0} | Engine is already processing, 'start_processing' request has been ignored!\".format(\n                    self.__class__.__name__))\n            return False\n        LOGGER.debug(\"> Starting processing operation!\")\n        self.__is_processing = True\n        self.Application_Progress_Status_processing.Processing_progressBar.setRange(0, steps)\n        self.Application_Progress_Status_processing.Processing_progressBar.setValue(0)\n        self.Application_Progress_Status_processing.show()\n        self.set_processing_message(message)\n        return True",
    "docstring": "Registers the start of a processing operation.\n\n        :param message: Operation description.\n        :type message: unicode\n        :param steps: Operation steps.\n        :type steps: int\n        :param warning: Emit warning message.\n        :type warning: int\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def fire_event(self, event_name, wait=False, *args, **kwargs):\n        tasks = []\n        event_method_name = \"on_\" + event_name\n        for plugin in self._plugins:\n            event_method = getattr(plugin.object, event_method_name, None)\n            if event_method:\n                try:\n                    task = self._schedule_coro(event_method(*args, **kwargs))\n                    tasks.append(task)\n                    def clean_fired_events(future):\n                        try:\n                            self._fired_events.remove(task)\n                        except (KeyError, ValueError):\n                            pass\n                    task.add_done_callback(clean_fired_events)\n                except AssertionError:\n                    self.logger.error(\"Method '%s' on plugin '%s' is not a coroutine\" %\n                                      (event_method_name, plugin.name))\n        self._fired_events.extend(tasks)\n        if wait:\n            if tasks:\n                yield from asyncio.wait(tasks, loop=self._loop)",
    "docstring": "Fire an event to plugins.\n        PluginManager schedule @asyncio.coroutinecalls for each plugin on method called \"on_\" + event_name\n        For example, on_connect will be called on event 'connect'\n        Method calls are schedule in the asyn loop. wait parameter must be set to true to wait until all\n        mehtods are completed.\n        :param event_name:\n        :param args:\n        :param kwargs:\n        :param wait: indicates if fire_event should wait for plugin calls completion (True), or not\n        :return:"
  },
  {
    "code": "def regex_lexer(regex_pat):\n    if isinstance(regex_pat, str):\n        regex_pat = re.compile(regex_pat)\n        def f(inp_str, pos):\n            m = regex_pat.match(inp_str, pos)\n            return m.group() if m else None\n    elif hasattr(regex_pat, 'match'):\n        def f(inp_str, pos):\n            m = regex_pat.match(inp_str, pos)\n            return m.group() if m else None\n    else:\n        regex_pats = tuple(re.compile(e) for e in regex_pat)\n        def f(inp_str, pos):\n            for each_pat in regex_pats:\n                m = each_pat.match(inp_str, pos)\n                if m:\n                    return m.group()\n    return f",
    "docstring": "generate token names' cache"
  },
  {
    "code": "async def status_by_zip(self, zip_code: str) -> dict:\n        try:\n            location = next((\n                d for d in await self.user_reports()\n                if d['zip'] == zip_code))\n        except StopIteration:\n            return {}\n        return await self.status_by_coordinates(\n            float(location['latitude']), float(location['longitude']))",
    "docstring": "Get symptom data for the provided ZIP code."
  },
  {
    "code": "def delete(build_folder):\n    if _meta_.del_build in [\"on\", \"ON\"] and os.path.exists(build_folder):\n        shutil.rmtree(build_folder)",
    "docstring": "Delete build directory and all its contents."
  },
  {
    "code": "def retract(args):\n    if not args.msg:\n        return \"Syntax: !vote retract <pollnum>\"\n    if not args.msg.isdigit():\n        return \"Not A Valid Positive Integer.\"\n    response = get_response(args.session, args.msg, args.nick)\n    if response is None:\n        return \"You haven't voted on that poll yet!\"\n    args.session.delete(response)\n    return \"Vote retracted\"",
    "docstring": "Deletes a vote for a poll."
  },
  {
    "code": "def lnprior(pars):\n    logprob = (\n        naima.uniform_prior(pars[0], 0.0, np.inf)\n        + naima.uniform_prior(pars[1], -1, 5)\n        + naima.uniform_prior(pars[3], 0, np.inf)\n    )\n    return logprob",
    "docstring": "Return probability of parameter values according to prior knowledge.\n    Parameter limits should be done here through uniform prior ditributions"
  },
  {
    "code": "def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):\n    if isinstance(s, unicode):\n        return s\n    if strings_only and is_protected_type(s):\n        return s\n    try:\n        if not isinstance(s, basestring,):\n            if hasattr(s, '__unicode__'):\n                s = unicode(s)\n            else:\n                try:\n                    s = unicode(str(s), encoding, errors)\n                except UnicodeEncodeError:\n                    if not isinstance(s, Exception):\n                        raise\n                    s = u' '.join([force_unicode(arg, encoding, strings_only,\n                            errors) for arg in s])\n        elif not isinstance(s, unicode):\n            s = s.decode(encoding, errors)\n    except UnicodeDecodeError, e:\n        if not isinstance(s, Exception):\n            raise DjangoUnicodeDecodeError(s, *e.args)\n        else:\n            s = u' '.join([force_unicode(arg, encoding, strings_only,\n                    errors) for arg in s])\n    return s",
    "docstring": "Similar to smart_unicode, except that lazy instances are resolved to\n    strings, rather than kept as lazy objects.\n\n    If strings_only is True, don't convert (some) non-string-like objects."
  },
  {
    "code": "def describe(self, element):\n        if (element == 'tasks'):\n            return self.tasks_df.describe()\n        elif (element == 'task_runs'):\n            return self.task_runs_df.describe()\n        else:\n            return \"ERROR: %s not found\" % element",
    "docstring": "Return tasks or task_runs Panda describe."
  },
  {
    "code": "def dependency_of_fetches(fetches, op):\n    try:\n        from tensorflow.python.client.session import _FetchHandler as FetchHandler\n        handler = FetchHandler(op.graph, fetches, {})\n        targets = tuple(handler.fetches() + handler.targets())\n    except ImportError:\n        if isinstance(fetches, list):\n            targets = tuple(fetches)\n        elif isinstance(fetches, dict):\n            raise ValueError(\"Don't know how to parse dictionary to fetch list! \"\n                             \"This is a bug of tensorpack.\")\n        else:\n            targets = (fetches, )\n    return dependency_of_targets(targets, op)",
    "docstring": "Check that op is in the subgraph induced by the dependencies of fetches.\n    fetches may have more general structure.\n\n    Args:\n        fetches: An argument to `sess.run`. Nested structure will affect performance.\n        op (tf.Operation or tf.Tensor):\n\n    Returns:\n        bool: True if any of `fetches` depend on `op`."
  },
  {
    "code": "def timetopythonvalue(time_val):\n    \"Convert a time or time range from ArcGIS REST server format to Python\"\n    if isinstance(time_val, sequence):\n        return map(timetopythonvalue, time_val)\n    elif isinstance(time_val, numeric):\n        return datetime.datetime(*(time.gmtime(time_val))[:6])\n    elif isinstance(time_val, numeric):\n        values = []\n        try:\n            values = map(long, time_val.split(\",\"))\n        except:\n            pass\n        if values:\n            return map(timetopythonvalue, values)\n    raise ValueError(repr(time_val))",
    "docstring": "Convert a time or time range from ArcGIS REST server format to Python"
  },
  {
    "code": "def get_unique_name(self, prefix):\n        ident = sum(t.startswith(prefix) for t, _ in self.layers.items()) + 1\n        return '%s_%d' % (prefix, ident)",
    "docstring": "Returns an index-suffixed unique name for the given prefix.\n        This is used for auto-generating layer names based on the type-prefix."
  },
  {
    "code": "def load_data(self, data, **kwargs):\n        self.__set_map__(**kwargs)\n        start = datetime.datetime.now()\n        log.debug(\"Dataload stated\")\n        if isinstance(data, list):\n            data = self._convert_results(data, **kwargs)\n        class_types = self.__group_data__(data, **kwargs)\n        self._generate_classes(class_types, self.non_defined, **kwargs)\n        for triple in data:\n            self.add_triple(sub=triple, **kwargs)\n        log.debug(\"Dataload completed in '%s'\",\n                  (datetime.datetime.now() - start))",
    "docstring": "Bulk adds rdf data to the class\n\n        args:\n            data: the data to be loaded\n\n        kwargs:\n            strip_orphans: True or False - remove triples that have an\n                           orphan blanknode as the object\n            obj_method: \"list\", or None: if \"list\" the object of a method\n                         will be in the form of a list."
  },
  {
    "code": "def reset_globals(version=None, loop=None):\n    global containers\n    global instruments\n    global labware\n    global robot\n    global reset\n    global modules\n    global hardware\n    robot, reset, instruments, containers, labware, modules, hardware\\\n        = build_globals(version, loop)",
    "docstring": "Reinitialize the global singletons with a given API version.\n\n    :param version: 1 or 2. If `None`, pulled from the `useProtocolApiV2`\n                    advanced setting."
  },
  {
    "code": "def isRectangular(self):\n        upper = (self.ur - self.ul).unit\n        if not bool(upper):\n            return False\n        right = (self.lr - self.ur).unit\n        if not bool(right):\n            return False\n        left  = (self.ll - self.ul).unit\n        if not bool(left):\n            return False\n        lower = (self.lr - self.ll).unit\n        if not bool(lower):\n            return False\n        eps = 1e-5\n        return abs(sum(map(lambda x,y: x*y, upper, right))) <= eps and \\\n               abs(sum(map(lambda x,y: x*y, upper, left))) <= eps and \\\n               abs(sum(map(lambda x,y: x*y, left, lower))) <= eps",
    "docstring": "Check if quad is rectangular."
  },
  {
    "code": "def get_file_size(path):\n    assert isinstance(path, (str, _oldstr))\n    if not os.path.isfile(path):\n        raise IOError('File \"%s\" does not exist.', path)\n    return os.path.getsize(path)",
    "docstring": "The the size of a file in bytes.\n\n    Parameters\n    ----------\n    path: str\n        The path of the file.\n\n    Returns\n    -------\n    int\n        The size of the file in bytes.\n\n    Raises\n    ------\n    IOError\n        If the file does not exist.\n    OSError\n        If a file system error occurs."
  },
  {
    "code": "def _create_xml_node(cls):\n        try:\n            xml_map = cls._xml_map\n        except AttributeError:\n            raise ValueError(\"This model has no XML definition\")\n        return _create_xml_node(\n            xml_map.get('name', cls.__name__),\n            xml_map.get(\"prefix\", None),\n            xml_map.get(\"ns\", None)\n        )",
    "docstring": "Create XML node from \"_xml_map\"."
  },
  {
    "code": "def clear_recent_files(self):\n        self.manager.clear()\n        self.update_actions()\n        self.clear_requested.emit()",
    "docstring": "Clear recent files and menu."
  },
  {
    "code": "def reconfigArg(ArgConfig):\n  r\n  _type = ArgConfig.get('type')\n  if _type:\n    if hasattr(_type, '__ec_config__'):\n      _type.__ec_config__(ArgConfig)\n  if not 'type_str' in ArgConfig:\n    ArgConfig['type_str'] = (_type.__name__ if isinstance(_type, type) else 'unspecified type') if _type else 'str'\n  if not 'desc' in ArgConfig:\n    ArgConfig['desc'] = ArgConfig['name']\n  return ArgConfig",
    "docstring": "r\"\"\"Reconfigures an argument based on its configuration."
  },
  {
    "code": "def create(self, name):\n        vg = self.attach(-1, 1)\n        vg._name = name\n        return vg",
    "docstring": "Create a new vgroup, and assign it a name.\n\n        Args::\n\n          name   name to assign to the new vgroup\n\n        Returns::\n\n          VG instance for the new vgroup\n\n        A create(name) call is equivalent to an attach(-1, 1) call,\n        followed by a call to the setname(name) method of the instance.\n\n        C library equivalent : no equivalent"
  },
  {
    "code": "def add_all_database_reactions(model, compartments):\n    added = set()\n    for rxnid in model.database.reactions:\n        reaction = model.database.get_reaction(rxnid)\n        if all(compound.compartment in compartments\n               for compound, _ in reaction.compounds):\n            if not model.has_reaction(rxnid):\n                added.add(rxnid)\n            model.add_reaction(rxnid)\n    return added",
    "docstring": "Add all reactions from database that occur in given compartments.\n\n    Args:\n        model: :class:`psamm.metabolicmodel.MetabolicModel`."
  },
  {
    "code": "async def on_isupport_maxlist(self, value):\n        self._list_limits = {}\n        for entry in value.split(','):\n            modes, limit = entry.split(':')\n            self._list_limits[frozenset(modes)] = int(limit)\n            for mode in modes:\n                self._list_limit_groups[mode] = frozenset(modes)",
    "docstring": "Limits on channel modes involving lists."
  },
  {
    "code": "def _optional_envs():\n    envs = {\n        key: os.environ.get(key)\n        for key in OPTIONAL_ENV_VARS\n        if key in os.environ\n    }\n    if 'JOB_NAME' in envs and 'BUILD_NUMBER' not in envs:\n        raise BrowserConfigError(\"Missing BUILD_NUMBER environment var\")\n    if 'BUILD_NUMBER' in envs and 'JOB_NAME' not in envs:\n        raise BrowserConfigError(\"Missing JOB_NAME environment var\")\n    return envs",
    "docstring": "Parse environment variables for optional values,\n    raising a `BrowserConfig` error if they are insufficiently specified.\n\n    Returns a `dict` of environment variables."
  },
  {
    "code": "def get_pidpath(rundir, process_type, name=None):\n    assert rundir, \"rundir is not configured\"\n    path = os.path.join(rundir, '%s.pid' % process_type)\n    if name:\n        path = os.path.join(rundir, '%s.%s.pid' % (process_type, name))\n    log.log('common', 'get_pidpath for type %s, name %r: %s'\n            % (process_type, name, path))\n    return path",
    "docstring": "Get the full path to the pid file for the given process type and name."
  },
  {
    "code": "def set_mouse_button_callback(window, cbfun):\n    window_addr = ctypes.cast(ctypes.pointer(window),\n                              ctypes.POINTER(ctypes.c_long)).contents.value\n    if window_addr in _mouse_button_callback_repository:\n        previous_callback = _mouse_button_callback_repository[window_addr]\n    else:\n        previous_callback = None\n    if cbfun is None:\n        cbfun = 0\n    c_cbfun = _GLFWmousebuttonfun(cbfun)\n    _mouse_button_callback_repository[window_addr] = (cbfun, c_cbfun)\n    cbfun = c_cbfun\n    _glfw.glfwSetMouseButtonCallback(window, cbfun)\n    if previous_callback is not None and previous_callback[0] != 0:\n        return previous_callback[0]",
    "docstring": "Sets the mouse button callback.\n\n    Wrapper for:\n        GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun cbfun);"
  },
  {
    "code": "def multiple_sources(stmt):\n    sources = list(set([e.source_api for e in stmt.evidence]))\n    if len(sources) > 1:\n        return True\n    return False",
    "docstring": "Return True if statement is supported by multiple sources.\n\n    Note: this is currently not used and replaced by BeliefEngine score cutoff"
  },
  {
    "code": "def section_names(self, ordkey=\"wall_time\"):\n        section_names = []\n        for idx, timer in enumerate(self.timers()):\n            if idx == 0:\n                section_names = [s.name for s in timer.order_sections(ordkey)]\n        return section_names",
    "docstring": "Return the names of sections ordered by ordkey.\n        For the time being, the values are taken from the first timer."
  },
  {
    "code": "def action_download(self, courseid, taskid, path):\n        wanted_path = self.verify_path(courseid, taskid, path)\n        if wanted_path is None:\n            raise web.notfound()\n        task_fs = self.task_factory.get_task_fs(courseid, taskid)\n        (method, mimetype_or_none, file_or_url) = task_fs.distribute(wanted_path)\n        if method == \"local\":\n            web.header('Content-Type', mimetype_or_none)\n            return file_or_url\n        elif method == \"url\":\n            raise web.redirect(file_or_url)\n        else:\n            raise web.notfound()",
    "docstring": "Download a file or a directory"
  },
  {
    "code": "def _bd_(self):\n        if not getattr(self, '__bd__', False):\n            self.__bd = BetterDictLookUp(self)\n        return self.__bd",
    "docstring": "Property that allows dot lookups of otherwise hidden attributes."
  },
  {
    "code": "def write(path, data, binary=False):\n    mode = \"w\"\n    if binary:\n        mode = \"wb\"\n    with open(path, mode) as f:\n        f.write(data)\n    f.close()",
    "docstring": "Writes a given data to a file located at the given path."
  },
  {
    "code": "def status(self):\n        orig_dict = self._get(self._service_url('status'))\n        orig_dict['implementation_version'] = orig_dict.pop('Implementation-Version')\n        orig_dict['built_from_git_sha1'] = orig_dict.pop('Built-From-Git-SHA1')\n        return Status(orig_dict)",
    "docstring": "Get the status of Alerting Service\n\n        :return: Status object"
  },
  {
    "code": "def _collect_zipimporter_cache_entries(normalized_path, cache):\n    result = []\n    prefix_len = len(normalized_path)\n    for p in cache:\n        np = normalize_path(p)\n        if (np.startswith(normalized_path) and\n                np[prefix_len:prefix_len + 1] in (os.sep, '')):\n            result.append(p)\n    return result",
    "docstring": "Return zipimporter cache entry keys related to a given normalized path.\n\n    Alternative path spellings (e.g. those using different character case or\n    those using alternative path separators) related to the same path are\n    included. Any sub-path entries are included as well, i.e. those\n    corresponding to zip archives embedded in other zip archives."
  },
  {
    "code": "def promote_s3app(self):\n        utils.banner(\"Promoting S3 App\")\n        primary_region = self.configs['pipeline']['primary_region']\n        s3obj = s3.S3Deployment(\n            app=self.app,\n            env=self.env,\n            region=self.region,\n            prop_path=self.json_path,\n            artifact_path=self.artifact_path,\n            artifact_version=self.artifact_version,\n            primary_region=primary_region)\n        s3obj.promote_artifacts(promote_stage=self.promote_stage)",
    "docstring": "promotes S3 deployment to LATEST"
  },
  {
    "code": "def form_valid(self, form, formsets):\n        new_object = False\n        if not self.object:\n            new_object = True\n        instance = getattr(form, 'instance', None)\n        auto_tags, changed_tags, old_tags = tag_handler.get_tags_from_data(\n            form.data, self.get_tags(instance))\n        tag_handler.set_auto_tags_for_form(form, auto_tags)\n        with transaction.commit_on_success():\n            self.object = self.save_form(form)\n            self.save_formsets(form, formsets, auto_tags=auto_tags)\n            url = self.get_object_url()\n            self.log_action(self.object, CMSLog.SAVE, url=url)\n            msg = self.write_message()\n        if not new_object and changed_tags and old_tags:\n            tag_handler.update_changed_tags(changed_tags, old_tags)\n        return self.success_response(msg)",
    "docstring": "Response for valid form. In one transaction this will\n        save the current form and formsets, log the action\n        and message the user.\n\n        Returns the results of calling the `success_response` method."
  },
  {
    "code": "async def async_run_command(self, command, retry=False):\n        if not self.is_connected:\n            await self.async_connect()\n        try:\n            result = await asyncio.wait_for(self._client.run(\n                \"%s && %s\" % (_PATH_EXPORT_COMMAND, command)), 9)\n        except asyncssh.misc.ChannelOpenError:\n            if not retry:\n                await self.async_connect()\n                return self.async_run_command(command, retry=True)\n            else:\n                self._connected = False\n                _LOGGER.error(\"No connection to host\")\n                return []\n        except TimeoutError:\n            del self._client\n            self._connected = False\n            _LOGGER.error(\"Host timeout.\")\n            return []\n        self._connected = True\n        return result.stdout.split('\\n')",
    "docstring": "Run commands through an SSH connection.\n\n        Connect to the SSH server if not currently connected, otherwise\n        use the existing connection."
  },
  {
    "code": "def get_by_code(self, code):\n        if any(x in code for x in ('_', '-')):\n            cc = CultureCode.objects.get(code=code.replace('_', '-'))\n            return cc.language\n        elif len(code) == 2:\n            return self.get(iso_639_1=code)\n        elif len(code) == 3:\n            return self.get(Q(iso_639_2T=code) |\n                            Q(iso_639_2B=code) |\n                            Q(iso_639_3=code))\n        raise ValueError(\n            'Code must be either 2, or 3 characters: \"%s\" is %s' % (code, len(code)))",
    "docstring": "Retrieve a language by a code.\n\n        :param code: iso code (any of the three) or its culture code\n        :return: a Language object"
  },
  {
    "code": "def get_dependencies(self, recursive=False):\n        dependencies = set()\n        for element in self.elements:\n            if isinstance(element, CellReference) or isinstance(\n                    element, CellArray):\n                if recursive:\n                    dependencies.update(\n                        element.ref_cell.get_dependencies(True))\n                dependencies.add(element.ref_cell)\n        return dependencies",
    "docstring": "Returns a list of the cells included in this cell as references.\n\n        Parameters\n        ----------\n        recursive : bool\n            If True returns cascading dependencies.\n\n        Returns\n        -------\n        out : set of ``Cell``\n            List of the cells referenced by this cell."
  },
  {
    "code": "def common(self, other):\n\t\tmandatory = min(self.mandatory, other.mandatory)\n\t\toptional = min(self.optional, other.optional)\n\t\treturn multiplier(mandatory, mandatory + optional)",
    "docstring": "Find the shared part of two multipliers. This is the largest multiplier\n\t\t\twhich can be safely subtracted from both the originals. This may\n\t\t\treturn the \"zero\" multiplier."
  },
  {
    "code": "def get_task_cls(cls, name):\n        task_cls = cls._get_reg().get(name)\n        if not task_cls:\n            raise TaskClassNotFoundException(cls._missing_task_msg(name))\n        if task_cls == cls.AMBIGUOUS_CLASS:\n            raise TaskClassAmbigiousException('Task %r is ambiguous' % name)\n        return task_cls",
    "docstring": "Returns an unambiguous class or raises an exception."
  },
  {
    "code": "def load_meta_data(self, path=None, recursively=True):\n        meta_data_path = path if path is not None else self.state_machine.file_system_path\n        if meta_data_path:\n            path_meta_data = os.path.join(meta_data_path, storage.FILE_NAME_META_DATA)\n            try:\n                tmp_meta = storage.load_data_file(path_meta_data)\n            except ValueError:\n                tmp_meta = {}\n        else:\n            tmp_meta = {}\n        tmp_meta = Vividict(tmp_meta)\n        if recursively:\n            root_state_path = None if not path else os.path.join(path, self.root_state.state.state_id)\n            self.root_state.load_meta_data(root_state_path)\n        if tmp_meta:\n            self.meta = tmp_meta\n            self.meta_signal.emit(MetaSignalMsg(\"load_meta_data\", \"all\", True))",
    "docstring": "Load meta data of state machine model from the file system\n\n        The meta data of the state machine model is loaded from the file system and stored in the meta property of the\n        model. Existing meta data is removed. Also the meta data of root state and children is loaded.\n\n        :param str path: Optional path to the meta data file. If not given, the path will be derived from the state\n            machine's path on the filesystem"
  },
  {
    "code": "def regroup(target, expression):\n    if not target: return ''\n    return [\n        {'grouper': key, 'list': list(val)}\n        for key, val in\n        groupby(obj_list, lambda v, f=expression.resolve: f(v, True))\n    ]",
    "docstring": "Regroups a list of alike objects by a common attribute.\n\n    This complex tag is best illustrated by use of an example:  say that\n    ``people`` is a list of ``Person`` objects that have ``first_name``,\n    ``last_name``, and ``gender`` attributes, and you'd like to display a list\n    that looks like:\n\n        * Male:\n            * George Bush\n            * Bill Clinton\n        * Female:\n            * Margaret Thatcher\n            * Colendeeza Rice\n        * Unknown:\n            * Pat Smith\n\n    The following snippet of template code would accomplish this dubious task::\n\n        {% regroup people by gender as grouped %}\n        <ul>\n        {% for group in grouped %}\n            <li>{{ group.grouper }}\n            <ul>\n                {% for item in group.list %}\n                <li>{{ item }}</li>\n                {% endfor %}\n            </ul>\n        {% endfor %}\n        </ul>\n\n    As you can see, ``{% regroup %}`` populates a variable with a list of\n    objects with ``grouper`` and ``list`` attributes.  ``grouper`` contains the\n    item that was grouped by; ``list`` contains the list of objects that share\n    that ``grouper``.  In this case, ``grouper`` would be ``Male``, ``Female``\n    and ``Unknown``, and ``list`` is the list of people with those genders.\n\n    Note that ``{% regroup %}`` does not work when the list to be grouped is not\n    sorted by the key you are grouping by!  This means that if your list of\n    people was not sorted by gender, you'd need to make sure it is sorted\n    before using it, i.e.::\n\n        {% regroup people|dictsort:\"gender\" by gender as grouped %}"
  },
  {
    "code": "def describe(DomainName,\n             region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    try:\n        domain = conn.describe_elasticsearch_domain_config(DomainName=DomainName)\n        if domain and 'DomainConfig' in domain:\n            domain = domain['DomainConfig']\n            keys = ('ElasticsearchClusterConfig', 'EBSOptions', 'AccessPolicies',\n                    'SnapshotOptions', 'AdvancedOptions')\n            return {'domain': dict([(k, domain.get(k, {}).get('Options')) for k in keys if k in domain])}\n        else:\n            return {'domain': None}\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Given a domain name describe its properties.\n\n    Returns a dictionary of interesting properties.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_elasticsearch_domain.describe mydomain"
  },
  {
    "code": "def vars_class(cls):\n    return dict(chain.from_iterable(\n        vars(cls).items() for cls in reversed(cls.__mro__)))",
    "docstring": "Return a dict of vars for the given class, including all ancestors.\n\n    This differs from the usual behaviour of `vars` which returns attributes\n    belonging to the given class and not its ancestors."
  },
  {
    "code": "def InterpolateValue(self,\n                       value,\n                       type_info_obj=type_info.String(),\n                       default_section=None,\n                       context=None):\n    if isinstance(value, Text):\n      try:\n        value = StringInterpolator(\n            value,\n            self,\n            default_section=default_section,\n            parameter=type_info_obj.name,\n            context=context).Parse()\n      except InterpolationError as e:\n        message = \"{cause}: {detail}\".format(cause=e, detail=value)\n        raise type(e)(message)\n      value = type_info_obj.FromString(value)\n    if isinstance(value, list):\n      value = [\n          self.InterpolateValue(\n              v, default_section=default_section, context=context)\n          for v in value\n      ]\n    return value",
    "docstring": "Interpolate the value and parse it with the appropriate type."
  },
  {
    "code": "def interstore(self, dest, *others):\n        keys = [self.key]\n        keys.extend([other.key for other in others])\n        self.database.sinterstore(dest, keys)\n        return self.database.Set(dest)",
    "docstring": "Store the intersection of the current set and one or more\n        others in a new key.\n\n        :param dest: the name of the key to store intersection\n        :param others: One or more :py:class:`Set` instances\n        :returns: A :py:class:`Set` referencing ``dest``."
  },
  {
    "code": "def extended_fade_out(self, segment, duration):\n        dur = int(duration * segment.track.samplerate)\n        if segment.start + segment.duration + dur <\\\n                segment.track.duration:\n            segment.duration += dur\n        else:\n            raise Exception(\n                \"Cannot create fade-out that extends past the track's end\")\n        score_loc_in_seconds = segment.comp_location_in_seconds +\\\n            segment.duration_in_seconds - duration\n        f = Fade(segment.track, score_loc_in_seconds, duration, 1.0, 0.0)\n        self.add_dynamic(f)\n        return f",
    "docstring": "Add a fade-out to a segment that extends the beginning of the\n        segment.\n\n        :param segment: Segment to fade out\n        :type segment: :py:class:`radiotool.composer.Segment`\n        :param duration: Duration of fade-out (in seconds)\n        :returns: The fade that has been added to the composition\n        :rtype: :py:class:`Fade`"
  },
  {
    "code": "def happybirthday(person):\n    print('Happy Birthday To You')\n    time.sleep(2)\n    print('Happy Birthday To You')\n    time.sleep(2)\n    print('Happy Birthday Dear ' + str(person[0].upper()) + str(person[1:]))\n    time.sleep(2)\n    print('Happy Birthday To You')",
    "docstring": "Sing Happy Birthday"
  },
  {
    "code": "def cylinder(target, throat_length='throat.length',\n             throat_diameter='throat.diameter'):\n    r\n    leng = target[throat_length]\n    diam = target[throat_diameter]\n    value = _sp.pi/4*leng*diam**2\n    return value",
    "docstring": "r\"\"\"\n    Calculate throat volume assuing a cylindrical shape\n\n    Parameters\n    ----------\n    target : OpenPNM Object\n        The object which this model is associated with. This controls the\n        length of the calculated array, and also provides access to other\n        necessary properties.\n\n    throat_length and throat_diameter : strings\n        The dictionary keys containing the arrays with the throat diameter and\n        length values.\n\n    Notes\n    -----\n    At present this models does NOT account for the volume reprsented by the\n    intersection of the throat with a spherical pore body."
  },
  {
    "code": "def sequence(self):\n        seq = [x.mol_code for x in self._monomers]\n        return ' '.join(seq)",
    "docstring": "Returns the sequence of the `Polynucleotide` as a string.\n\n        Returns\n        -------\n        sequence : str\n            String of the monomer sequence of the `Polynucleotide`."
  },
  {
    "code": "def disconnect(self, reason):\n        self._server._disconnect_client(self._conn_key, self, reason)",
    "docstring": "Disconnect this client connection for specified reason"
  },
  {
    "code": "def rule(self):\n        step_ratio = self.step_ratio\n        method = self.method\n        if method in ('multicomplex', ) or self.n == 0:\n            return np.ones((1,))\n        order, method_order = self.n - 1, self._method_order\n        parity = self._parity(method, order, method_order)\n        step = self._richardson_step()\n        num_terms, ix = (order + method_order) // step, order // step\n        fd_rules = FD_RULES.get((step_ratio, parity, num_terms))\n        if fd_rules is None:\n            fd_mat = self._fd_matrix(step_ratio, parity, num_terms)\n            fd_rules = linalg.pinv(fd_mat)\n            FD_RULES[(step_ratio, parity, num_terms)] = fd_rules\n        if self._flip_fd_rule:\n            return -fd_rules[ix]\n        return fd_rules[ix]",
    "docstring": "Return finite differencing rule.\n\n        The rule is for a nominal unit step size, and must be scaled later\n        to reflect the local step size.\n\n        Member methods used\n        -------------------\n        _fd_matrix\n\n        Member variables used\n        ---------------------\n        n\n        order\n        method"
  },
  {
    "code": "def next_task(self):\n        node = self._find_next_ready_node()\n        if node is None:\n            return None\n        executor = node.get_executor()\n        if executor is None:\n            return None\n        tlist = executor.get_all_targets()\n        task = self.tasker(self, tlist, node in self.original_top, node)\n        try:\n            task.make_ready()\n        except Exception as e :\n            self.ready_exc = sys.exc_info()\n        if self.ready_exc:\n            task.exception_set(self.ready_exc)\n        self.ready_exc = None\n        return task",
    "docstring": "Returns the next task to be executed.\n\n        This simply asks for the next Node to be evaluated, and then wraps\n        it in the specific Task subclass with which we were initialized."
  },
  {
    "code": "def find_outputs_in_range(self, ifo, current_segment, useSplitLists=False):\n        currsegment_list = segments.segmentlist([current_segment])\n        overlap_files = self.find_all_output_in_range(ifo, current_segment,\n                                                    useSplitLists=useSplitLists)\n        overlap_windows = [abs(i.segment_list & currsegment_list) for i in overlap_files]\n        if not overlap_windows:\n            return []\n        overlap_windows = numpy.array(overlap_windows, dtype = int)\n        segmentLst = overlap_files[overlap_windows.argmax()].segment_list\n        output_files = [f for f in overlap_files if f.segment_list==segmentLst]\n        return output_files",
    "docstring": "Return the list of Files that is most appropriate for the supplied\n        time range. That is, the Files whose coverage time has the\n        largest overlap with the supplied time range.\n\n        Parameters\n        -----------\n        ifo : string\n           Name of the ifo (or ifos) that the File should correspond to\n        current_segment : glue.segment.segment\n           The segment of time that files must intersect.\n\n        Returns\n        --------\n        FileList class\n           The list of Files that are most appropriate for the time range"
  },
  {
    "code": "def add_connection_score(self, node):\n        conntime = node.seconds_until_connect_ok()\n        if conntime > 0:\n            self.log(\"not considering %r for new connection; has %r left on \"\n                     \"connect blackout\" % (node, conntime))\n            return -conntime\n        numconns = self.num_connectors_to(node)\n        if numconns >= self.max_connections_per_node:\n            return float('-Inf')\n        return sys.maxint - numconns",
    "docstring": "Return a numeric value that determines this node's score for adding\n        a new connection. A negative value indicates that no connections\n        should be made to this node for at least that number of seconds.\n        A value of -inf indicates no connections should be made to this\n        node for the foreseeable future.\n\n        This score should ideally take into account the connectedness of\n        available nodes, so that those with less current connections will\n        get more."
  },
  {
    "code": "def get_average_along_axis(self, ind):\n        m = self.data[\"total\"]\n        ng = self.dim\n        if ind == 0:\n            total = np.sum(np.sum(m, axis=1), 1)\n        elif ind == 1:\n            total = np.sum(np.sum(m, axis=0), 1)\n        else:\n            total = np.sum(np.sum(m, axis=0), 0)\n        return total / ng[(ind + 1) % 3] / ng[(ind + 2) % 3]",
    "docstring": "Get the averaged total of the volumetric data a certain axis direction.\n        For example, useful for visualizing Hartree Potentials from a LOCPOT\n        file.\n\n        Args:\n            ind (int): Index of axis.\n\n        Returns:\n            Average total along axis"
  },
  {
    "code": "def load(self):\n        if self._dict is None:\n            if self.dirty:\n                self._dict = self._loader(self.filename)\n                self.cache()\n            else:\n                with open(self.cachename, 'rb') as stream:\n                    self._dict = cPickle.load(stream)\n        return self._dict",
    "docstring": "Loads the Python object\n\n        Loads the Python object, either via loader(filename) or the\n        pickled cache file, whichever was modified most recently."
  },
  {
    "code": "def text(self):\n        texts = []\n        for child in self.childs:\n            if isinstance(child, Tag):\n                texts.append(child.text())\n            elif isinstance(child, Content):\n                texts.append(child.render())\n            else:\n                texts.append(child)\n        return \" \".join(texts)",
    "docstring": "Renders the contents inside this element, without html tags."
  },
  {
    "code": "def userlogin(self, event):\n        client_uuid = event.clientuuid\n        self.log(event.user, pretty=True, lvl=verbose)\n        self.log('Adding client')\n        self.clients[event.clientuuid] = event.user\n        for topic, alert in self.alerts.items():\n            self.alert(client_uuid, alert)",
    "docstring": "Checks if an alert is ongoing and alerts the newly connected\n        client, if so."
  },
  {
    "code": "def setSystemProperty(cls, key, value):\n        SparkContext._ensure_initialized()\n        SparkContext._jvm.java.lang.System.setProperty(key, value)",
    "docstring": "Set a Java system property, such as spark.executor.memory. This must\n        must be invoked before instantiating SparkContext."
  },
  {
    "code": "def _effectupdate_raise_line_padding_on_focus(self, time_passed):\n        data = self._effects['raise-line-padding-on-focus']\n        pps = data['padding_pps']\n        for i, option in enumerate(self.options):\n            if i == self.option:\n                if option['padding_line'] < data['padding']:\n                    option['padding_line'] += pps * time_passed\n                elif option['padding_line'] > data['padding']:\n                    option['padding_line'] = data['padding']\n            elif option['padding_line']:\n                if option['padding_line'] > 0:\n                    option['padding_line'] -= pps * time_passed\n                elif option['padding_line'] < 0:\n                    option['padding_line'] = 0",
    "docstring": "Gradually enlarge the padding of the focused line."
  },
  {
    "code": "def relieve_all_models(self):\n        map(self.relieve_model, list(self.__registered_models))\n        self.__registered_models.clear()",
    "docstring": "Relieve all registered models\n\n        The method uses the set of registered models to relieve them."
  },
  {
    "code": "def bk_light(cls):\n        \"Make the current background color light.\"\n        wAttributes = cls._get_text_attributes()\n        wAttributes |= win32.BACKGROUND_INTENSITY\n        cls._set_text_attributes(wAttributes)",
    "docstring": "Make the current background color light."
  },
  {
    "code": "def _is_accepted(self, element_tag):\n        element_tag = element_tag.lower()\n        if self._ignored_tags is not None \\\n           and element_tag in self._ignored_tags:\n            return False\n        if self._followed_tags is not None:\n            return element_tag in self._followed_tags\n        else:\n            return True",
    "docstring": "Return if the link is accepted by the filters."
  },
  {
    "code": "def GetNodeStorageUnits(r, node, storage_type, output_fields):\n    query = {\n        \"storage_type\": storage_type,\n        \"output_fields\": output_fields,\n    }\n    return r.request(\"get\", \"/2/nodes/%s/storage\" % node, query=query)",
    "docstring": "Gets the storage units for a node.\n\n    @type node: str\n    @param node: the node whose storage units to return\n    @type storage_type: str\n    @param storage_type: storage type whose units to return\n    @type output_fields: str\n    @param output_fields: storage type fields to return\n\n    @rtype: int\n    @return: job id where results can be retrieved"
  },
  {
    "code": "def get_fields(self, strip_labels=False):\n        if strip_labels:\n            return [\n                f[0] if type(f) in (tuple, list) else f for f in self.fields\n            ]\n        return self.fields",
    "docstring": "Hook to dynamically change the fields that will be displayed"
  },
  {
    "code": "def second_textx_model(self, model_parser):\n        if self.grammar_parser.debug:\n            self.grammar_parser.dprint(\"RESOLVING MODEL PARSER: second_pass\")\n        self._resolve_rule_refs(self.grammar_parser, model_parser)\n        self._determine_rule_types(model_parser.metamodel)\n        self._resolve_cls_refs(self.grammar_parser, model_parser)\n        return model_parser",
    "docstring": "Cross reference resolving for parser model."
  },
  {
    "code": "def __calculate_audio_frames(self):\n\t\tif self.audioformat is None:\n\t\t\treturn\n\t\tstart_frame = self.clock.current_frame\n\t\ttotalsize = int(self.clip.audio.fps*self.clip.audio.duration)\n\t\tself.audio_times = list(range(0, totalsize, \n\t\t\tself.audioformat['buffersize'])) + [totalsize]\n\t\tdel(self.audio_times[0:start_frame])",
    "docstring": "Aligns audio with video. \n\t\tThis should be called for instance after a seeking operation or resuming \n\t\tfrom a pause."
  },
  {
    "code": "def update_nb_metadata(nb_path=None, title=None, summary=None, keywords='fastai', overwrite=True, **kwargs):\n    \"Creates jekyll metadata for given notebook path.\"\n    nb = read_nb(nb_path)\n    data = {'title': title, 'summary': summary, 'keywords': keywords, **kwargs}\n    data = {k:v for (k,v) in data.items() if v is not None}\n    if not data: return\n    nb['metadata']['jekyll'] = data\n    write_nb(nb, nb_path)\n    NotebookNotary().sign(nb)",
    "docstring": "Creates jekyll metadata for given notebook path."
  },
  {
    "code": "def contains_info(self, key, value):\n        if self.library is None:\n            return 0\n        load = self.library.load_card\n        matches = 0\n        for code in self.cards:\n            card = load(code)\n            if card.get_info(key) == value:\n                matches += 1\n        return matches",
    "docstring": "Returns how many cards in the deck have the specified value under the\n        specified key in their info data.\n\n        This method requires a library to be stored in the deck instance and\n        will return `None` if there is no library."
  },
  {
    "code": "def _format_type(lines, element, spacer=\"\"):\n    rlines = []\n    rlines.append(element.signature)\n    _format_summary(rlines, element)\n    rlines.append(\"\")\n    _format_generic(rlines, element, [\"summary\"])\n    if len(element.executables) > 0:\n        rlines.append(\"\\nEMBEDDED PROCEDURES\")\n        for key, value in list(element.executables.items()):\n            rlines.append(\"  {}\".format(value.__str__()))\n            target = value.target\n            if target is not None:\n                _format_executable(rlines, target, \"  \")\n    if len(element.members) > 0:\n        rlines.append(\"\\nEMBEDDED MEMBERS\")\n        for key, value in list(element.members.items()):\n            _format_value_element(rlines, value, \"  \")\n    lines.extend([spacer + l for l in rlines])",
    "docstring": "Formats a derived type for full documentation output."
  },
  {
    "code": "def split(str, pattern, limit=-1):\n    sc = SparkContext._active_spark_context\n    return Column(sc._jvm.functions.split(_to_java_column(str), pattern, limit))",
    "docstring": "Splits str around matches of the given pattern.\n\n    :param str: a string expression to split\n    :param pattern: a string representing a regular expression. The regex string should be\n        a Java regular expression.\n    :param limit: an integer which controls the number of times `pattern` is applied.\n\n        * ``limit > 0``: The resulting array's length will not be more than `limit`, and the\n                         resulting array's last entry will contain all input beyond the last\n                         matched pattern.\n        * ``limit <= 0``: `pattern` will be applied as many times as possible, and the resulting\n                          array can be of any size.\n\n    .. versionchanged:: 3.0\n       `split` now takes an optional `limit` field. If not provided, default limit value is -1.\n\n    >>> df = spark.createDataFrame([('oneAtwoBthreeC',)], ['s',])\n    >>> df.select(split(df.s, '[ABC]', 2).alias('s')).collect()\n    [Row(s=[u'one', u'twoBthreeC'])]\n    >>> df.select(split(df.s, '[ABC]', -1).alias('s')).collect()\n    [Row(s=[u'one', u'two', u'three', u''])]"
  },
  {
    "code": "def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT):\n    pub = jps.Publisher(topic_name, host=host, pub_port=pub_port)\n    time.sleep(0.1)\n    if repeat_rate is None:\n        pub.publish(json_msg)\n    else:\n        try:\n            while True:\n                pub.publish(json_msg)\n                time.sleep(1.0 / repeat_rate)\n        except KeyboardInterrupt:\n            pass",
    "docstring": "publishes the data to the topic\n\n    :param topic_name: name of the topic\n    :param json_msg: data to be published\n    :param repeat_rate: if None, publishes once. if not None, it is used as [Hz]."
  },
  {
    "code": "def _get_has_relation_query(self, relation):\n        from .relations import Relation\n        return Relation.no_constraints(\n            lambda: getattr(self.get_model(), relation)()\n        )",
    "docstring": "Get the \"has\" relation base query\n\n        :type relation: str\n\n        :rtype: Builder"
  },
  {
    "code": "def _validate_cert_format(name):\n    cert_formats = ['cer', 'pfx']\n    if name not in cert_formats:\n        message = (\"Invalid certificate format '{0}' specified. Valid formats:\"\n                   ' {1}').format(name, cert_formats)\n        raise SaltInvocationError(message)",
    "docstring": "Ensure that the certificate format, as determind from user input, is valid."
  },
  {
    "code": "def uniform_crossover(parents):\n    chromosome_length = len(parents[0])\n    children = [[], []]\n    for i in range(chromosome_length):\n        selected_parent = random.randint(0, 1)\n        children[0].append(parents[selected_parent][i])\n        children[1].append(parents[1 - selected_parent][i])\n    return children",
    "docstring": "Perform uniform crossover on two parent chromosomes.\n\n    Randomly take genes from one parent or the other.\n    Ex. p1 = xxxxx, p2 = yyyyy, child = xyxxy"
  },
  {
    "code": "def _rule_compare(rule1, rule2):\n    commonkeys = set(rule1.keys()).intersection(rule2.keys())\n    for key in commonkeys:\n        if rule1[key] != rule2[key]:\n            return False\n    return True",
    "docstring": "Compare the common keys between security group rules against eachother"
  },
  {
    "code": "def Param(name, value=None, unit=None, ucd=None, dataType=None, utype=None,\n          ac=True):\n    atts = locals()\n    atts.pop('ac')\n    temp_dict = {}\n    temp_dict.update(atts)\n    for k in temp_dict.keys():\n        if atts[k] is None:\n            del atts[k]\n    if (ac\n        and value is not None\n        and (not isinstance(value, string_types))\n        and dataType is None\n        ):\n        if type(value) in _datatypes_autoconversion:\n            datatype, func = _datatypes_autoconversion[type(value)]\n            atts['dataType'] = datatype\n            atts['value'] = func(value)\n    return objectify.Element('Param', attrib=atts)",
    "docstring": "'Parameter', used as a general purpose key-value entry in the 'What' section.\n\n    May be assembled into a :class:`Group`.\n\n    NB ``name`` is not mandated by schema, but *is* mandated in full spec.\n\n    Args:\n        value(str): String representing parameter value.\n            Or, if ``ac`` is true, then 'autoconversion' is attempted, in which case\n            ``value`` can also be an instance of one of the following:\n\n             * :py:obj:`bool`\n             * :py:obj:`int`\n             * :py:obj:`float`\n             * :py:class:`datetime.datetime`\n\n            This allows you to create Params without littering your code\n            with string casts, or worrying if the passed value is a float or a\n            string, etc.\n            NB the value is always *stored* as a string representation,\n            as per VO spec.\n        unit(str): Units of value. See :class:`.definitions.units`\n        ucd(str): `unified content descriptor <http://arxiv.org/abs/1110.0525>`_.\n            For a list of valid UCDs, see:\n            http://vocabularies.referata.com/wiki/Category:IVOA_UCD.\n        dataType(str): Denotes type of ``value``; restricted to 3 options:\n            ``string`` (default), ``int`` , or ``float``.\n            (NB *not* to be confused with standard XML Datatypes, which have many\n            more possible values.)\n        utype(str): See http://wiki.ivoa.net/twiki/bin/view/IVOA/Utypes\n        ac(bool): Attempt automatic conversion of passed ``value`` to string,\n            and set ``dataType`` accordingly (only attempted if ``dataType``\n            is the default, i.e. ``None``).\n            (NB only supports types listed in _datatypes_autoconversion dict)"
  },
  {
    "code": "def build_agency(pfeed):\n    return pd.DataFrame({\n      'agency_name': pfeed.meta['agency_name'].iat[0],\n      'agency_url': pfeed.meta['agency_url'].iat[0],\n      'agency_timezone': pfeed.meta['agency_timezone'].iat[0],\n    }, index=[0])",
    "docstring": "Given a ProtoFeed, return a DataFrame representing ``agency.txt``"
  },
  {
    "code": "def remove_section(self, section_name):\n        if section_name == \"DEFAULT\":\n            raise Exception(\"'DEFAULT' is reserved section name.\")\n        if section_name in self._sections:\n            del self._sections[section_name]\n        else:\n            raise Exception(\"Error! cannot find section '%s'.\")",
    "docstring": "Remove a section, it cannot be the DEFAULT section."
  },
  {
    "code": "def _load(self, scale=0.001):\n        ncf = Dataset(self.path, 'r')\n        bandnum = OLCI_BAND_NAMES.index(self.bandname)\n        resp = ncf.variables[\n            'mean_spectral_response_function'][bandnum, :]\n        wvl = ncf.variables[\n            'mean_spectral_response_function_wavelength'][bandnum, :] * scale\n        self.rsr = {'wavelength': wvl, 'response': resp}",
    "docstring": "Load the OLCI relative spectral responses"
  },
  {
    "code": "def _get_boolean(self, source, bitarray):\n        raw_value = self._get_raw(source, bitarray)\n        return {\n            source['shortcut']: {\n                'description': source.get('description'),\n                'unit': source.get('unit', ''),\n                'value': True if raw_value else False,\n                'raw_value': raw_value,\n            }\n        }",
    "docstring": "Get boolean value, based on the data in XML"
  },
  {
    "code": "def environment(**kv):\n    added = []\n    changed = {}\n    for key, value in kv.items():\n        if key not in os.environ:\n            added.append(key)\n        else:\n            changed[key] = os.environ[key]\n        os.environ[key] = value\n    yield\n    for key in added:\n        del os.environ[key]\n    for key in changed:\n        os.environ[key] = changed[key]",
    "docstring": "Context manager to run Python code with a modified UNIX process environment.\n\n    All key/value pairs in the keyword arguments are added (or changed, if the\n    key names an existing environmental variable) in the process environment\n    upon entrance into the context. Changes are undone upon exit: added\n    environmental variables are removed from the environment, and those whose\n    value was changed are reset to their pristine value."
  },
  {
    "code": "def update(self, iterable):\n        for pair in pairwise_longest(iterable, fillvalue=_FILL):\n            self._edges.append(pair)\n            self._results = None",
    "docstring": "Update with an ordered iterable of items.\n\n        Args:\n            iterable: An ordered iterable of items. The relative\n               order of the items in this iterable will be respected\n               in the TopoSet (in the absence of cycles)."
  },
  {
    "code": "def get_dict(self, obj, state=None, base_name='View'):\n        return self.get_dict_for_class(class_name=obj.__class__,\n                                       state=obj.state,\n                                       base_name=base_name)",
    "docstring": "The style dict for a view instance."
  },
  {
    "code": "def plot_trajectory(*args, **kwargs):\n    interactive = kwargs.pop('interactive', True)\n    if interactive:\n        plot_trajectory_with_elegans(*args, **kwargs)\n    else:\n        plot_trajectory_with_matplotlib(*args, **kwargs)",
    "docstring": "Generate a plot from received instance of TrajectoryObserver and show it\n    See also plot_trajectory_with_elegans and plot_trajectory_with_matplotlib.\n\n    Parameters\n    ----------\n    obs : TrajectoryObserver\n        TrajectoryObserver to render.\n    interactive : bool, default True\n        Choose a visualizer. If False, show the plot with matplotlib.\n        If True (only available on IPython Notebook), show it with elegans.\n\n    Examples\n    --------\n    >>> plot_trajectory(obs)\n    >>> plot_trajectory(obs, interactive=False)"
  },
  {
    "code": "def addImagePath(new_path):\n    if os.path.exists(new_path):\n        Settings.ImagePaths.append(new_path)\n    elif \"http://\" in new_path or \"https://\" in new_path:\n        request = requests.get(new_path)\n        if request.status_code < 400:\n            Settings.ImagePaths.append(new_path)\n        else:\n            raise OSError(\"Unable to connect to \" + new_path)\n    else:\n        raise OSError(\"File not found: \" + new_path)",
    "docstring": "Convenience function. Adds a path to the list of paths to search for images.\n\n    Can be a URL (but must be accessible)."
  },
  {
    "code": "def _wait(starting_time, first_timestamp, timestamp):\n        target_time = starting_time + (timestamp - first_timestamp)\n        time.sleep(max(target_time - time.time(), 0))",
    "docstring": "Given that the first timestamp in the trace file is\n        ``first_timestamp`` and we started playing back the file at\n        ``starting_time``, block until the current ``timestamp`` should occur."
  },
  {
    "code": "def is_optional(attr):\n    return isinstance(attr.validator, _OptionalValidator) or (attr.default is not None and attr.default is not NOTHING)",
    "docstring": "Helper method to find if an attribute is mandatory\n\n    :param attr:\n    :return:"
  },
  {
    "code": "def shutdown_kernel(self):\n        kernel_id = self.get_kernel_id()\n        if kernel_id:\n            delete_url = self.add_token(url_path_join(self.server_url,\n                                                      'api/kernels/',\n                                                      kernel_id))\n            delete_req = requests.delete(delete_url)\n            if delete_req.status_code != 204:\n                QMessageBox.warning(\n                    self,\n                    _(\"Server error\"),\n                    _(\"The Jupyter Notebook server \"\n                      \"failed to shutdown the kernel \"\n                      \"associated with this notebook. \"\n                      \"If you want to shut it down, \"\n                      \"you'll have to close Spyder.\"))",
    "docstring": "Shutdown the kernel of the client."
  },
  {
    "code": "def newick(self, tree_format=0):\n        \"Returns newick represenation of the tree in its current state.\"\n        if self.treenode.children:\n            features = {\"name\", \"dist\", \"support\", \"height\", \"idx\"}\n            testnode = self.treenode.children[0]\n            extrafeat = {i for i in testnode.features if i not in features}\n            features.update(extrafeat)\n            return self.treenode.write(format=tree_format)",
    "docstring": "Returns newick represenation of the tree in its current state."
  },
  {
    "code": "def compstat(sdat, tstart=None, tend=None):\n    data = sdat.tseries_between(tstart, tend)\n    time = data['t'].values\n    delta_time = time[-1] - time[0]\n    data = data.iloc[:, 1:].values\n    mean = np.trapz(data, x=time, axis=0) / delta_time\n    rms = np.sqrt(np.trapz((data - mean)**2, x=time, axis=0) / delta_time)\n    with open(misc.out_name('statistics.dat'), 'w') as out_file:\n        mean.tofile(out_file, sep=' ', format=\"%10.5e\")\n        out_file.write('\\n')\n        rms.tofile(out_file, sep=' ', format=\"%10.5e\")\n        out_file.write('\\n')",
    "docstring": "Compute statistics from series output by StagYY.\n\n    Create a file 'statistics.dat' containing the mean and standard deviation\n    of each series on the requested time span.\n\n    Args:\n        sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.\n        tstart (float): starting time. Set to None to start at the beginning of\n            available data.\n        tend (float): ending time. Set to None to stop at the end of available\n            data."
  },
  {
    "code": "def process_composite_comment(self, level, comments, key):\n        if key not in comments:\n            comment = \"\"\n        else:\n            value = comments[key]\n            spacer = self.whitespace(level, 0)\n            if isinstance(value, list):\n                comments = [self.format_comment(spacer, v) for v in value]\n                comment = self.newlinechar.join(comments)\n            else:\n                comment = self.format_comment(spacer, value)\n        return comment",
    "docstring": "Process comments for composites such as MAP, LAYER etc."
  },
  {
    "code": "def kappa_se_calc(PA, PE, POP):\n    try:\n        result = math.sqrt((PA * (1 - PA)) / (POP * ((1 - PE)**2)))\n        return result\n    except Exception:\n        return \"None\"",
    "docstring": "Calculate kappa standard error.\n\n    :param PA: observed agreement among raters (overall accuracy)\n    :type PA : float\n    :param PE:  hypothetical probability of chance agreement (random accuracy)\n    :type PE : float\n    :param POP: population\n    :type POP:int\n    :return: kappa standard error as float"
  },
  {
    "code": "def get(postcode):\n    postcode = quote(postcode.replace(' ', ''))\n    url = '%s/postcode/%s.json' % (END_POINT, postcode)\n    return _get_json_resp(url)",
    "docstring": "Request data associated with `postcode`.\n\n    :param postcode: the postcode to search for. The postcode may \n                     contain spaces (they will be removed).\n\n    :returns: a dict of the nearest postcode's data or None if no \n              postcode data is found."
  },
  {
    "code": "def create_payload(self):\n        payload = super(OverrideValue, self).create_payload()\n        if hasattr(self, 'smart_class_parameter'):\n            del payload['smart_class_parameter_id']\n        if hasattr(self, 'smart_variable'):\n            del payload['smart_variable_id']\n        return payload",
    "docstring": "Remove ``smart_class_parameter_id`` or ``smart_variable_id``"
  },
  {
    "code": "def curtailment(self):\n        if self._curtailment is not None:\n            result_dict = {}\n            for key, gen_list in self._curtailment.items():\n                curtailment_df = pd.DataFrame()\n                for gen in gen_list:\n                    curtailment_df[gen] = gen.curtailment\n                result_dict[key] = curtailment_df\n            return result_dict\n        else:\n            return None",
    "docstring": "Holds curtailment assigned to each generator per curtailment target.\n\n        Returns\n        -------\n        :obj:`dict` with :pandas:`pandas.DataFrame<dataframe>`\n            Keys of the dictionary are generator types (and weather cell ID)\n            curtailment targets were given for. E.g. if curtailment is provided\n            as a :pandas:`pandas.DataFrame<dataframe>` with\n            :pandas.`pandas.MultiIndex` columns with levels 'type' and\n            'weather cell ID' the dictionary key is a tuple of\n            ('type','weather_cell_id').\n            Values of the dictionary are dataframes with the curtailed power in\n            kW per generator and time step. Index of the dataframe is a\n            :pandas:`pandas.DatetimeIndex<datetimeindex>`. Columns are the\n            generators of type\n            :class:`edisgo.grid.components.GeneratorFluctuating`."
  },
  {
    "code": "def _init_peewee_ext(cls, app, dummy_configuration=None,\n                         dummy_configure_args=None):\n        if 'DATABASE' not in app.config:\n            app.add_post_configure_callback(partial(cls._init_peewee_ext, app),\n                                            run_once=True)\n            return\n        _PEEWEE_EXT.init_app(app)",
    "docstring": "Init the actual PeeWee extension with the app that was created.\n\n        Since PeeWee requires the ``DATABASE`` config parameter to be present\n        IMMEDIATELY upon initializing the application, we need to delay this\n        construction. This is because, in standard use, we will create the app\n        and attempt to init this extension BEFORE we configure the app, which\n        is totally fine. To fix this, we just need to set this up to try and\n        run after every call to configure. If there is not ``DATABASE`` config\n        parameter present when run, this method does nothing other than\n        reschedule itself to run in the future.\n\n        In all cases, this is a Post Configure Hook that should RUN ONCE!\n\n        Args:\n            app (flask.Flask): The application you want to init the PeeWee\n                Flask extension for. Hint: if you need to use this as\n                a callback, use a partial to provide this.\n            dummy_configuration (dict): The resulting application configuration\n                that the post_configure hook provides to all of it's callbacks.\n                We will NEVER use this, but since we utilize the post_configure\n                system to register this for complicated apps, we gotta accept\n                it.\n            dummy_configure_args (list[object]): The args passed to the\n                :meth:`configure` function that triggered this callback. Just\n                like the above arg, we'll never use it, but we must accept it."
  },
  {
    "code": "def similarity_by_path(sense1: \"wn.Synset\", sense2: \"wn.Synset\", option: str = \"path\") -> float:\n    if option.lower() in [\"path\", \"path_similarity\"]:\n        return max(wn.path_similarity(sense1, sense2, if_none_return=0),\n                   wn.path_similarity(sense2, sense1, if_none_return=0))\n    elif option.lower() in [\"wup\", \"wupa\", \"wu-palmer\", \"wu-palmer\"]:\n        return max(wn.wup_similarity(sense1, sense2, if_none_return=0),\n                   wn.wup_similarity(sense2, sense1, if_none_return=0))\n    elif option.lower() in ['lch', \"leacock-chordorow\"]:\n        if sense1.pos != sense2.pos:\n            return 0\n        return wn.lch_similarity(sense1, sense2, if_none_return=0)",
    "docstring": "Returns maximum path similarity between two senses.\n\n    :param sense1: A synset.\n    :param sense2: A synset.\n    :param option: String, one of ('path', 'wup', 'lch').\n    :return: A float, similarity measurement."
  },
  {
    "code": "def _internal_reschedule(callback, retry=3, sleep_time=constants.DEFAULT_SLEEP):\n        for foo in range(retry):\n            container_process = callback[0](callback[1], *callback[2], **callback[3])\n            time.sleep(sleep_time)\n            container_process.poll()\n            rcode = container_process.returncode\n            if rcode is None:\n                return container_process\n        raise ConuException(\"Unable to start nspawn container - process failed for {}-times\".format(retry))",
    "docstring": "workaround method for internal_run_container method\n        It sometimes fails because of Dbus or whatever, so try to start it moretimes\n\n        :param callback: callback method list\n        :param retry: how many times try to invoke command\n        :param sleep_time: how long wait before subprocess.poll() to find if it failed\n        :return: subprocess object"
  },
  {
    "code": "def create_pos(self, name, pos_type,\n                   pos_id, location=None):\n        arguments = {'name': name,\n                     'type': pos_type,\n                     'id': pos_id,\n                     'location': location}\n        return self.do_req('POST', self.merchant_api_base_url + '/pos/', arguments).json()",
    "docstring": "Create POS resource\n\n        Arguments:\n            name:\n                Human-readable name of the POS, used for displaying payment\n                request origin to end user\n            pos_type:\n                POS type\n            location:\n                Merchant location\n            pos_id:\n                The ID of the POS that is to be created. Has to be unique for\n                the merchant"
  },
  {
    "code": "def verify_response(self, response_json, signed_id_name='transactionid'):\n        auth_json = response_json.get('auth', {})\n        nonce = auth_json.get('nonce', '')\n        timestamp = auth_json.get('timestamp', '')\n        signature = binascii.unhexlify(auth_json.get('signature', ''))\n        signed_id = response_json.get(signed_id_name, '')\n        return self.verify_signature(signature=signature, nonce=nonce, timestamp=timestamp, signed_id=signed_id)",
    "docstring": "Verify the response message.\n\n        :param response_json: \n        :param signed_id_name: \n        :return:"
  },
  {
    "code": "def append_sample(self, v, vartype, _left=False):\n        vstr = str(v).rjust(2)\n        length = len(vstr)\n        if vartype is dimod.SPIN:\n            def f(datum):\n                return _spinstr(datum.sample[v], rjust=length)\n        else:\n            def f(datum):\n                return _binarystr(datum.sample[v], rjust=length)\n        self.append(vstr, f, _left=_left)",
    "docstring": "Add a sample column"
  },
  {
    "code": "def _populate_common_request(self, request):\n        url_record = self._item_session.url_record\n        if url_record.parent_url and not request.fields.get('Referer'):\n            self._add_referrer(request, url_record)\n        if self._fetch_rule.http_login:\n            request.username, request.password = self._fetch_rule.http_login",
    "docstring": "Populate the Request with common fields."
  },
  {
    "code": "def do_selection_reduction_to_one_parent(selection):\n        all_models_selected = selection.get_all()\n        parent_m_count_dict = {}\n        for model in all_models_selected:\n            parent_m_count_dict[model.parent] = parent_m_count_dict[model.parent] + 1 if model.parent in parent_m_count_dict else 1\n        parent_m = None\n        current_count_parent = 0\n        for possible_parent_m, count in parent_m_count_dict.items():\n            parent_m = possible_parent_m if current_count_parent < count else parent_m\n        if len(selection.states) == 1 and selection.get_selected_state().state.is_root_state:\n            parent_m = None\n            if len(all_models_selected) > 1:\n                selection.set(selection.get_selected_state())\n        if parent_m is not None:\n            for model in all_models_selected:\n                if model.parent is not parent_m:\n                    selection.remove(model)\n        return parent_m",
    "docstring": "Find and reduce selection to one parent state.\n\n        :param selection:\n        :return: state model which is parent of selection or None if root state"
  },
  {
    "code": "def select_radio_button(self, key):\n        key_index = list(self._parameter.options.keys()).index(key)\n        radio_button = self.input_button_group.button(key_index)\n        radio_button.click()",
    "docstring": "Helper to select a radio button with key.\n\n        :param key: The key of the radio button.\n        :type key: str"
  },
  {
    "code": "def setArticleThreshold(self, value):\n        assert isinstance(value, int)\n        assert value >= 0\n        self.topicPage[\"articleTreshWgt\"] = value",
    "docstring": "what is the minimum total weight that an article has to have in order to get it among the results?\n        @param value: threshold to use"
  },
  {
    "code": "def top(self, num, key=None):\n        def topIterator(iterator):\n            yield heapq.nlargest(num, iterator, key=key)\n        def merge(a, b):\n            return heapq.nlargest(num, a + b, key=key)\n        return self.mapPartitions(topIterator).reduce(merge)",
    "docstring": "Get the top N elements from an RDD.\n\n        .. note:: This method should only be used if the resulting array is expected\n            to be small, as all the data is loaded into the driver's memory.\n\n        .. note:: It returns the list sorted in descending order.\n\n        >>> sc.parallelize([10, 4, 2, 12, 3]).top(1)\n        [12]\n        >>> sc.parallelize([2, 3, 4, 5, 6], 2).top(2)\n        [6, 5]\n        >>> sc.parallelize([10, 4, 2, 12, 3]).top(3, key=str)\n        [4, 3, 2]"
  },
  {
    "code": "def has_child_banks(self, bank_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.has_child_catalogs(catalog_id=bank_id)\n        return self._hierarchy_session.has_children(id_=bank_id)",
    "docstring": "Tests if a bank has any children.\n\n        arg:    bank_id (osid.id.Id): a ``bank_id``\n        return: (boolean) - ``true`` if the ``bank_id`` has children,\n                ``false`` otherwise\n        raise:  NotFound - ``bank_id`` is not found\n        raise:  NullArgument - ``bank_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def __init_configsvrs(self, params):\n        self._configsvrs = []\n        for cfg in params:\n            cfg = self._strip_auth(cfg)\n            server_id = cfg.pop('server_id', None)\n            version = cfg.pop('version', self._version)\n            cfg.update({'configsvr': True})\n            if self.enable_ipv6:\n                common.enable_ipv6_single(cfg)\n            self._configsvrs.append(Servers().create(\n                'mongod', cfg, sslParams=self.sslParams, autostart=True,\n                version=version, server_id=server_id))",
    "docstring": "create and start config servers"
  },
  {
    "code": "def shlex_split(s, **kwargs):\n    if isinstance(s, six.string_types):\n        return salt.utils.data.decode(\n            shlex.split(salt.utils.stringutils.to_str(s), **kwargs)\n        )\n    else:\n        return s",
    "docstring": "Only split if variable is a string"
  },
  {
    "code": "def recursive_cov(self, cov, length, mean, chain, scaling=1, epsilon=0):\n        r\n        n = length + len(chain)\n        k = length\n        new_mean = self.recursive_mean(mean, length, chain)\n        t0 = k * np.outer(mean, mean)\n        t1 = np.dot(chain.T, chain)\n        t2 = n * np.outer(new_mean, new_mean)\n        t3 = epsilon * np.eye(cov.shape[0])\n        new_cov = (\n            k - 1) / (\n                n - 1.) * cov + scaling / (\n                    n - 1.) * (\n                        t0 + t1 - t2 + t3)\n        return new_cov, new_mean",
    "docstring": "r\"\"\"Compute the covariance recursively.\n\n        Return the new covariance and the new mean.\n\n        .. math::\n            C_k & = \\frac{1}{k-1} (\\sum_{i=1}^k x_i x_i^T - k\\bar{x_k}\\bar{x_k}^T)\n            C_n & = \\frac{1}{n-1} (\\sum_{i=1}^k x_i x_i^T + \\sum_{i=k+1}^n x_i x_i^T - n\\bar{x_n}\\bar{x_n}^T)\n                & = \\frac{1}{n-1} ((k-1)C_k + k\\bar{x_k}\\bar{x_k}^T + \\sum_{i=k+1}^n x_i x_i^T - n\\bar{x_n}\\bar{x_n}^T)\n\n        :Parameters:\n            -  cov : matrix\n                Previous covariance matrix.\n            -  length : int\n                Length of chain used to compute the previous covariance.\n            -  mean : array\n                Previous mean.\n            -  chain : array\n                Sample used to update covariance.\n            -  scaling : float\n                Scaling parameter\n            -  epsilon : float\n                Set to a small value to avoid singular matrices."
  },
  {
    "code": "def line(self, text=''):\n        self.out.write(text)\n        self.out.write('\\n')",
    "docstring": "A simple helper to write line with `\\n`"
  },
  {
    "code": "def participant_names(self):\n        with self._mutex:\n            return [obj.get_component_profile().instance_name \\\n                    for obj in self._participants]",
    "docstring": "The names of the RTObjects participating in this context."
  },
  {
    "code": "def dict_has_any_keys(self, keys):\n        if not _is_non_string_iterable(keys):\n            keys = [keys]\n        with cython_context():\n            return SArray(_proxy=self.__proxy__.dict_has_any_keys(keys))",
    "docstring": "Create a boolean SArray by checking the keys of an SArray of\n        dictionaries. An element of the output SArray is True if the\n        corresponding input element's dictionary has any of the given keys.\n        Fails on SArrays whose data type is not ``dict``.\n\n        Parameters\n        ----------\n        keys : list\n            A list of key values to check each dictionary against.\n\n        Returns\n        -------\n        out : SArray\n            A SArray of int type, where each element indicates whether the\n            input SArray element contains any key in the input list.\n\n        See Also\n        --------\n        dict_has_all_keys\n\n        Examples\n        --------\n        >>> sa = turicreate.SArray([{\"this\":1, \"is\":5, \"dog\":7}, {\"animal\":1},\n                                 {\"this\": 2, \"are\": 1, \"cat\": 5}])\n        >>> sa.dict_has_any_keys([\"is\", \"this\", \"are\"])\n        dtype: int\n        Rows: 3\n        [1, 0, 1]"
  },
  {
    "code": "def _read_page_header(file_obj):\n    tin = TFileTransport(file_obj)\n    pin = TCompactProtocolFactory().get_protocol(tin)\n    page_header = parquet_thrift.PageHeader()\n    page_header.read(pin)\n    return page_header",
    "docstring": "Read the page_header from the given fo."
  },
  {
    "code": "def log(message, type):\n    (sys.stdout if type == 'notice' else sys.stderr).write(message + \"\\n\")",
    "docstring": "Log notices to stdout and errors to stderr"
  },
  {
    "code": "def create_identity(user_id, curve_name):\n    result = interface.Identity(identity_str='gpg://', curve_name=curve_name)\n    result.identity_dict['host'] = user_id\n    return result",
    "docstring": "Create GPG identity for hardware device."
  },
  {
    "code": "def _reset(self, command, *args, **kwargs):\n        if self.indexable:\n            self.deindex()\n        result = self._traverse_command(command, *args, **kwargs)\n        if self.indexable:\n            self.index()\n        return result",
    "docstring": "Shortcut for commands that reset values of the field.\n        All will be deindexed and reindexed."
  },
  {
    "code": "def time_coef(tc, nc, tb, nb):\n    tc = float(tc)\n    nc = float(nc)\n    tb = float(tb)\n    nb = float(nb)\n    q = (tc * nb) / (tb * nc)\n    return q",
    "docstring": "Return time coefficient relative to base numbers.\n    @param  tc:     current test time\n    @param  nc:     current test data size\n    @param  tb:     base test time\n    @param  nb:     base test data size\n    @return:        time coef."
  },
  {
    "code": "def get_exitstatus(self):\n        logger.debug(\"Exit status is {0}\".format(self._spawn.exitstatus))\n        return self._spawn.exitstatus",
    "docstring": "Get the exit status of the program execution.\n\n        Returns:\n            int: Exit status as reported by the operating system,\n                 or None if it is not available."
  },
  {
    "code": "def SensorDataDelete(self, sensor_id, data_id):\r\n        if self.__SenseApiCall__('/sensors/{0}/data/{1}.json'.format(sensor_id, data_id), 'DELETE'):\r\n            return True\r\n        else:\r\n            self.__error_ = \"api call unsuccessful\"\r\n            return False",
    "docstring": "Delete a sensor datum from a specific sensor in CommonSense.\r\n            \r\n            @param sensor_id (int) - Sensor id of the sensor to delete data from\r\n            @param data_id (int) - Id of the data point to delete\r\n            \r\n            @return (bool) - Boolean indicating whether SensorDataDelete was successful."
  },
  {
    "code": "def _node_info(conn):\n    raw = conn.getInfo()\n    info = {'cpucores': raw[6],\n            'cpumhz': raw[3],\n            'cpumodel': six.text_type(raw[0]),\n            'cpus': raw[2],\n            'cputhreads': raw[7],\n            'numanodes': raw[4],\n            'phymemory': raw[1],\n            'sockets': raw[5]}\n    return info",
    "docstring": "Internal variant of node_info taking a libvirt connection as parameter"
  },
  {
    "code": "def convert_values(self, matchdict: Dict[str, str]) -> Dict[str, Any]:\n        converted = {}\n        for varname, value in matchdict.items():\n            converter = self.converters[varname]\n            converted[varname] = converter(value)\n        return converted",
    "docstring": "convert values of ``matchdict``\n        with converter this object has."
  },
  {
    "code": "def max_brightness(self):\n        status_filename = os.path.join(self.path, 'max_brightness')\n        with open(status_filename) as status_fp:\n            result = status_fp.read()\n        status_text = result.strip()\n        try:\n            status = int(status_text)\n        except ValueError:\n            return status_text\n        return status",
    "docstring": "Get the device's maximum brightness level."
  },
  {
    "code": "def assign_value(self, comp_def, value, src_ref):\n        super().assign_value(comp_def, value, src_ref)\n        if \"rclr\" in comp_def.properties:\n            del comp_def.properties[\"rclr\"]\n        if \"rset\" in comp_def.properties:\n            del comp_def.properties[\"rset\"]",
    "docstring": "Overrides other related properties"
  },
  {
    "code": "def _schema_from_verb(verb, partial=False):\n    from .verbs import Verbs\n    return getattr(Verbs, verb)(partial=partial)",
    "docstring": "Return an instance of schema for given verb."
  },
  {
    "code": "def is_valid_callsign(self, callsign, timestamp=timestamp_now):\n        try:\n            if self.get_all(callsign, timestamp):\n                return True\n        except KeyError:\n            return False",
    "docstring": "Checks if a callsign is valid\n\n        Args:\n            callsign (str): Amateur Radio callsign\n            timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)\n\n        Returns:\n            bool: True / False\n\n        Example:\n            The following checks if \"DH1TW\" is a valid callsign\n\n            >>> from pyhamtools import LookupLib, Callinfo\n            >>> my_lookuplib = LookupLib(lookuptype=\"countryfile\")\n            >>> cic = Callinfo(my_lookuplib)\n            >>> cic.is_valid_callsign(\"DH1TW\")\n            True"
  },
  {
    "code": "def convert_bytes_to_ints(in_bytes, num):\n    dt = numpy.dtype('>i' + str(num))\n    return numpy.frombuffer(in_bytes, dt)",
    "docstring": "Convert a byte array into an integer array. The number of bytes forming an integer\n    is defined by num\n\n    :param in_bytes: the input bytes\n    :param num: the number of bytes per int\n    :return the integer array"
  },
  {
    "code": "def update(self):\n        if 'id' in self._bug:\n            result = self._bugsy.request('bug/%s' % self._bug['id'])\n            self._bug = dict(**result['bugs'][0])\n        else:\n            raise BugException(\"Unable to update bug that isn't in Bugzilla\")",
    "docstring": "Update this object with the latest changes from Bugzilla\n\n            >>> bug.status\n            'NEW'\n            #Changes happen on Bugzilla\n            >>> bug.update()\n            >>> bug.status\n            'FIXED'"
  },
  {
    "code": "def _set_align(self, orientation, value):\n        orientation_letter = orientation[0]\n        possible_alignments = getattr(\n            self, '_possible_{}aligns'.format(orientation_letter))\n        all_alignments = getattr(\n            self, '_all_{}aligns'.format(orientation_letter))\n        if value not in possible_alignments:\n            if value in all_alignments:\n                msg = 'non-permitted'\n            else:\n                msg = 'non-existant'\n            raise ValueError(\n                \"Can't set {} {} alignment {!r} on element {!r}\".format(\n                    msg, orientation, value, self))\n        setattr(self, '_{}align'.format(orientation_letter), value)",
    "docstring": "We define a setter because it's better to diagnose this kind of\n        programmatic error here than have to work out why alignment is odd when\n        we sliently fail!"
  },
  {
    "code": "def get_resources_by_bin(self, bin_id):\n        mgr = self._get_provider_manager('RESOURCE', local=True)\n        lookup_session = mgr.get_resource_lookup_session_for_bin(bin_id, proxy=self._proxy)\n        lookup_session.use_isolated_bin_view()\n        return lookup_session.get_resources()",
    "docstring": "Gets the list of ``Resources`` associated with a ``Bin``.\n\n        arg:    bin_id (osid.id.Id): ``Id`` of a ``Bin``\n        return: (osid.resource.ResourceList) - list of related resources\n        raise:  NotFound - ``bin_id`` is not found\n        raise:  NullArgument - ``bin_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def from_dict(self, d):\n        self.length = d.get(\"length\", 0)\n        self.instanceHigh = d.get(\"instanceHigh\", 0)\n        self.instanceMid = d.get(\"instanceMid\", 0)\n        self.instanceLow = d.get(\"instanceLow\", 0)\n        material = d.get(\"material\", {'Data1':0, 'Data2':0, 'Data3':0, 'Data4': [0 for i in range(8)]})\n        self.Data1 = material.get('Data1', 0)\n        self.Data2 = material.get('Data2', 0)\n        self.Data3 = material.get('Data3', 0)\n        self.Data4 = material.get(\"Data4\", [0 for i in range(8)])\n        self.SMPTELabel = d.get(\"SMPTELabel\", [0 for i in range(12)])",
    "docstring": "Set MobID from a dict"
  },
  {
    "code": "def set_connection(self, service_name, to_cache):\n        self.services.setdefault(service_name, {})\n        self.services[service_name]['connection'] = to_cache",
    "docstring": "Sets a connection class within the cache.\n\n        :param service_name: The service a given ``Connection`` talks to. Ex.\n            ``sqs``, ``sns``, ``dynamodb``, etc.\n        :type service_name: string\n\n        :param to_cache: The class to be cached for the service.\n        :type to_cache: class"
  },
  {
    "code": "def _update_items(self, items):\n        self.items = items\n        self.map = {item: idx for (idx, item) in enumerate(items)}",
    "docstring": "Replace the 'items' list of this OrderedSet with a new one, updating\n        self.map accordingly."
  },
  {
    "code": "def blob_counter(self):\n        import aa\n        from ROOT import EventFile\n        try:\n            event_file = EventFile(self.filename)\n        except Exception:\n            raise SystemExit(\"Could not open file\")\n        num_blobs = 0\n        for event in event_file:\n            num_blobs += 1\n        return num_blobs",
    "docstring": "Create a blob counter."
  },
  {
    "code": "def getOriginLocalizedName(self, origin, pchNameArray, unNameArraySize, unStringSectionsToInclude):\n        fn = self.function_table.getOriginLocalizedName\n        result = fn(origin, pchNameArray, unNameArraySize, unStringSectionsToInclude)\n        return result",
    "docstring": "Retrieves the name of the origin in the current language. unStringSectionsToInclude is a bitfield of values in EVRInputStringBits that allows the \n        application to specify which parts of the origin's information it wants a string for."
  },
  {
    "code": "def styled_plot(*style_sheets):\n    def decorator(get_plot):\n        def wrapper(*args, fonts=None, style=None, no_base_style=False,\n                    **kwargs):\n            if no_base_style:\n                list_style = []\n            else:\n                list_style = list(style_sheets)\n            if style is not None:\n                if isinstance(style, list):\n                    list_style += style\n                else:\n                    list_style += [style]\n            if fonts is not None:\n                list_style += [{'font.family': 'sans-serif',\n                               'font.sans-serif': fonts}]\n            matplotlib.pyplot.style.use(list_style)\n            return get_plot(*args, **kwargs)\n        return wrapper\n    return decorator",
    "docstring": "Return a decorator that will apply matplotlib style sheets to a plot.\n\n    ``style_sheets`` is a base set of styles, which will be ignored if\n    ``no_base_style`` is set in the decorated function arguments.\n\n    The style will further be overwritten by any styles in the ``style``\n    optional argument of the decorated function.\n\n    Args:\n        style_sheets (:obj:`list`, :obj:`str`, or :obj:`dict`): Any matplotlib\n            supported definition of a style sheet. Can be a list of style of\n            style sheets."
  },
  {
    "code": "def getpart(self, ix):\r\n        if self.offsets[ix] == 0:\r\n            return\r\n        comp, ofs, size, checksum = self.getsectioninfo(ix)\r\n        fh = FileSection(self.fh, ofs, ofs + size)\r\n        if comp == 2:\r\n            import zlib\r\n            wbits = -15 if self.magic == 'IDA0' else 15\r\n            fh = makeStringIO(zlib.decompress(fh.read(size), wbits))\r\n        elif comp == 0:\r\n            pass\r\n        else:\r\n            raise Exception(\"unsupported section encoding: %02x\" % comp)\r\n        return fh",
    "docstring": "Returns a fileobject for the specified section.\r\n\r\n        This method optionally decompresses the data found in the .idb file,\r\n        and returns a file-like object, with seek, read, tell."
  },
  {
    "code": "def text2html_table(items:Collection[Collection[str]])->str:\n    \"Put the texts in `items` in an HTML table, `widths` are the widths of the columns in %.\"\n    html_code = f\n    html_code += f\n    for i in items[0]: html_code += f\"      <th>{_treat_html(i)}</th>\"\n    html_code += f\"    </tr>\\n  </thead>\\n  <tbody>\"\n    html_code += \"  <tbody>\"\n    for line in items[1:]:\n        html_code += \"    <tr>\"\n        for i in line: html_code += f\"      <td>{_treat_html(i)}</td>\"\n        html_code += \"    </tr>\"\n    html_code += \"  </tbody>\\n</table>\"\n    return html_code",
    "docstring": "Put the texts in `items` in an HTML table, `widths` are the widths of the columns in %."
  },
  {
    "code": "def parse_url(arg, extract, key=None):\n    return ops.ParseURL(arg, extract, key).to_expr()",
    "docstring": "Returns the portion of a URL corresponding to a part specified\n    by 'extract'\n    Can optionally specify a key to retrieve an associated value\n    if extract parameter is 'QUERY'\n\n    Parameters\n    ----------\n    extract : one of {'PROTOCOL', 'HOST', 'PATH', 'REF',\n                'AUTHORITY', 'FILE', 'USERINFO', 'QUERY'}\n    key : string (optional)\n\n    Examples\n    --------\n    >>> url = \"https://www.youtube.com/watch?v=kEuEcWfewf8&t=10\"\n    >>> parse_url(url, 'QUERY', 'v')  # doctest: +SKIP\n    'kEuEcWfewf8'\n\n    Returns\n    -------\n    extracted : string"
  },
  {
    "code": "def add_to_cart(item_id):\n    cart = Cart(session['cart'])\n    if cart.change_item(item_id, 'add'):\n        session['cart'] = cart.to_dict()\n    return list_products()",
    "docstring": "Cart with Product"
  },
  {
    "code": "def apply(self, p_todolist, p_archive):\n        if self.todolist and p_todolist:\n            p_todolist.replace(self.todolist.todos())\n        if self.archive and p_archive:\n            p_archive.replace(self.archive.todos())",
    "docstring": "Applies backup on supplied p_todolist."
  },
  {
    "code": "def addFilter(self, filterclass):\n        if filterclass not in self.filters:\n            self.filters.append(filterclass)",
    "docstring": "Add a filter class to the parser."
  },
  {
    "code": "def micros_to_timestamp(micros, timestamp):\n  seconds = long(micros / _MICROS_PER_SECOND)\n  micro_remainder = micros % _MICROS_PER_SECOND\n  timestamp.seconds = seconds\n  timestamp.nanos = micro_remainder * _NANOS_PER_MICRO",
    "docstring": "Convert microseconds from utc epoch to google.protobuf.timestamp.\n\n  Args:\n    micros: a long, number of microseconds since utc epoch.\n    timestamp: a google.protobuf.timestamp.Timestamp to populate."
  },
  {
    "code": "def parse(cls, filepath, filecontent, parser):\n    try:\n      objects = parser.parse(filepath, filecontent)\n    except Exception as e:\n      raise MappingError('Failed to parse {}:\\n{}'.format(filepath, e))\n    objects_by_name = {}\n    for obj in objects:\n      if not Serializable.is_serializable(obj):\n        raise UnaddressableObjectError('Parsed a non-serializable object: {!r}'.format(obj))\n      attributes = obj._asdict()\n      name = attributes.get('name')\n      if not name:\n        raise UnaddressableObjectError('Parsed a non-addressable object: {!r}'.format(obj))\n      if name in objects_by_name:\n        raise DuplicateNameError('An object already exists at {!r} with name {!r}: {!r}.  Cannot '\n                                 'map {!r}'.format(filepath, name, objects_by_name[name], obj))\n      objects_by_name[name] = obj\n    return cls(filepath, OrderedDict(sorted(objects_by_name.items())))",
    "docstring": "Parses a source for addressable Serializable objects.\n\n    No matter the parser used, the parsed and mapped addressable objects are all 'thin'; ie: any\n    objects they point to in other namespaces or even in the same namespace but from a seperate\n    source are left as unresolved pointers.\n\n    :param string filepath: The path to the byte source containing serialized objects.\n    :param string filecontent: The content of byte source containing serialized objects to be parsed.\n    :param symbol_table: The symbol table cls to expose a symbol table dict.\n    :type symbol_table: Instance of :class:`pants.engine.parser.SymbolTable`.\n    :param parser: The parser cls to use.\n    :type parser: A :class:`pants.engine.parser.Parser`."
  },
  {
    "code": "def get_pulls_list(project, auth=False, **params):\n    params.setdefault(\"state\", \"closed\")\n    url = \"https://api.github.com/repos/{project}/pulls\".format(project=project)\n    if auth:\n        headers = make_auth_header()\n    else:\n        headers = None\n    pages = get_paged_request(url, headers=headers, **params)\n    return pages",
    "docstring": "get pull request list"
  },
  {
    "code": "def valid_words_set(path_to_user_dictionary=None,\n                    user_dictionary_words=None):\n    def read_file(binary_file):\n        return binary_file.read().decode(\"ascii\").splitlines()\n    try:\n        valid = _valid_words_cache[path_to_user_dictionary]\n        return valid\n    except KeyError:\n        words = set()\n        with resource_stream(\"polysquarelinter\", \"en_US.txt\") as words_file:\n            words |= set([\"\".join(l).lower() for l in read_file(words_file)])\n        if path_to_user_dictionary:\n            words |= set([w.lower() for w in user_dictionary_words])\n            words |= user_dictionary_words\n        _valid_words_cache[path_to_user_dictionary] = words\n        return words",
    "docstring": "Get a set of valid words.\n\n    If :path_to_user_dictionary: is specified, then the newline-separated\n    words in that file will be added to the word set."
  },
  {
    "code": "def create_or_update_group_alias(self, name, alias_id=None, mount_accessor=None, canonical_id=None, mount_point=DEFAULT_MOUNT_POINT):\n        params = {\n            'name': name,\n            'mount_accessor': mount_accessor,\n            'canonical_id': canonical_id,\n        }\n        if alias_id is not None:\n            params['id'] = alias_id\n        api_path = '/v1/{mount_point}/group-alias'.format(mount_point=mount_point)\n        response = self._adapter.post(\n            url=api_path,\n            json=params,\n        )\n        return response.json()",
    "docstring": "Creates or update a group alias.\n\n        Supported methods:\n            POST: /{mount_point}/group-alias. Produces: 200 application/json\n\n        :param alias_id: ID of the group alias. If set, updates the corresponding existing group alias.\n        :type alias_id: str | unicode\n        :param name: Name of the group alias.\n        :type name: str | unicode\n        :param mount_accessor: Mount accessor to which this alias belongs to\n        :type mount_accessor: str | unicode\n        :param canonical_id: ID of the group to which this is an alias.\n        :type canonical_id: str | unicode\n        :param mount_point: The \"path\" the method/backend was mounted on.\n        :type mount_point: str | unicode\n        :return: The JSON response of the request.\n        :rtype: requests.Response"
  },
  {
    "code": "def rewrite_elife_references_json(json_content, doi):\n    references_rewrite_json = elife_references_rewrite_json()\n    if doi in references_rewrite_json:\n        json_content = rewrite_references_json(json_content, references_rewrite_json[doi])\n    if doi == \"10.7554/eLife.12125\":\n        for i, ref in enumerate(json_content):\n            if ref.get(\"id\") and ref.get(\"id\") == \"bib11\":\n                del json_content[i]\n    return json_content",
    "docstring": "this does the work of rewriting elife references json"
  },
  {
    "code": "def main():\n    with open(FILENAME, \"r\") as file_obj:\n        contents = file_obj.read()\n    desired = get_desired()\n    if contents == EXPECTED:\n        with open(FILENAME, \"w\") as file_obj:\n            file_obj.write(desired)\n    elif contents != desired:\n        raise ValueError(\"Unexpected contents\", contents, \"Expected\", EXPECTED)",
    "docstring": "Main entry point to replace autogenerated contents.\n\n    Raises:\n        ValueError: If the file doesn't contain the expected or\n            desired contents."
  },
  {
    "code": "def environment_session_path(cls, project, environment, user, session):\n        return google.api_core.path_template.expand(\n            'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}',\n            project=project,\n            environment=environment,\n            user=user,\n            session=session,\n        )",
    "docstring": "Return a fully-qualified environment_session string."
  },
  {
    "code": "def sas_logical_interconnects(self):\n        if not self.__sas_logical_interconnects:\n            self.__sas_logical_interconnects = SasLogicalInterconnects(self.__connection)\n        return self.__sas_logical_interconnects",
    "docstring": "Gets the SasLogicalInterconnects API client.\n\n        Returns:\n            SasLogicalInterconnects:"
  },
  {
    "code": "def setTimeout(self, time):\n        self.conversation.SetDDETimeout(round(time))\n        return self.conversation.GetDDETimeout()",
    "docstring": "Set global timeout value, in seconds, for all DDE calls"
  },
  {
    "code": "def querying_context(self, packet_type):\n        if self.set_state(tds_base.TDS_QUERYING) != tds_base.TDS_QUERYING:\n            raise tds_base.Error(\"Couldn't switch to state\")\n        self._writer.begin_packet(packet_type)\n        try:\n            yield\n        except:\n            if self.state != tds_base.TDS_DEAD:\n                self.set_state(tds_base.TDS_IDLE)\n            raise\n        else:\n            self.set_state(tds_base.TDS_PENDING)\n            self._writer.flush()",
    "docstring": "Context manager for querying.\n\n        Sets state to TDS_QUERYING, and reverts it to TDS_IDLE if exception happens inside managed block,\n        and to TDS_PENDING if managed block succeeds and flushes buffer."
  },
  {
    "code": "def predict(self, features):\n        distances = [self._distance(x) for x in features]\n        class_predict = [np.argmin(d) for d in distances]\n        return self.le.inverse_transform(class_predict)",
    "docstring": "Predict class outputs for an unlabelled feature set"
  },
  {
    "code": "def copy_out(source: Iterable[bytes], dest: io.BytesIO, use_placeholders: bool = False):\n    for line in source:\n        if use_placeholders:\n            if not line.strip():\n                continue\n            if line.startswith(PLACEHOLDER):\n                line = b\"\\n\"\n        dest.write(line)",
    "docstring": "Copy lines from source to destination.\n\n    :param source: Source line iterable.\n    :param dest: Destination open file.\n    :param use_placeholders: When true, convert lines containing placeholders to\n                             empty lines and drop true empty lines (assume to be\n                             spuriously generated)."
  },
  {
    "code": "def clean_proc(proc, wait_for_kill=10):\n    if not proc:\n        return\n    try:\n        waited = 0\n        while proc.is_alive():\n            proc.terminate()\n            waited += 1\n            time.sleep(0.1)\n            if proc.is_alive() and (waited >= wait_for_kill):\n                log.error('Process did not die with terminate(): %s', proc.pid)\n                os.kill(proc.pid, signal.SIGKILL)\n    except (AssertionError, AttributeError):\n        pass",
    "docstring": "Generic method for cleaning up multiprocessing procs"
  },
  {
    "code": "def get_managers(self):\n        if self._single_env:\n            return None\n        if not hasattr(self, '_managers'):\n            self._managers = self.env.get_slave_managers()\n        return self._managers",
    "docstring": "Get managers for the slave environments."
  },
  {
    "code": "def re_balance(self):\n        self.update_heights(recursive=False)\n        self.update_balances(False)\n        while self.balance < -1 or self.balance > 1:\n            if self.balance > 1:\n                if self.node.left.balance < 0:\n                    self.node.left.rotate_left()\n                    self.update_heights()\n                    self.update_balances()\n                self.rotate_right()\n                self.update_heights()\n                self.update_balances()\n            if self.balance < -1:\n                if self.node.right.balance > 0:\n                    self.node.right.rotate_right()\n                    self.update_heights()\n                    self.update_balances()\n                self.rotate_left()\n                self.update_heights()\n                self.update_balances()",
    "docstring": "Re balance tree. After inserting or deleting a node,"
  },
  {
    "code": "def _resolve_call(self, table, column='', value='', **kwargs):\n        if not column:\n            return self.catalog(table)\n        elif not value:\n            return self.catalog(table, column)\n        column = column.upper()\n        value = str(value).upper()\n        data = self.call_api(table, column, value, **kwargs)\n        if isinstance(data, dict):\n            data = data.values()[0]\n        return data",
    "docstring": "Internal method to resolve the API wrapper call."
  },
  {
    "code": "def set_int_attribute(self, target, display_mask, attr, value):\n    reply = NVCtrlSetAttributeAndGetStatusReplyRequest(display=self.display,\n                                                       opcode=self.display.get_extension_major(extname),\n                                                       target_id=target.id(),\n                                                       target_type=target.type(),\n                                                       display_mask=display_mask,\n                                                       attr=attr,\n                                                       value=value)\n    return reply._data.get('flags') != 0",
    "docstring": "Set the value of an integer attribute"
  },
  {
    "code": "def executors(opts, functions=None, context=None, proxy=None):\n    executors = LazyLoader(\n        _module_dirs(opts, 'executors', 'executor'),\n        opts,\n        tag='executor',\n        pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}},\n    )\n    executors.pack['__executors__'] = executors\n    return executors",
    "docstring": "Returns the executor modules"
  },
  {
    "code": "def plot_phi(self, colorbar=True, cb_orientation='vertical',\n                 cb_label='$g_\\phi$, m s$^{-2}$', ax=None, show=True,\n                 fname=None, **kwargs):\n        if ax is None:\n            fig, axes = self.phi.plot(colorbar=colorbar,\n                                      cb_orientation=cb_orientation,\n                                      cb_label=cb_label, show=False, **kwargs)\n            if show:\n                fig.show()\n            if fname is not None:\n                fig.savefig(fname)\n            return fig, axes\n        else:\n            self.phi.plot(colorbar=colorbar, cb_orientation=cb_orientation,\n                          cb_label=cb_label, ax=ax, **kwargs)",
    "docstring": "Plot the phi component of the gravity field.\n\n        Usage\n        -----\n        x.plot_phi([tick_interval, xlabel, ylabel, ax, colorbar,\n                    cb_orientation, cb_label, show, fname, **kwargs])\n\n        Parameters\n        ----------\n        tick_interval : list or tuple, optional, default = [30, 30]\n            Intervals to use when plotting the x and y ticks. If set to None,\n            ticks will not be plotted.\n        xlabel : str, optional, default = 'longitude'\n            Label for the longitude axis.\n        ylabel : str, optional, default = 'latitude'\n            Label for the latitude axis.\n        ax : matplotlib axes object, optional, default = None\n            A single matplotlib axes object where the plot will appear.\n        colorbar : bool, optional, default = True\n            If True, plot a colorbar.\n        cb_orientation : str, optional, default = 'vertical'\n            Orientation of the colorbar: either 'vertical' or 'horizontal'.\n        cb_label : str, optional, default = '$g_\\phi$, m s$^{-2}$'\n            Text label for the colorbar.\n        show : bool, optional, default = True\n            If True, plot the image to the screen.\n        fname : str, optional, default = None\n            If present, and if axes is not specified, save the image to the\n            specified file.\n        kwargs : optional\n            Keyword arguements that will be sent to the SHGrid.plot()\n            and plt.imshow() methods."
  },
  {
    "code": "def exists(self, path, mtime=None):\n        self._connect()\n        if self.sftp:\n            exists = self._sftp_exists(path, mtime)\n        else:\n            exists = self._ftp_exists(path, mtime)\n        self._close()\n        return exists",
    "docstring": "Return `True` if file or directory at `path` exist, False otherwise.\n\n        Additional check on modified time when mtime is passed in.\n\n        Return False if the file's modified time is older mtime."
  },
  {
    "code": "def compare(self, other, r_threshold=1e-3):\n        return compute_rmsd(self.r, other.r) < r_threshold",
    "docstring": "Compare two rotations\n\n           The RMSD of the rotation matrices is computed. The return value\n           is True when the RMSD is below the threshold, i.e. when the two\n           rotations are almost identical."
  },
  {
    "code": "def block_view(request):\n    blocked_ip_list = get_blocked_ips()\n    blocked_username_list = get_blocked_usernames()\n    context = {'blocked_ip_list': blocked_ip_list,\n               'blocked_username_list': blocked_username_list}\n    return render(request, 'defender/admin/blocks.html', context)",
    "docstring": "List the blocked IP and Usernames"
  },
  {
    "code": "def handle_onchain_secretreveal(\n        mediator_state: MediatorTransferState,\n        onchain_secret_reveal: ContractReceiveSecretReveal,\n        channelidentifiers_to_channels: ChannelMap,\n        pseudo_random_generator: random.Random,\n        block_number: BlockNumber,\n) -> TransitionResult[MediatorTransferState]:\n    secrethash = onchain_secret_reveal.secrethash\n    is_valid_reveal = is_valid_secret_reveal(\n        state_change=onchain_secret_reveal,\n        transfer_secrethash=mediator_state.secrethash,\n        secret=onchain_secret_reveal.secret,\n    )\n    if is_valid_reveal:\n        secret = onchain_secret_reveal.secret\n        block_number = onchain_secret_reveal.block_number\n        secret_reveal = set_onchain_secret(\n            state=mediator_state,\n            channelidentifiers_to_channels=channelidentifiers_to_channels,\n            secret=secret,\n            secrethash=secrethash,\n            block_number=block_number,\n        )\n        balance_proof = events_for_balanceproof(\n            channelidentifiers_to_channels=channelidentifiers_to_channels,\n            transfers_pair=mediator_state.transfers_pair,\n            pseudo_random_generator=pseudo_random_generator,\n            block_number=block_number,\n            secret=secret,\n            secrethash=secrethash,\n        )\n        iteration = TransitionResult(mediator_state, secret_reveal + balance_proof)\n    else:\n        iteration = TransitionResult(mediator_state, list())\n    return iteration",
    "docstring": "The secret was revealed on-chain, set the state of all transfers to\n    secret known."
  },
  {
    "code": "def his_from_sql(self, db_name, point):\n        his = self._read_from_sql('select * from \"%s\"' % \"history\", db_name)\n        his.index = his[\"index\"].apply(Timestamp)\n        return his.set_index(\"index\")[point]",
    "docstring": "Retrive point histories from SQL database"
  },
  {
    "code": "def xml(self, operator='set', indent = \"\"):\n        xml = indent + \"<meta id=\\\"\" + self.key + \"\\\"\"\n        if operator != 'set':\n            xml += \" operator=\\\"\" + operator + \"\\\"\"\n        if not self.value:\n            xml += \" />\"\n        else:\n            xml += \">\" + self.value + \"</meta>\"\n        return xml",
    "docstring": "Serialize the metadata field to XML"
  },
  {
    "code": "def _check_len(self, pkt):\n        if len(pkt) % 2:\n            last_chr = pkt[-1]\n            if last_chr <= b'\\x80':\n                return pkt[:-1] + b'\\x00' + last_chr\n            else:\n                return pkt[:-1] + b'\\xff' + chb(orb(last_chr) - 1)\n        else:\n            return pkt",
    "docstring": "Check for odd packet length and pad according to Cisco spec.\n        This padding is only used for checksum computation.  The original\n        packet should not be altered."
  },
  {
    "code": "def _add_warc_action_log(self, path, url):\n        _logger.debug('Adding action log record.')\n        actions = []\n        with open(path, 'r', encoding='utf-8', errors='replace') as file:\n            for line in file:\n                actions.append(json.loads(line))\n        log_data = json.dumps(\n            {'actions': actions},\n            indent=4,\n        ).encode('utf-8')\n        self._action_warc_record = record = WARCRecord()\n        record.set_common_fields('metadata', 'application/json')\n        record.fields['WARC-Target-URI'] = 'urn:X-wpull:snapshot?url={0}' \\\n            .format(wpull.url.percent_encode_query_value(url))\n        record.block_file = io.BytesIO(log_data)\n        self._warc_recorder.set_length_and_maybe_checksums(record)\n        self._warc_recorder.write_record(record)",
    "docstring": "Add the action log to the WARC file."
  },
  {
    "code": "def exists(name, region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    try:\n        conn.get_queue_url(QueueName=name)\n    except botocore.exceptions.ClientError as e:\n        missing_code = 'AWS.SimpleQueueService.NonExistentQueue'\n        if e.response.get('Error', {}).get('Code') == missing_code:\n            return {'result': False}\n        return {'error': __utils__['boto3.get_error'](e)}\n    return {'result': True}",
    "docstring": "Check to see if a queue exists.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_sqs.exists myqueue region=us-east-1"
  },
  {
    "code": "def get_module(name: str) -> typing.Union[types.ModuleType, None]:\n    return sys.modules.get(name)",
    "docstring": "Retrieves the loaded module for the given module name or returns None if\n    no such module has been loaded.\n\n    :param name:\n        The name of the module to be retrieved\n    :return:\n        Either the loaded module with the specified name, or None if no such\n        module has been imported."
  },
  {
    "code": "def VerifyStructure(self, parser_mediator, line):\n    self._last_month = 0\n    self._year_use = parser_mediator.GetEstimatedYear()\n    key = 'header'\n    try:\n      structure = self._MAC_WIFI_HEADER.parseString(line)\n    except pyparsing.ParseException:\n      structure = None\n    if not structure:\n      key = 'turned_over_header'\n      try:\n        structure = self._MAC_WIFI_TURNED_OVER_HEADER.parseString(line)\n      except pyparsing.ParseException:\n        structure = None\n    if not structure:\n      logger.debug('Not a Mac Wifi log file')\n      return False\n    time_elements_tuple = self._GetTimeElementsTuple(key, structure)\n    try:\n      dfdatetime_time_elements.TimeElementsInMilliseconds(\n          time_elements_tuple=time_elements_tuple)\n    except ValueError:\n      logger.debug(\n          'Not a Mac Wifi log file, invalid date and time: {0!s}'.format(\n              structure.date_time))\n      return False\n    self._last_month = time_elements_tuple[1]\n    return True",
    "docstring": "Verify that this file is a Mac Wifi log file.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      line (str): line from a text file.\n\n    Returns:\n      bool: True if the line is in the expected format, False if not."
  },
  {
    "code": "def version_from_frame(frame):\n    module = getmodule(frame)\n    if module is None:\n        s = \"<unknown from {0}:{1}>\"\n        return s.format(frame.f_code.co_filename, frame.f_lineno)\n    module_name = module.__name__\n    variable = \"AUTOVERSION_{}\".format(module_name.upper())\n    override = os.environ.get(variable, None)\n    if override is not None:\n        return override\n    while True:\n        try:\n            get_distribution(module_name)\n        except DistributionNotFound:\n            module_name, dot, _ = module_name.partition(\".\")\n            if dot == \"\":\n                break\n        else:\n            return getversion(module_name)\n    return None",
    "docstring": "Given a ``frame``, obtain the version number of the module running there."
  },
  {
    "code": "def merge_versioned(releases, schema=None, merge_rules=None):\n    if not merge_rules:\n        merge_rules = get_merge_rules(schema)\n    merged = OrderedDict()\n    for release in sorted(releases, key=lambda release: release['date']):\n        release = release.copy()\n        ocid = release.pop('ocid')\n        merged[('ocid',)] = ocid\n        releaseID = release['id']\n        date = release['date']\n        tag = release.pop('tag', None)\n        flat = flatten(release, merge_rules)\n        processed = process_flattened(flat)\n        for key, value in processed.items():\n            if key in merged and value == merged[key][-1]['value']:\n                continue\n            if key not in merged:\n                merged[key] = []\n            merged[key].append(OrderedDict([\n                ('releaseID', releaseID),\n                ('releaseDate', date),\n                ('releaseTag', tag),\n                ('value', value),\n            ]))\n    return unflatten(merged, merge_rules)",
    "docstring": "Merges a list of releases into a versionedRelease."
  },
  {
    "code": "def apply_init(m, init_func:LayerFunc):\n    \"Initialize all non-batchnorm layers of `m` with `init_func`.\"\n    apply_leaf(m, partial(cond_init, init_func=init_func))",
    "docstring": "Initialize all non-batchnorm layers of `m` with `init_func`."
  },
  {
    "code": "def get_min_distance(element):\n    try:\n        from scipy.spatial.distance import pdist\n        return pdist(element.array([0, 1])).min()\n    except:\n        return _get_min_distance_numpy(element)",
    "docstring": "Gets the minimum sampling distance of the x- and y-coordinates\n    in a grid."
  },
  {
    "code": "def write_spo(sub, prd, obj):\n    rcvtriples.append(make_spo(sub, prd, obj))",
    "docstring": "write triples to a buffer incase we decide to drop them"
  },
  {
    "code": "def query_struct(self, name):\n        sql = 'select id, file_id, name from code_items '\\\n              'where name = ?'\n        self.cursor.execute(sql, (name,))\n        for i in self.cursor.fetchall():\n            sql = 'select id, type, name from code_items ' \\\n                  'where parent_id = ?'\n            self.cursor.execute(sql, (i[0],))\n            members = self.cursor.fetchall()\n            if members:\n                print(self.file_id_to_name(i[1]), i[2])\n                print(members)",
    "docstring": "Query struct."
  },
  {
    "code": "def to_pandas_closed_closed(date_range, add_tz=True):\n    if not date_range:\n        return None\n    start = date_range.start\n    end = date_range.end\n    if start:\n        start = to_dt(start, mktz()) if add_tz else start\n        if date_range.startopen:\n            start += timedelta(milliseconds=1)\n    if end:\n        end = to_dt(end, mktz()) if add_tz else end\n        if date_range.endopen:\n            end -= timedelta(milliseconds=1)\n    return DateRange(start, end)",
    "docstring": "Pandas DateRange slicing is CLOSED-CLOSED inclusive at both ends.\n\n    Parameters\n    ----------\n    date_range : `DateRange` object\n        converted to CLOSED_CLOSED form for Pandas slicing\n\n    add_tz : `bool`\n        Adds a TimeZone to the daterange start and end if it doesn't\n        have one.\n\n    Returns\n    -------\n    Returns a date_range with start-end suitable for slicing in pandas."
  },
  {
    "code": "def bundle(context, name):\n    if context.obj['db'].bundle(name):\n        click.echo(click.style('bundle name already exists', fg='yellow'))\n        context.abort()\n    new_bundle = context.obj['db'].new_bundle(name)\n    context.obj['db'].add_commit(new_bundle)\n    new_version = context.obj['db'].new_version(created_at=new_bundle.created_at)\n    new_version.bundle = new_bundle\n    context.obj['db'].add_commit(new_version)\n    click.echo(click.style(f\"new bundle added: {new_bundle.name} ({new_bundle.id})\", fg='green'))",
    "docstring": "Add a new bundle."
  },
  {
    "code": "def _calculateEncodingKey(comparator):\n    encodingName = None\n    for k, v in list(_encodings.items()):\n        if v == comparator:\n            encodingName = k\n            break\n    return encodingName",
    "docstring": "Gets the first key of all available encodings where the corresponding\n    value matches the comparator.\n\n    Args:\n        comparator (string): A view name for an encoding.\n\n    Returns:\n        str: A key for a specific encoding used by python."
  },
  {
    "code": "def update_boot_system_use(self, boot_sys_use):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('Boot Record not yet initialized')\n        self.boot_system_use = boot_sys_use.ljust(197, b'\\x00')",
    "docstring": "A method to update the boot system use field of this Boot Record.\n\n        Parameters:\n         boot_sys_use - The new boot system use field for this Boot Record.\n        Returns:\n         Nothing."
  },
  {
    "code": "def get_collection(self, folderid, username=\"\", offset=0, limit=10):\n        if not username and self.standard_grant_type == \"authorization_code\":\n            response = self._req('/collections/{}'.format(folderid), {\n                \"offset\":offset,\n                \"limit\":limit\n            })\n        else:\n            if not username:\n                raise DeviantartError(\"No username defined.\")\n            else:\n                response = self._req('/collections/{}'.format(folderid), {\n                    \"username\":username,\n                    \"offset\":offset,\n                    \"limit\":limit\n                })\n        deviations = []\n        for item in response['results']:\n            d = Deviation()\n            d.from_dict(item)\n            deviations.append(d)\n        if \"name\" in response:\n            name = response['name']\n        else:\n            name = None\n        return {\n            \"results\" : deviations,\n            \"name\" : name,\n            \"has_more\" : response['has_more'],\n            \"next_offset\" : response['next_offset']\n        }",
    "docstring": "Fetch collection folder contents\n\n        :param folderid: UUID of the folder to list\n        :param username: The user to list folders for, if omitted the authenticated user is used\n        :param offset: the pagination offset\n        :param limit: the pagination limit"
  },
  {
    "code": "def get_game(site, description=\"\", create=False):\n    game = None\n    games = Game.objects.filter(site=site).order_by(\"-created\")\n    try:\n        game = games[0]\n    except IndexError:\n        game = None\n    if game is None or game.is_expired() or is_after_endtime():\n        if create:\n            if is_starttime():\n                game = Game(site=site, description=description)\n                game.save()\n            else:\n                raise TimeRangeError(\n                    _(u\"game start outside of the valid timerange\"))\n        else:\n            game = None\n    elif not is_after_endtime():\n        game = games[0]\n    return game",
    "docstring": "get the current game, if its still active, else\n        creates a new game, if the current time is inside the\n        GAME_START_TIMES interval and create=True\n        @param create: create a game, if there is no active game\n        @returns: None if there is no active Game, and none shoul be\n        created or the (new) active Game."
  },
  {
    "code": "def validate_username(username):\n        try:\n            validate_slug(username)\n        except ValidationError:\n            username = slugify(username)\n        user_model_cls = get_user_model()\n        _username = username\n        while user_model_cls.objects.filter(username=_username).exists():\n            _username = '{}{}'.format(username, random.randint(1, 100))\n        return _username",
    "docstring": "This validation step is done when we are sure the user\n        does not exit on the systems and we need to create a new user."
  },
  {
    "code": "def iterfd(fd):\n    unpk = msgpack.Unpacker(fd, **unpacker_kwargs)\n    for mesg in unpk:\n        yield mesg",
    "docstring": "Generator which unpacks a file object of msgpacked content.\n\n    Args:\n        fd: File object to consume data from.\n\n    Notes:\n        String objects are decoded using utf8 encoding.  In order to handle\n        potentially malformed input, ``unicode_errors='surrogatepass'`` is set\n        to allow decoding bad input strings.\n\n    Yields:\n        Objects from a msgpack stream."
  },
  {
    "code": "def pdhg(x, f, g, A, tau, sigma, niter, **kwargs):\n    def fun_select(k):\n        return [0]\n    f = odl.solvers.SeparableSum(f)\n    A = odl.BroadcastOperator(A, 1)\n    y = kwargs.pop('y', None)\n    if y is None:\n        y_new = None\n    else:\n        y_new = A.range.element([y])\n    spdhg_generic(x, f, g, A, tau, [sigma], niter, fun_select, y=y_new,\n                  **kwargs)\n    if y is not None:\n        y.assign(y_new[0])",
    "docstring": "Computes a saddle point with PDHG.\n\n    This algorithm is the same as \"algorithm 1\" in [CP2011a] but with\n    extrapolation on the dual variable.\n\n\n    Parameters\n    ----------\n    x : primal variable\n        This variable is both input and output of the method.\n    f : function\n        Functional Y -> IR_infty that has a convex conjugate with a\n        proximal operator, i.e. f.convex_conj.proximal(sigma) : Y -> Y.\n    g : function\n        Functional X -> IR_infty that has a proximal operator, i.e.\n        g.proximal(tau) : X -> X.\n    A : function\n        Operator A : X -> Y that possesses an adjoint: A.adjoint\n    tau : scalar / vector / matrix\n        Step size for primal variable. Note that the proximal operator of g\n        has to be well-defined for this input.\n    sigma : scalar\n        Scalar / vector / matrix used as step size for dual variable. Note that\n        the proximal operator related to f (see above) has to be well-defined\n        for this input.\n    niter : int\n        Number of iterations\n\n    Other Parameters\n    ----------------\n    y: dual variable\n        Dual variable is part of a product space\n    z: variable\n        Adjoint of dual variable, z = A^* y.\n    theta : scalar\n        Extrapolation factor.\n    callback : callable\n        Function called with the current iterate after each iteration.\n\n    References\n    ----------\n    [CP2011a] Chambolle, A and Pock, T. *A First-Order\n    Primal-Dual Algorithm for Convex Problems with Applications to\n    Imaging*. Journal of Mathematical Imaging and Vision, 40 (2011),\n    pp 120-145."
  },
  {
    "code": "def get_default(self, node):\n        if self.opposite_property in node.inst.properties:\n            return not node.inst.properties[self.opposite_property]\n        else:\n            return self.default",
    "docstring": "If not explicitly set, check if the opposite was set first before returning\n        default"
  },
  {
    "code": "def get(self, key):\n    key = self._service_key(key)\n    return self._service_ops['get'](key)",
    "docstring": "Return the object in `service` named by `key` or None.\n\n    Args:\n      key: Key naming the object to retrieve.\n\n    Returns:\n      object or None"
  },
  {
    "code": "def _handle_event(self, connection, event):\n        with self.mutex:\n            matching_handlers = sorted(\n                self.handlers.get(\"all_events\", [])\n                + self.handlers.get(event.type, [])\n            )\n            for handler in matching_handlers:\n                result = handler.callback(connection, event)\n                if result == \"NO MORE\":\n                    return",
    "docstring": "Handle an Event event incoming on ServerConnection connection."
  },
  {
    "code": "def genkeyhex():\n    while True:\n        key = hash256(\n                hexlify(os.urandom(40) + str(datetime.datetime.now())\n                                            .encode(\"utf-8\")))\n        if int(key,16) > 1 and int(key,16) < N:\n            break\n    return key",
    "docstring": "Generate new random Bitcoin private key, using os.urandom and\n    double-sha256.  Hex format."
  },
  {
    "code": "def _device_expiry_callback(self):\n        expired = 0\n        for adapters in self._devices.values():\n            to_remove = []\n            now = monotonic()\n            for adapter_id, dev in adapters.items():\n                if 'expires' not in dev:\n                    continue\n                if now > dev['expires']:\n                    to_remove.append(adapter_id)\n                    local_conn = \"adapter/%d/%s\" % (adapter_id, dev['connection_string'])\n                    if local_conn in self._conn_strings:\n                        del self._conn_strings[local_conn]\n            for entry in to_remove:\n                del adapters[entry]\n                expired += 1\n        if expired > 0:\n            self._logger.info('Expired %d devices', expired)",
    "docstring": "Periodic callback to remove expired devices from visible_devices."
  },
  {
    "code": "def _K(m):\n    M = m*(m - 1)//2\n    K = np.zeros((M, m**2), dtype=np.int64)\n    row = 0\n    for j in range(1, m):\n        col = (j - 1)*m + j\n        s = m - j\n        K[row:(row+s), col:(col+s)] = np.eye(s)\n        row += s\n    return K",
    "docstring": "matrix K_m from Wiktorsson2001"
  },
  {
    "code": "def save(self, fname, mode=None, validate=True, wd=False, inline=False,\n             relative=True, pack=False, encoding='utf-8'):\n        super(WorkflowGenerator, self).save(fname,\n                                            mode=mode,\n                                            validate=validate,\n                                            wd=wd,\n                                            inline=inline,\n                                            relative=relative,\n                                            pack=pack,\n                                            encoding=encoding)",
    "docstring": "Save workflow to file\n\n        For nlppln, the default is to save workflows with relative paths."
  },
  {
    "code": "def set_authoring_nodes(self, editor):\n        project_node = self.default_project_node\n        file_node = self.register_file(editor.file, project_node)\n        editor_node = self.register_editor(editor, file_node)\n        return True",
    "docstring": "Sets the Model authoring Nodes using given editor.\n\n        :param editor: Editor to set.\n        :type editor: Editor\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def DirContains(self,f) :\n        def match(fsNode) :\n            if not fsNode.isdir() : return False \n            for c in fsNode.children() :\n                if f(c) : return True\n            return False\n        return self.make_return(match)",
    "docstring": "Matches dirs that have a child that matches filter f"
  },
  {
    "code": "def val_to_signed_integer(value, bitwidth):\n    if isinstance(value, WireVector) or isinstance(bitwidth, WireVector):\n        raise PyrtlError('inputs must not be wirevectors')\n    if bitwidth < 1:\n        raise PyrtlError('bitwidth must be a positive integer')\n    neg_mask = 1 << (bitwidth - 1)\n    neg_part = value & neg_mask\n    pos_mask = neg_mask - 1\n    pos_part = value & pos_mask\n    return pos_part - neg_part",
    "docstring": "Return value as intrepreted as a signed integer under twos complement.\n\n    :param value: a python integer holding the value to convert\n    :param bitwidth: the length of the integer in bits to assume for conversion\n\n    Given an unsigned integer (not a wirevector!) covert that to a signed\n    integer.  This is useful for printing and interpreting values which are\n    negative numbers in twos complement. ::\n\n        val_to_signed_integer(0xff, 8) == -1"
  },
  {
    "code": "def add_plot(x, y, xl, yl, fig, ax, LATEX=False, linestyle=None, **kwargs):\n    if LATEX:\n        xl_data = xl[1]\n        yl_data = yl[1]\n    else:\n        xl_data = xl[0]\n        yl_data = yl[0]\n    for idx in range(len(y)):\n        ax.plot(x, y[idx], label=yl_data[idx], linestyle=linestyle)\n    ax.legend(loc='upper right')\n    ax.set_ylim(auto=True)",
    "docstring": "Add plots to an existing plot"
  },
  {
    "code": "def space(self):\n        schema = SpaceSchema()\n        resp = self.service.get(self.base+'space/')\n        return self.service.decode(schema, resp)",
    "docstring": "Get system disk space usage.\n\n        :return: :class:`system.Space <system.Space>` object\n        :rtype: system.Space"
  },
  {
    "code": "def of(cls, msg_header: MessageHeader) -> 'MessageDecoder':\n        cte_hdr = msg_header.parsed.content_transfer_encoding\n        return cls.of_cte(cte_hdr)",
    "docstring": "Return a decoder from the message header object.\n\n        See Also:\n            :meth:`.of_cte`\n\n        Args:\n            msg_header: The message header object."
  },
  {
    "code": "def state(self):\n        state = self._resource.get('state', self.default_state)\n        if state not in State:\n            state = getattr(State, state)\n        if not self.parent:\n            raise Exception('Unable to check the parent state')\n        parent_state = self.parent.state\n        return max([state, parent_state], key=attrgetter('value'))",
    "docstring": "Get the SubResource state\n\n        If the parents state has a higher priority, then it overrides the\n        SubResource state\n\n        ..note:: This assumes that self.parent is populated"
  },
  {
    "code": "def advertise(\n        self,\n        routers=None,\n        name=None,\n        timeout=None,\n        router_file=None,\n        jitter=None,\n    ):\n        name = name or self.name\n        if not self.is_listening():\n            self.listen()\n        return hyperbahn.advertise(\n            self,\n            name,\n            routers,\n            timeout,\n            router_file,\n            jitter,\n        )",
    "docstring": "Make a service available on the Hyperbahn routing mesh.\n\n        This will make contact with a Hyperbahn host from a list of known\n        Hyperbahn routers. Additional Hyperbahn connections will be established\n        once contact has been made with the network.\n\n        :param router:\n            A seed list of addresses of Hyperbahn routers, e.g.,\n            ``[\"127.0.0.1:23000\"]``.\n\n        :param name:\n            The identity of this service on the Hyperbahn.\n\n            This is usually unnecessary, as it defaults to the name given when\n            initializing the :py:class:`TChannel` (which is used as your\n            identity as a caller).\n\n        :returns:\n            A future that resolves to the remote server's response after\n            the first advertise finishes.\n\n            Advertisement will continue to happen periodically."
  },
  {
    "code": "def start(self):\n        with self._operational_lock:\n            ready = threading.Event()\n            thread = threading.Thread(\n                name=_BIDIRECTIONAL_CONSUMER_NAME,\n                target=self._thread_main,\n                args=(ready,)\n            )\n            thread.daemon = True\n            thread.start()\n            ready.wait()\n            self._thread = thread\n            _LOGGER.debug(\"Started helper thread %s\", thread.name)",
    "docstring": "Start the background thread and begin consuming the thread."
  },
  {
    "code": "def form_invalid(self, form):\n        LOGGER.debug(\"Invalid Email Form Submitted\")\n        messages.add_message(self.request, messages.ERROR, _(\"Invalid Email Address.\"))\n        return super(EmailTermsView, self).form_invalid(form)",
    "docstring": "Override of CreateView method, logs invalid email form submissions."
  },
  {
    "code": "def call_with_context(func, context, *args):\n    return make_context_aware(func, len(args))(*args + (context,))",
    "docstring": "Check if given function has more arguments than given. Call it with context\n    as last argument or without it."
  },
  {
    "code": "def _gluster_output_cleanup(result):\n    ret = ''\n    for line in result.splitlines():\n        if line.startswith('gluster>'):\n            ret += line[9:].strip()\n        elif line.startswith('Welcome to gluster prompt'):\n            pass\n        else:\n            ret += line.strip()\n    return ret",
    "docstring": "Gluster versions prior to 6 have a bug that requires tricking\n    isatty. This adds \"gluster> \" to the output. Strip it off and\n    produce clean xml for ElementTree."
  },
  {
    "code": "def complete(self, GET):\n        token = self.get_access_token(verifier=GET.get('oauth_verifier', None))\n        return token",
    "docstring": "When redirect back to our application, try to complete the flow by\n        requesting an access token. If the access token request fails, it'll\n        throw an `OAuthError`.\n        \n        Tries to complete the flow by validating against the `GET` paramters \n        received."
  },
  {
    "code": "def validate(schema_text, data_text, deserializer=_default_deserializer):\n    schema = Schema(deserializer(schema_text))\n    data = deserializer(data_text)\n    return Validator.validate(schema, data)",
    "docstring": "Validate specified JSON text with specified schema.\n\n    Both arguments are converted to JSON objects with :func:`simplejson.loads`,\n    if present, or :func:`json.loads`.\n\n    :param schema_text:\n        Text of the JSON schema to check against\n    :type schema_text:\n        :class:`str`\n    :param data_text:\n        Text of the JSON object to check\n    :type data_text:\n        :class:`str`\n    :param deserializer:\n        Function to convert the schema and data to JSON objects\n    :type deserializer:\n        :class:`callable`\n    :returns:\n        Same as :meth:`json_schema_validator.validator.Validator.validate`\n    :raises:\n        Whatever may be raised by simplejson (in particular\n        :class:`simplejson.decoder.JSONDecoderError`, a subclass of\n        :class:`ValueError`) or json\n    :raises:\n        Whatever may be raised by\n        :meth:`json_schema_validator.validator.Validator.validate`. In particular\n        :class:`json_schema_validator.errors.ValidationError` and\n        :class:`json_schema_validator.errors.SchemaError`"
  },
  {
    "code": "def __refresh_statusbar(self, index):\r\n        finfo = self.data[index]\r\n        self.encoding_changed.emit(finfo.encoding)\r\n        line, index = finfo.editor.get_cursor_line_column()\r\n        self.sig_editor_cursor_position_changed.emit(line, index)",
    "docstring": "Refreshing statusbar widgets"
  },
  {
    "code": "def socket_reader(connection: socket, buffer_size: int = 1024):\n    while connection is not None:\n        try:\n            buffer = connection.recv(buffer_size)\n            if not len(buffer):\n                raise ConnectionAbortedError\n        except ConnectionAbortedError:\n            print('connection aborted')\n            connection.close()\n            yield None\n        except OSError:\n            print('socket closed')\n            connection.close()\n            yield None\n        else:\n            yield buffer",
    "docstring": "read data from adb socket"
  },
  {
    "code": "def check_flavors(session):\n    nclient = nova.Client(NOVA_VERSION, session=session,\n                          region_name=os.environ['OS_REGION_NAME'])\n    flavors = nclient.flavors.list()\n    to_id = dict(list(map(lambda n: [n.name, n.id], flavors)))\n    to_flavor = dict(list(map(lambda n: [n.id, n.name], flavors)))\n    return to_id, to_flavor",
    "docstring": "Build the flavors mapping\n\n    returns the mappings id <-> flavor"
  },
  {
    "code": "def scheduling_blocks():\n    sbi_list = SchedulingBlockInstanceList()\n    return dict(active=sbi_list.active,\n                completed=sbi_list.completed,\n                aborted=sbi_list.aborted)",
    "docstring": "Return list of Scheduling Block instances known to SDP."
  },
  {
    "code": "def avail_locations(call=None):\n    if call == 'action':\n        raise SaltCloudSystemExit(\n            'The avail_locations function must be called with '\n            '-f or --function, or with the --list-locations option.'\n        )\n    server, user, password = _get_xml_rpc()\n    auth = ':'.join([user, password])\n    host_pool = server.one.hostpool.info(auth)[1]\n    locations = {}\n    for host in _get_xml(host_pool):\n        locations[host.find('NAME').text] = _xml_to_dict(host)\n    return locations",
    "docstring": "Return available OpenNebula locations.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud --list-locations opennebula\n        salt-cloud --function avail_locations opennebula\n        salt-cloud -f avail_locations opennebula"
  },
  {
    "code": "def write_class(self, obj, parent=None):\n        self._writeStruct(\">B\", 1, (self.TC_CLASS,))\n        self.write_classdesc(obj)",
    "docstring": "Writes a class to the stream\n\n        :param obj: A JavaClass object\n        :param parent:"
  },
  {
    "code": "def getMAC(self, bType=MacType.RandomMac):\n        print '%s call getMAC' % self.port\n        if self.isPowerDown:\n            macAddr64 = self.mac\n        else:\n            if bType == MacType.FactoryMac:\n                macAddr64 = self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:HardwareAddress')[0])\n            elif bType == MacType.HashMac:\n                macAddr64 = self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:MACAddress')[0])\n            else:\n                macAddr64 = self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:ExtendedAddress')[0])\n        return int(macAddr64, 16)",
    "docstring": "get one specific type of MAC address\n           currently OpenThreadWpan only supports Random MAC address\n\n        Args:\n            bType: indicate which kind of MAC address is required\n\n        Returns:\n            specific type of MAC address"
  },
  {
    "code": "def delete_secret(self, path, mount_point=DEFAULT_MOUNT_POINT):\n        api_path = '/v1/{mount_point}/{path}'.format(mount_point=mount_point, path=path)\n        return self._adapter.delete(\n            url=api_path,\n        )",
    "docstring": "Delete the secret at the specified location.\n\n        Supported methods:\n            DELETE: /{mount_point}/{path}. Produces: 204 (empty body)\n\n\n        :param path: Specifies the path of the secret to delete.\n            This is specified as part of the URL.\n        :type path: str | unicode\n        :param mount_point: The \"path\" the secret engine was mounted on.\n        :type mount_point: str | unicode\n        :return: The response of the delete_secret request.\n        :rtype: requests.Response"
  },
  {
    "code": "def MI_get_item(self, key, index=0):\n    'return list of item'\n    index = _key_to_index_single(force_list(self.indices.keys()), index)\n    if index != 0:\n        key = self.indices[index][key]\n    value = super(MIMapping, self).__getitem__(key)\n    N = len(self.indices)\n    if N == 1:\n        return [key]\n    if N == 2:\n        value = [value]\n    return [key] + value",
    "docstring": "return list of item"
  },
  {
    "code": "def save_html_with_metadata(fig, filename, fig_kwds, kwds):\n    if isinstance(fig, str):\n        text = fig\n    else:\n        from mpld3 import fig_to_html\n        text = fig_to_html(fig, **fig_kwds)\n    f = open(filename, 'w')\n    for key, value in kwds.items():\n        value = escape(value, escape_table)\n        line = \"<div class=pycbc-meta key=\\\"%s\\\" value=\\\"%s\\\"></div>\" % (str(key), value)\n        f.write(line)\n    f.write(text)",
    "docstring": "Save a html output to file with metadata"
  },
  {
    "code": "async def dump_field(obj, elem, elem_type, params=None):\n    if isinstance(elem, (int, bool)) or issubclass(elem_type, x.UVarintType) or issubclass(elem_type, x.IntType):\n        return set_elem(obj, elem)\n    elif issubclass(elem_type, x.BlobType) or isinstance(obj, bytes) or isinstance(obj, bytearray):\n        return set_elem(obj, await dump_blob(elem))\n    elif issubclass(elem_type, x.UnicodeType) or isinstance(elem, str):\n        return set_elem(obj, elem)\n    elif issubclass(elem_type, x.VariantType):\n        return set_elem(obj, await dump_variant(None, elem, elem_type, params))\n    elif issubclass(elem_type, x.ContainerType):\n        return set_elem(obj, await dump_container(None, elem, elem_type, params))\n    elif issubclass(elem_type, x.MessageType):\n        return set_elem(obj, await dump_message(None, elem))\n    else:\n        raise TypeError",
    "docstring": "Dumps generic field to the popo object representation, according to the element specification.\n    General multiplexer.\n\n    :param obj:\n    :param elem:\n    :param elem_type:\n    :param params:\n    :return:"
  },
  {
    "code": "def rooms_clean_history(self, room_id, latest, oldest, **kwargs):\n        return self.__call_api_post('rooms.cleanHistory', roomId=room_id, latest=latest, oldest=oldest, kwargs=kwargs)",
    "docstring": "Cleans up a room, removing messages from the provided time range."
  },
  {
    "code": "def write_kwargs_to_attrs(cls, attrs, **kwargs):\n        for arg, val in kwargs.items():\n            if val is None:\n                val = str(None)\n            if isinstance(val, dict):\n                attrs[arg] = val.keys()\n                cls.write_kwargs_to_attrs(attrs, **val)\n            else:\n                attrs[arg] = val",
    "docstring": "Writes the given keywords to the given ``attrs``.\n\n        If any keyword argument points to a dict, the keyword will point to a\n        list of the dict's keys. Each key is then written to the attrs with its\n        corresponding value.\n\n        Parameters\n        ----------\n        attrs : an HDF attrs\n            The ``attrs`` of an hdf file or a group in an hdf file.\n        \\**kwargs :\n            The keywords to write."
  },
  {
    "code": "def mem_ds(res, extent, srs=None, dtype=gdal.GDT_Float32):\n    dst_ns = int((extent[2] - extent[0])/res + 0.99)\n    dst_nl = int((extent[3] - extent[1])/res + 0.99)\n    m_ds = gdal.GetDriverByName('MEM').Create('', dst_ns, dst_nl, 1, dtype)\n    m_gt = [extent[0], res, 0, extent[3], 0, -res]\n    m_ds.SetGeoTransform(m_gt)\n    if srs is not None:\n        m_ds.SetProjection(srs.ExportToWkt())\n    return m_ds",
    "docstring": "Create a new GDAL Dataset in memory\n\n    Useful for various applications that require a Dataset"
  },
  {
    "code": "def onMessageReceived(self, method_frame, properties, body):\n        if \"UUID\" not in properties.headers:\n            self.process_exception(\n                e=ValueError(\"No UUID provided, message ignored.\"),\n                uuid=\"\",\n                routing_key=self.parseKey(method_frame),\n                body=body\n            )\n            return True\n        key = self.parseKey(method_frame)\n        uuid = properties.headers[\"UUID\"]\n        try:\n            result = self.react_fn(\n                serializers.deserialize(body, self.globals),\n                self.get_sendback(uuid, key)\n            )\n            print \"sending response\", key\n            self.sendResponse(\n                serializers.serialize(result),\n                uuid,\n                key\n            )\n        except Exception, e:\n            self.process_exception(\n                e=e,\n                uuid=uuid,\n                routing_key=key,\n                body=str(e),\n                tb=traceback.format_exc().strip()\n            )\n        return True",
    "docstring": "React to received message - deserialize it, add it to users reaction\n        function stored in ``self.react_fn`` and send back result.\n\n        If `Exception` is thrown during process, it is sent back instead of\n        message.\n\n        Note:\n            In case of `Exception`, response message doesn't have useful `body`,\n            but in headers is stored following (string) parameters:\n\n            - ``exception``, where the Exception's message is stored\n            - ``exception_type``, where ``e.__class__`` is stored\n            - ``exception_name``, where ``e.__class__.__name__`` is stored\n            - ``traceback`` where the full traceback is stored (contains line\n              number)\n\n            This allows you to react to unexpected cases at the other end of\n            the AMQP communication."
  },
  {
    "code": "def pg_backup(self, pg_dump_exe='pg_dump', exclude_schema=None):\n        command = [\n            pg_dump_exe, '-Fc', '-f', self.file,\n            'service={}'.format(self.pg_service)\n            ]\n        if exclude_schema:\n            command.append(' '.join(\"--exclude-schema={}\".format(schema) for schema in exclude_schema))\n        subprocess.check_output(command, stderr=subprocess.STDOUT)",
    "docstring": "Call the pg_dump command to create a db backup\n\n        Parameters\n        ----------\n        pg_dump_exe: str\n            the pg_dump command path\n        exclude_schema: str[]\n            list of schemas to be skipped"
  },
  {
    "code": "def kick_user(self, room_id, user_id, reason=\"\"):\n        self.set_membership(room_id, user_id, \"leave\", reason)",
    "docstring": "Calls set_membership with membership=\"leave\" for the user_id provided"
  },
  {
    "code": "def access_token(self, value, request):\n        if self.validate(value, request) is not None:\n            return None\n        access_token = AccessToken.objects.for_token(value)\n        return access_token",
    "docstring": "Try to get the `AccessToken` associated with the provided token.\n\n        *The provided value must pass `BearerHandler.validate()`*"
  },
  {
    "code": "def accept( self ):\r\n        if ( not self.uiNameTXT.text() ):\r\n            QMessageBox.information(self,\r\n                                   'Invalid Name',\r\n                                   'You need to supply a name for your layout.')\r\n            return\r\n        prof = self.profile()\r\n        if ( not prof ):\r\n            prof = XViewProfile()\r\n        prof.setName(nativestring(self.uiNameTXT.text()))\r\n        prof.setVersion(self.uiVersionSPN.value())\r\n        prof.setDescription(nativestring(self.uiDescriptionTXT.toPlainText()))\r\n        prof.setIcon(self.uiIconBTN.filepath())\r\n        super(XViewProfileDialog, self).accept()",
    "docstring": "Saves the data to the profile before closing."
  },
  {
    "code": "def get_filter_args_for_all_events_from_channel(\n        token_network_address: TokenNetworkAddress,\n        channel_identifier: ChannelID,\n        contract_manager: ContractManager,\n        from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,\n        to_block: BlockSpecification = 'latest',\n) -> Dict:\n    event_filter_params = get_filter_args_for_specific_event_from_channel(\n        token_network_address=token_network_address,\n        channel_identifier=channel_identifier,\n        event_name=ChannelEvent.OPENED,\n        contract_manager=contract_manager,\n        from_block=from_block,\n        to_block=to_block,\n    )\n    event_filter_params['topics'] = [None, event_filter_params['topics'][1]]\n    return event_filter_params",
    "docstring": "Return the filter params for all events of a given channel."
  },
  {
    "code": "def _relation_module(role, interface):\n    _append_path(hookenv.charm_dir())\n    _append_path(os.path.join(hookenv.charm_dir(), 'hooks'))\n    base_module = 'relations.{}.{}'.format(interface, role)\n    for module in ('reactive.{}'.format(base_module), base_module):\n        if module in sys.modules:\n            break\n        try:\n            importlib.import_module(module)\n            break\n        except ImportError:\n            continue\n    else:\n        hookenv.log('Unable to find implementation for relation: '\n                    '{} of {}'.format(role, interface), hookenv.ERROR)\n        return None\n    return sys.modules[module]",
    "docstring": "Return module for relation based on its role and interface, or None.\n\n    Prefers new location (reactive/relations) over old (hooks/relations)."
  },
  {
    "code": "def main(self):\n        args = self.args\n        parsed_pytree, pypackages = self.parse_py_tree(pytree=args.pytree)\n        parsed_doctree = self.parse_doc_tree(doctree=args.doctree, pypackages=pypackages)\n        return self.compare_trees(parsed_pytree=parsed_pytree, parsed_doctree=parsed_doctree)",
    "docstring": "Parse package trees and report on any discrepancies."
  },
  {
    "code": "def _construct_output_to_match(output_block):\n    output_block.validate()\n    selections = (\n        u'%s AS `%s`' % (output_block.fields[key].to_match(), key)\n        for key in sorted(output_block.fields.keys())\n    )\n    return u'SELECT %s FROM' % (u', '.join(selections),)",
    "docstring": "Transform a ConstructResult block into a MATCH query string."
  },
  {
    "code": "def update(self, other):\n        if isinstance(other, cookielib.CookieJar):\n            for cookie in other:\n                self.set_cookie(copy.copy(cookie))\n        else:\n            super(RequestsCookieJar, self).update(other)",
    "docstring": "Updates this jar with cookies from another CookieJar or dict-like"
  },
  {
    "code": "def halt(self):\n        buf = []\n        buf.append(self.act_end)\n        buf.append(0)\n        crc = self.calculate_crc(buf)\n        self.clear_bitmask(0x08, 0x80)\n        self.card_write(self.mode_transrec, buf)\n        self.clear_bitmask(0x08, 0x08)\n        self.authed = False",
    "docstring": "Switch state to HALT"
  },
  {
    "code": "def set_description(self, name, action, seqno, value=None, default=False,\n                        disable=False):\n        commands = ['route-map %s %s %s' % (name, action, seqno)]\n        if value is not None:\n            commands.append(self.command_builder('description', disable=True))\n        commands.append(self.command_builder('description', value=value,\n                                             default=default, disable=disable))\n        return self.configure(commands)",
    "docstring": "Configures the routemap description\n\n        Args:\n            name (string): The full name of the routemap.\n            action (string): The action to take for this routemap clause.\n            seqno (integer): The sequence number for the routemap clause.\n            value (string): The value to configure for the routemap description\n            default (bool): Specifies to default the routemap description value\n            disable (bool): Specifies to negate the routemap description\n\n        Returns:\n            True if the operation succeeds otherwise False is returned"
  },
  {
    "code": "def _require_homogeneous_roots(self, accept_predicate, reject_predicate):\n    if len(self.context.target_roots) == 0:\n      raise self.NoActivationsError('No target specified.')\n    def resolve(targets):\n      for t in targets:\n        if type(t) == Target:\n          for r in resolve(t.dependencies):\n            yield r\n        else:\n          yield t\n    expanded_roots = list(resolve(self.context.target_roots))\n    accepted = list(filter(accept_predicate, expanded_roots))\n    rejected = list(filter(reject_predicate, expanded_roots))\n    if len(accepted) == 0:\n      return None\n    elif len(rejected) == 0:\n      return accepted\n    else:\n      def render_target(target):\n        return '{} (a {})'.format(target.address.reference(), target.type_alias)\n      raise self.IncompatibleActivationsError('Mutually incompatible targets specified: {} vs {} '\n                                              '(and {} others)'\n                                              .format(render_target(accepted[0]),\n                                                      render_target(rejected[0]),\n                                                      len(accepted) + len(rejected) - 2))",
    "docstring": "Ensures that there is no ambiguity in the context according to the given predicates.\n\n    If any targets in the context satisfy the accept_predicate, and no targets satisfy the\n    reject_predicate, returns the accepted targets.\n\n    If no targets satisfy the accept_predicate, returns None.\n\n    Otherwise throws TaskError."
  },
  {
    "code": "def reinstall_ruby(ruby, runas=None, env=None):\n    return _rvm(['reinstall', ruby], runas=runas, env=env)",
    "docstring": "Reinstall a ruby implementation\n\n    ruby\n        The version of ruby to reinstall\n\n    runas\n        The user under which to run rvm. If not specified, then rvm will be run\n        as the user under which Salt is running.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rvm.reinstall_ruby 1.9.3-p385"
  },
  {
    "code": "def db(self):\n        if self._db is None:\n            if self.tcex.default_args.tc_playbook_db_type == 'Redis':\n                from .tcex_redis import TcExRedis\n                self._db = TcExRedis(\n                    self.tcex.default_args.tc_playbook_db_path,\n                    self.tcex.default_args.tc_playbook_db_port,\n                    self.tcex.default_args.tc_playbook_db_context,\n                )\n            elif self.tcex.default_args.tc_playbook_db_type == 'TCKeyValueAPI':\n                from .tcex_key_value import TcExKeyValue\n                self._db = TcExKeyValue(self.tcex)\n            else:\n                err = u'Invalid DB Type: ({})'.format(self.tcex.default_args.tc_playbook_db_type)\n                raise RuntimeError(err)\n        return self._db",
    "docstring": "Return the correct KV store for this execution."
  },
  {
    "code": "def delMargin(self, name):\n        for index, margin in enumerate(self._margins):\n            if margin.getName() == name:\n                visible = margin.isVisible()\n                margin.clear()\n                margin.deleteLater()\n                del self._margins[index]\n                if visible:\n                    self.updateViewport()\n                return True\n        return False",
    "docstring": "Deletes a margin.\n           Returns True if the margin was deleted and False otherwise."
  },
  {
    "code": "def table_path(cls, project, instance, table):\n        return google.api_core.path_template.expand(\n            \"projects/{project}/instances/{instance}/tables/{table}\",\n            project=project,\n            instance=instance,\n            table=table,\n        )",
    "docstring": "Return a fully-qualified table string."
  },
  {
    "code": "def _validate_paths(self, settings, name, value):\n        return [self._validate_path(settings, name, item)\n                for item in value]",
    "docstring": "Apply ``SettingsPostProcessor._validate_path`` to each element in\n        list.\n\n        Args:\n            settings (dict): Current settings.\n            name (str): Setting name.\n            value (list): List of paths to patch.\n\n        Raises:\n            boussole.exceptions.SettingsInvalidError: Once a path does not\n                exists.\n\n        Returns:\n            list: Validated paths."
  },
  {
    "code": "def update_cookies(self, cookies: Optional[LooseCookies]) -> None:\n        if not cookies:\n            return\n        c = SimpleCookie()\n        if hdrs.COOKIE in self.headers:\n            c.load(self.headers.get(hdrs.COOKIE, ''))\n            del self.headers[hdrs.COOKIE]\n        if isinstance(cookies, Mapping):\n            iter_cookies = cookies.items()\n        else:\n            iter_cookies = cookies\n        for name, value in iter_cookies:\n            if isinstance(value, Morsel):\n                mrsl_val = value.get(value.key, Morsel())\n                mrsl_val.set(value.key, value.value, value.coded_value)\n                c[name] = mrsl_val\n            else:\n                c[name] = value\n        self.headers[hdrs.COOKIE] = c.output(header='', sep=';').strip()",
    "docstring": "Update request cookies header."
  },
  {
    "code": "def postman(host, port=587, auth=(None, None),\n            force_tls=False, options=None):\n    return Postman(\n        host=host,\n        port=port,\n        middlewares=[\n            middleware.tls(force=force_tls),\n            middleware.auth(*auth),\n        ],\n        **options\n    )",
    "docstring": "Creates a Postman object with TLS and Auth\n    middleware. TLS is placed before authentication\n    because usually authentication happens and is\n    accepted only after TLS is enabled.\n\n    :param auth: Tuple of (username, password) to\n        be used to ``login`` to the server.\n    :param force_tls: Whether TLS should be forced.\n    :param options: Dictionary of keyword arguments\n        to be used when the SMTP class is called."
  },
  {
    "code": "def close(self):\n        files = self.__dict__.get(\"files\")\n        for _key, value in iter_multi_items(files or ()):\n            value.close()",
    "docstring": "Closes associated resources of this request object.  This\n        closes all file handles explicitly.  You can also use the request\n        object in a with statement which will automatically close it.\n\n        .. versionadded:: 0.9"
  },
  {
    "code": "def DeregisterFormatter(cls, formatter_class):\n    formatter_data_type = formatter_class.DATA_TYPE.lower()\n    if formatter_data_type not in cls._formatter_classes:\n      raise KeyError(\n          'Formatter class not set for data type: {0:s}.'.format(\n              formatter_class.DATA_TYPE))\n    del cls._formatter_classes[formatter_data_type]",
    "docstring": "Deregisters a formatter class.\n\n    The formatter classes are identified based on their lower case data type.\n\n    Args:\n      formatter_class (type): class of the formatter.\n\n    Raises:\n      KeyError: if formatter class is not set for the corresponding data type."
  },
  {
    "code": "def _find_valid_index(self, how):\n        assert how in ['first', 'last']\n        if len(self) == 0:\n            return None\n        is_valid = ~self.isna()\n        if self.ndim == 2:\n            is_valid = is_valid.any(1)\n        if how == 'first':\n            idxpos = is_valid.values[::].argmax()\n        if how == 'last':\n            idxpos = len(self) - 1 - is_valid.values[::-1].argmax()\n        chk_notna = is_valid.iat[idxpos]\n        idx = self.index[idxpos]\n        if not chk_notna:\n            return None\n        return idx",
    "docstring": "Retrieves the index of the first valid value.\n\n        Parameters\n        ----------\n        how : {'first', 'last'}\n            Use this parameter to change between the first or last valid index.\n\n        Returns\n        -------\n        idx_first_valid : type of index"
  },
  {
    "code": "def define(rest):\n\t\"Define a word\"\n\tword = rest.strip()\n\tres = util.lookup(word)\n\tfmt = (\n\t\t'{lookup.provider} says: {res}' if res else\n\t\t\"{lookup.provider} does not have a definition for that.\")\n\treturn fmt.format(**dict(locals(), lookup=util.lookup))",
    "docstring": "Define a word"
  },
  {
    "code": "def alter_zero_tip_allowed_states(tree, feature):\n    zero_parent2tips = defaultdict(list)\n    allowed_state_feature = get_personalized_feature_name(feature, ALLOWED_STATES)\n    for tip in tree:\n        if tip.dist == 0:\n            state = getattr(tip, feature, None)\n            if state is not None and state != '':\n                zero_parent2tips[tip.up].append(tip)\n    for parent, zero_tips in zero_parent2tips.items():\n        counts = None\n        for tip in zero_tips:\n            if counts is None:\n                counts = getattr(tip, allowed_state_feature).copy()\n            else:\n                counts += getattr(tip, allowed_state_feature)\n        if counts.max() == len(zero_tips):\n            continue\n        allowed_states = None\n        for tip in zero_tips:\n            if allowed_states is None:\n                allowed_states = getattr(tip, allowed_state_feature).copy()\n            else:\n                tip_allowed_states = getattr(tip, allowed_state_feature)\n                allowed_states[np.nonzero(tip_allowed_states)] = 1\n            tip.add_feature(allowed_state_feature, allowed_states)",
    "docstring": "Alters the bottom-up likelihood arrays for zero-distance tips\n    to make sure they do not contradict with other zero-distance tip siblings.\n\n    :param tree: ete3.Tree, the tree of interest\n    :param feature: str, character for which the likelihood is altered\n    :return: void, modifies the get_personalised_feature_name(feature, BU_LH) feature to zero-distance tips."
  },
  {
    "code": "def bump(self, level='patch', label=None):\n        bump = self._bump_pre if level == 'pre' else self._bump\n        bump(level, label)",
    "docstring": "Bump version following semantic versioning rules."
  },
  {
    "code": "def __get_hosts(self, pattern):\n        (name, enumeration_details) = self._enumeration_info(pattern)\n        hpat = self._hosts_in_unenumerated_pattern(name)\n        hpat = sorted(hpat, key=lambda x: x.name)\n        return set(self._apply_ranges(pattern, hpat))",
    "docstring": "finds hosts that postively match a particular pattern.  Does not\n        take into account negative matches."
  },
  {
    "code": "def _node_participation_settings(self):\n    try:\n        return self.node_participation_settings\n    except ObjectDoesNotExist:\n        node_participation_settings = NodeParticipationSettings(node=self)\n        node_participation_settings.save()\n        return node_participation_settings",
    "docstring": "Return node_participation_settings record\n    or create it if it does not exist\n\n    usage:\n    node = Node.objects.get(pk=1)\n    node.participation_settings"
  },
  {
    "code": "def uploadFile(uploadfunc, fileindex, existing, uf, skip_broken=False):\n    if uf[\"location\"].startswith(\"toilfs:\") or uf[\"location\"].startswith(\"_:\"):\n        return\n    if uf[\"location\"] in fileindex:\n        uf[\"location\"] = fileindex[uf[\"location\"]]\n        return\n    if not uf[\"location\"] and uf[\"path\"]:\n        uf[\"location\"] = schema_salad.ref_resolver.file_uri(uf[\"path\"])\n    if uf[\"location\"].startswith(\"file://\") and not os.path.isfile(uf[\"location\"][7:]):\n        if skip_broken:\n            return\n        else:\n            raise cwltool.errors.WorkflowException(\n                \"File is missing: %s\" % uf[\"location\"])\n    uf[\"location\"] = write_file(\n        uploadfunc, fileindex, existing, uf[\"location\"])",
    "docstring": "Update a file object so that the location is a reference to the toil file\n    store, writing it to the file store if necessary."
  },
  {
    "code": "def create_authz_decision_query(self, destination, action,\n            evidence=None, resource=None, subject=None,\n            message_id=0, consent=None, extensions=None,\n            sign=None, sign_alg=None, digest_alg=None, **kwargs):\n        return self._message(AuthzDecisionQuery, destination, message_id,\n                             consent, extensions, sign, action=action,\n                             evidence=evidence, resource=resource,\n                             subject=subject, sign_alg=sign_alg,\n                             digest_alg=digest_alg, **kwargs)",
    "docstring": "Creates an authz decision query.\n\n        :param destination: The IdP endpoint\n        :param action: The action you want to perform (has to be at least one)\n        :param evidence: Why you should be able to perform the action\n        :param resource: The resource you want to perform the action on\n        :param subject: Who wants to do the thing\n        :param message_id: Message identifier\n        :param consent: If the principal gave her consent to this request\n        :param extensions: Possible request extensions\n        :param sign: Whether the request should be signed or not.\n        :return: AuthzDecisionQuery instance"
  },
  {
    "code": "def delete_port(self, port):\n        port_id = self._find_port_id(port)\n        ret = self.network_conn.delete_port(port=port_id)\n        return ret if ret else True",
    "docstring": "Deletes the specified port"
  },
  {
    "code": "def identify(self, text, **kwargs):\n        if text is None:\n            raise ValueError('text must be provided')\n        headers = {}\n        if 'headers' in kwargs:\n            headers.update(kwargs.get('headers'))\n        sdk_headers = get_sdk_headers('language_translator', 'V3', 'identify')\n        headers.update(sdk_headers)\n        params = {'version': self.version}\n        data = text\n        headers['content-type'] = 'text/plain'\n        url = '/v3/identify'\n        response = self.request(\n            method='POST',\n            url=url,\n            headers=headers,\n            params=params,\n            data=data,\n            accept_json=True)\n        return response",
    "docstring": "Identify language.\n\n        Identifies the language of the input text.\n\n        :param str text: Input text in UTF-8 format.\n        :param dict headers: A `dict` containing the request headers\n        :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n        :rtype: DetailedResponse"
  },
  {
    "code": "def _adjust(a, a_offset, b):\n    x = (b[-1] & 0xFF) + (a[a_offset + len(b) - 1] & 0xFF) + 1\n    a[a_offset + len(b) - 1] = ctypes.c_ubyte(x).value\n    x >>= 8\n    for i in range(len(b)-2, -1, -1):\n        x += (b[i] & 0xFF) + (a[a_offset + i] & 0xFF)\n        a[a_offset + i] = ctypes.c_ubyte(x).value\n        x >>= 8",
    "docstring": "a = bytearray\n    a_offset = int\n    b = bytearray"
  },
  {
    "code": "def check_unassigned(chars, bad_tables):\n    bad_tables = (\n        stringprep.in_table_a1,)\n    violator = check_against_tables(chars, bad_tables)\n    if violator is not None:\n        raise ValueError(\"Input contains unassigned code point: \"\n                         \"U+{:04x}\".format(ord(violator)))",
    "docstring": "Check that `chars` does not contain any unassigned code points as per\n    the given list of `bad_tables`.\n\n    Operates on a list of unicode code points provided in `chars`."
  },
  {
    "code": "def get(self, resource_manager, identities):\n        m = self.resolve(resource_manager.resource_type)\n        params = {}\n        client_filter = False\n        if m.filter_name:\n            if m.filter_type == 'list':\n                params[m.filter_name] = identities\n            elif m.filter_type == 'scalar':\n                assert len(identities) == 1, \"Scalar server side filter\"\n                params[m.filter_name] = identities[0]\n        else:\n            client_filter = True\n        resources = self.filter(resource_manager, **params)\n        if client_filter:\n            if all(map(lambda r: isinstance(r, six.string_types), resources)):\n                resources = [r for r in resources if r in identities]\n            else:\n                resources = [r for r in resources if r[m.id] in identities]\n        return resources",
    "docstring": "Get resources by identities"
  },
  {
    "code": "def create_contentkey_authorization_policy_options(access_token, key_delivery_type=\"2\", \\\nname=\"HLS Open Authorization Policy\", key_restriction_type=\"0\"):\n    path = '/ContentKeyAuthorizationPolicyOptions'\n    endpoint = ''.join([ams_rest_endpoint, path])\n    body = '{ \\\n\t\t\"Name\":\"policy\",\\\n\t\t\"KeyDeliveryType\":\"' + key_delivery_type + '\", \\\n\t\t\"KeyDeliveryConfiguration\":\"\", \\\n\t\t\t\"Restrictions\":[{ \\\n\t\t\t\"Name\":\"' + name + '\", \\\n\t\t\t\"KeyRestrictionType\":\"' + key_restriction_type + '\", \\\n\t\t\t\"Requirements\":null \\\n\t\t}] \\\n\t}'\n    return do_ams_post(endpoint, path, body, access_token, \"json_only\")",
    "docstring": "Create Media Service Content Key Authorization Policy Options.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        key_delivery_type (str): A Media Service Content Key Authorization Policy Delivery Type.\n        name (str): A Media Service Contenty Key Authorization Policy Name.\n        key_restiction_type (str): A Media Service Contenty Key Restriction Type.\n\n    Returns:\n        HTTP response. JSON body."
  },
  {
    "code": "def api_send_mail(request, key=None, hproPk=None):\n    if not check_api_key(request, key, hproPk):\n        return HttpResponseForbidden\n    sender = request.POST.get('sender', settings.MAIL_SENDER)\n    dests = request.POST.getlist('dests')\n    subject = request.POST['subject']\n    message = request.POST['message']\n    html_message = request.POST.get('html_message')\n    if html_message and html_message.lower() == 'false':\n        html_message = False\n    if 'response_id' in request.POST:\n        key = hproPk + ':' + request.POST['response_id']\n    else:\n        key = None\n    generic_send_mail(sender, dests, subject, message, key, 'PlugIt API (%s)' % (hproPk or 'StandAlone',), html_message)\n    return HttpResponse(json.dumps({}), content_type=\"application/json\")",
    "docstring": "Send a email. Posts parameters are used"
  },
  {
    "code": "def ffmpeg_works():\n  images = np.zeros((2, 32, 32, 3), dtype=np.uint8)\n  try:\n    _encode_gif(images, 2)\n    return True\n  except (IOError, OSError):\n    return False",
    "docstring": "Tries to encode images with ffmpeg to check if it works."
  },
  {
    "code": "def _get_first_urn(self, urn):\n        urn = URN(urn)\n        subreference = None\n        textId = urn.upTo(URN.NO_PASSAGE)\n        if urn.reference is not None:\n            subreference = str(urn.reference)\n        firstId = self.resolver.getTextualNode(textId=textId, subreference=subreference).firstId\n        r = render_template(\n            \"cts/GetFirstUrn.xml\",\n            firstId=firstId,\n            full_urn=textId,\n            request_urn=str(urn)\n        )\n        return r, 200, {\"content-type\": \"application/xml\"}",
    "docstring": "Provisional route for GetFirstUrn request\n\n        :param urn: URN to filter the resource\n        :param inv: Inventory Identifier\n        :return: GetFirstUrn response"
  },
  {
    "code": "def get_variable_str(self):\n        if self.var_name is None:\n            prefix = ''\n        else:\n            prefix = self.var_name\n        suffix = str(self.var_value)\n        if len(suffix) == 0:\n            suffix = \"''\"\n        elif len(suffix) > self.__max_str_length_displayed__:\n            suffix = ''\n        if len(prefix) > 0 and len(suffix) > 0:\n            return prefix + '=' + suffix\n        else:\n            return prefix + suffix",
    "docstring": "Utility method to get the variable value or 'var_name=value' if name is not None.\n        Note that values with large string representations will not get printed\n\n        :return:"
  },
  {
    "code": "def on_expired(self):\n        print('Authentication expired')\n        self.is_authenticating.acquire()\n        self.is_authenticating.notify_all()\n        self.is_authenticating.release()",
    "docstring": "Device authentication expired."
  },
  {
    "code": "def block_to_svg(block=None):\n    block = working_block(block)\n    try:\n        from graphviz import Source\n        return Source(block_to_graphviz_string())._repr_svg_()\n    except ImportError:\n        raise PyrtlError('need graphviz installed (try \"pip install graphviz\")')",
    "docstring": "Return an SVG for the block."
  },
  {
    "code": "def object_absent(container, name, profile):\n    existing_object = __salt__['libcloud_storage.get_container_object'](container, name, profile)\n    if existing_object is None:\n        return state_result(True, \"Object already absent\", name, {})\n    else:\n        result = __salt__['libcloud_storage.delete_object'](container, name, profile)\n        return state_result(result, \"Deleted object\", name, {})",
    "docstring": "Ensures a object is absent.\n\n    :param container: Container name\n    :type  container: ``str``\n\n    :param name: Object name in cloud\n    :type  name: ``str``\n\n    :param profile: The profile key\n    :type  profile: ``str``"
  },
  {
    "code": "def token(cls: Type[CSVType], time: int) -> CSVType:\n        csv = cls()\n        csv.time = str(time)\n        return csv",
    "docstring": "Return CSV instance from time\n\n        :param time: Timestamp\n        :return:"
  },
  {
    "code": "def mask(self, masklist):\n        if not hasattr(masklist, '__len__'):\n            masklist = tuple(masklist)\n        if len(masklist) != len(self):\n            raise Exception(\"Masklist length (%s) must match length \"\n                            \"of DataTable (%s)\" % (len(masklist), len(self)))\n        new_datatable = DataTable()\n        for field in self.fields:\n            new_datatable[field] = list(compress(self[field], masklist))\n        return new_datatable",
    "docstring": "`masklist` is an array of Bools or equivalent.\n\n        This returns a new DataTable using only the rows that were True\n        (or equivalent) in the mask."
  },
  {
    "code": "def register_rpc(name=None):\n    def wrapper(func):\n        func_name = func.__name__\n        rpc_name = name or func_name\n        uwsgi.register_rpc(rpc_name, func)\n        _LOG.debug(\"Registering '%s' for RPC under '%s' alias ...\", func_name, rpc_name)\n        return func\n    return wrapper",
    "docstring": "Decorator. Allows registering a function for RPC.\n\n    * http://uwsgi.readthedocs.io/en/latest/RPC.html\n\n    Example:\n\n        .. code-block:: python\n\n            @register_rpc()\n            def expose_me():\n                do()\n\n\n    :param str|unicode name: RPC function name to associate\n        with decorated function.\n\n    :rtype: callable"
  },
  {
    "code": "def index(self, values=None, only_index=None):\n        assert self.indexable, \"Field not indexable\"\n        assert not only_index or self.has_index(only_index), \"Invalid index\"\n        if only_index:\n            only_index = only_index if isclass(only_index) else only_index.__class__\n        if values is None:\n            values = self.proxy_get()\n        for value in values:\n            if value is not None:\n                needs_to_check_uniqueness = bool(self.unique)\n                for index in self._indexes:\n                    if only_index and not isinstance(index, only_index):\n                        continue\n                    index.add(value, check_uniqueness=needs_to_check_uniqueness and index.handle_uniqueness)\n                    if needs_to_check_uniqueness and index.handle_uniqueness:\n                        needs_to_check_uniqueness = False",
    "docstring": "Index all values stored in the field, or only given ones if any."
  },
  {
    "code": "def set_to_cache(self):\n        queryset = self.get_queryset()\n        cache.set(self._get_cache_key(), {\n            'queryset':\n                [\n                    queryset.none(),\n                    queryset.query,\n                ],\n            'cls': self.__class__,\n            'search_fields': tuple(self.search_fields),\n            'max_results': int(self.max_results),\n            'url': str(self.get_url()),\n            'dependent_fields': dict(self.dependent_fields),\n        })",
    "docstring": "Add widget's attributes to Django's cache.\n\n        Split the QuerySet, to not pickle the result set."
  },
  {
    "code": "def get_app_name(mod_name):\n    rparts = list(reversed(mod_name.split('.')))\n    try:\n        try:\n            return rparts[rparts.index(MODELS_MODULE_NAME) + 1]\n        except ValueError:\n            return rparts[1]\n    except IndexError:\n        return mod_name",
    "docstring": "Retrieve application name from models.py module path\n\n    >>> get_app_name('testapp.models.foo')\n    'testapp'\n\n    'testapp' instead of 'some.testapp' for compatibility:\n    >>> get_app_name('some.testapp.models.foo')\n    'testapp'\n    >>> get_app_name('some.models.testapp.models.foo')\n    'testapp'\n    >>> get_app_name('testapp.foo')\n    'testapp'\n    >>> get_app_name('some.testapp.foo')\n    'testapp'"
  },
  {
    "code": "def remove_files(self, *filenames):\n        filenames = list_strings(filenames)\n        for dirpath, dirnames, fnames in os.walk(self.workdir):\n            for fname in fnames:\n                if fname in filenames:\n                    filepath = os.path.join(dirpath, fname)\n                    os.remove(filepath)",
    "docstring": "Remove all the files listed in filenames."
  },
  {
    "code": "def add_reading(self, reading):\n        is_break = False\n        utc = None\n        if reading.stream in self._break_streams:\n            is_break = True\n        if reading.stream in self._anchor_streams:\n            utc = self._anchor_streams[reading.stream](reading)\n        self.add_point(reading.reading_id, reading.raw_time, utc, is_break=is_break)",
    "docstring": "Add an IOTileReading."
  },
  {
    "code": "def _upload(auth_http, project_id, bucket_name, file_path, object_name, acl):\n    with open(file_path, 'rb') as f:\n        data = f.read()\n    content_type, content_encoding = mimetypes.guess_type(file_path)\n    headers = {\n        'x-goog-project-id': project_id,\n        'x-goog-api-version': API_VERSION,\n        'x-goog-acl': acl,\n        'Content-Length': '%d' % len(data)\n    }\n    if content_type: headers['Content-Type'] = content_type\n    if content_type: headers['Content-Encoding'] = content_encoding\n    try:\n        response, content = auth_http.request(\n            'http://%s.storage.googleapis.com/%s' % (bucket_name, object_name),\n            method='PUT',\n            headers=headers,\n            body=data)\n    except httplib2.ServerNotFoundError, se:\n        raise Error(404, 'Server not found.')\n    if response.status >= 300:\n        raise Error(response.status, response.reason)\n    return content",
    "docstring": "Uploads a file to Google Cloud Storage.\n\n    Args:\n        auth_http: An authorized httplib2.Http instance.\n        project_id: The project to upload to.\n        bucket_name: The bucket to upload to.\n        file_path: Path to the file to upload.\n        object_name: The name within the bucket to upload to.\n        acl: The ACL to assign to the uploaded file."
  },
  {
    "code": "def show_letter(\n            self,\n            s,\n            text_colour=[255, 255, 255],\n            back_colour=[0, 0, 0]\n        ):\n        if len(s) > 1:\n            raise ValueError('Only one character may be passed into this method')\n        previous_rotation = self._rotation\n        self._rotation -= 90\n        if self._rotation < 0:\n            self._rotation = 270\n        dummy_colour = [None, None, None]\n        pixel_list = [dummy_colour] * 8\n        pixel_list.extend(self._get_char_pixels(s))\n        pixel_list.extend([dummy_colour] * 16)\n        coloured_pixels = [\n            text_colour if pixel == [255, 255, 255] else back_colour\n            for pixel in pixel_list\n        ]\n        self.set_pixels(coloured_pixels)\n        self._rotation = previous_rotation",
    "docstring": "Displays a single text character on the LED matrix using the specified\n        colours"
  },
  {
    "code": "def request_password_reset(self, user_id):\n\t\tcontent = self._fetch(\"/user/%s/password/request_reset\" % (user_id), method=\"POST\")\n\t\treturn FastlyUser(self, content)",
    "docstring": "Requests a password reset for the specified user."
  },
  {
    "code": "def as_knock(self, created=False):\n        knock = {}\n        if self.should_knock(created):\n            for field, data in self._retrieve_data(None, self._knocker_data):\n                knock[field] = data\n        return knock",
    "docstring": "Returns a dictionary with the knock data built from _knocker_data"
  },
  {
    "code": "def as_dictionary(self):\n        return {\n            \"name\": self.name,\n            \"type\": self.type,\n            \"value\": remove_0x_prefix(self.value) if self.type == 'bytes32' else self.value\n        }",
    "docstring": "Return the parameter as a dictionary.\n\n        :return: dict"
  },
  {
    "code": "def create_blueprint(state):\n    blueprint = Blueprint(\n        'invenio_jsonschemas',\n        __name__,\n    )\n    @blueprint.route('/<path:schema_path>')\n    def get_schema(schema_path):\n        try:\n            schema_dir = state.get_schema_dir(schema_path)\n        except JSONSchemaNotFound:\n            abort(404)\n        resolved = request.args.get(\n            'resolved',\n            current_app.config.get('JSONSCHEMAS_RESOLVE_SCHEMA'),\n            type=int\n        )\n        with_refs = request.args.get(\n            'refs',\n            current_app.config.get('JSONSCHEMAS_REPLACE_REFS'),\n            type=int\n        ) or resolved\n        if resolved or with_refs:\n            schema = state.get_schema(\n                schema_path,\n                with_refs=with_refs,\n                resolved=resolved\n            )\n            return jsonify(schema)\n        else:\n            return send_from_directory(schema_dir, schema_path)\n    return blueprint",
    "docstring": "Create blueprint serving JSON schemas.\n\n    :param state: :class:`invenio_jsonschemas.ext.InvenioJSONSchemasState`\n        instance used to retrieve the schemas."
  },
  {
    "code": "def post_multipart(self, url, params, files):\n        resp = requests.post(\n            url,\n            data=params,\n            params=params,\n            files=files,\n            headers=self.headers,\n            allow_redirects=False,\n            auth=self.oauth\n        )\n        return self.json_parse(resp)",
    "docstring": "Generates and issues a multipart request for data files\n\n        :param url: a string, the url you are requesting\n        :param params: a dict, a key-value of all the parameters\n        :param files:  a dict, matching the form '{name: file descriptor}'\n\n        :returns: a dict parsed from the JSON response"
  },
  {
    "code": "def get_vm_extension(access_token, subscription_id, resource_group, vm_name, extension_name):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/resourceGroups/', resource_group,\n                        '/providers/Microsoft.Compute/virtualMachines/', vm_name,\n                        '/extensions/', extension_name,\n                        '?api-version=', COMP_API])\n    return do_get(endpoint, access_token)",
    "docstring": "Get details about a VM extension.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n        resource_group (str): Azure resource group name.\n        vm_name (str): Name of the virtual machine.\n        extension_name (str): VM extension name.\n\n    Returns:\n        HTTP response. JSON body of VM extension properties."
  },
  {
    "code": "def cached(func):\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        global cache\n        key = json.dumps((func, args, kwargs), sort_keys=True, default=str)\n        try:\n            return cache[key]\n        except KeyError:\n            pass\n        res = func(*args, **kwargs)\n        cache[key] = res\n        return res\n    wrapper._wrapped = func\n    return wrapper",
    "docstring": "Cache return values for multiple executions of func + args\n\n    For example::\n\n        @cached\n        def unit_get(attribute):\n            pass\n\n        unit_get('test')\n\n    will cache the result of unit_get + 'test' for future calls."
  },
  {
    "code": "def instantiate_for_read_and_search(handle_server_url, reverselookup_username, reverselookup_password, **config):\n        if handle_server_url is None and 'reverselookup_baseuri' not in config.keys():\n            raise TypeError('You must specify either \"handle_server_url\" or \"reverselookup_baseuri\".' + \\\n                ' Searching not possible without the URL of a search servlet.')\n        inst = EUDATHandleClient(\n            handle_server_url,\n            reverselookup_username=reverselookup_username,\n            reverselookup_password=reverselookup_password,\n            **config\n        )\n        return inst",
    "docstring": "Initialize client with read access and with search function.\n\n        :param handle_server_url: The URL of the Handle Server. May be None\n            (then, the default 'https://hdl.handle.net' is used).\n        :param reverselookup_username: The username to authenticate at the\n            reverse lookup servlet.\n        :param reverselookup_password: The password to authenticate at the\n            reverse lookup servlet.\n        :param \\**config: More key-value pairs may be passed that will be passed\n            on to the constructor as config. Config options from the\n            credentials object are overwritten by this.\n        :return: An instance of the client."
  },
  {
    "code": "def set(cls, **kwargs):\n        global SCOUT_PYTHON_VALUES\n        for key, value in kwargs.items():\n            SCOUT_PYTHON_VALUES[key] = value",
    "docstring": "Sets a configuration value for the Scout agent. Values set here will\n        not override values set in ENV."
  },
  {
    "code": "def post(self, path, payload=None, headers=None):\n        return self._request('post', path, payload, headers)",
    "docstring": "HTTP POST operation.\n\n        :param path: URI Path\n        :param payload: HTTP Body\n        :param headers: HTTP Headers\n\n        :raises ApiError: Raises if the remote server encountered an error.\n        :raises ApiConnectionError: Raises if there was a connectivity issue.\n\n        :return: Response"
  },
  {
    "code": "def unicode_props(self, props, value, in_group=False, negate=False):\n        category = None\n        if props.startswith(\"^\"):\n            negate = not negate\n        if props.startswith(\"^\"):\n            props = props[1:]\n        if value:\n            if _uniprops.is_enum(props):\n                category = props\n                props = value\n            elif value in ('y', 'yes', 't', 'true'):\n                category = 'binary'\n            elif value in ('n', 'no', 'f', 'false'):\n                category = 'binary'\n                negate = not negate\n            else:\n                raise ValueError('Invalid Unicode property!')\n        v = _uniprops.get_unicode_property((\"^\" if negate else \"\") + props, category, self.is_bytes)\n        if not in_group:\n            if not v:\n                v = '^%s' % ('\\x00-\\xff' if self.is_bytes else _uniprops.UNICODE_RANGE)\n            v = \"[%s]\" % v\n        properties = [v]\n        return properties",
    "docstring": "Insert Unicode properties.\n\n        Unicode properties are very forgiving.\n        Case doesn't matter and `[ -_]` will be stripped out."
  },
  {
    "code": "def secret_file(filename):\n    filestat = os.stat(abspath(filename))\n    if stat.S_ISREG(filestat.st_mode) == 0 and \\\n       stat.S_ISLNK(filestat.st_mode) == 0:\n        e_msg = \"Secret file %s must be a real file or symlink\" % filename\n        raise aomi.exceptions.AomiFile(e_msg)\n    if platform.system() != \"Windows\":\n        if filestat.st_mode & stat.S_IROTH or \\\n           filestat.st_mode & stat.S_IWOTH or \\\n           filestat.st_mode & stat.S_IWGRP:\n            e_msg = \"Secret file %s has too loose permissions\" % filename\n            raise aomi.exceptions.AomiFile(e_msg)",
    "docstring": "Will check the permissions of things which really\n    should be secret files"
  },
  {
    "code": "def asfreq(self, freq, method=None, how=None, normalize=False,\n               fill_value=None):\n        from pandas.core.resample import asfreq\n        return asfreq(self, freq, method=method, how=how, normalize=normalize,\n                      fill_value=fill_value)",
    "docstring": "Convert TimeSeries to specified frequency.\n\n        Optionally provide filling method to pad/backfill missing values.\n\n        Returns the original data conformed to a new index with the specified\n        frequency. ``resample`` is more appropriate if an operation, such as\n        summarization, is necessary to represent the data at the new frequency.\n\n        Parameters\n        ----------\n        freq : DateOffset object, or string\n        method : {'backfill'/'bfill', 'pad'/'ffill'}, default None\n            Method to use for filling holes in reindexed Series (note this\n            does not fill NaNs that already were present):\n\n            * 'pad' / 'ffill': propagate last valid observation forward to next\n              valid\n            * 'backfill' / 'bfill': use NEXT valid observation to fill\n        how : {'start', 'end'}, default end\n            For PeriodIndex only, see PeriodIndex.asfreq\n        normalize : bool, default False\n            Whether to reset output index to midnight\n        fill_value : scalar, optional\n            Value to use for missing values, applied during upsampling (note\n            this does not fill NaNs that already were present).\n\n            .. versionadded:: 0.20.0\n\n        Returns\n        -------\n        converted : same type as caller\n\n        See Also\n        --------\n        reindex\n\n        Notes\n        -----\n        To learn more about the frequency strings, please see `this link\n        <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.\n\n        Examples\n        --------\n\n        Start by creating a series with 4 one minute timestamps.\n\n        >>> index = pd.date_range('1/1/2000', periods=4, freq='T')\n        >>> series = pd.Series([0.0, None, 2.0, 3.0], index=index)\n        >>> df = pd.DataFrame({'s':series})\n        >>> df\n                               s\n        2000-01-01 00:00:00    0.0\n        2000-01-01 00:01:00    NaN\n        2000-01-01 00:02:00    2.0\n        2000-01-01 00:03:00    3.0\n\n        Upsample the series into 30 second bins.\n\n        >>> df.asfreq(freq='30S')\n                               s\n        2000-01-01 00:00:00    0.0\n        2000-01-01 00:00:30    NaN\n        2000-01-01 00:01:00    NaN\n        2000-01-01 00:01:30    NaN\n        2000-01-01 00:02:00    2.0\n        2000-01-01 00:02:30    NaN\n        2000-01-01 00:03:00    3.0\n\n        Upsample again, providing a ``fill value``.\n\n        >>> df.asfreq(freq='30S', fill_value=9.0)\n                               s\n        2000-01-01 00:00:00    0.0\n        2000-01-01 00:00:30    9.0\n        2000-01-01 00:01:00    NaN\n        2000-01-01 00:01:30    9.0\n        2000-01-01 00:02:00    2.0\n        2000-01-01 00:02:30    9.0\n        2000-01-01 00:03:00    3.0\n\n        Upsample again, providing a ``method``.\n\n        >>> df.asfreq(freq='30S', method='bfill')\n                               s\n        2000-01-01 00:00:00    0.0\n        2000-01-01 00:00:30    NaN\n        2000-01-01 00:01:00    NaN\n        2000-01-01 00:01:30    2.0\n        2000-01-01 00:02:00    2.0\n        2000-01-01 00:02:30    3.0\n        2000-01-01 00:03:00    3.0"
  },
  {
    "code": "def preprocess_files(self, prefix):\n            if prefix is None: return\n            files = (\"bin/yang2dsdl\", \"man/man1/yang2dsdl.1\",\n                     \"pyang/plugins/jsonxsl.py\")\n            regex = re.compile(\"^(.*)/usr/local(.*)$\")\n            for f in files:\n                  inf = open(f)\n                  cnt = inf.readlines()\n                  inf.close()\n                  ouf = open(f,\"w\")\n                  for line in cnt:\n                        mo = regex.search(line)\n                        if mo is None:\n                              ouf.write(line)\n                        else:\n                              ouf.write(mo.group(1) + prefix + mo.group(2) +\n                                        \"\\n\")\n                  ouf.close()",
    "docstring": "Change the installation prefix where necessary."
  },
  {
    "code": "def convert_vec2_to_vec4(scale, data):\n    it = iter(data)\n    while True:\n        yield next(it) * scale\n        yield next(it) * scale\n        yield 0.0\n        yield 1.0",
    "docstring": "transforms an array of 2d coords into 4d"
  },
  {
    "code": "def get_tree_collection_strings(self, scale=1, guide_tree=None):\n        records = [self.collection[i] for i in self.indices]\n        return TreeCollectionTaskInterface().scrape_args(records)",
    "docstring": "Function to get input strings for tree_collection\n        tree_collection needs distvar, genome_map and labels -\n        these are returned in the order above"
  },
  {
    "code": "def set_all_xlims(self, xlim, dx, xscale, fontsize=None):\n        self._set_all_lims('x', xlim, dx, xscale, fontsize)\n        return",
    "docstring": "Set limits and ticks for x axis for whole figure.\n\n        This will set x axis limits and tick marks for the entire figure.\n        It can be overridden in the SinglePlot class.\n\n        Args:\n            xlim (len-2 list of floats): The limits for the axis.\n            dx (float): Amount to increment by between the limits.\n            xscale (str): Scale of the axis. Either `log` or `lin`.\n            fontsize (int, optional): Set fontsize for x axis tick marks.\n                Default is None."
  },
  {
    "code": "def set_account_password(self, account, raw_password):\n        luser = self._get_account(account.username)\n        changes = changeset(luser, {\n            'password': raw_password,\n        })\n        save(changes, database=self._database)",
    "docstring": "Account's password was changed."
  },
  {
    "code": "def sample(self, count, return_index=False):\n        samples, index = sample.sample_surface(self, count)\n        if return_index:\n            return samples, index\n        return samples",
    "docstring": "Return random samples distributed normally across the\n        surface of the mesh\n\n        Parameters\n        ---------\n        count : int\n          Number of points to sample\n        return_index : bool\n          If True will also return the index of which face each\n          sample was taken from.\n\n        Returns\n        ---------\n        samples : (count, 3) float\n          Points on surface of mesh\n        face_index : (count, ) int\n          Index of self.faces"
  },
  {
    "code": "def delete_where_unique(cls, ip, object_id, location):\r\n        result = cls.where_unique(ip, object_id, location)\r\n        if result is None:\r\n            return None\r\n        result.delete()\r\n        return True",
    "docstring": "delete by ip and object id"
  },
  {
    "code": "def get_enum_key(key, choices):\n    if key in choices:\n        return key\n    keys = [k for k in choices if k.startswith(key)]\n    if len(keys) == 1:\n        return keys[0]",
    "docstring": "Get an enum by prefix or equality"
  },
  {
    "code": "def get_Tuple_params(tpl):\n    try:\n        return tpl.__tuple_params__\n    except AttributeError:\n        try:\n            if tpl.__args__ is None:\n                return None\n            if tpl.__args__[0] == ():\n                return ()\n            else:\n                if tpl.__args__[-1] is Ellipsis:\n                    return tpl.__args__[:-1] if len(tpl.__args__) > 1 else None\n                else:\n                    return tpl.__args__\n        except AttributeError:\n            return None",
    "docstring": "Python version independent function to obtain the parameters\n    of a typing.Tuple object.\n    Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that.\n    Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1."
  },
  {
    "code": "def has_required_params(self):\n        return self.consumer_key and\\\n                self.consumer_secret and\\\n                self.resource_link_id and\\\n                self.launch_url",
    "docstring": "Check if required parameters for a tool launch are set."
  },
  {
    "code": "def render(self, data, accepted_media_type=None, renderer_context=None):\n        renderer_context = renderer_context or {}\n        callback = self.get_callback(renderer_context)\n        json = super(JSONPRenderer, self).render(data, accepted_media_type,\n                                                 renderer_context)\n        return callback.encode(self.charset) + b'(' + json + b');'",
    "docstring": "Renders into jsonp, wrapping the json output in a callback function.\n\n        Clients may set the callback function name using a query parameter\n        on the URL, for example: ?callback=exampleCallbackName"
  },
  {
    "code": "def secret_write(backend,entry):\n    path,value=entry.split('=')\n    if value.startswith('@'):\n        with open(value[1:]) as vfile:\n            value = vfile.read()\n    click.echo(click.style('%s - Writing secret' % get_datetime(), fg='green'))\n    check_and_print(\n        DKCloudCommandRunner.secret_write(backend.dki,path,value))",
    "docstring": "Write a secret"
  },
  {
    "code": "def parse_subargs(module, parser, method, opts):\n    module.cli_args(parser)\n    subargs = parser.parse_args(opts)\n    return subargs",
    "docstring": "Attach argument parser for action specific options.\n\n    Arguments\n    ---------\n    module : module\n        name of module to extract action from\n    parser : argparser\n        argparser object to attach additional arguments to\n    method : str\n        name of method (morris, sobol, etc).\n        Must match one of the available submodules\n    opts : list\n        A list of argument options to parse\n\n    Returns\n    ---------\n    subargs : argparser namespace object"
  },
  {
    "code": "def schedule_deleted(sender, instance, **kwargs):\n    from contentstore.tasks import deactivate_schedule\n    deactivate_schedule.delay(str(instance.scheduler_schedule_id))",
    "docstring": "Fires off the celery task to ensure that this schedule is deactivated\n\n    Arguments:\n        sender {class} -- The model class, always Schedule\n        instance {Schedule} --\n            The instance of the schedule that we want to deactivate"
  },
  {
    "code": "def delete_tag_from_job(user, job_id, tag_id):\n    _JJT = models.JOIN_JOBS_TAGS\n    job = v1_utils.verify_existence_and_get(job_id, _TABLE)\n    if not user.is_in_team(job['team_id']):\n        raise dci_exc.Unauthorized()\n    v1_utils.verify_existence_and_get(tag_id, models.TAGS)\n    query = _JJT.delete().where(sql.and_(_JJT.c.tag_id == tag_id,\n                                         _JJT.c.job_id == job_id))\n    try:\n        flask.g.db_conn.execute(query)\n    except sa_exc.IntegrityError:\n        raise dci_exc.DCICreationConflict('tag', 'tag_id')\n    return flask.Response(None, 204, content_type='application/json')",
    "docstring": "Delete a tag from a job."
  },
  {
    "code": "def load(self, **kwargs):\n        if LooseVersion(self.tmos_ver) == LooseVersion('11.6.0'):\n            return self._load_11_6(**kwargs)\n        else:\n            return super(Rule, self)._load(**kwargs)",
    "docstring": "Custom load method to address issue in 11.6.0 Final,\n\n        where non existing objects would be True."
  },
  {
    "code": "def complete_media(self, text, line, begidx, endidx):\n        choices = {'actor': query_actors,\n                   'director': TabCompleteExample.static_list_directors,\n                   'movie_file': (self.path_complete,)\n                   }\n        completer = argparse_completer.AutoCompleter(TabCompleteExample.media_parser,\n                                                     self,\n                                                     arg_choices=choices)\n        tokens, _ = self.tokens_for_completion(line, begidx, endidx)\n        results = completer.complete_command(tokens, text, line, begidx, endidx)\n        return results",
    "docstring": "Adds tab completion to media"
  },
  {
    "code": "def match(Class, path, pattern, flags=re.I, sortkey=None, ext=None):\n        return sorted(\n            [\n                Class(fn=fn)\n                for fn in rglob(path, f\"*{ext or ''}\")\n                if re.search(pattern, os.path.basename(fn), flags=flags) is not None\n                and os.path.basename(fn)[0] != '~'\n            ],\n            key=sortkey,\n        )",
    "docstring": "for a given path and regexp pattern, return the files that match"
  },
  {
    "code": "def chunked(iterable, n):\n    iterable = iter(iterable)\n    while 1:\n        t = tuple(islice(iterable, n))\n        if t:\n            yield t\n        else:\n            return",
    "docstring": "Returns chunks of n length of iterable\n\n    If len(iterable) % n != 0, then the last chunk will have length\n    less than n.\n\n    Example:\n\n    >>> chunked([1, 2, 3, 4, 5], 2)\n    [(1, 2), (3, 4), (5,)]"
  },
  {
    "code": "def get_datanode_fp_meta(fp):\n    directory_meta = list(CMIP5_DATANODE_FP_ATTS)\n    meta = get_dir_meta(fp, directory_meta)\n    meta.update(get_cmor_fname_meta(fp))\n    return meta",
    "docstring": "Processes a datanode style file path.\n\n    Section 3.2 of the `Data Reference Syntax`_ details:\n\n        It is recommended that ESGF data nodes should layout datasets\n        on disk mapping DRS components to directories as:\n\n            <activity>/<product>/<institute>/<model>/<experiment>/\n            <frequency>/<modeling_realm>/<mip_table>/<ensemble_member>/\n            <version_number>/<variable_name>/<CMOR filename>.nc\n\n    Arguments:\n        fp (str): A file path conforming to DRS spec.\n\n    Returns:\n        dict: Metadata as extracted from the file path.\n\n    .. _Data Reference Syntax:\n       http://cmip-pcmdi.llnl.gov/cmip5/docs/cmip5_data_reference_syntax.pdf"
  },
  {
    "code": "def exp10(x, context=None):\n    return _apply_function_in_current_context(\n        BigFloat,\n        mpfr.mpfr_exp10,\n        (BigFloat._implicit_convert(x),),\n        context,\n    )",
    "docstring": "Return ten raised to the power x."
  },
  {
    "code": "def install_program(self):\n        text = templ_program.render(**self.options)\n        config = Configuration(self.buildout, self.program + '.conf', {\n            'deployment': self.deployment_name,\n            'directory': os.path.join(self.options['etc-directory'], 'conf.d'),\n            'text': text})\n        return [config.install()]",
    "docstring": "install supervisor program config file"
  },
  {
    "code": "def set_shellwidget(self, shellwidget):\n        self.shellwidget = shellwidget\n        shellwidget.set_figurebrowser(self)\n        shellwidget.sig_new_inline_figure.connect(self._handle_new_figure)",
    "docstring": "Bind the shellwidget instance to the figure browser"
  },
  {
    "code": "def define_wide_deep_flags():\n  flags_core.define_base()\n  flags_core.define_benchmark()\n  flags_core.define_performance(\n      num_parallel_calls=False, inter_op=True, intra_op=True,\n      synthetic_data=False, max_train_steps=False, dtype=False,\n      all_reduce_alg=False)\n  flags.adopt_module_key_flags(flags_core)\n  flags.DEFINE_enum(\n      name=\"model_type\", short_name=\"mt\", default=\"wide_deep\",\n      enum_values=['wide', 'deep', 'wide_deep'],\n      help=\"Select model topology.\")\n  flags.DEFINE_boolean(\n      name=\"download_if_missing\", default=True, help=flags_core.help_wrap(\n          \"Download data to data_dir if it is not already present.\"))",
    "docstring": "Add supervised learning flags, as well as wide-deep model type."
  },
  {
    "code": "def sendCommand(self, command):\n    data = { 'rapi' : command }\n    full_url = self.url + urllib.parse.urlencode(data)\n    data = urllib.request.urlopen(full_url)\n    response = re.search('\\<p>&gt;\\$(.+)\\<script', data.read().decode('utf-8'))\n    if response == None:\n      response = re.search('\\>\\>\\$(.+)\\<p>', data.read().decode('utf-8'))\n    return response.group(1).split()",
    "docstring": "Sends a command through the web interface of the charger and parses the response"
  },
  {
    "code": "def _get_mean_and_median(hist: Hist) -> Tuple[float, float]:\n    x = ctypes.c_double(0)\n    q = ctypes.c_double(0.5)\n    hist.ComputeIntegral()\n    hist.GetQuantiles(1, x, q)\n    mean = hist.GetMean()\n    return (mean, x.value)",
    "docstring": "Retrieve the mean and median from a ROOT histogram.\n\n    Note:\n        These values are not so trivial to calculate without ROOT, as they are the bin values\n        weighted by the bin content.\n\n    Args:\n        hist: Histogram from which the values will be extract.\n    Returns:\n        mean, median of the histogram."
  },
  {
    "code": "def byaxis(self):\n        space = self\n        class NpyTensorSpacebyaxis(object):\n            def __getitem__(self, indices):\n                try:\n                    iter(indices)\n                except TypeError:\n                    newshape = space.shape[indices]\n                else:\n                    newshape = tuple(space.shape[i] for i in indices)\n                if isinstance(space.weighting, ArrayWeighting):\n                    new_array = np.asarray(space.weighting.array[indices])\n                    weighting = NumpyTensorSpaceArrayWeighting(\n                        new_array, space.weighting.exponent)\n                else:\n                    weighting = space.weighting\n                return type(space)(newshape, space.dtype, weighting=weighting)\n            def __repr__(self):\n                return repr(space) + '.byaxis'\n        return NpyTensorSpacebyaxis()",
    "docstring": "Return the subspace defined along one or several dimensions.\n\n        Examples\n        --------\n        Indexing with integers or slices:\n\n        >>> space = odl.rn((2, 3, 4))\n        >>> space.byaxis[0]\n        rn(2)\n        >>> space.byaxis[1:]\n        rn((3, 4))\n\n        Lists can be used to stack spaces arbitrarily:\n\n        >>> space.byaxis[[2, 1, 2]]\n        rn((4, 3, 4))"
  },
  {
    "code": "def check_boundary_lines_similar(l_1, l_2):\n    num_matches = 0\n    if (type(l_1) != list) or (type(l_2) != list) or (len(l_1) != len(l_2)):\n        return 0\n    num_elements = len(l_1)\n    for i in xrange(0, num_elements):\n        if l_1[i].isdigit() and l_2[i].isdigit():\n            num_matches += 1\n        else:\n            l1_str = l_1[i].lower()\n            l2_str = l_2[i].lower()\n            if (l1_str[0] == l2_str[0]) and \\\n                    (l1_str[len(l1_str) - 1] == l2_str[len(l2_str) - 1]):\n                num_matches = num_matches + 1\n    if (len(l_1) == 0) or (float(num_matches) / float(len(l_1)) < 0.9):\n        return 0\n    else:\n        return 1",
    "docstring": "Compare two lists to see if their elements are roughly the same.\n    @param l_1: (list) of strings.\n    @param l_2: (list) of strings.\n    @return: (int) 1/0."
  },
  {
    "code": "def get(self, value):\n        config = self.get_block('vrf definition %s' % value)\n        if not config:\n            return None\n        response = dict(vrf_name=value)\n        response.update(self._parse_rd(config))\n        response.update(self._parse_description(config))\n        config = self.get_block('no ip routing vrf %s' % value)\n        if config:\n            response['ipv4_routing'] = False\n        else:\n            response['ipv4_routing'] = True\n        config = self.get_block('no ipv6 unicast-routing vrf %s' % value)\n        if config:\n            response['ipv6_routing'] = False\n        else:\n            response['ipv6_routing'] = True\n        return response",
    "docstring": "Returns the VRF configuration as a resource dict.\n\n        Args:\n            value (string): The vrf name to retrieve from the\n                running configuration.\n\n        Returns:\n            A Python dict object containing the VRF attributes as\n                key/value pairs."
  },
  {
    "code": "def find_faderport_output_name(number=0):\n    outs = [i for i in mido.get_output_names() if i.lower().startswith('faderport')]\n    if 0 <= number < len(outs):\n        return outs[number]\n    else:\n        return None",
    "docstring": "Find the MIDI output name for a connected FaderPort.\n\n    NOTE! Untested for more than one FaderPort attached.\n    :param number: 0 unless you've got more than one FaderPort attached.\n                   In which case 0 is the first, 1 is the second etc\n    :return: Port name or None"
  },
  {
    "code": "def plot_delta_m(fignum, B, DM, Bcr, s):\n    plt.figure(num=fignum)\n    plt.clf()\n    if not isServer:\n        plt.figtext(.02, .01, version_num)\n    plt.plot(B, DM, 'b')\n    plt.xlabel('B (T)')\n    plt.ylabel('Delta M')\n    linex = [0, Bcr, Bcr]\n    liney = [old_div(DM[0], 2.), old_div(DM[0], 2.), 0]\n    plt.plot(linex, liney, 'r')\n    plt.title(s)",
    "docstring": "function to plot Delta M curves\n\n    Parameters\n    __________\n    fignum : matplotlib figure number\n    B : array of field values\n    DM : array of difference between top and bottom curves in hysteresis loop\n    Bcr : coercivity of remanence\n    s : specimen name"
  },
  {
    "code": "def _formatOntologyTermObject(self, terms, element_type):\n        elementClause = None\n        if not isinstance(terms, collections.Iterable):\n            terms = [terms]\n        elements = []\n        for term in terms:\n            if term.term_id:\n                elements.append('?{} = <{}> '.format(\n                    element_type, term.term_id))\n            else:\n                elements.append('?{} = <{}> '.format(\n                    element_type, self._toNamespaceURL(term.term)))\n        elementClause = \"({})\".format(\" || \".join(elements))\n        return elementClause",
    "docstring": "Formats the ontology term object for query"
  },
  {
    "code": "def authenticate(api_key, api_url, **kwargs):\n    muddle = Muddle(**kwargs)\n    muddle.authenticate(api_key, api_url)\n    return muddle",
    "docstring": "Returns a muddle instance, with API key and url set for requests."
  },
  {
    "code": "def _transition_loop(self):\n        while self._transitions:\n            start = time.time()\n            for transition in self._transitions:\n                transition.step()\n                if transition.finished:\n                    self._transitions.remove(transition)\n            time_delta = time.time() - start\n            sleep_time = max(0, self.MIN_STEP_TIME - time_delta)\n            time.sleep(sleep_time)",
    "docstring": "Execute all queued transitions step by step."
  },
  {
    "code": "def get_user(self, username):\n        User = get_user_model()\n        try:\n            user = User.objects.get(**{\n                User.USERNAME_FIELD: username,\n            })\n            if user.is_active:\n                raise ActivationError(\n                    self.ALREADY_ACTIVATED_MESSAGE,\n                    code='already_activated'\n                )\n            return user\n        except User.DoesNotExist:\n            raise ActivationError(\n                self.BAD_USERNAME_MESSAGE,\n                code='bad_username'\n            )",
    "docstring": "Given the verified username, look up and return the\n        corresponding user account if it exists, or raising\n        ``ActivationError`` if it doesn't."
  },
  {
    "code": "def sendExact( signal=Any, sender=Anonymous, *arguments, **named ):\n    responses = []\n    for receiver in liveReceivers(getReceivers(sender, signal)):\n        response = robustapply.robustApply(\n            receiver,\n            signal=signal,\n            sender=sender,\n            *arguments,\n            **named\n        )\n        responses.append((receiver, response))\n    return responses",
    "docstring": "Send signal only to those receivers registered for exact message\n\n    sendExact allows for avoiding Any/Anonymous registered\n    handlers, sending only to those receivers explicitly\n    registered for a particular signal on a particular\n    sender."
  },
  {
    "code": "def write_warc(self, resources=None, dumpfile=None):\n        try:\n            from warc import WARCFile, WARCHeader, WARCRecord\n        except:\n            raise DumpError(\"Failed to load WARC library\")\n        wf = WARCFile(dumpfile, mode=\"w\", compress=self.compress)\n        for resource in resources:\n            wh = WARCHeader({})\n            wh.url = resource.uri\n            wh.ip_address = None\n            wh.date = resource.lastmod\n            wh.content_type = 'text/plain'\n            wh.result_code = 200\n            wh.checksum = 'aabbcc'\n            wh.location = self.archive_path(resource.path)\n            wf.write_record(WARCRecord(header=wh, payload=resource.path))\n        wf.close()\n        warcsize = os.path.getsize(dumpfile)\n        self.logging.info(\n            \"Wrote WARC file dump %s with size %d bytes\" %\n            (dumpfile, warcsize))",
    "docstring": "Write a WARC dump file.\n\n        WARC support is not part of ResourceSync v1.0 (Z39.99 2014) but is left\n        in this library for experimentation."
  },
  {
    "code": "def normalize(seq):\n    s = float(sum(seq))\n    return [v/s for v in seq]",
    "docstring": "Scales each number in the sequence so that the sum of all numbers equals 1."
  },
  {
    "code": "def GetUserInfo(knowledge_base, user):\n  if \"\\\\\" in user:\n    domain, user = user.split(\"\\\\\", 1)\n    users = [\n        u for u in knowledge_base.users\n        if u.username == user and u.userdomain == domain\n    ]\n  else:\n    users = [u for u in knowledge_base.users if u.username == user]\n  if not users:\n    return\n  else:\n    return users[0]",
    "docstring": "Get a User protobuf for a specific user.\n\n  Args:\n    knowledge_base: An rdf_client.KnowledgeBase object.\n    user: Username as string. May contain domain like DOMAIN\\\\user.\n\n  Returns:\n    A User rdfvalue or None"
  },
  {
    "code": "def monday_of_week(year, week):\n    str_time = time.strptime('{0} {1} 1'.format(year, week), '%Y %W %w')\n    date = timezone.datetime(year=str_time.tm_year, month=str_time.tm_mon,\n                             day=str_time.tm_mday, tzinfo=timezone.utc)\n    if timezone.datetime(year, 1, 4).isoweekday() > 4:\n        date -= timezone.timedelta(days=7)\n    return date",
    "docstring": "Returns a datetime for the monday of the given week of the given year."
  },
  {
    "code": "def done(self):\n        return self._exception != self._SENTINEL or self._result != self._SENTINEL",
    "docstring": "Return True the future is done, False otherwise.\n\n        This still returns True in failure cases; checking :meth:`result` or\n        :meth:`exception` is the canonical way to assess success or failure."
  },
  {
    "code": "def load_table(self, table):\n        region = table.database if table.database else self.default_region\n        resource_name, collection_name = table.table.split('_', 1)\n        boto_region_name = region.replace('_', '-')\n        resource = self.boto3_session.resource(resource_name, region_name=boto_region_name)\n        if not hasattr(resource, collection_name):\n            raise QueryError(\n                'Unknown collection <{0}> of resource <{1}>'.format(collection_name, resource_name))\n        self.attach_region(region)\n        self.refresh_table(region, table.table, resource, getattr(resource, collection_name))",
    "docstring": "Load resources as specified by given table into our db."
  },
  {
    "code": "def _parse_normalization(normalization):\n        parsed_normalization = None\n        if isinstance(normalization, dict):\n            if len(normalization.keys()) == 1:\n                items = list(normalization.items())[0]\n                if len(items) == 2:\n                    if items[1] and isinstance(items[1], dict):\n                        parsed_normalization = items\n                    else:\n                        parsed_normalization = items[0]\n        elif isinstance(normalization, STR_TYPE):\n            parsed_normalization = normalization\n        return parsed_normalization",
    "docstring": "Parse a normalization item.\n\n        Transform dicts into a tuple containing the normalization\n        options. If a string is found, the actual value is used.\n\n        Args:\n            normalization: Normalization to parse.\n\n        Returns:\n            Tuple or string containing the parsed normalization."
  },
  {
    "code": "def add(self, **kwargs):\n    new_element = self._message_descriptor._concrete_class(**kwargs)\n    new_element._SetListener(self._message_listener)\n    self._values.append(new_element)\n    if not self._message_listener.dirty:\n      self._message_listener.Modified()\n    return new_element",
    "docstring": "Adds a new element at the end of the list and returns it. Keyword\n    arguments may be used to initialize the element."
  },
  {
    "code": "def mark_deactivated(self,request,queryset):\n        rows_updated = queryset.update(Active=False, End=datetime.date.today() )\n        if rows_updated == 1:\n            message_bit = \"1 cage was\"\n        else:\n            message_bit = \"%s cages were\" % rows_updated\n        self.message_user(request, \"%s successfully marked as deactivated.\" % message_bit)",
    "docstring": "An admin action for marking several cages as inactive.\n\t\t\n        This action sets the selected cages as Active=False and Death=today.\n        This admin action also shows as the output the number of mice sacrificed."
  },
  {
    "code": "def add(self, user, status=None, symmetrical=False):\n        if not status:\n            status = RelationshipStatus.objects.following()\n        relationship, created = Relationship.objects.get_or_create(\n            from_user=self.instance,\n            to_user=user,\n            status=status,\n            site=Site.objects.get_current()\n        )\n        if symmetrical:\n            return (relationship, user.relationships.add(self.instance, status, False))\n        else:\n            return relationship",
    "docstring": "Add a relationship from one user to another with the given status,\n        which defaults to \"following\".\n\n        Adding a relationship is by default asymmetrical (akin to following\n        someone on twitter).  Specify a symmetrical relationship (akin to being\n        friends on facebook) by passing in :param:`symmetrical` = True\n\n        .. note::\n\n            If :param:`symmetrical` is set, the function will return a tuple\n            containing the two relationship objects created"
  },
  {
    "code": "def check( state_engine, nameop, block_id, checked_ops ):\n    namespace_id = nameop['namespace_id']\n    sender = nameop['sender']\n    if not state_engine.is_namespace_revealed( namespace_id ):\n       log.warning(\"Namespace '%s' is not revealed\" % namespace_id )\n       return False\n    revealed_namespace = state_engine.get_namespace_reveal( namespace_id )\n    if revealed_namespace['recipient'] != sender:\n       log.warning(\"Namespace '%s' is not owned by '%s' (but by %s)\" % (namespace_id, sender, revealed_namespace['recipient']))\n       return False\n    if state_engine.is_namespace_ready( namespace_id ):\n       log.warning(\"Namespace '%s' is already registered\" % namespace_id )\n       return False\n    nameop['sender_pubkey'] = revealed_namespace['sender_pubkey']\n    nameop['address'] = revealed_namespace['address']\n    return True",
    "docstring": "Verify the validity of a NAMESPACE_READY operation.\n    It is only valid if it has been imported by the same sender as\n    the corresponding NAMESPACE_REVEAL, and the namespace is still\n    in the process of being imported."
  },
  {
    "code": "def run(self):\n        try:\n            self.initialize_connection()\n        except ChromecastConnectionError:\n            self._report_connection_status(\n                ConnectionStatus(CONNECTION_STATUS_DISCONNECTED,\n                                 NetworkAddress(self.host, self.port)))\n            return\n        self.heartbeat_controller.reset()\n        self._force_recon = False\n        logging.debug(\"Thread started...\")\n        while not self.stop.is_set():\n            if self.run_once() == 1:\n                break\n        self._cleanup()",
    "docstring": "Connect to the cast and start polling the socket."
  },
  {
    "code": "def linkorcopy(self, src, dst):\n        if os.path.isdir(dst):\n            log.warn('linkorcopy given a directory as destination. '\n                     'Use caution.')\n            log.debug('src: %s  dst: %s', src, dst)\n        elif os.path.exists(dst):\n            os.unlink(dst)\n        elif not os.path.exists(os.path.dirname(dst)):\n            os.makedirs(os.path.dirname(dst))\n        if self.linkfiles:\n            log.debug('Linking: %s -> %s', src, dst)\n            os.link(src, dst)\n        else:\n            log.debug('Copying: %s -> %s', src, dst)\n            shutil.copy2(src, dst)",
    "docstring": "hardlink src file to dst if possible, otherwise copy."
  },
  {
    "code": "def _prepare_tokens_for_encode(tokens):\n  prepared_tokens = []\n  def _prepare_token(t, next_t):\n    skip_next = False\n    t = _escape(t)\n    if next_t == \" \":\n      t += \"_\"\n      skip_next = True\n    return t, skip_next\n  next_tokens = tokens[1:] + [None]\n  skip_single_token = False\n  for token, next_token in zip(tokens, next_tokens):\n    if skip_single_token:\n      skip_single_token = False\n      continue\n    if token == _UNDERSCORE_REPLACEMENT:\n      t1, t2 = _UNDERSCORE_REPLACEMENT[:2], _UNDERSCORE_REPLACEMENT[2:]\n      t1, _ = _prepare_token(t1, None)\n      t2, _ = _prepare_token(t2, next_token)\n      prepared_tokens.append(t1)\n      prepared_tokens.append(t2)\n      continue\n    token, skip_single_token = _prepare_token(token, next_token)\n    prepared_tokens.append(token)\n  return prepared_tokens",
    "docstring": "Prepare tokens for encoding.\n\n  Tokens followed by a single space have \"_\" appended and the single space token\n  is dropped.\n\n  If a token is _UNDERSCORE_REPLACEMENT, it is broken up into 2 tokens.\n\n  Args:\n    tokens: `list<str>`, tokens to prepare.\n\n  Returns:\n    `list<str>` prepared tokens."
  },
  {
    "code": "def fetch_url(url, dest, parent_to_remove_before_fetch):\n    logger.debug('Downloading file {} from {}', dest, url)\n    try:\n        shutil.rmtree(parent_to_remove_before_fetch)\n    except FileNotFoundError:\n        pass\n    os.makedirs(parent_to_remove_before_fetch)\n    resp = requests.get(url, stream=True)\n    with open(dest, 'wb') as fetch_file:\n        for chunk in resp.iter_content(chunk_size=32 * 1024):\n            fetch_file.write(chunk)",
    "docstring": "Helper function to fetch a file from a URL."
  },
  {
    "code": "def cache_finite_samples(f):\n\tcache = {}\n\tdef wrap(*args):\n\t\tkey = FRAME_RATE, args\n\t\tif key not in cache:\n\t\t\tcache[key] = [sample for sample in f(*args)]\n\t\treturn (sample for sample in cache[key])\n\treturn wrap",
    "docstring": "Decorator to cache audio samples produced by the wrapped generator."
  },
  {
    "code": "def recipe_details(recipe_id, lang=\"en\"):\n    params = {\"recipe_id\": recipe_id, \"lang\": lang}\n    cache_name = \"recipe_details.%(recipe_id)s.%(lang)s.json\" % params\n    return get_cached(\"recipe_details.json\", cache_name, params=params)",
    "docstring": "This resource returns a details about a single recipe.\n\n    :param recipe_id: The recipe to query for.\n    :param lang: The language to display the texts in.\n\n    The response is an object with the following properties:\n\n    recipe_id (number):\n        The recipe id.\n\n    type (string):\n        The type of the produced item.\n\n    output_item_id (string):\n        The item id of the produced item.\n\n    output_item_count (string):\n        The amount of items produced.\n\n    min_rating (string):\n        The minimum rating of the recipe.\n\n    time_to_craft_ms (string):\n        The time it takes to craft the item.\n\n    disciplines (list):\n        A list of crafting disciplines that can use the recipe.\n\n    flags (list):\n        Additional recipe flags. Known flags:\n\n        ``AutoLearned``:\n            Set for recipes that don't have to be discovered.\n\n        ``LearnedFromItem``:\n            Set for recipes that need a recipe sheet.\n\n    ingredients (list):\n        A list of objects describing the ingredients for this recipe. Each\n        object contains the following properties:\n\n        item_id (string):\n            The item id of the ingredient.\n\n        count (string):\n            The amount of ingredients required."
  },
  {
    "code": "def refresh(self, id_or_uri, timeout=-1):\n        uri = self._client.build_uri(id_or_uri) + \"/refresh\"\n        return self._client.update_with_zero_body(uri, timeout=timeout)",
    "docstring": "The Refresh action reclaims the top-of-rack switches in a logical switch.\n\n        Args:\n            id_or_uri:\n                Can be either the Logical Switch ID or URI\n            timeout:\n                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n                in OneView, just stop waiting for its completion.\n\n        Returns:\n            dict: The Logical Switch"
  },
  {
    "code": "def conv2d_trans(ni:int, nf:int, ks:int=2, stride:int=2, padding:int=0, bias=False) -> nn.ConvTranspose2d:\n    \"Create `nn.ConvTranspose2d` layer.\"\n    return nn.ConvTranspose2d(ni, nf, kernel_size=ks, stride=stride, padding=padding, bias=bias)",
    "docstring": "Create `nn.ConvTranspose2d` layer."
  },
  {
    "code": "def is_effective(self):\n        now = DateTime.utcnow()\n        return self.get_start_date() <= now and self.get_end_date() >= now",
    "docstring": "Tests if the current date is within the start end end dates inclusive.\n\n        return: (boolean) - ``true`` if this is effective, ``false``\n                otherwise\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def chdir(self, path):\n        self.cwd = self._join_chunks(self._normalize_path(path))",
    "docstring": "Changes the current directory to the given path"
  },
  {
    "code": "def cli(yamlfile, directory, out, classname, format):\n    DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out)",
    "docstring": "Generate graphviz representations of the biolink model"
  },
  {
    "code": "def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):\n    client = _get_client()\n    if isinstance(opts, dict):\n        client.opts.update(opts)\n    info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)\n    return info",
    "docstring": "Spin up an instance using Salt Cloud\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt minionname cloud.profile my-gce-config myinstance"
  },
  {
    "code": "def detectPalmOS(self):\n        if UAgentInfo.devicePalm in self.__userAgent \\\n           or UAgentInfo.engineBlazer in self.__userAgent \\\n           or UAgentInfo.engineXiino in self.__userAgent:\n            return not self.detectPalmWebOS()\n        return False",
    "docstring": "Return detection of a PalmOS device\n\n        Detects if the current browser is on a PalmOS device."
  },
  {
    "code": "def stop(self, force=False, wait=False):\n        log.debug(\"Stopping cluster `%s` ...\", self.name)\n        failed = self._stop_all_nodes(wait)\n        if failed:\n            if force:\n                self._delete_saved_data()\n                log.warning(\n                    \"Not all cluster nodes have been terminated.\"\n                    \" However, as requested, data about the cluster\"\n                    \" has been removed from local storage.\")\n            else:\n                self.repository.save_or_update(self)\n                log.warning(\n                    \"Not all cluster nodes have been terminated.\"\n                    \" Fix errors above and re-run `elasticluster stop %s`\",\n                    self.name)\n        else:\n            self._delete_saved_data()",
    "docstring": "Terminate all VMs in this cluster and delete its repository.\n\n        :param bool force:\n          remove cluster from storage even if not all nodes could be stopped."
  },
  {
    "code": "def _objs_opts(objs, all=None, **opts):\n    if objs:\n        t = objs\n    elif all in (False, None):\n        t = ()\n    elif all is True:\n        t = tuple(_values(sys.modules)) + (\n            globals(), stack(sys.getrecursionlimit())[2:])\n    else:\n        raise ValueError('invalid option: %s=%r' % ('all', all))\n    return t, opts",
    "docstring": "Return given or 'all' objects\n       and the remaining options."
  },
  {
    "code": "def _ParseCommentRecord(self, structure):\n    comment = structure[1]\n    if comment.startswith('Version'):\n      _, _, self._version = comment.partition(':')\n    elif comment.startswith('Software'):\n      _, _, self._software = comment.partition(':')\n    elif comment.startswith('Time'):\n      _, _, time_format = comment.partition(':')\n      if 'local' in time_format.lower():\n        self._use_local_timezone = True",
    "docstring": "Parse a comment and store appropriate attributes.\n\n    Args:\n      structure (pyparsing.ParseResults): parsed log line."
  },
  {
    "code": "def _get_args(self, executable, *args):\n        args = list(args)\n        args.insert(0, executable)\n        if self.username:\n            args.append(\"--username={}\".format(self.username))\n        if self.host:\n            args.append(\"--host={}\".format(self.host))\n        if self.port:\n            args.append(\"--port={}\".format(self.port))\n        args.append(self.dbname)\n        return args",
    "docstring": "compile all the executable and the arguments, combining with common arguments\n        to create a full batch of command args"
  },
  {
    "code": "def _sanitize_input_structure(input_structure):\n        input_structure = input_structure.copy()\n        input_structure.remove_spin()\n        input_structure = input_structure.get_primitive_structure(use_site_props=False)\n        if \"magmom\" in input_structure.site_properties:\n            input_structure.remove_site_property(\"magmom\")\n        return input_structure",
    "docstring": "Sanitize our input structure by removing magnetic information\n        and making primitive.\n\n        Args:\n            input_structure: Structure\n\n        Returns: Structure"
  },
  {
    "code": "def match_one_pattern(pattern: str, s: str, *args: Optional[Callable], **flags):\n    match: Optional[List[str]] = re.findall(pattern, s,\n                                            **flags)\n    if match:\n        if len(args) == 0:\n            return match\n        elif len(args) == 1:\n            wrapper, = args\n            return [wrapper(m) for m in match]\n        else:\n            raise TypeError(\n                'Multiple wrappers are given! Only one should be given!')\n    else:\n        print(\"Pattern \\\"{0}\\\" not found in string {1}!\".format(pattern, s))\n        return None",
    "docstring": "Find a pattern in a certain string. If found and a wrapper is given, then return the wrapped matched-string; if no\n    wrapper is given, return the pure matched string. If no match is found, return None.\n\n    :param pattern: a pattern, can be a string or a regular expression\n    :param s: a string\n    :param args: at most 1 argument can be given\n    :param flags: the same flags as ``re.findall``'s\n    :return:\n\n    .. doctest::\n\n        >>> p = \"\\d+\"\n        >>> s = \"abc 123 def 456\"\n        >>> match_one_pattern(p, s)\n        ['123', '456']\n        >>> match_one_pattern(p, s, int)\n        [123, 456]\n        >>> match_one_pattern(p, \"abc 123 def\")\n        ['123']\n        >>> print(match_one_pattern('s', 'abc'))\n        Pattern \"s\" not found in string abc!\n        None\n        >>> match_one_pattern('s', 'Ssa', flags=re.IGNORECASE)\n        ['S', 's']"
  },
  {
    "code": "def check_action_type(self, value):\n        if value is not None:\n            if not isinstance(value, ActionType):\n                raise AttributeError(\"Invalid check action %s\" % value)\n        self._check_action_type = value",
    "docstring": "Set the value for the CheckActionType, validating input"
  },
  {
    "code": "def influx_count_(self, measurement):\n        try:\n            q = \"select count(*) from \" + measurement\n            self.start(\"Querying: count ...\")\n            datalen = self.influx_cli.query(q)\n            self.end(\"Finished querying\")\n            numrows = int(datalen[measurement][datalen[measurement].keys()[0]])\n            return numrows\n        except Exception as e:\n            self.err(e, self.influx_count_,\n                     \"Can not count rows for measurement\")",
    "docstring": "Count the number of rows for a measurement"
  },
  {
    "code": "def run(self):\n    _LOGGER.info(\"Started\")\n    while True:\n      self._maybe_reconnect()\n      line = ''\n      try:\n        t = self._telnet\n        if t is not None:\n          line = t.read_until(b\"\\n\")\n      except EOFError:\n        try:\n          self._lock.acquire()\n          self._disconnect_locked()\n          continue\n        finally:\n          self._lock.release()\n      self._recv_cb(line.decode('ascii').rstrip())",
    "docstring": "Main thread function to maintain connection and receive remote status."
  },
  {
    "code": "def from_frame(klass, frame, connection):\n        event = frame.headers['new']\n        data = json.loads(frame.body)\n        info = data['info']\n        task = Task.fromDict(info)\n        task.connection = connection\n        return klass(task, event)",
    "docstring": "Create a new TaskStateChange event from a Stompest Frame."
  },
  {
    "code": "def from_path(cls, path):\n    if os.path.exists(path) is False:\n      raise errors.InvalidPathError(path)\n    return cls(path=path)",
    "docstring": "Instantiates a project class from a given path.\n\n    :param path: app folder path source code\n\n    Returns\n      A project instance."
  },
  {
    "code": "def match_global_phase(a: np.ndarray,\n                       b: np.ndarray\n                       ) -> Tuple[np.ndarray, np.ndarray]:\n    if a.shape != b.shape:\n        return a, b\n    k = max(np.ndindex(*a.shape), key=lambda t: abs(b[t]))\n    def dephase(v):\n        r = np.real(v)\n        i = np.imag(v)\n        if i == 0:\n            return -1 if r < 0 else 1\n        if r == 0:\n            return 1j if i < 0 else -1j\n        return np.exp(-1j * np.arctan2(i, r))\n    return a * dephase(a[k]), b * dephase(b[k])",
    "docstring": "Phases the given matrices so that they agree on the phase of one entry.\n\n    To maximize precision, the position with the largest entry from one of the\n    matrices is used when attempting to compute the phase difference between\n    the two matrices.\n\n    Args:\n        a: A numpy array.\n        b: Another numpy array.\n\n    Returns:\n        A tuple (a', b') where a' == b' implies a == b*exp(i t) for some t."
  },
  {
    "code": "def cleanup(self, keep=5):\n        releases = self.get_releases()\n        current_version = self.get_current_release()\n        to_delete = [version for version in releases[keep:] if version != current_version]\n        for release in to_delete:\n            self._runner.run(\"rm -rf '{0}'\".format(os.path.join(self._releases, release)))",
    "docstring": "Remove all but the ``keep`` most recent releases.\n\n        If any of the candidates for deletion are pointed to by the\n        'current' symlink, they will not be deleted.\n\n        This method performs N + 2 network operations where N is the\n        number of old releases that are cleaned up.\n\n        :param int keep: Number of old releases to keep around"
  },
  {
    "code": "def get_minimum_size(self, data):\n        size = self.element.get_minimum_size(data)\n        if self.angle in (RotateLM.NORMAL, RotateLM.UPSIDE_DOWN):\n            return size\n        else:\n            return datatypes.Point(size.y, size.x)",
    "docstring": "Returns the rotated minimum size."
  },
  {
    "code": "def build_plane_arrays(x, y, qlist):\r\n    if type(qlist) is not list:\r\n        return_list = False\r\n        qlist = [qlist]\r\n    else:\r\n        return_list = True\r\n    xv = x[np.where(y==y[0])[0]]\r\n    yv = y[np.where(x==x[0])[0]]\r\n    qlistp = []\r\n    for n in range(len(qlist)):\r\n        qlistp.append(np.zeros((len(yv), len(xv))))\r\n    for j in range(len(qlist)):\r\n        for n in range(len(yv)):\r\n            i = np.where(y==yv[n])[0]\r\n            qlistp[j][n,:] = qlist[j][i]\r\n    if not return_list:\r\n        qlistp = qlistp[0]\r\n    return xv, yv, qlistp",
    "docstring": "Build a 2-D array out of data taken in the same plane, for contour\r\n    plotting."
  },
  {
    "code": "def a_return_and_reconnect(ctx):\n    ctx.ctrl.send(\"\\r\")\n    ctx.device.connect(ctx.ctrl)\n    return True",
    "docstring": "Send new line and reconnect."
  },
  {
    "code": "def dict_of_lists_add(dictionary, key, value):\n    list_objs = dictionary.get(key, list())\n    list_objs.append(value)\n    dictionary[key] = list_objs",
    "docstring": "Add value to a list in a dictionary by key\n\n    Args:\n        dictionary (DictUpperBound): Dictionary to which to add values\n        key (Any): Key within dictionary\n        value (Any): Value to add to list in dictionary\n\n    Returns:\n        None"
  },
  {
    "code": "def transmit_ack_bpdu(self):\n        ack_flags = 0b10000001\n        bpdu_data = self._generate_config_bpdu(ack_flags)\n        self.ofctl.send_packet_out(self.ofport.port_no, bpdu_data)",
    "docstring": "Send Topology Change Ack BPDU."
  },
  {
    "code": "def get_value(value_proto):\n  field = value_proto.WhichOneof('value_type')\n  if field in __native_value_types:\n      return getattr(value_proto, field)\n  if field == 'timestamp_value':\n    return from_timestamp(value_proto.timestamp_value)\n  if field == 'array_value':\n    return [get_value(sub_value)\n            for sub_value in value_proto.array_value.values]\n  return None",
    "docstring": "Gets the python object equivalent for the given value proto.\n\n  Args:\n    value_proto: datastore.Value proto message.\n\n  Returns:\n    the corresponding python object value. timestamps are converted to\n    datetime, and datastore.Value is returned for blob_key_value."
  },
  {
    "code": "def _gen_packet_setpower(self, sequence, power, fade):\n        level = pack(\"<H\", Power.BULB_OFF if power == 0 else Power.BULB_ON)\n        duration = pack(\"<I\", fade)\n        payload = bytearray(level)\n        payload.extend(duration)\n        return self._gen_packet(sequence, PayloadType.SETPOWER2, payload)",
    "docstring": "Generate \"setpower\" packet payload."
  },
  {
    "code": "def findInNodeRegByHA(self, remoteHa):\n        regName = [nm for nm, ha in self.registry.items()\n                   if self.sameAddr(ha, remoteHa)]\n        if len(regName) > 1:\n            raise RuntimeError(\"more than one node registry entry with the \"\n                               \"same ha {}: {}\".format(remoteHa, regName))\n        if regName:\n            return regName[0]\n        return None",
    "docstring": "Returns the name of the remote by HA if found in the node registry, else\n        returns None"
  },
  {
    "code": "def executemany(self, command, params=None, max_attempts=5):\n        attempts = 0\n        while attempts < max_attempts:\n            try:\n                self._cursor.executemany(command, params)\n                self._commit()\n                return True\n            except Exception as e:\n                attempts += 1\n                self.reconnect()\n                continue",
    "docstring": "Execute multiple SQL queries without returning a result."
  },
  {
    "code": "def push(h, x):\n    h.push(x)\n    up(h, h.size()-1)",
    "docstring": "Push a new value into heap."
  },
  {
    "code": "def alias(requestContext, seriesList, newName):\n    try:\n        seriesList.name = newName\n    except AttributeError:\n        for series in seriesList:\n            series.name = newName\n    return seriesList",
    "docstring": "Takes one metric or a wildcard seriesList and a string in quotes.\n    Prints the string instead of the metric name in the legend.\n\n    Example::\n\n        &target=alias(Sales.widgets.largeBlue,\"Large Blue Widgets\")"
  },
  {
    "code": "def is_date(v) -> (bool, date):\n        if isinstance(v, date):\n            return True, v\n        try:\n            reg = r'^([0-9]{4})(?:-(0[1-9]|1[0-2])(?:-(0[1-9]|[1-2][0-9]|3[0-1])(?:T' \\\n                  r'([0-5][0-9])(?::([0-5][0-9])(?::([0-5][0-9]))?)?)?)?)?$'\n            match = re.match(reg, v)\n            if match:\n                groups = match.groups()\n                patterns = ['%Y', '%m', '%d', '%H', '%M', '%S']\n                d = datetime.strptime('-'.join([x for x in groups if x]),\n                                      '-'.join([patterns[i] for i in range(len(patterns)) if groups[i]]))\n                return True, d\n        except:\n            pass\n        return False, v",
    "docstring": "Boolean function for checking if v is a date\n\n        Args:\n            v:\n        Returns: bool"
  },
  {
    "code": "def load(self, response):\n        self._models = []\n        if isinstance(response, dict):\n            for key in response.keys():\n                model = self.model_class(self, href='')\n                model.load(response[key])\n                self._models.append(model)\n        else:\n            for item in response:\n                model = self.model_class(self,\n                                         href=item.get('href'))\n                model.load(item)\n                self._models.append(model)",
    "docstring": "Parse the GET response for the collection.\n\n        This operates as a lazy-loader, meaning that the data are only downloaded\n        from the server if there are not already loaded.\n        Collection items are loaded sequentially.\n\n        In some rare cases, a collection can have an asynchronous request\n        triggered.  For those cases, we handle it here."
  },
  {
    "code": "def _cmp_by_origin(path1, path2):\n    def get_origin_pref(origin):\n        if origin.value == BGP_ATTR_ORIGIN_IGP:\n            return 3\n        elif origin.value == BGP_ATTR_ORIGIN_EGP:\n            return 2\n        elif origin.value == BGP_ATTR_ORIGIN_INCOMPLETE:\n            return 1\n        else:\n            LOG.error('Invalid origin value encountered %s.', origin)\n            return 0\n    origin1 = path1.get_pattr(BGP_ATTR_TYPE_ORIGIN)\n    origin2 = path2.get_pattr(BGP_ATTR_TYPE_ORIGIN)\n    assert origin1 is not None and origin2 is not None\n    if origin1.value == origin2.value:\n        return None\n    origin1 = get_origin_pref(origin1)\n    origin2 = get_origin_pref(origin2)\n    if origin1 == origin2:\n        return None\n    elif origin1 > origin2:\n        return path1\n    return path2",
    "docstring": "Select the best path based on origin attribute.\n\n    IGP is preferred over EGP; EGP is preferred over Incomplete.\n    If both paths have same origin, we return None."
  },
  {
    "code": "def pre_process_json(obj):\n    if type(obj) is dict:\n        new_dict = {}\n        for key, value in obj.items():\n            new_dict[key] = pre_process_json(value)\n        return new_dict\n    elif type(obj) is list:\n        new_list = []\n        for item in obj:\n            new_list.append(pre_process_json(item))\n        return new_list\n    elif hasattr(obj, 'todict'):\n        return dict(obj.todict())\n    else:\n        try:\n            json.dumps(obj)\n        except TypeError:\n            try:\n                json.dumps(obj.__dict__)\n            except TypeError:\n                return str(obj)\n            else:\n                return obj.__dict__\n        else:\n            return obj",
    "docstring": "Preprocess items in a dictionary or list and prepare them to be json serialized."
  },
  {
    "code": "def preparse(self, context):\n        context.early_args, unused = (\n            context.early_parser.parse_known_args(context.argv))",
    "docstring": "Parse a portion of command line arguments with the early parser.\n\n        This method relies on ``context.argv`` and ``context.early_parser``\n        and produces ``context.early_args``.\n\n        The ``context.early_args`` object is the return value from argparse.\n        It is the dict/object like namespace object."
  },
  {
    "code": "def get_trades(self, max_id=None, count=None, instrument=None, ids=None):\n        url = \"{0}/{1}/accounts/{2}/trades\".format(\n            self.domain,\n            self.API_VERSION,\n            self.account_id\n        )\n        params = {\n            \"maxId\": int(max_id) if max_id and max_id > 0 else None,\n            \"count\": int(count) if count and count > 0 else None,\n            \"instrument\": instrument,\n            \"ids\": ','.join(ids) if ids else None\n        }\n        try:\n            return self._Client__call(uri=url, params=params, method=\"get\")\n        except RequestException:\n            return False\n        except AssertionError:\n            return False",
    "docstring": "Get a list of open trades\n\n            Parameters\n            ----------\n            max_id : int\n                The server will return trades with id less than or equal\n                to this, in descending order (for pagination)\n            count : int\n                Maximum number of open trades to return. Default: 50 Max\n                value: 500\n            instrument : str\n                Retrieve open trades for a specific instrument only\n                Default: all\n            ids : list\n                A list of trades to retrieve. Maximum number of ids: 50.\n                No other parameter may be specified with the ids\n                parameter.\n\n            See more:\n            http://developer.oanda.com/rest-live/trades/#getListOpenTrades"
  },
  {
    "code": "def transform(data_frame, **kwargs):\n    norm = kwargs.get('norm', 1.0)\n    axis = kwargs.get('axis', 0)\n    if axis == 0:\n        norm_vector = _get_norms_of_rows(data_frame, kwargs.get('method', 'vector'))\n    else:\n        norm_vector = _get_norms_of_cols(data_frame, kwargs.get('method', 'first'))\n    if 'labels' in kwargs:\n        if axis == 0:\n            return data_frame.apply(lambda col: col * norm / norm_vector, axis=0), \\\n                    kwargs['labels'].apply(lambda col: col * norm / norm_vector, axis=0)\n        else:\n            raise ValueError(\"label normalization incompatible with normalization by column\")\n    else:\n        if axis == 0:\n            return data_frame.apply(lambda col: col * norm / norm_vector, axis=0)\n        else:\n            return data_frame.apply(lambda row: row * norm / norm_vector, axis=1)",
    "docstring": "Return a transformed DataFrame.\n\n    Transform data_frame along the given axis. By default, each row will be normalized (axis=0).\n\n    Parameters\n    -----------\n    data_frame : DataFrame\n        Data to be normalized.\n    axis : int, optional\n        0 (default) to normalize each row, 1 to normalize each column.\n    method : str, optional\n        Valid methods are:\n        \n        -  \"vector\" : Default for normalization by row (axis=0).\n           Normalize along axis as a vector with norm `norm`\n        -  \"last\" : Linear normalization setting last value along the axis to `norm`\n        -  \"first\" : Default for normalization of columns (axis=1).\n           Linear normalization setting first value along the given axis to `norm`\n        -  \"mean\" : Normalize so that the mean of each vector along the given axis is `norm`\n    norm : float, optional\n        Target value of normalization, defaults to 1.0.\n    labels : DataFrame, optional\n        Labels may be passed as keyword argument, in which\n        case the label values will also be normalized and returned.\n\n    Returns\n    -----------\n    df : DataFrame\n        Normalized data.\n    labels : DataFrame, optional\n        Normalized labels, if provided as input.\n\n    Notes\n    -----------\n    If labels are real-valued, they should also be normalized.\n\n    ..\n        Having row_norms as a numpy array should be benchmarked against \n        using a DataFrame:\n        http://stackoverflow.com/questions/12525722/normalize-data-in-pandas\n        Note: This isn't a bottleneck. Using a feature set with 13k rows and 256\n        data_frame ('ge' from 1962 until now), the normalization was immediate."
  },
  {
    "code": "def get_new_author(self, api_author):\n        return Author(site_id=self.site_id,\n                      wp_id=api_author[\"ID\"],\n                      **self.api_object_data(\"author\", api_author))",
    "docstring": "Instantiate a new Author from api data.\n\n        :param api_author: the api data for the Author\n        :return: the new Author"
  },
  {
    "code": "def update_question_group(self, id, quiz_id, course_id, quiz_groups_name=None, quiz_groups_pick_count=None, quiz_groups_question_points=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"course_id\"] = course_id\r\n        path[\"quiz_id\"] = quiz_id\r\n        path[\"id\"] = id\r\n        if quiz_groups_name is not None:\r\n            data[\"quiz_groups[name]\"] = quiz_groups_name\r\n        if quiz_groups_pick_count is not None:\r\n            data[\"quiz_groups[pick_count]\"] = quiz_groups_pick_count\r\n        if quiz_groups_question_points is not None:\r\n            data[\"quiz_groups[question_points]\"] = quiz_groups_question_points\r\n        self.logger.debug(\"PUT /api/v1/courses/{course_id}/quizzes/{quiz_id}/groups/{id} with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"PUT\", \"/api/v1/courses/{course_id}/quizzes/{quiz_id}/groups/{id}\".format(**path), data=data, params=params, no_data=True)",
    "docstring": "Update a question group.\r\n\r\n        Update a question group"
  },
  {
    "code": "def get_link_name (self, tag, attrs, attr):\n        if tag == 'a' and attr == 'href':\n            data = self.parser.peek(MAX_NAMELEN)\n            data = data.decode(self.parser.encoding, \"ignore\")\n            name = linkname.href_name(data)\n            if not name:\n                name = attrs.get_true('title', u'')\n        elif tag == 'img':\n            name = attrs.get_true('alt', u'')\n            if not name:\n                name = attrs.get_true('title', u'')\n        else:\n            name = u\"\"\n        return name",
    "docstring": "Parse attrs for link name. Return name of link."
  },
  {
    "code": "def decode_response(data):\n    res = CaseInsensitiveDict()\n    for dataline in data.decode('utf-8').splitlines()[1:]:\n        dataline = dataline.strip()\n        if not dataline:\n            continue\n        line_parts = dataline.split(':', 1)\n        if len(line_parts) < 2:\n            line_parts = (line_parts[0], '')\n        res[line_parts[0].strip()] = line_parts[1].strip()\n    return res",
    "docstring": "Decodes the data from a SSDP response.\n\n    Args:\n        data (bytes): The encoded response.\n\n    Returns:\n        dict of string -> string: Case-insensitive dictionary of header name to\n        header value pairs extracted from the response."
  },
  {
    "code": "def _get_setup(self, result):\n        self.__devices = {}\n        if ('setup' not in result.keys() or\n                'devices' not in result['setup'].keys()):\n            raise Exception(\n                \"Did not find device definition.\")\n        for device_data in result['setup']['devices']:\n            device = Device(self, device_data)\n            self.__devices[device.url] = device\n        self.__location = result['setup']['location']\n        self.__gateway = result['setup']['gateways']",
    "docstring": "Internal method which process the results from the server."
  },
  {
    "code": "def hook(self, function, dependencies=None):\n        if not isinstance(dependencies, (Iterable, type(None), str)):\n            raise TypeError(\"Invalid list of dependencies provided!\")\n        if not hasattr(function, \"__deps__\"):\n            function.__deps__ = dependencies\n        if self.isloaded(function.__deps__):\n            self.append(function)\n        else:\n            self._later.append(function)\n        for ext in self._later:\n            if self.isloaded(ext.__deps__):\n                self._later.remove(ext)\n                self.hook(ext)",
    "docstring": "Tries to load a hook\n\n        Args:\n            function (func): Function that will be called when the event is called\n\n        Kwargs:\n            dependencies (str): String or Iterable with modules whose hooks should be called before this one\n\n        Raises:\n            :class:TypeError\n\n        Note that the dependencies are module-wide, that means that if\n        `parent.foo` and `parent.bar` are both subscribed to `example` event\n        and `child` enumerates `parent` as dependcy, **both** `foo` and `bar`\n        must be called in order for the dependcy to get resolved."
  },
  {
    "code": "def add_query_to_url(url, extra_query):\n    split = urllib.parse.urlsplit(url)\n    merged_query = urllib.parse.parse_qsl(split.query)\n    if isinstance(extra_query, dict):\n        for k, v in extra_query.items():\n            if not isinstance(v, (tuple, list)):\n                merged_query.append((k, v))\n            else:\n                for cv in v:\n                    merged_query.append((k, cv))\n    else:\n        merged_query.extend(extra_query)\n    merged_split = urllib.parse.SplitResult(\n        split.scheme,\n        split.netloc,\n        split.path,\n        urllib.parse.urlencode(merged_query),\n        split.fragment,\n    )\n    return merged_split.geturl()",
    "docstring": "Adds an extra query to URL, returning the new URL.\n\n    Extra query may be a dict or a list as returned by\n    :func:`urllib.parse.parse_qsl()` and :func:`urllib.parse.parse_qs()`."
  },
  {
    "code": "def get_translation_dicts(self):\n        keysym_to_string_dict = {}\n        string_to_keysym_dict = {}\n        Xlib.XK.load_keysym_group('latin2')\n        Xlib.XK.load_keysym_group('latin3')\n        Xlib.XK.load_keysym_group('latin4')\n        Xlib.XK.load_keysym_group('greek')\n        for string, keysym in Xlib.XK.__dict__.items():\n            if string.startswith('XK_'):\n                string_to_keysym_dict[string[3:]] = keysym\n                keysym_to_string_dict[keysym] = string[3:]\n        return keysym_to_string_dict, string_to_keysym_dict",
    "docstring": "Returns dictionaries for the translation of keysyms to strings and from\n        strings to keysyms."
  },
  {
    "code": "def list_delete(self, id):\n        id = self.__unpack_id(id)\n        self.__api_request('DELETE', '/api/v1/lists/{0}'.format(id))",
    "docstring": "Delete a list."
  },
  {
    "code": "def plot_connectivity_surrogate(self, measure_name, repeats=100, fig=None):\n        cb = self.get_surrogate_connectivity(measure_name, repeats)\n        self._prepare_plots(True, False)\n        cu = np.percentile(cb, 95, axis=0)\n        fig = self.plotting.plot_connectivity_spectrum([cu], self.fs_, freq_range=self.plot_f_range, fig=fig)\n        return fig",
    "docstring": "Plot spectral connectivity measure under the assumption of no actual connectivity.\n\n        Repeatedly samples connectivity from phase-randomized data. This provides estimates of the connectivity\n        distribution if there was no causal structure in the data.\n\n        Parameters\n        ----------\n        measure_name : str\n            Name of the connectivity measure to calculate. See :class:`Connectivity` for supported measures.\n        repeats : int, optional\n            How many surrogate samples to take.\n        fig : {None, Figure object}, optional\n            Where to plot the topos. f set to **None**, a new figure is created. Otherwise plot into the provided\n            figure object.\n\n        Returns\n        -------\n        fig : Figure object\n            Instance of the figure in which was plotted."
  },
  {
    "code": "def safe_makedirs(fdir):\n    if os.path.isdir(fdir):\n        pass\n    else:\n        try:\n            os.makedirs(fdir)\n        except WindowsError as e:\n            if 'Cannot create a file when that file already exists' in e:\n                log.debug('relevant dir already exists')\n            else:\n                raise WindowsError(e)\n    return True",
    "docstring": "Make an arbitrary directory.  This is safe to call for Python 2 users.\n\n    :param fdir: Directory path to make.\n    :return:"
  },
  {
    "code": "def _get_object_as_soft(self):\n        soft = [\"^%s = %s\" % (self.geotype, self.name),\n                self._get_metadata_as_string(),\n                self._get_columns_as_string(),\n                self._get_table_as_string()]\n        return \"\\n\".join(soft)",
    "docstring": "Get the object as SOFT formated string."
  },
  {
    "code": "def delete_blob(call=None, kwargs=None):\n    if kwargs is None:\n        kwargs = {}\n    if 'container' not in kwargs:\n        raise SaltCloudSystemExit(\n            'A container must be specified'\n        )\n    if 'blob' not in kwargs:\n        raise SaltCloudSystemExit(\n            'A blob must be specified'\n        )\n    storageservice = _get_block_blob_service(kwargs)\n    storageservice.delete_blob(kwargs['container'], kwargs['blob'])\n    return True",
    "docstring": "Delete a blob from a container."
  },
  {
    "code": "def refresh_session(self):\n        if not self._refresh_token:\n            if self._username and self._password:\n                return self.login(self._username, self._password)\n            return\n        return self._authenticate(\n            grant_type='refresh_token',\n            refresh_token=self._refresh_token,\n            client_id=self._client_id,\n            client_secret=self._client_secret\n        )",
    "docstring": "Re-authenticate using the refresh token if available.\n        Otherwise log in using the username and password\n        if it was used to authenticate initially.\n\n        :return: The authentication response or `None` if not available"
  },
  {
    "code": "def is_oriented(self):\n        if util.is_shape(self.primitive.transform, (4, 4)):\n            return not np.allclose(self.primitive.transform[\n                                   0:3, 0:3], np.eye(3))\n        else:\n            return False",
    "docstring": "Returns whether or not the current box is rotated at all."
  },
  {
    "code": "def _legacy_api_registration_check(self):\n        logger.debug('Checking registration status...')\n        machine_id = generate_machine_id()\n        try:\n            url = self.api_url + '/v1/systems/' + machine_id\n            net_logger.info(\"GET %s\", url)\n            res = self.session.get(url, timeout=self.config.http_timeout)\n        except requests.ConnectionError:\n            logger.error('Connection timed out. Running connection test...')\n            self.test_connection()\n            return False\n        try:\n            unreg_status = json.loads(res.content).get('unregistered_at', 'undefined')\n            self.config.account_number = json.loads(res.content).get('account_number', 'undefined')\n        except ValueError:\n            return False\n        if unreg_status == 'undefined':\n            return None\n        elif unreg_status is None:\n            return True\n        else:\n            return unreg_status",
    "docstring": "Check registration status through API"
  },
  {
    "code": "def connect_full_direct(self, config):\n        for input_id, output_id in self.compute_full_connections(config, True):\n            connection = self.create_connection(config, input_id, output_id)\n            self.connections[connection.key] = connection",
    "docstring": "Create a fully-connected genome, including direct input-output connections."
  },
  {
    "code": "def get_results(self):\n        summary = self.handle.get_summary_data(self.group_name)\n        results = {'template': {'status': 'no data'},\n                   'complement': {'status': 'no data'},\n                   '2d': {'status': 'no data'}}\n        if 'genome_mapping_template' in summary:\n            results['template'] = self._get_results(summary['genome_mapping_template'])\n        if 'genome_mapping_complement' in summary:\n            results['complement'] = self._get_results(summary['genome_mapping_complement'])\n        if 'genome_mapping_2d' in summary:\n            results['2d'] = self._get_results(summary['genome_mapping_2d'])\n        return results",
    "docstring": "Get details about the alignments that have been performed.\n\n        :return: A dict of dicts.\n\n        The keys of the top level are 'template', 'complement' and '2d'.\n        Each of these dicts contains the following fields:\n\n            * status: Can be 'no data', 'no match found', or 'match found'.\n            * direction: Can be 'forward', 'reverse'.\n            * ref_name: Name of reference.\n            * ref_span: Section of reference aligned to, as a tuple (start, end).\n            * seq_span: Section of the called sequence that aligned, as a tuple (start, end).\n            * seq_len: Total length of the called sequence.\n            * num_aligned: Number of bases that aligned to bases in the reference.\n            * num_correct: Number of aligned bases that match the reference.\n            * num_deletions: Number of bases in the aligned section of the\n                reference that are not aligned to bases in the called sequence.\n            * num_insertions: Number of bases in the aligned section of the called\n                sequence that are not aligned to bases in the reference.\n            * identity: The fraction of aligned bases that are correct (num_correct /\n                num_aligned).\n            * accuracy: The overall basecall accuracy, according to the alignment.\n                (num_correct / (num_aligned + num_deletions + num_insertions)).\n        \n        Note that if the status field is not 'match found', then all the other\n        fields will be absent."
  },
  {
    "code": "def is_ip_addr_list(value, min=None, max=None):\n    return [is_ip_addr(mem) for mem in is_list(value, min, max)]",
    "docstring": "Check that the value is a list of IP addresses.\n\n    You can optionally specify the minimum and maximum number of members.\n\n    Each list member is checked that it is an IP address.\n\n    >>> vtor = Validator()\n    >>> vtor.check('ip_addr_list', ())\n    []\n    >>> vtor.check('ip_addr_list', [])\n    []\n    >>> vtor.check('ip_addr_list', ('1.2.3.4', '5.6.7.8'))\n    ['1.2.3.4', '5.6.7.8']\n    >>> vtor.check('ip_addr_list', ['a'])  # doctest: +SKIP\n    Traceback (most recent call last):\n    VdtValueError: the value \"a\" is unacceptable."
  },
  {
    "code": "def transform(v1, v2):\n    theta = angle(v1,v2)\n    x = N.cross(v1,v2)\n    x = x / N.linalg.norm(x)\n    A = N.array([\n        [0, -x[2], x[1]],\n        [x[2], 0, -x[0]],\n        [-x[1], x[0], 0]])\n    R = N.exp(A*theta)\n    return R",
    "docstring": "Create an affine transformation matrix that maps vector 1\n    onto vector 2\n\n    https://math.stackexchange.com/questions/293116/rotating-one-3d-vector-to-another"
  },
  {
    "code": "def _connect_secureish(*args, **kwargs):\n    if tuple(int(x) for x in boto.__version__.split('.')) >= (2, 6, 0):\n        kwargs['validate_certs'] = True\n    kwargs['is_secure'] = True\n    auth_region_name = kwargs.pop('auth_region_name', None)\n    conn = connection.S3Connection(*args, **kwargs)\n    if auth_region_name:\n        conn.auth_region_name = auth_region_name\n    return conn",
    "docstring": "Connect using the safest available options.\n\n    This turns on encryption (works in all supported boto versions)\n    and certificate validation (in the subset of supported boto\n    versions that can handle certificate validation, namely, those\n    after 2.6.0).\n\n    Versions below 2.6 don't support the validate_certs option to\n    S3Connection, and enable it via configuration option just seems to\n    cause an error."
  },
  {
    "code": "def set_in_bounds(self,obj,val):\n        if not callable(val):\n            bounded_val = self.crop_to_bounds(val)\n        else:\n            bounded_val = val\n        super(Number,self).__set__(obj,bounded_val)",
    "docstring": "Set to the given value, but cropped to be within the legal bounds.\n        All objects are accepted, and no exceptions will be raised.  See\n        crop_to_bounds for details on how cropping is done."
  },
  {
    "code": "def insert_chain(cur, chain, encoded_data=None):\n    if encoded_data is None:\n        encoded_data = {}\n    if 'nodes' not in encoded_data:\n        encoded_data['nodes'] = json.dumps(sorted(chain), separators=(',', ':'))\n    if 'chain_length' not in encoded_data:\n        encoded_data['chain_length'] = len(chain)\n    insert = \"INSERT OR IGNORE INTO chain(chain_length, nodes) VALUES (:chain_length, :nodes);\"\n    cur.execute(insert, encoded_data)",
    "docstring": "Insert a chain into the cache.\n\n    Args:\n        cur (:class:`sqlite3.Cursor`):\n            An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.\n\n        chain (iterable):\n            A collection of nodes. Chains in embedding act as one node.\n\n        encoded_data (dict, optional):\n            If a dictionary is provided, it will be populated with the serialized data. This is\n            useful for preventing encoding the same information many times.\n\n    Notes:\n        This function assumes that the nodes in chain are index-labeled."
  },
  {
    "code": "def _get_external_id(account_info):\n    if all(k in account_info for k in ('external_id', 'external_method')):\n        return dict(id=account_info['external_id'],\n                    method=account_info['external_method'])\n    return None",
    "docstring": "Get external id from account info."
  },
  {
    "code": "def _jamo_to_hangul_char(lead, vowel, tail=0):\n    lead = ord(lead) - _JAMO_LEAD_OFFSET\n    vowel = ord(vowel) - _JAMO_VOWEL_OFFSET\n    tail = ord(tail) - _JAMO_TAIL_OFFSET if tail else 0\n    return chr(tail + (vowel - 1) * 28 + (lead - 1) * 588 + _JAMO_OFFSET)",
    "docstring": "Return the Hangul character for the given jamo characters."
  },
  {
    "code": "def _substitute(self, expr, mapping):\n        node = expr.op()\n        try:\n            return mapping[node]\n        except KeyError:\n            if node.blocks():\n                return expr\n            new_args = list(node.args)\n            unchanged = True\n            for i, arg in enumerate(new_args):\n                if isinstance(arg, ir.Expr):\n                    new_arg = self.substitute(arg, mapping)\n                    unchanged = unchanged and new_arg is arg\n                    new_args[i] = new_arg\n            if unchanged:\n                return expr\n            try:\n                new_node = type(node)(*new_args)\n            except IbisTypeError:\n                return expr\n            try:\n                name = expr.get_name()\n            except ExpressionError:\n                name = None\n            return expr._factory(new_node, name=name)",
    "docstring": "Substitute expressions with other expressions.\n\n        Parameters\n        ----------\n        expr : ibis.expr.types.Expr\n        mapping : Mapping[ibis.expr.operations.Node, ibis.expr.types.Expr]\n\n        Returns\n        -------\n        ibis.expr.types.Expr"
  },
  {
    "code": "def _streaming_request_iterable(self, config, requests):\n        yield self.types.StreamingRecognizeRequest(streaming_config=config)\n        for request in requests:\n            yield request",
    "docstring": "A generator that yields the config followed by the requests.\n\n        Args:\n            config (~.speech_v1.types.StreamingRecognitionConfig): The\n                configuration to use for the stream.\n            requests (Iterable[~.speech_v1.types.StreamingRecognizeRequest]):\n                The input objects.\n\n        Returns:\n            Iterable[~.speech_v1.types.StreamingRecognizeRequest]): The\n                correctly formatted input for\n                :meth:`~.speech_v1.SpeechClient.streaming_recognize`."
  },
  {
    "code": "def format_datetime(cls, timestamp):\n        if not timestamp:\n            raise DateTimeFormatterException('timestamp must a valid string {}'.format(timestamp))\n        return timestamp.strftime(cls.DATETIME_FORMAT)",
    "docstring": "Creates a string representing the date and time information provided by\n        the given `timestamp` object."
  },
  {
    "code": "def _speak_as_literal_punctuation(self, element):\n        self._speak_as(\n            element,\n            self._get_regular_expression_of_symbols(),\n            'literal-punctuation',\n            self._operation_speak_as_literal_punctuation\n        )",
    "docstring": "Speak the punctuation for elements only.\n\n        :param element: The element.\n        :type element: hatemile.util.html.htmldomelement.HTMLDOMElement"
  },
  {
    "code": "def read32(self, offset):\n        if not isinstance(offset, (int, long)):\n            raise TypeError(\"Invalid offset type, should be integer.\")\n        offset = self._adjust_offset(offset)\n        self._validate_offset(offset, 4)\n        return struct.unpack(\"=L\", self.mapping[offset:offset + 4])[0]",
    "docstring": "Read 32-bits from the specified `offset` in bytes, relative to the\n        base physical address of the MMIO region.\n\n        Args:\n            offset (int, long): offset from base physical address, in bytes.\n\n        Returns:\n            int: 32-bit value read.\n\n        Raises:\n            TypeError: if `offset` type is invalid.\n            ValueError: if `offset` is out of bounds."
  },
  {
    "code": "def help(self, stream):\n        if stream not in self.streams:\n            log.error(\"Stream '{}' not found in the database.\".format(stream))\n        params = self._stream_df[self._stream_df['STREAM'] == stream].values[0]\n        self._print_stream_parameters(params)",
    "docstring": "Show the help for a given stream."
  },
  {
    "code": "def disconnect_pools(self):\n        with self._lock:\n            for pool in self._pools.itervalues():\n                pool.disconnect()\n            self._pools.clear()",
    "docstring": "Disconnects all connections from the internal pools."
  },
  {
    "code": "def to_string(address, leading_dot=False):\n\t\tif isinstance(address, WFQDN) is False:\n\t\t\traise TypeError('Invalid type for FQDN address')\n\t\tresult = '.'.join(address._labels)\n\t\treturn result if leading_dot is False else (result + '.')",
    "docstring": "Return doted-written address by the given WFQDN object\n\n\t\t:param address: address to convert\n\t\t:param leading_dot: whether this function place leading dot to the result or not\n\t\t:return: str"
  },
  {
    "code": "def base36encode(number):\n    ALPHABET = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n    base36 = ''\n    sign = ''\n    if number < 0:\n        sign = '-'\n        number = -number\n    if 0 <= number < len(ALPHABET):\n        return sign + ALPHABET[number]\n    while number != 0:\n        number, i = divmod(number, len(ALPHABET))\n        base36 = ALPHABET[i] + base36\n    return sign + base36",
    "docstring": "Converts an integer into a base36 string."
  },
  {
    "code": "def get_country_name(self, callsign, timestamp=timestamp_now):\n        return self.get_all(callsign, timestamp)[const.COUNTRY]",
    "docstring": "Returns the country name where the callsign is located\n\n        Args:\n            callsign (str): Amateur Radio callsign\n            timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)\n\n        Returns:\n            str: name of the Country\n\n        Raises:\n            KeyError: No Country found for callsign\n\n        Note:\n            Don't rely on the country name when working with several instances of\n            py:class:`Callinfo`. Clublog and Country-files.org use slightly different names\n            for countries. Example:\n\n            - Country-files.com: \"Fed. Rep. of Germany\"\n            - Clublog: \"FEDERAL REPUBLIC OF GERMANY\""
  },
  {
    "code": "def _update_chime_status(self, message=None, status=None):\n        chime_status = status\n        if isinstance(message, Message):\n            chime_status = message.chime_on\n        if chime_status is None:\n            return\n        if chime_status != self._chime_status:\n            self._chime_status, old_status = chime_status, self._chime_status\n            if old_status is not None:\n                self.on_chime_changed(status=self._chime_status)\n        return self._chime_status",
    "docstring": "Uses the provided message to update the Chime state.\n\n        :param message: message to use to update\n        :type message: :py:class:`~alarmdecoder.messages.Message`\n        :param status: chime status, overrides message bits.\n        :type status: bool\n\n        :returns: bool indicating the new status"
  },
  {
    "code": "def rollback(awsclient, function_name, alias_name=ALIAS_NAME, version=None):\n    if version:\n        log.info('rolling back to version {}'.format(version))\n    else:\n        log.info('rolling back to previous version')\n        version = _get_previous_version(awsclient, function_name, alias_name)\n        if version == '0':\n            log.error('unable to find previous version of lambda function')\n            return 1\n        log.info('new version is %s' % str(version))\n    _update_alias(awsclient, function_name, version, alias_name)\n    return 0",
    "docstring": "Rollback a lambda function to a given version.\n\n    :param awsclient:\n    :param function_name:\n    :param alias_name:\n    :param version:\n    :return: exit_code"
  },
  {
    "code": "def on_hello(self, message):\n        logger.info(\"Got a hello\")\n        self.identify(self.token)\n        self.heartbeat_thread = Heartbeat(self.ws,\n                                          message['d']['heartbeat_interval'])\n        self.heartbeat_thread.start()\n        return",
    "docstring": "Runs on a hello event from websocket connection\n\n        Args:\n            message (dict): Full message from Discord websocket connection\""
  },
  {
    "code": "def set_field(self, field, idx, value):\n        if isinstance(idx, (int, float, str)):\n            idx = [idx]\n        if isinstance(value, (int, float)):\n            value = [value]\n        models = [self._idx_model[i] for i in idx]\n        for i, m, v in zip(idx, models, value):\n            assert hasattr(self.system.__dict__[m], field)\n            uid = self.system.__dict__[m].get_uid(idx)\n            self.system.__dict__[m].__dict__[field][uid] = v",
    "docstring": "Set the field ``field`` of elements ``idx`` to ``value``.\n\n        This function does not if the field is valid for all models.\n\n        :param field: field name\n        :param idx: element idx\n        :param value: value of fields to set\n        :return: None"
  },
  {
    "code": "def to_default_timezone_datetime(self, value):\n        return timezone.localtime(self.to_utc_datetime(value), timezone.get_default_timezone())",
    "docstring": "convert to default timezone datetime"
  },
  {
    "code": "def set_results(self, results: str):\n        if results.upper() == \"HTML\":\n            self.HTML = 1\n        else:\n            self.HTML = 0\n        self.results = results",
    "docstring": "This method set the results attribute for the SASdata object; it stays in effect till changed\n        results - set the default result type for this SASdata object. 'Pandas' or 'HTML' or 'TEXT'.\n\n        :param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives\n        :return: None"
  },
  {
    "code": "def explain_permutation_importance(estimator,\n                                   vec=None,\n                                   top=_TOP,\n                                   target_names=None,\n                                   targets=None,\n                                   feature_names=None,\n                                   feature_re=None,\n                                   feature_filter=None,\n                                   ):\n    coef = estimator.feature_importances_\n    coef_std = estimator.feature_importances_std_\n    return get_feature_importance_explanation(estimator, vec, coef,\n        coef_std=coef_std,\n        feature_names=feature_names,\n        feature_filter=feature_filter,\n        feature_re=feature_re,\n        top=top,\n        description=DESCRIPTION_SCORE_DECREASE + estimator.caveats_,\n        is_regression=isinstance(estimator.wrapped_estimator_, RegressorMixin),\n    )",
    "docstring": "Return an explanation of PermutationImportance.\n\n    See :func:`eli5.explain_weights` for description of\n    ``top``, ``feature_names``, ``feature_re`` and ``feature_filter``\n    parameters.\n\n    ``target_names`` and ``targets`` parameters are ignored.\n\n    ``vec`` is a vectorizer instance used to transform\n    raw features to the input of the estimator (e.g. a fitted\n    CountVectorizer instance); you can pass it instead of ``feature_names``."
  },
  {
    "code": "def play_async(cls, file_path, on_done=None):\n        thread = threading.Thread(\n            target=AudioPlayer.play, args=(file_path, on_done,))\n        thread.start()",
    "docstring": "Play an audio file asynchronously.\n\n        :param file_path: the path to the file to play.\n        :param on_done: callback when audio playback completes."
  },
  {
    "code": "def countSeries(requestContext, *seriesLists):\n    if not seriesLists or not any(seriesLists):\n        series = constantLine(requestContext, 0).pop()\n        series.pathExpression = \"countSeries()\"\n    else:\n        seriesList, start, end, step = normalize(seriesLists)\n        name = \"countSeries(%s)\" % formatPathExpressions(seriesList)\n        values = (int(len(row)) for row in zip_longest(*seriesList))\n        series = TimeSeries(name, start, end, step, values)\n        series.pathExpression = name\n    return [series]",
    "docstring": "Draws a horizontal line representing the number of nodes found in the\n    seriesList.\n\n    Example::\n\n        &target=countSeries(carbon.agents.*.*)"
  },
  {
    "code": "def non_quoted_string_regex(self, strict=True):\n        old_regex = self.regex\n        regex_alternative = r'([{}]+)'.format(re.escape(self.charset))\n        if strict:\n            regex_alternative = r'^' + regex_alternative + r'$'\n        self.regex = re.compile(regex_alternative)\n        try:\n            yield\n        finally:\n            self.regex = old_regex",
    "docstring": "For certain file formats, strings need not necessarily follow the\n        normal convention of being denoted by single or double quotes. In these\n        cases, we modify the regex accordingly.\n\n        Public, because detect_secrets.core.audit needs to reference it.\n\n        :type strict: bool\n        :param strict: if True, the regex will match the entire string."
  },
  {
    "code": "def add_dicts(d1, d2):\n    if d1 is None:\n        return d2\n    if d2 is None:\n        return d1\n    keys = set(d1)\n    keys.update(set(d2))\n    ret = {}\n    for key in keys:\n        v1 = d1.get(key)\n        v2 = d2.get(key)\n        if v1 is None:\n            ret[key] = v2\n        elif v2 is None:\n            ret[key] = v1\n        else:\n            ret[key] = v1 + v2\n    return ret",
    "docstring": "Merge two dicts of addable values"
  },
  {
    "code": "def flux_minimization(model, fixed, solver, weights={}):\n    fba = FluxBalanceProblem(model, solver)\n    for reaction_id, value in iteritems(fixed):\n        flux = fba.get_flux_var(reaction_id)\n        fba.prob.add_linear_constraints(flux >= value)\n    fba.minimize_l1()\n    return ((reaction_id, fba.get_flux(reaction_id))\n            for reaction_id in model.reactions)",
    "docstring": "Minimize flux of all reactions while keeping certain fluxes fixed.\n\n    The fixed reactions are given in a dictionary as reaction id\n    to value mapping. The weighted L1-norm of the fluxes is minimized.\n\n    Args:\n        model: MetabolicModel to solve.\n        fixed: dict of additional lower bounds on reaction fluxes.\n        solver: LP solver instance to use.\n        weights: dict of weights on the L1-norm terms.\n\n    Returns:\n        An iterator of reaction ID and reaction flux pairs."
  },
  {
    "code": "def from_soup(self,author,soup):\n\t\temail = soup.find('span',class_='icon icon-mail').findParent('a').get('href').split(':')[-1]  if soup.find('span',class_='icon icon-mail') else ''\n\t\tfacebook = soup.find('span',class_='icon icon-facebook').findParent('a').get('href') if soup.find('span',class_='icon icon-facebook') else ''\n\t\ttwitter = soup.find('span',class_='icon icon-twitter-3').findParent('a').get('href') if soup.find('span',class_='icon icon-twitter-3') else ''\n\t\tlink = soup.find('span',class_='icon icon-link').findParent('a').get('href') if soup.find('span',class_='icon icon-link') else ''\n\t\treturn Contact(email,facebook,twitter,link)",
    "docstring": "Factory Pattern. Fetches contact data from given soup and builds the object"
  },
  {
    "code": "def _compensate_humidity(self, adc_h):\n        var_h = self._temp_fine - 76800.0\n        if var_h == 0:\n            return 0\n        var_h = ((adc_h - (self._calibration_h[3] * 64.0 +\n                           self._calibration_h[4] / 16384.0 * var_h))\n                 * (self._calibration_h[1] / 65536.0\n                    * (1.0 + self._calibration_h[5] / 67108864.0 * var_h\n                       * (1.0 + self._calibration_h[2] / 67108864.0 * var_h))))\n        var_h *= 1.0 - self._calibration_h[0] * var_h / 524288.0\n        if var_h > 100.0:\n            var_h = 100.0\n        elif var_h < 0.0:\n            var_h = 0.0\n        return var_h",
    "docstring": "Compensate humidity.\n\n        Formula from datasheet Bosch BME280 Environmental sensor.\n        8.1 Compensation formulas in double precision floating point\n        Edition BST-BME280-DS001-10 | Revision 1.1 | May 2015."
  },
  {
    "code": "def maybe_a(generator):\n    class MaybeAGenerator(ArbitraryInterface):\n        @classmethod\n        def arbitrary(cls):\n            return arbitrary(one_of(None, generator))\n    MaybeAGenerator.__name__ = ''.join(['maybe_a(', generator.__name__, ')'])\n    return MaybeAGenerator",
    "docstring": "Generates either an arbitrary value of the specified generator or None.\n    This is a class factory, it makes a class which is a closure around the\n    specified generator."
  },
  {
    "code": "def virtualfields(self):\n        if self._virtualfields is None:\n            vfs = tuple()\n        else:\n            vfs = tuple(self._virtualfields)\n        return vfs",
    "docstring": "Returns a tuple listing the names of virtual fields in self."
  },
  {
    "code": "def one_of_keyword_only(*valid_keywords):\n    def decorator(func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            sentinel = object()\n            values = {}\n            for key in valid_keywords:\n                kwarg_value = kwargs.pop(key, sentinel)\n                if kwarg_value is not sentinel:\n                    values[key] = kwarg_value\n            if kwargs:\n                raise TypeError('Unexpected arguments: {}'.format(kwargs))\n            if not values:\n                raise TypeError('Must provide one of {} as keyword argument'.format(', '.join(valid_keywords)))\n            if len(values) > 1:\n                raise TypeError('Must provide only one of {} as keyword argument. Received {}'.format(\n                    ', '.join(valid_keywords),\n                    values\n                ))\n            return func(*(args + values.popitem()))\n        return wrapper\n    return decorator",
    "docstring": "Decorator to help make one-and-only-one keyword-only argument functions more reusable\n\n    Notes:\n        Decorated function should take 2 arguments, the first for the key, the second the value\n\n    Examples:\n\n        ::\n\n            @one_of_keyword_only('a', 'b', 'c')\n            def func(key, value):\n                if key == 'a':\n                    ...\n                elif key == 'b':\n                    ...\n                else:\n                    # key = 'c'\n                    ...\n\n            ...\n\n            func(a=1)\n            func(b=2)\n            func(c=3)\n\n            try:\n                func(d=4)\n            except TypeError:\n                ...\n\n            try:\n                func(a=1, b=2)\n            except TypeError:\n                ...\n\n    Args:\n        *valid_keywords (str): All allowed keyword argument names\n\n    Raises:\n        TypeError: On decorated call, if 0 or 2+ arguments are provided or kwargs contains a key not in valid_keywords"
  },
  {
    "code": "def dcmdottoang_vel(R,Rdot):\n    w = vee_map(Rdot.dot(R.T))\n    Omega = vee_map(R.T.dot(Rdot))\n    return (w, Omega)",
    "docstring": "Convert a rotation matrix to angular velocity\n        \n        w - angular velocity in inertial frame\n        Omega - angular velocity in body frame"
  },
  {
    "code": "def setDashboardOverlaySceneProcess(self, ulOverlayHandle, unProcessId):\n        fn = self.function_table.setDashboardOverlaySceneProcess\n        result = fn(ulOverlayHandle, unProcessId)\n        return result",
    "docstring": "Sets the dashboard overlay to only appear when the specified process ID has scene focus"
  },
  {
    "code": "def delete_host_template(self, name):\n    return host_templates.delete_host_template(self._get_resource_root(), name, self.name)",
    "docstring": "Deletes a host template.\n    @param name: Name of the host template to delete.\n    @return: An ApiHostTemplate object."
  },
  {
    "code": "def freeze(self):\n        self.target.disable()\n        self.filter.configure(state='disable')\n        self.prog_ob.configure(state='disable')\n        self.pi.configure(state='disable')\n        self.observers.configure(state='disable')\n        self.comment.configure(state='disable')",
    "docstring": "Freeze all settings so that they can't be altered"
  },
  {
    "code": "def dump(self):\n        self.print(\"Dumping data to {}\".format(self.dump_filename))\n        pickle.dump({\n            'data': self.counts,\n            'livetime': self.get_livetime()\n        }, open(self.dump_filename, \"wb\"))",
    "docstring": "Write coincidence counts into a Python pickle"
  },
  {
    "code": "def create_statement(\n        self, session_id: int, code: str, kind: StatementKind = None\n    ) -> Statement:\n        data = {\"code\": code}\n        if kind is not None:\n            if self.legacy_server():\n                LOGGER.warning(\"statement kind ignored on Livy<0.5.0\")\n            data[\"kind\"] = kind.value\n        response = self._client.post(\n            f\"/sessions/{session_id}/statements\", data=data\n        )\n        return Statement.from_json(session_id, response)",
    "docstring": "Run a statement in a session.\n\n        :param session_id: The ID of the session.\n        :param code: The code to execute.\n        :param kind: The kind of code to execute."
  },
  {
    "code": "def resolve_class(classref):\n    if classref is None:\n        return None\n    elif isinstance(classref, six.class_types):\n        return classref\n    elif isinstance(classref, six.string_types):\n        return import_class(classref)\n    else:\n        raise ValueError(\"Unable to resolve class for '%s'\" % classref)",
    "docstring": "Attempt to return a Python class for the input class reference.\n\n    If `classref` is a class or None, return it. If `classref` is a\n    python classpath (e.g., \"foo.bar.MyClass\") import the class and return\n    it.\n\n    Args:\n        classref: A fully-qualified Python path to class, or a Python class.\n\n    Returns:\n        A class."
  },
  {
    "code": "def _start_nodes_parallel(self, nodes, max_thread_pool_size):\n        thread_pool_size = min(len(nodes), max_thread_pool_size)\n        thread_pool = Pool(processes=thread_pool_size)\n        log.debug(\"Created pool of %d threads\", thread_pool_size)\n        keep_running = True\n        def sigint_handler(signal, frame):\n            log.error(\n                \"Interrupted: will save cluster state and exit\"\n                \" after all nodes have started.\")\n            keep_running = False\n        with sighandler(signal.SIGINT, sigint_handler):\n            result = thread_pool.map_async(self._start_node, nodes)\n            while not result.ready():\n                result.wait(1)\n                if not keep_running:\n                    log.error(\"Aborting upon user interruption ...\")\n                    thread_pool.close()\n                    thread_pool.join()\n                    self.repository.save_or_update(self)\n                    sys.exit(1)\n            return set(node for node, ok\n                       in itertools.izip(nodes, result.get()) if ok)",
    "docstring": "Start the nodes using a pool of multiprocessing threads for speed-up.\n\n        Return set of nodes that were actually started."
  },
  {
    "code": "def _is_broken_ref(key1, value1, key2, value2):\n    if key1 != 'Link' or key2 != 'Str':\n        return False\n    n = 0 if _PANDOCVERSION < '1.16' else 1\n    if isinstance(value1[n][0]['c'], list):\n        return False\n    s = value1[n][0]['c'] + value2\n    return True if _REF.match(s) else False",
    "docstring": "True if this is a broken reference; False otherwise."
  },
  {
    "code": "def spelling(self):\n        if not self.is_tagged(WORDS):\n            self.tokenize_words()\n        return [data[SPELLING] for data in vabamorf.spellcheck(self.word_texts, suggestions=False)]",
    "docstring": "Flag incorrectly spelled words.\n        Returns a list of booleans, where element at each position denotes, if the word at the same position\n        is spelled correctly."
  },
  {
    "code": "def query(self, q, format=\"\", convert=True):\n\t\tlines = [\"PREFIX %s: <%s>\" % (k, r) for k, r in self.prefixes.iteritems()]\n\t\tlines.extend(q.split(\"\\n\"))\n\t\tquery = \"\\n\".join(lines)\n\t\tif self.verbose:\n\t\t\tprint(query, \"\\n\\n\")\n\t\treturn self.__doQuery(query, format, convert)",
    "docstring": "Generic SELECT query structure. 'q' is the main body of the query.\n\n\t\tThe results passed out are not converted yet: see the 'format' method\n\t\tResults could be iterated using the idiom: for l in obj : do_something_with_line(l)\n\n\t\tIf convert is False, we return the collection of rdflib instances"
  },
  {
    "code": "def do(self, func, *args, **kwargs):\n        if not callable(func):\n            func = getattr(self.engine.function, func)\n        func(self, *args, **kwargs)\n        return self",
    "docstring": "Apply the function to myself, and return myself.\n\n        Look up the function in the database if needed. Pass it any\n        arguments given, keyword or positional.\n\n        Useful chiefly when chaining."
  },
  {
    "code": "def rect(self):\n        if self._w3c:\n            return self._execute(Command.GET_ELEMENT_RECT)['value']\n        else:\n            rect = self.size.copy()\n            rect.update(self.location)\n            return rect",
    "docstring": "A dictionary with the size and location of the element."
  },
  {
    "code": "def classes(self):\n        p = lambda o: isinstance(o, Class) and self._docfilter(o)\n        return sorted(filter(p, self.doc.values()))",
    "docstring": "Returns all documented module level classes in the module\n        sorted alphabetically as a list of `pydoc.Class`."
  },
  {
    "code": "def publish(self, exchange, routing_key, body, properties=None):\n        future = concurrent.Future()\n        properties = properties or {}\n        properties.setdefault('app_id', self.default_app_id)\n        properties.setdefault('message_id', str(uuid.uuid4()))\n        properties.setdefault('timestamp', int(time.time()))\n        if self.ready:\n            if self.publisher_confirmations:\n                self.message_number += 1\n                self.messages[self.message_number] = future\n            else:\n                future.set_result(None)\n            try:\n                self.channel.basic_publish(\n                    exchange, routing_key, body,\n                    pika.BasicProperties(**properties), True)\n            except exceptions.AMQPError as error:\n                future.set_exception(\n                    PublishingFailure(\n                        properties['message_id'],\n                        exchange, routing_key,\n                        error.__class__.__name__))\n        else:\n            future.set_exception(NotReadyError(\n                self.state_description, properties['message_id']))\n        return future",
    "docstring": "Publish a message to RabbitMQ. If the RabbitMQ connection is not\n        established or is blocked, attempt to wait until sending is possible.\n\n        :param str exchange: The exchange to publish the message to.\n        :param str routing_key: The routing key to publish the message with.\n        :param bytes body: The message body to send.\n        :param dict properties: An optional dict of additional properties\n                                to append.\n        :rtype: tornado.concurrent.Future\n        :raises: :exc:`sprockets.mixins.amqp.NotReadyError`\n        :raises: :exc:`sprockets.mixins.amqp.PublishingError`"
  },
  {
    "code": "def _latex_format(obj: Any) -> str:\n    if isinstance(obj, float):\n        try:\n            return sympy.latex(symbolize(obj))\n        except ValueError:\n            return \"{0:.4g}\".format(obj)\n    return str(obj)",
    "docstring": "Format an object as a latex string."
  },
  {
    "code": "def get_fields(model_class, field_name='', path=''):\n    fields = get_direct_fields_from_model(model_class)\n    app_label = model_class._meta.app_label\n    if field_name != '':\n        field, model, direct, m2m = _get_field_by_name(model_class, field_name)\n        path += field_name\n        path += '__'\n        if direct:\n            try:\n                new_model = _get_remote_field(field).parent_model\n            except AttributeError:\n                new_model = _get_remote_field(field).model\n        else:\n            new_model = field.related_model\n        fields = get_direct_fields_from_model(new_model)\n        app_label = new_model._meta.app_label\n    return {\n        'fields': fields,\n        'path': path,\n        'app_label': app_label,\n    }",
    "docstring": "Get fields and meta data from a model\n\n    :param model_class: A django model class\n    :param field_name: The field name to get sub fields from\n    :param path: path of our field in format\n        field_name__second_field_name__ect__\n    :returns: Returns fields and meta data about such fields\n        fields: Django model fields\n        properties: Any properties the model has\n        path: Our new path\n    :rtype: dict"
  },
  {
    "code": "def get_manifest_list(image, registry, insecure=False, dockercfg_path=None):\n    version = 'v2_list'\n    registry_session = RegistrySession(registry, insecure=insecure, dockercfg_path=dockercfg_path)\n    response, _ = get_manifest(image, registry_session, version)\n    return response",
    "docstring": "Return manifest list for image.\n\n    :param image: ImageName, the remote image to inspect\n    :param registry: str, URI for registry, if URI schema is not provided,\n                          https:// will be used\n    :param insecure: bool, when True registry's cert is not verified\n    :param dockercfg_path: str, dirname of .dockercfg location\n\n    :return: response, or None, with manifest list"
  },
  {
    "code": "def __normalize_name(self, name):\n        if not name.startswith(self.__root_namespace):\n            name = foundations.namespace.set_namespace(self.__root_namespace,\n                                                       foundations.namespace.set_namespace(self.__default_namespace,\n                                                                                           name))\n            LOGGER.debug(\"> Normalized name: '{0}'.\".format(name))\n            return name\n        else:\n            LOGGER.debug(\"> Name '{0}' is already normalized!\".format(name))\n            return name",
    "docstring": "Normalizes given action name.\n\n        :param name: Action name.\n        :type name: unicode\n        :return: Normalized name.\n        :rtype: bool"
  },
  {
    "code": "def get_context_data(self, **kwargs):\n        self.request.session.set_test_cookie()\n        if not self.request.session.test_cookie_worked():\n            messages.add_message(\n                self.request, messages.ERROR, \"Please enable cookies.\")\n        self.request.session.delete_test_cookie()\n        return super().get_context_data(**kwargs)",
    "docstring": "Tests cookies."
  },
  {
    "code": "def do_quit(self, args):\n        self._interp.set_break(self._interp.BREAK_NONE)\n        return True",
    "docstring": "The quit command"
  },
  {
    "code": "def role_get(user):\n    user_roles = []\n    with salt.utils.files.fopen('/etc/user_attr', 'r') as user_attr:\n        for role in user_attr:\n            role = salt.utils.stringutils.to_unicode(role)\n            role = role.strip().strip().split(':')\n            if len(role) != 5:\n                continue\n            if role[0] != user:\n                continue\n            attrs = {}\n            for attr in role[4].strip().split(';'):\n                attr_key, attr_val = attr.strip().split('=')\n                if attr_key in ['auths', 'profiles', 'roles']:\n                    attrs[attr_key] = attr_val.strip().split(',')\n                else:\n                    attrs[attr_key] = attr_val\n            if 'roles' in attrs:\n                user_roles.extend(attrs['roles'])\n    return list(set(user_roles))",
    "docstring": "List roles for user\n\n    user : string\n        username\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rbac.role_get leo"
  },
  {
    "code": "def encoded_query(self):\n        if self.query is not None and self.query != '' and self.query != {}:\n            try:\n                return urlencode(self.query, doseq=True, quote_via=urlquote)\n            except TypeError:\n                return '&'.join([\"{0}={1}\".format(urlquote(k), urlquote(self.query[k][0])) for k in self.query])\n        else:\n            return ''",
    "docstring": "Returns the encoded query string of the URL. This may be different from the rawquery element,\n        as that contains the query parsed by urllib but unmodified.\n        The return value takes the form of key=value&key=value, and it never contains a leading question mark."
  },
  {
    "code": "def getenv(key, value=None):\n    key = path2fsn(key)\n    if is_win and PY2:\n        return environ.get(key, value)\n    return os.getenv(key, value)",
    "docstring": "Like `os.getenv` but returns unicode under Windows + Python 2\n\n    Args:\n        key (pathlike): The env var to get\n        value (object): The value to return if the env var does not exist\n    Returns:\n        `fsnative` or `object`:\n            The env var or the passed value if it doesn't exist"
  },
  {
    "code": "def begin(self):\n        if not hasattr(self.local, 'tx'):\n            self.local.tx = []\n        self.local.tx.append(self.executable.begin())",
    "docstring": "Enter a transaction explicitly.\n\n        No data will be written until the transaction has been committed."
  },
  {
    "code": "def _subscribe_resp(self, data):\n        if _is_subscribe_response(data):\n            status = bytes([data[23]])\n            _LOGGER.debug(\"Successfully subscribed to %s, state: %s\",\n                          self.host, ord(status))\n            return status",
    "docstring": "Handle a subscribe response.\n\n        :param data: Payload.\n        :returns: State (ON/OFF)"
  },
  {
    "code": "def reward_scope(self,\n                     state: Sequence[tf.Tensor],\n                     action: Sequence[tf.Tensor],\n                     next_state: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]:\n        scope = {}\n        scope.update(self.non_fluents_scope())\n        scope.update(self.state_scope(state))\n        scope.update(self.action_scope(action))\n        scope.update(self.next_state_scope(next_state))\n        return scope",
    "docstring": "Returns the complete reward fluent scope for the\n        current `state`, `action` fluents, and `next_state` fluents.\n\n        Args:\n            state (Sequence[tf.Tensor]): The current state fluents.\n            action (Sequence[tf.Tensor]): The action fluents.\n            next_state (Sequence[tf.Tensor]): The next state fluents.\n\n        Returns:\n            A mapping from fluent names to :obj:`rddl2tf.fluent.TensorFluent`."
  },
  {
    "code": "def ecg_simulate(duration=10, sampling_rate=1000, bpm=60, noise=0.01):\n    cardiac = scipy.signal.wavelets.daub(10)\n    cardiac = np.concatenate([cardiac, np.zeros(10)])\n    num_heart_beats = int(duration * bpm / 60)\n    ecg = np.tile(cardiac , num_heart_beats)\n    noise = np.random.normal(0, noise, len(ecg))\n    ecg = noise + ecg\n    ecg = scipy.signal.resample(ecg, sampling_rate*duration)\n    return(ecg)",
    "docstring": "Simulates an ECG signal.\n\n    Parameters\n    ----------\n    duration : int\n        Desired recording length.\n    sampling_rate : int\n        Desired sampling rate.\n    bpm : int\n        Desired simulated heart rate.\n    noise : float\n        Desired noise level.\n\n\n    Returns\n    ----------\n    ECG_Response : dict\n        Event-related ECG response features.\n\n    Example\n    ----------\n    >>> import neurokit as nk\n    >>> import pandas as pd\n    >>>\n    >>> ecg = nk.ecg_simulate(duration=10, bpm=60, sampling_rate=1000, noise=0.01)\n    >>> pd.Series(ecg).plot()\n\n    Notes\n    ----------\n    *Authors*\n\n    - `Diarmaid O Cualain <https://github.com/diarmaidocualain>`_\n    - `Dominique Makowski <https://dominiquemakowski.github.io/>`_\n\n    *Dependencies*\n\n    - numpy\n    - scipy.signal\n\n    References\n    -----------"
  },
  {
    "code": "def _file_lines(self, filename):\n        try:\n            return self._file_lines_cache[filename]\n        except KeyError:\n            if os.path.isfile(filename):\n                with open(filename) as python_file:\n                    self._file_lines_cache[filename] = python_file.readlines()\n            else:\n                self._file_lines_cache[filename] = \"\"\n            return self._file_lines_cache[filename]",
    "docstring": "Get lines for filename, caching opened files."
  },
  {
    "code": "def get_orders(self, product_id=None, status=None, **kwargs):\n        params = kwargs\n        if product_id is not None:\n            params['product_id'] = product_id\n        if status is not None:\n            params['status'] = status\n        return self._send_paginated_message('/orders', params=params)",
    "docstring": "List your current open orders.\n\n        This method returns a generator which may make multiple HTTP requests\n        while iterating through it.\n\n        Only open or un-settled orders are returned. As soon as an\n        order is no longer open and settled, it will no longer appear\n        in the default request.\n\n        Orders which are no longer resting on the order book, will be\n        marked with the 'done' status. There is a small window between\n        an order being 'done' and 'settled'. An order is 'settled' when\n        all of the fills have settled and the remaining holds (if any)\n        have been removed.\n\n        For high-volume trading it is strongly recommended that you\n        maintain your own list of open orders and use one of the\n        streaming market data feeds to keep it updated. You should poll\n        the open orders endpoint once when you start trading to obtain\n        the current state of any open orders.\n\n        Args:\n            product_id (Optional[str]): Only list orders for this\n                product\n            status (Optional[list/str]): Limit list of orders to\n                this status or statuses. Passing 'all' returns orders\n                of all statuses.\n                ** Options: 'open', 'pending', 'active', 'done',\n                    'settled'\n                ** default: ['open', 'pending', 'active']\n\n        Returns:\n            list: Containing information on orders. Example::\n                [\n                    {\n                        \"id\": \"d0c5340b-6d6c-49d9-b567-48c4bfca13d2\",\n                        \"price\": \"0.10000000\",\n                        \"size\": \"0.01000000\",\n                        \"product_id\": \"BTC-USD\",\n                        \"side\": \"buy\",\n                        \"stp\": \"dc\",\n                        \"type\": \"limit\",\n                        \"time_in_force\": \"GTC\",\n                        \"post_only\": false,\n                        \"created_at\": \"2016-12-08T20:02:28.53864Z\",\n                        \"fill_fees\": \"0.0000000000000000\",\n                        \"filled_size\": \"0.00000000\",\n                        \"executed_value\": \"0.0000000000000000\",\n                        \"status\": \"open\",\n                        \"settled\": false\n                    },\n                    {\n                        ...\n                    }\n                ]"
  },
  {
    "code": "def makeSoftwareVersion(store, version, systemVersion):\n    return store.findOrCreate(SoftwareVersion,\n                              systemVersion=systemVersion,\n                              package=unicode(version.package),\n                              version=unicode(version.short()),\n                              major=version.major,\n                              minor=version.minor,\n                              micro=version.micro)",
    "docstring": "Return the SoftwareVersion object from store corresponding to the\n    version object, creating it if it doesn't already exist."
  },
  {
    "code": "def _run_detection(self):\n        if self.verbose:\n            print('Running QRS detection...')\n        self.qrs_inds = []\n        self.backsearch_qrs_inds = []\n        for self.peak_num in range(self.n_peaks_i):\n            if self._is_qrs(self.peak_num):\n                self._update_qrs(self.peak_num)\n            else:\n                self._update_noise(self.peak_num)\n            if self._require_backsearch():\n                self._backsearch()\n        if self.qrs_inds:\n            self.qrs_inds = np.array(self.qrs_inds) + self.sampfrom\n        else:\n            self.qrs_inds = np.array(self.qrs_inds)\n        if self.verbose:\n            print('QRS detection complete.')",
    "docstring": "Run the qrs detection after all signals and parameters have been\n        configured and set."
  },
  {
    "code": "def getelm(frstyr, lineln, lines):\n    frstyr = ctypes.c_int(frstyr)\n    lineln = ctypes.c_int(lineln)\n    lines = stypes.listToCharArrayPtr(lines, xLen=lineln, yLen=2)\n    epoch = ctypes.c_double()\n    elems = stypes.emptyDoubleVector(10)\n    libspice.getelm_c(frstyr, lineln, lines, ctypes.byref(epoch), elems)\n    return epoch.value, stypes.cVectorToPython(elems)",
    "docstring": "Given a the \"lines\" of a two-line element set, parse the\n    lines and return the elements in units suitable for use\n    in SPICE software.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/getelm_c.html\n\n    :param frstyr: Year of earliest representable two-line elements.\n    :type frstyr: int\n    :param lineln: Length of strings in lines array.\n    :type lineln: int\n    :param lines: A pair of \"lines\" containing two-line elements.\n    :type lines: list of str\n    :return:\n            The epoch of the elements in seconds past J2000,\n            The elements converted to SPICE units.\n    :rtype: tuple"
  },
  {
    "code": "def _resize_to_minimum(worksheet, rows=None, cols=None):\n    current_cols, current_rows = (\n        worksheet.col_count,\n        worksheet.row_count\n        )\n    if rows is not None and rows <= current_rows:\n        rows = None\n    if cols is not None and cols <= current_cols:\n        cols = None\n    if cols is not None or rows is not None:\n        worksheet.resize(rows, cols)",
    "docstring": "Resize the worksheet to guarantee a minimum size, either in rows,\n    or columns, or both.\n\n    Both rows and cols are optional."
  },
  {
    "code": "def list(self):\n        mylist = []\n        for prod in self.product_list:\n            if self.purchasable(prod) and not self.entitled(prod):\n                mylist.append(prod)\n        return mylist",
    "docstring": "return list of purchasable and not entitled products"
  },
  {
    "code": "def subscribe(self, clock_name: str=None, clock_slots: Iterable[str]=None, subscriptions: Dict[str, Any]={}):\n\t\tfor area in subscriptions:\n\t\t\tinit_full(self, area, subscriptions[area])\n\t\t\tsubscriptions[area] = {'slots': subscriptions[area]}\n\t\tif clock_name is not None:\n\t\t\tself.clock_name = clock_name\n\t\t\tself.clock_slots = clock_slots\n\t\t\tsubscriptions[clock_name] = {'slots': clock_slots, 'buffer-length': 1}\n\t\tself.setup(puller=True, subscriptions=subscriptions)",
    "docstring": "Subscribes this Area to the given Areas and optionally given Slots. Must be called before the Area is run.\n\n\t\tArgs:\n\t\t\tclock_name: The name of the Area that is used as synchronizing Clock.\n\t\t\tclock_slots: The slots of the Clock relevant to this Area.\n\t\t\tsubscriptions: A dictionary containing the relevant Areas names as keys and optionally the Slots as values."
  },
  {
    "code": "def get_std_dev_area(self, mag, rake):\n        assert rake is None or -180 <= rake <= 180\n        if rake is None:\n            return 0.24\n        elif (-45 <= rake <= 45) or (rake >= 135) or (rake <= -135):\n            return 0.22\n        elif rake > 0:\n            return 0.26\n        else:\n            return 0.22",
    "docstring": "Standard deviation for WC1994. Magnitude is ignored."
  },
  {
    "code": "def step(self, t, x_im1, v_im1_2, dt):\n        x_i = x_im1 + v_im1_2 * dt\n        F_i = self.F(t, np.vstack((x_i, v_im1_2)), *self._func_args)\n        a_i = F_i[self.ndim:]\n        v_i = v_im1_2 + a_i * dt / 2\n        v_ip1_2 = v_i + a_i * dt / 2\n        return x_i, v_i, v_ip1_2",
    "docstring": "Step forward the positions and velocities by the given timestep.\n\n        Parameters\n        ----------\n        dt : numeric\n            The timestep to move forward."
  },
  {
    "code": "def iter_grants(self, as_json=True):\n        self._connect()\n        result = self.db_connection.cursor().execute(\n            \"SELECT data, format FROM grants\"\n        )\n        for data, data_format in result:\n            if (not as_json) and data_format == 'json':\n                raise Exception(\"Cannot convert JSON source to XML output.\")\n            elif as_json and data_format == 'xml':\n                data = self.grantxml2json(data)\n            elif as_json and data_format == 'json':\n                data = json.loads(data)\n            yield data\n        self._disconnect()",
    "docstring": "Fetch records from the SQLite database."
  },
  {
    "code": "def convert_args(self, command, args):\n\t\tfor wanted, arg in zip(command.argtypes(), args):\n\t\t\twanted = wanted.type_\n\t\t\tif(wanted == \"const\"):\n\t\t\t\ttry:\n\t\t\t\t\tyield to_int(arg)\n\t\t\t\texcept:\n\t\t\t\t\tif(arg in self.processor.constants):\n\t\t\t\t\t\tyield self.processor.constants[arg]\n\t\t\t\t\telse:\n\t\t\t\t\t\tyield arg\n\t\t\tif(wanted == \"register\"):\n\t\t\t\tyield self.register_indices[arg]",
    "docstring": "Converts ``str -> int`` or ``register -> int``."
  },
  {
    "code": "def wait_for_completion(report, interval=10):\n    for jobid in report.collect('jobid'):\n        try:\n            if not Job.finished(jobid):\n                logging.info('waiting for SLURM job %s', jobid)\n                time.sleep(interval)\n                while not Job.finished(jobid):\n                    time.sleep(interval)\n            yield Job.fromid(jobid)._asdict()\n        except OSError as e:\n            if e.errno == errno.ENOENT:\n                yield dict(id=str(jobid))\n            else:\n                raise e",
    "docstring": "Wait for asynchronous jobs stil running in the given campaign.\n\n    :param report: memory representation of a campaign report\n    :type campaign: ReportNode\n    :param interval: wait interval\n    :type interval: int or float\n    :return: list of asynchronous job identifiers"
  },
  {
    "code": "def emit_event(self, event_name, event_body):\n        for transport in self.event_transports:\n            transport.emit_event(event_name, event_body)",
    "docstring": "Publishes an event of type ``event_name`` to all subscribers, having the body\n        ``event_body``. The event is pushed through all available event transports.\n\n        The event body must be a Python object that can be represented as a JSON.\n\n        :param event_name: a ``str`` representing the event type\n        :param event_body: a Python object that can be represented as JSON.\n\n        .. versionadded:: 0.5.0\n\n        .. versionchanged:: 0.10.0\n            Added parameter broadcast"
  },
  {
    "code": "def read_path(source, path, separator='/'):\n    parts = path.strip(separator).split(separator)\n    current = source\n    for part in parts[:-1]:\n        if part not in current:\n            return\n        current = current[part]\n        if not isinstance(current, dict):\n            return\n    return current.get(parts[-1])",
    "docstring": "Read a value from a dict supporting a deep path as a key.\n\n    :param source: a dict to read data from\n    :param path: a key or path to a key (path is delimited by `separator`)\n    :keyword separator: the separator used in the path (ex. Could be \".\" for a\n        json/mongodb type of value)"
  },
  {
    "code": "def get_by_id(self, institution_id, _options=None):\n        options = _options or {}\n        return self.client.post_public_key('/institutions/get_by_id', {\n            'institution_id': institution_id,\n            'options': options,\n        })",
    "docstring": "Fetch a single institution by id.\n\n        :param  str     institution_id:"
  },
  {
    "code": "def paranoidconfig(**kwargs):\n    def _decorator(func):\n        for k,v in kwargs.items():\n            Settings._set(k, v, function=func)\n        return _wrap(func)\n    return _decorator",
    "docstring": "A function decorator to set a local setting.\n\n    Settings may be set either globally (using\n    settings.Settings.set()) or locally using this decorator.  The\n    setting name should be passed as a keyword argument, and the value\n    to assign the setting should be passed as the value.  See\n    settings.Settings for the different settings which can be set.\n\n    Example usage:\n    \n      | @returns(Number)\n      | @paranoidconfig(enabled=False)\n      | def slow_function():\n      |     ..."
  },
  {
    "code": "def reset(self):\n        self.terms = OrderedDict()\n        self.y = None\n        self.backend = None\n        self.added_terms = []\n        self._added_priors = {}\n        self.completes = []\n        self.clean_data = None",
    "docstring": "Reset list of terms and y-variable."
  },
  {
    "code": "def wait_all_tasks_done(self, timeout=None, delay=0.5, interval=0.1):\n        timeout = self._timeout if timeout is None else timeout\n        timeout = timeout or float(\"inf\")\n        start_time = time.time()\n        time.sleep(delay)\n        while 1:\n            if not self.todo_tasks:\n                return self.all_tasks\n            if time.time() - start_time > timeout:\n                return self.done_tasks\n            time.sleep(interval)",
    "docstring": "Block, only be used while loop running in a single non-main thread."
  },
  {
    "code": "def CreateSmartShoppingAd(client, ad_group_id):\n  ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809')\n  adgroup_ad = {\n      'adGroupId': ad_group_id,\n      'ad': {\n          'xsi_type': 'GoalOptimizedShoppingAd'\n      }\n  }\n  ad_operation = {\n      'operator': 'ADD',\n      'operand': adgroup_ad\n  }\n  ad_result = ad_group_ad_service.mutate([ad_operation])\n  for adgroup_ad in ad_result['value']:\n    print 'Smart Shopping ad with ID \"%s\" was added.' % adgroup_ad['ad']['id']",
    "docstring": "Adds a new Smart Shopping ad.\n\n  Args:\n    client: an AdWordsClient instance.\n    ad_group_id: an integer ID for an ad group."
  },
  {
    "code": "def file_view(self, request, field_entry_id):\n        model = self.fieldentry_model\n        field_entry = get_object_or_404(model, id=field_entry_id)\n        path = join(fs.location, field_entry.value)\n        response = HttpResponse(content_type=guess_type(path)[0])\n        f = open(path, \"r+b\")\n        response[\"Content-Disposition\"] = \"attachment; filename=%s\" % f.name\n        response.write(f.read())\n        f.close()\n        return response",
    "docstring": "Output the file for the requested field entry."
  },
  {
    "code": "def fail(self, group, message):\n        logger.warn('Failing %s (%s): %s', self.jid, group, message)\n        return self.client('fail', self.jid, self.client.worker_name, group,\n            message, json.dumps(self.data)) or False",
    "docstring": "Mark the particular job as failed, with the provided type, and a\n        more specific message. By `type`, we mean some phrase that might be\n        one of several categorical modes of failure. The `message` is\n        something more job-specific, like perhaps a traceback.\n\n        This method should __not__ be used to note that a job has been dropped\n        or has failed in a transient way. This method __should__ be used to\n        note that a job has something really wrong with it that must be\n        remedied.\n\n        The motivation behind the `type` is so that similar errors can be\n        grouped together. Optionally, updated data can be provided for the job.\n        A job in any state can be marked as failed. If it has been given to a\n        worker as a job, then its subsequent requests to heartbeat or complete\n        that job will fail. Failed jobs are kept until they are canceled or\n        completed. __Returns__ the id of the failed job if successful, or\n        `False` on failure."
  },
  {
    "code": "def from_cwl(cls, data, __reference__=None):\n        class_name = data.get('class', None)\n        cls = cls.registry.get(class_name, cls)\n        if __reference__:\n            with with_reference(__reference__):\n                self = cls(\n                    **{k: v\n                       for k, v in iteritems(data) if k != 'class'}\n                )\n        else:\n            self = cls(**{k: v for k, v in iteritems(data) if k != 'class'})\n        return self",
    "docstring": "Return an instance from CWL data."
  },
  {
    "code": "def _check_all_devices_in_sync(self):\n        if len(self._get_devices_by_failover_status('In Sync')) != \\\n                len(self.devices):\n            msg = \"Expected all devices in group to have 'In Sync' status.\"\n            raise UnexpectedDeviceGroupState(msg)",
    "docstring": "Wait until all devices have failover status of 'In Sync'.\n\n        :raises: UnexpectedClusterState"
  },
  {
    "code": "def get(number, locale):\n        if locale == 'pt_BR':\n            locale = 'xbr'\n        if len(locale) > 3:\n            locale = locale.split(\"_\")[0]\n        rule = PluralizationRules._rules.get(locale, lambda _: 0)\n        _return = rule(number)\n        if not isinstance(_return, int) or _return < 0:\n            return 0\n        return _return",
    "docstring": "Returns the plural position to use for the given locale and number.\n\n        @type number: int\n        @param number: The number\n\n        @type locale: str\n        @param locale: The locale\n\n        @rtype: int\n        @return: The plural position"
  },
  {
    "code": "def paginate_resources(cls, request, resources, on_fail_status):\n        if not resources:\n            return (resources, client_list_control_pb2.ClientPagingResponse())\n        paging = request.paging\n        limit = min(paging.limit, MAX_PAGE_SIZE) or DEFAULT_PAGE_SIZE\n        try:\n            if paging.start:\n                start_index = cls.index_by_id(paging.start, resources)\n            else:\n                start_index = 0\n            if start_index < 0 or start_index >= len(resources):\n                raise AssertionError\n        except AssertionError:\n            raise _ResponseFailed(on_fail_status)\n        paged_resources = resources[start_index: start_index + limit]\n        if start_index + limit < len(resources):\n            paging_response = client_list_control_pb2.ClientPagingResponse(\n                next=cls.id_by_index(start_index + limit, resources),\n                start=cls.id_by_index(start_index, resources),\n                limit=limit)\n        else:\n            paging_response = client_list_control_pb2.ClientPagingResponse(\n                start=cls.id_by_index(start_index, resources),\n                limit=limit)\n        return paged_resources, paging_response",
    "docstring": "Truncates a list of resources based on ClientPagingControls\n\n        Args:\n            request (object): The parsed protobuf request object\n            resources (list of objects): The resources to be paginated\n\n        Returns:\n            list: The paginated list of resources\n            object: The ClientPagingResponse to be sent back to the client"
  },
  {
    "code": "def verify_hmac_sha1(request, client_secret=None,\n                     resource_owner_secret=None):\n    norm_params = normalize_parameters(request.params)\n    bs_uri = base_string_uri(request.uri)\n    sig_base_str = signature_base_string(request.http_method, bs_uri,\n                                         norm_params)\n    signature = sign_hmac_sha1(sig_base_str, client_secret,\n                               resource_owner_secret)\n    match = safe_string_equals(signature, request.signature)\n    if not match:\n        log.debug('Verify HMAC-SHA1 failed: signature base string: %s',\n                  sig_base_str)\n    return match",
    "docstring": "Verify a HMAC-SHA1 signature.\n\n    Per `section 3.4`_ of the spec.\n\n    .. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4\n\n    To satisfy `RFC2616 section 5.2`_ item 1, the request argument's uri\n    attribute MUST be an absolute URI whose netloc part identifies the\n    origin server or gateway on which the resource resides. Any Host\n    item of the request argument's headers dict attribute will be\n    ignored.\n\n    .. _`RFC2616 section 5.2`: https://tools.ietf.org/html/rfc2616#section-5.2"
  },
  {
    "code": "def register_payload(self, *payloads, flavour: ModuleType):\n        for payload in payloads:\n            self._logger.debug('registering payload %s (%s)', NameRepr(payload), NameRepr(flavour))\n            self.runners[flavour].register_payload(payload)",
    "docstring": "Queue one or more payload for execution after its runner is started"
  },
  {
    "code": "def add_repo(name,\n             description=None,\n             homepage=None,\n             private=None,\n             has_issues=None,\n             has_wiki=None,\n             has_downloads=None,\n             auto_init=None,\n             gitignore_template=None,\n             license_template=None,\n             profile=\"github\"):\n    try:\n        client = _get_client(profile)\n        organization = client.get_organization(\n            _get_config_value(profile, 'org_name')\n        )\n        given_params = {\n            'description': description,\n            'homepage': homepage,\n            'private': private,\n            'has_issues': has_issues,\n            'has_wiki': has_wiki,\n            'has_downloads': has_downloads,\n            'auto_init': auto_init,\n            'gitignore_template': gitignore_template,\n            'license_template': license_template\n        }\n        parameters = {'name': name}\n        for param_name, param_value in six.iteritems(given_params):\n            if param_value is not None:\n                parameters[param_name] = param_value\n        organization._requester.requestJsonAndCheck(\n            \"POST\",\n            organization.url + \"/repos\",\n            input=parameters\n        )\n        return True\n    except github.GithubException:\n        log.exception('Error creating a repo')\n        return False",
    "docstring": "Create a new github repository.\n\n    name\n        The name of the team to be created.\n\n    description\n        The description of the repository.\n\n    homepage\n        The URL with more information about the repository.\n\n    private\n        The visiblity of the repository. Note that private repositories require\n        a paid GitHub account.\n\n    has_issues\n        Whether to enable issues for this repository.\n\n    has_wiki\n        Whether to enable the wiki for this repository.\n\n    has_downloads\n        Whether to enable downloads for this repository.\n\n    auto_init\n        Whether to create an initial commit with an empty README.\n\n    gitignore_template\n        The desired language or platform for a .gitignore, e.g \"Haskell\".\n\n    license_template\n        The desired LICENSE template to apply, e.g \"mit\" or \"mozilla\".\n\n    profile\n        The name of the profile configuration to use. Defaults to ``github``.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion github.add_repo 'repo_name'\n\n    .. versionadded:: 2016.11.0"
  },
  {
    "code": "def list(self, **kwargs):\n        projects = Project.select().order_by(Project.name)\n        if len(projects) == 0:\n            self._print('No projects available', 'yellow')\n            return\n        for project in projects:\n            project_repr = self._PROJECT_ITEM.format(project.name, project.path)\n            row = '- {}'.format(self._PROJECT_ITEM.format(project.name, project.path))\n            six.print_(row)",
    "docstring": "displays all projects on database"
  },
  {
    "code": "def _fill_file_path(line, data):\n    def _find_file(xs, target):\n        if isinstance(xs, dict):\n            for v in xs.values():\n                f = _find_file(v, target)\n                if f:\n                    return f\n        elif isinstance(xs, (list, tuple)):\n            for x in xs:\n                f = _find_file(x, target)\n                if f:\n                    return f\n        elif isinstance(xs, six.string_types) and os.path.exists(xs) and xs.endswith(\"/%s\" % target):\n            return xs\n    orig_file = line.split(\"=\")[-1].replace('\"', '').strip()\n    full_file = _find_file(data, os.path.basename(orig_file))\n    if not full_file and os.path.exists(os.path.abspath(orig_file)):\n        full_file = os.path.abspath(orig_file)\n    assert full_file, \"Did not find vcfanno input file %s\" % (orig_file)\n    return 'file=\"%s\"\\n' % full_file",
    "docstring": "Fill in a full file path in the configuration file from data dictionary."
  },
  {
    "code": "def postappend(self):\n        if not self.doc and self.parent.doc:\n            self.setdocument(self.parent.doc)\n        if self.doc and self.doc.deepvalidation:\n            self.deepvalidation()",
    "docstring": "This method will be called after an element is added to another and does some checks.\n\n        It can do extra checks and if necessary raise exceptions to prevent addition. By default makes sure the right document is associated.\n\n        This method is mostly for internal use."
  },
  {
    "code": "def reconcileLimits(self):\n        if self.minValue < self.maxValue:\n            return\n        minFixed = (self.minValueSource in ['min'])\n        maxFixed = (self.maxValueSource in ['max', 'limit'])\n        if minFixed and maxFixed:\n            raise GraphError('The %s must be less than the %s' %\n                             (self.minValueSource, self.maxValueSource))\n        elif minFixed:\n            self.maxValue = self.minValue + self.chooseDelta(self.minValue)\n        elif maxFixed:\n            self.minValue = self.maxValue - self.chooseDelta(self.maxValue)\n        else:\n            delta = self.chooseDelta(max(abs(self.minValue),\n                                         abs(self.maxValue)))\n            average = (self.minValue + self.maxValue) / 2.0\n            self.minValue = average - delta\n            self.maxValue = average + delta",
    "docstring": "If self.minValue is not less than self.maxValue, fix the problem.\n\n        If self.minValue is not less than self.maxValue, adjust\n        self.minValue and/or self.maxValue (depending on which was not\n        specified explicitly by the user) to make self.minValue <\n        self.maxValue. If the user specified both limits explicitly, then\n        raise GraphError."
  },
  {
    "code": "def validate(self, r):\n        if self.show_invalid:\n            r.valid = True\n        elif r.valid:\n            if not r.description:\n                r.valid = False\n            if r.size and (r.size + r.offset) > r.file.size:\n                r.valid = False\n            if r.jump and (r.jump + r.offset) > r.file.size:\n                r.valid = False\n            if hasattr(r, \"location\") and (r.location != r.offset):\n                r.valid = False\n        if r.valid:\n            if r.id == self.one_of_many:\n                r.display = False\n            elif r.many:\n                self.one_of_many = r.id\n            else:\n                self.one_of_many = None",
    "docstring": "Called automatically by self.result."
  },
  {
    "code": "def pdebug(*args, **kwargs):\n    if should_msg(kwargs.get(\"groups\", [\"debug\"])):\n        global colorama_init\n        if not colorama_init:\n            colorama_init = True\n            colorama.init()\n        args = indent_text(*args, **kwargs)\n        sys.stderr.write(colorama.Fore.CYAN)\n        sys.stderr.write(\"\".join(args))\n        sys.stderr.write(colorama.Fore.RESET)\n        sys.stderr.write(\"\\n\")",
    "docstring": "print formatted output to stdout with indentation control"
  },
  {
    "code": "def linear_regression(self, target, regression_length, mask=NotSpecified):\n        from .statistical import RollingLinearRegression\n        return RollingLinearRegression(\n            dependent=self,\n            independent=target,\n            regression_length=regression_length,\n            mask=mask,\n        )",
    "docstring": "Construct a new Factor that performs an ordinary least-squares\n        regression predicting the columns of `self` from `target`.\n\n        This method can only be called on factors which are deemed safe for use\n        as inputs to other factors. This includes `Returns` and any factors\n        created from `Factor.rank` or `Factor.zscore`.\n\n        Parameters\n        ----------\n        target : zipline.pipeline.Term with a numeric dtype\n            The term to use as the predictor/independent variable in each\n            regression. This may be a Factor, a BoundColumn or a Slice. If\n            `target` is two-dimensional, regressions are computed asset-wise.\n        regression_length : int\n            Length of the lookback window over which to compute each\n            regression.\n        mask : zipline.pipeline.Filter, optional\n            A Filter describing which assets should be regressed with the\n            target slice each day.\n\n        Returns\n        -------\n        regressions : zipline.pipeline.factors.RollingLinearRegression\n            A new Factor that will compute linear regressions of `target`\n            against the columns of `self`.\n\n        Examples\n        --------\n        Suppose we want to create a factor that regresses AAPL's 10-day returns\n        against the 10-day returns of all other assets, computing each\n        regression over 30 days. This can be achieved by doing the following::\n\n            returns = Returns(window_length=10)\n            returns_slice = returns[sid(24)]\n            aapl_regressions = returns.linear_regression(\n                target=returns_slice, regression_length=30,\n            )\n\n        This is equivalent to doing::\n\n            aapl_regressions = RollingLinearRegressionOfReturns(\n                target=sid(24), returns_length=10, regression_length=30,\n            )\n\n        See Also\n        --------\n        :func:`scipy.stats.linregress`\n        :class:`zipline.pipeline.factors.RollingLinearRegressionOfReturns`"
  },
  {
    "code": "def Parse(self, stat, file_obj, knowledge_base):\n    _ = knowledge_base\n    lines = self.parser.ParseEntries(utils.ReadFileBytesAsUnicode(file_obj))\n    if os.path.basename(stat.pathspec.path) in self._CSH_FILES:\n      paths = self._ParseCshVariables(lines)\n    else:\n      paths = self._ParseShVariables(lines)\n    for path_name, path_vals in iteritems(paths):\n      yield rdf_protodict.AttributedDict(\n          config=stat.pathspec.path, name=path_name, vals=path_vals)",
    "docstring": "Identifies the paths set within a file.\n\n    Expands paths within the context of the file, but does not infer fully\n    expanded paths from external states. There are plenty of cases where path\n    attributes are unresolved, e.g. sourcing other files.\n\n    Lines are not handled literally. A field parser is used to:\n    - Break lines with multiple distinct statements into separate lines (e.g.\n      lines with a ';' separating stanzas.\n    - Strip out comments.\n    - Handle line continuations to capture multi-line configurations into one\n      statement.\n\n    Args:\n      stat: statentry\n      file_obj: VFSFile\n      knowledge_base: unused\n\n    Yields:\n      An attributed dict for each env vars. 'name' contains the path name, and\n      'vals' contains its vals."
  },
  {
    "code": "def find_ids(self, element_ids):\n        elements = [_transform.FigureElement.find_id(self, eid)\n                    for eid in element_ids]\n        return Panel(*elements)",
    "docstring": "Find elements with given IDs.\n\n        Parameters\n        ----------\n        element_ids : list of strings\n            list of IDs to find\n\n        Returns\n        -------\n        a new `Panel` object which contains all the found elements."
  },
  {
    "code": "def tokenize(string):\n    for match in TOKENS_REGEX.finditer(string):\n        yield Token(match.lastgroup, match.group().strip(), match.span())",
    "docstring": "Match and yield all the tokens of the input string."
  },
  {
    "code": "def choices_validator(choices):\n    def validator(value):\n        if value not in choices:\n            raise ValidationError(\n                \"{} is not in {}\".format(value, list(choices))\n            )\n    return validator",
    "docstring": "Return validator function that will check if ``value in choices``.\n\n    Args:\n        max_value (list, set, tuple): allowed choices for new validator"
  },
  {
    "code": "def wait(timeout: Optional[float] = None) -> Iterator[Any]:\n    if timeout is not None:\n        tcod.lib.SDL_WaitEventTimeout(tcod.ffi.NULL, int(timeout * 1000))\n    else:\n        tcod.lib.SDL_WaitEvent(tcod.ffi.NULL)\n    return get()",
    "docstring": "Block until events exist, then return an event iterator.\n\n    `timeout` is the maximum number of seconds to wait as a floating point\n    number with millisecond precision, or it can be None to wait forever.\n\n    Returns the same iterator as a call to :any:`tcod.event.get`.\n\n    Example::\n\n        for event in tcod.event.wait():\n            if event.type == \"QUIT\":\n                print(event)\n                raise SystemExit()\n            elif event.type == \"KEYDOWN\":\n                print(event)\n            elif event.type == \"MOUSEBUTTONDOWN\":\n                print(event)\n            elif event.type == \"MOUSEMOTION\":\n                print(event)\n            else:\n                print(event)"
  },
  {
    "code": "def asyncPipeStringtokenizer(context=None, _INPUT=None, conf=None, **kwargs):\n    conf['delimiter'] = conf.pop('to-str', dict.get(conf, 'delimiter'))\n    splits = yield asyncGetSplits(_INPUT, conf, **cdicts(opts, kwargs))\n    parsed = yield asyncDispatch(splits, *get_async_dispatch_funcs())\n    items = yield asyncStarMap(partial(maybeDeferred, parse_result), parsed)\n    _OUTPUT = utils.multiplex(items)\n    returnValue(_OUTPUT)",
    "docstring": "A string module that asynchronously splits a string into tokens\n    delimited by separators. Loopable.\n\n    Parameters\n    ----------\n    context : pipe2py.Context object\n    _INPUT : twisted Deferred iterable of items or strings\n    conf : {\n        'to-str': {'value': <delimiter>},\n        'dedupe': {'type': 'bool', value': <1>},\n        'sort': {'type': 'bool', value': <1>}\n    }\n\n    Returns\n    -------\n    _OUTPUT : twisted.internet.defer.Deferred generator of items"
  },
  {
    "code": "def recurse_module( overall_record, index, shared, stop_types=STOP_TYPES, already_seen=None, min_size=0 ):\n    for record in recurse( \n        overall_record, index, \n        stop_types=stop_types, \n        already_seen=already_seen, \n        type_group=True,\n    ):\n        if record.get('totsize') is not None:\n            continue \n        rinfo = record \n        rinfo['module'] = overall_record.get('name',NON_MODULE_REFS )\n        if not record['refs']:\n            rinfo['rsize'] = 0\n            rinfo['children'] = []\n        else:\n            rinfo['children'] = rinfo_children = list ( children( record, index, stop_types=stop_types ) )\n            rinfo['rsize'] = sum([\n                (\n                    child.get('totsize',0.0)/float(len(shared.get( child['address'], [])) or 1)\n                )\n                for child in rinfo_children\n            ], 0.0 )\n        rinfo['totsize'] = record['size'] + rinfo['rsize']\n    return None",
    "docstring": "Creates a has-a recursive-cost hierarchy\n    \n    Mutates objects in-place to produce a hierarchy of memory usage based on \n    reference-holding cost assignment"
  },
  {
    "code": "def read_sql(self, code: str) -> pandas.DataFrame:\n        if self.kind != SessionKind.SQL:\n            raise ValueError(\"not a SQL session\")\n        output = self._execute(code)\n        output.raise_for_status()\n        if output.json is None:\n            raise RuntimeError(\"statement had no JSON output\")\n        return dataframe_from_json_output(output.json)",
    "docstring": "Evaluate a Spark SQL satatement and retrieve the result.\n\n        :param code: The Spark SQL statement to evaluate."
  },
  {
    "code": "def split_input(val, mapper=None):\n    if mapper is None:\n        mapper = lambda x: x\n    if isinstance(val, list):\n        return list(map(mapper, val))\n    try:\n        return list(map(mapper, [x.strip() for x in val.split(',')]))\n    except AttributeError:\n        return list(map(mapper, [x.strip() for x in six.text_type(val).split(',')]))",
    "docstring": "Take an input value and split it into a list, returning the resulting list"
  },
  {
    "code": "def charm_icon(self, charm_id, channel=None):\n        url = self.charm_icon_url(charm_id, channel=channel)\n        response = self._get(url)\n        return response.content",
    "docstring": "Get the charm icon.\n\n        @param charm_id The ID of the charm.\n        @param channel Optional channel name."
  },
  {
    "code": "def render_secretfile(opt):\n    LOG.debug(\"Using Secretfile %s\", opt.secretfile)\n    secretfile_path = abspath(opt.secretfile)\n    obj = load_vars(opt)\n    return render(secretfile_path, obj)",
    "docstring": "Renders and returns the Secretfile construct"
  },
  {
    "code": "def _check_tcpdump():\n    with open(os.devnull, 'wb') as devnull:\n        try:\n            proc = subprocess.Popen([conf.prog.tcpdump, \"--version\"],\n                                    stdout=devnull, stderr=subprocess.STDOUT)\n        except OSError:\n            return False\n    if OPENBSD:\n        return proc.wait() == 1\n    else:\n        return proc.wait() == 0",
    "docstring": "Return True if the tcpdump command can be started"
  },
  {
    "code": "def updateFromKwargs(self, properties, kwargs, collector, **unused):\n        properties[self.name] = self.getFromKwargs(kwargs)",
    "docstring": "Primary entry point to turn 'kwargs' into 'properties"
  },
  {
    "code": "def poll(self, id):\n        id = self.__unpack_id(id)\n        url = '/api/v1/polls/{0}'.format(str(id))\n        return self.__api_request('GET', url)",
    "docstring": "Fetch information about the poll with the given id\n\n        Returns a `poll dict`_."
  },
  {
    "code": "def url_paths(self):\n        unformatted_paths = self._url_module.url_paths\n        paths = {}\n        for unformatted_path, handler in unformatted_paths.items():\n            path = unformatted_path.format(\"\")\n            paths[path] = handler\n        return paths",
    "docstring": "A dictionary of the paths of the urls to be mocked with this service and\n        the handlers that should be called in their place"
  },
  {
    "code": "def _to_ndarray(self, a):\n        if isinstance(a, (list, tuple)):\n            a = numpy.array(a)\n        if not is_ndarray(a):\n            raise TypeError(\"Expected an ndarray but got object of type '{}' instead\".format(type(a)))\n        return a",
    "docstring": "Casts Python lists and tuples to a numpy array or raises an AssertionError."
  },
  {
    "code": "def sanitize_random(value):\n    if not value:\n        return value\n    return ''.join(random.choice(CHARACTERS) for _ in range(len(value)))",
    "docstring": "Random string of same length as the given value."
  },
  {
    "code": "def sobol(N, dim, scrambled=1):\n    while(True):\n        seed = np.random.randint(2**32)\n        out = lowdiscrepancy.sobol(N, dim, scrambled, seed, 1, 0)\n        if (scrambled == 0) or ((out < 1.).all() and (out > 0.).all()):\n            return out",
    "docstring": "Sobol sequence. \n\n    Parameters\n    ----------\n    N : int\n        length of sequence\n    dim: int\n        dimension\n    scrambled: int\n        which scrambling method to use: \n\n            + 0: no scrambling\n            + 1: Owen's scrambling\n            + 2: Faure-Tezuka\n            + 3: Owen + Faure-Tezuka\n\n    Returns\n    -------\n    (N, dim) numpy array. \n\n\n    Notes \n    -----\n    For scrambling, seed is set randomly. \n\n    Fun fact: this venerable but playful piece of Fortran code occasionally\n    returns numbers above 1. (i.e. for a very small number of seeds); when this\n    happen we just start over (since the seed is randomly generated)."
  },
  {
    "code": "def subscriptions(self):\n        if _debug: ChangeOfValueServices._debug(\"subscriptions\")\n        subscription_list = []\n        for obj, cov_detection in self.cov_detections.items():\n            for cov in cov_detection.cov_subscriptions:\n                subscription_list.append(cov)\n        return subscription_list",
    "docstring": "Generator for the active subscriptions."
  },
  {
    "code": "def get_convex_hull(self):\n        proj, polygon2d = self._get_proj_convex_hull()\n        if isinstance(polygon2d, (shapely.geometry.LineString,\n                                  shapely.geometry.Point)):\n            polygon2d = polygon2d.buffer(self.DIST_TOLERANCE, 1)\n        from openquake.hazardlib.geo.polygon import Polygon\n        return Polygon._from_2d(polygon2d, proj)",
    "docstring": "Get a convex polygon object that contains projections of all the points\n        of the mesh.\n\n        :returns:\n            Instance of :class:`openquake.hazardlib.geo.polygon.Polygon` that\n            is a convex hull around all the points in this mesh. If the\n            original mesh had only one point, the resulting polygon has a\n            square shape with a side length of 10 meters. If there were only\n            two points, resulting polygon is a stripe 10 meters wide."
  },
  {
    "code": "def stdout(self):\n        stdout_path = os.path.join(self.config.artifact_dir, 'stdout')\n        if not os.path.exists(stdout_path):\n            raise AnsibleRunnerException(\"stdout missing\")\n        return open(os.path.join(self.config.artifact_dir, 'stdout'), 'r')",
    "docstring": "Returns an open file handle to the stdout representing the Ansible run"
  },
  {
    "code": "def remote_file_exists(self, url):\n        status = requests.head(url).status_code\n        if status != 200:\n            raise RemoteFileDoesntExist",
    "docstring": "Checks whether the remote file exists.\n\n        :param url:\n            The url that has to be checked.\n        :type url:\n            String\n\n        :returns:\n            **True** if remote file exists and **False** if it doesn't exist."
  },
  {
    "code": "def get(self, udid):\n        timeout = self.get_argument('timeout', 20.0)\n        if timeout is not None:\n            timeout = float(timeout)\n        que = self.ques[udid]\n        try:\n            item = yield que.get(timeout=time.time()+timeout)\n            print 'get from queue:', item\n            self.write(item)\n            que.task_done()\n        except gen.TimeoutError:\n            print 'timeout'\n            self.write('')\n        finally:\n            self.finish()",
    "docstring": "get new task"
  },
  {
    "code": "def fix_client_permissions(portal):\n    wfs = get_workflows()\n    start = time.time()\n    clients = portal.clients.objectValues()\n    total = len(clients)\n    for num, client in enumerate(clients):\n        logger.info(\"Fixing permission for client {}/{} ({})\"\n                    .format(num, total, client.getName()))\n        update_role_mappings(client, wfs=wfs)\n    end = time.time()\n    logger.info(\"Fixing client permissions took %.2fs\" % float(end-start))\n    transaction.commit()",
    "docstring": "Fix client permissions"
  },
  {
    "code": "def profile():\n    verification_form = VerificationForm(formdata=None, prefix=\"verification\")\n    profile_form = profile_form_factory()\n    form = request.form.get('submit', None)\n    if form == 'profile':\n        handle_profile_form(profile_form)\n    elif form == 'verification':\n        handle_verification_form(verification_form)\n    return render_template(\n        current_app.config['USERPROFILES_PROFILE_TEMPLATE'],\n        profile_form=profile_form,\n        verification_form=verification_form,)",
    "docstring": "View for editing a profile."
  },
  {
    "code": "def _get_default_annual_spacing(nyears):\n    if nyears < 11:\n        (min_spacing, maj_spacing) = (1, 1)\n    elif nyears < 20:\n        (min_spacing, maj_spacing) = (1, 2)\n    elif nyears < 50:\n        (min_spacing, maj_spacing) = (1, 5)\n    elif nyears < 100:\n        (min_spacing, maj_spacing) = (5, 10)\n    elif nyears < 200:\n        (min_spacing, maj_spacing) = (5, 25)\n    elif nyears < 600:\n        (min_spacing, maj_spacing) = (10, 50)\n    else:\n        factor = nyears // 1000 + 1\n        (min_spacing, maj_spacing) = (factor * 20, factor * 100)\n    return (min_spacing, maj_spacing)",
    "docstring": "Returns a default spacing between consecutive ticks for annual data."
  },
  {
    "code": "def extendedboldqc(auth, label, scan_ids=None, project=None, aid=None):\n    if not aid:\n        aid = accession(auth, label, project)\n    path = '/data/experiments'\n    params = {\n        'xsiType': 'neuroinfo:extendedboldqc',\n        'columns': ','.join(extendedboldqc.columns.keys())\n    }\n    if project:\n        params['project'] = project\n    params['xnat:mrSessionData/ID'] = aid\n    _,result = _get(auth, path, 'json', autobox=True, params=params)\n    for result in result['ResultSet']['Result']:\n        if scan_ids == None or result['neuroinfo:extendedboldqc/scan/scan_id'] in scan_ids:\n            data = dict()\n            for k,v in iter(extendedboldqc.columns.items()):\n                data[v] = result[k]\n            yield data",
    "docstring": "Get ExtendedBOLDQC data as a sequence of dictionaries.\n\n    Example:\n        >>> import yaxil\n        >>> import json\n        >>> auth = yaxil.XnatAuth(url='...', username='...', password='...')\n        >>> for eqc in yaxil.extendedboldqc2(auth, 'AB1234C')\n        ...     print(json.dumps(eqc, indent=2))\n\n    :param auth: XNAT authentication object\n    :type auth: :mod:`yaxil.XnatAuth`\n    :param label: XNAT MR Session label\n    :type label: str\n    :param scan_ids: Scan numbers to return\n    :type scan_ids: list\n    :param project: XNAT MR Session project\n    :type project: str\n    :param aid: XNAT Accession ID\n    :type aid: str\n    :returns: Generator of scan data dictionaries\n    :rtype: :mod:`dict`"
  },
  {
    "code": "def make_input_from_multiple_strings(sentence_id: SentenceId, strings: List[str]) -> TranslatorInput:\n    if not bool(strings):\n        return TranslatorInput(sentence_id=sentence_id, tokens=[], factors=None)\n    tokens = list(data_io.get_tokens(strings[0]))\n    factors = [list(data_io.get_tokens(factor)) for factor in strings[1:]]\n    if not all(len(factor) == len(tokens) for factor in factors):\n        logger.error(\"Length of string sequences do not match: '%s'\", strings)\n        return _bad_input(sentence_id, reason=str(strings))\n    return TranslatorInput(sentence_id=sentence_id, tokens=tokens, factors=factors)",
    "docstring": "Returns a TranslatorInput object from multiple strings, where the first element corresponds to the surface tokens\n    and the remaining elements to additional factors. All strings must parse into token sequences of the same length.\n\n    :param sentence_id: Sentence id.\n    :param strings: A list of strings representing a factored input sequence.\n    :return: A TranslatorInput."
  },
  {
    "code": "def get(name, defval=None):\n    with s_datfile.openDatFile('synapse.data/%s.mpk' % name) as fd:\n        return s_msgpack.un(fd.read())",
    "docstring": "Return an object from the embedded synapse data folder.\n\n    Example:\n\n        for tld in syanpse.data.get('iana.tlds'):\n            dostuff(tld)\n\n    NOTE: Files are named synapse/data/<name>.mpk"
  },
  {
    "code": "def all(self):\n        if self._stream:\n            return chain.from_iterable(self._get_streamed_response())\n        return self._get_buffered_response()[0]",
    "docstring": "Returns a chained generator response containing all matching records\n\n        :return:\n            - Iterable response"
  },
  {
    "code": "def from_string(cls, s):\n        stream = cStringIO(s)\n        stream.seek(0)\n        return cls(**yaml.safe_load(stream))",
    "docstring": "Create an istance from string s containing a YAML dictionary."
  },
  {
    "code": "def mri_head_reco_op_32_channel():\n    space = odl.uniform_discr(min_pt=[-115.2, -115.2],\n                              max_pt=[115.2, 115.2],\n                              shape=[256, 256],\n                              dtype=complex)\n    trafo = odl.trafos.FourierTransform(space)\n    return odl.ReductionOperator(odl.ComplexModulus(space) * trafo.inverse, 32)",
    "docstring": "Reconstruction operator for 32 channel MRI of a head.\n\n    This is a T2 weighted TSE scan of a healthy volunteer.\n\n    The reconstruction operator is the sum of the modulus of each channel.\n\n    See the data source with DOI `10.5281/zenodo.800527`_ or the\n    `project webpage`_ for further information.\n\n    See Also\n    --------\n    mri_head_data_32_channel\n\n    References\n    ----------\n    .. _10.5281/zenodo.800529: https://zenodo.org/record/800527\n    .. _project webpage: http://imsc.uni-graz.at/mobis/internal/\\\nplatform_aktuell.html"
  },
  {
    "code": "def predict(self, parameters, viterbi):\n        x_dot_parameters = np.einsum('ijk,kl->ijl', self.x, parameters)\n        if not viterbi:\n            alpha = forward_predict(self._lattice, x_dot_parameters,\n                                    self.state_machine.n_states)\n        else:\n            alpha = forward_max_predict(self._lattice, x_dot_parameters,\n                                        self.state_machine.n_states)\n        I, J, _ = self.x.shape\n        class_Z = {}\n        Z = -np.inf\n        for state, predicted_class in self.states_to_classes.items():\n            weight = alpha[I - 1, J - 1, state]\n            class_Z[self.states_to_classes[state]] = weight\n            Z = np.logaddexp(Z, weight)\n        return {label: np.exp(class_z - Z) for label, class_z in class_Z.items()}",
    "docstring": "Run forward algorithm to find the predicted distribution over classes."
  },
  {
    "code": "def ping(self, reconnect=True):\n        if self._sock is None:\n            if reconnect:\n                self.connect()\n                reconnect = False\n            else:\n                raise err.Error(\"Already closed\")\n        try:\n            self._execute_command(COMMAND.COM_PING, \"\")\n            self._read_ok_packet()\n        except Exception:\n            if reconnect:\n                self.connect()\n                self.ping(False)\n            else:\n                raise",
    "docstring": "Check if the server is alive.\n\n        :param reconnect: If the connection is closed, reconnect.\n        :raise Error: If the connection is closed and reconnect=False."
  },
  {
    "code": "def addEmptyTab(self, text=''):\n        tab = self.defaultTabWidget()\n        c = self.count()\n        self.addTab(tab, text)\n        self.setCurrentIndex(c)\n        if not text:\n            self.tabBar().editTab(c)\n        self.sigTabAdded.emit(tab)\n        return tab",
    "docstring": "Add a new DEFAULT_TAB_WIDGET, open editor to set text if no text is given"
  },
  {
    "code": "def _apply_index_days(self, i, roll):\n        nanos = (roll % 2) * Timedelta(days=self.day_of_month - 1).value\n        return i + nanos.astype('timedelta64[ns]')",
    "docstring": "Add days portion of offset to DatetimeIndex i.\n\n        Parameters\n        ----------\n        i : DatetimeIndex\n        roll : ndarray[int64_t]\n\n        Returns\n        -------\n        result : DatetimeIndex"
  },
  {
    "code": "def circle(branch: str):\n    assert os.environ.get('CIRCLE_BRANCH') == branch\n    assert not os.environ.get('CI_PULL_REQUEST')",
    "docstring": "Performs necessary checks to ensure that the circle build is one\n    that should create releases.\n\n    :param branch: The branch the environment should be running against."
  },
  {
    "code": "def _filter_plans(attr, name, plans):\n    return [plan for plan in plans if plan[attr] == name]",
    "docstring": "Helper to return list of usage plan items matching the given attribute value."
  },
  {
    "code": "def makedbthreads(self):\n        for sample in self.metadata:\n            if sample[self.analysistype].combinedtargets != 'NA':\n                self.targetfolders.add(sample[self.analysistype].targetpath)\n        for i in range(len(self.targetfolders)):\n            threads = Thread(target=self.makeblastdb, args=())\n            threads.setDaemon(True)\n            threads.start()\n        for targetdir in self.targetfolders:\n            self.targetfiles = glob(os.path.join(targetdir, '*.fasta'))\n            try:\n                _ = self.targetfiles[0]\n            except IndexError:\n                self.targetfiles = glob(os.path.join(targetdir, '*.fasta'))\n            for targetfile in self.targetfiles:\n                self.records[targetfile] = SeqIO.to_dict(SeqIO.parse(targetfile, 'fasta'))\n                self.dqueue.put(targetfile)\n        self.dqueue.join()",
    "docstring": "Setup and create threads for class"
  },
  {
    "code": "def addAggShkDstn(self,AggShkDstn):\n        if len(self.IncomeDstn[0]) > 3:\n            self.IncomeDstn = self.IncomeDstnWithoutAggShocks\n        else:\n            self.IncomeDstnWithoutAggShocks = self.IncomeDstn\n        self.IncomeDstn = [combineIndepDstns(self.IncomeDstn[t],AggShkDstn) for t in range(self.T_cycle)]",
    "docstring": "Updates attribute IncomeDstn by combining idiosyncratic shocks with aggregate shocks.\n\n        Parameters\n        ----------\n        AggShkDstn : [np.array]\n            Aggregate productivity shock distribution.  First element is proba-\n            bilities, second element is agg permanent shocks, third element is\n            agg transitory shocks.\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def _is_device(path):\n    out = __salt__['cmd.run_all']('file -i {0}'.format(path))\n    _verify_run(out)\n    return re.split(r'\\s+', out['stdout'])[1][:-1] == 'inode/blockdevice'",
    "docstring": "Return True if path is a physical device."
  },
  {
    "code": "def convert_to_string(ndarr):\n    with contextlib.closing(BytesIO()) as bytesio:\n        _internal_write(bytesio, ndarr)\n        return bytesio.getvalue()",
    "docstring": "Writes the contents of the numpy.ndarray ndarr to bytes in IDX format and\n    returns it."
  },
  {
    "code": "def _GetSignatureMatchParserNames(self, file_object):\n    parser_names = []\n    scan_state = pysigscan.scan_state()\n    self._file_scanner.scan_file_object(scan_state, file_object)\n    for scan_result in iter(scan_state.scan_results):\n      format_specification = (\n          self._formats_with_signatures.GetSpecificationBySignature(\n              scan_result.identifier))\n      if format_specification.identifier not in parser_names:\n        parser_names.append(format_specification.identifier)\n    return parser_names",
    "docstring": "Determines if a file-like object matches one of the known signatures.\n\n    Args:\n      file_object (file): file-like object whose contents will be checked\n          for known signatures.\n\n    Returns:\n      list[str]: parser names for which the contents of the file-like object\n          matches their known signatures."
  },
  {
    "code": "def run(self, **client_params):\n        try:\n            self.send(self.get_collection_endpoint(),\n                      http_method=\"POST\",\n                      **client_params)\n        except Exception as e:\n            raise CartoException(e)",
    "docstring": "Actually creates the async job on the CARTO server\n\n\n        :param client_params: To be send to the CARTO API. See CARTO's\n                                documentation depending on the subclass\n                                you are using\n        :type client_params: kwargs\n\n\n        :return:\n        :raise: CartoException"
  },
  {
    "code": "def find_guest(name, quiet=False, path=None):\n    if quiet:\n        log.warning(\"'quiet' argument is being deprecated.\"\n                 ' Please migrate to --quiet')\n    for data in _list_iter(path=path):\n        host, l = next(six.iteritems(data))\n        for x in 'running', 'frozen', 'stopped':\n            if name in l[x]:\n                if not quiet:\n                    __jid_event__.fire_event(\n                        {'data': host,\n                         'outputter': 'lxc_find_host'},\n                        'progress')\n                return host\n    return None",
    "docstring": "Returns the host for a container.\n\n    path\n        path to the container parent\n        default: /var/lib/lxc (system default)\n\n        .. versionadded:: 2015.8.0\n\n\n    .. code-block:: bash\n\n        salt-run lxc.find_guest name"
  },
  {
    "code": "def to_sky(self, wcs, mode='all'):\n        sky_params = self._to_sky_params(wcs, mode=mode)\n        return SkyCircularAperture(**sky_params)",
    "docstring": "Convert the aperture to a `SkyCircularAperture` object defined\n        in celestial coordinates.\n\n        Parameters\n        ----------\n        wcs : `~astropy.wcs.WCS`\n            The world coordinate system (WCS) transformation to use.\n\n        mode : {'all', 'wcs'}, optional\n            Whether to do the transformation including distortions\n            (``'all'``; default) or only including only the core WCS\n            transformation (``'wcs'``).\n\n        Returns\n        -------\n        aperture : `SkyCircularAperture` object\n            A `SkyCircularAperture` object."
  },
  {
    "code": "def get_empty_tracks(self):\n        empty_track_indices = [idx for idx, track in enumerate(self.tracks)\n                               if not np.any(track.pianoroll)]\n        return empty_track_indices",
    "docstring": "Return the indices of tracks with empty pianorolls.\n\n        Returns\n        -------\n        empty_track_indices : list\n            The indices of tracks with empty pianorolls."
  },
  {
    "code": "def _multiline_convert(config, start=\"banner login\", end=\"EOF\", depth=1):\n        ret = list(config)\n        try:\n            s = ret.index(start)\n            e = s\n            while depth:\n                e = ret.index(end, e + 1)\n                depth = depth - 1\n        except ValueError:\n            return ret\n        ret[s] = {\"cmd\": ret[s], \"input\": \"\\n\".join(ret[s + 1 : e])}\n        del ret[s + 1 : e + 1]\n        return ret",
    "docstring": "Converts running-config HEREDOC into EAPI JSON dict"
  },
  {
    "code": "def update_descriptor_le(self, lineedit, tf):\n        if tf:\n            descriptor = tf.descriptor\n            lineedit.setText(descriptor)\n        else:\n            lineedit.setText(\"\")",
    "docstring": "Update the given line edit to show the descriptor that is stored in the index\n\n        :param lineedit: the line edit to update with the descriptor\n        :type lineedit: QLineEdit\n        :param tf: the selected taskfileinfo\n        :type tf: :class:`TaskFileInfo` | None\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def write(self, data):\n        if not isinstance(data, (bytes, bytearray, list)):\n            raise TypeError(\"Invalid data type, should be bytes, bytearray, or list.\")\n        if isinstance(data, list):\n            data = bytearray(data)\n        try:\n            return os.write(self._fd, data)\n        except OSError as e:\n            raise SerialError(e.errno, \"Writing serial port: \" + e.strerror)",
    "docstring": "Write `data` to the serial port and return the number of bytes\n        written.\n\n        Args:\n            data (bytes, bytearray, list): a byte array or list of 8-bit integers to write.\n\n        Returns:\n            int: number of bytes written.\n\n        Raises:\n            SerialError: if an I/O or OS error occurs.\n            TypeError: if `data` type is invalid.\n            ValueError: if data is not valid bytes."
  },
  {
    "code": "def account_delete(request, username,\n        template_name=accounts_settings.ACCOUNTS_PROFILE_DETAIL_TEMPLATE,\n        extra_context=None, **kwargs):\n    user = get_object_or_404(get_user_model(),\n                             username__iexact=username)\n    user.is_active = False\n    user.save()\n    return redirect(reverse('accounts_admin'))",
    "docstring": "Delete an account."
  },
  {
    "code": "def create_mv_rule(tensorprod_rule, dim):\n    def mv_rule(order, sparse=False, part=None):\n        if sparse:\n            order = numpy.ones(dim, dtype=int)*order\n            tensorprod_rule_ = lambda order, part=part:\\\n                tensorprod_rule(order, part=part)\n            return chaospy.quad.sparse_grid(tensorprod_rule_, order)\n        return tensorprod_rule(order, part=part)\n    return mv_rule",
    "docstring": "Convert tensor product rule into a multivariate quadrature generator."
  },
  {
    "code": "def signal_committed_filefields(sender, instance, **kwargs):\n    for field_name in getattr(instance, '_uncommitted_filefields', ()):\n        fieldfile = getattr(instance, field_name)\n        if fieldfile:\n            signals.saved_file.send_robust(sender=sender, fieldfile=fieldfile)",
    "docstring": "A post_save signal handler which sends a signal for each ``FileField`` that\n    was committed this save."
  },
  {
    "code": "def find_transition(self, gene: Gene, multiplexes: Tuple[Multiplex, ...]) -> Transition:\n        multiplexes = tuple(multiplex for multiplex in multiplexes if gene in multiplex.genes)\n        for transition in self.transitions:\n            if transition.gene == gene and set(transition.multiplexes) == set(multiplexes):\n                return transition\n        raise AttributeError(f'transition K_{gene.name}' + ''.join(f\"+{multiplex!r}\" for multiplex in multiplexes) + ' does not exist')",
    "docstring": "Find and return a transition in the model for the given gene and multiplexes.\n        Raise an AttributeError if there is no multiplex in the graph with the given name."
  },
  {
    "code": "def emit(event, *args, **kwargs):\n    if 'namespace' in kwargs:\n        namespace = kwargs['namespace']\n    else:\n        namespace = flask.request.namespace\n    callback = kwargs.get('callback')\n    broadcast = kwargs.get('broadcast')\n    room = kwargs.get('room')\n    if room is None and not broadcast:\n        room = flask.request.sid\n    include_self = kwargs.get('include_self', True)\n    ignore_queue = kwargs.get('ignore_queue', False)\n    socketio = flask.current_app.extensions['socketio']\n    return socketio.emit(event, *args, namespace=namespace, room=room,\n                         include_self=include_self, callback=callback,\n                         ignore_queue=ignore_queue)",
    "docstring": "Emit a SocketIO event.\n\n    This function emits a SocketIO event to one or more connected clients. A\n    JSON blob can be attached to the event as payload. This is a function that\n    can only be called from a SocketIO event handler, as in obtains some\n    information from the current client context. Example::\n\n        @socketio.on('my event')\n        def handle_my_custom_event(json):\n            emit('my response', {'data': 42})\n\n    :param event: The name of the user event to emit.\n    :param args: A dictionary with the JSON data to send as payload.\n    :param namespace: The namespace under which the message is to be sent.\n                      Defaults to the namespace used by the originating event.\n                      A ``'/'`` can be used to explicitly specify the global\n                      namespace.\n    :param callback: Callback function to invoke with the client's\n                     acknowledgement.\n    :param broadcast: ``True`` to send the message to all clients, or ``False``\n                      to only reply to the sender of the originating event.\n    :param room: Send the message to all the users in the given room. If this\n                 argument is set, then broadcast is implied to be ``True``.\n    :param include_self: ``True`` to include the sender when broadcasting or\n                         addressing a room, or ``False`` to send to everyone\n                         but the sender.\n    :param ignore_queue: Only used when a message queue is configured. If\n                         set to ``True``, the event is emitted to the\n                         clients directly, without going through the queue.\n                         This is more efficient, but only works when a\n                         single server process is used, or when there is a\n                         single addresee. It is recommended to always leave\n                         this parameter with its default value of ``False``."
  },
  {
    "code": "def sequence_charge(seq, pH=7.4):\n    if 'X' in seq:\n        warnings.warn(_nc_warning_str, NoncanonicalWarning)\n    adj_protein_charge = sum(\n        [partial_charge(aa, pH) * residue_charge[aa] * n\n         for aa, n in Counter(seq).items()])\n    adj_protein_charge += (\n        partial_charge('N-term', pH) * residue_charge['N-term'])\n    adj_protein_charge += (\n        partial_charge('C-term', pH) * residue_charge['C-term'])\n    return adj_protein_charge",
    "docstring": "Calculates the total charge of the input polypeptide sequence.\n\n    Parameters\n    ----------\n    seq : str\n        Sequence of amino acids.\n    pH : float\n        pH of interest."
  },
  {
    "code": "def allowed_transitions():\n    try:\n        sdp_state = SDPState()\n        return sdp_state.allowed_target_states[sdp_state.current_state]\n    except KeyError:\n        LOG.error(\"Key Error\")\n        return dict(state=\"KeyError\", reason=\"KeyError\")",
    "docstring": "Get target states allowed for the current state."
  },
  {
    "code": "def _DecodeUrlSafe(urlsafe):\n  if not isinstance(urlsafe, basestring):\n    raise TypeError('urlsafe must be a string; received %r' % urlsafe)\n  if isinstance(urlsafe, unicode):\n    urlsafe = urlsafe.encode('utf8')\n  mod = len(urlsafe) % 4\n  if mod:\n    urlsafe += '=' * (4 - mod)\n  return base64.b64decode(urlsafe.replace('-', '+').replace('_', '/'))",
    "docstring": "Decode a url-safe base64-encoded string.\n\n  This returns the decoded string."
  },
  {
    "code": "def with_params(self, params):\n        return self.replace(params=_merge_maps(self.params, params))",
    "docstring": "Create a new request with added query parameters\n\n        Parameters\n        ----------\n        params: Mapping\n            the query parameters to add"
  },
  {
    "code": "def validate_accounting_equation(cls):\n        balances = [account.balance(raw=True) for account in Account.objects.root_nodes()]\n        if sum(balances, Balance()) != 0:\n            raise exceptions.AccountingEquationViolationError(\n                \"Account balances do not sum to zero. They sum to {}\".format(sum(balances))\n            )",
    "docstring": "Check that all accounts sum to 0"
  },
  {
    "code": "def get_participants_for_section(section, person=None):\n    section_label = encode_section_label(section.section_label())\n    url = \"/rest/gradebook/v1/section/{}/participants\".format(section_label)\n    headers = {}\n    if person is not None:\n        headers[\"X-UW-Act-as\"] = person.uwnetid\n    data = get_resource(url, headers)\n    participants = []\n    for pt in data[\"participants\"]:\n        participants.append(_participant_from_json(pt))\n    return participants",
    "docstring": "Returns a list of gradebook participants for the passed section and person."
  },
  {
    "code": "def _ask_questionnaire():\n    answers = {}\n    print(info_header)\n    pprint(questions.items())\n    for question, default in questions.items():\n        response = _ask(question, default, str(type(default)), show_hint=True)\n        if type(default) == unicode and type(response) != str:\n            response = response.decode('utf-8')\n        answers[question] = response\n    return answers",
    "docstring": "Asks questions to fill out a HFOS plugin template"
  },
  {
    "code": "def trigger_script(self):\n        if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED,):\n            return [1]\n        try:\n            self.remote_bridge.parsed_script = UpdateScript.FromBinary(self._device.script)\n            self.remote_bridge.status = BRIDGE_STATUS.IDLE\n        except Exception as exc:\n            self._logger.exception(\"Error parsing script streamed to device\")\n            self.remote_bridge.script_error = exc\n            self.remote_bridge.error = 1\n        return [0]",
    "docstring": "Actually process a script."
  },
  {
    "code": "def reprkwargs(kwargs, sep=', ', fmt=\"{0!s}={1!r}\"):\n    return sep.join(fmt.format(k, v) for k, v in kwargs.iteritems())",
    "docstring": "Display kwargs."
  },
  {
    "code": "def set_log_format(log_format, server=_DEFAULT_SERVER):\n    setting = 'LogPluginClsid'\n    log_format_types = get_log_format_types()\n    format_id = log_format_types.get(log_format, None)\n    if not format_id:\n        message = (\"Invalid log format '{0}' specified. Valid formats:\"\n                   ' {1}').format(log_format, log_format_types.keys())\n        raise SaltInvocationError(message)\n    _LOG.debug(\"Id for '%s' found: %s\", log_format, format_id)\n    current_log_format = get_log_format(server)\n    if log_format == current_log_format:\n        _LOG.debug('%s already contains the provided format.', setting)\n        return True\n    _set_wmi_setting('IIsSmtpServerSetting', setting, format_id, server)\n    new_log_format = get_log_format(server)\n    ret = log_format == new_log_format\n    if ret:\n        _LOG.debug(\"Setting %s configured successfully: %s\", setting, log_format)\n    else:\n        _LOG.error(\"Unable to configure %s with value: %s\", setting, log_format)\n    return ret",
    "docstring": "Set the active log format for the SMTP virtual server.\n\n    :param str log_format: The log format name.\n    :param str server: The SMTP server name.\n\n    :return: A boolean representing whether the change succeeded.\n    :rtype: bool\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' win_smtp_server.set_log_format 'Microsoft IIS Log File Format'"
  },
  {
    "code": "def _serve_runs(self, request):\n    if self._db_connection_provider:\n      db = self._db_connection_provider()\n      cursor = db.execute(\n)\n      run_names = [row[0] for row in cursor]\n    else:\n      run_names = sorted(self._multiplexer.Runs())\n      def get_first_event_timestamp(run_name):\n        try:\n          return self._multiplexer.FirstEventTimestamp(run_name)\n        except ValueError as e:\n          logger.warn(\n              'Unable to get first event timestamp for run %s: %s', run_name, e)\n          return float('inf')\n      run_names.sort(key=get_first_event_timestamp)\n    return http_util.Respond(request, run_names, 'application/json')",
    "docstring": "Serve a JSON array of run names, ordered by run started time.\n\n    Sort order is by started time (aka first event time) with empty times sorted\n    last, and then ties are broken by sorting on the run name."
  },
  {
    "code": "def chmod(f):\n    try:\n        os.chmod(f, S_IWRITE)\n    except Exception as e:\n        pass\n    try:\n        os.chmod(f, 0o777)\n    except Exception as e:\n        pass",
    "docstring": "change mod to writeable"
  },
  {
    "code": "def enable_glut(self, app=None):\n        import OpenGL.GLUT as glut\n        from pydev_ipython.inputhookglut import glut_display_mode, \\\n                                              glut_close, glut_display, \\\n                                              glut_idle, inputhook_glut\n        if GUI_GLUT not in self._apps:\n            glut.glutInit(sys.argv)\n            glut.glutInitDisplayMode(glut_display_mode)\n            if bool(glut.glutSetOption):\n                glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE,\n                                    glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS)\n            glut.glutCreateWindow(sys.argv[0])\n            glut.glutReshapeWindow(1, 1)\n            glut.glutHideWindow()\n            glut.glutWMCloseFunc(glut_close)\n            glut.glutDisplayFunc(glut_display)\n            glut.glutIdleFunc(glut_idle)\n        else:\n            glut.glutWMCloseFunc(glut_close)\n            glut.glutDisplayFunc(glut_display)\n            glut.glutIdleFunc(glut_idle)\n        self.set_inputhook(inputhook_glut)\n        self._current_gui = GUI_GLUT\n        self._apps[GUI_GLUT] = True",
    "docstring": "Enable event loop integration with GLUT.\n\n        Parameters\n        ----------\n\n        app : ignored\n            Ignored, it's only a placeholder to keep the call signature of all\n            gui activation methods consistent, which simplifies the logic of\n            supporting magics.\n\n        Notes\n        -----\n\n        This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to\n        integrate with terminal based applications like IPython. Due to GLUT\n        limitations, it is currently not possible to start the event loop\n        without first creating a window. You should thus not create another\n        window but use instead the created one. See 'gui-glut.py' in the\n        docs/examples/lib directory.\n\n        The default screen mode is set to:\n        glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH"
  },
  {
    "code": "def download_and_parse_mnist_file(fname, target_dir=None, force=False):\n    fname = download_file(fname, target_dir=target_dir, force=force)\n    fopen = gzip.open if os.path.splitext(fname)[1] == '.gz' else open\n    with fopen(fname, 'rb') as fd:\n        return parse_idx(fd)",
    "docstring": "Download the IDX file named fname from the URL specified in dataset_url\n    and return it as a numpy array.\n\n    Parameters\n    ----------\n    fname : str\n        File name to download and parse\n\n    target_dir : str\n        Directory where to store the file\n\n    force : bool\n        Force downloading the file, if it already exists\n\n    Returns\n    -------\n    data : numpy.ndarray\n        Numpy array with the dimensions and the data in the IDX file"
  },
  {
    "code": "def form(**kwargs: Question):\n    return Form(*(FormField(k, q) for k, q in kwargs.items()))",
    "docstring": "Create a form with multiple questions.\n\n    The parameter name of a question will be the key for the answer in\n    the returned dict."
  },
  {
    "code": "def __get_ac_tree(self, ac: model.AssetClass, with_stocks: bool):\n        output = []\n        output.append(self.__get_ac_row(ac))\n        for child in ac.classes:\n            output += self.__get_ac_tree(child, with_stocks)\n        if with_stocks:\n            for stock in ac.stocks:\n                row = None\n                if isinstance(stock, Stock):\n                    row = self.__get_stock_row(stock, ac.depth + 1)\n                elif isinstance(stock, CashBalance):\n                    row = self.__get_cash_row(stock, ac.depth + 1)\n                output.append(row)\n        return output",
    "docstring": "formats the ac tree - entity with child elements"
  },
  {
    "code": "def find_largest_contig(self):\n        for sample in self.metadata:\n            sample[self.analysistype].longest_contig = sample[self.analysistype].contig_lengths",
    "docstring": "Determine the largest contig for each strain"
  },
  {
    "code": "def _create_aural_content_element(self, content, data_property_value):\n        content_element = self._create_content_element(\n            content,\n            data_property_value\n        )\n        content_element.set_attribute('unselectable', 'on')\n        content_element.set_attribute('class', 'screen-reader-only')\n        return content_element",
    "docstring": "Create a element to show the content, only to aural displays.\n\n        :param content: The text content of element.\n        :type content: str\n        :param data_property_value: The value of custom attribute used to\n                                    identify the fix.\n        :type data_property_value: str\n        :return: The element to show the content.\n        :rtype: hatemile.util.html.htmldomelement.HTMLDOMElement"
  },
  {
    "code": "def _add_baseline_to_exclude_files(args):\n    baseline_name_regex = r'^{}$'.format(args.import_filename[0])\n    if not args.exclude_files:\n        args.exclude_files = baseline_name_regex\n    elif baseline_name_regex not in args.exclude_files:\n        args.exclude_files += r'|{}'.format(baseline_name_regex)",
    "docstring": "Modifies args.exclude_files in-place."
  },
  {
    "code": "def focus_changed(self):\r\n        fwidget = QApplication.focusWidget()\r\n        for finfo in self.data:\r\n            if fwidget is finfo.editor:\r\n                self.refresh()\r\n        self.editor_focus_changed.emit()",
    "docstring": "Editor focus has changed"
  },
  {
    "code": "def set_measurements(test):\n  test.measurements.level_none = 0\n  time.sleep(1)\n  test.measurements.level_some = 8\n  time.sleep(1)\n  test.measurements.level_all = 9\n  time.sleep(1)\n  level_all = test.get_measurement('level_all')\n  assert level_all.value == 9",
    "docstring": "Test phase that sets a measurement."
  },
  {
    "code": "def prepend_urls(self):\n        return [\n            url(r\"^(?P<resource_name>%s)/(?P<pk>\\w[\\w/-]*)/generate%s$\" %\n                (self._meta.resource_name, trailing_slash()),\n                self.wrap_view('generate'), name=\"api_tileset_generate\"),\n            url(r\"^(?P<resource_name>%s)/(?P<pk>\\w[\\w/-]*)/download%s$\" %\n                (self._meta.resource_name, trailing_slash()),\n                self.wrap_view('download'), name=\"api_tileset_download\"),\n            url(r\"^(?P<resource_name>%s)/(?P<pk>\\w[\\w/-]*)/status%s$\" %\n                (self._meta.resource_name, trailing_slash()),\n                self.wrap_view('status'), name=\"api_tileset_status\"),\n            url(r\"^(?P<resource_name>%s)/(?P<pk>\\w[\\w/-]*)/stop%s$\" %\n                (self._meta.resource_name, trailing_slash()),\n                self.wrap_view('stop'), name=\"api_tileset_stop\"),\n        ]",
    "docstring": "Add the following array of urls to the Tileset base urls"
  },
  {
    "code": "def _abort_batches(self):\n        error = Errors.IllegalStateError(\"Producer is closed forcefully.\")\n        for batch in self._incomplete.all():\n            tp = batch.topic_partition\n            with self._tp_locks[tp]:\n                batch.records.close()\n            batch.done(exception=error)\n            self.deallocate(batch)",
    "docstring": "Go through incomplete batches and abort them."
  },
  {
    "code": "def _read_protocol_line(self):\n        while True:\n            line = self._proc.stdout.readline().decode('utf-8')\n            if not line:\n                raise jsonrpc_client_base.AppStartError(\n                    self._ad, 'Unexpected EOF waiting for app to start')\n            line = line.strip()\n            if (line.startswith('INSTRUMENTATION_RESULT:')\n                    or line.startswith('SNIPPET ')):\n                self.log.debug(\n                    'Accepted line from instrumentation output: \"%s\"', line)\n                return line\n            self.log.debug('Discarded line from instrumentation output: \"%s\"',\n                           line)",
    "docstring": "Reads the next line of instrumentation output relevant to snippets.\n\n        This method will skip over lines that don't start with 'SNIPPET' or\n        'INSTRUMENTATION_RESULT'.\n\n        Returns:\n            (str) Next line of snippet-related instrumentation output, stripped.\n\n        Raises:\n            jsonrpc_client_base.AppStartError: If EOF is reached without any\n                protocol lines being read."
  },
  {
    "code": "def log_detail(job_id=None, task_name=None, log_id=None):\n        jobs = get_jobs()\n        job = [job for job in jobs if str(job['job_id']) == job_id][0]\n        return render_template('log_detail.html',\n                               job=job,\n                               task_name=task_name,\n                               task=[task for task in job['tasks']\n                                     if task['name'] == task_name][0],\n                               log_id=log_id)",
    "docstring": "Show a detailed description of a specific log."
  },
  {
    "code": "def element_href_use_filter(name, _filter):\n    if name and _filter:\n        element = fetch_meta_by_name(name, filter_context=_filter)\n        if element.json:\n            return element.json.pop().get('href')",
    "docstring": "Get element href using filter\n\n    Filter should be a valid entry point value, ie host, router, network,\n    single_fw, etc\n\n    :param name: name of element\n    :param _filter: filter type, unknown filter will result in no matches\n    :return: element href (if found), else None"
  },
  {
    "code": "def add_note(path, filename=\"note.txt\"):\n    path = os.path.expanduser(path)\n    assert os.path.isdir(path), \"{} is not a valid directory.\".format(path)\n    filepath = os.path.join(path, filename)\n    exists = os.path.isfile(filepath)\n    try:\n        subprocess.call([EDITOR, filepath])\n    except Exception as exc:\n        logger.error(\"Editing note failed!\")\n        raise exc\n    if exists:\n        print(\"Note updated at:\", filepath)\n    else:\n        print(\"Note created at:\", filepath)",
    "docstring": "Opens a txt file at the given path where user can add and save notes.\n\n    Args:\n        path (str): Directory where note will be saved.\n        filename (str): Name of note. Defaults to \"note.txt\""
  },
  {
    "code": "def _rgbtomask(self, obj):\n        dat = obj.get_image().get_data()\n        return dat.sum(axis=2).astype(np.bool)",
    "docstring": "Convert RGB arrays from mask canvas object back to boolean mask."
  },
  {
    "code": "def preformat_call(self, api_call):\n        api_call_formatted = api_call.lstrip('/')\n        api_call_formatted = api_call_formatted.rstrip('?')\n        if api_call != api_call_formatted:\n            logger.debug('api_call post strip =\\n%s' % api_call_formatted)\n        return api_call_formatted",
    "docstring": "Return properly formatted QualysGuard API call."
  },
  {
    "code": "def get_changed_files(self) -> List[str]:\n        out = shell_tools.output_of(\n            'git',\n            'diff',\n            '--name-only',\n            self.compare_commit_id,\n            self.actual_commit_id,\n            '--',\n            cwd=self.destination_directory)\n        return [e for e in out.split('\\n') if e.strip()]",
    "docstring": "Get the files changed on one git branch vs another.\n\n        Returns:\n            List[str]: File paths of changed files, relative to the git repo\n                root."
  },
  {
    "code": "def _get_next(request):\n    next = request.POST.get('next', request.GET.get('next',\n                            request.META.get('HTTP_REFERER', None)))\n    if not next:\n        next = request.path\n    return next",
    "docstring": "The part that's the least straightforward about views in this module is\n    how they determine their redirects after they have finished computation.\n\n    In short, they will try and determine the next place to go in the\n    following order:\n\n    1. If there is a variable named ``next`` in the *POST* parameters, the\n       view will redirect to that variable's value.\n    2. If there is a variable named ``next`` in the *GET* parameters,\n       the view will redirect to that variable's value.\n    3. If Django can determine the previous page from the HTTP headers,\n       the view will redirect to that previous page."
  },
  {
    "code": "def updates_selection(update_selection):\n    def handle_update(selection, *args, **kwargs):\n        old_selection = selection.get_all()\n        update_selection(selection, *args, **kwargs)\n        new_selection = selection.get_all()\n        affected_models = old_selection ^ new_selection\n        if len(affected_models) != 0:\n            deselected_models = old_selection - new_selection\n            selected_models = new_selection - old_selection\n            map(selection.relieve_model, deselected_models)\n            map(selection.observe_model, selected_models)\n            selection.update_core_element_lists()\n            if selection.focus and selection.focus not in new_selection:\n                del selection.focus\n            affected_classes = set(model.core_element.__class__ for model in affected_models)\n            msg_namedtuple = SelectionChangedSignalMsg(update_selection.__name__, new_selection, old_selection,\n                                                       affected_classes)\n            selection.selection_changed_signal.emit(msg_namedtuple)\n            if selection.parent_signal is not None:\n                selection.parent_signal.emit(msg_namedtuple)\n    return handle_update",
    "docstring": "Decorator indicating that the decorated method could change the selection"
  },
  {
    "code": "def compute_date_range_chunks(sessions, start_date, end_date, chunksize):\n    if start_date not in sessions:\n        raise KeyError(\"Start date %s is not found in calendar.\" %\n                       (start_date.strftime(\"%Y-%m-%d\"),))\n    if end_date not in sessions:\n        raise KeyError(\"End date %s is not found in calendar.\" %\n                       (end_date.strftime(\"%Y-%m-%d\"),))\n    if end_date < start_date:\n        raise ValueError(\"End date %s cannot precede start date %s.\" %\n                         (end_date.strftime(\"%Y-%m-%d\"),\n                          start_date.strftime(\"%Y-%m-%d\")))\n    if chunksize is None:\n        return [(start_date, end_date)]\n    start_ix, end_ix = sessions.slice_locs(start_date, end_date)\n    return (\n        (r[0], r[-1]) for r in partition_all(\n            chunksize, sessions[start_ix:end_ix]\n        )\n    )",
    "docstring": "Compute the start and end dates to run a pipeline for.\n\n    Parameters\n    ----------\n    sessions : DatetimeIndex\n        The available dates.\n    start_date : pd.Timestamp\n        The first date in the pipeline.\n    end_date : pd.Timestamp\n        The last date in the pipeline.\n    chunksize : int or None\n        The size of the chunks to run. Setting this to None returns one chunk.\n\n    Returns\n    -------\n    ranges : iterable[(np.datetime64, np.datetime64)]\n        A sequence of start and end dates to run the pipeline for."
  },
  {
    "code": "def GetZipInfoByPathSpec(self, path_spec):\n    location = getattr(path_spec, 'location', None)\n    if location is None:\n      raise errors.PathSpecError('Path specification missing location.')\n    if not location.startswith(self.LOCATION_ROOT):\n      raise errors.PathSpecError('Invalid location in path specification.')\n    if len(location) > 1:\n      return self._zip_file.getinfo(location[1:])\n    return None",
    "docstring": "Retrieves the ZIP info for a path specification.\n\n    Args:\n      path_spec (PathSpec): a path specification.\n\n    Returns:\n      zipfile.ZipInfo: a ZIP info object or None if not available.\n\n    Raises:\n      PathSpecError: if the path specification is incorrect."
  },
  {
    "code": "def _find_combo_data(widget, value):\n    for idx in range(widget.count()):\n        if widget.itemData(idx) is value or (widget.itemData(idx) == value) is True:\n            return idx\n    else:\n        raise ValueError(\"%s not found in combo box\" % (value,))",
    "docstring": "Returns the index in a combo box where itemData == value\n\n    Raises a ValueError if data is not found"
  },
  {
    "code": "def get_scalar_product(self, other):\n        return self.x*other.x+self.y*other.y",
    "docstring": "Returns the scalar product of this vector with the given\n        other vector."
  },
  {
    "code": "def compute_mga_entropy_stat(mga_vec, codon_pos,\n                             stat_func=np.mean,\n                             default_val=0.0):\n    if mga_vec is None:\n        return default_val\n    myscores = fetch_mga_scores(mga_vec, codon_pos)\n    if myscores is not None and len(myscores):\n        score_stat = stat_func(myscores)\n    else:\n        score_stat = default_val\n    return score_stat",
    "docstring": "Compute MGA entropy conservation statistic\n\n    Parameters\n    ----------\n    mga_vec : np.array\n        numpy vector containing MGA Entropy conservation scores for residues\n    codon_pos : list of int\n        position of codon in protein sequence\n    stat_func : function, default=np.mean\n        function that calculates a statistic\n    default_val : float\n        default value to return if there are no mutations\n\n    Returns\n    -------\n    score_stat : float\n        MGA entropy score statistic for provided mutation list"
  },
  {
    "code": "def pdf(self, mu):\n        if self.transform is not None:\n            mu = self.transform(mu)                \n        return ss.poisson.pmf(mu, self.lmd0)",
    "docstring": "PDF for Poisson prior\n\n        Parameters\n        ----------\n        mu : float\n            Latent variable for which the prior is being formed over\n\n        Returns\n        ----------\n        - p(mu)"
  },
  {
    "code": "def get_alternative(self, experiment_name):\n        experiment = None\n        try:\n            experiment = experiment_manager[experiment_name]\n        except KeyError:\n            pass\n        if experiment:\n            if experiment.is_displaying_alternatives():\n                alternative = self._get_enrollment(experiment)\n                if alternative is not None:\n                    return alternative\n            else:\n                return experiment.default_alternative\n        return conf.CONTROL_GROUP",
    "docstring": "Get the alternative this user is enrolled in."
  },
  {
    "code": "def _mpl_marker2pgfp_marker(data, mpl_marker, marker_face_color):\n    try:\n        pgfplots_marker = _MP_MARKER2PGF_MARKER[mpl_marker]\n    except KeyError:\n        pass\n    else:\n        if (marker_face_color is not None) and pgfplots_marker == \"o\":\n            pgfplots_marker = \"*\"\n            data[\"tikz libs\"].add(\"plotmarks\")\n        marker_options = None\n        return (data, pgfplots_marker, marker_options)\n    try:\n        data[\"tikz libs\"].add(\"plotmarks\")\n        pgfplots_marker, marker_options = _MP_MARKER2PLOTMARKS[mpl_marker]\n    except KeyError:\n        pass\n    else:\n        if (\n            marker_face_color is not None\n            and (\n                not isinstance(marker_face_color, str)\n                or marker_face_color.lower() != \"none\"\n            )\n            and pgfplots_marker not in [\"|\", \"-\", \"asterisk\", \"star\"]\n        ):\n            pgfplots_marker += \"*\"\n        return (data, pgfplots_marker, marker_options)\n    return data, None, None",
    "docstring": "Translates a marker style of matplotlib to the corresponding style\n    in PGFPlots."
  },
  {
    "code": "def bartlett(timeseries, segmentlength, **kwargs):\n    kwargs.pop('noverlap', None)\n    return welch(timeseries, segmentlength, noverlap=0, **kwargs)",
    "docstring": "Calculate a PSD using Bartlett's method"
  },
  {
    "code": "def stop_service(name):\n        with win32.OpenSCManager(\n            dwDesiredAccess = win32.SC_MANAGER_CONNECT\n        ) as hSCManager:\n            with win32.OpenService(hSCManager, name,\n                                   dwDesiredAccess = win32.SERVICE_STOP\n            ) as hService:\n                win32.ControlService(hService, win32.SERVICE_CONTROL_STOP)",
    "docstring": "Stop the service given by name.\n\n        @warn: This method requires UAC elevation in Windows Vista and above.\n\n        @see: L{get_services}, L{get_active_services},\n            L{start_service}, L{pause_service}, L{resume_service}"
  },
  {
    "code": "def item_selection_changed(self):\r\n        is_selection = len(self.selectedItems()) > 0\r\n        self.expand_selection_action.setEnabled(is_selection)\r\n        self.collapse_selection_action.setEnabled(is_selection)",
    "docstring": "Item selection has changed"
  },
  {
    "code": "def lasio_get(l,\n              section,\n              item,\n              attrib='value',\n              default=None,\n              remap=None,\n              funcs=None):\n    remap = remap or {}\n    item_to_fetch = remap.get(item, item)\n    if item_to_fetch is None:\n        return None\n    try:\n        obj = getattr(l, section)\n        result = getattr(obj, item_to_fetch)[attrib]\n    except:\n        return default\n    if funcs is not None:\n        f = funcs.get(item, null)\n        result = f(result)\n    return result",
    "docstring": "Grabs, renames and transforms stuff from a lasio object.\n\n    Args:\n        l (lasio): a lasio instance.\n        section (str): The LAS section to grab from, eg ``well``\n        item (str): The item in the LAS section to grab from, eg ``name``\n        attrib (str): The attribute of the item to grab, eg ``value``\n        default (str): What to return instead.\n        remap (dict): Optional. A dict of 'old': 'new' LAS field names.\n        funcs (dict): Optional. A dict of 'las field': function() for\n            implementing a transform before loading. Can be a lambda.\n\n    Returns:\n        The transformed item."
  },
  {
    "code": "def get_system_by_name(self, name):\n        for elem in self.systems:\n            if elem.name == name:\n                return elem\n        return None",
    "docstring": "Return a system with that name or None."
  },
  {
    "code": "def find_nn_triangles_point(tri, cur_tri, point):\n    r\n    nn = []\n    candidates = set(tri.neighbors[cur_tri])\n    candidates |= set(tri.neighbors[tri.neighbors[cur_tri]].flat)\n    candidates.discard(-1)\n    for neighbor in candidates:\n        triangle = tri.points[tri.simplices[neighbor]]\n        cur_x, cur_y = circumcenter(triangle[0], triangle[1], triangle[2])\n        r = circumcircle_radius_2(triangle[0], triangle[1], triangle[2])\n        if dist_2(point[0], point[1], cur_x, cur_y) < r:\n            nn.append(neighbor)\n    return nn",
    "docstring": "r\"\"\"Return the natural neighbors of a triangle containing a point.\n\n    This is based on the provided Delaunay Triangulation.\n\n    Parameters\n    ----------\n    tri: Object\n        A Delaunay Triangulation\n    cur_tri: int\n        Simplex code for Delaunay Triangulation lookup of\n        a given triangle that contains 'position'.\n    point: (x, y)\n        Coordinates used to calculate distances to\n        simplexes in 'tri'.\n\n    Returns\n    -------\n    nn: (N, ) array\n        List of simplex codes for natural neighbor\n        triangles in 'tri'."
  },
  {
    "code": "def gramian(self):\n        if self.mode == 'spark':\n            rdd = self.values.tordd()\n            from pyspark.accumulators import AccumulatorParam\n            class MatrixAccumulator(AccumulatorParam):\n                def zero(self, value):\n                    return zeros(shape(value))\n                def addInPlace(self, val1, val2):\n                    val1 += val2\n                    return val1\n            global mat\n            init = zeros((self.shape[1], self.shape[1]))\n            mat = rdd.context.accumulator(init, MatrixAccumulator())\n            def outer_sum(x):\n                global mat\n                mat += outer(x, x)\n            rdd.values().foreach(outer_sum)\n            return self._constructor(mat.value, index=self.index)\n        if self.mode == 'local':\n            return self._constructor(dot(self.values.T, self.values), index=self.index)",
    "docstring": "Compute gramian of a distributed matrix.\n\n        The gramian is defined as the product of the matrix\n        with its transpose, i.e. A^T * A."
  },
  {
    "code": "def transform(self, jam, query=None):\n        anns = []\n        if query:\n            results = jam.search(**query)\n        else:\n            results = jam.annotations\n        for ann in results:\n            try:\n                anns.append(jams.nsconvert.convert(ann, self.namespace))\n            except jams.NamespaceError:\n                pass\n        duration = jam.file_metadata.duration\n        if not anns:\n            anns = [self.empty(duration)]\n        results = []\n        for ann in anns:\n            results.append(self.transform_annotation(ann, duration))\n            if ann.time is None or ann.duration is None:\n                valid = [0, duration]\n            else:\n                valid = [ann.time, ann.time + ann.duration]\n            results[-1]['_valid'] = time_to_frames(valid, sr=self.sr,\n                                                   hop_length=self.hop_length)\n        return self.merge(results)",
    "docstring": "Transform jam object to make data for this task\n\n        Parameters\n        ----------\n        jam : jams.JAMS\n            The jams container object\n\n        query : string, dict, or callable [optional]\n            An optional query to narrow the elements of `jam.annotations`\n            to be considered.\n\n            If not provided, all annotations are considered.\n\n        Returns\n        -------\n        data : dict\n            A dictionary of transformed annotations.\n            All annotations which can be converted to the target namespace\n            will be converted."
  },
  {
    "code": "def algebra_simplify(alphabet_size=26,\n                     min_depth=0,\n                     max_depth=2,\n                     nbr_cases=10000):\n  if max_depth < min_depth:\n    raise ValueError(\"max_depth must be greater than or equal to min_depth. \"\n                     \"Got max_depth=%s, min_depth=%s\" % (max_depth, min_depth))\n  alg_cfg = math_dataset_init(alphabet_size, digits=5)\n  for _ in range(nbr_cases):\n    sample, target = generate_algebra_simplify_sample(\n        alg_cfg.vlist, list(alg_cfg.ops.values()), min_depth, max_depth)\n    yield {\n        \"inputs\": alg_cfg.int_encoder(sample),\n        \"targets\": alg_cfg.int_encoder(target)\n    }",
    "docstring": "Generate the algebra simplify dataset.\n\n  Each sample is a symbolic math expression involving unknown variables. The\n  task is to simplify the expression. The target is the resulting expression.\n\n  Args:\n    alphabet_size: How many possible variables there are. Max 52.\n    min_depth: Minimum depth of the expression trees on both sides of the\n        equals sign in the equation.\n    max_depth: Maximum depth of the expression trees on both sides of the\n        equals sign in the equation.\n    nbr_cases: The number of cases to generate.\n\n  Yields:\n    A dictionary {\"inputs\": input-list, \"targets\": target-list} where\n    input-list are the tokens encoding the expression to simplify, and\n    target-list is a list of tokens encoding the resulting math expression after\n    simplifying.\n\n  Raises:\n    ValueError: If `max_depth` < `min_depth`."
  },
  {
    "code": "def get_channelstate_settled(\n        chain_state: ChainState,\n        payment_network_id: PaymentNetworkID,\n        token_address: TokenAddress,\n) -> List[NettingChannelState]:\n    return get_channelstate_filter(\n        chain_state,\n        payment_network_id,\n        token_address,\n        lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_SETTLED,\n    )",
    "docstring": "Return the state of settled channels in a token network."
  },
  {
    "code": "def get(self, do_process_raw_report = True):\r\n        \"Read report from device\"\r\n        assert(self.__hid_object.is_opened())\r\n        if self.__report_kind != HidP_Input and \\\r\n                self.__report_kind != HidP_Feature:\r\n            raise HIDError(\"Only for input or feature reports\")\r\n        self.__alloc_raw_data()\r\n        raw_data = self.__raw_data\r\n        raw_data[0] = self.__report_id\r\n        read_function = None\r\n        if self.__report_kind == HidP_Feature:\r\n            read_function = hid_dll.HidD_GetFeature\r\n        elif self.__report_kind == HidP_Input:\r\n            read_function = hid_dll.HidD_GetInputReport\r\n        if read_function and read_function(int(self.__hid_object.hid_handle),\r\n                                           byref(raw_data), len(raw_data)):\r\n            if do_process_raw_report:\r\n                self.set_raw_data(raw_data)\r\n                self.__hid_object._process_raw_report(raw_data)\r\n            return helpers.ReadOnlyList(raw_data)\r\n        return helpers.ReadOnlyList([])",
    "docstring": "Read report from device"
  },
  {
    "code": "def add_data_file(data_files, target, source):\n    for t, f in data_files:\n        if t == target:\n            break\n    else:\n        data_files.append((target, []))\n        f = data_files[-1][1]\n    if source not in f:\n        f.append(source)",
    "docstring": "Add an entry to data_files"
  },
  {
    "code": "def output_lines(output, encoding='utf-8', error_exc=None):\n    if isinstance(output, ExecResult):\n        exit_code, output = output\n        if exit_code != 0 and error_exc is not None:\n            raise error_exc(output.decode(encoding))\n    return output.decode(encoding).splitlines()",
    "docstring": "Convert bytestring container output or the result of a container exec\n    command into a sequence of unicode lines.\n\n    :param output:\n        Container output bytes or an\n        :class:`docker.models.containers.ExecResult` instance.\n    :param encoding:\n        The encoding to use when converting bytes to unicode\n        (default ``utf-8``).\n    :param error_exc:\n        Optional exception to raise if ``output`` is an ``ExecResult`` with a\n        nonzero exit code.\n\n    :returns: list[str]"
  },
  {
    "code": "def infect(cls, graph, key, default_scope=None):\n        func = graph.factory_for(key)\n        if isinstance(func, cls):\n            func = func.func\n        factory = cls(key, func, default_scope)\n        graph._registry.factories[key] = factory\n        return factory",
    "docstring": "Forcibly convert an entry-point based factory to a ScopedFactory.\n\n        Must be invoked before resolving the entry point.\n\n        :raises AlreadyBoundError: for non entry-points; these should be declared with @scoped_binding"
  },
  {
    "code": "def create_issue(self, title, body, labels=None):\n        kwargs = self.github_request.create(\n            title=title, body=body, labels=labels)\n        return GithubIssue(github_request=self.github_request, **kwargs)",
    "docstring": "Creates a new issue in Github.\n\n        :params title: title of the issue to be created\n        :params body: body of the issue to be created\n        :params labels: (optional) list of labels for the issue\n        :returns: newly created issue\n        :rtype: :class:`exreporter.stores.github.GithubIssue`"
  },
  {
    "code": "def run_matrix_in_parallel(self, process_data):\n        worker_data = [{'matrix': entry, 'pipeline': process_data.pipeline,\n                        'model': process_data.model, 'options': process_data.options,\n                        'hooks': process_data.hooks} for entry in self.matrix\n                       if Matrix.can_process_matrix(entry, process_data.options.matrix_tags)]\n        output = []\n        success = True\n        with closing(multiprocessing.Pool(multiprocessing.cpu_count())) as pool:\n            for result in pool.map(matrix_worker, worker_data):\n                output += result['output']\n                if not result['success']:\n                    success = False\n        return {'success': success, 'output': output}",
    "docstring": "Running pipelines in parallel."
  },
  {
    "code": "def get_namespace_entry(self, url: str, name: str) -> Optional[NamespaceEntry]:\n        entry_filter = and_(Namespace.url == url, NamespaceEntry.name == name)\n        result = self.session.query(NamespaceEntry).join(Namespace).filter(entry_filter).all()\n        if 0 == len(result):\n            return\n        if 1 < len(result):\n            log.warning('result for get_namespace_entry is too long. Returning first of %s', [str(r) for r in result])\n        return result[0]",
    "docstring": "Get a given NamespaceEntry object.\n\n        :param url: The url of the namespace source\n        :param name: The value of the namespace from the given url's document"
  },
  {
    "code": "def load_mmd():\n    global _MMD_LIB\n    global _LIB_LOCATION\n    try:\n        lib_file = 'libMultiMarkdown' + SHLIB_EXT[platform.system()]\n        _LIB_LOCATION = os.path.abspath(os.path.join(DEFAULT_LIBRARY_DIR, lib_file))\n        if not os.path.isfile(_LIB_LOCATION):\n            _LIB_LOCATION = ctypes.util.find_library('MultiMarkdown')\n        _MMD_LIB = ctypes.cdll.LoadLibrary(_LIB_LOCATION)\n    except:\n        _MMD_LIB = None",
    "docstring": "Loads libMultiMarkdown for usage"
  },
  {
    "code": "def inference(images, num_classes, for_training=False, restore_logits=True,\n              scope=None):\n  batch_norm_params = {\n      'decay': BATCHNORM_MOVING_AVERAGE_DECAY,\n      'epsilon': 0.001,\n  }\n  with slim.arg_scope([slim.ops.conv2d, slim.ops.fc], weight_decay=0.00004):\n    with slim.arg_scope([slim.ops.conv2d],\n                        stddev=0.1,\n                        activation=tf.nn.relu,\n                        batch_norm_params=batch_norm_params):\n      logits, endpoints = slim.inception.inception_v3(\n          images,\n          dropout_keep_prob=0.8,\n          num_classes=num_classes,\n          is_training=for_training,\n          restore_logits=restore_logits,\n          scope=scope)\n  _activation_summaries(endpoints)\n  auxiliary_logits = endpoints['aux_logits']\n  return logits, auxiliary_logits",
    "docstring": "Build Inception v3 model architecture.\n\n  See here for reference: http://arxiv.org/abs/1512.00567\n\n  Args:\n    images: Images returned from inputs() or distorted_inputs().\n    num_classes: number of classes\n    for_training: If set to `True`, build the inference model for training.\n      Kernels that operate differently for inference during training\n      e.g. dropout, are appropriately configured.\n    restore_logits: whether or not the logits layers should be restored.\n      Useful for fine-tuning a model with different num_classes.\n    scope: optional prefix string identifying the ImageNet tower.\n\n  Returns:\n    Logits. 2-D float Tensor.\n    Auxiliary Logits. 2-D float Tensor of side-head. Used for training only."
  },
  {
    "code": "def _prepPointsForSegments(points):\n    while 1:\n        point = points[-1]\n        if point.segmentType:\n            break\n        else:\n            point = points.pop()\n            points.insert(0, point)\n            continue\n        break",
    "docstring": "Move any off curves at the end of the contour\n    to the beginning of the contour. This makes\n    segmentation easier."
  },
  {
    "code": "async def publish_changes(self, zone, changes):\n        zone_id = self.get_managed_zone(zone)\n        url = f'{self._base_url}/managedZones/{zone_id}/changes'\n        resp = await self.request('post', url, json=changes)\n        return json.loads(resp)['id']",
    "docstring": "Post changes to a zone.\n\n        Args:\n            zone (str): DNS zone of the change.\n            changes (dict): JSON compatible dict of a `Change\n                <https://cloud.google.com/dns/api/v1/changes>`_.\n        Returns:\n            string identifier of the change."
  },
  {
    "code": "def _get_main_and_json(directory):\n    directory = os.path.normpath(os.path.abspath(directory))\n    checker_main = os.path.normpath(os.path.join(directory, os.path.pardir, \"checker-workflow-wrapping-tool.cwl\"))\n    if checker_main and os.path.exists(checker_main):\n        main_cwl = [checker_main]\n    else:\n        main_cwl = glob.glob(os.path.join(directory, \"main-*.cwl\"))\n        main_cwl = [x for x in main_cwl if not x.find(\"-pack\") >= 0]\n        assert len(main_cwl) == 1, \"Did not find main CWL in %s\" % directory\n    main_json = glob.glob(os.path.join(directory, \"main-*-samples.json\"))\n    assert len(main_json) == 1, \"Did not find main json in %s\" % directory\n    project_name = os.path.basename(directory).split(\"-workflow\")[0]\n    return main_cwl[0], main_json[0], project_name",
    "docstring": "Retrieve the main CWL and sample JSON files from a bcbio generated directory."
  },
  {
    "code": "def save(name, data, rc_file='~/.odoorpcrc'):\n    conf = ConfigParser()\n    conf.read([os.path.expanduser(rc_file)])\n    if not conf.has_section(name):\n        conf.add_section(name)\n    for key in data:\n        value = data[key]\n        conf.set(name, key, str(value))\n    with open(os.path.expanduser(rc_file), 'w') as file_:\n        os.chmod(os.path.expanduser(rc_file), stat.S_IREAD | stat.S_IWRITE)\n        conf.write(file_)",
    "docstring": "Save the `data` session configuration under the name `name`\n    in the `rc_file` file.\n\n    >>> import odoorpc\n    >>> odoorpc.session.save(\n    ...     'foo',\n    ...     {'type': 'ODOO', 'host': 'localhost', 'protocol': 'jsonrpc',\n    ...      'port': 8069, 'timeout': 120, 'database': 'db_name'\n    ...      'user': 'admin', 'passwd': 'password'})    # doctest: +SKIP\n\n    .. doctest::\n        :hide:\n\n        >>> import odoorpc\n        >>> session = '%s_session' % DB\n        >>> odoorpc.session.save(\n        ...     session,\n        ...     {'type': 'ODOO', 'host': HOST, 'protocol': PROTOCOL,\n        ...      'port': PORT, 'timeout': 120, 'database': DB,\n        ...      'user': USER, 'passwd': PWD})"
  },
  {
    "code": "def servers(self, server='api.telldus.com', port=http.HTTPS_PORT):\n        logging.debug(\"Fetching server list from %s:%d\", server, port)\n        conn = http.HTTPSConnection(server, port, context=self.ssl_context())\n        conn.request('GET', \"/server/assign?protocolVersion=2\")\n        response = conn.getresponse()\n        if response.status != http.OK:\n            raise RuntimeError(\"Could not connect to {}:{}: {} {}\".format(\n                server, port, response.status, response.reason))\n        servers = []\n        def extract_servers(name, attributes):\n            if name == \"server\":\n                servers.append((attributes['address'],\n                                int(attributes['port'])))\n        parser = expat.ParserCreate()\n        parser.StartElementHandler = extract_servers\n        parser.ParseFile(response)\n        logging.debug(\"Found %d available servers\", len(servers))\n        return servers",
    "docstring": "Fetch list of servers that can be connected to.\n\n        :return: list of (address, port) tuples"
  },
  {
    "code": "def transform_bbox(bbox, target_crs):\n    warnings.warn(\"This function is deprecated, use BBox.transform method instead\", DeprecationWarning, stacklevel=2)\n    return bbox.transform(target_crs)",
    "docstring": "Maps bbox from current crs to target_crs\n\n    :param bbox: bounding box\n    :type bbox: geometry.BBox\n    :param target_crs: target CRS\n    :type target_crs: constants.CRS\n    :return: bounding box in target CRS\n    :rtype: geometry.BBox"
  },
  {
    "code": "def validate(self):\n        try:\n            resp = self.request().get(self.validate_url, verify=self.verifySSL).json()\n        except TokenExpiredError:\n            return False\n        except AttributeError:\n            return False\n        if 'error' in resp:\n            return False\n        return True",
    "docstring": "Confirms the current token is still valid.\n        Returns True if it is valid, False otherwise."
  },
  {
    "code": "def reconstruct_files(input_dir):\n    input_dir = input_dir.rstrip('/')\n    with nl.notify('Attempting to organize/reconstruct directory'):\n        for r,ds,fs in os.walk(input_dir):\n            for f in fs:\n                if f[0]=='.':\n                    shutil.move(os.path.join(r,f),os.path.join(r,'i'+f))\n        nl.dicom.organize_dir(input_dir)\n        output_dir = '%s-sorted' % input_dir\n        if os.path.exists(output_dir):\n            with nl.run_in(output_dir):\n                for dset_dir in os.listdir('.'):\n                    with nl.notify('creating dataset from %s' % dset_dir):\n                        nl.dicom.create_dset(dset_dir)\n        else:\n            nl.notify('Warning: failed to auto-organize directory %s' % input_dir,level=nl.level.warning)",
    "docstring": "sorts ``input_dir`` and tries to reconstruct the subdirectories found"
  },
  {
    "code": "def _pwl1_to_poly(self, generators):\n        for g in generators:\n            if (g.pcost_model == PW_LINEAR) and (len(g.p_cost) == 2):\n                g.pwl_to_poly()\n        return generators",
    "docstring": "Converts single-block piecewise-linear costs into linear\n        polynomial."
  },
  {
    "code": "def unpack_classical_reg(c):\n    if isinstance(c, list) or isinstance(c, tuple):\n        if len(c) > 2 or len(c) == 0:\n            raise ValueError(\"if c is a list/tuple, it should be of length <= 2\")\n        if len(c) == 1:\n            c = (c[0], 0)\n        if not isinstance(c[0], str):\n            raise ValueError(\"if c is a list/tuple, its first member should be a string\")\n        if not isinstance(c[1], int):\n            raise ValueError(\"if c is a list/tuple, its second member should be an int\")\n        return MemoryReference(c[0], c[1])\n    if isinstance(c, MemoryReference):\n        return c\n    elif isinstance(c, str):\n        return MemoryReference(c, 0)\n    else:\n        raise TypeError(\"c should be a list of length 2, a pair, a string, or a MemoryReference\")",
    "docstring": "Get the address for a classical register.\n\n    :param c: A list of length 2, a pair, a string (to be interpreted as name[0]), or a MemoryReference.\n    :return: The address as a MemoryReference."
  },
  {
    "code": "def configfile_from_path(path, strict=True):\n    extension = path.split('.')[-1]\n    conf_type = FILE_TYPES.get(extension)\n    if not conf_type:\n        raise exc.UnrecognizedFileExtension(\n            \"Cannot parse file of type {0}. Choices are {1}.\".format(\n                extension,\n                FILE_TYPES.keys(),\n            )\n        )\n    return conf_type(path=path, strict=strict)",
    "docstring": "Get a ConfigFile object based on a file path.\n\n    This method will inspect the file extension and return the appropriate\n    ConfigFile subclass initialized with the given path.\n\n    Args:\n        path (str): The file path which represents the configuration file.\n        strict (bool): Whether or not to parse the file in strict mode.\n\n    Returns:\n        confpy.loaders.base.ConfigurationFile: The subclass which is\n            specialized for the given file path.\n\n    Raises:\n        UnrecognizedFileExtension: If there is no loader for the path."
  },
  {
    "code": "def getComponentName(self, pchRenderModelName, unComponentIndex, pchComponentName, unComponentNameLen):\n        fn = self.function_table.getComponentName\n        result = fn(pchRenderModelName, unComponentIndex, pchComponentName, unComponentNameLen)\n        return result",
    "docstring": "Use this to get the names of available components.  Index does not correlate to a tracked device index, but\n        is only used for iterating over all available components.  If the index is out of range, this function will return 0.\n        Otherwise, it will return the size of the buffer required for the name."
  },
  {
    "code": "def parse_args(self, args=None, namespace=None):\n        assert self.initialized, '`init` must be called before `parse_args`.'\n        namespace = self.parser.parse_args(args, namespace)\n        handler = self._get_handler(namespace, remove_handler=True)\n        if handler:\n            return handler(**vars(namespace))",
    "docstring": "Parse the command-line arguments and call the associated handler.\n\n        The signature is the same as `argparse.ArgumentParser.parse_args\n        <https://docs.python.org/2/library/argparse.html#argparse.ArgumentParser.parse_args>`_.\n\n        Args\n        ----\n        args : list\n            A list of argument strings.  If ``None`` the list is taken from\n            ``sys.argv``.\n        namespace : argparse.Namespace\n            A Namespace instance.  Defaults to a new empty Namespace.\n\n        Returns\n        -------\n        The return value of the handler called with the populated Namespace as\n        kwargs."
  },
  {
    "code": "def ground_height(self):\n        lat = self.pkt['I105']['Lat']['val']\n        lon = self.pkt['I105']['Lon']['val']\n        global ElevationMap\n        ret = ElevationMap.GetElevation(lat, lon)\n        ret -= gen_settings.wgs84_to_AMSL\n        return ret * 3.2807",
    "docstring": "return height above ground in feet"
  },
  {
    "code": "def filter_line(line: str, context: RunContext) -> typing.Optional[str]:\n    if context.filters is not None:\n        for filter_ in context.filters:\n            if re.match(filter_, line):\n                return None\n    return line",
    "docstring": "Filters out lines that match a given regex\n\n    :param line: line to filter\n    :type line: str\n    :param context: run context\n    :type context: _RunContext\n    :return: line if it doesn't match the filter\n    :rtype: optional str"
  },
  {
    "code": "def _update_pi_vars(self):\n        with scipy.errstate(divide='raise', under='raise', over='raise',\n                invalid='raise'):\n            for r in range(self.nsites):\n                self.pi_codon[r] = self.pi[r][CODON_TO_AA]\n                pim = scipy.tile(self.pi_codon[r], (N_CODON, 1))\n                self.piAx_piAy[r] = pim.transpose() / pim\n            self.ln_pi_codon = scipy.log(self.pi_codon)\n            self.piAx_piAy_beta = self.piAx_piAy**self.beta\n            self.ln_piAx_piAy_beta = scipy.log(self.piAx_piAy_beta)",
    "docstring": "Update variables that depend on `pi`.\n\n        These are `pi_codon`, `ln_pi_codon`, `piAx_piAy`, `piAx_piAy_beta`,\n        `ln_piAx_piAy_beta`.\n\n        Update using current `pi` and `beta`."
  },
  {
    "code": "def gopro_get_request_send(self, target_system, target_component, cmd_id, force_mavlink1=False):\n                return self.send(self.gopro_get_request_encode(target_system, target_component, cmd_id), force_mavlink1=force_mavlink1)",
    "docstring": "Request a GOPRO_COMMAND response from the GoPro\n\n                target_system             : System ID (uint8_t)\n                target_component          : Component ID (uint8_t)\n                cmd_id                    : Command ID (uint8_t)"
  },
  {
    "code": "def count_nonzero(data, mapper=None, blen=None, storage=None,\n                  create='array', **kwargs):\n    return reduce_axis(data, reducer=np.count_nonzero,\n                       block_reducer=np.add, mapper=mapper,\n                       blen=blen, storage=storage, create=create, **kwargs)",
    "docstring": "Count the number of non-zero elements."
  },
  {
    "code": "async def _load_all_nodes(self):\n        get_all_nodes_information = GetAllNodesInformation(pyvlx=self.pyvlx)\n        await get_all_nodes_information.do_api_call()\n        if not get_all_nodes_information.success:\n            raise PyVLXException(\"Unable to retrieve node information\")\n        self.clear()\n        for notification_frame in get_all_nodes_information.notification_frames:\n            node = convert_frame_to_node(self.pyvlx, notification_frame)\n            if node is not None:\n                self.add(node)",
    "docstring": "Load all nodes via API."
  },
  {
    "code": "def cylindrical(cls, mag, theta, z=0):\n        return cls(\n            mag * math.cos(theta),\n            mag * math.sin(theta),\n            z\n        )",
    "docstring": "Returns a Vector instance from cylindircal coordinates"
  },
  {
    "code": "async def delete_pairwise(self, their_did: str) -> None:\n        LOGGER.debug('Wallet.delete_pairwise >>> their_did: %s', their_did)\n        if not ok_did(their_did):\n            LOGGER.debug('Wallet.delete_pairwise <!< Bad DID %s', their_did)\n            raise BadIdentifier('Bad DID {}'.format(their_did))\n        await self.delete_non_secret(TYPE_PAIRWISE, their_did)\n        LOGGER.debug('Wallet.delete_pairwise <<<')",
    "docstring": "Remove a pairwise DID record by its remote DID. Silently return if no such record is present.\n        Raise WalletState for closed wallet, or BadIdentifier for invalid pairwise DID.\n\n        :param their_did: remote DID marking pairwise DID to remove"
  },
  {
    "code": "def send_message(self,message):\n        if self._state == STATE_DISCONNECTED:\n            raise Exception(\"WAMP is currently disconnected!\")\n        message = message.as_str()\n        logger.debug(\"SND>: {}\".format(message))\n        if not self.ws:\n            raise Exception(\"WAMP is currently disconnected!\")\n        self.ws.send(message)",
    "docstring": "Send awamp message to the server. We don't wait\n            for a response here. Just fire out a message"
  },
  {
    "code": "def freeze(self):\n        if self.value is None:\n            self.value = \"\"\n        if self.dialect in [DIALECT_ALTREE]:\n            name_tuple = parse_name_altree(self)\n        elif self.dialect in [DIALECT_MYHERITAGE]:\n            name_tuple = parse_name_myher(self)\n        elif self.dialect in [DIALECT_ANCESTRIS]:\n            name_tuple = parse_name_ancestris(self)\n        else:\n            name_tuple = split_name(self.value)\n        self.value = name_tuple\n        return self",
    "docstring": "Method called by parser when updates to this record finish.\n\n        :return: self"
  },
  {
    "code": "def resize(self):\n        resized_size = self.get_resized_size()\n        if not resized_size:\n            return\n        self.image = self.image.resize(resized_size, Image.ANTIALIAS)",
    "docstring": "Get target size for a cropped image and do the resizing if we got\n        anything usable."
  },
  {
    "code": "def from_json(self, json_string):\n        obj = json.loads(json_string)\n        self.from_dict(obj['groups'], obj['data'])\n        return self",
    "docstring": "Override current FlatTable using data from json.\n\n        :param json_string: JSON String\n        :type json_string: str"
  },
  {
    "code": "def previous_obj(self):\n        previous_obj = None\n        if self.previous_visit:\n            try:\n                previous_obj = self.model.objects.get(\n                    **{f\"{self.model.visit_model_attr()}\": self.previous_visit}\n                )\n            except ObjectDoesNotExist:\n                pass\n        return previous_obj",
    "docstring": "Returns a model obj that is the first occurrence of a previous\n        obj relative to this object's appointment.\n\n        Override this method if not am EDC subject model / CRF."
  },
  {
    "code": "def _read_openephys(openephys_file):\n    root = ElementTree.parse(openephys_file).getroot()\n    channels = []\n    for recording in root:\n        s_freq = float(recording.attrib['samplerate'])\n        for processor in recording:\n            for channel in processor:\n                channels.append(channel.attrib)\n    return s_freq, channels",
    "docstring": "Read the channel labels and their respective files from the\n    'Continuous_Data.openephys' file\n\n    Parameters\n    ----------\n    openephys_file : Path\n        path to Continuous_Data.openephys inside the open-ephys folder\n\n    Returns\n    -------\n    int\n        sampling frequency\n    list of dict\n        list of channels containing the label, the filename and the gain"
  },
  {
    "code": "def remove(item):\n    if os.path.isdir(item):\n        shutil.rmtree(item)\n    else:\n        os.remove(item)",
    "docstring": "Delete item, whether it's a file, a folder, or a folder\n    full of other files and folders."
  },
  {
    "code": "def create_roots(self, yam):\n        self.local_grammar = SchemaNode(\"grammar\")\n        self.local_grammar.attr = {\n            \"ns\": yam.search_one(\"namespace\").arg,\n            \"nma:module\": self.module.arg}\n        src_text = \"YANG module '%s'\" % yam.arg\n        revs = yam.search(\"revision\")\n        if len(revs) > 0:\n            src_text += \" revision %s\" % self.current_revision(revs)\n        self.dc_element(self.local_grammar, \"source\", src_text)\n        start = SchemaNode(\"start\", self.local_grammar)\n        self.data = SchemaNode(\"nma:data\", start, interleave=True)\n        self.data.occur = 2\n        self.rpcs = SchemaNode(\"nma:rpcs\", start, interleave=False)\n        self.notifications = SchemaNode(\"nma:notifications\", start,\n                                        interleave=False)",
    "docstring": "Create the top-level structure for module `yam`."
  },
  {
    "code": "def fill(image, mask=None, iterations=1):\n    global fill_table\n    if mask is None:\n        masked_image = image\n    else:\n        masked_image = image.astype(bool).copy()\n        masked_image[~mask] = True\n    result = table_lookup(masked_image, fill_table, True, iterations)\n    if not mask is None:\n        result[~mask] = image[~mask]\n    return result",
    "docstring": "Fill isolated black pixels\n    \n    1 1 1     1 1 1\n    1 0 1 ->  1 1 1\n    1 1 1     1 1 1"
  },
  {
    "code": "def authenticate(self, username, password):\n        url = URLS['token']\n        data = {\n            \"grant_type\": \"password\",\n            \"client_id\": self.client_id,\n            \"client_secret\": self.client_secret,\n            \"username\": username,\n            \"password\": password\n        }\n        r = requests.post(url, data=data)\n        r.raise_for_status()\n        j = r.json()\n        self.access_token = j['access_token']\n        self.refresh_token = j['refresh_token']\n        self._set_token_expiration_time(expires_in=j['expires_in'])\n        return r",
    "docstring": "Uses a Smappee username and password to request an access token,\n        refresh token and expiry date.\n\n        Parameters\n        ----------\n        username : str\n        password : str\n\n        Returns\n        -------\n        requests.Response\n            access token is saved in self.access_token\n            refresh token is saved in self.refresh_token\n            expiration time is set in self.token_expiration_time as\n            datetime.datetime"
  },
  {
    "code": "def drain(self):\n        if self.debug:\n            sys.stderr.write(\"%s: DRAIN INPUT (%i bytes waiting)\\n\" %(\n                    self.__class__.__name__,\n                    self.ser.inWaiting()\n                    ))\n        old_timeout = self.ser.timeout\n        self.ser.timeout = 0.1\n        data = self.ser.read(1)\n        while len(data):\n            if self.debug:\n                sys.stderr.write(\"%s: DRAINED 0x%x (%c)\\n\" %(self.__class__.__name__, ord(data[0]), data[0]))\n            data = self.ser.read(1)\n        self.ser.timeout = old_timeout\n        return True",
    "docstring": "Drain input."
  },
  {
    "code": "def encode(self, s):\n    if s.endswith(\".mp3\"):\n      out_filepath = s[:-4] + \".wav\"\n      call([\n          \"sox\", \"--guard\", s, \"-r\", \"16k\", \"-b\", \"16\", \"-c\", \"1\", out_filepath\n      ])\n      s = out_filepath\n    elif not s.endswith(\".wav\"):\n      out_filepath = s + \".wav\"\n      if not os.path.exists(out_filepath):\n        call([\"sox\", \"-r\", \"16k\", \"-b\", \"16\", \"-c\", \"1\", s, out_filepath])\n      s = out_filepath\n    rate, data = wavfile.read(s)\n    assert rate == self._sample_rate\n    assert len(data.shape) == 1\n    if data.dtype not in [np.float32, np.float64]:\n      data = data.astype(np.float32) / np.iinfo(data.dtype).max\n    return data.tolist()",
    "docstring": "Transform a string with a filename into a list of float32.\n\n    Args:\n      s: path to the file with a waveform.\n\n    Returns:\n      samples: list of int16s"
  },
  {
    "code": "def run_slurm(self, steps=None, **kwargs):\n        params = self.extra_slurm_params\n        params.update(kwargs)\n        if 'time'       not in params: params['time']       = self.default_time\n        if 'job_name'   not in params: params['job_name']   = self.job_name\n        if 'email'      not in params: params['email']      = None\n        if 'dependency' not in params: params['dependency'] = 'singleton'\n        self.slurm_job = LoggedJobSLURM(self.command(steps),\n                                        base_dir = self.parent.p.logs_dir,\n                                        modules  = self.modules,\n                                        **params)\n        return self.slurm_job.run()",
    "docstring": "Run the steps via the SLURM queue."
  },
  {
    "code": "def get_numeric_features_to_observed_range(examples):\n  observed_features = collections.defaultdict(list)\n  for example in examples:\n    for feature_name in get_numeric_feature_names(example):\n      original_feature = parse_original_feature_from_example(\n          example, feature_name)\n      observed_features[feature_name].extend(original_feature.original_value)\n  return {\n      feature_name: {\n          'observedMin': min(feature_values),\n          'observedMax': max(feature_values),\n      }\n      for feature_name, feature_values in iteritems(observed_features)\n  }",
    "docstring": "Returns numerical features and their observed ranges.\n\n  Args:\n    examples: Examples to read to get ranges.\n\n  Returns:\n    A dict mapping feature_name -> {'observedMin': 'observedMax': } dicts,\n    with a key for each numerical feature."
  },
  {
    "code": "def collides(self,position,size):\n        word_rect = pygame.Rect(position,self.word_size)\n        if word_rect.collidelistall(self.used_pos) == []:\n            return False\n        else:\n            return True",
    "docstring": "Returns True if the word collides with another plotted word."
  },
  {
    "code": "def setup_client(self, client_id=None, user_data=None, scan=True, broadcast=False):\n        if client_id is None:\n            client_id = str(uuid.uuid4())\n        if client_id in self._clients:\n            raise  ArgumentError(\"Duplicate client_id: {}\".format(client_id))\n        async def _client_callback(conn_string, _, event_name, event):\n            event_tuple = (conn_string, event_name, event)\n            await self._forward_client_event(client_id, event_tuple)\n        client_monitor = self.adapter.register_monitor([], [], _client_callback)\n        self._clients[client_id] = dict(user_data=user_data, connections={},\n                                        monitor=client_monitor)\n        self._adjust_global_events(client_id, scan, broadcast)\n        return client_id",
    "docstring": "Setup a newly connected client.\n\n        ``client_id`` must be unique among all connected clients.  If it is\n        passed as None, a random client_id will be generated as a string and\n        returned.\n\n        This method reserves internal resources for tracking what devices this\n        client has connected to and installs a monitor into the adapter on\n        behalf of the client.\n\n        It should be called whenever a new client connects to the device server\n        before any other activities by that client are allowed.  By default,\n        all clients start receiving ``device_seen`` events but if you want\n        your client to also receive broadcast events, you can pass broadcast=True.\n\n        Args:\n            client_id (str): A unique identifier for this client that will be\n                used to refer to it in all future interactions.  If this is\n                None, then a random string will be generated for the client_id.\n            user_data (object): An arbitrary object that you would like to store\n                with this client and will be passed to your event handler when\n                events are forwarded to this client.\n            scan (bool): Whether to install a monitor to listen for device_found\n                events.\n            broadcast (bool): Whether to install a monitor to list for broadcast\n                events.\n\n        Returns:\n            str: The client_id.\n\n            If a client id was passed in, it will be the same as what was passed\n            in.  If no client id was passed in then it will be a random unique\n            string."
  },
  {
    "code": "def read_perseus(f):\n    df = pd.read_csv(f, delimiter='\\t', header=[0,1,2,3], low_memory=False)\n    df.columns = pd.MultiIndex.from_tuples([(x,) for x in df.columns.get_level_values(0)])\n    return df",
    "docstring": "Load a Perseus processed data table\n\n    :param f: Source file\n    :return: Pandas dataframe of imported data"
  },
  {
    "code": "def DefaultSelector(sock):\n    \"Return the best selector for the platform\"\n    global _DEFAULT_SELECTOR\n    if _DEFAULT_SELECTOR is None:\n        if has_selector('poll'):\n            _DEFAULT_SELECTOR = PollSelector\n        elif hasattr(select, 'select'):\n            _DEFAULT_SELECTOR = SelectSelector\n        else:\n            raise RedisError('Platform does not support any selectors')\n    return _DEFAULT_SELECTOR(sock)",
    "docstring": "Return the best selector for the platform"
  },
  {
    "code": "def get_certificate():\n    if os.path.exists(CERT_PATH):\n        log('Reading ovs certificate from {}'.format(CERT_PATH))\n        with open(CERT_PATH, 'r') as cert:\n            full_cert = cert.read()\n            begin_marker = \"-----BEGIN CERTIFICATE-----\"\n            end_marker = \"-----END CERTIFICATE-----\"\n            begin_index = full_cert.find(begin_marker)\n            end_index = full_cert.rfind(end_marker)\n            if end_index == -1 or begin_index == -1:\n                raise RuntimeError(\"Certificate does not contain valid begin\"\n                                   \" and end markers.\")\n            full_cert = full_cert[begin_index:(end_index + len(end_marker))]\n            return full_cert\n    else:\n        log('Certificate not found', level=WARNING)\n        return None",
    "docstring": "Read openvswitch certificate from disk"
  },
  {
    "code": "def updateCheckedText(self):\n        if not self.isCheckable():\n            return\n        indexes = self.checkedIndexes()\n        items = self.checkedItems()\n        if len(items) < 2 or self.separator():\n            self.lineEdit().setText(self.separator().join(items))\n        else:\n            self.lineEdit().setText('{0} items selected'.format(len(items)))\n        if not self.signalsBlocked():\n            self.checkedItemsChanged.emit(items)\n            self.checkedIndexesChanged.emit(indexes)",
    "docstring": "Updates the text in the editor to reflect the latest state."
  },
  {
    "code": "def verify(password, hash):\n    _, algorithm, cost, salt, password_hash = hash.split(\"$\")\n    password = pbkdf2.pbkdf2_hex(password, salt, int(cost) * 500)\n    return _safe_str_cmp(password, password_hash)",
    "docstring": "Verify a password against a passed hash"
  },
  {
    "code": "def get_urls(self):\n        not_clone_url = [url(r'^(.+)/will_not_clone/$',\n                             admin.site.admin_view(self.will_not_clone))]\n        restore_url = [\n            url(r'^(.+)/restore/$', admin.site.admin_view(self.restore))]\n        return not_clone_url + restore_url + super(VersionedAdmin,\n                                                   self).get_urls()",
    "docstring": "Appends the custom will_not_clone url to the admin site"
  },
  {
    "code": "def finder_for_path(path):\n    result = None\n    pkgutil.get_importer(path)\n    loader = sys.path_importer_cache.get(path)\n    finder = _finder_registry.get(type(loader))\n    if finder:\n        module = _dummy_module\n        module.__file__ = os.path.join(path, '')\n        module.__loader__ = loader\n        result = finder(module)\n    return result",
    "docstring": "Return a resource finder for a path, which should represent a container.\n\n    :param path: The path.\n    :return: A :class:`ResourceFinder` instance for the path."
  },
  {
    "code": "def optional_else(self, node, last):\n        if node.orelse:\n            min_first_max_last(node, node.orelse[-1])\n            if 'else' in self.operators:\n                position = (node.orelse[0].first_line, node.orelse[0].first_col)\n                _, efirst = self.operators['else'].find_previous(position)\n                if efirst and efirst > last:\n                    elast, _ = self.operators[':'].find_previous(position)\n                    node.op_pos.append(NodeWithPosition(elast, efirst))",
    "docstring": "Create op_pos for optional else"
  },
  {
    "code": "def onNicknameChange(\n        self,\n        mid=None,\n        author_id=None,\n        changed_for=None,\n        new_nickname=None,\n        thread_id=None,\n        thread_type=ThreadType.USER,\n        ts=None,\n        metadata=None,\n        msg=None,\n    ):\n        log.info(\n            \"Nickname change from {} in {} ({}) for {}: {}\".format(\n                author_id, thread_id, thread_type.name, changed_for, new_nickname\n            )\n        )",
    "docstring": "Called when the client is listening, and somebody changes the nickname of a person\n\n        :param mid: The action ID\n        :param author_id: The ID of the person who changed the nickname\n        :param changed_for: The ID of the person whom got their nickname changed\n        :param new_nickname: The new nickname\n        :param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`\n        :param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`\n        :param ts: A timestamp of the action\n        :param metadata: Extra metadata about the action\n        :param msg: A full set of the data recieved\n        :type thread_type: models.ThreadType"
  },
  {
    "code": "def on_iteration(self):\n        self._cancel_consumers_if_requested()\n        if len(self._consumers) == 0:\n            _log.debug('requesting stop after iteration')\n            self.should_stop = True",
    "docstring": "Kombu callback for each `drain_events` loop iteration."
  },
  {
    "code": "def _len_frame(obj):\n    c = getattr(obj, 'f_code', None)\n    if c:\n       n = _len_code(c)\n    else:\n       n = 0\n    return n",
    "docstring": "Length of a frame object."
  },
  {
    "code": "def load_manifest(data):\n    if isinstance(data, dict):\n        return data\n    doc = yaml.safe_load(data)\n    if not isinstance(doc, dict):\n        raise Exception(\"Manifest didn't result in dict.\")\n    return doc",
    "docstring": "Helper for loading a manifest yaml doc."
  },
  {
    "code": "def get_auth_info(self):\n        try:\n            response = self.session.get(self.auth_root, headers={\n                'Accept': 'application/protobuf'\n            })\n            message = web_pb2.AuthInfo()\n            message.ParseFromString(response.content)\n            return AuthInfo(message)\n        except requests.exceptions.ConnectionError:\n            raise ConnectionFailure('Connection to {} refused'.format(self.address))",
    "docstring": "Returns general authentication information. This operation\n        does not require authenticating and is useful to test\n        if a server requires authentication or not.\n\n        :rtype: .AuthInfo"
  },
  {
    "code": "def _year_expand(s):\n        regex = r\"^((?:19|20)\\d{2})?(\\s*-\\s*)?((?:19|20)\\d{2})?$\"\n        try:\n            start, dash, end = match(regex, ustr(s)).groups()\n            start = start or 1900\n            end = end or 2099\n        except AttributeError:\n            return 1900, 2099\n        return (int(start), int(end)) if dash else (int(start), int(start))",
    "docstring": "Parses a year or dash-delimeted year range"
  },
  {
    "code": "def reverse(self):\n        enabled = self.lib.iperf_get_test_reverse(self._test)\n        if enabled:\n            self._reverse = True\n        else:\n            self._reverse = False\n        return self._reverse",
    "docstring": "Toggles direction of test\n\n        :rtype: bool"
  },
  {
    "code": "def process_array_items(self, array, json):\n        for item in json['items']:\n            key = None\n            processed = self.from_json(item)\n            if isinstance(processed, Asset):\n                key = 'Asset'\n            elif isinstance(processed, Entry):\n                key = 'Entry'\n            if key is not None:\n                array.items_mapped[key][processed.sys['id']] = processed\n            array.items.append(processed)",
    "docstring": "Iterate through all `items` and create a resource for each.\n\n        In addition map the resources under the `items_mapped` by the resource id and type.\n\n        :param array: Array resource.\n        :param json: Raw JSON dictionary."
  },
  {
    "code": "def value(self):\n        value = self._properties.get(\"value\")\n        if value is not None:\n            value = base64.b64decode(value)\n        return value",
    "docstring": "Value of the variable, as bytes.\n\n        See\n        https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables\n\n        :rtype: bytes or ``NoneType``\n        :returns: The value of the variable or ``None`` if the property\n                  is not set locally."
  },
  {
    "code": "def send_message(\n            self,\n            title=None,\n            body=None,\n            icon=None,\n            data=None,\n            sound=None,\n            badge=None,\n            api_key=None,\n            **kwargs):\n        from .fcm import fcm_send_message\n        result = fcm_send_message(\n            registration_id=str(self.registration_id),\n            title=title,\n            body=body,\n            icon=icon,\n            data=data,\n            sound=sound,\n            badge=badge,\n            api_key=api_key,\n            **kwargs\n        )\n        self._deactivate_device_on_error_result(result)\n        return result",
    "docstring": "Send single notification message."
  },
  {
    "code": "def _split_keys_v2(joined):\n    left, _, right = joined.rpartition('::')\n    return _decode_v2(left), _decode_v2(right)",
    "docstring": "Split two keys out a string created by _join_keys_v2."
  },
  {
    "code": "def mount(dmg):\n    temp_dir = __salt__['temp.dir'](prefix='dmg-')\n    cmd = 'hdiutil attach -readonly -nobrowse -mountpoint {0} \"{1}\"'.format(temp_dir, dmg)\n    return __salt__['cmd.run'](cmd), temp_dir",
    "docstring": "Attempt to mount a dmg file to a temporary location and return the\n    location of the pkg file inside\n\n    Args:\n        dmg (str): The location of the dmg file to mount\n\n    Returns:\n        tuple: Tuple containing the results of the command along with the mount\n               point\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' macpackage.mount /tmp/software.dmg"
  },
  {
    "code": "def terminate_ex(self, nodes, threads=False, attempts=3):\n        while nodes and attempts > 0:\n            if threads:\n                nodes = self.terminate_with_threads(nodes)\n            else:\n                nodes = self.terminate(nodes)\n            if nodes:\n                logger.info(\"Attempt to terminate the remaining instances once more.\")\n                attempts -= 1\n        return nodes",
    "docstring": "Wrapper method for terminate.\n\n        :param   nodes: Nodes to be destroyed.\n        :type    nodes: ``list``\n\n        :param   attempts: The amount of attempts for retrying to terminate failed instances.\n        :type    attempts: ``int``\n\n        :param   threads: Whether to use the threaded approach or not.\n        :type    threads: ``bool``"
  },
  {
    "code": "def _getFirstPathExpression(name):\n    tokens = grammar.parseString(name)\n    pathExpression = None\n    while pathExpression is None:\n        if tokens.pathExpression:\n            pathExpression = tokens.pathExpression\n        elif tokens.expression:\n            tokens = tokens.expression\n        elif tokens.call:\n            tokens = tokens.call.args[0]\n        else:\n            break\n    return pathExpression",
    "docstring": "Returns the first metric path in an expression."
  },
  {
    "code": "def dataset_view(self, dataset):\n        if '/' in dataset:\n            self.validate_dataset_string(dataset)\n            dataset_urls = dataset.split('/')\n            owner_slug = dataset_urls[0]\n            dataset_slug = dataset_urls[1]\n        else:\n            owner_slug = self.get_config_value(self.CONFIG_NAME_USER)\n            dataset_slug = dataset\n        result = self.process_response(\n            self.datasets_view_with_http_info(owner_slug, dataset_slug))\n        return Dataset(result)",
    "docstring": "view metadata for a dataset.\n\n            Parameters\n            ==========\n            dataset: the string identified of the dataset\n                     should be in format [owner]/[dataset-name]"
  },
  {
    "code": "def set_memory(self, total=None, static=None):\n        if total:\n            self.params[\"rem\"][\"mem_total\"] = total\n        if static:\n            self.params[\"rem\"][\"mem_static\"] = static",
    "docstring": "Set the maxium allowed memory.\n\n        Args:\n            total: The total memory. Integer. Unit: MBytes. If set to None,\n                this parameter will be neglected.\n            static: The static memory. Integer. Unit MBytes. If set to None,\n                this parameterwill be neglected."
  },
  {
    "code": "def raise_for_redefined_namespace(self, line: str, position: int, namespace: str) -> None:\n        if self.disallow_redefinition and self.has_namespace(namespace):\n            raise RedefinedNamespaceError(self.get_line_number(), line, position, namespace)",
    "docstring": "Raise an exception if a namespace is already defined.\n\n        :raises: RedefinedNamespaceError"
  },
  {
    "code": "def loadFromFile(self, filename):\n        file = open(filename, 'rb')\n        try:\n            wsdl = self.loadFromStream(file)\n        finally:\n            file.close()\n        return wsdl",
    "docstring": "Return a WSDL instance loaded from the given file."
  },
  {
    "code": "def CreateMenuItem(self, MenuItemId, PluginContext, CaptionText, HintText=u'', IconPath='', Enabled=True,\n                       ContactType=pluginContactTypeAll, MultipleContacts=False):\n        cmd = 'CREATE MENU_ITEM %s CONTEXT %s CAPTION %s ENABLED %s' % (tounicode(MenuItemId), PluginContext,\n            quote(tounicode(CaptionText)), cndexp(Enabled, 'true', 'false'))\n        if HintText:\n            cmd += ' HINT %s' % quote(tounicode(HintText))\n        if IconPath:\n            cmd += ' ICON %s' % quote(path2unicode(IconPath))\n        if MultipleContacts:\n            cmd += ' ENABLE_MULTIPLE_CONTACTS true'\n        if PluginContext == pluginContextContact:\n            cmd += ' CONTACT_TYPE_FILTER %s' % ContactType\n        self._Skype._DoCommand(cmd)\n        return PluginMenuItem(self._Skype, MenuItemId, CaptionText, HintText, Enabled)",
    "docstring": "Creates custom menu item in Skype client's \"Do More\" menus.\n\n        :Parameters:\n          MenuItemId : unicode\n            Unique identifier for the menu item.\n          PluginContext : `enums`.pluginContext*\n            Menu item context. Allows to choose in which client windows will the menu item appear.\n          CaptionText : unicode\n            Caption text.\n          HintText : unicode\n            Hint text (optional). Shown when mouse hoovers over the menu item.\n          IconPath : unicode\n            Path to the icon (optional).\n          Enabled : bool\n            Initial state of the menu item. True by default.\n          ContactType : `enums`.pluginContactType*\n            In case of `enums.pluginContextContact` tells which contacts the menu item should appear\n            for. Defaults to `enums.pluginContactTypeAll`.\n          MultipleContacts : bool\n            Set to True if multiple contacts should be allowed (defaults to False).\n\n        :return: Menu item object.\n        :rtype: `PluginMenuItem`"
  },
  {
    "code": "def format_exp_floats(decimals):\n    threshold = 10 ** 5\n    return (\n        lambda n: \"{:.{prec}e}\".format(n, prec=decimals) if n > threshold else \"{:4.{prec}f}\".format(n, prec=decimals)\n    )",
    "docstring": "sometimes the exp. column can be too large"
  },
  {
    "code": "def getDarkCurrentAverages(exposuretimes, imgs):\r\n    x, imgs_p = sortForSameExpTime(exposuretimes, imgs)\r\n    s0, s1 = imgs[0].shape\r\n    imgs = np.empty(shape=(len(x), s0, s1),\r\n                    dtype=imgs[0].dtype)\r\n    for i, ip in zip(imgs, imgs_p):\r\n        if len(ip) == 1:\r\n            i[:] = ip[0]\r\n        else:\r\n            i[:] = averageSameExpTimes(ip)\r\n    return x, imgs",
    "docstring": "return exposure times, image averages for each exposure time"
  },
  {
    "code": "def start(self):\n        self.zap_socket = self.context.socket(zmq.REP)\n        self.zap_socket.linger = 1\n        zapLoc = 'inproc://zeromq.zap.{}'.format(MultiZapAuthenticator.count)\n        self.zap_socket.bind(zapLoc)\n        self.log.debug('Starting ZAP at {}'.format(zapLoc))",
    "docstring": "Create and bind the ZAP socket"
  },
  {
    "code": "def is_ipv4(ip: str) -> bool:\n    try:\n        socket.inet_aton(ip)\n    except socket.error:\n        return False\n    return True",
    "docstring": "Returns True if the IPv4 address ia valid, otherwise returns False."
  },
  {
    "code": "def load(self):\n        self.layer.ResetReading()\n        for i in range(self.nfeatures):\n            if self.__features[i] is None:\n                self.__features[i] = self.layer[i]",
    "docstring": "load all feature into memory\n\n        Returns\n        -------"
  },
  {
    "code": "def cmd_stop(self, argv, help):\n        parser = argparse.ArgumentParser(\n            prog=\"%s stop\" % self.progname,\n            description=help,\n        )\n        instances = self.get_instances(command='stop')\n        parser.add_argument(\"instance\", nargs=1,\n                            metavar=\"instance\",\n                            help=\"Name of the instance from the config.\",\n                            choices=sorted(instances))\n        args = parser.parse_args(argv)\n        instance = instances[args.instance[0]]\n        instance.stop()",
    "docstring": "Stops the instance"
  },
  {
    "code": "def run_tpm(system, steps, blackbox):\n    node_tpms = []\n    for node in system.nodes:\n        node_tpm = node.tpm_on\n        for input_node in node.inputs:\n            if not blackbox.in_same_box(node.index, input_node):\n                if input_node in blackbox.output_indices:\n                    node_tpm = marginalize_out([input_node], node_tpm)\n        node_tpms.append(node_tpm)\n    noised_tpm = rebuild_system_tpm(node_tpms)\n    noised_tpm = convert.state_by_node2state_by_state(noised_tpm)\n    tpm = convert.state_by_node2state_by_state(system.tpm)\n    tpm = np.dot(tpm, np.linalg.matrix_power(noised_tpm, steps - 1))\n    return convert.state_by_state2state_by_node(tpm)",
    "docstring": "Iterate the TPM for the given number of timesteps.\n\n    Returns:\n        np.ndarray: tpm * (noise_tpm^(t-1))"
  },
  {
    "code": "def all(self, domain=None):\n        if domain is None:\n            return {k: dict(v) for k, v in list(self.messages.items())}\n        return dict(self.messages.get(domain, {}))",
    "docstring": "Gets the messages within a given domain.\n\n        If domain is None, it returns all messages.\n\n        @type id: The\n        @param id: message id\n\n        @rtype: dict\n        @return: A dict of messages"
  },
  {
    "code": "def getCheckerByName(self, checkerType):\n        for checker in sum(list(self.linter._checkers.values()), []):\n            if isinstance(checker, checkerType):\n                return checker\n        return None",
    "docstring": "Get checker by given name.\n\n        @checkerType: type of the checker"
  },
  {
    "code": "def construct(cls, faker, path_to_factories=None):\n        factory = faker.__class__()\n        if path_to_factories is not None and os.path.isdir(path_to_factories):\n            for filename in os.listdir(path_to_factories):\n                if os.path.isfile(filename):\n                    cls._resolve(path_to_factories, filename)\n        return factory",
    "docstring": "Create a new factory container.\n\n        :param faker: A faker generator instance\n        :type faker: faker.Generator\n\n        :param path_to_factories: The path to factories\n        :type path_to_factories: str\n\n        :rtype: Factory"
  },
  {
    "code": "def get_asset_spatial_assignment_session(self, proxy):\n        if not self.supports_asset_spatial_assignment():\n            raise Unimplemented()\n        try:\n            from . import sessions\n        except ImportError:\n            raise\n        proxy = self._convert_proxy(proxy)\n        try:\n            session = sessions.AssetSpatialAssignmentSession(proxy, runtime=self._runtime)\n        except AttributeError:\n            raise\n        return session",
    "docstring": "Gets the session for assigning spatial coverage to an asset.\n\n        arg     proxy (osid.proxy.Proxy): a proxy\n        return: (osid.repository.AssetSpatialAssignmentSession) - an\n                AssetSpatialAssignmentSession\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - supports_asset_spatial_assignment() is\n                false\n        compliance: optional - This method must be implemented if\n                    supports_asset_spatial_assignment() is true."
  },
  {
    "code": "def distclean(ctx=None):\n\tglobal commands\n\tlst=os.listdir('.')\n\tfor f in lst:\n\t\tif f==Options.lockfile:\n\t\t\ttry:\n\t\t\t\tproj=Environment.Environment(f)\n\t\t\texcept:\n\t\t\t\tLogs.warn('could not read %r'%f)\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\tshutil.rmtree(proj[BLDDIR])\n\t\t\texcept IOError:\n\t\t\t\tpass\n\t\t\texcept OSError,e:\n\t\t\t\tif e.errno!=errno.ENOENT:\n\t\t\t\t\tLogs.warn('project %r cannot be removed'%proj[BLDDIR])\n\t\t\ttry:\n\t\t\t\tos.remove(f)\n\t\t\texcept OSError,e:\n\t\t\t\tif e.errno!=errno.ENOENT:\n\t\t\t\t\tLogs.warn('file %r cannot be removed'%f)\n\t\tif not commands and f.startswith('.waf'):\n\t\t\tshutil.rmtree(f,ignore_errors=True)",
    "docstring": "removes the build directory"
  },
  {
    "code": "def tagrefs(self):\n        n = self._nmembers\n        ret = []\n        if n:\n            tags = _C.array_int32(n)\n            refs = _C.array_int32(n)\n            k = _C.Vgettagrefs(self._id, tags, refs, n)\n            _checkErr('tagrefs', k, \"error getting tags and refs\")\n            for m in xrange(k):\n                ret.append((tags[m], refs[m]))\n        return ret",
    "docstring": "Get the tags and reference numbers of all the vgroup\n        members.\n\n        Args::\n\n          no argument\n\n        Returns::\n\n          list of (tag,ref) tuples, one for each vgroup member\n\n        C library equivalent : Vgettagrefs"
  },
  {
    "code": "def trimSegments(self, minPermanence=None, minNumSyns=None):\n    if minPermanence is None:\n      minPermanence = self.connectedPerm\n    if minNumSyns is None:\n      minNumSyns = self.activationThreshold\n    totalSegsRemoved, totalSynsRemoved = 0, 0\n    for c,i in product(xrange(self.numberOfCols), xrange(self.cellsPerColumn)):\n      (segsRemoved, synsRemoved) = self.trimSegmentsInCell(colIdx=c, cellIdx=i,\n                segList=self.cells[c][i], minPermanence=minPermanence,\n                minNumSyns=minNumSyns)\n      totalSegsRemoved += segsRemoved\n      totalSynsRemoved += synsRemoved\n    return totalSegsRemoved, totalSynsRemoved",
    "docstring": "This method deletes all synapses whose permanence is less than\n    minPermanence and deletes any segments that have less than\n    minNumSyns synapses remaining.\n\n    Parameters:\n    --------------------------------------------------------------\n    minPermanence:      Any syn whose permamence is 0 or < minPermanence will\n                        be deleted. If None is passed in, then\n                        self.connectedPerm is used.\n    minNumSyns:         Any segment with less than minNumSyns synapses remaining\n                        in it will be deleted. If None is passed in, then\n                        self.activationThreshold is used.\n    retval:             (numSegsRemoved, numSynsRemoved)"
  },
  {
    "code": "def type_to_string(t):\n        if t == MemoryElement.TYPE_I2C:\n            return 'I2C'\n        if t == MemoryElement.TYPE_1W:\n            return '1-wire'\n        if t == MemoryElement.TYPE_DRIVER_LED:\n            return 'LED driver'\n        if t == MemoryElement.TYPE_LOCO:\n            return 'Loco Positioning'\n        if t == MemoryElement.TYPE_TRAJ:\n            return 'Trajectory'\n        if t == MemoryElement.TYPE_LOCO2:\n            return 'Loco Positioning 2'\n        return 'Unknown'",
    "docstring": "Get string representation of memory type"
  },
  {
    "code": "def get_initial_status_brok(self):\n        data = {'uuid': self.uuid}\n        self.fill_data_brok_from(data, 'full_status')\n        return Brok({'type': 'notification_raise', 'data': data})",
    "docstring": "Get a initial status brok\n\n        :return: brok with wanted data\n        :rtype: alignak.brok.Brok"
  },
  {
    "code": "def prompt_protocol():\n    stop = 3\n    ans = \"\"\n    while True and stop > 0:\n        ans = input(\"Save as (d)ictionary or (o)bject?\\n\"\n                    \"* Note:\\n\"\n                    \"Dictionaries are more basic, and are compatible with Python v2.7+.\\n\"\n                    \"Objects are more complex, and are only compatible with v3.4+ \")\n        if ans not in (\"d\", \"o\"):\n            print(\"Invalid response: Please choose 'd' or 'o'\")\n        else:\n            break\n    if ans == \"\":\n        ans = \"d\"\n    return ans",
    "docstring": "Prompt user if they would like to save pickle file as a dictionary or an object.\n\n    :return str: Answer"
  },
  {
    "code": "def ordered_tags(self):\n        tags = list(self.tags.all())\n        return sorted(\n            tags,\n            key=lambda tag: ((type(tag) != Tag) * 100000) + tag.count(),\n            reverse=True\n        )",
    "docstring": "gets the related tags\n\n        :return: `list` of `Tag` instances"
  },
  {
    "code": "def forget(identifier):\n    errors = False\n    for one in identifier:\n        cfg = RepoListConfig()\n        info = cfg.find_by_any(one, \"ilc\")\n        if not info:\n            warn(\"No repos matching %r\" % one)\n            errors = True\n            continue\n        note(\"Removing record of repo [%s] at %s\" % (\n            info.shortid(), info.localrepo.repo_path))\n        with saveconfig(RepoListConfig()) as cfg:\n            cfg.remove_repo(info.repoid)\n    if errors:\n        sys.exit(1)",
    "docstring": "Tells homely to forget about a dotfiles repository that was previously\n    added. You can then run `homely update` to have homely perform automatic\n    cleanup of anything that was installed by that dotfiles repo.\n\n    REPO\n        This should be the path to a local dotfiles repository that has already\n        been registered using `homely add`. You may specify multiple REPOs to\n        remove at once."
  },
  {
    "code": "def sorted_bfs_successors(G, source=None):\n    if source is None:\n        source = G.root\n    successors = defaultdict(list)\n    for src, target in sorted_bfs_edges(G, source):\n        successors[src].append(target)\n    return dict(successors)",
    "docstring": "Return dictionary of successors in breadth-first-search from source.\n\n    Parameters\n    ----------\n    G : DiscourseDocumentGraph graph\n\n    source : node\n       Specify starting node for breadth-first search and return edges in\n       the component reachable from source.\n\n    Returns\n    -------\n    successors: dict\n       A dictionary with nodes as keys and list of succssors nodes as values."
  },
  {
    "code": "def select_grid_model_residential(lvgd):\n    string_properties = lvgd.lv_grid.network.static_data['LV_model_grids_strings']\n    apartment_string = lvgd.lv_grid.network.static_data[\n        'LV_model_grids_strings_per_grid']\n    apartment_house_branch_ratio = cfg_ding0.get(\"assumptions\",\n                                                 \"apartment_house_branch_ratio\")\n    population_per_apartment = cfg_ding0.get(\"assumptions\",\n                                             \"population_per_apartment\")\n    apartments = round(lvgd.population / population_per_apartment)\n    if apartments > 196:\n        apartments = 196\n    strings = apartment_string.loc[apartments]\n    selected_strings = [int(s) for s in strings[strings >= 1].index.tolist()]\n    selected_strings_df = string_properties.loc[selected_strings]\n    occurence_selector = [str(i) for i in selected_strings]\n    selected_strings_df['occurence'] = strings.loc[occurence_selector].tolist()\n    return selected_strings_df",
    "docstring": "Selects typified model grid based on population\n\n    Parameters\n    ----------\n    lvgd : LVGridDistrictDing0\n        Low-voltage grid district object\n\n    Returns\n    -------\n    :pandas:`pandas.DataFrame<dataframe>`\n        Selected string of typified model grid\n    :pandas:`pandas.DataFrame<dataframe>`\n        Parameters of chosen Transformer\n\n    Notes\n    -----\n    In total 196 distinct LV grid topologies are available that are chosen\n    by population in the LV grid district. Population is translated to\n    number of house branches. Each grid model fits a number of house\n    branches. If this number exceeds 196, still the grid topology of 196\n    house branches is used. The peak load of the LV grid district is\n    uniformly distributed across house branches."
  },
  {
    "code": "def add_field(self, field):\n        field = FieldFactory(\n            field,\n        )\n        field.set_table(self)\n        field_name = field.get_name()\n        for existing_field in self.fields:\n            if existing_field.get_name() == field_name:\n                return None\n        self.before_add_field(field)\n        field.before_add()\n        if field.ignore is False:\n            self.fields.append(field)\n        return field",
    "docstring": "Adds a field to this table\n\n        :param field: This can be a string of a field name, a dict of {'alias': field}, or\n            a ``Field`` instance\n        :type field: str or dict or Field"
  },
  {
    "code": "def setup_toolbar(self):\n        self.savefig_btn = create_toolbutton(\n            self, icon=ima.icon('filesave'),\n            tip=_(\"Save Image As...\"),\n            triggered=self.emit_save_figure)\n        self.delfig_btn = create_toolbutton(\n            self, icon=ima.icon('editclear'),\n            tip=_(\"Delete image\"),\n            triggered=self.emit_remove_figure)\n        toolbar = QVBoxLayout()\n        toolbar.setContentsMargins(0, 0, 0, 0)\n        toolbar.setSpacing(1)\n        toolbar.addWidget(self.savefig_btn)\n        toolbar.addWidget(self.delfig_btn)\n        toolbar.addStretch(2)\n        return toolbar",
    "docstring": "Setup the toolbar."
  },
  {
    "code": "def log(cls, q):\n        v_norm = np.linalg.norm(q.vector)\n        q_norm = q.norm\n        tolerance = 1e-17\n        if q_norm < tolerance:\n            return Quaternion(scalar=-float('inf'), vector=float('nan')*q.vector)\n        if v_norm < tolerance:\n            return Quaternion(scalar=log(q_norm), vector=[0,0,0])\n        vec = q.vector / v_norm\n        return Quaternion(scalar=log(q_norm), vector=acos(q.scalar/q_norm)*vec)",
    "docstring": "Quaternion Logarithm.\n\n        Find the logarithm of a quaternion amount.\n\n        Params:\n             q: the input quaternion/argument as a Quaternion object.\n\n        Returns:\n             A quaternion amount representing log(q) := (log(|q|), v/|v|acos(w/|q|)).\n\n        Note:\n            The method computes the logarithm of general quaternions. See [Source](https://math.stackexchange.com/questions/2552/the-logarithm-of-quaternion/2554#2554) for more details."
  },
  {
    "code": "def _rescanSizes(self, force=True):\n        status = self.QUOTA_CTL(cmd=BTRFS_QUOTA_CTL_ENABLE).status\n        logger.debug(\"CTL Status: %s\", hex(status))\n        status = self.QUOTA_RESCAN_STATUS()\n        logger.debug(\"RESCAN Status: %s\", status)\n        if not status.flags:\n            if not force:\n                return\n            self.QUOTA_RESCAN()\n        logger.warn(\"Waiting for btrfs quota usage scan...\")\n        self.QUOTA_RESCAN_WAIT()",
    "docstring": "Zero and recalculate quota sizes to subvolume sizes will be correct."
  },
  {
    "code": "def conjugate_quat(quat):\n    return Quat(-quat.x, -quat.y, -quat.z, quat.w)",
    "docstring": "Negate the vector part of the quaternion."
  },
  {
    "code": "def line(self, x0, y0, x1, y1, c='*'):\n        r\n        steep = abs(y1 - y0) > abs(x1 - x0)\n        if steep:\n            (x0, y0) = (y0, x0)\n            (x1, y1) = (y1, x1)\n        if x0 > x1:\n            (x0, x1) = (x1, x0)\n            (y0, y1) = (y1, y0)\n        deltax = x1 - x0\n        deltay = abs(y1 - y0)\n        error = deltax / 2\n        y = y0\n        if y0 < y1:\n            ystep = 1\n        else:\n            ystep = -1\n        for x in range(x0, x1 - 1):\n            if steep:\n                self[y, x] = c\n            else:\n                self[x, y] = c\n            error = error - deltay\n            if error < 0:\n                y = y + ystep\n                error = error + deltax",
    "docstring": "r\"\"\"Draws a line\n\n        Who would have thought this would be so complicated?  Thanks\n        again Wikipedia_ <3\n\n        .. _Wikipedia: http://en.wikipedia.org/wiki/Bresenham's_line_algorithm"
  },
  {
    "code": "def T(self):\n        return ScoreMatrix(self.tests, self.models, scores=self.values,\n                           weights=self.weights, transpose=True)",
    "docstring": "Get transpose of this ScoreMatrix."
  },
  {
    "code": "def inverse_transform(self, X, copy=None):\n        check_is_fitted(self, 'scale_')\n        copy = copy if copy is not None else self.copy\n        if sparse.issparse(X):\n            if self.with_mean:\n                raise ValueError(\n                    \"Cannot uncenter sparse matrices: pass `with_mean=False` \"\n                    \"instead See docstring for motivation and alternatives.\")\n            if not sparse.isspmatrix_csr(X):\n                X = X.tocsr()\n                copy = False\n            if copy:\n                X = X.copy()\n            if self.scale_ is not None:\n                inplace_column_scale(X, self.scale_)\n        else:\n            X = numpy.asarray(X)\n            if copy:\n                X = X.copy()\n            if self.with_std:\n                X *= self.scale_\n            if self.with_mean:\n                X += self.mean_\n        return X",
    "docstring": "Scale back the data to the original representation.\n\n        :param X: Scaled data matrix.\n        :type X: numpy.ndarray, shape [n_samples, n_features]\n        :param bool copy: Copy the X data matrix.\n        :return: X data matrix with the scaling operation reverted.\n        :rtype: numpy.ndarray, shape [n_samples, n_features]"
  },
  {
    "code": "def paint(self, tbl):\n        if not isinstance(tbl, Table):\n            logging.error(\"unable to paint table: invalid object\")\n            return False\n        self.term.stream.write(self.term.clear)\n        self.term.stream.write(str(tbl))\n        return True",
    "docstring": "Paint the table on terminal\n        Currently only print out basic string format"
  },
  {
    "code": "def copy(self):\n        copy_factor = CanonicalDistribution(self.variables, self.K.copy(),\n                                            self.h.copy(), self.g)\n        return copy_factor",
    "docstring": "Makes a copy of the factor.\n\n        Returns\n        -------\n        CanonicalDistribution object: Copy of the factor\n\n        Examples\n        --------\n        >>> from pgmpy.factors.continuous import CanonicalDistribution\n        >>> phi = CanonicalDistribution(['X', 'Y'], np.array([[1, -1], [-1, 1]]),\n                                  np.array([[1], [-1]]), -3)\n        >>> phi.variables\n        ['X', 'Y']\n\n        >>> phi.K\n        array([[1, -1],\n               [-1, 1]])\n\n        >>> phi.h\n        array([[1],\n               [-1]])\n\n        >>> phi.g\n        -3\n\n        >>> phi2 = phi.copy()\n\n        >>> phi2.variables\n        ['X', 'Y']\n\n        >>> phi2.K\n        array([[1, -1],\n               [-1, 1]])\n\n        >>> phi2.h\n        array([[1],\n               [-1]])\n\n        >>> phi2.g\n        -3"
  },
  {
    "code": "def create_templates_static_files(app_path):\n    templates_path = os.path.join(app_path, 'templates')\n    static_path = os.path.join(app_path, 'static')\n    _mkdir_p(templates_path)\n    _mkdir_p(static_path)\n    os.chdir(static_path)\n    img_path = os.path.join(static_path, 'img')\n    css_path = os.path.join(static_path, 'css')\n    js_path = os.path.join(static_path, 'js')\n    _mkdir_p(img_path)\n    _mkdir_p(css_path)\n    _mkdir_p(js_path)\n    return css_path, templates_path",
    "docstring": "create templates and static"
  },
  {
    "code": "def book(self, symbol='btcusd', limit_bids=0, limit_asks=0):\n        url = self.base_url + '/v1/book/' + symbol\n        params = {\n            'limit_bids': limit_bids,\n            'limit_asks': limit_asks\n        }\n        return requests.get(url, params)",
    "docstring": "Send a request to get the public order book, return the response.\n\n        Arguments:\n        symbol -- currency symbol (default 'btcusd')\n        limit_bids -- limit the number of bids returned (default 0)\n        limit_asks -- limit the number of asks returned (default 0)"
  },
  {
    "code": "def total_msgs(xml):\n    count = 0\n    for x in xml:\n        count += len(x.message)\n    return count",
    "docstring": "count total number of msgs"
  },
  {
    "code": "def get_query_parameters(args, cell_body, date_time=datetime.datetime.now()):\n  env = google.datalab.utils.commands.notebook_environment()\n  config = google.datalab.utils.commands.parse_config(cell_body, env=env, as_dict=False)\n  sql = args['query']\n  if sql is None:\n    raise Exception('Cannot extract query parameters in non-query cell')\n  if config:\n    jsonschema.validate(config, BigQuerySchema.QUERY_PARAMS_SCHEMA)\n  config = config or {}\n  config_parameters = config.get('parameters', [])\n  return bigquery.Query.get_query_parameters(config_parameters, date_time=date_time)",
    "docstring": "Extract query parameters from cell body if provided\n  Also validates the cell body schema using jsonschema to catch errors before sending the http\n  request. This validation isn't complete, however; it does not validate recursive schemas,\n  but it acts as a good filter against most simple schemas\n\n  Args:\n    args: arguments passed to the magic cell\n    cell_body: body of the magic cell\n    date_time: The timestamp at which the date-time related parameters need to be resolved.\n\n  Returns:\n    Validated object containing query parameters"
  },
  {
    "code": "def tag(self, layer):\n        mapping = self.layer_tagger_mapping\n        if layer in mapping:\n            mapping[layer]()\n        return self",
    "docstring": "Tag the annotations of given layer. It can automatically tag any built-in layer type."
  },
  {
    "code": "def _get_crc32(self, filename):\n        buffer = self.zip.read(filename)\n        if filename not in self.files_crc32:\n            self.files_crc32[filename] = crc32(buffer)\n            if self.files_crc32[filename] != self.zip.getinfo(filename).CRC:\n                log.error(\"File '{}' has different CRC32 after unpacking! \"\n                          \"Declared: {:08x}, Calculated: {:08x}\".format(filename,\n                                                                        self.zip.getinfo(filename).CRC,\n                                                                        self.files_crc32[filename]))\n        return buffer",
    "docstring": "Calculates and compares the CRC32 and returns the raw buffer.\n\n        The CRC32 is added to `files_crc32` dictionary, if not present.\n\n        :param filename: filename inside the zipfile\n        :rtype: bytes"
  },
  {
    "code": "def network_protocol(self, layer: Optional[Layer] = None) -> str:\n        key = self._validate_enum(item=layer, enum=Layer)\n        protocols = NETWORK_PROTOCOLS[key]\n        return self.random.choice(protocols)",
    "docstring": "Get a random network protocol form OSI model.\n\n        :param layer: Enum object Layer.\n        :return: Protocol name.\n\n        :Example:\n            AMQP"
  },
  {
    "code": "def filter_by_size(feat_dir: Path, prefixes: List[str], feat_type: str,\n                   max_samples: int) -> List[str]:\n    prefix_lens = get_prefix_lens(Path(feat_dir), prefixes, feat_type)\n    prefixes = [prefix for prefix, length in prefix_lens\n                if length <= max_samples]\n    return prefixes",
    "docstring": "Sorts the files by their length and returns those with less\n    than or equal to max_samples length. Returns the filename prefixes of\n    those files. The main job of the method is to filter, but the sorting\n    may give better efficiency when doing dynamic batching unless it gets\n    shuffled downstream."
  },
  {
    "code": "def write_file(self, name, path=None):\n        if path is None:\n            path = name\n        self.zf.write(path, name)",
    "docstring": "Write the contents of a file from the disk to the XPI."
  },
  {
    "code": "def wrap_list(item):\n    if item is None:\n        return []\n    elif isinstance(item, list):\n        return item\n    elif isinstance(item, (tuple, set)):\n        return list(item)\n    else:\n        return [item]",
    "docstring": "Returns an object as a list.\n\n    If the object is a list, it is returned directly. If it is a tuple or set, it\n    is returned as a list. If it is another object, it is wrapped in a list and\n    returned."
  },
  {
    "code": "def get_vhost(self, vname):\n        vname = quote(vname, '')\n        path = Client.urls['vhosts_by_name'] % vname\n        vhost = self._call(path, 'GET', headers=Client.json_headers)\n        return vhost",
    "docstring": "Returns the attributes of a single named vhost in a dict.\n\n        :param string vname: Name of the vhost to get.\n        :returns dict vhost: Attribute dict for the named vhost"
  },
  {
    "code": "def assert_tz_offset(tz):\n    tz_offset = get_tz_offset(tz)\n    system_offset = get_system_offset()\n    if tz_offset != system_offset:\n        msg = ('Timezone offset does not match system offset: {0} != {1}. '\n               'Please, check your config files.').format(\n                   tz_offset, system_offset\n               )\n        raise ValueError(msg)",
    "docstring": "Assert that system's timezone offset equals to the timezone offset found.\n\n    If they don't match, we probably have a misconfiguration, for example, an\n    incorrect timezone set in /etc/timezone file in systemd distributions."
  },
  {
    "code": "def build_raw_request_message(self, request, args, is_completed=False):\n        request.flags = FlagsType.none if is_completed else FlagsType.fragment\n        if request.state == StreamState.init:\n            message = CallRequestMessage(\n                flags=request.flags,\n                ttl=request.ttl * 1000,\n                tracing=request.tracing,\n                service=request.service,\n                headers=request.headers,\n                checksum=request.checksum,\n                args=args\n            )\n            request.state = (StreamState.completed if is_completed\n                             else StreamState.streaming)\n        elif request.state == StreamState.streaming:\n            message = CallRequestContinueMessage(\n                flags=request.flags,\n                checksum=request.checksum,\n                args=args\n            )\n            request.state = (StreamState.completed if is_completed\n                             else StreamState.streaming)\n        message.id = request.id\n        return message",
    "docstring": "build protocol level message based on request and args.\n\n        request object contains meta information about outgoing request.\n        args are the currently chunk data from argstreams\n        is_completed tells the flags of the message\n\n        :param request: Request\n        :param args: array of arg streams\n        :param is_completed: message flags\n        :return: CallRequestMessage/CallRequestContinueMessage"
  },
  {
    "code": "def C0t_(self):\n        self._check_estimated()\n        return self._rc.cov_XY(bessel=self.bessel)",
    "docstring": "Time-lagged covariance matrix"
  },
  {
    "code": "def from_protobuf(cls, msg):\n        if not isinstance(msg, cls._protobuf_cls):\n            raise TypeError(\"Expected message of type \"\n                            \"%r\" % cls._protobuf_cls.__name__)\n        kwargs = {k: getattr(msg, k) for k in cls._get_params()}\n        return cls(**kwargs)",
    "docstring": "Create an instance from a protobuf message."
  },
  {
    "code": "def first(seq, key=lambda x: bool(x), default=None, apply=lambda x: x):\n    return next((apply(x) for x in seq if key(x)), default() if callable(default) else default)",
    "docstring": "Give the first value that satisfies the key test.\n\n    Args:\n        seq (iterable):\n        key (callable): test for each element of iterable\n        default: returned when all elements fail test\n        apply (callable): applied to element before return, but not to default value\n\n    Returns: first element in seq that passes key, mutated with optional apply\n\n    Examples:\n        >>> first([0, False, None, [], (), 42])\n        42\n        >>> first([0, False, None, [], ()]) is None\n        True\n        >>> first([0, False, None, [], ()], default='ohai')\n        'ohai'\n        >>> import re\n        >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])\n        >>> m.group(1)\n        'bc'\n\n        The optional `key` argument specifies a one-argument predicate function\n        like that used for `filter()`.  The `key` argument, if supplied, must be\n        in keyword form.  For example:\n        >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)\n        4"
  },
  {
    "code": "def _start_update_server(auth_token):\n    server = AccumulatorServer((\"localhost\", 0), _UpdateRequestHandler, auth_token)\n    thread = threading.Thread(target=server.serve_forever)\n    thread.daemon = True\n    thread.start()\n    return server",
    "docstring": "Start a TCP server to receive accumulator updates in a daemon thread, and returns it"
  },
  {
    "code": "def _validated_config_filename(self, name):\n        dir_name = self._make_config_dir()\n        filename = os.path.join(dir_name, name.split(\".json\")[0] + \".json\")\n        return filename",
    "docstring": "Make config dir and return full file path and extension\n\n        Args:\n            name (str): Filename without dir or extension\n\n        Returns:\n            str: Full path including extension"
  },
  {
    "code": "def recent(category=None, pages=1, sort=None, order=None):\n\ts = Search()\n\ts.recent(category, pages, sort, order)\n\treturn s",
    "docstring": "Return most recently added torrents. Can be sorted and categorized\n\t\tand contain multiple pages."
  },
  {
    "code": "def create(cls, config_file=None):\n        if cls.instance is None:\n            cls.instance = cls(config_file)\n            cls.instance.load_ini()\n        if config_file and config_file != cls.instance.config_file:\n            raise RuntimeError(\"Configuration initialized a second time with a different file!\")\n        return cls.instance",
    "docstring": "Return the default configuration."
  },
  {
    "code": "def lost_master_primary(self):\n        self.primaries_disconnection_times[self.master_replica.instId] = time.perf_counter()\n        self._schedule_view_change()",
    "docstring": "Schedule an primary connection check which in turn can send a view\n        change message"
  },
  {
    "code": "def _flush_wait(flush_future, write_future):\n    if write_future.done():\n        if not _pending_measurements():\n            flush_future.set_result(True)\n            return\n        else:\n            write_future = _write_measurements()\n    ioloop.IOLoop.current().add_timeout(\n        ioloop.IOLoop.current().time() + 0.25,\n        _flush_wait, flush_future, write_future)",
    "docstring": "Pause briefly allowing any pending metric writes to complete before\n    shutting down.\n\n    :param tornado.concurrent.Future flush_future: The future to resolve\n        when the shutdown is complete.\n    :param tornado.concurrent.Future write_future: The future that is for the\n        current batch write operation."
  },
  {
    "code": "def autodiscover(self, message):\n        if message[\"version\"] in self.allowed_versions:\n            logger.debug(\"<%s> Client version matches server \"\n                         \"version.\" % message[\"cuuid\"])\n            response = serialize_data({\"method\": \"OHAI Client\",\n                                       \"version\": self.version,\n                                       \"server_name\": self.server_name},\n                                      self.compression,\n                                      encryption=False)\n        else:\n            logger.warning(\"<%s> Client version %s does not match allowed server \"\n                           \"versions %s\" % (message[\"cuuid\"],\n                                            message[\"version\"],\n                                            self.version))\n            response = serialize_data({\"method\": \"BYE REGISTER\"},\n                                      self.compression,\n                                      encryption=False)\n        return response",
    "docstring": "This function simply returns the server version number as a response\n        to the client.\n\n        Args:\n          message (dict): A dictionary of the autodiscover message from the\n            client.\n\n        Returns:\n          A JSON string of the \"OHAI Client\" server response with the server's\n          version number.\n\n        Examples:\n          >>> response\n          '{\"method\": \"OHAI Client\", \"version\": \"1.0\"}'"
  },
  {
    "code": "def generate_packer_filename(provider, region, builder):\n    filename = '{0}_{1}_{2}.json'.format(provider, region, builder)\n    return filename",
    "docstring": "Generate a filename to be used by packer.\n\n    Args:\n        provider (str): Name of Spinnaker provider.\n        region (str): Name of provider region to use.\n        builder (str): Name of builder process type.\n\n    Returns:\n        str: Generated filename based on parameters."
  },
  {
    "code": "def search_module(mod, pat, ignore_case=True, recursive=False, _seen=None):\n    r\n    if _seen is not None and mod in _seen:\n        return []\n    import utool as ut\n    reflags = re.IGNORECASE * ignore_case\n    found_list = [name for name in dir(mod) if re.search(pat, name, flags=reflags)]\n    if recursive:\n        if _seen is None:\n            _seen = set()\n        _seen.add(mod)\n        module_attrs = [getattr(mod, name) for name in dir(mod)]\n        submodules = [\n            submod for submod in module_attrs\n            if isinstance(submod, types.ModuleType) and submod not in _seen and\n            ut.is_defined_by_module(submod, mod)\n        ]\n        for submod in submodules:\n            found_list += search_module(submod, pat, ignore_case=ignore_case, recursive=recursive, _seen=_seen)\n    found_list = ut.unique_ordered(found_list)\n    return found_list",
    "docstring": "r\"\"\"\n    Searches module functions, classes, and constants for members matching a\n    pattern.\n\n    Args:\n        mod (module): live python module\n        pat (str): regular expression\n\n    Returns:\n        list: found_list\n\n    CommandLine:\n        python -m utool.util_dev --exec-search_module --mod=utool --pat=module\n        python -m utool.util_dev --exec-search_module --mod=opengm --pat=cut\n        python -m utool.util_dev --exec-search_module --mod=opengm --pat=multi\n        python -m utool.util_dev --exec-search_module --mod=plottool --pat=networkx\n        python -m utool.util_dev --exec-search_module --mod=utool --pat=Levenshtein\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_dev import *  # NOQA\n        >>> import utool as ut\n        >>> recursive = True\n        >>> ignore_case = True\n        >>> modname = ut.get_argval('--mod', type_=str, default='utool')\n        >>> pat = ut.get_argval('--pat', type_=str, default='search')\n        >>> mod = ut.import_modname(modname)\n        >>> print('pat = %r' % (pat,))\n        >>> print('mod = %r' % (mod,))\n        >>> found_list = search_module(mod, pat, recursive=recursive)\n        >>> result = ('found_list = %s' % (ut.repr2(found_list),))\n        >>> print(result)\n\n    Ignore:\n        mod = cv2\n        pat = 'freak'"
  },
  {
    "code": "def lookup_path(self, mold_id_path, default=_marker):\n        fragments = mold_id_path.split('/')\n        mold_id = '/'.join(fragments[:2])\n        try:\n            subpath = []\n            for piece in fragments[2:]:\n                if (sep in piece or (altsep and altsep in piece) or\n                        piece == pardir):\n                    raise KeyError\n                elif piece and piece != '.':\n                    subpath.append(piece)\n            path = self.mold_id_to_path(mold_id)\n        except KeyError:\n            if default is _marker:\n                raise\n            return default\n        return join(path, *subpath)",
    "docstring": "For the given mold_id_path, look up the mold_id and translate\n        that path to its filesystem equivalent."
  },
  {
    "code": "def sort(self):\n        if self.is_guaranteed_sorted:\n            self.log(u\"Already sorted, returning\")\n            return\n        self.log(u\"Sorting...\")\n        self.__fragments = sorted(self.__fragments)\n        self.log(u\"Sorting... done\")\n        self.log(u\"Checking relative positions...\")\n        for i in range(len(self) - 1):\n            current_interval = self[i].interval\n            next_interval = self[i + 1].interval\n            if current_interval.relative_position_of(next_interval) not in self.ALLOWED_POSITIONS:\n                self.log(u\"Found overlapping fragments:\")\n                self.log([u\"  Index %d => %s\", i, current_interval])\n                self.log([u\"  Index %d => %s\", i + 1, next_interval])\n                self.log_exc(u\"The list contains two fragments overlapping in a forbidden way\", None, True, ValueError)\n        self.log(u\"Checking relative positions... done\")\n        self.__sorted = True",
    "docstring": "Sort the fragments in the list.\n\n        :raises ValueError: if there is a fragment which violates\n                            the list constraints"
  },
  {
    "code": "def set_extana_callback(self, callback, data=None):\n        self.extana_callback = callback\n        self.extana_callback_data = data",
    "docstring": "Register a callback for incoming data packets from the SK8-ExtAna board.\n\n        This method allows you to pass in a callable which will be called on \n        receipt of each packet sent from the SK8-ExtAna board. Set to `None` to\n        disable it again.\n\n        Args:\n            callback: a callable with the following signature:\n                        (ana1, ana2, temp, seq, timestamp, data)\n                      where:\n                        ana1, ana2 = current values of the two analogue inputs\n                        temp = temperature sensor reading\n                        seq = packet sequence number (int, 0-255)\n                        timestamp = value of time.time() when packet received\n                        data = value of `data` parameter passed to this method\n            data: an optional arbitrary object that will be passed as a \n                parameter to the callback"
  },
  {
    "code": "def _parse(self, line):\n        try:\n            result = line.split(':', maxsplit=4)\n            filename, line_num_txt, column_txt, message_type, text = result\n        except ValueError:\n            return\n        try:\n            self.line_num = int(line_num_txt.strip())\n            self.column = int(column_txt.strip())\n        except ValueError:\n            return\n        self.filename = filename\n        self.message_type = message_type.strip()\n        self.text = text.strip()\n        self.valid = True",
    "docstring": "Parse the output line"
  },
  {
    "code": "def content_type(self, data):\n        self._content_type = str(data)\n        self.add_header('Content-Type', str(data))",
    "docstring": "The Content-Type header value for this request."
  },
  {
    "code": "def _construct_permission(self, function, source_arn=None, source_account=None, suffix=\"\", event_source_token=None):\n        lambda_permission = LambdaPermission(self.logical_id + 'Permission' + suffix,\n                                             attributes=function.get_passthrough_resource_attributes())\n        try:\n            function_name_or_arn = function.get_runtime_attr(\"name\")\n        except NotImplementedError:\n            function_name_or_arn = function.get_runtime_attr(\"arn\")\n        lambda_permission.Action = 'lambda:invokeFunction'\n        lambda_permission.FunctionName = function_name_or_arn\n        lambda_permission.Principal = self.principal\n        lambda_permission.SourceArn = source_arn\n        lambda_permission.SourceAccount = source_account\n        lambda_permission.EventSourceToken = event_source_token\n        return lambda_permission",
    "docstring": "Constructs the Lambda Permission resource allowing the source service to invoke the function this event\n        source triggers.\n\n        :returns: the permission resource\n        :rtype: model.lambda_.LambdaPermission"
  },
  {
    "code": "def validate_body(schema):\n    location = get_callsite_location()\n    def decorator(fn):\n        validate_schema(schema)\n        wrapper = wrap_request(fn, schema)\n        record_schemas(\n            fn, wrapper, location, request_schema=sort_schema(schema))\n        return wrapper\n    return decorator",
    "docstring": "Validate the body of incoming requests for a flask view.\n\n    An example usage might look like this::\n\n        from snapstore_schemas import validate_body\n\n\n        @validate_body({\n            'type': 'array',\n            'items': {\n                'type': 'object',\n                'properties': {\n                    'snap_id': {'type': 'string'},\n                    'series': {'type': 'string'},\n                    'name': {'type': 'string'},\n                    'title': {'type': 'string'},\n                    'keywords': {\n                        'type': 'array',\n                        'items': {'type': 'string'}\n                    },\n                    'summary': {'type': 'string'},\n                    'description': {'type': 'string'},\n                    'created_at': {'type': 'string'},\n                },\n                'required': ['snap_id', 'series'],\n                'additionalProperties': False\n            }\n        })\n        def my_flask_view():\n            # view code here\n            return \"Hello World\", 200\n\n    All incoming request that have been routed to this view will be matched\n    against the specified schema. If the request body does not match the schema\n    an instance of `DataValidationError` will be raised.\n\n    By default this will cause the flask application to return a 500 response,\n    but this can be customised by telling flask how to handle these exceptions.\n    The exception instance has an 'error_list' attribute that contains a list\n    of all the errors encountered while processing the request body."
  },
  {
    "code": "def show_dependencies(self, stream=sys.stdout):\n        def child_iter(node):\n            return [d.node for d in node.deps]\n        def text_str(node):\n            return colored(str(node), color=node.status.color_opts[\"color\"])\n        for task in self.iflat_tasks():\n            print(draw_tree(task, child_iter, text_str), file=stream)",
    "docstring": "Writes to the given stream the ASCII representation of the dependency tree."
  },
  {
    "code": "def _prepareSubForm(self, liveForm):\n        liveForm = liveForm.asSubForm(self.name)\n        if self._parameterIsCompact:\n            liveForm.compact()\n        return liveForm",
    "docstring": "Utility for turning liveforms into subforms, and compacting them as\n        necessary.\n\n        @param liveForm: a liveform.\n        @type liveForm: L{LiveForm}\n\n        @return: a sub form.\n        @rtype: L{LiveForm}"
  },
  {
    "code": "def srv_event(token, hits, url=RBA_URL):\n    if url is None:\n        log.error(\"Please provide a valid RainbowAlga URL.\")\n        return\n    ws_url = url + '/message'\n    if isinstance(hits, pd.core.frame.DataFrame):\n        pos = [tuple(x) for x in hits[['x', 'y', 'z']].values]\n        time = list(hits['time'])\n        tot = list(hits['tot'])\n    elif isinstance(hits, Table):\n        pos = list(zip(hits.pos_x, hits.pos_y, hits.pos_z))\n        time = list(hits.time)\n        tot = list(hits.tot)\n    else:\n        log.error(\n            \"No calibration information found in hits (type: {0})\".format(\n                type(hits)\n            )\n        )\n        return\n    event = {\n        \"hits\": {\n            'pos': pos,\n            'time': time,\n            'tot': tot,\n        }\n    }\n    srv_data(ws_url, token, event, 'event')",
    "docstring": "Serve event to RainbowAlga"
  },
  {
    "code": "def nmf_tsne(data, k, n_runs=10, init='enhanced', **params):\n    clusters = []\n    nmf = NMF(k)\n    tsne = TSNE(2)\n    km = KMeans(k)\n    for i in range(n_runs):\n        w = nmf.fit_transform(data)\n        h = nmf.components_\n        tsne_wh = tsne.fit_transform(w.dot(h).T)\n        clust = km.fit_predict(tsne_wh)\n        clusters.append(clust)\n    clusterings = np.vstack(clusters)\n    consensus = CE.cluster_ensembles(clusterings, verbose=False, N_clusters_max=k)\n    nmf_new = NMF(k, init='custom')\n    init_w, init_h = nmf_init(data, consensus, k, init)\n    W = nmf_new.fit_transform(data, W=init_w, H=init_h)\n    H = nmf_new.components_\n    return W, H",
    "docstring": "runs tsne-consensus-NMF\n\n    1. run a bunch of NMFs, get W and H\n    2. run tsne + km on all WH matrices\n    3. run consensus clustering on all km results\n    4. use consensus clustering as initialization for a new run of NMF\n    5. return the W and H from the resulting NMF run"
  },
  {
    "code": "def update_redirect(self):\n        page_history = Stack(session.get(\"page_history\", []))\n        page_history.push(request.url)\n        session[\"page_history\"] = page_history.to_json()",
    "docstring": "Call it on your own endpoint's to update the back history navigation.\n            If you bypass it, the next submit or back will go over it."
  },
  {
    "code": "def update(self, iteration, fobj):\n        self.bst.update(self.dtrain, iteration, fobj)",
    "docstring": "Update the boosters for one iteration"
  },
  {
    "code": "def only_passed_and_wait(result):\n    verdict = result.get(\"verdict\", \"\").strip().lower()\n    if verdict in Verdicts.PASS + Verdicts.WAIT:\n        return result\n    return None",
    "docstring": "Returns PASS and WAIT results only, skips everything else."
  },
  {
    "code": "def queue_bind(self, queue, exchange, routing_key, arguments=None):\n        return self.channel.queue_bind(queue=queue,\n                                       exchange=exchange,\n                                       routing_key=routing_key,\n                                       arguments=arguments)",
    "docstring": "Bind queue to an exchange using a routing key."
  },
  {
    "code": "def disable_snapshots(self, volume_id, schedule_type):\n        return self.client.call('Network_Storage', 'disableSnapshots',\n                                schedule_type, id=volume_id)",
    "docstring": "Disables snapshots for a specific block volume at a given schedule\n\n        :param integer volume_id: The id of the volume\n        :param string schedule_type: 'HOURLY'|'DAILY'|'WEEKLY'\n        :return: Returns whether successfully disabled or not"
  },
  {
    "code": "def rollaxis(vari, axis, start=0):\n    if isinstance(vari, Poly):\n        core_old = vari.A.copy()\n        core_new = {}\n        for key in vari.keys:\n            core_new[key] = rollaxis(core_old[key], axis, start)\n        return Poly(core_new, vari.dim, None, vari.dtype)\n    return numpy.rollaxis(vari, axis, start)",
    "docstring": "Roll the specified axis backwards, until it lies in a given position.\n\n    Args:\n        vari (chaospy.poly.base.Poly, numpy.ndarray):\n            Input array or polynomial.\n        axis (int):\n            The axis to roll backwards. The positions of the other axes do not\n            change relative to one another.\n        start (int):\n            The axis is rolled until it lies before thes position."
  },
  {
    "code": "def format_endpoint(schema, addr, port, api_version):\n    return '{}://{}:{}/{}/'.format(schema, addr, port,\n                                   get_api_suffix(api_version))",
    "docstring": "Return a formatted keystone endpoint\n    @param schema: http or https\n    @param addr: ipv4/ipv6 host of the keystone service\n    @param port: port of the keystone service\n    @param api_version: 2 or 3\n    @returns a fully formatted keystone endpoint"
  },
  {
    "code": "def _set_final_freeness(self, flag):\n        if flag:\n            self.state.memory.store(self.heap_base + self.heap_size - self._chunk_size_t_size, ~CHUNK_P_MASK)\n        else:\n            self.state.memory.store(self.heap_base + self.heap_size - self._chunk_size_t_size, CHUNK_P_MASK)",
    "docstring": "Sets the freedom of the final chunk. Since no proper chunk follows the final chunk, the heap itself manages\n        this. Nonetheless, for now it is implemented as if an additional chunk followed the final chunk."
  },
  {
    "code": "def _create_filter_dsl(urlkwargs, definitions):\n    filters = []\n    for name, filter_factory in definitions.items():\n        values = request.values.getlist(name, type=text_type)\n        if values:\n            filters.append(filter_factory(values))\n            for v in values:\n                urlkwargs.add(name, v)\n    return (filters, urlkwargs)",
    "docstring": "Create a filter DSL expression."
  },
  {
    "code": "def __generate_key(self, config):\n        cwd = config.get('ssh_path', self._install_directory())\n        if config.is_affirmative('create', default=\"yes\"):\n            if not os.path.exists(cwd):\n                os.makedirs(cwd)\n            if not os.path.exists(os.path.join(cwd, config.get('keyname'))):\n                command = \"ssh-keygen -t %(type)s -f %(keyname)s -N  \" % config.to_dict()\n                lib.call(command, cwd=cwd, output_log_level=logging.DEBUG)\n        if not config.has('ssh_path'):\n            config.set('ssh_path', cwd)\n        config.set('ssh_key_path', os.path.join(config.get('ssh_path'), config.get('keyname')))",
    "docstring": "Generate the ssh key, and return the ssh config location"
  },
  {
    "code": "def destroy(self):\n        self.stop()\n        if self.base_pathname is not None:\n            self._robust_remove(self.base_pathname)",
    "docstring": "Undo the effects of initdb.\n\n        Destroy all evidence of this DBMS, including its backing files."
  },
  {
    "code": "def _extract_image_urls(arg: Message_T) -> List[str]:\n    arg_as_msg = Message(arg)\n    return [s.data['url'] for s in arg_as_msg\n            if s.type == 'image' and 'url' in s.data]",
    "docstring": "Extract all image urls from a message-like object."
  },
  {
    "code": "def iterpackages(self):\n        pkgdir = os.path.join(self._path, self.PKG_DIR)\n        if not os.path.isdir(pkgdir):\n            return\n        for team in sub_dirs(pkgdir):\n            for user in sub_dirs(self.team_path(team)):\n                for pkg in sub_dirs(self.user_path(team, user)):\n                    pkgpath = self.package_path(team, user, pkg)\n                    for hsh in sub_files(os.path.join(pkgpath, PackageStore.CONTENTS_DIR)):\n                        yield self.get_package(team, user, pkg, pkghash=hsh)",
    "docstring": "Return an iterator over all the packages in the PackageStore."
  },
  {
    "code": "def _handle_aui(self, data):\n        msg = AUIMessage(data)\n        self.on_aui_message(message=msg)\n        return msg",
    "docstring": "Handle AUI messages.\n\n        :param data: RF message to parse\n        :type data: string\n\n        :returns: :py:class`~alarmdecoder.messages.AUIMessage`"
  },
  {
    "code": "def set_attributes(self, attr_obj=None, ns_uri=None, **attr_dict):\n        self._set_element_attributes(self.impl_node,\n            attr_obj=attr_obj, ns_uri=ns_uri, **attr_dict)",
    "docstring": "Add or update this element's attributes, where attributes can be\n        specified in a number of ways.\n\n        :param attr_obj: a dictionary or list of attribute name/value pairs.\n        :type attr_obj: dict, list, tuple, or None\n        :param ns_uri: a URI defining a namespace for the new attributes.\n        :type ns_uri: string or None\n        :param dict attr_dict: attribute name and values specified as keyword\n            arguments."
  },
  {
    "code": "def filter_content_types(self, content_type_qs):\n        valid_ct_ids = []\n        for ct in content_type_qs:\n            model = ct.model_class()\n            if model and issubclass(model, EventBase):\n                valid_ct_ids.append(ct.id)\n        return content_type_qs.filter(pk__in=valid_ct_ids)",
    "docstring": "Filter the content types selectable to only event subclasses"
  },
  {
    "code": "def instances_changed(self):\n        value = bool(lib.EnvGetInstancesChanged(self._env))\n        lib.EnvSetInstancesChanged(self._env, int(False))\n        return value",
    "docstring": "True if any instance has changed."
  },
  {
    "code": "def on(self, event):\n        handler = self._handlers.get(event, None)\n        if not handler:\n            raise ValueError(\"Unknown event '{}'\".format(event))\n        return handler.register",
    "docstring": "Returns a wrapper for the given event.\n\n        Usage:\n\n            @dispatch.on(\"my_event\")\n            def handle_my_event(foo, bar, baz):\n                ..."
  },
  {
    "code": "def get_matrix_from_list(self, rows, columns, matrix_list, rowBased=True):\n        resultMatrix = Matrix(columns, rows, matrix_list, rowBased)\n        return resultMatrix",
    "docstring": "Create a new Matrix instance from a matrix_list.\n\n        :note: This method is used to create a Matrix instance using cpython.\n        :param integer rows:        The height of the Matrix.\n        :param integer columns:     The width of the Matrix.\n        :param matrix_list:         A one dimensional list containing the\n                                    values for Matrix. Depending on the\n                                    rowBased parameter, either the rows are\n                                    combined or the columns.\n        :param rowBased Boolean:    Only necessary if the oneDimArray is given.\n                                    Indicates whether the oneDimArray combines\n                                    rows together (rowBased=True) or columns\n                                    (rowBased=False)."
  },
  {
    "code": "def set_location(self, obj, cursor):\n        if (hasattr(cursor, 'location') and cursor.location is not None and\n                cursor.location.file is not None):\n            obj.location = (cursor.location.file.name, cursor.location.line)\n        return",
    "docstring": "Location is also used for codegeneration ordering."
  },
  {
    "code": "def render_template(process, template_string, context):\n    from resolwe.flow.managers import manager\n    expression_engine = process.requirements.get('expression-engine', None)\n    if not expression_engine:\n        return template_string\n    return manager.get_expression_engine(expression_engine).evaluate_block(template_string, context)",
    "docstring": "Render template using the specified expression engine."
  },
  {
    "code": "def instance(cls, *args, **kwgs):\n        if not hasattr(cls, \"_instance\"):\n            cls._instance = cls(*args, **kwgs)\n        return cls._instance",
    "docstring": "Will be the only instance"
  },
  {
    "code": "def findNestedNamespaces(self, lst):\n        if self.kind == \"namespace\":\n            lst.append(self)\n        for c in self.children:\n            c.findNestedNamespaces(lst)",
    "docstring": "Recursive helper function for finding nested namespaces.  If this node is a\n        namespace node, it is appended to ``lst``.  Each node also calls each of its\n        child ``findNestedNamespaces`` with the same list.\n\n        :Parameters:\n            ``lst`` (list)\n                The list each namespace node is to be appended to."
  },
  {
    "code": "def haversine(point1, point2, unit='km'):\n    AVG_EARTH_RADIUS_KM = 6371.0088\n    conversions = {'km': 1,\n                   'm': 1000,\n                   'mi': 0.621371192,\n                   'nmi': 0.539956803,\n                   'ft': 3280.839895013,\n                   'in': 39370.078740158}\n    avg_earth_radius = AVG_EARTH_RADIUS_KM * conversions[unit]\n    lat1, lng1 = point1\n    lat2, lng2 = point2\n    lat1, lng1, lat2, lng2 = map(radians, (lat1, lng1, lat2, lng2))\n    lat = lat2 - lat1\n    lng = lng2 - lng1\n    d = sin(lat * 0.5) ** 2 + cos(lat1) * cos(lat2) * sin(lng * 0.5) ** 2\n    return 2 * avg_earth_radius * asin(sqrt(d))",
    "docstring": "Calculate the great-circle distance between two points on the Earth surface.\n\n    :input: two 2-tuples, containing the latitude and longitude of each point\n    in decimal degrees.\n\n    Keyword arguments:\n    unit -- a string containing the initials of a unit of measurement (i.e. miles = mi)\n            default 'km' (kilometers).\n\n    Example: haversine((45.7597, 4.8422), (48.8567, 2.3508))\n\n    :output: Returns the distance between the two points.\n\n    The default returned unit is kilometers. The default unit can be changed by\n    setting the unit parameter to a string containing the initials of the desired unit.\n    Other available units are miles (mi), nautic miles (nmi), meters (m),\n    feets (ft) and inches (in)."
  },
  {
    "code": "def get_urlhash(self, url, fmt):\n        with self.open(os.path.basename(url)) as f:\n            return {'url': fmt(url), 'sha256': filehash(f, 'sha256')}",
    "docstring": "Returns the hash of the file of an internal url"
  },
  {
    "code": "def trigger_info(self, trigger=None, dump=False):\n        if dump:\n            return self._syntax\n        response = None\n        for category in self._syntax:\n            for topic in self._syntax[category]:\n                if trigger in self._syntax[category][topic]:\n                    if response is None:\n                        response = list()\n                    fname, lineno = self._syntax[category][topic][trigger]['trigger']\n                    response.append(dict(\n                        category=category,\n                        topic=topic,\n                        trigger=trigger,\n                        filename=fname,\n                        line=lineno,\n                    ))\n        return response",
    "docstring": "Get information about a trigger.\n\n        Pass in a raw trigger to find out what file name and line number it\n        appeared at. This is useful for e.g. tracking down the location of the\n        trigger last matched by the user via ``last_match()``. Returns a list\n        of matching triggers, containing their topics, filenames and line\n        numbers. Returns ``None`` if there weren't any matches found.\n\n        The keys in the trigger info is as follows:\n\n        * ``category``: Either 'topic' (for normal) or 'thats'\n          (for %Previous triggers)\n        * ``topic``: The topic name\n        * ``trigger``: The raw trigger text\n        * ``filename``: The filename the trigger was found in.\n        * ``lineno``: The line number the trigger was found on.\n\n        Pass in a true value for ``dump``, and the entire syntax tracking\n        tree is returned.\n\n        :param str trigger: The raw trigger text to look up.\n        :param bool dump: Whether to dump the entire syntax tracking tree.\n\n        :return: A list of matching triggers or ``None`` if no matches."
  },
  {
    "code": "def get_locator(self, dmin, dmax):\n        'Pick the best locator based on a distance.'\n        _check_implicitly_registered()\n        delta = relativedelta(dmax, dmin)\n        num_days = (delta.years * 12.0 + delta.months) * 31.0 + delta.days\n        num_sec = (delta.hours * 60.0 + delta.minutes) * 60.0 + delta.seconds\n        tot_sec = num_days * 86400. + num_sec\n        if abs(tot_sec) < self.minticks:\n            self._freq = -1\n            locator = MilliSecondLocator(self.tz)\n            locator.set_axis(self.axis)\n            locator.set_view_interval(*self.axis.get_view_interval())\n            locator.set_data_interval(*self.axis.get_data_interval())\n            return locator\n        return dates.AutoDateLocator.get_locator(self, dmin, dmax)",
    "docstring": "Pick the best locator based on a distance."
  },
  {
    "code": "def endings(self):\n        if not self.is_tagged(ANALYSIS):\n            self.tag_analysis()\n        return self.get_analysis_element(ENDING)",
    "docstring": "The list of word endings.\n\n        Ambiguous cases are separated with pipe character by default.\n        Use :py:meth:`~estnltk.text.Text.get_analysis_element` to specify custom separator for ambiguous entries."
  },
  {
    "code": "def update_is_start(self):\n        self.is_start = self.state.is_root_state or \\\n                        self.parent is None or \\\n                        isinstance(self.parent.state, LibraryState) or \\\n                        self.state.state_id == self.state.parent.start_state_id",
    "docstring": "Updates the `is_start` property of the state\n        \n        A state is a start state, if it is the root state, it has no parent, the parent is a LibraryState or the state's\n        state_id is identical with the ContainerState.start_state_id of the ContainerState it is within."
  },
  {
    "code": "def probably_wkt(text):\n    valid = False\n    valid_types = set([\n        'POINT', 'LINESTRING', 'POLYGON', 'MULTIPOINT',\n        'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION',\n    ])\n    matched = re.match(r'(\\w+)\\s*\\([^)]+\\)', text.strip())\n    if matched:\n        valid = matched.group(1).upper() in valid_types\n    return valid",
    "docstring": "Quick check to determine if the provided text looks like WKT"
  },
  {
    "code": "def show_config():\n    ret = {}\n    cmd = 'cpan -J'\n    out = __salt__['cmd.run'](cmd).splitlines()\n    for line in out:\n        if '=>' not in line:\n            continue\n        comps = line.split('=>')\n        key = comps[0].replace(\"'\", '').strip()\n        val = comps[1].replace(\"',\", '').replace(\"'\", '').strip()\n        ret[key] = val\n    return ret",
    "docstring": "Return a dict of CPAN configuration values\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' cpan.show_config"
  },
  {
    "code": "def load_or_create_client_key(pem_path):\n    acme_key_file = pem_path.asTextMode().child(u'client.key')\n    if acme_key_file.exists():\n        key = serialization.load_pem_private_key(\n            acme_key_file.getContent(),\n            password=None,\n            backend=default_backend())\n    else:\n        key = generate_private_key(u'rsa')\n        acme_key_file.setContent(\n            key.private_bytes(\n                encoding=serialization.Encoding.PEM,\n                format=serialization.PrivateFormat.TraditionalOpenSSL,\n                encryption_algorithm=serialization.NoEncryption()))\n    return JWKRSA(key=key)",
    "docstring": "Load the client key from a directory, creating it if it does not exist.\n\n    .. note:: The client key that will be created will be a 2048-bit RSA key.\n\n    :type pem_path: ``twisted.python.filepath.FilePath``\n    :param pem_path: The certificate directory\n        to use, as with the endpoint."
  },
  {
    "code": "def get_data():\n    data, targets = make_classification(\n        n_samples=1000,\n        n_features=45,\n        n_informative=12,\n        n_redundant=7,\n        random_state=134985745,\n    )\n    return data, targets",
    "docstring": "Synthetic binary classification dataset."
  },
  {
    "code": "def _make_xml(self, endpoints):\n        root = ElementTree.Element(TAG_ENDPOINT_DESCRIPTIONS)\n        for endpoint in endpoints:\n            self._make_endpoint(root, endpoint)\n        self._indent(root)\n        return root",
    "docstring": "Converts the given endpoint description beans into an XML Element\n\n        :param endpoints: A list of EndpointDescription beans\n        :return: A string containing an XML document"
  },
  {
    "code": "def is_free(self):\n        raise NotImplementedError(\"%s not implemented for %s\" % (self.is_free.__func__.__name__,\n                                                                 self.__class__.__name__))",
    "docstring": "Returns a concrete determination as to whether the chunk is free."
  },
  {
    "code": "def run_fn(self, name, *args, **kwds):\n        fn = None\n        to_check = [picardrun]\n        for ns in to_check:\n            try:\n                fn = getattr(ns, name)\n                break\n            except AttributeError:\n                pass\n        assert fn is not None, \"Could not find function %s in %s\" % (name, to_check)\n        return fn(self, *args, **kwds)",
    "docstring": "Run pre-built functionality that used Broad tools by name.\n\n        See the gatkrun, picardrun module for available functions."
  },
  {
    "code": "def legacy_requests_view(request, rtype):\n    if not rtype in ['food', 'maintenance']:\n        raise Http404\n    requests_dict = []\n    requests = TeacherRequest.objects.filter(request_type=rtype)\n    request_count = requests.count()\n    paginator = Paginator(requests, 50)\n    page = request.GET.get('page')\n    try:\n        requests = paginator.page(page)\n    except PageNotAnInteger:\n        requests = paginator.page(1)\n    except EmptyPage:\n        requests = paginator.page(paginator.num_pages)\n    for req in requests:\n        requests_dict.append(\n            (req, TeacherResponse.objects.filter(request=req),)\n        )\n    return render_to_response(\n        'teacher_requests.html',\n        {'page_name': \"Legacy {rtype} Requests\".format(rtype=rtype.title()),\n         'requests_dict': requests_dict,\n         'requests': requests,\n         'request_type': rtype.title(),\n         'request_count': request_count,},\n        context_instance=RequestContext(request)\n    )",
    "docstring": "View to see legacy requests of rtype request type, which should be either\n    'food' or 'maintenance'."
  },
  {
    "code": "def initialize_variables(sess, saver, logdir, checkpoint=None, resume=None):\n  sess.run(tf.group(\n      tf.local_variables_initializer(),\n      tf.global_variables_initializer()))\n  if resume and not (logdir or checkpoint):\n    raise ValueError('Need to specify logdir to resume a checkpoint.')\n  if logdir:\n    state = tf.train.get_checkpoint_state(logdir)\n    if checkpoint:\n      checkpoint = os.path.join(logdir, checkpoint)\n    if not checkpoint and state and state.model_checkpoint_path:\n      checkpoint = state.model_checkpoint_path\n    if checkpoint and resume is False:\n      message = 'Found unexpected checkpoint when starting a new run.'\n      raise RuntimeError(message)\n    if checkpoint:\n      saver.restore(sess, checkpoint)",
    "docstring": "Initialize or restore variables from a checkpoint if available.\n\n  Args:\n    sess: Session to initialize variables in.\n    saver: Saver to restore variables.\n    logdir: Directory to search for checkpoints.\n    checkpoint: Specify what checkpoint name to use; defaults to most recent.\n    resume: Whether to expect recovering a checkpoint or starting a new run.\n\n  Raises:\n    ValueError: If resume expected but no log directory specified.\n    RuntimeError: If no resume expected but a checkpoint was found."
  },
  {
    "code": "def upload_cart(cart, collection):\n    cart_cols = cart_db()\n    cart_json = read_json_document(cart.cart_file())\n    try:\n        cart_id = cart_cols[collection].save(cart_json)\n    except MongoErrors.AutoReconnect:\n        raise JuicerConfigError(\"Error saving cart to `cart_host`. Ensure that this node is the master.\")\n    return cart_id",
    "docstring": "Connect to mongo and store your cart in the specified collection."
  },
  {
    "code": "def underlying_variable_ref(t):\n  while t.op.type in [\"Identity\", \"ReadVariableOp\", \"Enter\"]:\n    t = t.op.inputs[0]\n  op_type = t.op.type\n  if \"Variable\" in op_type or \"VarHandle\" in op_type:\n    return t\n  else:\n    return None",
    "docstring": "Find the underlying variable ref.\n\n  Traverses through Identity, ReadVariableOp, and Enter ops.\n  Stops when op type has Variable or VarHandle in name.\n\n  Args:\n    t: a Tensor\n\n  Returns:\n    a Tensor that is a variable ref, or None on error."
  },
  {
    "code": "def AddKeyByPath(self, key_path, registry_key):\n    if not key_path.startswith(definitions.KEY_PATH_SEPARATOR):\n      raise ValueError('Key path does not start with: {0:s}'.format(\n          definitions.KEY_PATH_SEPARATOR))\n    if not self._root_key:\n      self._root_key = FakeWinRegistryKey(self._key_path_prefix)\n    path_segments = key_paths.SplitKeyPath(key_path)\n    parent_key = self._root_key\n    for path_segment in path_segments:\n      try:\n        subkey = FakeWinRegistryKey(path_segment)\n        parent_key.AddSubkey(subkey)\n      except KeyError:\n        subkey = parent_key.GetSubkeyByName(path_segment)\n      parent_key = subkey\n    parent_key.AddSubkey(registry_key)",
    "docstring": "Adds a Windows Registry key for a specific key path.\n\n    Args:\n      key_path (str): Windows Registry key path to add the key.\n      registry_key (WinRegistryKey): Windows Registry key.\n\n    Raises:\n      KeyError: if the subkey already exists.\n      ValueError: if the Windows Registry key cannot be added."
  },
  {
    "code": "def stack_plot(self, *args, **kwargs):\n        df = self.as_pandas(with_metadata=True)\n        ax = plotting.stack_plot(df, *args, **kwargs)\n        return ax",
    "docstring": "Plot timeseries stacks of existing data\n\n        see pyam.plotting.stack_plot() for all available options"
  },
  {
    "code": "def AUC_analysis(AUC):\n    try:\n        if AUC == \"None\":\n            return \"None\"\n        if AUC < 0.6:\n            return \"Poor\"\n        if AUC >= 0.6 and AUC < 0.7:\n            return \"Fair\"\n        if AUC >= 0.7 and AUC < 0.8:\n            return \"Good\"\n        if AUC >= 0.8 and AUC < 0.9:\n            return \"Very Good\"\n        return \"Excellent\"\n    except Exception:\n        return \"None\"",
    "docstring": "Analysis AUC with interpretation table.\n\n    :param AUC: area under the ROC curve\n    :type AUC : float\n    :return: interpretation result as str"
  },
  {
    "code": "def normpath(path):\n    scheme, netloc, path_ = parse(path)\n    return unparse(scheme, netloc, os.path.normpath(path_))",
    "docstring": "Normalize ``path``, collapsing redundant separators and up-level refs."
  },
  {
    "code": "def get_program_args(self):\n    ret = []\n    for arg in self.get_options().program_args:\n      ret.extend(safe_shlex_split(arg))\n    return ret",
    "docstring": "Get the program args to run this JVM with.\n\n    These are the arguments passed to main() and are program-specific."
  },
  {
    "code": "def _iter_bitmasks(eid):\n    bitmask = idaapi.get_first_bmask(eid)\n    yield bitmask\n    while bitmask != DEFMASK:\n        bitmask = idaapi.get_next_bmask(eid, bitmask)\n        yield bitmask",
    "docstring": "Iterate all bitmasks in a given enum.\n\n    Note that while `DEFMASK` indicates no-more-bitmasks, it is also a\n    valid bitmask value. The only way to tell if it exists is when iterating\n    the serials."
  },
  {
    "code": "def verify_module(self, filename, module, verify_signature):\n        with open(filename, 'rb') as f:\n            module_data = f.read()\n        self.verify_checksum(module_data, module['checksum'],\n                             module['location'])\n        if self.gpg_verify:\n            signature_url = \"{0}/{1}\".format(self.url, module['signature'])\n            file_url = \"{0}/{1}\".format(self.url, module['location'])\n            self.verify_file_signature(signature_url, file_url, filename)",
    "docstring": "Verify kernel module checksum and signature\n\n        :type filename: str\n        :param filename: downloaded kernel module path\n        :type module: dict\n        :param module: kernel module metadata\n        :type verify_signature: bool\n        :param verify_signature: enable/disable signature verification"
  },
  {
    "code": "def get_highlights(self, user: Union[int, Profile]) -> Iterator[Highlight]:\n        userid = user if isinstance(user, int) else user.userid\n        data = self.context.graphql_query(\"7c16654f22c819fb63d1183034a5162f\",\n                                          {\"user_id\": userid, \"include_chaining\": False, \"include_reel\": False,\n                                           \"include_suggested_users\": False, \"include_logged_out_extras\": False,\n                                           \"include_highlight_reels\": True})[\"data\"][\"user\"]['edge_highlight_reels']\n        if data is None:\n            raise BadResponseException('Bad highlights reel JSON.')\n        yield from (Highlight(self.context, edge['node'], user if isinstance(user, Profile) else None)\n                    for edge in data['edges'])",
    "docstring": "Get all highlights from a user.\n        To use this, one needs to be logged in.\n\n        .. versionadded:: 4.1\n\n        :param user: ID or Profile of the user whose highlights should get fetched."
  },
  {
    "code": "def __get_indexer(in_fns, selected_type=None):\n  indexer = None\n  if selected_type is not None:\n    indexer = get_indexer_by_filetype(selected_type)\n  else:\n    if len(in_fns) == 0:\n      raise IndexError(\"reading from stdin, unable to guess input file \" +\n                       \"type, use -t option to set manually.\\n\")\n    else:\n      extension = set([os.path.splitext(f)[1] for f in in_fns])\n      assert(len(extension) >= 1)\n      if len(extension) > 1:\n        raise IndexError(\"more than one file extension present, unable \" +\n                         \"to get input type, use -t option to set manually.\\n\")\n      else:\n        indexer = get_indexer_by_file_extension(list(extension)[0])\n  assert(indexer is not None)\n  return indexer",
    "docstring": "Determine which indexer to use based on input files and type option."
  },
  {
    "code": "def forum_topic_list(self, title_matches=None, title=None,\n                         category_id=None):\n        params = {\n            'search[title_matches]': title_matches,\n            'search[title]': title,\n            'search[category_id]': category_id\n            }\n        return self._get('forum_topics.json', params)",
    "docstring": "Function to get forum topics.\n\n        Parameters:\n            title_matches (str): Search body for the given terms.\n            title (str): Exact title match.\n            category_id (int): Can be: 0, 1, 2 (General, Tags, Bugs & Features\n                               respectively)."
  },
  {
    "code": "def parse_time_step(time_step, target='s', units_ref=None):\n    log.info(\"Parsing time step %s\", time_step)\n    value = re.findall(r'\\d+', time_step)[0]\n    valuelen = len(value)\n    try:\n        value = float(value)\n    except:\n        HydraPluginError(\"Unable to extract number of time steps (%s) from time step %s\" % (value, time_step))\n    unit = time_step[valuelen:].strip()\n    period = get_time_period(unit)\n    log.info(\"Time period is %s\", period)\n    converted_time_step = units_ref.convert(value, period, target)\n    log.info(\"Time period is %s %s\", converted_time_step, period)\n    return float(converted_time_step), value, period",
    "docstring": "Read in the time step and convert it to seconds."
  },
  {
    "code": "def is_file_url(url):\n    from .misc import to_text\n    if not url:\n        return False\n    if not isinstance(url, six.string_types):\n        try:\n            url = getattr(url, \"url\")\n        except AttributeError:\n            raise ValueError(\"Cannot parse url from unknown type: {0!r}\".format(url))\n    url = to_text(url, encoding=\"utf-8\")\n    return urllib_parse.urlparse(url.lower()).scheme == \"file\"",
    "docstring": "Returns true if the given url is a file url"
  },
  {
    "code": "def setup_logging(verbosity, formats=None):\n    if formats is None:\n        formats = {}\n    log_level = logging.INFO\n    log_format = formats.get(\"info\", INFO_FORMAT)\n    if sys.stdout.isatty():\n        log_format = formats.get(\"color\", COLOR_FORMAT)\n    if verbosity > 0:\n        log_level = logging.DEBUG\n        log_format = formats.get(\"debug\", DEBUG_FORMAT)\n    if verbosity < 2:\n        logging.getLogger(\"botocore\").setLevel(logging.CRITICAL)\n    hdlr = logging.StreamHandler()\n    hdlr.setFormatter(ColorFormatter(log_format, ISO_8601))\n    logging.root.addHandler(hdlr)\n    logging.root.setLevel(log_level)",
    "docstring": "Configure a proper logger based on verbosity and optional log formats.\n\n    Args:\n        verbosity (int): 0, 1, 2\n        formats (dict): Optional, looks for `info`, `color`, and `debug` keys\n                        which may override the associated default log formats."
  },
  {
    "code": "def run_step(context):\n    logger.debug(\"started\")\n    format_expression = context.get('nowUtcIn', None)\n    if format_expression:\n        formatted_expression = context.get_formatted_string(format_expression)\n        context['nowUtc'] = datetime.now(\n            timezone.utc).strftime(formatted_expression)\n    else:\n        context['nowUtc'] = datetime.now(timezone.utc).isoformat()\n    logger.info(f\"timestamp {context['nowUtc']} saved to context nowUtc\")\n    logger.debug(\"done\")",
    "docstring": "pypyr step saves current utc datetime to context.\n\n    Args:\n        context: pypyr.context.Context. Mandatory.\n                 The following context key is optional:\n                - nowUtcIn. str. Datetime formatting expression. For full list\n                  of possible expressions, check here:\n                  https://docs.python.org/3.7/library/datetime.html#strftime-and-strptime-behavior\n\n    All inputs support pypyr formatting expressions.\n\n    This step creates now in context, containing a string representation of the\n    timestamp. If input formatting not specified, defaults to ISO8601.\n\n    Default is:\n    YYYY-MM-DDTHH:MM:SS.ffffff+00:00, or, if microsecond is 0,\n    YYYY-MM-DDTHH:MM:SS\n\n    Returns:\n        None. updates context arg."
  },
  {
    "code": "def encrypt_file(self,\n                     path,\n                     output_path=None,\n                     overwrite=False,\n                     enable_verbose=True):\n        path, output_path = files.process_dst_overwrite_args(\n            src=path, dst=output_path, overwrite=overwrite,\n            src_to_dst_func=files.get_encrpyted_path,\n        )\n        with open(path, \"rb\") as infile, open(output_path, \"wb\") as outfile:\n            encrypt_bigfile(infile, outfile, self.his_pubkey)",
    "docstring": "Encrypt a file using rsa.\n\n        RSA for big file encryption is very slow. For big file, I recommend\n        to use symmetric encryption and use RSA to encrypt the password."
  },
  {
    "code": "def get_all_preordered_namespace_hashes( self ):\n        cur = self.db.cursor()\n        namespace_hashes = namedb_get_all_preordered_namespace_hashes( cur, self.lastblock )\n        return namespace_hashes",
    "docstring": "Get all oustanding namespace preorder hashes that have not expired.\n        Used for testing"
  },
  {
    "code": "def set_asset_dir(self):\n        log = logging.getLogger(self.cls_logger + '.get_asset_dir')\n        try:\n            self.asset_dir = os.environ['ASSET_DIR']\n        except KeyError:\n            log.warn('Environment variable ASSET_DIR is not set!')\n        else:\n            log.info('Found environment variable ASSET_DIR: {a}'.format(a=self.asset_dir))",
    "docstring": "Returns the ASSET_DIR environment variable\n\n        This method gets the ASSET_DIR environment variable for the\n        current asset install. It returns either the string value if\n        set or None if it is not set.\n\n        :return: None"
  },
  {
    "code": "def remove_column(conn, table, column_name, schema=None):\n    activity_table = get_activity_table(schema=schema)\n    remove = sa.cast(column_name, sa.Text)\n    query = (\n        activity_table\n        .update()\n        .values(\n            old_data=activity_table.c.old_data - remove,\n            changed_data=activity_table.c.changed_data - remove,\n        )\n        .where(activity_table.c.table_name == table)\n    )\n    return conn.execute(query)",
    "docstring": "Removes given `activity` jsonb data column key. This function is useful\n    when you are doing schema changes that require removing a column.\n\n    Let's say you've been using PostgreSQL-Audit for a while for a table called\n    article. Now you want to remove one audited column called 'created_at' from\n    this table.\n\n    ::\n\n        from alembic import op\n        from postgresql_audit import remove_column\n\n\n        def upgrade():\n            op.remove_column('article', 'created_at')\n            remove_column(op, 'article', 'created_at')\n\n\n    :param conn:\n        An object that is able to execute SQL (either SQLAlchemy Connection,\n        Engine or Alembic Operations object)\n    :param table:\n        The table to remove the column from\n    :param column_name:\n        Name of the column to remove\n    :param schema:\n        Optional name of schema to use."
  },
  {
    "code": "def export(self, timestamp=None):\n        if self._timestamp is None:\n            raise Exception(\"No timestamp set. Has the archive been initialized?\")\n        if self.skip_notebook_export:\n            super(NotebookArchive, self).export(timestamp=self._timestamp,\n                                                info={'notebook':self.notebook_name})\n            return\n        self.export_success = None\n        name = self.get_namespace()\n        capture_cmd = ((r\"var capture = '%s._notebook_data=r\\\"\\\"\\\"'\" % name)\n                       + r\"+json_string+'\\\"\\\"\\\"'; \")\n        cmd = (r'var kernel = IPython.notebook.kernel; '\n               + r'var json_data = IPython.notebook.toJSON(); '\n               + r'var json_string = JSON.stringify(json_data); '\n               + capture_cmd\n               + \"var pycmd = capture + ';%s._export_with_html()'; \" % name\n               + r\"kernel.execute(pycmd)\")\n        tstamp = time.strftime(self.timestamp_format, self._timestamp)\n        export_name = self._format(self.export_name, {'timestamp':tstamp, 'notebook':self.notebook_name})\n        print(('Export name: %r\\nDirectory    %r' % (export_name,\n                                                     os.path.join(os.path.abspath(self.root))))\n               + '\\n\\nIf no output appears, please check holoviews.archive.last_export_status()')\n        display(Javascript(cmd))",
    "docstring": "Get the current notebook data and export."
  },
  {
    "code": "def get_scheme_dirs():\n    scheme_glob = rel_to_cwd('schemes', '**', '*.yaml')\n    scheme_groups = glob(scheme_glob)\n    scheme_groups = [get_parent_dir(path) for path in scheme_groups]\n    return set(scheme_groups)",
    "docstring": "Return a set of all scheme directories."
  },
  {
    "code": "def walk(cls, top=\".\", ext=\".abo\"):\n        paths = []\n        for root, dirs, files in os.walk(top):\n            for f in files:\n                if f.endswith(ext):\n                    paths.append(os.path.join(root, f))\n        parser = cls()\n        okfiles = parser.parse(paths)\n        return parser, paths, okfiles",
    "docstring": "Scan directory tree starting from top, look for files with extension `ext` and\n        parse timing data.\n\n        Return: (parser, paths, okfiles)\n            where `parser` is the new object, `paths` is the list of files found and `okfiles`\n            is the list of files that have been parsed successfully.\n            (okfiles == paths) if all files have been parsed."
  },
  {
    "code": "def _as_log_entry(self, name, now):\n        d = {\n            u'http_response_code': self.response_code,\n            u'timestamp': time.mktime(now.timetuple())\n        }\n        severity = _SEVERITY.INFO\n        if self.response_code >= 400:\n            severity = _SEVERITY.ERROR\n            d[u'error_cause'] = self.error_cause.name\n        if self.request_size > 0:\n            d[u'request_size'] = self.request_size\n        if self.response_size > 0:\n            d[u'response_size'] = self.response_size\n        if self.method:\n            d[u'http_method'] = self.method\n        if self.request_time:\n            d[u'request_latency_in_ms'] = self.request_time.total_seconds() * 1000\n        for key in self.COPYABLE_LOG_FIELDS:\n            value = getattr(self, key, None)\n            if value:\n                d[key] = value\n        return sc_messages.LogEntry(\n            name=name,\n            timestamp=timestamp.to_rfc3339(now),\n            severity=severity,\n            structPayload=_struct_payload_from(d))",
    "docstring": "Makes a `LogEntry` from this instance for the given log_name.\n\n        Args:\n          rules (:class:`ReportingRules`): determines what labels, metrics and\n            logs to include in the report request.\n          now (:class:`datetime.DateTime`): the current time\n\n        Return:\n          a ``LogEntry`` generated from this instance with the given name\n          and timestamp\n\n        Raises:\n          ValueError: if the fields in this instance are insufficient to\n            to create a valid ``ServicecontrolServicesReportRequest``"
  },
  {
    "code": "def wrap_embedded_keyvalue(self, data):\n        if data is not None:\n            try:\n                data = u'{}'.format(data)\n            except UnicodeEncodeError:\n                pass\n            variables = []\n            for v in re.finditer(self._vars_keyvalue_embedded, data):\n                variables.append(v.group(0))\n            for var in set(variables):\n                variable_string = re.search(self._variable_parse, var).group(0)\n                data = data.replace(var, '\": \"{}\"'.format(variable_string))\n        return data",
    "docstring": "Wrap keyvalue embedded variable in double quotes.\n\n        Args:\n            data (string): The data with embedded variables.\n\n        Returns:\n            (string): Results retrieved from DB"
  },
  {
    "code": "def get_query_with_new_limit(self, new_limit):\n        if not self._limit:\n            return self.sql + ' LIMIT ' + str(new_limit)\n        limit_pos = None\n        tokens = self._parsed[0].tokens\n        for pos, item in enumerate(tokens):\n            if item.ttype in Keyword and item.value.lower() == 'limit':\n                limit_pos = pos\n                break\n        limit = tokens[limit_pos + 2]\n        if limit.ttype == sqlparse.tokens.Literal.Number.Integer:\n            tokens[limit_pos + 2].value = new_limit\n        elif limit.is_group:\n            tokens[limit_pos + 2].value = (\n                '{}, {}'.format(next(limit.get_identifiers()), new_limit)\n            )\n        str_res = ''\n        for i in tokens:\n            str_res += str(i.value)\n        return str_res",
    "docstring": "returns the query with the specified limit"
  },
  {
    "code": "def items(self):\n        if hasattr(self, '_items'):\n            return self.filter_items(self._items)\n        self._items = self.get_items()\n        return self.filter_items(self._items)",
    "docstring": "access for filtered items"
  },
  {
    "code": "def replace_coord(self, i):\n        da = next(islice(self.data_iterator, i, i+1))\n        name, coord = self.get_alternative_coord(da, i)\n        other_coords = {key: da.coords[key]\n                        for key in set(da.coords).difference(da.dims)}\n        ret = da.rename({da.dims[-1]: name}).assign_coords(\n            **{name: coord}).assign_coords(**other_coords)\n        return ret",
    "docstring": "Replace the coordinate for the data array at the given position\n\n        Parameters\n        ----------\n        i: int\n            The number of the data array in the raw data (if the raw data is\n            not an interactive list, use 0)\n\n        Returns\n        xarray.DataArray\n            The data array with the replaced coordinate"
  },
  {
    "code": "def _error_result_to_exception(error_result):\n    reason = error_result.get(\"reason\")\n    status_code = _ERROR_REASON_TO_EXCEPTION.get(\n        reason, http_client.INTERNAL_SERVER_ERROR\n    )\n    return exceptions.from_http_status(\n        status_code, error_result.get(\"message\", \"\"), errors=[error_result]\n    )",
    "docstring": "Maps BigQuery error reasons to an exception.\n\n    The reasons and their matching HTTP status codes are documented on\n    the `troubleshooting errors`_ page.\n\n    .. _troubleshooting errors: https://cloud.google.com/bigquery\\\n        /troubleshooting-errors\n\n    :type error_result: Mapping[str, str]\n    :param error_result: The error result from BigQuery.\n\n    :rtype google.cloud.exceptions.GoogleCloudError:\n    :returns: The mapped exception."
  },
  {
    "code": "def install(self):\n        super(SystemD, self).install()\n        self.deploy_service_file(self.svc_file_path, self.svc_file_dest)\n        self.deploy_service_file(self.env_file_path, self.env_file_dest)\n        sh.systemctl.enable(self.name)\n        sh.systemctl('daemon-reload')",
    "docstring": "Install the service on the local machine\n\n        This is where we deploy the service files to their relevant\n        locations and perform any other required actions to configure\n        the service and make it ready to be `start`ed."
  },
  {
    "code": "def reset(self):\n        shutil.copy2(self.config_file + \".orig\", self.config_file)\n        if filecmp.cmp(self.config_file + \".orig\", self.config_file):\n            print(\"{0}The reset was done{1}\".format(\n                self.meta.color[\"GREEN\"], self.meta.color[\"ENDC\"]))\n        else:\n            print(\"{0}Reset failed{1}\".format(self.meta.color[\"RED\"],\n                                              self.meta.color[\"ENDC\"]))",
    "docstring": "Reset slpkg.conf file with default values"
  },
  {
    "code": "def xmlrpc_reschedule(self):\n        if not len(self.scheduled_tasks) == 0:\n            self.reschedule = list(self.scheduled_tasks.items())\n            self.scheduled_tasks = {}\n        return True",
    "docstring": "Reschedule all running tasks."
  },
  {
    "code": "def transport_jabsorbrpc(self):\n        self.context.install_bundle(\n            \"pelix.remote.transport.jabsorb_rpc\"\n        ).start()\n        with use_waiting_list(self.context) as ipopo:\n            ipopo.add(\n                rs.FACTORY_TRANSPORT_JABSORBRPC_EXPORTER,\n                \"pelix-jabsorbrpc-exporter\",\n            )\n            ipopo.add(\n                rs.FACTORY_TRANSPORT_JABSORBRPC_IMPORTER,\n                \"pelix-jabsorbrpc-importer\",\n            )",
    "docstring": "Installs the JABSORB-RPC transport bundles and instantiates components"
  },
  {
    "code": "def get(self):\n        frac, whole = modf(self.size * self.percent / 100.0)\n        ret = curses_bars[8] * int(whole)\n        if frac > 0:\n            ret += curses_bars[int(frac * 8)]\n            whole += 1\n        ret += self.__empty_char * int(self.size - whole)\n        if self.__with_text:\n            ret = '{}{:5.1f}%'.format(ret, self.percent)\n        return ret",
    "docstring": "Return the bars."
  },
  {
    "code": "def keys(self, name_start, name_end, limit=10):\n        limit = get_positive_integer('limit', limit)\n        return self.execute_command('keys', name_start, name_end, limit)",
    "docstring": "Return a list of the top ``limit`` keys between ``name_start`` and\n        ``name_end``\n\n        Similiar with **Redis.KEYS**        \n\n        .. note:: The range is (``name_start``, ``name_end``]. ``name_start``\n           isn't in the range, but ``name_end`` is.\n\n        :param string name_start: The lower bound(not included) of keys to be\n         returned, empty string ``''`` means -inf\n        :param string name_end: The upper bound(included) of keys to be\n         returned, empty string ``''`` means +inf\n        :param int limit: number of elements will be returned.\n        :return: a list of keys\n        :rtype: list\n        \n        >>> ssdb.keys('set_x1', 'set_x3', 10)\n        ['set_x2', 'set_x3']\n        >>> ssdb.keys('set_x ', 'set_xx', 3)\n        ['set_x1', 'set_x2', 'set_x3']\n        >>> ssdb.keys('set_x ', '', 3)\n        ['set_x1', 'set_x2', 'set_x3', 'set_x4']\n        >>> ssdb.keys('set_zzzzz ', '', )\n        []"
  },
  {
    "code": "def items_to_extract(self, offset=0, length=None):\n        endoffset = length and offset + length\n        qs = self.origin_data()[offset:endoffset]\n        self.items_to_extract_length = qs.count()\n        return qs",
    "docstring": "Return an iterable of specific items to extract.\n        As a side-effect, set self.items_to_extract_length.\n\n        :param offset: where to start extracting\n        :param length: how many to extract\n        :return: An iterable of the specific"
  },
  {
    "code": "def createCleanup(self, varBind, **context):\n        name, val = varBind\n        (debug.logger & debug.FLAG_INS and\n         debug.logger('%s: createCleanup(%s, %r)' % (self, name, val)))\n        instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})\n        idx = context['idx']\n        self.branchVersionId += 1\n        instances[self.ST_CREATE].pop(-idx - 1, None)\n        self._vars[name].writeCleanup(varBind, **context)",
    "docstring": "Finalize Managed Object Instance creation.\n\n        Implements the successful third step of the multi-step workflow similar to\n        the SNMP SET command processing (:RFC:`1905#section-4.2.5`).\n\n        The goal of the third (successful) phase is to seal the new Managed Object\n        Instance. Once the system transitions into the *cleanup* state, no roll back\n        to the previous Managed Object Instance state is possible.\n\n        The role of this object in the MIB tree is non-terminal. It does not\n        access the actual Managed Object Instance, but just traverses one level\n        down the MIB tree and hands off the query to the underlying objects.\n\n        Parameters\n        ----------\n        varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing\n            new Managed Object Instance value to create\n\n        Other Parameters\n        ----------------\n        \\*\\*context:\n\n            Query parameters:\n\n            * `cbFun` (callable) - user-supplied callable that is invoked to\n              pass the new value of the Managed Object Instance or an error.\n\n            * `instances` (dict): user-supplied dict for temporarily holding\n              Managed Objects Instances being created.\n\n        Notes\n        -----\n        The callback functions (e.g. `cbFun`) have the same signature as this\n        method where `varBind` contains the new Managed Object Instance value.\n\n        In case of an error, the `error` key in the `context` dict will contain\n        an exception object."
  },
  {
    "code": "def move_camera(action, action_space, minimap):\n  minimap.assign_to(spatial(action, action_space).camera_move.center_minimap)",
    "docstring": "Move the camera."
  },
  {
    "code": "def check_ttl_max_tries(tries, enqueued_at, max_tries, ttl):\n    if max_tries > 0 and tries >= max_tries:\n        raise FSQMaxTriesError(errno.EINTR, u'Max tries exceded:'\\\n                               u' {0} ({1})'.format(max_tries, tries))\n    if ttl > 0 and datetime.datetime.now() < enqueued_at + datetime.timedelta(\n            seconds=ttl):\n        raise FSQTTLExpiredError(errno.EINTR, u'TTL Expired:'\\\n                                 u' {0}'.format(ttl))",
    "docstring": "Check that the ttl for an item has not expired, and that the item has\n       not exceeded it's maximum allotted tries"
  },
  {
    "code": "def _build_toctree_node(parent=None, entries=None, includefiles=None,\n                        caption=None):\n    subnode = sphinx.addnodes.toctree()\n    subnode['parent'] = parent\n    subnode['entries'] = entries\n    subnode['includefiles'] = includefiles\n    subnode['caption'] = caption\n    subnode['maxdepth'] = 1\n    subnode['hidden'] = False\n    subnode['glob'] = None\n    subnode['hidden'] = False\n    subnode['includehidden'] = False\n    subnode['numbered'] = 0\n    subnode['titlesonly'] = False\n    return subnode",
    "docstring": "Factory for a toctree node."
  },
  {
    "code": "def create(graph, kmin=0, kmax=10, verbose=True):\n    from turicreate._cython.cy_server import QuietProgress\n    if not isinstance(graph, _SGraph):\n        raise TypeError('graph input must be a SGraph object.')\n    opts = {'graph': graph.__proxy__, 'kmin': kmin, 'kmax': kmax}\n    with QuietProgress(verbose):\n        params = _tc.extensions._toolkits.graph.kcore.create(opts)\n    return KcoreModel(params['model'])",
    "docstring": "Compute the K-core decomposition of the graph. Return a model object with\n    total number of cores as well as the core id for each vertex in the graph.\n\n    Parameters\n    ----------\n    graph : SGraph\n        The graph on which to compute the k-core decomposition.\n\n    kmin : int, optional\n        Minimum core id. Vertices having smaller core id than `kmin` will be\n        assigned with core_id = `kmin`.\n\n    kmax : int, optional\n        Maximum core id. Vertices having larger core id than `kmax` will be\n        assigned with core_id=`kmax`.\n\n    verbose : bool, optional\n        If True, print progress updates.\n\n    Returns\n    -------\n    out : KcoreModel\n\n    References\n    ----------\n    - Alvarez-Hamelin, J.I., et al. (2005) `K-Core Decomposition: A Tool for the\n      Visualization of Large Networks <http://arxiv.org/abs/cs/0504107>`_.\n\n    Examples\n    --------\n    If given an :class:`~turicreate.SGraph` ``g``, we can create\n    a :class:`~turicreate.kcore.KcoreModel` as follows:\n\n    >>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/email-Enron.txt.gz', format='snap')\n    >>> kc = turicreate.kcore.create(g)\n\n    We can obtain the ``core id`` corresponding to each vertex in the graph\n    ``g`` using:\n\n    >>> kcore_id = kc['core_id']     # SFrame\n\n    We can add the new core id field to the original graph g using:\n\n    >>> g.vertices['core_id'] = kc['graph'].vertices['core_id']\n\n    Note that the task above does not require a join because the vertex\n    ordering is preserved through ``create()``.\n\n    See Also\n    --------\n    KcoreModel"
  },
  {
    "code": "def latex_name(self):\n        star = ('*' if self._star_latex_name else '')\n        if self._latex_name is not None:\n            return self._latex_name + star\n        return self.__class__.__name__.lower() + star",
    "docstring": "Return the name of the class used in LaTeX.\n\n        It can be `None` when the class doesn't have a name."
  },
  {
    "code": "def subscribe(self, *, create_task=True, **params):\n        if create_task and not self.task:\n            self.task = asyncio.ensure_future(self.run(**params))\n        return self.channel.subscribe()",
    "docstring": "Subscribes to the Docker events channel. Use the keyword argument\n        create_task=False to prevent automatically spawning the background\n        tasks that listen to the events.\n\n        This function returns a ChannelSubscriber object."
  },
  {
    "code": "def is_working_day(self, day,\n                       extra_working_days=None, extra_holidays=None):\n        day = cleaned_date(day)\n        if extra_working_days:\n            extra_working_days = tuple(map(cleaned_date, extra_working_days))\n        if extra_holidays:\n            extra_holidays = tuple(map(cleaned_date, extra_holidays))\n        if extra_working_days and day in extra_working_days:\n            return True\n        if day.weekday() in self.get_weekend_days():\n            return False\n        return not self.is_holiday(day, extra_holidays=extra_holidays)",
    "docstring": "Return True if it's a working day.\n        In addition to the regular holidays, you can add exceptions.\n\n        By providing ``extra_working_days``, you'll state that these dates\n        **are** working days.\n\n        By providing ``extra_holidays``, you'll state that these dates **are**\n        holidays, even if not in the regular calendar holidays (or weekends).\n\n        Please note that the ``extra_working_days`` list has priority over the\n        ``extra_holidays`` list."
  },
  {
    "code": "def import_tf_tensor(self, x, tf_x):\n    return self.LaidOutTensor(self.make_slices(tf_x, x.shape))",
    "docstring": "Import a tf.Tensor, producing a LaidOutTensor.\n\n    Args:\n      x: a Tensor\n      tf_x: a tf.Tensor\n    Returns:\n      a LaidOutTensor"
  },
  {
    "code": "def to_string(self, other):\n        arg = \"%s/%s,%s\" % (\n                self.ttl, self.get_remaining_ttl(current_time_millis()), other)\n        return DNSEntry.to_string(self, \"record\", arg)",
    "docstring": "String representation with addtional information"
  },
  {
    "code": "def _terms(self):\n        res = []\n        for sign, terms in self.terms.items():\n            for ID, lon in terms.items():\n                res.append(self.T(ID, sign))\n        return res",
    "docstring": "Returns a list with the objects as terms."
  },
  {
    "code": "def merge_parts(self, version_id=None, **kwargs):\n        self.file.update_checksum(**kwargs)\n        with db.session.begin_nested():\n            obj = ObjectVersion.create(\n                self.bucket,\n                self.key,\n                _file_id=self.file_id,\n                version_id=version_id\n            )\n            self.delete()\n        return obj",
    "docstring": "Merge parts into object version."
  },
  {
    "code": "def parse_type_signature(sig):\n    match = TYPE_SIG_RE.match(sig.strip())\n    if not match:\n        raise RuntimeError('Type signature invalid, got ' + sig)\n    groups = match.groups()\n    typ = groups[0]\n    generic_types = groups[1]\n    if not generic_types:\n        generic_types = []\n    else:\n        generic_types = split_sig(generic_types[1:-1])\n    is_array = (groups[2] is not None)\n    return typ, generic_types, is_array",
    "docstring": "Parse a type signature"
  },
  {
    "code": "def vbd_list(name=None, call=None):\n    if call == 'function':\n        raise SaltCloudSystemExit(\n            'This function must be called with -a, --action argument.'\n        )\n    if name is None:\n        return 'A name kwarg is rquired'\n    ret = {}\n    data = {}\n    session = _get_session()\n    vms = session.xenapi.VM.get_by_name_label(name)\n    if len(vms) == 1:\n        vm = vms[0]\n        vbds = session.xenapi.VM.get_VBDs(vm)\n        if vbds is not None:\n            x = 0\n            for vbd in vbds:\n                vbd_record = session.xenapi.VBD.get_record(vbd)\n                data['vbd-{}'.format(x)] = vbd_record\n                x += 1\n    ret = data\n    return ret",
    "docstring": "Get a list of VBDs on a VM\n\n    **requires**: the name of the vm with the vbd definition\n\n    .. code-block:: bash\n\n        salt-cloud -a vbd_list xenvm01"
  },
  {
    "code": "def apply_formatting_dict(obj: Any, formatting: Dict[str, Any]) -> Any:\n    new_obj = obj\n    if isinstance(obj, str):\n        if \"$\" not in obj:\n            new_obj = string.Formatter().vformat(obj, (), formatting_dict(**formatting))\n    elif isinstance(obj, dict):\n        new_obj = {}\n        for k, v in obj.items():\n            new_obj[k] = apply_formatting_dict(v, formatting)\n    elif isinstance(obj, list):\n        new_obj = []\n        for i, el in enumerate(obj):\n            new_obj.append(apply_formatting_dict(el, formatting))\n    elif isinstance(obj, int) or isinstance(obj, float) or obj is None:\n        pass\n    elif isinstance(obj, enum.Enum):\n        pass\n    else:\n        logger.debug(f\"Unrecognized obj '{obj}' of type '{type(obj)}'\")\n    return new_obj",
    "docstring": "Recursively apply a formatting dict to all strings in a configuration.\n\n    Note that it skips applying the formatting if the string appears to contain latex (specifically,\n    if it contains an \"$\"), since the formatting fails on nested brackets.\n\n    Args:\n        obj: Some configuration object to recursively applying the formatting to.\n        formatting (dict): String formatting options to apply to each configuration field.\n    Returns:\n        dict: Configuration with formatting applied to every field."
  },
  {
    "code": "def add_head(self, head):\n        if not isinstance(head, DependencyNode):\n            raise TypeError('\"head\" must be a DependencyNode')\n        self._heads.append(head)",
    "docstring": "Add head Node"
  },
  {
    "code": "def add_method(info, target_cls, virtual=False, dont_replace=False):\n    name = escape_identifier(info.name)\n    if virtual:\n        name = \"do_\" + name\n        attr = VirtualMethodAttribute(info, target_cls, name)\n    else:\n        attr = MethodAttribute(info, target_cls, name)\n    if dont_replace and hasattr(target_cls, name):\n        return\n    setattr(target_cls, name, attr)",
    "docstring": "Add a method to the target class"
  },
  {
    "code": "def set_(filename, section, parameter, value):\n    filename = _quote(filename)\n    section = _quote(section)\n    parameter = _quote(parameter)\n    value = _quote(six.text_type(value))\n    result = __salt__['cmd.run_all'](\n            'openstack-config --set {0} {1} {2} {3}'.format(\n                filename, section, parameter, value\n                ),\n            python_shell=False,\n            )\n    if result['retcode'] == 0:\n        return result['stdout']\n    else:\n        raise salt.exceptions.CommandExecutionError(result['stderr'])",
    "docstring": "Set a value in an OpenStack configuration file.\n\n    filename\n        The full path to the configuration file\n\n    section\n        The section in which the parameter will be set\n\n    parameter\n        The parameter to change\n\n    value\n        The value to set\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-call openstack_config.set /etc/keystone/keystone.conf sql connection foo"
  },
  {
    "code": "def boltzmann_exploration(actions, utilities, temperature, action_counter):\n    utilities = [utilities[x] for x in actions]\n    temperature = max(temperature, 0.01)\n    _max = max(utilities)\n    _min = min(utilities)\n    if _max == _min:\n        return random.choice(actions)\n    utilities = [math.exp(((u - _min) / (_max - _min)) / temperature) for u in utilities]\n    probs = [u / sum(utilities) for u in utilities]\n    i = 0\n    tot = probs[i]\n    r = random.random()\n    while i < len(actions) and r >= tot:\n        i += 1\n        tot += probs[i]\n    return actions[i]",
    "docstring": "returns an action with a probability depending on utilities and temperature"
  },
  {
    "code": "def green_callback(fn, obj=None, green_mode=None):\n    executor = get_object_executor(obj, green_mode)\n    @wraps(fn)\n    def greener(*args, **kwargs):\n        return executor.submit(fn, *args, **kwargs)\n    return greener",
    "docstring": "Return a green verion of the given callback."
  },
  {
    "code": "def clear_subsystem_caches(subsys):\n    try:\n        subsys._repertoire_cache.clear()\n        subsys._mice_cache.clear()\n    except TypeError:\n        try:\n            subsys._repertoire_cache.cache = {}\n            subsys._mice_cache.cache = {}\n        except AttributeError:\n            subsys._repertoire_cache = {}\n            subsys._repertoire_cache_info = [0, 0]\n            subsys._mice_cache = {}",
    "docstring": "Clear subsystem caches"
  },
  {
    "code": "def dev_from_name(self, name):\n        try:\n            return next(iface for iface in six.itervalues(self)\n                        if (iface.name == name or iface.description == name))\n        except (StopIteration, RuntimeError):\n            raise ValueError(\"Unknown network interface %r\" % name)",
    "docstring": "Return the first pcap device name for a given Windows\n        device name."
  },
  {
    "code": "def get_evernote_client(self, token=None):\n        if token:\n            return EvernoteClient(token=token, sandbox=self.sandbox)\n        else:\n            return EvernoteClient(consumer_key=self.consumer_key, consumer_secret=self.consumer_secret,\n                                  sandbox=self.sandbox)",
    "docstring": "get the token from evernote"
  },
  {
    "code": "def new_revoke_public_key_transaction(self, ont_id: str, bytes_operator: bytes, revoked_pub_key: str or bytes,\n                                          b58_payer_address: str, gas_limit: int, gas_price: int):\n        if isinstance(revoked_pub_key, str):\n            bytes_revoked_pub_key = bytes.fromhex(revoked_pub_key)\n        elif isinstance(revoked_pub_key, bytes):\n            bytes_revoked_pub_key = revoked_pub_key\n        else:\n            raise SDKException(ErrorCode.params_type_error('a bytes or str type of public key is required.'))\n        bytes_ont_id = ont_id.encode('utf-8')\n        args = dict(ontid=bytes_ont_id, pk=bytes_revoked_pub_key, operator=bytes_operator)\n        tx = self.__generate_transaction('removeKey', args, b58_payer_address, gas_limit, gas_price)\n        return tx",
    "docstring": "This interface is used to generate a Transaction object which is used to remove public key.\n\n        :param ont_id: OntId.\n        :param bytes_operator: operator args in from of bytes.\n        :param revoked_pub_key: a public key string which will be removed.\n        :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction.\n        :param gas_limit: an int value that indicate the gas limit.\n        :param gas_price: an int value that indicate the gas price.\n        :return: a Transaction object which is used to remove public key."
  },
  {
    "code": "def _generate_next_token_helper(self, past_states, transitions):\n        key = tuple(past_states)\n        assert key in transitions, \"%s\" % str(key)\n        return utils.weighted_choice(transitions[key].items())",
    "docstring": "generates next token based previous states"
  },
  {
    "code": "def parse_boolean_envvar(val):\n    if not val or val.lower() in {'false', '0'}:\n        return False\n    elif val.lower() in {'true', '1'}:\n        return True\n    else:\n        raise ValueError('Invalid boolean environment variable: %s' % val)",
    "docstring": "Parse a boolean environment variable."
  },
  {
    "code": "def eval_valid(self, feval=None):\n        return [item for i in range_(1, self.__num_dataset)\n                for item in self.__inner_eval(self.name_valid_sets[i - 1], i, feval)]",
    "docstring": "Evaluate for validation data.\n\n        Parameters\n        ----------\n        feval : callable or None, optional (default=None)\n            Customized evaluation function.\n            Should accept two parameters: preds, train_data,\n            and return (eval_name, eval_result, is_higher_better) or list of such tuples.\n            For multi-class task, the preds is group by class_id first, then group by row_id.\n            If you want to get i-th row preds in j-th class, the access way is preds[j * num_data + i].\n\n        Returns\n        -------\n        result : list\n            List with evaluation results."
  },
  {
    "code": "def add_fileformat(self, fileformat):\n        self.fileformat = fileformat\n        logger.info(\"Adding fileformat to vcf: {0}\".format(fileformat))\n        return",
    "docstring": "Add fileformat line to the header.\n\n        Arguments:\n            fileformat (str): The id of the info line"
  },
  {
    "code": "def imwrite(file, data=None, shape=None, dtype=None, **kwargs):\n    tifargs = parse_kwargs(kwargs, 'append', 'bigtiff', 'byteorder', 'imagej')\n    if data is None:\n        dtype = numpy.dtype(dtype)\n        size = product(shape) * dtype.itemsize\n        byteorder = dtype.byteorder\n    else:\n        try:\n            size = data.nbytes\n            byteorder = data.dtype.byteorder\n        except Exception:\n            size = 0\n            byteorder = None\n    bigsize = kwargs.pop('bigsize', 2**32-2**25)\n    if 'bigtiff' not in tifargs and size > bigsize and not (\n            tifargs.get('imagej', False) or tifargs.get('truncate', False)):\n        tifargs['bigtiff'] = True\n    if 'byteorder' not in tifargs:\n        tifargs['byteorder'] = byteorder\n    with TiffWriter(file, **tifargs) as tif:\n        return tif.save(data, shape, dtype, **kwargs)",
    "docstring": "Write numpy array to TIFF file.\n\n    Refer to the TiffWriter class and its asarray function for documentation.\n\n    A BigTIFF file is created if the data size in bytes is larger than 4 GB\n    minus 32 MB (for metadata), and 'bigtiff' is not specified, and 'imagej'\n    or 'truncate' are not enabled.\n\n    Parameters\n    ----------\n    file : str or binary stream\n        File name or writable binary stream, such as an open file or BytesIO.\n    data : array_like\n        Input image. The last dimensions are assumed to be image depth,\n        height, width, and samples.\n        If None, an empty array of the specified shape and dtype is\n        saved to file.\n        Unless 'byteorder' is specified in 'kwargs', the TIFF file byte order\n        is determined from the data's dtype or the dtype argument.\n    shape : tuple\n        If 'data' is None, shape of an empty array to save to the file.\n    dtype : numpy.dtype\n        If 'data' is None, data-type of an empty array to save to the file.\n    kwargs : dict\n        Parameters 'append', 'byteorder', 'bigtiff', and 'imagej', are passed\n        to the TiffWriter constructor. Other parameters are passed to the\n        TiffWriter.save function.\n\n    Returns\n    -------\n    offset, bytecount : tuple or None\n        If the image data are written contiguously, return offset and bytecount\n        of image data in the file."
  },
  {
    "code": "def createOverlay(self, pchOverlayKey, pchOverlayName):\n        fn = self.function_table.createOverlay\n        pOverlayHandle = VROverlayHandle_t()\n        result = fn(pchOverlayKey, pchOverlayName, byref(pOverlayHandle))\n        return result, pOverlayHandle",
    "docstring": "Creates a new named overlay. All overlays start hidden and with default settings."
  },
  {
    "code": "def get_java_container(self, package_name=None, object_name=None, java_class_instance=None):\n        if package_name is not None:\n            jcontainer = self.import_scala_package_object(package_name)\n        elif object_name is not None:\n            jcontainer = self.import_scala_object(object_name)\n        elif java_class_instance is not None:\n            jcontainer = java_class_instance\n        else:\n            raise RuntimeError(\"Expected one of package_name, object_name or java_class_instance\")\n        return jcontainer",
    "docstring": "Convenience method to get the container that houses methods we wish to call a method on."
  },
  {
    "code": "def update(self, data):\n        self._md.update(data)\n        bufpos = self._nbytes & 63\n        self._nbytes += len(data)\n        if self._rarbug and len(data) > 64:\n            dpos = self.block_size - bufpos\n            while dpos + self.block_size <= len(data):\n                self._corrupt(data, dpos)\n                dpos += self.block_size",
    "docstring": "Process more data."
  },
  {
    "code": "def image_generator(images, labels):\n  if not images:\n    raise ValueError(\"Must provide some images for the generator.\")\n  width, height, _ = images[0].shape\n  for (enc_image, label) in zip(encode_images_as_png(images), labels):\n    yield {\n        \"image/encoded\": [enc_image],\n        \"image/format\": [\"png\"],\n        \"image/class/label\": [int(label)],\n        \"image/height\": [height],\n        \"image/width\": [width]\n    }",
    "docstring": "Generator for images that takes image and labels lists and creates pngs.\n\n  Args:\n    images: list of images given as [width x height x channels] numpy arrays.\n    labels: list of ints, same length as images.\n\n  Yields:\n    A dictionary representing the images with the following fields:\n    * image/encoded: the string encoding the image as PNG,\n    * image/format: the string \"png\" representing image format,\n    * image/class/label: an integer representing the label,\n    * image/height: an integer representing the height,\n    * image/width: an integer representing the width.\n    Every field is actually a singleton list of the corresponding type.\n\n  Raises:\n    ValueError: if images is an empty list."
  },
  {
    "code": "def create_back_links(env):\n    if env.needs_workflow['backlink_creation']:\n        return\n    needs = env.needs_all_needs\n    for key, need in needs.items():\n        for link in need[\"links\"]:\n            link_main = link.split('.')[0]\n            try:\n                link_part = link.split('.')[1]\n            except IndexError:\n                link_part = None\n            if link_main in needs:\n                if key not in needs[link_main][\"links_back\"]:\n                    needs[link_main][\"links_back\"].append(key)\n                if link_part is not None:\n                    if link_part in needs[link_main]['parts']:\n                        if 'links_back' not in needs[link_main]['parts'][link_part].keys():\n                            needs[link_main]['parts'][link_part]['links_back'] = []\n                        needs[link_main]['parts'][link_part]['links_back'].append(key)\n    env.needs_workflow['backlink_creation'] = True",
    "docstring": "Create back-links in all found needs.\n    But do this only once, as all needs are already collected and this sorting is for all\n    needs and not only for the ones of the current document.\n\n    :param env: sphinx enviroment\n    :return: None"
  },
  {
    "code": "async def eval(self, text, opts=None, user=None):\n        if user is None:\n            user = self.auth.getUserByName('root')\n        await self.boss.promote('storm', user=user, info={'query': text})\n        async with await self.snap(user=user) as snap:\n            async for node in snap.eval(text, opts=opts, user=user):\n                yield node",
    "docstring": "Evaluate a storm query and yield Nodes only."
  },
  {
    "code": "def send_message(self, message):\n        if not self.live():\n            raise IOError(\"Connection is not live.\")\n        message.add_flag(BEGIN_END_FLAG)\n        self.write(message.buffer)",
    "docstring": "Sends a message to this connection.\n\n        :param message: (Message), message to be sent to this connection."
  },
  {
    "code": "def _ParseLogonApplications(self, parser_mediator, registry_key):\n    for application in self._LOGON_APPLICATIONS:\n      command_value = registry_key.GetValueByName(application)\n      if not command_value:\n        continue\n      values_dict = {\n          'Application': application,\n          'Command': command_value.GetDataAsObject(),\n          'Trigger': 'Logon'}\n      event_data = windows_events.WindowsRegistryEventData()\n      event_data.key_path = registry_key.path\n      event_data.offset = registry_key.offset\n      event_data.regvalue = values_dict\n      event_data.source_append = ': Winlogon'\n      event = time_events.DateTimeValuesEvent(\n          registry_key.last_written_time, definitions.TIME_DESCRIPTION_WRITTEN)\n      parser_mediator.ProduceEventWithEventData(event, event_data)",
    "docstring": "Parses the registered logon applications.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      registry_key (dfwinreg.WinRegistryKey): Windows Registry key."
  },
  {
    "code": "def set_orders(self, object_pks):\n        objects_to_sort = self.filter(pk__in=object_pks)\n        max_value = self.model.objects.all().aggregate(\n            models.Max('sort_order')\n        )['sort_order__max']\n        orders = list(objects_to_sort.values_list('sort_order', flat=True))\n        if len(orders) != len(object_pks):\n            pks = set(objects_to_sort.values_list('pk', flat=True))\n            message = 'The following object_pks are not in this queryset: {}'.format(\n                [pk for pk in object_pks if pk not in pks]\n            )\n            raise TypeError(message)\n        with transaction.atomic():\n            objects_to_sort.update(sort_order=models.F('sort_order') + max_value)\n            for pk, order in zip(object_pks, orders):\n                self.filter(pk=pk).update(sort_order=order)\n        return objects_to_sort",
    "docstring": "Perform a mass update of sort_orders across the full queryset.\n        Accepts a list, object_pks, of the intended order for the objects.\n\n        Works as follows:\n        - Compile a list of all sort orders in the queryset. Leave out anything that\n          isn't in the object_pks list - this deals with pagination and any\n          inconsistencies.\n        - Get the maximum among all model object sort orders. Update the queryset to add\n          it to all the existing sort order values. This lifts them 'out of the way' of\n          unique_together clashes when setting the intended sort orders.\n        - Set the sort order on each object. Use only sort_order values that the objects\n          had before calling this method, so they get rearranged in place.\n        Performs O(n) queries."
  },
  {
    "code": "def is_boolean(node):\n    return any([\n        isinstance(node, ast.Name)\n        and node.id in ('True', 'False'),\n        hasattr(ast, 'NameConstant')\n        and isinstance(node, getattr(ast, 'NameConstant'))\n        and str(node.value) in ('True', 'False')\n    ])",
    "docstring": "Checks if node is True or False"
  },
  {
    "code": "def download_files(files):\n    for (url, file) in files:\n        print(\"Downloading %s as %s\" % (url, file))\n        data = download_url(url)\n        if data is None:\n            continue\n        try:\n            open(file, mode='wb').write(data)\n        except Exception as e:\n            print(\"Failed to save to %s : %s\" % (file, e))",
    "docstring": "download an array of files"
  },
  {
    "code": "def sky_fraction(self):\n        pix_id = self._best_res_pixels()\n        nb_pix_filled = pix_id.size\n        return nb_pix_filled / float(3 << (2*(self.max_order + 1)))",
    "docstring": "Sky fraction covered by the MOC"
  },
  {
    "code": "def get_jwt(self, request):\n        try:\n            authorization = request.authorization\n        except ValueError:\n            return None\n        if authorization is None:\n            return None\n        authtype, token = authorization\n        if authtype.lower() != self.auth_header_prefix.lower():\n            return None\n        return token",
    "docstring": "Extract the JWT token from the authorisation header of the request.\n\n        Returns the JWT token or None, if the token cannot be extracted.\n\n        :param request: request object.\n        :type request: :class:`morepath.Request`"
  },
  {
    "code": "def load_yaml(data=None, path=None, name='NT'):\n    if data and not path:\n        return mapper(yaml.load(data), _nt_name=name)\n    if path and not data:\n        with open(path, 'r') as f:\n            data = yaml.load(f)\n        return mapper(data, _nt_name=name)\n    if data and path:\n        raise ValueError('expected one source and received two')",
    "docstring": "Map namedtuples with yaml data."
  },
  {
    "code": "def is_url(value, **kwargs):\n    try:\n        value = validators.url(value, **kwargs)\n    except SyntaxError as error:\n        raise error\n    except Exception:\n        return False\n    return True",
    "docstring": "Indicate whether ``value`` is a URL.\n\n    .. note::\n\n      URL validation is...complicated. The methodology that we have\n      adopted here is *generally* compliant with\n      `RFC 1738 <https://tools.ietf.org/html/rfc1738>`_,\n      `RFC 6761 <https://tools.ietf.org/html/rfc6761>`_,\n      `RFC 2181 <https://tools.ietf.org/html/rfc2181>`_  and uses a combination of\n      string parsing and regular expressions,\n\n      This approach ensures more complete coverage for unusual edge cases, while\n      still letting us use regular expressions that perform quickly.\n\n    :param value: The value to evaluate.\n\n    :param allow_special_ips: If ``True``, will succeed when validating special IP\n      addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``,\n      will fail if ``value`` is a special IP address. Defaults to ``False``.\n    :type allow_special_ips: :class:`bool <python:bool>`\n\n    :returns: ``True`` if ``value`` is valid, ``False`` if it is not.\n    :rtype: :class:`bool <python:bool>`\n\n    :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates\n      keyword parameters passed to the underlying validator"
  },
  {
    "code": "def gammalnStirling(z):\n    return (0.5 * (np.log(2. * np.pi) - np.log(z))) \\\n           + (z * (np.log(z + (1. / ((12. * z) - (1. / (10. * z))))) - 1.))",
    "docstring": "Uses Stirling's approximation for the log-gamma function suitable for large arguments."
  },
  {
    "code": "async def send_script(self, conn_id, data):\n        adapter_id = self._get_property(conn_id, 'adapter')\n        return await self.adapters[adapter_id].send_script(conn_id, data)",
    "docstring": "Send a script to a device.\n\n        See :meth:`AbstractDeviceAdapter.send_script`."
  },
  {
    "code": "def term_to_binary(term, compressed=False):\n    data_uncompressed = _term_to_binary(term)\n    if compressed is False:\n        return b_chr(_TAG_VERSION) + data_uncompressed\n    else:\n        if compressed is True:\n            compressed = 6\n        if compressed < 0 or compressed > 9:\n            raise InputException('compressed in [0..9]')\n        data_compressed = zlib.compress(data_uncompressed, compressed)\n        size_uncompressed = len(data_uncompressed)\n        if size_uncompressed > 4294967295:\n            raise OutputException('uint32 overflow')\n        return (\n            b_chr(_TAG_VERSION) + b_chr(_TAG_COMPRESSED_ZLIB) +\n            struct.pack(b'>I', size_uncompressed) + data_compressed\n        )",
    "docstring": "Encode Python types into Erlang terms in binary data"
  },
  {
    "code": "def start(self):\n        if self._response is not None:\n            raise RuntimeError(\"command execution already started\")\n        request = aioxmpp.IQ(\n            type_=aioxmpp.IQType.SET,\n            to=self._peer_jid,\n            payload=adhoc_xso.Command(self._command_name),\n        )\n        self._response = yield from self._stream.send_iq_and_wait_for_reply(\n            request,\n        )\n        return self._response.first_payload",
    "docstring": "Initiate the session by starting to execute the command with the peer.\n\n        :return: The :attr:`~.xso.Command.first_payload` of the response\n\n        This sends an empty command IQ request with the\n        :attr:`~.ActionType.EXECUTE` action.\n\n        The :attr:`status`, :attr:`response` and related attributes get updated\n        with the newly received values."
  },
  {
    "code": "def _call_one_middleware(self, middleware):\n        args = {}\n        for arg in middleware['args']:\n            if hasattr(self, arg):\n                args[arg] = reduce(getattr, arg.split('.'), self)\n        self.logger.debug('calling middleware event {}'\n                          .format(middleware['name']))\n        middleware['call'](**args)",
    "docstring": "Evaluate arguments and execute the middleware function"
  },
  {
    "code": "def load_pickle(file, encoding=None):\n    if encoding:\n        with open(file, 'rb') as f:\n            return pickle.load(f, encoding=encoding)\n    with open(file, 'rb') as f:\n       return pickle.load(f)",
    "docstring": "Load a pickle file.\n\n    Args:\n        file (str): Path to pickle file\n\n    Returns:\n        object: Loaded object from pickle file"
  },
  {
    "code": "def positions_to_contigs(positions):\n    if isinstance(positions, np.ndarray):\n        flattened_positions = positions.flatten()\n    else:\n        try:\n            flattened_positions = np.array(\n                [pos for contig in positions for pos in contig])\n        except TypeError:\n            flattened_positions = np.array(positions)\n    if (np.diff(positions) == 0).any() and not (0 in set(positions)):\n        warnings.warn(\"I detected identical consecutive nonzero values.\")\n        return positions\n    n = len(flattened_positions)\n    contigs = np.ones(n)\n    counter = 0\n    for i in range(1, n):\n        if positions[i] == 0:\n            counter += 1\n            contigs[i] += counter\n        else:\n            contigs[i] = contigs[i - 1]\n    return contigs",
    "docstring": "Flattens and converts a positions array to a contigs array, if applicable."
  },
  {
    "code": "def remove_widget(self, widget):\n        self._grid_widgets = dict((key, val)\n                                  for (key, val) in self._grid_widgets.items()\n                                  if val[-1] != widget)\n        self._need_solver_recreate = True",
    "docstring": "Remove a widget from this grid\n\n        Parameters\n        ----------\n        widget : Widget\n            The Widget to remove"
  },
  {
    "code": "def plot_noncontiguous(ax, data, ind, color='black', label='', offset=0,\n        linewidth=0.5, linestyle='-'):\n    def slice_with_nans(ind, data, offset):\n        import copy\n        import numpy\n        ind_nan          = numpy.zeros(len(data))\n        ind_nan[:]       = numpy.nan\n        ind_nan[ind-offset] = copy.deepcopy(ind)\n        data_nan = copy.deepcopy(data)\n        data_nan[numpy.isnan(ind_nan)] = numpy.nan\n        return ind_nan, data_nan\n    x, y = slice_with_nans(ind, data, offset)\n    ax.plot(x, y, color=color, linewidth=linewidth, linestyle=linestyle,\n            label=label)\n    return ax",
    "docstring": "Plot non-contiguous slice of data\n\n    Args\n    ----\n    data: ndarray\n        The data with non continguous regions to plot\n    ind: ndarray\n        indices of data to be plotted\n    color: matplotlib color\n        Color of plotted line\n    label: str\n        Name to be shown in legend\n    offset: int\n        The number of index positions to reset start of data to zero\n    linewidth: float\n        The width of the plotted line\n    linstyle: str\n        The char representation of the plotting style for the line\n\n    Returns\n    -------\n    ax: pyplot.ax\n        Axes object with line glyph added for non-contiguous regions"
  },
  {
    "code": "def next_content(self, start, amount=1):\n        while start < len(self.code) and self.code[start] in (' ', '\\t', '\\n'):\n            start += 1\n        return self.code[start: start + amount]",
    "docstring": "Returns the next non-whitespace characters"
  },
  {
    "code": "def change_token(self, id):\n        schema = UserSchema(exclude=('password', 'password_confirm'))\n        resp = self.service.post(self.base+str(id)+'/token/')\n        return self.service.decode(schema, resp)",
    "docstring": "Change a user's token.\n\n        :param id: User ID as an int.\n        :return: :class:`users.User <users.User>` object\n        :rtype: users.User"
  },
  {
    "code": "def transpose(vari):\n    if isinstance(vari, Poly):\n        core = vari.A.copy()\n        for key in vari.keys:\n            core[key] = transpose(core[key])\n        return Poly(core, vari.dim, vari.shape[::-1], vari.dtype)\n    return numpy.transpose(vari)",
    "docstring": "Transpose a shapeable quantety.\n\n    Args:\n        vari (chaospy.poly.base.Poly, numpy.ndarray):\n            Quantety of interest.\n\n    Returns:\n        (chaospy.poly.base.Poly, numpy.ndarray):\n            Same type as ``vari``.\n\n    Examples:\n        >>> P = chaospy.reshape(chaospy.prange(4), (2,2))\n        >>> print(P)\n        [[1, q0], [q0^2, q0^3]]\n        >>> print(chaospy.transpose(P))\n        [[1, q0^2], [q0, q0^3]]"
  },
  {
    "code": "def has_privs(self, user, lowest_mode='o'):\n        if isinstance(user, User):\n            user = user.nick\n        user_prefixes = self.prefixes.get(user, None)\n        if not user_prefixes:\n            return False\n        mode_dict = self.s.features.available['prefix']\n        caught = False\n        for mode, prefix in mode_dict.items():\n            if mode in lowest_mode and not caught:\n                caught = True\n            elif mode not in lowest_mode and not caught:\n                continue\n            if prefix in user_prefixes:\n                return True\n        return False",
    "docstring": "Return True if user has the given mode or higher."
  },
  {
    "code": "def wrap_query_in_nested_if_field_is_nested(query, field, nested_fields):\n    for element in nested_fields:\n        match_pattern = r'^{}.'.format(element)\n        if re.match(match_pattern, field):\n            return generate_nested_query(element, query)\n    return query",
    "docstring": "Helper for wrapping a query into a nested if the fields within the query are nested\n\n    Args:\n        query : The query to be wrapped.\n        field : The field that is being queried.\n        nested_fields : List of fields which are nested.\n    Returns:\n        (dict): The nested query"
  },
  {
    "code": "def get(self, index):\n        return SyncListItemContext(\n            self._version,\n            service_sid=self._solution['service_sid'],\n            list_sid=self._solution['list_sid'],\n            index=index,\n        )",
    "docstring": "Constructs a SyncListItemContext\n\n        :param index: The index\n\n        :returns: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext\n        :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemContext"
  },
  {
    "code": "def convert_sequence_to_motor_units(cycles, unit_converter):\n    cv_cycles = copy.deepcopy(cycles)\n    for cycle in cv_cycles:\n        for move in cycle['moves']:\n            move['A'] = unit_converter.to_motor_velocity_acceleration( \\\n                move['A'])\n            move['AD'] = \\\n                unit_converter.to_motor_velocity_acceleration( \\\n                move['AD'])\n            move['V'] = unit_converter.to_motor_velocity_acceleration( \\\n                move['V'])\n            move['D'] = int(unit_converter.to_motor_distance(move['D']))\n    return cv_cycles",
    "docstring": "Converts a move sequence to motor units.\n\n    Converts a move sequence to motor units using the provied converter.\n\n    Parameters\n    ----------\n    cycles : iterable of dicts\n        The iterable of cycles of motion to do one after another. See\n        ``compile_sequence`` for format.\n    unit_converter : UnitConverter, optional\n        ``GeminiMotorDrive.utilities.UnitConverter`` to use to convert\n        the units in `cycles` to motor units.\n\n    Returns\n    -------\n    motor_cycles : list of dicts\n        A deep copy of `cycles` with all units converted to motor units.\n\n    See Also\n    --------\n    compile_sequence\n    GeminiMotorDrive.utilities.UnitConverter"
  },
  {
    "code": "def process_remote_sources(raw_config, environment=None):\n    config = yaml.safe_load(raw_config)\n    if config and config.get('package_sources'):\n        processor = SourceProcessor(\n            sources=config['package_sources'],\n            stacker_cache_dir=config.get('stacker_cache_dir')\n        )\n        processor.get_package_sources()\n        if processor.configs_to_merge:\n            for i in processor.configs_to_merge:\n                logger.debug(\"Merging in remote config \\\"%s\\\"\", i)\n                remote_config = yaml.safe_load(open(i))\n                config = merge_map(remote_config, config)\n            if not environment:\n                environment = {}\n            return render(str(config), environment)\n    return raw_config",
    "docstring": "Stage remote package sources and merge in remote configs.\n\n    Args:\n        raw_config (str): the raw stacker configuration string.\n        environment (dict, optional): any environment values that should be\n            passed to the config\n\n    Returns:\n        str: the raw stacker configuration string"
  },
  {
    "code": "def iter_documents(self, fileids=None, categories=None, _destroy=False):\n        doc_ids = self._filter_ids(fileids, categories)\n        for doc in imap(self.get_document, doc_ids):\n            yield doc\n            if _destroy:\n                doc.destroy()",
    "docstring": "Return an iterator over corpus documents."
  },
  {
    "code": "def access_id(self, id_, lineno, scope=None, default_type=None, default_class=CLASS.unknown):\n        if isinstance(default_type, symbols.BASICTYPE):\n            default_type = symbols.TYPEREF(default_type, lineno, implicit=False)\n        assert default_type is None or isinstance(default_type, symbols.TYPEREF)\n        if not check_is_declared_explicit(lineno, id_):\n            return None\n        result = self.get_entry(id_, scope)\n        if result is None:\n            if default_type is None:\n                default_type = symbols.TYPEREF(self.basic_types[global_.DEFAULT_IMPLICIT_TYPE],\n                                               lineno, implicit=True)\n            result = self.declare_variable(id_, lineno, default_type)\n            result.declared = False\n            result.class_ = default_class\n            return result\n        if default_type is not None and result.type_ == self.basic_types[TYPE.auto]:\n            result.type_ = default_type\n            warning_implicit_type(lineno, id_, default_type)\n        return result",
    "docstring": "Access a symbol by its identifier and checks if it exists.\n        If not, it's supposed to be an implicit declared variable.\n\n        default_class is the class to use in case of an undeclared-implicit-accessed id"
  },
  {
    "code": "def set_custom_value(self, field_name, value):\n        custom_field = self.get_custom_field(field_name)\n        custom_value = CustomFieldValue.objects.get_or_create(\n            field=custom_field, object_id=self.id)[0]\n        custom_value.value = value\n        custom_value.save()",
    "docstring": "Set a value for a specified custom field\n        field_name - Name of the custom field you want.\n        value - Value to set it to"
  },
  {
    "code": "async def status(request: web.Request) -> web.Response:\n    connectivity = {'status': 'none', 'interfaces': {}}\n    try:\n        connectivity['status'] = await nmcli.is_connected()\n        connectivity['interfaces'] = {\n            i.value: await nmcli.iface_info(i) for i in nmcli.NETWORK_IFACES\n        }\n        log.debug(\"Connectivity: {}\".format(connectivity['status']))\n        log.debug(\"Interfaces: {}\".format(connectivity['interfaces']))\n        status = 200\n    except subprocess.CalledProcessError as e:\n        log.error(\"CalledProcessError: {}\".format(e.stdout))\n        status = 500\n    except FileNotFoundError as e:\n        log.error(\"FileNotFoundError: {}\".format(e))\n        status = 500\n    return web.json_response(connectivity, status=status)",
    "docstring": "Get request will return the status of the machine's connection to the\n    internet as well as the status of its network interfaces.\n\n    The body of the response is a json dict containing\n\n    'status': internet connectivity status, where the options are:\n      \"none\" - no connection to router or network\n      \"portal\" - device behind a captive portal and cannot reach full internet\n      \"limited\" - connection to router but not internet\n      \"full\" - connection to router and internet\n      \"unknown\" - an exception occured while trying to determine status\n    'interfaces': JSON object of networking interfaces, keyed by device name,\n    where the value of each entry is another object with the keys:\n      - 'type': \"ethernet\" or \"wifi\"\n      - 'state': state string, e.g. \"disconnected\", \"connecting\", \"connected\"\n      - 'ipAddress': the ip address, if it exists (null otherwise); this also\n        contains the subnet mask in CIDR notation, e.g. 10.2.12.120/16\n      - 'macAddress': the MAC address of the interface device\n      - 'gatewayAddress': the address of the current gateway, if it exists\n        (null otherwise)\n\n\n    Example request:\n    ```\n    GET /networking/status\n    ```\n\n    Example response:\n    ```\n    200 OK\n    {\n        \"status\": \"full\",\n        \"interfaces\": {\n            \"wlan0\": {\n                \"ipAddress\": \"192.168.43.97/24\",\n                \"macAddress\": \"B8:27:EB:6C:95:CF\",\n                \"gatewayAddress\": \"192.168.43.161\",\n                \"state\": \"connected\",\n                \"type\": \"wifi\"\n            },\n            \"eth0\": {\n                \"ipAddress\": \"169.254.229.173/16\",\n                \"macAddress\": \"B8:27:EB:39:C0:9A\",\n                \"gatewayAddress\": null,\n                \"state\": \"connected\",\n                \"type\": \"ethernet\"\n            }\n        }\n    }\n    ```"
  },
  {
    "code": "def run(self, bundle,\n              container_id=None,\n              log_path=None,\n              pid_file=None,\n              log_format=\"kubernetes\"):\n    return self._run(bundle,\n                     container_id=container_id,\n                     log_path=log_path,\n                     pid_file=pid_file,\n                     command=\"run\",\n                     log_format=log_format)",
    "docstring": "run is a wrapper to create, start, attach, and delete a container.\n\n        Equivalent command line example:      \n          singularity oci run -b ~/bundle mycontainer\n\n        Parameters\n        ==========\n        bundle: the full path to the bundle folder\n        container_id: an optional container_id. If not provided, use same\n                      container_id used to generate OciImage instance\n        log_path: the path to store the log.\n        pid_file: specify the pid file path to use\n        log_format: defaults to kubernetes. Can also be \"basic\" or \"json\""
  },
  {
    "code": "def period_end_day(self, value=None):\n        if value is not None:\n            try:\n                value = str(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type str '\n                                 'for field `period_end_day`'.format(value))\n            if ',' in value:\n                raise ValueError('value should not contain a comma '\n                                 'for field `period_end_day`')\n        self._period_end_day = value",
    "docstring": "Corresponds to IDD Field `period_end_day`\n\n        Args:\n            value (str): value for IDD Field `period_end_day`\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def mk_dropdown_tree(cls, model, for_node=None):\n        options = [(0, _('-- root --'))]\n        for node in model.get_root_nodes():\n            cls.add_subtree(for_node, node, options)\n        return options",
    "docstring": "Creates a tree-like list of choices"
  },
  {
    "code": "def is_iso8601(instance: str):\n    if not isinstance(instance, str):\n        return True\n    return ISO8601.match(instance) is not None",
    "docstring": "Validates ISO8601 format"
  },
  {
    "code": "def get_context_data(self, **kwargs):\n        self.set_return_page('viewregistrations',_('View Registrations'),event_id=self.object.id)\n        context = {\n            'event': self.object,\n            'registrations': EventRegistration.objects.filter(\n                event=self.object,\n                cancelled=False\n            ).order_by('registration__customer__user__first_name', 'registration__customer__user__last_name'),\n        }\n        context.update(kwargs)\n        return super(EventRegistrationSummaryView, self).get_context_data(**context)",
    "docstring": "Add the list of registrations for the given series"
  },
  {
    "code": "def extract_audioclip_samples(d) -> dict:\n\tret = {}\n\tif not d.data:\n\t\treturn {}\n\ttry:\n\t\tfrom fsb5 import FSB5\n\texcept ImportError as e:\n\t\traise RuntimeError(\"python-fsb5 is required to extract AudioClip\")\n\taf = FSB5(d.data)\n\tfor i, sample in enumerate(af.samples):\n\t\tif i > 0:\n\t\t\tfilename = \"%s-%i.%s\" % (d.name, i, af.get_sample_extension())\n\t\telse:\n\t\t\tfilename = \"%s.%s\" % (d.name, af.get_sample_extension())\n\t\ttry:\n\t\t\tsample = af.rebuild_sample(sample)\n\t\texcept ValueError as e:\n\t\t\tprint(\"WARNING: Could not extract %r (%s)\" % (d, e))\n\t\t\tcontinue\n\t\tret[filename] = sample\n\treturn ret",
    "docstring": "Extract all the sample data from an AudioClip and\n\tconvert it from FSB5 if needed."
  },
  {
    "code": "def join(self, inner_iterable, outer_key_selector=identity,\n             inner_key_selector=identity,\n             result_selector=lambda outer, inner: (outer, inner)):\n        if self.closed():\n            raise ValueError(\"Attempt to call join() on a closed Queryable.\")\n        if not is_iterable(inner_iterable):\n            raise TypeError(\"Cannot compute join() with inner_iterable of \"\n                   \"non-iterable {0}\".format(str(type(inner_iterable))[7: -1]))\n        if not is_callable(outer_key_selector):\n            raise TypeError(\"join() parameter outer_key_selector={0} is not \"\n                            \"callable\".format(repr(outer_key_selector)))\n        if not is_callable(inner_key_selector):\n            raise TypeError(\"join() parameter inner_key_selector={0} is not \"\n                            \"callable\".format(repr(inner_key_selector)))\n        if not is_callable(result_selector):\n            raise TypeError(\"join() parameter result_selector={0} is not \"\n                            \"callable\".format(repr(result_selector)))\n        return self._create(self._generate_join_result(inner_iterable, outer_key_selector,\n                                                       inner_key_selector, result_selector))",
    "docstring": "Perform an inner join with a second sequence using selected keys.\n\n        The order of elements from outer is maintained. For each of these the\n        order of elements from inner is also preserved.\n\n        Note: This method uses deferred execution.\n\n        Args:\n            inner_iterable: The sequence to join with the outer sequence.\n\n            outer_key_selector: An optional unary function to extract keys from\n                elements of the outer (source) sequence. The first positional\n                argument of the function should accept outer elements and the\n                result value should be the key. If omitted, the identity\n                function is used.\n\n            inner_key_selector: An optional  unary function to extract keys\n                from elements of the inner_iterable. The first positional\n                argument of the function should accept outer elements and the\n                result value should be the key.  If omitted, the identity\n                function is used.\n\n            result_selector: An optional binary function to create a result\n                element from two matching elements of the outer and inner. If\n                omitted the result elements will be a 2-tuple pair of the\n                matching outer and inner elements.\n\n        Returns:\n            A Queryable whose elements are the result of performing an inner-\n            join on two sequences.\n\n        Raises:\n            ValueError: If the Queryable has been closed.\n            TypeError: If the inner_iterable is not in fact iterable.\n            TypeError: If the outer_key_selector is not callable.\n            TypeError: If the inner_key_selector is not callable.\n            TypeError: If the result_selector is not callable."
  },
  {
    "code": "def _fallback_to_available_output(self):\n        if len(self.active_comb) == 1:\n            self._choose_what_to_display(force_refresh=True)\n            self._apply()\n            self.py3.update()",
    "docstring": "Fallback to the first available output when the active layout\n        was composed of only one output.\n\n        This allows us to avoid cases where you get stuck with a black sreen\n        on your laptop by switching back to the integrated screen\n        automatically !"
  },
  {
    "code": "def check_ok_button(self):\n        login = self.login.text()\n        password = self.password.text()\n        url = self.url.text()\n        if self.layers.count() >= 1 and login and password and url:\n            self.ok_button.setEnabled(True)\n        else:\n            self.ok_button.setEnabled(False)",
    "docstring": "Helper to enable or not the OK button."
  },
  {
    "code": "def init(project_name):\n    dst_path = os.path.join(os.getcwd(), project_name)\n    start_init_info(dst_path)\n    _mkdir_p(dst_path)\n    os.chdir(dst_path)\n    init_code('manage.py', _manage_basic_code)\n    init_code('requirement.txt', _requirement_code)\n    app_path = os.path.join(dst_path, 'app')\n    _mkdir_p(app_path)\n    os.chdir(app_path)\n    init_code('views.py', _views_basic_code)\n    init_code('forms.py', _forms_basic_code)\n    init_code('__init__.py', _init_basic_code)\n    create_templates_static_files(app_path)\n    init_done_info()",
    "docstring": "build a minimal flask project"
  },
  {
    "code": "def genome_mutation(candidate):\n    size = len(candidate)\n    prob = random.random()\n    if prob > .5:\n        p = random.randint(0, size-1)\n        q = random.randint(0, size-1)\n        if p > q:\n            p, q = q, p\n        q += 1\n        s = candidate[p:q]\n        x = candidate[:p] + s[::-1] + candidate[q:]\n        return creator.Individual(x),\n    else:\n        p = random.randint(0, size-1)\n        q = random.randint(0, size-1)\n        cq = candidate.pop(q)\n        candidate.insert(p, cq)\n        return candidate,",
    "docstring": "Return the mutants created by inversion mutation on the candidates.\n\n    This function performs inversion or insertion. It randomly chooses two\n    locations along the candidate and reverses the values within that\n    slice. Insertion is done by popping one item and insert it back at random\n    position."
  },
  {
    "code": "def where(cond, a, b, use_numexpr=True):\n    if use_numexpr:\n        return _where(cond, a, b)\n    return _where_standard(cond, a, b)",
    "docstring": "evaluate the where condition cond on a and b\n\n        Parameters\n        ----------\n\n        cond : a boolean array\n        a :    return if cond is True\n        b :    return if cond is False\n        use_numexpr : whether to try to use numexpr (default True)"
  },
  {
    "code": "def get_offset(self):\n        resp = requests.head(self.url, headers=self.headers)\n        offset = resp.headers.get('upload-offset')\n        if offset is None:\n            msg = 'Attempt to retrieve offset fails with status {}'.format(resp.status_code)\n            raise TusCommunicationError(msg, resp.status_code, resp.content)\n        return int(offset)",
    "docstring": "Return offset from tus server.\n\n        This is different from the instance attribute 'offset' because this makes an\n        http request to the tus server to retrieve the offset."
  },
  {
    "code": "def to_bytes(value):\n    if isinstance(value, text_type):\n        return value.encode('utf-8')\n    elif isinstance(value, ffi.CData):\n        return ffi.string(value)\n    elif isinstance(value, binary_type):\n        return value\n    else:\n        raise ValueError('Value must be text, bytes, or char[]')",
    "docstring": "Converts bytes, unicode, and C char arrays to bytes.\n\n    Unicode strings are encoded to UTF-8."
  },
  {
    "code": "def disconnect(self, event, cb):\n        try:\n            self._callbacks[event].remove(cb)\n        except KeyError:\n            raise ValueError(\"{!r} is not a valid cursor event\".format(event))\n        except ValueError:\n            raise ValueError(\"Callback {} is not registered\".format(event))",
    "docstring": "Disconnect a previously connected callback.\n\n        If a callback is connected multiple times, only one connection is\n        removed."
  },
  {
    "code": "def scipy_sparse_to_spmatrix(A):\n    coo = A.tocoo()\n    SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)\n    return SP",
    "docstring": "Efficient conversion from scipy sparse matrix to cvxopt sparse matrix"
  },
  {
    "code": "def userInvitations(self):\n        self.__init()\n        items = []\n        for n in self._userInvitations:\n            if \"id\" in n:\n                url = \"%s/%s\" % (self.root, n['id'])\n                items.append(self.Invitation(url=url,\n                                             securityHandler=self._securityHandler,\n                                             proxy_url=self._proxy_url,\n                                             proxy_port=self._proxy_port,\n                                             initialize=True))\n        return items",
    "docstring": "gets all user invitations"
  },
  {
    "code": "def palettize(self, colormap):\n        if self.mode not in (\"L\", \"LA\"):\n            raise ValueError(\"Image should be grayscale to colorize\")\n        l_data = self.data.sel(bands=['L'])\n        def _palettize(data):\n            return colormap.palettize(data)[0]\n        new_data = l_data.data.map_blocks(_palettize, dtype=l_data.dtype)\n        self.palette = tuple(colormap.colors)\n        if self.mode == \"L\":\n            mode = \"P\"\n        else:\n            mode = \"PA\"\n            new_data = da.concatenate([new_data, self.data.sel(bands=['A'])], axis=0)\n        self.data.data = new_data\n        self.data.coords['bands'] = list(mode)",
    "docstring": "Palettize the current image using `colormap`.\n\n        .. note::\n\n            Works only on \"L\" or \"LA\" images."
  },
  {
    "code": "def verify_token(self, token):\n        try:\n            result = self.resolver.get_token(token)\n        except Exception as ex:\n            raise EauthAuthenticationError(\n                \"Token validation failed with {0}.\".format(repr(ex)))\n        return result",
    "docstring": "If token is valid Then returns user name associated with token\n        Else False."
  },
  {
    "code": "def applyFracdet(self, lon, lat):\n        self.loadFracdet()\n        fracdet_core = meanFracdet(self.m_fracdet, lon, lat, np.tile(0.1, len(lon)))\n        fracdet_wide = meanFracdet(self.m_fracdet, lon, lat, np.tile(0.5, len(lon)))\n        return (fracdet_core >= self.config[self.algorithm]['fracdet_core_threshold']) \\\n            & (fracdet_core >= self.config[self.algorithm]['fracdet_core_threshold'])",
    "docstring": "We want to enforce minimum fracdet for a satellite to be considered detectable\n\n        True is passes fracdet cut"
  },
  {
    "code": "def main():\n    argv = sys.argv\n    if len(argv) < 2:\n        targetfile = 'target.y'\n    else:\n        targetfile = argv[1]\n    print 'Parsing ruleset: ' + targetfile,\n    flex_a = Flexparser()\n    mma = flex_a.yyparse(targetfile)\n    print 'OK'\n    print 'Perform minimization on initial automaton:',\n    mma.minimize()\n    print 'OK'\n    print 'Perform Brzozowski on minimal automaton:',\n    brzozowski_a = Brzozowski(mma)\n    mma_regex = brzozowski_a.get_regex()\n    print mma_regex",
    "docstring": "Testing function for DFA brzozowski algebraic method Operation"
  },
  {
    "code": "def read_bytes(self, count):\n        if self.pos + count > self.remaining_length:\n            return NC.ERR_PROTOCOL, None\n        ba = bytearray(count)\n        for x in xrange(0, count):\n            ba[x] = self.payload[self.pos]\n            self.pos += 1\n        return NC.ERR_SUCCESS, ba",
    "docstring": "Read count number of bytes."
  },
  {
    "code": "def comp_pipe_handle(loc, tokens):\n    internal_assert(len(tokens) >= 3 and len(tokens) % 2 == 1, \"invalid composition pipe tokens\", tokens)\n    funcs = [tokens[0]]\n    stars = []\n    direction = None\n    for i in range(1, len(tokens), 2):\n        op, fn = tokens[i], tokens[i + 1]\n        new_direction, star = comp_pipe_info(op)\n        if direction is None:\n            direction = new_direction\n        elif new_direction != direction:\n            raise CoconutDeferredSyntaxError(\"cannot mix function composition pipe operators with different directions\", loc)\n        funcs.append(fn)\n        stars.append(star)\n    if direction == \"backwards\":\n        funcs.reverse()\n        stars.reverse()\n    func = funcs.pop(0)\n    funcstars = zip(funcs, stars)\n    return \"_coconut_base_compose(\" + func + \", \" + \", \".join(\n        \"(%s, %s)\" % (f, star) for f, star in funcstars\n    ) + \")\"",
    "docstring": "Process pipe function composition."
  },
  {
    "code": "def str2float(text):\n    try:\n        return float(re.sub(r\"\\(.+\\)*\", \"\", text))\n    except TypeError:\n        if isinstance(text, list) and len(text) == 1:\n            return float(re.sub(r\"\\(.+\\)*\", \"\", text[0]))\n    except ValueError as ex:\n        if text.strip() == \".\":\n            return 0\n        raise ex",
    "docstring": "Remove uncertainty brackets from strings and return the float."
  },
  {
    "code": "def sanitize_filepath(file_path, replacement_text=\"\", platform=None, max_len=None):\n    return FilePathSanitizer(platform=platform, max_len=max_len).sanitize(\n        file_path, replacement_text\n    )",
    "docstring": "Make a valid file path from a string.\n\n    Replace invalid characters for a file path within the ``file_path``\n    with the ``replacement_text``.\n    Invalid characters are as followings:\n    |invalid_file_path_chars|, |invalid_win_file_path_chars| (and non printable characters).\n\n    Args:\n        file_path (str or PathLike object):\n            File path to sanitize.\n        replacement_text (str, optional):\n            Replacement text for invalid characters.\n            Defaults to ``\"\"``.\n        platform (str, optional):\n            .. include:: platform.txt\n        max_len (int, optional):\n            The upper limit of the ``file_path`` length. Truncate the name if the ``file_path``\n            length exceedd this value. If the value is |None|, the default value automatically\n            determined by the execution platform:\n\n                - ``Linux``: 4096\n                - ``macOS``: 1024\n                - ``Windows``: 260\n\n    Returns:\n        Same type as the argument (str or PathLike object):\n            Sanitized filepath.\n\n    Raises:\n        ValueError:\n            If the ``file_path`` is an invalid file path.\n\n    Example:\n        :ref:`example-sanitize-file-path`"
  },
  {
    "code": "def contains_pts(self, pts):\n        obj1, obj2 = self.objects\n        arg1 = obj2.contains_pts(pts)\n        arg2 = np.logical_not(obj1.contains_pts(pts))\n        return np.logical_and(arg1, arg2)",
    "docstring": "Containment test on arrays."
  },
  {
    "code": "def generate_docker_file(py_ver: PyVer):\n    with open(os.path.join(script_templates_root, 'Dockerfile')) as fh:\n        return fh.read().format(py_ver=py_ver, author=author_file)",
    "docstring": "Templated docker files"
  },
  {
    "code": "def dequeue(ctx):\n    tweet =ctx.obj['TWEETLIST'].peek()\n    if tweet is None:\n        click.echo(\"Nothing to dequeue.\")\n        ctx.exit(1)\n    if ctx.obj['DRYRUN']:\n        click.echo(tweet)\n    else:\n        tweet = ctx.obj['TWEETLIST'].pop()\n        ctx.obj['TWEEPY_API'].update_status(tweet)",
    "docstring": "Sends a tweet from the queue"
  },
  {
    "code": "def _run_hooked_methods(self, hook: str):\n        for method in self._potentially_hooked_methods:\n            for callback_specs in method._hooked:\n                if callback_specs['hook'] != hook:\n                    continue\n                when = callback_specs.get('when')\n                if when:\n                    if self._check_callback_conditions(callback_specs):\n                        method()\n                else:\n                    method()",
    "docstring": "Iterate through decorated methods to find those that should be\n            triggered by the current hook. If conditions exist, check them before\n            running otherwise go ahead and run."
  },
  {
    "code": "def csrf(request):\n    def _get_val():\n        token = get_token(request)\n        if token is None:\n            return 'NOTPROVIDED'\n        else:\n            token = force_bytes(token, encoding='latin-1')\n            key = force_bytes(\n                get_random_string(len(token)),\n                encoding='latin-1'\n            )\n            value = b64_encode(xor(token, key))\n            return force_text(b'$'.join((key, value)), encoding='latin-1')\n    _get_val = lazy(_get_val, text_type)\n    return {'csrf_token': _get_val()}",
    "docstring": "Context processor that provides a CSRF token, or the string 'NOTPROVIDED'\n    if it has not been provided by either a view decorator or the middleware"
  },
  {
    "code": "def _format_capability_report(self, data):\n        if self.log_output:\n            return\n        else:\n            pin_modes = {0: 'Digital_Input', 1: 'Digital_Output',\n                         2: 'Analog', 3: 'PWM', 4: 'Servo',\n                         5: 'Shift', 6: 'I2C', 7: 'One Wire',\n                         8: 'Stepper', 9: 'Encoder'}\n            x = 0\n            pin = 0\n            print('\\nCapability Report')\n            print('-----------------\\n')\n            while x < len(data):\n                print('{} {}{}'.format('Pin', str(pin), ':'))\n                while data[x] != 127:\n                    mode_str = \"\"\n                    pin_mode = pin_modes.get(data[x])\n                    mode_str += str(pin_mode)\n                    x += 1\n                    bits = data[x]\n                    print('{:>5}{}{} {}'.format('  ', mode_str, ':', bits))\n                    x += 1\n                x += 1\n                pin += 1",
    "docstring": "This is a private utility method.\n        This method formats a capability report if the user wishes to\n        send it to the console.\n        If log_output = True, no output is generated\n\n        :param data: Capability report\n\n        :returns: None"
  },
  {
    "code": "def _add_column(self, type, name, **parameters):\n        parameters.update({\n            'type': type,\n            'name': name\n        })\n        column = Fluent(**parameters)\n        self._columns.append(column)\n        return column",
    "docstring": "Add a new column to the blueprint.\n\n        :param type: The column type\n        :type type: str\n\n        :param name: The column name\n        :type name: str\n\n        :param parameters: The column parameters\n        :type parameters: dict\n\n        :rtype: Fluent"
  },
  {
    "code": "def rowxcol(row, col):\n    row = row.reshape(4, 4)\n    col = col.reshape(4, 8)\n    ret = uint2exprs(0, 8)\n    for i in range(4):\n        for j in range(4):\n            if row[i, j]:\n                ret ^= xtime(col[i], j)\n    return ret",
    "docstring": "Multiply one row and one column."
  },
  {
    "code": "def to_native(key):\n    item = find(whatever=key)\n    if not item:\n        raise NonExistentLanguageError('Language does not exist.')\n    return item[u'native']",
    "docstring": "Find the native name for the language specified by key.\n\n    >>> to_native('br')\n    u'brezhoneg'\n    >>> to_native('sw')\n    u'Kiswahili'"
  },
  {
    "code": "def save_form(self, request, form, change):\n        obj = form.save(commit=False)\n        if not obj.id and \"in_sitemap\" not in form.fields:\n            obj.in_sitemap = False\n        return super(LinkAdmin, self).save_form(request, form, change)",
    "docstring": "Don't show links in the sitemap."
  },
  {
    "code": "def state_destruction(self, model, prop_name, info):\n        import rafcon.gui.singleton as gui_singletons\n        states_editor_ctrl = gui_singletons.main_window_controller.get_controller('states_editor_ctrl')\n        state_identifier = states_editor_ctrl.get_state_identifier(self.model)\n        states_editor_ctrl.close_page(state_identifier, delete=True)",
    "docstring": "Close state editor when state is being destructed"
  },
  {
    "code": "def remove_source(self, source):\n        geocode_service = self._get_service_by_name(source[0])\n        self._sources.remove(geocode_service(**source[1]))",
    "docstring": "Remove a geocoding service from this instance."
  },
  {
    "code": "def grid_linspace(bounds, count):\n    bounds = np.asanyarray(bounds, dtype=np.float64)\n    if len(bounds) != 2:\n        raise ValueError('bounds must be (2, dimension!')\n    count = np.asanyarray(count, dtype=np.int)\n    if count.shape == ():\n        count = np.tile(count, bounds.shape[1])\n    grid_elements = [np.linspace(*b, num=c) for b, c in zip(bounds.T, count)]\n    grid = np.vstack(np.meshgrid(*grid_elements)\n                     ).reshape(bounds.shape[1], -1).T\n    return grid",
    "docstring": "Return a grid spaced inside a bounding box with edges spaced using np.linspace.\n\n    Parameters\n    ---------\n    bounds: (2,dimension) list of [[min x, min y, etc], [max x, max y, etc]]\n    count:  int, or (dimension,) int, number of samples per side\n\n    Returns\n    -------\n    grid: (n, dimension) float, points in the specified bounds"
  },
  {
    "code": "def find_elements_by_name(self, name, update=False) -> Elements:\n        return self.find_elements(by=By.NAME, value=name, update=update)",
    "docstring": "Finds multiple elements by name.\n\n        Args:\n            name: The name of the elements to be found.\n            update: If the interface has changed, this option should be True.\n\n        Returns:\n            A list with elements if any was found. An empty list if not.\n\n        Raises:\n            NoSuchElementException - If the element wasn't found.\n\n        Usage:\n            elements = driver.find_elements_by_name('foo')"
  },
  {
    "code": "def _toggle_monitoring(self, action, no_ssh=False):\n        payload = {\n            'action': action,\n            'name': self.name,\n            'no_ssh': no_ssh,\n            'public_ips': self.info['public_ips'],\n            'dns_name': self.info['extra'].get('dns_name', 'n/a')\n        }\n        data = json.dumps(payload)\n        req = self.request(self.mist_client.uri+\"/clouds/\"+self.cloud.id+\"/machines/\"+self.id+\"/monitoring\",\n                           data=data)\n        req.post()",
    "docstring": "Enable or disable monitoring on a machine\n\n        :param action: Can be either \"enable\" or \"disable\""
  },
  {
    "code": "def penUp(self):\n        if self._penDown==True:\n            self._penDown = False\n            self._addPolylineToElements()",
    "docstring": "Raises the pen. Any movement will not draw lines till pen is lowered again."
  },
  {
    "code": "def get_config(cli_args=None, config_path=None):\n    config = Config(app_name=\"MYAPP\",\n                    cli_args=cli_args,\n                    config_path=config_path)\n    config_dict = config.get_config()\n    return config_dict",
    "docstring": "Perform standard setup - get the merged config\n\n    :param cli_args dict: A dictionary of CLI arguments\n    :param config_path string: Path to the config file to load\n\n    :return dict: A dictionary of config values drawn from different sources"
  },
  {
    "code": "def get_thread_block_dimensions(params, block_size_names=None):\n    if not block_size_names:\n        block_size_names = default_block_size_names\n    block_size_x = params.get(block_size_names[0], 256)\n    block_size_y = params.get(block_size_names[1], 1)\n    block_size_z = params.get(block_size_names[2], 1)\n    return (int(block_size_x), int(block_size_y), int(block_size_z))",
    "docstring": "thread block size from tuning params, currently using convention"
  },
  {
    "code": "def summarize_taxa(biom):\n    tamtcounts = defaultdict(int)\n    tot_seqs = 0.0\n    for row, col, amt in biom['data']:\n        tot_seqs += amt\n        rtax = biom['rows'][row]['metadata']['taxonomy']\n        for i, t in enumerate(rtax):\n            t = t.strip()\n            if i == len(rtax)-1 and len(t) > 3 and len(rtax[-1]) > 3:\n                t = 's__'+rtax[i-1].strip().split('_')[-1]+'_'+t.split('_')[-1]\n            tamtcounts[t] += amt\n    lvlData = {lvl: levelData(tamtcounts, tot_seqs, lvl) for lvl in ['k', 'p', 'c', 'o', 'f', 'g', 's']}\n    return tot_seqs, lvlData",
    "docstring": "Given an abundance table, group the counts by every\n    taxonomic level."
  },
  {
    "code": "def _CaptureRequestLogId(self):\n    if callable(request_log_id_collector):\n      request_log_id = request_log_id_collector()\n      if request_log_id:\n        self.breakpoint['labels'][\n            labels.Breakpoint.REQUEST_LOG_ID] = request_log_id",
    "docstring": "Captures the request log id if possible.\n\n    The request log id is stored inside the breakpoint labels."
  },
  {
    "code": "def filePath(self, index):\n        return self._fs_model_source.filePath(\n            self._fs_model_proxy.mapToSource(index))",
    "docstring": "Gets the file path of the item at the specified ``index``.\n\n        :param index: item index - QModelIndex\n        :return: str"
  },
  {
    "code": "def extend(self, content, zorder):\n        if zorder not in self._content:\n            self._content[zorder] = []\n        self._content[zorder].extend(content)",
    "docstring": "Extends with a list and a z-order"
  },
  {
    "code": "def _get_client(self):\n        client_kwargs = self._storage_parameters.get('client', dict())\n        if self._unsecure:\n            client_kwargs = client_kwargs.copy()\n            client_kwargs['use_ssl'] = False\n        return self._get_session().client(\"s3\", **client_kwargs)",
    "docstring": "S3 Boto3 client\n\n        Returns:\n            boto3.session.Session.client: client"
  },
  {
    "code": "def from_file(cls, f, fname=None, readers=None):\n        if isinstance(f, six.string_types):\n            f = io.open(f, 'rb')\n        if not fname and hasattr(f, 'name'):\n            fname = f.name\n        return cls.from_string(f.read(), fname=fname, readers=readers)",
    "docstring": "Create a Document from a file.\n\n        Usage::\n\n            with open('paper.html', 'rb') as f:\n                doc = Document.from_file(f)\n\n        .. note::\n\n            Always open files in binary mode by using the 'rb' parameter.\n\n        :param file|string f: A file-like object or path to a file.\n        :param string fname: (Optional) The filename. Used to help determine file format.\n        :param list[chemdataextractor.reader.base.BaseReader] readers: (Optional) List of readers to use."
  },
  {
    "code": "def _ensure_authed(self, ptype, message):\n        if (\n            not self.server_mode\n            or ptype <= HIGHEST_USERAUTH_MESSAGE_ID\n            or self.is_authenticated()\n        ):\n            return None\n        reply = Message()\n        if ptype == MSG_GLOBAL_REQUEST:\n            reply.add_byte(cMSG_REQUEST_FAILURE)\n        elif ptype == MSG_CHANNEL_OPEN:\n            kind = message.get_text()\n            chanid = message.get_int()\n            reply.add_byte(cMSG_CHANNEL_OPEN_FAILURE)\n            reply.add_int(chanid)\n            reply.add_int(OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED)\n            reply.add_string(\"\")\n            reply.add_string(\"en\")\n        return reply",
    "docstring": "Checks message type against current auth state.\n\n        If server mode, and auth has not succeeded, and the message is of a\n        post-auth type (channel open or global request) an appropriate error\n        response Message is crafted and returned to caller for sending.\n\n        Otherwise (client mode, authed, or pre-auth message) returns None."
  },
  {
    "code": "def revoke_access_token(self):\n        if not self._access_token:\n            return\n        self.execute_post('authentication/revoke', json=dict(\n            token_type_hint='access_token',\n            token=self._access_token\n        ))\n        self._access_token = None",
    "docstring": "Revoke the access token currently in use."
  },
  {
    "code": "def get_crc(msg):\n    register = 0xFFFF\n    for byte_ in msg:\n        try:\n            val = struct.unpack('<B', byte_)[0]\n        except TypeError:\n            val = byte_\n        register = \\\n            (register >> 8) ^ look_up_table[(register ^ val) & 0xFF]\n    return struct.pack('<H', register)",
    "docstring": "Return CRC of 2 byte for message.\n\n        >>> assert get_crc(b'\\x02\\x07') == struct.unpack('<H', b'\\x41\\x12')\n\n    :param msg: A byte array.\n    :return: Byte array of 2 bytes."
  },
  {
    "code": "def sort(self, order=\"asc\"):\n        self.__prepare()\n        if isinstance(self._json_data, list):\n            if order == \"asc\":\n                self._json_data = sorted(self._json_data)\n            else:\n                self._json_data = sorted(self._json_data, reverse=True)\n        return self",
    "docstring": "Getting the sorted result of the given list\n\n        :@param order: \"asc\"\n        :@type order: string\n\n        :@return self"
  },
  {
    "code": "def get_media_stream(self, media_item, format, quality):\n        result = self._ajax_api.VideoPlayer_GetStandardConfig(\n            media_id=media_item.media_id,\n            video_format=format,\n            video_quality=quality)\n        return MediaStream(result)",
    "docstring": "Get the stream data for a given media item\n\n        @param crunchyroll.models.Media media_item\n        @param int format\n        @param int quality\n        @return crunchyroll.models.MediaStream"
  },
  {
    "code": "def rmtree_or_file(path, ignore_errors=False, onerror=None):\n  if ignore_errors and not os.path.exists(path):\n    return\n  if os.path.isdir(path) and not os.path.islink(path):\n    shutil.rmtree(path, ignore_errors=ignore_errors, onerror=onerror)\n  else:\n    os.unlink(path)",
    "docstring": "rmtree fails on files or symlinks. This removes the target, whatever it is."
  },
  {
    "code": "def has_value(cls, value: int) -> bool:\n        return any(value == item.value for item in cls)",
    "docstring": "True if specified value exists in int enum; otherwise, False."
  },
  {
    "code": "def get_tokens(max_value):\n  vocab = [str(i) for i in range(max_value)]\n  vocab = set(vocab)\n  vocab.update(CodeOp.LITERALS)\n  vocab.update(CodeOp.KEYWORDS)\n  vocab |= set(\"\".join(vocab))\n  return sorted(vocab)",
    "docstring": "Defines tokens.\n\n  Args:\n    max_value: the maximum numeric range for the token.\n\n  Returns:\n    list of string tokens in vocabulary."
  },
  {
    "code": "def _get_node_key(self, node_dict_item):\n        s = tuple(sorted(node_dict_item['sources']))\n        t = tuple(sorted(node_dict_item['targets']))\n        return (s, t)",
    "docstring": "Return a tuple of sorted sources and targets given a node dict."
  },
  {
    "code": "def competition_submissions(self, competition):\n        submissions_result = self.process_response(\n            self.competitions_submissions_list_with_http_info(id=competition))\n        return [Submission(s) for s in submissions_result]",
    "docstring": "get the list of Submission for a particular competition\n\n            Parameters\n            ==========\n            competition: the name of the competition"
  },
  {
    "code": "def from_string(cls, value):\n        match = cls.pattern.search(value)\n        if match is None:\n            raise ValueError('\"%s\" is not a valid media type' % value)\n        try:\n            return cls(match.group('mime_type'), float(match.group('weight') or 1))\n        except ValueError:\n            return cls(value)",
    "docstring": "Return single instance parsed from given accept header string."
  },
  {
    "code": "def ascii_printable(self, keysym):\n        if 0 <= keysym < 9:\n            return False\n        elif 13 < keysym < 32:\n            return False\n        elif keysym > 126:\n            return False\n        else:\n            return True",
    "docstring": "If the keysym corresponds to a non-printable ascii character this will\n        return False. If it is printable, then True will be returned.\n\n        ascii 11 (vertical tab) and ascii 12 are printable, chr(11) and chr(12)\n        will return '\\x0b' and '\\x0c' respectively."
  },
  {
    "code": "def init_cmu(filehandle=None):\n    global pronunciations, lookup, rhyme_lookup\n    if pronunciations is None:\n        if filehandle is None:\n            filehandle = cmudict.dict_stream()\n        pronunciations = parse_cmu(filehandle)\n        filehandle.close()\n        lookup = collections.defaultdict(list)\n        for word, phones in pronunciations:\n            lookup[word].append(phones)\n        rhyme_lookup = collections.defaultdict(list)\n        for word, phones in pronunciations:\n            rp = rhyming_part(phones)\n            if rp is not None:\n                rhyme_lookup[rp].append(word)",
    "docstring": "Initialize the module's pronunciation data.\n\n    This function is called automatically the first time you attempt to use\n    another function in the library that requires loading the pronunciation\n    data from disk. You can call this function manually to control when and\n    how the pronunciation data is loaded (e.g., you're using this module in\n    a web application and want to load the data asynchronously).\n\n    :param filehandle: a filehandle with CMUdict-formatted data\n    :returns: None"
  },
  {
    "code": "def with_device(\n            self,\n            new_device: devices.Device,\n            qubit_mapping: Callable[[ops.Qid], ops.Qid] = lambda e: e,\n    ) -> 'Circuit':\n        return Circuit(\n            moments=[ops.Moment(operation.transform_qubits(qubit_mapping)\n                            for operation in moment.operations)\n                     for moment in self._moments],\n            device=new_device\n        )",
    "docstring": "Maps the current circuit onto a new device, and validates.\n\n        Args:\n            new_device: The new device that the circuit should be on.\n            qubit_mapping: How to translate qubits from the old device into\n                qubits on the new device.\n\n        Returns:\n            The translated circuit."
  },
  {
    "code": "def _check_update_fw(self, tenant_id, drvr_name):\n        if self.fwid_attr[tenant_id].is_fw_complete():\n            fw_dict = self.fwid_attr[tenant_id].get_fw_dict()\n            self.modify_fw_device(tenant_id, fw_dict.get('fw_id'), fw_dict)",
    "docstring": "Update the Firewall config by calling the driver.\n\n        This function calls the device manager routine to update the device\n        with modified FW cfg."
  },
  {
    "code": "def on_subscribe(self):\n        def decorator(handler):\n            self.client.on_subscribe = handler\n            return handler\n        return decorator",
    "docstring": "Decorate a callback function to handle subscritions.\n\n        **Usage:**::\n\n            @mqtt.on_subscribe()\n            def handle_subscribe(client, userdata, mid, granted_qos):\n                print('Subscription id {} granted with qos {}.'\n                      .format(mid, granted_qos))"
  },
  {
    "code": "def _format_background(background):\n    if os.path.isfile(background):\n        with open(background, \"r\") as i_file:\n            background = i_file.read().splitlines()\n    else:\n        background = background.splitlines()\n    final_background = \"\"\n    for line in background:\n        if line == \"\":\n            final_background += r\"\\\\\" + \"\\n\\n\"\n            continue\n        final_background += latex.wrap_lines(latex.sanitize_tex(line))\n    return final_background",
    "docstring": "Formats the background section\n\n    :param background: the background content or file.\n\n    :type background: str or file\n\n    :returns: the background content.\n    :rtype: str"
  },
  {
    "code": "def published(self, request=None):\n        language = getattr(request, 'LANGUAGE_CODE', get_language())\n        if not language:\n            return self.model.objects.none()\n        qs = self.get_queryset()\n        qs = qs.filter(\n            translations__is_published=True,\n            translations__language_code=language,\n        )\n        qs = qs.filter(\n            models.Q(category__isnull=True) |\n            models.Q(category__is_published=True))\n        return qs",
    "docstring": "Returns the published documents in the current language.\n\n        :param request: A Request instance."
  },
  {
    "code": "def acquire_account(self, account=None, owner=None):\n        with self.unlock_cond:\n            if len(self.accounts) == 0:\n                raise ValueError('account pool is empty')\n            if account:\n                while account not in self.unlocked_accounts:\n                    self.unlock_cond.wait()\n                self.unlocked_accounts.remove(account)\n            else:\n                while len(self.unlocked_accounts) == 0:\n                    self.unlock_cond.wait()\n                account = self.unlocked_accounts.popleft()\n            if owner is not None:\n                self.owner2account[owner].append(account)\n                self.account2owner[account] = owner\n            account.acquire(False)\n            self.unlock_cond.notify_all()\n            return account",
    "docstring": "Waits until an account becomes available, then locks and returns it.\n        If an account is not passed, the next available account is returned.\n\n        :type  account: Account\n        :param account: The account to be acquired, or None.\n        :type  owner: object\n        :param owner: An optional descriptor for the owner.\n        :rtype:  :class:`Account`\n        :return: The account that was acquired."
  },
  {
    "code": "def as_dictionary(self, is_proof=True):\n        if self._created is None:\n            self._created = DDO._get_timestamp()\n        data = {\n            '@context': DID_DDO_CONTEXT_URL,\n            'id': self._did,\n            'created': self._created,\n        }\n        if self._public_keys:\n            values = []\n            for public_key in self._public_keys:\n                values.append(public_key.as_dictionary())\n            data['publicKey'] = values\n        if self._authentications:\n            values = []\n            for authentication in self._authentications:\n                values.append(authentication)\n            data['authentication'] = values\n        if self._services:\n            values = []\n            for service in self._services:\n                values.append(service.as_dictionary())\n            data['service'] = values\n        if self._proof and is_proof:\n            data['proof'] = self._proof\n        return data",
    "docstring": "Return the DDO as a JSON dict.\n\n        :param if is_proof: if False then do not include the 'proof' element.\n        :return: dict"
  },
  {
    "code": "def parse_component_by_typename(self, node, type_):\n        if 'id' in node.lattrib:\n            id_ = node.lattrib['id']\n        else:\n            id_ = node.tag\n        if 'type' in node.lattrib:\n            type_ = node.lattrib['type']\n        else:\n            type_ = node.tag\n        component = Component(id_, type_)\n        if self.current_component:\n            component.set_parent_id(self.current_component.id)\n            self.current_component.add_child(component)\n        else:\n            self.model.add_component(component)\n        for key in node.attrib:\n            if key.lower() not in ['id', 'type']:\n                component.set_parameter(key, node.attrib[key])\n        old_component = self.current_component\n        self.current_component = component\n        self.process_nested_tags(node, 'component')\n        self.current_component = old_component",
    "docstring": "Parses components defined directly by component name.\n\n        @param node: Node containing the <Component> element\n        @type node: xml.etree.Element\n\n        @param type_: Type of this component.\n        @type type_: string\n\n        @raise ParseError: Raised when the component does not have an id."
  },
  {
    "code": "def write_pre_script(self,fh):\n    if self.__pre_script:\n      fh.write( 'SCRIPT PRE ' + str(self) + ' ' + self.__pre_script + ' ' +\n        ' '.join(self.__pre_script_args) + '\\n' )",
    "docstring": "Write the pre script for the job, if there is one\n    @param fh: descriptor of open DAG file."
  },
  {
    "code": "def deserialize(serial_data: dict) -> 'Response':\n        r = Response(serial_data.get('id'))\n        r.data.update(serial_data.get('data', {}))\n        r.ended = serial_data.get('ended', False)\n        r.failed = not serial_data.get('success', True)\n        def load_messages(message_type: str):\n            messages = [\n                ResponseMessage(**data)\n                for data in serial_data.get(message_type, [])\n            ]\n            setattr(r, message_type, getattr(r, message_type) + messages)\n        load_messages('errors')\n        load_messages('warnings')\n        load_messages('messages')\n        return r",
    "docstring": "Converts a serialized dictionary response to a Response object"
  },
  {
    "code": "def get_instance(self, payload):\n        return UserInstance(self._version, payload, service_sid=self._solution['service_sid'], )",
    "docstring": "Build an instance of UserInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.chat.v2.service.user.UserInstance\n        :rtype: twilio.rest.chat.v2.service.user.UserInstance"
  },
  {
    "code": "def get_projected_fantasy_defense_game_stats_by_week(self, season, week):\n        result = self._method_call(\"FantasyDefenseProjectionsByGame/{season}/{week}\", \"projections\", season=season, week=week)\n        return result",
    "docstring": "Projected Fantasy Defense Game Stats by Week"
  },
  {
    "code": "def fileinfo(fileobj, filename=None, content_type=None, existing=None):\n        return _FileInfo(fileobj, filename, content_type).get_info(existing)",
    "docstring": "Tries to extract from the given input the actual file object, filename and content_type\n\n        This is used by the create and replace methods to correctly deduce their parameters\n        from the available information when possible."
  },
  {
    "code": "def calc_qar_v1(self):\n    der = self.parameters.derived.fastaccess\n    flu = self.sequences.fluxes.fastaccess\n    log = self.sequences.logs.fastaccess\n    for idx in range(der.nmb):\n        flu.qar[idx] = 0.\n        for jdx in range(der.ar_order[idx]):\n            flu.qar[idx] += der.ar_coefs[idx, jdx] * log.logout[idx, jdx]",
    "docstring": "Calculate the discharge responses of the different AR processes.\n\n    Required derived parameters:\n      |Nmb|\n      |AR_Order|\n      |AR_Coefs|\n\n    Required log sequence:\n      |LogOut|\n\n    Calculated flux sequence:\n      |QAR|\n\n    Examples:\n\n        Assume there are four response functions, involving zero, one, two,\n        and three AR coefficients respectively:\n\n        >>> from hydpy.models.arma import *\n        >>> parameterstep()\n        >>> derived.nmb(4)\n        >>> derived.ar_order.shape = 4\n        >>> derived.ar_order = 0, 1, 2, 3\n        >>> derived.ar_coefs.shape = (4, 3)\n        >>> logs.logout.shape = (4, 3)\n        >>> fluxes.qar.shape = 4\n\n        The coefficients of the different AR processes are stored in\n        separate rows of the 2-dimensional parameter `ma_coefs`.\n        Note the special case of the first AR process of zero order\n        (first row), which involves no autoregressive memory at all:\n\n        >>> derived.ar_coefs = ((nan, nan, nan),\n        ...                     (1.0, nan, nan),\n        ...                     (0.8, 0.2, nan),\n        ...                     (0.5, 0.3, 0.2))\n\n        The \"memory values\" of the different AR processes are defined as\n        follows (one row for each process).  The values of the last time\n        step are stored in first column, the values of the last time step\n        in the second column, and so on:\n\n        >>> logs.logout = ((nan, nan, nan),\n        ...                (1.0, nan, nan),\n        ...                (2.0, 3.0, nan),\n        ...                (4.0, 5.0, 6.0))\n\n        Applying method |calc_qar_v1| is equivalent to calculating the\n        inner product of the different rows of both matrices:\n\n        >>> model.calc_qar_v1()\n        >>> fluxes.qar\n        qar(0.0, 1.0, 2.2, 4.7)"
  },
  {
    "code": "def missing_node_cache(prov_dir, node_list, provider, opts):\n    cached_nodes = []\n    for node in os.listdir(prov_dir):\n        cached_nodes.append(os.path.splitext(node)[0])\n    for node in cached_nodes:\n        if node not in node_list:\n            delete_minion_cachedir(node, provider, opts)\n            if 'diff_cache_events' in opts and opts['diff_cache_events']:\n                fire_event(\n                    'event',\n                    'cached node missing from provider',\n                    'salt/cloud/{0}/cache_node_missing'.format(node),\n                    args={'missing node': node},\n                    sock_dir=opts.get(\n                        'sock_dir',\n                        os.path.join(__opts__['sock_dir'], 'master')),\n                    transport=opts.get('transport', 'zeromq')\n                )",
    "docstring": "Check list of nodes to see if any nodes which were previously known about\n    in the cache have been removed from the node list.\n\n    This function will only run if configured to do so in the main Salt Cloud\n    configuration file (normally /etc/salt/cloud).\n\n    .. code-block:: yaml\n\n        diff_cache_events: True\n\n    .. versionadded:: 2014.7.0"
  },
  {
    "code": "def compute_header_hmac_hash(context):\n    return hmac.new(\n        hashlib.sha512(\n            b'\\xff' * 8 +\n            hashlib.sha512(\n                context._.header.value.dynamic_header.master_seed.data +\n                context.transformed_key +\n                b'\\x01'\n            ).digest()\n        ).digest(),\n        context._.header.data,\n        hashlib.sha256\n    ).digest()",
    "docstring": "Compute HMAC-SHA256 hash of header.\n    Used to prevent header tampering."
  },
  {
    "code": "def rtt_write(self, buffer_index, data):\n        buf_size = len(data)\n        buf = (ctypes.c_ubyte * buf_size)(*bytearray(data))\n        bytes_written = self._dll.JLINK_RTTERMINAL_Write(buffer_index, buf, buf_size)\n        if bytes_written < 0:\n            raise errors.JLinkRTTException(bytes_written)\n        return bytes_written",
    "docstring": "Writes data to the RTT buffer.\n\n        This method will write at most len(data) bytes to the specified RTT\n        buffer.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          buffer_index (int): the index of the RTT buffer to write to\n          data (list): the list of bytes to write to the RTT buffer\n\n        Returns:\n          The number of bytes successfully written to the RTT buffer.\n\n        Raises:\n          JLinkRTTException if the underlying JLINK_RTTERMINAL_Write call fails."
  },
  {
    "code": "def delete_error_message(sender, instance, name, source, target, **kwargs):\n    if source != StateMixin.States.ERRED:\n        return\n    instance.error_message = ''\n    instance.save(update_fields=['error_message'])",
    "docstring": "Delete error message if instance state changed from erred"
  },
  {
    "code": "def parse_row(self):\n        fields = self.mapping\n        for i, cell in enumerate(self.row[0:len(fields)]):\n            field_name, field_type = fields[str(i)]\n            parsed_cell = self.clean_cell(cell, field_type)\n            self.parsed_row[field_name] = parsed_cell",
    "docstring": "Parses a row, cell-by-cell, returning a dict of field names\n        to the cleaned field values."
  },
  {
    "code": "def peer_retrieve(key, relation_name='cluster'):\n    cluster_rels = relation_ids(relation_name)\n    if len(cluster_rels) > 0:\n        cluster_rid = cluster_rels[0]\n        return relation_get(attribute=key, rid=cluster_rid,\n                            unit=local_unit())\n    else:\n        raise ValueError('Unable to detect'\n                         'peer relation {}'.format(relation_name))",
    "docstring": "Retrieve a named key from peer relation `relation_name`."
  },
  {
    "code": "def download(self, song):\n\t\tsong_id = song['id']\n\t\tresponse = self._call(\n\t\t\tmm_calls.Export,\n\t\t\tself.uploader_id,\n\t\t\tsong_id)\n\t\taudio = response.body\n\t\tsuggested_filename = unquote(\n\t\t\tresponse.headers['Content-Disposition'].split(\"filename*=UTF-8''\")[-1]\n\t\t)\n\t\treturn (audio, suggested_filename)",
    "docstring": "Download a song from a Google Music library.\n\n\t\tParameters:\n\t\t\tsong (dict): A song dict.\n\n\t\tReturns:\n\t\t\ttuple: Song content as bytestring, suggested filename."
  },
  {
    "code": "def _handle_empty(self, user, response):\n        if len(response.keys()) == 0:\n            response = self.show_user(user)\n            if len(response) == 0:\n                response = self.show_user(user)\n        return response",
    "docstring": "Apollo likes to return empty user arrays, even when you REALLY\n        want a user response back... like creating a user."
  },
  {
    "code": "def update_repository_config_acl(namespace, config, snapshot_id, acl_updates):\n    uri = \"configurations/{0}/{1}/{2}/permissions\".format(namespace,\n                                                config, snapshot_id)\n    return __post(uri, json=acl_updates)",
    "docstring": "Set configuration permissions.\n\n    The configuration should exist in the methods repository.\n\n    Args:\n        namespace (str): Configuration namespace\n        config (str): Configuration name\n        snapshot_id (int): snapshot_id of the method\n        acl_updates (list(dict)): List of access control updates\n\n    Swagger:\n        https://api.firecloud.org/#!/Method_Repository/setConfigACL"
  },
  {
    "code": "def all_linked_artifacts_exist(self):\n    if not self.has_resolved_artifacts:\n      return False\n    for path in self.resolved_artifact_paths:\n      if not os.path.isfile(path):\n        return False\n    else:\n      return True",
    "docstring": "All of the artifact paths for this resolve point to existing files."
  },
  {
    "code": "def show_letter(letter, text_color=None, back_color=None):\n    text_color = text_color or [255, 255, 255]\n    back_color = back_color or [0, 0, 0]\n    _sensehat.show_letter(letter, text_color, back_color)\n    return {'letter': letter}",
    "docstring": "Displays a single letter on the LED matrix.\n\n    letter\n        The letter to display\n    text_color\n        The color in which the letter is shown. Defaults to '[255, 255, 255]' (white).\n    back_color\n        The background color of the display. Defaults to '[0, 0, 0]' (black).\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'raspberry' sensehat.show_letter O\n        salt 'raspberry' sensehat.show_letter X '[255, 0, 0]'\n        salt 'raspberry' sensehat.show_letter B '[0, 0, 255]' '[255, 255, 0]'"
  },
  {
    "code": "def get_as_nullable_datetime(self, key):\n        value = self.get(key)\n        return DateTimeConverter.to_nullable_datetime(value)",
    "docstring": "Converts map element into a Date or returns None if conversion is not possible.\n\n        :param key: an index of element to get.\n\n        :return: Date value of the element or None if conversion is not supported."
  },
  {
    "code": "def safe_process_files(path, files, args, state):\n    for fn in files:\n        full_fn = os.path.join(path, fn)\n        try:\n            if not process_file(path, fn, args, state):\n                return False\n        except Exception, e:\n            sys.stderr.write(\"error: %s\\n%s\\n\" % (os.path.join(path, fn), traceback.format_exc()))\n            state.log_failed(full_fn)\n        if state.should_quit():\n            return False\n    return True",
    "docstring": "Process a number of files in a directory. Catches any exception from the\n    processing and checks if we should fail directly or keep going."
  },
  {
    "code": "def _init_titles(self):\n        super(ModelRestApi, self)._init_titles()\n        class_name = self.datamodel.model_name\n        if not self.list_title:\n            self.list_title = \"List \" + self._prettify_name(class_name)\n        if not self.add_title:\n            self.add_title = \"Add \" + self._prettify_name(class_name)\n        if not self.edit_title:\n            self.edit_title = \"Edit \" + self._prettify_name(class_name)\n        if not self.show_title:\n            self.show_title = \"Show \" + self._prettify_name(class_name)\n        self.title = self.list_title",
    "docstring": "Init Titles if not defined"
  },
  {
    "code": "def create_detector(self, detector):\n        resp = self._post(self._u(self._DETECTOR_ENDPOINT_SUFFIX),\n                          data=detector)\n        resp.raise_for_status()\n        return resp.json()",
    "docstring": "Creates a new detector.\n\n        Args:\n            detector (object): the detector model object. Will be serialized as\n                JSON.\n        Returns:\n            dictionary of the response (created detector model)."
  },
  {
    "code": "def get_sections_2d(self):\n        sections_hdrgos_act = []\n        hdrgos_act_all = self.get_hdrgos()\n        hdrgos_act_secs = set()\n        if self.hdrobj.sections:\n            for section_name, hdrgos_all_lst in self.hdrobj.sections:\n                hdrgos_all_set = set(hdrgos_all_lst)\n                hdrgos_act_set = hdrgos_all_set.intersection(hdrgos_act_all)\n                if hdrgos_act_set:\n                    hdrgos_act_secs |= hdrgos_act_set\n                    hdrgos_act_lst = []\n                    hdrgos_act_ctr = cx.Counter()\n                    for hdrgo_p in hdrgos_all_lst:\n                        if hdrgo_p in hdrgos_act_set and hdrgos_act_ctr[hdrgo_p] == 0:\n                            hdrgos_act_lst.append(hdrgo_p)\n                        hdrgos_act_ctr[hdrgo_p] += 1\n                    sections_hdrgos_act.append((section_name, hdrgos_act_lst))\n            hdrgos_act_rem = hdrgos_act_all.difference(hdrgos_act_secs)\n            if hdrgos_act_rem:\n                sections_hdrgos_act.append((self.hdrobj.secdflt, hdrgos_act_rem))\n        else:\n            sections_hdrgos_act.append((self.hdrobj.secdflt, hdrgos_act_all))\n        return sections_hdrgos_act",
    "docstring": "Get 2-D list of sections and hdrgos sets actually used in grouping."
  },
  {
    "code": "def incomplete(transaction):\n        transaction.block_transfer = True\n        transaction.response = Response()\n        transaction.response.destination = transaction.request.source\n        transaction.response.token = transaction.request.token\n        transaction.response.code = defines.Codes.REQUEST_ENTITY_INCOMPLETE.number\n        return transaction",
    "docstring": "Notifies incomplete blockwise exchange.\n\n        :type transaction: Transaction\n        :param transaction: the transaction that owns the response\n        :rtype : Transaction\n        :return: the edited transaction"
  },
  {
    "code": "def _logger_levels(self):\n        return {\n            'debug': logging.DEBUG,\n            'info': logging.INFO,\n            'warning': logging.WARNING,\n            'error': logging.ERROR,\n            'critical': logging.CRITICAL,\n        }",
    "docstring": "Return log levels."
  },
  {
    "code": "def GetFeedItems(client, feed):\n  feed_item_service = client.GetService('FeedItemService', 'v201809')\n  feed_items = []\n  more_pages = True\n  selector = {\n      'fields': ['FeedItemId', 'AttributeValues'],\n      'predicates': [\n          {\n              'field': 'Status',\n              'operator': 'EQUALS',\n              'values': ['ENABLED']\n          },\n          {\n              'field': 'FeedId',\n              'operator': 'EQUALS',\n              'values': [feed['id']]\n          }\n      ],\n      'paging': {\n          'startIndex': 0,\n          'numberResults': PAGE_SIZE\n      }\n  }\n  while more_pages:\n    page = feed_item_service.get(selector)\n    if 'entries' in page:\n      feed_items.extend(page['entries'])\n    selector['paging']['startIndex'] += PAGE_SIZE\n    more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries'])\n  return feed_items",
    "docstring": "Returns the Feed Items for a given Feed.\n\n  Args:\n    client: an AdWordsClient instance.\n    feed: the Feed we are retrieving Feed Items from.\n\n  Returns:\n    The Feed Items associated with the given Feed."
  },
  {
    "code": "def compute_offset_to_first_complete_codon(\n        offset_to_first_complete_reference_codon,\n        n_trimmed_from_reference_sequence):\n    if n_trimmed_from_reference_sequence <= offset_to_first_complete_reference_codon:\n        return (\n            offset_to_first_complete_reference_codon -\n            n_trimmed_from_reference_sequence)\n    else:\n        n_nucleotides_trimmed_after_first_codon = (\n            n_trimmed_from_reference_sequence -\n            offset_to_first_complete_reference_codon)\n        frame = n_nucleotides_trimmed_after_first_codon % 3\n        return (3 - frame) % 3",
    "docstring": "Once we've aligned the variant sequence to the ReferenceContext, we need\n    to transfer reading frame from the reference transcripts to the variant\n    sequences.\n\n    Parameters\n    ----------\n    offset_to_first_complete_reference_codon : int\n\n    n_trimmed_from_reference_sequence : int\n\n    Returns an offset into the variant sequence that starts from a complete\n    codon."
  },
  {
    "code": "def get_time_buckets(start, end):\n        d = DatalakeRecord.TIME_BUCKET_SIZE_IN_MS\n        first_bucket = start / d\n        last_bucket = end / d\n        return list(range(\n            int(first_bucket),\n            int(last_bucket) + 1))",
    "docstring": "get the time buckets spanned by the start and end times"
  },
  {
    "code": "def get_recent_async(self, count, callback):\n        validate_nonnegative_int(count, 'count')\n        Validation.callable_check(callback, allow_none=True)\n        evt = self._client._request_sub_recent(self.subid, count=count)\n        self._client._add_recent_cb_for(evt, callback)\n        return evt",
    "docstring": "Similar to `get_recent` except instead of returning an iterable, passes each dict to the given function which\n        must accept a single argument. Returns the request.\n\n        `callback` (mandatory) (function) instead of returning an iterable, pass each dict (as described above) to the\n        given function which must accept a single argument. Nothing is returned."
  },
  {
    "code": "def _cs_path_exists(fspath):\n        if not os.path.exists(fspath):\n            return False\n        abspath = os.path.abspath(fspath)\n        directory, filename = os.path.split(abspath)\n        return filename in os.listdir(directory)",
    "docstring": "Case-sensitive path existence check\n\n        >>> sdist_add_defaults._cs_path_exists(__file__)\n        True\n        >>> sdist_add_defaults._cs_path_exists(__file__.upper())\n        False"
  },
  {
    "code": "def create_slug(self):\n        name = self.slug_source\n        counter = 0\n        while True:\n            if counter == 0:\n                slug = slugify(name)\n            else:\n                slug = slugify('{0} {1}'.format(name, str(counter)))\n            try:\n                self.__class__.objects.exclude(pk=self.pk).get(slug=slug)\n                counter += 1\n            except ObjectDoesNotExist:\n                break\n        return slug",
    "docstring": "Creates slug, checks if slug is unique, and loop if not"
  },
  {
    "code": "def walk_data(cls, dist, path='/'):\n    for rel_fn in filter(None, dist.resource_listdir(path)):\n      full_fn = os.path.join(path, rel_fn)\n      if dist.resource_isdir(full_fn):\n        for fn, stream in cls.walk_data(dist, full_fn):\n          yield fn, stream\n      else:\n        yield full_fn[1:], dist.get_resource_stream(dist._provider, full_fn)",
    "docstring": "Yields filename, stream for files identified as data in the distribution"
  },
  {
    "code": "def get_fw_extractor(fw_file):\n    fw_img_extractor = FirmwareImageExtractor(fw_file)\n    extension = fw_img_extractor.fw_file_ext.lower()\n    if extension == '.scexe':\n        fw_img_extractor._do_extract = types.MethodType(\n            _extract_scexe_file, fw_img_extractor)\n    elif extension == '.rpm':\n        fw_img_extractor._do_extract = types.MethodType(\n            _extract_rpm_file, fw_img_extractor)\n    elif extension in RAW_FIRMWARE_EXTNS:\n        def dummy_extract(self):\n            return fw_img_extractor.fw_file, False\n        fw_img_extractor.extract = types.MethodType(\n            dummy_extract, fw_img_extractor)\n    else:\n        raise exception.InvalidInputError(\n            'Unexpected compact firmware file type: %s' % fw_file)\n    return fw_img_extractor",
    "docstring": "Gets the firmware extractor object fine-tuned for specified type\n\n    :param fw_file: compact firmware file to be extracted from\n    :raises: InvalidInputError, for unsupported file types\n    :returns: FirmwareImageExtractor object"
  },
  {
    "code": "def get(self, path, params=None):\n        resp = self._session.get(path, params=params)\n        if resp.status_code != 200:\n            if resp.headers.get('Content-Type', '').startswith('text/html'):\n                text = resp.reason\n            else:\n                text = resp.text\n            raise requests.HTTPError('Error accessing {0}\\n'\n                                     'Server Error ({1:d}: {2})'.format(resp.request.url,\n                                                                        resp.status_code,\n                                                                        text))\n        return resp",
    "docstring": "Make a GET request, optionally including a parameters, to a path.\n\n        The path of the request is the full URL.\n\n        Parameters\n        ----------\n        path : str\n            The URL to request\n        params : DataQuery, optional\n            The query to pass when making the request\n\n        Returns\n        -------\n        resp : requests.Response\n            The server's response to the request\n\n        Raises\n        ------\n        HTTPError\n            If the server returns anything other than a 200 (OK) code\n\n        See Also\n        --------\n        get_query, get"
  },
  {
    "code": "def graph_from_adjacency_matrix(matrix, node_prefix='', directed=False):\n    node_orig = 1\n    if directed:\n        graph = Dot(graph_type='digraph')\n    else:\n        graph = Dot(graph_type='graph')\n    for row in matrix:\n        if not directed:\n            skip = matrix.index(row)\n            r = row[skip:]\n        else:\n            skip = 0\n            r = row\n        node_dest = skip + 1\n        for e in r:\n            if e:\n                graph.add_edge(\n                    Edge(\n                        node_prefix + node_orig,\n                        node_prefix + node_dest))\n            node_dest += 1\n        node_orig += 1\n    return graph",
    "docstring": "Creates a basic graph out of an adjacency matrix.\n\n    The matrix has to be a list of rows of values\n    representing an adjacency matrix.\n    The values can be anything: bool, int, float, as long\n    as they can evaluate to True or False."
  },
  {
    "code": "def _get_args(self, kwargs):\n        _args = list()\n        _kwargs = salt.utils.args.clean_kwargs(**kwargs)\n        return _args, _kwargs",
    "docstring": "Discard all keywords which aren't function-specific from the kwargs.\n\n        :param kwargs:\n        :return:"
  },
  {
    "code": "def update_fp(self, fp, length):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('Inode is not yet initialized')\n        self.original_data_location = self.DATA_IN_EXTERNAL_FP\n        self.data_fp = fp\n        self.data_length = length\n        self.fp_offset = 0",
    "docstring": "Update the Inode to use a different file object and length.\n\n        Parameters:\n         fp - A file object that contains the data for this Inode.\n         length - The length of the data.\n        Returns:\n         Nothing."
  },
  {
    "code": "def extra(name: str, desc: str) -> Callable:\n    def attr_dec(f):\n        f.__setattr__(\"extra_fn\", True)\n        f.__setattr__(\"name\", name)\n        f.__setattr__(\"desc\", desc)\n        return f\n    return attr_dec",
    "docstring": "Decorator for slave channel's \"additional features\" interface.\n\n    Args:\n        name (str): A human readable name for the function.\n        desc (str): A short description and usage of it. Use\n            ``{function_name}`` in place of the function name\n            in the description.\n\n    Returns:\n        The decorated method."
  },
  {
    "code": "def load_characters(self):\n    characters_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(self.id) + u'/' + utilities.urlencode(self.title) + u'/characters').text\n    self.set(self.parse_characters(utilities.get_clean_dom(characters_page)))\n    return self",
    "docstring": "Fetches the MAL media characters page and sets the current media's character attributes.\n\n    :rtype: :class:`.Media`\n    :return: current media object."
  },
  {
    "code": "def deprecated(message):\n    def f__(f):\n        def f_(*args, **kwargs):\n            from warnings import warn\n            warn(message, category=DeprecationWarning, stacklevel=2)\n            return f(*args, **kwargs)\n        f_.__name__ = f.__name__\n        f_.__doc__ = f.__doc__\n        f_.__dict__.update(f.__dict__)\n        return f_\n    return f__",
    "docstring": "Decorator for deprecating functions and methods.\n\n    ::\n\n        @deprecated(\"'foo' has been deprecated in favour of 'bar'\")\n        def foo(x):\n            pass"
  },
  {
    "code": "def _get_balance(self):\n        response = self.session.get(self.balance_url, verify=False)\n        soup = BeautifulSoup(response.text, 'html.parser')\n        first_line = soup.select(\n            \"table.data tr:nth-of-type(2)\")[0].text.strip().split('\\n')\n        total, today = first_line[-2:]\n        logging.info('%-26sTotal:%-8s', today, total)\n        return '\\n'.join([u\"Today: {0}\".format(today),\n                          \"Total: {0}\".format(total)])",
    "docstring": "Get to know how much you totally have and how much you get today."
  },
  {
    "code": "def text_search(self, text, sort=None, offset=100, page=1):\n        assert page >= 1, f'Invalid page value {page}. Required page >= 1.'\n        payload = {\"text\": text, \"sort\": sort, \"offset\": offset, \"page\": page}\n        response = self.requests_session.get(\n            f'{self.url}/query',\n            params=payload,\n            headers=self._headers\n        )\n        if response.status_code == 200:\n            return self._parse_search_response(response.content)\n        else:\n            raise Exception(f'Unable to search for DDO: {response.content}')",
    "docstring": "Search in aquarius using text query.\n\n        Given the string aquarius will do a full-text query to search in all documents.\n\n        Currently implemented are the MongoDB and Elastic Search drivers.\n\n        For a detailed guide on how to search, see the MongoDB driver documentation:\n        mongodb driverCurrently implemented in:\n        https://docs.mongodb.com/manual/reference/operator/query/text/\n\n        And the Elastic Search documentation:\n        https://www.elastic.co/guide/en/elasticsearch/guide/current/full-text-search.html\n        Other drivers are possible according to each implementation.\n\n        :param text: String to be search.\n        :param sort: 1/-1 to sort ascending or descending.\n        :param offset: Integer with the number of elements displayed per page.\n        :param page: Integer with the number of page.\n        :return: List of DDO instance"
  },
  {
    "code": "def get(name, import_str=False):\n    value = None\n    default_value = getattr(default_settings, name)\n    try:\n        value = getattr(settings, name)\n    except AttributeError:\n        if name in default_settings.required_attrs:\n            raise Exception('You must set ' + name + ' in your settings.')\n    if isinstance(default_value, dict) and value:\n        default_value.update(value)\n        value = default_value\n    else:\n        if value is None:\n            value = default_value\n        value = import_from_str(value) if import_str else value\n    return value",
    "docstring": "Helper function to use inside the package."
  },
  {
    "code": "def append_field(self, fieldname):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('RR record not yet initialized!')\n        if fieldname == 'PX':\n            bit = 0\n        elif fieldname == 'PN':\n            bit = 1\n        elif fieldname == 'SL':\n            bit = 2\n        elif fieldname == 'NM':\n            bit = 3\n        elif fieldname == 'CL':\n            bit = 4\n        elif fieldname == 'PL':\n            bit = 5\n        elif fieldname == 'RE':\n            bit = 6\n        elif fieldname == 'TF':\n            bit = 7\n        else:\n            raise pycdlibexception.PyCdlibInternalError('Unknown RR field name %s' % (fieldname))\n        self.rr_flags |= (1 << bit)",
    "docstring": "Mark a field as present in the Rock Ridge records.\n\n        Parameters:\n         fieldname - The name of the field to mark as present; should be one\n                     of 'PX', 'PN', 'SL', 'NM', 'CL', 'PL', 'RE', or 'TF'.\n        Returns:\n         Nothing."
  },
  {
    "code": "def entropy_bits(\n            lst: Union[\n                List[Union[int, str, float, complex]],\n                Tuple[Union[int, str, float, complex]]\n            ]\n    ) -> float:\n        if not isinstance(lst, (tuple, list)):\n            raise TypeError('lst must be a list or a tuple')\n        size = len(lst)\n        if (\n                size == 2\n                and isinstance(lst[0], (int, float))\n                and isinstance(lst[1], (int, float))\n        ):\n            return calc_entropy_bits_nrange(lst[0], lst[1])\n        return calc_entropy_bits(lst)",
    "docstring": "Calculate the entropy of a wordlist or a numerical range.\n\n        Keyword arguments:\n        lst -- A wordlist as list or tuple, or a numerical range as a list:\n        (minimum, maximum)"
  },
  {
    "code": "def _brightness(x, change:uniform):\n    \"Apply `change` in brightness of image `x`.\"\n    return x.add_(scipy.special.logit(change))",
    "docstring": "Apply `change` in brightness of image `x`."
  },
  {
    "code": "def GenerateConfigFile(load_hook, dump_hook, **kwargs) -> ConfigFile:\n    def ConfigFileGenerator(filename, safe_load: bool=True):\n        cfg = ConfigFile(fd=filename, load_hook=load_hook, dump_hook=dump_hook, safe_load=safe_load, **kwargs)\n        return cfg\n    return ConfigFileGenerator",
    "docstring": "Generates a ConfigFile object using the specified hooks.\n\n    These hooks should be functions, and have one argument.\n    When a hook is called, the ConfigFile object is passed to it. Use this to load your data from the fd object, or request, or whatever.\n\n    This returns a ConfigFile object."
  },
  {
    "code": "def rollback(cls, bigchain, new_height, txn_ids):\n        bigchain.delete_elections(new_height)\n        txns = [bigchain.get_transaction(tx_id) for tx_id in txn_ids]\n        elections = cls._get_votes(txns)\n        for election_id in elections:\n            election = bigchain.get_transaction(election_id)\n            election.on_rollback(bigchain, new_height)",
    "docstring": "Looks for election and vote transactions inside the block and\n           cleans up the database artifacts possibly created in `process_blocks`.\n\n           Part of the `end_block`/`commit` crash recovery."
  },
  {
    "code": "async def _bind_key_to_queue(self, routing_key: AnyStr, queue_name: AnyStr) -> None:\n        logger.info(\"Binding key='%s'\", routing_key)\n        result = await self._channel.queue_bind(\n            exchange_name=self._exchange_name,\n            queue_name=queue_name,\n            routing_key=routing_key,\n        )\n        return result",
    "docstring": "Bind to queue with specified routing key.\n\n        :param routing_key: Routing key to bind with.\n        :param queue_name: Name of the queue\n        :return: Does not return anything"
  },
  {
    "code": "def import_enum(dest, src, name):\n    dest.enums[name] = src.enums[name]",
    "docstring": "Import Enum `name` from Registry `src` to Registry `dest`.\n\n    :param Registry dest: Destination Registry\n    :param Registry src: Source Registry\n    :param str name: Name of Enum to import"
  },
  {
    "code": "def create(self, username, password, tags=''):\n        user_payload = json.dumps({\n            'password': password,\n            'tags': tags\n        })\n        return self.http_client.put(API_USER % username,\n                                    payload=user_payload)",
    "docstring": "Create User.\n\n        :param str username: Username\n        :param str password: Password\n        :param str tags: Comma-separate list of tags (e.g. monitoring)\n\n        :rtype: None"
  },
  {
    "code": "def _process_key(evt):\n    key = evt.GetKeyCode()\n    if key in KEYMAP:\n        return KEYMAP[key], ''\n    if 97 <= key <= 122:\n        key -= 32\n    if key >= 32 and key <= 127:\n        return keys.Key(chr(key)), chr(key)\n    else:\n        return None, None",
    "docstring": "Helper to convert from wx keycode to vispy keycode"
  },
  {
    "code": "def format_number(\n        x, use_rounding=True, is_population=False, coefficient=1):\n    if use_rounding:\n        x = rounding(x, is_population)\n    x //= coefficient\n    number = add_separators(x)\n    return number",
    "docstring": "Format a number according to the standards.\n\n    :param x: A number to be formatted in a locale friendly way.\n    :type x: int\n\n    :param use_rounding: Flag to enable a rounding.\n    :type use_rounding: bool\n\n    :param is_population: Flag if the number is population. It needs to be\n        used with enable_rounding.\n    :type is_population: bool\n\n    :param coefficient: Divide the result after the rounding.\n    :type coefficient:float\n\n    :returns: A locale friendly formatted string e.g. 1,000,0000.00\n        representing the original x. If a ValueError exception occurs,\n        x is simply returned.\n    :rtype: basestring"
  },
  {
    "code": "def wrap_json(func=None, *, encoder=json.JSONEncoder, preserve_raw_body=False):\n    if func is None:\n        return functools.partial(\n            wrap_json,\n            encoder=encoder,\n            preserve_raw_body=preserve_raw_body\n        )\n    wrapped_func = wrap_json_body(func, preserve_raw_body=preserve_raw_body)\n    wrapped_func = wrap_json_response(wrapped_func, encoder=encoder)\n    return wrapped_func",
    "docstring": "A middleware that parses the body of json requests and\n    encodes the json responses.\n\n    NOTE: this middleware exists just for backward compatibility,\n    but it has some limitations in terms of response body encoding\n    because it only accept list or dictionary outputs and json\n    specification allows store other values also.\n\n    It is recommended use the `wrap_json_body` and wrap_json_response`\n    instead of this."
  },
  {
    "code": "def _tokens_to_subtoken(self, tokens):\n        ret = []\n        for token in tokens:\n            ret.extend(\n                self._escaped_token_to_subtoken_strings(_escape_token(token, self._alphabet)))\n        return ret",
    "docstring": "Converts a list of tokens to a list of subtoken.\n\n        Args:\n          tokens: a list of strings.\n        Returns:\n          a list of integers in the range [0, vocab_size)"
  },
  {
    "code": "def show_member(self, member, **_params):\n        return self.get(self.member_path % (member), params=_params)",
    "docstring": "Fetches information of a certain load balancer member."
  },
  {
    "code": "def owned_expansions(self):\n        owned = {}\n        for el in self.expansion_locations:\n            def is_near_to_expansion(t):\n                return t.position.distance_to(el) < self.EXPANSION_GAP_THRESHOLD\n            th = next((x for x in self.townhalls if is_near_to_expansion(x)), None)\n            if th:\n                owned[el] = th\n        return owned",
    "docstring": "List of expansions owned by the player."
  },
  {
    "code": "def refresh_context(self):\n        User = self.model('res.user')\n        self.context = User.get_preferences(True)\n        return self.context",
    "docstring": "Get the default context of the user and save it"
  },
  {
    "code": "def record_to_objects(self, preference=None):\n        from ambry.orm.file import File\n        for f in self.list_records():\n            pref = preference if preference else f.record.preference\n            if pref == File.PREFERENCE.FILE:\n                self._bundle.logger.debug('   Cleaning objects for file {}'.format(f.path))\n                f.clean_objects()\n            if pref in (File.PREFERENCE.FILE, File.PREFERENCE.MERGE):\n                self._bundle.logger.debug('   rto {}'.format(f.path))\n                f.record_to_objects()",
    "docstring": "Create objects from files, or merge the files into the objects."
  },
  {
    "code": "def _makeflags(self):\n        if self.meta.makeflags in [\"on\", \"ON\"]:\n            cpus = multiprocessing.cpu_count()\n            os.environ[\"MAKEFLAGS\"] = \"-j{0}\".format(cpus)",
    "docstring": "Set variable MAKEFLAGS with the numbers of\n        processors"
  },
  {
    "code": "def _to_base36(number):\n    if number < 0:\n        raise ValueError(\"Cannot encode negative numbers\")\n    chars = \"\"\n    while number != 0:\n        number, i = divmod(number, 36)\n        chars = _alphabet[i] + chars\n    return chars or \"0\"",
    "docstring": "Convert a positive integer to a base36 string.\n\n    Taken from Stack Overflow and modified."
  },
  {
    "code": "def elements(self):\n        elements = []\n        for el in ct:\n            if isinstance(el[1], datapoint.Element.Element):\n                elements.append(el[1])\n        return elements",
    "docstring": "Return a list of the elements which are not None"
  },
  {
    "code": "def _observed_name(field, name):\n        if MARSHMALLOW_VERSION_INFO[0] < 3:\n            dump_to = getattr(field, \"dump_to\", None)\n            load_from = getattr(field, \"load_from\", None)\n            return dump_to or load_from or name\n        return field.data_key or name",
    "docstring": "Adjust field name to reflect `dump_to` and `load_from` attributes.\n\n        :param Field field: A marshmallow field.\n        :param str name: Field name\n        :rtype: str"
  },
  {
    "code": "def cmd_output_add(self, args):\n        device = args[0]\n        print(\"Adding output %s\" % device)\n        try:\n            conn = mavutil.mavlink_connection(device, input=False, source_system=self.settings.source_system)\n            conn.mav.srcComponent = self.settings.source_component\n        except Exception:\n            print(\"Failed to connect to %s\" % device)\n            return\n        self.mpstate.mav_outputs.append(conn)\n        try:\n            mp_util.child_fd_list_add(conn.port.fileno())\n        except Exception:\n            pass",
    "docstring": "add new output"
  },
  {
    "code": "def set_config(self, config):\n        self._configmixin_queue.append(copy.deepcopy(config))\n        self.new_config()",
    "docstring": "Update the component's configuration.\n\n        Use the :py:meth:`get_config` method to get a copy of the\n        component's configuration, update that copy then call\n        :py:meth:`set_config` to update the component. This enables\n        the configuration to be changed in a threadsafe manner while\n        the component is running, and allows several values to be\n        changed at once.\n\n        :param ConfigParent config: New configuration."
  },
  {
    "code": "def _warn_about_problematic_credentials(credentials):\n    from google.auth import _cloud_sdk\n    if credentials.client_id == _cloud_sdk.CLOUD_SDK_CLIENT_ID:\n        warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING)",
    "docstring": "Determines if the credentials are problematic.\n\n    Credentials from the Cloud SDK that are associated with Cloud SDK's project\n    are problematic because they may not have APIs enabled and have limited\n    quota. If this is the case, warn about it."
  },
  {
    "code": "def capture_logger(name):\n    import logging\n    logger = logging.getLogger(name)\n    try:\n        import StringIO\n        stream = StringIO.StringIO()\n    except ImportError:\n        from io import StringIO\n        stream = StringIO()\n    handler = logging.StreamHandler(stream)\n    logger.addHandler(handler)\n    try:\n        yield stream\n    finally:\n        logger.removeHandler(handler)",
    "docstring": "Context manager to capture a logger output with a StringIO stream."
  },
  {
    "code": "def _init_connection(self):\n        if not self.servers:\n            raise RuntimeError(\"No server defined\")\n        server = random.choice(self.servers)\n        if server.scheme in [\"http\", \"https\"]:\n            self.connection = http_connect(\n                [server for server in self.servers if server.scheme in [\"http\", \"https\"]],\n                timeout=self.timeout, basic_auth=self.basic_auth, max_retries=self.max_retries, retry_time=self.retry_time)\n            return\n        elif server.scheme == \"thrift\":\n            self.connection = thrift_connect(\n                [server for server in self.servers if server.scheme == \"thrift\"],\n                timeout=self.timeout, max_retries=self.max_retries, retry_time=self.retry_time)",
    "docstring": "Create initial connection pool"
  },
  {
    "code": "def brake_on(self):\n        data = []\n        data.append(0x0A)\n        data.append(self.servoid)\n        data.append(RAM_WRITE_REQ)\n        data.append(TORQUE_CONTROL_RAM)\n        data.append(0x01)\n        data.append(0x40)\n        send_data(data)",
    "docstring": "Set the Brakes of Herkulex\n\n        In braked mode, position control and velocity control\n        will not work, enable torque before that\n\n        Args:\n            none"
  },
  {
    "code": "def DiffPrimitiveArrays(self, oldObj, newObj):\n      if len(oldObj) != len(newObj):\n         __Log__.debug('DiffDoArrays: Array lengths do not match %d != %d'\n            % (len(oldObj), len(newObj)))\n         return False\n      match = True\n      if self._ignoreArrayOrder:\n         oldSet = oldObj and frozenset(oldObj) or frozenset()\n         newSet = newObj and frozenset(newObj) or frozenset()\n         match = (oldSet == newSet)\n      else:\n         for i, j in zip(oldObj, newObj):\n            if i != j:\n               match = False\n               break\n      if not match:\n         __Log__.debug(\n            'DiffPrimitiveArrays: One of the elements do not match.')\n         return False\n      return True",
    "docstring": "Diff two primitive arrays"
  },
  {
    "code": "def main_btn_clicked(self, widget, data=None):\n        self.remove_link_button()\n        data = dict()\n        data['debugging'] = self.debugging\n        self.run_window.hide()\n        self.parent.open_window(widget, data)",
    "docstring": "Button switches to Dev Assistant GUI main window"
  },
  {
    "code": "def transmit(self, channel, message):\n\t\ttarget = (\n\t\t\tself.slack.server.channels.find(channel)\n\t\t\tor self._find_user_channel(username=channel)\n\t\t)\n\t\tmessage = self._expand_references(message)\n\t\ttarget.send_message(message, thread=getattr(channel, 'thread', None))",
    "docstring": "Send the message to Slack.\n\n\t\t:param channel: channel or user to whom the message should be sent.\n\t\t\tIf a ``thread`` attribute is present, that thread ID is used.\n\t\t:param str message: message to send."
  },
  {
    "code": "def mont_pub_to_ed_pub(cls, mont_pub):\n        if not isinstance(mont_pub, bytes):\n            raise TypeError(\"Wrong type passed for the mont_pub parameter.\")\n        if len(mont_pub) != cls.MONT_PUB_KEY_SIZE:\n            raise ValueError(\"Invalid value passed for the mont_pub parameter.\")\n        return bytes(cls._mont_pub_to_ed_pub(bytearray(mont_pub)))",
    "docstring": "Derive a Twisted Edwards public key from given Montgomery public key.\n\n        :param mont_pub: A bytes-like object encoding the public key with length\n            MONT_PUB_KEY_SIZE.\n        :returns: A bytes-like object encoding the public key with length ED_PUB_KEY_SIZE."
  },
  {
    "code": "def _mount(device):\n    dest = tempfile.mkdtemp()\n    res = __states__['mount.mounted'](dest, device=device, fstype='btrfs',\n                                      opts='subvol=/', persist=False)\n    if not res['result']:\n        log.error('Cannot mount device %s in %s', device, dest)\n        _umount(dest)\n        return None\n    return dest",
    "docstring": "Mount the device in a temporary place."
  },
  {
    "code": "def _post_compute(self):\n        self._x_labels, self._y_labels = self._y_labels, self._x_labels\n        self._x_labels_major, self._y_labels_major = (\n            self._y_labels_major, self._x_labels_major\n        )\n        self._x_2nd_labels, self._y_2nd_labels = (\n            self._y_2nd_labels, self._x_2nd_labels\n        )\n        self.show_y_guides, self.show_x_guides = (\n            self.show_x_guides, self.show_y_guides\n        )",
    "docstring": "After computations transpose labels"
  },
  {
    "code": "def convert_to_ip(self):\n        self._values, self._header._unit = self._header.data_type.to_ip(\n                self._values, self._header.unit)",
    "docstring": "Convert the Data Collection to IP units."
  },
  {
    "code": "def getL2Representations(self):\n    return [set(L2.getSelf()._pooler.getActiveCells()) for L2 in self.L2Regions]",
    "docstring": "Returns the active representation in L2."
  },
  {
    "code": "def fix_post_relative_url(rel_url):\n        m = re.match(\n            r'^(?P<year>\\d{4})/(?P<month>\\d{1,2})/(?P<day>\\d{1,2})/'\n            r'(?P<post_name>[^/]+?)'\n            r'(?:(?:\\.html)|(?:/(?P<index>index(?:\\.html?)?)?))?$',\n            rel_url\n        )\n        if not m:\n            return None\n        year, month, day, post_name = m.groups()[:4]\n        try:\n            d = date(year=int(year), month=int(month), day=int(day))\n            return '/'.join((d.strftime('%Y/%m/%d'), post_name,\n                             'index.html' if m.group('index') else ''))\n        except (TypeError, ValueError):\n            return None",
    "docstring": "Fix post relative url to a standard, uniform format.\n\n        Possible input:\n        - 2016/7/8/my-post\n        - 2016/07/08/my-post.html\n        - 2016/8/09/my-post/\n        - 2016/8/09/my-post/index\n        - 2016/8/09/my-post/index.htm\n        - 2016/8/09/my-post/index.html\n\n        :param rel_url: relative url to fix\n        :return: fixed relative url, or None if cannot recognize"
  },
  {
    "code": "def _canonicalize_fraction(cls, non_repeating, repeating):\n        if repeating == []:\n            return (non_repeating, repeating)\n        repeat_len = len(repeating)\n        indices = range(len(non_repeating), -1, -repeat_len)\n        end = next(\n           i for i in indices if non_repeating[(i - repeat_len):i] != repeating\n        )\n        indices = range(min(repeat_len - 1, end), 0, -1)\n        index = next(\n           (i for i in indices \\\n              if repeating[-i:] == non_repeating[(end-i):end]),\n           0\n        )\n        return (\n           non_repeating[:(end - index)],\n           repeating[-index:] + repeating[:-index]\n        )",
    "docstring": "If the same fractional value can be represented by stripping repeating\n        part from ``non_repeating``, do it.\n\n        :param non_repeating: non repeating part of fraction\n        :type non_repeating: list of int\n        :param repeating: repeating part of fraction\n        :type repeating: list of int\n        :returns: new non_repeating and repeating parts\n        :rtype: tuple of list of int * list of int\n\n        Complexity: O(len(non_repeating))"
  },
  {
    "code": "def run(self):\n        self._prepare()\n        for recipe in self._recipes:\n            run_recipe = True\n            if not self.arguments.yes:\n                run_recipe = pypro.console.ask_bool('Run %s.%s' % (recipe.module, recipe.name), \"yes\")\n            if run_recipe:\n                recipe.run(self, self.arguments)\n        if self.arguments.verbose:\n            pypro.console.out('Thanks for using pypro. Support this project at https://github.com/avladev/pypro')",
    "docstring": "Starts recipes execution."
  },
  {
    "code": "def _shuffle(y, labels, random_state):\n    if labels is None:\n        ind = random_state.permutation(len(y))\n    else:\n        ind = np.arange(len(labels))\n        for label in np.unique(labels):\n            this_mask = (labels == label)\n            ind[this_mask] = random_state.permutation(ind[this_mask])\n    return y[ind]",
    "docstring": "Return a shuffled copy of y eventually shuffle among same labels."
  },
  {
    "code": "def load():\n    config = ConfigParser.RawConfigParser(DEFAULTS)\n    config.readfp(open(CONF_PATH))\n    for section in config.sections():\n        globals()[section] = {}\n        for key, val in config.items(section):\n            globals()[section][key] = val",
    "docstring": "| Load the configuration file.\n    | Add dynamically configuration to the module.\n\n    :rtype: None"
  },
  {
    "code": "def normal(obj, params, **kwargs):\n    normalize = kwargs.get('normalize', True)\n    if isinstance(obj, abstract.Curve):\n        if isinstance(params, (list, tuple)):\n            return ops.normal_curve_single_list(obj, params, normalize)\n        else:\n            return ops.normal_curve_single(obj, params, normalize)\n    if isinstance(obj, abstract.Surface):\n        if isinstance(params[0], float):\n            return ops.normal_surface_single(obj, params, normalize)\n        else:\n            return ops.normal_surface_single_list(obj, params, normalize)",
    "docstring": "Evaluates the normal vector of the curves or surfaces at the input parameter values.\n\n    This function is designed to evaluate normal vectors of the B-Spline and NURBS shapes at single or\n    multiple parameter positions.\n\n    :param obj: input geometry\n    :type obj: abstract.Curve or abstract.Surface\n    :param params: parameters\n    :type params: float, list or tuple\n    :return: a list containing \"point\" and \"vector\" pairs\n    :rtype: tuple"
  },
  {
    "code": "def apply_mask(data: bytes, mask: bytes) -> bytes:\n    if len(mask) != 4:\n        raise ValueError(\"mask must contain 4 bytes\")\n    return bytes(b ^ m for b, m in zip(data, itertools.cycle(mask)))",
    "docstring": "Apply masking to the data of a WebSocket message.\n\n    ``data`` and ``mask`` are bytes-like objects.\n\n    Return :class:`bytes`."
  },
  {
    "code": "def get_experiment_in_group(self, group, bucketing_id):\n    experiment_id = self.bucketer.find_bucket(bucketing_id, group.id, group.trafficAllocation)\n    if experiment_id:\n      experiment = self.config.get_experiment_from_id(experiment_id)\n      if experiment:\n        self.logger.info('User with bucketing ID \"%s\" is in experiment %s of group %s.' % (\n          bucketing_id,\n          experiment.key,\n          group.id\n        ))\n        return experiment\n    self.logger.info('User with bucketing ID \"%s\" is not in any experiments of group %s.' % (\n      bucketing_id,\n      group.id\n    ))\n    return None",
    "docstring": "Determine which experiment in the group the user is bucketed into.\n\n    Args:\n      group: The group to bucket the user into.\n      bucketing_id: ID to be used for bucketing the user.\n\n    Returns:\n      Experiment if the user is bucketed into an experiment in the specified group. None otherwise."
  },
  {
    "code": "def parseOneGame(self):\n\t\tif self.index < self.datalen:\n\t\t\tmatch = self.reGameTreeStart.match(self.data, self.index)\n\t\t\tif match:\n\t\t\t\tself.index = match.end()\n\t\t\t\treturn self.parseGameTree()\n\t\treturn None",
    "docstring": "Parses one game from 'self.data'. Returns a 'GameTree' containing\n\t\t\tone game, or 'None' if the end of 'self.data' has been reached."
  },
  {
    "code": "def delete_dataset(dataset_id,**kwargs):\n    try:\n        d = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one()\n    except NoResultFound:\n        raise HydraError(\"Dataset %s does not exist.\"%dataset_id)\n    dataset_rs = db.DBSession.query(ResourceScenario).filter(ResourceScenario.dataset_id==dataset_id).all()\n    if len(dataset_rs) > 0:\n        raise HydraError(\"Cannot delete %s. Dataset is used by one or more resource scenarios.\"%dataset_id)\n    db.DBSession.delete(d)\n    db.DBSession.flush()\n    db.DBSession.expunge_all()",
    "docstring": "Removes a piece of data from the DB.\n        CAUTION! Use with care, as this cannot be undone easily."
  },
  {
    "code": "def to_pandas(self):\n        try:\n            from pandas import DataFrame, Series\n        except ImportError:\n            raise ImportError('You must have pandas installed to export pandas DataFrames')\n        result = DataFrame(self._raw_tree)\n        return result",
    "docstring": "Return a pandas dataframe representation of the condensed tree.\n\n        Each row of the dataframe corresponds to an edge in the tree.\n        The columns of the dataframe are `parent`, `child`, `lambda_val`\n        and `child_size`.\n\n        The `parent` and `child` are the ids of the\n        parent and child nodes in the tree. Node ids less than the number\n        of points in the original dataset represent individual points, while\n        ids greater than the number of points are clusters.\n\n        The `lambda_val` value is the value (1/distance) at which the `child`\n        node leaves the cluster.\n\n        The `child_size` is the number of points in the `child` node."
  },
  {
    "code": "def register(self, key, **kwargs):\n        dimensions = dict((k, str(v)) for k, v in kwargs.items())\n        composite_key = self._composite_name(key, dimensions)\n        self._metadata[composite_key] = {\n            'metric': key,\n            'dimensions': dimensions\n        }\n        return composite_key",
    "docstring": "Registers metadata for a metric and returns a composite key"
  },
  {
    "code": "def _check_id_validity(self, p_ids):\n        errors = []\n        valid_ids = self.todolist.ids()\n        if len(p_ids) == 0:\n            errors.append('No todo item was selected')\n        else:\n            errors = [\"Invalid todo ID: {}\".format(todo_id)\n                      for todo_id in p_ids - valid_ids]\n        errors = '\\n'.join(errors) if errors else None\n        return errors",
    "docstring": "Checks if there are any invalid todo IDs in p_ids list.\n\n        Returns proper error message if any ID is invalid and None otherwise."
  },
  {
    "code": "def replace_static_libraries(self, exclusions=None):\n        if \"stdc++\" not in self.libraries:\n            self.libraries.append(\"stdc++\")\n        if exclusions is None:\n            exclusions = []\n        for library_name in set(self.libraries) - set(exclusions):\n            static_lib = find_static_library(library_name, self.library_dirs)\n            if static_lib:\n                self.libraries.remove(library_name)\n                self.extra_objects.append(static_lib)",
    "docstring": "Replaces references to libraries with full paths to their static\n        versions if the static version is to be found on the library path."
  },
  {
    "code": "def get_attachment(self, file_path):\n        try:\n            file_ = open(file_path, 'rb')\n            attachment = MIMEBase('application', 'octet-stream')\n            attachment.set_payload(file_.read())\n            file_.close()\n            encoders.encode_base64(attachment)\n            attachment.add_header('Content-Disposition', 'attachment',\n                                  filename=os.path.basename(file_path))\n            return attachment\n        except IOError:\n            traceback.print_exc()\n            message = ('The requested file could not be read. Maybe wrong '\n                       'permissions?')\n            print >> sys.stderr, message\n            sys.exit(6)",
    "docstring": "Get file as MIMEBase message"
  },
  {
    "code": "def get_detection_results(url, timeout, metadata=False, save_har=False):\n    plugins = load_plugins()\n    if not plugins:\n        raise NoPluginsError('No plugins found')\n    logger.debug('[+] Starting detection with %(n)d plugins', {'n': len(plugins)})\n    response = get_response(url, plugins, timeout)\n    if save_har:\n        fd, path = tempfile.mkstemp(suffix='.har')\n        logger.info(f'Saving HAR file to {path}')\n        with open(fd, 'w') as f:\n            json.dump(response['har'], f)\n    det = Detector(response, plugins, url)\n    softwares = det.get_results(metadata=metadata)\n    output = {\n        'url': url,\n        'softwares': softwares,\n    }\n    return output",
    "docstring": "Return results from detector.\n\n    This function prepares the environment loading the plugins,\n    getting the response and passing it to the detector.\n\n    In case of errors, it raises exceptions to be handled externally."
  },
  {
    "code": "def overview(index, start, end):\n    results = {\n        \"activity_metrics\": [Commits(index, start, end)],\n        \"author_metrics\": [Authors(index, start, end)],\n        \"bmi_metrics\": [],\n        \"time_to_close_metrics\": [],\n        \"projects_metrics\": []\n    }\n    return results",
    "docstring": "Compute metrics in the overview section for enriched git indexes.\n\n    Returns a dictionary. Each key in the dictionary is the name of\n    a metric, the value is the value of that metric. Value can be\n    a complex object (eg, a time series).\n\n    :param index: index object\n    :param start: start date to get the data from\n    :param end: end date to get the data upto\n    :return: dictionary with the value of the metrics"
  },
  {
    "code": "def fix_e701(self, result):\n        line_index = result['line'] - 1\n        target = self.source[line_index]\n        c = result['column']\n        fixed_source = (target[:c] + '\\n' +\n                        _get_indentation(target) + self.indent_word +\n                        target[c:].lstrip('\\n\\r \\t\\\\'))\n        self.source[result['line'] - 1] = fixed_source\n        return [result['line'], result['line'] + 1]",
    "docstring": "Put colon-separated compound statement on separate lines."
  },
  {
    "code": "def user_exists(username, domain='', database=None, **kwargs):\n    if domain:\n        username = '{0}\\\\{1}'.format(domain, username)\n    if database:\n        kwargs['database'] = database\n    return len(tsql_query(query=\"SELECT name FROM sysusers WHERE name='{0}'\".format(username), **kwargs)) == 1",
    "docstring": "Find if an user exists in a specific database on the MS SQL server.\n    domain, if provided, will be prepended to username\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt minion mssql.user_exists 'USERNAME' [database='DBNAME']"
  },
  {
    "code": "def StoreCSRFCookie(user, response):\n  csrf_token = GenerateCSRFToken(user, None)\n  response.set_cookie(\n      \"csrftoken\", csrf_token, max_age=CSRF_TOKEN_DURATION.seconds)",
    "docstring": "Decorator for WSGI handler that inserts CSRF cookie into response."
  },
  {
    "code": "def getEmpTraitCovar(self):\n        if self.P==1:\n            out=self.Y[self.Iok].var()\n        else:\n            out=SP.cov(self.Y[self.Iok].T)\n        return out",
    "docstring": "Returns the empirical trait covariance matrix"
  },
  {
    "code": "def _has_level_handler(logger):\n    level = logger.getEffectiveLevel()\n    current = logger\n    while current:\n        if any(handler.level <= level for handler in current.handlers):\n            return True\n        if not current.propagate:\n            break\n        current = current.parent\n    return False",
    "docstring": "Check if there is a handler in the logging chain that will handle\n    the given logger's effective level."
  },
  {
    "code": "def update(self, data):\n        self.debug(data)\n        self._check(data)\n        wg_uuid = data.get('workGroup')\n        self.log.debug(\"wg_uuid : %s \", wg_uuid)\n        uuid = data.get('uuid')\n        url = \"%(base)s/%(wg_uuid)s/nodes/%(uuid)s\" % {\n            'base': self.local_base_url,\n            'wg_uuid': wg_uuid,\n            'uuid': uuid\n        }\n        return self.core.update(url, data)",
    "docstring": "Update meta of one document."
  },
  {
    "code": "def _parse_price(html_chunk):\n    price = get_first_content(\n        html_chunk.find(\"div\", {\"class\": \"prices\"})\n    )\n    if not price:\n        return None\n    price = dhtmlparser.removeTags(price)\n    price = price.split(\"\\n\")[-1]\n    return price",
    "docstring": "Parse price of the book.\n\n    Args:\n        html_chunk (obj): HTMLElement containing slice of the page with details.\n\n    Returns:\n        str/None: Price as string with currency or None if not found."
  },
  {
    "code": "def add_chain(self, *nodes, _input=BEGIN, _output=None, _name=None):\n        if len(nodes):\n            _input = self._resolve_index(_input)\n            _output = self._resolve_index(_output)\n            _first = None\n            _last = None\n            for i, node in enumerate(nodes):\n                _last = self.add_node(node)\n                if not i and _name:\n                    if _name in self.named:\n                        raise KeyError(\"Duplicate name {!r} in graph.\".format(_name))\n                    self.named[_name] = _last\n                if _first is None:\n                    _first = _last\n                self.outputs_of(_input, create=True).add(_last)\n                _input = _last\n            if _output is not None:\n                self.outputs_of(_input, create=True).add(_output)\n            if hasattr(self, \"_topologcally_sorted_indexes_cache\"):\n                del self._topologcally_sorted_indexes_cache\n            return GraphRange(self, _first, _last)\n        return GraphRange(self, None, None)",
    "docstring": "Add a chain in this graph."
  },
  {
    "code": "def edit(self,\n             name,\n             description=None,\n             homepage=None,\n             private=None,\n             has_issues=None,\n             has_wiki=None,\n             has_downloads=None,\n             default_branch=None):\n        edit = {'name': name, 'description': description, 'homepage': homepage,\n                'private': private, 'has_issues': has_issues,\n                'has_wiki': has_wiki, 'has_downloads': has_downloads,\n                'default_branch': default_branch}\n        self._remove_none(edit)\n        json = None\n        if edit:\n            json = self._json(self._patch(self._api, data=dumps(edit)), 200)\n            self._update_(json)\n            return True\n        return False",
    "docstring": "Edit this repository.\n\n        :param str name: (required), name of the repository\n        :param str description: (optional), If not ``None``, change the\n            description for this repository. API default: ``None`` - leave\n            value unchanged.\n        :param str homepage: (optional), If not ``None``, change the homepage\n            for this repository. API default: ``None`` - leave value unchanged.\n        :param bool private: (optional), If ``True``, make the repository\n            private. If ``False``, make the repository public. API default:\n            ``None`` - leave value unchanged.\n        :param bool has_issues: (optional), If ``True``, enable issues for\n            this repository. If ``False``, disable issues for this repository.\n            API default: ``None`` - leave value unchanged.\n        :param bool has_wiki: (optional), If ``True``, enable the wiki for\n            this repository. If ``False``, disable the wiki for this\n            repository. API default: ``None`` - leave value unchanged.\n        :param bool has_downloads: (optional), If ``True``, enable downloads\n            for this repository. If ``False``, disable downloads for this\n            repository. API default: ``None`` - leave value unchanged.\n        :param str default_branch: (optional), If not ``None``, change the\n            default branch for this repository. API default: ``None`` - leave\n            value unchanged.\n        :returns: bool -- True if successful, False otherwise"
  },
  {
    "code": "def draw_img_button(width=200, height=50, text='This is a button', color=rgb(200,100,50)):\n    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)\n    ctx = cairo.Context(surface)\n    ctx.rectangle(0, 0, width - 1, height - 1)\n    ctx.set_source_rgb(color.red/255.0, color.green/255.0, color.blue/255.0)\n    ctx.fill()\n    ctx.set_source_rgb(1.0, 1.0, 1.0)\n    ctx.select_font_face(\n        \"Helvetica\",\n        cairo.FONT_SLANT_NORMAL,\n        cairo.FONT_WEIGHT_BOLD\n    )\n    ctx.set_font_size(15.0)\n    ctx.move_to(15, 2 * height / 3)\n    ctx.show_text(text)\n    surface.write_to_png('button.png')",
    "docstring": "Draws a simple image button."
  },
  {
    "code": "def auth_db_connect(db_path):\n    def dict_factory(cursor, row): return {col[0] : row[idx] for idx,col in enumerate(cursor.description)}\n    conn = db.connect(db_path)\n    conn.row_factory = dict_factory\n    if not auth_db_connect.init:\n        conn.execute('create table if not exists tokens (expires int, token text, ip text)')\n        conn.execute('create table if not exists session_tokens (expires int, token text, ip text, username text)')\n        auth_db_connect.init = True\n    return conn",
    "docstring": "An SQLite database is used to store authentication transient data,\n    this is tokens, strings of random data which are signed by the client,\n    and session_tokens which identify authenticated users"
  },
  {
    "code": "def read(self, size=None):\n        if size is not None:\n            read_size = min(size, self.__remaining_bytes)\n        else:\n            read_size = self.__remaining_bytes\n        data = self.__stream.read(read_size)\n        if read_size > 0 and not data:\n            raise exceptions.StreamExhausted(\n                'Not enough bytes in stream; expected %d, exhausted '\n                'after %d' % (\n                    self.__max_bytes,\n                    self.__max_bytes - self.__remaining_bytes))\n        self.__remaining_bytes -= len(data)\n        return data",
    "docstring": "Read at most size bytes from this slice.\n\n        Compared to other streams, there is one case where we may\n        unexpectedly raise an exception on read: if the underlying stream\n        is exhausted (i.e. returns no bytes on read), and the size of this\n        slice indicates we should still be able to read more bytes, we\n        raise exceptions.StreamExhausted.\n\n        Args:\n          size: If provided, read no more than size bytes from the stream.\n\n        Returns:\n          The bytes read from this slice.\n\n        Raises:\n          exceptions.StreamExhausted"
  },
  {
    "code": "def _register_make(cls):\n    assert cls.nxm_headers is not None\n    assert cls.nxm_headers is not []\n    for nxm_header in cls.nxm_headers:\n        assert nxm_header not in _MF_FIELDS\n        _MF_FIELDS[nxm_header] = cls.make\n    return cls",
    "docstring": "class decorator to Register mf make"
  },
  {
    "code": "def export(self, fn:PathOrStr, **kwargs):\n        \"Export the minimal state and save it in `fn` to load an empty version for inference.\"\n        pickle.dump(self.get_state(**kwargs), open(fn, 'wb'))",
    "docstring": "Export the minimal state and save it in `fn` to load an empty version for inference."
  },
  {
    "code": "def join(self, *args, **kwargs):\n        super(ThreadReturn, self).join(*args, **kwargs)\n        return self._return",
    "docstring": "Joins the thread.\n\n        Args:\n          self (ThreadReturn): the ``ThreadReturn`` instance\n          args: optional list of arguments\n          kwargs: optional key-word arguments\n\n        Returns:\n          The return value of the exited thread."
  },
  {
    "code": "def tag_implications(self, name_matches=None, antecedent_name=None,\n                         tag_id=None):\n        params = {\n            'search[name_matches]': name_matches,\n            'search[antecedent_name]': antecedent_name,\n            'search[id]': tag_id\n            }\n        return self._get('tag_implications.json', params)",
    "docstring": "Get tags implications.\n\n        Parameters:\n            name_matches (str): Match antecedent or consequent name.\n            antecedent_name (str): Match antecedent name (exact match).\n            tag_id (int): Tag implication id."
  },
  {
    "code": "def delete(ctx, slot, force):\n    controller = ctx.obj['controller']\n    if not force and not controller.slot_status[slot - 1]:\n        ctx.fail('Not possible to delete an empty slot.')\n    force or click.confirm(\n        'Do you really want to delete'\n        ' the configuration of slot {}?'.format(slot), abort=True, err=True)\n    click.echo('Deleting the configuration of slot {}...'.format(slot))\n    try:\n        controller.zap_slot(slot)\n    except YkpersError as e:\n        _failed_to_write_msg(ctx, e)",
    "docstring": "Deletes the configuration of a slot."
  },
  {
    "code": "def naturalday(value, format='%b %d'):\n    try:\n        value = date(value.year, value.month, value.day)\n    except AttributeError:\n        return value\n    except (OverflowError, ValueError):\n        return value\n    delta = value - date.today()\n    if delta.days == 0:\n        return _('today')\n    elif delta.days == 1:\n        return _('tomorrow')\n    elif delta.days == -1:\n        return _('yesterday')\n    return value.strftime(format)",
    "docstring": "For date values that are tomorrow, today or yesterday compared to\n    present day returns representing string. Otherwise, returns a string\n    formatted according to ``format``."
  },
  {
    "code": "def parse(self, input):\n        result = self._parseIso8601(input)\n        if not result:\n            result = self._parseSimple(input)\n        if result is not None:\n            return result\n        else:\n            raise ParameterException(\"Invalid time delta - could not parse %s\" % input)",
    "docstring": "Parses a time delta from the input.\n\n        See :py:class:`TimeDeltaParameter` for details on supported formats."
  },
  {
    "code": "def requirements(requirements_file):\n    return [\n        str(pkg.req) for pkg in parse_requirements(\n            requirements_file, session=pip_download.PipSession()) if pkg.req is not None]",
    "docstring": "Return packages mentioned in the given file.\n\n    Args:\n        requirements_file (str): path to the requirements file to be parsed.\n\n    Returns:\n        (list): 3rd-party package dependencies contained in the file."
  },
  {
    "code": "def get_brandings(self):\n        connection = Connection(self.token)\n        connection.set_url(self.production, self.BRANDINGS_URL)\n        return connection.get_request()",
    "docstring": "Get all account brandings\n        @return List of brandings"
  },
  {
    "code": "def get_array_indices(self):\n        for token in self.tokens:\n            if isinstance(token, SquareBrackets):\n                yield token.tokens[1:-1]",
    "docstring": "Returns an iterator of index token lists"
  },
  {
    "code": "def save_config(\n        self, cmd=\"configuration write\", confirm=False, confirm_response=\"\"\n    ):\n        output = self.enable()\n        output += self.config_mode()\n        output += self.send_command(cmd)\n        output += self.exit_config_mode()\n        return output",
    "docstring": "Save Config on Mellanox devices Enters and Leaves Config Mode"
  },
  {
    "code": "def add_node(self, name, desc, layout, node_x, node_y):\n        existing_node = get_session().query(Node).filter(Node.name==name, Node.network_id==self.id).first()\n        if existing_node is not None:\n            raise HydraError(\"A node with name %s is already in network %s\"%(name, self.id))\n        node = Node()\n        node.name        = name\n        node.description = desc\n        node.layout      = str(layout) if layout is not None else None\n        node.x           = node_x\n        node.y           = node_y\n        get_session().add(node)\n        self.nodes.append(node)\n        return node",
    "docstring": "Add a node to a network."
  },
  {
    "code": "def translate_alias(self, alias, namespace=None, target_namespaces=None, translate_ncbi_namespace=None):\n        if translate_ncbi_namespace is None:\n            translate_ncbi_namespace = self.translate_ncbi_namespace\n        seq_id = self._get_unique_seqid(alias=alias, namespace=namespace)\n        aliases = self.aliases.fetch_aliases(seq_id=seq_id,\n                                             translate_ncbi_namespace=translate_ncbi_namespace)\n        if target_namespaces:\n            aliases = [a for a in aliases if a[\"namespace\"] in target_namespaces]\n        return aliases",
    "docstring": "given an alias and optional namespace, return a list of all other\n        aliases for same sequence"
  },
  {
    "code": "def create_binding(self, key, shard=None, public=False,\n                       special_lobby_binding=False):\n        shard = shard or self.get_shard_id()\n        factory = recipient.Broadcast if public else recipient.Agent\n        recp = factory(key, shard)\n        binding = self._messaging.create_binding(recp)\n        if special_lobby_binding:\n            self._bindings_preserved_on_shard_change[binding] = True\n        return binding",
    "docstring": "Used by Interest instances."
  },
  {
    "code": "def clean_egginfo(self):\n        dir_name = os.path.join(self.root, self.get_egginfo_dir())\n        self._clean_directory(dir_name)",
    "docstring": "Clean .egginfo directory"
  },
  {
    "code": "def modifie(self, key: str, value: Any) -> None:\n        if key in self.FIELDS_OPTIONS:\n            self.modifie_options(key, value)\n        else:\n            self.modifications[key] = value",
    "docstring": "Store the modification. `value` should be dumped in DB compatible format."
  },
  {
    "code": "def _coords(shape):\n    assert shape.geom_type == 'Polygon'\n    coords = [list(shape.exterior.coords)]\n    for interior in shape.interiors:\n        coords.append(list(interior.coords))\n    return coords",
    "docstring": "Return a list of lists of coordinates of the polygon. The list consists\n    firstly of the list of exterior coordinates followed by zero or more lists\n    of any interior coordinates."
  },
  {
    "code": "def save(self):\n        for key in self.defaults.__dict__:\n            data = getattr(self.data, key)\n            self.cfg_file.Write(key, data)",
    "docstring": "Saves configuration file"
  },
  {
    "code": "def hdr(data, filename):\n    hdrobj = data if isinstance(data, HDRobject) else HDRobject(data)\n    hdrobj.write(filename)",
    "docstring": "write ENVI header files\n\n    Parameters\n    ----------\n    data: str or dict\n        the file or dictionary to get the info from\n    filename: str\n        the HDR file to write\n\n    Returns\n    -------"
  },
  {
    "code": "def add_child(self, child):\n        self.children.append(child)\n        child.parent = self\n        self.udepth = max([child.udepth for child in self.children]) + 1",
    "docstring": "Adds a branch to the current tree."
  },
  {
    "code": "def add_writable_file_volume(self,\n                                 runtime,\n                                 volume,\n                                 host_outdir_tgt,\n                                 tmpdir_prefix\n                                ):\n        if self.inplace_update:\n            self.append_volume(runtime, volume.resolved, volume.target,\n                               writable=True)\n        else:\n            if host_outdir_tgt:\n                if not os.path.exists(os.path.dirname(host_outdir_tgt)):\n                    os.makedirs(os.path.dirname(host_outdir_tgt))\n                shutil.copy(volume.resolved, host_outdir_tgt)\n            else:\n                tmp_dir, tmp_prefix = os.path.split(tmpdir_prefix)\n                tmpdir = tempfile.mkdtemp(prefix=tmp_prefix, dir=tmp_dir)\n                file_copy = os.path.join(\n                    tmpdir, os.path.basename(volume.resolved))\n                shutil.copy(volume.resolved, file_copy)\n                self.append_volume(runtime, file_copy, volume.target,\n                                   writable=True)\n            ensure_writable(host_outdir_tgt or file_copy)",
    "docstring": "Append a writable file mapping to the runtime option list."
  },
  {
    "code": "def zip(self, store=False, store_params=None):\n        params = locals()\n        params.pop('store')\n        params.pop('store_params')\n        new_transform = self.add_transform_task('zip', params)\n        if store:\n            return new_transform.store(**store_params) if store_params else new_transform.store()\n        return utils.make_call(CDN_URL, 'get', transform_url=new_transform.url)",
    "docstring": "Returns a zip file of the current transformation. This is different from\n        the zip function that lives on the Filestack Client\n\n        *returns* [Filestack.Transform]"
  },
  {
    "code": "def _instantiate_task(api, kwargs):\n    file_id = kwargs['file_id']\n    kwargs['file_id'] = file_id if str(file_id).strip() else None\n    kwargs['cid'] = kwargs['file_id'] or None\n    kwargs['rate_download'] = kwargs['rateDownload']\n    kwargs['percent_done'] = kwargs['percentDone']\n    kwargs['add_time'] = get_utcdatetime(kwargs['add_time'])\n    kwargs['last_update'] = get_utcdatetime(kwargs['last_update'])\n    is_transferred = (kwargs['status'] == 2 and kwargs['move'] == 1)\n    if is_transferred:\n        kwargs['pid'] = api.downloads_directory.cid\n    else:\n        kwargs['pid'] = None\n    del kwargs['rateDownload']\n    del kwargs['percentDone']\n    if 'url' in kwargs:\n        if not kwargs['url']:\n            kwargs['url'] = None\n    else:\n        kwargs['url'] = None\n    task = Task(api, **kwargs)\n    if is_transferred:\n        task._parent = api.downloads_directory\n    return task",
    "docstring": "Create a Task object from raw kwargs"
  },
  {
    "code": "def search(self):\n        search = self.document_class().search()\n        search = self.custom_filter(search)\n        search = self.filter_search(search)\n        search = self.order_search(search)\n        search = self.filter_permissions(search)\n        if search.count() > ELASTICSEARCH_SIZE:\n            limit = self.paginator.get_limit(self.request)\n            if not limit or limit > ELASTICSEARCH_SIZE:\n                raise TooManyResults()\n        search = search.extra(size=ELASTICSEARCH_SIZE)\n        return search",
    "docstring": "Handle the search request."
  },
  {
    "code": "def get_session(username, password, pin, cookie_path=COOKIE_PATH):\n    class MoparAuth(AuthBase):\n        def __init__(self, username, password, pin, cookie_path):\n            self.username = username\n            self.password = password\n            self.pin = pin\n            self.cookie_path = cookie_path\n        def __call__(self, r):\n            return r\n    session = requests.session()\n    session.auth = MoparAuth(username, password, pin, cookie_path)\n    session.headers.update({'User-Agent': USER_AGENT})\n    if os.path.exists(cookie_path):\n        _LOGGER.info(\"cookie found at: %s\", cookie_path)\n        session.cookies = _load_cookies(cookie_path)\n    else:\n        _login(session)\n    return session",
    "docstring": "Get a new session."
  },
  {
    "code": "def multigraph_collect(G, traversal, attrib=None):\n    collected = []\n    for u, v in util.pairwise(traversal):\n        attribs = G[u[0]][v[0]][v[1]]\n        if attrib is None:\n            collected.append(attribs)\n        else:\n            collected.append(attribs[attrib])\n    return collected",
    "docstring": "Given a MultiDiGraph traversal, collect attributes along it.\n\n    Parameters\n    -------------\n    G:          networkx.MultiDiGraph\n    traversal:  (n) list of (node, instance) tuples\n    attrib:     dict key, name to collect. If None, will return all\n\n    Returns\n    -------------\n    collected: (len(traversal) - 1) list of attributes"
  },
  {
    "code": "def advance_page(self):\n        if self.next_link is None:\n            raise StopIteration(\"End of paging\")\n        self._current_page_iter_index = 0\n        self._response = self._get_next(self.next_link)\n        self._derserializer(self, self._response)\n        return self.current_page",
    "docstring": "Force moving the cursor to the next azure call.\n\n        This method is for advanced usage, iterator protocol is prefered.\n\n        :raises: StopIteration if no further page\n        :return: The current page list\n        :rtype: list"
  },
  {
    "code": "def get_push_pop_stack():\n  push = copy.deepcopy(PUSH_STACK)\n  pop = copy.deepcopy(POP_STACK)\n  anno.setanno(push, 'pop', pop)\n  anno.setanno(push, 'gen_push', True)\n  anno.setanno(pop, 'push', push)\n  op_id = _generate_op_id()\n  return push, pop, op_id",
    "docstring": "Create pop and push nodes for substacks that are linked.\n\n  Returns:\n    A push and pop node which have `push_func` and `pop_func` annotations\n        respectively, identifying them as such. They also have a `pop` and\n        `push` annotation respectively, which links the push node to the pop\n        node and vice versa."
  },
  {
    "code": "def get_role(self, request: Request):\n        idr = request.identifier\n        return self._get_role(idr)",
    "docstring": "None roles are stored as empty strings, so the role returned as None\n        by this function means that corresponding DID is not stored in a ledger."
  },
  {
    "code": "def get(self, sched_rule_id):\n        path = '/'.join(['schedulerule', sched_rule_id])\n        return self.rachio.get(path)",
    "docstring": "Retrieve the information for a scheduleRule entity."
  },
  {
    "code": "def connect(port, baud=115200, user='micro', password='python', wait=0):\n    try:\n        ip_address = socket.gethostbyname(port)\n        connect_telnet(port, ip_address, user=user, password=password)\n    except socket.gaierror:\n        connect_serial(port, baud=baud, wait=wait)",
    "docstring": "Tries to connect automagically via network or serial."
  },
  {
    "code": "def line(ax, p1, p2, permutation=None, **kwargs):\n    pp1 = project_point(p1, permutation=permutation)\n    pp2 = project_point(p2, permutation=permutation)\n    ax.add_line(Line2D((pp1[0], pp2[0]), (pp1[1], pp2[1]), **kwargs))",
    "docstring": "Draws a line on `ax` from p1 to p2.\n\n    Parameters\n    ----------\n    ax: Matplotlib AxesSubplot, None\n        The subplot to draw on.\n    p1: 2-tuple\n        The (x,y) starting coordinates\n    p2: 2-tuple\n        The (x,y) ending coordinates\n    kwargs:\n        Any kwargs to pass through to Matplotlib."
  },
  {
    "code": "def write_zip(self, resources=None, dumpfile=None):\n        compression = (ZIP_DEFLATED if self.compress else ZIP_STORED)\n        zf = ZipFile(\n            dumpfile,\n            mode=\"w\",\n            compression=compression,\n            allowZip64=True)\n        rdm = ResourceDumpManifest(resources=resources)\n        real_path = {}\n        for resource in resources:\n            archive_path = self.archive_path(resource.path)\n            real_path[archive_path] = resource.path\n            resource.path = archive_path\n        zf.writestr('manifest.xml', rdm.as_xml())\n        for resource in resources:\n            zf.write(real_path[resource.path], arcname=resource.path)\n        zf.close()\n        zipsize = os.path.getsize(dumpfile)\n        self.logger.info(\n            \"Wrote ZIP file dump %s with size %d bytes\" %\n            (dumpfile, zipsize))",
    "docstring": "Write a ZIP format dump file.\n\n        Writes a ZIP file containing the resources in the iterable resources along with\n        a manifest file manifest.xml (written first). No checks on the size of files\n        or total size are performed, this is expected to have been done beforehand."
  },
  {
    "code": "def gettempdir():\n    global tempdir\n    if tempdir is None:\n        _once_lock.acquire()\n        try:\n            if tempdir is None:\n                tempdir = _get_default_tempdir()\n        finally:\n            _once_lock.release()\n    return tempdir",
    "docstring": "Accessor for tempfile.tempdir."
  },
  {
    "code": "def get_structure_from_mp(formula):\n    m = MPRester()\n    entries = m.get_entries(formula, inc_structure=\"final\")\n    if len(entries) == 0:\n        raise ValueError(\"No structure with formula %s in Materials Project!\" %\n                         formula)\n    elif len(entries) > 1:\n        warnings.warn(\"%d structures with formula %s found in Materials \"\n                      \"Project. The lowest energy structure will be returned.\" %\n                      (len(entries), formula))\n    return min(entries, key=lambda e: e.energy_per_atom).structure",
    "docstring": "Convenience method to get a crystal from the Materials Project database via\n    the API. Requires PMG_MAPI_KEY to be set.\n\n    Args:\n        formula (str): A formula\n\n    Returns:\n        (Structure) The lowest energy structure in Materials Project with that\n            formula."
  },
  {
    "code": "def tryPrepare(self, pp: PrePrepare):\n        rv, msg = self.canPrepare(pp)\n        if rv:\n            self.doPrepare(pp)\n        else:\n            self.logger.debug(\"{} cannot send PREPARE since {}\".format(self, msg))",
    "docstring": "Try to send the Prepare message if the PrePrepare message is ready to\n        be passed into the Prepare phase."
  },
  {
    "code": "def lookUpReportsByCountry(self, countryName):\n        code = self.findCountryTwoDigitCode(countryName)\n        if code is None:\n            raise Exception(\"Invalid country name.\")\n        url = self._base_url + self._url_list_reports + \"/%s\" % code\n        params = {\n            \"f\" : \"json\",\n        }\n        return self._post(url=url,\n                             param_dict=params,\n                             securityHandler=self._securityHandler,\n                             proxy_url=self._proxy_url,\n                             proxy_port=self._proxy_port)",
    "docstring": "looks up a country by it's name\n        Inputs\n           countryName - name of the country to get reports list."
  },
  {
    "code": "def push_object(self, channel_id, obj):\n        return self.push(channel_id, json.dumps(obj).replace('\"', '\\\\\"'))",
    "docstring": "Push ``obj`` for ``channel_id``. ``obj`` will be encoded as JSON in\n        the request."
  },
  {
    "code": "def _list_syntax_error():\n    _, e, _ = sys.exc_info()\n    if isinstance(e, SyntaxError) and hasattr(e, 'filename'):\n        yield path.dirname(e.filename)",
    "docstring": "If we're going through a syntax error, add the directory of the error to\n    the watchlist."
  },
  {
    "code": "def spots_at(self, x, y):\n        for spot in self.spot.values():\n            if spot.collide_point(x, y):\n                yield spot",
    "docstring": "Iterate over spots that collide the given point."
  },
  {
    "code": "def read(self, memory, addr, length):\n        if memory.id in self._read_requests:\n            logger.warning('There is already a read operation ongoing for '\n                           'memory id {}'.format(memory.id))\n            return False\n        rreq = _ReadRequest(memory, addr, length, self.cf)\n        self._read_requests[memory.id] = rreq\n        rreq.start()\n        return True",
    "docstring": "Read the specified amount of bytes from the given memory at the given\n        address"
  },
  {
    "code": "def crop(self, start_timestamp, end_timestamp):\n        output = {}\n        for key, value in self.items():\n            if key >= start_timestamp and key <= end_timestamp:\n                output[key] = value\n        if output:\n            return TimeSeries(output)\n        else:\n            raise ValueError('TimeSeries data was empty or invalid.')",
    "docstring": "Return a new TimeSeries object contains all the timstamps and values within\n        the specified range.\n\n        :param int start_timestamp: the start timestamp value\n        :param int end_timestamp: the end timestamp value\n        :return: :class:`TimeSeries` object."
  },
  {
    "code": "def _check_email_match(self, user, email):\n        if user.email != email:\n            raise CommandError(\n                _(\n                    'Skipping user \"{}\" because the specified and existing email '\n                    'addresses do not match.'\n                ).format(user.username)\n            )",
    "docstring": "DRY helper.\n\n        Requiring the user to specify both username and email will help catch\n        certain issues, for example if the expected username has already been\n        taken by someone else."
  },
  {
    "code": "def type(self, mpath):\n        try:\n            return self.stat(mpath)[\"type\"]\n        except errors.MantaResourceNotFoundError:\n            return None\n        except errors.MantaAPIError:\n            _, ex, _ = sys.exc_info()\n            if ex.code in ('ResourceNotFound', 'DirectoryDoesNotExist'):\n                return None\n            else:\n                raise",
    "docstring": "Return the manta type for the given manta path.\n\n        @param mpath {str} The manta path for which to get the type.\n        @returns {str|None} The manta type, e.g. \"object\" or \"directory\",\n            or None if the path doesn't exist."
  },
  {
    "code": "def create(sld, tld, nameserver, ip):\n    opts = salt.utils.namecheap.get_opts('namecheap.domains.ns.create')\n    opts['SLD'] = sld\n    opts['TLD'] = tld\n    opts['Nameserver'] = nameserver\n    opts['IP'] = ip\n    response_xml = salt.utils.namecheap.post_request(opts)\n    if response_xml is None:\n        return False\n    domainnscreateresult = response_xml.getElementsByTagName('DomainNSCreateResult')[0]\n    return salt.utils.namecheap.string_to_value(domainnscreateresult.getAttribute('IsSuccess'))",
    "docstring": "Creates a new nameserver. Returns ``True`` if the nameserver was created\n    successfully.\n\n    sld\n        SLD of the domain name\n\n    tld\n        TLD of the domain name\n\n    nameserver\n        Nameserver to create\n\n    ip\n        Nameserver IP address\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' namecheap_domains_ns.create sld tld nameserver ip"
  },
  {
    "code": "def write_table_to_file(self, dtype, custom_name=None, append=False, dir_path=None):\n        if custom_name:\n            fname = custom_name\n        else:\n            fname = self.filenames[dtype]\n        if not dir_path:\n            dir_path=self.directory\n        if dtype in self.tables:\n            write_df = self.remove_names(dtype)\n            outfile = self.tables[dtype].write_magic_file(custom_name=fname,\n                                                          dir_path=dir_path,\n                                                          append=append, df=write_df)\n        return outfile",
    "docstring": "Write out a MagIC table to file, using custom filename\n        as specified in self.filenames.\n\n        Parameters\n        ----------\n        dtype : str\n            magic table name"
  },
  {
    "code": "def tangent_surface_single_list(obj, param_list, normalize):\n    ret_vector = []\n    for param in param_list:\n        temp = tangent_surface_single(obj, param, normalize)\n        ret_vector.append(temp)\n    return tuple(ret_vector)",
    "docstring": "Evaluates the surface tangent vectors at the given list of parameter values.\n\n    :param obj: input surface\n    :type obj: abstract.Surface\n    :param param_list: parameter list\n    :type param_list: list or tuple\n    :param normalize: if True, the returned vector is converted to a unit vector\n    :type normalize: bool\n    :return: a list containing \"point\" and \"vector\" pairs\n    :rtype: tuple"
  },
  {
    "code": "def list_metering_labels(self, retrieve_all=True, **_params):\n        return self.list('metering_labels', self.metering_labels_path,\n                         retrieve_all, **_params)",
    "docstring": "Fetches a list of all metering labels for a project."
  },
  {
    "code": "def serialize_compound(self, tag):\n        separator, fmt = self.comma, '{{{}}}'\n        with self.depth():\n            if self.should_expand(tag):\n                separator, fmt = self.expand(separator, fmt)\n            return fmt.format(separator.join(\n                f'{self.stringify_compound_key(key)}{self.colon}{self.serialize(value)}'\n                for key, value in tag.items()\n            ))",
    "docstring": "Return the literal representation of a compound tag."
  },
  {
    "code": "def emulate_abs(self, x_val, y_val, timeval):\n        x_event = self.create_event_object(\n            \"Absolute\",\n            0x00,\n            x_val,\n            timeval)\n        y_event = self.create_event_object(\n            \"Absolute\",\n            0x01,\n            y_val,\n            timeval)\n        return x_event, y_event",
    "docstring": "Emulate the absolute co-ordinates of the mouse cursor."
  },
  {
    "code": "def copy_data(data_length, blocksize, infp, outfp):\n    use_sendfile = False\n    if have_sendfile:\n        try:\n            x_unused = infp.fileno()\n            y_unused = outfp.fileno()\n            use_sendfile = True\n        except (AttributeError, io.UnsupportedOperation):\n            pass\n    if use_sendfile:\n        in_offset = infp.tell()\n        out_offset = outfp.tell()\n        sendfile(outfp.fileno(), infp.fileno(), in_offset, data_length)\n        infp.seek(in_offset + data_length)\n        outfp.seek(out_offset + data_length)\n    else:\n        left = data_length\n        readsize = blocksize\n        while left > 0:\n            if left < readsize:\n                readsize = left\n            data = infp.read(readsize)\n            data_len = len(data)\n            if data_len != readsize:\n                data_len = left\n            outfp.write(data)\n            left -= data_len",
    "docstring": "A utility function to copy data from the input file object to the output\n    file object.  This function will use the most efficient copy method available,\n    which is often sendfile.\n\n    Parameters:\n     data_length - The amount of data to copy.\n     blocksize - How much data to copy per iteration.\n     infp - The file object to copy data from.\n     outfp - The file object to copy data to.\n    Returns:\n     Nothing."
  },
  {
    "code": "def execute_go_cmd(self, cmd, gopath=None, args=None, env=None,\n                     workunit_factory=None, workunit_name=None, workunit_labels=None, **kwargs):\n    go_cmd = self.create_go_cmd(cmd, gopath=gopath, args=args)\n    if workunit_factory is None:\n      return go_cmd.spawn(**kwargs).wait()\n    else:\n      name = workunit_name or cmd\n      labels = [WorkUnitLabel.TOOL] + (workunit_labels or [])\n      with workunit_factory(name=name, labels=labels, cmd=str(go_cmd)) as workunit:\n        process = go_cmd.spawn(env=env,\n                               stdout=workunit.output('stdout'),\n                               stderr=workunit.output('stderr'),\n                               **kwargs)\n        returncode = process.wait()\n        workunit.set_outcome(WorkUnit.SUCCESS if returncode == 0 else WorkUnit.FAILURE)\n        return returncode, go_cmd",
    "docstring": "Runs a Go command that is optionally targeted to a Go workspace.\n\n    If a `workunit_factory` is supplied the command will run in a work unit context.\n\n    :param string cmd: Go command to execute, e.g. 'test' for `go test`\n    :param string gopath: An optional $GOPATH which points to a valid Go workspace from which to run\n                          the command.\n    :param list args: An optional list of arguments and flags to pass to the Go command.\n    :param dict env: A custom environment to launch the Go command in.  If `None` the current\n                     environment is used.\n    :param workunit_factory: An optional callable that can produce a `WorkUnit` context\n    :param string workunit_name: An optional name for the work unit; defaults to the `cmd`\n    :param list workunit_labels: An optional sequence of labels for the work unit.\n    :param kwargs: Keyword arguments to pass through to `subprocess.Popen`.\n    :returns: A tuple of the exit code and the go command that was run.\n    :rtype: (int, :class:`GoDistribution.GoCommand`)"
  },
  {
    "code": "def filter_model_items(index_instance, model_items, model_name, start_date, end_date):\n    if index_instance.updated_field is None:\n        logger.warning(\"No updated date field found for {} - not restricting with start and end date\".format(model_name))\n    else:\n        if start_date:\n            model_items = model_items.filter(**{'{}__gte'.format(index_instance.updated_field): __str_to_tzdate__(start_date)})\n        if end_date:\n            model_items = model_items.filter(**{'{}__lte'.format(index_instance.updated_field): __str_to_tzdate__(end_date)})\n    return model_items",
    "docstring": "Filters the model items queryset based on start and end date."
  },
  {
    "code": "def set_locale(request):\n    return request.query.get('lang', app.ps.babel.select_locale_by_request(request))",
    "docstring": "Return locale from GET lang param or automatically."
  },
  {
    "code": "def postprocess(self, tempname, filename):\n        if os.name == 'posix':\n            mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777\n            os.chmod(tempname, mode)",
    "docstring": "Perform any platform-specific postprocessing of `tempname`\n\n        This is where Mac header rewrites should be done; other platforms don't\n        have anything special they should do.\n\n        Resource providers should call this method ONLY after successfully\n        extracting a compressed resource.  They must NOT call it on resources\n        that are already in the filesystem.\n\n        `tempname` is the current (temporary) name of the file, and `filename`\n        is the name it will be renamed to by the caller after this routine\n        returns."
  },
  {
    "code": "def get(self):\n        return StepContextContext(\n            self._version,\n            flow_sid=self._solution['flow_sid'],\n            engagement_sid=self._solution['engagement_sid'],\n            step_sid=self._solution['step_sid'],\n        )",
    "docstring": "Constructs a StepContextContext\n\n        :returns: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext\n        :rtype: twilio.rest.studio.v1.flow.engagement.step.step_context.StepContextContext"
  },
  {
    "code": "def write_bytes(self, data, n):\n        for pos in xrange(0, n):\n            self.payload[self.pos + pos] = data[pos]\n        self.pos += n",
    "docstring": "Write n number of bytes to this packet."
  },
  {
    "code": "def naive(\n    year, month, day, hour=0, minute=0, second=0, microsecond=0\n):\n    return DateTime(year, month, day, hour, minute, second, microsecond)",
    "docstring": "Return a naive DateTime."
  },
  {
    "code": "def _deserialize(self, value, attr, data):\n        value = super(SanitizedUnicode, self)._deserialize(value, attr, data)\n        value = fix_text(value)\n        value = ''.join(filter(self.is_valid_xml_char, value))\n        for char in self.UNWANTED_CHARACTERS:\n            value = value.replace(char, '')\n        return value",
    "docstring": "Deserialize sanitized string value."
  },
  {
    "code": "def _get_model_table(self, part):\n        rows = self.parser.find(part).find_children('tr').list_results()\n        table = []\n        for row in rows:\n            table.append(self._get_model_row(self.parser.find(\n                row\n            ).find_children('td,th').list_results()))\n        return self._get_valid_model_table(table)",
    "docstring": "Returns a list that represents the table.\n\n        :param part: The table header, table footer or table body.\n        :type part: hatemile.util.html.htmldomelement.HTMLDOMElement\n        :return: The list that represents the table.\n        :rtype: list(list(hatemile.util.html.htmldomelement.HTMLDOMElement))"
  },
  {
    "code": "def save_file(self, data, dfile):\n        self.enforce_type(self.jobject, \"weka.core.converters.FileSourcedConverter\")\n        if not javabridge.is_instance_of(dfile, \"Ljava/io/File;\"):\n            dfile = javabridge.make_instance(\n                \"Ljava/io/File;\", \"(Ljava/lang/String;)V\", javabridge.get_env().new_string_utf(str(dfile)))\n        javabridge.call(self.jobject, \"setFile\", \"(Ljava/io/File;)V\", dfile)\n        javabridge.call(self.jobject, \"setInstances\", \"(Lweka/core/Instances;)V\", data.jobject)\n        javabridge.call(self.jobject, \"writeBatch\", \"()V\")",
    "docstring": "Saves the Instances object in the specified file.\n\n        :param data: the data to save\n        :type data: Instances\n        :param dfile: the file to save the data to\n        :type dfile: str"
  },
  {
    "code": "def tail(self, since, filter_pattern, limit=10000, keep_open=True, colorize=True, http=False, non_http=False, force_colorize=False):\n        try:\n            since_stamp = string_to_timestamp(since)\n            last_since = since_stamp\n            while True:\n                new_logs = self.zappa.fetch_logs(\n                    self.lambda_name,\n                    start_time=since_stamp,\n                    limit=limit,\n                    filter_pattern=filter_pattern,\n                    )\n                new_logs = [ e for e in new_logs if e['timestamp'] > last_since ]\n                self.print_logs(new_logs, colorize, http, non_http, force_colorize)\n                if not keep_open:\n                    break\n                if new_logs:\n                    last_since = new_logs[-1]['timestamp']\n                time.sleep(1)\n        except KeyboardInterrupt:\n            try:\n                sys.exit(0)\n            except SystemExit:\n                os._exit(130)",
    "docstring": "Tail this function's logs.\n\n        if keep_open, do so repeatedly, printing any new logs"
  },
  {
    "code": "def neuron(layer_name, channel_n, x=None, y=None, batch=None):\n  def inner(T):\n    layer = T(layer_name)\n    shape = tf.shape(layer)\n    x_ = shape[1] // 2 if x is None else x\n    y_ = shape[2] // 2 if y is None else y\n    if batch is None:\n      return layer[:, x_, y_, channel_n]\n    else:\n      return layer[batch, x_, y_, channel_n]\n  return inner",
    "docstring": "Visualize a single neuron of a single channel.\n\n  Defaults to the center neuron. When width and height are even numbers, we\n  choose the neuron in the bottom right of the center 2x2 neurons.\n\n  Odd width & height:               Even width & height:\n\n  +---+---+---+                     +---+---+---+---+\n  |   |   |   |                     |   |   |   |   |\n  +---+---+---+                     +---+---+---+---+\n  |   | X |   |                     |   |   |   |   |\n  +---+---+---+                     +---+---+---+---+\n  |   |   |   |                     |   |   | X |   |\n  +---+---+---+                     +---+---+---+---+\n                                    |   |   |   |   |\n                                    +---+---+---+---+"
  },
  {
    "code": "def gpu_r2c_fft(in1, is_gpuarray=False, store_on_gpu=False):\n    if is_gpuarray:\n        gpu_in1 = in1\n    else:\n        gpu_in1 = gpuarray.to_gpu_async(in1.astype(np.float32))\n    output_size = np.array(in1.shape)\n    output_size[1] = 0.5*output_size[1] + 1\n    gpu_out1 = gpuarray.empty([output_size[0], output_size[1]], np.complex64)\n    gpu_plan = Plan(gpu_in1.shape, np.float32, np.complex64)\n    fft(gpu_in1, gpu_out1, gpu_plan)\n    if store_on_gpu:\n        return gpu_out1\n    else:\n        return gpu_out1.get()",
    "docstring": "This function makes use of the scikits implementation of the FFT for GPUs to take the real to complex FFT.\n\n    INPUTS:\n    in1             (no default):       The array on which the FFT is to be performed.\n    is_gpuarray     (default=True):     Boolean specifier for whether or not input is on the gpu.\n    store_on_gpu    (default=False):    Boolean specifier for whether the result is to be left on the gpu or not.\n\n    OUTPUTS:\n    gpu_out1                            The gpu array containing the result.\n    OR\n    gpu_out1.get()                      The result from the gpu array."
  },
  {
    "code": "def compute_regressor(exp_condition, hrf_model, frame_times, con_id='cond',\n                      oversampling=50, fir_delays=None, min_onset=-24):\n    tr = float(frame_times.max()) / (np.size(frame_times) - 1)\n    hr_regressor, hr_frame_times = _sample_condition(\n        exp_condition, frame_times, oversampling, min_onset)\n    hkernel = _hrf_kernel(hrf_model, tr, oversampling, fir_delays)\n    conv_reg = np.array([np.convolve(hr_regressor, h)[:hr_regressor.size]\n                         for h in hkernel])\n    computed_regressors = _resample_regressor(\n        conv_reg, hr_frame_times, frame_times)\n    if hrf_model != 'fir':\n        computed_regressors = _orthogonalize(computed_regressors)\n    reg_names = _regressor_names(con_id, hrf_model, fir_delays=fir_delays)\n    return computed_regressors, reg_names",
    "docstring": "This is the main function to convolve regressors with hrf model\n\n    Parameters\n    ----------\n    exp_condition : array-like of shape (3, n_events)\n        yields description of events for this condition as a\n        (onsets, durations, amplitudes) triplet\n\n    hrf_model : {'spm', 'spm + derivative', 'spm + derivative + dispersion',\n        'glover', 'glover + derivative', 'fir', None}\n        Name of the hrf model to be used\n\n    frame_times : array of shape (n_scans)\n        the desired sampling times\n\n    con_id : string\n        optional identifier of the condition\n\n    oversampling : int, optional\n        oversampling factor to perform the convolution\n\n    fir_delays : 1D-array-like, optional\n        delays (in seconds) used in case of a finite impulse reponse model\n\n    min_onset : float, optional\n        minimal onset relative to frame_times[0] (in seconds)\n        events that start before frame_times[0] + min_onset are not considered\n\n    Returns\n    -------\n    computed_regressors: array of shape(n_scans, n_reg)\n        computed regressors sampled at frame times\n\n    reg_names: list of strings\n        corresponding regressor names\n\n    Notes\n    -----\n    The different hemodynamic models can be understood as follows:\n    'spm': this is the hrf model used in SPM\n    'spm + derivative': SPM model plus its time derivative (2 regressors)\n    'spm + time + dispersion': idem, plus dispersion derivative (3 regressors)\n    'glover': this one corresponds to the Glover hrf\n    'glover + derivative': the Glover hrf + time derivative (2 regressors)\n    'glover + derivative + dispersion': idem + dispersion derivative\n                                        (3 regressors)\n    'fir': finite impulse response basis, a set of delayed dirac models\n           with arbitrary length. This one currently assumes regularly spaced\n           frame times (i.e. fixed time of repetition).\n    It is expected that spm standard and Glover model would not yield\n    large differences in most cases.\n\n    In case of glover and spm models, the derived regressors are\n    orthogonalized wrt the main one."
  },
  {
    "code": "def last_requestline(sent_data):\n    for line in reversed(sent_data):\n        try:\n            parse_requestline(decode_utf8(line))\n        except ValueError:\n            pass\n        else:\n            return line",
    "docstring": "Find the last line in sent_data that can be parsed with parse_requestline"
  },
  {
    "code": "def get_time_variables(ds):\n    time_variables = set()\n    for variable in ds.get_variables_by_attributes(standard_name='time'):\n        time_variables.add(variable.name)\n    for variable in ds.get_variables_by_attributes(axis='T'):\n        if variable.name not in time_variables:\n            time_variables.add(variable.name)\n    regx = r'^(?:day|d|hour|hr|h|minute|min|second|s)s? since .*$'\n    for variable in ds.get_variables_by_attributes(units=lambda x: isinstance(x, basestring)):\n        if re.match(regx, variable.units) and variable.name not in time_variables:\n            time_variables.add(variable.name)\n    return time_variables",
    "docstring": "Returns a list of variables describing the time coordinate\n\n    :param netCDF4.Dataset ds: An open netCDF4 Dataset"
  },
  {
    "code": "def mixed_parcel(p, temperature, dewpt, parcel_start_pressure=None,\n                 heights=None, bottom=None, depth=100 * units.hPa, interpolate=True):\n    r\n    if not parcel_start_pressure:\n        parcel_start_pressure = p[0]\n    theta = potential_temperature(p, temperature)\n    mixing_ratio = saturation_mixing_ratio(p, dewpt)\n    mean_theta, mean_mixing_ratio = mixed_layer(p, theta, mixing_ratio, bottom=bottom,\n                                                heights=heights, depth=depth,\n                                                interpolate=interpolate)\n    mean_temperature = (mean_theta / potential_temperature(parcel_start_pressure,\n                                                           1 * units.kelvin)) * units.kelvin\n    mean_vapor_pressure = vapor_pressure(parcel_start_pressure, mean_mixing_ratio)\n    mean_dewpoint = dewpoint(mean_vapor_pressure)\n    return (parcel_start_pressure, mean_temperature.to(temperature.units),\n            mean_dewpoint.to(dewpt.units))",
    "docstring": "r\"\"\"Calculate the properties of a parcel mixed from a layer.\n\n    Determines the properties of an air parcel that is the result of complete mixing of a\n    given atmospheric layer.\n\n    Parameters\n    ----------\n    p : `pint.Quantity`\n        Atmospheric pressure profile\n    temperature : `pint.Quantity`\n        Atmospheric temperature profile\n    dewpt : `pint.Quantity`\n        Atmospheric dewpoint profile\n    parcel_start_pressure : `pint.Quantity`, optional\n        Pressure at which the mixed parcel should begin (default None)\n    heights: `pint.Quantity`, optional\n        Atmospheric heights corresponding to the given pressures (default None)\n    bottom : `pint.Quantity`, optional\n        The bottom of the layer as a pressure or height above the surface pressure\n        (default None)\n    depth : `pint.Quantity`, optional\n        The thickness of the layer as a pressure or height above the bottom of the layer\n        (default 100 hPa)\n    interpolate : bool, optional\n        Interpolate the top and bottom points if they are not in the given data\n\n    Returns\n    -------\n    `pint.Quantity, pint.Quantity, pint.Quantity`\n        The pressure, temperature, and dewpoint of the mixed parcel."
  },
  {
    "code": "def all_dependencies(self, target):\n    for dep in target.closure(bfs=True, **self.target_closure_kwargs):\n      yield dep",
    "docstring": "All transitive dependencies of the context's target."
  },
  {
    "code": "def _request(self, endpoint, method, data=None, **kwargs):\n        final_url = self.url + endpoint\n        if not self._is_authenticated:\n            raise LoginRequired\n        rq = self.session\n        if method == 'get':\n            request = rq.get(final_url, **kwargs)\n        else:\n            request = rq.post(final_url, data, **kwargs)\n        request.raise_for_status()\n        request.encoding = 'utf_8'\n        if len(request.text) == 0:\n            data = json.loads('{}')\n        else:\n            try:\n                data = json.loads(request.text)\n            except ValueError:\n                data = request.text\n        return data",
    "docstring": "Method to hanle both GET and POST requests.\n\n        :param endpoint: Endpoint of the API.\n        :param method: Method of HTTP request.\n        :param data: POST DATA for the request.\n        :param kwargs: Other keyword arguments.\n\n        :return: Response for the request."
  },
  {
    "code": "def name2rgb(hue):\n    r, g, b = colorsys.hsv_to_rgb(hue / 360.0, .8, .7)\n    return tuple(int(x * 256) for x in [r, g, b])",
    "docstring": "Originally used to calculate color based on module name."
  },
  {
    "code": "def write_to_path(self,path,suffix='',format='png',overwrite=False):\n        if os.path.exists(path) and overwrite is False: raise ValueError(\"Error: use ovewrite=True to overwrite images\")\n        if not os.path.exists(path): os.makedirs(path)\n        for i,r in self.iterrows():\n            spath = os.path.join(path,r['project_name'],r['sample_name'])\n            if not os.path.exists(spath): os.makedirs(spath)\n            if suffix == '':\n                fname = os.path.join(spath,r['frame_name']+'.'+format)\n            else: fname = os.path.join(spath,r['frame_name']+'_'+suffix+'.'+format)\n            imageio.imwrite(fname, r['image'],format=format)",
    "docstring": "Output the data the dataframe's 'image' column to a directory structured by project->sample and named by frame\n\n        Args:\n            path (str): Where to write the directory of images\n            suffix (str): for labeling the imaages you write\n            format (str): default 'png' format to write the file\n            overwrite (bool): default False. if true can overwrite files in the path\n\n        Modifies:\n            Creates path folder if necessary and writes images to path"
  },
  {
    "code": "def get_names_and_paths(compiler_output: Dict[str, Any]) -> Dict[str, str]:\n    return {\n        contract_name: make_path_relative(path)\n        for path in compiler_output\n        for contract_name in compiler_output[path].keys()\n    }",
    "docstring": "Return a mapping of contract name to relative path as defined in compiler output."
  },
  {
    "code": "def supports(cls, *functionalities):\n        def _decorator(view):\n            if not hasattr(view, \"_supports\"):\n                view._supports = set()\n            for functionality in functionalities:\n                view._supports.add(functionality)\n            return view\n        return _decorator",
    "docstring": "A view decorator to indicate that an xBlock view has support for the\n        given functionalities.\n\n        Arguments:\n            functionalities: String identifiers for the functionalities of the view.\n                For example: \"multi_device\"."
  },
  {
    "code": "def convert_from_file(cls, input_file=None, output_file=None, output_format='json', indent=2, compact=False):\n        if input_file is None:\n            content = sys.stdin.read()\n            config = ConfigFactory.parse_string(content)\n        else:\n            config = ConfigFactory.parse_file(input_file)\n        res = cls.convert(config, output_format, indent, compact)\n        if output_file is None:\n            print(res)\n        else:\n            with open(output_file, \"w\") as fd:\n                fd.write(res)",
    "docstring": "Convert to json, properties or yaml\n\n        :param input_file: input file, if not specified stdin\n        :param output_file: output file, if not specified stdout\n        :param output_format: json, properties or yaml\n        :return: json, properties or yaml string representation"
  },
  {
    "code": "def points(self, size=1.0, highlight=None, colorlist=None, opacity=1.0):\n        if colorlist is None:\n            colorlist = [get_atom_color(t) for t in self.topology['atom_types']]\n        if highlight is not None:\n            if isinstance(highlight, int):\n                colorlist[highlight] = 0xff0000\n            if isinstance(highlight, (list, np.ndarray)):\n                for i in highlight:\n                    colorlist[i] = 0xff0000\n        sizes = [size] * len(self.topology['atom_types'])\n        points = self.add_representation('points', {'coordinates': self.coordinates.astype('float32'),\n                                                    'colors': colorlist,\n                                                    'sizes': sizes,\n                                                    'opacity': opacity})\n        def update(self=self, points=points):\n            self.update_representation(points, {'coordinates': self.coordinates.astype('float32')})\n        self.update_callbacks.append(update)\n        self.autozoom(self.coordinates)",
    "docstring": "Display the system as points.\n\n        :param float size: the size of the points."
  },
  {
    "code": "def get_data_csv(file_name, encoding='utf-8', file_contents=None, on_demand=False):\n    def yield_csv(csv_contents, csv_file):\n        try:\n            for line in csv_contents:\n                yield line\n        finally:\n            try:\n                csv_file.close()\n            except:\n                pass\n    def process_csv(csv_contents, csv_file):\n        return [line for line in yield_csv(csv_contents, csv_file)]\n    if file_contents:\n        csv_file = BytesIO(file_contents)\n    else:\n        csv_file = open(file_name, 'rb')\n    reader = csv.reader(csv_file, dialect=csv.excel, encoding=encoding)\n    if on_demand:\n        table = yield_csv(reader, csv_file)\n    else:\n        table = process_csv(reader, csv_file)\n    return [table]",
    "docstring": "Gets good old csv data from a file.\n\n    Args:\n        file_name: The name of the local file, or the holder for the\n            extension type when the file_contents are supplied.\n        encoding: Loads the file with the specified cell encoding.\n        file_contents: The file-like object holding contents of file_name.\n            If left as None, then file_name is directly loaded.\n        on_demand: Requests that a yielder be used in place of a full data\n            copy."
  },
  {
    "code": "def __grabHotkeysForWindow(self, window):\n        c = self.app.configManager\n        hotkeys = c.hotKeys + c.hotKeyFolders\n        window_info = self.get_window_info(window)\n        for item in hotkeys:\n            if item.get_applicable_regex() is not None and item._should_trigger_window_title(window_info):\n                self.__enqueue(self.__grabHotkey, item.hotKey, item.modifiers, window)\n            elif self.__needsMutterWorkaround(item):\n                self.__enqueue(self.__grabHotkey, item.hotKey, item.modifiers, window)",
    "docstring": "Grab all hotkeys relevant to the window\n\n        Used when a new window is created"
  },
  {
    "code": "def covered_interval(bin):\n    if bin < 0 or bin > MAX_BIN:\n        raise OutOfRangeError(\n            'Invalid bin number %d (maximum bin number is %d)'\n            % (bin, MAX_BIN))\n    shift = SHIFT_FIRST\n    for offset in BIN_OFFSETS:\n        if offset <= bin:\n            return bin - offset << shift, bin + 1 - offset << shift\n        shift += SHIFT_NEXT",
    "docstring": "Given a bin number `bin`, return the interval covered by this bin.\n\n    :arg int bin: Bin number.\n\n    :return: Tuple of `start, stop` being the zero-based, open-ended interval\n      covered by `bin`.\n    :rtype: tuple(int)\n\n    :raise OutOfRangeError: If bin number `bin` exceeds the maximum bin\n      number."
  },
  {
    "code": "def MP(candidate, references, n):\n    counts = Counter(ngrams(candidate, n))\n    if not counts:\n        return 0\n    max_counts = {}\n    for reference in references:\n        reference_counts = Counter(ngrams(reference, n))\n        for ngram in counts:\n            max_counts[ngram] = max(max_counts.get(ngram, 0), reference_counts[ngram])\n    clipped_counts = dict((ngram, min(count, max_counts[ngram])) for ngram, count in counts.items())\n    return sum(clipped_counts.values()) / sum(counts.values())",
    "docstring": "calculate modified precision"
  },
  {
    "code": "def _get_managed_files(self):\n        if self.grains_core.os_data().get('os_family') == 'Debian':\n            return self.__get_managed_files_dpkg()\n        elif self.grains_core.os_data().get('os_family') in ['Suse', 'redhat']:\n            return self.__get_managed_files_rpm()\n        return list(), list(), list()",
    "docstring": "Build a in-memory data of all managed files."
  },
  {
    "code": "def get_all_units(self, params=None):\n        if not params:\n            params = {}\n        return self._iterate_through_pages(self.get_units_per_page, resource=UNITS, **{'params': params})",
    "docstring": "Get all units\n        This will iterate over all pages until it gets all elements.\n        So if the rate limit exceeded it will throw an Exception and you will get nothing\n\n        :param params: search params\n        :return: list"
  },
  {
    "code": "def _define_jco_args(cmd_parser):\n    jo_group = cmd_parser.add_argument_group('Job options', 'Job configuration options')\n    jo_group.add_argument('--job-name', help='Job name')\n    jo_group.add_argument('--preload', action='store_true', help='Preload job onto all resources in the instance')\n    jo_group.add_argument('--trace', choices=['error', 'warn', 'info', 'debug', 'trace'], help='Application trace level')\n    jo_group.add_argument('--submission-parameters', '-p', nargs='+', action=_SubmitParamArg, help=\"Submission parameters as name=value pairs\")\n    jo_group.add_argument('--job-config-overlays', help=\"Path to file containing job configuration overlays JSON. Overrides any job configuration set by the application.\" , metavar='file')\n    return jo_group,",
    "docstring": "Define job configuration arguments.\n    Returns groups defined, currently one."
  },
  {
    "code": "def _process_docstrings(self, doc, members, add=True):\n        if ((doc.doctype == \"member\" or doc.doctype == \"local\") and \n            doc.pointsto is not None and \n            doc.pointsto in members):\n            if add:\n                members[doc.pointsto].docstring.append(doc)\n            else:\n                members[doc.pointsto].overwrite_docs(doc)\n            return True\n        else:\n            return False",
    "docstring": "Adds the docstrings from the list of DocElements to their\n        respective members.\n\n        Returns true if the doc element belonged to a member."
  },
  {
    "code": "def set_set_point(self, param):\n        if self.temperature_low_limit <= param <= self.temperature_high_limit:\n            self.set_point_temperature = param\n        return \"\"",
    "docstring": "Sets the target temperature.\n\n        :param param: The new temperature in C. Must be positive.\n        :return: Empty string."
  },
  {
    "code": "def check_path(path, credentials=None):\n    from thunder.readers import get_file_reader\n    reader = get_file_reader(path)(credentials=credentials)\n    existing = reader.list(path, directories=True)\n    if existing:\n        raise ValueError('Path %s appears to already exist. Specify a new directory, '\n                         'or call with overwrite=True to overwrite.' % path)",
    "docstring": "Check that specified output path does not already exist\n\n    The ValueError message will suggest calling with overwrite=True;\n    this function is expected to be called from the various output methods\n    that accept an 'overwrite' keyword argument."
  },
  {
    "code": "def get_os_filename (path):\n    if os.name == 'nt':\n        path = prepare_urlpath_for_nt(path)\n    res = urllib.url2pathname(fileutil.pathencode(path))\n    if os.name == 'nt' and res.endswith(':') and len(res) == 2:\n        res += os.sep\n    return res",
    "docstring": "Return filesystem path for given URL path."
  },
  {
    "code": "def metadata(self):\n        if self.__metadata__ is None:\n            metadata = {}\n            for test_run in self.test_runs.defer(None).all():\n                for key, value in test_run.metadata.items():\n                    metadata.setdefault(key, [])\n                    if value not in metadata[key]:\n                        metadata[key].append(value)\n            for key in metadata.keys():\n                if len(metadata[key]) == 1:\n                    metadata[key] = metadata[key][0]\n                else:\n                    metadata[key] = sorted(metadata[key], key=str)\n            self.__metadata__ = metadata\n        return self.__metadata__",
    "docstring": "The build metadata is the union of the metadata in its test runs.\n        Common keys with different values are transformed into a list with each\n        of the different values."
  },
  {
    "code": "def linear_trend(x, param):\n    linReg = linregress(range(len(x)), x)\n    return [(\"attr_\\\"{}\\\"\".format(config[\"attr\"]), getattr(linReg, config[\"attr\"]))\n            for config in param]",
    "docstring": "Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to\n    length of the time series minus one.\n    This feature assumes the signal to be uniformly sampled. It will not use the time stamps to fit the model.\n    The parameters control which of the characteristics are returned.\n\n    Possible extracted attributes are \"pvalue\", \"rvalue\", \"intercept\", \"slope\", \"stderr\", see the documentation of\n    linregress for more information.\n\n    :param x: the time series to calculate the feature of\n    :type x: numpy.ndarray\n    :param param: contains dictionaries {\"attr\": x} with x an string, the attribute name of the regression model\n    :type param: list\n    :return: the different feature values\n    :return type: pandas.Series"
  },
  {
    "code": "def _process_response(self, response: Response):\n        _logger.debug('Handling response')\n        self._redirect_tracker.load(response)\n        if self._redirect_tracker.is_redirect():\n            self._process_redirect()\n            self._loop_type = LoopType.redirect\n        elif response.status_code == http.client.UNAUTHORIZED and self._next_request.password:\n            self._process_authentication(response)\n        else:\n            self._next_request = None\n            self._loop_type = LoopType.normal\n        if self._cookie_jar:\n            self._extract_cookies(response)\n            if self._next_request:\n                self._add_cookies(self._next_request)",
    "docstring": "Handle the response and update the internal state."
  },
  {
    "code": "def detect_nexson_version(blob):\n    n = get_nexml_el(blob)\n    assert isinstance(n, dict)\n    return n.get('@nexml2json', BADGER_FISH_NEXSON_VERSION)",
    "docstring": "Returns the nexml2json attribute or the default code for badgerfish"
  },
  {
    "code": "def saveToFile(self,imageObjectList):\n        virtual = imageObjectList[0].inmemory\n        for key in self.masklist.keys():\n            filename = self.masknames[key]\n            newHDU = fits.PrimaryHDU()\n            newHDU.data = self.masklist[key]\n            if virtual:\n                for img in imageObjectList:\n                    img.saveVirtualOutputs({filename:newHDU})\n            else:\n                try:\n                    newHDU.writeto(filename, overwrite=True)\n                    log.info(\"Saving static mask to disk: %s\" % filename)\n                except IOError:\n                    log.error(\"Problem saving static mask file: %s to \"\n                              \"disk!\\n\" % filename)\n                    raise IOError",
    "docstring": "Saves the static mask to a file\n            it uses the signatures associated with each\n            mask to contruct the filename for the output mask image."
  },
  {
    "code": "def add_all_from_dict(self, dictionary, **kwargs):\n        for name, procedure in dictionary.items():\n            self.add(name, procedure, **kwargs)",
    "docstring": "Batch-add function implementations to the library.\n\n        :param dictionary:  A mapping from name to procedure class, i.e. the first two arguments to add()\n        :param kwargs:      Any additional kwargs will be passed to the constructors of _each_ procedure class"
  },
  {
    "code": "def ReadCronJobs(self, cronjob_ids=None, cursor=None):\n    query = (\"SELECT job, UNIX_TIMESTAMP(create_time), enabled, \"\n             \"forced_run_requested, last_run_status, \"\n             \"UNIX_TIMESTAMP(last_run_time), current_run_id, state, \"\n             \"UNIX_TIMESTAMP(leased_until), leased_by \"\n             \"FROM cron_jobs\")\n    if cronjob_ids is None:\n      cursor.execute(query)\n      return [self._CronJobFromRow(row) for row in cursor.fetchall()]\n    query += \" WHERE job_id IN (%s)\" % \", \".join([\"%s\"] * len(cronjob_ids))\n    cursor.execute(query, cronjob_ids)\n    res = []\n    for row in cursor.fetchall():\n      res.append(self._CronJobFromRow(row))\n    if len(res) != len(cronjob_ids):\n      missing = set(cronjob_ids) - set([c.cron_job_id for c in res])\n      raise db.UnknownCronJobError(\"CronJob(s) with id(s) %s not found.\" %\n                                   missing)\n    return res",
    "docstring": "Reads all cronjobs from the database."
  },
  {
    "code": "def apply(self, df):\n        if hasattr(self.definition, '__call__'):\n            r = self.definition(df)\n        elif self.definition in df.columns:\n            r = df[self.definition]\n        elif not isinstance(self.definition, string_types):\n            r = pd.Series(self.definition, index=df.index)\n        else:\n            raise ValueError(\"Invalid column definition: %s\" % str(self.definition))\n        return r.astype(self.astype) if self.astype else r",
    "docstring": "Takes a pd.DataFrame and returns the newly defined column, i.e.\n        a pd.Series that has the same index as `df`."
  },
  {
    "code": "def stop_deployment(awsclient, deployment_id):\n    log.info('Deployment: %s - stopping active deployment.', deployment_id)\n    client_codedeploy = awsclient.get_client('codedeploy')\n    response = client_codedeploy.stop_deployment(\n        deploymentId=deployment_id,\n        autoRollbackEnabled=True\n    )",
    "docstring": "stop tenkai deployment.\n\n    :param awsclient:\n    :param deployment_id:"
  },
  {
    "code": "def rows(self):\n        for line in self.text.splitlines():\n            yield tuple(self.getcells(line))",
    "docstring": "Returns an iterator of row tuples."
  },
  {
    "code": "def image(self):\n        if self.bands == 1:\n            return self.data.squeeze()\n        elif self.bands == 3:\n            return numpy.dstack(self.data)",
    "docstring": "An Image like array of ``self.data`` convenient for image processing tasks\n\n        * 2D array for single band, grayscale image data\n        * 3D array for three band, RGB image data\n\n        Enables working with ``self.data`` as if it were a PIL image.\n\n        See https://planetaryimage.readthedocs.io/en/latest/usage.html to see\n        how to open images to view them and make manipulations."
  },
  {
    "code": "def _get_matching_dns_entry_ids(self, identifier=None, rtype=None,\n                                    name=None, content=None):\n        record_ids = []\n        if not identifier:\n            records = self._list_records(rtype, name, content)\n            record_ids = [record['id'] for record in records]\n        else:\n            record_ids.append(identifier)\n        return record_ids",
    "docstring": "Return a list of DNS entries that match the given criteria."
  },
  {
    "code": "def is_namedtuple(type_: Type[Any]) -> bool:\n    return _issubclass(type_, tuple) and hasattr(type_, '_field_types') and hasattr(type_, '_fields')",
    "docstring": "Generated with typing.NamedTuple"
  },
  {
    "code": "def get_pan_rect(self):\n        wd, ht = self.get_window_size()\n        win_pts = np.asarray([(0, 0), (wd, 0), (wd, ht), (0, ht)])\n        arr_pts = self.tform['data_to_window'].from_(win_pts)\n        return arr_pts",
    "docstring": "Get the coordinates in the actual data corresponding to the\n        area shown in the display for the current zoom level and pan.\n\n        Returns\n        -------\n        points : list\n            Coordinates in the form of\n            ``[(x0, y0), (x1, y1), (x2, y2), (x3, y3)]``\n            from lower-left to lower-right."
  },
  {
    "code": "def instantiate(self, parallel_envs, seed=0, preset='default') -> VecEnv:\n        envs = DummyVecEnv([self._creation_function(i, seed, preset) for i in range(parallel_envs)])\n        if self.frame_history is not None:\n            envs = VecFrameStack(envs, self.frame_history)\n        return envs",
    "docstring": "Create vectorized environments"
  },
  {
    "code": "def do_version():\n    v = ApiPool.ping.model.Version(\n        name=ApiPool().current_server_name,\n        version=ApiPool().current_server_api.get_version(),\n        container=get_container_version(),\n    )\n    log.info(\"/version: \" + pprint.pformat(v))\n    return v",
    "docstring": "Return version details of the running server api"
  },
  {
    "code": "def load(store):\n    store = normalize_store_arg(store)\n    if contains_array(store, path=None):\n        return Array(store=store, path=None)[...]\n    elif contains_group(store, path=None):\n        grp = Group(store=store, path=None)\n        return LazyLoader(grp)",
    "docstring": "Load data from an array or group into memory.\n\n    Parameters\n    ----------\n    store : MutableMapping or string\n        Store or path to directory in file system or name of zip file.\n\n    Returns\n    -------\n    out\n        If the store contains an array, out will be a numpy array. If the store contains\n        a group, out will be a dict-like object where keys are array names and values\n        are numpy arrays.\n\n    See Also\n    --------\n    save, savez\n\n    Notes\n    -----\n    If loading data from a group of arrays, data will not be immediately loaded into\n    memory. Rather, arrays will be loaded into memory as they are requested."
  },
  {
    "code": "def wait_send(self, timeout = None):\n\t\tself._send_queue_cleared.clear()\n\t\tself._send_queue_cleared.wait(timeout = timeout)",
    "docstring": "Wait until all queued messages are sent."
  },
  {
    "code": "def from_jd(jd):\n    jd += 0.5\n    z = trunc(jd)\n    a = z\n    b = a + 1524\n    c = trunc((b - 122.1) / 365.25)\n    d = trunc(365.25 * c)\n    e = trunc((b - d) / 30.6001)\n    if trunc(e < 14):\n        month = e - 1\n    else:\n        month = e - 13\n    if trunc(month > 2):\n        year = c - 4716\n    else:\n        year = c - 4715\n    day = b - d - trunc(30.6001 * e)\n    return (year, month, day)",
    "docstring": "Calculate Julian calendar date from Julian day"
  },
  {
    "code": "def download_directory(self, bucket, key, directory, transfer_config=None, subscribers=None):\n        check_io_access(directory, os.W_OK)\n        return self._queue_task(bucket, [FilePair(key, directory)], transfer_config,\n                                subscribers, enumAsperaDirection.RECEIVE)",
    "docstring": "download a directory using Aspera"
  },
  {
    "code": "def ping():\n    try:\n        curl_couchdb('/cozy/')\n        ping = True\n    except requests.exceptions.ConnectionError, error:\n        print error\n        ping = False\n    return ping",
    "docstring": "Ping CozyDB with existing credentials"
  },
  {
    "code": "def send_mass_user_template_mail(subject_template, body_template, users, context):\n    message_tuples = []\n    for user in users:\n        context['user'] = user\n        subject, body = render_mail_template(subject_template, body_template, context)\n        message_tuples.append((subject, body, conf.get('DEFAULT_FROM_EMAIL'), [user.email]))\n    if message_tuples:\n        send_mass_mail(message_tuples)",
    "docstring": "Similar to `send_mass_template_mail` this function renders the given templates\n    into email subjects and bodies.\n\n    The emails are send one-by-one."
  },
  {
    "code": "def _complete_cases(self, text, line, istart, iend):\n        if text == \"\":\n            return list(self.live.keys())\n        else:\n            return [c for c in self.live if c.startswith(text)]",
    "docstring": "Returns the completion list of possible test cases for the active unit test."
  },
  {
    "code": "def setup_remoteckan(self, remoteckan=None, **kwargs):\n        if remoteckan is None:\n            self._remoteckan = self.create_remoteckan(self.get_hdx_site_url(), full_agent=self.get_user_agent(),\n                                                      **kwargs)\n        else:\n            self._remoteckan = remoteckan",
    "docstring": "Set up remote CKAN from provided CKAN or by creating from configuration\n\n        Args:\n            remoteckan (Optional[ckanapi.RemoteCKAN]): CKAN instance. Defaults to setting one up from configuration.\n\n        Returns:\n            None"
  },
  {
    "code": "def create_lbaas_l7rule(self, l7policy, body=None):\n        return self.post(self.lbaas_l7rules_path % l7policy, body=body)",
    "docstring": "Creates rule for a certain L7 policy."
  },
  {
    "code": "def scale(self, image, size, crop, options):\n        original_size = self.get_image_size(image)\n        factor = self._calculate_scaling_factor(original_size, size, crop is not None)\n        if factor < 1 or options['scale_up']:\n            width = int(original_size[0] * factor)\n            height = int(original_size[1] * factor)\n            image = self.engine_scale(image, width, height)\n        return image",
    "docstring": "Wrapper for ``engine_scale``, checks if the scaling factor is below one or that scale_up\n        option is set to True before calling ``engine_scale``.\n\n        :param image:\n        :param size:\n        :param crop:\n        :param options:\n        :return:"
  },
  {
    "code": "def _get_expiration(self, headers: dict) -> int:\n        expiration_str = headers.get('expires')\n        if not expiration_str:\n            return 0\n        expiration = datetime.strptime(expiration_str, '%a, %d %b %Y %H:%M:%S %Z')\n        delta = (expiration - datetime.utcnow()).total_seconds()\n        return math.ceil(abs(delta))",
    "docstring": "Gets the expiration time of the data from the response headers.\n\n        Args:\n            headers: dictionary of headers from ESI\n\n        Returns:\n            value of seconds from now the data expires"
  },
  {
    "code": "def get_hist(rfile, histname, get_overflow=False):\n    import root_numpy as rnp\n    rfile = open_rfile(rfile)\n    hist = rfile[histname]\n    xlims = np.array(list(hist.xedges()))\n    bin_values = rnp.hist2array(hist, include_overflow=get_overflow)\n    rfile.close()\n    return bin_values, xlims",
    "docstring": "Read a 1D Histogram."
  },
  {
    "code": "def _read_data(self):\n        while True:\n            try:\n                data = yield from self._socket.recv()\n            except asyncio.CancelledError:\n                break\n            except ConnectionClosed:\n                break\n            self._push_packet(data)\n        self._loop.call_soon(self.close)",
    "docstring": "Reads data from the connection and adds it to _push_packet,\n        until the connection is closed or the task in cancelled."
  },
  {
    "code": "def getTypedValueNoExceptions(self, row):\n        return wrapply(self.type, wrapply(self.getValue, row))",
    "docstring": "Returns the properly-typed value for the given row at this column.\n           Returns the type's default value if either the getter or the type conversion fails."
  },
  {
    "code": "def assert_is_lat(val):\n    assert type(val) is float or type(val) is int, \"Value must be a number\"\n    if val < -90.0 or val > 90.0:\n        raise ValueError(\"Latitude value must be between -90 and 90\")",
    "docstring": "Checks it the given value is a feasible decimal latitude\n\n    :param val: value to be checked\n    :type val: int of float\n    :returns:  `None`\n    :raises: *ValueError* if value is out of latitude boundaries, *AssertionError* if type is wrong"
  },
  {
    "code": "def set_widgets(self):\n        last_layer = self.parent.layer and self.parent.layer.id() or None\n        self.lblDescribeCanvasHazLayer.clear()\n        self.list_compatible_canvas_layers()\n        self.auto_select_one_item(self.lstCanvasHazLayers)\n        if last_layer:\n            layers = []\n            for index in range(self.lstCanvasHazLayers.count()):\n                item = self.lstCanvasHazLayers.item(index)\n                layers += [item.data(Qt.UserRole)]\n            if last_layer in layers:\n                self.lstCanvasHazLayers.setCurrentRow(layers.index(last_layer))\n        hazard = self.parent.step_fc_functions1.selected_value(\n            layer_purpose_hazard['key'])\n        icon_path = get_image_path(hazard)\n        self.lblIconIFCWHazardFromCanvas.setPixmap(QPixmap(icon_path))",
    "docstring": "Set widgets on the Hazard Layer From TOC tab."
  },
  {
    "code": "def latexpdf():\n    rc = latex()\n    print('Running LaTeX files through pdflatex...')\n    builddir = os.path.join(BUILDDIR, 'latex')\n    subprocess.call(['make', '-C', builddir, 'all-pdf'])\n    print('pdflatex finished; the PDF files are in {}.'.format(builddir))",
    "docstring": "make LaTeX files and run them through pdflatex"
  },
  {
    "code": "def modInv(a, m):\n    if coPrime([a, m]):\n        linearCombination = extendedEuclid(a, m)\n        return linearCombination[1] % m\n    else:\n        return 0",
    "docstring": "returns the multiplicative inverse of a in modulo m as a\n       positive value between zero and m-1"
  },
  {
    "code": "def rgb_to_cmy(r, g=None, b=None):\n  if type(r) in [list,tuple]:\n    r, g, b = r\n  return (1-r, 1-g, 1-b)",
    "docstring": "Convert the color from RGB coordinates to CMY.\n\n  Parameters:\n    :r:\n      The Red component value [0...1]\n    :g:\n      The Green component value [0...1]\n    :b:\n      The Blue component value [0...1]\n\n  Returns:\n    The color as an (c, m, y) tuple in the range:\n    c[0...1],\n    m[0...1],\n    y[0...1]\n\n  >>> rgb_to_cmy(1, 0.5, 0)\n  (0, 0.5, 1)"
  },
  {
    "code": "def swaplevel(self, i=-2, j=-1, copy=True):\n        new_index = self.index.swaplevel(i, j)\n        return self._constructor(self._values, index=new_index,\n                                 copy=copy).__finalize__(self)",
    "docstring": "Swap levels i and j in a MultiIndex.\n\n        Parameters\n        ----------\n        i, j : int, str (can be mixed)\n            Level of index to be swapped. Can pass level name as string.\n\n        Returns\n        -------\n        Series\n            Series with levels swapped in MultiIndex.\n\n        .. versionchanged:: 0.18.1\n\n           The indexes ``i`` and ``j`` are now optional, and default to\n           the two innermost levels of the index."
  },
  {
    "code": "def easeOutBounce(n):\n    _checkRange(n)\n    if n < (1/2.75):\n        return 7.5625 * n * n\n    elif n < (2/2.75):\n        n -= (1.5/2.75)\n        return 7.5625 * n * n + 0.75\n    elif n < (2.5/2.75):\n        n -= (2.25/2.75)\n        return 7.5625 * n * n + 0.9375\n    else:\n        n -= (2.65/2.75)\n        return 7.5625 * n * n + 0.984375",
    "docstring": "A bouncing tween function that hits the destination and then bounces to rest.\n\n    Args:\n      n (float): The time progress, starting at 0.0 and ending at 1.0.\n\n    Returns:\n      (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine()."
  },
  {
    "code": "def view_package_path(self, package: str) -> _PATH:\n        if package not in self.view_packgets_list():\n            raise NoSuchPackageException(\n                f'There is no such package {package!r}.')\n        output, _ = self._execute(\n            '-s', self.device_sn, 'shell', 'pm', 'path', package)\n        return output[8:-1]",
    "docstring": "Print the path to the APK of the given."
  },
  {
    "code": "def _parse_state_file(state_file_path='terraform.tfstate'):\n    ret = {}\n    with salt.utils.files.fopen(state_file_path, 'r') as fh_:\n        tfstate = salt.utils.json.load(fh_)\n    modules = tfstate.get('modules')\n    if not modules:\n        log.error('Malformed tfstate file. No modules found')\n        return ret\n    for module in modules:\n        resources = module.get('resources', [])\n        for resource_name, resource in salt.ext.six.iteritems(resources):\n            roster_entry = None\n            if resource['type'] == 'salt_host':\n                roster_entry = _handle_salt_host_resource(resource)\n            if not roster_entry:\n                continue\n            minion_id = roster_entry.get(MINION_ID, resource.get('id'))\n            if not minion_id:\n                continue\n            if MINION_ID in roster_entry:\n                del roster_entry[MINION_ID]\n            _add_ssh_key(roster_entry)\n            ret[minion_id] = roster_entry\n    return ret",
    "docstring": "Parses the terraform state file passing different resource types to the right handler"
  },
  {
    "code": "def check_if_numbers_are_consecutive(list_):\n    return all((True if second - first == 1 else False\n                for first, second in zip(list_[:-1], list_[1:])))",
    "docstring": "Returns True if numbers in the list are consecutive\n\n    :param list_: list of integers\n    :return: Boolean"
  },
  {
    "code": "def read_ascii_catalog(filename, format_, unit=None):\n    catalog = ascii.read(filename, format=format_)\n    columns = catalog.columns\n    if 'RA' in columns and 'Dec' in columns:\n        if unit is None:\n            unit = (hour, degree)\n        coords = SkyCoord(catalog['RA'],\n                          catalog['Dec'],\n                          unit=unit,\n                          frame='icrs')\n    elif 'Lat' in columns and 'Lon' in columns:\n        if unit is None:\n            unit = (degree, degree)\n        coords = SkyCoord(catalog['Lon'],\n                          catalog['Lat'],\n                          unit=unit,\n                          frame='galactic')\n    else:\n        raise Exception('columns RA,Dec or Lon,Lat not found')\n    return coords",
    "docstring": "Read an ASCII catalog file using Astropy.\n\n    This routine is used by pymoctool to load coordinates from a\n    catalog file in order to generate a MOC representation."
  },
  {
    "code": "def get_option_float(self, name, section=None, vars=None, expect=None):\n        val = self.get_option(name, section, vars, expect)\n        if val:\n            return float(val)",
    "docstring": "Just like ``get_option`` but parse as a float."
  },
  {
    "code": "def setdefault(self, key, default=None):\n        self._wlock.acquire()\n        try:\n            try:\n                return self[key]\n            except KeyError:\n                self[key] = default\n                return default\n        finally:\n            self._wlock.release()",
    "docstring": "Set `default` if the key is not in the cache otherwise\n        leave unchanged. Return the value of this key."
  },
  {
    "code": "def _display_status(normalized_data, stream):\n    if 'Pull complete' in normalized_data['status'] or 'Download complete' in normalized_data['status']:\n        stream.write(\"\\n\")\n    if 'id' in normalized_data:\n        stream.write(\"%s - \" % normalized_data['id'])\n    stream.write(\"{0}\\n\".format(normalized_data['status']))",
    "docstring": "print status message from docker-py stream."
  },
  {
    "code": "def add_attachment(self, attachment):\n        self._attachments = self._ensure_append(attachment, self._attachments)",
    "docstring": "Add an attachment to this email\n\n        :param attachment: Add an attachment to this email\n        :type attachment: Attachment"
  },
  {
    "code": "def copy_dir(self, path):\n        for directory in path:\n            if os.path.isdir(path):\n                full_path = os.path.join(self.archive_dir, directory.lstrip('/'))\n                logger.debug(\"Copying %s to %s\", directory, full_path)\n                shutil.copytree(directory, full_path)\n            else:\n                logger.debug(\"Not a directory: %s\", directory)\n        return path",
    "docstring": "Recursively copy directory"
  },
  {
    "code": "def background_chart(chart, foreground, colors):\n    def convert_background(entry):\n        try:\n            attr = urwid.AttrSpec(foreground, entry, colors)\n        except urwid.AttrSpecError:\n            return None\n        if colors > 16 and attr.background_basic and \\\n            attr.background_number >= 8:\n            entry = 'h%d'%attr.background_number\n            attr = urwid.AttrSpec(foreground, entry, colors)\n        return attr, entry\n    return parse_chart(chart, convert_background)",
    "docstring": "Create text markup for a background colour chart\n\n    chart -- palette chart as string\n    foreground -- colour to use for foreground of chart\n    colors -- number of colors (88 or 256)\n\n    This will remap 8 <= colour < 16 to high-colour versions\n    in the hopes of greater compatibility"
  },
  {
    "code": "def _add_list_row(self, feature_list, key=None):\n        if len(feature_list) > len(self._column_name_list):\n            raise IndexError(\"Input list must have %s columns or less\" % len(self._column_name_list))\n        self._row_memo = {}\n        if key is not None:\n            if key in self._row_name_idx:\n                self._rows[self._row_name_idx[key]] = feature_list\n                return\n            else:\n                self._row_name_idx[key] = len(self._rows)\n                self._row_name_list.append(key)\n        self._rows.append(feature_list)",
    "docstring": "Add a list row to the matrix\n\n        :param str key: key used when rows is a dict rather than an array\n        :param feature_list: a list of features in the same order as column_names\n\n        :raise IndexError: if the list doesnt match the expected number of columns"
  },
  {
    "code": "def crop_bbox_by_coords(bbox, crop_coords, crop_height, crop_width, rows, cols):\n    bbox = denormalize_bbox(bbox, rows, cols)\n    x_min, y_min, x_max, y_max = bbox\n    x1, y1, x2, y2 = crop_coords\n    cropped_bbox = [x_min - x1, y_min - y1, x_max - x1, y_max - y1]\n    return normalize_bbox(cropped_bbox, crop_height, crop_width)",
    "docstring": "Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the\n    required height and width of the crop."
  },
  {
    "code": "def ParseFileObject(self, parser_mediator, file_object):\n    filename = parser_mediator.GetFilename()\n    if not filename.startswith('INFO2'):\n      return\n    file_header_map = self._GetDataTypeMap('recycler_info2_file_header')\n    try:\n      file_header, _ = self._ReadStructureFromFileObject(\n          file_object, 0, file_header_map)\n    except (ValueError, errors.ParseError) as exception:\n      raise errors.UnableToParseFile((\n          'Unable to parse Windows Recycler INFO2 file header with '\n          'error: {0!s}').format(exception))\n    if file_header.unknown1 != 5:\n      parser_mediator.ProduceExtractionWarning('unsupported format signature.')\n      return\n    file_entry_size = file_header.file_entry_size\n    if file_entry_size not in (280, 800):\n      parser_mediator.ProduceExtractionWarning(\n          'unsupported file entry size: {0:d}'.format(file_entry_size))\n      return\n    file_offset = file_object.get_offset()\n    file_size = file_object.get_size()\n    while file_offset < file_size:\n      self._ParseInfo2Record(\n          parser_mediator, file_object, file_offset, file_entry_size)\n      file_offset += file_entry_size",
    "docstring": "Parses a Windows Recycler INFO2 file-like object.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      file_object (dfvfs.FileIO): file-like object.\n\n    Raises:\n      UnableToParseFile: when the file cannot be parsed."
  },
  {
    "code": "def parse_event_xml(self, event_data) -> dict:\n        event = {}\n        event_xml = event_data.decode()\n        message = MESSAGE.search(event_xml)\n        if not message:\n            return {}\n        event[EVENT_OPERATION] = message.group(EVENT_OPERATION)\n        topic = TOPIC.search(event_xml)\n        if topic:\n            event[EVENT_TOPIC] = topic.group(EVENT_TOPIC)\n        source = SOURCE.search(event_xml)\n        if source:\n            event[EVENT_SOURCE] = source.group(EVENT_SOURCE)\n            event[EVENT_SOURCE_IDX] = source.group(EVENT_SOURCE_IDX)\n        data = DATA.search(event_xml)\n        if data:\n            event[EVENT_TYPE] = data.group(EVENT_TYPE)\n            event[EVENT_VALUE] = data.group(EVENT_VALUE)\n        _LOGGER.debug(event)\n        return event",
    "docstring": "Parse metadata xml."
  },
  {
    "code": "def _has_nested(self, relations, operator='>=', count=1, boolean='and', extra=None):\n        relations = relations.split('.')\n        def closure(q):\n            if len(relations) > 1:\n                q.where_has(relations.pop(0), closure)\n            else:\n                q.has(relations.pop(0), operator, count, boolean, extra)\n        return self.where_has(relations.pop(0), closure)",
    "docstring": "Add nested relationship count conditions to the query.\n\n        :param relations: nested relations\n        :type relations: str\n\n        :param operator: The operator\n        :type operator: str\n\n        :param count: The count\n        :type count: int\n\n        :param boolean: The boolean value\n        :type boolean: str\n\n        :param extra: The extra query\n        :type extra: Builder or callable\n\n        :rtype: Builder"
  },
  {
    "code": "def _send(self, prepared_request):\n        session = Session()\n        response = session.send(prepared_request)\n        return Response(response)",
    "docstring": "Send a PreparedRequest to the server.\n\n        Parameters\n            prepared_request (requests.PreparedRequest)\n\n        Returns\n            (Response)\n                A Response object, whichcontains a server's\n                response to an HTTP request."
  },
  {
    "code": "def set_permission(self, permission, value, parent=False, admin=False):\n        try:\n            if not getattr(self, 'parent_{}'.format(permission)) and not parent and not admin:\n                return False\n            level = 'parent' if parent else 'self'\n            setattr(self, '{}_{}'.format(level, permission), value)\n            if parent and not value:\n                setattr(self, 'self_{}'.format(permission), False)\n            self.save()\n            return True\n        except Exception as e:\n            logger.error(\"Error occurred setting permission {} to {}: {}\".format(permission, value, e))\n            return False",
    "docstring": "Sets permission for personal information.\n            Returns False silently if unable to set permission.\n            Returns True if successful."
  },
  {
    "code": "def _NewMatchSection(self, val):\n    section = {\"criterion\": val, \"config\": {}}\n    self.matches.append(section)\n    self.section = section[\"config\"]\n    self.processor = self._ParseMatchGrp",
    "docstring": "Create a new configuration section for each match clause.\n\n    Each match clause is added to the main config, and the criterion that will\n    trigger the match is recorded, as is the configuration.\n\n    Args:\n      val: The value following the 'match' keyword."
  },
  {
    "code": "def console_set_char_background(\n    con: tcod.console.Console,\n    x: int,\n    y: int,\n    col: Tuple[int, int, int],\n    flag: int = BKGND_SET,\n) -> None:\n    lib.TCOD_console_set_char_background(_console(con), x, y, col, flag)",
    "docstring": "Change the background color of x,y to col using a blend mode.\n\n    Args:\n        con (Console): Any Console instance.\n        x (int): Character x position from the left.\n        y (int): Character y position from the top.\n        col (Union[Tuple[int, int, int], Sequence[int]]):\n            An (r, g, b) sequence or Color instance.\n        flag (int): Blending mode to use, defaults to BKGND_SET."
  },
  {
    "code": "def full_restapi_key_transformer(key, attr_desc, value):\n    keys = _FLATTEN.split(attr_desc['key'])\n    return ([_decode_attribute_map_key(k) for k in keys], value)",
    "docstring": "A key transformer that returns the full RestAPI key path.\n\n    :param str _: The attribute name\n    :param dict attr_desc: The attribute metadata\n    :param object value: The value\n    :returns: A list of keys using RestAPI syntax."
  },
  {
    "code": "def append(self, path, data, **kwargs):\n        metadata_response = self._post(\n            path, 'APPEND', expected_status=httplib.TEMPORARY_REDIRECT, **kwargs)\n        data_response = self._requests_session.post(\n            metadata_response.headers['location'], data=data, **self._requests_kwargs)\n        _check_response(data_response)\n        assert not data_response.content",
    "docstring": "Append to the given file.\n\n        :param data: ``bytes`` or a ``file``-like object\n        :param buffersize: The size of the buffer used in transferring data.\n        :type buffersize: int"
  },
  {
    "code": "def _format_value(self, value):\n        value, unit = self.py3.format_units(value, unit=self.unit, si=self.si_units)\n        return self.py3.safe_format(self.format_value, {\"value\": value, \"unit\": unit})",
    "docstring": "Return formatted string"
  },
  {
    "code": "def get(self, server):\n        if not isinstance(server, six.binary_type):\n            server = server.encode('utf-8')\n        data = self._execute('get', server)\n        result = json.loads(data.decode('utf-8'))\n        if result['Username'] == '' and result['Secret'] == '':\n            raise errors.CredentialsNotFound(\n                'No matching credentials in {}'.format(self.program)\n            )\n        return result",
    "docstring": "Retrieve credentials for `server`. If no credentials are found,\n            a `StoreError` will be raised."
  },
  {
    "code": "def gravatar(self, size=20):\n        default = \"mm\"\n        gravatar_url = \"//www.gravatar.com/avatar/\" + hashlib.md5(self.email.lower()).hexdigest() + \"?\"\n        gravatar_url += urllib.urlencode({'d': default, 's': str(size)})\n        return gravatar_url",
    "docstring": "Construct a gravatar image address for the user"
  },
  {
    "code": "def atlas_peer_download_zonefile_inventory( my_hostport, peer_hostport, maxlen, bit_offset=0, timeout=None, peer_table={} ):\n    if timeout is None:\n        timeout = atlas_inv_timeout()\n    interval = 524288\n    peer_inv = \"\"\n    log.debug(\"Download zonefile inventory %s-%s from %s\" % (bit_offset, maxlen, peer_hostport))\n    if bit_offset > maxlen:\n        return peer_inv\n    for offset in xrange( bit_offset, maxlen, interval):\n        next_inv = atlas_peer_get_zonefile_inventory_range( my_hostport, peer_hostport, offset, interval, timeout=timeout, peer_table=peer_table )\n        if next_inv is None:\n            log.debug(\"Failed to sync inventory for %s from %s to %s\" % (peer_hostport, offset, offset+interval))\n            break\n        peer_inv += next_inv\n        if len(next_inv) < interval:\n            break\n    return peer_inv",
    "docstring": "Get the zonefile inventory from the remote peer\n    Start from the given bit_offset\n\n    NOTE: this doesn't update the peer table health by default;\n    you'll have to explicitly pass in a peer table (i.e. setting\n    to {} ensures that nothing happens)."
  },
  {
    "code": "def add(self, child):\n        if isinstance(child, Include):\n            self.add_include(child)\n        elif isinstance(child, Dimension):\n            self.add_dimension(child)\n        elif isinstance(child, Unit):\n            self.add_unit(child)\n        elif isinstance(child, ComponentType):\n            self.add_component_type(child)\n        elif isinstance(child, Component):\n            self.add_component(child)\n        elif isinstance(child, FatComponent):\n            self.add_fat_component(child)\n        elif isinstance(child, Constant):\n            self.add_constant(child)\n        else:\n            raise ModelError('Unsupported child element')",
    "docstring": "Adds a typed child object to the model.\n\n        @param child: Child object to be added."
  },
  {
    "code": "def UnicodeFromCodePage(string):\n  codepage = ctypes.windll.kernel32.GetOEMCP()\n  try:\n    return string.decode(\"cp%s\" % codepage)\n  except UnicodeError:\n    try:\n      return string.decode(\"utf16\", \"ignore\")\n    except UnicodeError:\n      return string.decode(\"utf8\", \"ignore\")",
    "docstring": "Attempt to coerce string into a unicode object."
  },
  {
    "code": "def compress(data, compresslevel=9):\n    buf = io.BytesIO()\n    with GzipFile(fileobj=buf, mode='wb', compresslevel=compresslevel) as f:\n        f.write(data)\n    return buf.getvalue()",
    "docstring": "Compress data in one shot and return the compressed string.\n    Optional argument is the compression level, in range of 0-9."
  },
  {
    "code": "def _u_distance_covariance_sqr_naive(x, y, exponent=1):\n    a = _u_distance_matrix(x, exponent=exponent)\n    b = _u_distance_matrix(y, exponent=exponent)\n    return u_product(a, b)",
    "docstring": "Naive unbiased estimator for distance covariance.\n\n    Computes the unbiased estimator for distance covariance between two\n    matrices, using an :math:`O(N^2)` algorithm."
  },
  {
    "code": "def quote_names(db, names):\n    c = db.cursor()\n    c.execute(\"SELECT pg_catalog.quote_ident(n) FROM pg_catalog.unnest(%s::text[]) n\", [list(names)])\n    return [name for (name,) in c]",
    "docstring": "psycopg2 doesn't know how to quote identifier names, so we ask the server"
  },
  {
    "code": "def enableHook(self, msgObj):\n        self.killListIdx = len(qte_global.kill_list) - 2\n        self.qteMain.qtesigKeyseqComplete.connect(self.disableHook)",
    "docstring": "Enable yank-pop.\n\n        This method is connected to the 'yank-qtmacs_text_edit' hook\n        (triggered by the yank macro) to ensure that yank-pop only\n        gets activated afterwards."
  },
  {
    "code": "def get_default_library_patters():\n    python_version = platform.python_version_tuple()\n    python_implementation = platform.python_implementation()\n    system = platform.system()\n    if python_implementation == \"PyPy\":\n        if python_version[0] == \"2\":\n            return [\"*/lib-python/%s.%s/*\" % python_version[:2], \"*/site-packages/*\"]\n        else:\n            return [\"*/lib-python/%s/*\" % python_version[0], \"*/site-packages/*\"]\n    else:\n        if system == \"Windows\":\n            return [r\"*\\lib\\*\"]\n        return [\"*/lib/python%s.%s/*\" % python_version[:2], \"*/lib64/python%s.%s/*\" % python_version[:2]]",
    "docstring": "Returns library paths depending on the used platform.\n\n    :return: a list of glob paths"
  },
  {
    "code": "def gettext(message):\n    global _default\n    _default = _default or translation(DEFAULT_LANGUAGE)\n    translation_object = getattr(_active, 'value', _default)\n    result = translation_object.gettext(message)\n    return result",
    "docstring": "Translate the 'message' string. It uses the current thread to find the\n    translation object to use. If no current translation is activated, the\n    message will be run through the default translation object."
  },
  {
    "code": "def filter_service_by_servicegroup_name(group):\n    def inner_filter(items):\n        service = items[\"service\"]\n        if service is None:\n            return False\n        return group in [items[\"servicegroups\"][g].servicegroup_name for g in service.servicegroups]\n    return inner_filter",
    "docstring": "Filter for service\n    Filter on group\n\n    :param group: group to filter\n    :type group: str\n    :return: Filter\n    :rtype: bool"
  },
  {
    "code": "def p_next(self):\n        \"Consume and return the next char\"\n        try:\n            self.pos += 1\n            return self.input[self.pos - 1]\n        except IndexError:\n            self.pos -= 1\n            return None",
    "docstring": "Consume and return the next char"
  },
  {
    "code": "def get_roles_by_type(resource_root, service_name, role_type,\n                      cluster_name=\"default\", view=None):\n  roles = get_all_roles(resource_root, service_name, cluster_name, view)\n  return [ r for r in roles if r.type == role_type ]",
    "docstring": "Get all roles of a certain type in a service\n  @param resource_root: The root Resource object.\n  @param service_name: Service name\n  @param role_type: Role type\n  @param cluster_name: Cluster name\n  @return: A list of ApiRole objects."
  },
  {
    "code": "def notify_observers(table, kind, primary_key=None):\n    if IN_MIGRATIONS:\n        return\n    if not Observer.objects.filter(dependencies__table=table).exists():\n        return\n    def handler():\n        try:\n            async_to_sync(get_channel_layer().send)(\n                CHANNEL_MAIN,\n                {\n                    'type': TYPE_ORM_NOTIFY,\n                    'table': table,\n                    'kind': kind,\n                    'primary_key': str(primary_key),\n                },\n            )\n        except ChannelFull:\n            logger.exception(\"Unable to notify workers.\")\n    batcher = PrioritizedBatcher.global_instance()\n    if batcher.is_started:\n        batcher.add(\n            'rest_framework_reactive', handler, group_by=(table, kind, primary_key)\n        )\n    else:\n        handler()",
    "docstring": "Transmit ORM table change notification.\n\n    :param table: Name of the table that has changed\n    :param kind: Change type\n    :param primary_key: Primary key of the affected instance"
  },
  {
    "code": "def convert_2_utc(self, datetime_, timezone):\n        datetime_ = self.tz_mapper[timezone].localize(datetime_)\n        return datetime_.astimezone(pytz.UTC)",
    "docstring": "convert to datetime to UTC offset."
  },
  {
    "code": "def _main_loop(self):\n        self.logger.debug(\"Running main loop\")\n        old_time = 0\n        while True:\n            for plugin_key in self.plugins_dict:\n                obj = self.plugins_dict[plugin_key]\n                self._process_plugin(obj)\n            if self.settings['STATS_DUMP'] != 0:\n                new_time = int(old_div(time.time(), self.settings['STATS_DUMP']))\n                if new_time != old_time:\n                    self._dump_stats()\n                    if self.settings['STATS_DUMP_CRAWL']:\n                        self._dump_crawl_stats()\n                    if self.settings['STATS_DUMP_QUEUE']:\n                        self._dump_queue_stats()\n                    old_time = new_time\n            self._report_self()\n            time.sleep(self.settings['SLEEP_TIME'])",
    "docstring": "The internal while true main loop for the redis monitor"
  },
  {
    "code": "def appendChild(self, param):\n        Symbol.appendChild(self, param)\n        if param.offset is None:\n            param.offset = self.size\n            self.size += param.size",
    "docstring": "Overrides base class."
  },
  {
    "code": "def marker(self):\n        if not self._marker:\n            assert markers, 'Package packaging is needed for environment markers'\n            self._marker = markers.Marker(self.raw)\n        return self._marker",
    "docstring": "Return environment marker."
  },
  {
    "code": "def render_pdf_file_to_image_files_pdftoppm_pgm(pdf_file_name, root_output_file_path,\n                                           res_x=150, res_y=150):\n    comm_output = render_pdf_file_to_image_files_pdftoppm_ppm(pdf_file_name,\n                                        root_output_file_path, res_x, res_y, [\"-gray\"])\n    return comm_output",
    "docstring": "Same as renderPdfFileToImageFile_pdftoppm_ppm but with -gray option for pgm."
  },
  {
    "code": "def writePlist(dataObject, filepath):\n    plistData, error = (\n        NSPropertyListSerialization.\n        dataFromPropertyList_format_errorDescription_(\n            dataObject, NSPropertyListXMLFormat_v1_0, None))\n    if plistData is None:\n        if error:\n            error = error.encode('ascii', 'ignore')\n        else:\n            error = \"Unknown error\"\n        raise NSPropertyListSerializationException(error)\n    else:\n        if plistData.writeToFile_atomically_(filepath, True):\n            return\n        else:\n            raise NSPropertyListWriteException(\n                \"Failed to write plist data to %s\" % filepath)",
    "docstring": "Write 'rootObject' as a plist to filepath."
  },
  {
    "code": "def calculate_weighted_avg(bonds):\n    minimum_bond = min(bonds)\n    weighted_sum = 0.0\n    total_sum = 0.0\n    for entry in bonds:\n        weighted_sum += entry * exp(1 - (entry / minimum_bond) ** 6)\n        total_sum += exp(1 - (entry / minimum_bond) ** 6)\n    return weighted_sum / total_sum",
    "docstring": "Returns the weighted average bond length given by\n    Hoppe's effective coordination number formula.\n\n    Args:\n        bonds (list): list of floats that are the\n        bond distances between a cation and its\n        peripheral ions"
  },
  {
    "code": "def add_dipole_gwb(psr, dist=1, ngw=1000, seed=None, flow=1e-8,\n                   fhigh=1e-5, gwAmp=1e-20,  alpha=-0.66,\n                   logspacing=True, dipoleamps=None, \n                   dipoledir=None, dipolemag=None):\n    gwb = GWB(ngw, seed, flow, fhigh, gwAmp, alpha, logspacing,\n              dipoleamps, dipoledir, dipolemag)\n    gwb.add_gwb(psr,dist)\n    return gwb",
    "docstring": "Add a stochastic background from inspiraling binaries distributed\n    according to a pure dipole distribution, using the tempo2\n    code that underlies the GWdipolebkgrd plugin.\n\n    The basic use is identical to that of 'add_gwb':\n    Here 'dist' is the pulsar distance [in kpc]; 'ngw' is the number of binaries,\n    'seed' (a negative integer) reseeds the GWbkgrd pseudorandom-number-generator,\n    'flow' and 'fhigh' [Hz] determine the background band, 'gwAmp' and 'alpha'\n    determine its amplitude and exponent, and setting 'logspacing' to False\n    will use linear spacing for the individual sources.\n\n    Additionally, the dipole component can be specified by using one of two\n    methods:\n    1) Specify the dipole direction as three dipole amplitudes, in the vector\n    dipoleamps\n    2) Specify the direction of the dipole as a magnitude dipolemag, and a vector\n    dipoledir=[dipolephi, dipoletheta]\n\n    It is also possible to create a background object with\n    \n    gwb = GWB(ngw,seed,flow,fhigh,gwAmp,alpha,logspacing)\n\n    then call the method gwb.add_gwb(pulsar[i],dist) repeatedly to get a\n    consistent background for multiple pulsars.\n    \n    Returns the GWB object"
  },
  {
    "code": "def parse_cobol(lines):\n    output = []\n    intify = [\"level\", \"occurs\"]\n    for row in lines:\n        match = CobolPatterns.row_pattern.match(row.strip())\n        if not match:\n            _logger().warning(\"Found unmatched row %s\" % row.strip())\n            continue\n        match = match.groupdict()\n        for i in intify:\n            match[i] = int(match[i]) if match[i] is not None else None\n        if match['pic'] is not None:\n            match['pic_info'] = parse_pic_string(match['pic'])\n        output.append(match)\n    return output",
    "docstring": "Parses the COBOL\n     - converts the COBOL line into a dictionary containing the information\n     - parses the pic information into type, length, precision\n     - ~~handles redefines~~ -> our implementation does not do that anymore\n       because we want to display item that was redefined."
  },
  {
    "code": "def install_monitor(self, mon):\n        assert self.binded\n        for module in self._modules:\n            module.install_monitor(mon)",
    "docstring": "Installs monitor on all executors."
  },
  {
    "code": "def read_tabular(filepath):\n    _, fn, ext = splitext2(filepath)\n    if ext == '.h5':\n        return _read_tabular_h5(filepath)\n    elif ext == '.pkl':\n        return _read_tabular_pickle(filepath)\n    else:\n        raise NotImplementedError",
    "docstring": "Read tabular object in HDF5 or pickle format\n\n    Args:\n        filepath (path-like): path to read to; must end in '.h5' or '.pkl'"
  },
  {
    "code": "def calculate_svd(data):\n    if (not isinstance(data, np.ndarray)) or (data.ndim != 2):\n        raise TypeError('Input data must be a 2D np.ndarray.')\n    return svd(data, check_finite=False, lapack_driver='gesvd',\n               full_matrices=False)",
    "docstring": "Calculate Singular Value Decomposition\n\n    This method calculates the Singular Value Decomposition (SVD) of the input\n    data using SciPy.\n\n    Parameters\n    ----------\n    data : np.ndarray\n        Input data array, 2D matrix\n\n    Returns\n    -------\n    tuple of left singular vector, singular values and right singular vector\n\n    Raises\n    ------\n    TypeError\n        For invalid data type"
  },
  {
    "code": "def _branch_name(cls, version):\n    suffix = version.public[len(version.base_version):]\n    components = version.base_version.split('.') + [suffix]\n    if suffix == '' or suffix.startswith('rc'):\n      return '{}.{}.x'.format(*components[:2])\n    elif suffix.startswith('.dev'):\n      return 'master'\n    else:\n      raise ValueError('Unparseable pants version number: {}'.format(version))",
    "docstring": "Defines a mapping between versions and branches.\n\n    In particular, `-dev` suffixed releases always live on master. Any other (modern) release\n    lives in a branch."
  },
  {
    "code": "def set_ip_port(self, ip, port):\n        self.address = ip\n        self.port = port\n        self.stop()\n        self.start()",
    "docstring": "set ip and port"
  },
  {
    "code": "def get_lock_request(name, version, patch_lock, weak=True):\n    ch = '~' if weak else ''\n    if patch_lock == PatchLock.lock:\n        s = \"%s%s==%s\" % (ch, name, str(version))\n        return PackageRequest(s)\n    elif (patch_lock == PatchLock.no_lock) or (not version):\n        return None\n    version_ = version.trim(patch_lock.rank)\n    s = \"%s%s-%s\" % (ch, name, str(version_))\n    return PackageRequest(s)",
    "docstring": "Given a package and patch lock, return the equivalent request.\n\n    For example, for object 'foo-1.2.1' and lock type 'lock_3', the equivalent\n    request is '~foo-1.2'. This restricts updates to foo to patch-or-lower\n    version changes only.\n\n    For objects not versioned down to a given lock level, the closest possible\n    lock is applied. So 'lock_3' applied to 'foo-1' would give '~foo-1'.\n\n    Args:\n        name (str): Package name.\n        version (Version): Package version.\n        patch_lock (PatchLock): Lock type to apply.\n\n    Returns:\n        `PackageRequest` object, or None if there is no equivalent request."
  },
  {
    "code": "def get_meta_attributes(self, **kwargs):\n        superuser = kwargs.get('superuser', False)\n        if (self.untl_object.qualifier == 'recordStatus'\n                or self.untl_object.qualifier == 'system'):\n            if superuser:\n                self.editable = True\n                self.repeatable = True\n            else:\n                self.editable = False\n            self.view_type = 'qualified-input'\n        elif self.untl_object.qualifier == 'hidden':\n            self.label = 'Object Hidden'\n            self.view_type = 'radio'\n        else:\n            self.editable = False\n            self.view_type = 'qualified-input'",
    "docstring": "Determine the form attributes for the meta field."
  },
  {
    "code": "def terminal_title(self):\n        result = self.application.get_title()\n        assert result is None or isinstance(result, six.text_type)\n        return result",
    "docstring": "Return the current title to be displayed in the terminal.\n        When this in `None`, the terminal title remains the original."
  },
  {
    "code": "def detach_framebuffer(self, screen_id, id_p):\n        if not isinstance(screen_id, baseinteger):\n            raise TypeError(\"screen_id can only be an instance of type baseinteger\")\n        if not isinstance(id_p, basestring):\n            raise TypeError(\"id_p can only be an instance of type basestring\")\n        self._call(\"detachFramebuffer\",\n                     in_p=[screen_id, id_p])",
    "docstring": "Removes the graphics updates target for a screen.\n\n        in screen_id of type int\n\n        in id_p of type str"
  },
  {
    "code": "def _get_var_name(self, name, fresh=False):\n        if name not in self._var_name_mappers:\n            self._var_name_mappers[name] = VariableNamer(name)\n        if fresh:\n            var_name = self._var_name_mappers[name].get_next()\n        else:\n            var_name = self._var_name_mappers[name].get_current()\n        return var_name",
    "docstring": "Get variable name."
  },
  {
    "code": "def is_regex_type(type_):\n    return (\n        callable(type_)\n        and getattr(type_, \"__name__\", None) == REGEX_TYPE_NAME\n        and hasattr(type_, \"__supertype__\")\n        and is_compiled_pattern(type_.__supertype__)\n    )",
    "docstring": "Checks if the given type is a regex type.\n\n    :param type_: The type to check\n    :return: True if the type is a regex type, otherwise False\n    :rtype: bool"
  },
  {
    "code": "def get_properties_of_managed_object(mo_ref, properties):\n    service_instance = get_service_instance_from_managed_object(mo_ref)\n    log.trace('Retrieving name of %s', type(mo_ref).__name__)\n    try:\n        items = get_mors_with_properties(service_instance,\n                                         type(mo_ref),\n                                         container_ref=mo_ref,\n                                         property_list=['name'],\n                                         local_properties=True)\n        mo_name = items[0]['name']\n    except vmodl.query.InvalidProperty:\n        mo_name = '<unnamed>'\n    log.trace('Retrieving properties \\'%s\\' of %s \\'%s\\'',\n              properties, type(mo_ref).__name__, mo_name)\n    items = get_mors_with_properties(service_instance,\n                                     type(mo_ref),\n                                     container_ref=mo_ref,\n                                     property_list=properties,\n                                     local_properties=True)\n    if not items:\n        raise salt.exceptions.VMwareApiError(\n            'Properties of managed object \\'{0}\\' weren\\'t '\n            'retrieved'.format(mo_name))\n    return items[0]",
    "docstring": "Returns specific properties of a managed object, retrieved in an\n    optimally.\n\n    mo_ref\n        The managed object reference.\n\n    properties\n        List of properties of the managed object to retrieve."
  },
  {
    "code": "def post_intent(self, intent_json):\n        endpoint = self._intent_uri()\n        return self._post(endpoint, data=intent_json)",
    "docstring": "Sends post request to create a new intent"
  },
  {
    "code": "def clean(self):\n        self.feed()\n        if self.current_parent_element['tag'] != '':\n            self.cleaned_html += '</{}>'.format(self.current_parent_element['tag'])\n        self.cleaned_html = re.sub(r'(</[u|o]l>)<p></p>', r'\\g<1>', self.cleaned_html)\n        self._remove_pre_formatting()\n        return self.cleaned_html",
    "docstring": "Goes through the txt input and cleans up any problematic HTML."
  },
  {
    "code": "def set_add(parent, idx, value):\n  lst = get_child(parent, idx)\n  if value not in lst:\n    lst.append(value)",
    "docstring": "Add an item to a list if it doesn't exist."
  },
  {
    "code": "def set_offset_and_sequence_number(self, event_data):\n        if not event_data:\n            raise Exception(event_data)\n        self.offset = event_data.offset.value\n        self.sequence_number = event_data.sequence_number",
    "docstring": "Updates offset based on event.\n\n        :param event_data: A received EventData with valid offset and sequenceNumber.\n        :type event_data: ~azure.eventhub.common.EventData"
  },
  {
    "code": "def __initialize_languages_model(self):\n        languages = [PYTHON_LANGUAGE, LOGGING_LANGUAGE, TEXT_LANGUAGE]\n        existingGrammarFiles = [os.path.normpath(language.file) for language in languages]\n        for directory in RuntimeGlobals.resources_directories:\n            for file in foundations.walkers.files_walker(directory, (\"\\.{0}$\".format(self.__extension),), (\"\\._\",)):\n                if os.path.normpath(file) in existingGrammarFiles:\n                    continue\n                languageDescription = get_language_description(file)\n                if not languageDescription:\n                    continue\n                LOGGER.debug(\"> Adding '{0}' language to model.\".format(languageDescription))\n                languages.append(languageDescription)\n        self.__languages_model = LanguagesModel(self, sorted(languages, key=lambda x: (x.name)))\n        self.__get_supported_file_types_string()",
    "docstring": "Initializes the languages Model."
  },
  {
    "code": "def reduce_sum_square(attrs, inputs, proto_obj):\n    square_op = symbol.square(inputs[0])\n    sum_op = symbol.sum(square_op, axis=attrs.get('axes'),\n                        keepdims=attrs.get('keepdims'))\n    return sum_op, attrs, inputs",
    "docstring": "Reduce the array along a given axis by sum square value"
  },
  {
    "code": "def get_next_line(self):\n        line = self.freq_file.readline().strip().split()\n        if len(line) < 1:\n            self.load_genotypes()\n            line = self.freq_file.readline().strip().split()\n        info_line = self.info_file.readline().strip().split()\n        info = float(info_line[4])\n        exp_freq = float(info_line[3])\n        return line, info, exp_freq",
    "docstring": "If we reach the end of the file, we simply open the next, until we \\\n        run out of archives to process"
  },
  {
    "code": "def _unstack_extension_series(series, level, fill_value):\n    from pandas.core.reshape.concat import concat\n    dummy_arr = np.arange(len(series))\n    result = _Unstacker(dummy_arr, series.index,\n                        level=level, fill_value=-1).get_result()\n    out = []\n    values = extract_array(series, extract_numpy=False)\n    for col, indices in result.iteritems():\n        out.append(Series(values.take(indices.values,\n                                      allow_fill=True,\n                                      fill_value=fill_value),\n                          name=col, index=result.index))\n    return concat(out, axis='columns', copy=False, keys=result.columns)",
    "docstring": "Unstack an ExtensionArray-backed Series.\n\n    The ExtensionDtype is preserved.\n\n    Parameters\n    ----------\n    series : Series\n        A Series with an ExtensionArray for values\n    level : Any\n        The level name or number.\n    fill_value : Any\n        The user-level (not physical storage) fill value to use for\n        missing values introduced by the reshape. Passed to\n        ``series.values.take``.\n\n    Returns\n    -------\n    DataFrame\n        Each column of the DataFrame will have the same dtype as\n        the input Series."
  },
  {
    "code": "def delete(self, ids):\n        url = build_uri_with_ids('api/v3/vip-request/%s/', ids)\n        return super(ApiVipRequest, self).delete(url)",
    "docstring": "Method to delete vip's by their id's\n\n        :param ids: Identifiers of vip's\n        :return: None"
  },
  {
    "code": "def compute_err_score(true_positives, n_ref, n_est):\n    n_ref_sum = float(n_ref.sum())\n    if n_ref_sum == 0:\n        warnings.warn(\"Reference frequencies are all empty.\")\n        return 0., 0., 0., 0.\n    e_sub = (np.min([n_ref, n_est], axis=0) - true_positives).sum()/n_ref_sum\n    e_miss_numerator = n_ref - n_est\n    e_miss_numerator[e_miss_numerator < 0] = 0\n    e_miss = e_miss_numerator.sum()/n_ref_sum\n    e_fa_numerator = n_est - n_ref\n    e_fa_numerator[e_fa_numerator < 0] = 0\n    e_fa = e_fa_numerator.sum()/n_ref_sum\n    e_tot = (np.max([n_ref, n_est], axis=0) - true_positives).sum()/n_ref_sum\n    return e_sub, e_miss, e_fa, e_tot",
    "docstring": "Compute error score metrics.\n\n    Parameters\n    ----------\n    true_positives : np.ndarray\n        Array containing the number of true positives at each time point.\n    n_ref : np.ndarray\n        Array containing the number of reference frequencies at each time\n        point.\n    n_est : np.ndarray\n        Array containing the number of estimate frequencies at each time point.\n\n    Returns\n    -------\n    e_sub : float\n        Substitution error\n    e_miss : float\n        Miss error\n    e_fa : float\n        False alarm error\n    e_tot : float\n        Total error"
  },
  {
    "code": "def exclude(self, target, operation, role, value):\n        target = {\"result\": self.data[\"proxies\"][\"result\"],\n                  \"instance\": self.data[\"proxies\"][\"instance\"],\n                  \"plugin\": self.data[\"proxies\"][\"plugin\"]}[target]\n        if operation == \"add\":\n            target.add_exclusion(role, value)\n        elif operation == \"remove\":\n            target.remove_exclusion(role, value)\n        else:\n            raise TypeError(\"operation must be either `add` or `remove`\")",
    "docstring": "Exclude a `role` of `value` at `target`\n\n        Arguments:\n            target (str): Destination proxy model\n            operation (str): \"add\" or \"remove\" exclusion\n            role (str): Role to exclude\n            value (str): Value of `role` to exclude"
  },
  {
    "code": "def WaitUntilComplete(self,poll_freq=2,timeout=None):\n\t\tstart_time = time.time()\n\t\twhile not self.time_completed:\n\t\t\tstatus = self.Status()\n\t\t\tif status == 'executing':\n\t\t\t\tif not self.time_executed:  self.time_executed = time.time()\n\t\t\t\tif clc.v2.time_utils.TimeoutExpired(start_time, timeout):\n\t\t\t\t\traise clc.RequestTimeoutException('Timeout waiting for Request: {0}'.format(self.id), status)\n\t\t\telif status == 'succeeded':\n\t\t\t\tself.time_completed = time.time()\n\t\t\telif status in (\"failed\", \"resumed\" or \"unknown\"):\n\t\t\t\tself.time_completed = time.time()\n\t\t\t\traise(clc.CLCException(\"%s %s execution %s\" % (self.context_key,self.context_val,status)))\n\t\t\ttime.sleep(poll_freq)",
    "docstring": "Poll until status is completed.\n\n\t\tIf status is 'notStarted' or 'executing' continue polling.\n\t\tIf status is 'succeeded' return\n\t\tElse raise exception\n\n\t\tpoll_freq option is in seconds"
  },
  {
    "code": "def delete_existing_policy(self, scaling_policy, server_group):\n        self.log.info(\"Deleting policy %s on %s\", scaling_policy['policyName'], server_group)\n        delete_dict = {\n            \"application\":\n            self.app,\n            \"description\":\n            \"Delete scaling policy\",\n            \"job\": [{\n                \"policyName\": scaling_policy['policyName'],\n                \"serverGroupName\": server_group,\n                \"credentials\": self.env,\n                \"region\": self.region,\n                \"provider\": \"aws\",\n                \"type\": \"deleteScalingPolicy\",\n                \"user\": \"foremast-autoscaling-policy\"\n            }]\n        }\n        wait_for_task(json.dumps(delete_dict))",
    "docstring": "Given a scaling_policy and server_group, deletes the existing scaling_policy.\n        Scaling policies need to be deleted instead of upserted for consistency.\n\n        Args:\n            scaling_policy (json): the scaling_policy json from Spinnaker that should be deleted\n            server_group (str): the affected server_group"
  },
  {
    "code": "def to_array(self):\n        array = super(ReplyKeyboardMarkup, self).to_array()\n        array['keyboard'] = self._as_array(self.keyboard)\n        if self.resize_keyboard is not None:\n            array['resize_keyboard'] = bool(self.resize_keyboard)\n        if self.one_time_keyboard is not None:\n            array['one_time_keyboard'] = bool(self.one_time_keyboard)\n        if self.selective is not None:\n            array['selective'] = bool(self.selective)\n        return array",
    "docstring": "Serializes this ReplyKeyboardMarkup to a dictionary.\n\n        :return: dictionary representation of this object.\n        :rtype: dict"
  },
  {
    "code": "def on_server_shutdown(self):\n        if not self._container:\n            return\n        self._container.stop()\n        self._container.remove(v=True, force=True)",
    "docstring": "Stop the container before shutting down."
  },
  {
    "code": "def get_fixed_param_names(self) -> List[str]:\n        args = set(self.args.keys()) | set(self.auxs.keys())\n        return list(args & set(self.sym.list_arguments()))",
    "docstring": "Get the fixed params of the network.\n\n        :return: List of strings, names of the layers"
  },
  {
    "code": "def GetPathSegmentAndSuffix(self, base_path, path):\n    if path is None or base_path is None or not path.startswith(base_path):\n      return None, None\n    path_index = len(base_path)\n    if base_path and not base_path.endswith(self.PATH_SEPARATOR):\n      path_index += 1\n    if path_index == len(path):\n      return '', ''\n    path_segment, _, suffix = path[path_index:].partition(self.PATH_SEPARATOR)\n    return path_segment, suffix",
    "docstring": "Determines the path segment and suffix of the path.\n\n    None is returned if the path does not start with the base path and\n    an empty string if the path exactly matches the base path.\n\n    Args:\n      base_path (str): base path.\n      path (str): path.\n\n    Returns:\n      tuple[str, str]: path segment and suffix string."
  },
  {
    "code": "def _fluent_size(self, fluents, ordering) -> Sequence[Sequence[int]]:\n        shapes = []\n        for name in ordering:\n            fluent = fluents[name]\n            shape = self._param_types_to_shape(fluent.param_types)\n            shapes.append(shape)\n        return tuple(shapes)",
    "docstring": "Returns the sizes of `fluents` following the given `ordering`.\n\n        Returns:\n            Sequence[Sequence[int]]: A tuple of tuple of integers\n            representing the shape and size of each fluent."
  },
  {
    "code": "def application_unauthenticated(request, token, state=None, label=None):\n    application = base.get_application(secret_token=token)\n    if application.expires < datetime.datetime.now():\n        return render(\n            template_name='kgapplications/common_expired.html',\n            context={'application': application},\n            request=request)\n    roles = {'is_applicant', 'is_authorised'}\n    if request.user.is_authenticated:\n        if request.user == application.applicant:\n            url = base.get_url(\n                request, application, roles, label)\n            return HttpResponseRedirect(url)\n    state_machine = base.get_state_machine(application)\n    return state_machine.process(\n        request, application, state, label, roles)",
    "docstring": "An somebody is trying to access an application."
  },
  {
    "code": "def split_fasta(f, id2f):\n    opened = {}\n    for seq in parse_fasta(f):\n        id = seq[0].split('>')[1].split()[0]\n        if id not in id2f:\n            continue\n        fasta = id2f[id]\n        if fasta not in opened:\n            opened[fasta] = '%s.fa' % fasta\n        seq[1] += '\\n'\n        with open(opened[fasta], 'a+') as f_out:\n            f_out.write('\\n'.join(seq))",
    "docstring": "split fasta file into separate fasta files based on list of scaffolds\n    that belong to each separate file"
  },
  {
    "code": "def create_payload(entities):\n        types = {e.etype for e in entities}\n        if len(types) != 1:\n            raise ValueError(\"Can't create payload with \" +\n                             str(len(types)) + \" types\")\n        all_attrs = set()\n        for e in entities:\n            all_attrs.update(set(e.attrs.keys()))\n        all_attrs = list(all_attrs)\n        header = \"entity:\" + entities[0].etype + \"_id\"\n        payload = '\\t'.join([header] + all_attrs) + '\\n'\n        for e in entities:\n            line = e.entity_id\n            for a in all_attrs:\n                line += '\\t' + e.attrs.get(a, \"\")\n            payload += line + '\\n'\n        return payload",
    "docstring": "Create a tsv payload describing entities.\n\n        A TSV payload consists of 1 header row describing entity type\n        and attribute names. Each subsequent line is an entity_id followed\n        by attribute values separated by the tab \"\\\\t\" character. This\n        payload can be uploaded to the workspace via\n        firecloud.api.upload_entities()"
  },
  {
    "code": "def get_application_configurations(self, name=None):\n        if hasattr(self, 'applicationConfigurations'):\n           return self._get_elements(self.applicationConfigurations, 'applicationConfigurations', ApplicationConfiguration, None, name)",
    "docstring": "Retrieves application configurations for this instance.\n\n        Args:\n            name (str, optional): Only return application configurations containing property **name** that matches `name`. `name` can be a\n                regular expression. If `name` is not supplied, then all application configurations are returned.\n\n        Returns:\n            list(ApplicationConfiguration): A list of application configurations matching the given `name`.\n        \n        .. versionadded 1.12"
  },
  {
    "code": "def generate_span_requests(self, span_datas):\n        pb_spans = [\n            utils.translate_to_trace_proto(span_data)\n            for span_data in span_datas\n        ]\n        yield trace_service_pb2.ExportTraceServiceRequest(\n            node=self.node,\n            spans=pb_spans)",
    "docstring": "Span request generator.\n\n        :type span_datas: list of\n                         :class:`~opencensus.trace.span_data.SpanData`\n        :param span_datas: SpanData tuples to convert to protobuf spans\n                           and send to opensensusd agent\n\n        :rtype: list of\n                `~gen.opencensus.agent.trace.v1.trace_service_pb2.ExportTraceServiceRequest`\n        :returns: List of span export requests."
  },
  {
    "code": "def _force_close(self, file_length=None):\n    if file_length is None:\n      file_length = self._get_offset_from_gcs() + 1\n    self._send_data('', 0, file_length)",
    "docstring": "Close this buffer on file_length.\n\n    Finalize this upload immediately on file_length.\n    Contents that are still in memory will not be uploaded.\n\n    This is a utility method that does not modify self.\n\n    Args:\n      file_length: file length. Must match what has been uploaded. If None,\n        it will be queried from GCS."
  },
  {
    "code": "def reverse_translate(\n        protein_seq,\n        template_dna=None, leading_seq=None, trailing_seq=None,\n        forbidden_seqs=(), include_stop=True, manufacturer=None):\n    if manufacturer == 'gen9':\n        forbidden_seqs += gen9.reserved_restriction_sites\n    leading_seq = restriction_sites.get(leading_seq, leading_seq or '')\n    trailing_seq = restriction_sites.get(trailing_seq, trailing_seq or '')\n    codon_list = make_codon_list(protein_seq, template_dna, include_stop)\n    sanitize_codon_list(codon_list, forbidden_seqs)\n    dna_seq = leading_seq + ''.join(codon_list) + trailing_seq\n    if manufacturer == 'gen9':\n        gen9.apply_quality_control_checks(dna_seq)\n    return dna_seq",
    "docstring": "Generate a well-behaved DNA sequence from the given protein sequence.  If a \n    template DNA sequence is specified, the returned DNA sequence will be as \n    similar to it  as possible.  Any given restriction sites will not be \n    present in the sequence.  And finally, the given leading and trailing \n    sequences will be appropriately concatenated."
  },
  {
    "code": "def set_error_callback(self, callback):\n        self.logger.debug('Setting error callback: %r', callback)\n        self._on_error = callback",
    "docstring": "Assign a method to invoke when a request has encountered an\n        unrecoverable error in an action execution.\n\n        :param method callback: The method to invoke"
  },
  {
    "code": "def will_tag(self):\n        wanttags = self.retrieve_config('Tag', 'no')\n        if wanttags == 'yes':\n            if aux.staggerexists:\n                willtag = True\n            else:\n                willtag = False\n                print((\"You want me to tag {0}, but you have not installed \"\n                       \"the Stagger module. I cannot honour your request.\").\n                      format(self.name), file=sys.stderr, flush=True)\n        else:\n            willtag = False\n        return willtag",
    "docstring": "Check whether the feed should be tagged"
  },
  {
    "code": "def getAttributeValueData(self, index):\n        offset = self._get_attribute_offset(index)\n        return self.m_attributes[offset + const.ATTRIBUTE_IX_VALUE_DATA]",
    "docstring": "Return the data of the attribute at the given index\n\n        :param index: index of the attribute"
  },
  {
    "code": "def _retrieve(self):\n        url = \"%s://%s:%d/manager/status\" % (self._proto, self._host, self._port)\n        params = {}\n        params['XML'] = 'true'\n        response = util.get_url(url, self._user, self._password, params)\n        tree = ElementTree.XML(response)\n        return tree",
    "docstring": "Query Apache Tomcat Server Status Page in XML format and return \n        the result as an ElementTree object.\n        \n        @return: ElementTree object of Status Page XML."
  },
  {
    "code": "def getPortType(self):\n        wsdl = self.getService().getWSDL()\n        binding = wsdl.bindings[self.binding]\n        return wsdl.portTypes[binding.type]",
    "docstring": "Return the PortType object that is referenced by this port."
  },
  {
    "code": "def drop_index(self, name):\n        name = self._normalize_identifier(name)\n        if not self.has_index(name):\n            raise IndexDoesNotExist(name, self._name)\n        del self._indexes[name]",
    "docstring": "Drops an index from this table.\n\n        :param name: The index name\n        :type name: str"
  },
  {
    "code": "def print_debug(*args, **kwargs):\n    if WTF_CONFIG_READER.get(\"debug\", False) == True:\n        print(*args, **kwargs)",
    "docstring": "Print if and only if the debug flag is set true in the config.yaml file.\n\n    Args:\n        args : var args of print arguments."
  },
  {
    "code": "def connect(self, their_unl, events, force_master=1, hairpin=1,\r\n                nonce=\"0\" * 64):\r\n        parms = (their_unl, events, force_master, hairpin, nonce)\r\n        t = Thread(target=self.connect_handler, args=parms)\r\n        t.start()\r\n        self.unl_threads.append(t)",
    "docstring": "A new thread is spawned because many of the connection techniques\r\n        rely on sleep to determine connection outcome or to synchronise hole\r\n        punching techniques. If the sleep is in its own thread it won't\r\n        block main execution."
  },
  {
    "code": "def _reload(self, force=False):\n        self._config_map = dict()\n        self._registered_env_keys = set()\n        self.__reload_sources(force)\n        self.__load_environment_keys()\n        self.verify()\n        self._clear_memoization()",
    "docstring": "Reloads the configuration from the file and environment variables. Useful if using\n        `os.environ` instead of this class' `set_env` method, or if the underlying configuration\n        file is changed externally."
  },
  {
    "code": "def ipv4_range_type(string):\n    import re\n    ip_format = r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'\n    if not re.match(\"^{}$\".format(ip_format), string):\n        if not re.match(\"^{ip_format}-{ip_format}$\".format(ip_format=ip_format), string):\n            raise ValueError\n    return string",
    "docstring": "Validates an IPv4 address or address range."
  },
  {
    "code": "def Connect(self, Skype):\n        self._Skype = Skype\n        self._Skype.RegisterEventHandler('CallStatus', self._CallStatus)\n        del self._Channels[:]",
    "docstring": "Connects this call channel manager instance to Skype. This is the first thing you should\n        do after creating this object.\n\n        :Parameters:\n          Skype : `Skype`\n            The Skype object.\n\n        :see: `Disconnect`"
  },
  {
    "code": "def default(value):\n    if isinstance(value, Decimal):\n        primative = float(value)\n        if int(primative) == primative:\n            return int(primative)\n        else:\n            return primative\n    elif isinstance(value, set):\n        return list(value)\n    elif isinstance(value, Binary):\n        return b64encode(value.value)\n    raise TypeError(\"Cannot encode %s value %r\" % (type(value), value))",
    "docstring": "Default encoder for JSON"
  },
  {
    "code": "def mouse_move_event(self, event):\r\n        self.example.mouse_position_event(event.x(), event.y())",
    "docstring": "Forward mouse cursor position events to the example"
  },
  {
    "code": "def uniform_pdf():\n    norm_const = 1.0\n    def pdf(x):\n        return norm_const * np.sin(np.pi/180.0 * x)\n    norm_dev = quad(pdf, 0.0, 180.0)[0]\n    norm_const /= norm_dev \n    return pdf",
    "docstring": "Uniform PDF for orientation averaging.\n\n    Returns:\n        pdf(x), a function that returns the value of the spherical Jacobian-\n        normalized uniform PDF. It is normalized for the interval [0, 180]."
  },
  {
    "code": "def _get_result_files_base(self, temp_dir):\n        if not self._use_namespaces:\n            return super(ContainerExecutor, self)._get_result_files_base(temp_dir)\n        else:\n            return os.path.join(temp_dir, \"temp\")",
    "docstring": "Given the temp directory that is created for each run, return the path to the directory\n        where files created by the tool are stored."
  },
  {
    "code": "def enable_global_typechecked_profiler(flag = True):\n    global global_typechecked_profiler, _global_type_agent, global_typelogged_profiler\n    global_typechecked_profiler = flag\n    if flag and checking_enabled:\n        if _global_type_agent is None:\n            _global_type_agent = TypeAgent()\n            _global_type_agent.start()\n        elif not _global_type_agent.active:\n            _global_type_agent.start()\n    elif not flag and not global_typelogged_profiler and \\\n            not _global_type_agent is None and _global_type_agent.active:\n        _global_type_agent.stop()",
    "docstring": "Enables or disables global typechecking mode via a profiler.\n    See flag global_typechecked_profiler.\n    Does not work if checking_enabled is false."
  },
  {
    "code": "def closure_for_targets(cls, target_roots, exclude_scopes=None, include_scopes=None,\n                          bfs=None, postorder=None, respect_intransitive=False):\n    target_roots = list(target_roots)\n    if not target_roots:\n      return OrderedSet()\n    build_graph = target_roots[0]._build_graph\n    addresses = [target.address for target in target_roots]\n    dep_predicate = cls._closure_dep_predicate(target_roots,\n                                               include_scopes=include_scopes,\n                                               exclude_scopes=exclude_scopes,\n                                               respect_intransitive=respect_intransitive)\n    closure = OrderedSet()\n    if not bfs:\n      build_graph.walk_transitive_dependency_graph(\n        addresses=addresses,\n        work=closure.add,\n        postorder=postorder,\n        dep_predicate=dep_predicate,\n      )\n    else:\n      closure.update(build_graph.transitive_subgraph_of_addresses_bfs(\n        addresses=addresses,\n        dep_predicate=dep_predicate,\n      ))\n    closure.update(target_roots)\n    return closure",
    "docstring": "Computes the closure of the given targets respecting the given input scopes.\n\n    :API: public\n\n    :param list target_roots: The list of Targets to start from. These targets will always be\n      included in the closure, regardless of scope settings.\n    :param Scope exclude_scopes: If present and non-empty, only dependencies which have none of the\n      scope names in this Scope will be traversed.\n    :param Scope include_scopes: If present and non-empty, only dependencies which have at least one\n      of the scope names in this Scope will be traversed.\n    :param bool bfs: Whether to traverse in breadth-first or depth-first order. (Defaults to True).\n    :param bool respect_intransitive: If True, any dependencies which have the 'intransitive' scope\n      will not be included unless they are direct dependencies of one of the root targets. (Defaults\n      to False)."
  },
  {
    "code": "def config_logging(args):\n    if args.quiet:\n        logging.getLogger().setLevel(logging.CRITICAL)\n    elif args.verbose:\n        logging.getLogger().setLevel(logging.DEBUG)",
    "docstring": "Override root logger's level"
  },
  {
    "code": "def get_counted_number(context, config, variables, **kw):\n    ctx = config.get(\"context\")\n    obj = variables.get(ctx, context)\n    counter_type = config.get(\"counter_type\")\n    counter_reference = config.get(\"counter_reference\")\n    seq_items = get_objects_in_sequence(obj, counter_type, counter_reference)\n    number = len(seq_items)\n    return number",
    "docstring": "Compute the number for the sequence type \"Counter\""
  },
  {
    "code": "def opt_restore(prefix, opts):\n    return {prefix + name: value for name, value in opts.items()}",
    "docstring": "Given a dict of opts, add the given prefix to each key"
  },
  {
    "code": "def extend_webfont_settings(webfont_settings):\n    if not webfont_settings.get('fontdir_path', False):\n        raise IcomoonSettingsError((\"Webfont settings miss the required key \"\n                                    \"item 'fontdir_path'\"))\n    if not webfont_settings.get('csspart_path', False):\n        webfont_settings['csspart_path'] = None\n    return webfont_settings",
    "docstring": "Validate a webfont settings and optionally fill missing ``csspart_path``\n    option.\n\n    Args:\n        webfont_settings (dict): Webfont settings (an item value from\n            ``settings.ICOMOON_WEBFONTS``).\n\n    Returns:\n        dict: Webfont settings"
  },
  {
    "code": "def read_binary_array(self, key, b64decode=True, decode=False):\n        data = None\n        if key is not None:\n            data = self.db.read(key.strip())\n            if data is not None:\n                data_decoded = []\n                for d in json.loads(data, object_pairs_hook=OrderedDict):\n                    if b64decode:\n                        dd = base64.b64decode(d)\n                        if decode:\n                            try:\n                                dd = dd.decode('utf-8')\n                            except UnicodeDecodeError:\n                                dd = dd.decode('latin-1')\n                        data_decoded.append(dd)\n                    else:\n                        data_decoded.append(d)\n                data = data_decoded\n        else:\n            self.tcex.log.warning(u'The key field was None.')\n        return data",
    "docstring": "Read method of CRUD operation for binary array data.\n\n        Args:\n            key (string): The variable to read from the DB.\n            b64decode (bool): If true the data will be base64 decoded.\n            decode (bool): If true the data will be decoded to a String.\n\n        Returns:\n            (list): Results retrieved from DB."
  },
  {
    "code": "def set_style(primary=None, secondary=None):\n    global _primary_style, _secondary_style\n    if primary:\n        _primary_style = primary\n    if secondary:\n        _secondary_style = secondary",
    "docstring": "Sets primary and secondary component styles."
  },
  {
    "code": "def output_sizes(self):\n    return tuple([l() if callable(l) else l for l in self._output_sizes])",
    "docstring": "Returns a tuple of all output sizes of all the layers."
  },
  {
    "code": "def get_crumb_list_by_selector(self, crumb_selector):\n        return [\n            self.parsedpage.get_text_from_node(crumb)\n            for crumb in self.parsedpage.get_nodes_by_selector(crumb_selector)\n        ]",
    "docstring": "Return a list of crumbs."
  },
  {
    "code": "def run_keepedalive_process(main_write_pipe, process_read_pipe, obj):\n    while obj != 'stop':\n        oneshot_in_process(obj)\n        main_write_pipe.send('job is done')\n        readers = [process_read_pipe]\n        while readers:\n            for r in wait(readers):\n                try:\n                    obj = r.recv()\n                except EOFError:\n                    pass\n                finally:\n                    readers.remove(r)",
    "docstring": "Procees who don't finish while job to do"
  },
  {
    "code": "def com_google_fonts_check_metadata_valid_name_values(style,\n                                                      font_metadata,\n                                                      font_familynames,\n                                                      typographic_familynames):\n  from fontbakery.constants import RIBBI_STYLE_NAMES\n  if style in RIBBI_STYLE_NAMES:\n    familynames = font_familynames\n  else:\n    familynames = typographic_familynames\n  failed = False\n  for font_familyname in familynames:\n    if font_familyname not in font_metadata.name:\n      failed = True\n      yield FAIL, (\"METADATA.pb font.name field (\\\"{}\\\")\"\n                   \" does not match correct font name format (\\\"{}\\\").\"\n                   \"\").format(font_metadata.name,\n                              font_familyname)\n  if not failed:\n    yield PASS, (\"METADATA.pb font.name field contains\"\n                 \" font name in right format.\")",
    "docstring": "METADATA.pb font.name field contains font name in right format?"
  },
  {
    "code": "def decode_transaction_input(self, transaction_hash: bytes) -> Dict:\n        transaction = self.contract.web3.eth.getTransaction(\n            transaction_hash,\n        )\n        return self.contract.decode_function_input(\n            transaction['input'],\n        )",
    "docstring": "Return inputs of a method call"
  },
  {
    "code": "def Grow(self,size):\n\t\tif size>1024:  raise(clc.CLCException(\"Cannot grow disk beyond 1024GB\"))\n\t\tif size<=self.size:  raise(clc.CLCException(\"New size must exceed current disk size\"))\n\t\tdisk_set = [{'diskId': o.id, 'sizeGB': o.size} for o in self.parent.disks if o!=self]\n\t\tself.size = size\n\t\tdisk_set.append({'diskId': self.id, 'sizeGB': self.size})\n\t\tself.parent.server.dirty = True\n\t\treturn(clc.v2.Requests(clc.v2.API.Call('PATCH','servers/%s/%s' % (self.parent.server.alias,self.parent.server.id),\n\t\t                                       json.dumps([{\"op\": \"set\", \"member\": \"disks\", \"value\": disk_set}]),\n\t\t\t\t\t\t\t\t\t\t\t   session=self.session),\n\t\t\t\t\t\t\t   alias=self.parent.server.alias,\n\t\t\t\t\t\t\t   session=self.session))",
    "docstring": "Grow disk to the newly specified size.\n\n\t\tSize must be less than 1024 and must be greater than the current size.\n\n\t\t>>> clc.v2.Server(\"WA1BTDIX01\").Disks().disks[2].Grow(30).WaitUntilComplete()\n\t\t0"
  },
  {
    "code": "def model(self):\n        if self.is_bootloader:\n            out = self.fastboot.getvar('product').strip()\n            lines = out.decode('utf-8').split('\\n', 1)\n            if lines:\n                tokens = lines[0].split(' ')\n                if len(tokens) > 1:\n                    return tokens[1].lower()\n            return None\n        model = self.adb.getprop('ro.build.product').lower()\n        if model == 'sprout':\n            return model\n        return self.adb.getprop('ro.product.name').lower()",
    "docstring": "The Android code name for the device."
  },
  {
    "code": "def save(self, path):\n        f = h5py.File(path, 'w')\n        try:\n            fm_group = f.create_group('Datamat')\n            for field in self.fieldnames():\n                try:\n                    fm_group.create_dataset(field, data = self.__dict__[field])\n                except (TypeError,) as e:\n                    sub_group = fm_group.create_group(field)\n                    for i, d in enumerate(self.__dict__[field]):\n                        index_group = sub_group.create_group(str(i))\n                        print((field, d))\n                        for key, value in list(d.items()):\n                            index_group.create_dataset(key, data=value)\n            for param in self.parameters():\n                fm_group.attrs[param]=self.__dict__[param]\n        finally:\n            f.close()",
    "docstring": "Saves Datamat to path.\n\n        Parameters:\n            path : string\n                Absolute path of the file to save to."
  },
  {
    "code": "def srp(x, promisc=None, iface=None, iface_hint=None, filter=None,\n        nofilter=0, type=ETH_P_ALL, *args, **kargs):\n    if iface is None and iface_hint is not None:\n        iface = conf.route.route(iface_hint)[0]\n    s = conf.L2socket(promisc=promisc, iface=iface,\n                      filter=filter, nofilter=nofilter, type=type)\n    result = sndrcv(s, x, *args, **kargs)\n    s.close()\n    return result",
    "docstring": "Send and receive packets at layer 2"
  },
  {
    "code": "def job_is_running(self, job_id):\n\t\tjob_id = normalize_job_id(job_id)\n\t\tif job_id not in self._jobs:\n\t\t\treturn False\n\t\tjob_desc = self._jobs[job_id]\n\t\tif job_desc['job']:\n\t\t\treturn job_desc['job'].is_alive()\n\t\treturn False",
    "docstring": "Check if a job is currently running. False is returned if the job does\n\t\tnot exist.\n\n\t\t:param job_id: Job identifier to check the status of.\n\t\t:type job_id: :py:class:`uuid.UUID`\n\t\t:rtype: bool"
  },
  {
    "code": "def get_datasets(self):\n        assoc_result, datasets_dicts = self._read_from_hdx('showcase', self.data['id'], fieldname='showcase_id',\n                                                           action=self.actions()['list_datasets'])\n        datasets = list()\n        if assoc_result:\n            for dataset_dict in datasets_dicts:\n                dataset = hdx.data.dataset.Dataset(dataset_dict, configuration=self.configuration)\n                datasets.append(dataset)\n        return datasets",
    "docstring": "Get any datasets in the showcase\n\n        Returns:\n            List[Dataset]: List of datasets"
  },
  {
    "code": "def prep_bootstrap(mpt):\n    bs_ = __salt__['config.gather_bootstrap_script']()\n    fpd_ = os.path.join(mpt, 'tmp', \"{0}\".format(\n        uuid.uuid4()))\n    if not os.path.exists(fpd_):\n        os.makedirs(fpd_)\n    os.chmod(fpd_, 0o700)\n    fp_ = os.path.join(fpd_, os.path.basename(bs_))\n    shutil.copy(bs_, fp_)\n    tmppath = fpd_.replace(mpt, '')\n    return fp_, tmppath",
    "docstring": "Update and get the random script to a random place\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' seed.prep_bootstrap /tmp"
  },
  {
    "code": "def append_faces(vertices_seq, faces_seq):\n    vertices_len = np.array([len(i) for i in vertices_seq])\n    face_offset = np.append(0, np.cumsum(vertices_len)[:-1])\n    new_faces = []\n    for offset, faces in zip(face_offset, faces_seq):\n        if len(faces) == 0:\n            continue\n        new_faces.append(faces + offset)\n    vertices = vstack_empty(vertices_seq)\n    faces = vstack_empty(new_faces)\n    return vertices, faces",
    "docstring": "Given a sequence of zero- indexed faces and vertices\n    combine them into a single array of faces and\n    a single array of vertices.\n\n    Parameters\n    -----------\n    vertices_seq : (n, ) sequence of (m, d) float\n      Multiple arrays of verticesvertex arrays\n    faces_seq : (n, ) sequence of (p, j) int\n      Zero indexed faces for matching vertices\n\n    Returns\n    ----------\n    vertices : (i, d) float\n      Points in space\n    faces : (j, 3) int\n      Reference vertex indices"
  },
  {
    "code": "def show_rbac_policy(self, rbac_policy_id, **_params):\n        return self.get(self.rbac_policy_path % rbac_policy_id,\n                        params=_params)",
    "docstring": "Fetch information of a certain RBAC policy."
  },
  {
    "code": "def add_sections(app, doctree, fromdocname):\n    needs = getattr(app.builder.env, 'needs_all_needs', {})\n    for key, need_info in needs.items():\n        sections = get_sections(need_info)\n        need_info['sections'] = sections\n        need_info['section_name'] = sections[0] if sections else \"\"",
    "docstring": "Add section titles to the needs as additional attributes that can\n    be used in tables and filters"
  },
  {
    "code": "def _collection_default_options(self, name, **kargs):\n        wc = (self.write_concern\n              if self.write_concern.acknowledged else WriteConcern())\n        return self.get_collection(\n            name, codec_options=DEFAULT_CODEC_OPTIONS,\n            read_preference=ReadPreference.PRIMARY,\n            write_concern=wc)",
    "docstring": "Get a Collection instance with the default settings."
  },
  {
    "code": "def get_endpoints(self):\n        def process_result(result):\n            return [line.split(';')[0][2:-1] for line in result.split(',')]\n        return Command('get', ['.well-known', 'core'], parse_json=False,\n                       process_result=process_result)",
    "docstring": "Return all available endpoints on the gateway.\n\n        Returns a Command."
  },
  {
    "code": "def _validate_field(param, fields):\n    if '/' not in param.field and param.field not in fields:\n        raise InvalidQueryParams(**{\n            'detail': 'The filter query param of \"%s\" is not possible. The '\n                      'resource requested does not have a \"%s\" field. Please '\n                      'modify your request & retry.' % (param, param.field),\n            'links': LINK,\n            'parameter': PARAM,\n        })",
    "docstring": "Ensure the field exists on the model"
  },
  {
    "code": "def copy_pkg(self, filename, id_=-1):\n        for repo in self._children:\n            repo.copy_pkg(filename, id_)",
    "docstring": "Copy a pkg, dmg, or zip to all repositories.\n\n        Args:\n            filename: String path to the local file to copy.\n            id_: Integer ID you wish to associate package with for a JDS\n                or CDP only. Default is -1, which is used for creating\n                a new package object in the database."
  },
  {
    "code": "def load_data_file(fname, directory=None, force_download=False):\n    _url_root = 'http://github.com/vispy/demo-data/raw/master/'\n    url = _url_root + fname\n    if directory is None:\n        directory = config['data_path']\n        if directory is None:\n            raise ValueError('config[\"data_path\"] is not defined, '\n                             'so directory must be supplied')\n    fname = op.join(directory, op.normcase(fname))\n    if op.isfile(fname):\n        if not force_download:\n            return fname\n        if isinstance(force_download, string_types):\n            ntime = time.strptime(force_download, '%Y-%m-%d')\n            ftime = time.gmtime(op.getctime(fname))\n            if ftime >= ntime:\n                return fname\n            else:\n                print('File older than %s, updating...' % force_download)\n    if not op.isdir(op.dirname(fname)):\n        os.makedirs(op.abspath(op.dirname(fname)))\n    _fetch_file(url, fname)\n    return fname",
    "docstring": "Get a standard vispy demo data file\n\n    Parameters\n    ----------\n    fname : str\n        The filename on the remote ``demo-data`` repository to download,\n        e.g. ``'molecular_viewer/micelle.npy'``. These correspond to paths\n        on ``https://github.com/vispy/demo-data/``.\n    directory : str | None\n        Directory to use to save the file. By default, the vispy\n        configuration directory is used.\n    force_download : bool | str\n        If True, the file will be downloaded even if a local copy exists\n        (and this copy will be overwritten). Can also be a YYYY-MM-DD date\n        to ensure a file is up-to-date (modified date of a file on disk,\n        if present, is checked).\n\n    Returns\n    -------\n    fname : str\n        The path to the file on the local system."
  },
  {
    "code": "def brier_score(self):\n        reliability, resolution, uncertainty = self.brier_score_components()\n        return reliability - resolution + uncertainty",
    "docstring": "Calculate the Brier Score"
  },
  {
    "code": "def _label_from_list(self, labels:Iterator, label_cls:Callable=None, from_item_lists:bool=False, **kwargs)->'LabelList':\n        \"Label `self.items` with `labels`.\"\n        if not from_item_lists:\n            raise Exception(\"Your data isn't split, if you don't want a validation set, please use `split_none`.\")\n        labels = array(labels, dtype=object)\n        label_cls = self.get_label_cls(labels, label_cls=label_cls, **kwargs)\n        y = label_cls(labels, path=self.path, **kwargs)\n        res = self._label_list(x=self, y=y)\n        return res",
    "docstring": "Label `self.items` with `labels`."
  },
  {
    "code": "def manage_initial_service_status_brok(self, b):\n        host_name = b.data['host_name']\n        service_description = b.data['service_description']\n        service_id = host_name+\"/\"+service_description\n        logger.debug(\"got initial service status: %s\", service_id)\n        if host_name not in self.hosts_cache:\n            logger.error(\"initial service status, host is unknown: %s.\", service_id)\n            return\n        self.services_cache[service_id] = {\n        }\n        if 'customs' in b.data:\n            self.services_cache[service_id]['_GRAPHITE_POST'] = \\\n                sanitize_name(b.data['customs'].get('_GRAPHITE_POST', None))\n        logger.debug(\"initial service status received: %s\", service_id)",
    "docstring": "Prepare the known services cache"
  },
  {
    "code": "def find_task(self, name):\n        try:\n            return self.tasks[name]\n        except KeyError:\n            pass\n        similarities = []\n        for task_name, task in self.tasks.items():\n            ratio = SequenceMatcher(None, name, task_name).ratio()\n            if ratio >= 0.75:\n                similarities.append(task)\n        if len(similarities) == 1:\n            return similarities[0]\n        else:\n            raise NoSuchTaskError(similarities)",
    "docstring": "Find a task by name.\n\n        If a task with the exact name cannot be found, then tasks with similar\n        names are searched for.\n\n        Returns\n        -------\n        Task\n            If the task is found.\n\n        Raises\n        ------\n        NoSuchTaskError\n            If the task cannot be found."
  },
  {
    "code": "def _construct_control_flow_slice(self, simruns):\n        if self._cfg is None:\n            l.error('Please build CFG first.')\n        cfg = self._cfg.graph\n        for simrun in simruns:\n            if simrun not in cfg:\n                l.error('SimRun instance %s is not in the CFG.', simrun)\n        stack = [ ]\n        for simrun in simruns:\n            stack.append(simrun)\n        self.runs_in_slice = networkx.DiGraph()\n        self.cfg_nodes_in_slice = networkx.DiGraph()\n        self.chosen_statements = { }\n        while stack:\n            block = stack.pop()\n            if block.addr not in self.chosen_statements:\n                self.chosen_statements[block.addr] = True\n                predecessors = cfg.predecessors(block)\n                for pred in predecessors:\n                    stack.append(pred)\n                    self.cfg_nodes_in_slice.add_edge(pred, block)\n                    self.runs_in_slice.add_edge(pred.addr, block.addr)",
    "docstring": "Build a slice of the program without considering the effect of data dependencies.\n        This is an incorrect hack, but it should work fine with small programs.\n\n        :param simruns: A list of SimRun targets. You probably wanna get it from the CFG somehow. It must exist in the\n                        CFG."
  },
  {
    "code": "def put(self, name, handler, builder=None, request=None, get=True):\n        chan = self._channel(name)\n        return _p4p.ClientOperation(chan, handler=unwrapHandler(handler, self._nt),\n                                    builder=defaultBuilder(builder, self._nt),\n                                    pvRequest=wrapRequest(request), get=get, put=True)",
    "docstring": "Write a new value to a PV.\n\n        :param name: A single name string or list of name strings\n        :param callable handler: Completion notification.  Called with None (success), RemoteError, or Cancelled\n        :param callable builder: Called when the PV Put type is known.  A builder is responsible\n                                 for filling in the Value to be sent.  builder(value)\n        :param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default.\n        :param bool get: Whether to do a Get before the Put.  If True then the value passed to the builder callable\n                         will be initialized with recent PV values.  eg. use this with NTEnum to find the enumeration list.\n\n        :returns: A object with a method cancel() which may be used to abort the operation."
  },
  {
    "code": "def get_version(self):\n        return Version.objects.get(\n            content_type=self.content_type,\n            object_id=self.object_id,\n            version_number=self.publish_version,\n        )",
    "docstring": "Get the version object for the related object."
  },
  {
    "code": "def _find_append_zero_crossings(x, y):\n    r\n    crossings = find_intersections(x[1:], y[1:], np.zeros_like(y[1:]) * y.units)\n    x = concatenate((x, crossings[0]))\n    y = concatenate((y, crossings[1]))\n    sort_idx = np.argsort(x)\n    x = x[sort_idx]\n    y = y[sort_idx]\n    keep_idx = np.ediff1d(x, to_end=[1]) > 0\n    x = x[keep_idx]\n    y = y[keep_idx]\n    return x, y",
    "docstring": "r\"\"\"\n    Find and interpolate zero crossings.\n\n    Estimate the zero crossings of an x,y series and add estimated crossings to series,\n    returning a sorted array with no duplicate values.\n\n    Parameters\n    ----------\n    x : `pint.Quantity`\n        x values of data\n    y : `pint.Quantity`\n        y values of data\n\n    Returns\n    -------\n    x : `pint.Quantity`\n        x values of data\n    y : `pint.Quantity`\n        y values of data"
  },
  {
    "code": "def create(self, subscription_id, name, parameters, type='analysis', service='facebook'):\n        params = {\n            'subscription_id': subscription_id,\n            'name': name,\n            'parameters': parameters,\n            'type': type\n        }\n        return self.request.post(service + '/task/', params)",
    "docstring": "Create a PYLON task\n\n            :param subscription_id: The ID of the recording to create the task for\n            :type subscription_id: str\n            :param name: The name of the new task\n            :type name: str\n            :param parameters: The parameters for this task\n            :type parameters: dict\n            :param type: The type of analysis to create, currently only 'analysis' is accepted\n            :type type: str\n            :param service: The PYLON service (facebook)\n            :type service: str\n            :return: dict of REST API output with headers attached\n            :rtype: :class:`~datasift.request.DictResponse`\n            :raises: :class:`~datasift.exceptions.DataSiftApiException`,\n                :class:`requests.exceptions.HTTPError`"
  },
  {
    "code": "def _generate_reads(seq, name):\n    reads = dict()\n    if len(seq) < 130 and len(seq) > 70:\n        reads.update(_mature(seq[:40], 0, name))\n        reads.update(_mature(seq[-40:], len(seq) - 40, name))\n        reads.update(_noise(seq, name))\n        reads.update(_noise(seq, name, 25))\n    return reads",
    "docstring": "Main function that create reads from precursors"
  },
  {
    "code": "def _req_fix(self, line):\n        deps = []\n        for dep in line[18:].strip().split(\",\"):\n            dep = dep.split(\"|\")\n            if self.repo == \"slacky\":\n                if len(dep) > 1:\n                    for d in dep:\n                        deps.append(d.split()[0])\n                dep = \"\".join(dep)\n                deps.append(dep.split()[0])\n            else:\n                if len(dep) > 1:\n                    for d in dep:\n                        deps.append(d)\n                deps.append(dep[0])\n        return deps",
    "docstring": "Fix slacky and salix requirements because many dependencies splitting\n        with \",\" and others with \"|\""
  },
  {
    "code": "def method_name(func):\n    @wraps(func)\n    def _method_name(*args, **kwargs):\n        name = to_pascal_case(func.__name__)\n        return func(name=name, *args, **kwargs)\n    return _method_name",
    "docstring": "Method wrapper that adds the name of the method being called to its arguments list in Pascal case"
  },
  {
    "code": "def scan_full(self, regex, return_string=True, advance_pointer=True):\n        regex = get_regex(regex)\n        self.match = regex.match(self.string, self.pos)\n        if not self.match:\n            return\n        if advance_pointer:\n            self.pos = self.match.end()\n        if return_string:\n            return self.match.group(0)\n        return len(self.match.group(0))",
    "docstring": "Match from the current position.\n\n        If `return_string` is false and a match is found, returns the number of\n        characters matched.\n\n            >>> s = Scanner(\"test string\")\n            >>> s.scan_full(r' ')\n            >>> s.scan_full(r'test ')\n            'test '\n            >>> s.pos\n            5\n            >>> s.scan_full(r'stri', advance_pointer=False)\n            'stri'\n            >>> s.pos\n            5\n            >>> s.scan_full(r'stri', return_string=False, advance_pointer=False)\n            4\n            >>> s.pos\n            5"
  },
  {
    "code": "def get_catalogue_header_value(cls, catalog, key):\n        header_value = None\n        if '' in catalog:\n            for line in catalog[''].split('\\n'):\n                if line.startswith('%s:' % key):\n                    header_value = line.split(':', 1)[1].strip()\n        return header_value",
    "docstring": "Get `.po` header value."
  },
  {
    "code": "def next_frame_ae():\n  hparams = next_frame_basic_deterministic()\n  hparams.bottom[\"inputs\"] = modalities.video_bitwise_bottom\n  hparams.top[\"inputs\"] = modalities.video_top\n  hparams.hidden_size = 256\n  hparams.batch_size = 8\n  hparams.num_hidden_layers = 4\n  hparams.num_compress_steps = 4\n  hparams.dropout = 0.4\n  return hparams",
    "docstring": "Conv autoencoder."
  },
  {
    "code": "def parse_variables_mapping(variables_mapping, ignore=False):\n    run_times = 0\n    parsed_variables_mapping = {}\n    while len(parsed_variables_mapping) != len(variables_mapping):\n        for var_name in variables_mapping:\n            run_times += 1\n            if run_times > len(variables_mapping) * 4:\n                not_found_variables = {\n                    key: variables_mapping[key]\n                    for key in variables_mapping\n                    if key not in parsed_variables_mapping\n                }\n                raise exceptions.VariableNotFound(not_found_variables)\n            if var_name in parsed_variables_mapping:\n                continue\n            value = variables_mapping[var_name]\n            variables = extract_variables(value)\n            if var_name in variables:\n                if ignore:\n                    parsed_variables_mapping[var_name] = value\n                    continue\n                raise exceptions.VariableNotFound(var_name)\n            if variables:\n                if any([_var_name not in parsed_variables_mapping for _var_name in variables]):\n                    continue\n            parsed_value = parse_lazy_data(value, parsed_variables_mapping)\n            parsed_variables_mapping[var_name] = parsed_value\n    return parsed_variables_mapping",
    "docstring": "eval each prepared variable and function in variables_mapping.\n\n    Args:\n        variables_mapping (dict):\n            {\n                \"varA\": LazyString(123$varB),\n                \"varB\": LazyString(456$varC),\n                \"varC\": LazyString(${sum_two($a, $b)}),\n                \"a\": 1,\n                \"b\": 2,\n                \"c\": {\"key\": LazyString($b)},\n                \"d\": [LazyString($a), 3]\n            }\n        ignore (bool): If set True, VariableNotFound will be ignored.\n            This is used when initializing tests.\n\n    Returns:\n        dict: parsed variables_mapping should not contain any variable or function.\n            {\n                \"varA\": \"1234563\",\n                \"varB\": \"4563\",\n                \"varC\": \"3\",\n                \"a\": 1,\n                \"b\": 2,\n                \"c\": {\"key\": 2},\n                \"d\": [1, 3]\n            }"
  },
  {
    "code": "def _summarize_call(parts):\n    svtype = [x.split(\"=\")[1] for x in parts[7].split(\";\") if x.startswith(\"SVTYPE=\")]\n    svtype = svtype[0] if svtype else \"\"\n    start, end = _get_start_end(parts)\n    return {\"svtype\": svtype, \"size\": int(end) - int(start)}",
    "docstring": "Provide summary metrics on size and svtype for a SV call."
  },
  {
    "code": "def delete_group_policy(self, group_name, policy_name):\n        params = {'GroupName' : group_name,\n                  'PolicyName' : policy_name}\n        return self.get_response('DeleteGroupPolicy', params, verb='POST')",
    "docstring": "Deletes the specified policy document for the specified group.\n\n        :type group_name: string\n        :param group_name: The name of the group the policy is associated with.\n\n        :type policy_name: string\n        :param policy_name: The policy document to delete."
  },
  {
    "code": "def delete_item2(self, tablename, key, expr_values=None, alias=None,\n                     condition=None, returns=NONE, return_capacity=None,\n                     return_item_collection_metrics=NONE, **kwargs):\n        keywords = {\n            'TableName': tablename,\n            'Key': self.dynamizer.encode_keys(key),\n            'ReturnValues': returns,\n            'ReturnConsumedCapacity': self._default_capacity(return_capacity),\n            'ReturnItemCollectionMetrics': return_item_collection_metrics,\n        }\n        values = build_expression_values(self.dynamizer, expr_values, kwargs)\n        if values:\n            keywords['ExpressionAttributeValues'] = values\n        if alias:\n            keywords['ExpressionAttributeNames'] = alias\n        if condition:\n            keywords['ConditionExpression'] = condition\n        result = self.call('delete_item', **keywords)\n        if result:\n            return Result(self.dynamizer, result, 'Attributes')",
    "docstring": "Delete an item from a table\n\n        For many parameters you will want to reference the DynamoDB API:\n        http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DeleteItem.html\n\n        Parameters\n        ----------\n        tablename : str\n            Name of the table to update\n        key : dict\n            Primary key dict specifying the hash key and, if applicable, the\n            range key of the item.\n        expr_values : dict, optional\n            See docs for ExpressionAttributeValues. See also: kwargs\n        alias : dict, optional\n            See docs for ExpressionAttributeNames\n        condition : str, optional\n            See docs for ConditionExpression\n        returns : {NONE, ALL_OLD, UPDATED_OLD, ALL_NEW, UPDATED_NEW}, optional\n            Return either the old or new values, either all attributes or just\n            the ones that changed. (default NONE)\n        return_capacity : {NONE, INDEXES, TOTAL}, optional\n            INDEXES will return the consumed capacity for indexes, TOTAL will\n            return the consumed capacity for the table and the indexes.\n            (default NONE)\n        return_item_collection_metrics : (NONE, SIZE), optional\n            SIZE will return statistics about item collections that were\n            modified.\n        **kwargs : dict, optional\n            If expr_values is not provided, the kwargs dict will be used as the\n            ExpressionAttributeValues (a ':' will be automatically prepended to\n            all keys)."
  },
  {
    "code": "def list(self, path=None, with_metadata=False, include_partitions=False):\n        import json\n        sub_path = self.prefix + '/' + path.strip('/') if path else self.prefix\n        l = {}\n        for e in self.bucket.list(sub_path):\n            path = e.name.replace(self.prefix, '', 1).strip('/')\n            if path.startswith('_') or path.startswith('meta'):\n                continue\n            if not include_partitions and path.count('/') > 1:\n                continue\n            if with_metadata:\n                d = self.metadata(path)\n                if d and 'identity' in d:\n                    d['identity'] = json.loads(d['identity'])\n            else:\n                d = {}\n            d['caches'] = [self.repo_id]\n            if path:\n                l[path] = d\n        return l",
    "docstring": "Get a list of all of bundle files in the cache. Does not return partition files"
  },
  {
    "code": "def parse_device(lines):\n    name, status_line, device = parse_device_header(lines.pop(0))\n    if not status_line:\n        status_line = lines.pop(0)\n    status = parse_device_status(status_line, device[\"personality\"])\n    bitmap = None\n    resync = None\n    for line in lines:\n        if line.startswith(\"      bitmap:\"):\n            bitmap = parse_device_bitmap(line)\n        elif line.startswith(\"      [\"):\n            resync = parse_device_resync_progress(line)\n        elif line.startswith(\"      \\tresync=\"):\n            resync = parse_device_resync_standby(line)\n        else:\n            raise NotImplementedError(\"unknown device line: {0}\".format(line))\n    device.update({\n        \"status\": status,\n        \"bitmap\": bitmap,\n        \"resync\": resync,\n    })\n    return (name, device)",
    "docstring": "Parse all the lines of a device block.\n\n    A device block is composed of a header line with the name of the device and\n    at least one extra line describing the device and its status.  The extra\n    lines have a varying format depending on the status and personality of the\n    device (e.g. RAID1 vs RAID5, healthy vs recovery/resync)."
  },
  {
    "code": "def GetOutputPluginStates(output_plugins, source=None, token=None):\n  output_plugins_states = []\n  for plugin_descriptor in output_plugins:\n    plugin_class = plugin_descriptor.GetPluginClass()\n    try:\n      _, plugin_state = plugin_class.CreatePluginAndDefaultState(\n          source_urn=source, args=plugin_descriptor.plugin_args, token=token)\n    except Exception as e:\n      raise ValueError(\"Plugin %s failed to initialize (%s)\" %\n                       (plugin_class, e))\n    plugin_state[\"logs\"] = []\n    plugin_state[\"errors\"] = []\n    output_plugins_states.append(\n        rdf_flow_runner.OutputPluginState(\n            plugin_state=plugin_state, plugin_descriptor=plugin_descriptor))\n  return output_plugins_states",
    "docstring": "Initializes state for a list of output plugins."
  },
  {
    "code": "def fire(self, event):\n        self.browser.fire(self.element, event)\n        return self",
    "docstring": "Fires a specified DOM event on the current node.\n\n        :param event: the name of the event to fire (e.g., 'click').\n\n        Returns the :class:`zombie.dom.DOMNode` to allow function chaining."
  },
  {
    "code": "async def _maybe_release_last_part(self) -> None:\n        if self._last_part is not None:\n            if not self._last_part.at_eof():\n                await self._last_part.release()\n            self._unread.extend(self._last_part._unread)\n            self._last_part = None",
    "docstring": "Ensures that the last read body part is read completely."
  },
  {
    "code": "def _parse_fields(self, query):\n        field_args = {\n            k: v\n            for k, v in query.items() if k.startswith('fields[')\n        }\n        fields = {}\n        for k, v in field_args.items():\n            fields[k[7:-1]] = v.split(',')\n        return fields",
    "docstring": "Parse the querystring args for fields.\n\n        :param query: Dict of query args"
  },
  {
    "code": "def add_slices(self, dashboard_id):\n        data = json.loads(request.form.get('data'))\n        session = db.session()\n        Slice = models.Slice\n        dash = (\n            session.query(models.Dashboard).filter_by(id=dashboard_id).first())\n        check_ownership(dash, raise_if_false=True)\n        new_slices = session.query(Slice).filter(\n            Slice.id.in_(data['slice_ids']))\n        dash.slices += new_slices\n        session.merge(dash)\n        session.commit()\n        session.close()\n        return 'SLICES ADDED'",
    "docstring": "Add and save slices to a dashboard"
  },
  {
    "code": "def decode_body(cls, header, f):\n        assert header.packet_type == MqttControlPacketType.pubrel\n        decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))\n        packet_id, = decoder.unpack(mqtt_io.FIELD_U16)\n        if header.remaining_len != decoder.num_bytes_consumed:\n            raise DecodeError('Extra bytes at end of packet.')\n        return decoder.num_bytes_consumed, MqttPubrel(packet_id)",
    "docstring": "Generates a `MqttPubrel` packet given a\n        `MqttFixedHeader`.  This method asserts that header.packet_type\n        is `pubrel`.\n\n        Parameters\n        ----------\n        header: MqttFixedHeader\n        f: file\n            Object with a read method.\n\n        Raises\n        ------\n        DecodeError\n            When there are extra bytes at the end of the packet.\n\n        Returns\n        -------\n        int\n            Number of bytes consumed from ``f``.\n        MqttPubrel\n            Object extracted from ``f``."
  },
  {
    "code": "def slugify_argument(func):\n    @six.wraps(func)\n    def wrapped(*args, **kwargs):\n        if \"slugify\" in kwargs and kwargs['slugify']:\n            return _slugify(func(*args, **kwargs))\n        else:\n            return func(*args, **kwargs)\n    return wrapped",
    "docstring": "Wraps a function that returns a string, adding the 'slugify' argument.\n\n    >>> slugified_fn = slugify_argument(lambda *args, **kwargs: \"YOU ARE A NICE LADY\")\n    >>> slugified_fn()\n    'YOU ARE A NICE LADY'\n    >>> slugified_fn(slugify=True)\n    'you-are-a-nice-lady'"
  },
  {
    "code": "def details(self):\n        params = {'wsfunction': 'core_course_get_categories',\n                  'criteria[0][key]': 'id',\n                  'criteria[0][value]': self.category_id}\n        params.update(self.request_params)\n        return requests.post(self.api_url, params=params, verify=False)",
    "docstring": "Returns details for given category\n\n        :returns: category response object\n\n        Example Usage::\n\n        >>> import muddle\n        >>> muddle.category(10).details()"
  },
  {
    "code": "def next(self):\n        while True:\n            if not self._resp:\n                self._start()\n            if self._stop:\n                raise StopIteration\n            skip, data = self._process_data(next_(self._lines))\n            if not skip:\n                break\n        return data",
    "docstring": "Handles the iteration by pulling the next line out of the stream,\n        attempting to convert the response to JSON if necessary.\n\n        :returns: Data representing what was seen in the feed"
  },
  {
    "code": "def add_input(self, name, value=None):\n        self._input_vars.append(name)\n        self.__setattr__(name, value)",
    "docstring": "Create a new input variable called ``name`` for this process\n        and initialize it with the given ``value``.\n\n        Quantity is accessible in two ways:\n\n            * as a process attribute, i.e. ``proc.name``\n            * as a member of the input dictionary,\n              i.e. ``proc.input['name']``\n\n        Use attribute method to set values, e.g.\n        ```proc.name = value ```\n\n        :param str name:        name of diagnostic quantity to be initialized\n        :param array value:     initial value for quantity [default: None]"
  },
  {
    "code": "def _load_wurlitzer(self):\n        if not os.name == 'nt':\n            from IPython.core.getipython import get_ipython\n            try:\n                get_ipython().run_line_magic('reload_ext', 'wurlitzer')\n            except Exception:\n                pass",
    "docstring": "Load wurlitzer extension."
  },
  {
    "code": "def create_model(self,\n                     base_model_id,\n                     forced_glossary=None,\n                     parallel_corpus=None,\n                     name=None,\n                     **kwargs):\n        if base_model_id is None:\n            raise ValueError('base_model_id must be provided')\n        headers = {}\n        if 'headers' in kwargs:\n            headers.update(kwargs.get('headers'))\n        sdk_headers = get_sdk_headers('language_translator', 'V3',\n                                      'create_model')\n        headers.update(sdk_headers)\n        params = {\n            'version': self.version,\n            'base_model_id': base_model_id,\n            'name': name\n        }\n        form_data = {}\n        if forced_glossary:\n            form_data['forced_glossary'] = (None, forced_glossary,\n                                            'application/octet-stream')\n        if parallel_corpus:\n            form_data['parallel_corpus'] = (None, parallel_corpus,\n                                            'application/octet-stream')\n        url = '/v3/models'\n        response = self.request(\n            method='POST',\n            url=url,\n            headers=headers,\n            params=params,\n            files=form_data,\n            accept_json=True)\n        return response",
    "docstring": "Create model.\n\n        Uploads Translation Memory eXchange (TMX) files to customize a translation model.\n        You can either customize a model with a forced glossary or with a corpus that\n        contains parallel sentences. To create a model that is customized with a parallel\n        corpus <b>and</b> a forced glossary, proceed in two steps: customize with a\n        parallel corpus first and then customize the resulting model with a glossary.\n        Depending on the type of customization and the size of the uploaded corpora,\n        training can range from minutes for a glossary to several hours for a large\n        parallel corpus. You can upload a single forced glossary file and this file must\n        be less than <b>10 MB</b>. You can upload multiple parallel corpora tmx files. The\n        cumulative file size of all uploaded files is limited to <b>250 MB</b>. To\n        successfully train with a parallel corpus you must have at least <b>5,000 parallel\n        sentences</b> in your corpus.\n        You can have a <b>maxium of 10 custom models per language pair</b>.\n\n        :param str base_model_id: The model ID of the model to use as the base for\n        customization. To see available models, use the `List models` method. Usually all\n        IBM provided models are customizable. In addition, all your models that have been\n        created via parallel corpus customization, can be further customized with a forced\n        glossary.\n        :param file forced_glossary: A TMX file with your customizations. The\n        customizations in the file completely overwrite the domain translaton data,\n        including high frequency or high confidence phrase translations. You can upload\n        only one glossary with a file size less than 10 MB per call. A forced glossary\n        should contain single words or short phrases.\n        :param file parallel_corpus: A TMX file with parallel sentences for source and\n        target language. You can upload multiple parallel_corpus files in one request. All\n        uploaded parallel_corpus files combined, your parallel corpus must contain at\n        least 5,000 parallel sentences to train successfully.\n        :param str name: An optional model name that you can use to identify the model.\n        Valid characters are letters, numbers, dashes, underscores, spaces and\n        apostrophes. The maximum length is 32 characters.\n        :param dict headers: A `dict` containing the request headers\n        :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n        :rtype: DetailedResponse"
  },
  {
    "code": "def annotation_id(self, value):\n        if value in [None, ''] or str(value).strip() == '':\n            raise AttributeError(\"Invalid ID value supplied\")\n        self._id = value",
    "docstring": "Set ID for Annotation"
  },
  {
    "code": "def render_booleanfield(field, attrs):\n\tattrs.setdefault(\"_no_label\", True)\n\tattrs.setdefault(\"_inline\", True)\n\tfield.field.widget.attrs[\"style\"] = \"display:hidden\"\n\treturn wrappers.CHECKBOX_WRAPPER % {\n\t\t\"style\": pad(attrs.get(\"_style\", \"\")),\n\t\t\"field\": field,\n\t\t\"label\": format_html(\n\t\t\twrappers.LABEL_TEMPLATE, field.html_name, mark_safe(field.label)\n\t\t)\n\t}",
    "docstring": "Render BooleanField with label next to instead of above."
  },
  {
    "code": "def dump(self, script, file=None):\n        \"Write a compressed representation of script to the Pickler's file object.\"\n        if file is None:\n            file = self._file\n        self._dump(script, file, self._protocol, self._version)",
    "docstring": "Write a compressed representation of script to the Pickler's file object."
  },
  {
    "code": "def set_dimensional_calibrations(self, dimensional_calibrations: typing.List[CalibrationModule.Calibration]) -> None:\n        self.__data_item.set_dimensional_calibrations(dimensional_calibrations)",
    "docstring": "Set the dimensional calibrations.\n\n        :param dimensional_calibrations: A list of calibrations, must match the dimensions of the data.\n\n        .. versionadded:: 1.0\n\n        Scriptable: Yes"
  },
  {
    "code": "def get_managed_zone(self, zone):\n        if zone.endswith('.in-addr.arpa.'):\n            return self.reverse_prefix + '-'.join(zone.split('.')[-5:-3])\n        return self.forward_prefix + '-'.join(zone.split('.')[:-1])",
    "docstring": "Get the GDNS managed zone name for a DNS zone.\n\n        Google uses custom string names with specific `requirements\n        <https://cloud.google.com/dns/api/v1/managedZones#resource>`_\n        for storing records. The scheme implemented here chooses a\n        managed zone name which removes the trailing dot and replaces\n        other dots with dashes, and in the case of reverse records,\n        uses only the two most significant octets, prepended with\n        'reverse'. At least two octets are required for reverse DNS zones.\n\n        Example:\n           get_managed_zone('example.com.') = 'example-com'\n           get_managed_zone('20.10.in-addr.arpa.) = 'reverse-20-10'\n           get_managed_zone('30.20.10.in-addr.arpa.) = 'reverse-20-10'\n           get_managed_zone('40.30.20.10.in-addr.arpa.) = 'reverse-20-10'\n\n        Args:\n            zone (str): DNS zone.\n        Returns:\n            str of managed zone name."
  },
  {
    "code": "def _populate_alternate_kwargs(kwargs):\n    resource_namespace = kwargs['namespace']\n    resource_type = kwargs.get('child_type_{}'.format(kwargs['last_child_num'])) or kwargs['type']\n    resource_name = kwargs.get('child_name_{}'.format(kwargs['last_child_num'])) or kwargs['name']\n    _get_parents_from_parts(kwargs)\n    kwargs['resource_namespace'] = resource_namespace\n    kwargs['resource_type'] = resource_type\n    kwargs['resource_name'] = resource_name\n    return kwargs",
    "docstring": "Translates the parsed arguments into a format used by generic ARM commands\n    such as the resource and lock commands."
  },
  {
    "code": "def listen_loop(self):\n        while self.listening:\n            try:\n                data, address = self.sock.recvfrom(self.bufsize)\n                self.receive_datagram(data, address)\n                if self.stats_enabled:\n                    self.stats['bytes_recieved'] += len(data)\n            except socket.error as error:\n                if error.errno == errno.WSAECONNRESET:\n                    logger.info(\"connection reset\")\n                else:\n                    raise\n        logger.info(\"Shutting down the listener...\")",
    "docstring": "Starts the listen loop and executes the receieve_datagram method\n        whenever a packet is receieved.\n\n        Args:\n          None\n\n        Returns:\n          None"
  },
  {
    "code": "def clean_ns(tag):\n    if '}' in tag:\n        split = tag.split('}')\n        return split[0].strip('{'), split[-1]\n    return '', tag",
    "docstring": "Return a tag and its namespace separately."
  },
  {
    "code": "def listTables(self,walkTrace=tuple(),case=None,element=None):\n        if case == 'sectionmain': print(walkTrace,self.title)\n        if case == 'table':\n            caption,tab = element\n            try:\n                print(walkTrace,tab._leopardref,caption)\n            except AttributeError:\n                tab._leopardref = next(self._reportSection._tabnr)\n                print(walkTrace,tab._leopardref,caption)",
    "docstring": "List section tables."
  },
  {
    "code": "def _get_part_reader(self, headers: 'CIMultiDictProxy[str]') -> Any:\n        ctype = headers.get(CONTENT_TYPE, '')\n        mimetype = parse_mimetype(ctype)\n        if mimetype.type == 'multipart':\n            if self.multipart_reader_cls is None:\n                return type(self)(headers, self._content)\n            return self.multipart_reader_cls(\n                headers, self._content, _newline=self._newline\n            )\n        else:\n            return self.part_reader_cls(\n                self._boundary, headers, self._content, _newline=self._newline\n            )",
    "docstring": "Dispatches the response by the `Content-Type` header, returning\n        suitable reader instance.\n\n        :param dict headers: Response headers"
  },
  {
    "code": "def _update_response_body(self, resource):\n        rpr = self._get_response_representer(resource)\n        self.request.response.content_type = \\\n                                rpr.content_type.mime_type_string\n        rpr_body = rpr.to_bytes(resource)\n        self.request.response.body = rpr_body",
    "docstring": "Creates a representer and updates the response body with the byte\n        representation created for the given resource."
  },
  {
    "code": "def _find_realname(self, post_input):\n        if \"lis_person_name_full\" in post_input:\n            return post_input[\"lis_person_name_full\"]\n        if \"lis_person_name_given\" in post_input and \"lis_person_name_family\" in post_input:\n            return post_input[\"lis_person_name_given\"] + post_input[\"lis_person_name_family\"]\n        if \"lis_person_contact_email_primary\" in post_input:\n            return post_input[\"lis_person_contact_email_primary\"]\n        if \"lis_person_name_family\" in post_input:\n            return post_input[\"lis_person_name_family\"]\n        if \"lis_person_name_given\" in post_input:\n            return post_input[\"lis_person_name_given\"]\n        return post_input[\"user_id\"]",
    "docstring": "Returns the most appropriate name to identify the user"
  },
  {
    "code": "def serializeTransform(transformObj):\n    return ' '.join([command + '(' + ' '.join([scourUnitlessLength(number) for number in numbers]) + ')'\n                     for command, numbers in transformObj])",
    "docstring": "Reserializes the transform data with some cleanups."
  },
  {
    "code": "def repository_url_part(distro):\n    if distro.normalized_release.int_major >= 6:\n        if distro.normalized_name == 'redhat':\n            return 'rhel' + distro.normalized_release.major\n        if distro.normalized_name in ['centos', 'scientific', 'oracle', 'virtuozzo']:\n            return 'el' + distro.normalized_release.major\n    return 'el6'",
    "docstring": "Historically everything CentOS, RHEL, and Scientific has been mapped to\n    `el6` urls, but as we are adding repositories for `rhel`, the URLs should\n    map correctly to, say, `rhel6` or `rhel7`.\n\n    This function looks into the `distro` object and determines the right url\n    part for the given distro, falling back to `el6` when all else fails.\n\n    Specifically to work around the issue of CentOS vs RHEL::\n\n        >>> import platform\n        >>> platform.linux_distribution()\n        ('Red Hat Enterprise Linux Server', '7.0', 'Maipo')"
  },
  {
    "code": "def getCatalogDefinitions():\n    final = {}\n    analysis_request = bika_catalog_analysisrequest_listing_definition\n    analysis = bika_catalog_analysis_listing_definition\n    autoimportlogs = bika_catalog_autoimportlogs_listing_definition\n    worksheet = bika_catalog_worksheet_listing_definition\n    report = bika_catalog_report_definition\n    final.update(analysis_request)\n    final.update(analysis)\n    final.update(autoimportlogs)\n    final.update(worksheet)\n    final.update(report)\n    return final",
    "docstring": "Returns a dictionary with catalogs definitions."
  },
  {
    "code": "def joliet_vd_factory(joliet, sys_ident, vol_ident, set_size, seqnum,\n                      log_block_size, vol_set_ident, pub_ident_str,\n                      preparer_ident_str, app_ident_str, copyright_file,\n                      abstract_file, bibli_file, vol_expire_date, app_use, xa):\n    if joliet == 1:\n        escape_sequence = b'%/@'\n    elif joliet == 2:\n        escape_sequence = b'%/C'\n    elif joliet == 3:\n        escape_sequence = b'%/E'\n    else:\n        raise pycdlibexception.PyCdlibInvalidInput('Invalid Joliet level; must be 1, 2, or 3')\n    svd = PrimaryOrSupplementaryVD(VOLUME_DESCRIPTOR_TYPE_SUPPLEMENTARY)\n    svd.new(0, sys_ident, vol_ident, set_size, seqnum, log_block_size,\n            vol_set_ident, pub_ident_str, preparer_ident_str, app_ident_str,\n            copyright_file, abstract_file,\n            bibli_file, vol_expire_date, app_use, xa, 1, escape_sequence)\n    return svd",
    "docstring": "An internal function to create an Joliet Volume Descriptor.\n\n    Parameters:\n     joliet - The joliet version to use, one of 1, 2, or 3.\n     sys_ident - The system identification string to use on the new ISO.\n     vol_ident - The volume identification string to use on the new ISO.\n     set_size - The size of the set of ISOs this ISO is a part of.\n     seqnum - The sequence number of the set of this ISO.\n     log_block_size - The logical block size to use for the ISO.  While ISO9660\n                      technically supports sizes other than 2048 (the default),\n                      this almost certainly doesn't work.\n     vol_set_ident - The volume set identification string to use on the new ISO.\n     pub_ident_str - The publisher identification string to use on the new ISO.\n     preparer_ident_str - The preparer identification string to use on the new ISO.\n     app_ident_str - The application identification string to use on the new ISO.\n     copyright_file - The name of a file at the root of the ISO to use as the\n                      copyright file.\n     abstract_file - The name of a file at the root of the ISO to use as the\n                     abstract file.\n     bibli_file - The name of a file at the root of the ISO to use as the\n                  bibliographic file.\n     vol_expire_date - The date that this ISO will expire at.\n     app_use - Arbitrary data that the application can stuff into the primary\n               volume descriptor of this ISO.\n     xa - Whether to add the ISO9660 Extended Attribute extensions to this\n          ISO.  The default is False.\n    Returns:\n     The newly created Joliet Volume Descriptor."
  },
  {
    "code": "def zcross(seq, hysteresis=0, first_sign=0):\n  neg_hyst = -hysteresis\n  seq_iter = iter(seq)\n  if first_sign == 0:\n    last_sign = 0\n    for el in seq_iter:\n      yield 0\n      if (el > hysteresis) or (el < neg_hyst):\n        last_sign = -1 if el < 0 else 1\n        break\n  else:\n    last_sign = -1 if first_sign < 0 else 1\n  for el in seq_iter:\n    if el * last_sign < neg_hyst:\n      last_sign = -1 if el < 0 else 1\n      yield 1\n    else:\n      yield 0",
    "docstring": "Zero-crossing stream.\n\n  Parameters\n  ----------\n  seq :\n    Any iterable to be used as input for the zero crossing analysis\n  hysteresis :\n    Crossing exactly zero might happen many times too fast due to high\n    frequency oscilations near zero. To avoid this, you can make two\n    threshold limits for the zero crossing detection: ``hysteresis`` and\n    ``-hysteresis``. Defaults to zero (0), which means no hysteresis and only\n    one threshold.\n  first_sign :\n    Optional argument with the sign memory from past. Gets the sig from any\n    signed number. Defaults to zero (0), which means \"any\", and the first sign\n    will be the first one found in data.\n\n  Returns\n  -------\n  A Stream instance that outputs 1 for each crossing detected, 0 otherwise."
  },
  {
    "code": "def get_albums(self, limit=None):\n        url = (self._imgur._base_url + \"/3/account/{0}/albums/{1}\".format(self.name,\n                                                                       '{}'))\n        resp = self._imgur._send_request(url, limit=limit)\n        return [Album(alb, self._imgur, False) for alb in resp]",
    "docstring": "Return  a list of the user's albums.\n\n        Secret and hidden albums are only returned if this is the logged-in\n        user."
  },
  {
    "code": "def get_types(self):\n        from . import types\n        url_path = '/handcar/services/learning/types/'\n        type_list = self._get_request(url_path)\n        type_list += types.TYPES\n        return objects.TypeList(type_list)",
    "docstring": "Gets all the known Types.\n\n        return: (osid.type.TypeList) - the list of all known Types\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        compliance: mandatory - This method must be implemented."
  },
  {
    "code": "def _copy_params(self):\n        cls = type(self)\n        src_name_attrs = [(x, getattr(cls, x)) for x in dir(cls)]\n        src_params = list(filter(lambda nameAttr: isinstance(nameAttr[1], Param), src_name_attrs))\n        for name, param in src_params:\n            setattr(self, name, param._copy_new_parent(self))",
    "docstring": "Copy all params defined on the class to current object."
  },
  {
    "code": "def _setup_trunk(self, trunk, vlan_id=None):\n        LOG.info('Binding trunk port: %s.', trunk)\n        try:\n            self._trunk_rpc.update_subport_bindings(self._context,\n                                                    trunk.sub_ports)\n            vlan_trunk = [s.segmentation_id for s in trunk.sub_ports]\n            self._set_port_vlan(trunk.port_id, vlan_id, vlan_trunk)\n            self._trunk_rpc.update_trunk_status(self._context, trunk.id,\n                                                t_const.ACTIVE_STATUS)\n        except Exception:\n            LOG.exception(\"Failure setting up subports for %s\", trunk.port_id)\n            self._trunk_rpc.update_trunk_status(self._context, trunk.id,\n                                                t_const.DEGRADED_STATUS)",
    "docstring": "Sets up VLAN trunk and updates the trunk status."
  },
  {
    "code": "def is_valid_py_file(path):\n    import os\n    is_valid = False\n    if os.path.isfile(path) and not os.path.splitext(path)[1] == '.pyx':\n        try:\n            with open(path, 'rb') as f:\n                compile(f.read(), path, 'exec')\n                is_valid = True\n        except:\n            pass\n    return is_valid",
    "docstring": "Checks whether the file can be read by the coverage module. This is especially\n    needed for .pyx files and .py files with syntax errors."
  },
  {
    "code": "def parse_member_from_rsvp(data):\n    return MeetupMember(\n        id=data['member'].get('member_id', None),\n        name=data['member'].get('name', None),\n        photo=(parse_photo(data['member_photo'])\n               if 'member_photo' in data else None)\n    )",
    "docstring": "Parse a ``MeetupMember`` from the given RSVP response data.\n\n    Returns\n    -------\n    A ``pythonkc_meetups.types.MeetupMember``."
  },
  {
    "code": "def chown_r(path: str, user: str, group: str) -> None:\n    for root, dirs, files in os.walk(path):\n        for x in dirs:\n            shutil.chown(os.path.join(root, x), user, group)\n        for x in files:\n            shutil.chown(os.path.join(root, x), user, group)",
    "docstring": "Performs a recursive ``chown``.\n\n    Args:\n        path: path to walk down\n        user: user name or ID\n        group: group name or ID\n\n    As per http://stackoverflow.com/questions/2853723"
  },
  {
    "code": "def get_open_orders(self, market=None):\n        return self._api_query(path_dict={\n            API_V1_1: '/market/getopenorders',\n            API_V2_0: '/key/market/getopenorders'\n        }, options={'market': market, 'marketname': market} if market else None, protection=PROTECTION_PRV)",
    "docstring": "Get all orders that you currently have opened.\n        A specific market can be requested.\n\n        Endpoint:\n        1.1 /market/getopenorders\n        2.0 /key/market/getopenorders\n\n        :param market: String literal for the market (ie. BTC-LTC)\n        :type market: str\n        :return: Open orders info in JSON\n        :rtype : dict"
  },
  {
    "code": "def cas2mach(cas, h):\n    tas = cas2tas(cas, h)\n    M   = tas2mach(tas, h)\n    return M",
    "docstring": "CAS Mach conversion"
  },
  {
    "code": "def connectionLostForKey(self, key):\n        if key in self.cachedConnections:\n            del self.cachedConnections[key]\n        if self._shuttingDown and self._shuttingDown.get(key):\n            d, self._shuttingDown[key] = self._shuttingDown[key], None\n            d.callback(None)",
    "docstring": "Remove lost connection from cache.\n\n        @param key: key of connection that was lost\n        @type key: L{tuple} of L{IAddress} and C{extraHash}"
  },
  {
    "code": "def add_epoch_number(batch: Batch, epoch: int) -> Batch:\n    for instance in batch.instances:\n        instance.fields['epoch_num'] = MetadataField(epoch)\n    return batch",
    "docstring": "Add the epoch number to the batch instances as a MetadataField."
  },
  {
    "code": "def _sync_hooks(self, repos, asynchronous=True):\n        if not asynchronous:\n            for repo_id in repos:\n                try:\n                    with db.session.begin_nested():\n                        self.sync_repo_hook(repo_id)\n                    db.session.commit()\n                except RepositoryAccessError as e:\n                    current_app.logger.warning(e.message, exc_info=True)\n                except NoResultFound:\n                    pass\n        else:\n            db.session.commit()\n            sync_hooks.delay(self.user_id, repos)",
    "docstring": "Check if a hooks sync task needs to be started."
  },
  {
    "code": "def selected_option(self):\n        \" Return the currently selected option. \"\n        i = 0\n        for category in self.options:\n            for o in category.options:\n                if i == self.selected_option_index:\n                    return o\n                else:\n                    i += 1",
    "docstring": "Return the currently selected option."
  },
  {
    "code": "def dump_relation(api, rel_cfg, pid, data):\n    schema_class = rel_cfg.schema\n    if schema_class is not None:\n        schema = schema_class()\n        schema.context['pid'] = pid\n        result, errors = schema.dump(api)\n        data.setdefault(rel_cfg.name, []).append(result)",
    "docstring": "Dump a specific relation to a data dict."
  },
  {
    "code": "def mmGetPlotUnionSDRActivity(self, title=\"Union SDR Activity Raster\",\n                                showReset=False, resetShading=0.25):\n    unionSDRTrace = self.mmGetTraceUnionSDR().data\n    columnCount = self.getNumColumns()\n    activityType = \"Union SDR Activity\"\n    return self.mmGetCellTracePlot(unionSDRTrace, columnCount, activityType,\n                                   title=title, showReset=showReset,\n                                   resetShading=resetShading)",
    "docstring": "Returns plot of the activity of union SDR bits.\n    @param title an optional title for the figure\n    @param showReset if true, the first set of activities after a reset\n                        will have a gray background\n    @param resetShading If showReset is true, this float specifies the\n    intensity of the reset background with 0.0 being white and 1.0 being black\n    @return (Plot) plot"
  },
  {
    "code": "def __verify_job_has_started(self):\n        self.__get_job()\n        pods = self.__get_pods()\n        assert len(pods) > 0, \"No pod scheduled by \" + self.uu_name\n        for pod in pods:\n            status = pod.obj['status']\n            for cont_stats in status.get('containerStatuses', []):\n                if 'terminated' in cont_stats['state']:\n                    t = cont_stats['state']['terminated']\n                    err_msg = \"Pod %s %s (exit code %d). Logs: `kubectl logs pod/%s`\" % (\n                        pod.name, t['reason'], t['exitCode'], pod.name)\n                    assert t['exitCode'] == 0, err_msg\n                if 'waiting' in cont_stats['state']:\n                    wr = cont_stats['state']['waiting']['reason']\n                    assert wr == 'ContainerCreating', \"Pod %s %s. Logs: `kubectl logs pod/%s`\" % (\n                        pod.name, wr, pod.name)\n            for cond in status.get('conditions', []):\n                if 'message' in cond:\n                    if cond['reason'] == 'ContainersNotReady':\n                        return False\n                    assert cond['status'] != 'False', \\\n                        \"[ERROR] %s - %s\" % (cond['reason'], cond['message'])\n        return True",
    "docstring": "Asserts that the job has successfully started"
  },
  {
    "code": "def split_limits_heads(self):\n        heads = []\n        new_limit_to = []\n        for limit in self.limit_to:\n            if '.' in limit:\n                name, limit = limit.split('.', 1)\n                heads.append(name)\n                new_limit_to.append(limit)\n            else:\n                heads.append(limit)\n        return heads, new_limit_to",
    "docstring": "Return first parts of dot-separated strings, and rest of strings.\n\n        Returns:\n            (list of str, list of str): the heads and rest of the strings."
  },
  {
    "code": "def time_afterwards_preceding(\n            self, when: datetime.datetime) -> Optional[datetime.timedelta]:\n        if self.is_empty():\n            return None\n        end_time = self.end_datetime()\n        if when <= end_time:\n            return datetime.timedelta()\n        else:\n            return when - end_time",
    "docstring": "Returns the time after our last interval, but before ``when``.\n        If ``self`` is an empty list, returns ``None``."
  },
  {
    "code": "def _apply_conv(self, inputs, w):\n    outputs = tf.nn.convolution(inputs, w, strides=self._stride,\n                                padding=self._conv_op_padding,\n                                dilation_rate=self._rate,\n                                data_format=self._data_format)\n    return outputs",
    "docstring": "Apply a convolution operation on `inputs` using variable `w`.\n\n    Args:\n      inputs: A Tensor of shape `data_format` and of type `tf.float16`,\n          `tf.bfloat16` or `tf.float32`.\n      w: A weight matrix of the same type as `inputs`.\n\n    Returns:\n      outputs: The result of the convolution operation on `inputs`."
  },
  {
    "code": "def feed_interval_get(feed_id, parameters):\n\t'Get adaptive interval between checks for a feed.'\n\tval = cache.get(getkey( T_INTERVAL,\n\t\tkey=feed_interval_key(feed_id, parameters) ))\n\treturn val if isinstance(val, tuple) else (val, None)",
    "docstring": "Get adaptive interval between checks for a feed."
  },
  {
    "code": "def check_positive(**params):\n    for p in params:\n        if not isinstance(params[p], numbers.Number) or params[p] <= 0:\n            raise ValueError(\n                \"Expected {} > 0, got {}\".format(p, params[p]))",
    "docstring": "Check that parameters are positive as expected\n\n    Raises\n    ------\n    ValueError : unacceptable choice of parameters"
  },
  {
    "code": "def add(self, post_id):\n        post_data = self.get_post_data()\n        post_data['user_name'] = self.userinfo.user_name\n        post_data['user_id'] = self.userinfo.uid\n        post_data['post_id'] = post_id\n        replyid = MReply.create_reply(post_data)\n        if replyid:\n            out_dic = {'pinglun': post_data['cnt_reply'],\n                       'uid': replyid}\n            logger.info('add reply result dic: {0}'.format(out_dic))\n            return json.dump(out_dic, self)",
    "docstring": "Adding reply to a post."
  },
  {
    "code": "def opensearch(self, query, results=10, redirect=True):\n        self._check_query(query, \"Query must be specified\")\n        query_params = {\n            \"action\": \"opensearch\",\n            \"search\": query,\n            \"limit\": (100 if results > 100 else results),\n            \"redirects\": (\"resolve\" if redirect else \"return\"),\n            \"warningsaserror\": True,\n            \"namespace\": \"\",\n        }\n        results = self.wiki_request(query_params)\n        self._check_error_response(results, query)\n        res = list()\n        for i, item in enumerate(results[1]):\n            res.append((item, results[2][i], results[3][i]))\n        return res",
    "docstring": "Execute a MediaWiki opensearch request, similar to search box\n            suggestions and conforming to the OpenSearch specification\n\n            Args:\n                query (str): Title to search for\n                results (int): Number of pages within the radius to return\n                redirect (bool): If **False** return the redirect itself, \\\n                                 otherwise resolve redirects\n            Returns:\n                List: List of results that are stored in a tuple \\\n                      (Title, Summary, URL)"
  },
  {
    "code": "def phenotype_data(self):\n        if self._phenotype_data is None:\n            pheno_data = {}\n            for gsm_name, gsm in iteritems(self.gsms):\n                tmp = {}\n                for key, value in iteritems(gsm.metadata):\n                    if len(value) == 0:\n                        tmp[key] = np.nan\n                    elif key.startswith(\"characteristics_\"):\n                        for i, char in enumerate(value):\n                            char = re.split(\":\\s+\", char)\n                            char_type, char_value = [char[0],\n                                                     \": \".join(char[1:])]\n                            tmp[key + \".\" + str(\n                                i) + \".\" + char_type] = char_value\n                    else:\n                        tmp[key] = \",\".join(value)\n                pheno_data[gsm_name] = tmp\n            self._phenotype_data = DataFrame(pheno_data).T\n        return self._phenotype_data",
    "docstring": "Get the phenotype data for each of the sample."
  },
  {
    "code": "def caller_path(steps=1):\n    frame = sys._getframe(steps + 1)\n    try:\n        path = os.path.dirname(frame.f_code.co_filename)\n    finally:\n        del frame\n    if not path:\n        path = os.getcwd()\n    return os.path.realpath(path)",
    "docstring": "Return the path to the source file of the current frames' caller."
  },
  {
    "code": "def reindex(self, kdims=[], force=False):\n        if not isinstance(kdims, list):\n            kdims = [kdims]\n        kdims = [self.get_dimension(kd, strict=True) for kd in kdims]\n        dropped = [kd for kd in self.kdims if kd not in kdims]\n        if dropped:\n            raise ValueError(\"DynamicMap does not allow dropping dimensions, \"\n                             \"reindex may only be used to reorder dimensions.\")\n        return super(DynamicMap, self).reindex(kdims, force)",
    "docstring": "Reorders key dimensions on DynamicMap\n\n        Create a new object with a reordered set of key dimensions.\n        Dropping dimensions is not allowed on a DynamicMap.\n\n        Args:\n            kdims: List of dimensions to reindex the mapping with\n            force: Not applicable to a DynamicMap\n\n        Returns:\n            Reindexed DynamicMap"
  },
  {
    "code": "def identify_names(filename):\n    node, _ = parse_source_file(filename)\n    if node is None:\n        return {}\n    finder = NameFinder()\n    finder.visit(node)\n    names = list(finder.get_mapping())\n    names += extract_object_names_from_docs(filename)\n    example_code_obj = collections.OrderedDict()\n    for name, full_name in names:\n        if name in example_code_obj:\n            continue\n        splitted = full_name.rsplit('.', 1)\n        if len(splitted) == 1:\n            continue\n        module, attribute = splitted\n        module_short = get_short_module_name(module, attribute)\n        cobj = {'name': attribute, 'module': module,\n                'module_short': module_short}\n        example_code_obj[name] = cobj\n    return example_code_obj",
    "docstring": "Builds a codeobj summary by identifying and resolving used names."
  },
  {
    "code": "def np2model_tensor(a):\n    \"Tranform numpy array `a` to a tensor of the same type.\"\n    dtype = model_type(a.dtype)\n    res = as_tensor(a)\n    if not dtype: return res\n    return res.type(dtype)",
    "docstring": "Tranform numpy array `a` to a tensor of the same type."
  },
  {
    "code": "def iiif_info_handler(prefix=None, identifier=None,\n                      config=None, klass=None, auth=None, **args):\n    if (not auth or degraded_request(identifier) or auth.info_authz()):\n        if (auth):\n            logging.debug(\"Authorized for image %s\" % identifier)\n        i = IIIFHandler(prefix, identifier, config, klass, auth)\n        try:\n            return i.image_information_response()\n        except IIIFError as e:\n            return i.error_response(e)\n    elif (auth.info_authn()):\n        abort(401)\n    else:\n        response = redirect(host_port_prefix(\n            config.host, config.port, prefix) + '/' + identifier + '-deg/info.json')\n        response.headers['Access-control-allow-origin'] = '*'\n        return response",
    "docstring": "Handler for IIIF Image Information requests."
  },
  {
    "code": "def _linear_inverse_kamb(cos_dist, sigma=3):\n    n = float(cos_dist.size)\n    radius = _kamb_radius(n, sigma)\n    f = 2 / (1 - radius)\n    cos_dist = cos_dist[cos_dist >= radius]\n    count = (f * (cos_dist - radius))\n    return count, _kamb_units(n, radius)",
    "docstring": "Kernel function from Vollmer for linear smoothing."
  },
  {
    "code": "def new(cls, store_type, store_entries):\n        if store_type not in ['jks', 'jceks']:\n            raise UnsupportedKeystoreTypeException(\"The Keystore Type '%s' is not supported\" % store_type)\n        entries = {}\n        for entry in store_entries:\n            if not isinstance(entry, AbstractKeystoreEntry):\n                raise UnsupportedKeystoreEntryTypeException(\"Entries must be a KeyStore Entry\")\n            if store_type != 'jceks' and isinstance(entry, SecretKeyEntry):\n                raise UnsupportedKeystoreEntryTypeException('Secret Key only allowed in JCEKS keystores')\n            alias = entry.alias\n            if alias in entries:\n                raise DuplicateAliasException(\"Found duplicate alias '%s'\" % alias)\n            entries[alias] = entry\n        return cls(store_type, entries)",
    "docstring": "Helper function to create a new KeyStore.\n\n        :param string store_type: What kind of keystore\n          the store should be. Valid options are jks or jceks.\n        :param list store_entries: Existing entries that\n          should be added to the keystore.\n\n        :returns: A loaded :class:`KeyStore` instance,\n          with the specified entries.\n\n        :raises DuplicateAliasException: If some of the\n          entries have the same alias.\n        :raises UnsupportedKeyStoreTypeException: If the keystore is of\n          an unsupported type\n        :raises UnsupportedKeyStoreEntryTypeException: If some\n          of the keystore entries are unsupported (in this keystore type)"
  },
  {
    "code": "def StreamMedia(self, callback=None, finish_callback=None,\n                    additional_headers=None, use_chunks=True):\n        callback = callback or self.progress_callback\n        finish_callback = finish_callback or self.finish_callback\n        self.EnsureInitialized()\n        while True:\n            if self.__initial_response is not None:\n                response = self.__initial_response\n                self.__initial_response = None\n            else:\n                end_byte = self.__ComputeEndByte(self.progress,\n                                                 use_chunks=use_chunks)\n                response = self.__GetChunk(\n                    self.progress, end_byte,\n                    additional_headers=additional_headers)\n            if self.total_size is None:\n                self.__SetTotal(response.info)\n            response = self.__ProcessResponse(response)\n            self._ExecuteCallback(callback, response)\n            if (response.status_code == http_client.OK or\n                    self.progress >= self.total_size):\n                break\n        self._ExecuteCallback(finish_callback, response)",
    "docstring": "Stream the entire download.\n\n        Args:\n          callback: (default: None) Callback to call as each chunk is\n              completed.\n          finish_callback: (default: None) Callback to call when the\n              download is complete.\n          additional_headers: (default: None) Additional headers to\n              include in fetching bytes.\n          use_chunks: (bool, default: True) If False, ignore self.chunksize\n              and stream this download in a single request.\n\n        Returns:\n            None. Streams bytes into self.stream."
  },
  {
    "code": "def run(self, *args):\n        if self.source is None:\n            self.model.summary()\n        else:\n            x_data, y_data = next(iter(self.source.train_loader()))\n            self.model.summary(input_size=x_data.shape[1:])",
    "docstring": "Print model summary"
  },
  {
    "code": "def parseMemory(buffer, size):\n    ret = libxml2mod.xmlParseMemory(buffer, size)\n    if ret is None:raise parserError('xmlParseMemory() failed')\n    return xmlDoc(_obj=ret)",
    "docstring": "parse an XML in-memory block and build a tree."
  },
  {
    "code": "def request(self, arg=None):\n        if not self.status:\n            return '{\"result\": \"No message\"}'\n        try:\n            status_dict = json.loads(mpstatus_to_json(self.status))\n        except Exception as e:\n            print(e)\n            return\n        if not arg:\n            return json.dumps(status_dict)\n        new_dict = status_dict\n        args = arg.split('/')\n        for key in args:\n            if key in new_dict:\n                new_dict = new_dict[key]\n            else:\n                return '{\"key\": \"%s\", \"last_dict\": %s}' % (key, json.dumps(new_dict))\n        return json.dumps(new_dict)",
    "docstring": "Deal with requests"
  },
  {
    "code": "def wait_for_zone_op(access_token, project, zone, name, interval=1.0):\n    assert isinstance(interval, (int, float))\n    assert interval >= 0.1\n    status = 'RUNNING'\n    progress = 0\n    LOGGER.info('Waiting for zone operation \"%s\" to finish...', name)\n    while status != 'DONE':\n        r = requests.get('https://www.googleapis.com/compute/v1/'\n                         'projects/%s/zones/%s/operations/%s?access_token=%s'\n                         % (project, zone, name, access_token.access_token))\n        r.raise_for_status()\n        result = r.json()\n        status = result['status']\n        progress = result['progress']\n        time.sleep(interval)\n    LOGGER.info('Zone operation \"%s\" done!', name)",
    "docstring": "Wait until a zone operation is finished.\n\n    TODO: docstring"
  },
  {
    "code": "def polynomial_reduce_mod( poly, polymod, p ):\n  assert polymod[-1] == 1\n  assert len( polymod ) > 1\n  while len( poly ) >= len( polymod ):\n    if poly[-1] != 0:\n      for i in range( 2, len( polymod ) + 1 ):\n        poly[-i] = ( poly[-i] - poly[-1] * polymod[-i] ) % p\n    poly = poly[0:-1]\n  return poly",
    "docstring": "Reduce poly by polymod, integer arithmetic modulo p.\n\n  Polynomials are represented as lists of coefficients\n  of increasing powers of x."
  },
  {
    "code": "def grok_filter_name(element):\n    e_name = None\n    if element.name == 'default':\n        if isinstance(element.node, jinja2.nodes.Getattr):\n            e_name = element.node.node.name\n        else:\n            e_name = element.node.name\n    return e_name",
    "docstring": "Extracts the name, which may be embedded, for a Jinja2\n    filter node"
  },
  {
    "code": "def send_keys_to_element(self, element, *keys_to_send):\n        self.click(element)\n        self.send_keys(*keys_to_send)\n        return self",
    "docstring": "Sends keys to an element.\n\n        :Args:\n         - element: The element to send keys.\n         - keys_to_send: The keys to send.  Modifier keys constants can be found in the\n           'Keys' class."
  },
  {
    "code": "def get_alpha_or_number(number, template):\n    match = re.match(r\".*\\{alpha:(\\d+a\\d+d)\\}$\", template.strip())\n    if match and match.groups():\n        format = match.groups()[0]\n        return to_alpha(number, format)\n    return number",
    "docstring": "Returns an Alphanumber that represents the number passed in, expressed\n    as defined in the template. Otherwise, returns the number"
  },
  {
    "code": "def clean(self):\n        if os.path.isdir(self.schema_mof_dir):\n            shutil.rmtree(self.schema_mof_dir)",
    "docstring": "Remove all of the MOF files and the `schema_mof_dir` for the defined\n        schema.  This is useful because while the downloaded schema is a single\n        compressed zip file, it creates several thousand MOF files that take up\n        considerable space.\n\n        The next time the :class:`~pywbem_mock.DMTFCIMSchema` object for this\n        `schema_version` and `schema_root_dir` is created, the MOF file are\n        extracted again."
  },
  {
    "code": "def event(self, event):\r\n        if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Tab:\r\n            return False\r\n        return QWidget.event(self, event)",
    "docstring": "Qt Override.\r\n\r\n        Usefull when in line edit mode."
  },
  {
    "code": "def getIndxOps(self, valu, cmpr='='):\n        func = self.indxcmpr.get(cmpr)\n        if func is None:\n            raise s_exc.NoSuchCmpr(name=self.name, cmpr=cmpr)\n        return func(valu)",
    "docstring": "Return a list of index operation tuples to lift values in a table.\n\n        Valid index operations include:\n            ('eq', <indx>)\n            ('pref', <indx>)\n            ('range', (<minindx>, <maxindx>))"
  },
  {
    "code": "def query_by_post(postid):\n        return TabReply.select().where(\n            TabReply.post_id == postid\n        ).order_by(TabReply.timestamp.desc())",
    "docstring": "Get reply list of certain post."
  },
  {
    "code": "def from_learners(cls, learn_gen:Learner, learn_crit:Learner, switcher:Callback=None,\n                      weights_gen:Tuple[float,float]=None, **learn_kwargs):\n        \"Create a GAN from `learn_gen` and `learn_crit`.\"\n        losses = gan_loss_from_func(learn_gen.loss_func, learn_crit.loss_func, weights_gen=weights_gen)\n        return cls(learn_gen.data, learn_gen.model, learn_crit.model, *losses, switcher=switcher, **learn_kwargs)",
    "docstring": "Create a GAN from `learn_gen` and `learn_crit`."
  },
  {
    "code": "def update_nodes(self, char, patch, backdate=False):\n        if backdate:\n            parbranch, parrev = self._real._parentbranch_rev.get(\n                self._real.branch, ('trunk', 0)\n            )\n            tick_now = self._real.tick\n            self._real.tick = parrev\n        for i, (n, npatch) in enumerate(patch.items(), 1):\n            self.update_node(char, n, npatch)\n        if backdate:\n            self._real.tick = tick_now",
    "docstring": "Change the stats of nodes in a character according to a\n        dictionary."
  },
  {
    "code": "def _linefeed(self):\n        last_line = self._cursor.blockNumber() == self._text_edit.blockCount() - 1\n        if self._cursor.atEnd() or last_line:\n            if last_line:\n                self._cursor.movePosition(self._cursor.EndOfBlock)\n            self._cursor.insertText('\\n')\n        else:\n            self._cursor.movePosition(self._cursor.Down)\n            self._cursor.movePosition(self._cursor.StartOfBlock)\n        self._text_edit.setTextCursor(self._cursor)",
    "docstring": "Performs a line feed."
  },
  {
    "code": "def validate(self, instance, value):\n        if isinstance(value, datetime.datetime):\n            return value\n        if not isinstance(value, string_types):\n            self.error(\n                instance=instance,\n                value=value,\n                extra='Cannot convert non-strings to datetime.',\n            )\n        try:\n            return self.from_json(value)\n        except ValueError:\n            self.error(\n                instance=instance,\n                value=value,\n                extra='Invalid format for converting to datetime.',\n            )",
    "docstring": "Check if value is a valid datetime object or JSON datetime string"
  },
  {
    "code": "def on_peer_down(self, peer):\n        LOG.debug('Cleaning obsolete paths whose source/version: %s/%s',\n                  peer.ip_address, peer.version_num)\n        self._table_manager.clean_stale_routes(peer)",
    "docstring": "Peer down handler.\n\n        Cleans up the paths in global tables that was received from this peer."
  },
  {
    "code": "def get_tx_amount(cls, txid, txindex):\n        for api_call in cls.GET_TX_AMOUNT_MAIN:\n            try:\n                return api_call(txid, txindex)\n            except cls.IGNORED_ERRORS:\n                pass\n        raise ConnectionError('All APIs are unreachable.')",
    "docstring": "Gets the amount of a given transaction output.\n\n        :param txid: The transaction id in question.\n        :type txid: ``str``\n        :param txindex: The transaction index in question.\n        :type txindex: ``int``\n        :raises ConnectionError: If all API services fail.\n        :rtype: ``Decimal``"
  },
  {
    "code": "def get(self, device_id: int) -> Optional[Device]:\n        return self._devices.get(device_id)",
    "docstring": "Get device using the specified ID, or None if not found."
  },
  {
    "code": "def import_sip04_data_all(data_filename):\n    filename, fformat = os.path.splitext(data_filename)\n    if fformat == '.csv':\n        print('Import SIP04 data from .csv file')\n        df_all = _import_csv_file(data_filename)\n    elif fformat == '.mat':\n        print('Import SIP04 data from .mat file')\n        df_all = _import_mat_file(data_filename)\n    else:\n        print('Please use .csv or .mat format.')\n        df_all = None\n    return df_all",
    "docstring": "Import ALL data from the result files\n\n    Parameters\n    ----------\n    data_filename : string\n        Path to .mat or .csv file containing SIP-04 measurement results. Note\n        that the .csv file does not contain all data contained in the .mat\n        file!\n\n    Returns\n    -------\n    df_all : :py:class:`pandas.DataFrame`\n        The data, contained in a DataFrame"
  },
  {
    "code": "def hydrate_time(nanoseconds, tz=None):\n    seconds, nanoseconds = map(int, divmod(nanoseconds, 1000000000))\n    minutes, seconds = map(int, divmod(seconds, 60))\n    hours, minutes = map(int, divmod(minutes, 60))\n    seconds = (1000000000 * seconds + nanoseconds) / 1000000000\n    t = Time(hours, minutes, seconds)\n    if tz is None:\n        return t\n    tz_offset_minutes, tz_offset_seconds = divmod(tz, 60)\n    zone = FixedOffset(tz_offset_minutes)\n    return zone.localize(t)",
    "docstring": "Hydrator for `Time` and `LocalTime` values.\n\n    :param nanoseconds:\n    :param tz:\n    :return: Time"
  },
  {
    "code": "def extend_array(a, n):\n    a_new = a.copy()\n    for d in range(a.ndim):\n        a_new = np.repeat(a_new, n, axis=d)\n    return a_new",
    "docstring": "Increase the resolution of an array by duplicating its values to fill\n    a larger array.\n\n    Parameters\n    ----------\n    a: array, shape (a1, a2, a3, ...)\n    n: integer\n        Factor by which to expand the array.\n\n    Returns\n    -------\n    ae: array, shape (n * a1, n * a2, n * a3, ...)"
  },
  {
    "code": "def set_topics(self, topics):\n        if set(topics).difference(self._topics):\n            future = self.cluster.request_update()\n        else:\n            future = Future().success(set(topics))\n        self._topics = set(topics)\n        return future",
    "docstring": "Set specific topics to track for metadata.\n\n        Arguments:\n            topics (list of str): topics to check for metadata\n\n        Returns:\n            Future: resolves after metadata request/response"
  },
  {
    "code": "def assert_hashable(*args, **kw):\n    try:\n        for i, arg in enumerate(args):\n            hash(arg)\n    except TypeError:\n        raise TypeError('Argument in position %d is not hashable: %r' % (i, arg))\n    try:\n        for key, val in iterate_items(kw):\n            hash(val)\n    except TypeError:\n        raise TypeError('Keyword argument %r is not hashable: %r' % (key, val))",
    "docstring": "Verify that each argument is hashable.\n\n    Passes silently if successful. Raises descriptive TypeError otherwise.\n\n    Example::\n\n        >>> assert_hashable(1, 'foo', bar='baz')\n        >>> assert_hashable(1, [], baz='baz')\n        Traceback (most recent call last):\n          ...\n        TypeError: Argument in position 1 is not hashable: []\n        >>> assert_hashable(1, 'foo', bar=[])\n        Traceback (most recent call last):\n          ...\n        TypeError: Keyword argument 'bar' is not hashable: []"
  },
  {
    "code": "def _only_main(func):\n    @wraps(func)\n    def wrapper(self, *args, **kwargs):\n        if not self.is_main:\n            return getattr(self.main, func.__name__)(*args, **kwargs)\n        return func(self, *args, **kwargs)\n    return wrapper",
    "docstring": "Call the given `func` only from the main project"
  },
  {
    "code": "def zip(self, *items):\n        return self.__class__(list(zip(self.items, *items)))",
    "docstring": "Zip the collection together with one or more arrays.\n\n        :param items: The items to zip\n        :type items: list\n\n        :rtype: Collection"
  },
  {
    "code": "def set_wake_on_modem(enabled):\n    state = salt.utils.mac_utils.validate_enabled(enabled)\n    cmd = 'systemsetup -setwakeonmodem {0}'.format(state)\n    salt.utils.mac_utils.execute_return_success(cmd)\n    return salt.utils.mac_utils.confirm_updated(\n        state,\n        get_wake_on_modem,\n    )",
    "docstring": "Set whether or not the computer will wake from sleep when modem activity is\n    detected.\n\n    :param bool enabled: True to enable, False to disable. \"On\" and \"Off\" are\n        also acceptable values. Additionally you can pass 1 and 0 to represent\n        True and False respectively\n\n    :return: True if successful, False if not\n    :rtype: bool\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' power.set_wake_on_modem True"
  },
  {
    "code": "def set_state(self, state):\n        self.basicevent.SetBinaryState(BinaryState=int(state))\n        self._state = int(state)",
    "docstring": "Set the state of this device to on or off."
  },
  {
    "code": "def get_domain_config(self, domain):\n        domain_root = self.identify_domain_root(domain)\n        host = ''\n        if len(domain_root) != len(domain):\n            host = domain.replace('.' + domain_root, '')\n        domain_connect_api = self._identify_domain_connect_api(domain_root)\n        ret = self._get_domain_config_for_root(domain_root, domain_connect_api)\n        return DomainConnectConfig(domain, domain_root, host, ret)",
    "docstring": "Makes a discovery of domain name and resolves configuration of DNS provider\n\n        :param domain: str\n            domain name\n        :return: DomainConnectConfig\n            domain connect config\n        :raises: NoDomainConnectRecordException\n            when no _domainconnect record found\n        :raises: NoDomainConnectSettingsException\n            when settings are not found"
  },
  {
    "code": "def _send_to_kafka(self, master):\n        appid_topic = \"{prefix}.outbound_{appid}\".format(\n                                                    prefix=self.topic_prefix,\n                                                    appid=master['appid'])\n        firehose_topic = \"{prefix}.outbound_firehose\".format(\n                                                    prefix=self.topic_prefix)\n        try:\n            if self.use_appid_topics:\n                f1 = self.producer.send(appid_topic, master)\n                f1.add_callback(self._kafka_success)\n                f1.add_errback(self._kafka_failure)\n            f2 = self.producer.send(firehose_topic, master)\n            f2.add_callback(self._kafka_success)\n            f2.add_errback(self._kafka_failure)\n            return True\n        except Exception as ex:\n            message = \"An exception '{0}' occured while sending a message \" \\\n                \"to kafka. Arguments:\\n{1!r}\" \\\n                .format(type(ex).__name__, ex.args)\n            self.logger.error(message)\n        return False",
    "docstring": "Sends the message back to Kafka\n        @param master: the final dict to send\n        @returns: True if successfully sent to kafka"
  },
  {
    "code": "def create_version(self, service_id, inherit_service_id=None, comment=None):\n\t\tbody = self._formdata({\n\t\t\t\"service_id\": service_id,\n\t\t\t\"inherit_service_id\": inherit_service_id,\n\t\t\t\"comment\": comment,\n\t\t}, FastlyVersion.FIELDS)\n\t\tcontent = self._fetch(\"/service/%s/version\" % service_id, method=\"POST\", body=body)\n\t\treturn FastlyVersion(self, content)",
    "docstring": "Create a version for a particular service."
  },
  {
    "code": "def _count_counters(self, counter):\n        if getattr(self, 'as_set', False):\n            return len(set(counter))\n        else:\n            return sum(counter.values())",
    "docstring": "Return all elements count from Counter"
  },
  {
    "code": "def get_accessibility(self, plugin_override=True):\n        vals = self._hook_manager.call_hook('course_accessibility', course=self, default=self._accessible)\n        return vals[0] if len(vals) and plugin_override else self._accessible",
    "docstring": "Return the AccessibleTime object associated with the accessibility of this course"
  },
  {
    "code": "def remove(self, item):\n        item = self.__coerce(item)\n        self.all.remove(item)\n        super().remove(item)",
    "docstring": "Remove either an unparsed argument string or an argument object.\n\n        :param Union[str,Arg] item: Item to remove\n\n        >>> arguments = TexArgs([RArg('arg0'), '[arg2]', '{arg3}'])\n        >>> arguments.remove('{arg0}')\n        >>> len(arguments)\n        2\n        >>> arguments[0]\n        OArg('arg2')"
  },
  {
    "code": "def run(ctx, commandline):\n    file = ctx.obj['FILE']\n    dotenv_as_dict = dotenv_values(file)\n    if not commandline:\n        click.echo('No command given.')\n        exit(1)\n    ret = run_command(commandline, dotenv_as_dict)\n    exit(ret)",
    "docstring": "Run command with environment variables present."
  },
  {
    "code": "def kwargs(self):\n        if hasattr(self, '_has_kwargs') and self._has_kwargs:\n            raise NotImplementedError(\n                \"Class %s does not provide a kwargs property\"\n                % str(self.__class__.__name__))\n        return {}",
    "docstring": "The dictionary of keyword-only arguments for the instantiation of\n        the Expression"
  },
  {
    "code": "def _get_methods_that_calculate_outputs(inputs, outputs, methods):\n    intermediates = get_calculatable_quantities(inputs, methods)\n    return_methods = {}\n    outputs = list(outputs)\n    keep_going = True\n    while keep_going:\n        keep_going = False\n        for output in outputs:\n            try:\n                output_dict = return_methods[output]\n            except:\n                output_dict = {}\n            for args, func in methods[output].items():\n                if args not in output_dict.keys():\n                    needed = []\n                    for arg in args:\n                        if arg in inputs:\n                            pass\n                        elif arg in outputs:\n                            pass\n                        elif arg in intermediates:\n                            if arg not in outputs:\n                                needed.append(arg)\n                        else:\n                            break\n                    else:\n                        output_dict[args] = func\n                        if len(needed) > 0:\n                            outputs.extend(needed)\n                            keep_going = True\n            if len(output_dict) > 0:\n                return_methods[output] = output_dict\n    return return_methods",
    "docstring": "Given iterables of input variable names, output variable names,\n    and a methods dictionary, returns the subset of the methods dictionary\n    that can be calculated, doesn't calculate something we already have,\n    and only contains equations that might help calculate the outputs from\n    the inputs."
  },
  {
    "code": "def _check_reply_pending(self, option):\n        if not self.telnet_opt_dict.has_key(option):\n            self.telnet_opt_dict[option] = TelnetOption()\n        return self.telnet_opt_dict[option].reply_pending",
    "docstring": "Test the status of requested Telnet options."
  },
  {
    "code": "def eigenvector_sensitivity(T, k, j, right=True):\n    r\n    T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric')\n    if _issparse(T):\n        _showSparseConversionWarning()\n        eigenvector_sensitivity(T.todense(), k, j, right=right)\n    else:\n        return dense.sensitivity.eigenvector_sensitivity(T, k, j, right=right)",
    "docstring": "r\"\"\"Sensitivity matrix of a selected eigenvector element.\n\n    Parameters\n    ----------\n    T : (M, M) ndarray\n        Transition matrix (stochastic matrix).\n    k : int\n        Eigenvector index\n    j : int\n        Element index\n    right : bool\n        If True compute for right eigenvector, otherwise compute for left eigenvector.\n\n    Returns\n    -------\n    S : (M, M) ndarray\n        Sensitivity matrix for the j-th element of the k-th eigenvector."
  },
  {
    "code": "def is_token_valid(self, token):\n        try:\n            _tinfo = self.handler.info(token)\n        except KeyError:\n            return False\n        if is_expired(int(_tinfo['exp'])) or _tinfo['black_listed']:\n            return False\n        session_info = self[_tinfo['sid']]\n        if session_info[\"oauth_state\"] == \"authz\":\n            if _tinfo['handler'] != self.handler['code']:\n                return False\n        elif session_info[\"oauth_state\"] == \"token\":\n            if _tinfo['handler'] != self.handler['access_token']:\n                return False\n        return True",
    "docstring": "Checks validity of a given token\n\n        :param token: Access or refresh token"
  },
  {
    "code": "def should_sample(self):\n        return self.span_context.trace_options.enabled \\\n            or self.sampler.should_sample(self.span_context.trace_id)",
    "docstring": "Determine whether to sample this request or not.\n        If the context enables tracing, return True.\n        Else follow the decision of the sampler.\n\n        :rtype: bool\n        :returns: Whether to trace the request or not."
  },
  {
    "code": "def kill(self, wait=True, sig=None):\n        if sig is None:\n            sig = self._sig_kill\n        if self.running():\n            os.killpg(self.process.pid, sig)\n            if wait:\n                self.process.wait()\n        self._kill_all_kids(sig)\n        self._clear_process()\n        return self",
    "docstring": "Kill the process if running.\n\n        :param bool wait: set to `True` to wait for the process to end,\n            or False, to simply proceed after sending signal.\n        :param int sig: signal used to kill process run by the executor.\n            None by default.\n        :returns: itself\n        :rtype: SimpleExecutor"
  },
  {
    "code": "def _put_bucket_cors(self):\n        if self.s3props['cors']['enabled'] and self.s3props['website']['enabled']:\n            cors_config = {}\n            cors_rules = []\n            for each_rule in self.s3props['cors']['cors_rules']:\n                cors_rules.append({\n                    'AllowedHeaders': each_rule['cors_headers'],\n                    'AllowedMethods': each_rule['cors_methods'],\n                    'AllowedOrigins': each_rule['cors_origins'],\n                    'ExposeHeaders': each_rule['cors_expose_headers'],\n                    'MaxAgeSeconds': each_rule['cors_max_age']\n                })\n            cors_config = {\n                'CORSRules': cors_rules\n            }\n            LOG.debug(cors_config)\n            _response = self.s3client.put_bucket_cors(Bucket=self.bucket, CORSConfiguration=cors_config)\n        else:\n            _response = self.s3client.delete_bucket_cors(Bucket=self.bucket)\n        LOG.debug('Response setting up S3 CORS: %s', _response)\n        LOG.info('S3 CORS configuration updated')",
    "docstring": "Adds bucket cors configuration."
  },
  {
    "code": "def density_matrix(self):\n        size = 2 ** len(self._qubit_map)\n        return np.reshape(self._density_matrix, (size, size))",
    "docstring": "Returns the density matrix at this step in the simulation.\n\n        The density matrix that is stored in this result is returned in the\n        computational basis with these basis states defined by the qubit_map.\n        In particular the value in the qubit_map is the index of the qubit,\n        and these are translated into binary vectors where the last qubit is\n        the 1s bit of the index, the second-to-last is the 2s bit of the index,\n        and so forth (i.e. big endian ordering). The density matrix is a\n        `2 ** num_qubits` square matrix, with rows and columns ordered by\n        the computational basis as just described.\n\n        Example:\n             qubit_map: {QubitA: 0, QubitB: 1, QubitC: 2}\n             Then the returned density matrix will have (row and column) indices\n             mapped to qubit basis states like the following table\n\n                    | QubitA | QubitB | QubitC\n                :-: | :----: | :----: | :----:\n                 0  |   0    |   0    |   0\n                 1  |   0    |   0    |   1\n                 2  |   0    |   1    |   0\n                 3  |   0    |   1    |   1\n                 4  |   1    |   0    |   0\n                 5  |   1    |   0    |   1\n                 6  |   1    |   1    |   0\n                 7  |   1    |   1    |   1"
  },
  {
    "code": "def convert_complexFaultSource(self, node):\n        geom = node.complexFaultGeometry\n        edges = self.geo_lines(geom)\n        mfd = self.convert_mfdist(node)\n        msr = valid.SCALEREL[~node.magScaleRel]()\n        with context(self.fname, node):\n            cmplx = source.ComplexFaultSource(\n                source_id=node['id'],\n                name=node['name'],\n                tectonic_region_type=node.attrib.get('tectonicRegion'),\n                mfd=mfd,\n                rupture_mesh_spacing=self.complex_fault_mesh_spacing,\n                magnitude_scaling_relationship=msr,\n                rupture_aspect_ratio=~node.ruptAspectRatio,\n                edges=edges,\n                rake=~node.rake,\n                temporal_occurrence_model=self.get_tom(node))\n        return cmplx",
    "docstring": "Convert the given node into a complex fault object.\n\n        :param node: a node with tag areaGeometry\n        :returns: a :class:`openquake.hazardlib.source.ComplexFaultSource`\n                  instance"
  },
  {
    "code": "def decode_csr(b64der):\n    try:\n        return x509.load_der_x509_csr(\n            decode_b64jose(b64der), default_backend())\n    except ValueError as error:\n        raise DeserializationError(error)",
    "docstring": "Decode JOSE Base-64 DER-encoded CSR.\n\n    :param str b64der: The encoded CSR.\n\n    :rtype: `cryptography.x509.CertificateSigningRequest`\n    :return: The decoded CSR."
  },
  {
    "code": "def start(ctx, **kwargs):\n    update_context(ctx, kwargs)\n    daemon = mk_daemon(ctx)\n    if ctx.debug or kwargs['no_fork']:\n        daemon.run()\n    else:\n        daemon.start()",
    "docstring": "start a vaping process"
  },
  {
    "code": "def arbiter(**params):\n    arbiter = get_actor()\n    if arbiter is None:\n        return set_actor(_spawn_actor('arbiter', None, **params))\n    elif arbiter.is_arbiter():\n        return arbiter",
    "docstring": "Obtain the ``arbiter``.\n\n    It returns the arbiter instance only if we are on the arbiter\n    context domain, otherwise it returns nothing."
  },
  {
    "code": "def stop(self, check=True):\n        if (check and self.countiter > 0 and self.opts['termination_callback'] and\n                self.opts['termination_callback'] != str(self.opts['termination_callback'])):\n            self.callbackstop = self.opts['termination_callback'](self)\n        return self._stopdict(self, check)",
    "docstring": "return a dictionary with the termination status.\n        With ``check==False``, the termination conditions are not checked\n        and the status might not reflect the current situation."
  },
  {
    "code": "def getNucleotideCodon(sequence, x1) :\n\tif x1 < 0 or x1 >= len(sequence) :\n\t\treturn None\n\tp = x1%3\n\tif p == 0 :\n\t\treturn (sequence[x1: x1+3], 0)\n\telif p ==1 :\n\t\treturn (sequence[x1-1: x1+2], 1)\n\telif p == 2 :\n\t\treturn (sequence[x1-2: x1+1], 2)",
    "docstring": "Returns the entire codon of the nucleotide at pos x1 in sequence, \n\tand the position of that nocleotide in the codon in a tuple"
  },
  {
    "code": "def _nanmedian(array, axis=None):\n    if isinstance(axis, tuple):\n        array = _move_tuple_axes_first(array, axis=axis)\n        axis = 0\n    return bottleneck.nanmedian(array, axis=axis)",
    "docstring": "Bottleneck nanmedian function that handle tuple axis."
  },
  {
    "code": "def in_SCAT_box(x, y, low_bound, high_bound, x_max, y_max):\n    passing = True\n    upper_limit = high_bound(x)\n    lower_limit = low_bound(x)\n    if x > x_max or y > y_max:\n        passing = False\n    if x < 0 or y < 0:\n        passing = False\n    if y > upper_limit:\n        passing = False\n    if y < lower_limit:\n        passing = False\n    return passing",
    "docstring": "determines if a particular point falls within a box"
  },
  {
    "code": "def urlencode_params(params):\n    params = [(key, normalize_for_urlencode(val)) for key, val in params]\n    return requests.utils.unquote_unreserved(urlencode(params))",
    "docstring": "URL encodes the parameters.\n\n    :param params: The parameters\n    :type params: list of key/value tuples.\n\n    :rtype: string"
  },
  {
    "code": "def move(fname, folder, options):\n    if os.path.isfile(fname):\n        shutil.move(fname, folder)\n    else:\n        if options.silent is False:\n            print('{0} missing'.format(fname))",
    "docstring": "Move file to dir if existing"
  },
  {
    "code": "def _create_alias_map(im, alias=None):\n    r\n    phases_num = sp.unique(im * 1)\n    phases_num = sp.trim_zeros(phases_num)\n    al = {}\n    for values in phases_num:\n        al[values] = 'phase{}'.format(values)\n    if alias is not None:\n        alias_sort = dict(sorted(alias.items()))\n        phase_labels = sp.array([*alias_sort])\n        al = alias\n        if set(phase_labels) != set(phases_num):\n            raise Exception('Alias labels does not match with image labels '\n                            'please provide correct image labels')\n    return al",
    "docstring": "r\"\"\"\n    Creates an alias mapping between phases in original image and identifyable\n    names. This mapping is used during network extraction to label\n    interconnection between and properties of each phase.\n\n    Parameters\n    ----------\n    im : ND-array\n        Image of porous material where each phase is represented by unique\n        integer. Phase integer should start from 1. Boolean image will extract\n        only one network labeled with True's only.\n\n    alias : dict (Optional)\n        A dictionary that assigns unique image label to specific phase.\n        For example {1: 'Solid'} will show all structural properties associated\n        with label 1 as Solid phase properties.\n        If ``None`` then default labelling will be used i.e {1: 'Phase1',..}.\n\n    Returns\n    -------\n    A dictionary with numerical phase labels as key, and readable phase names\n    as valuies. If no alias is provided then default labelling is used\n    i.e {1: 'Phase1',..}"
  },
  {
    "code": "def remove_workspace(self):\n        def confirm_clicked():\n            if len(self.document_model.workspaces) > 1:\n                command = Workspace.RemoveWorkspaceCommand(self)\n                command.perform()\n                self.document_controller.push_undo_command(command)\n        caption = _(\"Remove workspace named '{0}'?\").format(self.__workspace.name)\n        self.pose_confirmation_message_box(caption, confirm_clicked, accepted_text=_(\"Remove Workspace\"),\n                                           message_box_id=\"remove_workspace\")",
    "docstring": "Pose a dialog to confirm removal then remove workspace."
  },
  {
    "code": "def collectstatic(settings_module,\n                  bin_env=None,\n                  no_post_process=False,\n                  ignore=None,\n                  dry_run=False,\n                  clear=False,\n                  link=False,\n                  no_default_ignore=False,\n                  pythonpath=None,\n                  env=None,\n                  runas=None):\n    args = ['noinput']\n    kwargs = {}\n    if no_post_process:\n        args.append('no-post-process')\n    if ignore:\n        kwargs['ignore'] = ignore\n    if dry_run:\n        args.append('dry-run')\n    if clear:\n        args.append('clear')\n    if link:\n        args.append('link')\n    if no_default_ignore:\n        args.append('no-default-ignore')\n    return command(settings_module,\n                   'collectstatic',\n                   bin_env,\n                   pythonpath,\n                   env,\n                   runas,\n                   *args, **kwargs)",
    "docstring": "Collect static files from each of your applications into a single location\n    that can easily be served in production.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' django.collectstatic <settings_module>"
  },
  {
    "code": "def sanitize_dict(input_dict):\n    r\n    plain_dict = dict()\n    for key in input_dict.keys():\n        value = input_dict[key]\n        if hasattr(value, 'keys'):\n            plain_dict[key] = sanitize_dict(value)\n        else:\n            plain_dict[key] = value\n    return plain_dict",
    "docstring": "r\"\"\"\n    Given a nested dictionary, ensures that all nested dicts are normal\n    Python dicts.  This is necessary for pickling, or just converting\n    an 'auto-vivifying' dict to something that acts normal."
  },
  {
    "code": "def normalize_feature_inputs(ctx, param, value):\n    for feature_like in value or ('-',):\n        try:\n            with click.open_file(feature_like) as src:\n                for feature in iter_features(iter(src)):\n                    yield feature\n        except IOError:\n            coords = list(coords_from_query(feature_like))\n            yield {\n                'type': 'Feature',\n                'properties': {},\n                'geometry': {\n                    'type': 'Point',\n                    'coordinates': coords}}",
    "docstring": "Click callback that normalizes feature input values.\n\n    Returns a generator over features from the input value.\n\n    Parameters\n    ----------\n    ctx: a Click context\n    param: the name of the argument or option\n    value: object\n        The value argument may be one of the following:\n\n        1. A list of paths to files containing GeoJSON feature\n           collections or feature sequences.\n        2. A list of string-encoded coordinate pairs of the form\n           \"[lng, lat]\", or \"lng, lat\", or \"lng lat\".\n\n        If no value is provided, features will be read from stdin."
  },
  {
    "code": "def clear(self):\n        for field in self.__privfields__:\n            delattr(self, field)\n            setattr(self, field, MPI(0))",
    "docstring": "delete and re-initialize all private components to zero"
  },
  {
    "code": "def _format_eval_result(value, show_stdv=True):\n    if len(value) == 4:\n        return '%s\\'s %s: %g' % (value[0], value[1], value[2])\n    elif len(value) == 5:\n        if show_stdv:\n            return '%s\\'s %s: %g + %g' % (value[0], value[1], value[2], value[4])\n        else:\n            return '%s\\'s %s: %g' % (value[0], value[1], value[2])\n    else:\n        raise ValueError(\"Wrong metric value\")",
    "docstring": "Format metric string."
  },
  {
    "code": "def dmag(self,band):\n        if self.mags is None:\n            raise ValueError('dmag is not defined because primary mags are not defined for this population.')\n        return self.stars['{}_mag'.format(band)] - self.mags[band]",
    "docstring": "Magnitude difference between primary star and BG stars"
  },
  {
    "code": "def get_banks(self):\n        catalogs = self._get_provider_session('bank_lookup_session').get_banks()\n        cat_list = []\n        for cat in catalogs:\n            cat_list.append(Bank(self._provider_manager, cat, self._runtime, self._proxy))\n        return BankList(cat_list)",
    "docstring": "Pass through to provider BankLookupSession.get_banks"
  },
  {
    "code": "def get_layout_context(self):\n        errors = self.non_field_errors()\n        for field in self.hidden_fields():\n            errors.extend(field.errors)\n        return {\n            'form': self,\n            'errors': errors,\n            'hidden_fields': self.hidden_fields(),\n            'visible_fields': self.visible_fields(),\n        }",
    "docstring": "Returns the context which is used when rendering the form to HTML.\n\n        The generated template context will contain the following variables:\n\n        * form: `Form` instance\n        * errors: `ErrorList` instance with non field errors and hidden field errors\n        * hidden_fields: All hidden fields to render.\n        * visible_fields: All visible fields to render.\n\n        :return: Template context for form rendering."
  },
  {
    "code": "def save_cb(self):\n        w = Widgets.SaveDialog(title='Save plot')\n        target = w.get_path()\n        if target is None:\n            return\n        plot_ext = self.settings.get('file_suffix', '.png')\n        if not target.endswith(plot_ext):\n            target += plot_ext\n        fig_dpi = 100\n        try:\n            fig = self.tab_plot.get_figure()\n            fig.savefig(target, dpi=fig_dpi)\n        except Exception as e:\n            self.logger.error(str(e))\n        else:\n            self.logger.info('Table plot saved as {0}'.format(target))",
    "docstring": "Save plot to file."
  },
  {
    "code": "def showdeletion(self, *objects):\n        from ..memory import showdeletion as S\n        for o in objects:\n            S.monitor_object_cleanup(o)",
    "docstring": "Record a stack trace at the point when an ROOT TObject is deleted"
  },
  {
    "code": "def bool(self, item, default=None):\n        try:\n            item = self.__getattr__(item)\n        except AttributeError as err:\n            if default is not None:\n                return default\n            raise err\n        if isinstance(item, (bool, int)):\n            return bool(item)\n        if (isinstance(item, str) and\n                item.lower() in ('n', 'no', 'false', 'f', '0')):\n            return False\n        return True if item else False",
    "docstring": "Return value of key as a boolean\n\n        :param item: key of value to transform\n        :param default: value to return if item does not exist\n        :return: approximated bool of value"
  },
  {
    "code": "def _get_taxids(self, taxids=None):\n        taxid_keys = set(self.taxid2asscs.keys())\n        return taxid_keys if taxids is None else set(taxids).intersection(taxid_keys)",
    "docstring": "Return user-specified taxids or taxids in self.taxid2asscs"
  },
  {
    "code": "def by_visits(self, event_kind=None):\n        qs = self.get_queryset()\n        if event_kind is not None:\n            qs = qs.filter(event__kind=event_kind)\n        qs = qs.annotate(num_visits=Count('event')) \\\n                .order_by('-num_visits', 'name_sort')\n        return qs",
    "docstring": "Gets Venues in order of how many Events have been held there.\n        Adds a `num_visits` field to each one.\n\n        event_kind filters by kind of Event, e.g. 'theatre', 'cinema', etc."
  },
  {
    "code": "def get_item(self):\n        \"If the item is publishable, get the visible version\"\n        if hasattr(self, 'get_draft'):\n            draft = self.get_draft()\n        else:\n            draft = self\n        if not hasattr(self, '_item_cache'):\n            try:\n                self._item_cache = draft.item.get_published_or_draft()\n            except AttributeError:\n                self._item_cache = draft.item\n        return self._item_cache",
    "docstring": "If the item is publishable, get the visible version"
  },
  {
    "code": "def _collect_layer_outputs(mod, data, include_layer=None, max_num_examples=None, logger=None):\n    collector = _LayerOutputCollector(include_layer=include_layer, logger=logger)\n    num_examples = _collect_layer_statistics(mod, data, collector, max_num_examples, logger)\n    return collector.nd_dict, num_examples",
    "docstring": "Collect layer outputs and save them in a dictionary mapped by layer names."
  },
  {
    "code": "def table_delete(self, table_name):\n    url = Api._ENDPOINT + (Api._TABLES_PATH % table_name)\n    return datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials,\n                                      raw_response=True)",
    "docstring": "Issues a request to delete a table.\n\n    Args:\n      table_name: the name of the table as a tuple of components.\n    Returns:\n      A parsed result object.\n    Raises:\n      Exception if there is an error performing the operation."
  },
  {
    "code": "def trace_memory_clean_caches(self):\n        urllib.parse.clear_cache()\n        re.purge()\n        linecache.clearcache()\n        copyreg.clear_extension_cache()\n        if hasattr(fnmatch, \"purge\"):\n            fnmatch.purge()\n        elif hasattr(fnmatch, \"_purge\"):\n            fnmatch._purge()\n        if hasattr(encodings, \"_cache\") and len(encodings._cache) > 0:\n            encodings._cache = {}\n        for handler in context.log.handlers:\n            handler.flush()",
    "docstring": "Avoid polluting results with some builtin python caches"
  },
  {
    "code": "def stop_and_destroy(self, sync=True):\n        def _self_destruct():\n            try_it_n_times(operation=self.destroy,\n                           expected_error_codes=['SERVER_STATE_ILLEGAL'],\n                           custom_error='destroying server failed')\n            for storage in self.storage_devices:\n                try_it_n_times(operation=storage.destroy,\n                               expected_error_codes=['STORAGE_STATE_ILLEGAL'],\n                               custom_error='destroying storage failed')\n        if sync:\n            self.populate()\n        if self.state in ['maintenance', 'error']:\n            self._wait_for_state_change(['stopped', 'started'])\n        if self.state == 'started':\n            try_it_n_times(operation=self.stop,\n                           expected_error_codes=['SERVER_STATE_ILLEGAL'],\n                           custom_error='stopping server failed')\n            self._wait_for_state_change(['stopped'])\n        if self.state == 'stopped':\n            _self_destruct()\n        else:\n            raise Exception('unknown server state: ' + self.state)",
    "docstring": "Destroy a server and its storages. Stops the server before destroying.\n\n        Syncs the server state from the API, use sync=False to disable."
  },
  {
    "code": "def get_sdk_version(self):\n        name = 'VCVarsQueryRegistry.bat'\n        path = os.path.join(self.tool_dir, name)\n        batch = read_file(path)\n        if not batch:\n            raise RuntimeError(_('failed to find the SDK version'))\n        regex = r'(?<=\\\\Microsoft SDKs\\\\Windows\\\\).+?(?=\")'\n        try:\n            version = re.search(regex, batch).group()\n        except AttributeError:\n            return ''\n        else:\n            logging.debug(_('SDK version: %s'), version)\n            return version",
    "docstring": "Get the version of Windows SDK\n        from VCVarsQueryRegistry.bat."
  },
  {
    "code": "def option(self, key, value=None, **kwargs):\n        if not isinstance(self._container, Section):\n            raise ValueError(\"Options can only be added inside a section!\")\n        option = Option(key, value, container=self._container, **kwargs)\n        option.value = value\n        self._container.structure.insert(self._idx, option)\n        self._idx += 1\n        return self",
    "docstring": "Creates a new option inside a section\n\n        Args:\n            key (str): key of the option\n            value (str or None): value of the option\n            **kwargs: are passed to the constructor of :class:`Option`\n\n        Returns:\n            self for chaining"
  },
  {
    "code": "def authenticate_credentials(self, payload):\n        username = payload.get('preferred_username') or payload.get('username')\n        if username is None:\n            raise exceptions.AuthenticationFailed('JWT must include a preferred_username or username claim!')\n        else:\n            try:\n                user, __ = get_user_model().objects.get_or_create(username=username)\n                attributes_updated = False\n                for claim, attr in self.get_jwt_claim_attribute_map().items():\n                    payload_value = payload.get(claim)\n                    if getattr(user, attr) != payload_value and payload_value is not None:\n                        setattr(user, attr, payload_value)\n                        attributes_updated = True\n                if attributes_updated:\n                    user.save()\n            except:\n                msg = 'User retrieval failed.'\n                logger.exception(msg)\n                raise exceptions.AuthenticationFailed(msg)\n        return user",
    "docstring": "Get or create an active user with the username contained in the payload."
  },
  {
    "code": "def replace(self, v):\n        if self.popsize < self._popsize:\n            return self.add(v)\n        k = self.tournament(negative=True)\n        self.clean(self.population[k])\n        self.population[k] = v\n        v.position = len(self._hist)\n        self._hist.append(v)\n        self.bsf = v\n        self.estopping = v\n        self._inds_replace += 1\n        self._density += self.get_density(v)\n        if self._inds_replace == self._popsize:\n            self._inds_replace = 0\n            self.generation += 1\n            gc.collect()",
    "docstring": "Replace an individual selected by negative tournament selection with\n        individual v"
  },
  {
    "code": "def evaluate_parameter_sets(self):\n        self.parameter_interpreter = LcoptParameterSet(self.modelInstance)\n        self.modelInstance.evaluated_parameter_sets = self.parameter_interpreter.evaluated_parameter_sets\n        self.modelInstance.bw2_export_params = self.parameter_interpreter.bw2_export_params",
    "docstring": "This takes the parameter sets of the model instance and evaluates any formulas using the parameter values to create a \n        fixed, full set of parameters for each parameter set in the model"
  },
  {
    "code": "def maelstrom(args):\n    infile = args.inputfile\n    genome = args.genome\n    outdir = args.outdir\n    pwmfile = args.pwmfile\n    methods = args.methods\n    ncpus = args.ncpus\n    if not os.path.exists(infile):\n        raise ValueError(\"file {} does not exist\".format(infile))\n    if methods:\n        methods = [x.strip() for x in methods.split(\",\")]\n    run_maelstrom(infile, genome, outdir, pwmfile, methods=methods, ncpus=ncpus)",
    "docstring": "Run the maelstrom method."
  },
  {
    "code": "def filter_belief():\n    if request.method == 'OPTIONS':\n        return {}\n    response = request.body.read().decode('utf-8')\n    body = json.loads(response)\n    stmts_json = body.get('statements')\n    belief_cutoff = body.get('belief_cutoff')\n    if belief_cutoff is not None:\n        belief_cutoff = float(belief_cutoff)\n    stmts = stmts_from_json(stmts_json)\n    stmts_out = ac.filter_belief(stmts, belief_cutoff)\n    return _return_stmts(stmts_out)",
    "docstring": "Filter to beliefs above a given threshold."
  },
  {
    "code": "def check_nonbond(molecule, thresholds):\n    for atom1 in range(molecule.graph.num_vertices):\n        for atom2 in range(atom1):\n            if molecule.graph.distances[atom1, atom2] > 2:\n                distance = np.linalg.norm(molecule.coordinates[atom1] - molecule.coordinates[atom2])\n                if distance < thresholds[frozenset([molecule.numbers[atom1], molecule.numbers[atom2]])]:\n                    return False\n    return True",
    "docstring": "Check whether all nonbonded atoms are well separated.\n\n       If a nonbond atom pair is found that has an interatomic distance below\n       the given thresholds. The thresholds dictionary has the following format:\n       {frozenset([atom_number1, atom_number2]): distance}\n\n       When random geometries are generated for sampling the conformational\n       space of a molecule without strong repulsive nonbonding interactions, try\n       to underestimate the thresholds at first instance and exclude bond\n       stretches and bending motions for the random manipuulations. Then compute\n       the forces projected on the nonbonding distance gradients. The distance\n       for which the absolute value of these gradients drops below 100 kJ/mol is\n       a coarse guess of a proper threshold value."
  },
  {
    "code": "def is_correct(self):\n        state = True\n        if self.members:\n            self.members = list(set(self.members))\n        if self.unknown_members:\n            for member in self.unknown_members:\n                msg = \"[%s::%s] as %s, got unknown member '%s'\" % (\n                    self.my_type, self.get_name(), self.__class__.my_type, member\n                )\n                self.add_error(msg)\n            state = False\n        return super(Itemgroup, self).is_correct() and state",
    "docstring": "Check if a group is valid.\n        Valid mean all members exists, so list of unknown_members is empty\n\n        :return: True if group is correct, otherwise False\n        :rtype: bool"
  },
  {
    "code": "def check_closed_streams(options):\n    if sys.version_info[0:3] >= (3, 6, 4):\n        return True\n    if sys.stderr is None:\n        sys.stderr = open(os.devnull, 'w')\n    if sys.stdin is None:\n        if options.input_file == '-':\n            print(\"Trying to read from stdin but stdin seems closed\", file=sys.stderr)\n            return False\n        sys.stdin = open(os.devnull, 'r')\n    if sys.stdout is None:\n        if options.output_file == '-':\n            print(\n                textwrap.dedent(\n                ),\n                file=sys.stderr,\n            )\n            return False\n        sys.stdout = open(os.devnull, 'w')\n    return True",
    "docstring": "Work around Python issue with multiprocessing forking on closed streams\n\n    https://bugs.python.org/issue28326\n\n    Attempting to a fork/exec a new Python process when any of std{in,out,err}\n    are closed or not flushable for some reason may raise an exception.\n    Fix this by opening devnull if the handle seems to be closed.  Do this\n    globally to avoid tracking places all places that fork.\n\n    Seems to be specific to multiprocessing.Process not all Python process\n    forkers.\n\n    The error actually occurs when the stream object is not flushable,\n    but replacing an open stream object that is not flushable with\n    /dev/null is a bad idea since it will create a silent failure.  Replacing\n    a closed handle with /dev/null seems safe."
  },
  {
    "code": "def _detect_notebook():\n    try:\n        from IPython import get_ipython\n        from ipykernel import zmqshell\n    except ImportError:\n        return False\n    kernel = get_ipython()\n    return isinstance(kernel, zmqshell.ZMQInteractiveShell)",
    "docstring": "This isn't 100% correct but seems good enough\n\n    Returns\n    -------\n    bool\n        True if it detects this is a notebook, otherwise False."
  },
  {
    "code": "async def set_dhw_setpoint(self, temperature,\n                               timeout=OTGW_DEFAULT_TIMEOUT):\n        cmd = OTGW_CMD_SET_WATER\n        status = {}\n        ret = await self._wait_for_cmd(cmd, temperature, timeout)\n        if ret is None:\n            return\n        ret = float(ret)\n        status[DATA_DHW_SETPOINT] = ret\n        self._update_status(status)\n        return ret",
    "docstring": "Set the domestic hot water setpoint. This command is only\n        available with boilers that support this function.\n        Return the newly accepted setpoint, or None on failure.\n\n        This method is a coroutine"
  },
  {
    "code": "def availableRoles(self):\n        eventRoles = self.eventrole_set.filter(capacity__gt=0)\n        if eventRoles.count() > 0:\n            return [x.role for x in eventRoles]\n        elif isinstance(self,Series):\n            return self.classDescription.danceTypeLevel.danceType.roles.all()\n        return []",
    "docstring": "Returns the set of roles for this event.  Since roles are not always custom specified for\n        event, this looks for the set of available roles in multiple places.  If no roles are found,\n        then the method returns an empty list, in which case it can be assumed that the event's registration\n        is not role-specific."
  },
  {
    "code": "def has_own_property(self, attr):\n        try:\n            object.__getattribute__(self, attr)\n        except AttributeError:\n            return False\n        else:\n            return True",
    "docstring": "Returns if the property"
  },
  {
    "code": "def compute_laplacian_matrix(affinity_matrix, method='auto', **kwargs):\n    if method == 'auto':\n        method = 'geometric'\n    return Laplacian.init(method, **kwargs).laplacian_matrix(affinity_matrix)",
    "docstring": "Compute the laplacian matrix with the given method"
  },
  {
    "code": "def _submit_rate(self, metric_name, val, metric, custom_tags=None, hostname=None):\n        _tags = self._metric_tags(metric_name, val, metric, custom_tags, hostname)\n        self.rate('{}.{}'.format(self.NAMESPACE, metric_name), val, _tags, hostname=hostname)",
    "docstring": "Submit a metric as a rate, additional tags provided will be added to\n        the ones from the label provided via the metrics object.\n\n        `custom_tags` is an array of 'tag:value' that will be added to the\n        metric when sending the rate to Datadog."
  },
  {
    "code": "def do_quit(self, arg):\n        for name, fh in self._backup:\n            setattr(sys, name, fh)\n        self.console.writeline('*** Aborting program ***\\n')\n        self.console.flush()\n        self.console.close()\n        WebPdb.active_instance = None\n        return Pdb.do_quit(self, arg)",
    "docstring": "quit || exit || q\n        Stop and quit the current debugging session"
  },
  {
    "code": "def force_bytes(value):\n    if IS_PY3:\n        if isinstance(value, str):\n            value = value.encode('utf-8', 'backslashreplace')\n    else:\n        if isinstance(value, unicode):\n            value = value.encode('utf-8')\n    return value",
    "docstring": "Forces a Unicode string to become a bytestring."
  },
  {
    "code": "def API520_B(Pset, Pback, overpressure=0.1):\n    r\n    gauge_backpressure = (Pback-atm)/(Pset-atm)*100\n    if overpressure not in [0.1, 0.16, 0.21]:\n        raise Exception('Only overpressure of 10%, 16%, or 21% are permitted')\n    if (overpressure == 0.1 and gauge_backpressure < 30) or (\n        overpressure == 0.16 and gauge_backpressure < 38) or (\n        overpressure == 0.21 and gauge_backpressure < 50):\n        return 1\n    elif gauge_backpressure > 50:\n        raise Exception('Gauge pressure must be < 50%')\n    if overpressure == 0.16:\n        Kb = interp(gauge_backpressure, Kb_16_over_x, Kb_16_over_y)\n    elif overpressure == 0.1:\n        Kb = interp(gauge_backpressure, Kb_10_over_x, Kb_10_over_y)\n    return Kb",
    "docstring": "r'''Calculates capacity correction due to backpressure on balanced\n    spring-loaded PRVs in vapor service. For pilot operated valves,\n    this is always 1. Applicable up to 50% of the percent gauge backpressure,\n    For use in API 520 relief valve sizing. 1D interpolation among a table with\n    53 backpressures is performed.\n\n    Parameters\n    ----------\n    Pset : float\n        Set pressure for relief [Pa]\n    Pback : float\n        Backpressure, [Pa]\n    overpressure : float, optional\n        The maximum fraction overpressure; one of 0.1, 0.16, or 0.21, []\n\n    Returns\n    -------\n    Kb : float\n        Correction due to vapor backpressure [-]\n\n    Notes\n    -----\n    If the calculated gauge backpressure is less than 30%, 38%, or 50% for\n    overpressures of 0.1, 0.16, or 0.21, a value of 1 is returned.\n\n    Percent gauge backpressure must be under 50%.\n\n    Examples\n    --------\n    Custom examples from figure 30:\n\n    >>> API520_B(1E6, 5E5)\n    0.7929945420944432\n\n    References\n    ----------\n    .. [1] API Standard 520, Part 1 - Sizing and Selection."
  },
  {
    "code": "def class_name(self, cls, parts=0, aliases=None):\n        module = cls.__module__\n        if module in ('__builtin__', 'builtins'):\n            fullname = cls.__name__\n        else:\n            fullname = '%s.%s' % (module, cls.__name__)\n        if parts == 0:\n            result = fullname\n        else:\n            name_parts = fullname.split('.')\n            result = '.'.join(name_parts[-parts:])\n        if aliases is not None and result in aliases:\n            return aliases[result]\n        return result",
    "docstring": "Given a class object, return a fully-qualified name.\n\n        This works for things I've tested in matplotlib so far, but may not be\n        completely general."
  },
  {
    "code": "def _rec_owner_number(self):\n        player = self._header.initial.players[self._header.replay.rec_player]\n        return player.attributes.player_color + 1",
    "docstring": "Get rec owner number."
  },
  {
    "code": "def check_classes(self, scope=-1):\n        for entry in self[scope].values():\n            if entry.class_ is None:\n                syntax_error(entry.lineno, \"Unknown identifier '%s'\" % entry.name)",
    "docstring": "Check if pending identifiers are defined or not. If not,\n        returns a syntax error. If no scope is given, the current\n        one is checked."
  },
  {
    "code": "def min_order_amount(self) -> Money:\n        return self._fetch('minimum order amount', self.market.code)(self._min_order_amount)()",
    "docstring": "Minimum amount to place an order."
  },
  {
    "code": "def parse_registries(filesystem, registries):\n    results = {}\n    for path in registries:\n        with NamedTemporaryFile(buffering=0) as tempfile:\n            filesystem.download(path, tempfile.name)\n            registry = RegistryHive(tempfile.name)\n            registry.rootkey = registry_root(path)\n            results.update({k.path: (k.timestamp, k.values)\n                            for k in registry.keys()})\n    return results",
    "docstring": "Returns a dictionary with the content of the given registry hives.\n\n    {\"\\\\Registry\\\\Key\\\\\", ((\"ValueKey\", \"ValueType\", ValueValue))}"
  },
  {
    "code": "async def add(ctx, left: int, right: int):\n    await ctx.send(left + right)",
    "docstring": "Adds two numbers together."
  },
  {
    "code": "def trie(self):\n        domain = 0\n        if domain not in self.domains:\n            self.register_domain(domain=domain)\n        return self.domains[domain].trie",
    "docstring": "A property to link into IntentEngine's trie.\n\n        warning:: this is only for backwards compatiblility and should not be used if you\n        intend on using domains.\n\n        Return: the domains trie from its IntentEngine"
  },
  {
    "code": "def PushSection(self, name, pre_formatters):\n        if name == '@':\n            value = self.stack[-1].context\n        else:\n            value = self.stack[-1].context.get(name)\n        for i, (f, args, formatter_type) in enumerate(pre_formatters):\n            if formatter_type == ENHANCED_FUNC:\n                value = f(value, self, args)\n            elif formatter_type == SIMPLE_FUNC:\n                value = f(value)\n            else:\n                assert False, 'Invalid formatter type %r' % formatter_type\n        self.stack.append(_Frame(value))\n        return value",
    "docstring": "Given a section name, push it on the top of the stack.\n\n    Returns:\n      The new section, or None if there is no such section."
  },
  {
    "code": "def pascal_row(n):\n    result = [1]\n    x, numerator = 1, n\n    for denominator in range(1, n // 2 + 1):\n        x *= numerator\n        x /= denominator\n        result.append(x)\n        numerator -= 1\n    if n & 1 == 0:\n        result.extend(reversed(result[:-1]))\n    else:\n        result.extend(reversed(result))\n    return result",
    "docstring": "Returns n-th row of Pascal's triangle"
  },
  {
    "code": "def list_datasources(self, source_id):\n        target_url = self.client.get_url('DATASOURCE', 'GET', 'multi', {'source_id': source_id})\n        return base.Query(self.client.get_manager(Datasource), target_url)",
    "docstring": "Filterable list of Datasources for a Source."
  },
  {
    "code": "def find_mappable(*axes):\n    for ax in axes:\n        for aset in ('collections', 'images'):\n            try:\n                return getattr(ax, aset)[-1]\n            except (AttributeError, IndexError):\n                continue\n    raise ValueError(\"Cannot determine mappable layer on any axes \"\n                     \"for this colorbar\")",
    "docstring": "Find the most recently added mappable layer in the given axes\n\n    Parameters\n    ----------\n    *axes : `~matplotlib.axes.Axes`\n        one or more axes to search for a mappable"
  },
  {
    "code": "def iter_links_param_element(cls, element):\n        valuetype = element.attrib.get('valuetype', '')\n        if valuetype.lower() == 'ref' and 'value' in element.attrib:\n            link_type = identify_link_type(element.attrib.get('value'))\n            yield LinkInfo(\n                element=element, tag=element.tag, attrib='value',\n                link=element.attrib.get('value'),\n                inline=True, linked=False,\n                base_link=None,\n                value_type='plain',\n                link_type=link_type\n            )",
    "docstring": "Iterate a ``param`` element."
  },
  {
    "code": "def get_all_names(self):\n        result = set()\n        for module in self.names:\n            result.update(set(self.names[module]))\n        return result",
    "docstring": "Return the list of all cached global names"
  },
  {
    "code": "def _get_insert_commands(self, rows, cols):\n        insert_queries = {}\n        for table in tqdm(list(rows.keys()), total=len(list(rows.keys())), desc='Getting insert rows queries'):\n            insert_queries[table] = {}\n            _rows = rows.pop(table)\n            _cols = cols.pop(table)\n            if len(_rows) > 1:\n                insert_queries[table]['insert_many'] = self.insert_many(table, _cols, _rows, execute=False)\n            elif len(_rows) == 1:\n                insert_queries[table]['insert'] = self.insert(table, _cols, _rows, execute=False)\n        return insert_queries",
    "docstring": "Retrieve dictionary of insert statements to be executed."
  },
  {
    "code": "def select_matchedfilter_class(curr_exe):\n    exe_to_class_map = {\n        'pycbc_inspiral'          : PyCBCInspiralExecutable,\n        'pycbc_inspiral_skymax'   : PyCBCInspiralExecutable,\n        'pycbc_multi_inspiral'    : PyCBCMultiInspiralExecutable,\n    }\n    try:\n        return exe_to_class_map[curr_exe]\n    except KeyError:\n        raise NotImplementedError(\n            \"No job class exists for executable %s, exiting\" % curr_exe)",
    "docstring": "This function returns a class that is appropriate for setting up\n    matched-filtering jobs within workflow.\n\n    Parameters\n    ----------\n    curr_exe : string\n        The name of the matched filter executable to be used.\n\n    Returns\n    --------\n    exe_class : Sub-class of pycbc.workflow.core.Executable that holds utility\n        functions appropriate for the given executable.  Instances of the class\n        ('jobs') **must** have methods\n        * job.create_node()\n        and\n        * job.get_valid_times(ifo, )"
  },
  {
    "code": "def survival_function_at_times(self, times, label=None):\n        label = coalesce(label, self._label)\n        return pd.Series(self._survival_function(self._fitted_parameters_, times), index=_to_array(times), name=label)",
    "docstring": "Return a Pandas series of the predicted survival value at specific times.\n\n        Parameters\n        -----------\n        times: iterable or float\n          values to return the survival function at.\n        label: string, optional\n          Rename the series returned. Useful for plotting.\n\n        Returns\n        --------\n        pd.Series"
  },
  {
    "code": "def fire(self, sender=None, **params):\r\n        keys = (_make_id(None), _make_id(sender))\r\n        results = []\r\n        for (_, key), callback in self.callbacks:\r\n            if key in keys:\r\n                results.append(callback(self, sender, **params))\r\n        return results",
    "docstring": "Fire callbacks from a ``sender``."
  },
  {
    "code": "def recpgr(body, rectan, re, f):\n    body = stypes.stringToCharP(body)\n    rectan = stypes.toDoubleVector(rectan)\n    re = ctypes.c_double(re)\n    f = ctypes.c_double(f)\n    lon = ctypes.c_double()\n    lat = ctypes.c_double()\n    alt = ctypes.c_double()\n    libspice.recpgr_c(body, rectan, re, f, ctypes.byref(lon), ctypes.byref(lat),\n                      ctypes.byref(alt))\n    return lon.value, lat.value, alt.value",
    "docstring": "Convert rectangular coordinates to planetographic coordinates.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/recpgr_c.html\n\n    :param body: Body with which coordinate system is associated.\n    :type body: str\n    :param rectan: Rectangular coordinates of a point.\n    :type rectan: 3-Element Array of floats\n    :param re: Equatorial radius of the reference spheroid.\n    :type re: float\n    :param f: Flattening coefficient.\n    :type f: float\n    :return:\n            Planetographic longitude (radians),\n            Planetographic latitude (radians),\n            Altitude above reference spheroid\n    :rtype: tuple"
  },
  {
    "code": "def DecoratorMixin(decorator):\n    class Mixin(object):\n        __doc__ = decorator.__doc__\n        @classmethod\n        def as_view(cls, *args, **kwargs):\n            view = super(Mixin, cls).as_view(*args, **kwargs)\n            return decorator(view)\n    Mixin.__name__ = str('DecoratorMixin(%s)' % decorator.__name__)\n    return Mixin",
    "docstring": "Converts a decorator written for a function view into a mixin for a\n    class-based view.\n\n    ::\n\n        LoginRequiredMixin = DecoratorMixin(login_required)\n\n        class MyView(LoginRequiredMixin):\n            pass\n\n        class SomeView(DecoratorMixin(some_decorator),\n                       DecoratorMixin(something_else)):\n            pass"
  },
  {
    "code": "def atlasdb_get_random_peer( con=None, path=None ):\n    ret = {}\n    with AtlasDBOpen(con=con, path=path) as dbcon:\n        num_peers = atlasdb_num_peers( con=con, path=path )\n        if num_peers is None or num_peers == 0:\n            ret['peer_hostport'] = None\n        else:\n            r = random.randint(1, num_peers)\n            sql = \"SELECT * FROM peers WHERE peer_index = ?;\"\n            args = (r,)\n            cur = dbcon.cursor()\n            res = atlasdb_query_execute( cur, sql, args )\n            ret = {'peer_hostport': None}\n            for row in res:\n                ret.update( row )\n                break\n    return ret['peer_hostport']",
    "docstring": "Select a peer from the db at random\n    Return None if the table is empty"
  },
  {
    "code": "def share_secret(threshold, nshares, secret, identifier, hash_id=Hash.SHA256):\n    if identifier is None:\n        raise TSSError('an identifier must be provided')\n    if not Hash.is_valid(hash_id):\n        raise TSSError('invalid hash algorithm %s' % hash_id)\n    secret = encode(secret)\n    identifier = encode(identifier)\n    if hash_id != Hash.NONE:\n        secret += Hash.to_func(hash_id)(secret).digest()\n    shares = generate_shares(threshold, nshares, secret)\n    header = format_header(identifier, hash_id, threshold, len(secret) + 1)\n    return [format_share(header, share) for share in shares]",
    "docstring": "Create nshares of the secret. threshold specifies the number of shares\n    needed for reconstructing the secret value. A 0-16 bytes identifier must\n    be provided. Optionally the secret is hashed with the algorithm specified\n    by hash_id, a class attribute of Hash.\n    This function must return a list of formatted shares or raises a TSSError\n    exception if anything went wrong."
  },
  {
    "code": "def send_location(self, latitude, longitude, **options):\n        return self.bot.api_call(\n            \"sendLocation\",\n            chat_id=self.id,\n            latitude=latitude,\n            longitude=longitude,\n            **options\n        )",
    "docstring": "Send a point on the map.\n\n        :param float latitude: Latitude of the location\n        :param float longitude: Longitude of the location\n        :param options: Additional sendLocation options (see\n            https://core.telegram.org/bots/api#sendlocation)"
  },
  {
    "code": "def check_id_idx_exclusivity(id, idx):\n    if (id is not None and idx is not None):\n        msg = (\"'id' and 'idx' fields can't both not be None,\" +\n               \" please specify subset in only one of these fields\")\n        logger.error(msg)\n        raise Exception(\"parse_gctx.check_id_idx_exclusivity: \" + msg)\n    elif id is not None:\n        return (\"id\", id)\n    elif idx is not None:\n        return (\"idx\", idx)\n    else:\n        return (None, [])",
    "docstring": "Makes sure user didn't provide both ids and idx values to subset by.\n\n    Input:\n        - id (list or None): if not None, a list of string id names\n        - idx (list or None): if not None, a list of integer id indexes\n\n    Output:\n        - a tuple: first element is subset type, second is subset content"
  },
  {
    "code": "def c_transform_entropic(b, M, reg, beta):\n    n_source = np.shape(M)[0]\n    alpha = np.zeros(n_source)\n    for i in range(n_source):\n        r = M[i, :] - beta\n        min_r = np.min(r)\n        exp_beta = np.exp(-(r - min_r) / reg) * b\n        alpha[i] = min_r - reg * np.log(np.sum(exp_beta))\n    return alpha",
    "docstring": "The goal is to recover u from the c-transform.\n\n    The function computes the c_transform of a dual variable from the other\n    dual variable:\n\n    .. math::\n        u = v^{c,reg} = -reg \\sum_j exp((v - M)/reg) b_j\n\n    Where :\n\n    - M is the (ns,nt) metric cost matrix\n    - u, v are dual variables in R^IxR^J\n    - reg is the regularization term\n\n    It is used to recover an optimal u from optimal v solving the semi dual\n    problem, see Proposition 2.1 of [18]_\n\n\n    Parameters\n    ----------\n\n    b : np.ndarray(nt,)\n        target measure\n    M : np.ndarray(ns, nt)\n        cost matrix\n    reg : float\n        regularization term > 0\n    v : np.ndarray(nt,)\n        dual variable\n\n    Returns\n    -------\n\n    u : np.ndarray(ns,)\n        dual variable\n\n    Examples\n    --------\n\n    >>> n_source = 7\n    >>> n_target = 4\n    >>> reg = 1\n    >>> numItermax = 300000\n    >>> a = ot.utils.unif(n_source)\n    >>> b = ot.utils.unif(n_target)\n    >>> rng = np.random.RandomState(0)\n    >>> X_source = rng.randn(n_source, 2)\n    >>> Y_target = rng.randn(n_target, 2)\n    >>> M = ot.dist(X_source, Y_target)\n    >>> method = \"ASGD\"\n    >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,\n                                                      method, numItermax)\n    >>> print(asgd_pi)\n\n    References\n    ----------\n\n    [Genevay et al., 2016] :\n                    Stochastic Optimization for Large-scale Optimal Transport,\n                     Advances in Neural Information Processing Systems (2016),\n                      arXiv preprint arxiv:1605.08527."
  },
  {
    "code": "def set_mode_auto(self):\n        if self.mavlink10():\n            self.mav.command_long_send(self.target_system, self.target_component,\n                                       mavlink.MAV_CMD_MISSION_START, 0, 0, 0, 0, 0, 0, 0, 0)\n        else:\n            MAV_ACTION_SET_AUTO = 13\n            self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_SET_AUTO)",
    "docstring": "enter auto mode"
  },
  {
    "code": "def add_load_constant(self, name, output_name, constant_value, shape):\n        spec = self.spec\n        nn_spec = self.nn_spec\n        spec_layer = nn_spec.layers.add()\n        spec_layer.name = name\n        spec_layer.output.append(output_name)\n        spec_layer_params = spec_layer.loadConstant\n        data = spec_layer_params.data\n        data.floatValue.extend(map(float, constant_value.flatten()))\n        spec_layer_params.shape.extend(shape)\n        if len(data.floatValue) != np.prod(shape):\n            raise ValueError(\"Dimensions of 'shape' do not match the size of the provided constant\")\n        if len(shape) != 3:\n            raise ValueError(\"'shape' must be of length 3\")",
    "docstring": "Add a load constant layer.\n\n        Parameters\n        ----------\n        name: str\n            The name of this layer.\n\n        output_name: str\n            The output blob name of this layer.\n\n        constant_value: numpy.array\n            value of the constant as a numpy array.\n\n        shape: [int]\n            List of ints representing the shape of the constant. Must be of length 3: [C,H,W]\n\n\n        See Also\n        --------\n        add_elementwise"
  },
  {
    "code": "def is_evalframeex(self):\n        if self._gdbframe.name() == 'PyEval_EvalFrameEx':\n            if self._gdbframe.type() == gdb.NORMAL_FRAME:\n                return True\n        return False",
    "docstring": "Is this a PyEval_EvalFrameEx frame?"
  },
  {
    "code": "def get_window_size(window):\n    width_value = ctypes.c_int(0)\n    width = ctypes.pointer(width_value)\n    height_value = ctypes.c_int(0)\n    height = ctypes.pointer(height_value)\n    _glfw.glfwGetWindowSize(window, width, height)\n    return width_value.value, height_value.value",
    "docstring": "Retrieves the size of the client area of the specified window.\n\n    Wrapper for:\n        void glfwGetWindowSize(GLFWwindow* window, int* width, int* height);"
  },
  {
    "code": "def get_remote_content(filepath):\n        with hide('running'):\n            temp = BytesIO()\n            get(filepath, temp)\n            content = temp.getvalue().decode('utf-8')\n        return content.strip()",
    "docstring": "A handy wrapper to get a remote file content"
  },
  {
    "code": "def shawn_text(self):\n        if len(self._shawn_text) == len(self):\n            return self._shawn_text\n        if self.style == self.DOTS:\n            return chr(0x2022) * len(self)\n        ranges = [\n            (902, 1366),\n            (192, 683),\n            (33, 122)\n        ]\n        s = ''\n        while len(s) < len(self.text):\n            apolo = randint(33, 1366)\n            for a, b in ranges:\n                if a <= apolo <= b:\n                    s += chr(apolo)\n                    break\n        self._shawn_text = s\n        return s",
    "docstring": "The text displayed instead of the real one."
  },
  {
    "code": "def set_computer_desc(desc=None):\n    if six.PY2:\n        desc = _to_unicode(desc)\n    system_info = win32net.NetServerGetInfo(None, 101)\n    if desc is None:\n        return False\n    system_info['comment'] = desc\n    try:\n        win32net.NetServerSetInfo(None, 101, system_info)\n    except win32net.error as exc:\n        (number, context, message) = exc.args\n        log.error('Failed to update system')\n        log.error('nbr: %s', number)\n        log.error('ctx: %s', context)\n        log.error('msg: %s', message)\n        return False\n    return {'Computer Description': get_computer_desc()}",
    "docstring": "Set the Windows computer description\n\n    Args:\n\n        desc (str):\n            The computer description\n\n    Returns:\n        str: Description if successful, otherwise ``False``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!'"
  },
  {
    "code": "def make_jagged_equity_info(num_assets,\n                            start_date,\n                            first_end,\n                            frequency,\n                            periods_between_ends,\n                            auto_close_delta):\n    frame = pd.DataFrame(\n        {\n            'symbol': [chr(ord('A') + i) for i in range(num_assets)],\n            'start_date': start_date,\n            'end_date': pd.date_range(\n                first_end,\n                freq=(periods_between_ends * frequency),\n                periods=num_assets,\n            ),\n            'exchange': 'TEST',\n        },\n        index=range(num_assets),\n    )\n    if auto_close_delta is not None:\n        frame['auto_close_date'] = frame['end_date'] + auto_close_delta\n    return frame",
    "docstring": "Create a DataFrame representing assets that all begin at the same start\n    date, but have cascading end dates.\n\n    Parameters\n    ----------\n    num_assets : int\n        How many assets to create.\n    start_date : pd.Timestamp\n        The start date for all the assets.\n    first_end : pd.Timestamp\n        The date at which the first equity will end.\n    frequency : str or pd.tseries.offsets.Offset (e.g. trading_day)\n        Frequency used to interpret the next argument.\n    periods_between_ends : int\n        Starting after the first end date, end each asset every\n        `frequency` * `periods_between_ends`.\n\n    Returns\n    -------\n    info : pd.DataFrame\n        DataFrame representing newly-created assets."
  },
  {
    "code": "def glance(self, nitems=5):\n        nitems = max([1, min([nitems, self.num_samples - 1])])\n        return self.__take(nitems, iter(self.__data.items()))",
    "docstring": "Quick and partial glance of the data matrix.\n\n        Parameters\n        ----------\n        nitems : int\n            Number of items to glance from the dataset.\n            Default : 5\n\n        Returns\n        -------\n        dict"
  },
  {
    "code": "def virtual_media(self):\n        return virtual_media.VirtualMediaCollection(\n            self._conn, utils.get_subresource_path_by(self, 'VirtualMedia'),\n            redfish_version=self.redfish_version)",
    "docstring": "Property to provide reference to `VirtualMediaCollection` instance.\n\n        It is calculated once when the first time it is queried. On refresh,\n        this property gets reset."
  },
  {
    "code": "def reset_rf_samples():\n    forest._generate_sample_indices = (lambda rs, n_samples:\n        forest.check_random_state(rs).randint(0, n_samples, n_samples))",
    "docstring": "Undoes the changes produced by set_rf_samples."
  },
  {
    "code": "def close(self):\n        if self._con:\n            self._pool.unshare(self._shared_con)\n            self._shared_con = self._con = None",
    "docstring": "Close the pooled shared connection."
  },
  {
    "code": "def rvpl(self, prompt, error='Entered value is invalid', intro=None,\n             validator=lambda x: x != '', clean=lambda x: x.strip(),\n             strict=True, default=None):\n        if intro:\n            self.pstd(utils.rewrap_long(intro))\n        val = self.read(prompt, clean)\n        while not validator(val):\n            if not strict:\n                return default\n            if hasattr(error, '__call__'):\n                self.perr(error(val))\n            else:\n                self.perr(error)\n            val = self.read(prompt, clean)\n        return val",
    "docstring": "Start a read-validate-print loop\n\n        The RVPL will read the user input, validate it, and loop until the\n        entered value passes the validation, then return it.\n\n        Error message can be customized using the ``error`` argument. If the\n        value is a callable, it will be called with the value and it will be\n        expected to return a printable message. Exceptions raised by the\n        ``error`` function are not trapped.\n\n        When ``intro`` is passed, it is printed above the prompt.\n\n        The ``validator`` argument is is a function that validates the user\n        input. Default validator simply validates if user entered any value.\n\n        The ``clean`` argument specifies a function for the ``read()`` method\n        with the same semantics."
  },
  {
    "code": "def matrix2cube(data_matrix, im_shape):\n    r\n    return data_matrix.T.reshape([data_matrix.shape[1]] + list(im_shape))",
    "docstring": "r\"\"\"Matrix to Cube\n\n    This method transforms a 2D matrix to a 3D cube\n\n    Parameters\n    ----------\n    data_matrix : np.ndarray\n        Input data cube, 2D array\n    im_shape : tuple\n        2D shape of the individual images\n\n    Returns\n    -------\n    np.ndarray 3D cube\n\n    Examples\n    --------\n    >>> from modopt.base.transform import matrix2cube\n    >>> a = np.array([[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14],\n    [3, 7, 11, 15]])\n    >>> matrix2cube(a, (2, 2))\n    array([[[ 0,  1],\n            [ 2,  3]],\n\n           [[ 4,  5],\n            [ 6,  7]],\n\n           [[ 8,  9],\n            [10, 11]],\n\n           [[12, 13],\n            [14, 15]]])"
  },
  {
    "code": "def pipeline_name(self):\n        if 'pipeline_name' in self.data:\n            return self.data.get('pipeline_name')\n        elif self.pipeline is not None:\n            return self.pipeline.data.name",
    "docstring": "Get pipeline name of current stage instance.\n\n        Because instantiating stage instance could be performed in different ways and those return different results,\n        we have to check where from to get name of the pipeline.\n\n        :return: pipeline name."
  },
  {
    "code": "def load(fname: str) -> 'Config':\n        with open(fname) as inp:\n            obj = yaml.load(inp)\n            obj.__add_frozen()\n            return obj",
    "docstring": "Returns a Config object loaded from a file. The loaded object is not frozen.\n\n        :param fname: Name of file to load the Config from.\n        :return: Configuration."
  },
  {
    "code": "def parse_port_from_tensorboard_output(tensorboard_output: str) -> int:\n    search = re.search(\"at http://[^:]+:([0-9]+)\", tensorboard_output)\n    if search is not None:\n        port = search.group(1)\n        return int(port)\n    else:\n        raise UnexpectedOutputError(tensorboard_output, \"Address and port where Tensorboard has started,\"\n                                                        \" e.g. TensorBoard 1.8.0 at http://martin-VirtualBox:36869\")",
    "docstring": "Parse tensorboard port from its outputted message.\n\n    :param tensorboard_output: Output message of Tensorboard\n    in format TensorBoard 1.8.0 at http://martin-VirtualBox:36869\n    :return: Returns the port TensorBoard is listening on.\n    :raise UnexpectedOutputError"
  },
  {
    "code": "def from_cli(cls, opt):\n        injection_file = opt.injection_file\n        chirp_time_window = \\\n            opt.injection_filter_rejector_chirp_time_window\n        match_threshold = opt.injection_filter_rejector_match_threshold\n        coarsematch_deltaf = opt.injection_filter_rejector_coarsematch_deltaf\n        coarsematch_fmax = opt.injection_filter_rejector_coarsematch_fmax\n        seg_buffer = opt.injection_filter_rejector_seg_buffer\n        if opt.injection_filter_rejector_f_lower is not None:\n            f_lower = opt.injection_filter_rejector_f_lower\n        else:\n            f_lower = opt.low_frequency_cutoff\n        return cls(injection_file, chirp_time_window, match_threshold,\n                   f_lower, coarsematch_deltaf=coarsematch_deltaf,\n                   coarsematch_fmax=coarsematch_fmax,\n                   seg_buffer=seg_buffer)",
    "docstring": "Create an InjFilterRejector instance from command-line options."
  },
  {
    "code": "def to_FIB(self, other):\n        if not isinstance(other, GroundedFunctionNetwork):\n            raise TypeError(\n                f\"Expected GroundedFunctionNetwork, but got {type(other)}\"\n            )\n        def shortname(var):\n            return var[var.find(\"::\") + 2 : var.rfind(\"_\")]\n        def shortname_vars(graph, shortname):\n            return [v for v in graph.nodes() if shortname in v]\n        this_var_nodes = [\n            shortname(n)\n            for (n, d) in self.nodes(data=True)\n            if d[\"type\"] == \"variable\"\n        ]\n        other_var_nodes = [\n            shortname(n)\n            for (n, d) in other.nodes(data=True)\n            if d[\"type\"] == \"variable\"\n        ]\n        shared_vars = set(this_var_nodes).intersection(set(other_var_nodes))\n        full_shared_vars = {\n            full_var\n            for shared_var in shared_vars\n            for full_var in shortname_vars(self, shared_var)\n        }\n        return ForwardInfluenceBlanket(self, full_shared_vars)",
    "docstring": "Creates a ForwardInfluenceBlanket object representing the\n        intersection of this model with the other input model.\n\n        Args:\n            other: The GroundedFunctionNetwork object to compare this model to.\n\n        Returns:\n            A ForwardInfluenceBlanket object to use for model comparison."
  },
  {
    "code": "def _make_cache_key(key_prefix):\n    if callable(key_prefix):\n        cache_key = key_prefix()\n    elif '%s' in key_prefix:\n        cache_key = key_prefix % request.path\n    else:\n        cache_key = key_prefix\n    cache_key = cache_key.encode('utf-8')\n    return cache_key",
    "docstring": "Make cache key from prefix\n    Borrowed from Flask-Cache extension"
  },
  {
    "code": "def communicate(args):\n  if args.local:\n    raise ValueError(\"The communicate command can only be used without the '--local' command line option\")\n  jm = setup(args)\n  jm.communicate(job_ids=get_ids(args.job_ids))",
    "docstring": "Uses qstat to get the status of the requested jobs."
  },
  {
    "code": "def from_json(json):\n        segments = [Segment.from_json(s) for s in json['segments']]\n        return Track(json['name'], segments).compute_metrics()",
    "docstring": "Creates a Track from a JSON file.\n\n        No preprocessing is done.\n\n        Arguments:\n            json: map with the keys: name (optional) and segments.\n        Return:\n            A track instance"
  },
  {
    "code": "def render_child(self, child, view_name=None, context=None):\n        return child.render(view_name or self._view_name, context)",
    "docstring": "A shortcut to render a child block.\n\n        Use this method to render your children from your own view function.\n\n        If `view_name` is not provided, it will default to the view name you're\n        being rendered with.\n\n        Returns the same value as :func:`render`."
  },
  {
    "code": "def create_ondemand_instances(ec2, image_id, spec, num_instances=1):\n    instance_type = spec['instance_type']\n    log.info('Creating %s instance(s) ... ', instance_type)\n    for attempt in retry_ec2(retry_for=a_long_time,\n                             retry_while=inconsistencies_detected):\n        with attempt:\n            return ec2.run_instances(image_id,\n                                     min_count=num_instances,\n                                     max_count=num_instances,\n                                     **spec).instances",
    "docstring": "Requests the RunInstances EC2 API call but accounts for the race between recently created\n    instance profiles, IAM roles and an instance creation that refers to them.\n\n    :rtype: list[Instance]"
  },
  {
    "code": "def list_corpus_files(dotted_path):\n    corpus_path = get_file_path(dotted_path, extension=CORPUS_EXTENSION)\n    paths = []\n    if os.path.isdir(corpus_path):\n        paths = glob.glob(corpus_path + '/**/*.' + CORPUS_EXTENSION, recursive=True)\n    else:\n        paths.append(corpus_path)\n    paths.sort()\n    return paths",
    "docstring": "Return a list of file paths to each data file in the specified corpus."
  },
  {
    "code": "def fit_effective_mass(distances, energies, parabolic=True):\n    if parabolic:\n        fit = np.polyfit(distances, energies, 2)\n        c = 2 * fit[0]\n    else:\n        def f(x, alpha, d):\n            top = np.sqrt(4 * alpha * d * x**2 + 1) - 1\n            bot = 2 * alpha\n            return top / bot\n        bounds = ((1e-8, -np.inf), (np.inf, np.inf))\n        popt, _ = curve_fit(f, distances, energies, p0=[1., 1.],\n                            bounds=bounds)\n        c = 2 * popt[1]\n    eff_mass = (angstrom_to_bohr**2 / eV_to_hartree) / c\n    return eff_mass",
    "docstring": "Fit the effective masses using either a parabolic or nonparabolic fit.\n\n    Args:\n        distances (:obj:`numpy.ndarray`): The x-distances between k-points in\n            reciprocal Angstroms, normalised to the band extrema.\n        energies (:obj:`numpy.ndarray`): The band eigenvalues normalised to the\n            eigenvalue of the band extrema.\n        parabolic (:obj:`bool`, optional): Use a parabolic fit of the band\n            edges. If ``False`` then nonparabolic fitting will be attempted.\n            Defaults to ``True``.\n\n    Returns:\n        float: The effective mass in units of electron rest mass, :math:`m_0`."
  },
  {
    "code": "def tokens(self, tokenset='internal'):\n        toks = self.get('tokens', {}).get(tokenset)\n        if toks is not None:\n            if isinstance(toks, stringtypes):\n                toks = YyTokenLattice.from_string(toks)\n            elif isinstance(toks, Sequence):\n                toks = YyTokenLattice.from_list(toks)\n        return toks",
    "docstring": "Deserialize and return a YyTokenLattice object for the\n        initial or internal token set, if provided, from the YY\n        format or the JSON-formatted data; otherwise return the\n        original string.\n\n        Args:\n            tokenset (str): return `'initial'` or `'internal'` tokens\n                (default: `'internal'`)\n        Returns:\n            :class:`YyTokenLattice`"
  },
  {
    "code": "def maybe_add_child(self, fcoord):\n        if fcoord not in self.children:\n            new_position = self.position.play_move(\n                coords.from_flat(fcoord))\n            self.children[fcoord] = MCTSNode(\n                new_position, fmove=fcoord, parent=self)\n        return self.children[fcoord]",
    "docstring": "Adds child node for fcoord if it doesn't already exist, and returns it."
  },
  {
    "code": "def list_virtual(hostname, username, password, name):\n    ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}\n    if __opts__['test']:\n        return _test_output(ret, 'list', params={\n            'hostname': hostname,\n            'username': username,\n            'password': password,\n            'name': name\n        }\n        )\n    response = __salt__['bigip.list_virtual'](hostname, username, password, name)\n    return _load_result(response, ret)",
    "docstring": "A function to list a specific virtual.\n\n    hostname\n        The host/address of the bigip device\n    username\n        The iControl REST username\n    password\n        The iControl REST password\n    name\n        The name of the virtual to list"
  },
  {
    "code": "def stop(self, *args, **kwargs):\n        warnings.warn(\n            \"The 'stop()' method is deprecated, please use 'remove()' instead\", DeprecationWarning\n        )\n        return self.remove(*args, **kwargs)",
    "docstring": "Deprecated function to |remove| an existing handler.\n\n        Warnings\n        --------\n        .. deprecated:: 0.2.2\n          ``stop()`` will be removed in Loguru 1.0.0, it is replaced by ``remove()`` which is a less\n          confusing name."
  },
  {
    "code": "def update_index(entries):\n    context = GLOBAL_TEMPLATE_CONTEXT.copy()\n    context['entries'] = entries\n    context['last_build'] = datetime.datetime.now().strftime(\n        \"%Y-%m-%dT%H:%M:%SZ\")\n    list(map(lambda x: _render(context, x[0],\n                               os.path.join(CONFIG['output_to'], x[1])),\n             (('entry_index.html', 'index.html'), ('atom.xml', 'atom.xml'))))",
    "docstring": "find the last 10 entries in the database and create the main\n    page.\n    Each entry in has an doc_id, so we only get the last 10 doc_ids.\n\n    This method also updates the ATOM feed."
  },
  {
    "code": "def filter_pages(pages, pagenum, pagename):\n    if pagenum:\n        try:\n            pages = [list(pages)[pagenum - 1]]\n        except IndexError:\n            raise IndexError('Invalid page number: %d' % pagenum)\n    if pagename:\n        pages = [page for page in pages if page.name == pagename]\n        if pages == []:\n            raise IndexError('Page not found: pagename=%s' % pagename)\n    return pages",
    "docstring": "Choices pages by pagenum and pagename"
  },
  {
    "code": "def convert_dedent(self):\n        if self.indent_amounts:\n            self.indent_amounts.pop()\n        tokenum = INDENT\n        last_indent = 0\n        if self.indent_amounts:\n            last_indent = self.indent_amounts[-1]\n        while self.result[-1][0] == INDENT:\n            self.result.pop()\n        value = self.indent_type * last_indent\n        return tokenum, value",
    "docstring": "Convert a dedent into an indent"
  },
  {
    "code": "def pday(dayfmt):\n\tyear, month, day = map(int, dayfmt.split('-'))\n\treturn '{day} the {number}'.format(\n\t\tday=calendar.day_name[calendar.weekday(year, month, day)],\n\t\tnumber=inflect.engine().ordinal(day),\n\t)",
    "docstring": "P the day\n\n\t>>> print(pday('2012-08-24'))\n\tFriday the 24th"
  },
  {
    "code": "def config_dict(name: str) -> Dict[str, Any]:\n    try:\n        content = resource_string(PACKAGE, DATADIR.format(name)).decode()\n    except DistributionNotFound as error:\n        LOGGER.warning(\"Cannot load %s from packages: %s\", name, error)\n        content = DATA_FALLBACK.joinpath(name).read_text()\n    return cast(Dict[str, Any], json.loads(content))",
    "docstring": "Load a JSON configuration dict from Guesslang config directory.\n\n    :param name: the JSON file name.\n    :return: configuration"
  },
  {
    "code": "def get_flair_list(self, subreddit, *args, **kwargs):\n        url = self.config['flairlist'].format(\n            subreddit=six.text_type(subreddit))\n        return self.get_content(url, *args, root_field=None,\n                                thing_field='users', after_field='next',\n                                **kwargs)",
    "docstring": "Return a get_content generator of flair mappings.\n\n        :param subreddit: Either a Subreddit object or the name of the\n            subreddit to return the flair list for.\n\n        The additional parameters are passed directly into\n        :meth:`.get_content`. Note: the `url`, `root_field`, `thing_field`, and\n        `after_field` parameters cannot be altered."
  },
  {
    "code": "def refineData(root, options):\n    worker = root.worker\n    job = root.jobs\n    jobTypesTree = root.job_types\n    jobTypes = []\n    for childName in jobTypesTree:\n        jobTypes.append(jobTypesTree[childName])\n    return root, worker, job, jobTypes",
    "docstring": "walk down from the root and gather up the important bits."
  },
  {
    "code": "def _iter_vars(mod):\n    vars = sorted(var for var in dir(mod) if _is_public(var))\n    for var in vars:\n        yield getattr(mod, var)",
    "docstring": "Iterate through a list of variables define in a module's\n    public namespace."
  },
  {
    "code": "def complete_invoice(self, invoice_id, complete_dict):\n        return self._create_put_request(\n            resource=INVOICES,\n            billomat_id=invoice_id,\n            command=COMPLETE,\n            send_data=complete_dict\n        )",
    "docstring": "Completes an invoice\n\n        :param complete_dict: the complete dict with the template id\n        :param invoice_id: the invoice id\n        :return: Response"
  },
  {
    "code": "def attach_keypress(fig, scaling=1.1):\n    def press(event):\n        if event.key == 'q':\n            plt.close(fig)\n        elif event.key == 'e':\n            fig.set_size_inches(scaling * fig.get_size_inches(), forward=True)\n        elif event.key == 'c':\n            fig.set_size_inches(fig.get_size_inches() / scaling, forward=True)\n    if not hasattr(fig, '_sporco_keypress_cid'):\n        cid = fig.canvas.mpl_connect('key_press_event', press)\n        fig._sporco_keypress_cid = cid\n    return press",
    "docstring": "Attach a key press event handler that configures keys for closing a\n    figure and changing the figure size. Keys 'e' and 'c' respectively\n    expand and contract the figure, and key 'q' closes it.\n\n    **Note:** Resizing may not function correctly with all matplotlib\n    backends (a\n    `bug <https://github.com/matplotlib/matplotlib/issues/10083>`__\n    has been reported).\n\n    Parameters\n    ----------\n    fig : :class:`matplotlib.figure.Figure` object\n        Figure to which event handling is to be attached\n   scaling : float, optional (default 1.1)\n      Scaling factor for figure size changes\n\n    Returns\n    -------\n    press : function\n      Key press event handler function"
  },
  {
    "code": "def cat(*wizards):\n    data = {}\n    for wizard in wizards:\n        try:\n            response = None\n            while True:\n                response = yield wizard.send(response)\n        except Success as s:\n            data.update(s.data)\n    raise Success(data)",
    "docstring": "A higher-order wizard which is the concatenation of a number of other\n    wizards.\n\n    The resulting data is the union of all wizard outputs."
  },
  {
    "code": "def _delete_device(device):\n    log.trace('Deleting device with type %s', type(device))\n    device_spec = vim.vm.device.VirtualDeviceSpec()\n    device_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.remove\n    device_spec.device = device\n    return device_spec",
    "docstring": "Returns a vim.vm.device.VirtualDeviceSpec specifying to remove a virtual\n    machine device\n\n    device\n        Device data type object"
  },
  {
    "code": "def first(self, skipna=None, keep_attrs=None):\n        return self._first_or_last(duck_array_ops.first, skipna, keep_attrs)",
    "docstring": "Return the first element of each group along the group dimension"
  },
  {
    "code": "def get_lowest_probable_prepared_certificate_in_view(\n            self, view_no) -> Optional[int]:\n        seq_no_pp = SortedList()\n        seq_no_p = set()\n        for (v, p) in self.prePreparesPendingPrevPP:\n            if v == view_no:\n                seq_no_pp.add(p)\n            if v > view_no:\n                break\n        for (v, p), pr in self.preparesWaitingForPrePrepare.items():\n            if v == view_no and len(pr) >= self.quorums.prepare.value:\n                seq_no_p.add(p)\n        for n in seq_no_pp:\n            if n in seq_no_p:\n                return n\n        return None",
    "docstring": "Return lowest pp_seq_no of the view for which can be prepared but\n        choose from unprocessed PRE-PREPAREs and PREPAREs."
  },
  {
    "code": "def urlencode(resource):\n    if isinstance(resource, str):\n        return _urlencode(resource.encode('utf-8'))\n    return _urlencode(resource)",
    "docstring": "This implementation of urlencode supports all unicode characters\n\n    :param: resource: Resource value to be url encoded."
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'corpora' in _dict:\n            args['corpora'] = [\n                Corpus._from_dict(x) for x in (_dict.get('corpora'))\n            ]\n        else:\n            raise ValueError(\n                'Required property \\'corpora\\' not present in Corpora JSON')\n        return cls(**args)",
    "docstring": "Initialize a Corpora object from a json dictionary."
  },
  {
    "code": "def real(self, newreal):\n        try:\n            iter(newreal)\n        except TypeError:\n            for part in self.parts:\n                part.real = newreal\n            return\n        if self.space.is_power_space:\n            try:\n                for part in self.parts:\n                    part.real = newreal\n            except (ValueError, TypeError):\n                for part, new_re in zip(self.parts, newreal):\n                    part.real = new_re\n                pass\n        elif len(newreal) == len(self):\n            for part, new_re in zip(self.parts, newreal):\n                part.real = new_re\n        else:\n            raise ValueError(\n                'dimensions of the new real part does not match the space, '\n                'got element {} to set real part of {}'.format(newreal, self))",
    "docstring": "Setter for the real part.\n\n        This method is invoked by ``x.real = other``.\n\n        Parameters\n        ----------\n        newreal : array-like or scalar\n            Values to be assigned to the real part of this element."
  },
  {
    "code": "def check_address(address):\n    if not check_string(address, min_length=26, max_length=35, pattern=OP_ADDRESS_PATTERN):\n        return False\n    try:\n        keylib.b58check_decode(address)\n        return True\n    except:\n        return False",
    "docstring": "verify that a string is a base58check address\n\n    >>> check_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg')\n    True\n    >>> check_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJh')\n    False\n    >>> check_address('mkkJsS22dnDJhD8duFkpGnHNr9uz3JEcWu')\n    True\n    >>> check_address('mkkJsS22dnDJhD8duFkpGnHNr9uz3JEcWv')\n    False\n    >>> check_address('MD8WooqTKmwromdMQfSNh8gPTPCSf8KaZj')\n    True\n    >>> check_address('SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2i')\n    True\n    >>> check_address('SSXMcDiCZ7yFSQSUj7mWzmDcdwYhq97p2j')\n    False\n    >>> check_address('16SuThrz')\n    False\n    >>> check_address('1TGKrgtrQjgoPjoa5BnUZ9Qu')\n    False\n    >>> check_address('1LPckRbeTfLjzrfTfnCtP7z2GxFTpZLafXi')\n    True"
  },
  {
    "code": "def removeFriend(self, friend_id=None):\n        payload = {\"friend_id\": friend_id, \"unref\": \"none\", \"confirm\": \"Confirm\"}\n        r = self._post(self.req_url.REMOVE_FRIEND, payload)\n        query = parse_qs(urlparse(r.url).query)\n        if \"err\" not in query:\n            log.debug(\"Remove was successful!\")\n            return True\n        else:\n            log.warning(\"Error while removing friend\")\n            return False",
    "docstring": "Removes a specifed friend from your friend list\n\n        :param friend_id: The ID of the friend that you want to remove\n        :return: Returns error if the removing was unsuccessful, returns True when successful."
  },
  {
    "code": "def write(nodes, output=sys.stdout, fmt='%.7E', gml=True, xmlns=None):\n    root = Node('nrml', nodes=nodes)\n    namespaces = {xmlns or NRML05: ''}\n    if gml:\n        namespaces[GML_NAMESPACE] = 'gml:'\n    with floatformat(fmt):\n        node_to_xml(root, output, namespaces)\n    if hasattr(output, 'mode') and '+' in output.mode:\n        output.seek(0)\n        read(output)",
    "docstring": "Convert nodes into a NRML file. output must be a file\n    object open in write mode. If you want to perform a\n    consistency check, open it in read-write mode, then it will\n    be read after creation and validated.\n\n    :params nodes: an iterable over Node objects\n    :params output: a file-like object in write or read-write mode\n    :param fmt: format used for writing the floats (default '%.7E')\n    :param gml: add the http://www.opengis.net/gml namespace\n    :param xmlns: NRML namespace like http://openquake.org/xmlns/nrml/0.4"
  },
  {
    "code": "def paragraph_spans(self):\n        if not self.is_tagged(PARAGRAPHS):\n            self.tokenize_paragraphs()\n        return self.spans(PARAGRAPHS)",
    "docstring": "The list of spans representing ``paragraphs`` layer elements."
  },
  {
    "code": "def layer_postprocess(layer_input, layer_output, hparams):\n  return layer_prepostprocess(\n      layer_input,\n      layer_output,\n      sequence=hparams.layer_postprocess_sequence,\n      dropout_rate=hparams.layer_prepostprocess_dropout,\n      norm_type=hparams.norm_type,\n      depth=None,\n      epsilon=hparams.norm_epsilon,\n      dropout_broadcast_dims=comma_separated_string_to_integer_list(\n          getattr(hparams, \"layer_prepostprocess_dropout_broadcast_dims\", \"\")),\n      default_name=\"layer_postprocess\")",
    "docstring": "Apply layer postprocessing.\n\n  See layer_prepostprocess() for details.\n\n  A hyperparameters object is passed for convenience.  The hyperparameters\n  that may be used are:\n\n    layer_postprocess_sequence\n    layer_prepostprocess_dropout\n    norm_type\n    hidden_size\n    norm_epsilon\n\n  Args:\n    layer_input: a Tensor\n    layer_output: a Tensor\n    hparams: a hyperparameters object.\n\n  Returns:\n    a Tensor"
  },
  {
    "code": "def _inherit_from(context, uri, calling_uri):\n    if uri is None:\n        return None\n    template = _lookup_template(context, uri, calling_uri)\n    self_ns = context['self']\n    ih = self_ns\n    while ih.inherits is not None:\n        ih = ih.inherits\n    lclcontext = context._locals({'next': ih})\n    ih.inherits = TemplateNamespace(\"self:%s\" % template.uri,\n                                lclcontext,\n                                template=template,\n                                populate_self=False)\n    context._data['parent'] = lclcontext._data['local'] = ih.inherits\n    callable_ = getattr(template.module, '_mako_inherit', None)\n    if callable_ is not None:\n        ret = callable_(template, lclcontext)\n        if ret:\n            return ret\n    gen_ns = getattr(template.module, '_mako_generate_namespaces', None)\n    if gen_ns is not None:\n        gen_ns(context)\n    return (template.callable_, lclcontext)",
    "docstring": "called by the _inherit method in template modules to set\n    up the inheritance chain at the start of a template's\n    execution."
  },
  {
    "code": "def search_phenotype_association_sets(self, dataset_id):\n        request = protocol.SearchPhenotypeAssociationSetsRequest()\n        request.dataset_id = dataset_id\n        request.page_size = pb.int(self._page_size)\n        return self._run_search_request(\n            request, \"phenotypeassociationsets\",\n            protocol.SearchPhenotypeAssociationSetsResponse)",
    "docstring": "Returns an iterator over the PhenotypeAssociationSets on the server."
  },
  {
    "code": "def _authenticate(self,\n                     auth,\n                     application,\n                     application_url=None,\n                     for_user=None,\n                     scopes=None,\n                     created_with=None,\n                     max_age=None,\n                     strength='strong',\n                     fail_if_already_exists=False,\n                     hostname=platform.node()):\n        url = '%s/authentications' % (self.domain)\n        payload = {\"scopes\": scopes, \"note\": application, \"note_url\": application_url,\n                   'hostname': hostname,\n                   'user': for_user,\n                   'max-age': max_age,\n                   'created_with': None,\n                   'strength': strength,\n                   'fail-if-exists': fail_if_already_exists}\n        data, headers = jencode(payload)\n        res = self.session.post(url, auth=auth, data=data, headers=headers)\n        self._check_response(res)\n        res = res.json()\n        token = res['token']\n        self.session.headers.update({'Authorization': 'token %s' % (token)})\n        return token",
    "docstring": "Use basic authentication to create an authentication token using the interface below.\n        With this technique, a username and password need not be stored permanently, and the user can\n        revoke access at any time.\n\n        :param username: The users name\n        :param password: The users password\n        :param application: The application that is requesting access\n        :param application_url: The application's home page\n        :param scopes: Scopes let you specify exactly what type of access you need. Scopes limit access for the tokens."
  },
  {
    "code": "def download(self,\n                 destination,\n                 condition=None,\n                 media_count=None,\n                 timeframe=None,\n                 new_only=False,\n                 pgpbar_cls=None,\n                 dlpbar_cls=None,\n                 ):\n        destination, close_destination = self._init_destfs(destination)\n        queue = Queue()\n        medias_queued = self._fill_media_queue(\n            queue, destination, iter(self.medias()), media_count,\n            new_only, condition)\n        queue.put(None)\n        worker = InstaDownloader(\n            queue=queue,\n            destination=destination,\n            namegen=self.namegen,\n            add_metadata=self.add_metadata,\n            dump_json=self.dump_json,\n            dump_only=self.dump_only,\n            pbar=None,\n            session=self.session)\n        worker.run()\n        return medias_queued",
    "docstring": "Download the refered post to the destination.\n\n        See `InstaLooter.download` for argument reference.\n\n        Note:\n            This function, opposed to other *looter* implementations, will\n            not spawn new threads, but simply use the main thread to download\n            the files.\n\n            Since a worker is in charge of downloading a *media* at a time\n            (and not a *file*), there would be no point in spawning more."
  },
  {
    "code": "def copy(self, strip=None, deep='ref'):\n        dd = self.to_dict(strip=strip, deep=deep)\n        return self.__class__(fromdict=dd)",
    "docstring": "Return another instance of the object, with the same attributes\n\n        If deep=True, all attributes themselves are also copies"
  },
  {
    "code": "def set_tcp_flags(self, tcp_flags):\n        if tcp_flags < 0 or tcp_flags > 255:\n            raise ValueError(\"Invalid tcp_flags. Valid: 0-255.\")\n        prev_size = 0\n        if self._json_dict.get('tcp_flags') is not None:\n            prev_size = len(str(self._json_dict['tcp_flags'])) + len('tcp_flags') + 3\n        self._json_dict['tcp_flags'] = tcp_flags\n        new_size = len(str(self._json_dict['tcp_flags'])) + len('tcp_flags') + 3\n        self._size += new_size - prev_size\n        if prev_size == 0 and self._has_field:\n            self._size += 2\n        self._has_field = True",
    "docstring": "Set the complete tcp flag bitmask"
  },
  {
    "code": "def tokenize_ofp_instruction_arg(arg):\n    arg_re = re.compile(\"[^,()]*\")\n    try:\n        rest = arg\n        result = []\n        while len(rest):\n            m = arg_re.match(rest)\n            if m.end(0) == len(rest):\n                result.append(rest)\n                return result\n            if rest[m.end(0)] == '(':\n                this_block, rest = _tokenize_paren_block(\n                    rest, m.end(0) + 1)\n                result.append(this_block)\n            elif rest[m.end(0)] == ',':\n                result.append(m.group(0))\n                rest = rest[m.end(0):]\n            else:\n                raise Exception\n            if len(rest):\n                assert rest[0] == ','\n                rest = rest[1:]\n        return result\n    except Exception:\n        raise ryu.exception.OFPInvalidActionString(action_str=arg)",
    "docstring": "Tokenize an argument portion of ovs-ofctl style action string."
  },
  {
    "code": "def _checkResponseRegisterAddress(payload, registeraddress):\n    _checkString(payload, minlength=2, description='payload')\n    _checkRegisteraddress(registeraddress)\n    BYTERANGE_FOR_STARTADDRESS = slice(0, 2)\n    bytesForStartAddress = payload[BYTERANGE_FOR_STARTADDRESS]\n    receivedStartAddress = _twoByteStringToNum(bytesForStartAddress)\n    if receivedStartAddress != registeraddress:\n        raise ValueError('Wrong given write start adress: {0}, but commanded is {1}. The data payload is: {2!r}'.format( \\\n            receivedStartAddress, registeraddress, payload))",
    "docstring": "Check that the start adress as given in the response is correct.\n\n    The first two bytes in the payload holds the address value.\n\n    Args:\n        * payload (string): The payload\n        * registeraddress (int): The register address (use decimal numbers, not hex).\n\n    Raises:\n        TypeError, ValueError"
  },
  {
    "code": "def get_aside(self, aside_usage_id):\n        aside_type = self.id_reader.get_aside_type_from_usage(aside_usage_id)\n        xblock_usage = self.id_reader.get_usage_id_from_aside(aside_usage_id)\n        xblock_def = self.id_reader.get_definition_id(xblock_usage)\n        aside_def_id, aside_usage_id = self.id_generator.create_aside(xblock_def, xblock_usage, aside_type)\n        keys = ScopeIds(self.user_id, aside_type, aside_def_id, aside_usage_id)\n        block = self.create_aside(aside_type, keys)\n        return block",
    "docstring": "Create an XBlockAside in this runtime.\n\n        The `aside_usage_id` is used to find the Aside class and data."
  },
  {
    "code": "def surge_handler(response, **kwargs):\n    if response.status_code == codes.conflict:\n        json = response.json()\n        errors = json.get('errors', [])\n        error = errors[0] if errors else json.get('error')\n        if error and error.get('code') == 'surge':\n            raise SurgeError(response)\n    return response",
    "docstring": "Error Handler to surface 409 Surge Conflict errors.\n\n    Attached as a callback hook on the Request object.\n\n    Parameters\n        response (requests.Response)\n            The HTTP response from an API request.\n        **kwargs\n            Arbitrary keyword arguments."
  },
  {
    "code": "def count_by(records: Sequence[Dict], field_name: str) -> defaultdict:\n    counter = defaultdict(int)\n    for record in records:\n        name = record[field_name]\n        counter[name] += 1\n    return counter",
    "docstring": "Frequency each value occurs in a record sequence for a given field name."
  },
  {
    "code": "def _render_str(self, string):\n        if isinstance(string, StrLabel):\n            string = string._render(string.expr)\n        string = str(string)\n        if len(string) == 0:\n            return ''\n        name, supers, subs = split_super_sub(string)\n        return render_unicode_sub_super(\n            name, subs, supers, sub_first=True, translate_symbols=True,\n            unicode_sub_super=self._settings['unicode_sub_super'])",
    "docstring": "Returned a unicodified version of the string"
  },
  {
    "code": "def getMoviesFromJSON(jsonURL):\n    response = urllib.request.urlopen(jsonURL)\n    jsonData = response.read().decode('utf-8')\n    objects = json.loads(jsonData)\n    if jsonURL.find('quickfind') != -1:\n        objects = objects['results']\n    optionalInfo = ['actors','directors','rating','genre','studio','releasedate']\n    movies = []\n    for obj in objects:\n        movie = Movie()\n        movie.title = obj['title']\n        movie.baseURL = obj['location']\n        movie.posterURL = obj['poster']\n        if movie.posterURL.find('http:') == -1:\n            movie.posterURL = \"http://apple.com%s\" % movie.posterURL\n        movie.trailers = obj['trailers']\n        for i in optionalInfo:\n            if i in obj:\n                setattr(movie, i, obj[i])\n        movies.append(movie)\n    return movies",
    "docstring": "Main function for this library\n\n    Returns list of Movie classes from apple.com/trailers json URL\n    such as: http://trailers.apple.com/trailers/home/feeds/just_added.json\n\n    The Movie classes use lazy loading mechanisms so that data not\n    directly available from JSON are loaded on demand. Currently these\n    lazy loaded parts are:\n     * poster\n     * trailerLinks\n     * description\n\n    Be warned that accessing these fields can take long time due to\n    network access. Therefore do the loading in thread separate from\n    UI thread or your users will notice.\n\n    There are optional fields that may or may not be present in every\n    Movie instance. These include:\n     * actors (list)\n     * directors (list)\n     * rating (string)\n     * genre (string)\n     * studio (string)\n     * releasedate (sring)\n    Please take care when trying to access these fields as they may\n    not exist."
  },
  {
    "code": "def NAND(*args, **kwargs):\n    errors = []\n    for arg in args:\n        try:\n            arg()\n        except CertifierError as e:\n            errors.append(e)\n    if (len(errors) != len(args)) and len(args) > 1:\n        exc = kwargs.get(\n            'exc',\n            CertifierValueError('Expecting no certified values'),\n        )\n        if exc is not None:\n            raise exc",
    "docstring": "ALL args must raise an exception when called overall.\n    Raise the specified exception on failure OR the first exception.\n\n    :params iterable[Certifier] args:\n        The certifiers to call\n    :param callable kwargs['exc']:\n        Callable that excepts the unexpectedly raised exception as argument and return an\n        exception to raise."
  },
  {
    "code": "def get_by_slug(tag_slug):\n        label_recs = TabTag.select().where(TabTag.slug == tag_slug)\n        return label_recs.get() if label_recs else False",
    "docstring": "Get label by slug."
  },
  {
    "code": "def wnfild(small, window):\n    assert isinstance(window, stypes.SpiceCell)\n    assert window.dtype == 1\n    small = ctypes.c_double(small)\n    libspice.wnfild_c(small, ctypes.byref(window))\n    return window",
    "docstring": "Fill small gaps between adjacent intervals of a double precision window.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnfild_c.html\n\n    :param small: Limiting measure of small gaps. \n    :type small: float\n    :param window: Window to be filled \n    :type window: spiceypy.utils.support_types.SpiceCell\n    :return: Filled Window.\n    :rtype: spiceypy.utils.support_types.SpiceCell"
  },
  {
    "code": "def POST_AUTH(self):\n        username = self.user_manager.session_username()\n        user_info = self.database.users.find_one({\"username\": username})\n        user_input = web.input()\n        success = None\n        if \"register_courseid\" in user_input and user_input[\"register_courseid\"] != \"\":\n            try:\n                course = self.course_factory.get_course(user_input[\"register_courseid\"])\n                if not course.is_registration_possible(user_info):\n                    success = False\n                else:\n                    success = self.user_manager.course_register_user(course, username, user_input.get(\"register_password\", None))\n            except:\n                success = False\n        elif \"new_courseid\" in user_input and self.user_manager.user_is_superadmin():\n            try:\n                courseid = user_input[\"new_courseid\"]\n                self.course_factory.create_course(courseid, {\"name\": courseid, \"accessible\": False})\n                success = True\n            except:\n                success = False\n        return self.show_page(success)",
    "docstring": "Parse course registration or course creation and display the course list page"
  },
  {
    "code": "def write(self, file_or_filename, prog=None, format='xdot'):\n        if prog is None:\n            file = super(DotWriter, self).write(file_or_filename)\n        else:\n            buf = StringIO.StringIO()\n            super(DotWriter, self).write(buf)\n            buf.seek(0)\n            data = self.create(buf.getvalue(), prog, format)\n            if isinstance(file_or_filename, basestring):\n                file = None\n                try:\n                    file = open(file_or_filename, \"wb\")\n                except:\n                    logger.error(\"Error opening %s.\" % file_or_filename)\n                finally:\n                    if file is not None:\n                        file.write(data)\n                        file.close()\n            else:\n                file = file_or_filename\n                file.write(data)\n        return file",
    "docstring": "Writes the case data in Graphviz DOT language.\n\n        The format 'raw' is used to dump the Dot representation of the Case\n        object, without further processing. The output can be processed by any\n        of graphviz tools, defined in 'prog'."
  },
  {
    "code": "def mark_nonreturning_calls_endpoints(self):\n        for src, dst, data in self.transition_graph.edges(data=True):\n            if 'type' in data and data['type'] == 'call':\n                func_addr = dst.addr\n                if func_addr in self._function_manager:\n                    function = self._function_manager[func_addr]\n                    if function.returning is False:\n                        the_node = self.get_node(src.addr)\n                        self._callout_sites.add(the_node)\n                        self._add_endpoint(the_node, 'call')",
    "docstring": "Iterate through all call edges in transition graph. For each call a non-returning function, mark the source\n        basic block as an endpoint.\n\n        This method should only be executed once all functions are recovered and analyzed by CFG recovery, so we know\n        whether each function returns or not.\n\n        :return: None"
  },
  {
    "code": "def fast_sync_snapshot_decompress( snapshot_path, output_dir ):\n    if not tarfile.is_tarfile(snapshot_path):\n        return {'error': 'Not a tarfile-compatible archive: {}'.format(snapshot_path)}\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n    with tarfile.TarFile.bz2open(snapshot_path, 'r') as f:\n        tarfile.TarFile.extractall(f, path=output_dir)\n    return {'status': True}",
    "docstring": "Given the path to a snapshot file, decompress it and \n    write its contents to the given output directory\n\n    Return {'status': True} on success\n    Return {'error': ...} on failure"
  },
  {
    "code": "def _highest_perm_from_iter(self, perm_iter):\n        perm_set = set(perm_iter)\n        for perm_str in reversed(ORDERED_PERM_LIST):\n            if perm_str in perm_set:\n                return perm_str",
    "docstring": "Return the highest perm present in ``perm_iter`` or None if ``perm_iter`` is\n        empty."
  },
  {
    "code": "def _GetChunkForReading(self, chunk):\n    try:\n      return self.chunk_cache.Get(chunk)\n    except KeyError:\n      pass\n    missing_chunks = []\n    for chunk_number in range(chunk, chunk + 10):\n      if chunk_number not in self.chunk_cache:\n        missing_chunks.append(chunk_number)\n    self._ReadChunks(missing_chunks)\n    try:\n      return self.chunk_cache.Get(chunk)\n    except KeyError:\n      raise aff4.ChunkNotFoundError(\"Cannot open chunk %s\" % chunk)",
    "docstring": "Returns the relevant chunk from the datastore and reads ahead."
  },
  {
    "code": "def eigen_table(self):\r\n        idx = [\"Eigenvalue\", \"Variability (%)\", \"Cumulative (%)\"]\r\n        table = pd.DataFrame(\r\n            np.array(\r\n                [self.eigenvalues, self.inertia, self.cumulative_inertia]\r\n            ),\r\n            columns=[\"F%s\" % i for i in range(1, self.keep + 1)],\r\n            index=idx,\r\n        )\r\n        return table",
    "docstring": "Eigenvalues, expl. variance, and cumulative expl. variance."
  },
  {
    "code": "def render_table(self, headers, rows, style=None):\n        table = self.table(headers, rows, style)\n        table.render(self._io)",
    "docstring": "Format input to textual table."
  },
  {
    "code": "def data_to_stream(self, data_element, stream):\n        generator = \\\n            self._make_representation_generator(stream, self.resource_class,\n                                                self._mapping)\n        generator.run(data_element)",
    "docstring": "Writes the given data element to the given stream."
  },
  {
    "code": "def score(self, testing_features, testing_target):\n        if self.fitted_pipeline_ is None:\n            raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.')\n        testing_features, testing_target = self._check_dataset(testing_features, testing_target, sample_weight=None)\n        score = SCORERS[self.scoring_function](\n            self.fitted_pipeline_,\n            testing_features.astype(np.float64),\n            testing_target.astype(np.float64)\n        )\n        return score",
    "docstring": "Return the score on the given testing data using the user-specified scoring function.\n\n        Parameters\n        ----------\n        testing_features: array-like {n_samples, n_features}\n            Feature matrix of the testing set\n        testing_target: array-like {n_samples}\n            List of class labels for prediction in the testing set\n\n        Returns\n        -------\n        accuracy_score: float\n            The estimated test set accuracy"
  },
  {
    "code": "def add_object(self, object):\n        if object.id is None:\n            object.get_id()\n        self.db.engine.save(object)",
    "docstring": "Add object to db session. Only for session-centric object-database mappers."
  },
  {
    "code": "def ndlayout_(self, dataset, kdims, cols=3):\n        try:\n            return hv.NdLayout(dataset, kdims=kdims).cols(cols)\n        except Exception as e:\n            self.err(e, self.layout_, \"Can not create layout\")",
    "docstring": "Create a Holoview NdLayout from a dictionnary of chart objects"
  },
  {
    "code": "def get_api_key(self, api_key_id):\n        api = self._get_api(iam.DeveloperApi)\n        return ApiKey(api.get_api_key(api_key_id))",
    "docstring": "Get API key details for key registered in organisation.\n\n        :param str api_key_id: The ID of the API key to be updated (Required)\n        :returns: API key object\n        :rtype: ApiKey"
  },
  {
    "code": "def discover_OP_information(OP_uri):\n    _, content = httplib2.Http().request(\n        '%s/.well-known/openid-configuration' % OP_uri)\n    return _json_loads(content)",
    "docstring": "Discovers information about the provided OpenID Provider.\n\n    :param OP_uri: The base URI of the Provider information is requested for.\n    :type OP_uri: str\n    :returns: The contents of the Provider metadata document.\n    :rtype: dict\n\n    .. versionadded:: 1.0"
  },
  {
    "code": "def client_details(self, *args):\n        self.log(_('Client details:', lang='de'))\n        client = self._clients[args[0]]\n        self.log('UUID:', client.uuid, 'IP:', client.ip, 'Name:', client.name, 'User:', self._users[client.useruuid],\n                 pretty=True)",
    "docstring": "Display known details about a given client"
  },
  {
    "code": "def is_running(self):\n        state = yield from self._get_container_state()\n        if state == \"running\":\n            return True\n        if self.status == \"started\":\n            yield from self.stop()\n        return False",
    "docstring": "Checks if the container is running.\n\n        :returns: True or False\n        :rtype: bool"
  },
  {
    "code": "def url(self, name):\n        scheme = 'http'\n        path = self._prepend_name_prefix(name)\n        query = ''\n        fragment = ''\n        url_tuple = (scheme, self.netloc, path, query, fragment)\n        return urllib.parse.urlunsplit(url_tuple)",
    "docstring": "Return URL of resource"
  },
  {
    "code": "def get_subprocess_output(cls, command, ignore_stderr=True, **kwargs):\n    if ignore_stderr is False:\n      kwargs.setdefault('stderr', subprocess.STDOUT)\n    try:\n      return subprocess.check_output(command, **kwargs).decode('utf-8').strip()\n    except (OSError, subprocess.CalledProcessError) as e:\n      subprocess_output = getattr(e, 'output', '').strip()\n      raise cls.ExecutionError(str(e), subprocess_output)",
    "docstring": "Get the output of an executed command.\n\n    :param command: An iterable representing the command to execute (e.g. ['ls', '-al']).\n    :param ignore_stderr: Whether or not to ignore stderr output vs interleave it with stdout.\n    :raises: `ProcessManager.ExecutionError` on `OSError` or `CalledProcessError`.\n    :returns: The output of the command."
  },
  {
    "code": "def _rolling_window(a, window, axis=-1):\n    axis = _validate_axis(a, axis)\n    a = np.swapaxes(a, axis, -1)\n    if window < 1:\n        raise ValueError(\n            \"`window` must be at least 1. Given : {}\".format(window))\n    if window > a.shape[-1]:\n        raise ValueError(\"`window` is too long. Given : {}\".format(window))\n    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)\n    strides = a.strides + (a.strides[-1],)\n    rolling = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides,\n                                              writeable=False)\n    return np.swapaxes(rolling, -2, axis)",
    "docstring": "Make an ndarray with a rolling window along axis.\n\n    Parameters\n    ----------\n    a : array_like\n        Array to add rolling window to\n    axis: int\n        axis position along which rolling window will be applied.\n    window : int\n        Size of rolling window\n\n    Returns\n    -------\n    Array that is a view of the original array with a added dimension\n    of size w.\n\n    Examples\n    --------\n    >>> x=np.arange(10).reshape((2,5))\n    >>> np.rolling_window(x, 3, axis=-1)\n    array([[[0, 1, 2], [1, 2, 3], [2, 3, 4]],\n           [[5, 6, 7], [6, 7, 8], [7, 8, 9]]])\n\n    Calculate rolling mean of last dimension:\n    >>> np.mean(np.rolling_window(x, 3, axis=-1), -1)\n    array([[ 1.,  2.,  3.],\n           [ 6.,  7.,  8.]])\n\n    This function is taken from https://github.com/numpy/numpy/pull/31\n    but slightly modified to accept axis option."
  },
  {
    "code": "def dump_requestdriver_cookies_into_webdriver(requestdriver, webdriverwrapper, handle_sub_domain=True):\n    driver_hostname = urlparse(webdriverwrapper.current_url()).netloc\n    for cookie in requestdriver.session.cookies:\n        cookiedomain = cookie.domain\n        if handle_sub_domain:\n            if is_subdomain(cookiedomain, driver_hostname):\n                cookiedomain = driver_hostname\n        try:\n            webdriverwrapper.add_cookie({\n                'name': cookie.name,\n                'value': cookie.value,\n                'domain': cookiedomain,\n                'path': cookie.path\n            })\n        except WebDriverException, e:\n            raise WebDriverException(\n                msg='Cannot set cookie \"{name}\" with domain \"{domain}\" on url \"{url}\" {override}: {message}'.format(\n                    name=cookie.name,\n                    domain=cookiedomain,\n                    url=webdriverwrapper.current_url(),\n                    override='(Note that subdomain override is set!)' if handle_sub_domain else '',\n                    message=e.message),\n                screen=e.screen,\n                stacktrace=e.stacktrace\n            )",
    "docstring": "Adds all cookies in the RequestDriver session to Webdriver\n\n    @type requestdriver: RequestDriver\n    @param requestdriver: RequestDriver with cookies\n    @type webdriverwrapper: WebDriverWrapper\n    @param webdriverwrapper: WebDriverWrapper to receive cookies\n    @param handle_sub_domain: If True, will check driver url and change cookies with subdomains of that domain to match\n    the current driver domain in order to avoid cross-domain cookie errors\n    @rtype: None\n    @return: None"
  },
  {
    "code": "def call_at_most_every(seconds, count=1):\n  def decorator(func):\n    try:\n      call_history = getattr(func, '_call_history')\n    except AttributeError:\n      call_history = collections.deque(maxlen=count)\n      setattr(func, '_call_history', call_history)\n    @functools.wraps(func)\n    def _wrapper(*args, **kwargs):\n      current_time = time.time()\n      window_count = sum(ts > current_time - seconds for ts in call_history)\n      if window_count >= count:\n        time.sleep(call_history[window_count - count] - current_time + seconds)\n      call_history.append(time.time())\n      return func(*args, **kwargs)\n    return _wrapper\n  return decorator",
    "docstring": "Call the decorated function at most count times every seconds seconds.\n\n  The decorated function will sleep to ensure that at most count invocations\n  occur within any 'seconds' second window."
  },
  {
    "code": "def due(self):\n        if self._duration:\n            return self.begin + self._duration\n        elif self._due_time:\n            return self._due_time\n        else:\n            return None",
    "docstring": "Get or set the end of the todo.\n\n        |  Will return an :class:`Arrow` object.\n        |  May be set to anything that :func:`Arrow.get` understands.\n        |  If set to a non null value, removes any already\n            existing duration.\n        |  Setting to None will have unexpected behavior if\n            begin is not None.\n        |  Must not be set to an inferior value than self.begin."
  },
  {
    "code": "def get_referenced_fields_and_fragment_names(\n    context: ValidationContext,\n    cached_fields_and_fragment_names: Dict,\n    fragment: FragmentDefinitionNode,\n) -> Tuple[NodeAndDefCollection, List[str]]:\n    cached = cached_fields_and_fragment_names.get(fragment.selection_set)\n    if cached:\n        return cached\n    fragment_type = type_from_ast(context.schema, fragment.type_condition)\n    return get_fields_and_fragment_names(\n        context, cached_fields_and_fragment_names, fragment_type, fragment.selection_set\n    )",
    "docstring": "Get referenced fields and nested fragment names\n\n    Given a reference to a fragment, return the represented collection of fields as well\n    as a list of nested fragment names referenced via fragment spreads."
  },
  {
    "code": "def get_channel(self, name):\n        r = self.kraken_request('GET', 'channels/' + name)\n        return models.Channel.wrap_get_channel(r)",
    "docstring": "Return the channel for the given name\n\n        :param name: the channel name\n        :type name: :class:`str`\n        :returns: the model instance\n        :rtype: :class:`models.Channel`\n        :raises: None"
  },
  {
    "code": "def keepalive(nurse, *patients):\n    if DISABLED:\n        return\n    if hashable(nurse):\n        hashable_patients = []\n        for p in patients:\n            if hashable(p):\n                log.debug(\"Keeping {0} alive for lifetime of {1}\".format(p, nurse))\n                hashable_patients.append(p)\n            else:\n                log.warning(\"Unable to keep unhashable object {0} \"\n                            \"alive for lifetime of {1}\".format(p, nurse))\n        KEEPALIVE.setdefault(nurse, set()).update(hashable_patients)\n    else:\n        log.warning(\"Unable to keep objects alive for lifetime of \"\n                    \"unhashable object {0}\".format(nurse))",
    "docstring": "Keep ``patients`` alive at least as long as ``nurse`` is around using a\n    ``WeakKeyDictionary``."
  },
  {
    "code": "def prt_num_sig(self, prt=sys.stdout, alpha=0.05):\n        ctr = self.get_num_sig(alpha)\n        prt.write(\"{N:6,} TOTAL: {TXT}\\n\".format(N=len(self.nts), TXT=\" \".join([\n            \"FDR({FDR:4})\".format(FDR=ctr['FDR']),\n            \"Bonferroni({B:4})\".format(B=ctr['Bonferroni']),\n            \"Benjamini({B:4})\".format(B=ctr['Benjamini']),\n            \"PValue({P:4})\".format(P=ctr['PValue']),\n            os.path.basename(self.fin_davidchart)])))",
    "docstring": "Print the number of significant GO terms."
  },
  {
    "code": "def timezone(client, location, timestamp=None, language=None):\n    params = {\n        \"location\": convert.latlng(location),\n        \"timestamp\": convert.time(timestamp or datetime.utcnow())\n    }\n    if language:\n        params[\"language\"] = language\n    return client._request( \"/maps/api/timezone/json\", params)",
    "docstring": "Get time zone for a location on the earth, as well as that location's\n    time offset from UTC.\n\n    :param location: The latitude/longitude value representing the location to\n        look up.\n    :type location: string, dict, list, or tuple\n\n    :param timestamp: Timestamp specifies the desired time as seconds since\n        midnight, January 1, 1970 UTC. The Time Zone API uses the timestamp to\n        determine whether or not Daylight Savings should be applied. Times\n        before 1970 can be expressed as negative values. Optional. Defaults to\n        ``datetime.utcnow()``.\n    :type timestamp: int or datetime.datetime\n\n    :param language: The language in which to return results.\n    :type language: string\n\n    :rtype: dict"
  },
  {
    "code": "def get_vip_settings(vip):\n    iface = get_iface_for_address(vip)\n    netmask = get_netmask_for_address(vip)\n    fallback = False\n    if iface is None:\n        iface = config('vip_iface')\n        fallback = True\n    if netmask is None:\n        netmask = config('vip_cidr')\n        fallback = True\n    return iface, netmask, fallback",
    "docstring": "Calculate which nic is on the correct network for the given vip.\n\n    If nic or netmask discovery fail then fallback to using charm supplied\n    config. If fallback is used this is indicated via the fallback variable.\n\n    @param vip: VIP to lookup nic and cidr for.\n    @returns (str, str, bool): eg (iface, netmask, fallback)"
  },
  {
    "code": "def set_figure_window_geometry(fig='gcf', position=None, size=None):\n    if type(fig)==str:          fig = _pylab.gcf()\n    elif _fun.is_a_number(fig): fig = _pylab.figure(fig)\n    if _pylab.get_backend().find('Qt') >= 0:\n        w = fig.canvas.window()\n        if not size == None:\n            w.resize(size[0],size[1])\n        if not position == None:\n            w.move(position[0], position[1])\n    elif _pylab.get_backend().find('WX') >= 0:\n        w = fig.canvas.Parent\n        if not size == None:\n            w.SetSize(size)\n        if not position == None:\n            w.SetPosition(position)",
    "docstring": "This will currently only work for Qt4Agg and WXAgg backends.\n\n    postion = [x, y]\n    size    = [width, height]\n\n    fig can be 'gcf', a number, or a figure object."
  },
  {
    "code": "def get_category_or_404(path):\n    path_bits = [p for p in path.split('/') if p]\n    return get_object_or_404(Category, slug=path_bits[-1])",
    "docstring": "Retrieve a Category instance by a path."
  },
  {
    "code": "def double_tap(self, on_element):\n        self._actions.append(lambda: self._driver.execute(\n            Command.DOUBLE_TAP, {'element': on_element.id}))\n        return self",
    "docstring": "Double taps on a given element.\n\n        :Args:\n         - on_element: The element to tap."
  },
  {
    "code": "def recent_all_projects(self, limit=30, offset=0):\n        method = 'GET'\n        url = ('/recent-builds?circle-token={token}&limit={limit}&'\n               'offset={offset}'.format(token=self.client.api_token,\n                                        limit=limit,\n                                        offset=offset))\n        json_data = self.client.request(method, url)\n        return json_data",
    "docstring": "Return information about recent builds across all projects.\n\n        Args:\n            limit (int), Number of builds to return, max=100, defaults=30.\n            offset (int): Builds returned from this point, default=0.\n\n        Returns:\n            A list of dictionaries."
  },
  {
    "code": "def waiting(self, timeout=0):\n        \"Return True if data is ready for the client.\"\n        if self.linebuffer:\n            return True\n        (winput, woutput, wexceptions) = select.select((self.sock,), (), (), timeout)\n        return winput != []",
    "docstring": "Return True if data is ready for the client."
  },
  {
    "code": "def _flush(self):\n        for consumer in self.consumers:\n            if not getattr(consumer, \"closed\", False):\n                consumer.flush()",
    "docstring": "Flushes all registered consumer streams."
  },
  {
    "code": "def render_template(template, **context):\n    parts = template.split('/')\n    renderer = _get_renderer(parts[:-1])\n    return renderer.render(renderer.load_template(parts[-1:][0]), context)",
    "docstring": "Renders a given template and context.\n\n    :param template: The template name\n    :param context: the variables that should be available in the\n                    context of the template."
  },
  {
    "code": "def create_processors_from_settings(self):\n        config = getattr(settings, DJANGO_PROCESSOR_SETTING_NAME, [])\n        processors = self.instantiate_objects(config)\n        return processors",
    "docstring": "Expects the Django setting \"EVENT_TRACKING_PROCESSORS\" to be defined and\n        point to a list of backend engine configurations.\n\n        Example::\n\n            EVENT_TRACKING_PROCESSORS = [\n                {\n                    'ENGINE': 'some.arbitrary.Processor'\n                },\n                {\n                    'ENGINE': 'some.arbitrary.OtherProcessor',\n                    'OPTIONS': {\n                        'user': 'foo'\n                    }\n                },\n            ]"
  },
  {
    "code": "def db_create(cls, impl, working_dir):\n        global VIRTUALCHAIN_DB_SCRIPT\n        log.debug(\"Setup chain state in {}\".format(working_dir))\n        path = config.get_snapshots_filename(impl, working_dir)\n        if os.path.exists( path ):\n            raise Exception(\"Database {} already exists\")\n        lines = [l + \";\" for l in VIRTUALCHAIN_DB_SCRIPT.split(\";\")]\n        con = sqlite3.connect(path, isolation_level=None, timeout=2**30)\n        for line in lines:\n            con.execute(line)\n        con.row_factory = StateEngine.db_row_factory\n        return con",
    "docstring": "Create a sqlite3 db at the given path.\n        Create all the tables and indexes we need.\n        Returns a db connection on success\n        Raises an exception on error"
  },
  {
    "code": "def parse(self, vd, extent_loc):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('Boot Record already initialized')\n        (descriptor_type, identifier, version,\n         self.boot_system_identifier, self.boot_identifier,\n         self.boot_system_use) = struct.unpack_from(self.FMT, vd, 0)\n        if descriptor_type != VOLUME_DESCRIPTOR_TYPE_BOOT_RECORD:\n            raise pycdlibexception.PyCdlibInvalidISO('Invalid boot record descriptor type')\n        if identifier != b'CD001':\n            raise pycdlibexception.PyCdlibInvalidISO('Invalid boot record identifier')\n        if version != 1:\n            raise pycdlibexception.PyCdlibInvalidISO('Invalid boot record version')\n        self.orig_extent_loc = extent_loc\n        self._initialized = True",
    "docstring": "A method to parse a Boot Record out of a string.\n\n        Parameters:\n         vd - The string to parse the Boot Record out of.\n         extent_loc - The extent location this Boot Record is current at.\n        Returns:\n         Nothing."
  },
  {
    "code": "def main(self):\n        self.targets()\n        self.bait(k=49)\n        self.reversebait(maskmiddle='t', k=19)\n        self.subsample_reads()",
    "docstring": "Run the required methods in the appropriate order"
  },
  {
    "code": "def command(state, host, hostname, command, ssh_user=None):\n    connection_target = hostname\n    if ssh_user:\n        connection_target = '@'.join((ssh_user, hostname))\n    yield 'ssh {0} \"{1}\"'.format(connection_target, command)",
    "docstring": "Execute commands on other servers over SSH.\n\n    + hostname: the hostname to connect to\n    + command: the command to execute\n    + ssh_user: connect with this user"
  },
  {
    "code": "def get_named_range(self, name):\n        url = self.build_url(self._endpoints.get('get_named_range').format(name=name))\n        response = self.session.get(url)\n        if not response:\n            return None\n        return self.named_range_constructor(parent=self, **{self._cloud_data_key: response.json()})",
    "docstring": "Retrieves a Named range by it's name"
  },
  {
    "code": "def extract_bad_snapshot(e):\n        msg = e.response['Error']['Message']\n        error = e.response['Error']['Code']\n        e_snap_id = None\n        if error == 'InvalidSnapshot.NotFound':\n            e_snap_id = msg[msg.find(\"'\") + 1:msg.rfind(\"'\")]\n            log.warning(\"Snapshot not found %s\" % e_snap_id)\n        elif error == 'InvalidSnapshotID.Malformed':\n            e_snap_id = msg[msg.find('\"') + 1:msg.rfind('\"')]\n            log.warning(\"Snapshot id malformed %s\" % e_snap_id)\n        return e_snap_id",
    "docstring": "Handle various client side errors when describing snapshots"
  },
  {
    "code": "def dumpLines(self):\n        for i, line in enumerate(self.lines):\n            logger.debug(\"Line %d:\", i)\n            logger.debug(line.dumpFragments())",
    "docstring": "For debugging dump all line and their content"
  },
  {
    "code": "def list_candidate_adapter_ports(self, full_properties=False):\n        sg_cpc = self.cpc\n        adapter_mgr = sg_cpc.adapters\n        port_list = []\n        port_uris = self.get_property('candidate-adapter-port-uris')\n        if port_uris:\n            for port_uri in port_uris:\n                m = re.match(r'^(/api/adapters/[^/]*)/.*', port_uri)\n                adapter_uri = m.group(1)\n                adapter = adapter_mgr.resource_object(adapter_uri)\n                port_mgr = adapter.ports\n                port = port_mgr.resource_object(port_uri)\n                port_list.append(port)\n                if full_properties:\n                    port.pull_full_properties()\n        return port_list",
    "docstring": "Return the current candidate storage adapter port list of this storage\n        group.\n\n        The result reflects the actual list of ports used by the CPC, including\n        any changes that have been made during discovery. The source for this\n        information is the 'candidate-adapter-port-uris' property of the\n        storage group object.\n\n        Parameters:\n\n          full_properties (bool):\n            Controls that the full set of resource properties for each returned\n            candidate storage adapter port is being retrieved, vs. only the\n            following short set: \"element-uri\", \"element-id\", \"class\",\n            \"parent\".\n\n            TODO: Verify short list of properties.\n\n        Returns:\n\n          List of :class:`~zhmcclient.Port` objects representing the\n          current candidate storage adapter ports of this storage group.\n\n        Raises:\n\n          :exc:`~zhmcclient.HTTPError`\n          :exc:`~zhmcclient.ParseError`\n          :exc:`~zhmcclient.AuthError`\n          :exc:`~zhmcclient.ConnectionError`"
  },
  {
    "code": "def verify(\n    signature: Ed25519Signature, digest: bytes, pub_key: Ed25519PublicPoint\n) -> None:\n    _ed25519.checkvalid(signature, digest, pub_key)",
    "docstring": "Verify Ed25519 signature. Raise exception if the signature is invalid."
  },
  {
    "code": "def customtype(self):\n        result = None\n        if self.is_custom:\n            self.dependency()\n            if self._kind_module is not None:\n                if self.kind.lower() in self._kind_module.types:\n                    result = self._kind_module.types[self.kind.lower()]\n        return result",
    "docstring": "If this variable is a user-derivedy type, return the CustomType instance that\n        is its kind."
  },
  {
    "code": "def split_path(path, ref=None):\n    path = abspath(path, ref)\n    return path.strip(os.path.sep).split(os.path.sep)",
    "docstring": "Split a path into its components.\n\n    Parameters\n    ----------\n    path : str\n        absolute or relative path with respect to `ref`\n    ref : str or None\n        reference path if `path` is relative\n\n    Returns\n    -------\n    list : str\n        components of the path"
  },
  {
    "code": "def _value_equals(value1, value2, all_close):\n    if value1 is None:\n        value1 = np.nan\n    if value2 is None:\n        value2 = np.nan\n    are_floats = np.can_cast(type(value1), float) and np.can_cast(type(value2), float)\n    if all_close and are_floats:\n        return np.isclose(value1, value2, equal_nan=True)\n    else:\n        if are_floats:\n            return value1 == value2 or (value1 != value1 and value2 != value2)\n        else:\n            return value1 == value2",
    "docstring": "Get whether 2 values are equal\n\n    value1, value2 : ~typing.Any\n    all_close : bool\n        compare with np.isclose instead of =="
  },
  {
    "code": "def path(self):\n        if not self.name:\n            raise ValueError(\"Cannot determine path without a blob name.\")\n        return self.path_helper(self.bucket.path, self.name)",
    "docstring": "Getter property for the URL path to this Blob.\n\n        :rtype: str\n        :returns: The URL path to this Blob."
  },
  {
    "code": "def get(cls, keyval, key='id', user_id=None):\n        if keyval is None:\n            return None\n        if (key in cls.__table__.columns\n                and cls.__table__.columns[key].primary_key):\n            return cls.query.get(keyval)\n        else:\n            result = cls.query.filter(\n                getattr(cls, key) == keyval)\n            return result.first()",
    "docstring": "Fetches a single instance which has value `keyval`\n        for the attribute `key`.\n\n        Args:\n\n            keyval: The value of the attribute.\n\n            key (str, optional):  The attribute to search by. By default,\n                it is 'id'.\n\n        Returns:\n\n            A model instance if found. Else None.\n\n        Examples:\n\n            >>> User.get(35)\n            user35@i.com\n\n            >>> User.get('user35@i.com', key='email')\n            user35@i.com"
  },
  {
    "code": "def prepare_query(self, symbol,  start_date, end_date):\n        query = \\\n            'select * from yahoo.finance.historicaldata where symbol = \"%s\" and startDate = \"%s\" and endDate = \"%s\"' \\\n            % (symbol, start_date, end_date)\n        return query",
    "docstring": "Method returns prepared request query for Yahoo YQL API."
  },
  {
    "code": "def _tostring(value):\n        if value is True:\n            value = 'true'\n        elif value is False:\n            value = 'false'\n        elif value is None:\n            value = ''\n        return unicode(value)",
    "docstring": "Convert value to XML compatible string"
  },
  {
    "code": "def __updatable():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('file', nargs='?', type=argparse.FileType(), default=None, help='Requirements file')\n    args = parser.parse_args()\n    if args.file:\n        packages = parse_requirements_list(args.file)\n    else:\n        packages = get_parsed_environment_package_list()\n    for package in packages:\n        __list_package_updates(package['package'], package['version'])",
    "docstring": "Function used to output packages update information in the console"
  },
  {
    "code": "def cmd(send, msg, args):\n    parser = arguments.ArgParser(args['config'])\n    parser.add_argument('--lang', '--from', default=None)\n    parser.add_argument('--to', default='en')\n    parser.add_argument('msg', nargs='+')\n    try:\n        cmdargs = parser.parse_args(msg)\n    except arguments.ArgumentException as e:\n        send(str(e))\n        return\n    send(gen_translate(' '.join(cmdargs.msg), cmdargs.lang, cmdargs.to))",
    "docstring": "Translate something.\n\n    Syntax: {command} [--from <language code>] [--to <language code>] <text>\n    See https://cloud.google.com/translate/v2/translate-reference#supported_languages for a list of valid language codes"
  },
  {
    "code": "def clear_rubric(self):\n        if (self.get_rubric_metadata().is_read_only() or\n                self.get_rubric_metadata().is_required()):\n            raise errors.NoAccess()\n        self._my_map['rubricId'] = self._rubric_default",
    "docstring": "Clears the rubric.\n\n        raise:  NoAccess - ``Metadata.isRequired()`` or\n                ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def with_options(\n            self, codec_options=None, read_preference=None,\n            write_concern=None, read_concern=None):\n        return Collection(self.__database,\n                          self.__name,\n                          False,\n                          codec_options or self.codec_options,\n                          read_preference or self.read_preference,\n                          write_concern or self.write_concern,\n                          read_concern or self.read_concern)",
    "docstring": "Get a clone of this collection changing the specified settings.\n\n          >>> coll1.read_preference\n          Primary()\n          >>> from pymongo import ReadPreference\n          >>> coll2 = coll1.with_options(read_preference=ReadPreference.SECONDARY)\n          >>> coll1.read_preference\n          Primary()\n          >>> coll2.read_preference\n          Secondary(tag_sets=None)\n\n        :Parameters:\n          - `codec_options` (optional): An instance of\n            :class:`~bson.codec_options.CodecOptions`. If ``None`` (the\n            default) the :attr:`codec_options` of this :class:`Collection`\n            is used.\n          - `read_preference` (optional): The read preference to use. If\n            ``None`` (the default) the :attr:`read_preference` of this\n            :class:`Collection` is used. See :mod:`~pymongo.read_preferences`\n            for options.\n          - `write_concern` (optional): An instance of\n            :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the\n            default) the :attr:`write_concern` of this :class:`Collection`\n            is used.\n          - `read_concern` (optional): An instance of\n            :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the\n            default) the :attr:`read_concern` of this :class:`Collection`\n            is used."
  },
  {
    "code": "def insert_function(self, fname, ftype):\r\n        \"Inserts a new function\"\r\n        index = self.insert_id(fname, SharedData.KINDS.FUNCTION, [SharedData.KINDS.GLOBAL_VAR, SharedData.KINDS.FUNCTION], ftype)\r\n        self.table[index].set_attribute(\"Params\",0)\r\n        return index",
    "docstring": "Inserts a new function"
  },
  {
    "code": "def replace_uri(rdf, fromuri, touri):\n    replace_subject(rdf, fromuri, touri)\n    replace_predicate(rdf, fromuri, touri)\n    replace_object(rdf, fromuri, touri)",
    "docstring": "Replace all occurrences of fromuri with touri in the given model.\n\n    If touri is a list or tuple of URIRef, all values will be inserted.\n    If touri=None, will delete all occurrences of fromuri instead."
  },
  {
    "code": "def levelize_smooth_or_improve_candidates(to_levelize, max_levels):\n    if isinstance(to_levelize, tuple) or isinstance(to_levelize, str):\n        to_levelize = [to_levelize for i in range(max_levels)]\n    elif isinstance(to_levelize, list):\n        if len(to_levelize) < max_levels:\n            mlz = max_levels - len(to_levelize)\n            toext = [to_levelize[-1] for i in range(mlz)]\n            to_levelize.extend(toext)\n    elif to_levelize is None:\n        to_levelize = [(None, {}) for i in range(max_levels)]\n    return to_levelize",
    "docstring": "Turn parameter in to a list per level.\n\n    Helper function to preprocess the smooth and improve_candidates\n    parameters passed to smoothed_aggregation_solver and rootnode_solver.\n\n    Parameters\n    ----------\n    to_levelize : {string, tuple, list}\n        Parameter to preprocess, i.e., levelize and convert to a level-by-level\n        list such that entry i specifies the parameter at level i\n    max_levels : int\n        Defines the maximum number of levels considered\n\n    Returns\n    -------\n    to_levelize : list\n        The parameter list such that entry i specifies the parameter choice\n        at level i.\n\n    Notes\n    --------\n    This routine is needed because the user will pass in a parameter option\n    such as smooth='jacobi', or smooth=['jacobi', None], and this option must\n    be \"levelized\", or converted to a list of length max_levels such that entry\n    [i] in that list is the parameter choice for level i.\n\n    The parameter choice in to_levelize can be a string, tuple or list.  If\n    it is a string or tuple, then that option is assumed to be the\n    parameter setting at every level.  If to_levelize is inititally a list,\n    if the length of the list is less than max_levels, the last entry in the\n    list defines that parameter for all subsequent levels.\n\n    Examples\n    --------\n    >>> from pyamg.util.utils import levelize_smooth_or_improve_candidates\n    >>> improve_candidates = ['gauss_seidel', None]\n    >>> levelize_smooth_or_improve_candidates(improve_candidates, 4)\n    ['gauss_seidel', None, None, None]"
  },
  {
    "code": "def bind(self, instance):\n        p = self.clone()\n        p.instance = weakref.ref(instance)\n        return p",
    "docstring": "Bind an instance to this Pangler.\n\n        Returns a clone of this Pangler, with the only difference being that\n        the new Pangler is bound to the provided instance. Both will have the\n        same `id`, but new hooks will not be shared."
  },
  {
    "code": "def _cancel_outstanding(self):\n        for d in list(self._outstanding):\n            d.addErrback(lambda _: None)\n            d.cancel()",
    "docstring": "Cancel all of our outstanding requests"
  },
  {
    "code": "def track_model(model):\n    @receiver(post_save, sender=model, weak=False, dispatch_uid='simpleimages')\n    def transform_signal(sender, **kwargs):\n        simpleimages.utils.perform_transformation(\n            kwargs['instance'],\n            kwargs['update_fields']\n        )\n    def disconnect():\n        post_save.disconnect(sender=model, dispatch_uid='simpleimages')\n    return disconnect",
    "docstring": "Perform designated transformations on model, when it saves.\n\n    Calls :py:func:`~simpleimages.utils.perform_transformation`\n    on every model saves using\n    :py:data:`django.db.models.signals.post_save`.\n\n    It uses the ``update_fields`` kwarg to tell what fields it should\n    transform."
  },
  {
    "code": "def mock_method(self, interface, dbus_method, in_signature, *args, **kwargs):\n        if in_signature == '' and len(args) > 0:\n            raise TypeError('Fewer items found in D-Bus signature than in Python arguments')\n        m = dbus.connection.MethodCallMessage('a.b', '/a', 'a.b', 'a')\n        m.append(signature=in_signature, *args)\n        args = m.get_args_list()\n        self.log(dbus_method + self.format_args(args))\n        self.call_log.append((int(time.time()), str(dbus_method), args))\n        self.MethodCalled(dbus_method, args)\n        code = self.methods[interface][dbus_method][2]\n        if code and isinstance(code, types.FunctionType):\n            return code(self, *args)\n        elif code:\n            loc = locals().copy()\n            exec(code, globals(), loc)\n            if 'ret' in loc:\n                return loc['ret']",
    "docstring": "Master mock method.\n\n        This gets \"instantiated\" in AddMethod(). Execute the code snippet of\n        the method and return the \"ret\" variable if it was set."
  },
  {
    "code": "def mean(name, add, match):\n    ret = {'name': name,\n           'changes': {},\n           'comment': '',\n           'result': True}\n    if name not in __reg__:\n        __reg__[name] = {}\n        __reg__[name]['val'] = 0\n        __reg__[name]['total'] = 0\n        __reg__[name]['count'] = 0\n    for event in __events__:\n        try:\n            event_data = event['data']['data']\n        except KeyError:\n            event_data = event['data']\n        if salt.utils.stringutils.expr_match(event['tag'], match):\n            if add in event_data:\n                try:\n                    comp = int(event_data)\n                except ValueError:\n                    continue\n            __reg__[name]['total'] += comp\n            __reg__[name]['count'] += 1\n            __reg__[name]['val'] = __reg__[name]['total'] / __reg__[name]['count']\n    return ret",
    "docstring": "Accept a numeric value from the matched events and store a running average\n    of the values in the given register. If the specified value is not numeric\n    it will be skipped\n\n    USAGE:\n\n    .. code-block:: yaml\n\n        foo:\n          reg.mean:\n            - add: data_field\n            - match: my/custom/event"
  },
  {
    "code": "def slides(self):\n        sldIdLst = self._element.get_or_add_sldIdLst()\n        self.part.rename_slide_parts([sldId.rId for sldId in sldIdLst])\n        return Slides(sldIdLst, self)",
    "docstring": "|Slides| object containing the slides in this presentation."
  },
  {
    "code": "def index(self, text, terms=None, **kwargs):\n        self.clear()\n        terms = terms or text.terms.keys()\n        pairs = combinations(terms, 2)\n        count = comb(len(terms), 2)\n        for t1, t2 in bar(pairs, expected_size=count, every=1000):\n            score = text.score_braycurtis(t1, t2, **kwargs)\n            self.set_pair(t1, t2, score)",
    "docstring": "Index all term pair distances.\n\n        Args:\n            text (Text): The source text.\n            terms (list): Terms to index."
  },
  {
    "code": "def _get_record_by_label(xapi, rectype, label):\n    uuid = _get_label_uuid(xapi, rectype, label)\n    if uuid is False:\n        return False\n    return getattr(xapi, rectype).get_record(uuid)",
    "docstring": "Internal, returns a full record for uuid"
  },
  {
    "code": "def first(self):\n        csvsource = CSVSource(self.source, self.factory, self.key())\n        try:\n            item = csvsource.items().next()\n            return item\n        except StopIteration:\n            return None",
    "docstring": "Returns the first ICachableItem in the ICachableSource"
  },
  {
    "code": "def _convert_timedelta_to_seconds(timedelta):\n    days_in_seconds = timedelta.days * 24 * 3600\n    return int((timedelta.microseconds + (timedelta.seconds + days_in_seconds) * 10 ** 6) / 10 ** 6)",
    "docstring": "Returns the total seconds calculated from the supplied timedelta.\n\n       (Function provided to enable running on Python 2.6 which lacks timedelta.total_seconds())."
  },
  {
    "code": "def _is_installation_local(name):\n    loc = os.path.normcase(pkg_resources.working_set.by_key[name].location)\n    pre = os.path.normcase(sys.prefix)\n    return os.path.commonprefix([loc, pre]) == pre",
    "docstring": "Check whether the distribution is in the current Python installation.\n\n    This is used to distinguish packages seen by a virtual environment. A venv\n    may be able to see global packages, but we don't want to mess with them."
  },
  {
    "code": "def grant_bonus(self, worker_id, assignment_id, bonus_price, reason):\n        params = bonus_price.get_as_params('BonusAmount', 1)\n        params['WorkerId'] = worker_id\n        params['AssignmentId'] = assignment_id\n        params['Reason'] = reason\n        return self._process_request('GrantBonus', params)",
    "docstring": "Issues a payment of money from your account to a Worker.  To\n        be eligible for a bonus, the Worker must have submitted\n        results for one of your HITs, and have had those results\n        approved or rejected. This payment happens separately from the\n        reward you pay to the Worker when you approve the Worker's\n        assignment.  The Bonus must be passed in as an instance of the\n        Price object."
  },
  {
    "code": "def get_docs(self, vocab):\n        for string in self.strings:\n            vocab[string]\n        orth_col = self.attrs.index(ORTH)\n        for tokens, spaces in zip(self.tokens, self.spaces):\n            words = [vocab.strings[orth] for orth in tokens[:, orth_col]]\n            doc = Doc(vocab, words=words, spaces=spaces)\n            doc = doc.from_array(self.attrs, tokens)\n            yield doc",
    "docstring": "Recover Doc objects from the annotations, using the given vocab."
  },
  {
    "code": "def _find_parent(self, path_elements):\n        if not self.path_elements:\n            return self\n        elif self.path_elements == path_elements[0:len(self.path_elements)]:\n            return self\n        else:\n            return self.parent._find_parent(path_elements)",
    "docstring": "Recurse up the tree of FileSetStates until we find a parent, i.e.\n        one whose path_elements member is the start of the path_element\n        argument"
  },
  {
    "code": "def decode_mysql_string_literal(text):\n    assert text.startswith(\"'\")\n    assert text.endswith(\"'\")\n    text = text[1:-1]\n    return MYSQL_STRING_ESCAPE_SEQUENCE_PATTERN.sub(\n        unescape_single_character,\n        text,\n    )",
    "docstring": "Removes quotes and decodes escape sequences from given MySQL string literal\n    returning the result.\n\n    :param text: MySQL string literal, with the quotes still included.\n    :type text: str\n\n    :return: Given string literal with quotes removed and escape sequences\n             decoded.\n    :rtype: str"
  },
  {
    "code": "def _login(login_func, *args):\n    response = login_func(*args)\n    _fail_if_contains_errors(response)\n    user_json = response.json()\n    return User(user_json)",
    "docstring": "A helper function for logging in. It's purpose is to avoid duplicate\n    code in the login functions."
  },
  {
    "code": "def image_create(auth=None, **kwargs):\n    cloud = get_operator_cloud(auth)\n    kwargs = _clean_kwargs(keep_name=True, **kwargs)\n    return cloud.create_image(**kwargs)",
    "docstring": "Create an image\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' glanceng.image_create name=cirros file=cirros.raw disk_format=raw\n        salt '*' glanceng.image_create name=cirros file=cirros.raw disk_format=raw hw_scsi_model=virtio-scsi hw_disk_bus=scsi"
  },
  {
    "code": "def receive_message(self, operation, request_id):\n        try:\n            return receive_message(\n                self.sock, operation, request_id, self.max_message_size)\n        except BaseException as error:\n            self._raise_connection_failure(error)",
    "docstring": "Receive a raw BSON message or raise ConnectionFailure.\n\n        If any exception is raised, the socket is closed."
  },
  {
    "code": "def correct(self, z):\n        c = self.linear_system.Ml*(\n            self.linear_system.b - self.linear_system.A*z)\n        c = utils.inner(self.W, c, ip_B=self.ip_B)\n        if self.Q is not None and self.R is not None:\n            c = scipy.linalg.solve_triangular(self.R, self.Q.T.conj().dot(c))\n        if self.WR is not self.VR:\n            c = self.WR.dot(scipy.linalg.solve_triangular(self.VR, c))\n        return z + self.W.dot(c)",
    "docstring": "Correct the given approximate solution ``z`` with respect to the\n        linear system ``linear_system`` and the deflation space defined by\n        ``U``."
  },
  {
    "code": "def to_capabilities(self):\n        caps = self._caps\n        opts = self._options.copy()\n        if len(self._arguments) > 0:\n            opts[self.SWITCHES] = ' '.join(self._arguments)\n        if len(self._additional) > 0:\n            opts.update(self._additional)\n        if len(opts) > 0:\n            caps[Options.KEY] = opts\n        return caps",
    "docstring": "Marshals the IE options to the correct object."
  },
  {
    "code": "def default_dtype(field=None):\n        if field is None or field == RealNumbers():\n            return np.dtype('float64')\n        elif field == ComplexNumbers():\n            return np.dtype('complex128')\n        else:\n            raise ValueError('no default data type defined for field {}'\n                             ''.format(field))",
    "docstring": "Return the default data type of this class for a given field.\n\n        Parameters\n        ----------\n        field : `Field`, optional\n            Set of numbers to be represented by a data type.\n            Currently supported : `RealNumbers`, `ComplexNumbers`\n            The default ``None`` means `RealNumbers`\n\n        Returns\n        -------\n        dtype : `numpy.dtype`\n            Numpy data type specifier. The returned defaults are:\n\n                ``RealNumbers()`` : ``np.dtype('float64')``\n\n                ``ComplexNumbers()`` : ``np.dtype('complex128')``"
  },
  {
    "code": "def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:\n        return self._query(f'guilds/{guild_id}/members', 'GET')",
    "docstring": "Get a list of members in the guild\n\n        Args:\n            guild_id: snowflake id of the guild\n\n        Returns:\n            List of dictionary objects of users in the guild.\n\n            Example:\n                [\n                    {\n                        \"id\": \"41771983423143937\",\n                        \"name\": \"Discord Developers\",\n                        \"icon\": \"SEkgTU9NIElUUyBBTkRSRUkhISEhISEh\",\n                        \"splash\": null,\n                        \"owner_id\": \"80351110224678912\",\n                        \"region\": \"us-east\",\n                        \"afk_channel_id\": \"42072017402331136\",\n                        \"afk_timeout\": 300,\n                        \"embed_enabled\": true,\n                        \"embed_channel_id\": \"41771983444115456\",\n                        \"verification_level\": 1,\n                        \"roles\": [],\n                        \"emojis\": [],\n                        \"features\": [\"INVITE_SPLASH\"],\n                        \"unavailable\": false\n                    },\n                    {\n                        \"id\": \"41771983423143937\",\n                        \"name\": \"Discord Developers\",\n                        \"icon\": \"SEkgTU9NIElUUyBBTkRSRUkhISEhISEh\",\n                        \"splash\": null,\n                        \"owner_id\": \"80351110224678912\",\n                        \"region\": \"us-east\",\n                        \"afk_channel_id\": \"42072017402331136\",\n                        \"afk_timeout\": 300,\n                        \"embed_enabled\": true,\n                        \"embed_channel_id\": \"41771983444115456\",\n                        \"verification_level\": 1,\n                        \"roles\": [],\n                        \"emojis\": [],\n                        \"features\": [\"INVITE_SPLASH\"],\n                        \"unavailable\": false\n                    }\n                ]"
  },
  {
    "code": "def move_down(self):\n        old_index = self.current_index\n        self.current_index += 1\n        self.__wrap_index()\n        self.__handle_selections(old_index, self.current_index)",
    "docstring": "Try to select the button under the currently selected one.\n        If a button is not there, wrap down to the top of the menu and select the first button."
  },
  {
    "code": "def addRelationship(self,\n                        originItemId,\n                        destinationItemId,\n                        relationshipType):\n        url = \"%s/addRelationship\" % self.root\n        params = {\n            \"originItemId\" : originItemId,\n            \"destinationItemId\": destinationItemId,\n            \"relationshipType\" : relationshipType,\n            \"f\" : \"json\"\n        }\n        return self._post(url=url,\n                             param_dict=params,\n                             securityHandler=self._securityHandler,\n                             proxy_port=self._proxy_port,\n                             proxy_url=self._proxy_url)",
    "docstring": "Adds a relationship of a certain type between two items.\n\n        Inputs:\n           originItemId - The item ID of the origin item of the\n                          relationship\n           destinationItemId - The item ID of the destination item of the\n                               relationship.\n           relationshipType - The type of relationship between the two\n                              items. Must be defined in Relationship types."
  },
  {
    "code": "def default_user_agent(name=\"python-requests\"):\n    _implementation = platform.python_implementation()\n    if _implementation == 'CPython':\n        _implementation_version = platform.python_version()\n    elif _implementation == 'PyPy':\n        _implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major,\n                                                sys.pypy_version_info.minor,\n                                                sys.pypy_version_info.micro)\n        if sys.pypy_version_info.releaselevel != 'final':\n            _implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel])\n    elif _implementation == 'Jython':\n        _implementation_version = platform.python_version()\n    elif _implementation == 'IronPython':\n        _implementation_version = platform.python_version()\n    else:\n        _implementation_version = 'Unknown'\n    try:\n        p_system = platform.system()\n        p_release = platform.release()\n    except IOError:\n        p_system = 'Unknown'\n        p_release = 'Unknown'\n    return \" \".join(['%s/%s' % (name, __version__),\n                     '%s/%s' % (_implementation, _implementation_version),\n                     '%s/%s' % (p_system, p_release)])",
    "docstring": "Return a string representing the default user agent."
  },
  {
    "code": "def CreateConstMuskingumXFile(x_value,\n                              in_connectivity_file,\n                              out_x_file):\n    num_rivers = 0\n    with open_csv(in_connectivity_file, \"r\") as csvfile:\n        reader = csv_reader(csvfile)\n        for _ in reader:\n            num_rivers += 1\n    with open_csv(out_x_file, 'w') as kfile:\n        x_writer = csv_writer(kfile)\n        for _ in xrange(num_rivers):\n            x_writer.writerow([x_value])",
    "docstring": "Create muskingum X file from value that is constant all the way through\n    for each river segment.\n\n    Parameters\n    ----------\n    x_value: float\n        Value for the muskingum X parameter [0-0.5].\n    in_connectivity_file: str\n        The path to the RAPID connectivity file.\n    out_x_file: str\n        The path to the output x file.\n\n\n    Example::\n\n        from RAPIDpy.gis.muskingum import CreateConstMuskingumXFile\n\n        CreateConstMuskingumXFile(\n            x_value=0.3,\n            in_connectivity_file='/path/to/rapid_connect.csv',\n            out_x_file='/path/to/x.csv')"
  },
  {
    "code": "def lineReceived(self, line):\n        if line and line.isdigit():\n            self._expectedLength = int(line)\n            self._rawBuffer = []\n            self._rawBufferLength = 0\n            self.setRawMode()\n        else:\n            self.keepAliveReceived()",
    "docstring": "Called when a line is received.\n\n        We expect a length in bytes or an empty line for keep-alive. If\n        we got a length, switch to raw mode to receive that amount of bytes."
  },
  {
    "code": "def perform_srl(responses, prompt):\n    predictor = Predictor.from_path(\"https://s3-us-west-2.amazonaws.com/allennlp/models/srl-model-2018.05.25.tar.gz\")\n    sentences = [{\"sentence\": prompt + \" \" + response} for response in responses]\n    output = predictor.predict_batch_json(sentences)\n    full_output = [{\"sentence\": prompt + response,\n                    \"response\": response,\n                    \"srl\": srl} for (response, srl) in zip(responses, output)]\n    return full_output",
    "docstring": "Perform semantic role labeling on a list of responses, given a prompt."
  },
  {
    "code": "def from_pure(cls, z):\n        return cls(cls._key, {z: 1.0}, {z: 1.0}, pyxray.element_symbol(z))",
    "docstring": "Creates a pure composition.\n\n        Args:\n            z (int): atomic number"
  },
  {
    "code": "def build_header(\n    filename, disposition='attachment', filename_compat=None\n):\n    if disposition != 'attachment':\n        assert is_token(disposition)\n    rv = disposition\n    if is_token(filename):\n        rv += '; filename=%s' % (filename, )\n        return rv\n    elif is_ascii(filename) and is_lws_safe(filename):\n        qd_filename = qd_quote(filename)\n        rv += '; filename=\"%s\"' % (qd_filename, )\n        if qd_filename == filename:\n            return rv\n    elif filename_compat:\n        if is_token(filename_compat):\n            rv += '; filename=%s' % (filename_compat, )\n        else:\n            assert is_lws_safe(filename_compat)\n            rv += '; filename=\"%s\"' % (qd_quote(filename_compat), )\n    rv += \"; filename*=utf-8''%s\" % (percent_encode(\n        filename, safe=attr_chars_nonalnum, encoding='utf-8'), )\n    return rv.encode('iso-8859-1')",
    "docstring": "Generate a Content-Disposition header for a given filename.\n\n    For legacy clients that don't understand the filename* parameter,\n    a filename_compat value may be given.\n    It should either be ascii-only (recommended) or iso-8859-1 only.\n    In the later case it should be a character string\n    (unicode in Python 2).\n\n    Options for generating filename_compat (only useful for legacy clients):\n    - ignore (will only send filename*);\n    - strip accents using unicode's decomposing normalisations,\n    which can be done from unicode data (stdlib), and keep only ascii;\n    - use the ascii transliteration tables from Unidecode (PyPI);\n    - use iso-8859-1\n    Ignore is the safest, and can be used to trigger a fallback\n    to the document location (which can be percent-encoded utf-8\n    if you control the URLs).\n\n    See https://tools.ietf.org/html/rfc6266#appendix-D"
  },
  {
    "code": "def import_instance(\n        self,\n        name,\n        input_config,\n        retry=google.api_core.gapic_v1.method.DEFAULT,\n        timeout=google.api_core.gapic_v1.method.DEFAULT,\n        metadata=None,\n    ):\n        if \"import_instance\" not in self._inner_api_calls:\n            self._inner_api_calls[\n                \"import_instance\"\n            ] = google.api_core.gapic_v1.method.wrap_method(\n                self.transport.import_instance,\n                default_retry=self._method_configs[\"ImportInstance\"].retry,\n                default_timeout=self._method_configs[\"ImportInstance\"].timeout,\n                client_info=self._client_info,\n            )\n        request = cloud_redis_pb2.ImportInstanceRequest(\n            name=name, input_config=input_config\n        )\n        operation = self._inner_api_calls[\"import_instance\"](\n            request, retry=retry, timeout=timeout, metadata=metadata\n        )\n        return google.api_core.operation.from_gapic(\n            operation,\n            self.transport._operations_client,\n            cloud_redis_pb2.Instance,\n            metadata_type=cloud_redis_pb2.OperationMetadata,\n        )",
    "docstring": "Import a Redis RDB snapshot file from GCS into a Redis instance.\n\n        Redis may stop serving during this operation. Instance state will be\n        IMPORTING for entire operation. When complete, the instance will contain\n        only data from the imported file.\n\n        The returned operation is automatically deleted after a few hours, so\n        there is no need to call DeleteOperation.\n\n        Example:\n            >>> from google.cloud import redis_v1\n            >>>\n            >>> client = redis_v1.CloudRedisClient()\n            >>>\n            >>> name = client.instance_path('[PROJECT]', '[LOCATION]', '[INSTANCE]')\n            >>>\n            >>> # TODO: Initialize `input_config`:\n            >>> input_config = {}\n            >>>\n            >>> response = client.import_instance(name, input_config)\n            >>>\n            >>> def callback(operation_future):\n            ...     # Handle result.\n            ...     result = operation_future.result()\n            >>>\n            >>> response.add_done_callback(callback)\n            >>>\n            >>> # Handle metadata.\n            >>> metadata = response.metadata()\n\n        Args:\n            name (str): Required. Redis instance resource name using the form:\n                ``projects/{project_id}/locations/{location_id}/instances/{instance_id}``\n                where ``location_id`` refers to a GCP region\n            input_config (Union[dict, ~google.cloud.redis_v1.types.InputConfig]): Required. Specify data to be imported.\n\n                If a dict is provided, it must be of the same form as the protobuf\n                message :class:`~google.cloud.redis_v1.types.InputConfig`\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.redis_v1.types._OperationFuture` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def submit(self, func, *args, **kwargs):\n        self.op_sequence += 1\n        self.sqs.send_message(\n            QueueUrl=self.map_queue,\n            MessageBody=utils.dumps({'args': args, 'kwargs': kwargs}),\n            MessageAttributes={\n                'sequence_id': {\n                    'StringValue': str(self.op_sequence),\n                    'DataType': 'Number'},\n                'op': {\n                    'StringValue': named(func),\n                    'DataType': 'String',\n                },\n                'ser': {\n                    'StringValue': 'json',\n                    'DataType': 'String'}}\n        )\n        self.futures[self.op_sequence] = f = SQSFuture(\n            self.op_sequence)\n        return f",
    "docstring": "Submit a function for serialized execution on sqs"
  },
  {
    "code": "def _extcap_call(prog, args, keyword, values):\n    p = subprocess.Popen(\n        [prog] + args,\n        stdout=subprocess.PIPE, stderr=subprocess.PIPE\n    )\n    data, err = p.communicate()\n    if p.returncode != 0:\n        raise OSError(\"%s returned with error code %s: %s\" % (prog,\n                                                              p.returncode,\n                                                              err))\n    data = plain_str(data)\n    res = []\n    for ifa in data.split(\"\\n\"):\n        ifa = ifa.strip()\n        if not ifa.startswith(keyword):\n            continue\n        res.append(tuple([re.search(r\"{%s=([^}]*)}\" % val, ifa).group(1)\n                   for val in values]))\n    return res",
    "docstring": "Function used to call a program using the extcap format,\n    then parse the results"
  },
  {
    "code": "def get_polygon_filter_names():\n    names = []\n    for p in PolygonFilter.instances:\n        names.append(p.name)\n    return names",
    "docstring": "Get the names of all polygon filters in the order of creation"
  },
  {
    "code": "def named_entity_texts(self):\n        if not self.is_tagged(NAMED_ENTITIES):\n            self.tag_named_entities()\n        return self.texts(NAMED_ENTITIES)",
    "docstring": "The texts representing named entities."
  },
  {
    "code": "def event_later(self, delay, data_tuple):\n        return self._base.event_later(delay, self.make_event_data(*data_tuple))",
    "docstring": "Schedule an event to be emitted after a delay.\n\n        :param delay: number of seconds\n        :param data_tuple: a 2-tuple (flavor, data)\n        :return: an event object, useful for cancelling."
  },
  {
    "code": "def values(self) -> List[\"Package\"]:\n        values = [self.build_dependencies.get(name) for name in self.build_dependencies]\n        return values",
    "docstring": "Return an iterable of the available `Package` instances."
  },
  {
    "code": "def get_context_file_name(pid_file):\n    root = os.path.dirname(pid_file)\n    port_file = os.path.join(root, \"context.json\")\n    return port_file",
    "docstring": "When the daemon is started write out the information which port it was using."
  },
  {
    "code": "def collect_transitive_dependencies(\n    collected: Set[str], dep_graph: DepGraph, from_name: str\n) -> None:\n    immediate_deps = dep_graph[from_name]\n    for to_name in immediate_deps:\n        if to_name not in collected:\n            collected.add(to_name)\n            collect_transitive_dependencies(collected, dep_graph, to_name)",
    "docstring": "Collect transitive dependencies.\n\n    From a dependency graph, collects a list of transitive dependencies by recursing\n    through a dependency graph."
  },
  {
    "code": "def allreduce_grads(all_grads, average):\n    if get_tf_version_tuple() <= (1, 12):\n        from tensorflow.contrib import nccl\n    else:\n        from tensorflow.python.ops import nccl_ops as nccl\n    nr_tower = len(all_grads)\n    if nr_tower == 1:\n        return all_grads\n    new_all_grads = []\n    for grads in zip(*all_grads):\n        summed = nccl.all_sum(grads)\n        grads_for_devices = []\n        for g in summed:\n            with tf.device(g.device):\n                if average:\n                    g = tf.multiply(g, 1.0 / nr_tower)\n            grads_for_devices.append(g)\n        new_all_grads.append(grads_for_devices)\n    ret = list(zip(*new_all_grads))\n    return ret",
    "docstring": "All-reduce average the gradients among K devices. Results are broadcasted to all devices.\n\n    Args:\n        all_grads (K x N): List of list of gradients. N is the number of variables.\n        average (bool): average gradients or not.\n\n    Returns:\n        K x N: same as input, but each grad is replaced by the average over K devices."
  },
  {
    "code": "def prefer_type(self, prefer, over):\n        self._write_lock.acquire()\n        try:\n            if self._preferred(preferred=over, over=prefer):\n                raise ValueError(\n                    \"Type %r is already preferred over %r.\" % (over, prefer))\n            prefs = self._prefer_table.setdefault(prefer, set())\n            prefs.add(over)\n        finally:\n            self._write_lock.release()",
    "docstring": "Prefer one type over another type, all else being equivalent.\n\n        With abstract base classes (Python's abc module) it is possible for\n        a type to appear to be a subclass of another type without the supertype\n        appearing in the subtype's MRO. As such, the supertype has no order\n        with respect to other supertypes, and this may lead to amguity if two\n        implementations are provided for unrelated abstract types.\n\n        In such cases, it is possible to disambiguate by explictly telling the\n        function to prefer one type over the other.\n\n        Arguments:\n            prefer: Preferred type (class).\n            over: The type we don't like (class).\n\n        Raises:\n            ValueError: In case of logical conflicts."
  },
  {
    "code": "def from_record(self, record):\n        self.record = record\n        self._setup_tls_files(self.record['files'])\n        return self",
    "docstring": "Build a bundle from a CertStore record"
  },
  {
    "code": "def unquote (s, matching=False):\n    if not s:\n        return s\n    if len(s) < 2:\n        return s\n    if matching:\n        if s[0] in (\"\\\"'\") and s[0] == s[-1]:\n            s = s[1:-1]\n    else:\n        if s[0] in (\"\\\"'\"):\n            s = s[1:]\n        if s[-1] in (\"\\\"'\"):\n            s = s[:-1]\n    return s",
    "docstring": "Remove leading and ending single and double quotes.\n    The quotes need to match if matching is True. Only one quote from each\n    end will be stripped.\n\n    @return: if s evaluates to False, return s as is, else return\n        string with stripped quotes\n    @rtype: unquoted string, or s unchanged if it is evaluting to False"
  },
  {
    "code": "def by_population_density(self,\n                              lower=-1,\n                              upper=2 ** 31,\n                              zipcode_type=ZipcodeType.Standard,\n                              sort_by=SimpleZipcode.population_density.name,\n                              ascending=False,\n                              returns=DEFAULT_LIMIT):\n        return self.query(\n            population_density_lower=lower,\n            population_density_upper=upper,\n            sort_by=sort_by, zipcode_type=zipcode_type,\n            ascending=ascending, returns=returns,\n        )",
    "docstring": "Search zipcode information by population density range.\n\n        `population density` is `population per square miles on land`"
  },
  {
    "code": "def map_to_precursor_biopython(seqs, names, loci, args):\n    precursor = precursor_sequence(loci, args.ref).upper()\n    dat = dict()\n    for s, n in itertools.izip(seqs, names):\n        res = _align(str(s), precursor)\n        if res:\n            dat[n] = res\n    logger.debug(\"mapped in %s: %s out of %s\" % (loci, len(dat), len(seqs)))\n    return dat",
    "docstring": "map the sequences using biopython package"
  },
  {
    "code": "def get_all_permissions(self):\n        perms = set()\n        for role in self.get_user_roles():\n            for perm_view in role.permissions:\n                t = (perm_view.permission.name, perm_view.view_menu.name)\n                perms.add(t)\n        return perms",
    "docstring": "Returns a set of tuples with the perm name and view menu name"
  },
  {
    "code": "def set_hw_virt_ex_property(self, property_p, value):\n        if not isinstance(property_p, HWVirtExPropertyType):\n            raise TypeError(\"property_p can only be an instance of type HWVirtExPropertyType\")\n        if not isinstance(value, bool):\n            raise TypeError(\"value can only be an instance of type bool\")\n        self._call(\"setHWVirtExProperty\",\n                     in_p=[property_p, value])",
    "docstring": "Sets a new value for the specified hardware virtualization boolean property.\n\n        in property_p of type :class:`HWVirtExPropertyType`\n            Property type to set.\n\n        in value of type bool\n            New property value.\n\n        raises :class:`OleErrorInvalidarg`\n            Invalid property."
  },
  {
    "code": "async def create(self, model_, **data):\n        inst = model_(**data)\n        query = model_.insert(**dict(inst.__data__))\n        pk = await self.execute(query)\n        if inst._pk is None:\n            inst._pk = pk\n        return inst",
    "docstring": "Create a new object saved to database."
  },
  {
    "code": "def get_long_description():\n    with open(\"README.rst\", \"r\") as f:\n        readme = f.read()\n    with open(\"CHANGELOG.rst\", \"r\") as f:\n        changelog = f.read()\n        changelog = changelog.replace(\"\\nUnreleased\\n------------------\", \"\")\n    return \"\\n\".join([readme, changelog])",
    "docstring": "Return this projects description."
  },
  {
    "code": "def delete(self, *args, **kwargs):\n        from fields import RatingField\n        qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')\n        to_update = []\n        for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):\n            model_class = ContentType.objects.get(pk=content_type).model_class()\n            if model_class:\n                to_update.extend(list(model_class.objects.filter(pk__in=list(objects)[0])))\n        retval = super(VoteQuerySet, self).delete(*args, **kwargs)\n        for obj in to_update:\n            for field in getattr(obj, '_djangoratings', []):\n                getattr(obj, field.name)._update(commit=False)\n            obj.save()\n        return retval",
    "docstring": "Handles updating the related `votes` and `score` fields attached to the model."
  },
  {
    "code": "def a10_allocate_ip_from_dhcp_range(self, subnet, interface_id, mac, port_id):\n        subnet_id = subnet[\"id\"]\n        network_id = subnet[\"network_id\"]\n        iprange_result = self.get_ipallocationpool_by_subnet_id(subnet_id)\n        ip_in_use_list = [x.ip_address for x in self.get_ipallocations_by_subnet_id(subnet_id)]\n        range_begin, range_end = iprange_result.first_ip, iprange_result.last_ip\n        ip_address = IPHelpers.find_unused_ip(range_begin, range_end, ip_in_use_list)\n        if not ip_address:\n            msg = \"Cannot allocate from subnet {0}\".format(subnet)\n            LOG.error(msg)\n            raise Exception\n        mark_in_use = {\n            \"ip_address\": ip_address,\n            \"network_id\": network_id,\n            \"port_id\": port_id,\n            \"subnet_id\": subnet[\"id\"]\n        }\n        self.create_ipallocation(mark_in_use)\n        return ip_address, subnet[\"cidr\"], mark_in_use[\"port_id\"]",
    "docstring": "Search for an available IP.addr from unallocated nmodels.IPAllocationPool range.\n        If no addresses are available then an error is raised. Returns the address as a string.\n        This search is conducted by a difference of the nmodels.IPAllocationPool set_a\n        and the current IP allocations."
  },
  {
    "code": "def clear_output(output=None):\n    for target in env.sos_dict['_output'] if output is None else output:\n        if isinstance(target, file_target) and target.exists():\n            try:\n                target.unlink()\n            except Exception as e:\n                env.logger.warning(f'Failed to remove {target}: {e}')",
    "docstring": "Remove file targets in `_output` when a step fails to complete"
  },
  {
    "code": "def _prepend_schema_name(self, message):\n        if self._name:\n            message = \"{0!r} {1!s}\".format(self._name, message)\n        return message",
    "docstring": "If a custom schema name has been defined, prepends it to the error\n        message that gets raised when a schema error occurs."
  },
  {
    "code": "def load(self):\n        self._validate()\n        self._logger.logging_load()\n        self._csv_reader = csv.reader(\n            six.StringIO(self.source.strip()),\n            delimiter=self.delimiter,\n            quotechar=self.quotechar,\n            strict=True,\n            skipinitialspace=True,\n        )\n        formatter = CsvTableFormatter(self._to_data_matrix())\n        formatter.accept(self)\n        return formatter.to_table_data()",
    "docstring": "Extract tabular data as |TableData| instances from a CSV text object.\n        |load_source_desc_text|\n\n        :return:\n            Loaded table data.\n            |load_table_name_desc|\n\n            ===================  ========================================\n            Format specifier     Value after the replacement\n            ===================  ========================================\n            ``%(filename)s``     ``\"\"``\n            ``%(format_name)s``  ``\"csv\"``\n            ``%(format_id)s``    |format_id_desc|\n            ``%(global_id)s``    |global_id|\n            ===================  ========================================\n        :rtype: |TableData| iterator\n        :raises pytablereader.DataError:\n            If the CSV data is invalid.\n\n        .. seealso::\n            :py:func:`csv.reader`"
  },
  {
    "code": "def file_name(self, value):\n        if isinstance(value, FileName):\n            self._file_name = value\n        else:\n            self._file_name = FileName(value)",
    "docstring": "The filename of the attachment\n\n        :param file_name: The filename of the attachment\n        :type file_name: FileName, string"
  },
  {
    "code": "def replaceNode(self, cur):\n        if cur is None: cur__o = None\n        else: cur__o = cur._o\n        ret = libxml2mod.xmlReplaceNode(self._o, cur__o)\n        if ret is None:raise treeError('xmlReplaceNode() failed')\n        __tmp = xmlNode(_obj=ret)\n        return __tmp",
    "docstring": "Unlink the old node from its current context, prune the new\n          one at the same place. If @cur was already inserted in a\n           document it is first unlinked from its existing context."
  },
  {
    "code": "def direction(self, direction):\n        if not isinstance(direction, str):\n            raise TypeError(\"direction must be of type str\")\n        accepted_values = ['i', 'x', 'y', 'z', 's', 'c']\n        if direction not in accepted_values:\n            raise ValueError(\"must be one of: {}\".format(accepted_values))\n        self._direction = direction",
    "docstring": "set the direction"
  },
  {
    "code": "def get_auth():\n    import getpass\n    user = input(\"User Name: \")\n    pswd = getpass.getpass('Password: ')\n    return Github(user, pswd)",
    "docstring": "Get authentication."
  },
  {
    "code": "def run_basic_group():\n  test = htf.Test(htf.PhaseGroup(\n      setup=[setup_phase],\n      main=[main_phase],\n      teardown=[teardown_phase],\n  ))\n  test.execute()",
    "docstring": "Run the basic phase group example.\n\n  In this example, there are no terminal phases; all phases are run."
  },
  {
    "code": "def _slice_split_info_to_instruction_dicts(self, list_sliced_split_info):\n    instruction_dicts = []\n    for sliced_split_info in list_sliced_split_info:\n      mask = splits_lib.slice_to_percent_mask(sliced_split_info.slice_value)\n      filepaths = list(sorted(self._build_split_filenames(\n          split_info_list=[sliced_split_info.split_info],\n      )))\n      if sliced_split_info.split_info.num_examples:\n        shard_id2num_examples = splits_lib.get_shard_id2num_examples(\n            sliced_split_info.split_info.num_shards,\n            sliced_split_info.split_info.num_examples,\n        )\n        mask_offsets = splits_lib.compute_mask_offsets(shard_id2num_examples)\n      else:\n        logging.warning(\n            \"Statistics not present in the dataset. TFDS is not able to load \"\n            \"the total number of examples, so using the subsplit API may not \"\n            \"provide precise subsplits.\"\n        )\n        mask_offsets = [0] * len(filepaths)\n      for filepath, mask_offset in zip(filepaths, mask_offsets):\n        instruction_dicts.append({\n            \"filepath\": filepath,\n            \"mask\": mask,\n            \"mask_offset\": mask_offset,\n        })\n    return instruction_dicts",
    "docstring": "Return the list of files and reading mask of the files to read."
  },
  {
    "code": "def lock(self):\n        try:\n            self._do_lock()\n            return\n        except LockError:\n            time.sleep(self.TIMEOUT)\n        self._do_lock()",
    "docstring": "Acquire lock for dvc repo."
  },
  {
    "code": "def initialize_training(self, training_info: TrainingInfo, model_state=None, hidden_state=None):\n        if model_state is not None:\n            self.model.load_state_dict(model_state)\n        else:\n            self.model.reset_weights()\n        self.algo.initialize(\n            training_info=training_info, model=self.model, environment=self.env_roller.environment, device=self.device\n        )",
    "docstring": "Prepare models for training"
  },
  {
    "code": "def get_extra_claims(self, claims_set):\n        reserved_claims = (\n            self.userid_claim, \"iss\", \"aud\", \"exp\", \"nbf\", \"iat\", \"jti\",\n            \"refresh_until\", \"nonce\"\n        )\n        extra_claims = {}\n        for claim in claims_set:\n            if claim not in reserved_claims:\n                extra_claims[claim] = claims_set[claim]\n        if not extra_claims:\n            return None\n        return extra_claims",
    "docstring": "Get claims holding extra identity info from the claims set.\n\n        Returns a dictionary of extra claims or None if there are none.\n\n        :param claims_set: set of claims, which was included in the received\n        token."
  },
  {
    "code": "def info():\n    if current_app.testing or current_app.debug:\n        return jsonify(dict(\n            user=request.oauth.user.id,\n            client=request.oauth.client.client_id,\n            scopes=list(request.oauth.scopes)\n        ))\n    else:\n        abort(404)",
    "docstring": "Test to verify that you have been authenticated."
  },
  {
    "code": "def reset(self):\n        self._destroy_viewer()\n        self._reset_internal()\n        self.sim.forward()\n        return self._get_observation()",
    "docstring": "Resets simulation."
  },
  {
    "code": "def cancel_firewall(self, firewall_id, dedicated=False):\n        fwl_billing = self._get_fwl_billing_item(firewall_id, dedicated)\n        billing_item_service = self.client['Billing_Item']\n        return billing_item_service.cancelService(id=fwl_billing['id'])",
    "docstring": "Cancels the specified firewall.\n\n        :param int firewall_id: Firewall ID to be cancelled.\n        :param bool dedicated: If true, the firewall instance is dedicated,\n                               otherwise, the firewall instance is shared."
  },
  {
    "code": "def get_allowed_permissions_for(brain_or_object, user=None):\n    allowed = []\n    user = get_user(user)\n    obj = api.get_object(brain_or_object)\n    for permission in get_mapped_permissions_for(brain_or_object):\n        if user.has_permission(permission, obj):\n            allowed.append(permission)\n    return allowed",
    "docstring": "Get the allowed permissions for the given object\n\n    Code extracted from `IRoleManager.manage_getUserRolesAndPermissions`\n\n    :param brain_or_object: Catalog brain or object\n    :param user: A user ID, user object or None (for the current user)\n    :returns: List of allowed permissions"
  },
  {
    "code": "def check(self, options=None):\n        self.check_values(options)\n        self.check_attributes(options)\n        self.check_values(options)\n        return self",
    "docstring": "check for ambiguous keys and move attributes into dict"
  },
  {
    "code": "def as_bin(self, as_spendable=False):\n        f = io.BytesIO()\n        self.stream(f, as_spendable=as_spendable)\n        return f.getvalue()",
    "docstring": "Return the txo as binary."
  },
  {
    "code": "def serialize_elements(document, elements, options=None):\n    ctx = Context(document, options)\n    tree_root = root = etree.Element('div')\n    for elem in elements:\n        _ser = ctx.get_serializer(elem)\n        if _ser:\n            root = _ser(ctx, document, elem, root)\n    return etree.tostring(tree_root, pretty_print=ctx.options.get('pretty_print', True), encoding=\"utf-8\", xml_declaration=False)",
    "docstring": "Serialize list of elements into HTML string.\n\n    :Args:\n      - document (:class:`ooxml.doc.Document`): Document object\n      - elements (list): List of elements\n      - options (dict): Optional dictionary with :class:`Context` options\n\n    :Returns:\n      Returns HTML representation of the document."
  },
  {
    "code": "def strip_text_after_string(txt, junk):\n    if junk in txt:\n        return txt[:txt.find(junk)]\n    else:\n        return txt",
    "docstring": "used to strip any poorly documented comments at the end of function defs"
  },
  {
    "code": "def cmyk(c, m, y, k):\n    return Color(\"cmyk\", c, m, y, k)",
    "docstring": "Create a spectra.Color object in the CMYK color space.\n\n    :param float c: c coordinate.\n    :param float m: m coordinate.\n    :param float y: y coordinate.\n    :param float k: k coordinate.\n\n    :rtype: Color\n    :returns: A spectra.Color object in the CMYK color space."
  },
  {
    "code": "def _checkDragDropEvent(self, ev):\n        mimedata = ev.mimeData()\n        if mimedata.hasUrls():\n            urls = [str(url.toLocalFile()) for url in mimedata.urls() if url.toLocalFile()]\n        else:\n            urls = []\n        if urls:\n            ev.acceptProposedAction()\n            return urls\n        else:\n            ev.ignore()\n            return None",
    "docstring": "Checks if event contains a file URL, accepts if it does, ignores if it doesn't"
  },
  {
    "code": "def terminate(self, reason=None):\n        self.logger.info('terminating')\n        self.loop.unloop(pyev.EVUNLOOP_ALL)",
    "docstring": "Terminate the service with a reason."
  },
  {
    "code": "def get_doc(self, doc_id):\n        resp = self._r_session.get('/'.join([self._scheduler, 'docs', '_replicator', doc_id]))\n        resp.raise_for_status()\n        return response_to_json_dict(resp)",
    "docstring": "Get replication document state for a given replication document ID."
  },
  {
    "code": "def addReadGroup(self, readGroup):\n        id_ = readGroup.getId()\n        self._readGroupIdMap[id_] = readGroup\n        self._readGroupIds.append(id_)",
    "docstring": "Adds the specified ReadGroup to this ReadGroupSet."
  },
  {
    "code": "def create(self):\n        log.info(\"{module}: {name} [{id}] created\".format(module=self.manager.module_name,\n                                                          name=self.name,\n                                                          id=self.id))",
    "docstring": "Creates the node."
  },
  {
    "code": "def trend_msg(self, trend, significant=1):\n        ret = '-'\n        if trend is None:\n            ret = ' '\n        elif trend > significant:\n            ret = '/'\n        elif trend < -significant:\n            ret = '\\\\'\n        return ret",
    "docstring": "Return the trend message.\n\n        Do not take into account if trend < significant"
  },
  {
    "code": "def reset(self):\n        animation_gen = self._frame_function(*self._animation_args,\n                                             **self._animation_kwargs)\n        self._current_generator = itertools.cycle(\n            util.concatechain(animation_gen, self._back_up_generator))",
    "docstring": "Reset the current animation generator."
  },
  {
    "code": "def exposure_notes(self):\n        notes = []\n        exposure = definition(self.exposure.keywords.get('exposure'))\n        if 'notes' in exposure:\n            notes += exposure['notes']\n        if self.exposure.keywords['layer_mode'] == 'classified':\n            if 'classified_notes' in exposure:\n                notes += exposure['classified_notes']\n        if self.exposure.keywords['layer_mode'] == 'continuous':\n            if 'continuous_notes' in exposure:\n                notes += exposure['continuous_notes']\n        return notes",
    "docstring": "Get the exposure specific notes defined in definitions.\n\n        This method will do a lookup in definitions and return the\n        exposure definition specific notes dictionary.\n\n        This is a helper function to make it\n        easy to get exposure specific notes from the definitions metadata.\n\n        .. versionadded:: 3.5\n\n        :returns: A list like e.g. safe.definitions.exposure_land_cover[\n            'notes']\n        :rtype: list, None"
  },
  {
    "code": "def msvd(m):\n  u, s, vdgr = np.linalg.svd(m)\n  order = s.argsort()\n  s = s[order]\n  u= u[:,order]\n  vdgr = vdgr[order]\n  return u, s, vdgr.conj().T",
    "docstring": "Modified singular value decomposition.\n\n  Returns U, S, V where Udagger M V = diag(S) and the singular values\n  are sorted in ascending order (small to large)."
  },
  {
    "code": "def integrate_box(self,low,high,forcequad=False,**kwargs):\n        if not self.adaptive and not forcequad:\n            return self.gauss_kde.integrate_box_1d(low,high)*self.norm\n        return quad(self.evaluate,low,high,**kwargs)[0]",
    "docstring": "Integrates over a box. Optionally force quad integration, even for non-adaptive.\n\n        If adaptive mode is not being used, this will just call the\n        `scipy.stats.gaussian_kde` method `integrate_box_1d`.  Else,\n        by default, it will call `scipy.integrate.quad`.  If the\n        `forcequad` flag is turned on, then that integration will be\n        used even if adaptive mode is off.\n\n        Parameters\n        ----------\n        low : float\n            Lower limit of integration\n\n        high : float\n            Upper limit of integration\n\n        forcequad : bool\n            If `True`, then use the quad integration even if adaptive mode is off.\n\n        kwargs\n            Keyword arguments passed to `scipy.integrate.quad`."
  },
  {
    "code": "def clear_alert_destination(self, destination=0, channel=None):\n        if channel is None:\n            channel = self.get_network_channel()\n        self.set_alert_destination(\n            '0.0.0.0', False, 0, 0, destination, channel)",
    "docstring": "Clear an alert destination\n\n        Remove the specified alert destination configuration.\n\n        :param destination:  The destination to clear (defaults to 0)"
  },
  {
    "code": "def block_quote(node):\n    o = nodes.block_quote()\n    o.line = node.sourcepos[0][0]\n    for n in MarkDown(node):\n        o += n\n    return o",
    "docstring": "A block quote"
  },
  {
    "code": "def iter_instances(self):\n        for wrkey in set(self.keys()):\n            obj = self.get(wrkey)\n            if obj is None:\n                continue\n            yield wrkey, obj",
    "docstring": "Iterate over the stored objects\n\n        Yields:\n            wrkey: The two-tuple key used to store the object\n            obj: The instance or function object"
  },
  {
    "code": "def eqdate(y):\n    y = datetime.date.today() if y == 'TODAY' else datetime.date(*y)\n    return lambda x: x == y",
    "docstring": "Like eq but compares datetime with y,m,d tuple.\n    Also accepts magic string 'TODAY'."
  },
  {
    "code": "def write_nb(root, nb_name, cells):\n    nb = new_notebook(cells=cells,\n                      metadata={\n                        'language': 'python',\n                        })\n    nb_path = os.path.join(root, '%s.ipynb' % nb_name)\n    with codecs.open(nb_path, encoding='utf-8', mode='w') as nb_file:\n        nbformat.write(nb, nb_file, NB_VERSION)\n    print(\"Created Jupyter notebook at:\\n%s\" % nb_path)",
    "docstring": "Write a jupyter notebook to disk.\n\n    Takes a given a root directory, a notebook name, and a list of cells."
  },
  {
    "code": "def copy(self, *args, **kwargs):\n        for slot in self.__slots__:\n            attr = getattr(self, slot)\n            if slot[0] == '_':\n                slot = slot[1:]\n            if slot not in kwargs:\n                kwargs[slot] = attr\n        result = type(self)(*args, **kwargs)\n        return result",
    "docstring": "Copy this model element and contained elements if they exist."
  },
  {
    "code": "def convert_to_dict(item):\n    actual_type = detect_type(item)\n    if actual_type==\"dict\":\n        return item\n    elif actual_type==\"list\":\n        temp = {}\n        ctr = 0\n        for entry in item:\n            temp[ctr]=entry\n            ctr += 1\n        return temp\n    elif actual_type==\"mongoengine\":\n        return item.__dict__['_data']\n    elif actual_type==\"class\":\n        return item.__dict__\n    elif actual_type==\"iterable_dict\":\n        d = {}\n        for key in item:\n            d[key] = item[key]\n        return d\n    elif actual_type==\"object\":\n        tuples = getmembers(item)\n        d = {}\n        for (key, value) in tuples:\n            d[key] = value\n        return d\n    return {}",
    "docstring": "Examine an item of any type and return a true dictionary.\n\n    If the item is already a dictionary, then the item is returned as-is. Easy.\n\n    Otherwise, it attempts to interpret it. So far, this routine can handle:\n    \n    * a class, function, or anything with a .__dict__ entry\n    * a legacy mongoEngine document (a class for MongoDb handling)\n    * a list (index positions are used as keys)\n    * a generic object that is iterable\n    * a generic object with members\n\n    .. versionadded:: 0.0.4\n\n    :param item:\n        Any object such as a variable, instance, or function.\n    :returns:\n        A true dictionary. If unable to get convert 'item', then an empty dictionary '{}' is returned."
  },
  {
    "code": "def do(self, x_orig):\n        if self.scales is None:\n            return x_orig\n        else:\n            return np.dot(self.rotation.transpose(), x_orig)*self.scales",
    "docstring": "Transform the unknowns to preconditioned coordinates\n\n           This method also transforms the gradient to original coordinates"
  },
  {
    "code": "def list_taxa(pdb_list, sleep_time=.1):\n    if len(pdb_list)*sleep_time > 30:\n        warnings.warn(\"Because of API limitations, this function\\\n        will take at least \" + str(len(pdb_list)*sleep_time) + \" seconds to return results.\\\n        If you need greater speed, try modifying the optional argument sleep_time=.1, (although \\\n        this may cause the search to time out)\" )\n    taxa = []\n    for pdb_id in pdb_list:\n        all_info = get_all_info(pdb_id)\n        species_results = walk_nested_dict(all_info, 'Taxonomy', maxdepth=25,outputs=[])\n        first_result = walk_nested_dict(species_results,'@name',outputs=[])\n        if first_result:\n            taxa.append(first_result[-1])\n        else:\n            taxa.append('Unknown')\n        time.sleep(sleep_time)\n    return taxa",
    "docstring": "Given a list of PDB IDs, look up their associated species\n\n    This function digs through the search results returned\n    by the get_all_info() function and returns any information on\n    taxonomy included within the description.\n\n    The PDB website description of each entry includes the name\n    of the species (and sometimes details of organ or body part)\n    for each protein structure sample.\n\n    Parameters\n    ----------\n\n    pdb_list : list of str\n        List of PDB IDs\n\n    sleep_time : float\n        Time (in seconds) to wait between requests. If this number is too small\n        the API will stop working, but it appears to vary among different systems\n\n    Returns\n    -------\n\n    taxa : list of str\n        A list of the names or classifictions of species\n        associated with entries\n\n    Examples\n    --------\n\n    >>> crispr_query = make_query('crispr')\n    >>> crispr_results = do_search(crispr_query)\n    >>> print(list_taxa(crispr_results[:10]))\n    ['Thermus thermophilus',\n     'Sulfolobus solfataricus P2',\n     'Hyperthermus butylicus DSM 5456',\n     'unidentified phage',\n     'Sulfolobus solfataricus P2',\n     'Pseudomonas aeruginosa UCBPP-PA14',\n     'Pseudomonas aeruginosa UCBPP-PA14',\n     'Pseudomonas aeruginosa UCBPP-PA14',\n     'Sulfolobus solfataricus',\n     'Thermus thermophilus HB8']"
  },
  {
    "code": "def usage(self, auth, resource, metric, starttime, endtime, defer=False):\n        return self._call('usage', auth,\n                          [resource, metric, starttime, endtime], defer)",
    "docstring": "Returns metric usage for client and its subhierarchy.\n\n        Args:\n            auth: <cik> for authentication\n            resource: ResourceID\n            metrics: Metric to measure (as string), it may be an entity or consumable.\n            starttime: Start time of window to measure useage (format is ___).\n            endtime: End time of window to measure useage (format is ___)."
  },
  {
    "code": "def characterize_local_files(filedir, max_bytes=MAX_FILE_DEFAULT):\n    file_data = {}\n    logging.info('Characterizing files in {}'.format(filedir))\n    for filename in os.listdir(filedir):\n        filepath = os.path.join(filedir, filename)\n        file_stats = os.stat(filepath)\n        creation_date = arrow.get(file_stats.st_ctime).isoformat()\n        file_size = file_stats.st_size\n        if file_size <= max_bytes:\n            file_md5 = hashlib.md5()\n            with open(filepath, \"rb\") as f:\n                for chunk in iter(lambda: f.read(4096), b\"\"):\n                    file_md5.update(chunk)\n            md5 = file_md5.hexdigest()\n            file_data[filename] = {\n                'tags': guess_tags(filename),\n                'description': '',\n                'md5': md5,\n                'creation_date': creation_date,\n            }\n    return file_data",
    "docstring": "Collate local file info as preperation for Open Humans upload.\n\n    Note: Files with filesize > max_bytes are not included in returned info.\n\n    :param filedir: This field is target directory to get files from.\n    :param max_bytes: This field is the maximum file size to consider. Its\n        default value is 128m."
  },
  {
    "code": "def _read_config(cfg_file):\n    config = ConfigParser()\n    config.optionxform = lambda option: option\n    if not os.path.exists(cfg_file):\n        config.add_section(_MAIN_SECTION_NAME)\n        config.add_section(_ENVIRONMENT_SECTION_NAME)\n    else:\n        config.read(cfg_file)\n    return config",
    "docstring": "Return a ConfigParser object populated from the settings.cfg file.\n\n    :return: A Config Parser object."
  },
  {
    "code": "def _postback(self):\n        return requests.post(self.get_endpoint(), data=b\"cmd=_notify-validate&\" + self.query.encode(\"ascii\")).content",
    "docstring": "Perform PayPal Postback validation."
  },
  {
    "code": "def pdf(self, mu):\n        if self.transform is not None:\n            mu = self.transform(mu)             \n        return (1.0/float(self.sigma0))*np.exp(-(0.5*(mu-self.mu0)**2)/float(self.sigma0**2))",
    "docstring": "PDF for Normal prior\n\n        Parameters\n        ----------\n        mu : float\n            Latent variable for which the prior is being formed over\n\n        Returns\n        ----------\n        - p(mu)"
  },
  {
    "code": "def poly2o_residual(params, data, mask):\n    bg = poly2o_model(params, shape=data.shape)\n    res = (data - bg)[mask]\n    return res.flatten()",
    "docstring": "lmfit 2nd order polynomial residuals"
  },
  {
    "code": "def _sort_lambda(sortedby='cpu_percent',\n                 sortedby_secondary='memory_percent'):\n    ret = None\n    if sortedby == 'io_counters':\n        ret = _sort_io_counters\n    elif sortedby == 'cpu_times':\n        ret = _sort_cpu_times\n    return ret",
    "docstring": "Return a sort lambda function for the sortedbykey"
  },
  {
    "code": "def fetch(self):\n        params = values.of({})\n        payload = self._version.fetch(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return StepInstance(\n            self._version,\n            payload,\n            flow_sid=self._solution['flow_sid'],\n            engagement_sid=self._solution['engagement_sid'],\n            sid=self._solution['sid'],\n        )",
    "docstring": "Fetch a StepInstance\n\n        :returns: Fetched StepInstance\n        :rtype: twilio.rest.studio.v1.flow.engagement.step.StepInstance"
  },
  {
    "code": "def set_preferences(request, dashboard_id):\n    try:\n        preferences = DashboardPreferences.objects.get(\n            user=request.user,\n            dashboard_id=dashboard_id\n        )\n    except DashboardPreferences.DoesNotExist:\n        preferences = None\n    if request.method == \"POST\":\n        form = DashboardPreferencesForm(\n            user=request.user,\n            dashboard_id=dashboard_id,\n            data=request.POST,\n            instance=preferences\n        )\n        if form.is_valid():\n            preferences = form.save()\n            if request.is_ajax():\n                return HttpResponse('true')\n            messages.success(request, 'Preferences saved')\n        elif request.is_ajax():\n            return HttpResponse('false')\n    else:\n        form = DashboardPreferencesForm(\n            user=request.user,\n            dashboard_id=dashboard_id,\n            instance=preferences\n        )\n    return render_to_response(\n        'admin_tools/dashboard/preferences_form.html',\n         {'form': form}\n    )",
    "docstring": "This view serves and validates a preferences form."
  },
  {
    "code": "def _strip_version_from_dependency(dep):\n    usedmark = ''\n    for mark in '< > ='.split():\n        split = dep.split(mark)\n        if len(split) > 1:\n            usedmark = mark\n            break\n    if usedmark:\n        return split[0].strip()\n    else:\n        return dep.strip()",
    "docstring": "For given dependency string, return only the package name"
  },
  {
    "code": "def get_invalid_mailbox(value, endchars):\n    invalid_mailbox = InvalidMailbox()\n    while value and value[0] not in endchars:\n        if value[0] in PHRASE_ENDS:\n            invalid_mailbox.append(ValueTerminal(value[0],\n                                                 'misplaced-special'))\n            value = value[1:]\n        else:\n            token, value = get_phrase(value)\n            invalid_mailbox.append(token)\n    return invalid_mailbox, value",
    "docstring": "Read everything up to one of the chars in endchars.\n\n    This is outside the formal grammar.  The InvalidMailbox TokenList that is\n    returned acts like a Mailbox, but the data attributes are None."
  },
  {
    "code": "def load_adjusted_array(self, domain, columns, dates, sids, mask):\n        if len(columns) != 1:\n            raise ValueError(\n                \"Can't load multiple columns with DataFrameLoader\"\n            )\n        column = columns[0]\n        self._validate_input_column(column)\n        date_indexer = self.dates.get_indexer(dates)\n        assets_indexer = self.assets.get_indexer(sids)\n        good_dates = (date_indexer != -1)\n        good_assets = (assets_indexer != -1)\n        data = self.baseline[ix_(date_indexer, assets_indexer)]\n        mask = (good_assets & as_column(good_dates)) & mask\n        data[~mask] = column.missing_value\n        return {\n            column: AdjustedArray(\n                data=data,\n                adjustments=self.format_adjustments(dates, sids),\n                missing_value=column.missing_value,\n            ),\n        }",
    "docstring": "Load data from our stored baseline."
  },
  {
    "code": "def template_str(tem, queue=False, **kwargs):\n    conflict = _check_queue(queue, kwargs)\n    if conflict is not None:\n        return conflict\n    opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)\n    try:\n        st_ = salt.state.State(opts,\n                               proxy=__proxy__,\n                               initial_pillar=_get_initial_pillar(opts))\n    except NameError:\n        st_ = salt.state.State(opts, initial_pillar=_get_initial_pillar(opts))\n    ret = st_.call_template_str(tem)\n    _set_retcode(ret)\n    return ret",
    "docstring": "Execute the information stored in a string from an sls template\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' state.template_str '<Template String>'"
  },
  {
    "code": "def pack(o, default=encode,\n         encoding='utf-8', unicode_errors='strict', use_single_float=False,\n         autoreset=1, use_bin_type=1):\n    return Packer(default=default, encoding=encoding,\n                  unicode_errors=unicode_errors,\n                  use_single_float=use_single_float,\n                  autoreset=autoreset,\n                  use_bin_type=use_bin_type).pack(o)",
    "docstring": "Pack an object and return the packed bytes."
  },
  {
    "code": "def update_global_variables_list_store(self):\n        self.list_store_iterators = {}\n        self.list_store.clear()\n        keys = self.model.global_variable_manager.get_all_keys()\n        keys.sort()\n        for key in keys:\n            iter = self.list_store.append([key,\n                                           self.model.global_variable_manager.get_data_type(key).__name__,\n                                           str(self.model.global_variable_manager.get_representation(key)),\n                                           str(self.model.global_variable_manager.is_locked(key)),\n                                           ])\n            self.list_store_iterators[key] = iter",
    "docstring": "Updates the global variable list store\n\n        Triggered after creation or deletion of a variable has taken place."
  },
  {
    "code": "def main():\n    parser = __build_option_parser()\n    args = parser.parse_args()\n    analyze_ws = AnalyzeWS(args)\n    try:\n        analyze_ws.set_file(args.file_[0])\n    except IOError:\n        print 'IOError raised while reading file. Exiting!'\n        sys.exit(3)\n    if args.to_file or args.to_browser:\n        analyze_ws.to_file_mode()\n        if args.to_browser:\n            analyze_ws.to_browser_mode()\n    else:\n        analyze_ws.interactive_mode()",
    "docstring": "Main method of the script"
  },
  {
    "code": "def Process(self, parser_mediator, **kwargs):\n    if kwargs:\n      raise ValueError('Unused keyword arguments: {0:s}.'.format(\n          ', '.join(kwargs.keys())))",
    "docstring": "Evaluates if this is the correct plugin and processes data accordingly.\n\n    The purpose of the process function is to evaluate if this particular\n    plugin is the correct one for the particular data structure at hand.\n    This function accepts one value to use for evaluation, that could be\n    a registry key, list of table names for a database or any other criteria\n    that can be used to evaluate if the plugin should be run or not.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between\n          parsers and other components, such as storage and dfvfs.\n      kwargs (dict[str, object]): Depending on the plugin they may require\n          different sets of arguments to be able to evaluate whether or not\n          this is the correct plugin.\n\n    Raises:\n      ValueError: when there are unused keyword arguments."
  },
  {
    "code": "def add(ctx, alias, mapping, backend):\n    if not backend:\n        backends_list = ctx.obj['settings'].get_backends()\n        if len(backends_list) > 1:\n            raise click.UsageError(\n                \"You're using more than 1 backend. Please set the backend to \"\n                \"add the alias to with the --backend option (choices are %s)\" %\n                \", \".join(dict(backends_list).keys())\n            )\n    add_mapping(ctx, alias, mapping, backend)",
    "docstring": "Add a new alias to your configuration file."
  },
  {
    "code": "def recompile(self, nick=None, new_nick=None, **kw):\n        if self.bot.nick == nick.nick:\n            self.bot.config['nick'] = new_nick\n            self.bot.recompile()",
    "docstring": "recompile regexp on new nick"
  },
  {
    "code": "def _get_account_number(self, token, uuid):\n        data = {\"accessToken\": token,\n                \"uuid\": uuid}\n        try:\n            raw_res = yield from self._session.post(ACCOUNT_URL,\n                                                    data=data,\n                                                    headers=self._headers,\n                                                    timeout=self._timeout)\n        except OSError:\n            raise PyFidoError(\"Can not get account number\")\n        try:\n            json_content = yield from raw_res.json()\n            account_number = json_content\\\n                            .get('getCustomerAccounts', {})\\\n                            .get('accounts', [{}])[0]\\\n                            .get('accountNumber')\n        except (OSError, ValueError):\n            raise PyFidoError(\"Bad json getting account number\")\n        if account_number is None:\n            raise PyFidoError(\"Can not get account number\")\n        return account_number",
    "docstring": "Get fido account number."
  },
  {
    "code": "def dump_as_json(record, output_file):\n    def default_func(value):\n        if isinstance(value, frozenset):\n            return sorted(value)\n        raise TypeError(repr(value) + \" is not JSON serializable\")\n    converted_record = record._replace(\n        ordered_statistics=[x._asdict() for x in record.ordered_statistics])\n    json.dump(\n        converted_record._asdict(), output_file,\n        default=default_func, ensure_ascii=False)\n    output_file.write(os.linesep)",
    "docstring": "Dump an relation record as a json value.\n\n    Arguments:\n        record -- A RelationRecord instance to dump.\n        output_file -- A file to output."
  },
  {
    "code": "def _PrintAnalysisStatusUpdateLinear(self, processing_status):\n    for worker_status in processing_status.workers_status:\n      status_line = (\n          '{0:s} (PID: {1:d}) - events consumed: {2:d} - running: '\n          '{3!s}\\n').format(\n              worker_status.identifier, worker_status.pid,\n              worker_status.number_of_consumed_events,\n              worker_status.status not in definitions.ERROR_STATUS_INDICATORS)\n      self._output_writer.Write(status_line)",
    "docstring": "Prints an analysis status update in linear mode.\n\n    Args:\n      processing_status (ProcessingStatus): processing status."
  },
  {
    "code": "def _get_id(self, file_path):\n        title = '%s._get_id' % self.__class__.__name__\n        list_kwargs = {\n            'spaces': self.drive_space,\n            'fields': 'files(id, parents)'\n        }\n        path_segments = file_path.split(os.sep)\n        parent_id = ''\n        empty_string = ''\n        while path_segments:\n            walk_query = \"name = '%s'\" % path_segments.pop(0)\n            if parent_id:\n                walk_query += \"and '%s' in parents\" % parent_id\n            list_kwargs['q'] = walk_query\n            try:\n                response = self.drive.list(**list_kwargs).execute()\n            except:\n                raise DriveConnectionError(title)\n            file_list = response.get('files', [])\n            if file_list:\n                if path_segments:\n                    parent_id = file_list[0].get('id')\n                else:\n                    file_id = file_list[0].get('id')\n                    return file_id, parent_id\n            else:\n                return empty_string, empty_string",
    "docstring": "a helper method for retrieving id of file or folder"
  },
  {
    "code": "def input_flush():\n    try:\n        import sys, termios\n        termios.tcflush(sys.stdin, termios.TCIFLUSH)\n    except ImportError:\n        import msvcrt\n        while msvcrt.kbhit():\n            msvcrt.getch()",
    "docstring": "Flush the input buffer on posix and windows."
  },
  {
    "code": "def extract_and_process(path_in, path_out):\n    path_in = os.path.realpath(os.path.expanduser(path_in))\n    path_out = os.path.realpath(os.path.expanduser(path_out))\n    extract_from_directory(path_in, path_out)\n    jsons = glob.glob(os.path.join(path_out, '*.jsonld'))\n    logger.info('Found %d JSON-LD files to process in %s' %\n                (len(jsons), path_out))\n    stmts = []\n    for json in jsons:\n        ep = process_json_file(json)\n        if ep:\n            stmts += ep.statements\n    return stmts",
    "docstring": "Run Eidos on a set of text files and process output with INDRA.\n\n    The output is produced in the specified output folder but\n    the output files aren't processed by this function.\n\n    Parameters\n    ----------\n    path_in : str\n        Path to an input folder with some text files\n    path_out : str\n        Path to an output folder in which Eidos places the output\n        JSON-LD files\n\n    Returns\n    -------\n    stmts : list[indra.statements.Statements]\n        A list of INDRA Statements"
  },
  {
    "code": "def send_remote_port(self):\r\n        msg = \"REMOTE TCP %s\" % (str(self.transport.getPeer().port))\r\n        self.send_line(msg)",
    "docstring": "Sends the remote port mapped for the connection.\r\n        This port is surprisingly often the same as the locally\r\n        bound port for an endpoint because a lot of NAT types\r\n        preserve the port."
  },
  {
    "code": "def register_introspection_functions(self):\n        self.funcs.update({'system.listMethods' : self.system_listMethods,\n                      'system.methodSignature' : self.system_methodSignature,\n                      'system.methodHelp' : self.system_methodHelp})",
    "docstring": "Registers the XML-RPC introspection methods in the system\n        namespace.\n\n        see http://xmlrpc.usefulinc.com/doc/reserved.html"
  },
  {
    "code": "def get_networks(self):\n        networks = self.c_resources[\"networks\"]\n        result = []\n        for net in networks:\n            _c_network = net.get(\"_c_network\")\n            if _c_network is None:\n                continue\n            roles = utils.get_roles_as_list(net)\n            result.append((roles, _c_network))\n        return result",
    "docstring": "Get the networks assoiated with the resource description.\n\n        Returns\n            list of tuple roles, network"
  },
  {
    "code": "def _set_batch(self, batch, fg, bg, bgblend=1, nullChar=False):\n        for (x, y), char in batch:\n            self._set_char(x, y, char, fg, bg, bgblend)",
    "docstring": "Try to perform a batch operation otherwise fall back to _set_char.\n        If fg and bg are defined then this is faster but not by very\n        much.\n\n        if any character is None then nullChar is True\n\n        batch is a iterable of [(x, y), ch] items"
  },
  {
    "code": "def make_opfields( cls ):\n        opfields = {}\n        for opname in SERIALIZE_FIELDS.keys():\n            opcode = NAME_OPCODES[opname]\n            opfields[opcode] = SERIALIZE_FIELDS[opname]\n        return opfields",
    "docstring": "Calculate the virtulachain-required opfields dict."
  },
  {
    "code": "def _render_timestep(self,\n            t: int,\n            s: Fluents, a: Fluents, f: Fluents,\n            r: np.float32) -> None:\n        print(\"============================\")\n        print(\"TIME = {}\".format(t))\n        print(\"============================\")\n        fluent_variables = self._compiler.rddl.action_fluent_variables\n        self._render_fluent_timestep('action', a, fluent_variables)\n        fluent_variables = self._compiler.rddl.interm_fluent_variables\n        self._render_fluent_timestep('interms', f, fluent_variables)\n        fluent_variables = self._compiler.rddl.state_fluent_variables\n        self._render_fluent_timestep('states', s, fluent_variables)\n        self._render_reward(r)",
    "docstring": "Prints fluents and rewards for the given timestep `t`.\n\n        Args:\n            t (int): timestep\n            s (Sequence[Tuple[str], np.array]: State fluents.\n            a (Sequence[Tuple[str], np.array]: Action fluents.\n            f (Sequence[Tuple[str], np.array]: Interm state fluents.\n            r (np.float32): Reward."
  },
  {
    "code": "def read_static_uplink(self):\n        if self.node_list is None or self.node_uplink_list is None:\n            return\n        for node, port in zip(self.node_list.split(','),\n                              self.node_uplink_list.split(',')):\n            if node.strip() == self.host_name:\n                self.static_uplink = True\n                self.static_uplink_port = port.strip()\n                return",
    "docstring": "Read the static uplink from file, if given."
  },
  {
    "code": "def _activity_helper(modifier: str, location=None):\n    rv = {MODIFIER: modifier}\n    if location:\n        rv[LOCATION] = location\n    return rv",
    "docstring": "Make an activity dictionary.\n\n    :param str modifier:\n    :param Optional[dict] location: An entity from :func:`pybel.dsl.entity`\n    :rtype: dict"
  },
  {
    "code": "def get_mentions(self, *args, **kwargs):\n        return self.get_content(self.config['mentions'], *args, **kwargs)",
    "docstring": "Return a get_content generator for username mentions.\n\n        The additional parameters are passed directly into\n        :meth:`.get_content`. Note: the `url` parameter cannot be altered."
  },
  {
    "code": "def directly_connected(self, ident):\n        content_id, subtopic_id = normalize_ident(ident)\n        return self.everything(include_deleted=False,\n                               content_id=content_id,\n                               subtopic_id=subtopic_id)",
    "docstring": "Return a generator of labels connected to ``ident``.\n\n        ``ident`` may be a ``content_id`` or a ``(content_id,\n        subtopic_id)``.\n\n        If no labels are defined for ``ident``, then the generator\n        will yield no labels.\n\n        Note that this only returns *directly* connected labels. It\n        will not follow transitive relationships.\n\n        :param ident: content id or (content id and subtopic id)\n        :type ident: ``str`` or ``(str, str)``\n        :rtype: generator of :class:`Label`"
  },
  {
    "code": "def _has_terms(self):\n        loc = self._super_get('_term_location')\n        return self._super_has(loc) \\\n               and isiterable(self._super_get(loc)) \\\n               and len(self._super_get(loc)) > 0 \\\n               and all([isinstance(term, Term) for term in self._super_get(loc)])",
    "docstring": "bool, whether the instance has any sub-terms"
  },
  {
    "code": "def shell_call(self, shellcmd):\n        return(subprocess.call(self.shellsetup + shellcmd, shell=True))",
    "docstring": "Shell call with necessary setup first."
  },
  {
    "code": "def delete_stream(stream_name, region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    r = _execute_with_retries(conn,\n                              \"delete_stream\",\n                              StreamName=stream_name)\n    if 'error' not in r:\n        r['result'] = True\n    return r",
    "docstring": "Delete the stream with name stream_name. This cannot be undone! All data will be lost!!\n\n    CLI example::\n\n        salt myminion boto_kinesis.delete_stream my_stream region=us-east-1"
  },
  {
    "code": "def call(cmd_args, suppress_output=False):\n    if not funcy.is_list(cmd_args) and not funcy.is_tuple(cmd_args):\n        cmd_args = shlex.split(cmd_args)\n    logger.info('executing `{}`'.format(' '.join(cmd_args)))\n    call_request = CallRequest(cmd_args, suppress_output=suppress_output)\n    call_result = call_request.run()\n    if call_result.exitval:\n        logger.error('`{}` returned error code {}'.format(' '.join(cmd_args), call_result.exitval))\n    return call_result",
    "docstring": "Call an arbitary command and return the exit value, stdout, and stderr as a tuple\n\n    Command can be passed in as either a string or iterable\n\n    >>> result = call('hatchery', suppress_output=True)\n    >>> result.exitval\n    0\n    >>> result = call(['hatchery', 'notreal'])\n    >>> result.exitval\n    1"
  },
  {
    "code": "def get_commands_in_namespace(namespace=None, level=1):\n    from ..command import Command\n    commands = {}\n    if namespace is None:\n        frame = inspect.stack()[level][0]\n        namespace = frame.f_globals\n    elif inspect.ismodule(namespace):\n        namespace = vars(namespace)\n    for name in namespace:\n        obj = namespace[name]\n        if isinstance(obj, Command):\n            commands[name] = obj\n    return OrderedDict((name, commands[name]) for name in sorted(commands))",
    "docstring": "Get commands in namespace.\n\n    Args:\n        namespace (dict|module): Typically a module. If not passed, the\n            globals from the call site will be used.\n        level (int): If not called from the global scope, set this\n            appropriately to account for the call stack.\n\n    Returns:\n        OrderedDict: The commands found in the namespace, ordered by\n            name.\n\n    Can be used to create ``__all__`` lists::\n\n        __all__ = list(get_commands_in_namespace())"
  },
  {
    "code": "def reduce_list_of_bags_of_words(list_of_keyword_sets):\n    bag_of_words = dict()\n    get_bag_of_words_keys = bag_of_words.keys\n    for keyword_set in list_of_keyword_sets:\n        for keyword in keyword_set:\n            if keyword in get_bag_of_words_keys():\n                bag_of_words[keyword] += 1\n            else:\n                bag_of_words[keyword] = 1\n    return bag_of_words",
    "docstring": "Reduces a number of keyword sets to a bag-of-words.\n\n    Input:  - list_of_keyword_sets: This is a python list of sets of strings.\n\n    Output: - bag_of_words: This is the corresponding multi-set or bag-of-words, in the form of a python dictionary."
  },
  {
    "code": "def add_metadata_query_properties(self, meta_constraints, id_table, id_column):\n        for mc in meta_constraints:\n            meta_key = str(mc.key)\n            ct = mc.constraint_type\n            sql_template =\n            self.sql_args.append(SQLBuilder.map_value(mc.value))\n            self.sql_args.append(meta_key)\n            if ct == 'less':\n                self.where_clauses.append(sql_template.format(id_table, id_column, 'floatValue', '<='))\n            elif ct == 'greater':\n                self.where_clauses.append(sql_template.format(id_table, id_column, 'floatValue', '>='))\n            elif ct == 'number_equals':\n                self.where_clauses.append(sql_template.format(id_table, id_column, 'floatValue', '='))\n            elif ct == 'string_equals':\n                self.where_clauses.append(sql_template.format(id_table, id_column, 'stringValue', '='))\n            else:\n                raise ValueError(\"Unknown meta constraint type!\")",
    "docstring": "Construct WHERE clauses from a list of MetaConstraint objects, adding them to the query state.\n\n        :param meta_constraints:\n            A list of MetaConstraint objects, each of which defines a condition over metadata which must be satisfied\n            for results to be included in the overall query.\n        :raises:\n            ValueError if an unknown meta constraint type is encountered."
  },
  {
    "code": "def contains_circle(self, pt, radius):\n    return (self.l < pt.x - radius and self.r > pt.x + radius and\n            self.t < pt.y - radius and self.b > pt.y + radius)",
    "docstring": "Is the circle completely inside this rect?"
  },
  {
    "code": "def read_sps(path):\n    for line in open(path):\n        xs = line.rstrip().split(' ')\n        yield xs[1:], int(xs[0])",
    "docstring": "Read a LibSVM file line-by-line.\n\n    Args:\n        path (str): A path to the LibSVM file to read.\n\n    Yields:\n        data (list) and target (int)."
  },
  {
    "code": "def format_unencoded(self, tokensource, outfile):\n        source = self._format_lines(tokensource)\n        if self.hl_lines:\n            source = self._highlight_lines(source)\n        if not self.nowrap:\n            if self.linenos == 2:\n                source = self._wrap_inlinelinenos(source)\n            if self.lineanchors:\n                source = self._wrap_lineanchors(source)\n            if self.linespans:\n                source = self._wrap_linespans(source)\n            source = self.wrap(source, outfile)\n            if self.linenos == 1:\n                source = self._wrap_tablelinenos(source)\n            if self.full:\n                source = self._wrap_full(source, outfile)\n        for t, piece in source:\n            outfile.write(piece)",
    "docstring": "The formatting process uses several nested generators; which of\n        them are used is determined by the user's options.\n\n        Each generator should take at least one argument, ``inner``,\n        and wrap the pieces of text generated by this.\n\n        Always yield 2-tuples: (code, text). If \"code\" is 1, the text\n        is part of the original tokensource being highlighted, if it's\n        0, the text is some piece of wrapping. This makes it possible to\n        use several different wrappers that process the original source\n        linewise, e.g. line number generators."
  },
  {
    "code": "def is_node(objecttype):\n    if not isclass(objecttype):\n        return False\n    if not issubclass(objecttype, ObjectType):\n        return False\n    for i in objecttype._meta.interfaces:\n        if issubclass(i, Node):\n            return True\n    return False",
    "docstring": "Check if the given objecttype has Node as an interface"
  },
  {
    "code": "def includeme(config):\n    root = config.get_root_resource()\n    root.add('nef_polymorphic', '{collections:.+,.+}',\n             view=PolymorphicESView,\n             factory=PolymorphicACL)",
    "docstring": "Connect view to route that catches all URIs like\n    'something,something,...'"
  },
  {
    "code": "def _order_pases(self, passes):\n        passes = set(passes)\n        pass_deps = {}\n        for opt in passes:\n            _, before, after = self._known_passes[opt]\n            if opt not in pass_deps:\n                pass_deps[opt] = set()\n            for after_pass in after:\n                pass_deps[opt].add(after_pass)\n            for other in before:\n                if other not in passes:\n                    continue\n                if other not in pass_deps:\n                    pass_deps[other] = set()\n                pass_deps[other].add(opt)\n        return toposort_flatten(pass_deps)",
    "docstring": "Topologically sort optimization passes.\n\n        This ensures that the resulting passes are run in order\n        respecting before/after constraints.\n\n        Args:\n            passes (iterable): An iterable of pass names that should\n                be included in the optimization passes run."
  },
  {
    "code": "def _execute_cmd(plugin, args='', run_type='cmd.retcode'):\n    data = {}\n    all_plugins = list_plugins()\n    if plugin in all_plugins:\n        data = __salt__[run_type](\n                '{0}{1} {2}'.format(PLUGINDIR, plugin, args),\n                python_shell=False)\n    return data",
    "docstring": "Execute nagios plugin if it's in the directory with salt command specified in run_type"
  },
  {
    "code": "def get_proxies(self, url):\n        hostname = urlparse(url).hostname\n        if hostname is None:\n            hostname = \"\"\n        value_from_js_func = self.pac.find_proxy_for_url(url, hostname)\n        if value_from_js_func in self._cache:\n            return self._cache[value_from_js_func]\n        config_values = parse_pac_value(self.pac.find_proxy_for_url(url, hostname), self.socks_scheme)\n        if self._proxy_auth:\n            config_values = [add_proxy_auth(value, self._proxy_auth) for value in config_values]\n        self._cache[value_from_js_func] = config_values\n        return config_values",
    "docstring": "Get the proxies that are applicable to a given URL, according to the PAC file.\n\n        :param str url: The URL for which to find appropriate proxies.\n        :return: All the proxies that apply to the given URL.\n            Can be empty, which means to abort the request.\n        :rtype: list[str]"
  },
  {
    "code": "def ApproximateDistanceBetweenPoints(pa, pb):\n  alat, alon = pa\n  blat, blon = pb\n  sa = transitfeed.Stop(lat=alat, lng=alon)\n  sb = transitfeed.Stop(lat=blat, lng=blon)\n  return transitfeed.ApproximateDistanceBetweenStops(sa, sb)",
    "docstring": "Finds the distance between two points on the Earth's surface.\n\n  This is an approximate distance based on assuming that the Earth is a sphere.\n  The points are specified by their lattitude and longitude.\n\n  Args:\n    pa: the first (lat, lon) point tuple\n    pb: the second (lat, lon) point tuple\n\n  Returns:\n    The distance as a float in metres."
  },
  {
    "code": "def img_binary_list():\n        qemu_imgs = []\n        for path in Qemu.paths_list():\n            try:\n                for f in os.listdir(path):\n                    if (f == \"qemu-img\" or f == \"qemu-img.exe\") and \\\n                            os.access(os.path.join(path, f), os.X_OK) and \\\n                            os.path.isfile(os.path.join(path, f)):\n                        qemu_path = os.path.join(path, f)\n                        version = yield from Qemu._get_qemu_img_version(qemu_path)\n                        qemu_imgs.append({\"path\": qemu_path, \"version\": version})\n            except OSError:\n                continue\n        return qemu_imgs",
    "docstring": "Gets QEMU-img binaries list available on the host.\n\n        :returns: Array of dictionary {\"path\": Qemu-img binary path, \"version\": version of Qemu-img}"
  },
  {
    "code": "def frameify(self, state, data):\n        data = state.recv_buf + data\n        while data:\n            line, sep, rest = data.partition('\\n')\n            if sep != '\\n':\n                break\n            data = rest\n            if self.carriage_return and line[-1] == '\\r':\n                line = line[:-1]\n            try:\n                yield line\n            except FrameSwitch:\n                break\n        state.recv_buf = data",
    "docstring": "Split data into a sequence of lines."
  },
  {
    "code": "def get_mutations_size(self):\n        mutation_size = 0\n        for mutation in self._get_mutations():\n            mutation_size += mutation.ByteSize()\n        return mutation_size",
    "docstring": "Gets the total mutations size for current row\n\n        For example:\n\n        .. literalinclude:: snippets_table.py\n            :start-after: [START bigtable_row_get_mutations_size]\n            :end-before: [END bigtable_row_get_mutations_size]"
  },
  {
    "code": "def within_depth_range(self, lower_depth=None, upper_depth=None):\n        if not lower_depth:\n            if not upper_depth:\n                return self.catalogue\n            else:\n                lower_depth = np.inf\n        if not upper_depth:\n            upper_depth = 0.0\n        is_valid = np.logical_and(self.catalogue.data['depth'] >= upper_depth,\n                                  self.catalogue.data['depth'] < lower_depth)\n        return self.select_catalogue(is_valid)",
    "docstring": "Selects events within a specified depth range\n\n        :param float lower_depth:\n            Lower depth for consideration\n\n        :param float upper_depth:\n            Upper depth for consideration\n\n        :returns:\n            Instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue`\n            containing only selected events"
  },
  {
    "code": "def save_excel(self, fd):\n        from pylon.io.excel import ExcelWriter\n        ExcelWriter(self).write(fd)",
    "docstring": "Saves the case as an Excel spreadsheet."
  },
  {
    "code": "def confusion_matrix(\n    gold, pred, null_pred=False, null_gold=False, normalize=False, pretty_print=True\n):\n    conf = ConfusionMatrix(null_pred=null_pred, null_gold=null_gold)\n    gold = arraylike_to_numpy(gold)\n    pred = arraylike_to_numpy(pred)\n    conf.add(gold, pred)\n    mat = conf.compile()\n    if normalize:\n        mat = mat / len(gold)\n    if pretty_print:\n        conf.display(normalize=normalize)\n    return mat",
    "docstring": "A shortcut method for building a confusion matrix all at once.\n\n    Args:\n        gold: an array-like of gold labels (ints)\n        pred: an array-like of predictions (ints)\n        null_pred: If True, include the row corresponding to null predictions\n        null_gold: If True, include the col corresponding to null gold labels\n        normalize: if True, divide counts by the total number of items\n        pretty_print: if True, pretty-print the matrix before returning"
  },
  {
    "code": "def full_name_natural_split(full_name):\n    parts = full_name.strip().split(' ')\n    first_name = \"\"\n    if parts:\n        first_name = parts.pop(0)\n    if first_name.lower() == \"el\" and parts:\n        first_name += \" \" + parts.pop(0)\n    last_name = \"\"\n    if parts:\n        last_name = parts.pop()\n    if (last_name.lower() == 'i' or last_name.lower() == 'ii'\n        or last_name.lower() == 'iii' and parts):\n        last_name = parts.pop() + \" \" + last_name\n    middle_initials = \"\"\n    for middle_name in parts:\n        if middle_name:\n            middle_initials += middle_name[0]\n    return first_name, middle_initials, last_name",
    "docstring": "This function splits a full name into a natural first name, last name\n    and middle initials."
  },
  {
    "code": "def open_browser(url: str, browser: str = None) -> None:\n    if '--open-browser' in sys.argv:\n        sys.argv.remove('--open-browser')\n    if browser is None:\n        browser = config.browser\n    if browser in _browsers:\n        webbrowser.get(browser).open(url)\n    else:\n        webbrowser.open(url)",
    "docstring": "Open web browser."
  },
  {
    "code": "def get_curve(self, mnemonic, alias=None):\n        return self.data.get(self.get_mnemonic(mnemonic, alias=alias), None)",
    "docstring": "Wraps get_mnemonic.\n\n        Instead of picking curves by name directly from the data dict, you\n        can pick them up with this method, which takes account of the alias\n        dict you pass it. If you do not pass an alias dict, then you get the\n        curve you asked for, if it exists, or None. NB Wells do not have alias\n        dicts, but Projects do.\n\n        Args:\n            mnemonic (str): the name of the curve you want.\n            alias (dict): an alias dictionary, mapping mnemonics to lists of\n                mnemonics.\n\n        Returns:\n            Curve."
  },
  {
    "code": "def calculate_iI_correspondence(omega):\n    r\n    Ne = len(omega[0])\n    om = omega[0][0]\n    correspondence = []\n    I = 0\n    for i in range(Ne):\n        if omega[i][0] != om:\n            om = omega[i][0]\n            I += 1\n        correspondence += [(i+1, I+1)]\n    Nnd = I+1\n    def I_nd(i):\n        return correspondence[i-1][1]\n    def i_d(I):\n        for i in range(Ne):\n            if correspondence[i][1] == I:\n                return correspondence[i][0]\n    return i_d, I_nd, Nnd",
    "docstring": "r\"\"\"Get the correspondance between degenerate and nondegenerate schemes."
  },
  {
    "code": "def set(self, key, value):\n        return self.__setitem__(key, value, force=True)",
    "docstring": "Set a key's value regardless of whether a change is seen."
  },
  {
    "code": "def _create_feed_dict(self, data):\n        return {\n            self.input_data: data,\n            self.hrand: np.random.rand(data.shape[0], self.num_hidden),\n            self.vrand: np.random.rand(data.shape[0], data.shape[1])\n        }",
    "docstring": "Create the dictionary of data to feed to tf session during training.\n\n        :param data: training/validation set batch\n        :return: dictionary(self.input_data: data, self.hrand: random_uniform,\n                            self.vrand: random_uniform)"
  },
  {
    "code": "def expected_counts(p0, T, N):\n    r\n    if (N <= 0):\n        EC = coo_matrix(T.shape, dtype=float)\n        return EC\n    else:\n        p_k = 1.0 * p0\n        p_sum = 1.0 * p_k\n        Tt = T.transpose()\n        for k in np.arange(N - 1):\n            p_k = Tt.dot(p_k)\n            p_sum += p_k\n        D_psum = diags(p_sum, 0)\n        EC = D_psum.dot(T)\n        return EC",
    "docstring": "r\"\"\"Compute expected transition counts for Markov chain after N steps.\n\n    Expected counts are computed according to ..math::\n\n    E[C_{ij}^{(n)}]=\\sum_{k=0}^{N-1} (p_0^T T^{k})_{i} p_{ij}\n\n    Parameters\n    ----------\n    p0 : (M,) ndarray\n        Starting (probability) vector of the chain.\n    T : (M, M) sparse matrix\n        Transition matrix of the chain.\n    N : int\n        Number of steps to take from initial state.\n\n    Returns\n    --------\n    EC : (M, M) sparse matrix\n        Expected value for transition counts after N steps."
  },
  {
    "code": "def _add_colorbar(ax: Axes, cmap: colors.Colormap, cmap_data: np.ndarray, norm: colors.Normalize):\n    fig = ax.get_figure()\n    mappable = cm.ScalarMappable(cmap=cmap, norm=norm)\n    mappable.set_array(cmap_data)\n    fig.colorbar(mappable, ax=ax)",
    "docstring": "Show a colorbar right of the plot."
  },
  {
    "code": "def visit_tryfinally(self, node, parent):\n        newnode = nodes.TryFinally(node.lineno, node.col_offset, parent)\n        newnode.postinit(\n            [self.visit(child, newnode) for child in node.body],\n            [self.visit(n, newnode) for n in node.finalbody],\n        )\n        return newnode",
    "docstring": "visit a TryFinally node by returning a fresh instance of it"
  },
  {
    "code": "def raw_mode():\n    if WIN:\n        yield\n    else:\n        import tty\n        import termios\n        if not isatty(sys.stdin):\n            f = open(\"/dev/tty\")\n            fd = f.fileno()\n        else:\n            fd = sys.stdin.fileno()\n            f = None\n        try:\n            old_settings = termios.tcgetattr(fd)\n            tty.setraw(fd)\n        except termios.error:\n            pass\n        try:\n            yield\n        finally:\n            try:\n                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n                if f is not None:\n                    f.close()\n            except termios.error:\n                pass",
    "docstring": "Enables terminal raw mode during the context.\n\n    Note: Currently noop for Windows systems.\n\n    Usage: ::\n\n        with raw_mode():\n            do_some_stuff()"
  },
  {
    "code": "def _printTraceback(self, test, err):\n        exception_type, exception_value = err[:2]\n        extracted_tb = extract_relevant_tb(\n            err[2],\n            exception_type,\n            exception_type is test.failureException)\n        test_frame_index = index_of_test_frame(\n            extracted_tb,\n            exception_type,\n            exception_value,\n            test)\n        if test_frame_index:\n            extracted_tb = extracted_tb[test_frame_index:]\n        with self.bar.dodging():\n            self.stream.write(''.join(\n                format_traceback(\n                    extracted_tb,\n                    exception_type,\n                    exception_value,\n                    self._cwd,\n                    self._term,\n                    self._options.function_color,\n                    self._options.dim_color,\n                    self._options.editor,\n                    self._options.editor_shortcut_template)))",
    "docstring": "Print a nicely formatted traceback.\n\n        :arg err: exc_info()-style traceback triple\n        :arg test: the test that precipitated this call"
  },
  {
    "code": "def amplification_circuit(algorithm: Program, oracle: Program,\n                          qubits: List[int],\n                          num_iter: int,\n                          decompose_diffusion: bool = False) -> Program:\n    program = Program()\n    uniform_superimposer = Program().inst([H(qubit) for qubit in qubits])\n    program += uniform_superimposer\n    if decompose_diffusion:\n        diffusion = decomposed_diffusion_program(qubits)\n    else:\n        diffusion = diffusion_program(qubits)\n    defined_gates = oracle.defined_gates + algorithm.defined_gates + diffusion.defined_gates\n    for _ in range(num_iter):\n        program += (oracle.instructions\n                 + algorithm.dagger().instructions\n                 + diffusion.instructions\n                 + algorithm.instructions)\n    for gate in defined_gates:\n        program.defgate(gate.name, gate.matrix)\n    return program",
    "docstring": "Returns a program that does ``num_iter`` rounds of amplification, given a measurement-less\n    algorithm, an oracle, and a list of qubits to operate on.\n\n    :param algorithm: A program representing a measurement-less algorithm run on qubits.\n    :param oracle: An oracle maps any basis vector ``|psi>`` to either ``+|psi>`` or\n        ``-|psi>`` depending on whether ``|psi>`` is in the desirable subspace or the undesirable\n        subspace.\n    :param qubits: the qubits to operate on\n    :param num_iter: number of iterations of amplifications to run\n    :param decompose_diffusion: If True, decompose the Grover diffusion gate into two qubit\n     gates. If False, use a defgate to define the gate.\n    :return: The amplified algorithm."
  },
  {
    "code": "def _waitForSSHPort(self):\n        logger.debug('Waiting for ssh port to open...')\n        for i in count():\n            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n            try:\n                s.settimeout(a_short_time)\n                s.connect((self.effectiveIP, 22))\n                logger.debug('...ssh port open')\n                return i\n            except socket.error:\n                pass\n            finally:\n                s.close()",
    "docstring": "Wait until the instance represented by this box is accessible via SSH.\n\n        :return: the number of unsuccessful attempts to connect to the port before a the first\n        success"
  },
  {
    "code": "def remap_overlapping_column_names(table_op, root_table, data_columns):\n    if not isinstance(table_op, ops.Join):\n        return None\n    left_root, right_root = ops.distinct_roots(table_op.left, table_op.right)\n    suffixes = {\n        left_root: constants.LEFT_JOIN_SUFFIX,\n        right_root: constants.RIGHT_JOIN_SUFFIX,\n    }\n    column_names = [\n        ({name, name + suffixes[root_table]} & data_columns, name)\n        for name in root_table.schema.names\n    ]\n    mapping = OrderedDict(\n        (first(col_name), final_name)\n        for col_name, final_name in column_names\n        if col_name\n    )\n    return mapping",
    "docstring": "Return an ``OrderedDict`` mapping possibly suffixed column names to\n    column names without suffixes.\n\n    Parameters\n    ----------\n    table_op : TableNode\n        The ``TableNode`` we're selecting from.\n    root_table : TableNode\n        The root table of the expression we're selecting from.\n    data_columns : set or frozenset\n        The available columns to select from\n\n    Returns\n    -------\n    mapping : OrderedDict[str, str]\n        A map from possibly-suffixed column names to column names without\n        suffixes."
  },
  {
    "code": "def write_molecule(filename, format=None):\n    datafile(filename, format=format,\n             mode='w').write('molecule',current_system())",
    "docstring": "Write the system displayed in a file as a molecule."
  },
  {
    "code": "def mime_type(self, path):\n        name, ext = os.path.splitext(path)\n        return MIME_TYPES[ext]",
    "docstring": "Get mime-type from filename"
  },
  {
    "code": "def check_verifier(self, verifier):\n        lower, upper = self.verifier_length\n        return (set(verifier) <= self.safe_characters and\n                lower <= len(verifier) <= upper)",
    "docstring": "Checks that the verifier contains only safe characters\n        and is no shorter than lower and no longer than upper."
  },
  {
    "code": "def get_export_configuration(self, config_id):\n        sql = (\n            'SELECT uid, exportConfigId, exportType, searchString, targetURL, '\n            'targetUser, targetPassword, exportName, description, active '\n            'FROM archive_exportConfig WHERE exportConfigId = %s')\n        return first_from_generator(\n                self.generators.export_configuration_generator(sql=sql, sql_args=(config_id,)))",
    "docstring": "Retrieve the ExportConfiguration with the given ID\n\n        :param string config_id:\n            ID for which to search\n        :return:\n            a :class:`meteorpi_model.ExportConfiguration` or None, or no match was found."
  },
  {
    "code": "def received_message(self, m):\n        m = str(m)\n        logger.debug(\"Incoming upstream WS: %s\", m)\n        uwsgi.websocket_send(m)\n        logger.debug(\"Send ok\")",
    "docstring": "Push upstream messages to downstream."
  },
  {
    "code": "def determine_emitter(cls, request):\n        default_emitter = cls._meta.emitters[0]\n        if not request:\n            return default_emitter\n        if request.method == 'OPTIONS':\n            return JSONEmitter\n        accept = request.META.get('HTTP_ACCEPT', '*/*')\n        if accept == '*/*':\n            return default_emitter\n        base_format = mimeparse.best_match(cls._meta.emitters_dict.keys(),\n                                           accept)\n        return cls._meta.emitters_dict.get(\n            base_format,\n            default_emitter)",
    "docstring": "Get emitter for request.\n\n        :return emitter: Instance of adrest.utils.emitters.BaseEmitter"
  },
  {
    "code": "def add_list(self, bl):\n        if self.cur_element is None:\n            self.add_text_frame()\n        self.push_element()\n        self.cur_element._text_box.append(bl.node)\n        style = bl.style_name\n        if style not in self._preso._styles_added:\n            self._preso._styles_added[style] = 1\n            content = bl.default_styles_root()[0]\n            self._preso._auto_styles.append(content)\n        self.cur_element = bl",
    "docstring": "note that this pushes the cur_element, but doesn't pop it.\n        You'll need to do that"
  },
  {
    "code": "def _update_card_file_location(self, card_name, new_directory):\n        with tmp_chdir(self.gssha_directory):\n            file_card = self.project_manager.getCard(card_name)\n            if file_card:\n                if file_card.value:\n                    original_location = file_card.value.strip(\"'\").strip('\"')\n                    new_location = os.path.join(new_directory,\n                                                os.path.basename(original_location))\n                    file_card.value = '\"{0}\"'.format(os.path.basename(original_location))\n                    try:\n                        move(original_location, new_location)\n                    except OSError as ex:\n                        log.warning(ex)\n                        pass",
    "docstring": "Moves card to new gssha working directory"
  },
  {
    "code": "def iter_generic_bases(type_):\n    for t in type_.__mro__:\n        if not isinstance(t, typing.GenericMeta):\n            continue\n        yield t\n        t = t.__origin__\n        while t:\n            yield t\n            t = t.__origin__",
    "docstring": "Iterates over all generics `type_` derives from, including origins.\n\n    This function is only necessary because, in typing 3.5.0, a generic doesn't\n    get included in the list of bases when it constructs a parameterized version\n    of itself. This was fixed in aab2c59; now it would be enough to just iterate\n    over the MRO."
  },
  {
    "code": "def resolve_deps(self, obj):\n        deps = self.get_deps(obj)\n        return list(self.iresolve(*deps))",
    "docstring": "Returns list of resolved dependencies for given obj.\n\n        :param obj: Object to lookup dependencies for\n        :type obj: object\n        :return: Resolved dependencies\n        :rtype: list"
  },
  {
    "code": "def authenticate(self, username, password):\n        if username is None or password is None:\n            return False\n        if not re.match(\"^[A-Za-z0-9_-]*$\", username):\n            return False\n        user_dn = self.get_user_dn(username)\n        server = ldap3.Server(\n                self.uri,\n                use_ssl=self.use_ssl\n            )\n        connection = ldap3.Connection(server, user=user_dn, password=password)\n        return connection.bind()",
    "docstring": "Authenticate the user with a bind on the LDAP server"
  },
  {
    "code": "def class_name_to_resource_name(class_name: str) -> str:\n    s = re.sub('(.)([A-Z][a-z]+)', r'\\1 \\2', class_name)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1 \\2', s)",
    "docstring": "Converts a camel case class name to a resource name with spaces.\n\n    >>> class_name_to_resource_name('FooBarObject')\n    'Foo Bar Object'\n\n    :param class_name: The name to convert.\n    :returns: The resource name."
  },
  {
    "code": "def _run_argparser(self, argv):\n        if self._parser is None:\n            raise ValueError('Link was not given a parser on initialization')\n        args = self._parser.parse_args(argv)\n        self.update_args(args.__dict__)\n        return args",
    "docstring": "Initialize a link with a set of arguments using an `argparser.ArgumentParser`"
  },
  {
    "code": "def secret_absent(name, namespace='default', **kwargs):\n    ret = {'name': name,\n           'changes': {},\n           'result': False,\n           'comment': ''}\n    secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs)\n    if secret is None:\n        ret['result'] = True if not __opts__['test'] else None\n        ret['comment'] = 'The secret does not exist'\n        return ret\n    if __opts__['test']:\n        ret['comment'] = 'The secret is going to be deleted'\n        ret['result'] = None\n        return ret\n    __salt__['kubernetes.delete_secret'](name, namespace, **kwargs)\n    ret['result'] = True\n    ret['changes'] = {\n        'kubernetes.secret': {\n            'new': 'absent', 'old': 'present'}}\n    ret['comment'] = 'Secret deleted'\n    return ret",
    "docstring": "Ensures that the named secret is absent from the given namespace.\n\n    name\n        The name of the secret\n\n    namespace\n        The name of the namespace"
  },
  {
    "code": "def from_raw_message(cls, rawmessage):\n        empty = cls.create_empty(0x00)\n        userdata_dict = cls.normalize(empty, rawmessage)\n        return Userdata(userdata_dict)",
    "docstring": "Create a user data instance from a raw byte stream."
  },
  {
    "code": "def update(self, batch_size, ignore_stale_grad=False):\n        if not self._kv_initialized:\n            self._init_kvstore()\n        if self._params_to_init:\n            self._init_params()\n        assert not (self._kvstore and self._update_on_kvstore), \\\n                'update() when parameters are updated on kvstore ' \\\n                'is not supported. Try setting `update_on_kvstore` ' \\\n                'to False when creating trainer.'\n        self._check_and_rescale_grad(self._scale / batch_size)\n        self._update(ignore_stale_grad)",
    "docstring": "Makes one step of parameter update.\n\n        Should be called after `autograd.backward()` and outside of `record()` scope,\n        and after `trainer.update()`.\n\n\n        For normal parameter updates, `step()` should be used, which internally calls\n        `allreduce_grads()` and then `update()`. However, if you need to get the reduced\n        gradients to perform certain transformation, such as in gradient clipping, then\n        you may want to manually call `allreduce_grads()` and `update()` separately.\n\n        Parameters\n        ----------\n        batch_size : int\n            Batch size of data processed. Gradient will be normalized by `1/batch_size`.\n            Set this to 1 if you normalized loss manually with `loss = mean(loss)`.\n        ignore_stale_grad : bool, optional, default=False\n            If true, ignores Parameters with stale gradient (gradient that has not\n            been updated by `backward` after last step) and skip update."
  },
  {
    "code": "def get_entry(user, identifier=None, cmd=None):\n    cron_entries = list_tab(user).get('crons', False)\n    for cron_entry in cron_entries:\n        if identifier and cron_entry.get('identifier') == identifier:\n            return cron_entry\n        elif cmd and cron_entry.get('cmd') == cmd:\n            return cron_entry\n    return False",
    "docstring": "Return the specified entry from user's crontab.\n    identifier will be used if specified, otherwise will lookup cmd\n    Either identifier or cmd should be specified.\n\n    user:\n        User's crontab to query\n\n    identifier:\n        Search for line with identifier\n\n    cmd:\n        Search for cron line with cmd\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' cron.identifier_exists root identifier=task1"
  },
  {
    "code": "def get_render_language(contentitem):\n    plugin = contentitem.plugin\n    if plugin.render_ignore_item_language \\\n    or (plugin.cache_output and plugin.cache_output_per_language):\n        return get_language()\n    else:\n        return contentitem.language_code",
    "docstring": "Tell which language should be used to render the content item."
  },
  {
    "code": "def get_action_cache(self, action_key):\n        data = None\n        if self.cache:\n            data = self.cache.get(\n                self.app.config['ACCESS_ACTION_CACHE_PREFIX'] +\n                action_key\n            )\n        return data",
    "docstring": "Get action needs and excludes from cache.\n\n        .. note:: It returns the action if a cache system is defined.\n\n        :param action_key: The unique action name.\n        :returns: The action stored in cache or ``None``."
  },
  {
    "code": "def _disabled(funs):\n    ret = []\n    _disabled = __salt__['grains.get']('state_runs_disabled')\n    for state in funs:\n        for _state in _disabled:\n            if '.*' in _state:\n                target_state = _state.split('.')[0]\n                target_state = target_state + '.' if not target_state.endswith('.') else target_state\n                if state.startswith(target_state):\n                    err = (\n                        'The state file \"{0}\" is currently disabled by \"{1}\", '\n                        'to re-enable, run state.enable {1}.'\n                    ).format(\n                        state,\n                        _state,\n                    )\n                    ret.append(err)\n                    continue\n            else:\n                if _state == state:\n                    err = (\n                        'The state file \"{0}\" is currently disabled, '\n                        'to re-enable, run state.enable {0}.'\n                    ).format(\n                        _state,\n                    )\n                    ret.append(err)\n                    continue\n    return ret",
    "docstring": "Return messages for disabled states\n    that match state functions in funs."
  },
  {
    "code": "def authenticate_request(self, method, bucket='', key='', headers=None):\n        path = self.conn.calling_format.build_path_base(bucket, key)\n        auth_path = self.conn.calling_format.build_auth_path(bucket, key)\n        http_request = boto.connection.AWSAuthConnection.build_base_http_request(\n                self.conn,\n                method,\n                path,\n                auth_path,\n                {},\n                headers\n                )\n        http_request.authorize(connection=self.conn)\n        return http_request",
    "docstring": "Authenticate a HTTP request by filling in Authorization field header.\n\n        :param method: HTTP method (e.g. GET, PUT, POST)\n        :param bucket: name of the bucket.\n        :param key: name of key within bucket.\n        :param headers: dictionary of additional HTTP headers.\n\n        :return: boto.connection.HTTPRequest object with Authorization header\n        filled (NB: will also have a Date field if none before and a User-Agent\n        field will be set to Boto)."
  },
  {
    "code": "def filenames(self):\n        if self._is_reader:\n            assert self._filenames is not None\n            return self._filenames\n        else:\n            return self.data_producer.filenames",
    "docstring": "list of file names the data is originally being read from.\n\n        Returns\n        -------\n        names : list of str\n            list of file names at the beginning of the input chain."
  },
  {
    "code": "def index():\n    crawlers = []\n    for crawler in manager:\n        data = Event.get_counts(crawler)\n        data['last_active'] = crawler.last_run\n        data['total_ops'] = crawler.op_count\n        data['running'] = crawler.is_running\n        data['crawler'] = crawler\n        crawlers.append(data)\n    return render_template('index.html', crawlers=crawlers)",
    "docstring": "Generate a list of all crawlers, alphabetically, with op counts."
  },
  {
    "code": "def keys_to_snake_case(camel_case_dict):\n    return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())",
    "docstring": "Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on\n    each of the keys in the dictionary and returns a new dictionary.\n\n    :param camel_case_dict: Dictionary with the keys to convert.\n    :type camel_case_dict: Dictionary.\n\n    :return: Dictionary with the keys converted to snake case."
  },
  {
    "code": "def _process_m2m_through(self, obj, action):\n        source = getattr(obj, self.field.rel.field.m2m_field_name())\n        target = getattr(obj, self.field.rel.field.m2m_reverse_field_name())\n        pk_set = set()\n        if target:\n            pk_set.add(target.pk)\n        self.process_m2m(source, pk_set, action=action, reverse=False, cache_key=obj)",
    "docstring": "Process custom M2M through model actions."
  },
  {
    "code": "def convert_money(amount, currency_from, currency_to):\n    new_amount = base_convert_money(amount, currency_from, currency_to)\n    return moneyed.Money(new_amount, currency_to)",
    "docstring": "Convert 'amount' from 'currency_from' to 'currency_to' and return a Money\n    instance of the converted amount."
  },
  {
    "code": "def pull(self, key, default=None):\n        val = self.get(key, default)\n        self.forget(key)\n        return val",
    "docstring": "Pulls an item from the collection.\n\n        :param key: The key\n        :type key: mixed\n\n        :param default: The default value\n        :type default: mixed\n\n        :rtype: mixed"
  },
  {
    "code": "def get_queryset(self):\n        self.author = get_object_or_404(\n            Author, **{Author.USERNAME_FIELD: self.kwargs['username']})\n        return self.author.entries_published()",
    "docstring": "Retrieve the author by his username and\n        build a queryset of his published entries."
  },
  {
    "code": "def f(field: str, kwargs: Dict[str, Any],\n      default: Optional[Any] = None) -> str:\n    if default is not None:\n        return str(kwargs.get(field, default))\n    return str(kwargs[field])",
    "docstring": "Alias for more readable command construction"
  },
  {
    "code": "def prt_results(self, goea_results):\n        if self.args.outfile is None:\n            self._prt_results(goea_results)\n        else:\n            outfiles = self.args.outfile.split(\",\")\n            grpwr = self.prepgrp.get_objgrpwr(goea_results) if self.prepgrp else None\n            if grpwr is None:\n                self.prt_outfiles_flat(goea_results, outfiles)\n            else:\n                grpwr.prt_outfiles_grouped(outfiles)",
    "docstring": "Print GOEA results to the screen or to a file."
  },
  {
    "code": "def _send_request(self, operation, url, payload, desc):\n        res = None\n        try:\n            payload_json = None\n            if payload and payload != '':\n                payload_json = jsonutils.dumps(payload)\n            self._login()\n            desc_lookup = {'POST': ' creation', 'PUT': ' update',\n                           'DELETE': ' deletion', 'GET': ' get'}\n            res = requests.request(operation, url, data=payload_json,\n                                   headers=self._req_headers,\n                                   timeout=self.timeout_resp, verify=False)\n            desc += desc_lookup.get(operation, operation.lower())\n            LOG.info(\"DCNM-send_request: %(desc)s %(url)s %(pld)s\",\n                     {'desc': desc, 'url': url, 'pld': payload})\n            self._logout()\n        except (requests.HTTPError, requests.Timeout,\n                requests.ConnectionError) as exc:\n            LOG.exception('Error during request: %s', exc)\n            raise dexc.DfaClientRequestFailed(reason=exc)\n        return res",
    "docstring": "Send request to DCNM."
  },
  {
    "code": "def filter_regex(names, regex):\n    return tuple(name for name in names\n                 if regex.search(name) is not None)",
    "docstring": "Return a tuple of strings that match the regular expression pattern."
  },
  {
    "code": "def del_host(self, mac):\n\t\tmsg = OmapiMessage.open(b\"host\")\n\t\tmsg.obj.append((b\"hardware-address\", pack_mac(mac)))\n\t\tmsg.obj.append((b\"hardware-type\", struct.pack(\"!I\", 1)))\n\t\tresponse = self.query_server(msg)\n\t\tif response.opcode != OMAPI_OP_UPDATE:\n\t\t\traise OmapiErrorNotFound()\n\t\tif response.handle == 0:\n\t\t\traise OmapiError(\"received invalid handle from server\")\n\t\tresponse = self.query_server(OmapiMessage.delete(response.handle))\n\t\tif response.opcode != OMAPI_OP_STATUS:\n\t\t\traise OmapiError(\"delete failed\")",
    "docstring": "Delete a host object with with given mac address.\n\n\t\t@type mac: str\n\t\t@raises ValueError:\n\t\t@raises OmapiError:\n\t\t@raises OmapiErrorNotFound: if no lease object with the given\n\t\t\t\tmac address could be found\n\t\t@raises socket.error:"
  },
  {
    "code": "def keyring_auth(username=None, region=None, authenticate=True):\n    if not keyring:\n        raise exc.KeyringModuleNotInstalled(\"The 'keyring' Python module is \"\n                \"not installed on this system.\")\n    if username is None:\n        username = settings.get(\"keyring_username\")\n    if not username:\n        raise exc.KeyringUsernameMissing(\"No username specified for keyring \"\n                \"authentication.\")\n    password = keyring.get_password(\"pyrax\", username)\n    if password is None:\n        raise exc.KeyringPasswordNotFound(\"No password was found for the \"\n                \"username '%s'.\" % username)\n    set_credentials(username, password, region=region,\n            authenticate=authenticate)",
    "docstring": "Use the password stored within the keyring to authenticate. If a username\n    is supplied, that name is used; otherwise, the keyring_username value\n    from the config file is used.\n\n    If there is no username defined, or if the keyring module is not installed,\n    or there is no password set for the given username, the appropriate errors\n    will be raised.\n\n    If the region is passed, it will authenticate against the proper endpoint\n    for that region, and set the default region for connections."
  },
  {
    "code": "def set_color_temp(self, color_temp):\n        if self._json_state['control_url']:\n            url = CONST.INTEGRATIONS_URL + self._device_uuid\n            color_data = {\n                'action': 'setcolortemperature',\n                'colorTemperature': int(color_temp)\n            }\n            response = self._abode.send_request(\"post\", url, data=color_data)\n            response_object = json.loads(response.text)\n            _LOGGER.debug(\"Set Color Temp Response: %s\", response.text)\n            if response_object['idForPanel'] != self.device_id:\n                raise AbodeException((ERROR.SET_STATUS_DEV_ID))\n            if response_object['colorTemperature'] != int(color_temp):\n                _LOGGER.warning(\n                    (\"Set color temp mismatch for device %s. \"\n                     \"Request val: %s, Response val: %s \"),\n                    self.device_id, color_temp,\n                    response_object['colorTemperature'])\n            self.update(response_object)\n            _LOGGER.info(\"Set device %s color_temp to: %s\",\n                         self.device_id, color_temp)\n            return True\n        return False",
    "docstring": "Set device color."
  },
  {
    "code": "def infer_from_frame_stack(self, ob_stack):\n    logits, vf = self.sess.run([self.logits_t, self.value_function_t],\n                               feed_dict={self.obs_t: ob_stack})\n    return logits, vf",
    "docstring": "Infer policy from stack of observations.\n\n    Args:\n      ob_stack: array of shape (1, frame_stack_size, height, width, channels)\n\n    Returns:\n      logits and vf."
  },
  {
    "code": "def _is_gpg2(version):\n    (major, minor, micro) = _match_version_string(version)\n    if major == 2:\n        return True\n    return False",
    "docstring": "Returns True if using GnuPG version 2.x.\n\n    :param tuple version: A tuple of three integers indication major, minor,\n        and micro version numbers."
  },
  {
    "code": "def apply_patches(self):\n        success = True\n        for name, patch in sorted(self):\n            success = self.apply_patch(patch)\n        return success",
    "docstring": "Applies the patches.\n\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def get_xy_name(self, yidx, xidx=0):\n        assert isinstance(xidx, int)\n        if isinstance(yidx, int):\n            yidx = [yidx]\n        uname = ['Time [s]'] + self.uname\n        fname = ['$Time\\\\ [s]$'] + self.fname\n        xname = [list(), list()]\n        yname = [list(), list()]\n        xname[0] = uname[xidx]\n        xname[1] = fname[xidx]\n        yname[0] = [uname[i] for i in yidx]\n        yname[1] = [fname[i] for i in yidx]\n        return xname, yname",
    "docstring": "Return variable names for the given indices\n\n        :param yidx:\n        :param xidx:\n        :return:"
  },
  {
    "code": "def validate(document, spec):\n    if not spec:\n        return True\n    missing = []\n    for key, field in spec.iteritems():\n        if field.required and key not in document:\n            missing.append(key)\n    failed = []\n    for key, field in spec.iteritems():\n        if key in document:\n            try: document[key] = field.validate(document[key])\n            except ValueError: failed.append(key)\n    if missing or failed:\n        if missing and not failed:\n            raise ValueError(\"Required fields missing: %s\" % (missing))\n        if failed and not missing:\n            raise ValueError(\"Keys did not match spec: %s\" % (failed))\n        raise ValueError(\"Missing fields: %s, Invalid fields: %s\" % (missing, failed))\n    return True",
    "docstring": "Validate that a document meets a specification.  Returns True if\n    validation was successful, but otherwise raises a ValueError."
  },
  {
    "code": "def save_reg(data):\n    reg_dir = _reg_dir()\n    regfile = os.path.join(reg_dir, 'register')\n    try:\n        if not os.path.exists(reg_dir):\n            os.makedirs(reg_dir)\n    except OSError as exc:\n        if exc.errno == errno.EEXIST:\n            pass\n        else:\n            raise\n    try:\n        with salt.utils.files.fopen(regfile, 'a') as fh_:\n            salt.utils.msgpack.dump(data, fh_)\n    except Exception:\n        log.error('Could not write to msgpack file %s', __opts__['outdir'])\n        raise",
    "docstring": "Save the register to msgpack files"
  },
  {
    "code": "def _get_value_from_ast(self, obj):\n        if isinstance(obj, ast.Num):\n            return obj.n\n        elif isinstance(obj, ast.Str):\n            return obj.s\n        elif isinstance(obj, ast.List):\n            return [self._get_value_from_ast(e) for e in obj.elts]\n        elif isinstance(obj, ast.Tuple):\n            return tuple([self._get_value_from_ast(e) for e in obj.elts])\n        elif sys.version_info.major >= 3 and isinstance(obj, ast.NameConstant):\n            return obj.value\n        elif isinstance(obj, ast.Name) and (obj.id in [\"True\", \"False\", \"None\"]):\n            return string_to_constant[obj.id]\n        raise NameError(\"name '%s' is not defined\" % obj.id)",
    "docstring": "Return the value of the ast object."
  },
  {
    "code": "def find_encodings(enc=None, system=False):\n    if not enc:\n        enc = 'utf-8'\n    if system:\n        if getattr(sys.stdin, 'encoding', None) is None:\n            enc = sys.stdin.encoding\n            log.debug(\"Obtained encoding from stdin: %s\" % enc)\n        else:\n            enc = 'ascii'\n    enc = enc.lower()\n    codec_alias = encodings.normalize_encoding(enc)\n    codecs.register(encodings.search_function)\n    coder = codecs.lookup(codec_alias)\n    return coder",
    "docstring": "Find functions for encoding translations for a specific codec.\n\n    :param str enc: The codec to find translation functions for. It will be\n                    normalized by converting to lowercase, excluding\n                    everything which is not ascii, and hyphens will be\n                    converted to underscores.\n\n    :param bool system: If True, find encodings based on the system's stdin\n                        encoding, otherwise assume utf-8.\n\n    :raises: :exc:LookupError if the normalized codec, ``enc``, cannot be\n             found in Python's encoding translation map."
  },
  {
    "code": "def join_path(path):\n    if isinstance(path, str):\n        return path\n    return os.path.join(*path)",
    "docstring": "If given a string, return it, otherwise combine a list into a string using os.path.join"
  },
  {
    "code": "def is_allowed(self, name_or_class, mask):\n        if isinstance(name_or_class, type):\n            name = name_or_class.type\n        else:\n            name = name_or_class\n        info = self.connections[name]\n        limit = self.config[name + '_limit']\n        if limit and info['total'] >= limit:\n            msg = (\n                \"Sorry, there is too much DCC %s active. Please try again \"\n                \"later.\") % name.upper()\n            self.bot.notice(mask, msg)\n            return False\n        if mask not in info['masks']:\n            return True\n        limit = self.config[name + '_user_limit']\n        if limit and info['masks'][mask] >= limit:\n            msg = (\n                \"Sorry, you have too many DCC %s active. Close the other \"\n                \"connection(s) or wait a few seconds and try again.\"\n            ) % name.upper()\n            self.bot.notice(mask, msg)\n            return False\n        return True",
    "docstring": "Return True is a new connection is allowed"
  },
  {
    "code": "def init(self, conn):\n        base = self.read_scripts()[0]['fname']\n        logging.info('Creating the initial schema from %s',  base)\n        apply_sql_script(conn, os.path.join(self.upgrade_dir, base))\n        self.install_versioning(conn)",
    "docstring": "Create the version table and run the base script on an empty database.\n\n        :param conn: a DB API 2 connection"
  },
  {
    "code": "def decode_obj_table(table_entries, plugin):\n    entries = []\n    for entry in table_entries:\n        if isinstance(entry, Container):\n            assert not hasattr(entry, '__recursion_lock__')\n            user_obj_def = plugin.user_objects[entry.classID]\n            assert entry.version == user_obj_def.version\n            entry = Container(class_name=entry.classID,\n                              **dict(zip(user_obj_def.defaults.keys(),\n                                         entry.values)))\n        entries.append(entry)\n    return decode_network(entries)",
    "docstring": "Return root of obj table. Converts user-class objects"
  },
  {
    "code": "def class_from_string(name):\n    module_name, class_name = name.rsplit('.', 1)\n    __import__(module_name)\n    module = sys.modules[module_name]\n    return getattr(module, class_name)",
    "docstring": "Get a python class object from its name"
  },
  {
    "code": "def reply(self, user, msg, errors_as_replies=True):\n        return self._brain.reply(user, msg, errors_as_replies)",
    "docstring": "Fetch a reply from the RiveScript brain.\n\n        Arguments:\n            user (str): A unique user ID for the person requesting a reply.\n                This could be e.g. a screen name or nickname. It's used internally\n                to store user variables (including topic and history), so if your\n                bot has multiple users each one should have a unique ID.\n            msg (str): The user's message. This is allowed to contain\n                punctuation and such, but any extraneous data such as HTML tags\n                should be removed in advance.\n            errors_as_replies (bool): When errors are encountered (such as a\n                deep recursion error, no reply matched, etc.) this will make the\n                reply be a text representation of the error message. If you set\n                this to ``False``, errors will instead raise an exception, such as\n                a ``DeepRecursionError`` or ``NoReplyError``. By default, no\n                exceptions are raised and errors are set in the reply instead.\n\n        Returns:\n            str: The reply output."
  },
  {
    "code": "def diagonal_basis_commutes(pauli_a, pauli_b):\n    overlapping_active_qubits = set(pauli_a.get_qubits()) & set(pauli_b.get_qubits())\n    for qubit_index in overlapping_active_qubits:\n        if (pauli_a[qubit_index] != 'I' and pauli_b[qubit_index] != 'I' and\n           pauli_a[qubit_index] != pauli_b[qubit_index]):\n            return False\n    return True",
    "docstring": "Test if `pauli_a` and `pauli_b` share a diagonal basis\n\n    Example:\n\n        Check if [A, B] with the constraint that A & B must share a one-qubit\n        diagonalizing basis. If the inputs were [sZ(0), sZ(0) * sZ(1)] then this\n        function would return True.  If the inputs were [sX(5), sZ(4)] this\n        function would return True.  If the inputs were [sX(0), sY(0) * sZ(2)]\n        this function would return False.\n\n    :param pauli_a: Pauli term to check commutation against `pauli_b`\n    :param pauli_b: Pauli term to check commutation against `pauli_a`\n    :return: Boolean of commutation result\n    :rtype: Bool"
  },
  {
    "code": "def iskip( value, iterable ):\r\n    for e in iterable:\r\n        if value is None:\r\n            if e is None:\r\n                continue\r\n        elif e == value:\r\n            continue\r\n        yield e",
    "docstring": "Skips all values in 'iterable' matching the given 'value'."
  },
  {
    "code": "def bin(self, size, name, value=None):\n        self._add_field(Binary(size, name, value))",
    "docstring": "Add new binary field to template.\n\n        This keyword has to be called within a binary container. See `New Binary\n        Container`."
  },
  {
    "code": "def save_configuration(self):\n        self.check_credentials()\n        c = self._get_pypirc_command()\n        c._store_pypirc(self.username, self.password)",
    "docstring": "Save the PyPI access configuration. You must have set ``username`` and\n        ``password`` attributes before calling this method.\n\n        Again, distutils is used to do the actual work."
  },
  {
    "code": "def _check_timers(self):\n        if self._timer_queue:\n            timer = self._timer_queue[0]\n            if timer['timeout_abs'] < _current_time_millis():\n                self._timer_queue.pop(0)\n                self._logger.debug('Timer {} expired for stm {}, adding it to event queue.'.format(timer['id'], timer['stm'].id))\n                self._add_event(timer['id'], [], {}, timer['stm'], front=True)\n            else:\n                self._next_timeout = (\n                    timer['timeout_abs'] - _current_time_millis()) / 1000\n                if self._next_timeout < 0:\n                    self._next_timeout = 0\n        else:\n            self._next_timeout = None",
    "docstring": "Check for expired timers.\n\n        If there are any timers that expired, place them in the event\n        queue."
  },
  {
    "code": "def relocate(self):\n        name=self.SearchVar.get()\n        if kbos.has_key(name):\n\t    import orbfit,ephem,math\n\t    jdate=ephem.julian_date(w.date.get())\n \t    try:\n\t        (ra,dec,a,b,ang)=orbfit.predict(kbos[name],jdate,568)\n\t    except:\n\t\treturn\n\t    ra=math.radians(ra)\n\t    dec=math.radians(dec)\n\telif mpc_objs.has_key(name):\n\t    ra=mpc_objs[name].ra\n\t    dec=mpc_objs[name].dec\n\tself.recenter(ra,dec)\n\tself.create_point(ra,dec,color='blue',size=4)",
    "docstring": "Move to the postion of self.SearchVar"
  },
  {
    "code": "def exit_on_exception(self, raised_exception, message='', exit_code=99):\n        self.exit_on_error(message=message, exit_code=None)\n        logger.critical(\"-----\\nException: %s\\nBack trace of the error:\\n%s\",\n                        str(raised_exception), traceback.format_exc())\n        exit(exit_code)",
    "docstring": "Log generic message when getting an unrecoverable error\n\n        :param raised_exception: raised Exception\n        :type raised_exception: Exception\n        :param message: message for the exit reason\n        :type message: str\n        :param exit_code: exit with the provided value as exit code\n        :type exit_code: int\n        :return: None"
  },
  {
    "code": "def nato(sentence, pad=' ', format='telephony'):\n    try:\n        return '' + ALPHABET['nato'][format](sentence, pad)\n    except KeyError:\n        raise TypeError('Unsupported NATO alphabet \"%s\"' % (format,))",
    "docstring": "Transform a sentence using the NATO spelling alphabet.\n\n    :param sentence: input sentence\n    :param pad: default ``' '``\n    :param format: default ``telephony``, options ``telephony`` or ``phonetic``\n\n    >>> print(nato('Python'))\n    papa yankee tango hotel oscar november\n\n    >>> print(nato('Python', format='phonetic'))\n    pah-pah yang-key tang-go hoh-tel oss-cah no-vem-ber"
  },
  {
    "code": "def get_id(self, name, recurse=True):\n        self._dlog(\"getting id '{}'\".format(name))\n        var = self._search(\"vars\", name, recurse)\n        return var",
    "docstring": "Get the first id matching ``name``. Will either be a local\n        or a var.\n\n        :name: TODO\n        :returns: TODO"
  },
  {
    "code": "def disconnect(self, func):\n        if id(self) not in _alleged_receivers:\n            return\n        l = _alleged_receivers[id(self)]\n        try:\n            l.remove(func)\n        except ValueError:\n            return\n        if not l:\n            del _alleged_receivers[id(self)]",
    "docstring": "No longer call the function when something changes here."
  },
  {
    "code": "def _file_changed_nilrt(full_filepath):\n    rs_state_dir = \"/var/lib/salt/restartcheck_state\"\n    base_filename = os.path.basename(full_filepath)\n    timestamp_file = os.path.join(rs_state_dir, '{0}.timestamp'.format(base_filename))\n    md5sum_file = os.path.join(rs_state_dir, '{0}.md5sum'.format(base_filename))\n    if not os.path.exists(timestamp_file) or not os.path.exists(md5sum_file):\n        return True\n    prev_timestamp = __salt__['file.read'](timestamp_file).rstrip()\n    cur_timestamp = str(int(os.path.getmtime(full_filepath)))\n    if prev_timestamp != cur_timestamp:\n        return True\n    return bool(__salt__['cmd.retcode']('md5sum -cs {0}'.format(md5sum_file), output_loglevel=\"quiet\"))",
    "docstring": "Detect whether a file changed in an NILinuxRT system using md5sum and timestamp\n    files from a state directory.\n\n    Returns:\n             - False if md5sum/timestamp state files don't exist\n             - True/False depending if ``base_filename`` got modified/touched"
  },
  {
    "code": "def delete_feature(self, dataset, fid):\n        uri = URITemplate(\n            self.baseuri + '/{owner}/{did}/features/{fid}').expand(\n                owner=self.username, did=dataset, fid=fid)\n        return self.session.delete(uri)",
    "docstring": "Removes a feature from a dataset.\n\n        Parameters\n        ----------\n        dataset : str\n            The dataset id.\n\n        fid : str\n            The feature id.\n\n        Returns\n        -------\n        HTTP status code."
  },
  {
    "code": "def equally_spaced_points(self, point, distance):\n        lons, lats, depths = geodetic.intervals_between(\n            self.longitude, self.latitude, self.depth,\n            point.longitude, point.latitude, point.depth,\n            distance)\n        return [Point(lons[i], lats[i], depths[i]) for i in range(len(lons))]",
    "docstring": "Compute the set of points equally spaced between this point\n        and the given point.\n\n        :param point:\n            Destination point.\n        :type point:\n            Instance of :class:`Point`\n        :param distance:\n            Distance between points (in km).\n        :type distance:\n            float\n        :returns:\n            The list of equally spaced points.\n        :rtype:\n            list of :class:`Point` instances"
  },
  {
    "code": "def _parse_authorization(cls, response, uri=None):\n        links = _parse_header_links(response)\n        try:\n            new_cert_uri = links[u'next'][u'url']\n        except KeyError:\n            raise errors.ClientError('\"next\" link missing')\n        return (\n            response.json()\n            .addCallback(\n                lambda body: messages.AuthorizationResource(\n                    body=messages.Authorization.from_json(body),\n                    uri=cls._maybe_location(response, uri=uri),\n                    new_cert_uri=new_cert_uri))\n            )",
    "docstring": "Parse an authorization resource."
  },
  {
    "code": "def make_key(self, value):\n        if value:\n            parts = [self.key_filter.sub('', x)\n                     for x in self.key_split.split(value.lower())]\n            key = parts[0] + ''.join(map(str.capitalize, parts[1:]))\n        else:\n            key = ''\n        if key in self.seen_keys:\n            i = 1\n            while '%s%d' % (key, i) in self.seen_keys:\n                i += 1\n            key = '%s%d' % (key, i)\n        self.seen_keys.add(key)\n        return key",
    "docstring": "Make camelCase variant of value."
  },
  {
    "code": "def use_isolated_bin_view(self):\n        self._bin_view = ISOLATED\n        for session in self._get_provider_sessions():\n            try:\n                session.use_isolated_bin_view()\n            except AttributeError:\n                pass",
    "docstring": "Pass through to provider ResourceLookupSession.use_isolated_bin_view"
  },
  {
    "code": "def join_here(*paths, **kwargs):\n    path = os.path.abspath(\".\")\n    for next_path in paths:\n        next_path = next_path.lstrip(\"\\\\\").lstrip(\"/\").strip() if not \\\n            kwargs.get('strict') else next_path\n        path = os.path.abspath(os.path.join(path, next_path))\n    return path if not kwargs.get('safe') else safe_path(path)",
    "docstring": "Join any path or paths as a sub directory of the current file's directory.\n\n    .. code:: python\n\n        reusables.join_here(\"Makefile\")\n        # 'C:\\\\Reusables\\\\Makefile'\n\n    :param paths: paths to join together\n    :param kwargs: 'strict', do not strip os.sep\n    :param kwargs: 'safe', make them into a safe path it True\n    :return: abspath as string"
  },
  {
    "code": "def orthorhombic(a: float, b: float, c: float):\n        return Lattice.from_parameters(a, b, c, 90, 90, 90)",
    "docstring": "Convenience constructor for an orthorhombic lattice.\n\n        Args:\n            a (float): *a* lattice parameter of the orthorhombic cell.\n            b (float): *b* lattice parameter of the orthorhombic cell.\n            c (float): *c* lattice parameter of the orthorhombic cell.\n\n        Returns:\n            Orthorhombic lattice of dimensions a x b x c."
  },
  {
    "code": "def set_active(self, username, active_state):\n        if active_state not in (True, False):\n            raise ValueError(\"active_state must be True or False\")\n        user = self.get_user(username)\n        if user is None:\n            return None\n        if user['active'] is active_state:\n            return True\n        user['active'] = active_state\n        response = self._put(self.rest_url + \"/user\",\n                             params={\"username\": username},\n                             data=json.dumps(user))\n        if response.status_code == 204:\n            return True\n        return None",
    "docstring": "Set the active state of a user\n\n        Args:\n            username: The account username\n            active_state: True or False\n\n        Returns:\n            True: If successful\n            None: If no user or failure occurred"
  },
  {
    "code": "def _store_oauth_access_token(self, oauth_access_token):\n        c = Cookie(version=0, name='oauth_access_token', value=oauth_access_token,\n            port=None, port_specified=False,\n            domain='steamwebbrowser.tld', domain_specified=True, domain_initial_dot=False,\n            path='/', path_specified=True,\n            secure=False, expires=None, discard=False, comment=None, comment_url=None, rest={},\n        )\n        self.session.cookies.set_cookie(c)\n        self._save_cookies()",
    "docstring": "Called when login is complete to store the oauth access token\n            This implementation stores the oauth_access_token in a seperate cookie for domain steamwebbrowser.tld"
  },
  {
    "code": "def analyze(fqdn, result, argl, argd):\n    package = fqdn.split('.')[0]\n    if package not in _methods:\n        _load_methods(package)\n    if _methods[package] is not None and fqdn in _methods[package]:\n        return _methods[package][fqdn](fqdn, result, *argl, **argd)",
    "docstring": "Analyzes the result from calling the method with the specified FQDN.\n\n    Args:\n        fqdn (str): full-qualified name of the method that was called.\n        result: result of calling the method with `fqdn`.\n        argl (tuple): positional arguments passed to the method call.\n        argd (dict): keyword arguments passed to the method call."
  },
  {
    "code": "def get_pattern_link_topattern(self, patternnumber):\n        _checkPatternNumber(patternnumber)\n        address = _calculateRegisterAddress('linkpattern', patternnumber)\n        return self.read_register(address)",
    "docstring": "Get the 'linked pattern' value for a given pattern.\n\n        Args:\n            patternnumber (integer): From 0-7\n            \n        Returns:\n            The 'linked pattern' value (int)."
  },
  {
    "code": "def write(self, b):\n                from . import mavutil\n                self.debug(\"sending '%s' (0x%02x) of len %u\\n\" % (b, ord(b[0]), len(b)), 2)\n                while len(b) > 0:\n                        n = len(b)\n                        if n > 70:\n                                n = 70\n                        buf = [ord(x) for x in b[:n]]\n                        buf.extend([0]*(70-len(buf)))\n                        self.mav.mav.serial_control_send(self.port,\n                                                         mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE |\n                                                         mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND,\n                                                         0,\n                                                         0,\n                                                         n,\n                                                         buf)\n                        b = b[n:]",
    "docstring": "write some bytes"
  },
  {
    "code": "def load(self, entity_class, entity):\n        if self.__needs_flushing:\n            self.flush()\n        if entity.id is None:\n            raise ValueError('Can not load entity without an ID.')\n        cache = self.__get_cache(entity_class)\n        sess_ent = cache.get_by_id(entity.id)\n        if sess_ent is None:\n            if self.__clone_on_load:\n                sess_ent = self.__clone(entity, cache)\n            else:\n                cache.add(entity)\n                sess_ent = entity\n            self.__unit_of_work.register_clean(entity_class, sess_ent)\n        return sess_ent",
    "docstring": "Load the given repository entity into the session and return a\n        clone. If it was already loaded before, look up the loaded entity\n        and return it.\n\n        All entities referenced by the loaded entity will also be loaded\n        (and cloned) recursively.\n\n        :raises ValueError: When an attempt is made to load an entity that\n          has no ID"
  },
  {
    "code": "def get_library_state_copy_instance(self, lib_os_path):\n        if lib_os_path in self._loaded_libraries:\n            state_machine = self._loaded_libraries[lib_os_path]\n            state_copy = copy.deepcopy(state_machine.root_state)\n            return state_machine.version, state_copy\n        else:\n            state_machine = storage.load_state_machine_from_path(lib_os_path)\n            self._loaded_libraries[lib_os_path] = state_machine\n            if config.global_config.get_config_value(\"NO_PROGRAMMATIC_CHANGE_OF_LIBRARY_STATES_PERFORMED\", False):\n                return state_machine.version, state_machine.root_state\n            else:\n                state_copy = copy.deepcopy(state_machine.root_state)\n                return state_machine.version, state_copy",
    "docstring": "A method to get a state copy of the library specified via the lib_os_path.\n\n        :param lib_os_path: the location of the library to get a copy for\n        :return:"
  },
  {
    "code": "def process(self, processor:PreProcessors=None):\n        \"Apply `processor` or `self.processor` to `self`.\"\n        if processor is not None: self.processor = processor\n        self.processor = listify(self.processor)\n        for p in self.processor: p.process(self)\n        return self",
    "docstring": "Apply `processor` or `self.processor` to `self`."
  },
  {
    "code": "def get_grade_systems_by_gradebooks(self, gradebook_ids):\n        grade_system_list = []\n        for gradebook_id in gradebook_ids:\n            grade_system_list += list(\n                self.get_grade_systems_by_gradebook(gradebook_id))\n        return objects.GradeSystemList(grade_system_list)",
    "docstring": "Gets the list of grade systems corresponding to a list of ``Gradebooks``.\n\n        arg:    gradebook_ids (osid.id.IdList): list of gradebook\n                ``Ids``\n        return: (osid.grading.GradeSystemList) - list of grade systems\n        raise:  NullArgument - ``gradebook_ids`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def slugify(text):\n    slug = re.sub(r'[^\\w]+', ' ', text)\n    slug = \"-\".join(slug.lower().strip().split())\n    return slug",
    "docstring": "Returns a slug of given text, normalizing unicode data for file-safe\n    strings. Used for deciding where to write images to disk.\n\n    Parameters\n    ----------\n    text : string\n        The string to slugify\n\n    Returns\n    -------\n    slug : string\n        A normalized slug representation of the text\n\n    .. seealso:: http://yashchandra.com/2014/05/08/how-to-generate-clean-url-or-a-slug-in-python/"
  },
  {
    "code": "def checkout_branch(self, branch):\n        _, stdout, stderr = self.git_exec(\n            ['checkout', branch],\n            with_extended_output=True)\n        return '\\n'.join([stderr, stdout])",
    "docstring": "Checks out given branch."
  },
  {
    "code": "def get_substructure(data, path):\n    if not len(path):\n        return data\n    try:\n        return get_substructure(data[path[0]], path[1:])\n    except (TypeError, IndexError, KeyError):\n        return None",
    "docstring": "Tries to retrieve a sub-structure within some data. If the path does not\n    match any sub-structure, returns None.\n\n    >>> data = {'a': 5, 'b': {'c': [1, 2, [{'f': [57]}], 4], 'd': 'test'}}\n    >>> get_substructure(island, \"bc\")\n    [1, 2, [{'f': [57]}], 4]\n    >>> get_substructure(island, ['b', 'c'])\n    [1, 2, [{'f': [57]}], 4]\n    >>> get_substructure(island, ['b', 'c', 2, 0, 'f', 0])\n    57\n    >>> get_substructure(island, ['b', 'c', 2, 0, 'f', 'd'])\n    None\n\n    @param data: a container\n    @type data: str|dict|list|(an indexable container)\n\n    @param path: location of the data\n    @type path: list|str\n\n    @rtype: *"
  },
  {
    "code": "def to_dict(self, save_data=True):\n        model_dict = super(SparseGPClassification,self).to_dict(save_data)\n        model_dict[\"class\"] = \"GPy.models.SparseGPClassification\"\n        return model_dict",
    "docstring": "Store the object into a json serializable dictionary\n\n        :param boolean save_data: if true, it adds the data self.X and self.Y to the dictionary\n        :return dict: json serializable dictionary containing the needed information to instantiate the object"
  },
  {
    "code": "def _get_section(self, name, type):\n        for section in self.sections:\n            if section['name'] == name and section['type'] == type:\n                return section\n        return None",
    "docstring": "Find and return a section with `name` and `type`"
  },
  {
    "code": "def load(cls, path, base=None):\n        obj = cls()\n        obj.read(path, base)\n        return obj",
    "docstring": "Either load a path and return a shovel object or return None"
  },
  {
    "code": "def transition_complete(self, pipeline_key):\n    def txn():\n      pipeline_record = db.get(pipeline_key)\n      if pipeline_record is None:\n        logging.warning(\n            'Tried to mark pipeline ID \"%s\" as complete but it does not exist.',\n            pipeline_key.name())\n        raise db.Rollback()\n      if pipeline_record.status not in (\n          _PipelineRecord.WAITING, _PipelineRecord.RUN):\n        logging.warning(\n            'Tried to mark pipeline ID \"%s\" as complete, found bad state: %s',\n            pipeline_key.name(), pipeline_record.status)\n        raise db.Rollback()\n      pipeline_record.status = _PipelineRecord.DONE\n      pipeline_record.finalized_time = self._gettime()\n      pipeline_record.put()\n    db.run_in_transaction(txn)",
    "docstring": "Marks the given pipeline as complete.\n\n    Does nothing if the pipeline is no longer in a state that can be completed.\n\n    Args:\n      pipeline_key: db.Key of the _PipelineRecord that has completed."
  },
  {
    "code": "def get_bool_raw(s: str) -> Optional[bool]:\n    if s == \"Y\" or s == \"y\":\n        return True\n    elif s == \"N\" or s == \"n\":\n        return False\n    return None",
    "docstring": "Maps ``\"Y\"``, ``\"y\"`` to ``True`` and ``\"N\"``, ``\"n\"`` to ``False``."
  },
  {
    "code": "def ungroupslice(groups,gslice):\r\n  'this is a helper for contigsub.'\r\n  'coordinate transform: takes a match from seqingroups() and transforms to ungrouped coordinates'\r\n  eltsbefore=0\r\n  for i in range(gslice[0]): eltsbefore+=len(groups[i])-1\r\n  x=eltsbefore+gslice[1]; return [x-1,x+gslice[2]-1]",
    "docstring": "this is a helper for contigsub."
  },
  {
    "code": "def clear(self):\n        if not self._clear:\n            self.lib._jit_clear_state(self.state)\n            self._clear = True",
    "docstring": "Clears state so it can be used for generating entirely new\n        instructions."
  },
  {
    "code": "def as_vartype(vartype):\n    if isinstance(vartype, Vartype):\n        return vartype\n    try:\n        if isinstance(vartype, str):\n            vartype = Vartype[vartype]\n        elif isinstance(vartype, frozenset):\n            vartype = Vartype(vartype)\n        else:\n            vartype = Vartype(frozenset(vartype))\n    except (ValueError, KeyError):\n        raise TypeError((\"expected input vartype to be one of: \"\n                         \"Vartype.SPIN, 'SPIN', {-1, 1}, \"\n                         \"Vartype.BINARY, 'BINARY', or {0, 1}.\"))\n    return vartype",
    "docstring": "Cast various inputs to a valid vartype object.\n\n    Args:\n        vartype (:class:`.Vartype`/str/set):\n            Variable type. Accepted input values:\n\n            * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n            * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n    Returns:\n        :class:`.Vartype`: Either :class:`.Vartype.SPIN` or\n        :class:`.Vartype.BINARY`.\n\n    See also:\n        :func:`~dimod.decorators.vartype_argument`"
  },
  {
    "code": "def sle(self, other):\n        self._check_match(other)\n        return self.to_sint() <= other.to_sint()",
    "docstring": "Compares two equal-sized BinWords, treating them as signed\n        integers, and returning True if the first is smaller or equal."
  },
  {
    "code": "def parse(cls, filename, root=None):\n    if root is not None:\n      if os.path.isabs(filename):\n        raise ValueError(\"filename must be a relative path if root is specified\")\n      full_filename = os.path.join(root, filename)\n    else:\n      full_filename = filename\n    with io.open(full_filename, 'rb') as fp:\n      blob = fp.read()\n    tree = cls._parse(blob, filename)\n    return cls(blob=blob, tree=tree, root=root, filename=filename)",
    "docstring": "Parses the file at filename and returns a PythonFile.\n\n    If root is specified, it will open the file with root prepended to the path. The idea is to\n    allow for errors to contain a friendlier file path than the full absolute path."
  },
  {
    "code": "def is_ssh_available(host, port=22):\n    s = socket.socket()\n    try:\n        s.connect((host, port))\n        return True\n    except:\n        return False",
    "docstring": "checks if ssh port is open"
  },
  {
    "code": "def to_json(fn, obj):\n    with open(fn, 'w') as f:\n        json.dump(obj, f, cls=OperatorEncoder, indent=2, ensure_ascii=False)\n    return fn",
    "docstring": "Convenience method to save pyquil.operator_estimation objects as a JSON file.\n\n    See :py:func:`read_json`."
  },
  {
    "code": "def download_go_basic_obo(obo=\"go-basic.obo\", prt=sys.stdout, loading_bar=True):\n    if not os.path.isfile(obo):\n        http = \"http://purl.obolibrary.org/obo/go\"\n        if \"slim\" in obo:\n            http = \"http://www.geneontology.org/ontology/subsets\"\n        obo_remote = \"{HTTP}/{OBO}\".format(HTTP=http, OBO=os.path.basename(obo))\n        dnld_file(obo_remote, obo, prt, loading_bar)\n    else:\n        if prt is not None:\n            prt.write(\"  EXISTS: {FILE}\\n\".format(FILE=obo))\n    return obo",
    "docstring": "Download Ontologies, if necessary."
  },
  {
    "code": "def _checkJobGraphAcylicDFS(self, stack, visited, extraEdges):\n        if self not in visited:\n            visited.add(self)\n            stack.append(self)\n            for successor in self._children + self._followOns + extraEdges[self]:\n                successor._checkJobGraphAcylicDFS(stack, visited, extraEdges)\n            assert stack.pop() == self\n        if self in stack:\n            stack.append(self)\n            raise JobGraphDeadlockException(\"A cycle of job dependencies has been detected '%s'\" % stack)",
    "docstring": "DFS traversal to detect cycles in augmented job graph."
  },
  {
    "code": "def to_bb(YY, y=\"deprecated\"):\n    cols,rows = np.nonzero(YY)\n    if len(cols)==0: return np.zeros(4, dtype=np.float32)\n    top_row = np.min(rows)\n    left_col = np.min(cols)\n    bottom_row = np.max(rows)\n    right_col = np.max(cols)\n    return np.array([left_col, top_row, right_col, bottom_row], dtype=np.float32)",
    "docstring": "Convert mask YY to a bounding box, assumes 0 as background nonzero object"
  },
  {
    "code": "def append_config_item(self, key, value):\n        return _lxc.Container.set_config_item(self, key, value)",
    "docstring": "Append 'value' to 'key', assuming 'key' is a list.\n            If 'key' isn't a list, 'value' will be set as the value of 'key'."
  },
  {
    "code": "def type_consumer():\n    while True:\n        item = _task_queue.get()\n        if isinstance(item, KeyAndTypes):\n            if item.key in collected_args:\n                _flush_signature(item.key, UnknownType)\n            collected_args[item.key] = ArgTypes(item.types)\n        else:\n            assert isinstance(item, KeyAndReturn)\n            if item.key in collected_args:\n                _flush_signature(item.key, item.return_type)\n        _task_queue.task_done()",
    "docstring": "Infinite loop of the type consumer thread.\n    It gets types to process from the task query."
  },
  {
    "code": "def dbus_readBytesFD(self, fd, byte_count):\n        f = os.fdopen(fd, 'rb')\n        result = f.read(byte_count)\n        f.close()\n        return bytearray(result)",
    "docstring": "Reads byte_count bytes from fd and returns them."
  },
  {
    "code": "def parse_config_list(config_list):\n  if config_list is None:\n    return {}\n  else:\n    mapping = {}\n    for pair in config_list:\n      if (constants.CONFIG_SEPARATOR not in pair) or (pair.count(constants.CONFIG_SEPARATOR) != 1):\n        raise ValueError(\"configs must be passed as two strings separted by a %s\", constants.CONFIG_SEPARATOR)\n      (config, value) = pair.split(constants.CONFIG_SEPARATOR)\n      mapping[config] = value\n    return mapping",
    "docstring": "Parse a list of configuration properties separated by '='"
  },
  {
    "code": "def standardize(table, with_std=True):\n    if isinstance(table, pandas.DataFrame):\n        cat_columns = table.select_dtypes(include=['category']).columns\n    else:\n        cat_columns = []\n    new_frame = _apply_along_column(table, standardize_column, with_std=with_std)\n    for col in cat_columns:\n        new_frame[col] = table[col].copy()\n    return new_frame",
    "docstring": "Perform Z-Normalization on each numeric column of the given table.\n\n    Parameters\n    ----------\n    table : pandas.DataFrame or numpy.ndarray\n        Data to standardize.\n\n    with_std : bool, optional, default: True\n        If ``False`` data is only centered and not converted to unit variance.\n\n    Returns\n    -------\n    normalized : pandas.DataFrame\n        Table with numeric columns normalized.\n        Categorical columns in the input table remain unchanged."
  },
  {
    "code": "def dump_to_pyc(co, python_version, output_dir):\n    pyc_basename = ntpath.basename(co.co_filename)\n    pyc_name = pyc_basename + '.pyc'\n    if pyc_name not in IGNORE:\n        logging.info(\"Extracting %s\", pyc_name)\n        pyc_header = _generate_pyc_header(python_version, len(co.co_code))\n        destination = os.path.join(output_dir, pyc_name)\n        pyc = open(destination, 'wb')\n        pyc.write(pyc_header)\n        marshaled_code = marshal.dumps(co)\n        pyc.write(marshaled_code)\n        pyc.close()\n    else:\n        logging.info(\"Skipping %s\", pyc_name)",
    "docstring": "Save given code_object as a .pyc file."
  },
  {
    "code": "def parse(self, element):\n        result = []\n        if element.text is not None and element.tag == self.identifier:\n            l, k = (0, 0)\n            raw = element.text.split()\n            while k < len(self.values):\n                dtype = self.dtype[k]\n                if isinstance(self.values[k], int):\n                    for i in range(self.values[k]):\n                        result.append(self._caster[dtype](raw[i + l]))\n                    l += self.values[k]\n                    k += 1\n                else:\n                    rest = [ self._caster[dtype](val) for val in raw[l::] ]\n                    result.extend(rest)\n                    break\n        else:\n            msg.warn(\"no results for parsing {} using line {}\".format(element.tag, self.identifier))\n        return result",
    "docstring": "Parses the contents of the specified XML element using template info.\n\n        :arg element: the XML element from the input file being converted."
  },
  {
    "code": "def replace_aliases(cut_dict, aliases):\n    for k, v in cut_dict.items():\n        for k0, v0 in aliases.items():\n            cut_dict[k] = cut_dict[k].replace(k0, '(%s)' % v0)",
    "docstring": "Substitute aliases in a cut dictionary."
  },
  {
    "code": "def parse(cls, fptr, offset, length):\n        num_bytes = offset + length - fptr.tell()\n        read_buffer = fptr.read(num_bytes)\n        ndr, = struct.unpack_from('>H', read_buffer, offset=0)\n        box_offset = 2\n        data_entry_url_box_list = []\n        for j in range(ndr):\n            box_fptr = io.BytesIO(read_buffer[box_offset:])\n            box_buffer = box_fptr.read(8)\n            (box_length, box_id) = struct.unpack_from('>I4s', box_buffer,\n                                                      offset=0)\n            box = DataEntryURLBox.parse(box_fptr, 0, box_length)\n            box.offset = offset + 8 + box_offset\n            data_entry_url_box_list.append(box)\n            box_offset += box_length\n        return cls(data_entry_url_box_list, length=length, offset=offset)",
    "docstring": "Parse data reference box.\n\n        Parameters\n        ----------\n        fptr : file\n            Open file object.\n        offset : int\n            Start position of box in bytes.\n        length : int\n            Length of the box in bytes.\n\n        Returns\n        -------\n        DataReferenceBox\n            Instance of the current data reference box."
  },
  {
    "code": "def Boolean(v):\n    if isinstance(v, basestring):\n        v = v.lower()\n        if v in ('1', 'true', 'yes', 'on', 'enable'):\n            return True\n        if v in ('0', 'false', 'no', 'off', 'disable'):\n            return False\n        raise ValueError\n    return bool(v)",
    "docstring": "Convert human-readable boolean values to a bool.\n\n    Accepted values are 1, true, yes, on, enable, and their negatives.\n    Non-string values are cast to bool.\n\n    >>> validate = Schema(Boolean())\n    >>> validate(True)\n    True\n    >>> validate(\"1\")\n    True\n    >>> validate(\"0\")\n    False\n    >>> with raises(MultipleInvalid, \"expected boolean\"):\n    ...   validate('moo')\n    >>> try:\n    ...  validate('moo')\n    ... except MultipleInvalid as e:\n    ...   assert isinstance(e.errors[0], BooleanInvalid)"
  },
  {
    "code": "def inserir(self, name, read, write, edit, remove):\n        ugroup_map = dict()\n        ugroup_map['nome'] = name\n        ugroup_map['leitura'] = read\n        ugroup_map['escrita'] = write\n        ugroup_map['edicao'] = edit\n        ugroup_map['exclusao'] = remove\n        code, xml = self.submit({'user_group': ugroup_map}, 'POST', 'ugroup/')\n        return self.response(code, xml)",
    "docstring": "Insert new user group and returns its identifier.\n\n        :param name: User group's name.\n        :param read: If user group has read permission ('S' ou 'N').\n        :param write: If user group has write permission ('S' ou 'N').\n        :param edit: If user group has edit permission ('S' ou 'N').\n        :param remove: If user group has remove permission ('S' ou 'N').\n\n        :return: Dictionary with structure: {'user_group': {'id': < id >}}\n\n        :raise InvalidParameterError: At least one of the parameters is invalid or none..\n        :raise NomeGrupoUsuarioDuplicadoError: User group name already exists.\n        :raise ValorIndicacaoPermissaoInvalidoError: Read, write, edit or remove value is invalid.\n        :raise DataBaseError: Networkapi failed to access database.\n        :raise XMLError: Networkapi fails generating response XML."
  },
  {
    "code": "def node_created_handler(sender, **kwargs):\n    if kwargs['created']:\n        obj = kwargs['instance']\n        queryset = exclude_owner_of_node(obj)\n        create_notifications.delay(**{\n            \"users\": queryset,\n            \"notification_model\": Notification,\n            \"notification_type\": \"node_created\",\n            \"related_object\": obj\n        })",
    "docstring": "send notification when a new node is created according to users's settings"
  },
  {
    "code": "def children_bp(self, feature, child_featuretype='exon', merge=False,\n                    ignore_strand=False):\n        children = self.children(feature, featuretype=child_featuretype,\n                                 order_by='start')\n        if merge:\n            children = self.merge(children, ignore_strand=ignore_strand)\n        total = 0\n        for child in children:\n            total += len(child)\n        return total",
    "docstring": "Total bp of all children of a featuretype.\n\n        Useful for getting the exonic bp of an mRNA.\n\n        Parameters\n        ----------\n\n        feature : str or Feature instance\n\n        child_featuretype : str\n            Which featuretype to consider.  For example, to get exonic bp of an\n            mRNA, use `child_featuretype='exon'`.\n\n        merge : bool\n            Whether or not to merge child features together before summing\n            them.\n\n        ignore_strand : bool\n            If True, then overlapping features on different strands will be\n            merged together; otherwise, merging features with different strands\n            will result in a ValueError.\n\n        Returns\n        -------\n        Integer representing the total number of bp."
  },
  {
    "code": "def _check_pretrained_file_names(cls, pretrained_file_name):\n        embedding_name = cls.__name__.lower()\n        if pretrained_file_name not in cls.pretrained_file_name_sha1:\n            raise KeyError('Cannot find pretrained file %s for token embedding %s. Valid '\n                           'pretrained files for embedding %s: %s' %\n                           (pretrained_file_name, embedding_name, embedding_name,\n                            ', '.join(cls.pretrained_file_name_sha1.keys())))",
    "docstring": "Checks if a pre-trained token embedding file name is valid.\n\n\n        Parameters\n        ----------\n        pretrained_file_name : str\n            The pre-trained token embedding file."
  },
  {
    "code": "def _deshuffle_field(self, *args):\n        ip = self._invpermutation\n        fields = []\n        for arg in args:\n            fields.append( arg[ip] )\n        if len(fields) == 1:\n            return fields[0]\n        else:\n            return fields",
    "docstring": "Return to original ordering"
  },
  {
    "code": "def getenv_int(key, default=0):\n    try:\n        return int(os.environ.get(key, str(default)))\n    except ValueError:\n        return default",
    "docstring": "Get an integer-valued environment variable `key`, if it exists and parses\n    as an integer, otherwise return `default`."
  },
  {
    "code": "def _validate_lattice_spacing(self, lattice_spacing):\n        dataType = np.float64\n        if lattice_spacing is not None:\n            lattice_spacing = np.asarray(lattice_spacing, dtype=dataType)\n            lattice_spacing = lattice_spacing.reshape((3,))\n            if np.shape(lattice_spacing) != (self.dimension,):\n                raise ValueError('Lattice spacing should be a vector of '\n                                 'size:({},). Please include lattice spacing '\n                                 'of size >= 0 depending on desired '\n                                 'dimensionality.'\n                                 .format(self.dimension))\n        else:\n            raise ValueError('No lattice_spacing provided. Please provide '\n                             'lattice spacing\\'s that are >= 0. with size ({},)'\n                             .format((self.dimension)))\n        if np.any(np.isnan(lattice_spacing)):\n            raise ValueError('None type or NaN type values present in '\n                             'lattice_spacing: {}.'.format(lattice_spacing))\n        elif np.any(lattice_spacing < 0.0):\n            raise ValueError('Negative lattice spacing value. One of '\n                             'the spacing: {} is negative.'\n                             .format(lattice_spacing))\n        self.lattice_spacing = lattice_spacing",
    "docstring": "Ensure that lattice spacing is provided and correct.\n\n        _validate_lattice_spacing will ensure that the lattice spacing\n        provided are acceptable values. Additional Numpy errors can also occur\n        due to the conversion to a Numpy array.\n\n        Exceptions Raised\n        -----------------\n        ValueError : Incorrect lattice_spacing input"
  },
  {
    "code": "def _decode(self, obj, context):\n        cls = self._get_class(obj.classID)\n        return cls.from_construct(obj, context)",
    "docstring": "Initialises a new Python class from a construct using the mapping\n        passed to the adapter."
  },
  {
    "code": "def close_project(self):\r\n        if self.current_active_project:\r\n            self.switch_to_plugin()\r\n            if self.main.editor is not None:\r\n                self.set_project_filenames(\r\n                    self.main.editor.get_open_filenames())\r\n            path = self.current_active_project.root_path\r\n            self.current_active_project = None\r\n            self.set_option('current_project_path', None)\r\n            self.setup_menu_actions()\r\n            self.sig_project_closed.emit(path)\r\n            self.sig_pythonpath_changed.emit()\r\n            if self.dockwidget is not None:\r\n                self.set_option('visible_if_project_open',\r\n                                self.dockwidget.isVisible())\r\n                self.dockwidget.close()\r\n            self.explorer.clear()\r\n            self.restart_consoles()",
    "docstring": "Close current project and return to a window without an active\r\n        project"
  },
  {
    "code": "def run_forever(self):\n        self.starting()\n        self.keep_running = True\n        def handle(signum, frame):\n            self.interrupt()\n            self.keep_running = False\n        signal.signal(signal.SIGINT, handle)\n        while self.keep_running:\n            if self.max_tasks and self.tasks_complete >= self.max_tasks:\n                self.stopping()\n            if self.gator.len():\n                result = self.gator.pop()\n                self.tasks_complete += 1\n                self.result(result)\n            if self.nap_time >= 0:\n                time.sleep(self.nap_time)\n        return 0",
    "docstring": "Causes the worker to run either forever or until the\n        ``Worker.max_tasks`` are reached."
  },
  {
    "code": "def refactor_rename_current_module(self, new_name):\n        refactor = Rename(self.project, self.resource, None)\n        return self._get_changes(refactor, new_name)",
    "docstring": "Rename the current module."
  },
  {
    "code": "async def send(self, sender, **kwargs):\n        if not self.receivers:\n            return []\n        responses = []\n        futures = []\n        for receiver in self._get_receivers(sender):\n            method = receiver()\n            if callable(method):\n                futures.append(method(sender=sender, **kwargs))\n        if len(futures) > 0:\n            responses = await asyncio.gather(*futures)\n        return responses",
    "docstring": "send a signal from the sender to all connected receivers"
  },
  {
    "code": "def get_hostname(self):\n        self.oem_init()\n        try:\n            return self._oem.get_hostname()\n        except exc.UnsupportedFunctionality:\n            return self.get_mci()",
    "docstring": "Get the hostname used by the BMC in various contexts\n\n        This can vary somewhat in interpretation, but generally speaking\n        this should be the name that shows up on UIs and in DHCP requests and\n        DNS registration requests, as applicable.\n\n        :return: current hostname"
  },
  {
    "code": "def _handle_authentication_error(self):\n        response = make_response('Access Denied')\n        response.headers['WWW-Authenticate'] = self.auth.get_authenticate_header()\n        response.status_code = 401\n        return response",
    "docstring": "Return an authentication error."
  },
  {
    "code": "def T_sigma(self, sigma):\n        R_sigma, Q_sigma = self.RQ_sigma(sigma)\n        return lambda v: R_sigma + self.beta * Q_sigma.dot(v)",
    "docstring": "Given a policy `sigma`, return the T_sigma operator.\n\n        Parameters\n        ----------\n        sigma : array_like(int, ndim=1)\n            Policy vector, of length n.\n\n        Returns\n        -------\n        callable\n            The T_sigma operator."
  },
  {
    "code": "def Lewis(D=None, alpha=None, Cp=None, k=None, rho=None):\n    r\n    if k and Cp and rho:\n        alpha = k/(rho*Cp)\n    elif alpha:\n        pass\n    else:\n        raise Exception('Insufficient information provided for Le calculation')\n    return alpha/D",
    "docstring": "r'''Calculates Lewis number or `Le` for a fluid with the given parameters.\n\n    .. math::\n        Le = \\frac{k}{\\rho C_p D} = \\frac{\\alpha}{D}\n\n    Inputs can be either of the following sets:\n\n    * Diffusivity and Thermal diffusivity\n    * Diffusivity, heat capacity, thermal conductivity, and density\n\n    Parameters\n    ----------\n    D : float\n        Diffusivity of a species, [m^2/s]\n    alpha : float, optional\n        Thermal diffusivity, [m^2/s]\n    Cp : float, optional\n        Heat capacity, [J/kg/K]\n    k : float, optional\n        Thermal conductivity, [W/m/K]\n    rho : float, optional\n        Density, [kg/m^3]\n\n    Returns\n    -------\n    Le : float\n        Lewis number []\n\n    Notes\n    -----\n    .. math::\n        Le=\\frac{\\text{Thermal diffusivity}}{\\text{Mass diffusivity}} =\n        \\frac{Sc}{Pr}\n\n    An error is raised if none of the required input sets are provided.\n\n    Examples\n    --------\n    >>> Lewis(D=22.6E-6, alpha=19.1E-6)\n    0.8451327433628318\n    >>> Lewis(D=22.6E-6, rho=800., k=.2, Cp=2200)\n    0.00502815768302494\n\n    References\n    ----------\n    .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n       Eighth Edition. McGraw-Hill Professional, 2007.\n    .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n       Applications. Boston: McGraw Hill Higher Education, 2006.\n    .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n       Berlin; New York:: Springer, 2010."
  },
  {
    "code": "def linear_chirp(npts=2000):\n    time = np.linspace(0, 20, npts)\n    chirp = np.sin(0.2 * np.pi * (0.1 + 24.0 / 2.0 * time) * time)\n    return chirp",
    "docstring": "Generates a simple linear chirp.\n\n    :param npts: Number of samples.\n    :type npts: int\n    :returns: Generated signal\n    :rtype: numpy.ndarray"
  },
  {
    "code": "def extract_translations(self, string):\n        trans = []\n        for t in Lexer(string.decode(\"utf-8\"), None).tokenize():\n            if t.token_type == TOKEN_BLOCK:\n                if not t.contents.startswith(\n                        (self.tranz_tag, self.tranzchoice_tag)):\n                    continue\n                is_tranzchoice = t.contents.startswith(\n                    self.tranzchoice_tag +\n                    \" \")\n                kwargs = {\n                    \"id\": self._match_to_transvar(id_re, t.contents),\n                    \"number\": self._match_to_transvar(number_re, t.contents),\n                    \"domain\": self._match_to_transvar(domain_re, t.contents),\n                    \"locale\": self._match_to_transvar(locale_re, t.contents),\n                    \"is_transchoice\": is_tranzchoice, \"parameters\": TransVar(\n                        [x.split(\"=\")[0].strip() for x in properties_re.findall(t.contents) if x],\n                        TransVar.LITERAL\n                    ),\n                    \"lineno\": t.lineno,\n                }\n                trans.append(Translation(**kwargs))\n        return trans",
    "docstring": "Extract messages from Django template string."
  },
  {
    "code": "def merged_pex(cls, path, pex_info, interpreter, pexes, interpeter_constraints=None):\n    pex_paths = [pex.path() for pex in pexes if pex]\n    if pex_paths:\n      pex_info = pex_info.copy()\n      pex_info.merge_pex_path(':'.join(pex_paths))\n    with safe_concurrent_creation(path) as safe_path:\n      builder = PEXBuilder(safe_path, interpreter, pex_info=pex_info)\n      if interpeter_constraints:\n        for constraint in interpeter_constraints:\n          builder.add_interpreter_constraint(constraint)\n      yield builder",
    "docstring": "Yields a pex builder at path with the given pexes already merged.\n\n    :rtype: :class:`pex.pex_builder.PEXBuilder`"
  },
  {
    "code": "def _set_extremum_session_metrics(session_group, aggregation_metric,\n                                  extremum_fn):\n  measurements = _measurements(session_group, aggregation_metric)\n  ext_session = extremum_fn(\n      measurements,\n      key=operator.attrgetter('metric_value.value')).session_index\n  del session_group.metric_values[:]\n  session_group.metric_values.MergeFrom(\n      session_group.sessions[ext_session].metric_values)",
    "docstring": "Sets the metrics for session_group to those of its \"extremum session\".\n\n  The extremum session is the session in session_group with the extremum value\n  of the metric given by 'aggregation_metric'. The extremum is taken over the\n  subset of sessions in the group whose 'aggregation_metric' was measured\n  at the largest training step among the sessions in the group.\n\n  Args:\n    session_group: A SessionGroup protobuffer.\n    aggregation_metric: A MetricName protobuffer.\n    extremum_fn: callable. Must be either 'min' or 'max'. Determines the type of\n      extremum to compute."
  },
  {
    "code": "def migrator(state):\n    cleverbot_kwargs, convos_kwargs = state\n    cb = Cleverbot(**cleverbot_kwargs)\n    for convo_kwargs in convos_kwargs:\n        cb.conversation(**convo_kwargs)\n    return cb",
    "docstring": "Nameless conversations will be lost."
  },
  {
    "code": "def devices(self):\n        install_devices = self.install_devices\n        if 'bootstrap-system-devices' in env.instance.config:\n            devices = set(env.instance.config['bootstrap-system-devices'].split())\n        else:\n            devices = set(self.sysctl_devices)\n            for sysctl_device in self.sysctl_devices:\n                for install_device in install_devices:\n                    if install_device.startswith(sysctl_device):\n                        devices.remove(sysctl_device)\n        return devices",
    "docstring": "computes the name of the disk devices that are suitable\n        installation targets by subtracting CDROM- and USB devices\n        from the list of total mounts."
  },
  {
    "code": "def _records_commit(record_ids):\n    for record_id in record_ids:\n        record = Record.get_record(record_id)\n        record.commit()",
    "docstring": "Commit all records."
  },
  {
    "code": "def version(self):\n        response = self.get(version=\"\", base=\"/version\")\n        response.raise_for_status()\n        data = response.json()\n        return (data[\"major\"], data[\"minor\"])",
    "docstring": "Get Kubernetes API version"
  },
  {
    "code": "def intersperse(x, ys):\n    it = iter(ys)\n    try:\n        y = next(it)\n    except StopIteration:\n        return\n    yield y\n    for y in it:\n        yield x\n        yield y",
    "docstring": "Returns an iterable where ``x`` is inserted between\n    each element of ``ys``\n\n    :type ys: Iterable"
  },
  {
    "code": "def gen_rsd_cdf(K, delta, c):\n    mu = gen_mu(K, delta, c)\n    return [sum(mu[:d+1]) for d in range(K)]",
    "docstring": "The CDF of the RSD on block degree, precomputed for\n    sampling speed"
  },
  {
    "code": "def call(self, tokens, *args, **kwargs):\n        tokens.append([evaluate, [args, kwargs], {}])\n        return tokens",
    "docstring": "Add args and kwargs to the tokens."
  },
  {
    "code": "def sync(ui, repo, **opts):\n\tif codereview_disabled:\n\t\traise hg_util.Abort(codereview_disabled)\n\tif not opts[\"local\"]:\n\t\tif hg_incoming(ui, repo):\n\t\t\terr = hg_pull(ui, repo, update=True)\n\t\telse:\n\t\t\terr = hg_update(ui, repo)\n\t\tif err:\n\t\t\treturn err\n\tsync_changes(ui, repo)",
    "docstring": "synchronize with remote repository\n\n\tIncorporates recent changes from the remote repository\n\tinto the local repository."
  },
  {
    "code": "def normalize_events_list(old_list):\n    new_list = []\n    for _event in old_list:\n        new_event = dict(_event)\n        if new_event.get('args'):\n            new_event['args'] = dict(new_event['args'])\n            encode_byte_values(new_event['args'])\n        if new_event.get('queue_identifier'):\n            del new_event['queue_identifier']\n        hexbytes_to_str(new_event)\n        name = new_event['event']\n        if name == 'EventPaymentReceivedSuccess':\n            new_event['initiator'] = to_checksum_address(new_event['initiator'])\n        if name in ('EventPaymentSentSuccess', 'EventPaymentSentFailed'):\n            new_event['target'] = to_checksum_address(new_event['target'])\n        encode_byte_values(new_event)\n        encode_object_to_str(new_event)\n        new_list.append(new_event)\n    return new_list",
    "docstring": "Internally the `event_type` key is prefixed with underscore but the API\n    returns an object without that prefix"
  },
  {
    "code": "def cmd_dist(self, nm=None, ch=None):\n        viewer = self.get_viewer(ch)\n        if viewer is None:\n            self.log(\"No current viewer/channel.\")\n            return\n        if nm is None:\n            rgbmap = viewer.get_rgbmap()\n            dist = rgbmap.get_dist()\n            self.log(str(dist))\n        else:\n            viewer.set_color_algorithm(nm)",
    "docstring": "dist nm=dist_name ch=chname\n\n        Set a color distribution for the given channel.\n        Possible values are linear, log, power, sqrt, squared, asinh, sinh,\n        and histeq.\n\n        If no value is given, reports the current color distribution\n        algorithm."
  },
  {
    "code": "def trade_history(\n        self, from_=None, count=None, from_id=None, end_id=None,\n        order=None, since=None, end=None, pair=None\n    ):\n        return self._trade_api_call(\n            'TradeHistory', from_=from_, count=count, from_id=from_id, end_id=end_id,\n            order=order, since=since, end=end, pair=pair\n        )",
    "docstring": "Returns trade history.\n        To use this method you need a privilege of the info key.\n\n        :param int or None from_: trade ID, from which the display starts (default 0)\n        :param int or None count: the number of trades for display\t(default 1000)\n        :param int or None from_id: trade ID, from which the display starts\t(default 0)\n        :param int or None end_id: trade ID on which the display ends (default inf.)\n        :param str or None order: sorting (default 'DESC')\n        :param int or None since: the time to start the display (default 0)\n        :param int or None end: the time to end the display\t(default inf.)\n        :param str or None pair: pair to be displayed (ex. 'btc_usd')"
  },
  {
    "code": "def main(**kwargs):\n    options = ApplicationOptions(**kwargs)\n    Event.configure(is_logging_enabled=options.event_logging)\n    application = Application(options)\n    application.run(options.definition)",
    "docstring": "The Pipeline tool."
  },
  {
    "code": "def decorator(func):\n        def function_timer(*args, **kwargs):\n            start = time.time()\n            value = func(*args, **kwargs)\n            end = time.time()\n            runtime = end - start\n            if runtime < 60:\n                runtime = str('sec: ' + str('{:f}'.format(runtime)))\n            else:\n                runtime = str('min: ' + str('{:f}'.format(runtime / 60)))\n            print('{func:50} --> {time}'.format(func=func.__qualname__, time=runtime))\n            return value\n        return function_timer",
    "docstring": "A function timer decorator."
  },
  {
    "code": "def launcher():\n    parser = OptionParser()\n    parser.add_option(\n        '-f',\n        '--file',\n        dest='filename',\n        default='agents.csv',\n        help='snmposter configuration file'\n    )\n    options, args = parser.parse_args()\n    factory = SNMPosterFactory()\n    snmpd_status = subprocess.Popen(\n        [\"service\", \"snmpd\", \"status\"],\n        stdout=subprocess.PIPE\n    ).communicate()[0]\n    if \"is running\" in snmpd_status:\n        message = \"snmd service is running. Please stop it and try again.\"\n        print >> sys.stderr, message\n        sys.exit(1)\n    try:\n        factory.configure(options.filename)\n    except IOError:\n        print >> sys.stderr, \"Error opening %s.\" % options.filename\n        sys.exit(1)\n    factory.start()",
    "docstring": "Launch it."
  },
  {
    "code": "def extract_version(exepath, version_arg, word_index=-1, version_rank=3):\n    if isinstance(version_arg, basestring):\n        version_arg = [version_arg]\n    args = [exepath] + version_arg\n    stdout, stderr, returncode = _run_command(args)\n    if returncode:\n        raise RezBindError(\"failed to execute %s: %s\\n(error code %d)\"\n                           % (exepath, stderr, returncode))\n    stdout = stdout.strip().split('\\n')[0].strip()\n    log(\"extracting version from output: '%s'\" % stdout)\n    try:\n        strver = stdout.split()[word_index]\n        toks = strver.replace('.', ' ').replace('-', ' ').split()\n        strver = '.'.join(toks[:version_rank])\n        version = Version(strver)\n    except Exception as e:\n        raise RezBindError(\"failed to parse version from output '%s': %s\"\n                           % (stdout, str(e)))\n    log(\"extracted version: '%s'\" % str(version))\n    return version",
    "docstring": "Run an executable and get the program version.\n\n    Args:\n        exepath: Filepath to executable.\n        version_arg: Arg to pass to program, eg \"-V\". Can also be a list.\n        word_index: Expect the Nth word of output to be the version.\n        version_rank: Cap the version to this many tokens.\n\n    Returns:\n        `Version` object."
  },
  {
    "code": "def use(self, id):\n        if self._connected and id > 0:\n            self.send_command('use', keys={'sid': id})",
    "docstring": "Use a particular Virtual Server instance\n        @param id: Virtual Server ID\n        @type id: int"
  },
  {
    "code": "def event(self, coro):\n        if not asyncio.iscoroutinefunction(coro):\n            raise TypeError('event registered must be a coroutine function')\n        setattr(self, coro.__name__, coro)\n        log.debug('%s has successfully been registered as an event', coro.__name__)\n        return coro",
    "docstring": "A decorator that registers an event to listen to.\n\n        You can find more info about the events on the :ref:`documentation below <discord-api-events>`.\n\n        The events must be a |corourl|_, if not, :exc:`TypeError` is raised.\n\n        Example\n        ---------\n\n        .. code-block:: python3\n\n            @client.event\n            async def on_ready():\n                print('Ready!')\n\n        Raises\n        --------\n        TypeError\n            The coroutine passed is not actually a coroutine."
  },
  {
    "code": "def get_texts_and_labels(sentence_chunk):\n    words = sentence_chunk.split('\\n')\n    texts = []\n    labels = []\n    for word in words:\n        word = word.strip()\n        if len(word) > 0:\n            toks = word.split('\\t')\n            texts.append(toks[0].strip())\n            labels.append(toks[-1].strip())\n    return texts, labels",
    "docstring": "Given a sentence chunk, extract original texts and labels."
  },
  {
    "code": "def _initalize_tree(self, position, momentum, slice_var, stepsize):\n        position_bar, momentum_bar, _ = self.simulate_dynamics(self.model, position, momentum, stepsize,\n                                                               self.grad_log_pdf).get_proposed_values()\n        _, logp_bar = self.grad_log_pdf(position_bar, self.model).get_gradient_log_pdf()\n        hamiltonian = logp_bar - 0.5 * np.dot(momentum_bar, momentum_bar)\n        candidate_set_size = slice_var < np.exp(hamiltonian)\n        accept_set_bool = hamiltonian > np.log(slice_var) - 10000\n        return position_bar, momentum_bar, candidate_set_size, accept_set_bool",
    "docstring": "Initalizes root node of the tree, i.e depth = 0"
  },
  {
    "code": "def get_existing_pipelines(self):\n        url = \"{0}/applications/{1}/pipelineConfigs\".format(API_URL, self.app_name)\n        resp = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)\n        assert resp.ok, 'Failed to lookup pipelines for {0}: {1}'.format(self.app_name, resp.text)\n        return resp.json()",
    "docstring": "Get existing pipeline configs for specific application.\n\n        Returns:\n            str: Pipeline config json"
  },
  {
    "code": "def _catch_exceptions(self, exctype, value, tb):\n        self.error('Uncaught exception', exc_info=(exctype, value, tb))\n        print_exception_formatted(exctype, value, tb)",
    "docstring": "Catches all exceptions and logs them."
  },
  {
    "code": "def create_translation_field(translated_field, language):\n    cls_name = translated_field.__class__.__name__\n    if not isinstance(translated_field, tuple(SUPPORTED_FIELDS.keys())):\n        raise ImproperlyConfigured(\"%s is not supported by Linguist.\" % cls_name)\n    translation_class = field_factory(translated_field.__class__)\n    kwargs = get_translation_class_kwargs(translated_field.__class__)\n    return translation_class(\n        translated_field=translated_field, language=language, **kwargs\n    )",
    "docstring": "Takes the original field, a given language, a decider model and return a\n    Field class for model."
  },
  {
    "code": "def upgradeCatalog1to2(oldCatalog):\n    newCatalog = oldCatalog.upgradeVersion('tag_catalog', 1, 2,\n                                           tagCount=oldCatalog.tagCount)\n    tags = newCatalog.store.query(Tag, Tag.catalog == newCatalog)\n    tagNames = tags.getColumn(\"name\").distinct()\n    for t in tagNames:\n        _TagName(store=newCatalog.store, catalog=newCatalog, name=t)\n    return newCatalog",
    "docstring": "Create _TagName instances which version 2 of Catalog automatically creates\n    for use in determining the tagNames result, but which version 1 of Catalog\n    did not create."
  },
  {
    "code": "def has_open_file(self, file_object):\n        return (file_object in [wrappers[0].get_object()\n                                for wrappers in self.open_files if wrappers])",
    "docstring": "Return True if the given file object is in the list of open files.\n\n        Args:\n            file_object: The FakeFile object to be checked.\n\n        Returns:\n            `True` if the file is open."
  },
  {
    "code": "def setImagePlotAutoRangeOn(self, axisNumber):\n        setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.yAxisRangeCti, axisNumber)",
    "docstring": "Sets the image plot's auto-range on for the axis with number axisNumber.\n\n            :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes)."
  },
  {
    "code": "def amax(data, axis=None, mapper=None, blen=None, storage=None,\n         create='array', **kwargs):\n    return reduce_axis(data, axis=axis, reducer=np.amax,\n                       block_reducer=np.maximum, mapper=mapper,\n                       blen=blen, storage=storage, create=create, **kwargs)",
    "docstring": "Compute the maximum value."
  },
  {
    "code": "def send_audio(self, url, name, **audioinfo):\n        return self.client.api.send_content(self.room_id, url, name, \"m.audio\",\n                                            extra_information=audioinfo)",
    "docstring": "Send a pre-uploaded audio to the room.\n\n        See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-audio\n        for audioinfo\n\n        Args:\n            url (str): The mxc url of the audio.\n            name (str): The filename of the audio.\n            audioinfo (): Extra information about the audio."
  },
  {
    "code": "def load_data(self, data):\n        dates = fill_date_range(self.start_date, self.end_date)\n        for row, date in zip(data, dates):\n            data = {'date': date}\n            if self.add:\n                for elem, vals in zip(self.parameter, row):\n                    data['elem'] = elem\n                    for add, val in zip(['value'] + self.add, vals):\n                        data[add] = val\n                    yield data\n            else:\n                for elem, val in zip(self.parameter, row):\n                    if elem.isdigit():\n                        elem = \"e%s\" % elem\n                    data[elem] = val\n                yield data",
    "docstring": "MultiStnData data results are arrays without explicit dates;\n        Infer time series based on start date."
  },
  {
    "code": "def _get_bottom_line_coordinates(self):\n        rect_x, rect_y, rect_width, rect_height = self.rect\n        start_point = rect_x, rect_y + rect_height\n        end_point = rect_x + rect_width, rect_y + rect_height\n        return start_point, end_point",
    "docstring": "Returns start and stop coordinates of bottom line"
  },
  {
    "code": "def get_api_user_key(self, api_dev_key, username=None, password=None):\n        username = username or get_config('pastebin', 'api_user_name')\n        password = password or get_config('pastebin', 'api_user_password')\n        if username and password:\n            data = {\n                'api_user_name': username,\n                'api_user_password': password,\n                'api_dev_key': api_dev_key,\n            }\n            urlencoded_data = urllib.urlencode(data)\n            req = urllib2.Request('http://pastebin.com/api/api_login.php',\n                                  urlencoded_data)\n            response = urllib2.urlopen(req)\n            user_key = response.read()\n            logging.debug(\"User key: %s\" % user_key)\n            return user_key\n        else:\n            logging.info(\"Pastebin: not using any user key\")\n            return \"\"",
    "docstring": "Get api user key to enable posts from user accounts if username\n        and password available.\n        Not getting an api_user_key means that the posts will be \"guest\" posts"
  },
  {
    "code": "def adjust_datetime_to_timezone(value, from_tz, to_tz=None):\n    if to_tz is None:\n        to_tz = settings.TIME_ZONE\n    if value.tzinfo is None:\n        if not hasattr(from_tz, \"localize\"):\n            from_tz = pytz.timezone(smart_str(from_tz))\n        value = from_tz.localize(value)\n    return value.astimezone(pytz.timezone(smart_str(to_tz)))",
    "docstring": "Given a ``datetime`` object adjust it according to the from_tz timezone\n    string into the to_tz timezone string."
  },
  {
    "code": "def get(self):\r\n        u\r\n        inputHookFunc = c_void_p.from_address(self.inputHookPtr).value\r\n        Cevent = INPUT_RECORD()\r\n        count = DWORD(0)\r\n        while 1:\r\n            if inputHookFunc:\r\n                call_function(inputHookFunc, ())\r\n            status = self.ReadConsoleInputW(self.hin, \r\n                                        byref(Cevent), 1, byref(count))\r\n            if status and count.value == 1:\r\n                e = event(self, Cevent)\r\n                return e",
    "docstring": "u'''Get next event from queue."
  },
  {
    "code": "def serve_forever(self, poll_interval=0.5):\n        while self.is_alive:\n            self.handle_request()\n            time.sleep(poll_interval)",
    "docstring": "Cycle for webserer"
  },
  {
    "code": "def request_get_user(self, user_ids) -> dict:\n        method_params = {'user_ids': user_ids}\n        response = self.session.send_method_request('users.get', method_params)\n        self.check_for_errors('users.get', method_params, response)\n        return response",
    "docstring": "Method to get users by ID, do not need authorization"
  },
  {
    "code": "def render_html(input_text, **context):\n    global g_parser\n    if g_parser is None:\n        g_parser = Parser()\n    return g_parser.format(input_text, **context)",
    "docstring": "A module-level convenience method that creates a default bbcode parser,\n    and renders the input string as HTML."
  },
  {
    "code": "def _smooth_best_span_estimates(self):\n        self._smoothed_best_spans = smoother.perform_smooth(self.x,\n                                                            self._best_span_at_each_point,\n                                                            MID_SPAN)",
    "docstring": "Apply a MID_SPAN smooth to the best span estimates at each observation."
  },
  {
    "code": "def find_by_id(self, user, params={}, **options): \n        path = \"/users/%s\" % (user)\n        return self.client.get(path, params, **options)",
    "docstring": "Returns the full user record for the single user with the provided ID.\n\n        Parameters\n        ----------\n        user : {String} An identifier for the user. Can be one of an email address,\n        the globally unique identifier for the user, or the keyword `me`\n        to indicate the current user making the request.\n        [params] : {Object} Parameters for the request"
  },
  {
    "code": "def build(self):\n        self._calculate_average_field_lengths()\n        self._create_field_vectors()\n        self._create_token_set()\n        return Index(\n            inverted_index=self.inverted_index,\n            field_vectors=self.field_vectors,\n            token_set=self.token_set,\n            fields=list(self._fields.keys()),\n            pipeline=self.search_pipeline,\n        )",
    "docstring": "Builds the index, creating an instance of `lunr.Index`.\n\n        This completes the indexing process and should only be called once all\n        documents have been added to the index."
  },
  {
    "code": "def set_xlim(self, xlims, dx, xscale, reverse=False):\n        self._set_axis_limits('x', xlims, dx, xscale, reverse)\n        return",
    "docstring": "Set x limits for plot.\n\n        This will set the limits for the x axis\n        for the specific plot.\n\n        Args:\n            xlims (len-2 list of floats): The limits for the axis.\n            dx (float): Amount to increment by between the limits.\n            xscale (str): Scale of the axis. Either `log` or `lin`.\n            reverse (bool, optional): If True, reverse the axis tick marks. Default is False."
  },
  {
    "code": "def header_size(self):\n        if not self.header:\n            return 0\n        max_entry = max(self.header.values(),\n                        key=lambda val: val['offset'])\n        return max_entry['offset'] + max_entry['value'].nbytes",
    "docstring": "Size of `file`'s header in bytes.\n\n        The size of the header is determined from `header`. If this is not\n        possible (i.e., before the header has been read), 0 is returned."
  },
  {
    "code": "def make_fixed_temp_multi_apec(kTs, name_template='apec%d', norm=None):\n    total_model = None\n    sub_models = []\n    for i, kT in enumerate(kTs):\n        component = ui.xsapec(name_template % i)\n        component.kT = kT\n        ui.freeze(component.kT)\n        if norm is not None:\n            component.norm = norm\n        sub_models.append(component)\n        if total_model is None:\n            total_model = component\n        else:\n            total_model = total_model + component\n    return total_model, sub_models",
    "docstring": "Create a model summing multiple APEC components at fixed temperatures.\n\n    *kTs*\n      An iterable of temperatures for the components, in keV.\n    *name_template* = 'apec%d'\n      A template to use for the names of each component; it is string-formatted\n      with the 0-based component number as an argument.\n    *norm* = None\n      An initial normalization to be used for every component, or None to use\n      the Sherpa default.\n    Returns:\n      A tuple ``(total_model, sub_models)``, where *total_model* is a Sherpa\n      model representing the sum of the APEC components and *sub_models* is\n      a list of the individual models.\n\n    This function creates a vector of APEC model components and sums them.\n    Their *kT* parameters are set and then frozen (using\n    :func:`sherpa.astro.ui.freeze`), so that upon exit from this function, the\n    amplitude of each component is the only free parameter."
  },
  {
    "code": "def makeSequenceAbsolute(relVSequence, minV, maxV):\n    return [(value * (maxV - minV)) + minV for value in relVSequence]",
    "docstring": "Makes every value in a sequence absolute"
  },
  {
    "code": "def _soap_client_call(method_name, *args):\n    soap_client = _build_soap_client()\n    soap_args = _convert_soap_method_args(*args)\n    if PYSIMPLESOAP_1_16_2:\n        return getattr(soap_client, method_name)(*soap_args)\n    else:\n        return getattr(soap_client, method_name)(soap_client, *soap_args)",
    "docstring": "Wrapper to call SoapClient method"
  },
  {
    "code": "def create_grupo_l3(self):\n        return GrupoL3(\n            self.networkapi_url,\n            self.user,\n            self.password,\n            self.user_ldap)",
    "docstring": "Get an instance of grupo_l3 services facade."
  },
  {
    "code": "def ensure_sequence_filter(data):\n    if not isinstance(data, (list, tuple, set, dict)):\n        return [data]\n    return data",
    "docstring": "Ensure sequenced data.\n\n    **sequence**\n\n        ensure that parsed data is a sequence\n\n    .. code-block:: jinja\n\n        {% set my_string = \"foo\" %}\n        {% set my_list = [\"bar\", ] %}\n        {% set my_dict = {\"baz\": \"qux\"} %}\n\n        {{ my_string|sequence|first }}\n        {{ my_list|sequence|first }}\n        {{ my_dict|sequence|first }}\n\n\n    will be rendered as:\n\n    .. code-block:: yaml\n\n        foo\n        bar\n        baz"
  },
  {
    "code": "def add_state(self, state, storage_load=False):\n        state_id = super(BarrierConcurrencyState, self).add_state(state)\n        if not storage_load and not self.__init_running and not state.state_id == UNIQUE_DECIDER_STATE_ID:\n            for o_id, o in list(state.outcomes.items()):\n                if not o_id == -1 and not o_id == -2:\n                    self.add_transition(state.state_id, o_id, self.states[UNIQUE_DECIDER_STATE_ID].state_id, None)\n        return state_id",
    "docstring": "Overwrite the parent class add_state method\n\n         Add automatic transition generation for the decider_state.\n\n        :param state: The state to be added\n        :return:"
  },
  {
    "code": "def put(self, artifact):\n    artifact = M2Coordinate.create(artifact)\n    if artifact.rev is None:\n      raise self.MissingVersion('Cannot pin an artifact to version \"None\"! {}'.format(artifact))\n    key = self._key(artifact)\n    previous = self._artifacts_to_versions.get(key)\n    self._artifacts_to_versions[key] = artifact\n    if previous != artifact:\n      self._id = None",
    "docstring": "Adds the given coordinate to the set, using its version to pin it.\n\n    If this set already contains an artifact with the same coordinates other than the version, it is\n    replaced by the new artifact.\n\n    :param M2Coordinate artifact: the artifact coordinate."
  },
  {
    "code": "def get_total_supply(self) -> int:\n        func = InvokeFunction('totalSupply')\n        response = self.__sdk.get_network().send_neo_vm_transaction_pre_exec(self.__hex_contract_address, None, func)\n        try:\n            total_supply = ContractDataParser.to_int(response['Result'])\n        except SDKException:\n            total_supply = 0\n        return total_supply",
    "docstring": "This interface is used to call the TotalSupply method in ope4\n        that return the total supply of the oep4 token.\n\n        :return: the total supply of the oep4 token."
  },
  {
    "code": "def update(self, a, b, c, d):\n        self.table.ravel()[:] = [a, b, c, d]\n        self.N = self.table.sum()",
    "docstring": "Update contingency table with new values without creating a new object."
  },
  {
    "code": "def _create_interface_specification(schema_graph, graphql_types, hidden_classes, cls_name):\n    def interface_spec():\n        abstract_inheritance_set = (\n            superclass_name\n            for superclass_name in sorted(list(schema_graph.get_inheritance_set(cls_name)))\n            if (superclass_name not in hidden_classes and\n                schema_graph.get_element_by_class_name(superclass_name).abstract)\n        )\n        return [\n            graphql_types[x]\n            for x in abstract_inheritance_set\n            if x not in hidden_classes\n        ]\n    return interface_spec",
    "docstring": "Return a function that specifies the interfaces implemented by the given type."
  },
  {
    "code": "def get(self, cls, rid):\n        self.validate_record_type(cls)\n        rows = self.db.select(cls, where={ID: rid}, limit=1)\n        if not rows:\n            raise KeyError('No {} record with id {}'.format(cls, rid))\n        return rows[0]",
    "docstring": "Return record of given type with key `rid`\n\n        >>> s = teststore()\n        >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'})\n        >>> r = s.get('tstoretest', '1')\n        >>> r['name']\n        'Toto'\n        >>> s.get('badcls', '1')\n        Traceback (most recent call last):\n            ...\n        ValueError: Unsupported record type \"badcls\"\n        >>> s.get('tstoretest', '2')\n        Traceback (most recent call last):\n            ...\n        KeyError: 'No tstoretest record with id 2'"
  },
  {
    "code": "async def read_reply(self):\n        code = 500\n        messages = []\n        go_on = True\n        while go_on:\n            try:\n                line = await self.readline()\n            except ValueError as e:\n                code = 500\n                go_on = False\n            else:\n                try:\n                    code = int(line[:3])\n                except ValueError as e:\n                    raise ConnectionResetError(\"Connection lost.\") from e\n                else:\n                    go_on = line[3:4] == b\"-\"\n            message = line[4:].strip(b\" \\t\\r\\n\").decode(\"ascii\")\n            messages.append(message)\n        full_message = \"\\n\".join(messages)\n        return code, full_message",
    "docstring": "Reads a reply from the server.\n\n        Raises:\n            ConnectionResetError: If the connection with the server is lost\n                (we can't read any response anymore). Or if the server\n                replies without a proper return code.\n\n        Returns:\n            (int, str): A (code, full_message) 2-tuple consisting of:\n\n                - server response code ;\n                - server response string corresponding to response code\n                  (multiline responses are returned in a single string)."
  },
  {
    "code": "def named_objs(objlist, namesdict=None):\n    objs = OrderedDict()\n    if namesdict is not None:\n        objtoname = {hashable(v): k for k, v in namesdict.items()}\n    for obj in objlist:\n        if namesdict is not None and hashable(obj) in objtoname:\n            k = objtoname[hashable(obj)]\n        elif hasattr(obj, \"name\"):\n            k = obj.name\n        elif hasattr(obj, '__name__'):\n            k = obj.__name__\n        else:\n            k = as_unicode(obj)\n        objs[k] = obj\n    return objs",
    "docstring": "Given a list of objects, returns a dictionary mapping from\n    string name for the object to the object itself. Accepts\n    an optional name,obj dictionary, which will override any other\n    name if that item is present in the dictionary."
  },
  {
    "code": "def block_events(self):\n        BaseObject.block_events(self)\n        for i in range(self._widget.topLevelItemCount()):\n            self._widget.topLevelItem(i).param.blockSignals(True)\n        return self",
    "docstring": "Special version of block_events that loops over all tree elements."
  },
  {
    "code": "def realign(self, cut_off, chains_to_skip = set()):\n        if cut_off != self.cut_off:\n            self.cut_off = cut_off\n            for c in self.chains:\n                if c not in chains_to_skip:\n                    self.clustal_matches[c] = None\n                    self.substring_matches[c] = None\n                    if self.alignment.get(c):\n                        del self.alignment[c]\n                    if self.seqres_to_uniparc_sequence_maps.get(c):\n                        del self.seqres_to_uniparc_sequence_maps[c]\n            self._align_with_clustal(chains_to_skip = chains_to_skip)\n            self._align_with_substrings(chains_to_skip = chains_to_skip)\n            self._check_alignments(chains_to_skip = chains_to_skip)\n            self._get_residue_mapping(chains_to_skip = chains_to_skip)",
    "docstring": "Alter the cut-off and run alignment again. This is much quicker than creating a new PDBUniParcSequenceAligner\n            object as the UniParcEntry creation etc. in the constructor does not need to be repeated.\n\n            The chains_to_skip argument (a Set) allows us to skip chains that were already matched which speeds up the alignment even more."
  },
  {
    "code": "def GetCampaignFeeds(client, feed, placeholder_type):\n  campaign_feed_service = client.GetService('CampaignFeedService', 'v201809')\n  campaign_feeds = []\n  more_pages = True\n  selector = {\n      'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'],\n      'predicates': [\n          {\n              'field': 'Status',\n              'operator': 'EQUALS',\n              'values': ['ENABLED']\n          },\n          {\n              'field': 'FeedId',\n              'operator': 'EQUALS',\n              'values': [feed['id']]\n          },\n          {\n              'field': 'PlaceholderTypes',\n              'operator': 'CONTAINS_ANY',\n              'values': [placeholder_type]\n          }\n      ],\n      'paging': {\n          'startIndex': 0,\n          'numberResults': PAGE_SIZE\n      }\n  }\n  while more_pages:\n    page = campaign_feed_service.get(selector)\n    if 'entries' in page:\n      campaign_feeds.extend(page['entries'])\n    selector['paging']['startIndex'] += PAGE_SIZE\n    more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries'])\n  return campaign_feeds",
    "docstring": "Get a list of Feed Item Ids used by a campaign via a given Campaign Feed.\n\n  Args:\n    client: an AdWordsClient instance.\n    feed: a Campaign Feed.\n    placeholder_type: the Placeholder Type.\n\n  Returns:\n    A list of Feed Item Ids."
  },
  {
    "code": "def _pfp__notify_update(self, child=None):\n        if getattr(self, \"_pfp__union_update_other_children\", True):\n            self._pfp__union_update_other_children = False\n            new_data = child._pfp__build()\n            new_stream =  bitwrap.BitwrappedStream(six.BytesIO(new_data))\n            for other_child in self._pfp__children:\n                if other_child is child:\n                    continue\n                if isinstance(other_child, Array) and other_child.is_stringable():\n                    other_child._pfp__set_value(new_data)\n                else:\n                    other_child._pfp__parse(new_stream)\n                new_stream.seek(0)\n            self._pfp__no_update_other_children = True\n        super(Union, self)._pfp__notify_update(child=child)",
    "docstring": "Handle a child with an updated value"
  },
  {
    "code": "def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):\n        for a, axe in axes.items():\n            if axe is not None:\n                mgr = mgr.reindex_axis(axe,\n                                       axis=self._get_block_manager_axis(a),\n                                       copy=False)\n        if copy:\n            mgr = mgr.copy()\n        if dtype is not None:\n            if len(mgr.blocks) > 1 or mgr.blocks[0].values.dtype != dtype:\n                mgr = mgr.astype(dtype=dtype)\n        return mgr",
    "docstring": "passed a manager and a axes dict"
  },
  {
    "code": "def getActors(self):\n        cl = vtk.vtkPropCollection()\n        self.GetActors(cl)\n        self.actors = []\n        cl.InitTraversal()\n        for i in range(self.GetNumberOfPaths()):\n            act = vtk.vtkActor.SafeDownCast(cl.GetNextProp())\n            if act.GetPickable():\n                self.actors.append(act)\n        return self.actors",
    "docstring": "Unpack a list of ``vtkActor`` objects from a ``vtkAssembly``."
  },
  {
    "code": "def MGMT_COMM_GET(self, Addr='ff02::1', TLVs=[]):\n        print '%s call MGMT_COMM_GET' % self.port\n        try:\n            cmd = 'commissioner mgmtget'\n            if len(TLVs) != 0:\n                tlvs = \"\".join(hex(tlv).lstrip(\"0x\").zfill(2) for tlv in TLVs)\n                cmd += ' binary '\n                cmd += tlvs\n            print cmd\n            return self.__sendCommand(cmd)[0] == 'Done'\n        except Exception, e:\n            ModuleHelper.WriteIntoDebugLogger(\"MGMT_COMM_GET() Error: \" + str(e))",
    "docstring": "send MGMT_COMM_GET command\n\n        Returns:\n            True: successful to send MGMT_COMM_GET\n            False: fail to send MGMT_COMM_GET"
  },
  {
    "code": "def _get_session(self):\n        if self._session is None:\n            session = self._session = self._database.session()\n            session.create()\n        return self._session",
    "docstring": "Create session as needed.\n\n        .. note::\n\n           Caller is responsible for cleaning up the session after\n           all partitions have been processed."
  },
  {
    "code": "def run_clients():\n    clients = request.form.get('clients')\n    if not clients:\n        return jsonify({'Error': 'no clients provided'})\n    result = {}\n    for client_id in clients.split(','):\n        if client_id not in drivers:\n            init_client(client_id)\n            init_timer(client_id)\n        result[client_id] = get_client_info(client_id)\n    return jsonify(result)",
    "docstring": "Force create driver for client"
  },
  {
    "code": "def get_conf_update(self):\n        dyn_conf = self.get_collection_rules()\n        if not dyn_conf:\n            return self.get_conf_file()\n        version = dyn_conf.get('version', None)\n        if version is None:\n            raise ValueError(\"ERROR: Could not find version in json\")\n        dyn_conf['file'] = self.collection_rules_file\n        logger.debug(\"Success reading config\")\n        config_hash = hashlib.sha1(json.dumps(dyn_conf).encode('utf-8')).hexdigest()\n        logger.debug('sha1 of config: %s', config_hash)\n        return dyn_conf",
    "docstring": "Get updated config from URL, fallback to local file if download fails."
  },
  {
    "code": "def mkdir(dir_path,\n          user=None,\n          group=None,\n          mode=None):\n    dir_path = os.path.expanduser(dir_path)\n    directory = os.path.normpath(dir_path)\n    if not os.path.isdir(directory):\n        makedirs_perms(directory, user, group, mode)\n    return True",
    "docstring": "Ensure that a directory is available.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' file.mkdir /opt/jetty/context"
  },
  {
    "code": "def offset(self, offset_value):\n        new_instance = deepcopy(self)\n        new_instance.poly_funct.coef[0] += offset_value\n        return new_instance",
    "docstring": "Return a copy of self, shifted a constant offset.\n\n        Parameters\n        ----------\n        offset_value : float\n            Number of pixels to shift the CCDLine."
  },
  {
    "code": "def close(self: Any) -> None:\n        if self._file_obj is not None:\n            self._file_obj.close()\n        self._file_obj = None",
    "docstring": "Close any files linked to this object"
  },
  {
    "code": "def is_inside_bounds(value, params):\n    if value in params:\n        return True\n    else:\n        if params.ndim == 1:\n            return params.contains_all(np.ravel(value))\n        else:\n            bcast_value = np.broadcast_arrays(*value)\n            stacked_value = np.vstack(bcast_value)\n            flat_value = stacked_value.reshape(params.ndim, -1)\n            return params.contains_all(flat_value)",
    "docstring": "Return ``True`` if ``value`` is contained in ``params``.\n\n    This method supports broadcasting in the sense that for\n    ``params.ndim >= 2``, if more than one value is given, the inputs\n    are broadcast against each other.\n\n    Parameters\n    ----------\n    value : `array-like`\n        Value(s) to be checked. For several inputs, the final bool\n        tells whether all inputs pass the check or not.\n    params : `IntervalProd`\n        Set in which the value is / the values are supposed to lie.\n\n    Returns\n    -------\n    is_inside_bounds : bool\n        ``True`` is all values lie in ``params``, ``False`` otherwise.\n\n    Examples\n    --------\n    Check a single point:\n\n    >>> params = odl.IntervalProd([0, 0], [1, 2])\n    >>> is_inside_bounds([0, 0], params)\n    True\n    >>> is_inside_bounds([0, -1], params)\n    False\n\n    Using broadcasting:\n\n    >>> pts_ax0 = np.array([0, 0, 1, 0, 1])[:, None]\n    >>> pts_ax1 = np.array([2, 0, 1])[None, :]\n    >>> is_inside_bounds([pts_ax0, pts_ax1], params)\n    True\n    >>> pts_ax1 = np.array([-2, 1])[None, :]\n    >>> is_inside_bounds([pts_ax0, pts_ax1], params)\n    False"
  },
  {
    "code": "def write(self, frames):\n        with HDFStore(self._path, 'w',\n                      complevel=self._complevel, complib=self._complib) \\\n                as store:\n            panel = pd.Panel.from_dict(dict(frames))\n            panel.to_hdf(store, 'updates')\n        with tables.open_file(self._path, mode='r+') as h5file:\n            h5file.set_node_attr('/', 'version', 0)",
    "docstring": "Write the frames to the target HDF5 file, using the format used by\n        ``pd.Panel.to_hdf``\n\n        Parameters\n        ----------\n        frames : iter[(int, DataFrame)] or dict[int -> DataFrame]\n            An iterable or other mapping of sid to the corresponding OHLCV\n            pricing data."
  },
  {
    "code": "def normalize_scheme(path, ext):\n    path = addextension(path, ext)\n    parsed = urlparse(path)\n    if parsed.scheme:\n        return path\n    else:\n        import os\n        dirname, filename = os.path.split(path)\n        if not os.path.isabs(dirname):\n            dirname = os.path.abspath(dirname)\n            path = os.path.join(dirname, filename)\n        return \"file://\" + path",
    "docstring": "Normalize scheme for paths related to hdfs"
  },
  {
    "code": "def pack(name, root, path=None, pack_format='tar', compress='bzip2'):\n    if pack_format == 'tar':\n        _tar(name, root, path, compress)",
    "docstring": "Pack up a directory structure, into a specific format\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt myminion genesis.pack centos /root/centos\n        salt myminion genesis.pack centos /root/centos pack_format='tar'"
  },
  {
    "code": "def check_plate_compatibility(tool, source_plate, sink_plate):\n        if sink_plate == source_plate.parent:\n            return None\n        if sink_plate.meta_data_id == source_plate.meta_data_id:\n            if sink_plate.is_sub_plate(source_plate):\n                return None\n            return \"Sink plate {} is not a simplification of source plate {}\".format(\n                sink_plate.plate_id, source_plate.plate_id)\n        meta_data_diff = set(source_plate.ancestor_meta_data_ids) - set(sink_plate.ancestor_meta_data_ids)\n        if len(meta_data_diff) == 1:\n            if tool.aggregation_meta_data not in meta_data_diff:\n                return \"Aggregate tool meta data ({}) \" \\\n                       \"does not match the diff between source and sink plates ({})\".format(\n                        tool.aggregation_meta_data, list(meta_data_diff)[0])\n        else:\n            return \"{} not in source's parent plates\".format(sink_plate.plate_id)",
    "docstring": "Checks whether the source and sink plate are compatible given the tool\n\n        :param tool: The tool\n        :param source_plate: The source plate\n        :param sink_plate: The sink plate\n        :return: Either an error, or None\n        :type tool: Tool\n        :type source_plate: Plate\n        :type sink_plate: Plate\n        :rtype: None | str"
  },
  {
    "code": "def eval(self, packet):\n        result = None\n        terms  = None\n        if self._when is None or self._when.eval(packet):\n            result = self._equation.eval(packet)\n        return result",
    "docstring": "Returns the result of evaluating this DNToEUConversion in the\n        context of the given Packet."
  },
  {
    "code": "def beta_array(C, HIGHSCALE, *args, **kwargs):\n    beta_odict = beta(C, HIGHSCALE, *args, **kwargs)\n    return np.hstack([np.asarray(b).ravel() for b in beta_odict.values()])",
    "docstring": "Return the beta functions of all SM parameters and SMEFT Wilson\n    coefficients as a 1D numpy array."
  },
  {
    "code": "def list_tables(self, dataset):\n        request = self.client.tables().list(projectId=dataset.project_id,\n                                            datasetId=dataset.dataset_id,\n                                            maxResults=1000)\n        response = request.execute()\n        while response is not None:\n            for t in response.get('tables', []):\n                yield t['tableReference']['tableId']\n            request = self.client.tables().list_next(request, response)\n            if request is None:\n                break\n            response = request.execute()",
    "docstring": "Returns the list of tables in a given dataset.\n\n           :param dataset:\n           :type dataset: BQDataset"
  },
  {
    "code": "def maybe_timeout_options(self):\n    if self._exit_timeout_start_time:\n      return NailgunProtocol.TimeoutOptions(self._exit_timeout_start_time, self._exit_timeout)\n    else:\n      return None",
    "docstring": "Implements the NailgunProtocol.TimeoutProvider interface."
  },
  {
    "code": "def register_predictor(cls, name):\n        def decorator(subclass):\n            cls._predictors[name.lower()] = subclass\n            subclass.name = name.lower()\n            return subclass\n        return decorator",
    "docstring": "Register method to keep list of predictors."
  },
  {
    "code": "def _default_service_formatter(\n        service_url,\n        width,\n        height,\n        background,\n        foreground,\n        options\n        ):\n        image_tmp = '{service_url}/{width}x{height}/{background}/{foreground}/'\n        image_url = image_tmp.format(\n            service_url=service_url,\n            width=width,\n            height=height,\n            background=background,\n            foreground=foreground\n            )\n        if options:\n            image_url += '?' + urlencode(options)\n        return image_url",
    "docstring": "Generate an image URL for a service"
  },
  {
    "code": "def exec_command(self, command):\n        m = Message()\n        m.add_byte(cMSG_CHANNEL_REQUEST)\n        m.add_int(self.remote_chanid)\n        m.add_string(\"exec\")\n        m.add_boolean(True)\n        m.add_string(command)\n        self._event_pending()\n        self.transport._send_user_message(m)\n        self._wait_for_event()",
    "docstring": "Execute a command on the server.  If the server allows it, the channel\n        will then be directly connected to the stdin, stdout, and stderr of\n        the command being executed.\n\n        When the command finishes executing, the channel will be closed and\n        can't be reused.  You must open a new channel if you wish to execute\n        another command.\n\n        :param str command: a shell command to execute.\n\n        :raises:\n            `.SSHException` -- if the request was rejected or the channel was\n            closed"
  },
  {
    "code": "def get_mesos_task(task_name):\n    tasks = get_mesos_tasks()\n    if tasks is not None:\n        for task in tasks:\n            if task['name'] == task_name:\n                return task\n    return None",
    "docstring": "Get a mesos task with a specific task name"
  },
  {
    "code": "def op_count(cls, crawler, stage=None):\n        if stage:\n            total_ops = conn.get(make_key(crawler, stage))\n        else:\n            total_ops = conn.get(make_key(crawler, \"total_ops\"))\n        return unpack_int(total_ops)",
    "docstring": "Total operations performed for this crawler"
  },
  {
    "code": "def scan(self):\n        self._logger.info(\"iface '%s' scans\", self.name())\n        self._wifi_ctrl.scan(self._raw_obj)",
    "docstring": "Trigger the wifi interface to scan."
  },
  {
    "code": "def _get_process_cwd(pid):\n    cmd = 'lsof -a -p {0} -d cwd -Fn'.format(pid)\n    data = common.shell_process(cmd)\n    if not data is None:\n        lines = str(data).split('\\n')\n        if len(lines) > 1:\n            return lines[1][1:] or None\n    return None",
    "docstring": "Returns the working directory for the provided process identifier.\n\n        `pid`\n            System process identifier.\n\n        Returns string or ``None``.\n\n        Note this is used as a workaround, since `psutil` isn't consistent on\n        being able to provide this path in all cases, especially MacOS X."
  },
  {
    "code": "def key(self, *args, _prefix=None, **kwargs):\n        if kwargs:\n            raise NotImplementedError(\n                'kwarg cache keys not implemented')\n        return (_prefix,) + tuple(args)",
    "docstring": "Get the cache key for the given function args.\n\n        Kwargs:\n           prefix: A constant to prefix to the key."
  },
  {
    "code": "def ScriptHash(self):\n        if self._scriptHash is None:\n            self._scriptHash = Crypto.ToScriptHash(self.Script, unhex=False)\n        return self._scriptHash",
    "docstring": "Get the script hash.\n\n        Returns:\n            UInt160:"
  },
  {
    "code": "def is_executable(path):\n  return os.path.isfile(path) and os.access(path, os.X_OK)",
    "docstring": "Returns whether a path names an existing executable file."
  },
  {
    "code": "def get_variable_for_feature(self, feature_key, variable_key):\n    feature = self.feature_key_map.get(feature_key)\n    if not feature:\n      self.logger.error('Feature with key \"%s\" not found in the datafile.' % feature_key)\n      return None\n    if variable_key not in feature.variables:\n      self.logger.error('Variable with key \"%s\" not found in the datafile.' % variable_key)\n      return None\n    return feature.variables.get(variable_key)",
    "docstring": "Get the variable with the given variable key for the given feature.\n\n    Args:\n      feature_key: The key of the feature for which we are getting the variable.\n      variable_key: The key of the variable we are getting.\n\n    Returns:\n      Variable with the given key in the given variation."
  },
  {
    "code": "def _is_potential_multi_index(columns):\n    return (len(columns) and not isinstance(columns, MultiIndex) and\n            all(isinstance(c, tuple) for c in columns))",
    "docstring": "Check whether or not the `columns` parameter\n    could be converted into a MultiIndex.\n\n    Parameters\n    ----------\n    columns : array-like\n        Object which may or may not be convertible into a MultiIndex\n\n    Returns\n    -------\n    boolean : Whether or not columns could become a MultiIndex"
  },
  {
    "code": "def pivot(self, index, **kwargs):\n        try:\n            df = self._pivot(index, **kwargs)\n            return pd.pivot_table(self.df, index=kwargs[\"index\"],  **kwargs)\n        except Exception as e:\n            self.err(e, \"Can not pivot dataframe\")",
    "docstring": "Pivots a dataframe"
  },
  {
    "code": "def _rotate(degrees:uniform):\n    \"Rotate image by `degrees`.\"\n    angle = degrees * math.pi / 180\n    return [[cos(angle), -sin(angle), 0.],\n            [sin(angle),  cos(angle), 0.],\n            [0.        ,  0.        , 1.]]",
    "docstring": "Rotate image by `degrees`."
  },
  {
    "code": "def parse_profile_from_hcard(hcard: str, handle: str):\n    from federation.entities.diaspora.entities import DiasporaProfile\n    doc = html.fromstring(hcard)\n    profile = DiasporaProfile(\n        name=_get_element_text_or_none(doc, \".fn\"),\n        image_urls={\n            \"small\": _get_element_attr_or_none(doc, \".entity_photo_small .photo\", \"src\"),\n            \"medium\": _get_element_attr_or_none(doc, \".entity_photo_medium .photo\", \"src\"),\n            \"large\": _get_element_attr_or_none(doc, \".entity_photo .photo\", \"src\"),\n        },\n        public=True if _get_element_text_or_none(doc, \".searchable\") == \"true\" else False,\n        id=handle,\n        handle=handle,\n        guid=_get_element_text_or_none(doc, \".uid\"),\n        public_key=_get_element_text_or_none(doc, \".key\"),\n    )\n    return profile",
    "docstring": "Parse all the fields we can from a hCard document to get a Profile.\n\n    :arg hcard: HTML hcard document (str)\n    :arg handle: User handle in username@domain.tld format\n    :returns: ``federation.entities.diaspora.entities.DiasporaProfile`` instance"
  },
  {
    "code": "def get_title(self, obj):\n        search_title = self.get_model_config_value(obj, 'search_title')\n        if not search_title:\n            return super().get_title(obj)\n        return search_title.format(**obj.__dict__)",
    "docstring": "Set search entry title for object"
  },
  {
    "code": "def access_token(self):\n        access_token = self.session.get(self.access_token_key)\n        if access_token:\n            if not self.expires_at:\n                return access_token\n            timestamp = time.time()\n            if self.expires_at - timestamp > 60:\n                return access_token\n        self.fetch_access_token()\n        return self.session.get(self.access_token_key)",
    "docstring": "WeChat access token"
  },
  {
    "code": "def descendants(self, unroll=False, skip_not_present=True, in_post_order=False):\n        for child in self.children(unroll, skip_not_present):\n            if in_post_order:\n                yield from child.descendants(unroll, skip_not_present, in_post_order)\n            yield child\n            if not in_post_order:\n                yield from child.descendants(unroll, skip_not_present, in_post_order)",
    "docstring": "Returns an iterator that provides nodes for all descendants of this\n        component.\n\n        Parameters\n        ----------\n        unroll : bool\n            If True, any children that are arrays are unrolled.\n\n        skip_not_present : bool\n            If True, skips children whose 'ispresent' property is set to False\n\n        in_post_order : bool\n            If True, descendants are walked using post-order traversal\n            (children first) rather than the default pre-order traversal\n            (parents first).\n\n        Yields\n        ------\n        :class:`~Node`\n            All descendant nodes of this component"
  },
  {
    "code": "def get_env(self):\n        env = super(KubeSpawner, self).get_env()\n        env['JUPYTER_IMAGE_SPEC'] = self.image\n        env['JUPYTER_IMAGE'] = self.image\n        return env",
    "docstring": "Return the environment dict to use for the Spawner.\n\n        See also: jupyterhub.Spawner.get_env"
  },
  {
    "code": "def error_wrapper(fn, error_class):\n    def wrapper(*args, **kwargs):\n        try:\n            return fn(*args, **kwargs)\n        except Exception as e:\n            six.reraise(error_class, error_class(e), sys.exc_info()[2])\n    return wrapper",
    "docstring": "Wraps function fn in a try catch block that re-raises error_class.\n\n    Args:\n        fn (function): function to wrapped\n        error_class (Exception): Error class to be re-raised\n\n    Returns:\n        (object): fn wrapped in a try catch."
  },
  {
    "code": "def collect_analysis(using):\n    python_analysis = defaultdict(dict)\n    for index in registry.indexes_for_connection(using):\n        python_analysis.update(index._doc_type.mapping._collect_analysis())\n    return stringer(python_analysis)",
    "docstring": "generate the analysis settings from Python land"
  },
  {
    "code": "def _mock_request(self, **kwargs):\n        model = kwargs.get('model')\n        service = model.service_model.endpoint_prefix\n        operation = model.name\n        LOG.debug('_make_request: %s.%s', service, operation)\n        return self.load_response(service, operation)",
    "docstring": "A mocked out make_request call that bypasses all network calls\n        and simply returns any mocked responses defined."
  },
  {
    "code": "def _deep_different(left, right, entry):\n    left = chunk_zip_entry(left, entry)\n    right = chunk_zip_entry(right, entry)\n    for ldata, rdata in zip_longest(left, right):\n        if ldata != rdata:\n            return True\n    return False",
    "docstring": "checks that entry is identical between ZipFile instances left and\n    right"
  },
  {
    "code": "def _read_data_type_2(self, length):\n        if length != 20:\n            raise ProtocolError(f'{self.alias}: [Typeno 2] invalid format')\n        _resv = self._read_fileng(4)\n        _home = self._read_fileng(16)\n        data = dict(\n            ip=ipaddress.ip_address(_home),\n        )\n        return data",
    "docstring": "Read IPv6-Route Type 2 data.\n\n        Structure of IPv6-Route Type 2 data [RFC 6275]:\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |  Next Header  | Hdr Ext Len=2 | Routing Type=2|Segments Left=1|\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |                            Reserved                           |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |                                                               |\n            +                                                               +\n            |                                                               |\n            +                         Home Address                          +\n            |                                                               |\n            +                                                               +\n            |                                                               |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n            Octets      Bits        Name                    Description\n              0           0     route.next              Next Header\n              1           8     route.length            Header Extensive Length\n              2          16     route.type              Routing Type\n              3          24     route.seg_left          Segments Left\n              4          32     -                       Reserved\n              8          64     route.ip                Home Address"
  },
  {
    "code": "def add_login_attempt_to_db(request, login_valid,\n                            get_username=get_username_from_request,\n                            username=None):\n    if not config.STORE_ACCESS_ATTEMPTS:\n        return\n    username = username or get_username(request)\n    user_agent = request.META.get('HTTP_USER_AGENT', '<unknown>')[:255]\n    ip_address = get_ip(request)\n    http_accept = request.META.get('HTTP_ACCEPT', '<unknown>')\n    path_info = request.META.get('PATH_INFO', '<unknown>')\n    if config.USE_CELERY:\n        from .tasks import add_login_attempt_task\n        add_login_attempt_task.delay(user_agent, ip_address, username,\n                                     http_accept, path_info, login_valid)\n    else:\n        store_login_attempt(user_agent, ip_address, username,\n                            http_accept, path_info, login_valid)",
    "docstring": "Create a record for the login attempt If using celery call celery\n    task, if not, call the method normally"
  },
  {
    "code": "def destroy(self, id):\n        path = '{}/destroy'.format(id)\n        url = utils.urljoin(self.url, path)\n        response = self.session.post(url)\n        return response.ok",
    "docstring": "Destroy a group.\n\n        :param str id: a group ID\n        :return: ``True`` if successful\n        :rtype: bool"
  },
  {
    "code": "def _idx_table_by_num(tables):\n    logger_jsons.info(\"enter idx_table_by_num\")\n    _tables = []\n    for name, table in tables.items():\n        try:\n            tmp = _idx_col_by_num(table)\n            _tables.append(tmp)\n        except Exception as e:\n            logger_jsons.error(\"idx_table_by_num: {}\".format(e))\n    logger_jsons.info(\"exit idx_table_by_num\")\n    return _tables",
    "docstring": "Switch tables to index-by-number\n\n    :param dict tables: Metadata\n    :return list _tables: Metadata"
  },
  {
    "code": "def formatBodyNode(root,path):\n    body        = root\n    body.name   = \"body\"\n    body.weight = calcFnWeight(body)\n    body.path   = path\n    body.pclass = None\n    return body",
    "docstring": "Format the root node for use as the body node."
  },
  {
    "code": "def _update_seek(self, offset, whence):\n        with self._seek_lock:\n            if whence == SEEK_SET:\n                self._seek = offset\n            elif whence == SEEK_CUR:\n                self._seek += offset\n            elif whence == SEEK_END:\n                self._seek = offset + self._size\n            else:\n                raise ValueError('whence value %s unsupported' % whence)\n        return self._seek",
    "docstring": "Update seek value.\n\n        Args:\n            offset (int): Offset.\n            whence (int): Whence.\n\n        Returns:\n            int: Seek position."
  },
  {
    "code": "def tags_with_text(xml, tags=None):\n    if tags is None:\n        tags = []\n    for element in xml:\n        if element.text is not None:\n            tags.append(element)\n        elif len(element) > 0:\n            tags_with_text(element, tags)\n        else:\n            message = 'Unknown XML structure: {}'.format(element)\n            raise ValueError(message)\n    return tags",
    "docstring": "Return a list of tags that contain text retrieved recursively from an\n    XML tree."
  },
  {
    "code": "def get_protein_substitution_language() -> ParserElement:\n    parser_element = psub_tag + nest(\n        amino_acid(PSUB_REFERENCE),\n        ppc.integer(PSUB_POSITION),\n        amino_acid(PSUB_VARIANT),\n    )\n    parser_element.setParseAction(_handle_psub)\n    return parser_element",
    "docstring": "Build a protein substitution parser."
  },
  {
    "code": "def title(self):\n        tmp = c.namemap_lookup(self.id) if c.namemap_lookup(self.id) is not None else self._title\n        return secure_filename(tmp)",
    "docstring": "get title of this node. If an entry for this course is found in the configuration namemap it is used, otherwise the default\n        value from stud.ip is used."
  },
  {
    "code": "def get_my_credits(self, access_token=None, user_id=None):\n        if access_token:\n            self.req.credential.set_token(access_token)\n        if user_id:\n            self.req.credential.set_user_id(user_id)\n        if not self.check_credentials():\n            raise CredentialsError('credentials invalid')\n        else:\n            user_data_url = '/users/' + self.req.credential.get_user_id()\n            user_data = self.req.get(user_data_url)\n            if \"credit\" in user_data:\n                if \"promotionalCodesUsed\" in user_data[\"credit\"]:\n                    del user_data[\"credit\"][\"promotionalCodesUsed\"]\n                if \"lastRefill\" in user_data[\"credit\"]:\n                    del user_data[\"credit\"][\"lastRefill\"]\n                return user_data[\"credit\"]\n            return {}",
    "docstring": "Get the credits by user to use in the QX Platform"
  },
  {
    "code": "def residuals(self, pars, x, y, order):\n        return y - self.fourier_series(pars, x, order)",
    "docstring": "Residual of Fourier Series.\n\n        Parameters\n        ----------\n        pars : array_like\n            Fourier series parameters.\n        x : array_like\n            An array of date.\n        y : array_like\n            An array of true values to fit.\n        order : int\n            An order of Fourier Series."
  },
  {
    "code": "def token(cls: Type[CLTVType], timestamp: int) -> CLTVType:\n        cltv = cls()\n        cltv.timestamp = str(timestamp)\n        return cltv",
    "docstring": "Return CLTV instance from timestamp\n\n        :param timestamp: Timestamp\n        :return:"
  },
  {
    "code": "def list_templates(self) -> List[str]:\n        result = set()\n        for loader in self._loaders():\n            for template in loader.list_templates():\n                result.add(str(template))\n        return list(result)",
    "docstring": "Returns a list of all avilable templates in environment.\n\n        This considers the loaders on the :attr:`app` and blueprints."
  },
  {
    "code": "def read_bytes(self, start_position: int, size: int) -> bytes:\n        return bytes(self._bytes[start_position:start_position + size])",
    "docstring": "Read a value from memory and return a fresh bytes instance"
  },
  {
    "code": "def fillna(self, value):\n        if not is_scalar(value):\n            raise TypeError('Value to replace with is not a valid scalar')\n        return Series(weld_replace(self.weld_expr,\n                                   self.weld_type,\n                                   default_missing_data_literal(self.weld_type),\n                                   value),\n                      self.index,\n                      self.dtype,\n                      self.name)",
    "docstring": "Returns Series with missing values replaced with value.\n\n        Parameters\n        ----------\n        value : {int, float, bytes, bool}\n            Scalar value to replace missing values with.\n\n        Returns\n        -------\n        Series\n            With missing values replaced."
  },
  {
    "code": "def point_dist2(p1, p2):\n    v = vector(p1, p2)\n    return np.dot(v, v)",
    "docstring": "compute the square of the euclidian distance between two 3D points\n\n    Args:\n        p1, p2: indexable objects with\n        indices 0, 1, 2 corresponding to 3D cartesian coordinates.\n    Returns:\n        The square of the euclidian distance between the points."
  },
  {
    "code": "async def delete_pattern(self, pattern, count=None):\n        cursor = '0'\n        count_deleted = 0\n        while cursor != 0:\n            cursor, identities = await self.client.scan(\n                cursor=cursor, match=pattern, count=count\n            )\n            count_deleted += await self.client.delete(*identities)\n        return count_deleted",
    "docstring": "delete cache according to pattern in redis,\n        delete `count` keys each time"
  },
  {
    "code": "def do_phonefy(self, query, **kwargs):\n        results = []\n        test = self.check_phonefy(query, kwargs)\n        if test:\n            r = {\n                \"type\": \"i3visio.phone\",\n                \"value\": self.platformName + \" - \" + query,\n                \"attributes\": []\n            }\n            try:\n                aux = {\n                    \"type\": \"i3visio.uri\",\n                    \"value\": self.createURL(query, mode=\"phonefy\"),\n                    \"attributes\": []\n                }\n                r[\"attributes\"].append(aux)\n            except:\n                pass\n            aux = {\n                \"type\": \"i3visio.platform\",\n                \"value\": self.platformName,\n                \"attributes\": []\n            }\n            r[\"attributes\"].append(aux)\n            r[\"attributes\"] += self.process_phonefy(test)\n            results.append(r)\n        return results",
    "docstring": "Verifying a phonefy query in this platform.\n\n        This might be redefined in any class inheriting from Platform.\n\n        Args:\n        -----\n            query: The element to be searched.\n\n        Return:\n        -------\n            A list of elements to be appended."
  },
  {
    "code": "def cumulative_gaps_to(self,\n                           when: datetime.datetime) -> datetime.timedelta:\n        gaps = self.gaps()\n        return gaps.cumulative_time_to(when)",
    "docstring": "Return the cumulative time within our gaps, up to ``when``."
  },
  {
    "code": "def parsetypes(dtype):\n    return [dtype[i].name.strip('1234567890').rstrip('ing') \n            for i in range(len(dtype))]",
    "docstring": "Parse the types from a structured numpy dtype object.\n\n    Return list of string representations of types from a structured numpy \n    dtype object, e.g. ['int', 'float', 'str'].\n\n    Used by :func:`tabular.io.saveSV` to write out type information in the \n    header.\n\n    **Parameters**\n\n        **dtype** :  numpy dtype object\n\n            Structured numpy dtype object to parse.\n\n    **Returns**\n\n        **out** :  list of strings\n\n            List of strings corresponding to numpy types::\n\n                [dtype[i].name.strip('1234567890').rstrip('ing') \\ \n                 for i in range(len(dtype))]"
  },
  {
    "code": "def owner(self, pathobj):\n        stat = self.stat(pathobj)\n        if not stat.is_dir:\n            return stat.modified_by\n        else:\n            return 'nobody'",
    "docstring": "Returns file owner\n        This makes little sense for Artifactory, but to be consistent\n        with pathlib, we return modified_by instead, if available"
  },
  {
    "code": "def get_html_column_count(html_string):\n    try:\n        from bs4 import BeautifulSoup\n    except ImportError:\n        print(\"ERROR: You must have BeautifulSoup to use html2data\")\n        return\n    soup = BeautifulSoup(html_string, 'html.parser')\n    table = soup.find('table')\n    if not table:\n        return 0\n    column_counts = []\n    trs = table.findAll('tr')\n    if len(trs) == 0:\n        return 0\n    for tr in range(len(trs)):\n        if tr == 0:\n            tds = trs[tr].findAll('th')\n            if len(tds) == 0:\n                tds = trs[tr].findAll('td')\n        else:\n            tds = trs[tr].findAll('td')\n        count = 0\n        for td in tds:\n            if td.has_attr('colspan'):\n                count += int(td['colspan'])\n            else:\n                count += 1\n        column_counts.append(count)\n    return max(column_counts)",
    "docstring": "Gets the number of columns in an html table.\n\n    Paramters\n    ---------\n    html_string : str\n\n    Returns\n    -------\n    int\n        The number of columns in the table"
  },
  {
    "code": "def selection(self, index):\n        self.update()\n        self.isActiveWindow()\n        self._parent.delete_btn.setEnabled(True)",
    "docstring": "Update selected row."
  },
  {
    "code": "def register_variable_compilation(self, path, compilation_cbk, listclass):\n        self.compilations_variable[path] = {\n            'callback':  compilation_cbk,\n            'listclass': listclass\n        }",
    "docstring": "Register given compilation method for variable on given path.\n\n        :param str path: JPath for given variable.\n        :param callable compilation_cbk: Compilation callback to be called.\n        :param class listclass: List class to use for lists."
  },
  {
    "code": "def is_correctness_available(self, question_id):\n        response = self.get_response(question_id)\n        if response.is_answered():\n            item = self._get_item(response.get_item_id())\n            return item.is_correctness_available_for_response(response)\n        return False",
    "docstring": "is a measure of correctness available for the question"
  },
  {
    "code": "def handle_profile_form(form):\n    form.process(formdata=request.form)\n    if form.validate_on_submit():\n        email_changed = False\n        with db.session.begin_nested():\n            current_userprofile.username = form.username.data\n            current_userprofile.full_name = form.full_name.data\n            db.session.add(current_userprofile)\n            if current_app.config['USERPROFILES_EMAIL_ENABLED'] and \\\n               form.email.data != current_user.email:\n                current_user.email = form.email.data\n                current_user.confirmed_at = None\n                db.session.add(current_user)\n                email_changed = True\n        db.session.commit()\n        if email_changed:\n            send_confirmation_instructions(current_user)\n            flash(_('Profile was updated. We have sent a verification '\n                    'email to %(email)s. Please check it.',\n                    email=current_user.email),\n                  category='success')\n        else:\n            flash(_('Profile was updated.'), category='success')",
    "docstring": "Handle profile update form."
  },
  {
    "code": "def addcols(self, desc, dminfo={}, addtoparent=True):\n        tdesc = desc\n        if 'name' in desc:\n            import casacore.tables.tableutil as pt\n            if len(desc) == 2 and 'desc' in desc:\n                tdesc = pt.maketabdesc(desc)\n            elif 'valueType' in desc:\n                cd = pt.makecoldesc(desc['name'], desc)\n                tdesc = pt.maketabdesc(cd)\n        self._addcols(tdesc, dminfo, addtoparent)\n        self._makerow()",
    "docstring": "Add one or more columns.\n\n        Columns can always be added to a normal table.\n        They can also be added to a reference table and optionally to its\n        parent table.\n\n        `desc`\n          contains a description of the column(s) to be added. It can be given\n          in three ways:\n\n          - a dict created by :func:`maketabdesc`. In this way multiple\n            columns can be added.\n          - a dict created by :func:`makescacoldesc`, :func:`makearrcoldesc`,\n            or :func:`makecoldesc`. In this way a single column can be added.\n          - a dict created by :func:`getcoldesc`. The key 'name' containing\n            the column name has to be defined in such a dict.\n\n        `dminfo`\n          can be used to provide detailed data manager info to tell how the\n          column(s) have to be stored. The dminfo of an existing column can be\n          obtained using method :func:`getdminfo`.\n        `addtoparent`\n          defines if the column should also be added to the parent table in\n          case the current table is a reference table (result of selection).\n          If True, it will be added to the parent if it does not exist yet.\n\n        For example, add a column using the same data manager type as another\n        column::\n\n          coldmi = t.getdminfo('colarrtsm')     # get dminfo of existing column\n          coldmi[\"NAME\"] = 'tsm2'               # give it a unique name\n          t.addcols (maketabdesc(makearrcoldesc(\"colarrtsm2\",0., ndim=2)),\n                     coldmi)"
  },
  {
    "code": "def incremental_value(self, slip_moment, mmax, mag_value, bbar, dbar):\n        delta_m = mmax - mag_value\n        a_3 = self._get_a3(bbar, dbar, slip_moment, mmax)\n        return a_3 * bbar * (np.exp(bbar * delta_m) - 1.0) * (delta_m > 0.0)",
    "docstring": "Returns the incremental rate with Mmax = Mag_value"
  },
  {
    "code": "def apply_transformation(self, structure):\n        sga = SpacegroupAnalyzer(structure, symprec=self.symprec,\n                                 angle_tolerance=self.angle_tolerance)\n        return sga.get_conventional_standard_structure(international_monoclinic=self.international_monoclinic)",
    "docstring": "Returns most primitive cell for structure.\n\n        Args:\n            structure: A structure\n\n        Returns:\n            The same structure in a conventional standard setting"
  },
  {
    "code": "def accept_kwargs(func):\n    def wrapped(val, **kwargs):\n        try:\n            return func(val, **kwargs)\n        except TypeError:\n            return func(val)\n    return wrapped",
    "docstring": "Wrap a function that may not accept kwargs so they are accepted\n\n    The output function will always have call signature of\n    :code:`func(val, **kwargs)`, whereas the original function may have\n    call signatures of :code:`func(val)` or :code:`func(val, **kwargs)`.\n    In the case of the former, rather than erroring, kwargs are just\n    ignored.\n\n    This method is called on serializer/deserializer function; these\n    functions always receive kwargs from serialize, but by using this,\n    the original functions may simply take a single value."
  },
  {
    "code": "def export_3_column(stimfunction,\n                    filename,\n                    temporal_resolution=100.0\n                    ):\n    stim_counter = 0\n    event_counter = 0\n    while stim_counter < stimfunction.shape[0]:\n        if stimfunction[stim_counter, 0] != 0:\n            event_onset = str(stim_counter / temporal_resolution)\n            weight = str(stimfunction[stim_counter, 0])\n            event_duration = 0\n            while stimfunction[stim_counter, 0] != 0 & stim_counter <= \\\n                    stimfunction.shape[0]:\n                event_duration = event_duration + 1\n                stim_counter = stim_counter + 1\n            event_duration = str(event_duration / temporal_resolution)\n            with open(filename, \"a\") as file:\n                file.write(event_onset + '\\t' + event_duration + '\\t' +\n                           weight + '\\n')\n            event_counter = event_counter + 1\n        stim_counter = stim_counter + 1",
    "docstring": "Output a tab separated three column timing file\n\n    This produces a three column tab separated text file, with the three\n    columns representing onset time (s), event duration (s) and weight,\n    respectively. Useful if you want to run the simulated data through FEAT\n    analyses. In a way, this is the reverse of generate_stimfunction\n\n    Parameters\n    ----------\n\n    stimfunction : timepoint by 1 array\n        The stimulus function describing the time course of events. For\n        instance output from generate_stimfunction.\n\n    filename : str\n        The name of the three column text file to be output\n\n    temporal_resolution : float\n        How many elements per second are you modeling with the\n        stimfunction?"
  },
  {
    "code": "def check_dimensions(self, dataset):\n        required_ctx = TestCtx(BaseCheck.HIGH, 'All geophysical variables are time-series incomplete feature types')\n        message = '{} must be a valid timeseries feature type. It must have dimensions of (timeSeries, time).'\n        message += ' And all coordinates must have dimensions of (timeSeries)'\n        for variable in util.get_geophysical_variables(dataset):\n            is_valid = util.is_multi_timeseries_incomplete(dataset, variable)\n            required_ctx.assert_true(\n                is_valid,\n                message.format(variable)\n            )\n        return required_ctx.to_result()",
    "docstring": "Checks that the feature types of this dataset are consitent with a time series incomplete dataset\n\n        :param netCDF4.Dataset dataset: An open netCDF dataset"
  },
  {
    "code": "def __request(self, url, params):\n        log.debug('request: %s %s' %(url, str(params)))\n        try:\n            response = urlopen(url, urlencode(params)).read()\n            if params.get('action') != 'data':\n                log.debug('response: %s' % response)\n            if params.get('action', None) == 'data':\n                return response\n            else:\n                return json.loads(response)\n        except TypeError, e:\n            log.exception('request error')\n            raise ServerError(e)\n        except IOError, e:\n            log.error('request error: %s' % str(e))\n            raise ServerError(e)",
    "docstring": "Make an HTTP POST request to the server and return JSON data. \n\n        :param url: HTTP URL to object.\n\n        :returns: Response as dict."
  },
  {
    "code": "def share(\n        self,\n        share_id: str,\n        token: dict = None,\n        augment: bool = False,\n        prot: str = \"https\",\n    ) -> dict:\n        share_url = \"{}://v1.{}.isogeo.com/shares/{}\".format(\n            prot, self.api_url, share_id\n        )\n        share_req = self.get(\n            share_url, headers=self.header, proxies=self.proxies, verify=self.ssl\n        )\n        checker.check_api_response(share_req)\n        share = share_req.json()\n        if augment:\n            share = utils.share_extender(\n                share, self.search(whole_share=1, share=share_id).get(\"results\")\n            )\n        else:\n            pass\n        return share",
    "docstring": "Get information about a specific share and its applications.\n\n        :param str token: API auth token\n        :param str share_id: share UUID\n        :param bool augment: option to improve API response by adding\n         some tags on the fly.\n        :param str prot: https [DEFAULT] or http\n         (use it only for dev and tracking needs)."
  },
  {
    "code": "def dissolved(self, concs):\n        new_concs = concs.copy()\n        for r in self.rxns:\n            if r.has_precipitates(self.substances):\n                net_stoich = np.asarray(r.net_stoich(self.substances))\n                s_net, s_stoich, s_idx = r.precipitate_stoich(self.substances)\n                new_concs -= new_concs[s_idx]/s_stoich * net_stoich\n        return new_concs",
    "docstring": "Return dissolved concentrations"
  },
  {
    "code": "def versions_from_archive(self):\n        py_vers = versions_from_trove(self.classifiers)\n        return [ver for ver in py_vers if ver != self.unsupported_version]",
    "docstring": "Return Python versions extracted from trove classifiers."
  },
  {
    "code": "def _node(self, tax_id):\n        s = select([self.nodes.c.parent_id, self.nodes.c.rank],\n                   self.nodes.c.tax_id == tax_id)\n        res = s.execute()\n        output = res.fetchone()\n        if not output:\n            msg = 'value \"{}\" not found in nodes.tax_id'.format(tax_id)\n            raise ValueError(msg)\n        else:\n            return output",
    "docstring": "Returns parent_id, rank\n\n        FIXME: expand return rank to include custom 'below' ranks built when\n               get_lineage is caled"
  },
  {
    "code": "def load_data(self, *args, **kwargs):\n        argpos = {\n            v['extras']['argpos']: k for k, v in self.parameters.iteritems()\n            if 'argpos' in v['extras']\n        }\n        data = dict(\n            {argpos[n]: a for n, a in enumerate(args)}, **kwargs\n        )\n        return self.apply_units_to_cache(data)",
    "docstring": "Collects positional and keyword arguments into `data` and applies units.\n\n        :return: data"
  },
  {
    "code": "def dump(cls, obj, file, protocol=0):\n        cls.save_option_state = True\n        pickle.dump(obj, file, protocol=protocol)\n        cls.save_option_state = False",
    "docstring": "Equivalent to pickle.dump except that the HoloViews option\n        tree is saved appropriately."
  },
  {
    "code": "def get_grid(start, end, nsteps=100):\n    step = (end-start) / float(nsteps)\n    return [start + i * step for i in xrange(nsteps+1)]",
    "docstring": "Generates a equal distanced list of float values with nsteps+1 values, begining start and ending with end.\n\n    :param start: the start value of the generated list.\n\n    :type float\n\n    :param end: the end value of the generated list.\n\n    :type float\n\n    :param nsteps: optional the number of steps (default=100), i.e. the generated list contains nstep+1 values.\n\n    :type int"
  },
  {
    "code": "def SpawnProcess(popen_args, passwd=None):\n  if passwd is not None:\n    p = subprocess.Popen(popen_args, stdin=subprocess.PIPE)\n    p.communicate(input=passwd)\n  else:\n    p = subprocess.Popen(popen_args)\n    p.wait()\n  if p.returncode != 0:\n    raise ErrorDuringRepacking(\" \".join(popen_args))",
    "docstring": "Spawns a process."
  },
  {
    "code": "def register_signals(self):\n        for index in self.indexes:\n            if index.object_type:\n                self._connect_signal(index)",
    "docstring": "Register signals for all indexes."
  },
  {
    "code": "def provision_system_user(items, database_name, overwrite=False, clear=False, skip_user_check=False):\n    from hfos.provisions.base import provisionList\n    from hfos.database import objectmodels\n    if overwrite is True:\n        hfoslog('Refusing to overwrite system user!', lvl=warn,\n                emitter='PROVISIONS')\n        overwrite = False\n    system_user_count = objectmodels['user'].count({'name': 'System'})\n    if system_user_count == 0 or clear is False:\n        provisionList(Users, 'user', overwrite, clear,  skip_user_check=True)\n        hfoslog('Provisioning: Users: Done.', emitter=\"PROVISIONS\")\n    else:\n        hfoslog('System user already present.', lvl=warn, emitter='PROVISIONS')",
    "docstring": "Provision a system user"
  },
  {
    "code": "def trigger(self, username, project, branch, **build_params):\n        method = 'POST'\n        url = ('/project/{username}/{project}/tree/{branch}?'\n               'circle-token={token}'.format(\n                   username=username, project=project,\n                   branch=branch, token=self.client.api_token))\n        if build_params is not None:\n            json_data = self.client.request(method, url,\n                                            build_parameters=build_params)\n        else:\n            json_data = self.client.request(method, url)\n        return json_data",
    "docstring": "Trigger new build and return a summary of the build."
  },
  {
    "code": "def run(analysis, path=None, name=None, info=None, **kwargs):\n    kwargs.update({\n        'analysis': analysis,\n        'path': path,\n        'name': name,\n        'info': info,\n    })\n    main(**kwargs)",
    "docstring": "Run a single analysis.\n\n    :param Analysis analysis: Analysis class to run.\n    :param str path: Path of analysis. Can be `__file__`.\n    :param str name: Name of the analysis.\n    :param dict info: Optional entries are ``version``, ``title``,\n        ``readme``, ...\n    :param dict static: Map[url regex, root-folder] to serve static content."
  },
  {
    "code": "def compare(self, other, t_threshold=1e-3, r_threshold=1e-3):\n        return compute_rmsd(self.t, other.t) < t_threshold and compute_rmsd(self.r, other.r) < r_threshold",
    "docstring": "Compare two transformations\n\n           The RMSD values of the rotation matrices and the translation vectors\n           are computed. The return value is True when the RMSD values are below\n           the thresholds, i.e. when the two transformations are almost\n           identical."
  },
  {
    "code": "def point_on_line(point, line_start, line_end, accuracy=50.):\n    length = dist(line_start, line_end)\n    ds = length / float(accuracy)\n    if -ds < (dist(line_start, point) + dist(point, line_end) - length) < ds:\n        return True\n    return False",
    "docstring": "Checks whether a point lies on a line\n\n    The function checks whether the point \"point\" (P) lies on the line defined by its starting point line_start (A) and\n    its end point line_end (B).\n    This is done by comparing the distance of [AB] with the sum of the distances [AP] and [PB]. If the difference is\n    smaller than [AB] / accuracy, the point P is assumed to be on the line. By increasing the value of accuracy (the\n    default is 50), the tolerance is decreased.\n    :param point: Point to be checked (tuple with x any y coordinate)\n    :param line_start: Starting point of the line (tuple with x any y coordinate)\n    :param line_end: End point of the line (tuple with x any y coordinate)\n    :param accuracy: The higher this value, the less distance is tolerated\n    :return: True if the point is one the line, False if not"
  },
  {
    "code": "def calc_secondary_parameters(self):\n        self.a = self.x/(2.*self.d**.5)\n        self.b = self.u/(2.*self.d**.5)",
    "docstring": "Determine the values of the secondary parameters `a` and `b`."
  },
  {
    "code": "def catch_result(task_func):\n    @functools.wraps(task_func, assigned=available_attrs(task_func))\n    def dec(*args, **kwargs):\n        orig_stdout = sys.stdout\n        sys.stdout = content = StringIO()\n        task_response = task_func(*args, **kwargs)\n        sys.stdout = orig_stdout\n        content.seek(0)\n        task_response['stdout'] = content.read()\n        return task_response\n    return dec",
    "docstring": "Catch printed result from Celery Task and return it in task response"
  },
  {
    "code": "def _warnCount(self, warnings, warningCount=None):\n        if not warningCount:\n            warningCount = {}\n        for warning in warnings:\n            wID = warning[\"warning_id\"]\n            if not warningCount.get(wID):\n                warningCount[wID] = {}\n                warningCount[wID][\"count\"] = 1\n                warningCount[wID][\"message\"] = warning.get(\"warning_message\")\n            else:\n                warningCount[wID][\"count\"] += 1\n        return warningCount",
    "docstring": "Calculate the count of each warning, being given a list of them.\n\n        @param warnings: L{list} of L{dict}s that come from\n            L{tools.parsePyLintWarnings}.\n        @param warningCount: A L{dict} produced by this method previously, if\n            you are adding to the warnings.\n\n        @return: L{dict} of L{dict}s for the warnings."
  },
  {
    "code": "def workspaces(self, index=None):\r\n        c = self.centralWidget()\r\n        if index is None:\r\n            return (c.widget(n) for n in range(c.count()))\r\n        else:\r\n            return c.widget(index)",
    "docstring": "return generator for all all workspace instances"
  },
  {
    "code": "def delete_network_precommit(self, context):\n        segments = context.network_segments\n        for segment in segments:\n            if not self.check_segment(segment):\n                return\n            vlan_id = segment.get(api.SEGMENTATION_ID)\n            if not vlan_id:\n                return\n            self.ucsm_db.delete_vlan_entry(vlan_id)\n            if any([True for ip, ucsm in CONF.ml2_cisco_ucsm.ucsms.items()\n                    if ucsm.sp_template_list]):\n                self.ucsm_db.delete_sp_template_for_vlan(vlan_id)\n            if any([True for ip, ucsm in CONF.ml2_cisco_ucsm.ucsms.items()\n                    if ucsm.vnic_template_list]):\n                self.ucsm_db.delete_vnic_template_for_vlan(vlan_id)",
    "docstring": "Delete entry corresponding to Network's VLAN in the DB."
  },
  {
    "code": "def backprop(self, input_data, targets,\n                 cache=None):\n        if cache is not None:\n            activations = cache\n        else:\n            activations = self.feed_forward(input_data, prediction=False)\n        if activations.shape != targets.shape:\n            raise ValueError('Activations (shape = %s) and targets (shape = %s) are different sizes' %\n                             (activations.shape, targets.shape))\n        delta = substract_matrix(activations, targets)\n        nan_to_zeros(delta, delta)\n        df_W = linalg.dot(input_data, delta, transa='T')\n        df_b = matrix_sum_out_axis(delta, 0)\n        df_input = linalg.dot(delta, self.W, transb='T')\n        if self.l1_penalty_weight:\n            df_W += self.l1_penalty_weight * sign(self.W)\n        if self.l2_penalty_weight:\n            df_W += self.l2_penalty_weight * self.W\n        return (df_W, df_b), df_input",
    "docstring": "Backpropagate through the logistic layer.\n\n        **Parameters:**\n\n        input_data : ``GPUArray``\n            Inpute data to compute activations for.\n\n        targets : ``GPUArray``\n            The target values of the units.\n\n        cache : list of ``GPUArray``\n            Cache obtained from forward pass. If the cache is\n            provided, then the activations are not recalculated.\n\n        **Returns:**\n\n        gradients : tuple of ``GPUArray``\n            Gradients with respect to the weights and biases in the\n            form ``(df_weights, df_biases)``.\n\n        df_input : ``GPUArray``\n            Gradients with respect to the input."
  },
  {
    "code": "def _keyboard_access(self, element):\n        if not element.has_attribute('tabindex'):\n            tag = element.get_tag_name()\n            if (tag == 'A') and (not element.has_attribute('href')):\n                element.set_attribute('tabindex', '0')\n            elif (\n                (tag != 'A')\n                and (tag != 'INPUT')\n                and (tag != 'BUTTON')\n                and (tag != 'SELECT')\n                and (tag != 'TEXTAREA')\n            ):\n                element.set_attribute('tabindex', '0')",
    "docstring": "Provide keyboard access for element, if it not has.\n\n        :param element: The element.\n        :type element: hatemile.util.html.htmldomelement.HTMLDOMElement"
  },
  {
    "code": "def get_list(self, key, pipeline=False):\n        if pipeline:\n            return self._pipeline.lrange(key, 0, -1)\n        return self._db.lrange(key, 0, -1)",
    "docstring": "Get all the value in the list stored at key.\n\n        Args:\n            key (str): Key where the list is stored.\n            pipeline (bool): True, start a transaction block. Default false.\n\n        Returns:\n            list: values in the list ordered by list index"
  },
  {
    "code": "def add_stream(self, name=None, tpld_id=None, state=XenaStreamState.enabled):\n        stream = XenaStream(parent=self, index='{}/{}'.format(self.index, len(self.streams)), name=name)\n        stream._create()\n        tpld_id = tpld_id if tpld_id else XenaStream.next_tpld_id\n        stream.set_attributes(ps_comment='\"{}\"'.format(stream.name), ps_tpldid=tpld_id)\n        XenaStream.next_tpld_id = max(XenaStream.next_tpld_id + 1, tpld_id + 1)\n        stream.set_state(state)\n        return stream",
    "docstring": "Add stream.\n\n        :param name: stream description.\n        :param tpld_id: TPLD ID. If None the a unique value will be set.\n        :param state: new stream state.\n        :type state: xenamanager.xena_stream.XenaStreamState\n        :return: newly created stream.\n        :rtype: xenamanager.xena_stream.XenaStream"
  },
  {
    "code": "def trk50(msg):\n    d = hex2bin(data(msg))\n    if d[11] == '0':\n        return None\n    sign = int(d[12])\n    value = bin2int(d[13:23])\n    if sign:\n        value = value - 1024\n    trk = value * 90.0 / 512.0\n    if trk < 0:\n        trk = 360 + trk\n    return round(trk, 3)",
    "docstring": "True track angle, BDS 5,0 message\n\n    Args:\n        msg (String): 28 bytes hexadecimal message (BDS50) string\n\n    Returns:\n        float: angle in degrees to true north (from 0 to 360)"
  },
  {
    "code": "def get_version(self, state=None, date=None):\n        version_model = self._meta._version_model\n        q = version_model.objects.filter(object_id=self.pk)\n        if state:\n            q = version_model.normal.filter(object_id=self.pk, state=state)\n        if date:\n            q = q.filter(date_published__lte=date)\n        q = q.order_by('-date_published')\n        results = q[:1]\n        if results:\n            return results[0]\n        return None",
    "docstring": "Get a particular version of an item\n\n        :param state: The state you want to get.\n        :param date: Get a version that was published before or on this date."
  },
  {
    "code": "def exception(self, url, exception):\n        return (time.time() + self.ttl, self.factory(url))",
    "docstring": "What to return when there's an exception."
  },
  {
    "code": "def remove_label(self, label):\n        self._logger.info('Removing label \"{}\"'.format(label))\n        count = self._matches[constants.LABEL_FIELDNAME].value_counts().get(\n            label, 0)\n        self._matches = self._matches[\n            self._matches[constants.LABEL_FIELDNAME] != label]\n        self._logger.info('Removed {} labelled results'.format(count))",
    "docstring": "Removes all results rows associated with `label`.\n\n        :param label: label to filter results on\n        :type label: `str`"
  },
  {
    "code": "def delete(self):\n        if not self._sync:\n            del self._buffer\n        shutil.rmtree(self.cache_dir)",
    "docstring": "Delete the write buffer and cache directory."
  },
  {
    "code": "def _GetDatabaseAccount(self):\n        try:\n            database_account = self._GetDatabaseAccountStub(self.DefaultEndpoint)\n            return database_account\n        except errors.HTTPFailure:\n            for location_name in self.PreferredLocations:\n                locational_endpoint = _GlobalEndpointManager.GetLocationalEndpoint(self.DefaultEndpoint, location_name)\n                try:\n                    database_account = self._GetDatabaseAccountStub(locational_endpoint)\n                    return database_account\n                except errors.HTTPFailure:\n                    pass\n            return None",
    "docstring": "Gets the database account first by using the default endpoint, and if that doesn't returns\n           use the endpoints for the preferred locations in the order they are specified to get \n           the database account."
  },
  {
    "code": "def get_corpus(args):\n    tokenizer = get_tokenizer(args)\n    return tacl.Corpus(args.corpus, tokenizer)",
    "docstring": "Returns a `tacl.Corpus`."
  },
  {
    "code": "def get_all_locators(self):\n        locators = []\n        self._lock.acquire()\n        try:\n            for reference in self._references:\n                locators.append(reference.get_locator())\n        finally:\n            self._lock.release()\n        return locators",
    "docstring": "Gets locators for all registered component references in this reference map.\n\n        :return: a list with component locators."
  },
  {
    "code": "def fromxlsx(filename, sheet=None, range_string=None, row_offset=0,\n             column_offset=0, **kwargs):\n    return XLSXView(filename, sheet=sheet, range_string=range_string,\n                    row_offset=row_offset, column_offset=column_offset,\n                    **kwargs)",
    "docstring": "Extract a table from a sheet in an Excel .xlsx file.\n\n    N.B., the sheet name is case sensitive.\n\n    The `sheet` argument can be omitted, in which case the first sheet in\n    the workbook is used by default.\n\n    The `range_string` argument can be used to provide a range string\n    specifying a range of cells to extract.\n\n    The `row_offset` and `column_offset` arguments can be used to\n    specify offsets.\n\n    Any other keyword arguments are passed through to\n    :func:`openpyxl.load_workbook()`."
  },
  {
    "code": "def format_raw_script(raw_script):\n    if six.PY2:\n        script = ' '.join(arg.decode('utf-8') for arg in raw_script)\n    else:\n        script = ' '.join(raw_script)\n    return script.strip()",
    "docstring": "Creates single script from a list of script parts.\n\n    :type raw_script: [basestring]\n    :rtype: basestring"
  },
  {
    "code": "def from_dict(self, mapdict):\n        self.name_format = mapdict[\"identifier\"]\n        try:\n            self._fro = dict(\n                [(k.lower(), v) for k, v in mapdict[\"fro\"].items()])\n        except KeyError:\n            pass\n        try:\n            self._to = dict([(k.lower(), v) for k, v in mapdict[\"to\"].items()])\n        except KeyError:\n            pass\n        if self._fro is None and self._to is None:\n            raise ConverterError(\"Missing specifications\")\n        if self._fro is None or self._to is None:\n            self.adjust()",
    "docstring": "Import the attribute map from  a dictionary\n\n        :param mapdict: The dictionary"
  },
  {
    "code": "def select_tmpltbank_class(curr_exe):\n    exe_to_class_map = {\n        'pycbc_geom_nonspinbank'  : PyCBCTmpltbankExecutable,\n        'pycbc_aligned_stoch_bank': PyCBCTmpltbankExecutable\n    }\n    try:\n        return exe_to_class_map[curr_exe]\n    except KeyError:\n        raise NotImplementedError(\n            \"No job class exists for executable %s, exiting\" % curr_exe)",
    "docstring": "This function returns a class that is appropriate for setting up\n    template bank jobs within workflow.\n\n    Parameters\n    ----------\n    curr_exe : string\n        The name of the executable to be used for generating template banks.\n\n    Returns\n    --------\n    exe_class : Sub-class of pycbc.workflow.core.Executable that holds utility\n        functions appropriate for the given executable.  Instances of the class\n        ('jobs') **must** have methods\n        * job.create_node()\n        and\n        * job.get_valid_times(ifo, )"
  },
  {
    "code": "def save(self):\n        resp = self.r_session.put(\n            self.document_url,\n            data=self.json(),\n            headers={'Content-Type': 'application/json'}\n        )\n        resp.raise_for_status()",
    "docstring": "Saves changes made to the locally cached SecurityDocument object's data\n        structures to the remote database."
  },
  {
    "code": "def _generate_username(self):\n        while True:\n            username = str(uuid.uuid4())\n            username = username.replace('-', '')\n            username = username[:-2]\n            try:\n                User.objects.get(username=username)\n            except User.DoesNotExist:\n                return username",
    "docstring": "Generate a unique username"
  },
  {
    "code": "def dummy_batch(m: nn.Module, size:tuple=(64,64))->Tensor:\n    \"Create a dummy batch to go through `m` with `size`.\"\n    ch_in = in_channels(m)\n    return one_param(m).new(1, ch_in, *size).requires_grad_(False).uniform_(-1.,1.)",
    "docstring": "Create a dummy batch to go through `m` with `size`."
  },
  {
    "code": "def hcf(num1, num2):\n    if num1 > num2:\n        smaller = num2\n    else:\n        smaller = num1\n    for i in range(1, smaller + 1):\n        if ((num1 % i == 0) and (num2 % i == 0)):\n            return i",
    "docstring": "Find the highest common factor of 2 numbers\n\n    :type num1: number\n    :param num1: The first number to find the hcf for\n\n    :type num2: number\n    :param num2: The second number to find the hcf for"
  },
  {
    "code": "def emulate_seek(fd, offset, chunk=CHUNK):\n    while chunk and offset > CHUNK:\n        fd.read(chunk)\n        offset -= chunk\n    fd.read(offset)",
    "docstring": "Emulates a seek on an object that does not support it\n\n    The seek is emulated by reading and discarding bytes until specified offset\n    is reached.\n\n    The ``offset`` argument is in bytes from start of file. The ``chunk``\n    argument can be used to adjust the size of the chunks in which read\n    operation is performed. Larger chunks will reach the offset in less reads\n    and cost less CPU but use more memory. Conversely, smaller chunks will be\n    more memory efficient, but cause more read operations and more CPU usage.\n\n    If chunk is set to None, then the ``offset`` amount of bytes is read at\n    once. This is fastest but depending on the offset size, may use a lot of\n    memory.\n\n    Default chunk size is controlled by the ``fsend.rangewrapper.CHUNK``\n    constant, which is 8KB by default.\n\n    This function has no return value."
  },
  {
    "code": "def config_to_options(config):\n    class Options:\n        host=config.get('smtp', 'host', raw=True)\n        port=config.getint('smtp', 'port')\n        to_addr=config.get('mail', 'to_addr', raw=True)\n        from_addr=config.get('mail', 'from_addr', raw=True)\n        subject=config.get('mail', 'subject', raw=True)\n        encoding=config.get('mail', 'encoding', raw=True)\n        username=config.get('auth', 'username')\n    opts = Options()\n    opts.from_addr % {'host': opts.host, 'prog': 'notify'}\n    opts.to_addr % {'host': opts.host, 'prog': 'notify'}\n    return opts",
    "docstring": "Convert ConfigParser instance to argparse.Namespace\n\n    Parameters\n    ----------\n    config : object\n        A ConfigParser instance\n\n    Returns\n    -------\n    object\n        An argparse.Namespace instance"
  },
  {
    "code": "def print_version():\n    click.echo(\"Versions:\")\n    click.secho(\n        \"CLI Package Version: %(version)s\"\n        % {\"version\": click.style(get_cli_version(), bold=True)}\n    )\n    click.secho(\n        \"API Package Version: %(version)s\"\n        % {\"version\": click.style(get_api_version(), bold=True)}\n    )",
    "docstring": "Print the environment versions."
  },
  {
    "code": "def get_interface_mode(args):\n    calculator_list = ['wien2k', 'abinit', 'qe', 'elk', 'siesta', 'cp2k',\n                       'crystal', 'vasp', 'dftbp', 'turbomole']\n    for calculator in calculator_list:\n        mode = \"%s_mode\" % calculator\n        if mode in args and args.__dict__[mode]:\n            return calculator\n    return None",
    "docstring": "Return calculator name\n\n    The calculator name is obtained from command option arguments where\n    argparse is used. The argument attribute name has to be\n    \"{calculator}_mode\". Then this method returns {calculator}."
  },
  {
    "code": "def _get_redirect_url(self, request):\n        if 'next' in request.session:\n            next_url = request.session['next']\n            del request.session['next']\n        elif 'next' in request.GET:\n            next_url = request.GET.get('next')\n        elif 'next' in request.POST:\n            next_url = request.POST.get('next')\n        else:\n            next_url = request.user.get_absolute_url()\n        if not next_url:\n            next_url = '/'\n        return next_url",
    "docstring": "Next gathered from session, then GET, then POST,\n        then users absolute url."
  },
  {
    "code": "def from_dict(cls, d):\n        if type(d) != dict:\n            raise TypeError('Expecting a <dict>, got a {0}'.format(type(d)))\n        obj = cls()\n        obj._full_data = d\n        obj._import_attributes(d)\n        obj._a_tags = obj._parse_a_tags(d)\n        return obj",
    "docstring": "Given a dict in python-zimbra format or XML, generate\n        a Python object."
  },
  {
    "code": "def network(self, borrow=False):\n        if self._network is None and self.network_json is not None:\n            self.load_weights()\n            if borrow:\n                return self.borrow_cached_network(\n                    self.network_json,\n                    self.network_weights)\n            else:\n                import keras.models\n                self._network = keras.models.model_from_json(self.network_json)\n                if self.network_weights is not None:\n                    self._network.set_weights(self.network_weights)\n                self.network_json = None\n                self.network_weights = None\n        return self._network",
    "docstring": "Return the keras model associated with this predictor.\n\n        Parameters\n        ----------\n        borrow : bool\n            Whether to return a cached model if possible. See\n            borrow_cached_network for details\n\n        Returns\n        -------\n        keras.models.Model"
  },
  {
    "code": "def _system_parameters(**kwargs):\n    return {key: value for key, value in kwargs.items()\n            if (value is not None or value == {})}",
    "docstring": "Returns system keyword arguments removing Nones.\n\n    Args:\n        kwargs: system keyword arguments.\n\n    Returns:\n        dict: system keyword arguments."
  },
  {
    "code": "def compareBIM(args):\n    class Dummy(object):\n        pass\n    compareBIM_args = Dummy()\n    compareBIM_args.before = args.bfile + \".bim\"\n    compareBIM_args.after = args.out + \".bim\"\n    compareBIM_args.out = args.out + \".removed_snps\"\n    try:\n        CompareBIM.checkArgs(compareBIM_args)\n        beforeBIM = CompareBIM.readBIM(compareBIM_args.before)\n        afterBIM = CompareBIM.readBIM(compareBIM_args.after)\n        CompareBIM.compareSNPs(beforeBIM, afterBIM, compareBIM_args.out)\n    except CompareBIM.ProgramError as e:\n        raise ProgramError(\"CompareBIM: \" + e.message)",
    "docstring": "Compare two BIM file.\n\n    :param args: the options.\n\n    :type args: argparse.Namespace\n\n    Creates a *Dummy* object to mimic an :py:class:`argparse.Namespace` class\n    containing the options for the :py:mod:`pyGenClean.PlinkUtils.compare_bim`\n    module."
  },
  {
    "code": "def hook(self, debug, pid):\n        label = \"%s!%s\" % (self.__modName, self.__procName)\n        try:\n            hook = self.__hook[pid]\n        except KeyError:\n            try:\n                aProcess = debug.system.get_process(pid)\n            except KeyError:\n                aProcess = Process(pid)\n            hook = Hook(self.__preCB, self.__postCB,\n                        self.__paramCount, self.__signature,\n                        aProcess.get_arch() )\n            self.__hook[pid] = hook\n        hook.hook(debug, pid, label)",
    "docstring": "Installs the API hook on a given process and module.\n\n        @warning: Do not call from an API hook callback.\n\n        @type  debug: L{Debug}\n        @param debug: Debug object.\n\n        @type  pid: int\n        @param pid: Process ID."
  },
  {
    "code": "def repo_exists(self, auth, username, repo_name):\n        path = \"/repos/{u}/{r}\".format(u=username, r=repo_name)\n        return self._get(path, auth=auth).ok",
    "docstring": "Returns whether a repository with name ``repo_name`` owned by the user with username ``username`` exists.\n\n        :param auth.Authentication auth: authentication object\n        :param str username: username of owner of repository\n        :param str repo_name: name of repository\n        :return: whether the repository exists\n        :rtype: bool\n        :raises NetworkFailure: if there is an error communicating with the server\n        :raises ApiFailure: if the request cannot be serviced"
  },
  {
    "code": "def gamma_reset(self):\n        with open(self._fb_device) as f:\n            fcntl.ioctl(f, self.SENSE_HAT_FB_FBIORESET_GAMMA, self.SENSE_HAT_FB_GAMMA_DEFAULT)",
    "docstring": "Resets the LED matrix gamma correction to default"
  },
  {
    "code": "def altz_to_utctz_str(altz):\n    utci = -1 * int((float(altz) / 3600) * 100)\n    utcs = str(abs(utci))\n    utcs = \"0\" * (4 - len(utcs)) + utcs\n    prefix = (utci < 0 and '-') or '+'\n    return prefix + utcs",
    "docstring": "As above, but inverses the operation, returning a string that can be used\n    in commit objects"
  },
  {
    "code": "def create_job(name=None,\n               config_xml=None,\n               saltenv='base'):\n    if not name:\n        raise SaltInvocationError('Required parameter \\'name\\' is missing')\n    if job_exists(name):\n        raise CommandExecutionError('Job \\'{0}\\' already exists'.format(name))\n    if not config_xml:\n        config_xml = jenkins.EMPTY_CONFIG_XML\n    else:\n        config_xml_file = _retrieve_config_xml(config_xml, saltenv)\n        with salt.utils.files.fopen(config_xml_file) as _fp:\n            config_xml = salt.utils.stringutils.to_unicode(_fp.read())\n    server = _connect()\n    try:\n        server.create_job(name, config_xml)\n    except jenkins.JenkinsException as err:\n        raise CommandExecutionError(\n            'Encountered error creating job \\'{0}\\': {1}'.format(name, err)\n        )\n    return config_xml",
    "docstring": "Return the configuration file.\n\n    :param name: The name of the job is check if it exists.\n    :param config_xml: The configuration file to use to create the job.\n    :param saltenv: The environment to look for the file in.\n    :return: The configuration file used for the job.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' jenkins.create_job jobname\n\n        salt '*' jenkins.create_job jobname config_xml='salt://jenkins/config.xml'"
  },
  {
    "code": "def connect(self):\n        if self.session and self.session.is_expired:\n            self.disconnect(abandon_session=True)\n        if not self.session:\n            try:\n                login_result = self.login(self.username, self.password)\n            except AccountFault:\n                log.error('Login failed, invalid username or password')\n                raise\n            else:\n                self.session = login_result.session_id\n        self.connected = time()\n        return self.connected",
    "docstring": "Connects to the Responsys soap service\n\n        Uses the credentials passed to the client init to login and setup the session id returned.\n        Returns True on successful connection, otherwise False."
  },
  {
    "code": "def get_finished(self):\n        indices  = []\n        for idf, v in self.q.items():\n            if v.poll() != None:\n                indices.append(idf)\n        for i in indices:\n            self.q.pop(i)\n        return indices",
    "docstring": "Clean up terminated processes and returns the list of their ids"
  },
  {
    "code": "def create_dep(self, projects):\n        dialog = DepCreatorDialog(projects=projects, parent=self)\n        dialog.exec_()\n        dep = dialog.dep\n        return dep",
    "docstring": "Create and return a new dep\n\n        :param projects: the projects for the dep\n        :type projects: :class:`jukeboxcore.djadapter.models.Project`\n        :returns: The created dep or None\n        :rtype: None | :class:`jukeboxcore.djadapter.models.Dep`\n        :raises: None"
  },
  {
    "code": "def fix(self, to_file=None):\n        self.packer_cmd = self.packer.fix\n        self._add_opt(self.packerfile)\n        result = self.packer_cmd()\n        if to_file:\n            with open(to_file, 'w') as f:\n                f.write(result.stdout.decode())\n        result.fixed = json.loads(result.stdout.decode())\n        return result",
    "docstring": "Implements the `packer fix` function\n\n        :param string to_file: File to output fixed template to"
  },
  {
    "code": "def get_root_dir(self):\n        if os.path.isdir(self.root_path):\n            return self.root_path\n        else:\n            return os.path.dirname(self.root_path)",
    "docstring": "Retrieve the absolute path to the root directory of this data source.\n\n        Returns:\n            str: absolute path to the root directory of this data source."
  },
  {
    "code": "def call_git_branch():\n    try:\n        with open(devnull, \"w\") as fnull:\n            arguments = [GIT_COMMAND, 'rev-parse', '--abbrev-ref', 'HEAD']\n            return check_output(arguments, cwd=CURRENT_DIRECTORY,\n                                stderr=fnull).decode(\"ascii\").strip()\n    except (OSError, CalledProcessError):\n        return None",
    "docstring": "return the string output of git desribe"
  },
  {
    "code": "def calc_secondary_parameters(self):\n        self.c = 1./(self.k*special.gamma(self.n))",
    "docstring": "Determine the value of the secondary parameter `c`."
  },
  {
    "code": "def _change_source_state(name, state):\n    choc_path = _find_chocolatey(__context__, __salt__)\n    cmd = [choc_path, 'source', state, '--name', name]\n    result = __salt__['cmd.run_all'](cmd, python_shell=False)\n    if result['retcode'] != 0:\n        raise CommandExecutionError(\n            'Running chocolatey failed: {0}'.format(result['stdout'])\n        )\n    return result['stdout']",
    "docstring": "Instructs Chocolatey to change the state of a source.\n\n    name\n        Name of the repository to affect.\n\n    state\n        State in which you want the chocolatey repository."
  },
  {
    "code": "def receive(self, sock):\n    msg = None\n    data = b''\n    recv_done = False\n    recv_len = -1\n    while not recv_done:\n      buf = sock.recv(BUFSIZE)\n      if buf is None or len(buf) == 0:\n        raise Exception(\"socket closed\")\n      if recv_len == -1:\n        recv_len = struct.unpack('>I', buf[:4])[0]\n        data += buf[4:]\n        recv_len -= len(data)\n      else:\n        data += buf\n        recv_len -= len(buf)\n      recv_done = (recv_len == 0)\n    msg = pickle.loads(data)\n    return msg",
    "docstring": "Receive a message on ``sock``."
  },
  {
    "code": "def edit(self, tag_name=None, target_commitish=None, name=None, body=None,\n             draft=None, prerelease=None):\n        url = self._api\n        data = {\n            'tag_name': tag_name,\n            'target_commitish': target_commitish,\n            'name': name,\n            'body': body,\n            'draft': draft,\n            'prerelease': prerelease,\n        }\n        self._remove_none(data)\n        r = self._session.patch(\n            url, data=json.dumps(data), headers=Release.CUSTOM_HEADERS\n        )\n        successful = self._boolean(r, 200, 404)\n        if successful:\n            self.__init__(r.json(), self)\n        return successful",
    "docstring": "Users with push access to the repository can edit a release.\n\n        If the edit is successful, this object will update itself.\n\n        :param str tag_name: (optional), Name of the tag to use\n        :param str target_commitish: (optional), The \"commitish\" value that\n            determines where the Git tag is created from. Defaults to the\n            repository's default branch.\n        :param str name: (optional), Name of the release\n        :param str body: (optional), Description of the release\n        :param boolean draft: (optional), True => Release is a draft\n        :param boolean prerelease: (optional), True => Release is a prerelease\n        :returns: True if successful; False if not successful"
  },
  {
    "code": "def purgeDeletedWidgets():\n        toremove = []\n        for field in AbstractEditorWidget.funit_fields:\n            if sip.isdeleted(field):\n                toremove.append(field)\n        for field in toremove:\n            AbstractEditorWidget.funit_fields.remove(field)\n        toremove = []\n        for field in AbstractEditorWidget.tunit_fields:\n            if sip.isdeleted(field):\n                toremove.append(field)\n        for field in toremove:\n            AbstractEditorWidget.tunit_fields.remove(field)",
    "docstring": "Finds old references to stashed fields and deletes them"
  },
  {
    "code": "def make_csr(A):\n    if not (isspmatrix_csr(A) or isspmatrix_bsr(A)):\n        try:\n            A = csr_matrix(A)\n            print('Implicit conversion of A to CSR in pyamg.blackbox.make_csr')\n        except BaseException:\n            raise TypeError('Argument A must have type csr_matrix or\\\n                    bsr_matrix, or be convertible to csr_matrix')\n    if A.shape[0] != A.shape[1]:\n        raise TypeError('Argument A must be a square')\n    A = A.asfptype()\n    return A",
    "docstring": "Convert A to CSR, if A is not a CSR or BSR matrix already.\n\n    Parameters\n    ----------\n    A : array, matrix, sparse matrix\n        (n x n) matrix to convert to CSR\n\n    Returns\n    -------\n    A : csr_matrix, bsr_matrix\n        If A is csr_matrix or bsr_matrix, then do nothing and return A.\n        Else, convert A to CSR if possible and return.\n\n    Examples\n    --------\n    >>> from pyamg.gallery import poisson\n    >>> from pyamg.blackbox import make_csr\n    >>> A = poisson((40,40),format='csc')\n    >>> Acsr = make_csr(A)\n    Implicit conversion of A to CSR in pyamg.blackbox.make_csr"
  },
  {
    "code": "def get_conservation(block):\n    consensus = block['sequences'][0]['seq']\n    assert all(c.isupper() for c in consensus), \\\n            \"So-called consensus contains indels!\"\n    cleaned = [[c for c in s['seq'] if not c.islower()]\n               for s in block['sequences'][1:]]\n    height = float(len(cleaned))\n    for row in cleaned:\n        if len(row) != len(consensus):\n            raise ValueError(\"Aligned sequence length (%s) doesn't match \"\n                             \"consensus (%s)\"\n                             % (len(row), len(consensus)))\n    columns = zip(*cleaned)\n    return dict((idx + 1, columns[idx].count(cons_char) / height)\n                for idx, cons_char in enumerate(consensus))",
    "docstring": "Calculate conservation levels at each consensus position.\n\n    Return a dict of {position: float conservation}"
  },
  {
    "code": "def _parse_tokenize(self, rule):\n        for token in self._TOKENIZE_RE.split(rule):\n            if not token or token.isspace():\n                continue\n            clean = token.lstrip('(')\n            for i in range(len(token) - len(clean)):\n                yield '(', '('\n            if not clean:\n                continue\n            else:\n                token = clean\n            clean = token.rstrip(')')\n            trail = len(token) - len(clean)\n            lowered = clean.lower()\n            if lowered in ('and', 'or', 'not'):\n                yield lowered, clean\n            elif clean:\n                if len(token) >= 2 and ((token[0], token[-1]) in\n                                        [('\"', '\"'), (\"'\", \"'\")]):\n                    yield 'string', token[1:-1]\n                else:\n                    yield 'check', self._parse_check(clean)\n            for i in range(trail):\n                yield ')', ')'",
    "docstring": "Tokenizer for the policy language."
  },
  {
    "code": "def get_document(self, doc_url, force_download=False):\n        doc_url = str(doc_url)\n        if (self.use_cache and\n                not force_download and\n                self.cache.has_document(doc_url)):\n            doc_data = self.cache.get_document(doc_url)\n        else:\n            doc_data = self.api_request(doc_url, raw=True)\n            if self.update_cache:\n                self.cache.add_document(doc_url, doc_data)\n        return doc_data",
    "docstring": "Retrieve the data for the given document from the server\n\n        :type doc_url: String or Document\n        :param doc_url: the URL of the document, or a Document object\n        :type force_download: Boolean\n        :param force_download: True to download from the server\n            regardless of the cache's contents\n\n        :rtype: String\n        :returns: the document data\n\n        :raises: APIError if the API request is not successful"
  },
  {
    "code": "def density_matrix_of(self, qubits: List[ops.Qid] = None) -> np.ndarray:\n        r\n        return density_matrix_from_state_vector(\n            self.state_vector(),\n            [self.qubit_map[q] for q in qubits] if qubits is not None else None\n        )",
    "docstring": "r\"\"\"Returns the density matrix of the state.\n\n        Calculate the density matrix for the system on the list, qubits.\n        Any qubits not in the list that are present in self.state_vector() will\n        be traced out. If qubits is None the full density matrix for\n        self.state_vector() is returned, given self.state_vector() follows\n        standard Kronecker convention of numpy.kron.\n\n        For example:\n            self.state_vector() = np.array([1/np.sqrt(2), 1/np.sqrt(2)],\n                dtype=np.complex64)\n            qubits = None\n            gives us \\rho = \\begin{bmatrix}\n                                0.5 & 0.5\n                                0.5 & 0.5\n                            \\end{bmatrix}\n\n        Args:\n            qubits: list containing qubit IDs that you would like\n                to include in the density matrix (i.e.) qubits that WON'T\n                be traced out.\n\n        Returns:\n            A numpy array representing the density matrix.\n\n        Raises:\n            ValueError: if the size of the state represents more than 25 qubits.\n            IndexError: if the indices are out of range for the number of qubits\n                corresponding to the state."
  },
  {
    "code": "def connect_to(self, service_name, **kwargs):\n        service_class = self.get_connection(service_name)\n        return service_class.connect_to(**kwargs)",
    "docstring": "Shortcut method to make instantiating the ``Connection`` classes\n        easier.\n\n        Forwards ``**kwargs`` like region, keys, etc. on to the constructor.\n\n        :param service_name: A string that specifies the name of the desired\n            service. Ex. ``sqs``, ``sns``, ``dynamodb``, etc.\n        :type service_name: string\n\n        :rtype: <kotocore.connection.Connection> instance"
  },
  {
    "code": "async def start_async(self):\n        if self.run_task:\n            raise Exception(\"A PartitionManager cannot be started multiple times.\")\n        partition_count = await self.initialize_stores_async()\n        _logger.info(\"%r PartitionCount: %r\", self.host.guid, partition_count)\n        self.run_task = asyncio.ensure_future(self.run_async())",
    "docstring": "Intializes the partition checkpoint and lease store and then calls run async."
  },
  {
    "code": "def rtl_langs(self):\n        def is_rtl(lang):\n            base_rtl = ['ar', 'fa', 'he', 'ur']\n            return any([lang.startswith(base_code) for base_code in base_rtl])\n        return sorted(set([lang for lang in self.translated_locales if is_rtl(lang)]))",
    "docstring": "Returns the set of translated RTL language codes present in self.locales.\n        Ignores source locale."
  },
  {
    "code": "def parseBranches(self, descendants):\n        parsed, parent, cond = [], False, lambda b: (b.string or '').strip()\n        for branch in filter(cond, descendants):\n            if self.getHeadingLevel(branch) == self.depth:\n                parsed.append({'root':branch.string, 'source':branch})\n                parent = True\n            elif not parent:\n                parsed.append({'root':branch.string, 'source':branch})\n            else:\n                parsed[-1].setdefault('descendants', []).append(branch)\n        return [TOC(depth=self.depth+1, **kwargs) for kwargs in parsed]",
    "docstring": "Parse top level of markdown\n\n        :param list elements: list of source objects\n        :return: list of filtered TreeOfContents objects"
  },
  {
    "code": "def _handleCallAnswered(self, regexMatch, callId=None):\n        if regexMatch:\n            groups = regexMatch.groups()\n            if len(groups) > 1:\n                callId = int(groups[0])\n                self.activeCalls[callId].answered = True\n            else:\n                for call in dictValuesIter(self.activeCalls):\n                    if call.answered == False and type(call) == Call:\n                        call.answered = True\n                        return\n        else:\n            self.activeCalls[callId].answered = True",
    "docstring": "Handler for \"outgoing call answered\" event notification line"
  },
  {
    "code": "def as_native_str(encoding='utf-8'):\n    if PY3:\n        return lambda f: f\n    else:\n        def encoder(f):\n            @functools.wraps(f)\n            def wrapper(*args, **kwargs):\n                return f(*args, **kwargs).encode(encoding=encoding)\n            return wrapper\n        return encoder",
    "docstring": "A decorator to turn a function or method call that returns text, i.e.\n    unicode, into one that returns a native platform str.\n\n    Use it as a decorator like this::\n\n        from __future__ import unicode_literals\n\n        class MyClass(object):\n            @as_native_str(encoding='ascii')\n            def __repr__(self):\n                return next(self._iter).upper()"
  },
  {
    "code": "def _get_LDAP_connection():\n    server = ldap3.Server('ldap://' + get_optional_env('EPFL_LDAP_SERVER_FOR_SEARCH'))\n    connection = ldap3.Connection(server)\n    connection.open()\n    return connection, get_optional_env('EPFL_LDAP_BASE_DN_FOR_SEARCH')",
    "docstring": "Return a LDAP connection"
  },
  {
    "code": "def get_one(cls, enforcement_id):\n        qry = db.Enforcements.filter(enforcement_id == Enforcements.enforcement_id)\n        return qry",
    "docstring": "Return the properties of any enforcement action"
  },
  {
    "code": "def prime_gen() -> int:\n    D = {}\n    yield 2\n    for q in itertools.islice(itertools.count(3), 0, None, 2):\n        p = D.pop(q, None)\n        if p is None:\n            D[q * q] = 2 * q\n            yield q\n        else:\n            x = p + q\n            while x in D:\n                x += p\n            D[x] = p",
    "docstring": "A generator for prime numbers starting from 2."
  },
  {
    "code": "def table(columns, names, page_size=None, format_strings=None):\n    if page_size is None:\n        page = 'disable'\n    else:\n        page = 'enable'\n    div_id = uuid.uuid4()\n    column_descriptions = []\n    for column, name in zip(columns, names):\n        if column.dtype.kind == 'S':\n            ctype = 'string'\n        else:\n            ctype = 'number'\n        column_descriptions.append((ctype, name))\n    data = []\n    for item in zip(*columns):\n        data.append(list(item))\n    return google_table_template.render(div_id=div_id,\n                                page_enable=page,\n                                column_descriptions = column_descriptions,\n                                page_size=page_size,\n                                data=data,\n                                format_strings=format_strings,\n                               )",
    "docstring": "Return an html table of this data\n\n    Parameters\n    ----------\n    columns : list of numpy arrays\n    names : list of strings\n        The list of columns names\n    page_size : {int, None}, optional\n        The number of items to show on each page of the table\n    format_strings : {lists of strings, None}, optional\n        The ICU format string for this column, None for no formatting. All\n    columns must have a format string if provided.\n\n    Returns\n    -------\n    html_table : str\n        A str containing the html code to display a table of this data"
  },
  {
    "code": "def check_boto_reqs(boto_ver=None,\n                    boto3_ver=None,\n                    botocore_ver=None,\n                    check_boto=True,\n                    check_boto3=True):\n    if check_boto is True:\n        try:\n            import boto\n            has_boto = True\n        except ImportError:\n            has_boto = False\n        if boto_ver is None:\n            boto_ver = '2.0.0'\n        if not has_boto or version_cmp(boto.__version__, boto_ver) == -1:\n            return False, 'A minimum version of boto {0} is required.'.format(boto_ver)\n    if check_boto3 is True:\n        try:\n            import boto3\n            import botocore\n            has_boto3 = True\n        except ImportError:\n            has_boto3 = False\n        if boto3_ver is None:\n            boto3_ver = '1.2.6'\n        if botocore_ver is None:\n            botocore_ver = '1.3.23'\n        if not has_boto3 or version_cmp(boto3.__version__, boto3_ver) == -1:\n            return False, 'A minimum version of boto3 {0} is required.'.format(boto3_ver)\n        elif version_cmp(botocore.__version__, botocore_ver) == -1:\n            return False, 'A minimum version of botocore {0} is required'.format(botocore_ver)\n    return True",
    "docstring": "Checks for the version of various required boto libs in one central location. Most\n    boto states and modules rely on a single version of the boto, boto3, or botocore libs.\n    However, some require newer versions of any of these dependencies. This function allows\n    the module to pass in a version to override the default minimum required version.\n\n    This function is useful in centralizing checks for ``__virtual__()`` functions in the\n    various, and many, boto modules and states.\n\n    boto_ver\n        The minimum required version of the boto library. Defaults to ``2.0.0``.\n\n    boto3_ver\n        The minimum required version of the boto3 library. Defaults to ``1.2.6``.\n\n    botocore_ver\n        The minimum required version of the botocore library. Defaults to ``1.3.23``.\n\n    check_boto\n        Boolean defining whether or not to check for boto deps. This defaults to ``True`` as\n        most boto modules/states rely on boto, but some do not.\n\n    check_boto3\n        Boolean defining whether or not to check for boto3 (and therefore botocore) deps.\n        This defaults to ``True`` as most boto modules/states rely on boto3/botocore, but\n        some do not."
  },
  {
    "code": "def hashed(source_filename, prepared_options, thumbnail_extension, **kwargs):\n    parts = ':'.join([source_filename] + prepared_options)\n    short_sha = hashlib.sha1(parts.encode('utf-8')).digest()\n    short_hash = base64.urlsafe_b64encode(short_sha[:9]).decode('utf-8')\n    return '.'.join([short_hash, thumbnail_extension])",
    "docstring": "Generate a short hashed thumbnail filename.\n\n    Creates a 12 character url-safe base64 sha1 filename (plus the extension),\n    for example: ``6qW1buHgLaZ9.jpg``."
  },
  {
    "code": "def filter_oids(self, oids):\n        oids = set(oids)\n        return self[self['_oid'].map(lambda x: x in oids)]",
    "docstring": "Leaves only objects with specified oids.\n\n        :param oids: list of oids to include"
  },
  {
    "code": "def on_mouse_motion(self, x, y, dx, dy):\r\n        self.example.mouse_position_event(x, self.buffer_height - y)",
    "docstring": "Pyglet specific mouse motion callback.\r\n        Forwards and traslates the event to the example"
  },
  {
    "code": "def post(self, uri, body=None, logon_required=True,\n             wait_for_completion=True, operation_timeout=None):\n        try:\n            return self._urihandler.post(self._hmc, uri, body, logon_required,\n                                         wait_for_completion)\n        except HTTPError as exc:\n            raise zhmcclient.HTTPError(exc.response())\n        except ConnectionError as exc:\n            raise zhmcclient.ConnectionError(exc.message, None)",
    "docstring": "Perform the HTTP POST method against the resource identified by a URI,\n        using a provided request body, on the faked HMC.\n\n        HMC operations using HTTP POST are either synchronous or asynchronous.\n        Asynchronous operations return the URI of an asynchronously executing\n        job that can be queried for status and result.\n\n        Examples for synchronous operations:\n\n        * With no response body: \"Logon\", \"Update CPC Properties\"\n        * With a response body: \"Create Partition\"\n\n        Examples for asynchronous operations:\n\n        * With no ``job-results`` field in the completed job status response:\n          \"Start Partition\"\n        * With a ``job-results`` field in the completed job status response\n          (under certain conditions): \"Activate a Blade\", or \"Set CPC Power\n          Save\"\n\n        The `wait_for_completion` parameter of this method can be used to deal\n        with asynchronous HMC operations in a synchronous way.\n\n        Parameters:\n\n          uri (:term:`string`):\n            Relative URI path of the resource, e.g. \"/api/session\".\n            This URI is relative to the base URL of the session (see the\n            :attr:`~zhmcclient.Session.base_url` property).\n            Must not be `None`.\n\n          body (:term:`json object`):\n            JSON object to be used as the HTTP request body (payload).\n            `None` means the same as an empty dictionary, namely that no HTTP\n            body is included in the request.\n\n          logon_required (bool):\n            Boolean indicating whether the operation requires that the session\n            is logged on to the HMC. For example, the \"Logon\" operation does\n            not require that.\n\n            Because this is a faked HMC, this does not perform a real logon,\n            but it is still used to update the state in the faked HMC.\n\n          wait_for_completion (bool):\n            Boolean controlling whether this method should wait for completion\n            of the requested HMC operation, as follows:\n\n            * If `True`, this method will wait for completion of the requested\n              operation, regardless of whether the operation is synchronous or\n              asynchronous.\n\n              This will cause an additional entry in the time statistics to be\n              created for the asynchronous operation and waiting for its\n              completion. This entry will have a URI that is the targeted URI,\n              appended with \"+completion\".\n\n            * If `False`, this method will immediately return the result of the\n              HTTP POST method, regardless of whether the operation is\n              synchronous or asynchronous.\n\n          operation_timeout (:term:`number`):\n            Timeout in seconds, when waiting for completion of an asynchronous\n            operation. The special value 0 means that no timeout is set. `None`\n            means that the default async operation timeout of the session is\n            used.\n\n            For `wait_for_completion=True`, a\n            :exc:`~zhmcclient.OperationTimeout` is raised when the timeout\n            expires.\n\n            For `wait_for_completion=False`, this parameter has no effect.\n\n        Returns:\n\n          :term:`json object`:\n\n            If `wait_for_completion` is `True`, returns a JSON object\n            representing the response body of the synchronous operation, or the\n            response body of the completed job that performed the asynchronous\n            operation. If a synchronous operation has no response body, `None`\n            is returned.\n\n            If `wait_for_completion` is `False`, returns a JSON object\n            representing the response body of the synchronous or asynchronous\n            operation. In case of an asynchronous operation, the JSON object\n            will have a member named ``job-uri``, whose value can be used with\n            the :meth:`~zhmcclient.Session.query_job_status` method to\n            determine the status of the job and the result of the original\n            operation, once the job has completed.\n\n            See the section in the :term:`HMC API` book about the specific HMC\n            operation and about the 'Query Job Status' operation, for a\n            description of the members of the returned JSON objects.\n\n        Raises:\n\n          :exc:`~zhmcclient.HTTPError`\n          :exc:`~zhmcclient.ParseError` (not implemented)\n          :exc:`~zhmcclient.AuthError` (not implemented)\n          :exc:`~zhmcclient.ConnectionError`"
  },
  {
    "code": "def get(self, name):\n        pm = self._libeng.engGetVariable(self._ep, name)\n        out = mxarray_to_ndarray(self._libmx, pm)\n        self._libmx.mxDestroyArray(pm)\n        return out",
    "docstring": "Get variable `name` from MATLAB workspace.\n\n        Parameters\n        ----------\n        name : str\n            Name of the variable in MATLAB workspace.\n\n        Returns\n        -------\n        array_like\n            Value of the variable `name`."
  },
  {
    "code": "def create_release_settings_action(target, source, env):\n    with open(str(source[0]), \"r\") as fileobj:\n        settings = json.load(fileobj)\n    settings['release'] = True\n    settings['release_date'] = datetime.datetime.utcnow().isoformat()\n    settings['dependency_versions'] = {}\n    for dep in env['TILE'].dependencies:\n        tile = IOTile(os.path.join('build', 'deps', dep['unique_id']))\n        settings['dependency_versions'][dep['unique_id']] = str(tile.parsed_version)\n    with open(str(target[0]), \"w\") as fileobj:\n        json.dump(settings, fileobj, indent=4)",
    "docstring": "Copy module_settings.json and add release and build information"
  },
  {
    "code": "def make_soma(points, soma_check=None, soma_class=SOMA_CONTOUR):\n    if soma_check:\n        soma_check(points)\n    stype = _get_type(points, soma_class)\n    if stype is None:\n        raise SomaError('Invalid soma points')\n    return stype(points)",
    "docstring": "Make a soma object from a set of points\n\n    Infers the soma type (SomaSinglePoint, SomaSimpleContour)\n    from the points and the 'soma_class'\n\n    Parameters:\n        points: collection of points forming a soma.\n        soma_check: optional validation function applied to points. Should\n        raise a SomaError if points not valid.\n        soma_class(str): one of 'contour' or 'cylinder' to specify the type\n\n    Raises:\n        SomaError if no soma points found, points incompatible with soma, or\n        if soma_check(points) fails."
  },
  {
    "code": "def from_jsondict(cls, dict_, decode_string=base64.b64decode,\n                      **additional_args):\n        r\n        decode = lambda k, x: cls._decode_value(k, x, decode_string,\n                                                **additional_args)\n        kwargs = cls._restore_args(_mapdict_kv(decode, dict_))\n        try:\n            return cls(**dict(kwargs, **additional_args))\n        except TypeError:\n            print(\"CLS %s\" % cls)\n            print(\"ARG %s\" % dict_)\n            print(\"KWARG %s\" % kwargs)\n            raise",
    "docstring": "r\"\"\"Create an instance from a JSON style dict.\n\n        Instantiate this class with parameters specified by the dict.\n\n        This method takes the following arguments.\n\n        .. tabularcolumns:: |l|L|\n\n        =============== =====================================================\n        Argument        Descrpition\n        =============== =====================================================\n        dict\\_          A dictionary which describes the parameters.\n                        For example, {\"Param1\": 100, \"Param2\": 200}\n        decode_string   (Optional) specify how to decode strings.\n                        The default is base64.\n                        This argument is used only for attributes which don't\n                        have explicit type annotations in _TYPE class\n                        attribute.\n        additional_args (Optional) Additional kwargs for constructor.\n        =============== ====================================================="
  },
  {
    "code": "def process_args(mod_id, args, type_args):\n    res = list(args)\n    if len(args) > len(type_args):\n        raise ValueError(\n            'Too many arguments specified for module \"{}\" (Got {}, expected '\n            '{})'.format(mod_id, len(args), len(type_args))\n        )\n    for i in range(len(args), len(type_args)):\n        arg_info = type_args[i]\n        if \"default\" in arg_info:\n            args.append(arg_info[\"default\"])\n        else:\n            raise ValueError(\n                'Not enough module arguments supplied for module \"{}\" (Got '\n                '{}, expecting {})'.format(\n                    mod_id, len(args), len(type_args)\n                )\n            )\n    return args",
    "docstring": "Takes as input a list of arguments defined on a module and the information\n    about the required arguments defined on the corresponding module type.\n    Validates that the number of supplied arguments is valid and fills any\n    missing arguments with their default values from the module type"
  },
  {
    "code": "def get_one(self, cls=None, **kwargs):\n        case = cls() if cls else self._CasesClass()\n        for attr, value in kwargs.iteritems():\n            setattr(case, attr, value)\n        return case",
    "docstring": "Returns a one case."
  },
  {
    "code": "def open_font(self, name):\n        fid = self.display.allocate_resource_id()\n        ec = error.CatchError(error.BadName)\n        request.OpenFont(display = self.display,\n                         onerror = ec,\n                         fid = fid,\n                         name = name)\n        self.sync()\n        if ec.get_error():\n            self.display.free_resource_id(fid)\n            return None\n        else:\n            cls = self.display.get_resource_class('font', fontable.Font)\n            return cls(self.display, fid, owner = 1)",
    "docstring": "Open the font identifed by the pattern name and return its\n        font object. If name does not match any font, None is returned."
  },
  {
    "code": "def kube_cronjob_next_schedule_time(self, metric, scraper_config):\n        check_basename = scraper_config['namespace'] + '.cronjob.on_schedule_check'\n        curr_time = int(time.time())\n        for sample in metric.samples:\n            on_schedule = int(sample[self.SAMPLE_VALUE]) - curr_time\n            tags = [\n                self._format_tag(label_name, label_value, scraper_config)\n                for label_name, label_value in iteritems(sample[self.SAMPLE_LABELS])\n            ]\n            tags += scraper_config['custom_tags']\n            if on_schedule < 0:\n                message = \"The service check scheduled at {} is {} seconds late\".format(\n                    time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int(sample[self.SAMPLE_VALUE]))), on_schedule\n                )\n                self.service_check(check_basename, self.CRITICAL, tags=tags, message=message)\n            else:\n                self.service_check(check_basename, self.OK, tags=tags)",
    "docstring": "Time until the next schedule"
  },
  {
    "code": "def _decode_var(cls, string):\n        str_match = cls.quoted_string_regex.match(string)\n        if str_match:\n            return string.strip(\"'\" if str_match.groups()[0] else '\"')\n        elif string.isdigit() and cls.is_digit_regex.match(string) is not None:\n            return int(string)\n        elif string.lower() in (\"true\", \"false\"):\n            return string.lower() == \"true\"\n        elif string.lstrip(\"-\").isdigit():\n            try:\n                return int(string)\n            except ValueError:\n                return string\n        elif \".\" in string.lstrip(\"-\"):\n            try:\n                return float(string)\n            except ValueError:\n                return string\n        else:\n            return string",
    "docstring": "Decodes a given string into the appropriate type in Python.\n\n        :param str string: The string to decode\n        :return: The decoded value"
  },
  {
    "code": "def get_installed_version(dist_name, working_set=None):\n    req = pkg_resources.Requirement.parse(dist_name)\n    if working_set is None:\n        working_set = pkg_resources.WorkingSet()\n    dist = working_set.find(req)\n    return dist.version if dist else None",
    "docstring": "Get the installed version of dist_name avoiding pkg_resources cache"
  },
  {
    "code": "def is44(msg):\n    if allzeros(msg):\n        return False\n    d = hex2bin(data(msg))\n    if wrongstatus(d, 5, 6, 23):\n        return False\n    if wrongstatus(d, 35, 36, 46):\n        return False\n    if wrongstatus(d, 47, 48, 49):\n        return False\n    if wrongstatus(d, 50, 51, 56):\n        return False\n    if bin2int(d[0:4]) > 4:\n        return False\n    vw = wind44(msg)\n    if vw is not None and vw[0] > 250:\n        return False\n    temp, temp2 = temp44(msg)\n    if min(temp, temp2) > 60 or max(temp, temp2) < -80:\n        return False\n    return True",
    "docstring": "Check if a message is likely to be BDS code 4,4.\n\n    Meteorological routine air report\n\n    Args:\n        msg (String): 28 bytes hexadecimal message string\n\n    Returns:\n        bool: True or False"
  },
  {
    "code": "def withHeartbeater(cls, heartbeater):\n        instance = cls(heartbeater)\n        heartbeater.writeHeartbeat = instance.heartbeat\n        return instance",
    "docstring": "Connect a SockJSProtocolMachine to its heartbeater."
  },
  {
    "code": "def get(self, tags=[], trigger_ids=[]):\n        params = {}\n        if len(tags) > 0:\n            params['tags'] = ','.join(tags)\n        if len(trigger_ids) > 0:\n            params['triggerIds'] = ','.join(trigger_ids)\n        url = self._service_url('triggers', params=params)\n        triggers_dict = self._get(url)\n        return Trigger.list_to_object_list(triggers_dict)",
    "docstring": "Get triggers with optional filtering. Querying without parameters returns all the trigger definitions.\n\n        :param tags: Fetch triggers with matching tags only. Use * to match all values.\n        :param trigger_ids: List of triggerIds to fetch"
  },
  {
    "code": "def remove_instance(self, instance):\n        if instance.is_external:\n            logger.info(\"Request external process to stop for %s\", instance.name)\n            instance.stop_process()\n            logger.info(\"External process stopped.\")\n        instance.clear_queues(self.daemon.sync_manager)\n        self.instances.remove(instance)",
    "docstring": "Request to cleanly remove the given instance.\n        If instance is external also shutdown it cleanly\n\n        :param instance: instance to remove\n        :type instance: object\n        :return: None"
  },
  {
    "code": "def update_result_ctrl(self, event):\n        if not self:\n            return\n        printLen = 0\n        self.result_ctrl.SetValue('')\n        if hasattr(event, 'msg'):\n            self.result_ctrl.AppendText(event.msg)\n            printLen = len(event.msg)\n        if hasattr(event, 'err'):\n            errLen = len(event.err)\n            errStyle = wx.TextAttr(wx.RED)\n            self.result_ctrl.AppendText(event.err)\n            self.result_ctrl.SetStyle(printLen, printLen+errLen, errStyle)\n        if not hasattr(event, 'err') or event.err == '':\n            if self._ok_pressed:\n                self.Destroy()\n        self._ok_pressed = False",
    "docstring": "Update event result following execution by main window"
  },
  {
    "code": "def to_dataframe(self, fieldnames=(), verbose=True, index=None,\n                     coerce_float=False, datetime_index=False):\n        return read_frame(self, fieldnames=fieldnames, verbose=verbose,\n                          index_col=index, coerce_float=coerce_float,\n                          datetime_index=datetime_index)",
    "docstring": "Returns a DataFrame from the queryset\n\n        Paramaters\n        -----------\n\n        fieldnames:  The model field names(columns) to utilise in creating\n                     the DataFrame. You can span a relationships in the usual\n                     Django ORM way by using the foreign key field name\n                     separated by double underscores and refer to a field\n                     in a related model.\n\n\n        index:  specify the field to use  for the index. If the index\n                field is not in fieldnames it will be appended. This\n                is mandatory for timeseries.\n\n        verbose: If  this is ``True`` then populate the DataFrame with the\n                 human readable versions for foreign key fields else\n                 use the actual values set in the model\n\n        coerce_float:   Attempt to convert values to non-string, non-numeric\n                        objects (like decimal.Decimal) to floating point.\n\n        datetime_index: specify whether index should be converted to a\n                        DateTimeIndex."
  },
  {
    "code": "def _new_song(self):\n        s = self.song\n        if self.shuffle:\n            self.song = self.shuffles[random.randrange(len(self.shuffles))]\n        else:\n            self.song += 1\n            if self.song >= len(self.loop):\n                self.song = 0\n        self.dif_song = s != self.song\n        self.pos = 0",
    "docstring": "Used internally to get a metasong index."
  },
  {
    "code": "def get_optional(self, key: str,\n                     default: Optional[Any] = None) -> Optional[Any]:\n        return self.state.get(key, default)",
    "docstring": "Simply get a argument with given key.\n\n        Deprecated. Use `session.state.get()` instead."
  },
  {
    "code": "def border(self, L):\n        if self.shape == L_shape:\n            L.append(self.value)\n        else:\n            for x in self.sons:\n                x.border(L)",
    "docstring": "Append to L the border of the subtree."
  },
  {
    "code": "def stream_request_body(cls: Type[RequestHandler]) -> Type[RequestHandler]:\n    if not issubclass(cls, RequestHandler):\n        raise TypeError(\"expected subclass of RequestHandler, got %r\", cls)\n    cls._stream_request_body = True\n    return cls",
    "docstring": "Apply to `RequestHandler` subclasses to enable streaming body support.\n\n    This decorator implies the following changes:\n\n    * `.HTTPServerRequest.body` is undefined, and body arguments will not\n      be included in `RequestHandler.get_argument`.\n    * `RequestHandler.prepare` is called when the request headers have been\n      read instead of after the entire body has been read.\n    * The subclass must define a method ``data_received(self, data):``, which\n      will be called zero or more times as data is available.  Note that\n      if the request has an empty body, ``data_received`` may not be called.\n    * ``prepare`` and ``data_received`` may return Futures (such as via\n      ``@gen.coroutine``, in which case the next method will not be called\n      until those futures have completed.\n    * The regular HTTP method (``post``, ``put``, etc) will be called after\n      the entire body has been read.\n\n    See the `file receiver demo <https://github.com/tornadoweb/tornado/tree/master/demos/file_upload/>`_\n    for example usage."
  },
  {
    "code": "def is_module_reloadable(self, module, modname):\n        if self.has_cython:\n            return False\n        else:\n            if (self.is_module_in_pathlist(module) or\n                    self.is_module_in_namelist(modname)):\n                return False\n            else:\n                return True",
    "docstring": "Decide if a module is reloadable or not."
  },
  {
    "code": "def add_node_set_configuration(self, param_name, node_to_value):\n        for nid, val in future.utils.iteritems(node_to_value):\n            self.add_node_configuration(param_name, nid, val)",
    "docstring": "Set Nodes parameter\n\n        :param param_name: parameter identifier (as specified by the chosen model)\n        :param node_to_value: dictionary mapping each node a parameter value"
  },
  {
    "code": "def pre_process_data(filepath):\n    positive_path = os.path.join(filepath, 'pos')\n    negative_path = os.path.join(filepath, 'neg')\n    pos_label = 1\n    neg_label = 0\n    dataset = []\n    for filename in glob.glob(os.path.join(positive_path, '*.txt')):\n        with open(filename, 'r') as f:\n            dataset.append((pos_label, f.read()))\n    for filename in glob.glob(os.path.join(negative_path, '*.txt')):\n        with open(filename, 'r') as f:\n            dataset.append((neg_label, f.read()))\n    shuffle(dataset)\n    return dataset",
    "docstring": "This is dependent on your training data source but we will try to generalize it as best as possible."
  },
  {
    "code": "def models_get(self, resource_url):\n        obj_dir, obj_json, is_active, cache_id = self.get_object(resource_url)\n        model = ModelHandle(obj_json)\n        if not cache_id in self.cache:\n            self.cache_add(resource_url, cache_id)\n        return model",
    "docstring": "Get handle for model resource at given Url.\n\n        Parameters\n        ----------\n        resource_url : string\n            Url for subject resource at SCO-API\n\n        Returns\n        -------\n        models.ModelHandle\n            Handle for local copy of subject resource"
  },
  {
    "code": "def enter_config_value(self, key, default=\"\"):\n        value = input('Please enter a value for ' + key + ': ')\n        if value:\n            return value\n        else:\n            return default",
    "docstring": "Prompts user for a value"
  },
  {
    "code": "def _qstr(self, question):\n        \"we need to cope with a list, or a list of lists\"\n        parts = []\n        for entry in question:\n            if type(entry) is list:\n                parts.append(self._qstr(entry))\n            else:\n                parts.append('\"%s\"<%d>' % (self._count_data.get_candidate_title(entry), entry))\n        return ', '.join(parts)",
    "docstring": "we need to cope with a list, or a list of lists"
  },
  {
    "code": "def interpoled_resampling(W, x):\n    N = W.shape[0] \n    idx = np.argsort(x)\n    xs = x[idx] \n    ws = W[idx]\n    cs = np.cumsum(avg_n_nplusone(ws)) \n    u = random.rand(N)\n    xrs = np.empty(N)\n    where = np.searchsorted(cs, u)\n    for n in range(N): \n        m = where[n]\n        if m==0:\n            xrs[n] = xs[0]\n        elif m==N:\n            xrs[n] = xs[-1]\n        else:\n            xrs[n] = interpol(cs[m-1], cs[m], xs[m-1], xs[m], u[n])\n    return xrs",
    "docstring": "Resampling based on an interpolated CDF, as described in Malik and Pitt. \n\n    Parameters\n    ----------\n    W: (N,) array\n        weights \n    x: (N,) array \n        particles\n\n    Returns\n    -------\n    xrs: (N,) array\n        the resampled particles"
  },
  {
    "code": "def interaction_method(self, kind, x):\n        if self.info is None or self.code != ERR_INTERACTION_REQUIRED:\n            raise InteractionError(\n                'not an interaction-required error (code {})'.format(\n                    self.code)\n            )\n        entry = self.info.interaction_methods.get(kind)\n        if entry is None:\n            raise InteractionMethodNotFound(\n                'interaction method {} not found'.format(kind)\n            )\n        return x.from_dict(entry)",
    "docstring": "Checks whether the error is an InteractionRequired error\n        that implements the method with the given name, and JSON-unmarshals the\n        method-specific data into x by calling its from_dict method\n        with the deserialized JSON object.\n        @param kind The interaction method kind (string).\n        @param x A class with a class method from_dict that returns a new\n        instance of the interaction info for the given kind.\n        @return The result of x.from_dict."
  },
  {
    "code": "def convert_unit(value, unit, to):\n    if unit == to:\n        return value\n    units = ('W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns')\n    factors = (7, 24, 60, 60, 1000, 1000, 1000)\n    monthly_units = ('Y', 'Q', 'M')\n    monthly_factors = (4, 3)\n    try:\n        i, j = units.index(unit), units.index(to)\n    except ValueError:\n        try:\n            i, j = monthly_units.index(unit), monthly_units.index(to)\n            factors = monthly_factors\n        except ValueError:\n            raise ValueError(\n                'Cannot convert to or from variable length interval'\n            )\n    factor = functools.reduce(operator.mul, factors[min(i, j) : max(i, j)], 1)\n    assert factor > 1\n    if i < j:\n        return value * factor\n    assert i > j\n    return value // factor",
    "docstring": "Convert `value`, is assumed to be in units of `unit`, to units of `to`.\n\n    Parameters\n    ----------\n    value : Union[numbers.Real, ibis.expr.types.NumericValue]\n\n    Returns\n    -------\n    Union[numbers.Integral, ibis.expr.types.NumericValue]\n\n    Examples\n    --------\n    >>> one_second = 1000\n    >>> x = convert_unit(one_second, 'ms', 's')\n    >>> x\n    1\n    >>> one_second = 1\n    >>> x = convert_unit(one_second, 's', 'ms')\n    >>> x\n    1000\n    >>> x = convert_unit(one_second, 's', 's')\n    >>> x\n    1\n    >>> x = convert_unit(one_second, 's', 'M')\n    Traceback (most recent call last):\n        ...\n    ValueError: Cannot convert to or from variable length interval"
  },
  {
    "code": "def get_commands_aliases_and_macros_for_completion(self) -> List[str]:\n        visible_commands = set(self.get_visible_commands())\n        alias_names = set(self.get_alias_names())\n        macro_names = set(self.get_macro_names())\n        return list(visible_commands | alias_names | macro_names)",
    "docstring": "Return a list of visible commands, aliases, and macros for tab completion"
  },
  {
    "code": "def endless_permutations(N, random_state=None):\n    generator = check_random_state(random_state)\n    while True:\n        batch_inds = generator.permutation(N)\n        for b in batch_inds:\n            yield b",
    "docstring": "Generate an endless sequence of random integers from permutations of the\n    set [0, ..., N).\n\n    If we call this N times, we will sweep through the entire set without\n    replacement, on the (N+1)th call a new permutation will be created, etc.\n\n    Parameters\n    ----------\n    N: int\n        the length of the set\n    random_state: int or RandomState, optional\n        random seed\n\n    Yields\n    ------\n    int:\n        a random int from the set [0, ..., N)"
  },
  {
    "code": "def binormal_curve_single_list(obj, param_list, normalize):\n    ret_vector = []\n    for param in param_list:\n        temp = binormal_curve_single(obj, param, normalize)\n        ret_vector.append(temp)\n    return tuple(ret_vector)",
    "docstring": "Evaluates the curve binormal vectors at the given list of parameter values.\n\n    :param obj: input curve\n    :type obj: abstract.Curve\n    :param param_list: parameter list\n    :type param_list: list or tuple\n    :param normalize: if True, the returned vector is converted to a unit vector\n    :type normalize: bool\n    :return: a list containing \"point\" and \"vector\" pairs\n    :rtype: tuple"
  },
  {
    "code": "def get_rss_feed_content(url, offset=0, limit=None, exclude_items_in=None):\n    end = limit + offset if limit is not None else None\n    response = _get(url)\n    try:\n        feed_data = feedparser.parse(response.text)\n        if not feed_data.feed:\n            logger.warning('No valid feed data found at {}'.format(url))\n            return False\n        content = feed_data.entries\n    except Exception as parse_error:\n        logger.warning(\n            'Failed to parse feed from {}: {}'.format(url, str(parse_error))\n        )\n        return False\n    if exclude_items_in:\n        exclude_ids = [item['guid'] for item in exclude_items_in]\n        content = [item for item in content if item['guid'] not in exclude_ids]\n    content = content[offset:end]\n    for item in content:\n        updated_time = time.mktime(item['updated_parsed'])\n        item['updated_datetime'] = datetime.fromtimestamp(updated_time)\n    return content",
    "docstring": "Get the entries from an RSS feed"
  },
  {
    "code": "def align_add(tree, key, item, align_thres=2.0):\n    for near_key, near_list in get_near_items(tree, key):\n        if abs(key - near_key) < align_thres:\n            near_list.append(item)\n            return\n    tree[key] = [item]",
    "docstring": "Adding the item object to a binary tree with the given\n    key while allow for small key differences\n    close_enough_func that checks if two keys are\n    within threshold"
  },
  {
    "code": "def get_sql_insert(table: str,\n                   fieldlist: Sequence[str],\n                   delims: Tuple[str, str] = (\"\", \"\")) -> str:\n    return (\n        \"INSERT INTO \" + delimit(table, delims) +\n        \" (\" +\n        \",\".join([delimit(x, delims) for x in fieldlist]) +\n        \") VALUES (\" +\n        \",\".join([\"?\"] * len(fieldlist)) +\n        \")\"\n    )",
    "docstring": "Returns ?-marked SQL for an INSERT statement."
  },
  {
    "code": "def register_resource(mod, view, **kwargs):\n    resource_name = view.__name__.lower()[:-8]\n    endpoint = kwargs.get('endpoint', \"{}_api\".format(resource_name))\n    plural_resource_name = inflect.engine().plural(resource_name)\n    path = kwargs.get('url', plural_resource_name).strip('/')\n    url = '/{}'.format(path)\n    setattr(view, '_url', url)\n    view_func = view.as_view(endpoint)\n    mod.add_url_rule(url, view_func=view_func,\n                     methods=['GET', 'POST', 'OPTIONS'])\n    mod.add_url_rule('{}/<obj_id>'.format(url),\n                     view_func=view_func,\n                     methods=['GET', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'])",
    "docstring": "Register the resource on the resource name or a custom url"
  },
  {
    "code": "def setImgShape(self, shape):\r\n        self.img = type('Dummy', (object,), {})\r\n        self.img.shape = shape",
    "docstring": "image shape must be known for calculating camera matrix\r\n        if method==Manual and addPoints is used instead of addImg\r\n        this method must be called before .coeffs are obtained"
  },
  {
    "code": "def getch(self):\n        self.pos += 1\n        return self.string[self.pos - 1:self.pos]",
    "docstring": "Get a single character and advance the scan pointer.\n\n            >>> s = Scanner(\"abc\")\n            >>> s.getch()\n            'a'\n            >>> s.getch()\n            'b'\n            >>> s.getch()\n            'c'\n            >>> s.pos\n            3"
  },
  {
    "code": "def create_month_selectbox(name, selected_month=0, ln=None):\n    ln = default_ln(ln)\n    out = \"<select name=\\\"%s\\\">\\n\" % name\n    for i in range(0, 13):\n        out += \"<option value=\\\"%i\\\"\" % i\n        if (i == selected_month):\n            out += \" selected=\\\"selected\\\"\"\n        out += \">%s</option>\\n\" % get_i18n_month_name(i, ln)\n    out += \"</select>\\n\"\n    return out",
    "docstring": "Creates an HTML menu for month selection. Value of selected field is\n    numeric.\n\n    @param name: name of the control, your form will be sent with name=value...\n    @param selected_month: preselect a month. use 0 for the Label 'Month'\n    @param ln: language of the menu\n    @return: html as string"
  },
  {
    "code": "def build_truncated_gr_mfd(mfd):\n    return Node(\"truncGutenbergRichterMFD\",\n                {\"aValue\": mfd.a_val, \"bValue\": mfd.b_val,\n                 \"minMag\": mfd.min_mag, \"maxMag\": mfd.max_mag})",
    "docstring": "Parses the truncated Gutenberg Richter MFD as a Node\n\n    :param mfd:\n        MFD as instance of :class:\n        `openquake.hazardlib.mfd.truncated_gr.TruncatedGRMFD`\n    :returns:\n        Instance of :class:`openquake.baselib.node.Node`"
  },
  {
    "code": "def _reads_in_peaks(bam_file, peaks_file, sample):\n    if not peaks_file:\n        return {}\n    rip = number_of_mapped_reads(sample, bam_file, bed_file = peaks_file)\n    return {\"metrics\": {\"RiP\": rip}}",
    "docstring": "Calculate number of reads in peaks"
  },
  {
    "code": "def create_terms_index(es, index_name: str):\n    with open(mappings_terms_fn, \"r\") as f:\n        mappings_terms = yaml.load(f, Loader=yaml.SafeLoader)\n    try:\n        es.indices.create(index=index_name, body=mappings_terms)\n    except Exception as e:\n        log.error(f\"Could not create elasticsearch terms index: {e}\")",
    "docstring": "Create terms index"
  },
  {
    "code": "def _pycall_path_simple(\n    x1: int, y1: int, x2: int, y2: int, handle: Any\n) -> float:\n    return ffi.from_handle(handle)(x1, y1, x2, y2)",
    "docstring": "Does less and should run faster, just calls the handle function."
  },
  {
    "code": "def migrate_secret_key(old_key):\n    if 'SECRET_KEY' not in current_app.config or \\\n            current_app.config['SECRET_KEY'] is None:\n        raise click.ClickException(\n            'SECRET_KEY is not set in the configuration.')\n    for ep in iter_entry_points('invenio_base.secret_key'):\n        try:\n            ep.load()(old_key=old_key)\n        except Exception:\n            current_app.logger.error(\n                'Failed to initialize entry point: {0}'.format(ep))\n            raise\n    click.secho('Successfully changed secret key.', fg='green')",
    "docstring": "Call entry points exposed for the SECRET_KEY change."
  },
  {
    "code": "def process(self, model=None, context=None):\n        self.filter(model, context)\n        return self.validate(model, context)",
    "docstring": "Perform validation and filtering at the same time, return a\n        validation result object.\n\n        :param model: object or dict\n        :param context: object, dict or None\n        :return: shiftschema.result.Result"
  },
  {
    "code": "def newer(self, source, target):\n        if not os.path.exists(source):\n            raise DistlibException(\"file '%r' does not exist\" %\n                                   os.path.abspath(source))\n        if not os.path.exists(target):\n            return True\n        return os.stat(source).st_mtime > os.stat(target).st_mtime",
    "docstring": "Tell if the target is newer than the source.\n\n        Returns true if 'source' exists and is more recently modified than\n        'target', or if 'source' exists and 'target' doesn't.\n\n        Returns false if both exist and 'target' is the same age or younger\n        than 'source'. Raise PackagingFileError if 'source' does not exist.\n\n        Note that this test is not very accurate: files created in the same\n        second will have the same \"age\"."
  },
  {
    "code": "def add_menu(self, name, link=None):\n        if self.menu_began:\n            if self.menu_separator_tag:\n                self.write(self.menu_separator_tag)\n        else:\n            self.write('<ul class=\"horizontal\">')\n            self.menu_began = True\n        self.write('<li>')\n        if link:\n            self.write('<a href=\"{}\">', self._rel(link))\n        self.write(name)\n        if link:\n            self.write('</a>')\n        self.write('</li>')",
    "docstring": "Adds a menu entry, will create it if it doesn't exist yet"
  },
  {
    "code": "def end_stream(self, stream_id):\n        with (yield from self._get_stream(stream_id).wlock):\n            yield from self._resumed.wait()\n            self._conn.end_stream(stream_id)\n            self._flush()",
    "docstring": "Close the given stream locally.\n\n        This may block until the underlying transport becomes writable, or\n        other coroutines release the wlock on this stream.\n\n        :param stream_id: Which stream to close."
  },
  {
    "code": "def remove(self, session_id):\n        session = self._items.get(session_id, None)\n        if session is not None:\n            session.promoted = -1\n            session.on_delete(True)\n            del self._items[session_id]\n            return True\n        return False",
    "docstring": "Remove session object from the container\n\n        `session_id`\n            Session identifier"
  },
  {
    "code": "def table(schema, name=None):\n    if not isinstance(schema, Schema):\n        if isinstance(schema, dict):\n            schema = Schema.from_dict(schema)\n        else:\n            schema = Schema.from_tuples(schema)\n    node = ops.UnboundTable(schema, name=name)\n    return node.to_expr()",
    "docstring": "Create an unbound Ibis table for creating expressions. Cannot be executed\n    without being bound to some physical table.\n\n    Useful for testing\n\n    Parameters\n    ----------\n    schema : ibis Schema\n    name : string, default None\n      Name for table\n\n    Returns\n    -------\n    table : TableExpr"
  },
  {
    "code": "def entity_types(self):\n        r = fapi.get_entity_types(self.namespace, self.name, self.api_url)\n        fapi._check_response_code(r, 200)\n        return r.json().keys()",
    "docstring": "List entity types in workspace."
  },
  {
    "code": "def _sysv_enable(name):\n    if not _service_is_chkconfig(name) and not _chkconfig_add(name):\n        return False\n    cmd = '/sbin/chkconfig {0} on'.format(name)\n    return not __salt__['cmd.retcode'](cmd, python_shell=False)",
    "docstring": "Enable the named sysv service to start at boot.  The service will be enabled\n    using chkconfig with default run-levels if the service is chkconfig\n    compatible.  If chkconfig is not available, then this will fail."
  },
  {
    "code": "def _init_qualifier_decl(qualifier_decl, qual_repo):\n        assert qualifier_decl.name not in qual_repo\n        if qualifier_decl.tosubclass is None:\n            qualifier_decl.tosubclass = True\n        if qualifier_decl.overridable is None:\n            qualifier_decl.overridable = True\n        if qualifier_decl.translatable is None:\n            qualifier_decl.translatable = False",
    "docstring": "Initialize the flavors of a qualifier declaration if they are not\n        already set."
  },
  {
    "code": "def use_gradient(grad_f):\n  grad_f_name = register_to_random_name(grad_f)\n  def function_wrapper(f):\n    def inner(*inputs):\n      state = {\"out_value\": None}\n      out = f(*inputs)\n      def store_out(out_value):\n        state[\"out_value\"] = out_value\n      store_name = \"store_\" + f.__name__\n      store = tf.py_func(store_out, [out], (), stateful=True, name=store_name)\n      def mock_f(*inputs):\n        return state[\"out_value\"]\n      with tf.control_dependencies([store]):\n        with gradient_override_map({\"PyFunc\": grad_f_name}):\n          mock_name = \"mock_\" + f.__name__\n          mock_out = tf.py_func(mock_f, inputs, out.dtype, stateful=True,\n                                name=mock_name)\n          mock_out.set_shape(out.get_shape())\n      return mock_out\n    return inner\n  return function_wrapper",
    "docstring": "Decorator for easily setting custom gradients for TensorFlow functions.\n\n  * DO NOT use this function if you need to serialize your graph.\n  * This function will cause the decorated function to run slower.\n\n  Example:\n\n    def _foo_grad(op, grad): ...\n\n    @use_gradient(_foo_grad)\n    def foo(x1, x2, x3): ...\n\n  Args:\n    grad_f: function to use as gradient.\n\n  Returns:\n    A decorator to apply to the function you wish to override the gradient of."
  },
  {
    "code": "def cancel(self):\n        conn = self._assert_open()\n        conn._try_activate_cursor(self)\n        self._session.cancel_if_pending()",
    "docstring": "Cancel current statement"
  },
  {
    "code": "def get_explanation_dict(self, entry):\n        centry = self.process_entry(entry)\n        if centry is None:\n            uncorrected_energy = entry.uncorrected_energy\n            corrected_energy = None\n        else:\n            uncorrected_energy = centry.uncorrected_energy\n            corrected_energy = centry.energy\n        d = {\"compatibility\": self.__class__.__name__,\n             \"uncorrected_energy\": uncorrected_energy,\n             \"corrected_energy\": corrected_energy}\n        corrections = []\n        corr_dict = self.get_corrections_dict(entry)\n        for c in self.corrections:\n            cd = {\"name\": str(c),\n                  \"description\": c.__doc__.split(\"Args\")[0].strip(),\n                  \"value\": corr_dict.get(str(c), 0)}\n            corrections.append(cd)\n        d[\"corrections\"] = corrections\n        return d",
    "docstring": "Provides an explanation dict of the corrections that are being applied\n        for a given compatibility scheme. Inspired by the \"explain\" methods\n        in many database methodologies.\n\n        Args:\n            entry: A ComputedEntry.\n\n        Returns:\n            (dict) of the form\n            {\"Compatibility\": \"string\",\n            \"Uncorrected_energy\": float,\n            \"Corrected_energy\": float,\n            \"Corrections\": [{\"Name of Correction\": {\n            \"Value\": float, \"Explanation\": \"string\"}]}"
  },
  {
    "code": "def cp(source, bucket, checksum, key_prefix):\n    from .models import Bucket\n    from .helpers import populate_from_path\n    for object_version in populate_from_path(\n            Bucket.get(bucket), source, checksum=checksum,\n            key_prefix=key_prefix):\n        click.secho(str(object_version))\n    db.session.commit()",
    "docstring": "Create new bucket from all files in directory."
  },
  {
    "code": "def keypoint_vflip(kp, rows, cols):\n    x, y, angle, scale = kp\n    c = math.cos(angle)\n    s = math.sin(angle)\n    angle = math.atan2(-s, c)\n    return [x, (rows - 1) - y, angle, scale]",
    "docstring": "Flip a keypoint vertically around the x-axis."
  },
  {
    "code": "async def file(location, mime_type=None, headers=None, _range=None):\n    filename = path.split(location)[-1]\n    async with open_async(location, mode='rb') as _file:\n        if _range:\n            await _file.seek(_range.start)\n            out_stream = await _file.read(_range.size)\n            headers['Content-Range'] = 'bytes %s-%s/%s' % (\n                _range.start, _range.end, _range.total)\n        else:\n            out_stream = await _file.read()\n    mime_type = mime_type or guess_type(filename)[0] or 'text/plain'\n    return HTTPResponse(status=200,\n                        headers=headers,\n                        content_type=mime_type,\n                        body_bytes=out_stream)",
    "docstring": "Return a response object with file data.\n\n    :param location: Location of file on system.\n    :param mime_type: Specific mime_type.\n    :param headers: Custom Headers.\n    :param _range:"
  },
  {
    "code": "def make(directory):\n    if os.path.exists(directory):\n        if os.path.isdir(directory):\n            click.echo('Directory already exists')\n        else:\n            click.echo('Path exists and is not a directory')\n        sys.exit()\n    os.makedirs(directory)\n    os.mkdir(os.path.join(directory, 'jsons'))\n    copy_default_config(os.path.join(directory, 'config.yaml'))",
    "docstring": "Makes a RAS Machine directory"
  },
  {
    "code": "def deriv2(self, p):\n        p = self._clean(p)\n        fl = np.log(1 - p)\n        d2 = -1 / ((1 - p)**2 * fl)\n        d2 *= 1 + 1 / fl\n        return d2",
    "docstring": "Second derivative of the C-Log-Log ink function\n\n        Parameters\n        ----------\n        p : array-like\n            Mean parameters\n\n        Returns\n        -------\n        g''(p) : array\n            The second derivative of the CLogLog link function"
  },
  {
    "code": "def update_model_cache(table_name):\n    model_cache_info = ModelCacheInfo(table_name, uuid.uuid4().hex)\n    model_cache_backend.share_model_cache_info(model_cache_info)",
    "docstring": "Updates model cache by generating a new key for the model"
  },
  {
    "code": "def from_event(cls, event):\n        source = Chatter(event.source)\n        return cls(source, event.target, event.arguments[0], event.tags)",
    "docstring": "Create a message from an event\n\n        :param event: the event that was received of type ``pubmsg`` or ``privmsg``\n        :type event: :class:`Event3`\n        :returns: a message that resembles the event\n        :rtype: :class:`Message3`\n        :raises: None"
  },
  {
    "code": "def handle_annotation_pattern(self, line: str, position: int, tokens: ParseResults) -> ParseResults:\n        annotation = tokens['name']\n        self.raise_for_redefined_annotation(line, position, annotation)\n        self.annotation_to_pattern[annotation] = re.compile(tokens['value'])\n        return tokens",
    "docstring": "Handle statements like ``DEFINE ANNOTATION X AS PATTERN \"Y\"``.\n\n        :raises: RedefinedAnnotationError"
  },
  {
    "code": "def read_hdf5_dict(h5f, names=None, path=None, on_missing='error', **kwargs):\n    if path:\n        h5f = h5f[path]\n    if names is None:\n        names = kwargs.pop('flags', None)\n    if names is None:\n        try:\n            names = find_flag_groups(h5f, strict=True)\n        except KeyError:\n            names = None\n        if not names:\n            raise ValueError(\"Failed to automatically parse available flag \"\n                             \"names from HDF5, please give a list of names \"\n                             \"to read via the ``names=`` keyword\")\n    out = DataQualityDict()\n    for name in names:\n        try:\n            out[name] = read_hdf5_flag(h5f, name, **kwargs)\n        except KeyError as exc:\n            if on_missing == 'ignore':\n                pass\n            elif on_missing == 'warn':\n                warnings.warn(str(exc))\n            else:\n                raise ValueError('no H5Group found for flag '\n                                 '{0!r}'.format(name))\n    return out",
    "docstring": "Read a `DataQualityDict` from an HDF5 file"
  },
  {
    "code": "def leb128_encode(value):\n        if value == 0:\n            return b'\\x00'\n        result = []\n        while value != 0:\n            byte = value & 0x7f\n            value >>= 7\n            if value != 0:\n                byte |= 0x80\n            result.append(byte)\n        return bytes(result)",
    "docstring": "Encodes an integer using LEB128.\n\n        :param int value: The value to encode.\n        :return: The LEB128-encoded integer.\n        :rtype: bytes"
  },
  {
    "code": "def find_python():\n    python = (\n        _state.get(\"pythonExecutable\") or\n        next((\n            exe for exe in\n            os.getenv(\"PYBLISH_QML_PYTHON_EXECUTABLE\", \"\").split(os.pathsep)\n            if os.path.isfile(exe)), None\n        ) or\n        which(\"python\") or\n        which(\"python3\")\n    )\n    if not python or not os.path.isfile(python):\n        raise ValueError(\"Could not locate Python executable.\")\n    return python",
    "docstring": "Search for Python automatically"
  },
  {
    "code": "def free(self, ptr):\n        raise NotImplementedError(\"%s not implemented for %s\" % (self.free.__func__.__name__,\n                                                                 self.__class__.__name__))",
    "docstring": "A somewhat faithful implementation of libc `free`.\n\n        :param ptr: the location in memory to be freed"
  },
  {
    "code": "def todate(self):\n        arr = get_gregorian_date_from_julian_day(self.tojulianday())\n        return datetime.date(int(arr[0]), int(arr[1]), int(arr[2]))",
    "docstring": "Calculates the corresponding day in the gregorian calendar. this is the main use case of this library.\n\n        :return: Corresponding date in gregorian calendar.\n        :rtype: :py:class:`datetime.date`"
  },
  {
    "code": "def _get_all_forums(self):\n        if not hasattr(self, '_all_forums'):\n            self._all_forums = list(Forum.objects.all())\n        return self._all_forums",
    "docstring": "Returns all forums."
  },
  {
    "code": "def filter_service_by_regex_name(regex):\n    host_re = re.compile(regex)\n    def inner_filter(items):\n        service = items[\"service\"]\n        if service is None:\n            return False\n        return host_re.match(service.service_description) is not None\n    return inner_filter",
    "docstring": "Filter for service\n    Filter on regex\n\n    :param regex: regex to filter\n    :type regex: str\n    :return: Filter\n    :rtype: bool"
  },
  {
    "code": "def pick_free_port(hostname=REDIRECT_HOST, port=0):\n    import socket\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    try:\n        s.bind((hostname, port))\n    except OSError as e:\n        log.warning(\"Could not bind to %s:%s %s\", hostname, port, e)\n        if port == 0:\n            print('Unable to find an open port for authentication.')\n            raise AuthenticationException(e)\n        else:\n            return pick_free_port(hostname, 0)\n    addr, port = s.getsockname()\n    s.close()\n    return port",
    "docstring": "Try to bind a port. Default=0 selects a free port."
  },
  {
    "code": "def get_feature_variable_integer(self, feature_key, variable_key, user_id, attributes=None):\n    variable_type = entities.Variable.Type.INTEGER\n    return self._get_feature_variable_for_type(feature_key, variable_key, variable_type, user_id, attributes)",
    "docstring": "Returns value for a certain integer variable attached to a feature flag.\n\n    Args:\n      feature_key: Key of the feature whose variable's value is being accessed.\n      variable_key: Key of the variable whose value is to be accessed.\n      user_id: ID for user.\n      attributes: Dict representing user attributes.\n\n    Returns:\n      Integer value of the variable. None if:\n      - Feature key is invalid.\n      - Variable key is invalid.\n      - Mismatch with type of variable."
  },
  {
    "code": "def get_default_envlist(version):\n    if version in ['pypy', 'pypy3']:\n        return version\n    match = re.match(r'^(\\d)\\.(\\d)(?:\\.\\d+)?$', version or '')\n    if match:\n        major, minor = match.groups()\n        return 'py{major}{minor}'.format(major=major, minor=minor)\n    return guess_python_env()",
    "docstring": "Parse a default tox env based on the version.\n\n    The version comes from the ``TRAVIS_PYTHON_VERSION`` environment\n    variable. If that isn't set or is invalid, then use\n    sys.version_info to come up with a reasonable default."
  },
  {
    "code": "def _parse_invite(client, command, actor, args):\n    target, _, channel = args.rpartition(\" \")\n    client.dispatch_event(\"INVITE\", actor, target, channel.lower())",
    "docstring": "Parse an INVITE and dispatch an event."
  },
  {
    "code": "def get_empty_config():\n    empty_color_config = get_empty_color_config()\n    result = Config(\n        examples_dir=None,\n        custom_dir=None,\n        color_config=empty_color_config,\n        use_color=None,\n        pager_cmd=None,\n        editor_cmd=None,\n        squeeze=None,\n        subs=None\n    )\n    return result",
    "docstring": "Return an empty Config object with no options set."
  },
  {
    "code": "def length(self):\n        return math.sqrt((self.X * self.X) + (self.Y * self.Y))",
    "docstring": "Gets the length of this Vector"
  },
  {
    "code": "def put(self, key, value):\n    super(DirectoryTreeDatastore, self).put(key, value)\n    str_key = str(key)\n    if str_key == '/':\n      return\n    dir_key = key.parent.instance('directory')\n    directory = self.directory(dir_key)\n    if str_key not in directory:\n      directory.append(str_key)\n      super(DirectoryTreeDatastore, self).put(dir_key, directory)",
    "docstring": "Stores the object `value` named by `key`self.\n       DirectoryTreeDatastore stores a directory entry."
  },
  {
    "code": "def write(self, data):\n        if self.is_closing():\n            return\n        self._write_buffer += data\n        if len(self._write_buffer) >= self._output_buffer_limit_high:\n            self._protocol.pause_writing()\n        if self._write_buffer:\n            self._can_write.set()",
    "docstring": "Send `data` over the IBB. If `data` is larger than the block size\n        is is chunked and sent in chunks.\n\n        Chunks from one call of :meth:`write` will always be sent in\n        series."
  },
  {
    "code": "def _basic_return(self, frame_in):\n        reply_text = try_utf8_decode(frame_in.reply_text)\n        message = (\n            \"Message not delivered: %s (%s) to queue '%s' from exchange '%s'\" %\n            (\n                reply_text,\n                frame_in.reply_code,\n                frame_in.routing_key,\n                frame_in.exchange\n            )\n        )\n        exception = AMQPMessageError(message,\n                                     reply_code=frame_in.reply_code)\n        self.exceptions.append(exception)",
    "docstring": "Handle a Basic Return Frame and treat it as an error.\n\n        :param specification.Basic.Return frame_in: Amqp frame.\n\n        :return:"
  },
  {
    "code": "def raw(self):\n        if self._raw:\n            return text_type(self._raw).strip(\"\\r\\n\")\n        else:\n            return text_type(base64decode(self._b64encoded)).strip(\"\\r\\n\")",
    "docstring": "Return raw key.\n\n        returns:\n            str: raw key"
  },
  {
    "code": "def getMessage(self):\n        msg = str(self.msg)\n        if self.args:\n            msg = msg % self.args\n        if platform.system().lower() == 'windows' or self.levelno < 10:\n            return msg\n        elif self.levelno >= 50:\n            return utils.return_colorized(msg, 'critical')\n        elif self.levelno >= 40:\n            return utils.return_colorized(msg, 'error')\n        elif self.levelno >= 30:\n            return utils.return_colorized(msg, 'warn')\n        elif self.levelno >= 20:\n            return utils.return_colorized(msg, 'info')\n        else:\n            return utils.return_colorized(msg, 'debug')",
    "docstring": "Returns a colorized log message based on the log level.\n\n        If the platform is windows the original message will be returned\n        without colorization windows escape codes are crazy.\n\n        :returns: ``str``"
  },
  {
    "code": "def find_breaking_changes(\n    old_schema: GraphQLSchema, new_schema: GraphQLSchema\n) -> List[BreakingChange]:\n    return (\n        find_removed_types(old_schema, new_schema)\n        + find_types_that_changed_kind(old_schema, new_schema)\n        + find_fields_that_changed_type_on_object_or_interface_types(\n            old_schema, new_schema\n        )\n        + find_fields_that_changed_type_on_input_object_types(\n            old_schema, new_schema\n        ).breaking_changes\n        + find_types_removed_from_unions(old_schema, new_schema)\n        + find_values_removed_from_enums(old_schema, new_schema)\n        + find_arg_changes(old_schema, new_schema).breaking_changes\n        + find_interfaces_removed_from_object_types(old_schema, new_schema)\n        + find_removed_directives(old_schema, new_schema)\n        + find_removed_directive_args(old_schema, new_schema)\n        + find_added_non_null_directive_args(old_schema, new_schema)\n        + find_removed_directive_locations(old_schema, new_schema)\n    )",
    "docstring": "Find breaking changes.\n\n    Given two schemas, returns a list containing descriptions of all the types of\n    breaking changes covered by the other functions down below."
  },
  {
    "code": "def cleanup(self):\n        \"Remove the directory containin the clone and virtual environment.\"\n        log.info('Removing temp dir %s', self._tempdir.name)\n        self._tempdir.cleanup()",
    "docstring": "Remove the directory containin the clone and virtual environment."
  },
  {
    "code": "def mat_to_numpy_arr(self):\n  import numpy as np\n  self.dat['mat'] = np.asarray(self.dat['mat'])",
    "docstring": "convert list to numpy array - numpy arrays can not be saved as json"
  },
  {
    "code": "def register_for_duty(self, context):\n        cctxt = self.client.prepare()\n        return cctxt.call(context, 'register_for_duty', host=self.host)",
    "docstring": "Report that a config agent is ready for duty."
  },
  {
    "code": "def generate_name(self, name=None):\n        if name == None:\n            name = self.RobotNamer.generate()\n        self.name = name.replace('-','_')",
    "docstring": "generate a Robot Name for the instance to use, if the user doesn't\n           supply one."
  },
  {
    "code": "def argmax(attrs, inputs, proto_obj):\n    axis = attrs.get('axis', 0)\n    keepdims = attrs.get('keepdims', 1)\n    argmax_op = symbol.argmax(inputs[0], axis=axis, keepdims=keepdims)\n    cast_attrs = {'dtype': 'int64'}\n    return 'cast', cast_attrs, argmax_op",
    "docstring": "Returns indices of the maximum values along an axis"
  },
  {
    "code": "def start(self, driver=None):\n        if driver is not None:\n            assert driver in [\n                    'alsa',\n                    'oss',\n                    'jack',\n                    'portaudio',\n                    'sndmgr',\n                    'coreaudio',\n                    'Direct Sound',\n                    'dsound',\n                    'pulseaudio'\n                    ]\n            fluid_settings_setstr(self.settings, 'audio.driver', driver)\n        self.audio_driver = new_fluid_audio_driver(self.settings, self.synth)",
    "docstring": "Start audio output driver in separate background thread.\n\n        Call this function any time after creating the Synth object.\n        If you don't call this function, use get_samples() to generate\n        samples.\n\n        Optional keyword argument:\n          driver: which audio driver to use for output\n                  Possible choices:\n                    'alsa', 'oss', 'jack', 'portaudio'\n                    'sndmgr', 'coreaudio', 'Direct Sound',\n                    'dsound', 'pulseaudio'\n\n        Not all drivers will be available for every platform, it depends on\n        which drivers were compiled into FluidSynth for your platform."
  },
  {
    "code": "def email_generator(names=None, domains=None, unique=False):\n    if names is None:\n        names = [name.encode('ascii', 'ignore').lower().replace(b' ', b'')\n                 for name in ENGLISH_MONARCHS]\n    if domains is None:\n        domains = DOMAINS\n    if unique:\n        uniquifyer = lambda: str(next(_unique_counter))\n    else:\n        uniquifyer = lambda: ''\n    while True:\n        yield '{0}{1}@{2}'.format(\n            random.choice(names), uniquifyer(), random.choice(domains))",
    "docstring": "Creates a generator for generating email addresses.\n\n    :arg names: list of names to use; defaults to ENGLISH_MONARCHS\n        lowercased, ascii-fied, and stripped of whitespace\n\n    :arg domains: list of domains to use; defaults to DOMAINS\n\n    :arg unique: True if you want the username part of the email\n        addresses to be unique\n\n    :returns: generator\n\n    Example::\n\n        from eadred.helpers import email_generator\n\n        gen = email_generator()\n        for i in range(50):\n            mymodel = SomeModel(email=gen.next())\n            mymodel.save()\n\n\n    Example 2:\n\n    >>> gen = email_generator()\n    >>> gen.next()\n    'eadwig@example.net'\n    >>> gen.next()\n    'henrybeauclerc@mail1.example.org'\n    >>> gen.next()\n    'williamrufus@example.com'"
  },
  {
    "code": "def get_all(rc_file='~/.odoorpcrc'):\n    conf = ConfigParser()\n    conf.read([os.path.expanduser(rc_file)])\n    sessions = {}\n    for name in conf.sections():\n        sessions[name] = {\n            'type': conf.get(name, 'type'),\n            'host': conf.get(name, 'host'),\n            'protocol': conf.get(name, 'protocol'),\n            'port': conf.getint(name, 'port'),\n            'timeout': conf.getfloat(name, 'timeout'),\n            'user': conf.get(name, 'user'),\n            'passwd': conf.get(name, 'passwd'),\n            'database': conf.get(name, 'database'),\n        }\n    return sessions",
    "docstring": "Return all session configurations from the `rc_file` file.\n\n    >>> import odoorpc\n    >>> from pprint import pprint as pp\n    >>> pp(odoorpc.session.get_all())     # doctest: +SKIP\n    {'foo': {'database': 'db_name',\n             'host': 'localhost',\n             'passwd': 'password',\n             'port': 8069,\n             'protocol': 'jsonrpc',\n             'timeout': 120,\n             'type': 'ODOO',\n             'user': 'admin'},\n     ...}\n\n    .. doctest::\n        :hide:\n\n        >>> import odoorpc\n        >>> session = '%s_session' % DB\n        >>> odoo.save(session)\n        >>> data = odoorpc.session.get_all()\n        >>> data[session]['host'] == HOST\n        True\n        >>> data[session]['protocol'] == PROTOCOL\n        True\n        >>> data[session]['port'] == int(PORT)\n        True\n        >>> data[session]['database'] == DB\n        True\n        >>> data[session]['user'] == USER\n        True\n        >>> data[session]['passwd'] == PWD\n        True\n        >>> data[session]['type'] == 'ODOO'\n        True"
  },
  {
    "code": "def list_all_python_programs(self):\n        self.tot_lines = 0\n        self.tot_bytes = 0\n        self.tot_files = 0\n        self.tot_loc = 0\n        self.lstPrograms = []\n        fl = mod_fl.FileList([self.fldr], ['*.py'], [\"__pycache__\", \"/venv/\", \"/venv2/\", \".git\"])\n        for fip in fl.get_list():\n            if '__init__.py' not in fip:\n                self.add(fip, 'TODO - add comment')\n                f = mod_file.TextFile(fip)\n                self.tot_lines += f.count_lines_in_file()\n                self.tot_loc += f.count_lines_of_code()\n                self.tot_bytes += f.size\n                self.tot_files += 1\n        print('All Python Program Statistics')\n        print('Files = ', self.tot_files, ' Bytes = ', self.tot_bytes, ' Lines = ', self.tot_lines, ' Lines of Code = ', self.tot_loc)",
    "docstring": "collects a filelist of all .py programs"
  },
  {
    "code": "def Search(self,key):\n\t\tresults = []\n\t\tfor disk in self.disks:\n\t\t\tif disk.id.lower().find(key.lower()) != -1:  results.append(disk)\n\t\t\telif key.lower() in disk.partition_paths:  results.append(disk)\n\t\treturn(results)",
    "docstring": "Search disk list by partial mount point or ID"
  },
  {
    "code": "def generate(env):\n    env['MIDL']          = 'MIDL.EXE'\n    env['MIDLFLAGS']     = SCons.Util.CLVar('/nologo')\n    env['MIDLCOM']       = '$MIDL $MIDLFLAGS /tlb ${TARGETS[0]} /h ${TARGETS[1]} /iid ${TARGETS[2]} /proxy ${TARGETS[3]} /dlldata ${TARGETS[4]} $SOURCE 2> NUL'\n    env['BUILDERS']['TypeLibrary'] = midl_builder",
    "docstring": "Add Builders and construction variables for midl to an Environment."
  },
  {
    "code": "def Binary(x):\n    if isinstance(x, text_type) and not (JYTHON or IRONPYTHON):\n        return x.encode()\n    return bytes(x)",
    "docstring": "Return x as a binary type."
  },
  {
    "code": "def changelog_cli(ctx):\n    if ctx.invoked_subcommand:\n        return\n    from peltak.core import shell\n    from . import logic\n    shell.cprint(logic.changelog())",
    "docstring": "Generate changelog from commit messages."
  },
  {
    "code": "def port(self, port):\n        if not isinstance(port, int):\n            raise WebDriverException(\"Port needs to be an integer\")\n        try:\n            port = int(port)\n            if port < 1 or port > 65535:\n                raise WebDriverException(\"Port number must be in the range 1..65535\")\n        except (ValueError, TypeError):\n            raise WebDriverException(\"Port needs to be an integer\")\n        self._port = port\n        self.set_preference(\"webdriver_firefox_port\", self._port)",
    "docstring": "Sets the port that WebDriver will be running on"
  },
  {
    "code": "def CreateUnit(self, parent=None, value=None, bid_amount=None):\n    unit = {\n        'xsi_type': 'ProductPartition',\n        'partitionType': 'UNIT'\n    }\n    if parent is not None:\n      unit['parentCriterionId'] = parent['id']\n      unit['caseValue'] = value\n    if bid_amount is not None and bid_amount > 0:\n      bidding_strategy_configuration = {\n          'bids': [{\n              'xsi_type': 'CpcBid',\n              'bid': {\n                  'xsi_type': 'Money',\n                  'microAmount': str(bid_amount)\n              }\n          }]\n      }\n      adgroup_criterion = {\n          'xsi_type': 'BiddableAdGroupCriterion',\n          'biddingStrategyConfiguration': bidding_strategy_configuration\n      }\n    else:\n      adgroup_criterion = {\n          'xsi_type': 'NegativeAdGroupCriterion'\n      }\n    adgroup_criterion['adGroupId'] = self.adgroup_id\n    adgroup_criterion['criterion'] = unit\n    self.CreateAddOperation(adgroup_criterion)\n    return unit",
    "docstring": "Creates a unit node.\n\n    Args:\n      parent: The node that should be this node's parent.\n      value: The value being partitioned on.\n      bid_amount: The amount to bid for matching products, in micros.\n    Returns:\n      A new unit node."
  },
  {
    "code": "def get_table_schema(self, dataset, table, project_id=None):\n        project_id = self._get_project_id(project_id)\n        try:    \n            result = self.bigquery.tables().get(\n                projectId=project_id,\n                tableId=table,\n                datasetId=dataset).execute(num_retries=self.num_retries)\n        except HttpError as e:\n            if int(e.resp['status']) == 404:\n                logger.warn('Table %s.%s does not exist', dataset, table)\n                return None\n            raise\n        return result['schema']['fields']",
    "docstring": "Return the table schema.\n\n        Parameters\n        ----------\n        dataset : str\n            The dataset containing the `table`.\n        table : str\n            The table to get the schema for\n        project_id: str, optional\n            The project of the dataset.\n\n        Returns\n        -------\n        list\n            A ``list`` of ``dict`` objects that represent the table schema. If\n            the table doesn't exist, None is returned."
  },
  {
    "code": "def is_valid_number_for_region(numobj, region_code):\n    country_code = numobj.country_code\n    if region_code is None:\n        return False\n    metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code.upper())\n    if (metadata is None or\n        (region_code != REGION_CODE_FOR_NON_GEO_ENTITY and\n         country_code != country_code_for_valid_region(region_code))):\n        return False\n    nsn = national_significant_number(numobj)\n    return (_number_type_helper(nsn, metadata) != PhoneNumberType.UNKNOWN)",
    "docstring": "Tests whether a phone number is valid for a certain region.\n\n    Note this doesn't verify the number is actually in use, which is\n    impossible to tell by just looking at a number itself. If the country\n    calling code is not the same as the country calling code for the region,\n    this immediately exits with false. After this, the specific number pattern\n    rules for the region are examined. This is useful for determining for\n    example whether a particular number is valid for Canada, rather than just\n    a valid NANPA number.\n\n    Warning: In most cases, you want to use is_valid_number instead. For\n    example, this method will mark numbers from British Crown dependencies\n    such as the Isle of Man as invalid for the region \"GB\" (United Kingdom),\n    since it has its own region code, \"IM\", which may be undesirable.\n\n    Arguments:\n    numobj -- The phone number object that we want to validate.\n    region_code -- The region that we want to validate the phone number for.\n\n    Returns a boolean that indicates whether the number is of a valid pattern."
  },
  {
    "code": "def set_cell(self, i, j, value):\n        bool_tests = [\n            value in self._possibles[i][j],\n            value in self._poss_rows[i],\n            value in self._poss_cols[j],\n            value in self._poss_box[(i // self.order) * self.order + (j // self.order)],\n            value not in self.row(i),\n            value not in self.col(j),\n            value not in self.box(i, j)\n        ]\n        if all(bool_tests):\n            self[i][j] = value\n        else:\n            raise SudokuHasNoSolutionError(\"This value cannot be set here!\")",
    "docstring": "Set a cell's value, with a series of safety checks\n\n        :param i: The row number\n        :type i: int\n        :param j: The column number\n        :type j: int\n        :param value: The value to set\n        :type value: int\n        :raises: :py:class:`dlxsudoku.exceptions.SudokuHasNoSolutionError`"
  },
  {
    "code": "def value_at(self, x):\n        x = Quantity(x, self.xindex.unit).value\n        try:\n            idx = (self.xindex.value == x).nonzero()[0][0]\n        except IndexError as e:\n            e.args = (\"Value %r not found in array index\" % x,)\n            raise\n        return self[idx]",
    "docstring": "Return the value of this `Series` at the given `xindex` value\n\n        Parameters\n        ----------\n        x : `float`, `~astropy.units.Quantity`\n            the `xindex` value at which to search\n\n        Returns\n        -------\n        y : `~astropy.units.Quantity`\n            the value of this Series at the given `xindex` value"
  },
  {
    "code": "def chain_functions(functions):\n    functions = list(functions)\n    if not functions:\n        return _no_op\n    elif len(functions) == 1:\n        return functions[0]\n    else:\n        return partial(reduce, lambda res, f: f(res), functions)",
    "docstring": "Chain a list of single-argument functions together and return.\n\n    The functions are applied in list order, and the output of the\n    previous functions is passed to the next function.\n\n    Parameters\n    ----------\n    functions : list\n        A list of single-argument functions to chain together.\n\n    Returns\n    -------\n    func : callable\n        A single argument function.\n\n    Examples\n    --------\n    Chain several functions together!\n\n        >>> funcs = [lambda x: x * 4, len, lambda x: x + 5]\n        >>> func = chain_functions(funcs)\n        >>> func('hey')\n        17"
  },
  {
    "code": "def update(self, item, id_expression=None, upsert=False, update_ops={}, safe=None, **kwargs):\n\t\tif safe is None:\n\t\t\tsafe = self.safe\n\t\tself.queue.append(UpdateDocumentOp(self.transaction_id, self, item, safe, id_expression=id_expression,\n\t\t\t\t\t\t  upsert=upsert, update_ops=update_ops, **kwargs))\n\t\tif self.autoflush:\n\t\t\treturn self.flush()",
    "docstring": "Update an item in the database.  Uses the on_update keyword to each\n\t\t\tfield to decide which operations to do, or.\n\n\t\t\t:param item: An instance of a :class:`~ommongo.document.Document` \\\n\t\t\t\tsubclass\n\t\t\t:param id_expression: A query expression that uniquely picks out \\\n\t\t\t\tthe item which should be updated.  If id_expression is not \\\n\t\t\t\tpassed, update uses item.mongo_id.\n\t\t\t:param upsert: Whether the update operation should be an upsert. \\\n\t\t\t\tIf the item may not be in the database yet this should be True\n\t\t\t:param update_ops: By default the operation used to update a field \\\n\t\t\t\tis specified with the on_update argument to its constructor. \\\n\t\t\t\tTo override that value, use this dictionary, with  \\\n\t\t\t\t:class:`~ommongo.document.QueryField` objects as the keys \\\n\t\t\t\tand the mongo operation to use as the values.\n\t\t\t:param kwargs: The kwargs are merged into update_ops dict to \\\n\t\t\t\tdecide which fields to update the operation for.  These can \\\n\t\t\t\tonly be for the top-level document since the keys \\\n\t\t\t\tare just strings.\n\n\t\t\t.. warning::\n\n\t\t\t\tThis operation is **experimental** and **not fully tested**,\n\t\t\t\talthough it does have code coverage."
  },
  {
    "code": "def list_flavors(self, limit=None, marker=None):\n        return self._flavor_manager.list(limit=limit, marker=marker)",
    "docstring": "Returns a list of all available Flavors."
  },
  {
    "code": "def estimate(self, observations, weights):\n        N, M = self._output_probabilities.shape\n        K = len(observations)\n        self._output_probabilities = np.zeros((N, M))\n        if self.__impl__ == self.__IMPL_C__:\n            for k in range(K):\n                dc.update_pout(observations[k], weights[k], self._output_probabilities, dtype=config.dtype)\n        elif self.__impl__ == self.__IMPL_PYTHON__:\n            for k in range(K):\n                for o in range(M):\n                    times = np.where(observations[k] == o)[0]\n                    self._output_probabilities[:, o] += np.sum(weights[k][times, :], axis=0)\n        else:\n            raise RuntimeError('Implementation '+str(self.__impl__)+' not available')\n        self._output_probabilities /= np.sum(self._output_probabilities, axis=1)[:, None]",
    "docstring": "Maximum likelihood estimation of output model given the observations and weights\n\n        Parameters\n        ----------\n\n        observations : [ ndarray(T_k) ] with K elements\n            A list of K observation trajectories, each having length T_k\n        weights : [ ndarray(T_k, N) ] with K elements\n            A list of K weight matrices, each having length T_k and containing the probability of any of the states in\n            the given time step\n\n        Examples\n        --------\n\n        Generate an observation model and samples from each state.\n\n        >>> import numpy as np\n        >>> ntrajectories = 3\n        >>> nobs = 1000\n        >>> B = np.array([[0.5,0.5],[0.1,0.9]])\n        >>> output_model = DiscreteOutputModel(B)\n\n        >>> from scipy import stats\n        >>> nobs = 1000\n        >>> obs = np.empty(nobs, dtype = object)\n        >>> weights = np.empty(nobs, dtype = object)\n\n        >>> gens = [stats.rv_discrete(values=(range(len(B[i])), B[i])) for i in range(B.shape[0])]\n        >>> obs = [gens[i].rvs(size=nobs) for i in range(B.shape[0])]\n        >>> weights = [np.zeros((nobs, B.shape[1])) for i in range(B.shape[0])]\n        >>> for i in range(B.shape[0]): weights[i][:, i] = 1.0\n\n        Update the observation model parameters my a maximum-likelihood fit.\n\n        >>> output_model.estimate(obs, weights)"
  },
  {
    "code": "def _validate_geometry(self, geometry):\n        if geometry is not None and geometry not in self.valid_geometries:\n            raise InvalidParameterError(\"{} is not a valid geometry\".format(geometry))\n        return geometry",
    "docstring": "Validates geometry, raising error if invalid."
  },
  {
    "code": "def get_all_subscriptions(self, next_token=None):\n        params = {'ContentType' : 'JSON'}\n        if next_token:\n            params['NextToken'] = next_token\n        response = self.make_request('ListSubscriptions', params, '/', 'GET')\n        body = response.read()\n        if response.status == 200:\n            return json.loads(body)\n        else:\n            boto.log.error('%s %s' % (response.status, response.reason))\n            boto.log.error('%s' % body)\n            raise self.ResponseError(response.status, response.reason, body)",
    "docstring": "Get list of all subscriptions.\n\n        :type next_token: string\n        :param next_token: Token returned by the previous call to\n                           this method."
  },
  {
    "code": "def _make_style_str(styledict):\n    s = ''\n    for key in list(styledict.keys()):\n        s += \"%s:%s;\" % (key, styledict[key])\n    return s",
    "docstring": "Make an SVG style string from the dictionary. See also _parse_style_str also."
  },
  {
    "code": "def clean_path(path):\n    path = path.replace(os.sep, '/')\n    if path.startswith('./'):\n        path = path[2:]\n    return path",
    "docstring": "Clean the path"
  },
  {
    "code": "def linear(self, x):\n    with tf.name_scope(\"presoftmax_linear\"):\n      batch_size = tf.shape(x)[0]\n      length = tf.shape(x)[1]\n      x = tf.reshape(x, [-1, self.hidden_size])\n      logits = tf.matmul(x, self.shared_weights, transpose_b=True)\n      return tf.reshape(logits, [batch_size, length, self.vocab_size])",
    "docstring": "Computes logits by running x through a linear layer.\n\n    Args:\n      x: A float32 tensor with shape [batch_size, length, hidden_size]\n    Returns:\n      float32 tensor with shape [batch_size, length, vocab_size]."
  },
  {
    "code": "def import_checks(path):\n    dir = internal.check_dir / path\n    file = internal.load_config(dir)[\"checks\"]\n    mod = internal.import_file(dir.name, (dir / file).resolve())\n    sys.modules[dir.name] = mod\n    return mod",
    "docstring": "Import checks module given relative path.\n\n    :param path: relative path from which to import checks module\n    :type path: str\n    :returns: the imported module\n    :raises FileNotFoundError: if ``path / .check50.yaml`` does not exist\n    :raises yaml.YAMLError: if ``path / .check50.yaml`` is not a valid YAML file\n\n    This function is particularly useful when a set of checks logically extends\n    another, as is often the case in CS50's own problems that have a \"less comfy\"\n    and \"more comfy\" version. The \"more comfy\" version can include all of the\n    \"less comfy\" checks like so::\n\n        less = check50.import_checks(\"../less\")\n        from less import *\n\n    .. note::\n        the ``__name__`` of the imported module is given by the basename\n        of the specified path (``less`` in the above example)."
  },
  {
    "code": "def to_unix(cls, timestamp):\n        if not isinstance(timestamp, datetime.datetime):\n            raise TypeError('Time.milliseconds expects a datetime object')\n        base = time.mktime(timestamp.timetuple())\n        return base",
    "docstring": "Wrapper over time module to produce Unix epoch time as a float"
  },
  {
    "code": "def _init_entri(self, laman):\n        sup = BeautifulSoup(laman.text, 'html.parser')\n        estr = ''\n        for label in sup.find('hr').next_siblings:\n            if label.name == 'hr':\n                self.entri.append(Entri(estr))\n                break\n            if label.name == 'h2':\n                if estr:\n                    self.entri.append(Entri(estr))\n                estr = ''\n            estr += str(label).strip()",
    "docstring": "Membuat objek-objek entri dari laman yang diambil.\n\n        :param laman: Laman respons yang dikembalikan oleh KBBI daring.\n        :type laman: Response"
  },
  {
    "code": "def authorization_url(self, **kwargs):\n        kwargs.setdefault('access_type', 'offline')\n        url, state = self.oauth2session.authorization_url(\n            self.client_config['auth_uri'], **kwargs)\n        return url, state",
    "docstring": "Generates an authorization URL.\n\n        This is the first step in the OAuth 2.0 Authorization Flow. The user's\n        browser should be redirected to the returned URL.\n\n        This method calls\n        :meth:`requests_oauthlib.OAuth2Session.authorization_url`\n        and specifies the client configuration's authorization URI (usually\n        Google's authorization server) and specifies that \"offline\" access is\n        desired. This is required in order to obtain a refresh token.\n\n        Args:\n            kwargs: Additional arguments passed through to\n                :meth:`requests_oauthlib.OAuth2Session.authorization_url`\n\n        Returns:\n            Tuple[str, str]: The generated authorization URL and state. The\n                user must visit the URL to complete the flow. The state is used\n                when completing the flow to verify that the request originated\n                from your application. If your application is using a different\n                :class:`Flow` instance to obtain the token, you will need to\n                specify the ``state`` when constructing the :class:`Flow`."
  },
  {
    "code": "def set_expiration(self, key, ignore_missing=False,\n            additional_seconds=None, seconds=None):\n        if key not in self.time_dict and ignore_missing:\n            return\n        elif key not in self.time_dict and not ignore_missing:\n            raise Exception('Key missing from `TimedDict` and '\n                '`ignore_missing` is False.')\n        if additional_seconds is not None:\n            self.time_dict[key] += additional_seconds\n        elif seconds is not None:\n            self.time_dict[key] = time.time() + seconds",
    "docstring": "Alters the expiration time for a key. If the key is not\n        present, then raise an Exception unless `ignore_missing`\n        is set to `True`.\n\n        Args:\n            key: The key whose expiration we are changing.\n            ignore_missing (bool): If set, then return silently\n                if the key does not exist. Default is `False`.\n            additional_seonds (int): Add this many seconds to the\n                current expiration time.\n            seconds (int): Expire the key this many seconds from now."
  },
  {
    "code": "def login(config, api_key=\"\"):\n    if not api_key:\n        info_out(\n            \"If you don't have an API Key, go to:\\n\"\n            \"https://bugzilla.mozilla.org/userprefs.cgi?tab=apikey\\n\"\n        )\n        api_key = getpass.getpass(\"API Key: \")\n    url = urllib.parse.urljoin(config.bugzilla_url, \"/rest/whoami\")\n    assert url.startswith(\"https://\"), url\n    response = requests.get(url, params={\"api_key\": api_key})\n    if response.status_code == 200:\n        if response.json().get(\"error\"):\n            error_out(\"Failed - {}\".format(response.json()))\n        else:\n            update(\n                config.configfile,\n                {\n                    \"BUGZILLA\": {\n                        \"bugzilla_url\": config.bugzilla_url,\n                        \"api_key\": api_key,\n                    }\n                },\n            )\n            success_out(\"Yay! It worked!\")\n    else:\n        error_out(\"Failed - {} ({})\".format(response.status_code, response.json()))",
    "docstring": "Store your Bugzilla API Key"
  },
  {
    "code": "def tokens(cls, tokens):\n        return cls(Lnk.TOKENS, tuple(map(int, tokens)))",
    "docstring": "Create a Lnk object for a token range.\n\n        Args:\n            tokens: a list of token identifiers"
  },
  {
    "code": "def on_post(resc, req, resp):\n    signals.pre_req.send(resc.model)\n    signals.pre_req_create.send(resc.model)\n    props = req.deserialize()\n    model = resc.model()\n    from_rest(model, props)\n    goldman.sess.store.create(model)\n    props = to_rest_model(model, includes=req.includes)\n    resp.last_modified = model.updated\n    resp.location = '%s/%s' % (req.path, model.rid_value)\n    resp.status = falcon.HTTP_201\n    resp.serialize(props)\n    signals.post_req.send(resc.model)\n    signals.post_req_create.send(resc.model)",
    "docstring": "Deserialize the payload & create the new single item"
  },
  {
    "code": "def kill(self, name):\n        if not name:\n            raise ValueError(\"Name can't be None or empty\")\n        with self.__instances_lock:\n            try:\n                stored_instance = self.__instances.pop(name)\n                factory_context = stored_instance.context.factory_context\n                stored_instance.kill()\n                factory_context.is_singleton_active = False\n            except KeyError:\n                try:\n                    context, _ = self.__waiting_handlers.pop(name)\n                    context.factory_context.is_singleton_active = False\n                except KeyError:\n                    raise ValueError(\n                        \"Unknown component instance '{0}'\".format(name)\n                    )",
    "docstring": "Kills the given component\n\n        :param name: Name of the component to kill\n        :raise ValueError: Invalid component name"
  },
  {
    "code": "def growthfromrange(rangegrowth, startdate, enddate):\n    _yrs = (pd.Timestamp(enddate) - pd.Timestamp(startdate)).total_seconds() /\\\n            dt.timedelta(365.25).total_seconds()\n    return yrlygrowth(rangegrowth, _yrs)",
    "docstring": "Annual growth given growth from start date to end date."
  },
  {
    "code": "def winnow_by_keys(dct, keys=None, filter_func=None):\n    has = {}\n    has_not = {}\n    for key in dct:\n        key_passes_check = False\n        if keys is not None:\n            key_passes_check = key in keys\n        elif filter_func is not None:\n            key_passes_check = filter_func(key)\n        if key_passes_check:\n            has[key] = dct[key]\n        else:\n            has_not[key] = dct[key]\n    return WinnowedResult(has, has_not)",
    "docstring": "separates a dict into has-keys and not-has-keys pairs, using either\n    a list of keys or a filtering function."
  },
  {
    "code": "def determine_repo_dir(template, abbreviations, clone_to_dir, checkout,\n                       no_input, password=None):\n    template = expand_abbreviations(template, abbreviations)\n    if is_zip_file(template):\n        unzipped_dir = unzip(\n            zip_uri=template,\n            is_url=is_repo_url(template),\n            clone_to_dir=clone_to_dir,\n            no_input=no_input,\n            password=password\n        )\n        repository_candidates = [unzipped_dir]\n        cleanup = True\n    elif is_repo_url(template):\n        cloned_repo = clone(\n            repo_url=template,\n            checkout=checkout,\n            clone_to_dir=clone_to_dir,\n            no_input=no_input,\n        )\n        repository_candidates = [cloned_repo]\n        cleanup = False\n    else:\n        repository_candidates = [\n            template,\n            os.path.join(clone_to_dir, template)\n        ]\n        cleanup = False\n    for repo_candidate in repository_candidates:\n        if repository_has_cookiecutter_json(repo_candidate):\n            return repo_candidate, cleanup\n    raise RepositoryNotFound(\n        'A valid repository for \"{}\" could not be found in the following '\n        'locations:\\n{}'.format(\n            template,\n            '\\n'.join(repository_candidates)\n        )\n    )",
    "docstring": "Locate the repository directory from a template reference.\n\n    Applies repository abbreviations to the template reference.\n    If the template refers to a repository URL, clone it.\n    If the template is a path to a local repository, use it.\n\n    :param template: A directory containing a project template directory,\n        or a URL to a git repository.\n    :param abbreviations: A dictionary of repository abbreviation\n        definitions.\n    :param clone_to_dir: The directory to clone the repository into.\n    :param checkout: The branch, tag or commit ID to checkout after clone.\n    :param no_input: Prompt the user at command line for manual configuration?\n    :param password: The password to use when extracting the repository.\n    :return: A tuple containing the cookiecutter template directory, and\n        a boolean descriving whether that directory should be cleaned up\n        after the template has been instantiated.\n    :raises: `RepositoryNotFound` if a repository directory could not be found."
  },
  {
    "code": "def pretty_dump(fn):\n    @wraps(fn)\n    def pretty_dump_wrapper(*args, **kwargs):\n        response.content_type = \"application/json; charset=utf-8\"\n        return json.dumps(\n            fn(*args, **kwargs),\n            indent=4,\n            separators=(',', ': ')\n        )\n    return pretty_dump_wrapper",
    "docstring": "Decorator used to output prettified JSON.\n\n    ``response.content_type`` is set to ``application/json; charset=utf-8``.\n\n    Args:\n        fn (fn pointer): Function returning any basic python data structure.\n\n    Returns:\n        str: Data converted to prettified JSON."
  },
  {
    "code": "def _maybe_normalize(self, var):\n        if self.normalize:\n            try:\n                return self._norm.normalize(var)\n            except HGVSUnsupportedOperationError as e:\n                _logger.warning(str(e) + \"; returning unnormalized variant\")\n        return var",
    "docstring": "normalize variant if requested, and ignore HGVSUnsupportedOperationError\n        This is better than checking whether the variant is intronic because\n        future UTAs will support LRG, which will enable checking intronic variants."
  },
  {
    "code": "def addFailure(self, test, err, capt=None, tbinfo=None):\n        self.__insert_test_result(constants.State.FAILURE, test, err)",
    "docstring": "After a test failure, we want to record testcase run information."
  },
  {
    "code": "def add_code_mapping(self, from_pdb_code, to_pdb_code):\n        if from_pdb_code in self.code_map:\n            assert(self.code_map[from_pdb_code] == to_pdb_code)\n        else:\n            self.code_map[from_pdb_code] = to_pdb_code",
    "docstring": "Add a code mapping without a given instance."
  },
  {
    "code": "def create_query(self, fields=None):\n        if fields is None:\n            return Query(self.fields)\n        non_contained_fields = set(fields) - set(self.fields)\n        if non_contained_fields:\n            raise BaseLunrException(\n                \"Fields {} are not part of the index\", non_contained_fields\n            )\n        return Query(fields)",
    "docstring": "Convenience method to create a Query with the Index's fields.\n\n        Args:\n            fields (iterable, optional): The fields to include in the Query,\n                defaults to the Index's `all_fields`.\n\n        Returns:\n            Query: With the specified fields or all the fields in the Index."
  },
  {
    "code": "def tx_for_tx_hash(self, tx_hash):\n        try:\n            url_append = \"?token=%s&includeHex=true\" % self.api_key\n            url = self.base_url(\"txs/%s%s\" % (b2h_rev(tx_hash), url_append))\n            result = json.loads(urlopen(url).read().decode(\"utf8\"))\n            tx = Tx.parse(io.BytesIO(h2b(result.get(\"hex\"))))\n            return tx\n        except Exception:\n            raise Exception",
    "docstring": "returns the pycoin.tx object for tx_hash"
  },
  {
    "code": "def reset(self):\n        self.idx_annotations.setText('Load Annotation File...')\n        self.idx_rater.setText('')\n        self.annot = None\n        self.dataset_markers = None\n        self.idx_marker.clearContents()\n        self.idx_marker.setRowCount(0)\n        w1 = self.idx_summary.takeAt(1).widget()\n        w2 = self.idx_summary.takeAt(1).widget()\n        self.idx_summary.removeWidget(w1)\n        self.idx_summary.removeWidget(w2)\n        w1.deleteLater()\n        w2.deleteLater()\n        b1 = QGroupBox('Staging')\n        b2 = QGroupBox('Signal quality')\n        self.idx_summary.addWidget(b1)\n        self.idx_summary.addWidget(b2)\n        self.display_eventtype()\n        self.update_annotations()\n        self.parent.create_menubar()",
    "docstring": "Remove all annotations from window."
  },
  {
    "code": "def eventsource_connect(url, io_loop=None, callback=None, connect_timeout=None):\n    if io_loop is None:\n        io_loop = IOLoop.current()\n    if isinstance(url, httpclient.HTTPRequest):\n        assert connect_timeout is None\n        request = url\n        request.headers = httputil.HTTPHeaders(request.headers)\n    else:\n        request = httpclient.HTTPRequest(\n            url,\n            connect_timeout=connect_timeout,\n            headers=httputil.HTTPHeaders({\n                \"Accept-Encoding\": \"identity\"\n            })\n        )\n    request = httpclient._RequestProxy(\n        request, httpclient.HTTPRequest._DEFAULTS)\n    conn = EventSourceClient(io_loop, request)\n    if callback is not None:\n        io_loop.add_future(conn.connect_future, callback)\n    return conn.connect_future",
    "docstring": "Client-side eventsource support.\n\n    Takes a url and returns a Future whose result is a\n    `EventSourceClient`."
  },
  {
    "code": "def frommembers(cls, members=()):\n        return cls.fromint(sum(map(cls._map.__getitem__, set(members))))",
    "docstring": "Create a set from an iterable of members."
  },
  {
    "code": "def sort_dicoms(dicoms):\n    dicom_input_sorted_x = sorted(dicoms, key=lambda x: (x.ImagePositionPatient[0]))\n    dicom_input_sorted_y = sorted(dicoms, key=lambda x: (x.ImagePositionPatient[1]))\n    dicom_input_sorted_z = sorted(dicoms, key=lambda x: (x.ImagePositionPatient[2]))\n    diff_x = abs(dicom_input_sorted_x[-1].ImagePositionPatient[0] - dicom_input_sorted_x[0].ImagePositionPatient[0])\n    diff_y = abs(dicom_input_sorted_y[-1].ImagePositionPatient[1] - dicom_input_sorted_y[0].ImagePositionPatient[1])\n    diff_z = abs(dicom_input_sorted_z[-1].ImagePositionPatient[2] - dicom_input_sorted_z[0].ImagePositionPatient[2])\n    if diff_x >= diff_y and diff_x >= diff_z:\n        return dicom_input_sorted_x\n    if diff_y >= diff_x and diff_y >= diff_z:\n        return dicom_input_sorted_y\n    if diff_z >= diff_x and diff_z >= diff_y:\n        return dicom_input_sorted_z",
    "docstring": "Sort the dicoms based om the image possition patient\n\n    :param dicoms: list of dicoms"
  },
  {
    "code": "def rebin_scale(a, scale=1):\n    newshape = tuple((side * scale) for side in a.shape)\n    return rebin(a, newshape)",
    "docstring": "Scale an array to a new shape."
  },
  {
    "code": "def active_days(records):\n    days = set(r.datetime.date() for r in records)\n    return len(days)",
    "docstring": "The number of days during which the user was active. A user is considered\n    active if he sends a text, receives a text, initiates a call, receives a\n    call, or has a mobility point."
  },
  {
    "code": "def mergeStyles(self, styles):\n        \" XXX Bugfix for use in PISA \"\n        for k, v in six.iteritems(styles):\n            if k in self and self[k]:\n                self[k] = copy.copy(self[k])\n                self[k].update(v)\n            else:\n                self[k] = v",
    "docstring": "XXX Bugfix for use in PISA"
  },
  {
    "code": "def get_token(self, code=None):\n        tokenobj = self.steemconnect().get_access_token(code)\n        for t in tokenobj:\n            if t == 'error':\n                self.msg.error_message(str(tokenobj[t]))\n                return False\n            elif t == 'access_token':\n                self.username = tokenobj['username']\n                self.refresh_token = tokenobj['refresh_token']\n                return tokenobj[t]",
    "docstring": "Uses a SteemConnect refresh token\n        to retreive an access token"
  },
  {
    "code": "def _get_ruuvitag_datas(macs=[], search_duratio_sec=None, run_flag=RunFlag(), bt_device=''):\n        mac_blacklist = []\n        start_time = time.time()\n        data_iter = ble.get_datas(mac_blacklist, bt_device)\n        for ble_data in data_iter:\n            if search_duratio_sec and time.time() - start_time > search_duratio_sec:\n                data_iter.send(StopIteration)\n                break\n            if not run_flag.running:\n                data_iter.send(StopIteration)\n                break\n            if macs and not ble_data[0] in macs:\n                continue\n            (data_format, data) = RuuviTagSensor.convert_data(ble_data[1])\n            if data is not None:\n                state = get_decoder(data_format).decode_data(data)\n                if state is not None:\n                    yield (ble_data[0], state)\n            else:\n                mac_blacklist.append(ble_data[0])",
    "docstring": "Get data from BluetoothCommunication and handle data encoding.\n\n        Args:\n            macs (list): MAC addresses. Default empty list\n            search_duratio_sec (int): Search duration in seconds. Default None\n            run_flag (object): RunFlag object. Function executes while run_flag.running. Default new RunFlag\n            bt_device (string): Bluetooth device id\n        Yields:\n            tuple: MAC and State of RuuviTag sensor data"
  },
  {
    "code": "def delete(self, exchange, if_unused=False, nowait=True, ticket=None,\n               cb=None):\n        nowait = nowait and self.allow_nowait() and not cb\n        args = Writer()\n        args.write_short(ticket or self.default_ticket).\\\n            write_shortstr(exchange).\\\n            write_bits(if_unused, nowait)\n        self.send_frame(MethodFrame(self.channel_id, 40, 20, args))\n        if not nowait:\n            self._delete_cb.append(cb)\n            self.channel.add_synchronous_cb(self._recv_delete_ok)",
    "docstring": "Delete an exchange."
  },
  {
    "code": "def createStopOrder(self, quantity, parentId=0, stop=0., trail=None,\n            transmit=True, group=None, stop_limit=False, rth=False, tif=\"DAY\",\n            account=None):\n        if trail:\n            if trail == \"percent\":\n                order = self.createOrder(quantity,\n                            trailingPercent = stop,\n                            transmit  = transmit,\n                            orderType = dataTypes[\"ORDER_TYPE_TRAIL_STOP\"],\n                            ocaGroup  = group,\n                            parentId  = parentId,\n                            rth       = rth,\n                            tif       = tif,\n                            account   = account\n                        )\n            else:\n                order = self.createOrder(quantity,\n                            trailStopPrice = stop,\n                            stop      = stop,\n                            transmit  = transmit,\n                            orderType = dataTypes[\"ORDER_TYPE_TRAIL_STOP\"],\n                            ocaGroup  = group,\n                            parentId  = parentId,\n                            rth       = rth,\n                            tif       = tif,\n                            account   = account\n                        )\n        else:\n            order = self.createOrder(quantity,\n                        stop      = stop,\n                        price     = stop if stop_limit else 0.,\n                        transmit  = transmit,\n                        orderType = dataTypes[\"ORDER_TYPE_STOP_LIMIT\"] if stop_limit else dataTypes[\"ORDER_TYPE_STOP\"],\n                        ocaGroup  = group,\n                        parentId  = parentId,\n                        rth       = rth,\n                        tif       = tif,\n                        account   = account\n                    )\n        return order",
    "docstring": "Creates STOP order"
  },
  {
    "code": "def to_bqm(self, model):\n        linear = ((v, float(model.get_py_value(bias)))\n                  for v, bias in self.linear.items())\n        quadratic = ((u, v, float(model.get_py_value(bias)))\n                     for (u, v), bias in self.quadratic.items())\n        offset = float(model.get_py_value(self.offset))\n        return dimod.BinaryQuadraticModel(linear, quadratic, offset, dimod.SPIN)",
    "docstring": "Given a pysmt model, return a bqm.\n\n        Adds the values of the biases as determined by the SMT solver to a bqm.\n\n        Args:\n            model: A pysmt model.\n\n        Returns:\n            :obj:`dimod.BinaryQuadraticModel`"
  },
  {
    "code": "def get_grid_mapping_variables(ds):\n    grid_mapping_variables = []\n    for ncvar in ds.get_variables_by_attributes(grid_mapping=lambda x: x is not None):\n        if ncvar.grid_mapping in ds.variables:\n            grid_mapping_variables.append(ncvar.grid_mapping)\n    return grid_mapping_variables",
    "docstring": "Returns a list of grid mapping variables\n\n    :param netCDF4.Dataset ds: An open netCDF4 Dataset"
  },
  {
    "code": "def absent(name, **connection_args):\n    ret = {'name': name,\n           'changes': {},\n           'result': True,\n           'comment': ''}\n    if __salt__['mysql.db_exists'](name, **connection_args):\n        if __opts__['test']:\n            ret['result'] = None\n            ret['comment'] = \\\n                'Database {0} is present and needs to be removed'.format(name)\n            return ret\n        if __salt__['mysql.db_remove'](name, **connection_args):\n            ret['comment'] = 'Database {0} has been removed'.format(name)\n            ret['changes'][name] = 'Absent'\n            return ret\n        else:\n            err = _get_mysql_error()\n            if err is not None:\n                ret['comment'] = 'Unable to remove database {0} ' \\\n                                 '({1})'.format(name, err)\n                ret['result'] = False\n                return ret\n    else:\n        err = _get_mysql_error()\n        if err is not None:\n            ret['comment'] = err\n            ret['result'] = False\n            return ret\n    ret['comment'] = ('Database {0} is not present, so it cannot be removed'\n            ).format(name)\n    return ret",
    "docstring": "Ensure that the named database is absent\n\n    name\n        The name of the database to remove"
  },
  {
    "code": "def _remove_untraceable(self):\n        self._probe_mapping = {}\n        wvs = {wv for wv in self.tracer.wires_to_track if self._traceable(wv)}\n        self.tracer.wires_to_track = wvs\n        self.tracer._wires = {wv.name: wv for wv in wvs}\n        self.tracer.trace.__init__(wvs)",
    "docstring": "Remove from the tracer those wires that CompiledSimulation cannot track.\n\n        Create _probe_mapping for wires only traceable via probes."
  },
  {
    "code": "def _raw_input_contains_national_prefix(raw_input, national_prefix, region_code):\n    nnn = normalize_digits_only(raw_input)\n    if nnn.startswith(national_prefix):\n        try:\n            return is_valid_number(parse(nnn[len(national_prefix):], region_code))\n        except NumberParseException:\n            return False\n    return False",
    "docstring": "Check if raw_input, which is assumed to be in the national format, has a\n    national prefix. The national prefix is assumed to be in digits-only\n    form."
  },
  {
    "code": "def obj_deref(ref):\n    from indico_livesync.models.queue import EntryType\n    if ref['type'] == EntryType.category:\n        return Category.get_one(ref['category_id'])\n    elif ref['type'] == EntryType.event:\n        return Event.get_one(ref['event_id'])\n    elif ref['type'] == EntryType.session:\n        return Session.get_one(ref['session_id'])\n    elif ref['type'] == EntryType.contribution:\n        return Contribution.get_one(ref['contrib_id'])\n    elif ref['type'] == EntryType.subcontribution:\n        return SubContribution.get_one(ref['subcontrib_id'])\n    else:\n        raise ValueError('Unexpected object type: {}'.format(ref['type']))",
    "docstring": "Returns the object identified by `ref`"
  },
  {
    "code": "def transform_attrs(obj, keys, container, func, extras=None):\n    cpextras = extras\n    for reportlab, css in keys:\n        extras = cpextras\n        if extras is None:\n            extras = []\n        elif not isinstance(extras, list):\n            extras = [extras]\n        if css in container:\n            extras.insert(0, container[css])\n            setattr(obj,\n                    reportlab,\n                    func(*extras)\n                    )",
    "docstring": "Allows to apply one function to set of keys cheching if key is in container,\n    also trasform ccs key to report lab keys.\n\n    extras = Are extra params for func, it will be call like func(*[param1, param2]) \n\n    obj = frag\n    keys = [(reportlab, css), ... ]\n    container = cssAttr"
  },
  {
    "code": "def send(self, to, from_, body):\n        try:\n            msg = self.client.sms.messages.create(\n                body=body,\n                to=to,\n                from_=from_\n                )\n            print msg.sid\n        except twilio.TwilioRestException as e:\n            raise",
    "docstring": "Send BODY to TO from FROM as an SMS!"
  },
  {
    "code": "def _enable_logpersist(self):\n        if not self._ad.is_rootable:\n            return\n        logpersist_warning = ('%s encountered an error enabling persistent'\n                              ' logs, logs may not get saved.')\n        if not self._ad.adb.has_shell_command('logpersist.start'):\n            logging.warning(logpersist_warning, self)\n            return\n        try:\n            self._ad.adb.shell('logpersist.stop --clear')\n            self._ad.adb.shell('logpersist.start')\n        except adb.AdbError:\n            logging.warning(logpersist_warning, self)",
    "docstring": "Attempts to enable logpersist daemon to persist logs."
  },
  {
    "code": "def to_rest_models(models, includes=None):\n    props = {}\n    props['data'] = []\n    for model in models:\n        props['data'].append(_to_rest(model, includes=includes))\n    props['included'] = _to_rest_includes(models, includes=includes)\n    return props",
    "docstring": "Convert the models into a dict for serialization\n\n    models should be an array of single model objects that\n    will each be serialized.\n\n    :return: dict"
  },
  {
    "code": "def _build_time(time, kwargs):\n    tz = kwargs.pop('tz', 'UTC')\n    if time:\n        if kwargs:\n            raise ValueError('Cannot pass kwargs and a time')\n        else:\n            return ensure_utc(time, tz)\n    elif not kwargs:\n        raise ValueError('Must pass a time or kwargs')\n    else:\n        return datetime.time(**kwargs)",
    "docstring": "Builds the time argument for event rules."
  },
  {
    "code": "def analyze(output_dir, dataset, cloud=False, project_id=None):\n  job = analyze_async(\n      output_dir=output_dir,\n      dataset=dataset,\n      cloud=cloud,\n      project_id=project_id)\n  job.wait()\n  print('Analyze: ' + str(job.state))",
    "docstring": "Blocking version of analyze_async. See documentation of analyze_async."
  },
  {
    "code": "def revoke_token(token_id, user):\n    try:\n        token = TokenBlacklist.query.filter_by(id=token_id, user_identity=user).one()\n        token.revoked = True\n        db.session.commit()\n    except NoResultFound:\n        raise TokenNotFound(\"Could not find the token {}\".format(token_id))",
    "docstring": "Revokes the given token. Raises a TokenNotFound error if the token does\n    not exist in the database"
  },
  {
    "code": "def convert_timestamp(timestamp):\n    datetime = dt.datetime.utcfromtimestamp(timestamp/1000.)\n    return np.datetime64(datetime.replace(tzinfo=None))",
    "docstring": "Converts bokehJS timestamp to datetime64."
  },
  {
    "code": "def filter(objects, Type=None, min=-1, max=-1):\n    res = []\n    if min > max:\n        raise ValueError(\"minimum must be smaller than maximum\")\n    if Type is not None:\n        res = [o for o in objects if isinstance(o, Type)]\n    if min > -1:\n        res = [o for o in res if _getsizeof(o) < min]\n    if max > -1:\n        res = [o for o in res if _getsizeof(o) > max]\n    return res",
    "docstring": "Filter objects.\n\n    The filter can be by type, minimum size, and/or maximum size.\n\n    Keyword arguments:\n    Type -- object type to filter by\n    min -- minimum object size\n    max -- maximum object size"
  },
  {
    "code": "def add_nodes_from(self, nodes, weights=None):\n        nodes = list(nodes)\n        if weights:\n            if len(nodes) != len(weights):\n                raise ValueError(\"The number of elements in nodes and weights\"\n                                 \"should be equal.\")\n            for index in range(len(nodes)):\n                self.add_node(node=nodes[index], weight=weights[index])\n        else:\n            for node in nodes:\n                self.add_node(node=node)",
    "docstring": "Add multiple nodes to the Graph.\n\n        **The behviour of adding weights is different than in networkx.\n\n        Parameters\n        ----------\n        nodes: iterable container\n            A container of nodes (list, dict, set, or any hashable python\n            object).\n\n        weights: list, tuple (default=None)\n            A container of weights (int, float). The weight value at index i\n            is associated with the variable at index i.\n\n        Examples\n        --------\n        >>> from pgmpy.base import DAG\n        >>> G = DAG()\n        >>> G.add_nodes_from(nodes=['A', 'B', 'C'])\n        >>> sorted(G.nodes())\n        ['A', 'B', 'C']\n\n        Adding nodes with weights:\n        >>> G.add_nodes_from(nodes=['D', 'E'], weights=[0.3, 0.6])\n        >>> G.node['D']\n        {'weight': 0.3}\n        >>> G.node['E']\n        {'weight': 0.6}\n        >>> G.node['A']\n        {'weight': None}"
  },
  {
    "code": "def add_crosshair_to_image(fname, opFilename):\n    im = Image.open(fname)\n    draw = ImageDraw.Draw(im)\n    draw.line((0, 0) + im.size, fill=(255, 255, 255))\n    draw.line((0, im.size[1], im.size[0], 0), fill=(255, 255, 255))\n    del draw  \n    im.save(opFilename)",
    "docstring": "convert an image by adding a cross hair"
  },
  {
    "code": "def supernodes(par, post, colcount):\n    snpar, flag = pothen_sun(par, post, colcount)\n    n = len(par)\n    N = len(snpar)\n    snode = matrix(0, (n,1))\n    snptr = matrix(0, (N+1,1))\n    slist = [[] for i in range(n)]\n    for i in range(n):\n        f = flag[i]\n        if f < 0:\n            slist[i].append(i)\n        else:\n            slist[f].append(i)\n    k = 0; j = 0\n    for i,sl in enumerate(slist):\n        nsl = len(sl)\n        if nsl > 0:\n            snode[k:k+nsl] = matrix(sl)\n            snptr[j+1] = snptr[j] + nsl\n            k += nsl\n            j += 1\n    return snode, snptr, snpar",
    "docstring": "Find supernodes.\n\n    ARGUMENTS\n    par       parent array\n\n    post      array with post ordering\n\n    colcount  array with column counts\n\n    RETURNS\n    snode     array with supernodes; snode[snptr[k]:snptr[k+1]] contains\n              the indices of supernode k\n\n    snptr     pointer array; snptr[k] is the index of the representative\n              vertex of supernode k in the snode array\n\n    snpar     supernodal parent structure"
  },
  {
    "code": "def rerun(version=\"3.7.0\"):\n    from commandlib import Command\n    Command(DIR.gen.joinpath(\"py{0}\".format(version), \"bin\", \"python\"))(\n        DIR.gen.joinpath(\"state\", \"examplepythoncode.py\")\n    ).in_dir(DIR.gen.joinpath(\"state\")).run()",
    "docstring": "Rerun last example code block with specified version of python."
  },
  {
    "code": "def rebuild(self, image):\n        if isinstance(image, Image):\n            image = image.id\n        return self.act(type='rebuild', image=image)",
    "docstring": "Rebuild the droplet with the specified image\n\n            A rebuild action functions just like a new create. [APIDocs]_\n\n        :param image: an image ID, an image slug, or an `Image` object\n            representing the image the droplet should use as a base\n        :type image: integer, string, or `Image`\n        :return: an `Action` representing the in-progress operation on the\n            droplet\n        :rtype: Action\n        :raises DOAPIError: if the API endpoint replies with an error"
  },
  {
    "code": "def stream_fastq_full(fastq, threads):\n    logging.info(\"Nanoget: Starting to collect full metrics from plain fastq file.\")\n    inputfastq = handle_compressed_input(fastq)\n    with cfutures.ProcessPoolExecutor(max_workers=threads) as executor:\n        for results in executor.map(extract_all_from_fastq, SeqIO.parse(inputfastq, \"fastq\")):\n            yield results\n    logging.info(\"Nanoget: Finished collecting statistics from plain fastq file.\")",
    "docstring": "Generator for returning metrics extracted from fastq.\n\n    Extract from a fastq file:\n    -readname\n    -average and median quality\n    -read_lenght"
  },
  {
    "code": "def check_cond_latents(cond_latents, hparams):\n  if cond_latents is None:\n    return\n  if not isinstance(cond_latents[0], list):\n    cond_latents = [cond_latents]\n  exp_num_latents = hparams.num_cond_latents\n  if hparams.latent_dist_encoder == \"conv_net\":\n    exp_num_latents += int(hparams.cond_first_frame)\n  if len(cond_latents) != exp_num_latents:\n    raise ValueError(\"Expected number of cond_latents: %d, got %d\" %\n                     (exp_num_latents, len(cond_latents)))\n  for cond_latent in cond_latents:\n    if len(cond_latent) != hparams.n_levels - 1:\n      raise ValueError(\"Expected level_latents to be %d, got %d\" %\n                       (hparams.n_levels - 1, len(cond_latent)))",
    "docstring": "Shape checking for cond_latents."
  },
  {
    "code": "def _sample_groups(problem, N, num_levels=4):\n    if len(problem['groups']) != problem['num_vars']:\n        raise ValueError(\"Groups do not match to number of variables\")\n    group_membership, _ = compute_groups_matrix(problem['groups'])\n    if group_membership is None:\n        raise ValueError(\"Please define the 'group_membership' matrix\")\n    if not isinstance(group_membership, np.ndarray):\n        raise TypeError(\"Argument 'group_membership' should be formatted \\\n                         as a numpy ndarray\")\n    num_params = group_membership.shape[0]\n    num_groups = group_membership.shape[1]\n    sample = np.zeros((N * (num_groups + 1), num_params))\n    sample = np.array([generate_trajectory(group_membership,\n                                           num_levels)\n                       for n in range(N)])\n    return sample.reshape((N * (num_groups + 1), num_params))",
    "docstring": "Generate trajectories for groups\n\n    Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories,\n    where :math:`g` is the number of groups and :math:`k` is the number\n    of factors\n\n    Arguments\n    ---------\n    problem : dict\n        The problem definition\n    N : int\n        The number of trajectories to generate\n    num_levels : int, default=4\n        The number of grid levels\n\n    Returns\n    -------\n    numpy.ndarray"
  },
  {
    "code": "def to_msgpack(self, path_or_buf=None, encoding='utf-8', **kwargs):\n        from pandas.io import packers\n        return packers.to_msgpack(path_or_buf, self, encoding=encoding,\n                                  **kwargs)",
    "docstring": "Serialize object to input file path using msgpack format.\n\n        THIS IS AN EXPERIMENTAL LIBRARY and the storage format\n        may not be stable until a future release.\n\n        Parameters\n        ----------\n        path : string File path, buffer-like, or None\n            if None, return generated string\n        append : bool whether to append to an existing msgpack\n            (default is False)\n        compress : type of compressor (zlib or blosc), default to None (no\n            compression)"
  },
  {
    "code": "def fuller_scaling(target, DABo, To, Po, temperature='pore.temperature',\n                   pressure='pore.pressure'):\n    r\n    Ti = target[temperature]\n    Pi = target[pressure]\n    value = DABo*(Ti/To)**1.75*(Po/Pi)\n    return value",
    "docstring": "r\"\"\"\n    Uses Fuller model to adjust a diffusion coefficient for gases from\n    reference conditions to conditions of interest\n\n    Parameters\n    ----------\n    target : OpenPNM Object\n        The object for which these values are being calculated.  This\n        controls the length of the calculated array, and also provides\n        access to other necessary thermofluid properties.\n\n    DABo : float, array_like\n        Diffusion coefficient at reference conditions\n\n    Po, To : float, array_like\n        Pressure & temperature at reference conditions, respectively\n\n    pressure : string\n        The dictionary key containing the pressure values in Pascals (Pa)\n\n    temperature : string\n        The dictionary key containing the temperature values in Kelvin (K)"
  },
  {
    "code": "def pad(self, *args, **kwargs):\n        if not args:\n            start, end = self.padding\n        else:\n            start, end = args\n        if kwargs.pop('inplace', False):\n            new = self\n        else:\n            new = self.copy()\n        if kwargs:\n            raise TypeError(\"unexpected keyword argument %r\"\n                            % list(kwargs.keys())[0])\n        new.known = [(s[0]+start, s[1]+end) for s in self.known]\n        new.active = [(s[0]+start, s[1]+end) for s in self.active]\n        return new",
    "docstring": "Apply a padding to each segment in this `DataQualityFlag`\n\n        This method either takes no arguments, in which case the value of\n        the :attr:`~DataQualityFlag.padding` attribute will be used,\n        or two values representing the padding for the start and end of\n        each segment.\n\n        For both the `start` and `end` paddings, a positive value means\n        pad forward in time, so that a positive `start` pad or negative\n        `end` padding will contract a segment at one or both ends,\n        and vice-versa.\n\n        This method will apply the same padding to both the\n        `~DataQualityFlag.known` and `~DataQualityFlag.active` lists,\n        but will not :meth:`~DataQualityFlag.coalesce` the result.\n\n        Parameters\n        ----------\n        start : `float`\n            padding to apply to the start of the each segment\n        end : `float`\n            padding to apply to the end of each segment\n        inplace : `bool`, optional, default: `False`\n            modify this object in-place, default is `False`, i.e. return\n            a copy of the original object with padded segments\n\n        Returns\n        -------\n        paddedflag : `DataQualityFlag`\n            a view of the modified flag"
  },
  {
    "code": "def report_error_event(self, error_report):\n        logger = self.logging_client.logger(\"errors\")\n        logger.log_struct(error_report)",
    "docstring": "Report error payload.\n\n        :type error_report: dict\n        :param: error_report:\n            dict payload of the error report formatted according to\n            https://cloud.google.com/error-reporting/docs/formatting-error-messages\n            This object should be built using\n            :meth:~`google.cloud.error_reporting.client._build_error_report`"
  },
  {
    "code": "def import_module(modulename):\n    module = None\n    try:\n        module = importlib.import_module(modulename)\n    except ImportError:\n        if \".\" in modulename:\n            modules = modulename.split(\".\")\n            package = \".\".join(modules[1:len(modules)])\n            module = importlib.import_module(package)\n        else:\n            raise\n    return module",
    "docstring": "Static method for importing module modulename. Can handle relative imports as well.\n\n    :param modulename: Name of module to import. Can be relative\n    :return: imported module instance."
  },
  {
    "code": "def mechanism_indices(self, direction):\n        return {\n            Direction.CAUSE: self.effect_indices,\n            Direction.EFFECT: self.cause_indices\n        }[direction]",
    "docstring": "The indices of nodes in the mechanism system."
  },
  {
    "code": "def num_fmt(num, max_digits=None):\n    r\n    if num is None:\n        return 'None'\n    def num_in_mag(num, mag):\n        return mag > num and num > (-1 * mag)\n    if max_digits is None:\n        if num_in_mag(num, 1):\n            if num_in_mag(num, .1):\n                max_digits = 4\n            else:\n                max_digits = 3\n        else:\n            max_digits = 1\n    if util_type.is_float(num):\n        num_str = ('%.' + str(max_digits) + 'f') % num\n        num_str = num_str.rstrip('0').lstrip('0')\n        if num_str.startswith('.'):\n            num_str = '0' + num_str\n        if num_str.endswith('.'):\n            num_str = num_str + '0'\n        return num_str\n    elif util_type.is_int(num):\n        return int_comma_str(num)\n    else:\n        return '%r'",
    "docstring": "r\"\"\"\n    Weird function. Not very well written. Very special case-y\n\n    Args:\n        num (int or float):\n        max_digits (int):\n\n    Returns:\n        str:\n\n    CommandLine:\n        python -m utool.util_num --test-num_fmt\n\n    Example:\n        >>> # DISABLE_DOCTEST\n        >>> from utool.util_num import *  # NOQA\n        >>> # build test data\n        >>> num_list = [0, 0.0, 1.2, 1003232, 41431232., .0000000343, -.443243]\n        >>> max_digits = None\n        >>> # execute function\n        >>> result = [num_fmt(num, max_digits) for num in num_list]\n        >>> # verify results\n        >>> print(result)\n        ['0', '0.0', '1.2', '1,003,232', '41431232.0', '0.0', '-0.443']"
  },
  {
    "code": "def _point_plot_defaults(self, args, kwargs):\n        if args:\n            return args, kwargs\n        if 'ls' not in kwargs and 'linestyle' not in kwargs:\n            kwargs['linestyle'] = 'none'\n        if 'marker' not in kwargs:\n            kwargs['marker'] = 'o'\n        return args, kwargs",
    "docstring": "To avoid confusion for new users, this ensures that \"scattered\"\n        points are plotted by by `plot` instead of points joined by a line.\n\n        Parameters\n        ----------\n        args : tuple\n            Arguments representing additional parameters to be passed to\n            `self.plot`.\n        kwargs : dict\n            Keyword arguments representing additional parameters to be passed\n            to `self.plot`.\n\n        Returns\n        -------\n        Modified versions of `args` and `kwargs`."
  },
  {
    "code": "def extract_fields(self):\n        dm = IDataManager(self.context)\n        fieldnames = filter(lambda name: name not in self.ignore, self.keys)\n        out = dict()\n        for fieldname in fieldnames:\n            try:\n                fieldvalue = dm.json_data(fieldname)\n            except Unauthorized:\n                logger.debug(\"Skipping restricted field '%s'\" % fieldname)\n                continue\n            except ValueError:\n                logger.debug(\"Skipping invalid field '%s'\" % fieldname)\n                continue\n            out[fieldname] = api.to_json_value(self.context, fieldname, fieldvalue)\n        return out",
    "docstring": "Extract the given fieldnames from the object\n\n        :returns: Schema name/value mapping\n        :rtype: dict"
  },
  {
    "code": "def Get(self, flags, off):\n        N.enforce_number(off, N.UOffsetTFlags)\n        return flags.py_type(encode.Get(flags.packer_type, self.Bytes, off))",
    "docstring": "Get retrieves a value of the type specified by `flags`  at the\n        given offset."
  },
  {
    "code": "def assign_unassigned_members(self, group_category_id, sync=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"group_category_id\"] = group_category_id\r\n        if sync is not None:\r\n            data[\"sync\"] = sync\r\n        self.logger.debug(\"POST /api/v1/group_categories/{group_category_id}/assign_unassigned_members with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"POST\", \"/api/v1/group_categories/{group_category_id}/assign_unassigned_members\".format(**path), data=data, params=params, single_item=True)",
    "docstring": "Assign unassigned members.\r\n\r\n        Assign all unassigned members as evenly as possible among the existing\r\n        student groups."
  },
  {
    "code": "def reject(self, func):\n        return self._wrap(list(filter(lambda val: not func(val), self.obj)))",
    "docstring": "Return all the elements for which a truth test fails."
  },
  {
    "code": "def open_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS):\n        hProcess = win32.OpenProcess(dwDesiredAccess, win32.FALSE, self.dwProcessId)\n        try:\n            self.close_handle()\n        except Exception:\n            warnings.warn(\n                \"Failed to close process handle: %s\" % traceback.format_exc())\n        self.hProcess = hProcess",
    "docstring": "Opens a new handle to the process.\n\n        The new handle is stored in the L{hProcess} property.\n\n        @warn: Normally you should call L{get_handle} instead, since it's much\n            \"smarter\" and tries to reuse handles and merge access rights.\n\n        @type  dwDesiredAccess: int\n        @param dwDesiredAccess: Desired access rights.\n            Defaults to L{win32.PROCESS_ALL_ACCESS}.\n            See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx}\n\n        @raise WindowsError: It's not possible to open a handle to the process\n            with the requested access rights. This tipically happens because\n            the target process is a system process and the debugger is not\n            runnning with administrative rights."
  },
  {
    "code": "def ekopr(fname):\n    fname = stypes.stringToCharP(fname)\n    handle = ctypes.c_int()\n    libspice.ekopr_c(fname, ctypes.byref(handle))\n    return handle.value",
    "docstring": "Open an existing E-kernel file for reading.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopr_c.html\n\n    :param fname: Name of EK file.\n    :type fname: str\n    :return: Handle attached to EK file.\n    :rtype: int"
  },
  {
    "code": "def dumps(self, fd, **kwargs):\n        if 0 <= fd <= 2:\n            data = [self.stdin, self.stdout, self.stderr][fd].concretize(**kwargs)\n            if type(data) is list:\n                data = b''.join(data)\n            return data\n        return self.get_fd(fd).concretize(**kwargs)",
    "docstring": "Returns the concrete content for a file descriptor.\n\n        BACKWARD COMPATIBILITY: if you ask for file descriptors 0 1 or 2, it will return the data from stdin, stdout,\n        or stderr as a flat string.\n\n        :param fd:  A file descriptor.\n        :return:    The concrete content.\n        :rtype:     str"
  },
  {
    "code": "def _SerializeEntries(entries):\n  output = []\n  for python_format, wire_format, type_descriptor in entries:\n    if wire_format is None or (python_format and\n                               type_descriptor.IsDirty(python_format)):\n      wire_format = type_descriptor.ConvertToWireFormat(python_format)\n    precondition.AssertIterableType(wire_format, bytes)\n    output.extend(wire_format)\n  return b\"\".join(output)",
    "docstring": "Serializes given triplets of python and wire values and a descriptor."
  },
  {
    "code": "def add(self, template, resource, name=None):\n        if hasattr(resource, '_rhino_meta'):\n            route = Route(\n                    template, Resource(resource), name=name, ranges=self.ranges)\n        else:\n            route = Route(\n                    template, resource, name=name, ranges=self.ranges)\n        obj_id = id(resource)\n        if obj_id not in self._lookup:\n            self._lookup[obj_id] = route\n        if name is not None:\n            if name in self.named_routes:\n                raise InvalidArgumentError(\"A route named '%s' already exists in this %s object.\"\n                        % (name, self.__class__.__name__))\n            self.named_routes[name] = route\n        self.routes.append(route)",
    "docstring": "Add a route to a resource.\n\n        The optional `name` assigns a name to this route that can be used when\n        building URLs. The name must be unique within this Mapper object."
  },
  {
    "code": "def discovery_mdns(self):\n        logging.getLogger(\"zeroconf\").setLevel(logging.WARNING)\n        self.context.install_bundle(\"pelix.remote.discovery.mdns\").start()\n        with use_waiting_list(self.context) as ipopo:\n            ipopo.add(rs.FACTORY_DISCOVERY_ZEROCONF, \"pelix-discovery-zeroconf\")",
    "docstring": "Installs the mDNS discovery bundles and instantiates components"
  },
  {
    "code": "def associate_dhcp_options(self, dhcp_options_id, vpc_id):\n        params = {'DhcpOptionsId': dhcp_options_id,\n                  'VpcId' : vpc_id}\n        return self.get_status('AssociateDhcpOptions', params)",
    "docstring": "Associate a set of Dhcp Options with a VPC.\n\n        :type dhcp_options_id: str\n        :param dhcp_options_id: The ID of the Dhcp Options\n\n        :type vpc_id: str\n        :param vpc_id: The ID of the VPC.\n\n        :rtype: bool\n        :return: True if successful"
  },
  {
    "code": "def _outfp_write_with_check(self, outfp, data, enable_overwrite_check=True):\n        start = outfp.tell()\n        outfp.write(data)\n        if self._track_writes:\n            end = outfp.tell()\n            if end > self.pvd.space_size * self.pvd.logical_block_size():\n                raise pycdlibexception.PyCdlibInternalError('Wrote past the end of the ISO! (%d > %d)' % (end, self.pvd.space_size * self.pvd.logical_block_size()))\n            if enable_overwrite_check:\n                bisect.insort_left(self._write_check_list, self._WriteRange(start, end - 1))",
    "docstring": "Internal method to write data out to the output file descriptor,\n        ensuring that it doesn't go beyond the bounds of the ISO.\n\n        Parameters:\n         outfp - The file object to write to.\n         data - The actual data to write.\n         enable_overwrite_check - Whether to do overwrite checking if it is enabled.  Some pieces of code explicitly want to overwrite data, so this allows them to disable the checking.\n        Returns:\n         Nothing."
  },
  {
    "code": "def get_job_log_url(self, project, **params):\n        return self._get_json(self.JOB_LOG_URL_ENDPOINT, project,\n                              **params)",
    "docstring": "Gets job log url, filtered by parameters\n\n        :param project: project (repository name) to query data for\n        :param params: keyword arguments to filter results"
  },
  {
    "code": "def wol(mac, bcast='255.255.255.255', destport=9):\n    dest = salt.utils.network.mac_str_to_bytes(mac)\n    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n    sock.sendto(b'\\xff' * 6 + dest * 16, (bcast, int(destport)))\n    return True",
    "docstring": "Send a \"Magic Packet\" to wake up a Minion\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-run network.wol 08-00-27-13-69-77\n        salt-run network.wol 080027136977 255.255.255.255 7\n        salt-run network.wol 08:00:27:13:69:77 255.255.255.255 7"
  },
  {
    "code": "def diff_levenshtein(self, diffs):\n    levenshtein = 0\n    insertions = 0\n    deletions = 0\n    for (op, data) in diffs:\n      if op == self.DIFF_INSERT:\n        insertions += len(data)\n      elif op == self.DIFF_DELETE:\n        deletions += len(data)\n      elif op == self.DIFF_EQUAL:\n        levenshtein += max(insertions, deletions)\n        insertions = 0\n        deletions = 0\n    levenshtein += max(insertions, deletions)\n    return levenshtein",
    "docstring": "Compute the Levenshtein distance; the number of inserted, deleted or\n    substituted characters.\n\n    Args:\n      diffs: Array of diff tuples.\n\n    Returns:\n      Number of changes."
  },
  {
    "code": "def process_streamers(self):\n        in_progress = self._stream_manager.in_progress()\n        triggered = self.graph.check_streamers(blacklist=in_progress)\n        for streamer in triggered:\n            self._stream_manager.process_streamer(streamer, callback=self._handle_streamer_finished)",
    "docstring": "Check if any streamers should be handed to the stream manager."
  },
  {
    "code": "def _commit(self):\n        if not self.in_progress:\n            raise ValueError(_CANT_COMMIT)\n        commit_response = _commit_with_retry(self._client, self._write_pbs, self._id)\n        self._clean_up()\n        return list(commit_response.write_results)",
    "docstring": "Transactionally commit the changes accumulated.\n\n        Returns:\n            List[google.cloud.proto.firestore.v1beta1.\\\n                write_pb2.WriteResult, ...]: The write results corresponding\n            to the changes committed, returned in the same order as the\n            changes were applied to this transaction. A write result contains\n            an ``update_time`` field.\n\n        Raises:\n            ValueError: If no transaction is in progress."
  },
  {
    "code": "def geo_search(user_id, search_location):\n    url = \"https://api.twitter.com/1.1/geo/search.json\"\n    params =  {\"query\" : search_location }\n    response = make_twitter_request(url, user_id, params).json()\n    return response",
    "docstring": "Search for a location - free form"
  },
  {
    "code": "def get_properties(attributes):\n        return [key for key, value in six.iteritems(attributes)\n                if isinstance(value, property)]",
    "docstring": "Return tuple of names of defined properties.\n\n        :type attributes: dict\n        :rtype: list"
  },
  {
    "code": "def set_orient(self):\n        self.orient = RADTODEG(N.arctan2(self.cd12,self.cd22))",
    "docstring": "Return the computed orientation based on CD matrix."
  },
  {
    "code": "def run(self):\n        if self.status:\n            self.set_status('aborted')\n            raise LimpydJobsException('This worker run is already terminated')\n        self.set_status('starting')\n        self.start_date = datetime.utcnow()\n        if self.max_duration:\n            self.wanted_end_date = self.start_date + self.max_duration\n        must_stop = self.must_stop()\n        if not must_stop:\n            while not self.keys and not must_stop:\n                self.update_keys()\n                if not self.keys:\n                    sleep(self.fetch_priorities_delay)\n                must_stop = self.must_stop()\n            if not must_stop:\n                self.requeue_delayed_jobs()\n                self.run_started()\n                self._main_loop()\n        self.set_status('terminated')\n        self.end_date = datetime.utcnow()\n        self.run_ended()\n        if self.terminate_gracefuly:\n            self.stop_handling_end_signal()",
    "docstring": "The main method of the worker. Will ask redis for list items via\n        blocking calls, get jobs from them, try to execute these jobs, and end\n        when needed."
  },
  {
    "code": "def _unpack(c, tmp, package, version, git_url=None):\n    real_version = version[:]\n    source = None\n    if git_url:\n        pass\n    else:\n        cwd = os.getcwd()\n        print(\"Moving into temp dir %s\" % tmp)\n        os.chdir(tmp)\n        try:\n            flags = \"--download=. --build=build --no-use-wheel\"\n            cmd = \"pip install %s %s==%s\" % (flags, package, version)\n            c.run(cmd)\n            globs = []\n            globexpr = \"\"\n            for extension, opener in (\n                (\"zip\", \"unzip\"),\n                (\"tgz\", \"tar xzvf\"),\n                (\"tar.gz\", \"tar xzvf\"),\n            ):\n                globexpr = \"*.{0}\".format(extension)\n                globs = glob(globexpr)\n                if globs:\n                    break\n            archive = os.path.basename(globs[0])\n            source, _, _ = archive.rpartition(\".{0}\".format(extension))\n            c.run(\"{0} {1}\".format(opener, globexpr))\n        finally:\n            os.chdir(cwd)\n    return real_version, source",
    "docstring": "Download + unpack given package into temp dir ``tmp``.\n\n    Return ``(real_version, source)`` where ``real_version`` is the \"actual\"\n    version downloaded (e.g. if a Git master was indicated, it will be the SHA\n    of master HEAD) and ``source`` is the source directory (relative to\n    unpacked source) to import into ``<project>/vendor``."
  },
  {
    "code": "def setup_user_manager(app):\n    from flask_user import SQLAlchemyAdapter\n    from rio.models import User\n    init = dict(\n        db_adapter=SQLAlchemyAdapter(db, User),\n    )\n    user_manager.init_app(app, **init)",
    "docstring": "Setup flask-user manager."
  },
  {
    "code": "def make_scratch_dirs(file_mapping, dry_run=True):\n        scratch_dirs = {}\n        for value in file_mapping.values():\n            scratch_dirname = os.path.dirname(value)\n            scratch_dirs[scratch_dirname] = True\n        for scratch_dirname in scratch_dirs:\n            if dry_run:\n                print(\"mkdir -f %s\" % (scratch_dirname))\n            else:\n                try:\n                    os.makedirs(scratch_dirname)\n                except OSError:\n                    pass",
    "docstring": "Make any directories need in the scratch area"
  },
  {
    "code": "def refresh(self):\n        j = self.vera_request(id='sdata', output_format='json').json()\n        devices = j.get('devices')\n        for device_data in devices:\n            if device_data.get('id') == self.device_id:\n                self.update(device_data)",
    "docstring": "Refresh the dev_info data used by get_value.\n\n        Only needed if you're not using subscriptions."
  },
  {
    "code": "def _rescale(self, points):\n        return [(\n            x, self._scale_diff + (y - self._scale_min_2nd) * self._scale\n            if y is not None else None\n        ) for x, y in points]",
    "docstring": "Scale for secondary"
  },
  {
    "code": "def get_health_events(self, recipient):\n        if recipient not in self.addresses_events:\n            self.start_health_check(recipient)\n        return self.addresses_events[recipient]",
    "docstring": "Starts a healthcheck task for `recipient` and returns a\n        HealthEvents with locks to react on its current state."
  },
  {
    "code": "def preprocess(net, image):\n    return np.float32(np.rollaxis(image, 2)[::-1]) - net.transformer.mean[\"data\"]",
    "docstring": "convert to Caffe input image layout"
  },
  {
    "code": "def sort(self):\n        beams = [v for (_, v) in self.entries.items()]\n        sortedBeams = sorted(beams, reverse=True, key=lambda x: x.prTotal*x.prText)\n        return [x.labeling for x in sortedBeams]",
    "docstring": "return beam-labelings, sorted by probability"
  },
  {
    "code": "def principal_inertia_components(self):\n        components, vectors = inertia.principal_axis(self.moment_inertia)\n        self._cache['principal_inertia_vectors'] = vectors\n        return components",
    "docstring": "Return the principal components of inertia\n\n        Ordering corresponds to mesh.principal_inertia_vectors\n\n        Returns\n        ----------\n        components : (3,) float\n          Principal components of inertia"
  },
  {
    "code": "def _on_process_error(self, error):\n        if self is None:\n            return\n        if error not in PROCESS_ERROR_STRING:\n            error = -1\n        if not self._prevent_logs:\n            _logger().warning(PROCESS_ERROR_STRING[error])",
    "docstring": "Logs process error"
  },
  {
    "code": "def _is_ipv4_like(s):\n    parts = s.split('.')\n    if len(parts) != 4:\n        return False\n    for part in parts:\n        try:\n            int(part)\n        except ValueError:\n            return False\n    return True",
    "docstring": "Find if a string superficially looks like an IPv4 address.\n\n    AWS documentation plays it fast and loose with this; in other\n    regions, it seems like even non-valid IPv4 addresses (in\n    particular, ones that possess decimal numbers out of range for\n    IPv4) are rejected."
  },
  {
    "code": "def has_object_permission(self, request, view, obj):\n        user = request.user\n        if not user.is_superuser and not user.is_anonymous():\n            valid = False\n            try:\n                ct = ContentType.objects.get_for_model(obj)\n                fpm = FilterPermissionModel.objects.get(user=user,\n                                                        content_type=ct)\n                myq = QSerializer(base64=True).loads(fpm.filter)\n                try:\n                    myobj = obj.__class__.objects.filter(myq).distinct().get(pk=obj.pk)\n                    if myobj:\n                        valid = True\n                except ObjectDoesNotExist:\n                    valid = False\n            except ObjectDoesNotExist:\n                valid = True\n            finally:\n                return valid\n        else:\n            return True",
    "docstring": "check filter permissions"
  },
  {
    "code": "def sort_untl(self, sort_structure):\n        self.children.sort(key=lambda obj: sort_structure.index(obj.tag))",
    "docstring": "Sort the UNTL Python object by the index\n        of a sort structure pre-ordered list."
  },
  {
    "code": "def normalise_rows(matrix):\n    lengths = np.apply_along_axis(np.linalg.norm, 1, matrix)\n    if not (lengths > 0).all():\n        lengths[lengths == 0] = 1\n    return matrix / lengths[:, np.newaxis]",
    "docstring": "Scales all rows to length 1. Fails when row is 0-length, so it\n    leaves these unchanged"
  },
  {
    "code": "def upload(self, src_file_path, dst_file_name=None):\n        self._check_session()\n        status, data = self._rest.upload_file(\n            'files', src_file_path, dst_file_name)\n        return data",
    "docstring": "Upload the specified file to the server."
  },
  {
    "code": "def get_dep(self, name: str) -> str:\n        deps = self.meta[\"dependencies\"]\n        for d in deps:\n            if d[\"model\"] == name:\n                return d\n        raise KeyError(\"%s not found in %s.\" % (name, deps))",
    "docstring": "Return the uuid of the dependency identified with \"name\".\n\n        :param name:\n        :return: UUID"
  },
  {
    "code": "def returnIndexList(self, limit=False):\n        if limit==False:\n            return self.index_track\n        result = []\n        for i in range(limit):\n            if len(self.table)>i:\n                result.append(self.index_track[i])\n        return result",
    "docstring": "Return a list of integers that are list-index references to the\n        original list of dictionaries.\"\n\n        Example of use:\n\n        >>> test = [\n        ...    {\"name\": \"Jim\",   \"age\": 18, \"income\": 93000, \"order\": 2},\n        ...    {\"name\": \"Larry\", \"age\": 18,                  \"order\": 3},\n        ...    {\"name\": \"Joe\",   \"age\": 20, \"income\": 15000, \"order\": 1},\n        ...    {\"name\": \"Bill\",  \"age\": 19, \"income\": 29000, \"order\": 4},\n        ... ]\n        >>> print PLOD(test).returnIndexList()\n        [0, 1, 2, 3]\n        >>> print PLOD(test).sort(\"name\").returnIndexList()\n        [3, 0, 2, 1]\n        \n        :param limit:\n           A number limiting the quantity of entries to return. Defaults to\n           False, which means that the full list is returned.\n        :return:\n           A list of integers representing the original indices."
  },
  {
    "code": "def fetch_import_ref_restriction(self,):\n        inter = self.get_refobjinter()\n        restricted = self.status() not in (self.LOADED, self.UNLOADED)\n        return restricted or inter.fetch_action_restriction(self, 'import_reference')",
    "docstring": "Fetch whether importing the reference is restricted\n\n        :returns: True, if importing the reference is restricted\n        :rtype: :class:`bool`\n        :raises: None"
  },
  {
    "code": "def reverse_timezone(self, query, timeout=DEFAULT_SENTINEL):\n        ensure_pytz_is_installed()\n        try:\n            lat, lng = self._coerce_point_to_string(query).split(',')\n        except ValueError:\n            raise ValueError(\"Must be a coordinate pair or Point\")\n        params = {\n            \"lat\": lat,\n            \"lng\": lng,\n            \"username\": self.username,\n        }\n        url = \"?\".join((self.api_timezone, urlencode(params)))\n        logger.debug(\"%s.reverse_timezone: %s\", self.__class__.__name__, url)\n        return self._parse_json_timezone(\n            self._call_geocoder(url, timeout=timeout)\n        )",
    "docstring": "Find the timezone for a point in `query`.\n\n        GeoNames always returns a timezone: if the point being queried\n        doesn't have an assigned Olson timezone id, a ``pytz.FixedOffset``\n        timezone is used to produce the :class:`geopy.timezone.Timezone`.\n\n        .. versionadded:: 1.18.0\n\n        :param query: The coordinates for which you want a timezone.\n        :type query: :class:`geopy.point.Point`, list or tuple of (latitude,\n            longitude), or string as \"%(latitude)s, %(longitude)s\"\n\n        :param int timeout: Time, in seconds, to wait for the geocoding service\n            to respond before raising a :class:`geopy.exc.GeocoderTimedOut`\n            exception. Set this only if you wish to override, on this call\n            only, the value set during the geocoder's initialization.\n\n        :rtype: :class:`geopy.timezone.Timezone`"
  },
  {
    "code": "def _compute(self):\n        newstate = self._implicit_solver()\n        adjustment = {}\n        tendencies = {}\n        for name, var in self.state.items():\n            adjustment[name] = newstate[name] - var\n            tendencies[name] = adjustment[name] / self.timestep\n        self.adjustment = adjustment\n        self._update_diagnostics(newstate)\n        return tendencies",
    "docstring": "Computes the state variable tendencies in time for implicit processes.\n\n        To calculate the new state the :func:`_implicit_solver()` method is\n        called for daughter classes. This however returns the new state of the\n        variables, not just the tendencies. Therefore, the adjustment is\n        calculated which is the difference between the new and the old state\n        and stored in the object's attribute adjustment.\n\n        Calculating the new model states through solving the matrix problem\n        already includes the multiplication with the timestep. The derived\n        adjustment is divided by the timestep to calculate the implicit\n        subprocess tendencies, which can be handeled by the\n        :func:`~climlab.process.time_dependent_process.TimeDependentProcess.compute`\n        method of the parent\n        :class:`~climlab.process.time_dependent_process.TimeDependentProcess` class.\n\n        :ivar dict adjustment:  holding all state variables' adjustments\n                                of the implicit process which are the\n                                differences between the new states (which have\n                                been solved through matrix inversion) and the\n                                old states."
  },
  {
    "code": "def decompose_nfkd(text):\n    if text is None:\n        return None\n    if not hasattr(decompose_nfkd, '_tr'):\n        decompose_nfkd._tr = Transliterator.createInstance('Any-NFKD')\n    return decompose_nfkd._tr.transliterate(text)",
    "docstring": "Perform unicode compatibility decomposition.\n\n    This will replace some non-standard value representations in unicode and\n    normalise them, while also separating characters and their diacritics into\n    two separate codepoints."
  },
  {
    "code": "def scheduled(wait=False):\n    manager.run_scheduled()\n    while wait:\n        manager.run_scheduled()\n        time.sleep(settings.SCHEDULER_INTERVAL)",
    "docstring": "Run crawlers that are due."
  },
  {
    "code": "def logp_partial_gradient(self, variable, calculation_set=None):\n        if (calculation_set is None) or (self in calculation_set):\n            if not datatypes.is_continuous(variable):\n                return zeros(shape(variable.value))\n            if variable is self:\n                try:\n                    gradient_func = self._logp_partial_gradients['value']\n                except KeyError:\n                    raise NotImplementedError(\n                        repr(\n                            self) +\n                        \" has no gradient function for 'value'\")\n                gradient = np.reshape(\n                    gradient_func.get(\n                    ),\n                    np.shape(\n                        variable.value))\n            else:\n                gradient = builtins.sum(\n                    [self._pgradient(variable,\n                                     parameter,\n                                     value) for parameter,\n                     value in six.iteritems(self.parents)])\n            return gradient\n        else:\n            return 0",
    "docstring": "Calculates the partial gradient of the posterior of self with respect to variable.\n        Returns zero if self is not in calculation_set."
  },
  {
    "code": "def pay(self, predecessor):\n        assert predecessor is None or isinstance(predecessor, MatchSet)\n        if predecessor is not None:\n            expectation = self._algorithm.get_future_expectation(self)\n            predecessor.payoff += expectation",
    "docstring": "If the predecessor is not None, gives the appropriate amount of\n        payoff to the predecessor in payment for its contribution to this\n        match set's expected future payoff. The predecessor argument should\n        be either None or a MatchSet instance whose selected action led\n        directly to this match set's situation.\n\n        Usage:\n            match_set = model.match(situation)\n            match_set.pay(previous_match_set)\n\n        Arguments:\n            predecessor: The MatchSet instance which was produced by the\n                same classifier set in response to the immediately\n                preceding situation, or None if this is the first situation\n                in the scenario.\n        Return: None"
  },
  {
    "code": "def register_factory(self, key, factory=_sentinel, scope=NoneScope, allow_overwrite=False):\n        if factory is _sentinel:\n            return functools.partial(self.register_factory, key, scope=scope, allow_overwrite=allow_overwrite)\n        if not allow_overwrite and key in self._providers:\n            raise KeyError(\"Key %s already exists\" % key)\n        provider = self.provider(factory, scope)\n        self._providers[key] = provider\n        return factory",
    "docstring": "Creates and registers a provider using the given key, factory, and scope.\n        Can also be used as a decorator.\n\n        :param key: Provider key\n        :type key:  object\n        :param factory: Factory callable\n        :type factory: callable\n        :param scope: Scope key, factory, or instance\n        :type scope: object or callable\n        :return: Factory (or None if we're creating a provider without a factory)\n        :rtype: callable or None"
  },
  {
    "code": "def source(self, fields=None, **kwargs):\n        s = self._clone()\n        if fields and kwargs:\n            raise ValueError(\"You cannot specify fields and kwargs at the same time.\")\n        if fields is not None:\n            s._source = fields\n            return s\n        if kwargs and not isinstance(s._source, dict):\n            s._source = {}\n        for key, value in kwargs.items():\n            if value is None:\n                try:\n                    del s._source[key]\n                except KeyError:\n                    pass\n            else:\n                s._source[key] = value\n        return s",
    "docstring": "Selectively control how the _source field is returned.\n\n        :arg fields: wildcard string, array of wildcards, or dictionary of includes and excludes\n\n        If ``fields`` is None, the entire document will be returned for\n        each hit.  If fields is a dictionary with keys of 'include' and/or\n        'exclude' the fields will be either included or excluded appropriately.\n\n        Calling this multiple times with the same named parameter will override the\n        previous values with the new ones.\n\n        Example::\n\n            s = Search()\n            s = s.source(include=['obj1.*'], exclude=[\"*.description\"])\n\n            s = Search()\n            s = s.source(include=['obj1.*']).source(exclude=[\"*.description\"])"
  },
  {
    "code": "def getMemoryStats(self):\n        if self._statusxml is None:\n            self.initStats()\n        node = self._statusxml.find('jvm/memory')\n        memstats = {}\n        if node is not None:\n            for (key,val) in node.items():\n                memstats[key] = util.parse_value(val)\n        return memstats",
    "docstring": "Return JVM Memory Stats for Apache Tomcat Server.\n        \n        @return: Dictionary of memory utilization stats."
  },
  {
    "code": "def generate_csv(src, out):\n    writer = UnicodeWriter(open(out, 'wb'), delimiter=';')\n    writer.writerow(('Reference ID', 'Created', 'Origin', 'Subject'))\n    for cable in cables_from_source(src, predicate=pred.origin_filter(pred.origin_germany)):\n        writer.writerow((cable.reference_id, cable.created, cable.origin, titlefy(cable.subject)))",
    "docstring": "\\\n    Walks through `src` and generates the CSV file `out`"
  },
  {
    "code": "def before_request(request, tracer=None):\n    if tracer is None:\n        tracer = opentracing.tracer\n    tags_dict = {\n        tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER,\n        tags.HTTP_URL: request.full_url,\n    }\n    remote_ip = request.remote_ip\n    if remote_ip:\n        tags_dict[tags.PEER_HOST_IPV4] = remote_ip\n    caller_name = request.caller_name\n    if caller_name:\n        tags_dict[tags.PEER_SERVICE] = caller_name\n    remote_port = request.remote_port\n    if remote_port:\n        tags_dict[tags.PEER_PORT] = remote_port\n    operation = request.operation\n    try:\n        carrier = {}\n        for key, value in six.iteritems(request.headers):\n            carrier[key] = value\n        parent_ctx = tracer.extract(\n            format=Format.HTTP_HEADERS, carrier=carrier\n        )\n    except Exception as e:\n        logging.exception('trace extract failed: %s' % e)\n        parent_ctx = None\n    span = tracer.start_span(\n        operation_name=operation,\n        child_of=parent_ctx,\n        tags=tags_dict)\n    return span",
    "docstring": "Attempts to extract a tracing span from incoming request.\n    If no tracing context is passed in the headers, or the data\n    cannot be parsed, a new root span is started.\n\n    :param request: HTTP request with `.headers` property exposed\n        that satisfies a regular dictionary interface\n    :param tracer: optional tracer instance to use. If not specified\n        the global opentracing.tracer will be used.\n    :return: returns a new, already started span."
  },
  {
    "code": "def _sections_to_variance_sections(self, sections_over_time):\n    variance_sections = []\n    for i in range(len(sections_over_time[0])):\n      time_sections = [sections[i] for sections in sections_over_time]\n      variance = np.var(time_sections, axis=0)\n      variance_sections.append(variance)\n    return variance_sections",
    "docstring": "Computes the variance of corresponding sections over time.\n\n    Returns:\n      a list of np arrays."
  },
  {
    "code": "def add_locations(self, locations):\n        if isinstance(locations, (str, ustr)):\n            self._add_from_str(locations)\n        elif isinstance(locations, (list, tuple)):\n            self._add_from_list(locations)",
    "docstring": "Add extra locations to AstralGeocoder.\n\n        Extra locations can be\n\n        * A single string containing one or more locations separated by a newline.\n        * A list of strings\n        * A list of lists/tuples that are passed to a :class:`Location` constructor"
  },
  {
    "code": "def copy_node(node):\n  if not isinstance(node, gast.AST):\n    return [copy_node(n) for n in node]\n  new_node = copy.deepcopy(node)\n  setattr(new_node, anno.ANNOTATION_FIELD,\n          getattr(node, anno.ANNOTATION_FIELD, {}).copy())\n  return new_node",
    "docstring": "Copy a node but keep its annotations intact."
  },
  {
    "code": "def mutations_batcher(self, flush_count=FLUSH_COUNT, max_row_bytes=MAX_ROW_BYTES):\n        return MutationsBatcher(self, flush_count, max_row_bytes)",
    "docstring": "Factory to create a mutation batcher associated with this instance.\n\n        For example:\n\n        .. literalinclude:: snippets_table.py\n            :start-after: [START bigtable_mutations_batcher]\n            :end-before: [END bigtable_mutations_batcher]\n\n        :type table: class\n        :param table: class:`~google.cloud.bigtable.table.Table`.\n\n        :type flush_count: int\n        :param flush_count: (Optional) Maximum number of rows per batch. If it\n                reaches the max number of rows it calls finish_batch() to\n                mutate the current row batch. Default is FLUSH_COUNT (1000\n                rows).\n\n        :type max_row_bytes: int\n        :param max_row_bytes: (Optional) Max number of row mutations size to\n                flush. If it reaches the max number of row mutations size it\n                calls finish_batch() to mutate the current row batch.\n                Default is MAX_ROW_BYTES (5 MB)."
  },
  {
    "code": "def create_node_rating_counts_settings(sender, **kwargs):\n    created = kwargs['created']\n    node = kwargs['instance']\n    if created:\n        create_related_object.delay(NodeRatingCount, {'node': node})\n        create_related_object.delay(NodeParticipationSettings, {'node': node})",
    "docstring": "create node rating count and settings"
  },
  {
    "code": "def G(self, ID, lat, lon):\n        eqM = utils.eqCoords(lon, lat)\n        eqZ = eqM\n        if lat != 0:\n            eqZ = utils.eqCoords(lon, 0)\n        return {\n            'id': ID,\n            'lat': lat,\n            'lon': lon,\n            'ra': eqM[0],\n            'decl': eqM[1],\n            'raZ': eqZ[0],\n            'declZ': eqZ[1],\n        }",
    "docstring": "Creates a generic entry for an object."
  },
  {
    "code": "def _cb_inform_sensor_status(self, msg):\n        timestamp = msg.arguments[0]\n        num_sensors = int(msg.arguments[1])\n        assert len(msg.arguments) == 2 + num_sensors * 3\n        for n in xrange(num_sensors):\n            name = msg.arguments[2 + n * 3]\n            status = msg.arguments[3 + n * 3]\n            value = msg.arguments[4 + n * 3]\n            self.update_sensor(name, timestamp, status, value)",
    "docstring": "Update received for an sensor."
  },
  {
    "code": "def get_fd(file_or_fd, default=None):\n    fd = file_or_fd\n    if fd is None:\n        fd = default\n    if hasattr(fd, \"fileno\"):\n        fd = fd.fileno()\n    return fd",
    "docstring": "Helper function for getting a file descriptor."
  },
  {
    "code": "def add_widget(self, widget, column=0):\n        if self._frame is None:\n            raise RuntimeError(\"You must add the Layout to the Frame before you can add a Widget.\")\n        self._columns[column].append(widget)\n        widget.register_frame(self._frame)\n        if widget.name in self._frame.data:\n            widget.value = self._frame.data[widget.name]",
    "docstring": "Add a widget to this Layout.\n\n        If you are adding this Widget to the Layout dynamically after starting to play the Scene,\n        don't forget to ensure that the value is explicitly set before the next update.\n\n        :param widget: The widget to be added.\n        :param column: The column within the widget for this widget.  Defaults to zero."
  },
  {
    "code": "def generate_source_image(source_file, processor_options, generators=None,\n                          fail_silently=True):\n    processor_options = ThumbnailOptions(processor_options)\n    was_closed = getattr(source_file, 'closed', False)\n    if generators is None:\n        generators = [\n            utils.dynamic_import(name)\n            for name in settings.THUMBNAIL_SOURCE_GENERATORS]\n    exceptions = []\n    try:\n        for generator in generators:\n            source = source_file\n            try:\n                source.open()\n            except Exception:\n                try:\n                    source.seek(0)\n                except Exception:\n                    source = None\n            try:\n                image = generator(source, **processor_options)\n            except Exception as e:\n                if not fail_silently:\n                    if len(generators) == 1:\n                        raise\n                    exceptions.append(e)\n                image = None\n            if image:\n                return image\n    finally:\n        if was_closed:\n            try:\n                source_file.close()\n            except Exception:\n                pass\n    if exceptions and not fail_silently:\n        raise NoSourceGenerator(*exceptions)",
    "docstring": "Processes a source ``File`` through a series of source generators, stopping\n    once a generator returns an image.\n\n    The return value is this image instance or ``None`` if no generators\n    return an image.\n\n    If the source file cannot be opened, it will be set to ``None`` and still\n    passed to the generators."
  },
  {
    "code": "def set_element(self, row, col, value):\n        javabridge.call(\n            self.jobject, \"setElement\", \"(IID)V\", row, col, value)",
    "docstring": "Sets the float value at the specified location.\n\n        :param row: the 0-based index of the row\n        :type row: int\n        :param col: the 0-based index of the column\n        :type col: int\n        :param value: the float value for that cell\n        :type value: float"
  },
  {
    "code": "def update(self, **kwargs):\n        data = kwargs.get('data')\n        if data is not None:\n            if (util.pd and isinstance(data, util.pd.DataFrame) and\n                list(data.columns) != list(self.data.columns) and self._index):\n                data = data.reset_index()\n            self.verify(data)\n            kwargs['data'] = self._concat(data)\n            self._count += 1\n        super(Buffer, self).update(**kwargs)",
    "docstring": "Overrides update to concatenate streamed data up to defined length."
  },
  {
    "code": "def _set_autocommit(connection):\n        if hasattr(connection.connection, \"autocommit\"):\n            if callable(connection.connection.autocommit):\n                connection.connection.autocommit(True)\n            else:\n                connection.connection.autocommit = True\n        elif hasattr(connection.connection, \"set_isolation_level\"):\n            connection.connection.set_isolation_level(0)",
    "docstring": "Make sure a connection is in autocommit mode."
  },
  {
    "code": "def string_to_datetime(self, obj):\n        if isinstance(obj, six.string_types) and len(obj) == 19:\n            try:\n                return datetime.strptime(obj, \"%Y-%m-%dT%H:%M:%S\")\n            except ValueError:\n                pass\n        if isinstance(obj, six.string_types) and len(obj) > 19:\n            try:\n                return datetime.strptime(obj, \"%Y-%m-%dT%H:%M:%S.%f\")\n            except ValueError:\n                pass\n        if isinstance(obj, six.string_types) and len(obj) == 10:\n            try:\n                return datetime.strptime(obj, \"%Y-%m-%d\")\n            except ValueError:\n                pass\n        return obj",
    "docstring": "Decode a datetime string to a datetime object"
  },
  {
    "code": "async def get_wallet_record(wallet_handle: int,\n                            type_: str,\n                            id: str,\n                            options_json: str) -> str:\n    logger = logging.getLogger(__name__)\n    logger.debug(\"get_wallet_record: >>> wallet_handle: %r, type_: %r, id: %r, options_json: %r\",\n                 wallet_handle,\n                 type_,\n                 id,\n                 options_json)\n    if not hasattr(get_wallet_record, \"cb\"):\n        logger.debug(\"get_wallet_record: Creating callback\")\n        get_wallet_record.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_char_p))\n    c_wallet_handle = c_int32(wallet_handle)\n    c_type = c_char_p(type_.encode('utf-8'))\n    c_id = c_char_p(id.encode('utf-8'))\n    c_options_json = c_char_p(options_json.encode('utf-8'))\n    wallet_record = await do_call('indy_get_wallet_record',\n                                  c_wallet_handle,\n                                  c_type,\n                                  c_id,\n                                  c_options_json,\n                                  get_wallet_record.cb)\n    res = wallet_record.decode()\n    logger.debug(\"get_wallet_record: <<< res: %r\", res)\n    return res",
    "docstring": "Get an wallet record by id\n\n    :param wallet_handle: wallet handler (created by open_wallet).\n    :param type_: allows to separate different record types collections\n    :param id: the id of record\n    :param options_json: //TODO: FIXME: Think about replacing by bitmask\n      {\n        retrieveType: (optional, false by default) Retrieve record type,\n        retrieveValue: (optional, true by default) Retrieve record value,\n        retrieveTags: (optional, true by default) Retrieve record tags\n      }\n    :return: wallet record json:\n     {\n       id: \"Some id\",\n       type: \"Some type\", // present only if retrieveType set to true\n       value: \"Some value\", // present only if retrieveValue set to true\n       tags: <tags json>, // present only if retrieveTags set to true\n     }"
  },
  {
    "code": "def _handle_exists(self, node, scope, ctxt, stream):\n        res = fields.Int()\n        try:\n            self._handle_node(node.expr, scope, ctxt, stream)\n            res._pfp__set_value(1)\n        except AttributeError:\n            res._pfp__set_value(0)\n        return res",
    "docstring": "Handle the exists unary operator\n\n        :node: TODO\n        :scope: TODO\n        :ctxt: TODO\n        :stream: TODO\n        :returns: TODO"
  },
  {
    "code": "def query_echo(cls, request,\n                   foo: (Ptypes.query, String('A query parameter'))) -> [\n            (200, 'Ok', String)]:\n        log.info('Echoing query param, value is: {}'.format(foo))\n        for i in range(randint(0, MAX_LOOP_DURATION)):\n            yield\n        msg = 'The value sent was: {}'.format(foo)\n        Respond(200, msg)",
    "docstring": "Echo the query parameter."
  },
  {
    "code": "def validate_args(args):\n    if not args.minutes and not args.start_time:\n        print(\"Error: missing --minutes or --start-time\")\n        return False\n    if args.minutes and args.start_time:\n        print(\"Error: --minutes shouldn't be specified if --start-time is used\")\n        return False\n    if args.end_time and not args.start_time:\n        print(\"Error: --end-time can't be used without --start-time\")\n        return False\n    if args.minutes and args.minutes <= 0:\n        print(\"Error: --minutes must be > 0\")\n        return False\n    if args.start_time and not TIME_FORMAT_REGEX.match(args.start_time):\n        print(\"Error: --start-time format is not valid\")\n        print(\"Example format: '2015-11-26 11:00:00'\")\n        return False\n    if args.end_time and not TIME_FORMAT_REGEX.match(args.end_time):\n        print(\"Error: --end-time format is not valid\")\n        print(\"Example format: '2015-11-26 11:00:00'\")\n        return False\n    if args.batch_size <= 0:\n        print(\"Error: --batch-size must be > 0\")\n        return False\n    return True",
    "docstring": "Basic option validation. Returns False if the options are not valid,\n    True otherwise.\n\n    :param args: the command line options\n    :type args: map\n    :param brokers_num: the number of brokers"
  },
  {
    "code": "def use_comparative_composition_view(self):\n        self._object_views['composition'] = COMPARATIVE\n        for session in self._get_provider_sessions():\n            try:\n                session.use_comparative_composition_view()\n            except AttributeError:\n                pass",
    "docstring": "Pass through to provider CompositionLookupSession.use_comparative_composition_view"
  },
  {
    "code": "def detect_terminal(_environ=os.environ):\n    if _environ.get('TMUX'):\n        return 'tmux'\n    elif subdict_by_key_prefix(_environ, 'BYOBU'):\n        return 'byobu'\n    elif _environ.get('TERM').startswith('screen'):\n        return _environ['TERM']\n    elif _environ.get('COLORTERM'):\n        return _environ['COLORTERM']\n    else:\n        return _environ.get('TERM')",
    "docstring": "Detect \"terminal\" you are using.\n\n    First, this function checks if you are in tmux, byobu, or screen.\n    If not it uses $COLORTERM [#]_ if defined and fallbacks to $TERM.\n\n    .. [#] So, if you are in Gnome Terminal you have \"gnome-terminal\"\n       instead of \"xterm-color\"\"."
  },
  {
    "code": "def get_agent(msg):\n    agent = msg['msg']['agent']\n    if isinstance(agent, list):\n        agent = agent[0]\n    return agent",
    "docstring": "Handy hack to handle legacy messages where 'agent' was a list."
  },
  {
    "code": "def getManagedObjects(self, objectPath):\n        d = {}\n        for p in sorted(self.exports.keys()):\n            if not p.startswith(objectPath) or p == objectPath:\n                continue\n            o = self.exports[p]\n            i = {}\n            d[p] = i\n            for iface in o.getInterfaces():\n                i[iface.name] = o.getAllProperties(iface.name)\n        return d",
    "docstring": "Returns a Python dictionary containing the reply content for\n        org.freedesktop.DBus.ObjectManager.GetManagedObjects"
  },
  {
    "code": "def get_docstring(obj):\n    docstring = getdoc(obj, allow_inherited=True)\n    if docstring is None:\n        logger = getLogger(__name__)\n        logger.warning(\"Object %s doesn't have a docstring.\", obj)\n        docstring = 'Undocumented'\n    return prepare_docstring(docstring, ignore=1)",
    "docstring": "Extract the docstring from an object as individual lines.\n\n    Parameters\n    ----------\n    obj : object\n        The Python object (class, function or method) to extract docstrings\n        from.\n\n    Returns\n    -------\n    lines : `list` of `str`\n        Individual docstring lines with common indentation removed, and\n        newline characters stripped.\n\n    Notes\n    -----\n    If the object does not have a docstring, a docstring with the content\n    ``\"Undocumented.\"`` is created."
  },
  {
    "code": "def _normalize_overlap(overlap, window, nfft, samp, method='welch'):\n    if method == 'bartlett':\n        return 0\n    if overlap is None and isinstance(window, string_types):\n        return recommended_overlap(window, nfft)\n    if overlap is None:\n        return 0\n    return seconds_to_samples(overlap, samp)",
    "docstring": "Normalise an overlap in physical units to a number of samples\n\n    Parameters\n    ----------\n    overlap : `float`, `Quantity`, `None`\n        the overlap in some physical unit (seconds)\n\n    window : `str`\n        the name of the window function that will be used, only used\n        if `overlap=None` is given\n\n    nfft : `int`\n        the number of samples that will be used in the fast Fourier\n        transform\n\n    samp : `Quantity`\n        the sampling rate (Hz) of the data that will be transformed\n\n    method : `str`\n        the name of the averaging method, default: `'welch'`, only\n        used to return `0` for `'bartlett'` averaging\n\n    Returns\n    -------\n    noverlap : `int`\n        the number of samples to be be used for the overlap"
  },
  {
    "code": "def make_label(self, path):\n        from datetime import datetime\n        from StringIO import StringIO\n        path = path.lstrip(\"/\")\n        bucket, label = path.split(\"/\", 1)\n        bucket = self.ofs._require_bucket(bucket)\n        key = self.ofs._get_key(bucket, label)\n        if key is None:\n            key = bucket.new_key(label)\n            self.ofs._update_key_metadata(key, { '_creation_time': str(datetime.utcnow()) })\n            key.set_contents_from_file(StringIO(''))\n        key.close()",
    "docstring": "this borrows too much from the internals of ofs\n        maybe expose different parts of the api?"
  },
  {
    "code": "def setup_arrow_buttons(self):\n        vsb = self.scrollarea.verticalScrollBar()\n        style = vsb.style()\n        opt = QStyleOptionSlider()\n        vsb.initStyleOption(opt)\n        vsb_up_arrow = style.subControlRect(\n                QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarAddLine, self)\n        up_btn = up_btn = QPushButton(icon=ima.icon('last_edit_location'))\n        up_btn.setFlat(True)\n        up_btn.setFixedHeight(vsb_up_arrow.size().height())\n        up_btn.clicked.connect(self.go_up)\n        down_btn = QPushButton(icon=ima.icon('folding.arrow_down_on'))\n        down_btn.setFlat(True)\n        down_btn.setFixedHeight(vsb_up_arrow.size().height())\n        down_btn.clicked.connect(self.go_down)\n        return up_btn, down_btn",
    "docstring": "Setup the up and down arrow buttons that are placed at the top and\n        bottom of the scrollarea."
  },
  {
    "code": "def last_week_of_year(cls, year):\n        if year == cls.max.year:\n            return cls.max\n        return cls(year+1, 0)",
    "docstring": "Return the last week of the given year.\n        This week with either have week-number 52 or 53.\n\n        This will be the same as Week(year+1, 0), but will even work for\n        year 9999 where this expression would overflow.\n\n        The first week of a given year is simply Week(year, 1), so there\n        is no dedicated classmethod for that."
  },
  {
    "code": "def relative_humidity_from_dewpoint(temperature, dewpt):\n    r\n    e = saturation_vapor_pressure(dewpt)\n    e_s = saturation_vapor_pressure(temperature)\n    return (e / e_s)",
    "docstring": "r\"\"\"Calculate the relative humidity.\n\n    Uses temperature and dewpoint in celsius to calculate relative\n    humidity using the ratio of vapor pressure to saturation vapor pressures.\n\n    Parameters\n    ----------\n    temperature : `pint.Quantity`\n        The temperature\n    dew point : `pint.Quantity`\n        The dew point temperature\n\n    Returns\n    -------\n    `pint.Quantity`\n        The relative humidity\n\n    See Also\n    --------\n    saturation_vapor_pressure"
  },
  {
    "code": "def cleanup(self):\n        if self.process is None:\n            return\n        if self.process.poll() is None:\n            log.info(\"Sending TERM to %d\", self.process.pid)\n            self.process.terminate()\n            start = time.clock()\n            while time.clock() - start < 1.0:\n                time.sleep(0.05)\n                if self.process.poll() is not None:\n                    break\n            else:\n                log.info(\"Sending KILL to %d\", self.process.pid)\n                self.process.kill()\n        assert self.process.poll() is not None",
    "docstring": "Clean up, making sure the process is stopped before we pack up and go home."
  },
  {
    "code": "def _stream_search(self, query):\n        for doc in self.solr.search(query, rows=100000000):\n            if self.unique_key != \"_id\":\n                doc[\"_id\"] = doc.pop(self.unique_key)\n            yield doc",
    "docstring": "Helper method for iterating over Solr search results."
  },
  {
    "code": "def qsize(self):\n        if not self.connected:\n            raise QueueNotConnectedError(\"Queue is not Connected\")\n        try:\n            size = self.__db.llen(self._key)\n        except redis.ConnectionError as e:\n            raise redis.ConnectionError(repr(e))\n        return size",
    "docstring": "Returns the number of items currently in the queue\n\n        :return: Integer containing size of the queue\n        :exception: ConnectionError if queue is not connected"
  },
  {
    "code": "def p(i, sample_size, weights):\n        weight_i = weights[i]\n        weights_sum = sum(weights)\n        other_weights = list(weights)\n        del other_weights[i]\n        probability_of_i = 0\n        for picks in range(0, sample_size):\n            permutations = list(itertools.permutations(other_weights, picks))\n            permutation_probabilities = []\n            for permutation in permutations:\n                pick_probabilities = []\n                pick_weight_sum = weights_sum\n                for pick in permutation:\n                    pick_probabilities.append(pick / pick_weight_sum)\n                    pick_weight_sum -= pick\n                pick_probabilities += [weight_i / pick_weight_sum]\n                permutation_probability = reduce(\n                    lambda x, y: x * y, pick_probabilities\n                    )\n                permutation_probabilities.append(permutation_probability)\n            probability_of_i += sum(permutation_probabilities)\n        return probability_of_i",
    "docstring": "Given a weighted set and sample size return the probabilty that the\n        weight `i` will be present in the sample.\n\n        Created to test the output of the `SomeOf` maker class. The math was\n        provided by Andy Blackshaw - thank you dad :)"
  },
  {
    "code": "def _order_by_is_valid_or_none(self, params):\n        if not \"order_by\" in params or not params[\"order_by\"]:\n            return True\n        def _order_by_dict_is_not_well_formed(d):\n            if not isinstance(d, dict):\n                return True\n            if \"property_name\" in d and d[\"property_name\"]:\n                if \"direction\" in d and not direction.is_valid_direction(d[\"direction\"]):\n                    return True\n                for k in d:\n                    if k != \"property_name\" and k != \"direction\":\n                        return True\n                return False\n            return True\n        order_by_list = json.loads(params[\"order_by\"])\n        for order_by in order_by_list:\n            if _order_by_dict_is_not_well_formed(order_by):\n                return False\n        if not \"group_by\" in params or not params[\"group_by\"]:\n            return False\n        return True",
    "docstring": "Validates that a given order_by has proper syntax.\n\n        :param params: Query params.\n        :return: Returns True if either no order_by is present, or if the order_by is well-formed."
  },
  {
    "code": "def after_websocket(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:\n        handler = ensure_coroutine(func)\n        self.after_websocket_funcs[name].append(handler)\n        return func",
    "docstring": "Add an after websocket function.\n\n        This is designed to be used as a decorator. An example usage,\n\n        .. code-block:: python\n\n            @app.after_websocket\n            def func(response):\n                return response\n\n        Arguments:\n            func: The after websocket function itself.\n            name: Optional blueprint key name."
  },
  {
    "code": "def get_words(data):\n    words = re.findall(r\"\\w+\", data)\n    LOGGER.debug(\"> Words: '{0}'\".format(\", \".join(words)))\n    return words",
    "docstring": "Extracts the words from given string.\n\n    Usage::\n\n        >>> get_words(\"Users are: John Doe, Jane Doe, Z6PO.\")\n        [u'Users', u'are', u'John', u'Doe', u'Jane', u'Doe', u'Z6PO']\n\n    :param data: Data to extract words from.\n    :type data: unicode\n    :return: Words.\n    :rtype: list"
  },
  {
    "code": "def cache_key_exist(self, key):\n        key_exist = True if cache.get(key) else False\n        status = 200 if key_exist else 404\n        return json_success(json.dumps({'key_exist': key_exist}),\n                            status=status)",
    "docstring": "Returns if a key from cache exist"
  },
  {
    "code": "def cached_read(self, kind):\n        if not kind in self.cache:\n            self.pull_stats(kind)\n        if self.epochnow() - self.cache[kind]['lastcall'] > self.cache_timeout:\n            self.pull_stats(kind)\n        return self.cache[kind]['lastvalue']",
    "docstring": "Cache stats calls to prevent hammering the API"
  },
  {
    "code": "async def post(self, url_path: str, params: dict = None, rtype: str = RESPONSE_JSON, schema: dict = None) -> Any:\n        if params is None:\n            params = dict()\n        client = API(self.endpoint.conn_handler(self.session, self.proxy))\n        response = await client.requests_post(url_path, **params)\n        if schema is not None:\n            await parse_response(response, schema)\n        if rtype == RESPONSE_AIOHTTP:\n            return response\n        elif rtype == RESPONSE_TEXT:\n            return await response.text()\n        elif rtype == RESPONSE_JSON:\n            return await response.json()",
    "docstring": "POST request on self.endpoint + url_path\n\n        :param url_path: Url encoded path following the endpoint\n        :param params: Url query string parameters dictionary\n        :param rtype: Response type\n        :param schema: Json Schema to validate response (optional, default None)\n        :return:"
  },
  {
    "code": "def _prep_fields_param(fields):\n    store_samples = False\n    if fields is None:\n        return True, None\n    if isinstance(fields, str):\n        fields = [fields]\n    else:\n        fields = list(fields)\n    if 'samples' in fields:\n        fields.remove('samples')\n        store_samples = True\n    elif '*' in fields:\n        store_samples = True\n    return store_samples, fields",
    "docstring": "Prepare the `fields` parameter, and determine whether or not to store samples."
  },
  {
    "code": "def generous_parse_uri(uri):\n    parse_result = urlparse(uri)\n    if parse_result.scheme == '':\n        abspath = os.path.abspath(parse_result.path)\n        if IS_WINDOWS:\n            abspath = windows_to_unix_path(abspath)\n        fixed_uri = \"file://{}\".format(abspath)\n        parse_result = urlparse(fixed_uri)\n    return parse_result",
    "docstring": "Return a urlparse.ParseResult object with the results of parsing the\n    given URI. This has the same properties as the result of parse_uri.\n\n    When passed a relative path, it determines the absolute path, sets the\n    scheme to file, the netloc to localhost and returns a parse of the result."
  },
  {
    "code": "def main(args=None):\n    try:\n        from psyplot_gui import get_parser as _get_parser\n    except ImportError:\n        logger.debug('Failed to import gui', exc_info=True)\n        parser = get_parser(create=False)\n        parser.update_arg('output', required=True)\n        parser.create_arguments()\n        parser.parse2func(args)\n    else:\n        parser = _get_parser(create=False)\n        parser.create_arguments()\n        parser.parse_known2func(args)",
    "docstring": "Main function for usage of psyplot from the command line\n\n    This function creates a parser that parses command lines to the\n    :func:`make_plot` functions or (if the ``psyplot_gui`` module is\n    present, to the :func:`psyplot_gui.start_app` function)\n\n    Returns\n    -------\n    psyplot.parser.FuncArgParser\n        The parser that has been used from the command line"
  },
  {
    "code": "def remove_user(self, group, username):\n        try:\n            self.lookup_id(group)\n        except ldap_tools.exceptions.InvalidResult as err:\n            raise err from None\n        operation = {'memberUid': [(ldap3.MODIFY_DELETE, [username])]}\n        self.client.modify(self.__distinguished_name(group), operation)",
    "docstring": "Remove a user from the specified LDAP group.\n\n        Args:\n            group: Name of group to update\n            username: Username of user to remove\n\n        Raises:\n            ldap_tools.exceptions.InvalidResult:\n                Results of the query were invalid.  The actual exception raised\n                inherits from InvalidResult.  See #lookup_id for more info."
  },
  {
    "code": "def create_new_values(self):\n        model = self.queryset.model\n        pks = []\n        extra_create_kwargs = self.extra_create_kwargs()\n        for value in self._new_values:\n            create_kwargs = {self.create_field: value}\n            create_kwargs.update(extra_create_kwargs)\n            new_item = self.create_item(**create_kwargs)\n            pks.append(new_item.pk)\n        return model.objects.filter(pk__in=pks)",
    "docstring": "Create values created by the user input. Return the model instances QS."
  },
  {
    "code": "def get_temperature_from_humidity(self):\n        self._init_humidity()\n        temp = 0\n        data = self._humidity.humidityRead()\n        if (data[2]):\n            temp = data[3]\n        return temp",
    "docstring": "Returns the temperature in Celsius from the humidity sensor"
  },
  {
    "code": "def count_base_units(units):\n    ret = {}\n    for unit in units:\n        factor, base_unit = get_conversion_factor(unit)\n        ret.setdefault(base_unit, 0)\n        ret[base_unit] += 1\n    return ret",
    "docstring": "Returns a dict mapping names of base units to how many times they\n    appear in the given iterable of units.  Effectively this counts how\n    many length units you have, how many time units, and so forth."
  },
  {
    "code": "def read(self, file_path):\n        if not os.path.exists(file_path):\n            raise InvalidZoneinfoFile(\"The tzinfo file does not exist\")\n        with open(file_path, \"rb\") as fd:\n            return self._parse(fd)",
    "docstring": "Read a zoneinfo structure from the given path.\n\n        :param file_path: The path of a zoneinfo file."
  },
  {
    "code": "def install_hooks():\n    if PY3:\n        return\n    install_aliases()\n    flog.debug('sys.meta_path was: {0}'.format(sys.meta_path))\n    flog.debug('Installing hooks ...')\n    newhook = RenameImport(RENAMES)\n    if not detect_hooks():\n        sys.meta_path.append(newhook)\n    flog.debug('sys.meta_path is now: {0}'.format(sys.meta_path))",
    "docstring": "This function installs the future.standard_library import hook into\n    sys.meta_path."
  },
  {
    "code": "def generate(self, output_dir, work, ngrams, labels, minus_ngrams):\n        template = self._get_template()\n        colours = generate_colours(len(ngrams))\n        for siglum in self._corpus.get_sigla(work):\n            ngram_data = zip(labels, ngrams)\n            content = self._generate_base(work, siglum)\n            for ngrams_group in ngrams:\n                content = self._highlight(content, ngrams_group, True)\n            content = self._highlight(content, minus_ngrams, False)\n            self._ngrams_count = 1\n            content = self._format_content(content)\n            report_name = '{}-{}.html'.format(work, siglum)\n            self._write(work, siglum, content, output_dir, report_name,\n                        template, ngram_data=ngram_data,\n                        minus_ngrams=minus_ngrams, colours=colours)",
    "docstring": "Generates HTML reports for each witness to `work`, showing its text\n        with the n-grams in `ngrams` highlighted.\n\n        Any n-grams in `minus_ngrams` have any highlighting of them\n        (or subsets of them) removed.\n\n        :param output_dir: directory to write report to\n        :type output_dir: `str`\n        :param work: name of work to highlight\n        :type work: `str`\n        :param ngrams: groups of n-grams to highlight\n        :type ngrams: `list` of `list` of `str`\n        :param labels: labels for the groups of n-grams\n        :type labels: `list` of `str`\n        :param minus_ngrams: n-grams to remove highlighting from\n        :type minus_ngrams: `list` of `str`\n        :rtype: `str`"
  },
  {
    "code": "def is_archlinux():\n    if platform.system().lower() == 'linux':\n        if platform.linux_distribution() == ('', '', ''):\n            if os.path.exists('/etc/arch-release'):\n                return True\n    return False",
    "docstring": "return True if the current distribution is running on debian like OS."
  },
  {
    "code": "def _less_or_close(a, value, **kwargs):\n    r\n    return (a < value) | np.isclose(a, value, **kwargs)",
    "docstring": "r\"\"\"Compare values for less or close to boolean masks.\n\n    Returns a boolean mask for values less than or equal to a target within a specified\n    absolute or relative tolerance (as in :func:`numpy.isclose`).\n\n    Parameters\n    ----------\n    a : array-like\n        Array of values to be compared\n    value : float\n        Comparison value\n\n    Returns\n    -------\n    array-like\n        Boolean array where values are less than or nearly equal to value."
  },
  {
    "code": "def get_parameter_definitions(self):\n        output = {}\n        for var_name, attrs in self.defined_variables().items():\n            var_type = attrs.get(\"type\")\n            if isinstance(var_type, CFNType):\n                cfn_attrs = copy.deepcopy(attrs)\n                cfn_attrs[\"type\"] = var_type.parameter_type\n                output[var_name] = cfn_attrs\n        return output",
    "docstring": "Get the parameter definitions to submit to CloudFormation.\n\n        Any variable definition whose `type` is an instance of `CFNType` will\n        be returned as a CloudFormation Parameter.\n\n        Returns:\n            dict: parameter definitions. Keys are parameter names, the values\n                are dicts containing key/values for various parameter\n                properties."
  },
  {
    "code": "def create_worker_build(self, **kwargs):\n        missing = set()\n        for required in ('platform', 'release', 'arrangement_version'):\n            if not kwargs.get(required):\n                missing.add(required)\n        if missing:\n            raise ValueError(\"Worker build missing required parameters: %s\" %\n                             missing)\n        if kwargs.get('platforms'):\n            raise ValueError(\"Worker build called with unwanted platforms param\")\n        arrangement_version = kwargs['arrangement_version']\n        kwargs.setdefault('inner_template', WORKER_INNER_TEMPLATE.format(\n            arrangement_version=arrangement_version))\n        kwargs.setdefault('outer_template', WORKER_OUTER_TEMPLATE)\n        kwargs.setdefault('customize_conf', WORKER_CUSTOMIZE_CONF)\n        kwargs['build_type'] = BUILD_TYPE_WORKER\n        try:\n            return self._do_create_prod_build(**kwargs)\n        except IOError as ex:\n            if os.path.basename(ex.filename) == kwargs['inner_template']:\n                raise OsbsValidationException(\"worker invalid arrangement_version %s\" %\n                                              arrangement_version)\n            raise",
    "docstring": "Create a worker build\n\n        Pass through method to create_prod_build with the following\n        modifications:\n            - platform param is required\n            - release param is required\n            - arrangement_version param is required, which is used to\n              select which worker_inner:n.json template to use\n            - inner template set to worker_inner:n.json if not set\n            - outer template set to worker.json if not set\n            - customize configuration set to worker_customize.json if not set\n\n        :return: BuildResponse instance"
  },
  {
    "code": "def calculate_md5(fileobject, size=2**16):\n    fileobject.seek(0)\n    md5 = hashlib.md5()\n    for data in iter(lambda: fileobject.read(size), b''):\n        if not data: break\n        if isinstance(data, six.text_type):\n            data = data.encode('utf-8')\n        md5.update(data)\n    fileobject.seek(0)\n    return md5.hexdigest()",
    "docstring": "Utility function to calculate md5 hashes while being light on memory usage.\n\n    By reading the fileobject piece by piece, we are able to process content that\n    is larger than available memory"
  },
  {
    "code": "def write(self, path):\n        with open(path, 'wb') as f:\n            f.write(self.getXML())",
    "docstring": "Write RSS content to file."
  },
  {
    "code": "def namedb_get_all_namespace_ids( cur ):\n    query = \"SELECT namespace_id FROM namespaces WHERE op = ?;\"\n    args = (NAMESPACE_READY,)\n    namespace_rows = namedb_query_execute( cur, query, args )\n    ret = []\n    for namespace_row in namespace_rows:\n        ret.append( namespace_row['namespace_id'] )\n    return ret",
    "docstring": "Get a list of all READY namespace IDs."
  },
  {
    "code": "def equities_sids_for_country_code(self, country_code):\n        sids = self._compute_asset_lifetimes([country_code]).sid\n        return tuple(sids.tolist())",
    "docstring": "Return all of the sids for a given country.\n\n        Parameters\n        ----------\n        country_code : str\n            An ISO 3166 alpha-2 country code.\n\n        Returns\n        -------\n        tuple[int]\n            The sids whose exchanges are in this country."
  },
  {
    "code": "def _iter_indented_subactions(self, action):\n        try:\n            get_subactions = action._get_subactions\n        except AttributeError:\n            pass\n        else:\n            self._indent()\n            if isinstance(action, argparse._SubParsersAction):\n                for subaction in sorted(\n                        get_subactions(), key=lambda x: x.dest):\n                    yield subaction\n            else:\n                for subaction in get_subactions():\n                    yield subaction\n            self._dedent()",
    "docstring": "Sort the subcommands alphabetically"
  },
  {
    "code": "async def prepare_decrypter(client, cdn_client, cdn_redirect):\n        cdn_aes = AESModeCTR(\n            key=cdn_redirect.encryption_key,\n            iv=cdn_redirect.encryption_iv[:12] + bytes(4)\n        )\n        decrypter = CdnDecrypter(\n            cdn_client, cdn_redirect.file_token,\n            cdn_aes, cdn_redirect.cdn_file_hashes\n        )\n        cdn_file = await cdn_client(GetCdnFileRequest(\n            file_token=cdn_redirect.file_token,\n            offset=cdn_redirect.cdn_file_hashes[0].offset,\n            limit=cdn_redirect.cdn_file_hashes[0].limit\n        ))\n        if isinstance(cdn_file, CdnFileReuploadNeeded):\n            await client(ReuploadCdnFileRequest(\n                file_token=cdn_redirect.file_token,\n                request_token=cdn_file.request_token\n            ))\n            cdn_file = decrypter.get_file()\n        else:\n            cdn_file.bytes = decrypter.cdn_aes.encrypt(cdn_file.bytes)\n            cdn_hash = decrypter.cdn_file_hashes.pop(0)\n            decrypter.check(cdn_file.bytes, cdn_hash)\n        return decrypter, cdn_file",
    "docstring": "Prepares a new CDN decrypter.\n\n        :param client: a TelegramClient connected to the main servers.\n        :param cdn_client: a new client connected to the CDN.\n        :param cdn_redirect: the redirect file object that caused this call.\n        :return: (CdnDecrypter, first chunk file data)"
  },
  {
    "code": "def _get_cached_mounted_points():\n    result = []\n    try:\n        mounted_devices_key = winreg.OpenKey(\n            winreg.HKEY_LOCAL_MACHINE, \"SYSTEM\\\\MountedDevices\"\n        )\n        for v in _iter_vals(mounted_devices_key):\n            if \"DosDevices\" not in v[0]:\n                continue\n            volume_string = v[1].decode(\"utf-16le\", \"ignore\")\n            if not _is_mbed_volume(volume_string):\n                continue\n            mount_point_match = re.match(\".*\\\\\\\\(.:)$\", v[0])\n            if not mount_point_match:\n                logger.debug(\"Invalid disk pattern for entry %s, skipping\", v[0])\n                continue\n            mount_point = mount_point_match.group(1)\n            result.append({\"mount_point\": mount_point, \"volume_string\": volume_string})\n    except OSError:\n        logger.error('Failed to open \"MountedDevices\" in registry')\n    return result",
    "docstring": "! Get the volumes present on the system\n    @return List of mount points and their associated target id\n      Ex. [{ 'mount_point': 'D:', 'target_id_usb_id': 'xxxx'}, ...]"
  },
  {
    "code": "def devices(self):\n        'return generator of configured devices'\n        return self.fs is not None and [JFSDevice(d, self, parentpath=self.rootpath) for d in self.fs.devices.iterchildren()] or [x for x in []]",
    "docstring": "return generator of configured devices"
  },
  {
    "code": "def normalize_index(index):\n    index = np.asarray(index)\n    if len(index) == 0:\n        return index.astype('int')\n    if index.dtype == 'bool':\n        index = index.nonzero()[0]\n    elif index.dtype == 'int':\n        pass\n    else:\n        raise ValueError('Index should be either integer or bool')\n    return index",
    "docstring": "normalize numpy index"
  },
  {
    "code": "def user(self):\n        return self.users.get(self.contexts[self.current_context].get(\"user\", \"\"), {})",
    "docstring": "Returns the current user set by current context"
  },
  {
    "code": "def add_ip_address(list_name, item_name):\n    payload = {\"jsonrpc\": \"2.0\",\n               \"id\": \"ID0\",\n               \"method\": \"add_policy_ip_addresses\",\n               \"params\": [list_name, {\"item_name\": item_name}]}\n    response = __proxy__['bluecoat_sslv.call'](payload, True)\n    return _validate_change_result(response)",
    "docstring": "Add an IP address to an IP address list.\n\n    list_name(str): The name of the specific policy IP address list to append to.\n\n    item_name(str): The IP address to append to the list.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24"
  },
  {
    "code": "def list_tag(self, limit=500, offset=0):\n        evt = self._client._request_entity_tag_list(self.__lid, limit=limit, offset=offset)\n        self._client._wait_and_except_if_failed(evt)\n        return evt.payload['tags']",
    "docstring": "List `all` the tags for this Thing\n\n        Returns lists of tags, as below\n\n            #!python\n            [\n                \"mytag1\",\n                \"mytag2\"\n                \"ein_name\",\n                \"nochein_name\"\n            ]\n\n        - OR...\n\n        Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)\n        containing the error if the infrastructure detects a problem\n\n        Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)\n        if there is a communications problem between you and the infrastructure\n\n        `limit` (optional) (integer) Return at most this many tags\n\n        `offset` (optional) (integer) Return tags starting at this offset"
  },
  {
    "code": "def report(self, name, ok, msg=None, deltat=20):\n        r = self.reports[name]\n        if time.time() < r.last_report + deltat:\n            r.ok = ok\n            return\n        r.last_report = time.time()\n        if ok and not r.ok:\n            self.say(\"%s OK\" % name)\n        r.ok = ok\n        if not r.ok:\n            self.say(msg)",
    "docstring": "report a sensor error"
  },
  {
    "code": "def drop_index(self, table, column):\n        self.execute('ALTER TABLE {0} DROP INDEX {1}'.format(wrap(table), column))\n        self._printer('\\tDropped index from column {0}'.format(column))",
    "docstring": "Drop an index from a table."
  },
  {
    "code": "def get_gene_id(gene_name):\n    from intermine.webservice import Service\n    service = Service('http://yeastmine.yeastgenome.org/yeastmine/service')\n    query = service.new_query('Gene')\n    query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol',\n                   'name', 'sgdAlias', 'crossReferences.identifier',\n                   'crossReferences.source.name')\n    query.add_constraint('organism.shortName', '=', 'S. cerevisiae', code='B')\n    query.add_constraint('Gene', 'LOOKUP', gene_name, code='A')\n    for row in query.rows():\n        gid = row['secondaryIdentifier']\n    return gid",
    "docstring": "Retrieve systematic yeast gene name from the common name.\n\n    :param gene_name: Common name for yeast gene (e.g. ADE2).\n    :type gene_name: str\n    :returns: Systematic name for yeast gene (e.g. YOR128C).\n    :rtype: str"
  },
  {
    "code": "def _recode_for_categories(codes, old_categories, new_categories):\n    from pandas.core.algorithms import take_1d\n    if len(old_categories) == 0:\n        return codes.copy()\n    elif new_categories.equals(old_categories):\n        return codes.copy()\n    indexer = coerce_indexer_dtype(new_categories.get_indexer(old_categories),\n                                   new_categories)\n    new_codes = take_1d(indexer, codes.copy(), fill_value=-1)\n    return new_codes",
    "docstring": "Convert a set of codes for to a new set of categories\n\n    Parameters\n    ----------\n    codes : array\n    old_categories, new_categories : Index\n\n    Returns\n    -------\n    new_codes : array\n\n    Examples\n    --------\n    >>> old_cat = pd.Index(['b', 'a', 'c'])\n    >>> new_cat = pd.Index(['a', 'b'])\n    >>> codes = np.array([0, 1, 1, 2])\n    >>> _recode_for_categories(codes, old_cat, new_cat)\n    array([ 1,  0,  0, -1])"
  },
  {
    "code": "def from_record(cls, record, crs, schema=None):\n        properties = cls._to_properties(record, schema)\n        vector = GeoVector(shape(record['geometry']), crs)\n        if record.get('raster'):\n            assets = {k: dict(type=RASTER_TYPE, product='visual', **v) for k, v in record.get('raster').items()}\n        else:\n            assets = record.get('assets', {})\n        return cls(vector, properties, assets)",
    "docstring": "Create GeoFeature from a record."
  },
  {
    "code": "def list_files(tag=None, sat_id=None, data_path=None, format_str=None):\n    index = pds.date_range(pysat.datetime(2017,12,1), pysat.datetime(2018,12,1)) \n    names = [ data_path+date.strftime('%Y-%m-%d')+'.nofile' for date in index]\n    return pysat.Series(names, index=index)",
    "docstring": "Produce a fake list of files spanning a year"
  },
  {
    "code": "def upload(self, sys_id, file_path, name=None, multipart=False):\n        if not isinstance(multipart, bool):\n            raise InvalidUsage('Multipart must be of type bool')\n        resource = self.resource\n        if name is None:\n            name = os.path.basename(file_path)\n        resource.parameters.add_custom({\n            'table_name': self.table_name,\n            'table_sys_id': sys_id,\n            'file_name': name\n        })\n        data = open(file_path, 'rb').read()\n        headers = {}\n        if multipart:\n            headers[\"Content-Type\"] = \"multipart/form-data\"\n            path_append = '/upload'\n        else:\n            headers[\"Content-Type\"] = \"text/plain\"\n            path_append = '/file'\n        return resource.request(method='POST', data=data, headers=headers, path_append=path_append)",
    "docstring": "Attaches a new file to the provided record\n\n        :param sys_id: the sys_id of the record to attach the file to\n        :param file_path: local absolute path of the file to upload\n        :param name: custom name for the uploaded file (instead of basename)\n        :param multipart: whether or not to use multipart\n        :return: the inserted record"
  },
  {
    "code": "def get_raw(self):\n        return [self.name, self.size, self.last_modified, self.location]",
    "docstring": "Get a list with information about the file.\n\n        The returned list contains name, size, last_modified and location."
  },
  {
    "code": "def unregister_dependent_on(self, tree):\n        if tree in self.dependent_on:\n            self.dependent_on.remove(tree)",
    "docstring": "unregistering tree that we are dependent on"
  },
  {
    "code": "def _resolved_pid(self):\n        if not isinstance(self.pid, PersistentIdentifier):\n            return resolve_pid(self.pid)\n        return self.pid",
    "docstring": "Resolve self.pid if it is a fetched pid."
  },
  {
    "code": "def _fingerprint_dict_with_files(self, option_val):\n    return stable_option_fingerprint({\n      k: self._expand_possible_file_value(v) for k, v in option_val.items()\n    })",
    "docstring": "Returns a fingerprint of the given dictionary containing file paths.\n\n    Any value which is a file path which exists on disk will be fingerprinted by that file's\n    contents rather than by its path.\n\n    This assumes the files are small enough to be read into memory.\n\n    NB: The keys of the dict are assumed to be strings -- if they are not, the dict should be\n    converted to encode its keys with `stable_option_fingerprint()`, as is done in the `fingerprint()`\n    method."
  },
  {
    "code": "def unregister(self, plugin=None, name=None):\n        if name is None:\n            assert plugin is not None, \"one of name or plugin needs to be specified\"\n            name = self.get_name(plugin)\n        if plugin is None:\n            plugin = self.get_plugin(name)\n        if self._name2plugin.get(name):\n            del self._name2plugin[name]\n        for hookcaller in self._plugin2hookcallers.pop(plugin, []):\n            hookcaller._remove_plugin(plugin)\n        return plugin",
    "docstring": "unregister a plugin object and all its contained hook implementations\n        from internal data structures."
  },
  {
    "code": "def device_message(device,\n                   code,\n                   ts=None,\n                   origin=None,\n                   type=None,\n                   severity=None,\n                   title=None,\n                   description=None,\n                   hint=None,\n                   **metaData):\n    if ts is None:\n        ts = local_now()\n    payload = MessagePayload(device=device)\n    payload.messages.append(\n        Message(\n            code=code,\n            ts=ts,\n            origin=origin,\n            type=type,\n            severity=severity,\n            title=title,\n            description=description,\n            hint=hint,\n            **metaData))\n    return dumps(payload)",
    "docstring": "This quickly builds a time-stamped message. If `ts` is None, the\n    current time is used."
  },
  {
    "code": "def CreateAFF4Object(stat_response, client_id_urn, mutation_pool, token=None):\n  urn = stat_response.pathspec.AFF4Path(client_id_urn)\n  if stat.S_ISDIR(stat_response.st_mode):\n    ftype = standard.VFSDirectory\n  else:\n    ftype = aff4_grr.VFSFile\n  with aff4.FACTORY.Create(\n      urn, ftype, mode=\"w\", mutation_pool=mutation_pool, token=token) as fd:\n    fd.Set(fd.Schema.STAT(stat_response))\n    fd.Set(fd.Schema.PATHSPEC(stat_response.pathspec))",
    "docstring": "This creates a File or a Directory from a stat response."
  },
  {
    "code": "def addHeader(self, name, value, must_understand=False):\n        self.headers[name] = value\n        self.headers.set_required(name, must_understand)",
    "docstring": "Sets a persistent header to send with each request.\n\n        @param name: Header name."
  },
  {
    "code": "def get_facet_serializer_class(self):\n        if self.facet_serializer_class is None:\n            raise AttributeError(\n                \"%(cls)s should either include a `facet_serializer_class` attribute, \"\n                \"or override %(cls)s.get_facet_serializer_class() method.\" %\n                {\"cls\": self.__class__.__name__}\n            )\n        return self.facet_serializer_class",
    "docstring": "Return the class to use for serializing facets.\n        Defaults to using ``self.facet_serializer_class``."
  },
  {
    "code": "def list(ctx):\n    if ctx.namespace != 'accounts':\n        click.echo(\n            click.style('Only account data is available for listing.', fg='red')\n        )\n        return\n    swag = create_swag_from_ctx(ctx)\n    accounts = swag.get_all()\n    _table = [[result['name'], result.get('id')] for result in accounts]\n    click.echo(\n        tabulate(_table, headers=[\"Account Name\", \"Account Number\"])\n    )",
    "docstring": "List SWAG account info."
  },
  {
    "code": "def create(self):\n        logger.info(\"creating server\")\n        self.library.Srv_Create.restype = snap7.snap7types.S7Object\n        self.pointer = snap7.snap7types.S7Object(self.library.Srv_Create())",
    "docstring": "create the server."
  },
  {
    "code": "def cropbox(self, image, geometry, options):\n        cropbox = options['cropbox']\n        if not cropbox:\n            return image\n        x, y, x2, y2 = parse_cropbox(cropbox)\n        return self._cropbox(image, x, y, x2, y2)",
    "docstring": "Wrapper for ``_cropbox``"
  },
  {
    "code": "def enable_repeat(self, value=None):\n        if value is None:\n            value = not self.repeated\n        spotifyconnect.Error.maybe_raise(lib.SpPlaybackEnableRepeat(value))",
    "docstring": "Enable repeat mode"
  },
  {
    "code": "def get_messages(module):\n    answer = collections.OrderedDict()\n    for name in dir(module):\n        candidate = getattr(module, name)\n        if inspect.isclass(candidate) and issubclass(candidate, message.Message):\n            answer[name] = candidate\n    return answer",
    "docstring": "Discovers all protobuf Message classes in a given import module.\n\n    Args:\n        module (module): A Python module; :func:`dir` will be run against this\n            module to find Message subclasses.\n\n    Returns:\n        dict[str, google.protobuf.message.Message]: A dictionary with the\n            Message class names as keys, and the Message subclasses themselves\n            as values."
  },
  {
    "code": "def dumps(self, value):\n    for serializer in self:\n      value = serializer.dumps(value)\n    return value",
    "docstring": "returns serialized `value`."
  },
  {
    "code": "def type_converter(text):\n    if text.isdigit():\n        return int(text), int\n    try:\n        return float(text), float\n    except ValueError:\n        return text, STRING_TYPE",
    "docstring": "I convert strings into integers, floats, and strings!"
  },
  {
    "code": "def do_view(self):\n        self.current.output['login_process'] = True\n        self.current.task_data['login_successful'] = False\n        if self.current.is_auth:\n            self._do_upgrade()\n        else:\n            try:\n                auth_result = self.current.auth.authenticate(\n                    self.current.input['username'],\n                    self.current.input['password'])\n                self.current.task_data['login_successful'] = auth_result\n                if auth_result:\n                    self._do_upgrade()\n            except ObjectDoesNotExist:\n                self.current.log.exception(\"Wrong username or another error occurred\")\n                pass\n            except:\n                raise\n            if self.current.output.get('cmd') != 'upgrade':\n                self.current.output['status_code'] = 403\n            else:\n                KeepAlive(self.current.user_id).reset()",
    "docstring": "Authenticate user with given credentials.\n        Connects user's queue and exchange"
  },
  {
    "code": "def assert_sigfigs_equal(x, y, sigfigs=3):\n    xpow =  np.floor(np.log10(x))\n    x = x * 10**(- xpow)\n    y = y * 10**(- xpow)\n    assert_almost_equal(x, y, sigfigs)",
    "docstring": "Tests if all elements in x and y\n    agree up to a certain number of\n    significant figures.\n\n    :param np.ndarray x: Array of numbers.\n    :param np.ndarray y: Array of numbers you want to\n        be equal to ``x``.\n    :param int sigfigs: How many significant\n        figures you demand that they share.\n        Default is 3."
  },
  {
    "code": "def rdfs_properties(rdf):\n    superprops = {}\n    for s, o in rdf.subject_objects(RDFS.subPropertyOf):\n        superprops.setdefault(s, set())\n        for sp in rdf.transitive_objects(s, RDFS.subPropertyOf):\n            if sp != s:\n                superprops[s].add(sp)\n    for p, sps in superprops.items():\n        logging.debug(\"setting superproperties: %s -> %s\", p, str(sps))\n        for s, o in rdf.subject_objects(p):\n            for sp in sps:\n                rdf.add((s, sp, o))",
    "docstring": "Perform RDFS subproperty inference.\n\n    Add superproperties where subproperties have been used."
  },
  {
    "code": "def adjustHSP(self, hsp):\n        reduction = self._reductionForOffset(\n            min(hsp.readStartInSubject, hsp.subjectStart))\n        hsp.readEndInSubject = hsp.readEndInSubject - reduction\n        hsp.readStartInSubject = hsp.readStartInSubject - reduction\n        hsp.subjectEnd = hsp.subjectEnd - reduction\n        hsp.subjectStart = hsp.subjectStart - reduction",
    "docstring": "Adjust the read and subject start and end offsets in an HSP.\n\n        @param hsp: a L{dark.hsp.HSP} or L{dark.hsp.LSP} instance."
  },
  {
    "code": "def check_angle_sampling(nvecs, angles):\n    failed_nvecs = []\n    failures = []\n    for i, vec in enumerate(nvecs):\n        X = (angles*vec[:, None]).sum(axis=0)\n        diff = float(np.abs(X.max() - X.min()))\n        if diff < (2.*np.pi):\n            warnings.warn(\"Need a longer integration window for mode {0}\"\n                          .format(vec))\n            failed_nvecs.append(vec.tolist())\n            failures.append(0)\n        elif (diff/len(X)) > np.pi:\n            warnings.warn(\"Need a finer sampling for mode {0}\"\n                          .format(str(vec)))\n            failed_nvecs.append(vec.tolist())\n            failures.append(1)\n    return np.array(failed_nvecs), np.array(failures)",
    "docstring": "Returns a list of the index of elements of n which do not have adequate\n    toy angle coverage. The criterion is that we must have at least one sample\n    in each Nyquist box when we project the toy angles along the vector n.\n\n    Parameters\n    ----------\n    nvecs : array_like\n        Array of integer vectors.\n    angles : array_like\n        Array of angles.\n\n    Returns\n    -------\n    failed_nvecs : :class:`numpy.ndarray`\n        Array of all integer vectors that failed checks. Has shape (N,3).\n    failures : :class:`numpy.ndarray`\n        Array of flags that designate whether this failed needing a longer\n        integration window (0) or finer sampling (1)."
  },
  {
    "code": "def prophist(self,prop,fig=None,log=False, mask=None,\n                 selected=False,**kwargs):\n        setfig(fig)\n        inds = None\n        if mask is not None:\n            inds = np.where(mask)[0]\n        elif inds is None:\n            if selected:\n                inds = self.selected.index\n            else:\n                inds = self.stars.index\n        if selected:\n            vals = self.selected[prop].values\n        else:\n            vals = self.stars[prop].iloc[inds].values\n        if prop=='depth' and hasattr(self,'depth'):\n            vals *= self.dilution_factor[inds]\n        if log:\n            h = plt.hist(np.log10(vals),**kwargs)\n        else:\n            h = plt.hist(vals,**kwargs)\n        plt.xlabel(prop)",
    "docstring": "Plots a 1-d histogram of desired property.\n\n        :param prop:\n            Name of property to plot.  Must be column of ``self.stars``.\n\n        :param fig: (optional)\n            Argument for :func:`plotutils.setfig`\n\n        :param log: (optional)\n            Whether to plot the histogram of log10 of the property.\n\n        :param mask: (optional)\n            Boolean array (length of ``self.stars``) to say\n            which indices to plot (``True`` is good).\n\n        :param selected: (optional)\n            If ``True``, then only the \"selected\" stars (that is, stars\n            obeying all distribution constraints attached to this object)\n            will be plotted.  In this case, ``mask`` will be ignored.\n\n        :param **kwargs:\n            Additional keyword arguments passed to :func:`plt.hist`."
  },
  {
    "code": "def load_psat(cls, fd):\n        from pylon.io.psat import PSATReader\n        return PSATReader().read(fd)",
    "docstring": "Returns a case object from the given PSAT data file."
  },
  {
    "code": "def requeue(self):\n        if self.acknowledged:\n            raise self.MessageStateError(\n                \"Message already acknowledged with state: %s\" % self._state)\n        self.backend.requeue(self.delivery_tag)\n        self._state = \"REQUEUED\"",
    "docstring": "Reject this message and put it back on the queue.\n\n        You must not use this method as a means of selecting messages\n        to process.\n\n        :raises MessageStateError: If the message has already been\n            acknowledged/requeued/rejected."
  },
  {
    "code": "def pathstrip(path, n):\n  pathlist = [path]\n  while os.path.dirname(pathlist[0]) != b'':\n    pathlist[0:1] = os.path.split(pathlist[0])\n  return b'/'.join(pathlist[n:])",
    "docstring": "Strip n leading components from the given path"
  },
  {
    "code": "def body_template(self, value):\n        if self.method == VERB.GET:\n            raise AssertionError(\"body_template cannot be set for GET requests\")\n        if value is None:\n            self.logger.warning(\"body_template is None, parsing will be ignored\")\n            return\n        if not isinstance(value, DataCollection):\n            msg = \"body_template must be an instance of %s.%s\" % (\n                DataCollection.__module__,\n                DataCollection.__name__\n            )\n            raise AssertionError(msg)\n        self._body_template = value\n        self.set_deserializer_by_mime_type(self.content_type)",
    "docstring": "Must be an instance of a prestans.types.DataCollection subclass; this is\n        generally set during the RequestHandler lifecycle. Setting this spwans the\n        parsing process of the body. If the HTTP verb is GET an AssertionError is\n        thrown. Use with extreme caution."
  },
  {
    "code": "def update_host_template(resource_root, name, cluster_name, api_host_template):\n  return call(resource_root.put,\n      HOST_TEMPLATE_PATH % (cluster_name, name),\n      ApiHostTemplate, data=api_host_template, api_version=3)",
    "docstring": "Update a host template identified by name in the specified cluster.\n  @param resource_root: The root Resource object.\n  @param name: Host template name.\n  @param cluster_name: Cluster name.\n  @param api_host_template: The updated host template.\n  @return: The updated ApiHostTemplate.\n  @since: API v3"
  },
  {
    "code": "def is_single_tree(data_wrapper):\n    db = data_wrapper.data_block\n    bad_ids = db[db[:, COLS.P] == -1][1:, COLS.ID]\n    return CheckResult(len(bad_ids) == 0, bad_ids.tolist())",
    "docstring": "Check that data forms a single tree\n\n    Only the first point has ID of -1.\n\n    Returns:\n        CheckResult with result and list of IDs\n\n    Note:\n        This assumes no_missing_parents passed."
  },
  {
    "code": "def generate(self, num_to_generate, starting_place):\n        res = []\n        activ = starting_place[None, :]\n        index = activ.__getattribute__(self.argfunc)(1)\n        item = self.weights[index]\n        for x in range(num_to_generate):\n            activ = self.forward(item, prev_activation=activ)[0]\n            index = activ.__getattribute__(self.argfunc)(1)\n            res.append(index)\n            item = self.weights[index]\n        return res",
    "docstring": "Generate data based on some initial position."
  },
  {
    "code": "def bgrewriteaof(host=None, port=None, db=None, password=None):\n    server = _connect(host, port, db, password)\n    return server.bgrewriteaof()",
    "docstring": "Asynchronously rewrite the append-only file\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' redis.bgrewriteaof"
  },
  {
    "code": "def attach_network_interface(self, network_interface_id,\n                                 instance_id, device_index):\n        params = {'NetworkInterfaceId' : network_interface_id,\n                  'InstanceId' : instance_id,\n                  'Deviceindex' : device_index}\n        return self.get_status('AttachNetworkInterface', params, verb='POST')",
    "docstring": "Attaches a network interface to an instance.\n\n        :type network_interface_id: str\n        :param network_interface_id: The ID of the network interface to attach.\n\n        :type instance_id: str\n        :param instance_id: The ID of the instance that will be attached\n            to the network interface.\n\n        :type device_index: int\n        :param device_index: The index of the device for the network\n            interface attachment on the instance."
  },
  {
    "code": "def create_cms_plugin_page(apphook, apphook_namespace, placeholder_slot=None):\n    creator = CmsPluginPageCreator(\n        apphook=apphook,\n        apphook_namespace=apphook_namespace,\n    )\n    creator.placeholder_slot = placeholder_slot\n    plugin_page = creator.create()\n    return plugin_page",
    "docstring": "Create cms plugin page in all existing languages.\n    Add a link to the index page.\n\n    :param apphook: e.g...........: 'FooBarApp'\n    :param apphook_namespace: e.g.: 'foobar'\n    :return:"
  },
  {
    "code": "def run_later(self, callable_, timeout, *args, **kwargs):\n        self.lock.acquire()\n        try:\n            if self.die:\n                raise RuntimeError('This timer has been shut down and '\n                                   'does not accept new jobs.')\n            job = TimerTask(callable_, *args, **kwargs)\n            self._jobs.append((job, time.time() + timeout))\n            self._jobs.sort(key=lambda j: j[1])\n            self.lock.notify()\n            return job\n        finally:\n            self.lock.release()",
    "docstring": "Schedules the specified callable for delayed execution.\n\n        Returns a TimerTask instance that can be used to cancel pending\n        execution."
  },
  {
    "code": "def _view_changed(self, event=None):\n        tr = self.node_transform(self._linked_view.scene)\n        p1, p2 = tr.map(self._axis_ends())\n        if self.orientation in ('left', 'right'):\n            self.axis.domain = (p1[1], p2[1])\n        else:\n            self.axis.domain = (p1[0], p2[0])",
    "docstring": "Linked view transform has changed; update ticks."
  },
  {
    "code": "def import_functions(names, src, dst):\n    for name in names:\n        module = importlib.import_module('pygsp.' + src)\n        setattr(sys.modules['pygsp.' + dst], name, getattr(module, name))",
    "docstring": "Import functions in package from their implementation modules."
  },
  {
    "code": "def get_responses(self):\n        response_list = []\n        for question_map in self._my_map['questions']:\n            response_list.append(self._get_response_from_question_map(question_map))\n        return ResponseList(response_list)",
    "docstring": "Gets list of the latest responses"
  },
  {
    "code": "def _get_updated_rows(self, auth, function):\n        qps = []\n        for row in self._curs_pg:\n            qps.append(\n                {\n                    'operator': 'equals',\n                    'val1': 'id',\n                    'val2': row['id']\n                }\n            )\n        if len(qps) == 0:\n            return []\n        q = qps[0]\n        for qp in qps[1:]:\n            q = {\n                'operator': 'or',\n                'val1': q,\n                'val2': qp\n            }\n        updated = function(auth, q, { 'max_result': 10000 })['result']\n        return updated",
    "docstring": "Get rows updated by last update query\n\n            * `function` [function]\n                Function to use for searching (one of the search_* functions).\n\n            Helper function used to fetch all rows which was updated by the\n            latest UPDATE ... RETURNING id query."
  },
  {
    "code": "def get_parent_repository_ids(self, repository_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.get_parent_catalog_ids(catalog_id=repository_id)\n        return self._hierarchy_session.get_parents(id_=repository_id)",
    "docstring": "Gets the parent ``Ids`` of the given repository.\n\n        arg:    repository_id (osid.id.Id): a repository ``Id``\n        return: (osid.id.IdList) - the parent ``Ids`` of the repository\n        raise:  NotFound - ``repository_id`` is not found\n        raise:  NullArgument - ``repository_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def write(self, text):\n        text = str(text)\n        text = text.replace(IAC, IAC+IAC)\n        text = text.replace(chr(10), chr(13)+chr(10))\n        self.writecooked(text)",
    "docstring": "Send a packet to the socket. This function cooks output."
  },
  {
    "code": "def getElementsCustomFilter(self, filterFunc, root='root'):\n        (root, isFromRoot) = self._handleRootArg(root)\n        elements = []\n        if isFromRoot is True and filterFunc(root) is True:\n            elements.append(root)\n        getElementsCustomFilter = self.getElementsCustomFilter\n        for child in root.children:\n            if filterFunc(child) is True:\n                elements.append(child)\n            elements += getElementsCustomFilter(filterFunc, child)\n        return TagCollection(elements)",
    "docstring": "getElementsCustomFilter - Scan elements using a provided function\n\n            @param filterFunc <function>(node) - A function that takes an AdvancedTag as an argument, and returns True if some arbitrary criteria is met\n\n            @return - TagCollection of all matching elements"
  },
  {
    "code": "def kill_definitions(self, atom, code_loc, data=None, dummy=True):\n        if data is None:\n            data = DataSet(Undefined(atom.size), atom.size)\n        self.kill_and_add_definition(atom, code_loc, data, dummy=dummy)",
    "docstring": "Overwrite existing definitions w.r.t 'atom' with a dummy definition instance. A dummy definition will not be\n        removed during simplification.\n\n        :param Atom atom:\n        :param CodeLocation code_loc:\n        :param object data:\n        :return: None"
  },
  {
    "code": "def getCMakeFlags(self, engineRoot, fmt):\n\t\treturn Utility.join(\n\t\t\tfmt.delim,\n\t\t\t[\n\t\t\t\t'-DCMAKE_PREFIX_PATH=' + self.getPrefixDirectories(engineRoot, ';'),\n\t\t\t\t'-DCMAKE_INCLUDE_PATH=' + self.getIncludeDirectories(engineRoot, ';'),\n\t\t\t\t'-DCMAKE_LIBRARY_PATH=' + self.getLinkerDirectories(engineRoot, ';'),\n\t\t\t] + self.resolveRoot(self.cmakeFlags, engineRoot),\n\t\t\tfmt.quotes\n\t\t)",
    "docstring": "Constructs the CMake invocation flags string for building against this library"
  },
  {
    "code": "def download_loci(self):\n        pool = multiprocessing.Pool(processes=self.threads)\n        pool.map(self.download_threads, self.loci_url)\n        pool.close()\n        pool.join()",
    "docstring": "Uses a multi-threaded approach to download allele files"
  },
  {
    "code": "def get_related_fields(model_class, field_name, path=\"\"):\n    if field_name:\n        field, model, direct, m2m = _get_field_by_name(model_class, field_name)\n        if direct:\n            try:\n                new_model = _get_remote_field(field).parent_model()\n            except AttributeError:\n                new_model = _get_remote_field(field).model\n        else:\n            if hasattr(field, 'related_model'):\n                new_model = field.related_model\n            else:\n                new_model = field.model()\n        path += field_name\n        path += '__'\n    else:\n        new_model = model_class\n    new_fields = get_relation_fields_from_model(new_model)\n    model_ct = ContentType.objects.get_for_model(new_model)\n    return (new_fields, model_ct, path)",
    "docstring": "Get fields for a given model"
  },
  {
    "code": "def get_backend(backend, path, backends):\n    m_norm = normalize_vault_path(path)\n    for mount_name, values in backends.items():\n        b_norm = normalize_vault_path(mount_name)\n        if (m_norm == b_norm) and values['type'] == backend:\n            return values\n    return None",
    "docstring": "Returns mountpoint details for a backend"
  },
  {
    "code": "def memoize(fn=None):\n    cache = { }\n    arg_hash_fn = fn_arg_hash_function(fn)\n    def decorated(*args, **kwargs):\n        try:\n            hash_ = arg_hash_fn(*args, **kwargs)\n        except TypeError:\n            return fn(*args, **kwargs)\n        try:\n            return cache[hash_]\n        except KeyError:\n            return_val = fn(*args, **kwargs)\n            cache[hash_] = return_val\n            return return_val\n    _functools.update_wrapper(decorated, fn)\n    return decorated",
    "docstring": "Caches the result of the provided function."
  },
  {
    "code": "def _proc_builtin(self, tarfile):\n        self.offset_data = tarfile.fileobj.tell()\n        offset = self.offset_data\n        if self.isreg() or self.type not in SUPPORTED_TYPES:\n            offset += self._block(self.size)\n        tarfile.offset = offset\n        self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors)\n        return self",
    "docstring": "Process a builtin type or an unknown type which\n           will be treated as a regular file."
  },
  {
    "code": "def Column(self, column_name):\n    column_idx = None\n    for idx, column in enumerate(self.header.columns):\n      if column.name == column_name:\n        column_idx = idx\n        break\n    if column_idx is None:\n      raise KeyError(\"Column '{}' not found\".format(column_name))\n    for row in self.rows:\n      yield row.values[column_idx]",
    "docstring": "Iterates over values of a given column.\n\n    Args:\n      column_name: A nome of the column to retrieve the values for.\n\n    Yields:\n      Values of the specified column.\n\n    Raises:\n      KeyError: If given column is not present in the table."
  },
  {
    "code": "def parseFile(self, srcFile, closeFile=False):\n        try:\n            result = self.parse(srcFile.read())\n        finally:\n            if closeFile:\n                srcFile.close()\n        return result",
    "docstring": "Parses CSS file-like objects using the current cssBuilder.\n        Use for external stylesheets."
  },
  {
    "code": "def make_config(self, data: dict):\n        self.validate_config(data)\n        config_data = self.prepare_config(data)\n        return config_data",
    "docstring": "Make a MIP config."
  },
  {
    "code": "def transfer(self, from_acct: Account, b58_to_address: str, value: int, payer_acct: Account, gas_limit: int,\n                 gas_price: int) -> str:\n        func = InvokeFunction('transfer')\n        if not isinstance(value, int):\n            raise SDKException(ErrorCode.param_err('the data type of value should be int.'))\n        if value < 0:\n            raise SDKException(ErrorCode.param_err('the value should be equal or great than 0.'))\n        if not isinstance(from_acct, Account):\n            raise SDKException(ErrorCode.param_err('the data type of from_acct should be Account.'))\n        Oep4.__b58_address_check(b58_to_address)\n        from_address = from_acct.get_address().to_bytes()\n        to_address = Address.b58decode(b58_to_address).to_bytes()\n        func.set_params_value(from_address, to_address, value)\n        tx_hash = self.__sdk.get_network().send_neo_vm_transaction(self.__hex_contract_address, from_acct, payer_acct,\n                                                                   gas_limit, gas_price, func, False)\n        return tx_hash",
    "docstring": "This interface is used to call the Transfer method in ope4\n        that transfer an amount of tokens from one account to another account.\n\n        :param from_acct: an Account class that send the oep4 token.\n        :param b58_to_address: a base58 encode address that receive the oep4 token.\n        :param value: an int value that indicate the amount oep4 token that will be transferred in this transaction.\n        :param payer_acct: an Account class that used to pay for the transaction.\n        :param gas_limit: an int value that indicate the gas limit.\n        :param gas_price: an int value that indicate the gas price.\n        :return: the hexadecimal transaction hash value."
  },
  {
    "code": "def Update(self, data):\n        m = len(data)\n        self.params[:m] += data",
    "docstring": "Updates a Dirichlet distribution.\n\n        data: sequence of observations, in order corresponding to params"
  },
  {
    "code": "def iter_cols(self, start=None, end=None):\n        start = start or 0\n        end = end or self.ncols\n        for i in range(start, end):\n            yield self.iloc[:, i]",
    "docstring": "Iterate each of the Region cols in this region"
  },
  {
    "code": "def _init(init, X, N, rank, dtype):\n    Uinit = [None for _ in range(N)]\n    if isinstance(init, list):\n        Uinit = init\n    elif init == 'random':\n        for n in range(1, N):\n            Uinit[n] = array(rand(X.shape[n], rank), dtype=dtype)\n    elif init == 'nvecs':\n        for n in range(1, N):\n            Uinit[n] = array(nvecs(X, n, rank), dtype=dtype)\n    else:\n        raise 'Unknown option (init=%s)' % str(init)\n    return Uinit",
    "docstring": "Initialization for CP models"
  },
  {
    "code": "def configure(self, options, conf):\n        self.conf = conf\n        self.enabled = options.epdb_debugErrors or options.epdb_debugFailures\n        self.enabled_for_errors = options.epdb_debugErrors\n        self.enabled_for_failures = options.epdb_debugFailures",
    "docstring": "Configure which kinds of exceptions trigger plugin."
  },
  {
    "code": "def _update_secret(namespace, name, data, apiserver_url):\n    url = \"{0}/api/v1/namespaces/{1}/secrets/{2}\".format(apiserver_url,\n                                                         namespace, name)\n    data = [{\"op\": \"replace\", \"path\": \"/data\", \"value\": data}]\n    ret = _kpatch(url, data)\n    if ret.get(\"status\") == 404:\n        return \"Node {0} doesn't exist\".format(url)\n    return ret",
    "docstring": "Replace secrets data by a new one"
  },
  {
    "code": "def is_openmp_supported():\n    log_threshold = log.set_threshold(log.FATAL)\n    ret = check_openmp_support()\n    log.set_threshold(log_threshold)\n    return ret",
    "docstring": "Determine whether the build compiler has OpenMP support."
  },
  {
    "code": "def _get_queryset_methods(cls, queryset_class):\n        def create_method(name, method):\n            def manager_method(self, *args, **kwargs):\n                return getattr(self.get_queryset(), name)(*args, **kwargs)\n            manager_method.__name__ = method.__name__\n            manager_method.__doc__ = method.__doc__\n            return manager_method\n        orig_method = models.Manager._get_queryset_methods\n        new_methods = orig_method(queryset_class)\n        inspect_func = inspect.isfunction\n        for name, method in inspect.getmembers(queryset_class, predicate=inspect_func):\n            if hasattr(cls, name) or name in new_methods:\n                continue\n            queryset_only = getattr(method, 'queryset_only', None)\n            if queryset_only or (queryset_only is None and name.startswith('_')):\n                continue\n            new_methods[name] = create_method(name, method)\n        return new_methods",
    "docstring": "Django overrloaded method for add cyfunction."
  },
  {
    "code": "def set_expected_update_frequency(self, update_frequency):\n        try:\n            int(update_frequency)\n        except ValueError:\n            update_frequency = Dataset.transform_update_frequency(update_frequency)\n        if not update_frequency:\n            raise HDXError('Invalid update frequency supplied!')\n        self.data['data_update_frequency'] = update_frequency",
    "docstring": "Set expected update frequency\n\n        Args:\n            update_frequency (str): Update frequency\n\n        Returns:\n            None"
  },
  {
    "code": "def F_beta(self, beta):\n        try:\n            F_dict = {}\n            for i in self.TP.keys():\n                F_dict[i] = F_calc(\n                    TP=self.TP[i],\n                    FP=self.FP[i],\n                    FN=self.FN[i],\n                    beta=beta)\n            return F_dict\n        except Exception:\n            return {}",
    "docstring": "Calculate FBeta score.\n\n        :param beta: beta parameter\n        :type beta : float\n        :return: FBeta score for classes as dict"
  },
  {
    "code": "def ReplaceIxes(self, path, old_prefix, old_suffix, new_prefix, new_suffix):\n        old_prefix = self.subst('$'+old_prefix)\n        old_suffix = self.subst('$'+old_suffix)\n        new_prefix = self.subst('$'+new_prefix)\n        new_suffix = self.subst('$'+new_suffix)\n        dir,name = os.path.split(str(path))\n        if name[:len(old_prefix)] == old_prefix:\n            name = name[len(old_prefix):]\n        if name[-len(old_suffix):] == old_suffix:\n            name = name[:-len(old_suffix)]\n        return os.path.join(dir, new_prefix+name+new_suffix)",
    "docstring": "Replace old_prefix with new_prefix and old_suffix with new_suffix.\n\n        env - Environment used to interpolate variables.\n        path - the path that will be modified.\n        old_prefix - construction variable for the old prefix.\n        old_suffix - construction variable for the old suffix.\n        new_prefix - construction variable for the new prefix.\n        new_suffix - construction variable for the new suffix."
  },
  {
    "code": "def _merge(*args):\n    return re.compile(r'^' + r'[/-]'.join(args) + r'(?:\\s+' + _dow + ')?$')",
    "docstring": "Create a composite pattern and compile it."
  },
  {
    "code": "def getSequenceCombinaisons(polymorphipolymorphicDnaSeqSeq, pos = 0) :\n\tif type(polymorphipolymorphicDnaSeqSeq) is not types.ListType :\n\t\tseq = list(polymorphipolymorphicDnaSeqSeq)\n\telse :\n\t\tseq = polymorphipolymorphicDnaSeqSeq\n\tif pos >= len(seq) :\n\t\treturn [''.join(seq)]\n\tvariants = []\n\tif seq[pos] in polymorphicNucleotides :\n\t\tchars = decodePolymorphicNucleotide(seq[pos])\n\telse :\n\t\tchars = seq[pos]\n\tfor c in chars :\n\t\trseq = copy.copy(seq)\n\t\trseq[pos] = c\n\t\tvariants.extend(getSequenceCombinaisons(rseq, pos + 1))\n\treturn variants",
    "docstring": "Takes a dna sequence with polymorphismes and returns all the possible sequences that it can yield"
  },
  {
    "code": "def _weight_generator(self, reviewers):\n        scores = [r.anomalous_score for r in reviewers]\n        mu = np.average(scores)\n        sigma = np.std(scores)\n        if sigma:\n            def w(v):\n                try:\n                    exp = math.exp(self.alpha * (v - mu) / sigma)\n                    return 1. / (1. + exp)\n                except OverflowError:\n                    return 0.\n            return w\n        else:\n            return lambda v: 1.",
    "docstring": "Compute a weight function for the given reviewers.\n\n        Args:\n          reviewers: a set of reviewers to compute weight function.\n\n        Returns:\n          a function computing a weight for a reviewer."
  },
  {
    "code": "def mtf_bitransformer_base():\n  hparams = mtf_transformer2_base()\n  hparams.max_length = 256\n  hparams.shared_embedding = True\n  hparams.add_hparam(\"encoder_layers\", [\"self_att\", \"drd\"] * 6)\n  hparams.add_hparam(\"decoder_layers\", [\"self_att\", \"enc_att\", \"drd\"] * 6)\n  hparams.add_hparam(\"encoder_num_layers\", 6)\n  hparams.add_hparam(\"decoder_num_layers\", 6)\n  hparams.add_hparam(\"encoder_num_heads\", 8)\n  hparams.add_hparam(\"decoder_num_heads\", 8)\n  hparams.add_hparam(\"local_attention_radius\", 128)\n  hparams.add_hparam(\"encoder_num_memory_heads\", 0)\n  hparams.add_hparam(\"decoder_num_memory_heads\", 0)\n  hparams.add_hparam(\"encoder_shared_kv\", False)\n  hparams.add_hparam(\"decoder_shared_kv\", False)\n  hparams.add_hparam(\"decode_length_multiplier\", 1.5)\n  hparams.add_hparam(\"decode_length_constant\", 10.0)\n  hparams.add_hparam(\"alpha\", 0.6)\n  hparams.sampling_temp = 0.0\n  return hparams",
    "docstring": "Machine translation base configuration."
  },
  {
    "code": "def deserialize(cls, data, content_type=None):\n        deserializer = Deserializer(cls._infer_class_models())\n        return deserializer(cls.__name__, data, content_type=content_type)",
    "docstring": "Parse a str using the RestAPI syntax and return a model.\n\n        :param str data: A str using RestAPI structure. JSON by default.\n        :param str content_type: JSON by default, set application/xml if XML.\n        :returns: An instance of this model\n        :raises: DeserializationError if something went wrong"
  },
  {
    "code": "def CreateSitelinkFeedItem(feed_items, feed_item_id):\n  site_link_from_feed = feed_items[feed_item_id]\n  site_link_feed_item = {\n      'sitelinkText': site_link_from_feed['text'],\n      'sitelinkLine2': site_link_from_feed['line2'],\n      'sitelinkLine3': site_link_from_feed['line3'],\n  }\n  if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']:\n    site_link_feed_item['sitelinkFinalUrls'] = {\n        'urls': site_link_from_feed['finalUrls']\n    }\n    if 'finalMobileUrls' in site_link_from_feed:\n      site_link_feed_item['sitelinkFinalMobileUrls'] = {\n          'urls': site_link_from_feed['finalMobileUrls']\n      }\n    site_link_feed_item['sitelinkTrackingUrlTemplate'] = (\n        site_link_from_feed['trackingUrlTemplate'])\n  else:\n    site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url']\n  return site_link_feed_item",
    "docstring": "Creates a Sitelink Feed Item.\n\n  Args:\n    feed_items: a list of all Feed Items.\n    feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item\n        should be created.\n\n  Returns:\n    The new Sitelink Feed Item."
  },
  {
    "code": "def reset(self):\n        self.reset_bars()\n        self.url_progressbar.reset()\n        for prop in dir(self):\n            if prop.startswith(\"__\"):\n                continue\n            prop_obj = getattr(self, prop)\n            if prop_obj is not None and hasattr(prop_obj, \"reset\"):\n                prop_obj.reset()\n        properties = (\n            getattr(self.__class__, prop)\n            for prop in self._property_list\n            if hasattr(self.__class__, prop)\n        )\n        for prop in properties:\n            if hasattr(prop, \"reset\"):\n                prop.reset()\n            elif hasattr(prop, \"__set__\"):\n                prop.__set__(None, \"\")\n        self.additional_info = None",
    "docstring": "Reset all inputs back to default."
  },
  {
    "code": "def register_arrays(self, arrays):\n        if isinstance(arrays, collections.Mapping):\n            arrays = arrays.itervalues()\n        for ary in arrays:\n            self.register_array(**ary)",
    "docstring": "Register arrays using a list of dictionaries defining the arrays.\n\n        The list should itself contain dictionaries. i.e.\n\n        .. code-block:: python\n\n            D = [{ 'name':'uvw', 'shape':(3,'ntime','nbl'),'dtype':np.float32 },\n                { 'name':'lm', 'shape':(2,'nsrc'),'dtype':np.float32 }]\n\n        Parameters\n        ----------\n        arrays : A list or dict.\n            A list or dictionary of dictionaries describing arrays."
  },
  {
    "code": "def countBy(self, val):\n        def by(result, key, value):\n            if key not in result:\n                result[key] = 0\n            result[key] += 1\n        res = self._group(self.obj, val, by)\n        return self._wrap(res)",
    "docstring": "Counts instances of an object that group by a certain criterion. Pass\n        either a string attribute to count by, or a function that returns the\n        criterion."
  },
  {
    "code": "def monitor_experiment(args):\n    if args.time <= 0:\n        print_error('please input a positive integer as time interval, the unit is second.')\n        exit(1)\n    while True:\n        try:\n            os.system('clear')\n            update_experiment()\n            show_experiment_info()\n            time.sleep(args.time)\n        except KeyboardInterrupt:\n            exit(0)\n        except Exception as exception:\n            print_error(exception)\n            exit(1)",
    "docstring": "monitor the experiment"
  },
  {
    "code": "def push(self, value: Union[int, bytes]) -> None:\n        if len(self.values) > 1023:\n            raise FullStack('Stack limit reached')\n        validate_stack_item(value)\n        self.values.append(value)",
    "docstring": "Push an item onto the stack."
  },
  {
    "code": "def _parameter_objects(parameter_objects_from_pillars, parameter_object_overrides):\n    from_pillars = copy.deepcopy(__salt__['pillar.get'](parameter_objects_from_pillars))\n    from_pillars.update(parameter_object_overrides)\n    parameter_objects = _standardize(_dict_to_list_ids(from_pillars))\n    for parameter_object in parameter_objects:\n        parameter_object['attributes'] = _properties_from_dict(parameter_object['attributes'])\n    return parameter_objects",
    "docstring": "Return a list of parameter objects that configure the pipeline\n\n    parameter_objects_from_pillars\n        The pillar key to use for lookup\n\n    parameter_object_overrides\n        Parameter objects to use. Will override objects read from pillars."
  },
  {
    "code": "def protect(self, passphrase, enc_alg, hash_alg):\n        if self.is_public:\n            warnings.warn(\"Public keys cannot be passphrase-protected\", stacklevel=2)\n            return\n        if self.is_protected and not self.is_unlocked:\n            warnings.warn(\"This key is already protected with a passphrase - \"\n                          \"please unlock it before attempting to specify a new passphrase\", stacklevel=2)\n            return\n        for sk in itertools.chain([self], self.subkeys.values()):\n            sk._key.protect(passphrase, enc_alg, hash_alg)\n        del passphrase",
    "docstring": "Add a passphrase to a private key. If the key is already passphrase protected, it should be unlocked before\n        a new passphrase can be specified.\n\n        Has no effect on public keys.\n\n        :param passphrase: A passphrase to protect the key with\n        :type passphrase: ``str``, ``unicode``\n        :param enc_alg: Symmetric encryption algorithm to use to protect the key\n        :type enc_alg: :py:obj:`~constants.SymmetricKeyAlgorithm`\n        :param hash_alg: Hash algorithm to use in the String-to-Key specifier\n        :type hash_alg: :py:obj:`~constants.HashAlgorithm`"
  },
  {
    "code": "def launched():\n    if not PREFIX:\n        return False\n    return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)",
    "docstring": "Test whether the current python environment is the correct lore env.\n\n    :return:  :any:`True` if the environment is launched\n    :rtype: bool"
  },
  {
    "code": "def active_network_addresses(hypervisor):\n    active = []\n    for network in hypervisor.listNetworks():\n        try:\n            xml = hypervisor.networkLookupByName(network).XMLDesc(0)\n        except libvirt.libvirtError:\n            continue\n        else:\n            ip_element = etree.fromstring(xml).find('.//ip')\n            address = ip_element.get('address')\n            netmask = ip_element.get('netmask')\n            active.append(ipaddress.IPv4Network(u'/'.join((address, netmask)),\n                                                strict=False))\n    return active",
    "docstring": "Query libvirt for the already reserved addresses."
  },
  {
    "code": "def get_health_check(name, region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    retries = 30\n    while True:\n        try:\n            lb = conn.get_all_load_balancers(load_balancer_names=[name])\n            lb = lb[0]\n            ret = odict.OrderedDict()\n            hc = lb.health_check\n            ret['interval'] = hc.interval\n            ret['target'] = hc.target\n            ret['healthy_threshold'] = hc.healthy_threshold\n            ret['timeout'] = hc.timeout\n            ret['unhealthy_threshold'] = hc.unhealthy_threshold\n            return ret\n        except boto.exception.BotoServerError as e:\n            if retries and e.code == 'Throttling':\n                log.debug('Throttled by AWS API, will retry in 5 seconds.')\n                time.sleep(5)\n                retries -= 1\n                continue\n            log.error('ELB %s not found.', name,\n                      exc_info_on_logleve=logging.DEBUG)\n            return {}",
    "docstring": "Get the health check configured for this ELB.\n\n    CLI example:\n\n    .. code-block:: bash\n\n        salt myminion boto_elb.get_health_check myelb"
  },
  {
    "code": "def all_files_in_directory(path):\n    file_list = []\n    for dirname, dirnames, filenames in os.walk(path):\n        for filename in filenames:\n            file_list.append(os.path.join(dirname, filename))\n    return file_list",
    "docstring": "Recursively ist all files under a directory"
  },
  {
    "code": "def progress(status_code):\n    lookup = {\n        'pk_dsa': 'DSA key generation',\n        'pk_elg': 'Elgamal key generation',\n        'primegen': 'Prime generation',\n        'need_entropy': 'Waiting for new entropy in the RNG',\n        'tick': 'Generic tick without any special meaning - still working.',\n        'starting_agent': 'A gpg-agent was started.',\n        'learncard': 'gpg-agent or gpgsm is learning the smartcard data.',\n        'card_busy': 'A smartcard is still working.' }\n    for key, value in lookup.items():\n        if str(status_code) == key:\n            return value",
    "docstring": "Translate PROGRESS status codes from GnuPG to messages."
  },
  {
    "code": "def list_blocked_work_units(self, work_spec_name, start=0, limit=None):\n        return self.registry.filter(WORK_UNITS_ + work_spec_name + _BLOCKED,\n                                    start=start, limit=limit)",
    "docstring": "Get a dictionary of blocked work units for some work spec.\n\n        The dictionary is from work unit name to work unit definiton.\n        Work units included in this list are blocked because they were\n        listed as the first work unit in\n        :func:`add_dependent_work_units`, and the work unit(s) they\n        depend on have not completed yet.  This function does not tell\n        why work units are blocked, it merely returns the fact that\n        they are."
  },
  {
    "code": "def _get_sync(self, url):\n        response = self.session.get(url)\n        if response.status_code == requests.codes.ok:\n            return response.json()\n        else:\n            raise HTTPError",
    "docstring": "Internal method used for GET requests\n\n        Args:\n            url (str): URL to fetch\n\n        Returns:\n            Individual URL request's response\n\n        Raises:\n          HTTPError: If HTTP request failed."
  },
  {
    "code": "def compute_eager_pipelines(self):\n        for name, pipe in self._pipelines.items():\n            if pipe.eager:\n                self.pipeline_output(name)",
    "docstring": "Compute any pipelines attached with eager=True."
  },
  {
    "code": "def create_new_reference(self, obj, global_ref=False):\n        opaque_ref = self.state.project.loader.extern_object.allocate()\n        l.debug(\"Map %s to opaque reference 0x%x\", obj, opaque_ref)\n        if global_ref:\n            self.global_refs[opaque_ref] = obj\n        else:\n            self.local_refs[opaque_ref] = obj\n        return opaque_ref",
    "docstring": "Create a new reference thats maps to the given object.\n\n        :param obj:              Object which gets referenced.\n        :param bool global_ref:  Whether a local or global reference is created."
  },
  {
    "code": "def decode_streaming(self, data):\n        lookup = dict(((b, v), s) for (s, (b, v)) in self._table.items())\n        buffer = 0\n        size = 0\n        for byte in data:\n            for m in [128, 64, 32, 16, 8, 4, 2, 1]:\n                buffer = (buffer << 1) + bool(from_byte(byte) & m)\n                size += 1\n                if (size, buffer) in lookup:\n                    symbol = lookup[size, buffer]\n                    if symbol == _EOF:\n                        return\n                    yield symbol\n                    buffer = 0\n                    size = 0",
    "docstring": "Decode given data in streaming fashion\n\n        :param data: sequence of bytes (string, list or generator of bytes)\n        :return: generator of symbols"
  },
  {
    "code": "def get_magnitude_squared(self):\n        return self.x*self.x + self.y*self.y",
    "docstring": "Returns the square of the magnitude of this vector."
  },
  {
    "code": "def eventFilter(self, widget, event):\n        if event.type() == QEvent.MouseButtonPress:\n            if event.button() == Qt.LeftButton:\n                self.sig_canvas_clicked.emit(self)\n        return super(FigureThumbnail, self).eventFilter(widget, event)",
    "docstring": "A filter that is used to send a signal when the figure canvas is\n        clicked."
  },
  {
    "code": "def mark(request):\n    notification_id = request.POST.get('id', None)\n    action = request.POST.get('action', None)\n    success = True\n    if notification_id:\n        try:\n            notification = Notification.objects.get(pk=notification_id,\n                                                    recipient=request.user)\n            if action == 'read':\n                notification.mark_as_read()\n                msg = _(\"Marked as read\")\n            elif action == 'unread':\n                notification.mark_as_unread()\n                msg = _(\"Marked as unread\")\n            else:\n                success = False\n                msg = _(\"Invalid mark action.\")\n        except Notification.DoesNotExist:\n            success = False\n            msg = _(\"Notification does not exists.\")\n    else:\n        success = False\n        msg = _(\"Invalid Notification ID\")\n    ctx = {'msg': msg, 'success': success, 'action': action}\n    return notification_redirect(request, ctx)",
    "docstring": "Handles marking of individual notifications as read or unread.\n    Takes ``notification id`` and mark ``action`` as POST data.\n\n    :param request: HTTP request context.\n\n    :returns: Response to mark action of supplied notification ID."
  },
  {
    "code": "def op_funcdef_handle(tokens):\n    func, base_args = get_infix_items(tokens)\n    args = []\n    for arg in base_args[:-1]:\n        rstrip_arg = arg.rstrip()\n        if not rstrip_arg.endswith(unwrapper):\n            if not rstrip_arg.endswith(\",\"):\n                arg += \", \"\n            elif arg.endswith(\",\"):\n                arg += \" \"\n        args.append(arg)\n    last_arg = base_args[-1]\n    if last_arg.rstrip().endswith(\",\"):\n        last_arg = last_arg.rsplit(\",\")[0]\n    args.append(last_arg)\n    return func + \"(\" + \"\".join(args) + \")\"",
    "docstring": "Process infix defs."
  },
  {
    "code": "def to_tree(instance, *children):\n    yield unicode(instance)\n    for i, child in enumerate(children):\n        lines = 0\n        yield \"|\"\n        yield \"+---\" + unicode(child)\n        if i != len(children) - 1:\n            a = \"|\"\n        else:\n            a = \" \"\n        for j, item in enumerate(child.itervalues()):\n            if j != len(child) - 1:\n                b = \"|\"\n            else:\n                b = \" \"\n            if j == 0:\n                yield a + \"   |\"\n            for k, line in enumerate(item.to_tree()):\n                lines += 1\n                if k == 0:\n                    yield a + \"   +---\" + line\n                else:\n                    yield a + \"   \" + b + \"   \" + line\n        if len(children) > 1 and i == len(children) - 1 and lines > 1:\n            yield a",
    "docstring": "Generate tree structure of an instance, and its children. This method\n    yields its results, instead of returning them."
  },
  {
    "code": "def _new(self, name, **kwargs):\n        if self._name_path:\n            parent = self\n            for path_element in self._name_path.split(\"/\"):\n                self._set_xml_from_keys(parent, (path_element, None))\n                parent = parent.find(path_element)\n            parent.text = name\n        else:\n            ElementTree.SubElement(self, \"name\").text = name\n        for item in self.data_keys.items():\n            self._set_xml_from_keys(self, item, **kwargs)",
    "docstring": "Create a new JSSObject with name and \"keys\".\n\n        Generate a default XML template for this object, based on\n        the class attribute \"keys\".\n\n        Args:\n            name: String name of the object to use as the\n                object's name property.\n            kwargs:\n                Accepted keyword args can be viewed by checking the\n                \"data_keys\" class attribute. Typically, they include all\n                top-level keys, and non-duplicated keys used elsewhere.\n\n                Values will be cast to string. (Int 10, bool False\n                become string values \"10\" and \"false\").\n\n                Ignores kwargs that aren't in object's keys attribute."
  },
  {
    "code": "def _on_stackexchange_user(self, future, access_token, response):\n        response['access_token'] = access_token\n        future.set_result(response)",
    "docstring": "Invoked as a callback when self.stackexchange_request returns the\n        response to the request for user data.\n\n        :param method future: The callback method to pass along\n        :param str access_token: The access token for the user's use\n        :param dict response: The HTTP response already decoded"
  },
  {
    "code": "def getPyClass(self):\n        if self.hasExtPyClass():\n            classInfo = self.extPyClasses[self.name]\n            return \".\".join(classInfo)\n        return 'Holder'",
    "docstring": "Name of generated inner class that will be specified as pyclass."
  },
  {
    "code": "def dict_to_querystring(dictionary):\n    s = u\"\"\n    for d in dictionary.keys():\n        s = unicode.format(u\"{0}{1}={2}&\", s, d, dictionary[d])\n    return s[:-1]",
    "docstring": "Converts a dict to a querystring suitable to be appended to a URL."
  },
  {
    "code": "def get_size(self):\n        rec = self.get_rectangle()\n        return (int(rec[2]-rec[0]), int(rec[3]-rec[1]))",
    "docstring": "Get the size of the tree.\n\n        Returns:\n            tupel: (width, height)"
  },
  {
    "code": "def load_nb(cls, inline=True):\n        from IPython.display import publish_display_data\n        cls._loaded = True\n        init_notebook_mode(connected=not inline)\n        publish_display_data(data={MIME_TYPES['jlab-hv-load']:\n                                   get_plotlyjs()})",
    "docstring": "Loads the plotly notebook resources."
  },
  {
    "code": "def get_dates_in_period(start=None, top=None, step=1, step_dict={}):\n    delta = relativedelta(**step_dict) if step_dict else timedelta(days=step)\n    start = start or datetime.today()\n    top = top or start + delta\n    dates = []\n    current = start\n    while current <= top:\n        dates.append(current)\n        current += delta\n    return dates",
    "docstring": "Return a list of dates from the `start` to `top`."
  },
  {
    "code": "def _make_data(data) -> Tuple[List[Dict], List[Dict]]:\n        jsdata = []\n        for idx, row in data.iterrows():\n            row.index = row.index.astype(str)\n            rdict = row.to_dict()\n            rdict.update(dict(key=str(idx)))\n            jsdata.append(rdict)\n        return jsdata, Table._make_columns(data.columns)",
    "docstring": "Transform table data into JSON."
  },
  {
    "code": "def getPermutedTensors(W, kw, n, m2, noisePct):\n  W2 = W.repeat(m2, 1)\n  nz = W[0].nonzero()\n  numberToZero = int(round(noisePct * kw))\n  for i in range(m2):\n    indices = np.random.permutation(kw)[0:numberToZero]\n    for j in indices:\n      W2[i,nz[j]] = 0\n  return W2",
    "docstring": "Generate m2 noisy versions of W. Noisy\n  version of W is generated by randomly permuting noisePct of the non-zero\n  components to other components.\n\n  :param W:\n  :param n:\n  :param m2:\n  :param noisePct:\n\n  :return:"
  },
  {
    "code": "def save(self, fname):\n        with open(fname, 'wb') as f:\n            f.write(encode(self.text))",
    "docstring": "Save the report"
  },
  {
    "code": "def main():\n    parser = argparse.ArgumentParser(description=DESCRIPTION)\n    parser.add_argument(\n        '-v', '--verbose', help='increase output verbosity', action='store_true'\n    )\n    args = parser.parse_args()\n    generator = SignatureGenerator(debug=args.verbose)\n    crash_data = json.loads(sys.stdin.read())\n    ret = generator.generate(crash_data)\n    print(json.dumps(ret, indent=2))",
    "docstring": "Takes crash data via stdin and generates a Socorro signature"
  },
  {
    "code": "def list(self,table, **kparams):\n        records = self.api.list(table, **kparams)\n        return records",
    "docstring": "get a collection of records by table name.\n        returns a collection of SnowRecord obj."
  },
  {
    "code": "def save(filepath, obj, on_overwrite = 'ignore'):\n    filepath = preprocess(filepath)\n    if os.path.exists(filepath):\n        if on_overwrite == 'backup':\n            backup = filepath + '.bak'\n            shutil.move(filepath, backup)\n            save(filepath, obj)\n            try:\n                os.remove(backup)\n            except Exception, e:\n                warnings.warn(\"Got an error while traing to remove \"+backup+\":\"+str(e))\n            return\n        else:\n            assert on_overwrite == 'ignore'\n    try:\n        _save(filepath, obj)\n    except RuntimeError, e:\n        if str(e).find('recursion') != -1:\n            warnings.warn('pylearn2.utils.save encountered the following '\n                          'error: ' + str(e) +\n                          '\\nAttempting to resolve this error by calling ' +\n                          'sys.setrecusionlimit and retrying')\n            old_limit = sys.getrecursionlimit()\n            try:\n                sys.setrecursionlimit(50000)\n                _save(filepath, obj)\n            finally:\n                sys.setrecursionlimit(old_limit)",
    "docstring": "Serialize `object` to a file denoted by `filepath`.\n\n    Parameters\n    ----------\n    filepath : str\n        A filename. If the suffix is `.joblib` and joblib can be\n        imported, `joblib.dump` is used in place of the regular\n        pickling mechanisms; this results in much faster saves by\n        saving arrays as separate .npy files on disk. If the file\n        suffix is `.npy` than `numpy.save` is attempted on `obj`.\n        Otherwise, (c)pickle is used.\n\n    obj : object\n        A Python object to be serialized.\n\n    on_overwrite: A string specifying what to do if the file already\n                exists.\n                ignore: just overwrite it\n                backup: make a copy of the file (<filepath>.bak) and\n                        delete it when done saving the new copy.\n                        this allows recovery of the old version of\n                        the file if saving the new one fails"
  },
  {
    "code": "def cleaned_selector(html):\n    import parsel\n    try:\n        tree = _cleaned_html_tree(html)\n        sel = parsel.Selector(root=tree, type='html')\n    except (lxml.etree.XMLSyntaxError,\n            lxml.etree.ParseError,\n            lxml.etree.ParserError,\n            UnicodeEncodeError):\n        sel = parsel.Selector(html)\n    return sel",
    "docstring": "Clean parsel.selector."
  },
  {
    "code": "def start_log_monitor(self):\n        stdout_file, stderr_file = self.new_log_files(\"log_monitor\")\n        process_info = ray.services.start_log_monitor(\n            self.redis_address,\n            self._logs_dir,\n            stdout_file=stdout_file,\n            stderr_file=stderr_file,\n            redis_password=self._ray_params.redis_password)\n        assert ray_constants.PROCESS_TYPE_LOG_MONITOR not in self.all_processes\n        self.all_processes[ray_constants.PROCESS_TYPE_LOG_MONITOR] = [\n            process_info\n        ]",
    "docstring": "Start the log monitor."
  },
  {
    "code": "def parse_optimize(self):\n        match = re.search(\"EQUILIBRIUM GEOMETRY LOCATED\", self.text)\n        spmatch = \"SADDLE POINT LOCATED\" in self.text\n        located = True if match or spmatch else False\n        points = grep_split(\" BEGINNING GEOMETRY SEARCH POINT NSERCH=\",\n                            self.text)\n        if self.tddft == \"excite\":\n            points = [self.parse_energy(point) for point in points[1:]]\n        else:\n            regex = re.compile(r'NSERCH:\\s+\\d+\\s+E=\\s+([+-]?\\d+\\.\\d+)')\n            points = [Energy(states=[State(0,None,float(m.group(1)), 0.0, 0.0)]) for m in regex.finditer(self.text)]\n        if \"FAILURE TO LOCATE STATIONARY POINT, TOO MANY STEPS TAKEN\" in self.text:\n            self.errcode = GEOM_NOT_LOCATED\n            self.errmsg = \"too many steps taken: %i\"%len(points)\n        if located:\n            self.errcode = OK\n        return Optimize(points=points)",
    "docstring": "Parse the ouput resulted of a geometry optimization. Or a\n        saddle point."
  },
  {
    "code": "def DateStringToDateObject(date_string):\n  if re.match('^\\d{8}$', date_string) == None:\n    return None\n  try:\n    return datetime.date(int(date_string[0:4]), int(date_string[4:6]),\n                         int(date_string[6:8]))\n  except ValueError:\n    return None",
    "docstring": "Return a date object for a string \"YYYYMMDD\"."
  },
  {
    "code": "def set_sleep_timer(self, sleep_time_seconds):\n        try:\n            if sleep_time_seconds is None:\n                sleep_time = ''\n            else:\n                sleep_time = format(\n                    datetime.timedelta(seconds=int(sleep_time_seconds))\n                )\n            self.avTransport.ConfigureSleepTimer([\n                ('InstanceID', 0),\n                ('NewSleepTimerDuration', sleep_time),\n            ])\n        except SoCoUPnPException as err:\n            if 'Error 402 received' in str(err):\n                raise ValueError('invalid sleep_time_seconds, must be integer \\\n                    value between 0 and 86399 inclusive or None')\n            raise\n        except ValueError:\n            raise ValueError('invalid sleep_time_seconds, must be integer \\\n                value between 0 and 86399 inclusive or None')",
    "docstring": "Sets the sleep timer.\n\n        Args:\n            sleep_time_seconds (int or NoneType): How long to wait before\n                turning off speaker in seconds, None to cancel a sleep timer.\n                Maximum value of 86399\n\n        Raises:\n            SoCoException: Upon errors interacting with Sonos controller\n            ValueError: Argument/Syntax errors"
  },
  {
    "code": "def get_iex_listed_symbol_dir(start=None, **kwargs):\r\n    import warnings\r\n    warnings.warn(WNG_MSG % (\"get_iex_listed_symbol_dir\",\r\n                             \"refdata.get_iex_listed_symbol_dir\"))\r\n    return ListedSymbolDir(start=start, **kwargs)",
    "docstring": "MOVED to iexfinance.refdata.get_listed_symbol_dir"
  },
  {
    "code": "def hooked_by(self, addr):\n        if not self.is_hooked(addr):\n            l.warning(\"Address %s is not hooked\", self._addr_to_str(addr))\n            return None\n        return self._sim_procedures[addr]",
    "docstring": "Returns the current hook for `addr`.\n\n        :param addr: An address.\n\n        :returns:    None if the address is not hooked."
  },
  {
    "code": "def round(self):\n        x, y = self.anchor\n        self.anchor = (normalizers.normalizeRounding(x),\n                       normalizers.normalizeRounding(y))\n        x, y = self.bcpIn\n        self.bcpIn = (normalizers.normalizeRounding(x),\n                      normalizers.normalizeRounding(y))\n        x, y = self.bcpOut\n        self.bcpOut = (normalizers.normalizeRounding(x),\n                       normalizers.normalizeRounding(y))",
    "docstring": "Round coordinates."
  },
  {
    "code": "def structure_transform(self, original_structure, new_structure,\n                            refine_rotation=True):\n        sm = StructureMatcher()\n        if not sm.fit(original_structure, new_structure):\n            warnings.warn(\"original and new structures do not match!\")\n        trans_1 = self.get_ieee_rotation(original_structure, refine_rotation)\n        trans_2 = self.get_ieee_rotation(new_structure, refine_rotation)\n        new = self.rotate(trans_1)\n        new = new.rotate(np.transpose(trans_2))\n        return new",
    "docstring": "Transforms a tensor from one basis for an original structure\n        into a new basis defined by a new structure.\n\n        Args:\n            original_structure (Structure): structure corresponding\n                to the basis of the current tensor\n            new_structure (Structure): structure corresponding to the\n                desired basis\n            refine_rotation (bool): whether to refine the rotations\n                generated in get_ieee_rotation\n\n        Returns:\n            Tensor that has been transformed such that its basis\n            corresponds to the new_structure's basis"
  },
  {
    "code": "def allDecisions(self, result, **values):\n\t\tdata = self.__getDecision(result, multiple=True, **values)\n\t\tdata = [data[value] for value in result]\n\t\tif len(data) == 1:\n\t\t\treturn data[0]\n\t\telse:\n\t\t\treturn data",
    "docstring": "Joust like self.decision but for multiple finded values.\n\n\t\tReturns:\n\t\t\tArrays of arrays of finded elements or if finds only one mach, array of strings."
  },
  {
    "code": "def _push_property_schema(self, prop):\n        schema = Schema(self._schema.properties[prop])\n        self._push_schema(schema, \".properties.\" + prop)",
    "docstring": "Construct a sub-schema from a property of the current schema."
  },
  {
    "code": "def get_teams(self):\n        return self.make_request(host=\"erikberg.com\", sport='nba',\n                                 method=\"teams\", id=None,\n                                 format=\"json\",\n                                 parameters={})",
    "docstring": "Return json current roster of team"
  },
  {
    "code": "def canonical(self):\n        if not hasattr(self, '_canonical'):\n            self._canonical = conf.lib.clang_getCanonicalCursor(self)\n        return self._canonical",
    "docstring": "Return the canonical Cursor corresponding to this Cursor.\n\n        The canonical cursor is the cursor which is representative for the\n        underlying entity. For example, if you have multiple forward\n        declarations for the same class, the canonical cursor for the forward\n        declarations will be identical."
  },
  {
    "code": "def json_success(self, json):\n        if type(json) is dict and 'result' in json and json['result'] == 'success':\n            return True\n        return False",
    "docstring": "Check the JSON response object for the success flag\n\n        Parameters\n        ----------\n        json : dict\n            A dictionary representing a JSON object from lendingclub.com"
  },
  {
    "code": "def to_pfull_from_phalf(arr, pfull_coord):\n    phalf_top = arr.isel(**{internal_names.PHALF_STR: slice(1, None)})\n    phalf_top = replace_coord(phalf_top, internal_names.PHALF_STR,\n                              internal_names.PFULL_STR, pfull_coord)\n    phalf_bot = arr.isel(**{internal_names.PHALF_STR: slice(None, -1)})\n    phalf_bot = replace_coord(phalf_bot, internal_names.PHALF_STR,\n                              internal_names.PFULL_STR, pfull_coord)\n    return 0.5*(phalf_bot + phalf_top)",
    "docstring": "Compute data at full pressure levels from values at half levels."
  },
  {
    "code": "def recursive_setattr(obj: Any, attr: str, val: Any) -> Any:\n    pre, _, post = attr.rpartition('.')\n    return setattr(recursive_getattr(obj, pre) if pre else obj, post, val)",
    "docstring": "Recusrive ``setattr``.\n\n    This can be used as a drop in for the standard ``setattr(...)``. Credit to:\n    https://stackoverflow.com/a/31174427\n\n    Args:\n        obj: Object to retrieve the attribute from.\n        attr: Name of the attribute, with each successive attribute separated by a \".\".\n        value: Value to set the attribute to.\n    Returns:\n        The requested attribute. (Same as ``getattr``).\n    Raises:\n        AttributeError: If the attribute was not found and no default was provided. (Same as ``getattr``)."
  },
  {
    "code": "def set_progress_message(self, message, line_break=False):\n        end = '\\r' if not line_break else None\n        @self.connect\n        def on_progress(value, value_max, **kwargs):\n            kwargs['end'] = None if value == value_max else end\n            _default_on_progress(message, value, value_max, **kwargs)",
    "docstring": "Set a progress message.\n\n        The string needs to contain `{progress}`."
  },
  {
    "code": "async def _on_trace_notification(self, trace_event):\n        conn_string = trace_event.get('connection_string')\n        payload = trace_event.get('payload')\n        await self.notify_event(conn_string, 'trace', payload)",
    "docstring": "Callback function called when a trace chunk is received.\n\n        Args:\n            trace_chunk (dict): The received trace chunk information"
  },
  {
    "code": "def cookiestring(self, value):\n        c = Cookie.SimpleCookie(value)\n        sc = [(i.key, i.value) for i in c.values()]\n        self.cookies = dict(sc)",
    "docstring": "Cookie string setter"
  },
  {
    "code": "def trigger_streamer(*inputs, **kwargs):\n    streamer_marker = kwargs['mark_streamer']\n    try:\n        reading = inputs[1].pop()\n    except StreamEmptyError:\n        return []\n    finally:\n        for input_x in inputs:\n            input_x.skip_all()\n    try:\n        streamer_marker(reading.value)\n    except ArgumentError:\n        return []\n    return [IOTileReading(0, 0, 0)]",
    "docstring": "Trigger a streamer based on the index read from input b.\n\n    Returns:\n        list(IOTileReading)"
  },
  {
    "code": "def _is_domain_match(domain: str, hostname: str) -> bool:\n        if hostname == domain:\n            return True\n        if not hostname.endswith(domain):\n            return False\n        non_matching = hostname[:-len(domain)]\n        if not non_matching.endswith(\".\"):\n            return False\n        return not is_ip_address(hostname)",
    "docstring": "Implements domain matching adhering to RFC 6265."
  },
  {
    "code": "def _save_fastq_space(items):\n    to_cleanup = {}\n    for data in (utils.to_single_data(x) for x in items):\n        for fname in data.get(\"files\", []):\n            if os.path.realpath(fname).startswith(dd.get_work_dir(data)):\n                to_cleanup[fname] = data[\"config\"]\n    for fname, config in to_cleanup.items():\n        utils.save_diskspace(fname, \"Cleanup prep files after alignment finished\", config)",
    "docstring": "Potentially save fastq space prior to merging, since alignments done."
  },
  {
    "code": "def dumps(obj, indent=None, default=None, sort_keys=False, **kw):\n    return YAMLEncoder(indent=indent, default=default, sort_keys=sort_keys, **kw).encode(obj)",
    "docstring": "Dump string."
  },
  {
    "code": "def _check_required_fields(self, fields=None, either_fields=None):\n        for (key, value) in fields.items():\n            if not value:\n                raise HSException(\"Field '%s' is required.\" % key)\n        if either_fields is not None:\n            for field in either_fields:\n                if not any(field.values()):\n                    raise HSException(\"One of the following fields is required: %s\" % \", \".join(field.keys()))",
    "docstring": "Check the values of the fields\n\n        If no value found in `fields`, an exception will be raised.\n        `either_fields` are the fields that one of them must have a value\n\n        Raises:\n            HSException: If no value found in at least one item of`fields`, or\n                no value found in one of the items of `either_fields`\n\n        Returns:\n            None"
  },
  {
    "code": "def _create_field(self, field_id):\n        config = self._field_configs[field_id]\n        adapter = self._adapters[config['type']]\n        if 'name' in config:\n            name = config['name']\n        else:\n            name = None\n        if 'size' in config:\n            columns = config['size']\n        else:\n            columns = None\n        if 'values' in config:\n            values = config['values']\n        else:\n            values = None\n        field = adapter.get_field(name, columns, values)\n        if 'results_name' in config:\n            field = field.setResultsName(config['results_name'])\n        else:\n            field = field.setResultsName(field_id)\n        return field",
    "docstring": "Creates the field with the specified parameters.\n\n        :param field_id: identifier for the field\n        :return: the basic rule for the field"
  },
  {
    "code": "def count(args):\n    p = OptionParser(count.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n    coveragefile, fastafile = args\n    countsfile = coveragefile.split(\".\")[0] + \".bin\"\n    if op.exists(countsfile):\n        logging.error(\"`{0}` file exists. Remove before proceed.\"\\\n                .format(countsfile))\n        return\n    fastasize, sizes, offsets = get_offsets(fastafile)\n    logging.debug(\"Initialize array of uint8 with size {0}\".format(fastasize))\n    ar = np.zeros(fastasize, dtype=np.uint8)\n    update_array(ar, coveragefile, sizes, offsets)\n    ar.tofile(countsfile)\n    logging.debug(\"Array written to `{0}`\".format(countsfile))",
    "docstring": "%prog count t.coveragePerBase fastafile\n\n    Serialize the genomeCoverage results. The coordinate system of the count array\n    will be based on the fastafile."
  },
  {
    "code": "def search_users(self, user):\n        user_url = \"%s/%s/%s\" % (self.url, \"user\", user)\n        response = self.jss.get(user_url)\n        return LDAPUsersResults(self.jss, response)",
    "docstring": "Search for LDAP users.\n\n        Args:\n            user: User to search for. It is not entirely clear how the\n                JSS determines the results- are regexes allowed, or\n                globbing?\n\n        Returns:\n            LDAPUsersResult object.\n\n        Raises:\n            Will raise a JSSGetError if no results are found."
  },
  {
    "code": "def save(self):\n        if self.Death:\n            self.Alive = False\n        super(Animal, self).save()",
    "docstring": "The save method for Animal class is over-ridden to set Alive=False when a Death date is entered.  This is not the case for a cause of death."
  },
  {
    "code": "def _extract_intensities(image, mask = slice(None)):\n    return numpy.array(image, copy=True)[mask].ravel()",
    "docstring": "Internal, single-image version of `intensities`."
  },
  {
    "code": "def inception_v3_arg_scope(weight_decay=0.00004,\n                           stddev=0.1,\n                           batch_norm_var_collection='moving_vars'):\n  batch_norm_params = {\n      'decay': 0.9997,\n      'epsilon': 0.001,\n      'updates_collections': tf.GraphKeys.UPDATE_OPS,\n      'variables_collections': {\n          'beta': None,\n          'gamma': None,\n          'moving_mean': [batch_norm_var_collection],\n          'moving_variance': [batch_norm_var_collection],\n      }\n  }\n  with slim.arg_scope([slim.conv2d, slim.fully_connected],\n                      weights_regularizer=slim.l2_regularizer(weight_decay)):\n    with slim.arg_scope([slim.conv2d],\n                        weights_initializer=tf.truncated_normal_initializer(stddev=stddev),\n                        activation_fn=tf.nn.relu, normalizer_fn=slim.batch_norm,\n                        normalizer_params=batch_norm_params) as sc:\n      return sc",
    "docstring": "Defines the default InceptionV3 arg scope.\n\n  Args:\n    weight_decay: The weight decay to use for regularizing the model.\n    stddev: The standard deviation of the trunctated normal weight initializer.\n    batch_norm_var_collection: The name of the collection for the batch norm\n      variables.\n\n  Returns:\n    An `arg_scope` to use for the inception v3 model."
  },
  {
    "code": "def _extract_field_with_regex(self, field):\n        matched = re.search(field, self.text)\n        if not matched:\n            err_msg = u\"Failed to extract data with regex! => {}\\n\".format(field)\n            err_msg += u\"response body: {}\\n\".format(self.text)\n            logger.log_error(err_msg)\n            raise exceptions.ExtractFailure(err_msg)\n        return matched.group(1)",
    "docstring": "extract field from response content with regex.\n            requests.Response body could be json or html text.\n\n        Args:\n            field (str): regex string that matched r\".*\\(.*\\).*\"\n\n        Returns:\n            str: matched content.\n\n        Raises:\n            exceptions.ExtractFailure: If no content matched with regex.\n\n        Examples:\n            >>> # self.text: \"LB123abcRB789\"\n            >>> filed = \"LB[\\d]*(.*)RB[\\d]*\"\n            >>> _extract_field_with_regex(field)\n            abc"
  },
  {
    "code": "def choose_branch(exclude=None):\n    if exclude is None:\n        master = conf.get('git.master_branch', 'master')\n        develop = conf.get('git.devel_branch', 'develop')\n        exclude = {master, develop}\n    branches = list(set(git.branches()) - exclude)\n    for i, branch_name in enumerate(branches):\n        shell.cprint('<90>[{}] <33>{}'.format(i + 1, branch_name))\n    choice = 0\n    while choice < 1 or choice > len(branches):\n        prompt = \"Pick a base branch from the above [1-{}]\".format(\n            len(branches)\n        )\n        choice = click.prompt(prompt, value_proc=int)\n        if not (1 <= choice <= len(branches)):\n            fmt = \"Invalid choice {}, you must pick a number between {} and {}\"\n            log.err(fmt.format(choice, 1, len(branches)))\n    return branches[choice - 1]",
    "docstring": "Show the user a menu to pick a branch from the existing ones.\n\n    Args:\n        exclude (list[str]):\n            List of branch names to exclude from the menu. By default it will\n            exclude master and develop branches. To show all branches pass an\n            empty array here.\n\n    Returns:\n        str: The name of the branch chosen by the user. If the user inputs an\n        invalid choice, he will be asked again (and again) until he picks a\n        a valid branch."
  },
  {
    "code": "def shutdown(self):\n        status = self.can.close(self.handle)\n        if status != CANAL_ERROR_SUCCESS:\n            raise CanError(\"could not shut down bus: status == {}\".format(status))",
    "docstring": "Shuts down connection to the device safely.\n\n        :raise cam.CanError: is closing the connection did not work"
  },
  {
    "code": "def get_response_for_url(self, url):\n        if not url or \"//\" not in url:\n            raise ValueError(\"Missing or invalid url: %s\" % url)\n        render_url = self.BASE_URL + url\n        headers = {\n            'X-Prerender-Token': self.token,\n        }\n        r = self.session.get(render_url, headers=headers, allow_redirects=False)\n        assert r.status_code < 500\n        return self.build_django_response_from_requests_response(r)",
    "docstring": "Accepts a fully-qualified url.\n        Returns an HttpResponse, passing through all headers and the status code."
  },
  {
    "code": "def set_xml_output(self, xml_file):\n    if self.get_database() is None:\n      raise ValueError, \"no database specified\"\n    self.add_file_opt('extract', xml_file)\n    self.__xml_output = xml_file",
    "docstring": "Tell ligolw_sqlite to dump the contents of the database to a file."
  },
  {
    "code": "def get(self):\n        model = self.oracle.compute()\n        if model:\n            if self.htype == 'rc2':\n                self.hset = filter(lambda v: v > 0, model)\n            else:\n                self.hset = model\n            return list(map(lambda vid: self.idpool.id2obj[vid], self.hset))",
    "docstring": "This method computes and returns a hitting set. The hitting set is\n            obtained using the underlying oracle operating the MaxSAT problem\n            formulation. The computed solution is mapped back to objects of the\n            problem domain.\n\n            :rtype: list(obj)"
  },
  {
    "code": "def applications(self):\n        url = self._url + \"/applications\"\n        params = {\"f\" : \"json\"}\n        res = self._get(url=url,\n                           param_dict=params,\n                           proxy_url=self._proxy_url,\n                           proxy_port=self._proxy_port)\n        items = []\n        if \"applications\" in res.keys():\n            for apps in res['applications']:\n                items.append(\n                    self.Application(url=\"%s/%s\" % (self._url, apps['username']),\n                                     securityHandler=self._securityHandler,\n                                     proxy_url=self._proxy_url,\n                                     proxy_port=self._proxy_port)\n                )\n        return items",
    "docstring": "returns all the group applications to join"
  },
  {
    "code": "def pad_vocabulary(self, vocab, pad):\n        vocab_size = len(vocab)\n        padded_vocab_size = (vocab_size + pad - 1) // pad * pad\n        for i in range(0, padded_vocab_size - vocab_size):\n            token = f'madeupword{i:04d}'\n            vocab.append(token)\n        assert len(vocab) % pad == 0",
    "docstring": "Pads vocabulary to a multiple of 'pad' tokens.\n\n        :param vocab: list with vocabulary\n        :param pad: integer"
  },
  {
    "code": "def get_cert_builder(expires):\n    now = datetime.utcnow().replace(second=0, microsecond=0)\n    if expires is None:\n        expires = get_expires(expires, now=now)\n    expires = expires.replace(second=0, microsecond=0)\n    builder = x509.CertificateBuilder()\n    builder = builder.not_valid_before(now)\n    builder = builder.not_valid_after(expires)\n    builder = builder.serial_number(x509.random_serial_number())\n    return builder",
    "docstring": "Get a basic X509 cert builder object.\n\n    Parameters\n    ----------\n\n    expires : datetime\n        When this certificate will expire."
  },
  {
    "code": "def get_root_outcome_group(self):\n        from canvasapi.outcome import OutcomeGroup\n        response = self.__requester.request(\n            'GET',\n            'global/root_outcome_group'\n        )\n        return OutcomeGroup(self.__requester, response.json())",
    "docstring": "Redirect to root outcome group for context\n\n        :calls: `GET /api/v1/global/root_outcome_group \\\n        <https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.redirect>`_\n\n        :returns: The OutcomeGroup of the context.\n        :rtype: :class:`canvasapi.outcome.OutcomeGroup`"
  },
  {
    "code": "def process_tag(node):\n    text = ''\n    exceptions = ['table']\n    for element in node.children:\n        if isinstance(element, NavigableString):\n            text += element\n        elif not node.name in exceptions:\n            text += process_tag(element)\n    try:\n        convert_fn = globals()[\"convert_%s\" % node.name.lower()]\n        text = convert_fn(node, text)\n    except KeyError:\n        pass\n    return text",
    "docstring": "Recursively go through a tag's children, converting them, then\n    convert the tag itself."
  },
  {
    "code": "def webcam_attach(self, path, settings):\n        if not isinstance(path, basestring):\n            raise TypeError(\"path can only be an instance of type basestring\")\n        if not isinstance(settings, basestring):\n            raise TypeError(\"settings can only be an instance of type basestring\")\n        self._call(\"webcamAttach\",\n                     in_p=[path, settings])",
    "docstring": "Attaches the emulated USB webcam to the VM, which will use a host video capture device.\n\n        in path of type str\n            The host path of the capture device to use.\n\n        in settings of type str\n            Optional settings."
  },
  {
    "code": "def _uniq(self):\n        pd = []\n        for d in range(1, self.maxdepth):\n            pd.extend(map(lambda x: int(4**(d+1) + x), self.pixeldict[d]))\n        return sorted(pd)",
    "docstring": "Create a list of all the pixels that cover this region.\n        This list contains overlapping pixels of different orders.\n\n        Returns\n        -------\n        pix : list\n            A list of HEALPix pixel numbers."
  },
  {
    "code": "def preview(self, argv):\n        opts = cmdline(argv, FLAGS_RESULTS)\n        self.foreach(opts.args, lambda job: \n            output(job.preview(**opts.kwargs)))",
    "docstring": "Retrieve the preview for the specified search jobs."
  },
  {
    "code": "def get_database_columns(self, tables=None, database=None):\n        source = database if database else self.database\n        tables = tables if tables else self.tables\n        return {tbl: self.get_columns(tbl) for tbl in tqdm(tables, total=len(tables),\n                                                           desc='Getting {0} columns'.format(source))}",
    "docstring": "Retrieve a dictionary of columns."
  },
  {
    "code": "def get_cluster_view(p):\n    from cluster_helper import cluster as ipc\n    return ipc.cluster_view(p['scheduler'], p['queue'], p['num_jobs'], p['cores_per_job'], start_wait=p['timeout'], extra_params={\"resources\": p['resources'], \"mem\": p['mem'], \"tag\": p['tag'], \"run_local\": False})",
    "docstring": "get ipython running"
  },
  {
    "code": "def _check_and_uninstall_ruby(ret, ruby, user=None):\n    ret = _ruby_installed(ret, ruby, user=user)\n    if ret['result']:\n        if ret['default']:\n            __salt__['rbenv.default']('system', runas=user)\n        if __salt__['rbenv.uninstall_ruby'](ruby, runas=user):\n            ret['result'] = True\n            ret['changes'][ruby] = 'Uninstalled'\n            ret['comment'] = 'Successfully removed ruby'\n            return ret\n        else:\n            ret['result'] = False\n            ret['comment'] = 'Failed to uninstall ruby'\n            return ret\n    else:\n        ret['result'] = True\n        ret['comment'] = 'Ruby {0} is already absent'.format(ruby)\n    return ret",
    "docstring": "Verify that ruby is uninstalled"
  },
  {
    "code": "def lower_bollinger_band(data, period, std=2.0):\n    catch_errors.check_for_period_error(data, period)\n    period = int(period)\n    simple_ma = sma(data, period)[period-1:]\n    lower_bb = []\n    for idx in range(len(data) - period + 1):\n        std_dev = np.std(data[idx:idx + period])\n        lower_bb.append(simple_ma[idx] - std_dev * std)\n    lower_bb = fill_for_noncomputable_vals(data, lower_bb)\n    return np.array(lower_bb)",
    "docstring": "Lower Bollinger Band.\n\n    Formula:\n    u_bb = SMA(t) - STD(SMA(t-n:t)) * std_mult"
  },
  {
    "code": "def fetch_cache_key(request):\n        m = hashlib.md5()\n        m.update(request.body)\n        return m.hexdigest()",
    "docstring": "Returns a hashed cache key."
  },
  {
    "code": "def compare_files(path1, path2):\n    diff = difflib.ndiff(open(path1).readlines(), open(path2).readlines())\n    return [x for x in diff if x[0] in ['-', '+', '?']]",
    "docstring": "Returns the delta between two files using -, ?, + format excluding\n    lines that are the same\n\n    Args:\n        path1 (str): Path to first file\n        path2 (str): Path to second file\n\n    Returns:\n        List[str]: Delta between the two files"
  },
  {
    "code": "def _do_private_mode(FetcherClass, services, kwargs, random_wait_seconds, timeout, verbose):\n    addresses = kwargs.pop('addresses')\n    results = {}\n    with futures.ThreadPoolExecutor(max_workers=len(addresses)) as executor:\n        fetches = {}\n        for address in addresses:\n            k = kwargs\n            k['address'] = address\n            random.shuffle(services)\n            srv = FetcherClass(\n                services=services, verbose=verbose, timeout=timeout or 5.0,\n                random_wait_seconds=random_wait_seconds\n            )\n            fetches[executor.submit(srv.action, **k)] = (srv, address)\n        to_iterate = futures.as_completed(fetches)\n        for future in to_iterate:\n            service, address = fetches[future]\n            results[address] = future.result()\n    return results",
    "docstring": "Private mode is only applicable to address_balance, unspent_outputs, and\n    historical_transactions. There will always be a list for the `addresses`\n    argument. Each address goes to a random service. Also a random delay is\n    performed before the external fetch for improved privacy."
  },
  {
    "code": "def calculate_hash_of_dir(directory, file_list=None):\n    md5_hash = md5()\n    if not os.path.exists(directory):\n        return -1\n    try:\n        for subdir, dirs, files in os.walk(directory):\n            for _file in files:\n                file_path = os.path.join(subdir, _file)\n                if file_list is not None and file_path not in file_list:\n                    continue\n                try:\n                    _file_object = open(file_path, 'rb')\n                except Exception:\n                    _file_object.close()\n                    return -1\n                while 1:\n                    buf = _file_object.read(4096)\n                    if not buf:\n                        break\n                    md5_hash.update(md5(buf).hexdigest().encode())\n                _file_object.close()\n    except Exception:\n        return -1\n    return md5_hash.hexdigest()",
    "docstring": "Calculate hash of directory."
  },
  {
    "code": "def pool(self):\n        self._pool = self._pool or gevent.pool.Pool(size=self.pool_size)\n        return self._pool",
    "docstring": "Get an gevent pool used to dispatch requests."
  },
  {
    "code": "def _set_survey_scenario(self, survey_scenario):\n        self.survey_scenario = survey_scenario\n        if survey_scenario.simulation is None:\n            survey_scenario.simulation = survey_scenario.new_simulation()\n        period = self.period\n        self.filter_by = filter_by = survey_scenario.calculate_variable(\n            variable = self.filter_by_name, period = period)\n        self.weight_name = weight_name = self.survey_scenario.weight_column_name_by_entity['menage']\n        self.initial_weight_name = weight_name + \"_ini\"\n        self.initial_weight = initial_weight = survey_scenario.calculate_variable(\n            variable = weight_name, period = period)\n        self.initial_total_population = sum(initial_weight * filter_by)\n        self.weight = survey_scenario.calculate_variable(variable = weight_name, period = period)",
    "docstring": "Set survey scenario\n\n            :param survey_scenario: the survey scenario"
  },
  {
    "code": "def chord_counts(im):\n    r\n    labels, N = spim.label(im > 0)\n    props = regionprops(labels, coordinates='xy')\n    chord_lens = sp.array([i.filled_area for i in props])\n    return chord_lens",
    "docstring": "r\"\"\"\n    Finds the length of each chord in the supplied image and returns a list\n    of their individual sizes\n\n    Parameters\n    ----------\n    im : ND-array\n        An image containing chords drawn in the void space.\n\n    Returns\n    -------\n    result : 1D-array\n        A 1D array with one element for each chord, containing its length.\n\n    Notes\n    ----\n    The returned array can be passed to ``plt.hist`` to plot the histogram,\n    or to ``sp.histogram`` to get the histogram data directly. Another useful\n    function is ``sp.bincount`` which gives the number of chords of each\n    length in a format suitable for ``plt.plot``."
  },
  {
    "code": "def cycle_find_app(_parser, cmd, args):\n    parser = argparse.ArgumentParser(\n        prog=_parser.prog,\n        description=_parser.description,\n    )\n    parser.add_argument('-w', '--width', type=int, default=4, help='the length of the cycled value')\n    parser.add_argument('value', help='the value to determine the position of, read from stdin if missing', nargs='?')\n    args = parser.parse_args(args)\n    index = cycle_find(pwnypack.main.string_value_or_stdin(args.value), args.width)\n    if index == -1:\n        print('Not found.')\n        sys.exit(1)\n    else:\n        print('Found at position: %d' % index)",
    "docstring": "Find the first position of a value in a de Bruijn sequence."
  },
  {
    "code": "def _OpenCollectionPath(coll_path):\n  hunt_collection = results.HuntResultCollection(coll_path)\n  if hunt_collection and hunt_collection[0].payload:\n    return hunt_collection\n  indexed_collection = sequential_collection.GeneralIndexedCollection(coll_path)\n  if indexed_collection:\n    return indexed_collection",
    "docstring": "Tries to open various types of collections at the given path."
  },
  {
    "code": "def interface_to_relations(interface_name):\n    results = []\n    for role in ('provides', 'requires', 'peers'):\n        results.extend(role_and_interface_to_relations(role, interface_name))\n    return results",
    "docstring": "Given an interface, return a list of relation names for the current\n    charm that use that interface.\n\n    :returns: A list of relation names."
  },
  {
    "code": "def make_quantile_df(data, draw_quantiles):\n    dens = data['density'].cumsum() / data['density'].sum()\n    ecdf = interp1d(dens, data['y'], assume_sorted=True)\n    ys = ecdf(draw_quantiles)\n    violin_xminvs = interp1d(data['y'], data['xminv'])(ys)\n    violin_xmaxvs = interp1d(data['y'], data['xmaxv'])(ys)\n    data = pd.DataFrame({\n        'x': interleave(violin_xminvs, violin_xmaxvs),\n        'y': np.repeat(ys, 2),\n        'group': np.repeat(np.arange(1, len(ys)+1), 2)})\n    return data",
    "docstring": "Return a dataframe with info needed to draw quantile segments"
  },
  {
    "code": "def construct_blastall_cmdline(\n    fname1, fname2, outdir, blastall_exe=pyani_config.BLASTALL_DEFAULT\n):\n    fstem1 = os.path.splitext(os.path.split(fname1)[-1])[0]\n    fstem2 = os.path.splitext(os.path.split(fname2)[-1])[0]\n    fstem1 = fstem1.replace(\"-fragments\", \"\")\n    prefix = os.path.join(outdir, \"%s_vs_%s\" % (fstem1, fstem2))\n    cmd = (\n        \"{0} -p blastn -o {1}.blast_tab -i {2} -d {3} \"\n        + \"-X 150 -q -1 -F F -e 1e-15 \"\n        + \"-b 1 -v 1 -m 8\"\n    )\n    return cmd.format(blastall_exe, prefix, fname1, fname2)",
    "docstring": "Returns a single blastall command.\n\n    - blastall_exe - path to BLASTALL executable"
  },
  {
    "code": "def shot_start_data(shot, role):\n    if role == QtCore.Qt.DisplayRole:\n        return str(shot.startframe)",
    "docstring": "Return the data for startframe\n\n    :param shot: the shot that holds the data\n    :type shot: :class:`jukeboxcore.djadapter.models.Shot`\n    :param role: item data role\n    :type role: QtCore.Qt.ItemDataRole\n    :returns: data for the start\n    :rtype: depending on role\n    :raises: None"
  },
  {
    "code": "def emit_toi_stats(toi_set, peripherals):\n    count_by_zoom = defaultdict(int)\n    total = 0\n    for coord_int in toi_set:\n        coord = coord_unmarshall_int(coord_int)\n        count_by_zoom[coord.zoom] += 1\n        total += 1\n    peripherals.stats.gauge('tiles-of-interest.count', total)\n    for zoom, count in count_by_zoom.items():\n        peripherals.stats.gauge(\n            'tiles-of-interest.by-zoom.z{:02d}'.format(zoom),\n            count\n        )",
    "docstring": "Calculates new TOI stats and emits them via statsd."
  },
  {
    "code": "def fd_taper(out, start, end, beta=8, side='left'):\n    out = out.copy()\n    width = end - start\n    winlen = 2 * int(width / out.delta_f)\n    window = Array(signal.get_window(('kaiser', beta), winlen))\n    kmin = int(start / out.delta_f)\n    kmax = kmin + winlen//2\n    if side == 'left':\n        out[kmin:kmax] *= window[:winlen//2]\n        out[:kmin] *= 0.\n    elif side == 'right':\n        out[kmin:kmax] *= window[winlen//2:]\n        out[kmax:] *= 0.\n    else:\n        raise ValueError(\"unrecognized side argument {}\".format(side))\n    return out",
    "docstring": "Applies a taper to the given FrequencySeries.\n\n    A half-kaiser window is used for the roll-off.\n\n    Parameters\n    ----------\n    out : FrequencySeries\n        The ``FrequencySeries`` to taper.\n    start : float\n        The frequency (in Hz) to start the taper window.\n    end : float\n        The frequency (in Hz) to end the taper window.\n    beta : int, optional\n        The beta parameter to use for the Kaiser window. See\n        ``scipy.signal.kaiser`` for details. Default is 8.\n    side : {'left', 'right'}\n        The side to apply the taper to. If ``'left'`` (``'right'``), the taper\n        will roll up (down) between ``start`` and ``end``, with all values\n        before ``start`` (after ``end``) set to zero. Default is ``'left'``.\n\n    Returns\n    -------\n    FrequencySeries\n        The tapered frequency series."
  },
  {
    "code": "def setNamedItem(self, item: Attr) -> None:\n        from wdom.web_node import WdomElement\n        if not isinstance(item, Attr):\n            raise TypeError('item must be an instance of Attr')\n        if isinstance(self._owner, WdomElement):\n            self._owner.js_exec('setAttribute', item.name,\n                                item.value)\n        self._dict[item.name] = item\n        item._owner = self._owner",
    "docstring": "Set ``Attr`` object in this collection."
  },
  {
    "code": "def from_T050017(cls, url, coltype = LIGOTimeGPS):\n\t\tmatch = cls._url_regex.search(url)\n\t\tif not match:\n\t\t\traise ValueError(\"could not convert %s to CacheEntry\" % repr(url))\n\t\tobservatory = match.group(\"obs\")\n\t\tdescription = match.group(\"dsc\")\n\t\tstart = match.group(\"strt\")\n\t\tduration = match.group(\"dur\")\n\t\tif start == \"-\" and duration == \"-\":\n\t\t\tsegment = None\n\t\telse:\n\t\t\tsegment = segments.segment(coltype(start), coltype(start) + coltype(duration))\n\t\treturn cls(observatory, description, segment, url)",
    "docstring": "Parse a URL in the style of T050017-00 into a CacheEntry.\n\t\tThe T050017-00 file name format is, essentially,\n\n\t\tobservatory-description-start-duration.extension\n\n\t\tExample:\n\n\t\t>>> c = CacheEntry.from_T050017(\"file://localhost/data/node144/frames/S5/strain-L2/LLO/L-L1_RDS_C03_L2-8365/L-L1_RDS_C03_L2-836562330-83.gwf\")\n\t\t>>> c.observatory\n\t\t'L'\n\t\t>>> c.host\n\t\t'localhost'\n\t\t>>> os.path.basename(c.path)\n\t\t'L-L1_RDS_C03_L2-836562330-83.gwf'"
  },
  {
    "code": "def connection_sync(self, connection_id, connProps=None):\n        if connProps is None:\n            connProps = {}\n        request = requests_pb2.ConnectionSyncRequest()\n        request.connection_id = connection_id\n        request.conn_props.auto_commit = connProps.get('autoCommit', False)\n        request.conn_props.has_auto_commit = True\n        request.conn_props.read_only = connProps.get('readOnly', False)\n        request.conn_props.has_read_only = True\n        request.conn_props.transaction_isolation = connProps.get('transactionIsolation', 0)\n        request.conn_props.catalog = connProps.get('catalog', '')\n        request.conn_props.schema = connProps.get('schema', '')\n        response_data = self._apply(request)\n        response = responses_pb2.ConnectionSyncResponse()\n        response.ParseFromString(response_data)\n        return response.conn_props",
    "docstring": "Synchronizes connection properties with the server.\n\n        :param connection_id:\n            ID of the current connection.\n\n        :param connProps:\n            Dictionary with the properties that should be changed.\n\n        :returns:\n            A ``common_pb2.ConnectionProperties`` object."
  },
  {
    "code": "def attach(domain, filename):\n    log.info('Attaching datasets for domain %s', domain)\n    result = actions.attach(domain, filename)\n    log.info('Attached %s datasets to %s', result.success, domain)",
    "docstring": "Attach existing datasets to their harvest remote id\n\n    Mapping between identifiers should be in FILENAME CSV file."
  },
  {
    "code": "def create_md5(path):\n    m = hashlib.md5()\n    with open(path, \"rb\") as f:\n        while True:\n            data = f.read(8192)\n            if not data:\n                break\n            m.update(data)\n    return m.hexdigest()",
    "docstring": "Create the md5 hash of a file using the hashlib library."
  },
  {
    "code": "def recover_all(lbn, profile='default'):\n    ret = {}\n    config = get_running(profile)\n    try:\n        workers_ = config['worker.{0}.balance_workers'.format(lbn)].split(',')\n    except KeyError:\n        return ret\n    for worker in workers_:\n        curr_state = worker_status(worker, profile)\n        if curr_state['activation'] != 'ACT':\n            worker_activate(worker, lbn, profile)\n        if not curr_state['state'].startswith('OK'):\n            worker_recover(worker, lbn, profile)\n        ret[worker] = worker_status(worker, profile)\n    return ret",
    "docstring": "Set the all the workers in lbn to recover and activate them if they are not\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt '*' modjk.recover_all loadbalancer1\n        salt '*' modjk.recover_all loadbalancer1 other-profile"
  },
  {
    "code": "def split_qname(self, cybox_id):\n        if ':' in cybox_id:\n            (namespace, uid) = cybox_id.split(':', 1)\n        else:\n            namespace = None\n            uid = cybox_id\n        if namespace and namespace in self.namespace_dict:\n            namespace_uri = self.namespace_dict[namespace]\n        else:\n            logger.warning(\"Could not retrieve namespace for identifier %s\" % (cybox_id))\n            namespace_uri = None\n        if not namespace_uri:\n            if self.default_identifier_ns_uri:\n                namespace_uri = self.default_identifier_ns_uri\n            else:\n                namespace_uri = \"%s/%s\" % (DINGOS_MISSING_ID_NAMESPACE_URI_PREFIX, namespace)\n        return (namespace, namespace_uri, uid)",
    "docstring": "Separate the namespace from the identifier in a qualified name and lookup the namespace URI associated\n        with the given namespace."
  },
  {
    "code": "def _build_meta(meta: str, pipelines: Iterable['Pipeline']) -> 'Pipeline':\n        return Pipeline(protocol=[\n            {\n                'meta': meta,\n                'pipelines': [\n                    pipeline.protocol\n                    for pipeline in pipelines\n                ]\n            },\n        ])",
    "docstring": "Build a pipeline with a given meta-argument.\n\n        :param meta: either union or intersection\n        :param pipelines:"
  },
  {
    "code": "def load(cls, path: str, password: str = None) -> 'Account':\n        with open(path) as f:\n            keystore = json.load(f)\n        if not check_keystore_json(keystore):\n            raise ValueError('Invalid keystore file')\n        return Account(keystore, password, path=path)",
    "docstring": "Load an account from a keystore file.\n\n        Args:\n            path: full path to the keyfile\n            password: the password to decrypt the key file or `None` to leave it encrypted"
  },
  {
    "code": "def initialize(self, calc_reg):\n        self._isinitialized = True\n        self.calc_order = topological_sort(calc_reg.dependencies)",
    "docstring": "Initialize the simulation. Organize calculations by dependency.\n\n        :param calc_reg: Calculation registry.\n        :type calc_reg:\n            :class:`~simkit.core.calculation.CalcRegistry`"
  },
  {
    "code": "def docs(root_url, path):\n    root_url = root_url.rstrip('/')\n    path = path.lstrip('/')\n    if root_url == OLD_ROOT_URL:\n        return 'https://docs.taskcluster.net/{}'.format(path)\n    else:\n        return '{}/docs/{}'.format(root_url, path)",
    "docstring": "Generate URL for path in the Taskcluster docs."
  },
  {
    "code": "def logical_intf_helper(interface):\n    if interface is None:\n        return LogicalInterface.get_or_create(name='default_eth').href\n    elif isinstance(interface, LogicalInterface):\n        return interface.href\n    elif interface.startswith('http'):\n        return interface\n    return LogicalInterface.get_or_create(name=interface).href",
    "docstring": "Logical Interface finder by name. Create if it doesn't exist.\n    This is useful when adding logical interfaces to for inline\n    or capture interfaces.\n\n    :param interface: logical interface name\n    :return str href: href of logical interface"
  },
  {
    "code": "def error_handler(task):\n    @wraps(task)\n    def wrapper(self, *args, **kwargs):\n        try:\n            return task(self, *args, **kwargs)\n        except Exception as e:\n            self.connected = False\n            if not self.testing:\n                exc_type, exc_obj, exc_tb = sys.exc_info()\n                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n                error_message = (\n                    \"[\" + str(datetime.now()) + \"] Error in task \\\"\" +\n                    task.__name__ + \"\\\" (\" +\n                    fname + \"/\" + str(exc_tb.tb_lineno) +\n                    \")\" + e.message\n                )\n                self.logger.error(\"%s: RPC instruction failed\" % error_message)\n    return wrapper",
    "docstring": "Handle and log RPC errors."
  },
  {
    "code": "def GenerateFileData(self):\n    while 1:\n      line = self.rfile.readline()\n      chunk_size = int(line.split(\";\")[0], 16)\n      if chunk_size == 0:\n        break\n      for chunk in self._GenerateChunk(chunk_size):\n        yield chunk\n      lf = self.rfile.read(2)\n      if lf != \"\\r\\n\":\n        raise IOError(\"Unable to parse chunk.\")\n    for header in self.rfile.readline():\n      if not header:\n        break",
    "docstring": "Generates the file data for a chunk encoded file."
  },
  {
    "code": "def to_yaml(value, pretty=False):\n    if not yaml:\n        raise NotImplementedError('No supported YAML library available')\n    options = {\n        'Dumper': BasicYamlDumper,\n        'allow_unicode': True,\n    }\n    options['default_flow_style'] = not pretty\n    return yaml.dump(value, **options).rstrip()",
    "docstring": "Serializes the given value to YAML.\n\n    :param value: the value to serialize\n    :param pretty:\n        whether or not to format the output in a more human-readable way; if\n        not specified, defaults to ``False``\n    :type pretty: bool\n    :rtype: str"
  },
  {
    "code": "def set_backend(self, backend):\n        if isinstance(backend, str):\n            name = backend\n            args = []\n            kwargs = {}\n        elif isinstance(backend, (tuple, list)):\n            name = ''\n            args = []\n            kwargs = {}\n            for i in range(len(backend)):\n                if i == 0:\n                    name = backend[i]\n                else:\n                    if isinstance(backend[i], dict):\n                        kwargs.update(backend[i])\n                    else:\n                        args += backend[i]\n        else:\n            raise TypeError(\"Backend must be string, tuple, or list\")\n        if name in available_backends:\n            self.backend = name\n            self._backend = available_backends[name]()\n        elif name is None:\n            raise Exception((\"A backend (e.g. 'jNeuroML' or 'NEURON') \"\n                             \"must be selected\"))\n        else:\n            raise Exception(\"Backend %s not found in backends.py\"\n                            % name)\n        self._backend.model = self\n        self._backend.init_backend(*args, **kwargs)",
    "docstring": "Set the simulation backend."
  },
  {
    "code": "def eigvalsh(a, eigvec=False):\n    if eigvec == True:\n        val, vec = eigh(a, eigvec=True)\n        return val, gvar.mean(vec)\n    else:\n        return eigh(a, eigvec=False)",
    "docstring": "Eigenvalues of Hermitian matrix ``a``.\n\n    Args:\n        a: Two-dimensional, square Hermitian matrix/array of numbers\n            and/or :class:`gvar.GVar`\\s. Array elements must be\n            real-valued if `gvar.GVar`\\s are involved (i.e., symmetric\n            matrix).\n        eigvec (bool): If ``True``, method returns a tuple of arrays\n            ``(val, vec)`` where ``val[i]`` are the\n            eigenvalues of ``a``, and ``vec[:, i]`` are the mean\n            values of the corresponding eigenvectors. Only ``val`` is\n            returned if ``eigvec=False`` (default).\n\n    Returns:\n        Array ``val`` of eigenvalues of matrix ``a`` if parameter\n        ``eigvec==False`` (default); otherwise a tuple of\n        arrays ``(val, vec)`` where ``val[i]`` are the eigenvalues\n        (in ascending order) and ``vec[:, i]`` are the mean values\n        of the corresponding eigenvectors.\n\n    Raises:\n        ValueError: If matrix is not square and two-dimensional."
  },
  {
    "code": "def elevation_along_path(client, path, samples):\n    if type(path) is str:\n        path = \"enc:%s\" % path\n    else:\n        path = convert.shortest_path(path)\n    params = {\n        \"path\": path,\n        \"samples\": samples\n    }\n    return client._request(\"/maps/api/elevation/json\", params).get(\"results\", [])",
    "docstring": "Provides elevation data sampled along a path on the surface of the earth.\n\n    :param path: An encoded polyline string, or a list of latitude/longitude\n        values from which you wish to calculate elevation data.\n    :type path: string, dict, list, or tuple\n\n    :param samples: The number of sample points along a path for which to\n        return elevation data.\n    :type samples: int\n\n    :rtype: list of elevation data responses"
  },
  {
    "code": "def JsonResponseModel(self):\n        old_model = self.response_type_model\n        self.__response_type_model = 'json'\n        yield\n        self.__response_type_model = old_model",
    "docstring": "In this context, return raw JSON instead of proto."
  },
  {
    "code": "def get_knowledge_base(project_id, knowledge_base_id):\n    import dialogflow_v2beta1 as dialogflow\n    client = dialogflow.KnowledgeBasesClient()\n    knowledge_base_path = client.knowledge_base_path(\n        project_id, knowledge_base_id)\n    response = client.get_knowledge_base(knowledge_base_path)\n    print('Got Knowledge Base:')\n    print(' - Display Name: {}'.format(response.display_name))\n    print(' - Knowledge ID: {}'.format(response.name))",
    "docstring": "Gets a specific Knowledge base.\n\n    Args:\n        project_id: The GCP project linked with the agent.\n        knowledge_base_id: Id of the Knowledge base."
  },
  {
    "code": "def on_leave(self):\n        if self.roomId != '-1':\n            logging.debug('chat: leave room (roomId: %s)' % self.roomId)\n            self.publishToOther(self.roomId, 'leave', {\n                'username': self.username\n            })\n            self.leave(self.roomId)\n        self.initialize()",
    "docstring": "Quit chat room"
  },
  {
    "code": "def _display_choices(self, choices):\n        print(\"Choose the number of the correct choice:\")\n        choice_map = {}\n        for i, choice in enumerate(choices):\n            i = str(i)\n            print('{}) {}'.format(i, format.indent(choice,\n                                                   ' ' * (len(i) + 2)).strip()))\n            choice = format.normalize(choice)\n            choice_map[i] = choice\n        return choice_map",
    "docstring": "Prints a mapping of numbers to choices and returns the\n        mapping as a dictionary."
  },
  {
    "code": "def get_all(self):\n        for name, values in self._map.items():\n            for value in values:\n                yield (name, value)",
    "docstring": "Return an iterator of name-value pairs."
  },
  {
    "code": "def _parse_body(self, body):\n    if is_python3():\n      return json.loads(body.decode('UTF-8'))\n    else:\n      return json.loads(body)",
    "docstring": "For just call a deserializer for FORMAT"
  },
  {
    "code": "def get_election_electoral_votes(self, election):\n        candidate_election = CandidateElection.objects.get(\n            candidate=self, election=election\n        )\n        return candidate_election.electoral_votes.all()",
    "docstring": "Get all electoral votes for this candidate in an election."
  },
  {
    "code": "def pad_block(block, block_size):\n    unique_vals, unique_counts = np.unique(block, return_counts=True)\n    most_frequent_value = unique_vals[np.argmax(unique_counts)]\n    return np.pad(block,\n                  tuple((0, desired_size - actual_size)\n                        for desired_size, actual_size\n                        in zip(block_size, block.shape)),\n                  mode=\"constant\", constant_values=most_frequent_value)",
    "docstring": "Pad a block to block_size with its most frequent value"
  },
  {
    "code": "def set_payload_format(self, payload_format):\n        request = {\n            \"command\": \"payload_format\",\n            \"format\": payload_format\n        }\n        status = self._check_command_response_status(request)\n        self.format = payload_format\n        return status",
    "docstring": "Set the payload format for messages sent to and from the VI.\n\n        Returns True if the command was successful."
  },
  {
    "code": "def validate_unique(self, exclude=None):\n        errors = {}\n        try:\n            super(TranslatableModelMixin, self).validate_unique(exclude=exclude)\n        except ValidationError as e:\n            errors = e.message_dict\n        for local_cache in six.itervalues(self._translations_cache):\n            for translation in six.itervalues(local_cache):\n                if is_missing(translation):\n                    continue\n                try:\n                    translation.validate_unique(exclude=exclude)\n                except ValidationError as e:\n                    errors.update(e.message_dict)\n        if errors:\n            raise ValidationError(errors)",
    "docstring": "Also validate the unique_together of the translated model."
  },
  {
    "code": "def vertex_normals(self):\n        assert hasattr(self.faces_sparse, 'dot')\n        vertex_normals = geometry.mean_vertex_normals(\n            vertex_count=len(self.vertices),\n            faces=self.faces,\n            face_normals=self.face_normals,\n            sparse=self.faces_sparse)\n        return vertex_normals",
    "docstring": "The vertex normals of the mesh. If the normals were loaded\n        we check to make sure we have the same number of vertex\n        normals and vertices before returning them. If there are\n        no vertex normals defined or a shape mismatch we  calculate\n        the vertex normals from the mean normals of the faces the\n        vertex is used in.\n\n        Returns\n        ----------\n        vertex_normals : (n,3) float\n          Represents the surface normal at each vertex.\n          Where n == len(self.vertices)"
  },
  {
    "code": "def contribute_to_related_class(self, cls, related):\n        super(VersionedForeignKey, self).contribute_to_related_class(cls,\n                                                                     related)\n        accessor_name = related.get_accessor_name()\n        if hasattr(cls, accessor_name):\n            setattr(cls, accessor_name,\n                    VersionedReverseManyToOneDescriptor(related))",
    "docstring": "Override ForeignKey's methods, and replace the descriptor, if set by\n        the parent's methods"
  },
  {
    "code": "def raise_(tp, value=None, tb=None):\n    if value is not None and isinstance(tp, Exception):\n        raise TypeError(\"instance exception may not have a separate value\")\n    if value is not None:\n        exc = tp(value)\n    else:\n        exc = tp\n    if exc.__traceback__ is not tb:\n        raise exc.with_traceback(tb)\n    raise exc",
    "docstring": "A function that matches the Python 2.x ``raise`` statement. This\n    allows re-raising exceptions with the cls value and traceback on\n    Python 2 and 3."
  },
  {
    "code": "def load_tensor(f, format=None):\n    s = _load_bytes(f)\n    return load_tensor_from_string(s, format=format)",
    "docstring": "Loads a serialized TensorProto into memory\n\n    @params\n    f can be a file-like object (has \"read\" function) or a string containing a file name\n    format is for future use\n\n    @return\n    Loaded in-memory TensorProto"
  },
  {
    "code": "def traverse_dependency_graph(self, ref, collector, memo=None):\n    resolved_ref = self.refs_by_unversioned_refs.get(ref.unversioned)\n    if resolved_ref:\n      ref = resolved_ref\n    if memo is None:\n      memo = dict()\n    visited = set()\n    return self._do_traverse_dependency_graph(ref, collector, memo, visited)",
    "docstring": "Traverses module graph, starting with ref, collecting values for each ref into the sets\n    created by the collector function.\n\n    :param ref an IvyModuleRef to start traversing the ivy dependency graph\n    :param collector a function that takes a ref and returns a new set of values to collect for\n           that ref, which will also be updated with all the dependencies accumulated values\n    :param memo is a dict of ref -> set that memoizes the results of each node in the graph.\n           If provided, allows for retaining cache across calls.\n    :returns the accumulated set for ref"
  },
  {
    "code": "def full_info(**kwargs):\n    conn = __get_conn(**kwargs)\n    info = {'freecpu': _freecpu(conn),\n            'freemem': _freemem(conn),\n            'node_info': _node_info(conn),\n            'vm_info': vm_info()}\n    conn.close()\n    return info",
    "docstring": "Return the node_info, vm_info and freemem\n\n    :param connection: libvirt connection URI, overriding defaults\n\n        .. versionadded:: 2019.2.0\n    :param username: username to connect with, overriding defaults\n\n        .. versionadded:: 2019.2.0\n    :param password: password to connect with, overriding defaults\n\n        .. versionadded:: 2019.2.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' virt.full_info"
  },
  {
    "code": "def qc_data(self, tests, alias=None):\n        r = {m: c.quality(tests, alias) for m, c in self.data.items()}\n        s = self.qc_curve_group(tests, alias=alias)\n        for m, results in r.items():\n            if m in s:\n                results.update(s[m])\n        return r",
    "docstring": "Run a series of tests against the data and return the corresponding\n        results.\n\n        Args:\n            tests (list): a list of functions.\n\n        Returns:\n            list. The results. Stick to booleans (True = pass) or ints."
  },
  {
    "code": "def serialize(obj, **options):\n    try:\n        if 'file_out' in options:\n            return toml.dump(obj, options['file_out'], **options)\n        else:\n            return toml.dumps(obj, **options)\n    except Exception as error:\n        raise SerializationError(error)",
    "docstring": "Serialize Python data to TOML.\n\n    :param obj: the data structure to serialize.\n    :param options: options given to lower pytoml module."
  },
  {
    "code": "def is_ancestor(self, ancestor_rev, rev):\n        try:\n            self.git.merge_base(ancestor_rev, rev, is_ancestor=True)\n        except GitCommandError as err:\n            if err.status == 1:\n                return False\n            raise\n        return True",
    "docstring": "Check if a commit  is an ancestor of another\n\n        :param ancestor_rev: Rev which should be an ancestor\n        :param rev: Rev to test against ancestor_rev\n        :return: ``True``, ancestor_rev is an accestor to rev."
  },
  {
    "code": "def append_sfixed64(self, value):\n        sign = (value & 0x8000000000000000) and -1 or 0\n        if value >> 64 != sign:\n            raise errors.EncodeError('SFixed64 out of range: %d' % value)\n        self._stream.append_little_endian64(value & 0xffffffffffffffff)",
    "docstring": "Appends a signed 64-bit integer to our buffer, in little-endian\n        byte-order."
  },
  {
    "code": "def d8distdowntostream(np, p, fel, src, dist, distancemethod, thresh, workingdir=None,\n                           mpiexedir=None, exedir=None,\n                           log_file=None, runtime_file=None, hostfile=None):\n        fname = TauDEM.func_name('d8distdowntostream')\n        return TauDEM.run(FileClass.get_executable_fullpath(fname, exedir),\n                          {'-fel': fel, '-p': p, '-src': src},\n                          workingdir,\n                          {'-thresh': thresh, '-m': TauDEM.convertdistmethod(distancemethod)},\n                          {'-dist': dist},\n                          {'mpipath': mpiexedir, 'hostfile': hostfile, 'n': np},\n                          {'logfile': log_file, 'runtimefile': runtime_file})",
    "docstring": "Run D8 distance down to stream by different method for distance.\n        This function is extended from d8hdisttostrm by Liangjun.\n\n        Please clone `TauDEM by lreis2415`_ and compile for this program.\n\n        .. _TauDEM by lreis2415:\n           https://github.com/lreis2415/TauDEM"
  },
  {
    "code": "def on_master_missing(self):\n        self.info(\"We could not contact the master agency, starting a new one\")\n        if self._starting_master:\n            self.info(\"Master already starting, waiting for it\")\n            return\n        if self._shutdown_task is not None:\n            self.info(\"Not spwaning master because we are about to terminate \"\n                      \"ourselves\")\n            return\n        if self._startup_task is not None:\n            raise error.FeatError(\"Standalone started without a previous \"\n                                  \"master agency already running, terminating \"\n                                  \"it\")\n        if self._acquire_lock():\n            self._starting_master = True\n            self._release_lock_cl = time.callLater(10, self._release_lock)\n            return self._spawn_agency('master')",
    "docstring": "Tries to spawn a master agency if the slave agency failed to connect\n        for several times. To avoid several slave agencies spawning the master\n        agency a file lock is used"
  },
  {
    "code": "def add_synonym(self, syn):\n        n = self.node(syn.class_id)\n        if 'meta' not in n:\n            n['meta'] = {}\n        meta = n['meta']\n        if 'synonyms' not in meta:\n            meta['synonyms'] = []\n        meta['synonyms'].append(syn.as_dict())",
    "docstring": "Adds a synonym for a node"
  },
  {
    "code": "def parse_lines(self, lines: Iterable[str]) -> List[ParseResults]:\n        return [\n            self.parseString(line, line_number)\n            for line_number, line in enumerate(lines)\n        ]",
    "docstring": "Parse multiple lines in succession."
  },
  {
    "code": "def format_diff_xml(a_xml, b_xml):\n    return '\\n'.join(\n        difflib.ndiff(\n            reformat_to_pretty_xml(a_xml).splitlines(),\n            reformat_to_pretty_xml(b_xml).splitlines(),\n        )\n    )",
    "docstring": "Create a diff between two XML documents.\n\n    Args:\n      a_xml: str\n      b_xml: str\n\n    Returns:\n      str : `Differ`-style delta"
  },
  {
    "code": "def _colorize(self, msg, color=None, encode=False):\n        colors = {\n            'red':    '31',\n            'green':  '32',\n            'yellow': '33'\n        }\n        if not color or not color in colors:\n            return msg\n        if encode:\n            return u'\\x1b[1;{}m{}\\x1b[0m'.format(colors[color], msg)\n        return '\\x1b[1;{}m{}\\x1b[0m'.format(colors[color], msg)",
    "docstring": "Colorize a string."
  },
  {
    "code": "def close(self):\n        if self.is_connected:\n            self.client.close()\n            if self.forward_agent and self._agent_handler is not None:\n                self._agent_handler.close()",
    "docstring": "Terminate the network connection to the remote end, if open.\n\n        If no connection is open, this method does nothing.\n\n        .. versionadded:: 2.0"
  },
  {
    "code": "def attach(func, params):\n\tsig = inspect.signature(func)\n\tparams = Projection(sig.parameters.keys(), params)\n\treturn functools.partial(func, **params)",
    "docstring": "Given a function and a namespace of possible parameters,\n\tbind any params matching the signature of the function\n\tto that function."
  },
  {
    "code": "def request_data(key, url, file, string_content, start, end, fix_apple):\n    data = []\n    try:\n        data += events(url=url, file=file, string_content=string_content,\n                       start=start, end=end, fix_apple=fix_apple)\n    finally:\n        update_events(key, data)\n        request_finished(key)",
    "docstring": "Request data, update local data cache and remove this Thread form queue.\n\n    :param key: key for data source to get result later\n    :param url: iCal URL\n    :param file: iCal file path\n    :param string_content: iCal content as string\n    :param start: start date\n    :param end: end date\n    :param fix_apple: fix known Apple iCal issues"
  },
  {
    "code": "def intern(obj, timeout):\n    core.gear.timeout = timeout\n    core.gear.pool.append(obj)",
    "docstring": "Tell untwisted to process an extern event\n    loop."
  },
  {
    "code": "def text(self, prompt, default=None):\n        prompt = prompt if prompt is not None else 'Enter some text'\n        prompt += \" [{0}]: \".format(default) if default is not None else ': '\n        return self.input(curry(filter_text, default=default), prompt)",
    "docstring": "Prompts the user for some text, with optional default"
  },
  {
    "code": "def reshape(self, *shape):\n        if prod(self.shape) != prod(shape):\n            raise ValueError(\"Reshaping must leave the number of elements unchanged\")\n        if self.shape[-1] != shape[-1]:\n            raise ValueError(\"Reshaping cannot change the size of the constituent series (last dimension)\")\n        if self.labels is not None:\n            newlabels = self.labels.reshape(*shape[:-1])\n        else:\n            newlabels = None\n        return self._constructor(self.values.reshape(shape), labels=newlabels).__finalize__(self, noprop=('labels',))",
    "docstring": "Reshape the Series object\n\n        Cannot change the last dimension.\n\n        Parameters\n        ----------\n        shape: one or more ints\n            New shape"
  },
  {
    "code": "def apply_default_constraints(self):\n        try:\n            self.apply_secthresh(pipeline_weaksec(self.koi))\n        except NoWeakSecondaryError:\n            logging.warning('No secondary eclipse threshold set for {}'.format(self.koi))\n        self.set_maxrad(default_r_exclusion(self.koi))",
    "docstring": "Applies default secthresh & exclusion radius constraints"
  },
  {
    "code": "def future_set_exception_unless_cancelled(\n    future: \"Union[futures.Future[_T], Future[_T]]\", exc: BaseException\n) -> None:\n    if not future.cancelled():\n        future.set_exception(exc)\n    else:\n        app_log.error(\"Exception after Future was cancelled\", exc_info=exc)",
    "docstring": "Set the given ``exc`` as the `Future`'s exception.\n\n    If the Future is already canceled, logs the exception instead. If\n    this logging is not desired, the caller should explicitly check\n    the state of the Future and call ``Future.set_exception`` instead of\n    this wrapper.\n\n    Avoids ``asyncio.InvalidStateError`` when calling ``set_exception()`` on\n    a cancelled `asyncio.Future`.\n\n    .. versionadded:: 6.0"
  },
  {
    "code": "def image_url(self):\n        return construct_api_url(self.input, 'image', self.resolvers, False, self.get3d, False, **self.kwargs)",
    "docstring": "URL of a GIF image."
  },
  {
    "code": "def drop(self, *column_or_columns):\n        exclude = _varargs_labels_as_list(column_or_columns)\n        return self.select([c for (i, c) in enumerate(self.labels)\n                            if i not in exclude and c not in exclude])",
    "docstring": "Return a Table with only columns other than selected label or\n        labels.\n\n        Args:\n            ``column_or_columns`` (string or list of strings): The header\n            names or indices of the columns to be dropped.\n\n            ``column_or_columns`` must be an existing header name, or a\n            valid column index.\n\n        Returns:\n            An instance of ``Table`` with given columns removed.\n\n        >>> t = Table().with_columns(\n        ...     'burgers',  make_array('cheeseburger', 'hamburger', 'veggie burger'),\n        ...     'prices',   make_array(6, 5, 5),\n        ...     'calories', make_array(743, 651, 582))\n        >>> t\n        burgers       | prices | calories\n        cheeseburger  | 6      | 743\n        hamburger     | 5      | 651\n        veggie burger | 5      | 582\n        >>> t.drop('prices')\n        burgers       | calories\n        cheeseburger  | 743\n        hamburger     | 651\n        veggie burger | 582\n        >>> t.drop(['burgers', 'calories'])\n        prices\n        6\n        5\n        5\n        >>> t.drop('burgers', 'calories')\n        prices\n        6\n        5\n        5\n        >>> t.drop([0, 2])\n        prices\n        6\n        5\n        5\n        >>> t.drop(0, 2)\n        prices\n        6\n        5\n        5\n        >>> t.drop(1)\n        burgers       | calories\n        cheeseburger  | 743\n        hamburger     | 651\n        veggie burger | 582"
  },
  {
    "code": "def get_comment_collection(cmt_id):\n    query = \n    recid = run_sql(query, (cmt_id,))\n    record_primary_collection = guess_primary_collection_of_a_record(\n        recid[0][0])\n    return record_primary_collection",
    "docstring": "Extract the collection where the comment is written"
  },
  {
    "code": "def sign(self, payload):\n        if self.authenticator:\n            return self.authenticator.signed(payload)\n        return payload",
    "docstring": "Sign payload using the supplied authenticator"
  },
  {
    "code": "def _clean_schema_fields(self, fields):\n        fields_sorted = sorted(fields, key=lambda field: field[\"name\"])\n        return [\n            {\"name\": field[\"name\"], \"type\": field[\"type\"]}\n            for field in fields_sorted\n        ]",
    "docstring": "Return a sanitized version of the schema for comparisons."
  },
  {
    "code": "def missing_db_response(func):\n    @wraps(func)\n    def with_exception_handling(*args, **kwargs):\n        try:\n            return func(*args, **kwargs)\n        except ConnectionError as error:\n            return (dict(error='Unable to connect to Configuration Db.',\n                         error_message=str(error),\n                         links=dict(root='{}'.format(get_root_url()))),\n                    HTTPStatus.NOT_FOUND)\n    return with_exception_handling",
    "docstring": "Decorator to check connection exceptions"
  },
  {
    "code": "def wait(self):\n        self.thread.join()\n        if self.error is not None:\n            return self.error\n        return self.result",
    "docstring": "Wait for the request to finish and return the result or error when finished\n\n        :returns: result or error\n        :type: result tyoe or Error"
  },
  {
    "code": "def languages(self, **kwargs):\n        path = '/projects/%s/languages' % self.get_id()\n        return self.manager.gitlab.http_get(path, **kwargs)",
    "docstring": "Get languages used in the project with percentage value.\n\n        Args:\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabGetError: If the server failed to perform the request"
  },
  {
    "code": "def pngout(ext_args):\n    args = _PNGOUT_ARGS + [ext_args.old_filename, ext_args.new_filename]\n    extern.run_ext(args)\n    return _PNG_FORMAT",
    "docstring": "Run the external program pngout on the file."
  },
  {
    "code": "def specs_to_ir(specs, version='0.1b1', debug=False, route_whitelist_filter=None):\n    parser_factory = ParserFactory(debug=debug)\n    partial_asts = []\n    for path, text in specs:\n        logger.info('Parsing spec %s', path)\n        parser = parser_factory.get_parser()\n        if debug:\n            parser.test_lexing(text)\n        partial_ast = parser.parse(text, path)\n        if parser.got_errors_parsing():\n            msg, lineno, path = parser.get_errors()[0]\n            raise InvalidSpec(msg, lineno, path)\n        elif len(partial_ast) == 0:\n            logger.info('Empty spec: %s', path)\n        else:\n            partial_asts.append(partial_ast)\n    return IRGenerator(partial_asts, version, debug=debug,\n                       route_whitelist_filter=route_whitelist_filter).generate_IR()",
    "docstring": "Converts a collection of Stone specifications into the intermediate\n    representation used by Stone backends.\n\n    The process is: Lexer -> Parser -> Semantic Analyzer -> IR Generator.\n\n    The code is structured as:\n        1. Parser (Lexer embedded within)\n        2. IR Generator (Semantic Analyzer embedded within)\n\n    :type specs: List[Tuple[path: str, text: str]]\n    :param specs: `path` is never accessed and is only used to report the\n        location of a bad spec to the user. `spec` is the text contents of\n        a spec (.stone) file.\n\n    :raises: InvalidSpec\n\n    :returns: stone.ir.Api"
  },
  {
    "code": "def _alter_umask(self):\n        if self.umask is None:\n            yield\n        else:\n            prev_umask = os.umask(self.umask)\n            try:\n                yield\n            finally:\n                os.umask(prev_umask)",
    "docstring": "Temporarily alter umask to custom setting, if applicable"
  },
  {
    "code": "def remove_column(table, remove_index):\r\n        for row_index in range(len(table)):\r\n            old_row = table[row_index]\r\n            new_row = []\r\n            for column_index in range(len(old_row)):\r\n                if column_index != remove_index:\r\n                    new_row.append(old_row[column_index])\r\n            table[row_index] = new_row\r\n        return table",
    "docstring": "Removes the specified column from the table."
  },
  {
    "code": "def setTargetRange(self, targetRange, padding=None):\n        if self.axisNumber == X_AXIS:\n            xRange, yRange = targetRange, None\n        else:\n            xRange, yRange = None, targetRange\n        self.viewBox.setRange(xRange = xRange, yRange=yRange, padding=padding,\n                              update=False, disableAutoRange=False)",
    "docstring": "Sets the range of the target."
  },
  {
    "code": "def iter_items(self, depth: int = 1):\n        if depth is not None and not isinstance(depth, int):\n            raise TypeError\n        def itor(root, d):\n            if d is not None:\n                d -= 1\n                if d < 0:\n                    return\n            for name in os.listdir(root):\n                path = os.path.join(root, name)\n                node = NodeInfo.from_path(path)\n                yield node\n                if isinstance(node, DirectoryInfo):\n                    yield from itor(path, d)\n        yield from itor(self._path, depth)",
    "docstring": "get items from directory."
  },
  {
    "code": "def __check_right_side_conflict(x, y, dfs_data):\n    r = dfs_data['FG']['r']\n    w, z = dfs_data['RF'][r]\n    return __check_conflict_fronds(x, y, w, z, dfs_data)",
    "docstring": "Checks to see if the frond xy will conflict with a frond on the right side of the embedding."
  },
  {
    "code": "def maybe_coroutine(obj):\n    if six.PY3 and asyncio.iscoroutine(obj):\n        return defer.ensureDeferred(obj)\n    return obj",
    "docstring": "If 'obj' is a coroutine and we're using Python3, wrap it in\n    ensureDeferred. Otherwise return the original object.\n\n    (This is to insert in all callback chains from user code, in case\n    that user code is Python3 and used 'async def')"
  },
  {
    "code": "def get_tags(self, use_cached=True):\n        device_json = self.get_device_json(use_cached)\n        potential_tags = device_json.get(\"dpTags\")\n        if potential_tags:\n            return list(filter(None, potential_tags.split(\",\")))\n        else:\n            return []",
    "docstring": "Get the list of tags for this device"
  },
  {
    "code": "def threeD_gridplot(nodes, **kwargs):\n    from mpl_toolkits.mplot3d import Axes3D\n    import matplotlib.pyplot as plt\n    lats = []\n    longs = []\n    depths = []\n    for node in nodes:\n        lats.append(float(node[0]))\n        longs.append(float(node[1]))\n        depths.append(float(node[2]))\n    fig = plt.figure()\n    ax = fig.add_subplot(111, projection='3d')\n    ax.scatter(lats, longs, depths)\n    ax.set_ylabel(\"Latitude (deg)\")\n    ax.set_xlabel(\"Longitude (deg)\")\n    ax.set_zlabel(\"Depth(km)\")\n    ax.get_xaxis().get_major_formatter().set_scientific(False)\n    ax.get_yaxis().get_major_formatter().set_scientific(False)\n    fig = _finalise_figure(fig=fig, **kwargs)\n    return fig",
    "docstring": "Plot in a series of grid points in 3D.\n\n    :type nodes: list\n    :param nodes: List of tuples of the form (lat, long, depth)\n\n    :returns: :class:`matplotlib.figure.Figure`\n\n    .. rubric:: Example\n\n    >>> from eqcorrscan.utils.plotting import threeD_gridplot\n    >>> nodes = [(-43.5, 170.4, 4), (-43.3, 170.8, 12), (-43.4, 170.3, 8)]\n    >>> threeD_gridplot(nodes=nodes)  # doctest: +SKIP\n\n    .. plot::\n\n        from eqcorrscan.utils.plotting import threeD_gridplot\n        nodes = [(-43.5, 170.4, 4), (-43.3, 170.8, 12), (-43.4, 170.3, 8)]\n        threeD_gridplot(nodes=nodes)"
  },
  {
    "code": "def temperature(self):\n        ut = self.get_raw_temp()\n        x1 = ((ut - self.cal['AC6']) * self.cal['AC5']) >> 15\n        x2 = (self.cal['MC'] << 11) // (x1 + self.cal['MD'])\n        b5 = x1 + x2\n        return ((b5 + 8) >> 4) / 10",
    "docstring": "Get the temperature from the sensor.\n\n        :returns: The temperature in degree celcius as a float\n\n        :example:\n\n        >>> sensor = BMP180(gw)\n        >>> sensor.load_calibration()\n        >>> sensor.temperature()\n        21.4"
  },
  {
    "code": "def _save_subimports(self, code, top_level_dependencies):\n        for x in top_level_dependencies:\n            if isinstance(x, types.ModuleType) and hasattr(x, '__package__') and x.__package__:\n                prefix = x.__name__ + '.'\n                for name, module in sys.modules.items():\n                    if name is not None and name.startswith(prefix):\n                        tokens = set(name[len(prefix):].split('.'))\n                        if not tokens - set(code.co_names):\n                            self.save(module)\n                            self.write(pickle.POP)",
    "docstring": "Ensure de-pickler imports any package child-modules that\n        are needed by the function"
  },
  {
    "code": "def list_adb_devices_by_usb_id():\n    out = adb.AdbProxy().devices(['-l'])\n    clean_lines = new_str(out, 'utf-8').strip().split('\\n')\n    results = []\n    for line in clean_lines:\n        tokens = line.strip().split()\n        if len(tokens) > 2 and tokens[1] == 'device':\n            results.append(tokens[2])\n    return results",
    "docstring": "List the usb id of all android devices connected to the computer that\n    are detected by adb.\n\n    Returns:\n        A list of strings that are android device usb ids. Empty if there's\n        none."
  },
  {
    "code": "def check_tx(self, raw_transaction):\n        self.abort_if_abci_chain_is_not_synced()\n        logger.debug('check_tx: %s', raw_transaction)\n        transaction = decode_transaction(raw_transaction)\n        if self.bigchaindb.is_valid_transaction(transaction):\n            logger.debug('check_tx: VALID')\n            return ResponseCheckTx(code=CodeTypeOk)\n        else:\n            logger.debug('check_tx: INVALID')\n            return ResponseCheckTx(code=CodeTypeError)",
    "docstring": "Validate the transaction before entry into\n        the mempool.\n\n        Args:\n            raw_tx: a raw string (in bytes) transaction."
  },
  {
    "code": "def set_impact_state(self):\n        cls = self.__class__\n        if cls.enable_problem_impacts_states_change:\n            logger.debug(\"%s is impacted and goes UNREACHABLE\", self)\n            self.state_before_impact = self.state\n            self.state_id_before_impact = self.state_id\n            self.state_changed_since_impact = False\n            self.set_unreachable()",
    "docstring": "We just go an impact, so we go unreachable\n        But only if we enable this state change in the conf\n\n        :return: None"
  },
  {
    "code": "def _encode_dask_array(values, uniques=None, encode=False, onehot_dtype=None):\n    if uniques is None:\n        if encode and onehot_dtype:\n            raise ValueError(\"Cannot use 'encode` and 'onehot_dtype' simultaneously.\")\n        if encode:\n            uniques, encoded = da.unique(values, return_inverse=True)\n            return uniques, encoded\n        else:\n            return da.unique(values)\n    if encode:\n        if onehot_dtype:\n            dtype = onehot_dtype\n            new_axis = 1\n            chunks = values.chunks + (len(uniques),)\n        else:\n            dtype = np.dtype(\"int\")\n            new_axis = None\n            chunks = values.chunks\n        return (\n            uniques,\n            values.map_blocks(\n                _check_and_search_block,\n                uniques,\n                onehot_dtype=onehot_dtype,\n                dtype=dtype,\n                new_axis=new_axis,\n                chunks=chunks,\n            ),\n        )\n    else:\n        return uniques",
    "docstring": "One-hot or label encode a dask array.\n\n    Parameters\n    ----------\n    values : da.Array, shape [n_samples,]\n    unqiques : np.ndarray, shape [n_uniques,]\n    encode : bool, default False\n        Whether to encode the values (True) or just discover the uniques.\n    onehot_dtype : np.dtype, optional\n        Optional dtype for the resulting one-hot encoded array. This changes\n        the shape, dtype, and underlying storage of the returned dask array.\n\n        ======= ================= =========================\n        thing   onehot_dtype=None onehot_dtype=onehot_dtype\n        ======= ================= =========================\n        shape   (n_samples,)      (n_samples, len(uniques))\n        dtype   np.intp           onehot_dtype\n        storage np.ndarray        scipy.sparse.csr_matrix\n        ======= ================= =========================\n\n    Returns\n    -------\n    uniques : ndarray\n        The discovered uniques (uniques=None) or just `uniques`\n    encoded : da.Array, optional\n        The encoded values. Only returend when ``encode=True``."
  },
  {
    "code": "def delete_cached_branch_info(self):\n        if os.path.isfile(constants.cached_branch_info):\n            logger.debug('Deleting cached branch_info file...')\n            os.remove(constants.cached_branch_info)\n        else:\n            logger.debug('Cached branch_info file does not exist.')",
    "docstring": "Deletes cached branch_info file"
  },
  {
    "code": "def connect(self, signal, **kwargs):\n        signal.connect(self, **kwargs)\n        self.connections.append((signal, kwargs))",
    "docstring": "Connect a specific signal type to this receiver."
  },
  {
    "code": "def _get_debug_context(debug_port, debug_args, debugger_path):\n        if debug_port and debugger_path:\n            try:\n                debugger = Path(debugger_path).resolve(strict=True)\n            except OSError as error:\n                if error.errno == errno.ENOENT:\n                    raise DebugContextException(\"'{}' could not be found.\".format(debugger_path))\n                else:\n                    raise error\n            if not debugger.is_dir():\n                raise DebugContextException(\"'{}' should be a directory with the debugger in it.\".format(debugger_path))\n            debugger_path = str(debugger)\n        return DebugContext(debug_port=debug_port, debug_args=debug_args, debugger_path=debugger_path)",
    "docstring": "Creates a DebugContext if the InvokeContext is in a debugging mode\n\n        Parameters\n        ----------\n        debug_port int\n             Port to bind the debugger to\n        debug_args str\n            Additional arguments passed to the debugger\n        debugger_path str\n            Path to the directory of the debugger to mount on Docker\n\n        Returns\n        -------\n        samcli.commands.local.lib.debug_context.DebugContext\n            Object representing the DebugContext\n\n        Raises\n        ------\n        samcli.commands.local.cli_common.user_exceptions.DebugContext\n            When the debugger_path is not valid"
  },
  {
    "code": "def _add_event_in_element(self, element, event):\n        if not self.main_script_added:\n            self._generate_main_scripts()\n        if self.script_list is not None:\n            self.id_generator.generate_id(element)\n            self.script_list.append_text(\n                event\n                + \"Elements.push('\"\n                + element.get_attribute('id')\n                + \"');\"\n            )",
    "docstring": "Add a type of event in element.\n\n        :param element: The element.\n        :type element: hatemile.util.html.htmldomelement.HTMLDOMElement\n        :param event: The type of event.\n        :type event: str"
  },
  {
    "code": "def forward(self, actions, batch_info):\n        while len(self.processes) < actions.shape[0]:\n            len_action_space = self.action_space.shape[-1]\n            self.processes.append(\n                OrnsteinUhlenbeckNoiseProcess(\n                    np.zeros(len_action_space), float(self.std_dev) * np.ones(len_action_space)\n                )\n            )\n        noise = torch.from_numpy(np.stack([x() for x in self.processes])).float().to(actions.device)\n        return torch.min(torch.max(actions + noise, self.low_tensor), self.high_tensor)",
    "docstring": "Return model step after applying noise"
  },
  {
    "code": "def register_token(self, token_class, regexp=None):\n        if regexp is None:\n            regexp = token_class.regexp\n        self.tokens.register(token_class, regexp)",
    "docstring": "Register a token class.\n\n        Args:\n            token_class (tdparser.Token): the token class to register\n            regexp (optional str): the regexp for elements of that token.\n                Defaults to the `regexp` attribute of the token class."
  },
  {
    "code": "def plotnoisecum(noisepkl, fluxscale=1, plot_width=450, plot_height=400):\n    noises = read_noise(noisepkl)\n    imnoise = np.sort(fluxscale*noises[4])\n    frac = [float(count)/len(imnoise) for count in reversed(range(1, len(imnoise)+1))]\n    noiseplot = Figure(plot_width=plot_width, plot_height=plot_height, toolbar_location=\"above\",\n                       x_axis_label='Image noise (Jy; cal scaling {0:.3})'.format(fluxscale),\n                       y_axis_label='Cumulative fraction', tools='pan, wheel_zoom, reset')\n    noiseplot.line(imnoise, frac)\n    if fluxscale != 1:\n        return noiseplot, imnoise\n    else:\n        return noiseplot",
    "docstring": "Merged noise pkl converted to interactive cumulative histogram \n\n    noisepkl is standard noise pickle file.\n    fluxscale is scaling applied by gain calibrator. telcal solutions have fluxscale=1.\n    also returns corrected imnoise values if non-unity fluxscale provided"
  },
  {
    "code": "def monitor(self, listener):\n        for line in self._stream():\n            self._record.append(line)\n            if self.verbose:\n                self.out.blather(line)\n            if listener(line) is self.MONITOR_STOP:\n                return",
    "docstring": "Relay the stream to listener until told to stop."
  },
  {
    "code": "def ApplyPluginToTypedCollection(plugin, type_names, fetch_fn):\n  for chunk in plugin.Start():\n    yield chunk\n  def GetValues(tn):\n    for v in fetch_fn(tn):\n      yield v\n  for type_name in sorted(type_names):\n    stored_cls = rdfvalue.RDFValue.classes[type_name]\n    for chunk in plugin.ProcessValues(stored_cls,\n                                      functools.partial(GetValues, type_name)):\n      yield chunk\n  for chunk in plugin.Finish():\n    yield chunk",
    "docstring": "Applies instant output plugin to a collection of results.\n\n  Args:\n    plugin: InstantOutputPlugin instance.\n    type_names: List of type names (strings) to be processed.\n    fetch_fn: Function that takes a type name as an argument and returns\n      available items (FlowResult) corresponding to this type. Items are\n      returned as a generator\n\n  Yields:\n    Bytes chunks, as generated by the plugin."
  },
  {
    "code": "def indent(self, value):\n        if isinstance(value, str):\n            if value.isspace() or len(value) == 0:\n                self._indent = value\n            else:\n                raise ValueError('String indentation can only contain '\n                                 'whitespace.')\n        elif isinstance(value, int):\n            if value >= 0:\n                self._indent = value * ' '\n            else:\n                raise ValueError('Indentation spacing must be nonnegative.')\n        else:\n            raise TypeError('Indentation must be specified by string or space '\n                            'width.')",
    "docstring": "Validate and set the indent width."
  },
  {
    "code": "def add_layer_item(self, layer):\n        if not layer.is_draft_version:\n            raise ValueError(\"Layer isn't a draft version\")\n        self.items.append(layer.latest_version)",
    "docstring": "Adds a Layer to the publish group."
  },
  {
    "code": "def print_status(self):\n        tweets = self.received\n        now = time.time()\n        diff = now - self.since\n        self.since = now\n        self.received = 0\n        if diff > 0:\n            logger.info(\"Receiving tweets at %s tps\", tweets / diff)",
    "docstring": "Print out the current tweet rate and reset the counter"
  },
  {
    "code": "def save(self):\n        result = yield gen.Task(RedisSession._redis_client.set,\n                                self._key, self.dumps())\n        LOGGER.debug('Saved session %s (%r)', self.id, result)\n        raise gen.Return(result)",
    "docstring": "Store the session data in redis\n\n        :param method callback: The callback method to invoke when done"
  },
  {
    "code": "def this(func, cache_obj=CACHE_OBJ, key=None, ttl=None, *args, **kwargs):\n    key = key or (func.__name__ + str(args) + str(kwargs))\n    if cache_obj.has(key):\n        return cache_obj.get(key)\n    value = func(*args, **kwargs)\n    cache_obj.upsert(key, value, ttl)\n    return value",
    "docstring": "Store the output from the decorated function in the cache and pull it\n    from the cache on future invocations without rerunning.\n\n    Normally, the value will be stored under a key which takes into account\n    all of the parameters that are passed into it, thereby caching different\n    invocations separately. If you specify a key, all invocations will be\n    cached under that key, and different invocations will return the same\n    value, which may be unexpected. So, be careful!\n\n    If the cache is disabled, the decorated function will just run normally.\n\n    Unlike the other functions in this module, you must pass a custom cache_obj\n    to this() in order to operate on the non-global cache. This is because of\n    wonky behavior when using decorator.decorator from a class method.\n\n    :param func: (expensive?) function to decorate\n    :param cache_obj: cache to a specific object (for use from the cache object itself)\n    :param key: optional key to store the value under\n    :param ttl: optional expiry to apply to the cached value\n    :param *args: arg tuple to pass to the decorated function\n    :param **kwargs: kwarg dict to pass to the decorated function"
  },
  {
    "code": "def group_required(groups=None):\n        def wrapper(func):\n            @wraps(func)\n            def wrapped(*args, **kwargs):\n                if g.user is None:\n                    return redirect(\n                        url_for(current_app.config['LDAP_LOGIN_VIEW'],\n                                next=request.path))\n                match = [group for group in groups if group in g.ldap_groups]\n                if not match:\n                    abort(401)\n                return func(*args, **kwargs)\n            return wrapped\n        return wrapper",
    "docstring": "When applied to a view function, any unauthenticated requests will\n        be redirected to the view named in LDAP_LOGIN_VIEW. Authenticated\n        requests are only permitted if they belong to one of the listed groups.\n\n        The login view is responsible for asking for credentials, checking\n        them, and setting ``flask.g.user`` to the name of the authenticated\n        user and ``flask.g.ldap_groups`` to the authenticated user's groups\n        if the credentials are acceptable.\n\n        :param list groups: List of groups that should be able to access the\n            view function."
  },
  {
    "code": "def version_info(self):\n        if self._api_version is None:\n            self.query_api_version()\n        return self._api_version['api-major-version'],\\\n            self._api_version['api-minor-version']",
    "docstring": "Returns API version information for the HMC.\n\n        This operation does not require authentication.\n\n        Returns:\n\n          :term:`HMC API version`: The HMC API version supported by the HMC.\n\n        Raises:\n\n          :exc:`~zhmcclient.HTTPError`\n          :exc:`~zhmcclient.ParseError`\n          :exc:`~zhmcclient.ConnectionError`"
  },
  {
    "code": "def get_did_providers(self, did):\n        register_values = self.contract_concise.getDIDRegister(did)\n        if register_values and len(register_values) == 5:\n            return DIDRegisterValues(*register_values).providers\n        return None",
    "docstring": "Return the list providers registered on-chain for the given did.\n\n        :param did: hex str the id of an asset on-chain\n        :return:\n            list of addresses\n            None if asset has no registerd providers"
  },
  {
    "code": "def compile(self, db):\n        sql = self.expression\n        if self.alias:\n            sql += (' AS ' + db.quote_column(self.alias))\n        return sql",
    "docstring": "Building the sql expression\n\n        :param db: the database instance"
  },
  {
    "code": "def _is_readable(self, obj):\n        try:\n            read = getattr(obj, 'read')\n        except AttributeError:\n            return False\n        else:\n            return is_method(read, max_arity=1)",
    "docstring": "Check if the argument is a readable file-like object."
  },
  {
    "code": "def text(self, text):\n        ret = u\"\".join(text.content)\n        if 'url' in text.properties:\n            return u\"`%s`_\" % ret\n        if 'bold' in text.properties:\n            return u\"**%s**\" % ret\n        if 'italic' in text.properties:\n            return u\"*%s*\" % ret\n        if 'sub' in text.properties:\n            return ur\"\\ :sub:`%s`\\ \" % ret\n        if 'super' in text.properties:\n            return ur\"\\ :sup:`%s`\\ \" % ret\n        return ret",
    "docstring": "process a pyth text and return the formatted string"
  },
  {
    "code": "def threadsafe_call(self, fn, *args, **kwargs):\n        def handler():\n            try:\n                fn(*args, **kwargs)\n            except Exception:\n                warn(\"error caught while excecuting async callback\\n%s\\n\",\n                     format_exc())\n        def greenlet_wrapper():\n            gr = greenlet.greenlet(handler)\n            gr.switch()\n        self._async_session.threadsafe_call(greenlet_wrapper)",
    "docstring": "Wrapper around `AsyncSession.threadsafe_call`."
  },
  {
    "code": "def soldOutForRole(event, role):\r\n    if not isinstance(event, Event) or not isinstance(role, DanceRole):\r\n        return None\r\n    return event.soldOutForRole(role)",
    "docstring": "This tag allows one to determine whether any event is sold out for any\r\n    particular role."
  },
  {
    "code": "def connectRelay(self):\n        self.protocol = self.connector.buildProtocol(None)\n        self.connected = True\n        self.protocol.makeConnection(self)",
    "docstring": "Builds the target protocol and connects it to the relay transport."
  },
  {
    "code": "def broadcast(self, fcn, args):\n        results = self.map(_lockstep_fcn, [(len(self), fcn, args)] * len(self))\n        _numdone.value = 0\n        return results",
    "docstring": "Do a function call on every worker.\n\n        Parameters\n        ----------\n        fcn: funtion\n            Function to call.\n        args: tuple\n            The arguments for Pool.map"
  },
  {
    "code": "def dispatch(self, request, *args, **kwargs):\n        if request.GET.get(self.xeditable_fieldname_param):\n            return self.get_ajax_xeditable_choices(request, *args, **kwargs)\n        return super(XEditableMixin, self).dispatch(request, *args, **kwargs)",
    "docstring": "Introduces the ``ensure_csrf_cookie`` decorator and handles xeditable choices ajax."
  },
  {
    "code": "def get_env_str(env):\n    return ' '.join(\"{0}='{1}'\".format(k, v) for k, v in env.items())",
    "docstring": "Gets a string representation of a dict as though it contained environment\n    variable values."
  },
  {
    "code": "def tzname(self, dt):\n        tt = _localtime(_mktime((dt.year, dt.month, dt.day,\n                 dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))\n        return _time.tzname[tt.tm_isdst > 0]",
    "docstring": "datetime -> string name of time zone."
  },
  {
    "code": "def upload_GitHub_deploy_key(deploy_repo, ssh_key, *, read_only=False,\n    title=\"Doctr deploy key for pushing to gh-pages from Travis\", **login_kwargs):\n    DEPLOY_KEY_URL = \"https://api.github.com/repos/{deploy_repo}/keys\".format(deploy_repo=deploy_repo)\n    data = {\n        \"title\": title,\n        \"key\": ssh_key,\n        \"read_only\": read_only,\n    }\n    return GitHub_post(data, DEPLOY_KEY_URL, **login_kwargs)",
    "docstring": "Uploads a GitHub deploy key to ``deploy_repo``.\n\n    If ``read_only=True``, the deploy_key will not be able to write to the\n    repo."
  },
  {
    "code": "def load_plugin_classes(classes, category=None, overwrite=False):\n    load_errors = []\n    for klass in classes:\n        for pcat, pinterface in _plugins_interface.items():\n            if category is not None and not pcat == category:\n                continue\n            if all([hasattr(klass, attr) for attr in pinterface]):\n                if klass.plugin_name in _all_plugins[pcat] and not overwrite:\n                    err = '{0} is already set for {1}'.format(\n                        klass.plugin_name, pcat)\n                    load_errors.append((klass.__name__, '{}'.format(err)))\n                    continue\n                _all_plugins[pcat][klass.plugin_name] = klass()\n            else:\n                load_errors.append((\n                    klass.__name__,\n                    'does not match {} interface: {}'.format(pcat, pinterface)\n                ))\n    return load_errors",
    "docstring": "load plugins from class objects\n\n    Parameters\n    ----------\n    classes: list\n        list of classes\n    category : None or str\n        if str, apply for single plugin category\n    overwrite : bool\n        if True, allow existing plugins to be overwritten\n\n    Examples\n    --------\n\n    >>> from pprint import pprint\n    >>> pprint(view_plugins())\n    {'decoders': {}, 'encoders': {}, 'parsers': {}}\n\n    >>> class DecoderPlugin(object):\n    ...     plugin_name = 'example'\n    ...     plugin_descript = 'a decoder for dicts containing _example_ key'\n    ...     dict_signature = ('_example_',)\n    ...\n    >>> errors = load_plugin_classes([DecoderPlugin])\n\n    >>> pprint(view_plugins())\n    {'decoders': {'example': 'a decoder for dicts containing _example_ key'},\n     'encoders': {},\n     'parsers': {}}\n\n    >>> unload_all_plugins()"
  },
  {
    "code": "def get_version(self, service_id, version_number):\n\t\tcontent = self._fetch(\"/service/%s/version/%d\" % (service_id, version_number))\n\t\treturn FastlyVersion(self, content)",
    "docstring": "Get the version for a particular service."
  },
  {
    "code": "def compute_statistic(self, layout):\n        data = self.data\n        if not len(data):\n            return type(data)()\n        params = self.stat.setup_params(data)\n        data = self.stat.use_defaults(data)\n        data = self.stat.setup_data(data)\n        data = self.stat.compute_layer(data, params, layout)\n        self.data = data",
    "docstring": "Compute & return statistics for this layer"
  },
  {
    "code": "def load(file):\n    with open(file, 'r') as f:\n        contents = f.read()\n    lambder.load_events(contents)",
    "docstring": "Load events from a json file"
  },
  {
    "code": "def get_special_location(self, special_location=0):\n        try:\n            return(self.process.GetSpecialLocation(special_location))\n        except Exception as e: \n            print(e)\n            print(\"Could not retreive special location\")",
    "docstring": "SpecialLocation\n          0 - Gets the path to the Backup Folders folder location.\n          1 - Gets the path to the Unfiled Notes folder location.\n          2 - Gets the path to the Default Notebook folder location."
  },
  {
    "code": "def add(self, type, orig, replace):\n        ret = libxml2mod.xmlACatalogAdd(self._o, type, orig, replace)\n        return ret",
    "docstring": "Add an entry in the catalog, it may overwrite existing but\n           different entries."
  },
  {
    "code": "def clear_knowledge_category(self):\n        if (self.get_knowledge_category_metadata().is_read_only() or\n                self.get_knowledge_category_metadata().is_required()):\n            raise errors.NoAccess()\n        self._my_map['knowledgeCategoryId'] = self._knowledge_category_default",
    "docstring": "Clears the knowledge category.\n\n        raise:  NoAccess - ``Metadata.isRequired()`` or\n                ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _get_editable(self, request):\n        try:\n            editable_settings = self._editable_caches[request]\n        except KeyError:\n            editable_settings = self._editable_caches[request] = self._load()\n        return editable_settings",
    "docstring": "Get the dictionary of editable settings for a given request. Settings\n        are fetched from the database once per request and then stored in\n        ``_editable_caches``, a WeakKeyDictionary that will automatically\n        discard each entry when no more references to the request exist."
  },
  {
    "code": "def render(self, rect, data):\n        num_elements = len(self.elements)\n        col_width = (rect.w-self.margin*(num_elements-1)) / float(num_elements)\n        x = rect.x\n        for element in self.elements:\n            if element is not None:\n                element.render(datatypes.Rectangle(\n                        x, rect.y, col_width, rect.h\n                        ), data)\n            x += col_width + self.margin",
    "docstring": "Draws the columns."
  },
  {
    "code": "def set_brightness(self, brightness):\n        brightness = min([1.0, max([brightness, 0.0])])\n        self.state.brightness = brightness\n        self._repeat_last_frame()\n        sequence_number = self.zmq_publisher.publish_brightness(brightness)\n        logging.debug(\"Set brightness to {brightPercent:05.1f}%\".format(brightPercent=brightness*100))\n        return (True, sequence_number, \"OK\")",
    "docstring": "set general brightness in range 0...1"
  },
  {
    "code": "def attach_issue(resource_id, table, user_id):\n    data = schemas.issue.post(flask.request.json)\n    issue = _get_or_create_issue(data)\n    if table.name == 'jobs':\n        join_table = models.JOIN_JOBS_ISSUES\n    else:\n        join_table = models.JOIN_COMPONENTS_ISSUES\n    key = '%s_id' % table.name[0:-1]\n    query = join_table.insert().values({\n        'user_id': user_id,\n        'issue_id': issue['id'],\n        key: resource_id\n    })\n    try:\n        flask.g.db_conn.execute(query)\n    except sa_exc.IntegrityError:\n        raise dci_exc.DCICreationConflict(join_table.name,\n                                          '%s, issue_id' % key)\n    result = json.dumps({'issue': dict(issue)})\n    return flask.Response(result, 201, content_type='application/json')",
    "docstring": "Attach an issue to a specific job."
  },
  {
    "code": "def publish_properties(self):\n        publish = self.publish\n        publish(b\"$homie\", b\"3.0.1\")\n        publish(b\"$name\", self.settings.DEVICE_NAME)\n        publish(b\"$state\", b\"init\")\n        publish(b\"$fw/name\", b\"Microhomie\")\n        publish(b\"$fw/version\", __version__)\n        publish(b\"$implementation\", bytes(sys.platform, \"utf-8\"))\n        publish(b\"$localip\", utils.get_local_ip())\n        publish(b\"$mac\", utils.get_local_mac())\n        publish(b\"$stats\", b\"interval,uptime,freeheap\")\n        publish(b\"$stats/interval\", self.stats_interval)\n        publish(b\"$nodes\", b\",\".join(self.node_ids))\n        for node in self.nodes:\n            try:\n                for propertie in node.get_properties():\n                    if propertie:\n                        publish(*propertie)\n            except NotImplementedError:\n                raise\n            except Exception as error:\n                self.node_error(node, error)",
    "docstring": "publish device and node properties"
  },
  {
    "code": "def _get_fields_info(self, cols, model_schema, filter_rel_fields, **kwargs):\n        ret = list()\n        for col in cols:\n            page = page_size = None\n            col_args = kwargs.get(col, {})\n            if col_args:\n                page = col_args.get(API_PAGE_INDEX_RIS_KEY, None)\n                page_size = col_args.get(API_PAGE_SIZE_RIS_KEY, None)\n            ret.append(\n                self._get_field_info(\n                    model_schema.fields[col],\n                    filter_rel_fields.get(col, []),\n                    page=page,\n                    page_size=page_size,\n                )\n            )\n        return ret",
    "docstring": "Returns a dict with fields detail\n            from a marshmallow schema\n\n        :param cols: list of columns to show info for\n        :param model_schema: Marshmallow model schema\n        :param filter_rel_fields: expects add_query_rel_fields or\n                                    edit_query_rel_fields\n        :param kwargs: Receives all rison arguments for pagination\n        :return: dict with all fields details"
  },
  {
    "code": "def resume(self, obj):\n        if isinstance(obj, str):\n            savefile = open(obj, 'rb')\n        else:\n            savefile = obj\n        game = pickle.loads(zlib.decompress(savefile.read()))\n        if savefile is not obj:\n            savefile.close()\n        game.random_generator = random.Random()\n        game.random_generator.setstate(game.random_state)\n        del game.random_state\n        return game",
    "docstring": "Returns an Adventure game saved to the given file."
  },
  {
    "code": "def get_next_slip(raw):\n    if not is_slip(raw):\n        return None, raw\n    length = raw[1:].index(SLIP_END)\n    slip_packet = decode(raw[1:length+1])\n    new_raw = raw[length+2:]\n    return slip_packet, new_raw",
    "docstring": "Get the next slip packet from raw data.\n\n    Returns the extracted packet plus the raw data with the remaining data stream."
  },
  {
    "code": "def draw(self, labels):\n        y_lower = 10\n        colors = color_palette(self.colormap, self.n_clusters_)\n        for idx in range(self.n_clusters_):\n            values = self.silhouette_samples_[labels == idx]\n            values.sort()\n            size = values.shape[0]\n            y_upper = y_lower + size\n            color = colors[idx]\n            self.ax.fill_betweenx(\n                np.arange(y_lower, y_upper), 0, values,\n                facecolor=color, edgecolor=color, alpha=0.5\n            )\n            self.ax.text(-0.05, y_lower + 0.5 * size, str(idx))\n            y_lower = y_upper + 10\n        self.ax.axvline(\n            x=self.silhouette_score_, color=\"red\", linestyle=\"--\"\n        )\n        return self.ax",
    "docstring": "Draw the silhouettes for each sample and the average score.\n\n        Parameters\n        ----------\n\n        labels : array-like\n            An array with the cluster label for each silhouette sample,\n            usually computed with ``predict()``. Labels are not stored on the\n            visualizer so that the figure can be redrawn with new data."
  },
  {
    "code": "def make(parser):\n    s = parser.add_subparsers(\n        title='commands',\n        metavar='COMMAND',\n        help='description',\n        )\n    def gen_pass_f(args):\n        gen_pass()\n    gen_pass_parser = s.add_parser('gen-pass', help='generate the password')\n    gen_pass_parser.set_defaults(func=gen_pass_f)\n    def cmd_f(args):\n        cmd(args.user, args.hosts.split(','), args.key_filename, args.password, args.run)\n    cmd_parser = s.add_parser('cmd', help='run command line on the target host')\n    cmd_parser.add_argument('--run', help='the command running on the remote node', action='store', default=None, dest='run')\n    cmd_parser.set_defaults(func=cmd_f)",
    "docstring": "DEPRECATED\n    prepare OpenStack basic environment"
  },
  {
    "code": "def get_graph(cls, response):\n\t\tif cls.is_graph(response):\n\t\t\treturn response\n\t\tif hasattr(response, '__getitem__'):\n\t\t\tif len(response) > 0 and \\\n\t\t\t   cls.is_graph(response[0]):\n\t\t\t\treturn response[0]",
    "docstring": "Given a Flask response, find the rdflib Graph"
  },
  {
    "code": "def enable(self):\n        payload = {\n            \"new_state\": \"1\"\n        }\n        data = json.dumps(payload)\n        req = self.request(self.mist_client.uri+'/clouds/'+self.id, data=data)\n        req.post()\n        self.enabled = True\n        self.mist_client.update_clouds()",
    "docstring": "Enable the Cloud.\n\n        :returns:  A list of mist.clients' updated clouds."
  },
  {
    "code": "def _normalize(parsed, **options):\n    if options.get(\"exact\"):\n        return parsed\n    if isinstance(parsed, time):\n        now = options[\"now\"] or datetime.now()\n        return datetime(\n            now.year,\n            now.month,\n            now.day,\n            parsed.hour,\n            parsed.minute,\n            parsed.second,\n            parsed.microsecond,\n        )\n    elif isinstance(parsed, date) and not isinstance(parsed, datetime):\n        return datetime(parsed.year, parsed.month, parsed.day)\n    return parsed",
    "docstring": "Normalizes the parsed element.\n\n    :param parsed: The parsed elements.\n    :type parsed: Parsed\n\n    :rtype: Parsed"
  },
  {
    "code": "def get_default_runner(udf_class, input_col_delim=',', null_indicator='NULL', stdin=None):\n    proto = udf.get_annotation(udf_class)\n    in_types, out_types = parse_proto(proto)\n    stdin = stdin or sys.stdin\n    arg_parser = ArgParser(in_types, stdin, input_col_delim, null_indicator)\n    stdin_feed = make_feed(arg_parser)\n    collector = StdoutCollector(out_types)\n    ctor = _get_runner_class(udf_class)\n    return ctor(udf_class, stdin_feed, collector)",
    "docstring": "Create a default runner with specified udf class."
  },
  {
    "code": "def _ReceiveOp(self):\n    try:\n      fs_msg, received_bytes = self._fs.Recv()\n    except (IOError, struct.error):\n      logging.critical(\"Broken local Fleetspeak connection (read end).\")\n      raise\n    received_type = fs_msg.data.TypeName()\n    if not received_type.endswith(\"grr.GrrMessage\"):\n      raise ValueError(\n          \"Unexpected proto type received through Fleetspeak: %r; expected \"\n          \"grr.GrrMessage.\" % received_type)\n    stats_collector_instance.Get().IncrementCounter(\"grr_client_received_bytes\",\n                                                    received_bytes)\n    grr_msg = rdf_flows.GrrMessage.FromSerializedString(fs_msg.data.value)\n    grr_msg.auth_state = jobs_pb2.GrrMessage.AUTHENTICATED\n    self._threads[\"Worker\"].QueueMessages([grr_msg])",
    "docstring": "Receives a single message through Fleetspeak."
  },
  {
    "code": "def _extract_local_archive(working_dir, cleanup_functions, env_name, local_archive):\n    with zipfile.ZipFile(local_archive) as z:\n        z.extractall(working_dir)\n        archive_filenames = z.namelist()\n    root_elements = {m.split(posixpath.sep, 1)[0] for m in archive_filenames}\n    abs_archive_filenames = [os.path.abspath(os.path.join(working_dir, f)) for f in root_elements]\n    def cleanup():\n        for fn in abs_archive_filenames:\n            if os.path.isdir(fn):\n                shutil.rmtree(fn)\n            else:\n                os.unlink(fn)\n    cleanup_functions.append(cleanup)\n    env_dir = os.path.join(working_dir, env_name)\n    _fix_permissions(env_dir)\n    return env_dir",
    "docstring": "Helper internal function for extracting a zipfile and ensure that a cleanup is queued.\n\n    Parameters\n    ----------\n    working_dir : str\n    cleanup_functions : List[() -> NoneType]\n    env_name : str\n    local_archive : str"
  },
  {
    "code": "def launch_run(self, command, project=None, entity=None, run_id=None):\n        query = gql(\n)\n        patch = BytesIO()\n        if self.git.dirty:\n            self.git.repo.git.execute(['git', 'diff'], output_stream=patch)\n            patch.seek(0)\n        cwd = \".\"\n        if self.git.enabled:\n            cwd = cwd + os.getcwd().replace(self.git.repo.working_dir, \"\")\n        return self.gql(query, variable_values={\n            'entity': entity or self.settings('entity'),\n            'model': project or self.settings('project'),\n            'command': command,\n            'runId': run_id,\n            'patch': patch.read().decode(\"utf8\"),\n            'cwd': cwd\n        })",
    "docstring": "Launch a run in the cloud.\n\n        Args:\n            command (str): The command to run\n            program (str): The file to run\n            project (str): The project to scope the runs to\n            entity (str, optional): The entity to scope this project to.  Defaults to public models\n            run_id (str, optional): The run_id to scope to\n\n        Returns:\n                [{\"podName\",\"status\"}]"
  },
  {
    "code": "def close(self):\n        if self.fileobj is None:\n            return\n        if self.mode == WRITE:\n            self.close_member()\n            self.fileobj = None\n        elif self.mode == READ:\n            self.fileobj = None\n        if self.myfileobj:\n            self.myfileobj.close()\n            self.myfileobj = None",
    "docstring": "Closes the gzip with care to handle multiple members."
  },
  {
    "code": "def can_create_objective_bank_with_record_types(self, objective_bank_record_types):\n        if self._catalog_session is not None:\n            return self._catalog_session.can_create_catalog_with_record_types(catalog_record_types=objective_bank_record_types)\n        return True",
    "docstring": "Tests if this user can create a single ``ObjectiveBank`` using the desired record types.\n\n        While ``LearningManager.getObjectiveBankRecordTypes()`` can be\n        used to examine which records are supported, this method tests\n        which record(s) are required for creating a specific\n        ``ObjectiveBank``. Providing an empty array tests if an\n        ``ObjectiveBank`` can be created with no records.\n\n        arg:    objective_bank_record_types (osid.type.Type[]): array of\n                objective bank record types\n        return: (boolean) - ``true`` if ``ObjectiveBank`` creation using\n                the specified ``Types`` is supported, ``false``\n                otherwise\n        raise:  NullArgument - ``objective_bank_record_types`` is\n                ``null``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def declareProvisioner(self, *args, **kwargs):\n        return self._makeApiCall(self.funcinfo[\"declareProvisioner\"], *args, **kwargs)",
    "docstring": "Update a provisioner\n\n        Declare a provisioner, supplying some details about it.\n\n        `declareProvisioner` allows updating one or more properties of a provisioner as long as the required scopes are\n        possessed. For example, a request to update the `aws-provisioner-v1`\n        provisioner with a body `{description: 'This provisioner is great'}` would require you to have the scope\n        `queue:declare-provisioner:aws-provisioner-v1#description`.\n\n        The term \"provisioner\" is taken broadly to mean anything with a provisionerId.\n        This does not necessarily mean there is an associated service performing any\n        provisioning activity.\n\n        This method takes input: ``v1/update-provisioner-request.json#``\n\n        This method gives output: ``v1/provisioner-response.json#``\n\n        This method is ``experimental``"
  },
  {
    "code": "def _read_config_file(args):\n    stage = args.stage\n    with open(args.config, 'rt') as f:\n        config = yaml.safe_load(f.read())\n    STATE['stages'] = config['stages']\n    config['config'] = _decrypt_item(config['config'], stage=stage, key='',\n                                     render=True)\n    return config['stages'], config['config']",
    "docstring": "Decrypt config file, returns a tuple with stages and config."
  },
  {
    "code": "def recv(self, timeout=None):\n        if timeout:\n            try:\n                testsock = self._zmq.select([self.socket], [], [], timeout)[0]\n            except zmq.ZMQError as e:\n                if e.errno == errno.EINTR:\n                    testsock = None\n                else:\n                    raise\n            if not testsock:\n                return\n            rv = self.socket.recv(self._zmq.NOBLOCK)\n            return LogRecord.from_dict(json.loads(rv))\n        else:\n            return super(ZeroMQPullSubscriber, self).recv(timeout)",
    "docstring": "Overwrite standard recv for timeout calls to catch interrupt errors."
  },
  {
    "code": "def ot_tnrs_match_names(name_list,\n                        context_name=None,\n                        do_approximate_matching=True,\n                        include_dubious=False,\n                        include_deprecated=True,\n                        tnrs_wrapper=None):\n    if tnrs_wrapper is None:\n        from peyotl.sugar import tnrs\n        tnrs_wrapper = tnrs\n    match_obj = tnrs_wrapper.match_names(name_list,\n                                         context_name=context_name,\n                                         do_approximate_matching=do_approximate_matching,\n                                         include_deprecated=include_deprecated,\n                                         include_dubious=include_dubious,\n                                         wrap_response=True)\n    return match_obj",
    "docstring": "Uses a peyotl wrapper around an Open Tree web service to get a list of OTT IDs matching\n    the `name_list`.\n    The tnrs_wrapper can be None (in which case the default wrapper from peyotl.sugar will be used.\n    All other arguments correspond to the arguments of the web-service call.\n    A ValueError will be raised if the `context_name` does not match one of the valid names for a\n        taxonomic context.\n    This uses the wrap_response option to create and return a TNRSRespose object around the response."
  },
  {
    "code": "def get_service_resources(cls, model):\n        key = cls.get_model_key(model)\n        return cls.get_service_name_resources(key)",
    "docstring": "Get resource models by service model"
  },
  {
    "code": "def paginate(self, request, offset=0, limit=None):\n        return self.collection.offset(offset).limit(limit), self.collection.count()",
    "docstring": "Paginate queryset."
  },
  {
    "code": "def set(self, attr_dict):\n    for key in attr_dict:\n      if key == self._id_attribute:\n        setattr(self, self._id_attribute, attr_dict[key])\n      else:\n        setattr(self, u\"_\" + key, attr_dict[key])\n    return self",
    "docstring": "Sets attributes of this user object.\n\n    :type attr_dict: dict\n    :param attr_dict: Parameters to set, with attribute keys.\n\n    :rtype: :class:`.Base`\n    :return: The current object."
  },
  {
    "code": "def _processChanges(self, unused_output):\n        for branch in self.branches + self.bookmarks:\n            rev = yield self._getHead(branch)\n            if rev is None:\n                continue\n            yield self._processBranchChanges(rev, branch)",
    "docstring": "Send info about pulled changes to the master and record current.\n\n        HgPoller does the recording by moving the working dir to the head\n        of the branch.\n        We don't update the tree (unnecessary treatment and waste of space)\n        instead, we simply store the current rev number in a file.\n        Recall that hg rev numbers are local and incremental."
  },
  {
    "code": "def strip_command(self, command_string, output):\n        backspace_char = \"\\x08\"\n        if backspace_char in output:\n            output = output.replace(backspace_char, \"\")\n            output_lines = output.split(self.RESPONSE_RETURN)\n            new_output = output_lines[1:]\n            return self.RESPONSE_RETURN.join(new_output)\n        else:\n            command_length = len(command_string)\n            return output[command_length:]",
    "docstring": "Strip command_string from output string\n\n        Cisco IOS adds backspaces into output for long commands (i.e. for commands that line wrap)\n\n        :param command_string: The command string sent to the device\n        :type command_string: str\n\n        :param output: The returned output as a result of the command string sent to the device\n        :type output: str"
  },
  {
    "code": "def _handle_uninitialized_read(self, addr, inspect=True, events=True):\n        if self._uninitialized_read_handler is None:\n            v = self.state.solver.Unconstrained(\"%s_%s\" % (self.id, addr), self.width*self.state.arch.byte_width, key=self.variable_key_prefix + (addr,), inspect=inspect, events=events)\n            return v.reversed if self.endness == \"Iend_LE\" else v\n        else:\n            return self._uninitialized_read_handler(self, addr, inspect=inspect, events=events)",
    "docstring": "The default uninitialized read handler. Returns symbolic bytes."
  },
  {
    "code": "def get_shiftfile_row(self):\n        if self.fit is not None:\n            rowstr = '%s    %0.6f  %0.6f    %0.6f     %0.6f   %0.6f  %0.6f\\n'%(\n                    self.name,self.fit['offset'][0],self.fit['offset'][1],\n                    self.fit['rot'],self.fit['scale'][0],\n                    self.fit['rms'][0],self.fit['rms'][1])\n        else:\n            rowstr = None\n        return rowstr",
    "docstring": "Return the information for a shiftfile for this image to provide\n            compatability with the IRAF-based MultiDrizzle."
  },
  {
    "code": "def random_split(valid_pct:float, *arrs:NPArrayableList)->SplitArrayList:\n    \"Randomly split `arrs` with `valid_pct` ratio. good for creating validation set.\"\n    assert (valid_pct>=0 and valid_pct<=1), 'Validation set percentage should be between 0 and 1'\n    is_train = np.random.uniform(size=(len(arrs[0]),)) > valid_pct\n    return arrays_split(is_train, *arrs)",
    "docstring": "Randomly split `arrs` with `valid_pct` ratio. good for creating validation set."
  },
  {
    "code": "def WaitForSnapshotCompleted(snapshot):\n  print 'Waiting for snapshot %s to be completed...' % (snapshot)\n  while True:\n      snapshot.update()\n      sys.stdout.write('.')\n      sys.stdout.flush()\n      if snapshot.status == 'completed':\n          break\n      time.sleep(5)\n  return",
    "docstring": "Blocks until snapshot is complete."
  },
  {
    "code": "def rename(self, name):\n        r = self._h._http_resource(\n            method='PUT',\n            resource=('apps', self.name),\n            data={'app[name]': name}\n        )\n        return r.ok",
    "docstring": "Renames app to given name."
  },
  {
    "code": "def ellipse_to_cov(sigma_maj, sigma_min, theta):\n    cth = np.cos(theta)\n    sth = np.sin(theta)\n    covxx = cth**2 * sigma_maj**2 + sth**2 * sigma_min**2\n    covyy = sth**2 * sigma_maj**2 + cth**2 * sigma_min**2\n    covxy = cth * sth * sigma_maj**2 - cth * sth * sigma_min**2\n    return np.array([[covxx, covxy], [covxy, covyy]])",
    "docstring": "Compute the covariance matrix in two variables x and y given\n    the std. deviation along the semi-major and semi-minor axes and\n    the rotation angle of the error ellipse.\n\n    Parameters\n    ----------\n    sigma_maj : float\n        Std. deviation along major axis of error ellipse.\n\n    sigma_min : float\n        Std. deviation along minor axis of error ellipse.\n\n    theta : float\n        Rotation angle in radians from x-axis to ellipse major axis."
  },
  {
    "code": "def DeleteUser(username):\n  grr_api = maintenance_utils.InitGRRRootAPI()\n  try:\n    grr_api.GrrUser(username).Get().Delete()\n  except api_errors.ResourceNotFoundError:\n    raise UserNotFoundError(username)",
    "docstring": "Deletes a GRR user from the datastore."
  },
  {
    "code": "def insert_metric_changes(db, metrics, metric_mapping, commit):\n    values = [\n        [commit.sha, metric_mapping[metric.name], metric.value]\n        for metric in metrics\n        if metric.value != 0\n    ]\n    db.executemany(\n        'INSERT INTO metric_changes (sha, metric_id, value) VALUES (?, ?, ?)',\n        values,\n    )",
    "docstring": "Insert into the metric_changes tables.\n\n    :param metrics: `list` of `Metric` objects\n    :param dict metric_mapping: Maps metric names to ids\n    :param Commit commit:"
  },
  {
    "code": "def get_datetime(self, tz=None):\n        dt = self.datetime\n        assert dt.tzinfo == pytz.utc, \"Algorithm should have a utc datetime\"\n        if tz is not None:\n            dt = dt.astimezone(tz)\n        return dt",
    "docstring": "Returns the current simulation datetime.\n\n        Parameters\n        ----------\n        tz : tzinfo or str, optional\n            The timezone to return the datetime in. This defaults to utc.\n\n        Returns\n        -------\n        dt : datetime\n            The current simulation datetime converted to ``tz``."
  },
  {
    "code": "def getAnalogID(self,num):\n        listidx = self.An.index(num)\n        return self.Ach_id[listidx]",
    "docstring": "Returns the COMTRADE ID of a given channel number.\n        The number to be given is the same of the COMTRADE header."
  },
  {
    "code": "def from_dict(self, d: Dict[str, Any]) -> None:\n        for key, value in d.items():\n            if key.isupper():\n                self._setattr(key, value)\n        logger.info(\"Config is loaded from dict: %r\", d)",
    "docstring": "Load values from a dict."
  },
  {
    "code": "def Is64bit(self):\n    if \"64\" not in platform.machine():\n      return False\n    iswow64 = ctypes.c_bool(False)\n    if IsWow64Process is None:\n      return False\n    if not IsWow64Process(self.h_process, ctypes.byref(iswow64)):\n      raise process_error.ProcessError(\"Error while calling IsWow64Process.\")\n    return not iswow64.value",
    "docstring": "Returns true if this is a 64 bit process."
  },
  {
    "code": "def GuinierPorod(q, G, Rg, alpha):\n    return GuinierPorodMulti(q, G, Rg, alpha)",
    "docstring": "Empirical Guinier-Porod scattering\n\n    Inputs:\n    -------\n        ``q``: independent variable\n        ``G``: factor of the Guinier-branch\n        ``Rg``: radius of gyration\n        ``alpha``: power-law exponent\n\n    Formula:\n    --------\n        ``G * exp(-q^2*Rg^2/3)`` if ``q<q_sep`` and ``a*q^alpha`` otherwise.\n        ``q_sep`` and ``a`` are determined from conditions of smoothness at\n        the cross-over.\n\n    Literature:\n    -----------\n        B. Hammouda: A new Guinier-Porod model. J. Appl. Crystallogr. (2010) 43,\n            716-719."
  },
  {
    "code": "def to_creator(self, for_modify=False):\n        signature = {}\n        if for_modify:\n            try:\n                signature['id'] = self.id\n            except AttributeError:\n                raise AttributeError('a modify request should specify an ID')\n            if hasattr(self, 'name'):\n                signature['name'] = self.name\n        else:\n            signature['name'] = self.name\n        if self.has_content():\n            if self._contenttype == 'text/plain':\n                plain_text = self._content\n                html_text = ''\n            else:\n                html_text = self._content\n                plain_text = ''\n            content_plain = {'type': 'text/plain', '_content': plain_text}\n            content_html = {'type': 'text/html', '_content': html_text}\n            signature['content'] = [content_plain, content_html]\n        else:\n            if not for_modify:\n                raise AttributeError(\n                    'too little information on signature, '\n                    'run setContent before')\n        return signature",
    "docstring": "Returns a dict object suitable for a 'CreateSignature'.\n\n        A signature object for creation is like :\n\n            <signature name=\"unittest\">\n              <content type=\"text/plain\">My signature content</content>\n            </signature>\n\n        which is :\n\n            {\n             'name' : 'unittest',\n             'content': {\n               'type': 'text/plain',\n               '_content': 'My signature content'\n             }\n            }\n\n        Note that if the contenttype is text/plain, the content with text/html\n        will be cleared by the request (for consistency)."
  },
  {
    "code": "def init1(self, dae):\n        self.v0 = matrix(dae.y[self.v])",
    "docstring": "Set initial voltage for time domain simulation"
  },
  {
    "code": "def delete_speaker(self, speaker_uri):\n        response = self.api_request(speaker_uri, method='DELETE')\n        return self.__check_success(response)",
    "docstring": "Delete an speaker from a collection\n\n        :param speaker_uri: the URI that references the speaker\n        :type speaker_uri: String\n\n        :rtype: Boolean\n        :returns: True if the speaker was deleted\n\n        :raises: APIError if the request was not successful"
  },
  {
    "code": "def wells_by_index(self) -> Dict[str, Well]:\n        return {well: wellObj\n                for well, wellObj in zip(self._ordering, self._wells)}",
    "docstring": "Accessor function used to create a look-up table of Wells by name.\n\n        With indexing one can treat it as a typical python\n        dictionary whose keys are well names. To access well A1, for example,\n        simply write: labware.wells_by_index()['A1']\n\n        :return: Dictionary of well objects keyed by well name"
  },
  {
    "code": "def delete_channel(current):\n    ch_key = current.input['channel_key']\n    ch = Channel(current).objects.get(owner_id=current.user_id, key=ch_key)\n    ch.delete()\n    Subscriber.objects.filter(channel_id=ch_key).delete()\n    Message.objects.filter(channel_id=ch_key).delete()\n    current.output = {'status': 'Deleted', 'code': 200}",
    "docstring": "Delete a channel\n\n        .. code-block:: python\n\n            #  request:\n                {\n                'view':'_zops_delete_channel,\n                'channel_key': key,\n                }\n\n            #  response:\n                {\n                'status': 'OK',\n                'code': 200\n                }"
  },
  {
    "code": "def attach_file(self, filename, resource_id=None):\n        if resource_id is None:\n            resource_id = os.path.basename(filename)\n        upload_url = self.links[REF_MODEL_RUN_ATTACHMENTS] + '/' + resource_id\n        response = requests.post(\n            upload_url,\n            files={'file': open(filename, 'rb')}\n        )\n        if response.status_code != 200:\n            try:\n                raise ValueError(json.loads(response.text)['message'])\n            except KeyError as ex:\n                raise ValueError('invalid state change: ' + str(response.text))\n        return self.refresh()",
    "docstring": "Upload an attachment for the model run.\n\n        Paramerers\n        ----------\n        filename : string\n            Path to uploaded file\n\n        resource_id : string\n            Identifier of the attachment. If None, the filename will be used as\n            resource identifier.\n\n        Returns\n        -------\n        ModelRunHandle\n            Refreshed run handle."
  },
  {
    "code": "def color(self, color):\n        self._data['color'] = color\n        request = self._base_request\n        request['color'] = color\n        return self._tc_requests.update(request, owner=self.owner)",
    "docstring": "Updates the security labels color.\n\n        Args:\n            color:"
  },
  {
    "code": "def get_disabled(jail=None):\n    en_ = get_enabled(jail)\n    all_ = get_all(jail)\n    return sorted(set(all_) - set(en_))",
    "docstring": "Return what services are available but not enabled to start at boot\n\n    .. versionchanged:: 2016.3.4\n\n    Support for jail (representing jid or jail name) keyword argument in kwargs\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' service.get_disabled"
  },
  {
    "code": "def getBirthdate(self, string=True):\n        if string:\n            return self._convert_string(self.birthdate.rstrip())\n        else:\n            return datetime.strptime(self._convert_string(self.birthdate.rstrip()), \"%d %b %Y\")",
    "docstring": "Returns the birthdate as string object\n\n        Parameters\n        ----------\n        None\n\n        Examples\n        --------\n        >>> import pyedflib\n        >>> f = pyedflib.data.test_generator()\n        >>> f.getBirthdate()=='30 jun 1969'\n        True\n        >>> f._close()\n        >>> del f"
  },
  {
    "code": "def remove_output(clean=False, **kwargs):\n    if not clean:\n        return False\n    found = False\n    cwd = os.getcwd()\n    for file in os.listdir(cwd):\n        if file.endswith('_eig.txt') or \\\n                file.endswith('_out.txt') or \\\n                file.endswith('_out.lst') or \\\n                file.endswith('_out.dat') or \\\n                file.endswith('_prof.txt'):\n            found = True\n            try:\n                os.remove(file)\n                logger.info('<{:s}> removed.'.format(file))\n            except IOError:\n                logger.error('Error removing file <{:s}>.'.format(file))\n    if not found:\n        logger.info('no output found in the working directory.')\n    return True",
    "docstring": "Remove the outputs generated by Andes, including power flow reports\n    ``_out.txt``, time-domain list ``_out.lst`` and data ``_out.dat``,\n    eigenvalue analysis report ``_eig.txt``.\n\n    Parameters\n    ----------\n    clean : bool\n        If ``True``, execute the function body. Returns otherwise.\n\n    kwargs : dict\n        Other keyword arguments\n\n    Returns\n    -------\n    bool\n        ``True`` is the function body executes with success. ``False``\n        otherwise."
  },
  {
    "code": "def is_locked(self, request: AxesHttpRequest, credentials: dict = None) -> bool:\n        if settings.AXES_LOCK_OUT_AT_FAILURE:\n            return self.get_failures(request, credentials) >= settings.AXES_FAILURE_LIMIT\n        return False",
    "docstring": "Checks if the request or given credentials are locked."
  },
  {
    "code": "def get_action(self, action):\n        func_name = action.replace('-', '_')\n        if not hasattr(self, func_name):\n            raise DaemonError(\n                'Invalid action \"{action}\"'.format(action=action))\n        func = getattr(self, func_name)\n        if (not hasattr(func, '__call__') or\n                getattr(func, '__daemonocle_exposed__', False) is not True):\n            raise DaemonError(\n                'Invalid action \"{action}\"'.format(action=action))\n        return func",
    "docstring": "Get a callable action."
  },
  {
    "code": "def send_file_from_directory(filename, directory, app=None):\n    if app is None:\n        app = current_app\n    cache_timeout = app.get_send_file_max_age(filename)\n    return send_from_directory(directory, filename, cache_timeout=cache_timeout)",
    "docstring": "Helper to add static rules, like in `abilian.app`.app.\n\n    Example use::\n\n       app.add_url_rule(\n          app.static_url_path + '/abilian/<path:filename>',\n          endpoint='abilian_static',\n          view_func=partial(send_file_from_directory,\n                            directory='/path/to/static/files/dir'))"
  },
  {
    "code": "def add_attribute_label(self, attribute_id, label):\n        if not self.can_update():\n            self._tcex.handle_error(910, [self.type])\n        return self.tc_requests.add_attribute_label(\n            self.api_type, self.api_sub_type, self.unique_id, attribute_id, label, owner=self.owner\n        )",
    "docstring": "Adds a security labels to a attribute\n\n        Args:\n            attribute_id:\n            label:\n\n        Returns: A response json"
  },
  {
    "code": "def load_graph_xml(xml, filename, load_all=False):\n    ret = []\n    try:\n        root = objectify.fromstring(xml)\n    except Exception:\n        return []\n    if root.tag != 'graphs':\n        return []\n    if not hasattr(root, 'graph'):\n        return []\n    for g in root.graph:\n        name = g.attrib['name']\n        expressions = [e.text for e in g.expression]\n        if load_all:\n            ret.append(GraphDefinition(name, e, g.description.text, expressions, filename))\n            continue\n        if have_graph(name):\n            continue\n        for e in expressions:\n            if expression_ok(e):\n                ret.append(GraphDefinition(name, e, g.description.text, expressions, filename))\n                break\n    return ret",
    "docstring": "load a graph from one xml string"
  },
  {
    "code": "def mapstr_to_list(mapstr):\n    maplist = []\n    with StringIO(mapstr) as infile:\n        for row in infile:\n            maplist.append(row.strip())\n    return maplist",
    "docstring": "Convert an ASCII map string with rows to a list of strings, 1 string per row."
  },
  {
    "code": "def patch_ligotimegps(module=\"ligo.lw.lsctables\"):\n    module = import_module(module)\n    orig = module.LIGOTimeGPS\n    module.LIGOTimeGPS = _ligotimegps\n    try:\n        yield\n    finally:\n        module.LIGOTimeGPS = orig",
    "docstring": "Context manager to on-the-fly patch LIGOTimeGPS to accept all int types"
  },
  {
    "code": "def circleconvert(amount, currentformat, newformat):\n    if currentformat.lower() == newformat.lower():\n        return amount\n    if currentformat.lower() == 'radius':\n        if newformat.lower() == 'diameter':\n            return amount * 2\n        elif newformat.lower() == 'circumference':\n            return amount * 2 * math.pi\n        raise ValueError(\"Invalid new format provided.\")\n    elif currentformat.lower() == 'diameter':\n        if newformat.lower() == 'radius':\n            return amount / 2\n        elif newformat.lower() == 'circumference':\n            return amount * math.pi\n        raise ValueError(\"Invalid new format provided.\")\n    elif currentformat.lower() == 'circumference':\n        if newformat.lower() == 'radius':\n            return amount / math.pi / 2\n        elif newformat.lower() == 'diameter':\n            return amount / math.pi",
    "docstring": "Convert a circle measurement.\n\n    :type amount: number\n    :param amount: The number to convert.\n\n    :type currentformat: string\n    :param currentformat: The format of the provided value.\n\n    :type newformat: string\n    :param newformat: The intended format of the value.\n\n    >>> circleconvert(45, \"radius\", \"diameter\")\n    90"
  },
  {
    "code": "def license_id(filename):\n    import editdistance\n    with io.open(filename, encoding='UTF-8') as f:\n        contents = f.read()\n    norm = _norm_license(contents)\n    min_edit_dist = sys.maxsize\n    min_edit_dist_spdx = ''\n    for spdx, text in licenses.LICENSES:\n        norm_license = _norm_license(text)\n        if norm == norm_license:\n            return spdx\n        if norm and abs(len(norm) - len(norm_license)) / len(norm) > .05:\n            continue\n        edit_dist = editdistance.eval(norm, norm_license)\n        if edit_dist < min_edit_dist:\n            min_edit_dist = edit_dist\n            min_edit_dist_spdx = spdx\n    if norm and min_edit_dist / len(norm) < .05:\n        return min_edit_dist_spdx\n    else:\n        return None",
    "docstring": "Return the spdx id for the license contained in `filename`.  If no\n    license is detected, returns `None`.\n\n    spdx: https://spdx.org/licenses/\n    licenses from choosealicense.com: https://github.com/choosealicense.com\n\n    Approximate algorithm:\n\n    1. strip copyright line\n    2. normalize whitespace (replace all whitespace with a single space)\n    3. check exact text match with existing licenses\n    4. failing that use edit distance"
  },
  {
    "code": "def get_recent_tracks(self, limit=10, cacheable=True, time_from=None, time_to=None):\n        params = self._get_params()\n        if limit:\n            params[\"limit\"] = limit\n        if time_from:\n            params[\"from\"] = time_from\n        if time_to:\n            params[\"to\"] = time_to\n        seq = []\n        for track in _collect_nodes(\n            limit, self, self.ws_prefix + \".getRecentTracks\", cacheable, params\n        ):\n            if track.hasAttribute(\"nowplaying\"):\n                continue\n            title = _extract(track, \"name\")\n            artist = _extract(track, \"artist\")\n            date = _extract(track, \"date\")\n            album = _extract(track, \"album\")\n            timestamp = track.getElementsByTagName(\"date\")[0].getAttribute(\"uts\")\n            seq.append(\n                PlayedTrack(Track(artist, title, self.network), album, date, timestamp)\n            )\n        return seq",
    "docstring": "Returns this user's played track as a sequence of PlayedTrack objects\n        in reverse order of playtime, all the way back to the first track.\n\n        Parameters:\n        limit : If None, it will try to pull all the available data.\n        from (Optional) : Beginning timestamp of a range - only display\n        scrobbles after this time, in UNIX timestamp format (integer\n        number of seconds since 00:00:00, January 1st 1970 UTC). This\n        must be in the UTC time zone.\n        to (Optional) : End timestamp of a range - only display scrobbles\n        before this time, in UNIX timestamp format (integer number of\n        seconds since 00:00:00, January 1st 1970 UTC). This must be in\n        the UTC time zone.\n\n        This method uses caching. Enable caching only if you're pulling a\n        large amount of data."
  },
  {
    "code": "def runtime(self):\n        warnings.warn(\"admm.ADMM.runtime attribute has been replaced by \"\n                      \"an upgraded timer class: please see the documentation \"\n                      \"for admm.ADMM.solve method and util.Timer class\",\n                      PendingDeprecationWarning)\n        return self.timer.elapsed('init') + self.timer.elapsed('solve')",
    "docstring": "Transitional property providing access to the new timer\n        mechanism. This will be removed in the future."
  },
  {
    "code": "def close_transport(self):\n        if (self.path):\n            self._release_media_transport(self.path,\n                                          self.access_type)\n            self.path = None",
    "docstring": "Forcibly close previously acquired media transport.\n\n        .. note:: The user should first make sure any transport\n            event handlers are unregistered first."
  },
  {
    "code": "async def runItemCmdr(item, outp=None, **opts):\n    cmdr = await getItemCmdr(item, outp=outp, **opts)\n    await cmdr.runCmdLoop()",
    "docstring": "Create a cmdr for the given item and run the cmd loop.\n\n    Example:\n\n        runItemCmdr(foo)"
  },
  {
    "code": "def _start_scan(self, active):\n        success, retval = self._set_scan_parameters(active=active)\n        if not success:\n            return success, retval\n        try:\n            response = self._send_command(6, 2, [2])\n            if response.payload[0] != 0:\n                self._logger.error('Error starting scan for devices, error=%d', response.payload[0])\n                return False, {'reason': \"Could not initiate scan for ble devices, error_code=%d, response=%s\" % (response.payload[0], response)}\n        except InternalTimeoutError:\n            return False, {'reason': \"Timeout waiting for response\"}\n        return True, None",
    "docstring": "Begin scanning forever"
  },
  {
    "code": "def create_signature(self, base_url, payload=None):\n        url = urlparse(base_url)\n        url_to_sign = \"{path}?{query}\".format(path=url.path, query=url.query)\n        converted_payload = self._convert(payload)\n        decoded_key = base64.urlsafe_b64decode(self.private_key.encode('utf-8'))\n        signature = hmac.new(decoded_key, str.encode(url_to_sign + converted_payload), hashlib.sha256)\n        return bytes.decode(base64.urlsafe_b64encode(signature.digest()))",
    "docstring": "Creates unique signature for request.\n        Make sure ALL 'GET' and 'POST' data is already included before\n        creating the signature or receiver won't be able to re-create it.\n\n        :param base_url:\n            The url you'll using for your request.\n        :param payload:\n            The POST data that you'll be sending."
  },
  {
    "code": "def format_string(format, *cols):\n    sc = SparkContext._active_spark_context\n    return Column(sc._jvm.functions.format_string(format, _to_seq(sc, cols, _to_java_column)))",
    "docstring": "Formats the arguments in printf-style and returns the result as a string column.\n\n    :param col: the column name of the numeric value to be formatted\n    :param d: the N decimal places\n\n    >>> df = spark.createDataFrame([(5, \"hello\")], ['a', 'b'])\n    >>> df.select(format_string('%d %s', df.a, df.b).alias('v')).collect()\n    [Row(v=u'5 hello')]"
  },
  {
    "code": "def enable_asynchronous(self):\n        def is_monkey_patched():\n            try:\n                from gevent import monkey, socket\n            except ImportError:\n                return False\n            if hasattr(monkey, \"saved\"):\n                return \"socket\" in monkey.saved\n            return gevent.socket.socket == socket.socket\n        if not is_monkey_patched():\n            raise Exception(\"To activate asynchonoucity, please monkey patch\"\n                            \" the socket module with gevent\")\n        return True",
    "docstring": "Check if socket have been monkey patched by gevent"
  },
  {
    "code": "def set_debug_listener(stream):\n    def debugger(sig, frame):\n        launch_debugger(frame, stream)\n    if hasattr(signal, 'SIGUSR1'):\n        signal.signal(signal.SIGUSR1, debugger)\n    else:\n        logger.warn(\"Cannot set SIGUSR1 signal for debug mode.\")",
    "docstring": "Break into a debugger if receives the SIGUSR1 signal"
  },
  {
    "code": "def eat_config(self, conf_file):\n        cfg = ConfigParser.RawConfigParser()\n        cfg.readfp(conf_file)\n        sec = 'channels'\n        mess = 'missmatch of channel keys'\n        assert(set(self.pack.D.keys()) == set([int(i) for i in cfg.options(sec)])), mess\n        if not self.pack.chnames:\n            self.pack.chnames = dict(self.pack.chnames_0)\n        for i in cfg.options(sec):\n            self.pack.chnames[self.pack._key(int(i))] = cfg.get(sec, i)\n        sec = 'conditions'\n        conops = cfg.options(sec)\n        self.reset()\n        for con in conops:\n            self.set_condition(con, cfg.get(sec, con))",
    "docstring": "conf_file a file opened for reading.\n\n        Update the packs channel names and the conditions, accordingly."
  },
  {
    "code": "def has_dtypes(df, items):\n    dtypes = df.dtypes\n    for k, v in items.items():\n        if not dtypes[k] == v:\n            raise AssertionError(\"{} has the wrong dtype. Should be ({}), is ({})\".format(k, v,dtypes[k]))\n    return df",
    "docstring": "Assert that a DataFrame has ``dtypes``\n\n    Parameters\n    ==========\n    df: DataFrame\n    items: dict\n      mapping of columns to dtype.\n\n    Returns\n    =======\n    df : DataFrame"
  },
  {
    "code": "def request_search(self, txt=None):\n        if self.checkBoxRegex.isChecked():\n            try:\n                re.compile(self.lineEditSearch.text(), re.DOTALL)\n            except sre_constants.error as e:\n                self._show_error(e)\n                return\n            else:\n                self._show_error(None)\n        if txt is None or isinstance(txt, int):\n            txt = self.lineEditSearch.text()\n        if txt:\n            self.job_runner.request_job(\n                self._exec_search, txt, self._search_flags())\n        else:\n            self.job_runner.cancel_requests()\n            self._clear_occurrences()\n            self._on_search_finished()",
    "docstring": "Requests a search operation.\n\n        :param txt: The text to replace. If None, the content of lineEditSearch\n                    is used instead."
  },
  {
    "code": "def _pre_tune(self):\n        if self._running is None:\n            self._running = True\n        elif self._running is False:\n            log.error(\n                'This %s was scheduled to stop. Not running %s.tune_in()',\n                self.__class__.__name__, self.__class__.__name__\n            )\n            return\n        elif self._running is True:\n            log.error(\n                'This %s is already running. Not running %s.tune_in()',\n                self.__class__.__name__, self.__class__.__name__\n            )\n            return\n        try:\n            log.info(\n                '%s is starting as user \\'%s\\'',\n                self.__class__.__name__, salt.utils.user.get_user()\n            )\n        except Exception as err:\n            log.log(\n                salt.utils.platform.is_windows() and logging.DEBUG or logging.ERROR,\n                'Failed to get the user who is starting %s',\n                self.__class__.__name__,\n                exc_info=err\n            )",
    "docstring": "Set the minion running flag and issue the appropriate warnings if\n        the minion cannot be started or is already running"
  },
  {
    "code": "def MICECache(subsystem, parent_cache=None):\n    if config.REDIS_CACHE:\n        cls = RedisMICECache\n    else:\n        cls = DictMICECache\n    return cls(subsystem, parent_cache=parent_cache)",
    "docstring": "Construct a |MICE| cache.\n\n    Uses either a Redis-backed cache or a local dict cache on the object.\n\n    Args:\n        subsystem (Subsystem): The subsystem that this is a cache for.\n\n    Kwargs:\n        parent_cache (MICECache): The cache generated by the uncut\n            version of ``subsystem``. Any cached |MICE| which are\n            unaffected by the cut are reused in this cache. If None,\n            the cache is initialized empty."
  },
  {
    "code": "def is_member(self, ldap_user, group_dn):\n        try:\n            user_uid = ldap_user.attrs[\"uid\"][0]\n            try:\n                is_member = ldap_user.connection.compare_s(\n                    group_dn, \"memberUid\", user_uid.encode()\n                )\n            except (ldap.UNDEFINED_TYPE, ldap.NO_SUCH_ATTRIBUTE):\n                is_member = False\n            if not is_member:\n                try:\n                    user_gid = ldap_user.attrs[\"gidNumber\"][0]\n                    is_member = ldap_user.connection.compare_s(\n                        group_dn, \"gidNumber\", user_gid.encode()\n                    )\n                except (ldap.UNDEFINED_TYPE, ldap.NO_SUCH_ATTRIBUTE):\n                    is_member = False\n        except (KeyError, IndexError):\n            is_member = False\n        return is_member",
    "docstring": "Returns True if the group is the user's primary group or if the user is\n        listed in the group's memberUid attribute."
  },
  {
    "code": "def get_compute_credentials(key):\n    scopes = ['https://www.googleapis.com/auth/compute']\n    credentials = ServiceAccountCredentials.from_json_keyfile_dict(\n        key, scopes=scopes)\n    return credentials",
    "docstring": "Authenticates a service account for the compute engine.\n\n    This uses the `oauth2client.service_account` module. Since the `google`\n    Python package does not support the compute engine (yet?), we need to make\n    direct HTTP requests. For that we need authentication tokens. Obtaining\n    these based on the credentials provided by the `google.auth2` module is\n    much more cumbersome than using the `oauth2client` module.\n\n    See:\n    - https://cloud.google.com/iap/docs/authentication-howto\n    - https://developers.google.com/identity/protocols/OAuth2ServiceAccount\n    \n    TODO: docstring"
  },
  {
    "code": "async def _scp(self, source, destination, scp_opts):\n        cmd = [\n            'scp',\n            '-i', os.path.expanduser('~/.local/share/juju/ssh/juju_id_rsa'),\n            '-o', 'StrictHostKeyChecking=no',\n            '-q',\n            '-B'\n        ]\n        cmd.extend(scp_opts.split() if isinstance(scp_opts, str) else scp_opts)\n        cmd.extend([source, destination])\n        loop = self.model.loop\n        process = await asyncio.create_subprocess_exec(*cmd, loop=loop)\n        await process.wait()\n        if process.returncode != 0:\n            raise JujuError(\"command failed: %s\" % cmd)",
    "docstring": "Execute an scp command. Requires a fully qualified source and\n        destination."
  },
  {
    "code": "def setAutoRangeOff(self):\n        if self.getRefreshBlocked():\n            logger.debug(\"setAutoRangeOff blocked for {}\".format(self.nodeName))\n            return\n        if self.autoRangeCti:\n            self.autoRangeCti.data = False\n        self._forceRefreshAutoRange()",
    "docstring": "Turns off the auto range checkbox.\n            Calls _refreshNodeFromTarget, not _updateTargetFromNode, because setting auto range off\n            does not require a redraw of the target."
  },
  {
    "code": "def data_complete(self):\n        return task.data_complete(self.datadir, self.sitedir,\n            self._get_container_name)",
    "docstring": "Return True if all the expected datadir files are present"
  },
  {
    "code": "def main(self, x):\n        for i in range(len(self.taps_fix_reversed)):\n            self.next.mul[i] = x * self.taps_fix_reversed[i]\n            if i == 0:\n                self.next.acc[0] = self.mul[i]\n            else:\n                self.next.acc[i] = self.acc[i - 1] + self.mul[i]\n        self.next.out = self.acc[-1]\n        return self.out",
    "docstring": "Transposed form FIR implementation, uses full precision"
  },
  {
    "code": "def validate_process_steps(prop, value):\n    if value is not None:\n        validate_type(prop, value, (dict, list))\n        procstep_keys = set(_complex_definitions[prop])\n        for idx, procstep in enumerate(wrap_value(value)):\n            ps_idx = prop + '[' + str(idx) + ']'\n            validate_type(ps_idx, procstep, dict)\n            for ps_prop, ps_val in iteritems(procstep):\n                ps_key = '.'.join((ps_idx, ps_prop))\n                if ps_prop not in procstep_keys:\n                    _validation_error(prop, None, value, ('keys: {0}'.format(','.join(procstep_keys))))\n                if ps_prop != 'sources':\n                    validate_type(ps_key, ps_val, string_types)\n                else:\n                    validate_type(ps_key, ps_val, (string_types, list))\n                    for src_idx, src_val in enumerate(wrap_value(ps_val)):\n                        src_key = ps_key + '[' + str(src_idx) + ']'\n                        validate_type(src_key, src_val, string_types)",
    "docstring": "Default validation for Process Steps data structure"
  },
  {
    "code": "def load_data(path, dense=False):\n    catalog = {'.csv': load_csv, '.sps': load_svmlight_file, '.h5': load_hdf5}\n    ext = os.path.splitext(path)[1]\n    func = catalog[ext]\n    X, y = func(path)\n    if dense and sparse.issparse(X):\n        X = X.todense()\n    return X, y",
    "docstring": "Load data from a CSV, LibSVM or HDF5 file based on the file extension.\n\n    Args:\n        path (str): A path to the CSV, LibSVM or HDF5 format file containing data.\n        dense (boolean): An optional variable indicating if the return matrix\n                         should be dense.  By default, it is false.\n\n    Returns:\n        Data matrix X and target vector y"
  },
  {
    "code": "async def get_advanced_settings(request: web.Request) -> web.Response:\n    res = _get_adv_settings()\n    return web.json_response(res)",
    "docstring": "Handles a GET request and returns a json body with the key \"settings\" and a\n    value that is a list of objects where each object has keys \"id\", \"title\",\n    \"description\", and \"value\""
  },
  {
    "code": "def check_config(conf):\n    if 'fmode' in conf and not isinstance(conf['fmode'], string_types):\n        raise TypeError(TAG + \": `fmode` must be a string\")\n    if 'dmode' in conf and not isinstance(conf['dmode'], string_types):\n        raise TypeError(TAG + \": `dmode` must be a string\")\n    if 'depth' in conf:\n        if not isinstance(conf['depth'], int):\n            raise TypeError(TAG + \": `depth` must be an int\")\n        if conf['depth'] < 0:\n            raise ValueError(TAG + \": `depth` must be a positive number\")\n    if 'hash_alg' in conf:\n        if not isinstance(conf['hash_alg'], string_types):\n            raise TypeError(TAG + \": `hash_alg` must be a string\")\n        if conf['hash_alg'] not in ACCEPTED_HASH_ALG:\n            raise ValueError(TAG + \": `hash_alg` must be one of \" + str(ACCEPTED_HASH_ALG))",
    "docstring": "Type and boundary check"
  },
  {
    "code": "def OneResult(parser):\n    \"Parse like parser, but return exactly one result, not a tuple.\"\n    def parse(text):\n        results = parser(text)\n        assert len(results) == 1, \"Expected one result but got %r\" % (results,)\n        return results[0]\n    return parse",
    "docstring": "Parse like parser, but return exactly one result, not a tuple."
  },
  {
    "code": "def updateData(self, signal, fs):\n        t = threading.Thread(target=_doSpectrogram, args=(self.spec_done, (fs, signal),), kwargs=self.specgramArgs)\n        t.start()",
    "docstring": "Displays a spectrogram of the provided signal\n\n        :param signal: 1-D signal of audio\n        :type signal: numpy.ndarray\n        :param fs: samplerate of signal\n        :type fs: int"
  },
  {
    "code": "def update(self, items):\n        post_data = {}\n        items_json = json.dumps(items, default=dthandler)\n        post_data['data'] = items_json\n        response = self.post_attribute(\"update\", data=post_data)\n        return response['ticket']",
    "docstring": "Update a catalog object\n\n        Args:\n            items (list): A list of dicts describing update data and action codes (see api docs)\n\n        Kwargs:\n\n        Returns:\n            A ticket id\n\n        Example:\n\n        >>> c = catalog.Catalog('my_songs', type='song')\n        >>> items\n        [{'action': 'update',\n          'item': {'artist_name': 'dAn ThE aUtOmAtOr',\n                   'disc_number': 1,\n                   'genre': 'Instrumental',\n                   'item_id': '38937DDF04BC7FC4',\n                   'play_count': 5,\n                   'release': 'Bombay the Hard Way: Guns, Cars & Sitars',\n                   'song_name': 'Inspector Jay From Dehli',\n                   'track_number': 9,\n                   'url': 'file://localhost/Users/tylerw/Music/iTunes/iTunes%20Media/Music/Dan%20the%20Automator/Bombay%20the%20Hard%20Way_%20Guns,%20Cars%20&%20Sitars/09%20Inspector%20Jay%20From%20Dehli.m4a'}}]\n        >>> ticket = c.update(items)\n        >>> ticket\n        u'7dcad583f2a38e6689d48a792b2e4c96'\n        >>> c.status(ticket)\n        {u'ticket_status': u'complete', u'update_info': []}\n        >>>"
  },
  {
    "code": "def find_boost():\n    short_version = \"{}{}\".format(sys.version_info[0], sys.version_info[1])\n    boostlibnames = ['boost_python-py' + short_version,\n                     'boost_python' + short_version,\n                     'boost_python',\n                     ]\n    if sys.version_info[0] == 2:\n        boostlibnames += [\"boost_python-mt\"]\n    else:\n        boostlibnames += [\"boost_python3-mt\"]\n    for libboostname in boostlibnames:\n        if find_library_file(libboostname):\n            return libboostname\n    warnings.warn(no_boost_error)\n    return boostlibnames[0]",
    "docstring": "Find the name of the boost-python library. Returns None if none is found."
  },
  {
    "code": "def _pfp__show(self, level=0, include_offset=False):\n        res = []\n        res.append(\"{}{} {{\".format(\n            \"{:04x} \".format(self._pfp__offset) if include_offset else \"\",\n            self._pfp__show_name\n        ))\n        for child in self._pfp__children:\n            res.append(\"{}{}{:10s} = {}\".format(\n                \"    \"*(level+1),\n                \"{:04x} \".format(child._pfp__offset) if include_offset else \"\",\n                child._pfp__name,\n                child._pfp__show(level+1, include_offset)\n            ))\n        res.append(\"{}}}\".format(\"    \"*level))\n        return \"\\n\".join(res)",
    "docstring": "Show the contents of the struct"
  },
  {
    "code": "def _exposure_to_weights(self, y, exposure=None, weights=None):\n        y = y.ravel()\n        if exposure is not None:\n            exposure = np.array(exposure).astype('f').ravel()\n            exposure = check_array(exposure, name='sample exposure',\n                                   ndim=1, verbose=self.verbose)\n        else:\n            exposure = np.ones_like(y.ravel()).astype('float64')\n        exposure = exposure.ravel()\n        check_lengths(y, exposure)\n        y = y / exposure\n        if weights is not None:\n            weights = np.array(weights).astype('f').ravel()\n            weights = check_array(weights, name='sample weights',\n                                  ndim=1, verbose=self.verbose)\n        else:\n            weights = np.ones_like(y).astype('float64')\n        check_lengths(weights, exposure)\n        weights = weights * exposure\n        return y, weights",
    "docstring": "simple tool to create a common API\n\n        Parameters\n        ----------\n        y : array-like, shape (n_samples,)\n            Target values (integers in classification, real numbers in\n            regression)\n            For classification, labels must correspond to classes.\n        exposure : array-like shape (n_samples,) or None, default: None\n            containing exposures\n            if None, defaults to array of ones\n        weights : array-like shape (n_samples,) or None, default: None\n            containing sample weights\n            if None, defaults to array of ones\n\n        Returns\n        -------\n        y : y normalized by exposure\n        weights : array-like shape (n_samples,)"
  },
  {
    "code": "def area(self):\n        r\n        edges = tuple(edge._nodes for edge in self._edges)\n        return _surface_helpers.compute_area(edges)",
    "docstring": "r\"\"\"The area of the current curved polygon.\n\n        This assumes, but does not check, that the current curved polygon\n        is valid (i.e. it is bounded by the edges).\n\n        This computes the area via Green's theorem. Using the vector field\n        :math:`\\mathbf{F} = \\left[-y, x\\right]^T`, since\n        :math:`\\partial_x(x) - \\partial_y(-y) = 2` Green's theorem says\n\n        .. math::\n\n           \\int_{\\mathcal{P}} 2 \\, d\\textbf{x} =\n           \\int_{\\partial \\mathcal{P}} -y \\, dx + x \\, dy\n\n        (where :math:`\\mathcal{P}` is the current curved polygon).\n\n        Note that for a given edge :math:`C(r)` with control points\n        :math:`x_j, y_j`, the integral can be simplified:\n\n        .. math::\n\n            \\int_C -y \\, dx + x \\, dy = \\int_0^1 (x y' - y x') \\, dr\n                = \\sum_{i < j} (x_i y_j - y_i x_j) \\int_0^1 b_{i, d}\n                b'_{j, d} \\, dr\n\n        where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials.\n\n        Returns:\n            float: The area of the current curved polygon."
  },
  {
    "code": "def copy_table(\n        self,\n        sources,\n        destination,\n        job_id=None,\n        job_id_prefix=None,\n        location=None,\n        project=None,\n        job_config=None,\n        retry=DEFAULT_RETRY,\n    ):\n        job_id = _make_job_id(job_id, job_id_prefix)\n        if project is None:\n            project = self.project\n        if location is None:\n            location = self.location\n        job_ref = job._JobReference(job_id, project=project, location=location)\n        sources = _table_arg_to_table_ref(sources, default_project=self.project)\n        if not isinstance(sources, collections_abc.Sequence):\n            sources = [sources]\n        sources = [\n            _table_arg_to_table_ref(source, default_project=self.project)\n            for source in sources\n        ]\n        destination = _table_arg_to_table_ref(destination, default_project=self.project)\n        copy_job = job.CopyJob(\n            job_ref, sources, destination, client=self, job_config=job_config\n        )\n        copy_job._begin(retry=retry)\n        return copy_job",
    "docstring": "Copy one or more tables to another table.\n\n        See\n        https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.copy\n\n        Arguments:\n            sources (Union[ \\\n                :class:`~google.cloud.bigquery.table.Table`, \\\n                :class:`~google.cloud.bigquery.table.TableReference`, \\\n                str, \\\n                Sequence[ \\\n                    Union[ \\\n                        :class:`~google.cloud.bigquery.table.Table`, \\\n                        :class:`~google.cloud.bigquery.table.TableReference`, \\\n                        str, \\\n                    ] \\\n                ], \\\n            ]):\n                Table or tables to be copied.\n            destination (Union[\n                :class:`~google.cloud.bigquery.table.Table`, \\\n                :class:`~google.cloud.bigquery.table.TableReference`, \\\n                str, \\\n            ]):\n                Table into which data is to be copied.\n\n        Keyword Arguments:\n            job_id (str): (Optional) The ID of the job.\n            job_id_prefix (str)\n                (Optional) the user-provided prefix for a randomly generated\n                job ID. This parameter will be ignored if a ``job_id`` is\n                also given.\n            location (str):\n                Location where to run the job. Must match the location of any\n                source table as well as the destination table.\n            project (str):\n                Project ID of the project of where to run the job. Defaults\n                to the client's project.\n            job_config (google.cloud.bigquery.job.CopyJobConfig):\n                (Optional) Extra configuration options for the job.\n            retry (google.api_core.retry.Retry):\n                (Optional) How to retry the RPC.\n\n        Returns:\n            google.cloud.bigquery.job.CopyJob: A new copy job instance."
  },
  {
    "code": "def reboot(self):\n        reboot_msg = self.message_factory.command_long_encode(\n            0, 0,\n            mavutil.mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN,\n            0,\n            1,\n            0,\n            0,\n            0,\n            0, 0, 0)\n        self.send_mavlink(reboot_msg)",
    "docstring": "Requests an autopilot reboot by sending a ``MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN`` command."
  },
  {
    "code": "def validate_range_value(value):\n    if value == (None, None):\n        return\n    if not hasattr(value, '__iter__'):\n        raise TypeError('Range value must be an iterable, got \"%s\".' % value)\n    if not 2 == len(value):\n        raise ValueError('Range value must consist of two elements, got %d.' %\n                         len(value))\n    if not all(isinstance(x, (int,float)) for x in value):\n        raise TypeError('Range value must consist of two numbers, got \"%s\" '\n                        'and \"%s\" instead.' % value)\n    if not value[0] <= value[1]:\n        raise ValueError('Range must consist of min and max values (min <= '\n                         'max) but got \"%s\" and \"%s\" instead.' % value)\n    return",
    "docstring": "Validates given value against `Schema.TYPE_RANGE` data type. Raises\n    TypeError or ValueError if something is wrong. Returns None if everything\n    is OK."
  },
  {
    "code": "def is_valid(number):\n    n = str(number)\n    if not n.isdigit():\n        return False\n    return int(n[-1]) == get_check_digit(n[:-1])",
    "docstring": "determines whether the card number is valid."
  },
  {
    "code": "def unaccent(string, encoding=\"utf-8\"):\n    string = to_unicode(string)\n    if has_unidecode:\n        return unidecode.unidecode(string)\n    if PYTHON_VERSION < 3:\n        if type(string) == str:\n            string = unicode(string, encoding)\n        nfkd_form = unicodedata.normalize('NFKD', string)\n        return u\"\".join([c for c in nfkd_form if not unicodedata.combining(c)]).encode(\"ascii\", \"ignore\")\n    else:\n        return string",
    "docstring": "not just unaccent, but full to-ascii transliteration"
  },
  {
    "code": "def get_global_vars(func):\n    closure = getclosurevars(func)\n    if closure['nonlocal']:\n        raise TypeError(\"Can't launch a job with closure variables: %s\" %\n                        closure['nonlocals'].keys())\n    globalvars = dict(modules={},\n                      functions={},\n                      vars={})\n    for name, value in closure['global'].items():\n        if inspect.ismodule(value):\n            globalvars['modules'][name] = value.__name__\n        elif inspect.isfunction(value) or inspect.ismethod(value):\n            globalvars['functions'][name] = value\n        else:\n            globalvars['vars'][name] = value\n    return globalvars",
    "docstring": "Store any methods or variables bound from the function's closure\n\n    Args:\n        func (function): function to inspect\n\n    Returns:\n        dict: mapping of variable names to globally bound VARIABLES"
  },
  {
    "code": "def by_type(self, type_name):\n        if IRestorator.providedBy(type_name):\n            type_name = type_name.type_name\n        return (x[1] for x in self._links if x[0] == type_name)",
    "docstring": "Return an iterator of doc_ids of the documents of the\n        specified type."
  },
  {
    "code": "def remove_all_static_host_mappings():\n    LOG.debug(\"remove_host_mapping() called\")\n    session = bc.get_writer_session()\n    try:\n        mapping = _lookup_all_host_mappings(\n                      session=session,\n                      is_static=True)\n        for host in mapping:\n            session.delete(host)\n        session.flush()\n    except c_exc.NexusHostMappingNotFound:\n        pass",
    "docstring": "Remove all entries defined in config file from mapping data base."
  },
  {
    "code": "def _exit_handling(self):\n        def close_asyncio_loop():\n            loop = None\n            try:\n                loop = asyncio.get_event_loop()\n            except AttributeError:\n                pass\n            if loop is not None:\n                loop.close()\n        atexit.register(close_asyncio_loop)",
    "docstring": "Makes sure the asyncio loop is closed."
  },
  {
    "code": "def __add_paths(self, config):\n        bin_path = os.path.join(self.directory.install_directory(self.feature_name), 'bin')\n        whitelist_executables = self._get_whitelisted_executables(config)\n        for f in os.listdir(bin_path):\n            for pattern in BLACKLISTED_EXECUTABLES:\n                if re.match(pattern, f):\n                    continue\n            if whitelist_executables and f not in whitelist_executables:\n                continue\n            self.directory.symlink_to_bin(f, os.path.join(bin_path, f))",
    "docstring": "add the proper resources into the environment"
  },
  {
    "code": "def stop_processing(self, warning=True):\n        if not self.__is_processing:\n            warning and LOGGER.warning(\n                \"!> {0} | Engine is not processing, 'stop_processing' request has been ignored!\".format(\n                    self.__class__.__name__))\n            return False\n        LOGGER.debug(\"> Stopping processing operation!\")\n        self.__is_processing = False\n        self.Application_Progress_Status_processing.Processing_label.setText(QString())\n        self.Application_Progress_Status_processing.Processing_progressBar.setRange(0, 100)\n        self.Application_Progress_Status_processing.Processing_progressBar.setValue(0)\n        self.Application_Progress_Status_processing.hide()\n        return True",
    "docstring": "Registers the end of a processing operation.\n\n        :param warning: Emit warning message.\n        :type warning: int\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def _plot_thermo(self, func, temperatures, factor=1, ax=None, ylabel=None, label=None, ylim=None, **kwargs):\n        ax, fig, plt = get_ax_fig_plt(ax)\n        values = []\n        for t in temperatures:\n            values.append(func(t, structure=self.structure) * factor)\n        ax.plot(temperatures, values, label=label, **kwargs)\n        if ylim:\n            ax.set_ylim(ylim)\n        ax.set_xlim((np.min(temperatures), np.max(temperatures)))\n        ylim = plt.ylim()\n        if ylim[0] < 0 < ylim[1]:\n            plt.plot(plt.xlim(), [0, 0], 'k-', linewidth=1)\n        ax.set_xlabel(r\"$T$ (K)\")\n        if ylabel:\n            ax.set_ylabel(ylabel)\n        return fig",
    "docstring": "Plots a thermodynamic property for a generic function from a PhononDos instance.\n\n        Args:\n            func: the thermodynamic function to be used to calculate the property\n            temperatures: a list of temperatures\n            factor: a multiplicative factor applied to the thermodynamic property calculated. Used to change\n                the units.\n            ax: matplotlib :class:`Axes` or None if a new figure should be created.\n            ylabel: label for the y axis\n            label: label of the plot\n            ylim: tuple specifying the y-axis limits.\n            kwargs: kwargs passed to the matplotlib function 'plot'.\n        Returns:\n            matplotlib figure"
  },
  {
    "code": "def parse_info(response):\r\n    info = {}\r\n    response = response.decode('utf-8')\r\n    def get_value(value):\r\n        if ',' and '=' not in value:\r\n            return value\r\n        sub_dict = {}\r\n        for item in value.split(','):\r\n            k, v = item.split('=')\r\n            try:\r\n                sub_dict[k] = int(v)\r\n            except ValueError:\r\n                sub_dict[k] = v\r\n        return sub_dict\r\n    data = info\r\n    for line in response.splitlines():\r\n        keyvalue = line.split(':')\r\n        if len(keyvalue) == 2:\r\n            key, value = keyvalue\r\n            try:\r\n                data[key] = int(value)\r\n            except ValueError:\r\n                data[key] = get_value(value)\r\n        else:\r\n            data = {}\r\n            info[line[2:]] = data\r\n    return info",
    "docstring": "Parse the response of Redis's INFO command into a Python dict.\r\nIn doing so, convert byte data into unicode."
  },
  {
    "code": "def _updateWordSet(self):\n        self._wordSet = set(self._keywords) | set(self._customCompletions)\n        start = time.time()\n        for line in self._qpart.lines:\n            for match in _wordRegExp.findall(line):\n                self._wordSet.add(match)\n            if time.time() - start > self._WORD_SET_UPDATE_MAX_TIME_SEC:\n                break",
    "docstring": "Make a set of words, which shall be completed, from text"
  },
  {
    "code": "def get_inputs(node, kwargs):\n    name = node[\"name\"]\n    proc_nodes = kwargs[\"proc_nodes\"]\n    index_lookup = kwargs[\"index_lookup\"]\n    inputs = node[\"inputs\"]\n    attrs = node.get(\"attrs\", {})\n    input_nodes = []\n    for ip in inputs:\n        input_node_id = index_lookup[ip[0]]\n        input_nodes.append(proc_nodes[input_node_id].name)\n    return name, input_nodes, attrs",
    "docstring": "Helper function to get inputs"
  },
  {
    "code": "def _update_records(self, records, data):\n        data = {k: v for k, v in data.items() if v}\n        records = [dict(record, **data) for record in records]\n        return self._apicall(\n            'updateDnsRecords',\n            domainname=self.domain,\n            dnsrecordset={'dnsrecords': records},\n        ).get('dnsrecords', [])",
    "docstring": "Insert or update a list of DNS records, specified in the netcup API\n        convention.\n\n        The fields ``hostname``, ``type``, and ``destination`` are mandatory\n        and must be provided either in the record dict or through ``data``!"
  },
  {
    "code": "def modpath_pkg_resources(module, entry_point):\n    result = []\n    try:\n        path = resource_filename_mod_entry_point(module.__name__, entry_point)\n    except ImportError:\n        logger.warning(\"module '%s' could not be imported\", module.__name__)\n    except Exception:\n        logger.warning(\"%r does not appear to be a valid module\", module)\n    else:\n        if path:\n            result.append(path)\n    return result",
    "docstring": "Goes through pkg_resources for compliance with various PEPs.\n\n    This one accepts a module as argument."
  },
  {
    "code": "def prep_for_intensity_plot(data, meth_code, dropna=(), reqd_cols=()):\n    dropna = list(dropna)\n    reqd_cols = list(reqd_cols)\n    try:\n        magn_col = get_intensity_col(data)\n    except AttributeError:\n        return False, \"Could not get intensity method from data\"\n    if magn_col not in dropna:\n        dropna.append(magn_col)\n    data = data.dropna(axis=0, subset=dropna)\n    if 'method_codes' not in reqd_cols:\n        reqd_cols.append('method_codes')\n    if magn_col not in reqd_cols:\n        reqd_cols.append(magn_col)\n    try:\n        data = data[reqd_cols]\n    except KeyError as ex:\n        print(ex)\n        missing = set(reqd_cols).difference(data.columns)\n        return False, \"missing these required columns: {}\".format(\", \".join(missing))\n    data = data[data['method_codes'].str.contains(meth_code).astype(bool)]\n    return True, data",
    "docstring": "Strip down measurement data to what is needed for an intensity plot.\n    Find the column with intensity data.\n    Drop empty columns, and make sure required columns are present.\n    Keep only records with the specified method code.\n\n    Parameters\n    ----------\n    data : pandas DataFrame\n        measurement dataframe\n    meth_code : str\n        MagIC method code to include, i.e. 'LT-AF-Z'\n    dropna : list\n        columns that must not be empty\n    reqd_cols : list\n        columns that must be present\n\n    Returns\n    ----------\n    status : bool\n        True if successful, else False\n    data : pandas DataFrame\n        measurement data with required columns"
  },
  {
    "code": "def overtime(self):\n        if self._overtime.lower() == 'ot':\n            return 1\n        if self._overtime.lower() == 'so':\n            return SHOOTOUT\n        if self._overtime == '':\n            return 0\n        num = re.findall(r'\\d+', self._overtime)\n        if len(num) > 0:\n            return num[0]\n        return 0",
    "docstring": "Returns an ``int`` of the number of overtimes that were played during\n        the game, or an int constant if the game went to a shootout."
  },
  {
    "code": "def _maybe_purge_cache(self):\n        if self._last_reload_check + MIN_CHECK_INTERVAL > time.time():\n            return\n        for name, tmpl in list(self.cache.items()):\n            if not os.stat(tmpl.path):\n                self.cache.pop(name)\n                continue\n            if os.stat(tmpl.path).st_mtime > tmpl.mtime:\n                self.cache.clear()\n                break\n        self._last_reload_check = time.time()",
    "docstring": "If enough time since last check has elapsed, check if any\n        of the cached templates has changed. If any of the template\n        files were deleted, remove that file only. If any were\n        changed, then purge the entire cache."
  },
  {
    "code": "def get_subwords(self, word, on_unicode_error='strict'):\n        pair = self.f.getSubwords(word, on_unicode_error)\n        return pair[0], np.array(pair[1])",
    "docstring": "Given a word, get the subwords and their indicies."
  },
  {
    "code": "def toggle_rich_text(self, checked):\r\n        if checked:\r\n            self.docstring = not checked\r\n            self.switch_to_rich_text()\r\n        self.set_option('rich_mode', checked)",
    "docstring": "Toggle between sphinxified docstrings or plain ones"
  },
  {
    "code": "def get_entities_tsv(namespace, workspace, etype):\n    uri = \"workspaces/{0}/{1}/entities/{2}/tsv\".format(namespace,\n                                                workspace, etype)\n    return __get(uri)",
    "docstring": "List entities of given type in a workspace as a TSV.\n\n    Identical to get_entities(), but the response is a TSV.\n\n    Args:\n        namespace (str): project to which workspace belongs\n        workspace (str): Workspace name\n        etype (str): Entity type\n\n    Swagger:\n        https://api.firecloud.org/#!/Entities/browserDownloadEntitiesTSV"
  },
  {
    "code": "def _find_cont_gaussian_smooth(wl, fluxes, ivars, w):\n    print(\"Finding the continuum\")\n    bot = np.dot(ivars, w.T)\n    top = np.dot(fluxes*ivars, w.T)\n    bad = bot == 0\n    cont = np.zeros(top.shape)\n    cont[~bad] = top[~bad] / bot[~bad]\n    return cont",
    "docstring": "Returns the weighted mean block of spectra\n\n    Parameters\n    ----------\n    wl: numpy ndarray\n        wavelength vector\n    flux: numpy ndarray\n        block of flux values \n    ivar: numpy ndarray\n        block of ivar values\n    L: float\n        width of Gaussian used to assign weights\n\n    Returns\n    -------\n    smoothed_fluxes: numpy ndarray\n        block of smoothed flux values, mean spectra"
  },
  {
    "code": "def togglePopup(self):\r\n        if not self._popupWidget.isVisible():\r\n            self.showPopup()\r\n        elif self._popupWidget.currentMode() != self._popupWidget.Mode.Dialog:\r\n            self._popupWidget.close()",
    "docstring": "Toggles whether or not the popup is visible."
  },
  {
    "code": "def createLrrBafPlot(raw_dir, problematic_samples, format, dpi, out_prefix):\n    dir_name = out_prefix + \".LRR_BAF\"\n    if not os.path.isdir(dir_name):\n        os.mkdir(dir_name)\n    baf_lrr_plot_options = [\"--problematic-samples\", problematic_samples,\n                            \"--raw-dir\", raw_dir, \"--format\", format,\n                            \"--dpi\", str(dpi),\n                            \"--out\", os.path.join(dir_name, \"baf_lrr\")]\n    try:\n        baf_lrr_plot.main(baf_lrr_plot_options)\n    except baf_lrr_plot.ProgramError as e:\n        msg = \"BAF LRR plot: {}\".format(e)\n        raise ProgramError(msg)",
    "docstring": "Creates the LRR and BAF plot.\n\n    :param raw_dir: the directory containing the intensities.\n    :param problematic_samples: the file containing the problematic samples.\n    :param format: the format of the plot.\n    :param dpi: the DPI of the resulting images.\n    :param out_prefix: the prefix of the output file.\n\n    :type raw_dir: str\n    :type problematic_samples: str\n    :type format: str\n    :type out_prefix: str\n\n    Creates the LRR (Log R Ratio) and BAF (B Allele Frequency) of the\n    problematic samples using the :py:mod:`pyGenClean.SexCheck.baf_lrr_plot`\n    module."
  },
  {
    "code": "def format_jid_instance_ext(jid, job):\n    ret = format_job_instance(job)\n    ret.update({\n        'JID': jid,\n        'StartTime': jid_to_time(jid)})\n    return ret",
    "docstring": "Format the jid correctly with jid included"
  },
  {
    "code": "def setStartSegment(self, segment):\n        segments = self.segments\n        if not isinstance(segment, int):\n            segmentIndex = segments.index(segment)\n        else:\n            segmentIndex = segment\n        if len(self.segments) < 2:\n            return\n        if segmentIndex == 0:\n            return\n        if segmentIndex >= len(segments):\n            raise ValueError((\"The contour does not contain a segment \"\n                              \"at index %d\" % segmentIndex))\n        self._setStartSegment(segmentIndex)",
    "docstring": "Set the first segment on the contour.\n        segment can be a segment object or an index."
  },
  {
    "code": "def iterate(self, max_iter=None):\n        with self as active_streamer:\n            for n, obj in enumerate(active_streamer.stream_):\n                if max_iter is not None and n >= max_iter:\n                    break\n                yield obj",
    "docstring": "Instantiate an iterator.\n\n        Parameters\n        ----------\n        max_iter : None or int > 0\n            Maximum number of iterations to yield.\n            If ``None``, exhaust the stream.\n\n        Yields\n        ------\n        obj : Objects yielded by the streamer provided on init.\n\n        See Also\n        --------\n        cycle : force an infinite stream."
  },
  {
    "code": "def resume(env, identifier):\n    vsi = SoftLayer.VSManager(env.client)\n    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')\n    env.client['Virtual_Guest'].resume(id=vs_id)",
    "docstring": "Resumes a paused virtual server."
  },
  {
    "code": "def check_length_of_shape_or_intercept_names(name_list,\n                                             num_alts,\n                                             constrained_param,\n                                             list_title):\n    if len(name_list) != (num_alts - constrained_param):\n        msg_1 = \"{} is of the wrong length:\".format(list_title)\n        msg_2 = \"len({}) == {}\".format(list_title, len(name_list))\n        correct_length = num_alts - constrained_param\n        msg_3 = \"The correct length is: {}\".format(correct_length)\n        total_msg = \"\\n\".join([msg_1, msg_2, msg_3])\n        raise ValueError(total_msg)\n    return None",
    "docstring": "Ensures that the length of the parameter names matches the number of\n    parameters that will be estimated. Will raise a ValueError otherwise.\n\n    Parameters\n    ----------\n    name_list : list of strings.\n        Each element should be the name of a parameter that is to be estimated.\n    num_alts : int.\n        Should be the total number of alternatives in the universal choice set\n        for this dataset.\n    constrainted_param : {0, 1, True, False}\n        Indicates whether (1 or True) or not (0 or False) one of the type of\n        parameters being estimated will be constrained. For instance,\n        constraining one of the intercepts.\n    list_title : str.\n        Should specify the type of parameters whose names are being checked.\n        Examples include 'intercept_params' or 'shape_params'.\n\n    Returns\n    -------\n    None."
  },
  {
    "code": "def choice(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = (), random=random) -> Entry:\n        chosen_entry = None\n        for i, entry in enumerate(self.find_all(board, minimum_weight=minimum_weight, exclude_moves=exclude_moves)):\n            if chosen_entry is None or random.randint(0, i) == i:\n                chosen_entry = entry\n        if chosen_entry is None:\n            raise IndexError()\n        return chosen_entry",
    "docstring": "Uniformly selects a random entry for the given position.\n\n        :raises: :exc:`IndexError` if no entries are found."
  },
  {
    "code": "async def start_child():\n    logger.info('Started to watch for code changes')\n    loop = asyncio.get_event_loop()\n    watcher = aionotify.Watcher()\n    flags = (\n        aionotify.Flags.MODIFY |\n        aionotify.Flags.DELETE |\n        aionotify.Flags.ATTRIB |\n        aionotify.Flags.MOVED_TO |\n        aionotify.Flags.MOVED_FROM |\n        aionotify.Flags.CREATE |\n        aionotify.Flags.DELETE_SELF |\n        aionotify.Flags.MOVE_SELF\n    )\n    watched_dirs = list_dirs()\n    for dir_name in watched_dirs:\n        watcher.watch(path=dir_name, flags=flags)\n    await watcher.setup(loop)\n    while True:\n        evt = await watcher.get_event()\n        file_path = path.join(evt.alias, evt.name)\n        if file_path in watched_dirs or file_path.endswith('.py'):\n            await asyncio.sleep(settings.CODE_RELOAD_DEBOUNCE)\n            break\n    watcher.close()\n    exit_for_reload()",
    "docstring": "Start the child process that will look for changes in modules."
  },
  {
    "code": "def to_array(self):\n        array = super(SuccessfulPayment, self).to_array()\n        array['currency'] = u(self.currency)\n        array['total_amount'] = int(self.total_amount)\n        array['invoice_payload'] = u(self.invoice_payload)\n        array['telegram_payment_charge_id'] = u(self.telegram_payment_charge_id)\n        array['provider_payment_charge_id'] = u(self.provider_payment_charge_id)\n        if self.shipping_option_id is not None:\n            array['shipping_option_id'] = u(self.shipping_option_id)\n        if self.order_info is not None:\n            array['order_info'] = self.order_info.to_array()\n        return array",
    "docstring": "Serializes this SuccessfulPayment to a dictionary.\n\n        :return: dictionary representation of this object.\n        :rtype: dict"
  },
  {
    "code": "def find_step_impl(self, step):\n        result = None\n        for si in self.steps[step.step_type]:\n            matches = si.match(step.match)\n            if matches:\n                if result:\n                    raise AmbiguousStepImpl(step, result[0], si)\n                args = [self._apply_transforms(arg, si) for arg in matches.groups()]\n                result = si, args\n        if not result:\n            raise UndefinedStepImpl(step)\n        return result",
    "docstring": "Find the implementation of the step for the given match string. Returns the StepImpl object\n        corresponding to the implementation, and the arguments to the step implementation. If no\n        implementation is found, raises UndefinedStepImpl. If more than one implementation is\n        found, raises AmbiguousStepImpl.\n        \n        Each of the arguments returned will have been transformed by the first matching transform\n        implementation."
  },
  {
    "code": "def do_up(self,args):\n        parser = CommandArgumentParser(\"up\")\n        args = vars(parser.parse_args(args))\n        if None == self.parent:\n            print \"You're at the root. Try 'quit' to quit\"\n        else:\n            return True",
    "docstring": "Navigate up by one level.\n\n        For example, if you are in `(aws)/stack:.../asg:.../`, executing `up` will place you in `(aws)/stack:.../`.\n\n        up -h for more details"
  },
  {
    "code": "def is_iterable_of_int(l):\n    r\n    if not is_iterable(l):\n        return False\n    return all(is_int(value) for value in l)",
    "docstring": "r\"\"\" Checks if l is iterable and contains only integral types"
  },
  {
    "code": "def run_iqtree(phy, model, threads, cluster, node):\n    if threads > 24:\n        ppn = 24\n    else:\n        ppn = threads\n    tree = '%s.treefile' % (phy)\n    if check(tree) is False:\n        if model is False:\n            model = 'TEST'\n        dir = os.getcwd()\n        command = 'iqtree-omp -s %s -m %s -nt %s -quiet' % \\\n                    (phy, model, threads)\n        if cluster is False:\n            p = Popen(command, shell = True)\n        else:\n            if node is False:\n               node = '1'\n            qsub = 'qsub -l nodes=%s:ppn=%s -m e -N iqtree' % (node, ppn)\n            command = 'cd /tmp; mkdir iqtree; cd iqtree; cp %s/%s .; %s; mv * %s/; rm -r ../iqtree' \\\n                    % (dir, phy, command, dir)\n            re_call = 'cd %s; %s --no-fast --iq' % (dir.rsplit('/', 1)[0], ' '.join(sys.argv))\n            p = Popen('echo \"%s;%s\" | %s' % (command, re_call, qsub), shell = True)\n        p.communicate()\n    return tree",
    "docstring": "run IQ-Tree"
  },
  {
    "code": "def clone(cls, repo_location, repo_dir=None,\n              branch_or_tag=None, temp=False):\n        if temp:\n            reponame = repo_location.rsplit('/', 1)[-1]\n            suffix = '%s.temp_simpl_GitRepo' % '_'.join(\n                [str(x) for x in (reponame, branch_or_tag) if x])\n            repo_dir = create_tempdir(suffix=suffix, delete=True)\n        else:\n            repo_dir = repo_dir or os.getcwd()\n        git_clone(repo_dir, repo_location, branch_or_tag=branch_or_tag)\n        return cls(repo_dir)",
    "docstring": "Clone repo at repo_location into repo_dir and checkout branch_or_tag.\n\n        Defaults into current working directory if repo_dir is not supplied.\n\n        If 'temp' is True, a temporary directory will be created for you\n        and the repository will be cloned into it. The tempdir is scheduled\n        for deletion (when the process exits) through an exit function\n        registered with the atexit module. If 'temp' is True, repo_dir\n        is ignored.\n\n        If branch_or_tag is not specified, the HEAD of the primary\n        branch of the cloned repo is checked out."
  },
  {
    "code": "def init_celery(project_name):\n    os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%s.settings' % project_name)\n    app = Celery(project_name)\n    app.config_from_object('django.conf:settings')\n    app.autodiscover_tasks(settings.INSTALLED_APPS, related_name='tasks')\n    return app",
    "docstring": "init celery app without the need of redundant code"
  },
  {
    "code": "def encode_packet(packet: dict) -> str:\n    if packet['protocol'] == 'rfdebug':\n        return '10;RFDEBUG=' + packet['command'] + ';'\n    elif packet['protocol'] == 'rfudebug':\n        return '10;RFDEBUG=' + packet['command'] + ';'\n    else:\n        return SWITCH_COMMAND_TEMPLATE.format(\n            node=PacketHeader.master.value,\n            **packet\n        )",
    "docstring": "Construct packet string from packet dictionary.\n\n    >>> encode_packet({\n    ...     'protocol': 'newkaku',\n    ...     'id': '000001',\n    ...     'switch': '01',\n    ...     'command': 'on',\n    ... })\n    '10;newkaku;000001;01;on;'"
  },
  {
    "code": "def _get_adjustment(mag, year, mmin, completeness_year, t_f, mag_inc=0.1):\n    if len(completeness_year) == 1:\n        if (mag >= mmin) and (year >= completeness_year[0]):\n            return 1.0\n        else:\n            return False\n    kval = int(((mag - mmin) / mag_inc)) + 1\n    if (kval >= 1) and (year >= completeness_year[kval - 1]):\n        return t_f\n    else:\n        return False",
    "docstring": "If the magnitude is greater than the minimum in the completeness table\n    and the year is greater than the corresponding completeness year then\n    return the Weichert factor\n\n    :param float mag:\n        Magnitude of an earthquake\n\n    :param float year:\n        Year of earthquake\n\n    :param np.ndarray completeness_table:\n        Completeness table\n\n    :param float mag_inc:\n        Magnitude increment\n\n    :param float t_f:\n        Weichert adjustment factor\n\n    :returns:\n        Weichert adjustment factor is event is in complete part of catalogue\n        (0.0 otherwise)"
  },
  {
    "code": "def add(self, chassis):\n        self.chassis_chain[chassis] = IxeChassis(self.session, chassis, len(self.chassis_chain) + 1)\n        self.chassis_chain[chassis].connect()",
    "docstring": "add chassis.\n\n        :param chassis: chassis IP address."
  },
  {
    "code": "def elapsed():\n    environ.abort_thread()\n    step = _cd.project.get_internal_project().current_step\n    r = _get_report()\n    r.append_body(render.elapsed_time(step.elapsed_time))\n    result = '[ELAPSED]: {}\\n'.format(timedelta(seconds=step.elapsed_time))\n    r.stdout_interceptor.write_source(result)",
    "docstring": "Displays the elapsed time since the step started running."
  },
  {
    "code": "def record_little_endian(self):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('Path Table Record not yet initialized')\n        return self._record(self.extent_location, self.parent_directory_num)",
    "docstring": "A method to generate a string representing the little endian version of\n        this Path Table Record.\n\n        Parameters:\n         None.\n        Returns:\n         A string representing the little endian version of this Path Table Record."
  },
  {
    "code": "def schwefelmult(self, x, pen_fac=1e4):\n        y = [x] if isscalar(x[0]) else x\n        N = len(y[0])\n        f = array([418.9829 * N - 1.27275661e-5 * N - sum(x * np.sin(np.abs(x)**0.5))\n                + pen_fac * sum((abs(x) > 500) * (abs(x) - 500)**2) for x in y])\n        return f if len(f) > 1 else f[0]",
    "docstring": "multimodal Schwefel function with domain -500..500"
  },
  {
    "code": "def coerce(cls, arg):\n        try:\n            return cls(arg).value\n        except (ValueError, TypeError):\n            raise InvalidParameterDatatype(\"%s coerce error\" % (cls.__name__,))",
    "docstring": "Given an arg, return the appropriate value given the class."
  },
  {
    "code": "def breadcrumb(self):\n        ret = []\n        here = self\n        while here:\n            ret.append(here)\n            here = here.parent\n        return list(reversed(ret))",
    "docstring": "Get the category hierarchy leading up to this category, including\n        root and self.\n\n        For example, path/to/long/category will return a list containing\n        Category('path'), Category('path/to'), and Category('path/to/long')."
  },
  {
    "code": "def rm_known_host(user=None, hostname=None, config=None, port=None):\n    if not hostname:\n        return {'status': 'error',\n                'error': 'hostname argument required'}\n    full = _get_known_hosts_file(config=config, user=user)\n    if isinstance(full, dict):\n        return full\n    if not os.path.isfile(full):\n        return {'status': 'error',\n                'error': 'Known hosts file {0} does not exist'.format(full)}\n    ssh_hostname = _hostname_and_port_to_ssh_hostname(hostname, port)\n    cmd = ['ssh-keygen', '-R', ssh_hostname, '-f', full]\n    cmd_result = __salt__['cmd.run'](cmd, python_shell=False)\n    if not salt.utils.platform.is_windows():\n        if os.geteuid() == 0 and user:\n            uinfo = __salt__['user.info'](user)\n            os.chown(full, uinfo['uid'], uinfo['gid'])\n    return {'status': 'removed', 'comment': cmd_result}",
    "docstring": "Remove all keys belonging to hostname from a known_hosts file.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' ssh.rm_known_host <user> <hostname>"
  },
  {
    "code": "def list(self):\n        before, after = self.filename_template.split('%s', 1)\n        filename_re = re.compile(r'%s(.{5,})%s$' % (re.escape(before),\n                                                    re.escape(after)))\n        result = []\n        for filename in os.listdir(self.path):\n            if filename.endswith(_fs_transaction_suffix):\n                continue\n            match = filename_re.match(filename)\n            if match is not None:\n                result.append(match.group(1))\n        return result",
    "docstring": "Lists all sessions in the store.\n\n        .. versionadded:: 0.6"
  },
  {
    "code": "def warn(self, msg):\n        self.warnings.append(\n            self.state.document.reporter.warning(msg, line=self.lineno)\n        )",
    "docstring": "Add a warning message.\n\n        :param msg: The warning message to add.\n        :type msg: str"
  },
  {
    "code": "def instances(self):\n        ist = lib.EnvGetNextInstanceInClass(self._env, self._cls, ffi.NULL)\n        while ist != ffi.NULL:\n            yield Instance(self._env, ist)\n            ist = lib.EnvGetNextInstanceInClass(self._env, self._cls, ist)",
    "docstring": "Iterate over the instances of the class."
  },
  {
    "code": "def to_networkx_graph(self, node_attribute_name='bias', edge_attribute_name='bias'):\n        import networkx as nx\n        BQM = nx.Graph()\n        BQM.add_nodes_from(((v, {node_attribute_name: bias, 'vartype': self.vartype})\n                            for v, bias in iteritems(self.linear)))\n        BQM.add_edges_from(((u, v, {edge_attribute_name: bias}) for (u, v), bias in iteritems(self.quadratic)))\n        BQM.offset = self.offset\n        BQM.vartype = self.vartype\n        return BQM",
    "docstring": "Convert a binary quadratic model to NetworkX graph format.\n\n        Args:\n            node_attribute_name (hashable, optional, default='bias'):\n                Attribute name for linear biases.\n\n            edge_attribute_name (hashable, optional, default='bias'):\n                Attribute name for quadratic biases.\n\n        Returns:\n            :class:`networkx.Graph`: A NetworkX graph with biases stored as\n            node/edge attributes.\n\n        Examples:\n            This example converts a binary quadratic model to a NetworkX graph, using first\n            the default attribute name for quadratic biases then \"weight\".\n\n            >>> import networkx as nx\n            >>> bqm = dimod.BinaryQuadraticModel({0: 1, 1: -1, 2: .5},\n            ...                                  {(0, 1): .5, (1, 2): 1.5},\n            ...                                  1.4,\n            ...                                  dimod.SPIN)\n            >>> BQM = bqm.to_networkx_graph()\n            >>> BQM[0][1]['bias']\n            0.5\n            >>> BQM.node[0]['bias']\n            1\n            >>> BQM_w = bqm.to_networkx_graph(edge_attribute_name='weight')\n            >>> BQM_w[0][1]['weight']\n            0.5"
  },
  {
    "code": "def name_check(self, original, loc, tokens):\n        internal_assert(len(tokens) == 1, \"invalid name tokens\", tokens)\n        if self.strict:\n            self.unused_imports.discard(tokens[0])\n        if tokens[0] == \"exec\":\n            return self.check_py(\"3\", \"exec function\", original, loc, tokens)\n        elif tokens[0].startswith(reserved_prefix):\n            raise self.make_err(CoconutSyntaxError, \"variable names cannot start with reserved prefix \" + reserved_prefix, original, loc)\n        else:\n            return tokens[0]",
    "docstring": "Check the given base name."
  },
  {
    "code": "def _get_projection(self):\n        try:\n            proj_str = self.nc.attrs['gdal_projection']\n        except TypeError:\n            proj_str = self.nc.attrs['gdal_projection'].decode()\n        radius_a = proj_str.split('+a=')[-1].split()[0]\n        if float(radius_a) > 10e3:\n            units = 'm'\n            scale = 1.0\n        else:\n            units = 'km'\n            scale = 1e3\n        if 'units' not in proj_str:\n            proj_str = proj_str + ' +units=' + units\n        area_extent = (float(self.nc.attrs['gdal_xgeo_up_left']) / scale,\n                       float(self.nc.attrs['gdal_ygeo_low_right']) / scale,\n                       float(self.nc.attrs['gdal_xgeo_low_right']) / scale,\n                       float(self.nc.attrs['gdal_ygeo_up_left']) / scale)\n        return proj_str, area_extent",
    "docstring": "Get projection from the NetCDF4 attributes"
  },
  {
    "code": "def stream_decode_response_unicode(iterator, r):\n    encoding = get_encoding_from_headers(r.headers)\n    if encoding is None:\n        for item in iterator:\n            yield item\n        return\n    decoder = codecs.getincrementaldecoder(encoding)(errors='replace')\n    for chunk in iterator:\n        rv = decoder.decode(chunk)\n        if rv:\n            yield rv\n    rv = decoder.decode('', final=True)\n    if rv:\n        yield rv",
    "docstring": "Stream decodes a iterator."
  },
  {
    "code": "def get_zones(self):\n        home_data = self.get_home()\n        if not home_data['isSuccess']:\n            return []\n        zones = []\n        for receiver in home_data['data']['receivers']:\n            for zone in receiver['zones']:\n                zones.append(zone)\n        return zones",
    "docstring": "Get all zones"
  },
  {
    "code": "def labels_to_onehots(labels, num_classes):\n    batch_size = labels.get_shape().as_list()[0]\n    with tf.name_scope(\"one_hot\"):\n        labels = tf.expand_dims(labels, 1)\n        indices = tf.expand_dims(tf.range(0, batch_size, 1), 1)\n        sparse_ptrs = tf.concat(1, [indices, labels], name=\"ptrs\")\n        onehots = tf.sparse_to_dense(sparse_ptrs, [batch_size, num_classes],\n                                     1.0, 0.0)\n        return onehots",
    "docstring": "Convert a vector of integer class labels to a matrix of one-hot target vectors.\n\n    :param labels: a vector of integer labels, 0 to num_classes. Has shape (batch_size,).\n    :param num_classes: the total number of classes\n    :return: has shape (batch_size, num_classes)"
  },
  {
    "code": "def equiv(self, other):\n        if self == other:\n            return True\n        elif (not isinstance(other, Weighting) or\n              self.exponent != other.exponent):\n            return False\n        elif isinstance(other, MatrixWeighting):\n            return other.equiv(self)\n        elif isinstance(other, ConstWeighting):\n            return np.array_equiv(self.array, other.const)\n        else:\n            return np.array_equal(self.array, other.array)",
    "docstring": "Return True if other is an equivalent weighting.\n\n        Returns\n        -------\n        equivalent : bool\n            ``True`` if ``other`` is a `Weighting` instance with the same\n            `Weighting.impl`, which yields the same result as this\n            weighting for any input, ``False`` otherwise. This is checked\n            by entry-wise comparison of arrays/constants."
  },
  {
    "code": "def check_data_port_connection(self, check_data_port):\n        for data_flow in self.data_flows.values():\n            from_port = self.get_data_port(data_flow.from_state, data_flow.from_key)\n            to_port = self.get_data_port(data_flow.to_state, data_flow.to_key)\n            if check_data_port is from_port or check_data_port is to_port:\n                if not (from_port.data_type is object or to_port.data_type is object):\n                    if not type_inherits_of_type(from_port.data_type, to_port.data_type):\n                        return False, \"Connection of two non-compatible data types\"\n        return True, \"valid\"",
    "docstring": "Checks the connection validity of a data port\n\n        The method is called by a child state to check the validity of a data port in case it is connected with data\n        flows. The data port does not belong to 'self', but to one of self.states.\n        If the data port is connected to a data flow, the method checks, whether these connect consistent data types\n        of ports.\n\n        :param rafcon.core.data_port.DataPort check_data_port: The port to check\n        :return: valid, message"
  },
  {
    "code": "def required(self, method, _dict, require):\n        for key in require:\n            if key not in _dict:\n                raise LunrError(\"'%s' is required argument for method '%s'\"\n                                % (key, method))",
    "docstring": "Ensure the required items are in the dictionary"
  },
  {
    "code": "def at_line(self, line: FileLine) -> Iterator[InsertionPoint]:\n        logger.debug(\"finding insertion points at line: %s\", str(line))\n        filename = line.filename\n        line_num = line.num\n        for ins in self.in_file(filename):\n            if line_num == ins.location.line:\n                logger.debug(\"found insertion point at line [%s]: %s\",\n                             str(line), ins)\n                yield ins",
    "docstring": "Returns an iterator over all of the insertion points located at a\n        given line."
  },
  {
    "code": "def _access_token(self, request: Request=None, page_id: Text=''):\n        if not page_id:\n            msg = request.message\n            page_id = msg.get_page_id()\n        page = self.settings()\n        if page['page_id'] == page_id:\n            return page['page_token']\n        raise PlatformOperationError('Trying to get access token of the '\n                                     'page \"{}\", which is not configured.'\n                                     .format(page_id))",
    "docstring": "Guess the access token for that specific request."
  },
  {
    "code": "def existing_path(value):\n    if os.path.exists(value):\n        return value\n    else:\n        raise argparse.ArgumentTypeError(\"Path {0} not found\".format(value))",
    "docstring": "Throws when the path does not exist"
  },
  {
    "code": "def _textlist(self, _addtail=False):\n    result = []\n    if (not _addtail) and (self.text is not None):\n        result.append(self.text)\n    for elem in self:\n        result.extend(elem.textlist(True))\n    if _addtail and self.tail is not None:\n        result.append(self.tail)\n    return result",
    "docstring": "Returns a list of text strings contained within an element and its sub-elements.\n\n    Helpful for extracting text from prose-oriented XML (such as XHTML or DocBook)."
  },
  {
    "code": "def modified_files(root, tracked_only=False, commit=None):\n    assert os.path.isabs(root), \"Root has to be absolute, got: %s\" % root\n    command = ['hg', 'status']\n    if commit:\n        command.append('--change=%s' % commit)\n    status_lines = subprocess.check_output(command).decode('utf-8').split(\n        os.linesep)\n    modes = ['M', 'A']\n    if not tracked_only:\n        modes.append(r'\\?')\n    modes_str = '|'.join(modes)\n    modified_file_status = utils.filter_lines(\n        status_lines,\n        r'(?P<mode>%s) (?P<filename>.+)' % modes_str,\n        groups=('filename', 'mode'))\n    return dict((os.path.join(root, filename), mode)\n                for filename, mode in modified_file_status)",
    "docstring": "Returns a list of files that has been modified since the last commit.\n\n    Args:\n      root: the root of the repository, it has to be an absolute path.\n      tracked_only: exclude untracked files when True.\n      commit: SHA1 of the commit. If None, it will get the modified files in the\n        working copy.\n\n    Returns: a dictionary with the modified files as keys, and additional\n      information as value. In this case it adds the status returned by\n      hg status."
  },
  {
    "code": "def frontendediting_request_processor(page, request):\n    if 'frontend_editing' not in request.GET:\n        return\n    response = HttpResponseRedirect(request.path)\n    if request.user.has_module_perms('page'):\n        if 'frontend_editing' in request.GET:\n            try:\n                enable_fe = int(request.GET['frontend_editing']) > 0\n            except ValueError:\n                enable_fe = False\n            if enable_fe:\n                response.set_cookie(str('frontend_editing'), enable_fe)\n                clear_cache()\n            else:\n                response.delete_cookie(str('frontend_editing'))\n                clear_cache()\n    else:\n        response.delete_cookie(str('frontend_editing'))\n    return response",
    "docstring": "Sets the frontend editing state in the cookie depending on the\n    ``frontend_editing`` GET parameter and the user's permissions."
  },
  {
    "code": "def remove_raw(self, length_tag, value_tag):\n        self.raw_len_tags.remove(length_tag)\n        self.raw_data_tags.remove(value_tag)\n        return",
    "docstring": "Remove the tags for a data type field.\n\n        :param length_tag: tag number of the length field.\n        :param value_tag: tag number of the value field.\n\n        You can remove either private or standard data field definitions in\n        case a particular application uses them for a field of a different\n        type."
  },
  {
    "code": "def deltas(errors, epsilon, mean, std):\n    below = errors[errors <= epsilon]\n    if not len(below):\n        return 0, 0\n    return mean - below.mean(), std - below.std()",
    "docstring": "Compute mean and std deltas.\n\n    delta_mean = mean(errors) - mean(all errors below epsilon)\n    delta_std = std(errors) - std(all errors below epsilon)"
  },
  {
    "code": "def validate_offset(reference_event, estimated_event, t_collar=0.200, percentage_of_length=0.5):\n        if 'event_offset' in reference_event and 'event_offset' in estimated_event:\n            annotated_length = reference_event['event_offset'] - reference_event['event_onset']\n            return math.fabs(reference_event['event_offset'] - estimated_event['event_offset']) <= max(t_collar, percentage_of_length * annotated_length)\n        elif 'offset' in reference_event and 'offset' in estimated_event:\n            annotated_length = reference_event['offset'] - reference_event['onset']\n            return math.fabs(reference_event['offset'] - estimated_event['offset']) <= max(t_collar, percentage_of_length * annotated_length)",
    "docstring": "Validate estimated event based on event offset\n\n        Parameters\n        ----------\n        reference_event : dict\n            Reference event.\n\n        estimated_event : dict\n            Estimated event.\n\n        t_collar : float > 0, seconds\n            First condition, Time collar with which the estimated offset has to be in order to be consider valid estimation.\n            Default value 0.2\n\n        percentage_of_length : float in [0, 1]\n            Second condition, percentage of the length within which the estimated offset has to be in order to be\n            consider valid estimation.\n            Default value 0.5\n\n        Returns\n        -------\n        bool"
  },
  {
    "code": "def displaceAbs(x, y, sourcePos_x, sourcePos_y):\n    x_mapped = x - sourcePos_x\n    y_mapped = y - sourcePos_y\n    absmapped = np.sqrt(x_mapped**2+y_mapped**2)\n    return absmapped",
    "docstring": "calculates a grid of distances to the observer in angel\n\n    :param mapped_cartcoord: mapped cartesian coordinates\n    :type mapped_cartcoord: numpy array (n,2)\n    :param sourcePos: source position\n    :type sourcePos: numpy vector [x0,y0]\n    :returns:  array of displacement\n    :raises: AttributeError, KeyError"
  },
  {
    "code": "def teardown(self):\n        if not self._torn:\n            self._expectations = []\n            self._torn = True\n            self._teardown()",
    "docstring": "Clean up all expectations and restore the original attribute of the\n        mocked object."
  },
  {
    "code": "def draw(self, milliseconds, surface):\n        super(CollidableObj, self).draw(milliseconds, surface)",
    "docstring": "Render the bounds of this collision ojbect onto the specified surface."
  },
  {
    "code": "def clean_names(lines, ensure_unique_names=False, strip_prefix=False,\n                make_database_safe=False):\n    names = {}\n    for row in lines:\n        if strip_prefix:\n            row['name'] = row['name'][row['name'].find('-') + 1:]\n            if row['indexed_by'] is not None:\n                row['indexed_by'] = row['indexed_by'][row['indexed_by'].find(\n                    '-') + 1:]\n        if ensure_unique_names:\n            i = 1\n            while (row['name'] if i == 1 else\n                   row['name'] + \"-\" + str(i)) in names:\n                i += 1\n            names[row['name'] if i == 1 else row['name'] + \"-\" + str(i)] = 1\n            if i > 1:\n                row['name'] = row['name'] + \"-\" + str(i)\n        if make_database_safe:\n            row['name'] = row['name'].replace(\"-\", \"_\")\n    return lines",
    "docstring": "Clean the names.\n\n    Options to:\n     - strip prefixes on names\n     - enforce unique names\n     - make database safe names by converting - to _"
  },
  {
    "code": "def parse_line(self, line):\n        if line == '':\n            return\n        if regex_comment.search(line):\n            return\n        global_parameters = regex_global.search(line)\n        if global_parameters:\n            self.parse_global_meta(global_parameters.group('parameters'))\n            return\n        crtf_line = regex_line.search(line)\n        if crtf_line:\n            region = regex_region.search(crtf_line.group('region'))\n            type_ = region.group('type') or 'reg'\n            include = region.group('include') or '+'\n            region_type = region.group('regiontype').lower()\n            if region_type in self.valid_definition:\n                helper = CRTFRegionParser(self.global_meta, include, type_, region_type,\n                                          *crtf_line.group('region', 'parameters'))\n                self.shapes.append(helper.shape)\n            else:\n                self._raise_error(\"Not a valid CRTF Region type: '{0}'.\".format(region_type))\n        else:\n            self._raise_error(\"Not a valid CRTF line: '{0}'.\".format(line))\n            return",
    "docstring": "Parses a single line."
  },
  {
    "code": "def join(self):\n        pending = set()\n        exceptions = set()\n        while len(self._tasks) > 0 or len(pending) > 0:\n            while len(self._tasks) > 0 and len(pending) < self._concurrency:\n                task, args, kwargs = self._tasks.pop(0)\n                pending.add(task(*args, **kwargs))\n            (done, pending) = yield from asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)\n            for task in done:\n                if task.exception():\n                    exceptions.add(task.exception())\n        if len(exceptions) > 0:\n            raise exceptions.pop()",
    "docstring": "Wait for all task to finish"
  },
  {
    "code": "def dskrb2(vrtces, plates, corsys, corpar):\n    nv     = ctypes.c_int(len(vrtces))\n    vrtces = stypes.toDoubleMatrix(vrtces)\n    np     = ctypes.c_int(len(plates))\n    plates = stypes.toIntMatrix(plates)\n    corsys = ctypes.c_int(corsys)\n    corpar = stypes.toDoubleVector(corpar)\n    mncor3 = ctypes.c_double(0.0)\n    mxcor3 = ctypes.c_double(0.0)\n    libspice.dskrb2_c(nv, vrtces, np, plates, corsys, corpar, ctypes.byref(mncor3), ctypes.byref(mxcor3))\n    return mncor3.value, mxcor3.value",
    "docstring": "Determine range bounds for a set of triangular plates to\n    be stored in a type 2 DSK segment.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskrb2_c.html\n\n    :param vrtces: Vertices\n    :type vrtces: NxM-Element Array of floats\n    :param plates: Plates\n    :type plates: NxM-Element Array of ints\n    :param corsys: DSK coordinate system code\n    :type corsys: int\n    :param corpar: DSK coordinate system parameters\n    :type corpar: N-Element Array of floats\n    :return: Lower and Upper bound on range of third coordinate\n    :rtype: tuple"
  },
  {
    "code": "def check_install_conflicts(to_install):\n    package_set, _ = create_package_set_from_installed()\n    would_be_installed = _simulate_installation_of(to_install, package_set)\n    whitelist = _create_whitelist(would_be_installed, package_set)\n    return (\n        package_set,\n        check_package_set(\n            package_set, should_ignore=lambda name: name not in whitelist\n        )\n    )",
    "docstring": "For checking if the dependency graph would be consistent after \\\n    installing given requirements"
  },
  {
    "code": "def constrain_norms(self, srcNames, cov_scale=1.0):\n        for name in srcNames:\n            par = self.like.normPar(name)\n            err = par.error()\n            val = par.getValue()\n            if par.error() == 0.0 or not par.isFree():\n                continue\n            self.add_gauss_prior(name, par.getName(),\n                                 val, err * cov_scale)",
    "docstring": "Constrain the normalizations of one or more sources by\n        adding gaussian priors with sigma equal to the parameter\n        error times a scaling factor."
  },
  {
    "code": "def RecursiveMultiListChildren(self, urns, limit=None, age=NEWEST_TIME):\n    checked_urns = set()\n    urns_to_check = urns\n    while True:\n      found_children = []\n      for subject, values in self.MultiListChildren(\n          urns_to_check, limit=limit, age=age):\n        found_children.extend(values)\n        yield subject, values\n      checked_urns.update(urns_to_check)\n      urns_to_check = set(found_children) - checked_urns\n      if not urns_to_check:\n        break",
    "docstring": "Recursively lists bunch of directories.\n\n    Args:\n      urns: List of urns to list children.\n      limit: Max number of children to list (NOTE: this is per urn).\n      age: The age of the items to retrieve. Should be one of ALL_TIMES,\n        NEWEST_TIME or a range.\n\n    Yields:\n       (subject<->children urns) tuples. RecursiveMultiListChildren will fetch\n       children lists for initial set of urns and then will fetch children's\n       children, etc.\n\n       For example, for the following objects structure:\n       a->\n          b -> c\n            -> d\n\n       RecursiveMultiListChildren(['a']) will return:\n       [('a', ['b']), ('b', ['c', 'd'])]"
  },
  {
    "code": "def parse(self, data):\n        self.binding_var_count = 0\n        self.segment_count = 0\n        segments = self.parser.parse(data)\n        path_wildcard = False\n        for segment in segments:\n            if segment.kind == _TERMINAL and segment.literal == '**':\n                if path_wildcard:\n                    raise ValidationException(\n                        'validation error: path template cannot contain more '\n                        'than one path wildcard')\n                path_wildcard = True\n        return segments",
    "docstring": "Returns a list of path template segments parsed from data.\n\n        Args:\n            data: A path template string.\n        Returns:\n            A list of _Segment."
  },
  {
    "code": "def get_next_index(self, matrix, manipulation, indices_left):\n        f = manipulation[0]\n        indices = list(indices_left.intersection(manipulation[2]))\n        sums = np.sum(matrix[indices], axis=1)\n        if f < 1:\n            next_index = indices[sums.argmax(axis=0)]\n        else:\n            next_index = indices[sums.argmin(axis=0)]\n        return next_index",
    "docstring": "Returns an index that should have the most negative effect on the\n        matrix sum"
  },
  {
    "code": "def run_deploy_website(restart_apache=False, restart_uwsgi=False,\n                       restart_nginx=False):\n    run_git_pull()\n    run_pip_install()\n    run_rsync_project()\n    run_syncdb()\n    run_collectstatic()\n    if getattr(settings, 'MAKEMESSAGES_ON_DEPLOYMENT', False):\n        run_makemessages()\n    if getattr(settings, 'COMPILEMESSAGES_ON_DEPLOYMENT', False):\n        run_compilemessages()\n    if restart_apache:\n        run_restart_apache()\n    if restart_uwsgi:\n        run_restart_uwsgi()\n    if restart_nginx:\n        run_restart_nginx()\n    else:\n        run_touch_wsgi()",
    "docstring": "Executes all tasks necessary to deploy the website on the given server.\n\n    Usage::\n\n        fab <server> run_deploy_website"
  },
  {
    "code": "def get_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str:\n        return sys.executable",
    "docstring": "Returns the path to the current Python executable."
  },
  {
    "code": "def _create_merge_filelist(bam_files, base_file, config):\n    bam_file_list = \"%s.list\" % os.path.splitext(base_file)[0]\n    samtools = config_utils.get_program(\"samtools\", config)\n    with open(bam_file_list, \"w\") as out_handle:\n        for f in sorted(bam_files):\n            do.run('{} quickcheck -v {}'.format(samtools, f),\n                   \"Ensure integrity of input merge BAM files\")\n            out_handle.write(\"%s\\n\" % f)\n    return bam_file_list",
    "docstring": "Create list of input files for merge, ensuring all files are valid."
  },
  {
    "code": "def put_and_track(self, url, payload, refresh_rate_sec=1):\n        if not url.startswith('/v1/procedures'):\n            raise Exception(\"The only supported route is /v1/procedures\")\n        parts = url.split('/')\n        len_parts = len(parts)\n        if len_parts not in [4, 6]:\n            raise Exception(\n                \"You must either PUT a procedure or a procedure run\")\n        proc_id = parts[3]\n        run_id = None\n        if len_parts == 4:\n                if 'params' not in payload:\n                    payload['params'] = {}\n                payload['params']['runOnCreation'] = True\n        elif len_parts == 6:\n            run_id = parts[-1]\n        pm = ProgressMonitor(self, refresh_rate_sec, proc_id, run_id,\n                             self.notebook)\n        t = threading.Thread(target=pm.monitor_progress)\n        t.start()\n        try:\n            return self.put(url, payload)\n        except Exception as e:\n            print(e)\n        finally:\n            pass\n            pm.event.set()\n            t.join()",
    "docstring": "Put and track progress, displaying progress bars.\n\n        May display the wrong progress if 2 things post/put on the same\n        procedure name at the same time."
  },
  {
    "code": "def gpio_get(self, pins=None):\n        if pins is None:\n            pins = range(4)\n        size = len(pins)\n        indices = (ctypes.c_uint8 * size)(*pins)\n        statuses = (ctypes.c_uint8 * size)()\n        result = self._dll.JLINK_EMU_GPIO_GetState(ctypes.byref(indices),\n                                                   ctypes.byref(statuses),\n                                                   size)\n        if result < 0:\n            raise errors.JLinkException(result)\n        return list(statuses)",
    "docstring": "Returns a list of states for the given pins.\n\n        Defaults to the first four pins if an argument is not given.\n\n        Args:\n          self (JLink): the ``JLink`` instance\n          pins (list): indices of the GPIO pins whose states are requested\n\n        Returns:\n          A list of states.\n\n        Raises:\n          JLinkException: on error."
  },
  {
    "code": "def create_app(path=None, user_content=False, context=None, username=None,\n               password=None, render_offline=False, render_wide=False,\n               render_inline=False, api_url=None, title=None, text=None,\n               autorefresh=None, quiet=None, grip_class=None):\n    if grip_class is None:\n        grip_class = Grip\n    if text is not None:\n        display_filename = DirectoryReader(path, True).filename_for(None)\n        source = TextReader(text, display_filename)\n    elif path == '-':\n        source = StdinReader()\n    else:\n        source = DirectoryReader(path)\n    if render_offline:\n        renderer = OfflineRenderer(user_content, context)\n    elif user_content or context or api_url:\n        renderer = GitHubRenderer(user_content, context, api_url)\n    else:\n        renderer = None\n    auth = (username, password) if username or password else None\n    return grip_class(source, auth, renderer, None, render_wide,\n                      render_inline, title, autorefresh, quiet)",
    "docstring": "Creates a Grip application with the specified overrides."
  },
  {
    "code": "def list_targets(Rule,\n             region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        targets = conn.list_targets_by_rule(Rule=Rule)\n        ret = []\n        if targets and 'Targets' in targets:\n            keys = ('Id', 'Arn', 'Input',\n                    'InputPath')\n            for target in targets.get('Targets'):\n                ret.append(dict([(k, target.get(k)) for k in keys if k in target]))\n            return {'targets': ret}\n        else:\n            return {'targets': None}\n    except ClientError as e:\n        err = __utils__['boto3.get_error'](e)\n        if e.response.get('Error', {}).get('Code') == 'RuleNotFoundException':\n            return {'error': \"Rule {0} not found\".format(Rule)}\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Given a rule name list the targets of that rule.\n\n    Returns a dictionary of interesting properties.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_cloudwatch_event.list_targets myrule"
  },
  {
    "code": "def _mean_of_runs(stats, key='runs'):\n    num_runs = len(stats[key])\n    first = stats[key][0]\n    mean = {}\n    for stat_key in first:\n        if isinstance(first[stat_key], numbers.Number):\n            mean[stat_key] = sum(run[stat_key]\n                                 for run in stats[key]) / float(num_runs)\n    return mean",
    "docstring": "Obtain the mean of stats.\n\n    Args:\n        stats: dict; A set of stats, structured as above.\n        key: str; Optional key to determine where list of runs is found in stats"
  },
  {
    "code": "def zoom_reset(self):\n        self._zoom_factor = self._zoom_factors[0] if self._zoom_default == 0 else self._zoom_default\n        if self._zoom_factors.index(self._zoom_factor) == 0:\n            self._button_zoom_out.config(state=tk.DISABLED)\n            self._button_zoom_in.config(state=tk.NORMAL)\n        elif self._zoom_factors.index(self.zoom_factor) + 1 == len(self._zoom_factors):\n            self._button_zoom_out.config(state=tk.NORMAL)\n            self._button_zoom_in.config(state=tk.DISABLED)\n        self.draw_timeline()",
    "docstring": "Reset the zoom factor to default and redraw TimeLine"
  },
  {
    "code": "def get_max_bitlen(self):\n        payload_max_bitlen = self.max_size * self.value_type.get_max_bitlen()\n        return {\n            self.MODE_DYNAMIC: payload_max_bitlen + self.max_size.bit_length(),\n            self.MODE_STATIC: payload_max_bitlen\n        }[self.mode]",
    "docstring": "Returns total maximum bit length of the array, including length field if applicable."
  },
  {
    "code": "def _zom_name(lexer):\n    tok = next(lexer)\n    if isinstance(tok, DOT):\n        first = _expect_token(lexer, {NameToken}).value\n        rest = _zom_name(lexer)\n        return (first, ) + rest\n    else:\n        lexer.unpop_token(tok)\n        return tuple()",
    "docstring": "Return zero or more names."
  },
  {
    "code": "def find(self, name, namespace=None):\n        if \".\" in name:\n            namespace, name = name.rsplit(\".\", 1)\n        caret = self.raw\n        if namespace:\n            for term in namespace.split('.'):\n                if term not in caret:\n                    caret[term] = Bunch()\n                caret = caret[term]\n        return caret[name]",
    "docstring": "Find plugin object\n\n        Parameters\n        ----------\n        name : string\n            A name of the object entry or full namespace\n        namespace : string, optional\n            A period separated namespace. E.g. `foo.bar.hogehoge`\n\n        Returns\n        -------\n        instance\n            An instance found\n\n        Raises\n        ------\n        KeyError\n            If the named instance have not registered\n\n        Examples\n        --------\n        >>> registry = Registry()\n        >>> registry.register('hello', 'goodbye')\n        >>> registry.register('foo', 'bar', 'hoge.hoge.hoge')\n        >>> registry.register('foobar', 'foobar', 'hoge.hoge')\n        >>> registry.find('hello') == 'goodbye'\n        True\n        >>> registry.find('foo', 'hoge.hoge.hoge') == 'bar'\n        True\n        >>> registry.find('hoge.hoge.foobar') == 'foobar'\n        True"
  },
  {
    "code": "def scalar(name, data, step=None, description=None):\n  summary_metadata = metadata.create_summary_metadata(\n      display_name=None, description=description)\n  summary_scope = (\n      getattr(tf.summary.experimental, 'summary_scope', None) or\n      tf.summary.summary_scope)\n  with summary_scope(\n      name, 'scalar_summary', values=[data, step]) as (tag, _):\n    tf.debugging.assert_scalar(data)\n    return tf.summary.write(tag=tag,\n                            tensor=tf.cast(data, tf.float32),\n                            step=step,\n                            metadata=summary_metadata)",
    "docstring": "Write a scalar summary.\n\n  Arguments:\n    name: A name for this summary. The summary tag used for TensorBoard will\n      be this name prefixed by any active name scopes.\n    data: A real numeric scalar value, convertible to a `float32` Tensor.\n    step: Explicit `int64`-castable monotonic step value for this summary. If\n      omitted, this defaults to `tf.summary.experimental.get_step()`, which must\n      not be None.\n    description: Optional long-form description for this summary, as a\n      constant `str`. Markdown is supported. Defaults to empty.\n\n  Returns:\n    True on success, or false if no summary was written because no default\n    summary writer was available.\n\n  Raises:\n    ValueError: if a default writer exists, but no step was provided and\n      `tf.summary.experimental.get_step()` is None."
  },
  {
    "code": "def get_all_unresolved(self):\n        assert self.final, 'Call build() before using the graph.'\n        out = set()\n        for v in self.broken_deps.values():\n            out |= v\n        return out",
    "docstring": "Returns a set of all unresolved imports."
  },
  {
    "code": "def _isdst(dt):\n    if type(dt) == datetime.date:\n        dt = datetime.datetime.combine(dt, datetime.datetime.min.time())\n    dtc = dt.replace(year=datetime.datetime.now().year)\n    if time.localtime(dtc.timestamp()).tm_isdst == 1:\n        return True\n    return False",
    "docstring": "Check if date is in dst."
  },
  {
    "code": "def _get_line_styles(marker_str):\n    def _extract_marker_value(marker_str, code_dict):\n        val = None\n        for code in code_dict:\n            if code in marker_str:\n                val = code_dict[code]\n                break\n        return val\n    return [_extract_marker_value(marker_str, code_dict) for\n            code_dict in [LINE_STYLE_CODES, COLOR_CODES, MARKER_CODES]]",
    "docstring": "Return line style, color and marker type from specified marker string.\n\n    For example, if ``marker_str`` is 'g-o' then the method returns\n    ``('solid', 'green', 'circle')``."
  },
  {
    "code": "def to_package(self, repo_url):\n        return Package(name=self.name, url=repo_url + self.name)",
    "docstring": "Return the package representation of this repo."
  },
  {
    "code": "def limits(self,variable):\n        (vmin,vmax), = self.SELECT('min(%(variable)s), max(%(variable)s)' % vars())\n        return vmin,vmax",
    "docstring": "Return minimum and maximum of variable across all rows of data."
  },
  {
    "code": "def fetch_events(cursor, config, account_name):\n    query = config['indexer'].get('query',\n        'select * from events where user_agent glob \\'*CloudCustodian*\\'')\n    for event in cursor.execute(query):\n        event['account'] = account_name\n        event['_index'] = config['indexer']['idx_name']\n        event['_type'] = config['indexer'].get('idx_type', 'traildb')\n        yield event",
    "docstring": "Generator that returns the events"
  },
  {
    "code": "def calcMzFromMass(mass, charge):\n    mz = (mass + (maspy.constants.atomicMassProton * charge)) / charge\n    return mz",
    "docstring": "Calculate the mz value of a peptide from its mass and charge.\n\n    :param mass: float, exact non protonated mass\n    :param charge: int, charge state\n\n    :returns: mass to charge ratio of the specified charge state"
  },
  {
    "code": "def collect(self):\n        for app_name, tools_path in get_apps_tools().items():\n            self.stdout.write(\"Copying files from '{}'.\".format(tools_path))\n            app_name = app_name.replace('.', '_')\n            app_destination_path = os.path.join(self.destination_path, app_name)\n            if not os.path.isdir(app_destination_path):\n                os.mkdir(app_destination_path)\n            for root, dirs, files in os.walk(tools_path):\n                for dir_name in dirs:\n                    dir_source_path = os.path.join(root, dir_name)\n                    dir_destination_path = self.change_path_prefix(\n                        dir_source_path, tools_path, self.destination_path, app_name\n                    )\n                    if not os.path.isdir(dir_destination_path):\n                        os.mkdir(dir_destination_path)\n                for file_name in files:\n                    file_source_path = os.path.join(root, file_name)\n                    file_destination_path = self.change_path_prefix(\n                        file_source_path, tools_path, self.destination_path, app_name\n                    )\n                    shutil.copy2(file_source_path, file_destination_path)",
    "docstring": "Get tools' locations and copy them to a single location."
  },
  {
    "code": "def _fetch(self, searchtype, fields, **kwargs):\n        fields['vintage'] = self.vintage\n        fields['benchmark'] = self.benchmark\n        fields['format'] = 'json'\n        if 'layers' in kwargs:\n            fields['layers'] = kwargs['layers']\n        returntype = kwargs.get('returntype', 'geographies')\n        url = self._geturl(searchtype, returntype)\n        try:\n            with requests.get(url, params=fields, timeout=kwargs.get('timeout')) as r:\n                content = r.json()\n                if \"addressMatches\" in content.get('result', {}):\n                    return AddressResult(content)\n                if \"geographies\" in content.get('result', {}):\n                    return GeographyResult(content)\n                raise ValueError()\n        except (ValueError, KeyError):\n            raise ValueError(\"Unable to parse response from Census\")\n        except RequestException as e:\n            raise e",
    "docstring": "Fetch a response from the Geocoding API."
  },
  {
    "code": "def diff(xi, yi, order=1) -> np.ndarray:\n    yi = np.array(yi).copy()\n    flip = False\n    if xi[-1] < xi[0]:\n        xi = np.flipud(xi.copy())\n        yi = np.flipud(yi)\n        flip = True\n    midpoints = (xi[1:] + xi[:-1]) / 2\n    for _ in range(order):\n        d = np.diff(yi)\n        d /= np.diff(xi)\n        yi = np.interp(xi, midpoints, d)\n    if flip:\n        yi = np.flipud(yi)\n    return yi",
    "docstring": "Take the numerical derivative of a 1D array.\n\n    Output is mapped onto the original coordinates  using linear interpolation.\n    Expects monotonic xi values.\n\n    Parameters\n    ----------\n    xi : 1D array-like\n        Coordinates.\n    yi : 1D array-like\n        Values.\n    order : positive integer (optional)\n        Order of differentiation.\n\n    Returns\n    -------\n    1D numpy array\n        Numerical derivative. Has the same shape as the input arrays."
  },
  {
    "code": "async def ack(self, msg):\n        ack_proto = protocol.Ack()\n        ack_proto.subject = msg.proto.subject\n        ack_proto.sequence = msg.proto.sequence\n        await self._nc.publish(msg.sub.ack_inbox, ack_proto.SerializeToString())",
    "docstring": "Used to manually acks a message.\n\n        :param msg: Message which is pending to be acked by client."
  },
  {
    "code": "def generate_signed_url(\n        self,\n        expiration=None,\n        api_access_endpoint=_API_ACCESS_ENDPOINT,\n        method=\"GET\",\n        headers=None,\n        query_parameters=None,\n        client=None,\n        credentials=None,\n        version=None,\n    ):\n        if version is None:\n            version = \"v2\"\n        elif version not in (\"v2\", \"v4\"):\n            raise ValueError(\"'version' must be either 'v2' or 'v4'\")\n        resource = \"/{bucket_name}\".format(bucket_name=self.name)\n        if credentials is None:\n            client = self._require_client(client)\n            credentials = client._credentials\n        if version == \"v2\":\n            helper = generate_signed_url_v2\n        else:\n            helper = generate_signed_url_v4\n        return helper(\n            credentials,\n            resource=resource,\n            expiration=expiration,\n            api_access_endpoint=api_access_endpoint,\n            method=method.upper(),\n            headers=headers,\n            query_parameters=query_parameters,\n        )",
    "docstring": "Generates a signed URL for this bucket.\n\n        .. note::\n\n            If you are on Google Compute Engine, you can't generate a signed\n            URL using GCE service account. Follow `Issue 50`_ for updates on\n            this. If you'd like to be able to generate a signed URL from GCE,\n            you can use a standard service account from a JSON file rather\n            than a GCE service account.\n\n        .. _Issue 50: https://github.com/GoogleCloudPlatform/\\\n                      google-auth-library-python/issues/50\n\n        If you have a bucket that you want to allow access to for a set\n        amount of time, you can use this method to generate a URL that\n        is only valid within a certain time period.\n\n        This is particularly useful if you don't want publicly\n        accessible buckets, but don't want to require users to explicitly\n        log in.\n\n        :type expiration: Union[Integer, datetime.datetime, datetime.timedelta]\n        :param expiration: Point in time when the signed URL should expire.\n\n        :type api_access_endpoint: str\n        :param api_access_endpoint: Optional URI base.\n\n        :type method: str\n        :param method: The HTTP verb that will be used when requesting the URL.\n\n        :type headers: dict\n        :param headers:\n            (Optional) Additional HTTP headers to be included as part of the\n            signed URLs.  See:\n            https://cloud.google.com/storage/docs/xml-api/reference-headers\n            Requests using the signed URL *must* pass the specified header\n            (name and value) with each request for the URL.\n\n        :type query_parameters: dict\n        :param query_parameters:\n            (Optional) Additional query paramtersto be included as part of the\n            signed URLs.  See:\n            https://cloud.google.com/storage/docs/xml-api/reference-headers#query\n\n        :type client: :class:`~google.cloud.storage.client.Client` or\n                      ``NoneType``\n        :param client: (Optional) The client to use.  If not passed, falls back\n                       to the ``client`` stored on the blob's bucket.\n\n\n        :type credentials: :class:`oauth2client.client.OAuth2Credentials` or\n                           :class:`NoneType`\n        :param credentials: (Optional) The OAuth2 credentials to use to sign\n                            the URL. Defaults to the credentials stored on the\n                            client used.\n\n        :type version: str\n        :param version: (Optional) The version of signed credential to create.\n                        Must be one of 'v2' | 'v4'.\n\n        :raises: :exc:`ValueError` when version is invalid.\n        :raises: :exc:`TypeError` when expiration is not a valid type.\n        :raises: :exc:`AttributeError` if credentials is not an instance\n                of :class:`google.auth.credentials.Signing`.\n\n        :rtype: str\n        :returns: A signed URL you can use to access the resource\n                  until expiration."
  },
  {
    "code": "def nice_identifier():\n    'do not use uuid.uuid4, because it can block'\n    big = reduce(mul, struct.unpack('<LLLL', os.urandom(16)), 1)\n    big = big % 2**128\n    return uuid.UUID(int=big).hex",
    "docstring": "do not use uuid.uuid4, because it can block"
  },
  {
    "code": "def _send_chunk(self, index, chunk):\n        self._pending_chunks += 1\n        self.outbox.put((index, chunk))",
    "docstring": "Send the current chunk to the workers for processing.\n        Called when the _partial_chunk is complete.\n\n        Blocks when the outbox is full."
  },
  {
    "code": "def specialspaceless(parser, token):\n    nodelist = parser.parse(('endspecialspaceless',))\n    parser.delete_first_token()\n    return SpecialSpacelessNode(nodelist)",
    "docstring": "Removes whitespace between HTML tags, and introduces a whitespace\n    after buttons an inputs, necessary for Bootstrap to place them\n    correctly in the layout."
  },
  {
    "code": "def dumpJson(obj, **kwargs):\n    def handleDateAndBinaryForJs(x):\n        if six.PY3 and isinstance(x, six.binary_type):\n            x = x.decode()\n        if isinstance(x, datetime.datetime) or isinstance(x, datetime.date):\n            return stringDate(x)\n        else:\n            return x\n    d = json.dumps(obj, separators=(',', ':'), default=handleDateAndBinaryForJs, **kwargs)\n    assert '\\n' not in d\n    return d",
    "docstring": "Match JS's JSON.stringify.  When using the default seperators,\n    base64 encoding JSON results in \\n sequences in the output.  Hawk\n    barfs in your face if you have that in the text"
  },
  {
    "code": "def _lookup_generic_scalar(self,\n                               obj,\n                               as_of_date,\n                               country_code,\n                               matches,\n                               missing):\n        result = self._lookup_generic_scalar_helper(\n            obj, as_of_date, country_code,\n        )\n        if result is not None:\n            matches.append(result)\n        else:\n            missing.append(obj)",
    "docstring": "Convert asset_convertible to an asset.\n\n        On success, append to matches.\n        On failure, append to missing."
  },
  {
    "code": "def package_in_memory(cls, workflow_name, workflow_files):\n        s = StringIO()\n        p = cls(s, workflow_name, meta_data=[])\n        p.add_bpmn_files_by_glob(workflow_files)\n        p.create_package()\n        return s.getvalue()",
    "docstring": "Generates wf packages from workflow diagrams.\n\n        Args:\n            workflow_name: Name of wf\n            workflow_files:  Diagram  file.\n\n        Returns:\n            Workflow package (file like) object"
  },
  {
    "code": "def download_files_if_not_in_manifest(files_iterator, output_path):\n    local_manifest = read_local_manifest(output_path)\n    with open(get_local_manifest_path(output_path), 'a') as manifest_fh:\n        for (file_name, width) in files_iterator:\n            if is_file_in_manifest(file_name, width, local_manifest):\n                logging.info('Skipping file %s', file_name)\n                continue\n            try:\n                download_file(file_name, output_path, width=width)\n                write_file_to_manifest(file_name, width, manifest_fh)\n            except DownloadException, e:\n                logging.error(\"Could not download %s: %s\", file_name, e.message)",
    "docstring": "Download the given files to the given path, unless in manifest."
  },
  {
    "code": "def _load_words(self):\n        with open(self._words_file, 'r') as f:\n            self._censor_list = [line.strip() for line in f.readlines()]",
    "docstring": "Loads the list of profane words from file."
  },
  {
    "code": "def PenForNode( self, node, depth=0 ):\n        if node == self.selectedNode:\n            return self.SELECTED_PEN\n        return self.DEFAULT_PEN",
    "docstring": "Determine the pen to use to display the given node"
  },
  {
    "code": "def cli(ctx, project_dir):\n    exit_code = SCons(project_dir).sim()\n    ctx.exit(exit_code)",
    "docstring": "Launch the verilog simulation."
  },
  {
    "code": "def search(self, keyword, children=None, arg=None):\n        if children is None:\n            children = self.substmts\n        return [ ch for ch in children\n                 if (ch.keyword == keyword and\n                     (arg is None or ch.arg == arg))]",
    "docstring": "Return list of receiver's substmts with `keyword`."
  },
  {
    "code": "def import_object(path):\n    spl = path.split('.')\n    if len(spl) == 1:\n        return importlib.import_module(path)\n    cls = spl[-1]\n    mods = '.'.join(spl[:-1])\n    mm = importlib.import_module(mods)\n    try:\n        obj = getattr(mm, cls)\n        return obj\n    except AttributeError:\n        pass\n    rr = importlib.import_module(path)\n    return rr",
    "docstring": "Import an object given its fully qualified name."
  },
  {
    "code": "def create_floatingip(floating_network, port=None, profile=None):\n    conn = _auth(profile)\n    return conn.create_floatingip(floating_network, port)",
    "docstring": "Creates a new floatingIP\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' neutron.create_floatingip network-name port-name\n\n    :param floating_network: Network name or ID to allocate floatingIP from\n    :param port: Of the port to be associated with the floatingIP (Optional)\n    :param profile: Profile to build on (Optional)\n    :return: Created floatingIP information"
  },
  {
    "code": "def _get_hba_type(hba_type):\n    if hba_type == \"parallel\":\n        return vim.host.ParallelScsiHba\n    elif hba_type == \"block\":\n        return vim.host.BlockHba\n    elif hba_type == \"iscsi\":\n        return vim.host.InternetScsiHba\n    elif hba_type == \"fibre\":\n        return vim.host.FibreChannelHba\n    raise ValueError('Unknown Host Bus Adapter Type')",
    "docstring": "Convert a string representation of a HostHostBusAdapter into an\n    object reference."
  },
  {
    "code": "def _list_to_seq(lst):\n    ml = autoclass('scala.collection.mutable.MutableList')()\n    for element in lst:\n        ml.appendElem(element)\n    return ml",
    "docstring": "Return a scala.collection.Seq from a Python list."
  },
  {
    "code": "def dispatch(self):\n        'Perform dispatch, using request embedded within flask global state'\n        import flask\n        body = flask.request.get_json()\n        return self. dispatch_with_args(body, argMap=dict())",
    "docstring": "Perform dispatch, using request embedded within flask global state"
  },
  {
    "code": "def generate_take(out_f, steps, line_prefix):\n    out_f.write(\n        '{0}constexpr inline int take(int n_)\\n'\n        '{0}{{\\n'\n        '{0}  return {1} 0 {2};\\n'\n        '{0}}}\\n'\n        '\\n'.format(\n            line_prefix,\n            ''.join('n_ >= {0} ? {0} : ('.format(s) for s in steps),\n            ')' * len(steps)\n        )\n    )",
    "docstring": "Generate the take function"
  },
  {
    "code": "def get_eager_datasource(cls, session, datasource_type, datasource_id):\n        datasource_class = ConnectorRegistry.sources[datasource_type]\n        return (\n            session.query(datasource_class)\n            .options(\n                subqueryload(datasource_class.columns),\n                subqueryload(datasource_class.metrics),\n            )\n            .filter_by(id=datasource_id)\n            .one()\n        )",
    "docstring": "Returns datasource with columns and metrics."
  },
  {
    "code": "def teardown_global_logging():\n    global global_logging_started\n    if not global_logging_started:\n        return\n    stdout_logger = logging.getLogger(__name__ + '.stdout')\n    stderr_logger = logging.getLogger(__name__ + '.stderr')\n    if sys.stdout is stdout_logger:\n        sys.stdout = sys.stdout.stream\n    if sys.stderr is stderr_logger:\n        sys.stderr = sys.stderr.stream\n    exc_type, exc_value, exc_traceback = sys.exc_info()\n    if exc_type is not None:\n        sys.excepthook(exc_type, exc_value, exc_traceback)\n    del exc_type\n    del exc_value\n    del exc_traceback\n    if not PY3K:\n        sys.exc_clear()\n    del sys.excepthook\n    logging.captureWarnings(False)\n    rawinput = 'input' if PY3K else 'raw_input'\n    if hasattr(builtins, '_original_raw_input'):\n        setattr(builtins, rawinput, builtins._original_raw_input)\n        del builtins._original_raw_input\n    global_logging_started = False",
    "docstring": "Disable global logging of stdio, warnings, and exceptions."
  },
  {
    "code": "def from_wms(cls, filename, vector, resolution, destination_file=None):\n        doc = wms_vrt(filename,\n                      bounds=vector,\n                      resolution=resolution).tostring()\n        filename = cls._save_to_destination_file(doc, destination_file)\n        return GeoRaster2.open(filename)",
    "docstring": "Create georaster from the web service definition file."
  },
  {
    "code": "def find_package(name, installed, package=False):\n    if package:\n        name = name.lower()\n        tests = (\n            lambda x: x.user and name == x.name.lower(),\n            lambda x: x.local and name == x.name.lower(),\n            lambda x: name == x.name.lower(),\n        )\n    else:\n        tests = (\n            lambda x: x.user and name in x.import_names,\n            lambda x: x.local and name in x.import_names,\n            lambda x: name in x.import_names,\n        )\n    for t in tests:\n        try:\n            found = list(filter(t, installed))\n            if found and not found[0].is_scan:\n                return found[0]\n        except StopIteration:\n            pass\n    return None",
    "docstring": "Finds a package in the installed list.\n\n    If `package` is true, match package names, otherwise, match import paths."
  },
  {
    "code": "def from_file(cls, filename):\n        with zopen(filename) as f:\n            return cls.from_string(f.read())",
    "docstring": "Read an Fiesta input from a file. Currently tested to work with\n        files generated from this class itself.\n\n        Args:\n            filename: Filename to parse.\n\n        Returns:\n            FiestaInput object"
  },
  {
    "code": "def deserialize_instance(model, data={}):\n    \"Translate raw data into a model instance.\"\n    ret = model()\n    for k, v in data.items():\n        if v is not None:\n            try:\n                f = model._meta.get_field(k)\n                if isinstance(f, DateTimeField):\n                    v = dateparse.parse_datetime(v)\n                elif isinstance(f, TimeField):\n                    v = dateparse.parse_time(v)\n                elif isinstance(f, DateField):\n                    v = dateparse.parse_date(v)\n            except FieldDoesNotExist:\n                pass\n        setattr(ret, k, v)\n    return ret",
    "docstring": "Translate raw data into a model instance."
  },
  {
    "code": "def _quantityToReal(self, quantity):\n        if not quantity:\n            return 1.0\n        try:\n            return float(quantity.replace(',', '.'))\n        except ValueError:\n            pass\n        try:\n            return float(self.ptc.numbers[quantity])\n        except KeyError:\n            pass\n        return 0.0",
    "docstring": "Convert a quantity, either spelled-out or numeric, to a float\n\n        @type    quantity: string\n        @param   quantity: quantity to parse to float\n        @rtype:  int\n        @return: the quantity as an float, defaulting to 0.0"
  },
  {
    "code": "def tablespace_create(name, location, options=None, owner=None, user=None,\n                      host=None, port=None, maintenance_db=None, password=None,\n                      runas=None):\n    owner_query = ''\n    options_query = ''\n    if owner:\n        owner_query = 'OWNER \"{0}\"'.format(owner)\n    if options:\n        optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)]\n        options_query = 'WITH ( {0} )'.format(', '.join(optionstext))\n    query = 'CREATE TABLESPACE \"{0}\" {1} LOCATION \\'{2}\\' {3}'.format(name,\n                                                                owner_query,\n                                                                location,\n                                                                options_query)\n    ret = _psql_prepare_and_run(['-c', query],\n                                user=user, host=host, port=port,\n                                maintenance_db=maintenance_db,\n                                password=password, runas=runas)\n    return ret['retcode'] == 0",
    "docstring": "Adds a tablespace to the Postgres server.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' postgres.tablespace_create tablespacename '/path/datadir'\n\n    .. versionadded:: 2015.8.0"
  },
  {
    "code": "def put_subsegment(self, subsegment):\n        entity = self.get_trace_entity()\n        if not entity:\n            log.warning(\"Active segment or subsegment not found. Discarded %s.\" % subsegment.name)\n            return\n        entity.add_subsegment(subsegment)\n        self._local.entities.append(subsegment)",
    "docstring": "Store the subsegment created by ``xray_recorder`` to the context.\n        If you put a new subsegment while there is already an open subsegment,\n        the new subsegment becomes the child of the existing subsegment."
  },
  {
    "code": "def procedures(self, *a, **kw):\n        fut = self._run_operation(self._impl.procedures, *a, **kw)\n        return fut",
    "docstring": "Executes SQLProcedures and creates a result set of information\n        about the procedures in the data source."
  },
  {
    "code": "def _build_signature(self):\n        sig_contents = \\\n            self.payload + \".\" + \\\n            b64encode(b\"application/xml\").decode(\"ascii\") + \".\" + \\\n            b64encode(b\"base64url\").decode(\"ascii\") + \".\" + \\\n            b64encode(b\"RSA-SHA256\").decode(\"ascii\")\n        sig_hash = SHA256.new(sig_contents.encode(\"ascii\"))\n        cipher = PKCS1_v1_5.new(self.private_key)\n        sig = urlsafe_b64encode(cipher.sign(sig_hash))\n        key_id = urlsafe_b64encode(bytes(self.author_handle, encoding=\"utf-8\"))\n        return sig, key_id",
    "docstring": "Create the signature using the private key."
  },
  {
    "code": "def _nbinom_ztrunc_p(mu, k_agg):\n        p_eq = lambda p, mu, k_agg: (k_agg * p) / (1 - (1 + p)**-k_agg) - mu\n        p = optim.brentq(p_eq, 1e-10, 1e10, args=(mu, k_agg))\n        return p",
    "docstring": "Calculates p parameter for truncated negative binomial\n\n        Function given in Sampford 1955, equation 4\n\n        Note that omega = 1 / 1 + p in Sampford"
  },
  {
    "code": "def load_schema(filename, context=None):\n    table = import_from_uri(filename)\n    field_names = table.field_names\n    assert \"field_name\" in field_names\n    assert \"field_type\" in field_names\n    context = context or {\n        key.replace(\"Field\", \"\").lower(): getattr(rows.fields, key)\n        for key in dir(rows.fields)\n        if \"Field\" in key and key != \"Field\"\n    }\n    return OrderedDict(\n        [\n            (row.field_name, context[row.field_type])\n            for row in table\n        ]\n    )",
    "docstring": "Load schema from file in any of the supported formats\n\n    The table must have at least the fields `field_name` and `field_type`.\n    `context` is a `dict` with field_type as key pointing to field class, like:\n        {\"text\": rows.fields.TextField, \"value\": MyCustomField}"
  },
  {
    "code": "def do_imports(self):\n        self.do_import('worker_class', Worker)\n        self.do_import('queue_model', self.options.worker_class.queue_model)\n        self.do_import('error_model', self.options.worker_class.error_model)\n        self.do_import('callback', self.options.worker_class.callback)",
    "docstring": "Import all importable options"
  },
  {
    "code": "def add_connectionmanager_api(mock):\n    iface = 'org.ofono.ConnectionManager'\n    mock.AddProperties(iface, {\n        'Attached': _parameters.get('Attached', True),\n        'Bearer': _parameters.get('Bearer', 'gprs'),\n        'RoamingAllowed': _parameters.get('RoamingAllowed', False),\n        'Powered': _parameters.get('ConnectionPowered', True),\n    })\n    mock.AddMethods(iface, [\n        ('GetProperties', '', 'a{sv}', 'ret = self.GetAll(\"%s\")' % iface),\n        ('SetProperty', 'sv', '', 'self.Set(\"%(i)s\", args[0], args[1]); '\n         'self.EmitSignal(\"%(i)s\", \"PropertyChanged\", \"sv\", [args[0], args[1]])' % {'i': iface}),\n        ('AddContext', 's', 'o', 'ret = \"/\"'),\n        ('RemoveContext', 'o', '', ''),\n        ('DeactivateAll', '', '', ''),\n        ('GetContexts', '', 'a(oa{sv})', 'ret = dbus.Array([])'),\n    ])",
    "docstring": "Add org.ofono.ConnectionManager API to a mock"
  },
  {
    "code": "def to_xarray(self) -> \"xarray.Dataset\":\n        import xarray as xr\n        data_vars = {\n            \"frequencies\": xr.DataArray(self.frequencies, dims=\"bin\"),\n            \"errors2\": xr.DataArray(self.errors2, dims=\"bin\"),\n            \"bins\": xr.DataArray(self.bins, dims=(\"bin\", \"x01\"))\n        }\n        coords = {}\n        attrs = {\n            \"underflow\": self.underflow,\n            \"overflow\": self.overflow,\n            \"inner_missed\": self.inner_missed,\n            \"keep_missed\": self.keep_missed\n        }\n        attrs.update(self._meta_data)\n        return xr.Dataset(data_vars, coords, attrs)",
    "docstring": "Convert to xarray.Dataset"
  },
  {
    "code": "def knit(self, input_file, opts_chunk='eval=FALSE'):\n        tmp_in = tempfile.NamedTemporaryFile(mode='w+')\n        tmp_out = tempfile.NamedTemporaryFile(mode='w+')\n        tmp_in.file.write(input_file.read())\n        tmp_in.file.flush()\n        tmp_in.file.seek(0)\n        self._knit(tmp_in.name, tmp_out.name, opts_chunk)\n        tmp_out.file.flush()\n        return tmp_out",
    "docstring": "Use Knitr to convert the r-markdown input_file\n        into markdown, returning a file object."
  },
  {
    "code": "def download_files(file_list):\n    for _, source_data_file in file_list:\n        sql_gz_name = source_data_file['name'].split('/')[-1]\n        msg = 'Downloading: %s' % (sql_gz_name)\n        log.debug(msg)\n        new_data = objectstore.get_object(\n            handelsregister_conn, source_data_file, 'handelsregister')\n        with open('data/{}'.format(sql_gz_name), 'wb') as outputzip:\n            outputzip.write(new_data)",
    "docstring": "Download the latest data."
  },
  {
    "code": "def stoch2array(self):\n        a = np.empty(self.dim)\n        for stochastic in self.stochastics:\n            a[self._slices[stochastic]] = stochastic.value\n        return a",
    "docstring": "Return the stochastic objects as an array."
  },
  {
    "code": "def extract(features, groups,\n            weight_method=default_weight_method,\n            num_bins=default_num_bins,\n            edge_range=default_edge_range,\n            trim_outliers=default_trim_behaviour,\n            trim_percentile=default_trim_percentile,\n            use_original_distribution=False,\n            relative_to_all=False,\n            asymmetric=False,\n            return_networkx_graph=default_return_networkx_graph,\n            out_weights_path=default_out_weights_path):\n    features, groups, num_bins, edge_range, group_ids, num_groups, num_links = check_params(\n            features, groups, num_bins, edge_range, trim_outliers, trim_percentile)\n    weight_func, use_orig_distr, non_symmetric = check_weight_method(weight_method,\n                                                                     use_original_distribution, asymmetric)\n    edges = compute_bin_edges(features, num_bins, edge_range,\n                              trim_outliers, trim_percentile, use_orig_distr)\n    if relative_to_all:\n        result = non_pairwise.relative_to_all(features, groups, edges, weight_func,\n                                              use_orig_distr, group_ids, num_groups,\n                                              return_networkx_graph, out_weights_path)\n    else:\n        result = pairwise_extract(features, groups, edges, weight_func, use_orig_distr,\n                                  group_ids, num_groups, num_links,\n                                  non_symmetric, return_networkx_graph, out_weights_path)\n    return result",
    "docstring": "Extracts the histogram-distance weighted adjacency matrix.\n\n    Parameters\n    ----------\n    features : ndarray or str\n        1d array of scalar values, either provided directly as a 1d numpy array,\n        or as a path to a file containing these values\n\n    groups : ndarray or str\n        Membership array of same length as `features`, each value specifying which group that particular node belongs to.\n        Input can be either provided directly as a 1d numpy array,or as a path to a file containing these values.\n\n        For example, if you have cortical thickness values for 1000 vertices (`features` is ndarray of length 1000),\n        belonging to 100 patches, the groups array (of length 1000) could  have numbers 1 to 100 (number of unique values)\n        specifying which element belongs to which cortical patch.\n\n        Grouping with numerical values (contiguous from 1 to num_patches) is strongly recommended for simplicity,\n        but this could also be a list of strings of length p, in which case a tuple is returned,\n        identifying which weight belongs to which pair of patches.\n\n    weight_method : string or callable, optional\n        Type of distance (or metric) to compute between the pair of histograms.\n        It can either be a string identifying one of the weights implemented below, or a valid callable.\n\n        If a string, it must be one of the following methods:\n\n        - 'chebyshev'\n        - 'chebyshev_neg'\n        - 'chi_square'\n        - 'correlate'\n        - 'correlate_1'\n        - 'cosine'\n        - 'cosine_1'\n        - 'cosine_2'\n        - 'cosine_alt'\n        - 'euclidean'\n        - 'fidelity_based'\n        - 'histogram_intersection'\n        - 'histogram_intersection_1'\n        - 'jensen_shannon'\n        - 'kullback_leibler'\n        - 'manhattan'\n        - 'minowski'\n        - 'noelle_1'\n        - 'noelle_2'\n        - 'noelle_3'\n        - 'noelle_4'\n        - 'noelle_5'\n        - 'relative_bin_deviation'\n        - 'relative_deviation'\n\n        Note only the following are *metrics*:\n\n        - 'manhattan'\n        - 'minowski'\n        - 'euclidean'\n        - 'noelle_2'\n        - 'noelle_4'\n        - 'noelle_5'\n\n        The following are *semi- or quasi-metrics*:\n\n        - 'kullback_leibler'\n        - 'jensen_shannon'\n        - 'chi_square'\n        - 'chebyshev'\n        - 'cosine_1'\n        - 'chebyshev_neg'\n        - 'correlate_1'\n        - 'histogram_intersection_1'\n        - 'relative_deviation'\n        - 'relative_bin_deviation'\n        - 'noelle_1'\n        - 'noelle_3'\n\n        The following are  classified to be similarity functions:\n\n        - 'histogram_intersection'\n        - 'correlate'\n        - 'cosine'\n        - 'cosine_2'\n        - 'cosine_alt'\n        - 'fidelity_based'\n\n        *Default* choice: 'minowski'.\n\n        The method can also be one of the following identifying metrics that operate on the original data directly -\n         e.g. difference in the medians coming from the distributions of the pair of ROIs.\n\n         - 'diff_medians'\n         - 'diff_means'\n         - 'diff_medians_abs'\n         - 'diff_means_abs'\n\n         Please note this can lead to adjacency matrices that may not be symmetric\n            e.g. difference metric on two scalars is not symmetric).\n            In this case, be sure to use the flag: allow_non_symmetric=True\n\n        If weight_method is a callable, it must two accept two arrays as input and return one scalar as output.\n            Example: ``diff_in_skew = lambda x, y: abs(scipy.stats.skew(x)-scipy.stats.skew(y))``\n            NOTE: this method will be applied to histograms (not the original distribution of features from group/ROI).\n            In order to apply this callable directly on the original distribution (without trimming and histogram binning),\n            use ``use_original_distribution=True``.\n\n    num_bins : scalar, optional\n        Number of bins to use when computing histogram within each patch/group.\n\n        Note:\n\n        1) Please ensure same number of bins are used across different subjects\n        2) histogram shape can vary widely with number of bins (esp with fewer bins in the range of 3-20), and hence the features extracted based on them vary also.\n        3) It is recommended to study the impact of this parameter on the final results of the experiment.\n\n        This could also be optimized within an inner cross-validation loop if desired.\n\n    edge_range : tuple or None\n        The range of edges within which to bin the given values.\n        This can be helpful to ensure correspondence across multiple invocations of hiwenet (for different subjects),\n        in terms of range across all bins as well as individual bin edges.\n        Default is to automatically compute from the given values.\n\n        Accepted format:\n\n            - tuple of finite values: (range_min, range_max)\n            - None, triggering automatic calculation (default)\n\n        Notes : when controlling the ``edge_range``, it is not possible trim the tails (e.g. using the parameters\n        ``trim_outliers`` and ``trim_percentile``) for the current set of features using its own range.\n\n    trim_outliers : bool, optional\n        Whether to trim a small percentile of outliers at the edges of feature range,\n        when features are expected to contain extreme outliers (like 0 or eps or Inf).\n        This is important to avoid numerical problems and also to stabilize the weight estimates.\n\n    trim_percentile : float\n        Small value specifying the percentile of outliers to trim.\n        Default: 5 (5%). Must be in open interval (0, 100).\n\n    use_original_distribution : bool, optional\n        When using a user-defined callable, this flag\n        1) allows skipping of pre-processing (trimming outliers) and histogram construction,\n        2) enables the application of arbitrary callable (user-defined) on the original distributions coming from the two groups/ROIs/nodes directly.\n\n        Example: ``diff_in_medians = lambda x, y: abs(np.median(x)-np.median(y))``\n\n        This option is valid only when weight_method is a valid callable,\n            which must take two inputs (possibly of different lengths) and return a single scalar.\n\n    relative_to_all : bool\n        Flag to instruct the computation of a grand histogram (distribution pooled from values in all ROIs),\n        and compute distances (based on distance specified by ``weight_method``) by from each ROI to the grand mean.\n        This would result in only N distances for N ROIs, instead of the usual N*(N-1) pair-wise distances.\n\n    asymmetric : bool\n        Flag to identify resulting adjacency matrix is expected to be non-symmetric.\n        Note: this results in twice the computation time!\n        Default: False , for histogram metrics implemented here are symmetric.\n\n    return_networkx_graph : bool, optional\n        Specifies the need for a networkx graph populated with weights computed. Default: False.\n\n    out_weights_path : str, optional\n        Where to save the extracted weight matrix. If networkx output is returned, it would be saved in GraphML format.\n        Default: nothing saved unless instructed.\n\n    Returns\n    -------\n    edge_weights : ndarray\n        numpy 2d array of pair-wise edge-weights (of size: num_groups x num_groups),\n        wherein num_groups is determined by the total number of unique values in `groups`.\n\n        **Note**:\n\n        - Only the upper triangular matrix is filled as the distance between node i and j would be the same as j and i.\n        - The edge weights from the upper triangular matrix can easily be obtained by\n\n        .. code-block:: python\n\n            weights_array = edge_weights[ np.triu_indices_from(edge_weights, 1) ]"
  },
  {
    "code": "def _get_master_proc_by_name(self, name, tags):\n        master_name = GUnicornCheck._get_master_proc_name(name)\n        master_procs = [p for p in psutil.process_iter() if p.cmdline() and p.cmdline()[0] == master_name]\n        if len(master_procs) == 0:\n            self.service_check(\n                self.SVC_NAME,\n                AgentCheck.CRITICAL,\n                tags=['app:' + name] + tags,\n                message=\"No gunicorn process with name %s found\" % name,\n            )\n            raise GUnicornCheckError(\"Found no master process with name: %s\" % master_name)\n        else:\n            self.log.debug(\"There exist %s master process(es) with the name %s\" % (len(master_procs), name))\n            return master_procs",
    "docstring": "Return a psutil process for the master gunicorn process with the given name."
  },
  {
    "code": "def should_set_cookie(self, app: 'Quart', session: SessionMixin) -> bool:\n        if session.modified:\n            return True\n        save_each = app.config['SESSION_REFRESH_EACH_REQUEST']\n        return save_each and session.permanent",
    "docstring": "Helper method to return if the Set Cookie header should be present.\n\n        This triggers if the session is marked as modified or the app\n        is configured to always refresh the cookie."
  },
  {
    "code": "def parse_reaction_list(path, reactions, default_compartment=None):\n    context = FilePathContext(path)\n    for reaction_def in reactions:\n        if 'include' in reaction_def:\n            include_context = context.resolve(reaction_def['include'])\n            for reaction in parse_reaction_file(\n                    include_context, default_compartment):\n                yield reaction\n        else:\n            yield parse_reaction(reaction_def, default_compartment, context)",
    "docstring": "Parse a structured list of reactions as obtained from a YAML file\n\n    Yields tuples of reaction ID and reaction object. Path can be given as a\n    string or a context."
  },
  {
    "code": "def run_impl(self, change, entry, out):\n        options = self.options\n        javascripts = self._relative_uris(options.html_javascripts)\n        stylesheets = self._relative_uris(options.html_stylesheets)\n        template_class = resolve_cheetah_template(type(change))\n        template = template_class()\n        template.transaction = DummyTransaction()\n        template.transaction.response(resp=out)\n        template.change = change\n        template.entry = entry\n        template.options = options\n        template.breadcrumbs = self.breadcrumbs\n        template.javascripts = javascripts\n        template.stylesheets = stylesheets\n        template.render_change = lambda c: self.run_impl(c, entry, out)\n        template.respond()\n        template.shutdown()",
    "docstring": "sets up the report directory for an HTML report. Obtains the\n        top-level Cheetah template that is appropriate for the change\n        instance, and runs it.\n\n        The cheetah templates are supplied the following values:\n         * change - the Change instance to report on\n         * entry - the string name of the entry for this report\n         * options - the cli options object\n         * breadcrumbs - list of backlinks\n         * javascripts - list of .js links\n         * stylesheets - list of .css links\n\n        The cheetah templates are also given a render_change method\n        which can be called on another Change instance to cause its\n        template to be resolved and run in-line."
  },
  {
    "code": "def libvlc_media_player_set_video_title_display(p_mi, position, timeout):\n    f = _Cfunctions.get('libvlc_media_player_set_video_title_display', None) or \\\n        _Cfunction('libvlc_media_player_set_video_title_display', ((1,), (1,), (1,),), None,\n                    None, MediaPlayer, Position, ctypes.c_int)\n    return f(p_mi, position, timeout)",
    "docstring": "Set if, and how, the video title will be shown when media is played.\n    @param p_mi: the media player.\n    @param position: position at which to display the title, or libvlc_position_disable to prevent the title from being displayed.\n    @param timeout: title display timeout in milliseconds (ignored if libvlc_position_disable).\n    @version: libVLC 2.1.0 or later."
  },
  {
    "code": "def qrot(vector, quaternion):\n    t = 2 * np.cross(quaternion[1:], vector)\n    v_rot = vector + quaternion[0] * t + np.cross(quaternion[1:], t)\n    return v_rot",
    "docstring": "Rotate a 3D vector using quaternion algebra.\n\n    Implemented by Vladimir Kulikovskiy.\n\n    Parameters\n    ----------\n    vector: np.array\n    quaternion: np.array\n\n    Returns\n    -------\n    np.array"
  },
  {
    "code": "def getResiduals(self):\n        X = np.zeros((self.N*self.P,self.n_fixed_effs))\n        ip = 0\n        for i in range(self.n_terms):\n            Ki = self.A[i].shape[0]*self.F[i].shape[1]\n            X[:,ip:ip+Ki] = np.kron(self.A[i].T,self.F[i])\n            ip += Ki\n        y = np.reshape(self.Y,(self.Y.size,1),order='F')\n        RV = regressOut(y,X)\n        RV = np.reshape(RV,self.Y.shape,order='F')\n        return RV",
    "docstring": "regress out fixed effects and results residuals"
  },
  {
    "code": "def easeInOutQuad(n):\n    _checkRange(n)\n    if n < 0.5:\n        return 2 * n**2\n    else:\n        n = n * 2 - 1\n        return -0.5 * (n*(n-2) - 1)",
    "docstring": "A quadratic tween function that accelerates, reaches the midpoint, and then decelerates.\n\n    Args:\n      n (float): The time progress, starting at 0.0 and ending at 1.0.\n\n    Returns:\n      (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine()."
  },
  {
    "code": "def log_inference(batch_id, batch_num, metric, step_loss, log_interval):\n    metric_nm, metric_val = metric.get()\n    if not isinstance(metric_nm, list):\n        metric_nm = [metric_nm]\n        metric_val = [metric_val]\n    eval_str = '[Batch %d/%d] loss=%.4f, metrics:' + \\\n               ','.join([i + ':%.4f' for i in metric_nm])\n    logging.info(eval_str, batch_id + 1, batch_num, \\\n                 step_loss / log_interval, \\\n                 *metric_val)",
    "docstring": "Generate and print out the log message for inference."
  },
  {
    "code": "def parse(cls, root):\n        subsection = root.tag.replace(utils.lxmlns(\"mets\"), \"\", 1)\n        if subsection not in cls.ALLOWED_SUBSECTIONS:\n            raise exceptions.ParseError(\n                \"SubSection can only parse elements with tag in %s with METS namespace\"\n                % (cls.ALLOWED_SUBSECTIONS,)\n            )\n        section_id = root.get(\"ID\")\n        created = root.get(\"CREATED\", \"\")\n        status = root.get(\"STATUS\", \"\")\n        child = root[0]\n        if child.tag == utils.lxmlns(\"mets\") + \"mdWrap\":\n            mdwrap = MDWrap.parse(child)\n            obj = cls(subsection, mdwrap, section_id)\n        elif child.tag == utils.lxmlns(\"mets\") + \"mdRef\":\n            mdref = MDRef.parse(child)\n            obj = cls(subsection, mdref, section_id)\n        else:\n            raise exceptions.ParseError(\n                \"Child of %s must be mdWrap or mdRef\" % subsection\n            )\n        obj.created = created\n        obj.status = status\n        return obj",
    "docstring": "Create a new SubSection by parsing root.\n\n        :param root: Element or ElementTree to be parsed into an object.\n        :raises exceptions.ParseError: If root's tag is not in :const:`SubSection.ALLOWED_SUBSECTIONS`.\n        :raises exceptions.ParseError: If the first child of root is not mdRef or mdWrap."
  },
  {
    "code": "def from_dict(cls, d):\n        o = super(DistributionList, cls).from_dict(d)\n        o.members = []\n        if 'dlm' in d:\n            o.members = [utils.get_content(member)\n                         for member in utils.as_list(d[\"dlm\"])]\n        return o",
    "docstring": "Override default, adding the capture of members."
  },
  {
    "code": "def collect(self, order_ref):\n        response = self.client.post(\n            self._collect_endpoint, json={\"orderRef\": order_ref}\n        )\n        if response.status_code == 200:\n            return response.json()\n        else:\n            raise get_json_error_class(response)",
    "docstring": "Collects the result of a sign or auth order using the\n        ``orderRef`` as reference.\n\n        RP should keep on calling collect every two seconds as long as status\n        indicates pending. RP must abort if status indicates failed. The user\n        identity is returned when complete.\n\n        Example collect results returned while authentication or signing is\n        still pending:\n\n        .. code-block:: json\n\n            {\n                \"orderRef\":\"131daac9-16c6-4618-beb0-365768f37288\",\n                \"status\":\"pending\",\n                \"hintCode\":\"userSign\"\n            }\n\n        Example collect result when authentication or signing has failed:\n\n        .. code-block:: json\n\n            {\n                \"orderRef\":\"131daac9-16c6-4618-beb0-365768f37288\",\n                \"status\":\"failed\",\n                \"hintCode\":\"userCancel\"\n            }\n\n        Example collect result when authentication or signing is successful\n        and completed:\n\n        .. code-block:: json\n\n            {\n                \"orderRef\":\"131daac9-16c6-4618-beb0-365768f37288\",\n                \"status\":\"complete\",\n                \"completionData\": {\n                    \"user\": {\n                        \"personalNumber\":\"190000000000\",\n                        \"name\":\"Karl Karlsson\",\n                        \"givenName\":\"Karl\",\n                        \"surname\":\"Karlsson\"\n                    },\n                    \"device\": {\n                        \"ipAddress\":\"192.168.0.1\"\n                    },\n                    \"cert\": {\n                        \"notBefore\":\"1502983274000\",\n                        \"notAfter\":\"1563549674000\"\n                    },\n                    \"signature\":\"<base64-encoded data>\",\n                    \"ocspResponse\":\"<base64-encoded data>\"\n                }\n            }\n\n        See `BankID Relying Party Guidelines Version: 3.0 <https://www.bankid.com/assets/bankid/rp/bankid-relying-party-guidelines-v3.0.pdf>`_\n        for more details about how to inform end user of the current status,\n        whether it is pending, failed or completed.\n\n        :param order_ref: The ``orderRef`` UUID returned from auth or sign.\n        :type order_ref: str\n        :return: The CollectResponse parsed to a dictionary.\n        :rtype: dict\n        :raises BankIDError: raises a subclass of this error\n                             when error has been returned from server."
  },
  {
    "code": "def adopt(self, payload, *args, flavour: ModuleType, **kwargs):\n        if args or kwargs:\n            payload = functools.partial(payload, *args, **kwargs)\n        self._meta_runner.register_payload(payload, flavour=flavour)",
    "docstring": "Concurrently run ``payload`` in the background\n\n        If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution."
  },
  {
    "code": "def _init_kelas(self, makna_label):\n        kelas = makna_label.find(color='red')\n        lain = makna_label.find(color='darkgreen')\n        info = makna_label.find(color='green')\n        if kelas:\n            kelas = kelas.find_all('span')\n        if lain:\n            self.kelas = {lain.text.strip(): lain['title'].strip()}\n            self.submakna = lain.next_sibling.strip()\n            self.submakna += ' ' + makna_label.find(color='grey').text.strip()\n        else:\n            self.kelas = {\n                k.text.strip(): k['title'].strip() for k in kelas\n            } if kelas else {}\n        self.info = info.text.strip() if info else ''",
    "docstring": "Memproses kelas kata yang ada dalam makna.\n\n        :param makna_label: BeautifulSoup untuk makna yang ingin diproses.\n        :type makna_label: BeautifulSoup"
  },
  {
    "code": "def GetCPIOArchiveFileEntryByPathSpec(self, path_spec):\n    location = getattr(path_spec, 'location', None)\n    if location is None:\n      raise errors.PathSpecError('Path specification missing location.')\n    if not location.startswith(self.LOCATION_ROOT):\n      raise errors.PathSpecError('Invalid location in path specification.')\n    if len(location) == 1:\n      return None\n    return self._cpio_archive_file.GetFileEntryByPath(location[1:])",
    "docstring": "Retrieves the CPIO archive file entry for a path specification.\n\n    Args:\n      path_spec (PathSpec): a path specification.\n\n    Returns:\n      CPIOArchiveFileEntry: CPIO archive file entry or None if not available.\n\n    Raises:\n      PathSpecError: if the path specification is incorrect."
  },
  {
    "code": "def within_joyner_boore_distance(self, surface, distance, **kwargs):\n        upper_depth, lower_depth = _check_depth_limits(kwargs)\n        rjb = surface.get_joyner_boore_distance(\n            self.catalogue.hypocentres_as_mesh())\n        is_valid = np.logical_and(\n            rjb <= distance,\n            np.logical_and(self.catalogue.data['depth'] >= upper_depth,\n                           self.catalogue.data['depth'] < lower_depth))\n        return self.select_catalogue(is_valid)",
    "docstring": "Select events within a Joyner-Boore distance of a fault\n\n        :param surface:\n            Fault surface as instance of\n            nhlib.geo.surface.base.SimpleFaultSurface  or as instance of\n            nhlib.geo.surface.ComplexFaultSurface\n\n        :param float distance:\n            Rupture distance (km)\n\n        :returns:\n            Instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue`\n            containing only selected events"
  },
  {
    "code": "def run(self, file, updateconfig=True, clean=False, path=None):\n        if updateconfig:\n            self.update_config()\n        self.program, self.version = self.setup(path)\n        commandline = (\n            self.program + \" -c \" + self.config['CONFIG_FILE'] + \" \" + file)\n        rcode = os.system(commandline)\n        if (rcode):\n            raise SExtractorException(\n                \"SExtractor command [%s] failed.\" % commandline\n            )\n        if clean:\n            self.clean()",
    "docstring": "Run SExtractor.\n\n        If updateconfig is True (default), the configuration\n        files will be updated before running SExtractor.\n\n        If clean is True (default: False), configuration files\n        (if any) will be deleted after SExtractor terminates."
  },
  {
    "code": "def iter_all_children(self):\n        if self.inline_child:\n            yield self.inline_child\n        for x in self.children:\n            yield x",
    "docstring": "Return an iterator that yields every node which is a child of this one.\n\n        This includes inline children, and control structure `else` clauses."
  },
  {
    "code": "def run_forever(self):\n        res = self.slack.rtm.start()\n        self.log.info(\"current channels: %s\",\n                      ','.join(c['name'] for c in res.body['channels']\n                               if c['is_member']))\n        self.id = res.body['self']['id']\n        self.name = res.body['self']['name']\n        self.my_mention = \"<@%s>\" % self.id\n        self.ws = websocket.WebSocketApp(\n            res.body['url'],\n            on_message=self._on_message,\n            on_error=self._on_error,\n            on_close=self._on_close,\n            on_open=self._on_open)\n        self.prepare_connection(self.config)\n        self.ws.run_forever()",
    "docstring": "Run the bot, blocking forever."
  },
  {
    "code": "def set_sampling_info(self, sample):\n        if sample.getScheduledSamplingSampler() and sample.getSamplingDate():\n            return True\n        sampler = self.get_form_value(\"getScheduledSamplingSampler\", sample,\n                                      sample.getScheduledSamplingSampler())\n        sampled = self.get_form_value(\"getSamplingDate\",\n                                      sample.getSamplingDate())\n        if not all([sampler, sampled]):\n            return False\n        sample.setScheduledSamplingSampler(sampler)\n        sample.setSamplingDate(DateTime(sampled))\n        return True",
    "docstring": "Updates the scheduled Sampling sampler and the Sampling Date with the\n        values provided in the request. If neither Sampling sampler nor Sampling\n        Date are present in the request, returns False"
  },
  {
    "code": "def connect(self):\n        self.socket = socket.socket()\n        self.socket.settimeout(self.timeout_in_seconds)\n        try:\n            self.socket.connect(self.addr)\n        except socket.timeout:\n            raise GraphiteSendException(\n                \"Took over %d second(s) to connect to %s\" %\n                (self.timeout_in_seconds, self.addr))\n        except socket.gaierror:\n            raise GraphiteSendException(\n                \"No address associated with hostname %s:%s\" % self.addr)\n        except Exception as error:\n            raise GraphiteSendException(\n                \"unknown exception while connecting to %s - %s\" %\n                (self.addr, error)\n            )\n        return self.socket",
    "docstring": "Make a TCP connection to the graphite server on port self.port"
  },
  {
    "code": "def _prep_cmd(cmd, tx_out_file):\n    cmd = \" \".join(cmd) if isinstance(cmd, (list, tuple)) else cmd\n    return \"export TMPDIR=%s && %s\" % (os.path.dirname(tx_out_file), cmd)",
    "docstring": "Wrap CNVkit commands ensuring we use local temporary directories."
  },
  {
    "code": "def evaluate_block(self, template, context=None, escape=None, safe_wrapper=None):\n        if context is None:\n            context = {}\n        try:\n            with self._evaluation_context(escape, safe_wrapper):\n                template = self._environment.from_string(template)\n                return template.render(**context)\n        except jinja2.TemplateError as error:\n            raise EvaluationError(error.args[0])\n        finally:\n            self._escape = None",
    "docstring": "Evaluate a template block."
  },
  {
    "code": "def find_range(self, interval):\n        return self.find(self.tree, interval, self.start, self.end)",
    "docstring": "wrapper for find"
  },
  {
    "code": "def get_grade_systems_by_ids(self, grade_system_ids):\n        collection = JSONClientValidated('grading',\n                                         collection='GradeSystem',\n                                         runtime=self._runtime)\n        object_id_list = []\n        for i in grade_system_ids:\n            object_id_list.append(ObjectId(self._get_id(i, 'grading').get_identifier()))\n        result = collection.find(\n            dict({'_id': {'$in': object_id_list}},\n                 **self._view_filter()))\n        result = list(result)\n        sorted_result = []\n        for object_id in object_id_list:\n            for object_map in result:\n                if object_map['_id'] == object_id:\n                    sorted_result.append(object_map)\n                    break\n        return objects.GradeSystemList(sorted_result, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets a ``GradeSystemList`` corresponding to the given ``IdList``.\n\n        In plenary mode, the returned list contains all of the systems\n        specified in the ``Id`` list, in the order of the list,\n        including duplicates, or an error results if an ``Id`` in the\n        supplied list is not found or inaccessible. Otherwise,\n        inaccessible ``GradeSystems`` may be omitted from the list and\n        may present the elements in any order including returning a\n        unique set.\n\n        arg:    grade_system_ids (osid.id.IdList): the list of ``Ids``\n                to retrieve\n        return: (osid.grading.GradeSystemList) - the returned\n                ``GradeSystem`` list\n        raise:  NotFound - an ``Id was`` not found\n        raise:  NullArgument - ``grade_system_ids`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_args(cls, dist, header=None):\n    if header is None:\n        header = cls.get_header()\n    spec = str(dist.as_requirement())\n    for type_ in 'console', 'gui':\n        group = type_ + '_scripts'\n        for name, ep in dist.get_entry_map(group).items():\n            if re.search(r'[\\\\/]', name):\n                raise ValueError(\"Path separators not allowed in script names\")\n            script_text = TEMPLATE.format(\n                ep.module_name,\n                ep.attrs[0],\n                '.'.join(ep.attrs),\n                spec,\n                group,\n                name,\n            )\n            args = cls._get_script_args(type_, name, header, script_text)\n            for res in args:\n                yield res",
    "docstring": "Overrides easy_install.ScriptWriter.get_args\n\n    This method avoids using pkg_resources to map a named entry_point\n    to a callable at invocation time."
  },
  {
    "code": "def find_name():\n    name_file = read_file('__init__.py')\n    name_match = re.search(r'^__package_name__ = [\"\\']([^\"\\']*)[\"\\']',\n                           name_file, re.M)\n    if name_match:\n        return name_match.group(1)\n    raise RuntimeError('Unable to find name string.')",
    "docstring": "Only define name in one place"
  },
  {
    "code": "def AsDict(self):\n    sources = []\n    for source in self.sources:\n      source_definition = {\n          'type': source.type_indicator,\n          'attributes': source.AsDict()\n      }\n      if source.supported_os:\n        source_definition['supported_os'] = source.supported_os\n      if source.conditions:\n        source_definition['conditions'] = source.conditions\n      sources.append(source_definition)\n    artifact_definition = {\n        'name': self.name,\n        'doc': self.description,\n        'sources': sources,\n    }\n    if self.labels:\n      artifact_definition['labels'] = self.labels\n    if self.supported_os:\n      artifact_definition['supported_os'] = self.supported_os\n    if self.provides:\n      artifact_definition['provides'] = self.provides\n    if self.conditions:\n      artifact_definition['conditions'] = self.conditions\n    if self.urls:\n      artifact_definition['urls'] = self.urls\n    return artifact_definition",
    "docstring": "Represents an artifact as a dictionary.\n\n    Returns:\n      dict[str, object]: artifact attributes."
  },
  {
    "code": "def __wrap(self, func):\n        def deffunc(*args, **kwargs):\n            if hasattr(inspect, 'signature'):\n                function_args = inspect.signature(func).parameters\n            else:\n                function_args = inspect.getargspec(func).args\n            filtered_kwargs = kwargs.copy()\n            for param in function_args:\n                if param in kwargs:\n                    filtered_kwargs[param] = kwargs[param]\n                elif param in self._defaults:\n                    filtered_kwargs[param] = self._defaults[param]\n            return func(*args, **filtered_kwargs)\n        wrapped = functools.update_wrapper(deffunc, func)\n        wrapped.__doc__ = ('WARNING: this function has been modified by the Presets '\n                           'package.\\nDefault parameter values described in the '\n                           'documentation below may be inaccurate.\\n\\n{}'.format(wrapped.__doc__))\n        return wrapped",
    "docstring": "This decorator overrides the default arguments of a function.\n\n        For each keyword argument in the function, the decorator first checks\n        if the argument has been overridden by the caller, and uses that value instead if so.\n\n        If not, the decorator consults the Preset object for an override value.\n\n        If both of the above cases fail, the decorator reverts to the function's native\n        default parameter value."
  },
  {
    "code": "def string_to_sign(self, http_request):\n        headers_to_sign = self.headers_to_sign(http_request)\n        canonical_headers = self.canonical_headers(headers_to_sign)\n        string_to_sign = '\\n'.join([http_request.method,\n                                    http_request.path,\n                                    '',\n                                    canonical_headers,\n                                    '',\n                                    http_request.body])\n        return string_to_sign, headers_to_sign",
    "docstring": "Return the canonical StringToSign as well as a dict\n        containing the original version of all headers that\n        were included in the StringToSign."
  },
  {
    "code": "def get(self, key):\n        modcommit = self._get_modcommit(key)\n        if not modcommit: return None\n        if key not in self.foreignkeys:\n            return cPickle.loads(str(modcommit.value))\n        try:\n            return TimeMachine(uid = modcommit.value).get_object()\n        except self.content_type.DoesNotExist:\n            raise DisciplineException(\"When restoring a ForeignKey, the \" \\\n                \"%s %s was not found.\" % (self.content_type.name, self.uid))",
    "docstring": "Return the value of a field.\n        \n        Take a string argument representing a field name, return the value of\n        that field at the time of this TimeMachine. When restoring a \n        ForeignKey-pointer object that doesn't exist, raise \n        DisciplineException"
  },
  {
    "code": "def map_agent(self, agent, do_rename):\n        agent_text = agent.db_refs.get('TEXT')\n        mapped_to_agent_json = self.agent_map.get(agent_text)\n        if mapped_to_agent_json:\n            mapped_to_agent = \\\n                Agent._from_json(mapped_to_agent_json['agent'])\n            return mapped_to_agent, False\n        if agent_text in self.gm.keys():\n            map_db_refs = self.gm[agent_text]\n        else:\n            return agent, False\n        if map_db_refs is None:\n            logger.debug(\"Skipping %s\" % agent_text)\n            return None, True\n        else:\n            self.update_agent_db_refs(agent, agent_text, do_rename)\n        return agent, False",
    "docstring": "Return the given Agent with its grounding mapped.\n\n        This function grounds a single agent. It returns the new Agent object\n        (which might be a different object if we load a new agent state\n        from json) or the same object otherwise.\n\n        Parameters\n        ----------\n        agent : :py:class:`indra.statements.Agent`\n            The Agent to map.\n        do_rename: bool\n            If True, the Agent name is updated based on the mapped grounding.\n            If do_rename is True the priority for setting the name is\n            FamPlex ID, HGNC symbol, then the gene name\n            from Uniprot.\n\n        Returns\n        -------\n        grounded_agent : :py:class:`indra.statements.Agent`\n            The grounded Agent.\n        maps_to_none : bool\n            True if the Agent is in the grounding map and maps to None."
  },
  {
    "code": "def cli_info(self, event):\n        self.log('Instance:', self.instance,\n                 'Dev:', self.development,\n                 'Host:', self.host,\n                 'Port:', self.port,\n                 'Insecure:', self.insecure,\n                 'Frontend:', self.frontendtarget)",
    "docstring": "Provides information about the running instance"
  },
  {
    "code": "def _consume(self):\n        while not self.is_closed:\n            msg = self._command_queue.get()\n            if msg is None:\n                return\n            with self._lock:\n                if self.is_ready:\n                    (command, reps, wait) = msg\n                    if command.select and self._selected_number != command.group_number:\n                        if self._send_raw(command.select_command.get_bytes(self)):\n                            self._selected_number = command.group_number\n                            time.sleep(SELECT_WAIT)\n                        else:\n                            self.is_ready = False\n                    for _ in range(reps):\n                        if self.is_ready:\n                            if self._send_raw(command.get_bytes(self)):\n                                time.sleep(wait)\n                            else:\n                                self.is_ready = False\n            if not self.is_ready and not self.is_closed:\n                if self.version < 6:\n                    time.sleep(RECONNECT_TIME)\n                    self.is_ready = True",
    "docstring": "Consume commands from the queue.\n\n        The command is repeated according to the configured value.\n        Wait after each command is sent.\n\n        The bridge socket is a shared resource. It must only\n        be used by one thread at a time. Note that this can and\n        will delay commands if multiple groups are attempting\n        to communicate at the same time on the same bridge."
  },
  {
    "code": "def get_projects():\n    assert request.method == \"GET\", \"GET request expected received {}\".format(request.method)\n    try:\n        if request.method == 'GET':\n            projects = utils.get_projects()\n            return jsonify(projects)\n    except Exception as e:\n        logging.error(e)\n    return jsonify({\"0\": \"__EMPTY\"})",
    "docstring": "Send a dictionary of projects that are available on the database.\n\n    Usage description:\n    This function is usually called to get and display the list of projects available in the database.\n\n    :return: JSON, {<int_keys>: <project_name>}"
  },
  {
    "code": "def _link_record(self):\n        action = self._get_lexicon_option('action')\n        identifier = self._get_lexicon_option('identifier')\n        rdtype = self._get_lexicon_option('type')\n        name = (self._fqdn_name(self._get_lexicon_option('name'))\n                if self._get_lexicon_option('name') else None)\n        link = self._get_provider_option('linked')\n        qname = name\n        if identifier:\n            rdtype, name, _ = self._parse_identifier(identifier)\n        if action != 'list' and rdtype in ('A', 'AAAA', 'TXT') and name and link == 'yes':\n            if action != 'update' or name == qname or not qname:\n                LOGGER.info('Hetzner => Enable CNAME lookup '\n                            '(see --linked parameter)')\n                return name, True\n        LOGGER.info('Hetzner => Disable CNAME lookup '\n                    '(see --linked parameter)')\n        return name, False",
    "docstring": "Checks restrictions for use of CNAME lookup and returns a tuple of the\n        fully qualified record name to lookup and a boolean, if a CNAME lookup\n        should be done or not. The fully qualified record name is empty if no\n        record name is specified by this provider."
  },
  {
    "code": "def from_db_value(self, value, expression, connection, context):\n        if value is None:\n            return value\n        return self.parse_seconds(value)",
    "docstring": "Handle data loaded from database."
  },
  {
    "code": "def hexstr(text):\n    text = text.strip().lower()\n    if text.startswith(('0x', '0X')):\n        text = text[2:]\n    if not text:\n        raise s_exc.BadTypeValu(valu=text, name='hexstr',\n                                mesg='No string left after stripping')\n    try:\n        s_common.uhex(text)\n    except (binascii.Error, ValueError) as e:\n        raise s_exc.BadTypeValu(valu=text, name='hexstr', mesg=str(e))\n    return text",
    "docstring": "Ensure a string is valid hex.\n\n    Args:\n        text (str): String to normalize.\n\n    Examples:\n        Norm a few strings:\n\n            hexstr('0xff00')\n            hexstr('ff00')\n\n    Notes:\n        Will accept strings prefixed by '0x' or '0X' and remove them.\n\n    Returns:\n        str: Normalized hex string."
  },
  {
    "code": "def _get_queue_batch_size(self, queue):\n        batch_queues = self.config['BATCH_QUEUES']\n        batch_size = 1\n        for part in dotted_parts(queue):\n            if part in batch_queues:\n                batch_size = batch_queues[part]\n        return batch_size",
    "docstring": "Get queue batch size."
  },
  {
    "code": "def _get_text_color(self):\n        color = self.code_array.cell_attributes[self.key][\"textcolor\"]\n        return tuple(c / 255.0 for c in color_pack2rgb(color))",
    "docstring": "Returns text color rgb tuple of right line"
  },
  {
    "code": "def add_suffix(string, suffix):\n    if string[-len(suffix):] != suffix:\n        return string + suffix\n    else:\n        return string",
    "docstring": "Adds a suffix to a string, if the string does not already have that suffix.\n\n    :param string: the string that should have a suffix added to it\n    :param suffix: the suffix to be added to the string\n    :return: the string with the suffix added, if it does not already end in\n        the suffix. Otherwise, it returns the original string."
  },
  {
    "code": "def get_weekday_parameters(self, filename='shlp_weekday_factors.csv'):\n        file = os.path.join(self.datapath, filename)\n        f_df = pd.read_csv(file, index_col=0)\n        tmp_df = f_df.query('shlp_type==\"{0}\"'.format(self.shlp_type)).drop(\n            'shlp_type', axis=1)\n        tmp_df['weekdays'] = np.array(list(range(7))) + 1\n        return np.array(list(map(float, pd.DataFrame.merge(\n            tmp_df, self.df, left_on='weekdays', right_on='weekday',\n            how='inner', left_index=True).sort_index()['wochentagsfaktor'])))",
    "docstring": "Retrieve the weekday parameter from csv-file\n\n        Parameters\n        ----------\n        filename : string\n            name of file where sigmoid factors are stored"
  },
  {
    "code": "def getClsNames(item):\n    mro = inspect.getmro(item.__class__)\n    mro = [c for c in mro if c not in clsskip]\n    return ['%s.%s' % (c.__module__, c.__name__) for c in mro]",
    "docstring": "Return a list of \"fully qualified\" class names for an instance.\n\n    Example:\n\n        for name in getClsNames(foo):\n            print(name)"
  },
  {
    "code": "def get_ladder_metadata(session, url):\n    parsed = make_scrape_request(session, url)\n    tag = parsed.find('a', href=re.compile(LADDER_ID_REGEX))\n    return {\n        'id': int(tag['href'].split('/')[-1]),\n        'slug': url.split('/')[-1],\n        'url': url\n    }",
    "docstring": "Get ladder metadata."
  },
  {
    "code": "def asdict(self):\n        if self.cache and self._cached_asdict is not None:\n            return self._cached_asdict\n        d = self._get_nosync()\n        if self.cache:\n            self._cached_asdict = d\n        return d",
    "docstring": "Retrieve all attributes as a dictionary."
  },
  {
    "code": "def add_check(self, func, *, call_once=False):\n        if call_once:\n            self._check_once.append(func)\n        else:\n            self._checks.append(func)",
    "docstring": "Adds a global check to the bot.\n\n        This is the non-decorator interface to :meth:`.check`\n        and :meth:`.check_once`.\n\n        Parameters\n        -----------\n        func\n            The function that was used as a global check.\n        call_once: :class:`bool`\n            If the function should only be called once per\n            :meth:`.Command.invoke` call."
  },
  {
    "code": "def UpdateTaskAsProcessingByIdentifier(self, task_identifier):\n    with self._lock:\n      task_processing = self._tasks_processing.get(task_identifier, None)\n      if task_processing:\n        task_processing.UpdateProcessingTime()\n        self._UpdateLatestProcessingTime(task_processing)\n        return\n      task_queued = self._tasks_queued.get(task_identifier, None)\n      if task_queued:\n        logger.debug('Task {0:s} was queued, now processing.'.format(\n            task_identifier))\n        self._tasks_processing[task_identifier] = task_queued\n        del self._tasks_queued[task_identifier]\n        task_queued.UpdateProcessingTime()\n        self._UpdateLatestProcessingTime(task_queued)\n        return\n      task_abandoned = self._tasks_abandoned.get(task_identifier, None)\n      if task_abandoned:\n        del self._tasks_abandoned[task_identifier]\n        self._tasks_processing[task_identifier] = task_abandoned\n        logger.debug('Task {0:s} was abandoned, but now processing.'.format(\n            task_identifier))\n        task_abandoned.UpdateProcessingTime()\n        self._UpdateLatestProcessingTime(task_abandoned)\n        return\n      if task_identifier in self._tasks_pending_merge:\n        return\n    raise KeyError('Status of task {0:s} is unknown.'.format(task_identifier))",
    "docstring": "Updates the task manager to reflect the task is processing.\n\n    Args:\n      task_identifier (str): unique identifier of the task.\n\n    Raises:\n      KeyError: if the task is not known to the task manager."
  },
  {
    "code": "def _GetCallingPrototypeAsString(self, flow_cls):\n    output = []\n    output.append(\"flow.StartAFF4Flow(client_id=client_id, \")\n    output.append(\"flow_name=\\\"%s\\\", \" % flow_cls.__name__)\n    prototypes = []\n    if flow_cls.args_type:\n      for type_descriptor in flow_cls.args_type.type_infos:\n        if not type_descriptor.hidden:\n          prototypes.append(\"%s=%s\" %\n                            (type_descriptor.name, type_descriptor.name))\n    output.append(\", \".join(prototypes))\n    output.append(\")\")\n    return \"\".join(output)",
    "docstring": "Get a description of the calling prototype for this flow class."
  },
  {
    "code": "def mget(self, key, *keys, encoding=_NOTSET):\n        return self.execute(b'MGET', key, *keys, encoding=encoding)",
    "docstring": "Get the values of all the given keys."
  },
  {
    "code": "def set_link_status(link_id, status, **kwargs):\n    user_id = kwargs.get('user_id')\n    try:\n        link_i = db.DBSession.query(Link).filter(Link.id == link_id).one()\n    except NoResultFound:\n        raise ResourceNotFoundError(\"Link %s not found\"%(link_id))\n    link_i.network.check_write_permission(user_id)\n    link_i.status = status\n    db.DBSession.flush()",
    "docstring": "Set the status of a link"
  },
  {
    "code": "def min_length_discard(records, min_length):\n    logging.info('Applying _min_length_discard generator: '\n                 'discarding records shorter than %d.', min_length)\n    for record in records:\n        if len(record) < min_length:\n            logging.debug('Discarding short sequence: %s, length=%d',\n                record.id, len(record))\n        else:\n            yield record",
    "docstring": "Discard any records that are shorter than min_length."
  },
  {
    "code": "def scatter(self, *args, **kwargs):\n        marker_type = kwargs.pop(\"marker\", \"circle\")\n        if isinstance(marker_type, string_types) and marker_type in _MARKER_SHORTCUTS:\n            marker_type = _MARKER_SHORTCUTS[marker_type]\n        if marker_type == \"circle\" and \"radius\" in kwargs:\n            return self.circle(*args, **kwargs)\n        else:\n            return self._scatter(*args, marker=marker_type, **kwargs)",
    "docstring": "Creates a scatter plot of the given x and y items.\n\n        Args:\n            x (str or seq[float]) : values or field names of center x coordinates\n\n            y (str or seq[float]) : values or field names of center y coordinates\n\n            size (str or list[float]) : values or field names of sizes in screen units\n\n            marker (str, or list[str]): values or field names of marker types\n\n            color (color value, optional): shorthand to set both fill and line color\n\n            source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source.\n                An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource`\n                if needed. If none is supplied, one is created for the user automatically.\n\n            **kwargs: :ref:`userguide_styling_line_properties` and :ref:`userguide_styling_fill_properties`\n\n        Examples:\n\n            >>> p.scatter([1,2,3],[4,5,6], marker=\"square\", fill_color=\"red\")\n            >>> p.scatter(\"data1\", \"data2\", marker=\"mtype\", source=data_source, ...)\n\n        .. note::\n            When passing ``marker=\"circle\"`` it is also possible to supply a\n            ``radius`` value in data-space units. When configuring marker type\n            from a data source column, *all* markers incuding circles may only\n            be configured with ``size`` in screen units."
  },
  {
    "code": "def apply_rcparams(kind=\"fast\"):\n    if kind == \"default\":\n        matplotlib.rcdefaults()\n    elif kind == \"fast\":\n        matplotlib.rcParams[\"text.usetex\"] = False\n        matplotlib.rcParams[\"mathtext.fontset\"] = \"cm\"\n        matplotlib.rcParams[\"font.family\"] = \"sans-serif\"\n        matplotlib.rcParams[\"font.size\"] = 14\n        matplotlib.rcParams[\"legend.edgecolor\"] = \"grey\"\n        matplotlib.rcParams[\"contour.negative_linestyle\"] = \"solid\"\n    elif kind == \"publication\":\n        matplotlib.rcParams[\"text.usetex\"] = True\n        preamble = \"\\\\usepackage[cm]{sfmath}\\\\usepackage{amssymb}\"\n        matplotlib.rcParams[\"text.latex.preamble\"] = preamble\n        matplotlib.rcParams[\"mathtext.fontset\"] = \"cm\"\n        matplotlib.rcParams[\"font.family\"] = \"sans-serif\"\n        matplotlib.rcParams[\"font.serif\"] = \"cm\"\n        matplotlib.rcParams[\"font.sans-serif\"] = \"cm\"\n        matplotlib.rcParams[\"font.size\"] = 14\n        matplotlib.rcParams[\"legend.edgecolor\"] = \"grey\"\n        matplotlib.rcParams[\"contour.negative_linestyle\"] = \"solid\"",
    "docstring": "Quickly apply rcparams for given purposes.\n\n    Parameters\n    ----------\n    kind: {'default', 'fast', 'publication'} (optional)\n        Settings to use. Default is 'fast'."
  },
  {
    "code": "def share_with_link(self, share_type='view', share_scope='anonymous'):\n        if not self.object_id:\n            return None\n        url = self.build_url(\n            self._endpoints.get('share_link').format(id=self.object_id))\n        data = {\n            'type': share_type,\n            'scope': share_scope\n        }\n        response = self.con.post(url, data=data)\n        if not response:\n            return None\n        data = response.json()\n        return DriveItemPermission(parent=self, **{self._cloud_data_key: data})",
    "docstring": "Creates or returns a link you can share with others\n\n        :param str share_type: 'view' to allow only view access,\n         'edit' to allow editions, and\n         'embed' to allow the DriveItem to be embedded\n        :param str share_scope: 'anonymous': anyone with the link can access.\n         'organization' Only organization members can access\n        :return: link to share\n        :rtype: DriveItemPermission"
  },
  {
    "code": "def run(wf, *, display, n_threads=1):\n    worker = dynamic_exclusion_worker(display, n_threads)\n    return noodles.Scheduler(error_handler=display.error_handler)\\\n        .run(worker, get_workflow(wf))",
    "docstring": "Run the workflow using the dynamic-exclusion worker."
  },
  {
    "code": "def CELERY_RESULT_BACKEND(self):\n        configured = get('CELERY_RESULT_BACKEND', None)\n        if configured:\n            return configured\n        if not self._redis_available():\n            return None\n        host, port = self.REDIS_HOST, self.REDIS_PORT\n        if host and port:\n            default = \"redis://{host}:{port}/{db}\".format(\n                    host=host, port=port,\n                    db=self.CELERY_REDIS_RESULT_DB)\n        return default",
    "docstring": "Redis result backend config"
  },
  {
    "code": "def _fields_common(self):\n        result = {}\n        if not self.testmode:\n            result[\"__reponame__\"] = self.repo.repo.full_name\n            result[\"__repodesc__\"] = self.repo.repo.description\n            result[\"__repourl__\"] = self.repo.repo.html_url\n            result[\"__repodir__\"] = self.repodir\n            if self.organization is not None:\n                owner = self.repo.organization\n            else:\n                owner = self.repo.user\n            result[\"__username__\"] = owner.name\n            result[\"__userurl__\"] = owner.html_url\n            result[\"__useravatar__\"] = owner.avatar_url\n            result[\"__useremail__\"] = owner.email\n        return result",
    "docstring": "Returns a dictionary of fields and values that are common to all events\n        for which fields dictionaries are created."
  },
  {
    "code": "def map(self, key_pattern, func, all_args, timeout=None):\n        results = []\n        keys = [\n            make_key(key_pattern, func, args, {})\n            for args in all_args\n        ]\n        cached = dict(zip(keys, self.get_many(keys)))\n        cache_to_add = {}\n        for key, args in zip(keys, all_args):\n            val = cached[key]\n            if val is None:\n                val = func(*args)\n                cache_to_add[key] = val if val is not None else NONE_RESULT\n            if val == NONE_RESULT:\n                val = None\n            results.append(val)\n        if cache_to_add:\n            self.set_many(cache_to_add, timeout)\n        return results",
    "docstring": "Cache return value of multiple calls.\n\n        Args:\n            key_pattern (str): the key pattern to use for generating\n                               keys for caches of the decorated function.\n            func (function): the function to call.\n            all_args (list): a list of args to be used to make calls to\n                             the function.\n            timeout (int): the cache timeout\n\n        Returns:\n            A list of the return values of the calls.\n\n        Example::\n\n            def add(a, b):\n                return a + b\n\n            cache.map(key_pat, add, [(1, 2), (3, 4)]) == [3, 7]"
  },
  {
    "code": "def makeUnicodeToGlyphNameMapping(self):\n        compiler = self.context.compiler\n        cmap = None\n        if compiler is not None:\n            table = compiler.ttFont.get(\"cmap\")\n            if table is not None:\n                cmap = table.getBestCmap()\n        if cmap is None:\n            from ufo2ft.util import makeUnicodeToGlyphNameMapping\n            if compiler is not None:\n                glyphSet = compiler.glyphSet\n            else:\n                glyphSet = self.context.font\n            cmap = makeUnicodeToGlyphNameMapping(glyphSet)\n        return cmap",
    "docstring": "Return the Unicode to glyph name mapping for the current font."
  },
  {
    "code": "def _margtime_loglr(self, mf_snr, opt_snr):\n        return special.logsumexp(mf_snr, b=self._deltat) - 0.5*opt_snr",
    "docstring": "Returns the log likelihood ratio marginalized over time."
  },
  {
    "code": "def metrics(self, name):\n        return [\n            MetricStub(\n                ensure_unicode(stub.name),\n                stub.type,\n                stub.value,\n                normalize_tags(stub.tags),\n                ensure_unicode(stub.hostname),\n            )\n            for stub in self._metrics.get(to_string(name), [])\n        ]",
    "docstring": "Return the metrics received under the given name"
  },
  {
    "code": "def log_request(self, extra=''):\n        thread_name = threading.currentThread().getName().lower()\n        if thread_name == 'mainthread':\n            thread_name = ''\n        else:\n            thread_name = '-%s' % thread_name\n        if self.config['proxy']:\n            if self.config['proxy_userpwd']:\n                auth = ' with authorization'\n            else:\n                auth = ''\n            proxy_info = ' via %s proxy of type %s%s' % (\n                self.config['proxy'], self.config['proxy_type'], auth)\n        else:\n            proxy_info = ''\n        if extra:\n            extra = '[%s] ' % extra\n        logger_network.debug(\n            '[%s%s] %s%s %s%s',\n            ('%02d' % self.request_counter\n             if self.request_counter is not None else 'NA'),\n            thread_name,\n            extra, self.request_method or 'GET',\n            self.config['url'], proxy_info)",
    "docstring": "Send request details to logging system."
  },
  {
    "code": "def run_parser(quil):\n    input_stream = InputStream(quil)\n    lexer = QuilLexer(input_stream)\n    stream = CommonTokenStream(lexer)\n    parser = QuilParser(stream)\n    parser.removeErrorListeners()\n    parser.addErrorListener(CustomErrorListener())\n    tree = parser.quil()\n    pyquil_listener = PyQuilListener()\n    walker = ParseTreeWalker()\n    walker.walk(pyquil_listener, tree)\n    return pyquil_listener.result",
    "docstring": "Run the ANTLR parser.\n\n    :param str quil: a single or multiline Quil program\n    :return: list of instructions that were parsed"
  },
  {
    "code": "def current(self):\n        results = self._timeline.find_withtag(tk.CURRENT)\n        return results[0] if len(results) != 0 else None",
    "docstring": "Currently active item on the _timeline Canvas\n\n        :rtype: str"
  },
  {
    "code": "def get_url(path, host, port, method=\"http\"):\n    return urlunsplit(\n        (method, \"%s:%s\" % (host, port), path, \"\", \"\")\n    )",
    "docstring": "make url from path, host and port\n\n    :param method: str\n    :param path: str, path within the request, e.g. \"/api/version\"\n    :param host: str\n    :param port: str or int\n    :return: str"
  },
  {
    "code": "def tbframes(tb):\n  'unwind traceback tb_next structure to array'\n  frames=[tb.tb_frame]\n  while tb.tb_next: tb=tb.tb_next; frames.append(tb.tb_frame)\n  return frames",
    "docstring": "unwind traceback tb_next structure to array"
  },
  {
    "code": "def get_disabled():\n    ret = set()\n    for name in _iter_service_names():\n        if _service_is_upstart(name):\n            if _upstart_is_disabled(name):\n                ret.add(name)\n        else:\n            if _service_is_sysv(name):\n                if _sysv_is_disabled(name):\n                    ret.add(name)\n    return sorted(ret)",
    "docstring": "Return the disabled services\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' service.get_disabled"
  },
  {
    "code": "def get_data():\n    y = 1.0 / (1.0 + 1j*(n_x.get_value()-0.002)*1000) + _n.random.rand()*0.1\n    _t.sleep(0.1)\n    return abs(y), _n.angle(y, True)",
    "docstring": "Currently pretends to talk to an instrument and get back the magnitud\n    and phase of the measurement."
  },
  {
    "code": "def getComponentByPosition(self, idx, default=noValue, instantiate=True):\n        try:\n            componentValue = self._componentValues[idx]\n        except IndexError:\n            if not instantiate:\n                return default\n            self.setComponentByPosition(idx)\n            componentValue = self._componentValues[idx]\n        if default is noValue or componentValue.isValue:\n            return componentValue\n        else:\n            return default",
    "docstring": "Return |ASN.1| type component value by position.\n\n        Equivalent to Python sequence subscription operation (e.g. `[]`).\n\n        Parameters\n        ----------\n        idx : :class:`int`\n            Component index (zero-based). Must either refer to an existing\n            component or to N+1 component (if *componentType* is set). In the latter\n            case a new component type gets instantiated and appended to the |ASN.1|\n            sequence.\n\n        Keyword Args\n        ------------\n        default: :class:`object`\n            If set and requested component is a schema object, return the `default`\n            object instead of the requested component.\n\n        instantiate: :class:`bool`\n            If `True` (default), inner component will be automatically instantiated.\n            If 'False' either existing component or the `noValue` object will be\n            returned.\n\n        Returns\n        -------\n        : :py:class:`~pyasn1.type.base.PyAsn1Item`\n            Instantiate |ASN.1| component type or return existing component value\n\n        Examples\n        --------\n\n        .. code-block:: python\n\n            # can also be SetOf\n            class MySequenceOf(SequenceOf):\n                componentType = OctetString()\n\n            s = MySequenceOf()\n\n            # returns component #0 with `.isValue` property False\n            s.getComponentByPosition(0)\n\n            # returns None\n            s.getComponentByPosition(0, default=None)\n\n            s.clear()\n\n            # returns noValue\n            s.getComponentByPosition(0, instantiate=False)\n\n            # sets component #0 to OctetString() ASN.1 schema\n            # object and returns it\n            s.getComponentByPosition(0, instantiate=True)\n\n            # sets component #0 to ASN.1 value object\n            s.setComponentByPosition(0, 'ABCD')\n\n            # returns OctetString('ABCD') value object\n            s.getComponentByPosition(0, instantiate=False)\n\n            s.clear()\n\n            # returns noValue\n            s.getComponentByPosition(0, instantiate=False)"
  },
  {
    "code": "def sort_by_size(self, group_limit=None, discard_others=False,\n                     others_label='others'):\n        self.groups = OrderedDict(sorted(six.iteritems(self.groups),\n                                         key=lambda x: len(x[1]),\n                                         reverse=True))\n        if group_limit is not None:\n            if not discard_others:\n                group_keys = self.groups.keys()[group_limit - 1:]\n                self.groups.setdefault(others_label, list())\n            else:\n                group_keys = self.groups.keys()[group_limit:]\n            for g in group_keys:\n                if not discard_others:\n                    self.groups[others_label].extend(self.groups[g])\n                del self.groups[g]\n            if (others_label in self.groups and\n                    len(self.groups[others_label]) == 0):\n                del self.groups[others_label]\n        if discard_others and others_label in self.groups:\n            del self.groups[others_label]",
    "docstring": "Sort the groups by the number of elements they contain, descending.\n\n        Also has option to limit the number of groups. If this option is\n        chosen, the remaining elements are placed into another group with the\n        name specified with others_label. if discard_others is True, the others\n        group is removed instead."
  },
  {
    "code": "def reconnectRemote(self, remote):\n        if not isinstance(remote, Remote):\n            raise PlenumTypeError('remote', remote, Remote)\n        logger.info('{} reconnecting to {}'.format(self, remote))\n        public, secret = self.selfEncKeys\n        remote.disconnect()\n        remote.connect(self.ctx, public, secret)\n        self.sendPingPong(remote, is_ping=True)",
    "docstring": "Disconnect remote and connect to it again\n\n        :param remote: instance of Remote from self.remotes\n        :param remoteName: name of remote\n        :return:"
  },
  {
    "code": "def get_validation_errors(self, xml_input):\n        errors = []\n        try:\n            parsed_xml = etree.parse(self._handle_xml(xml_input))\n            self.xmlschema.assertValid(parsed_xml)\n        except (etree.DocumentInvalid, etree.XMLSyntaxError), e:\n            errors = self._handle_errors(e.error_log)\n        except AttributeError:\n            raise CannotValidate('Set XSD to validate the XML')\n        return errors",
    "docstring": "This method returns a list of validation errors. If there are no errors\n        an empty list is returned"
  },
  {
    "code": "def get_applicable_content_pattern_names(self, path):\n    encodings = set()\n    applicable_content_pattern_names = set()\n    for path_pattern_name, content_pattern_names in self._required_matches.items():\n      m = self._path_matchers[path_pattern_name]\n      if m.matches(path):\n        encodings.add(m.content_encoding)\n        applicable_content_pattern_names.update(content_pattern_names)\n    if len(encodings) > 1:\n      raise ValueError('Path matched patterns with multiple content encodings ({}): {}'.format(\n        ', '.join(sorted(encodings)), path\n      ))\n    content_encoding = next(iter(encodings)) if encodings else None\n    return applicable_content_pattern_names, content_encoding",
    "docstring": "Return the content patterns applicable to a given path.\n\n    Returns a tuple (applicable_content_pattern_names, content_encoding).\n\n    If path matches no path patterns, the returned content_encoding will be None (and\n    applicable_content_pattern_names will be empty)."
  },
  {
    "code": "def convert_hardsigmoid(node, **kwargs):\n    name, input_nodes, attrs = get_inputs(node, kwargs)\n    alpha = float(attrs.get(\"alpha\", 0.2))\n    beta = float(attrs.get(\"beta\", 0.5))\n    node = onnx.helper.make_node(\n        'HardSigmoid',\n        input_nodes,\n        [name],\n        alpha=alpha,\n        beta=beta,\n        name=name\n    )\n    return [node]",
    "docstring": "Map MXNet's hard_sigmoid operator attributes to onnx's HardSigmoid operator\n    and return the created node."
  },
  {
    "code": "def _ast_worker(tokens, tokens_len, index, term):\n    statements = []\n    arguments = []\n    while index < tokens_len:\n        if term:\n            if term(index, tokens):\n                break\n        if tokens[index].type == TokenType.Word and \\\n           index + 1 < tokens_len and \\\n           tokens[index + 1].type == TokenType.LeftParen:\n            index, statement = _handle_function_call(tokens,\n                                                     tokens_len,\n                                                     index)\n            statements.append(statement)\n        elif _is_word_type(tokens[index].type):\n            arguments.append(Word(type=_word_type(tokens[index].type),\n                                  contents=tokens[index].content,\n                                  line=tokens[index].line,\n                                  col=tokens[index].col,\n                                  index=index))\n        index = index + 1\n    return (index, GenericBody(statements=statements,\n                               arguments=arguments))",
    "docstring": "The main collector for all AST functions.\n\n    This function is called recursively to find both variable use and function\n    calls and returns a GenericBody with both those variables and function\n    calls hanging off of it. The caller can figure out what to do with both of\n    those"
  },
  {
    "code": "def debug(self_,msg,*args,**kw):\n        self_.__db_print(DEBUG,msg,*args,**kw)",
    "docstring": "Print msg merged with args as a debugging statement.\n\n        See Python's logging module for details of message formatting."
  },
  {
    "code": "def _structure(msg, fp=None, level=0, include_default=False):\n    if fp is None:\n        fp = sys.stdout\n    tab = ' ' * (level * 4)\n    print(tab + msg.get_content_type(), end='', file=fp)\n    if include_default:\n        print(' [%s]' % msg.get_default_type(), file=fp)\n    else:\n        print(file=fp)\n    if msg.is_multipart():\n        for subpart in msg.get_payload():\n            _structure(subpart, fp, level+1, include_default)",
    "docstring": "A handy debugging aid"
  },
  {
    "code": "def getActionSetHandle(self, pchActionSetName):\n        fn = self.function_table.getActionSetHandle\n        pHandle = VRActionSetHandle_t()\n        result = fn(pchActionSetName, byref(pHandle))\n        return result, pHandle",
    "docstring": "Returns a handle for an action set. This handle is used for all performance-sensitive calls."
  },
  {
    "code": "def smooth(data, fw):\r\n    if fw == 0:\r\n        fdata = data\r\n    else:\r\n        fdata = lfilter(np.ones(fw)/fw, 1, data)\r\n    return fdata",
    "docstring": "Smooth data with a moving average."
  },
  {
    "code": "def get_all_dataset_names(configuration=None, **kwargs):\n        dataset = Dataset(configuration=configuration)\n        dataset['id'] = 'all dataset names'\n        return dataset._write_to_hdx('list', kwargs, 'id')",
    "docstring": "Get all dataset names in HDX\n\n        Args:\n            configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration.\n            **kwargs: See below\n            limit (int): Number of rows to return. Defaults to all dataset names.\n            offset (int): Offset in the complete result for where the set of returned dataset names should begin\n\n        Returns:\n            List[str]: list of all dataset names in HDX"
  },
  {
    "code": "def run(self) -> None:\n        fd = self._fd\n        encoding = self._encoding\n        line_terminators = self._line_terminators\n        queue = self._queue\n        buf = \"\"\n        while True:\n            try:\n                c = fd.read(1).decode(encoding)\n            except UnicodeDecodeError as e:\n                log.warning(\"Decoding error from {!r}: {!r}\", self._cmdargs, e)\n                if self._suppress_decoding_errors:\n                    continue\n                else:\n                    raise\n            if not c:\n                return\n            buf += c\n            for t in line_terminators:\n                try:\n                    t_idx = buf.index(t) + len(t)\n                    fragment = buf[:t_idx]\n                    buf = buf[t_idx:]\n                    queue.put(fragment)\n                except ValueError:\n                    pass",
    "docstring": "Read lines and put them on the queue."
  },
  {
    "code": "def _netname(name: str) -> dict:\n        try:\n            long = net_query(name).name\n            short = net_query(name).shortname\n        except AttributeError:\n            raise UnsupportedNetwork()\n        return {'long': long,\n                'short': short}",
    "docstring": "resolute network name,\n        required because some providers use shortnames and other use longnames."
  },
  {
    "code": "def update(self, environments):\n        data = {'environments': environments}\n        environments_ids = [str(env.get('id')) for env in environments]\n        return super(ApiEnvironment, self).put('api/v3/environment/%s/' %\n                                               ';'.join(environments_ids), data)",
    "docstring": "Method to update environments\n\n        :param environments: List containing environments desired to updated\n        :return: None"
  },
  {
    "code": "def ReadSerializedDict(cls, json_dict):\n    if json_dict:\n      json_object = cls._ConvertDictToObject(json_dict)\n      if not isinstance(json_object, containers_interface.AttributeContainer):\n        raise TypeError('{0:s} is not an attribute container type.'.format(\n            type(json_object)))\n      return json_object\n    return None",
    "docstring": "Reads an attribute container from serialized dictionary form.\n\n    Args:\n      json_dict (dict[str, object]): JSON serialized objects.\n\n    Returns:\n      AttributeContainer: attribute container or None.\n\n    Raises:\n      TypeError: if the serialized dictionary does not contain an\n          AttributeContainer."
  },
  {
    "code": "def fetch_image(self,rtsp_server_uri = _source,timeout_secs = 15):\n        self._check_ffmpeg()\n        cmd = \"ffmpeg -rtsp_transport tcp -i {} -loglevel quiet -frames 1 -f image2pipe -\".format(rtsp_server_uri)\n        with _sp.Popen(cmd, shell=True,  stdout=_sp.PIPE) as process:\n            try:\n                stdout,stderr = process.communicate(timeout=timeout_secs)\n            except _sp.TimeoutExpired as e:\n                process.kill()\n                raise TimeoutError(\"Connection to {} timed out\".format(rtsp_server_uri),e)\n        return _Image.open(_io.BytesIO(stdout))",
    "docstring": "Fetch a single frame using FFMPEG. Convert to PIL Image. Slow."
  },
  {
    "code": "def validate_data_files(problem, data_files, min_size):\n  data_dir = os.path.split(data_files[0])[0]\n  out_filepaths = problem.out_filepaths(data_dir)\n  missing_filepaths = set(out_filepaths) - set(data_files)\n  if missing_filepaths:\n    tf.logging.error(\"Missing %d data files\", len(missing_filepaths))\n  too_small = []\n  for data_file in data_files:\n    length = get_length(data_file)\n    if length < min_size:\n      too_small.append(data_file)\n  if too_small:\n    tf.logging.error(\"%d files too small\", len(too_small))\n  bad_files = too_small + list(missing_filepaths)\n  return bad_files",
    "docstring": "Validate presence and minimum size of files."
  },
  {
    "code": "def delete(self, domain, delete_subdomains=False):\n        uri = \"/%s/%s\" % (self.uri_base, utils.get_id(domain))\n        if delete_subdomains:\n            uri = \"%s?deleteSubdomains=true\" % uri\n        resp, resp_body = self._async_call(uri, method=\"DELETE\",\n                error_class=exc.DomainDeletionFailed, has_response=False)",
    "docstring": "Deletes the specified domain and all of its resource records. If the\n        domain has subdomains, each subdomain will now become a root domain. If\n        you wish to also delete any subdomains, pass True to 'delete_subdomains'."
  },
  {
    "code": "def deep_dependendants(self, target):\n        direct_dependents = self._gettask(target).provides_for\n        return (direct_dependents +\n                reduce(\n                    lambda a, b: a + b,\n                    [self.deep_dependendants(x) for x in direct_dependents],\n                    []))",
    "docstring": "Recursively finds the dependents of a given build target.\n            Assumes the dependency graph is noncyclic"
  },
  {
    "code": "async def create_new_pump_async(self, partition_id, lease):\n        loop = asyncio.get_event_loop()\n        partition_pump = EventHubPartitionPump(self.host, lease)\n        loop.create_task(partition_pump.open_async())\n        self.partition_pumps[partition_id] = partition_pump\n        _logger.info(\"Created new partition pump %r %r\", self.host.guid, partition_id)",
    "docstring": "Create a new pump thread with a given lease.\n\n        :param partition_id: The partition ID.\n        :type partition_id: str\n        :param lease: The lease to be used.\n        :type lease: ~azure.eventprocessorhost.lease.Lease"
  },
  {
    "code": "def remove_uid(self, uid):\n        for sid in self.get('uid2sid', uid):\n            self.remove('sid2uid', sid, uid)\n        self.delete('uid2sid', uid)",
    "docstring": "Remove all references to a specific User ID\n\n        :param uid: A User ID"
  },
  {
    "code": "def generate_apsara_log_config(json_value):\n        input_detail = json_value['inputDetail']\n        output_detail = json_value['outputDetail']\n        config_name = json_value['configName']\n        logSample = json_value.get('logSample', '')\n        logstore_name = output_detail['logstoreName']\n        endpoint = output_detail.get('endpoint', '')\n        log_path = input_detail['logPath']\n        file_pattern = input_detail['filePattern']\n        log_begin_regex = input_detail.get('logBeginRegex', '')\n        topic_format = input_detail['topicFormat']\n        filter_keys = input_detail['filterKey']\n        filter_keys_reg = input_detail['filterRegex']\n        config = ApsaraLogConfigDetail(config_name, logstore_name, endpoint, log_path, file_pattern,\n                                       log_begin_regex, topic_format, filter_keys, filter_keys_reg, logSample)\n        return config",
    "docstring": "Generate apsara logtail config from loaded json value\n\n        :param json_value:\n        :return:"
  },
  {
    "code": "def put_file(self, filename, index, doc_type, id=None, name=None):\n        if id is None:\n            request_method = 'POST'\n        else:\n            request_method = 'PUT'\n        path = make_path(index, doc_type, id)\n        doc = file_to_attachment(filename)\n        if name:\n            doc[\"_name\"] = name\n        return self._send_request(request_method, path, doc)",
    "docstring": "Store a file in a index"
  },
  {
    "code": "def copy(self):\n        return Header([line.copy() for line in self.lines], self.samples.copy())",
    "docstring": "Return a copy of this header"
  },
  {
    "code": "def _ensure_config_file_exists():\n    config_file = Path(ELIBConfig.config_file_path).absolute()\n    if not config_file.exists():\n        raise ConfigFileNotFoundError(ELIBConfig.config_file_path)",
    "docstring": "Makes sure the config file exists.\n\n    :raises: :class:`epab.core.new_config.exc.ConfigFileNotFoundError`"
  },
  {
    "code": "def evalsha(self, sha, numkeys, *keys_and_args):\n        return self.execute_command('EVALSHA', sha, numkeys, *keys_and_args)",
    "docstring": "Use the ``sha`` to execute a Lua script already registered via EVAL\n        or SCRIPT LOAD. Specify the ``numkeys`` the script will touch and the\n        key names and argument values in ``keys_and_args``. Returns the result\n        of the script.\n\n        In practice, use the object returned by ``register_script``. This\n        function exists purely for Redis API completion."
  },
  {
    "code": "def create_archive_dir(self):\n        archive_dir = os.path.join(self.tmp_dir, self.archive_name)\n        os.makedirs(archive_dir, 0o700)\n        return archive_dir",
    "docstring": "Create the archive dir"
  },
  {
    "code": "def _normalize(image):\n  offset = tf.constant(MEAN_RGB, shape=[1, 1, 3])\n  image -= offset\n  scale = tf.constant(STDDEV_RGB, shape=[1, 1, 3])\n  image /= scale\n  return image",
    "docstring": "Normalize the image to zero mean and unit variance."
  },
  {
    "code": "def series(self):\n        if not self.pages:\n            return []\n        useframes = self.pages.useframes\n        keyframe = self.pages.keyframe.index\n        series = []\n        for name in ('lsm', 'ome', 'imagej', 'shaped', 'fluoview', 'sis',\n                     'uniform', 'mdgel'):\n            if getattr(self, 'is_' + name, False):\n                series = getattr(self, '_series_' + name)()\n                break\n        self.pages.useframes = useframes\n        self.pages.keyframe = keyframe\n        if not series:\n            series = self._series_generic()\n        series = [s for s in series if product(s.shape) > 0]\n        for i, s in enumerate(series):\n            s.index = i\n        return series",
    "docstring": "Return related pages as TiffPageSeries.\n\n        Side effect: after calling this function, TiffFile.pages might contain\n        TiffPage and TiffFrame instances."
  },
  {
    "code": "def find_frequencies(data, freq=44100, bits=16):\n    n = len(data)\n    p = _fft(data)\n    uniquePts = numpy.ceil((n + 1) / 2.0)\n    p = [(abs(x) / float(n)) ** 2 * 2 for x in p[0:uniquePts]]\n    p[0] = p[0] / 2\n    if n % 2 == 0:\n        p[-1] = p[-1] / 2\n    s = freq / float(n)\n    freqArray = numpy.arange(0, uniquePts * s, s)\n    return zip(freqArray, p)",
    "docstring": "Convert audio data into a frequency-amplitude table using fast fourier\n    transformation.\n\n    Return a list of tuples (frequency, amplitude).\n\n    Data should only contain one channel of audio."
  },
  {
    "code": "def get_lib_module_dict(self):\n        from importlib import import_module\n        if not self.ref:\n            return {}\n        u = parse_app_url(self.ref)\n        if u.scheme == 'file':\n            if not self.set_sys_path():\n                return {}\n            for module_name in self.lib_dir_names:\n                try:\n                    m = import_module(module_name)\n                    return {k: v for k, v in m.__dict__.items() if not k.startswith('__')}\n                except ModuleNotFoundError as e:\n                    if not module_name in str(e):\n                        raise\n                    continue\n        else:\n            return {}",
    "docstring": "Load the 'lib' directory as a python module, so it can be used to provide functions\n        for rowpipe transforms. This only works filesystem packages"
  },
  {
    "code": "def grounded_slot_range(self, slot: Optional[Union[SlotDefinition, Optional[str]]]) -> str:\n        if slot is not None and not isinstance(slot, str):\n            slot = slot.range\n        if slot is None:\n            return DEFAULT_BUILTIN_TYPE_NAME\n        elif slot in builtin_names:\n            return slot\n        elif slot in self.schema.types:\n            return self.grounded_slot_range(self.schema.types[slot].typeof)\n        else:\n            return slot",
    "docstring": "Chase the slot range to its final form\n\n        @param slot: slot to check\n        @return: name of resolved range"
  },
  {
    "code": "def hydrate(self, database, recursive=True):\n        if isinstance(self, Document):\n            self.reload(database)\n        for field in self:\n            obj = getattr(self, field)\n            if isinstance(obj, Document):\n                obj.reload(database)\n                if recursive:\n                    obj.hydrate(database)\n        return self",
    "docstring": "By default, recursively reloads all instances of Document\n        in the model.  Recursion can be turned off.\n\n        :param database: the `Database` object source for rehydrating.\n        :return: an updated instance of `Document` / self."
  },
  {
    "code": "def domain_name(self, levels=1):\n        if levels < 1:\n            raise ValueError(\"levels must be greater than or equal to 1\")\n        if levels == 1:\n            return self.domain_word() + '.' + self.tld()\n        else:\n            return self.domain_word() + '.' + self.domain_name(levels - 1)",
    "docstring": "Produce an Internet domain name with the specified number of\n        subdomain levels.\n\n        >>> domain_name()\n        nichols-phillips.com\n        >>> domain_name(2)\n        williamson-hopkins.jackson.com"
  },
  {
    "code": "def closed(self, user):\n        decision = False\n        for record in self.history:\n            if record[\"when\"] < self.options.since.date:\n                continue\n            if not decision and record[\"when\"] < self.options.until.date:\n                for change in record[\"changes\"]:\n                    if (change[\"field_name\"] == \"status\"\n                            and change[\"added\"] == \"CLOSED\"\n                            and record[\"who\"] in [user.email, user.name]):\n                        decision = True\n            else:\n                for change in record[\"changes\"]:\n                    if (change[\"field_name\"] == \"status\"\n                            and change[\"removed\"] == \"CLOSED\"):\n                        decision = False\n        return decision",
    "docstring": "Moved to CLOSED and not later moved to ASSIGNED"
  },
  {
    "code": "def _reverse_call(self, related_method, *values):\n        related_fields = self._to_fields(*values)\n        for related_field in related_fields:\n            if callable(related_method):\n                related_method(related_field, self.instance._pk)\n            else:\n                getattr(related_field, related_method)(self.instance._pk)",
    "docstring": "Convert each value to a related field, then call the method on each\n        field, passing self.instance as argument.\n        If related_method is a string, it will be the method of the related field.\n        If it's a callable, it's a function which accept the related field and\n        self.instance."
  },
  {
    "code": "def get_all_users(self):\n\t\tr = requests.get(api_url+'users/', headers=self.headers)\n\t\tprint(request_status(r))\n\t\tr.raise_for_status()\n\t\toutput = r.json()\n\t\tresult = []\n\t\tfor x in output:\n\t\t\tresult.append(User(x))\n\t\treturn result",
    "docstring": "Returns all the users"
  },
  {
    "code": "def nearest_interval(self, interval):\n        thresh_range = 25\n        if interval < self.intervals[0] - thresh_range or interval > self.intervals[-1] + thresh_range:\n            raise IndexError(\"The interval given is beyond \" + str(thresh_range)\n                             + \" cents over the range of intervals defined.\")\n        index = find_nearest_index(self.intervals, interval)\n        return self.intervals[index]",
    "docstring": "This function returns the nearest interval to any given interval."
  },
  {
    "code": "def is_valid(hal_id):\n    match = REGEX.match(hal_id)\n    return (match is not None) and (match.group(0) == hal_id)",
    "docstring": "Check that a given HAL id is a valid one.\n\n    :param hal_id: The HAL id to be checked.\n    :returns: Boolean indicating whether the HAL id is valid or not.\n\n    >>> is_valid(\"hal-01258754, version 1\")\n    True\n\n    >>> is_valid(\"hal-01258754\")\n    True\n\n    >>> is_valid(\"hal-01258754v2\")\n    True\n\n    >>> is_valid(\"foobar\")\n    False"
  },
  {
    "code": "def _termIsObsolete(oboTerm):\n    isObsolete = False\n    if u'is_obsolete' in oboTerm:\n        if oboTerm[u'is_obsolete'].lower() == u'true':\n            isObsolete = True\n    return isObsolete",
    "docstring": "Determine wheter an obo 'Term' entry is marked as obsolete.\n\n    :param oboTerm: a dictionary as return by\n        :func:`maspy.ontology._attributeLinesToDict()`\n\n    :return: bool"
  },
  {
    "code": "def instance(host=None, port=None):\n        if not hasattr(WebServer, \"_instance\") or WebServer._instance is None:\n            assert host is not None\n            assert port is not None\n            WebServer._instance = WebServer(host, port)\n        return WebServer._instance",
    "docstring": "Singleton to return only one instance of Server.\n\n        :returns: instance of Server"
  },
  {
    "code": "def _load_github_repo():\n    if 'TRAVIS' in os.environ:\n        raise RuntimeError('Detected that we are running in Travis. '\n                           'Stopping to prevent infinite loops.')\n    try:\n        with open(os.path.join(config_dir, 'repo'), 'r') as f:\n            return f.read()\n    except (OSError, IOError):\n        raise RuntimeError('Could not find your repository. '\n                           'Have you ran `trytravis --repo`?')",
    "docstring": "Loads the GitHub repository from the users config."
  },
  {
    "code": "def _make_hlog_numeric(b, r, d):\n    hlog_obj = lambda y, x, b, r, d: hlog_inv(y, b, r, d) - x\n    find_inv = vectorize(lambda x: brentq(hlog_obj, -2 * r, 2 * r,\n                                          args=(x, b, r, d)))\n    return find_inv",
    "docstring": "Return a function that numerically computes the hlog transformation for given parameter values."
  },
  {
    "code": "def eval(self, data, name, feval=None):\n        if not isinstance(data, Dataset):\n            raise TypeError(\"Can only eval for Dataset instance\")\n        data_idx = -1\n        if data is self.train_set:\n            data_idx = 0\n        else:\n            for i in range_(len(self.valid_sets)):\n                if data is self.valid_sets[i]:\n                    data_idx = i + 1\n                    break\n        if data_idx == -1:\n            self.add_valid(data, name)\n            data_idx = self.__num_dataset - 1\n        return self.__inner_eval(name, data_idx, feval)",
    "docstring": "Evaluate for data.\n\n        Parameters\n        ----------\n        data : Dataset\n            Data for the evaluating.\n        name : string\n            Name of the data.\n        feval : callable or None, optional (default=None)\n            Customized evaluation function.\n            Should accept two parameters: preds, train_data,\n            and return (eval_name, eval_result, is_higher_better) or list of such tuples.\n            For multi-class task, the preds is group by class_id first, then group by row_id.\n            If you want to get i-th row preds in j-th class, the access way is preds[j * num_data + i].\n\n        Returns\n        -------\n        result : list\n            List with evaluation results."
  },
  {
    "code": "def scores(factors):\n    temperaments = {\n        const.CHOLERIC: 0,\n        const.MELANCHOLIC: 0,\n        const.SANGUINE: 0,\n        const.PHLEGMATIC: 0                \n    }\n    qualities = {\n        const.HOT: 0,\n        const.COLD: 0,\n        const.DRY: 0,\n        const.HUMID: 0\n    }\n    for factor in factors:\n        element = factor['element']\n        temperament = props.base.elementTemperament[element]\n        temperaments[temperament] += 1\n        tqualities = props.base.temperamentQuality[temperament]\n        qualities[tqualities[0]] += 1\n        qualities[tqualities[1]] += 1\n    return {\n        'temperaments': temperaments,\n        'qualities': qualities\n    }",
    "docstring": "Computes the score of temperaments\n    and elements."
  },
  {
    "code": "def visit_subscript(self, node, parent):\n        context = self._get_context(node)\n        newnode = nodes.Subscript(\n            ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent\n        )\n        newnode.postinit(\n            self.visit(node.value, newnode), self.visit(node.slice, newnode)\n        )\n        return newnode",
    "docstring": "visit a Subscript node by returning a fresh instance of it"
  },
  {
    "code": "def gracefulShutdown(self):\n        if not self.bf.perspective:\n            log.msg(\"No active connection, shutting down NOW\")\n            reactor.stop()\n            return\n        log.msg(\n            \"Telling the master we want to shutdown after any running builds are finished\")\n        d = self.bf.perspective.callRemote(\"shutdown\")\n        def _shutdownfailed(err):\n            if err.check(AttributeError):\n                log.msg(\n                    \"Master does not support worker initiated shutdown.  Upgrade master to 0.8.3 or later to use this feature.\")\n            else:\n                log.msg('callRemote(\"shutdown\") failed')\n                log.err(err)\n        d.addErrback(_shutdownfailed)\n        return d",
    "docstring": "Start shutting down"
  },
  {
    "code": "def layer_covariance(layer1, layer2=None):\n    layer2 = layer2 or layer1\n    act1, act2 = layer1.activations, layer2.activations\n    num_datapoints = act1.shape[0]\n    return np.matmul(act1.T, act2) / float(num_datapoints)",
    "docstring": "Computes the covariance matrix between the neurons of two layers. If only one\n    layer is passed, computes the symmetric covariance matrix of that layer."
  },
  {
    "code": "def by_credentials(cls, session, login, password):\n        user = cls.by_login(session, login, local=True)\n        if not user:\n            return None\n        if crypt.check(user.password, password):\n            return user",
    "docstring": "Get a user from given credentials\n\n        :param session: SQLAlchemy session\n        :type session: :class:`sqlalchemy.Session`\n\n        :param login: username\n        :type login: unicode\n\n        :param password: user password\n        :type password: unicode\n\n        :return: associated user\n        :rtype: :class:`pyshop.models.User`"
  },
  {
    "code": "def pv_count(self):\n        self.open()\n        count = lvm_vg_get_pv_count(self.handle)\n        self.close()\n        return count",
    "docstring": "Returns the physical volume count."
  },
  {
    "code": "def from_polar(degrees, magnitude):\n        vec = Vector2()\n        vec.X = math.cos(math.radians(degrees)) * magnitude\n        vec.Y = -math.sin(math.radians(degrees)) * magnitude\n        return vec",
    "docstring": "Convert polar coordinates to Carteasian Coordinates"
  },
  {
    "code": "def url(self):\n        end_url = (\"/accounts/{account_id}/alerts/{alert_id}/mentions/\"\n                  \"{mention_id}/children?\")\n        def without_keys(d, keys):\n            return {x: d[x] for x in d if x not in keys}\n        keys = {\"access_token\", \"account_id\", \"alert_id\"}\n        parameters = without_keys(self.params, keys)\n        for key, value in list(parameters.items()):\n            if value != '':\n                end_url += '&' + key + '={' + key + '}'\n        end_url = end_url.format(**self.params)\n        return self._base_url + end_url",
    "docstring": "The concatenation of the `base_url` and `end_url` that make up the\n        resultant url.\n\n        :return: the `base_url` and the `end_url`.\n        :rtype: str"
  },
  {
    "code": "def check_version(chrome_exe):\n    cmd = [chrome_exe, '--version']\n    out = subprocess.check_output(cmd, timeout=60)\n    m = re.search(br'(Chromium|Google Chrome) ([\\d.]+)', out)\n    if not m:\n        sys.exit(\n                'unable to parse browser version from output of '\n                '%r: %r' % (subprocess.list2cmdline(cmd), out))\n    version_str = m.group(2).decode()\n    major_version = int(version_str.split('.')[0])\n    if major_version < 64:\n        sys.exit('brozzler requires chrome/chromium version 64 or '\n                 'later but %s reports version %s' % (\n                     chrome_exe, version_str))",
    "docstring": "Raises SystemExit if `chrome_exe` is not a supported browser version.\n\n    Must run in the main thread to have the desired effect."
  },
  {
    "code": "def merge(a, b):\n    \"merges b into a recursively if a and b are dicts\"\n    for key in b:\n        if isinstance(a.get(key), dict) and isinstance(b.get(key), dict):\n            merge(a[key], b[key])\n        else:\n            a[key] = b[key]\n    return a",
    "docstring": "merges b into a recursively if a and b are dicts"
  },
  {
    "code": "def create_x10(plm, housecode, unitcode, feature):\n    from insteonplm.devices.ipdb import IPDB\n    ipdb = IPDB()\n    product = ipdb.x10(feature)\n    deviceclass = product.deviceclass\n    device = None\n    if deviceclass:\n        device = deviceclass(plm, housecode, unitcode)\n    return device",
    "docstring": "Create an X10 device from a feature definition."
  },
  {
    "code": "def text(el, strip=True):\n    if not el:\n        return \"\"\n    text = el.text\n    if strip:\n        text = text.strip()\n    return text",
    "docstring": "Return the text of a ``BeautifulSoup`` element"
  },
  {
    "code": "def unused(self):\n    unused = self.definitions - self.used\n    used_nodes = set([u[1] for u in self.used])\n    unused = set([u for u in unused if u[1] not in used_nodes])\n    return unused",
    "docstring": "Calculate which AST nodes are unused.\n\n    Note that we have to take special care in the case of\n    x,y = f(z) where x is used later, but y is not."
  },
  {
    "code": "def _pick_selected_option(cls):\n        for option in cls.select_el:\n            if not hasattr(option, \"selected\"):\n                return None\n            if option.selected:\n                return option.value\n        return None",
    "docstring": "Select handler for authors."
  },
  {
    "code": "def _validate(self,val):\n        if isinstance(self.class_, tuple):\n            class_name = ('(%s)' % ', '.join(cl.__name__ for cl in self.class_))\n        else:\n            class_name = self.class_.__name__\n        if self.is_instance:\n            if not (isinstance(val,self.class_)) and not (val is None and self.allow_None):\n                raise ValueError(\n                    \"Parameter '%s' value must be an instance of %s, not '%s'\" %\n                    (self.name, class_name, val))\n        else:\n            if not (val is None and self.allow_None) and not (issubclass(val,self.class_)):\n                raise ValueError(\n                    \"Parameter '%s' must be a subclass of %s, not '%s'\" %\n                    (val.__name__, class_name, val.__class__.__name__))",
    "docstring": "val must be None, an instance of self.class_ if self.is_instance=True or a subclass of self_class if self.is_instance=False"
  },
  {
    "code": "def studio(self):\n        if self._studio is None:\n            from twilio.rest.studio import Studio\n            self._studio = Studio(self)\n        return self._studio",
    "docstring": "Access the Studio Twilio Domain\n\n        :returns: Studio Twilio Domain\n        :rtype: twilio.rest.studio.Studio"
  },
  {
    "code": "def pause(env, identifier):\n    vsi = SoftLayer.VSManager(env.client)\n    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')\n    if not (env.skip_confirmations or\n            formatting.confirm('This will pause the VS with id %s. Continue?'\n                               % vs_id)):\n        raise exceptions.CLIAbort('Aborted.')\n    env.client['Virtual_Guest'].pause(id=vs_id)",
    "docstring": "Pauses an active virtual server."
  },
  {
    "code": "def order_duplicate_volume(self, origin_volume_id, origin_snapshot_id=None,\n                               duplicate_size=None, duplicate_iops=None,\n                               duplicate_tier_level=None,\n                               duplicate_snapshot_size=None,\n                               hourly_billing_flag=False):\n        file_mask = 'id,billingItem[location,hourlyFlag],snapshotCapacityGb,'\\\n                    'storageType[keyName],capacityGb,originalVolumeSize,'\\\n                    'provisionedIops,storageTierLevel,'\\\n                    'staasVersion,hasEncryptionAtRest'\n        origin_volume = self.get_file_volume_details(origin_volume_id,\n                                                     mask=file_mask)\n        order = storage_utils.prepare_duplicate_order_object(\n            self, origin_volume, duplicate_iops, duplicate_tier_level,\n            duplicate_size, duplicate_snapshot_size, 'file',\n            hourly_billing_flag\n        )\n        if origin_snapshot_id is not None:\n            order['duplicateOriginSnapshotId'] = origin_snapshot_id\n        return self.client.call('Product_Order', 'placeOrder', order)",
    "docstring": "Places an order for a duplicate file volume.\n\n        :param origin_volume_id: The ID of the origin volume to be duplicated\n        :param origin_snapshot_id: Origin snapshot ID to use for duplication\n        :param duplicate_size: Size/capacity for the duplicate volume\n        :param duplicate_iops: The IOPS per GB for the duplicate volume\n        :param duplicate_tier_level: Tier level for the duplicate volume\n        :param duplicate_snapshot_size: Snapshot space size for the duplicate\n        :param hourly_billing_flag: Billing type, monthly (False)\n            or hourly (True), default to monthly.\n        :return: Returns a SoftLayer_Container_Product_Order_Receipt"
  },
  {
    "code": "def type_name(cls):\n        if cls.__type_name__:\n            type_name = cls.__type_name__.lower()\n        else:\n            camelcase = re.compile(r'([a-z])([A-Z])')\n            ccase = lambda s: camelcase.sub(lambda v: '{0}_{1}'.format(v.group(1), v.group(2)), s)\n            type_name = ccase(cls.__name__)\n            type_name = type_name[-48:]\n            type_name = type_name.lower()\n            type_name = re.sub(r'^_+', '', type_name)\n            cls.__type_name__ = type_name\n        return type_name",
    "docstring": "Returns the type name if it's been defined\n        otherwise, it creates it from the class name"
  },
  {
    "code": "def _return_wrapper(fits, return_all, start, trace):\n    if not is_iterable(fits):\n        fits = [fits]\n    if trace:\n        print('Total fit time: %.3f seconds' % (time.time() - start))\n    if not return_all:\n        return fits[0]\n    return fits",
    "docstring": "If the user wants to get all of the models back, this will\n    return a list of the ARIMA models, otherwise it will just return\n    the model. If this is called from the end of the function, ``fits``\n    will already be a list.\n\n    We *know* that if a function call makes it here, ``fits`` is NOT None\n    or it would have thrown an exception in :func:`_post_ppc_arima`.\n\n    Parameters\n    ----------\n    fits : iterable or ARIMA\n        The ARIMA(s)\n\n    return_all : bool\n        Whether to return all."
  },
  {
    "code": "def indices(self, data):\n        duration = self.data_duration(data)\n        for start in range(0, duration - self.duration, self.stride):\n            yield start",
    "docstring": "Generate patch start indices\n\n        Parameters\n        ----------\n        data : dict of np.ndarray\n            As produced by pumpp.transform\n\n        Yields\n        ------\n        start : int >= 0\n            The start index of a sample patch"
  },
  {
    "code": "def console_get_char(con: tcod.console.Console, x: int, y: int) -> int:\n    return lib.TCOD_console_get_char(_console(con), x, y)",
    "docstring": "Return the character at the x,y of this console.\n\n    .. deprecated:: 8.4\n        Array access performs significantly faster than using this function.\n        See :any:`Console.ch`."
  },
  {
    "code": "def iter_files(self, number=-1, etag=None):\n        url = self._build_url('files', base_url=self._api)\n        return self._iter(int(number), url, PullFile, etag=etag)",
    "docstring": "Iterate over the files associated with this pull request.\n\n        :param int number: (optional), number of files to return. Default:\n            -1 returns all available files.\n        :param str etag: (optional), ETag from a previous request to the same\n            endpoint\n        :returns: generator of :class:`PullFile <PullFile>`\\ s"
  },
  {
    "code": "def get_user_avatar(self, userid):\n        response, status_code = self.__pod__.User.get_v1_admin_user_uid_avatar(\n            sessionToken=self.__session,\n            uid=userid\n        ).result()\n        self.logger.debug('%s: %s' % (status_code, response))\n        return status_code, response",
    "docstring": "get avatar by user id"
  },
  {
    "code": "def undo(self, i=-1):\n        _history_enabled = self.history_enabled\n        param = self.get_history(i)\n        self.disable_history()\n        param.undo()\n        self.remove_parameter(uniqueid=param.uniqueid)\n        if _history_enabled:\n            self.enable_history()",
    "docstring": "Undo an item in the history logs\n\n        :parameter int i: integer for indexing (can be positive or\n            negative).  Defaults to -1 if not provided (the latest\n            recorded history item)\n        :raises ValueError: if no history items have been recorded"
  },
  {
    "code": "def get_parser(self, prog_name):\n        parser = argparse.ArgumentParser(description=self.get_description(),\n                                         prog=prog_name, add_help=False)\n        return parser",
    "docstring": "Override to add command options."
  },
  {
    "code": "def on_step_end(self, **kwargs:Any)->None:\n        \"Update the params from master to model and zero grad.\"\n        self.learn.model.zero_grad()\n        master2model(self.model_params, self.master_params, self.flat_master)",
    "docstring": "Update the params from master to model and zero grad."
  },
  {
    "code": "def get_config(section, option, allow_empty_option=True, default=\"\"):\n    try:\n        value = config.get(section, option)\n        if value is None or len(value) == 0:\n            if allow_empty_option:\n                return \"\"\n            else:\n                return default\n        else:\n            return value\n    except ConfigParser.NoSectionError:\n        return default",
    "docstring": "Get data from configs"
  },
  {
    "code": "def onEdge(self, canvas):\n        sides = []\n        if int(self.position[0]) <= 0:\n            sides.append(1)\n        if (int(self.position[0]) + self.image.width) >= canvas.width:\n            sides.append(3)\n        if int(self.position[1]) <= 0:\n            sides.append(2)\n        if (int(self.position[1]) + self.image.height) >= canvas.height:\n            sides.append(0)\n        return sides",
    "docstring": "Returns a list of the sides of the sprite\n                which are touching the edge of the canvas.\n\n            0 = Bottom\n            1 = Left\n            2 = Top\n            3 = Right"
  },
  {
    "code": "def get_streams(self):\n        self._write_lock.acquire()\n        try:\n            return itervalues(self._stream_by_id)\n        finally:\n            self._write_lock.release()",
    "docstring": "Return a snapshot of all streams in existence at time of call."
  },
  {
    "code": "def finalize(self):\n        self.pause_session_logging()\n        self._disable_logging()\n        self._msg_callback = None\n        self._error_msg_callback = None\n        self._warning_msg_callback = None\n        self._info_msg_callback = None",
    "docstring": "Clean up the object.\n\n        After calling this method the object can't be used anymore.\n        This will be reworked when changing the logging model."
  },
  {
    "code": "def get_next_start_id(self):\n        link = self.rws_connection.last_result.links.get(\"next\", None)\n        if link:\n            link = link['url']\n            p = urlparse(link)\n            start_id = int(parse_qs(p.query)['startid'][0])\n            return start_id\n        return None",
    "docstring": "If link for next result set has been passed, extract it and get the next set start id"
  },
  {
    "code": "def get_current_target(module, module_parameter=None, action_parameter=None):\n    result = exec_action(module, 'show', module_parameter=module_parameter, action_parameter=action_parameter)[0]\n    if not result:\n        return None\n    if result == '(unset)':\n        return None\n    return result",
    "docstring": "Get the currently selected target for the given module.\n\n    module\n        name of the module to be queried for its current target\n\n    module_parameter\n        additional params passed to the defined module\n\n    action_parameter\n        additional params passed to the 'show' action\n\n    CLI Example (current target of system-wide ``java-vm``):\n\n    .. code-block:: bash\n\n        salt '*' eselect.get_current_target java-vm action_parameter='system'\n\n    CLI Example (current target of ``kernel`` symlink):\n\n    .. code-block:: bash\n\n        salt '*' eselect.get_current_target kernel"
  },
  {
    "code": "def get_plugins(sites=None):\n    plugins = []\n    for plugin in CMSPlugin.objects.all():\n        if plugin:\n            cl = plugin.get_plugin_class().model\n            if 'posts' in cl._meta.get_all_field_names():\n                instance = plugin.get_plugin_instance()[0]\n                plugins.append(instance)\n    if sites and len(sites) > 0:\n        onsite = []\n        for plugin in plugins:\n            try:\n                if plugin.page.site in sites:\n                    onsite.append(plugin)\n            except AttributeError:\n                continue\n        return onsite\n    return plugins",
    "docstring": "Returns all GoScale plugins\n\n    It ignored all other django-cms plugins"
  },
  {
    "code": "def ensure_repo_exists(self):\n        if not os.path.isdir(self.cwd):\n            os.makedirs(self.cwd)\n        if not os.path.isdir(os.path.join(self.cwd, \".git\")):\n            self.git.init()\n            self.git.config(\"user.email\", \"you@example.com\")\n            self.git.config(\"user.name\", \"Your Name\")",
    "docstring": "Create git repo if one does not exist yet"
  },
  {
    "code": "def is_link_text_present(self, link_text):\n        soup = self.get_beautiful_soup()\n        html_links = soup.find_all('a')\n        for html_link in html_links:\n            if html_link.text.strip() == link_text.strip():\n                return True\n        return False",
    "docstring": "Returns True if the link text appears in the HTML of the page.\n            The element doesn't need to be visible,\n            such as elements hidden inside a dropdown selection."
  },
  {
    "code": "def json_as_html(self):\n        from cspreports import utils\n        formatted_json = utils.format_report(self.json)\n        return mark_safe(\"<pre>\\n%s</pre>\" % escape(formatted_json))",
    "docstring": "Print out self.json in a nice way."
  },
  {
    "code": "def find_top_level_directory(start_directory):\n    top_level = start_directory\n    while os.path.isfile(os.path.join(top_level, '__init__.py')):\n        top_level = os.path.dirname(top_level)\n        if top_level == os.path.dirname(top_level):\n            raise ValueError(\"Can't find top level directory\")\n    return os.path.abspath(top_level)",
    "docstring": "Finds the top-level directory of a project given a start directory\n    inside the project.\n\n    Parameters\n    ----------\n    start_directory : str\n        The directory in which test discovery will start."
  },
  {
    "code": "def clone_source_dir(source_dir, dest_dir):\n    if os.path.isdir(dest_dir):\n        print('removing', dest_dir)\n        shutil.rmtree(dest_dir)\n    shutil.copytree(source_dir, dest_dir)",
    "docstring": "Copies the source Protobuf files into a build directory.\n\n    Args:\n        source_dir (str): source directory of the Protobuf files\n        dest_dir (str): destination directory of the Protobuf files"
  },
  {
    "code": "def split_given_spans(self, spans, sep=' '):\n        N = len(spans)\n        results = [{TEXT: text} for text in self.texts_from_spans(spans, sep=sep)]\n        for elem in self:\n            if isinstance(self[elem], list):\n                splits = divide_by_spans(self[elem], spans, translate=True, sep=sep)\n                for idx in range(N):\n                    results[idx][elem] = splits[idx]\n        return [Text(res) for res in results]",
    "docstring": "Split the text into several pieces.\n\n        Resulting texts have all the layers that are present in the text instance that is splitted.\n        The elements are copied to resulting pieces that are covered by their spans.\n        However, this can result in empty layers if no element of a splitted layer fits into\n        a span of a particular output piece.\n\n        The positions of layer elements that are copied are translated according to the container span,\n        so they are consistent with returned text lengths.\n\n        Parameters\n        ----------\n\n        spans: list of spans.\n            The positions determining the regions that will end up as individual pieces.\n            Spans themselves can be lists of spans, which denote multilayer-style text regions.\n        sep: str\n            The separator that is used to join together text pieces of multilayer spans.\n\n        Returns\n        -------\n        list of Text\n            One instance of text per span."
  },
  {
    "code": "def set_window_iconify_callback(window, cbfun):\n    window_addr = ctypes.cast(ctypes.pointer(window),\n                              ctypes.POINTER(ctypes.c_long)).contents.value\n    if window_addr in _window_iconify_callback_repository:\n        previous_callback = _window_iconify_callback_repository[window_addr]\n    else:\n        previous_callback = None\n    if cbfun is None:\n        cbfun = 0\n    c_cbfun = _GLFWwindowiconifyfun(cbfun)\n    _window_iconify_callback_repository[window_addr] = (cbfun, c_cbfun)\n    cbfun = c_cbfun\n    _glfw.glfwSetWindowIconifyCallback(window, cbfun)\n    if previous_callback is not None and previous_callback[0] != 0:\n        return previous_callback[0]",
    "docstring": "Sets the iconify callback for the specified window.\n\n    Wrapper for:\n        GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, GLFWwindowiconifyfun cbfun);"
  },
  {
    "code": "def init(lib_name=None, bin_path=None, sdk_path=None):\n  if sum(bool(x) for x in [lib_name, bin_path, sdk_path]) > 1:\n    raise ValueError('expected zero or one arguments')\n  if sdk_path:\n    if sys.platform.startswith('win32'):\n      bin_path = os.path.join(sdk_path, 'bin')\n    elif sys.platform.startswith('darwin'):\n      bin_path = os.path.join(sdk_path, 'myo.framework')\n    else:\n      raise RuntimeError('unsupported platform: {!r}'.format(sys.platform))\n  if bin_path:\n    lib_name = os.path.join(bin_path, _getdlname())\n  if not lib_name:\n    lib_name = _getdlname()\n  global libmyo\n  libmyo = ffi.dlopen(lib_name)",
    "docstring": "Initialize the Myo SDK by loading the libmyo shared library. With no\n  arguments, libmyo must be on your `PATH` or `LD_LIBRARY_PATH`.\n\n  You can specify the exact path to libmyo with *lib_name*. Alternatively,\n  you can specify the binaries directory that contains libmyo with *bin_path*.\n  Finally, you can also pass the path to the Myo SDK root directory and it\n  will figure out the path to libmyo by itself."
  },
  {
    "code": "def main(arguments):\n    global verbose\n    global veryVerbose\n    global iteration_num\n    global single_score\n    global pr_flag\n    global match_triple_dict\n    iteration_num = arguments.r + 1\n    if arguments.ms:\n        single_score = False\n    if arguments.v:\n        verbose = True\n    if arguments.vv:\n        veryVerbose = True\n    if arguments.pr:\n        pr_flag = True\n    floatdisplay = \"%%.%df\" % arguments.significant\n    for (precision, recall, best_f_score) in score_amr_pairs(args.f[0], args.f[1],\n                                                             justinstance=arguments.justinstance,\n                                                             justattribute=arguments.justattribute,\n                                                             justrelation=arguments.justrelation):\n        if pr_flag:\n            print(\"Precision: \" + floatdisplay % precision)\n            print(\"Recall: \" + floatdisplay % recall)\n        print(\"F-score: \" + floatdisplay % best_f_score)\n    args.f[0].close()\n    args.f[1].close()",
    "docstring": "Main function of smatch score calculation"
  },
  {
    "code": "def get_template_path(filename):\n    if os.path.isfile(filename):\n        return os.path.abspath(filename)\n    for i in sys.path:\n        if os.path.isfile(os.path.join(i, filename)):\n            return os.path.abspath(os.path.join(i, filename))\n    return None",
    "docstring": "Find raw template in working directory or in sys.path.\n\n    template_path from config may refer to templates colocated with the Stacker\n    config, or files in remote package_sources. Here, we emulate python module\n    loading to find the path to the template.\n\n    Args:\n        filename (str): Template filename.\n\n    Returns:\n        Optional[str]: Path to file, or None if no file found"
  },
  {
    "code": "def _close(self, name, suppress_logging):\n        try:\n            pool_names = list(self.pools)\n            if name in pool_names:\n                self.pools[name].close()\n                del self.pools[name]\n        except Exception as e:\n            self.logger.error('Exception on closing Flopsy Pool for {0}: {1}'.format(name, e),\n                              exc_info=not suppress_logging)",
    "docstring": "closes one particular pool and all its amqp amqp connections"
  },
  {
    "code": "def from_urdf_file(cls, urdf_file, base_elements=None, last_link_vector=None, base_element_type=\"link\", active_links_mask=None, name=\"chain\"):\n        if base_elements is None:\n            base_elements = [\"base_link\"]\n        links = URDF_utils.get_urdf_parameters(urdf_file, base_elements=base_elements, last_link_vector=last_link_vector, base_element_type=base_element_type)\n        return cls([link_lib.OriginLink()] + links, active_links_mask=active_links_mask, name=name)",
    "docstring": "Creates a chain from an URDF file\n\n        Parameters\n        ----------\n        urdf_file: str\n            The path of the URDF file\n        base_elements: list of strings\n            List of the links beginning the chain\n        last_link_vector: numpy.array\n            Optional : The translation vector of the tip.\n        name: str\n            The name of the Chain\n        base_element_type: str\n        active_links_mask: list[bool]"
  },
  {
    "code": "def resolve_randconfig(self, args):\n        ttype = args.get('ttype')\n        if is_null(ttype):\n            sys.stderr.write('Target type must be specified')\n            return None\n        name_keys = dict(target_type=ttype,\n                         fullpath=True)\n        randconfig = self.randconfig(**name_keys)\n        rand_override = args.get('rand_config')\n        if is_not_null(rand_override):\n            randconfig = rand_override\n        return randconfig",
    "docstring": "Get the name of the specturm file based on the job arguments"
  },
  {
    "code": "def _openapi_json(self):\n        from pprint import pprint\n        pprint(self.to_dict())\n        return current_app.response_class(json.dumps(self.to_dict(), indent=4),\n                                          mimetype='application/json')",
    "docstring": "Serve JSON spec file"
  },
  {
    "code": "def get_morph_files(directory):\n    lsdir = (os.path.join(directory, m) for m in os.listdir(directory))\n    return list(filter(_is_morphology_file, lsdir))",
    "docstring": "Get a list of all morphology files in a directory\n\n    Returns:\n        list with all files with extensions '.swc' , 'h5' or '.asc' (case insensitive)"
  },
  {
    "code": "def add_known_host(host, application_name, user=None):\n    cmd = ['ssh-keyscan', '-H', '-t', 'rsa', host]\n    try:\n        remote_key = subprocess.check_output(cmd).strip()\n    except Exception as e:\n        log('Could not obtain SSH host key from %s' % host, level=ERROR)\n        raise e\n    current_key = ssh_known_host_key(host, application_name, user)\n    if current_key and remote_key:\n        if is_same_key(remote_key, current_key):\n            log('Known host key for compute host %s up to date.' % host)\n            return\n        else:\n            remove_known_host(host, application_name, user)\n    log('Adding SSH host key to known hosts for compute node at %s.' % host)\n    with open(known_hosts(application_name, user), 'a') as out:\n        out.write(\"{}\\n\".format(remote_key))",
    "docstring": "Add the given host key to the known hosts file.\n\n    :param host: host name\n    :type host: str\n    :param application_name: Name of application eg nova-compute-something\n    :type application_name: str\n    :param user: The user that the ssh asserts are for.\n    :type user: str"
  },
  {
    "code": "def green(cls):\n        \"Make the text foreground color green.\"\n        wAttributes = cls._get_text_attributes()\n        wAttributes &= ~win32.FOREGROUND_MASK\n        wAttributes |=  win32.FOREGROUND_GREEN\n        cls._set_text_attributes(wAttributes)",
    "docstring": "Make the text foreground color green."
  },
  {
    "code": "def guest_resize_cpus(self, userid, cpu_cnt):\n        action = \"resize guest '%s' to have '%i' virtual cpus\" % (userid,\n                                                                  cpu_cnt)\n        LOG.info(\"Begin to %s\" % action)\n        with zvmutils.log_and_reraise_sdkbase_error(action):\n            self._vmops.resize_cpus(userid, cpu_cnt)\n        LOG.info(\"%s successfully.\" % action)",
    "docstring": "Resize virtual cpus of guests.\n\n        :param userid: (str) the userid of the guest to be resized\n        :param cpu_cnt: (int) The number of virtual cpus that the guest should\n               have defined in user directory after resize. The value should\n               be an integer between 1 and 64."
  },
  {
    "code": "def get_error_info(self) -> Tuple[Optional[str], Optional[str]]:\n        etag = self.find1(\"error-app-tag\")\n        emsg = self.find1(\"error-message\")\n        return (etag.argument if etag else None, emsg.argument if emsg else None)",
    "docstring": "Return receiver's error tag and error message if present."
  },
  {
    "code": "def auto_param_specs(self):\n        for spec in self.study_class.parameter_specs():\n            if spec.name not in self._name_map:\n                yield spec",
    "docstring": "Parameter pecs in the sub-study class that are not explicitly provided\n        in the name map"
  },
  {
    "code": "def handle_request(self):\n        timeout = self.socket.gettimeout()\n        if timeout is None:\n            timeout = self.timeout\n        elif self.timeout is not None:\n            timeout = min(timeout, self.timeout)\n        fd_sets = select.select([self], [], [], timeout)\n        if not fd_sets[0]:\n            self.handle_timeout()\n            return\n        self._handle_request_noblock()",
    "docstring": "Handle one request, possibly blocking.\n\n        Respects self.timeout."
  },
  {
    "code": "def create_prototype(sample_dimension,\n                     parameter_kind_base='user',\n                     parameter_kind_options=[],\n                     state_stay_probabilities=[0.6, 0.6, 0.7]):\n    parameter_kind = create_parameter_kind(base=parameter_kind_base,\n                                           options=parameter_kind_options)\n    transition = create_transition(state_stay_probabilities)\n    state_count = len(state_stay_probabilities)\n    states = []\n    for i in range(state_count):\n        state = create_gmm(np.zeros(sample_dimension),\n                           np.ones(sample_dimension),\n                           weights=None,\n                           gconsts=None)\n        states.append(state)\n    hmms = [create_hmm(states, transition)]\n    macros = [create_options(vector_size=sample_dimension,\n                             parameter_kind=parameter_kind)]\n    model = create_model(macros, hmms)\n    return model",
    "docstring": "Create a prototype HTK model file using a feature file."
  },
  {
    "code": "def has_value(key):\n    return salt.utils.data.traverse_dict_and_list(\n        __grains__,\n        key,\n        KeyError) is not KeyError",
    "docstring": "Determine whether a key exists in the grains dictionary.\n\n    Given a grains dictionary that contains the following structure::\n\n        {'pkg': {'apache': 'httpd'}}\n\n    One would determine if the apache key in the pkg dict exists by::\n\n        pkg:apache\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' grains.has_value pkg:apache"
  },
  {
    "code": "def merkleroot(merkletree: 'MerkleTreeState') -> Locksroot:\n    assert merkletree.layers, 'the merkle tree layers are empty'\n    assert merkletree.layers[MERKLEROOT], 'the root layer is empty'\n    return Locksroot(merkletree.layers[MERKLEROOT][0])",
    "docstring": "Return the root element of the merkle tree."
  },
  {
    "code": "def set_child_value(\n            self, sensor_id, child_id, value_type, value, **kwargs):\n        if not self.is_sensor(sensor_id, child_id):\n            return\n        if self.sensors[sensor_id].new_state:\n            self.sensors[sensor_id].set_child_value(\n                child_id, value_type, value,\n                children=self.sensors[sensor_id].new_state)\n        else:\n            self.add_job(partial(\n                self.sensors[sensor_id].set_child_value, child_id, value_type,\n                value, **kwargs))",
    "docstring": "Add a command to set a sensor value, to the queue.\n\n        A queued command will be sent to the sensor when the gateway\n        thread has sent all previously queued commands.\n\n        If the sensor attribute new_state returns True, the command will be\n        buffered in a queue on the sensor, and only the internal sensor state\n        will be updated. When a smartsleep message is received, the internal\n        state will be pushed to the sensor, via _handle_smartsleep method."
  },
  {
    "code": "def peid_features(self, pefile_handle):\n        peid_match = self.peid_sigs.match(pefile_handle)\n        return peid_match if peid_match else []",
    "docstring": "Get features from PEid signature database"
  },
  {
    "code": "def kick_chat_member(self, user_id):\n        return self.bot.api_call(\"kickChatMember\", chat_id=self.id, user_id=user_id)",
    "docstring": "Use this method to kick a user from a group or a supergroup.\n        The bot must be an administrator in the group for this to work.\n\n        :param int user_id: Unique identifier of the target user"
  },
  {
    "code": "def match_country_name_to_its_code(country_name, city=''):\n    if country_name:\n        country_name = country_name.upper().replace('.', '').strip()\n        if country_to_iso_code.get(country_name):\n            return country_to_iso_code.get(country_name)\n        elif country_name == 'KOREA':\n            if city.upper() in south_korean_cities:\n                return 'KR'\n        else:\n            for c_code, spellings in countries_alternative_spellings.items():\n                for spelling in spellings:\n                    if country_name == spelling:\n                        return c_code\n    return None",
    "docstring": "Try to match country name with its code.\n\n    Name of the city helps when country_name is \"Korea\"."
  },
  {
    "code": "def list_items(self, url, container=None, last_obj=None, spr=False):\n        headers, container_uri = self._return_base_data(\n            url=url,\n            container=container\n        )\n        if container:\n            resp = self._header_getter(uri=container_uri, headers=headers)\n            if resp.status_code == 404:\n                LOG.info('Container [ %s ] not found.', container)\n                return [resp]\n        return self._list_getter(\n            uri=container_uri,\n            headers=headers,\n            last_obj=last_obj,\n            spr=spr\n        )",
    "docstring": "Builds a long list of objects found in a container.\n\n        NOTE: This could be millions of Objects.\n\n        :param url:\n        :param container:\n        :param last_obj:\n        :param spr: \"single page return\" Limit the returned data to one page\n        :type spr: ``bol``\n        :return None | list:"
  },
  {
    "code": "def set_as_object(self, value):\n        self.clear()\n        map = MapConverter.to_map(value)\n        self.append(map)",
    "docstring": "Sets a new value to map element\n\n        :param value: a new element or map value."
  },
  {
    "code": "def set(self, key, value):\n        return uwsgi.cache_set(key, value, self.timeout, self.name)",
    "docstring": "Sets the specified key value.\n\n        :param str|unicode key:\n\n        :param int|str|unicode value:\n\n        :rtype: bool"
  },
  {
    "code": "def format_configdictfield_nodes(field_name, field, field_id, state, lineno):\n    value_item = nodes.definition_list_item()\n    value_item += nodes.term(text=\"Value type\")\n    value_item_def = nodes.definition()\n    value_item_def_para = nodes.paragraph()\n    name = '.'.join((field.itemtype.__module__, field.itemtype.__name__))\n    value_item_def_para += pending_config_xref(rawsource=name)\n    value_item_def += value_item_def_para\n    value_item += value_item_def\n    dl = nodes.definition_list()\n    dl += create_default_item_node(field, state)\n    dl += create_field_type_item_node(field, state)\n    dl += create_keytype_item_node(field, state)\n    dl += value_item\n    desc_node = create_description_node(field, state)\n    title = create_title_node(field_name, field, field_id, state, lineno)\n    return [title, dl, desc_node]",
    "docstring": "Create a section node that documents a ConfigDictField config field.\n\n    Parameters\n    ----------\n    field_name : `str`\n        Name of the configuration field (the attribute name of on the config\n        class).\n    field : ``lsst.pex.config.ConfigDictField``\n        A configuration field.\n    field_id : `str`\n        Unique identifier for this field. This is used as the id and name of\n        the section node. with a -section suffix\n    state : ``docutils.statemachine.State``\n        Usually the directive's ``state`` attribute.\n    lineno (`int`)\n        Usually the directive's ``lineno`` attribute.\n\n    Returns\n    -------\n    ``docutils.nodes.section``\n        Section containing documentation nodes for the ConfigDictField."
  },
  {
    "code": "def get_filenames(dirname, full_path=False, match_regex=None, extension=None):\n    if not os.path.exists(dirname):\n        raise OSError('directory \"{}\" does not exist'.format(dirname))\n    match_regex = re.compile(match_regex) if match_regex else None\n    for filename in sorted(os.listdir(dirname)):\n        if extension and not os.path.splitext(filename)[-1] == extension:\n            continue\n        if match_regex and not match_regex.search(filename):\n            continue\n        if full_path is True:\n            yield os.path.join(dirname, filename)\n        else:\n            yield filename",
    "docstring": "Get all filenames under ``dirname`` that match ``match_regex`` or have file\n    extension equal to ``extension``, optionally prepending the full path.\n\n    Args:\n        dirname (str): /path/to/dir on disk where files to read are saved\n        full_path (bool): if False, return filenames without path; if True,\n            return filenames with path, as ``os.path.join(dirname, fname)``\n        match_regex (str): include files whose names match this regex pattern\n        extension (str): if files only of a certain type are wanted,\n            specify the file extension (e.g. \".txt\")\n\n    Yields:\n        str: next matching filename"
  },
  {
    "code": "def solution_to_array(solution, events, slots):\n    array = np.zeros((len(events), len(slots)), dtype=np.int8)\n    for item in solution:\n        array[item[0], item[1]] = 1\n    return array",
    "docstring": "Convert a schedule from solution to array form\n\n    Parameters\n    ----------\n    solution : list or tuple\n        of tuples of event index and slot index for each scheduled item\n    events : list or tuple\n        of :py:class:`resources.Event` instances\n    slots : list or tuple\n        of :py:class:`resources.Slot` instances\n\n    Returns\n    -------\n    np.array\n        An E by S array (X) where E is the number of events and S the\n        number of slots. Xij is 1 if event i is scheduled in slot j and\n        zero otherwise\n\n    Example\n    -------\n    For For 3 events, 7 slots and the solution::\n\n        [(0, 1), (1, 4), (2, 5)]\n\n    The resulting array would be::\n\n        [[0, 1, 0, 0, 0, 0, 0],\n         [0, 0, 0, 0, 1, 0, 0],\n         [0, 0, 0, 0, 0, 1, 0]]"
  },
  {
    "code": "def is_group(self):\n        if self._broadcast is None and self.chat:\n            self._broadcast = getattr(self.chat, 'broadcast', None)\n        return (\n            isinstance(self._chat_peer, (types.PeerChat, types.PeerChannel))\n            and not self._broadcast\n        )",
    "docstring": "True if the message was sent on a group or megagroup."
  },
  {
    "code": "def omit(keys, from_, strict=False):\n    ensure_iterable(keys)\n    ensure_mapping(from_)\n    if strict:\n        remaining_keys = set(iterkeys(from_))\n        remove_subset(remaining_keys, keys)\n    else:\n        remaining_keys = set(iterkeys(from_)) - set(keys)\n    return from_.__class__((k, from_[k]) for k in remaining_keys)",
    "docstring": "Returns a subset of given dictionary, omitting specified keys.\n\n    :param keys: Iterable of keys to exclude\n    :param strict: Whether ``keys`` are required to exist in the dictionary\n\n    :return: Dictionary filtered by omitting ``keys``\n\n    :raise KeyError: If ``strict`` is True and one of ``keys`` is not found\n                     in the dictionary\n\n    .. versionadded:: 0.0.2"
  },
  {
    "code": "def _debug_line(linenum: int, line: str, extramsg: str = \"\") -> None:\n        log.critical(\"{}Line {}: {!r}\", extramsg, linenum, line)",
    "docstring": "Writes a debugging report on a line."
  },
  {
    "code": "def adjust_ether (self, ip=None, ether=None):\n    if ip != None and ip.haslayer(IP) and ether != None and ether.haslayer(Ether):\n      iplong = atol(ip.dst)\n      ether.dst = \"01:00:5e:%02x:%02x:%02x\" % ( (iplong>>16)&0x7F, (iplong>>8)&0xFF, (iplong)&0xFF )\n      return True\n    else:\n      return False",
    "docstring": "Called to explicitely fixup an associated Ethernet header\n\n    The function adjusts the ethernet header destination MAC address based on \n    the destination IP address."
  },
  {
    "code": "def set_itunes_author_name(self):\n        try:\n            self.itunes_author_name = self.soup.find('itunes:author').string\n        except AttributeError:\n            self.itunes_author_name = None",
    "docstring": "Parses author name from itunes tags and sets value"
  },
  {
    "code": "def sample_zip(items_list, num_samples, allow_overflow=False, per_bin=1):\n    samples_list = [[] for _ in range(num_samples)]\n    samples_iter = zip_longest(*items_list)\n    sx = 0\n    for ix, samples_ in zip(range(num_samples), samples_iter):\n        samples = filter_Nones(samples_)\n        samples_list[sx].extend(samples)\n        if (ix + 1) % per_bin == 0:\n            sx += 1\n    if allow_overflow:\n        overflow_samples = flatten([filter_Nones(samples_) for samples_ in samples_iter])\n        return samples_list, overflow_samples\n    else:\n        try:\n            samples_iter.next()\n        except StopIteration:\n            pass\n        else:\n            raise AssertionError('Overflow occured')\n        return samples_list",
    "docstring": "Helper for sampling\n\n    Given a list of lists, samples one item for each list and bins them into\n    num_samples bins. If all sublists are of equal size this is equivilent to a\n    zip, but otherewise consecutive bins will have monotonically less\n    elemements\n\n    # Doctest doesn't work with assertionerror\n    #util_list.sample_zip(items_list, 2)\n    #...\n    #AssertionError: Overflow occured\n\n    Args:\n        items_list (list):\n        num_samples (?):\n        allow_overflow (bool):\n        per_bin (int):\n\n    Returns:\n        tuple : (samples_list, overflow_samples)\n\n    Examples:\n        >>> # DISABLE_DOCTEST\n        >>> from utool import util_list\n        >>> items_list = [[1, 2, 3, 4, 0], [5, 6, 7], [], [8, 9], [10]]\n        >>> util_list.sample_zip(items_list, 5)\n        ...\n        [[1, 5, 8, 10], [2, 6, 9], [3, 7], [4], [0]]\n        >>> util_list.sample_zip(items_list, 2, allow_overflow=True)\n        ...\n        ([[1, 5, 8, 10], [2, 6, 9]], [3, 7, 4])\n        >>> util_list.sample_zip(items_list, 4, allow_overflow=True, per_bin=2)\n        ...\n        ([[1, 5, 8, 10, 2, 6, 9], [3, 7, 4], [], []], [0])"
  },
  {
    "code": "def cleanSystem(cls):\n        resourceRootDirPath = os.environ[cls.rootDirPathEnvName]\n        os.environ.pop(cls.rootDirPathEnvName)\n        shutil.rmtree(resourceRootDirPath)\n        for k, v in list(os.environ.items()):\n            if k.startswith(cls.resourceEnvNamePrefix):\n                os.environ.pop(k)",
    "docstring": "Removes all downloaded, localized resources"
  },
  {
    "code": "def _init_file_logger(logger, level, log_path, log_size, log_count):\n    if level not in [logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]:\n        level = logging.DEBUG\n    for h in logger.handlers:\n        if isinstance(h, logging.handlers.RotatingFileHandler):\n            if h.level == level:\n                return\n    fh = logging.handlers.RotatingFileHandler(\n        log_path, maxBytes=log_size, backupCount=log_count)\n    fh.setLevel(level)\n    fh.setFormatter(_formatter)\n    logger.addHandler(fh)",
    "docstring": "one logger only have one level RotatingFileHandler"
  },
  {
    "code": "def from_flag(cls, flag):\n        value = _get_flag_value(flag)\n        if value is None:\n            return None\n        relation_name = value['relation']\n        conversations = Conversation.load(value['conversations'])\n        return cls.from_name(relation_name, conversations)",
    "docstring": "Find relation implementation in the current charm, based on the\n        name of an active flag.\n\n        You should not use this method directly.\n        Use :func:`endpoint_from_flag` instead."
  },
  {
    "code": "def load_limits(self, config):\n        self._limits['history_size'] = 28800\n        if not hasattr(config, 'has_section'):\n            return False\n        if config.has_section('global'):\n            self._limits['history_size'] = config.get_float_value('global', 'history_size', default=28800)\n            logger.debug(\"Load configuration key: {} = {}\".format('history_size', self._limits['history_size']))\n        if config.has_section(self.plugin_name):\n            for level, _ in config.items(self.plugin_name):\n                limit = '_'.join([self.plugin_name, level])\n                try:\n                    self._limits[limit] = config.get_float_value(self.plugin_name, level)\n                except ValueError:\n                    self._limits[limit] = config.get_value(self.plugin_name, level).split(\",\")\n                logger.debug(\"Load limit: {} = {}\".format(limit, self._limits[limit]))\n        return True",
    "docstring": "Load limits from the configuration file, if it exists."
  },
  {
    "code": "def export_db(filename=None, remote=False):\n    local_machine()\n    if not filename:\n        filename = settings.DB_DUMP_FILENAME\n    if remote:\n        backup_dir = settings.FAB_SETTING('SERVER_DB_BACKUP_DIR')\n    else:\n        backup_dir = ''\n    local('pg_dump -c -Fc -O -U {0}{1} {2} -f {3}{4}'.format(\n        env.db_role, HOST, env.db_name, backup_dir, filename))",
    "docstring": "Exports the database.\n\n    Make sure that you have this in your ``~/.pgpass`` file:\n\n    localhost:5433:*:<db_role>:<password>\n\n    Also make sure that the file has ``chmod 0600 .pgpass``.\n\n    Usage::\n\n        fab export_db\n        fab export_db:filename=foobar.dump"
  },
  {
    "code": "def append_sample(self, **kwargs) -> 'Seeding':\n        data = {\n            'seed': random.randint(0, 1000000)\n        }\n        data.update(kwargs)\n        return self._append_seed(SEED_TYPE_SAMPLE, data)",
    "docstring": "Add seed induction methods.\n\n        Kwargs can have ``number_edges`` or ``number_seed_nodes``.\n\n        :returns: self for fluid API"
  },
  {
    "code": "def create(self, name):\n        if not os.path.exists(self.directory):\n            os.makedirs(self.directory)\n        filename = self.get_new_filename(name)\n        with open(os.path.join(self.directory, filename), 'w') as fp:\n            fp.write(\"def up(db): pass\\n\\n\\n\")\n            fp.write(\"def down(db): pass\\n\")\n            logger.info(filename)",
    "docstring": "Create a new empty migration."
  },
  {
    "code": "def checksum (data, start = 0, skip_word = None):\n  if len(data) % 2 != 0:\n    arr = array.array('H', data[:-1])\n  else:\n    arr = array.array('H', data)\n  if skip_word is not None:\n    for i in range(0, len(arr)):\n      if i == skip_word:\n        continue\n      start +=  arr[i]\n  else:\n    for i in range(0, len(arr)):\n      start +=  arr[i]\n  if len(data) % 2 != 0:\n    start += struct.unpack('H', data[-1:]+b'\\x00')[0]\n  start  = (start >> 16) + (start & 0xffff)\n  start += (start >> 16)\n  return ntohs(~start & 0xffff)",
    "docstring": "Calculate standard internet checksum over data starting at start'th byte\n\n  skip_word: If specified, it's the word offset of a word in data to \"skip\"\n             (as if it were zero).  The purpose is when data is received\n             data which contains a computed checksum that you are trying to\n             verify -- you want to skip that word since it was zero when\n             the checksum was initially calculated."
  },
  {
    "code": "def __get_formulas(self):\n        array = self._get_target().getFormulaArray()\n        return tuple(itertools.chain.from_iterable(array))",
    "docstring": "Gets formulas in this cell range as a tuple.\n\n        If cells contain actual formulas then the returned values start\n        with an equal sign  but all values are returned."
  },
  {
    "code": "def make_template_name(self, model_type, sourcekey):\n        format_dict = self.__dict__.copy()\n        format_dict['sourcekey'] = sourcekey\n        if model_type == 'IsoSource':\n            return self._name_factory.spectral_template(**format_dict)\n        elif model_type in ['MapCubeSource', 'SpatialMap']:\n            return self._name_factory.diffuse_template(**format_dict)\n        else:\n            raise ValueError(\"Unexpected model_type %s\" % model_type)",
    "docstring": "Make the name of a template file for particular component\n\n        Parameters\n        ----------\n\n        model_type : str\n            Type of model to use for this component\n        sourcekey : str\n            Key to identify this component\n\n        Returns filename or None if component does not require a template file"
  },
  {
    "code": "def _make_ntgrid(grid):\n    hnames = [_nospace(n) for n in grid[0][1:]]\n    vnames = [_nospace(row[0]) for row in grid[1:]]\n    vnames_s = \" \".join(vnames)\n    hnames_s = \" \".join(hnames)\n    ntcol = collections.namedtuple('ntcol', vnames_s)\n    ntrow = collections.namedtuple('ntrow', hnames_s)\n    rdict = [dict(list(zip(hnames, row[1:]))) for row in grid[1:]]\n    ntrows = [ntrow(**rdict[i]) for i, name in enumerate(vnames)]\n    ntcols = ntcol(**dict(list(zip(vnames, ntrows))))\n    return ntcols",
    "docstring": "make a named tuple grid\n\n    [[\"\",  \"a b\", \"b c\", \"c d\"],\n     [\"x y\", 1,     2,     3 ],\n     [\"y z\", 4,     5,     6 ],\n     [\"z z\", 7,     8,     9 ],]\n    will return\n    ntcol(x_y=ntrow(a_b=1, b_c=2, c_d=3),\n          y_z=ntrow(a_b=4, b_c=5, c_d=6),\n          z_z=ntrow(a_b=7, b_c=8, c_d=9))"
  },
  {
    "code": "def pole_error(ax, fit, **kwargs):\n    ell = normal_errors(fit.axes, fit.covariance_matrix)\n    lonlat = -N.array(ell)\n    n = len(lonlat)\n    codes = [Path.MOVETO]\n    codes += [Path.LINETO]*(n-1)\n    vertices = list(lonlat)\n    plot_patch(ax, vertices, codes, **kwargs)",
    "docstring": "Plot the error to the pole to a plane on a `mplstereonet`\n    axis object."
  },
  {
    "code": "def rebuild( self ):\r\n        self.markForRebuild(False)\r\n        self._textData = []\r\n        if ( self.rebuildBlocked() ):\r\n            return\r\n        scene = self.scene()\r\n        if ( not scene ):\r\n            return\r\n        if ( scene.currentMode() == scene.Mode.Month ):\r\n            self.rebuildMonth()\r\n        elif ( scene.currentMode() in (scene.Mode.Day, scene.Mode.Week) ):\r\n            self.rebuildDay()",
    "docstring": "Rebuilds the current item in the scene."
  },
  {
    "code": "def get_pid(self, name):\n        pid_file = os.path.join(self.get_work_folder(name), \"notebook.pid\")\n        return pid_file",
    "docstring": "Get PID file name for a named notebook."
  },
  {
    "code": "def size_in_days(self):\n        unit, instant, length = self\n        if unit == DAY:\n            return length\n        if unit in [MONTH, YEAR]:\n            last_day = self.start.offset(length, unit).offset(-1, DAY)\n            return (last_day.date - self.start.date).days + 1\n        raise ValueError(\"Cannot calculate number of days in {0}\".format(unit))",
    "docstring": "Return the size of the period in days.\n\n        >>> period('month', '2012-2-29', 4).size_in_days\n        28\n        >>> period('year', '2012', 1).size_in_days\n        366"
  },
  {
    "code": "def _build_datasets(*args, **kwargs):\n    datasets = OrderedDict()\n    _add_arg_datasets(datasets, args)\n    _add_kwarg_datasets(datasets, kwargs)\n    return datasets",
    "docstring": "Build the datasets into a dict, where the keys are the name of the\n    data set and the values are the data sets themselves.\n\n    :param args:\n        Tuple of unnamed data sets.\n    :type args:\n        `tuple` of varies\n    :param kwargs:\n        Dict of pre-named data sets.\n    :type kwargs:\n        `dict` of `unicode` to varies\n    :return:\n        The dataset dict.\n    :rtype:\n        `dict`"
  },
  {
    "code": "def _in_search_queryset(*, instance, index) -> bool:\n    try:\n        return instance.__class__.objects.in_search_queryset(instance.id, index=index)\n    except Exception:\n        logger.exception(\"Error checking object in_search_queryset.\")\n        return False",
    "docstring": "Wrapper around the instance manager method."
  },
  {
    "code": "def read(self):\n        p = os.path.join(self.path, self.name)\n        try:\n            with open(p) as f:\n                json_text = f.read()\n        except FileNotFoundError as e:\n            raise JSONFileError(e) from e\n        try:\n            json.loads(json_text)\n        except (json.JSONDecodeError, TypeError) as e:\n            raise JSONFileError(f\"{e} Got {p}\") from e\n        return json_text",
    "docstring": "Returns the file contents as validated JSON text."
  },
  {
    "code": "def completer_tokenize(cls, value, min_length=3):\n        tokens = list(itertools.chain(*[\n            [m for m in n.split(\"'\") if len(m) > min_length]\n            for n in value.split(' ')\n        ]))\n        return list(set([value] + tokens + [' '.join(tokens)]))",
    "docstring": "Quick and dirty tokenizer for completion suggester"
  },
  {
    "code": "def crossplat_loop_run(coro) -> Any:\n    if sys.platform == 'win32':\n        signal.signal(signal.SIGINT, signal.SIG_DFL)\n        loop = asyncio.ProactorEventLoop()\n    else:\n        loop = asyncio.new_event_loop()\n    asyncio.set_event_loop(loop)\n    with contextlib.closing(loop):\n        return loop.run_until_complete(coro)",
    "docstring": "Cross-platform method for running a subprocess-spawning coroutine."
  },
  {
    "code": "def getValue(self, name, scope=None, native=False):\n        theParamList = self._taskParsObj.getParList()\n        fullName = basicpar.makeFullName(scope, name)\n        for i in range(self.numParams):\n            par = theParamList[i]\n            entry = self.entryNo[i]\n            if par.fullName() == fullName or \\\n               (scope is None and par.name == name):\n                if native:\n                    return entry.convertToNative(entry.choice.get())\n                else:\n                    return entry.choice.get()\n        raise RuntimeError('Could not find par: \"'+fullName+'\"')",
    "docstring": "Return current par value from the GUI. This does not do any\n        validation, and it it not necessarily the same value saved in the\n        model, which is always behind the GUI setting, in time. This is NOT\n        to be used to get all the values - it would not be efficient."
  },
  {
    "code": "def directory_listing(conn: FTP, path: str) -> Tuple[List, List]:\n    entries = deque()\n    conn.dir(path, entries.append)\n    entries = map(parse_line, entries)\n    grouped_entries = defaultdict(list)\n    for key, value in entries:\n        grouped_entries[key].append(value)\n    directories = grouped_entries[ListingType.directory]\n    files = grouped_entries[ListingType.file]\n    return directories, files",
    "docstring": "Return the directories and files for single FTP listing."
  },
  {
    "code": "def call_async(self, func: Callable, *args, **kwargs):\n        return asyncio_extras.call_async(self.loop, func, *args, **kwargs)",
    "docstring": "Call the given callable in the event loop thread.\n\n        This method lets you call asynchronous code from a worker thread.\n        Do not use it from within the event loop thread.\n\n        If the callable returns an awaitable, it is resolved before returning to the caller.\n\n        :param func: a regular function or a coroutine function\n        :param args: positional arguments to call the callable with\n        :param kwargs: keyword arguments to call the callable with\n        :return: the return value of the call"
  },
  {
    "code": "def showDecidePage(request, openid_request):\n    trust_root = openid_request.trust_root\n    return_to = openid_request.return_to\n    try:\n        trust_root_valid = verifyReturnTo(trust_root, return_to) \\\n                           and \"Valid\" or \"Invalid\"\n    except DiscoveryFailure, err:\n        trust_root_valid = \"DISCOVERY_FAILED\"\n    except HTTPFetchingError, err:\n        trust_root_valid = \"Unreachable\"\n    pape_request = pape.Request.fromOpenIDRequest(openid_request)\n    return direct_to_template(\n        request,\n        'server/trust.html',\n        {'trust_root': trust_root,\n         'trust_handler_url':getViewURL(request, processTrustResult),\n         'trust_root_valid': trust_root_valid,\n         'pape_request': pape_request,\n         })",
    "docstring": "Render a page to the user so a trust decision can be made.\n\n    @type openid_request: openid.server.server.CheckIDRequest"
  },
  {
    "code": "def _parse_subject(subject):\n    ret = {}\n    nids = []\n    for nid_name, nid_num in six.iteritems(subject.nid):\n        if nid_num in nids:\n            continue\n        try:\n            val = getattr(subject, nid_name)\n            if val:\n                ret[nid_name] = val\n                nids.append(nid_num)\n        except TypeError as err:\n            log.debug(\"Missing attribute '%s'. Error: %s\", nid_name, err)\n    return ret",
    "docstring": "Returns a dict containing all values in an X509 Subject"
  },
  {
    "code": "def __parseKeyValueStore(self, data):\n        offset = 0\n        key_value_store = {}\n        while offset != len(data):\n            key = get_str(data, offset)\n            offset += len(key)+1\n            value = get_str(data, offset)\n            offset += len(value)+1\n            key_value_store[key] = value\n        return key_value_store",
    "docstring": "Returns a dictionary filled with the keys and values of the key value store"
  },
  {
    "code": "def get_cell(self, row, col):\n        return javabridge.call(\n            self.jobject, \"getCell\", \"(II)Ljava/lang/Object;\", row, col)",
    "docstring": "Returns the JB_Object at the specified location.\n\n        :param row: the 0-based index of the row\n        :type row: int\n        :param col: the 0-based index of the column\n        :type col: int\n        :return: the object in that cell\n        :rtype: JB_Object"
  },
  {
    "code": "def _install_signal_handlers(self):\n        def request_stop(signum, frame):\n            self._stop_requested = True\n            self.log.info('stop requested, waiting for task to finish')\n        signal.signal(signal.SIGINT, request_stop)\n        signal.signal(signal.SIGTERM, request_stop)",
    "docstring": "Sets up signal handlers for safely stopping the worker."
  },
  {
    "code": "def send_point_data(events, additional):\n    bodies = {}\n    for (site, content_id), count in events.items():\n        if not len(site) or not len(content_id):\n            continue\n        bodies.setdefault(site, [])\n        event, path = additional.get((site, content_id), (None, None))\n        bodies[site].append([content_id, event, path, count])\n    for site, points in bodies.items():\n        try:\n            data = [{\n                \"name\": site,\n                \"columns\": [\"content_id\", \"event\", \"path\", \"value\"],\n                \"points\": points,\n            }]\n            INFLUXDB_CLIENT.write_points(data)\n        except Exception as e:\n            LOGGER.exception(e)",
    "docstring": "creates data point payloads and sends them to influxdb"
  },
  {
    "code": "def on_assign(self, node):\n        val = self.run(node.value)\n        for tnode in node.targets:\n            self.node_assign(tnode, val)\n        return",
    "docstring": "Simple assignment."
  },
  {
    "code": "def get(_class, api, vid):\n        busses = api.vehicles(vid=vid)['vehicle']   \n        return _class.fromapi(api, api.vehicles(vid=vid)['vehicle'])",
    "docstring": "Return a Bus object for a certain vehicle ID `vid` using API\n        instance `api`."
  },
  {
    "code": "def find_txt(xml_tree, path, default=''):\n    value = ''\n    try:\n        xpath_applied = xml_tree.xpath(path)\n        if len(xpath_applied) and xpath_applied[0] is not None:\n            xpath_result = xpath_applied[0]\n            if isinstance(xpath_result, type(xml_tree)):\n                value = xpath_result.text.strip()\n            else:\n                value = xpath_result\n    except Exception:\n        value = default\n    return py23_compat.text_type(value)",
    "docstring": "Extracts the text value from an XML tree, using XPath.\n    In case of error, will return a default value.\n\n    :param xml_tree: the XML Tree object. Assumed is <type 'lxml.etree._Element'>.\n    :param path:     XPath to be applied, in order to extract the desired data.\n    :param default:  Value to be returned in case of error.\n    :return: a str value."
  },
  {
    "code": "def check_basic_auth(user, passwd):\n    auth = request.authorization\n    return auth and auth.username == user and auth.password == passwd",
    "docstring": "Checks user authentication using HTTP Basic Auth."
  },
  {
    "code": "def send(self, out, addr=_MDNS_ADDR, port=_MDNS_PORT):\n        for i in self.intf.values():\n            try:\n                return i.sendto(out.packet(), 0, (addr, port))\n            except:\n                traceback.print_exc()\n                return -1",
    "docstring": "Sends an outgoing packet."
  },
  {
    "code": "def make_op_return_tx(data, private_key,\n        blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,\n        change_address=None, format='bin'):\n    private_key_obj, from_address, inputs = analyze_private_key(private_key,\n        blockchain_client)\n    if not change_address:\n        change_address = from_address\n    outputs = make_op_return_outputs(data, inputs, change_address,\n        fee=fee, format=format)\n    unsigned_tx = serialize_transaction(inputs, outputs)\n    for i in xrange(0, len(inputs)):\n        signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex())\n        unsigned_tx = signed_tx\n    return signed_tx",
    "docstring": "Builds and signs an OP_RETURN transaction."
  },
  {
    "code": "def get_buildenv_graph(self):\n        buildenvs = set(target.buildenv for target in self.targets.values()\n                        if target.buildenv)\n        return nx.DiGraph(self.target_graph.subgraph(reduce(\n            lambda x, y: x | set(y),\n            (get_descendants(self.target_graph, buildenv)\n             for buildenv in buildenvs), buildenvs)))",
    "docstring": "Return a graph induced by buildenv nodes"
  },
  {
    "code": "def on_serial_port_change(self, serial_port):\n        if not isinstance(serial_port, ISerialPort):\n            raise TypeError(\"serial_port can only be an instance of type ISerialPort\")\n        self._call(\"onSerialPortChange\",\n                     in_p=[serial_port])",
    "docstring": "Triggered when settings of a serial port of the\n        associated virtual machine have changed.\n\n        in serial_port of type :class:`ISerialPort`\n\n        raises :class:`VBoxErrorInvalidVmState`\n            Session state prevents operation.\n        \n        raises :class:`VBoxErrorInvalidObjectState`\n            Session type prevents operation."
  },
  {
    "code": "def preferences(self, section=None):\n        if section is None:\n            return [self[section][name] for section in self for name in self[section]]\n        else:\n            return [self[section][name] for name in self[section]]",
    "docstring": "Return a list of all registered preferences\n        or a list of preferences registered for a given section\n\n        :param section: The section name under which the preference is registered\n        :type section: str.\n        :return: a list of :py:class:`prefs.BasePreference` instances"
  },
  {
    "code": "def install_hook(self, hook_name, hook_content):\n        hook_path = os.path.join(self.path, '.git/hooks', hook_name)\n        with open(hook_path, 'w') as f:\n            f.write(hook_content)\n        os.chmod(hook_path, stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE)",
    "docstring": "Install the repository hook for this repo.\n\n        Args:\n            hook_name (str)\n            hook_content (str)"
  },
  {
    "code": "def extend_variables(raw_variables, override_variables):\n    if not raw_variables:\n        override_variables_mapping = ensure_mapping_format(override_variables)\n        return override_variables_mapping\n    elif not override_variables:\n        raw_variables_mapping = ensure_mapping_format(raw_variables)\n        return raw_variables_mapping\n    else:\n        raw_variables_mapping = ensure_mapping_format(raw_variables)\n        override_variables_mapping = ensure_mapping_format(override_variables)\n        raw_variables_mapping.update(override_variables_mapping)\n        return raw_variables_mapping",
    "docstring": "extend raw_variables with override_variables.\n        override_variables will merge and override raw_variables.\n\n    Args:\n        raw_variables (list):\n        override_variables (list):\n\n    Returns:\n        dict: extended variables mapping\n\n    Examples:\n        >>> raw_variables = [{\"var1\": \"val1\"}, {\"var2\": \"val2\"}]\n        >>> override_variables = [{\"var1\": \"val111\"}, {\"var3\": \"val3\"}]\n        >>> extend_variables(raw_variables, override_variables)\n            {\n                'var1', 'val111',\n                'var2', 'val2',\n                'var3', 'val3'\n            }"
  },
  {
    "code": "def log_file(self):\n        log_file = self.get('log')\n        if not log_file:\n            log_file = '%s.log' % (self.name)\n            self.set('log', log_file)\n        return os.path.join(self.initial_dir, self.get('log'))",
    "docstring": "The path to the log file for this job."
  },
  {
    "code": "def _args2_fpath(dpath, fname, cfgstr, ext):\n    r\n    if len(ext) > 0 and ext[0] != '.':\n        raise ValueError('Please be explicit and use a dot in ext')\n    max_len = 128\n    cfgstr_hashlen = 16\n    prefix = fname\n    fname_cfgstr = consensed_cfgstr(prefix, cfgstr, max_len=max_len,\n                                    cfgstr_hashlen=cfgstr_hashlen)\n    fpath = join(dpath, fname_cfgstr + ext)\n    fpath = normpath(fpath)\n    return fpath",
    "docstring": "r\"\"\"\n    Ensures that the filename is not too long\n\n    Internal util_cache helper function\n    Windows MAX_PATH=260 characters\n    Absolute length is limited to 32,000 characters\n    Each filename component is limited to 255 characters\n\n    Args:\n        dpath (str):\n        fname (str):\n        cfgstr (str):\n        ext (str):\n\n    Returns:\n        str: fpath\n\n    CommandLine:\n        python -m utool.util_cache --test-_args2_fpath\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_cache import *  # NOQA\n        >>> from utool.util_cache import _args2_fpath\n        >>> import utool as ut\n        >>> dpath = 'F:\\\\data\\\\work\\\\PZ_MTEST\\\\_ibsdb\\\\_ibeis_cache'\n        >>> fname = 'normalizer_'\n        >>> cfgstr = u'PZ_MTEST_DSUUIDS((9)67j%dr%&bl%4oh4+)_QSUUIDS((9)67j%dr%&bl%4oh4+)zebra_plains_vsone_NN(single,K1+1,last,cks1024)_FILT(ratio<0.625;1.0,fg;1.0)_SV(0.01;2;1.57minIn=4,nRR=50,nsum,)_AGG(nsum)_FLANN(4_kdtrees)_FEATWEIGHT(ON,uselabel,rf)_FEAT(hesaff+sift_)_CHIP(sz450)'\n        >>> ext = '.cPkl'\n        >>> fpath = _args2_fpath(dpath, fname, cfgstr, ext)\n        >>> result = str(ut.ensure_unixslash(fpath))\n        >>> target = 'F:/data/work/PZ_MTEST/_ibsdb/_ibeis_cache/normalizer_xfylfboirymmcpfg.cPkl'\n        >>> ut.assert_eq(result, target)"
  },
  {
    "code": "def run_task(func):\n    def _wrapped(*a, **k):\n        loop = asyncio.get_event_loop()\n        return loop.run_until_complete(func(*a, **k))\n    return _wrapped",
    "docstring": "Decorator to wrap an async function in an event loop.\n    Use for main sync interface methods."
  },
  {
    "code": "def upgrade_juju(\n            self, dry_run=False, reset_previous_upgrade=False,\n            upload_tools=False, version=None):\n        raise NotImplementedError()",
    "docstring": "Upgrade Juju on all machines in a model.\n\n        :param bool dry_run: Don't do the actual upgrade\n        :param bool reset_previous_upgrade: Clear the previous (incomplete)\n            upgrade status\n        :param bool upload_tools: Upload local version of tools\n        :param str version: Upgrade to a specific version"
  },
  {
    "code": "def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath):\n        device = '0.0.%s' % fcp\n        target = '%s:%s:%s' % (device, target_wwpn, target_lun)\n        disk_offline = '/sbin/chzdev zfcp-lun %s -d' % target\n        host_offline = '/sbin/chzdev zfcp-host %s -d' % fcp\n        offline_dev = 'chccwdev -d %s' % fcp\n        return '\\n'.join((disk_offline,\n                          host_offline,\n                          offline_dev))",
    "docstring": "ubuntu offline zfcp."
  },
  {
    "code": "def init_datamembers(self, rec):\n        if 'synonym'      in self.optional_attrs: rec.synonym = []\n        if 'xref'         in self.optional_attrs: rec.xref = set()\n        if 'subset'       in self.optional_attrs: rec.subset = set()\n        if 'comment'      in self.optional_attrs: rec.comment = \"\"\n        if 'relationship' in self.optional_attrs:\n            rec.relationship = {}\n            rec.relationship_rev = {}",
    "docstring": "Initialize current GOTerm with data members for storing optional attributes."
  },
  {
    "code": "def DefaultExtension(schema_obj, form_obj, schemata=None):\n    if schemata is None:\n        schemata = ['systemconfig', 'profile', 'client']\n    DefaultExtends = {\n        'schema': {\n            \"properties/modules\": [\n                schema_obj\n            ]\n        },\n        'form': {\n            'modules': {\n                'items/': form_obj\n            }\n        }\n    }\n    output = {}\n    for schema in schemata:\n        output[schema] = DefaultExtends\n    return output",
    "docstring": "Create a default field"
  },
  {
    "code": "def _StartDebugger():\n  global _hub_client\n  global _breakpoints_manager\n  cdbg_native.InitializeModule(_flags)\n  _hub_client = gcp_hub_client.GcpHubClient()\n  visibility_policy = _GetVisibilityPolicy()\n  _breakpoints_manager = breakpoints_manager.BreakpointsManager(\n      _hub_client,\n      visibility_policy)\n  capture_collector.SetLogger(logging.getLogger())\n  capture_collector.CaptureCollector.pretty_printers.append(\n      appengine_pretty_printers.PrettyPrinter)\n  _hub_client.on_active_breakpoints_changed = (\n      _breakpoints_manager.SetActiveBreakpoints)\n  _hub_client.on_idle = _breakpoints_manager.CheckBreakpointsExpiration\n  _hub_client.SetupAuth(\n      _flags.get('project_id'),\n      _flags.get('project_number'),\n      _flags.get('service_account_json_file'))\n  _hub_client.InitializeDebuggeeLabels(_flags)\n  _hub_client.Start()",
    "docstring": "Configures and starts the debugger."
  },
  {
    "code": "def _render_binaries(files, written_files):\n    for source_path, target_path in files.items():\n        needdir = os.path.dirname(target_path)\n        assert needdir, \"Target should have valid parent dir\"\n        try:\n            os.makedirs(needdir)\n        except OSError as err:\n            if err.errno != errno.EEXIST:\n                raise\n        if os.path.isfile(target_path):\n            if target_path in written_files:\n                LOG.warning(\"Previous stencil has already written file %s.\",\n                            target_path)\n            else:\n                print(\"Skipping existing file %s\" % target_path)\n                LOG.info(\"Skipping existing file %s\", target_path)\n                continue\n        print(\"Writing rendered file %s\" % target_path)\n        LOG.info(\"Writing rendered file %s\", target_path)\n        shutil.copy(source_path, target_path)\n        if os.path.exists(target_path):\n            written_files.append(target_path)",
    "docstring": "Write binary contents from filetable into files.\n\n    Using filetable for the input files, and the list of files, render\n    all the templates into actual files on disk, forcing to overwrite the file\n    as appropriate, and using the given open mode for the file."
  },
  {
    "code": "def make_http_credentials(username=None, password=None):\n    credentials = ''\n    if username is None:\n        return credentials\n    if username is not None:\n        if ':' in username:\n            return credentials\n        credentials += username\n    if credentials and password is not None:\n        credentials += \":%s\" % password\n    return \"%s@\" % credentials",
    "docstring": "Build auth part for api_url."
  },
  {
    "code": "def loglik(self, theta, t=None):\n        if t is None:\n            t = self.T - 1\n        l = np.zeros(shape=theta.shape[0])\n        for s in range(t + 1):\n            l += self.logpyt(theta, s)\n        return l",
    "docstring": "log-likelihood at given parameter values. \n\n        Parameters\n        ----------\n        theta: dict-like\n            theta['par'] is a ndarray containing the N values for parameter par\n        t: int \n            time (if set to None, the full log-likelihood is returned)\n\n        Returns\n        -------\n        l: float numpy.ndarray\n            the N log-likelihood values"
  },
  {
    "code": "def openTypeHeadCreatedFallback(info):\n    if \"SOURCE_DATE_EPOCH\" in os.environ:\n        t = datetime.utcfromtimestamp(int(os.environ[\"SOURCE_DATE_EPOCH\"]))\n        return t.strftime(_date_format)\n    else:\n        return dateStringForNow()",
    "docstring": "Fallback to the environment variable SOURCE_DATE_EPOCH if set, otherwise\n    now."
  },
  {
    "code": "def get_version(tool_name, tool_command):\n        result = {}\n        for line in Bash(ShellConfig(script=tool_command, internal=True)).process():\n            if line.find(\"command not found\") >= 0:\n                VersionsCheck.LOGGER.error(\"Required tool '%s' not found (stopping pipeline)!\", tool_name)\n                sys.exit(1)\n            else:\n                version = list(re.findall(r'(\\d+(\\.\\d+)+)+', line))[0][0]\n                result = {tool_name: Version(str(version))}\n            break\n        return result",
    "docstring": "Get name and version of a tool defined by given command.\n\n        Args:\n            tool_name (str): name of the tool.\n            tool_command (str): Bash one line command to get the version of the tool.\n\n        Returns:\n            dict: tool name and version or empty when no line has been found"
  },
  {
    "code": "def no_duplicates_sections2d(sections2d, prt=None):\n    no_dups = True\n    ctr = cx.Counter()\n    for _, hdrgos in sections2d:\n        for goid in hdrgos:\n            ctr[goid] += 1\n    for goid, cnt in ctr.most_common():\n        if cnt == 1:\n            break\n        no_dups = False\n        if prt is not None:\n            prt.write(\"**SECTIONS WARNING FOUND: {N:3} {GO}\\n\".format(N=cnt, GO=goid))\n    return no_dups",
    "docstring": "Check for duplicate header GO IDs in the 2-D sections variable."
  },
  {
    "code": "def coverage():\n    \"generate coverage report and show in browser\"\n    coverage_index = path(\"build/coverage/index.html\")\n    coverage_index.remove()\n    sh(\"paver test\")\n    coverage_index.exists() and webbrowser.open(coverage_index)",
    "docstring": "generate coverage report and show in browser"
  },
  {
    "code": "def __instances(self):\n        for instance in self.__instances_cache:\n            yield instance\n        for instance in self.__instances_original:\n            self.__instances_cache.append(instance)\n            yield instance",
    "docstring": "Cache instances, allowing generators to be used and reused. \n            This fills a cache as the generator gets emptied, eventually\n            reading exclusively from the cache."
  },
  {
    "code": "def ifo(self):\n        if len(self.ifo_list) == 1:\n            return self.ifo_list[0]\n        else:\n            err = \"self.ifo_list must contain only one ifo to access the \"\n            err += \"ifo property. %s.\" %(str(self.ifo_list),)\n            raise TypeError(err)",
    "docstring": "If only one ifo in the ifo_list this will be that ifo. Otherwise an\n        error is raised."
  },
  {
    "code": "def layer_prepostprocess(previous_value,\n                         x,\n                         sequence,\n                         dropout_rate,\n                         norm_type,\n                         depth,\n                         epsilon,\n                         default_name,\n                         name=None,\n                         dropout_broadcast_dims=None,\n                         layer_collection=None):\n  with tf.variable_scope(name, default_name=default_name):\n    if sequence == \"none\":\n      return x\n    for c in sequence:\n      if c == \"a\":\n        x += previous_value\n      elif c == \"z\":\n        x = zero_add(previous_value, x)\n      elif c == \"n\":\n        x = apply_norm(\n            x, norm_type, depth, epsilon, layer_collection=layer_collection)\n      else:\n        assert c == \"d\", (\"Unknown sequence step %s\" % c)\n        x = dropout_with_broadcast_dims(\n            x, 1.0 - dropout_rate, broadcast_dims=dropout_broadcast_dims)\n    return x",
    "docstring": "Apply a sequence of functions to the input or output of a layer.\n\n  The sequence is specified as a string which may contain the following\n  characters:\n    a: add previous_value\n    n: apply normalization\n    d: apply dropout\n    z: zero add\n\n  For example, if sequence==\"dna\", then the output is\n    previous_value + normalize(dropout(x))\n\n  Args:\n    previous_value: A Tensor, to be added as a residual connection ('a')\n    x: A Tensor to be transformed.\n    sequence: a string.\n    dropout_rate: a float\n    norm_type: a string (see apply_norm())\n    depth: an integer (size of last dimension of x).\n    epsilon: a float (parameter for normalization)\n    default_name: a string\n    name: a string\n    dropout_broadcast_dims:  an optional list of integers less than 3\n      specifying in which dimensions to broadcast the dropout decisions.\n      saves memory.\n    layer_collection: A tensorflow_kfac.LayerCollection. Only used by the\n      KFAC optimizer. Default is None.\n\n  Returns:\n    a Tensor"
  },
  {
    "code": "def printSysLog(self, logString):\n        if zvmsdklog.LOGGER.getloglevel() <= logging.DEBUG:\n            if self.daemon == '':\n                self.logger.debug(self.requestId + \": \" + logString)\n            else:\n                self.daemon.logger.debug(self.requestId + \": \" + logString)\n        if self.captureLogs is True:\n            self.results['logEntries'].append(self.requestId + \": \" +\n                logString)\n        return",
    "docstring": "Log one or more lines.  Optionally, add them to logEntries list.\n\n        Input:\n           Strings to be logged."
  },
  {
    "code": "def _add(self, shard_uri, name):\n        return self.router_command(\"addShard\", (shard_uri, {\"name\": name}), is_eval=False)",
    "docstring": "execute addShard command"
  },
  {
    "code": "def get_active_tasks(self):\n        current_tasks = self.celery.control.inspect().active() or dict()\n        return [\n            task.get('id') for host in current_tasks.values() for task in host]",
    "docstring": "Return a list of UUIDs of active tasks."
  },
  {
    "code": "def build_or_reuse_placeholder(tensor_spec):\n    g = tfv1.get_default_graph()\n    name = tensor_spec.name\n    try:\n        tensor = g.get_tensor_by_name(name + ':0')\n        assert \"Placeholder\" in tensor.op.type, \"Tensor {} exists but is not a placeholder!\".format(name)\n        assert tensor_spec.is_compatible_with(tensor), \\\n            \"Tensor {} exists but is not compatible with the signature!\".format(tensor)\n        return tensor\n    except KeyError:\n        with tfv1.name_scope(None):\n            ret = tfv1.placeholder(\n                tensor_spec.dtype, shape=tensor_spec.shape, name=tensor_spec.name)\n        return ret",
    "docstring": "Build a tf.placeholder from the metadata in the given tensor spec, or return an existing one.\n\n    Args:\n        tensor_spec (tf.TensorSpec):\n\n    Returns:\n        tf.Tensor:"
  },
  {
    "code": "def open_listing_page(trailing_part_of_url):\n    base_url = 'http://www.bbc.co.uk/programmes/'\n    print(\"Opening web page: \" + base_url + trailing_part_of_url)\n    try:\n        html = requests.get(base_url + trailing_part_of_url).text\n    except (IOError, NameError):\n        print(\"Error opening web page.\")\n        print(\"Check network connection and/or programme id.\")\n        sys.exit(1)\n    try:\n        return lxml.html.fromstring(html)\n    except lxml.etree.ParserError:\n        print(\"Error trying to parse web page.\")\n        print(\"Maybe there's no programme listing?\")\n        sys.exit(1)",
    "docstring": "Opens a BBC radio tracklisting page based on trailing part of url.\n    Returns a lxml ElementTree derived from that page.\n\n    trailing_part_of_url: a string, like the pid or e.g. pid/segments.inc"
  },
  {
    "code": "def keep_levels(self, level_indices):\n        if not isinstance(level_indices, list):\n            self.log_exc(u\"level_indices is not an instance of list\", None, True, TypeError)\n        for l in level_indices:\n            if not isinstance(l, int):\n                self.log_exc(u\"level_indices contains an element not int\", None, True, TypeError)\n        prev_levels = self.levels\n        level_indices = set(level_indices)\n        if 0 not in level_indices:\n            level_indices.add(0)\n        level_indices = level_indices & set(range(self.height))\n        level_indices = sorted(level_indices)[::-1]\n        for l in level_indices:\n            for node in prev_levels[l]:\n                node.remove_children(reset_parent=False)\n        for i in range(len(level_indices) - 1):\n            l = level_indices[i]\n            for node in prev_levels[l]:\n                parent_node = node.ancestor(l - level_indices[i + 1])\n                parent_node.add_child(node)",
    "docstring": "Rearrange the tree rooted at this node\n        to keep only the given levels.\n\n        The returned Tree will still be rooted\n        at the current node, i.e. this function\n        implicitly adds ``0`` to ``level_indices``.\n\n        If ``level_indices`` is an empty list,\n        only this node will be returned, with no children.\n\n        Elements of ``level_indices`` that do not\n        represent valid level indices (e.g., negative, or too large)\n        will be ignored and no error will be raised.\n\n        Important: this function modifies\n        the original tree in place!\n\n        :param list level_indices: the list of int, representing the levels to keep\n        :raises: TypeError if ``level_indices`` is not a list or if\n                 it contains an element which is not an int"
  },
  {
    "code": "def ip():\n    ok, err = _hack_ip()\n    if not ok:\n        click.secho(click.style(err, fg='red'))\n        sys.exit(1)\n    click.secho(click.style(err, fg='green'))",
    "docstring": "Show ip address."
  },
  {
    "code": "def _validate_scales(self, proposal):\n        scales = proposal.value\n        for name in self.trait_names(scaled=True):\n            trait = self.traits()[name]\n            if name not in scales:\n                if not trait.allow_none:\n                    raise TraitError(\"Missing scale for data attribute %s.\" %\n                                     name)\n            else:\n                if scales[name].rtype != trait.get_metadata('rtype'):\n                    raise TraitError(\"Range type mismatch for scale %s.\" %\n                                     name)\n        return scales",
    "docstring": "Validates the `scales` based on the mark's scaled attributes metadata.\n\n        First checks for missing scale and then for 'rtype' compatibility."
  },
  {
    "code": "def has_active_subscription(self, plan=None):\n\t\tif plan is None:\n\t\t\tvalid_subscriptions = self._get_valid_subscriptions()\n\t\t\tif len(valid_subscriptions) == 0:\n\t\t\t\treturn False\n\t\t\telif len(valid_subscriptions) == 1:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\traise TypeError(\n\t\t\t\t\t\"plan cannot be None if more than one valid subscription exists for this customer.\"\n\t\t\t\t)\n\t\telse:\n\t\t\tif isinstance(plan, StripeModel):\n\t\t\t\tplan = plan.id\n\t\t\treturn any(\n\t\t\t\t[\n\t\t\t\t\tsubscription.is_valid()\n\t\t\t\t\tfor subscription in self.subscriptions.filter(plan__id=plan)\n\t\t\t\t]\n\t\t\t)",
    "docstring": "Checks to see if this customer has an active subscription to the given plan.\n\n\t\t:param plan: The plan for which to check for an active subscription. If plan is None and\n\t\t\tthere exists only one active subscription, this method will check if that subscription\n\t\t\tis valid. Calling this method with no plan and multiple valid subscriptions for this customer will\n\t\t\tthrow an exception.\n\t\t:type plan: Plan or string (plan ID)\n\n\t\t:returns: True if there exists an active subscription, False otherwise.\n\t\t:throws: TypeError if ``plan`` is None and more than one active subscription exists for this customer."
  },
  {
    "code": "def _paramf16(ins):\n    output = _f16_oper(ins.quad[1])\n    output.append('push de')\n    output.append('push hl')\n    return output",
    "docstring": "Pushes 32bit fixed point param into the stack"
  },
  {
    "code": "def match_entry_line(str_to_match, regex_obj=MAIN_REGEX_OBJ):\n    match_obj = regex_obj.match(str_to_match)\n    if not match_obj:\n        error_message = ('Line \"%s\" is unrecognized by overlay4u. '\n                'This is only meant for use with Ubuntu Linux.')\n        raise UnrecognizedMountEntry(error_message % str_to_match)\n    return match_obj.groupdict()",
    "docstring": "Does a regex match of the mount entry string"
  },
  {
    "code": "def execute_on_keys(self, keys, entry_processor):\n        key_list = []\n        for key in keys:\n            check_not_none(key, \"key can't be None\")\n            key_list.append(self._to_data(key))\n        if len(keys) == 0:\n            return ImmediateFuture([])\n        return self._encode_invoke(map_execute_on_keys_codec, entry_processor=self._to_data(entry_processor),\n                                   keys=key_list)",
    "docstring": "Applies the user defined EntryProcessor to the entries mapped by the collection of keys. Returns the results\n        mapped by each key in the collection.\n\n        :param keys: (Collection), collection of the keys for the entries to be processed.\n        :param entry_processor: (object), A stateful serializable object which represents the EntryProcessor defined on\n            server side.\n            This object must have a serializable EntryProcessor counter part registered on server side with the actual\n            ``org.hazelcast.map.EntryProcessor`` implementation.\n        :return: (Sequence), list of map entries which includes the keys and the results of the entry process."
  },
  {
    "code": "def resolver(schema):\n    name = schema.__name__\n    if name.endswith(\"Schema\"):\n        return name[:-6] or name\n    return name",
    "docstring": "Default implementation of a schema name resolver function"
  },
  {
    "code": "def _parse_or_match(self, text, pos, method_name):\n        if not self.grammar:\n            raise RuntimeError(\n                \"The {cls}.{method}() shortcut won't work because {cls} was \"\n                \"never associated with a specific \" \"grammar. Fill out its \"\n                \"`grammar` attribute, and try again.\".format(\n                    cls=self.__class__.__name__,\n                    method=method_name))\n        return self.visit(getattr(self.grammar, method_name)(text, pos=pos))",
    "docstring": "Execute a parse or match on the default grammar, followed by a\n        visitation.\n\n        Raise RuntimeError if there is no default grammar specified."
  },
  {
    "code": "def cross_boundary(prev_obj, obj):\n    if prev_obj is None:\n        return\n    if isinstance(obj, _SecuredAttribute):\n        obj.parent = prev_obj\n    if hasattr(prev_obj, '_pecan'):\n        if obj not in prev_obj._pecan.get('unlocked', []):\n            handle_security(prev_obj)",
    "docstring": "Check permissions as we move between object instances."
  },
  {
    "code": "def arbiter(rst, clk, req_vec, gnt_vec=None, gnt_idx=None, gnt_vld=None, gnt_rdy=None, ARBITER_TYPE=\"priority\"):\n    if ARBITER_TYPE == \"priority\":\n        _arb = arbiter_priority(req_vec, gnt_vec, gnt_idx, gnt_vld)\n    elif (ARBITER_TYPE == \"roundrobin\"):\n        _arb = arbiter_roundrobin(rst, clk, req_vec, gnt_vec, gnt_idx, gnt_vld, gnt_rdy)\n    else:\n        assert \"Arbiter: Unknown arbiter type: {}\".format(ARBITER_TYPE)\n    return _arb",
    "docstring": "Wrapper that provides common interface to all arbiters"
  },
  {
    "code": "def _make_tonnetz_matrix():\n    pi = np.pi\n    chroma = np.arange(12)\n    fifth_x = r_fifth*(np.sin((7*pi/6) * chroma))\n    fifth_y = r_fifth*(np.cos((7*pi/6) * chroma))\n    minor_third_x = r_minor_thirds*(np.sin(3*pi/2 * chroma))\n    minor_third_y = r_minor_thirds*(np.cos(3*pi/2 * chroma))\n    major_third_x = r_major_thirds*(np.sin(2*pi/3 * chroma))\n    major_third_y = r_major_thirds*(np.cos(2*pi/3 * chroma))\n    return np.vstack((fifth_x, fifth_y,\n                      minor_third_x, minor_third_y,\n                      major_third_x, major_third_y))",
    "docstring": "Return the tonnetz projection matrix."
  },
  {
    "code": "def delete(self,storagemodel):\n        modeldefinition = self.getmodeldefinition(storagemodel, True)\n        pk = storagemodel.getPartitionKey()\n        rk = storagemodel.getRowKey()\n        try:\n            modeldefinition['tableservice'].delete_entity(modeldefinition['tablename'], pk, rk)\n            storagemodel._exists = False\n        except AzureMissingResourceHttpError as e:\n            log.debug('can not delete table entity:  Table {}, PartitionKey {}, RowKey {} because {!s}'.format(modeldefinition['tablename'], pk, rk, e))\n        finally:\n            return storagemodel",
    "docstring": "delete existing Entity"
  },
  {
    "code": "def _augment(self):\n        _pred, _ready, istar, j, mu = self._build_tree()\n        self._v[_ready] += self._d[_ready] - mu\n        while True:\n            i = _pred[j]\n            self._y[j] = i\n            k = j\n            j = self._x[i]\n            self._x[i] = k\n            if i == istar:\n                break\n        self._update_cred()",
    "docstring": "Finds a minimum cost path and adds it to the matching"
  },
  {
    "code": "def diff_archives(archive1, archive2, verbosity=0, interactive=True):\n    util.check_existing_filename(archive1)\n    util.check_existing_filename(archive2)\n    if verbosity >= 0:\n        util.log_info(\"Comparing %s with %s ...\" % (archive1, archive2))\n    res = _diff_archives(archive1, archive2, verbosity=verbosity, interactive=interactive)\n    if res == 0 and verbosity >= 0:\n        util.log_info(\"... no differences found.\")",
    "docstring": "Print differences between two archives."
  },
  {
    "code": "def clear_on_run(self, prefix=\"Running Tests:\"):\n        if platform.system() == 'Windows':\n            os.system('cls')\n        else:\n            os.system('clear')\n        if prefix:\n            print(prefix)",
    "docstring": "Clears console before running the tests."
  },
  {
    "code": "def as_percent(self, precision=2, *args, **kwargs):\n        f = Formatter(as_percent(precision), args, kwargs)\n        return self._add_formatter(f)",
    "docstring": "Format subset as percentages\n\n        :param precision: Decimal precision\n        :param subset: Pandas subset"
  },
  {
    "code": "def generic_find_fk_constraint_name(table, columns, referenced, insp):\n    for fk in insp.get_foreign_keys(table):\n        if fk['referred_table'] == referenced and set(fk['referred_columns']) == columns:\n            return fk['name']",
    "docstring": "Utility to find a foreign-key constraint name in alembic migrations"
  },
  {
    "code": "def _get_server(self):\n        with self._lock:\n            inactive_server_count = len(self._inactive_servers)\n            for i in range(inactive_server_count):\n                try:\n                    ts, server, message = heapq.heappop(self._inactive_servers)\n                except IndexError:\n                    pass\n                else:\n                    if (ts + self.retry_interval) > time():\n                        heapq.heappush(self._inactive_servers,\n                                       (ts, server, message))\n                    else:\n                        self._active_servers.append(server)\n                        logger.warn(\"Restored server %s into active pool\",\n                                    server)\n            if not self._active_servers:\n                ts, server, message = heapq.heappop(self._inactive_servers)\n                self._active_servers.append(server)\n                logger.info(\"Restored server %s into active pool\", server)\n            server = self._active_servers[0]\n            self._roundrobin()\n            return server",
    "docstring": "Get server to use for request.\n        Also process inactive server list, re-add them after given interval."
  },
  {
    "code": "def is_valid_group(group_name, nova_creds):\n    valid_groups = []\n    for key, value in nova_creds.items():\n        supernova_groups = value.get('SUPERNOVA_GROUP', [])\n        if hasattr(supernova_groups, 'startswith'):\n            supernova_groups = [supernova_groups]\n        valid_groups.extend(supernova_groups)\n    valid_groups.append('all')\n    if group_name in valid_groups:\n        return True\n    else:\n        return False",
    "docstring": "Checks to see if the configuration file contains a SUPERNOVA_GROUP\n    configuration option."
  },
  {
    "code": "def cal_model_performance(obsl, siml):\r\n    nse = MathClass.nashcoef(obsl, siml)\r\n    r2 = MathClass.rsquare(obsl, siml)\r\n    rmse = MathClass.rmse(obsl, siml)\r\n    pbias = MathClass.pbias(obsl, siml)\r\n    rsr = MathClass.rsr(obsl, siml)\r\n    print('NSE: %.2f, R-square: %.2f, PBIAS: %.2f%%, RMSE: %.2f, RSR: %.2f' %\r\n          (nse, r2, pbias, rmse, rsr))",
    "docstring": "Calculate model performance indexes."
  },
  {
    "code": "def validate(bundle):\n    errors = []\n    add_error = errors.append\n    series, services, machines, relations = _validate_sections(\n        bundle, add_error)\n    if errors:\n        return errors\n    _validate_series(series, 'bundle', add_error)\n    _validate_services(services, machines, add_error)\n    _validate_machines(machines, add_error)\n    _validate_relations(relations, services, add_error)\n    return errors",
    "docstring": "Validate a bundle object and all of its components.\n\n    The bundle must be passed as a YAML decoded object.\n\n    Return a list of bundle errors, or an empty list if the bundle is valid."
  },
  {
    "code": "def _ProcessEntries(self, fd):\n    p = config_file.KeyValueParser(kv_sep=\"{\", term=\"}\", sep=None)\n    data = utils.ReadFileBytesAsUnicode(fd)\n    entries = p.ParseEntries(data)\n    for entry in entries:\n      for section, cfg in iteritems(entry):\n        if cfg:\n          cfg = cfg[0].strip()\n        else:\n          cfg = \"\"\n        self._ParseSection(section, cfg)",
    "docstring": "Extract entries from the xinetd config files."
  },
  {
    "code": "def search_string(self):\n        self.__normalize()\n        tmpl_source = unicode(open(self.tmpl_file).read())\n        compiler = Compiler()\n        template = compiler.compile(tmpl_source)\n        out = template(self)\n        if not out:\n            return False\n        out = ''.join(out)\n        out = re.sub('\\n', '', out)\n        out = re.sub('\\s{3,}', ' ', out)\n        out = re.sub(',\\s*([}\\\\]])', '\\\\1', out)\n        out = re.sub('([{\\\\[}\\\\]])(,?)\\s*([{\\\\[}\\\\]])', '\\\\1\\\\2\\\\3', out)\n        out = re.sub('\\s*([{\\\\[\\\\]}:,])\\s*', '\\\\1', out)\n        return out",
    "docstring": "Returns the JSON string that LendingClub expects for it's search"
  },
  {
    "code": "def install(plugin_name, *args, **kwargs):\n    if isinstance(plugin_name, types.StringTypes):\n        plugin_name = [plugin_name]\n    conda_args = (['install', '-y', '--json'] + list(args) + plugin_name)\n    install_log_js = ch.conda_exec(*conda_args, verbose=False)\n    install_log = json.loads(install_log_js.split('\\x00')[-1])\n    if 'actions' in install_log and not install_log.get('dry_run'):\n        _save_action({'conda_args': conda_args, 'install_log': install_log})\n        logger.debug('Installed plugin(s): ```%s```', install_log['actions'])\n    return install_log",
    "docstring": "Install plugin packages based on specified Conda channels.\n\n    .. versionchanged:: 0.19.1\n        Do not save rollback info on dry-run.\n\n    .. versionchanged:: 0.24\n        Remove channels argument.  Use Conda channels as configured in Conda\n        environment.\n\n        Note that channels can still be explicitly set through :data:`*args`.\n\n    Parameters\n    ----------\n    plugin_name : str or list\n        Plugin package(s) to install.\n\n        Version specifiers are also supported, e.g., ``package >=1.0.5``.\n    *args\n        Extra arguments to pass to Conda ``install`` command.\n\n    Returns\n    -------\n    dict\n        Conda installation log object (from JSON Conda install output)."
  },
  {
    "code": "def compute_permutation_for_rotation(positions_a,\n                                     positions_b,\n                                     lattice,\n                                     symprec):\n    def sort_by_lattice_distance(fracs):\n        carts = np.dot(fracs - np.rint(fracs), lattice.T)\n        perm = np.argsort(np.sum(carts**2, axis=1))\n        sorted_fracs = np.array(fracs[perm], dtype='double', order='C')\n        return perm, sorted_fracs\n    (perm_a, sorted_a) = sort_by_lattice_distance(positions_a)\n    (perm_b, sorted_b) = sort_by_lattice_distance(positions_b)\n    perm_between = _compute_permutation_c(sorted_a,\n                                          sorted_b,\n                                          lattice,\n                                          symprec)\n    return perm_a[perm_between][np.argsort(perm_b)]",
    "docstring": "Get the overall permutation such that\n\n        positions_a[perm[i]] == positions_b[i]   (modulo the lattice)\n\n    or in numpy speak,\n\n        positions_a[perm] == positions_b   (modulo the lattice)\n\n    This version is optimized for the case where positions_a and positions_b\n    are related by a rotation."
  },
  {
    "code": "def _get_upstream(self):\n    if not self._remote or not self._branch:\n      branch = self.branch_name\n      if not branch:\n        raise Scm.LocalException('Failed to determine local branch')\n      def get_local_config(key):\n        value = self._check_output(['config', '--local', '--get', key],\n                                   raise_type=Scm.LocalException)\n        return value.strip()\n      self._remote = self._remote or get_local_config('branch.{}.remote'.format(branch))\n      self._branch = self._branch or get_local_config('branch.{}.merge'.format(branch))\n    return self._remote, self._branch",
    "docstring": "Return the remote and remote merge branch for the current branch"
  },
  {
    "code": "def getVals(self):\n        return [(name, self._fieldValDict.get(name)) \n                for name in self._fieldNameList]",
    "docstring": "Returns value list for Munin Graph\n        \n        @return: List of name-value pairs."
  },
  {
    "code": "def _fetch_size(self, request: Request) -> int:\n        try:\n            size = yield from self._commander.size(request.file_path)\n            return size\n        except FTPServerError:\n            return",
    "docstring": "Return size of file.\n\n        Coroutine."
  },
  {
    "code": "def onScreen(x, y=None):\n    x, y = _unpackXY(x, y)\n    x = int(x)\n    y = int(y)\n    width, height = platformModule._size()\n    return 0 <= x < width and 0 <= y < height",
    "docstring": "Returns whether the given xy coordinates are on the screen or not.\n\n    Args:\n      Either the arguments are two separate values, first arg for x and second\n        for y, or there is a single argument of a sequence with two values, the\n        first x and the second y.\n        Example: onScreen(x, y) or onScreen([x, y])\n\n    Returns:\n      bool: True if the xy coordinates are on the screen at its current\n        resolution, otherwise False."
  },
  {
    "code": "def create_task(self, ):\n        depi = self.dep_cb.currentIndex()\n        assert depi >= 0\n        dep = self.deps[depi]\n        deadline = self.deadline_de.dateTime().toPython()\n        try:\n            task = djadapter.models.Task(department=dep, project=self.element.project, element=self.element, deadline=deadline)\n            task.save()\n            self.task = task\n            self.accept()\n        except:\n            log.exception(\"Could not create new task\")",
    "docstring": "Create a task and store it in the self.task\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def pipeline_status(url, pipeline_id, auth, verify_ssl):\n    status_result = requests.get(url + '/' + pipeline_id + '/status', headers=X_REQ_BY, auth=auth, verify=verify_ssl)\n    status_result.raise_for_status()\n    logging.debug('Status request: ' + url + '/status')\n    logging.debug(status_result.json())\n    return status_result.json()",
    "docstring": "Retrieve the current status for a pipeline.\n\n    Args:\n        url          (str): the host url in the form 'http://host:port/'.\n        pipeline_id  (str): the ID of of the exported pipeline.\n        auth         (tuple): a tuple of username, and password.\n        verify_ssl   (bool): whether to verify ssl certificates\n\n    Returns:\n        dict: the response json"
  },
  {
    "code": "def parse_numeric_code(self, force_hex=False):\n        code = None\n        got_error = False\n        if not force_hex:\n            try:\n                code = int(self.numeric_code)\n            except ValueError:\n                got_error = True\n        if force_hex or got_error:\n            try:\n                code = int(self.numeric_code, 16)\n            except ValueError:\n                raise\n        return code",
    "docstring": "Parses and returns the numeric code as an integer.\n\n        The numeric code can be either base 10 or base 16, depending on\n        where the message came from.\n\n        :param force_hex: force the numeric code to be processed as base 16.\n        :type force_hex: boolean\n\n        :raises: ValueError"
  },
  {
    "code": "def rotate_x(self, deg):\n        rad = math.radians(deg)\n        mat = numpy.array([\n            [1, 0, 0, 0],\n            [0, math.cos(rad), math.sin(rad), 0],\n            [0, -math.sin(rad), math.cos(rad), 0],\n            [0, 0, 0, 1]\n        ])\n        self.vectors = self.vectors.dot(mat)\n        return self",
    "docstring": "Rotate mesh around x-axis\n\n        :param float deg: Rotation angle (degree)\n        :return:"
  },
  {
    "code": "def add_voice_call_api(mock):\n    mock.AddProperty('org.ofono.VoiceCallManager', 'EmergencyNumbers', ['911', '13373'])\n    mock.calls = []\n    mock.AddMethods('org.ofono.VoiceCallManager', [\n        ('GetProperties', '', 'a{sv}', 'ret = self.GetAll(\"org.ofono.VoiceCallManager\")'),\n        ('Transfer', '', '', ''),\n        ('SwapCalls', '', '', ''),\n        ('ReleaseAndAnswer', '', '', ''),\n        ('ReleaseAndSwap', '', '', ''),\n        ('HoldAndAnswer', '', '', ''),\n        ('SendTones', 's', '', ''),\n        ('PrivateChat', 'o', 'ao', NOT_IMPLEMENTED),\n        ('CreateMultiparty', '', 'o', NOT_IMPLEMENTED),\n        ('HangupMultiparty', '', '', NOT_IMPLEMENTED),\n        ('GetCalls', '', 'a(oa{sv})', 'ret = [(c, objects[c].GetAll(\"org.ofono.VoiceCall\")) for c in self.calls]')\n    ])",
    "docstring": "Add org.ofono.VoiceCallManager API to a mock"
  },
  {
    "code": "def dataframe(self, spark, group_by='greedy', limit=None, sample=1, seed=42, decode=None, summaries=None, schema=None, table_name=None):\n        rdd = self.records(spark.sparkContext, group_by, limit, sample, seed, decode, summaries)\n        if not schema:\n            df = rdd.map(lambda d: Row(**d)).toDF()\n        else:\n            df = spark.createDataFrame(rdd, schema=schema)\n        if table_name:\n            df.createOrReplaceTempView(table_name)\n        return df",
    "docstring": "Convert RDD returned from records function to a dataframe\n\n        :param spark: a SparkSession object\n        :param group_by: specifies a paritition strategy for the objects\n        :param limit: maximum number of objects to retrieve\n        :param decode: an optional transformation to apply to the objects retrieved\n        :param sample: percentage of results to return. Useful to return a sample\n            of the dataset. This parameter is ignored when 'limit' is set.\n        :param seed: initialize internal state of the random number generator (42 by default).\n            This is used to make the dataset sampling reproducible. It an be set to None to obtain\n            different samples.\n        :param summaries: an iterable containing the summary for each item in the dataset. If None, it\n            will compute calling the summaries dataset.\n        :param schema: a Spark schema that overrides automatic conversion to a dataframe\n        :param table_name: allows resulting dataframe to easily be queried using SparkSQL\n        :return: a Spark DataFrame"
  },
  {
    "code": "def gpg_error(exception, message):\n    LOGGER.debug(\"GPG Command %s\", ' '.join([str(x) for x in exception.cmd]))\n    LOGGER.debug(\"GPG Output %s\", exception.output)\n    raise CryptoritoError(message)",
    "docstring": "Handles the output of subprocess errors\n    in a way that is compatible with the log level"
  },
  {
    "code": "def close_db():\n    db = repo.Repo.db\n    if db is not None:\n        db.close()\n    repo.Repo.db = None\n    base.Repo.db = None\n    query.Repo.db = None",
    "docstring": "Close the connection to the database opened in `connect_db`"
  },
  {
    "code": "def delete(self, *, page_size=DEFAULT_BATCH_SIZE, **options):\n        from .model import delete_multi\n        deleted = 0\n        options = QueryOptions(self).replace(keys_only=True)\n        for page in self.paginate(page_size=page_size, **options):\n            keys = list(page)\n            deleted += len(keys)\n            delete_multi(keys)\n        return deleted",
    "docstring": "Deletes all the entities that match this query.\n\n        Note:\n          Since Datasotre doesn't provide a native way to delete\n          entities by query, this method paginates through all the\n          entities' keys and issues a single delete_multi call per\n          page.\n\n        Parameters:\n          \\**options(QueryOptions, optional)\n\n        Returns:\n          int: The number of deleted entities."
  },
  {
    "code": "def wr_xlsx(self, fout_xlsx):\n        objwr = WrXlsxSortedGos(\"GOEA\", self.sortobj)\n        kws_xlsx = {\n            'title': self.ver_list,\n            'fld2fmt': {f:'{:8.2e}' for f in self.flds_cur if f[:2] == 'p_'},\n            'prt_flds': self.flds_cur}\n        objwr.wr_xlsx_nts(fout_xlsx, self.desc2nts, **kws_xlsx)",
    "docstring": "Print grouped GOEA results into an xlsx file."
  },
  {
    "code": "def get_top_level_forum_url(self):\n        return (\n            reverse('forum:index') if self.top_level_forum is None else\n            reverse(\n                'forum:forum',\n                kwargs={'slug': self.top_level_forum.slug, 'pk': self.kwargs['pk']},\n            )\n        )",
    "docstring": "Returns the parent forum from which forums are marked as read."
  },
  {
    "code": "def set_opengl_implementation(option):\r\n    if option == 'software':\r\n        QCoreApplication.setAttribute(Qt.AA_UseSoftwareOpenGL)\r\n        if QQuickWindow is not None:\r\n            QQuickWindow.setSceneGraphBackend(QSGRendererInterface.Software)\r\n    elif option == 'desktop':\r\n        QCoreApplication.setAttribute(Qt.AA_UseDesktopOpenGL)\r\n        if QQuickWindow is not None:\r\n            QQuickWindow.setSceneGraphBackend(QSGRendererInterface.OpenGL)\r\n    elif option == 'gles':\r\n        QCoreApplication.setAttribute(Qt.AA_UseOpenGLES)\r\n        if QQuickWindow is not None:\r\n            QQuickWindow.setSceneGraphBackend(QSGRendererInterface.OpenGL)",
    "docstring": "Set the OpenGL implementation used by Spyder.\r\n\r\n    See issue 7447 for the details."
  },
  {
    "code": "def semimajor(P,M):\n    if type(P) != Quantity:\n        P = P*u.day\n    if type(M) != Quantity:\n        M = M*u.M_sun\n    a = ((P/2/np.pi)**2*const.G*M)**(1./3)\n    return a.to(u.AU)",
    "docstring": "P, M can be ``Quantity`` objects; otherwise default to day, M_sun"
  },
  {
    "code": "def load_from_args(args):\n    if not args.reads:\n        return None\n    if args.read_source_name:\n        read_source_names = util.expand(\n            args.read_source_name,\n            'read_source_name',\n            'read source',\n            len(args.reads))\n    else:\n        read_source_names = util.drop_prefix(args.reads)\n    filters = []\n    for (name, info) in READ_FILTERS.items():\n        value = getattr(args, name)\n        if value is not None:\n            filters.append(functools.partial(info[-1], value))\n    return [\n        load_bam(filename, name, filters)\n        for (filename, name)\n        in zip(args.reads, read_source_names)\n    ]",
    "docstring": "Given parsed commandline arguments, returns a list of ReadSource objects"
  },
  {
    "code": "def find_connectable_ip(host, port=None):\n    try:\n        addrinfos = socket.getaddrinfo(host, None)\n    except socket.gaierror:\n        return None\n    ip = None\n    for family, _, _, _, sockaddr in addrinfos:\n        connectable = True\n        if port:\n            connectable = is_connectable(port, sockaddr[0])\n        if connectable and family == socket.AF_INET:\n            return sockaddr[0]\n        if connectable and not ip and family == socket.AF_INET6:\n            ip = sockaddr[0]\n    return ip",
    "docstring": "Resolve a hostname to an IP, preferring IPv4 addresses.\n\n    We prefer IPv4 so that we don't change behavior from previous IPv4-only\n    implementations, and because some drivers (e.g., FirefoxDriver) do not\n    support IPv6 connections.\n\n    If the optional port number is provided, only IPs that listen on the given\n    port are considered.\n\n    :Args:\n        - host - A hostname.\n        - port - Optional port number.\n\n    :Returns:\n        A single IP address, as a string. If any IPv4 address is found, one is\n        returned. Otherwise, if any IPv6 address is found, one is returned. If\n        neither, then None is returned."
  },
  {
    "code": "def set_value(self, var_name, value):\n        if var_name in self.outside_name_map:\n            var_name = self.outside_name_map[var_name]\n            print('%s=%.5f' % (var_name, 1e9*value))\n            if var_name == 'Precipitation':\n                value = 1e9*value\n        species_idx = self.species_name_map[var_name]\n        self.state[species_idx] = value",
    "docstring": "Set the value of a given variable to a given value.\n\n        Parameters\n        ----------\n        var_name : str\n            The name of the variable in the model whose value should be set.\n\n        value : float\n            The value the variable should be set to"
  },
  {
    "code": "def set_scale_alpha_from_selection(self):\n        selection = self.treeview_layers.get_selection()\n        list_store, selected_iter = selection.get_selected()\n        if selected_iter is None:\n            self.adjustment_alpha.set_value(100)\n            self.scale_alpha.set_sensitive(False)\n            return\n        else:\n            surface_name, alpha = list_store[selected_iter]\n            self.adjustment_alpha.set_value(alpha * 100)\n            self.scale_alpha.set_sensitive(True)",
    "docstring": "Set scale marker to alpha for selected layer."
  },
  {
    "code": "def observable_object_keys(instance):\n    digits_re = re.compile(r\"^\\d+$\")\n    for key in instance['objects']:\n        if not digits_re.match(key):\n            yield JSONError(\"'%s' is not a good key value. Observable Objects \"\n                            \"should use non-negative integers for their keys.\"\n                            % key, instance['id'], 'observable-object-keys')",
    "docstring": "Ensure observable-objects keys are non-negative integers."
  },
  {
    "code": "def session_list(consul_url=None, token=None, return_list=False, **kwargs):\n    ret = {}\n    if not consul_url:\n        consul_url = _get_config()\n        if not consul_url:\n            log.error('No Consul URL found.')\n            ret['message'] = 'No Consul URL found.'\n            ret['res'] = False\n            return ret\n    query_params = {}\n    if 'dc' in kwargs:\n        query_params['dc'] = kwargs['dc']\n    function = 'session/list'\n    ret = _query(consul_url=consul_url,\n                 function=function,\n                 token=token,\n                 query_params=query_params)\n    if return_list:\n        _list = []\n        for item in ret['data']:\n            _list.append(item['ID'])\n        return _list\n    return ret",
    "docstring": "Used to list sessions.\n\n    :param consul_url: The Consul server URL.\n    :param dc: By default, the datacenter of the agent is queried;\n               however, the dc can be provided using the \"dc\" parameter.\n    :param return_list: By default, all information about the sessions is\n                        returned, using the return_list parameter will return\n                        a list of session IDs.\n    :return: A list of all available sessions.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' consul.session_list"
  },
  {
    "code": "def get_product_string(self):\n        self._check_device_status()\n        str_p = ffi.new(\"wchar_t[]\", 255)\n        rv = hidapi.hid_get_product_string(self._device, str_p, 255)\n        if rv == -1:\n            raise IOError(\"Failed to read product string from HID device: {0}\"\n                          .format(self._get_last_error_string()))\n        return ffi.string(str_p)",
    "docstring": "Get the Product String from the HID device.\n\n        :return:    The Product String\n        :rtype:     unicode"
  },
  {
    "code": "def register_actor(name, actor_handle):\n    if not isinstance(name, str):\n        raise TypeError(\"The name argument must be a string.\")\n    if not isinstance(actor_handle, ray.actor.ActorHandle):\n        raise TypeError(\"The actor_handle argument must be an ActorHandle \"\n                        \"object.\")\n    actor_name = _calculate_key(name)\n    pickled_state = pickle.dumps(actor_handle)\n    already_exists = _internal_kv_put(actor_name, pickled_state)\n    if already_exists:\n        actor_handle._ray_new_actor_handles.pop()\n        raise ValueError(\n            \"Error: the actor with name={} already exists\".format(name))",
    "docstring": "Register a named actor under a string key.\n\n   Args:\n       name: The name of the named actor.\n       actor_handle: The actor object to be associated with this name"
  },
  {
    "code": "def ls(manager: Manager, url: Optional[str], namespace_id: Optional[int]):\n    if url:\n        n = manager.get_or_create_namespace(url)\n        if isinstance(n, Namespace):\n            _page(n.entries)\n        else:\n            click.echo('uncachable namespace')\n    elif namespace_id is not None:\n        _ls(manager, Namespace, namespace_id)\n    else:\n        click.echo('Missing argument -i or -u')",
    "docstring": "List cached namespaces."
  },
  {
    "code": "def assertEqual(first, second, message=None):\n    if not first == second:\n        raise TestStepFail(\n            format_message(message) if message is not None else \"Assert: %s != %s\" % (str(first),\n                                                                                      str(second)))",
    "docstring": "Assert that first equals second.\n\n    :param first: First part to evaluate\n    :param second: Second part to evaluate\n    :param message: Failure message\n    :raises: TestStepFail if not first == second"
  },
  {
    "code": "def open(self) -> bool:\n        return self.state is State.OPEN and not self.transfer_data_task.done()",
    "docstring": "This property is ``True`` when the connection is usable.\n\n        It may be used to detect disconnections but this is discouraged per\n        the EAFP_ principle. When ``open`` is ``False``, using the connection\n        raises a :exc:`~websockets.exceptions.ConnectionClosed` exception.\n\n        .. _EAFP: https://docs.python.org/3/glossary.html#term-eafp"
  },
  {
    "code": "def isUrl(urlString):\n    parsed = urlparse.urlparse(urlString)\n    urlparseValid = parsed.netloc != '' and parsed.scheme != ''\n    regex = re.compile(\n        r'^(?:http|ftp)s?://'\n        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)'\n        r'+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|'\n        r'localhost|'\n        r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'\n        r'(?::\\d+)?'\n        r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\n    return regex.match(urlString) and urlparseValid",
    "docstring": "Attempts to return whether a given URL string is valid by checking\n    for the presence of the URL scheme and netloc using the urlparse\n    module, and then using a regex.\n\n    From http://stackoverflow.com/questions/7160737/"
  },
  {
    "code": "def modver(self, *args):\n        g = get_root(self).globals\n        if self.ok():\n            tname = self.val.get()\n            if tname in self.successes:\n                self.verify.config(bg=g.COL['start'])\n            elif tname in self.failures:\n                self.verify.config(bg=g.COL['stop'])\n            else:\n                self.verify.config(bg=g.COL['main'])\n            self.verify.config(state='normal')\n        else:\n            self.verify.config(bg=g.COL['main'])\n            self.verify.config(state='disable')\n        if self.callback is not None:\n            self.callback()",
    "docstring": "Switches colour of verify button"
  },
  {
    "code": "def get_direct_band_gap(self):\n        if self.is_metal():\n            return 0.0\n        dg = self.get_direct_band_gap_dict()\n        return min(v['value'] for v in dg.values())",
    "docstring": "Returns the direct band gap.\n\n        Returns:\n             the value of the direct band gap"
  },
  {
    "code": "def find_fields(self, classname=\".*\", fieldname=\".*\", fieldtype=\".*\", accessflags=\".*\"):\n        for cname, c in self.classes.items():\n            if re.match(classname, cname):\n                for f in c.get_fields():\n                    z = f.get_field()\n                    if re.match(fieldname, z.get_name()) and \\\n                       re.match(fieldtype, z.get_descriptor()) and \\\n                       re.match(accessflags, z.get_access_flags_string()):\n                        yield f",
    "docstring": "find fields by regex\n\n        :param classname: regular expression of the classname\n        :param fieldname: regular expression of the fieldname\n        :param fieldtype: regular expression of the fieldtype\n        :param accessflags: regular expression of the access flags\n        :rtype: generator of `FieldClassAnalysis`"
  },
  {
    "code": "def CallNtpdate(logger):\n  ntpd_inactive = subprocess.call(['service', 'ntpd', 'status'])\n  try:\n    if not ntpd_inactive:\n      subprocess.check_call(['service', 'ntpd', 'stop'])\n    subprocess.check_call(\n        'ntpdate `awk \\'$1==\"server\" {print $2}\\' /etc/ntp.conf`', shell=True)\n    if not ntpd_inactive:\n      subprocess.check_call(['service', 'ntpd', 'start'])\n  except subprocess.CalledProcessError:\n    logger.warning('Failed to sync system time with ntp server.')\n  else:\n    logger.info('Synced system time with ntp server.')",
    "docstring": "Sync clock using ntpdate.\n\n  Args:\n    logger: logger object, used to write to SysLog and serial port."
  },
  {
    "code": "def from_row(row):\n    subject = (row[5][0].upper() + row[5][1:]) if row[5] else row[5]\n    return Advice.objects.create(\n        id=row[0],\n        administration=cleanup(row[1]),\n        type=row[2],\n        session=datetime.strptime(row[4], '%d/%m/%Y'),\n        subject=cleanup(subject),\n        topics=[t.title() for t in cleanup(row[6]).split(', ')],\n        tags=[tag.strip() for tag in row[7].split(',') if tag.strip()],\n        meanings=cleanup(row[8]).replace(' / ', '/').split(', '),\n        part=_part(row[9]),\n        content=cleanup(row[10]),\n    )",
    "docstring": "Create an advice from a CSV row"
  },
  {
    "code": "def monitors(self):\n        import ns1.rest.monitoring\n        return ns1.rest.monitoring.Monitors(self.config)",
    "docstring": "Return a new raw REST interface to monitors resources\n\n        :rtype: :py:class:`ns1.rest.monitoring.Monitors`"
  },
  {
    "code": "def isConnected(self, fromName, toName):\n        for c in self.connections:\n            if (c.fromLayer.name == fromName and\n                c.toLayer.name == toName):\n                return 1\n        return 0",
    "docstring": "Are these two layers connected this way?"
  },
  {
    "code": "def find_needed_input(input_format):\n    needed_inputs = [re.cls for re in registry if re.category==RegistryCategories.inputs and re.cls.input_format == input_format]\n    if len(needed_inputs)>0:\n        return needed_inputs[0]\n    return None",
    "docstring": "Find a needed input class\n    input_format - needed input format, see utils.input.dataformats"
  },
  {
    "code": "def register_instances(name, instances, region=None, key=None, keyid=None,\n                       profile=None):\n    if isinstance(instances, six.string_types) or isinstance(instances, six.text_type):\n        instances = [instances]\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    try:\n        registered_instances = conn.register_instances(name, instances)\n    except boto.exception.BotoServerError as error:\n        log.warning(error)\n        return False\n    registered_instance_ids = [instance.id for instance in\n                               registered_instances]\n    register_failures = set(instances).difference(set(registered_instance_ids))\n    if register_failures:\n        log.warning('Instance(s): %s not registered with ELB %s.',\n                    list(register_failures), name)\n        register_result = False\n    else:\n        register_result = True\n    return register_result",
    "docstring": "Register instances with an ELB.  Instances is either a string\n    instance id or a list of string instance id's.\n\n    Returns:\n\n    - ``True``: instance(s) registered successfully\n    - ``False``: instance(s) failed to be registered\n\n    CLI example:\n\n    .. code-block:: bash\n\n        salt myminion boto_elb.register_instances myelb instance_id\n        salt myminion boto_elb.register_instances myelb \"[instance_id,instance_id]\""
  },
  {
    "code": "def GetSystemConfigurationArtifact(self, session_identifier=CURRENT_SESSION):\n    system_configuration = artifacts.SystemConfigurationArtifact()\n    system_configuration.code_page = self.GetValue(\n        'codepage', default_value=self._codepage)\n    system_configuration.hostname = self._hostnames.get(\n        session_identifier, None)\n    system_configuration.keyboard_layout = self.GetValue('keyboard_layout')\n    system_configuration.operating_system = self.GetValue('operating_system')\n    system_configuration.operating_system_product = self.GetValue(\n        'operating_system_product')\n    system_configuration.operating_system_version = self.GetValue(\n        'operating_system_version')\n    date_time = datetime.datetime(2017, 1, 1)\n    time_zone = self._time_zone.tzname(date_time)\n    if time_zone and isinstance(time_zone, py2to3.BYTES_TYPE):\n      time_zone = time_zone.decode('ascii')\n    system_configuration.time_zone = time_zone\n    user_accounts = self._user_accounts.get(session_identifier, {})\n    system_configuration.user_accounts = list(user_accounts.values())\n    return system_configuration",
    "docstring": "Retrieves the knowledge base as a system configuration artifact.\n\n    Args:\n      session_identifier (Optional[str])): session identifier, where\n          CURRENT_SESSION represents the active session.\n\n    Returns:\n      SystemConfigurationArtifact: system configuration artifact."
  },
  {
    "code": "def get_crop_size(crop_w, crop_h, image_w, image_h):\n    scale1 = float(crop_w) / float(image_w)\n    scale2 = float(crop_h) / float(image_h)\n    scale1_w = crop_w\n    scale1_h = int(round(image_h * scale1))\n    scale2_w = int(round(image_w * scale2))\n    scale2_h = crop_h\n    if scale1_h > crop_h:\n        return (scale1_w, scale1_h)\n    else:\n        return (scale2_w, scale2_h)",
    "docstring": "Determines the correct scale size for the image\n\n    when img w == crop w and img h > crop h\n        Use these dimensions\n\n    when img h == crop h and img w > crop w\n        Use these dimensions"
  },
  {
    "code": "def galprop_gasmap(self, **kwargs):\n        kwargs_copy = self.base_dict.copy()\n        kwargs_copy.update(**kwargs)\n        self._replace_none(kwargs_copy)        \n        localpath = NameFactory.galprop_gasmap_format.format(**kwargs_copy)\n        if kwargs.get('fullpath', False):\n            return self.fullpath(localpath=localpath)\n        return localpath",
    "docstring": "return the file name for Galprop input gasmaps"
  },
  {
    "code": "def reload(self):\n        self.restarted_adapter = False\n        self.data.clear()\n        if conf.use_winpcapy:\n            from scapy.arch.pcapdnet import load_winpcapy\n            load_winpcapy()\n        self.load()\n        conf.iface = get_working_if()",
    "docstring": "Reload interface list"
  },
  {
    "code": "def to_json(self):\n        result = {\n            'sys': {}\n        }\n        for k, v in self.sys.items():\n            if k in ['space', 'content_type', 'created_by',\n                     'updated_by', 'published_by']:\n                v = v.to_json()\n            if k in ['created_at', 'updated_at', 'deleted_at',\n                     'first_published_at', 'published_at', 'expires_at']:\n                v = v.isoformat()\n            result['sys'][camel_case(k)] = v\n        return result",
    "docstring": "Returns the JSON representation of the resource."
  },
  {
    "code": "def deleteVertex(self, document, waitForSync = False) :\n        url = \"%s/vertex/%s\" % (self.URL, document._id)\n        r = self.connection.session.delete(url, params = {'waitForSync' : waitForSync})\n        data = r.json()\n        if r.status_code == 200 or r.status_code == 202 :\n            return True\n        raise DeletionError(\"Unable to delete vertice, %s\" % document._id, data)",
    "docstring": "deletes a vertex from the graph as well as al linked edges"
  },
  {
    "code": "def add_middleware(self, middleware, *, before=None, after=None):\n        assert not (before and after), \\\n            \"provide either 'before' or 'after', but not both\"\n        if before or after:\n            for i, m in enumerate(self.middleware):\n                if isinstance(m, before or after):\n                    break\n            else:\n                raise ValueError(\"Middleware %r not found\" % (before or after))\n            if before:\n                self.middleware.insert(i, middleware)\n            else:\n                self.middleware.insert(i + 1, middleware)\n        else:\n            self.middleware.append(middleware)\n        self.actor_options |= middleware.actor_options\n        for actor_name in self.get_declared_actors():\n            middleware.after_declare_actor(self, actor_name)\n        for queue_name in self.get_declared_queues():\n            middleware.after_declare_queue(self, queue_name)\n        for queue_name in self.get_declared_delay_queues():\n            middleware.after_declare_delay_queue(self, queue_name)",
    "docstring": "Add a middleware object to this broker.  The middleware is\n        appended to the end of the middleware list by default.\n\n        You can specify another middleware (by class) as a reference\n        point for where the new middleware should be added.\n\n        Parameters:\n          middleware(Middleware): The middleware.\n          before(type): Add this middleware before a specific one.\n          after(type): Add this middleware after a specific one.\n\n        Raises:\n          ValueError: When either ``before`` or ``after`` refer to a\n            middleware that hasn't been registered yet."
  },
  {
    "code": "def new(namespace, name, protected=False,\n            attributes=dict(), api_url=fapi.PROD_API_ROOT):\n        r = fapi.create_workspace(namespace, name, protected, attributes, api_url)\n        fapi._check_response_code(r, 201)\n        return Workspace(namespace, name, api_url)",
    "docstring": "Create a new FireCloud workspace.\n\n        Returns:\n            Workspace: A new FireCloud workspace\n\n        Raises:\n            FireCloudServerError: API call failed."
  },
  {
    "code": "def _insert_new_layers(self, new_layers, start_node_id, end_node_id):\n        new_node_id = self._add_node(deepcopy(self.node_list[end_node_id]))\n        temp_output_id = new_node_id\n        for layer in new_layers[:-1]:\n            temp_output_id = self.add_layer(layer, temp_output_id)\n        self._add_edge(new_layers[-1], temp_output_id, end_node_id)\n        new_layers[-1].input = self.node_list[temp_output_id]\n        new_layers[-1].output = self.node_list[end_node_id]\n        self._redirect_edge(start_node_id, end_node_id, new_node_id)",
    "docstring": "Insert the new_layers after the node with start_node_id."
  },
  {
    "code": "def bleu_score(predictions, labels, **unused_kwargs):\n  outputs = tf.to_int32(tf.argmax(predictions, axis=-1))\n  outputs = tf.squeeze(outputs, axis=[-1, -2])\n  labels = tf.squeeze(labels, axis=[-1, -2])\n  bleu = tf.py_func(compute_bleu, (labels, outputs), tf.float32)\n  return bleu, tf.constant(1.0)",
    "docstring": "BLEU score computation between labels and predictions.\n\n  An approximate BLEU scoring method since we do not glue word pieces or\n  decode the ids and tokenize the output. By default, we use ngram order of 4\n  and use brevity penalty. Also, this does not have beam search.\n\n  Args:\n    predictions: tensor, model predictions\n    labels: tensor, gold output.\n\n  Returns:\n    bleu: int, approx bleu score"
  },
  {
    "code": "def _corrupt(self, data, dpos):\n        ws = list(self._BLK_BE.unpack_from(data, dpos))\n        for t in range(16, 80):\n            tmp = ws[(t - 3) & 15] ^ ws[(t - 8) & 15] ^ ws[(t - 14) & 15] ^ ws[(t - 16) & 15]\n            ws[t & 15] = ((tmp << 1) | (tmp >> (32 - 1))) & 0xFFFFFFFF\n        self._BLK_LE.pack_into(data, dpos, *ws)",
    "docstring": "Corruption from SHA1 core."
  },
  {
    "code": "def incident(self, name, owner=None, **kwargs):\n        return Incident(self.tcex, name, owner=owner, **kwargs)",
    "docstring": "Create the Incident TI object.\n\n        Args:\n            owner:\n            name:\n            **kwargs:\n\n        Return:"
  },
  {
    "code": "def open(self):\n        self._connection = sqlite3.connect(self._dbname)\n        self._cursor = self._connection.cursor()\n        self._session_info = SessionInfoTable(self._connection, self._cursor)\n        self._reports = ReportsTable(self._connection, self._cursor)",
    "docstring": "open the database"
  },
  {
    "code": "def run(self):\n        self.init_run()\n        if self.debug: self.dump(\"AfterInit: \")\n        while self.step():\n            pass",
    "docstring": "Runs the simulation."
  },
  {
    "code": "def fencekml(self, layername):\n        if layername.startswith('\"') and layername.endswith('\"'):\n            layername = layername[1:-1]\n        for layer in self.allayers:\n            if layer.key == layername:\n                self.fenceloader.clear()\n                if len(layer.points) < 3:\n                    return\n                self.fenceloader.target_system = self.target_system\n                self.fenceloader.target_component = self.target_component\n                bounds = mp_util.polygon_bounds(layer.points)\n                (lat, lon, width, height) = bounds\n                center = (lat+width/2, lon+height/2)\n                self.fenceloader.add_latlon(center[0], center[1])\n                for lat, lon in layer.points:\n                    self.fenceloader.add_latlon(lat, lon)\n                self.send_fence()",
    "docstring": "set a layer as the geofence"
  },
  {
    "code": "def override(self, obj):\n        for field in obj.__class__.export_fields:\n            setattr(self, field, getattr(obj, field))",
    "docstring": "Overrides the plain fields of the dashboard."
  },
  {
    "code": "def _spec_to_globs(address_mapper, specs):\n  patterns = set()\n  for spec in specs:\n    patterns.update(spec.make_glob_patterns(address_mapper))\n  return PathGlobs(include=patterns, exclude=address_mapper.build_ignore_patterns)",
    "docstring": "Given a Specs object, return a PathGlobs object for the build files that it matches."
  },
  {
    "code": "def edit(self, state):\n        if state and state.lower() == 'active':\n            data = dumps({'state': state.lower()})\n            json = self._json(self._patch(self._api, data=data))\n            self._update_attributes(json)\n        return self",
    "docstring": "Edit the user's membership.\n\n        :param str state: (required), the state the membership should be in.\n            Only accepts ``\"active\"``.\n        :returns: itself"
  },
  {
    "code": "def open_netcdf_writer(self, flatten=False, isolate=False, timeaxis=1):\n        self._netcdf_writer = netcdftools.NetCDFInterface(\n            flatten=bool(flatten),\n            isolate=bool(isolate),\n            timeaxis=int(timeaxis))",
    "docstring": "Prepare a new |NetCDFInterface| object for writing data."
  },
  {
    "code": "def vmotion_disable(host, username, password, protocol=None, port=None, host_names=None):\n    service_instance = salt.utils.vmware.get_service_instance(host=host,\n                                                              username=username,\n                                                              password=password,\n                                                              protocol=protocol,\n                                                              port=port)\n    host_names = _check_hosts(service_instance, host, host_names)\n    ret = {}\n    for host_name in host_names:\n        host_ref = _get_host_ref(service_instance, host, host_name=host_name)\n        vmotion_system = host_ref.configManager.vmotionSystem\n        try:\n            vmotion_system.DeselectVnic()\n        except vim.fault.HostConfigFault as err:\n            msg = 'vsphere.vmotion_disable failed: {0}'.format(err)\n            log.debug(msg)\n            ret.update({host_name: {'Error': msg,\n                                    'VMotion Disabled': False}})\n            continue\n        ret.update({host_name: {'VMotion Disabled': True}})\n    return ret",
    "docstring": "Disable vMotion for a given host or list of host_names.\n\n    host\n        The location of the host.\n\n    username\n        The username used to login to the host, such as ``root``.\n\n    password\n        The password used to login to the host.\n\n    protocol\n        Optionally set to alternate protocol if the host is not using the default\n        protocol. Default protocol is ``https``.\n\n    port\n        Optionally set to alternate port if the host is not using the default\n        port. Default port is ``443``.\n\n    host_names\n        List of ESXi host names. When the host, username, and password credentials\n        are provided for a vCenter Server, the host_names argument is required to\n        tell vCenter which hosts should disable VMotion.\n\n        If host_names is not provided, VMotion will be disabled for the ``host``\n        location instead. This is useful for when service instance connection\n        information is used for a single ESXi host.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        # Used for single ESXi host connection information\n        salt '*' vsphere.vmotion_disable my.esxi.host root bad-password\n\n        # Used for connecting to a vCenter Server\n        salt '*' vsphere.vmotion_disable my.vcenter.location root bad-password \\\n        host_names='[esxi-1.host.com, esxi-2.host.com]'"
  },
  {
    "code": "def _parse_coroutine(self):\n        while True:\n            d = yield\n            if d == int2byte(0):\n                pass\n            elif d == IAC:\n                d2 = yield\n                if d2 == IAC:\n                    self.received_data(d2)\n                elif d2 in (NOP, DM, BRK, IP, AO, AYT, EC, EL, GA):\n                    self.command_received(d2, None)\n                elif d2 in (DO, DONT, WILL, WONT):\n                    d3 = yield\n                    self.command_received(d2, d3)\n                elif d2 == SB:\n                    data = []\n                    while True:\n                        d3 = yield\n                        if d3 == IAC:\n                            d4 = yield\n                            if d4 == SE:\n                                break\n                            else:\n                                data.append(d4)\n                        else:\n                            data.append(d3)\n                    self.negotiate(b''.join(data))\n            else:\n                self.received_data(d)",
    "docstring": "Parser state machine.\n        Every 'yield' expression returns the next byte."
  },
  {
    "code": "def frmnam(frcode, lenout=_default_len_out):\n    frcode = ctypes.c_int(frcode)\n    lenout = ctypes.c_int(lenout)\n    frname = stypes.stringToCharP(lenout)\n    libspice.frmnam_c(frcode, lenout, frname)\n    return stypes.toPythonString(frname)",
    "docstring": "Retrieve the name of a reference frame associated with a SPICE ID code.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/frmnam_c.html\n\n    :param frcode: an integer code for a reference frame\n    :type frcode: int\n    :param lenout: Maximum length of output string.\n    :type lenout: int\n    :return: the name associated with the reference frame.\n    :rtype: str"
  },
  {
    "code": "def rename_command(source, destination):\n    source_ep, source_path = source\n    dest_ep, dest_path = destination\n    if source_ep != dest_ep:\n        raise click.UsageError(\n            (\n                \"rename requires that the source and dest \"\n                \"endpoints are the same, {} != {}\"\n            ).format(source_ep, dest_ep)\n        )\n    endpoint_id = source_ep\n    client = get_client()\n    autoactivate(client, endpoint_id, if_expires_in=60)\n    res = client.operation_rename(endpoint_id, oldpath=source_path, newpath=dest_path)\n    formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key=\"message\")",
    "docstring": "Executor for `globus rename`"
  },
  {
    "code": "def label_set(self):\n        label_set = list()\n        for class_ in self.class_set:\n            samples_in_class = self.sample_ids_in_class(class_)\n            label_set.append(self.labels[samples_in_class[0]])\n        return label_set",
    "docstring": "Set of labels in the dataset corresponding to class_set."
  },
  {
    "code": "def _format_object(obj, format_type=None):\n    if json_api_settings.FORMAT_KEYS is not None:\n        return format_keys(obj, format_type)\n    return format_field_names(obj, format_type)",
    "docstring": "Depending on settings calls either `format_keys` or `format_field_names`"
  },
  {
    "code": "def train_model(model_folder):\n    os.chdir(model_folder)\n    training = generate_training_command(model_folder)\n    if training is None:\n        return -1\n    logging.info(training)\n    os.chdir(model_folder)\n    os.system(training)",
    "docstring": "Train the model in ``model_folder``."
  },
  {
    "code": "def utime_delta(days=0, hours=0, minutes=0, seconds=0):\n    return (days * DAY) + (hours * HOUR) + (minutes * MINUTE) + (seconds * SECOND)",
    "docstring": "Gets time delta in microseconds.\n\n    Note: Do NOT use this function without keyword arguments.\n    It will become much-much harder to add extra time ranges later if positional arguments are used."
  },
  {
    "code": "def on_to_position(self, speed, position, brake=True, block=True):\n        speed = self._speed_native_units(speed)\n        self.speed_sp = int(round(speed))\n        self.position_sp = position\n        self._set_brake(brake)\n        self.run_to_abs_pos()\n        if block:\n            self.wait_until('running', timeout=WAIT_RUNNING_TIMEOUT)\n            self.wait_until_not_moving()",
    "docstring": "Rotate the motor at ``speed`` to ``position``\n\n        ``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue`\n        object, enabling use of other units."
  },
  {
    "code": "async def reconnect(self):\n        _LOGGER.debug('starting Connection.reconnect')\n        await self._connect()\n        while self._closed:\n            await self._retry_connection()\n        _LOGGER.debug('ending Connection.reconnect')",
    "docstring": "Reconnect to the modem."
  },
  {
    "code": "def get_cursor_vertical_diff(self):\n        if self.in_get_cursor_diff:\n            self.another_sigwinch = True\n            return 0\n        cursor_dy = 0\n        while True:\n            self.in_get_cursor_diff = True\n            self.another_sigwinch = False\n            cursor_dy += self._get_cursor_vertical_diff_once()\n            self.in_get_cursor_diff = False\n            if not self.another_sigwinch:\n                return cursor_dy",
    "docstring": "Returns the how far down the cursor moved since last render.\n\n        Note:\n            If another get_cursor_vertical_diff call is already in progress,\n            immediately returns zero. (This situation is likely if\n            get_cursor_vertical_diff is called from a SIGWINCH signal\n            handler, since sigwinches can happen in rapid succession and\n            terminal emulators seem not to respond to cursor position\n            queries before the next sigwinch occurs.)"
  },
  {
    "code": "def make_trajectory(first, filename, restart=False):\n    mode = 'w'\n    if restart:\n        mode = 'a'\n    return Trajectory(first, filename, mode)",
    "docstring": "Factory function to easily create a trajectory object"
  },
  {
    "code": "def read_passive_target(self, card_baud=PN532_MIFARE_ISO14443A, timeout_sec=1):\n        response = self.call_function(PN532_COMMAND_INLISTPASSIVETARGET,\n                                      params=[0x01, card_baud],\n                                      response_length=17)\n        if response is None:\n            return None\n        if response[0] != 0x01:\n            raise RuntimeError('More than one card detected!')\n        if response[5] > 7:\n            raise RuntimeError('Found card with unexpectedly long UID!')\n        return response[6:6+response[5]]",
    "docstring": "Wait for a MiFare card to be available and return its UID when found.\n        Will wait up to timeout_sec seconds and return None if no card is found,\n        otherwise a bytearray with the UID of the found card is returned."
  },
  {
    "code": "def _get_dopants(substitutions, num_dopants, match_oxi_sign):\n    n_type = [pred for pred in substitutions\n              if pred['dopant_species'].oxi_state >\n              pred['original_species'].oxi_state\n              and (not match_oxi_sign or\n                   np.sign(pred['dopant_species'].oxi_state) ==\n                   np.sign(pred['original_species'].oxi_state))]\n    p_type = [pred for pred in substitutions\n              if pred['dopant_species'].oxi_state <\n              pred['original_species'].oxi_state\n              and (not match_oxi_sign or\n                   np.sign(pred['dopant_species'].oxi_state) ==\n                   np.sign(pred['original_species'].oxi_state))]\n    return {'n_type': n_type[:num_dopants], 'p_type': p_type[:num_dopants]}",
    "docstring": "Utility method to get n- and p-type dopants from a list of substitutions."
  },
  {
    "code": "def create_mapping(self, mapped_class, configuration=None):\n        cfg = self.__configuration.copy()\n        if not configuration is None:\n            cfg.update(configuration)\n        provided_ifcs = provided_by(object.__new__(mapped_class))\n        if IMemberResource in provided_ifcs:\n            base_data_element_class = self.member_data_element_base_class\n        elif ICollectionResource in provided_ifcs:\n            base_data_element_class = self.collection_data_element_base_class\n        elif IResourceLink in provided_ifcs:\n            base_data_element_class = self.linked_data_element_base_class\n        else:\n            raise ValueError('Mapped class for data element class does not '\n                             'implement one of the required interfaces.')\n        name = \"%s%s\" % (mapped_class.__name__,\n                         base_data_element_class.__name__)\n        de_cls = type(name, (base_data_element_class,), {})\n        mp = self.mapping_class(self, mapped_class, de_cls, cfg)\n        de_cls.mapping = mp\n        return mp",
    "docstring": "Creates a new mapping for the given mapped class and representer\n        configuration.\n\n        :param configuration: configuration for the new data element class.\n        :type configuration: :class:`RepresenterConfiguration`\n        :returns: newly created instance of :class:`Mapping`"
  },
  {
    "code": "def QueryService(svc_name):\n  hscm = win32service.OpenSCManager(None, None,\n                                    win32service.SC_MANAGER_ALL_ACCESS)\n  result = None\n  try:\n    hs = win32serviceutil.SmartOpenService(hscm, svc_name,\n                                           win32service.SERVICE_ALL_ACCESS)\n    result = win32service.QueryServiceConfig(hs)\n    win32service.CloseServiceHandle(hs)\n  finally:\n    win32service.CloseServiceHandle(hscm)\n  return result",
    "docstring": "Query service and get its config."
  },
  {
    "code": "def evaluate_forward(\n        distribution,\n        x_data,\n        parameters=None,\n        cache=None,\n):\n    assert len(x_data) == len(distribution), (\n        \"distribution %s is not of length %d\" % (distribution, len(x_data)))\n    assert hasattr(distribution, \"_cdf\"), (\n        \"distribution require the `_cdf` method to function.\")\n    cache = cache if cache is not None else {}\n    parameters = load_parameters(\n        distribution, \"_cdf\", parameters=parameters, cache=cache)\n    cache[distribution] = x_data\n    out = numpy.zeros(x_data.shape)\n    out[:] = distribution._cdf(x_data, **parameters)\n    return out",
    "docstring": "Evaluate forward Rosenblatt transformation.\n\n    Args:\n        distribution (Dist):\n            Distribution to evaluate.\n        x_data (numpy.ndarray):\n            Locations for where evaluate forward transformation at.\n        parameters (:py:data:typing.Any):\n            Collection of parameters to override the default ones in the\n            distribution.\n        cache (:py:data:typing.Any):\n            A collection of previous calculations in case the same distribution\n            turns up on more than one occasion.\n\n    Returns:\n        The cumulative distribution values of ``distribution`` at location\n        ``x_data`` using parameters ``parameters``."
  },
  {
    "code": "def _ready_gzip_fastq(in_files, data, require_bgzip=False):\n    all_gzipped = all([not x or x.endswith(\".gz\") for x in in_files])\n    if require_bgzip and all_gzipped:\n        all_gzipped = all([not x or not _check_gzipped_input(x, data)[0] for x in in_files])\n    needs_convert = dd.get_quality_format(data).lower() == \"illumina\"\n    needs_trim = dd.get_trim_ends(data)\n    do_splitting = dd.get_align_split_size(data) is not False\n    return (all_gzipped and not needs_convert and not do_splitting and\n            not objectstore.is_remote(in_files[0]) and not needs_trim and not get_downsample_params(data))",
    "docstring": "Check if we have gzipped fastq and don't need format conversion or splitting.\n\n    Avoid forcing bgzip if we don't need indexed files."
  },
  {
    "code": "def _start_dev_proc(self,\n                        device_os,\n                        device_config):\n        log.info('Starting the child process for %s', device_os)\n        dos = NapalmLogsDeviceProc(device_os,\n                                   self.opts,\n                                   device_config)\n        os_proc = Process(target=dos.start)\n        os_proc.start()\n        os_proc.description = '%s device process' % device_os\n        log.debug('Started process %s for %s, having PID %s', os_proc._name, device_os, os_proc.pid)\n        return os_proc",
    "docstring": "Start the device worker process."
  },
  {
    "code": "def soft_break(self, el, text):\n        if el.name == 'p' and el.namespace and el.namespace == self.namespaces[\"text\"]:\n            text.append('\\n')",
    "docstring": "Apply soft break if needed."
  },
  {
    "code": "def add_size_scaled_points(\n            self, longitude, latitude, data, shape='o',\n            logplot=False, alpha=1.0, colour='b', smin=2.0, sscale=2.0,\n            overlay=False):\n        if logplot:\n            data = np.log10(data.copy())\n        x, y, = self.m(longitude, latitude)\n        self.m.scatter(x, y,\n                       marker=shape,\n                       s=(smin + data ** sscale),\n                       c=colour,\n                       alpha=alpha,\n                       zorder=2)\n        if not overlay:\n            plt.show()",
    "docstring": "Plots a set of points with size scaled according to the data\n\n        :param bool logplot:\n            Choose to scale according to the logarithm (base 10) of the data\n        :param float smin:\n            Minimum scale size\n        :param float sscale:\n            Scaling factor"
  },
  {
    "code": "def get_agents(self, addr=True, agent_cls=None, as_coro=False):\n        return self.env.get_agents(addr=addr, agent_cls=agent_cls)",
    "docstring": "Get agents from the managed environment.\n\n        This is a managing function for the\n        :py:meth:`~creamas.environment.Environment.get_agents`. Returned\n        agent list excludes the environment's manager agent (this agent) by\n        design."
  },
  {
    "code": "def check_local() -> None:\n    to_check = ['./replay', './replay/toDo', './replay/archive']\n    for i in to_check:\n        if not os.path.exists(i):\n            os.makedirs(i)",
    "docstring": "Verify required directories exist.\n\n    This functions checks the current working directory to ensure that\n    the required directories exist. If they do not exist, it will create them."
  },
  {
    "code": "def to_utf8(value):\n  if isinstance(value, unicode):\n    return value.encode('utf-8')\n  assert isinstance(value, str)\n  return value",
    "docstring": "Returns a string encoded using UTF-8.\n\n  This function comes from `Tornado`_.\n\n  :param value:\n    A unicode or string to be encoded.\n  :returns:\n    The encoded string."
  },
  {
    "code": "def set_mypy_args(self, mypy_args=None):\n        if mypy_args is None:\n            self.mypy_args = None\n        else:\n            self.mypy_errs = []\n            self.mypy_args = list(mypy_args)\n            if not any(arg.startswith(\"--python-version\") for arg in mypy_args):\n                self.mypy_args += [\n                    \"--python-version\",\n                    \".\".join(str(v) for v in get_target_info_len2(self.comp.target, mode=\"nearest\")),\n                ]\n            if logger.verbose:\n                for arg in verbose_mypy_args:\n                    if arg not in self.mypy_args:\n                        self.mypy_args.append(arg)\n            logger.log(\"MyPy args:\", self.mypy_args)",
    "docstring": "Set MyPy arguments."
  },
  {
    "code": "def final_spin_from_f0_tau(f0, tau, l=2, m=2):\n    f0, tau, input_is_array = ensurearray(f0, tau)\n    a, b, c = _berti_spin_constants[l,m]\n    origshape = f0.shape\n    f0 = f0.ravel()\n    tau = tau.ravel()\n    spins = numpy.zeros(f0.size)\n    for ii in range(spins.size):\n        Q = f0[ii] * tau[ii] * numpy.pi\n        try:\n            s = 1. - ((Q-a)/b)**(1./c)\n        except ValueError:\n            s = numpy.nan\n        spins[ii] = s\n    spins = spins.reshape(origshape)\n    return formatreturn(spins, input_is_array)",
    "docstring": "Returns the final spin based on the given frequency and damping time.\n\n    .. note::\n        Currently, only l = m = 2 is supported. Any other indices will raise\n        a ``KeyError``.\n\n    Parameters\n    ----------\n    f0 : float or array\n        Frequency of the QNM (in Hz).\n    tau : float or array\n        Damping time of the QNM (in seconds).\n    l : int, optional\n        l-index of the harmonic. Default is 2.\n    m : int, optional\n        m-index of the harmonic. Default is 2.\n\n    Returns\n    -------\n    float or array\n        The spin of the final black hole. If the combination of frequency\n        and damping times give an unphysical result, ``numpy.nan`` will be\n        returned."
  },
  {
    "code": "def create(self, set):\n        target_url = self.client.get_url('SET', 'POST', 'create')\n        r = self.client.request('POST', target_url, json=set._serialize())\n        return set._deserialize(r.json(), self)",
    "docstring": "Creates a new Set."
  },
  {
    "code": "def backward(self, out_grads=None, is_train=True):\n        if out_grads is None:\n            out_grads = []\n        elif isinstance(out_grads, NDArray):\n            out_grads = [out_grads]\n        elif isinstance(out_grads, dict):\n            out_grads = [out_grads[k] for k in self._symbol.list_outputs()]\n        for obj in out_grads:\n            if not isinstance(obj, NDArray):\n                raise TypeError(\"inputs must be NDArray\")\n        ndarray = c_handle_array(out_grads)\n        check_call(_LIB.MXExecutorBackwardEx(\n            self.handle,\n            mx_uint(len(out_grads)),\n            ndarray,\n            ctypes.c_int(is_train)))",
    "docstring": "Do backward pass to get the gradient of arguments.\n\n        Parameters\n        ----------\n        out_grads : NDArray or list of NDArray or dict of str to NDArray, optional\n            Gradient on the outputs to be propagated back.\n            This parameter is only needed when bind is called\n            on outputs that are not a loss function.\n        is_train : bool, default True\n            Whether this backward is for training or inference. Note that in rare\n            cases you want to call backward with is_train=False to get gradient\n            during inference.\n\n\n        Examples\n        --------\n        >>> # Example for binding on loss function symbol, which gives the loss value of the model.\n        >>> # Equivalently it gives the head gradient for backward pass.\n        >>> # In this example the built-in SoftmaxOutput is used as loss function.\n        >>> # MakeLoss can be used to define customized loss function symbol.\n        >>> net = mx.sym.Variable('data')\n        >>> net = mx.sym.FullyConnected(net, name='fc', num_hidden=6)\n        >>> net = mx.sym.Activation(net, name='relu', act_type=\"relu\")\n        >>> net = mx.sym.SoftmaxOutput(net, name='softmax')\n\n        >>> args =  {'data': mx.nd.ones((1, 4)), 'fc_weight': mx.nd.ones((6, 4)),\n        >>>          'fc_bias': mx.nd.array((1, 4, 4, 4, 5, 6)), 'softmax_label': mx.nd.ones((1))}\n        >>> args_grad = {'fc_weight': mx.nd.zeros((6, 4)), 'fc_bias': mx.nd.zeros((6))}\n        >>> texec = net.bind(ctx=mx.cpu(), args=args, args_grad=args_grad)\n        >>> out = texec.forward(is_train=True)[0].copy()\n        >>> print out.asnumpy()\n        [[ 0.00378404  0.07600445  0.07600445  0.07600445  0.20660152  0.5616011 ]]\n        >>> texec.backward()\n        >>> print(texec.grad_arrays[1].asnumpy())\n        [[ 0.00378404  0.00378404  0.00378404  0.00378404]\n         [-0.92399555 -0.92399555 -0.92399555 -0.92399555]\n         [ 0.07600445  0.07600445  0.07600445  0.07600445]\n         [ 0.07600445  0.07600445  0.07600445  0.07600445]\n         [ 0.20660152  0.20660152  0.20660152  0.20660152]\n         [ 0.5616011   0.5616011   0.5616011   0.5616011 ]]\n        >>>\n        >>> # Example for binding on non-loss function symbol.\n        >>> # Here the binding symbol is neither built-in loss function\n        >>> # nor customized loss created by MakeLoss.\n        >>> # As a result the head gradient is not automatically provided.\n        >>> a = mx.sym.Variable('a')\n        >>> b = mx.sym.Variable('b')\n        >>> # c is not a loss function symbol\n        >>> c = 2 * a + b\n        >>> args = {'a': mx.nd.array([1,2]), 'b':mx.nd.array([2,3])}\n        >>> args_grad = {'a': mx.nd.zeros((2)), 'b': mx.nd.zeros((2))}\n        >>> texec = c.bind(ctx=mx.cpu(), args=args, args_grad=args_grad)\n        >>> out = texec.forward(is_train=True)[0].copy()\n        >>> print(out.asnumpy())\n        [ 4.  7.]\n        >>> # out_grads is the head gradient in backward pass.\n        >>> # Here we define 'c' as loss function.\n        >>> # Then 'out' is passed as head gradient of backward pass.\n        >>> texec.backward(out)\n        >>> print(texec.grad_arrays[0].asnumpy())\n        [ 8.  14.]\n        >>> print(texec.grad_arrays[1].asnumpy())\n        [ 4.  7.]"
  },
  {
    "code": "def age(self):\r\n        if self.date_range is None:\r\n            return\r\n        dob = self.date_range.middle\r\n        today = datetime.date.today()\r\n        if (today.month, today.day) < (dob.month, dob.day):\r\n            return today.year - dob.year - 1\r\n        else:\r\n            return today.year - dob.year",
    "docstring": "int, the estimated age of the person.\r\n        \r\n        Note that A DOB object is based on a date-range and the exact date is \r\n        usually unknown so for age calculation the the middle of the range is \r\n        assumed to be the real date-of-birth."
  },
  {
    "code": "def wait_ready(self, name, timeout=5.0, sleep_interval=0.2):\n        end = time() + timeout\n        while True:\n            try:\n                info = self.bucket_info(name).value\n                for node in info['nodes']:\n                    if node['status'] != 'healthy':\n                        raise NotReadyError.pyexc('Not all nodes are healthy')\n                return\n            except E.CouchbaseError:\n                if time() + sleep_interval > end:\n                    raise\n                sleep(sleep_interval)",
    "docstring": "Wait for a newly created bucket to be ready.\n\n        :param string name: the name to wait for\n        :param seconds timeout: the maximum amount of time to wait\n        :param seconds sleep_interval: the number of time to sleep\n            between each probe\n        :raise: :exc:`.CouchbaseError` on internal HTTP error\n        :raise: :exc:`NotReadyError` if all nodes could not be\n            ready in time"
  },
  {
    "code": "def load(path=None, root=None, db=None, load_user=True):\n    \"Load all of the config files. \"\n    config = load_config(path, load_user=load_user)\n    remotes = load_remotes(path, load_user=load_user)\n    if remotes:\n        if not 'remotes' in config:\n            config.remotes = AttrDict()\n        for k, v in remotes.remotes.items():\n            config.remotes[k] = v\n    accounts = load_accounts(path, load_user=load_user)\n    if accounts:\n        if not 'accounts' in config:\n            config.accounts = AttrDict()\n        for k, v in accounts.accounts.items():\n            config.accounts[k] = v\n    update_config(config)\n    if root:\n        config.library.filesystem_root = root\n    if db:\n        config.library.database = db\n    return config",
    "docstring": "Load all of the config files."
  },
  {
    "code": "def uninstall_packages():\n    p = server_state('packages_installed')\n    if p: installed = set(p)\n    else: return\n    env.uninstalled_packages[env.host] = []\n    packages = set(get_packages())\n    uninstall = installed - packages\n    if uninstall and env.verbosity:\n        print env.host,'UNINSTALLING HOST PACKAGES'\n    for p in uninstall:\n        if env.verbosity:\n            print ' - uninstalling',p\n        uninstall_package(p)\n        env.uninstalled_packages[env.host].append(p)\n    set_server_state('packages_installed',get_packages())\n    return",
    "docstring": "Uninstall unwanted packages"
  },
  {
    "code": "def _is_ctype(self, ctype):\n        if not self.valid:\n            return False\n        mime = self.content_type\n        return self.ContentMimetypes.get(mime) == ctype",
    "docstring": "Return True iff content is valid and of the given type."
  },
  {
    "code": "def protocol_names(self):\n    l = self.protocols()\n    retval = [str(k.name) for k in l]\n    return retval",
    "docstring": "Returns all registered protocol names"
  },
  {
    "code": "def get_file(fname, datapath=datapath):\n    datapath = pathlib.Path(datapath)\n    datapath.mkdir(parents=True, exist_ok=True)\n    dlfile = datapath / fname\n    if not dlfile.exists():\n        print(\"Attempting to download file {} from {} to {}.\".\n              format(fname, webloc, datapath))\n        try:\n            dl_file(url=webloc+fname, dest=dlfile)\n        except BaseException:\n            warnings.warn(\"Download failed: {}\".format(fname))\n            raise\n    return dlfile",
    "docstring": "Return path of an example data file\n\n    Return the full path to an example data file name.\n    If the file does not exist in the `datapath` directory,\n    tries to download it from the ODTbrain GitHub repository."
  },
  {
    "code": "def set_lim(min, max, name):\n    scale = _context['scales'][_get_attribute_dimension(name)]\n    scale.min = min\n    scale.max = max\n    return scale",
    "docstring": "Set the domain bounds of the scale associated with the provided key.\n\n    Parameters\n    ----------\n    name: hashable\n        Any variable that can be used as a key for a dictionary\n\n    Raises\n    ------\n    KeyError\n        When no context figure is associated with the provided key."
  },
  {
    "code": "def _read_snc(snc_file):\n    snc_raw_dtype = dtype([('sampleStamp', '<i'),\n                           ('sampleTime', '<q')])\n    with snc_file.open('rb') as f:\n        f.seek(352)\n        snc_raw = fromfile(f, dtype=snc_raw_dtype)\n    sampleStamp = snc_raw['sampleStamp']\n    sampleTime = asarray([_filetime_to_dt(x) for x in snc_raw['sampleTime']])\n    return sampleStamp, sampleTime",
    "docstring": "Read Synchronization File and return sample stamp and time\n\n    Returns\n    -------\n    sampleStamp : list of int\n        Sample number from start of study\n    sampleTime : list of datetime.datetime\n        File time representation of sampleStamp\n\n    Notes\n    -----\n    The synchronization file is used to calculate a FILETIME given a sample\n    stamp (and vise-versa). Theoretically, it is possible to calculate a sample\n    stamp's FILETIME given the FILETIME of sample stamp zero (when sampling\n    started) and the sample rate. However, because the sample rate cannot be\n    represented with full precision the accuracy of the FILETIME calculation is\n    affected.\n\n    To compensate for the lack of accuracy, the synchronization file maintains\n    a sample stamp-to-computer time (called, MasterTime) mapping. Interpolation\n    is then used to calculate a FILETIME given a sample stamp (and vise-versa).\n\n    The attributes, sampleStamp and sampleTime, are used to predict (using\n    interpolation) the FILETIME based upon a given sample stamp (and\n    vise-versa). Currently, the only use for this conversion process is to\n    enable correlation of EEG (sample_stamp) data with other sources of data\n    such as Video (which works in FILETIME)."
  },
  {
    "code": "def make_client(instance):\n    neutron_client = utils.get_client_class(\n        API_NAME,\n        instance._api_version[API_NAME],\n        API_VERSIONS,\n    )\n    instance.initialize()\n    url = instance._url\n    url = url.rstrip(\"/\")\n    client = neutron_client(username=instance._username,\n                            project_name=instance._project_name,\n                            password=instance._password,\n                            region_name=instance._region_name,\n                            auth_url=instance._auth_url,\n                            endpoint_url=url,\n                            endpoint_type=instance._endpoint_type,\n                            token=instance._token,\n                            auth_strategy=instance._auth_strategy,\n                            insecure=instance._insecure,\n                            ca_cert=instance._ca_cert,\n                            retries=instance._retries,\n                            raise_errors=instance._raise_errors,\n                            session=instance._session,\n                            auth=instance._auth)\n    return client",
    "docstring": "Returns an neutron client."
  },
  {
    "code": "def make_parent_dirs(path, mode=0o777):\n  parent = os.path.dirname(path)\n  if parent:\n    make_all_dirs(parent, mode)\n  return path",
    "docstring": "Ensure parent directories of a file are created as needed."
  },
  {
    "code": "def create_dir_rec(path: Path):\n    if not path.exists():\n        Path.mkdir(path, parents=True, exist_ok=True)",
    "docstring": "Create a folder recursive.\n\n    :param path: path\n    :type path: ~pathlib.Path"
  },
  {
    "code": "def main():\n    logging.basicConfig(format=LOGGING_FORMAT)\n    log = logging.getLogger(__name__)\n    parser = argparse.ArgumentParser()\n    add_debug(parser)\n    add_app(parser)\n    add_env(parser)\n    add_properties(parser)\n    args = parser.parse_args()\n    logging.getLogger(__package__.split(\".\")[0]).setLevel(args.debug)\n    log.debug('Parsed arguements: %s', args)\n    if \"prod\" not in args.env:\n        log.info('No slack message sent, not a production environment')\n    else:\n        log.info(\"Sending slack message, production environment\")\n        slacknotify = SlackNotification(app=args.app, env=args.env, prop_path=args.properties)\n        slacknotify.post_message()",
    "docstring": "Send Slack notification to a configured channel."
  },
  {
    "code": "def merge_rdf_list(rdf_list):\n    if isinstance(rdf_list, list):\n        rdf_list = rdf_list[0]\n    rtn_list = []\n    item = rdf_list\n    if item.get('rdf_rest') and item.get('rdf_rest',[1])[0] != 'rdf_nil':\n        rtn_list += merge_rdf_list(item['rdf_rest'][0])\n    if item.get('rdf_first'):\n        rtn_list += item['rdf_first']\n    rtn_list.reverse()\n    return rtn_list",
    "docstring": "takes an rdf list and merges it into a python list\n\n    args:\n        rdf_list: the RdfDataset object with the list values\n\n    returns:\n        list of values"
  },
  {
    "code": "def inverse_transform(self, Y, columns=None):\n        try:\n            if not hasattr(self, \"data_pca\"):\n                try:\n                    if Y.shape[1] != self.data_nu.shape[1]:\n                        raise ValueError\n                except IndexError:\n                    raise ValueError\n                if columns is None:\n                    return Y\n                else:\n                    columns = np.array([columns]).flatten()\n                    return Y[:, columns]\n            else:\n                if columns is None:\n                    return self.data_pca.inverse_transform(Y)\n                else:\n                    columns = np.array([columns]).flatten()\n                    Y_inv = np.dot(Y, self.data_pca.components_[:, columns])\n                    if hasattr(self.data_pca, \"mean_\"):\n                        Y_inv += self.data_pca.mean_[columns]\n                    return Y_inv\n        except ValueError:\n            raise ValueError(\"data of shape {} cannot be inverse transformed\"\n                             \" from graph built on data of shape {}\".format(\n                                 Y.shape, self.data_nu.shape))",
    "docstring": "Transform input data `Y` to ambient data space defined by `self.data`\n\n        Takes data in the same reduced space as `self.data_nu` and transforms\n        it to be in the same ambient space as `self.data`.\n\n        Parameters\n        ----------\n        Y : array-like, shape=[n_samples_y, n_pca]\n            n_features must be the same as `self.data_nu`.\n        columns : list-like\n            list of integers referring to column indices in the original data\n            space to be returned. Avoids recomputing the full matrix where only\n            a few dimensions of the ambient space are of interest\n\n        Returns\n        -------\n        Inverse transformed data, shape=[n_samples_y, n_features]\n\n        Raises\n        ------\n        ValueError : if Y.shape[1] != self.data_nu.shape[1]"
  },
  {
    "code": "def encode_numpy(array):\n    return {'data' : base64.b64encode(array.data).decode('utf8'),\n            'type' : array.dtype.name,\n            'shape': array.shape}",
    "docstring": "Encode a numpy array as a base64 encoded string, to be JSON serialized. \n\n    :return: a dictionary containing the fields:\n                - *data*: the base64 string\n                - *type*: the array type\n                - *shape*: the array shape"
  },
  {
    "code": "def frameify(self, state, data):\n        try:\n            yield state.recv_buf + data\n        except FrameSwitch:\n            pass\n        finally:\n            state.recv_buf = ''",
    "docstring": "Yield the data as a single frame."
  },
  {
    "code": "def from_dict(cls, d):\n        def _from_dict(_d):\n            return AdfKey.from_dict(_d) if _d is not None else None\n        operation = d.get(\"operation\")\n        title = d.get(\"title\")\n        basis_set = _from_dict(d.get(\"basis_set\"))\n        xc = _from_dict(d.get(\"xc\"))\n        units = _from_dict(d.get(\"units\"))\n        scf = _from_dict(d.get(\"scf\"))\n        others = [AdfKey.from_dict(o) for o in d.get(\"others\", [])]\n        geo = _from_dict(d.get(\"geo\"))\n        return cls(operation, basis_set, xc, title, units, geo.subkeys, scf,\n                   others)",
    "docstring": "Construct a MSONable AdfTask object from the JSON dict.\n\n        Parameters\n        ----------\n        d : dict\n            A dict of saved attributes.\n\n        Returns\n        -------\n        task : AdfTask\n            An AdfTask object recovered from the JSON dict ``d``."
  },
  {
    "code": "def _compile(self, source, filename):\n        if filename == '<template>':\n            filename = 'dbt-{}'.format(\n                codecs.encode(os.urandom(12), 'hex').decode('ascii')\n            )\n            filename = jinja2._compat.encode_filename(filename)\n            linecache.cache[filename] = (\n                len(source),\n                None,\n                [line + '\\n' for line in source.splitlines()],\n                filename\n            )\n        return super(MacroFuzzEnvironment, self)._compile(source, filename)",
    "docstring": "Override jinja's compilation to stash the rendered source inside\n        the python linecache for debugging."
  },
  {
    "code": "def _get_opus_maximum(self):\n        label =\n        opmax = self.session.get_resource(\n            BASE_URI_TYPES % \"opmax\",\n            self.session.get_class(surf.ns.ECRM['E55_Type'])\n        )\n        if opmax.is_present():\n            return opmax\n        else:\n            opmax.rdfs_label.append(Literal(label, \"en\"))\n            logger.debug(\"Created a new opus maximum type instance\")\n            opmax.save()\n            return opmax",
    "docstring": "Instantiate an opus maximum type."
  },
  {
    "code": "def wsgi_proxyfix(factory=None):\n    def create_wsgi(app, **kwargs):\n        wsgi_app = factory(app, **kwargs) if factory else app.wsgi_app\n        if app.config.get('WSGI_PROXIES'):\n            return ProxyFix(wsgi_app, num_proxies=app.config['WSGI_PROXIES'])\n        return wsgi_app\n    return create_wsgi",
    "docstring": "Fix ``REMOTE_ADDR`` based on ``X-Forwarded-For`` headers.\n\n    .. note::\n\n       You must set ``WSGI_PROXIES`` to the correct number of proxies,\n       otherwise you application is susceptible to malicious attacks.\n\n    .. versionadded:: 1.0.0"
  },
  {
    "code": "def fit(self, train_set, test_set):\n        with tf.Graph().as_default(), tf.Session() as self.tf_session:\n            self.build_model()\n            tf.global_variables_initializer().run()\n            third = self.num_epochs // 3\n            for i in range(self.num_epochs):\n                lr_decay = self.lr_decay ** max(i - third, 0.0)\n                self.tf_session.run(\n                    tf.assign(self.lr_var, tf.multiply(self.learning_rate, lr_decay)))\n                train_perplexity = self._run_train_step(train_set, 'train')\n                print(\"Epoch: %d Train Perplexity: %.3f\"\n                      % (i + 1, train_perplexity))\n            test_perplexity = self._run_train_step(test_set, 'test')\n            print(\"Test Perplexity: %.3f\" % test_perplexity)",
    "docstring": "Fit the model to the given data.\n\n        :param train_set: training data\n        :param test_set: test data"
  },
  {
    "code": "def write(self, filename):\n        if not filename.endswith(('.mid', '.midi', '.MID', '.MIDI')):\n            filename = filename + '.mid'\n        pm = self.to_pretty_midi()\n        pm.write(filename)",
    "docstring": "Write the multitrack pianoroll to a MIDI file.\n\n        Parameters\n        ----------\n        filename : str\n            The name of the MIDI file to which the multitrack pianoroll is\n            written."
  },
  {
    "code": "def _run_parallel_multiprocess(self):\n        _log.debug(\"run.parallel.multiprocess.start\")\n        processes = []\n        ProcRunner.instance = self\n        for i in range(self._ncores):\n            self._status.running(i)\n            proc = multiprocessing.Process(target=ProcRunner.run, args=(i,))\n            proc.start()\n            processes.append(proc)\n        for i in range(self._ncores):\n            processes[i].join()\n            code = processes[i].exitcode\n            self._status.success(i) if 0 == code else self._status.fail(i)\n        _log.debug(\"run.parallel.multiprocess.end states={}\".format(self._status))",
    "docstring": "Run processes from queue"
  },
  {
    "code": "def google_storage_url(self, sat):\n        filename = sat['scene'] + '.tar.bz'\n        return url_builder([self.google, sat['sat'], sat['path'], sat['row'], filename])",
    "docstring": "Returns a google storage url the contains the scene provided.\n\n        :param sat:\n            Expects an object created by scene_interpreter method\n        :type sat:\n            dict\n\n        :returns:\n            (String) The URL to a google storage file"
  },
  {
    "code": "def stringify(data):\n    ret = []\n    for item in data:\n        if six.PY2 and isinstance(item, str):\n            item = salt.utils.stringutils.to_unicode(item)\n        elif not isinstance(item, six.string_types):\n            item = six.text_type(item)\n        ret.append(item)\n    return ret",
    "docstring": "Given an iterable, returns its items as a list, with any non-string items\n    converted to unicode strings."
  },
  {
    "code": "def get_eventhub_host(self):\n        for protocol in self.service.settings.data['publish']['protocol_details']:\n            if protocol['protocol'] == 'grpc':\n                return protocol['uri'][0:protocol['uri'].index(':')]",
    "docstring": "returns the publish grpc endpoint for ingestion."
  },
  {
    "code": "def edge_cost(self, node_a, node_b):\n        cost = float('inf')\n        node_object_a = self.get_node(node_a)\n        for edge_id in node_object_a['edges']:\n            edge = self.get_edge(edge_id)\n            tpl = (node_a, node_b)\n            if edge['vertices'] == tpl:\n                cost = edge['cost']\n                break\n        return cost",
    "docstring": "Returns the cost of moving between the edge that connects node_a to node_b.\n        Returns +inf if no such edge exists."
  },
  {
    "code": "def get_default_property_values(self, classname):\n        schema_element = self.get_element_by_class_name(classname)\n        result = {\n            property_name: property_descriptor.default\n            for property_name, property_descriptor in six.iteritems(schema_element.properties)\n        }\n        if schema_element.is_edge:\n            result.pop(EDGE_SOURCE_PROPERTY_NAME, None)\n            result.pop(EDGE_DESTINATION_PROPERTY_NAME, None)\n        return result",
    "docstring": "Return a dict with default values for all properties declared on this class."
  },
  {
    "code": "def after_loop(self, coro):\n        if not (inspect.iscoroutinefunction(coro) or inspect.isawaitable(coro)):\n            raise TypeError('Expected coroutine or awaitable, received {0.__name__!r}.'.format(type(coro)))\n        self._after_loop = coro",
    "docstring": "A function that also acts as a decorator to register a coroutine to be\n        called after the loop finished running.\n\n        Parameters\n        ------------\n        coro: :term:`py:awaitable`\n            The coroutine to register after the loop finishes.\n\n        Raises\n        -------\n        TypeError\n            The function was not a coroutine."
  },
  {
    "code": "def add_serviceListener(self, type, listener):\n        self.remove_service_listener(listener)\n        self.browsers.append(ServiceBrowser(self, type, listener))",
    "docstring": "Adds a listener for a particular service type.  This object\n        will then have its update_record method called when information\n        arrives for that type."
  },
  {
    "code": "def getRequiredNodes(self):\n        return {nodeShape:len(self.nodeReservations[nodeShape]) for nodeShape in self.nodeShapes}",
    "docstring": "Returns a dict from node shape to number of nodes required to run the packed jobs."
  },
  {
    "code": "def get_status(self):\n        status = self.get('status')\n        if status == Report.PASSED:\n            for sr_name in self._sub_reports:\n                sr = self._sub_reports[sr_name]\n                sr_status = sr.get_status()\n                reason = sr.get('reason')\n                if sr_status == Report.ERROR:\n                    self.error(reason)\n                    break\n                if sr_status == Report.FAILED:\n                    self.failed(reason)\n                    break\n            status = self.get('status')\n        return status",
    "docstring": "Get the status of the report and its sub-reports.\n\n        :rtype: str\n        :return: report status ('passed', 'failed' or 'error')"
  },
  {
    "code": "def _lease_owned(self, lease, current_uuid_path):\n        prev_uuid_path, prev_uuid = lease.metadata\n        with open(current_uuid_path) as f:\n            current_uuid = f.read()\n        return \\\n            current_uuid_path == prev_uuid_path and \\\n            prev_uuid == current_uuid",
    "docstring": "Checks if the given lease is owned by the prefix whose uuid is in\n        the given path\n\n        Note:\n            The prefix must be also in the same path it was when it took the\n            lease\n\n        Args:\n            path (str): Path to the lease\n            current_uuid_path (str): Path to the uuid to check ownership of\n\n        Returns:\n            bool: ``True`` if the given lease in owned by the prefix,\n                ``False`` otherwise"
  },
  {
    "code": "def build(obj: Any, *applicators: Callable[..., Any]) -> Any:\n    if isinstance(obj, BaseChain):\n        return pipe(obj, copy(), *applicators)\n    else:\n        return pipe(obj, *applicators)",
    "docstring": "Run the provided object through the series of applicator functions.\n\n    If ``obj`` is an instances of :class:`~eth.chains.base.BaseChain` the\n    applicators will be run on a copy of the chain and thus will not mutate the\n    provided chain instance."
  },
  {
    "code": "def _has_sj_index(ref_file):\n    return (file_exists(os.path.join(ref_file, \"sjdbInfo.txt\")) and\n            (file_exists(os.path.join(ref_file, \"transcriptInfo.tab\"))))",
    "docstring": "this file won't exist if we can do on the fly splice junction indexing"
  },
  {
    "code": "def recover(self, requeue=False, cb=None):\n        args = Writer()\n        args.write_bit(requeue)\n        self._recover_cb.append(cb)\n        self.send_frame(MethodFrame(self.channel_id, 60, 110, args))\n        self.channel.add_synchronous_cb(self._recv_recover_ok)",
    "docstring": "Ask server to redeliver all unacknowledged messages."
  },
  {
    "code": "def get_preservation_info(self, obj):\n        info = self.get_base_info(obj)\n        info.update({})\n        return info",
    "docstring": "Returns the info for a Preservation"
  },
  {
    "code": "def _get_vispy_caller():\n    records = inspect.stack()\n    for record in records[5:]:\n        module = record[0].f_globals['__name__']\n        if module.startswith('vispy'):\n            line = str(record[0].f_lineno)\n            func = record[3]\n            cls = record[0].f_locals.get('self', None)\n            clsname = \"\" if cls is None else cls.__class__.__name__ + '.'\n            caller = \"{0}:{1}{2}({3}): \".format(module, clsname, func, line)\n            return caller\n    return 'unknown'",
    "docstring": "Helper to get vispy calling function from the stack"
  },
  {
    "code": "def clear(self):\n        with self.__svc_lock:\n            self.__svc_registry.clear()\n            self.__svc_factories.clear()\n            self.__svc_specs.clear()\n            self.__bundle_svc.clear()\n            self.__bundle_imports.clear()\n            self.__factory_usage.clear()\n            self.__pending_services.clear()",
    "docstring": "Clears the registry"
  },
  {
    "code": "def convertSequenceMachineSequence(generatedSequences):\n  sequenceList = []\n  currentSequence = []\n  for s in generatedSequences:\n    if s is None:\n      sequenceList.append(currentSequence)\n      currentSequence = []\n    else:\n      currentSequence.append(s)\n  return sequenceList",
    "docstring": "Convert a sequence from the SequenceMachine into a list of sequences, such\n  that each sequence is a list of set of SDRs."
  },
  {
    "code": "def is_text_visible(driver, text, selector, by=By.CSS_SELECTOR):\n    try:\n        element = driver.find_element(by=by, value=selector)\n        return element.is_displayed() and text in element.text\n    except Exception:\n        return False",
    "docstring": "Returns whether the specified text is visible in the specified selector.\n    @Params\n    driver - the webdriver object (required)\n    text - the text string to search for\n    selector - the locator that is used (required)\n    by - the method to search for the locator (Default: By.CSS_SELECTOR)\n    @Returns\n    Boolean (is text visible)"
  },
  {
    "code": "def has_all_nonzero_neurite_radii(neuron, threshold=0.0):\n    bad_ids = []\n    seen_ids = set()\n    for s in _nf.iter_sections(neuron):\n        for i, p in enumerate(s.points):\n            info = (s.id, i)\n            if p[COLS.R] <= threshold and info not in seen_ids:\n                seen_ids.add(info)\n                bad_ids.append(info)\n    return CheckResult(len(bad_ids) == 0, bad_ids)",
    "docstring": "Check presence of neurite points with radius not above threshold\n\n    Arguments:\n        neuron(Neuron): The neuron object to test\n        threshold: value above which a radius is considered to be non-zero\n\n    Returns:\n        CheckResult with result including list of (section ID, point ID) pairs\n        of zero-radius points"
  },
  {
    "code": "def read(filename, data_wrapper=DataWrapper):\n    data = np.loadtxt(filename)\n    if len(np.shape(data)) == 1:\n        data = np.reshape(data, (1, -1))\n    data = data[:, [X, Y, Z, R, TYPE, ID, P]]\n    return data_wrapper(data, 'SWC', None)",
    "docstring": "Read an SWC file and return a tuple of data, format."
  },
  {
    "code": "async def set_config(self, on=None, tholddark=None, tholdoffset=None):\n        data = {\n            key: value for key, value in {\n                'on': on,\n                'tholddark': tholddark,\n                'tholdoffset': tholdoffset,\n            }.items() if value is not None\n        }\n        await self._request('put', 'sensors/{}/config'.format(self.id),\n                            json=data)",
    "docstring": "Change config of a CLIP LightLevel sensor."
  },
  {
    "code": "def board_msg(self):\n        board_str = \"s\\t\\t\"\n        for i in xrange(self.board_width):\n            board_str += str(i)+\"\\t\"\n        board_str = board_str.expandtabs(4)+\"\\n\\n\"\n        for i in xrange(self.board_height):\n            temp_line = str(i)+\"\\t\\t\"\n            for j in xrange(self.board_width):\n                if self.info_map[i, j] == 9:\n                    temp_line += \"@\\t\"\n                elif self.info_map[i, j] == 10:\n                    temp_line += \"?\\t\"\n                elif self.info_map[i, j] == 11:\n                    temp_line += \"*\\t\"\n                elif self.info_map[i, j] == 12:\n                    temp_line += \"!\\t\"\n                else:\n                    temp_line += str(self.info_map[i, j])+\"\\t\"\n            board_str += temp_line.expandtabs(4)+\"\\n\"\n        return board_str",
    "docstring": "Structure a board as in print_board."
  },
  {
    "code": "def daily_bounds(network, snapshots):\n    sus = network.storage_units\n    network.model.period_starts = network.snapshot_weightings.index[0::24]\n    network.model.storages = sus.index\n    def day_rule(m, s, p):\n        return (\n              m.state_of_charge[s, p] ==\n               m.state_of_charge[s, p + pd.Timedelta(hours=23)])\n    network.model.period_bound = po.Constraint(\n            network.model.storages, network.model.period_starts, rule=day_rule)",
    "docstring": "This will bound the storage level to 0.5 max_level every 24th hour."
  },
  {
    "code": "def get_items(self, collection_uri):\n        cname = os.path.split(collection_uri)[1]\n        return self.search_metadata(\"collection_name:%s\" % cname)",
    "docstring": "Return all items in this collection.\n\n        :param collection_uri: The URI that references the collection\n        :type collection_uri: String\n\n        :rtype: List\n        :returns: a list of the URIs of the items in this collection"
  },
  {
    "code": "def create_single_poll_submission(self, poll_id, poll_session_id, poll_submissions_poll_choice_id):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"poll_id\"] = poll_id\r\n        path[\"poll_session_id\"] = poll_session_id\r\n        data[\"poll_submissions[poll_choice_id]\"] = poll_submissions_poll_choice_id\r\n        self.logger.debug(\"POST /api/v1/polls/{poll_id}/poll_sessions/{poll_session_id}/poll_submissions with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"POST\", \"/api/v1/polls/{poll_id}/poll_sessions/{poll_session_id}/poll_submissions\".format(**path), data=data, params=params, no_data=True)",
    "docstring": "Create a single poll submission.\r\n\r\n        Create a new poll submission for this poll session"
  },
  {
    "code": "def start_session_if_none(self):\n        if not (self._screen_id and self._session):\n            self.update_screen_id()\n            self._session = YouTubeSession(screen_id=self._screen_id)",
    "docstring": "Starts a session it is not yet initialized."
  },
  {
    "code": "def addOutParameter(self, name, type, namespace=None, element_type=0):\n        parameter = ParameterInfo(name, type, namespace, element_type)\n        self.outparams.append(parameter)\n        return parameter",
    "docstring": "Add an output parameter description to the call info."
  },
  {
    "code": "def max(self, values, axis=0):\n        values = np.asarray(values)\n        return self.unique, self.reduce(values, np.maximum, axis)",
    "docstring": "return the maximum within each group\n\n        Parameters\n        ----------\n        values : array_like, [keys, ...]\n            values to take maximum of per group\n        axis : int, optional\n            alternative reduction axis for values\n\n        Returns\n        -------\n        unique: ndarray, [groups]\n            unique keys\n        reduced : ndarray, [groups, ...]\n            value array, reduced over groups"
  },
  {
    "code": "def _RawData(self, data):\n    if not isinstance(data, dict):\n      return data\n    result = collections.OrderedDict()\n    for k, v in iteritems(data):\n      result[k] = self._RawData(v)\n    return result",
    "docstring": "Convert data to common format.\n\n    Configuration options are normally grouped by the functional component which\n    define it (e.g. Logging.path is the path parameter for the logging\n    subsystem). However, sometimes it is more intuitive to write the config as a\n    flat string (e.g. Logging.path). In this case we group all the flat strings\n    in their respective sections and create the sections automatically.\n\n    Args:\n      data: A dict of raw data.\n\n    Returns:\n      a dict in common format. Any keys in the raw data which have a \".\" in them\n      are separated into their own sections. This allows the config to be\n      written explicitly in dot notation instead of using a section."
  },
  {
    "code": "def dispatch(self):\n        method_name = 'on_' + self.environ['REQUEST_METHOD'].lower()\n        method = getattr(self, method_name, None)\n        if method:\n            return method()\n        else:\n            return self.on_bad_method()",
    "docstring": "Handles dispatching of the request."
  },
  {
    "code": "def parse_runway_config(self):\n        if not os.path.isfile(self.runway_config_path):\n            LOGGER.error(\"Runway config file was not found (looking for \"\n                         \"%s)\",\n                         self.runway_config_path)\n            sys.exit(1)\n        with open(self.runway_config_path) as data_file:\n            return yaml.safe_load(data_file)",
    "docstring": "Read and parse runway.yml."
  },
  {
    "code": "def generate_new_cid(upstream_cid=None):\n    if upstream_cid is None:\n        return str(uuid.uuid4()) if getattr(settings, 'CID_GENERATE', False) else None\n    if (\n            getattr(settings, 'CID_CONCATENATE_IDS', False)\n            and getattr(settings, 'CID_GENERATE', False)\n    ):\n        return '%s, %s' % (upstream_cid, str(uuid.uuid4()))\n    return upstream_cid",
    "docstring": "Generate a new correlation id, possibly based on the given one."
  },
  {
    "code": "def genlmsg_parse(nlh, hdrlen, tb, maxtype, policy):\n    if not genlmsg_valid_hdr(nlh, hdrlen):\n        return -NLE_MSG_TOOSHORT\n    ghdr = genlmsghdr(nlmsg_data(nlh))\n    return int(nla_parse(tb, maxtype, genlmsg_attrdata(ghdr, hdrlen), genlmsg_attrlen(ghdr, hdrlen), policy))",
    "docstring": "Parse Generic Netlink message including attributes.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L191\n\n    Verifies the validity of the Netlink and Generic Netlink headers using genlmsg_valid_hdr() and calls nla_parse() on\n    the message payload to parse eventual attributes.\n\n    Positional arguments:\n    nlh -- Netlink message header (nlmsghdr class instance).\n    hdrlen -- length of user header (integer).\n    tb -- empty dict, to be updated with nlattr class instances to store parsed attributes.\n    maxtype -- maximum attribute id expected (integer).\n    policy -- dictionary of nla_policy class instances as values, with nla types as keys.\n\n    Returns:\n    0 on success or a negative error code."
  },
  {
    "code": "def get_precursor_mz(exact_mass, precursor_type):\n    d = {'[M-H]-': -1.007276,\n         '[M+H]+': 1.007276,\n         '[M+H-H2O]+': 1.007276 - ((1.007276 * 2) + 15.9949)\n         }\n    try:\n        return exact_mass + d[precursor_type]\n    except KeyError as e:\n        print(e)\n        return False",
    "docstring": "Calculate precursor mz based on exact mass and precursor type\n\n    Args:\n        exact_mass (float): exact mass of compound of interest\n        precursor_type (str): Precursor type (currently only works with '[M-H]-', '[M+H]+' and '[M+H-H2O]+'\n\n    Return:\n          neutral mass of compound"
  },
  {
    "code": "def _link(self, next_worker, next_is_first=False):\n        lock = multiprocessing.Lock()\n        next_worker._lock_prev_input = lock\n        self._lock_next_input = lock\n        lock.acquire()\n        lock = multiprocessing.Lock()\n        next_worker._lock_prev_output = lock\n        self._lock_next_output = lock\n        lock.acquire()\n        if next_is_first:\n            self._lock_next_input.release()\n            self._lock_next_output.release()",
    "docstring": "Link the worker to the given next worker object, \n        connecting the two workers with communication tubes."
  },
  {
    "code": "def run(self):\n        self.show()\n        if not self.wait:\n            return\n        for image in self.slides:\n            wait = image.get('time', 0)\n            wait = max(self.wait, wait)\n            print('waiting %d seconds %s' % (\n                wait, image.get('image', '')))\n            yield image\n            time.sleep(wait)\n            self.next()",
    "docstring": "Run the show"
  },
  {
    "code": "def getSubstitutionElement(self, elt, ps):\n        nsuri,ncname = _get_element_nsuri_name(elt)\n        typecode = GED(nsuri,ncname)\n        if typecode is None:\n            return\n        try:\n            nsuri,ncname = typecode.substitutionGroup\n        except (AttributeError, TypeError):\n            return\n        if (ncname == self.pname) and (nsuri == self.nspname or \n           (not nsuri and not self.nspname)):\n             return typecode\n        return",
    "docstring": "if elt matches a member of the head substitutionGroup, return \n        the GED typecode representation of the member.\n\n        head -- ElementDeclaration typecode, \n        elt -- the DOM element being parsed\n        ps -- ParsedSoap instance"
  },
  {
    "code": "def tags_context(self, worker_ctx, exc_info):\n        tags = {\n            'call_id': worker_ctx.call_id,\n            'parent_call_id': worker_ctx.immediate_parent_call_id,\n            'service_name': worker_ctx.container.service_name,\n            'method_name': worker_ctx.entrypoint.method_name\n        }\n        for key in worker_ctx.context_data:\n            for matcher in self.tag_type_context_keys:\n                if re.search(matcher, key):\n                    tags[key] = worker_ctx.context_data[key]\n                    break\n        self.client.tags_context(tags)",
    "docstring": "Merge any tags to include in the sentry payload."
  },
  {
    "code": "def set_cmap(cmap):\n    scale = _context['scales']['color']\n    for k, v in _process_cmap(cmap).items():\n        setattr(scale, k, v)\n    return scale",
    "docstring": "Set the color map of the current 'color' scale."
  },
  {
    "code": "def register_gid(self, tiled_gid, flags=None):\n        if flags is None:\n            flags = TileFlags(0, 0, 0)\n        if tiled_gid:\n            try:\n                return self.imagemap[(tiled_gid, flags)][0]\n            except KeyError:\n                gid = self.maxgid\n                self.maxgid += 1\n                self.imagemap[(tiled_gid, flags)] = (gid, flags)\n                self.gidmap[tiled_gid].append((gid, flags))\n                self.tiledgidmap[gid] = tiled_gid\n                return gid\n        else:\n            return 0",
    "docstring": "Used to manage the mapping of GIDs between the tmx and pytmx\n\n        :param tiled_gid: GID that is found in TMX data\n        :rtype: GID that pytmx uses for the the GID passed"
  },
  {
    "code": "def _info_transformers(fields, transformers):\n    if transformers is None:\n        transformers = dict()\n    for f in fields:\n        if f not in transformers:\n            transformers[f] = config.DEFAULT_TRANSFORMER.get(f, None)\n    return tuple(transformers[f] for f in fields)",
    "docstring": "Utility function to determine transformer functions for variants\n    fields."
  },
  {
    "code": "def change_return_type(f):\n    @wraps(f)\n    def wrapper(*args, **kwargs):\n        if kwargs.has_key('return_type'):\n            return_type = kwargs['return_type']\n            kwargs.pop('return_type')\n            return return_type(f(*args, **kwargs))\n        elif len(args) > 0:\n            return_type = type(args[0])\n            return return_type(f(*args, **kwargs))\n        else:\n            return f(*args, **kwargs)\n    return wrapper",
    "docstring": "Converts the returned value of wrapped function to the type of the\n    first arg or to the type specified by a kwarg key return_type's value."
  },
  {
    "code": "def show_graph_summary(g):\n    sample_data = []\n    print(\"list(g[RDFS.Class]) = \" + str(len(list(g[RDFS.Class]))))\n    num_subj = 0\n    for subj in g.subjects(RDF.type):\n        num_subj += 1\n        if num_subj < 5:\n            sample_data.append(\"subjects.subject: \" + get_string_from_rdf(subj))\n    print(\"g.subjects(RDF.type) = \" + str(num_subj))\n    num_subj = 0\n    for subj, pred, obj in g:\n        num_subj += 1\n        if num_subj < 5:\n            sample_data.append(\"g.subject   : \" + get_string_from_rdf(pred))\n            sample_data.append(\"g.predicate : \" + get_string_from_rdf(subj))\n            sample_data.append(\"g.object    : \" + get_string_from_rdf(obj))\n    print(\"g.obj(RDF.type) = \" + str(num_subj))\n    print (\"------ Sample Data ------\")\n    for line in sample_data:\n        print(line)",
    "docstring": "display sample data from a graph"
  },
  {
    "code": "def get_runtime_value(self, ihcid: int):\n        if self.client.get_runtime_value(ihcid):\n            return True\n        self.re_authenticate()\n        return self.client.get_runtime_value(ihcid)",
    "docstring": "Get runtime value with re-authenticate if needed"
  },
  {
    "code": "def _ScheduleVariableHunt(hunt_obj):\n  if hunt_obj.client_rate != 0:\n    raise VariableHuntCanNotHaveClientRateError(hunt_obj.hunt_id,\n                                                hunt_obj.client_rate)\n  seen_clients = set()\n  for flow_group in hunt_obj.args.variable.flow_groups:\n    for client_id in flow_group.client_ids:\n      if client_id in seen_clients:\n        raise CanStartAtMostOneFlowPerClientError(hunt_obj.hunt_id, client_id)\n      seen_clients.add(client_id)\n  now = rdfvalue.RDFDatetime.Now()\n  for flow_group in hunt_obj.args.variable.flow_groups:\n    flow_cls = registry.FlowRegistry.FlowClassByName(flow_group.flow_name)\n    flow_args = flow_group.flow_args if flow_group.HasField(\n        \"flow_args\") else None\n    for client_id in flow_group.client_ids:\n      flow.StartFlow(\n          client_id=client_id,\n          creator=hunt_obj.creator,\n          cpu_limit=hunt_obj.per_client_cpu_limit,\n          network_bytes_limit=hunt_obj.per_client_network_bytes_limit,\n          flow_cls=flow_cls,\n          flow_args=flow_args,\n          start_at=now,\n          parent_hunt_id=hunt_obj.hunt_id)",
    "docstring": "Schedules flows for a variable hunt."
  },
  {
    "code": "def check_overlap(pos, ins, thresh):\n    ins_pos = ins[0]\n    ins_len = ins[2]\n    ol = overlap(ins_pos, pos)\n    feat_len = pos[1] - pos[0] + 1\n    if float(ol) / float(feat_len) >= thresh:\n        return True\n    return False",
    "docstring": "make sure thresh % feature is contained within insertion"
  },
  {
    "code": "def from_string(cls, s):\n        log.debug(\"Parsing email from string\")\n        message = email.message_from_string(s)\n        return cls(message)",
    "docstring": "Init a new object from a string.\n\n        Args:\n            s (string): raw email\n\n        Returns:\n            Instance of MailParser"
  },
  {
    "code": "def exit_code_from_run_infos(run_infos: t.List[RunInfo]) -> int:\n    assert run_infos is not None\n    if not hasattr(run_infos, \"__iter__\"):\n        return run_infos.retcode\n    rcs = [ri.retcode for ri in run_infos]\n    max_rc = max(rcs)\n    min_rc = min(rcs)\n    if max_rc == 0:\n        return min_rc\n    return max_rc",
    "docstring": "Generate a single exit code from a list of RunInfo objects.\n\n    Takes a list of RunInfos and returns the exit code that is furthest away\n    from 0.\n\n    Args:\n        run_infos (t.List[RunInfo]): [description]\n\n    Returns:\n        int: [description]"
  },
  {
    "code": "def task_done(self, message):\n        topic_partition = (message.topic, message.partition)\n        if topic_partition not in self._topics:\n            logger.warning('Unrecognized topic/partition in task_done message: '\n                           '{0}:{1}'.format(*topic_partition))\n            return False\n        offset = message.offset\n        prev_done = self._offsets.task_done[topic_partition]\n        if prev_done is not None and offset != (prev_done + 1):\n            logger.warning('Marking task_done on a non-continuous offset: %d != %d + 1',\n                           offset, prev_done)\n        prev_commit = self._offsets.commit[topic_partition]\n        if prev_commit is not None and ((offset + 1) <= prev_commit):\n            logger.warning('Marking task_done on a previously committed offset?: %d (+1) <= %d',\n                           offset, prev_commit)\n        self._offsets.task_done[topic_partition] = offset\n        if self._does_auto_commit_messages():\n            self._incr_auto_commit_message_count()\n        if self._should_auto_commit():\n            self.commit()\n        return True",
    "docstring": "Mark a fetched message as consumed.\n\n        Offsets for messages marked as \"task_done\" will be stored back\n        to the kafka cluster for this consumer group on commit()\n\n        Arguments:\n            message (KafkaMessage): the message to mark as complete\n\n        Returns:\n            True, unless the topic-partition for this message has not\n            been configured for the consumer. In normal operation, this\n            should not happen. But see github issue 364."
  },
  {
    "code": "def load_elements(self, elements):\n        \"Initialize the internal element structures\"\n        self.pg_no = 0\n        self.elements = elements\n        self.keys = [v['name'].lower() for v in self.elements]",
    "docstring": "Initialize the internal element structures"
  },
  {
    "code": "def get_decorators(self, node):\n        if node.parent is None:\n            return []\n        results = {}\n        if not self.decorated.match(node.parent, results):\n            return []\n        decorators = results.get('dd') or [results['d']]\n        decs = []\n        for d in decorators:\n            for child in d.children:\n                if isinstance(child, Leaf) and child.type == token.NAME:\n                    decs.append(child.value)\n        return decs",
    "docstring": "Return a list of decorators found on a function definition.\n\n        This is a list of strings; only simple decorators\n        (e.g. @staticmethod) are returned.\n\n        If the function is undecorated or only non-simple decorators\n        are found, return []."
  },
  {
    "code": "def suspend_zone(self, days, zone=None):\n        if zone is None:\n            zone_cmd = 'suspendall'\n            relay_id = None\n        else:\n            if zone < 0 or zone > (len(self.relays) - 1):\n                return None\n            else:\n                zone_cmd = 'suspend'\n                relay_id = self.relays[zone]['relay_id']\n        if days <= 0:\n            time_cmd = 0\n        else:\n            time_cmd = time.mktime(time.localtime()) + (days * 86400)\n        return set_zones(self._user_token, zone_cmd, relay_id, time_cmd)",
    "docstring": "Suspend or unsuspend a zone or all zones for an amount of time.\n\n        :param days: Number of days to suspend the zone(s)\n        :type days: int\n        :param zone: The zone to suspend. If no zone is specified then suspend\n                     all zones\n        :type zone: int or None\n        :returns: The response from set_zones() or None if there was an error.\n        :rtype: None or string"
  },
  {
    "code": "def queue_exists(name, region, opts=None, user=None):\n    output = list_queues(region, opts, user)\n    return name in _parse_queue_list(output)",
    "docstring": "Returns True or False on whether the queue exists in the region\n\n    name\n        Name of the SQS queue to search for\n\n    region\n        Name of the region to search for the queue in\n\n    opts : None\n        Any additional options to add to the command line\n\n    user : None\n        Run hg as a user other than what the minion runs as\n\n    CLI Example:\n\n        salt '*' aws_sqs.queue_exists <sqs queue> <region>"
  },
  {
    "code": "def normalize_path(path, resolve_symlinks=True):\n    path = expanduser(path)\n    if resolve_symlinks:\n        path = os.path.realpath(path)\n    else:\n        path = os.path.abspath(path)\n    return os.path.normcase(path)",
    "docstring": "Convert a path to its canonical, case-normalized, absolute version."
  },
  {
    "code": "def _ensure_datetimelike_to_i8(other, to_utc=False):\n    from pandas import Index\n    from pandas.core.arrays import PeriodArray\n    if lib.is_scalar(other) and isna(other):\n        return iNaT\n    elif isinstance(other, (PeriodArray, ABCIndexClass,\n                            DatetimeLikeArrayMixin)):\n        if getattr(other, 'tz', None) is not None:\n            if to_utc:\n                other = other.tz_convert('UTC')\n            else:\n                other = other.tz_localize(None)\n    else:\n        try:\n            return np.array(other, copy=False).view('i8')\n        except TypeError:\n            other = Index(other)\n    return other.asi8",
    "docstring": "Helper for coercing an input scalar or array to i8.\n\n    Parameters\n    ----------\n    other : 1d array\n    to_utc : bool, default False\n        If True, convert the values to UTC before extracting the i8 values\n        If False, extract the i8 values directly.\n\n    Returns\n    -------\n    i8 1d array"
  },
  {
    "code": "def get_codemirror_parameters(self, name):\n        config = self.get_config(name)\n        return {k: config[k] for k in config if k not in self._internal_only}",
    "docstring": "Return CodeMirror parameters for given configuration name.\n\n        This is a reduced configuration from internal parameters.\n\n        Arguments:\n            name (string): Config name from available ones in\n                ``settings.CODEMIRROR_SETTINGS``.\n\n        Returns:\n            dict: Parameters."
  },
  {
    "code": "def gt(self, v, limit=None, offset=None):\n        if limit is not None and offset is None:\n            offset = 0\n        return self.zrangebyscore(\"(%f\" % v, self._max_score,\n                start=offset, num=limit)",
    "docstring": "Returns the list of the members of the set that have scores\n        greater than v."
  },
  {
    "code": "def reload(self, hardware_id, post_uri=None, ssh_keys=None):\n        config = {}\n        if post_uri:\n            config['customProvisionScriptUri'] = post_uri\n        if ssh_keys:\n            config['sshKeyIds'] = [key_id for key_id in ssh_keys]\n        return self.hardware.reloadOperatingSystem('FORCE', config,\n                                                   id=hardware_id)",
    "docstring": "Perform an OS reload of a server with its current configuration.\n\n        :param integer hardware_id: the instance ID to reload\n        :param string post_uri: The URI of the post-install script to run\n                                after reload\n        :param list ssh_keys: The SSH keys to add to the root user"
  },
  {
    "code": "def categories_to_colors(cats, colormap=None):\n    if colormap is None:\n        colormap = tableau20\n    if type(cats) != pd.Series:\n        cats = pd.Series(cats)\n    legend = pd.Series(dict(zip(set(cats), colormap)))\n    return(legend)",
    "docstring": "Map categorical data to colors.\n\n    Parameters\n    ----------\n    cats : pandas.Series or list\n        Categorical data as a list or in a Series.\n\n    colormap : list\n        List of RGB triples. If not provided, the tableau20 colormap defined in\n        this module will be used.\n\n    Returns\n    -------\n    legend : pd.Series\n        Series whose values are colors and whose index are the original\n        categories that correspond to those colors."
  },
  {
    "code": "def get_service_details(self, service_id: str) -> dict:\n        if not self._manager:\n            raise RuntimeError('Only the Swarm manager node can retrieve all'\n                               ' the services details.')\n        service = self._client.services.get(service_id)\n        return service.attrs",
    "docstring": "Get details of a service.\n\n        Only the manager nodes can retrieve service details\n\n        Args:\n            service_id (string): List of service id\n\n        Returns:\n            dict, details of the service"
  },
  {
    "code": "def add_adapter(self, adapter):\n        if self._started:\n            raise InternalError(\"New adapters cannot be added after start() is called\")\n        if isinstance(adapter, DeviceAdapter):\n            self._logger.warning(\"Wrapping legacy device adapter %s in async wrapper\", adapter)\n            adapter = AsynchronousModernWrapper(adapter, loop=self._loop)\n        self.adapters.append(adapter)\n        adapter_callback = functools.partial(self.handle_adapter_event,\n                                             len(self.adapters) - 1)\n        events = ['device_seen', 'broadcast', 'report', 'connection',\n                  'disconnection', 'trace', 'progress']\n        adapter.register_monitor([None], events, adapter_callback)",
    "docstring": "Add a device adapter to this aggregating adapter."
  },
  {
    "code": "def get_value(self, default=None):\n        if default is None:\n            default = ''\n        try:\n            text = self.currentText()\n        except ValueError:\n            lg.debug('Cannot convert \"' + str(text) + '\" to list. ' +\n                     'Using default ' + str(default))\n            text = default\n            self.set_value(text)\n        return text",
    "docstring": "Get selection from widget.\n\n        Parameters\n        ----------\n        default : str\n            str for use by widget\n\n        Returns\n        -------\n        str\n            selected item from the combobox"
  },
  {
    "code": "def _getNearestMappingIndexList(fromValList, toValList):\n    indexList = []\n    for fromTimestamp in fromValList:\n        smallestDiff = _getSmallestDifference(toValList, fromTimestamp)\n        i = toValList.index(smallestDiff)\n        indexList.append(i)\n    return indexList",
    "docstring": "Finds the indicies for data points that are closest to each other.\n\n    The inputs should be in relative time, scaled from 0 to 1\n    e.g. if you have [0, .1, .5., .9] and [0, .1, .2, 1]\n    will output [0, 1, 1, 2]"
  },
  {
    "code": "def ImportTypes(self, prefix=''):\n      dynTypeMgr = self.GetTypeManager()\n      filterSpec = None\n      if prefix != '':\n         filterSpec = vmodl.reflect.DynamicTypeManager.TypeFilterSpec(\n                                                              typeSubstr=prefix)\n      allTypes = dynTypeMgr.QueryTypeInfo(filterSpec)\n      DynamicTypeConstructor().CreateTypes(allTypes)\n      return allTypes",
    "docstring": "Build dynamic types"
  },
  {
    "code": "def read_float_matrix(rx_specifier):\n        path, offset = rx_specifier.strip().split(':', maxsplit=1)\n        offset = int(offset)\n        sample_format = 4\n        with open(path, 'rb') as f:\n            f.seek(offset)\n            binary = f.read(2)\n            assert (binary == b'\\x00B')\n            format = f.read(3)\n            assert (format == b'FM ')\n            f.read(1)\n            num_frames = struct.unpack('<i', f.read(4))[0]\n            f.read(1)\n            feature_size = struct.unpack('<i', f.read(4))[0]\n            data = f.read(num_frames * feature_size * sample_format)\n            feature_vector = np.frombuffer(data, dtype='float32')\n            feature_matrix = np.reshape(feature_vector, (num_frames, feature_size))\n            return feature_matrix",
    "docstring": "Return float matrix as np array for the given rx specifier."
  },
  {
    "code": "def query_params(*es_query_params):\n    def _wrapper(func):\n        @wraps(func)\n        def _wrapped(*args, **kwargs):\n            params = {}\n            if \"params\" in kwargs:\n                params = kwargs.pop(\"params\").copy()\n            for p in es_query_params + GLOBAL_PARAMS:\n                if p in kwargs:\n                    v = kwargs.pop(p)\n                    if v is not None:\n                        params[p] = _escape(v)\n            for p in (\"ignore\", \"request_timeout\"):\n                if p in kwargs:\n                    params[p] = kwargs.pop(p)\n            return func(*args, params=params, **kwargs)\n        return _wrapped\n    return _wrapper",
    "docstring": "Decorator that pops all accepted parameters from method's kwargs and puts\n    them in the params argument."
  },
  {
    "code": "def __get_size(conn, vm_):\n    size = config.get_cloud_config_value(\n        'size', vm_, __opts__, default='n1-standard-1', search_global=False)\n    return conn.ex_get_size(size, __get_location(conn, vm_))",
    "docstring": "Need to override libcloud to find the machine type in the proper zone."
  },
  {
    "code": "def cli(env):\n    manager = PlacementManager(env.client)\n    result = manager.list()\n    table = formatting.Table(\n        [\"Id\", \"Name\", \"Backend Router\", \"Rule\", \"Guests\", \"Created\"],\n        title=\"Placement Groups\"\n    )\n    for group in result:\n        table.add_row([\n            group['id'],\n            group['name'],\n            group['backendRouter']['hostname'],\n            group['rule']['name'],\n            group['guestCount'],\n            group['createDate']\n        ])\n    env.fout(table)",
    "docstring": "List placement groups."
  },
  {
    "code": "def _override_options(options, **overrides):\n    for opt, val in overrides.items():\n        passed_value = getattr(options, opt, _Default())\n        if opt in ('ignore', 'select') and passed_value:\n            value = process_value(opt, passed_value.value)\n            value += process_value(opt, val)\n            setattr(options, opt, value)\n        elif isinstance(passed_value, _Default):\n            setattr(options, opt, process_value(opt, val))",
    "docstring": "Override options."
  },
  {
    "code": "def copy_nrpe_checks(nrpe_files_dir=None):\n    NAGIOS_PLUGINS = '/usr/local/lib/nagios/plugins'\n    if nrpe_files_dir is None:\n        for segment in ['.', 'hooks']:\n            nrpe_files_dir = os.path.abspath(os.path.join(\n                os.getenv('CHARM_DIR'),\n                segment,\n                'charmhelpers',\n                'contrib',\n                'openstack',\n                'files'))\n            if os.path.isdir(nrpe_files_dir):\n                break\n        else:\n            raise RuntimeError(\"Couldn't find charmhelpers directory\")\n    if not os.path.exists(NAGIOS_PLUGINS):\n        os.makedirs(NAGIOS_PLUGINS)\n    for fname in glob.glob(os.path.join(nrpe_files_dir, \"check_*\")):\n        if os.path.isfile(fname):\n            shutil.copy2(fname,\n                         os.path.join(NAGIOS_PLUGINS, os.path.basename(fname)))",
    "docstring": "Copy the nrpe checks into place"
  },
  {
    "code": "def bundle_lambda(zipfile):\n    if not zipfile:\n        return 1\n    with open('bundle.zip', 'wb') as zfile:\n        zfile.write(zipfile)\n    log.info('Finished - a bundle.zip is waiting for you...')\n    return 0",
    "docstring": "Write zipfile contents to file.\n\n    :param zipfile:\n    :return: exit_code"
  },
  {
    "code": "def filter_batched_data(data, mapping):\n    for k, v in list(mapping.items()):\n        if isinstance(v, dict) and 'field' in v:\n            if 'transform' in v:\n                continue\n            v = v['field']\n        elif not isinstance(v, basestring):\n            continue\n        values = data[v]\n        try:\n            if len(unique_array(values)) == 1:\n                mapping[k] = values[0]\n                del data[v]\n        except:\n            pass",
    "docstring": "Iterates over the data and mapping for a ColumnDataSource and\n    replaces columns with repeating values with a scalar. This is\n    purely and optimization for scalar types."
  },
  {
    "code": "def on_click(self, event):\n        if event[\"button\"] == self.button_toggle:\n            if \"DPMS is Enabled\" in self.py3.command_output(\"xset -q\"):\n                self.py3.command_run(\"xset -dpms s off\")\n            else:\n                self.py3.command_run(\"xset +dpms s on\")\n        if event[\"button\"] == self.button_off:\n            self.py3.command_run(\"xset dpms force off\")",
    "docstring": "Control DPMS with mouse clicks."
  },
  {
    "code": "def return_resource(self, resource, status=200, statusMessage=\"OK\"):\n        self.set_status(status, statusMessage)\n        self.write(json.loads(json_util.dumps(resource)))",
    "docstring": "Return a resource response\n\n        :param str resource: The JSON String representation of a resource response\n        :param int status: Status code to use\n        :param str statusMessage: The message to use in the error response"
  },
  {
    "code": "def monkey_patch(cls):\n        on_read_the_docs = os.environ.get('READTHEDOCS', False)\n        if on_read_the_docs:\n            sys.modules['zbarlight._zbarlight'] = cls",
    "docstring": "Monkey path zbarlight C extension on Read The Docs"
  },
  {
    "code": "def delete_firmware_image(self, image_id):\n        api = self._get_api(update_service.DefaultApi)\n        api.firmware_image_destroy(image_id=image_id)\n        return",
    "docstring": "Delete a firmware image.\n\n        :param str image_id: image ID for the firmware to remove/delete (Required)\n        :return: void"
  },
  {
    "code": "def install_hooks(target, **hooks):\n        for name, hook in hooks.items():\n            func = getattr(target, name)\n            if not isinstance(func, HookedMethod):\n                func = HookedMethod(func)\n                setattr(target, name, func)\n            func.pending.append(hook)",
    "docstring": "Given the target `target`, apply the hooks given as keyword arguments to it.\n        If any targeted method has already been hooked, the hooks will not be overridden but will instead be pushed\n        into a list of pending hooks. The final behavior should be that all hooks call each other in a nested stack.\n\n        :param target:  Any object. Its methods named as keys in `hooks` will be replaced by `HookedMethod` objects.\n        :param hooks:   Any keywords will be interpreted as hooks to apply. Each method named will hooked with the\n                        coresponding function value."
  },
  {
    "code": "def reverse_sequences(records):\n    logging.info('Applying _reverse_sequences generator: '\n                 'reversing the order of sites in sequences.')\n    for record in records:\n        rev_record = SeqRecord(record.seq[::-1], id=record.id,\n                               name=record.name,\n                               description=record.description)\n        _reverse_annotations(record, rev_record)\n        yield rev_record",
    "docstring": "Reverse the order of sites in sequences."
  },
  {
    "code": "def setto(self, s):\n        length = len(s)\n        self.b[self.j+1:self.j+1+length] = s\n        self.k = self.j + length",
    "docstring": "set j+1...k to string s, readjusting k"
  },
  {
    "code": "def exec_iteration(self, counter, context, step_method):\n        logger.debug(\"starting\")\n        context['whileCounter'] = counter\n        logger.info(f\"while: running step with counter {counter}\")\n        step_method(context)\n        logger.debug(f\"while: done step {counter}\")\n        result = False\n        if self.stop:\n            result = context.get_formatted_as_type(self.stop, out_type=bool)\n        logger.debug(\"done\")\n        return result",
    "docstring": "Run a single loop iteration.\n\n        This method abides by the signature invoked by poll.while_until_true,\n        which is to say (counter, *args, **kwargs). In a normal execution\n        chain, this method's args passed by self.while_loop where context\n        and step_method set. while_until_true injects counter as a 1st arg.\n\n        Args:\n            counter. int. loop counter, which number of iteration is this.\n            context: (pypyr.context.Context) The pypyr context. This arg will\n                     mutate - after method execution will contain the new\n                     updated context.\n            step_method: (method/function) This is the method/function that\n                         will execute on every loop iteration. Signature is:\n                         function(context)\n\n         Returns:\n            bool. True if self.stop evaluates to True after step execution,\n                  False otherwise."
  },
  {
    "code": "def html_to_cnxml(html_source, cnxml_source):\n    source = _string2io(html_source)\n    xml = etree.parse(source)\n    cnxml = etree.parse(_string2io(cnxml_source))\n    xml = _transform('html5-to-cnxml.xsl', xml)\n    namespaces = {'c': 'http://cnx.rice.edu/cnxml'}\n    xpath = etree.XPath('//c:content', namespaces=namespaces)\n    replaceable_node = xpath(cnxml)[0]\n    replaceable_node.getparent().replace(replaceable_node, xml.getroot())\n    return etree.tostring(cnxml)",
    "docstring": "Transform the HTML to CNXML. We need the original CNXML content in\n    order to preserve the metadata in the CNXML document."
  },
  {
    "code": "def get_groups(self, condition=None, page_size=1000):\n        query_kwargs = {}\n        if condition is not None:\n            query_kwargs[\"condition\"] = condition.compile()\n        for group_data in self._conn.iter_json_pages(\"/ws/Group\", page_size=page_size, **query_kwargs):\n            yield Group.from_json(group_data)",
    "docstring": "Return an iterator over all groups in this device cloud account\n\n        Optionally, a condition can be specified to limit the number of\n        groups returned.\n\n        Examples::\n\n            # Get all groups and print information about them\n            for group in dc.devicecore.get_groups():\n                print group\n\n            # Iterate over all devices which are in a group with a specific\n            # ID.\n            group = dc.devicore.get_groups(group_id == 123)[0]\n            for device in dc.devicecore.get_devices(group_path == group.get_path()):\n                print device.get_mac()\n\n        :param condition: A condition to use when filtering the results set.  If\n            unspecified, all groups will be returned.\n        :param int page_size: The number of results to fetch in a\n            single page.  In general, the default will suffice.\n        :returns: Generator over the groups in this device cloud account.  No\n            guarantees about the order of results is provided and child links\n            between nodes will not be populated."
  },
  {
    "code": "def genderize(name, api_token=None):\n    GENDERIZE_API_URL = \"https://api.genderize.io/\"\n    TOTAL_RETRIES = 10\n    MAX_RETRIES = 5\n    SLEEP_TIME = 0.25\n    STATUS_FORCELIST = [502]\n    params = {\n        'name': name\n    }\n    if api_token:\n        params['apikey'] = api_token\n    session = requests.Session()\n    retries = urllib3.util.Retry(total=TOTAL_RETRIES,\n                                 connect=MAX_RETRIES,\n                                 status=MAX_RETRIES,\n                                 status_forcelist=STATUS_FORCELIST,\n                                 backoff_factor=SLEEP_TIME,\n                                 raise_on_status=True)\n    session.mount('http://', requests.adapters.HTTPAdapter(max_retries=retries))\n    session.mount('https://', requests.adapters.HTTPAdapter(max_retries=retries))\n    r = session.get(GENDERIZE_API_URL, params=params)\n    r.raise_for_status()\n    result = r.json()\n    gender = result['gender']\n    prob = result.get('probability', None)\n    acc = int(prob * 100) if prob else None\n    return gender, acc",
    "docstring": "Fetch gender from genderize.io"
  },
  {
    "code": "def _validate_columns(self):\n        for column_index in range(self.start[1], self.end[1]):\n            table_column = TableTranspose(self.table)[column_index]\n            column_type = None\n            if self.end[0] > self.start[0]:\n                column_type = get_cell_type(table_column[self.start[0]])\n            num_type_changes = 0\n            for row_index in range(self.start[0], self.end[0]):\n                if not check_cell_type(table_column[row_index], column_type):\n                    column_type = get_cell_type(table_column[row_index])\n                    num_type_changes += 1\n                if num_type_changes > 1:\n                    self.flag_change(self.flags, 'warning', (row_index-1, column_index),\n                                     self.worksheet, self.FLAGS['unexpected-change'])\n                    num_type_changes -= 1",
    "docstring": "Same as _validate_rows but for columns. Also ignore used_cells as _validate_rows should\n        update used_cells."
  },
  {
    "code": "def pushstrf(self, format, *args):\n        return lib.zmsg_pushstrf(self._as_parameter_, format, *args)",
    "docstring": "Push formatted string as new frame to front of message.\nReturns 0 on success, -1 on error."
  },
  {
    "code": "def insert_attachments(self, volumeID, attachments):\n        log.debug(\"adding new attachments to volume '{}': {}\".format(volumeID, attachments))\n        if not attachments:\n            return\n        rawVolume = self._req_raw_volume(volumeID)\n        attsID = list()\n        for index, a in enumerate(attachments):\n            try:\n                rawAttachment = self._assemble_attachment(a['file'], a)\n                rawVolume['_source']['_attachments'].append(rawAttachment)\n                attsID.append(rawAttachment['id'])\n            except Exception:\n                log.exception(\"Error while elaborating attachments array at index: {}\".format(index))\n                raise\n        self._db.modify_book(volumeID, rawVolume['_source'], version=rawVolume['_version'])\n        return attsID",
    "docstring": "add attachments to an already existing volume"
  },
  {
    "code": "def _get_day_of_month(other, day_option):\n    if day_option == 'start':\n        return 1\n    elif day_option == 'end':\n        days_in_month = _days_in_month(other)\n        return days_in_month\n    elif day_option is None:\n        raise NotImplementedError\n    else:\n        raise ValueError(day_option)",
    "docstring": "Find the day in `other`'s month that satisfies a BaseCFTimeOffset's\n    onOffset policy, as described by the `day_option` argument.\n\n    Parameters\n    ----------\n    other : cftime.datetime\n    day_option : 'start', 'end'\n        'start': returns 1\n        'end': returns last day of the month\n\n    Returns\n    -------\n    day_of_month : int"
  },
  {
    "code": "def _extract_version(version_string, pattern):\n    if version_string:\n        match = pattern.match(version_string.strip())\n        if match:\n            return match.group(1)\n    return \"\"",
    "docstring": "Extract the version from `version_string` using `pattern`.\n\n    Return the version as a string, with leading/trailing whitespace\n    stripped."
  },
  {
    "code": "def audiorate(filename):\n    if '.wav' in filename.lower():\n        wf = wave.open(filename)\n        fs = wf.getframerate()\n        wf.close()\n    elif '.call' in filename.lower():\n        fs = 333333\n    else:\n        raise IOError(\"Unsupported audio format for file: {}\".format(filename))\n    return fs",
    "docstring": "Determines the samplerate of the given audio recording file\n\n    :param filename: filename of the audiofile\n    :type filename: str\n    :returns: int -- samplerate of the recording"
  },
  {
    "code": "def main(self, function):\n        captured = self.command(function)\n        self.default_command = captured.__name__\n        return captured",
    "docstring": "Decorator to define the main function of the experiment.\n\n        The main function of an experiment is the default command that is being\n        run when no command is specified, or when calling the run() method.\n\n        Usually it is more convenient to use ``automain`` instead."
  },
  {
    "code": "def get_entries(path):\r\n    dirs, files = [], []\r\n    for entry in os.listdir(path):\r\n        if os.path.isdir(os.path.join(path, entry)):\r\n            dirs.append(entry)\r\n        else:\r\n            files.append(entry)\r\n    dirs.sort()\r\n    files.sort()\r\n    return dirs, files",
    "docstring": "Return sorted lists of directories and files in the given path."
  },
  {
    "code": "def _handle_return(self, node, scope, ctxt, stream):\n        self._dlog(\"handling return\")\n        if node.expr is None:\n            ret_val = None\n        else:\n            ret_val = self._handle_node(node.expr, scope, ctxt, stream)\n        self._dlog(\"return value = {}\".format(ret_val))\n        raise errors.InterpReturn(ret_val)",
    "docstring": "Handle Return nodes\n\n        :node: TODO\n        :scope: TODO\n        :ctxt: TODO\n        :stream: TODO\n        :returns: TODO"
  },
  {
    "code": "def plot_pot(self, colorbar=True, cb_orientation='vertical',\n                 cb_label='Potential, m$^2$ s$^{-2}$', ax=None, show=True,\n                 fname=None, **kwargs):\n        if ax is None:\n            fig, axes = self.pot.plot(colorbar=colorbar,\n                                      cb_orientation=cb_orientation,\n                                      cb_label=cb_label, show=False, **kwargs)\n            if show:\n                fig.show()\n            if fname is not None:\n                fig.savefig(fname)\n            return fig, axes\n        else:\n            self.pot.plot(colorbar=colorbar, cb_orientation=cb_orientation,\n                          cb_label=cb_label, ax=ax, **kwargs)",
    "docstring": "Plot the gravitational potential.\n\n        Usage\n        -----\n        x.plot_pot([tick_interval, xlabel, ylabel, ax, colorbar,\n                    cb_orientation, cb_label, show, fname, **kwargs])\n\n        Parameters\n        ----------\n        tick_interval : list or tuple, optional, default = [30, 30]\n            Intervals to use when plotting the x and y ticks. If set to None,\n            ticks will not be plotted.\n        xlabel : str, optional, default = 'longitude'\n            Label for the longitude axis.\n        ylabel : str, optional, default = 'latitude'\n            Label for the latitude axis.\n        ax : matplotlib axes object, optional, default = None\n            A single matplotlib axes object where the plot will appear.\n        colorbar : bool, optional, default = True\n            If True, plot a colorbar.\n        cb_orientation : str, optional, default = 'vertical'\n            Orientation of the colorbar: either 'vertical' or 'horizontal'.\n        cb_label : str, optional, default = 'potential, m s$^{-1}$'\n            Text label for the colorbar.\n        show : bool, optional, default = True\n            If True, plot the image to the screen.\n        fname : str, optional, default = None\n            If present, and if axes is not specified, save the image to the\n            specified file.\n        kwargs : optional\n            Keyword arguements that will be sent to the SHGrid.plot()\n            and plt.imshow() methods."
  },
  {
    "code": "def _number_of_line(member_tuple):\n    member = member_tuple[1]\n    try:\n        return member.__code__.co_firstlineno\n    except AttributeError:\n        pass\n    try:\n        return inspect.findsource(member)[1]\n    except BaseException:\n        pass\n    for value in vars(member).values():\n        try:\n            return value.__code__.co_firstlineno\n        except AttributeError:\n            pass\n    return 0",
    "docstring": "Try to return the number of the first line of the definition of a\n    member of a module."
  },
  {
    "code": "def dispatch(self, request, start_response):\n    dispatched_response = self.dispatch_non_api_requests(request,\n                                                         start_response)\n    if dispatched_response is not None:\n      return dispatched_response\n    try:\n      return self.call_backend(request, start_response)\n    except errors.RequestError as error:\n      return self._handle_request_error(request, error, start_response)",
    "docstring": "Handles dispatch to apiserver handlers.\n\n    This typically ends up calling start_response and returning the entire\n      body of the response.\n\n    Args:\n      request: An ApiRequest, the request from the user.\n      start_response: A function with semantics defined in PEP-333.\n\n    Returns:\n      A string, the body of the response."
  },
  {
    "code": "def ConfigureLazyWorkers(self):\n    lazy_worker_instances = self.__GetMissingWorkers()\n    if not lazy_worker_instances:\n      return\n    reachable_states = self.__AreInstancesReachable(lazy_worker_instances)\n    reachable_instances = [t[0] for t in zip(lazy_worker_instances, \n                                             reachable_states) if t[1]]\n    print 'reachable_instances: %s' % reachable_instances \n    self.__ConfigureWorkers(reachable_instances)\n    return",
    "docstring": "Lazy workers are instances that are running and reachable but failed to \n    register with the cldb to join the mapr cluster. This trys to find these \n    missing workers and add them to the cluster."
  },
  {
    "code": "def users(self, params):\n        resource = self.RESOURCE_USERS.format(account_id=self.account.id, id=self.id)\n        headers = {'Content-Type': 'application/json'}\n        response = Request(self.account.client,\n                           'post',\n                           resource,\n                           headers=headers,\n                           body=json.dumps(params)).perform()\n        success_count = response.body['data']['success_count']\n        total_count = response.body['data']['total_count']\n        return (success_count, total_count)",
    "docstring": "This is a private API and requires whitelisting from Twitter.\n        This endpoint will allow partners to add, update and remove users from a given\n            tailored_audience_id.\n        The endpoint will also accept multiple user identifier types per user as well."
  },
  {
    "code": "def _check_random_state(random_state):\n    if random_state is None or isinstance(random_state, int):\n        return sci.random.RandomState(random_state)\n    elif isinstance(random_state, sci.random.RandomState):\n        return random_state\n    else:\n        raise TypeError('Seed should be None, int or np.random.RandomState')",
    "docstring": "Checks and processes user input for seeding random numbers.\n\n    Parameters\n    ----------\n    random_state : int, RandomState instance or None\n        If int, a RandomState instance is created with this integer seed.\n        If RandomState instance, random_state is returned;\n        If None, a RandomState instance is created with arbitrary seed.\n\n    Returns\n    -------\n    scipy.random.RandomState instance\n\n    Raises\n    ------\n    TypeError\n        If ``random_state`` is not appropriately set."
  },
  {
    "code": "def _validate_ard_shape(self, name, value, ARD=None):\n        if ARD is None:\n            ARD = np.asarray(value).squeeze().shape != ()\n        if ARD:\n            value = value * np.ones(self.input_dim, dtype=settings.float_type)\n        if self.input_dim == 1 or not ARD:\n            correct_shape = ()\n        else:\n            correct_shape = (self.input_dim,)\n        if np.asarray(value).squeeze().shape != correct_shape:\n            raise ValueError(\"shape of {} does not match input_dim\".format(name))\n        return value, ARD",
    "docstring": "Validates the shape of a potentially ARD hyperparameter\n\n        :param name: The name of the parameter (used for error messages)\n        :param value: A scalar or an array.\n        :param ARD: None, False, or True. If None, infers ARD from shape of value.\n        :return: Tuple (value, ARD), where _value_ is a scalar if input_dim==1 or not ARD, array otherwise.\n            The _ARD_ is False if input_dim==1 or not ARD, True otherwise."
  },
  {
    "code": "def disable_reporting(self):\n        self.reporting = False\n        msg = bytearray([REPORT_DIGITAL + self.port_number, 0])\n        self.board.sp.write(msg)",
    "docstring": "Disable the reporting of the port."
  },
  {
    "code": "def execute_message_call(laser_evm, callee_address: str) -> None:\n    open_states = laser_evm.open_states[:]\n    del laser_evm.open_states[:]\n    for open_world_state in open_states:\n        if open_world_state[callee_address].deleted:\n            log.debug(\"Can not execute dead contract, skipping.\")\n            continue\n        next_transaction_id = get_next_transaction_id()\n        transaction = MessageCallTransaction(\n            world_state=open_world_state,\n            identifier=next_transaction_id,\n            gas_price=symbol_factory.BitVecSym(\n                \"gas_price{}\".format(next_transaction_id), 256\n            ),\n            gas_limit=8000000,\n            origin=symbol_factory.BitVecSym(\n                \"origin{}\".format(next_transaction_id), 256\n            ),\n            caller=symbol_factory.BitVecVal(ATTACKER_ADDRESS, 256),\n            callee_account=open_world_state[callee_address],\n            call_data=SymbolicCalldata(next_transaction_id),\n            call_value=symbol_factory.BitVecSym(\n                \"call_value{}\".format(next_transaction_id), 256\n            ),\n        )\n        _setup_global_state_for_execution(laser_evm, transaction)\n    laser_evm.exec()",
    "docstring": "Executes a message call transaction from all open states.\n\n    :param laser_evm:\n    :param callee_address:"
  },
  {
    "code": "def limit(self, limit):\n        if self._limit != limit:\n            self.dirty = True\n            self._limit = limit\n        return self",
    "docstring": "Limit the number of rows returned from the database.\n\n        :param limit: The number of rows to return in the recipe. 0 will\n                      return all rows.\n        :type limit: int"
  },
  {
    "code": "def phase_parents_by_transmission(g, window_size):\n    check_type(g, GenotypeArray)\n    check_dtype(g.values, 'i1')\n    check_ploidy(g.ploidy, 2)\n    if g.is_phased is None:\n        raise ValueError('genotype array must first have progeny phased by transmission')\n    check_min_samples(g.n_samples, 3)\n    g._values = memoryview_safe(g.values)\n    g._is_phased = memoryview_safe(g.is_phased)\n    _opt_phase_parents_by_transmission(g.values, g.is_phased.view('u1'), window_size)\n    return g",
    "docstring": "Phase parent genotypes from a trio or cross, given progeny genotypes\n    already phased by Mendelian transmission.\n\n    Parameters\n    ----------\n    g : GenotypeArray\n        Genotype array, with parents as first two columns and progeny as\n        remaining columns, where progeny genotypes are already phased.\n    window_size : int\n        Number of previous heterozygous sites to include when phasing each\n        parent. A number somewhere between 10 and 100 may be appropriate,\n        depending on levels of heterozygosity and quality of data.\n\n    Returns\n    -------\n    g : GenotypeArray\n        Genotype array with parents phased where possible."
  },
  {
    "code": "def _walk(self, target, visitor):\n    visited = set()\n    def walk(current):\n      if current not in visited:\n        visited.add(current)\n        keep_going = visitor(current)\n        if keep_going:\n          for dependency in self.dependencies(current):\n            walk(dependency)\n    walk(target)",
    "docstring": "Walks the dependency graph for the given target.\n\n    :param target: The target to start the walk from.\n    :param visitor: A function that takes a target and returns `True` if its dependencies should\n                    also be visited."
  },
  {
    "code": "def values_at(self, depth):\n        if depth < 1:\n            yield self\n        else:\n            for dict_tree in self.values():\n                for value in dict_tree.values_at(depth - 1):\n                    yield value",
    "docstring": "Iterate values at specified depth."
  },
  {
    "code": "def get_container_id(self, container_id=None):\n        if container_id == None and self.container_id == None:\n            bot.exit('You must provide a container_id.')\n        container_id = container_id or self.container_id\n        return container_id",
    "docstring": "a helper function shared between functions that will return a \n            container_id. First preference goes to a container_id provided by\n            the user at runtime. Second preference goes to the container_id\n            instantiated with the client.\n\n            Parameters\n            ==========\n            container_id: image uri to parse (required)"
  },
  {
    "code": "def _encode_ndef_uri_type(self, data):\n        t = 0x0\n        for (code, prefix) in uri_identifiers:\n            if data[:len(prefix)].decode('latin-1').lower() == prefix:\n                t = code\n                data = data[len(prefix):]\n                break\n        data = yubico_util.chr_byte(t) + data\n        return data",
    "docstring": "Implement NDEF URI Identifier Code.\n\n        This is a small hack to replace some well known prefixes (such as http://)\n        with a one byte code. If the prefix is not known, 0x00 is used."
  },
  {
    "code": "def write_fasta_file(self, outfile, force_rerun=False):\n        if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):\n            SeqIO.write(self, outfile, \"fasta\")\n        self.sequence_path = outfile",
    "docstring": "Write a FASTA file for the protein sequence, ``seq`` will now load directly from this file.\n\n        Args:\n            outfile (str): Path to new FASTA file to be written to\n            force_rerun (bool): If an existing file should be overwritten"
  },
  {
    "code": "def SignedVarintEncode(value):\n  result = b\"\"\n  if value < 0:\n    value += (1 << 64)\n  bits = value & 0x7f\n  value >>= 7\n  while value:\n    result += HIGH_CHR_MAP[bits]\n    bits = value & 0x7f\n    value >>= 7\n  result += CHR_MAP[bits]\n  return result",
    "docstring": "Encode a signed integer as a zigzag encoded signed integer."
  },
  {
    "code": "def stage_tc_create_security_label(self, label, resource):\n        sl_resource = resource.security_labels(label)\n        sl_resource.http_method = 'POST'\n        sl_response = sl_resource.request()\n        if sl_response.get('status') != 'Success':\n            self.log.warning(\n                '[tcex] Failed adding security label \"{}\" ({}).'.format(\n                    label, sl_response.get('response').text\n                )\n            )",
    "docstring": "Add a security label to a resource.\n\n        Args:\n            label (str): The security label (must exit in ThreatConnect).\n            resource (obj): An instance of tcex resource class."
  },
  {
    "code": "def setchival(self, bondorder, rotation):\n        rotation = [None, \"@\", \"@@\"][(rotation % 2)]\n        if not bondorder:\n            if len(self.oatoms) < 3 and self.explicit_hcount != 1:\n                raise PinkyError(\"Need to have an explicit hydrogen when specifying \"\\\n                                  \"chirality with less than three bonds\")\n            self._chirality = chirality.T(self.oatoms,\n                                            rotation)\n            return\n        if len(bondorder) != len(self.bonds):\n            raise AtomError(\"The order of all bonds must be specified\")\n        for bond in bondorder:\n            if bond not in self.bonds:\n                raise AtomError(\"Specified bonds to assign chirality are not attatched to atom\")\n        order = [bond.xatom(self) for bond in bonds]\n        self._chirality = chirality.T(order, rotation)",
    "docstring": "compute chiral ordering of surrounding atoms"
  },
  {
    "code": "def handle_pre_response(self, item_session: ItemSession) -> Actions:\n        action = self.consult_pre_response_hook(item_session)\n        if action == Actions.RETRY:\n            item_session.set_status(Status.skipped)\n        elif action == Actions.FINISH:\n            item_session.set_status(Status.done)\n        elif action == Actions.STOP:\n            raise HookStop('Script requested immediate stop.')\n        return action",
    "docstring": "Process a response that is starting."
  },
  {
    "code": "def get_current_user():\n    thread_local = AutomatedLoggingMiddleware.thread_local\n    if hasattr(thread_local, 'current_user'):\n        user = thread_local.current_user\n        if isinstance(user, AnonymousUser):\n            user = None\n    else:\n        user = None\n    return user",
    "docstring": "Get current user object from middleware"
  },
  {
    "code": "def share_project(project_id, usernames, read_only, share,**kwargs):\n    user_id = kwargs.get('user_id')\n    proj_i = _get_project(project_id)\n    proj_i.check_share_permission(int(user_id))\n    user_id = int(user_id)\n    for owner in proj_i.owners:\n        if user_id == owner.user_id:\n            break\n    else:\n       raise HydraError(\"Permission Denied. Cannot share project.\")\n    if read_only == 'Y':\n        write = 'N'\n        share = 'N'\n    else:\n        write = 'Y'\n    if proj_i.created_by != user_id and share == 'Y':\n        raise HydraError(\"Cannot share the 'sharing' ability as user %s is not\"\n                     \" the owner of project %s\"%\n                     (user_id, project_id))\n    for username in usernames:\n        user_i = _get_user(username)\n        proj_i.set_owner(user_i.id, write=write, share=share)\n        for net_i in proj_i.networks:\n            net_i.set_owner(user_i.id, write=write, share=share)\n    db.DBSession.flush()",
    "docstring": "Share an entire project with a list of users, identifed by\n        their usernames.\n\n        The read_only flag ('Y' or 'N') must be set\n        to 'Y' to allow write access or sharing.\n\n        The share flat ('Y' or 'N') must be set to 'Y' to allow the\n        project to be shared with other users"
  },
  {
    "code": "def drawing_update(self):\n        from MAVProxy.modules.mavproxy_map import mp_slipmap\n        if self.draw_callback is None:\n            return\n        self.draw_line.append(self.click_position)\n        if len(self.draw_line) > 1:\n            self.mpstate.map.add_object(mp_slipmap.SlipPolygon('drawing', self.draw_line,\n                                                          layer='Drawing', linewidth=2, colour=(128,128,255)))",
    "docstring": "update line drawing"
  },
  {
    "code": "def add_concept_filter(self, concept, concept_name=None):\n        if concept in self.query_params.keys():\n            if not concept_name:\n                concept_name = concept\n            if isinstance(self.query_params[concept], list):\n                if self.es_version == '1':\n                    es_filter = {'or': []}\n                    for or_filter in self.query_params[concept]:\n                        es_filter['or'].append(self._build_concept_term(concept_name, or_filter))\n                else:\n                    es_filter = {\"bool\": {\"should\": []}}\n                    for or_filter in self.query_params[concept]:\n                        es_filter[\"bool\"][\"should\"].append(self._build_concept_term(concept_name, or_filter))\n            else:\n                es_filter = self._build_concept_term(concept_name, self.query_params[concept])\n            self.filters.append(es_filter)",
    "docstring": "Add a concept filter\n\n        :param concept: concept which will be used as lowercase string in a search term\n        :param concept_name: name of the place where there will be searched for"
  },
  {
    "code": "def exists(self, client=None):\n        client = self._require_client(client)\n        query_params = self._query_params\n        query_params[\"fields\"] = \"name\"\n        try:\n            client._connection.api_request(\n                method=\"GET\",\n                path=self.path,\n                query_params=query_params,\n                _target_object=None,\n            )\n            return True\n        except NotFound:\n            return False",
    "docstring": "Determines whether or not this blob exists.\n\n        If :attr:`user_project` is set on the bucket, bills the API request\n        to that project.\n\n        :type client: :class:`~google.cloud.storage.client.Client` or\n                      ``NoneType``\n        :param client: Optional. The client to use.  If not passed, falls back\n                       to the ``client`` stored on the blob's bucket.\n\n        :rtype: bool\n        :returns: True if the blob exists in Cloud Storage."
  },
  {
    "code": "def pylog(self, *args, **kwargs):\n        printerr(self.name, args, kwargs, traceback.format_exc())",
    "docstring": "Display all available logging information."
  },
  {
    "code": "def export_to_dir(network, export_dir):\n    package_path = ding0.__path__[0]\n    network.export_to_csv_folder(os.path.join(package_path,\n                                              'output',\n                                              'debug',\n                                              'grid',\n                                              export_dir))",
    "docstring": "Exports PyPSA network as CSV files to directory\n\n    Args:\n        network: pypsa.Network\n        export_dir: str\n            Sub-directory in output/debug/grid/ where csv Files of PyPSA network are exported to."
  },
  {
    "code": "def add_after(self, pipeline):\n        if not isinstance(pipeline, Pipeline):\n            pipeline = Pipeline(pipeline)\n        self.pipes = self.pipes[:] + pipeline.pipes[:]\n        return self",
    "docstring": "Add a Pipeline to be applied after this processing pipeline.\n\n        Arguments:\n            pipeline: The Pipeline or callable to apply after this\n                Pipeline."
  },
  {
    "code": "def call_async(func):\n    @wraps(func)\n    def wrapper(self, *args, **kw):\n        def call():\n            try:\n                func(self, *args, **kw)\n            except Exception:\n                logger.exception(\n                    \"failed to call async [%r] with [%r] [%r]\", func, args, kw\n                )\n        self.loop.call_soon_threadsafe(call)\n    return wrapper",
    "docstring": "Decorates a function to be called async on the loop thread"
  },
  {
    "code": "def decode_cursor(self, request):\n        encoded = request.query_params.get(self.cursor_query_param)\n        if encoded is None:\n            return None\n        try:\n            querystring = b64decode(encoded.encode('ascii')).decode('ascii')\n            tokens = urlparse.parse_qs(querystring, keep_blank_values=True)\n            offset = tokens.get('o', ['0'])[0]\n            offset = _positive_int(offset, cutoff=self.offset_cutoff)\n            reverse = tokens.get('r', ['0'])[0]\n            reverse = bool(int(reverse))\n            position = tokens.get('p', None)\n        except (TypeError, ValueError):\n            raise NotFound(self.invalid_cursor_message)\n        return Cursor(offset=offset, reverse=reverse, position=position)",
    "docstring": "Given a request with a cursor, return a `Cursor` instance.\n\n        Differs from the standard CursorPagination to handle a tuple in the\n        position field."
  },
  {
    "code": "def is_valid(self):\n        return len(self.ref) == 1 and \\\n               len(self.alt) == 1 and \\\n               len(self.alt[0]) == 1",
    "docstring": "Only retain SNPs or single indels, and are bi-allelic"
  },
  {
    "code": "def display_animation(anim, **kwargs):\n    from IPython.display import HTML\n    return HTML(anim_to_html(anim, **kwargs))",
    "docstring": "Display the animation with an IPython HTML object"
  },
  {
    "code": "def count(y_true, y_score=None, countna=False):\n    if not countna:\n        return (~np.isnan(to_float(y_true))).sum()\n    else:\n        return len(y_true)",
    "docstring": "Counts the number of examples. If countna is False then only count labeled examples,\n    i.e. those with y_true not NaN"
  },
  {
    "code": "def _process_path_prefix(path_prefix):\n  _validate_path(path_prefix)\n  if not _GCS_PATH_PREFIX_REGEX.match(path_prefix):\n    raise ValueError('Path prefix should have format /bucket, /bucket/, '\n                     'or /bucket/prefix but got %s.' % path_prefix)\n  bucket_name_end = path_prefix.find('/', 1)\n  bucket = path_prefix\n  prefix = None\n  if bucket_name_end != -1:\n    bucket = path_prefix[:bucket_name_end]\n    prefix = path_prefix[bucket_name_end + 1:] or None\n  return bucket, prefix",
    "docstring": "Validate and process a Google Cloud Stoarge path prefix.\n\n  Args:\n    path_prefix: a Google Cloud Storage path prefix of format '/bucket/prefix'\n      or '/bucket/' or '/bucket'.\n\n  Raises:\n    ValueError: if path is invalid.\n\n  Returns:\n    a tuple of /bucket and prefix. prefix can be None."
  },
  {
    "code": "def main(argv: Optional[Sequence[str]] = None) -> None:\n    args = parse_arguments(argv=argv)\n    if args.logging:\n        logging.basicConfig(level=logging.DEBUG)\n    handle_skip()\n    action = args.action\n    request = parse_request()\n    LOGGER.debug('Received action %s with request:\\n%s',\n                 action, request)\n    try:\n        mapping = parse_mapping(args.mapping)\n    except Exception as error:\n        LOGGER.critical('Unable to parse mapping file', exc_info=True)\n        print(\n            'Unable to parse mapping file: {error}'.format(\n                error=error),\n            file=sys.stderr)\n        sys.exit(1)\n    if action == 'get':\n        get_password(request, mapping)\n    else:\n        LOGGER.info('Action %s is currently not supported', action)\n        sys.exit(1)",
    "docstring": "Start the pass-git-helper script.\n\n    Args:\n        argv:\n            If not ``None``, use the provided command line arguments for\n            parsing. Otherwise, extract them automatically."
  },
  {
    "code": "def parse_record(header, record):\n    major_version = header[1]\n    try:\n        return RECORD_PARSER[major_version](header, record)\n    except (KeyError, struct.error) as error:\n        raise RuntimeError(\"Corrupted USN Record\") from error",
    "docstring": "Parses a record according to its version."
  },
  {
    "code": "def get_perm_model():\n    try:\n        return django_apps.get_model(settings.PERM_MODEL, require_ready=False)\n    except ValueError:\n        raise ImproperlyConfigured(\"PERM_MODEL must be of the form 'app_label.model_name'\")\n    except LookupError:\n        raise ImproperlyConfigured(\n            \"PERM_MODEL refers to model '{}' that has not been installed\".format(settings.PERM_MODEL)\n        )",
    "docstring": "Returns the Perm model that is active in this project."
  },
  {
    "code": "def group_experiments_greedy(tomo_expt: TomographyExperiment):\n    diag_sets = _max_tpb_overlap(tomo_expt)\n    grouped_expt_settings_list = list(diag_sets.values())\n    grouped_tomo_expt = TomographyExperiment(grouped_expt_settings_list, program=tomo_expt.program)\n    return grouped_tomo_expt",
    "docstring": "Greedy method to group ExperimentSettings in a given TomographyExperiment\n\n    :param tomo_expt: TomographyExperiment to group ExperimentSettings within\n    :return: TomographyExperiment, with grouped ExperimentSettings according to whether\n        it consists of PauliTerms diagonal in the same tensor product basis"
  },
  {
    "code": "def _get_hosts_from_ports(self, ports):\n        hosts = map(lambda x: 'localhost:%d' % int(x.strip()), ports.split(','))\n        return list(set(hosts))",
    "docstring": "validate hostnames from a list of ports"
  },
  {
    "code": "def create_sequence_rule(self, sequence_rule_form):\n        collection = JSONClientValidated('assessment_authoring',\n                                         collection='SequenceRule',\n                                         runtime=self._runtime)\n        if not isinstance(sequence_rule_form, ABCSequenceRuleForm):\n            raise errors.InvalidArgument('argument type is not an SequenceRuleForm')\n        if sequence_rule_form.is_for_update():\n            raise errors.InvalidArgument('the SequenceRuleForm is for update only, not create')\n        try:\n            if self._forms[sequence_rule_form.get_id().get_identifier()] == CREATED:\n                raise errors.IllegalState('sequence_rule_form already used in a create transaction')\n        except KeyError:\n            raise errors.Unsupported('sequence_rule_form did not originate from this session')\n        if not sequence_rule_form.is_valid():\n            raise errors.InvalidArgument('one or more of the form elements is invalid')\n        insert_result = collection.insert_one(sequence_rule_form._my_map)\n        self._forms[sequence_rule_form.get_id().get_identifier()] = CREATED\n        result = objects.SequenceRule(\n            osid_object_map=collection.find_one({'_id': insert_result.inserted_id}),\n            runtime=self._runtime,\n            proxy=self._proxy)\n        return result",
    "docstring": "Creates a new ``SequenceRule``.\n\n        arg:    sequence_rule_form\n                (osid.assessment.authoring.SequenceRuleForm): the form\n                for this ``SequenceRule``\n        return: (osid.assessment.authoring.SequenceRule) - the new\n                ``SequenceRule``\n        raise:  IllegalState - ``sequence_rule_form`` already used in a\n                create transaction\n        raise:  InvalidArgument - one or more of the form elements is\n                invalid\n        raise:  NullArgument - ``sequence_rule_form`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        raise:  Unsupported - ``sequence_rule_form`` did not originate\n                from ``get_sequence_rule_form_for_create()``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def fetch_viewers(self, game):\n        r = self.kraken_request('GET', 'streams/summary',\n                                params={'game': game.name}).json()\n        game.viewers = r['viewers']\n        game.channels = r['channels']\n        return game",
    "docstring": "Query the viewers and channels of the given game and\n        set them on the object\n\n        :returns: the given game\n        :rtype: :class:`models.Game`\n        :raises: None"
  },
  {
    "code": "def find_substring_edge(self, substring, suffix_tree_id):\n        suffix_tree = self.suffix_tree_repo[suffix_tree_id]\n        started = datetime.datetime.now()\n        edge, ln = find_substring_edge(substring=substring, suffix_tree=suffix_tree, edge_repo=self.edge_repo)\n        print(\" - searched for edge in {} for substring: '{}'\".format(datetime.datetime.now() - started, substring))\n        return edge, ln",
    "docstring": "Returns an edge that matches the given substring."
  },
  {
    "code": "def tau_from_final_mass_spin(final_mass, final_spin, l=2, m=2, nmodes=1):\n    return get_lm_f0tau(final_mass, final_spin, l, m, nmodes)[1]",
    "docstring": "Returns QNM damping time for the given mass and spin and mode.\n\n    Parameters\n    ----------\n    final_mass : float or array\n        Mass of the black hole (in solar masses).\n    final_spin : float or array\n        Dimensionless spin of the final black hole.\n    l : int or array, optional\n        l-index of the harmonic. Default is 2.\n    m : int or array, optional\n        m-index of the harmonic. Default is 2.\n    nmodes : int, optional\n        The number of overtones to generate. Default is 1.\n\n    Returns\n    -------\n    float or array\n        The damping time of the QNM(s), in seconds. If only a single mode is\n        requested (and mass, spin, l, and m are not arrays), this will be a\n        float. If multiple modes requested, will be an array with shape\n        ``[input shape x] nmodes``, where ``input shape`` is the broadcasted\n        shape of the inputs."
  },
  {
    "code": "def add_repo(self, repo, team):\n        for t in self.iter_teams():\n            if team == t.name:\n                return t.add_repo(repo)\n        return False",
    "docstring": "Add ``repo`` to ``team``.\n\n        .. note::\n            This method is of complexity O(n). This iterates over all teams in\n            your organization and only adds the repo when the team name\n            matches the team parameter above. If you want constant time, you\n            should retrieve the team and call ``add_repo`` on that team\n            directly.\n\n        :param str repo: (required), form: 'user/repo'\n        :param str team: (required), team name"
  },
  {
    "code": "def dependency_status(data):\n    parents_statuses = set(\n        DataDependency.objects.filter(\n            child=data, kind=DataDependency.KIND_IO\n        ).distinct('parent__status').values_list('parent__status', flat=True)\n    )\n    if not parents_statuses:\n        return Data.STATUS_DONE\n    if None in parents_statuses:\n        return Data.STATUS_ERROR\n    if Data.STATUS_ERROR in parents_statuses:\n        return Data.STATUS_ERROR\n    if len(parents_statuses) == 1 and Data.STATUS_DONE in parents_statuses:\n        return Data.STATUS_DONE\n    return None",
    "docstring": "Return abstracted status of dependencies.\n\n    - ``STATUS_ERROR`` .. one dependency has error status or was deleted\n    - ``STATUS_DONE`` .. all dependencies have done status\n    - ``None`` .. other"
  },
  {
    "code": "def upload_to_s3(self, key, filename):\n        extra_args = {'ACL': self.acl}\n        guess = mimetypes.guess_type(filename)\n        content_type = guess[0]\n        encoding = guess[1]\n        if content_type:\n            extra_args['ContentType'] = content_type\n        if (self.gzip and content_type in self.gzip_content_types) or encoding == 'gzip':\n            extra_args['ContentEncoding'] = 'gzip'\n        if content_type in self.cache_control:\n            extra_args['CacheControl'] = ''.join((\n                'max-age=',\n                str(self.cache_control[content_type])\n            ))\n        if not self.dry_run:\n            logger.debug(\"Uploading %s\" % filename)\n            if self.verbosity > 0:\n                self.stdout.write(\"Uploading %s\" % filename)\n            s3_obj = self.s3_resource.Object(self.aws_bucket_name, key)\n            s3_obj.upload_file(filename, ExtraArgs=extra_args)\n        self.uploaded_files += 1\n        self.uploaded_file_list.append(filename)",
    "docstring": "Set the content type and gzip headers if applicable\n        and upload the item to S3"
  },
  {
    "code": "def untar(fname, verbose=True):\n    if fname.lower().endswith(\".tar.gz\"):\n        dirpath = os.path.join(BIGDATA_PATH, os.path.basename(fname)[:-7])\n        if os.path.isdir(dirpath):\n            return dirpath\n        with tarfile.open(fname) as tf:\n            members = tf.getmembers()\n            for member in tqdm(members, total=len(members)):\n                tf.extract(member, path=BIGDATA_PATH)\n        dirpath = os.path.join(BIGDATA_PATH, members[0].name)\n        if os.path.isdir(dirpath):\n            return dirpath\n    else:\n        logger.warning(\"Not a tar.gz file: {}\".format(fname))",
    "docstring": "Uunzip and untar a tar.gz file into a subdir of the BIGDATA_PATH directory"
  },
  {
    "code": "def add_vtt_file(self, vtt_file, language_type=None):\n        if not isinstance(vtt_file, DataInputStream):\n            raise InvalidArgument('vtt_file')\n        locale = DEFAULT_LANGUAGE_TYPE.identifier\n        if language_type is not None:\n            locale = language_type.identifier\n        self.my_osid_object_form.add_file(vtt_file,\n                                          locale,\n                                          asset_name=\"VTT File Container\",\n                                          asset_description=\"Used by an asset content to manage multi-language VTT files\")",
    "docstring": "Adds a vtt file tagged as the given language.\n\n        arg:    vtt_file (displayText): the new vtt_file\n        raise:  InvalidArgument - ``vtt_file`` is invalid\n        raise:  NoAccess - ``Metadata.isReadOnly()`` is ``true``\n        raise:  NullArgument - ``media_description`` is ``null``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def conditional_jit(function=None, **kwargs):\n    def wrapper(function):\n        try:\n            numba = importlib.import_module(\"numba\")\n            return numba.jit(**kwargs)(function)\n        except ImportError:\n            return function\n    if function:\n        return wrapper(function)\n    else:\n        return wrapper",
    "docstring": "Use numba's jit decorator if numba is installed.\n\n    Notes\n    -----\n        If called without arguments  then return wrapped function.\n\n        @conditional_jit\n        def my_func():\n            return\n\n        else called with arguments\n\n        @conditional_jit(nopython=True)\n        def my_func():\n            return"
  },
  {
    "code": "def set_error_output_file(filename):\n    filename = os.path.abspath(os.path.expanduser(filename))\n    fileOutputWindow = vtk.vtkFileOutputWindow()\n    fileOutputWindow.SetFileName(filename)\n    outputWindow = vtk.vtkOutputWindow()\n    outputWindow.SetInstance(fileOutputWindow)\n    return fileOutputWindow, outputWindow",
    "docstring": "Sets a file to write out the VTK errors"
  },
  {
    "code": "def for_display(self):\n        skip = \"\"\n        if self.skip:\n            skip = \" [SKIP]\"\n        result = \"{step_num}: {path}{skip}\".format(\n            step_num=self.step_num, path=self.path, skip=skip\n        )\n        description = self.task_config.get(\"description\")\n        if description:\n            result += \": {}\".format(description)\n        return result",
    "docstring": "Step details formatted for logging output."
  },
  {
    "code": "def assets(self, asset_type=None):\n        if not self.can_update():\n            self._tcex.handle_error(910, [self.type])\n        if not asset_type:\n            return self.tc_requests.adversary_assets(\n                self.api_type, self.api_sub_type, self.unique_id\n            )\n        if asset_type == 'PHONE':\n            return self.tc_requests.adversary_phone_assets(\n                self.api_type, self.api_sub_type, self.unique_id\n            )\n        if asset_type == 'HANDLER':\n            return self.tc_requests.adversary_handle_assets(\n                self.api_type, self.api_sub_type, self.unique_id\n            )\n        if asset_type == 'URL':\n            return self.tc_requests.adversary_url_assets(\n                self.api_type, self.api_sub_type, self.unique_id\n            )\n        self._tcex.handle_error(\n            925, ['asset_type', 'assets', 'asset_type', 'asset_type', asset_type]\n        )\n        return None",
    "docstring": "Retrieves all of the assets of a given asset_type\n\n        Args:\n            asset_type: (str) Either None, PHONE, HANDLER, or URL\n\n        Returns:"
  },
  {
    "code": "def utime(self, tarinfo, targetpath):\n        if not hasattr(os, 'utime'):\n            return\n        try:\n            os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))\n        except EnvironmentError as e:\n            raise ExtractError(\"could not change modification time\")",
    "docstring": "Set modification time of targetpath according to tarinfo."
  },
  {
    "code": "def get_from_category_qs(cls, category):\n        ids = cls.get_ties_for_categories_qs(category).values_list('object_id').distinct()\n        filter_kwargs = {'id__in': [i[0] for i in ids]}\n        return cls.objects.filter(**filter_kwargs)",
    "docstring": "Returns a QuerySet of objects of this type associated with the given category.\n\n        :param Category category:\n        :rtype: list\n        :return:"
  },
  {
    "code": "def drawImage(self, image):\n        padding = image.width() % 4\n        for i in range(0, image.height()):\n            tmp = image.copy(0, i, image.width() + padding, 1)\n            ptr = tmp.bits()\n            ptr.setsize(tmp.byteCount())\n            self._controller.sendUpdate(self._dx, i + self._dy, image.width() + self._dx - 1, i + self._dy, tmp.width(), tmp.height(), self._colorDepth, False, ptr.asstring())",
    "docstring": "Render of widget"
  },
  {
    "code": "def check_dependencies_remote(args):\n    cmd = [args.python, '-m', 'depends', args.requirement]\n    env = dict(PYTHONPATH=os.path.dirname(__file__))\n    return subprocess.check_call(cmd, env=env)",
    "docstring": "Invoke this command on a remote Python."
  },
  {
    "code": "def coverage(reportdir=None, extra=None):\n    import coverage as coverage_api\n    cov = coverage_api.coverage()\n    opts = {'directory': reportdir} if reportdir else {}\n    cov.start()\n    test(extra)\n    cov.stop()\n    cov.html_report(**opts)",
    "docstring": "Test this project with coverage reports"
  },
  {
    "code": "def encode_data_items(self, *args):\n        str_list = []\n        for arg in args:\n            if isinstance(arg, str):\n                arg_str = arg\n            elif isinstance(arg, int):\n                arg_str = self.INTEGER_PREFIX + self.encode_int(arg)\n            else:\n                arg_str = str(arg)\n            str_list.append(arg_str)\n        concatenated_str = self.SEPARATOR.join(str_list)\n        return concatenated_str",
    "docstring": "Encodes a list of integers and strings into a concatenated string.\n\n        - encode string items as-is.\n        - encode integer items as base-64 with a ``'~'`` prefix.\n        - concatenate encoded items with a ``'|'`` separator.\n\n        Example:\n            ``encode_data_items('abc', 123, 'xyz')`` returns ``'abc|~B7|xyz'``"
  },
  {
    "code": "def _is_defaultable(i, entry, table, check_for_aliases=True):\n    if (len(entry.sources) == 1 and\n            len(entry.route) == 1 and\n            None not in entry.sources):\n        source = next(iter(entry.sources))\n        sink = next(iter(entry.route))\n        if source.is_link and sink.is_link:\n            if source.opposite is sink:\n                key, mask = entry.key, entry.mask\n                if not check_for_aliases or \\\n                        not any(intersect(key, mask, d.key, d.mask) for\n                                d in table[i+1:]):\n                    return True\n    return False",
    "docstring": "Determine if an entry may be removed from a routing table and be\n    replaced by a default route.\n\n    Parameters\n    ----------\n    i : int\n        Position of the entry in the table\n    entry : RoutingTableEntry\n        The entry itself\n    table : [RoutingTableEntry, ...]\n        The table containing the entry.\n    check_for_aliases : bool\n        If True, the table is checked for aliased entries before suggesting a\n        route may be default routed."
  },
  {
    "code": "def export(self):\n        fields = ['id', 'host', 'port', 'user']\n        out = {}\n        for field in fields:\n            out[field] = getattr(self, field, None)\n        out['mountOptions'] = self.mount_opts\n        out['mountPoint'] = self.mount_point\n        out['beforeMount'] = self.cmd_before_mount\n        out['authType'] = self.auth_method\n        out['sshKey'] = self.ssh_key\n        return json.dumps(out, indent=4)",
    "docstring": "Serializes to JSON."
  },
  {
    "code": "def string_array_to_list(a):\n    result = []\n    length = javabridge.get_env().get_array_length(a)\n    wrapped = javabridge.get_env().get_object_array_elements(a)\n    for i in range(length):\n        result.append(javabridge.get_env().get_string(wrapped[i]))\n    return result",
    "docstring": "Turns the Java string array into Python unicode string list.\n\n    :param a: the string array to convert\n    :type a: JB_Object\n    :return: the string list\n    :rtype: list"
  },
  {
    "code": "def list_all_native_quantities(self, with_info=False):\n        q = self._native_quantities\n        return {k: self.get_quantity_info(k) for k in q} if with_info else list(q)",
    "docstring": "Return a list of all available native quantities in this catalog.\n\n        If *with_info* is `True`, return a dict with quantity info.\n\n        See also: list_all_quantities"
  },
  {
    "code": "def commit_buildroot(self):\n        logger.info(\"committing buildroot\")\n        self.ensure_is_built()\n        commit_message = \"docker build of '%s' (%s)\" % (self.image, self.uri)\n        self.buildroot_image_name = ImageName(\n            repo=\"buildroot-%s\" % self.image,\n            tag=datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))\n        self.buildroot_image_id = self.dt.commit_container(self.build_container_id, commit_message)\n        return self.buildroot_image_id",
    "docstring": "create image from buildroot\n\n        :return:"
  },
  {
    "code": "def set_posts_param_modified_after(self, params, post_type, status):\n        if not self.purge_first and not self.full and not self.modified_after:\n            if status == \"any\":\n                latest = Post.objects.filter(post_type=post_type).order_by(\"-modified\").first()\n            else:\n                latest = Post.objects.filter(post_type=post_type, status=status).order_by(\"-modified\").first()\n            if latest:\n                self.modified_after = latest.modified\n        if self.modified_after:\n            params[\"modified_after\"] = self.modified_after.isoformat()\n            logger.info(\"getting posts after: %s\", params[\"modified_after\"])",
    "docstring": "Set modified_after date to \"continue where we left off\" if appropriate\n\n        :param params: the GET params dict, which may be updated to include the \"modified_after\" key\n        :param post_type: post, page, attachment, or any custom post type set up in the WP API\n        :param status: publish, private, draft, etc.\n        :return: None"
  },
  {
    "code": "def get_output_score_metadata(self):\n        metadata = dict(self._mdata['output_score'])\n        metadata.update({'existing_decimal_values': self._my_map['outputScore']})\n        return Metadata(**metadata)",
    "docstring": "Gets the metadata for the output score start range.\n\n        return: (osid.Metadata) - metadata for the output score start\n                range\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def integers(self, start: int = 0, end: int = 10,\n                 length: int = 10) -> List[int]:\n        return self.random.randints(\n            length, start, end)",
    "docstring": "Generate a list of random integers.\n\n        Integers can be negative or positive numbers.\n        .. note: You can use both positive and negative numbers.\n\n        :param start: Start.\n        :param end: End.\n        :param length: Length of list.\n        :return: List of integers.\n\n        :Example:\n            [-20, -19, -18, -17]"
  },
  {
    "code": "def create(gandi, datacenter, bandwidth, ip_version, vlan, ip, attach,\n           background):\n    if ip_version != 4 and vlan:\n        gandi.echo('You must have an --ip-version to 4 when having a vlan.')\n        return\n    if ip and not vlan:\n        gandi.echo('You must have a --vlan when giving an --ip.')\n        return\n    vm_ = gandi.iaas.info(attach) if attach else None\n    if datacenter and vm_:\n        dc_id = gandi.datacenter.usable_id(datacenter)\n        if dc_id != vm_['datacenter_id']:\n            gandi.echo('The datacenter you provided does not match the '\n                       'datacenter of the vm you want to attach to.')\n            return\n    if not datacenter:\n        datacenter = vm_['datacenter_id'] if vm_ else 'LU'\n    try:\n        gandi.datacenter.is_opened(datacenter, 'iaas')\n    except DatacenterLimited as exc:\n        gandi.echo('/!\\ Datacenter %s will be closed on %s, '\n                   'please consider using another datacenter.' %\n                   (datacenter, exc.date))\n    return gandi.ip.create(ip_version, datacenter, bandwidth, attach,\n                           vlan, ip, background)",
    "docstring": "Create a public or private ip"
  },
  {
    "code": "def load_usps():\n    dataset_path = _load('usps')\n    df = _load_csv(dataset_path, 'data')\n    X = _load_images(os.path.join(dataset_path, 'images'), df.image)\n    y = df.label.values\n    return Dataset(load_usps.__doc__, X, y, accuracy_score, stratify=True)",
    "docstring": "USPs Digits Dataset.\n\n    The data of this dataset is a 3d numpy array vector with shape (224, 224, 3)\n    containing 9298 224x224 RGB photos of handwritten digits, and the target is\n    a 1d numpy integer array containing the label of the digit represented in\n    the image."
  },
  {
    "code": "def create_filter_predicate(self):\n        assert self.query_content_id is not None, \\\n            'must call SearchEngine.set_query_id first'\n        filter_names = self.query_params.getlist('filter')\n        if len(filter_names) == 0 and 'already_labeled' in self._filters:\n            filter_names = ['already_labeled']\n        init_filters = [(n, self._filters[n]) for n in filter_names]\n        preds = [lambda _: True]\n        for name, p in init_filters:\n            preds.append(p.set_query_id(self.query_content_id)\n                          .set_query_params(self.query_params)\n                          .create_predicate())\n        return lambda (cid, fc): fc is not None and all(p((cid, fc))\n                                                        for p in preds)",
    "docstring": "Creates a filter predicate.\n\n        The list of available filters is given by calls to\n        ``add_filter``, and the list of filters to use is given by\n        parameters in ``params``.\n\n        In this default implementation, multiple filters can be\n        specified with the ``filter`` parameter. Each filter is\n        initialized with the same set of query parameters given to the\n        search engine.\n\n        The returned function accepts a ``(content_id, FC)`` and\n        returns ``True`` if and only if every selected predicate\n        returns ``True`` on the same input."
  },
  {
    "code": "def cx_to_networkx(cx):\n    graph = networkx.MultiDiGraph()\n    for node_entry in get_aspect(cx, 'nodes'):\n        id = node_entry['@id']\n        attrs = get_attributes(get_aspect(cx, 'nodeAttributes'), id)\n        attrs['n'] = node_entry['n']\n        graph.add_node(id, **attrs)\n    for edge_entry in get_aspect(cx, 'edges'):\n        id = edge_entry['@id']\n        attrs = get_attributes(get_aspect(cx, 'edgeAttributes'), id)\n        attrs['i'] = edge_entry['i']\n        graph.add_edge(edge_entry['s'], edge_entry['t'], key=id, **attrs)\n    return graph",
    "docstring": "Return a MultiDiGraph representation of a CX network."
  },
  {
    "code": "def prep_pdf(qc_dir, config):\n    html_file = os.path.join(qc_dir, \"fastqc\", \"fastqc_report.html\")\n    html_fixed = \"%s-fixed%s\" % os.path.splitext(html_file)\n    try:\n        topdf = config_utils.get_program(\"wkhtmltopdf\", config)\n    except config_utils.CmdNotFound:\n        topdf = None\n    if topdf and utils.file_exists(html_file):\n        out_file = \"%s.pdf\" % os.path.splitext(html_file)[0]\n        if not utils.file_exists(out_file):\n            cmd = (\"sed 's/div.summary/div.summary-no/' %s | sed 's/div.main/div.main-no/' > %s\"\n                   % (html_file, html_fixed))\n            do.run(cmd, \"Fix fastqc CSS to be compatible with wkhtmltopdf\")\n            cmd = [topdf, html_fixed, out_file]\n            do.run(cmd, \"Convert QC HTML to PDF\")\n        return out_file",
    "docstring": "Create PDF from HTML summary outputs in QC directory.\n\n    Requires wkhtmltopdf installed: http://www.msweet.org/projects.php?Z1\n    Thanks to: https://www.biostars.org/p/16991/\n\n    Works around issues with CSS conversion on CentOS by adjusting CSS."
  },
  {
    "code": "def unpack(iterable, count, fill=None):\n    iterable = list(enumerate(iterable))\n    cnt = count if count <= len(iterable) else len(iterable)\n    results = [iterable[i][1] for i in range(cnt)]\n    results = merge(results, [fill for i in range(count-cnt)])\n    return tuple(results)",
    "docstring": "The iter data unpack function.\n\n    Example 1:\n        In[1]: source = 'abc'\n        In[2]: a, b = safe_unpack(source, 2)\n        In[3]: print(a, b)\n        a b\n\n    Example 2:\n        In[1]: source = 'abc'\n        In[2]: a, b, c, d = safe_unpack(source, 4)\n        In[3]: print(a, b, c, d)\n        a b None None"
  },
  {
    "code": "def get_productivity_stats(self, api_token, **kwargs):\n        params = {\n            'token': api_token\n        }\n        return self._get('get_productivity_stats', params, **kwargs)",
    "docstring": "Return a user's productivity stats.\n\n        :param api_token: The user's login api_token.\n        :type api_token: str\n        :return: The HTTP response to the request.\n        :rtype: :class:`requests.Response`"
  },
  {
    "code": "def aggregate_registry_timers():\n    import itertools\n    timers = sorted(shared_registry.values(), key=lambda t: t.desc)\n    aggregate_timers = []\n    for k, g in itertools.groupby(timers, key=lambda t: t.desc):\n        group = list(g)\n        num_calls = len(group)\n        total_elapsed_ms = sum(t.elapsed_time_ms for t in group)\n        first_start_time = min(t.start_time for t in group)\n        aggregate_timers.append(\n            (first_start_time, (k, total_elapsed_ms, num_calls)))\n    aggregate_timers.sort()\n    return zip(*aggregate_timers)[1]",
    "docstring": "Returns a list of aggregate timing information for registered timers.\n\n    Each element is a 3-tuple of\n\n        - timer description\n        - aggregate elapsed time\n        - number of calls\n\n    The list is sorted by the first start time of each aggregate timer."
  },
  {
    "code": "def copy_foreign_keys(self, event):\n        event_keys = set(event._meta.fields.keys())\n        obj_keys = self._meta.fields.keys()\n        matching_keys = event_keys.intersection(obj_keys)\n        for key in matching_keys:\n            if key == 'created_by':\n                continue\n            if not isinstance(self._meta.fields[key], peewee.ForeignKeyField):\n                continue\n            setattr(event, key, getattr(self, key))\n        possible_key = self.__class__.__name__.lower()\n        if possible_key in event_keys and event.code != 'AUDIT_DELETE':\n            setattr(event, possible_key, self)",
    "docstring": "Copies possible foreign key values from the object into the Event,\n        skipping common keys like modified and created.\n\n        Args:\n            event (Event): The Event instance to copy the FKs into\n            obj (fleaker.db.Model): The object to pull the values from"
  },
  {
    "code": "def purge(opts):\n    old = False\n    try:\n        environment = Environment.load(opts['ENVIRONMENT'], opts['--site'])\n    except DatacatsError:\n        environment = Environment.load(opts['ENVIRONMENT'], opts['--site'], data_only=True)\n        if get_format_version(environment.datadir) == 1:\n            old = True\n            environment = Environment.load(opts['ENVIRONMENT'], opts['--site'], allow_old=True)\n    if not opts['--delete-environment'] and not old:\n        environment.require_valid_site()\n    sites = [opts['--site']] if not opts['--delete-environment'] else environment.sites\n    if not opts['--yes']:\n        y_or_n_prompt('datacats purge will delete all stored data')\n    environment.stop_ckan()\n    environment.stop_supporting_containers()\n    environment.purge_data(sites)\n    if opts['--delete-environment']:\n        if environment.target:\n            rmtree(environment.target)\n        else:\n            DatacatsError((\"Unable to find the environment source\"\n            \" directory so that it can be deleted.\\n\"\n            \"Chances are it's because it already does not exist\"))",
    "docstring": "Purge environment database and uploaded files\n\nUsage:\n  datacats purge [-s NAME | --delete-environment] [-y] [ENVIRONMENT]\n\nOptions:\n  --delete-environment   Delete environment directory as well as its data, as\n                         well as the data for **all** sites.\n  -s --site=NAME         Specify a site to be purge [default: primary]\n  -y --yes               Respond yes to all prompts (i.e. force)\n\nENVIRONMENT may be an environment name or a path to an environment directory.\nDefault: '.'"
  },
  {
    "code": "def pixels_to_tiles(self, coords, clamp=True):\n        tile_coords = Vector2()\n        tile_coords.X = int(coords[0]) / self.spritesheet[0].width\n        tile_coords.Y = int(coords[1]) / self.spritesheet[0].height\n        if clamp:\n            tile_coords.X, tile_coords.Y = self.clamp_within_range(tile_coords.X, tile_coords.Y)\n        return tile_coords",
    "docstring": "Convert pixel coordinates into tile coordinates.\n        clamp determines if we should clamp the tiles to ones only on the tilemap."
  },
  {
    "code": "def has_uncacheable_headers(self, response):\n        cc_dict = get_header_dict(response, 'Cache-Control')\n        if cc_dict:\n            if 'max-age' in cc_dict and cc_dict['max-age'] == '0':\n                return True\n            if 'no-cache' in cc_dict:\n                return True\n            if 'private' in cc_dict:\n                return True\n        if response.has_header('Expires'):\n            if parse_http_date(response['Expires']) < time.time():\n                return True\n        return False",
    "docstring": "Should this response be cached based on it's headers\n            broken out from should_cache for flexibility"
  },
  {
    "code": "def send_msg_to_webhook(self, message):\n        payload = {\n            'content':message\n        }\n        header = {\n            'Content-Type':'application/json'\n        }\n        try:\n            request = requests.post(\n                self.api_url,\n                headers=header,\n                json=payload\n            )\n            request.raise_for_status()\n        except Exception as error_msg:\n            warning_msg = (\n                'EXCEPTION: UNABLE TO COMMIT LOG MESSAGE' +\n                '\\n\\texception={0}'.format(repr(error_msg)) +\n                '\\n\\tmessage={0}'.format(message)\n            )\n            warnings.warn(\n                warning_msg,\n                exceptions.WebhookFailedEmitWarning\n            )",
    "docstring": "separated Requests logic for easier testing\n\n        Args:\n            message (str): actual logging string to be passed to REST endpoint\n\n        Todo:\n            * Requests.text/json return for better testing options"
  },
  {
    "code": "def remover(self, id_rack):\n        if not is_valid_int_param(id_rack):\n            raise InvalidParameterError(\n                u'The identifier of Rack is invalid or was not informed.')\n        url = 'rack/' + str(id_rack) + '/'\n        code, xml = self.submit(None, 'DELETE', url)\n        return self.response(code, xml)",
    "docstring": "Remove Rack by the identifier.\n\n        :param id_rack: Identifier of the Rack. Integer value and greater than zero.\n\n        :return: None\n\n        :raise InvalidParameterError: The identifier of Rack is null and invalid.\n        :raise RackNaoExisteError: Rack not registered.\n        :raise RackError: Rack is associated with a script.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def reflect_right(self, value):\n        if value < self:\n            value = self.reflect(value)\n        return value",
    "docstring": "Only reflects the value if is < self."
  },
  {
    "code": "def run(self):\n        from zengine.models import User\n        user = User(username=self.manager.args.username, superuser=self.manager.args.super)\n        user.set_password(self.manager.args.password)\n        user.save()\n        print(\"New user created with ID: %s\" % user.key)",
    "docstring": "Creates user, encrypts password."
  },
  {
    "code": "def create_fw(self, tenant_id, data):\n        try:\n            return self._create_fw(tenant_id, data)\n        except Exception as exc:\n            LOG.error(\"Failed to create FW for device native, tenant \"\n                      \"%(tenant)s data %(data)s Exc %(exc)s\",\n                      {'tenant': tenant_id, 'data': data, 'exc': exc})\n            return False",
    "docstring": "Top level routine called when a FW is created."
  },
  {
    "code": "def ReplaceHomoglyphs(s):\n    homoglyphs = {\n        '\\xa0': ' ',\n        '\\u00e3': '',\n        '\\u00a0': ' ',\n        '\\u00a9': '(C)',\n        '\\u00ae': '(R)',\n        '\\u2014': '-',\n        '\\u2018': \"'\",\n        '\\u2019': \"'\",\n        '\\u201c': '\"',\n        '\\u201d': '\"',\n        '\\u2026': '...',\n        '\\u2e3a': '-',\n    }\n    def _ReplaceOne(c):\n        equiv = homoglyphs.get(c)\n        if equiv is not None:\n            return equiv\n        try:\n            c.encode('ascii')\n            return c\n        except UnicodeError:\n            pass\n        try:\n            return c.encode('unicode-escape').decode('ascii')\n        except UnicodeError:\n            return '?'\n    return ''.join([_ReplaceOne(c) for c in s])",
    "docstring": "Returns s with unicode homoglyphs replaced by ascii equivalents."
  },
  {
    "code": "def get_first_model_with_rest_name(cls, rest_name):\n        models = cls.get_models_with_rest_name(rest_name)\n        if len(models) > 0:\n            return models[0]\n        return None",
    "docstring": "Get the first model corresponding to a rest_name\n\n            Args:\n                rest_name: the rest name"
  },
  {
    "code": "def outline(self, inner, outer):\n        return self.dilate(outer).exclude(self.dilate(inner))",
    "docstring": "Compute region outline by differencing two dilations.\n\n        Parameters\n        ----------\n        inner : int\n            Size of inner outline boundary (in pixels)\n\n        outer : int\n            Size of outer outline boundary (in pixels)"
  },
  {
    "code": "def kwargs_to_variable_assignment(kwargs: dict, value_representation=repr,\n                                  assignment_operator: str = ' = ',\n                                  statement_separator: str = '\\n',\n                                  statement_per_line: bool = False) -> str:\n    code = []\n    join_str = '\\n' if statement_per_line else ''\n    for key, value in kwargs.items():\n        code.append(key + assignment_operator +\n                    value_representation(value)+statement_separator)\n    return join_str.join(code)",
    "docstring": "Convert a dictionary into a string with assignments\n\n    Each assignment is constructed based on:\n    key assignment_operator value_representation(value) statement_separator,\n    where key and value are the key and value of the dictionary.\n    Moreover one can seprate the assignment statements by new lines.\n\n    Parameters\n    ----------\n    kwargs : dict\n\n    assignment_operator: str, optional:\n        Assignment operator (\" = \" in python)\n    value_representation: str, optinal\n        How to represent the value in the assignments (repr function in python)\n    statement_separator : str, optional:\n        Statement separator (new line in python)\n    statement_per_line: bool, optional\n        Insert each statement on a different line\n\n    Returns\n    -------\n    str\n        All the assignemnts.\n\n    >>> kwargs_to_variable_assignment({'a': 2, 'b': \"abc\"})\n    \"a = 2\\\\nb = 'abc'\\\\n\"\n    >>> kwargs_to_variable_assignment({'a':2 ,'b': \"abc\"}, statement_per_line=True)\n    \"a = 2\\\\n\\\\nb = 'abc'\\\\n\"\n    >>> kwargs_to_variable_assignment({'a': 2})\n    'a = 2\\\\n'\n    >>> kwargs_to_variable_assignment({'a': 2}, statement_per_line=True)\n    'a = 2\\\\n'"
  },
  {
    "code": "def add_schema(self, schema):\n        if isinstance(schema, SchemaBuilder):\n            schema_uri = schema.schema_uri\n            schema = schema.to_schema()\n            if schema_uri is None:\n                del schema['$schema']\n        elif isinstance(schema, SchemaNode):\n            schema = schema.to_schema()\n        if '$schema' in schema:\n            self.schema_uri = self.schema_uri or schema['$schema']\n            schema = dict(schema)\n            del schema['$schema']\n        self._root_node.add_schema(schema)",
    "docstring": "Merge in a JSON schema. This can be a ``dict`` or another\n        ``SchemaBuilder``\n\n        :param schema: a JSON Schema\n\n        .. note::\n            There is no schema validation. If you pass in a bad schema,\n            you might get back a bad schema."
  },
  {
    "code": "def gaussian_pdf(x, g):\n        return (\n            numpy.exp(-(x - g.mean) ** 2 / 2. /g.var) /\n            numpy.sqrt(g.var * 2 * numpy.pi)\n            )",
    "docstring": "Gaussian probability density function at ``x`` for |GVar| ``g``."
  },
  {
    "code": "def view_set(method_name):\n    def view_set(value, context, **_params):\n        method = getattr(context[\"view\"], method_name)\n        return _set(method, context[\"key\"], value, (), {})\n    return view_set",
    "docstring": "Creates a setter that will call the view method with the context's\n    key as first parameter and the value as second parameter.\n    @param method_name: the name of a method belonging to the view.\n    @type method_name: str"
  },
  {
    "code": "def download_as_json(url):\n    try:\n        return Response('application/json', request(url=url)).read()\n    except HTTPError as err:\n        raise ResponseException('application/json', err)",
    "docstring": "Download the data at the URL and load it as JSON"
  },
  {
    "code": "def get_filename(self, variable):\n        fn2var = self._type2filename2variable.get(type(variable), {})\n        for (fn_, var) in fn2var.items():\n            if var == variable:\n                return fn_\n        return None",
    "docstring": "Return the auxiliary file name the given variable is allocated\n        to or |None| if the given variable is not allocated to any\n        auxiliary file name.\n\n        >>> from hydpy import dummies\n        >>> eqb = dummies.v2af.eqb[0]\n        >>> dummies.v2af.get_filename(eqb)\n        'file1'\n        >>> eqb += 500.0\n        >>> dummies.v2af.get_filename(eqb)"
  },
  {
    "code": "def get_pdffilepath(pdffilename):\n        return FILEPATHSTR.format(\n            root_dir=ROOT_DIR, os_sep=os.sep, os_extsep=os.extsep,\n            name=pdffilename,\n            folder=PURPOSE.get(\"plots\").get(\"folder\", \"plots\"),\n            ext=PURPOSE.get(\"plots\").get(\"extension\", \"pdf\")\n        )",
    "docstring": "Returns the path for the pdf file\n\n        args:\n            pdffilename: string\n                returns path for the plots folder / pdffilename.pdf"
  },
  {
    "code": "def ast_to_html(self, ast, link_resolver):\n        out, _ = cmark.ast_to_html(ast, link_resolver)\n        return out",
    "docstring": "See the documentation of `to_ast` for\n        more information.\n\n        Args:\n            ast: PyCapsule, a capsule as returned by `to_ast`\n            link_resolver: hotdoc.core.links.LinkResolver, a link\n                resolver instance."
  },
  {
    "code": "def _check_input_symbols(self, X):\n        symbols = np.concatenate(X)\n        if (len(symbols) == 1\n            or not np.issubdtype(symbols.dtype, np.integer)\n            or (symbols < 0).any()):\n            return False\n        u = np.unique(symbols)\n        return u[0] == 0 and u[-1] == len(u) - 1",
    "docstring": "Check if ``X`` is a sample from a Multinomial distribution.\n\n        That is ``X`` should be an array of non-negative integers from\n        range ``[min(X), max(X)]``, such that each integer from the range\n        occurs in ``X`` at least once.\n\n        For example ``[0, 0, 2, 1, 3, 1, 1]`` is a valid sample from a\n        Multinomial distribution, while ``[0, 0, 3, 5, 10]`` is not."
  },
  {
    "code": "def summary(self, h):\n        _, losses, _ = self.run(h=h)\n        df = pd.DataFrame(losses)\n        df.index = ['Ensemble'] + self.model_names\n        df.columns = [self.loss_name]\n        return df",
    "docstring": "Summarize the results for each model for h steps of the algorithm\n\n       Parameters\n        ----------\n        h : int\n            How many steps to run the aggregating algorithm on \n\n        Returns\n        ----------\n        - pd.DataFrame of losses for each model"
  },
  {
    "code": "async def init(\n        self,\n        *,\n        advertise_addr: str = None,\n        listen_addr: str = \"0.0.0.0:2377\",\n        force_new_cluster: bool = False,\n        swarm_spec: Mapping = None\n    ) -> str:\n        data = {\n            \"AdvertiseAddr\": advertise_addr,\n            \"ListenAddr\": listen_addr,\n            \"ForceNewCluster\": force_new_cluster,\n            \"Spec\": swarm_spec,\n        }\n        response = await self.docker._query_json(\"swarm/init\", method=\"POST\", data=data)\n        return response",
    "docstring": "Initialize a new swarm.\n\n        Args:\n            ListenAddr: listen address used for inter-manager communication\n            AdvertiseAddr: address advertised to other nodes.\n            ForceNewCluster: Force creation of a new swarm.\n            SwarmSpec: User modifiable swarm configuration.\n\n        Returns:\n            id of the swarm node"
  },
  {
    "code": "def _collect_unused(self, start: GridQubit,\n                        used: Set[GridQubit]) -> Set[GridQubit]:\n        def collect(n: GridQubit, visited: Set[GridQubit]):\n            visited.add(n)\n            for m in self._c_adj[n]:\n                if m not in used and m not in visited:\n                    collect(m, visited)\n        visited = set()\n        collect(start, visited)\n        return visited",
    "docstring": "Lists all the qubits that are reachable from given qubit.\n\n        Args:\n            start: The first qubit for which connectivity should be calculated.\n                   Might be a member of used set.\n            used: Already used qubits, which cannot be used during the\n                  collection.\n\n        Returns:\n            Set of qubits that are reachable from starting qubit without\n            traversing any of the used qubits."
  },
  {
    "code": "def merge_config(\n    config: Mapping[str, Any],\n    override_config: Mapping[str, Any] = None,\n    override_config_fn: str = None,\n) -> Mapping[str, Any]:\n    if override_config_fn:\n        with open(override_config_fn, \"r\") as f:\n            override_config = yaml.load(f, Loader=yaml.SafeLoader)\n    if not override_config:\n        log.info(\"Missing override_config\")\n    return functools.reduce(rec_merge, (config, override_config))",
    "docstring": "Override config with additional configuration in override_config or override_config_fn\n\n    Used in script to merge CLI options with Config\n\n    Args:\n        config: original configuration\n        override_config: new configuration to override/extend current config\n        override_config_fn: new configuration filename as YAML file"
  },
  {
    "code": "def new_project(self, project_root):\n        profile = Profile(**self.to_profile_info())\n        profile.validate()\n        project = Project.from_project_root(project_root, {})\n        cfg = self.from_parts(\n            project=project,\n            profile=profile,\n            args=deepcopy(self.args),\n        )\n        cfg.quoting = deepcopy(self.quoting)\n        return cfg",
    "docstring": "Given a new project root, read in its project dictionary, supply the\n        existing project's profile info, and create a new project file.\n\n        :param project_root str: A filepath to a dbt project.\n        :raises DbtProfileError: If the profile is invalid.\n        :raises DbtProjectError: If project is missing or invalid.\n        :returns RuntimeConfig: The new configuration."
  },
  {
    "code": "def start_new_gui_thread():\n    PyGUIThread = getattr(ROOT, 'PyGUIThread', None)\n    if PyGUIThread is not None:\n        assert not PyGUIThread.isAlive(), \"GUI thread already running!\"\n    assert _processRootEvents, (\n        \"GUI thread wasn't started when rootwait was imported, \"\n        \"so it can't be restarted\")\n    ROOT.keeppolling = 1\n    ROOT.PyGUIThread = threading.Thread(\n        None, _processRootEvents, None, (ROOT,))\n    ROOT.PyGUIThread.finishSchedule = _finishSchedule\n    ROOT.PyGUIThread.setDaemon(1)\n    ROOT.PyGUIThread.start()\n    log.debug(\"successfully started a new GUI thread\")",
    "docstring": "Attempt to start a new GUI thread, if possible.\n\n    It is only possible to start one if there was one running on module import."
  },
  {
    "code": "async def get_version(self, timeout: int = 15) -> Optional[str]:\n        command = [\"-version\"]\n        is_open = await self.open(cmd=command, input_source=None, output=\"\")\n        if not is_open:\n            _LOGGER.warning(\"Error starting FFmpeg.\")\n            return\n        try:\n            proc_func = functools.partial(self._proc.communicate, timeout=timeout)\n            output, _ = await self._loop.run_in_executor(None, proc_func)\n            result = re.search(r\"ffmpeg version (\\S*)\", output.decode())\n            if result is not None:\n                return result.group(1)\n        except (subprocess.TimeoutExpired, ValueError):\n            _LOGGER.warning(\"Timeout reading stdout.\")\n            self.kill()\n        return None",
    "docstring": "Execute FFmpeg process and parse the version information.\n\n        Return full FFmpeg version string. Such as 3.4.2-tessus"
  },
  {
    "code": "def flds_firstsort(d):\n    shape = [ len( np.unique(d[l]) )\n              for l in ['xs', 'ys', 'zs'] ];\n    si = np.lexsort((d['z'],d['y'],d['x']));\n    return si,shape;",
    "docstring": "Perform a lexsort and return the sort indices and shape as a tuple."
  },
  {
    "code": "def init_can(self, channel=Channel.CHANNEL_CH0, BTR=Baudrate.BAUD_1MBit, baudrate=BaudrateEx.BAUDEX_USE_BTR01,\n                 AMR=AMR_ALL, ACR=ACR_ALL, mode=Mode.MODE_NORMAL, OCR=OutputControl.OCR_DEFAULT,\n                 rx_buffer_entries=DEFAULT_BUFFER_ENTRIES, tx_buffer_entries=DEFAULT_BUFFER_ENTRIES):\n        if not self._ch_is_initialized.get(channel, False):\n            init_param = InitCanParam(mode, BTR, OCR, AMR, ACR, baudrate, rx_buffer_entries, tx_buffer_entries)\n            UcanInitCanEx2(self._handle, channel, init_param)\n            self._ch_is_initialized[channel] = True",
    "docstring": "Initializes a specific CAN channel of a device.\n\n        :param int channel: CAN channel to be initialized (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).\n        :param int BTR:\n            Baud rate register BTR0 as high byte, baud rate register BTR1 as low byte (see enum :class:`Baudrate`).\n        :param int baudrate: Baud rate register for all systec USB-CANmoduls (see enum :class:`BaudrateEx`).\n        :param int AMR: Acceptance filter mask (see method :meth:`set_acceptance`).\n        :param int ACR: Acceptance filter code (see method :meth:`set_acceptance`).\n        :param int mode: Transmission mode of CAN channel (see enum :class:`Mode`).\n        :param int OCR: Output Control Register (see enum :class:`OutputControl`).\n        :param int rx_buffer_entries: The number of maximum entries in the receive buffer.\n        :param int tx_buffer_entries: The number of maximum entries in the transmit buffer."
  },
  {
    "code": "def show_warning(message):\r\n    try:\r\n        import Tkinter, tkMessageBox\r\n        root = Tkinter.Tk()\r\n        root.withdraw()\r\n        tkMessageBox.showerror(\"Spyder\", message)\r\n    except ImportError:\r\n        pass\r\n    raise RuntimeError(message)",
    "docstring": "Show warning using Tkinter if available"
  },
  {
    "code": "def iter_breadth_first(self, root=None):\n        if root == None:\n            root = self\n        yield root\n        last = root \n        for node in self.iter_breadth_first(root):\n            if isinstance(node, DictCell):\n                for subpart in node:\n                    yield subpart\n                    last = subpart\n            if last == node:\n                return",
    "docstring": "Traverses the belief state's structure breadth-first"
  },
  {
    "code": "def micromanager_metadata(self):\n        if not self.is_micromanager:\n            return None\n        result = read_micromanager_metadata(self._fh)\n        result.update(self.pages[0].tags['MicroManagerMetadata'].value)\n        return result",
    "docstring": "Return consolidated MicroManager metadata as dict."
  },
  {
    "code": "def handle_json_wrapper_GET(self, handler, parsed_params):\n    schedule = self.server.schedule\n    result = handler(parsed_params)\n    content = ResultEncoder().encode(result)\n    self.send_response(200)\n    self.send_header('Content-Type', 'text/plain')\n    self.send_header('Content-Length', str(len(content)))\n    self.end_headers()\n    self.wfile.write(content)",
    "docstring": "Call handler and output the return value in JSON."
  },
  {
    "code": "def guess_wxr_version(self, tree):\n        for v in ('1.2', '1.1', '1.0'):\n            try:\n                tree.find('channel/{%s}wxr_version' % (WP_NS % v)).text\n                return v\n            except AttributeError:\n                pass\n        raise CommandError('Cannot resolve the wordpress namespace')",
    "docstring": "We will try to guess the wxr version used\n        to complete the wordpress xml namespace name."
  },
  {
    "code": "def label_search(self, label:str) -> List[dict]:\n        ilx_rows = self.label2rows(self.local_degrade(label))\n        if not ilx_rows:\n            return None\n        else:\n            return ilx_rows",
    "docstring": "Returns the rows in InterLex associated with that label\n\n        Note:\n            Pressumed to have duplicated labels in InterLex\n        Args:\n            label: label of the entity you want to find\n        Returns:\n            None or List[dict]"
  },
  {
    "code": "def episode_info(self, cosmoid, season, episode, **kwargs):\n        resource = 'season/%d/episode/%d/info' % (season, episode)\n        return self._cosmoid_request(resource, cosmoid, **kwargs)",
    "docstring": "Returns information about an episode in a television series\n\n        Maps to the `episode info <http://prod-doc.rovicorp.com/mashery/index.php/V1.MetaData.VideoService.Video:SeasonEpisode>`_ API method."
  },
  {
    "code": "def enrich(self, columns):\n        for column in columns:\n            if column not in self.data.columns:\n                return self.data\n        first_column = list(self.data[columns[0]])\n        count = 0\n        append_df = pandas.DataFrame()\n        for cell in first_column:\n            if len(cell) >= 1:\n                df = pandas.DataFrame()\n                for column in columns:\n                    df[column] = self.data.loc[count, column]\n                extra_df = pandas.DataFrame([self.data.loc[count]] * len(df))\n                for column in columns:\n                    extra_df[column] = list(df[column])\n                append_df = append_df.append(extra_df, ignore_index=True)\n                extra_df = pandas.DataFrame()\n            count = count + 1\n        self.data = self.data.append(append_df, ignore_index=True)\n        return self.data",
    "docstring": "This method appends at the end of the dataframe as many\n        rows as items are found in the list of elemnents in the\n        provided columns.\n\n        This assumes that the length of the lists for the several\n        specified columns is the same. As an example, for the row A\n        {\"C1\":\"V1\", \"C2\":field1, \"C3\":field2, \"C4\":field3}\n        we have three cells with a list of four elements each of them:\n        * field1: [1,2,3,4]\n        * field2: [\"a\", \"b\", \"c\", \"d\"]\n        * field3: [1.1, 2.2, 3.3, 4.4]\n\n        This method converts each of the elements of each cell in a new\n        row keeping the columns name:\n\n        {\"C1\":\"V1\", \"C2\":1, \"C3\":\"a\", \"C4\":1.1}\n        {\"C1\":\"V1\", \"C2\":2, \"C3\":\"b\", \"C4\":2.2}\n        {\"C1\":\"V1\", \"C2\":3, \"C3\":\"c\", \"C4\":3.3}\n        {\"C1\":\"V1\", \"C2\":4, \"C3\":\"d\", \"C4\":4.4}\n\n        :param columns: list of strings\n        :rtype pandas.DataFrame"
  },
  {
    "code": "def kruskal(graph, weight):\n    uf = UnionFind(len(graph))\n    edges = []\n    for u in range(len(graph)):\n        for v in graph[u]:\n            edges.append((weight[u][v], u, v))\n    edges.sort()\n    mst = []\n    for w, u, v in edges:\n        if uf.union(u, v):\n            mst.append((u, v))\n    return mst",
    "docstring": "Minimum spanning tree by Kruskal\n\n    :param graph: undirected graph in listlist or listdict format\n    :param weight: in matrix format or same listdict graph\n    :returns: list of edges of the tree\n    :complexity: ``O(|E|log|E|)``"
  },
  {
    "code": "def descriptions(cls):\n        schema = cls.json_get('%s/status/schema' % cls.api_url, empty_key=True,\n                              send_key=False)\n        descs = {}\n        for val in schema['fields']['status']['value']:\n            descs.update(val)\n        return descs",
    "docstring": "Retrieve status descriptions from status.gandi.net."
  },
  {
    "code": "def queue_files(dirpath, queue):\n    for root, _, files in os.walk(os.path.abspath(dirpath)):\n        if not files:\n            continue\n        for filename in files:\n            queue.put(os.path.join(root, filename))",
    "docstring": "Add files in a directory to a queue"
  },
  {
    "code": "def generate_sample_cfn_module(env_root, module_dir=None):\n    if module_dir is None:\n        module_dir = os.path.join(env_root, 'sampleapp.cfn')\n    generate_sample_module(module_dir)\n    for i in ['stacks.yaml', 'dev-us-east-1.env']:\n        shutil.copyfile(\n            os.path.join(ROOT,\n                         'templates',\n                         'cfn',\n                         i),\n            os.path.join(module_dir, i)\n        )\n    os.mkdir(os.path.join(module_dir, 'templates'))\n    with open(os.path.join(module_dir,\n                           'templates',\n                           'tf_state.yml'), 'w') as stream:\n        stream.write(\n            cfn_flip.flip(\n                check_output(\n                    [sys.executable,\n                     os.path.join(ROOT,\n                                  'templates',\n                                  'stacker',\n                                  'tfstate_blueprints',\n                                  'tf_state.py')]\n                )\n            )\n        )\n    LOGGER.info(\"Sample CloudFormation module created at %s\",\n                module_dir)",
    "docstring": "Generate skeleton CloudFormation sample module."
  },
  {
    "code": "def namespace(self, prefix=None):\n        e = self.__deref()\n        if e is not None:\n            return e.namespace(prefix)\n        return super(Element, self).namespace()",
    "docstring": "Get this schema element's target namespace.\n\n        In case of reference elements, the target namespace is defined by the\n        referenced and not the referencing element node.\n\n        @param prefix: The default prefix.\n        @type prefix: str\n        @return: The schema element's target namespace\n        @rtype: (I{prefix},I{URI})"
  },
  {
    "code": "def query_boost_version(boost_root):\n        boost_version = None\n        if os.path.exists(os.path.join(boost_root,'Jamroot')):\n            with codecs.open(os.path.join(boost_root,'Jamroot'), 'r', 'utf-8') as f:\n                for line in f.readlines():\n                    parts = line.split()\n                    if len(parts) >= 5 and parts[1] == 'BOOST_VERSION':\n                        boost_version = parts[3]\n                        break\n        if not boost_version:\n            boost_version = 'default'\n        return boost_version",
    "docstring": "Read in the Boost version from a given boost_root."
  },
  {
    "code": "def get_tool_definition(self, target):\n        if target not in self.targets_mcu_list:\n            logging.debug(\"Target not found in definitions\")\n            return None\n        mcu_record = self.targets.get_mcu_record(target) if self.mcus.get_mcu_record(target) is None else self.mcus.get_mcu_record(target)\n        try:\n            return mcu_record['tool_specific'][self.tool]\n        except KeyError:\n            return None",
    "docstring": "Returns tool specific dic or None if it does not exist for defined tool"
  },
  {
    "code": "def get_rotated(self, angle):\n        result = self.copy()\n        result.rotate(angle)\n        return result",
    "docstring": "Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise."
  },
  {
    "code": "def out_interactions_iter(self, nbunch=None, t=None):\n        if nbunch is None:\n            nodes_nbrs_succ = self._succ.items()\n        else:\n            nodes_nbrs_succ = [(n, self._succ[n]) for n in self.nbunch_iter(nbunch)]\n        for n, nbrs in nodes_nbrs_succ:\n            for nbr in nbrs:\n                if t is not None:\n                    if self.__presence_test(n, nbr, t):\n                        yield (n, nbr, {\"t\": [t]})\n                else:\n                    if nbr in self._succ[n]:\n                        yield (n, nbr, self._succ[n][nbr])",
    "docstring": "Return an iterator over the out interactions present in a given snapshot.\n\n        Edges are returned as tuples\n        in the order (node, neighbor).\n\n        Parameters\n        ----------\n        nbunch : iterable container, optional (default= all nodes)\n            A container of nodes.  The container will be iterated\n            through once.\n        t : snapshot id (default=None)\n            If None the the method returns an iterator over the edges of the flattened graph.\n\n        Returns\n        -------\n        edge_iter : iterator\n            An iterator of (u,v) tuples of interaction.\n\n        Notes\n        -----\n        Nodes in nbunch that are not in the graph will be (quietly) ignored.\n        For directed graphs this returns the out-interaction.\n\n        Examples\n        --------\n        >>> G = dn.DynDiGraph()\n        >>> G.add_interaction(0,1, 0)\n        >>> G.add_interaction(1,2, 0)\n        >>> G.add_interaction(2,3,1)\n        >>> [e for e in G.out_interactions_iter(t=0)]\n        [(0, 1), (1, 2)]\n        >>> list(G.out_interactions_iter())\n        [(0, 1), (1, 2), (2, 3)]"
  },
  {
    "code": "def open_subreddit_page(self, name):\n        from .subreddit_page import SubredditPage\n        with self.term.loader('Loading subreddit'):\n            page = SubredditPage(self.reddit, self.term, self.config,\n                                 self.oauth, name)\n        if not self.term.loader.exception:\n            return page",
    "docstring": "Open an instance of the subreddit page for the given subreddit name."
  },
  {
    "code": "def _data_update(subjects, queue, run_flag):\n        while run_flag.running:\n            while not queue.empty():\n                data = queue.get()\n                for subject in [s for s in subjects if not s.is_disposed]:\n                    subject.on_next(data)\n            time.sleep(0.1)",
    "docstring": "Get data from backgound process and notify all subscribed observers with the new data"
  },
  {
    "code": "def list_launch_configurations(region=None, key=None, keyid=None,\n                                profile=None):\n    ret = get_all_launch_configurations(region, key, keyid, profile)\n    return [r.name for r in ret]",
    "docstring": "List all Launch Configurations.\n\n    CLI example::\n\n        salt myminion boto_asg.list_launch_configurations"
  },
  {
    "code": "def volume_delete(pool, volume, **kwargs):\n    conn = __get_conn(**kwargs)\n    try:\n        vol = _get_storage_vol(conn, pool, volume)\n        return not bool(vol.delete())\n    finally:\n        conn.close()",
    "docstring": "Delete a libvirt managed volume.\n\n    :param pool: libvirt storage pool name\n    :param volume: name of the volume to delete\n    :param connection: libvirt connection URI, overriding defaults\n    :param username: username to connect with, overriding defaults\n    :param password: password to connect with, overriding defaults\n\n    .. versionadded:: Neon\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt \"*\" virt.volume_delete <pool> <volume>"
  },
  {
    "code": "def save_csv(p, sheet):\n    'Save as single CSV file, handling column names as first line.'\n    with p.open_text(mode='w') as fp:\n        cw = csv.writer(fp, **csvoptions())\n        colnames = [col.name for col in sheet.visibleCols]\n        if ''.join(colnames):\n            cw.writerow(colnames)\n        for r in Progress(sheet.rows, 'saving'):\n            cw.writerow([col.getDisplayValue(r) for col in sheet.visibleCols])",
    "docstring": "Save as single CSV file, handling column names as first line."
  },
  {
    "code": "def random(self, *args, **kwargs):\n        indexer = Random()\n        self.add(indexer)\n        return self",
    "docstring": "Add a random index.\n\n        Shortcut of :class:`recordlinkage.index.Random`::\n\n            from recordlinkage.index import Random\n\n            indexer = recordlinkage.Index()\n            indexer.add(Random())"
  },
  {
    "code": "def create(self, name, network):\n        if not network in SUPPORTED_NETWORKS:\n            raise ValueError('Network not valid!')\n        account = self.wrap(self.resource.create(dict(name=name,\n                                                      network=network)))\n        self.add(account)\n        return account",
    "docstring": "Create a new Account object and add it to this Accounts collection.\n\n        Args:\n          name (str): Account name\n          network (str): Type of cryptocurrency.  Can be one of, 'bitcoin', '\n            bitcoin_testnet', 'litecoin', 'dogecoin'.\n\n        Returns: The new round.Account"
  },
  {
    "code": "def get_peak_mem():\n    import resource\n    rusage_denom = 1024.\n    if sys.platform == 'darwin':\n        rusage_denom = rusage_denom * rusage_denom\n    mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / rusage_denom\n    return mem",
    "docstring": "this returns peak memory use since process starts till the moment its called"
  },
  {
    "code": "def img2code(self, key, img):\n        code_template = \\\n            \"wx.ImageFromData({width}, {height}, \" + \\\n            \"bz2.decompress(base64.b64decode('{data}'))).ConvertToBitmap()\"\n        code_alpha_template = \\\n            \"wx.ImageFromDataWithAlpha({width}, {height}, \" + \\\n            \"bz2.decompress(base64.b64decode('{data}')), \" + \\\n            \"bz2.decompress(base64.b64decode('{alpha}'))).ConvertToBitmap()\"\n        data = base64.b64encode(bz2.compress(img.GetData(), 9))\n        if img.HasAlpha():\n            alpha = base64.b64encode(bz2.compress(img.GetAlphaData(), 9))\n            code_str = code_alpha_template.format(\n                width=img.GetWidth(), height=img.GetHeight(),\n                data=data, alpha=alpha)\n        else:\n            code_str = code_template.format(width=img.GetWidth(),\n                                            height=img.GetHeight(), data=data)\n        return code_str",
    "docstring": "Pastes wx.Image into single cell"
  },
  {
    "code": "def register(self, *args):\n        super(ConfigurableMeta, self).register(*args)\n        from hfos.database import configschemastore\n        configschemastore[self.name] = self.configschema",
    "docstring": "Register a configurable component in the configuration schema\n        store"
  },
  {
    "code": "def update_snapshot(self, snapshot, display_name=None,\n            display_description=None):\n        return snapshot.update(display_name=display_name,\n                display_description=display_description)",
    "docstring": "Update the specified values on the specified snapshot. You may specify\n        one or more values to update."
  },
  {
    "code": "def fit(self, col):\n        dates = self.safe_datetime_cast(col)\n        self.default_val = dates.groupby(dates).count().index[0].timestamp() * 1e9",
    "docstring": "Prepare the transformer to convert data.\n\n        Args:\n            col(pandas.DataFrame): Data to transform.\n\n        Returns:\n            None"
  },
  {
    "code": "def certify_parameter(certifier, name, value, kwargs=None):\n    try:\n        certifier(value, **kwargs or {})\n    except CertifierError as err:\n        six.raise_from(\n            CertifierParamError(\n                name,\n                value,\n            ),\n            err)",
    "docstring": "Internal certifier for kwargs passed to Certifiable public methods.\n\n    :param callable certifier:\n        The certifier to use\n    :param str name:\n        The name of the kwargs\n    :param object value:\n        The value of the kwarg.\n    :param bool required:\n        Is the param required. Default=False.\n    :raises CertifierParamError:\n        A parameter failed internal certification."
  },
  {
    "code": "def viterbi_alignment(es, fs, t, a):\r\n    max_a = collections.defaultdict(float)\r\n    l_e = len(es)\r\n    l_f = len(fs)\r\n    for (j, e) in enumerate(es, 1):\r\n        current_max = (0, -1)\r\n        for (i, f) in enumerate(fs, 1):\r\n            val = t[(e, f)] * a[(i, j, l_e, l_f)]\r\n            if current_max[1] < val:\r\n                current_max = (i, val)\r\n        max_a[j] = current_max[0]\r\n    return max_a",
    "docstring": "return\r\n        dictionary\r\n            e in es -> f in fs"
  },
  {
    "code": "def _to_list(obj):\n    ret = {}\n    for attr in __attrs:\n        if hasattr(obj, attr):\n            ret[attr] = getattr(obj, attr)\n    return ret",
    "docstring": "Convert snetinfo object to list"
  },
  {
    "code": "def uri(self):\n        return url_for(\n            '.{0}_files'.format(self.pid.pid_type),\n            pid_value=self.pid.pid_value,\n            filename=self.file.key)",
    "docstring": "Get file download link.\n\n        ..  note::\n\n            The URI generation assumes that you can download the file using the\n            view ``invenio_records_ui.<pid_type>_files``."
  },
  {
    "code": "def patch_os_module():\n\tif not hasattr(os, 'symlink'):\n\t\tos.symlink = symlink\n\t\tos.path.islink = islink\n\tif not hasattr(os, 'readlink'):\n\t\tos.readlink = readlink",
    "docstring": "jaraco.windows provides the os.symlink and os.readlink functions.\n\tMonkey-patch the os module to include them if not present."
  },
  {
    "code": "def _check_states_enum(cls):\n        states_enum_name = cls.context.get_config('states_enum_name')\n        try:\n            cls.context['states_enum'] = getattr(\n                cls.context.new_class, states_enum_name)\n        except AttributeError:\n            raise ValueError('No states enum given!')\n        proper = True\n        try:\n            if not issubclass(cls.context.states_enum, Enum):\n                proper = False\n        except TypeError:\n            proper = False\n        if not proper:\n            raise ValueError(\n                'Please provide enum instance to define available states.')",
    "docstring": "Check if states enum exists and is proper one."
  },
  {
    "code": "def copy(self):\n        return self.__class__(self, key=self._keyfn, precedes=self._precedes)",
    "docstring": "Return a shallow copy of a pqdict."
  },
  {
    "code": "def serialize_attrs(self, *args):\n        cls = type(self)\n        result = {}\n        for a in args:\n            if hasattr(cls, a) and a not in cls.attrs_forbidden_for_serialization():\n                val = getattr(self, a)\n                if is_list_like(val):\n                    result[a] = list(val)\n                else:\n                    result[a] = val\n        return result",
    "docstring": "Converts and instance to a dictionary with only the specified\n        attributes as keys\n\n        Args:\n            *args (list): The attributes to serialize\n\n        Examples:\n\n            >>> customer = Customer.create(name=\"James Bond\", email=\"007@mi.com\",\n                                           phone=\"007\", city=\"London\")\n            >>> customer.serialize_attrs('name', 'email')\n            {'name': u'James Bond', 'email': u'007@mi.com'}"
  },
  {
    "code": "def are_equal(value1, value2):\n        if value1 == None or value2 == None:\n            return True\n        if value1 == None or value2 == None:\n            return False\n        return value1 == value2",
    "docstring": "Checks if two values are equal. The operation can be performed over values of any type.\n\n        :param value1: the first value to compare\n\n        :param value2: the second value to compare\n\n        :return: true if values are equal and false otherwise"
  },
  {
    "code": "def replace(zpool, old_device, new_device=None, force=False):\n    flags = []\n    target = []\n    if force:\n        flags.append('-f')\n    target.append(zpool)\n    target.append(old_device)\n    if new_device:\n        target.append(new_device)\n    res = __salt__['cmd.run_all'](\n        __utils__['zfs.zpool_command'](\n            command='replace',\n            flags=flags,\n            target=target,\n        ),\n        python_shell=False,\n    )\n    ret = __utils__['zfs.parse_command_result'](res, 'replaced')\n    if ret['replaced']:\n        ret['vdevs'] = _clean_vdev_config(\n            __salt__['zpool.status'](zpool=zpool)[zpool]['config'][zpool],\n        )\n    return ret",
    "docstring": "Replaces ``old_device`` with ``new_device``\n\n    .. note::\n\n        This is equivalent to attaching ``new_device``,\n        waiting for it to resilver, and then detaching ``old_device``.\n\n        The size of ``new_device`` must be greater than or equal to the minimum\n        size of all the devices in a mirror or raidz configuration.\n\n    zpool : string\n        Name of storage pool\n\n    old_device : string\n        Old device to replace\n\n    new_device : string\n        Optional new device\n\n    force : boolean\n        Forces use of new_device, even if its appears to be in use.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' zpool.replace myzpool /path/to/vdev1 /path/to/vdev2"
  },
  {
    "code": "def is_ancestor_of_book(self, id_, book_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.is_ancestor_of_catalog(id_=id_, catalog_id=book_id)\n        return self._hierarchy_session.is_ancestor(id_=id_, ancestor_id=book_id)",
    "docstring": "Tests if an ``Id`` is an ancestor of a book.\n\n        arg:    id (osid.id.Id): an ``Id``\n        arg:    book_id (osid.id.Id): the ``Id`` of a book\n        return: (boolean) - ``tru`` e if this ``id`` is an ancestor of\n                ``book_id,``  ``false`` otherwise\n        raise:  NotFound - ``book_id`` is not found\n        raise:  NullArgument - ``id`` or ``book_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*\n        *implementation notes*: If ``id`` not found return ``false``."
  },
  {
    "code": "def train(self, *args, **kwargs):\n        objs = self._do_transform(*args, **kwargs)\n        obj_list = [objs, ] if not isinstance(objs, Iterable) else objs\n        for obj in obj_list:\n            if not isinstance(obj, ODPSModelExpr):\n                continue\n            for meta in ['predictor', 'recommender']:\n                if meta not in self._metas:\n                    continue\n                mod = __import__(self.__class__.__module__.__name__, fromlist=[''])\\\n                    if not hasattr(self, '_env') else self._env\n                action_cls_name = underline_to_capitalized(self._metas[meta])\n                if not hasattr(mod, action_cls_name):\n                    action_cls_name = '_' + action_cls_name\n                setattr(obj, '_' + meta, mod + '.' + action_cls_name)\n        return objs",
    "docstring": "Perform training on a DataFrame.\n        The label field is specified by the ``label_field`` method.\n\n        :param train_data: DataFrame to be trained. Label field must be specified.\n        :type train_data: DataFrame\n\n        :return: Trained model\n        :rtype: MLModel"
  },
  {
    "code": "def _generate_to_tempfile(self, generator):\n    with temporary_file(cleanup=False, binary_mode=False) as output:\n      generator.write(output)\n      return output.name",
    "docstring": "Applies the specified generator to a temp file and returns the path to that file.\n    We generate into a temp file so that we don't lose any manual customizations on error."
  },
  {
    "code": "def _dat_read_params(fmt, sig_len, byte_offset, skew, tsamps_per_frame,\n                     sampfrom, sampto):\n    start_flat_sample = sampfrom * tsamps_per_frame\n    if (sampto + max(skew)) > sig_len:\n        end_flat_sample = sig_len * tsamps_per_frame\n        extra_flat_samples = (sampto + max(skew) - sig_len) * tsamps_per_frame\n    else:\n        end_flat_sample = (sampto + max(skew)) * tsamps_per_frame\n        extra_flat_samples = 0\n    if fmt == '212':\n        block_floor_samples = start_flat_sample % 2\n        start_flat_sample = start_flat_sample - block_floor_samples\n    elif fmt in ['310', '311']:\n        block_floor_samples = start_flat_sample % 3\n        start_flat_sample = start_flat_sample - block_floor_samples\n    else:\n        block_floor_samples = 0\n    start_byte = byte_offset + int(start_flat_sample * BYTES_PER_SAMPLE[fmt])\n    n_read_samples = end_flat_sample - start_flat_sample\n    nan_replace = [max(0, sampto + s - sig_len) for s in skew]\n    return (start_byte, n_read_samples, block_floor_samples,\n            extra_flat_samples, nan_replace)",
    "docstring": "Calculate the parameters used to read and process a dat file, given\n    its layout, and the desired sample range.\n\n    Parameters\n    ----------\n    fmt : str\n        The format of the dat file\n    sig_len : int\n        The signal length (per channel) of the dat file\n    byte_offset : int\n        The byte offset of the dat file\n    skew : list\n        The skew for the signals of the dat file\n    tsamps_per_frame : int\n        The total samples/frame for all channels of the dat file\n    sampfrom : int\n        The starting sample number to be read from the signals\n    sampto : int\n        The final sample number to be read from the signals\n\n    Returns\n    -------\n    start_byte : int\n        The starting byte to read the dat file from. Always points to\n        the start of a byte block for special formats.\n    n_read_samples : int\n        The number of flat samples to read from the dat file.\n    block_floor_samples : int\n        The extra samples read prior to the first desired sample, for\n        special formats, in order to ensure entire byte blocks are read.\n    extra_flat_samples : int\n        The extra samples desired beyond what is contained in the file.\n    nan_replace : list\n        The number of samples to replace with nan at the end of each\n        signal, due to skew wanting samples beyond the file.\n\n    Examples\n    --------\n    sig_len=100, t = 4 (total samples/frame), skew = [0, 2, 4, 5]\n    sampfrom=0, sampto=100 --> read_len = 100, n_sampread = 100*t, extralen = 5, nan_replace = [0, 2, 4, 5]\n    sampfrom=50, sampto=100 --> read_len = 50, n_sampread = 50*t, extralen = 5, nan_replace = [0, 2, 4, 5]\n    sampfrom=0, sampto=50 --> read_len = 50, n_sampread = 55*t, extralen = 0, nan_replace = [0, 0, 0, 0]\n    sampfrom=95, sampto=99 --> read_len = 4, n_sampread = 5*t, extralen = 4, nan_replace = [0, 1, 3, 4]"
  },
  {
    "code": "def unwrap_raw(content):\n    starting_symbol = get_start_symbol(content)\n    ending_symbol = ']' if starting_symbol == '[' else '}'\n    start = content.find(starting_symbol, 0)\n    end = content.rfind(ending_symbol)\n    return content[start:end+1]",
    "docstring": "unwraps the callback and returns the raw content"
  },
  {
    "code": "def is_bootstrapped(metadata):\n    fields = UNIHAN_FIELDS + DEFAULT_COLUMNS\n    if TABLE_NAME in metadata.tables.keys():\n        table = metadata.tables[TABLE_NAME]\n        if set(fields) == set(c.name for c in table.columns):\n            return True\n        else:\n            return False\n    else:\n        return False",
    "docstring": "Return True if cihai is correctly bootstrapped."
  },
  {
    "code": "def add_signature(name=None, inputs=None, outputs=None):\n  if not name:\n    name = \"default\"\n  if inputs is None:\n    inputs = {}\n  if outputs is None:\n    outputs = {}\n  if not isinstance(inputs, dict):\n    inputs = {\"default\": inputs}\n  if not isinstance(outputs, dict):\n    outputs = {\"default\": outputs}\n  message = find_signature_inputs_from_multivalued_ops(inputs)\n  if message: logging.error(message)\n  message = find_signature_input_colocation_error(name, inputs)\n  if message: raise ValueError(message)\n  saved_model_lib.add_signature(name, inputs, outputs)",
    "docstring": "Adds a signature to the module definition.\n\n  NOTE: This must be called within a `module_fn` that is defining a Module.\n\n  Args:\n    name: Signature name as a string. If omitted, it is interpreted as 'default'\n      and is the signature used when `Module.__call__` `signature` is not\n      specified.\n    inputs: A dict from input name to Tensor or SparseTensor to feed when\n      applying the signature. If a single tensor is passed, it is interpreted\n      as a dict with a single 'default' entry.\n    outputs: A dict from output name to Tensor or SparseTensor to return from\n      applying the signature. If a single tensor is passed, it is interpreted\n      as a dict with a single 'default' entry.\n\n  Raises:\n    ValueError: if the arguments are invalid."
  },
  {
    "code": "def find_occurrences(self, resource=None, pymodule=None):\n        tools = _OccurrenceToolsCreator(self.project, resource=resource,\n                                        pymodule=pymodule, docs=self.docs)\n        for offset in self._textual_finder.find_offsets(tools.source_code):\n            occurrence = Occurrence(tools, offset)\n            for filter in self.filters:\n                result = filter(occurrence)\n                if result is None:\n                    continue\n                if result:\n                    yield occurrence\n                break",
    "docstring": "Generate `Occurrence` instances"
  },
  {
    "code": "def printer(self):\n        if not self._has_loaded:\n            self.load()\n        if not self._printer_name:\n            raise exceptions.ConfigSectionMissingError('printer')\n        if not self._printer:\n            self._printer = getattr(printer, self._printer_name)(**self._printer_config)\n        return self._printer",
    "docstring": "Returns a printer that was defined in the config, or throws an\n        exception.\n\n        This method loads the default config if one hasn't beeen already loaded."
  },
  {
    "code": "def update_model(self, words):\n        extended_words = DefaultCompleter._DefaultCompleter__tokens[self.__language][:]\n        extended_words.extend((word for word in set(words)\n                               if word not in DefaultCompleter._DefaultCompleter__tokens[self.__language]))\n        self.setModel(QStringListModel(extended_words))\n        return True",
    "docstring": "Updates the completer model.\n\n        :param words: Words to update the completer with.\n        :type words: tuple or list\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def load(self, specfiles=None):\n        if specfiles is None:\n            specfiles = [_ for _ in viewkeys(self.info)]\n        else:\n            specfiles = aux.toList(specfiles)\n        for specfile in specfiles:\n            if specfile not in self.info:\n                warntext = 'Error while calling \"FiContainer.load()\": \"%s\" is'\\\n                           ' not present in \"FiContainer.info\"!'\\\n                            % (specfile, )\n                warnings.warn(warntext)\n                continue\n            else:\n                fiPath = aux.joinpath(self.info[specfile]['path'],\n                                      specfile+'.fic'\n                                      )\n                with zipfile.ZipFile(fiPath, 'r') as containerZip:\n                    jsonString = io.TextIOWrapper(containerZip.open('data'),\n                                                  encoding='utf-8'\n                                                  ).read()\n                self.container[specfile] = json.loads(jsonString,\n                                                      object_hook=Fi.jsonHook\n                                                      )",
    "docstring": "Imports the specified ``fic`` files from the hard disk.\n\n        :param specfiles: the name of an ms-run file or a list of names. If None\n            all specfiles are selected.\n        :type specfiles: None, str, [str, str]"
  },
  {
    "code": "def magic_session(db_session=None, url=None):\n    if db_session is not None:\n        yield db_session\n    else:\n        session = get_session(url, expire_on_commit=False)\n        try:\n            try:\n                yield session\n            finally:\n                session.commit()\n        finally:\n            session.close()",
    "docstring": "Either does nothing with the session you already have or\n    makes one that commits and closes no matter what happens"
  },
  {
    "code": "def setup_list_pars(self):\n        tdf = self.setup_temporal_list_pars()\n        sdf = self.setup_spatial_list_pars()\n        if tdf is None and sdf is None:\n            return\n        os.chdir(self.m.model_ws)\n        try:\n            apply_list_pars()\n        except Exception as e:\n            os.chdir(\"..\")\n            self.logger.lraise(\"error test running apply_list_pars():{0}\".format(str(e)))\n        os.chdir('..')\n        line = \"pyemu.helpers.apply_list_pars()\\n\"\n        self.logger.statement(\"forward_run line:{0}\".format(line))\n        self.frun_pre_lines.append(line)",
    "docstring": "main entry point for setting up list multiplier\n                parameters"
  },
  {
    "code": "def additional_assets(context: Context):\n    rsync_flags = '-avz' if context.verbosity == 2 else '-az'\n    for path in context.app.additional_asset_paths:\n        context.shell('rsync %s %s %s/' % (rsync_flags, path, context.app.asset_build_path))",
    "docstring": "Collects assets from GOV.UK frontend toolkit"
  },
  {
    "code": "def remove_root_book(self, book_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.remove_root_catalog(catalog_id=book_id)\n        return self._hierarchy_session.remove_root(id_=book_id)",
    "docstring": "Removes a root book.\n\n        arg:    book_id (osid.id.Id): the ``Id`` of a book\n        raise:  NotFound - ``book_id`` is not a root\n        raise:  NullArgument - ``book_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def populate(self, blueprint, documents):\n        documents = self.finish(blueprint, documents)\n        frames = []\n        for document in documents:\n            meta_document = {}\n            for field_name in blueprint._meta_fields:\n                meta_document[field_name] = document[field_name]\n                document.pop(field_name)\n            frame = blueprint.get_frame_cls()(document)\n            for key, value in meta_document.items():\n                setattr(frame, key, value)\n            frames.append(frame)\n        blueprint.on_fake(frames)\n        frames = blueprint.get_frame_cls().insert_many(frames)\n        blueprint.on_faked(frames)\n        return frames",
    "docstring": "Populate the database with documents"
  },
  {
    "code": "def _polygon_from_coords(coords, fix_geom=False, swap=True, dims=2):\n    assert len(coords) % dims == 0\n    number_of_points = len(coords)/dims\n    coords_as_array = np.array(coords)\n    reshaped = coords_as_array.reshape(number_of_points, dims)\n    points = [\n        (float(i[1]), float(i[0])) if swap else ((float(i[0]), float(i[1])))\n        for i in reshaped.tolist()\n        ]\n    polygon = Polygon(points).buffer(0)\n    try:\n        assert polygon.is_valid\n        return polygon\n    except AssertionError:\n        if fix_geom:\n            return polygon.buffer(0)\n        else:\n            raise RuntimeError(\"Geometry is not valid.\")",
    "docstring": "Return Shapely Polygon from coordinates.\n\n    - coords: list of alterating latitude / longitude coordinates\n    - fix_geom: automatically fix geometry"
  },
  {
    "code": "def _check_euk_contamination(self, hmm_hit_tables):\n        euk_hit_table = HMMreader(hmm_hit_tables.pop(-1))\n        other_hit_tables = [HMMreader(x) for x in hmm_hit_tables]\n        reads_unique_to_eukaryotes = []\n        reads_with_better_euk_hit = []\n        for hit in euk_hit_table.names():\n            bits = []\n            for hit_table in other_hit_tables:\n                if hit in hit_table.names():\n                    bits.append(hit_table.bit(hit))\n                else:\n                    reads_unique_to_eukaryotes.append(hit)\n            if bits:\n                if any([x for x in bits if x > euk_hit_table.bit(hit)]):\n                    continue\n                else:\n                    reads_with_better_euk_hit.append(hit)\n            else:\n                continue\n        if len(reads_with_better_euk_hit) == 0:\n            logging.info(\"No contaminating eukaryotic reads detected\")\n        else:\n            logging.info(\"Found %s read(s) that may be eukaryotic\" % len(reads_with_better_euk_hit + reads_unique_to_eukaryotes))\n        euk_reads = set(reads_with_better_euk_hit + reads_unique_to_eukaryotes)\n        return euk_reads",
    "docstring": "check_euk_contamination - Check output HMM tables hits reads that hit\n                                  the 18S HMM with a higher bit score.\n\n        Parameters\n        ----------\n        hmm_hit_tables : array\n            Array of paths to the output files produced by hmmsearch or\n            nhmmer.\n        run_stats : dict\n            A dictionary to updatewith the number of unique 18S reads and reads\n            detected by both 18S and non-18S HMMs\n\n        Returns\n        -------\n        euk_reads : set\n            Non-redundant set of all read names deemed to be eukaryotic"
  },
  {
    "code": "def get_querystring(uri):\n    parts = urlparse.urlsplit(uri)\n    return urlparse.parse_qs(parts.query)",
    "docstring": "Get Querystring information from uri.\n\n    :param uri: uri\n    :return: querystring info or {}"
  },
  {
    "code": "def end_time(self):\n        try:\n            return self.start_time + SCAN_DURATION[self.sector]\n        except KeyError:\n            return self.start_time",
    "docstring": "End timestamp of the dataset"
  },
  {
    "code": "def open_as_pillow(filename):\n    with __sys_open(filename, 'rb') as f:\n        data = BytesIO(f.read())\n        return Image.open(data)",
    "docstring": "This way can delete file immediately"
  },
  {
    "code": "def on_finish(self):\n        r = self.response\n        r.request_time = time.time() - self.start_time\n        if self.callback:\n            self.callback(r)",
    "docstring": "Called regardless of success or failure"
  },
  {
    "code": "def valid_ovsdb_addr(addr):\n    m = re.match(r'unix:(\\S+)', addr)\n    if m:\n        file = m.group(1)\n        return os.path.isfile(file)\n    m = re.match(r'(tcp|ssl):(\\S+):(\\d+)', addr)\n    if m:\n        address = m.group(2)\n        port = m.group(3)\n        if '[' in address:\n            address = address.strip('[').strip(']')\n            return ip.valid_ipv6(address) and port.isdigit()\n        else:\n            return ip.valid_ipv4(address) and port.isdigit()\n    return False",
    "docstring": "Returns True if the given addr is valid OVSDB server address, otherwise\n    False.\n\n    The valid formats are:\n\n    - ``unix:file``\n    - ``tcp:ip:port``\n    - ``ssl:ip:port``\n\n    If ip is IPv6 address, wrap ip with brackets (e.g., ssl:[::1]:6640).\n\n    :param addr: str value of OVSDB server address.\n    :return: True if valid, otherwise False."
  },
  {
    "code": "def _api_call(function):\n    @wraps(function)\n    def wrapper(*args, **kwargs):\n        try:\n            if not _webview_ready.wait(15):\n                raise Exception('Main window failed to start')\n            return function(*args, **kwargs)\n        except NameError:\n            raise Exception('Create a web view window first, before invoking this function')\n        except KeyError as e:\n            try:\n                uid = kwargs['uid']\n            except KeyError:\n                uid = args[-1]\n            raise Exception('Cannot call function: No webview exists with uid: {}'.format(uid))\n    return wrapper",
    "docstring": "Decorator to call a pywebview API, checking for _webview_ready and raisings\n    appropriate Exceptions on failure."
  },
  {
    "code": "def write_record(self, event_str):\n        header = struct.pack('Q', len(event_str))\n        header += struct.pack('I', masked_crc32c(header))\n        footer = struct.pack('I', masked_crc32c(event_str))\n        self._writer.write(header + event_str + footer)",
    "docstring": "Writes a serialized event to file."
  },
  {
    "code": "def delete(self):\n        logger.debug('Deleting Dagobah instance with ID {0}'.format(self.dagobah_id))\n        self.jobs = []\n        self.created_jobs = 0\n        self.backend.delete_dagobah(self.dagobah_id)",
    "docstring": "Delete this Dagobah instance from the Backend."
  },
  {
    "code": "def popitem(self):\n        heap = self._heap\n        position = self._position\n        try:\n            end = heap.pop(-1)\n        except IndexError:\n            raise KeyError('pqdict is empty')\n        if heap:\n            node = heap[0]\n            heap[0] = end\n            position[end.key] = 0\n            self._sink(0)\n        else:\n            node = end\n        del position[node.key]\n        return node.key, node.value",
    "docstring": "Remove and return the item with highest priority. Raises ``KeyError``\n        if pqdict is empty."
  },
  {
    "code": "def getAccountNames(store, protocol=None):\n    return ((meth.localpart, meth.domain) for meth\n                in getLoginMethods(store, protocol))",
    "docstring": "Retrieve account name information about the given database.\n\n    @param store: An Axiom Store representing a user account.  It must\n    have been opened through the store which contains its account\n    information.\n\n    @return: A generator of two-tuples of (username, domain) which\n    refer to the given store."
  },
  {
    "code": "def read_input(self, input_cls, filename, **kwargs):\n        input_inst = input_cls()\n        input_inst.read_input(filename)\n        return input_inst.get_data()",
    "docstring": "Read in input and do some minimal preformatting\n        input_cls - the class to use to read the input\n        filename - input filename"
  },
  {
    "code": "def uuidify(val):\n    if uuidutils.is_uuid_like(val):\n        return val\n    else:\n        try:\n            int_val = int(val, 16)\n        except ValueError:\n            with excutils.save_and_reraise_exception():\n                LOG.error(\"Invalid UUID format %s. Please provide an \"\n                          \"integer in decimal (0-9) or hex (0-9a-e) \"\n                          \"format\", val)\n        res = str(int_val)\n        num = 12 - len(res)\n        return \"00000000-0000-0000-0000-\" + \"0\" * num + res",
    "docstring": "Takes an integer and transforms it to a UUID format.\n\n    returns: UUID formatted version of input."
  },
  {
    "code": "def update_assessment_offered(self, assessment_offered_form):\n        collection = JSONClientValidated('assessment',\n                                         collection='AssessmentOffered',\n                                         runtime=self._runtime)\n        if not isinstance(assessment_offered_form, ABCAssessmentOfferedForm):\n            raise errors.InvalidArgument('argument type is not an AssessmentOfferedForm')\n        if not assessment_offered_form.is_for_update():\n            raise errors.InvalidArgument('the AssessmentOfferedForm is for update only, not create')\n        try:\n            if self._forms[assessment_offered_form.get_id().get_identifier()] == UPDATED:\n                raise errors.IllegalState('assessment_offered_form already used in an update transaction')\n        except KeyError:\n            raise errors.Unsupported('assessment_offered_form did not originate from this session')\n        if not assessment_offered_form.is_valid():\n            raise errors.InvalidArgument('one or more of the form elements is invalid')\n        collection.save(assessment_offered_form._my_map)\n        self._forms[assessment_offered_form.get_id().get_identifier()] = UPDATED\n        return objects.AssessmentOffered(\n            osid_object_map=assessment_offered_form._my_map,\n            runtime=self._runtime,\n            proxy=self._proxy)",
    "docstring": "Updates an existing assessment offered.\n\n        arg:    assessment_offered_form\n                (osid.assessment.AssessmentOfferedForm): the form\n                containing the elements to be updated\n        raise:  IllegalState - ``assessment_offrered_form`` already used\n                in an update transaction\n        raise:  InvalidArgument - the form contains an invalid value\n        raise:  NullArgument - ``assessment_offered_form`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        raise:  Unsupported - ``assessment_form`` did not originate from\n                ``get_assessment_form_for_update()``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "async def seek(self, pos, whence=sync_io.SEEK_SET):\n        return self._stream.seek(pos, whence)",
    "docstring": "Move to new file position.\n\n        Argument offset is a byte count.  Optional argument whence defaults to\n        SEEK_SET or 0 (offset from start of file, offset should be >= 0); other\n        values are SEEK_CUR or 1 (move relative to current position, positive\n        or negative), and SEEK_END or 2 (move relative to end of file, usually\n        negative, although many platforms allow seeking beyond the end of a\n        file).\n\n        Note that not all file objects are seekable."
  },
  {
    "code": "def update_rotation(self, dt, buttons):\n        assert isinstance(buttons, dict)\n        ma = buttons['right'] - buttons['left']\n        if ma != 0:\n            self.stats['battery'] -= self.battery_use['angular']\n            self.rotation += ma * dt * self.angular_velocity\n        a = math.radians(self.rotation)\n        self.impulse_dir = eu.Vector2(math.sin(a), math.cos(a))",
    "docstring": "Updates rotation and impulse direction"
  },
  {
    "code": "def add_api_key(key, value):\n    if key is None or key == \"\":\n        logger.error(\"Key cannot be empty\")\n    if value is None or value == \"\":\n        logger.error(\"Value cannot be empty\")\n    from .. import datatools\n    data = datatools.get_data()\n    if \"keys\" not in data[\"discord\"]:\n        data[\"discord\"][\"keys\"] = {}\n    is_key_new = False\n    if key not in data[\"discord\"][\"keys\"]:\n        is_key_new = True\n    elif data[\"discord\"][\"keys\"][key] == value:\n        logger.info(\"API key '{}' already has value '{}'\".format(key, value))\n        return\n    data[\"discord\"][\"keys\"][key] = value\n    datatools.write_data(data)\n    key_text = \"added\" if is_key_new else \"updated\"\n    logger.info(\"API key '{}' {} with value '{}'\".format(key, key_text, value))",
    "docstring": "Adds a key to the bot's data\n\n    Args:\n        key: The name of the key to add\n        value: The value for the key"
  },
  {
    "code": "def tmpconfig(request):\n    SUBFOLDER = tempfile.mkdtemp()\n    CONF = UserConfig('spyder-test',\n                      defaults=DEFAULTS,\n                      version=CONF_VERSION,\n                      subfolder=SUBFOLDER,\n                      raw_mode=True,\n                      )\n    def fin():\n        shutil.rmtree(SUBFOLDER)\n    request.addfinalizer(fin)\n    return CONF",
    "docstring": "Fixtures that returns a temporary CONF element."
  },
  {
    "code": "def cause_repertoire(self, mechanism, purview):\n        if not purview:\n            return np.array([1.0])\n        if not mechanism:\n            return max_entropy_distribution(purview, self.tpm_size)\n        purview = frozenset(purview)\n        joint = np.ones(repertoire_shape(purview, self.tpm_size))\n        joint *= functools.reduce(\n            np.multiply, [self._single_node_cause_repertoire(m, purview)\n                          for m in mechanism]\n        )\n        return distribution.normalize(joint)",
    "docstring": "Return the cause repertoire of a mechanism over a purview.\n\n        Args:\n            mechanism (tuple[int]): The mechanism for which to calculate the\n                cause repertoire.\n            purview (tuple[int]): The purview over which to calculate the\n                cause repertoire.\n\n        Returns:\n            np.ndarray: The cause repertoire of the mechanism over the purview.\n\n        .. note::\n            The returned repertoire is a distribution over purview node states,\n            not the states of the whole network."
  },
  {
    "code": "def parse_tenant_config_path(config_path):\n    try:\n        return config_path % connection.schema_name\n    except (TypeError, ValueError):\n        return os.path.join(config_path, connection.schema_name)",
    "docstring": "Convenience function for parsing django-tenants' path configuration strings.\n\n    If the string contains '%s', then the current tenant's schema name will be inserted at that location. Otherwise\n    the schema name will be appended to the end of the string.\n\n    :param config_path: A configuration path string that optionally contains '%s' to indicate where the tenant\n    schema name should be inserted.\n\n    :return: The formatted string containing the schema name"
  },
  {
    "code": "def is_alive(self, container: Container) -> bool:\n        uid = container.uid\n        return uid in self.__dockerc and \\\n               self.__dockerc[uid].status == 'running'",
    "docstring": "Determines whether a given container is still alive.\n\n        Returns:\n            `True` if the underlying Docker container for the given BugZoo\n            container is still alive, otherwise `False`."
  },
  {
    "code": "def kron(a, b):\n    if hasattr(a, '__kron__'):\n        return a.__kron__(b)\n    if a is None:\n        return b\n    else:\n        raise ValueError(\n            'Kron is waiting for two TT-vectors or two TT-matrices')",
    "docstring": "Kronecker product of two TT-matrices or two TT-vectors"
  },
  {
    "code": "def send_rpc_response(self, rpc_tag, result, response):\n        if rpc_tag not in self.in_flight_rpcs:\n            raise ArgumentError(\"In flight RPC could not be found, it may have timed out\", rpc_tag=rpc_tag)\n        del self.in_flight_rpcs[rpc_tag]\n        response_message = {\n            'response': response,\n            'result': result\n        }\n        try:\n            self.rpc_results.set(rpc_tag, response_message)\n        except KeyError:\n            self._logger.warning(\"RPC response came but no one was waiting: response=%s\", response)",
    "docstring": "Send a response to an RPC.\n\n        Args:\n            rpc_tag (str): The exact string given in a previous call to send_rpc_command\n            result (str): The result of the operation.  The possible values of response are:\n                service_not_found, rpc_not_found, timeout, success, invalid_response,\n                invalid_arguments, execution_exception\n            response (bytes): The raw bytes that we should send back as a response."
  },
  {
    "code": "def translocation(from_loc, to_loc):\n    rv = _activity_helper(TRANSLOCATION)\n    rv[EFFECT] = {\n        FROM_LOC: Entity(namespace=BEL_DEFAULT_NAMESPACE, name=from_loc) if isinstance(from_loc, str) else from_loc,\n        TO_LOC: Entity(namespace=BEL_DEFAULT_NAMESPACE, name=to_loc) if isinstance(to_loc, str) else to_loc,\n    }\n    return rv",
    "docstring": "Make a translocation dictionary.\n\n    :param dict from_loc: An entity dictionary from :func:`pybel.dsl.entity`\n    :param dict to_loc: An entity dictionary from :func:`pybel.dsl.entity`\n    :rtype: dict"
  },
  {
    "code": "def generate_hash(self, length=30):\n        import random, string\n        chars = string.ascii_letters + string.digits\n        ran = random.SystemRandom().choice\n        hash = ''.join(ran(chars) for i in range(length))\n        return hash",
    "docstring": "Generate random string of given length"
  },
  {
    "code": "def parse(*models, **kwargs):\n    if isinstance(models, tuple) and isinstance(models[0], list):\n        models = models[0]\n    config = kwargs.pop('config', False)\n    state = kwargs.pop('state', False)\n    profiles = kwargs.pop('profiles', [])\n    if not profiles and hasattr(napalm_device, 'profile'):\n        profiles = napalm_device.profile\n    if not profiles:\n        profiles = [__grains__.get('os')]\n    root = _get_root_object(models)\n    parser_kwargs = {\n        'device': napalm_device.get('DRIVER'),\n        'profile': profiles\n    }\n    if config:\n        root.parse_config(**parser_kwargs)\n    if state:\n        root.parse_state(**parser_kwargs)\n    return root.to_dict(filter=True)",
    "docstring": "Parse configuration from the device.\n\n    models\n        A list of models to be used when parsing.\n\n    config: ``False``\n        Parse config.\n\n    state: ``False``\n        Parse state.\n\n    profiles: ``None``\n        Use certain profiles to parse. If not specified, will use the device\n        default profile(s).\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' napalm_yang.parse models.openconfig_interfaces\n\n    Output Example:\n\n    .. code-block:: python\n\n        {\n            \"interfaces\": {\n                \"interface\": {\n                    \".local.\": {\n                        \"name\": \".local.\",\n                        \"state\": {\n                            \"admin-status\": \"UP\",\n                            \"counters\": {\n                                \"in-discards\": 0,\n                                \"in-errors\": 0,\n                                \"out-errors\": 0\n                            },\n                            \"enabled\": True,\n                            \"ifindex\": 0,\n                            \"last-change\": 0,\n                            \"oper-status\": \"UP\",\n                            \"type\": \"softwareLoopback\"\n                        },\n                        \"subinterfaces\": {\n                            \"subinterface\": {\n                                \".local..0\": {\n                                    \"index\": \".local..0\",\n                                    \"state\": {\n                                        \"ifindex\": 0,\n                                        \"name\": \".local..0\"\n                                    }\n                                }\n                            }\n                        }\n                    },\n                    \"ae0\": {\n                        \"name\": \"ae0\",\n                        \"state\": {\n                            \"admin-status\": \"UP\",\n                            \"counters\": {\n                                \"in-discards\": 0,\n                                \"in-errors\": 0,\n                                \"out-errors\": 0\n                            },\n                            \"enabled\": True,\n                            \"ifindex\": 531,\n                            \"last-change\": 255203,\n                            \"mtu\": 1518,\n                            \"oper-status\": \"DOWN\"\n                        },\n                        \"subinterfaces\": {\n                            \"subinterface\": {\n                                \"ae0.0\": {\n                                    \"index\": \"ae0.0\",\n                                    \"state\": {\n                                        \"description\": \"ASDASDASD\",\n                                        \"ifindex\": 532,\n                                        \"name\": \"ae0.0\"\n                                    }\n                                }\n                                \"ae0.32767\": {\n                                    \"index\": \"ae0.32767\",\n                                    \"state\": {\n                                        \"ifindex\": 535,\n                                        \"name\": \"ae0.32767\"\n                                    }\n                                }\n                            }\n                        }\n                    },\n                    \"dsc\": {\n                        \"name\": \"dsc\",\n                        \"state\": {\n                            \"admin-status\": \"UP\",\n                            \"counters\": {\n                                \"in-discards\": 0,\n                                \"in-errors\": 0,\n                                \"out-errors\": 0\n                            },\n                            \"enabled\": True,\n                            \"ifindex\": 5,\n                            \"last-change\": 0,\n                            \"oper-status\": \"UP\"\n                        }\n                    },\n                    \"ge-0/0/0\": {\n                        \"name\": \"ge-0/0/0\",\n                        \"state\": {\n                            \"admin-status\": \"UP\",\n                            \"counters\": {\n                                \"in-broadcast-pkts\": 0,\n                                \"in-discards\": 0,\n                                \"in-errors\": 0,\n                                \"in-multicast-pkts\": 0,\n                                \"in-unicast-pkts\": 16877,\n                                \"out-broadcast-pkts\": 0,\n                                \"out-errors\": 0,\n                                \"out-multicast-pkts\": 0,\n                                \"out-unicast-pkts\": 15742\n                            },\n                            \"description\": \"management interface\",\n                            \"enabled\": True,\n                            \"ifindex\": 507,\n                            \"last-change\": 258467,\n                            \"mtu\": 1400,\n                            \"oper-status\": \"UP\"\n                        },\n                        \"subinterfaces\": {\n                            \"subinterface\": {\n                                \"ge-0/0/0.0\": {\n                                    \"index\": \"ge-0/0/0.0\",\n                                    \"state\": {\n                                        \"description\": \"ge-0/0/0.0\",\n                                        \"ifindex\": 521,\n                                        \"name\": \"ge-0/0/0.0\"\n                                    }\n                                }\n                            }\n                        }\n                    }\n                    \"irb\": {\n                        \"name\": \"irb\",\n                        \"state\": {\n                            \"admin-status\": \"UP\",\n                            \"counters\": {\n                                \"in-discards\": 0,\n                                \"in-errors\": 0,\n                                \"out-errors\": 0\n                            },\n                            \"enabled\": True,\n                            \"ifindex\": 502,\n                            \"last-change\": 0,\n                            \"mtu\": 1514,\n                            \"oper-status\": \"UP\",\n                            \"type\": \"ethernetCsmacd\"\n                        }\n                    },\n                    \"lo0\": {\n                        \"name\": \"lo0\",\n                        \"state\": {\n                            \"admin-status\": \"UP\",\n                            \"counters\": {\n                                \"in-discards\": 0,\n                                \"in-errors\": 0,\n                                \"out-errors\": 0\n                            },\n                            \"description\": \"lo0\",\n                            \"enabled\": True,\n                            \"ifindex\": 6,\n                            \"last-change\": 0,\n                            \"oper-status\": \"UP\",\n                            \"type\": \"softwareLoopback\"\n                        },\n                        \"subinterfaces\": {\n                            \"subinterface\": {\n                                \"lo0.0\": {\n                                    \"index\": \"lo0.0\",\n                                    \"state\": {\n                                        \"description\": \"lo0.0\",\n                                        \"ifindex\": 16,\n                                        \"name\": \"lo0.0\"\n                                    }\n                                },\n                                \"lo0.16384\": {\n                                    \"index\": \"lo0.16384\",\n                                    \"state\": {\n                                        \"ifindex\": 21,\n                                        \"name\": \"lo0.16384\"\n                                    }\n                                },\n                                \"lo0.16385\": {\n                                    \"index\": \"lo0.16385\",\n                                    \"state\": {\n                                        \"ifindex\": 22,\n                                        \"name\": \"lo0.16385\"\n                                    }\n                                },\n                                \"lo0.32768\": {\n                                    \"index\": \"lo0.32768\",\n                                    \"state\": {\n                                        \"ifindex\": 248,\n                                        \"name\": \"lo0.32768\"\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }"
  },
  {
    "code": "def __get_node(self, word):\n\t\tnode = self.root\n\t\tfor c in word:\n\t\t\ttry:\n\t\t\t\tnode = node.children[c]\n\t\t\texcept KeyError:\n\t\t\t\treturn None\n\t\treturn node",
    "docstring": "Private function retrieving a final node of trie\n\t\tfor given word\n\n\t\tReturns node or None, if the trie doesn't contain the word."
  },
  {
    "code": "def data_to_string(self, data_element):\n        stream = NativeIO()\n        self.data_to_stream(data_element, stream)\n        return stream.getvalue()",
    "docstring": "Converts the given data element into a string representation.\n\n        :param data_element: object implementing\n            :class:`everest.representers.interfaces.IExplicitDataElement`\n        :returns: string representation (using the MIME content type\n            configured for this representer)"
  },
  {
    "code": "def get_es_ids(self):\n        search = self.search.source(['uri']).sort(['uri'])\n        es_ids = [item.meta.id for item in search.scan()]\n        return es_ids",
    "docstring": "reads all the elasticssearch ids for an index"
  },
  {
    "code": "def add_to_capabilities(self, capabilities):\n        proxy_caps = {}\n        proxy_caps['proxyType'] = self.proxyType['string']\n        if self.autodetect:\n            proxy_caps['autodetect'] = self.autodetect\n        if self.ftpProxy:\n            proxy_caps['ftpProxy'] = self.ftpProxy\n        if self.httpProxy:\n            proxy_caps['httpProxy'] = self.httpProxy\n        if self.proxyAutoconfigUrl:\n            proxy_caps['proxyAutoconfigUrl'] = self.proxyAutoconfigUrl\n        if self.sslProxy:\n            proxy_caps['sslProxy'] = self.sslProxy\n        if self.noProxy:\n            proxy_caps['noProxy'] = self.noProxy\n        if self.socksProxy:\n            proxy_caps['socksProxy'] = self.socksProxy\n        if self.socksUsername:\n            proxy_caps['socksUsername'] = self.socksUsername\n        if self.socksPassword:\n            proxy_caps['socksPassword'] = self.socksPassword\n        capabilities['proxy'] = proxy_caps",
    "docstring": "Adds proxy information as capability in specified capabilities.\n\n        :Args:\n         - capabilities: The capabilities to which proxy will be added."
  },
  {
    "code": "def to_json(self):\n        if self._embedding:\n            warnings.warn('Serialization of attached embedding '\n                          'to json is not supported. '\n                          'You may serialize the embedding to a binary format '\n                          'separately using vocab.embedding.serialize')\n        vocab_dict = {}\n        vocab_dict['idx_to_token'] = self._idx_to_token\n        vocab_dict['token_to_idx'] = dict(self._token_to_idx)\n        vocab_dict['reserved_tokens'] = self._reserved_tokens\n        vocab_dict['unknown_token'] = self._unknown_token\n        vocab_dict['padding_token'] = self._padding_token\n        vocab_dict['bos_token'] = self._bos_token\n        vocab_dict['eos_token'] = self._eos_token\n        return json.dumps(vocab_dict)",
    "docstring": "Serialize Vocab object to json string.\n\n        This method does not serialize the underlying embedding."
  },
  {
    "code": "def set_signal_type(self, sig_type):\n        if isinstance(sig_type, str):\n            sig_type = [sig_type]\n        self.snr_input.signal_type = sig_type\n        return",
    "docstring": "Set the signal type of interest.\n\n        Sets the signal type for which the SNR is calculated.\n        This means inspiral, merger, and/or ringdown.\n\n        Args:\n            sig_type (str or list of str): Signal type desired by user.\n                Choices are `ins`, `mrg`, `rd`, `all` for circular waveforms created with PhenomD.\n                If eccentric waveforms are used, must be `all`."
  },
  {
    "code": "def _parse(self, globals_dict):\n        globals = {}\n        if not isinstance(globals_dict, dict):\n            raise InvalidGlobalsSectionException(self._KEYWORD,\n                                                 \"It must be a non-empty dictionary\".format(self._KEYWORD))\n        for section_name, properties in globals_dict.items():\n            resource_type = self._make_resource_type(section_name)\n            if resource_type not in self.supported_properties:\n                raise InvalidGlobalsSectionException(self._KEYWORD,\n                                                     \"'{section}' is not supported. \"\n                                                     \"Must be one of the following values - {supported}\"\n                                                     .format(section=section_name,\n                                                             supported=self.supported_resource_section_names))\n            if not isinstance(properties, dict):\n                raise InvalidGlobalsSectionException(self._KEYWORD, \"Value of ${section} must be a dictionary\")\n            for key, value in properties.items():\n                supported = self.supported_properties[resource_type]\n                if key not in supported:\n                    raise InvalidGlobalsSectionException(self._KEYWORD,\n                                                         \"'{key}' is not a supported property of '{section}'. \"\n                                                         \"Must be one of the following values - {supported}\"\n                                                         .format(key=key, section=section_name, supported=supported))\n            globals[resource_type] = GlobalProperties(properties)\n        return globals",
    "docstring": "Takes a SAM template as input and parses the Globals section\n\n        :param globals_dict: Dictionary representation of the Globals section\n        :return: Processed globals dictionary which can be used to quickly identify properties to merge\n        :raises: InvalidResourceException if the input contains properties that we don't support"
  },
  {
    "code": "def open_submission(self, url=None):\n        if url is None:\n            data = self.get_selected_item()\n            url = data['permalink']\n            if data.get('url_type') == 'selfpost':\n                self.config.history.add(data['url_full'])\n        self.selected_page = self.open_submission_page(url)",
    "docstring": "Select the current submission to view posts."
  },
  {
    "code": "def del_calculation(job_id, confirmed=False):\n    if logs.dbcmd('get_job', job_id) is None:\n        print('There is no job %d' % job_id)\n        return\n    if confirmed or confirm(\n            'Are you sure you want to (abort and) delete this calculation and '\n            'all associated outputs?\\nThis action cannot be undone. (y/n): '):\n        try:\n            abort(job_id)\n            resp = logs.dbcmd('del_calc', job_id, getpass.getuser())\n        except RuntimeError as err:\n            safeprint(err)\n        else:\n            if 'success' in resp:\n                print('Removed %d' % job_id)\n            else:\n                print(resp['error'])",
    "docstring": "Delete a calculation and all associated outputs."
  },
  {
    "code": "def export_kappa_im(model, fname=None):\n    from .kappa_util import im_json_to_graph\n    kappa = _prepare_kappa(model)\n    imap = kappa.analyses_influence_map()\n    im = im_json_to_graph(imap)\n    for param in model.parameters:\n        try:\n            im.remove_node(param.name)\n        except:\n            pass\n    if fname:\n        agraph = networkx.nx_agraph.to_agraph(im)\n        agraph.draw(fname, prog='dot')\n    return im",
    "docstring": "Return a networkx graph representing the model's Kappa influence map.\n\n    Parameters\n    ----------\n    model : pysb.core.Model\n        A PySB model to be exported into a Kappa IM.\n    fname : Optional[str]\n        A file name, typically with .png or .pdf extension in which\n        the IM is rendered using pygraphviz.\n\n    Returns\n    -------\n    networkx.MultiDiGraph\n        A graph object representing the influence map."
  },
  {
    "code": "def authenticate(self, api_key):\n        self._api_key = api_key\n        self._session.auth = ('', self._api_key)\n        return self._verify_api_key()",
    "docstring": "Logs user into Heroku with given api_key."
  },
  {
    "code": "def _find_devices_mac(self):\n        self.keyboards.append(Keyboard(self))\n        self.mice.append(MightyMouse(self))\n        self.mice.append(Mouse(self))",
    "docstring": "Find devices on Mac."
  },
  {
    "code": "def _next_record(self, next_line):\n        record = self.loader.parse_record_stream(self.reader,\n                                                 next_line,\n                                                 self.known_format,\n                                                 self.no_record_parse,\n                                                 self.ensure_http_headers)\n        self.member_info = None\n        if not self.mixed_arc_warc:\n            self.known_format = record.format\n        return record",
    "docstring": "Use loader to parse the record from the reader stream\n        Supporting warc and arc records"
  },
  {
    "code": "def set_monitor(module):\n    def monitor(name, tensor,\n                track_data=True,\n                track_grad=True):\n        module.monitored_vars[name] = {\n            'tensor':tensor,\n            'track_data':track_data,\n            'track_grad':track_grad,\n        }\n    module.monitor = monitor",
    "docstring": "Defines the monitor method on the module."
  },
  {
    "code": "def formula_sections(self):\n        if self.dtree is not None:\n            return self.dtree.order\n        else:\n            return [s for s in self.manifest.sections() if s != \"config\"]",
    "docstring": "Return all sections related to a formula, re-ordered according to the \"depends\" section."
  },
  {
    "code": "def combine_first(self, other):\n        import pandas.core.computation.expressions as expressions\n        def extract_values(arr):\n            if isinstance(arr, (ABCIndexClass, ABCSeries)):\n                arr = arr._values\n            if needs_i8_conversion(arr):\n                if is_extension_array_dtype(arr.dtype):\n                    arr = arr.asi8\n                else:\n                    arr = arr.view('i8')\n            return arr\n        def combiner(x, y):\n            mask = isna(x)\n            if isinstance(mask, (ABCIndexClass, ABCSeries)):\n                mask = mask._values\n            x_values = extract_values(x)\n            y_values = extract_values(y)\n            if y.name not in self.columns:\n                return y_values\n            return expressions.where(mask, y_values, x_values)\n        return self.combine(other, combiner, overwrite=False)",
    "docstring": "Update null elements with value in the same location in `other`.\n\n        Combine two DataFrame objects by filling null values in one DataFrame\n        with non-null values from other DataFrame. The row and column indexes\n        of the resulting DataFrame will be the union of the two.\n\n        Parameters\n        ----------\n        other : DataFrame\n            Provided DataFrame to use to fill null values.\n\n        Returns\n        -------\n        DataFrame\n\n        See Also\n        --------\n        DataFrame.combine : Perform series-wise operation on two DataFrames\n            using a given function.\n\n        Examples\n        --------\n\n        >>> df1 = pd.DataFrame({'A': [None, 0], 'B': [None, 4]})\n        >>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})\n        >>> df1.combine_first(df2)\n             A    B\n        0  1.0  3.0\n        1  0.0  4.0\n\n        Null values still persist if the location of that null value\n        does not exist in `other`\n\n        >>> df1 = pd.DataFrame({'A': [None, 0], 'B': [4, None]})\n        >>> df2 = pd.DataFrame({'B': [3, 3], 'C': [1, 1]}, index=[1, 2])\n        >>> df1.combine_first(df2)\n             A    B    C\n        0  NaN  4.0  NaN\n        1  0.0  3.0  1.0\n        2  NaN  3.0  1.0"
  },
  {
    "code": "def clear_bucket_props(self, bucket):\n        bucket_type = self._get_bucket_type(bucket.bucket_type)\n        url = self.bucket_properties_path(bucket.name,\n                                          bucket_type=bucket_type)\n        url = self.bucket_properties_path(bucket.name)\n        headers = {'Content-Type': 'application/json'}\n        status, _, _ = self._request('DELETE', url, headers, None)\n        if status == 204:\n            return True\n        elif status == 405:\n            return False\n        else:\n            raise RiakError('Error %s clearing bucket properties.'\n                            % status)",
    "docstring": "reset the properties on the bucket object given"
  },
  {
    "code": "def getDigitalMinimum(self, chn=None):\n        if chn is not None:\n            if 0 <= chn < self.signals_in_file:\n                return self.digital_min(chn)\n            else:\n                return 0\n        else:\n            digMin = np.zeros(self.signals_in_file)\n            for i in np.arange(self.signals_in_file):\n                digMin[i] = self.digital_min(i)\n            return digMin",
    "docstring": "Returns the minimum digital value of signal edfsignal.\n\n        Parameters\n        ----------\n        chn : int\n            channel number\n\n        Examples\n        --------\n        >>> import pyedflib\n        >>> f = pyedflib.data.test_generator()\n        >>> f.getDigitalMinimum(0)\n        -32768\n        >>> f._close()\n        >>> del f"
  },
  {
    "code": "def reduce(self, dimensions=[], function=None, spreadfn=None, **kwargs):\n        kwargs['_method_args'] = (dimensions, function, spreadfn)\n        return self.__call__('reduce', **kwargs)",
    "docstring": "Applies a reduce function to all ViewableElement objects.\n\n        See :py:meth:`Dimensioned.opts` and :py:meth:`Apply.__call__`\n        for more information."
  },
  {
    "code": "def get_tree_depth( self ):\n        if (self.children):\n            depth = 1\n            childDepths = []\n            for child in self.children:\n                childDepths.append( child.get_tree_depth() )\n            return depth + max(childDepths)\n        else:\n            return 0",
    "docstring": "Finds depth of this tree."
  },
  {
    "code": "def _enter_single_subdir(root_dir):\n    current_cwd = os.getcwd()\n    try:\n        dest_dir = root_dir\n        dir_list = os.listdir(root_dir)\n        if len(dir_list) == 1:\n            first = os.path.join(root_dir, dir_list[0])\n            if os.path.isdir(first):\n                dest_dir = first\n        else:\n            dest_dir = root_dir\n        os.chdir(dest_dir)\n        yield dest_dir\n    finally:\n        os.chdir(current_cwd)",
    "docstring": "if the given directory has just a single subdir, enter that"
  },
  {
    "code": "def get_instance(self, payload):\n        return FieldInstance(\n            self._version,\n            payload,\n            assistant_sid=self._solution['assistant_sid'],\n            task_sid=self._solution['task_sid'],\n        )",
    "docstring": "Build an instance of FieldInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.autopilot.v1.assistant.task.field.FieldInstance\n        :rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldInstance"
  },
  {
    "code": "def fetch(self):\n        params = values.of({})\n        payload = self._version.fetch(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return PublishedTrackInstance(\n            self._version,\n            payload,\n            room_sid=self._solution['room_sid'],\n            participant_sid=self._solution['participant_sid'],\n            sid=self._solution['sid'],\n        )",
    "docstring": "Fetch a PublishedTrackInstance\n\n        :returns: Fetched PublishedTrackInstance\n        :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackInstance"
  },
  {
    "code": "def wait_for_vacancy(self, processor_type):\n        with self._condition:\n            self._condition.wait_for(lambda: (\n                self._processor_available(processor_type)\n                or self._cancelled_event.is_set()))\n            if self._cancelled_event.is_set():\n                raise WaitCancelledException()\n            processor = self[processor_type].next_processor()\n            return processor",
    "docstring": "Waits for a particular processor type to have the capacity to\n        handle additional transactions or until is_cancelled is True.\n\n        Args:\n            processor_type (ProcessorType): The family, and version of\n                the transaction processor.\n\n        Returns:\n            Processor"
  },
  {
    "code": "def read_metadata(self, symbol):\n        sym = self._get_symbol_info(symbol)\n        if not sym:\n            raise NoDataFoundException(\"Symbol does not exist.\")\n        x = self._symbols.find_one({SYMBOL: symbol})\n        return x[USERMETA] if USERMETA in x else None",
    "docstring": "Reads user defined metadata out for the given symbol\n\n        Parameters\n        ----------\n        symbol: str\n            symbol for the given item in the DB\n\n        Returns\n        -------\n        ?"
  },
  {
    "code": "def get_kde_home_dir ():\n    if os.environ.get(\"KDEHOME\"):\n        kde_home = os.path.abspath(os.environ[\"KDEHOME\"])\n    else:\n        home = os.environ.get(\"HOME\")\n        if not home:\n            return\n        kde3_home = os.path.join(home, \".kde\")\n        kde4_home = os.path.join(home, \".kde4\")\n        if fileutil.find_executable(\"kde4-config\"):\n            kde3_file = kde_home_to_config(kde3_home)\n            kde4_file = kde_home_to_config(kde4_home)\n            if os.path.exists(kde4_file) and os.path.exists(kde3_file):\n                if fileutil.get_mtime(kde4_file) >= fileutil.get_mtime(kde3_file):\n                    kde_home = kde4_home\n                else:\n                    kde_home = kde3_home\n            else:\n                kde_home = kde4_home\n        else:\n            kde_home = kde3_home\n    return kde_home if os.path.exists(kde_home) else None",
    "docstring": "Return KDE home directory or None if not found."
  },
  {
    "code": "def table_to_source_list(table, src_type=OutputSource):\n    source_list = []\n    if table is None:\n        return source_list\n    for row in table:\n        src = src_type()\n        for param in src_type.names:\n            if param in table.colnames:\n                val = row[param]\n                if isinstance(val, np.float32):\n                    val = np.float64(val)\n                setattr(src, param, val)\n        source_list.append(src)\n    return source_list",
    "docstring": "Convert a table of data into a list of sources.\n\n    A single table must have consistent source types given by src_type. src_type should be one of\n    :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools.models.SimpleSource`,\n    or :class:`AegeanTools.models.IslandSource`.\n\n\n    Parameters\n    ----------\n    table : Table\n        Table of sources\n\n    src_type : class\n        Sources must be of type :class:`AegeanTools.models.OutputSource`,\n        :class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSource`.\n\n    Returns\n    -------\n    sources : list\n        A list of objects of the given type."
  },
  {
    "code": "def guest_capture(self, userid, image_name, capture_type='rootonly',\n                      compress_level=6):\n        action = (\"capture guest '%(vm)s' to generate image '%(img)s'\" %\n                  {'vm': userid, 'img': image_name})\n        with zvmutils.log_and_reraise_sdkbase_error(action):\n            self._vmops.guest_capture(userid, image_name,\n                                      capture_type=capture_type,\n                                      compress_level=compress_level)",
    "docstring": "Capture the guest to generate a image\n\n        :param userid: (str) the user id of the vm\n        :param image_name: (str) the unique image name after capture\n        :param capture_type: (str) the type of capture, the value can be:\n               rootonly: indicate just root device will be captured\n               alldisks: indicate all the devices of the userid will be\n               captured\n        :param compress_level: the compression level of the image, default\n               is 6"
  },
  {
    "code": "def add_update_callback(self, callback, device):\n        self._update_callbacks.append([callback, device])\n        _LOGGER.debug('Added update callback to %s on %s', callback, device)",
    "docstring": "Register as callback for when a matching device changes."
  },
  {
    "code": "def save(callLog, logFilename):\n    with open(logFilename, \"wb\") as outp:\n      cPickle.dump(callLog, outp)",
    "docstring": "Save the call log history into this file.\n\n    @param  logFilename (path)\n            Filename in which to save a pickled version of the call logs."
  },
  {
    "code": "def mapzen_elevation_rgb(arr):\n    arr = np.clip(arr + 32768.0, 0.0, 65535.0)\n    r = arr / 256\n    g = arr % 256\n    b = (arr * 256) % 256\n    return np.stack([r, g, b]).astype(np.uint8)",
    "docstring": "Encode elevation value to RGB values compatible with Mapzen tangram.\n\n    Attributes\n    ----------\n    arr : numpy ndarray\n        Image array to encode.\n\n    Returns\n    -------\n    out : numpy ndarray\n        RGB array (3, h, w)"
  },
  {
    "code": "def track_end(self):\n        self.__tracking = False\n        changes = self.__changes\n        self.__changes = {}\n        return changes",
    "docstring": "Ends tracking of attributes changes.\n        Returns the changes that occurred to the attributes.\n          Only the final state of each attribute is obtained"
  },
  {
    "code": "def list_properties(self, list_all=False):\n        if list_all:\n            props = []\n            for k,v in self.env.property_rules.rdl_properties.items():\n                if type(self.inst) in v.bindable_to:\n                    props.append(k)\n            for k,v in self.env.property_rules.user_properties.items():\n                if type(self.inst) in v.bindable_to:\n                    props.append(k)\n            return props\n        else:\n            return list(self.inst.properties.keys())",
    "docstring": "Lists properties associated with this node.\n        By default, only lists properties that were explicitly set. If ``list_all`` is\n        set to ``True`` then lists all valid properties of this component type\n\n        Parameters\n        ----------\n        list_all: bool\n            If true, lists all valid properties of this component type."
  },
  {
    "code": "def create_socket():\n    sock = socket.socket(PF_CAN, socket.SOCK_RAW, CAN_RAW)\n    log.info('Created a socket')\n    return sock",
    "docstring": "Creates a raw CAN socket. The socket will\n    be returned unbound to any interface."
  },
  {
    "code": "def make(parser):\n    mds_parser = parser.add_subparsers(dest='subcommand')\n    mds_parser.required = True\n    mds_create = mds_parser.add_parser(\n        'create',\n        help='Deploy Ceph MDS on remote host(s)'\n    )\n    mds_create.add_argument(\n        'mds',\n        metavar='HOST[:NAME]',\n        nargs='+',\n        type=colon_separated,\n        help='host (and optionally the daemon name) to deploy on',\n        )\n    parser.set_defaults(\n        func=mds,\n        )",
    "docstring": "Ceph MDS daemon management"
  },
  {
    "code": "def get_device_sdr(self, record_id, reservation_id=None):\n        (next_id, record_data) = \\\n            get_sdr_data_helper(self.reserve_device_sdr_repository,\n                                self._get_device_sdr_chunk,\n                                record_id, reservation_id)\n        return sdr.SdrCommon.from_data(record_data, next_id)",
    "docstring": "Collects all data from the sensor device to get the SDR\n        specified by record id.\n\n        `record_id` the Record ID.\n        `reservation_id=None` can be set. if None the reservation ID will\n        be determined."
  },
  {
    "code": "def serialize_structmap(self, recurse=True, normative=False):\n        if not self.label:\n            return None\n        if self.is_empty_dir and not normative:\n            return None\n        el = etree.Element(utils.lxmlns(\"mets\") + \"div\", TYPE=self.mets_div_type)\n        el.attrib[\"LABEL\"] = self.label\n        if (not normative) and self.file_id():\n            etree.SubElement(el, utils.lxmlns(\"mets\") + \"fptr\", FILEID=self.file_id())\n        if self.dmdids:\n            if (not normative) or (normative and self.is_empty_dir):\n                el.set(\"DMDID\", \" \".join(self.dmdids))\n        if recurse and self._children:\n            for child in self._children:\n                child_el = child.serialize_structmap(\n                    recurse=recurse, normative=normative\n                )\n                if child_el is not None:\n                    el.append(child_el)\n        return el",
    "docstring": "Return the div Element for this file, appropriate for use in a\n        structMap.\n\n        If this FSEntry represents a directory, its children will be\n        recursively appended to itself. If this FSEntry represents a file, it\n        will contain a <fptr> element.\n\n        :param bool recurse: If true, serialize and apppend all children.\n            Otherwise, only serialize this element but not any children.\n        :param bool normative: If true, we are creating a \"Normative Directory\n            Structure\" logical structmap, in which case we add div elements for\n            empty directories and do not add fptr elements for files.\n        :return: structMap element for this FSEntry"
  },
  {
    "code": "def SetTicketAcceso(self, ta_string):\n        \"Establecer el token y sign desde un ticket de acceso XML\"\n        if ta_string:\n            ta = SimpleXMLElement(ta_string)\n            self.Token = str(ta.credentials.token)\n            self.Sign = str(ta.credentials.sign)\n            return True\n        else:\n            raise RuntimeError(\"Ticket de Acceso vacio!\")",
    "docstring": "Establecer el token y sign desde un ticket de acceso XML"
  },
  {
    "code": "def interface_type(self):\n        return self.visalib.parse_resource(self._resource_manager.session,\n                                           self.resource_name)[0].interface_type",
    "docstring": "The interface type of the resource as a number."
  },
  {
    "code": "def interpret_maskval(paramDict):\n    if 'maskval' not in paramDict:\n        return 0\n    maskval = paramDict['maskval']\n    if maskval is None:\n        maskval = np.nan\n    else:\n        maskval = float(maskval)\n    return maskval",
    "docstring": "Apply logic for interpreting final_maskval value..."
  },
  {
    "code": "def satisfier(self, term):\n        assigned_term = None\n        for assignment in self._assignments:\n            if assignment.dependency.name != term.dependency.name:\n                continue\n            if (\n                not assignment.dependency.is_root\n                and not assignment.dependency.name == term.dependency.name\n            ):\n                if not assignment.is_positive():\n                    continue\n                assert not term.is_positive()\n                return assignment\n            if assigned_term is None:\n                assigned_term = assignment\n            else:\n                assigned_term = assigned_term.intersect(assignment)\n            if assigned_term.satisfies(term):\n                return assignment\n        raise RuntimeError(\"[BUG] {} is not satisfied.\".format(term))",
    "docstring": "Returns the first Assignment in this solution such that the sublist of\n        assignments up to and including that entry collectively satisfies term."
  },
  {
    "code": "def get_request_feature(self, name):\n        if '[]' in name:\n            return self.request.query_params.getlist(\n                name) if name in self.features else None\n        elif '{}' in name:\n            return self._extract_object_params(\n                name) if name in self.features else {}\n        else:\n            return self.request.query_params.get(\n                name) if name in self.features else None",
    "docstring": "Parses the request for a particular feature.\n\n        Arguments:\n          name: A feature name.\n\n        Returns:\n          A feature parsed from the URL if the feature is supported, or None."
  },
  {
    "code": "def set_credentials(username, api_key=None, password=None, region=None,\n        tenant_id=None, authenticate=True):\n    global regions, services\n    pw_key = password or api_key\n    region = _safe_region(region)\n    tenant_id = tenant_id or settings.get(\"tenant_id\")\n    identity.set_credentials(username=username, password=pw_key,\n            tenant_id=tenant_id, region=region, authenticate=authenticate)\n    regions = tuple(identity.regions)\n    services = tuple(identity.services.keys())\n    connect_to_services(region=region)",
    "docstring": "Set the credentials directly, and then try to authenticate.\n\n    If the region is passed, it will authenticate against the proper endpoint\n    for that region, and set the default region for connections."
  },
  {
    "code": "def save(self):\n        data = super().save()\n        data['expr'] = self.expr.pattern\n        data['default_end'] = self.default_end\n        return data",
    "docstring": "Convert the scanner to JSON.\n\n        Returns\n        -------\n        `dict`\n            JSON data."
  },
  {
    "code": "def get_science_segments(workflow, out_dir, tags=None):\n    if tags is None:\n        tags = []\n    logging.info('Starting generation of science segments')\n    make_analysis_dir(out_dir)\n    start_time = workflow.analysis_time[0]\n    end_time = workflow.analysis_time[1]\n    sci_seg_name = \"SCIENCE\"\n    sci_segs = {}\n    sci_seg_dict = segments.segmentlistdict()\n    sci_seg_summ_dict = segments.segmentlistdict()\n    for ifo in workflow.ifos:\n        curr_sci_segs, curr_sci_xml, curr_seg_name = get_sci_segs_for_ifo(ifo,\n                              workflow.cp, start_time, end_time, out_dir, tags)\n        sci_seg_dict[ifo + ':' + sci_seg_name] = curr_sci_segs\n        sci_segs[ifo] = curr_sci_segs\n        sci_seg_summ_dict[ifo + ':' + sci_seg_name] = \\\n                          curr_sci_xml.seg_summ_dict[ifo + ':' + curr_seg_name]\n    sci_seg_file = SegFile.from_segment_list_dict(sci_seg_name,\n                                          sci_seg_dict, extension='xml',\n                                          valid_segment=workflow.analysis_time,\n                                          seg_summ_dict=sci_seg_summ_dict,\n                                          directory=out_dir, tags=tags)\n    logging.info('Done generating science segments')\n    return sci_seg_file, sci_segs, sci_seg_name",
    "docstring": "Get the analyzable segments after applying ini specified vetoes.\n\n    Parameters\n    -----------\n    workflow : Workflow object\n        Instance of the workflow object\n    out_dir : path\n        Location to store output files\n    tags : list of strings\n        Used to retrieve subsections of the ini file for\n        configuration options.\n\n    Returns\n    --------\n    sci_seg_file : workflow.core.SegFile instance\n        The segment file combined from all ifos containing the science segments.\n    sci_segs : Ifo keyed dict of ligo.segments.segmentlist instances\n        The science segs for each ifo, keyed by ifo\n    sci_seg_name : str\n        The name with which science segs are stored in the output XML file."
  },
  {
    "code": "def percentile_between(self,\n                           min_percentile,\n                           max_percentile,\n                           mask=NotSpecified):\n        return PercentileFilter(\n            self,\n            min_percentile=min_percentile,\n            max_percentile=max_percentile,\n            mask=mask,\n        )",
    "docstring": "Construct a new Filter representing entries from the output of this\n        Factor that fall within the percentile range defined by min_percentile\n        and max_percentile.\n\n        Parameters\n        ----------\n        min_percentile : float [0.0, 100.0]\n            Return True for assets falling above this percentile in the data.\n        max_percentile : float [0.0, 100.0]\n            Return True for assets falling below this percentile in the data.\n        mask : zipline.pipeline.Filter, optional\n            A Filter representing assets to consider when percentile\n            calculating thresholds.  If mask is supplied, percentile cutoffs\n            are computed each day using only assets for which ``mask`` returns\n            True.  Assets for which ``mask`` produces False will produce False\n            in the output of this Factor as well.\n\n        Returns\n        -------\n        out : zipline.pipeline.filters.PercentileFilter\n            A new filter that will compute the specified percentile-range mask.\n\n        See Also\n        --------\n        zipline.pipeline.filters.filter.PercentileFilter"
  },
  {
    "code": "def addFilter(self, field, value):\n        if \"<\" not in value or \">\" not in value or \"..\" not in value:\n            value = \":\" + value\n        if self.__urlFilters:\n            self.__urlFilters += \"+\" + field + str(quote(value))\n        else:\n            self.__urlFilters += field + str(quote(value))",
    "docstring": "Add a filter to the seach.\n\n        :param field: what field filter (see GitHub search).\n        :type field: str.\n        :param value: value of the filter (see GitHub search).\n        :type value: str."
  },
  {
    "code": "def send(self, obj):\n\t\tif not isinstance(obj, NotificationMessage):\n\t\t\traise ValueError, u\"You can only send NotificationMessage objects.\"\n\t\tself._send_queue.put(obj)",
    "docstring": "Send a push notification"
  },
  {
    "code": "def verify(self, id):\n        url = self._url('%s/verify' % (id))\n        return self.client.post(url)",
    "docstring": "Verify a custom domain\n\n        Args:\n           id (str): The id of the custom domain to delete\n\n\n        See: https://auth0.com/docs/api/management/v2#!/Custom_Domains/post_verify"
  },
  {
    "code": "def get_timex(self, timex_id):\n        if timex_id in self.idx:\n            return Ctime(self.idx[timex_id])\n        else:\n            return None",
    "docstring": "Returns the timex object for the supplied identifier\n        @type timex_id: string\n        @param timex_id: timex identifier"
  },
  {
    "code": "def get_default_net_device():\n    with open('/proc/net/route') as fh:\n        for line in fh:\n            iface, dest, _ = line.split(None, 2)\n            if dest == '00000000':\n                return iface\n    return None",
    "docstring": "Find the device where the default route is."
  },
  {
    "code": "def get_access_flags_string(value):\n    flags = []\n    for k, v in ACCESS_FLAGS.items():\n        if (k & value) == k:\n            flags.append(v)\n    return \" \".join(flags)",
    "docstring": "Transform an access flag field to the corresponding string\n\n    :param value: the value of the access flags\n    :type value: int\n\n    :rtype: string"
  },
  {
    "code": "def padding_to_length(padding):\n  non_padding = 1.0 - padding\n  return tf.to_int32(tf.reduce_sum(non_padding, axis=-1))",
    "docstring": "Calculate the length of mask based on padding.\n\n  Args:\n    padding: a Tensor with shape [..., length].\n  Returns:\n    a Tensor with shape [...]."
  },
  {
    "code": "def get_xml_root(xml_path):\n    r = requests.get(xml_path)\n    root = ET.fromstring(r.content)\n    return root",
    "docstring": "Load and parse an xml by given xml_path and return its root.\n\n    :param xml_path: URL to a xml file\n    :type xml_path: str\n    :return: xml root"
  },
  {
    "code": "def symbolic_master_equation(self, rho=None):\n        L, H = self.L, self.H\n        if rho is None:\n            rho = OperatorSymbol('rho', hs=self.space)\n        return (-I * (H * rho - rho * H) +\n                sum(Lk * rho * adjoint(Lk) -\n                    (adjoint(Lk) * Lk * rho + rho * adjoint(Lk) * Lk) / 2\n                    for Lk in L.matrix.ravel()))",
    "docstring": "Compute the symbolic Liouvillian acting on a state rho\n\n        If no rho is given, an OperatorSymbol is created in its place.\n        This correspnds to the RHS of the master equation\n        in which an average is taken over the external noise degrees of\n        freedom.\n\n        Args:\n            rho (Operator): A symbolic density matrix operator\n\n        Returns:\n            Operator: The RHS of the master equation."
  },
  {
    "code": "def set_backbuffer(self, preferred_backbuffer_size, flags=0):\n        if not (isinstance(preferred_backbuffer_size, Vector2)):\n            raise ValueError(\"preferred_backbuffer_size must be of type Vector2\")\n        self.__backbuffer = pygame.display.set_mode(preferred_backbuffer_size, flags)\n        self.Camera.world_center = preferred_backbuffer_size / 2.0",
    "docstring": "Create the backbuffer for the game."
  },
  {
    "code": "def _add_nat(self):\n        if is_period_dtype(self):\n            raise TypeError('Cannot add {cls} and {typ}'\n                            .format(cls=type(self).__name__,\n                                    typ=type(NaT).__name__))\n        result = np.zeros(len(self), dtype=np.int64)\n        result.fill(iNaT)\n        return type(self)(result, dtype=self.dtype, freq=None)",
    "docstring": "Add pd.NaT to self"
  },
  {
    "code": "def decode(self, envelope, session, target=None, modification_code=None, **kwargs):\n\t\tself.__args_check(envelope, target, modification_code)\n\t\tmessage = envelope.message()\n\t\tif len(message) < len(modification_code):\n\t\t\traise ValueError('Invalid message length')\n\t\tif isinstance(envelope, WMessengerTextEnvelope):\n\t\t\ttarget_envelope_cls = WMessengerTextEnvelope\n\t\telse:\n\t\t\ttarget_envelope_cls = WMessengerBytesEnvelope\n\t\tif target == WMessengerFixedModificationLayer.Target.head:\n\t\t\tif message[:len(modification_code)] != modification_code:\n\t\t\t\traise ValueError('Invalid header in message')\n\t\t\treturn target_envelope_cls(message[len(modification_code):], meta=envelope)\n\t\telse:\n\t\t\tif message[-len(modification_code):] != modification_code:\n\t\t\t\traise ValueError('Invalid tail in message')\n\t\t\treturn target_envelope_cls(message[:-len(modification_code)], meta=envelope)",
    "docstring": "Methods checks envelope for 'modification_code' existence and removes it.\n\n\t\t:param envelope: original envelope\n\t\t:param session: original session\n\t\t:param target: flag, that specifies whether code must be searched and removed at the start or at the end\n\t\t:param modification_code: code to search/remove\n\t\t:param kwargs: additional arguments\n\n\t\t:return: WMessengerTextEnvelope or WMessengerBytesEnvelope (depends on the original envelope)"
  },
  {
    "code": "def reset(self):\n    self.trnOverlaps = []\n    self.activeTRNSegments = []\n    self.activeTRNCellIndices = []\n    self.relayOverlaps = []\n    self.activeRelaySegments = []\n    self.burstReadyCellIndices = []\n    self.burstReadyCells = np.zeros((self.relayWidth, self.relayHeight))",
    "docstring": "Set everything back to zero"
  },
  {
    "code": "def _read_byte(self):\n        from .getch import _Getch\n        try:\n            g = _Getch()\n            self.tape[self.pointer] = ord(g())\n        except TypeError as e:\n            print \"Here's what _Getch() is giving me {}\".format(g())",
    "docstring": "Read a single byte from the user without waiting for the \\n character"
  },
  {
    "code": "def results(self, campaign_id):\n        return super(API, self).get(\n            resource_id=campaign_id,\n            resource_action='results',\n            resource_cls=CampaignResults)",
    "docstring": "Returns just the results for a given campaign"
  },
  {
    "code": "def ipostorder(self):\n        children = [self, ]\n        seen = set()\n        while children:\n            cur_node = children[-1]\n            if cur_node not in seen:\n                seen.add(cur_node)\n                children.extend(reversed(cur_node.children))\n            else:\n                children.pop()\n                yield cur_node",
    "docstring": "Depth-first post-order iteration of tree nodes"
  },
  {
    "code": "def can_route(self, endpoint, method=None, **kwargs):\n        view = flask.current_app.view_functions.get(endpoint)\n        if not view:\n            endpoint, args = flask._request_ctx.top.match(endpoint)\n            view = flask.current_app.view_functions.get(endpoint)\n        if not view:\n            return False\n        return self.can('http.' + (method or 'GET').lower(), view, **kwargs)",
    "docstring": "Make sure we can route to the given endpoint or url.\n\n        This checks for `http.get` permission (or other methods) on the ACL of\n        route functions, attached via the `ACL` decorator.\n\n        :param endpoint: A URL or endpoint to check for permission to access.\n        :param method: The HTTP method to check; defaults to `'GET'`.\n        :param **kwargs: The context to pass to predicates."
  },
  {
    "code": "def _generate_atom_feed(self, feed):\n        atom_feed = self.init_atom_feed(feed)\n        atom_feed.title(\"Feed\")\n        return atom_feed",
    "docstring": "A function returning a feed like `feedgen.feed.FeedGenerator`.\n        The function can be overwritten when used in other applications.\n\n        :param feed: a feed object\n        :return: an atom feed `feedgen.feed.FeedGenerator`"
  },
  {
    "code": "def namedb_get_account_tokens(cur, address):\n    sql = 'SELECT DISTINCT type FROM accounts WHERE address = ?;'\n    args = (address,)\n    rows = namedb_query_execute(cur, sql, args)\n    ret = []\n    for row in rows:\n        ret.append(row['type'])\n    return ret",
    "docstring": "Get an account's tokens\n    Returns the list of tokens on success\n    Returns None if not found"
  },
  {
    "code": "def _get_initial_sync_op(self):\n        def strip_port(s):\n            if s.endswith(':0'):\n                return s[:-2]\n            return s\n        local_vars = tf.local_variables()\n        local_var_by_name = dict([(strip_port(v.name), v) for v in local_vars])\n        ops = []\n        nr_shadow_vars = len(self._shadow_vars)\n        for v in self._shadow_vars:\n            vname = strip_port(v.name)\n            for i in range(self.nr_gpu):\n                name = 'tower%s/%s' % (i, vname)\n                assert name in local_var_by_name, \\\n                    \"Shadow variable {} doesn't match a corresponding local variable!\".format(v.name)\n                copy_to = local_var_by_name[name]\n                ops.append(copy_to.assign(v.read_value()))\n        return tf.group(*ops, name='sync_{}_variables_from_ps'.format(nr_shadow_vars))",
    "docstring": "Get the op to copy-initialized all local variables from PS."
  },
  {
    "code": "def git_remote(self):\n        if self._git_remotes is None or len(self._git_remotes) < 1:\n            return None\n        if 'origin' in self._git_remotes:\n            return self._git_remotes['origin']\n        k = sorted(self._git_remotes.keys())[0]\n        return self._git_remotes[k]",
    "docstring": "If the distribution is installed via git, return the first URL of the\n        'origin' remote if one is configured for the repo, or else the first\n        URL of the lexicographically-first remote, or else None.\n\n        :return: origin or first remote URL\n        :rtype: :py:obj:`str` or :py:data:`None`"
  },
  {
    "code": "def add_child(self, child):\n        assert isinstance(child, Term)\n        self.children.append(child)\n        child.parent = self\n        assert not child.term_is(\"Datafile.Section\")",
    "docstring": "Add a term to this term's children. Also sets the child term's parent"
  },
  {
    "code": "def claim_messages(self, queue, ttl, grace, count=None):\n        return queue.claim_messages(ttl, grace, count=count)",
    "docstring": "Claims up to `count` unclaimed messages from the specified queue. If\n        count is not specified, the default is to claim 10 messages.\n\n        The `ttl` parameter specifies how long the server should wait before\n        releasing the claim. The ttl value MUST be between 60 and 43200 seconds.\n\n        The `grace` parameter is the message grace period in seconds. The value\n        of grace MUST be between 60 and 43200 seconds. The server extends the\n        lifetime of claimed messages to be at least as long as the lifetime of\n        the claim itself, plus a specified grace period to deal with crashed\n        workers (up to 1209600 or 14 days including claim lifetime). If a\n        claimed message would normally live longer than the grace period, its\n        expiration will not be adjusted.\n\n        Returns a QueueClaim object, whose 'messages' attribute contains the\n        list of QueueMessage objects representing the claimed messages."
  },
  {
    "code": "def write(self, valuedict):\n        result = []\n        if self.identifier in valuedict:\n            values = valuedict[self.identifier]\n        else:\n            return result\n        if self.comment != \"\":\n            result.append(self.comment)\n        if self.repeat is not None and type(values) == type([]):\n            if self.repeat.isdigit():\n                for i in range(int(self.repeat)):  \n                    result.extend(self._write_iterate(values[i]))\n            else:\n                for value in values:\n                    result.extend(self._write_iterate(value))\n        elif type(values) == type({}):\n            result = self._write_iterate(values)\n        return result",
    "docstring": "Generates the lines for the converted input file using the specified\n        value dictionary."
  },
  {
    "code": "def __get_logged_in_id(self):\n        if self.__logged_in_id == None:\n            self.__logged_in_id = self.account_verify_credentials().id\n        return self.__logged_in_id",
    "docstring": "Fetch the logged in users ID, with caching. ID is reset on calls to log_in."
  },
  {
    "code": "def linear(current, target, rate, dt):\n    sign = (target > current) - (target < current)\n    if not sign:\n        return current\n    new_value = current + sign * rate * dt\n    if sign * new_value > sign * target:\n        return target\n    return new_value",
    "docstring": "This function returns the new value after moving towards\n    target at the given speed constantly for the time dt.\n\n    If for example the current position is 10 and the target is -20,\n    the returned value will be less than 10 if rate and dt are greater\n    than 0:\n\n    .. sourcecode:: Python\n\n        new_pos = linear(10, -20, 10, 0.1)  # new_pos = 9\n\n    The function makes sure that the returned value never overshoots:\n\n    .. sourcecode:: Python\n\n        new_pos = linear(10, -20, 10, 100)  # new_pos = -20\n\n    :param current: The current value of the variable to be changed.\n    :param target: The target value to approach.\n    :param rate: The rate at which the parameter should move towards target.\n    :param dt: The time for which to calculate the change.\n    :return: The new variable value."
  },
  {
    "code": "def prefix(rowPrefix):\n        fp = Range.followingPrefix(rowPrefix)\n        return Range(srow=rowPrefix, sinclude=True, erow=fp, einclude=False)",
    "docstring": "Returns a Range that covers all rows beginning with a prefix"
  },
  {
    "code": "def get_vm_ids_by_ud(access_token, subscription_id, resource_group, vmssname, updatedomain):\n    instance_viewlist = azurerm.list_vmss_vm_instance_view(access_token, subscription_id,\n                                                           resource_group, vmssname)\n    udinstancelist = []\n    for instance_view in instance_viewlist['value']:\n        vmud = instance_view['properties']['instance_view']['platformUpdateDomain']\n        if vmud == updatedomain:\n            udinstancelist.append(instance_view['instanceId'])\n    udinstancelist.sort()\n    return udinstancelist",
    "docstring": "look at VMSS VM instance view to get VM IDs by UD"
  },
  {
    "code": "def split(self, X, y):\n        check_ts_data(X, y)\n        Xt, Xc = get_ts_data_parts(X)\n        Ns = len(Xt)\n        Xt_new, y_new = self._ts_slice(Xt, y)\n        if Xc is not None:\n            Xc_new = np.concatenate([Xc] * self.n_splits)\n            X_new = TS_Data(Xt_new, Xc_new)\n        else:\n            X_new = np.array(Xt_new)\n        cv = self._make_indices(Ns)\n        return X_new, y_new, cv",
    "docstring": "Splits time series data and target arrays, and generates splitting indices\n\n        Parameters\n        ----------\n        X : array-like, shape [n_series, ...]\n           Time series data and (optionally) contextual data\n        y : array-like shape [n_series, ]\n            target vector\n\n        Returns\n        -------\n        X : array-like, shape [n_series * n_splits, ]\n            Split time series data and contextual data\n        y : array-like, shape [n_series * n_splits]\n            Split target data\n        cv : list, shape [2, n_splits]\n            Splitting indices"
  },
  {
    "code": "def update_hierarchy(self, hierarchy_form):\n        if self._catalog_session is not None:\n            return self._catalog_session.update_catalog(catalog_form=hierarchy_form)\n        collection = JSONClientValidated('hierarchy',\n                                         collection='Hierarchy',\n                                         runtime=self._runtime)\n        if not isinstance(hierarchy_form, ABCHierarchyForm):\n            raise errors.InvalidArgument('argument type is not an HierarchyForm')\n        if not hierarchy_form.is_for_update():\n            raise errors.InvalidArgument('the HierarchyForm is for update only, not create')\n        try:\n            if self._forms[hierarchy_form.get_id().get_identifier()] == UPDATED:\n                raise errors.IllegalState('hierarchy_form already used in an update transaction')\n        except KeyError:\n            raise errors.Unsupported('hierarchy_form did not originate from this session')\n        if not hierarchy_form.is_valid():\n            raise errors.InvalidArgument('one or more of the form elements is invalid')\n        collection.save(hierarchy_form._my_map)\n        self._forms[hierarchy_form.get_id().get_identifier()] = UPDATED\n        return objects.Hierarchy(osid_object_map=hierarchy_form._my_map, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Updates an existing hierarchy.\n\n        arg:    hierarchy_form (osid.hierarchy.HierarchyForm): the form\n                containing the elements to be updated\n        raise:  IllegalState - ``hierarchy_form`` already used in an\n                update transaction\n        raise:  InvalidArgument - the form contains an invalid value\n        raise:  NullArgument - ``hierarchy_id`` or ``hierarchy_form`` is\n                ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        raise:  Unsupported - ``hierarchy_form`` did not originate from\n                ``get_hierarchy_form_for_update()``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def GetFormattedMessages(self, event):\n    event_formatter = self.GetEventFormatter(event)\n    if not event_formatter:\n      return None, None\n    return event_formatter.GetMessages(self._formatter_mediator, event)",
    "docstring": "Retrieves the formatted messages related to the event.\n\n    Args:\n      event (EventObject): event.\n\n    Returns:\n      tuple: containing:\n\n        str: full message string or None if no event formatter was found.\n        str: short message string or None if no event formatter was found."
  },
  {
    "code": "def delete_attributes(self, item_name, attributes=None,\n                          expected_values=None):\n        return self.connection.delete_attributes(self, item_name, attributes,\n                                                 expected_values)",
    "docstring": "Delete attributes from a given item.\n\n        :type item_name: string\n        :param item_name: The name of the item whose attributes are being deleted.\n\n        :type attributes: dict, list or :class:`boto.sdb.item.Item`\n        :param attributes: Either a list containing attribute names which will cause\n                           all values associated with that attribute name to be deleted or\n                           a dict or Item containing the attribute names and keys and list\n                           of values to delete as the value.  If no value is supplied,\n                           all attribute name/values for the item will be deleted.\n                           \n        :type expected_value: list\n        :param expected_value: If supplied, this is a list or tuple consisting\n            of a single attribute name and expected value. The list can be of \n            the form:\n\n             * ['name', 'value']\n\n            In which case the call will first verify that the attribute \"name\"\n            of this item has a value of \"value\".  If it does, the delete\n            will proceed, otherwise a ConditionalCheckFailed error will be \n            returned. The list can also be of the form:\n\n             * ['name', True|False]\n\n            which will simply check for the existence (True) or \n            non-existence (False) of the attribute.\n\n        :rtype: bool\n        :return: True if successful"
  },
  {
    "code": "def inc_ptr(self, ptr):\n        result = ptr + self.reading_len[self.ws_type]\n        if result >= 0x10000:\n            result = self.data_start\n        return result",
    "docstring": "Get next circular buffer data pointer."
  },
  {
    "code": "def datatype_from_token(self, token):\n        if token.type == SystemRDLParser.ID:\n            typ = self.compiler.namespace.lookup_type(get_ID_text(token))\n            if typ is None:\n                self.msg.fatal(\n                    \"Type '%s' is not defined\" % get_ID_text(token),\n                    SourceRef.from_antlr(token)\n                )\n            if rdltypes.is_user_enum(typ) or rdltypes.is_user_struct(typ):\n                return typ\n            else:\n                self.msg.fatal(\n                    \"Type '%s' is not a struct or enum\" % get_ID_text(token),\n                    SourceRef.from_antlr(token)\n                )\n        else:\n            return self._DataType_Map[token.type]",
    "docstring": "Given a SystemRDLParser token, lookup the type\n        This only includes types under the \"data_type\" grammar rule"
  },
  {
    "code": "def _get_offset_day(self, other):\n        mstart = datetime(other.year, other.month, 1)\n        wday = mstart.weekday()\n        shift_days = (self.weekday - wday) % 7\n        return 1 + shift_days + self.week * 7",
    "docstring": "Find the day in the same month as other that has the same\n        weekday as self.weekday and is the self.week'th such day in the month.\n\n        Parameters\n        ----------\n        other : datetime\n\n        Returns\n        -------\n        day : int"
  },
  {
    "code": "def _export_corpus(self):\n        if not os.path.exists(self.mallet_bin):\n            raise IOError(\"MALLET path invalid or non-existent.\")\n        self.input_path = os.path.join(self.temp, \"input.mallet\")\n        exit = subprocess.call([\n                self.mallet_bin,\n                'import-file',\n                '--input', self.corpus_path,\n                '--output', self.input_path,\n                '--keep-sequence',\n                '--remove-stopwords'])\n        if exit != 0:\n            msg = \"MALLET import-file failed with exit code {0}.\".format(exit)\n            raise RuntimeError(msg)",
    "docstring": "Calls MALLET's `import-file` method."
  },
  {
    "code": "def add_teardown_callback(self, callback: Callable, pass_exception: bool = False) -> None:\n        assert check_argument_types()\n        self._check_closed()\n        self._teardown_callbacks.append((callback, pass_exception))",
    "docstring": "Add a callback to be called when this context closes.\n\n        This is intended for cleanup of resources, and the list of callbacks is processed in the\n        reverse order in which they were added, so the last added callback will be called first.\n\n        The callback may return an awaitable. If it does, the awaitable is awaited on before\n        calling any further callbacks.\n\n        :param callback: a callable that is called with either no arguments or with the exception\n            that ended this context, based on the value of ``pass_exception``\n        :param pass_exception: ``True`` to pass the callback the exception that ended this context\n            (or ``None`` if the context ended cleanly)"
  },
  {
    "code": "def slot_availability_array(events, slots):\n    array = np.ones((len(events), len(slots)))\n    for row, event in enumerate(events):\n        for col, slot in enumerate(slots):\n            if slot in event.unavailability or event.duration > slot.duration:\n                array[row, col] = 0\n    return array",
    "docstring": "Return a numpy array mapping events to slots\n\n    - Rows corresponds to events\n    - Columns correspond to stags\n\n    Array has value 0 if event cannot be scheduled in a given slot\n    (1 otherwise)"
  },
  {
    "code": "def _split_explanation(explanation):\n    raw_lines = (explanation or u('')).split('\\n')\n    lines = [raw_lines[0]]\n    for l in raw_lines[1:]:\n        if l and l[0] in ['{', '}', '~', '>']:\n            lines.append(l)\n        else:\n            lines[-1] += '\\\\n' + l\n    return lines",
    "docstring": "Return a list of individual lines in the explanation\n\n    This will return a list of lines split on '\\n{', '\\n}' and '\\n~'.\n    Any other newlines will be escaped and appear in the line as the\n    literal '\\n' characters."
  },
  {
    "code": "def iter_items(cls, repo, common_path=None, remote=None):\n        common_path = common_path or cls._common_path_default\n        if remote is not None:\n            common_path = join_path(common_path, str(remote))\n        return super(RemoteReference, cls).iter_items(repo, common_path)",
    "docstring": "Iterate remote references, and if given, constrain them to the given remote"
  },
  {
    "code": "def _get_exe(prog):\n        if prog in prog_to_env_var:\n            env_var = prog_to_env_var[prog]\n            if env_var in os.environ:\n                return os.environ[env_var]\n        return prog_to_default[prog]",
    "docstring": "Given a program name, return what we expect its exectuable to be called"
  },
  {
    "code": "def line(line_def, **kwargs):\n    def replace(s):\n        return \"(%s)\" % ansi.aformat(s.group()[1:], attrs=[\"bold\", ])\n    return ansi.aformat(\n        re.sub('@.?', replace, line_def),\n        **kwargs)",
    "docstring": "Highlights a character in the line"
  },
  {
    "code": "def battery_voltage(self):\n        msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_MSB_REG)\n        lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_LSB_REG)\n        voltage_bin = msb << 4 | lsb & 0x0f\n        return voltage_bin * 1.1",
    "docstring": "Returns voltage in mV"
  },
  {
    "code": "def checkForeignKeys(self, engine: Engine) -> None:\n        missing = (sqlalchemy_utils.functions\n                   .non_indexed_foreign_keys(self._metadata, engine=engine))\n        for table, keys in missing.items():\n            for key in keys:\n                logger.warning(\"Missing index on ForeignKey %s\" % key.columns)",
    "docstring": "Check Foreign Keys\n\n        Log any foreign keys that don't have indexes assigned to them.\n        This is a performance issue."
  },
  {
    "code": "def _assert_valid_permission(self, perm_str):\n        if perm_str not in ORDERED_PERM_LIST:\n            raise d1_common.types.exceptions.InvalidRequest(\n                0,\n                'Permission must be one of {}. perm_str=\"{}\"'.format(\n                    ', '.join(ORDERED_PERM_LIST), perm_str\n                ),\n            )",
    "docstring": "Raise D1 exception if ``perm_str`` is not a valid permission."
  },
  {
    "code": "def add_for_targets(self, targets, classpath_elements):\n    for target in targets:\n      self.add_for_target(target, classpath_elements)",
    "docstring": "Adds classpath path elements to the products of all the provided targets."
  },
  {
    "code": "def target_sequence_length(self):\n    if not self.is_aligned():\n      raise ValueError(\"no length for reference when read is not not aligned\")\n    if self.entries.tlen: return self.entries.tlen\n    if self.header:\n      if self.entries.rname in self.header.sequence_lengths:\n        return self.header.sequence_lengths[self.entries.rname]\n    elif self.reference:\n      return len(self.reference[self.entries.rname])\n    else:\n      raise ValueError(\"some reference needs to be set to go from psl to bam\\n\")\n    raise ValueError(\"No reference available\")",
    "docstring": "Get the length of the target sequence.  length of the entire chromosome\n\n    throws an error if there is no information available\n\n    :return: length\n    :rtype: int"
  },
  {
    "code": "def _get_instance(self, **kwargs):\n        current_app.logger.info(\"Getting instance\")\n        current_app.logger.debug(\"kwargs: {}\".format(kwargs))\n        current_app.logger.info(\n            \"Loading instance: {}\".format(kwargs['obj_id']))\n        rec = self.db_query.get_instance(self.db_collection, kwargs['obj_id'])\n        g._resource_instance = rec\n        current_app.logger.debug(\n            \"g._resource_instance: {}\".format(g._resource_instance))\n        return rec",
    "docstring": "Loads the record specified by the `obj_id` path in the url and\n           stores it in g._resource_instance"
  },
  {
    "code": "def dumps(self, obj, *, max_nested_level=100):\n        self._max_nested_level = max_nested_level\n        return self._encode(obj)",
    "docstring": "Returns a string representing a JSON-encoding of ``obj``.\n\n           The second optional ``max_nested_level`` argument controls the maximum\n           allowed recursion/nesting level.\n\n           See class description for details."
  },
  {
    "code": "def search(self, query, results=10, suggestion=False):\n        self._check_query(query, \"Query must be specified\")\n        search_params = {\n            \"list\": \"search\",\n            \"srprop\": \"\",\n            \"srlimit\": results,\n            \"srsearch\": query,\n        }\n        if suggestion:\n            search_params[\"srinfo\"] = \"suggestion\"\n        raw_results = self.wiki_request(search_params)\n        self._check_error_response(raw_results, query)\n        search_results = [d[\"title\"] for d in raw_results[\"query\"][\"search\"]]\n        if suggestion:\n            sug = None\n            if raw_results[\"query\"].get(\"searchinfo\"):\n                sug = raw_results[\"query\"][\"searchinfo\"][\"suggestion\"]\n            return search_results, sug\n        return search_results",
    "docstring": "Search for similar titles\n\n            Args:\n                query (str): Page title\n                results (int): Number of pages to return\n                suggestion (bool): Use suggestion\n            Returns:\n                tuple or list: tuple (list results, suggestion) if \\\n                               suggestion is **True**; list of results \\\n                               otherwise"
  },
  {
    "code": "def run_rc_file(editor, rc_file):\n    assert isinstance(editor, Editor)\n    assert isinstance(rc_file, six.string_types)\n    rc_file = os.path.expanduser(rc_file)\n    if not os.path.exists(rc_file):\n        print('Impossible to read %r' % rc_file)\n        _press_enter_to_continue()\n        return\n    try:\n        namespace = {}\n        with open(rc_file, 'r') as f:\n            code = compile(f.read(), rc_file, 'exec')\n            six.exec_(code, namespace, namespace)\n        if 'configure' in namespace:\n            namespace['configure'](editor)\n    except Exception as e:\n        traceback.print_exc()\n        _press_enter_to_continue()",
    "docstring": "Run rc file."
  },
  {
    "code": "def validate_subfolders(filedir, metadata):\n    if not os.path.isdir(filedir):\n        print(\"Error: \" + filedir + \" is not a directory\")\n        return False\n    subfolders = os.listdir(filedir)\n    for subfolder in subfolders:\n        if subfolder not in metadata:\n            print(\"Error: folder \" + subfolder +\n                  \" present on disk but not in metadata\")\n            return False\n    for subfolder in metadata:\n        if subfolder not in subfolders:\n            print(\"Error: folder \" + subfolder +\n                  \" present in metadata but not on disk\")\n            return False\n    return True",
    "docstring": "Check that all folders in the given directory have a corresponding\n    entry in the metadata file, and vice versa.\n\n    :param filedir: This field is the target directory from which to\n        match metadata\n    :param metadata: This field contains the metadata to be matched."
  },
  {
    "code": "def dvdot(s1, s2):\n    assert len(s1) is 6 and len(s2) is 6\n    s1 = stypes.toDoubleVector(s1)\n    s2 = stypes.toDoubleVector(s2)\n    return libspice.dvdot_c(s1, s2)",
    "docstring": "Compute the derivative of the dot product of two double\n    precision position vectors.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvdot_c.html\n\n    :param s1: First state vector in the dot product.\n    :type s1: 6-Element Array of floats\n    :param s2: Second state vector in the dot product.\n    :type s2: 6-Element Array of floats\n    :return: The derivative of the dot product.\n    :rtype: float"
  },
  {
    "code": "def op_list_apps(self):\n        self.logger.info('Listing known applications ...')\n        apps = self.get_apps()\n        for app in apps:\n            self.logger.info('Found `%s`' % app)\n        else:\n            self.logger.info('\\nDONE. No applications found in `%s` directory.\\n' % APPS_DIRNAME)\n        return apps",
    "docstring": "Prints out and returns a list of known applications.\n\n        :rtype: list\n        :return: list of applications"
  },
  {
    "code": "def encrypt_seal(self, data: Union[str, bytes]) -> bytes:\n        curve25519_public_key = libnacl.crypto_sign_ed25519_pk_to_curve25519(self.pk)\n        return libnacl.crypto_box_seal(ensure_bytes(data), curve25519_public_key)",
    "docstring": "Encrypt data with a curve25519 version of the ed25519 public key\n\n        :param data: Bytes data to encrypt"
  },
  {
    "code": "def avatar(self, blogname, size=64):\n        url = \"/v2/blog/{}/avatar/{}\".format(blogname, size)\n        return self.send_api_request(\"get\", url)",
    "docstring": "Retrieves the url of the blog's avatar\n\n        :param blogname: a string, the blog you want the avatar for\n\n        :returns: A dict created from the JSON response"
  },
  {
    "code": "def tee_log(tee_file: TextIO, loglevel: int) -> None:\n    handler = get_monochrome_handler(stream=tee_file)\n    handler.setLevel(loglevel)\n    rootlogger = logging.getLogger()\n    rootlogger.addHandler(handler)\n    with TeeContextManager(tee_file, capture_stdout=True):\n        with TeeContextManager(tee_file, capture_stderr=True):\n            try:\n                yield\n            except Exception:\n                exc_type, exc_value, exc_traceback = sys.exc_info()\n                lines = traceback.format_exception(exc_type, exc_value,\n                                                   exc_traceback)\n                log.critical(\"\\n\" + \"\".join(lines))\n                raise",
    "docstring": "Context manager to add a file output stream to our logging system.\n\n    Args:\n        tee_file: file-like object to write to\n        loglevel: log level (e.g. ``logging.DEBUG``) to use for this stream"
  },
  {
    "code": "def cfg_from_file(self, yaml_filename, config_dict):\n        import yaml\n        from easydict import EasyDict as edict\n        with open(yaml_filename, 'r') as f:\n            yaml_cfg = edict(yaml.load(f))\n        return self._merge_a_into_b(yaml_cfg, config_dict)",
    "docstring": "Load a config file and merge it into the default options."
  },
  {
    "code": "def incrementor(start=0, step=1):\n  def fxn(_):\n    nonlocal start\n    rval = start\n    start += step\n    return rval\n  return fxn",
    "docstring": "Returns a function that first returns the start value, and returns previous value + step on\n  each subsequent call."
  },
  {
    "code": "def get_available_fcp(self):\n        available_list = []\n        free_unreserved = self.db.get_all_free_unreserved()\n        for item in free_unreserved:\n            available_list.append(item[0])\n        return available_list",
    "docstring": "get all the fcps not reserved"
  },
  {
    "code": "def wrap_function_name(self, name):\n        if len(name) > 32:\n            ratio = 2.0/3.0\n            height = max(int(len(name)/(1.0 - ratio) + 0.5), 1)\n            width = max(len(name)/height, 32)\n            name = textwrap.fill(name, width, break_long_words=False)\n        name = name.replace(\", \", \",\")\n        name = name.replace(\"> >\", \">>\")\n        name = name.replace(\"> >\", \">>\")\n        return name",
    "docstring": "Split the function name on multiple lines."
  },
  {
    "code": "def select_random(ports=None, exclude_ports=None):\n    if ports is None:\n        ports = available_good_ports()\n    if exclude_ports is None:\n        exclude_ports = set()\n    ports.difference_update(set(exclude_ports))\n    for port in random.sample(ports, min(len(ports), 100)):\n        if not port_is_used(port):\n            return port\n    raise PortForException(\"Can't select a port\")",
    "docstring": "Returns random unused port number."
  },
  {
    "code": "def read_chunks(stream, block_size=2**10):\n    while True:\n        chunk = stream.read(block_size)\n        if not chunk:\n            break\n        yield chunk",
    "docstring": "Given a byte stream with reader, yield chunks of block_size\n    until the stream is consusmed."
  },
  {
    "code": "def database_all(self):\n        all = {}\n        for engine in self.engines():\n            all[engine] = self._database_all(engine)\n        return all",
    "docstring": "Return a dictionary mapping engines with databases"
  },
  {
    "code": "def selected_band(self):\n        item = self.lstBands.currentItem()\n        return item.data(QtCore.Qt.UserRole)",
    "docstring": "Obtain the layer mode selected by user.\n\n        :returns: selected layer mode.\n        :rtype: string, None"
  },
  {
    "code": "def _process_exlist(self, exc, raised):\n        if (not raised) or (raised and exc.endswith(\"*\")):\n            return exc[:-1] if exc.endswith(\"*\") else exc\n        return None",
    "docstring": "Remove raised info from exception message and create separate list for it."
  },
  {
    "code": "def reference_links(doc):\n    if doc.get('type') == 'organisation' and doc.get('state') != 'deactivated':\n        for asset_id_type, link in doc.get('reference_links', {}).get('links', {}).items():\n            value = {\n                'organisation_id': doc['_id'],\n                'link': link\n            }\n            yield asset_id_type, value",
    "docstring": "Get reference links"
  },
  {
    "code": "def extract_source_params(src):\n    tags = get_taglist(src)\n    data = []\n    for key, param, vtype in BASE_PARAMS:\n        if key in src.attrib:\n            if vtype == \"c\":\n                data.append((param, src.attrib[key]))\n            elif vtype == \"f\":\n                data.append((param, float(src.attrib[key])))\n            else:\n                data.append((param, None))\n        elif key in tags:\n            if vtype == \"c\":\n                data.append((param, src.nodes[tags.index(key)].text))\n            elif vtype == \"f\":\n                data.append((param, float(src.nodes[tags.index(key)].text)))\n            else:\n                data.append((param, None))\n        else:\n            data.append((param, None))\n    return dict(data)",
    "docstring": "Extract params from source object."
  },
  {
    "code": "def opt_allow_select_scan(self, allow):\n        allow = allow.lower() in (\"true\", \"t\", \"yes\", \"y\")\n        self.conf[\"allow_select_scan\"] = allow\n        self.engine.allow_select_scan = allow",
    "docstring": "Set option allow_select_scan"
  },
  {
    "code": "def _rsadp(self, c):\n        n = self.modulus\n        if type(c) is int:\n            c = long(c)        \n        if type(c) is not long or c > n-1:\n            warning(\"Key._rsaep() expects a long between 0 and n-1\")\n            return None\n        return self.key.decrypt(c)",
    "docstring": "Internal method providing raw RSA decryption, i.e. simple modular\n        exponentiation of the given ciphertext representative 'c', a long\n        between 0 and n-1.\n\n        This is the decryption primitive RSADP described in PKCS#1 v2.1,\n        i.e. RFC 3447 Sect. 5.1.2.\n\n        Input:\n           c: ciphertest representative, a long between 0 and n-1, where\n              n is the key modulus.\n\n        Output:\n           ciphertext representative, a long between 0 and n-1\n\n        Not intended to be used directly. Please, see encrypt() method."
  },
  {
    "code": "def _preconditions_snapshots_postconditions(checker: Callable) -> _PrePostSnaps:\n    preconditions = getattr(checker, \"__preconditions__\", [])\n    assert all(isinstance(precondition_group, list) for precondition_group in preconditions)\n    assert (all(\n        isinstance(precondition, icontract._Contract) for precondition_group in preconditions\n        for precondition in precondition_group))\n    preconditions = [group for group in preconditions if len(group) > 0]\n    snapshots = getattr(checker, \"__postcondition_snapshots__\", [])\n    assert all(isinstance(snap, icontract._Snapshot) for snap in snapshots)\n    postconditions = getattr(checker, \"__postconditions__\", [])\n    assert all(isinstance(postcondition, icontract._Contract) for postcondition in postconditions)\n    return _PrePostSnaps(preconditions=preconditions, snapshots=snapshots, postconditions=postconditions)",
    "docstring": "Collect the preconditions, snapshots and postconditions from a contract checker of a function."
  },
  {
    "code": "def monitored_resource_descriptor_path(cls, project, monitored_resource_descriptor):\n        return google.api_core.path_template.expand(\n            \"projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}\",\n            project=project,\n            monitored_resource_descriptor=monitored_resource_descriptor,\n        )",
    "docstring": "Return a fully-qualified monitored_resource_descriptor string."
  },
  {
    "code": "def delete_feature(ctx, dataset, fid):\n    service = ctx.obj.get('service')\n    res = service.delete_feature(dataset, fid)\n    if res.status_code != 204:\n        raise MapboxCLIException(res.text.strip())",
    "docstring": "Delete a feature.\n\n        $ mapbox datasets delete-feature dataset-id feature-id\n\n    All endpoints require authentication. An access token with\n    `datasets:write` scope is required, see `mapbox --help`."
  },
  {
    "code": "def refresh_state_in_ec(self, ec_index):\n        with self._mutex:\n            if ec_index >= len(self.owned_ecs):\n                ec_index -= len(self.owned_ecs)\n                if ec_index >= len(self.participating_ecs):\n                    raise exceptions.BadECIndexError(ec_index)\n                state = self._get_ec_state(self.participating_ecs[ec_index])\n                self.participating_ec_states[ec_index] = state\n            else:\n                state = self._get_ec_state(self.owned_ecs[ec_index])\n                self.owned_ec_states[ec_index] = state\n            return state",
    "docstring": "Get the up-to-date state of the component in an execution context.\n\n        This function will update the state, rather than using the cached\n        value. This may take time, if the component is executing on a remote\n        node.\n\n        @param ec_index The index of the execution context to check the state\n                        in. This index is into the total array of contexts,\n                        that is both owned and participating contexts. If the\n                        value of ec_index is greater than the length of @ref\n                        owned_ecs, that length is subtracted from ec_index and\n                        the result used as an index into @ref\n                        participating_ecs."
  },
  {
    "code": "def _build_split_filenames(self, split_info_list):\n    filenames = []\n    for split_info in split_info_list:\n      filenames.extend(naming.filepaths_for_dataset_split(\n          dataset_name=self.name,\n          split=split_info.name,\n          num_shards=split_info.num_shards,\n          data_dir=self._data_dir,\n          filetype_suffix=self._file_format_adapter.filetype_suffix,\n      ))\n    return filenames",
    "docstring": "Construct the split filenames associated with the split info.\n\n    The filenames correspond to the pre-processed datasets files present in\n    the root directory of the dataset.\n\n    Args:\n      split_info_list: (list[SplitInfo]) List of split from which generate the\n        filenames\n\n    Returns:\n      filenames: (list[str]) The list of filenames path corresponding to the\n        split info object"
  },
  {
    "code": "def on(self, message, namespace=None):\n        namespace = namespace or '/'\n        def decorator(handler):\n            def _handler(sid, *args):\n                return self._handle_event(handler, message, namespace, sid,\n                                          *args)\n            if self.server:\n                self.server.on(message, _handler, namespace=namespace)\n            else:\n                self.handlers.append((message, _handler, namespace))\n            return handler\n        return decorator",
    "docstring": "Decorator to register a SocketIO event handler.\n\n        This decorator must be applied to SocketIO event handlers. Example::\n\n            @socketio.on('my event', namespace='/chat')\n            def handle_my_custom_event(json):\n                print('received json: ' + str(json))\n\n        :param message: The name of the event. This is normally a user defined\n                        string, but a few event names are already defined. Use\n                        ``'message'`` to define a handler that takes a string\n                        payload, ``'json'`` to define a handler that takes a\n                        JSON blob payload, ``'connect'`` or ``'disconnect'``\n                        to create handlers for connection and disconnection\n                        events.\n        :param namespace: The namespace on which the handler is to be\n                          registered. Defaults to the global namespace."
  },
  {
    "code": "def label(self, nid, id_if_null=False):\n        g = self.get_graph()\n        if nid in g:\n            n = g.node[nid]\n            if 'label' in n:\n                return n['label']\n            else:\n                if id_if_null:\n                    return nid\n                else:\n                    return None\n        else:\n            if id_if_null:\n                return nid\n            else:\n                return None",
    "docstring": "Fetches label for a node\n\n        Arguments\n        ---------\n        nid : str\n            Node identifier for entity to be queried\n        id_if_null : bool\n            If True and node has no label return id as label\n\n        Return\n        ------\n        str"
  },
  {
    "code": "def saveFile(self):\n        filepath, _ = QtWidgets.QFileDialog.getSaveFileName(\n            self, \"Save File\", '', \"Androguard Session (*.ag)\")\n        if filepath:\n            if not filepath.endswith(\".ag\"):\n                filepath = \"{}.ag\".format(filepath)\n            self.showStatus(\"Saving %s...\" % str(filepath))\n            self.saveSession(filepath)\n            self.showStatus(\"Saved Session to %s!\" % str(filepath))",
    "docstring": "User clicked Save menu. Display a Dialog to ask whwre to save."
  },
  {
    "code": "def generate_grid_coords(gx, gy):\n    r\n    return np.vstack([gx.ravel(), gy.ravel()]).T",
    "docstring": "r\"\"\"Calculate x,y coordinates of each grid cell.\n\n    Parameters\n    ----------\n    gx: numeric\n        x coordinates in meshgrid\n    gy: numeric\n        y coordinates in meshgrid\n\n    Returns\n    -------\n    (X, Y) ndarray\n        List of coordinates in meshgrid"
  },
  {
    "code": "def set_exception(self, exception):\n        self.set_exc_info(\n            (exception.__class__,\n             exception,\n             getattr(exception, '__traceback__', None)))",
    "docstring": "Sets the exception of a ``Future.``"
  },
  {
    "code": "def assign_license(license_key, license_name, entity, entity_display_name,\n                   safety_checks=True, service_instance=None):\n    log.trace('Assigning license %s to entity %s', license_key, entity)\n    _validate_entity(entity)\n    if safety_checks:\n        licenses = salt.utils.vmware.get_licenses(service_instance)\n        if not [l for l in licenses if l.licenseKey == license_key]:\n            raise VMwareObjectRetrievalError('License \\'{0}\\' wasn\\'t found'\n                                             ''.format(license_name))\n    salt.utils.vmware.assign_license(\n        service_instance,\n        license_key,\n        license_name,\n        entity_ref=_get_entity(service_instance, entity),\n        entity_name=entity_display_name)",
    "docstring": "Assigns a license to an entity\n\n    license_key\n        Key of the license to assign\n        See ``_get_entity`` docstrings for format.\n\n    license_name\n        Display name of license\n\n    entity\n        Dictionary representation of an entity\n\n    entity_display_name\n        Entity name used in logging\n\n    safety_checks\n        Specify whether to perform safety check or to skip the checks and try\n        performing the required task. Default is False.\n\n    service_instance\n        Service instance (vim.ServiceInstance) of the vCenter/ESXi host.\n        Default is None.\n\n    .. code-block:: bash\n\n        salt '*' vsphere.assign_license license_key=00000:00000\n            license name=test entity={type:cluster,datacenter:dc,cluster:cl}"
  },
  {
    "code": "def parse_yaml_config(args):\n    try:\n        import yaml\n    except ImportError:\n        yaml = None\n    yml = {}\n    try:\n        with open(args.coveralls_yaml, 'r') as fp:\n            if not yaml:\n                raise SystemExit('PyYAML is required for parsing configuration')\n            yml = yaml.load(fp)\n    except IOError:\n        pass\n    yml = yml or {}\n    return yml",
    "docstring": "Parse yaml config"
  },
  {
    "code": "def filter(self, condition):\n        if isinstance(condition, basestring):\n            jdf = self._jdf.filter(condition)\n        elif isinstance(condition, Column):\n            jdf = self._jdf.filter(condition._jc)\n        else:\n            raise TypeError(\"condition should be string or Column\")\n        return DataFrame(jdf, self.sql_ctx)",
    "docstring": "Filters rows using the given condition.\n\n        :func:`where` is an alias for :func:`filter`.\n\n        :param condition: a :class:`Column` of :class:`types.BooleanType`\n            or a string of SQL expression.\n\n        >>> df.filter(df.age > 3).collect()\n        [Row(age=5, name=u'Bob')]\n        >>> df.where(df.age == 2).collect()\n        [Row(age=2, name=u'Alice')]\n\n        >>> df.filter(\"age > 3\").collect()\n        [Row(age=5, name=u'Bob')]\n        >>> df.where(\"age = 2\").collect()\n        [Row(age=2, name=u'Alice')]"
  },
  {
    "code": "def remove_peer(self, peer):\n        if peer.index < 0 or peer.index >= self.size():\n            raise IndexError('Peer index is out of range')\n        assert peer is self.peers[peer.index], \"peer is not in the heap\"\n        return heap.remove(self, peer.index)",
    "docstring": "Remove the peer from the heap.\n\n        Return: removed peer if peer exists. If peer's index is out of range,\n        raise IndexError."
  },
  {
    "code": "def preprocess_model(model, rewrap=True, **kwargs):\n    args = {**kwargs, **config.get('args', {})}\n    model = _process_template(model, **args)\n    if rewrap:\n        model = rewrap_model(model)\n    return model",
    "docstring": "Preprocess a MiniZinc model.\n\n    This function takes care of preprocessing the model by resolving the\n    template using the arguments passed as keyword arguments to this function.\n    Optionally, this function can also \"rewrap\" the model, deleting spaces at\n    the beginning of the lines while preserving indentation.\n\n    Parameters\n    ----------\n    model : str\n        The minizinc model (i.e. the content of a ``.mzn`` file).\n    rewrap : bool\n        Whether to \"rewrap\" the model, i.e. to delete leading spaces, while\n        preserving indentation. Default is ``True``.\n    **kwargs\n        Additional arguments to pass to the template engine.\n\n    Returns\n    -------\n    str\n        The preprocessed model."
  },
  {
    "code": "def run(self, command):\n        if isinstance(command, basestring):\n            command = command.split()\n        else:\n            command = list(command)\n        self.external.omero_cli(command)",
    "docstring": "Runs a command as if from the command-line\n        without the need for using popen or subprocess"
  },
  {
    "code": "def from_http(\n        cls,\n        raw_body: MutableMapping,\n        verification_token: Optional[str] = None,\n        team_id: Optional[str] = None,\n    ) -> \"Event\":\n        if verification_token and raw_body[\"token\"] != verification_token:\n            raise exceptions.FailedVerification(raw_body[\"token\"], raw_body[\"team_id\"])\n        if team_id and raw_body[\"team_id\"] != team_id:\n            raise exceptions.FailedVerification(raw_body[\"token\"], raw_body[\"team_id\"])\n        if raw_body[\"event\"][\"type\"].startswith(\"message\"):\n            return Message(raw_body[\"event\"], metadata=raw_body)\n        else:\n            return Event(raw_body[\"event\"], metadata=raw_body)",
    "docstring": "Create an event with data coming from the HTTP Event API.\n\n        If the event type is a message a :class:`slack.events.Message` is returned.\n\n        Args:\n            raw_body: Decoded body of the Event API request\n            verification_token: Slack verification token used to verify the request came from slack\n            team_id: Verify the event is for the correct team\n\n        Returns:\n            :class:`slack.events.Event` or :class:`slack.events.Message`\n\n        Raises:\n            :class:`slack.exceptions.FailedVerification`: when `verification_token` or `team_id` does not match the\n                                                          incoming event's."
  },
  {
    "code": "def which(cwd=None):\n        if cwd is None:\n            cwd = os.getcwd()\n        for (k, using_vc) in globals().items():\n            if k.startswith('using_') and using_vc(cwd=cwd):\n                return VersionControl.from_string(k[6:])\n        raise NotImplementedError(\"Unknown version control system, \"\n                                  \"or you're not in the project directory.\")",
    "docstring": "Try to find which version control system contains the cwd directory.\n\n        Returns the VersionControl superclass e.g. Git, if none were\n        found this will raise a NotImplementedError."
  },
  {
    "code": "def __get_query_range(cls, date_field, start=None, end=None):\n        if not start and not end:\n            return ''\n        start_end = {}\n        if start:\n            start_end[\"gte\"] = \"%s\" % start.isoformat()\n        if end:\n            start_end[\"lte\"] = \"%s\" % end.isoformat()\n        query_range = {date_field: start_end}\n        return query_range",
    "docstring": "Create a filter dict with date_field from start to end dates.\n\n        :param date_field: field with the date value\n        :param start: date with the from value. Should be a datetime.datetime object\n                      of the form: datetime.datetime(2018, 5, 25, 15, 17, 39)\n        :param end: date with the to value. Should be a datetime.datetime object\n                      of the form: datetime.datetime(2018, 5, 25, 15, 17, 39)\n        :return: a dict containing a range filter which can be used later in an\n                 es_dsl Search object using the `filter` method."
  },
  {
    "code": "def rename(self, names, inplace=False):\n        if (type(names) is not dict):\n            raise TypeError('names must be a dictionary: oldname -> newname')\n        if inplace:\n            self.__is_dirty__ = True\n            with cython_context():\n                if self._is_vertex_frame():\n                    graph_proxy = self.__graph__.__proxy__.rename_vertex_fields(names.keys(), names.values())\n                    self.__graph__.__proxy__ = graph_proxy\n                elif self._is_edge_frame():\n                    graph_proxy = self.__graph__.__proxy__.rename_edge_fields(names.keys(), names.values())\n                    self.__graph__.__proxy__ = graph_proxy\n            return self\n        else:\n            return super(GFrame, self).rename(names, inplace=inplace)",
    "docstring": "Rename the columns using the 'names' dict.  This changes the names of\n        the columns given as the keys and replaces them with the names given as\n        the values.\n\n        If inplace == False (default) this operation does not modify the\n        current SFrame, returning a new SFrame.\n\n        If inplace == True, this operation modifies the current\n        SFrame, returning self.\n\n        Parameters\n        ----------\n        names : dict[string, string]\n            Dictionary of [old_name, new_name]\n\n        inplace : bool, optional. Defaults to False.\n            Whether the SFrame is modified in place."
  },
  {
    "code": "def cancel_link_unlink_mode(self):\n        self.logger.info(\"cancel_link_unlink_mode\")\n        self.scene_command('08')\n        status = self.hub.get_buffer_status()\n        return status",
    "docstring": "Cancel linking or unlinking mode"
  },
  {
    "code": "def send(self):\n        response = self.session.request(\"method:queue\", [ self.data ])\n        self.data = response\n        return self",
    "docstring": "Send the draft."
  },
  {
    "code": "def create_redis_client(redis_address, password=None):\n    redis_ip_address, redis_port = redis_address.split(\":\")\n    return redis.StrictRedis(\n        host=redis_ip_address, port=int(redis_port), password=password)",
    "docstring": "Create a Redis client.\n\n    Args:\n        The IP address, port, and password of the Redis server.\n\n    Returns:\n        A Redis client."
  },
  {
    "code": "def oindex(a, selection):\n    selection = replace_ellipsis(selection, a.shape)\n    drop_axes = tuple([i for i, s in enumerate(selection) if is_integer(s)])\n    selection = ix_(selection, a.shape)\n    result = a[selection]\n    if drop_axes:\n        result = result.squeeze(axis=drop_axes)\n    return result",
    "docstring": "Implementation of orthogonal indexing with slices and ints."
  },
  {
    "code": "def swap_word_order(source):\n    assert len(source) % 4 == 0\n    words = \"I\" * (len(source) // 4)\n    return struct.pack(words, *reversed(struct.unpack(words, source)))",
    "docstring": "Swap the order of the words in 'source' bitstring"
  },
  {
    "code": "def add_vxlan_port(self, name, remote_ip,\n                       local_ip=None, key=None, ofport=None):\n        self.add_tunnel_port(name, 'vxlan', remote_ip,\n                             local_ip=local_ip, key=key, ofport=ofport)",
    "docstring": "Creates a VxLAN tunnel port.\n\n        See the description of ``add_tunnel_port()``."
  },
  {
    "code": "def _run_expiration(self, conn):\n        now = time.time()\n        script = conn.register_script(\n)\n        expiring = script(keys=[self._key_expiration()], args=[time.time()])\n        script = conn.register_script(\n)\n        for item in expiring:\n            script(keys=[self._key_available(), self._key_priorities(),\n                         self._key_workers(), self._key_reservations(item)],\n                   args=[item])",
    "docstring": "Return any items that have expired."
  },
  {
    "code": "def import_modules(names, src, dst):\n    for name in names:\n        module = importlib.import_module(src + '.' + name)\n        setattr(sys.modules[dst], name, module)",
    "docstring": "Import modules in package."
  },
  {
    "code": "def float_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs):\n        if (min is not None) and (max is not None) and not (max > min):\n            raise ValueError(\"Maximum limit has to be more than the minimum limit.\")\n        def float_validator(text):\n            error = None\n            try:\n                value = float(text)\n            except ValueError:\n                return None, \"Please enter a floating point value.\"\n            if (min is not None) and (value < min):\n                return None, \"The minimum allowable value is {0}.\".format(min)\n            if (max is not None) and (value > max):\n                return None, \"The maximum allowable value is {0}.\".format(max)\n            return value, None\n        return self.generic_entry(prompt, float_validator, message, rofi_args, **kwargs)",
    "docstring": "Prompt the user to enter a floating point number.\n\n        Parameters\n        ----------\n        prompt: string\n            Prompt to display to the user.\n        message: string, optional\n            Message to display under the entry line.\n        min, max: float, optional\n            Minimum and maximum values to allow. If None, no limit is imposed.\n\n        Returns\n        -------\n        float, or None if the dialog is cancelled."
  },
  {
    "code": "def read_grid_from_file(filename):\n    try:\n        f = open(filename, mode='r')\n        full_res = ast.literal_eval(f.read())\n        f.close()\n    except SyntaxError:\n        print('Problems reading ', filename)\n        full_res = {'grid': 0, 'all_done': False}\n    except (OSError, IOError):\n        full_res = {'grid': 0, 'all_done': False}\n    return full_res",
    "docstring": "Read the results of a full set of calculations from file"
  },
  {
    "code": "def alias_grade_entry(self, grade_entry_id, alias_id):\n        self._alias_id(primary_id=grade_entry_id, equivalent_id=alias_id)",
    "docstring": "Adds an ``Id`` to a ``GradeEntry`` for the purpose of creating compatibility.\n\n        The primary ``Id`` of the ``GradeEntry`` is determined by the\n        provider. The new ``Id`` performs as an alias to the primary\n        ``Id``. If the alias is a pointer to another grade entry, it is\n        reassigned to the given grade entry ``Id``.\n\n        arg:    grade_entry_id (osid.id.Id): the ``Id`` of a\n                ``GradeEntry``\n        arg:    alias_id (osid.id.Id): the alias ``Id``\n        raise:  AlreadyExists - ``alias_id`` is already assigned\n        raise:  NotFound - ``grade_entry_id`` not found\n        raise:  NullArgument - ``grade_entry_id`` or ``alias_id`` is\n                ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def CreateClass(cls, data_type_definition):\n    cls._ValidateDataTypeDefinition(data_type_definition)\n    class_definition = cls._CreateClassTemplate(data_type_definition)\n    namespace = {\n        '__builtins__' : {\n            'object': builtins.object,\n            'super': builtins.super},\n        '__name__': '{0:s}'.format(data_type_definition.name)}\n    if sys.version_info[0] >= 3:\n      namespace['__builtins__']['__build_class__'] = builtins.__build_class__\n    exec(class_definition, namespace)\n    return namespace[data_type_definition.name]",
    "docstring": "Creates a new structure values class.\n\n    Args:\n      data_type_definition (DataTypeDefinition): data type definition.\n\n    Returns:\n      class: structure values class."
  },
  {
    "code": "async def getLiftRows(self, lops):\n        for layeridx, layr in enumerate(self.layers):\n            async for x in layr.getLiftRows(lops):\n                yield layeridx, x",
    "docstring": "Yield row tuples from a series of lift operations.\n\n        Row tuples only requirement is that the first element\n        be the binary id of a node.\n\n        Args:\n            lops (list): A list of lift operations.\n\n        Yields:\n            (tuple): (layer_indx, (buid, ...)) rows."
  },
  {
    "code": "def _add_lines(specification, module):\n    caption = _all_spec2capt.get(specification, 'dummy')\n    if caption.split()[-1] in ('parameters', 'sequences', 'Masks'):\n        exists_collectionclass = True\n        name_collectionclass = caption.title().replace(' ', '')\n    else:\n        exists_collectionclass = False\n    lines = []\n    if specification == 'model':\n        lines += [f'',\n                  f'.. autoclass:: {module.__name__}.Model',\n                  f'    :members:',\n                  f'    :show-inheritance:',\n                  f'    :exclude-members: {\", \".join(EXCLUDE_MEMBERS)}']\n    elif exists_collectionclass:\n        lines += [f'',\n                  f'.. autoclass:: {module.__name__}.{name_collectionclass}',\n                  f'    :members:',\n                  f'    :show-inheritance:',\n                  f'    :exclude-members: {\", \".join(EXCLUDE_MEMBERS)}']\n    lines += ['',\n              '.. automodule:: ' + module.__name__,\n              '    :members:',\n              '    :show-inheritance:']\n    if specification == 'model':\n        lines += ['    :exclude-members: Model']\n    elif exists_collectionclass:\n        lines += ['    :exclude-members: ' + name_collectionclass]\n    return lines",
    "docstring": "Return autodoc commands for a basemodels docstring.\n\n    Note that `collection classes` (e.g. `Model`, `ControlParameters`,\n    `InputSequences` are placed on top of the respective section and the\n    `contained classes` (e.g. model methods, `ControlParameter` instances,\n    `InputSequence` instances at the bottom.  This differs from the order\n    of their definition in the respective modules, but results in a better\n    documentation structure."
  },
  {
    "code": "def edit(self, config={}, events=[], add_events=[], rm_events=[],\n             active=True):\n        data = {'config': config, 'active': active}\n        if events:\n            data['events'] = events\n        if add_events:\n            data['add_events'] = add_events\n        if rm_events:\n            data['remove_events'] = rm_events\n        json = self._json(self._patch(self._api, data=dumps(data)), 200)\n        if json:\n            self._update_(json)\n            return True\n        return False",
    "docstring": "Edit this hook.\n\n        :param dict config: (optional), key-value pairs of settings for this\n            hook\n        :param list events: (optional), which events should this be triggered\n            for\n        :param list add_events: (optional), events to be added to the list of\n           events that this hook triggers for\n        :param list rm_events: (optional), events to be remvoed from the list\n            of events that this hook triggers for\n        :param bool active: (optional), should this event be active\n        :returns: bool"
  },
  {
    "code": "def _get_description(arg):\n    desc = []\n    otherwise = False\n    if arg.can_be_inferred:\n        desc.append('If left unspecified, it will be inferred automatically.')\n        otherwise = True\n    elif arg.is_flag:\n        desc.append('This argument defaults to '\n                    '<code>None</code> and can be omitted.')\n        otherwise = True\n    if arg.type in {'InputPeer', 'InputUser', 'InputChannel',\n                    'InputNotifyPeer', 'InputDialogPeer'}:\n        desc.append(\n            'Anything entity-like will work if the library can find its '\n            '<code>Input</code> version (e.g., usernames, <code>Peer</code>, '\n            '<code>User</code> or <code>Channel</code> objects, etc.).'\n        )\n    if arg.is_vector:\n        if arg.is_generic:\n            desc.append('A list of other Requests must be supplied.')\n        else:\n            desc.append('A list must be supplied.')\n    elif arg.is_generic:\n        desc.append('A different Request must be supplied for this argument.')\n    else:\n        otherwise = False\n    if otherwise:\n        desc.insert(1, 'Otherwise,')\n        desc[-1] = desc[-1][:1].lower() + desc[-1][1:]\n    return ' '.join(desc).replace(\n        'list',\n        '<span class=\"tooltip\" title=\"Any iterable that supports len() '\n        'will work too\">list</span>'\n    )",
    "docstring": "Generates a proper description for the given argument."
  },
  {
    "code": "def _replace_series_name(seriesname, replacements):\n    for pat, replacement in six.iteritems(replacements):\n        if re.match(pat, seriesname, re.IGNORECASE | re.UNICODE):\n            return replacement\n    return seriesname",
    "docstring": "Performs replacement of series name.\n\n    Allow specified replacements of series names in cases where default\n    filenames match the wrong series, e.g. missing year gives wrong answer,\n    or vice versa. This helps the TVDB query get the right match."
  },
  {
    "code": "def add_input_arg(self, inp):\n        self.add_arg(inp._dax_repr())\n        self._add_input(inp)",
    "docstring": "Add an input as an argument"
  },
  {
    "code": "def construct(self, response_args, request, **kwargs):\n        response_args = self.do_pre_construct(response_args, request, **kwargs)\n        response = self.response_cls(**response_args)\n        return self.do_post_construct(response, request, **kwargs)",
    "docstring": "Construct the response\n\n        :param response_args: response arguments\n        :param request: The parsed request, a self.request_cls class instance\n        :param kwargs: Extra keyword arguments\n        :return: An instance of the self.response_cls class"
  },
  {
    "code": "def itermonthdays2(cls, year, month):\n        for day in NepCal.itermonthdates(year, month):\n            if day.month == month:\n                yield (day.day, day.weekday())\n            else:\n                yield (0, day.weekday())",
    "docstring": "Similar to itermonthdays2 but returns tuples of day and weekday."
  },
  {
    "code": "def set_instrumentation_callback(self, callback):\n        self.logger.debug('Setting instrumentation callback: %r', callback)\n        self._instrumentation_callback = callback",
    "docstring": "Assign a method to invoke when a request has completed gathering\n        measurements.\n\n        :param method callback: The method to invoke"
  },
  {
    "code": "def get_activities_by_objective_banks(self, objective_bank_ids):\n        activity_list = []\n        for objective_bank_id in objective_bank_ids:\n            activity_list += list(\n                self.get_activities_by_objective_bank(objective_bank_id))\n        return objects.ActivityList(activity_list)",
    "docstring": "Gets the list of ``Activities`` corresponding to a list of ``ObjectiveBanks``.\n\n        arg:    objective_bank_ids (osid.id.IdList): list of objective\n                bank ``Ids``\n        return: (osid.learning.ActivityList) - list of activities\n        raise:  NullArgument - ``objective_bank_ids`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def avail_images(conn=None, call=None):\n    if call == 'action':\n        raise SaltCloudSystemExit(\n            'The avail_images function must be called with '\n            '-f or --function, or with the --list-images option'\n        )\n    if not conn:\n        conn = get_conn()\n    ret = {}\n    for appliance in conn.list_appliances():\n        ret[appliance['name']] = appliance\n    return ret",
    "docstring": "Return a list of the server appliances that are on the provider"
  },
  {
    "code": "def political_views(self) -> str:\n        views = self._data['political_views']\n        return self.random.choice(views)",
    "docstring": "Get a random political views.\n\n        :return: Political views.\n\n        :Example:\n            Liberal."
  },
  {
    "code": "def is_cdl(filename):\n    if os.path.splitext(filename)[-1] != '.cdl':\n        return False\n    with open(filename, 'rb') as f:\n        data = f.read(32)\n    if data.startswith(b'netcdf') or b'dimensions' in data:\n        return True\n    return False",
    "docstring": "Quick check for .cdl ascii file\n\n    Example:\n        netcdf sample_file {\n        dimensions:\n            name_strlen = 7 ;\n            time = 96 ;\n        variables:\n            float lat ;\n                lat:units = \"degrees_north\" ;\n                lat:standard_name = \"latitude\" ;\n                lat:long_name = \"station latitude\" ;\n        etc...\n\n    :param str filename: Absolute path of file to check\n    :param str data: First chuck of data from file to check"
  },
  {
    "code": "def file_chunks(self, fp):\n        fsize = utils.file_size(fp)\n        offset = 0\n        if hasattr(fp, 'readinto'):\n            while offset < fsize:\n                nb = fp.readinto(self._internal)\n                yield self.buf[:nb]\n                offset += nb\n        else:\n            while offset < fsize:\n                nb = min(self.chunk_size, fsize - offset)\n                yield fp.read(nb)\n                offset += nb",
    "docstring": "Yields chunks of a file.\n\n        Parameters\n        ----------\n        fp : io.RawIOBase\n            The file to break into chunks\n            (must be an open file or have the ``readinto`` method)"
  },
  {
    "code": "def onPollVoted(\n        self,\n        mid=None,\n        poll=None,\n        added_options=None,\n        removed_options=None,\n        author_id=None,\n        thread_id=None,\n        thread_type=None,\n        ts=None,\n        metadata=None,\n        msg=None,\n    ):\n        log.info(\n            \"{} voted in poll {} in {} ({})\".format(\n                author_id, poll, thread_id, thread_type.name\n            )\n        )",
    "docstring": "Called when the client is listening, and somebody votes in a group poll\n\n        :param mid: The action ID\n        :param poll: Poll, that user voted in\n        :param author_id: The ID of the person who voted in the poll\n        :param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`\n        :param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`\n        :param ts: A timestamp of the action\n        :param metadata: Extra metadata about the action\n        :param msg: A full set of the data recieved\n        :type poll: models.Poll\n        :type thread_type: models.ThreadType"
  },
  {
    "code": "def getColorName(c):\n    c = np.array(getColor(c))\n    mdist = 99.0\n    kclosest = \"\"\n    for key in colors.keys():\n        ci = np.array(getColor(key))\n        d = np.linalg.norm(c - ci)\n        if d < mdist:\n            mdist = d\n            kclosest = str(key)\n    return kclosest",
    "docstring": "Find the name of a color.\n\n    .. hint:: |colorpalette| |colorpalette.py|_"
  },
  {
    "code": "def prior_names(self):\n        return list(self.prior_information.groupby(\n                self.prior_information.index).groups.keys())",
    "docstring": "get the prior information names\n\n        Returns\n        -------\n        prior_names : list\n            a list of prior information names"
  },
  {
    "code": "def manifest_history(self, synchronous=True, **kwargs):\n        kwargs = kwargs.copy()\n        kwargs.update(self._server_config.get_client_kwargs())\n        response = client.get(\n            self._org_path('manifest_history', kwargs['data']),\n            **kwargs\n        )\n        return _handle_response(response, self._server_config, synchronous)",
    "docstring": "Obtain manifest history for subscriptions.\n\n        :param synchronous: What should happen if the server returns an HTTP\n            202 (accepted) status code? Wait for the task to complete if\n            ``True``. Immediately return the server's response otherwise.\n        :param kwargs: Arguments to pass to requests.\n        :returns: The server's response, with all JSON decoded.\n        :raises: ``requests.exceptions.HTTPError`` If the server responds with\n            an HTTP 4XX or 5XX message."
  },
  {
    "code": "def _report_profile(self, command, lock_name, elapsed_time, memory):\n        message_raw = str(command) + \"\\t \" + \\\n            str(lock_name) + \"\\t\" + \\\n            str(datetime.timedelta(seconds = round(elapsed_time, 2))) + \"\\t \" + \\\n            str(memory)\n        with open(self.pipeline_profile_file, \"a\") as myfile:\n            myfile.write(message_raw + \"\\n\")",
    "docstring": "Writes a string to self.pipeline_profile_file."
  },
  {
    "code": "def _dict_func(self, func, axis, *args, **kwargs):\n        if \"axis\" not in kwargs:\n            kwargs[\"axis\"] = axis\n        if axis == 0:\n            index = self.columns\n        else:\n            index = self.index\n        func = {idx: func[key] for key in func for idx in index.get_indexer_for([key])}\n        def dict_apply_builder(df, func_dict={}):\n            return pandas.DataFrame(df.apply(func_dict, *args, **kwargs))\n        result_data = self.data.apply_func_to_select_indices_along_full_axis(\n            axis, dict_apply_builder, func, keep_remaining=False\n        )\n        full_result = self._post_process_apply(result_data, axis)\n        return full_result",
    "docstring": "Apply function to certain indices across given axis.\n\n        Args:\n            func: The function to apply.\n            axis: Target axis to apply the function along.\n\n        Returns:\n            A new PandasQueryCompiler."
  },
  {
    "code": "def set_key(self, section, key, value):\n        LOGGER.debug(\"> Saving '{0}' in '{1}' section with value: '{2}' in settings file.\".format(\n            key, section, foundations.strings.to_string(value)))\n        self.__settings.beginGroup(section)\n        self.__settings.setValue(key, QVariant(value))\n        self.__settings.endGroup()",
    "docstring": "Stores given key in settings file.\n\n        :param section: Current section to save the key into.\n        :type section: unicode\n        :param key: Current key to save.\n        :type key: unicode\n        :param value: Current key value to save.\n        :type value: object"
  },
  {
    "code": "def isinstance(self, instance, class_name):\n        if isinstance(instance, BaseNode):\n            klass = self.dynamic_node_classes.get(class_name, None)\n            if klass:\n                return isinstance(instance, klass)\n            return False\n        else:\n            raise TypeError(\"This function can only be used for BaseNode objects\")",
    "docstring": "Check if a BaseNode is an instance of a registered dynamic class"
  },
  {
    "code": "def fetch(self):\n        os.makedirs(os.path.dirname(self.cached_repo), exist_ok=True)\n        if not os.path.exists(self.cached_repo):\n            self._log.warning(\"Index not found, caching %s in %s\", self.repo, self.cached_repo)\n            git.clone(self.remote_url, self.cached_repo, checkout=True)\n        else:\n            self._log.debug(\"Index is cached\")\n            if self._are_local_and_remote_heads_different():\n                self._log.info(\"Cached index is not up to date, pulling %s\", self. repo)\n                git.pull(self.cached_repo, self.remote_url)\n        with open(os.path.join(self.cached_repo, self.INDEX_FILE), encoding=\"utf-8\") as _in:\n            self.contents = json.load(_in)",
    "docstring": "Load from the associated Git repository."
  },
  {
    "code": "def point_on_screen(self, pos):\n        if 0 <= pos[0] < self.width and 0 <= pos[1] < self.height:\n            return True\n        else:\n            return False",
    "docstring": "Is the point still on the screen?\n\n        :param pos: Point\n        :type pos: tuple\n        :return: Is it?\n        :rtype: bool"
  },
  {
    "code": "def echo_heading(text, marker='=', marker_color='blue'):\n    click.secho(marker * 3 + '>', fg=marker_color, nl=False)\n    click.echo(' ' + text)",
    "docstring": "Print a text formatted to look like a heading.\n\n    The output looks like:\n    ===> text\n    with marker='=' right now.\n\n    :param str text: the text to echo\n    :param str marker: the marker to mark the heading\n    :param str marker_color: one of ('black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white')"
  },
  {
    "code": "def wait_for_instance_deletion(self, credentials, name, **kwargs):\n        op_name = wait_for_instance_deletion(\n            credentials, self.project, self.zone, name, **kwargs)\n        return op_name",
    "docstring": "Wait for deletion of instance based on the configuration data.\n\n        TODO: docstring"
  },
  {
    "code": "def _get_bin(self, key):\n        sortedDict = {}\n        for item in self.redis_conn.zscan_iter(key):\n            my_item = ujson.loads(item[0])\n            my_score = -item[1]\n            if my_score not in sortedDict:\n                sortedDict[my_score] = []\n            sortedDict[my_score].append(my_item)\n        return sortedDict",
    "docstring": "Returns a binned dictionary based on redis zscore\n\n        @return: The sorted dict"
  },
  {
    "code": "def hash_answer(self, answer, timestamp):\n        timestamp = str(timestamp)\n        answer = str(answer)\n        hashed = ''\n        for _ in range(ITERATIONS):\n            hashed = salted_hmac(timestamp, answer).hexdigest()\n        return hashed",
    "docstring": "Cryptographically hash the answer with the provided timestamp\n\n        This method allows the widget to securely generate time-sensitive\n        signatures that will both prevent tampering with the answer as well as\n        provide some protection against replay attacks by limiting how long a\n        given signature is valid for. Using this same method, the field can\n        validate the submitted answer against the signature also provided in\n        the form."
  },
  {
    "code": "def _replace_none(self, aDict):\n        for k, v in aDict.items():\n            if v is None:\n                aDict[k] = 'none'",
    "docstring": "Replace all None values in a dict with 'none'"
  },
  {
    "code": "def description(self, value):\n        if not isinstance(value, six.string_types) and value is not None:\n            raise ValueError(\"Pass a string, or None\")\n        self._properties[\"description\"] = value",
    "docstring": "Update description of the zone.\n\n        :type value: str\n        :param value: (Optional) new description\n\n        :raises: ValueError for invalid value types."
  },
  {
    "code": "def add_positional_embedding(x, max_length, name=None, positions=None):\n  with tf.name_scope(\"add_positional_embedding\"):\n    _, length, depth = common_layers.shape_list(x)\n    var = tf.cast(tf.get_variable(name, [max_length, depth]), x.dtype)\n    if positions is None:\n      pad_length = tf.maximum(0, length - max_length)\n      sliced = tf.cond(\n          tf.less(length, max_length),\n          lambda: tf.slice(var, [0, 0], [length, -1]),\n          lambda: tf.pad(var, [[0, pad_length], [0, 0]]))\n      return x + tf.expand_dims(sliced, 0)\n    else:\n      return x + tf.gather(var, tf.to_int32(positions))",
    "docstring": "Adds positional embedding.\n\n  Args:\n    x: Tensor with shape [batch, length, depth].\n    max_length: int representing static maximum size of any dimension.\n    name: str representing name of the embedding tf.Variable.\n    positions: Tensor with shape [batch, length].\n\n  Returns:\n    Tensor of same shape as x."
  },
  {
    "code": "def warn(msg, *args):\n    if not args:\n        sys.stderr.write('WARNING: ' + msg)\n    else:\n        sys.stderr.write('WARNING: ' + msg % args)",
    "docstring": "Print a warning on stderr"
  },
  {
    "code": "def bridge_param(_param, _method, *args, **kwargs):\n    assert callable(_method), \"method %r is not callable\" % (_method, )\n    f = Fiber(debug_depth=1, debug_call=_method)\n    f.add_callback(drop_param, _method, *args, **kwargs)\n    f.add_callback(override_result, _param)\n    return f.succeed()",
    "docstring": "Used as a callback to keep the result from the previous callback\n    and use that instead of the result of the given callback when\n    chaining to the next callback in the fiber."
  },
  {
    "code": "def add_new_vehicle(self, hb):\n        if hb.type == mavutil.mavlink.MAV_TYPE_GCS:\n            return\n        sysid = hb.get_srcSystem()\n        self.vehicle_list.append(sysid)\n        self.vehicle_name_by_sysid[sysid] = self.vehicle_type_string(hb)\n        self.update_vehicle_menu()",
    "docstring": "add a new vehicle"
  },
  {
    "code": "def set(self, value):\n        value = min(self.max, max(self.min, value))\n        self._value = value\n        start_new_thread(self.func, (self.get(),))",
    "docstring": "Set the value of the bar. If the value is out of bound, sets it to an extremum"
  },
  {
    "code": "def cli(yamlfile, inline, format):\n    print(JsonSchemaGenerator(yamlfile, format).serialize(inline=inline))",
    "docstring": "Generate JSON Schema representation of a biolink model"
  },
  {
    "code": "def select_next(self):\n        self.footer.clear_message()\n        old_index = self.selected\n        new_index = self.selected + 1\n        if self.selected + 1 >= len(self.statuses):\n            self.fetch_next()\n            self.left.draw_statuses(self.statuses, self.selected, new_index - 1)\n            self.draw_footer_status()\n        self.selected = new_index\n        self.redraw_after_selection_change(old_index, new_index)",
    "docstring": "Move to the next status in the timeline."
  },
  {
    "code": "def _process_methods(self, req, resp, resource):\n        requested_method = self._get_requested_method(req)\n        if not requested_method:\n            return False\n        if self._cors_config['allow_all_methods']:\n            allowed_methods = self._get_resource_methods(resource)\n            self._set_allowed_methods(resp, allowed_methods)\n            if requested_method in allowed_methods:\n                return True\n        elif requested_method in self._cors_config['allow_methods_list']:\n            resource_methods = self._get_resource_methods(resource)\n            allowed_methods = [\n                method for method in resource_methods\n                if method in self._cors_config['allow_methods_list']\n            ]\n            self._set_allowed_methods(resp, allowed_methods)\n            if requested_method in allowed_methods:\n                return True\n        return False",
    "docstring": "Adds the Access-Control-Allow-Methods header to the response,\n        using the cors settings to determine which methods are allowed."
  },
  {
    "code": "def get_unavailable_brokers(zk, partition_metadata):\n    topic_data = zk.get_topics(partition_metadata.topic)\n    topic = partition_metadata.topic\n    partition = partition_metadata.partition\n    expected_replicas = set(topic_data[topic]['partitions'][str(partition)]['replicas'])\n    available_replicas = set(partition_metadata.replicas)\n    return expected_replicas - available_replicas",
    "docstring": "Returns the set of unavailable brokers from the difference of replica\n    set of given partition to the set of available replicas."
  },
  {
    "code": "def merge_upwards_if_smaller_than(self, small_size, a_or_u):\n        prev_app_size = self.app_size()\n        prev_use_size = self.use_size()\n        small_nodes = self._find_small_nodes(small_size, (), a_or_u)\n        for node, parents in small_nodes:\n            if len(parents) >= 2:\n                tail = parents[-2]._nodes[-1]\n                if tail._isdir is None:\n                    assert tail._app_size is not None, tail\n                    tail._add_size(node.app_size(), node.use_size())\n                    parents[-1]._nodes.remove(node)\n                    assert len(parents[-1]._nodes)\n        assert prev_app_size == self.app_size(), (\n            prev_app_size, self.app_size())\n        assert prev_use_size == self.use_size(), (\n            prev_use_size, self.use_size())",
    "docstring": "After prune_if_smaller_than is run, we may still have excess\n        nodes.\n\n        For example, with a small_size of 609710690:\n\n                     7  /*\n              28815419  /data/*\n                    32  /data/srv/*\n                925746  /data/srv/docker.bak/*\n                    12  /data/srv/docker.bak/shared/*\n             682860348  /data/srv/docker.bak/shared/standalone/*\n\n        This is reduced to:\n\n              31147487  /*\n             682860355  /data/srv/docker.bak/shared/standalone/*\n\n        Run this only when done with the scanning."
  },
  {
    "code": "def task_id(self):\n        if self['task_id']:\n            return self['task_id']\n        if self.extra and 'container_koji_task_id' in self.extra:\n            return self.extra['container_koji_task_id']",
    "docstring": "Hack to return a task ID for a build, including container CG builds.\n\n        We have something for this in Brewweb, but not yet for upstream Koji:\n        https://pagure.io/koji/issue/215"
  },
  {
    "code": "def prettytable(self):\n        table = prettytable.PrettyTable(self.columns)\n        if self.sortby:\n            if self.sortby in self.columns:\n                table.sortby = self.sortby\n            else:\n                msg = \"Column (%s) doesn't exist to sort by\" % self.sortby\n                raise exceptions.CLIAbort(msg)\n        for a_col, alignment in self.align.items():\n            table.align[a_col] = alignment\n        if self.title:\n            table.title = self.title\n        for row in self.rows:\n            table.add_row(row)\n        return table",
    "docstring": "Returns a new prettytable instance."
  },
  {
    "code": "def _stream_annotation(file_name, pb_dir):\n    url = posixpath.join(config.db_index_url, pb_dir, file_name)\n    response = requests.get(url)\n    response.raise_for_status()\n    ann_data = np.fromstring(response.content, dtype=np.dtype('<u1'))\n    return ann_data",
    "docstring": "Stream an entire remote annotation file from physiobank\n\n    Parameters\n    ----------\n    file_name : str\n        The name of the annotation file to be read.\n    pb_dir : str\n        The physiobank directory where the annotation file is located."
  },
  {
    "code": "def _verify_field_spec(self, spec, path):\n        if 'required' in spec and not isinstance(spec['required'], bool):\n            raise SchemaFormatException(\"{} required declaration should be True or False\", path)\n        if 'nullable' in spec and not isinstance(spec['nullable'], bool):\n            raise SchemaFormatException(\"{} nullable declaration should be True or False\", path)\n        if 'type' not in spec:\n            raise SchemaFormatException(\"{} has no type declared.\", path)\n        self._verify_type(spec, path)\n        if 'validates' in spec:\n            self._verify_validates(spec, path)\n        if 'default' in spec:\n            self._verify_default(spec, path)\n        if not set(spec.keys()).issubset(set(['type', 'required', 'validates', 'default', 'nullable'])):\n            raise SchemaFormatException(\"Unsupported field spec item at {}. Items: \"+repr(spec.keys()), path)",
    "docstring": "Verifies a given field specification is valid, recursing into nested schemas if required."
  },
  {
    "code": "def stop(self):\n        self.observer_thread.stop()\n        self.observer_thread.join()\n        logging.info(\"Configfile watcher plugin: Stopped\")",
    "docstring": "Stop the config change monitoring thread."
  },
  {
    "code": "def submit_statement_request(meth, end_point, query_str='', data=None,\n                             tries=2, **params):\n    full_end_point = 'statements/' + end_point.lstrip('/')\n    return make_db_rest_request(meth, full_end_point, query_str, data, params, tries)",
    "docstring": "Even lower level function to make the request."
  },
  {
    "code": "def decodeCommandLine(self, cmdline):\n        codec = getattr(sys.stdin, 'encoding', None) or sys.getdefaultencoding()\n        return unicode(cmdline, codec)",
    "docstring": "Turn a byte string from the command line into a unicode string."
  },
  {
    "code": "def _parse_numbered_syllable(unparsed_syllable):\n    tone_number = unparsed_syllable[-1]\n    if not tone_number.isdigit():\n        syllable, tone = unparsed_syllable, '5'\n    elif tone_number == '0':\n        syllable, tone = unparsed_syllable[:-1], '5'\n    elif tone_number in '12345':\n        syllable, tone = unparsed_syllable[:-1], tone_number\n    else:\n        raise ValueError(\"Invalid syllable: %s\" % unparsed_syllable)\n    return syllable, tone",
    "docstring": "Return the syllable and tone of a numbered Pinyin syllable."
  },
  {
    "code": "def robust_mean(log_values):\n    if log_values.shape[1] <= 3:\n        return numpy.nanmean(log_values, axis=1)\n    without_nans = numpy.nan_to_num(log_values)\n    mask = (\n        (~numpy.isnan(log_values)) &\n        (without_nans <= numpy.nanpercentile(log_values, 75, axis=1).reshape((-1, 1))) &\n        (without_nans >= numpy.nanpercentile(log_values, 25, axis=1).reshape((-1, 1))))\n    return (without_nans * mask.astype(float)).sum(1) / mask.sum(1)",
    "docstring": "Mean of values falling within the 25-75 percentiles.\n\n    Parameters\n    ----------\n    log_values : 2-d numpy.array\n        Center is computed along the second axis (i.e. per row).\n\n    Returns\n    -------\n    center : numpy.array of length log_values.shape[1]"
  },
  {
    "code": "def coerce(cls, key, value):\n        self = MutationList((MutationObj.coerce(key, v) for v in value))\n        self._key = key\n        return self",
    "docstring": "Convert plain list to MutationList"
  },
  {
    "code": "def highlightByAlternate(self):\r\n        palette = QtGui.QApplication.palette()\r\n        palette.setColor(palette.HighlightedText, palette.color(palette.Text))\r\n        clr = palette.color(palette.AlternateBase)\r\n        palette.setColor(palette.Highlight, clr.darker(110))\r\n        self.setPalette(palette)",
    "docstring": "Sets the palette highlighting for this tree widget to use a darker\r\n        version of the alternate color vs. the standard highlighting."
  },
  {
    "code": "def to_pandas(self):\n        if not all(ind.is_raw() for ind in self.values):\n            raise ValueError('Cannot convert to pandas MultiIndex if not evaluated.')\n        from pandas import MultiIndex as PandasMultiIndex\n        arrays = [ind.values for ind in self.values]\n        return PandasMultiIndex.from_arrays(arrays, names=self.names)",
    "docstring": "Convert to pandas MultiIndex.\n\n        Returns\n        -------\n        pandas.base.MultiIndex"
  },
  {
    "code": "def flush(self, n=4096):\n        try:\n            read = self.from_stream.read(n)\n            if read is None or len(read) == 0:\n                self.eof = True\n                if self.propagate_close:\n                    self.to_stream.close()\n                return None\n            return self.to_stream.write(read)\n        except OSError as e:\n            if e.errno != errno.EPIPE:\n                raise e",
    "docstring": "Flush `n` bytes of data from the reader Stream to the writer Stream.\n\n        Returns the number of bytes that were actually flushed. A return value\n        of zero is not an error.\n\n        If EOF has been reached, `None` is returned."
  },
  {
    "code": "def get_data(package, resource):\n    loader = get_loader(package)\n    if loader is None or not hasattr(loader, 'get_data'):\n        return None\n    mod = sys.modules.get(package) or loader.load_module(package)\n    if mod is None or not hasattr(mod, '__file__'):\n        return None\n    parts = resource.split('/')\n    parts.insert(0, os.path.dirname(mod.__file__))\n    resource_name = os.path.join(*parts)\n    return loader.get_data(resource_name)",
    "docstring": "Get a resource from a package.\n\n    This is a wrapper round the PEP 302 loader get_data API. The package\n    argument should be the name of a package, in standard module format\n    (foo.bar). The resource argument should be in the form of a relative\n    filename, using '/' as the path separator. The parent directory name '..'\n    is not allowed, and nor is a rooted name (starting with a '/').\n\n    The function returns a binary string, which is the contents of the\n    specified resource.\n\n    For packages located in the filesystem, which have already been imported,\n    this is the rough equivalent of\n\n        d = os.path.dirname(sys.modules[package].__file__)\n        data = open(os.path.join(d, resource), 'rb').read()\n\n    If the package cannot be located or loaded, or it uses a PEP 302 loader\n    which does not support get_data(), then None is returned."
  },
  {
    "code": "def console_type(self, console_type):\n        if console_type != self._console_type:\n            self._manager.port_manager.release_tcp_port(self._console, self._project)\n            if console_type == \"vnc\":\n                self._console = self._manager.port_manager.get_free_tcp_port(self._project, 5900, 6000)\n            else:\n                self._console = self._manager.port_manager.get_free_tcp_port(self._project)\n        self._console_type = console_type\n        log.info(\"{module}: '{name}' [{id}]: console type set to {console_type}\".format(module=self.manager.module_name,\n                                                                                        name=self.name,\n                                                                                        id=self.id,\n                                                                                        console_type=console_type))",
    "docstring": "Sets the console type for this node.\n\n        :param console_type: console type (string)"
  },
  {
    "code": "def get_site_symmetries(wyckoff):\n    ssyms = []\n    for w in wyckoff:\n        ssyms += [\"\\\"%-6s\\\"\" % w_s['site_symmetry'] for w_s in w['wyckoff']]\n    damp_array_site_symmetries(ssyms)",
    "docstring": "List up site symmetries\n\n    The data structure is as follows:\n\n        wyckoff[0]['wyckoff'][0]['site_symmetry']\n\n    Note\n    ----\n    Maximum length of string is 6."
  },
  {
    "code": "def free(self, connection):\n        LOGGER.debug('Pool %s freeing connection %s', self.id, id(connection))\n        try:\n            self.connection_handle(connection).free()\n        except KeyError:\n            raise ConnectionNotFoundError(self.id, id(connection))\n        if self.idle_connections == list(self.connections.values()):\n            with self._lock:\n                self.idle_start = self.time_method()\n        LOGGER.debug('Pool %s freed connection %s', self.id, id(connection))",
    "docstring": "Free the connection from use by the session that was using it.\n\n        :param connection: The connection to free\n        :type connection: psycopg2.extensions.connection\n        :raises: ConnectionNotFoundError"
  },
  {
    "code": "def second_order_diff(arr, x):\n    arr = np.array(arr)\n    dxf = (x[2] - x[0])/2\n    dxb = (x[-1] - x[-3])/2\n    dx = (x[2:] - x[:-2])/2\n    first = (-3*arr[0] + 4*arr[1] - arr[2])/(2*dxf)\n    last = (3*arr[-1] - 4*arr[-2] + arr[-3])/(2*dxb)\n    interior = (arr[2:] - arr[:-2])/(2*dx)\n    darr = np.concatenate(([first], interior, [last]))\n    return darr",
    "docstring": "Compute second order difference of an array.\n\n    A 2nd order forward difference is used for the first point, 2nd order\n    central difference for interior, and 2nd order backward difference for last\n    point, returning an array the same length as the input array."
  },
  {
    "code": "def plot_and_save(self,\n                      data,\n                      w=800,\n                      h=420,\n                      filename='chart',\n                      overwrite=True):\n        self.save(data, filename, overwrite)\n        return IFrame(filename + '.html', w, h)",
    "docstring": "Save the rendered html to a file and returns an IFrame to display the plot in the notebook."
  },
  {
    "code": "def exists(self, table_name, timeout=None):\n        _validate_not_none('table_name', table_name)\n        request = HTTPRequest()\n        request.method = 'GET'\n        request.host = self._get_host()\n        request.path = '/Tables' + \"('\" + table_name + \"')\"\n        request.headers = [('Accept', TablePayloadFormat.JSON_NO_METADATA)]\n        request.query = [('timeout', _int_to_str(timeout))]\n        try:\n            self._perform_request(request)\n            return True\n        except AzureHttpError as ex:\n            _dont_fail_not_exist(ex)\n            return False",
    "docstring": "Returns a boolean indicating whether the table exists.\n\n        :param str table_name:\n            The name of table to check for existence.\n        :param int timeout:\n            The server timeout, expressed in seconds.\n        :return: A boolean indicating whether the table exists.\n        :rtype: bool"
  },
  {
    "code": "def events(self):\n        if self._events is None:\n            self._events = self.parent.calendar.events(\n                calendarId=\"primary\", singleEvents=True, orderBy=\"startTime\",\n                timeMin=self.since, timeMax=self.until)\n        return self._events",
    "docstring": "All events in calendar within specified time range"
  },
  {
    "code": "def set_active_vectors(self, name, preference='cell'):\n        _, field = get_scalar(self, name, preference=preference, info=True)\n        if field == POINT_DATA_FIELD:\n            self.GetPointData().SetActiveVectors(name)\n        elif field == CELL_DATA_FIELD:\n            self.GetCellData().SetActiveVectors(name)\n        else:\n            raise RuntimeError('Data field ({}) not useable'.format(field))\n        self._active_vectors_info = [field, name]",
    "docstring": "Finds the vectors by name and appropriately sets it as active"
  },
  {
    "code": "def double( self ):\n    if self == INFINITY:\n      return INFINITY\n    p = self.__curve.p()\n    a = self.__curve.a()\n    l = ( ( 3 * self.__x * self.__x + a ) * \\\n          numbertheory.inverse_mod( 2 * self.__y, p ) ) % p\n    x3 = ( l * l - 2 * self.__x ) % p\n    y3 = ( l * ( self.__x - x3 ) - self.__y ) % p\n    return Point( self.__curve, x3, y3 )",
    "docstring": "Return a new point that is twice the old."
  },
  {
    "code": "def import_datasources(path, sync, recursive):\n    sync_array = sync.split(',')\n    p = Path(path)\n    files = []\n    if p.is_file():\n        files.append(p)\n    elif p.exists() and not recursive:\n        files.extend(p.glob('*.yaml'))\n        files.extend(p.glob('*.yml'))\n    elif p.exists() and recursive:\n        files.extend(p.rglob('*.yaml'))\n        files.extend(p.rglob('*.yml'))\n    for f in files:\n        logging.info('Importing datasources from file %s', f)\n        try:\n            with f.open() as data_stream:\n                dict_import_export.import_from_dict(\n                    db.session,\n                    yaml.safe_load(data_stream),\n                    sync=sync_array)\n        except Exception as e:\n            logging.error('Error when importing datasources from file %s', f)\n            logging.error(e)",
    "docstring": "Import datasources from YAML"
  },
  {
    "code": "def plot(self, file_type):\n        samples = self.mod_data[file_type]\n        plot_title = file_types[file_type]['title']\n        plot_func = file_types[file_type]['plot_func']\n        plot_params = file_types[file_type]['plot_params']\n        return plot_func(samples,\n                    file_type,\n                    plot_title=plot_title,\n                    plot_params=plot_params)",
    "docstring": "Call file_type plotting function."
  },
  {
    "code": "def stop_dag(self, name=None):\n        return self._client.send(\n            Request(\n                action='stop_dag',\n                payload={'name': name if name is not None else self._dag_name}\n            )\n        ).success",
    "docstring": "Send a stop signal to the specified dag or the dag that hosts this task.\n\n        Args:\n            name str: The name of the dag that should be stopped. If no name is given the\n                      dag that hosts this task is stopped.\n\n        Upon receiving the stop signal, the dag will not queue any new tasks and wait\n        for running tasks to terminate.\n\n        Returns:\n            bool: True if the signal was sent successfully."
  },
  {
    "code": "def getReadAlignmentId(self, gaAlignment):\n        compoundId = datamodel.ReadAlignmentCompoundId(\n            self.getCompoundId(), gaAlignment.fragment_name)\n        return str(compoundId)",
    "docstring": "Returns a string ID suitable for use in the specified GA\n        ReadAlignment object in this ReadGroupSet."
  },
  {
    "code": "def make_router():\n    global router\n    routings = [\n        ('GET', '^/$', index),\n        ('GET', '^/api/?$', index),\n        ('POST', '^/api/1/calculate/?$', calculate.api1_calculate),\n        ('GET', '^/api/2/entities/?$', entities.api2_entities),\n        ('GET', '^/api/1/field/?$', field.api1_field),\n        ('GET', '^/api/1/formula/(?P<name>[^/]+)/?$', formula.api1_formula),\n        ('GET', '^/api/2/formula/(?:(?P<period>[A-Za-z0-9:-]*)/)?(?P<names>[A-Za-z0-9_+-]+)/?$', formula.api2_formula),\n        ('GET', '^/api/1/parameters/?$', parameters.api1_parameters),\n        ('GET', '^/api/1/reforms/?$', reforms.api1_reforms),\n        ('POST', '^/api/1/simulate/?$', simulate.api1_simulate),\n        ('GET', '^/api/1/swagger$', swagger.api1_swagger),\n        ('GET', '^/api/1/variables/?$', variables.api1_variables),\n        ]\n    router = urls.make_router(*routings)\n    return router",
    "docstring": "Return a WSGI application that searches requests to controllers"
  },
  {
    "code": "def aggregate_gradients_using_copy_with_device_selection(\n        tower_grads, avail_devices, use_mean=True, check_inf_nan=False):\n    agg_grads = []\n    has_nan_or_inf_list = []\n    for i, single_grads in enumerate(zip(*tower_grads)):\n        with tf.device(avail_devices[i % len(avail_devices)]):\n            grad_and_var, has_nan_or_inf = aggregate_single_gradient(\n                single_grads, use_mean, check_inf_nan)\n            agg_grads.append(grad_and_var)\n            has_nan_or_inf_list.append(has_nan_or_inf)\n    return agg_grads",
    "docstring": "Aggregate gradients, controlling device for the aggregation.\n\n  Args:\n    tower_grads: List of lists of (gradient, variable) tuples. The outer list\n      is over towers. The inner list is over individual gradients.\n    use_mean: if True, mean is taken, else sum of gradients is taken.\n    check_inf_nan: If true, check grads for nans and infs.\n\n  Returns:\n    The tuple ([(average_gradient, variable),], has_nan_or_inf) where the\n      gradient has been averaged across all towers. The variable is chosen from\n      the first tower. The has_nan_or_inf indicates the grads has nan or inf."
  },
  {
    "code": "def set_dtreat_interp_indch(self, indch=None):\n        lC = [indch is None, type(indch) in [np.ndarray,list], type(indch) is dict]\n        assert any(lC)\n        if lC[2]:\n            lc = [type(k) is int and k<self._ddataRef['nt'] for k in indch.keys()]\n            assert all(lc)\n            for k in indch.keys():\n                assert hasattr(indch[k],'__iter__')\n                indch[k] = _format_ind(indch[k], n=self._ddataRef['nch'])\n        elif lC[1]:\n            indch = np.asarray(indch)\n            assert indch.ndim==1\n            indch = _format_ind(indch, n=self._ddataRef['nch'])\n        self._dtreat['interp-indch'] = indch\n        self._ddata['uptodate'] = False",
    "docstring": "Set the indices of the channels for which to interpolate data\n\n        The index can be provided as:\n            - A 1d np.ndarray of boolean or int indices of channels\n                => interpolate data at these channels for all times\n            - A dict with:\n                * keys = int indices of times\n                * values = array of int indices of chan. for which to interpolate\n\n        Time indices refer to self.ddataRef['t']\n        Channel indices refer to self.ddataRef['X']"
  },
  {
    "code": "def delete_authoring_nodes(self, editor):\n        editor_node = foundations.common.get_first_item(self.get_editor_nodes(editor))\n        file_node = editor_node.parent\n        self.unregister_editor(editor_node)\n        self.unregister_file(file_node, raise_exception=False)\n        return True",
    "docstring": "Deletes the Model authoring Nodes associated with given editor.\n\n        :param editor: Editor.\n        :type editor: Editor\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def pop(self):\n        if self._count == 0:\n            raise StreamEmptyError(\"Pop called on buffered stream walker without any data\", selector=self.selector)\n        while True:\n            curr = self.engine.get(self.storage_type, self.offset)\n            self.offset += 1\n            stream = DataStream.FromEncoded(curr.stream)\n            if self.matches(stream):\n                self._count -= 1\n                return curr",
    "docstring": "Pop a reading off of this stream and return it."
  },
  {
    "code": "def compute_covariance(L_aug, Y, k, p):\n    n, d = L_aug.shape\n    assert Y.shape[0] == n\n    mu = compute_mu(L_aug, Y, k, p)\n    return (L_aug.T @ L_aug) / n - mu @ np.diag(p) @ mu.T",
    "docstring": "Given label matrix L_aug and labels Y, compute the covariance.\n\n    Args:\n        L: (np.array {0,1}) [n, d] The augmented (indicator) label matrix\n        Y: (np.array int) [n] The true labels in {1,...,k}\n        k: (int) Cardinality\n        p: (np.array float) [k] The class balance"
  },
  {
    "code": "def compress(bytes, target):\n        length = len(bytes)\n        if target > length:\n            raise ValueError(\"Fewer input bytes than requested output\")\n        seg_size = length // target\n        segments = [bytes[i * seg_size:(i + 1) * seg_size]\n                    for i in range(target)]\n        segments[-1].extend(bytes[target * seg_size:])\n        checksum = lambda bytes: reduce(operator.xor, bytes, 0)\n        checksums = list(map(checksum, segments))\n        return checksums",
    "docstring": "Compress a list of byte values to a fixed target length.\n\n            >>> bytes = [96, 173, 141, 13, 135, 27, 96, 149, 128, 130, 151]\n            >>> HumanHasher.compress(bytes, 4)\n            [205, 128, 156, 96]\n\n        Attempting to compress a smaller number of bytes to a larger number is\n        an error:\n\n            >>> HumanHasher.compress(bytes, 15)  # doctest: +ELLIPSIS\n            Traceback (most recent call last):\n            ...\n            ValueError: Fewer input bytes than requested output"
  },
  {
    "code": "def glsl_type(self):\n        if self.dtype is None:\n            return None\n        dtshape = self.dtype[0].shape\n        n = dtshape[0] if dtshape else 1\n        if n > 1:\n            dtype = 'vec%d' % n\n        else:\n            dtype = 'float' if 'f' in self.dtype[0].base.kind else 'int'\n        return 'attribute', dtype",
    "docstring": "GLSL declaration strings required for a variable to hold this data."
  },
  {
    "code": "def bed(args):\n    p = OptionParser(bed.__doc__)\n    p.add_option(\"--switch\", default=False, action=\"store_true\",\n                 help=\"Switch reference and aligned map elements [default: %default]\")\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(not p.print_help())\n    mapout, = args\n    pf = mapout.split(\".\")[0]\n    mapbed = pf + \".bed\"\n    bm = BinMap(mapout)\n    bm.print_to_bed(mapbed, switch=opts.switch)\n    return mapbed",
    "docstring": "%prog fasta map.out\n\n    Convert MSTMAP output into bed format."
  },
  {
    "code": "def download(url, file_handle, chunk_size=1024):\n    r = requests.get(url, stream=True)\n    total_length = r.headers.get('content-length')\n    if total_length is None:\n        maxval = UnknownLength\n    else:\n        maxval = int(total_length)\n    name = file_handle.name\n    with progress_bar(name=name, maxval=maxval) as bar:\n        for i, chunk in enumerate(r.iter_content(chunk_size)):\n            if total_length:\n                bar.update(i * chunk_size)\n            file_handle.write(chunk)",
    "docstring": "Downloads a given URL to a specific file.\n\n    Parameters\n    ----------\n    url : str\n        URL to download.\n    file_handle : file\n        Where to save the downloaded URL."
  },
  {
    "code": "def expand(self, expression):\n        self.logger.debug(\"expand : expression %s\", str(expression))\n        if not is_string(expression):\n            return expression\n        result = self._pattern.sub(lambda var: str(self._variables[var.group(1)]), expression)\n        result = result.strip()\n        self.logger.debug('expand : %s - result : %s', expression, result)\n        if is_number(result):\n            if result.isdigit():\n                self.logger.debug('     expand is integer !!!')\n                return int(result)\n            else:\n                self.logger.debug('     expand is float !!!')\n                return float(result)\n        return result",
    "docstring": "Expands logical constructions."
  },
  {
    "code": "def _next_lowest_integer(group_keys):\n    try:\n        largest_int= max([ int(val) for val in group_keys if _is_int(val)])\n    except:\n        largest_int= 0\n    return largest_int + 1",
    "docstring": "returns the lowest available integer in a set of dict keys"
  },
  {
    "code": "def step(self)->Number:\n        \"Return next value along annealed schedule.\"\n        self.n += 1\n        return self.func(self.start, self.end, self.n/self.n_iter)",
    "docstring": "Return next value along annealed schedule."
  },
  {
    "code": "def string_tag(name, value):\n    return name.encode('utf-8') + \\\n        len(value).to_bytes(4, byteorder='big') + \\\n        value.encode('utf-8')",
    "docstring": "Create a DMAP tag with string data."
  },
  {
    "code": "def usermacro_delete(macroids, **kwargs):\n    conn_args = _login(**kwargs)\n    ret = {}\n    try:\n        if conn_args:\n            method = 'usermacro.delete'\n            if isinstance(macroids, list):\n                params = macroids\n            else:\n                params = [macroids]\n            ret = _query(method, params, conn_args['url'], conn_args['auth'])\n            return ret['result']['hostmacroids']\n        else:\n            raise KeyError\n    except KeyError:\n        return ret",
    "docstring": "Delete host usermacros.\n\n    :param macroids: macroids of the host usermacros\n\n    :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n    :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n    :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n    return: IDs of the deleted host usermacro.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' zabbix.usermacro_delete 21"
  },
  {
    "code": "def apicalCheck(self, apicalInput):\n    (activeApicalSegments, matchingApicalSegments,\n     apicalPotentialOverlaps) = self._calculateSegmentActivity(\n       self.apicalConnections, apicalInput, self.connectedPermanence,\n       self.activationThreshold, self.minThreshold, self.reducedBasalThreshold)\n    apicallySupportedCells = self.apicalConnections.mapSegmentsToCells(\n      activeApicalSegments)\n    predictedCells = np.intersect1d(\n      self.basalConnections.mapSegmentsToCells(self.activeBasalSegments),\n      apicallySupportedCells)\n    return predictedCells",
    "docstring": "Return 'recent' apically predicted cells for each tick  of apical timer\n    - finds active apical segments corresponding to predicted basal segment,\n\n    @param apicalInput (numpy array)\n    List of active input bits for the apical dendrite segments"
  },
  {
    "code": "def get_contrib_names(self, contrib):\n        collab = contrib.find('collab')\n        anon = contrib.find('anonymous')\n        if collab is not None:\n            proper_name = serialize(collab, strip=True)\n            file_as_name = proper_name\n        elif anon is not None:\n            proper_name = 'Anonymous'\n            file_as_name = proper_name\n        else:\n            name = contrib.find('name')\n            surname = name.find('surname').text\n            given = name.find('given-names')\n            if given is not None:\n                if given.text:\n                    proper_name = ' '.join([surname, given.text])\n                    file_as_name = ', '.join([surname, given.text[0]])\n                else:\n                    proper_name = surname\n                    file_as_name = proper_name\n            else:\n                proper_name = surname\n                file_as_name = proper_name\n        return proper_name, file_as_name",
    "docstring": "Returns an appropriate Name and File-As-Name for a contrib element.\n\n        This code was refactored out of nav_contributors and\n        package_contributors to provide a single definition point for a common\n        job. This is a useful utility that may be well-employed for other\n        publishers as well."
  },
  {
    "code": "def __schema_descriptor(self, services):\n    methods_desc = {}\n    for service in services:\n      protorpc_methods = service.all_remote_methods()\n      for protorpc_method_name in protorpc_methods.iterkeys():\n        rosy_method = '%s.%s' % (service.__name__, protorpc_method_name)\n        method_id = self.__id_from_name[rosy_method]\n        request_response = {}\n        request_schema_id = self.__request_schema.get(method_id)\n        if request_schema_id:\n          request_response['request'] = {\n              '$ref': request_schema_id\n              }\n        response_schema_id = self.__response_schema.get(method_id)\n        if response_schema_id:\n          request_response['response'] = {\n              '$ref': response_schema_id\n              }\n        methods_desc[rosy_method] = request_response\n    descriptor = {\n        'methods': methods_desc,\n        'schemas': self.__parser.schemas(),\n        }\n    return descriptor",
    "docstring": "Descriptor for the all the JSON Schema used.\n\n    Args:\n      services: List of protorpc.remote.Service instances implementing an\n        api/version.\n\n    Returns:\n      Dictionary containing all the JSON Schema used in the service."
  },
  {
    "code": "def cleanup(graph, subgraphs):\n    for subgraph in subgraphs.values():\n        update_node_helper(graph, subgraph)\n        update_metadata(graph, subgraph)",
    "docstring": "Clean up the metadata in the subgraphs.\n\n    :type graph: pybel.BELGraph\n    :type subgraphs: dict[Any,pybel.BELGraph]"
  },
  {
    "code": "def _check_patch_type_mismatch(self, patched_item, existing_item):\n        def raise_mismatch_error(patched_item, existing_item, data_type_name):\n            error_msg = ('Type mismatch. Patch {} corresponds to pre-existing '\n                'data_type {} ({}:{}) that has type other than {}.')\n            raise InvalidSpec(error_msg.format(\n                quote(patched_item.name),\n                quote(existing_item.name),\n                existing_item.path,\n                existing_item.lineno,\n                quote(data_type_name)), patched_item.lineno, patched_item.path)\n        if isinstance(patched_item, AstStructPatch):\n            if not isinstance(existing_item, AstStructDef):\n                raise_mismatch_error(patched_item, existing_item, 'struct')\n        elif isinstance(patched_item, AstUnionPatch):\n            if not isinstance(existing_item, AstUnionDef):\n                raise_mismatch_error(patched_item, existing_item, 'union')\n            else:\n                if existing_item.closed != patched_item.closed:\n                    raise_mismatch_error(\n                        patched_item, existing_item,\n                        'union_closed' if existing_item.closed else 'union')\n        else:\n            raise AssertionError(\n                'Unknown Patch Object Type {}'.format(patched_item.__class__.__name__))",
    "docstring": "Enforces that each patch has a corresponding, already-defined data type."
  },
  {
    "code": "def get_json(self, path, **kwargs):\n        url = self._make_url(path)\n        headers = kwargs.setdefault('headers', {})\n        headers.update({'Accept': 'application/json'})\n        response = self._make_request(\"GET\", url, **kwargs)\n        return json.loads(response.text)",
    "docstring": "Perform an HTTP GET request with JSON headers of the specified path against Device Cloud\n\n        Make an HTTP GET request against Device Cloud with this accounts\n        credentials and base url.  This method uses the\n        `requests <http://docs.python-requests.org/en/latest/>`_ library\n        `request method <http://docs.python-requests.org/en/latest/api/#requests.request>`_\n        and all keyword arguments will be passed on to that method.\n\n        This method will automatically add the ``Accept: application/json`` and parse the\n        JSON response from Device Cloud.\n\n        :param str path: Device Cloud path to GET\n        :param int retries: The number of times the request should be retried if an\n            unsuccessful response is received.  Most likely, you should leave this at 0.\n        :raises DeviceCloudHttpException: if a non-success response to the request is received\n            from Device Cloud\n        :returns: A python data structure containing the results of calling ``json.loads`` on the\n            body of the response from Device Cloud."
  },
  {
    "code": "def predict_variant_effects(variant, raise_on_error=False):\n    if len(variant.gene_ids) == 0:\n        effects = [Intergenic(variant)]\n    else:\n        effects = []\n        transcripts_grouped_by_gene = groupby_field(variant.transcripts, 'gene_id')\n        for gene_id in sorted(variant.gene_ids):\n            if gene_id not in transcripts_grouped_by_gene:\n                gene = variant.ensembl.gene_by_id(gene_id)\n                effects.append(Intragenic(variant, gene))\n            else:\n                for transcript in transcripts_grouped_by_gene[gene_id]:\n                    if raise_on_error:\n                        effect = predict_variant_effect_on_transcript(\n                            variant=variant,\n                            transcript=transcript)\n                    else:\n                        effect = predict_variant_effect_on_transcript_or_failure(\n                            variant=variant,\n                            transcript=transcript)\n                    effects.append(effect)\n    return EffectCollection(effects)",
    "docstring": "Determine the effects of a variant on any transcripts it overlaps.\n    Returns an EffectCollection object.\n\n    Parameters\n    ----------\n    variant : Variant\n\n    raise_on_error : bool\n        Raise an exception if we encounter an error while trying to\n        determine the effect of this variant on a transcript, or simply\n        log the error and continue."
  },
  {
    "code": "def _input_file_as_html_links(cls, session: AppSession):\n        scrape_result = session.factory['HTMLScraper'].scrape_file(\n            session.args.input_file,\n            encoding=session.args.local_encoding or 'utf-8'\n        )\n        for context in scrape_result.link_contexts:\n            yield context.link",
    "docstring": "Read input file as HTML and return the links."
  },
  {
    "code": "def _after_request(self, response):\n        cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and\n                         current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE',\n                                                True))\n        if getattr(g, 'oidc_id_token_dirty', False):\n            if g.oidc_id_token:\n                signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token)\n                response.set_cookie(\n                    current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'],\n                    signed_id_token,\n                    secure=cookie_secure,\n                    httponly=True,\n                    max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL'])\n            else:\n                response.set_cookie(\n                    current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'],\n                    '',\n                    path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'],\n                    secure=cookie_secure,\n                    httponly=True,\n                    expires=0)\n        return response",
    "docstring": "Set a new ID token cookie if the ID token has changed."
  },
  {
    "code": "def find_protein_complexes(model):\n    complexes = []\n    for rxn in model.reactions:\n        if not rxn.gene_reaction_rule:\n            continue\n        size = find_top_level_complex(rxn.gene_reaction_rule)\n        if size >= 2:\n            complexes.append(rxn)\n    return complexes",
    "docstring": "Find reactions that are catalyzed by at least a heterodimer.\n\n    Parameters\n    ----------\n    model : cobra.Model\n        The metabolic model under investigation.\n\n    Returns\n    -------\n    list\n        Reactions whose gene-protein-reaction association contains at least one\n        logical AND combining different gene products (heterodimer)."
  },
  {
    "code": "def power_in_band(events, dat, s_freq, frequency):\n    dat = diff(dat)\n    pw = empty(events.shape[0])\n    pw.fill(nan)\n    for i, one_event in enumerate(events):\n        x0 = one_event[0]\n        x1 = one_event[2]\n        if x0 < 0 or x1 >= len(dat):\n            pw[i] = nan\n        else:\n            sf, Pxx = periodogram(dat[x0:x1], s_freq)\n            b0 = asarray([abs(x - frequency[0]) for x in sf]).argmin()\n            b1 = asarray([abs(x - frequency[1]) for x in sf]).argmin()\n            pw[i] = mean(Pxx[b0:b1])\n    return pw",
    "docstring": "Define power of the signal within frequency band.\n\n    Parameters\n    ----------\n    events : ndarray (dtype='int')\n        N x 3 matrix with start, peak, end samples\n    dat : ndarray (dtype='float')\n        vector with the original data\n    s_freq : float\n        sampling frequency\n    frequency : tuple of float\n        low and high frequency of spindle band, for window\n\n    Returns\n    -------\n    ndarray (dtype='float')\n        vector with power"
  },
  {
    "code": "def transfer_and_wait(\n            self,\n            registry_address: PaymentNetworkID,\n            token_address: TokenAddress,\n            amount: TokenAmount,\n            target: Address,\n            identifier: PaymentID = None,\n            transfer_timeout: int = None,\n            secret: Secret = None,\n            secret_hash: SecretHash = None,\n    ):\n        payment_status = self.transfer_async(\n            registry_address=registry_address,\n            token_address=token_address,\n            amount=amount,\n            target=target,\n            identifier=identifier,\n            secret=secret,\n            secret_hash=secret_hash,\n        )\n        payment_status.payment_done.wait(timeout=transfer_timeout)\n        return payment_status",
    "docstring": "Do a transfer with `target` with the given `amount` of `token_address`."
  },
  {
    "code": "def context_lookup(self, vars):\n        while isinstance(vars, IscmExpr):\n            vars = vars.resolve(self.context)\n        for (k,v) in vars.items():\n            if isinstance(v, IscmExpr):\n                vars[k] = v.resolve(self.context)\n        return vars",
    "docstring": "Lookup the variables in the provided dictionary, resolve with entries\n        in the context"
  },
  {
    "code": "def choose_best_amplicon(self, amplicon_tuples):\n        quality = 0\n        amplicon_length = 0\n        best_amplicon = None\n        for amplicon in amplicon_tuples:\n            if int(amplicon[4]) >= quality and int(amplicon[5]) >= amplicon_length:\n                quality = int(amplicon[4])\n                amplicon_length = int(amplicon[5])\n                best_amplicon = amplicon\n        return best_amplicon",
    "docstring": "Iterates over amplicon tuples and returns the one with highest quality\n        and amplicon length."
  },
  {
    "code": "def _merge_with_defaults(params):\n    marks_params = [\n        tz.merge(default, param) for default, param in\n        zip(itertools.repeat(_default_params['marks']), params['marks'])\n    ] if 'marks' in params else [_default_params['marks']]\n    merged_without_marks = tz.merge_with(\n        tz.merge, tz.dissoc(_default_params, 'marks'),\n        tz.dissoc(params, 'marks')\n    )\n    return tz.merge(merged_without_marks, {'marks': marks_params})",
    "docstring": "Performs a 2-level deep merge of params with _default_params with corrent\n    merging of params for each mark.\n\n    This is a bit complicated since params['marks'] is a list and we need to\n    make sure each mark gets the default params."
  },
  {
    "code": "def client(self, container):\n        self._client_chk.check(container)\n        return ContainerClient(self._client, int(container))",
    "docstring": "Return a client instance that is bound to that container.\n\n        :param container: container id\n        :return: Client object bound to the specified container id\n        Return a ContainerResponse from container.create"
  },
  {
    "code": "def setKey(self, key, value):\n\t\tdata = self.getDictionary()\n\t\tdata[key] = value\n\t\tself.setDictionary(data)",
    "docstring": "Sets the value for the specified dictionary key"
  },
  {
    "code": "def add(self, term):\n        if isinstance(term, Conjunction):\n            for term_ in term.terms:\n                self.add(term_)\n        elif isinstance(term, Term):\n            self._terms.append(term)\n        else:\n            raise TypeError('Not a Term or Conjunction')",
    "docstring": "Add a term to the conjunction.\n\n        Args:\n            term (:class:`Term`, :class:`Conjunction`): term to add;\n                if a :class:`Conjunction`, all of its terms are added\n                to the current conjunction.\n        Raises:\n            :class:`TypeError`: when *term* is an invalid type"
  },
  {
    "code": "def seebeck_spb(eta,Lambda=0.5):\n    from fdint import fdk\n    return constants.k/constants.e * ((2. + Lambda) * fdk( 1.+ Lambda, eta)/ \n                 ((1.+Lambda)*fdk(Lambda, eta))- eta) * 1e+6",
    "docstring": "Seebeck analytic formula in the single parabolic model"
  },
  {
    "code": "def spaced_indexes(len_, n, trunc=False):\n    if n is None:\n        return np.arange(len_)\n    all_indexes = np.arange(len_)\n    if trunc:\n        n = min(len_, n)\n    if n == 0:\n        return np.empty(0)\n    stride = len_ // n\n    try:\n        indexes = all_indexes[0:-1:stride]\n    except ValueError:\n        raise ValueError('cannot slice list of len_=%r into n=%r parts' % (len_, n))\n    return indexes",
    "docstring": "Returns n evenly spaced indexes.\n    Returns as many as possible if trunc is true"
  },
  {
    "code": "def umount(mountpoint, persist=False):\n    cmd_args = ['umount', mountpoint]\n    try:\n        subprocess.check_output(cmd_args)\n    except subprocess.CalledProcessError as e:\n        log('Error unmounting {}\\n{}'.format(mountpoint, e.output))\n        return False\n    if persist:\n        return fstab_remove(mountpoint)\n    return True",
    "docstring": "Unmount a filesystem"
  },
  {
    "code": "def end_script(self):\n        if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.WAITING):\n            return [1]\n        self.remote_bridge.status = BRIDGE_STATUS.RECEIVED\n        return [0]",
    "docstring": "Indicate that we have finished receiving a script."
  },
  {
    "code": "async def wait(self):\n        if self._ping_task is None:\n            raise RuntimeError('Response is not started')\n        with contextlib.suppress(asyncio.CancelledError):\n            await self._ping_task",
    "docstring": "EventSourceResponse object is used for streaming data to the client,\n        this method returns future, so we can wain until connection will\n        be closed or other task explicitly call ``stop_streaming`` method."
  },
  {
    "code": "def parse_cstring(stream, offset):\n    stream.seek(offset)\n    string = \"\"\n    while True:\n        char = struct.unpack('c', stream.read(1))[0]\n        if char == b'\\x00':\n            return string\n        else:\n            string += char.decode()",
    "docstring": "parse_cstring will parse a null-terminated string in a bytestream.\n\n        The string will be decoded with UTF-8 decoder, of course since we are\n        doing this byte-a-byte, it won't really work for all Unicode strings.\n\n        TODO: add proper Unicode support"
  },
  {
    "code": "def reqContractDetails(self, contract: Contract) -> List[ContractDetails]:\n        return self._run(self.reqContractDetailsAsync(contract))",
    "docstring": "Get a list of contract details that match the given contract.\n        If the returned list is empty then the contract is not known;\n        If the list has multiple values then the contract is ambiguous.\n\n        The fully qualified contract is available in the the\n        ContractDetails.contract attribute.\n\n        This method is blocking.\n\n        https://interactivebrokers.github.io/tws-api/contract_details.html\n\n        Args:\n            contract: The contract to get details for."
  },
  {
    "code": "def ssh_authorized_key_exists(public_key, application_name, user=None):\n    with open(authorized_keys(application_name, user)) as keys:\n        return ('%s' % public_key) in keys.read()",
    "docstring": "Check if given key is in the authorized_key file.\n\n    :param public_key: Public key.\n    :type public_key: str\n    :param application_name: Name of application eg nova-compute-something\n    :type application_name: str\n    :param user: The user that the ssh asserts are for.\n    :type user: str\n    :returns: Whether given key is in the authorized_key file.\n    :rtype: boolean"
  },
  {
    "code": "def __generate_tree(self, top, src, resources, models, ctrls, views, utils):\n        res = self.__mkdir(top)\n        for fn in (src, models, ctrls, views, utils): res = self.__mkpkg(fn) or res\n        res = self.__mkdir(resources) or res\n        res = self.__mkdir(os.path.join(resources, \"ui\", \"builder\")) or res\n        res = self.__mkdir(os.path.join(resources, \"ui\", \"styles\")) or res\n        res = self.__mkdir(os.path.join(resources, \"external\")) or res\n        return res",
    "docstring": "Creates directories and packages"
  },
  {
    "code": "def get_pwm(self, led_num):\n        self.__check_range('led_number', led_num)\n        register_low = self.calc_led_register(led_num)\n        return self.__get_led_value(register_low)",
    "docstring": "Generic getter for all LED PWM value"
  },
  {
    "code": "def custom_property_prefix_strict(instance):\n    for prop_name in instance.keys():\n        if (instance['type'] in enums.PROPERTIES and\n                prop_name not in enums.PROPERTIES[instance['type']] and\n                prop_name not in enums.RESERVED_PROPERTIES and\n                not CUSTOM_PROPERTY_PREFIX_RE.match(prop_name)):\n            yield JSONError(\"Custom property '%s' should have a type that \"\n                            \"starts with 'x_' followed by a source unique \"\n                            \"identifier (like a domain name with dots \"\n                            \"replaced by hyphen), a hyphen and then the name.\"\n                            % prop_name, instance['id'],\n                            'custom-prefix')",
    "docstring": "Ensure custom properties follow strict naming style conventions.\n\n    Does not check property names in custom objects."
  },
  {
    "code": "def process_user_info_response(self, response):\n        mapping = (\n            ('username', 'preferred_username'),\n            ('email', 'email'),\n            ('last_name', 'family_name'),\n            ('first_name', 'given_name'),\n        )\n        return {dest: response[source] for dest, source in mapping}",
    "docstring": "Process the user info response data.\n\n        By default, this simply maps the edX user info key-values (example below) to Django-friendly names. If your\n        provider returns different fields, you should sub-class this class and override this method.\n\n        .. code-block:: python\n\n            {\n                \"username\": \"jdoe\",\n                \"email\": \"jdoe@example.com\",\n                \"first_name\": \"Jane\",\n                \"last_name\": \"Doe\"\n            }\n\n        Arguments:\n            response (dict): User info data\n\n        Returns:\n            dict"
  },
  {
    "code": "def _read_json_db(self):\n        try:\n            metadata_str = self.db_io.read_metadata_from_uri(\n                self.layer_uri, 'json')\n        except HashNotFoundError:\n            return {}\n        try:\n            metadata = json.loads(metadata_str)\n            return metadata\n        except ValueError:\n            message = tr('the file DB entry for %s does not appear to be '\n                         'valid JSON')\n            message %= self.layer_uri\n            raise MetadataReadError(message)",
    "docstring": "read metadata from a json string stored in a DB.\n\n        :return: the parsed json dict\n        :rtype: dict"
  },
  {
    "code": "def changelog_file_option_validator(ctx, param, value):\n    path = Path(value)\n    if not path.exists():\n        filename = click.style(path.name, fg=\"blue\", bold=True)\n        ctx.fail(\n            \"\\n\"\n            f\" {x_mark} Unable to find {filename}\\n\"\n            '   Run \"$ brau init\" to create one'\n        )\n    return path",
    "docstring": "Checks that the given file path exists in the current working directory.\n\n    Returns a :class:`~pathlib.Path` object. If the file does not exist raises\n    a :class:`~click.UsageError` exception."
  },
  {
    "code": "def GET_namespace_num_names(self, path_info, namespace_id):\n        if not check_namespace(namespace_id):\n            return self._reply_json({'error': 'Invalid namespace'}, status_code=400)\n        blockstackd_url = get_blockstackd_url()\n        name_count = blockstackd_client.get_num_names_in_namespace(namespace_id, hostport=blockstackd_url)\n        if json_is_error(name_count):\n            log.error(\"Failed to load namespace count for {}: {}\".format(namespace_id, name_count['error']))\n            return self._reply_json({'error': 'Failed to load namespace count: {}'.format(name_count['error'])}, status_code=404)\n        self._reply_json({'names_count': name_count})",
    "docstring": "Get the number of names in a namespace\n        Reply the number on success\n        Reply 404 if the namespace does not exist\n        Reply 502 on failure to talk to the blockstack server"
  },
  {
    "code": "def logtrick_sgd(sgd):\n    r\n    @wraps(sgd)\n    def new_sgd(fun, x0, data, bounds=None, eval_obj=False, **sgd_kwargs):\n        if bounds is None:\n            return sgd(fun, x0, data, bounds=bounds, eval_obj=eval_obj,\n                       **sgd_kwargs)\n        logx, expx, gradx, bounds = _logtrick_gen(bounds)\n        if bool(eval_obj):\n            def new_fun(x, *fargs, **fkwargs):\n                o, g = fun(expx(x), *fargs, **fkwargs)\n                return o, gradx(g, x)\n        else:\n            def new_fun(x, *fargs, **fkwargs):\n                return gradx(fun(expx(x), *fargs, **fkwargs), x)\n        result = sgd(new_fun, logx(x0), data, bounds=bounds, eval_obj=eval_obj,\n                     **sgd_kwargs)\n        result['x'] = expx(result['x'])\n        return result\n    return new_sgd",
    "docstring": "r\"\"\"\n    Log-Trick decorator for stochastic gradients.\n\n    This decorator implements the \"log trick\" for optimizing positive bounded\n    variables using SGD. It will apply this trick for any variables that\n    correspond to a Positive() bound.\n\n    Examples\n    --------\n    >>> from ..optimize import sgd\n    >>> from ..btypes import Bound, Positive\n\n    Here is an example where we may want to enforce a particular parameter or\n    parameters to be strictly greater than zero,\n\n    >>> def cost(w, data, lambda_):\n    ...     N = len(data)\n    ...     y, X = data[:, 0], data[:, 1:]\n    ...     y_est = X.dot(w)\n    ...     ww = w.T.dot(w)\n    ...     obj = (y - y_est).sum() / N + lambda_ * ww\n    ...     gradw = - 2 * X.T.dot(y - y_est) / N + 2 * lambda_ * w\n    ...     return obj, gradw\n\n    Now let's enforce that the `w` are positive,\n\n    >>> bounds = [Positive(), Positive()]\n    >>> new_sgd = logtrick_sgd(sgd)\n\n    Data\n\n    >>> y = np.linspace(1, 10, 100) + np.random.randn(100) + 1\n    >>> X = np.array([np.ones(100), np.linspace(1, 100, 100)]).T\n    >>> data = np.hstack((y[:, np.newaxis], X))\n\n    Initial values\n\n    >>> w_0 = np.array([1., 1.])\n    >>> lambda_0 = .25\n\n    >>> res = new_sgd(cost, w_0, data, args=(lambda_0,), bounds=bounds,\n    ...               batch_size=10, eval_obj=True)\n    >>> res.x >= 0\n    array([ True,  True], dtype=bool)\n\n    Note\n    ----\n    This decorator only works on unstructured optimizers. However, it can be\n    use with structured_minimizer, so long as it is the inner wrapper."
  },
  {
    "code": "def getReffs(self, level: int=1, subreference: CtsReference=None) -> CtsReferenceSet:\n        if not subreference and hasattr(self, \"reference\"):\n            subreference = self.reference\n        elif subreference and not isinstance(subreference, CtsReference):\n            subreference = CtsReference(subreference)\n        return self.getValidReff(level=level, reference=subreference)",
    "docstring": "CtsReference available at a given level\n\n        :param level: Depth required. If not set, should retrieve first encountered level (1 based)\n        :param subreference: Subreference (optional)\n        :returns: List of levels"
  },
  {
    "code": "def spp_call_peaks(\n                self, treatment_bam, control_bam, treatment_name, control_name,\n                output_dir, broad, cpus, qvalue=None):\n        broad = \"TRUE\" if broad else \"FALSE\"\n        cmd = self.tools.Rscript + \" `which spp_peak_calling.R` {0} {1} {2} {3} {4} {5} {6}\".format(\n            treatment_bam, control_bam, treatment_name, control_name, broad, cpus, output_dir\n        )\n        if qvalue is not None:\n            cmd += \" {}\".format(qvalue)\n        return cmd",
    "docstring": "Build command for R script to call peaks with SPP.\n\n        :param str treatment_bam: Path to file with data for treatment sample.\n        :param str control_bam: Path to file with data for control sample.\n        :param str treatment_name: Name for the treatment sample.\n        :param str control_name: Name for the control sample.\n        :param str output_dir: Path to folder for output.\n        :param str | bool broad: Whether to specify broad peak calling mode.\n        :param int cpus: Number of cores the script may use.\n        :param float qvalue: FDR, as decimal value\n        :return str: Command to run."
  },
  {
    "code": "def _assert_no_error(error, exception_class=None):\n    if error == 0:\n        return\n    cf_error_string = Security.SecCopyErrorMessageString(error, None)\n    output = _cf_string_to_unicode(cf_error_string)\n    CoreFoundation.CFRelease(cf_error_string)\n    if output is None or output == u'':\n        output = u'OSStatus %s' % error\n    if exception_class is None:\n        exception_class = ssl.SSLError\n    raise exception_class(output)",
    "docstring": "Checks the return code and throws an exception if there is an error to\n    report"
  },
  {
    "code": "def check_string(sql_string, add_semicolon=False):\n    prepped_sql = sqlprep.prepare_sql(sql_string, add_semicolon=add_semicolon)\n    success, msg = ecpg.check_syntax(prepped_sql)\n    return success, msg",
    "docstring": "Check whether a string is valid PostgreSQL. Returns a boolean\n    indicating validity and a message from ecpg, which will be an\n    empty string if the input was valid, or a description of the\n    problem otherwise."
  },
  {
    "code": "def detect_infinitive_phrase(sentence):\n    if not 'to' in sentence.lower():\n        return False\n    doc = nlp(sentence)\n    prev_word = None\n    for w in doc:\n        if prev_word == 'to':\n            if w.dep_ == 'ROOT' and w.tag_.startswith('VB'): \n                return True\n            else:\n                return False\n        prev_word = w.text.lower()",
    "docstring": "Given a string, return true if it is an infinitive phrase fragment"
  },
  {
    "code": "def get_for_accounts(self, accounts: List[Account]):\n        account_ids = [acc.guid for acc in accounts]\n        query = (\n            self.query\n            .filter(Split.account_guid.in_(account_ids))\n        )\n        splits = query.all()\n        return splits",
    "docstring": "Get all splits for the given accounts"
  },
  {
    "code": "def cb(option, value, parser):\n    arguments = [value]\n    for arg in parser.rargs:\n        if arg[0] != \"-\":\n            arguments.append(arg)\n        else:\n            del parser.rargs[:len(arguments)]\n            break\n    if getattr(parser.values, option.dest):\n        arguments.extend(getattr(parser.values, option.dest))\n    setattr(parser.values, option.dest, arguments)",
    "docstring": "Callback function to handle variable number of arguments in optparse"
  },
  {
    "code": "def draw_selection(self, surf):\n    select_start = self._select_start\n    if select_start:\n      mouse_pos = self.get_mouse_pos()\n      if (mouse_pos and mouse_pos.surf.surf_type & SurfType.SCREEN and\n          mouse_pos.surf.surf_type == select_start.surf.surf_type):\n        rect = point.Rect(select_start.world_pos, mouse_pos.world_pos)\n        surf.draw_rect(colors.green, rect, 1)",
    "docstring": "Draw the selection rectange."
  },
  {
    "code": "def transformer_text_encoder(inputs,\n                             target_space,\n                             hparams,\n                             name=None):\n  with tf.variable_scope(name, default_name=\"transformer_text_encoder\"):\n    inputs = common_layers.flatten4d3d(inputs)\n    [\n        encoder_input,\n        encoder_self_attention_bias,\n        ed,\n    ] = transformer_layers.transformer_prepare_encoder(\n        inputs, target_space=target_space, hparams=hparams)\n    encoder_input = tf.nn.dropout(encoder_input, 1.0 - hparams.dropout)\n    encoder_output = transformer_layers.transformer_encoder(\n        encoder_input, encoder_self_attention_bias, hparams)\n    return encoder_output, ed",
    "docstring": "Transformer text encoder over inputs with unmasked full attention.\n\n  Args:\n    inputs: Tensor of shape [batch, length, 1, hparams.hidden_size].\n    target_space: int. Used for encoding inputs under a target space id.\n    hparams: HParams.\n    name: string, variable scope.\n\n  Returns:\n    encoder_output: Tensor of shape [batch, length, hparams.hidden_size].\n    ed: Tensor of shape [batch, 1, 1, length]. Encoder-decoder attention bias\n      for any padded tokens."
  },
  {
    "code": "def compare_md5(self):\n        if self.direction == \"put\":\n            remote_md5 = self.remote_md5()\n            return self.source_md5 == remote_md5\n        elif self.direction == \"get\":\n            local_md5 = self.file_md5(self.dest_file)\n            return self.source_md5 == local_md5",
    "docstring": "Compare md5 of file on network device to md5 of local file."
  },
  {
    "code": "def _focus_tab(self, tab_idx):\r\n        for i in range(self.tab_widget.count()):\r\n            self.tab_widget.setTabEnabled(i, False)\r\n        self.tab_widget.setTabEnabled(tab_idx, True)\r\n        self.tab_widget.setCurrentIndex(tab_idx)",
    "docstring": "Change tab focus"
  },
  {
    "code": "def _remove_unicode_keys(dictobj):\n    if sys.version_info[:2] >= (3, 0): return dictobj\n    assert isinstance(dictobj, dict)\n    newdict = {}\n    for key, value in dictobj.items():\n        if type(key) is unicode:\n            key = key.encode('utf-8')\n        newdict[key] = value\n    return newdict",
    "docstring": "Convert keys from 'unicode' to 'str' type.\n\n    workaround for <http://bugs.python.org/issue2646>"
  },
  {
    "code": "def decompose_dateint(dateint):\n    year = int(dateint / 10000)\n    leftover = dateint - year * 10000\n    month = int(leftover / 100)\n    day = leftover - month * 100\n    return year, month, day",
    "docstring": "Decomposes the given dateint into its year, month and day components.\n\n    Arguments\n    ---------\n    dateint : int\n        An integer object decipting a specific calendaric day; e.g. 20161225.\n\n    Returns\n    -------\n    year : int\n        The year component of the given dateint.\n    month : int\n        The month component of the given dateint.\n    day : int\n        The day component of the given dateint."
  },
  {
    "code": "def load_config(self, path):\n        if path == None:\n            print(\"Path to config was null; using defaults.\")\n            return\n        if not os.path.exists(path):\n            print(\"[No user config file found at default location; using defaults.]\\n\")\n            return\n        user_config = None\n        with open(path) as f:\n            user_config = f.read()\n        extension = os.path.splitext(path)\n        if extension == 'yaml':\n            user_config = yaml.load(user_config)\n        else:\n            raise Error('Configuration file type \"{}\" not supported'.format(extension))\n        self.merge_config(user_config)\n        self.configuration = Configuration(self.data_config, self.model_config, self.conversation_config)",
    "docstring": "Load a configuration file; eventually, support dicts, .yaml, .csv, etc."
  },
  {
    "code": "def validate_argmax_with_skipna(skipna, args, kwargs):\n    skipna, args = process_skipna(skipna, args)\n    validate_argmax(args, kwargs)\n    return skipna",
    "docstring": "If 'Series.argmax' is called via the 'numpy' library,\n    the third parameter in its signature is 'out', which\n    takes either an ndarray or 'None', so check if the\n    'skipna' parameter is either an instance of ndarray or\n    is None, since 'skipna' itself should be a boolean"
  },
  {
    "code": "def get_stream_or_content_from_request(request):\n    if request.stream.tell():\n        logger.info('Request stream already consumed. '\n                    'Storing file content using in-memory data.')\n        return request.data\n    else:\n        logger.info('Storing file content using request stream.')\n        return request.stream",
    "docstring": "Ensure the proper content is uploaded.\n\n    Stream might be already consumed by authentication process.\n    Hence flask.request.stream might not be readable and return improper value.\n\n    This methods checks if the stream has already been consumed and if so\n    retrieve the data from flask.request.data where it has been stored."
  },
  {
    "code": "def thread_raise(thread, exctype):\n    import ctypes, inspect, threading, logging\n    if not inspect.isclass(exctype):\n        raise TypeError(\n                'cannot raise %s, only exception types can be raised (not '\n                'instances)' % exctype)\n    gate = thread_exception_gate(thread)\n    with gate.lock:\n        if gate.ok_to_raise.is_set() and thread.is_alive():\n            gate.ok_to_raise.clear()\n            logging.info('raising %s in thread %s', exctype, thread)\n            res = ctypes.pythonapi.PyThreadState_SetAsyncExc(\n                    ctypes.c_long(thread.ident), ctypes.py_object(exctype))\n            if res == 0:\n                raise ValueError(\n                        'invalid thread id? thread.ident=%s' % thread.ident)\n            elif res != 1:\n                ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, 0)\n                raise SystemError('PyThreadState_SetAsyncExc failed')\n        else:\n            logging.info('queueing %s for thread %s', exctype, thread)\n            gate.queue_exception(exctype)",
    "docstring": "Raises or queues the exception `exctype` for the thread `thread`.\n\n    See the documentation on the function `thread_exception_gate()` for more\n    information.\n\n    Adapted from http://tomerfiliba.com/recipes/Thread2/ which explains:\n    \"The exception will be raised only when executing python bytecode. If your\n    thread calls a native/built-in blocking function, the exception will be\n    raised only when execution returns to the python code.\"\n\n    Raises:\n        TypeError if `exctype` is not a class\n        ValueError, SystemError in case of unexpected problems"
  },
  {
    "code": "def get_task_runs(self, json_file=None):\n        if self.project is None:\n            raise ProjectError\n        loader = create_task_runs_loader(self.project.id, self.tasks,\n                                         json_file, self.all)\n        self.task_runs, self.task_runs_file = loader.load()\n        self._check_project_has_taskruns()\n        self.task_runs_df = dataframer.create_task_run_data_frames(self.tasks, self.task_runs)",
    "docstring": "Load all project Task Runs from Tasks."
  },
  {
    "code": "def get_state(cls, clz):\n        if clz not in cls.__shared_state:\n            cls.__shared_state[clz] = (\n                clz.init_state() if hasattr(clz, \"init_state\") else {}\n            )\n        return cls.__shared_state[clz]",
    "docstring": "Retrieve the state of a given Class.\n\n        :param clz: types.ClassType\n        :return: Class state.\n        :rtype: dict"
  },
  {
    "code": "def from_json(cls, data, api=None):\n        result = cls(api=api)\n        for elem_cls in [Node, Way, Relation, Area]:\n            for element in data.get(\"elements\", []):\n                e_type = element.get(\"type\")\n                if hasattr(e_type, \"lower\") and e_type.lower() == elem_cls._type_value:\n                    result.append(elem_cls.from_json(element, result=result))\n        return result",
    "docstring": "Create a new instance and load data from json object.\n\n        :param data: JSON data returned by the Overpass API\n        :type data: Dict\n        :param api:\n        :type api: overpy.Overpass\n        :return: New instance of Result object\n        :rtype: overpy.Result"
  },
  {
    "code": "def merge(self, other):\n        other.qualify()\n        for n in ('name',\n                  'qname',\n                  'min',\n                  'max',\n                  'default',\n                  'type',\n                  'nillable',\n                  'form_qualified',):\n            if getattr(self, n) is not None:\n                continue\n            v = getattr(other, n)\n            if v is None:\n                continue\n            setattr(self, n, v)",
    "docstring": "Merge another object as needed."
  },
  {
    "code": "def _parse_data_array(self, data_array):\n        tokenSeparator = data_array.encoding.tokenSeparator\n        blockSeparator = data_array.encoding.blockSeparator\n        data_values = data_array.values\n        lines = [x for x in data_values.split(blockSeparator) if x != \"\"]\n        ret_val = []\n        for row in lines:\n            values = row.split(tokenSeparator)\n            ret_val.append(\n                [\n                    float(v)\n                    if \" \" not in v.strip()\n                    else [float(vv) for vv in v.split()]\n                    for v in values\n                ]\n            )\n        return [list(x) for x in zip(*ret_val)]",
    "docstring": "Parses a general DataArray."
  },
  {
    "code": "def update_task_positions_obj(self, positions_obj_id, revision, values):\n        return positions_endpoints.update_task_positions_obj(self, positions_obj_id, revision, values)",
    "docstring": "Updates the ordering of tasks in the positions object with the given ID to the ordering in the given values.\n\n        See https://developer.wunderlist.com/documentation/endpoints/positions for more info\n\n        Return:\n        The updated TaskPositionsObj-mapped object defining the order of list layout"
  },
  {
    "code": "def _close_prepared_statement(self):\n        self.prepared_sql = None\n        self.flush_to_query_ready()\n        self.connection.write(messages.Close('prepared_statement', self.prepared_name))\n        self.connection.write(messages.Flush())\n        self._message = self.connection.read_expected_message(messages.CloseComplete)\n        self.connection.write(messages.Sync())",
    "docstring": "Close the prepared statement on the server."
  },
  {
    "code": "def count(self):\n        if self._primary_keys is None:\n            return self.queryset.count()\n        else:\n            return len(self.pks)",
    "docstring": "Return a count of instances."
  },
  {
    "code": "def _parse_bid_table(self, table):\n        player = table.find_all('td')[0].text\n        owner = table.find_all('td')[1].text\n        team = table.find('img')['alt']\n        price = int(table.find_all('td')[3].text.replace(\".\",\"\"))\n        bid_date = table.find_all('td')[4].text\n        trans_date = table.find_all('td')[5].text\n        status = table.find_all('td')[6].text\n        return player,owner,team,price,bid_date,trans_date,status",
    "docstring": "Convert table row values into strings\n        @return: player, owner, team, price, bid_date, trans_date, status"
  },
  {
    "code": "def filter(self, fn, skip_na=True, seed=None):\n        assert callable(fn), \"Input must be callable\"\n        if seed is None:\n            seed = abs(hash(\"%0.20f\" % time.time())) % (2 ** 31)\n        with cython_context():\n            return SArray(_proxy=self.__proxy__.filter(fn, skip_na, seed))",
    "docstring": "Filter this SArray by a function.\n\n        Returns a new SArray filtered by this SArray.  If `fn` evaluates an\n        element to true, this element is copied to the new SArray. If not, it\n        isn't. Throws an exception if the return type of `fn` is not castable\n        to a boolean value.\n\n        Parameters\n        ----------\n        fn : function\n            Function that filters the SArray. Must evaluate to bool or int.\n\n        skip_na : bool, optional\n            If True, will not apply fn to any undefined values.\n\n        seed : int, optional\n            Used as the seed if a random number generator is included in fn.\n\n        Returns\n        -------\n        out : SArray\n            The SArray filtered by fn. Each element of the SArray is of\n            type int.\n\n        Examples\n        --------\n        >>> sa = turicreate.SArray([1,2,3])\n        >>> sa.filter(lambda x: x < 3)\n        dtype: int\n        Rows: 2\n        [1, 2]"
  },
  {
    "code": "def floating_point_to_datetime(day, fp_time):\n    result = datetime(year=day.year, month=day.month, day=day.day)\n    result += timedelta(minutes=math.ceil(60 * fp_time))\n    return result",
    "docstring": "Convert a floating point time to a datetime."
  },
  {
    "code": "def read_user_mapping(self, user_name, mount_point=DEFAULT_MOUNT_POINT):\n        api_path = '/v1/auth/{mount_point}/map/users/{user_name}'.format(\n            mount_point=mount_point,\n            user_name=user_name,\n        )\n        response = self._adapter.get(url=api_path)\n        return response.json()",
    "docstring": "Read the GitHub user policy mapping.\n\n        Supported methods:\n            GET: /auth/{mount_point}/map/users/{user_name}. Produces: 200 application/json\n\n\n        :param user_name: GitHub user name\n        :type user_name: str | unicode\n        :param mount_point: The \"path\" the method/backend was mounted on.\n        :type mount_point: str | unicode\n        :return: The JSON response of the read_user_mapping request.\n        :rtype: dict"
  },
  {
    "code": "def _set_shared_instances(self):\n        self.inqueue = self.em.get_inqueue()\n        self.outqueue = self.em.get_outqueue()\n        self.namespace = self.em.get_namespace()",
    "docstring": "Sets attributes from the shared instances."
  },
  {
    "code": "def _build_tarball(src_repo) -> str:\n    run = partial(subprocess.run, cwd=src_repo, check=True)\n    run(['git', 'clean', '-xdff'])\n    src_repo = Path(src_repo)\n    if os.path.exists(src_repo / 'es' / 'upstream'):\n        run(['git', 'submodule', 'update', '--init', '--', 'es/upstream'])\n    run(['./gradlew', '--no-daemon', 'clean', 'distTar'])\n    distributions = Path(src_repo) / 'app' / 'build' / 'distributions'\n    return next(distributions.glob('crate-*.tar.gz'))",
    "docstring": "Build a tarball from src and return the path to it"
  },
  {
    "code": "def hash_shooter(video_path):\n    filesize = os.path.getsize(video_path)\n    readsize = 4096\n    if os.path.getsize(video_path) < readsize * 2:\n        return None\n    offsets = (readsize, filesize // 3 * 2, filesize // 3, filesize - readsize * 2)\n    filehash = []\n    with open(video_path, 'rb') as f:\n        for offset in offsets:\n            f.seek(offset)\n            filehash.append(hashlib.md5(f.read(readsize)).hexdigest())\n    return ';'.join(filehash)",
    "docstring": "Compute a hash using Shooter's algorithm\n\n    :param string video_path: path of the video\n    :return: the hash\n    :rtype: string"
  },
  {
    "code": "def update_notification_settings(self, api_token, event,\n                                     service, should_notify):\n        params = {\n            'token': api_token,\n            'notification_type': event,\n            'service': service,\n            'dont_notify': should_notify\n        }\n        return self._post('update_notification_setting', params)",
    "docstring": "Update a user's notification settings.\n\n        :param api_token: The user's login api_token.\n        :type api_token: str\n        :param event: Update the notification settings of this event.\n        :type event: str\n        :param service: ``email`` or ``push``\n        :type service: str\n        :param should_notify: If ``0`` notify, otherwise do not.\n        :type should_notify: int\n        :return: The HTTP response to the request.\n        :rtype: :class:`requests.Response`\n\n        >>> from pytodoist.api import TodoistAPI\n        >>> api = TodoistAPI()\n        >>> response = api.login('john.doe@gmail.com', 'password')\n        >>> user_info = response.json()\n        >>> user_api_token = user_info['api_token']\n        >>> response = api.update_notification_settings(user_api_token,\n        ...                                             'user_left_project',\n        ...                                             'email', 0)\n        ..."
  },
  {
    "code": "def get(self, index, doc_type, id, fields=None, model=None, **query_params):\n        path = make_path(index, doc_type, id)\n        if fields is not None:\n            query_params[\"fields\"] = \",\".join(fields)\n        model = model or self.model\n        return model(self, self._send_request('GET', path, params=query_params))",
    "docstring": "Get a typed JSON document from an index based on its id."
  },
  {
    "code": "def as_dict(self):\n        def conv(v):\n            if isinstance(v, SerializableAttributesHolder):\n                return v.as_dict()\n            elif isinstance(v, list):\n                return [conv(x) for x in v]\n            elif isinstance(v, dict):\n                return {x:conv(y) for (x,y) in v.items()}\n            else:\n                return v\n        return {k.replace('_', '-'): conv(v) for (k, v) in self._attributes.items()}",
    "docstring": "Returns a JSON-serializeable object representing this tree."
  },
  {
    "code": "def _render_asset(self, subpath):\n        return send_from_directory(\n            self.assets.cache_path, self.assets.cache_filename(subpath))",
    "docstring": "Renders the specified cache file."
  },
  {
    "code": "def get_bank_hierarchy_session(self):\n        if not self.supports_bank_hierarchy():\n            raise errors.Unimplemented()\n        return sessions.BankHierarchySession(runtime=self._runtime)",
    "docstring": "Gets the session traversing bank hierarchies.\n\n        return: (osid.assessment.BankHierarchySession) - a\n                ``BankHierarchySession``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_bank_hierarchy() is false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_bank_hierarchy()`` is true.*"
  },
  {
    "code": "def _to_backend(self, p):\n        if isinstance(p, self._cmp_base):\n            return p.path\n        elif isinstance(p, self._backend):\n            return p\n        elif self._backend is unicode and isinstance(p, bytes):\n            return p.decode(self._encoding)\n        elif self._backend is bytes and isinstance(p, unicode):\n            return p.encode(self._encoding,\n                            'surrogateescape' if PY3 else 'strict')\n        else:\n            raise TypeError(\"Can't construct a %s from %r\" % (\n                            self.__class__.__name__, type(p)))",
    "docstring": "Converts something to the correct path representation.\n\n        If given a Path, this will simply unpack it, if it's the correct type.\n        If given the correct backend, it will return that.\n        If given bytes for unicode of unicode for bytes, it will encode/decode\n        with a reasonable encoding. Note that these operations can raise\n        UnicodeError!"
  },
  {
    "code": "def get_from_area(self, lat_min, lon_min, lat_max, lon_max, picture_size=None, set_=None, map_filter=None):\n        page_size = 100\n        page = 0\n        result = self._request(lat_min, lon_min, lat_max, lon_max, page * page_size, (page + 1) * page_size,\n                               picture_size, set_, map_filter)\n        total_photos = result['count']\n        if total_photos < page_size:\n            return result\n        page += 1\n        pages = (total_photos / page_size) + 1\n        while page < pages:\n            new_result = self._request(lat_min, lon_min, lat_max, lon_max, page * page_size, (page + 1) * page_size,\n                                       picture_size, set_, map_filter)\n            result['photos'].extend(new_result['photos'])\n            page += 1\n        return result",
    "docstring": "Get all available photos for a specific bounding box\n\n        :param lat_min:\n            Minimum latitude of the bounding box\n        :type lat_min: float\n        :param lon_min:\n            Minimum longitude of the bounding box\n        :type lon_min: float\n        :param lat_max:\n            Maximum latitude of the bounding box\n        :type lat_max: float\n        :param lon_max:\n            Maximum longitude of the bounding box\n        :type lon_max: float\n        :param picture_size:\n            This can be: original, medium (*default*), small, thumbnail, square, mini_square\n        :type picture_size: basestring\n        :param set_:\n            This can be: public, popular or user-id; where user-id is the specific id of a user (as integer)\n        :type set_: basestring/int\n        :param map_filter:\n            Whether to return photos that look better together; when True, tries to avoid returning photos of the same\n            location\n        :type map_filter: bool\n        :return: Returns the full dataset of all available photos"
  },
  {
    "code": "def guess_mime_mimedb (filename):\n    mime, encoding = None, None\n    if mimedb is not None:\n        mime, encoding = mimedb.guess_type(filename, strict=False)\n    if mime not in ArchiveMimetypes and encoding in ArchiveCompressions:\n        mime = Encoding2Mime[encoding]\n        encoding = None\n    return mime, encoding",
    "docstring": "Guess MIME type from given filename.\n    @return: tuple (mime, encoding)"
  },
  {
    "code": "def broadcast_tx(cls, tx_hex):\n        success = None\n        for api_call in cls.BROADCAST_TX_MAIN:\n            try:\n                success = api_call(tx_hex)\n                if not success:\n                    continue\n                return\n            except cls.IGNORED_ERRORS:\n                pass\n        if success is False:\n            raise ConnectionError('Transaction broadcast failed, or '\n                                  'Unspents were already used.')\n        raise ConnectionError('All APIs are unreachable.')",
    "docstring": "Broadcasts a transaction to the blockchain.\n\n        :param tx_hex: A signed transaction in hex form.\n        :type tx_hex: ``str``\n        :raises ConnectionError: If all API services fail."
  },
  {
    "code": "def get_content(ident_hash, context=None):\n    id, version = get_id_n_version(ident_hash)\n    filename = 'index.cnxml.html'\n    if context is not None:\n        stmt = _get_sql('get-baked-content.sql')\n        args = dict(id=id, version=version, context=context)\n    else:\n        stmt = _get_sql('get-content.sql')\n        args = dict(id=id, version=version, filename=filename)\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            cursor.execute(stmt, args)\n            try:\n                content, _ = cursor.fetchone()\n            except TypeError:\n                raise ContentNotFound(ident_hash, context, filename)\n    return content[:]",
    "docstring": "Returns the content for the given ``ident_hash``.\n    ``context`` is optionally ident-hash used to find the content\n    within the context of a Collection ident_hash."
  },
  {
    "code": "def verify_order(self, hostname, domain, location, hourly, flavor, router=None):\n        create_options = self._generate_create_dict(hostname=hostname,\n                                                    router=router,\n                                                    domain=domain,\n                                                    flavor=flavor,\n                                                    datacenter=location,\n                                                    hourly=hourly)\n        return self.client['Product_Order'].verifyOrder(create_options)",
    "docstring": "Verifies an order for a dedicated host.\n\n        See :func:`place_order` for a list of available options."
  },
  {
    "code": "def _analyse_overview_field(content):\n    if \"(\" in content:\n        return content.split(\"(\")[0], content.split(\"(\")[0]\n    elif \"/\" in content:\n        return content.split(\"/\")[0], content.split(\"/\")[1]\n    return content, \"\"",
    "docstring": "Split the field in drbd-overview"
  },
  {
    "code": "def lang_match_xml(row, accepted_languages):\n    if not accepted_languages:\n        return True\n    column_languages = set()\n    for elem in row:\n        lang = elem[0].attrib.get(XML_LANG, None)\n        if lang:\n            column_languages.add(lang)\n    return (not column_languages) or (column_languages & accepted_languages)",
    "docstring": "Find if the XML row contains acceptable language data"
  },
  {
    "code": "def save(self, target=None, shp=None, shx=None, dbf=None):\r\n        if shp:\r\n            self.saveShp(shp)\r\n        if shx:\r\n            self.saveShx(shx)\r\n        if dbf:\r\n            self.saveDbf(dbf)\r\n        elif target:\r\n            self.saveShp(target)\r\n            self.shp.close()\r\n            self.saveShx(target)\r\n            self.shx.close()\r\n            self.saveDbf(target)\r\n            self.dbf.close()",
    "docstring": "Save the shapefile data to three files or\r\n        three file-like objects. SHP and DBF files can also\r\n        be written exclusively using saveShp, saveShx, and saveDbf respectively."
  },
  {
    "code": "def load(config, opt):\n        ctx = Context(opt)\n        seed_map = py_resources()\n        seed_keys = sorted(set([m[0] for m in seed_map]), key=resource_sort)\n        for config_key in seed_keys:\n            if config_key not in config:\n                continue\n            for resource_config in config[config_key]:\n                mod = find_model(config_key, resource_config, seed_map)\n                if not mod:\n                    LOG.warning(\"unable to find mod for %s\", resource_config)\n                    continue\n                ctx.add(mod(resource_config, opt))\n        for config_key in config.keys():\n            if config_key != 'pgp_keys' and \\\n               config_key not in seed_keys:\n                LOG.warning(\"missing model for %s\", config_key)\n        return filtered_context(ctx)",
    "docstring": "Loads and returns a full context object based on the Secretfile"
  },
  {
    "code": "def _get_resource(self, resource, obj, params=None, **kwargs):\n        r = self._http_resource('GET', resource, params=params)\n        item = self._resource_deserialize(r.content.decode(\"utf-8\"))\n        return obj.new_from_dict(item, h=self, **kwargs)",
    "docstring": "Returns a mapped object from an HTTP resource."
  },
  {
    "code": "def inspect_workers(self):\n        workers = tuple(self.workers.values())\n        expired = tuple(w for w in workers if not w.is_alive())\n        for worker in expired:\n            self.workers.pop(worker.pid)\n        return ((w.pid, w.exitcode) for w in expired if w.exitcode != 0)",
    "docstring": "Updates the workers status.\n\n        Returns the workers which have unexpectedly ended."
  },
  {
    "code": "def check_isis_version(major, minor=0, patch=0):\n    if ISIS_VERSION and (major, minor, patch) <= ISIS_VERISON_TUPLE:\n        return\n    msg = 'Version %s.%s.%s of isis required (%s found).'\n    raise VersionError(msg % (major, minor, patch, ISIS_VERSION))",
    "docstring": "Checks that the current isis version is equal to or above the suplied\n    version."
  },
  {
    "code": "def _free_up_space(self, size, this_rel_path=None):\n        space = self.size + size - self.maxsize\n        if space <= 0:\n            return\n        removes = []\n        for row in self.database.execute(\"SELECT path, size, time FROM files ORDER BY time ASC\"):\n            if space > 0:\n                removes.append(row[0])\n                space -= row[1]\n            else:\n                break\n        for rel_path in removes:\n            if rel_path != this_rel_path:\n                global_logger.debug(\"Deleting {}\".format(rel_path))\n                self.remove(rel_path)",
    "docstring": "If there are not size bytes of space left, delete files\n        until there is\n\n        Args:\n            size: size of the current file\n            this_rel_path: rel_pat to the current file, so we don't delete it."
  },
  {
    "code": "def _recursive_merge(dct, merge_dct, raise_on_missing):\n    for k, v in merge_dct.items():\n        if k in dct:\n            if isinstance(dct[k], dict) and isinstance(merge_dct[k], BaseMapping):\n                dct[k] = _recursive_merge(dct[k], merge_dct[k], raise_on_missing)\n            else:\n                dct[k] = merge_dct[k]\n        elif isinstance(dct, Extensible):\n            dct[k] = merge_dct[k]\n        else:\n            message = \"Unknown configuration key: '{k}'\".format(k=k)\n            if raise_on_missing:\n                raise KeyError(message)\n            else:\n                logging.getLogger(__name__).warning(message)\n    return dct",
    "docstring": "Recursive dict merge\n\n    This modifies `dct` in place. Use `copy.deepcopy` if this behavior is not desired."
  },
  {
    "code": "def cycle_focus(self):\n        windows = self.windows()\n        new_index = (windows.index(self.active_window) + 1) % len(windows)\n        self.active_window = windows[new_index]",
    "docstring": "Cycle through all windows."
  },
  {
    "code": "def tail_threshold(vals, N=1000):\n    vals = numpy.array(vals)\n    if len(vals) < N:\n        raise RuntimeError('Not enough input values to determine threshold')\n    vals.sort()\n    return min(vals[-N:])",
    "docstring": "Determine a threshold above which there are N louder values"
  },
  {
    "code": "def reset(self):\n        max_dataset_history = self.value('max_dataset_history')\n        keep_recent_datasets(max_dataset_history, self.info)\n        self.labels.reset()\n        self.channels.reset()\n        self.info.reset()\n        self.notes.reset()\n        self.overview.reset()\n        self.spectrum.reset()\n        self.traces.reset()",
    "docstring": "Remove all the information from previous dataset before loading a\n        new dataset."
  },
  {
    "code": "def squared_distance(v1, v2):\n        v1, v2 = _convert_to_vector(v1), _convert_to_vector(v2)\n        return v1.squared_distance(v2)",
    "docstring": "Squared distance between two vectors.\n        a and b can be of type SparseVector, DenseVector, np.ndarray\n        or array.array.\n\n        >>> a = Vectors.sparse(4, [(0, 1), (3, 4)])\n        >>> b = Vectors.dense([2, 5, 4, 1])\n        >>> a.squared_distance(b)\n        51.0"
  },
  {
    "code": "def _can_process_application(self, app):\n        return (self.LOCATION_KEY in app.properties and\n                isinstance(app.properties[self.LOCATION_KEY], dict) and\n                self.APPLICATION_ID_KEY in app.properties[self.LOCATION_KEY] and\n                self.SEMANTIC_VERSION_KEY in app.properties[self.LOCATION_KEY])",
    "docstring": "Determines whether or not the on_before_transform_template event can process this application\n\n        :param dict app: the application and its properties"
  },
  {
    "code": "def set_mode_by_id(self, zone_id, mode):\n        if not self._do_auth():\n            raise RuntimeError(\"Unable to login\")\n        data = {\n            \"ZoneId\": zone_id,\n            \"mode\": mode.value\n        }\n        headers = {\n            \"Accept\": \"application/json\",\n            \"Content-Type\": \"application/json\",\n            'Authorization':\n                'Bearer ' + self.login_data['token']['accessToken']\n        }\n        url = self.api_base_url + \"Home/SetZoneMode\"\n        response = requests.post(url, data=json.dumps(\n            data), headers=headers, timeout=10)\n        if response.status_code != 200:\n            return False\n        mode_data = response.json()\n        return mode_data.get(\"isSuccess\", False)",
    "docstring": "Set the mode by using the zone id\n        Supported zones are available in the enum Mode"
  },
  {
    "code": "def rpc_export(rpc_method_name, sync=False):\n    def dec(f):\n        f._nvim_rpc_method_name = rpc_method_name\n        f._nvim_rpc_sync = sync\n        f._nvim_bind = True\n        f._nvim_prefix_plugin_path = False\n        return f\n    return dec",
    "docstring": "Export a function or plugin method as a msgpack-rpc request handler."
  },
  {
    "code": "def GroupSizer(field_number, is_repeated, is_packed):\n  tag_size = _TagSize(field_number) * 2\n  assert not is_packed\n  if is_repeated:\n    def RepeatedFieldSize(value):\n      result = tag_size * len(value)\n      for element in value:\n        result += element.ByteSize()\n      return result\n    return RepeatedFieldSize\n  else:\n    def FieldSize(value):\n      return tag_size + value.ByteSize()\n    return FieldSize",
    "docstring": "Returns a sizer for a group field."
  },
  {
    "code": "def get_default_config_help(self):\n        config_help = super(PostgresqlCollector,\n                            self).get_default_config_help()\n        config_help.update({\n            'host': 'Hostname',\n            'dbname': 'DB to connect to in order to get list of DBs in PgSQL',\n            'user': 'Username',\n            'password': 'Password',\n            'port': 'Port number',\n            'password_provider': \"Whether to auth with supplied password or\"\n            \" .pgpass file  <password|pgpass>\",\n            'sslmode': 'Whether to use SSL - <disable|allow|require|...>',\n            'underscore': 'Convert _ to .',\n            'extended': 'Enable collection of extended database stats.',\n            'metrics': 'List of enabled metrics to collect',\n            'pg_version': \"The version of postgres that you'll be monitoring\"\n            \" eg. in format 9.2\",\n            'has_admin': 'Admin privileges are required to execute some'\n            ' queries.',\n        })\n        return config_help",
    "docstring": "Return help text for collector"
  },
  {
    "code": "def visit_Assign(self, node):\n        if self._in_class(node):\n            element_full_name = self._pop_indent_stack(node, \"prop\")\n            code_id = (self._fname, node.lineno)\n            self._processed_line = node.lineno\n            self._callables_db[element_full_name] = {\n                \"name\": element_full_name,\n                \"type\": \"prop\",\n                \"code_id\": code_id,\n                \"last_lineno\": None,\n            }\n            self._reverse_callables_db[code_id] = element_full_name\n            # code =\n        self.generic_visit(node)",
    "docstring": "Implement assignment walker.\n\n        Parse class properties defined via the property() function"
  },
  {
    "code": "def get_pools(time_span=None, api_code=None):\n    resource = 'pools'\n    if time_span is not None:\n        resource += '?timespan=' + time_span\n    if api_code is not None:\n        resource += '&api_code=' + api_code\n    response = util.call_api(resource, base_url='https://api.blockchain.info/')\n    json_response = json.loads(response)\n    return {k: v for (k, v) in json_response.items()}",
    "docstring": "Get number of blocks mined by each pool.\n\n    :param str time_span: duration of the chart.\n    Default is 4days (optional)\n    :param str api_code: Blockchain.info API code (optional)\n    :return: an instance of dict:{str,int}"
  },
  {
    "code": "def flatten(dictionary, separator='.', prefix=''):\n    new_dict = {}\n    for key, value in dictionary.items():\n        new_key = prefix + separator + key if prefix else key\n        if isinstance(value, collections.MutableMapping):\n            new_dict.update(flatten(value, separator, new_key))\n        elif isinstance(value, list):\n            new_value = []\n            for item in value:\n                if isinstance(item, collections.MutableMapping):\n                    new_value.append(flatten(item, separator, new_key))\n                else:\n                    new_value.append(item)\n            new_dict[new_key] = new_value\n        else:\n            new_dict[new_key] = value\n    return new_dict",
    "docstring": "Flatten the dictionary keys are separated by separator\n\n    Arguments:\n        dictionary {dict} -- The dictionary to be flattened.\n\n    Keyword Arguments:\n        separator {str} -- The separator to use (default is '.'). It will\n        crush items with key conflicts.\n        prefix {str} -- Used for recursive calls.\n\n    Returns:\n        dict -- The flattened dictionary."
  },
  {
    "code": "def push(self, element, value):\n        insert_pos = 0\n        for index, el in enumerate(self.tops):\n            if not self.find_min and el[1] >= value:\n                insert_pos = index+1\n            elif self.find_min and el[1] <= value:\n                insert_pos = index+1\n        self.tops.insert(insert_pos, [element, value])\n        self.tops = self.tops[:self.n]",
    "docstring": "Push an ``element`` into the datastrucutre together with its value\n           and only save it if it currently is one of the top n elements.\n\n           Drop elements if necessary."
  },
  {
    "code": "def get_banks_by_item(self, item_id):\n        mgr = self._get_provider_manager('ASSESSMENT', local=True)\n        lookup_session = mgr.get_bank_lookup_session(proxy=self._proxy)\n        return lookup_session.get_banks_by_ids(\n            self.get_bank_ids_by_item(item_id))",
    "docstring": "Gets the list of ``Banks`` mapped to an ``Item``.\n\n        arg:    item_id (osid.id.Id): ``Id`` of an ``Item``\n        return: (osid.assessment.BankList) - list of banks\n        raise:  NotFound - ``item_id`` is not found\n        raise:  NullArgument - ``item_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - assessment failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get(self, key):\n        if isinstance(key, unicode):\n            key = key.encode('utf-8')\n        v = self.client.get(key)\n        if v is None:\n            raise KeyError(\"Cache key [%s] not found\" % key)\n        else:\n            return v",
    "docstring": "because memcached does not provide a function to check if a key is existed\n        so here is a heck way, if the value is None, then raise Exception"
  },
  {
    "code": "def interleave(*args):\n    result = []\n    for array in zip(*args):\n        result.append(tuple(flatten(array)))\n    return result",
    "docstring": "Interleaves the elements of the provided arrays.\n\n        >>> a = [(0, 0), (1, 0), (2, 0), (3, 0)]\n        >>> b = [(0, 0), (0, 1), (0, 2), (0, 3)]\n        >>> interleave(a, b)\n        [(0, 0, 0, 0), (1, 0, 0, 1), (2, 0, 0, 2), (3, 0, 0, 3)]\n\n    This is useful for combining multiple vertex attributes into a single\n    vertex buffer. The shader attributes can be assigned a slice of the\n    vertex buffer."
  },
  {
    "code": "def get_message(message, *args, **kwargs):\n        msg = current_app.extensions['simplelogin'].messages.get(message)\n        if msg and (args or kwargs):\n            return msg.format(*args, **kwargs)\n        return msg",
    "docstring": "Helper to get internal messages outside this instance"
  },
  {
    "code": "def _Scroll(self, lines=None):\n    if lines is None:\n      lines = self._cli_lines\n    if lines < 0:\n      self._displayed -= self._cli_lines\n      self._displayed += lines\n      if self._displayed < 0:\n        self._displayed = 0\n      self._lines_to_show = self._cli_lines\n    else:\n      self._lines_to_show = lines\n    self._lastscroll = lines",
    "docstring": "Set attributes to scroll the buffer correctly.\n\n    Args:\n      lines: An int, number of lines to scroll. If None, scrolls\n        by the terminal length."
  },
  {
    "code": "def disconnect(self, connection):\n        self.log.debug(\"Disconnecting %s\" % connection)\n        for dest in list(self._topics.keys()):\n            if connection in self._topics[dest]:\n                self._topics[dest].remove(connection)\n            if not self._topics[dest]:\n                del self._topics[dest]",
    "docstring": "Removes a subscriber connection.\n\n        @param connection: The client connection to unsubscribe.\n        @type connection: L{coilmq.server.StompConnection}"
  },
  {
    "code": "def expireat(key, timestamp, host=None, port=None, db=None, password=None):\n    server = _connect(host, port, db, password)\n    return server.expireat(key, timestamp)",
    "docstring": "Set a keys expire at given UNIX time\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' redis.expireat foo 1400000000"
  },
  {
    "code": "def secret_hex(self, secret_hex):\n        if secret_hex is None:\n            raise ValueError(\"Invalid value for `secret_hex`, must not be `None`\")\n        if secret_hex is not None and not re.search('^(0[xX])?[0-9a-fA-F]{32,64}$', secret_hex):\n            raise ValueError(\"Invalid value for `secret_hex`, must be a follow pattern or equal to `/^(0[xX])?[0-9a-fA-F]{32,64}$/`\")\n        self._secret_hex = secret_hex",
    "docstring": "Sets the secret_hex of this PreSharedKey.\n        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.\n\n        :param secret_hex: The secret_hex of this PreSharedKey.\n        :type: str"
  },
  {
    "code": "def parameterize_path(path, parameters):\n    if parameters is None:\n        parameters = {}\n    try:\n        return path.format(**parameters)\n    except KeyError as key_error:\n        raise PapermillMissingParameterException(\"Missing parameter {}\".format(key_error))",
    "docstring": "Format a path with a provided dictionary of parameters\n\n    Parameters\n    ----------\n    path : string\n       Path with optional parameters, as a python format string\n    parameters : dict\n       Arbitrary keyword arguments to fill in the path"
  },
  {
    "code": "def discrete_index(self, indices):\n        elements = []\n        for i in indices:\n            elements.append(self[i])\n        return elements",
    "docstring": "get elements by discrete indices\n\n        :param indices: list\n            discrete indices\n        :return: elements"
  },
  {
    "code": "def del_cookie(self, name: str, *,\n                   domain: Optional[str]=None,\n                   path: str='/') -> None:\n        self._cookies.pop(name, None)\n        self.set_cookie(name, '', max_age=0,\n                        expires=\"Thu, 01 Jan 1970 00:00:00 GMT\",\n                        domain=domain, path=path)",
    "docstring": "Delete cookie.\n\n        Creates new empty expired cookie."
  },
  {
    "code": "def modules_and_args(modules=True, states=False, names_only=False):\n    dirs = []\n    module_dir = os.path.dirname(os.path.realpath(__file__))\n    state_dir = os.path.join(os.path.dirname(module_dir), 'states')\n    if modules:\n        dirs.append(module_dir)\n    if states:\n        dirs.append(state_dir)\n    ret = _mods_with_args(dirs)\n    if names_only:\n        return sorted(ret.keys())\n    else:\n        return OrderedDict(sorted(ret.items()))",
    "docstring": "Walk the Salt install tree and return a dictionary or a list\n    of the functions therein as well as their arguments.\n\n    :param modules: Walk the modules directory if True\n    :param states: Walk the states directory if True\n    :param names_only: Return only a list of the callable functions instead of a dictionary with arguments\n    :return: An OrderedDict with callable function names as keys and lists of arguments as\n             values (if ``names_only``==False) or simply an ordered list of callable\n             function nanes (if ``names_only``==True).\n\n    CLI Example:\n    (example truncated for brevity)\n\n    .. code-block:: bash\n\n        salt myminion baredoc.modules_and_args\n\n        myminion:\n            ----------\n        [...]\n            at.atrm:\n            at.jobcheck:\n            at.mod_watch:\n                - name\n            at.present:\n                - unique_tag\n                - name\n                - timespec\n                - job\n                - tag\n                - user\n            at.watch:\n                - unique_tag\n                - name\n                - timespec\n                - job\n                - tag\n                - user\n        [...]"
  },
  {
    "code": "def common_items_ratio(pronac, dt):\n    segment_id = get_segment_id(str(pronac))\n    metrics = data.common_items_metrics.to_dict(orient='index')[segment_id]\n    ratio = common_items_percentage(pronac, segment_common_items(segment_id))\n    k = 1.5\n    threshold = metrics['mean'] - k * metrics['std']\n    uncommon_items = get_uncommon_items(pronac)\n    pronac_filter = data.all_items['PRONAC'] == pronac\n    uncommon_items_filter = (\n        data.all_items['idPlanilhaItens']\n        .isin(uncommon_items)\n    )\n    items_filter = (pronac_filter & uncommon_items_filter)\n    filtered_items = (\n        data\n        .all_items[items_filter]\n        .drop_duplicates(subset='idPlanilhaItens')\n    )\n    uncommon_items = add_info_to_uncommon_items(filtered_items, uncommon_items)\n    return {\n        'is_outlier': ratio < threshold,\n        'valor': ratio,\n        'maximo_esperado': metrics['mean'],\n        'desvio_padrao': metrics['std'],\n        'items_incomuns': uncommon_items,\n        'items_comuns_que_o_projeto_nao_possui': get_common_items_not_present(pronac),\n    }",
    "docstring": "Calculates the common items on projects in a cultural segment,\n    calculates the uncommon items on projects in a cultural segment and\n    verify if a project is an outlier compared to the other projects\n    in his segment."
  },
  {
    "code": "def extend(self, elts):\n        elts = elts[:]\n        self._in_deque.append(elts)\n        event = self._event_for(elts)\n        self._event_deque.append(event)\n        return event",
    "docstring": "Adds elts to the tasks.\n\n        Args:\n           elts (Sequence): a iterable of elements that can be appended to the\n            task's bundle_field.\n\n        Returns:\n            Event: an event that can be used to wait on the response."
  },
  {
    "code": "def local_manager_rule(self):\n        adm_gid = self.local_manager_gid\n        if not adm_gid:\n            return None\n        config = self.root['settings']['ugm_localmanager'].attrs\n        return config[adm_gid]",
    "docstring": "Return rule for local manager."
  },
  {
    "code": "def vote_random(candidates, votes, n_winners):\n    rcands = list(candidates)\n    shuffle(rcands)\n    rcands = rcands[:min(n_winners, len(rcands))]\n    best = [(i, 0.0) for i in rcands]\n    return best",
    "docstring": "Select random winners from the candidates.\n\n    This voting method bypasses the given votes completely.\n\n    :param candidates: All candidates in the vote\n    :param votes: Votes from the agents\n    :param int n_winners: The number of vote winners"
  },
  {
    "code": "def stop_all(self):\n        pool = Pool(concurrency=3)\n        for node in self.nodes.values():\n            pool.append(node.stop)\n        yield from pool.join()",
    "docstring": "Stop all nodes"
  },
  {
    "code": "def load_extra(cls, filename):\n    try:\n      with open(filename, 'rb') as configuration_file:\n        cls.load_extra_data(configuration_file.read())\n        sys.stderr.write(\"Config successfully loaded from {0:s}\\n\".format(\n            filename))\n        return True\n    except IOError:\n      return False",
    "docstring": "Loads extra JSON configuration parameters from a file on the filesystem.\n\n    Args:\n      filename: str, the filename to open.\n\n    Returns:\n      bool: True if the extra configuration parameters were read."
  },
  {
    "code": "def forward(self):\n        if self._index >= len(self._history) - 1:\n            return None\n        self._index += 1\n        self._check_index()\n        return self.current_item",
    "docstring": "Go forward in history if possible.\n\n        Return the current item after going forward."
  },
  {
    "code": "def parse_args(self, ctx, args):\n        if args and args[0] in self.commands:\n            args.insert(0, '')\n        super(OptionalGroup, self).parse_args(ctx, args)",
    "docstring": "Check if the first argument is an existing command."
  },
  {
    "code": "def merge(dest, src, merge_lists=False, in_place=True):\n    if in_place:\n        merged = dest\n    else:\n        merged = copy.deepcopy(dest)\n    return dictupdate.update(merged, src, merge_lists=merge_lists)",
    "docstring": "defaults.merge\n        Allows deep merging of dicts in formulas.\n\n    merge_lists : False\n        If True, it will also merge lists instead of replace their items.\n\n    in_place : True\n        If True, it will merge into dest dict,\n        if not it will make a new copy from that dict and return it.\n\n        CLI Example:\n        .. code-block:: bash\n\n        salt '*' default.merge a=b d=e\n\n    It is more typical to use this in a templating language in formulas,\n    instead of directly on the command-line."
  },
  {
    "code": "def limited_to(self, left: Set[TLeft], right: Set[TRight]) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]':\n        return BipartiteGraph(((n1, n2), v) for (n1, n2), v in self._edges.items() if n1 in left and n2 in right)",
    "docstring": "Returns the induced subgraph where only the nodes from the given sets are included."
  },
  {
    "code": "def samefile(path1, path2):\n    path1, path1_is_storage = format_and_is_storage(path1)\n    path2, path2_is_storage = format_and_is_storage(path2)\n    if not path1_is_storage and not path2_is_storage:\n        return os_path_samefile(path1, path2)\n    if not path1_is_storage or not path2_is_storage:\n        return False\n    with handle_os_exceptions():\n        system = get_instance(path1)\n        if system is not get_instance(path2):\n            return False\n        elif system.relpath(path1) != system.relpath(path2):\n            return False\n    return True",
    "docstring": "Return True if both pathname arguments refer to the same file or directory.\n\n    Equivalent to \"os.path.samefile\".\n\n    Args:\n        path1 (path-like object): Path or URL.\n        path2 (path-like object): Path or URL.\n\n    Returns:\n        bool: True if same file or directory."
  },
  {
    "code": "def get_change_price(self, plan_old, plan_new, period):\n        if period is None or period < 1:\n            return None\n        plan_old_day_cost = self._calculate_day_cost(plan_old, period)\n        plan_new_day_cost = self._calculate_day_cost(plan_new, period)\n        if plan_new_day_cost <= plan_old_day_cost:\n            return self._calculate_final_price(period, None)\n        else:\n            return self._calculate_final_price(period, plan_new_day_cost - plan_old_day_cost)",
    "docstring": "Calculates total price of plan change. Returns None if no payment is required."
  },
  {
    "code": "def truncated_normal_expval(mu, tau, a, b):\n    phia = np.exp(normal_like(a, mu, tau))\n    phib = np.exp(normal_like(b, mu, tau))\n    sigma = 1. / np.sqrt(tau)\n    Phia = utils.normcdf((a - mu) / sigma)\n    if b == np.inf:\n        Phib = 1.0\n    else:\n        Phib = utils.normcdf((b - mu) / sigma)\n    return (mu + (phia - phib) / (Phib - Phia))[0]",
    "docstring": "Expected value of the truncated normal distribution.\n\n    .. math::\n       E(X) =\\mu + \\frac{\\sigma(\\varphi_1-\\varphi_2)}{T}\n\n\n    where\n\n    .. math::\n       T & =\\Phi\\left(\\frac{B-\\mu}{\\sigma}\\right)-\\Phi\n       \\left(\\frac{A-\\mu}{\\sigma}\\right)\\text \\\\\n       \\varphi_1 &=\n       \\varphi\\left(\\frac{A-\\mu}{\\sigma}\\right) \\\\\n       \\varphi_2 &=\n       \\varphi\\left(\\frac{B-\\mu}{\\sigma}\\right) \\\\\n\n    and :math:`\\varphi = N(0,1)` and :math:`tau & 1/sigma**2`.\n\n    :Parameters:\n      - `mu` : Mean of the distribution.\n      - `tau` : Precision of the distribution, which corresponds to 1/sigma**2 (tau > 0).\n      - `a` : Left bound of the distribution.\n      - `b` : Right bound of the distribution."
  },
  {
    "code": "def print_evaluation(period=1, show_stdv=True):\n    def callback(env):\n        if env.rank != 0 or (not env.evaluation_result_list) or period is False or period == 0:\n            return\n        i = env.iteration\n        if i % period == 0 or i + 1 == env.begin_iteration or i + 1 == env.end_iteration:\n            msg = '\\t'.join([_fmt_metric(x, show_stdv) for x in env.evaluation_result_list])\n            rabit.tracker_print('[%d]\\t%s\\n' % (i, msg))\n    return callback",
    "docstring": "Create a callback that print evaluation result.\n\n    We print the evaluation results every **period** iterations\n    and on the first and the last iterations.\n\n    Parameters\n    ----------\n    period : int\n        The period to log the evaluation results\n\n    show_stdv : bool, optional\n         Whether show stdv if provided\n\n    Returns\n    -------\n    callback : function\n        A callback that print evaluation every period iterations."
  },
  {
    "code": "def checkInstalledBrew(package, similar=True, speak=True, speakSimilar=True):\n    packages = subprocess.check_output(['brew', 'list']).split()\n    installed = package in packages\n    similar = []\n    if not installed:\n        similar = [pkg for pkg in packages if package in pkg]\n    if speak:\n        speakInstalledPackages(package, \"homebrew\", installed, similar, speakSimilar)\n    return (installed, similar)",
    "docstring": "checks if a given package is installed on homebrew"
  },
  {
    "code": "def stratified_kfold(df, n_folds):\n    sessions = pd.DataFrame.from_records(list(df.index.unique())).groupby(0).apply(lambda x: x[1].unique())\n    sessions.apply(lambda x: np.random.shuffle(x))\n    folds = []\n    for i in range(n_folds):\n        idx = sessions.apply(lambda x: pd.Series(x[i * (len(x) / n_folds):(i + 1) * (len(x) / n_folds)]))\n        idx = pd.DataFrame(idx.stack().reset_index(level=1, drop=True)).set_index(0, append=True).index.values\n        folds.append(df.loc[idx])\n    return folds",
    "docstring": "Create stratified k-folds from an indexed dataframe"
  },
  {
    "code": "def _get_stddevs(self, C, stddev_types, stddev_shape):\n        stddevs = []\n        for stddev_type in stddev_types:\n            assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n            if stddev_type == const.StdDev.TOTAL:\n                stddevs.append(C[\"sigtot\"] + np.zeros(stddev_shape))\n            elif stddev_type == const.StdDev.INTRA_EVENT:\n                stddevs.append(C['sig2'] + np.zeros(stddev_shape))\n            elif stddev_type == const.StdDev.INTER_EVENT:\n                stddevs.append(C['sig1'] + np.zeros(stddev_shape))\n        return stddevs",
    "docstring": "Returns the standard deviations given in Table 2"
  },
  {
    "code": "def read_data(self, timeout=10.0):\n        start_time = time.time()\n        while True:\n            data = None\n            try:\n                data = self.stdout_reader.queue.get(timeout=timeout)\n                if data:\n                    yield data\n                else:\n                    break\n            except queue.Empty:\n                end_time = time.time()\n                if not data:\n                    if end_time - start_time >= timeout:\n                        raise ReadTimeoutError('ffmpeg output: {}'.format(\n                            ''.join(self.stderr_reader.queue.queue)\n                        ))\n                    else:\n                        start_time = end_time\n                        continue",
    "docstring": "Read blocks of raw PCM data from the file."
  },
  {
    "code": "def parse_template_json(self, template_json):\n        assert template_json['type'] == self.DOCUMENT_TYPE, ''\n        self.template_id = template_json['templateId']\n        self.name = template_json.get('name')\n        self.creator = template_json.get('creator')\n        self.template = template_json['serviceAgreementTemplate']",
    "docstring": "Parse a template from a json.\n\n        :param template_json: json dict"
  },
  {
    "code": "def create(self, name, plugin_name, plugin_version, flavor_id,\n               description=None, volumes_per_node=None, volumes_size=None,\n               node_processes=None, node_configs=None, floating_ip_pool=None,\n               security_groups=None, auto_security_group=None,\n               availability_zone=None, volumes_availability_zone=None,\n               volume_type=None, image_id=None, is_proxy_gateway=None,\n               volume_local_to_instance=None, use_autoconfig=None,\n               shares=None, is_public=None, is_protected=None,\n               volume_mount_prefix=None, boot_from_volume=None,\n               boot_volume_type=None, boot_volume_availability_zone=None,\n               boot_volume_local_to_instance=None):\n        data = {\n            'name': name,\n            'plugin_name': plugin_name,\n            'plugin_version': plugin_version,\n            'flavor_id': flavor_id,\n            'node_processes': node_processes\n        }\n        return self._do_create(data, description, volumes_per_node,\n                               volumes_size, node_configs, floating_ip_pool,\n                               security_groups, auto_security_group,\n                               availability_zone, volumes_availability_zone,\n                               volume_type, image_id, is_proxy_gateway,\n                               volume_local_to_instance, use_autoconfig,\n                               shares, is_public, is_protected,\n                               volume_mount_prefix, boot_from_volume,\n                               boot_volume_type,\n                               boot_volume_availability_zone,\n                               boot_volume_local_to_instance)",
    "docstring": "Create a Node Group Template."
  },
  {
    "code": "def validate_empty_attributes(fully_qualified_name: str, spec: Dict[str, Any],\n                              *attributes: str) -> List[EmptyAttributeError]:\n    return [\n        EmptyAttributeError(fully_qualified_name, spec, attribute)\n        for attribute in attributes\n        if not spec.get(attribute, None)\n    ]",
    "docstring": "Validates to ensure that a set of attributes do not contain empty values"
  },
  {
    "code": "def remove_input(urls, preserves, verbose = False):\n\tfor path in map(url2path, urls):\n\t\tif any(os.path.samefile(path, preserve) for preserve in preserves):\n\t\t\tcontinue\n\t\tif verbose:\n\t\t\tprint >>sys.stderr, \"removing \\\"%s\\\" ...\" % path\n\t\ttry:\n\t\t\tos.remove(path)\n\t\texcept:\n\t\t\tpass",
    "docstring": "Attempt to delete all files identified by the URLs in urls except\n\tany that are the same as the files in the preserves list."
  },
  {
    "code": "def _diff_group_position(group):\n    old_start = group[0][0]\n    new_start = group[0][1]\n    old_length = new_length = 0\n    for old_line, new_line, line_or_conflict in group:\n        if isinstance(line_or_conflict, tuple):\n            old, new = line_or_conflict\n            old_length += len(old)\n            new_length += len(new)\n        else:\n            old_length += 1\n            new_length += 1\n    if old_length:\n        old_start += 1\n    if new_length:\n        new_start += 1\n    return color.LineNumber('@@ -%s,%s +%s,%s @@' % (old_start, old_length, new_start, new_length))",
    "docstring": "Generate a unified diff position line for a diff group"
  },
  {
    "code": "def assign(self, link_type, product, linked_product, data=None,\n               identifierType=None):\n        return bool(self.call('catalog_product_link.assign',\n                [link_type, product, linked_product, data, identifierType]))",
    "docstring": "Assign a product link\n\n        :param link_type: type of link, one of 'cross_sell', 'up_sell',\n                'related' or 'grouped'\n        :param product: ID or SKU of product\n        :param linked_product: ID or SKU of linked product\n        :param data: dictionary of link data, (position, qty, etc.)\n                Example: { 'position': '0', 'qty': 1}\n        :param identifierType: Defines whether the product or SKU value is\n                               passed in the \"product\" parameter.\n\n        :return: boolean"
  },
  {
    "code": "def __compress_attributes(self, dic):\n        result = {}\n        for k, v in dic.iteritems():\n            if isinstance(v, types.ListType) and len(v) == 1:\n                if k not in ('msExchMailboxSecurityDescriptor', 'msExchSafeSendersHash', 'msExchBlockedSendersHash',\n                             'replicationSignature', 'msExchSafeRecipientsHash', 'sIDHistory',\n                             'msRTCSIP-UserRoutingGroupId', 'mSMQDigests', 'mSMQSignCertificates',\n                             'msExchMasterAccountSid', 'msExchPreviousAccountSid', 'msExchUMPinChecksum',\n                             'userSMIMECertificate', 'userCertificate', 'userCert',\n                             'msExchDisabledArchiveGUID', 'msExchUMPinChecksum', 'msExchUMSpokenName',\n                             'objectSid', 'objectGUID', 'msExchArchiveGUID', 'thumbnailPhoto', 'msExchMailboxGuid'):\n                    try:\n                        result[k] = v[0].decode('utf-8')\n                    except Exception as e:\n                        logging. error(\"Failed to decode attribute: %s -- %s\" % (k, e))\n                        result[k] = v[0]\n        return result",
    "docstring": "This will convert all attributes that are list with only one item string into simple string. It seems that LDAP always return lists, even when it doesn\n        t make sense.\n\n        :param dic:\n        :return:"
  },
  {
    "code": "def get_new_broks(self):\n        for elt in self.all_my_hosts_and_services():\n            for brok in elt.broks:\n                self.add(brok)\n            elt.broks = []\n        for contact in self.contacts:\n            for brok in contact.broks:\n                self.add(brok)\n            contact.broks = []",
    "docstring": "Iter over all hosts and services to add new broks in internal lists\n\n        :return: None"
  },
  {
    "code": "def get_relationship_dicts(self):\n        if not self.relationships:\n            return None\n        for goid, goobj in self.go2obj.items():\n            for reltyp, relset in goobj.relationship.items():\n                relfwd_goids = set(o.id for o in relset)\n                print(\"CountRelativesInit RELLLLS\", goid, goobj.id, reltyp, relfwd_goids)",
    "docstring": "Given GO DAG relationships, return summaries per GO ID."
  },
  {
    "code": "def unpack(cls, msg, client, server, request_id):\n        flags, = _UNPACK_INT(msg[:4])\n        namespace, pos = _get_c_string(msg, 4)\n        docs = bson.decode_all(msg[pos:], CODEC_OPTIONS)\n        return cls(*docs, namespace=namespace, flags=flags, _client=client,\n                   request_id=request_id, _server=server)",
    "docstring": "Parse message and return an `OpInsert`.\n\n        Takes the client message as bytes, the client and server socket objects,\n        and the client request id."
  },
  {
    "code": "def protocol(alias_name, default=None, allow_none=False):\n    warnings.warn('Will be removed in v1.0', DeprecationWarning, stacklevel=2)\n    try:\n        return _split_docker_link(alias_name)[0]\n    except KeyError as err:\n        if default or allow_none:\n            return default\n        else:\n            raise err",
    "docstring": "Get the protocol from the docker link alias or return the default.\n\n    Args:\n        alias_name: The docker link alias\n        default: The default value if the link isn't available\n        allow_none: If the return value can be `None` (i.e. optional)\n\n    Examples:\n        Assuming a Docker link was created with ``docker --link postgres:db``\n        and the resulting environment variable is ``DB_PORT=tcp://172.17.0.82:5432``.\n\n        >>> envitro.docker.protocol('DB')\n        tcp"
  },
  {
    "code": "def _all_inner(self, fields, limit, order_by, offset):\n        response = self.session.get(self._get_table_url(),\n                                    params=self._get_formatted_query(fields, limit, order_by, offset))\n        yield self._get_content(response)\n        while 'next' in response.links:\n            self.url_link = response.links['next']['url']\n            response = self.session.get(self.url_link)\n            yield self._get_content(response)",
    "docstring": "Yields all records for the query and follows links if present on the response after validating\n\n        :return: List of records with content"
  },
  {
    "code": "def debug_file(self):\r\n        self.switch_to_plugin()\r\n        current_editor = self.get_current_editor()\r\n        if current_editor is not None:\r\n            current_editor.sig_debug_start.emit()\r\n        self.run_file(debug=True)",
    "docstring": "Debug current script"
  },
  {
    "code": "def publish(cls, message, client_filter=None):\n    with cls._lock:\n      for client in cls.subscribers:\n        if (not client_filter) or client_filter(client):\n          client.send(message)",
    "docstring": "Publish messages to subscribers.\n\n    Args:\n      message: The message to publish.\n      client_filter: A filter function to call passing in each client. Only\n                     clients for whom the function returns True will have the\n                     message sent to them."
  },
  {
    "code": "def read(self):\n        data = self.dev.read()\n        if len(data) == 0:\n            self.log.warning(\"READ : Nothing received\")\n            return\n        if data == b'\\x00':\n            self.log.warning(\"READ : Empty packet (Got \\\\x00)\")\n            return\n        pkt = bytearray(data)\n        data = self.dev.read(pkt[0])\n        pkt.extend(bytearray(data))\n        self.log.info(\"READ : %s\" % self.format_packet(pkt))\n        self.do_callback(pkt)\n        return pkt",
    "docstring": "We have been called to read! As a consumer, continue to read for\n        the length of the packet and then pass to the callback."
  },
  {
    "code": "def raw(text):\n    new_string = ''\n    for char in text:\n        try:\n            new_string += escape_dict[char]\n        except KeyError:\n            new_string += char\n    return new_string",
    "docstring": "Returns a raw string representation of text"
  },
  {
    "code": "def class_repr(value):\n    klass = value\n    if not isinstance(value, type):\n        klass = klass.__class__\n    return '.'.join([klass.__module__, klass.__name__])",
    "docstring": "Returns a representation of the value class.\n\n    Arguments\n    ---------\n    value\n        A class or a class instance\n\n    Returns\n    -------\n    str\n        The \"module.name\" representation of the value class.\n\n    Example\n    -------\n    >>> from datetime import date\n    >>> class_repr(date)\n    'datetime.date'\n    >>> class_repr(date.today())\n    'datetime.date'"
  },
  {
    "code": "def find_function(self, name):\n        deffunction = lib.EnvFindDeffunction(self._env, name.encode())\n        if deffunction == ffi.NULL:\n            raise LookupError(\"Function '%s' not found\" % name)\n        return Function(self._env, deffunction)",
    "docstring": "Find the Function by its name."
  },
  {
    "code": "def communicate_through(self, file):\n        if self._communication is not None:\n            raise ValueError(\"Already communicating.\")\n        self._communication = communication = Communication(\n            file, self._get_needle_positions,\n            self._machine, [self._on_message_received],\n            right_end_needle=self.right_end_needle,\n            left_end_needle=self.left_end_needle)\n        return communication",
    "docstring": "Setup communication through a file.\n\n        :rtype: AYABInterface.communication.Communication"
  },
  {
    "code": "def parse(html_string, wrapper=Parser, *args, **kwargs):\n    return Parser(lxml.html.fromstring(html_string), *args, **kwargs)",
    "docstring": "Parse html with wrapper"
  },
  {
    "code": "def nl_object_alloc(ops):\n    new = nl_object()\n    nl_init_list_head(new.ce_list)\n    new.ce_ops = ops\n    if ops.oo_constructor:\n        ops.oo_constructor(new)\n    _LOGGER.debug('Allocated new object 0x%x', id(new))\n    return new",
    "docstring": "Allocate a new object of kind specified by the operations handle.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/object.c#L54\n\n    Positional arguments:\n    ops -- cache operations handle (nl_object_ops class instance).\n\n    Returns:\n    New nl_object class instance or None."
  },
  {
    "code": "def stop_recording():\n    global _recording\n    if not _recording:\n        raise ValueError('Must call \"start_recording\" before.')\n    recorded_events_queue, hooked = _recording\n    unhook(hooked)\n    return list(recorded_events_queue.queue)",
    "docstring": "Stops the global recording of events and returns a list of the events\n    captured."
  },
  {
    "code": "def wrap_threading_start(start_func):\n    def call(self):\n        self._opencensus_context = (\n            execution_context.get_opencensus_full_context()\n        )\n        return start_func(self)\n    return call",
    "docstring": "Wrap the start function from thread. Put the tracer informations in the\n    threading object."
  },
  {
    "code": "def bytes_array(self):\n        assert len(self.dimensions) == 2, \\\n            '{}: cannot get value as bytes array!'.format(self.name)\n        l, n = self.dimensions\n        return [self.bytes[i*l:(i+1)*l] for i in range(n)]",
    "docstring": "Get the param as an array of raw byte strings."
  },
  {
    "code": "def tag(tagname, content='', attrs=None):\n    attrs_str = attrs and ' '.join(_generate_dom_attrs(attrs))\n    open_tag = tagname\n    if attrs_str:\n        open_tag += ' ' + attrs_str\n    if content is None:\n        return literal('<%s />' % open_tag)\n    content = ''.join(iterate(content, unless=(basestring, literal)))\n    return literal('<%s>%s</%s>' % (open_tag, content, tagname))",
    "docstring": "Helper for programmatically building HTML tags.\n\n    Note that this barely does any escaping, and will happily spit out\n    dangerous user input if used as such.\n\n    :param tagname:\n        Tag name of the DOM element we want to return.\n\n    :param content:\n        Optional content of the DOM element. If `None`, then the element is\n        self-closed. By default, the content is an empty string. Supports\n        iterables like generators.\n\n    :param attrs:\n        Optional dictionary-like collection of attributes for the DOM element.\n\n    Example::\n\n        >>> tag('div', content='Hello, world.')\n        u'<div>Hello, world.</div>'\n        >>> tag('script', attrs={'src': '/static/js/core.js'})\n        u'<script src=\"/static/js/core.js\"></script>'\n        >>> tag('script', attrs=[('src', '/static/js/core.js'), ('type', 'text/javascript')])\n        u'<script src=\"/static/js/core.js\" type=\"text/javascript\"></script>'\n        >>> tag('meta', content=None, attrs=dict(content='\"quotedquotes\"'))\n        u'<meta content=\"\\\\\\\\\"quotedquotes\\\\\\\\\"\" />'\n        >>> tag('ul', (tag('li', str(i)) for i in xrange(3)))\n        u'<ul><li>0</li><li>1</li><li>2</li></ul>'"
  },
  {
    "code": "def position_input(obj, visible=False):\n    if not obj.generic_position.all():\n        ObjectPosition.objects.create(content_object=obj)\n    return {'obj': obj, 'visible': visible,\n            'object_position': obj.generic_position.all()[0]}",
    "docstring": "Template tag to return an input field for the position of the object."
  },
  {
    "code": "def list_databases(self):\n        lines = output_lines(self.exec_psql('\\\\list'))\n        return [line.split('|') for line in lines]",
    "docstring": "Runs the ``\\\\list`` command and returns a list of column values with\n        information about all databases."
  },
  {
    "code": "def random_stats(self, all_stats, race, ch_class):\n        stats = []\n        res = {}\n        for s in all_stats:\n            stats.append(s['stat'])\n            res[s['stat']] = 0\n        cur_stat = 0\n        for stat in stats:\n            for ndx, i in enumerate(self.classes.dat):\n                if i['name'] == ch_class:\n                    cur_stat = int(i[stat])\n            for ndx, i in enumerate(self.races.dat):\n                if i['name'] == race:\n                    cur_stat += int(i[stat])\n            if cur_stat < 1:\n                cur_stat = 1\n            elif cur_stat > 10:\n                if stat not in ('Health', 'max_health'):\n                    cur_stat = 10\n            res[stat] = cur_stat\n        return res",
    "docstring": "create random stats based on the characters class and race\n        This looks up the tables from CharacterCollection to get\n        base stats and applies a close random fit"
  },
  {
    "code": "def _LogRecord_msg():\n    def _LogRecord_msgProperty(self):\n        return self.__msg\n    def _LogRecord_msgSetter(self, value):\n        self.__msg = to_unicode(value)\n    logging.LogRecord.msg = property(_LogRecord_msgProperty, _LogRecord_msgSetter)",
    "docstring": "Overrides logging.LogRecord.msg attribute to ensure variable content is stored as unicode."
  },
  {
    "code": "def with_pattern(pattern, regex_group_count=None):\n    def decorator(func):\n        func.pattern = pattern\n        func.regex_group_count = regex_group_count\n        return func\n    return decorator",
    "docstring": "Attach a regular expression pattern matcher to a custom type converter\n    function.\n\n    This annotates the type converter with the :attr:`pattern` attribute.\n\n    EXAMPLE:\n        >>> import parse\n        >>> @parse.with_pattern(r\"\\d+\")\n        ... def parse_number(text):\n        ...     return int(text)\n\n    is equivalent to:\n\n        >>> def parse_number(text):\n        ...     return int(text)\n        >>> parse_number.pattern = r\"\\d+\"\n\n    :param pattern: regular expression pattern (as text)\n    :param regex_group_count: Indicates how many regex-groups are in pattern.\n    :return: wrapped function"
  },
  {
    "code": "def log_game_start(self, players, terrain, numbers, ports):\n        self.reset()\n        self._set_players(players)\n        self._logln('{} v{}'.format(__name__, __version__))\n        self._logln('timestamp: {0}'.format(self.timestamp_str()))\n        self._log_players(players)\n        self._log_board_terrain(terrain)\n        self._log_board_numbers(numbers)\n        self._log_board_ports(ports)\n        self._logln('...CATAN!')",
    "docstring": "Begin a game.\n\n        Erase the log, set the timestamp, set the players, and write the log header.\n\n        The robber is assumed to start on the desert (or off-board).\n\n        :param players: iterable of catan.game.Player objects\n        :param terrain: list of 19 catan.board.Terrain objects.\n        :param numbers: list of 19 catan.board.HexNumber objects.\n        :param ports: list of catan.board.Port objects."
  },
  {
    "code": "def read(path):\n    url = '{}/{}/{}'.format(settings.VAULT_BASE_URL.rstrip('/'),\n                            settings.VAULT_BASE_SECRET_PATH.strip('/'),\n                            path.lstrip('/'))\n    headers = {'X-Vault-Token': settings.VAULT_ACCESS_TOKEN}\n    resp = requests.get(url, headers=headers)\n    if resp.ok:\n        return resp.json()['data']\n    else:\n        log.error('Failed VAULT GET request: %s %s', resp.status_code, resp.text)\n        raise Exception('Failed Vault GET request: {} {}'.format(resp.status_code, resp.text))",
    "docstring": "Read a secret from Vault REST endpoint"
  },
  {
    "code": "def set(self, key, value, confidence=100):\n        if value is None:\n            return\n        if key in self.info:\n            old_confidence, old_value = self.info.get(key)\n            if old_confidence >= confidence:\n                return\n        self.info[key] = (confidence, value)",
    "docstring": "Defines the given value with the given confidence, unless the same\n        value is already defined with a higher confidence level."
  },
  {
    "code": "def savemat(file_name, mdict, appendmat=True, format='7.3',\n            oned_as='row', store_python_metadata=True,\n            action_for_matlab_incompatible='error',\n            marshaller_collection=None, truncate_existing=False,\n            truncate_invalid_matlab=False, **keywords):\n    if float(format) < 7.3:\n        import scipy.io\n        scipy.io.savemat(file_name, mdict, appendmat=appendmat,\n                         format=format, oned_as=oned_as, **keywords)\n        return\n    if appendmat and not file_name.endswith('.mat'):\n        file_name = file_name + '.mat'\n    options = Options(store_python_metadata=store_python_metadata, \\\n        matlab_compatible=True, oned_as=oned_as, \\\n        action_for_matlab_incompatible=action_for_matlab_incompatible, \\\n        marshaller_collection=marshaller_collection)\n    writes(mdict=mdict, filename=file_name,\n           truncate_existing=truncate_existing,\n           truncate_invalid_matlab=truncate_invalid_matlab,\n           options=options)",
    "docstring": "Save a dictionary of python types to a MATLAB MAT file.\n\n    Saves the data provided in the dictionary `mdict` to a MATLAB MAT\n    file. `format` determines which kind/vesion of file to use. The\n    '7.3' version, which is HDF5 based, is handled by this package and\n    all types that this package can write are supported. Versions 4 and\n    5 are not HDF5 based, so everything is dispatched to the SciPy\n    package's ``scipy.io.savemat`` function, which this function is\n    modelled after (arguments not specific to this package have the same\n    names, etc.).\n\n    Parameters\n    ----------\n    file_name : str or file-like object\n        Name of the MAT file to store in. The '.mat' extension is\n        added on automatically if not present if `appendmat` is set to\n        ``True``. An open file-like object can be passed if the writing\n        is being dispatched to SciPy (`format` < 7.3).\n    mdict : dict\n        The dictionary of variables and their contents to store in the\n        file.\n    appendmat : bool, optional\n        Whether to append the '.mat' extension to `file_name` if it\n        doesn't already end in it or not.\n    format : {'4', '5', '7.3'}, optional\n        The MATLAB mat file format to use. The '7.3' format is handled\n        by this package while the '4' and '5' formats are dispatched to\n        SciPy.\n    oned_as : {'row', 'column'}, optional\n        Whether 1D arrays should be turned into row or column vectors.\n    store_python_metadata : bool, optional\n        Whether or not to store Python type information. Doing so allows\n        most types to be read back perfectly. Only applicable if not\n        dispatching to SciPy (`format` >= 7.3).\n    action_for_matlab_incompatible: str, optional\n        The action to perform writing data that is not MATLAB\n        compatible. The actions are to write the data anyways\n        ('ignore'), don't write the incompatible data ('discard'), or\n        throw a ``TypeNotMatlabCompatibleError`` exception.\n    marshaller_collection : MarshallerCollection, optional\n        Collection of marshallers to disk to use. Only applicable if\n        not dispatching to SciPy (`format` >= 7.3).\n    truncate_existing : bool, optional\n        Whether to truncate the file if it already exists before writing\n        to it.\n    truncate_invalid_matlab : bool, optional\n        Whether to truncate a file if the file doesn't have the proper\n        header (userblock in HDF5 terms) setup for MATLAB metadata to be\n        placed.\n    **keywords :\n        Additional keywords arguments to be passed onto\n        ``scipy.io.savemat`` if dispatching to SciPy (`format` < 7.3).\n\n    Raises\n    ------\n    ImportError\n        If `format` < 7.3 and the ``scipy`` module can't be found.\n    NotImplementedError\n        If writing a variable in `mdict` is not supported.\n    exceptions.TypeNotMatlabCompatibleError\n        If writing a type not compatible with MATLAB and\n        `action_for_matlab_incompatible` is set to ``'error'``.\n\n    Notes\n    -----\n    Writing the same data and then reading it back from disk using the\n    HDF5 based version 7.3 format (the functions in this package) or the\n    older format (SciPy functions) can lead to very different\n    results. Each package supports a different set of data types and\n    converts them to and from the same MATLAB types differently.\n\n    See Also\n    --------\n    loadmat : Equivelent function to do reading.\n    scipy.io.savemat : SciPy function this one models after and\n        dispatches to.\n    Options\n    writes : Function used to do the actual writing."
  },
  {
    "code": "def write(self, file_or_filename):\n        if isinstance(file_or_filename, basestring):\n            file = None\n            try:\n                file = open(file_or_filename, \"wb\")\n            except Exception, detail:\n                logger.error(\"Error opening %s.\" % detail)\n            finally:\n                if file is not None:\n                    self._write_data(file)\n                    file.close()\n        else:\n            file = file_or_filename\n            self._write_data(file)\n        return file",
    "docstring": "Writes the case data to file."
  },
  {
    "code": "def copytree_hardlink(source, dest):\n    copy2 = shutil.copy2\n    try:\n        shutil.copy2 = os.link\n        shutil.copytree(source, dest)\n    finally:\n        shutil.copy2 = copy2",
    "docstring": "Recursively copy a directory ala shutils.copytree, but hardlink files\n    instead of copying. Available on UNIX systems only."
  },
  {
    "code": "def info(ctx):\n    dev = ctx.obj['dev']\n    controller = ctx.obj['controller']\n    slot1, slot2 = controller.slot_status\n    click.echo('Slot 1: {}'.format(slot1 and 'programmed' or 'empty'))\n    click.echo('Slot 2: {}'.format(slot2 and 'programmed' or 'empty'))\n    if dev.is_fips:\n        click.echo('FIPS Approved Mode: {}'.format(\n            'Yes' if controller.is_in_fips_mode else 'No'))",
    "docstring": "Display status of YubiKey Slots."
  },
  {
    "code": "def prepare_editable_requirement(\n        self,\n        req,\n        require_hashes,\n        use_user_site,\n        finder\n    ):\n        assert req.editable, \"cannot prepare a non-editable req as editable\"\n        logger.info('Obtaining %s', req)\n        with indent_log():\n            if require_hashes:\n                raise InstallationError(\n                    'The editable requirement %s cannot be installed when '\n                    'requiring hashes, because there is no single file to '\n                    'hash.' % req\n                )\n            req.ensure_has_source_dir(self.src_dir)\n            req.update_editable(not self._download_should_save)\n            abstract_dist = make_abstract_dist(req)\n            with self.req_tracker.track(req):\n                abstract_dist.prep_for_dist(finder, self.build_isolation)\n            if self._download_should_save:\n                req.archive(self.download_dir)\n            req.check_if_exists(use_user_site)\n        return abstract_dist",
    "docstring": "Prepare an editable requirement"
  },
  {
    "code": "def Handle_Search(self, msg):\n        search_term = msg['object']['searchTerm']\n        results = self.db.searchForItem(search_term)\n        reply = {\"status\": \"OK\",\n                 \"type\": \"search\",\n                 \"object\": {\n                           \"received search\": msg['object']['searchTerm'],\n                           \"results\": results}\n                 }\n        return json.dumps(reply)",
    "docstring": "Handle a search.\n\n        :param msg: the received search\n        :type msg: dict\n        :returns: The message to reply with\n        :rtype: str"
  },
  {
    "code": "def _set_mtu_to_nics(self, conf):\n        for dom_name, dom_spec in conf.get('domains', {}).items():\n            for idx, nic in enumerate(dom_spec.get('nics', [])):\n                net = self._get_net(conf, dom_name, nic)\n                mtu = net.get('mtu', 1500)\n                if mtu != 1500:\n                    nic['mtu'] = mtu",
    "docstring": "For all the nics of all the domains in the conf that have MTU set,\n        save the MTU on the NIC definition.\n\n        Args:\n            conf (dict): Configuration spec to extract the domains from\n\n        Returns:\n            None"
  },
  {
    "code": "def team_info():\n    teams = __get_league_object().find('teams').findall('team')\n    output = []\n    for team in teams:\n        info = {}\n        for x in team.attrib:\n            info[x] = team.attrib[x]\n        output.append(info)\n    return output",
    "docstring": "Returns a list of team information dictionaries"
  },
  {
    "code": "def run(self, *args, **kw):\n        if self._runFunc is not None:\n            if 'mode' in kw: kw.pop('mode')\n            if '_save' in kw: kw.pop('_save')\n            return self._runFunc(self, *args, **kw)\n        else:\n            raise taskpars.NoExecError('No way to run task \"'+self.__taskName+\\\n                '\". You must either override the \"run\" method in your '+ \\\n                'ConfigObjPars subclass, or you must supply a \"run\" '+ \\\n                'function in your package.')",
    "docstring": "This may be overridden by a subclass."
  },
  {
    "code": "def _get_condition_json(self, index):\n    condition = self.condition_data[index]\n    condition_log = {\n      'name': condition[0],\n      'value': condition[1],\n      'type': condition[2],\n      'match': condition[3]\n    }\n    return json.dumps(condition_log)",
    "docstring": "Method to generate json for logging audience condition.\n\n    Args:\n      index: Index of the condition.\n\n    Returns:\n      String: Audience condition JSON."
  },
  {
    "code": "def iter_orgs(username, number=-1, etag=None):\n    return gh.iter_orgs(username, number, etag) if username else []",
    "docstring": "List the organizations associated with ``username``.\n\n    :param str username: (required), login of the user\n    :param int number: (optional), number of orgs to return. Default: -1,\n        return all of the issues\n    :param str etag: (optional), ETag from a previous request to the same\n        endpoint\n    :returns: generator of\n        :class:`Organization <github3.orgs.Organization>`"
  },
  {
    "code": "def replace_file(from_file, to_file):\n    try:\n        os.remove(to_file)\n    except OSError:\n        pass\n    copy(from_file, to_file)",
    "docstring": "Replaces to_file with from_file"
  },
  {
    "code": "def post(self, request, *args, **kwargs):\n        self.object = self.get_object()\n        form_class = self.get_form_class()\n        form = self.get_form(form_class)\n        formsets = self.get_formsets(form, saving=True)\n        valid_formsets = True\n        for formset in formsets.values():\n            if not formset.is_valid():\n                valid_formsets = False\n                break\n        if self.is_valid(form, formsets):\n            return self.form_valid(form, formsets)\n        else:\n            adminForm = self.get_admin_form(form)\n            adminFormSets = self.get_admin_formsets(formsets)\n            context = {\n                'adminForm': adminForm,\n                'formsets': adminFormSets,\n                'obj': self.object,\n            }\n            return self.form_invalid(form=form, **context)",
    "docstring": "Method for handling POST requests.\n        Validates submitted form and\n        formsets. Saves if valid, re displays\n        page with errors if invalid."
  },
  {
    "code": "def pdb(self):\n        if self.embed_disabled:\n            self.warning_log(\"Pdb is disabled when runned from the grid runner because of the multithreading\")\n            return False\n        if BROME_CONFIG['runner']['play_sound_on_pdb']:\n            say(BROME_CONFIG['runner']['sound_on_pdb'])\n        set_trace()",
    "docstring": "Start the python debugger\n\n        Calling pdb won't do anything in a multithread context"
  },
  {
    "code": "def _confirm_constant(a):\r\n    a = np.asanyarray(a)\r\n    return np.isclose(a, 1.0).all(axis=0).any()",
    "docstring": "Confirm `a` has volumn vector of 1s."
  },
  {
    "code": "def approximant(self, index):\n        if 'approximant' not in self.table.fieldnames:\n            raise ValueError(\"approximant not found in input file and no \"\n                \"approximant was specified on initialization\")\n        return self.table[\"approximant\"][index]",
    "docstring": "Return the name of the approximant ot use at the given index"
  },
  {
    "code": "def _try_lookup(table, value, default = \"\"):\n    try:\n        string = table[ value ]\n    except KeyError:\n        string = default\n    return string",
    "docstring": "try to get a string from the lookup table, return \"\" instead of key\n    error"
  },
  {
    "code": "def connection_made(self, transport):\n        self.transport = transport\n        self.transport.write(self.method.message.encode())\n        self.time_out_handle = self.loop.call_later(\n            TIME_OUT_LIMIT, self.time_out)",
    "docstring": "Connect to device is successful.\n\n        Start configuring RTSP session.\n        Schedule time out handle in case device doesn't respond."
  },
  {
    "code": "def create_cell_renderer_text(self, tree_view, title=\"title\", assign=0, editable=False):\n        renderer = Gtk.CellRendererText()\n        renderer.set_property('editable', editable)\n        column = Gtk.TreeViewColumn(title, renderer, text=assign)\n        tree_view.append_column(column)",
    "docstring": "Function creates a CellRendererText with title"
  },
  {
    "code": "def set_interval(self, timer_id, interval):\n        return lib.ztimerset_set_interval(self._as_parameter_, timer_id, interval)",
    "docstring": "Set timer interval. Returns 0 if OK, -1 on failure.\nThis method is slow, canceling the timer and adding a new one yield better performance."
  },
  {
    "code": "def _process(self, resource=None, data={}):\n        _data = data or self._data\n        rsc_url = self.get_rsc_endpoint(resource)\n        if _data:\n            req = requests.post(rsc_url, data=json.dumps(_data),\n                                headers=self.headers)\n        else:\n            req = requests.get(rsc_url, params=_data,\n                               headers=self.headers)\n        if req.status_code == 200:\n            self._response = json.loads(req.text)\n            if int(self._response['response_code']) == 00:\n                return (True, self._response)\n            else:\n                return (False, self._response['response_text'])\n        else:\n            return (500, \"Request Failed\")",
    "docstring": "Processes the current transaction\n\n        Sends an HTTP request to the PAYDUNYA API server"
  },
  {
    "code": "def sample(self, data_1, data_2, sample_size=15000,\n               blocked_proportion=.5, original_length_1=None,\n               original_length_2=None):\n        self._checkData(data_1, data_2)\n        self.active_learner = self.ActiveLearner(self.data_model)\n        self.active_learner.sample_product(data_1, data_2,\n                                           blocked_proportion,\n                                           sample_size,\n                                           original_length_1,\n                                           original_length_2)",
    "docstring": "Draws a random sample of combinations of records from\n        the first and second datasets, and initializes active\n        learning with this sample\n\n        Arguments:\n\n        data_1      -- Dictionary of records from first dataset, where the\n                       keys are record_ids and the values are dictionaries\n                       with the keys being field names\n        data_2      -- Dictionary of records from second dataset, same\n                       form as data_1\n\n        sample_size -- Size of the sample to draw"
  },
  {
    "code": "def put(self, *args, **kwargs):\n        self.inq.put((self._putcount, (args, kwargs)))\n        self._putcount += 1",
    "docstring": "place a new item into the pool to be handled by the workers\n\n        all positional and keyword arguments will be passed in as the arguments\n        to the function run by the pool's workers"
  },
  {
    "code": "def avg_time(self, source=None):\n        if source is None:\n            runtimes = []\n            for rec in self.source_stats.values():\n                runtimes.extend([r for r in rec.runtimes if r != 0])\n            return avg(runtimes)\n        else:\n            if callable(source):\n                return avg(self.source_stats[source.__name__].runtimes)\n            else:\n                return avg(self.source_stats[source].runtimes)",
    "docstring": "Returns the average time taken to scrape lyrics. If a string or a\n        function is passed as source, return the average time taken to scrape\n        lyrics from that source, otherwise return the total average."
  },
  {
    "code": "def random_seed_np_tf(seed):\n    if seed >= 0:\n        np.random.seed(seed)\n        tf.set_random_seed(seed)\n        return True\n    else:\n        return False",
    "docstring": "Seed numpy and tensorflow random number generators.\n\n    :param seed: seed parameter"
  },
  {
    "code": "def beginningPage(R):\n    p = R['PG']\n    if p.startswith('suppl '):\n        p = p[6:]\n    return p.split(' ')[0].split('-')[0].replace(';', '')",
    "docstring": "As pages may not be given as numbers this is the most accurate this function can be"
  },
  {
    "code": "async def request(self, method: base.String,\n                      data: Optional[Dict] = None,\n                      files: Optional[Dict] = None, **kwargs) -> Union[List, Dict, base.Boolean]:\n        return await api.make_request(self.session, self.__token, method, data, files,\n                                      proxy=self.proxy, proxy_auth=self.proxy_auth, timeout=self.timeout, **kwargs)",
    "docstring": "Make an request to Telegram Bot API\n\n        https://core.telegram.org/bots/api#making-requests\n\n        :param method: API method\n        :type method: :obj:`str`\n        :param data: request parameters\n        :type data: :obj:`dict`\n        :param files: files\n        :type files: :obj:`dict`\n        :return: result\n        :rtype: Union[List, Dict]\n        :raise: :obj:`aiogram.exceptions.TelegramApiError`"
  },
  {
    "code": "def get_conversation_between(self, um_from_user, um_to_user):\n        messages = self.filter(Q(sender=um_from_user, recipients=um_to_user,\n                                 sender_deleted_at__isnull=True) |\n                               Q(sender=um_to_user, recipients=um_from_user,\n                                 messagerecipient__deleted_at__isnull=True))\n        return messages",
    "docstring": "Returns a conversation between two users"
  },
  {
    "code": "def vsepg(v1, v2, ndim):\n    v1 = stypes.toDoubleVector(v1)\n    v2 = stypes.toDoubleVector(v2)\n    ndim = ctypes.c_int(ndim)\n    return libspice.vsepg_c(v1, v2, ndim)",
    "docstring": "Find the separation angle in radians between two double\n    precision vectors of arbitrary dimension. This angle is defined\n    as zero if either vector is zero.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsepg_c.html\n\n    :param v1: First vector \n    :type v1: Array of floats\n    :param v2: Second vector \n    :type v2: Array of floats\n    :param ndim: The number of elements in v1 and v2. \n    :type ndim: int\n    :return: separation angle in radians\n    :rtype: float"
  },
  {
    "code": "def read_dir_tree(self, file_hash):\n        json_d = self.read_index_object(file_hash, 'tree')\n        node = {'files' : json_d['files'], 'dirs' : {}}\n        for name, hsh in json_d['dirs'].iteritems(): node['dirs'][name] = self.read_dir_tree(hsh)\n        return node",
    "docstring": "Recursively read the directory structure beginning at hash"
  },
  {
    "code": "def is_lossy(label):\n    val = getkey(from_=label, keyword='INST_CMPRS_TYPE').decode().strip()\n    if val == 'LOSSY':\n        return True\n    else:\n        return False",
    "docstring": "Check Label file for the compression type."
  },
  {
    "code": "def _get_anchor(module_to_name, fullname):\n  if not _anchor_re.match(fullname):\n    raise ValueError(\"'%s' is not a valid anchor\" % fullname)\n  anchor = fullname\n  for module_name in module_to_name.values():\n    if fullname.startswith(module_name + \".\"):\n      rest = fullname[len(module_name)+1:]\n      if len(anchor) > len(rest):\n        anchor = rest\n  return anchor",
    "docstring": "Turn a full member name into an anchor.\n\n  Args:\n    module_to_name: Dictionary mapping modules to short names.\n    fullname: Fully qualified name of symbol.\n\n  Returns:\n    HTML anchor string.  The longest module name prefix of fullname is\n    removed to make the anchor.\n\n  Raises:\n    ValueError: If fullname uses characters invalid in an anchor."
  },
  {
    "code": "def union(self, rdds):\n        first_jrdd_deserializer = rdds[0]._jrdd_deserializer\n        if any(x._jrdd_deserializer != first_jrdd_deserializer for x in rdds):\n            rdds = [x._reserialize() for x in rdds]\n        cls = SparkContext._jvm.org.apache.spark.api.java.JavaRDD\n        jrdds = SparkContext._gateway.new_array(cls, len(rdds))\n        for i in range(0, len(rdds)):\n            jrdds[i] = rdds[i]._jrdd\n        return RDD(self._jsc.union(jrdds), self, rdds[0]._jrdd_deserializer)",
    "docstring": "Build the union of a list of RDDs.\n\n        This supports unions() of RDDs with different serialized formats,\n        although this forces them to be reserialized using the default\n        serializer:\n\n        >>> path = os.path.join(tempdir, \"union-text.txt\")\n        >>> with open(path, \"w\") as testFile:\n        ...    _ = testFile.write(\"Hello\")\n        >>> textFile = sc.textFile(path)\n        >>> textFile.collect()\n        [u'Hello']\n        >>> parallelized = sc.parallelize([\"World!\"])\n        >>> sorted(sc.union([textFile, parallelized]).collect())\n        [u'Hello', 'World!']"
  },
  {
    "code": "def mark_time(times, msg=None):\n    tt = time.clock()\n    times.append(tt)\n    if (msg is not None) and (len(times) > 1):\n        print msg, times[-1] - times[-2]",
    "docstring": "Time measurement utility.\n\n    Measures times of execution between subsequent calls using\n    time.clock(). The time is printed if the msg argument is not None.\n\n    Examples\n    --------\n\n    >>> times = []\n    >>> mark_time(times)\n    ... do something\n    >>> mark_time(times, 'elapsed')\n    elapsed 0.1\n    ... do something else\n    >>> mark_time(times, 'elapsed again')\n    elapsed again 0.05\n    >>> times\n    [0.10000000000000001, 0.050000000000000003]"
  },
  {
    "code": "def _get_sorted_action_keys(self, keys_list):\n        action_list = []\n        for key in keys_list:\n            if key.startswith('action-'):\n                action_list.append(key)\n        action_list.sort()\n        return action_list",
    "docstring": "This function returns only the elements starting with 'action-' in\n        'keys_list'. The returned list is sorted by the index appended to\n        the end of each element"
  },
  {
    "code": "async def generate_image(self, imgtype, face=None, hair=None):\n        if not isinstance(imgtype, str):\n            raise TypeError(\"type of 'imgtype' must be str.\")\n        if face and not isinstance(face, str):\n            raise TypeError(\"type of 'face' must be str.\")\n        if hair and not isinstance(hair, str):\n            raise TypeError(\"type of 'hair' must be str.\")\n        if (face or hair) and imgtype != 'awooo':\n            raise InvalidArguments('\\'face\\' and \\'hair\\' are arguments only available on the \\'awoo\\' image type')\n        url = f'https://api.weeb.sh/auto-image/generate?type={imgtype}' + (\"&face=\"+face if face else \"\")+ (\"&hair=\"+hair if hair else \"\")\n        async with aiohttp.ClientSession() as session:\n            async with session.get(url, headers=self.__headers) as resp:\n                if resp.status == 200:\n                    return await resp.read()\n                else:\n                    raise Exception((await resp.json())['message'])",
    "docstring": "Generate a basic image using the auto-image endpoint of weeb.sh.\n\n        This function is a coroutine.\n\n        Parameters:\n            imgtype: str - type of the generation to create, possible types are awooo, eyes, or won.\n            face: str - only used with awooo type, defines color of face\n            hair: str - only used with awooo type, defines color of hair/fur\n\n        Return Type: image data"
  },
  {
    "code": "def get_tx_identity_info(self, tx_ac):\n        rows = self._fetchall(self._queries['tx_identity_info'], [tx_ac])\n        if len(rows) == 0:\n            raise HGVSDataNotAvailableError(\n                \"No transcript definition for (tx_ac={tx_ac})\".format(tx_ac=tx_ac))\n        return rows[0]",
    "docstring": "returns features associated with a single transcript.\n\n        :param tx_ac: transcript accession with version (e.g., 'NM_199425.2')\n        :type tx_ac: str\n\n        # database output\n        -[ RECORD 1 ]--+-------------\n        tx_ac          | NM_199425.2\n        alt_ac         | NM_199425.2\n        alt_aln_method | transcript\n        cds_start_i    | 283\n        cds_end_i      | 1003\n        lengths        | {707,79,410}\n        hgnc           | VSX1"
  },
  {
    "code": "def add_item(self, item, **options):\n        export_item = {\n            \"item\": item.url,\n        }\n        export_item.update(options)\n        self.items.append(export_item)\n        return self",
    "docstring": "Add a layer or table item to the export.\n\n        :param Layer|Table item: The Layer or Table to add\n        :rtype: self"
  },
  {
    "code": "def _calculate_duration(start_time, finish_time):\n    if not (start_time and finish_time):\n        return 0\n    start = datetime.datetime.fromtimestamp(start_time)\n    finish = datetime.datetime.fromtimestamp(finish_time)\n    duration = finish - start\n    decimals = float((\"0.\" + str(duration.microseconds)))\n    return duration.seconds + decimals",
    "docstring": "Calculates how long it took to execute the testcase."
  },
  {
    "code": "def task_path(cls, project, location, queue, task):\n        return google.api_core.path_template.expand(\n            \"projects/{project}/locations/{location}/queues/{queue}/tasks/{task}\",\n            project=project,\n            location=location,\n            queue=queue,\n            task=task,\n        )",
    "docstring": "Return a fully-qualified task string."
  },
  {
    "code": "def _filehandle(self):\n        if self._fh and self._has_file_rolled():\n            try:\n                self._fh.close()\n            except Exception:\n                pass\n            self._fh = None\n        if not self._fh:\n            self._open_file(self.filename)\n            if not self.opened_before:\n                self.opened_before = True\n                self._fh.seek(0, os.SEEK_END)\n        return self._fh",
    "docstring": "Return a filehandle to the file being tailed"
  },
  {
    "code": "def copy(self, **params):\n        new_params = dict()\n        for name in ['owner', 'priority', 'key', 'final']:\n            new_params[name] = params.get(name, getattr(self, name))\n        return Route(**new_params)",
    "docstring": "Creates the new instance of the Route substituting the requested\n        parameters."
  },
  {
    "code": "def find_by(cls, **kwargs) -> 'Entity':\n        logger.debug(f'Lookup `{cls.__name__}` object with values '\n                     f'{kwargs}')\n        results = cls.query.filter(**kwargs).limit(1).all()\n        if not results:\n            raise ObjectNotFoundError(\n                f'`{cls.__name__}` object with values {[item for item in kwargs.items()]} '\n                f'does not exist.')\n        return results.first",
    "docstring": "Find a specific entity record that matches one or more criteria.\n\n        :param kwargs: named arguments consisting of attr_name and attr_value pairs to search on"
  },
  {
    "code": "def build_object(self, obj):\n        if not obj.exclude_from_static:\n            super(ShowPage, self).build_object(obj)",
    "docstring": "Override django-bakery to skip pages marked exclude_from_static"
  },
  {
    "code": "def backup(file_name, jail=None, chroot=None, root=None):\n    ret = __salt__['cmd.run'](\n        _pkg(jail, chroot, root) + ['backup', '-d', file_name],\n        output_loglevel='trace',\n        python_shell=False\n    )\n    return ret.split('...')[1]",
    "docstring": "Export installed packages into yaml+mtree file\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' pkg.backup /tmp/pkg\n\n    jail\n        Backup packages from the specified jail. Note that this will run the\n        command within the jail, and so the path to the backup file will be\n        relative to the root of the jail\n\n        CLI Example:\n\n        .. code-block:: bash\n\n            salt '*' pkg.backup /tmp/pkg jail=<jail name or id>\n\n    chroot\n        Backup packages from the specified chroot (ignored if ``jail`` is\n        specified). Note that this will run the command within the chroot, and\n        so the path to the backup file will be relative to the root of the\n        chroot.\n\n    root\n        Backup packages from the specified root (ignored if ``jail`` is\n        specified). Note that this will run the command within the root, and\n        so the path to the backup file will be relative to the root of the\n        root.\n\n        CLI Example:\n\n        .. code-block:: bash\n\n            salt '*' pkg.backup /tmp/pkg chroot=/path/to/chroot"
  },
  {
    "code": "def verify_existence_and_get(id, table, name=None, get_id=False):\n    where_clause = table.c.id == id\n    if name:\n        where_clause = table.c.name == name\n    if 'state' in table.columns:\n        where_clause = sql.and_(table.c.state != 'archived', where_clause)\n    query = sql.select([table]).where(where_clause)\n    result = flask.g.db_conn.execute(query).fetchone()\n    if result is None:\n        raise dci_exc.DCIException('Resource \"%s\" not found.' % id,\n                                   status_code=404)\n    if get_id:\n        return result.id\n    return result",
    "docstring": "Verify the existence of a resource in the database and then\n    return it if it exists, according to the condition, or raise an\n    exception.\n\n    :param id: id of the resource\n    :param table: the table object\n    :param name: the name of the row to look for\n    :param get_id: if True, return only the ID\n    :return:"
  },
  {
    "code": "def get_info(node_id, info_id):\n    exp = experiment(session)\n    node = models.Node.query.get(node_id)\n    if node is None:\n        return error_response(error_type=\"/info, node does not exist\")\n    info = models.Info.query.get(info_id)\n    if info is None:\n        return error_response(error_type=\"/info GET, info does not exist\",\n                              participant=node.participant)\n    elif (info.origin_id != node.id and\n          info.id not in\n            [t.info_id for t in node.transmissions(direction=\"incoming\",\n                                                   status=\"received\")]):\n        return error_response(error_type=\"/info GET, forbidden info\",\n                              status=403,\n                              participant=node.participant)\n    try:\n        exp.info_get_request(node=node, infos=info)\n        session.commit()\n    except:\n        return error_response(error_type=\"/info GET server error\",\n                              status=403,\n                              participant=node.participant)\n    return success_response(field=\"info\",\n                            data=info.__json__(),\n                            request_type=\"info get\")",
    "docstring": "Get a specific info.\n\n    Both the node and info id must be specified in the url."
  },
  {
    "code": "def save_model(self, request, obj, form, change):\n        if 'config.menu_structure' in form.changed_data:\n            from menus.menu_pool import menu_pool\n            menu_pool.clear(all=True)\n        return super(BlogConfigAdmin, self).save_model(request, obj, form, change)",
    "docstring": "Clear menu cache when changing menu structure"
  },
  {
    "code": "def validate_file(parser, arg):\n    if not os.path.isfile(arg):\n        parser.error(\"%s is not a file.\" % arg)\n    return arg",
    "docstring": "Validates that `arg` is a valid file."
  },
  {
    "code": "def smallest(heap, predicate):\n    n = heap.size()\n    items = deque([0])\n    while items:\n        current = items.popleft()\n        if current >= n:\n            continue\n        if predicate(heap.peek(current)):\n            return current\n        child1 = 2 * current + 1\n        child2 = child1 + 1\n        if child1 < n and child2 < n and heap.lt(child2, child1):\n            child1, child2 = child2, child1\n        if child1 < n:\n            items.append(child1)\n        if child2 < n:\n            items.append(child2)\n    raise NoMatchError()",
    "docstring": "Finds the index of the smallest item in the heap that matches the given\n    predicate.\n\n    :param heap:\n        Heap on which this search is being performed.\n    :param predicate:\n        Function that accepts an item from the heap and returns true or false.\n    :returns:\n        Index of the first item for which ``predicate`` returned true.\n    :raises NoMatchError:\n        If no matching items were found."
  },
  {
    "code": "def view_atype(self, atype):\n        if not self.cur_prj:\n            return\n        log.debug('Viewing atype %s', atype.name)\n        self.cur_atype = None\n        self.pages_tabw.setCurrentIndex(4)\n        self.atype_name_le.setText(atype.name)\n        self.atype_desc_pte.setPlainText(atype.description)\n        assetrootdata = treemodel.ListItemData(['Name', 'Description'])\n        assetrootitem = treemodel.TreeItem(assetrootdata)\n        self.atype_asset_model = treemodel.TreeModel(assetrootitem)\n        self.atype_asset_treev.setModel(self.atype_asset_model)\n        for a in djadapter.assets.filter(project=self.cur_prj, atype=atype):\n            assetdata = djitemdata.AssetItemData(a)\n            treemodel.TreeItem(assetdata, assetrootitem)\n        self.cur_atype = atype",
    "docstring": "View the given atype on the atype page\n\n        :param atype: the atype to view\n        :type atype: :class:`jukeboxcore.djadapter.models.Atype`\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def from_json(cls, json_doc):\n        d = json.loads(json_doc)\n        token = cls()\n        token.__dict__.update(d)\n        return token",
    "docstring": "Create and return a new Session Token based on the contents\n        of a JSON document.\n\n        :type json_doc: str\n        :param json_doc: A string containing a JSON document with a\n            previously saved Credentials object."
  },
  {
    "code": "def rst_filename_rel_autodoc_index(self, index_filename: str) -> str:\n        index_dir = dirname(abspath(expanduser(index_filename)))\n        return relpath(self.target_rst_filename, start=index_dir)",
    "docstring": "Returns the filename of the target RST file, relative to a specified\n        index file. Used to make the index refer to the RST."
  },
  {
    "code": "def _print_results(filename, data):\n    if filename:\n        with open(filename, 'wb') as f:\n            f.write(data)\n    else:\n        print data",
    "docstring": "Print data to a file or STDOUT.\n\n    Args:\n        filename (str or None): If None, print to STDOUT; otherwise, print\n            to the file with this name.\n        data (str): Data to print."
  },
  {
    "code": "def remove_padding(sequence):\n  length = sequence.pop('length')\n  sequence = tools.nested.map(lambda tensor: tensor[:length], sequence)\n  return sequence",
    "docstring": "Selects the used frames of a sequence, up to its length.\n\n  This function does not expect a batch of sequences, but a single sequence.\n  The sequence must be a dict with `length` key, which will removed from the\n  result.\n\n  Args:\n    sequence: Nested dict of tensors with time dimension.\n\n  Returns:\n    Nested dict of tensors with padding elements and `length` key removed."
  },
  {
    "code": "def list_lb_nat_rules(access_token, subscription_id, resource_group, lb_name):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/resourceGroups/', resource_group,\n                        '/providers/Microsoft.Network/loadBalancers/', lb_name,\n                        'inboundNatRules?api-version=', NETWORK_API])\n    return do_get(endpoint, access_token)",
    "docstring": "List the inbound NAT rules for a load balancer.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n        resource_group (str): Azure resource group name.\n        lb_name (str): Name of the load balancer.\n\n    Returns:\n        HTTP response. JSON body of load balancer NAT rules."
  },
  {
    "code": "def parse_content(self, text):\r\n        match = re.search(\r\n            self.usage_re_str.format(self.usage_name),\r\n            text,\r\n            flags=(re.DOTALL\r\n                   if self.case_sensitive\r\n                   else (re.DOTALL | re.IGNORECASE)))\r\n        if match is None:\r\n            return\r\n        dic = match.groupdict()\r\n        logger.debug(dic)\r\n        self.raw_content = dic['raw']\r\n        if dic['sep'] in ('\\n', '\\r\\n'):\r\n            self.formal_content = dic['section']\r\n            return\r\n        reallen = len(dic['name'])\r\n        replace = ''.ljust(reallen)\r\n        drop_name = match.expand('%s\\\\g<sep>\\\\g<section>' % replace)\r\n        self.formal_content = self.drop_started_empty_lines(drop_name).rstrip()",
    "docstring": "get Usage section and set to `raw_content`, `formal_content` of no\r\n        title and empty-line version"
  },
  {
    "code": "def _get_name(self):\n        if self.name is not None:\n            return self.name\n        if self.scoring_ is None:\n            return 'score'\n        if isinstance(self.scoring_, str):\n            return self.scoring_\n        if isinstance(self.scoring_, partial):\n            return self.scoring_.func.__name__\n        if isinstance(self.scoring_, _BaseScorer):\n            return self.scoring_._score_func.__name__\n        return self.scoring_.__name__",
    "docstring": "Find name of scoring function."
  },
  {
    "code": "def write_branch_data(self, file, padding=\"    \"):\n        attrs = ['%s=\"%s\"' % (k,v) for k,v in self.branch_attr.iteritems()]\n        attr_str = \", \".join(attrs)\n        for br in self.case.branches:\n            file.write(\"%s%s -> %s [%s];\\n\" % \\\n                (padding, br.from_bus.name, br.to_bus.name, attr_str))",
    "docstring": "Writes branch data in Graphviz DOT language."
  },
  {
    "code": "def register_nscf_task(self, *args, **kwargs):\n        kwargs[\"task_class\"] = NscfTask\n        return self.register_task(*args, **kwargs)",
    "docstring": "Register a nscf task."
  },
  {
    "code": "async def update_chat(self):\n        other = await self.bot.get_chat(self.id)\n        for key, value in other:\n            self[key] = value",
    "docstring": "User this method to update Chat data\n\n        :return: None"
  },
  {
    "code": "def readACTIONRECORD(self):\n        action = None\n        actionCode = self.readUI8()\n        if actionCode != 0:\n            actionLength = self.readUI16() if actionCode >= 0x80 else 0\n            action = SWFActionFactory.create(actionCode, actionLength)\n            action.parse(self)\n        return action",
    "docstring": "Read a SWFActionRecord"
  },
  {
    "code": "def to_json(self):\n        result = super(ContentType, self).to_json()\n        result.update({\n            'name': self.name,\n            'description': self.description,\n            'displayField': self.display_field,\n            'fields': [f.to_json() for f in self.fields]\n        })\n        return result",
    "docstring": "Returns the JSON representation of the content type."
  },
  {
    "code": "def search(self, **kw):\n        q = db.select(self.table).condition('status', 'active')\n        for k, v in kw:\n            q.condition(k, v)\n        data = q.execute()\n        users = []\n        for user in data:\n            users.append(self.load(user, self.model))\n        return users",
    "docstring": "Find the users match the condition in kw"
  },
  {
    "code": "def Tag(env, target, source, *more_tags, **kw_tags):\n    if not target:\n        target=source\n        first_tag=None\n    else:\n        first_tag=source\n    if first_tag:\n        kw_tags[first_tag[0]] = ''\n    if len(kw_tags) == 0 and len(more_tags) == 0:\n        raise UserError(\"No tags given.\")\n    for x in more_tags:\n        kw_tags[x] = ''\n    if not SCons.Util.is_List(target):\n        target=[target]\n    else:\n        target=env.Flatten(target)\n    for t in target:\n        for (k,v) in kw_tags.items():\n            if k[:10] != 'PACKAGING_':\n                k='PACKAGING_'+k\n            t.Tag(k, v)",
    "docstring": "Tag a file with the given arguments, just sets the accordingly named\n    attribute on the file object.\n\n    TODO: FIXME"
  },
  {
    "code": "def handle_profile_delete(self, sender, instance, **kwargs):\n    try:\n      self.handle_save(instance.user.__class__, instance.user)\n    except (get_profile_model().DoesNotExist):\n      pass",
    "docstring": "Custom handler for user profile delete"
  },
  {
    "code": "def decode(stream, *args, **kwargs):\n    encoding = kwargs.pop('encoding', DEFAULT_ENCODING)\n    decoder = get_decoder(encoding, stream, *args, **kwargs)\n    return decoder",
    "docstring": "A generator function to decode a datastream.\n\n    @param stream: AMF data to be decoded.\n    @type stream: byte data.\n    @kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}.\n    @return: A generator that will decode each element in the stream."
  },
  {
    "code": "def my_glob(pattern):\n    result = []\n    if pattern[0:4] == 'vos:':\n        dirname = os.path.dirname(pattern)\n        flist = listdir(dirname)\n        for fname in flist:\n            fname = '/'.join([dirname, fname])\n            if fnmatch.fnmatch(fname, pattern):\n                result.append(fname)\n    else:\n        result = glob(pattern)\n    return result",
    "docstring": "get a listing matching pattern\n\n    @param pattern:\n    @return:"
  },
  {
    "code": "def get_oqparam(job_ini, pkg=None, calculators=None, hc_id=None, validate=1,\n                **kw):\n    from openquake.calculators import base\n    OqParam.calculation_mode.validator.choices = tuple(\n        calculators or base.calculators)\n    if not isinstance(job_ini, dict):\n        basedir = os.path.dirname(pkg.__file__) if pkg else ''\n        job_ini = get_params([os.path.join(basedir, job_ini)])\n    if hc_id:\n        job_ini.update(hazard_calculation_id=str(hc_id))\n    job_ini.update(kw)\n    oqparam = OqParam(**job_ini)\n    if validate:\n        oqparam.validate()\n    return oqparam",
    "docstring": "Parse a dictionary of parameters from an INI-style config file.\n\n    :param job_ini:\n        Path to configuration file/archive or dictionary of parameters\n    :param pkg:\n        Python package where to find the configuration file (optional)\n    :param calculators:\n        Sequence of calculator names (optional) used to restrict the\n        valid choices for `calculation_mode`\n    :param hc_id:\n        Not None only when called from a post calculation\n    :param validate:\n        Flag. By default it is true and the parameters are validated\n    :param kw:\n        String-valued keyword arguments used to override the job.ini parameters\n    :returns:\n        An :class:`openquake.commonlib.oqvalidation.OqParam` instance\n        containing the validate and casted parameters/values parsed from\n        the job.ini file as well as a subdictionary 'inputs' containing\n        absolute paths to all of the files referenced in the job.ini, keyed by\n        the parameter name."
  },
  {
    "code": "def add_to_heap(self, heap, descriptors='stale', data='stale'):\n        if descriptors not in ['stale', 'all', 'none']:\n            raise ValueError(\"descriptors must be one of 'stale', 'all', 'none'\")\n        if data not in ['stale', 'all', 'none']:\n            raise ValueError(\"data must be one of 'stale', 'all', 'none'\")\n        for item in self._item_group.values():\n            info = self._get_info(item)\n            if (descriptors == 'all') or (descriptors == 'stale'\n                                          and self._descriptor_stale(item, info)):\n                heap.add_descriptor(item)\n                info.descriptor_cnt = self._descriptor_cnt\n            if item.value is not None:\n                if (data == 'all') or (data == 'stale' and info.version != item.version):\n                    heap.add_item(item)\n                    info.version = item.version\n        self._descriptor_cnt += 1\n        return heap",
    "docstring": "Update a heap to contains all the new items and item descriptors\n        since the last call.\n\n        Parameters\n        ----------\n        heap : :py:class:`Heap`\n            The heap to update.\n        descriptors : {'stale', 'all', 'none'}\n            Which descriptors to send. The default ('stale') sends only\n            descriptors that have not been sent, or have not been sent recently\n            enough according to the `descriptor_frequency` passed to the\n            constructor. The other options are to send all the descriptors or\n            none of them. Sending all descriptors is useful if a new receiver\n            is added which will be out of date.\n        data : {'stale', 'all', 'none'}\n            Which data items to send.\n        item_group : :py:class:`ItemGroup`, optional\n            If specified, uses the items from this item group instead of the\n            one passed to the constructor (which could be `None`).\n\n        Raises\n        ------\n        ValueError\n            if `descriptors` or `data` is not one of the legal values"
  },
  {
    "code": "def request_password_change_mail(self, password):\n        message = Msg(EMsg.ClientRequestChangeMail, extended=True)\n        message.body.password = password\n        resp = self.send_job_and_wait(message, timeout=10)\n        if resp is None:\n            return EResult.Timeout\n        else:\n            return EResult(resp.eresult)",
    "docstring": "Request password change mail\n\n        :param password: current account password\n        :type  password: :class:`str`\n        :return: result\n        :rtype: :class:`.EResult`"
  },
  {
    "code": "def _validate_question_area(self):\n        hazard_index = self.hazard_layer_combo.currentIndex()\n        exposure_index = self.exposure_layer_combo.currentIndex()\n        if hazard_index == -1 or exposure_index == -1:\n            if self.conflicting_plugin_detected:\n                message = conflicting_plugin_message()\n            else:\n                message = getting_started_message()\n            return False, message\n        else:\n            return True, None",
    "docstring": "Helper method to evaluate the current state of the dialog.\n\n        This function will determine if it is appropriate for the OK button to\n        be enabled or not.\n\n        .. note:: The enabled state of the OK button on the dialog will\n           NOT be updated (set True or False) depending on the outcome of\n           the UI readiness tests performed - **only** True or False\n           will be returned by the function.\n\n        :returns: A two-tuple where the first element is a Boolean reflecting\n         the results of the validation tests and the second is a message\n         indicating any reason why the validation may have failed.\n        :rtype: (Boolean, safe.messaging.Message)\n\n        Example::\n\n            flag,message = self._validate_question_area()"
  },
  {
    "code": "def listdir(self, folder_id='0', offset=None, limit=None, fields=None):\n\t\t'Get Box object, representing list of objects in a folder.'\n\t\tif fields is not None\\\n\t\t\tand not isinstance(fields, types.StringTypes): fields = ','.join(fields)\n\t\treturn self(\n\t\t\tjoin('folders', folder_id, 'items'),\n\t\t\tdict(offset=offset, limit=limit, fields=fields) )",
    "docstring": "Get Box object, representing list of objects in a folder."
  },
  {
    "code": "def perform_ops(self):\n        with self.db:\n            with closing(self.db.cursor()) as cursor:\n                cursor.execute('BEGIN TRANSACTION')\n                self._perform_ops(cursor)",
    "docstring": "Performs the stored operations on the database\n        connection."
  },
  {
    "code": "def weighted_random(sample, embedding):\n    unembeded = {}\n    for v, chain in iteritems(embedding):\n        vals = [sample[u] for u in chain]\n        unembeded[v] = random.choice(vals)\n    yield unembeded",
    "docstring": "Determines the sample values by weighed random choice.\n\n    Args:\n        sample (dict): A sample of the form {v: val, ...} where v is\n            a variable in the target graph and val is the associated value as\n            determined by a binary quadratic model sampler.\n        embedding (dict): The mapping from the source graph to the target graph.\n            Should be of the form {v: {s, ...}, ...} where v is a node in the\n            source graph and s is a node in the target graph.\n\n    Yields:\n        dict: The unembedded sample. When there is a chain break, the value\n        is chosen randomly, weighted by the frequency of the values\n        within the chain."
  },
  {
    "code": "def get_or_create(self, write_concern=None, auto_save=True,\n                      *q_objs, **query):\n        defaults = query.pop('defaults', {})\n        try:\n            doc = self.get(*q_objs, **query)\n            return doc, False\n        except self._document.DoesNotExist:\n            query.update(defaults)\n            doc = self._document(**query)\n            if auto_save:\n                doc.save(write_concern=write_concern)\n            return doc, True",
    "docstring": "Retrieve unique object or create, if it doesn't exist.\n\n        Returns a tuple of ``(object, created)``, where ``object`` is\n        the retrieved or created object and ``created`` is a boolean\n        specifying whether a new object was created.\n\n        Taken back from:\n\n        https://github.com/MongoEngine/mongoengine/\n        pull/1029/files#diff-05c70acbd0634d6d05e4a6e3a9b7d66b"
  },
  {
    "code": "def code_binary(item):\n    code_str = code(item)\n    if isinstance(code_str, six.string_types):\n        return code_str.encode('utf-8')\n    return code_str",
    "docstring": "Return a binary 'code' suitable for hashing."
  },
  {
    "code": "def local_manager_consider_for_user(self):\n        if not self.local_management_enabled:\n            return False\n        request = get_current_request()\n        if authenticated_userid(request) == security.ADMIN_USER:\n            return False\n        roles = security.authenticated_user(request).roles\n        if 'admin' in roles or 'manager' in roles:\n            return False\n        return True",
    "docstring": "Flag whether local manager ACL should be considered for current\n        authenticated user."
  },
  {
    "code": "def set_default_backend(self, backend_name):\n        if backend_name not in BACKENDS:\n            raise ValueError(f\"Unknown backend '{backend_name}'.\")\n        self._default_backend = backend_name",
    "docstring": "Set the default backend of this circuit.\n\n        This setting is only applied for this circuit.\n        If you want to change the default backend of all gates,\n        use `BlueqatGlobalSetting.set_default_backend()`.\n\n        After set the default backend by this method,\n        global setting is ignored even if `BlueqatGlobalSetting.set_default_backend()` is called.\n        If you want to use global default setting, call this method with backend_name=None.\n\n        Args:\n            backend_name (str or None): new default backend name.\n                If None is given, global setting is applied.\n\n        Raises:\n            ValueError: If `backend_name` is not registered backend."
  },
  {
    "code": "def parse_value(self, values):\n        result = self.get_default_value()\n        if not values:\n            return result\n        if not isinstance(values, list):\n            return values\n        return [self._cast_value(value) for value in values]",
    "docstring": "Cast value to proper collection."
  },
  {
    "code": "def find_defined_levels():\n    defined_levels = {}\n    for name in dir(logging):\n        if name.isupper():\n            value = getattr(logging, name)\n            if isinstance(value, int):\n                defined_levels[name] = value\n    return defined_levels",
    "docstring": "Find the defined logging levels.\n\n    :returns: A dictionary with level names as keys and integers as values.\n\n    Here's what the result looks like by default (when\n    no custom levels or level names have been defined):\n\n    >>> find_defined_levels()\n    {'NOTSET': 0,\n     'DEBUG': 10,\n     'INFO': 20,\n     'WARN': 30,\n     'WARNING': 30,\n     'ERROR': 40,\n     'FATAL': 50,\n     'CRITICAL': 50}"
  },
  {
    "code": "def walk(self, function, raise_errors=True,\n            call_on_sections=False, **keywargs):\n        out = {}\n        for i in range(len(self.scalars)):\n            entry = self.scalars[i]\n            try:\n                val = function(self, entry, **keywargs)\n                entry = self.scalars[i]\n                out[entry] = val\n            except Exception:\n                if raise_errors:\n                    raise\n                else:\n                    entry = self.scalars[i]\n                    out[entry] = False\n        for i in range(len(self.sections)):\n            entry = self.sections[i]\n            if call_on_sections:\n                try:\n                    function(self, entry, **keywargs)\n                except Exception:\n                    if raise_errors:\n                        raise\n                    else:\n                        entry = self.sections[i]\n                        out[entry] = False\n                entry = self.sections[i]\n            out[entry] = self[entry].walk(\n                function,\n                raise_errors=raise_errors,\n                call_on_sections=call_on_sections,\n                **keywargs)\n        return out",
    "docstring": "Walk every member and call a function on the keyword and value.\n\n        Return a dictionary of the return values\n\n        If the function raises an exception, raise the errror\n        unless ``raise_errors=False``, in which case set the return value to\n        ``False``.\n\n        Any unrecognised keyword arguments you pass to walk, will be pased on\n        to the function you pass in.\n\n        Note: if ``call_on_sections`` is ``True`` then - on encountering a\n        subsection, *first* the function is called for the *whole* subsection,\n        and then recurses into it's members. This means your function must be\n        able to handle strings, dictionaries and lists. This allows you\n        to change the key of subsections as well as for ordinary members. The\n        return value when called on the whole subsection has to be discarded.\n\n        See  the encode and decode methods for examples, including functions.\n\n        admonition:: caution\n\n        You can use ``walk`` to transform the names of members of a section\n        but you mustn't add or delete members.\n\n        >>> config = '''[XXXXsection]\n        ... XXXXkey = XXXXvalue'''.splitlines()\n        >>> cfg = ConfigObj(config)\n        >>> cfg\n        ConfigObj({'XXXXsection': {'XXXXkey': 'XXXXvalue'}})\n        >>> def transform(section, key):\n        ...     val = section[key]\n        ...     newkey = key.replace('XXXX', 'CLIENT1')\n        ...     section.rename(key, newkey)\n        ...     if isinstance(val, (tuple, list, dict)):\n        ...         pass\n        ...     else:\n        ...         val = val.replace('XXXX', 'CLIENT1')\n        ...         section[newkey] = val\n        >>> cfg.walk(transform, call_on_sections=True)\n        {'CLIENT1section': {'CLIENT1key': None}}\n        >>> cfg\n        ConfigObj({'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}})"
  },
  {
    "code": "def _create_messages(self, names, data, isDms=False):\n        chats = {}\n        empty_dms = []\n        formatter = SlackFormatter(self.__USER_DATA, data)\n        for name in names:\n            dir_path = os.path.join(self._PATH, name)\n            messages = []\n            day_files = glob.glob(os.path.join(dir_path, \"*.json\"))\n            if not day_files:\n                if isDms:\n                    empty_dms.append(name)\n                continue\n            for day in sorted(day_files):\n                with io.open(os.path.join(self._PATH, day), encoding=\"utf8\") as f:\n                    day_messages = json.load(f)\n                    messages.extend([Message(formatter, d) for d in day_messages])\n            chats[name] = messages\n        if isDms:\n            self._EMPTY_DMS = empty_dms\n        return chats",
    "docstring": "Creates object of arrays of messages from each json file specified by the names or ids\n\n        :param [str] names: names of each group of messages\n\n        :param [object] data: array of objects detailing where to get the messages from in\n        the directory structure\n\n        :param bool isDms: boolean value used to tell if the data is dm data so the function can\n        collect the empty dm directories and store them in memory only\n\n        :return: object of arrays of messages\n\n        :rtype: object"
  },
  {
    "code": "def name(self):\n        clonify_ids = [p.heavy['clonify']['id'] for p in self.heavies if 'clonify' in p.heavy]\n        if len(clonify_ids) > 0:\n            return clonify_ids[0]\n        return None",
    "docstring": "Returns the lineage name, or None if the name cannot be found."
  },
  {
    "code": "def install(environment, opts):\n    environment.require_data()\n    install_all(environment, opts['--clean'], verbose=not opts['--quiet'],\n        packages=opts['PACKAGE'])\n    for site in environment.sites:\n        environment = Environment.load(environment.name, site)\n        if 'web' in environment.containers_running():\n            manage.reload_(environment, {\n                '--address': opts['--address'],\n                '--background': False,\n                '--no-watch': False,\n                '--production': False,\n                'PORT': None,\n                '--syslog': False,\n                '--site-url': None,\n                '--interactive': False\n                })",
    "docstring": "Install or reinstall Python packages within this environment\n\nUsage:\n  datacats install [-q] [--address=IP] [ENVIRONMENT [PACKAGE ...]]\n  datacats install -c [q] [--address=IP] [ENVIRONMENT]\n\nOptions:\n  --address=IP          The address to bind to when reloading after install\n  -c --clean            Reinstall packages into a clean virtualenv\n  -q --quiet            Do not show output from installing packages and requirements.\n\nENVIRONMENT may be an environment name or a path to an environment directory.\nDefault: '.'"
  },
  {
    "code": "def getDetails(self):\n        response = self.pingdom.request('GET', 'checks/%s' % self.id)\n        self.__addDetails__(response.json()['check'])\n        return response.json()['check']",
    "docstring": "Update check details, returns dictionary of details"
  },
  {
    "code": "def render_to_texture(self, data, texture, offset, size):\n        assert isinstance(texture, Texture2D)\n        set_state(blend=False, depth_test=False)\n        orig_tex = Texture2D(255 - data, format='luminance', \n                             wrapping='clamp_to_edge', interpolation='nearest')\n        edf_neg_tex = self._render_edf(orig_tex)\n        orig_tex[:, :, 0] = data\n        edf_pos_tex = self._render_edf(orig_tex)\n        self.program_insert['u_texture'] = orig_tex\n        self.program_insert['u_pos_texture'] = edf_pos_tex\n        self.program_insert['u_neg_texture'] = edf_neg_tex\n        self.fbo_to[-1].color_buffer = texture\n        with self.fbo_to[-1]:\n            set_viewport(tuple(offset) + tuple(size))\n            self.program_insert.draw('triangle_strip')",
    "docstring": "Render a SDF to a texture at a given offset and size\n\n        Parameters\n        ----------\n        data : array\n            Must be 2D with type np.ubyte.\n        texture : instance of Texture2D\n            The texture to render to.\n        offset : tuple of int\n            Offset (x, y) to render to inside the texture.\n        size : tuple of int\n            Size (w, h) to render inside the texture."
  },
  {
    "code": "def ingest(self, token, endpoint=None, timeout=None, compress=None):\n        from . import ingest\n        if ingest.sf_pbuf:\n            client = ingest.ProtoBufSignalFxIngestClient\n        else:\n            _logger.warn('Protocol Buffers not installed properly; '\n                         'falling back to JSON.')\n            client = ingest.JsonSignalFxIngestClient\n        compress = compress if compress is not None else self._compress\n        return client(\n            token=token,\n            endpoint=endpoint or self._ingest_endpoint,\n            timeout=timeout or self._timeout,\n            compress=compress)",
    "docstring": "Obtain a datapoint and event ingest client."
  },
  {
    "code": "def send_request(self, job_request, message_expiry_in_seconds=None):\n        request_id = self.request_counter\n        self.request_counter += 1\n        meta = {}\n        wrapper = self._make_middleware_stack(\n            [m.request for m in self.middleware],\n            self._base_send_request,\n        )\n        try:\n            with self.metrics.timer('client.send.including_middleware', resolution=TimerResolution.MICROSECONDS):\n                wrapper(request_id, meta, job_request, message_expiry_in_seconds)\n            return request_id\n        finally:\n            self.metrics.commit()",
    "docstring": "Send a JobRequest, and return a request ID.\n\n        The context and control_extra arguments may be used to include extra values in the\n        context and control headers, respectively.\n\n        :param job_request: The job request object to send\n        :type job_request: JobRequest\n        :param message_expiry_in_seconds: How soon the message will expire if not received by a server (defaults to\n                                          sixty seconds unless the settings are otherwise)\n        :type message_expiry_in_seconds: int\n\n        :return: The request ID\n        :rtype: int\n\n        :raise: ConnectionError, InvalidField, MessageSendError, MessageSendTimeout, MessageTooLarge"
  },
  {
    "code": "def header_length(bytearray):\n    groups_of_3, leftover = divmod(len(bytearray), 3)\n    n = groups_of_3 * 4\n    if leftover:\n        n += 4\n    return n",
    "docstring": "Return the length of s when it is encoded with base64."
  },
  {
    "code": "def get_project(self, projectname):\n        cmd = [\"list\", \"accounts\", \"where\", \"name=%s\" % projectname]\n        results = self._read_output(cmd)\n        if len(results) == 0:\n            return None\n        elif len(results) > 1:\n            logger.error(\n                \"Command returned multiple results for '%s'.\" % projectname)\n            raise RuntimeError(\n                \"Command returned multiple results for '%s'.\" % projectname)\n        the_result = results[0]\n        the_project = the_result[\"Account\"]\n        if projectname.lower() != the_project.lower():\n            logger.error(\n                \"We expected projectname '%s' \"\n                \"but got projectname '%s'.\" % (projectname, the_project))\n            raise RuntimeError(\n                \"We expected projectname '%s' \"\n                \"but got projectname '%s'.\" % (projectname, the_project))\n        return the_result",
    "docstring": "Get the project details from Slurm."
  },
  {
    "code": "def get_object(self, obj_class, data=None, subset=None):\n        if subset:\n            if not isinstance(subset, list):\n                if isinstance(subset, basestring):\n                    subset = subset.split(\"&\")\n                else:\n                    raise TypeError\n        if data is None:\n            return self.get_list(obj_class, data, subset)\n        elif isinstance(data, (basestring, int)):\n            return self.get_individual_object(obj_class, data, subset)\n        elif isinstance(data, ElementTree.Element):\n            return self.get_new_object(obj_class, data)\n        else:\n            raise ValueError",
    "docstring": "Return a subclassed JSSObject instance by querying for\n        existing objects or posting a new object.\n\n        Args:\n            obj_class: The JSSObject subclass type to search for or\n                create.\n            data: The data parameter performs different operations\n                depending on the type passed.\n                None: Perform a list operation, or for non-container\n                    objects, return all data.\n                int: Retrieve an object with ID of <data>.\n                str: Retrieve an object with name of <str>. For some\n                    objects, this may be overridden to include searching\n                    by other criteria. See those objects for more info.\n                xml.etree.ElementTree.Element: Create a new object from\n                    xml.\n            subset:\n                A list of XML subelement tags to request (e.g.\n                ['general', 'purchasing']), OR an '&' delimited string\n                (e.g. 'general&purchasing'). This is not supported for\n                all JSSObjects.\n\n        Returns:\n            JSSObjectList: for empty or None arguments to data.\n            JSSObject: Returns an object of type obj_class for searches\n                and new objects.\n            (FUTURE) Will return None if nothing is found that match\n                the search criteria.\n\n        Raises:\n            TypeError: if subset not formatted properly.\n            JSSMethodNotAllowedError: if you try to perform an operation\n                not supported by that object type.\n            JSSGetError: If object searched for is not found.\n            JSSPostError: If attempted object creation fails."
  },
  {
    "code": "def certificate(self):\n        if not hasattr(self, '_certificate'):\n            cert_url = self._get_cert_url()\n            if not cert_url:\n                self._certificate = None\n                return self._certificate\n            try:\n                import requests\n            except ImportError:\n                raise ImproperlyConfigured(\"requests is required for bounce message verification.\")\n            try:\n                import M2Crypto\n            except ImportError:\n                raise ImproperlyConfigured(\"M2Crypto is required for bounce message verification.\")\n            response = requests.get(cert_url)\n            if response.status_code != 200:\n                logger.warning(u'Could not download certificate from %s: \"%s\"', cert_url, response.status_code)\n                self._certificate = None\n                return self._certificate\n            try:\n                self._certificate = M2Crypto.X509.load_cert_string(response.content)\n            except M2Crypto.X509.X509Error as e:\n                logger.warning(u'Could not load certificate from %s: \"%s\"', cert_url, e)\n                self._certificate = None\n        return self._certificate",
    "docstring": "Retrieves the certificate used to sign the bounce message.\n\n        TODO: Cache the certificate based on the cert URL so we don't have to\n        retrieve it for each bounce message. *We would need to do it in a\n        secure way so that the cert couldn't be overwritten in the cache*"
  },
  {
    "code": "def receive_message(self, message, data):\n        if self._socket_client.is_stopped:\n            return True\n        if data[MESSAGE_TYPE] == TYPE_CLOSE:\n            self._socket_client.disconnect_channel(message.source_id)\n            self._socket_client.receiver_controller.update_status()\n            return True\n        return False",
    "docstring": "Called when a connection message is received."
  },
  {
    "code": "def lru_cache(fn):\n    @wraps(fn)\n    def memoized_fn(*args):\n        pargs = pickle.dumps(args)\n        if pargs not in memoized_fn.cache:\n            memoized_fn.cache[pargs] = fn(*args)\n        return memoized_fn.cache[pargs]\n    for attr, value in iter(fn.__dict__.items()):\n        setattr(memoized_fn, attr, value)\n    memoized_fn.cache = {}\n    return memoized_fn",
    "docstring": "Memoization wrapper that can handle function attributes, mutable arguments, \n    and can be applied either as a decorator or at runtime.\n\n    :param fn: Function\n    :type fn: function\n    :returns: Memoized function\n    :rtype: function"
  },
  {
    "code": "def resolve_job(self, name):\n        for r in self.job_resolvers():\n            resolved_name = r(name)\n            if resolved_name is not None:\n                return resolved_name\n        return None",
    "docstring": "Attempt to resolve the task name in to a job name.\n\n        If no job resolver can resolve the task, i.e. they all return None,\n        return None.\n\n        Keyword arguments:\n        name -- Name of the task to be resolved."
  },
  {
    "code": "def check_publish_block(self, block_header):\n        if any(publisher_key != block_header.signer_public_key\n               for publisher_key in self._valid_block_publishers):\n            return False\n        if self._min_wait_time == 0:\n            return True\n        if self._min_wait_time < 0:\n            return False\n        assert self._min_wait_time > 0\n        if self._max_wait_time <= 0:\n            return self._start_time + self._min_wait_time <= time.time()\n        assert self._max_wait_time > 0\n        if self._max_wait_time <= self._min_wait_time:\n            return False\n        assert 0 < self._min_wait_time < self._max_wait_time\n        return self._start_time + self._wait_time <= time.time()",
    "docstring": "Check if a candidate block is ready to be claimed.\n\n        block_header (BlockHeader): the block_header to be checked if it\n            should be claimed\n        Returns:\n            Boolean: True if the candidate block_header should be claimed."
  },
  {
    "code": "def user_timeline(self, delegate, user=None, params={}, extra_args=None):\n        if user:\n            params['id'] = user\n        return self.__get('/statuses/user_timeline.xml', delegate, params,\n                          txml.Statuses, extra_args=extra_args)",
    "docstring": "Get the most recent updates for a user.\n\n        If no user is specified, the statuses for the authenticating user are\n        returned.\n\n        See search for example of how results are returned."
  },
  {
    "code": "def update_comment(self, comment_id, body):\n        path = '/msg/update_comment'\n        req = ET.Element('request')\n        ET.SubElement(req, 'comment_id').text = str(int(comment_id))\n        comment = ET.SubElement(req, 'comment')\n        ET.SubElement(comment, 'body').text = str(body)\n        return self._request(path, req)",
    "docstring": "Update a specific comment. This can be used to edit the content of an\n        existing comment."
  },
  {
    "code": "def parser(cls, buf, offset):\n        stats = OFPStats()\n        reserved, length = struct.unpack_from('!HH', buf, offset)\n        stats.length = length\n        offset += 4\n        length -= 4\n        fields = []\n        while length > 0:\n            n, value, _, field_len = ofproto.oxs_parse(buf, offset)\n            k, uv = ofproto.oxs_to_user(n, value, None)\n            fields.append((k, uv))\n            offset += field_len\n            length -= field_len\n        stats.fields = fields\n        return stats",
    "docstring": "Returns an object which is generated from a buffer including the\n        expression of the wire protocol of the flow stats."
  },
  {
    "code": "def OnNodeActivated(self, event):\n        self.activated_node = self.selected_node = event.node\n        self.squareMap.SetModel(event.node, self.adapter)\n        self.squareMap.SetSelected( event.node )\n        if editor:\n            if self.SourceShowFile(event.node):\n                if hasattr(event.node,'lineno'):\n                    self.sourceCodeControl.GotoLine(event.node.lineno)\n        self.RecordHistory()",
    "docstring": "Double-click or enter on a node in some control..."
  },
  {
    "code": "def set_naming_params(self, autonaming=None, prefix=None, suffix=None, name=None):\n        self._set('auto-procname', autonaming, cast=bool)\n        self._set('procname-prefix%s' % ('-spaced' if prefix and prefix.endswith(' ') else ''), prefix)\n        self._set('procname-append', suffix)\n        self._set('procname', name)\n        return self._section",
    "docstring": "Setups processes naming parameters.\n\n        :param bool autonaming: Automatically set process name to something meaningful.\n            Generated process names may be 'uWSGI Master', 'uWSGI Worker #', etc.\n\n        :param str|unicode prefix: Add prefix to process names.\n\n        :param str|unicode suffix: Append string to process names.\n\n        :param str|unicode name: Set process names to given static value."
  },
  {
    "code": "def get_feature(self, cat, img, feature):\n        filename = self.path(cat, img, feature)\n        data = loadmat(filename)\n        name = [k for k in list(data.keys()) if not k.startswith('__')]\n        if self.size is not None:\n            return imresize(data[name.pop()], self.size)\n        return data[name.pop()]",
    "docstring": "Load a feature from disk."
  },
  {
    "code": "def _write_cron_lines(user, lines):\n    lines = [salt.utils.stringutils.to_str(_l) for _l in lines]\n    path = salt.utils.files.mkstemp()\n    if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):\n        with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:\n            fp_.writelines(lines)\n        ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),\n                                      runas=user,\n                                      python_shell=False)\n    else:\n        with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:\n            fp_.writelines(lines)\n        ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),\n                                      python_shell=False)\n    os.remove(path)\n    return ret",
    "docstring": "Takes a list of lines to be committed to a user's crontab and writes it"
  },
  {
    "code": "def jsonify(obj):\n    if hasattr(obj, 'to_json'):\n        d = obj.to_json()\n        _push_metadata(d, obj)\n        return jsonify(d)\n    if isinstance(obj, np.ndarray):\n        return obj.tolist()\n    if isinstance(obj, (np.int32, np.int64)):\n        return int(obj)\n    if isinstance(obj, np.float64):\n        return float(obj)\n    if isinstance(obj, dict):\n        return _jsonify_dict(obj)\n    if hasattr(obj, '__dict__'):\n        return _jsonify_dict(obj.__dict__)\n    if isinstance(obj, (list, tuple)):\n        return [jsonify(item) for item in obj]\n    return obj",
    "docstring": "Return a JSON-encodable representation of an object, recursively using\n    any available ``to_json`` methods, converting NumPy arrays and datatypes to\n    native lists and types along the way."
  },
  {
    "code": "def draw_group_labels(self):\n        for i, label in enumerate(self.groups):\n            label_x = self.group_label_coords[\"x\"][i]\n            label_y = self.group_label_coords[\"y\"][i]\n            label_ha = self.group_label_aligns[\"has\"][i]\n            label_va = self.group_label_aligns[\"vas\"][i]\n            color = self.group_label_color[i]\n            self.ax.text(\n                s=label,\n                x=label_x,\n                y=label_y,\n                ha=label_ha,\n                va=label_va,\n                color=color,\n                fontsize=self.fontsize,\n                family=self.fontfamily,\n            )",
    "docstring": "Renders group labels to the figure."
  },
  {
    "code": "def run():\n    command = sys.argv[1].strip().lower()\n    print('[COMMAND]:', command)\n    if command == 'test':\n        return run_test()\n    elif command == 'build':\n        return run_build()\n    elif command == 'up':\n        return run_container()\n    elif command == 'serve':\n        import cauldron\n        cauldron.run_server(port=5010, public=True)",
    "docstring": "Execute the Cauldron container command"
  },
  {
    "code": "def _x_axis(self, draw_axes=True):\n        axis = self.svg.node(self.nodes['plot'], class_=\"axis y gauge\")\n        x, y = self.view((0, 0))\n        self.svg.node(axis, 'circle', cx=x, cy=y, r=4)",
    "docstring": "Override x axis to put a center circle in center"
  },
  {
    "code": "def bots_delete(self, bot):\n        self.client.bots.__getattr__(bot.name).__call__(_method=\"DELETE\", _params=dict(botName=bot.name))",
    "docstring": "Delete existing bot\n\n        :param bot: bot to delete\n        :type bot: Bot"
  },
  {
    "code": "def handle(self, **options):\n        self.set_options(**options)\n        os.makedirs(self.destination_path, exist_ok=True)\n        if self.interactive and any(os.listdir(self.destination_path)):\n            self.get_confirmation()\n        if self.clear:\n            self.clear_dir()\n        self.collect()",
    "docstring": "Collect tools."
  },
  {
    "code": "def plot_shade_mask(ax, ind, mask, facecolor='gray', alpha=0.5):\n    ymin, ymax = ax.get_ylim()\n    ax.fill_between(ind, ymin, ymax, where=mask,\n                    facecolor=facecolor, alpha=alpha)\n    return ax",
    "docstring": "Shade across x values where boolean mask is `True`\n\n    Args\n    ----\n    ax: pyplot.ax\n        Axes object to plot with a shaded region\n    ind: ndarray\n        The indices to use for the x-axis values of the data\n    mask: ndarray\n        Boolean mask array to determine which regions should be shaded\n    facecolor: matplotlib color\n        Color of the shaded area\n\n    Returns\n    -------\n    ax: pyplot.ax\n        Axes object with the shaded region added"
  },
  {
    "code": "def get_visualizations():\n    if not hasattr(g, 'visualizations'):\n        g.visualizations = {}\n        for VisClass in _get_visualization_classes():\n            vis = VisClass(get_model())\n            g.visualizations[vis.__class__.__name__] = vis\n    return g.visualizations",
    "docstring": "Get the available visualizations from the request context.  Put the\n    visualizations in the request context if they are not yet there.\n\n    Returns:\n        :obj:`list` of instances of :class:`.BaseVisualization` or\n        derived class"
  },
  {
    "code": "def insert_loan_entries(database, entries):\n    entries = map(clean_entry, entries)\n    database.loans.insert(entries, continue_on_error=True)",
    "docstring": "Insert a set of records of a loan report in the provided database.\n\n    Insert a set of new records into the provided database without checking\n    for conflicting entries.\n\n    @param db: The MongoDB database to operate on. The loans collection will be\n        used from this database.\n    @type db: pymongo.database.Database\n    @param entries: The entries to insert into the database.\n    @type entries: dict"
  },
  {
    "code": "def set_values(self,x):\n        x = numpy.atleast_2d(x)\n        x = x.real\n        C_inv = self.__C_inv__\n        theta = numpy.dot( x, C_inv )\n        self.theta = theta\n        return theta",
    "docstring": "Updates self.theta parameter. No returns values"
  },
  {
    "code": "def fit_transform(self, X, y=None):\n        U, S, V = self._fit(X)\n        U = U[:, : self.n_components_]\n        if self.whiten:\n            U *= np.sqrt(X.shape[0] - 1)\n        else:\n            U *= S[: self.n_components_]\n        return U",
    "docstring": "Fit the model with X and apply the dimensionality reduction on X.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            New data, where n_samples in the number of samples\n            and n_features is the number of features.\n\n        y : Ignored\n\n        Returns\n        -------\n        X_new : array-like, shape (n_samples, n_components)"
  },
  {
    "code": "def contains_plural_field(model, fields):\n    source_model = model\n    for orm_path in fields:\n        model = source_model\n        bits = orm_path.lstrip('+-').split('__')\n        for bit in bits[:-1]:\n            field = model._meta.get_field(bit)\n            if field.many_to_many or field.one_to_many:\n                return True\n            model = get_model_at_related_field(model, bit)\n    return False",
    "docstring": "Returns a boolean indicating if ``fields`` contains a relationship to multiple items."
  },
  {
    "code": "def binary_arguments_to_tensors(x1, x2):\n  if not isinstance(x1, Tensor) and not isinstance(x2, Tensor):\n    raise ValueError(\"at least one of x1 and x2 must be an mtf Tensor\")\n  elif isinstance(x1, Tensor) and isinstance(x2, Tensor):\n    return x1, x2\n  elif isinstance(x1, Tensor):\n    return x1, import_tf_tensor(\n        x1.mesh, tf.convert_to_tensor(x2, dtype=x1.dtype), Shape([]))\n  else:\n    return import_tf_tensor(x2.mesh, tf.convert_to_tensor(x1, dtype=x2.dtype),\n                            Shape([])), x2",
    "docstring": "Convert argument of a binary operation to Tensors.\n\n  Args:\n    x1: a Tensor or something convertible to a tf Scalar\n    x2: a Tensor or something convertible to a tf Scalar\n\n  Returns:\n    new_x1: a Tensor\n    new_x2: a Tensor\n\n  Raises:\n    ValueError: on failure"
  },
  {
    "code": "def split(self, pat, side='left'):\n        check_type(pat, str)\n        check_type(side, str)\n        _split_mapping = {\n            'left': 0,\n            'right': 1\n        }\n        if side not in _split_mapping:\n            raise ValueError('Can only select left or right side of split')\n        return _series_str_result(self, weld_str_split, pat=pat, side=_split_mapping[side])",
    "docstring": "Split once each element from the left and select a side to return.\n\n        Note this is unlike pandas split in that it essentially combines the split with a select.\n\n        Parameters\n        ----------\n        pat : str\n        side : {'left', 'right'}\n            Which side of the split to select and return in each element.\n\n        Returns\n        -------\n        Series"
  },
  {
    "code": "def get_rule_table(rules):\n    table = formatting.Table(['Id', 'KeyName'], \"Rules\")\n    for rule in rules:\n        table.add_row([rule['id'], rule['keyName']])\n    return table",
    "docstring": "Formats output from get_all_rules and returns a table."
  },
  {
    "code": "def apply_defaults(self, other_config):\n        if isinstance(other_config, self.__class__):\n            self.config.load_from_dict(other_config.config, overwrite=False)\n        else:\n            self.config.load_from_dict(other_config, overwrite=False)",
    "docstring": "Applies default values from a different ConfigObject or ConfigKey object to this ConfigObject.\n\n        If there are any values in this object that are also in the default object, it will use the values from this object."
  },
  {
    "code": "def en010(self, value=None):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type float '\n                                 'for field `en010`'.format(value))\n        self._en010 = value",
    "docstring": "Corresponds to IDD Field `en010`\n        mean coincident dry-bulb temperature to\n        Enthalpy corresponding to 1.0% annual cumulative frequency of occurrence\n\n        Args:\n            value (float): value for IDD Field `en010`\n                Unit: kJ/kg\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def a_send_line(text, ctx):\n    if hasattr(text, '__iter__'):\n        try:\n            ctx.ctrl.sendline(text.next())\n        except StopIteration:\n            ctx.finished = True\n    else:\n        ctx.ctrl.sendline(text)\n    return True",
    "docstring": "Send text line to the controller followed by `os.linesep`."
  },
  {
    "code": "def consume(self, amount=1):\n        current = self.leak()\n        if current + amount > self.capacity:\n            return False\n        self._incr(amount)\n        return True",
    "docstring": "Consume one or more units from the bucket."
  },
  {
    "code": "def pretty_print_str(self):\n        retval = ''\n        todo = [self.root]\n        while todo:\n            current = todo.pop()\n            for char in reversed(sorted(current.keys())):\n                todo.append(current[char])\n            indent = ' ' * (current.depth * 2)\n            retval += indent + current.__unicode__() + '\\n'\n        return retval.rstrip('\\n')",
    "docstring": "Create a string to pretty-print this trie to standard output."
  },
  {
    "code": "def get_axis_value(self, axis):\n\t\tif self.type != EventType.POINTER_AXIS:\n\t\t\traise AttributeError(_wrong_meth.format(self.type))\n\t\treturn self._libinput.libinput_event_pointer_get_axis_value(\n\t\t\tself._handle, axis)",
    "docstring": "Return the axis value of the given axis.\n\n\t\tThe interpretation of the value depends on the axis. For the two\n\t\tscrolling axes :attr:`~libinput.constant.PointerAxis.SCROLL_VERTICAL`\n\t\tand :attr:`~libinput.constant.PointerAxis.SCROLL_HORIZONTAL`, the value\n\t\tof the event is in relative scroll units, with the positive direction\n\t\tbeing down or right, respectively. For the interpretation of the value,\n\t\tsee :attr:`axis_source`.\n\n\t\tIf :meth:`has_axis` returns False for an axis, this method returns 0\n\t\tfor that axis.\n\n\t\tFor pointer events that are not of type\n\t\t:attr:`~libinput.constant.Event.POINTER_AXIS`, this method raises\n\t\t:exc:`AttributeError`.\n\n\t\tArgs:\n\t\t\taxis (~libinput.constant.PointerAxis): The axis who's value to get.\n\t\tReturns:\n\t\t\tfloat: The axis value of this event.\n\t\tRaises:\n\t\t\tAttributeError"
  },
  {
    "code": "def _use_widgets(objs):\n    from ..models.widgets import Widget\n    return _any(objs, lambda obj: isinstance(obj, Widget))",
    "docstring": "Whether a collection of Bokeh objects contains a any Widget\n\n    Args:\n        objs (seq[Model or Document]) :\n\n    Returns:\n        bool"
  },
  {
    "code": "def regexp_replace(str, pattern, replacement):\n    r\n    sc = SparkContext._active_spark_context\n    jc = sc._jvm.functions.regexp_replace(_to_java_column(str), pattern, replacement)\n    return Column(jc)",
    "docstring": "r\"\"\"Replace all substrings of the specified string value that match regexp with rep.\n\n    >>> df = spark.createDataFrame([('100-200',)], ['str'])\n    >>> df.select(regexp_replace('str', r'(\\d+)', '--').alias('d')).collect()\n    [Row(d=u'-----')]"
  },
  {
    "code": "def as_fixture(self, name=None):\n        if name is None:\n            name = self.name\n        def deco(f):\n            @functools.wraps(f)\n            def wrapper(*args, **kw):\n                with self:\n                    kw[name] = self\n                    return f(*args, **kw)\n            return wrapper\n        return deco",
    "docstring": "A decorator to inject this container into a function as a test fixture."
  },
  {
    "code": "def ToManagedObject(self):\n\t\tfrom Ucs import ClassFactory\n\t\tcln = UcsUtils.WordU(self.classId)\n\t\tmo = ClassFactory(cln)\n\t\tif mo and (isinstance(mo, ManagedObject) == True):\n\t\t\tmetaClassId = UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId)\n\t\t\tfor property in self.properties:\n\t\t\t\tif UcsUtils.WordU(property) in UcsUtils.GetUcsPropertyMetaAttributeList(metaClassId):\n\t\t\t\t\tmo.setattr(UcsUtils.WordU(property), self.properties[property])\n\t\t\t\telse:\n\t\t\t\t\tWriteUcsWarning(\"Property %s Not Exist in MO %s\" % (UcsUtils.WordU(property), metaClassId))\n\t\t\tif len(self.child):\n\t\t\t\tfor ch in self.child:\n\t\t\t\t\tmoch = ch.ToManagedObject()\n\t\t\t\t\tmo.child.append(moch)\n\t\t\treturn mo\n\t\telse:\n\t\t\treturn None",
    "docstring": "Method creates and returns an object of ManagedObject class using the classId and information from the\n\t\tGeneric managed object."
  },
  {
    "code": "def i2repr(self, pkt, packed_seconds):\n        time_struct = time.gmtime(self._convert_seconds(packed_seconds))\n        return time.strftime(\"%a %b %d %H:%M:%S %Y\", time_struct)",
    "docstring": "Convert the internal representation to a nice one using the RFC\n           format."
  },
  {
    "code": "def process_train_set(hdf5_file, train_archive, patch_archive, n_train,\n                      wnid_map, shuffle_seed=None):\n    producer = partial(train_set_producer, train_archive=train_archive,\n                       patch_archive=patch_archive, wnid_map=wnid_map)\n    consumer = partial(image_consumer, hdf5_file=hdf5_file,\n                       num_expected=n_train, shuffle_seed=shuffle_seed)\n    producer_consumer(producer, consumer)",
    "docstring": "Process the ILSVRC2010 training set.\n\n    Parameters\n    ----------\n    hdf5_file : :class:`h5py.File` instance\n        HDF5 file handle to which to write. Assumes `features`, `targets`\n        and `filenames` already exist and have first dimension larger than\n        `n_train`.\n    train_archive :  str or file-like object\n        Filename or file handle for the TAR archive of training images.\n    patch_archive :  str or file-like object\n        Filename or file handle for the TAR archive of patch images.\n    n_train : int\n        The number of items in the training set.\n    wnid_map : dict\n        A dictionary mapping WordNet IDs to class indices.\n    shuffle_seed : int or sequence, optional\n        Seed for a NumPy random number generator that permutes the\n        training set on disk. If `None`, no permutation is performed\n        (this is the default)."
  },
  {
    "code": "def do_layout(self, *args):\n        if self.size == [1, 1]:\n            return\n        for i in range(0, len(self.decks)):\n            self.layout_deck(i)",
    "docstring": "Layout each of my decks"
  },
  {
    "code": "def register_function_compilation(self, func, compilation_cbk, listclass):\n        self.compilations_function[func] = {\n            'callback':  compilation_cbk,\n            'listclass': listclass\n        }",
    "docstring": "Register given compilation method for given function.\n\n        :param str path: Function name.\n        :param callable compilation_cbk: Compilation callback to be called.\n        :param class listclass: List class to use for lists."
  },
  {
    "code": "def _determine_redirect(self, url, verb, timeout=15, headers={}):\n        requests_verb = getattr(self.session, verb)\n        r = requests_verb(url, timeout=timeout, headers=headers, allow_redirects=False)\n        redirect = 300 <= r.status_code < 400\n        url_new = url\n        if redirect:\n            redirect_url = r.headers['Location']\n            url_new = redirect_url\n            relative_redirect = not redirect_url.startswith('http')\n            if relative_redirect:\n                url_new = url\n            base_redir = base_url(redirect_url)\n            base_supplied = base_url(url)\n            same_base = base_redir == base_supplied\n            if same_base:\n                url_new = url\n        return url_new",
    "docstring": "Internal redirect function, focuses on HTTP and worries less about\n        application-y stuff.\n        @param url: the url to check\n        @param verb: the verb, e.g. head, or get.\n        @param timeout: the time, in seconds, that requests should wait\n            before throwing an exception.\n        @param headers: a set of headers as expected by requests.\n        @return: the url that needs to be scanned. It may be equal to the url\n            parameter if no redirect is needed."
  },
  {
    "code": "def get_current_consumer_offsets(\n    kafka_client,\n    group,\n    topics,\n    raise_on_error=True,\n):\n    topics = _verify_topics_and_partitions(kafka_client, topics, raise_on_error)\n    group_offset_reqs = [\n        OffsetFetchRequestPayload(topic, partition)\n        for topic, partitions in six.iteritems(topics)\n        for partition in partitions\n    ]\n    group_offsets = {}\n    send_api = kafka_client.send_offset_fetch_request_kafka\n    if group_offset_reqs:\n        group_resps = send_api(\n            group=group,\n            payloads=group_offset_reqs,\n            fail_on_error=False,\n            callback=pluck_topic_offset_or_zero_on_unknown,\n        )\n        for resp in group_resps:\n            group_offsets.setdefault(\n                resp.topic,\n                {},\n            )[resp.partition] = resp.offset\n    return group_offsets",
    "docstring": "Get current consumer offsets.\n\n    NOTE: This method does not refresh client metadata. It is up to the caller\n    to avoid using stale metadata.\n\n    If any partition leader is not available, the request fails for all the\n    other topics. This is the tradeoff of sending all topic requests in batch\n    and save both in performance and Kafka load.\n\n    :param kafka_client: a connected KafkaToolClient\n    :param group: kafka group_id\n    :param topics: topic list or dict {<topic>: [partitions]}\n    :param raise_on_error: if False the method ignores missing topics and\n      missing partitions. It still may fail on the request send.\n    :returns: a dict topic: partition: offset\n    :raises:\n      :py:class:`kafka_utils.util.error.UnknownTopic`: upon missing\n      topics and raise_on_error=True\n\n      :py:class:`kafka_utils.util.error.UnknownPartition`: upon missing\n      partitions and raise_on_error=True\n\n      FailedPayloadsError: upon send request error."
  },
  {
    "code": "def serialize(self, keep_readonly=False):\n        serializer = Serializer(self._infer_class_models())\n        return serializer._serialize(self, keep_readonly=keep_readonly)",
    "docstring": "Return the JSON that would be sent to azure from this model.\n\n        This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`.\n\n        :param bool keep_readonly: If you want to serialize the readonly attributes\n        :returns: A dict JSON compatible object\n        :rtype: dict"
  },
  {
    "code": "def clear(self):\n        for i in range(4):\n            while len(self._panels[i]):\n                key = sorted(list(self._panels[i].keys()))[0]\n                panel = self.remove(key)\n                panel.setParent(None)\n                panel.deleteLater()",
    "docstring": "Removes all panel from the CodeEditor."
  },
  {
    "code": "def _raise_on_incompatible(left, right):\n    if isinstance(right, np.ndarray):\n        other_freq = None\n    elif isinstance(right, (ABCPeriodIndex, PeriodArray, Period, DateOffset)):\n        other_freq = right.freqstr\n    else:\n        other_freq = _delta_to_tick(Timedelta(right)).freqstr\n    msg = DIFFERENT_FREQ.format(cls=type(left).__name__,\n                                own_freq=left.freqstr,\n                                other_freq=other_freq)\n    raise IncompatibleFrequency(msg)",
    "docstring": "Helper function to render a consistent error message when raising\n    IncompatibleFrequency.\n\n    Parameters\n    ----------\n    left : PeriodArray\n    right : DateOffset, Period, ndarray, or timedelta-like\n\n    Raises\n    ------\n    IncompatibleFrequency"
  },
  {
    "code": "def _create_bv_circuit(self, bit_map: Dict[str, str]) -> Program:\n        unitary, _ = self._compute_unitary_oracle_matrix(bit_map)\n        full_bv_circuit = Program()\n        full_bv_circuit.defgate(\"BV-ORACLE\", unitary)\n        full_bv_circuit.inst(X(self.ancilla), H(self.ancilla))\n        full_bv_circuit.inst([H(i) for i in self.computational_qubits])\n        full_bv_circuit.inst(\n            tuple([\"BV-ORACLE\"] + sorted(self.computational_qubits + [self.ancilla], reverse=True)))\n        full_bv_circuit.inst([H(i) for i in self.computational_qubits])\n        return full_bv_circuit",
    "docstring": "Implementation of the Bernstein-Vazirani Algorithm.\n\n        Given a list of input qubits and an ancilla bit, all initially in the\n        :math:`\\\\vert 0\\\\rangle` state, create a program that can find :math:`\\\\vec{a}` with one\n        query to the given oracle.\n\n        :param Dict[String, String] bit_map: truth-table of a function for Bernstein-Vazirani with\n            the keys being all possible bit vectors strings and the values being the function values\n        :rtype: Program"
  },
  {
    "code": "def find_and_reserve_fcp(self, assigner_id):\n        fcp_list = self.db.get_from_assigner(assigner_id)\n        if not fcp_list:\n            new_fcp = self.db.find_and_reserve()\n            if new_fcp is None:\n                LOG.info(\"no more fcp to be allocated\")\n                return None\n            LOG.debug(\"allocated %s fcp for %s assigner\" %\n                      (new_fcp, assigner_id))\n            return new_fcp\n        else:\n            old_fcp = fcp_list[0][0]\n            self.db.reserve(fcp_list[0][0])\n            return old_fcp",
    "docstring": "reserve the fcp to assigner_id\n\n        The function to reserve a fcp for user\n        1. Check whether assigner_id has a fcp already\n           if yes, make the reserve of that record to 1\n        2. No fcp, then find a fcp and reserve it\n\n        fcp will be returned, or None indicate no fcp"
  },
  {
    "code": "def _coord(self):\n        _coord = []\n        _node = self\n        while _node.parent:\n            _idx = _node.parent.childs.index(_node)\n            _coord.insert(0, _idx)\n            _node = _node.parent\n        return tuple(_coord)",
    "docstring": "Attribute indicating the tree coordinates for this node.\n\n        The tree coordinates of a node are expressed as a tuple of the\n        indices of the node and its ancestors, for example:\n        A grandchild node with node path \n        `/root.name/root.childs[2].name/root.childs[2].childs[0].name` \n        would have coordinates `(2,0)`.\n        The root node _coord is an empty tuple: `()`\n\n        :returns: the tree coordinates for this node.\n        :rtype: tuple"
  },
  {
    "code": "def corpus_page_generator(corpus_files, tmp_dir, max_page_size_exp):\n  for remote_filepath in corpus_files:\n    filepath = maybe_copy_file_to_directory(remote_filepath, tmp_dir)\n    tf.logging.info(\"Reading from \" + filepath)\n    command = [\"7z\", \"x\", \"-so\", filepath]\n    tf.logging.info(\"Running command: %s\", command)\n    p = subprocess.Popen(command, stdout=subprocess.PIPE, bufsize=-1)\n    for page in file_page_generator(p.stdout, 2**max_page_size_exp):\n      yield page",
    "docstring": "Generate pages from a list of .7z encoded history dumps.\n\n  Args:\n    corpus_files: a list of strings\n    tmp_dir: a string\n    max_page_size_exp: an integer\n\n  Yields:\n    strings"
  },
  {
    "code": "def receive_reply(self, msg, content):\n        reply_head = content.head()\n        if reply_head == 'error':\n            comment = content.gets('comment')\n            logger.error('Got error reply: \"%s\"' % comment)\n        else:\n            extractions = content.gets('ekb')\n            self.extractions.append(extractions)\n        self.reply_counter -= 1\n        if self.reply_counter == 0:\n            self.exit(0)",
    "docstring": "Handle replies with reading results."
  },
  {
    "code": "def end_of_line(event):\n    \" Move to the end of the line. \"\n    buff = event.current_buffer\n    buff.cursor_position += buff.document.get_end_of_line_position()",
    "docstring": "Move to the end of the line."
  },
  {
    "code": "def iterator(self):\n        default_language = getattr(self, '_default_language', None)\n        for obj in super(MultilingualModelQuerySet, self).iterator():\n            obj._default_language = default_language\n            yield obj",
    "docstring": "Add the default language information to all returned objects."
  },
  {
    "code": "def add_group(self, groupname, statements):\n\t\tmsg = OmapiMessage.open(b\"group\")\n\t\tmsg.message.append((\"create\", struct.pack(\"!I\", 1)))\n\t\tmsg.obj.append((\"name\", groupname))\n\t\tmsg.obj.append((\"statements\", statements))\n\t\tresponse = self.query_server(msg)\n\t\tif response.opcode != OMAPI_OP_UPDATE:\n\t\t\traise OmapiError(\"add group failed\")",
    "docstring": "Adds a group\n\t\t@type groupname: bytes\n\t\t@type statements: str"
  },
  {
    "code": "def diagonal_line(xi=None, yi=None, *, ax=None, c=None, ls=None, lw=None, zorder=3):\n    if ax is None:\n        ax = plt.gca()\n    if xi is None:\n        xi = ax.get_xlim()\n    if yi is None:\n        yi = ax.get_ylim()\n    if c is None:\n        c = matplotlib.rcParams[\"grid.color\"]\n    if ls is None:\n        ls = matplotlib.rcParams[\"grid.linestyle\"]\n    if lw is None:\n        lw = matplotlib.rcParams[\"grid.linewidth\"]\n    if ax is None:\n        ax = plt.gca()\n    diag_min = max(min(xi), min(yi))\n    diag_max = min(max(xi), max(yi))\n    line = ax.plot([diag_min, diag_max], [diag_min, diag_max], c=c, ls=ls, lw=lw, zorder=zorder)\n    return line",
    "docstring": "Plot a diagonal line.\n\n    Parameters\n    ----------\n    xi : 1D array-like (optional)\n        The x axis points. If None, taken from axis limits. Default is None.\n    yi : 1D array-like\n        The y axis points. If None, taken from axis limits. Default is None.\n    ax : axis (optional)\n        Axis to plot on. If none is supplied, the current axis is used.\n    c : string (optional)\n        Line color. Default derives from rcParams grid color.\n    ls : string (optional)\n        Line style. Default derives from rcParams linestyle.\n    lw : float (optional)\n        Line width. Default derives from rcParams linewidth.\n    zorder : number (optional)\n        Matplotlib zorder. Default is 3.\n\n    Returns\n    -------\n    matplotlib.lines.Line2D object\n        The plotted line."
  },
  {
    "code": "def decode(self, data, password=None):\n\t\tself.password = password\n\t\tself.raw = gntp.shim.u(data)\n\t\tparts = self.raw.split('\\r\\n\\r\\n')\n\t\tself.info = self._parse_info(self.raw)\n\t\tself.headers = self._parse_dict(parts[0])",
    "docstring": "Decode GNTP Message\n\n\t\t:param string data:"
  },
  {
    "code": "def as_dict(self, quiet: bool = False, infer_type_and_cast: bool = False):\n        if infer_type_and_cast:\n            params_as_dict = infer_and_cast(self.params)\n        else:\n            params_as_dict = self.params\n        if quiet:\n            return params_as_dict\n        def log_recursively(parameters, history):\n            for key, value in parameters.items():\n                if isinstance(value, dict):\n                    new_local_history = history + key  + \".\"\n                    log_recursively(value, new_local_history)\n                else:\n                    logger.info(history + key + \" = \" + str(value))\n        logger.info(\"Converting Params object to dict; logging of default \"\n                    \"values will not occur when dictionary parameters are \"\n                    \"used subsequently.\")\n        logger.info(\"CURRENTLY DEFINED PARAMETERS: \")\n        log_recursively(self.params, self.history)\n        return params_as_dict",
    "docstring": "Sometimes we need to just represent the parameters as a dict, for instance when we pass\n        them to PyTorch code.\n\n        Parameters\n        ----------\n        quiet: bool, optional (default = False)\n            Whether to log the parameters before returning them as a dict.\n        infer_type_and_cast : bool, optional (default = False)\n            If True, we infer types and cast (e.g. things that look like floats to floats)."
  },
  {
    "code": "def _is_socket(cls, stream):\n        try:\n            fd = stream.fileno()\n        except ValueError:\n            return False\n        sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW)\n        try:\n            sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)\n        except socket.error as ex:\n            if ex.args[0] != errno.ENOTSOCK:\n                return True\n        else:\n            return True",
    "docstring": "Check if the given stream is a socket."
  },
  {
    "code": "def get_setting(*args, **kwargs):\n    for name in args:\n        if hasattr(settings, name):\n            return getattr(settings, name)\n    if kwargs.get('raise_error', False):\n        setting_url = url % args[0].lower().replace('_', '-')\n        raise ImproperlyConfigured('Please make sure you specified at '\n            'least one of these settings: %s \\r\\nDocumentation: %s'\n            % (args, setting_url))\n    return kwargs.get('default_value', None)",
    "docstring": "Get a setting and raise an appropriate user friendly error if\n    the setting is not found."
  },
  {
    "code": "def _response(self, pdu):\n        if _debug: UDPDirector._debug(\"_response %r\", pdu)\n        addr = pdu.pduSource\n        peer = self.peers.get(addr, None)\n        if not peer:\n            peer = self.actorClass(self, addr)\n        peer.response(pdu)",
    "docstring": "Incoming datagrams are routed through an actor."
  },
  {
    "code": "def walk(self, oid, host, port, community):\n        ret = {}\n        if not isinstance(oid, tuple):\n            oid = self._convert_to_oid(oid)\n        host = socket.gethostbyname(host)\n        snmpAuthData = cmdgen.CommunityData(\n            'agent-{}'.format(community),\n            community)\n        snmpTransportData = cmdgen.UdpTransportTarget(\n            (host, port),\n            int(self.config['timeout']),\n            int(self.config['retries']))\n        resultTable = self.snmpCmdGen.nextCmd(snmpAuthData,\n                                              snmpTransportData,\n                                              oid)\n        varBindTable = resultTable[3]\n        for varBindTableRow in varBindTable:\n            for o, v in varBindTableRow:\n                ret[str(o)] = v.prettyPrint()\n        return ret",
    "docstring": "Perform an SNMP walk on a given OID"
  },
  {
    "code": "def init_word_db(cls, name, text):\n        text = text.replace('\\n', ' ').replace('\\r', ' ')\n        words = [w.strip() for w in text.split(' ') if w.strip()]\n        assert len(words) > 2, \\\n                'Database text sources must contain 3 or more words.'\n        freqs = {}\n        for i in range(len(words) - 2):\n            w1 = words[i]\n            w2 = words[i + 1]\n            w3 = words[i + 2]\n            key = (w1, w2)\n            if key in freqs:\n                freqs[key].append(w3)\n            else:\n                freqs[key] = [w3]\n        cls._dbs[name] = {\n            'freqs': freqs,\n            'words': words,\n            'word_count': len(words) - 2\n            }",
    "docstring": "Initialize a database of words for the maker with the given name"
  },
  {
    "code": "def blt(f: List[SYM], x: List[SYM]) -> Dict[str, Any]:\n    J = ca.jacobian(f, x)\n    nblock, rowperm, colperm, rowblock, colblock, coarserow, coarsecol = J.sparsity().btf()\n    return {\n        'J': J,\n        'nblock': nblock,\n        'rowperm': rowperm,\n        'colperm': colperm,\n        'rowblock': rowblock,\n        'colblock': colblock,\n        'coarserow': coarserow,\n        'coarsecol': coarsecol\n    }",
    "docstring": "Sort equations by dependence"
  },
  {
    "code": "def _debugGraph(self):\n        print(\"Len of graph: \", len(self.rdflib_graph))\n        for x, y, z in self.rdflib_graph:\n            print(x, y, z)",
    "docstring": "internal util to print out contents of graph"
  },
  {
    "code": "def parse_log_line(line):\n    matches = re.search(r'^\\[([^\\]]+)\\] ([^:]+: .*)', line)\n    error = re.search(r'Traceback', line)\n    if error:\n        return {'line': line, 'step': 'error'}\n    if not matches:\n        return {'line': line, 'step': None}\n    tstamp = matches.group(1)\n    msg = matches.group(2)\n    if not msg.find('Timing: ') >= 0:\n        return {'line': line, 'step': None}\n    when = datetime.strptime(tstamp, '%Y-%m-%dT%H:%MZ').replace(\n        tzinfo=pytz.timezone('UTC'))\n    step = msg.split(\":\")[-1].strip()\n    return {'line': line, 'step': step, 'when': when}",
    "docstring": "Parses a log line and returns it with more information\n\n    :param line: str - A line from a bcbio-nextgen log\n    :returns dict: A dictionary containing the line, if its a new step if its a Traceback or if the\n                   analysis is finished"
  },
  {
    "code": "def draw(board, term, cells):\n    for (x, y), state in board.iteritems():\n        with term.location(x, y):\n            print cells[state],",
    "docstring": "Draw a board to the terminal."
  },
  {
    "code": "def reverse(self):\n        if self.closed():\n            raise ValueError(\"Attempt to call reverse() on a \"\n                             \"closed Queryable.\")\n        try:\n            r = reversed(self._iterable)\n            return self._create(r)\n        except TypeError:\n            pass\n        return self._create(self._generate_reverse_result())",
    "docstring": "Returns the sequence reversed.\n\n        Note: This method uses deferred execution, but the whole source\n            sequence is consumed once execution commences.\n\n        Returns:\n            The source sequence in reverse order.\n\n        Raises:\n            ValueError: If the Queryable is closed()."
  },
  {
    "code": "def vector_str(p, decimal_places=2, print_zero=True):\n    style = '{0:.' + str(decimal_places) + 'f}'\n    return '[{0}]'.format(\", \".join([' ' if not print_zero and a == 0 else style.format(a) for a in p]))",
    "docstring": "Pretty-print the vector values."
  },
  {
    "code": "def _trigger(self):\n        self._completed.set()\n        for callback in self._callbacks:\n            callback(self)",
    "docstring": "Trigger all callbacks registered to this Future.\n\n        This method is called internally by the batch once the batch\n        completes.\n\n        Args:\n            message_id (str): The message ID, as a string."
  },
  {
    "code": "def nearest_subpackage(cls, package, all_packages):\n    def shared_prefix(candidate):\n      zipped = zip(package.split('.'), candidate.split('.'))\n      matching = itertools.takewhile(lambda pair: pair[0] == pair[1], zipped)\n      return [pair[0] for pair in matching]\n    shared_packages = [_f for _f in map(shared_prefix, all_packages) if _f]\n    return '.'.join(max(shared_packages, key=len)) if shared_packages else package",
    "docstring": "Given a package, find its nearest parent in all_packages."
  },
  {
    "code": "def draw(self):\r\n        glPushAttrib(GL_ALL_ATTRIB_BITS)\r\n        self.draw_score()\r\n        for sprite in self:\r\n            sprite.draw()\r\n        glPopAttrib()",
    "docstring": "Draw all the sprites in the system using their renderers.\r\n\r\n        This method is convenient to call from you Pyglet window's\r\n        on_draw handler to redraw particles when needed."
  },
  {
    "code": "def remove_metadata_key(self, obj, key):\n        meta_dict = {key: \"\"}\n        return self.set_metadata(obj, meta_dict)",
    "docstring": "Removes the specified key from the object's metadata. If the key does\n        not exist in the metadata, nothing is done."
  },
  {
    "code": "def predecessors(self, node, exclude_compressed=True):\n        preds = super(Graph, self).predecessors(node)\n        if exclude_compressed:\n            return [n for n in preds if not self.node[n].get('compressed', False)]\n        else:\n            return preds",
    "docstring": "Returns the list of predecessors of a given node\n\n        Parameters\n        ----------\n        node : str\n            The target node\n\n        exclude_compressed : boolean\n            If true, compressed nodes are excluded from the predecessors list\n\n        Returns\n        -------\n        list\n            List of predecessors nodes"
  },
  {
    "code": "def normalize_result(result, default, threshold=0.2):\n    if result is None:\n        return default\n    if result.get('confidence') is None:\n        return default\n    if result.get('confidence') < threshold:\n        return default\n    return normalize_encoding(result.get('encoding'),\n                              default=default)",
    "docstring": "Interpret a chardet result."
  },
  {
    "code": "def merge_tags(left, right, factory=Tags):\n    if isinstance(left, Mapping):\n        tags = dict(left)\n    elif hasattr(left, 'tags'):\n        tags = _tags_to_dict(left.tags)\n    else:\n        tags = _tags_to_dict(left)\n    if isinstance(right, Mapping):\n        tags.update(right)\n    elif hasattr(left, 'tags'):\n        tags.update(_tags_to_dict(right.tags))\n    else:\n        tags.update(_tags_to_dict(right))\n    return factory(**tags)",
    "docstring": "Merge two sets of tags into a new troposphere object\n\n    Args:\n        left (Union[dict, troposphere.Tags]): dictionary or Tags object to be\n            merged with lower priority\n        right (Union[dict, troposphere.Tags]): dictionary or Tags object to be\n            merged with higher priority\n        factory (type): Type of object to create. Defaults to the troposphere\n            Tags class."
  },
  {
    "code": "def create_exclude_rules(args):\n    global _cached_exclude_rules\n    if _cached_exclude_rules is not None:\n        return _cached_exclude_rules\n    rules = []\n    for excl_path in args.exclude:\n        abspath = os.path.abspath(os.path.join(args.root, excl_path))\n        rules.append((abspath, True))\n    for incl_path in args.include:\n        abspath = os.path.abspath(os.path.join(args.root, incl_path))\n        rules.append((abspath, False))\n    _cached_exclude_rules = sorted(rules, key=lambda p: p[0])\n    return _cached_exclude_rules",
    "docstring": "Creates the exlude rules"
  },
  {
    "code": "def difference(self, *others):\n        return self.copy(super(NGram, self).difference(*others))",
    "docstring": "Return the difference of two or more sets as a new set.\n\n        >>> from ngram import NGram\n        >>> a = NGram(['spam', 'eggs'])\n        >>> b = NGram(['spam', 'ham'])\n        >>> list(a.difference(b))\n        ['eggs']"
  },
  {
    "code": "def hasKey(self, key, notNone=False):\n        result = []\n        result_tracker = []\n        for counter, row in enumerate(self.table):\n            (target, _, value) = internal.dict_crawl(row, key)\n            if target:\n                if notNone==False or not value is None:\n                    result.append(row)\n                    result_tracker.append(self.index_track[counter])\n        self.table = result\n        self.index_track = result_tracker\n        return self",
    "docstring": "Return entries where the key is present.\n\n        Example of use:\n\n        >>> test = [\n        ...    {\"name\": \"Jim\",   \"age\": 18, \"income\": 93000, \"wigs\": 68       },\n        ...    {\"name\": \"Larry\", \"age\": 18,                  \"wigs\": [3, 2, 9]},\n        ...    {\"name\": \"Joe\",   \"age\": 20, \"income\": None , \"wigs\": [1, 2, 3]},\n        ...    {\"name\": \"Bill\",  \"age\": 19, \"income\": 29000                   },\n        ... ]\n        >>> print PLOD(test).hasKey(\"income\").returnString()\n        [\n            {age: 18, income: 93000, name: 'Jim' , wigs:        68},\n            {age: 20, income: None , name: 'Joe' , wigs: [1, 2, 3]},\n            {age: 19, income: 29000, name: 'Bill', wigs: None     }\n        ]\n        >>> print PLOD(test).hasKey(\"income\", notNone=True).returnString()\n        [\n            {age: 18, income: 93000, name: 'Jim' , wigs:   68},\n            {age: 19, income: 29000, name: 'Bill', wigs: None}\n        ]\n        \n        .. versionadded:: 0.1.2\n        \n        :param key:\n           The dictionary key (or cascading list of keys) to locate.\n        :param notNone:\n           If True, then None is the equivalent of a missing key. Otherwise, a key\n           with a value of None is NOT considered missing.\n        :returns: self"
  },
  {
    "code": "def sub_tags(self, *tags, **kw):\n        records = [x for x in self.sub_records if x.tag in tags]\n        if kw.get('follow', True):\n            records = [rec.ref if isinstance(rec, Pointer) else rec\n                       for rec in records]\n        return records",
    "docstring": "Returns list of direct sub-records matching any tag name.\n\n        Unlike :py:meth:`sub_tag` method this method does not support\n        hierarchical paths and does not resolve pointers.\n\n        :param str tags: Names of the sub-record tag\n        :param kw: Keyword arguments, only recognized keyword is `follow`\n            with the same meaning as in :py:meth:`sub_tag`.\n        :return: List of `Records`, possibly empty."
  },
  {
    "code": "def createSQL(self, sql, args=()):\n        before = time.time()\n        self._execSQL(sql, args)\n        after = time.time()\n        if after - before > 2.0:\n            log.msg('Extremely long CREATE: %s' % (after - before,))\n            log.msg(sql)",
    "docstring": "For use with auto-committing statements such as CREATE TABLE or CREATE\n        INDEX."
  },
  {
    "code": "def get_dependants(project_name):\n    for package in get_installed_distributions(user_only=ENABLE_USER_SITE):\n        if is_dependant(package, project_name):\n            yield package.project_name",
    "docstring": "Yield dependants of `project_name`."
  },
  {
    "code": "def from_Suite(suite, maxwidth=80):\n    subtitle = str(len(suite.compositions)) + ' Compositions' if suite.subtitle\\\n         == '' else suite.subtitle\n    result = os.linesep.join(add_headers(\n        maxwidth,\n        suite.title,\n        subtitle,\n        suite.author,\n        suite.email,\n        suite.description,\n        ))\n    hr = maxwidth * '='\n    n = os.linesep\n    result = n + hr + n + result + n + hr + n + n\n    for comp in suite:\n        c = from_Composition(comp, maxwidth)\n        result += c + n + hr + n + n\n    return result",
    "docstring": "Convert a mingus.containers.Suite to an ASCII tablature string, complete\n    with headers.\n\n    This function makes use of the Suite's title, subtitle, author, email\n    and description attributes."
  },
  {
    "code": "def _create_trial_info(self, expr_dir):\n        meta = self._build_trial_meta(expr_dir)\n        self.logger.debug(\"Create trial for %s\" % meta)\n        trial_record = TrialRecord.from_json(meta)\n        trial_record.save()",
    "docstring": "Create information for given trial.\n\n        Meta file will be loaded if exists, and the trial information\n        will be saved in db backend.\n\n        Args:\n            expr_dir (str): Directory path of the experiment."
  },
  {
    "code": "def get_span_kind_as_int(self, span):\n        kind = None\n        if \"span.kind\" in span.tags:\n            if span.tags[\"span.kind\"] in self.entry_kind:\n                kind = 1\n            elif span.tags[\"span.kind\"] in self.exit_kind:\n                kind = 2\n            else:\n                kind = 3\n        return kind",
    "docstring": "Will retrieve the `span.kind` tag and return the appropriate integer value for the Instana backend or\n            None if the tag is set to something we don't recognize.\n\n        :param span: The span to search for the `span.kind` tag\n        :return: Integer"
  },
  {
    "code": "def render_filter(self, next_filter):\n        next(next_filter)\n        while True:\n            data = (yield)\n            res = [self.cell_format(access(data)) for access in self.accessors]\n            next_filter.send(res)",
    "docstring": "Produce formatted output from the raw data stream."
  },
  {
    "code": "def spectrogram(t_signal, frame_width=FRAME_WIDTH, overlap=FRAME_STRIDE):\n    frame_width = min(t_signal.shape[0], frame_width)\n    w = np.hanning(frame_width)\n    num_components = frame_width // 2 + 1\n    num_frames = 1 + (len(t_signal) - frame_width) // overlap\n    f_signal = np.empty([num_frames, num_components], dtype=np.complex_)\n    for i, t in enumerate(range(0, len(t_signal) - frame_width, overlap)):\n        f_signal[i] = rfft(w * t_signal[t:t + frame_width])\n    return 20 * np.log10(1 + np.absolute(f_signal))",
    "docstring": "Calculate the magnitude spectrogram of a single-channel time-domain signal\n    from the real frequency components of the STFT with a hanning window\n    applied to each frame. The frame size and overlap between frames should\n    be specified in number of samples."
  },
  {
    "code": "def check_status_code(response, codes=None):\n    codes = codes or [200]\n    if response.status_code not in codes:\n        raise StatusCodeError(response.status_code)",
    "docstring": "Checks response.status_code is in codes.\n\n    :param requests.request response: Requests response\n    :param list codes: List of accepted codes or callable\n    :raises: StatusCodeError if code invalid"
  },
  {
    "code": "def init_centers_widths(self, R):\n        kmeans = KMeans(\n            init='k-means++',\n            n_clusters=self.K,\n            n_init=10,\n            random_state=100)\n        kmeans.fit(R)\n        centers = kmeans.cluster_centers_\n        widths = self._get_max_sigma(R) * np.ones((self.K, 1))\n        return centers, widths",
    "docstring": "Initialize prior of centers and widths\n\n        Returns\n        -------\n\n        centers : 2D array, with shape [K, n_dim]\n            Prior of factors' centers.\n\n        widths : 1D array, with shape [K, 1]\n            Prior of factors' widths."
  },
  {
    "code": "def recv_blocking(conn, msglen):\n    msg = b''\n    while len(msg) < msglen:\n        maxlen = msglen-len(msg)\n        if maxlen > 4096:\n            maxlen = 4096\n        tmpmsg = conn.recv(maxlen)\n        if not tmpmsg:\n            raise RuntimeError(\"socket connection broken\")\n        msg += tmpmsg\n        logging.debug(\"Msglen: %d of %d\", len(msg), msglen)\n    logging.debug(\"Message: %s\", msg)\n    return msg",
    "docstring": "Recieve data until msglen bytes have been received."
  },
  {
    "code": "def result(self, timeout=None):\n        if not self._poll(timeout).HasField('response'):\n            raise GaxError(self._operation.error.message)\n        return _from_any(self._result_type, self._operation.response)",
    "docstring": "Enters polling loop on OperationsClient.get_operation, and once\n        Operation.done is true, then returns Operation.response if successful or\n        throws GaxError if not successful.\n\n        This method will wait up to timeout seconds. If the call hasn't\n        completed in timeout seconds, then a RetryError will be raised. timeout\n        can be an int or float. If timeout is not specified or None, there is no\n        limit to the wait time."
  },
  {
    "code": "def list_active_vms(cwd=None):\n    vms = []\n    cmd = 'vagrant status'\n    reply = __salt__['cmd.shell'](cmd, cwd=cwd)\n    log.info('--->\\n%s', reply)\n    for line in reply.split('\\n'):\n        tokens = line.strip().split()\n        if len(tokens) > 1:\n            if tokens[1] == 'running':\n                vms.append(tokens[0])\n    return vms",
    "docstring": "Return a list of machine names for active virtual machine on the host,\n    which are defined in the Vagrantfile at the indicated path.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' vagrant.list_active_vms  cwd=/projects/project_1"
  },
  {
    "code": "def upload(self, picture, resize=None, rotation=None, noexif=None,\n               callback=None):\n        if not resize:\n            resize = self._resize\n        if not rotation:\n            rotation = self._rotation\n        if not noexif:\n            noexif = self._noexif\n        if not callback:\n            callback = self._callback\n        return upload(self._apikey, picture, resize,\n                      rotation, noexif, callback)",
    "docstring": "wraps upload function\n\n        :param str/tuple/list picture: Path to picture as str or picture data. \\\n            If data a tuple or list with the file name as str \\\n            and data as byte object in that order.\n        :param str resize: Aresolution in the folowing format: \\\n            '80x80'(optional)\n        :param str|degree rotation: The picture will be rotated by this Value.\\\n            Allowed values are 00, 90, 180, 270.(optional)\n        :param boolean noexif: set to True when exif data should be purged.\\\n            (optional)\n        :param function callback: function will be called after every read. \\\n            Need to take one argument. you can use the len function to \\\n            determine the body length and call bytes_read()."
  },
  {
    "code": "def replace_entity_resource(model, oldres, newres):\n    oldrids = set()\n    for rid, link in model:\n        if link[ORIGIN] == oldres or link[TARGET] == oldres or oldres in link[ATTRIBUTES].values():\n            oldrids.add(rid)\n            new_link = (newres if o == oldres else o, r, newres if t == oldres else t, dict((k, newres if v == oldres else v) for k, v in a.items()))\n            model.add(*new_link)\n    model.delete(oldrids)\n    return",
    "docstring": "Replace one entity in the model with another with the same links\n\n    :param model: Versa model to be updated\n    :param oldres: old/former resource IRI to be replaced\n    :param newres: new/replacement resource IRI\n    :return: None"
  },
  {
    "code": "def check_compatibility(self, other, check_edges=False, precision=1E-7):\n        if self.GetDimension() != other.GetDimension():\n            raise TypeError(\"histogram dimensionalities do not match\")\n        if len(self) != len(other):\n            raise ValueError(\"histogram sizes do not match\")\n        for axis in range(self.GetDimension()):\n            if self.nbins(axis=axis) != other.nbins(axis=axis):\n                raise ValueError(\n                    \"numbers of bins along axis {0:d} do not match\".format(\n                        axis))\n        if check_edges:\n            for axis in range(self.GetDimension()):\n                if not all([abs(l - r) < precision\n                    for l, r in zip(self._edges(axis), other._edges(axis))]):\n                    raise ValueError(\n                        \"edges do not match along axis {0:d}\".format(axis))",
    "docstring": "Test whether two histograms are considered compatible by the number of\n        dimensions, number of bins along each axis, and optionally the bin\n        edges.\n\n        Parameters\n        ----------\n\n        other : histogram\n            A rootpy histogram\n\n        check_edges : bool, optional (default=False)\n            If True then also check that the bin edges are equal within\n            the specified precision.\n\n        precision : float, optional (default=1E-7)\n            The value below which differences between floats are treated as\n            nil when comparing bin edges.\n\n        Raises\n        ------\n\n        TypeError\n            If the histogram dimensionalities do not match\n\n        ValueError\n            If the histogram sizes, number of bins along an axis, or\n            optionally the bin edges do not match"
  },
  {
    "code": "def get_single_file_info(self, rel_path):\n        f_path = self.get_full_file_path(rel_path)\n        return get_single_file_info(f_path, rel_path)",
    "docstring": "Gets last change time for a single file"
  },
  {
    "code": "def fetch_objects(self, oids):\n        objects = self.model.objects.in_bulk(oids)\n        if len(objects.keys()) != len(oids):\n            non_existants = set(oids) - set(objects.keys())\n            msg = _('Unknown identifiers: {identifiers}').format(\n                identifiers=', '.join(str(ne) for ne in non_existants))\n            raise validators.ValidationError(msg)\n        return [objects[id] for id in oids]",
    "docstring": "This methods is used to fetch models\n        from a list of identifiers.\n\n        Default implementation performs a bulk query on identifiers.\n\n        Override this method to customize the objects retrieval."
  },
  {
    "code": "def set_file_path(self, filePath):\n        if filePath is not None:\n            assert isinstance(filePath, basestring), \"filePath must be None or string\"\n            filePath = str(filePath)\n        self.__filePath = filePath",
    "docstring": "Set the file path that needs to be locked.\n\n        :Parameters:\n            #. filePath (None, path): The file that needs to be locked. When given and a lock\n               is acquired, the file will be automatically opened for writing or reading\n               depending on the given mode. If None is given, the locker can always be used\n               for its general purpose as shown in the examples."
  },
  {
    "code": "def generate_cutD_genomic_CDR3_segs(self):\n        max_palindrome_L = self.max_delDl_palindrome\n        max_palindrome_R = self.max_delDr_palindrome\n        self.cutD_genomic_CDR3_segs = []\n        for CDR3_D_seg in [x[1] for x in self.genD]:\n            if len(CDR3_D_seg) < min(max_palindrome_L, max_palindrome_R):\n                self.cutD_genomic_CDR3_segs += [cutR_seq(cutL_seq(CDR3_D_seg, 0, len(CDR3_D_seg)), 0, len(CDR3_D_seg))]\n            else:\n                self.cutD_genomic_CDR3_segs += [cutR_seq(cutL_seq(CDR3_D_seg, 0, max_palindrome_L), 0, max_palindrome_R)]",
    "docstring": "Add palindromic inserted nucleotides to germline V sequences.\n        \n        The maximum number of palindromic insertions are appended to the\n        germline D segments so that delDl and delDr can index directly for number \n        of nucleotides to delete from a segment.\n        \n        Sets the attribute cutV_genomic_CDR3_segs."
  },
  {
    "code": "def get_secondary_count(context, default=0):\n    if not is_ar(context):\n        return default\n    primary = context.getPrimaryAnalysisRequest()\n    if not primary:\n        return default\n    return len(primary.getSecondaryAnalysisRequests())",
    "docstring": "Returns the number of secondary ARs of this AR"
  },
  {
    "code": "def pad_to_size(data, shape, value=0.0):\n    shape = [data.shape[i] if shape[i] == -1 else shape[i]\n             for i in range(len(shape))]\n    new_data = np.empty(shape)\n    new_data[:] = value\n    II = [slice((shape[i] - data.shape[i])//2,\n                (shape[i] - data.shape[i])//2 + data.shape[i])\n          for i in range(len(shape))]\n    new_data[II] = data\n    return new_data",
    "docstring": "This is similar to `pad`, except you specify the final shape of the array.\n\n    Parameters\n    ----------\n    data : ndarray\n        Numpy array of any dimension and type.\n    shape : tuple\n        Final shape of padded array. Should be tuple of length ``data.ndim``.\n        If it has to pad unevenly, it will pad one more at the end of the axis\n        than at the beginning. If a dimension is specified as ``-1``, then it\n        will remain its current size along that dimension.\n    value : data.dtype\n        The value with which to pad. Default is ``0.0``. This can even be an\n        array, as long as ``pdata[:] = value`` is valid, where ``pdata`` is the\n        size of the padded array.\n\n    Examples\n    --------\n    >>> import deepdish as dd\n    >>> import numpy as np\n\n    Pad an array with zeros.\n\n    >>> x = np.ones((4, 2))\n    >>> dd.util.pad_to_size(x, (5, 5))\n    array([[ 0.,  1.,  1.,  0.,  0.],\n           [ 0.,  1.,  1.,  0.,  0.],\n           [ 0.,  1.,  1.,  0.,  0.],\n           [ 0.,  1.,  1.,  0.,  0.],\n           [ 0.,  0.,  0.,  0.,  0.]])"
  },
  {
    "code": "def _finalize_memory(jvm_opts):\n    avoid_min = 32\n    avoid_max = 48\n    out_opts = []\n    for opt in jvm_opts:\n        if opt.startswith(\"-Xmx\"):\n            spec = opt[4:]\n            val = int(spec[:-1])\n            mod = spec[-1]\n            if mod.upper() == \"M\":\n                adjust = 1024\n                min_val = avoid_min * 1024\n                max_val = avoid_max * 1024\n            else:\n                adjust = 1\n                min_val, max_val = avoid_min, avoid_max\n            if val >= min_val and val < max_val:\n                val = min_val - adjust\n            opt = \"%s%s%s\" % (opt[:4], val, mod)\n        out_opts.append(opt)\n    return out_opts",
    "docstring": "GRIDSS does not recommend setting memory between 32 and 48Gb.\n\n    https://github.com/PapenfussLab/gridss#memory-usage"
  },
  {
    "code": "def CreateTask(self, session_identifier):\n    task = tasks.Task(session_identifier)\n    logger.debug('Created task: {0:s}.'.format(task.identifier))\n    with self._lock:\n      self._tasks_queued[task.identifier] = task\n      self._total_number_of_tasks += 1\n      self.SampleTaskStatus(task, 'created')\n    return task",
    "docstring": "Creates a task.\n\n    Args:\n      session_identifier (str): the identifier of the session the task is\n          part of.\n\n    Returns:\n      Task: task attribute container."
  },
  {
    "code": "def Runs(self):\n    with self._accumulators_mutex:\n      items = list(six.iteritems(self._accumulators))\n    return {run_name: accumulator.Tags() for run_name, accumulator in items}",
    "docstring": "Return all the run names in the `EventMultiplexer`.\n\n    Returns:\n    ```\n      {runName: { scalarValues: [tagA, tagB, tagC],\n                  graph: true, meta_graph: true}}\n    ```"
  },
  {
    "code": "def write_sampler_metadata(self, sampler):\n        super(MultiTemperedMetadataIO, self).write_sampler_metadata(sampler)\n        self[self.sampler_group].attrs[\"ntemps\"] = sampler.ntemps",
    "docstring": "Adds writing ntemps to file."
  },
  {
    "code": "def permissions(self):\n        can_read = self._info.file.permissions & lib.GP_FILE_PERM_READ\n        can_write = self._info.file.permissions & lib.GP_FILE_PERM_DELETE\n        return \"{0}{1}\".format(\"r\" if can_read else \"-\",\n                               \"w\" if can_write else \"-\")",
    "docstring": "Permissions of the file.\n\n        Can be \"r-\" (read-only), \"-w\" (write-only), \"rw\" (read-write)\n        or \"--\" (no rights).\n\n        :rtype: str"
  },
  {
    "code": "def scan_django_settings(values, imports):\n    if isinstance(values, (str, bytes)):\n        if utils.is_import_str(values):\n            imports.add(values)\n    elif isinstance(values, dict):\n        for k, v in values.items():\n            scan_django_settings(k, imports)\n            scan_django_settings(v, imports)\n    elif hasattr(values, '__file__') and getattr(values, '__file__'):\n        imp, _ = utils.import_path_from_file(getattr(values, '__file__'))\n        imports.add(imp)\n    elif hasattr(values, '__iter__'):\n        for item in values:\n            scan_django_settings(item, imports)",
    "docstring": "Recursively scans Django settings for values that appear to be\n    imported modules."
  },
  {
    "code": "def _readline(sock, buf):\n    chunks = []\n    last_char = b''\n    while True:\n        if last_char == b'\\r' and buf[0:1] == b'\\n':\n            chunks[-1] = chunks[-1][:-1]\n            return buf[1:], b''.join(chunks)\n        elif buf.find(b'\\r\\n') != -1:\n            before, sep, after = buf.partition(b\"\\r\\n\")\n            chunks.append(before)\n            return after, b''.join(chunks)\n        if buf:\n            chunks.append(buf)\n            last_char = buf[-1:]\n        buf = _recv(sock, RECV_SIZE)\n        if not buf:\n            raise MemcacheUnexpectedCloseError()",
    "docstring": "Read line of text from the socket.\n\n    Read a line of text (delimited by \"\\r\\n\") from the socket, and\n    return that line along with any trailing characters read from the\n    socket.\n\n    Args:\n        sock: Socket object, should be connected.\n        buf: String, zero or more characters, returned from an earlier\n            call to _readline or _readvalue (pass an empty string on the\n            first call).\n\n    Returns:\n      A tuple of (buf, line) where line is the full line read from the\n      socket (minus the \"\\r\\n\" characters) and buf is any trailing\n      characters read after the \"\\r\\n\" was found (which may be an empty\n      string)."
  },
  {
    "code": "def parameter_action(self, text, loc, par):\r\n        exshared.setpos(loc, text)\r\n        if DEBUG > 0:\r\n            print(\"PARAM:\",par)\r\n            if DEBUG == 2: self.symtab.display()\r\n            if DEBUG > 2: return\r\n        index = self.symtab.insert_parameter(par.name, par.type)\r\n        self.shared.function_params += 1\r\n        return index",
    "docstring": "Code executed after recognising a parameter"
  },
  {
    "code": "def median(self, **kwargs):\n        if self._is_transposed:\n            kwargs[\"axis\"] = kwargs.get(\"axis\", 0) ^ 1\n            return self.transpose().median(**kwargs)\n        axis = kwargs.get(\"axis\", 0)\n        func = self._build_mapreduce_func(pandas.DataFrame.median, **kwargs)\n        return self._full_axis_reduce(axis, func)",
    "docstring": "Returns median of each column or row.\n\n        Returns:\n            A new QueryCompiler object containing the median of each column or row."
  },
  {
    "code": "def pollNextEvent(self, pEvent):\n        fn = self.function_table.pollNextEvent\n        result = fn(byref(pEvent), sizeof(VREvent_t))\n        return result != 0",
    "docstring": "Returns true and fills the event with the next event on the queue if there is one. If there are no events\n        this method returns false. uncbVREvent should be the size in bytes of the VREvent_t struct"
  },
  {
    "code": "def filter(self, displayed=False, enabled=False):\n        if self.evaluated:\n            result = self\n            if displayed:\n                result = ElementSelector(\n                    result.browser,\n                    elements=[e for e in result if e.is_displayed()]\n                )\n            if enabled:\n                result = ElementSelector(\n                    result.browser,\n                    elements=[e for e in result if e.is_enabled()]\n                )\n        else:\n            result = copy(self)\n            if displayed:\n                result.displayed = True\n            if enabled:\n                result.enabled = True\n        return result",
    "docstring": "Filter elements by visibility and enabled status.\n\n        :param displayed: whether to filter out invisible elements\n        :param enabled: whether to filter out disabled elements\n\n        Returns: an :class:`ElementSelector`"
  },
  {
    "code": "def update(self, friendly_name=None, description=None, query=None):\n    self._table._load_info()\n    if query is not None:\n      if isinstance(query, _query.Query):\n        query = query.sql\n      self._table._info['view'] = {'query': query}\n    self._table.update(friendly_name=friendly_name, description=description)",
    "docstring": "Selectively updates View information.\n\n    Any parameters that are None (the default) are not applied in the update.\n\n    Args:\n      friendly_name: if not None, the new friendly name.\n      description: if not None, the new description.\n      query: if not None, a new query string for the View."
  },
  {
    "code": "def loc_to_index(self, loc):\n        if loc is None:\n            return self._active_renderer_index\n        elif isinstance(loc, int):\n            return loc\n        elif isinstance(loc, collections.Iterable):\n            assert len(loc) == 2, '\"loc\" must contain two items'\n            return loc[0]*self.shape[0] + loc[1]",
    "docstring": "Return index of the render window given a location index.\n\n        Parameters\n        ----------\n        loc : int, tuple, or list\n            Index of the renderer to add the actor to.  For example,\n            ``loc=2`` or ``loc=(1, 1)``.\n\n        Returns\n        -------\n        idx : int\n            Index of the render window."
  },
  {
    "code": "def patch_func(replacement, target_mod, func_name):\n    original = getattr(target_mod, func_name)\n    vars(replacement).setdefault('unpatched', original)\n    setattr(target_mod, func_name, replacement)",
    "docstring": "Patch func_name in target_mod with replacement\n\n    Important - original must be resolved by name to avoid\n    patching an already patched function."
  },
  {
    "code": "def delete_project(self, id):\n        url = '/projects/{id}'.format(id=id)\n        response = self.delete(url)\n        if response is True:\n            return {}\n        else:\n            return response",
    "docstring": "Delete a project from the Gitlab server\n\n        Gitlab currently returns a Boolean True if the deleted and as such we return an\n        empty Dictionary\n\n        :param id: The ID of the project or NAMESPACE/PROJECT_NAME\n        :return: Dictionary\n        :raise: HttpError: If invalid response returned"
  },
  {
    "code": "def update_parameters(parameters, grads, learning_rate=1.2):\n    W1 = parameters[\"W1\"]\n    b1 = parameters[\"b1\"]\n    W2 = parameters[\"W2\"]\n    b2 = parameters[\"b2\"]\n    dW1 = grads[\"dW1\"]\n    db1 = grads[\"db1\"]\n    dW2 = grads[\"dW2\"]\n    db2 = grads[\"db2\"]\n    W1 -= learning_rate * dW1\n    b1 -= learning_rate * db1\n    W2 -= learning_rate * dW2\n    b2 -= learning_rate * db2\n    parameters = {\"W1\": W1,\n                  \"b1\": b1,\n                  \"W2\": W2,\n                  \"b2\": b2}\n    return parameters",
    "docstring": "Updates parameters using the gradient descent update rule given above\n\n    Arguments:\n    parameters -- python dictionary containing your parameters\n    grads -- python dictionary containing your gradients\n\n    Returns:\n    parameters -- python dictionary containing your updated parameters"
  },
  {
    "code": "def _areadist(ax, v, xr, c, bins=100, by=None, alpha=1, label=None):\n    y, x = np.histogram(v[~np.isnan(v)], bins)\n    x = x[:-1]\n    if by is None:\n        by = np.zeros((bins,))\n    ax.fill_between(x, y, by, facecolor=c, alpha=alpha, label=label)\n    return y",
    "docstring": "Plot the histogram distribution but as an area plot"
  },
  {
    "code": "def entity(self, entity_type, identifier=None):\n        entity = _ACLEntity(entity_type=entity_type, identifier=identifier)\n        if self.has_entity(entity):\n            entity = self.get_entity(entity)\n        else:\n            self.add_entity(entity)\n        return entity",
    "docstring": "Factory method for creating an Entity.\n\n        If an entity with the same type and identifier already exists,\n        this will return a reference to that entity.  If not, it will\n        create a new one and add it to the list of known entities for\n        this ACL.\n\n        :type entity_type: str\n        :param entity_type: The type of entity to create\n                            (ie, ``user``, ``group``, etc)\n\n        :type identifier: str\n        :param identifier: The ID of the entity (if applicable).\n                           This can be either an ID or an e-mail address.\n\n        :rtype: :class:`_ACLEntity`\n        :returns: A new Entity or a reference to an existing identical entity."
  },
  {
    "code": "def download_object(container_name, object_name, destination_path, profile,\n                    overwrite_existing=False, delete_on_failure=True, **libcloud_kwargs):\n    conn = _get_driver(profile=profile)\n    obj = conn.get_object(container_name, object_name)\n    libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs)\n    return conn.download_object(obj, destination_path, overwrite_existing, delete_on_failure, **libcloud_kwargs)",
    "docstring": "Download an object to the specified destination path.\n\n    :param container_name: Container name\n    :type  container_name: ``str``\n\n    :param object_name: Object name\n    :type  object_name: ``str``\n\n    :param destination_path: Full path to a file or a directory where the\n                                incoming file will be saved.\n    :type destination_path: ``str``\n\n    :param profile: The profile key\n    :type  profile: ``str``\n\n    :param overwrite_existing: True to overwrite an existing file,\n                                defaults to False.\n    :type overwrite_existing: ``bool``\n\n    :param delete_on_failure: True to delete a partially downloaded file if\n                                the download was not successful (hash\n                                mismatch / file size).\n    :type delete_on_failure: ``bool``\n\n    :param libcloud_kwargs: Extra arguments for the driver's download_object method\n    :type  libcloud_kwargs: ``dict``\n\n    :return: True if an object has been successfully downloaded, False\n                otherwise.\n    :rtype: ``bool``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion libcloud_storage.download_object MyFolder me.jpg /tmp/me.jpg profile1"
  },
  {
    "code": "def best_hits(self):\n        self.quality_sort()\n        best_hits = dict((query, next(blines)) for (query, blines) in \\\n                        groupby(self, lambda x: x.query))\n        self.ref_sort()\n        return best_hits",
    "docstring": "returns a dict with query => best mapped position"
  },
  {
    "code": "def hlog_inv(y, b=500, r=_display_max, d=_l_mmax):\n    aux = 1. * d / r * y\n    s = sign(y)\n    if s.shape:\n        s[s == 0] = 1\n    elif s == 0:\n        s = 1\n    return s * 10 ** (s * aux) + b * aux - s",
    "docstring": "Inverse of base 10 hyperlog transform."
  },
  {
    "code": "def generate_tags_multiple_files(input_files, tag, ignore_tags, ns=None):\n    return itertools.chain.from_iterable([generate_xmltags(\n        fn, tag, ignore_tags, ns) for fn in input_files])",
    "docstring": "Calls xmltag generator for multiple files."
  },
  {
    "code": "def parse_function(fn):\n  try:\n    return parse_string(inspect.getsource(fn))\n  except (IOError, OSError) as e:\n    raise ValueError(\n        'Cannot differentiate function: %s. Tangent must be able to access the '\n        'source code of the function. Functions defined in a Python '\n        'interpreter and functions backed by C extension modules do not '\n        'have accessible source code.' % e)",
    "docstring": "Get the source of a function and return its AST."
  },
  {
    "code": "def get_crawldelay (self, useragent):\n        for entry in self.entries:\n            if entry.applies_to(useragent):\n                return entry.crawldelay\n        return 0",
    "docstring": "Look for a configured crawl delay.\n\n        @return: crawl delay in seconds or zero\n        @rtype: integer >= 0"
  },
  {
    "code": "def parse(\n        args: typing.List[str] = None,\n        arg_parser: ArgumentParser = None\n) -> dict:\n    parser = arg_parser or create_parser()\n    return vars(parser.parse_args(args))",
    "docstring": "Parses the arguments for the cauldron server"
  },
  {
    "code": "def _remove_dots(src):\n    output = {}\n    for key, val in six.iteritems(src):\n        if isinstance(val, dict):\n            val = _remove_dots(val)\n        output[key.replace('.', '-')] = val\n    return output",
    "docstring": "Remove dots from the given data structure"
  },
  {
    "code": "def save(self, f):\n        return pickle.dump((self.perceptron.weights, self.tagdict, self.classes, self.clusters), f, protocol=pickle.HIGHEST_PROTOCOL)",
    "docstring": "Save pickled model to file."
  },
  {
    "code": "def ae_core_density(self):\n        mesh, values, attrib = self._parse_radfunc(\"ae_core_density\")\n        return RadialFunction(mesh, values)",
    "docstring": "The all-electron radial density."
  },
  {
    "code": "def content(self, **args):\n\t\tself.gist_name = ''\n\t\tif 'name' in args:\n\t\t\tself.gist_name = args['name']\n\t\t\tself.gist_id = self.getMyID(self.gist_name)\n\t\telif 'id' in args:\n\t\t\tself.gist_id = args['id']\n\t\telse:\n\t\t\traise Exception('Either provide authenticated user\\'s Unambigious Gistname or any unique Gistid')\n\t\tif self.gist_id:\n\t\t\tr = requests.get(\n\t\t\t\t'%s'%BASE_URL+'/gists/%s' %self.gist_id,\n\t\t\t\theaders=self.gist.header\n\t\t\t\t)\n\t\t\tif (r.status_code == 200):\n\t\t\t\tr_text = json.loads(r.text)\n\t\t\t\tif self.gist_name!='':\n\t\t\t\t\tcontent =  r.json()['files'][self.gist_name]['content']\n\t\t\t\telse:\n\t\t\t\t\tfor key,value in r.json()['files'].iteritems():\n\t\t\t\t\t\tcontent = r.json()['files'][value['filename']]['content']\n\t\t\t\treturn content\n\t\traise Exception('No such gist found')",
    "docstring": "Doesn't require manual fetching of gistID of a gist\n\t\tpassing gistName will return the content of gist. In case,\n\t\tnames are ambigious, provide GistID or it will return the contents\n\t\tof recent ambigious gistname"
  },
  {
    "code": "def render_pdf_file_to_image_files(pdf_file_name, output_filename_root, program_to_use):\n    res_x = str(args.resX)\n    res_y = str(args.resY)\n    if program_to_use == \"Ghostscript\":\n        if ex.system_os == \"Windows\":\n            ex.render_pdf_file_to_image_files__ghostscript_bmp(\n                                  pdf_file_name, output_filename_root, res_x, res_y)\n        else:\n            ex.render_pdf_file_to_image_files__ghostscript_png(\n                                  pdf_file_name, output_filename_root, res_x, res_y)\n    elif program_to_use == \"pdftoppm\":\n        use_gray = False\n        if use_gray:\n            ex.render_pdf_file_to_image_files_pdftoppm_pgm(\n                pdf_file_name, output_filename_root, res_x, res_y)\n        else:\n            ex.render_pdf_file_to_image_files_pdftoppm_ppm(\n                pdf_file_name, output_filename_root, res_x, res_y)\n    else:\n        print(\"Error in renderPdfFileToImageFile: Unrecognized external program.\",\n              file=sys.stderr)\n        ex.cleanup_and_exit(1)",
    "docstring": "Render all the pages of the PDF file at pdf_file_name to image files with\n    path and filename prefix given by output_filename_root.  Any directories must\n    have already been created, and the calling program is responsible for\n    deleting any directories or image files.  The program program_to_use,\n    currently either the string \"pdftoppm\" or the string \"Ghostscript\", will be\n    called externally.  The image type that the PDF is converted into must to be\n    directly openable by PIL."
  },
  {
    "code": "def _calc_b(w, aod700):\n    b1 = 0.00925*aod700**2 + 0.0148*aod700 - 0.0172\n    b0 = -0.7565*aod700**2 + 0.5057*aod700 + 0.4557\n    b = b1 * np.log(w) + b0\n    return b",
    "docstring": "Calculate the b coefficient."
  },
  {
    "code": "def _mangle_prefix(res):\n    res['total_addresses'] = unicode(res['total_addresses'])\n    res['used_addresses'] = unicode(res['used_addresses'])\n    res['free_addresses'] = unicode(res['free_addresses'])\n    if res['expires'].tzinfo is None:\n        res['expires'] = pytz.utc.localize(res['expires'])\n    if res['expires'] == pytz.utc.localize(datetime.datetime.max):\n        res['expires'] = None\n    return res",
    "docstring": "Mangle prefix result"
  },
  {
    "code": "def list_spiders(self, project):\n        url = self._build_url(constants.LIST_SPIDERS_ENDPOINT)\n        params = {'project': project}\n        json = self.client.get(url, params=params, timeout=self.timeout)\n        return json['spiders']",
    "docstring": "Lists all known spiders for a specific project. First class, maps\n        to Scrapyd's list spiders endpoint."
  },
  {
    "code": "def get_genes_for_hgnc_id(self, hgnc_symbol):\n        headers = {\"content-type\": \"application/json\"}\n        self.attempt = 0\n        ext = \"/xrefs/symbol/homo_sapiens/{}\".format(hgnc_symbol)\n        r = self.ensembl_request(ext, headers)\n        genes = []\n        for item in json.loads(r):\n            if item[\"type\"] == \"gene\":\n                genes.append(item[\"id\"])\n        return genes",
    "docstring": "obtain the ensembl gene IDs that correspond to a HGNC symbol"
  },
  {
    "code": "def to_python(self, reply, propagate=True):\n        try:\n            return reply['ok']\n        except KeyError:\n            error = self.Error(*reply.get('nok') or ())\n            if propagate:\n                raise error\n            return error",
    "docstring": "Extracts the value out of the reply message.\n\n        :param reply: In the case of a successful call the reply message\n            will be::\n\n                {'ok': return_value, **default_fields}\n\n            Therefore the method returns: return_value, **default_fields\n\n            If the method raises an exception the reply message\n            will be::\n\n                {'nok': [repr exc, str traceback], **default_fields}\n\n        :keyword propagate - Propagate exceptions raised instead of returning\n            a result representation of the error."
  },
  {
    "code": "def set_ignore_interrupts(flag=True):\n    log.info(\"setting ignore_interrupts to %r\" % flag)\n    state.ignore_interrupts = bool(flag)",
    "docstring": "turn off EINTR-raising from emulated syscalls on interruption by signals\n\n    due to the nature of greenhouse's system call emulation,\n    ``signal.siginterrupt`` can't be made to work with it. specifically,\n    greenhouse can't differentiate between different signals. so this function\n    toggles whether to restart for *ALL* or *NO* signals.\n\n    :param flag:\n        whether to turn EINTR exceptions off (``True``) or on (``False``)\n    :type flag: bool"
  },
  {
    "code": "def run_pip_install(upgrade=0):\n    command = 'pip install -r {0}'.format(\n        settings.FAB_SETTING('SERVER_REQUIREMENTS_PATH'))\n    if upgrade:\n        command += ' --upgrade'\n    run_workon(command)",
    "docstring": "Installs the requirement.txt file on the given server.\n\n    Usage::\n\n        fab <server> run_pip_install\n        fab <server> run_pip_install:upgrade=1\n\n    :param upgrade: If set to 1, the command will be executed with the\n      ``--upgrade`` flag."
  },
  {
    "code": "def values(self):\n        def iter_values():\n            val = self._element.val\n            if val is None:\n                return\n            for idx in range(val.ptCount_val):\n                yield val.pt_v(idx)\n        return tuple(iter_values())",
    "docstring": "Read-only. A sequence containing the float values for this series, in\n        the order they appear on the chart."
  },
  {
    "code": "def check_enough_space(dataset_local_dir, remote_fname, local_fname,\n                       max_disk_usage=0.9):\n    storage_need = os.path.getsize(remote_fname)\n    storage_total, storage_used = disk_usage(dataset_local_dir)\n    return ((storage_used + storage_need) <\n            (storage_total * max_disk_usage))",
    "docstring": "Check if the given local folder has enough space.\n\n    Check if the given local folder has enough space to store\n    the specified remote file.\n\n    Parameters\n    ----------\n    remote_fname : str\n        Path to the remote file\n    remote_fname : str\n        Path to the local folder\n    max_disk_usage : float\n        Fraction indicating how much of the total space in the\n        local folder can be used before the local cache must stop\n        adding to it.\n\n    Returns\n    -------\n    output : boolean\n        True if there is enough space to store the remote file."
  },
  {
    "code": "def spaceless_pdf_plot_maker(array, filename, vmax=None, dpi=DEFAULT_DPI):\n    if vmax is None:\n        vmax = np.percentile(array, DEFAULT_SATURATION_THRESHOLD)\n    plt.gca().set_axis_off()\n    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)\n    plt.margins(0, 0)\n    plt.gca().xaxis.set_major_locator(plt.NullLocator())\n    plt.gca().yaxis.set_major_locator(plt.NullLocator())\n    plt.figure()\n    if SEABORN:\n        sns.heatmap(array, vmax=vmax, cmap=\"Reds\")\n    else:\n        plt.imshow(array, vmax=vmax, cmap=\"Reds\", interpolation=\"none\")\n        plt.colorbar()\n    plt.savefig(filename, bbox_inches=\"tight\", pad_inches=0.0, dpi=dpi)\n    plt.close()",
    "docstring": "Draw a pretty plot from an array\n\n    A function that performs all the tedious matplotlib\n    magic to draw a 2D array with as few parameters and\n    as little whitespace as possible.\n\n    Parameters\n    ----------\n    array : array_like\n        The input array to draw.\n    filename : file, str or pathlib.Path\n        The output image to save the array into.\n    vmax : float, optional\n        The default saturation threshold for the array. If set to None, the\n        80th percentile value of the array is chosen. Default is None.\n    dpi : int, optional\n        Dots per inch (DPI) of the output image. Default is 200."
  },
  {
    "code": "def build(id=None, name=None, revision=None,\n          temporary_build=False, timestamp_alignment=False,\n          no_build_dependencies=False,\n          keep_pod_on_failure=False,\n          force_rebuild=False,\n          rebuild_mode=common.REBUILD_MODES_DEFAULT):\n    data = build_raw(id, name, revision, temporary_build, timestamp_alignment, no_build_dependencies,\n              keep_pod_on_failure, force_rebuild, rebuild_mode)\n    if data:\n        return utils.format_json(data)",
    "docstring": "Trigger a BuildConfiguration by name or ID"
  },
  {
    "code": "def __populate_repositories_of_interest(self, username):\n        user = self.github.get_user(username)\n        self.user_starred_repositories.extend(user.get_starred())\n        if self.deep_dive:\n            for following_user in user.get_following():\n                self.user_following_starred_repositories.extend(\n                    following_user.get_starred()\n                )",
    "docstring": "Method to populate repositories which will be used to suggest\n        repositories for the user. For this purpose we use two kinds of\n        repositories.\n\n        1. Repositories starred by user him/herself.\n        2. Repositories starred by the users followed by the user.\n\n        :param username: Username for the user for whom repositories are being\n                         suggested for."
  },
  {
    "code": "def estimateKronCovariances(phenos,K1r=None,K1c=None,K2r=None,K2c=None,covs=None,Acovs=None,covar_type='lowrank_diag',rank=1):\n    print(\".. Training the backgrond covariance with a GP model\")\n    vc = VAR.CVarianceDecomposition(phenos)\n    if K1r is not None:\n        vc.addRandomEffect(K1r,covar_type=covar_type,rank=rank)\n    if K2r is not None:\n        vc.addRandomEffect(is_noise=True,K=K2r,covar_type=covar_type,rank=rank)\n    for ic  in range(len(Acovs)):\n        vc.addFixedEffect(covs[ic],Acovs[ic])\n    start = time.time()\n    conv = vc.findLocalOptimum(fast=True)\n    assert conv, \"CVariance Decomposition has not converged\"\n    time_el = time.time()-start\n    print((\"Background model trained in %.2f s\" % time_el))\n    return vc",
    "docstring": "estimates the background covariance model before testing\n\n    Args:\n        phenos: [N x P] SP.array of P phenotypes for N individuals\n        K1r:    [N x N] SP.array of LMM-covariance/kinship koefficients (optional)\n                        If not provided, then linear regression analysis is performed\n        K1c:    [P x P] SP.array of LMM-covariance/kinship koefficients (optional)\n                        If not provided, then linear regression analysis is performed\n        K2r:    [N x N] SP.array of LMM-covariance/kinship koefficients (optional)\n                        If not provided, then linear regression analysis is performed\n        K2c:    [P x P] SP.array of LMM-covariance/kinship koefficients (optional)\n                        If not provided, then linear regression analysis is performed\n        covs:           list of SP.arrays holding covariates. Each covs[i] has one corresponding Acovs[i]\n        Acovs:          list of SP.arrays holding the phenotype design matrices for covariates.\n                        Each covs[i] has one corresponding Acovs[i].\n        covar_type:     type of covaraince to use. Default 'freeform'. possible values are\n                        'freeform': free form optimization,\n                        'fixed': use a fixed matrix specified in covar_K0,\n                        'diag': optimize a diagonal matrix,\n                        'lowrank': optimize a low rank matrix. The rank of the lowrank part is specified in the variable rank,\n                        'lowrank_id': optimize a low rank matrix plus the weight of a constant diagonal matrix. The rank of the lowrank part is specified in the variable rank,\n                        'lowrank_diag': optimize a low rank matrix plus a free diagonal matrix. The rank of the lowrank part is specified in the variable rank,\n                        'block': optimize the weight of a constant P x P block matrix of ones,\n                        'block_id': optimize the weight of a constant P x P block matrix of ones plus the weight of a constant diagonal matrix,\n                        'block_diag': optimize the weight of a constant P x P block matrix of ones plus a free diagonal matrix,\n        rank:           rank of a possible lowrank component (default 1)\n\n    Returns:\n        CVarianceDecomposition object"
  },
  {
    "code": "def longest_run_1d(arr):\n    v, rl = rle_1d(arr)[:2]\n    return np.where(v, rl, 0).max()",
    "docstring": "Return the length of the longest consecutive run of identical values.\n\n    Parameters\n    ----------\n    arr : bool array\n      Input array\n\n    Returns\n    -------\n    int\n      Length of longest run."
  },
  {
    "code": "def copy_contents_to(self, destination):\n        logger.info(\"Copying contents of %s to %s\" % (self, destination))\n        target = Folder(destination)\n        target.make()\n        self._create_target_tree(target)\n        dir_util.copy_tree(self.path, unicode(target))\n        return target",
    "docstring": "Copies the contents of this directory to the given destination.\n        Returns a Folder object that represents the moved directory."
  },
  {
    "code": "def remove_label(self, label, relabel=False):\n        self.remove_labels(label, relabel=relabel)",
    "docstring": "Remove the label number.\n\n        The removed label is assigned a value of zero (i.e.,\n        background).\n\n        Parameters\n        ----------\n        label : int\n            The label number to remove.\n\n        relabel : bool, optional\n            If `True`, then the segmentation image will be relabeled\n            such that the labels are in consecutive order starting from\n            1.\n\n        Examples\n        --------\n        >>> from photutils import SegmentationImage\n        >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4],\n        ...                           [0, 0, 0, 0, 0, 4],\n        ...                           [0, 0, 3, 3, 0, 0],\n        ...                           [7, 0, 0, 0, 0, 5],\n        ...                           [7, 7, 0, 5, 5, 5],\n        ...                           [7, 7, 0, 0, 5, 5]])\n        >>> segm.remove_label(label=5)\n        >>> segm.data\n        array([[1, 1, 0, 0, 4, 4],\n               [0, 0, 0, 0, 0, 4],\n               [0, 0, 3, 3, 0, 0],\n               [7, 0, 0, 0, 0, 0],\n               [7, 7, 0, 0, 0, 0],\n               [7, 7, 0, 0, 0, 0]])\n\n        >>> segm = SegmentationImage([[1, 1, 0, 0, 4, 4],\n        ...                           [0, 0, 0, 0, 0, 4],\n        ...                           [0, 0, 3, 3, 0, 0],\n        ...                           [7, 0, 0, 0, 0, 5],\n        ...                           [7, 7, 0, 5, 5, 5],\n        ...                           [7, 7, 0, 0, 5, 5]])\n        >>> segm.remove_label(label=5, relabel=True)\n        >>> segm.data\n        array([[1, 1, 0, 0, 3, 3],\n               [0, 0, 0, 0, 0, 3],\n               [0, 0, 2, 2, 0, 0],\n               [4, 0, 0, 0, 0, 0],\n               [4, 4, 0, 0, 0, 0],\n               [4, 4, 0, 0, 0, 0]])"
  },
  {
    "code": "def users(self):\n        return sa.orm.relationship(\n            \"User\",\n            secondary=\"users_resources_permissions\",\n            passive_deletes=True,\n            passive_updates=True,\n        )",
    "docstring": "returns all users that have permissions for this resource"
  },
  {
    "code": "def queue_stats(self, queue, tags):\n        for mname, pymqi_value in iteritems(metrics.queue_metrics()):\n            try:\n                mname = '{}.queue.{}'.format(self.METRIC_PREFIX, mname)\n                m = queue.inquire(pymqi_value)\n                self.gauge(mname, m, tags=tags)\n            except pymqi.Error as e:\n                self.warning(\"Error getting queue stats for {}: {}\".format(queue, e))\n        for mname, func in iteritems(metrics.queue_metrics_functions()):\n            try:\n                mname = '{}.queue.{}'.format(self.METRIC_PREFIX, mname)\n                m = func(queue)\n                self.gauge(mname, m, tags=tags)\n            except pymqi.Error as e:\n                self.warning(\"Error getting queue stats for {}: {}\".format(queue, e))",
    "docstring": "Grab stats from queues"
  },
  {
    "code": "def const_shuffle(arr, seed=23980):\n    old_seed = np.random.seed()\n    np.random.seed(seed)\n    np.random.shuffle(arr)\n    np.random.seed(old_seed)",
    "docstring": "Shuffle an array in-place with a fixed seed."
  },
  {
    "code": "def to_dict(self):\n        return {'access_key': self.access_key,\n                'secret_key': self.secret_key,\n                'session_token': self.session_token,\n                'expiration': self.expiration,\n                'request_id': self.request_id}",
    "docstring": "Return a Python dict containing the important information\n        about this Session Token."
  },
  {
    "code": "def add_user(self,\n                 username,\n                 email,\n                 directoryId=1,\n                 password=None,\n                 fullname=None,\n                 notify=False,\n                 active=True,\n                 ignore_existing=False,\n                 application_keys=None,\n                 ):\n        if not fullname:\n            fullname = username\n        url = self._options['server'] + '/rest/api/latest/user'\n        x = OrderedDict()\n        x['displayName'] = fullname\n        x['emailAddress'] = email\n        x['name'] = username\n        if password:\n            x['password'] = password\n        if notify:\n            x['notification'] = 'True'\n        if application_keys is not None:\n            x['applicationKeys'] = application_keys\n        payload = json.dumps(x)\n        try:\n            self._session.post(url, data=payload)\n        except JIRAError as e:\n            err = e.response.json()['errors']\n            if 'username' in err and err['username'] == 'A user with that username already exists.' and ignore_existing:\n                return True\n            raise e\n        return True",
    "docstring": "Create a new JIRA user.\n\n        :param username: the username of the new user\n        :type username: str\n        :param email: email address of the new user\n        :type email: str\n        :param directoryId: The directory ID the new user should be a part of (Default: 1)\n        :type directoryId: int\n        :param password: Optional, the password for the new user\n        :type password: Optional[str]\n        :param fullname: Optional, the full name of the new user\n        :type fullname: Optional[str]\n        :param notify: Whether or not to send a notification to the new user. (Default: False)\n        :type notify: bool\n        :param active: Whether or not to make the new user active upon creation. (Default: True)\n        :type active: bool\n        :param ignore_existing: Whether or not to ignore and existing user. (Default: False)\n        :type ignore_existing: bool\n        :param applicationKeys: Keys of products user should have access to\n        :type applicationKeys: Optional[list]\n\n        :return: Whether or not the user creation was successful.\n        :rtype: bool\n\n        :raises JIRAError:  If username already exists and `ignore_existing` has not been set to `True`."
  },
  {
    "code": "def order_by(self, *order_bys):\n        self._order_bys = []\n        for ingr in order_bys:\n            order_by = self._shelf.find(ingr, (Dimension, Metric))\n            self._order_bys.append(order_by)\n        self.dirty = True\n        return self",
    "docstring": "Add a list of ingredients to order by to the query. These can\n        either be Dimension or Metric objects or strings representing\n        order_bys on the shelf.\n\n        The Order_by expression will be added to the query's order_by statement\n\n        :param order_bys: Order_bys to add to the recipe. Order_bys can\n                         either be keys on the ``shelf`` or\n                         Dimension or Metric objects. If the\n                         key is prefixed by \"-\" the ordering will be\n                         descending.\n        :type order_bys: list"
  },
  {
    "code": "def filter_by(self, types=(), units=()):\n        if not (isinstance(types, Sequence) and isinstance(units, Sequence)):\n            raise TypeError('types/units must be a sequence')\n        empty = frozenset()\n        if types:\n            type_names = set()\n            for type_ in types:\n                type_names |= self.by_type.get(type_, empty)\n            if not units:\n                return type_names\n        if units:\n            unit_names = set()\n            for unit in units:\n                unit_names |= self.by_unit.get(unit, empty)\n            if not types:\n                return unit_names\n        return (type_names & unit_names) if (types and units) else empty",
    "docstring": "Return list of value labels, filtered by either or both type and unit. An empty\n        sequence for either argument will match as long as the other argument matches any values."
  },
  {
    "code": "def move_mouse_relative_to_window(self, window, x, y):\n        _libxdo.xdo_move_mouse_relative_to_window(\n            self._xdo, ctypes.c_ulong(window), x, y)",
    "docstring": "Move the mouse to a specific location relative to the top-left corner\n        of a window.\n\n        :param x: the target X coordinate on the screen in pixels.\n        :param y: the target Y coordinate on the screen in pixels."
  },
  {
    "code": "def get_doc_comments(text):\n    r\n    def make_pair(match):\n        comment = match.group()\n        try:\n            end = text.find('\\n', match.end(0)) + 1\n            if '@class' not in comment:\n                next_line = next(split_delimited('()', '\\n', text[end:]))\n            else:\n                next_line = text[end:text.find('\\n', end)]\n        except StopIteration:\n            next_line = ''\n        return (comment, next_line)\n    return [make_pair(match) for match in re.finditer('/\\*\\*(.*?)\\*/', \n            text, re.DOTALL)]",
    "docstring": "r\"\"\"\n    Return a list of all documentation comments in the file text.  Each\n    comment is a pair, with the first element being the comment text and\n    the second element being the line after it, which may be needed to\n    guess function & arguments.\n\n    >>> get_doc_comments(read_file('examples/module.js'))[0][0][:40]\n    '/**\\n * This is the module documentation.'\n    >>> get_doc_comments(read_file('examples/module.js'))[1][0][7:50]\n    'This is documentation for the first method.'\n    >>> get_doc_comments(read_file('examples/module.js'))[1][1]\n    'function the_first_function(arg1, arg2) '\n    >>> get_doc_comments(read_file('examples/module.js'))[2][0]\n    '/** This is the documentation for the second function. */'"
  },
  {
    "code": "def parse_media_type(media_type):\n    media_type, sep, parameter = str(media_type).partition(';')\n    media_type, sep, subtype = media_type.partition('/')\n    return tuple(x.strip() or None for x in (media_type, subtype, parameter))",
    "docstring": "Returns type, subtype, parameter tuple from an http media_type.\n    Can be applied to the 'Accept' or 'Content-Type' http header fields."
  },
  {
    "code": "def __get_keys(self):\n        keys = list()\n        tree_node = self\n        while tree_node is not None and tree_node.key is not None:\n            keys.insert(0, tree_node.key)\n            tree_node = tree_node.parent\n        return keys",
    "docstring": "Return the keys associated with this node by adding its key and then adding parent keys recursively."
  },
  {
    "code": "def _bind_socket(self, bindaddr):\n        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        sock.setblocking(0)\n        try:\n            sock.bind(bindaddr)\n        except Exception:\n            self._logger.exception(\"Unable to bind to %s\" % str(bindaddr))\n            raise\n        sock.listen(self.BACKLOG)\n        return sock",
    "docstring": "Create a listening server socket."
  },
  {
    "code": "def experiments_predictions_download(self, experiment_id, run_id):\n        model_run = self.experiments_predictions_get(experiment_id, run_id)\n        if model_run is None:\n            return None\n        if not model_run.state.is_success:\n            return None\n        funcdata = self.funcdata.get_object(model_run.state.model_output)\n        if funcdata is None:\n            return None\n        return FileInfo(\n            funcdata.upload_file,\n            funcdata.properties[datastore.PROPERTY_MIMETYPE],\n            funcdata.properties[datastore.PROPERTY_FILENAME]\n        )",
    "docstring": "Donwload the results of a prediction for a given experiment.\n\n        Parameters\n        ----------\n        experiment_id : string\n            Unique experiment identifier\n        run_id : string\n            Unique model run identifier\n\n        Returns\n        -------\n        FileInfo\n            Information about prediction result file on disk or None if\n            prediction is unknown or has no result"
  },
  {
    "code": "def branchpoints(image, mask=None):\n    global branchpoints_table\n    if mask is None:\n        masked_image = image\n    else:\n        masked_image = image.astype(bool).copy()\n        masked_image[~mask] = False\n    result = table_lookup(masked_image, branchpoints_table, False, 1)\n    if not mask is None:\n        result[~mask] = image[~mask]\n    return result",
    "docstring": "Remove all pixels from an image except for branchpoints\n    \n    image - a skeletonized image\n    mask -  a mask of pixels excluded from consideration\n    \n    1 0 1    ? 0 ?\n    0 1 0 -> 0 1 0\n    0 1 0    0 ? 0"
  },
  {
    "code": "def get_write_fields(self):\n        rec_write_fields = self.get_write_subset('record')\n        if self.comments != None:\n            rec_write_fields.append('comments')\n        self.check_field('n_sig')\n        if self.n_sig >  0:\n            sig_write_fields = self.get_write_subset('signal')\n        else:\n            sig_write_fields = None\n        return rec_write_fields, sig_write_fields",
    "docstring": "Get the list of fields used to write the header, separating\n        record and signal specification fields. Returns the default\n        required fields, the user defined fields,\n        and their dependencies.\n\n        Does NOT include `d_signal` or `e_d_signal`.\n\n        Returns\n        -------\n        rec_write_fields : list\n            Record specification fields to be written. Includes\n            'comment' if present.\n        sig_write_fields : dict\n            Dictionary of signal specification fields to be written,\n            with values equal to the channels that need to be present\n            for each field."
  },
  {
    "code": "def _step_begin(self, label, log=True):\n        if log:\n            self.step_label = label\n            self.step_begin_time = self.log(u\"STEP %d BEGIN (%s)\" % (self.step_index, label))",
    "docstring": "Log begin of a step"
  },
  {
    "code": "def integer_ceil(a, b):\n    quanta, mod = divmod(a, b)\n    if mod:\n        quanta += 1\n    return quanta",
    "docstring": "Return the ceil integer of a div b."
  },
  {
    "code": "def quantile(expr, prob=None, **kw):\n    prob = kw.get('_prob', prob)\n    output_type = _stats_type(expr)\n    if isinstance(prob, (list, set)) and not isinstance(expr, GroupBy):\n        output_type = types.List(output_type)\n    return _reduction(expr, Quantile, output_type, _prob=prob)",
    "docstring": "Percentile value.\n\n    :param expr:\n    :param prob: probability or list of probabilities, in [0, 1]\n    :return:"
  },
  {
    "code": "def update_highlights(self, old_highlight_set, new_highlight_set):\n        if not self.gui_up:\n            return\n        un_hilite_set = old_highlight_set - new_highlight_set\n        re_hilite_set = new_highlight_set - old_highlight_set\n        for key in un_hilite_set:\n            self._highlight_path(key, False)\n        for key in re_hilite_set:\n            self._highlight_path(key, True)",
    "docstring": "Unhighlight the entries represented by ``old_highlight_set``\n        and highlight the ones represented by ``new_highlight_set``.\n\n        Both are sets of keys."
  },
  {
    "code": "def list_ipsec_site_connections(self, retrieve_all=True, **_params):\n        return self.list('ipsec_site_connections',\n                         self.ipsec_site_connections_path,\n                         retrieve_all,\n                         **_params)",
    "docstring": "Fetches all configured IPsecSiteConnections for a project."
  },
  {
    "code": "def _tree_to_string(cls, root_element, xml_declaration=True, pretty_print=True):\n        from lxml import etree\n        return gf.safe_unicode(etree.tostring(\n            root_element,\n            encoding=\"UTF-8\",\n            method=\"xml\",\n            xml_declaration=xml_declaration,\n            pretty_print=pretty_print\n        ))",
    "docstring": "Return an ``lxml`` tree as a Unicode string."
  },
  {
    "code": "def inflate_bbox(self):\n        left, top, right, bottom = self.bounding_box\n        self.bounding_box = (\n            left & 0xFFFC,\n            top,\n            right if right % 4 == 0 else (right & 0xFFFC) + 0x04,\n            bottom)\n        return self.bounding_box",
    "docstring": "Realign the left and right edges of the bounding box such that they are\n        inflated to align modulo 4.\n\n        This method is optional, and used mainly to accommodate devices with\n        COM/SEG GDDRAM structures that store pixels in 4-bit nibbles."
  },
  {
    "code": "def handle_length(schema, field, validator, parent_schema):\n    if isinstance(field, fields.String):\n        minKey = 'minLength'\n        maxKey = 'maxLength'\n    elif isinstance(field, (fields.List, fields.Nested)):\n        minKey = 'minItems'\n        maxKey = 'maxItems'\n    else:\n        raise ValueError(\"In order to set the Length validator for JSON \"\n                         \"schema, the field must be either a List or a String\")\n    if validator.min:\n        schema[minKey] = validator.min\n    if validator.max:\n        schema[maxKey] = validator.max\n    if validator.equal:\n        schema[minKey] = validator.equal\n        schema[maxKey] = validator.equal\n    return schema",
    "docstring": "Adds validation logic for ``marshmallow.validate.Length``, setting the\n    values appropriately for ``fields.List``, ``fields.Nested``, and\n    ``fields.String``.\n\n    Args:\n        schema (dict): The original JSON schema we generated. This is what we\n            want to post-process.\n        field (fields.Field): The field that generated the original schema and\n            who this post-processor belongs to.\n        validator (marshmallow.validate.Length): The validator attached to the\n            passed in field.\n        parent_schema (marshmallow.Schema): The Schema instance that the field\n            belongs to.\n\n    Returns:\n        dict: A, possibly, new JSON Schema that has been post processed and\n            altered.\n\n    Raises:\n        ValueError: Raised if the `field` is something other than\n            `fields.List`, `fields.Nested`, or `fields.String`"
  },
  {
    "code": "def update_port_monitor(self, resource, timeout=-1):\n        data = resource.copy()\n        if 'type' not in data:\n            data['type'] = 'port-monitor'\n        uri = \"{}{}\".format(self.data[\"uri\"], self.PORT_MONITOR_PATH)\n        return self._helper.update(data, uri=uri, timeout=timeout)",
    "docstring": "Updates the port monitor configuration of a logical interconnect.\n\n        Args:\n            resource: Port monitor configuration.\n\n        Returns:\n            dict: Port monitor configuration."
  },
  {
    "code": "def get(token: Union[str, int] = None) -> 'Role':\n        if token is None:\n            return Role.USER\n        for role in Role:\n            if role == Role.ROLE_REMOVE:\n                continue\n            if isinstance(token, int) and token in role.value:\n                return role\n            if str(token).upper() == role.name or token in (str(v) for v in role.value):\n                return role\n        return None",
    "docstring": "Return enum instance corresponding to input token.\n\n        :param token: token identifying role to indy-sdk: 'STEWARD', 'TRUSTEE', 'TRUST_ANCHOR', '' or None\n        :return: enum instance corresponding to input token"
  },
  {
    "code": "def _parse_snapshot_restore_command(cls, args, action):\n        argparser = ArgumentParser(prog=\"cluster %s\" % action)\n        group = argparser.add_mutually_exclusive_group(required=True)\n        group.add_argument(\"--id\", dest=\"cluster_id\",\n                          help=\"execute on cluster with this id\")\n        group.add_argument(\"--label\", dest=\"label\",\n                          help=\"execute on cluster with this label\")\n        argparser.add_argument(\"--s3_location\",\n                          help=\"s3_location where backup is stored\", required=True)\n        if action == \"snapshot\":\n            argparser.add_argument(\"--backup_type\",\n                          help=\"backup_type: full/incremental, default is full\")\n        elif action == \"restore_point\":\n            argparser.add_argument(\"--backup_id\",\n                          help=\"back_id from which restoration will be done\", required=True)\n            argparser.add_argument(\"--table_names\",\n                          help=\"table(s) which are to be restored\", required=True)\n            argparser.add_argument(\"--no-overwrite\", action=\"store_false\",\n                          help=\"With this option, restore overwrites to the existing table if theres any in restore target\")\n            argparser.add_argument(\"--no-automatic\", action=\"store_false\",\n                          help=\"With this option, all the dependencies are automatically restored together with this backup image following the correct order\")\n        arguments = argparser.parse_args(args)\n        return arguments",
    "docstring": "Parse command line arguments for snapshot command."
  },
  {
    "code": "def mangleNec(code, freq=40):\n    timings = []\n    for octet in binascii.unhexlify(code.replace(\" \", \"\")):\n        burst = lambda x: x and \"0226 06AD\" or \"0226 0258\"\n        for bit in reversed(\"%08d\" % int(bin(ord(octet))[2:])):\n            bit = int(bit)\n            timings.append(burst(bit))\n    return mangleIR(\"K %0X22 214d 10b3 \" % freq + \" \".join(timings) + \" 0226 2000\")",
    "docstring": "Convert NEC code to shorthand notation"
  },
  {
    "code": "def config_flag(option, value, default=False, section=cli.name):\n    class x(object):\n        def __bool__(self, option=option, value=value,\n                     default=default, section=section):\n            config = read_config()\n            type = builtins.type(value)\n            get_option = option_getter(type)\n            try:\n                return get_option(config, section, option) == value\n            except (NoOptionError, NoSectionError):\n                return default\n        __nonzero__ = __bool__\n    return x()",
    "docstring": "Guesses whether a CLI flag should be turned on or off from the\n    configuration.  If the configuration option value is same with the given\n    value, it returns ``True``.\n\n    ::\n\n       @click.option('--ko-kr', 'locale', is_flag=True,\n                     default=config_flag('locale', 'ko_KR'))"
  },
  {
    "code": "def accel_increase_height(self, *args):\n        height = self.settings.general.get_int('window-height')\n        self.settings.general.set_int('window-height', min(height + 2, 100))\n        return True",
    "docstring": "Callback to increase height."
  },
  {
    "code": "def parse(self, filename):\n        path = os.path.abspath(filename)\n        if filename.endswith(\".xml\"):\n            return PawXmlSetup(path)\n        ppdesc = self.read_ppdesc(path)\n        if ppdesc is None:\n            logger.critical(\"Cannot find ppdesc in %s\" % path)\n            return None\n        psp_type = ppdesc.psp_type\n        parsers = {\n            \"FHI\": NcAbinitHeader.fhi_header,\n            \"GTH\": NcAbinitHeader.gth_header,\n            \"TM\": NcAbinitHeader.tm_header,\n            \"Teter\": NcAbinitHeader.tm_header,\n            \"HGH\": NcAbinitHeader.hgh_header,\n            \"HGHK\": NcAbinitHeader.hgh_header,\n            \"ONCVPSP\": NcAbinitHeader.oncvpsp_header,\n            \"PAW_abinit_text\": PawAbinitHeader.paw_header,\n        }\n        try:\n            header = parsers[ppdesc.name](path, ppdesc)\n        except Exception:\n            raise self.Error(path + \":\\n\" + straceback())\n        if psp_type == \"NC\":\n            pseudo = NcAbinitPseudo(path, header)\n        elif psp_type == \"PAW\":\n            pseudo = PawAbinitPseudo(path, header)\n        else:\n            raise NotImplementedError(\"psp_type not in [NC, PAW]\")\n        return pseudo",
    "docstring": "Read and parse a pseudopotential file. Main entry point for client code.\n\n        Returns:\n            pseudopotential object or None if filename is not a valid pseudopotential file."
  },
  {
    "code": "def root(self):\n        sector = self.header.directory_sector_start\n        position = (sector + 1) << self.header.sector_shift\n        return RootEntry(self, position)",
    "docstring": "Property provides access to root object in CFB."
  },
  {
    "code": "def resampled(\n        chunksize_bytes=DEFAULT_CHUNK_SIZE,\n        resample_to=SR44100(),\n        store_resampled=False):\n    class Resampled(BaseModel):\n        meta = JSONFeature(\n            MetaData,\n            store=True,\n            encoder=AudioMetaDataEncoder)\n        raw = ByteStreamFeature(\n            ByteStream,\n            chunksize=chunksize_bytes,\n            needs=meta,\n            store=False)\n        ogg = OggVorbisFeature(\n            OggVorbis,\n            needs=raw,\n            store=True)\n        pcm = AudioSamplesFeature(\n            AudioStream,\n            needs=raw,\n            store=False)\n        resampled = AudioSamplesFeature(\n            Resampler,\n            needs=pcm,\n            samplerate=resample_to,\n            store=store_resampled)\n    return Resampled",
    "docstring": "Create a basic processing pipeline that can resample all incoming audio\n    to a normalized sampling rate for downstream processing, and store a\n    convenient, compressed version for playback\n\n    :param chunksize_bytes: The number of bytes from the raw stream to process\n    at once\n    :param resample_to: The new, normalized sampling rate\n    :return: A simple processing pipeline"
  },
  {
    "code": "def update_domain_name(self,\n                           domain_name,\n                           certificate_name=None,\n                           certificate_body=None,\n                           certificate_private_key=None,\n                           certificate_chain=None,\n                           certificate_arn=None,\n                           lambda_name=None,\n                           stage=None,\n                           route53=True,\n                           base_path=None):\n        print(\"Updating domain name!\")\n        certificate_name = certificate_name + str(time.time())\n        api_gateway_domain = self.apigateway_client.get_domain_name(domainName=domain_name)\n        if not certificate_arn\\\n           and certificate_body and certificate_private_key and certificate_chain:\n            acm_certificate = self.acm_client.import_certificate(Certificate=certificate_body,\n                                                                 PrivateKey=certificate_private_key,\n                                                                 CertificateChain=certificate_chain)\n            certificate_arn = acm_certificate['CertificateArn']\n        self.update_domain_base_path_mapping(domain_name, lambda_name, stage, base_path)\n        return self.apigateway_client.update_domain_name(domainName=domain_name,\n                                                         patchOperations=[\n                                                             {\"op\" : \"replace\",\n                                                              \"path\" : \"/certificateName\",\n                                                              \"value\" : certificate_name},\n                                                             {\"op\" : \"replace\",\n                                                              \"path\" : \"/certificateArn\",\n                                                              \"value\" : certificate_arn}\n                                                         ])",
    "docstring": "This updates your certificate information for an existing domain,\n        with similar arguments to boto's update_domain_name API Gateway api.\n\n        It returns the resulting new domain information including the new certificate's ARN\n        if created during this process.\n\n        Previously, this method involved downtime that could take up to 40 minutes\n        because the API Gateway api only allowed this by deleting, and then creating it.\n\n        Related issues:     https://github.com/Miserlou/Zappa/issues/590\n                            https://github.com/Miserlou/Zappa/issues/588\n                            https://github.com/Miserlou/Zappa/pull/458\n                            https://github.com/Miserlou/Zappa/issues/882\n                            https://github.com/Miserlou/Zappa/pull/883"
  },
  {
    "code": "def is_path_like(obj, attr=('name', 'is_file', 'is_dir', 'iterdir')):\n    for a in attr:\n        if not hasattr(obj, a):\n            return False\n    return True",
    "docstring": "test if object is pathlib.Path like"
  },
  {
    "code": "def wait_for_any_log(nodes, pattern, timeout, filename='system.log', marks=None):\n    if marks is None:\n        marks = {}\n    for _ in range(timeout):\n        for node in nodes:\n            found = node.grep_log(pattern, filename=filename, from_mark=marks.get(node, None))\n            if found:\n                return node\n        time.sleep(1)\n    raise TimeoutError(time.strftime(\"%d %b %Y %H:%M:%S\", time.gmtime()) +\n                       \" Unable to find: \" + repr(pattern) + \" in any node log within \" + str(timeout) + \"s\")",
    "docstring": "Look for a pattern in the system.log of any in a given list\n    of nodes.\n    @param nodes The list of nodes whose logs to scan\n    @param pattern The target pattern\n    @param timeout How long to wait for the pattern. Note that\n                    strictly speaking, timeout is not really a timeout,\n                    but a maximum number of attempts. This implies that\n                    the all the grepping takes no time at all, so it is\n                    somewhat inaccurate, but probably close enough.\n    @param marks A dict of nodes to marks in the file. Keys must match the first param list.\n    @return The first node in whose log the pattern was found"
  },
  {
    "code": "def _parse_phone(self, val):\n        ret = {\n            'type': None,\n            'value': None\n        }\n        try:\n            ret['type'] = val[1]['type']\n        except (IndexError, KeyError, ValueError, TypeError):\n                pass\n        ret['value'] = val[3].strip()\n        try:\n            self.vars['phone'].append(ret)\n        except AttributeError:\n            self.vars['phone'] = []\n            self.vars['phone'].append(ret)",
    "docstring": "The function for parsing the vcard phone numbers.\n\n        Args:\n            val (:obj:`list`): The value to parse."
  },
  {
    "code": "def dump_database_as_insert_sql(engine: Engine,\n                                fileobj: TextIO = sys.stdout,\n                                include_ddl: bool = False,\n                                multirow: bool = False) -> None:\n    for tablename in get_table_names(engine):\n        dump_table_as_insert_sql(\n            engine=engine,\n            table_name=tablename,\n            fileobj=fileobj,\n            include_ddl=include_ddl,\n            multirow=multirow\n        )",
    "docstring": "Reads an entire database and writes SQL to replicate it to the output\n    file-like object.\n\n    Args:\n        engine: SQLAlchemy :class:`Engine`\n        fileobj: file-like object to write to\n        include_ddl: if ``True``, include the DDL to create the table as well\n        multirow: write multi-row ``INSERT`` statements"
  },
  {
    "code": "def filter_req_paths(paths, func):\n    if not isinstance(paths, list):\n        raise ValueError(\"Paths must be a list of paths.\")\n    libs = set()\n    junk = set(['\\n'])\n    for p in paths:\n        with p.open(mode='r') as reqs:\n            lines = set([line for line in reqs if func(line)])\n            libs.update(lines)\n    return list(libs - junk)",
    "docstring": "Return list of filtered libs."
  },
  {
    "code": "def _register_service(self):\n        if (\n            self._registration is None\n            and self.specifications\n            and self.__validated\n            and self.__controller_on\n        ):\n            properties = self._ipopo_instance.context.properties.copy()\n            bundle_context = self._ipopo_instance.bundle_context\n            self._registration = bundle_context.register_service(\n                self.specifications,\n                self._ipopo_instance.instance,\n                properties,\n                factory=self.__is_factory,\n                prototype=self.__is_prototype,\n            )\n            self._svc_reference = self._registration.get_reference()\n            self._ipopo_instance.safe_callback(\n                ipopo_constants.IPOPO_CALLBACK_POST_REGISTRATION,\n                self._svc_reference,\n            )",
    "docstring": "Registers the provided service, if possible"
  },
  {
    "code": "def plot_probability_alive_matrix(\n    model,\n    max_frequency=None,\n    max_recency=None,\n    title=\"Probability Customer is Alive,\\nby Frequency and Recency of a Customer\",\n    xlabel=\"Customer's Historical Frequency\",\n    ylabel=\"Customer's Recency\",\n    **kwargs\n):\n    from matplotlib import pyplot as plt\n    z = model.conditional_probability_alive_matrix(max_frequency, max_recency)\n    interpolation = kwargs.pop(\"interpolation\", \"none\")\n    ax = plt.subplot(111)\n    pcm = ax.imshow(z, interpolation=interpolation, **kwargs)\n    plt.xlabel(xlabel)\n    plt.ylabel(ylabel)\n    plt.title(title)\n    forceAspect(ax)\n    plt.colorbar(pcm, ax=ax)\n    return ax",
    "docstring": "Plot probability alive matrix as heatmap.\n\n    Plot a figure of the probability a customer is alive based on their\n    frequency and recency.\n\n    Parameters\n    ----------\n    model: lifetimes model\n        A fitted lifetimes model.\n    max_frequency: int, optional\n        The maximum frequency to plot. Default is max observed frequency.\n    max_recency: int, optional\n        The maximum recency to plot. This also determines the age of the customer.\n        Default to max observed age.\n    title: str, optional\n        Figure title\n    xlabel: str, optional\n        Figure xlabel\n    ylabel: str, optional\n        Figure ylabel\n    kwargs\n        Passed into the matplotlib.imshow command.\n\n    Returns\n    -------\n    axes: matplotlib.AxesSubplot"
  },
  {
    "code": "def __reset_unique_identities(self):\n        self.log(\"Reseting unique identities...\")\n        self.log(\"Clearing identities relationships\")\n        nids = 0\n        uidentities = api.unique_identities(self.db)\n        for uidentity in uidentities:\n            for identity in uidentity.identities:\n                api.move_identity(self.db, identity.id, identity.id)\n                nids += 1\n        self.log(\"Relationships cleared for %s identities\" % nids)\n        self.log(\"Clearing enrollments\")\n        with self.db.connect() as session:\n            enrollments = session.query(Enrollment).all()\n            for enr in enrollments:\n                session.delete(enr)\n        self.log(\"Enrollments cleared\")",
    "docstring": "Clear identities relationships and enrollments data"
  },
  {
    "code": "def load(self):\n        javabridge.call(self.jobject, \"reset\", \"()V\")\n        return Instances(javabridge.call(self.jobject, \"getDataSet\", \"()Lweka/core/Instances;\"))",
    "docstring": "Loads the text files from the specified directory and returns the Instances object.\n        In case of incremental loading, only the structure.\n\n        :return: the full dataset or the header (if incremental)\n        :rtype: Instances"
  },
  {
    "code": "def in_app() -> bool:\n        try:\n            MirageEnvironment.set_import_root()\n            import apps\n            if os.path.isfile(\"apps.py\"):\n                return True\n            else:\n                return False\n        except ImportError:\n            return False\n        except:\n            return False",
    "docstring": "Judge where current working directory is in Django application or not.\n\n        returns:\n            - (Bool) cwd is in app dir returns True"
  },
  {
    "code": "def delete_tmp_dir(self):\n        logger.debug(\"Deleting: \" + self.tmp_dir)\n        shutil.rmtree(self.tmp_dir, True)",
    "docstring": "Delete the entire tmp dir"
  },
  {
    "code": "def __ordering_deprecated(self):\n        msg = _format(\"Ordering comparisons involving {0} objects are \"\n                      \"deprecated.\", self.__class__.__name__)\n        if DEBUG_WARNING_ORIGIN:\n            msg += \"\\nTraceback:\\n\" + ''.join(traceback.format_stack())\n        warnings.warn(msg, DeprecationWarning, stacklevel=3)",
    "docstring": "Deprecated warning for pywbem CIM Objects"
  },
  {
    "code": "def authenticate(self, reauth=False):\n        auth_url = BASE_URL + \"/rest/user\"\n        payload = {'email': self.email, 'password': self.password}\n        arequest = requests.get(auth_url, params=payload)\n        status = arequest.status_code\n        if status != 200:\n            if reauth:\n                _LOGGER.error(\"Reauthentication request failed. \" + status)\n            else:\n                _LOGGER.error(\"Authentication request failed, please check credintials. \" + status)\n        self.token = arequest.json().get('usertoken')\n        if reauth:\n            _LOGGER.info(\"Reauthentication was successful, token updated.\")\n        else:\n            _LOGGER.info(\"Authentication was successful, token set.\")",
    "docstring": "Authenticate with the API and return an authentication token."
  },
  {
    "code": "def rotate(self, angle, axis, point=None, radians=False):\n        q = Quaternion.angle_and_axis(angle=angle, axis=axis, radians=radians)\n        self._vector = q.rotate_vector(v=self._vector, point=point)\n        return",
    "docstring": "Rotates `Atom` by `angle`.\n\n        Parameters\n        ----------\n        angle : float\n            Angle that `Atom` will be rotated.\n        axis : 3D Vector (tuple, list, numpy.array)\n            Axis about which the `Atom` will be rotated.\n        point : 3D Vector (tuple, list, numpy.array), optional\n            Point that the `axis` lies upon. If `None` then the origin is used.\n        radians : bool, optional\n            True is `angle` is define in radians, False is degrees."
  },
  {
    "code": "def model_setup(self):\n        for device in self.devman.devices:\n            if self.__dict__[device].n:\n                try:\n                    self.__dict__[device].setup()\n                except Exception as e:\n                    raise e",
    "docstring": "Call the ``setup`` function of the loaded models. This function is\n        to be called after parsing all the data files during the system set up.\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def status(self):\n        return {self._acronym_status(l): l for l in self.resp_text.split('\\n')\n                if l.startswith(self.prefix_status)}",
    "docstring": "Development status."
  },
  {
    "code": "def get_volumes(self):\n        vols = [self.find_volume(name) for name in self.virsp.listVolumes()]\n        return vols",
    "docstring": "Return a list of all Volumes in this Storage Pool"
  },
  {
    "code": "def add_static_path(self, prefix: str, path: str) -> None:\n        pattern = prefix\n        if not pattern.startswith('/'):\n            pattern = '/' + pattern\n        if not pattern.endswith('/(.*)'):\n            pattern = pattern + '/(.*)'\n        self.add_handlers(\n            r'.*',\n            [(pattern, StaticFileHandler, dict(path=path))]\n        )",
    "docstring": "Add path to serve static files.\n\n        ``prefix`` is used for url prefix to serve static files and ``path`` is\n        a path to the static file directory. ``prefix = '/_static'`` is\n        reserved for the server, so do not use it for your app."
  },
  {
    "code": "def clear(self):\n        self.country_code = None\n        self.national_number = None\n        self.extension = None\n        self.italian_leading_zero = None\n        self.number_of_leading_zeros = None\n        self.raw_input = None\n        self.country_code_source = CountryCodeSource.UNSPECIFIED\n        self.preferred_domestic_carrier_code = None",
    "docstring": "Erase the contents of the object"
  },
  {
    "code": "def switch(self):\n        base_block = self.base_block or self\n        self.next_block = Block(\n            self.parent, base_block=base_block, py3_wrapper=self.py3_wrapper\n        )\n        return self.next_block",
    "docstring": "block has been split via | so we need to start a new block for that\n        option and return it to the user."
  },
  {
    "code": "def get_point(cls, idx, size):\n        x, y = cls.POSITION[idx % 4]\n        idx //= 4\n        block_size = 2\n        while block_size < size:\n            block_idx = idx % 4\n            x, y = cls.get_point_in_block(x, y, block_idx, block_size)\n            idx //= 4\n            block_size *= 2\n        return x, y",
    "docstring": "Get curve point coordinates by index.\n\n        Parameters\n        ----------\n        idx : `int`\n            Point index.\n        size : `int`\n            Curve size.\n\n        Returns\n        -------\n        (`int`, `int`)\n            Point coordinates."
  },
  {
    "code": "def create_nouns(max=2):\n    nouns = []\n    for noun in range(0, max):\n        nouns.append(random.choice(noun_list))\n    return \" \".join(nouns)",
    "docstring": "Return a string of random nouns up to max number"
  },
  {
    "code": "def _update_events(self):\n        events = self._skybell.dev_cache(self, CONST.EVENT) or {}\n        for activity in self._activities:\n            event = activity.get(CONST.EVENT)\n            created_at = activity.get(CONST.CREATED_AT)\n            old_event = events.get(event)\n            if old_event and created_at < old_event.get(CONST.CREATED_AT):\n                continue\n            else:\n                events[event] = activity\n        self._skybell.update_dev_cache(\n            self,\n            {\n                CONST.EVENT: events\n            })",
    "docstring": "Update our cached list of latest activity events."
  },
  {
    "code": "def import_family(self, rfa_file):\n        self._add_entry(templates.IMPORT_FAMILY\n                                 .format(family_file=rfa_file))",
    "docstring": "Append a import family entry to the journal.\n\n        This instructs Revit to import a family into the opened model.\n\n        Args:\n            rfa_file (str): full path of the family file"
  },
  {
    "code": "def remove_labels(self, test):\n        ii = 0\n        while ii < len(self.labels):\n            if test(self.labels[ii]):\n                self.labels.pop(ii)\n            else:\n                ii += 1\n        return self",
    "docstring": "Remove labels from this cell.\n\n        The function or callable ``test`` is called for each label in\n        the cell.  If its return value evaluates to ``True``, the\n        corresponding label is removed from the cell.\n\n        Parameters\n        ----------\n        test : callable\n            Test function to query whether a label should be removed.\n            The function is called with the label as the only argument.\n\n        Returns\n        -------\n        out : ``Cell``\n            This cell.\n\n        Examples\n        --------\n        Remove labels in layer 1:\n\n        >>> cell.remove_labels(lambda lbl: lbl.layer == 1)"
  },
  {
    "code": "def timeout(duration):\n    if not isinstance(duration, int):\n        raise TypeError(\"timeout duration should be a positive integer\")\n    if duration <= 0:\n        raise ValueError(\"timeoutDuration should be a positive integer\")\n    def decorator(func):\n        def wrapped_func(*args, **kwargs):\n            try:\n                def alarm_handler(signum, stack):\n                    raise TimeoutError()\n                signal.signal(signal.SIGALRM, alarm_handler)\n                signal.alarm(duration)\n                reply = func(*args, **kwargs)\n            except TimeoutError as e:\n                raise e\n            return reply\n        return wrapped_func\n    return decorator",
    "docstring": "A decorator to force a time limit on the execution of an external function.\n\n    :param int duration: the timeout duration\n\n    :raises: TypeError, if duration is anything other than integer\n\n    :raises: ValueError, if duration is a negative integer\n\n    :raises TimeoutError, if the external function execution crosses 'duration' time"
  },
  {
    "code": "def encode_offset_fetch_request(cls, group, payloads, from_kafka=False):\n        version = 1 if from_kafka else 0\n        return kafka.protocol.commit.OffsetFetchRequest[version](\n            consumer_group=group,\n            topics=[(\n                topic,\n                list(topic_payloads.keys()))\n            for topic, topic_payloads in six.iteritems(group_by_topic_and_partition(payloads))])",
    "docstring": "Encode an OffsetFetchRequest struct. The request is encoded using\n        version 0 if from_kafka is false, indicating a request for Zookeeper\n        offsets. It is encoded using version 1 otherwise, indicating a request\n        for Kafka offsets.\n\n        Arguments:\n            group: string, the consumer group you are fetching offsets for\n            payloads: list of OffsetFetchRequestPayload\n            from_kafka: bool, default False, set True for Kafka-committed offsets"
  },
  {
    "code": "def write_job(self,fh):\n    if isinstance(self.job(),CondorDAGManJob):\n      fh.write( ' '.join(\n        ['SUBDAG EXTERNAL', self.__name, self.__job.get_sub_file()]) )\n      if self.job().get_dag_directory():\n        fh.write( ' DIR ' + self.job().get_dag_directory() )\n    else:\n      fh.write( 'JOB ' + self.__name + ' ' + self.__job.get_sub_file() )\n    fh.write( '\\n')\n    fh.write( 'RETRY ' + self.__name + ' ' + str(self.__retry) + '\\n' )",
    "docstring": "Write the DAG entry for this node's job to the DAG file descriptor.\n    @param fh: descriptor of open DAG file."
  },
  {
    "code": "def is_available(self) -> bool:\n        status_response = self._client.get_state(\n            'api/monitors/daemonStatus/id:{}/daemon:zmc.json'.format(\n                self._monitor_id\n            )\n        )\n        if not status_response:\n            _LOGGER.warning('Could not get availability for monitor {}'.format(\n                self._monitor_id\n            ))\n            return False\n        monitor_status = self._raw_result.get('Monitor_Status', None)\n        capture_fps = monitor_status and monitor_status['CaptureFPS']\n        return status_response.get('status', False) and capture_fps != \"0.00\"",
    "docstring": "Indicate if this Monitor is currently available."
  },
  {
    "code": "def import_variables(self, container, varnames=None):\n        if varnames is None:\n            for keyword in self.tkvariables:\n                setattr(container, keyword, self.tkvariables[keyword])\n        else:\n            for keyword in varnames:\n                if keyword in self.tkvariables:\n                    setattr(container, keyword, self.tkvariables[keyword])",
    "docstring": "Helper method to avoid call get_variable for every variable."
  },
  {
    "code": "def _coulomb(n1, n2, k, r):\n    delta = [x2 - x1 for x1, x2 in zip(n1['velocity'], n2['velocity'])]\n    distance = sqrt(sum(d ** 2 for d in delta))\n    if distance < 0.1:\n        delta = [uniform(0.1, 0.2) for _ in repeat(None, 3)]\n        distance = sqrt(sum(d ** 2 for d in delta))\n    if distance < r:\n        force = (k / distance) ** 2\n        n1['force'] = [f - force * d for f, d in zip(n1['force'], delta)]\n        n2['force'] = [f + force * d for f, d in zip(n2['force'], delta)]",
    "docstring": "Calculates Coulomb forces and updates node data."
  },
  {
    "code": "def partition(self, dimension):\n        for i, channel in enumerate(self.u):\n            if self.v[i].shape[1] < dimension:\n                raise IndexError('Channel is max dimension %s'\n                                 % self.v[i].shape[1])\n            self.data[i] = channel[:, 0:dimension]\n        self.dimension = dimension\n        return self",
    "docstring": "Partition subspace into desired dimension.\n\n        :type dimension: int\n        :param dimension: Maximum dimension to use."
  },
  {
    "code": "def load(self, spec):\n        if spec.template is not None:\n            return self.loader.unicode(spec.template, spec.template_encoding)\n        path = self._find(spec)\n        return self.loader.read(path, spec.template_encoding)",
    "docstring": "Find and return the template associated to a TemplateSpec instance.\n\n        Returns the template as a unicode string.\n\n        Arguments:\n\n          spec: a TemplateSpec instance."
  },
  {
    "code": "def randomize(self, device=None, percent=100, silent=False):\n        volume = self.get_volume(device)\n        blocks = int(volume['size'] / BLOCK_SIZE)\n        num_writes = int(blocks * percent * 0.01)\n        offsets = sorted(random.sample(range(blocks), num_writes))\n        total = 0\n        if not silent:\n            print('Writing urandom to %s bytes in %s' % (volume['size'],\n                                                         volume['path']))\n        with open(volume['path'], 'w') as file:\n            for offset in offsets:\n                if not silent:\n                    self.dot()\n                file.seek(offset * BLOCK_SIZE)\n                data = os.urandom(32768) * 128\n                total += len(data)\n                file.write(data)\n        print(\"\\nWrote: %s\" % total)",
    "docstring": "Writes random data to the beginning of each 4MB block on a block device\n        this is useful when performance testing the backup process\n\n        (Without any optional arguments will randomize the first 32k of each\n        4MB block on 100 percent of the device)"
  },
  {
    "code": "def parse_nem_file(nem_file) -> NEMFile:\n    reader = csv.reader(nem_file, delimiter=',')\n    return parse_nem_rows(reader, file_name=nem_file)",
    "docstring": "Parse NEM file and return meter readings named tuple"
  },
  {
    "code": "def scan(self):\n        if self.implicit is not None:\n            return\n        self.implicit = []\n        self.implicit_set = set()\n        self._children_reset()\n        if not self.has_builder():\n            return\n        build_env = self.get_build_env()\n        executor = self.get_executor()\n        if implicit_cache and not implicit_deps_changed:\n            implicit = self.get_stored_implicit()\n            if implicit is not None:\n                for tgt in executor.get_all_targets():\n                    tgt.add_to_implicit(implicit)\n                if implicit_deps_unchanged or self.is_up_to_date():\n                    return\n                for tgt in executor.get_all_targets():\n                    tgt.implicit = []\n                    tgt.implicit_set = set()\n        executor.scan_sources(self.builder.source_scanner)\n        scanner = self.get_target_scanner()\n        if scanner:\n            executor.scan_targets(scanner)",
    "docstring": "Scan this node's dependents for implicit dependencies."
  },
  {
    "code": "def try_friends(self, others):\n        befriended = False\n        k = int(10*self['openness'])\n        shuffle(others)\n        for friend in islice(others, k):\n            if friend == self:\n                continue\n            if friend.befriend(self):\n                self.befriend(friend, force=True)\n                self.debug('Hooray! new friend: {}'.format(friend.id))\n                befriended = True\n            else:\n                self.debug('{} does not want to be friends'.format(friend.id))\n        return befriended",
    "docstring": "Look for random agents around me and try to befriend them"
  },
  {
    "code": "def canceled_plan_summary_for(self, year, month):\n\t\treturn (\n\t\t\tself.canceled_during(year, month)\n\t\t\t.values(\"plan\")\n\t\t\t.order_by()\n\t\t\t.annotate(count=models.Count(\"plan\"))\n\t\t)",
    "docstring": "Return Subscriptions canceled within a time range with plan counts annotated."
  },
  {
    "code": "def callback(self):\n        try:\n            return self._callback()\n        except:\n            s = straceback()\n            self.exceptions.append(s)\n            self.shutdown(msg=\"Exception raised in callback!\\n\" + s)",
    "docstring": "The function that will be executed by the scheduler."
  },
  {
    "code": "def find_trigger_value(psd_var, idx, start, sample_rate):\n    time = start + idx / sample_rate\n    ind = numpy.digitize(time, psd_var.sample_times)\n    ind -= 1\n    vals = psd_var[ind]\n    return vals",
    "docstring": "Find the PSD variation value at a particular time\n\n    Parameters\n    ----------\n    psd_var : TimeSeries\n        Time series of the varaibility in the PSD estimation\n    idx : numpy.ndarray\n        Time indices of the triggers\n    start : float\n        GPS start time\n    sample_rate : float\n        Sample rate defined in ini file\n\n    Returns\n    -------\n    vals : Array\n        PSD variation value at a particular time"
  },
  {
    "code": "def submit_if_ready(args, submit_args, config):\n    __, ext = os.path.splitext(args.input_file)\n    if ext.lower() != \".xml\":\n        return None\n    with io.open(args.input_file, encoding=\"utf-8\") as input_file:\n        xml = input_file.read(1024)\n    if not (\"<testsuites\" in xml or \"<testcases\" in xml or \"<requirements\" in xml):\n        return None\n    if args.no_submit:\n        logger.info(\"Nothing to do\")\n        return 0\n    response = dump2polarion.submit_and_verify(\n        xml_file=args.input_file, config=config, **submit_args\n    )\n    return 0 if response else 2",
    "docstring": "Submits the input XML file if it's already in the expected format."
  },
  {
    "code": "def make_string(seq):\n    string = ''\n    for c in seq:\n        try:\n            if 32 <= c and c < 256:\n                string += chr(c)\n        except TypeError:\n            pass\n    if not string:\n        return str(seq)\n    return string",
    "docstring": "Don't throw an exception when given an out of range character."
  },
  {
    "code": "def has_obsgroup_id(self, group_id):\n        self.con.execute('SELECT 1 FROM archive_obs_groups WHERE publicId = %s', (group_id,))\n        return len(self.con.fetchall()) > 0",
    "docstring": "Check for the presence of the given group_id\n\n        :param string group_id:\n            The group ID\n        :return:\n            True if we have a :class:`meteorpi_model.ObservationGroup` with this Id, False otherwise"
  },
  {
    "code": "def _process_blacklist(self, blacklist):\n        blacklist_cache = {}\n        blacklist_cache_old = self._cache.get('blacklist', {})\n        for entry in blacklist:\n            blackkey = (entry.version, entry.operator)\n            if blackkey in blacklist_cache:\n                continue\n            elif blackkey in blacklist_cache_old:\n                blacklist_cache[blackkey] = blacklist_cache_old[blackkey]\n            else:\n                entry_cache = blacklist_cache[blackkey] = set()\n                blackversion = parse_version(entry.version or '0')\n                blackop = OPERATORS[entry.operator]\n                for key in self:\n                    if blackop(parse_version(key), blackversion):\n                        entry_cache.add(key)\n        self._cache['blacklist'] = blacklist_cache\n        return set().union(*blacklist_cache.values())",
    "docstring": "Process blacklist into set of excluded versions"
  },
  {
    "code": "def csep_periodic(ra, rb, L):\n    seps = ra[:, np.newaxis, :] - rb[np.newaxis, :, :]\n    for i_dim in range(ra.shape[1]):\n        seps_dim = seps[:, :, i_dim]\n        seps_dim[seps_dim > L[i_dim] / 2.0] -= L[i_dim]\n        seps_dim[seps_dim < -L[i_dim] / 2.0] += L[i_dim]\n    return seps",
    "docstring": "Return separation vectors between each pair of the two sets of points.\n\n    Parameters\n    ----------\n    ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.\n        Two sets of points.\n    L: float array, shape (d,)\n        System lengths.\n\n    Returns\n    -------\n    csep: float array-like, shape (n, m, d)\n        csep[i, j] is the separation vector from point j to point i.\n        Note the un-intuitive vector direction."
  },
  {
    "code": "def min_sequence_length(self, dataset_split):\n    return {\n        problem.DatasetSplit.TRAIN: 8,\n        problem.DatasetSplit.EVAL: 65,\n        problem.DatasetSplit.TEST: 65\n    }[dataset_split]",
    "docstring": "Determine the minimum sequence length given a dataset_split.\n\n    Args:\n      dataset_split: A problem.DatasetSplit.\n\n    Returns:\n      The minimum length that a sequence can be for this dataset_split."
  },
  {
    "code": "def get_base_input(test=False):\n    from django.forms.widgets import DateTimeBaseInput\n    if 'get_context' in dir(DateTimeBaseInput) and not test:\n        base_input = DateTimeBaseInput\n    else:\n        from bootstrap_datepicker_plus._compatibility import (\n            CompatibleDateTimeBaseInput\n        )\n        base_input = CompatibleDateTimeBaseInput\n    return base_input",
    "docstring": "Return DateTimeBaseInput class from django.forms.widgets module\n\n    Return _compatibility.DateTimeBaseInput class for older django versions."
  },
  {
    "code": "def addNode(self, node):\n        self.mybldgbuids[node.buid] = node\n        self.allbldgbuids[node.buid] = (node, self.doneevent)",
    "docstring": "Update the shared map with my in-construction node"
  },
  {
    "code": "def _encode_image(self, np_image):\n    if np_image.dtype != np.uint8:\n      raise ValueError('Image should be uint8. Detected: %s.' % np_image.dtype)\n    utils.assert_shape_match(np_image.shape, self._shape)\n    return self._runner.run(ENCODE_FN[self._encoding_format], np_image)",
    "docstring": "Returns np_image encoded as jpeg or png."
  },
  {
    "code": "def create_bokeh_server(io_loop, files, argvs, host, port):\n    from bokeh.server.server import Server\n    from bokeh.command.util import build_single_handler_applications\n    apps = build_single_handler_applications(files, argvs)\n    kwargs = {\n        'io_loop':io_loop,\n        'generate_session_ids':True,\n        'redirect_root':True,\n        'use_x_headers':False,\n        'secret_key':None,\n        'num_procs':1,\n        'host': host,\n        'sign_sessions':False,\n        'develop':False,\n        'port':port,\n        'use_index':True\n    }\n    server = Server(apps,**kwargs)\n    return server",
    "docstring": "Start bokeh server with applications paths"
  },
  {
    "code": "def secure(func_or_obj, check_permissions_for_obj=None):\n    if _allowed_check_permissions_types(func_or_obj):\n        return _secure_method(func_or_obj)\n    else:\n        if not _allowed_check_permissions_types(check_permissions_for_obj):\n            msg = \"When securing an object, secure() requires the \" + \\\n                  \"second argument to be method\"\n            raise TypeError(msg)\n        return _SecuredAttribute(func_or_obj, check_permissions_for_obj)",
    "docstring": "This method secures a method or class depending on invocation.\n\n    To decorate a method use one argument:\n        @secure(<check_permissions_method>)\n\n    To secure a class, invoke with two arguments:\n        secure(<obj instance>, <check_permissions_method>)"
  },
  {
    "code": "def search(self, index_name, query):\n        try:\n            results = self.els_search.search(index=index_name, body=query)\n            return results\n        except Exception, error:\n            error_str = 'Query failed: %s\\n' % str(error)\n            error_str += '\\nIs there a dynamic script in the query?, see www.elasticsearch.org'\n            print error_str\n            raise RuntimeError(error_str)",
    "docstring": "Search the given index_name with the given ELS query.\n\n        Args:\n            index_name: Name of the Index\n            query: The string to be searched.\n\n        Returns:\n            List of results.\n\n        Raises:\n            RuntimeError: When the search query fails."
  },
  {
    "code": "def _get_openstack_release(self):\n        for i, os_pair in enumerate(OPENSTACK_RELEASES_PAIRS):\n            setattr(self, os_pair, i)\n        releases = {\n            ('trusty', None): self.trusty_icehouse,\n            ('trusty', 'cloud:trusty-kilo'): self.trusty_kilo,\n            ('trusty', 'cloud:trusty-liberty'): self.trusty_liberty,\n            ('trusty', 'cloud:trusty-mitaka'): self.trusty_mitaka,\n            ('xenial', None): self.xenial_mitaka,\n            ('xenial', 'cloud:xenial-newton'): self.xenial_newton,\n            ('xenial', 'cloud:xenial-ocata'): self.xenial_ocata,\n            ('xenial', 'cloud:xenial-pike'): self.xenial_pike,\n            ('xenial', 'cloud:xenial-queens'): self.xenial_queens,\n            ('yakkety', None): self.yakkety_newton,\n            ('zesty', None): self.zesty_ocata,\n            ('artful', None): self.artful_pike,\n            ('bionic', None): self.bionic_queens,\n            ('bionic', 'cloud:bionic-rocky'): self.bionic_rocky,\n            ('bionic', 'cloud:bionic-stein'): self.bionic_stein,\n            ('cosmic', None): self.cosmic_rocky,\n            ('disco', None): self.disco_stein,\n        }\n        return releases[(self.series, self.openstack)]",
    "docstring": "Get openstack release.\n\n           Return an integer representing the enum value of the openstack\n           release."
  },
  {
    "code": "def header(self):\n        chunk_size = a2b_hex('%08x' % (len(self.track_data)\n                              + len(self.end_of_track())))\n        return TRACK_HEADER + chunk_size",
    "docstring": "Return the bytes for the header of track.\n\n        The header contains the length of the track_data, so you'll have to\n        call this function when you're done adding data (when you're not\n        using get_midi_data)."
  },
  {
    "code": "def render_app_name(context, app, template=\"/admin_app_name.html\"):\n    try:\n        template = app['app_label'] + template\n        text = render_to_string(template, context)\n    except:\n        text = app['name']\n    return text",
    "docstring": "Render the application name using the default template name. If it cannot find a\n        template matching the given path, fallback to the application name."
  },
  {
    "code": "def on_step_end(self, step, logs={}):\n        self.total_steps += 1\n        if self.total_steps % self.interval != 0:\n            return\n        filepath = self.filepath.format(step=self.total_steps, **logs)\n        if self.verbose > 0:\n            print('Step {}: saving model to {}'.format(self.total_steps, filepath))\n        self.model.save_weights(filepath, overwrite=True)",
    "docstring": "Save weights at interval steps during training"
  },
  {
    "code": "def fill_window(self, seqNum):\n        if _debug: SSM._debug(\"fill_window %r\", seqNum)\n        if _debug: SSM._debug(\"    - actualWindowSize: %r\", self.actualWindowSize)\n        for ix in range(self.actualWindowSize):\n            apdu = self.get_segment(seqNum + ix)\n            self.ssmSAP.request(apdu)\n            if not apdu.apduMor:\n                self.sentAllSegments = True\n                break",
    "docstring": "This function sends all of the packets necessary to fill\n        out the segmentation window."
  },
  {
    "code": "def vacuum(self, threshold=0.3):\n        url = (\"http://{master_addr}:{master_port}/\"\n               \"vol/vacuum?garbageThreshold={threshold}\").format(\n            master_addr=self.master_addr,\n            master_port=self.master_port,\n            threshold=threshold)\n        res = self.conn.get_data(url)\n        if res is not None:\n            return True\n        return False",
    "docstring": "Force garbage collection\n\n        :param float threshold (optional): The threshold is optional, and\n        will not change the default threshold.\n        :rtype: boolean"
  },
  {
    "code": "def handleHeader(self, key, value):\n        if key == 'CIMError':\n            self.CIMError = urllib.parse.unquote(value)\n        if key == 'PGErrorDetail':\n            self.PGErrorDetail = urllib.parse.unquote(value)",
    "docstring": "Handle header values."
  },
  {
    "code": "def preLoad(self):\n    logging.getLogger().debug(\"Preloading segment '%s'\" % (self))\n    real_url = self.buildUrl()\n    cache_url = self.buildUrl(cache_friendly=True)\n    audio_data = self.download(real_url)\n    assert(audio_data)\n    __class__.cache[cache_url] = audio_data",
    "docstring": "Store audio data in cache for fast playback."
  },
  {
    "code": "def _to_number(cls, string):\n        try:\n            if float(string) - int(string) == 0:\n                return int(string)\n            return float(string)\n        except ValueError:\n            try:\n                return float(string)\n            except ValueError:\n                return string",
    "docstring": "Convert string to int or float."
  },
  {
    "code": "def make_symlink(source, link_path):\n    if not supports_symlinks():\n        dbt.exceptions.system_error('create a symbolic link')\n    return os.symlink(source, link_path)",
    "docstring": "Create a symlink at `link_path` referring to `source`."
  },
  {
    "code": "def plot_color_map_bars(values, vmin=None, vmax=None, color_map=None,\n                        axis=None, **kwargs):\n    if axis is None:\n        fig, axis = plt.subplots()\n    norm = mpl.colors.Normalize(vmin=vmin or min(values),\n                                vmax=vmax or max(values), clip=True)\n    if color_map is None:\n        color_map = mpl.rcParams['image.cmap']\n    colors = color_map(norm(values.values).filled())\n    values.plot(kind='bar', ax=axis, color=colors, **kwargs)\n    return axis",
    "docstring": "Plot bar for each value in `values`, colored based on values mapped onto\n    the specified color map.\n\n    Args\n    ----\n\n        values (pandas.Series) : Numeric values to plot one bar per value.\n        axis : A matplotlib axis.  If `None`, an axis is created.\n        vmin : Minimum value to clip values at.\n        vmax : Maximum value to clip values at.\n        color_map : A matplotlib color map (see `matplotlib.cm`).\n        **kwargs : Extra keyword arguments to pass to `values.plot`.\n\n    Returns\n    -------\n\n        (axis) : Bar plot axis."
  },
  {
    "code": "def schoice(self, seq: str, end: int = 10) -> str:\n        return ''.join(self.choice(list(seq))\n                       for _ in range(end))",
    "docstring": "Choice function which returns string created from sequence.\n\n        :param seq: Sequence of letters or digits.\n        :type seq: tuple or list\n        :param end: Max value.\n        :return: Single string."
  },
  {
    "code": "def serialize_me(self, arn, event_time, tech, item=None):\n        payload = {\n            'arn': arn,\n            'event_time': event_time,\n            'tech': tech\n        }\n        if item:\n            payload['item'] = item\n        else:\n            payload['event_too_big'] = True\n        return self.dumps(payload).data.replace('<empty>', '')",
    "docstring": "Dumps the proper JSON for the schema. If the event is too big, then don't include the item.\n\n        :param arn:\n        :param event_time:\n        :param tech:\n        :param item:\n        :return:"
  },
  {
    "code": "def run(quiet, args):\n    if not args:\n        raise ClickException('pass a command to run')\n    cmd = ' '.join(args)\n    application = get_current_application()\n    name = application.name\n    settings = os.environ.get('DJANGO_SETTINGS_MODULE', '%s.settings' % name)\n    return application.run(\n        cmd,\n        verbose=not quiet,\n        abort=False,\n        capture=True,\n        env={\n            'DJANGO_SETTINGS_MODULE': settings\n        }\n    )",
    "docstring": "Run a local command.\n\n    Examples:\n\n    $ django run manage.py runserver\n\n    ..."
  },
  {
    "code": "def append(self, data):\n        t = self.tell()\n        self.seek(0, 2)\n        if hasattr(data, 'getvalue'):\n            self.write_utf8_string(data.getvalue())\n        else:\n            self.write_utf8_string(data)\n        self.seek(t)",
    "docstring": "Append data to the end of the stream. The pointer will not move if\n        this operation is successful.\n\n        @param data: The data to append to the stream.\n        @type data: C{str} or C{unicode}\n        @raise TypeError: data is not C{str} or C{unicode}"
  },
  {
    "code": "def cancel(self, invoice_id, **kwargs):\n        url = \"{}/{}/cancel\".format(self.base_url, invoice_id)\n        return self.post_url(url, {}, **kwargs)",
    "docstring": "Cancel an unpaid Invoice with given ID via API\n        It can only be called on an invoice that is not in the paid state.\n\n        Args:\n            invoice_id : Id for cancel the invoice\n        Returns:\n            The response for the API will be the invoice entity, similar to create/update API response, with status attribute's value as cancelled"
  },
  {
    "code": "def merge(self, other, inplace=None, overwrite_vars=frozenset(),\n              compat='no_conflicts', join='outer'):\n        inplace = _check_inplace(inplace)\n        variables, coord_names, dims = dataset_merge_method(\n            self, other, overwrite_vars=overwrite_vars, compat=compat,\n            join=join)\n        return self._replace_vars_and_dims(variables, coord_names, dims,\n                                           inplace=inplace)",
    "docstring": "Merge the arrays of two datasets into a single dataset.\n\n        This method generally not allow for overriding data, with the exception\n        of attributes, which are ignored on the second dataset. Variables with\n        the same name are checked for conflicts via the equals or identical\n        methods.\n\n        Parameters\n        ----------\n        other : Dataset or castable to Dataset\n            Dataset or variables to merge with this dataset.\n        inplace : bool, optional\n            If True, merge the other dataset into this dataset in-place.\n            Otherwise, return a new dataset object.\n        overwrite_vars : str or sequence, optional\n            If provided, update variables of these name(s) without checking for\n            conflicts in this dataset.\n        compat : {'broadcast_equals', 'equals', 'identical',\n                  'no_conflicts'}, optional\n            String indicating how to compare variables of the same name for\n            potential conflicts:\n            - 'broadcast_equals': all values must be equal when variables are\n              broadcast against each other to ensure common dimensions.\n            - 'equals': all values and dimensions must be the same.\n            - 'identical': all values, dimensions and attributes must be the\n              same.\n            - 'no_conflicts': only values which are not null in both datasets\n              must be equal. The returned dataset then contains the combination\n              of all non-null values.\n        join : {'outer', 'inner', 'left', 'right', 'exact'}, optional\n            Method for joining ``self`` and ``other`` along shared dimensions:\n\n            - 'outer': use the union of the indexes\n            - 'inner': use the intersection of the indexes\n            - 'left': use indexes from ``self``\n            - 'right': use indexes from ``other``\n            - 'exact': error instead of aligning non-equal indexes\n\n        Returns\n        -------\n        merged : Dataset\n            Merged dataset.\n\n        Raises\n        ------\n        MergeError\n            If any variables conflict (see ``compat``)."
  },
  {
    "code": "def ReplaceAttachment(self, attachment_link, attachment, options=None):\n        if options is None:\n            options = {}\n        CosmosClient.__ValidateResource(attachment)\n        path = base.GetPathFromLink(attachment_link)\n        attachment_id = base.GetResourceIdOrFullNameFromLink(attachment_link)\n        return self.Replace(attachment,\n                            path,\n                            'attachments',\n                            attachment_id,\n                            None,\n                            options)",
    "docstring": "Replaces an attachment and returns it.\n\n        :param str attachment_link:\n            The link to the attachment.\n        :param dict attachment:\n        :param dict options:\n            The request options for the request.\n\n        :return:\n            The replaced Attachment\n        :rtype:\n            dict"
  },
  {
    "code": "def add_nodes(self, lb, nodes):\n        if not isinstance(nodes, (list, tuple)):\n            nodes = [nodes]\n        node_dicts = [nd.to_dict() for nd in nodes]\n        resp, body = self.api.method_post(\"/loadbalancers/%s/nodes\" % lb.id,\n                body={\"nodes\": node_dicts})\n        return resp, body",
    "docstring": "Adds the list of nodes to the specified load balancer."
  },
  {
    "code": "def flat_unity(length, delta_f, low_freq_cutoff):\n    fseries = FrequencySeries(numpy.ones(length), delta_f=delta_f)\n    kmin = int(low_freq_cutoff / fseries.delta_f)\n    fseries.data[:kmin] = 0\n    return fseries",
    "docstring": "Returns a FrequencySeries of ones above the low_frequency_cutoff.\n\n    Parameters\n    ----------\n    length : int\n        Length of output Frequencyseries.\n    delta_f : float\n        Frequency step for output FrequencySeries.\n    low_freq_cutoff : int\n        Low-frequency cutoff for output FrequencySeries.\n\n    Returns\n    -------\n    FrequencySeries\n        Returns a FrequencySeries containing the unity PSD model."
  },
  {
    "code": "def to_utc_date(date):\n    return datetime.utcfromtimestamp(float(date.strftime('%s'))).replace(tzinfo=None) if date else None",
    "docstring": "Convert a datetime object from local to UTC format\n\n    >>> import datetime\n    >>> d = datetime.datetime(2017, 8, 15, 18, 24, 31)\n    >>> to_utc_date(d)\n    datetime.datetime(2017, 8, 16, 1, 24, 31)\n\n    Args:\n        date (`datetime`): Input datetime object\n\n    Returns:\n        `datetime`"
  },
  {
    "code": "def add_matplotlib_cmaps(fail_on_import_error=True):\n    try:\n        from matplotlib import cm as _cm\n        from matplotlib.cbook import mplDeprecation\n    except ImportError:\n        if fail_on_import_error:\n            raise\n        return\n    for name in _cm.cmap_d:\n        if not isinstance(name, str):\n            continue\n        try:\n            with warnings.catch_warnings():\n                warnings.simplefilter('error', mplDeprecation)\n                cm = _cm.get_cmap(name)\n                add_matplotlib_cmap(cm, name=name)\n        except Exception as e:\n            if fail_on_import_error:\n                print(\"Error adding colormap '%s': %s\" % (name, str(e)))",
    "docstring": "Add all matplotlib colormaps."
  },
  {
    "code": "def fit(self, data, debug=False):\n        data = util.apply_filter_query(data, self.fit_filters)\n        unique = data[self.segmentation_col].unique()\n        value_counts = data[self.segmentation_col].value_counts()\n        gone = set(self._group.models) - set(unique)\n        for g in gone:\n            del self._group.models[g]\n        for x in unique:\n            if x not in self._group.models and \\\n                    value_counts[x] > self.min_segment_size:\n                self.add_segment(x)\n        with log_start_finish(\n                'fitting models in segmented model {}'.format(self.name),\n                logger):\n            return self._group.fit(data, debug=debug)",
    "docstring": "Fit each segment. Segments that have not already been explicitly\n        added will be automatically added with default model and ytransform.\n\n        Parameters\n        ----------\n        data : pandas.DataFrame\n            Must have a column with the same name as `segmentation_col`.\n        debug : bool\n            If set to true will pass debug to the fit method of each model.\n\n        Returns\n        -------\n        fits : dict of statsmodels.regression.linear_model.OLSResults\n            Keys are the segment names."
  },
  {
    "code": "def assign(self, pm):\n        if isinstance(pm, QPixmap):\n            self._pm = pm\n        else:\n            self._xpmstr = pm\n            self._pm = None\n        self._icon = None",
    "docstring": "Reassign pixmap or xpm string array to wrapper"
  },
  {
    "code": "def _get_deleted_at_column(self, builder):\n        if len(builder.get_query().joins) > 0:\n            return builder.get_model().get_qualified_deleted_at_column()\n        else:\n            return builder.get_model().get_deleted_at_column()",
    "docstring": "Get the \"deleted at\" column for the builder.\n\n        :param builder: The query builder\n        :type builder: orator.orm.builder.Builder\n\n        :rtype: str"
  },
  {
    "code": "def pause(self, message: Optional[Message_T] = None, **kwargs) -> None:\n        if message:\n            asyncio.ensure_future(self.send(message, **kwargs))\n        raise _PauseException",
    "docstring": "Pause the session for further interaction."
  },
  {
    "code": "def _resolve_key(self, key):\n        with self._reserve(key):\n            factory = self.factory_for(key)\n            with self._profiler(key):\n                component = factory(self)\n            invoke_resolve_hook(component)\n        return self.assign(key, component)",
    "docstring": "Attempt to lazily create a component.\n\n        :raises NotBoundError: if the component does not have a bound factory\n        :raises CyclicGraphError: if the factory function requires a cycle\n        :raises LockedGraphError: if the graph is locked"
  },
  {
    "code": "def _recursive_merged_items(self, index):\n        subdirs = [os.path.join(d, \"parts\", str(index)) for d in self.localdirs]\n        m = ExternalMerger(self.agg, self.memory_limit, self.serializer, subdirs,\n                           self.scale * self.partitions, self.partitions, self.batch)\n        m.pdata = [{} for _ in range(self.partitions)]\n        limit = self._next_limit()\n        for j in range(self.spills):\n            path = self._get_spill_dir(j)\n            p = os.path.join(path, str(index))\n            with open(p, 'rb') as f:\n                m.mergeCombiners(self.serializer.load_stream(f), 0)\n            if get_used_memory() > limit:\n                m._spill()\n                limit = self._next_limit()\n        return m._external_items()",
    "docstring": "merge the partitioned items and return the as iterator\n\n        If one partition can not be fit in memory, then them will be\n        partitioned and merged recursively."
  },
  {
    "code": "def create_alarm_subscription(self,\n                                  on_data=None,\n                                  timeout=60):\n        manager = WebSocketSubscriptionManager(self._client, resource='alarms')\n        subscription = AlarmSubscription(manager)\n        wrapped_callback = functools.partial(\n            _wrap_callback_parse_alarm_data, subscription, on_data)\n        manager.open(wrapped_callback, instance=self._instance,\n                     processor=self._processor)\n        subscription.reply(timeout=timeout)\n        return subscription",
    "docstring": "Create a new alarm subscription.\n\n        :param on_data: Function that gets called with  :class:`.AlarmEvent`\n                        updates.\n        :param float timeout: The amount of seconds to wait for the request\n                              to complete.\n\n        :return: A Future that can be used to manage the background websocket\n                 subscription.\n        :rtype: .AlarmSubscription"
  },
  {
    "code": "def from_file(cls, h5_file):\n        return cls({\n            country: HDF5DailyBarReader.from_file(h5_file, country)\n            for country in h5_file.keys()\n        })",
    "docstring": "Construct from an h5py.File.\n\n        Parameters\n        ----------\n        h5_file : h5py.File\n            An HDF5 daily pricing file."
  },
  {
    "code": "def geometricBar(weights, alldistribT):\n    assert(len(weights) == alldistribT.shape[1])\n    return np.exp(np.dot(np.log(alldistribT), weights.T))",
    "docstring": "return the weighted geometric mean of distributions"
  },
  {
    "code": "def read_plugin_config(self):\n        folders = self.config[\"pluginfolders\"]\n        modules = plugins.get_plugin_modules(folders)\n        for pluginclass in plugins.get_plugin_classes(modules):\n            section = pluginclass.__name__\n            if self.has_section(section):\n                self.config[\"enabledplugins\"].append(section)\n                self.config[section] = pluginclass.read_config(self)",
    "docstring": "Read plugin-specific configuration values."
  },
  {
    "code": "def download(self, streamed=False, action=None, chunk_size=1024, **kwargs):\n        path = '/projects/%s/export/download' % self.project_id\n        result = self.manager.gitlab.http_get(path, streamed=streamed,\n                                              raw=True, **kwargs)\n        return utils.response_content(result, streamed, action, chunk_size)",
    "docstring": "Download the archive of a project export.\n\n        Args:\n            streamed (bool): If True the data will be processed by chunks of\n                `chunk_size` and each chunk is passed to `action` for\n                reatment\n            action (callable): Callable responsible of dealing with chunk of\n                data\n            chunk_size (int): Size of each chunk\n            **kwargs: Extra options to send to the server (e.g. sudo)\n\n        Raises:\n            GitlabAuthenticationError: If authentication is not correct\n            GitlabGetError: If the server failed to perform the request\n\n        Returns:\n            str: The blob content if streamed is False, None otherwise"
  },
  {
    "code": "def _build_idp_config_endpoints(self, config, providers):\n        idp_endpoints = []\n        for endp_category in self.endpoints:\n            for func, endpoint in self.endpoints[endp_category].items():\n                for provider in providers:\n                    _endpoint = \"{base}/{provider}/{endpoint}\".format(\n                        base=self.base_url, provider=provider, endpoint=endpoint)\n                    idp_endpoints.append((_endpoint, func))\n            config[\"service\"][\"idp\"][\"endpoints\"][endp_category] = idp_endpoints\n        return config",
    "docstring": "Builds the final frontend module config\n\n        :type config: dict[str, Any]\n        :type providers: list[str]\n        :rtype: dict[str, Any]\n\n        :param config: The module config\n        :param providers: A list of backend names\n        :return: The final config"
  },
  {
    "code": "def handle():\n    try:\n        cli = ZappaCLI()\n        sys.exit(cli.handle())\n    except SystemExit as e:\n        cli.on_exit()\n        sys.exit(e.code)\n    except KeyboardInterrupt:\n        cli.on_exit()\n        sys.exit(130)\n    except Exception as e:\n        cli.on_exit()\n        click.echo(\"Oh no! An \" + click.style(\"error occurred\", fg='red', bold=True) + \"! :(\")\n        click.echo(\"\\n==============\\n\")\n        import traceback\n        traceback.print_exc()\n        click.echo(\"\\n==============\\n\")\n        shamelessly_promote()\n        sys.exit(-1)",
    "docstring": "Main program execution handler."
  },
  {
    "code": "def get_instance(self, payload):\n        return AuthCallsCredentialListMappingInstance(\n            self._version,\n            payload,\n            account_sid=self._solution['account_sid'],\n            domain_sid=self._solution['domain_sid'],\n        )",
    "docstring": "Build an instance of AuthCallsCredentialListMappingInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance\n        :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance"
  },
  {
    "code": "def build_cycle_time(self, build_id):\n        json_form = self.__retrieve_as_json(self.builds_path % build_id)\n        return BuildCycleTime(\n            build_id,\n            json_form[u'buildTypeId'],\n            as_date(json_form, u'startDate'),\n            (as_date(json_form, u'finishDate') - as_date(json_form, u'queuedDate')).seconds * 1000\n        )",
    "docstring": "Returns a BuildCycleTime object for the given build"
  },
  {
    "code": "def _get_cmd(cmd):\n    check_cmd = \"RunTHetA.py\"\n    try:\n        local_cmd = subprocess.check_output([\"which\", check_cmd]).strip()\n    except subprocess.CalledProcessError:\n        return None\n    return [sys.executable, \"%s/%s\" % (os.path.dirname(os.path.realpath(local_cmd)), cmd)]",
    "docstring": "Retrieve required commands for running THetA with our local bcbio python."
  },
  {
    "code": "def process_wildcard(fractions):\n    wildcard_zs = set()\n    total_fraction = 0.0\n    for z, fraction in fractions.items():\n        if fraction == '?':\n            wildcard_zs.add(z)\n        else:\n            total_fraction += fraction\n    if not wildcard_zs:\n        return fractions\n    balance_fraction = (1.0 - total_fraction) / len(wildcard_zs)\n    for z in wildcard_zs:\n        fractions[z] = balance_fraction\n    return fractions",
    "docstring": "Processes element with a wildcard ``?`` weight fraction and returns\n    composition balanced to 1.0."
  },
  {
    "code": "def download_file(self, url, local_path):\n        response = requests.get(url, stream=True)\n        with open(local_path, 'wb') as f:\n            for chunk in tqdm(response.iter_content(chunk_size=1024), unit='KB'):\n                if chunk:\n                    f.write(chunk)\n                    f.flush()",
    "docstring": "Download a file from a remote host."
  },
  {
    "code": "def list_values(hive, key=None, use_32bit_registry=False, include_default=True):\n    r\n    return __utils__['reg.list_values'](hive=hive,\n                                        key=key,\n                                        use_32bit_registry=use_32bit_registry,\n                                        include_default=include_default)",
    "docstring": "r'''\n    Enumerates the values in a registry key or hive.\n\n    Args:\n\n        hive (str):\n            The name of the hive. Can be one of the following:\n\n                - HKEY_LOCAL_MACHINE or HKLM\n                - HKEY_CURRENT_USER or HKCU\n                - HKEY_USER or HKU\n                - HKEY_CLASSES_ROOT or HKCR\n                - HKEY_CURRENT_CONFIG or HKCC\n\n        key (str):\n            The key (looks like a path) to the value name. If a key is not\n            passed, the values under the hive will be returned.\n\n        use_32bit_registry (bool):\n            Accesses the 32bit portion of the registry on 64 bit installations.\n            On 32bit machines this is ignored.\n\n        include_default (bool):\n            Toggle whether to include the '(Default)' value.\n\n    Returns:\n        list: A list of values under the hive or key.\n\n    CLI Example:\n\n        .. code-block:: bash\n\n            salt '*' reg.list_values HKLM 'SYSTEM\\\\CurrentControlSet\\\\Services\\\\Tcpip'"
  },
  {
    "code": "def lazy_property(fn):\n    attr_name = '_lazy_' + fn.__name__\n    @property\n    @wraps(fn)\n    def _lazy_property(self):\n        if not hasattr(self, attr_name):\n            setattr(self, attr_name, fn(self))\n        return getattr(self, attr_name)\n    return _lazy_property",
    "docstring": "Decorator that makes a property lazy-evaluated whilst preserving\n    docstrings.\n\n    Args:\n        fn (function): the property in question\n\n    Returns:\n        evaluated version of the property."
  },
  {
    "code": "def get_opener(self, name):\n        if name not in self.registry:\n            raise NoOpenerError(\"No opener for %s\" % name)\n        index = self.registry[name]\n        return self.openers[index]",
    "docstring": "Retrieve an opener for the given protocol\n\n        :param name: name of the opener to open\n        :type name: string\n        :raises NoOpenerError: if no opener has been registered of that name"
  },
  {
    "code": "def connect(self, nice_quit_ev):\n        _logger.debug(\"Connecting to explicit server node: [%s]\", \n                      self.server_host)\n        try:\n            c = self.primitive_connect()\n        except gevent.socket.error:\n            _logger.exception(\"Could not connect to explicit server: [%s]\",\n                              self.server_host)\n            raise nsq.exceptions.NsqConnectGiveUpError(\n                    \"Could not connect to the nsqd server: [%s]\" % \n                    (self.server_host,))\n        _logger.info(\"Explicit server-node connected: [%s]\", self.server_host)\n        return c",
    "docstring": "Connect the server. We expect this to implement connection logistics \n        for servers that were explicitly prescribed to us."
  },
  {
    "code": "def iterate_schema(fields, schema, path_prefix=''):\n    if path_prefix and path_prefix[-1] != '.':\n        path_prefix += '.'\n    for field_schema in schema:\n        name = field_schema['name']\n        if 'group' in field_schema:\n            for rvals in iterate_schema(fields[name] if name in fields else {},\n                                        field_schema['group'], '{}{}'.format(path_prefix, name)):\n                yield rvals\n        else:\n            yield (field_schema, fields, '{}{}'.format(path_prefix, name))",
    "docstring": "Iterate over all schema sub-fields.\n\n    This will iterate over all field definitions in the schema. Some field v\n    alues might be None.\n\n    :param fields: field values to iterate over\n    :type fields: dict\n    :param schema: schema to iterate over\n    :type schema: dict\n    :param path_prefix: dot separated path prefix\n    :type path_prefix: str\n    :return: (field schema, field value, field path)\n    :rtype: tuple"
  },
  {
    "code": "def add_ds_ids_from_files(self):\n        for file_handlers in self.file_handlers.values():\n            try:\n                fh = file_handlers[0]\n                avail_ids = fh.available_datasets()\n            except NotImplementedError:\n                continue\n            for ds_id, ds_info in avail_ids:\n                coordinates = ds_info.get('coordinates')\n                if isinstance(coordinates, list):\n                    ds_info['coordinates'] = tuple(ds_info['coordinates'])\n                self.ids.setdefault(ds_id, ds_info)",
    "docstring": "Check files for more dynamically discovered datasets."
  },
  {
    "code": "def case_sensitive_name(self, package_name):\n        if len(self.environment[package_name]):\n            return self.environment[package_name][0].project_name",
    "docstring": "Return case-sensitive package name given any-case package name\n\n        @param project_name: PyPI project name\n        @type project_name: string"
  },
  {
    "code": "def download_if_not_exists(url: str, filename: str,\n                           skip_cert_verify: bool = True,\n                           mkdir: bool = True) -> None:\n    if os.path.isfile(filename):\n        log.info(\"No need to download, already have: {}\", filename)\n        return\n    if mkdir:\n        directory, basename = os.path.split(os.path.abspath(filename))\n        mkdir_p(directory)\n    download(url=url,\n             filename=filename,\n             skip_cert_verify=skip_cert_verify)",
    "docstring": "Downloads a URL to a file, unless the file already exists."
  },
  {
    "code": "def is_valid(obj: JSGValidateable, log: Optional[Union[TextIO, Logger]] = None) -> bool:\n    return obj._is_valid(log)",
    "docstring": "Determine whether obj is valid\n\n    :param obj: Object to validate\n    :param log: Logger to record validation failures.  If absent, no information is recorded"
  },
  {
    "code": "def reset(self):\n        self._current_index = -1\n        self._current_value = self._default_value\n        self._current_rendered = self._default_rendered\n        self.offset = None",
    "docstring": "Reset the field to its default state"
  },
  {
    "code": "def _create_scaling_policies(conn, as_name, scaling_policies):\n    'helper function to create scaling policies'\n    if scaling_policies:\n        for policy in scaling_policies:\n            policy = autoscale.policy.ScalingPolicy(\n                name=policy[\"name\"],\n                as_name=as_name,\n                adjustment_type=policy[\"adjustment_type\"],\n                scaling_adjustment=policy[\"scaling_adjustment\"],\n                min_adjustment_step=policy.get(\"min_adjustment_step\", None),\n                cooldown=policy[\"cooldown\"])\n            conn.create_scaling_policy(policy)",
    "docstring": "helper function to create scaling policies"
  },
  {
    "code": "def load_xml(self, xmlfile):\n        self.logger.info('Loading XML')\n        for c in self.components:\n            c.load_xml(xmlfile)\n        for name in self.like.sourceNames():\n            self.update_source(name)\n        self._fitcache = None\n        self.logger.info('Finished Loading XML')",
    "docstring": "Load model definition from XML.\n\n        Parameters\n        ----------\n        xmlfile : str\n            Name of the input XML file."
  },
  {
    "code": "def blocks(self, lines):\n        state = markdown.blockparser.State()\n        blocks = []\n        state.set('start')\n        currblock = 0\n        for line in lines:\n            line += '\\n'\n            if state.isstate('start'):\n                if line[:3] == '```':\n                    state.set('```')\n                else:\n                    state.set('\\n')\n                blocks.append('')\n                currblock = len(blocks) - 1\n            else:\n                marker = line[:3]\n                if state.isstate(marker):\n                    state.reset()\n            blocks[currblock] += line\n        return blocks",
    "docstring": "Groups lines into markdown blocks"
  },
  {
    "code": "def graph_edges(self):\n        edges = nx.get_edge_attributes(self._graph, 'branch').items()\n        edges_sorted = sorted(list(edges), key=lambda _: (''.join(sorted([repr(_[0][0]),repr(_[0][1])]))))\n        for edge in edges_sorted:\n            yield {'adj_nodes': edge[0], 'branch': edge[1]}",
    "docstring": "Returns a generator for iterating over graph edges\n\n        The edge of a graph is described by the two adjacent node and the branch\n        object itself. Whereas the branch object is used to hold all relevant\n        power system parameters.\n\n        Yields\n        ------\n        int\n            Description #TODO check\n        \n        Note\n        ----\n        There are generator functions for nodes (`Graph.nodes()`) and edges\n        (`Graph.edges()`) in NetworkX but unlike graph nodes, which can be\n        represented by objects, branch objects can only be accessed by using an\n        edge attribute ('branch' is used here)\n\n        To make access to attributes of the branch objects simpler and more\n        intuitive for the user, this generator yields a dictionary for each edge\n        that contains information about adjacent nodes and the branch object.\n\n        Note, the construction of the dictionary highly depends on the structure\n        of the in-going tuple (which is defined by the needs of networkX). If\n        this changes, the code will break."
  },
  {
    "code": "def incr(self, att, val=1):\n        if att not in self.counters:\n            raise ValueError(\"%s is not a counter.\")\n        self.db.hincrby(self.key(), att, val)",
    "docstring": "Increments a counter."
  },
  {
    "code": "def _write_scalar(self, name:str, scalar_value, iteration:int)->None:\n        \"Writes single scalar value to Tensorboard.\"\n        tag = self.metrics_root + name\n        self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration)",
    "docstring": "Writes single scalar value to Tensorboard."
  },
  {
    "code": "def GetClientOs(client_id, token=None):\n  if data_store.RelationalDBEnabled():\n    kb = data_store.REL_DB.ReadClientSnapshot(client_id).knowledge_base\n  else:\n    with aff4.FACTORY.Open(client_id, token=token) as client:\n      kb = client.Get(client.Schema.KNOWLEDGE_BASE)\n  return kb.os",
    "docstring": "Returns last known operating system name that the client used."
  },
  {
    "code": "def _resize(self, ratio_x, ratio_y, resampling):\n        new_width = int(np.ceil(self.width * ratio_x))\n        new_height = int(np.ceil(self.height * ratio_y))\n        dest_affine = self.affine * Affine.scale(1 / ratio_x, 1 / ratio_y)\n        if self.not_loaded():\n            window = rasterio.windows.Window(0, 0, self.width, self.height)\n            resized_raster = self.get_window(window, xsize=new_width, ysize=new_height, resampling=resampling)\n        else:\n            resized_raster = self._reproject(new_width, new_height, dest_affine, resampling=resampling)\n        return resized_raster",
    "docstring": "Return raster resized by ratio."
  },
  {
    "code": "def listen_tta(self, target, timeout):\n        info = \"{device} does not support listen as Type A Target\"\n        raise nfc.clf.UnsupportedTargetError(info.format(device=self))",
    "docstring": "Listen as Type A Target is not supported."
  },
  {
    "code": "def deprecated(instructions):\n    def decorator(func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            message = 'Call to deprecated function {}. {}'.format(func.__name__,\n                                                                  instructions)\n            frame = inspect.currentframe().f_back\n            warnings.warn_explicit(message,\n                                   category=DeprecatedWarning,\n                                   filename=inspect.getfile(frame.f_code),\n                                   lineno=frame.f_lineno)\n            return func(*args, **kwargs)\n        return wrapper\n    return decorator",
    "docstring": "Flags a method as deprecated.\n\n    :param instructions: A human-friendly string of instructions, such as: 'Please migrate to add_proxy() ASAP.'\n    :return: DeprecatedWarning"
  },
  {
    "code": "def get_app_content_types(self):\n        from django.contrib.contenttypes.models import ContentType\n        return [ContentType.objects.get_for_model(c) for c\n                in self.get_app_model_classes()]",
    "docstring": "Return a list of all content_types for this app."
  },
  {
    "code": "def setup_rabbitmq(self):\n        if not self.rabbitmq_key:\n            self.rabbitmq_key = '{}:start_urls'.format(self.name)\n        self.server = connection.from_settings(self.crawler.settings)\n        self.crawler.signals.connect(self.spider_idle, signal=signals.spider_idle)\n        self.crawler.signals.connect(self.item_scraped, signal=signals.item_scraped)",
    "docstring": "Setup RabbitMQ connection.\n\n            Call this method after spider has set its crawler object.\n        :return: None"
  },
  {
    "code": "def format_exc_skip(skip, limit=None):\n    etype, val, tb = sys.exc_info()\n    for i in range(skip):\n        tb = tb.tb_next\n    return (''.join(format_exception(etype, val, tb, limit))).rstrip()",
    "docstring": "Like traceback.format_exc but allow skipping the first frames."
  },
  {
    "code": "def _add_variable_proxy_methods(var, proxy_tensor):\n  proxy_tensor.read_value = lambda: tf.identity(proxy_tensor)\n  proxy_tensor.assign_sub = var.assign_sub\n  proxy_tensor.assign = var.assign\n  proxy_tensor.initialized_value = var.initialized_value",
    "docstring": "Proxy methods of underlying variable.\n\n  This enables our custom getters to still work with, e.g., batch norm.\n\n  Args:\n    var: Variable to proxy\n    proxy_tensor: Tensor that is identity of var"
  },
  {
    "code": "def has_cwd(state, dir, incorrect_msg=\"Your current working directory should be `{{dir}}`. Use `cd {{dir}}` to navigate there.\"):\n    expr = \"[[ $PWD == '{}' ]]\".format(dir)\n    _msg = state.build_message(incorrect_msg, fmt_kwargs={ 'dir': dir })\n    has_expr_exit_code(state, expr, output=\"0\", incorrect_msg=_msg)\n    return state",
    "docstring": "Check whether the student is in the expected directory.\n\n    This check is typically used before using ``has_expr_output()``\n    to make sure the student didn't navigate somewhere else.\n\n    Args:\n        state: State instance describing student and solution code. Can be omitted if used with ``Ex()``.\n        dir: Directory that the student should be in. Always use the absolute path.\n        incorrect_msg: If specified, this overrides the automatically generated message in\n                       case the student is not in the expected directory.\n\n    :Example:\n\n        If you want to be sure that the student is in ``/home/repl/my_dir``: ::\n\n            Ex().has_cwd('/home/repl/my_dir')"
  },
  {
    "code": "def timed(function):\n    @wraps(function)\n    def function_wrapper(obj, *args, **kwargs):\n        name = obj.__class__.__name__ + '.' + function.__name__\n        start = time.clock()\n        result = function(obj, *args, **kwargs)\n        print('{}: {:.4f} seconds'.format(name, time.clock() - start))\n        return result\n    return function_wrapper",
    "docstring": "Decorator timing the method call and printing the result to `stdout`"
  },
  {
    "code": "def create_datasource(jboss_config, name, datasource_properties, profile=None):\n    log.debug(\"======================== MODULE FUNCTION: jboss7.create_datasource, name=%s, profile=%s\", name, profile)\n    ds_resource_description = __get_datasource_resource_description(jboss_config, name, profile)\n    operation = '/subsystem=datasources/data-source=\"{name}\":add({properties})'.format(\n        name=name,\n        properties=__get_properties_assignment_string(datasource_properties, ds_resource_description)\n    )\n    if profile is not None:\n        operation = '/profile=\"{profile}\"'.format(profile=profile) + operation\n    return __salt__['jboss7_cli.run_operation'](jboss_config, operation, fail_on_error=False)",
    "docstring": "Create datasource in running jboss instance\n\n    jboss_config\n        Configuration dictionary with properties specified above.\n    name\n        Datasource name\n    datasource_properties\n        A dictionary of datasource properties to be created:\n          - driver-name: mysql\n          - connection-url: 'jdbc:mysql://localhost:3306/sampleDatabase'\n          - jndi-name: 'java:jboss/datasources/sampleDS'\n          - user-name: sampleuser\n          - password: secret\n          - min-pool-size: 3\n          - use-java-context: True\n    profile\n        The profile name (JBoss domain mode only)\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' jboss7.create_datasource '{\"cli_path\": \"integration.modules.sysmod.SysModuleTest.test_valid_docs\", \"controller\": \"10.11.12.13:9999\", \"cli_user\": \"jbossadm\", \"cli_password\": \"jbossadm\"}' 'my_datasource' '{\"driver-name\": \"mysql\", \"connection-url\": \"jdbc:mysql://localhost:3306/sampleDatabase\", \"jndi-name\": \"java:jboss/datasources/sampleDS\", \"user-name\": \"sampleuser\", \"password\": \"secret\", \"min-pool-size\": 3, \"use-java-context\": True}'"
  },
  {
    "code": "def start(self):\n        scheduler_threads = [\n            Thread(target=self._monitor_events, daemon=True),\n            Thread(target=self._processing_controller_status, daemon=True),\n            Thread(target=self._schedule_processing_blocks, daemon=True),\n            Thread(target=self._monitor_pbc_status, daemon=True)\n        ]\n        for thread in scheduler_threads:\n            thread.start()\n        try:\n            for thread in scheduler_threads:\n                thread.join()\n        except KeyboardInterrupt:\n            LOG.info('Keyboard interrupt!')\n            sys.exit(0)\n        finally:\n            LOG.info('Finally!')",
    "docstring": "Start the scheduler threads."
  },
  {
    "code": "def newAddress(self, currency='btc', label=''):\n        request = '/v1/deposit/' + currency + '/newAddress'\n        url = self.base_url + request\n        params = {\n            'request': request,\n            'nonce': self.get_nonce()\n        }\n        if label != '':\n            params['label'] = label\n        return requests.post(url, headers=self.prepare(params))",
    "docstring": "Send a request for a new cryptocurrency deposit address\n        with an optional label. Return the response.\n\n        Arguements:\n        currency -- a Gemini supported cryptocurrency (btc, eth)\n        label -- optional label for the deposit address"
  },
  {
    "code": "def import_address(self, address, account=\"*\", rescan=False):\n        response = self.make_request(\"importaddress\", [address, account, rescan])\n        error = response.get('error')\n        if error is not None:\n            raise Exception(error)\n        return response",
    "docstring": "param address = address to import\n        param label= account name to use"
  },
  {
    "code": "async def _wrap_ws(self, handler, *args, **kwargs):\n        try:\n            method = self.request_method()\n            data = await handler(self, *args, **kwargs)\n            status = self.responses.get(method, OK)\n            response = {\n                'type': 'response',\n                'key': getattr(self.request, 'key', None),\n                'status': status,\n                'payload': data\n            }\n        except Exception as ex:\n            response = {\n                'type': 'response',\n                'key': getattr(self.request, 'key', None),\n                'status': getattr(ex, 'status', 500),\n                'payload': getattr(ex, 'msg', 'general error')\n            }\n        return self.format(method, response)",
    "docstring": "wraps a handler by receiving a websocket request and returning a websocket response"
  },
  {
    "code": "def deinstall(name):\n    portpath = _check_portname(name)\n    old = __salt__['pkg.list_pkgs']()\n    result = __salt__['cmd.run_all'](\n        ['make', 'deinstall', 'BATCH=yes'],\n        cwd=portpath,\n        python_shell=False\n    )\n    __context__.pop('pkg.list_pkgs', None)\n    new = __salt__['pkg.list_pkgs']()\n    return salt.utils.data.compare_dicts(old, new)",
    "docstring": "De-install a port.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' ports.deinstall security/nmap"
  },
  {
    "code": "def create(self):\n        assert not self.called\n        return self.klass(*self.args, **self.kw)",
    "docstring": "Create a normal field from the lazy field"
  },
  {
    "code": "def bisine_wave(frequency):\n  f_hi = frequency\n  f_lo = frequency / 2.0\n  with tf.name_scope('hi'):\n    sine_hi = sine_wave(f_hi)\n  with tf.name_scope('lo'):\n    sine_lo = sine_wave(f_lo)\n  return tf.concat([sine_lo, sine_hi], axis=2)",
    "docstring": "Emit two sine waves, in stereo at different octaves."
  },
  {
    "code": "def column(self, column, option=None, **kw):\n        config = False\n        if option == 'type':\n            return self._column_types[column]\n        elif 'type' in kw:\n            config = True\n            self._column_types[column] = kw.pop('type')\n        if kw:\n            self._visual_drag.column(ttk.Treeview.column(self, column, 'id'), option, **kw)\n        if kw or option:\n            return ttk.Treeview.column(self, column, option, **kw)\n        elif not config:\n            res = ttk.Treeview.column(self, column, option, **kw)\n            res['type'] = self._column_types[column]\n            return res",
    "docstring": "Query or modify the options for the specified column.\n\n        If `kw` is not given, returns a dict of the column option values. If\n        `option` is specified then the value for that option is returned.\n        Otherwise, sets the options to the corresponding values.\n\n        :param id: the column's identifier (read-only option)\n        :param anchor: \"n\", \"ne\", \"e\", \"se\", \"s\", \"sw\", \"w\", \"nw\", or \"center\":\n                       alignment of the text in this column with respect to the cell\n        :param minwidth: minimum width of the column in pixels\n        :type minwidth: int\n        :param stretch: whether the column's width should be adjusted when the widget is resized\n        :type stretch: bool\n        :param width: width of the column in pixels\n        :type width: int\n        :param type: column's content type (for sorting), default type is `str`\n        :type type: type"
  },
  {
    "code": "def run(self, args):\n        jlink = self.create_jlink(args)\n        mcu = args.name[0].lower()\n        if pylink.unlock(jlink, mcu):\n            print('Successfully unlocked device!')\n        else:\n            print('Failed to unlock device!')",
    "docstring": "Unlocks the target device.\n\n        Args:\n          self (UnlockCommand): the ``UnlockCommand`` instance\n          args (Namespace): the arguments passed on the command-line\n\n        Returns:\n          ``None``"
  },
  {
    "code": "def create_send_message(self, string_message, controller, zone=None, parameter=None):\n        cc = hex(int(controller) - 1).replace('0x', '')\n        if zone is not None:\n            zz = hex(int(zone) - 1).replace('0x', '')\n        else:\n            zz = ''\n        if parameter is not None:\n            pr = hex(int(parameter)).replace('0x', '')\n        else:\n            pr = ''\n        string_message = string_message.replace('@cc', cc)\n        string_message = string_message.replace('@zz', zz)\n        string_message = string_message.replace('@kk', KEYPAD_CODE)\n        string_message = string_message.replace('@pr', pr)\n        send_msg = string_message.split()\n        send_msg = self.calc_checksum(send_msg)\n        return send_msg",
    "docstring": "Creates a message from a string, substituting the necessary parameters,\n        that is ready to send to the socket"
  },
  {
    "code": "def update_firmware(self, file, data=None, progress=None, bank=None):\n        self.oem_init()\n        if progress is None:\n            progress = lambda x: True\n        return self._oem.update_firmware(file, data, progress, bank)",
    "docstring": "Send file to BMC to perform firmware update\n\n         :param filename:  The filename to upload to the target BMC\n         :param data:  The payload of the firmware.  Default is to read from\n                       specified filename.\n         :param progress:  A callback that will be given a dict describing\n                           update process.  Provide if\n         :param bank: Indicate a target 'bank' of firmware if supported"
  },
  {
    "code": "def _get_snmp(self, oid):\n        if self.snmp_version in [\"v1\", \"v2c\"]:\n            return self._get_snmpv2c(oid)\n        else:\n            return self._get_snmpv3(oid)",
    "docstring": "Wrapper for generic SNMP call."
  },
  {
    "code": "def extern_store_i64(self, context_handle, i64):\n    c = self._ffi.from_handle(context_handle)\n    return c.to_value(i64)",
    "docstring": "Given a context and int32_t, return a new Handle to represent the int32_t."
  },
  {
    "code": "def pypi(\n    click_ctx,\n    requirements,\n    index=None,\n    python_version=3,\n    exclude_packages=None,\n    output=None,\n    subgraph_check_api=None,\n    no_transitive=True,\n    no_pretty=False,\n):\n    requirements = [requirement.strip() for requirement in requirements.split(\"\\\\n\") if requirement]\n    if not requirements:\n        _LOG.error(\"No requirements specified, exiting\")\n        sys.exit(1)\n    if not subgraph_check_api:\n        _LOG.info(\n            \"No subgraph check API provided, no queries will be done for dependency subgraphs that should be avoided\"\n        )\n    result = resolve_python(\n        requirements,\n        index_urls=index.split(\",\") if index else (\"https://pypi.org/simple\",),\n        python_version=int(python_version),\n        transitive=not no_transitive,\n        exclude_packages=set(map(str.strip, (exclude_packages or \"\").split(\",\"))),\n        subgraph_check_api=subgraph_check_api,\n    )\n    print_command_result(\n        click_ctx,\n        result,\n        analyzer=analyzer_name,\n        analyzer_version=analyzer_version,\n        output=output or \"-\",\n        pretty=not no_pretty,\n    )",
    "docstring": "Manipulate with dependency requirements using PyPI."
  },
  {
    "code": "def analyze(self, using=None, **kwargs):\n        return self._get_connection(using).indices.analyze(index=self._name, **kwargs)",
    "docstring": "Perform the analysis process on a text and return the tokens breakdown\n        of the text.\n\n        Any additional keyword arguments will be passed to\n        ``Elasticsearch.indices.analyze`` unchanged."
  },
  {
    "code": "def _normalize_server_settings(**settings):\n    ret = dict()\n    settings = salt.utils.args.clean_kwargs(**settings)\n    for setting in settings:\n        if isinstance(settings[setting], dict):\n            value_from_key = next(six.iterkeys(settings[setting]))\n            ret[setting] = \"{{{0}}}\".format(value_from_key)\n        else:\n            ret[setting] = settings[setting]\n    return ret",
    "docstring": "Convert setting values that has been improperly converted to a dict back to a string."
  },
  {
    "code": "def filename(self):\n        if self._filename is None:\n            self._filename = storage.get_file(self.basename,\n                                              self.ccd,\n                                              ext=self.extension,\n                                              version=self.type,\n                                              prefix=self.prefix)\n        return self._filename",
    "docstring": "Name if the MOP formatted file to parse.\n        @rtype: basestring\n        @return: filename"
  },
  {
    "code": "def _should_resolve_subgraph(subgraph_check_api: str, package_name: str, package_version: str, index_url: str) -> bool:\n    _LOGGER.info(\n        \"Checking if the given dependency subgraph for package %r in version %r from index %r should be resolved\",\n        package_name,\n        package_version,\n        index_url,\n    )\n    response = requests.get(\n        subgraph_check_api,\n        params={\"package_name\": package_name, \"package_version\": package_version, \"index_url\": index_url},\n    )\n    if response.status_code == 200:\n        return True\n    elif response.status_code == 208:\n        return False\n    response.raise_for_status()\n    raise ValueError(\n        \"Unreachable code - subgraph check API responded with unknown HTTP status \"\n        \"code %s for package %r in version %r from index %r\",\n        package_name,\n        package_version,\n        index_url,\n    )",
    "docstring": "Ask the given subgraph check API if the given package in the given version should be included in the resolution.\n\n    This subgraph resolving avoidence serves two purposes - we don't need to\n    resolve dependency subgraphs that were already analyzed and we also avoid\n    analyzing of \"core\" packages (like setuptools) where not needed as they\n    can break installation environment."
  },
  {
    "code": "def render_build_args(options, ns):\n    build_args = options.get('buildArgs', {})\n    for key, value in build_args.items():\n        build_args[key] = value.format(**ns)\n    return build_args",
    "docstring": "Get docker build args dict, rendering any templated args.\n\n    Args:\n    options (dict):\n        The dictionary for a given image from chartpress.yaml.\n        Fields in `options['buildArgs']` will be rendered and returned,\n        if defined.\n    ns (dict): the namespace used when rendering templated arguments"
  },
  {
    "code": "def delete(self, *, auto_commit=False):\n        try:\n            db.session.delete(self.resource)\n            if auto_commit:\n                db.session.commit()\n        except SQLAlchemyError:\n            self.log.exception('Failed deleting resource: {}'.format(self.id))\n            db.session.rollback()",
    "docstring": "Removes a resource from the database\n\n        Args:\n            auto_commit (bool): Automatically commit the transaction. Default: `False`\n\n        Returns:\n            `None`"
  },
  {
    "code": "def _get_lt_from_user_by_id(self, user, lt_id):\n        req = meta.Session.query(LayerTemplate).select_from(join(LayerTemplate, User))\n        try:\n            return req.filter(and_(User.login==user, LayerTemplate.id==lt_id)).one()\n        except Exception, e:\n            return None",
    "docstring": "Get a layertemplate owned by a user from the database by lt_id."
  },
  {
    "code": "def _notify_listeners(self, sender, message):\n        uid = message['uid']\n        msg_topic = message['topic']\n        self._ack(sender, uid, 'fire')\n        all_listeners = set()\n        for lst_topic, listeners in self.__listeners.items():\n            if fnmatch.fnmatch(msg_topic, lst_topic):\n                all_listeners.update(listeners)\n        self._ack(sender, uid, 'notice', 'ok' if all_listeners else 'none')\n        try:\n            results = []\n            for listener in all_listeners:\n                result = listener.handle_message(sender,\n                                                 message['topic'],\n                                                 message['content'])\n                if result:\n                    results.append(result)\n            self._ack(sender, uid, 'send', json.dumps(results))\n        except:\n            self._ack(sender, uid, 'send', \"Error\")",
    "docstring": "Notifies listeners of a new message"
  },
  {
    "code": "def get_partial_DOS(self):\n        warnings.warn(\"Phonopy.get_partial_DOS is deprecated. \"\n                      \"Use Phonopy.get_projected_dos_dict.\",\n                      DeprecationWarning)\n        pdos = self.get_projected_dos_dict()\n        return pdos['frequency_points'], pdos['projected_dos']",
    "docstring": "Return frequency points and partial DOS as a tuple.\n\n        Projection is done to atoms and may be also done along directions\n        depending on the parameters at run_partial_dos.\n\n        Returns\n        -------\n        A tuple with (frequency_points, partial_dos).\n\n        frequency_points: ndarray\n            shape=(frequency_sampling_points, ), dtype='double'\n        partial_dos:\n            shape=(frequency_sampling_points, projections), dtype='double'"
  },
  {
    "code": "def confirm_login_allowed(self, user):\n        if not user.is_active:\n            raise forms.ValidationError(\n                self.error_messages['inactive'],\n                code='inactive',\n            )",
    "docstring": "Controls whether the given User may log in. This is a policy setting,\n        independent of end-user authentication. This default behavior is to\n        allow login by active users, and reject login by inactive users.\n\n        If the given user cannot log in, this method should raise a\n        ``forms.ValidationError``.\n\n        If the given user may log in, this method should return None."
  },
  {
    "code": "def verify_registration(request):\n    user = process_verify_registration_data(request.data)\n    extra_data = None\n    if registration_settings.REGISTER_VERIFICATION_AUTO_LOGIN:\n        extra_data = perform_login(request, user)\n    return get_ok_response('User verified successfully', extra_data=extra_data)",
    "docstring": "Verify registration via signature."
  },
  {
    "code": "def calc_temperature_stats(self):\n        self.temp.max_delta = melodist.get_shift_by_data(self.data.temp, self._lon, self._lat, self._timezone)\n        self.temp.mean_course = melodist.util.calculate_mean_daily_course_by_month(self.data.temp, normalize=True)",
    "docstring": "Calculates statistics in order to derive diurnal patterns of temperature"
  },
  {
    "code": "def _get_data_from_bigquery(self, queries):\n    all_df = []\n    for query in queries:\n      all_df.append(query.execute().result().to_dataframe())\n    df = pd.concat(all_df, ignore_index=True)\n    return df",
    "docstring": "Get data from bigquery table or query."
  },
  {
    "code": "def create_directory(self, path=None):\n        if path is None:\n            path = self.get_path()\n        if not os.path.exists(path):\n            os.makedirs(path)",
    "docstring": "Create the directory for the given path. If path is None use the path of this instance\n\n        :param path: the path to create\n        :type path: str\n        :returns: None\n        :rtype: None\n        :raises: OSError"
  },
  {
    "code": "def writeline(self, line=b'', sep=b'\\n', echo=None):\n        self.writelines([line], sep, echo)",
    "docstring": "Write a byte sequences to the channel and terminate it with carriage\n        return and line feed.\n\n        Args:\n            line(bytes): The line to send.\n            sep(bytes): The separator to use after each line.\n            echo(bool): Whether to echo the written data to stdout.\n\n        Raises:\n            EOFError: If the channel was closed before all data was sent."
  },
  {
    "code": "def _fail_if_contains_errors(response, sync_uuid=None):\n    if response.status_code != _HTTP_OK:\n        raise RequestError(response)\n    response_json = response.json()\n    if sync_uuid and 'sync_status' in response_json:\n        status = response_json['sync_status']\n        if sync_uuid in status and 'error' in status[sync_uuid]:\n            raise RequestError(response)",
    "docstring": "Raise a RequestError Exception if a given response\n    does not denote a successful request."
  },
  {
    "code": "def auth_from_hass_config(path=None, **kwargs):\n    if path is None:\n        path = config.find_hass_config()\n    return Auth(os.path.join(path, \".storage/auth\"), **kwargs)",
    "docstring": "Initialize auth from HASS config."
  },
  {
    "code": "def merge_data(path_data, request_data):\n    merged = request_data.copy() if request_data else {}\n    merged.update(path_data or {})\n    return merged",
    "docstring": "Merge data from the URI path and the request.\n\n    Path data wins."
  },
  {
    "code": "def num_inputs(self):\n        num = 0\n        for walker, _ in self.inputs:\n            if not isinstance(walker, InvalidStreamWalker):\n                num += 1\n        return num",
    "docstring": "Return the number of connected inputs.\n\n        Returns:\n            int: The number of connected inputs"
  },
  {
    "code": "def incident_exists(name, message, status):\n    incidents = cachet.Incidents(endpoint=ENDPOINT)\n    all_incidents = json.loads(incidents.get())\n    for incident in all_incidents['data']:\n        if name == incident['name'] and \\\n           status == incident['status'] and \\\n           message.strip() == incident['message'].strip():\n            return True\n    return False",
    "docstring": "Check if an incident with these attributes already exists"
  },
  {
    "code": "def secondary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y):\n    spinx = secondary_spin(mass1, mass2, spin1x, spin2x)\n    spiny = secondary_spin(mass1, mass2, spin1y, spin2y)\n    return xi2_from_mass1_mass2_spin2x_spin2y(mass1, mass2, spinx, spiny)",
    "docstring": "Returns the effective precession spin argument for the smaller mass."
  },
  {
    "code": "def remove(self, bw):\n        try:\n            self.__ranges.remove(bw)\n        except KeyError:\n            if not bw.oneshot:\n                raise",
    "docstring": "Removes a buffer watch identifier.\n\n        @type  bw: L{BufferWatch}\n        @param bw:\n            Buffer watch identifier.\n\n        @raise KeyError: The buffer watch identifier was already removed."
  },
  {
    "code": "def parse_type(field):\n  if field.type_id == 'string':\n    if 'size' in field.options:\n      return \"parser.getString(%d)\" % field.options['size'].value\n    else:\n      return \"parser.getString()\"\n  elif field.type_id in JAVA_TYPE_MAP:\n    return \"parser.get\" + field.type_id.capitalize() + \"()\"\n  if field.type_id == 'array':\n    t = field.options['fill'].value\n    if t in JAVA_TYPE_MAP:\n      if 'size' in field.options:\n        return \"parser.getArrayof%s(%d)\" % (t.capitalize(), field.options['size'].value)\n      else:\n        return \"parser.getArrayof%s()\" % t.capitalize()\n    else:\n      if 'size' in field.options:\n        return \"parser.getArray(%s.class, %d)\" % (t, field.options['size'].value)\n      else:\n        return \"parser.getArray(%s.class)\" % t\n  else:\n    return \"new %s().parse(parser)\" % field.type_id",
    "docstring": "Function to pull a type from the binary payload."
  },
  {
    "code": "def write_hyper_response(self, links=[], meta={}, entity_name=None, entity=None, notifications=[], actions=[]):\n        assert entity_name is not None\n        assert entity is not None\n        meta.update({\n            \"status\": self.get_status()\n        })\n        self.write({\n            \"links\": links,\n            \"meta\": meta,\n            entity_name: entity,\n            \"notifications\": notifications,\n            \"actions\": actions\n        })",
    "docstring": "Writes a hyper media response object\n\n        :param list links: A list of links to the resources\n        :param dict meta: The meta data for this response\n        :param str entity_name: The entity name\n        :param object entity: The Entity itself\n        :param list notifications: List of notifications\n        :param list actions: List of actions"
  },
  {
    "code": "def broadcast_identifier(self):\n        if self.handler_type is not BROADCAST:\n            return None\n        if self.reliable_delivery:\n            raise EventHandlerConfigurationError(\n                \"You are using the default broadcast identifier \"\n                \"which is not compatible with reliable delivery. See \"\n                \":meth:`nameko.events.EventHandler.broadcast_identifier` \"\n                \"for details.\")\n        return uuid.uuid4().hex",
    "docstring": "A unique string to identify a service instance for `BROADCAST`\n        type handlers.\n\n        The `broadcast_identifier` is appended to the queue name when the\n        `BROADCAST` handler type is used. It must uniquely identify service\n        instances that receive broadcasts.\n\n        The default `broadcast_identifier` is a uuid that is set when the\n        service starts. It will change when the service restarts, meaning\n        that any unconsumed messages that were broadcast to the 'old' service\n        instance will not be received by the 'new' one. ::\n\n            @property\n            def broadcast_identifier(self):\n                # use a uuid as the identifier.\n                # the identifier will change when the service restarts and\n                # any unconsumed messages will be lost\n                return uuid.uuid4().hex\n\n        The default behaviour is therefore incompatible with reliable delivery.\n\n        An alternative `broadcast_identifier` that would survive service\n        restarts is ::\n\n            @property\n            def broadcast_identifier(self):\n                # use the machine hostname as the identifier.\n                # this assumes that only one instance of a service runs on\n                # any given machine\n                return socket.gethostname()\n\n        If neither of these approaches are appropriate, you could read the\n        value out of a configuration file ::\n\n            @property\n            def broadcast_identifier(self):\n                return self.config['SERVICE_IDENTIFIER']  # or similar\n\n        Broadcast queues are exclusive to ensure that `broadcast_identifier`\n        values are unique.\n\n        Because this method is a descriptor, it will be called during\n        container creation, regardless of the configured `handler_type`.\n        See :class:`nameko.extensions.Extension` for more details."
  },
  {
    "code": "def pastdate(self, prompt, default=None):\n        prompt = prompt if prompt is not None else \"Enter a past date\"\n        if default is not None:\n            prompt += \" [\" + default.strftime('%d %m %Y') + \"]\"\n        prompt += ': '\n        return self.input(curry(filter_pastdate, default=default), prompt)",
    "docstring": "Prompts user to input a date in the past."
  },
  {
    "code": "def add_photometry(self, compare_to_existing=True, **kwargs):\n        self._add_cat_dict(\n            Photometry,\n            self._KEYS.PHOTOMETRY,\n            compare_to_existing=compare_to_existing,\n            **kwargs)\n        return",
    "docstring": "Add a `Photometry` instance to this entry."
  },
  {
    "code": "def get_paginated_response(self, data):\n        metadata = {\n            'next': self.get_next_link(),\n            'previous': self.get_previous_link(),\n            'count': self.get_result_count(),\n            'num_pages': self.get_num_pages(),\n        }\n        if isinstance(data, dict):\n            if 'results' not in data:\n                raise TypeError(u'Malformed result dict')\n            data['pagination'] = metadata\n        else:\n            data = {\n                'results': data,\n                'pagination': metadata,\n            }\n        return Response(data)",
    "docstring": "Annotate the response with pagination information"
  },
  {
    "code": "def input_option(message, options=\"yn\", error_message=None):\n    def _valid(character):\n        if character not in options:\n            print(error_message % character)\n    return input(\"%s [%s]\" % (message, options), _valid, True, lambda a: a.lower())",
    "docstring": "Reads an option from the screen, with a specified prompt.\n        Keeps asking until a valid option is sent by the user."
  },
  {
    "code": "def guess_content_type_and_encoding(path):\n    for ext, content_type in _EXTENSION_TO_MIME_TYPE.items():\n        if path.endswith(ext):\n            return content_type\n    content_type, encoding = mimetypes.guess_type(path)\n    content_type = content_type or \"application/binary\"\n    return content_type, encoding",
    "docstring": "Guess the content type of a path, using ``mimetypes``.\n\n    Falls back to \"application/binary\" if no content type is found.\n\n    Args:\n        path (str): the path to guess the mimetype of\n\n    Returns:\n        str: the content type of the file"
  },
  {
    "code": "def delete_network(self, network):\n        net_id = self._find_network_id(network)\n        ret = self.network_conn.delete_network(network=net_id)\n        return ret if ret else True",
    "docstring": "Deletes the specified network"
  },
  {
    "code": "def update_extent_from_rectangle(self):\n        self.show()\n        self.canvas.unsetMapTool(self.rectangle_map_tool)\n        self.canvas.setMapTool(self.pan_tool)\n        rectangle = self.rectangle_map_tool.rectangle()\n        if rectangle:\n            self.bounding_box_group.setTitle(\n                self.tr('Bounding box from rectangle'))\n            extent = rectangle_geo_array(rectangle, self.iface.mapCanvas())\n            self.update_extent(extent)",
    "docstring": "Update extent value in GUI based from the QgsMapTool rectangle.\n\n        .. note:: Delegates to update_extent()"
  },
  {
    "code": "def to_representation(self, obj):\n        representation = {}\n        for name, field in self.fields.items():\n            if field.write_only:\n                continue\n            attribute = self.get_attribute(obj, field.source or name)\n            if attribute is None:\n                representation[name] = [] if field.many else None\n            elif field.many:\n                representation[name] = [\n                    field.to_representation(item) for item in attribute\n                ]\n            else:\n                representation[name] = field.to_representation(attribute)\n        return representation",
    "docstring": "Convert given internal object instance into representation dict.\n\n        Representation dict may be later serialized to the content-type\n        of choice in the resource HTTP method handler.\n\n        This loops over all fields and retrieves source keys/attributes as\n        field values with respect to optional field sources and converts each\n        one using ``field.to_representation()`` method.\n\n        Args:\n            obj (object): internal object that needs to be represented\n\n        Returns:\n            dict: representation dictionary"
  },
  {
    "code": "def config(name,\n           config,\n           write=True):\n    _build_config_tree(name, config)\n    configs = _render_configuration()\n    if __opts__.get('test', False):\n        comment = 'State syslog_ng will write \\'{0}\\' into {1}'.format(\n            configs,\n            __SYSLOG_NG_CONFIG_FILE\n        )\n        return _format_state_result(name, result=None, comment=comment)\n    succ = write\n    if write:\n        succ = _write_config(config=configs)\n    return _format_state_result(name, result=succ,\n                                changes={'new': configs, 'old': ''})",
    "docstring": "Builds syslog-ng configuration. This function is intended to be used from\n    the state module, users should not use it directly!\n\n    name : the id of the Salt document or it is the format of <statement name>.id\n    config : the parsed YAML code\n    write : if True, it writes  the config into the configuration file,\n    otherwise just returns it\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' syslog_ng.config name='s_local' config=\"[{'tcp':[{'ip':'127.0.0.1'},{'port':1233}]}]\""
  },
  {
    "code": "def mach2tas(Mach, H):\n    a = vsound(H)\n    Vtas = Mach*a\n    return Vtas",
    "docstring": "Mach number to True Airspeed"
  },
  {
    "code": "def add_child_book(self, book_id, child_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.add_child_catalog(catalog_id=book_id, child_id=child_id)\n        return self._hierarchy_session.add_child(id_=book_id, child_id=child_id)",
    "docstring": "Adds a child to a book.\n\n        arg:    book_id (osid.id.Id): the ``Id`` of a book\n        arg:    child_id (osid.id.Id): the ``Id`` of the new child\n        raise:  AlreadyExists - ``book_id`` is already a parent of\n                ``child_id``\n        raise:  NotFound - ``book_id`` or ``child_id`` not found\n        raise:  NullArgument - ``book_id`` or ``child_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def progress_status(self):\n        if self.line % self.freq == 0:\n            text = self.statustext.format(nele=self.line,\n                                          totalele=self.total_lines)\n            if self.main_window.grid.actions.pasting:\n                try:\n                    post_command_event(self.main_window,\n                                       self.main_window.StatusBarMsg,\n                                       text=text)\n                except TypeError:\n                    pass\n            else:\n                self.main_window.GetStatusBar().SetStatusText(text)\n            if is_gtk():\n                try:\n                    wx.Yield()\n                except:\n                    pass\n        self.line += 1",
    "docstring": "Displays progress in statusbar"
  },
  {
    "code": "def generate_ppi_network(\n        ppi_graph_path: str,\n        dge_list: List[Gene],\n        max_adj_p: float,\n        max_log2_fold_change: float,\n        min_log2_fold_change: float,\n        ppi_edge_min_confidence: Optional[float] = None,\n        current_disease_ids_path: Optional[str] = None,\n        disease_associations_path: Optional[str] = None,\n) -> Network:\n    protein_interactions = parsers.parse_ppi_graph(ppi_graph_path, ppi_edge_min_confidence)\n    protein_interactions = protein_interactions.simplify()\n    if disease_associations_path is not None and current_disease_ids_path is not None:\n        current_disease_ids = parsers.parse_disease_ids(current_disease_ids_path)\n        disease_associations = parsers.parse_disease_associations(disease_associations_path,\n                                                                  current_disease_ids)\n    else:\n        disease_associations = None\n    network = Network(\n        protein_interactions,\n        max_adj_p=max_adj_p,\n        max_l2fc=max_log2_fold_change,\n        min_l2fc=min_log2_fold_change,\n    )\n    network.set_up_network(dge_list, disease_associations=disease_associations)\n    return network",
    "docstring": "Generate the protein-protein interaction network.\n\n    :return Network: Protein-protein interaction network with information on differential expression."
  },
  {
    "code": "def read_float(self, registeraddress, functioncode=3, numberOfRegisters=2):\n        _checkFunctioncode(functioncode, [3, 4])\n        _checkInt(numberOfRegisters, minvalue=2, maxvalue=4, description='number of registers')\n        return self._genericCommand(functioncode, registeraddress, numberOfRegisters=numberOfRegisters, payloadformat='float')",
    "docstring": "Read a floating point number from the slave.\n\n        Floats are stored in two or more consecutive 16-bit registers in the slave. The\n        encoding is according to the standard IEEE 754.\n\n        There are differences in the byte order used by different manufacturers. A floating\n        point value of 1.0 is encoded (in single precision) as 3f800000 (hex). In this\n        implementation the data will be sent as ``'\\\\x3f\\\\x80'`` and ``'\\\\x00\\\\x00'``\n        to two consecutetive registers . Make sure to test that it makes sense for your instrument.\n        It is pretty straight-forward to change this code if some other byte order is\n        required by anyone (see support section).\n\n        Args:\n            * registeraddress (int): The slave register start address (use decimal numbers, not hex).\n            * functioncode (int): Modbus function code. Can be 3 or 4.\n            * numberOfRegisters (int): The number of registers allocated for the float. Can be 2 or 4.\n\n        ====================================== ================= =========== =================\n        Type of floating point number in slave Size              Registers   Range\n        ====================================== ================= =========== =================\n        Single precision (binary32)            32 bits (4 bytes) 2 registers 1.4E-45 to 3.4E38\n        Double precision (binary64)            64 bits (8 bytes) 4 registers 5E-324 to 1.8E308\n        ====================================== ================= =========== =================\n\n        Returns:\n            The numerical value (float).\n\n        Raises:\n            ValueError, TypeError, IOError"
  },
  {
    "code": "def show(self, func_name, values, labels=None):\n        s = self.Stanza(self.indent)\n        if func_name == '<module>' and self.in_console:\n            func_name = '<console>'\n        s.add([func_name + ': '])\n        reprs = map(self.safe_repr, values)\n        if labels:\n            sep = ''\n            for label, repr in zip(labels, reprs):\n                s.add([label + '=', self.CYAN, repr, self.NORMAL], sep)\n                sep = ', '\n        else:\n            sep = ''\n            for repr in reprs:\n                s.add([self.CYAN, repr, self.NORMAL], sep)\n                sep = ', '\n        self.writer.write(s.chunks)",
    "docstring": "Prints out nice representations of the given values."
  },
  {
    "code": "def copy_to_tmp(source):\n    tmp_dir = tempfile.mkdtemp()\n    p = pathlib.Path(source)\n    dirname = p.name or 'temp'\n    new_dir = os.path.join(tmp_dir, dirname)\n    if os.path.isdir(source):\n        shutil.copytree(source, new_dir)\n    else:\n        shutil.copy2(source, new_dir)\n    return new_dir",
    "docstring": "Copies ``source`` to a temporary directory, and returns the copied\n    location.\n\n    If source is a file, the copied location is also a file."
  },
  {
    "code": "def send_document(self, document, caption=\"\", **options):\n        return self.bot.api_call(\n            \"sendDocument\",\n            chat_id=str(self.id),\n            document=document,\n            caption=caption,\n            **options\n        )",
    "docstring": "Send a general file.\n\n        :param document: Object containing the document data\n        :param str caption: Document caption (optional)\n        :param options: Additional sendDocument options (see\n            https://core.telegram.org/bots/api#senddocument)\n\n        :Example:\n\n        >>> with open(\"file.doc\", \"rb\") as f:\n        >>>     await chat.send_document(f)"
  },
  {
    "code": "def coldesc(self, columnname, actual=True):\n        import casacore.tables.tableutil as pt\n        return pt.makecoldesc(columnname, self.getcoldesc(columnname, actual))",
    "docstring": "Make the description of a column.\n\n        Make the description object of the given column as\n        :func:`makecoldesc` is doing with the description given by\n        :func:`getcoldesc`."
  },
  {
    "code": "def gen_paula_etree(paula_id):\n    E = ElementMaker(nsmap=NSMAP)\n    tree = E('paula', version='1.1')\n    tree.append(E('header', paula_id=paula_id))\n    return E, tree",
    "docstring": "creates an element tree representation of an empty PAULA XML file."
  },
  {
    "code": "def linear_interpolate_rank(tensor1, tensor2, coeffs, rank=1):\n  _, _, _, num_channels = common_layers.shape_list(tensor1)\n  diff_sq_sum = tf.reduce_sum((tensor1 - tensor2)**2, axis=(0, 1, 2))\n  _, feature_ranks = tf.math.top_k(diff_sq_sum, k=rank)\n  feature_rank = feature_ranks[-1]\n  channel_inds = tf.range(num_channels, dtype=tf.int32)\n  channel_mask = tf.equal(channel_inds, feature_rank)\n  ones_t = tf.ones(num_channels, dtype=tf.float32)\n  zeros_t = tf.zeros(num_channels, dtype=tf.float32)\n  interp_tensors = []\n  for coeff in coeffs:\n    curr_coeff = tf.where(channel_mask, coeff * ones_t, zeros_t)\n    interp_tensor = tensor1 + curr_coeff * (tensor2 - tensor1)\n    interp_tensors.append(interp_tensor)\n  return tf.concat(interp_tensors, axis=0)",
    "docstring": "Linearly interpolate channel at \"rank\" between two tensors.\n\n  The channels are ranked according to their L2 norm between tensor1[channel]\n  and tensor2[channel].\n\n  Args:\n    tensor1: 4-D Tensor, NHWC\n    tensor2: 4-D Tensor, NHWC\n    coeffs: list of floats.\n    rank: integer.\n  Returns:\n    interp_latents: list of interpolated 4-D Tensors, shape=(NHWC)"
  },
  {
    "code": "def validate(self, value):\n        try:\n            self._choice = IPAddress(value)\n        except (ValueError, AddrFormatError):\n            self.error_message = '%s is not a valid IP address.' % value\n            return False\n        if self._choice.is_netmask():\n            return True\n        else:\n            self.error_message = '%s is not a valid IP netmask.' % value\n            return False",
    "docstring": "Return a boolean if the value is a valid netmask."
  },
  {
    "code": "def start_processing_handler(self, event):\n        self.logger.debug(\"Event %s: starting Volatility process(es).\", event)\n        for snapshot in self.snapshots:\n            self.process_snapshot(snapshot)\n        self.processing_done.set()",
    "docstring": "Asynchronous handler starting the Volatility processes."
  },
  {
    "code": "def history(namespace_module):\n    for path in get_namespace_history(namespace_module):\n        h = get_bel_resource_hash(path.as_posix())\n        click.echo('{}\\t{}'.format(path, h))",
    "docstring": "Hash all versions on Artifactory."
  },
  {
    "code": "def _feed_to_kafka(self, json_item):\n        @MethodTimer.timeout(self.settings['KAFKA_FEED_TIMEOUT'], False)\n        def _feed(json_item):\n            try:\n                self.logger.debug(\"Sending json to kafka at \" +\n                                  str(self.settings['KAFKA_PRODUCER_TOPIC']))\n                future = self.producer.send(self.settings['KAFKA_PRODUCER_TOPIC'],\n                                   json_item)\n                future.add_callback(self._kafka_success)\n                future.add_errback(self._kafka_failure)\n                self.producer.flush()\n                return True\n            except Exception as e:\n                self.logger.error(\"Lost connection to Kafka\")\n                self._spawn_kafka_connection_thread()\n                return False\n        return _feed(json_item)",
    "docstring": "Sends a request to Kafka\n\n        :param json_item: The json item to send\n        :returns: A boolean indicating whther the data was sent successfully or not"
  },
  {
    "code": "def _buf_append(self, string):\n        if not self._buf:\n            self._buf = string\n        else:\n            self._buf += string",
    "docstring": "Replace string directly without appending to an empty string,\n        avoiding type issues."
  },
  {
    "code": "def pending_work_items(self):\n        \"Iterable of all pending work items.\"\n        pending = self._conn.execute(\n            \"SELECT * FROM work_items WHERE job_id NOT IN (SELECT job_id FROM results)\"\n        )\n        return (_row_to_work_item(p) for p in pending)",
    "docstring": "Iterable of all pending work items."
  },
  {
    "code": "def add_cors(self, path, allowed_origins, allowed_headers=None, allowed_methods=None, max_age=None,\n                 allow_credentials=None):\n        if self.has_path(path, self._OPTIONS_METHOD):\n            return\n        if not allowed_origins:\n            raise ValueError(\"Invalid input. Value for AllowedOrigins is required\")\n        if not allowed_methods:\n            allowed_methods = self._make_cors_allowed_methods_for_path(path)\n            allowed_methods = \"'{}'\".format(allowed_methods)\n        if allow_credentials is not True:\n            allow_credentials = False\n        self.add_path(path, self._OPTIONS_METHOD)\n        self.get_path(path)[self._OPTIONS_METHOD] = self._options_method_response_for_cors(allowed_origins,\n                                                                                           allowed_headers,\n                                                                                           allowed_methods,\n                                                                                           max_age,\n                                                                                           allow_credentials)",
    "docstring": "Add CORS configuration to this path. Specifically, we will add a OPTIONS response config to the Swagger that\n        will return headers required for CORS. Since SAM uses aws_proxy integration, we cannot inject the headers\n        into the actual response returned from Lambda function. This is something customers have to implement\n        themselves.\n\n        If OPTIONS method is already present for the Path, we will skip adding CORS configuration\n\n        Following this guide:\n        https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#enable-cors-for-resource-using-swagger-importer-tool\n\n        :param string path: Path to add the CORS configuration to.\n        :param string/dict allowed_origins: Comma separate list of allowed origins.\n            Value can also be an intrinsic function dict.\n        :param string/dict allowed_headers: Comma separated list of allowed headers.\n            Value can also be an intrinsic function dict.\n        :param string/dict allowed_methods: Comma separated list of allowed methods.\n            Value can also be an intrinsic function dict.\n        :param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on\n            Access-Control-Max-Age header. Value can also be an intrinsic function dict.\n        :param bool/None allow_credentials: Flags whether request is allowed to contain credentials.\n        :raises ValueError: When values for one of the allowed_* variables is empty"
  },
  {
    "code": "def load(path):\n        with open(path, \"r\") as fobj:\n            analytics = Analytics(info=json.load(fobj))\n        os.unlink(path)\n        return analytics",
    "docstring": "Loads analytics report from json file specified by path.\n\n        Args:\n            path (str): path to json file with analytics report."
  },
  {
    "code": "def apply_scaling(self, copy=True):\n        if copy:\n            return self.multiplier * self.data + self.base\n        if self.multiplier != 1:\n            self.data *= self.multiplier\n        if self.base != 0:\n            self.data += self.base\n        return self.data",
    "docstring": "Scale pixel values to there true DN.\n\n        :param copy: whether to apply the scalling to a copy of the pixel data\n            and leave the orginial unaffected\n\n        :returns: a scalled version of the pixel data"
  },
  {
    "code": "def remove_reference(type_):\n    nake_type = remove_alias(type_)\n    if not is_reference(nake_type):\n        return type_\n    return nake_type.base",
    "docstring": "removes reference from the type definition\n\n    If type is not reference type, it will be returned as is."
  },
  {
    "code": "def cas(self, key, value, new_value):\n        return self.run_script('cas', keys=[key], args=[value, new_value])",
    "docstring": "Perform an atomic compare-and-set on the value in \"key\", using a prefix\n        match on the provided value."
  },
  {
    "code": "def _run_event_methods(self, tag, stage=None):\n        import inspect\n        from ambry.bundle.events import _runable_for_event\n        funcs = []\n        for func_name, f in inspect.getmembers(self, predicate=inspect.ismethod):\n            if _runable_for_event(f, tag, stage):\n                funcs.append(f)\n        for func in funcs:\n            func()",
    "docstring": "Run code in the bundle that is marked with events."
  },
  {
    "code": "async def execute_command(\n        self, *args: bytes, timeout: NumType = None\n    ) -> SMTPResponse:\n        command = b\" \".join(args) + b\"\\r\\n\"\n        await self.write_and_drain(command, timeout=timeout)\n        response = await self.read_response(timeout=timeout)\n        return response",
    "docstring": "Sends an SMTP command along with any args to the server, and returns\n        a response."
  },
  {
    "code": "async def export_wallet(self, von_wallet: Wallet, path: str) -> None:\n        LOGGER.debug('WalletManager.export_wallet >>> von_wallet %s, path %s', von_wallet, path)\n        if not von_wallet.handle:\n            LOGGER.debug('WalletManager.export_wallet <!< Wallet %s is closed', von_wallet.name)\n            raise WalletState('Wallet {} is closed'.format(von_wallet.name))\n        await wallet.export_wallet(\n            von_wallet.handle,\n            json.dumps({\n                'path': path,\n                **von_wallet.access_creds\n            }))\n        LOGGER.debug('WalletManager.export_wallet <<<')",
    "docstring": "Export an existing VON anchor wallet. Raise WalletState if wallet is closed.\n\n        :param von_wallet: open wallet\n        :param path: path to which to export wallet"
  },
  {
    "code": "def keep_scan(cls, result_key, token):\n        def _scan(self):\n            return self.get(token)\n        cls.scan(result_key, _scan)",
    "docstring": "Define a property that is set to the list of lines that contain the\n        given token.  Uses the get method of the log file."
  },
  {
    "code": "async def analog_write(self, command):\n        pin = int(command[0])\n        value = int(command[1])\n        await self.core.analog_write(pin, value)",
    "docstring": "This method writes a value to an analog pin.\n\n        It is used to set the output of a PWM pin or the angle of a Servo.\n\n        :param command: {\"method\": \"analog_write\", \"params\": [PIN, WRITE_VALUE]}\n        :returns: No return message."
  },
  {
    "code": "def get(cls, func_hint):\n        try:\n            return Func(func_hint)\n        except ValueError:\n            pass\n        if func_hint in cls._func_from_name:\n            return cls._func_from_name[func_hint]\n        if func_hint in cls._func_hash:\n            return func_hint\n        raise KeyError(\"unknown hash function\", func_hint)",
    "docstring": "Return a registered hash function matching the given hint.\n\n        The hint may be a `Func` member, a function name (with hyphens or\n        underscores), or its code.  A `Func` member is returned for standard\n        multihash functions and an integer code for application-specific ones.\n        If no matching function is registered, a `KeyError` is raised.\n\n        >>> fm = FuncReg.get(Func.sha2_256)\n        >>> fnu = FuncReg.get('sha2_256')\n        >>> fnh = FuncReg.get('sha2-256')\n        >>> fc = FuncReg.get(0x12)\n        >>> fm == fnu == fnh == fc\n        True"
  },
  {
    "code": "def relabel(self, catalogue):\n        for work, label in catalogue.items():\n            self._matches.loc[self._matches[constants.WORK_FIELDNAME] == work,\n                              constants.LABEL_FIELDNAME] = label",
    "docstring": "Relabels results rows according to `catalogue`.\n\n        A row whose work is labelled in the catalogue will have its\n        label set to the label in the catalogue. Rows whose works are\n        not labelled in the catalogue will be unchanged.\n\n        :param catalogue: mapping of work names to labels\n        :type catalogue: `Catalogue`"
  },
  {
    "code": "def __construct_lda_model(self):\n        repos_of_interest = self.__get_interests()\n        cleaned_tokens = self.__clean_and_tokenize(repos_of_interest)\n        if not cleaned_tokens:\n            cleaned_tokens = [[\"zkfgzkfgzkfgzkfgzkfgzkfg\"]]\n        dictionary = corpora.Dictionary(cleaned_tokens)\n        corpus = [dictionary.doc2bow(text) for text in cleaned_tokens]\n        self.lda_model = models.ldamodel.LdaModel(\n            corpus, num_topics=1, id2word=dictionary, passes=10\n        )",
    "docstring": "Method to create LDA model to procure list of topics from.\n\n        We do that by first fetching the descriptions of repositories user has\n        shown interest in. We tokenize the hence fetched descriptions to\n        procure list of cleaned tokens by dropping all the stop words and\n        language names from it.\n\n        We use the cleaned and sanitized token list to train LDA model from\n        which we hope to procure topics of interests to the authenticated user."
  },
  {
    "code": "def _download_items(db, last_id):\n    MAX_RETRY = 20\n    MAX_DOC_ID = 10000000\n    not_found_cnt = 0\n    for doc_id in xrange(last_id, MAX_DOC_ID):\n        doc_id += 1\n        print \"Downloading %d..\" % (doc_id)\n        if not_found_cnt >= MAX_RETRY:\n            print \"It looks like this is an end:\", doc_id - MAX_RETRY\n            break\n        try:\n            record = _download(doc_id)\n        except (DocumentNotFoundException, InvalidAlephBaseException):\n            print \"\\tnot found, skipping\"\n            not_found_cnt += 1\n            continue\n        not_found_cnt = 0\n        db[\"item_%d\" % doc_id] = record\n        db[\"last_id\"] = doc_id - MAX_RETRY if doc_id > MAX_RETRY else 1\n        if doc_id % 100 == 0:\n            db.commit()",
    "docstring": "Download items from the aleph and store them in `db`. Start from `last_id`\n    if specified.\n\n    Args:\n        db (obj): Dictionary-like object used as DB.\n        last_id (int): Start from this id."
  },
  {
    "code": "def run_queue(self, options, todo):\n    utils.logging_debug('AutoBatcher(%s): %d items',\n                        self._todo_tasklet.__name__, len(todo))\n    batch_fut = self._todo_tasklet(todo, options)\n    self._running.append(batch_fut)\n    batch_fut.add_callback(self._finished_callback, batch_fut, todo)",
    "docstring": "Actually run the _todo_tasklet."
  },
  {
    "code": "def pillars(opts, functions, context=None):\n    ret = LazyLoader(_module_dirs(opts, 'pillar'),\n                     opts,\n                     tag='pillar',\n                     pack={'__salt__': functions,\n                           '__context__': context,\n                           '__utils__': utils(opts)})\n    ret.pack['__ext_pillar__'] = ret\n    return FilterDictWrapper(ret, '.ext_pillar')",
    "docstring": "Returns the pillars modules"
  },
  {
    "code": "def add_tag(self, tag):\n        if tag not in self._tags:\n            self._tags[tag] = dict()",
    "docstring": "add a tag to the tag list"
  },
  {
    "code": "def _calculate_sunrise_hour_angle(self, solar_dec, depression=0.833):\n        hour_angle_arg = math.degrees(math.acos(\n            math.cos(math.radians(90 + depression)) /\n            (math.cos(math.radians(self.latitude)) * math.cos(\n                math.radians(solar_dec))) -\n            math.tan(math.radians(self.latitude)) *\n            math.tan(math.radians(solar_dec))\n        ))\n        return hour_angle_arg",
    "docstring": "Calculate hour angle for sunrise time in degrees."
  },
  {
    "code": "def print_with_pager(output):\n    if sys.stdout.isatty():\n        try:\n            pager = subprocess.Popen(\n                ['less', '-F', '-r', '-S', '-X', '-K'],\n                stdin=subprocess.PIPE, stdout=sys.stdout)\n        except subprocess.CalledProcessError:\n            print(output)\n            return\n        else:\n            pager.stdin.write(output.encode('utf-8'))\n            pager.stdin.close()\n            pager.wait()\n    else:\n        print(output)",
    "docstring": "Print the output to `stdout` using less when in a tty."
  },
  {
    "code": "def config_dirs():\n    paths = []\n    if platform.system() == 'Darwin':\n        paths.append(MAC_DIR)\n        paths.append(UNIX_DIR_FALLBACK)\n        paths.extend(xdg_config_dirs())\n    elif platform.system() == 'Windows':\n        paths.append(WINDOWS_DIR_FALLBACK)\n        if WINDOWS_DIR_VAR in os.environ:\n            paths.append(os.environ[WINDOWS_DIR_VAR])\n    else:\n        paths.append(UNIX_DIR_FALLBACK)\n        paths.extend(xdg_config_dirs())\n    out = []\n    for path in paths:\n        path = os.path.abspath(os.path.expanduser(path))\n        if path not in out:\n            out.append(path)\n    return out",
    "docstring": "Return a platform-specific list of candidates for user\n    configuration directories on the system.\n\n    The candidates are in order of priority, from highest to lowest. The\n    last element is the \"fallback\" location to be used when no\n    higher-priority config file exists."
  },
  {
    "code": "def citation_count(papers, key='ayjid', verbose=False):\n    if verbose:\n        print \"Generating citation counts for \"+unicode(len(papers))+\" papers...\"\n    counts = Counter()\n    for P in papers:\n        if P['citations'] is not None:\n            for p in P['citations']:\n                counts[p[key]] += 1\n    return counts",
    "docstring": "Generates citation counts for all of the papers cited by papers.\n\n    Parameters\n    ----------\n    papers : list\n        A list of :class:`.Paper` instances.\n    key : str\n        Property to use as node key. Default is 'ayjid' (recommended).\n    verbose : bool\n        If True, prints status messages.\n\n    Returns\n    -------\n    counts : dict\n        Citation counts for all papers cited by papers."
  },
  {
    "code": "def modify_ack_deadline(self, items):\n        ack_ids = [item.ack_id for item in items]\n        seconds = [item.seconds for item in items]\n        request = types.StreamingPullRequest(\n            modify_deadline_ack_ids=ack_ids, modify_deadline_seconds=seconds\n        )\n        self._manager.send(request)",
    "docstring": "Modify the ack deadline for the given messages.\n\n        Args:\n            items(Sequence[ModAckRequest]): The items to modify."
  },
  {
    "code": "def percentile_for_in(self, leaderboard_name, member):\n        if not self.check_member_in(leaderboard_name, member):\n            return None\n        responses = self.redis_connection.pipeline().zcard(\n            leaderboard_name).zrevrank(leaderboard_name, member).execute()\n        percentile = math.ceil(\n            (float(\n                (responses[0] -\n                 responses[1] -\n                 1)) /\n                float(\n                    responses[0]) *\n                100))\n        if self.order == self.ASC:\n            return 100 - percentile\n        else:\n            return percentile",
    "docstring": "Retrieve the percentile for a member in the named leaderboard.\n\n        @param leaderboard_name [String] Name of the leaderboard.\n        @param member [String] Member name.\n        @return the percentile for a member in the named leaderboard."
  },
  {
    "code": "def grid_search(grid_scores, change, subset=None, kind='line', cmap=None,\n                ax=None):\n    if change is None:\n        raise ValueError(('change can\\'t be None, you need to select at least'\n                          ' one value to make the plot.'))\n    if ax is None:\n        ax = plt.gca()\n    if cmap is None:\n        cmap = default_heatmap()\n    if isinstance(change, string_types) or len(change) == 1:\n        return _grid_search_single(grid_scores, change, subset, kind, ax)\n    elif len(change) == 2:\n        return _grid_search_double(grid_scores, change, subset, cmap, ax)\n    else:\n        raise ValueError('change must have length 1 or 2 or be a string')",
    "docstring": "Plot results from a sklearn grid search by changing two parameters at most.\n\n    Parameters\n    ----------\n    grid_scores : list of named tuples\n        Results from a sklearn grid search (get them using the\n        `grid_scores_` parameter)\n    change : str or iterable with len<=2\n        Parameter to change\n    subset : dictionary-like\n        parameter-value(s) pairs to subset from grid_scores.\n        (e.g. ``{'n_estimartors': [1, 10]}``), if None all combinations will be\n        used.\n    kind : ['line', 'bar']\n        This only applies whe change is a single parameter. Changes the\n        type of plot\n    cmap : matplotlib Colormap\n        This only applies when change are two parameters. Colormap used for\n        the matrix. If None uses a modified version of matplotlib's OrRd\n        colormap.\n    ax: matplotlib Axes\n        Axes object to draw the plot onto, otherwise uses current Axes\n\n    Returns\n    -------\n    ax: matplotlib Axes\n        Axes containing the plot\n\n    Examples\n    --------\n\n    .. plot:: ../../examples/grid_search.py"
  },
  {
    "code": "def _apply(self, ctx: ExtensionContext) -> AugmentedDict:\n        def process(pattern: Pattern[str], _str: str) -> Any:\n            _match = pattern.match(_str)\n            if _match is None:\n                return _str\n            placeholder, external_path = _match.group(1), _match.group(2)\n            with open(self.locator(\n                    external_path,\n                    cast(str, ctx.document) if Validator.is_file(document=ctx.document) else None\n            )) as fhandle:\n                content = fhandle.read()\n            return _str.replace(placeholder, content)\n        node_key, node_value = ctx.node\n        _pattern = re.compile(self.__pattern__)\n        return {node_key: process(_pattern, node_value)}",
    "docstring": "Performs the actual loading of an external resource into the current model.\n\n        Args:\n            ctx: The processing context.\n\n        Returns:\n            Returns a dictionary that gets incorporated into the actual model."
  },
  {
    "code": "def dict(cls, *args, **kwds):\n        if args:\n            if len(args) > 1:\n                raise TypeError(\"Too many positional arguments\")\n            x = args[0]\n            keys = []\n            vals = []\n            try:\n                x_keys = x.keys\n            except AttributeError:\n                for k, v in x:\n                    keys.append(k)\n                    vals.append(v)\n            else:\n                keys = x_keys()\n                vals = [x[k] for k in keys]\n            return q('!', keys, vals)\n        else:\n            if kwds:\n                keys = []\n                vals = []\n                for k, v in kwds.items():\n                    keys.append(k)\n                    vals.append(v)\n                return q('!', keys, vals)\n            else:\n                return q('()!()')",
    "docstring": "Construct a q dictionary\n\n        K.dict() -> new empty q dictionary (q('()!()')\n        K.dict(mapping) -> new dictionary initialized from a mapping object's\n            (key, value) pairs\n        K.dict(iterable) -> new dictionary initialized from an iterable\n            yielding (key, value) pairs\n        K.dict(**kwargs) -> new dictionary initialized with the name=value\n            pairs in the keyword argument list.\n            For example: K.dict(one=1, two=2)"
  },
  {
    "code": "def create_address(customer_id, data):\n    Address = client.model('party.address')\n    Country = client.model('country.country')\n    Subdivision = client.model('country.subdivision')\n    country, = Country.find([('code', '=', data['country'])])\n    state, = Subdivision.find([\n        ('code', 'ilike', '%-' + data['state']),\n        ('country', '=', country['id'])\n    ])\n    address, = Address.create([{\n        'party': customer_id,\n        'name': data['name'],\n        'street': data['street'],\n        'street_bis': data['street_bis'],\n        'city': data['city'],\n        'zip': data['zip'],\n        'country': country['id'],\n        'subdivision': state['id'],\n    }])\n    return address['id']",
    "docstring": "Create an address and return the id"
  },
  {
    "code": "def training_env():\n    from sagemaker_containers import _env\n    return _env.TrainingEnv(\n        resource_config=_env.read_resource_config(),\n        input_data_config=_env.read_input_data_config(),\n        hyperparameters=_env.read_hyperparameters())",
    "docstring": "Create a TrainingEnv.\n\n    Returns:\n        TrainingEnv: an instance of TrainingEnv"
  },
  {
    "code": "def validate_request(self, iface_name, func_name, params):\n        self.interface(iface_name).function(func_name).validate_params(params)",
    "docstring": "Validates that the given params match the expected length and types for this \n        interface and function.  \n\n        Returns two element tuple: (bool, string)\n\n        - `bool` - True if valid, False if not\n        - `string` - Description of validation error, or None if valid\n\n        :Parameters:\n          iface_name\n            Name of interface\n          func_name\n            Name of function\n          params\n            List of params to validate against this function"
  },
  {
    "code": "def unsubscribe_user_from_discussion(recID, uid):\n    query =\n    params = (recID, uid)\n    try:\n        res = run_sql(query, params)\n    except:\n        return 0\n    if res > 0:\n        return 1\n    return 0",
    "docstring": "Unsubscribe users from a discussion.\n\n    :param recID: record ID corresponding to the discussion we want to\n                  unsubscribe the user\n    :param uid: user id\n    :return 1 if successful, 0 if not"
  },
  {
    "code": "def _change_kind(self, post_uid):\n        post_data = self.get_post_data()\n        logger.info('admin post update: {0}'.format(post_data))\n        MPost.update_misc(post_uid, kind=post_data['kcat'])\n        update_category(post_uid, post_data)\n        self.redirect('/{0}/{1}'.format(router_post[post_data['kcat']], post_uid))",
    "docstring": "To modify the category of the post, and kind."
  },
  {
    "code": "def _clean_tag(t):\n    t = _scored_patt.sub(string=t, repl='')\n    if t == '_country_' or t.startswith('_country:'):\n        t = 'nnp_country'\n    elif t == 'vpb':\n        t = 'vb'\n    elif t == 'nnd':\n        t = 'nns'\n    elif t == 'nns_root:':\n        t = 'nns'\n    elif t == 'root:zygote':\n        t = 'nn'\n    elif t.startswith('root:'):\n        t = 'uh'\n    elif t in ('abbr_united_states_marine_corps', 'abbr_orange_juice'):\n        t = \"abbreviation\"\n    elif t == '+abbreviation':\n        t = 'abbreviation'\n    elif t.startswith('fw_misspelling:'):\n        t = 'fw'\n    return t",
    "docstring": "Fix up some garbage errors."
  },
  {
    "code": "def __verify_server_version(self):\n        if compare_versions('.'.join([_lib_major_version, _lib_minor_version]), self.product_version) > 0:\n            logger.warning('Client version {} connecting to server with newer minor release {}.'.format(\n                _lib_full_version,\n                self.product_version\n            ))\n        if compare_versions(_lib_major_version, self.product_version) != 0:\n            raise InvalidSwimlaneProductVersion(\n                self,\n                '{}.0'.format(_lib_major_version),\n                '{}.0'.format(str(int(_lib_major_version) + 1))\n            )",
    "docstring": "Verify connected to supported server product version\n\n        Notes:\n            Logs warning if connecting to a newer minor server version\n\n        Raises:\n            swimlane.exceptions.InvalidServerVersion: If server major version is higher than package major version"
  },
  {
    "code": "def _set_property(xml_root, name, value, properties=None):\n    if properties is None:\n        properties = xml_root.find(\"properties\")\n    for prop in properties:\n        if prop.get(\"name\") == name:\n            prop.set(\"value\", utils.get_unicode_str(value))\n            break\n    else:\n        etree.SubElement(\n            properties, \"property\", {\"name\": name, \"value\": utils.get_unicode_str(value)}\n        )",
    "docstring": "Sets property to specified value."
  },
  {
    "code": "def index_map(data):\n  (entry, text_fn) = data\n  text = text_fn()\n  logging.debug(\"Got %s\", entry.filename)\n  for s in split_into_sentences(text):\n    for w in split_into_words(s.lower()):\n      yield (w, entry.filename)",
    "docstring": "Index demo map function."
  },
  {
    "code": "def startup_script(self):\n        script_file = self.script_file\n        if script_file is None:\n            return None\n        try:\n            with open(script_file, \"rb\") as f:\n                return f.read().decode(\"utf-8\", errors=\"replace\")\n        except OSError as e:\n            raise VPCSError('Cannot read the startup script file \"{}\": {}'.format(script_file, e))",
    "docstring": "Returns the content of the current startup script"
  },
  {
    "code": "def _session_check(self):\n        if not os.path.exists(SESSION_FILE):\n            self._log.debug(\"Session file does not exist\")\n            return False\n        with open(SESSION_FILE, 'rb') as f:\n            cookies = requests.utils.cookiejar_from_dict(pickle.load(f))\n            self._session.cookies = cookies\n            self._log.debug(\"Loaded cookies from session file\")\n        response = self._session.get(url=self.TEST_URL, headers=self.HEADERS)\n        if self.TEST_KEY in str(response.content):\n            self._log.debug(\"Session file appears invalid\")\n            return False\n        self._is_authenticated = True\n        self._process_state()\n        return True",
    "docstring": "Attempt to authenticate the user through a session file.\n\n        This process is done to avoid having to authenticate the user every\n        single time. It uses a session file that is saved when a valid session\n        is captured and then reused. Because sessions can expire, we need to\n        test the session prior to calling the user authenticated. Right now\n        that is done with a test string found in an unauthenticated session.\n        This approach is not an ideal method, but it works."
  },
  {
    "code": "def getCredentials(self):\n        (username, password, public_key, private_key) = self.getCredentialValues()\n        if public_key or private_key:\n            return UserKeyCredential(username, public_key, private_key)\n        if username or password:\n            return UserPassCredential(username, password)\n        return None",
    "docstring": "Return UserKeyCredential or UserPassCredential."
  },
  {
    "code": "def bicluster_similarity(self, reference_model):\n        similarity_score = consensus_score(self.model.biclusters_, reference_model.biclusters_)\n        return similarity_score",
    "docstring": "Calculates the similarity between the current model of biclusters and the reference model of biclusters\n\n        :param reference_model: The reference model of biclusters\n        :return: Returns the consensus score(Hochreiter et. al., 2010), i.e. the similarity of two sets of biclusters."
  },
  {
    "code": "def getNamedItem(self, name: str) -> Optional[Attr]:\n        return self._dict.get(name, None)",
    "docstring": "Get ``Attr`` object which has ``name``.\n\n        If does not have ``name`` attr, return None."
  },
  {
    "code": "def get_one_dimensional_kernel(self, dim):\n        oneDkernel = GridRBF(input_dim=1, variance=self.variance.copy(), originalDimensions=dim)\n        return oneDkernel",
    "docstring": "Specially intended for Grid regression."
  },
  {
    "code": "def _update_alignment(self, alignment):\n        states = {\"top\": 2, \"middle\": 0, \"bottom\": 1}\n        self.alignment_tb.state = states[alignment]\n        self.alignment_tb.toggle(None)\n        self.alignment_tb.Refresh()",
    "docstring": "Updates vertical text alignment button\n\n        Parameters\n        ----------\n\n        alignment: String in [\"top\", \"middle\", \"right\"]\n        \\tSwitches button to untoggled if False and toggled if True"
  },
  {
    "code": "def update_aliases(self):\n        changed = False\n        try:\n            response = self.client.api.get_room_state(self.room_id)\n        except MatrixRequestError:\n            return False\n        for chunk in response:\n            content = chunk.get('content')\n            if content:\n                if 'aliases' in content:\n                    aliases = content['aliases']\n                    if aliases != self.aliases:\n                        self.aliases = aliases\n                        changed = True\n                if chunk.get('type') == 'm.room.canonical_alias':\n                    canonical_alias = content['alias']\n                    if self.canonical_alias != canonical_alias:\n                        self.canonical_alias = canonical_alias\n                        changed = True\n        if changed and self.aliases and not self.canonical_alias:\n            self.canonical_alias = self.aliases[0]\n        return changed",
    "docstring": "Get aliases information from room state\n\n        Returns:\n            boolean: True if the aliases changed, False if not"
  },
  {
    "code": "def connect_ec2_endpoint(url, aws_access_key_id=None, aws_secret_access_key=None, \n                         **kwargs):\n    from boto.ec2.regioninfo import RegionInfo\n    purl = urlparse.urlparse(url)\n    kwargs['port'] = purl.port\n    kwargs['host'] = purl.hostname\n    kwargs['path'] = purl.path\n    if not 'is_secure' in kwargs:\n        kwargs['is_secure'] = (purl.scheme == \"https\")\n    kwargs['region'] = RegionInfo(name = purl.hostname,\n        endpoint = purl.hostname)\n    kwargs['aws_access_key_id']=aws_access_key_id\n    kwargs['aws_secret_access_key']=aws_secret_access_key\n    return(connect_ec2(**kwargs))",
    "docstring": "Connect to an EC2 Api endpoint.  Additional arguments are passed\n    through to connect_ec2.\n\n    :type url: string\n    :param url: A url for the ec2 api endpoint to connect to\n\n    :type aws_access_key_id: string\n    :param aws_access_key_id: Your AWS Access Key ID\n\n    :type aws_secret_access_key: string\n    :param aws_secret_access_key: Your AWS Secret Access Key\n\n    :rtype: :class:`boto.ec2.connection.EC2Connection`\n    :return: A connection to Eucalyptus server"
  },
  {
    "code": "def format_specifier(ireq):\n    specs = ireq.specifier._specs if ireq.req is not None else []\n    specs = sorted(specs, key=lambda x: x._spec[1])\n    return \",\".join(str(s) for s in specs) or \"<any>\"",
    "docstring": "Generic formatter for pretty printing the specifier part of\n    InstallRequirements to the terminal."
  },
  {
    "code": "def connect_with_password(self, ssh, username, password, address, port, sock,\n                              timeout=20):\n        ssh.connect(username=username,\n                    password=password,\n                    hostname=address,\n                    port=port,\n                    sock=sock,\n                    timeout=timeout)",
    "docstring": "Create an ssh session to a remote host with a username and password\n\n        :type username: str\n        :param username: username used for ssh authentication\n        :type password: str\n        :param password: password used for ssh authentication\n        :type address: str\n        :param address: remote server address\n        :type port: int\n        :param port: remote server port"
  },
  {
    "code": "def plotdata(self, key, part='re', scale='log', steps=50):\n        if scale == 'log':\n            x = np.logspace(log(self.scale_min),\n                            log(self.scale_max),\n                            steps,\n                            base=e)\n        elif scale == 'linear':\n            x = np.linspace(self.scale_min,\n                            self.scale_max,\n                            steps)\n        y = self.fun(x)\n        y = np.array([d[key] for d in y])\n        if part == 're':\n            return x, y.real\n        elif part == 'im':\n            return x, y.imag",
    "docstring": "Return a tuple of arrays x, y that can be fed to plt.plot,\n        where x is the scale in GeV and y is the parameter of interest.\n\n        Parameters:\n\n        - key: dicionary key of the parameter to be plotted (e.g. a WCxf\n          coefficient name or a SM parameter like 'g')\n        - part: plot the real part 're' (default) or the imaginary part 'im'\n        - scale: 'log'; make the x steps logarithmically distributed; for\n          'linear', linearly distributed\n        - steps: steps in x to take (default: 50)"
  },
  {
    "code": "def save(self):\n        id = self.id or self.objects.id(self.name)\n        self.objects[id] = self.prepare_save(dict(self))\n        self.id = id\n        self.post_save()\n        return id",
    "docstring": "Save this entry.\n\n        If the entry does not have an :attr:`id`, a new id will be assigned,\n        and the :attr:`id` attribute set accordingly.\n\n        Pre-save processing of the fields saved can be done by\n        overriding the :meth:`prepare_save` method.\n\n        Additional actions to be done after the save operation\n        has been completed can be added by defining the\n        :meth:`post_save` method."
  },
  {
    "code": "def filter_silenced(self):\n        stashes = [\n            ('client', '/silence/{}'.format(self.event['client']['name'])),\n            ('check', '/silence/{}/{}'.format(\n                self.event['client']['name'],\n                self.event['check']['name'])),\n            ('check', '/silence/all/{}'.format(self.event['check']['name']))\n        ]\n        for scope, path in stashes:\n            if self.stash_exists(path):\n                self.bail(scope + ' alerts silenced')",
    "docstring": "Determine whether a check is silenced and shouldn't handle."
  },
  {
    "code": "def _database(self, writable=False):\n        if self.path == MEMORY_DB_NAME:\n            if not self.inmemory_db:\n                self.inmemory_db = xapian.inmemory_open()\n            return self.inmemory_db\n        if writable:\n            database = xapian.WritableDatabase(self.path, xapian.DB_CREATE_OR_OPEN)\n        else:\n            try:\n                database = xapian.Database(self.path)\n            except xapian.DatabaseOpeningError:\n                raise InvalidIndexError('Unable to open index at %s' % self.path)\n        return database",
    "docstring": "Private method that returns a xapian.Database for use.\n\n        Optional arguments:\n            ``writable`` -- Open the database in read/write mode (default=False)\n\n        Returns an instance of a xapian.Database or xapian.WritableDatabase"
  },
  {
    "code": "def _detect(self):\n        results = []\n        for c in self.slither.contracts_derived:\n            ret = self.detect_uninitialized(c)\n            for variable, functions in ret:\n                info = \"{}.{} ({}) is never initialized. It is used in:\\n\"\n                info = info.format(variable.contract.name,\n                                   variable.name,\n                                   variable.source_mapping_str)\n                for f in functions:\n                    info += \"\\t- {} ({})\\n\".format(f.name, f.source_mapping_str)\n                source = [variable.source_mapping]\n                source += [f.source_mapping for f in functions]\n                json = self.generate_json_result(info)\n                self.add_variable_to_json(variable, json)\n                self.add_functions_to_json(functions, json)\n                results.append(json)\n        return results",
    "docstring": "Detect uninitialized state variables\n\n        Recursively visit the calls\n        Returns:\n            dict: [contract name] = set(state variable uninitialized)"
  },
  {
    "code": "def capture(self, pattern, name=None):\n        if isinstance(pattern, basestring):\n            pattern = re.compile(pattern)\n        def munge(self, value):\n            match = pattern.match(value)\n            if not match:\n                return NONE\n            for group in [name or self.name, 1]:\n                try:\n                    return match.group(group)\n                except IndexError:\n                    pass\n            return NONE\n        return self.munge.attach(self)(munge)",
    "docstring": "Hooks munge to capture a value based on a regex."
  },
  {
    "code": "def stops(self):\n    stops = set()\n    for stop_time in self.stop_times():\n      stops |= stop_time.stops()\n    return stops",
    "docstring": "Return all stops visited by trips for this agency."
  },
  {
    "code": "def get_raw_data(self):\r\n        if self.__report_kind != HidP_Output \\\r\n                and self.__report_kind != HidP_Feature:\r\n            raise HIDError(\"Only for output or feature reports\")\r\n        self.__prepare_raw_data()\r\n        return helpers.ReadOnlyList(self.__raw_data)",
    "docstring": "Get raw HID report based on internal report item settings,\r\n        creates new c_ubytes storage"
  },
  {
    "code": "def loadFromTemplate(template, stim=None):\n        if stim is None:\n            stim = StimulusModel()\n        stim.setRepCount(template['reps'])\n        stim.setUserTag(template.get('user_tag', ''))\n        component_classes = get_stimuli_models()\n        for comp_doc in template['components']:\n            comp = get_component(comp_doc['stim_type'], component_classes)\n            comp.loadState(comp_doc)\n            stim.insertComponent(comp, *comp_doc['index'])\n        autoparams = template['autoparameters']\n        for p in autoparams:\n            selection = p['selection']\n            component_selection = []\n            for index in selection:\n                component = stim.component(*index)\n                component_selection.append(component)\n            p['selection'] = component_selection\n        stim.autoParams().setParameterList(autoparams)\n        stim.setReorderFunc(order_function(template['reorder']), template['reorder'])\n        stim.setStimType(template['testtype'])\n        return stim",
    "docstring": "Loads the stimlus to the state provided by a template\n\n        :param template: dict that includes all info nesessary to recreate stim\n        :type template: dict\n        :param stim: Stimulus to apply to, creates a new model if None\n        :type stim: StimulusModel"
  },
  {
    "code": "def parse_stage_name(stage):\n    if isinstance(stage, str):\n        return stage\n    try:\n        return stage.name\n    except AttributeError:\n        try:\n            return stage.__name__\n        except AttributeError:\n            raise TypeError(\"Unsupported stage type: {}\".format(type(stage)))",
    "docstring": "Determine the name of a stage.\n\n    The stage may be provided already as a name, as a Stage object, or as a\n    callable with __name__ (e.g., function).\n\n    :param str | pypiper.Stage | function stage: Object representing a stage,\n        from which to obtain name.\n    :return str: Name of putative pipeline Stage."
  },
  {
    "code": "def build_histogram(data, colorscale=None, nbins=10):\n    if colorscale is None:\n        colorscale = colorscale_default\n    colorscale = _colors_to_rgb(colorscale)\n    h_min, h_max = 0, 1\n    hist, bin_edges = np.histogram(data, range=(h_min, h_max), bins=nbins)\n    bin_mids = np.mean(np.array(list(zip(bin_edges, bin_edges[1:]))), axis=1)\n    histogram = []\n    max_bucket_value = max(hist)\n    sum_bucket_value = sum(hist)\n    for bar, mid in zip(hist, bin_mids):\n        height = np.floor(((bar / max_bucket_value) * 100) + 0.5)\n        perc = round((bar / sum_bucket_value) * 100.0, 1)\n        color = _map_val2color(mid, 0.0, 1.0, colorscale)\n        histogram.append({\"height\": height, \"perc\": perc, \"color\": color})\n    return histogram",
    "docstring": "Build histogram of data based on values of color_function"
  },
  {
    "code": "def clear_context(pid_file):\n    return\n    raise RuntimeError(\"Should not happen\")\n    fname = get_context_file_name(pid_file)\n    shutil.move(fname, fname.replace(\"context.json\", \"context.old.json\"))\n    data = {}\n    data[\"terminated\"] = str(datetime.datetime.now(datetime.timezone.utc))\n    set_context(pid_file, data)",
    "docstring": "Called at exit. Delete the context file to signal there is no active notebook.\n\n    We don't delete the whole file, but leave it around for debugging purposes. Maybe later we want to pass some information back to the web site."
  },
  {
    "code": "def save_file(client, bucket, data_file, items, dry_run=None):\n    logger.debug('Writing {number_items} items to s3. Bucket: {bucket} Key: {key}'.format(\n        number_items=len(items),\n        bucket=bucket,\n        key=data_file\n    ))\n    if not dry_run:\n        return _put_to_s3(client, bucket, data_file, json.dumps(items))",
    "docstring": "Tries to write JSON data to data file in S3."
  },
  {
    "code": "def find_unresolved_and_unreferenced_symbols(self):\n        unresolved = set()\n        unreferenced = self._definitions.copy()\n        self._collect_unresolved_and_unreferenced(set(), set(), unresolved, unreferenced,\n                                                  frozenset(self._definitions), start=True)\n        return unresolved, unreferenced - Scope.ALL_BUILTINS",
    "docstring": "Find any unresolved symbols, and unreferenced symbols from this scope.\n\n        :returns: ({unresolved}, {unreferenced})"
  },
  {
    "code": "def set_controller(self, controllers):\n        command = ovs_vsctl.VSCtlCommand('set-controller', [self.br_name])\n        command.args.extend(controllers)\n        self.run_command([command])",
    "docstring": "Sets the OpenFlow controller address.\n\n        This method is corresponding to the following ovs-vsctl command::\n\n            $ ovs-vsctl set-controller <bridge> <target>..."
  },
  {
    "code": "def set_icon(self, icon):\n        self._icon = icon\n        return self._listitem.setIconImage(icon)",
    "docstring": "Sets the listitem's icon image"
  },
  {
    "code": "def binaryRecordsStream(self, directory, recordLength):\n        return DStream(self._jssc.binaryRecordsStream(directory, recordLength), self,\n                       NoOpSerializer())",
    "docstring": "Create an input stream that monitors a Hadoop-compatible file system\n        for new files and reads them as flat binary files with records of\n        fixed length. Files must be written to the monitored directory by \"moving\"\n        them from another location within the same file system.\n        File names starting with . are ignored.\n\n        @param directory:       Directory to load data from\n        @param recordLength:    Length of each record in bytes"
  },
  {
    "code": "def start_monitoring(seconds_frozen=SECONDS_FROZEN,\n                     test_interval=TEST_INTERVAL):\n    thread = StoppableThread(target=monitor, args=(seconds_frozen,\n                                                   test_interval))\n    thread.daemon = True\n    thread.start()\n    return thread",
    "docstring": "Start monitoring for hanging threads.\n\n    seconds_frozen - How much time should thread hang to activate\n    printing stack trace - default(10)\n\n    tests_interval - Sleep time of monitoring thread (in milliseconds) \n    - default(100)"
  },
  {
    "code": "def init(self):\n        if not self.export_enable:\n            return None\n        try:\n            parameters = pika.URLParameters(\n                'amqp://' + self.user +\n                ':' + self.password +\n                '@' + self.host +\n                ':' + self.port + '/')\n            connection = pika.BlockingConnection(parameters)\n            channel = connection.channel()\n            return channel\n        except Exception as e:\n            logger.critical(\"Connection to rabbitMQ failed : %s \" % e)\n            return None",
    "docstring": "Init the connection to the rabbitmq server."
  },
  {
    "code": "def get_tweepy_auth(twitter_api_key,\n                    twitter_api_secret,\n                    twitter_access_token,\n                    twitter_access_token_secret):\n    auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret)\n    auth.set_access_token(twitter_access_token, twitter_access_token_secret)\n    return auth",
    "docstring": "Make a tweepy auth object"
  },
  {
    "code": "def analysis(self):\n        if self._analysis is not None:\n            return self._analysis\n        if self.cache_dir is not None:\n            path = os.path.join(self.cache_dir, self.checksum)\n            try:\n                if self.refresh_cache: raise IOError\n                with open(path + '.pickle', 'rb') as pickle_file:\n                    self._analysis = pickle.load(pickle_file)\n            except IOError:\n                self._analysis = librosa_analysis.analyze_frames(self.all_as_mono(), self.samplerate)\n                with open(path + '.pickle', 'wb') as pickle_file:\n                    pickle.dump(self._analysis, pickle_file, pickle.HIGHEST_PROTOCOL)\n        else:\n            self._analysis = librosa_analysis.analyze_frames(self.all_as_mono(), self.samplerate)\n        return self._analysis",
    "docstring": "Get musical analysis of the song using the librosa library"
  },
  {
    "code": "def params(self):\n        if self._GETPOST is None:\n            self._GETPOST = MultiDict(self.GET)\n            self._GETPOST.update(dict(self.POST))\n        return self._GETPOST",
    "docstring": "A combined MultiDict with POST and GET parameters."
  },
  {
    "code": "def _get_parents(folds, linenum):\n    parents = []\n    for fold in folds:\n        start, end = fold.range\n        if linenum >= start and linenum <= end:\n            parents.append(fold)\n        else:\n            continue\n    return parents",
    "docstring": "Get the parents at a given linenum.\n\n    If parents is empty, then the linenum belongs to the module.\n\n    Parameters\n    ----------\n    folds : list of :class:`FoldScopeHelper`\n    linenum : int\n        The line number to get parents for. Typically this would be the\n        cursor position.\n\n    Returns\n    -------\n    parents : list of :class:`FoldScopeHelper`\n        A list of :class:`FoldScopeHelper` objects that describe the defintion\n        heirarcy for the given ``linenum``. The 1st index will be the\n        top-level parent defined at the module level while the last index\n        will be the class or funtion that contains ``linenum``."
  },
  {
    "code": "def full(shape, fill_value, dtype=None, **kwargs):\n    return (dc.zeros(shape, **kwargs) + fill_value).astype(dtype)",
    "docstring": "Create an array of given shape and type, filled with `fill_value`.\n\n    Args:\n        shape (sequence of ints): 2D shape of the array.\n        fill_value (scalar or numpy.ndarray): Fill value or array.\n        dtype (data-type, optional): Desired data-type for the array.\n        kwargs (optional): Other arguments of the array (*coords, attrs, and name).\n\n    Returns:\n        array (decode.array): Decode array filled with `fill_value`."
  },
  {
    "code": "def sections(self) -> list:\n        self.config.read(self.filepath)\n        return self.config.sections()",
    "docstring": "List of sections."
  },
  {
    "code": "def exists(stream_name, region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    r = {}\n    stream = _get_basic_stream(stream_name, conn)\n    if 'error' in stream:\n        r['result'] = False\n        r['error'] = stream['error']\n    else:\n        r['result'] = True\n    return r",
    "docstring": "Check if the stream exists. Returns False and the error if it does not.\n\n    CLI example::\n\n        salt myminion boto_kinesis.exists my_stream region=us-east-1"
  },
  {
    "code": "def find_extensions(self, tag=None, namespace=None):\n        results = []\n        if tag and namespace:\n            for element in self.extension_elements:\n                if element.tag == tag and element.namespace == namespace:\n                    results.append(element)\n        elif tag and not namespace:\n            for element in self.extension_elements:\n                if element.tag == tag:\n                    results.append(element)\n        elif namespace and not tag:\n            for element in self.extension_elements:\n                if element.namespace == namespace:\n                    results.append(element)\n        else:\n            for element in self.extension_elements:\n                results.append(element)\n        return results",
    "docstring": "Searches extension elements for child nodes with the desired name.\n\n        Returns a list of extension elements within this object whose tag\n        and/or namespace match those passed in. To find all extensions in\n        a particular namespace, specify the namespace but not the tag name.\n        If you specify only the tag, the result list may contain extension\n        elements in multiple namespaces.\n\n        :param tag: str (optional) The desired tag\n        :param namespace: str (optional) The desired namespace\n\n        :Return: A list of elements whose tag and/or namespace match the\n            parameters values"
  },
  {
    "code": "def floor_func(self, addr):\n        try:\n            prev_addr = self._function_map.floor_addr(addr)\n            return self._function_map[prev_addr]\n        except KeyError:\n            return None",
    "docstring": "Return the function who has the greatest address that is less than or equal to `addr`.\n\n        :param int addr: The address to query.\n        :return:         A Function instance, or None if there is no other function before `addr`.\n        :rtype:          Function or None"
  },
  {
    "code": "async def set_record(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None,\n                         state=None, data=None, bucket=None):\n        if data is None:\n            data = {}\n        if bucket is None:\n            bucket = {}\n        chat, user = self.check_address(chat=chat, user=user)\n        addr = f\"fsm:{chat}:{user}\"\n        record = {'state': state, 'data': data, 'bucket': bucket}\n        conn = await self.redis()\n        await conn.execute('SET', addr, json.dumps(record))",
    "docstring": "Write record to storage\n\n        :param bucket:\n        :param chat:\n        :param user:\n        :param state:\n        :param data:\n        :return:"
  },
  {
    "code": "def map_dict(key_map, *dicts, copy=False, base=None):\n    it = combine_dicts(*dicts).items()\n    get = key_map.get\n    return combine_dicts({get(k, k): v for k, v in it}, copy=copy, base=base)",
    "docstring": "Returns a dict with new key values.\n\n    :param key_map:\n        A dictionary that maps the dict keys ({old key: new key}\n    :type key_map: dict\n\n    :param dicts:\n        A sequence of dicts.\n    :type dicts: dict\n\n    :param copy:\n        If True, it returns a deepcopy of input values.\n    :type copy: bool, optional\n\n    :param base:\n        Base dict where combine multiple dicts in one.\n    :type base: dict, optional\n\n    :return:\n        A unique dict with new key values.\n    :rtype: dict\n\n    Example::\n\n        >>> d = map_dict({'a': 'c', 'b': 'd'}, {'a': 1, 'b': 1}, {'b': 2})\n        >>> sorted(d.items())\n        [('c', 1), ('d', 2)]"
  },
  {
    "code": "def get_fullname(snapshot):\n    actor = get_actor(snapshot)\n    properties = api.get_user_properties(actor)\n    return properties.get(\"fullname\", actor)",
    "docstring": "Get the actor's fullname of the snapshot"
  },
  {
    "code": "def load_from_string(self, content, container, **kwargs):\n        return self.load_from_stream(anyconfig.compat.StringIO(content),\n                                     container, **kwargs)",
    "docstring": "Load config from given string 'cnf_content'.\n\n        :param content: Config content string\n        :param container: callble to make a container object later\n        :param kwargs: optional keyword parameters to be sanitized :: dict\n\n        :return: Dict-like object holding config parameters"
  },
  {
    "code": "def _domain_event_agent_lifecycle_cb(conn, domain, state, reason, opaque):\n    _salt_send_domain_event(opaque, conn, domain, opaque['event'], {\n        'state': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_', state),\n        'reason': _get_libvirt_enum_string('VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_REASON_', reason)\n    })",
    "docstring": "Domain agent lifecycle events handler"
  },
  {
    "code": "def clean_pid_file(pidfile):\n    if pidfile and os.path.exists(pidfile):\n        os.unlink(pidfile)",
    "docstring": "clean pid file."
  },
  {
    "code": "def geometric_center(coords, periodic):\n    max_vals = periodic\n    theta = 2 * np.pi * (coords / max_vals)\n    eps = np.cos(theta) * max_vals / (2 * np.pi)\n    zeta = np.sin(theta) * max_vals / (2 * np.pi)\n    eps_avg = eps.sum(axis=0)\n    zeta_avg = zeta.sum(axis=0)\n    theta_avg = np.arctan2(-zeta_avg, -eps_avg) + np.pi\n    return theta_avg * max_vals / (2 * np.pi)",
    "docstring": "Geometric center taking into account periodic boundaries"
  },
  {
    "code": "def nsdiffs(x, m, max_D=2, test='ocsb', **kwargs):\n    if max_D <= 0:\n        raise ValueError('max_D must be a positive integer')\n    testfunc = get_callable(test, VALID_STESTS)(m, **kwargs)\\\n        .estimate_seasonal_differencing_term\n    x = column_or_1d(check_array(x, ensure_2d=False,\n                                 force_all_finite=True, dtype=DTYPE))\n    if is_constant(x):\n        return 0\n    D = 0\n    dodiff = testfunc(x)\n    while dodiff == 1 and D < max_D:\n        D += 1\n        x = diff(x, lag=m)\n        if is_constant(x):\n            return D\n        dodiff = testfunc(x)\n    return D",
    "docstring": "Estimate the seasonal differencing term, ``D``.\n\n    Perform a test of seasonality for different levels of ``D`` to\n    estimate the number of seasonal differences required to make a given time\n    series stationary. Will select the maximum value of ``D`` for which\n    the time series is judged seasonally stationary by the statistical test.\n\n    Parameters\n    ----------\n    x : array-like, shape=(n_samples, [n_features])\n        The array to difference.\n\n    m : int\n        The number of seasonal periods (i.e., frequency of the\n        time series)\n\n    max_D : int, optional (default=2)\n        Maximum number of seasonal differences allowed. Must\n        be a positive integer. The estimated value of ``D`` will not\n        exceed ``max_D``.\n\n    test : str, optional (default='ocsb')\n        Type of unit root test of seasonality to use in order\n        to detect seasonal periodicity. Valid tests include (\"ocsb\", \"ch\").\n        Note that the CHTest is very slow for large data.\n\n    Returns\n    -------\n    D : int\n        The estimated seasonal differencing term. This is the maximum value\n        of ``D`` such that ``D <= max_D`` and the time series is judged\n        seasonally stationary. If the time series is constant, will return 0."
  },
  {
    "code": "def python_date_format(self, long_format=None, time_only=False):\n        msgid = long_format and 'date_format_long' or 'date_format_short'\n        if time_only:\n            msgid = 'time_format'\n        formatstring = translate(msgid, domain=\"senaite.core\",\n                                 context=self.request)\n        if formatstring is None or formatstring.startswith(\n                'date_') or formatstring.startswith('time_'):\n            self.logger.error(\"bika/%s/%s could not be translated\" %\n                              (self.request.get('LANGUAGE'), msgid))\n            properties = getToolByName(self.context,\n                                       'portal_properties').site_properties\n            if long_format:\n                format = properties.localLongTimeFormat\n            else:\n                if time_only:\n                    format = properties.localTimeOnlyFormat\n                else:\n                    format = properties.localTimeFormat\n            return format\n        return formatstring.replace(r\"${\", '%').replace('}', '')",
    "docstring": "This convert bika domain date format msgstrs to Python\n        strftime format strings, by the same rules as ulocalized_time.\n        XXX i18nl10n.py may change, and that is where this code is taken from."
  },
  {
    "code": "def setup_datafind_runtime_frames_multi_calls_perifo(cp, scienceSegs,\n                                                     outputDir, tags=None):\n    datafindcaches, _ = \\\n        setup_datafind_runtime_cache_multi_calls_perifo(cp, scienceSegs,\n                                                        outputDir, tags=tags)\n    datafindouts = convert_cachelist_to_filelist(datafindcaches)\n    return datafindcaches, datafindouts",
    "docstring": "This function uses the glue.datafind library to obtain the location of all\n    the frame files that will be needed to cover the analysis of the data\n    given in scienceSegs. This function will not check if the returned frames\n    cover the whole time requested, such sanity checks are done in the\n    pycbc.workflow.setup_datafind_workflow entry function. As opposed to\n    setup_datafind_runtime_single_call_perifo this call will one call to the\n    datafind server for every science segment. This function will return a list\n    of files corresponding to the individual frames returned by the datafind\n    query. This will allow pegasus to more easily identify all the files used\n    as input, but may cause problems for codes that need to take frame cache\n    files as input.\n\n    Parameters\n    -----------\n    cp : ConfigParser.ConfigParser instance\n        This contains a representation of the information stored within the\n        workflow configuration files\n    scienceSegs : Dictionary of ifo keyed glue.segment.segmentlist instances\n        This contains the times that the workflow is expected to analyse.\n    outputDir : path\n        All output files written by datafind processes will be written to this\n        directory.\n    tags : list of strings, optional (default=None)\n        Use this to specify tags. This can be used if this module is being\n        called more than once to give call specific configuration (by setting\n        options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).\n        This is also used to tag the Files returned by the class to uniqueify\n        the Files and uniqueify the actual filename.\n        FIXME: Filenames may not be unique with current codes!\n\n    Returns\n    --------\n    datafindcaches : list of glue.lal.Cache instances\n       The glue.lal.Cache representations of the various calls to the datafind\n       server and the returned frame files.\n    datafindOuts : pycbc.workflow.core.FileList\n        List of all the datafind output files for use later in the pipeline."
  },
  {
    "code": "def _get_format_module(image_format):\n    format_module = None\n    nag_about_gifs = False\n    if detect_format.is_format_selected(image_format,\n                                        Settings.to_png_formats,\n                                        png.PROGRAMS):\n        format_module = png\n    elif detect_format.is_format_selected(image_format, jpeg.FORMATS,\n                                          jpeg.PROGRAMS):\n        format_module = jpeg\n    elif detect_format.is_format_selected(image_format, gif.FORMATS,\n                                          gif.PROGRAMS):\n        format_module = gif\n        nag_about_gifs = True\n    return format_module, nag_about_gifs",
    "docstring": "Get the format module to use for optimizing the image."
  },
  {
    "code": "def add_clink(self,my_clink):\n        if self.causalRelations_layer is None:\n            self.causalRelations_layer = CcausalRelations()\n            self.root.append(self.causalRelations_layer.get_node())\n        self.causalRelations_layer.add_clink(my_clink)",
    "docstring": "Adds a clink to the causalRelations layer\n        @type my_clink: L{Cclink}\n        @param my_clink: clink object"
  },
  {
    "code": "def quit_all(editor, force=False):\n    quit(editor, all_=True, force=force)",
    "docstring": "Quit all."
  },
  {
    "code": "def sample_stats_to_xarray(self):\n        data = self.sample_stats\n        if not isinstance(data, dict):\n            raise TypeError(\"DictConverter.sample_stats is not a dictionary\")\n        return dict_to_dataset(data, library=None, coords=self.coords, dims=self.dims)",
    "docstring": "Convert sample_stats samples to xarray."
  },
  {
    "code": "def time_at_elevation(self, elevation, direction=SUN_RISING, date=None, local=True):\n        if local and self.timezone is None:\n            raise ValueError(\"Local time requested but Location has no timezone set.\")\n        if self.astral is None:\n            self.astral = Astral()\n        if date is None:\n            date = datetime.date.today()\n        if elevation > 90.0:\n            elevation = 180.0 - elevation\n            direction = SUN_SETTING\n        time_ = self.astral.time_at_elevation_utc(\n            elevation, direction, date, self.latitude, self.longitude\n        )\n        if local:\n            return time_.astimezone(self.tz)\n        else:\n            return time_",
    "docstring": "Calculate the time when the sun is at the specified elevation.\n\n        Note:\n            This method uses positive elevations for those above the horizon.\n\n            Elevations greater than 90 degrees are converted to a setting sun\n            i.e. an elevation of 110 will calculate a setting sun at 70 degrees.\n\n        :param elevation:  Elevation in degrees above the horizon to calculate for.\n        :type elevation:   float\n\n        :param direction:  Determines whether the time is for the sun rising or setting.\n                           Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``. Default is rising.\n        :type direction:   int\n\n        :param date: The date for which to calculate the elevation time.\n                     If no date is specified then the current date will be used.\n        :type date:  :class:`~datetime.date`\n\n        :param local: True  = Time to be returned in location's time zone;\n                      False = Time to be returned in UTC.\n                      If not specified then the time will be returned in local time\n        :type local:  bool\n\n        :returns: The date and time at which dusk occurs.\n        :rtype: :class:`~datetime.datetime`"
  },
  {
    "code": "def read_string_from_file(path, encoding=\"utf8\"):\n  with codecs.open(path, \"rb\", encoding=encoding) as f:\n    value = f.read()\n  return value",
    "docstring": "Read entire contents of file into a string."
  },
  {
    "code": "def storeFASTA(fastaFNH):\n    fasta = file_handle(fastaFNH).read()\n    return [FASTARecord(rec[0].split()[0], rec[0].split(None, 1)[1], \"\".join(rec[1:]))\n            for rec in (x.strip().split(\"\\n\") for x in fasta.split(\">\")[1:])]",
    "docstring": "Parse the records in a FASTA-format file by first reading the entire file into memory.\n\n    :type source: path to FAST file or open file handle\n    :param source: The data source from which to parse the FASTA records. Expects the\n                   input to resolve to a collection that can be iterated through, such as\n                   an open file handle.\n\n    :rtype: tuple\n    :return: FASTA records containing entries for id, description and data."
  },
  {
    "code": "def get_description(self, lang=None):\n        return self.metadata.get_single(key=RDF_NAMESPACES.CTS.description, lang=lang)",
    "docstring": "Get the DC description of the object\n\n        :param lang: Lang to retrieve\n        :return: Description string representation\n        :rtype: Literal"
  },
  {
    "code": "def indexOfClosest( arr, val ):\n    i_closest = None\n    for i,v in enumerate(arr):\n        d = math.fabs( v - val )\n        if i_closest == None or d < d_closest:\n            i_closest = i\n            d_closest = d\n    return i_closest",
    "docstring": "Return the index in arr of the closest float value to val."
  },
  {
    "code": "def _infer_binop(self, context):\n    left = self.left\n    right = self.right\n    context = context or contextmod.InferenceContext()\n    lhs_context = contextmod.copy_context(context)\n    rhs_context = contextmod.copy_context(context)\n    lhs_iter = left.infer(context=lhs_context)\n    rhs_iter = right.infer(context=rhs_context)\n    for lhs, rhs in itertools.product(lhs_iter, rhs_iter):\n        if any(value is util.Uninferable for value in (rhs, lhs)):\n            yield util.Uninferable\n            return\n        try:\n            yield from _infer_binary_operation(lhs, rhs, self, context, _get_binop_flow)\n        except exceptions._NonDeducibleTypeHierarchy:\n            yield util.Uninferable",
    "docstring": "Binary operation inference logic."
  },
  {
    "code": "def _set_upload_status(self, file_data_object, upload_status):\n        uuid = file_data_object['uuid']\n        return self.connection.update_data_object(\n            uuid,\n            {'uuid': uuid, 'value': { 'upload_status': upload_status}}\n        )",
    "docstring": "Set file_data_object.file_resource.upload_status"
  },
  {
    "code": "def __execute_rot(self, surface):\n        self.image = pygame.transform.rotate(surface, self.__rotation)\n        self.__resize_surface_extents()",
    "docstring": "Executes the rotating operation"
  },
  {
    "code": "def safe_better_repr(\n            self, obj, context=None, html=True, level=0, full=False\n    ):\n        context = context and dict(context) or {}\n        recursion = id(obj) in context\n        if not recursion:\n            context[id(obj)] = obj\n            try:\n                rv = self.better_repr(obj, context, html, level + 1, full)\n            except Exception:\n                rv = None\n            if rv:\n                return rv\n        self.obj_cache[id(obj)] = obj\n        if html:\n            return '<a href=\"%d\" class=\"inspect\">%s%s</a>' % (\n                id(obj), 'Recursion of '\n                if recursion else '', escape(self.safe_repr(obj))\n            )\n        return '%s%s' % (\n            'Recursion of ' if recursion else '', self.safe_repr(obj)\n        )",
    "docstring": "Repr with inspect links on objects"
  },
  {
    "code": "def wrap_all(self, rows: Iterable[Union[Mapping[str, Any], Sequence[Any]]]):\n        return (self.wrap(r) for r in rows)",
    "docstring": "Return row tuple for each row in rows."
  },
  {
    "code": "def print_languages_and_exit(lst, status=1, header=True):\n    if header:\n        print(\"Available languages:\")\n    for lg in lst:\n        print(\"- %s\" % lg)\n    sys.exit(status)",
    "docstring": "print a list of languages and exit"
  },
  {
    "code": "def _terminate_process_iou(self):\n        if self._iou_process:\n            log.info('Stopping IOU process for IOU VM \"{}\" PID={}'.format(self.name, self._iou_process.pid))\n            try:\n                self._iou_process.terminate()\n            except ProcessLookupError:\n                pass\n        self._started = False\n        self.status = \"stopped\"",
    "docstring": "Terminate the IOU process if running"
  },
  {
    "code": "def peek(self, iroute: \"InstanceRoute\") -> Optional[Value]:\n        val = self.value\n        sn = self.schema_node\n        for sel in iroute:\n            val, sn = sel.peek_step(val, sn)\n            if val is None:\n                return None\n        return val",
    "docstring": "Return a value within the receiver's subtree.\n\n        Args:\n            iroute: Instance route (relative to the receiver)."
  },
  {
    "code": "def delete_sandbox(self, si, logger, vcenter_data_model, delete_sandbox_actions, cancellation_context):\n        results = []\n        logger.info('Deleting saved sandbox command starting on ' + vcenter_data_model.default_datacenter)\n        if not delete_sandbox_actions:\n            raise Exception('Failed to delete saved sandbox, missing data in request.')\n        actions_grouped_by_save_types = groupby(delete_sandbox_actions, lambda x: x.actionParams.saveDeploymentModel)\n        artifactHandlersToActions = {ArtifactHandler.factory(k,\n                                                             self.pyvmomi_service,\n                                                             vcenter_data_model,\n                                                             si,\n                                                             logger,\n                                                             self.deployer,\n                                                             None,\n                                                             self.resource_model_parser,\n                                                             self.snapshot_saver,\n                                                             self.task_waiter,\n                                                             self.folder_manager,\n                                                             self.pg,\n                                                             self.cs): list(g)\n                                     for k, g in actions_grouped_by_save_types}\n        self._validate_save_deployment_models(artifactHandlersToActions, delete_sandbox_actions, results)\n        error_results = [r for r in results if not r.success]\n        if not error_results:\n            results = self._execute_delete_saved_sandbox(artifactHandlersToActions,\n                                                         cancellation_context,\n                                                         logger,\n                                                         results)\n        return results",
    "docstring": "Deletes a saved sandbox's artifacts\n\n        :param vcenter_data_model: VMwarevCenterResourceModel\n        :param vim.ServiceInstance si: py_vmomi service instance\n        :type si: vim.ServiceInstance\n        :param logger: Logger\n        :type logger: cloudshell.core.logger.qs_logger.get_qs_logger\n        :param list[SaveApp] delete_sandbox_actions:\n        :param cancellation_context:"
  },
  {
    "code": "def get_execution_host_info():\n    host = os.environ.get('HOSTNAME', None)\n    cluster = os.environ.get('SGE_O_HOST', None)\n    if host is None:\n        try:\n            import socket\n            host = host or socket.gethostname()\n        except:\n            pass\n    return host or 'unknown', cluster or 'unknown'",
    "docstring": "Tries to return a tuple describing the execution host.\n    Doesn't work for all queueing systems\n\n    Returns:\n        (HOSTNAME, CLUSTER_NAME)"
  },
  {
    "code": "def setValue(self, value):\n        if isinstance(value, Text):\n            self.value = value\n        else:\n            self.value = Text(value)\n        return self",
    "docstring": "Set the attributes value\n        @param value: The new value (may be None)\n        @type value: basestring\n        @return: self\n        @rtype: L{Attribute}"
  },
  {
    "code": "def get_column(self, chrom, position,\n                 missing_seqs=MissingSequenceHandler.TREAT_AS_ALL_GAPS,\n                 species=None):\n    blocks = self.get_blocks(chrom, position, position + 1)\n    if len(blocks) == 0:\n      raise NoSuchAlignmentColumnError(\"Request for column on chrom \" +\n                                       chrom + \" at position \" +\n                                       str(position) + \" not possible; \" +\n                                       \"genome alignment not defined at \" +\n                                       \"that locus.\")\n    if len(blocks) > 1:\n      raise NoUniqueColumnError(\"Request for column on chrom \" + chrom +\n                                \" at position \" + str(position) + \"not \" +\n                                \"possible; ambiguous alignment of that locus.\")\n    return blocks[0].get_column_absolute(position, missing_seqs, species)",
    "docstring": "Get the alignment column at the specified chromosome and position."
  },
  {
    "code": "def _disable_access_key(self, force_disable_self=False):\n        client = self.client\n        if self.validate is True:\n            return\n        else:\n            try:\n                client.update_access_key(\n                    UserName=self._search_user_for_key(),\n                    AccessKeyId=self.access_key_id,\n                    Status='Inactive'\n                )\n                logger.info(\n                    \"Access key {id} has \"\n                    \"been disabled.\".format(id=self.access_key_id)\n                )\n            except Exception as e:\n                logger.info(\n                    \"Access key {id} could not \"\n                    \"be disabled due to: {e}.\".format(\n                        e=e, id=self.access_key_id\n                    )\n                )",
    "docstring": "This function first checks to see if the key is already disabled\\\n\n        if not then it goes to disabling"
  },
  {
    "code": "def update():\n    with settings(warn_only=True):\n        print(cyan('\\nInstalling/Updating required packages...'))\n        pip = local('venv/bin/pip install -U --allow-all-external --src libs -r requirements.txt', capture=True)\n        if pip.failed:\n            print(red(pip))\n            abort(\"pip exited with return code %i\" % pip.return_code)\n        print(green('Packages requirements updated.'))",
    "docstring": "Update virtual env with requirements packages."
  },
  {
    "code": "def subscribe(self, feedUrl):\n        response = self.httpPost(\n            ReaderUrl.SUBSCRIPTION_EDIT_URL,\n            {'ac':'subscribe', 's': feedUrl})\n        if response and 'OK' in response:\n            return True\n        else:\n            return False",
    "docstring": "Adds a feed to the top-level subscription list\n\n        Ubscribing seems idempotent, you can subscribe multiple times\n        without error\n\n        returns True or throws HTTPError"
  },
  {
    "code": "def expand_to_chunk_size(self, chunk_size, offset=Vec(0,0,0, dtype=int)):\n    chunk_size = np.array(chunk_size, dtype=np.float32)\n    result = self.clone()\n    result = result - offset\n    result.minpt = np.floor(result.minpt / chunk_size) * chunk_size\n    result.maxpt = np.ceil(result.maxpt / chunk_size) * chunk_size \n    return (result + offset).astype(self.dtype)",
    "docstring": "Align a potentially non-axis aligned bbox to the grid by growing it\n    to the nearest grid lines.\n\n    Required:\n      chunk_size: arraylike (x,y,z), the size of chunks in the \n                    dataset e.g. (64,64,64)\n    Optional:\n      offset: arraylike (x,y,z), the starting coordinate of the dataset"
  },
  {
    "code": "def on_successful_login(self, subject, authc_token, account_id):\n        self.forget_identity(subject)\n        if authc_token.is_remember_me:\n            self.remember_identity(subject, authc_token, account_id)\n        else:\n            msg = (\"AuthenticationToken did not indicate that RememberMe is \"\n                   \"requested.  RememberMe functionality will not be executed \"\n                   \"for corresponding account.\")\n            logger.debug(msg)",
    "docstring": "Reacts to the successful login attempt by first always\n        forgetting any previously stored identity.  Then if the authc_token\n        is a ``RememberMe`` type of token, the associated identity\n        will be remembered for later retrieval during a new user session.\n\n        :param subject: the subject whose identifying attributes are being\n                        remembered\n        :param authc_token:  the token that resulted in a successful\n                             authentication attempt\n        :param account_id: id of authenticated account"
  },
  {
    "code": "def comments_are_open(content_object):\n    moderator = get_model_moderator(content_object.__class__)\n    if moderator is None:\n        return True\n    return CommentModerator.allow(moderator, None, content_object, None)",
    "docstring": "Return whether comments are still open for a given target object."
  },
  {
    "code": "def extra_metadata(self):\n        return get_extra_metadata(\n            self.gh.api,\n            self.repository['owner']['login'],\n            self.repository['name'],\n            self.release['tag_name'],\n        )",
    "docstring": "Get extra metadata for file in repository."
  },
  {
    "code": "def _add_device_to_device_group(self, device):\n        device_name = get_device_info(device).name\n        dg = pollster(self._get_device_group)(device)\n        dg.devices_s.devices.create(name=device_name, partition=self.partition)\n        pollster(self._check_device_exists_in_device_group)(device_name)",
    "docstring": "Add device to device service cluster group.\n\n        :param device: bigip object -- device to add to group"
  },
  {
    "code": "def catalogFactory(name, **kwargs):\n    fn = lambda member: inspect.isclass(member) and member.__module__==__name__\n    catalogs = odict(inspect.getmembers(sys.modules[__name__], fn))\n    if name not in list(catalogs.keys()):\n        msg = \"%s not found in catalogs:\\n %s\"%(name,list(kernels.keys()))\n        logger.error(msg)\n        msg = \"Unrecognized catalog: %s\"%name\n        raise Exception(msg)\n    return catalogs[name](**kwargs)",
    "docstring": "Factory for various catalogs."
  },
  {
    "code": "def read_remote_spec(filename, encoding='binary', cache=True,\n                     show_progress=True, **kwargs):\n    with get_readable_fileobj(filename, encoding=encoding, cache=cache,\n                              show_progress=show_progress) as fd:\n        header, wavelengths, fluxes = read_spec(fd, fname=filename, **kwargs)\n    return header, wavelengths, fluxes",
    "docstring": "Read FITS or ASCII spectrum from a remote location.\n\n    Parameters\n    ----------\n    filename : str\n        Spectrum filename.\n\n    encoding, cache, show_progress\n        See :func:`~astropy.utils.data.get_readable_fileobj`.\n\n    kwargs : dict\n        Keywords acceptable by :func:`read_fits_spec` (if FITS) or\n        :func:`read_ascii_spec` (if ASCII).\n\n    Returns\n    -------\n    header : dict\n        Metadata.\n\n    wavelengths, fluxes : `~astropy.units.quantity.Quantity`\n        Wavelength and flux of the spectrum."
  },
  {
    "code": "def generate_sample_set(self, tags=None):\n        if isinstance(tags, str):\n            tags = [tags]\n        md5_list = self.data_store.tag_match(tags)\n        return self.store_sample_set(md5_list)",
    "docstring": "Generate a sample_set that maches the tags or all if tags are not specified.\n\n            Args:\n                tags: Match samples against this tag list (or all if not specified)\n\n            Returns:\n                The sample_set of those samples matching the tags"
  },
  {
    "code": "def run(self):\n        which_command = self._args.which\n        if which_command == 'compound':\n            self._search_compound()\n        elif which_command == 'reaction':\n            self._search_reaction()",
    "docstring": "Run search command."
  },
  {
    "code": "def _on_grant(self, grant):\n        self.set_timeout(grant.expiration_time, ContractState.expired,\n                         self._run_and_terminate, self.contractor.cancelled,\n                         grant)\n        self.grant = grant\n        self.set_remote_id(grant.sender_id)\n        self.update_manager_address(grant.reply_to)\n        self.call_agent_side(self.contractor.granted, grant,\n                             ensure_state=ContractState.granted)",
    "docstring": "Called upon receiving the grant. Than calls granted and sets\n        up reporter if necessary."
  },
  {
    "code": "def get(self):\n        new_alarm = self.entity.get_alarm(self)\n        if new_alarm:\n            self._add_details(new_alarm._info)",
    "docstring": "Fetches the current state of the alarm from the API and updates the\n        object."
  },
  {
    "code": "def to_sql(self, connection, grammar):\n        self._add_implied_commands()\n        statements = []\n        for command in self._commands:\n            method = \"compile_%s\" % command.name\n            if hasattr(grammar, method):\n                sql = getattr(grammar, method)(self, command, connection)\n                if sql is not None:\n                    if isinstance(sql, list):\n                        statements += sql\n                    else:\n                        statements.append(sql)\n        return statements",
    "docstring": "Get the raw SQL statements for the blueprint.\n\n        :param connection: The connection to use\n        :type connection: orator.connections.Connection\n\n        :param grammar: The grammar to user\n        :type grammar: orator.schema.grammars.SchemaGrammar\n\n        :rtype: list"
  },
  {
    "code": "def detachChildren(self):\n        detached = self.children\n        self.children = []\n        for child in detached:\n            child.parent = None\n        return detached",
    "docstring": "Detach and return this element's children.\n        @return: The element's children (detached).\n        @rtype: [L{Element},...]"
  },
  {
    "code": "def signed_gt(a, b):\n    a, b = match_bitwidth(as_wires(a), as_wires(b), signed=True)\n    r = b - a\n    return r[-1] ^ (~a[-1]) ^ (~b[-1])",
    "docstring": "Return a single bit result of signed greater than comparison."
  },
  {
    "code": "def getVerifiersIDs(self):\n        verifiers_ids = list()\n        for brain in self.getAnalyses():\n            verifiers_ids += brain.getVerificators\n        return list(set(verifiers_ids))",
    "docstring": "Returns the ids from users that have verified at least one analysis\n        from this Analysis Request"
  },
  {
    "code": "def get_random_word(dictionary, min_word_length=3, max_word_length=8):\n    while True:\n        word = choice(dictionary)\n        if len(word) >= min_word_length and len(word) <= max_word_length:\n            break\n    return word",
    "docstring": "Returns a random word from the dictionary"
  },
  {
    "code": "def exec_(scope, data):\n    conn = scope.get('__connection__')\n    response = []\n    for line in data:\n        conn.send(line)\n        conn.expect_prompt()\n        response += conn.response.split('\\n')[1:]\n    scope.define(__response__=response)\n    return True",
    "docstring": "Sends the given data to the remote host and waits until the host\n    has responded with a prompt.\n    If the given data is a list of strings, each item is sent, and\n    after each item a prompt is expected.\n\n    This function also causes the response of the command to be stored\n    in the built-in __response__ variable.\n\n    :type  data: string\n    :param data: The data that is sent."
  },
  {
    "code": "def _put (self, url_data):\n        if self.shutdown or self.max_allowed_urls == 0:\n            return\n        log.debug(LOG_CACHE, \"queueing %s\", url_data.url)\n        key = url_data.cache_url\n        cache = url_data.aggregate.result_cache\n        if url_data.has_result or cache.has_result(key):\n            self.queue.appendleft(url_data)\n        else:\n            assert key is not None, \"no result for None key: %s\" % url_data\n            if self.max_allowed_urls is not None:\n                self.max_allowed_urls -= 1\n            self.num_puts += 1\n            if self.num_puts >= NUM_PUTS_CLEANUP:\n                self.cleanup()\n            self.queue.append(url_data)\n        self.unfinished_tasks += 1",
    "docstring": "Put URL in queue, increase number of unfished tasks."
  },
  {
    "code": "def get_availabilities(date):\n    day_of_week = dateutil.parser.parse(date).weekday()\n    availabilities = []\n    available_probability = 0.3\n    if day_of_week == 0:\n        start_hour = 10\n        while start_hour <= 16:\n            if random.random() < available_probability:\n                appointment_type = get_random_int(1, 4)\n                if appointment_type == 1:\n                    availabilities.append('{}:00'.format(start_hour))\n                elif appointment_type == 2:\n                    availabilities.append('{}:30'.format(start_hour))\n                else:\n                    availabilities.append('{}:00'.format(start_hour))\n                    availabilities.append('{}:30'.format(start_hour))\n            start_hour += 1\n    if day_of_week == 2 or day_of_week == 4:\n        availabilities.append('10:00')\n        availabilities.append('16:00')\n        availabilities.append('16:30')\n    return availabilities",
    "docstring": "Helper function which in a full implementation would  feed into a backend API to provide query schedule availability.\n    The output of this function is an array of 30 minute periods of availability, expressed in ISO-8601 time format.\n\n    In order to enable quick demonstration of all possible conversation paths supported in this example, the function\n    returns a mixture of fixed and randomized results.\n\n    On Mondays, availability is randomized; otherwise there is no availability on Tuesday / Thursday and availability at\n    10:00 - 10:30 and 4:00 - 5:00 on Wednesday / Friday."
  },
  {
    "code": "def delete_object(cache, template, indexes):\n    with cache as redis_connection:\n        pipe = redis_connection.pipeline()\n        for key in set(template.keys()):\n            pipe.delete(template[key] % indexes)\n        pipe.execute()",
    "docstring": "Delete an object in Redis using a pipeline.\n\n    Deletes all fields defined by the template.\n\n    Arguments:\n        template: a dictionary containg the keys for the object and\n            template strings for the corresponding redis keys. The template\n            string uses named string interpolation format. Example:\n\n            {\n                'username': 'user:%(id)s:username',\n                'email': 'user:%(id)s:email',\n                'phone': 'user:%(id)s:phone'\n            }\n\n        indexes: a dictionary containing the values to use to construct the\n            redis keys: Example:\n\n            {\n                'id': 342\n            }"
  },
  {
    "code": "def drop_privileges():\n    uid = int(pwd.getpwnam(settings.DROPLET_USER).pw_uid)\n    os.setuid(uid)",
    "docstring": "Set settings.DROPLET_USER UID for the current process\n\n    After calling this, root operation will be impossible to execute\n\n    See root context manager"
  },
  {
    "code": "def get_generic_type(type_tag):\n    return {\n        DEVICE_ALARM: TYPE_ALARM,\n        DEVICE_GLASS_BREAK: TYPE_CONNECTIVITY,\n        DEVICE_KEYPAD: TYPE_CONNECTIVITY,\n        DEVICE_REMOTE_CONTROLLER: TYPE_CONNECTIVITY,\n        DEVICE_SIREN: TYPE_CONNECTIVITY,\n        DEVICE_STATUS_DISPLAY: TYPE_CONNECTIVITY,\n        DEVICE_DOOR_CONTACT: TYPE_OPENING,\n        DEVICE_MOTION_CAMERA: TYPE_CAMERA,\n        DEVICE_MOTION_VIDEO_CAMERA: TYPE_CAMERA,\n        DEVICE_IP_CAM: TYPE_CAMERA,\n        DEVICE_OUTDOOR_MOTION_CAMERA: TYPE_CAMERA,\n        DEVICE_SECURE_BARRIER: TYPE_COVER,\n        DEVICE_DIMMER: TYPE_LIGHT,\n        DEVICE_DIMMER_METER: TYPE_LIGHT,\n        DEVICE_HUE: TYPE_LIGHT,\n        DEVICE_DOOR_LOCK: TYPE_LOCK,\n        DEVICE_WATER_SENSOR: TYPE_CONNECTIVITY,\n        DEVICE_SWITCH: TYPE_SWITCH,\n        DEVICE_NIGHT_SWITCH: TYPE_SWITCH,\n        DEVICE_POWER_SWITCH_SENSOR: TYPE_SWITCH,\n        DEVICE_POWER_SWITCH_METER: TYPE_SWITCH,\n        DEVICE_VALVE: TYPE_VALVE,\n        DEVICE_ROOM_SENSOR: TYPE_UNKNOWN_SENSOR,\n        DEVICE_TEMPERATURE_SENSOR: TYPE_UNKNOWN_SENSOR,\n        DEVICE_MULTI_SENSOR: TYPE_UNKNOWN_SENSOR,\n        DEVICE_PIR: TYPE_UNKNOWN_SENSOR,\n        DEVICE_POVS: TYPE_UNKNOWN_SENSOR,\n    }.get(type_tag.lower(), None)",
    "docstring": "Map type tag to generic type."
  },
  {
    "code": "def add_frame_widget(self, ref, left=1, top=1, right=20, bottom=1, width=20, height=4, direction=\"h\", speed=1):\n        if ref not in self.widgets:\n            widget = widgets.FrameWidget(\n                screen=self, ref=ref, left=left, top=top, right=right, bottom=bottom, width=width, height=height,\n                direction=direction, speed=speed,\n            )\n            self.widgets[ref] = widget\n            return self.widgets[ref]",
    "docstring": "Add Frame Widget"
  },
  {
    "code": "def get_reservation_resources(session, reservation_id, *models):\n    models_resources = []\n    reservation = session.GetReservationDetails(reservation_id).ReservationDescription\n    for resource in reservation.Resources:\n        if resource.ResourceModelName in models:\n            models_resources.append(resource)\n    return models_resources",
    "docstring": "Get all resources of given models in reservation.\n\n    :param session: CloudShell session\n    :type session: cloudshell.api.cloudshell_api.CloudShellAPISession\n    :param reservation_id: active reservation ID\n    :param models: list of requested models\n    :return: list of all resources of models in reservation"
  },
  {
    "code": "def drop(self):\n        import os\n        if self.path:\n            if os.path.exists(self.path):\n                os.remove(self.path)\n        else:\n            self._data = {}",
    "docstring": "Remove the database by deleting the JSON file."
  },
  {
    "code": "def line_count(fn):\n    with open(fn) as f:\n        for i, l in enumerate(f):\n            pass\n    return i + 1",
    "docstring": "Get line count of file\n\n    Args:\n        fn (str): Path to file\n\n    Return:\n          Number of lines in file (int)"
  },
  {
    "code": "def getFullParList(configObj):\n    plist = []\n    for par in configObj.keys():\n        if isinstance(configObj[par],configobj.Section):\n            plist.extend(getFullParList(configObj[par]))\n        else:\n            plist.append(par)\n    return plist",
    "docstring": "Return a single list of all parameter names included in the configObj\n    regardless of which section the parameter was stored"
  },
  {
    "code": "def replace(self, scaling_group, name, cooldown, min_entities,\n            max_entities, metadata=None):\n        body = self._create_group_config_body(name, cooldown, min_entities,\n                max_entities, metadata=metadata)\n        group_id = utils.get_id(scaling_group)\n        uri = \"/%s/%s/config\" % (self.uri_base, group_id)\n        resp, resp_body = self.api.method_put(uri, body=body)",
    "docstring": "Replace an existing ScalingGroup configuration. All of the attributes\n        must be specified If you wish to delete any of the optional attributes,\n        pass them in as None."
  },
  {
    "code": "def get_additional_handlers():\n    global _additional_handlers\n    if not isinstance(_additional_handlers, list):\n        handlers = []\n        for name in config.ADDITIONAL_HANDLERS:\n            module_name, function_name = name.rsplit('.', 1)\n            function = getattr(import_module(module_name), function_name)\n            handlers.append(function)\n        _additional_handlers = handlers\n    return _additional_handlers",
    "docstring": "Returns the actual functions from the dotted paths specified in ADDITIONAL_HANDLERS."
  },
  {
    "code": "def clean_username(self, username):\n        username_case = settings.CAS_FORCE_CHANGE_USERNAME_CASE\n        if username_case == 'lower':\n            username = username.lower()\n        elif username_case == 'upper':\n            username = username.upper()\n        elif username_case is not None:\n            raise ImproperlyConfigured(\n                \"Invalid value for the CAS_FORCE_CHANGE_USERNAME_CASE setting. \"\n                \"Valid values are `'lower'`, `'upper'`, and `None`.\")\n        return username",
    "docstring": "Performs any cleaning on the \"username\" prior to using it to get or\n        create the user object.  Returns the cleaned username.\n\n        By default, changes the username case according to\n        `settings.CAS_FORCE_CHANGE_USERNAME_CASE`."
  },
  {
    "code": "async def stop(wallet_name: str) -> None:\n        LOGGER.debug('RevRegBuilder.stop >>>')\n        dir_sentinel = join(RevRegBuilder.dir_tails_sentinel(wallet_name))\n        if isdir(dir_sentinel):\n            open(join(dir_sentinel, '.stop'), 'w').close()\n            while any(isfile(join(dir_sentinel, d, '.in-progress')) for d in listdir(dir_sentinel)):\n                await asyncio.sleep(1)\n        LOGGER.debug('RevRegBuilder.stop <<<')",
    "docstring": "Gracefully stop an external revocation registry builder, waiting for its current.\n\n        The indy-sdk toolkit uses a temporary directory for tails file mustration,\n        and shutting down the toolkit removes the directory, crashing the external\n        tails file write. This method allows a graceful stop to wait for completion\n        of such tasks already in progress.\n\n        :wallet_name: name external revocation registry builder to check\n        :return: whether a task is pending."
  },
  {
    "code": "def update(self, custom_field, params={}, **options): \n        path = \"/custom_fields/%s\" % (custom_field)\n        return self.client.put(path, params, **options)",
    "docstring": "A specific, existing custom field can be updated by making a PUT request on the URL for that custom field. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged\n        \n        When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the custom field.\n        \n        A custom field's `type` cannot be updated.\n        \n        An enum custom field's `enum_options` cannot be updated with this endpoint. Instead see \"Work With Enum Options\" for information on how to update `enum_options`.\n        \n        Returns the complete updated custom field record.\n\n        Parameters\n        ----------\n        custom_field : {Id} Globally unique identifier for the custom field.\n        [data] : {Object} Data for the request"
  },
  {
    "code": "def pseudoify(self):\n        assert self.is_toplevel\n        assert self.is_multi\n        assert len(self.multi_rep.siblings) > 0\n        rep = self.multi_rep\n        start = min([s.start for s in rep.siblings + [rep]])\n        end = max([s.end for s in rep.siblings + [rep]])\n        parent = Feature(None)\n        parent._pseudo = True\n        parent._seqid = self._seqid\n        parent.set_coord(start, end)\n        parent._strand = self._strand\n        for sibling in rep.siblings + [rep]:\n            parent.add_child(sibling, rangecheck=True)\n        parent.children = sorted(parent.children)\n        rep.siblings = sorted(rep.siblings)\n        return parent",
    "docstring": "Derive a pseudo-feature parent from the given multi-feature.\n\n        The provided multi-feature does not need to be the representative. The\n        newly created pseudo-feature has the same seqid as the provided multi-\n        feature, and spans its entire range. Otherwise, the pseudo-feature is\n        empty. It is used only for convenience in sorting."
  },
  {
    "code": "def resid_dev(self, endog, mu, scale=1.):\n        r\n        endog_mu = self._clean(endog / mu)\n        return np.sign(endog - mu) * np.sqrt(-2 * (-(endog - mu)/mu +\n                                                   np.log(endog_mu)))",
    "docstring": "r\"\"\"\n        Gamma deviance residuals\n\n        Parameters\n        -----------\n        endog : array-like\n            Endogenous response variable\n        mu : array-like\n            Fitted mean response variable\n        scale : float, optional\n            An optional argument to divide the residuals by scale. The default\n            is 1.\n\n        Returns\n        -------\n        resid_dev : array\n            Deviance residuals as defined below"
  },
  {
    "code": "def register_handler(self, handler):\n        self._handlers[handler.namespace] = handler\n        handler.registered(self)",
    "docstring": "Register a new namespace handler."
  },
  {
    "code": "def from_elements(cls, elts=None):\n        node = cls()\n        if elts is None:\n            node.elts = []\n        else:\n            node.elts = [const_factory(e) if _is_const(e) else e for e in elts]\n        return node",
    "docstring": "Create a node of this type from the given list of elements.\n\n        :param elts: The list of elements that the node should contain.\n        :type elts: list(NodeNG)\n\n        :returns: A new node containing the given elements.\n        :rtype: NodeNG"
  },
  {
    "code": "def process_post_tags(self, bulk_mode, api_post, post_tags):\n        post_tags[api_post[\"ID\"]] = []\n        for api_tag in six.itervalues(api_post[\"tags\"]):\n            tag = self.process_post_tag(bulk_mode, api_tag)\n            if tag:\n                post_tags[api_post[\"ID\"]].append(tag)",
    "docstring": "Create or update Tags related to a post.\n\n        :param bulk_mode: If True, minimize db operations by bulk creating post objects\n        :param api_post: the API data for the post\n        :param post_tags: a mapping of Tags keyed by post ID\n        :return: None"
  },
  {
    "code": "def get_pyquery(self, tree=None, page_numbers=None):\r\n        if not page_numbers:\r\n            page_numbers = []\r\n        if tree is None:\r\n            if not page_numbers and self.tree is not None:\r\n                tree = self.tree\r\n            else:\r\n                tree = self.get_tree(page_numbers)\r\n        if hasattr(tree, 'getroot'):\r\n            tree = tree.getroot()\r\n        return PyQuery(tree, css_translator=PDFQueryTranslator())",
    "docstring": "Wrap given tree in pyquery and return.\r\n            If no tree supplied, will generate one from given page_numbers, or\r\n            all page numbers."
  },
  {
    "code": "def close_position(self, repay_only):\n        params = {'repay_only': repay_only}\n        return self._send_message('post', '/position/close',\n                                  data=json.dumps(params))",
    "docstring": "Close position.\n\n        Args:\n            repay_only (bool): Undocumented by cbpro.\n\n        Returns:\n            Undocumented"
  },
  {
    "code": "def get_slope(self):\n        return ((self.p1.y-self.p2.y) / (self.p1.x-self.p2.x))",
    "docstring": "Return the slope m of this line segment."
  },
  {
    "code": "def tolerant_metaphone_processor(words):\n    for word in words:\n        r = 0\n        for w in double_metaphone(word):\n            if w:\n                w = w.strip()\n                if w:\n                    r += 1\n                    yield w\n        if not r:\n            yield word",
    "docstring": "Double metaphone word processor slightly modified so that when no\nwords are returned by the algorithm, the original word is returned."
  },
  {
    "code": "def RollbackAll(close=None):\n    if close:\n        warnings.simplefilter('default')\n        warnings.warn(\"close parameter will not need at all.\", DeprecationWarning)\n    for k, v in engine_manager.items():\n        session = v.session(create=False)\n        if session:\n            session.rollback()",
    "docstring": "Rollback all transactions, according Local.conn"
  },
  {
    "code": "def initialise(self):\n        self._checkWriteMode()\n        self._createSystemTable()\n        self._createNetworkTables()\n        self._createOntologyTable()\n        self._createReferenceSetTable()\n        self._createReferenceTable()\n        self._createDatasetTable()\n        self._createReadGroupSetTable()\n        self._createReadGroupTable()\n        self._createCallSetTable()\n        self._createVariantSetTable()\n        self._createVariantAnnotationSetTable()\n        self._createFeatureSetTable()\n        self._createContinuousSetTable()\n        self._createBiosampleTable()\n        self._createIndividualTable()\n        self._createPhenotypeAssociationSetTable()\n        self._createRnaQuantificationSetTable()",
    "docstring": "Initialise this data repository, creating any necessary directories\n        and file paths."
  },
  {
    "code": "def parse_attributes(self, attrstring):\n        if attrstring in [None, '', '.']:\n            return dict()\n        attributes = dict()\n        keyvaluepairs = attrstring.split(';')\n        for kvp in keyvaluepairs:\n            if kvp == '':\n                continue\n            key, value = kvp.split('=')\n            if key == 'ID':\n                assert ',' not in value\n                attributes[key] = value\n                continue\n            values = value.split(',')\n            valdict = dict((val, True) for val in values)\n            attributes[key] = valdict\n        return attributes",
    "docstring": "Parse an attribute string.\n\n        Given a string with semicolon-separated key-value pairs, populate a\n        dictionary with the given attributes."
  },
  {
    "code": "def startDataStoreMachine(self, dataStoreItemName, machineName):\n        url = self._url + \"/items/enterpriseDatabases/%s/machines/%s/start\" % (dataStoreItemName, machineName)\n        params = {\n            \"f\": \"json\"\n        }\n        return self._post(url=url, param_dict=params,\n                             securityHandler=self._securityHandler,\n                             proxy_url=self._proxy_url,\n                             proxy_port=self._proxy_port)",
    "docstring": "Starts the database instance running on the Data Store machine.\n\n        Inputs:\n           dataStoreItemName - name of the item to start\n           machineName - name of the machine to start on"
  },
  {
    "code": "def _GetKeyFromRegistry(self):\n    if not self._registry:\n      return\n    try:\n      self._registry_key = self._registry.GetKeyByPath(self._key_path)\n    except RuntimeError:\n      pass\n    if not self._registry_key:\n      return\n    for sub_registry_key in self._registry_key.GetSubkeys():\n      self.AddSubkey(sub_registry_key)\n    if self._key_path == 'HKEY_LOCAL_MACHINE\\\\System':\n      sub_registry_key = VirtualWinRegistryKey(\n          'CurrentControlSet', registry=self._registry)\n      self.AddSubkey(sub_registry_key)\n    self._registry = None",
    "docstring": "Determines the key from the Windows Registry."
  },
  {
    "code": "def debug_ratelimit(g):\n    assert isinstance(g, github.MainClass.Github), type(g)\n    debug(\"github ratelimit: {rl}\".format(rl=g.rate_limiting))",
    "docstring": "Log debug of github ratelimit information from last API call\n\n    Parameters\n    ----------\n    org: github.MainClass.Github\n        github object"
  },
  {
    "code": "def validate_args(self, qubits: Sequence[Qid]) -> None:\n        if len(qubits) == 0:\n            raise ValueError(\n                \"Applied a gate to an empty set of qubits. Gate: {}\".format(\n                    repr(self)))\n        if len(qubits) != self.num_qubits():\n            raise ValueError(\n                'Wrong number of qubits for <{!r}>. '\n                'Expected {} qubits but got <{!r}>.'.format(\n                    self,\n                    self.num_qubits(),\n                    qubits))\n        if any([not isinstance(qubit, Qid)\n                for qubit in qubits]):\n            raise ValueError(\n                    'Gate was called with type different than Qid.')",
    "docstring": "Checks if this gate can be applied to the given qubits.\n\n        By default checks if input is of type Qid and qubit count.\n        Child classes can override.\n\n        Args:\n            qubits: The collection of qubits to potentially apply the gate to.\n\n        Throws:\n            ValueError: The gate can't be applied to the qubits."
  },
  {
    "code": "def _get_transport(self):\n        if self.ssh_proxy:\n            if isinstance(self.ssh_proxy, paramiko.proxy.ProxyCommand):\n                proxy_repr = repr(self.ssh_proxy.cmd[1])\n            else:\n                proxy_repr = repr(self.ssh_proxy)\n            self.logger.debug('Connecting via proxy: {0}'.format(proxy_repr))\n            _socket = self.ssh_proxy\n        else:\n            _socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        if isinstance(_socket, socket.socket):\n            _socket.settimeout(SSH_TIMEOUT)\n            _socket.connect((self.ssh_host, self.ssh_port))\n        transport = paramiko.Transport(_socket)\n        transport.set_keepalive(self.set_keepalive)\n        transport.use_compression(compress=self.compression)\n        transport.daemon = self.daemon_transport\n        return transport",
    "docstring": "Return the SSH transport to the remote gateway"
  },
  {
    "code": "def is_multilingual_project(site_id=None):\n    from parler import appsettings\n    if site_id is None:\n        site_id = getattr(settings, 'SITE_ID', None)\n    return appsettings.PARLER_SHOW_EXCLUDED_LANGUAGE_TABS or site_id in appsettings.PARLER_LANGUAGES",
    "docstring": "Whether the current Django project is configured for multilingual support."
  },
  {
    "code": "def check_int_param(self, param, low, high, name):\n        try:\n            param = int(param)            \n        except:\n            raise ValueError(\n                'Parameter {} is not int or similar'.format(name)\n                )\n        if low != None or high != None:\n            if not low <= param <= high:\n                raise ValueError('Parameter {} is not in range <{}, {}>'\n                    .format(name, low, high))    \n        return param",
    "docstring": "Check if the value of the given parameter is in the given range\n        and an int.\n        Designed for testing parameters like `mu` and `eps`.\n        To pass this function the variable `param` must be able to be converted\n        into a float with a value between `low` and `high`.\n\n        **Args:**\n\n        * `param` : parameter to check (int or similar)\n\n        * `low` : lowest allowed value (int), or None\n\n        * `high` : highest allowed value (int), or None\n\n        * `name` : name of the parameter (string), it is used for an error message\n            \n        **Returns:**\n\n        * `param` : checked parameter converted to float"
  },
  {
    "code": "def make_pilothole_cutter(self):\n        pilothole_radius = self.pilothole_radius\n        if pilothole_radius is None:\n            (inner_radius, outer_radius) = self.get_radii()\n            pilothole_radius = inner_radius + self.pilothole_ratio * (outer_radius - inner_radius)\n        return cadquery.Workplane('XY') \\\n            .circle(pilothole_radius) \\\n            .extrude(self.length)",
    "docstring": "Make a solid to subtract from an interfacing solid to bore a pilot-hole."
  },
  {
    "code": "def _loadcache(cachefile):\n    cache = {}\n    if os.path.exists(cachefile):\n        with open(cachefile) as f:\n            for line in f:\n                line = line.split()\n                if len(line) == 2:\n                    try:\n                        cache[int(line[0])] = float(line[1])\n                    except:\n                        pass\n    return cache",
    "docstring": "Returns a dictionary resulting from reading a likelihood cachefile"
  },
  {
    "code": "def after_submit(analysis):\n    alsoProvides(analysis, ISubmitted)\n    promote_to_dependencies(analysis, \"submit\")\n    if IRequestAnalysis.providedBy(analysis):\n        analysis._reflex_rule_process('submit')\n    ws = analysis.getWorksheet()\n    if ws:\n        doActionFor(ws, 'submit')\n        push_reindex_to_actions_pool(ws)\n    if IRequestAnalysis.providedBy(analysis):\n        doActionFor(analysis.getRequest(), 'submit')\n        reindex_request(analysis)",
    "docstring": "Method triggered after a 'submit' transition for the analysis passed in\n    is performed. Promotes the submit transition to the Worksheet to which the\n    analysis belongs to. Note that for the worksheet there is already a guard\n    that assures the transition to the worksheet will only be performed if all\n    analyses within the worksheet have already been transitioned.\n    This function is called automatically by\n    bika.lims.workfow.AfterTransitionEventHandler"
  },
  {
    "code": "def _run_with_kvm(self, qemu_path, options):\n        if sys.platform.startswith(\"linux\") and self.manager.config.get_section_config(\"Qemu\").getboolean(\"enable_kvm\", True) \\\n                and \"-no-kvm\" not in options:\n            if os.path.basename(qemu_path) not in [\"qemu-system-x86_64\", \"qemu-system-i386\", \"qemu-kvm\"]:\n                return False\n            if not os.path.exists(\"/dev/kvm\"):\n                if self.manager.config.get_section_config(\"Qemu\").getboolean(\"require_kvm\", True):\n                    raise QemuError(\"KVM acceleration cannot be used (/dev/kvm doesn't exist). You can turn off KVM support in the gns3_server.conf by adding enable_kvm = false to the [Qemu] section.\")\n                else:\n                    return False\n            return True\n        return False",
    "docstring": "Check if we could run qemu with KVM\n\n        :param qemu_path: Path to qemu\n        :param options: String of qemu user options\n        :returns: Boolean True if we need to enable KVM"
  },
  {
    "code": "def format_error(err_type, err_value, err_trace=None):\n    if err_trace is None:\n        err_parts = \"\".join(traceback.format_exception_only(err_type, err_value)).strip().split(\": \", 1)\n        if len(err_parts) == 1:\n            err_name, err_msg = err_parts[0], \"\"\n        else:\n            err_name, err_msg = err_parts\n        err_name = err_name.split(\".\")[-1]\n        return err_name + \": \" + err_msg\n    else:\n        return \"\".join(traceback.format_exception(err_type, err_value, err_trace)).strip()",
    "docstring": "Properly formats the specified error."
  },
  {
    "code": "def CRPS(label, pred):\n    for i in range(pred.shape[0]):\n        for j in range(pred.shape[1] - 1):\n            if pred[i, j] > pred[i, j + 1]:\n                pred[i, j + 1] = pred[i, j]\n    return np.sum(np.square(label - pred)) / label.size",
    "docstring": "Custom evaluation metric on CRPS."
  },
  {
    "code": "def to_ip(self):\n        if 'chargeability' in self.data.columns:\n            tdip = reda.TDIP(data=self.data)\n        else:\n            raise Exception('Missing column \"chargeability\"')\n        return tdip",
    "docstring": "Return of copy of the data inside a TDIP container"
  },
  {
    "code": "def set_inputhook(self, callback):\n        ignore_CTRL_C()\n        self._callback = callback\n        self._callback_pyfunctype = self.PYFUNC(callback)\n        pyos_inputhook_ptr = self.get_pyos_inputhook()\n        original = self.get_pyos_inputhook_as_func()\n        pyos_inputhook_ptr.value = \\\n            ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value\n        self._installed = True\n        return original",
    "docstring": "Set PyOS_InputHook to callback and return the previous one."
  },
  {
    "code": "def _get_min_addr(self):\n        if not self._regions:\n            if self.project.arch.name != \"Soot\":\n                l.error(\"self._regions is empty or not properly set.\")\n            return None\n        return next(self._regions.irange())",
    "docstring": "Get the minimum address out of all regions. We assume self._regions is sorted.\n\n        :return: The minimum address.\n        :rtype:  int"
  },
  {
    "code": "def xor_key(first, second, trafaret):\n    trafaret = t.Trafaret._trafaret(trafaret)\n    def check_(value):\n        if (first in value) ^ (second in value):\n            key = first if first in value else second\n            yield first, t.catch_error(trafaret, value[key]), (key,)\n        elif first in value and second in value:\n            yield first, t.DataError(error='correct only if {} is not defined'.format(second)), (first,)\n            yield second, t.DataError(error='correct only if {} is not defined'.format(first)), (second,)\n        else:\n            yield first, t.DataError(error='is required if {} is not defined'.format('second')), (first,)\n            yield second, t.DataError(error='is required if {} is not defined'.format('first')), (second,)\n    return check_",
    "docstring": "xor_key - takes `first` and `second` key names and `trafaret`.\n\n    Checks if we have only `first` or only `second` in data, not both,\n    and at least one.\n\n    Then checks key value against trafaret."
  },
  {
    "code": "def user_id(self):\n        if not has_flask_login:\n            return\n        if not hasattr(current_app, 'login_manager'):\n            return\n        try:\n            is_authenticated = current_user.is_authenticated\n        except AttributeError:\n            return\n        if callable(is_authenticated):\n            is_authenticated = is_authenticated()\n        if not is_authenticated:\n            return\n        return current_user.get_id()",
    "docstring": "Return the ID of the current request's user"
  },
  {
    "code": "def predict_maxprob(self, x, **kwargs):\n        return self.base_estimator_.predict(x.values, **kwargs)",
    "docstring": "Most likely value. Generally equivalent to predict."
  },
  {
    "code": "def get_logger(name, level=None):\n    log = logging.getLogger(\"jb.%s\" % name)\n    if level is not None:\n        log.setLevel(level)\n    return log",
    "docstring": "Return a setup logger for the given name\n\n    :param name: The name for the logger. It is advised to use __name__. The logger name will be prepended by \\\"jb.\\\".\n    :type name: str\n    :param level: the logging level, e.g. logging.DEBUG, logging.INFO etc\n    :type level: int\n    :returns: Logger\n    :rtype: logging.Logger\n    :raises: None\n\n    The logger default level is defined in the constants :data:`jukeboxcore.constants.DEFAULT_LOGGING_LEVEL` but can be overwritten by the environment variable \\\"JUKEBOX_LOG_LEVEL\\\""
  },
  {
    "code": "def update_from_json(self, json_device):\n        self.identifier = json_device['Id']\n        self.license_plate = json_device['EquipmentHeader']['SerialNumber']\n        self.make = json_device['EquipmentHeader']['Make']\n        self.model = json_device['EquipmentHeader']['Model']\n        self.equipment_id = json_device['EquipmentHeader']['EquipmentID']\n        self.active = json_device['EngineRunning']\n        self.odo = json_device['Odometer']\n        self.latitude = json_device['Location']['Latitude']\n        self.longitude = json_device['Location']['Longitude']\n        self.altitude = json_device['Location']['Altitude']\n        self.speed = json_device['Speed']\n        self.last_seen = json_device['Location']['DateTime']",
    "docstring": "Set all attributes based on API response."
  },
  {
    "code": "def get_file_size(self, path):\n        id = self._get_id_for_path(path)\n        blob = self.repository._repo[id]\n        return blob.raw_length()",
    "docstring": "Returns size of the file at given ``path``."
  },
  {
    "code": "def clean_tmpdir(path):\n    if os.path.exists(path) and \\\n       os.path.isdir(path):\n        rmtree(path)",
    "docstring": "Invoked atexit, this removes our tmpdir"
  },
  {
    "code": "def process_dimensions(kdims, vdims):\n    dimensions = {}\n    for group, dims in [('kdims', kdims), ('vdims', vdims)]:\n        if dims is None:\n            continue\n        elif isinstance(dims, (tuple, basestring, Dimension, dict)):\n            dims = [dims]\n        elif not isinstance(dims, list):\n            raise ValueError(\"%s argument expects a Dimension or list of dimensions, \"\n                             \"specified as tuples, strings, dictionaries or Dimension \"\n                             \"instances, not a %s type. Ensure you passed the data as the \"\n                             \"first argument.\" % (group, type(dims).__name__))\n        for dim in dims:\n            if not isinstance(dim, (tuple, basestring, Dimension, dict)):\n                raise ValueError('Dimensions must be defined as a tuple, '\n                                 'string, dictionary or Dimension instance, '\n                                 'found a %s type.' % type(dim).__name__)\n        dimensions[group] = [asdim(d) for d in dims]\n    return dimensions",
    "docstring": "Converts kdims and vdims to Dimension objects.\n\n    Args:\n        kdims: List or single key dimension(s) specified as strings,\n            tuples dicts or Dimension objects.\n        vdims: List or single value dimension(s) specified as strings,\n            tuples dicts or Dimension objects.\n\n    Returns:\n        Dictionary containing kdims and vdims converted to Dimension\n        objects:\n\n        {'kdims': [Dimension('x')], 'vdims': [Dimension('y')]"
  },
  {
    "code": "def example_panel(self, ax, feature):\n        txt = '%s:%s-%s' % (feature.chrom, feature.start, feature.stop)\n        ax.text(0.5, 0.5, txt, transform=ax.transAxes)\n        return feature",
    "docstring": "A example panel that just prints the text of the feature."
  },
  {
    "code": "def propagate(self, *arg, **kw):\n        output = Network.propagate(self, *arg, **kw)\n        if self.interactive:\n            self.updateGraphics()\n        if type(output) == dict:\n            for layerName in output:\n                output[layerName] = [float(x) for x in output[layerName]]\n            return output\n        else:\n            return [float(x) for x in output]",
    "docstring": "Propagates activation through the network."
  },
  {
    "code": "def keys_list(gandi, fqdn):\n    keys = gandi.dns.keys(fqdn)\n    output_keys = ['uuid', 'algorithm', 'algorithm_name', 'ds', 'flags',\n                   'status']\n    for num, key in enumerate(keys):\n        if num:\n            gandi.separator_line()\n        output_generic(gandi, key, output_keys, justify=15)\n    return keys",
    "docstring": "List domain keys."
  },
  {
    "code": "def remove_and_record_multiple_spaces_in_line(line):\n    removed_spaces = {}\n    multispace_matches = re_group_captured_multiple_space.finditer(line)\n    for multispace in multispace_matches:\n        removed_spaces[multispace.start()] = \\\n            (multispace.end() - multispace.start() - 1)\n    line = re_group_captured_multiple_space.sub(u' ', line)\n    return (removed_spaces, line)",
    "docstring": "For a given string, locate all ocurrences of multiple spaces\n       together in the line, record the number of spaces found at each\n       position, and replace them with a single space.\n       @param line: (string) the text line to be processed for multiple\n        spaces.\n       @return: (tuple) countaining a dictionary and a string. The\n        dictionary contains information about the number of spaces removed\n        at given positions in the line. For example, if 3 spaces were\n        removed from the line at index '22', the dictionary would be set\n        as follows: { 22 : 3 }\n        The string that is also returned in this tuple is the line after\n        multiple-space ocurrences have replaced with single spaces."
  },
  {
    "code": "def create_lzma(archive, compression, cmd, verbosity, interactive, filenames):\n    return _create(archive, compression, cmd, 'alone', verbosity, filenames)",
    "docstring": "Create an LZMA archive with the lzma Python module."
  },
  {
    "code": "def spin(self):\n        for x in self.spinchars:\n            self.string = self.msg + \"...\\t\" + x + \"\\r\"\n            self.out.write(self.string.encode('utf-8'))\n            self.out.flush()\n            time.sleep(self.waittime)",
    "docstring": "Perform a single spin"
  },
  {
    "code": "def make_for_loop(loop_body_instrs, else_body_instrs, context):\n    iterator_expr = make_expr(\n        popwhile(not_a(instrs.GET_ITER), loop_body_instrs, side='left')\n    )\n    loop_body_instrs.popleft()\n    top_of_loop = loop_body_instrs.popleft()\n    target = make_assign_target(\n        loop_body_instrs.popleft(),\n        loop_body_instrs,\n        stack=[],\n    )\n    body, orelse_body = make_loop_body_and_orelse(\n        top_of_loop, loop_body_instrs, else_body_instrs, context\n    )\n    return ast.For(\n        target=target,\n        iter=iterator_expr,\n        body=body,\n        orelse=orelse_body,\n    )",
    "docstring": "Make an ast.For node."
  },
  {
    "code": "def call(self, obj, name, method, args, kwargs):\n        if name in self._callback_registry:\n            beforebacks, afterbacks = zip(*self._callback_registry.get(name, []))\n            hold = []\n            for b in beforebacks:\n                if b is not None:\n                    call = Data(name=name, kwargs=kwargs.copy(), args=args)\n                    v = b(obj, call)\n                else:\n                    v = None\n                hold.append(v)\n            out = method(*args, **kwargs)\n            for a, bval in zip(afterbacks, hold):\n                if a is not None:\n                    a(obj, Data(before=bval, name=name, value=out))\n                elif callable(bval):\n                    bval(out)\n            return out\n        else:\n            return method(*args, **kwargs)",
    "docstring": "Trigger a method along with its beforebacks and afterbacks.\n\n        Parameters\n        ----------\n        name: str\n            The name of the method that will be called\n        args: tuple\n            The arguments that will be passed to the base method\n        kwargs: dict\n            The keyword args that will be passed to the base method"
  },
  {
    "code": "def authorization_header(oauth_params):\n        authorization_headers = 'OAuth realm=\"\",'\n        authorization_headers += ','.join(['{0}=\"{1}\"'.format(k, urllib.quote(str(v)))\n            for k, v in oauth_params.items()])\n        return authorization_headers",
    "docstring": "Return Authorization header"
  },
  {
    "code": "def from_two_dim_array(cls, cols, rows, twoDimArray):\n        return Matrix(cols, rows, twoDimArray, rowBased=False, isOneDimArray=False)",
    "docstring": "Create a new Matrix instance from a two dimensional array.\n\n        :param integer columns:     The number of columns for the Matrix.\n        :param integer rows:        The number of rows for the Matrix.\n        :param list twoDimArray:    A two dimensional column based array\n                                    with the values of the matrix.\n        :raise: Raises an :py:exc:`ValueError` if:\n            - columns < 1 or\n            - rows < 1\n            - the size of the parameter does not match with the size of\n              the Matrix."
  },
  {
    "code": "def pexpireat(self, key, timestamp):\n        if not isinstance(timestamp, int):\n            raise TypeError(\"timestamp argument must be int, not {!r}\"\n                            .format(timestamp))\n        fut = self.execute(b'PEXPIREAT', key, timestamp)\n        return wait_convert(fut, bool)",
    "docstring": "Set expire timestamp on key, timestamp in milliseconds.\n\n        :raises TypeError: if timeout is not int"
  },
  {
    "code": "def debug(self, value):\n        self._debug = value\n        if self._debug:\n            logging.getLogger().setLevel(logging.DEBUG)",
    "docstring": "Turn on debug logging if necessary.\n\n        :param value: Value of debug flag"
  },
  {
    "code": "def _destroy(cls, cdata):\n        pp = ffi.new('{} **'.format(cls.LEPTONICA_TYPENAME), cdata)\n        cls.cdata_destroy(pp)",
    "docstring": "Destroy some cdata"
  },
  {
    "code": "def augmented_dickey_fuller(x, param):\n    res = None\n    try:\n        res = adfuller(x)\n    except LinAlgError:\n        res = np.NaN, np.NaN, np.NaN\n    except ValueError:\n        res = np.NaN, np.NaN, np.NaN\n    except MissingDataError:\n        res = np.NaN, np.NaN, np.NaN\n    return [('attr_\"{}\"'.format(config[\"attr\"]),\n                  res[0] if config[\"attr\"] == \"teststat\"\n             else res[1] if config[\"attr\"] == \"pvalue\"\n             else res[2] if config[\"attr\"] == \"usedlag\" else np.NaN)\n            for config in param]",
    "docstring": "The Augmented Dickey-Fuller test is a hypothesis test which checks whether a unit root is present in a time\n    series sample. This feature calculator returns the value of the respective test statistic.\n\n    See the statsmodels implementation for references and more details.\n\n    :param x: the time series to calculate the feature of\n    :type x: numpy.ndarray\n    :param param: contains dictionaries {\"attr\": x} with x str, either \"teststat\", \"pvalue\" or \"usedlag\"\n    :type param: list\n    :return: the value of this feature\n    :return type: float"
  },
  {
    "code": "def move(self, u_function):\n        if self.mesh:\n            self.u = u_function\n            delta = [u_function(p) for p in self.mesh.coordinates()]\n            movedpts = self.mesh.coordinates() + delta\n            self.polydata(False).GetPoints().SetData(numpy_to_vtk(movedpts))\n            self.poly.GetPoints().Modified()\n            self.u_values = delta\n        else:\n            colors.printc(\"Warning: calling move() but actor.mesh is\", self.mesh, c=3)\n        return self",
    "docstring": "Move a mesh by using an external function which prescribes the displacement\n        at any point in space.\n        Useful for manipulating ``dolfin`` meshes."
  },
  {
    "code": "def render_profile_data(self, as_parsed):\n        try:\n            return deep_map(self._render_profile_data, as_parsed)\n        except RecursionException:\n            raise DbtProfileError(\n                'Cycle detected: Profile input has a reference to itself',\n                project=as_parsed\n            )",
    "docstring": "Render the chosen profile entry, as it was parsed."
  },
  {
    "code": "def add_cell_footer(self):\n        logging.info('Adding footer cell')\n        for cell in self.nb['cells']:\n            if cell.cell_type == 'markdown':\n                if 'pynb_footer_tag' in cell.source:\n                    logging.debug('Footer cell already present')\n                    return\n        m =\n        self.add_cell_markdown(\n            m.format(exec_time=self.exec_time, exec_begin=self.exec_begin_dt, class_name=self.__class__.__name__,\n                     argv=str(sys.argv), cells_name=self.cells_name))",
    "docstring": "Add footer cell"
  },
  {
    "code": "def _getDecoratorsName(node):\n    decorators = []\n    if not node.decorators:\n        return decorators\n    for decorator in node.decorators.nodes:\n        decorators.append(decorator.as_string())\n    return decorators",
    "docstring": "Return a list with names of decorators attached to this node.\n\n    @param node: current node of pylint"
  },
  {
    "code": "def complex_randn(*args):\n    return np.random.randn(*args) + 1j*np.random.randn(*args)",
    "docstring": "Return a complex array of samples drawn from a standard normal\n    distribution.\n\n    Parameters\n    ----------\n    d0, d1, ..., dn : int\n      Dimensions of the random array\n\n    Returns\n    -------\n    a : ndarray\n      Random array of shape (d0, d1, ..., dn)"
  },
  {
    "code": "def add_callback(obj, callback, args=()):\n    callbacks = obj._callbacks\n    node = Node(callback, args)\n    if callbacks is None:\n        obj._callbacks = node\n        return node\n    if not isinstance(callbacks, dllist):\n        obj._callbacks = dllist()\n        obj._callbacks.insert(callbacks)\n        callbacks = obj._callbacks\n    callbacks.insert(node)\n    return node",
    "docstring": "Add a callback to an object."
  },
  {
    "code": "def register_token_getter(self, provider):\n        app = oauth.remote_apps[provider]\n        decorator = getattr(app, 'tokengetter')\n        def getter(token=None):\n            return self.token_getter(provider, token)\n        decorator(getter)",
    "docstring": "Register callback to retrieve token from session"
  },
  {
    "code": "def get_property(self, index, doctype, name):\n        return self.indices[index][doctype].properties[name]",
    "docstring": "Returns a property of a given type\n\n        :return a mapped property"
  },
  {
    "code": "def user_entry(entry_int, num_inst, command):\n    valid_entry = False\n    if not entry_int:\n        print(\"{}aborting{} - {} instance\\n\".\n              format(C_ERR, C_NORM, command))\n        sys.exit()\n    elif entry_int >= 1 and entry_int <= num_inst:\n        entry_idx = entry_int - 1\n        valid_entry = True\n    else:\n        print(\"{}Invalid entry:{} enter a number between 1\"\n              \" and {}.\".format(C_ERR, C_NORM, num_inst))\n        entry_idx = entry_int\n    return (entry_idx, valid_entry)",
    "docstring": "Validate user entry and returns index and validity flag.\n\n    Processes the user entry and take the appropriate action: abort\n    if '0' entered, set validity flag and index is valid entry, else\n    return invalid index and the still unset validity flag.\n\n    Args:\n        entry_int (int): a number entered or 999 if a non-int was entered.\n        num_inst (int): the largest valid number that can be entered.\n        command (str): program command to display in prompt.\n    Returns:\n        entry_idx(int): the dictionary index number of the targeted instance\n        valid_entry (bool): specifies if entry_idx is valid.\n    Raises:\n        SystemExit: if the user enters 0 when they are choosing from the\n                    list it triggers the \"abort\" option offered to the user."
  },
  {
    "code": "def uv_to_color(uv, image):\n    if image is None or uv is None:\n        return None\n    uv = np.asanyarray(uv, dtype=np.float64)\n    x = (uv[:, 0] * (image.width - 1))\n    y = ((1 - uv[:, 1]) * (image.height - 1))\n    x = x.round().astype(np.int64) % image.width\n    y = y.round().astype(np.int64) % image.height\n    colors = np.asanyarray(image.convert('RGBA'))[y, x]\n    assert colors.ndim == 2 and colors.shape[1] == 4\n    return colors",
    "docstring": "Get the color in a texture image.\n\n    Parameters\n    -------------\n    uv : (n, 2) float\n      UV coordinates on texture image\n    image : PIL.Image\n      Texture image\n\n    Returns\n    ----------\n    colors : (n, 4) float\n      RGBA color at each of the UV coordinates"
  },
  {
    "code": "def delete_objective_bank(self, objective_bank_id=None):\n        from dlkit.abstract_osid.id.primitives import Id as ABCId\n        if objective_bank_id is None:\n            raise NullArgument()\n        if not isinstance(objective_bank_id, ABCId):\n            raise InvalidArgument('argument type is not an osid Id')\n        try:\n            objective_bank = ObjectiveBankLookupSession(proxy=self._proxy,\n                                                        runtime=self._runtime).get_objective_bank(objective_bank_id)\n        except Exception:\n            raise\n        url_path = construct_url('objective_banks',\n                                 bank_id=objective_bank_id)\n        result = self._delete_request(url_path)\n        return objects.ObjectiveBank(result)",
    "docstring": "Deletes an ObjectiveBank.\n\n        arg:    objectiveBankId (osid.id.Id): the Id of the\n                ObjectiveBank to remove\n        raise:  NotFound - objectiveBankId not found\n        raise:  NullArgument - objectiveBankId is null\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        compliance: mandatory - This method must be implemented."
  },
  {
    "code": "def compile_regex_from_str(self, ft_str):\n        sequence = []\n        for m in re.finditer(r'\\[([^]]+)\\]', ft_str):\n            ft_mask = fts(m.group(1))\n            segs = self.all_segs_matching_fts(ft_mask)\n            sub_pat = '({})'.format('|'.join(segs))\n            sequence.append(sub_pat)\n        pattern = ''.join(sequence)\n        regex = re.compile(pattern)\n        return regex",
    "docstring": "Given a string describing features masks for a sequence of segments,\n        return a regex matching the corresponding strings.\n\n        Args:\n            ft_str (str): feature masks, each enclosed in square brackets, in\n            which the features are delimited by any standard delimiter.\n\n        Returns:\n           Pattern: regular expression pattern equivalent to `ft_str`"
  },
  {
    "code": "def itemgetters(*args):\n    f = itemgetter(*args)\n    def inner(l):\n        return [f(x) for x in l]\n    return inner",
    "docstring": "Get a handful of items from an iterable.\n\n    This is just map(itemgetter(...), iterable) with a list comprehension."
  },
  {
    "code": "def activate(self, user):\n        org_user = self.organization.add_user(user, **self.activation_kwargs())\n        self.invitee = user\n        self.save()\n        return org_user",
    "docstring": "Updates the `invitee` value and saves the instance\n\n        Provided as a way of extending the behavior.\n\n        Args:\n            user: the newly created user\n\n        Returns:\n            the linking organization user"
  },
  {
    "code": "def RestrictFeedItemToAdGroup(client, feed_item, adgroup_id):\n  feed_item_target_service = client.GetService(\n      'FeedItemTargetService', 'v201809')\n  ad_group_target = {\n      'xsi_type': 'FeedItemAdGroupTarget',\n      'feedId': feed_item['feedId'],\n      'feedItemId': feed_item['feedItemId'],\n      'adGroupId': adgroup_id\n  }\n  operation = {'operator': 'ADD', 'operand': ad_group_target}\n  response = feed_item_target_service.mutate([operation])\n  new_ad_group_target = response['value'][0]\n  print('Feed item target for feed ID %s and feed item ID %s was created to '\n        'restrict serving to ad group ID %s' %\n        (new_ad_group_target['feedId'],\n         new_ad_group_target['feedItemId'],\n         new_ad_group_target['adGroupId']))",
    "docstring": "Restricts the feed item to an ad group.\n\n  Args:\n    client: an AdWordsClient instance.\n    feed_item: The feed item.\n    adgroup_id: The ad group ID."
  },
  {
    "code": "def build_transform(self):\n        cfg = self.cfg\n        if cfg.INPUT.TO_BGR255:\n            to_bgr_transform = T.Lambda(lambda x: x * 255)\n        else:\n            to_bgr_transform = T.Lambda(lambda x: x[[2, 1, 0]])\n        normalize_transform = T.Normalize(\n            mean=cfg.INPUT.PIXEL_MEAN, std=cfg.INPUT.PIXEL_STD\n        )\n        transform = T.Compose(\n            [\n                T.ToPILImage(),\n                T.Resize(self.min_image_size),\n                T.ToTensor(),\n                to_bgr_transform,\n                normalize_transform,\n            ]\n        )\n        return transform",
    "docstring": "Creates a basic transformation that was used to train the models"
  },
  {
    "code": "def log_print_request(method, url, query_params=None, headers=None, body=None):\n    log_msg = '\\n>>>>>>>>>>>>>>>>>>>>> Request >>>>>>>>>>>>>>>>>>> \\n'\n    log_msg += '\\t> Method: %s\\n' % method\n    log_msg += '\\t> Url: %s\\n' % url\n    if query_params is not None:\n        log_msg += '\\t> Query params: {}\\n'.format(str(query_params))\n    if headers is not None:\n        log_msg += '\\t> Headers:\\n{}\\n'.format(json.dumps(dict(headers), sort_keys=True, indent=4))\n    if body is not None:\n        try:\n            log_msg += '\\t> Payload sent:\\n{}\\n'.format(_get_pretty_body(headers, body))\n        except:\n            log_msg += \"\\t> Payload could't be formatted\"\n    logger.debug(log_msg)",
    "docstring": "Log an HTTP request data in a user-friendly representation.\n\n    :param method: HTTP method\n    :param url: URL\n    :param query_params: Query parameters in the URL\n    :param headers: Headers (dict)\n    :param body: Body (raw body, string)\n    :return: None"
  },
  {
    "code": "def mkpassword(length=16, chars=None, punctuation=None):\n    if chars is None:\n        chars = string.ascii_letters + string.digits\n    data = [random.choice(chars) for _ in range(length)]\n    if punctuation:\n        data = data[:-punctuation]\n        for _ in range(punctuation):\n            data.append(random.choice(PUNCTUATION))\n        random.shuffle(data)\n    return ''.join(data)",
    "docstring": "Generates a random ascii string - useful to generate authinfos\n\n    :param length: string wanted length\n    :type length: ``int``\n\n    :param chars: character population,\n                  defaults to alphabet (lower & upper) + numbers\n    :type chars: ``str``, ``list``, ``set`` (sequence)\n\n    :param punctuation: number of punctuation signs to include in string\n    :type punctuation: ``int``\n\n    :rtype: ``str``"
  },
  {
    "code": "def stop_global_driver(force=False):\n        address, pid = _read_driver()\n        if address is None:\n            return\n        if not force:\n            try:\n                Client(address=address)\n            except ConnectionError:\n                if pid_exists(pid):\n                    raise\n        try:\n            os.kill(pid, signal.SIGTERM)\n        except OSError as exc:\n            ignore = (errno.ESRCH, errno.EPERM) if force else (errno.ESRCH,)\n            if exc.errno not in ignore:\n                raise\n        try:\n            os.remove(os.path.join(properties.config_dir, 'driver'))\n        except OSError:\n            pass",
    "docstring": "Stops the global driver if running.\n\n        No-op if no global driver is running.\n\n        Parameters\n        ----------\n        force : bool, optional\n            By default skein will check that the process associated with the\n            driver PID is actually a skein driver. Setting ``force`` to\n            ``True`` will kill the process in all cases."
  },
  {
    "code": "def checkIfRemoteIsNewer(self, localfile, remote_size, remote_modify):\n        is_remote_newer = False\n        status = os.stat(localfile)\n        LOG.info(\n            \"\\nLocal file size: %i\"\n            \"\\nLocal Timestamp: %s\",\n            status[ST_SIZE], datetime.fromtimestamp(status.st_mtime))\n        remote_dt = Bgee._convert_ftp_time_to_iso(remote_modify)\n        if remote_dt != datetime.fromtimestamp(status.st_mtime) or \\\n                status[ST_SIZE] != int(remote_size):\n            is_remote_newer = True\n            LOG.info(\n                \"Object on server is has different size %i and/or date %s\",\n                remote_size, remote_dt)\n        return is_remote_newer",
    "docstring": "Overrides checkIfRemoteIsNewer in Source class\n\n        :param localfile: str file path\n        :param remote_size: str bytes\n        :param remote_modify: str last modify date in the form 20160705042714\n        :return: boolean True if remote file is newer else False"
  },
  {
    "code": "def _create_inbound_thread(self):\n        inbound_thread = threading.Thread(target=self._process_incoming_data,\n                                          name=__name__)\n        inbound_thread.daemon = True\n        inbound_thread.start()\n        return inbound_thread",
    "docstring": "Internal Thread that handles all incoming traffic.\n\n        :rtype: threading.Thread"
  },
  {
    "code": "def load(self, format=None, *, kwargs={}):\n        return load(self, format=format, kwargs=kwargs)",
    "docstring": "deserialize object from the file.\n\n        auto detect format by file extension name if `format` is None.\n        for example, `.json` will detect as `json`.\n\n        * raise `FormatNotFoundError` on unknown format.\n        * raise `SerializeError` on any serialize exceptions."
  },
  {
    "code": "def _get_dependencies_from_json(ireq, sources):\n    if os.environ.get(\"PASSA_IGNORE_JSON_API\"):\n        return\n    if ireq.extras:\n        return\n    try:\n        version = get_pinned_version(ireq)\n    except ValueError:\n        return\n    url_prefixes = [\n        proc_url[:-7]\n        for proc_url in (\n            raw_url.rstrip(\"/\")\n            for raw_url in (source.get(\"url\", \"\") for source in sources)\n        )\n        if proc_url.endswith(\"/simple\")\n    ]\n    session = requests.session()\n    for prefix in url_prefixes:\n        url = \"{prefix}/pypi/{name}/{version}/json\".format(\n            prefix=prefix,\n            name=packaging.utils.canonicalize_name(ireq.name),\n            version=version,\n        )\n        try:\n            dependencies = _get_dependencies_from_json_url(url, session)\n            if dependencies is not None:\n                return dependencies\n        except Exception as e:\n            print(\"unable to read dependencies via {0} ({1})\".format(url, e))\n    session.close()\n    return",
    "docstring": "Retrieves dependencies for the install requirement from the JSON API.\n\n    :param ireq: A single InstallRequirement\n    :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`\n    :return: A set of dependency lines for generating new InstallRequirements.\n    :rtype: set(str) or None"
  },
  {
    "code": "def waveform_to_examples(data, sample_rate):\n  import resampy\n  if len(data.shape) > 1:\n    data = np.mean(data, axis=1)\n  if sample_rate != vggish_params.SAMPLE_RATE:\n    data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)\n  log_mel = mel_features.log_mel_spectrogram(\n      data,\n      audio_sample_rate=vggish_params.SAMPLE_RATE,\n      log_offset=vggish_params.LOG_OFFSET,\n      window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS,\n      hop_length_secs=vggish_params.STFT_HOP_LENGTH_SECONDS,\n      num_mel_bins=vggish_params.NUM_MEL_BINS,\n      lower_edge_hertz=vggish_params.MEL_MIN_HZ,\n      upper_edge_hertz=vggish_params.MEL_MAX_HZ)\n  features_sample_rate = 1.0 / vggish_params.STFT_HOP_LENGTH_SECONDS\n  example_window_length = int(round(\n      vggish_params.EXAMPLE_WINDOW_SECONDS * features_sample_rate))\n  example_hop_length = int(round(\n      vggish_params.EXAMPLE_HOP_SECONDS * features_sample_rate))\n  log_mel_examples = mel_features.frame(\n      log_mel,\n      window_length=example_window_length,\n      hop_length=example_hop_length)\n  return log_mel_examples",
    "docstring": "Converts audio waveform into an array of examples for VGGish.\n\n  Args:\n    data: np.array of either one dimension (mono) or two dimensions\n      (multi-channel, with the outer dimension representing channels).\n      Each sample is generally expected to lie in the range [-1.0, +1.0],\n      although this is not required.\n    sample_rate: Sample rate of data.\n\n  Returns:\n    3-D np.array of shape [num_examples, num_frames, num_bands] which represents\n    a sequence of examples, each of which contains a patch of log mel\n    spectrogram, covering num_frames frames of audio and num_bands mel frequency\n    bands, where the frame length is vggish_params.STFT_HOP_LENGTH_SECONDS."
  },
  {
    "code": "def guessoffset(args):\n    p = OptionParser(guessoffset.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(not p.print_help())\n    fastqfile, = args\n    ai = iter_fastq(fastqfile)\n    rec = next(ai)\n    offset = 64\n    while rec:\n        quality = rec.quality\n        lowcounts = len([x for x in quality if x < 59])\n        highcounts = len([x for x in quality if x > 74])\n        diff = highcounts - lowcounts\n        if diff > 10:\n            break\n        elif diff < -10:\n            offset = 33\n            break\n        rec = next(ai)\n    if offset == 33:\n        print(\"Sanger encoding (offset=33)\", file=sys.stderr)\n    elif offset == 64:\n        print(\"Illumina encoding (offset=64)\", file=sys.stderr)\n    return offset",
    "docstring": "%prog guessoffset fastqfile\n\n    Guess the quality offset of the fastqfile, whether 33 or 64.\n    See encoding schemes: <http://en.wikipedia.org/wiki/FASTQ_format>\n\n      SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS...............................\n      ..........................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n      ...............................IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII\n      .................................JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ\n      LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL...............................\n      !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefgh\n      |                         |    |        |                              |\n     33                        59   64       73                            104\n\n     S - Sanger        Phred+33,  raw reads typically (0, 40)\n     X - Solexa        Solexa+64, raw reads typically (-5, 40)\n     I - Illumina 1.3+ Phred+64,  raw reads typically (0, 40)\n     J - Illumina 1.5+ Phred+64,  raw reads typically (3, 40)\n     L - Illumina 1.8+ Phred+33,  raw reads typically (0, 40)\n        with 0=unused, 1=unused, 2=Read Segment Quality Control Indicator (bold)"
  },
  {
    "code": "def _expect_method(self, command):\n        child = pexpect.spawn(self._ipmitool_path, self.args + command)\n        i = child.expect([pexpect.TIMEOUT, 'Password: '], timeout=10)\n        if i == 0:\n            child.terminate()\n            self.error = 'ipmitool command timed out'\n            self.status = 1\n        else:\n            child.sendline(self.password)\n        i = child.expect([pexpect.TIMEOUT, pexpect.EOF], timeout=10)\n        if i == 0:\n            child.terminate()\n            self.error = 'ipmitool command timed out'\n            self.status = 1\n        else:\n            if child.exitstatus:\n                self.error = child.before\n            else:\n                self.output = child.before\n            self.status = child.exitstatus\n            child.close()",
    "docstring": "Use the expect module to execute ipmitool commands\n        and set status"
  },
  {
    "code": "def sel_list_pres(ds_sfc_x):\n    p_min, p_max = ds_sfc_x.sp.min().values, ds_sfc_x.sp.max().values\n    list_pres_level = [\n        '1', '2', '3',\n        '5', '7', '10',\n        '20', '30', '50',\n        '70', '100', '125',\n        '150', '175', '200',\n        '225', '250', '300',\n        '350', '400', '450',\n        '500', '550', '600',\n        '650', '700', '750',\n        '775', '800', '825',\n        '850', '875', '900',\n        '925', '950', '975',\n        '1000',\n    ]\n    ser_pres_level = pd.Series(list_pres_level).map(int)*100\n    pos_lev_max, pos_lev_min = (\n        ser_pres_level[ser_pres_level > p_max].idxmin(),\n        ser_pres_level[ser_pres_level < p_min].idxmax()\n    )\n    list_pres_sel = ser_pres_level.loc[pos_lev_min:pos_lev_max]/100\n    list_pres_sel = list_pres_sel.map(int).map(str).to_list()\n    return list_pres_sel",
    "docstring": "select proper levels for model level data download"
  },
  {
    "code": "def _read_data_type_rpl(self, length):\n        _cmpr = self._read_binary(1)\n        _padr = self._read_binary(1)\n        _resv = self._read_fileng(2)\n        _inti = int(_cmpr[:4], base=2)\n        _inte = int(_cmpr[4:], base=2)\n        _plen = int(_padr[:4], base=2)\n        _ilen = 16 - _inti\n        _elen = 16 - _inte\n        _addr = list()\n        for _ in (((length - 4) - _elen - _plen) // _ilen):\n            _addr.append(ipaddress.ip_address(self._read_fileng(_ilen)))\n        _addr.append(ipaddress.ip_address(self._read_fileng(_elen)))\n        _pads = self._read_fileng(_plen)\n        data = dict(\n            cmpri=_inti,\n            cmpre=_inte,\n            pad=_plen,\n            ip=tuple(_addr),\n        )\n        return data",
    "docstring": "Read IPv6-Route RPL Source data.\n\n        Structure of IPv6-Route RPL Source data [RFC 6554]:\n             0                   1                   2                   3\n             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |  Next Header  |  Hdr Ext Len  | Routing Type  | Segments Left |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            | CmprI | CmprE |  Pad  |               Reserved                |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |                                                               |\n            .                                                               .\n            .                        Addresses[1..n]                        .\n            .                                                               .\n            |                                                               |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n            Octets      Bits        Name                    Description\n              0           0     route.next              Next Header\n              1           8     route.length            Header Extensive Length\n              2          16     route.type              Routing Type\n              3          24     route.seg_left          Segments Left\n              4          32     route.cmpri             CmprI\n              4          36     route.cpmre             CmprE\n              5          40     route.pad               Pad Size\n              5          44     -                       Reserved\n              8          64     route.ip                Addresses"
  },
  {
    "code": "def get_cursor_left_position(self, count=1):\n        if count < 0:\n            return self.get_cursor_right_position(-count)\n        return - min(self.cursor_position_col, count)",
    "docstring": "Relative position for cursor left."
  },
  {
    "code": "def make_annotation(self):\n        annotation = dict()\n        for item in dir(self):\n            if len(item) > 0 and item[0] != '_' and \\\n                    not inspect.ismethod(getattr(self, item)):\n                annotation[item] = getattr(self, item)\n        annotation['action_mentions'] = list()\n        for action_mention in self.action_mentions:\n            annotation_mention = action_mention.make_annotation()\n            annotation['action_mentions'].append(annotation_mention)\n        return annotation",
    "docstring": "Returns a dictionary with all properties of the action\n        and each of its action mentions."
  },
  {
    "code": "def check_url(url):\n        request = urllib2.Request(url)\n        try:\n            response = urlopen(request)\n            return True, response.code\n        except urllib2.HTTPError as e:\n            return False, e.code",
    "docstring": "Check if resource at URL is fetchable. (by trying to fetch it and checking for 200 status.\n\n        Args:\n            url (str): Url to check.\n\n        Returns:\n            Returns a tuple of {True/False, response code}"
  },
  {
    "code": "def _valid_folder(self, base, name):\n        valid = True\n        fullpath = os.path.join(base, name)\n        if (\n            not self.recursive or\n            (\n                self.folder_exclude_check is not None and\n                not self.compare_directory(fullpath[self._base_len:] if self.dir_pathname else name)\n            )\n        ):\n            valid = False\n        if valid and (not self.show_hidden and util.is_hidden(fullpath)):\n            valid = False\n        return self.on_validate_directory(base, name) if valid else valid",
    "docstring": "Return whether a folder can be searched."
  },
  {
    "code": "def intervals_to_boundaries(intervals, q=5):\n    return np.unique(np.ravel(np.round(intervals, decimals=q)))",
    "docstring": "Convert interval times into boundaries.\n\n    Parameters\n    ----------\n    intervals : np.ndarray, shape=(n_events, 2)\n        Array of interval start and end-times\n    q : int\n        Number of decimals to round to. (Default value = 5)\n\n    Returns\n    -------\n    boundaries : np.ndarray\n        Interval boundary times, including the end of the final interval"
  },
  {
    "code": "def hookable(cls):\n    assert isinstance(cls, type)\n    hook_definitions = []\n    if not issubclass(cls, Hookable):\n        for k, v in list(cls.__dict__.items()):\n            if isinstance(v, (ClassHook, InstanceHook)):\n                delattr(cls, k)\n                if v.name is None:\n                    v.name = k\n                hook_definitions.append((k, v))\n    hookable_cls = type(cls.__name__, (cls, Hookable), {})\n    for k, v in hook_definitions:\n        setattr(hookable_cls, k, HookDescriptor(defining_hook=v, defining_class=hookable_cls))\n    return hookable_cls",
    "docstring": "Initialise hookery in a class that declares hooks by decorating it with this decorator.\n\n    This replaces the class with another one which has the same name, but also inherits Hookable\n    which has HookableMeta set as metaclass so that sub-classes of cls will have hook descriptors\n    initialised properly.\n\n    When you say:\n        @hookable\n        class My:\n            before = Hook()\n\n    then @hookable changes My.before to be a HookDescriptor which is then\n    changed into Hook if anyone accesses it.\n\n    There is no need to decorate sub-classes of cls with @hookable."
  },
  {
    "code": "def DomainTokensCreate(self, domain_id, amount):\r\n        if self.__SenseApiCall__('/domains/{0}/tokens.json'.format(domain_id), 'POST', parameters = {\"amount\":amount}):\r\n            return True\r\n        else:\r\n            self.__error__ = \"api call unsuccessful\"\r\n            return False",
    "docstring": "This method creates tokens that can be used by users who want to join the domain. \r\n            Tokens are automatically deleted after usage. \r\n            Only domain managers can create tokens."
  },
  {
    "code": "def _configure_root_logger(self):\n        root_logger = logging.getLogger()\n        root_logger.setLevel(logging.DEBUG)\n        if self.args.verbose:\n            handler = logging.StreamHandler(sys.stdout)\n        else:\n            handler = logging.handlers.RotatingFileHandler(\n                common.LOG_FILE,\n                maxBytes=common.MAX_LOG_SIZE,\n                backupCount=common.MAX_LOG_COUNT\n            )\n            handler.setLevel(logging.INFO)\n        handler.setFormatter(logging.Formatter(common.LOG_FORMAT))\n        root_logger.addHandler(handler)",
    "docstring": "Initialise logging system"
  },
  {
    "code": "def _get_servers_deque(servers, database):\n    key = (servers, database)\n    if key not in _servers_deques:\n        _servers_deques[key] = deque(servers)\n    return _servers_deques[key]",
    "docstring": "Returns deque of servers for given tuple of servers and\n    database name.\n    This deque have active server at the begining, if first server\n    is not accessible at the moment the deque will be rotated,\n    second server will be moved to the first position, thirt to the\n    second position etc, and previously first server will be moved\n    to the last position.\n    This allows to remember last successful server between calls\n    to connect function."
  },
  {
    "code": "def icetea_main():\n    from icetea_lib import IceteaManager\n    manager = IceteaManager.IceteaManager()\n    return_code = manager.run()\n    sys.exit(return_code)",
    "docstring": "Main function for running Icetea. Calls sys.exit with the return code to exit.\n\n    :return: Nothing."
  },
  {
    "code": "def get_sections_2d_nts(self, sortby=None):\n        sections_2d_nts = []\n        for section_name, hdrgos_actual in self.get_sections_2d():\n            hdrgo_nts = self.gosubdag.get_nts(hdrgos_actual, sortby=sortby)\n            sections_2d_nts.append((section_name, hdrgo_nts))\n        return sections_2d_nts",
    "docstring": "Get high GO IDs that are actually used to group current set of GO IDs."
  },
  {
    "code": "def _patch(self, uri, data):\n        headers = self._get_headers()\n        response = self.session.patch(uri, headers=headers,\n                data=json.dumps(data))\n        if response.status_code == 204:\n            return response\n        else:\n            logging.error(response.content)\n            response.raise_for_status()",
    "docstring": "Simple PATCH operation for a given path.\n\n        The body is expected to list operations to perform to update\n        the data.  Operations include:\n            - add\n            - remove\n            - replace\n            - move\n            - copy\n            - test\n\n        [\n             { \"op\": \"test\", \"path\": \"/a/b/c\", \"value\": \"foo\" },\n        ]"
  },
  {
    "code": "def send_http_error(self, http_code, cim_error=None,\n                        cim_error_details=None, headers=None):\n        self.send_response(http_code, http_client.responses.get(http_code, ''))\n        self.send_header(\"CIMExport\", \"MethodResponse\")\n        if cim_error is not None:\n            self.send_header(\"CIMError\", cim_error)\n        if cim_error_details is not None:\n            self.send_header(\"CIMErrorDetails\", cim_error_details)\n        if headers is not None:\n            for header, value in headers:\n                self.send_header(header, value)\n        self.end_headers()\n        self.log('%s: HTTP status %s; CIMError: %s, CIMErrorDetails: %s',\n                 (self._get_log_prefix(), http_code, cim_error,\n                  cim_error_details),\n                 logging.WARNING)",
    "docstring": "Send an HTTP response back to the WBEM server that indicates\n        an error at the HTTP level."
  },
  {
    "code": "def _dump(self, tree):\n        schema = []\n        if tree.tables:\n            for table in tree.tables:\n                desc = self.describe(table, refresh=True, require=True)\n                schema.append(desc.schema)\n        else:\n            for table in self.describe_all():\n                schema.append(table.schema)\n        return \"\\n\\n\".join(schema)",
    "docstring": "Run a DUMP statement"
  },
  {
    "code": "def create_partition(self, org_name, part_name, dci_id, vrf_prof,\n                         service_node_ip=None, desc=None):\n        desc = desc or org_name\n        res = self._create_or_update_partition(org_name, part_name,\n                                               desc, dci_id=dci_id,\n                                               service_node_ip=service_node_ip,\n                                               vrf_prof=vrf_prof)\n        if res and res.status_code in self._resp_ok:\n            LOG.debug(\"Created %s partition in DCNM.\", part_name)\n        else:\n            LOG.error(\"Failed to create %(part)s partition in DCNM.\"\n                      \"Response: %(res)s\", ({'part': part_name, 'res': res}))\n            raise dexc.DfaClientRequestFailed(reason=self._failure_msg(res))",
    "docstring": "Create partition on the DCNM.\n\n        :param org_name: name of organization to be created\n        :param part_name: name of partition to be created\n        :param dci_id: DCI ID\n        :vrf_prof: VRF profile for the partition\n        :param service_node_ip: Specifies the Default route IP address.\n        :param desc: string that describes organization"
  },
  {
    "code": "def fsdecode(path, os_name=os.name, fs_encoding=FS_ENCODING, errors=None):\n    if not isinstance(path, bytes):\n        return path\n    if not errors:\n        use_strict = PY_LEGACY or os_name == 'nt'\n        errors = 'strict' if use_strict else 'surrogateescape'\n    return path.decode(fs_encoding, errors=errors)",
    "docstring": "Decode given path.\n\n    :param path: path will be decoded if using bytes\n    :type path: bytes or str\n    :param os_name: operative system name, defaults to os.name\n    :type os_name: str\n    :param fs_encoding: current filesystem encoding, defaults to autodetected\n    :type fs_encoding: str\n    :return: decoded path\n    :rtype: str"
  },
  {
    "code": "def _general_approximating_model(self, beta, T, Z, R, Q, h_approx):\n        H = np.ones(self.data_length)*h_approx\n        mu = np.zeros(self.data_length)\n        return H, mu",
    "docstring": "Creates simplest kind of approximating Gaussian model\n\n        Parameters\n        ----------\n        beta : np.array\n            Contains untransformed starting values for latent variables\n\n        T, Z, R, Q : np.array\n            State space matrices used in KFS algorithm\n\n        h_approx : float\n            Value to use for the H matrix\n\n        Returns\n        ----------\n\n        H : np.array\n            Approximating measurement variance matrix\n\n        mu : np.array\n            Approximating measurement constants"
  },
  {
    "code": "def histpath(self):\n        from os import path\n        from fortpy import settings\n        return path.join(settings.cache_directory, \"history\")",
    "docstring": "Returns the full path to the console history file."
  },
  {
    "code": "def get_action_cache_key(name, argument):\n    tokens = [str(name)]\n    if argument:\n        tokens.append(str(argument))\n    return '::'.join(tokens)",
    "docstring": "Get an action cache key string."
  },
  {
    "code": "def remove_aliases(self_or_cls, aliases):\n        for k,v in self_or_cls.aliases.items():\n            if v in aliases:\n                self_or_cls.aliases.pop(k)",
    "docstring": "Remove a list of aliases."
  },
  {
    "code": "def ChangeUserStatus(self, Status):\n        if self.CurrentUserStatus.upper() == Status.upper():\n            return\n        self._ChangeUserStatus_Event = threading.Event()\n        self._ChangeUserStatus_Status = Status.upper()\n        self.RegisterEventHandler('UserStatus', self._ChangeUserStatus_UserStatus)\n        self.CurrentUserStatus = Status\n        self._ChangeUserStatus_Event.wait()\n        self.UnregisterEventHandler('UserStatus', self._ChangeUserStatus_UserStatus)\n        del self._ChangeUserStatus_Event, self._ChangeUserStatus_Status",
    "docstring": "Changes the online status for the current user.\n\n        :Parameters:\n          Status : `enums`.cus*\n            New online status for the user.\n\n        :note: This function waits until the online status changes. Alternatively, use the\n               `CurrentUserStatus` property to perform an immediate change of status."
  },
  {
    "code": "def sync_streams(self):\n        if self._sync_streams is None:\n            self._sync_streams = SyncStreamList(self._version, service_sid=self._solution['sid'], )\n        return self._sync_streams",
    "docstring": "Access the sync_streams\n\n        :returns: twilio.rest.sync.v1.service.sync_stream.SyncStreamList\n        :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamList"
  },
  {
    "code": "def prune(self):\n        pruned = []\n        for c in self.children:\n            c.prune()\n            if c.isempty(False):\n                pruned.append(c)\n        for p in pruned:\n            self.children.remove(p)",
    "docstring": "Prune the branch of empty nodes."
  },
  {
    "code": "def energy_ratio_by_chunks(x, param):\n    res_data = []\n    res_index = []\n    full_series_energy = np.sum(x ** 2)\n    for parameter_combination in param:\n        num_segments = parameter_combination[\"num_segments\"]\n        segment_focus = parameter_combination[\"segment_focus\"]\n        assert segment_focus < num_segments\n        assert num_segments > 0\n        res_data.append(np.sum(np.array_split(x, num_segments)[segment_focus] ** 2.0)/full_series_energy)\n        res_index.append(\"num_segments_{}__segment_focus_{}\".format(num_segments, segment_focus))\n    return list(zip(res_index, res_data))",
    "docstring": "Calculates the sum of squares of chunk i out of N chunks expressed as a ratio with the sum of squares over the whole\n    series.\n\n    Takes as input parameters the number num_segments of segments to divide the series into and segment_focus\n    which is the segment number (starting at zero) to return a feature on.\n\n    If the length of the time series is not a multiple of the number of segments, the remaining data points are\n    distributed on the bins starting from the first. For example, if your time series consists of 8 entries, the\n    first two bins will contain 3 and the last two values, e.g. `[ 0.,  1.,  2.], [ 3.,  4.,  5.]` and `[ 6.,  7.]`.\n\n    Note that the answer for `num_segments = 1` is a trivial \"1\" but we handle this scenario\n    in case somebody calls it. Sum of the ratios should be 1.0.\n\n    :param x: the time series to calculate the feature of\n    :type x: numpy.ndarray\n    :param param: contains dictionaries {\"num_segments\": N, \"segment_focus\": i} with N, i both ints\n    :return: the feature values\n    :return type: list of tuples (index, data)"
  },
  {
    "code": "def _handle_heading(self, token):\n        level = token.level\n        self._push()\n        while self._tokens:\n            token = self._tokens.pop()\n            if isinstance(token, tokens.HeadingEnd):\n                title = self._pop()\n                return Heading(title, level)\n            else:\n                self._write(self._handle_token(token))\n        raise ParserError(\"_handle_heading() missed a close token\")",
    "docstring": "Handle a case where a heading is at the head of the tokens."
  },
  {
    "code": "def quantity(*args):\n    if len(args) == 1:\n        if isinstance(args[0], str):\n            return Quantity(from_string(args[0]))\n        elif isinstance(args[0], dict):\n            if hasattr(args[0][\"value\"], \"__len__\"):\n                return QuantVec(from_dict_v(args[0]))\n            else:\n                return Quantity(from_dict(args[0]))\n        elif isinstance(args[0], Quantity) or isinstance(args[0], QuantVec):\n            return args[0]\n        else:\n            raise TypeError(\"Invalid argument type for\")\n    else:\n        if hasattr(args[0], \"__len__\"):\n            return QuantVec(*args)\n        else:\n            return Quantity(*args)",
    "docstring": "Create a quantity. This can be from a scalar or vector.\n\n    Example::\n\n      q1 = quantity(1.0, \"km/s\")\n      q2 = quantity(\"1km/s\")\n      q1 = quantity([1.0,2.0], \"km/s\")"
  },
  {
    "code": "def connect_container_to_network(self, container, net_id,\n                                     ipv4_address=None, ipv6_address=None,\n                                     aliases=None, links=None,\n                                     link_local_ips=None):\n        data = {\n            \"Container\": container,\n            \"EndpointConfig\": self.create_endpoint_config(\n                aliases=aliases, links=links, ipv4_address=ipv4_address,\n                ipv6_address=ipv6_address, link_local_ips=link_local_ips\n            ),\n        }\n        url = self._url(\"/networks/{0}/connect\", net_id)\n        res = self._post_json(url, data=data)\n        self._raise_for_status(res)",
    "docstring": "Connect a container to a network.\n\n        Args:\n            container (str): container-id/name to be connected to the network\n            net_id (str): network id\n            aliases (:py:class:`list`): A list of aliases for this endpoint.\n                Names in that list can be used within the network to reach the\n                container. Defaults to ``None``.\n            links (:py:class:`list`): A list of links for this endpoint.\n                Containers declared in this list will be linked to this\n                container. Defaults to ``None``.\n            ipv4_address (str): The IP address of this container on the\n                network, using the IPv4 protocol. Defaults to ``None``.\n            ipv6_address (str): The IP address of this container on the\n                network, using the IPv6 protocol. Defaults to ``None``.\n            link_local_ips (:py:class:`list`): A list of link-local\n                (IPv4/IPv6) addresses."
  },
  {
    "code": "def _Moran_BV_Matrix_array(variables, w, permutations=0, varnames=None):\n    if varnames is None:\n        varnames = ['x{}'.format(i) for i in range(k)]\n    k = len(variables)\n    rk = list(range(0, k - 1))\n    results = {}\n    for i in rk:\n        for j in range(i + 1, k):\n            y1 = variables[i]\n            y2 = variables[j]\n            results[i, j] = Moran_BV(y1, y2, w, permutations=permutations)\n            results[j, i] = Moran_BV(y2, y1, w, permutations=permutations)\n            results[i, j].varnames = {'x': varnames[i], 'y': varnames[j]}\n            results[j, i].varnames = {'x': varnames[j], 'y': varnames[i]}\n    return results",
    "docstring": "Base calculation for MORAN_BV_Matrix"
  },
  {
    "code": "def isCode(self, block, column):\n        dataObject = block.userData()\n        data = dataObject.data if dataObject is not None else None\n        return self._syntax.isCode(data, column)",
    "docstring": "Check if character at column is a a code"
  },
  {
    "code": "def safe_round(self, x):\n        val = x[self.col_name]\n        if np.isposinf(val):\n            val = sys.maxsize\n        elif np.isneginf(val):\n            val = -sys.maxsize\n        if np.isnan(val):\n            val = self.default_val\n        if self.subtype == 'integer':\n            return int(round(val))\n        return val",
    "docstring": "Returns a converter that takes in a value and turns it into an integer, if necessary.\n\n        Args:\n            col_name(str): Name of the column.\n            subtype(str): Numeric subtype of the values.\n\n        Returns:\n            function"
  },
  {
    "code": "def load_irac_psf(channel, show_progress=False):\n    channel = int(channel)\n    if channel < 1 or channel > 4:\n        raise ValueError('channel must be 1, 2, 3, or 4')\n    fn = 'irac_ch{0}_flight.fits'.format(channel)\n    path = get_path(fn, location='remote', show_progress=show_progress)\n    hdu = fits.open(path)[0]\n    return hdu",
    "docstring": "Load a Spitzer IRAC PSF image.\n\n    Parameters\n    ----------\n    channel : int (1-4)\n        The IRAC channel number:\n\n          * Channel 1:  3.6 microns\n          * Channel 2:  4.5 microns\n          * Channel 3:  5.8 microns\n          * Channel 4:  8.0 microns\n\n    show_progress : bool, optional\n        Whether to display a progress bar during the download (default\n        is `False`).\n\n    Returns\n    -------\n    hdu : `~astropy.io.fits.ImageHDU`\n        The IRAC PSF in a FITS image HDU.\n\n    Examples\n    --------\n    .. plot::\n        :include-source:\n\n        from astropy.visualization import LogStretch, ImageNormalize\n        from photutils.datasets import load_irac_psf\n        hdu1 = load_irac_psf(1)\n        hdu2 = load_irac_psf(2)\n        hdu3 = load_irac_psf(3)\n        hdu4 = load_irac_psf(4)\n\n        norm = ImageNormalize(hdu1.data, stretch=LogStretch())\n\n        fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)\n        ax1.imshow(hdu1.data, origin='lower', interpolation='nearest',\n                   norm=norm)\n        ax1.set_title('IRAC Ch1 PSF')\n        ax2.imshow(hdu2.data, origin='lower', interpolation='nearest',\n                   norm=norm)\n        ax2.set_title('IRAC Ch2 PSF')\n        ax3.imshow(hdu3.data, origin='lower', interpolation='nearest',\n                   norm=norm)\n        ax3.set_title('IRAC Ch3 PSF')\n        ax4.imshow(hdu4.data, origin='lower', interpolation='nearest',\n                   norm=norm)\n        ax4.set_title('IRAC Ch4 PSF')\n        plt.tight_layout()\n        plt.show()"
  },
  {
    "code": "def release(self, forceRelease=False):\n        if not self.held:\n            if forceRelease is False:\n                return False\n            else:\n                self.held = True\n        if not os.path.exists(self.lockPath):\n            self.held = False\n            self.acquiredAt = None\n            return True\n        if forceRelease is False:\n            if self.maxLockAge and time.time() > self.acquiredAt + self.maxLockAge:\n                self.held = False\n                self.acquiredAt = None\n                return False\n        self.acquiredAt = None\n        try:\n            os.rmdir(self.lockPath)\n            self.held = False\n            return True\n        except:\n            self.held = False\n            return False",
    "docstring": "release - Release the lock.\n\n            @param forceRelease <bool> default False - If True, will release the lock even if we don't hold it.\n\n            @return - True if lock is released, otherwise False"
  },
  {
    "code": "def derive_single_object_url_pattern(slug_url_kwarg, path, action):\n    if slug_url_kwarg:\n        return r'^%s/%s/(?P<%s>[^/]+)/$' % (path, action, slug_url_kwarg)\n    else:\n        return r'^%s/%s/(?P<pk>\\d+)/$' % (path, action)",
    "docstring": "Utility function called by class methods for single object views"
  },
  {
    "code": "def python_job(self, function, parameters=None):\n        if not callable(function):\n            raise utils.StimelaCabRuntimeError('Object given as function is not callable')\n        if self.name is None:\n            self.name = function.__name__\n        self.job = {\n                        'function'  :   function,\n                        'parameters':   parameters,\n                   }\n        return 0",
    "docstring": "Run python function\n\n        function    :   Python callable to execute\n        name        :   Name of function (if not given, will used function.__name__)\n        parameters  :   Parameters to parse to function\n        label       :   Function label; for logging purposes"
  },
  {
    "code": "def list_builds(self, field_selector=None, koji_task_id=None, running=None,\n                    labels=None):\n        if running:\n            running_fs = \",\".join([\"status!={status}\".format(status=status.capitalize())\n                                  for status in BUILD_FINISHED_STATES])\n            if not field_selector:\n                field_selector = running_fs\n            else:\n                field_selector = ','.join([field_selector, running_fs])\n        response = self.os.list_builds(field_selector=field_selector,\n                                       koji_task_id=koji_task_id, labels=labels)\n        serialized_response = response.json()\n        build_list = []\n        for build in serialized_response[\"items\"]:\n            build_list.append(BuildResponse(build, self))\n        return build_list",
    "docstring": "List builds with matching fields\n\n        :param field_selector: str, field selector for Builds\n        :param koji_task_id: str, only list builds for Koji Task ID\n        :return: BuildResponse list"
  },
  {
    "code": "def unicode_to_hex(unicode_string):\n    if unicode_string is None:\n        return None\n    acc = []\n    for c in unicode_string:\n        s = hex(ord(c)).replace(\"0x\", \"\").upper()\n        acc.append(\"U+\" + (\"0\" * (4 - len(s))) + s)\n    return u\" \".join(acc)",
    "docstring": "Return a string containing the Unicode hexadecimal codepoint\n    of each Unicode character in the given Unicode string.\n\n    Return ``None`` if ``unicode_string`` is ``None``.\n\n    Example::\n        a  => U+0061\n        ab => U+0061 U+0062\n\n    :param str unicode_string: the Unicode string to convert\n    :rtype: (Unicode) str"
  },
  {
    "code": "def edit_securitygroup(self, group_id, name=None, description=None):\n        successful = False\n        obj = {}\n        if name:\n            obj['name'] = name\n        if description:\n            obj['description'] = description\n        if obj:\n            successful = self.security_group.editObject(obj, id=group_id)\n        return successful",
    "docstring": "Edit security group details.\n\n        :param int group_id: The ID of the security group\n        :param string name: The name of the security group\n        :param string description: The description of the security group"
  },
  {
    "code": "def _charlist(self, data) -> list:\n        char_string =\n        nosub = self.sas.nosub\n        self.sas.nosub = False\n        ll = self.sas.submit(char_string.format(data.libref, data.table + data._dsopts()))\n        self.sas.nosub = nosub\n        l2 = ll['LOG'].partition(\"VARLIST=\\n\")\n        l2 = l2[2].rpartition(\"VARLISTend=\\n\")\n        charlist1 = l2[0].split(\"\\n\")\n        del charlist1[len(charlist1) - 1]\n        charlist1 = [x.casefold() for x in charlist1]\n        return charlist1",
    "docstring": "Private method to return the variables in a SAS Data set that are of type char\n\n        :param data: SAS Data object to process\n        :return: list of character variables\n        :rtype: list"
  },
  {
    "code": "def delete(self):\n        if not self.id:\n            return\n        if not self._loaded:\n            self.reload()\n        return self.http_delete(self.id, etag=self.etag)",
    "docstring": "Deletes the object. Returns without doing anything if the object is\n        new."
  },
  {
    "code": "def generate(env):\n    global PDFLaTeXAction\n    if PDFLaTeXAction is None:\n        PDFLaTeXAction = SCons.Action.Action('$PDFLATEXCOM', '$PDFLATEXCOMSTR')\n    global PDFLaTeXAuxAction\n    if PDFLaTeXAuxAction is None:\n        PDFLaTeXAuxAction = SCons.Action.Action(PDFLaTeXAuxFunction,\n                              strfunction=SCons.Tool.tex.TeXLaTeXStrFunction)\n    env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)\n    from . import pdf\n    pdf.generate(env)\n    bld = env['BUILDERS']['PDF']\n    bld.add_action('.ltx', PDFLaTeXAuxAction)\n    bld.add_action('.latex', PDFLaTeXAuxAction)\n    bld.add_emitter('.ltx', SCons.Tool.tex.tex_pdf_emitter)\n    bld.add_emitter('.latex', SCons.Tool.tex.tex_pdf_emitter)\n    SCons.Tool.tex.generate_common(env)",
    "docstring": "Add Builders and construction variables for pdflatex to an Environment."
  },
  {
    "code": "def _set(self):\n        self.__event.set()\n        if self._complete_func:\n            self.__run_completion_func(self._complete_func, self.id_)",
    "docstring": "Called internally by Client to indicate this request has finished"
  },
  {
    "code": "def from_config(cls, cfg, **kwargs):\n        cfg = dict(cfg, **kwargs)\n        pythonpath = cfg.get('pythonpath', [])\n        if 'here' in cfg:\n            pythonpath.append(cfg['here'])\n        for path in pythonpath:\n            sys.path.append(os.path.expanduser(path))\n        prog = cls.server and 'irc3d' or 'irc3'\n        if cfg.get('debug'):\n            cls.venusian_categories.append(prog + '.debug')\n        if cfg.get('interactive'):\n            import irc3.testing\n            context = getattr(irc3.testing, cls.__name__)(**cfg)\n        else:\n            context = cls(**cfg)\n        if cfg.get('raw'):\n            context.include('irc3.plugins.log',\n                            venusian_categories=[prog + '.debug'])\n        return context",
    "docstring": "return an instance configured with the ``cfg`` dict"
  },
  {
    "code": "def dloglikarray(self):\n        assert self.dparamscurrent, \"dloglikarray requires paramscurrent == True\"\n        nparams = len(self._index_to_param)\n        dloglikarray = scipy.ndarray(shape=(nparams,), dtype='float')\n        for (i, param) in self._index_to_param.items():\n            if isinstance(param, str):\n                dloglikarray[i] = self.dloglik[param]\n            elif isinstance(param, tuple):\n                dloglikarray[i] = self.dloglik[param[0]][param[1]]\n        return dloglikarray",
    "docstring": "Derivative of `loglik` with respect to `paramsarray`."
  },
  {
    "code": "def require_editable(f):\n    def wrapper(self, *args, **kwargs):\n        if not self._edit:\n            raise RegistryKeyNotEditable(\"The key is not set as editable.\")\n        return f(self, *args, **kwargs)\n    return wrapper",
    "docstring": "Makes sure the registry key is editable before trying to edit it."
  },
  {
    "code": "def lookup_hlr(self, phonenumber, params=None):\n        if params is None: params = {}\n        return HLR().load(self.request('lookup/' + str(phonenumber) + '/hlr', 'GET', params))",
    "docstring": "Retrieve the information of a specific HLR lookup."
  },
  {
    "code": "def IsErrorSuppressedByNolint(category, linenum):\n  return (linenum in _error_suppressions.get(category, set()) or\n          linenum in _error_suppressions.get(None, set()))",
    "docstring": "Returns true if the specified error category is suppressed on this line.\n\n  Consults the global error_suppressions map populated by\n  ParseNolintSuppressions/ResetNolintSuppressions.\n\n  Args:\n    category: str, the category of the error.\n    linenum: int, the current line number.\n  Returns:\n    bool, True iff the error should be suppressed due to a NOLINT comment."
  },
  {
    "code": "def markdown(iterable, renderer=HTMLRenderer):\n    with renderer() as renderer:\n        return renderer.render(Document(iterable))",
    "docstring": "Output HTML with default settings.\n    Enables inline and block-level HTML tags."
  },
  {
    "code": "def connect(self):\n        if not getattr(self._local, 'conn', None):\n            try:\n                server = self._servers.get()\n                logger.debug('Connecting to %s', server)\n                self._local.conn = ClientTransport(server, self._framed_transport,\n                    self._timeout, self._recycle)\n            except (Thrift.TException, socket.timeout, socket.error):\n                logger.warning('Connection to %s failed.', server)\n                self._servers.mark_dead(server)\n                return self.connect()\n        return self._local.conn",
    "docstring": "Create new connection unless we already have one."
  },
  {
    "code": "def _EnforceProcessMemoryLimit(self, memory_limit):\n    if resource:\n      if memory_limit is None:\n        memory_limit = 4 * 1024 * 1024 * 1024\n      elif memory_limit == 0:\n        memory_limit = resource.RLIM_INFINITY\n      resource.setrlimit(resource.RLIMIT_DATA, (memory_limit, memory_limit))",
    "docstring": "Enforces a process memory limit.\n\n    Args:\n      memory_limit (int): maximum number of bytes the process is allowed\n          to allocate, where 0 represents no limit and None a default of\n          4 GiB."
  },
  {
    "code": "def _check_array(self, X, **kwargs):\n        if isinstance(X, np.ndarray):\n            X = da.from_array(X, X.shape)\n        X = check_array(X, **kwargs)\n        return X",
    "docstring": "Validate the data arguments X and y.\n\n        By default, NumPy arrays are converted to 1-block dask arrays.\n\n        Parameters\n        ----------\n        X, y : array-like"
  },
  {
    "code": "def astype(self, dtype, copy=True):\n        if not copy and np.dtype(dtype) == self.dtype:\n            return self\n        res = zeros(shape=self.shape, ctx=self.context,\n                    dtype=dtype, stype=self.stype)\n        self.copyto(res)\n        return res",
    "docstring": "Return a copy of the array after casting to a specified type.\n\n        Parameters\n        ----------\n        dtype : numpy.dtype or str\n            The type of the returned array.\n        copy : bool\n            Default `True`. By default, astype always returns a newly\n            allocated ndarray on the same context. If this is set to\n            `False`, and the dtype requested is the same as the ndarray's\n            dtype, the ndarray is returned instead of a copy.\n\n        Examples\n        --------\n        >>> x = mx.nd.sparse.zeros('row_sparse', (2,3), dtype='float32')\n        >>> y = x.astype('int32')\n        >>> y.dtype\n        <type 'numpy.int32'>"
  },
  {
    "code": "def construct_asset_path(self, asset_path, css_path, output_filename, variant=None):\n        public_path = self.absolute_path(asset_path, os.path.dirname(css_path).replace('\\\\', '/'))\n        if self.embeddable(public_path, variant):\n            return \"__EMBED__%s\" % public_path\n        if not posixpath.isabs(asset_path):\n            asset_path = self.relative_path(public_path, output_filename)\n        return asset_path",
    "docstring": "Return a rewritten asset URL for a stylesheet"
  },
  {
    "code": "def URLRabbitmqBroker(url, *, middleware=None):\n    warnings.warn(\n        \"Use RabbitmqBroker with the 'url' parameter instead of URLRabbitmqBroker.\",\n        DeprecationWarning, stacklevel=2,\n    )\n    return RabbitmqBroker(url=url, middleware=middleware)",
    "docstring": "Alias for the RabbitMQ broker that takes a connection URL as a\n    positional argument.\n\n    Parameters:\n      url(str): A connection string.\n      middleware(list[Middleware]): The middleware to add to this\n        broker."
  },
  {
    "code": "def _format_description(ctx):\n    help_string = ctx.command.help or ctx.command.short_help\n    if not help_string:\n        return\n    bar_enabled = False\n    for line in statemachine.string2lines(\n            help_string, tab_width=4, convert_whitespace=True):\n        if line == '\\b':\n            bar_enabled = True\n            continue\n        if line == '':\n            bar_enabled = False\n        line = '| ' + line if bar_enabled else line\n        yield line\n    yield ''",
    "docstring": "Format the description for a given `click.Command`.\n\n    We parse this as reStructuredText, allowing users to embed rich\n    information in their help messages if they so choose."
  },
  {
    "code": "def latrec(radius, longitude, latitude):\n    radius = ctypes.c_double(radius)\n    longitude = ctypes.c_double(longitude)\n    latitude = ctypes.c_double(latitude)\n    rectan = stypes.emptyDoubleVector(3)\n    libspice.latrec_c(radius, longitude, latitude, rectan)\n    return stypes.cVectorToPython(rectan)",
    "docstring": "Convert from latitudinal coordinates to rectangular coordinates.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latrec_c.html\n\n    :param radius: Distance of a point from the origin.\n    :type radius: float\n    :param longitude: Longitude of point in radians.\n    :type longitude: float\n    :param latitude: Latitude of point in radians.\n    :type latitude: float\n    :return: Rectangular coordinates of the point.\n    :rtype: 3-Element Array of floats"
  },
  {
    "code": "def get_choice(prompt, choices):\n    print()\n    checker = []\n    for offset, choice in enumerate(choices):\n        number = offset + 1\n        print(\"\\t{}): '{}'\\n\".format(number, choice))\n        checker.append(str(number))\n    response = get_input(prompt, tuple(checker) + ('',))\n    if not response:\n        print(\"Exiting...\")\n        exit()\n    offset = int(response) - 1\n    selected = choices[offset]\n    return selected",
    "docstring": "Asks for a single choice out of multiple items.\n    Given those items, and a prompt to ask the user with"
  },
  {
    "code": "def _check_download_dir(link, download_dir, hashes):\n    download_path = os.path.join(download_dir, link.filename)\n    if os.path.exists(download_path):\n        logger.info('File was already downloaded %s', download_path)\n        if hashes:\n            try:\n                hashes.check_against_path(download_path)\n            except HashMismatch:\n                logger.warning(\n                    'Previously-downloaded file %s has bad hash. '\n                    'Re-downloading.',\n                    download_path\n                )\n                os.unlink(download_path)\n                return None\n        return download_path\n    return None",
    "docstring": "Check download_dir for previously downloaded file with correct hash\n        If a correct file is found return its path else None"
  },
  {
    "code": "def getOutputElementCount(self, name):\n    if name in [\"activeCells\", \"predictedCells\", \"predictedActiveCells\",\n                \"winnerCells\"]:\n      return self.cellsPerColumn * self.columnCount\n    else:\n      raise Exception(\"Invalid output name specified: %s\" % name)",
    "docstring": "Return the number of elements for the given output."
  },
  {
    "code": "def inspect_node(self, node_id):\n        url = self._url('/nodes/{0}', node_id)\n        return self._result(self._get(url), True)",
    "docstring": "Retrieve low-level information about a swarm node\n\n        Args:\n            node_id (string): ID of the node to be inspected.\n\n        Returns:\n            A dictionary containing data about this node.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def __type_check_attributes(self, node: yaml.Node, mapping: CommentedMap,\n                                argspec: inspect.FullArgSpec) -> None:\n        logger.debug('Checking for extraneous attributes')\n        logger.debug('Constructor arguments: {}, mapping: {}'.format(\n            argspec.args, list(mapping.keys())))\n        for key, value in mapping.items():\n            if not isinstance(key, str):\n                raise RecognitionError(('{}{}YAtiML only supports strings'\n                                        ' for mapping keys').format(\n                                            node.start_mark, os.linesep))\n            if key not in argspec.args and 'yatiml_extra' not in argspec.args:\n                raise RecognitionError(\n                    ('{}{}Found additional attributes'\n                     ' and {} does not support those').format(\n                         node.start_mark, os.linesep, self.class_.__name__))\n            if key in argspec.args and not self.__type_matches(\n                    value, argspec.annotations[key]):\n                raise RecognitionError(('{}{}Expected attribute {} to be of'\n                                        ' type {} but it is a(n) {}').format(\n                                            node.start_mark, os.linesep, key,\n                                            argspec.annotations[key],\n                                            type(value)))",
    "docstring": "Ensure all attributes have a matching constructor argument.\n\n        This checks that there is a constructor argument with a \\\n        matching type for each existing attribute.\n\n        If the class has a yatiml_extra attribute, then extra \\\n        attributes are okay and no error will be raised if they exist.\n\n        Args:\n            node: The node we're processing\n            mapping: The mapping with constructed subobjects\n            constructor_attrs: The attributes of the constructor, \\\n                    including self and yatiml_extra, if applicable"
  },
  {
    "code": "def get_node(self, goid, goobj):\n        return pydot.Node(\n            self.get_node_text(goid, goobj),\n            shape=\"box\",\n            style=\"rounded, filled\",\n            fillcolor=self.go2color.get(goid, \"white\"),\n            color=self.objcolor.get_bordercolor(goid))",
    "docstring": "Return pydot node."
  },
  {
    "code": "def minimum_eigen_vector(x, num_steps, learning_rate, vector_prod_fn):\n  x = tf.nn.l2_normalize(x)\n  for _ in range(num_steps):\n    x = eig_one_step(x, learning_rate, vector_prod_fn)\n  return x",
    "docstring": "Computes eigenvector which corresponds to minimum eigenvalue.\n\n  Args:\n    x: initial value of eigenvector.\n    num_steps: number of optimization steps.\n    learning_rate: learning rate.\n    vector_prod_fn: function which takes x and returns product H*x.\n\n  Returns:\n    approximate value of eigenvector.\n\n  This function finds approximate value of eigenvector of matrix H which\n  corresponds to smallest (by absolute value) eigenvalue of H.\n  It works by solving optimization problem x^{T}*H*x -> min."
  },
  {
    "code": "def show_xticklabels_for_all(self, row_column_list=None):\n        if row_column_list is None:\n            for subplot in self.subplots:\n                subplot.show_xticklabels()\n        else:\n            for row, column in row_column_list:\n                self.show_xticklabels(row, column)",
    "docstring": "Show the x-axis tick labels for all specified subplots.\n\n        :param row_column_list: a list containing (row, column) tuples to\n            specify the subplots, or None to indicate *all* subplots.\n        :type row_column_list: list or None"
  },
  {
    "code": "def walk(self, dirpath):\n        if self.is_ssh(dirpath):\n            self._check_ftp()\n            remotepath = self._get_remote(dirpath)\n            return self._sftp_walk(remotepath)\n        else:\n            return os.walk(dirpath)",
    "docstring": "Performs an os.walk on a local or SSH filepath."
  },
  {
    "code": "def as_view(cls, *class_args, **class_kwargs):\n        def view(*args, **kwargs):\n            self = view.view_class(*class_args, **class_kwargs)\n            return self.dispatch_request(*args, **kwargs)\n        if cls.decorators:\n            view.__module__ = cls.__module__\n            for decorator in cls.decorators:\n                view = decorator(view)\n        view.view_class = cls\n        view.__doc__ = cls.__doc__\n        view.__module__ = cls.__module__\n        view.__name__ = cls.__name__\n        return view",
    "docstring": "Return view function for use with the routing system, that\n        dispatches request to appropriate handler method."
  },
  {
    "code": "def hierarchical_map_vals(func, node, max_depth=None, depth=0):\n    if not hasattr(node, 'items'):\n        return func(node)\n    elif max_depth is not None and depth >= max_depth:\n        return map_dict_vals(func, node)\n    else:\n        keyval_list = [(key, hierarchical_map_vals(func, val, max_depth, depth + 1)) for key, val in node.items()]\n        if isinstance(node, OrderedDict):\n            return OrderedDict(keyval_list)\n        else:\n            return dict(keyval_list)",
    "docstring": "node is a dict tree like structure with leaves of type list\n\n    TODO: move to util_dict\n\n    CommandLine:\n        python -m utool.util_dict --exec-hierarchical_map_vals\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_dict import *  # NOQA\n        >>> import utool as ut\n        >>> item_list     = [1, 2, 3, 4, 5, 6, 7, 8]\n        >>> groupids_list = [[1, 2, 1, 2, 1, 2, 1, 2], [3, 2, 2, 2, 3, 1, 1, 1]]\n        >>> tree = ut.hierarchical_group_items(item_list, groupids_list)\n        >>> len_tree = ut.hierarchical_map_vals(len, tree)\n        >>> result = ('len_tree = ' + ut.repr4(len_tree, nl=1))\n        >>> print(result)\n        len_tree = {\n            1: {1: 1, 2: 1, 3: 2},\n            2: {1: 2, 2: 2},\n        }\n\n    Example1:\n        >>> # DISABLE_DOCTEST\n        >>> # UNSTABLE_DOCTEST\n        >>> from utool.util_dict import *  # NOQA\n        >>> import utool as ut\n        >>> depth = 4\n        >>> item_list = list(range(2 ** (depth + 1)))\n        >>> num = len(item_list) // 2\n        >>> groupids_list = []\n        >>> total = 0\n        >>> for level in range(depth):\n        ...     num2 = len(item_list) // int((num * 2))\n        ...     #nonflat_levelids = [([total + 2 * x + 1] * num + [total + 2 * x + 2] * num) for x in range(num2)]\n        ...     nonflat_levelids = [([1] * num + [2] * num) for x in range(num2)]\n        ...     levelids = ut.flatten(nonflat_levelids)\n        ...     groupids_list.append(levelids)\n        ...     total += num2 * 2\n        ...     num //= 2\n        >>> print('groupids_list = %s' % (ut.repr4(groupids_list, nl=1),))\n        >>> print('depth = %r' % (len(groupids_list),))\n        >>> tree = ut.hierarchical_group_items(item_list, groupids_list)\n        >>> print('tree = ' + ut.repr4(tree, nl=None))\n        >>> flat_tree_values = list(ut.iflatten_dict_values(tree))\n        >>> assert sorted(flat_tree_values) == sorted(item_list)\n        >>> print('flat_tree_values = ' + str(flat_tree_values))\n        >>> #print('flat_tree_keys = ' + str(list(ut.iflatten_dict_keys(tree))))\n        >>> #print('iflatten_dict_items = ' + str(list(ut.iflatten_dict_items(tree))))\n        >>> len_tree = ut.hierarchical_map_vals(len, tree, max_depth=4)\n        >>> result = ('len_tree = ' + ut.repr4(len_tree, nl=None))\n        >>> print(result)"
  },
  {
    "code": "def log(self, level, msg):\n        self._check_session()\n        level = level.upper()\n        allowed_levels = ('INFO', 'WARN', 'ERROR', 'FATAL')\n        if level not in allowed_levels:\n            raise ValueError('level must be one of: ' +\n                             ', '.join(allowed_levels))\n        self._rest.post_request(\n            'log', None, {'log_level': level.upper(), 'message': msg})",
    "docstring": "Write a diagnostic message to a log file or to standard output.\n\n        Arguments:\n        level -- Severity level of entry.  One of: INFO, WARN, ERROR, FATAL.\n        msg   -- Message to write to log."
  },
  {
    "code": "def get_rmse(self, data_x=None, data_y=None):\n        if data_x is None:\n            data_x = np.array(self.args[\"x\"])\n        if data_y is None:\n            data_y = np.array(self.args[\"y\"])\n        if len(data_x) != len(data_y):\n            raise ValueError(\"Lengths of data_x and data_y are different\")\n        rmse_y = self.bestfit_func(data_x)\n        return np.sqrt(np.mean((rmse_y - data_y) ** 2))",
    "docstring": "Get Root Mean Square Error using\n        self.bestfit_func\n\n        args:\n            x_min: scalar, default=min(x)\n                minimum x value of the line\n            x_max: scalar, default=max(x)\n                maximum x value of the line\n            resolution: int, default=1000\n                how many steps between x_min and x_max"
  },
  {
    "code": "def notify(self, n: int = 1) -> None:\n        waiters = []\n        while n and self._waiters:\n            waiter = self._waiters.popleft()\n            if not waiter.done():\n                n -= 1\n                waiters.append(waiter)\n        for waiter in waiters:\n            future_set_result_unless_cancelled(waiter, True)",
    "docstring": "Wake ``n`` waiters."
  },
  {
    "code": "def loading(self):\n        if getattr(self, '_initialized', False):\n            raise ValueError(\"Already loading\")\n        self._initialized = False\n        yield\n        self._initialized = True",
    "docstring": "Context manager for when you need to instantiate entities upon unpacking"
  },
  {
    "code": "def argmin(self, axis=None, skipna=True):\n        nv.validate_minmax_axis(axis)\n        return nanops.nanargmin(self._values, skipna=skipna)",
    "docstring": "Return a ndarray of the minimum argument indexer.\n\n        Parameters\n        ----------\n        axis : {None}\n            Dummy argument for consistency with Series\n        skipna : bool, default True\n\n        Returns\n        -------\n        numpy.ndarray\n\n        See Also\n        --------\n        numpy.ndarray.argmin"
  },
  {
    "code": "def parse_result(cls, result):\n        if len(result) == 3:\n            items, count, context = result\n        else:\n            context = {}\n            items, count = result\n        return items, count, context",
    "docstring": "Parse an items + count tuple result.\n\n        May either be three item tuple containing items, count, and a context dictionary (see: relation convention)\n        or a two item tuple containing only items and count."
  },
  {
    "code": "def __get_request_auth(username, password):\n    def __request_auth(credentials, user_data):\n        for credential in credentials:\n            if credential[0] == libvirt.VIR_CRED_AUTHNAME:\n                credential[4] = username if username else \\\n                                __salt__['config.get']('virt:connection:auth:username', credential[3])\n            elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT:\n                credential[4] = password if password else \\\n                                __salt__['config.get']('virt:connection:auth:password', credential[3])\n            else:\n                log.info('Unhandled credential type: %s', credential[0])\n        return 0",
    "docstring": "Get libvirt.openAuth callback with username, password values overriding\n    the configuration ones."
  },
  {
    "code": "def run(self):\n        notice('Starting output thread', self.color)\n        o = Thread(target=self.__output_thread, name='output')\n        o.start()\n        self.threads.append(o)\n        try:\n            notice('Starting input thread', self.color)\n            self.__input_thread()\n        except KeyboardInterrupt:\n            self.__shutdown()",
    "docstring": "Run self on provided screen"
  },
  {
    "code": "def isPeregrine(ID, sign, lon):\n    info = getInfo(sign, lon)\n    for dign, objID in info.items():\n        if dign not in ['exile', 'fall'] and ID == objID:\n            return False\n    return True",
    "docstring": "Returns if an object is peregrine\n    on a sign and longitude."
  },
  {
    "code": "async def _wait_for_data(self, current_command, number_of_bytes):\n        while number_of_bytes:\n            next_command_byte = await self.read()\n            current_command.append(next_command_byte)\n            number_of_bytes -= 1\n        return current_command",
    "docstring": "This is a private utility method.\n        This method accumulates the requested number of bytes and\n        then returns the full command\n\n        :param current_command:  command id\n\n        :param number_of_bytes:  how many bytes to wait for\n\n        :returns: command"
  },
  {
    "code": "def backup_list(self, query, detail):\n        import csv\n        from wal_e.storage.base import BackupInfo\n        bl = self._backup_list(detail)\n        if query is None:\n            bl_iter = bl\n        else:\n            bl_iter = bl.find_all(query)\n        w_csv = csv.writer(sys.stdout, dialect='excel-tab')\n        w_csv.writerow(BackupInfo._fields)\n        for bi in bl_iter:\n            w_csv.writerow([getattr(bi, k) for k in BackupInfo._fields])\n        sys.stdout.flush()",
    "docstring": "Lists base backups and basic information about them"
  },
  {
    "code": "def recurse_up(directory, filename):\n\tdirectory = osp.abspath(directory)\n\twhile True:\n\t\tsearchfile = osp.join(directory, filename)\n\t\tif osp.isfile(searchfile):\n\t\t\treturn directory\n\t\tif directory == '/': break\n\t\telse: directory = osp.dirname(directory)\n\treturn False",
    "docstring": "Recursive walk a directory up to root until it contains `filename`"
  },
  {
    "code": "def _prepareSObjects(sObjects):\n    sObjectsCopy = copy.deepcopy(sObjects)\n    if isinstance(sObjectsCopy, dict):\n        _doPrep(sObjectsCopy)\n    else:\n        for listitems in sObjectsCopy:\n            _doPrep(listitems)\n    return sObjectsCopy",
    "docstring": "Prepare a SObject"
  },
  {
    "code": "def apply_mapping(raw_row, mapping):\n    row = {target: mapping_func(raw_row[source_key])\n           for target, (mapping_func, source_key)\n           in mapping.fget().items()}\n    return row",
    "docstring": "Override this to hand craft conversion of row."
  },
  {
    "code": "def validate(self, metadata, path, value):\n        if isinstance(value, Requirement):\n            if metadata.testing and self.mock_value is not None:\n                value = self.mock_value\n            elif self.default_value is not None:\n                value = self.default_value\n            elif not value.required:\n                return None\n            else:\n                raise ValidationError(f\"Missing required configuration for: {'.'.join(path)}\")\n        try:\n            return self.type(value)\n        except ValueError:\n            raise ValidationError(f\"Missing required configuration for: {'.'.join(path)}: {value}\")",
    "docstring": "Validate this requirement."
  },
  {
    "code": "def to_cloudformation(self, **kwargs):\n        function = kwargs.get('function')\n        if not function:\n            raise TypeError(\"Missing required keyword argument: function\")\n        source_arn = self.get_source_arn()\n        permission = self._construct_permission(function, source_arn=source_arn)\n        subscription_filter = self.get_subscription_filter(function, permission)\n        resources = [permission, subscription_filter]\n        return resources",
    "docstring": "Returns the CloudWatch Logs Subscription Filter and Lambda Permission to which this CloudWatch Logs event source\n        corresponds.\n\n        :param dict kwargs: no existing resources need to be modified\n        :returns: a list of vanilla CloudFormation Resources, to which this push event expands\n        :rtype: list"
  },
  {
    "code": "def standard_exc_info(self):\n        tb = self.frames[0]\n        if type(tb) is not TracebackType:\n            tb = tb.tb\n        return self.exc_type, self.exc_value, tb",
    "docstring": "Standard python exc_info for re-raising"
  },
  {
    "code": "def update(self, other):\n        for new in other.values():\n            new_key = new.__class__.__name__\n            for child in new.__class__.mro()[1:-2]:\n                child_key = child.__name__\n                try:\n                    self[child_key].merge(new)\n                except KeyError:\n                    pass\n                except ValueError:\n                    del self[child_key]\n            try:\n                self[new_key].merge(new)\n            except (KeyError, ValueError):\n                self[new_key] = new",
    "docstring": "Update themeables with those from `other`\n\n        This method takes care of inserting the `themeable`\n        into the underlying dictionary. Before doing the\n        insertion, any existing themeables that will be\n        affected by a new from `other` will either be merged\n        or removed. This makes sure that a general themeable\n        of type :class:`text` can be added to override an\n        existing specific one of type :class:`axis_text_x`."
  },
  {
    "code": "def lazy(func):\n    try:\n        frame = sys._getframe(1)\n    except Exception:\n        _locals = None\n    else:\n        _locals = frame.f_locals\n    func_name = func.func_name if six.PY2 else func.__name__\n    return LazyStub(func_name, func, _locals)",
    "docstring": "Decorator, which can be used for lazy imports\n\n            @lazy\n            def yaml():\n                import yaml\n                return yaml"
  },
  {
    "code": "def clear_search_defaults(self, args=None):\n        if args is None:\n            self._search_defaults.clear()\n        else:\n            for arg in args:\n                if arg in self._search_defaults:\n                    del self._search_defaults[arg]",
    "docstring": "Clear all search defaults specified by the list of parameter names\n        given as ``args``.  If ``args`` is not given, then clear all existing\n        search defaults.\n\n        Examples::\n\n            conn.set_search_defaults(scope=ldap.SCOPE_BASE, attrs=['cn'])\n            conn.clear_search_defaults(['scope'])\n            conn.clear_search_defaults()"
  },
  {
    "code": "def freeze_extensions(self):\n        output_path = os.path.join(_registry_folder(), 'frozen_extensions.json')\n        with open(output_path, \"w\") as outfile:\n            json.dump(self._dump_extensions(), outfile)",
    "docstring": "Freeze the set of extensions into a single file.\n\n        Freezing extensions can speed up the extension loading process on\n        machines with slow file systems since it requires only a single file\n        to store all of the extensions.\n\n        Calling this method will save a file into the current virtual\n        environment that stores a list of all currently found extensions that\n        have been installed as entry_points.  Future calls to\n        `load_extensions` will only search the one single file containing\n        frozen extensions rather than enumerating all installed distributions."
  },
  {
    "code": "def input_password(self, locator, text):\r\n        self._info(\"Typing password into text field '%s'\" % locator)\r\n        self._element_input_text_by_locator(locator, text)",
    "docstring": "Types the given password into text field identified by `locator`.\r\n\r\n        Difference between this keyword and `Input Text` is that this keyword\r\n        does not log the given password. See `introduction` for details about\r\n        locating elements."
  },
  {
    "code": "def build_doctype(qualifiedName, publicId=None, systemId=None, internalSubset=None):\n    doctype = ElifeDocumentType(qualifiedName)\n    doctype._identified_mixin_init(publicId, systemId)\n    if internalSubset:\n        doctype.internalSubset = internalSubset\n    return doctype",
    "docstring": "Instantiate an ElifeDocumentType, a subclass of minidom.DocumentType, with\n    some properties so it is more testable"
  },
  {
    "code": "def load_repo(client, path=None, index='git'):\n    path = dirname(dirname(abspath(__file__))) if path is None else path\n    repo_name = basename(path)\n    repo = git.Repo(path)\n    create_git_index(client, index)\n    for ok, result in streaming_bulk(\n            client,\n            parse_commits(repo.refs.master.commit, repo_name),\n            index=index,\n            doc_type='doc',\n            chunk_size=50\n        ):\n        action, result = result.popitem()\n        doc_id = '/%s/doc/%s' % (index, result['_id'])\n        if not ok:\n            print('Failed to %s document %s: %r' % (action, doc_id, result))\n        else:\n            print(doc_id)",
    "docstring": "Parse a git repository with all it's commits and load it into elasticsearch\n    using `client`. If the index doesn't exist it will be created."
  },
  {
    "code": "def clear(self):\n        self.sam |= KEY_WRITE\n        for v in list(self.values()):\n            del self[v.name]\n        for k in list(self.subkeys()):\n            self.del_subkey(k.name)",
    "docstring": "Remove all subkeys and values from this key."
  },
  {
    "code": "def show_menu(title, options, default=None, height=None, width=None, multiselect=False, precolored=False):\n    plugins = [FilterPlugin()]\n    if any(isinstance(opt, OptionGroup) for opt in options):\n        plugins.append(OptionGroupPlugin())\n    if title:\n        plugins.append(TitlePlugin(title))\n    if precolored:\n        plugins.append(PrecoloredPlugin())\n    menu = Termenu(options, default=default, height=height,\n                   width=width, multiselect=multiselect, plugins=plugins)\n    return menu.show()",
    "docstring": "Shows an interactive menu in the terminal.\n\n    Arguments:\n        options: list of menu options\n        default: initial option to highlight\n        height: maximum height of the menu\n        width: maximum width of the menu\n        multiselect: allow multiple items to be selected?\n        precolored: allow strings with embedded ANSI commands\n\n    Returns:\n        * If multiselect is True, returns a list of selected options.\n        * If mutliselect is False, returns the selected option.\n        * If an option is a 2-tuple, the first item will be displayed and the\n          second item will be returned.\n        * If menu is cancelled (Esc pressed), returns None.\n        *\n    Notes:\n        * You can pass OptionGroup objects to `options` to create sub-headers\n          in the menu."
  },
  {
    "code": "def prepare_xml(args, parser):\n    if args.source == constants.TEI_SOURCE_CBETA_GITHUB:\n        corpus_class = tacl.TEICorpusCBETAGitHub\n    else:\n        raise Exception('Unsupported TEI source option provided')\n    corpus = corpus_class(args.input, args.output)\n    corpus.tidy()",
    "docstring": "Prepares XML files for stripping.\n\n    This process creates a single, normalised TEI XML file for each\n    work."
  },
  {
    "code": "def from_dict(cls, d):\n        return IonEntry(Ion.from_dict(d[\"ion\"]), d[\"energy\"], d.get(\"name\", None))",
    "docstring": "Returns an IonEntry object from a dict."
  },
  {
    "code": "def _PrintDictAsTable(self, src_dict):\n    key_list = list(src_dict.keys())\n    key_list.sort()\n    print('|', end='')\n    for key in key_list:\n      print(' {0:s} |'.format(key), end='')\n    print('')\n    print('|', end='')\n    for key in key_list:\n      print(' :---: |', end='')\n    print('')\n    print('|', end='')\n    for key in key_list:\n      print(' {0!s} |'.format(src_dict[key]), end='')\n    print('\\n')",
    "docstring": "Prints a table of artifact definitions.\n\n    Args:\n      src_dict (dict[str, ArtifactDefinition]): artifact definitions by name."
  },
  {
    "code": "def _configure_logger_for_production(logger):\n    stderr_handler = logging.StreamHandler(sys.stderr)\n    stderr_handler.setLevel(logging.INFO)\n    if 'STDERR' in app.config:\n        logger.addHandler(stderr_handler)\n    file_handler = logging.handlers.RotatingFileHandler(\n        app.config.get('LOG_FILE'), maxBytes=67108864, backupCount=5)\n    file_handler.setLevel(logging.INFO)\n    if 'LOG_FILE' in app.config:\n        logger.addHandler(file_handler)\n    mail_handler = logging.handlers.SMTPHandler(\n        '127.0.0.1',\n        app.config.get('FROM_EMAIL'),\n        app.config.get('ADMINS', []),\n        'CKAN Service Error')\n    mail_handler.setLevel(logging.ERROR)\n    if 'FROM_EMAIL' in app.config:\n        logger.addHandler(mail_handler)",
    "docstring": "Configure the given logger for production deployment.\n\n    Logs to stderr and file, and emails errors to admins."
  },
  {
    "code": "def jit_load(self):\n        try:\n            model = importlib.import_module('.' + self.model, 'andes.models')\n            device = getattr(model, self.device)\n            self.system.__dict__[self.name] = device(self.system, self.name)\n            g = self.system.__dict__[self.name]._group\n            self.system.group_add(g)\n            self.system.__dict__[g].register_model(self.name)\n            self.system.devman.register_device(self.name)\n            self.loaded = 1\n            logger.debug('Imported model <{:s}.{:s}>.'.format(\n                self.model, self.device))\n        except ImportError:\n            logger.error(\n                'non-JIT model <{:s}.{:s}> import error'\n                .format(self.model, self.device))\n        except AttributeError:\n            logger.error(\n                'model <{:s}.{:s}> not exist. Check models/__init__.py'\n                .format(self.model, self.device))",
    "docstring": "Import and instantiate this JIT object\n\n        Returns\n        -------"
  },
  {
    "code": "def _read_mode_tr(self, size, kind):\n        if size != 12:\n            raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')\n        _idnm = self._read_unpack(2)\n        _ohcn = self._read_unpack(2)\n        _rhcn = self._read_unpack(2)\n        _ipad = self._read_ipv4_addr()\n        data = dict(\n            kind=kind,\n            type=self._read_opt_type(kind),\n            length=size,\n            id=_idnm,\n            ohc=_ohcn,\n            rhc=_rhcn,\n            ip=_ipad,\n        )\n        return data",
    "docstring": "Read Traceroute option.\n\n        Positional arguments:\n            size - int, length of option\n            kind - int, 82 (TR)\n\n        Returns:\n            * dict -- extracted Traceroute (TR) option\n\n        Structure of Traceroute (TR) option [RFC 1393][RFC 6814]:\n             0               8              16              24\n            +-+-+-+-+-+-+-+-+---------------+---------------+---------------+\n            |F| C |  Number |    Length     |          ID Number            |\n            +-+-+-+-+-+-+-+-+---------------+---------------+---------------+\n            |      Outbound Hop Count       |       Return Hop Count        |\n            +---------------+---------------+---------------+---------------+\n            |                     Originator IP Address                     |\n            +---------------+---------------+---------------+---------------+\n\n            Octets      Bits        Name                    Description\n              0           0     ip.tr.kind              Kind (82)\n              0           0     ip.tr.type.copy         Copied Flag (0)\n              0           1     ip.tr.type.class        Option Class (0)\n              0           3     ip.tr.type.number       Option Number (18)\n              1           8     ip.tr.length            Length (12)\n              2          16     ip.tr.id                ID Number\n              4          32     ip.tr.ohc               Outbound Hop Count\n              6          48     ip.tr.rhc               Return Hop Count\n              8          64     ip.tr.ip                Originator IP Address"
  },
  {
    "code": "def get_points_within_r(center_points, target_points, r):\n    r\n    tree = cKDTree(target_points)\n    indices = tree.query_ball_point(center_points, r)\n    return tree.data[indices].T",
    "docstring": "r\"\"\"Get all target_points within a specified radius of a center point.\n\n    All data must be in same coordinate system, or you will get undetermined results.\n\n    Parameters\n    ----------\n    center_points: (X, Y) ndarray\n        location from which to grab surrounding points within r\n    target_points: (X, Y) ndarray\n        points from which to return if they are within r of center_points\n    r: integer\n        search radius around center_points to grab target_points\n\n    Returns\n    -------\n    matches: (X, Y) ndarray\n        A list of points within r distance of, and in the same\n        order as, center_points"
  },
  {
    "code": "def get(cls, action, suffix=None):\n        action_id = _action_id(action, suffix)\n        if action_id not in cls._HANDLERS:\n            if LOG_OPTS['register']:\n                hookenv.log('Registering reactive handler for %s' % _short_action_id(action, suffix),\n                            level=hookenv.DEBUG)\n            cls._HANDLERS[action_id] = cls(action, suffix)\n        return cls._HANDLERS[action_id]",
    "docstring": "Get or register a handler for the given action.\n\n        :param func action: Callback that is called when invoking the Handler\n        :param func suffix: Optional suffix for the handler's ID"
  },
  {
    "code": "def get_constraint(self, twig=None, **kwargs):\n        if twig is not None:\n            kwargs['twig'] = twig\n        kwargs['context'] = 'constraint'\n        return self.get(**kwargs)",
    "docstring": "Filter in the 'constraint' context\n\n        :parameter str constraint: name of the constraint (optional)\n        :parameter **kwargs: any other tags to do the filter\n            (except constraint or context)\n        :return: :class:`phoebe.parameters.parameters.ParameterSet`"
  },
  {
    "code": "def exportUsufy(data, ext, fileH):\n    if ext == \"csv\":\n        usufyToCsvExport(data, fileH+\".\"+ext)\n    elif ext == \"gml\":\n        usufyToGmlExport(data, fileH+\".\"+ext)\n    elif ext == \"json\":\n        usufyToJsonExport(data, fileH+\".\"+ext)\n    elif ext == \"ods\":\n        usufyToOdsExport(data, fileH+\".\"+ext)\n    elif ext == \"png\":\n        usufyToPngExport(data, fileH+\".\"+ext)\n    elif ext == \"txt\":\n        usufyToTextExport(data, fileH+\".\"+ext)\n    elif ext == \"xls\":\n        usufyToXlsExport(data, fileH+\".\"+ext)\n    elif ext == \"xlsx\":\n        usufyToXlsxExport(data, fileH+\".\"+ext)",
    "docstring": "Method that exports the different structures onto different formats.\n\n    Args:\n    -----\n        data: Data to export.\n        ext: One of the following: csv, excel, json, ods.\n        fileH: Fileheader for the output files.\n\n    Returns:\n    --------\n        Performs the export as requested by parameter."
  },
  {
    "code": "def client_credentials(self, client_id, client_secret, audience,\n                           grant_type='client_credentials'):\n        return self.post(\n            'https://{}/oauth/token'.format(self.domain),\n            data={\n                'client_id': client_id,\n                'client_secret': client_secret,\n                'audience': audience,\n                'grant_type': grant_type,\n            },\n            headers={'Content-Type': 'application/json'}\n        )",
    "docstring": "Client credentials grant\n\n        This is the OAuth 2.0 grant that server processes utilize in\n        order to access an API. Use this endpoint to directly request\n        an access_token by using the Application Credentials (a Client Id and\n        a Client Secret).\n\n        Args:\n            grant_type (str): Denotes the flow you're using. For client credentials\n            use client_credentials\n\n            client_id (str): your application's client Id\n\n            client_secret (str): your application's client Secret\n\n            audience (str): The unique identifier of the target API you want to access.\n\n        Returns:\n            access_token"
  },
  {
    "code": "def update(self, historics_id, name):\n        return self.request.post('update', data=dict(id=historics_id, name=name))",
    "docstring": "Update the name of the given Historics query.\n\n            Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsupdate\n\n            :param historics_id: playback id of the job to start\n            :type historics_id: str\n            :param name: new name of the stream\n            :type name: str\n            :return: dict of REST API output with headers attached\n            :rtype: :class:`~datasift.request.DictResponse`\n            :raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`"
  },
  {
    "code": "def get_valid_https_verify(value):\n    http_verify_value = value\n    bool_values = {'false': False, 'true': True}\n    if isinstance(value, bool):\n        http_verify_value = value\n    elif (isinstance(value, str) or isinstance(value, unicode)) and value.lower() in bool_values.keys():\n        http_verify_value = bool_values[value.lower()]\n    return http_verify_value",
    "docstring": "Get a value that can be the boolean representation of a string\n    or a boolean itself and returns It as a boolean.\n    If this is not the case, It returns a string.\n\n    :value: The HTTPS_verify input value. A string can be passed as a path\n            to a CA_BUNDLE certificate\n    :returns: True, False or a string."
  },
  {
    "code": "def _hashed_key(self):\n        return abs(int(hashlib.md5(\n            self.key_prefix.encode('utf8')\n        ).hexdigest(), 16)) % (10 ** (\n            self._size_mod if hasattr(self, '_size_mod') else 5))",
    "docstring": "Returns 16-digit numeric hash of the redis key"
  },
  {
    "code": "def no_content_response(response):\n    \"Cautious assessment of the response body for no content.\"\n    if not hasattr(response, '_container'):\n        return True\n    if response._container is None:\n        return True\n    if isinstance(response._container, (list, tuple)):\n        if len(response._container) == 1 and not response._container[0]:\n            return True\n    return False",
    "docstring": "Cautious assessment of the response body for no content."
  },
  {
    "code": "def clone_and_update(self, **kwargs):\n        cloned = self.clone()\n        cloned.update(**kwargs)\n        return cloned",
    "docstring": "Clones the object and updates the clone with the args\n\n        @param kwargs: Keyword arguments to set\n        @return: The cloned copy with updated values"
  },
  {
    "code": "def run_evaluation(self, stream_name: str) -> None:\n        def prediction():\n            logging.info('Running prediction')\n            self._run_zeroth_epoch([stream_name])\n            logging.info('Prediction done\\n\\n')\n        self._try_run(prediction)",
    "docstring": "Run the main loop with the given stream in the prediction mode.\n\n        :param stream_name: name of the stream to be evaluated"
  },
  {
    "code": "def _get_imports_h(self, data_types):\n        if not isinstance(data_types, list):\n            data_types = [data_types]\n        import_classes = []\n        for data_type in data_types:\n            if is_user_defined_type(data_type):\n                import_classes.append(fmt_class_prefix(data_type))\n            for field in data_type.all_fields:\n                data_type, _ = unwrap_nullable(field.data_type)\n                while is_list_type(data_type) or is_map_type(data_type):\n                    data_type = (data_type.value_data_type if\n                        is_map_type(data_type) else data_type.data_type)\n                if is_user_defined_type(data_type):\n                    import_classes.append(fmt_class_prefix(data_type))\n        import_classes = list(set(import_classes))\n        import_classes.sort()\n        return import_classes",
    "docstring": "Emits all necessary header file imports for the given Stone data type."
  },
  {
    "code": "def create(callback=None, path=None, method=Method.POST, resource=None, tags=None, summary=\"Create a new resource\",\n           middleware=None):\n    def inner(c):\n        op = ResourceOperation(c, path or NoPath, method, resource, tags, summary, middleware)\n        op.responses.add(Response(HTTPStatus.CREATED, \"{name} has been created\"))\n        op.responses.add(Response(HTTPStatus.BAD_REQUEST, \"Validation failed.\", Error))\n        return op\n    return inner(callback) if callback else inner",
    "docstring": "Decorator to configure an operation that creates a resource."
  },
  {
    "code": "def fit(self, volumes, energies):\n        eos_fit = self.model(np.array(volumes), np.array(energies))\n        eos_fit.fit()\n        return eos_fit",
    "docstring": "Fit energies as function of volumes.\n\n        Args:\n            volumes (list/np.array)\n            energies (list/np.array)\n\n        Returns:\n            EOSBase: EOSBase object"
  },
  {
    "code": "def all(self, order_by=None, limit=0):\n        with rconnect() as conn:\n            try:\n                query = self._base()\n                if order_by is not None:\n                    query = self._order_by(query, order_by)\n                if limit > 0:\n                    query = self._limit(query, limit)\n                log.debug(query)\n                rv = query.run(conn)\n            except Exception as e:\n                log.warn(e)\n                raise\n            else:\n                data = [self._model(_) for _ in rv]\n                return data",
    "docstring": "Fetch all items.\n\n            :param limit: How many rows to fetch.\n            :param order_by: column on which to order the results. \\\n            To change the sort, prepend with < or >."
  },
  {
    "code": "def random_int_generator(maxrange):\n    try:\n        return random.randint(0,maxrange)\n    except:\n        line, filename, synerror = trace()\n        raise ArcRestHelperError({\n                    \"function\": \"random_int_generator\",\n                    \"line\": line,\n                    \"filename\":  filename,\n                    \"synerror\": synerror,\n                                    }\n                                    )\n    finally:\n        pass",
    "docstring": "Generates a random integer from 0 to `maxrange`, inclusive.\n\n    Args:\n        maxrange (int): The upper range of integers to randomly choose.\n\n    Returns:\n        int: The randomly generated integer from :py:func:`random.randint`.\n\n    Examples:\n        >>> arcresthelper.common.random_int_generator(15)\n        9"
  },
  {
    "code": "def _add_updated_at_column(self, values):\n        if not self._model.uses_timestamps():\n            return values\n        column = self._model.get_updated_at_column()\n        if \"updated_at\" not in values:\n            values.update({column: self._model.fresh_timestamp_string()})\n        return values",
    "docstring": "Add the \"updated_at\" column to a dictionary of values.\n\n        :param values: The values to update\n        :type values: dict\n\n        :return: The new dictionary of values\n        :rtype: dict"
  },
  {
    "code": "def read_lock(self):\n        me = self._current_thread()\n        if me in self._pending_writers:\n            raise RuntimeError(\"Writer %s can not acquire a read lock\"\n                               \" while waiting for the write lock\"\n                               % me)\n        with self._cond:\n            while True:\n                if self._writer is None or self._writer == me:\n                    try:\n                        self._readers[me] = self._readers[me] + 1\n                    except KeyError:\n                        self._readers[me] = 1\n                    break\n                self._cond.wait()\n        try:\n            yield self\n        finally:\n            with self._cond:\n                try:\n                    me_instances = self._readers[me]\n                    if me_instances > 1:\n                        self._readers[me] = me_instances - 1\n                    else:\n                        self._readers.pop(me)\n                except KeyError:\n                    pass\n                self._cond.notify_all()",
    "docstring": "Context manager that grants a read lock.\n\n        Will wait until no active or pending writers.\n\n        Raises a ``RuntimeError`` if a pending writer tries to acquire\n        a read lock."
  },
  {
    "code": "async def _notify(self, message: BaseMessage, responder: Responder):\n        for cb in self._listeners:\n            coro = cb(message, responder, self.fsm_creates_task)\n            if not self.fsm_creates_task:\n                self._register = await coro",
    "docstring": "Notify all callbacks that a message was received."
  },
  {
    "code": "def get_version(cls):\n        cmd_pieces = [cls.tool, '--version']\n        process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE)\n        out, err = process.communicate()\n        if err:\n            return ''\n        else:\n            return out.splitlines()[0].strip()",
    "docstring": "Return the version number of the tool."
  },
  {
    "code": "def use_size(self):\n        \"Return the total used size, including children.\"\n        if self._nodes is None:\n            return self._use_size\n        return sum(i.use_size() for i in self._nodes)",
    "docstring": "Return the total used size, including children."
  },
  {
    "code": "def query(self, event, pk, ts=None):\n        key = self._keygen(event, ts)\n        pk_ts = self.r.zscore(key, pk)\n        return int(pk_ts) if pk_ts else None",
    "docstring": "Query the last update timestamp of an event pk.\n\n        You can pass a timestamp to only look for events later than that\n        within the same namespace.\n\n        :param event: the event name.\n        :param pk: the pk value for query.\n        :param ts: query event pk after ts, default to None which will query\n         all span of current namespace."
  },
  {
    "code": "def AddStatEntry(self, stat_entry, timestamp):\n    if timestamp in self._stat_entries:\n      message = (\"Duplicated stat entry write for path '%s' of type '%s' at \"\n                 \"timestamp '%s'. Old: %s. New: %s.\")\n      message %= (\"/\".join(self._components), self._path_type, timestamp,\n                  self._stat_entries[timestamp], stat_entry)\n      raise db.Error(message)\n    if timestamp not in self._path_infos:\n      path_info = rdf_objects.PathInfo(\n          path_type=self._path_type,\n          components=self._components,\n          timestamp=timestamp,\n          stat_entry=stat_entry)\n      self.AddPathInfo(path_info)\n    else:\n      self._path_infos[timestamp].stat_entry = stat_entry",
    "docstring": "Registers stat entry at a given timestamp."
  },
  {
    "code": "def initializable(self):\n        return bool(lib.EnvSlotInitableP(self._env, self._cls, self._name))",
    "docstring": "True if the Slot is initializable."
  },
  {
    "code": "def _range2cols(areas):\n    cols = []\n    for rng in areas.split(\",\"):\n        if \":\" in rng:\n            rng = rng.split(\":\")\n            cols.extend(lrange(_excel2num(rng[0]), _excel2num(rng[1]) + 1))\n        else:\n            cols.append(_excel2num(rng))\n    return cols",
    "docstring": "Convert comma separated list of column names and ranges to indices.\n\n    Parameters\n    ----------\n    areas : str\n        A string containing a sequence of column ranges (or areas).\n\n    Returns\n    -------\n    cols : list\n        A list of 0-based column indices.\n\n    Examples\n    --------\n    >>> _range2cols('A:E')\n    [0, 1, 2, 3, 4]\n    >>> _range2cols('A,C,Z:AB')\n    [0, 2, 25, 26, 27]"
  },
  {
    "code": "def _LoadAuditEvents(handlers,\n                     get_report_args,\n                     actions=None,\n                     token=None,\n                     transformers=None):\n  if transformers is None:\n    transformers = {}\n  if data_store.RelationalDBEnabled():\n    entries = data_store.REL_DB.ReadAPIAuditEntries(\n        min_timestamp=get_report_args.start_time,\n        max_timestamp=get_report_args.start_time + get_report_args.duration,\n        router_method_names=list(handlers.keys()))\n    rows = [_EntryToEvent(entry, handlers, transformers) for entry in entries]\n  else:\n    entries = report_utils.GetAuditLogEntries(\n        offset=get_report_args.duration,\n        now=get_report_args.start_time + get_report_args.duration,\n        token=token)\n    if actions is None:\n      actions = set(handlers.values())\n    rows = [entry for entry in entries if entry.action in actions]\n  rows.sort(key=lambda row: row.timestamp, reverse=True)\n  return rows",
    "docstring": "Returns AuditEvents for given handlers, actions, and timerange."
  },
  {
    "code": "def pack_data(self, remaining_size):\n        payload = self.part_struct.pack(self.locator_id, self.readoffset + 1, self.readlength, b'    ')\n        return 4, payload",
    "docstring": "Pack data. readoffset has to be increased by one, seems like HANA starts from 1, not zero."
  },
  {
    "code": "def get_object_class(object_type, vendor_id=0):\n    if _debug: get_object_class._debug(\"get_object_class %r vendor_id=%r\", object_type, vendor_id)\n    cls = registered_object_types.get((object_type, vendor_id))\n    if _debug: get_object_class._debug(\"    - direct lookup: %s\", repr(cls))\n    if (not cls) and vendor_id:\n        cls = registered_object_types.get((object_type, 0))\n        if _debug: get_object_class._debug(\"    - default lookup: %s\", repr(cls))\n    return cls",
    "docstring": "Return the class associated with an object type."
  },
  {
    "code": "def get_metrics(self, slug_list):\n        keys = ['seconds', 'minutes', 'hours', 'day', 'week', 'month', 'year']\n        key_mapping = {gran: key for gran, key in zip(GRANULARITIES, keys)}\n        keys = [key_mapping[gran] for gran in self._granularities()]\n        results = []\n        for slug in slug_list:\n            metrics = self.r.mget(*self._build_keys(slug))\n            if any(metrics):\n                results.append((slug, dict(zip(keys, metrics))))\n        return results",
    "docstring": "Get the metrics for multiple slugs.\n\n        Returns a list of two-tuples containing the metric slug and a\n        dictionary like the one returned by ``get_metric``::\n\n            (\n                some-metric, {\n                    'seconds': 0, 'minutes': 0, 'hours': 0,\n                    'day': 0, 'week': 0, 'month': 0, 'year': 0\n                }\n            )"
  },
  {
    "code": "def createissue(self, project_id, title, **kwargs):\n        data = {'id': id, 'title': title}\n        if kwargs:\n            data.update(kwargs)\n        request = requests.post(\n            '{0}/{1}/issues'.format(self.projects_url, project_id),\n            headers=self.headers, data=data, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)\n        if request.status_code == 201:\n            return request.json()\n        else:\n            return False",
    "docstring": "Create a new issue\n\n        :param project_id: project id\n        :param title: title of the issue\n        :return: dict with the issue created"
  },
  {
    "code": "def get_stored_files(self):\n        method = 'GET'\n        endpoint = '/rest/v1/storage/{}'.format(self.client.sauce_username)\n        return self.client.request(method, endpoint)",
    "docstring": "Check which files are in your temporary storage."
  },
  {
    "code": "def convert_to_utf8(string):\n    if (isinstance(string, unicode)):\n        return string.encode('utf-8')\n    try:\n        u = unicode(string, 'utf-8')\n    except TypeError:\n        return str(string)\n    utf8 = u.encode('utf-8')\n    return utf8",
    "docstring": "Convert string to UTF8"
  },
  {
    "code": "def mse(x, xhat):\n    buf_ = x - xhat\n    np.square(buf_, out=buf_)\n    sum_ = np.sum(buf_)\n    sum_ /= x.size\n    return sum_",
    "docstring": "Calcualte mse between vector or matrix x and xhat"
  },
  {
    "code": "def db_url(self, var=DEFAULT_DATABASE_ENV, default=NOTSET, engine=None):\n        return self.db_url_config(self.get_value(var, default=default), engine=engine)",
    "docstring": "Returns a config dictionary, defaulting to DATABASE_URL.\n\n        :rtype: dict"
  },
  {
    "code": "def get_url_array(self):\n        urlarray = []\n        for urlobjects in self.__json_object[\"base_urls\"]:\n            urlarray.append(urlobjects[\"url\"])\n        return urlarray",
    "docstring": "Get all url-objects in an array\n\n        :return sites (array): The sites from the JSON-file"
  },
  {
    "code": "def scan_and_connect(self, devnames, timeout=DEF_TIMEOUT, calibration=True):\n        responses = self.scan_devices(devnames, timeout)\n        for dev in devnames:\n            if dev not in responses:\n                logger.error('Failed to find device {} during scan'.format(dev))\n                return (False, [])\n        return self.connect([responses.get_device(dev) for dev in devnames], calibration)",
    "docstring": "Scan for and then connect to a set of one or more SK8s.\n\n        This method is intended to be a simple way to combine the steps of \n        running a BLE scan, checking the results and connecting to one or more\n        devices. When called, a scan is started for a period equal to `timeout`,\n        and a list of devices is collected. If at any point during the scan all of\n        the supplied devices are detected, the scan will be ended immediately. \n        \n        After the scan has completed, the method will only proceed to creating\n        connections if the scan results contain all the specified devices. \n\n        Args:\n            devnames (list): a list of device names (1 or more)\n            timeout (float): a time period in seconds to run the scanning process \n                (will be terminated early if all devices in `devnames` are discovered)\n\n        Returns:\n            Returns the same results as :meth:`connect`."
  },
  {
    "code": "def my_permissions(self,\n                       projectKey=None,\n                       projectId=None,\n                       issueKey=None,\n                       issueId=None,\n                       ):\n        params = {}\n        if projectKey is not None:\n            params['projectKey'] = projectKey\n        if projectId is not None:\n            params['projectId'] = projectId\n        if issueKey is not None:\n            params['issueKey'] = issueKey\n        if issueId is not None:\n            params['issueId'] = issueId\n        return self._get_json('mypermissions', params=params)",
    "docstring": "Get a dict of all available permissions on the server.\n\n        :param projectKey: limit returned permissions to the specified project\n        :type projectKey: Optional[str]\n        :param projectId: limit returned permissions to the specified project\n        :type projectId: Optional[str]\n        :param issueKey: limit returned permissions to the specified issue\n        :type issueKey: Optional[str]\n        :param issueId: limit returned permissions to the specified issue\n        :type issueId: Optional[str]\n        :rtype: Dict[str, Dict[str, Dict[str, str]]]"
  },
  {
    "code": "def is_acquired(self):\n        values = self.client.get(self.key)\n        return six.b(self._uuid) in values",
    "docstring": "Check if the lock is acquired"
  },
  {
    "code": "def _table_exists(self):\r\n        self.cursor.execute(\"SHOW TABLES\")\r\n        for table in self.cursor.fetchall():\r\n            if table[0].lower() == self.name.lower():\r\n                return True\r\n        return False",
    "docstring": "Database-specific method to see if the table exists"
  },
  {
    "code": "def draw_label_path(context, width, height, arrow_height, distance_to_port, port_offset):\n    c = context\n    c.rel_move_to(0, port_offset)\n    c.rel_line_to(0, distance_to_port)\n    c.rel_line_to(-width / 2., arrow_height)\n    c.rel_line_to(0, height - arrow_height)\n    c.rel_line_to(width, 0)\n    c.rel_line_to(0, -(height - arrow_height))\n    c.rel_line_to(-width / 2., -arrow_height)\n    c.close_path()",
    "docstring": "Draws the path for an upright label\n\n    :param context: The Cairo context\n    :param float width: Width of the label\n    :param float height: Height of the label\n    :param float distance_to_port: Distance to the port related to the label\n    :param float port_offset: Distance from the port center to its border\n    :param bool draw_connection_to_port: Whether to draw a line from the tip of the label to the port"
  },
  {
    "code": "def _spikes_in_clusters(spike_clusters, clusters):\n    if len(spike_clusters) == 0 or len(clusters) == 0:\n        return np.array([], dtype=np.int)\n    return np.nonzero(np.in1d(spike_clusters, clusters))[0]",
    "docstring": "Return the ids of all spikes belonging to the specified clusters."
  },
  {
    "code": "def check_valid_ip_or_cidr(val, return_as_cidr=False):\n    is_ip = True\n    if \"/\" in val:\n        ip_check(val, netmask_expected=True)\n        is_ip = False\n    else:\n        ip_check(val, netmask_expected=False)\n    if return_as_cidr and is_ip:\n        if val == \"0.0.0.0\":\n            val = \"0.0.0.0/0\"\n        else:\n            val = \"%s/32\" % val\n    try:\n        ipaddress.IPv4Network(unicode(val))\n    except Exception as e:\n        raise ArgsError(\"Not a valid network: %s\" % str(e))\n    return val",
    "docstring": "Checks that the value is a valid IP address or a valid CIDR.\n\n    Returns the specified value.\n\n    If 'return_as_cidr' is set then the return value will always be in the form\n    of a CIDR, even if a plain IP address was specified."
  },
  {
    "code": "async def generate_access_token(self, user):\n        payload = await self._get_payload(user)\n        secret = self._get_secret(True)\n        algorithm = self._get_algorithm()\n        return jwt.encode(payload, secret, algorithm=algorithm).decode(\"utf-8\")",
    "docstring": "Generate an access token for a given user."
  },
  {
    "code": "def _find_dirs(metadata):\n    ret = []\n    found = {}\n    for bucket_dict in metadata:\n        for bucket_name, data in six.iteritems(bucket_dict):\n            dirpaths = set()\n            for path in [k['Key'] for k in data]:\n                prefix = ''\n                for part in path.split('/')[:-1]:\n                    directory = prefix + part + '/'\n                    dirpaths.add(directory)\n                    prefix = directory\n            if bucket_name not in found:\n                found[bucket_name] = True\n                ret.append({bucket_name: list(dirpaths)})\n            else:\n                for bucket in ret:\n                    if bucket_name in bucket:\n                        bucket[bucket_name] += list(dirpaths)\n                        bucket[bucket_name] = list(set(bucket[bucket_name]))\n                        break\n    return ret",
    "docstring": "Looks for all the directories in the S3 bucket cache metadata.\n\n    Supports trailing '/' keys (as created by S3 console) as well as\n    directories discovered in the path of file keys."
  },
  {
    "code": "def activate_conf_set(self, set_name):\n        with self._mutex:\n            if not set_name in self.conf_sets:\n                raise exceptions.NoSuchConfSetError(set_name)\n            self._conf.activate_configuration_set(set_name)",
    "docstring": "Activate a configuration set by name.\n\n        @raises NoSuchConfSetError"
  },
  {
    "code": "def create(self, identity, role_sid=values.unset):\n        data = values.of({'Identity': identity, 'RoleSid': role_sid, })\n        payload = self._version.create(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return InviteInstance(\n            self._version,\n            payload,\n            service_sid=self._solution['service_sid'],\n            channel_sid=self._solution['channel_sid'],\n        )",
    "docstring": "Create a new InviteInstance\n\n        :param unicode identity: The `identity` value that identifies the new resource's User\n        :param unicode role_sid: The Role assigned to the new member\n\n        :returns: Newly created InviteInstance\n        :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance"
  },
  {
    "code": "def authenticate(self, environ):\n        try:\n            hd = parse_dict_header(environ['HTTP_AUTHORIZATION'])\n        except (KeyError, ValueError):\n            return False\n        return self.credentials_valid(\n            hd['response'],\n            environ['REQUEST_METHOD'],\n            environ['httpauth.uri'],\n            hd['nonce'],\n            hd['Digest username'],\n        )",
    "docstring": "Returns True if the credentials passed in the Authorization header are\n        valid, False otherwise."
  },
  {
    "code": "def get_firmware_image(self, image_id):\n        api = self._get_api(update_service.DefaultApi)\n        return FirmwareImage(api.firmware_image_retrieve(image_id))",
    "docstring": "Get a firmware image with provided image_id.\n\n        :param str image_id: The firmware ID for the image to retrieve (Required)\n        :return: FirmwareImage"
  },
  {
    "code": "def search(self, *filters, **kwargs):\n        report = self._app.reports.build(\n            'search-' + random_string(8),\n            keywords=kwargs.pop('keywords', []),\n            limit=kwargs.pop('limit', Report.default_limit)\n        )\n        for filter_tuples in filters:\n            report.filter(*filter_tuples)\n        return list(report)",
    "docstring": "Shortcut to generate a new temporary search report using provided filters and return the resulting records\n\n        Args:\n            *filters (tuple): Zero or more filter tuples of (field_name, operator, field_value)\n\n        Keyword Args:\n            keywords (list(str)): List of strings of keywords to use in report search\n            limit (int): Set maximum number of returned Records, defaults to `Report.default_limit`. Set to 0 to return\n                all records\n\n        Notes:\n            Uses a temporary Report instance with a random name to facilitate search. Records are normally paginated,\n            but are returned as a single list here, potentially causing performance issues with large searches.\n\n            All provided filters are AND'ed together\n\n            Filter operators are available as constants in `swimlane.core.search`\n\n        Examples:\n\n            ::\n\n                # Return records matching all filters with default limit\n\n                from swimlane.core import search\n\n                records = app.records.search(\n                    ('field_name', 'equals', 'field_value'),\n                    ('other_field', search.NOT_EQ, 'value')\n                )\n\n            ::\n\n                # Run keyword search with multiple keywords\n                records = app.records.search(keywords=['example', 'test'])\n\n            ::\n\n                # Return all records from app\n                records = app.records.search(limit=0)\n\n\n        Returns:\n            :class:`list` of :class:`~swimlane.core.resources.record.Record`: List of Record instances returned from the\n                search results"
  },
  {
    "code": "def int_to_gematria(num, gershayim=True):\n    if num in specialnumbers['specials']:\n        retval = specialnumbers['specials'][num]\n        return _add_gershayim(retval) if gershayim else retval\n    parts = []\n    rest = str(num)\n    while rest:\n        digit = int(rest[0])\n        rest = rest[1:]\n        if digit == 0:\n            continue\n        power = 10 ** len(rest)\n        parts.append(specialnumbers['numerals'][power * digit])\n    retval = ''.join(parts)\n    return _add_gershayim(retval) if gershayim else retval",
    "docstring": "convert integers between 1 an 999 to Hebrew numerals.\n\n           - set gershayim flag to False to ommit gershayim"
  },
  {
    "code": "def cmd_extract_email(infile, verbose, jsonout):\n    if verbose:\n        logging.basicConfig(level=logging.INFO, format='%(message)s')\n    data = infile.read()\n    result = []\n    result = extract_email(data)\n    if jsonout:\n        print(json.dumps(result, indent=4))\n    else:\n        print('\\n'.join(result))",
    "docstring": "Extract email addresses from a file or stdin.\n\n    Example:\n\n    \\b\n    $ cat /var/log/auth.log | habu.extract.email\n    john@securetia.com\n    raven@acmecorp.net\n    nmarks@fimax.com"
  },
  {
    "code": "def delete_snl(self, snl_ids):\n        try:\n            payload = {\"ids\": json.dumps(snl_ids)}\n            response = self.session.post(\n                \"{}/snl/delete\".format(self.preamble), data=payload)\n            if response.status_code in [200, 400]:\n                resp = json.loads(response.text, cls=MontyDecoder)\n                if resp[\"valid_response\"]:\n                    if resp.get(\"warning\"):\n                        warnings.warn(resp[\"warning\"])\n                    return resp\n                else:\n                    raise MPRestError(resp[\"error\"])\n            raise MPRestError(\"REST error with status code {} and error {}\"\n                              .format(response.status_code, response.text))\n        except Exception as ex:\n            raise MPRestError(str(ex))",
    "docstring": "Delete earlier submitted SNLs.\n\n        .. note::\n\n            As of now, this MP REST feature is open only to a select group of\n            users. Opening up submissions to all users is being planned for\n            the future.\n\n        Args:\n            snl_ids: List of SNL ids.\n\n        Raises:\n            MPRestError"
  },
  {
    "code": "def create_area(self, area_uuid):\n        response = self._make_request('post',\n                                      path=\"/area/{id}\".format(id=area_uuid),\n                                      headers={'Api-Key': self.auth_token})\n        return response.json()",
    "docstring": "Create an Upload Area\n\n        :param str area_uuid: A RFC4122-compliant ID for the upload area\n        :return: a dict of the form { \"uri\": \"s3://<bucket_name>/<upload-area-id>/\" }\n        :rtype: dict\n        :raises UploadApiException: if the an Upload Area was not created"
  },
  {
    "code": "def load_rml(self, rml_name):\n        conn = CFG.rml_tstore\n        cache_path = os.path.join(CFG.CACHE_DATA_PATH, 'rml_files', rml_name)\n        if not os.path.exists(cache_path):\n            results = get_graph(NSM.uri(getattr(NSM.kdr, rml_name), False),\n                                conn)\n            with open(cache_path, \"w\") as file_obj:\n                file_obj.write(json.dumps(results, indent=4))\n        else:\n            results = json.loads(open(cache_path).read())\n        self.rml[rml_name] = RdfDataset(results)\n        return self.rml[rml_name]",
    "docstring": "loads an rml mapping into memory\n\n        args:\n            rml_name(str): the name of the rml file"
  },
  {
    "code": "def incoming_connections(self):\n        return list(\n            takewhile(lambda c: c.direction == INCOMING, self.connections)\n        )",
    "docstring": "Returns a list of all incoming connections for this peer."
  },
  {
    "code": "def loads(cls, pickle_string):\n        cls.load_counter_offset = StoreOptions.id_offset()\n        val = pickle.loads(pickle_string)\n        cls.load_counter_offset = None\n        return val",
    "docstring": "Equivalent to pickle.loads except that the HoloViews trees is\n        restored appropriately."
  },
  {
    "code": "def converge(self, playbook=None, **kwargs):\n        if playbook is None:\n            pb = self._get_ansible_playbook(self.playbooks.converge, **kwargs)\n        else:\n            pb = self._get_ansible_playbook(playbook, **kwargs)\n        return pb.execute()",
    "docstring": "Executes ``ansible-playbook`` against the converge playbook unless\n        specified otherwise and returns a string.\n\n        :param playbook: An optional string containing an absolute path to a\n         playbook.\n        :param kwargs: An optional keyword arguments.\n        :return: str"
  },
  {
    "code": "def fetch(self):\n        response = Response()\n        has_next = True\n        while has_next:\n            resp = self._fetch(default_path='v2')\n            results = None\n            if resp.success:\n                results = resp.data['results']\n                self.add_get_param('page', resp.data['pagination']['page'] + 1)\n                has_next = resp.data['pagination']['has_next']\n            response.add(results, resp.status_code, resp.status_reason)\n        return response",
    "docstring": "Run the request and fetch the results.\n\n        This method will compile the request, send it to the SpaceGDN endpoint\n        defined with the `SpaceGDN` object and wrap the results in a\n        :class:`pyspacegdn.Response` object.\n\n        Returns a :class:`pyspacegdn.Response` object."
  },
  {
    "code": "def read_gain_from_frames(frame_filenames, gain_channel_name, start_time, end_time):\n    gain = frame.read_frame(frame_filenames, gain_channel_name,\n                      start_time=start_time, end_time=end_time)\n    return gain[0]",
    "docstring": "Returns the gain from the file."
  },
  {
    "code": "def is_satisfied(self):\n        return self._call_counter.has_correct_call_count() and (\n            self._call_counter.never() or self._is_satisfied)",
    "docstring": "Returns a boolean indicating whether or not the double has been satisfied. Stubs are\n        always satisfied, but mocks are only satisfied if they've been called as was declared,\n        or if call is expected not to happen.\n\n        :return: Whether or not the double is satisfied.\n        :rtype: bool"
  },
  {
    "code": "def map_overlay_obs(self):\n        return json.loads(self._query(LAYER, OBSERVATIONS, ALL, CAPABILITIES, \"\").decode(errors=\"replace\"))",
    "docstring": "Returns capabilities data for observation map overlays."
  },
  {
    "code": "def _is_last_child(self, tagname, attributes=None):\n        children = self.cur_node.getchildren()\n        if children:\n            result = self._is_node(tagname, attributes, node=children[-1])\n            return result\n        return False",
    "docstring": "Check if last child of cur_node is tagname with attributes"
  },
  {
    "code": "def set_loglevel(self, level):\n        self.log_level = level\n        log_manager.config_stdio(default_level=level)",
    "docstring": "Set the minimum loglevel for all components\n\n        Args:\n            level (int): eg. logging.DEBUG or logging.ERROR. See also https://docs.python.org/2/library/logging.html#logging-levels"
  },
  {
    "code": "def get(self, key, default=None, as_int=False, setter=None):\n        if as_int:\n            val = uwsgi.cache_num(key, self.name)\n        else:\n            val = decode(uwsgi.cache_get(key, self.name))\n        if val is None:\n            if setter is None:\n                return default\n            val = setter(key)\n            if val is None:\n                return default\n            self.set(key, val)\n        return val",
    "docstring": "Gets a value from the cache.\n\n        :param str|unicode key: The cache key to get value for.\n\n        :param default: Value to return if none found in cache.\n\n        :param bool as_int: Return 64bit number instead of str.\n\n        :param callable setter: Setter callable to automatically set cache\n            value if not already cached. Required to accept a key and return\n            a value that will be cached.\n\n        :rtype: str|unicode|int"
  },
  {
    "code": "def get_student_enrollments(self):\n        resp = self.requester.get(\n            urljoin(self.base_url, self.enrollment_url))\n        resp.raise_for_status()\n        return Enrollments(resp.json())",
    "docstring": "Returns an Enrollments object with the user enrollments\n\n        Returns:\n            Enrollments: object representing the student enrollments"
  },
  {
    "code": "def rm_subsets(ctx, dataset, kwargs):\n    \"removes the dataset's training-set and test-set folders if they exists\"\n    kwargs = parse_kwargs(kwargs)\n    data(dataset, **ctx.obj).rm_subsets(**kwargs)",
    "docstring": "removes the dataset's training-set and test-set folders if they exists"
  },
  {
    "code": "def cmd_part(self, connection, sender, target, payload):\n        if payload:\n            connection.part(payload)\n        else:\n            raise ValueError(\"No channel given\")",
    "docstring": "Asks the bot to leave a channel"
  },
  {
    "code": "async def full_dispatch_request(\n        self, request_context: Optional[RequestContext]=None,\n    ) -> Response:\n        await self.try_trigger_before_first_request_functions()\n        await request_started.send(self)\n        try:\n            result = await self.preprocess_request(request_context)\n            if result is None:\n                result = await self.dispatch_request(request_context)\n        except Exception as error:\n            result = await self.handle_user_exception(error)\n        return await self.finalize_request(result, request_context)",
    "docstring": "Adds pre and post processing to the request dispatching.\n\n        Arguments:\n            request_context: The request context, optional as Flask\n                omits this argument."
  },
  {
    "code": "def _dump(file_obj, options, out=sys.stdout):\n    total_count = 0\n    writer = None\n    keys = None\n    for row in DictReader(file_obj, options.col):\n        if not keys:\n            keys = row.keys()\n        if not writer:\n            writer = csv.DictWriter(out, keys, delimiter=u'\\t', quotechar=u'\\'', quoting=csv.QUOTE_MINIMAL) \\\n                if options.format == 'csv' \\\n                else JsonWriter(out) if options.format == 'json' \\\n                else None\n        if total_count == 0 and options.format == \"csv\" and not options.no_headers:\n            writer.writeheader()\n        if options.limit != -1 and total_count >= options.limit:\n            return\n        row_unicode = {k: v.decode(\"utf-8\") if isinstance(v, bytes) else v for k, v in row.items()}\n        writer.writerow(row_unicode)\n        total_count += 1",
    "docstring": "Dump to fo with given options."
  },
  {
    "code": "def select_functions(expr):\n    body = Group(expr)\n    return Group(\n        function(\"timestamp\", body, caseless=True)\n        | function(\"ts\", body, caseless=True)\n        | function(\"utctimestamp\", body, caseless=True)\n        | function(\"utcts\", body, caseless=True)\n        | function(\"now\", caseless=True)\n        | function(\"utcnow\", caseless=True)\n    ).setResultsName(\"function\")",
    "docstring": "Create the function expressions for selection"
  },
  {
    "code": "def aborting_function():\n    import random\n    logging.info('In aborting_function')\n    if random.random() < .5:\n        from furious.errors import AbortAndRestart\n        logging.info('Getting ready to restart')\n        raise AbortAndRestart()\n    logging.info('No longer restarting')",
    "docstring": "There is a 50% chance that this function will AbortAndRestart or\n    complete successfully.\n\n    The 50% chance simply represents a process that will fail half the time\n    and succeed half the time."
  },
  {
    "code": "def starts_with(self, other: 'Key') -> bool:\n        if (self.key_type, self.identity, self.group) != (other.key_type, other.identity,\n                                                          other.group):\n            return False\n        if self.key_type == KeyType.TIMESTAMP:\n            return True\n        if self.key_type == KeyType.DIMENSION:\n            if len(self.dimensions) < len(other.dimensions):\n                return False\n            return self.dimensions[0:len(other.dimensions)] == other.dimensions",
    "docstring": "Checks if this key starts with the other key provided. Returns False if key_type, identity\n        or group are different.\n        For `KeyType.TIMESTAMP` returns True.\n        For `KeyType.DIMENSION` does prefix match between the two dimensions property."
  },
  {
    "code": "def read_csv(fname):\n    values = defaultdict(list)\n    with open(fname) as f:\n        reader = csv.DictReader(f)\n        for row in reader:\n            for (k,v) in row.items():\n                values[k].append(v)\n    npvalues = {k: np.array(values[k]) for k in values.keys()}\n    for k in npvalues.keys():\n        for datatype in [np.int, np.float]:\n            try:\n                npvalues[k][:1].astype(datatype)\n                npvalues[k] = npvalues[k].astype(datatype)\n                break\n            except:\n                pass\n    dao = DataAccessObject(npvalues)\n    return dao",
    "docstring": "Read a csv file into a DataAccessObject\n\n    :param fname: filename"
  },
  {
    "code": "def tags_newer(self, versions_file, majors):\n        highest = versions_file.highest_version_major(majors)\n        all = self.tags_get()\n        newer = _newer_tags_get(highest, all)\n        if len(newer) == 0:\n            raise RuntimeError(\"No new tags found.\")\n        return newer",
    "docstring": "Checks this git repo tags for newer versions.\n        @param versions_file: a common.VersionsFile instance to\n            check against.\n        @param majors: a list of major branches to check. E.g. ['6', '7']\n        @raise RuntimeError: no newer tags were found.\n        @raise MissingMajorException: A new version from a newer major branch is\n            exists, but hasn't been downloaded due to it not being in majors."
  },
  {
    "code": "def open(self, title):\n        try:\n            properties = finditem(\n                lambda x: x['name'] == title,\n                self.list_spreadsheet_files()\n            )\n            properties['title'] = properties['name']\n            return Spreadsheet(self, properties)\n        except StopIteration:\n            raise SpreadsheetNotFound",
    "docstring": "Opens a spreadsheet.\n\n        :param title: A title of a spreadsheet.\n        :type title: str\n\n        :returns: a :class:`~gspread.models.Spreadsheet` instance.\n\n        If there's more than one spreadsheet with same title the first one\n        will be opened.\n\n        :raises gspread.SpreadsheetNotFound: if no spreadsheet with\n                                             specified `title` is found.\n\n        >>> c = gspread.authorize(credentials)\n        >>> c.open('My fancy spreadsheet')"
  },
  {
    "code": "def __x_product_aux (property_sets, seen_features):\n    assert is_iterable_typed(property_sets, property_set.PropertySet)\n    assert isinstance(seen_features, set)\n    if not property_sets:\n        return ([], set())\n    properties = property_sets[0].all()\n    these_features = set()\n    for p in property_sets[0].non_free():\n        these_features.add(p.feature)\n    if these_features & seen_features:\n        (inner_result, inner_seen) = __x_product_aux(property_sets[1:], seen_features)\n        return (inner_result, inner_seen | these_features)\n    else:\n        result = []\n        (inner_result, inner_seen) = __x_product_aux(property_sets[1:], seen_features | these_features)\n        if inner_result:\n            for inner in inner_result:\n                result.append(properties + inner)\n        else:\n            result.append(properties)\n        if inner_seen & these_features:\n            (inner_result2, inner_seen2) = __x_product_aux(property_sets[1:], seen_features)\n            result.extend(inner_result2)\n        return (result, inner_seen | these_features)",
    "docstring": "Returns non-conflicting combinations of property sets.\n\n    property_sets is a list of PropertySet instances. seen_features is a set of Property\n    instances.\n\n    Returns a tuple of:\n    - list of lists of Property instances, such that within each list, no two Property instance\n    have the same feature, and no Property is for feature in seen_features.\n    - set of features we saw in property_sets"
  },
  {
    "code": "def appname(path=None):\n    if path is None:\n        path = sys.argv[0]\n    name = os.path.basename(os.path.splitext(path)[0])\n    if name == 'mod_wsgi':\n        name = 'nvn_web'\n    return name",
    "docstring": "Return a useful application name based on the program argument.\nA special case maps 'mod_wsgi' to a more appropriate name so\nweb applications show up as our own."
  },
  {
    "code": "def enu2ecef(e1: float, n1: float, u1: float,\n             lat0: float, lon0: float, h0: float,\n             ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]:\n    x0, y0, z0 = geodetic2ecef(lat0, lon0, h0, ell, deg=deg)\n    dx, dy, dz = enu2uvw(e1, n1, u1, lat0, lon0, deg=deg)\n    return x0 + dx, y0 + dy, z0 + dz",
    "docstring": "ENU to ECEF\n\n    Parameters\n    ----------\n\n    e1 : float or numpy.ndarray of float\n        target east ENU coordinate (meters)\n    n1 : float or numpy.ndarray of float\n        target north ENU coordinate (meters)\n    u1 : float or numpy.ndarray of float\n        target up ENU coordinate (meters)\n    lat0 : float\n           Observer geodetic latitude\n    lon0 : float\n           Observer geodetic longitude\n    h0 : float\n         observer altitude above geodetic ellipsoid (meters)\n    ell : Ellipsoid, optional\n          reference ellipsoid\n    deg : bool, optional\n          degrees input/output  (False: radians in/out)\n\n\n    Results\n    -------\n    x : float or numpy.ndarray of float\n        target x ECEF coordinate (meters)\n    y : float or numpy.ndarray of float\n        target y ECEF coordinate (meters)\n    z : float or numpy.ndarray of float\n        target z ECEF coordinate (meters)"
  },
  {
    "code": "def get_maybe_base_expanded_node_name(self, node_name, run_key, device_name):\n    device_name = tf.compat.as_str(device_name)\n    if run_key not in self._run_key_to_original_graphs:\n      raise ValueError('Unknown run_key: %s' % run_key)\n    if device_name not in self._run_key_to_original_graphs[run_key]:\n      raise ValueError(\n          'Unknown device for run key \"%s\": %s' % (run_key, device_name))\n    return self._run_key_to_original_graphs[\n        run_key][device_name].maybe_base_expanded_node_name(node_name)",
    "docstring": "Obtain possibly base-expanded node name.\n\n    Base-expansion is the transformation of a node name which happens to be the\n    name scope of other nodes in the same graph. For example, if two nodes,\n    called 'a/b' and 'a/b/read' in a graph, the name of the first node will\n    be base-expanded to 'a/b/(b)'.\n\n    This method uses caching to avoid unnecessary recomputation.\n\n    Args:\n      node_name: Name of the node.\n      run_key: The run key to which the node belongs.\n      graph_def: GraphDef to which the node belongs.\n\n    Raises:\n      ValueError: If `run_key` and/or `device_name` do not exist in the record."
  },
  {
    "code": "def iris(display=False):\n    d = sklearn.datasets.load_iris()\n    df = pd.DataFrame(data=d.data, columns=d.feature_names)\n    if display:\n        return df, [d.target_names[v] for v in d.target]\n    else:\n        return df, d.target",
    "docstring": "Return the classic iris data in a nice package."
  },
  {
    "code": "def GetTopLevel(self, file_object):\n    try:\n      top_level_object = biplist.readPlist(file_object)\n    except (biplist.InvalidPlistException,\n            biplist.NotBinaryPlistException) as exception:\n      raise errors.UnableToParseFile(\n          'Unable to parse plist with error: {0!s}'.format(exception))\n    return top_level_object",
    "docstring": "Returns the deserialized content of a plist as a dictionary object.\n\n    Args:\n      file_object (dfvfs.FileIO): a file-like object to parse.\n\n    Returns:\n      dict[str, object]: contents of the plist.\n\n    Raises:\n      UnableToParseFile: when the file cannot be parsed."
  },
  {
    "code": "def polyline(self, arr):\n        for i in range(0, len(arr) - 1):\n            self.line(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1])",
    "docstring": "Draw a set of lines"
  },
  {
    "code": "def application_name(self):\n        if self._application_name is None and self.units:\n            self._application_name = self.units[0].unit_name.split('/')[0]\n        return self._application_name",
    "docstring": "The name of the remote application for this relation, or ``None``.\n\n        This is equivalent to::\n\n            relation.units[0].unit_name.split('/')[0]"
  },
  {
    "code": "def visit_FunctionDef(self, node):\n        assert self.current_function is None\n        self.current_function = node\n        self.naming = dict()\n        self.in_cond = False\n        self.generic_visit(node)\n        self.current_function = None",
    "docstring": "Initialize variable for the current function to add edges from calls.\n\n        We compute variable to call dependencies and add edges when returns\n        are reach."
  },
  {
    "code": "def get_version(*args):\n    contents = get_contents(*args)\n    metadata = dict(re.findall('__([a-z]+)__ = [\\'\"]([^\\'\"]+)', contents))\n    return metadata['version']",
    "docstring": "Extract the version number from a Python module."
  },
  {
    "code": "def unfinished_objects(self):\n        mask = self._end_isnull\n        if self._rbound is not None:\n            mask = mask | (self._end > self._rbound)\n        oids = set(self[mask]._oid.tolist())\n        return self[self._oid.apply(lambda oid: oid in oids)]",
    "docstring": "Leaves only versions of those objects that has some version with\n        `_end == None` or with `_end > right cutoff`."
  },
  {
    "code": "def get_subdomain_info(fqn, db_path=None, atlasdb_path=None, zonefiles_dir=None, check_pending=False, include_did=False):\n    opts = get_blockstack_opts()\n    if not is_subdomains_enabled(opts):\n        log.warn(\"Subdomain support is disabled\")\n        return None\n    if db_path is None:\n        db_path = opts['subdomaindb_path']\n    if zonefiles_dir is None:\n        zonefiles_dir = opts['zonefiles']\n    if atlasdb_path is None:\n        atlasdb_path = opts['atlasdb_path']\n    db = SubdomainDB(db_path, zonefiles_dir)\n    try:\n        subrec = db.get_subdomain_entry(fqn)\n    except SubdomainNotFound:\n        log.warn(\"No such subdomain: {}\".format(fqn))\n        return None\n    if check_pending:\n        subrec.pending = db.subdomain_check_pending(subrec, atlasdb_path)\n    if include_did:\n        subrec.did_info = db.get_subdomain_DID_info(fqn)\n    return subrec",
    "docstring": "Static method for getting the state of a subdomain, given its fully-qualified name.\n    Return the subdomain record on success.\n    Return None if not found."
  },
  {
    "code": "def enable_caching(self):\n        \"Enable the cache of this object.\"\n        self.caching_enabled = True\n        for c in self.values():\n            c.enable_cacher()",
    "docstring": "Enable the cache of this object."
  },
  {
    "code": "def meld(*values):\n    values = [x for x in values if x is not None]\n    if not values:\n        return None\n    result = repeated(*values)\n    if isrepeating(result):\n        return result\n    return getvalue(result)",
    "docstring": "Return the repeated value, or the first value if there's only one.\n\n    This is a convenience function, equivalent to calling\n    getvalue(repeated(x)) to get x.\n\n    This function skips over instances of None in values (None is not allowed\n    in repeated variables).\n\n    Examples:\n        meld(\"foo\", \"bar\") # => ListRepetition(\"foo\", \"bar\")\n        meld(\"foo\", \"foo\") # => ListRepetition(\"foo\", \"foo\")\n        meld(\"foo\", None) # => \"foo\"\n        meld(None) # => None"
  },
  {
    "code": "def wc_wrap(text, length):\n    line_words = []\n    line_len = 0\n    words = re.split(r\"\\s+\", text.strip())\n    for word in words:\n        word_len = wcswidth(word)\n        if line_words and line_len + word_len > length:\n            line = \" \".join(line_words)\n            if line_len <= length:\n                yield line\n            else:\n                yield from _wc_hard_wrap(line, length)\n            line_words = []\n            line_len = 0\n        line_words.append(word)\n        line_len += word_len + 1\n    if line_words:\n        line = \" \".join(line_words)\n        if line_len <= length:\n            yield line\n        else:\n            yield from _wc_hard_wrap(line, length)",
    "docstring": "Wrap text to given length, breaking on whitespace and taking into account\n    character width.\n\n    Meant for use on a single line or paragraph. Will destroy spacing between\n    words and paragraphs and any indentation."
  },
  {
    "code": "def convert(input_file_name, **kwargs):\n    delimiter = kwargs[\"delimiter\"] or \",\"\n    quotechar = kwargs[\"quotechar\"] or \"|\"\n    if six.PY2:\n        delimiter = delimiter.encode(\"utf-8\")\n        quotechar = quotechar.encode(\"utf-8\")\n    with open(input_file_name, \"rb\") as input_file:\n        reader = csv.reader(input_file,\n                            encoding=\"utf-8\",\n                            delimiter=delimiter,\n                            quotechar=quotechar)\n        csv_headers = []\n        if not kwargs.get(\"no_header\"):\n            csv_headers = next(reader)\n        csv_rows = [row for row in reader if row]\n        if not csv_headers and len(csv_rows) > 0:\n            end = len(csv_rows[0]) + 1\n            csv_headers = [\"Column {}\".format(n) for n in range(1, end)]\n    html = render_template(csv_headers, csv_rows, **kwargs)\n    return freeze_js(html)",
    "docstring": "Convert CSV file to HTML table"
  },
  {
    "code": "def is_hex_string(string):\n    pattern = re.compile(r'[A-Fa-f0-9]+')\n    if isinstance(string, six.binary_type):\n        string = str(string)\n    return pattern.match(string) is not None",
    "docstring": "Check if the string is only composed of hex characters."
  },
  {
    "code": "def make_env(env_type, real_env, sim_env_kwargs):\n  return {\n      \"real\": lambda: real_env.new_like(\n          batch_size=sim_env_kwargs[\"batch_size\"],\n          store_rollouts=False,\n      ),\n      \"simulated\": lambda: rl_utils.SimulatedBatchGymEnvWithFixedInitialFrames(\n          **sim_env_kwargs\n      ),\n  }[env_type]()",
    "docstring": "Factory function for envs."
  },
  {
    "code": "def expr(s):\n    prog = re.compile('\\{([^}]+)\\}')\n    def repl(matchobj):\n        return \"rec['%s']\" % matchobj.group(1)\n    return eval(\"lambda rec: \" + prog.sub(repl, s))",
    "docstring": "Construct a function operating on a table record.\n\n    The expression string is converted into a lambda function by prepending\n    the string with ``'lambda rec: '``, then replacing anything enclosed in\n    curly braces (e.g., ``\"{foo}\"``) with a lookup on the record (e.g.,\n    ``\"rec['foo']\"``), then finally calling :func:`eval`.\n\n    So, e.g., the expression string ``\"{foo} * {bar}\"`` is converted to the\n    function ``lambda rec: rec['foo'] * rec['bar']``"
  },
  {
    "code": "def _api_group_for_type(cls):\n    _groups = {\n        (u\"v1beta1\", u\"Deployment\"): u\"extensions\",\n        (u\"v1beta1\", u\"DeploymentList\"): u\"extensions\",\n        (u\"v1beta1\", u\"ReplicaSet\"): u\"extensions\",\n        (u\"v1beta1\", u\"ReplicaSetList\"): u\"extensions\",\n    }\n    key = (\n        cls.apiVersion,\n        cls.__name__.rsplit(u\".\")[-1],\n    )\n    group = _groups.get(key, None)\n    return group",
    "docstring": "Determine which Kubernetes API group a particular PClass is likely to\n    belong with.\n\n    This is basically nonsense.  The question being asked is wrong.  An\n    abstraction has failed somewhere.  Fixing that will get rid of the need\n    for this."
  },
  {
    "code": "def _get_best_indexes(logits, n_best_size):\n    index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)\n    best_indexes = []\n    for i in range(len(index_and_score)):\n        if i >= n_best_size:\n            break\n        best_indexes.append(index_and_score[i][0])\n    return best_indexes",
    "docstring": "Get the n-best logits from a list."
  },
  {
    "code": "def apply_published_filter(self, queryset, operation, value):\n        if operation not in [\"after\", \"before\"]:\n            raise ValueError()\n        return queryset.filter(Published(**{operation: value}))",
    "docstring": "Add the appropriate Published filter to a given elasticsearch query.\n\n        :param queryset: The DJES queryset object to be filtered.\n        :param operation: The type of filter (before/after).\n        :param value: The date or datetime value being applied to the filter."
  },
  {
    "code": "def get_corpus_path(name: str) -> [str, None]:\n    db = TinyDB(corpus_db_path())\n    temp = Query()\n    if len(db.search(temp.name == name)) > 0:\n        path = get_full_data_path(db.search(temp.name == name)[0][\"file\"])\n        db.close()\n        if not os.path.exists(path):\n            download(name)\n        return path\n    return None",
    "docstring": "Get corpus path\n\n    :param string name: corpus name"
  },
  {
    "code": "def _create_fw_fab_dev_te(self, tenant_id, drvr_name, fw_dict):\n        is_fw_virt = self.is_device_virtual()\n        ret = self.fabric.prepare_fabric_fw(tenant_id, fw_dict, is_fw_virt,\n                                            fw_constants.RESULT_FW_CREATE_INIT)\n        if not ret:\n            LOG.error(\"Prepare Fabric failed\")\n            return\n        else:\n            self.update_fw_db_final_result(fw_dict.get('fw_id'), (\n                fw_constants.RESULT_FW_CREATE_DONE))\n        ret = self.create_fw_device(tenant_id, fw_dict.get('fw_id'),\n                                    fw_dict)\n        if ret:\n            self.fwid_attr[tenant_id].fw_drvr_created(True)\n            self.update_fw_db_dev_status(fw_dict.get('fw_id'), 'SUCCESS')\n            LOG.info(\"FW device create returned success for tenant %s\",\n                     tenant_id)\n        else:\n            LOG.error(\"FW device create returned failure for tenant %s\",\n                      tenant_id)",
    "docstring": "Prepares the Fabric and configures the device.\n\n        This routine calls the fabric class to prepare the fabric when\n        a firewall is created. It also calls the device manager to\n        configure the device. It updates the database with the final\n        result."
  },
  {
    "code": "def decode(symbol_string, checksum=False, strict=False):\n    symbol_string = normalize(symbol_string, strict=strict)\n    if checksum:\n        symbol_string, check_symbol = symbol_string[:-1], symbol_string[-1]\n    number = 0\n    for symbol in symbol_string:\n        number = number * base + decode_symbols[symbol]\n    if checksum:\n        check_value = decode_symbols[check_symbol]\n        modulo = number % check_base\n        if check_value != modulo:\n            raise ValueError(\"invalid check symbol '%s' for string '%s'\" %\n                             (check_symbol, symbol_string))\n    return number",
    "docstring": "Decode an encoded symbol string.\n\n    If checksum is set to True, the string is assumed to have a\n    trailing check symbol which will be validated. If the\n    checksum validation fails, a ValueError is raised.\n\n    If strict is set to True, a ValueError is raised if the\n    normalization step requires changes to the string.\n\n    The decoded string is returned."
  },
  {
    "code": "def format_content(content):\n    paragraphs = parse_html(content)\n    first = True\n    for paragraph in paragraphs:\n        if not first:\n            yield \"\"\n        for line in paragraph:\n            yield line\n        first = False",
    "docstring": "Given a Status contents in HTML, converts it into lines of plain text.\n\n    Returns a generator yielding lines of content."
  },
  {
    "code": "def get_filters_params(self, params=None):\n        if not params:\n            params = self.params\n        lookup_params = params.copy()\n        for ignored in IGNORED_PARAMS:\n            if ignored in lookup_params:\n                del lookup_params[ignored]\n        return lookup_params",
    "docstring": "Returns all params except IGNORED_PARAMS"
  },
  {
    "code": "def _simulate_installation_of(to_install, package_set):\n    installed = set()\n    for inst_req in to_install:\n        dist = make_abstract_dist(inst_req).dist()\n        name = canonicalize_name(dist.key)\n        package_set[name] = PackageDetails(dist.version, dist.requires())\n        installed.add(name)\n    return installed",
    "docstring": "Computes the version of packages after installing to_install."
  },
  {
    "code": "def grant_local_roles_for(brain_or_object, roles, user=None):\n    user_id = get_user_id(user)\n    obj = api.get_object(brain_or_object)\n    if isinstance(roles, basestring):\n        roles = [roles]\n    obj.manage_addLocalRoles(user_id, roles)\n    return get_local_roles_for(brain_or_object)",
    "docstring": "Grant local roles for the object\n\n    Code extracted from `IRoleManager.manage_addLocalRoles`\n\n    :param brain_or_object: Catalog brain or object\n    :param user: A user ID, user object or None (for the current user)\n    :param roles: The local roles to grant for the current user"
  },
  {
    "code": "def setupTxns(self, key, force: bool = False):\n        import data\n        dataDir = os.path.dirname(data.__file__)\n        allEnvs = {\n            \"local\": Environment(\"pool_transactions_local\",\n                                 \"domain_transactions_local\"),\n            \"test\": Environment(\"pool_transactions_sandbox\",\n                                \"domain_transactions_sandbox\"),\n            \"live\": Environment(\"pool_transactions_live\",\n                                \"domain_transactions_live\")\n        }\n        for env in allEnvs.values():\n            fileName = getattr(env, key, None)\n            if not fileName:\n                continue\n            sourceFilePath = os.path.join(dataDir, fileName)\n            if not os.path.exists(sourceFilePath):\n                continue\n            destFilePath = os.path.join(\n                self.base_dir, genesis_txn_file(fileName))\n            if os.path.exists(destFilePath) and not force:\n                continue\n            copyfile(sourceFilePath, destFilePath)\n        return self",
    "docstring": "Create base transactions\n\n        :param key: ledger\n        :param force: replace existing transaction files"
  },
  {
    "code": "def get_assembly_mapping_data(self, source_assembly, target_assembly):\n        return self._load_assembly_mapping_data(\n            self._get_path_assembly_mapping_data(source_assembly, target_assembly)\n        )",
    "docstring": "Get assembly mapping data.\n\n        Parameters\n        ----------\n        source_assembly : {'NCBI36', 'GRCh37', 'GRCh38'}\n            assembly to remap from\n        target_assembly : {'NCBI36', 'GRCh37', 'GRCh38'}\n            assembly to remap to\n\n        Returns\n        -------\n        dict\n            dict of json assembly mapping data if loading was successful, else None"
  },
  {
    "code": "def lineage(self):\n        indexes = six.moves.range(1, len(self.parts))\n        return {FieldPath(*self.parts[:index]) for index in indexes}",
    "docstring": "Return field paths for all parents.\n\n        Returns: Set[:class:`FieldPath`]"
  },
  {
    "code": "def operation(self, other, function, **kwargs):\n        result = TimeSeries(**kwargs)\n        if isinstance(other, TimeSeries):\n            for time, value in self:\n                result[time] = function(value, other[time])\n            for time, value in other:\n                result[time] = function(self[time], value)\n        else:\n            for time, value in self:\n                result[time] = function(value, other)\n        return result",
    "docstring": "Calculate \"elementwise\" operation either between this TimeSeries\n        and another one, i.e.\n\n        operation(t) = function(self(t), other(t))\n\n        or between this timeseries and a constant:\n\n        operation(t) = function(self(t), other)\n\n        If it's another time series, the measurement times in the\n        resulting TimeSeries will be the union of the sets of\n        measurement times of the input time series. If it's a\n        constant, the measurement times will not change."
  },
  {
    "code": "def update_preferences_by_category(self, category, communication_channel_id, notification_preferences_frequency):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"communication_channel_id\"] = communication_channel_id\r\n        path[\"category\"] = category\r\n        data[\"notification_preferences[frequency]\"] = notification_preferences_frequency\r\n        self.logger.debug(\"PUT /api/v1/users/self/communication_channels/{communication_channel_id}/notification_preference_categories/{category} with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"PUT\", \"/api/v1/users/self/communication_channels/{communication_channel_id}/notification_preference_categories/{category}\".format(**path), data=data, params=params, no_data=True)",
    "docstring": "Update preferences by category.\r\n\r\n        Change the preferences for multiple notifications based on the category for a single communication channel"
  },
  {
    "code": "def get_layout():\n    tica_msm = TemplateDir(\n        'tica',\n        [\n            'tica/tica.py',\n            'tica/tica-plot.py',\n            'tica/tica-sample-coordinate.py',\n            'tica/tica-sample-coordinate-plot.py',\n        ],\n        [\n            TemplateDir(\n                'cluster',\n                [\n                    'cluster/cluster.py',\n                    'cluster/cluster-plot.py',\n                    'cluster/sample-clusters.py',\n                    'cluster/sample-clusters-plot.py',\n                ],\n                [\n                    TemplateDir(\n                        'msm',\n                        [\n                            'msm/timescales.py',\n                            'msm/timescales-plot.py',\n                            'msm/microstate.py',\n                            'msm/microstate-plot.py',\n                            'msm/microstate-traj.py',\n                        ],\n                        [],\n                    )\n                ]\n            )\n        ]\n    )\n    layout = TemplateDir(\n        '',\n        [\n            '0-test-install.py',\n            '1-get-example-data.py',\n            'README.md',\n        ],\n        [\n            TemplateDir(\n                'analysis',\n                [\n                    'analysis/gather-metadata.py',\n                    'analysis/gather-metadata-plot.py',\n                ],\n                [\n                    TemplateDir(\n                        'rmsd',\n                        [\n                            'rmsd/rmsd.py',\n                            'rmsd/rmsd-plot.py',\n                        ],\n                        [],\n                    ),\n                    TemplateDir(\n                        'landmarks',\n                        [\n                            'landmarks/find-landmarks.py',\n                            'landmarks/featurize.py',\n                            'landmarks/featurize-plot.py',\n                        ],\n                        [tica_msm],\n                    ),\n                    TemplateDir(\n                        'dihedrals',\n                        [\n                            'dihedrals/featurize.py',\n                            'dihedrals/featurize-plot.py',\n                        ],\n                        [tica_msm],\n                    )\n                ]\n            )\n        ]\n    )\n    return layout",
    "docstring": "Specify a hierarchy of our templates."
  },
  {
    "code": "def _build_dependent_model_list(self, obj_schema):\n        dep_models_list = []\n        if obj_schema:\n            obj_schema['type'] = obj_schema.get('type', 'object')\n        if obj_schema['type'] == 'array':\n            dep_models_list.extend(self._build_dependent_model_list(obj_schema.get('items', {})))\n        else:\n            ref = obj_schema.get('$ref')\n            if ref:\n                ref_obj_model = ref.split(\"/\")[-1]\n                ref_obj_schema = self._models().get(ref_obj_model)\n                dep_models_list.extend(self._build_dependent_model_list(ref_obj_schema))\n                dep_models_list.extend([ref_obj_model])\n            else:\n                properties = obj_schema.get('properties')\n                if properties:\n                    for _, prop_obj_schema in six.iteritems(properties):\n                        dep_models_list.extend(self._build_dependent_model_list(prop_obj_schema))\n        return list(set(dep_models_list))",
    "docstring": "Helper function to build the list of models the given object schema is referencing."
  },
  {
    "code": "def save_loop(self):\n        last_hash = hash(repr(self.hosts))\n        while self.running:\n            eventlet.sleep(self.save_interval)\n            next_hash = hash(repr(self.hosts))\n            if next_hash != last_hash:\n                self.save()\n                last_hash = next_hash",
    "docstring": "Saves the state if it has changed."
  },
  {
    "code": "async def subscribe(self, topic):\n        if self.socket_type not in {SUB, XSUB}:\n            raise AssertionError(\n                \"A %s socket cannot subscribe.\" % self.socket_type.decode(),\n            )\n        self._subscriptions.append(topic)\n        tasks = [\n            asyncio.ensure_future(\n                peer.connection.local_subscribe(topic),\n                loop=self.loop,\n            )\n            for peer in self._peers\n            if peer.connection\n        ]\n        if tasks:\n            try:\n                await asyncio.wait(tasks, loop=self.loop)\n            finally:\n                for task in tasks:\n                    task.cancel()",
    "docstring": "Subscribe the socket to the specified topic.\n\n        :param topic: The topic to subscribe to."
  },
  {
    "code": "def host_info_getter(func, name=None):\n    name = name or func.__name__\n    host_info_gatherers[name] = func\n    return func",
    "docstring": "The decorated function is added to the process of collecting the host_info.\n\n    This just adds the decorated function to the global\n    ``sacred.host_info.host_info_gatherers`` dictionary.\n    The functions from that dictionary are used when collecting the host info\n    using :py:func:`~sacred.host_info.get_host_info`.\n\n    Parameters\n    ----------\n    func : callable\n        A function that can be called without arguments and returns some\n        json-serializable information.\n    name : str, optional\n        The name of the corresponding entry in host_info.\n        Defaults to the name of the function.\n\n    Returns\n    -------\n    The function itself."
  },
  {
    "code": "def install_python(name, version=None, install_args=None, override_args=False):\n    return install(name,\n                   version=version,\n                   source='python',\n                   install_args=install_args,\n                   override_args=override_args)",
    "docstring": "Instructs Chocolatey to install a package via Python's easy_install.\n\n    name\n        The name of the package to be installed. Only accepts a single argument.\n\n    version\n        Install a specific version of the package. Defaults to latest version\n        available.\n\n    install_args\n        A list of install arguments you want to pass to the installation process\n        i.e product key or feature list\n\n    override_args\n        Set to true if you want to override the original install arguments (for\n        the native installer) in the package and use your own. When this is set\n        to False install_args will be appended to the end of the default\n        arguments\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' chocolatey.install_python <package name>\n        salt '*' chocolatey.install_python <package name> version=<package version>\n        salt '*' chocolatey.install_python <package name> install_args=<args> override_args=True"
  },
  {
    "code": "def is_user_profile_valid(user_profile):\n  if not user_profile:\n    return False\n  if not type(user_profile) is dict:\n    return False\n  if UserProfile.USER_ID_KEY not in user_profile:\n    return False\n  if UserProfile.EXPERIMENT_BUCKET_MAP_KEY not in user_profile:\n    return False\n  experiment_bucket_map = user_profile.get(UserProfile.EXPERIMENT_BUCKET_MAP_KEY)\n  if not type(experiment_bucket_map) is dict:\n    return False\n  for decision in experiment_bucket_map.values():\n    if type(decision) is not dict or UserProfile.VARIATION_ID_KEY not in decision:\n      return False\n  return True",
    "docstring": "Determine if provided user profile is valid or not.\n\n  Args:\n    user_profile: User's profile which needs to be validated.\n\n  Returns:\n    Boolean depending upon whether profile is valid or not."
  },
  {
    "code": "def convert_entrez_to_uniprot(self, entrez):\n        server = \"http://www.uniprot.org/uniprot/?query=%22GENEID+{0}%22&format=xml\".format(entrez)\n        r = requests.get(server, headers={\"Content-Type\": \"text/xml\"})\n        if not r.ok:\n            r.raise_for_status()\n            sys.exit()\n        response = r.text\n        info = xmltodict.parse(response)\n        try:\n            data = info['uniprot']['entry']['accession'][0]\n            return data\n        except TypeError:\n            data = info['uniprot']['entry'][0]['accession'][0]\n            return data",
    "docstring": "Convert Entrez Id to Uniprot Id"
  },
  {
    "code": "def stem_word(self, word):\n        if self.is_plural(word):\n            return self.stem_plural_word(word)\n        else:\n            return self.stem_singular_word(word)",
    "docstring": "Stem a word to its common stem form."
  },
  {
    "code": "def get_all_attribute_value(\n        self, tag_name, attribute, format_value=True, **attribute_filter\n    ):\n        tags = self.find_tags(tag_name, **attribute_filter)\n        for tag in tags:\n            value = tag.get(attribute) or tag.get(self._ns(attribute))\n            if value is not None:\n                if format_value:\n                    yield self._format_value(value)\n                else:\n                    yield value",
    "docstring": "Yields all the attribute values in xml files which match with the tag name and the specific attribute\n\n        :param str tag_name: specify the tag name\n        :param str attribute: specify the attribute\n        :param bool format_value: specify if the value needs to be formatted with packagename"
  },
  {
    "code": "def _at_least_x_are_true(a, b, x):\n  match = tf.equal(a, b)\n  match = tf.cast(match, tf.int32)\n  return tf.greater_equal(tf.reduce_sum(match), x)",
    "docstring": "At least `x` of `a` and `b` `Tensors` are true."
  },
  {
    "code": "def _apply_post_render_hooks(self, data, obj, fmt):\n        hooks = self.post_render_hooks.get(fmt,[])\n        for hook in hooks:\n            try:\n                data = hook(data, obj)\n            except Exception as e:\n                self.param.warning(\"The post_render_hook %r could not \"\n                                   \"be applied:\\n\\n %s\" % (hook, e))\n        return data",
    "docstring": "Apply the post-render hooks to the data."
  },
  {
    "code": "def update(self, **kwargs):\n        svg_changed = False\n        for prop in kwargs:\n            if prop == \"drawing_id\":\n                pass\n            elif getattr(self, prop) != kwargs[prop]:\n                if prop == \"svg\":\n                    svg_changed = True\n                setattr(self, prop, kwargs[prop])\n        data = self.__json__()\n        if not svg_changed:\n            del data[\"svg\"]\n        self._project.controller.notification.emit(\"drawing.updated\", data)\n        self._project.dump()",
    "docstring": "Update the drawing\n\n        :param kwargs: Drawing properties"
  },
  {
    "code": "def _auto(direction, name, value, source='auto', convert_to_human=True):\n    if direction not in ['to', 'from']:\n        return value\n    props = property_data_zpool()\n    if source == 'zfs':\n        props = property_data_zfs()\n    elif source == 'auto':\n        props.update(property_data_zfs())\n    value_type = props[name]['type'] if name in props else 'str'\n    if value_type == 'size' and direction == 'to':\n        return globals()['{}_{}'.format(direction, value_type)](value, convert_to_human)\n    return globals()['{}_{}'.format(direction, value_type)](value)",
    "docstring": "Internal magic for from_auto and to_auto"
  },
  {
    "code": "def _list_subnets_by_identifier(self, identifier):\n        identifier = identifier.split('/', 1)[0]\n        results = self.list_subnets(identifier=identifier, mask='id')\n        return [result['id'] for result in results]",
    "docstring": "Returns a list of IDs of the subnet matching the identifier.\n\n        :param string identifier: The identifier to look up\n        :returns: List of matching IDs"
  },
  {
    "code": "def gfonts_repo_structure(fonts):\n  from fontbakery.utils import get_absolute_path\n  abspath = get_absolute_path(fonts[0])\n  return abspath.split(os.path.sep)[-3] in [\"ufl\", \"ofl\", \"apache\"]",
    "docstring": "The family at the given font path\n      follows the files and directory structure\n      typical of a font project hosted on\n      the Google Fonts repo on GitHub ?"
  },
  {
    "code": "def __Post(self, path, request, body, headers):\n        return synchronized_request.SynchronizedRequest(self,\n                                                        request,\n                                                        self._global_endpoint_manager,\n                                                        self.connection_policy,\n                                                        self._requests_session,\n                                                        'POST',\n                                                        path,\n                                                        body,\n                                                        query_params=None,\n                                                        headers=headers)",
    "docstring": "Azure Cosmos 'POST' http request.\n\n        :params str url:\n        :params str path:\n        :params (str, unicode, dict) body:\n        :params dict headers:\n\n        :return:\n            Tuple of (result, headers).\n        :rtype:\n            tuple of (dict, dict)"
  },
  {
    "code": "def findspan(self, *words):\n        for span in self.select(AbstractSpanAnnotation,None,True):\n            if tuple(span.wrefs()) == words:\n                return span\n        raise NoSuchAnnotation",
    "docstring": "Returns the span element which spans over the specified words or morphemes.\n\n        See also:\n            :meth:`Word.findspans`"
  },
  {
    "code": "def new_result(self, job, update_model=True):\n\t\tif not job.exception is None:\n\t\t\tself.logger.warning(\"job {} failed with exception\\n{}\".format(job.id, job.exception))",
    "docstring": "registers finished runs\n\n\t\tEvery time a run has finished, this function should be called\n\t\tto register it with the result logger. If overwritten, make\n\t\tsure to call this method from the base class to ensure proper\n\t\tlogging.\n\n\n\t\tParameters\n\t\t----------\n\t\tjob: instance of hpbandster.distributed.dispatcher.Job\n\t\t\tcontains all necessary information about the job\n\t\tupdate_model: boolean\n\t\t\tdetermines whether a model inside the config_generator should be updated"
  },
  {
    "code": "def __load_pst(self):\n        if self.pst_arg is None:\n            return None\n        if isinstance(self.pst_arg, Pst):\n            self.__pst = self.pst_arg\n            return self.pst\n        else:\n            try:\n                self.log(\"loading pst: \" + str(self.pst_arg))\n                self.__pst = Pst(self.pst_arg)\n                self.log(\"loading pst: \" + str(self.pst_arg))\n                return self.pst\n            except Exception as e:\n                raise Exception(\"linear_analysis.__load_pst(): error loading\"+\\\n                                \" pest control from argument: \" +\n                                str(self.pst_arg) + '\\n->' + str(e))",
    "docstring": "private method set the pst attribute"
  },
  {
    "code": "def request_output(self, table, outtype):\n        job_types = [\"CSV\", \"DataSet\", \"FITS\", \"VOTable\"]\n        assert outtype in job_types\n        params = {\"tableName\": table, \"type\": outtype}\n        r = self._send_request(\"SubmitExtractJob\", params=params)\n        job_id = int(self._parse_single(r.text, \"long\"))\n        return job_id",
    "docstring": "Request the output for a given table.\n\n        ## Arguments\n\n        * `table` (str): The name of the table to export.\n        * `outtype` (str): The type of output. Must be one of:\n            CSV     - Comma Seperated Values\n            DataSet - XML DataSet\n            FITS    - Flexible Image Transfer System (FITS Binary)\n            VOTable - XML Virtual Observatory VOTABLE"
  },
  {
    "code": "def network_size(value, options=None, version=None):\n    ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version)\n    if not ipaddr_filter_out:\n        return\n    if not isinstance(value, (list, tuple, types.GeneratorType)):\n        return _network_size(ipaddr_filter_out[0])\n    return [\n        _network_size(ip_a)\n        for ip_a in ipaddr_filter_out\n    ]",
    "docstring": "Get the size of a network."
  },
  {
    "code": "def check_aggregate(self, variable, components=None, exclude_on_fail=False,\n                        multiplier=1, **kwargs):\n        df_components = self.aggregate(variable, components)\n        if df_components is None:\n            return\n        rows = self._apply_filters(variable=variable)\n        df_variable, df_components = (\n            _aggregate(self.data[rows], 'variable').align(df_components)\n        )\n        diff = df_variable[~np.isclose(df_variable, multiplier * df_components,\n                                       **kwargs)]\n        if len(diff):\n            msg = '`{}` - {} of {} rows are not aggregates of components'\n            logger().info(msg.format(variable, len(diff), len(df_variable)))\n            if exclude_on_fail:\n                self._exclude_on_fail(diff.index.droplevel([2, 3, 4]))\n            return IamDataFrame(diff, variable=variable).timeseries()",
    "docstring": "Check whether a timeseries matches the aggregation of its components\n\n        Parameters\n        ----------\n        variable: str\n            variable to be checked for matching aggregation of sub-categories\n        components: list of str, default None\n            list of variables, defaults to all sub-categories of `variable`\n        exclude_on_fail: boolean, default False\n            flag scenarios failing validation as `exclude: True`\n        multiplier: number, default 1\n            factor when comparing variable and sum of components\n        kwargs: passed to `np.isclose()`"
  },
  {
    "code": "def alter_and_get(self, function):\n        check_not_none(function, \"function can't be None\")\n        return self._encode_invoke(atomic_reference_alter_and_get_codec, function=self._to_data(function))",
    "docstring": "Alters the currently stored reference by applying a function on it and gets the result.\n\n        :param function: (Function), A stateful serializable object which represents the Function defined on\n            server side.\n            This object must have a serializable Function counter part registered on server side with the actual\n            ``org.hazelcast.core.IFunction`` implementation.\n        :return: (object), the new value, the result of the applied function."
  },
  {
    "code": "def v4_int_to_packed(address):\n    if address > _BaseV4._ALL_ONES:\n        raise ValueError('Address too large for IPv4')\n    return Bytes(struct.pack('!I', address))",
    "docstring": "The binary representation of this address.\n\n    Args:\n        address: An integer representation of an IPv4 IP address.\n\n    Returns:\n        The binary representation of this address.\n\n    Raises:\n        ValueError: If the integer is too large to be an IPv4 IP\n          address."
  },
  {
    "code": "def submit(self,\n               workflow_uuid='',\n               experiment='',\n               image='',\n               cmd='',\n               prettified_cmd='',\n               workflow_workspace='',\n               job_name='',\n               cvmfs_mounts='false'):\n        job_spec = {\n            'experiment': experiment,\n            'docker_img': image,\n            'cmd': cmd,\n            'prettified_cmd': prettified_cmd,\n            'env_vars': {},\n            'workflow_workspace': workflow_workspace,\n            'job_name': job_name,\n            'cvmfs_mounts': cvmfs_mounts,\n            'workflow_uuid': workflow_uuid\n        }\n        response, http_response = self._client.jobs.create_job(job=job_spec).\\\n            result()\n        if http_response.status_code == 400:\n            raise HTTPBadRequest('Bad request to create a job. Error: {}'.\n                                 format(http_response.data))\n        elif http_response.status_code == 500:\n            raise HTTPInternalServerError('Internal Server Error. Error: {}'.\n                                          format(http_response.data))\n        return response",
    "docstring": "Submit a job to RJC API.\n\n        :param name: Name of the job.\n        :param experiment: Experiment the job belongs to.\n        :param image: Identifier of the Docker image which will run the job.\n        :param cmd: String which represents the command to execute. It can be\n            modified by the workflow engine i.e. prepending ``cd /some/dir/``.\n        :prettified_cmd: Original command submitted by the user.\n        :workflow_workspace: Path to the workspace of the workflow.\n        :cvmfs_mounts: String with CVMFS volumes to mount in job pods.\n        :return: Returns a dict with the ``job_id``."
  },
  {
    "code": "def drawdown_recov(self, return_int=False):\n        td = self.recov_date() - self.drawdown_end()\n        if return_int:\n            return td.days\n        return td",
    "docstring": "Length of drawdown recovery in days.\n\n        This is the duration from trough to recovery date.\n\n        Parameters\n        ----------\n        return_int : bool, default False\n            If True, return the number of days as an int.\n            If False, return a Pandas Timedelta object.\n\n        Returns\n        -------\n        int or pandas._libs.tslib.Timedelta"
  },
  {
    "code": "def start_response(self, status = 200, headers = [], clearheaders = True, disabletransferencoding = False):\n        \"Start to send response\"\n        if self._sendHeaders:\n            raise HttpProtocolException('Cannot modify response, headers already sent')\n        self.status = status\n        self.disabledeflate = disabletransferencoding\n        if clearheaders:\n            self.sent_headers = headers[:]\n        else:\n            self.sent_headers.extend(headers)",
    "docstring": "Start to send response"
  },
  {
    "code": "def _to_bstr(l):\n    if isinstance(l, str):\n        l = l.encode('ascii', 'backslashreplace')\n    elif not isinstance(l, bytes):\n        l = str(l).encode('ascii', 'backslashreplace')\n    return l",
    "docstring": "Convert to byte string."
  },
  {
    "code": "def setCurrentIndex(self, y, x):\r\n        self.dataTable.selectionModel().setCurrentIndex(\r\n            self.dataTable.model().index(y, x),\r\n            QItemSelectionModel.ClearAndSelect)",
    "docstring": "Set current selection."
  },
  {
    "code": "def send_to_tsdb(self, realm, host, service, metrics, ts, path):\n        if ts is None:\n            ts = int(time.time())\n        data = {\n            \"measurement\": service,\n            \"tags\": {\n                \"host\": host,\n                \"service\": service,\n                \"realm\": '.'.join(realm) if isinstance(realm, list) else realm,\n                \"path\": path\n            },\n            \"time\": ts,\n            \"fields\": {}\n        }\n        if path is not None:\n            data['tags'].update({\"path\": path})\n        for metric, value, _ in metrics:\n            data['fields'].update({metric: value})\n        logger.debug(\"Data: %s\", data)\n        self.my_metrics.append(data)\n        if self.metrics_count >= self.metrics_flush_count:\n            self.flush()",
    "docstring": "Send performance data to time series database\n\n        Indeed this function stores metrics in the internal cache and checks if the flushing\n        is necessary and then flushes.\n\n        :param realm: concerned realm\n        :type: string\n        :param host: concerned host\n        :type: string\n        :param service: concerned service\n        :type: string\n        :param metrics: list of metrics couple (name, value)\n        :type: list\n        :param ts: timestamp\n        :type: int\n        :param path: full path (eg. Graphite) for the received metrics\n        :type: string"
  },
  {
    "code": "def translate(self, from_lang=None, to=\"de\"):\n        if from_lang is None:\n            from_lang = self.translator.detect(self.string)\n        return self.translator.translate(self.string,\n                                         from_lang=from_lang, to_lang=to)",
    "docstring": "Translate the word to another language using Google's Translate API.\n\n        .. versionadded:: 0.5.0 (``textblob``)"
  },
  {
    "code": "def clear(self):\n        with self._conn:\n            self._conn.execute('DELETE FROM results')\n            self._conn.execute('DELETE FROM work_items')",
    "docstring": "Clear all work items from the session.\n\n        This removes any associated results as well."
  },
  {
    "code": "def as_pyplot_figure(self, label=1, **kwargs):\n        import matplotlib.pyplot as plt\n        exp = self.as_list(label=label, **kwargs)\n        fig = plt.figure()\n        vals = [x[1] for x in exp]\n        names = [x[0] for x in exp]\n        vals.reverse()\n        names.reverse()\n        colors = ['green' if x > 0 else 'red' for x in vals]\n        pos = np.arange(len(exp)) + .5\n        plt.barh(pos, vals, align='center', color=colors)\n        plt.yticks(pos, names)\n        if self.mode == \"classification\":\n            title = 'Local explanation for class %s' % self.class_names[label]\n        else:\n            title = 'Local explanation'\n        plt.title(title)\n        return fig",
    "docstring": "Returns the explanation as a pyplot figure.\n\n        Will throw an error if you don't have matplotlib installed\n        Args:\n            label: desired label. If you ask for a label for which an\n                   explanation wasn't computed, will throw an exception.\n                   Will be ignored for regression explanations.\n            kwargs: keyword arguments, passed to domain_mapper\n\n        Returns:\n            pyplot figure (barchart)."
  },
  {
    "code": "def on_init(app):\n    docs_path = os.path.abspath(os.path.dirname(__file__))\n    root_path = os.path.abspath(os.path.join(docs_path, '..'))\n    apidoc_path = 'sphinx-apidoc'\n    swg2rst_path = 'swg2rst'\n    if hasattr(sys, 'real_prefix'):\n        bin_path = os.path.abspath(os.path.join(sys.prefix, 'bin'))\n        apidoc_path = os.path.join(bin_path, apidoc_path)\n        swg2rst_path = os.path.join(bin_path, swg2rst_path)\n    check_call([apidoc_path, '-o', docs_path, os.path.join(root_path, 'user_tasks'),\n                os.path.join(root_path, 'user_tasks/migrations')])\n    json_path = os.path.join(docs_path, 'swagger.json')\n    rst_path = os.path.join(docs_path, 'rest_api.rst')\n    check_call([swg2rst_path, json_path, '-f', 'rst', '-o', rst_path])",
    "docstring": "Run sphinx-apidoc and swg2rst after Sphinx initialization.\n\n    Read the Docs won't run tox or custom shell commands, so we need this to\n    avoid checking in the generated reStructuredText files."
  },
  {
    "code": "def toProtocolElement(self):\n        gaFeatureSet = protocol.FeatureSet()\n        gaFeatureSet.id = self.getId()\n        gaFeatureSet.dataset_id = self.getParentContainer().getId()\n        gaFeatureSet.reference_set_id = pb.string(self._referenceSet.getId())\n        gaFeatureSet.name = self._name\n        gaFeatureSet.source_uri = self._sourceUri\n        attributes = self.getAttributes()\n        for key in attributes:\n            gaFeatureSet.attributes.attr[key] \\\n                .values.extend(protocol.encodeValue(attributes[key]))\n        return gaFeatureSet",
    "docstring": "Returns the representation of this FeatureSet as the corresponding\n        ProtocolElement."
  },
  {
    "code": "def hide_zeroes(self):\n        for v in self.subset_labels:\n            if v is not None and v.get_text() == '0':\n                v.set_visible(False)",
    "docstring": "Sometimes it makes sense to hide the labels for subsets whose size is zero.\n        This utility method does this."
  },
  {
    "code": "def iteritems(self):\n        for (key, val) in six.iteritems(self.__dict__):\n            if key in self._printable_exclude:\n                continue\n            yield (key, val)",
    "docstring": "Wow this class is messed up. I had to overwrite items when\n        moving to python3, just because I haden't called it yet"
  },
  {
    "code": "def print_examples(self, full=False):\n        msg = []\n        i = 1\n        for key in sorted(self.DEMOS.keys()):\n            example = self.DEMOS[key]\n            if full or example[\"show\"]:\n                msg.append(u\"Example %d (%s)\" % (i, example[u\"description\"]))\n                msg.append(u\"  $ %s %s\" % (self.invoke, key))\n                msg.append(u\"\")\n                i += 1\n        self.print_generic(u\"\\n\" + u\"\\n\".join(msg) + u\"\\n\")\n        return self.HELP_EXIT_CODE",
    "docstring": "Print the examples and exit.\n\n        :param bool full: if ``True``, print all examples; otherwise,\n                          print only selected ones"
  },
  {
    "code": "def on_btn_metadata(self, event):\n        if not self.check_for_meas_file():\n            return\n        if not self.check_for_uncombined_files():\n            return\n        if self.data_model_num == 2:\n            wait = wx.BusyInfo('Compiling required data, please wait...')\n            wx.SafeYield()\n            self.ErMagic_frame = ErMagicBuilder.MagIC_model_builder(self.WD, self, self.er_magic)\n        elif self.data_model_num == 3:\n            wait = wx.BusyInfo('Compiling required data, please wait...')\n            wx.SafeYield()\n            self.ErMagic_frame = ErMagicBuilder.MagIC_model_builder3(self.WD, self, self.contribution)\n        self.ErMagic_frame.Show()\n        self.ErMagic_frame.Center()\n        size = wx.DisplaySize()\n        size = (size[0] - 0.3 * size[0], size[1] - 0.3 * size[1])\n        self.ErMagic_frame.Raise()\n        del wait",
    "docstring": "Initiate the series of windows to add metadata\n        to the contribution."
  },
  {
    "code": "def _execute_select_commands(self, source, commands):\n        rows = {}\n        for tbl, command in tqdm(commands, total=len(commands), desc='Executing {0} select queries'.format(source)):\n            if tbl not in rows:\n                rows[tbl] = []\n            rows[tbl].extend(self.fetch(command, commit=True))\n        self._commit()\n        return rows",
    "docstring": "Execute select queries for all of the tables from a source database."
  },
  {
    "code": "def swear_word(self) -> str:\n        bad_words = self._data['words'].get('bad')\n        return self.random.choice(bad_words)",
    "docstring": "Get a random swear word.\n\n        :return: Swear word.\n\n        :Example:\n            Damn."
  },
  {
    "code": "def surface_projection_from_fault_data(cls, edges):\n        lons = []\n        lats = []\n        for edge in edges:\n            for point in edge:\n                lons.append(point.longitude)\n                lats.append(point.latitude)\n        lons = numpy.array(lons, dtype=float)\n        lats = numpy.array(lats, dtype=float)\n        return Mesh(lons, lats, depths=None).get_convex_hull()",
    "docstring": "Get a surface projection of the complex fault surface.\n\n        :param edges:\n            A list of horizontal edges of the surface as instances\n            of :class:`openquake.hazardlib.geo.line.Line`.\n        :returns:\n            Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon`\n            describing the surface projection of the complex fault."
  },
  {
    "code": "def retrieve_content(self):\n        path = self._construct_path_to_source_content()\n        res = self._http.get(path)\n        self._populated_fields['content'] = res['content']\n        return res['content']",
    "docstring": "Retrieve the content of a resource."
  },
  {
    "code": "def get_report_details(self, report_id, id_type=None):\n        params = {'idType': id_type}\n        resp = self._client.get(\"reports/%s\" % report_id, params=params)\n        return Report.from_dict(resp.json())",
    "docstring": "Retrieves a report by its ID.  Internal and external IDs are both allowed.\n\n        :param str report_id: The ID of the incident report.\n        :param str id_type: Indicates whether ID is internal or external.\n\n        :return: The retrieved |Report| object.\n\n        Example:\n\n        >>> report = ts.get_report_details(\"1a09f14b-ef8c-443f-b082-9643071c522a\")\n        >>> print(report)\n        {\n          \"id\": \"1a09f14b-ef8c-443f-b082-9643071c522a\",\n          \"created\": 1515571633505,\n          \"updated\": 1515620420062,\n          \"reportBody\": \"Employee reported suspect email.  We had multiple reports of suspicious email overnight ...\",\n          \"title\": \"Phishing Incident\",\n          \"enclaveIds\": [\n            \"ac6a0d17-7350-4410-bc57-9699521db992\"\n          ],\n          \"distributionType\": \"ENCLAVE\",\n          \"timeBegan\": 1479941278000\n        }"
  },
  {
    "code": "def secure_boot(self):\n        return secure_boot.SecureBoot(\n            self._conn, utils.get_subresource_path_by(self, 'SecureBoot'),\n            redfish_version=self.redfish_version)",
    "docstring": "Property to provide reference to `SecureBoot` instance\n\n        It is calculated once when the first time it is queried. On refresh,\n        this property gets reset."
  },
  {
    "code": "def _get_ilo_details(self):\n        manager_uri = '/rest/v1/Managers/1'\n        status, headers, manager = self._rest_get(manager_uri)\n        if status != 200:\n            msg = self._get_extended_error(manager)\n            raise exception.IloError(msg)\n        mtype = self._get_type(manager)\n        if (mtype not in ['Manager.0', 'Manager.1']):\n            msg = \"%s is not a valid Manager type \" % mtype\n            raise exception.IloError(msg)\n        return manager, manager_uri",
    "docstring": "Gets iLO details\n\n        :raises: IloError, on an error from iLO.\n        :raises: IloConnectionError, if iLO is not up after reset.\n        :raises: IloCommandNotSupportedError, if the command is not supported\n                 on the server."
  },
  {
    "code": "def _get_block_transaction_data(db: BaseDB, transaction_root: Hash32) -> Iterable[Hash32]:\n        transaction_db = HexaryTrie(db, root_hash=transaction_root)\n        for transaction_idx in itertools.count():\n            transaction_key = rlp.encode(transaction_idx)\n            if transaction_key in transaction_db:\n                yield transaction_db[transaction_key]\n            else:\n                break",
    "docstring": "Returns iterable of the encoded transactions for the given block header"
  },
  {
    "code": "def find_group_differences(groups1, groups2):\n    r\n    import utool as ut\n    item_to_others1 = {item: set(_group) - {item}\n                       for _group in groups1 for item in _group}\n    item_to_others2 = {item: set(_group) - {item}\n                       for _group in groups2 for item in _group}\n    flat_items1 = ut.flatten(groups1)\n    flat_items2 = ut.flatten(groups2)\n    flat_items = list(set(flat_items1 + flat_items2))\n    errors = []\n    item_to_error = {}\n    for item in flat_items:\n        others1 = item_to_others1.get(item, set([]))\n        others2 = item_to_others2.get(item, set([]))\n        missing1 = others1 - others2\n        missing2 = others2 - others1\n        error = len(missing1) + len(missing2)\n        if error > 0:\n            item_to_error[item] = error\n        errors.append(error)\n    total_error = sum(errors)\n    return total_error",
    "docstring": "r\"\"\"\n    Returns a measure of how disimilar two groupings are\n\n    Args:\n        groups1 (list): true grouping of items\n        groups2 (list): predicted grouping of items\n\n    CommandLine:\n        python -m utool.util_alg find_group_differences\n\n    SeeAlso:\n        vtool.group_indicies\n        vtool.apply_grouping\n\n    Example0:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_alg import *  # NOQA\n        >>> groups1 = [[1, 2, 3], [4], [5, 6], [7, 8], [9, 10, 11]]\n        >>> groups2 = [[1, 2, 11], [3, 4], [5, 6], [7], [8, 9], [10]]\n        >>> total_error = find_group_differences(groups1, groups2)\n        >>> result = ('total_error = %r' % (total_error,))\n        >>> print(result)\n        total_error = 20\n\n    Example1:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_alg import *  # NOQA\n        >>> groups1 = [[1, 2, 3], [4], [5, 6]]\n        >>> groups2 = [[1, 2, 3], [4], [5, 6]]\n        >>> total_error = find_group_differences(groups1, groups2)\n        >>> result = ('total_error = %r' % (total_error,))\n        >>> print(result)\n        total_error = 0\n\n    Example2:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_alg import *  # NOQA\n        >>> groups1 = [[1, 2, 3], [4], [5, 6]]\n        >>> groups2 = [[1, 2], [4], [5, 6]]\n        >>> total_error = find_group_differences(groups1, groups2)\n        >>> result = ('total_error = %r' % (total_error,))\n        >>> print(result)\n        total_error = 4\n\n    Ignore:\n        # Can this be done via sklearn label analysis?\n        # maybe no... the labels assigned to each component are arbitrary\n        # maybe if we label edges? likely too many labels.\n        groups1 = [[1, 2, 3], [4], [5, 6], [7, 8], [9, 10, 11]]\n        groups2 = [[1, 2, 11], [3, 4], [5, 6], [7], [8, 9], [10]]"
  },
  {
    "code": "def fetch_bug_details(self, bug_ids):\n        params = {'include_fields': 'product, component, priority, whiteboard, id'}\n        params['id'] = bug_ids\n        try:\n            response = self.session.get(settings.BZ_API_URL + '/rest/bug', headers=self.session.headers,\n                                        params=params, timeout=30)\n            response.raise_for_status()\n        except RequestException as e:\n            logger.warning('error fetching bugzilla metadata for bugs due to {}'.format(e))\n            return None\n        if response.headers['Content-Type'] == 'text/html; charset=UTF-8':\n            return None\n        data = response.json()\n        if 'bugs' not in data:\n            return None\n        return data['bugs']",
    "docstring": "Fetches bug metadata from bugzilla and returns an encoded\n           dict if successful, otherwise returns None."
  },
  {
    "code": "def _highlight(string, color):\n\tif CONFIG['color']:\n\t\tif color < 8:\n\t\t\treturn '\\033[{color}m{string}\\033[0m'.format(string = string, color = color+30)\n\t\telse:\n\t\t\treturn '\\033[{color}m{string}\\033[0m'.format(string = string, color = color+82)\n\telse:\n\t\treturn string",
    "docstring": "Return a string highlighted for a terminal."
  },
  {
    "code": "def set_device_scale(self, x_scale, y_scale):\n        cairo.cairo_surface_set_device_scale(self._pointer, x_scale, y_scale)\n        self._check_status()",
    "docstring": "Sets a scale that is multiplied to the device coordinates determined\n        by the CTM when drawing to surface.\n\n        One common use for this is to render to very high resolution display\n        devices at a scale factor, so that code that assumes 1 pixel will be a\n        certain size will still work.  Setting a transformation via\n        cairo_translate() isn't sufficient to do this, since functions like\n        cairo_device_to_user() will expose the hidden scale.\n\n        Note that the scale affects drawing to the surface as well as using the\n        surface in a source pattern.\n\n        :param x_scale: the scale in the X direction, in device units.\n        :param y_scale: the scale in the Y direction, in device units.\n\n        *New in cairo 1.14.*\n\n        *New in cairocffi 0.9.*"
  },
  {
    "code": "def get_resources(self, ids, cache=True):\n        client = local_session(self.manager.session_factory).client('dax')\n        return client.describe_clusters(ClusterNames=ids).get('Clusters')",
    "docstring": "Retrieve dax resources for serverless policies or related resources"
  },
  {
    "code": "def verify(password_hash, password):\n    ensure(len(password_hash) == PWHASH_SIZE,\n           \"The password hash must be exactly %s bytes long\" %\n           nacl.bindings.crypto_pwhash_scryptsalsa208sha256_STRBYTES,\n           raising=exc.ValueError)\n    return nacl.bindings.crypto_pwhash_scryptsalsa208sha256_str_verify(\n        password_hash, password\n    )",
    "docstring": "Takes the output of scryptsalsa208sha256 and compares it against\n    a user provided password to see if they are the same\n\n    :param password_hash: bytes\n    :param password: bytes\n    :rtype: boolean\n\n    .. versionadded:: 1.2"
  },
  {
    "code": "def OnCopy(self, event):\n        focus = self.main_window.FindFocus()\n        if isinstance(focus, wx.TextCtrl):\n            focus.Copy()\n        else:\n            selection = self.main_window.grid.selection\n            data = self.main_window.actions.copy(selection)\n            self.main_window.clipboard.set_clipboard(data)\n        event.Skip()",
    "docstring": "Clipboard copy event handler"
  },
  {
    "code": "def parentItem(self, value):\n        self._parentItem = value\n        self._recursiveSetNodePath(self._constructNodePath())",
    "docstring": "The parent item"
  },
  {
    "code": "def __do_parse(self, pattern_str):\n        in_ = antlr4.InputStream(pattern_str)\n        lexer = STIXPatternLexer(in_)\n        lexer.removeErrorListeners()\n        token_stream = antlr4.CommonTokenStream(lexer)\n        parser = STIXPatternParser(token_stream)\n        parser.removeErrorListeners()\n        error_listener = ParserErrorListener()\n        parser.addErrorListener(error_listener)\n        parser._errHandler = antlr4.BailErrorStrategy()\n        for i, lit_name in enumerate(parser.literalNames):\n            if lit_name == u\"<INVALID>\":\n                parser.literalNames[i] = parser.symbolicNames[i]\n        try:\n            tree = parser.pattern()\n            return tree\n        except antlr4.error.Errors.ParseCancellationException as e:\n            real_exc = e.args[0]\n            parser._errHandler.reportError(parser, real_exc)\n            six.raise_from(ParseException(error_listener.error_message),\n                           real_exc)",
    "docstring": "Parses the given pattern and returns the antlr parse tree.\n\n        :param pattern_str: The STIX pattern\n        :return: The parse tree\n        :raises ParseException: If there is a parse error"
  },
  {
    "code": "async def create(cls, destination: Union[int, Subnet],\n                     source: Union[int, Subnet], gateway_ip: str, metric: int):\n        params = {\n            \"gateway_ip\": gateway_ip,\n            \"metric\": metric,\n        }\n        if isinstance(source, Subnet):\n            params[\"source\"] = source.id\n        elif isinstance(source, int):\n            params[\"source\"] = source\n        if isinstance(destination, Subnet):\n            params[\"destination\"] = destination.id\n        elif isinstance(destination, int):\n            params[\"destination\"] = destination\n        return cls._object(await cls._handler.create(**params))",
    "docstring": "Create a `StaticRoute` in MAAS.\n\n        :param name: The name of the `StaticRoute` (optional, will be given a\n        default value if not specified).\n        :type name: `str`\n        :param description: A description of the `StaticRoute` (optional).\n        :type description: `str`\n        :param class_type: The class type of the `StaticRoute` (optional).\n        :type class_type: `str`\n        :returns: The created StaticRoute\n        :rtype: `StaticRoute`"
  },
  {
    "code": "def form_valid(self, form):\n        self.metric_slugs = [k.strip() for k in form.cleaned_data['metrics']]\n        return super(AggregateFormView, self).form_valid(form)",
    "docstring": "Pull the metrics from the submitted form, and store them as a\n        list of strings in ``self.metric_slugs``."
  },
  {
    "code": "def uniqify(list_):\n  \"inefficient on long lists; short lists only. preserves order.\"\n  a=[]\n  for x in list_:\n    if x not in a: a.append(x)\n  return a",
    "docstring": "inefficient on long lists; short lists only. preserves order."
  },
  {
    "code": "def guarded(meth):\n    @functools.wraps(meth)\n    def _check(self, *args, **kwargs):\n        self._check_conn_validity(meth.__name__)\n        return meth(self, *args, **kwargs)\n    return _check",
    "docstring": "A decorator to add a sanity check to ConnectionResource methods."
  },
  {
    "code": "def __sub(self, string: str = '') -> str:\n        replacer = self.random.choice(['_', '-'])\n        return re.sub(r'\\s+', replacer, string.strip())",
    "docstring": "Replace spaces in string.\n\n        :param string: String.\n        :return: String without spaces."
  },
  {
    "code": "def validate_serializer(serializer, _type):\n    if not issubclass(serializer, _type):\n        raise ValueError(\"Serializer should be an instance of {}\".format(_type.__name__))",
    "docstring": "Validates the serializer for given type.\n\n    :param serializer: (Serializer), the serializer to be validated.\n    :param _type: (Type), type to be used for serializer validation."
  },
  {
    "code": "def view(self, channel_names='auto',\n             gates=None,\n             diag_kw={}, offdiag_kw={},\n             gate_colors=None, **kwargs):\n        if channel_names == 'auto':\n            channel_names = list(self.channel_names)\n        def plot_region(channels, **kwargs):\n            if channels[0] == channels[1]:\n                channels = channels[0]\n            kind = 'histogram'\n            self.plot(channels, kind=kind, gates=gates,\n                      gate_colors=gate_colors, autolabel=False)\n        channel_list = np.array(list(channel_names), dtype=object)\n        channel_mat = [[(x, y) for x in channel_list] for y in channel_list]\n        channel_mat = DataFrame(channel_mat, columns=channel_list, index=channel_list)\n        kwargs.setdefault('wspace', 0.1)\n        kwargs.setdefault('hspace', 0.1)\n        return plot_ndpanel(channel_mat, plot_region, **kwargs)",
    "docstring": "Generates a matrix of subplots allowing for a quick way\n        to examine how the sample looks in different channels.\n\n        Parameters\n        ----------\n        channel_names : [list | 'auto']\n            List of channel names to plot.\n        offdiag_plot : ['histogram' | 'scatter']\n            Specifies the type of plot for the off-diagonal elements.\n        diag_kw : dict\n            Not implemented\n\n        Returns\n        ------------\n\n        axes references"
  },
  {
    "code": "def serialize_basic(self, data, data_type, **kwargs):\n        custom_serializer = self._get_custom_serializers(data_type, **kwargs)\n        if custom_serializer:\n            return custom_serializer(data)\n        if data_type == 'str':\n            return self.serialize_unicode(data)\n        return eval(data_type)(data)",
    "docstring": "Serialize basic builting data type.\n        Serializes objects to str, int, float or bool.\n\n        Possible kwargs:\n        - is_xml bool : If set, adapt basic serializers without the need for basic_types_serializers\n        - basic_types_serializers dict[str, callable] : If set, use the callable as serializer\n\n        :param data: Object to be serialized.\n        :param str data_type: Type of object in the iterable."
  },
  {
    "code": "def read_host_file(path):\n  res = []\n  for l in file(path).xreadlines():\n    hostname = l.strip()\n    if hostname:\n      res.append(hostname)\n  return res",
    "docstring": "Read the host file. Return a list of hostnames."
  },
  {
    "code": "def download(self, replace=False):\n        download_data(\n            self.url, self.signature, data_home=self.data_home,\n            replace=replace, extract=True\n        )",
    "docstring": "Download the dataset from the hosted Yellowbrick data store and save\n        it to the location specified by ``get_data_home``. The downloader\n        verifies the download completed successfully and safely by comparing\n        the expected signature with the SHA 256 signature of the downloaded\n        archive file.\n\n        Parameters\n        ----------\n        replace : bool, default: False\n            If the data archive already exists, replace the dataset. If this is\n            False and the dataset exists, an exception is raised."
  },
  {
    "code": "def delete_from_environment(self, environment, synchronous=True):\n        if isinstance(environment, Environment):\n            environment_id = environment.id\n        else:\n            environment_id = environment\n        response = client.delete(\n            '{0}/environments/{1}'.format(self.path(), environment_id),\n            **self._server_config.get_client_kwargs()\n        )\n        return _handle_response(response, self._server_config, synchronous)",
    "docstring": "Delete this content view version from an environment.\n\n        This method acts much like\n        :meth:`nailgun.entity_mixins.EntityDeleteMixin.delete`.  The\n        documentation on that method describes how the deletion procedure works\n        in general. This method differs only in accepting an ``environment``\n        parameter.\n\n        :param environment: A :class:`nailgun.entities.Environment` object. The\n            environment's ``id`` parameter *must* be specified. As a\n            convenience, an environment ID may be passed in instead of an\n            ``Environment`` object."
  },
  {
    "code": "def add_dependency(self, from_task_name, to_task_name):\n        logger.debug('Adding dependency from {0} to {1}'.format(from_task_name, to_task_name))\n        if not self.state.allow_change_graph:\n            raise DagobahError(\"job's graph is immutable in its current state: %s\"\n                               % self.state.status)\n        self.add_edge(from_task_name, to_task_name)\n        self.commit()",
    "docstring": "Add a dependency between two tasks."
  },
  {
    "code": "def register_for_app(\n        self, app_label=None, exclude_models=None, exclude_model_classes=None\n    ):\n        models = []\n        exclude_models = exclude_models or []\n        app_config = django_apps.get_app_config(app_label)\n        for model in app_config.get_models():\n            if model._meta.label_lower in exclude_models:\n                pass\n            elif exclude_model_classes and issubclass(model, exclude_model_classes):\n                pass\n            else:\n                models.append(model._meta.label_lower)\n        self.register(models)",
    "docstring": "Registers all models for this app_label."
  },
  {
    "code": "def make_urls_hyperlinks(text: str) -> str:\n    find_url = r\n    replace_url = r'<a href=\"\\1\">\\1</a>'\n    find_email = re.compile(r'([.\\w\\-]+@(\\w[\\w\\-]+\\.)+[\\w\\-]+)')\n    replace_email = r'<a href=\"mailto:\\1\">\\1</a>'\n    text = re.sub(find_url, replace_url, text)\n    text = re.sub(find_email, replace_email, text)\n    return text",
    "docstring": "Adds hyperlinks to text that appears to contain URLs.\n\n    See\n\n    - http://stackoverflow.com/questions/1071191\n\n      - ... except that double-replaces everything; e.g. try with\n        ``text = \"me@somewhere.com me@somewhere.com\"``\n\n    - http://stackp.online.fr/?p=19"
  },
  {
    "code": "def generate_exports():\n\tenv = []\n\tfor name in list_installed_genomes():\n\t    try:\n\t        g = Genome(name)\n\t        env_name = re.sub(r'[^\\w]+', \"_\", name).upper()\n\t        env.append(\"export {}={}\".format(env_name, g.filename))\n\t    except:\n\t        pass\n\treturn env",
    "docstring": "Print export commands for setting environment variables."
  },
  {
    "code": "def unstaged():\n    with conf.within_proj_dir():\n        status = shell.run(\n            'git status --porcelain',\n            capture=True,\n            never_pretend=True\n        ).stdout\n        results = []\n        for file_status in status.split(os.linesep):\n            if file_status.strip() and file_status[0] == ' ':\n                results.append(file_status[3:].strip())\n        return results",
    "docstring": "Return a list of unstaged files in the project repository.\n\n    Returns:\n        list[str]: The list of files not tracked by project git repo."
  },
  {
    "code": "def _saveState(self, path):\r\n        self.addSession()\n        self._save(str(self.n_sessions), path)",
    "docstring": "save current state and add a new state"
  },
  {
    "code": "def del_kwnkb(mapper, connection, target):\n    if(target.kbtype == KnwKB.KNWKB_TYPES['taxonomy']):\n        if os.path.isfile(target.get_filename()):\n            os.remove(target.get_filename())",
    "docstring": "Remove taxonomy file."
  },
  {
    "code": "def worker_stop(obj, worker_ids):\n    if len(worker_ids) == 0:\n        msg = 'Would you like to stop all workers?'\n    else:\n        msg = '\\n{}\\n\\n{}'.format('\\n'.join(worker_ids),\n                                  'Would you like to stop these workers?')\n    if click.confirm(msg, default=True, abort=True):\n        stop_worker(obj['config'],\n                    worker_ids=list(worker_ids) if len(worker_ids) > 0 else None)",
    "docstring": "Stop running workers.\n\n    \\b\n    WORKER_IDS: The IDs of the worker that should be stopped or none to stop them all."
  },
  {
    "code": "def _iter_grouped(self):\n        for indices in self._group_indices:\n            yield self._obj.isel(**{self._group_dim: indices})",
    "docstring": "Iterate over each element in this group"
  },
  {
    "code": "def compute_groups_matrix(groups):\n    if not groups:\n        return None\n    num_vars = len(groups)\n    unique_group_names = list(OrderedDict.fromkeys(groups))\n    number_of_groups = len(unique_group_names)\n    indices = dict([(x, i) for (i, x) in enumerate(unique_group_names)])\n    output = np.zeros((num_vars, number_of_groups), dtype=np.int)\n    for parameter_row, group_membership in enumerate(groups):\n        group_index = indices[group_membership]\n        output[parameter_row, group_index] = 1\n    return output, unique_group_names",
    "docstring": "Generate matrix which notes factor membership of groups\n\n    Computes a k-by-g matrix which notes factor membership of groups\n    where:\n        k is the number of variables (factors)\n        g is the number of groups\n    Also returns a g-length list of unique group_names whose positions\n    correspond to the order of groups in the k-by-g matrix\n\n    Arguments\n    ---------\n    groups : list\n        Group names corresponding to each variable\n\n    Returns\n    -------\n    tuple\n        containing group matrix assigning parameters to\n        groups and a list of unique group names"
  },
  {
    "code": "def _calculate_expires(self):\n        self._backend_client.expires = None\n        now = datetime.utcnow()\n        self._backend_client.expires = now + timedelta(seconds=self._config.timeout)",
    "docstring": "Calculates the session expiry using the timeout"
  },
  {
    "code": "def getShocks(self):\n        employed = self.eStateNow == 1.0\n        N = int(np.sum(employed))\n        newly_unemployed = drawBernoulli(N,p=self.UnempPrb,seed=self.RNG.randint(0,2**31-1))\n        self.eStateNow[employed] = 1.0 - newly_unemployed",
    "docstring": "Determine which agents switch from employment to unemployment.  All unemployed agents remain\n        unemployed until death.\n\n        Parameters\n        ----------\n        None\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def remove_prefix(self, prefix):\n        if prefix not in self.__prefix_map:\n            return\n        ni = self.__lookup_prefix(prefix)\n        ni.prefixes.discard(prefix)\n        del self.__prefix_map[prefix]\n        if ni.preferred_prefix == prefix:\n            ni.preferred_prefix = next(iter(ni.prefixes), None)",
    "docstring": "Removes prefix from this set.  This is a no-op if the prefix\n        doesn't exist in it."
  },
  {
    "code": "def create_alert_policy(self, policy_name):\n    policy_data = { 'policy': { 'incident_preference': 'PER_POLICY', 'name': policy_name } }\n    create_policy = requests.post(\n      'https://api.newrelic.com/v2/alerts_policies.json',\n      headers=self.auth_header,\n      data=json.dumps(policy_data))\n    create_policy.raise_for_status()\n    policy_id = create_policy.json()['policy']['id']\n    self.refresh_all_alerts()\n    return policy_id",
    "docstring": "Creates an alert policy in NewRelic"
  },
  {
    "code": "def units_convertible(units1, units2, reftimeistime=True):\n    try:\n        u1 = Unit(units1)\n        u2 = Unit(units2)\n    except ValueError:\n        return False\n    return u1.is_convertible(u2)",
    "docstring": "Return True if a Unit representing the string units1 can be converted\n    to a Unit representing the string units2, else False.\n\n    :param str units1: A string representing the units\n    :param str units2: A string representing the units"
  },
  {
    "code": "def rows(self, *args) -> List[List[Well]]:\n        row_dict = self._create_indexed_dictionary(group=1)\n        keys = sorted(row_dict)\n        if not args:\n            res = [row_dict[key] for key in keys]\n        elif isinstance(args[0], int):\n            res = [row_dict[keys[idx]] for idx in args]\n        elif isinstance(args[0], str):\n            res = [row_dict[idx] for idx in args]\n        else:\n            raise TypeError\n        return res",
    "docstring": "Accessor function used to navigate through a labware by row.\n\n        With indexing one can treat it as a typical python nested list.\n        To access row A for example, simply write: labware.rows()[0]. This\n        will output ['A1', 'A2', 'A3', 'A4'...]\n\n        Note that this method takes args for backward-compatibility, but use\n        of args is deprecated and will be removed in future versions. Args\n        can be either strings or integers, but must all be the same type (e.g.:\n        `self.rows(1, 4, 8)` or `self.rows('A', 'B')`, but  `self.rows('A', 4)`\n        is invalid.\n\n        :return: A list of row lists"
  },
  {
    "code": "def ssh(ctx, cluster_id, key_file):\n    session = create_session(ctx.obj['AWS_PROFILE_NAME'])\n    client = session.client('emr')\n    result = client.describe_cluster(ClusterId=cluster_id)\n    target_dns = result['Cluster']['MasterPublicDnsName']\n    ssh_options = '-o StrictHostKeyChecking=no -o ServerAliveInterval=10'\n    cmd = 'ssh {ssh_options}  -i {key_file} hadoop@{target_dns}'.format(\n        ssh_options=ssh_options, key_file=key_file, target_dns=target_dns)\n    subprocess.call(cmd, shell=True)",
    "docstring": "SSH login to EMR master node"
  },
  {
    "code": "def trimsquants(self, col: str, sup: float):\n        try:\n            self.df = self._trimquants(col, None, sup)\n        except Exception as e:\n            self.err(e, self.trimsquants, \"Can not trim superior quantiles\")",
    "docstring": "Remove superior quantiles from the dataframe\n\n        :param col: column name\n        :type col: str\n        :param sup: superior quantile\n        :type sup: float\n\n        :example: ``ds.trimsquants(\"Col 1\", 0.99)``"
  },
  {
    "code": "def plot_estimates(positions, estimates):\n    x = list(positions)\n    fig = plt.figure(figsize=(SUBPLOT_WIDTH * len(estimates), FIGURE_HEIGHT))\n    for i, (title, y) in enumerate(zip(ESTIMATE_TITLES, estimates)):\n        ax = fig.add_subplot(1, len(estimates), i + 1)\n        ax.plot(x, y, linewidth=LINE_WIDTH, c=LINE_COLOR)\n        ax.title.set_text(title)\n        ax.set_xlim(0, 1)\n        ax.set_xlabel(\"position\")\n        ax.set_ylabel(\"$\\\\hat P$\")\n        ax.grid()\n    return fig",
    "docstring": "Plots density, and probability estimates.\n\n    Parameters\n    ----------\n    positions : iterable of float\n        Paragraph positions for which densities, and probabilities were estimated.\n    estimates : six-tuple of (sequence of float)\n        Estimates of P(relevant), p(position), p(position | relevant), P(position, relevant), and\n        P(relevant | position).\n\n    Returns\n    -------\n    matplotlib.figure.Figure\n        The plotted figure."
  },
  {
    "code": "def natural_neighbor_to_grid(xp, yp, variable, grid_x, grid_y):\n    r\n    points_obs = list(zip(xp, yp))\n    points_grid = generate_grid_coords(grid_x, grid_y)\n    img = natural_neighbor_to_points(points_obs, variable, points_grid)\n    return img.reshape(grid_x.shape)",
    "docstring": "r\"\"\"Generate a natural neighbor interpolation of the given points to a regular grid.\n\n    This assigns values to the given grid using the Liang and Hale [Liang2010]_.\n    approach.\n\n    Parameters\n    ----------\n    xp: (N, ) ndarray\n        x-coordinates of observations\n    yp: (N, ) ndarray\n        y-coordinates of observations\n    variable: (N, ) ndarray\n        observation values associated with (xp, yp) pairs.\n        IE, variable[i] is a unique observation at (xp[i], yp[i])\n    grid_x: (M, 2) ndarray\n        Meshgrid associated with x dimension\n    grid_y: (M, 2) ndarray\n        Meshgrid associated with y dimension\n\n    Returns\n    -------\n    img: (M, N) ndarray\n        Interpolated values on a 2-dimensional grid\n\n    See Also\n    --------\n    natural_neighbor_to_points"
  },
  {
    "code": "def get_analysis_data_by_title(self, ar_data, title):\n        analyses = ar_data.get(\"analyses\", [])\n        for analysis in analyses:\n            if analysis.get(\"title\") == title:\n                return analysis\n        return None",
    "docstring": "A template helper to pick an Analysis identified by the name of the\n        current Analysis Service.\n\n        ar_data is the dictionary structure which is returned by _ws_data"
  },
  {
    "code": "def first_location_of_minimum(x):\n    if not isinstance(x, (np.ndarray, pd.Series)):\n        x = np.asarray(x)\n    return np.argmin(x) / len(x) if len(x) > 0 else np.NaN",
    "docstring": "Returns the first location of the minimal value of x.\n    The position is calculated relatively to the length of x.\n\n    :param x: the time series to calculate the feature of\n    :type x: numpy.ndarray\n    :return: the value of this feature\n    :return type: float"
  },
  {
    "code": "def _apply_replacement(error, found_file, file_lines):\n    fixed_lines = file_lines\n    fixed_lines[error[1].line - 1] = error[1].replacement\n    concatenated_fixed_lines = \"\".join(fixed_lines)\n    found_file.seek(0)\n    found_file.write(concatenated_fixed_lines)\n    found_file.truncate()",
    "docstring": "Apply a single replacement."
  },
  {
    "code": "def get_es(urls=None, timeout=DEFAULT_TIMEOUT, force_new=False, **settings):\n    urls = urls or DEFAULT_URLS\n    if 'hosts' in settings:\n        raise DeprecationWarning('\"hosts\" is deprecated in favor of \"urls\".')\n    if not force_new:\n        key = _build_key(urls, timeout, **settings)\n        if key in _cached_elasticsearch:\n            return _cached_elasticsearch[key]\n    es = Elasticsearch(urls, timeout=timeout, **settings)\n    if not force_new:\n        _cached_elasticsearch[key] = es\n    return es",
    "docstring": "Create an elasticsearch `Elasticsearch` object and return it.\n\n    This will aggressively re-use `Elasticsearch` objects with the\n    following rules:\n\n    1. if you pass the same argument values to `get_es()`, then it\n       will return the same `Elasticsearch` object\n    2. if you pass different argument values to `get_es()`, then it\n       will return different `Elasticsearch` object\n    3. it caches each `Elasticsearch` object that gets created\n    4. if you pass in `force_new=True`, then you are guaranteed to get\n       a fresh `Elasticsearch` object AND that object will not be\n       cached\n\n    :arg urls: list of uris; Elasticsearch hosts to connect to,\n        defaults to ``['http://localhost:9200']``\n    :arg timeout: int; the timeout in seconds, defaults to 5\n    :arg force_new: Forces get_es() to generate a new Elasticsearch\n        object rather than pulling it from cache.\n    :arg settings: other settings to pass into Elasticsearch\n        constructor; See\n        `<http://elasticsearch-py.readthedocs.org/>`_ for more details.\n\n    Examples::\n\n        # Returns cached Elasticsearch object\n        es = get_es()\n\n        # Returns a new Elasticsearch object\n        es = get_es(force_new=True)\n\n        es = get_es(urls=['localhost'])\n\n        es = get_es(urls=['localhost:9200'], timeout=10,\n                    max_retries=3)"
  },
  {
    "code": "def update_video_image(edx_video_id, course_id, image_data, file_name):\n    try:\n        course_video = CourseVideo.objects.select_related('video').get(\n            course_id=course_id, video__edx_video_id=edx_video_id\n        )\n    except ObjectDoesNotExist:\n        error_message = u'VAL: CourseVideo not found for edx_video_id: {0} and course_id: {1}'.format(\n            edx_video_id,\n            course_id\n        )\n        raise ValVideoNotFoundError(error_message)\n    video_image, _ = VideoImage.create_or_update(course_video, file_name, image_data)\n    return video_image.image_url()",
    "docstring": "Update video image for an existing video.\n\n    NOTE: If `image_data` is None then `file_name` value will be used as it is, otherwise\n    a new file name is constructed based on uuid and extension from `file_name` value.\n    `image_data` will be None in case of course re-run and export.\n\n    Arguments:\n        image_data (InMemoryUploadedFile): Image data to be saved for a course video.\n\n    Returns:\n        course video image url\n\n    Raises:\n        Raises ValVideoNotFoundError if the CourseVideo cannot be retrieved."
  },
  {
    "code": "def deactivate_(self):\n        self.preDeactivate_()\n        self.active = False\n        self.image_dimensions = None\n        self.client = None",
    "docstring": "Init shmem variables to None"
  },
  {
    "code": "def item_frequency(sa, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT):\n    if (not isinstance(sa, tc.data_structures.sarray.SArray) or\n        sa.dtype != str):\n        raise ValueError(\"turicreate.visualization.item_frequency supports \" + \n            \"SArrays of dtype str\")\n    title = _get_title(title)\n    plt_ref = tc.extensions.plot_item_frequency(sa, \n      xlabel, ylabel, title)\n    return Plot(plt_ref)",
    "docstring": "Plots an item frequency of the sarray provided as input, and returns the \n    resulting Plot object.\n    \n    The function supports SArrays with dtype str.\n\n    Parameters\n    ----------\n    sa : SArray\n      The data to get an item frequency for. Must have dtype str\n    xlabel : str (optional)\n      The text label for the X axis. Defaults to \"Values\".\n    ylabel : str (optional)\n      The text label for the Y axis. Defaults to \"Count\".\n    title : str (optional)\n      The title of the plot. Defaults to LABEL_DEFAULT. If the value is\n      LABEL_DEFAULT, the title will be \"<xlabel> vs. <ylabel>\". If the value\n      is None, the title will be omitted. Otherwise, the string passed in as the\n      title will be used as the plot title.\n    \n    Returns\n    -------\n    out : Plot\n      A :class: Plot object that is the item frequency plot.\n\n    Examples\n    --------\n    Make an item frequency of an SArray.\n\n    >>> x = turicreate.SArray(['a','ab','acd','ab','a','a','a','ab','cd'])\n    >>> ifplt = turicreate.visualization.item_frequency(x)"
  },
  {
    "code": "def __callback(self, data):\n        method = self.__cb_message\n        if method is not None:\n            try:\n                method(data)\n            except Exception as ex:\n                _logger.exception(\"Error calling method: %s\", ex)",
    "docstring": "Safely calls back a method\n\n        :param data: Associated stanza"
  },
  {
    "code": "def set_value(self, dry_wet: LeakSensorState):\n        value = 0\n        if dry_wet == self._dry_wet_type:\n            value = 1\n        self._update_subscribers(value)",
    "docstring": "Set the value of the state to dry or wet."
  },
  {
    "code": "def tt_avg(self, print_output=True, output_file=\"tt.csv\"):\n        avg = self.tt.mean(axis=2)\n        if print_output:\n            np.savetxt(output_file, avg, delimiter=\",\")\n        return avg",
    "docstring": "Compute average term-topic matrix, and print to file if\n        print_output=True."
  },
  {
    "code": "def dilate(self, size):\n        if size > 0:\n            from scipy.ndimage.morphology import binary_dilation\n            size = (size * 2) + 1\n            coords = self.coordinates\n            tmp = zeros(self.extent + size * 2)\n            coords = (coords - self.bbox[0:len(self.center)] + size)\n            tmp[coords.T.tolist()] = 1\n            tmp = binary_dilation(tmp, ones((size, size)))\n            new = asarray(where(tmp)).T + self.bbox[0:len(self.center)] - size\n            new = [c for c in new if all(c >= 0)]\n        else:\n            return self\n        return one(new)",
    "docstring": "Dilate a region using morphological operators.\n\n        Parameters\n        ----------\n        size : int\n            Size of dilation in pixels"
  },
  {
    "code": "def find_module(self, fullname, path=None):\n        basepaths = [\"\"] + list(sys.path)\n        if fullname.startswith(\".\"):\n            if path is None:\n                return None\n            fullname = fullname[1:]\n            basepaths.insert(0, path)\n        fullpath = os.path.join(*fullname.split(\".\"))\n        for head in basepaths:\n            path = os.path.join(head, fullpath)\n            filepath = path + self.ext\n            dirpath = os.path.join(path, \"__init__\" + self.ext)\n            if os.path.exists(filepath):\n                self.run_compiler(filepath)\n                return None\n            if os.path.exists(dirpath):\n                self.run_compiler(path)\n                return None\n        return None",
    "docstring": "Searches for a Coconut file of the given name and compiles it."
  },
  {
    "code": "def do_static_merge(cls, c_source, c_target):\n        c_target.extend(c_source)\n        c_source.parent = c_target.parent\n        cls.CLUSTERS.remove(c_source)\n        for m in c_source.mentions:\n            cls.MENTION_TO_CLUSTER[m] = c_target",
    "docstring": "By the time we're just folding in clusters, there's no need to maintain\n        self.INSTANCES and self.clusters, so we just call this method"
  },
  {
    "code": "def prepare(self, context):\n\t\tif __debug__:\n\t\t\tlog.debug(\"Preparing request context.\", extra=dict(request=id(context)))\n\t\tcontext.request = Request(context.environ)\n\t\tcontext.response = Response(request=context.request)\n\t\tcontext.environ['web.base'] = context.request.script_name\n\t\tcontext.request.remainder = context.request.path_info.split('/')\n\t\tif context.request.remainder and not context.request.remainder[0]:\n\t\t\tdel context.request.remainder[0]\n\t\tcontext.path = Bread()",
    "docstring": "Add the usual suspects to the context.\n\t\t\n\t\tThis adds `request`, `response`, and `path` to the `RequestContext` instance."
  },
  {
    "code": "def css(app, env):\n    srcdir = os.path.abspath(os.path.dirname(__file__))\n    cssfile = 'bolditalic.css'\n    csspath = os.path.join(srcdir, cssfile)\n    buildpath = os.path.join(app.outdir, '_static')\n    try:\n        os.makedirs(buildpath)\n    except OSError:\n        if not os.path.isdir(buildpath):\n            raise\n    copy(csspath, buildpath)\n    app.add_stylesheet(cssfile)\n    return",
    "docstring": "Add bolditalic CSS.\n\n    :param app: Sphinx application context.\n    :param env: Sphinx environment context."
  },
  {
    "code": "def submit_sms_conversion(self, message_id, delivered=True, timestamp=None):\n        params = {\n            \"message-id\": message_id,\n            \"delivered\": delivered,\n            \"timestamp\": timestamp or datetime.now(pytz.utc),\n        }\n        _format_date_param(params, \"timestamp\")\n        return self.post(self.api_host, \"/conversions/sms\", params)",
    "docstring": "Notify Nexmo that an SMS was successfully received.\n\n        :param message_id: The `message-id` str returned by the send_message call.\n        :param delivered: A `bool` indicating that the message was or was not successfully delivered.\n        :param timestamp: A `datetime` object containing the time the SMS arrived.\n        :return: The parsed response from the server. On success, the bytestring b'OK'"
  },
  {
    "code": "def quantiles(x, qlist=(2.5, 25, 50, 75, 97.5)):\n    x = x.copy()\n    if x.ndim > 1:\n        sx = sort(x.T).T\n    else:\n        sx = sort(x)\n    try:\n        quants = [sx[int(len(sx) * q / 100.0)] for q in qlist]\n        return dict(zip(qlist, quants))\n    except IndexError:\n        print_(\"Too few elements for quantile calculation\")",
    "docstring": "Returns a dictionary of requested quantiles from array\n\n    :Arguments:\n      x : Numpy array\n          An array containing MCMC samples\n      qlist : tuple or list\n          A list of desired quantiles (defaults to (2.5, 25, 50, 75, 97.5))"
  },
  {
    "code": "def build_job(name=None, parameters=None):\n    if not name:\n        raise SaltInvocationError('Required parameter \\'name\\' is missing')\n    server = _connect()\n    if not job_exists(name):\n        raise CommandExecutionError('Job \\'{0}\\' does not exist.'.format(name))\n    try:\n        server.build_job(name, parameters)\n    except jenkins.JenkinsException as err:\n        raise CommandExecutionError(\n            'Encountered error building job \\'{0}\\': {1}'.format(name, err)\n        )\n    return True",
    "docstring": "Initiate a build for the provided job.\n\n    :param name: The name of the job is check if it exists.\n    :param parameters: Parameters to send to the job.\n    :return: True is successful, otherwise raise an exception.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' jenkins.build_job jobname"
  },
  {
    "code": "def get_generation_code(self, **gencode):\n        channels, verts = self.coordinates\n        channels = ', '.join([\"'{}'\".format(ch) for ch in channels])\n        verts = list(verts)\n        if len(verts) == 1:\n            verts = verts[0]\n            if len(verts) == 1:\n                verts = verts[0]\n        verts = apply_format(verts, '{:.3e}')\n        gencode.setdefault('name', self.name)\n        gencode.setdefault('region', self.region)\n        gencode.setdefault('gate_type', self._gencode_gate_class)\n        gencode.setdefault('verts', verts)\n        gencode.setdefault('channels', channels)\n        format_string = \"{name} = {gate_type}({verts}, ({channels}), region='{region}', name='{name}')\"\n        return format_string.format(**gencode)",
    "docstring": "Generates python code that can create the gate."
  },
  {
    "code": "def is_ip(string):\n    mo = re.match(r'(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)', string)\n    if mo is None:\n        return False\n    for group in mo.groups():\n        if int(group) not in list(range(0, 256)):\n            return False\n    return True",
    "docstring": "Returns True if the given string is an IPv4 address, False otherwise.\n\n    :type  string: string\n    :param string: Any string.\n    :rtype:  bool\n    :return: True if the string is an IP address, False otherwise."
  },
  {
    "code": "def _desy_bookkeeping2marc(self, key, value):\n    if 'identifier' not in value:\n        return {\n            'a': value.get('expert'),\n            'd': value.get('date'),\n            's': value.get('status'),\n        }\n    self.setdefault('035', []).append({\n        '9': 'DESY',\n        'z': value['identifier']\n    })",
    "docstring": "Populate the ``595_D`` MARC field.\n\n    Also populates the ``035`` MARC field through side effects."
  },
  {
    "code": "def canonicalize_half_turns(\n        half_turns: Union[sympy.Basic, float]\n) -> Union[sympy.Basic, float]:\n    if isinstance(half_turns, sympy.Basic):\n        return half_turns\n    half_turns %= 2\n    if half_turns > 1:\n        half_turns -= 2\n    return half_turns",
    "docstring": "Wraps the input into the range (-1, +1]."
  },
  {
    "code": "def sar(patch, cols, splits, divs, ear=False):\n    def sar_y_func(spatial_table, all_spp):\n        return np.mean(spatial_table['n_spp'])\n    def ear_y_func(spatial_table, all_spp):\n        endemic_counter = 0\n        for spp in all_spp:\n            spp_in_cell = [spp in x for x in spatial_table['spp_set']]\n            spp_n_cells = np.sum(spp_in_cell)\n            if spp_n_cells == 1:\n                endemic_counter += 1\n        n_cells = len(spatial_table)\n        return endemic_counter / n_cells\n    if ear:\n        y_func = ear_y_func\n    else:\n        y_func = sar_y_func\n    return _sar_ear_inner(patch, cols, splits, divs, y_func)",
    "docstring": "Calculates an empirical species area or endemics area relationship\n\n    Parameters\n    ----------\n    {0}\n    divs : str\n        Description of how to divide x_col and y_col. See notes.\n    ear : bool\n        If True, calculates an endemics area relationship\n\n    Returns\n    -------\n    {1} Result has 5 columns; div, x, and y; that give the ID for the\n    division given as an argument, fractional area, and the mean species\n    richness at that division.\n\n    Notes\n    -----\n    {2}\n\n    For the SAR and EAR, cols must also contain x_col and y_col, giving the x\n    and y dimensions along which to grid the patch.\n\n    {3}\n\n    {4}\n\n    Examples\n    --------\n\n    {5}\n\n    >>> # Get the SAR at the full area (1,1), 1 x 2 division,\n    >>> # 2 x 1 division, 2 x 2 division, 2 x 4 division, 4 x 2 division, and\n    >>> # 4 x 4 division\n    >>> sar = meco.empirical.sar(pat,\n                cols='spp_col:spp; count_col:count; x_col:row; y_col:column',\n                splits=\"\",\n                divs=\"1,1; 1,2; 2,1; 2,2; 2,4; 4,2; 4,4\")\n\n    >>> sar[0][1]\n       div  n_individs    n_spp   x        y\n    0  1,1   2445.0000  24.0000  16  24.0000\n    1  1,2   1222.5000  18.5000   8  18.5000\n    2  2,1   1222.5000  17.0000   8  17.0000\n    3  2,2    611.2500  13.5000   4  13.5000\n    4  2,4    305.6250  10.1250   2  10.1250\n    5  4,2    305.6250  10.5000   2  10.5000\n    6  4,4    152.8125   7.5625   1   7.5625\n\n    The column div gives the divisions specified in the function call. The\n    column n_individs specifies the average number of individuals across the\n    cells made from the given division. n_spp gives the average species across\n    the cells made from the given division. x gives the absolute area of a\n    cell for the given division. y gives the same information as n_spp and is\n    included for easy plotting.\n\n    See http://www.macroeco.org/tutorial_macroeco.html for additional\n    examples and explanation"
  },
  {
    "code": "def bundle_view(parser, token):\n    bits = token.split_contents()\n    if len(bits) < 3:\n        raise TemplateSyntaxError(\"'%s' takes at least two arguments\"\n                                  \" bundle and view_name\" % bits[0])\n    bundle = parser.compile_filter(bits[1])\n    viewname = parser.compile_filter(bits[2])\n    asvar = None\n    bits = bits[2:]\n    if len(bits) >= 2 and bits[-2] == 'as':\n        asvar = bits[-1]\n        bits = bits[:-2]\n    return ViewNode(bundle, viewname, asvar)",
    "docstring": "Returns an string version of a bundle view. This is done by\n    calling the `get_string_from_view` method of the provided bundle.\n\n    This tag expects that the request object as well as the\n    the original url_params are available in the context.\n\n    Requires two arguments bundle and the name of the view\n    you want to render. In addition, this tag also accepts\n    the 'as xxx' syntax.\n\n    Example:\n\n    {% bundle_url bundle main_list as html %}"
  },
  {
    "code": "def __unpack_tgz(self, filename):\r\n        if isinstance(filename, string_types) and self.__isValidTGZ(filename) and tarfile.is_tarfile(filename):\r\n            with tarfile.open(filename, mode='r:gz') as t:\r\n                for name in t.getnames():\r\n                    t.extract(name, self.plugin_abspath)\r\n        else:\r\n            raise TarError(\"Invalid Plugin Compressed File\")",
    "docstring": "Unpack the `tar.gz`, `tgz` compressed file format"
  },
  {
    "code": "def _create_cipher(self, password, salt, IV):\n        from Crypto.Protocol.KDF import PBKDF2\n        from Crypto.Cipher import AES\n        pw = PBKDF2(password, salt, dkLen=self.block_size)\n        return AES.new(pw[:self.block_size], AES.MODE_CFB, IV)",
    "docstring": "Create the cipher object to encrypt or decrypt a payload."
  },
  {
    "code": "def reMutualReceptions(self):\n        planets = copy(const.LIST_SEVEN_PLANETS)\n        planets.remove(self.obj.id)\n        mrs = {}\n        for ID in planets:\n            mr = self.dyn.reMutualReceptions(self.obj.id, ID)\n            if mr:\n                mrs[ID] = mr\n        return mrs",
    "docstring": "Returns all mutual receptions with the object\n        and other planets, indexed by planet ID. \n        It only includes ruler and exaltation receptions."
  },
  {
    "code": "def is_twss(self, phrase):\n        featureset = self.extract_features(phrase)\n        return self.classifier.classify(featureset)",
    "docstring": "The magic function- this accepts a phrase and tells you if it\n        classifies as an entendre"
  },
  {
    "code": "def _set_bounds(self, bounds):\n        min_value, max_value = bounds\n        self.min_value = None\n        self.max_value = None\n        self.min_value = min_value\n        self.max_value = max_value",
    "docstring": "Sets the boundaries for this parameter to min_value and max_value"
  },
  {
    "code": "def find(self, location):\n        try:\n            content = self.store[location]\n            return StringIO(content)\n        except:\n            reason = 'location \"%s\" not in document store' % location\n            raise Exception, reason",
    "docstring": "Find the specified location in the store.\n        @param location: The I{location} part of a URL.\n        @type location: str\n        @return: An input stream to the document.\n        @rtype: StringIO"
  },
  {
    "code": "def lock(self):\n        if self.cache.get(self.lock_name):\n            return False\n        else:\n            self.cache.set(self.lock_name, timezone.now(), self.timeout)\n            return True",
    "docstring": "This method sets a cache variable to mark current job as \"already running\"."
  },
  {
    "code": "def abort_submission(namespace, workspace, submission_id):\n    uri = \"workspaces/{0}/{1}/submissions/{2}\".format(namespace,\n                                        workspace, submission_id)\n    return __delete(uri)",
    "docstring": "Abort running job in a workspace.\n\n    Args:\n        namespace (str): project to which workspace belongs\n        workspace (str): Workspace name\n        submission_id (str): Submission's unique identifier\n\n    Swagger:\n        https://api.firecloud.org/#!/Submissions/deleteSubmission"
  },
  {
    "code": "def deep_merge(base, extra):\n    if extra is None:\n        return\n    for key, value in extra.items():\n        if value is None:\n            if key in base:\n                del base[key]\n        elif isinstance(base.get(key), dict) and isinstance(value, dict):\n            deep_merge(base[key], value)\n        else:\n            base[key] = value",
    "docstring": "Deeply merge two dictionaries, overriding existing keys in the base.\n\n    :param base: The base dictionary which will be merged into.\n    :param extra: The dictionary to merge into the base. Keys from this\n        dictionary will take precedence."
  },
  {
    "code": "def create(self):\n        steps = [\n            (self.create_role, (), {}),\n            (self.create_vpc, (), {}),\n            (self.create_cluster, (), {}),\n            (self.create_node_group, (), {}),\n            (self.create_spot_nodes, (), {}),\n            (self.create_utilities, (), {}),\n        ]\n        for step in tqdm.tqdm(steps, ncols=70):\n            method, args, kwargs = step\n            method(*args, **kwargs)",
    "docstring": "Deploy a cluster on Amazon's EKS Service configured\n        for Jupyterhub Deployments."
  },
  {
    "code": "def get_tree(self, process_name):\n        for tree_name, tree in self.trees.items():\n            if process_name in tree:\n                return tree",
    "docstring": "return tree that is managing time-periods for given process"
  },
  {
    "code": "def get_fw_policy(self, policy_id):\n        policy = None\n        try:\n            policy = self.neutronclient.show_firewall_policy(policy_id)\n        except Exception as exc:\n            LOG.error(\"Failed to get firewall plcy for id %(id)s \"\n                      \"Exc %(exc)s\",\n                      {'id': policy_id, 'exc': str(exc)})\n        return policy",
    "docstring": "Return the firewall policy, given its ID."
  },
  {
    "code": "def in_file(self, fn: str) -> Iterator[Statement]:\n        yield from self.__file_to_statements.get(fn, [])",
    "docstring": "Returns an iterator over all of the statements belonging to a file."
  },
  {
    "code": "def send_response(self, code, message=None):\n        self.log_request(code)\n        self.send_response_only(code, message)\n        self.send_header('Server', self.version_string())\n        self.send_header('Date', self.date_time_string())",
    "docstring": "Add the response header to the headers buffer and log the\n        response code.\n\n        Also send two standard headers with the server software\n        version and the current date."
  },
  {
    "code": "def create_driver(self):\n        driver_type = self.config.get('Driver', 'type')\n        try:\n            if self.config.getboolean_optional('Server', 'enabled'):\n                self.logger.info(\"Creating remote driver (type = %s)\", driver_type)\n                driver = self._create_remote_driver()\n            else:\n                self.logger.info(\"Creating local driver (type = %s)\", driver_type)\n                driver = self._create_local_driver()\n        except Exception as exc:\n            error_message = get_error_message_from_exception(exc)\n            self.logger.error(\"%s driver can not be launched: %s\", driver_type.capitalize(), error_message)\n            raise\n        return driver",
    "docstring": "Create a selenium driver using specified config properties\n\n        :returns: a new selenium driver\n        :rtype: selenium.webdriver.remote.webdriver.WebDriver"
  },
  {
    "code": "def _tp__get_typed_properties(self):\n        try:\n            return tuple(getattr(self, p) for p in self._tp__typed_properties)\n        except AttributeError:\n            raise NotImplementedError",
    "docstring": "Return a tuple of typed attrs that can be used for comparisons.\n\n        Raises:\n            NotImplementedError: Raised if this class was mixed into a class\n                that was not created by _AnnotatedObjectMeta."
  },
  {
    "code": "def _traverse_list(self, input_list, resolution_data, resolver_method):\n        for index, value in enumerate(input_list):\n            input_list[index] = self._traverse(value, resolution_data, resolver_method)\n        return input_list",
    "docstring": "Traverse a list to resolve intrinsic functions on every element\n\n        :param input_list: List of input\n        :param resolution_data: Data that the `resolver_method` needs to operate\n        :param resolver_method: Method that can actually resolve an intrinsic function, if it detects one\n        :return: Modified list with intrinsic functions resolved"
  },
  {
    "code": "def lex(filename):\n    with io.open(filename, mode='r', encoding='utf-8') as f:\n        it = _lex_file_object(f)\n        it = _balance_braces(it, filename)\n        for token, line, quoted in it:\n            yield (token, line, quoted)",
    "docstring": "Generates tokens from an nginx config file"
  },
  {
    "code": "def set_double_stack(socket_obj, double_stack=True):\n    try:\n        opt_ipv6_only = socket.IPV6_V6ONLY\n    except AttributeError:\n        if os.name == \"nt\":\n            opt_ipv6_only = 27\n        elif platform.system() == \"Linux\":\n            opt_ipv6_only = 26\n        else:\n            raise\n    socket_obj.setsockopt(ipproto_ipv6(), opt_ipv6_only, int(not double_stack))",
    "docstring": "Sets up the IPv6 double stack according to the operating system\n\n    :param socket_obj: A socket object\n    :param double_stack: If True, use the double stack, else only support IPv6\n    :raise AttributeError: Python or system doesn't support V6\n    :raise socket.error: Error setting up the double stack value"
  },
  {
    "code": "def _parse_scram_response(response):\n    return dict(item.split(b\"=\", 1) for item in response.split(b\",\"))",
    "docstring": "Split a scram response into key, value pairs."
  },
  {
    "code": "def deprecation_warning(func, name):\n    @wraps(func)\n    def caller(*args, **kwargs):\n        logger = logging.getLogger(__name__)\n        instance = func(*args, **kwargs)\n        logger.warning(\n            \"Distribution `chaospy.{}` has been renamed to \".format(name) +\n            \"`chaospy.{}` and will be deprecated next release.\".format(instance.__class__.__name__))\n        return instance\n    return caller",
    "docstring": "Add a deprecation warning do each distribution."
  },
  {
    "code": "def _put_overlay(self, overlay_name, overlay):\n        if not isinstance(overlay, dict):\n            raise TypeError(\"Overlay must be dict\")\n        if set(self._identifiers()) != set(overlay.keys()):\n            raise ValueError(\"Overlay keys must be dataset identifiers\")\n        self._storage_broker.put_overlay(overlay_name, overlay)",
    "docstring": "Store overlay so that it is accessible by the given name.\n\n        :param overlay_name: name of the overlay\n        :param overlay: overlay must be a dictionary where the keys are\n                        identifiers in the dataset\n        :raises: TypeError if the overlay is not a dictionary,\n                 ValueError if identifiers in overlay and dataset do not match"
  },
  {
    "code": "def enqueue(self, item_type, item):\n        with self.enlock:\n            self.queue[item_type].append(item)",
    "docstring": "Queue a new data item, make item iterable"
  },
  {
    "code": "def db(self, connection_string=None):\n        connection_string = connection_string or self.settings[\"db\"]\n        if not hasattr(self, \"_db_conns\"):\n            self._db_conns = {}\n        if not connection_string in self._db_conns:\n            self._db_conns[connection_string] = oz.sqlalchemy.session(connection_string=connection_string)\n        return self._db_conns[connection_string]",
    "docstring": "Gets the SQLALchemy session for this request"
  },
  {
    "code": "def print_statistics(self):\r\n        print(\"Q1 =\", self.Q1)\r\n        print(\"Q2 =\", self.Q2)\r\n        print(\"cR =\", self.cR)",
    "docstring": "Prints out the Q1, Q2, and cR statistics for the variogram fit.\r\n        NOTE that ideally Q1 is close to zero, Q2 is close to 1,\r\n        and cR is as small as possible."
  },
  {
    "code": "def determine_struct_tree_subtype(self, data_type, obj):\n        if '.tag' not in obj:\n            raise bv.ValidationError(\"missing '.tag' key\")\n        if not isinstance(obj['.tag'], six.string_types):\n            raise bv.ValidationError('expected string, got %s' %\n                                     bv.generic_type_name(obj['.tag']),\n                                     parent='.tag')\n        full_tags_tuple = (obj['.tag'],)\n        if full_tags_tuple in data_type.definition._tag_to_subtype_:\n            subtype = data_type.definition._tag_to_subtype_[full_tags_tuple]\n            if isinstance(subtype, bv.StructTree):\n                raise bv.ValidationError(\"tag '%s' refers to non-leaf subtype\" %\n                                         ('.'.join(full_tags_tuple)))\n            return subtype\n        else:\n            if self.strict:\n                raise bv.ValidationError(\"unknown subtype '%s'\" %\n                                         '.'.join(full_tags_tuple))\n            else:\n                if data_type.definition._is_catch_all_:\n                    return data_type\n                else:\n                    raise bv.ValidationError(\n                        \"unknown subtype '%s' and '%s' is not a catch-all\" %\n                        ('.'.join(full_tags_tuple), data_type.definition.__name__))",
    "docstring": "Searches through the JSON-object-compatible dict using the data type\n        definition to determine which of the enumerated subtypes `obj` is."
  },
  {
    "code": "def l2_regression_loss(y, target, name=None):\n  with tf.name_scope(name, 'l2_regression', [y, target]) as scope:\n    y = tf.convert_to_tensor(y, name='y')\n    target = tf.convert_to_tensor(target, name='target')\n    return tf.sqrt(l2_regression_sq_loss(y, target, name=scope))",
    "docstring": "Calculates the square root of the SSE between y and target.\n\n  Args:\n    y: the calculated values.\n    target: the desired values.\n    name: the name for this op, defaults to l2_regression\n  Returns:\n    A tensorflow op."
  },
  {
    "code": "def _readuint(self, length, start):\n        if not length:\n            raise InterpretError(\"Cannot interpret a zero length bitstring \"\n                                           \"as an integer.\")\n        offset = self._offset\n        startbyte = (start + offset) // 8\n        endbyte = (start + offset + length - 1) // 8\n        b = binascii.hexlify(bytes(self._datastore.getbyteslice(startbyte, endbyte + 1)))\n        assert b\n        i = int(b, 16)\n        final_bits = 8 - ((start + offset + length) % 8)\n        if final_bits != 8:\n            i >>= final_bits\n        i &= (1 << length) - 1\n        return i",
    "docstring": "Read bits and interpret as an unsigned int."
  },
  {
    "code": "def stream(self):\n        if self._stream is None:\n            self._stream = tempfile.NamedTemporaryFile(delete=False)\n            try:\n               self._stream.write(self.client.open(self.filename, view='data').read())\n            except:\n               pass\n        return self._stream",
    "docstring": "the stream to write the log content too.\n        @return:"
  },
  {
    "code": "def delete_host_from_segment(ipaddress, networkaddress, auth, url):\n    host_id = get_host_id(ipaddress, networkaddress, auth, url)\n    remove_scope_ip(host_id, auth.creds, auth.url)",
    "docstring": "Function to abstract"
  },
  {
    "code": "def intersect_regions(flist):\n    if len(flist) < 2:\n        raise Exception(\"Require at least two regions to perform intersection\")\n    a = Region.load(flist[0])\n    for b in [Region.load(f) for f in flist[1:]]:\n        a.intersect(b)\n    return a",
    "docstring": "Construct a region which is the intersection of all regions described in the given\n    list of file names.\n\n    Parameters\n    ----------\n    flist : list\n        A list of region filenames.\n\n    Returns\n    -------\n    region : :class:`AegeanTools.regions.Region`\n        The intersection of all regions, possibly empty."
  },
  {
    "code": "def set_property(self, name, value):\n        typeof = type(self.get_property(name))\n        self._interface.SetProperty(name,\n                                    translate_to_dbus_type(typeof, value))",
    "docstring": "Helper to set a property value by name, translating to correct\n        dbus type\n\n        See also :py:meth:`get_property`\n\n        :param str name: The property name in the object's dictionary\n            whose value shall be set.\n        :param value: Properties new value to be assigned.\n        :return:\n        :raises KeyError: if the property key is not found in the\n            object's dictionary\n        :raises dbus.Exception: org.bluez.Error.DoesNotExist\n        :raises dbus.Exception: org.bluez.Error.InvalidArguments"
  },
  {
    "code": "def process_like(proc):\n    newproc = copy.deepcopy(proc)\n    newproc.creation_date = time.strftime(\"%a, %d %b %Y %H:%M:%S %z\",\n                                          time.localtime())\n    return newproc",
    "docstring": "Make an exact clone of a process, including state and all subprocesses.\n\n    The creation date is updated.\n\n    :param proc:    process\n    :type proc:     :class:`~climlab.process.process.Process`\n    :return:        new process identical to the given process\n    :rtype:         :class:`~climlab.process.process.Process`\n\n    :Example:\n\n        ::\n\n            >>> import climlab\n            >>> from climlab.process.process import process_like\n\n            >>> model = climlab.EBM()\n            >>> model.subprocess.keys()\n            ['diffusion', 'LW', 'albedo', 'insolation']\n\n            >>> albedo = model.subprocess['albedo']\n            >>> albedo_copy = process_like(albedo)\n\n            >>> albedo.creation_date\n            'Thu, 24 Mar 2016 01:32:25 +0000'\n\n            >>> albedo_copy.creation_date\n            'Thu, 24 Mar 2016 01:33:29 +0000'"
  },
  {
    "code": "def add_string_pairs_from_button_element(xib_file, results, button, special_ui_components_prefix):\n    button_entry_comment = extract_element_internationalized_comment(button)\n    if button_entry_comment is None:\n        return\n    for state in button.getElementsByTagName('state'):\n        state_name = state.attributes['key'].value\n        state_entry_comment = button_entry_comment + \" - \" + state_name + \" state of button\"\n        if not add_string_pairs_from_attributed_ui_element(results, state, state_entry_comment):\n            try:\n                button_entry_key = state.attributes['title'].value\n            except KeyError:\n                try:\n                    button_entry_key = state.getElementsByTagName('string')[0].firstChild.nodeValue\n                except Exception:\n                    continue\n            results.append((button_entry_key, state_entry_comment))\n    warn_if_element_not_of_class(button, 'Button', special_ui_components_prefix)",
    "docstring": "Adds strings pairs from a button xib element.\n\n    Args:\n        xib_file (str): Path to the xib file.\n        results (list): The list to add the results to.\n        button(element): The button element from the xib, to extract the string pairs from.\n        special_ui_components_prefix(str): A custom prefix for internationalize component to allow (default is only JT)"
  },
  {
    "code": "def set_role_config_groups(self, role_config_group_refs):\n    update = copy.copy(self)\n    update.roleConfigGroupRefs = role_config_group_refs\n    return self._do_update(update)",
    "docstring": "Updates the role config groups in a host template.\n    @param role_config_group_refs: List of role config group refs.\n    @return: An ApiHostTemplate object."
  },
  {
    "code": "def load_global_conf(cls, global_configuration):\n        logger.debug(\"Propagate global parameter for %s:\", cls)\n        for prop, entry in global_configuration.properties.items():\n            if not entry.managed or not getattr(entry, 'class_inherit'):\n                continue\n            for (cls_dest, change_name) in entry.class_inherit:\n                if cls_dest == cls:\n                    value = getattr(global_configuration, prop)\n                    logger.debug(\"- global parameter %s=%s -> %s=%s\",\n                                 prop, getattr(global_configuration, prop),\n                                 change_name, value)\n                    if change_name is None:\n                        setattr(cls, prop, value)\n                    else:\n                        setattr(cls, change_name, value)",
    "docstring": "Apply global Alignak configuration.\n\n        Some objects inherit some properties from the global configuration if they do not\n        define their own value. E.g. the global 'accept_passive_service_checks' is inherited\n        by the services as 'accept_passive_checks'\n\n        :param cls: parent object\n        :type cls: object\n        :param global_configuration: current object (child)\n        :type global_configuration: object\n        :return: None"
  },
  {
    "code": "def inter(a, b):\n    assert isinstance(a, stypes.SpiceCell)\n    assert isinstance(b, stypes.SpiceCell)\n    assert a.dtype == b.dtype\n    if a.dtype is 0:\n        c = stypes.SPICECHAR_CELL(max(a.size, b.size), max(a.length, b.length))\n    elif a.dtype is 1:\n        c = stypes.SPICEDOUBLE_CELL(max(a.size, b.size))\n    elif a.dtype is 2:\n        c = stypes.SPICEINT_CELL(max(a.size, b.size))\n    else:\n        raise NotImplementedError\n    libspice.inter_c(ctypes.byref(a), ctypes.byref(b), ctypes.byref(c))\n    return c",
    "docstring": "Intersect two sets of any data type to form a third set.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/inter_c.html\n\n    :param a: First input set.\n    :type a: spiceypy.utils.support_types.SpiceCell\n    :param b: Second input set.\n    :type b: spiceypy.utils.support_types.SpiceCell\n    :return: Intersection of a and b.\n    :rtype: spiceypy.utils.support_types.SpiceCell"
  },
  {
    "code": "def dummy_func(arg1, arg2, arg3=None, arg4=[1, 2, 3], arg5={}, **kwargs):\n    foo = kwargs.get('foo', None)\n    bar = kwargs.pop('bar', 4)\n    foo2 = kwargs['foo2']\n    foobar = str(foo) + str(bar) + str(foo2)\n    return foobar",
    "docstring": "test func for kwargs parseing"
  },
  {
    "code": "def is_contextfree(self):\n        for lhs, rhs in self.rules:\n            if len(lhs) != 1:\n                return False\n            if lhs[0] not in self.nonterminals:\n                return False\n        return True",
    "docstring": "Returns True iff the grammar is context-free."
  },
  {
    "code": "def resend_presence(self):\n        if self.client.established:\n            return self.client.enqueue(self.make_stanza())",
    "docstring": "Re-send the currently configured presence.\n\n        :return: Stanza token of the presence stanza or :data:`None` if the\n                 stream is not established.\n        :rtype: :class:`~.stream.StanzaToken`\n\n        .. note::\n\n           :meth:`set_presence` automatically broadcasts the new presence if\n           any of the parameters changed."
  },
  {
    "code": "def get_productivity_stats(self):\n        response = API.get_productivity_stats(self.api_token)\n        _fail_if_contains_errors(response)\n        return response.json()",
    "docstring": "Return the user's productivity stats.\n\n        :return: A JSON-encoded representation of the user's productivity\n            stats.\n        :rtype: A JSON-encoded object.\n\n        >>> from pytodoist import todoist\n        >>> user = todoist.login('john.doe@gmail.com', 'password')\n        >>> stats = user.get_productivity_stats()\n        >>> print(stats)\n        {\"karma_last_update\": 50.0, \"karma_trend\": \"up\", ... }"
  },
  {
    "code": "def advance(self):\n        elem = next(self._iterable)\n        for deque in self._deques:\n            deque.append(elem)",
    "docstring": "Advance the base iterator, publish to constituent iterators."
  },
  {
    "code": "def _get_licences():\n  licenses = _LICENSES\n  for license in licenses:\n    print(\"{license_name} [{license_code}]\".format(\n          license_name=licenses[license], license_code=license))",
    "docstring": "Lists all the licenses on command line"
  },
  {
    "code": "def create_static_profile_path(client_id):\n    profile_path = os.path.join(STATIC_FILES_PATH, str(client_id))\n    if not os.path.exists(profile_path):\n        os.makedirs(profile_path)\n    return profile_path",
    "docstring": "Create a profile path folder if not exist\n    \n    @param client_id: ID of client user\n    @return string profile path"
  },
  {
    "code": "def is_connected(self):\n        if self._is_open:\n            err = hidapi.hid_read_timeout(self._device, ffi.NULL, 0, 0)\n            if err == -1:\n                return False\n            else:\n                return True\n        else:\n            en = Enumeration(vid=self.vendor_id, pid=self.product_id).find(path=self.path)\n            if len(en) == 0:\n                return False\n            else:\n                return True",
    "docstring": "Checks if the USB device is still connected"
  },
  {
    "code": "def pixels(self, value: int) -> 'Gap':\n        raise_not_number(value)\n        self.gap = '{}px'.format(value)\n        return self",
    "docstring": "Set the margin in pixels."
  },
  {
    "code": "def _read_as_int(self, addr, numBytes):\n        buf = self.read_register(addr, numBytes)\n        if len(buf) >= 4:\n            return struct.unpack_from(\"<i\", buf)[0]\n        else:\n            rtn = 0\n            for i, byte in enumerate(buf):\n                rtn |= byte << 8 * i\n            return rtn",
    "docstring": "Convenience method. Oftentimes we need to read a range of\n        registers to represent an int. This method will automatically read\n        @numBytes registers starting at @addr and convert the array into an int."
  },
  {
    "code": "def _get_key_value_config(self):\n        for rp in self._remote_providers:\n            val = self._get_remote_config(rp)\n            self._kvstore = val\n            return None\n        raise errors.RemoteConfigError(\"No Files Found\")",
    "docstring": "Retrieves the first found remote configuration."
  },
  {
    "code": "def _load_resource(self):\n        url = self._url\n        if self._params:\n            url += '?{0}'.format(six.moves.urllib_parse.urlencode(self._params))\n        r = getattr(self._session, self._meta.get_method.lower())(url)\n        if r.status_code == 404:\n            raise NotFoundException('Server returned 404 Not Found for the URL {0}'.format(self._url))\n        elif not 200 <= r.status_code < 400:\n            raise HTTPException('Server returned {0} ({1})'.format(r.status_code, r.reason), r)\n        data = self._meta.deserializer.to_dict(r.text)\n        self.populate_field_values(data)",
    "docstring": "Load resource data from server"
  },
  {
    "code": "def graphs(self):\n        result = Dummy()\n        for graph in graphs.__all__:\n            cls = getattr(graphs, graph)\n            setattr(result, cls.short_name, cls(self))\n        return result",
    "docstring": "Sorry for the black magic. The result is an object whose attributes\n        are all the graphs found in graphs.py initialized with this instance as\n        only argument."
  },
  {
    "code": "async def remove_key(request: web.Request) -> web.Response:\n    keys_dir = CONFIG['wifi_keys_dir']\n    available_keys = os.listdir(keys_dir)\n    requested_hash = request.match_info['key_uuid']\n    if requested_hash not in available_keys:\n        return web.json_response(\n            {'message': 'No such key file {}'\n             .format(requested_hash)},\n            status=404)\n    key_path = os.path.join(keys_dir, requested_hash)\n    name = os.listdir(key_path)[0]\n    shutil.rmtree(key_path)\n    return web.json_response(\n        {'message': 'Key file {} deleted'.format(name)},\n        status=200)",
    "docstring": "Remove a key.\n\n    ```\n    DELETE /wifi/keys/:id\n\n    -> 200 OK\n    {message: 'Removed key keyfile.pem'}\n    ```"
  },
  {
    "code": "def set_language(self, language):\n        if isinstance(language, str):\n            language_obj = languages.getlang(language)\n            if language_obj:\n                self.language = language_obj.code\n            else:\n                raise TypeError(\"Language code {} not found\".format(language))\n        if isinstance(language, languages.Language):\n            self.language = language.code",
    "docstring": "Set self.language to internal lang. repr. code from str or Language object."
  },
  {
    "code": "def weave_on(advices, pointcut=None, ctx=None, depth=1, ttl=None):\n    def __weave(target):\n        weave(\n            target=target, advices=advices, pointcut=pointcut,\n            ctx=ctx, depth=depth, ttl=ttl\n        )\n        return target\n    return __weave",
    "docstring": "Decorator for weaving advices on a callable target.\n\n    :param pointcut: condition for weaving advices on joinpointe.\n        The condition depends on its type.\n    :param ctx: target ctx (instance or class).\n    :type pointcut:\n        - NoneType: advices are weaved on target.\n        - str: target name is compared to pointcut regex.\n        - function: called with target in parameter, if True, advices will\n            be weaved on target.\n\n    :param depth: class weaving depthing\n    :type depth: int\n\n    :param public: (default True) weave only on public members\n    :type public: bool"
  },
  {
    "code": "def index(in_cram, config):\n    out_file = in_cram + \".crai\"\n    if not utils.file_uptodate(out_file, in_cram):\n        with file_transaction(config, in_cram + \".crai\") as tx_out_file:\n            tx_in_file = os.path.splitext(tx_out_file)[0]\n            utils.symlink_plus(in_cram, tx_in_file)\n            cmd = \"samtools index {tx_in_file}\"\n            do.run(cmd.format(**locals()), \"Index CRAM file\")\n    return out_file",
    "docstring": "Ensure CRAM file has a .crai index file."
  },
  {
    "code": "def _gen_success_message(publish_output):\n    application_id = publish_output.get('application_id')\n    details = json.dumps(publish_output.get('details'), indent=2)\n    if CREATE_APPLICATION in publish_output.get('actions'):\n        return \"Created new application with the following metadata:\\n{}\".format(details)\n    return 'The following metadata of application \"{}\" has been updated:\\n{}'.format(application_id, details)",
    "docstring": "Generate detailed success message for published applications.\n\n    Parameters\n    ----------\n    publish_output : dict\n        Output from serverlessrepo publish_application\n\n    Returns\n    -------\n    str\n        Detailed success message"
  },
  {
    "code": "def create_deployment(self, ref, force=False, payload='',\n                          auto_merge=False, description='', environment=None):\n        json = None\n        if ref:\n            url = self._build_url('deployments', base_url=self._api)\n            data = {'ref': ref, 'force': force, 'payload': payload,\n                    'auto_merge': auto_merge, 'description': description,\n                    'environment': environment}\n            self._remove_none(data)\n            headers = Deployment.CUSTOM_HEADERS\n            json = self._json(self._post(url, data=data, headers=headers),\n                              201)\n        return Deployment(json, self) if json else None",
    "docstring": "Create a deployment.\n\n        :param str ref: (required), The ref to deploy. This can be a branch,\n            tag, or sha.\n        :param bool force: Optional parameter to bypass any ahead/behind\n            checks or commit status checks. Default: False\n        :param str payload: Optional JSON payload with extra information about\n            the deployment. Default: \"\"\n        :param bool auto_merge: Optional parameter to merge the default branch\n            into the requested deployment branch if necessary. Default: False\n        :param str description: Optional short description. Default: \"\"\n        :param str environment: Optional name for the target deployment\n            environment (e.g., production, staging, qa). Default: \"production\"\n        :returns: :class:`Deployment <github3.repos.deployment.Deployment>`"
  },
  {
    "code": "def addSource(self, sourceUri, weight):\n        assert isinstance(weight, (float, int)), \"weight value has to be a positive or negative integer\"\n        self.topicPage[\"sources\"].append({\"uri\": sourceUri, \"wgt\": weight})",
    "docstring": "add a news source to the topic page\n        @param sourceUri: uri of the news source to add to the topic page\n        @param weight: importance of the news source (typically in range 1 - 50)"
  },
  {
    "code": "def translate(self):\n        expressions, varnames, funcnames = self.expr.translate()\n        argnames = []\n        for varname in varnames:\n            argnames.append(VARIABLE_PREFIX + varname)\n        for funcname in funcnames:\n            argnames.append(FUNCTION_PREFIX + funcname)\n        func = compile_func(\n            argnames,\n            [ast.Return(ast.List(expressions, ast.Load()))],\n        )\n        def wrapper_func(values={}, functions={}):\n            args = {}\n            for varname in varnames:\n                args[VARIABLE_PREFIX + varname] = values[varname]\n            for funcname in funcnames:\n                args[FUNCTION_PREFIX + funcname] = functions[funcname]\n            parts = func(**args)\n            return u''.join(parts)\n        return wrapper_func",
    "docstring": "Compile the template to a Python function."
  },
  {
    "code": "def _active_todos(self):\n        return [todo for todo in self.todolist.todos()\n                if not self._uncompleted_children(todo) and todo.is_active()]",
    "docstring": "Returns a list of active todos, taking uncompleted subtodos into\n        account.\n\n        The stored length of the todolist is taken into account, to prevent new\n        todos created by recurrence to pop up as newly activated tasks.\n        Since these todos pop up at the end of the list, we cut off the list\n        just before that point."
  },
  {
    "code": "def remove_all_listeners(self, event=None):\n        if event is not None:\n            self._events[event] = OrderedDict()\n        else:\n            self._events = defaultdict(OrderedDict)",
    "docstring": "Remove all listeners attached to ``event``.\n        If ``event`` is ``None``, remove all listeners on all events."
  },
  {
    "code": "def delete(self, robj, rw=None, r=None, w=None, dw=None, pr=None,\n               pw=None, timeout=None):\n        raise NotImplementedError",
    "docstring": "Deletes an object."
  },
  {
    "code": "def _objects_touch_each_other(self, object1: Object, object2: Object) -> bool:\n        in_vertical_range = object1.y_loc <= object2.y_loc + object2.size and \\\n                            object1.y_loc + object1.size >= object2.y_loc\n        in_horizantal_range = object1.x_loc <= object2.x_loc + object2.size and \\\n                            object1.x_loc + object1.size >= object2.x_loc\n        touch_side = object1.x_loc + object1.size == object2.x_loc or \\\n                     object2.x_loc + object2.size == object1.x_loc\n        touch_top_or_bottom = object1.y_loc + object1.size == object2.y_loc or \\\n                              object2.y_loc + object2.size == object1.y_loc\n        return (in_vertical_range and touch_side) or (in_horizantal_range and touch_top_or_bottom)",
    "docstring": "Returns true iff the objects touch each other."
  },
  {
    "code": "def _generate_field_with_default(**kwargs):\n        field = kwargs['field']\n        if callable(field.default):\n            return field.default()\n        return field.default",
    "docstring": "Only called if field.default != NOT_PROVIDED"
  },
  {
    "code": "def trans_history(\n        self, from_=None, count=None, from_id=None, end_id=None,\n        order=None, since=None, end=None\n    ):\n        return self._trade_api_call(\n            'TransHistory', from_=from_, count=count, from_id=from_id, end_id=end_id,\n            order=order, since=since, end=end\n        )",
    "docstring": "Returns the history of transactions.\n        To use this method you need a privilege of the info key.\n\n        :param int or None from_: transaction ID, from which the display starts (default 0)\n        :param int or None count: number of transaction to be displayed\t(default 1000)\n        :param int or None from_id: transaction ID, from which the display starts (default 0)\n        :param int or None end_id: transaction ID on which the display ends\t(default inf.)\n        :param str or None order: sorting (default 'DESC')\n        :param int or None since: the time to start the display (default 0)\n        :param int or None end: the time to end the display\t(default inf.)"
  },
  {
    "code": "def cmd_start(self, argv, help):\n        parser = argparse.ArgumentParser(\n            prog=\"%s start\" % self.progname,\n            description=help,\n        )\n        instances = self.get_instances(command='start')\n        parser.add_argument(\"instance\", nargs=1,\n                            metavar=\"instance\",\n                            help=\"Name of the instance from the config.\",\n                            choices=sorted(instances))\n        parser.add_argument(\"-o\", \"--override\", nargs=\"*\", type=str,\n                            dest=\"overrides\", metavar=\"OVERRIDE\",\n                            help=\"Option to override in instance config for startup script (name=value).\")\n        args = parser.parse_args(argv)\n        overrides = self._parse_overrides(args)\n        overrides['instances'] = self.instances\n        instance = instances[args.instance[0]]\n        instance.hooks.before_start(instance)\n        result = instance.start(overrides)\n        instance.hooks.after_start(instance)\n        if result is None:\n            return\n        instance.status()",
    "docstring": "Starts the instance"
  },
  {
    "code": "def select_candidates(config):\n    download_candidates = []\n    for group in config.group:\n        summary_file = get_summary(config.section, group, config.uri, config.use_cache)\n        entries = parse_summary(summary_file)\n        for entry in filter_entries(entries, config):\n            download_candidates.append((entry, group))\n    return download_candidates",
    "docstring": "Select candidates to download.\n\n    Parameters\n    ----------\n    config: NgdConfig\n        Runtime configuration object\n\n    Returns\n    -------\n    list of (<candidate entry>, <taxonomic group>)"
  },
  {
    "code": "def config_set(self, parameter, value):\n        if not isinstance(parameter, str):\n            raise TypeError(\"parameter must be str\")\n        fut = self.execute(b'CONFIG', b'SET', parameter, value)\n        return wait_ok(fut)",
    "docstring": "Set a configuration parameter to the given value."
  },
  {
    "code": "def flag_calls(func):\n    if hasattr(func, 'called'):\n        return func\n    def wrapper(*args, **kw):\n        wrapper.called = False\n        out = func(*args, **kw)\n        wrapper.called = True\n        return out\n    wrapper.called = False\n    wrapper.__doc__ = func.__doc__\n    return wrapper",
    "docstring": "Wrap a function to detect and flag when it gets called.\n\n    This is a decorator which takes a function and wraps it in a function with\n    a 'called' attribute. wrapper.called is initialized to False.\n\n    The wrapper.called attribute is set to False right before each call to the\n    wrapped function, so if the call fails it remains False.  After the call\n    completes, wrapper.called is set to True and the output is returned.\n\n    Testing for truth in wrapper.called allows you to determine if a call to\n    func() was attempted and succeeded."
  },
  {
    "code": "def wait(self):\n        now = _monotonic()\n        if now < self._ref:\n            delay = max(0, self._ref - now)\n            self.sleep_func(delay)\n        self._update_ref()",
    "docstring": "Blocks until the rate is met"
  },
  {
    "code": "def flush_all(self, delay=0, noreply=None):\n        if noreply is None:\n            noreply = self.default_noreply\n        cmd = b'flush_all ' + six.text_type(delay).encode('ascii')\n        if noreply:\n            cmd += b' noreply'\n        cmd += b'\\r\\n'\n        results = self._misc_cmd([cmd], b'flush_all', noreply)\n        if noreply:\n            return True\n        return results[0] == b'OK'",
    "docstring": "The memcached \"flush_all\" command.\n\n        Args:\n          delay: optional int, the number of seconds to wait before flushing,\n                 or zero to flush immediately (the default).\n          noreply: optional bool, True to not wait for the reply (defaults to\n                   self.default_noreply).\n\n        Returns:\n          True."
  },
  {
    "code": "def read_blocking(self):\n        while True:\n            data = self._read()\n            if data != None:\n                break\n        return self._parse_message(data)",
    "docstring": "Same as read, except blocks untill data is available to be read."
  },
  {
    "code": "def cancelOperation(self):\n        if self.isLongTouchingPoint:\n            self.toggleLongTouchPoint()\n        elif self.isTouchingPoint:\n            self.toggleTouchPoint()\n        elif self.isGeneratingTestCondition:\n            self.toggleGenerateTestCondition()",
    "docstring": "Cancels the ongoing operation if any."
  },
  {
    "code": "def activate(self, event):\n        self._index += 1\n        if self._index >= len(self._values):\n            self._index = 0\n        self._selection = self._values[self._index]\n        self.ao2.speak(self._selection)",
    "docstring": "Change the value."
  },
  {
    "code": "def get_files(*bases):\n        for base in bases:\n            basedir, _ = base.split(\".\", 1)\n            base = os.path.join(os.path.dirname(__file__), *base.split(\".\"))\n            rem = len(os.path.dirname(base)) + len(basedir) + 2\n            for root, dirs, files in os.walk(base):\n                for name in files:\n                    yield os.path.join(basedir, root, name)[rem:]",
    "docstring": "List all files in a data directory."
  },
  {
    "code": "def register_shortcut(self, qaction_or_qshortcut, context, name,\n                          add_sc_to_tip=False):\n        self.main.register_shortcut(qaction_or_qshortcut, context,\n                                    name, add_sc_to_tip)",
    "docstring": "Register QAction or QShortcut to Spyder main application.\n\n        if add_sc_to_tip is True, the shortcut is added to the\n        action's tooltip"
  },
  {
    "code": "def to_dict(self):\n        return {\n            'name': self.name,\n            'id': self.id,\n            'type': self.type,\n            'workflow_id': self.workflow_id,\n            'queue': self.queue,\n            'start_time': self.start_time,\n            'arguments': self.arguments,\n            'acknowledged': self.acknowledged,\n            'func_name': self.func_name,\n            'hostname': self.hostname,\n            'worker_name': self.worker_name,\n            'worker_pid': self.worker_pid,\n            'routing_key': self.routing_key\n        }",
    "docstring": "Return a dictionary of the job stats.\n\n        Returns:\n            dict: Dictionary of the stats."
  },
  {
    "code": "def flavor_extra_set(request, flavor_id, metadata):\n    flavor = _nova.novaclient(request).flavors.get(flavor_id)\n    if (not metadata):\n        return None\n    return flavor.set_keys(metadata)",
    "docstring": "Set the flavor extra spec keys."
  },
  {
    "code": "def conditions(self) -> Dict[str, Dict[str, Union[float, numpy.ndarray]]]:\n        conditions = {}\n        for subname in NAMES_CONDITIONSEQUENCES:\n            subseqs = getattr(self, subname, ())\n            subconditions = {seq.name: copy.deepcopy(seq.values)\n                             for seq in subseqs}\n            if subconditions:\n                conditions[subname] = subconditions\n        return conditions",
    "docstring": "Nested dictionary containing the values of all condition\n        sequences.\n\n        See the documentation on property |HydPy.conditions| for further\n        information."
  },
  {
    "code": "def delete(self):\n        if self._new:\n            raise Exception(\"This is a new object, %s not in data, \\\nindicating this entry isn't stored.\" % self.primaryKey)\n        r.table(self.table).get(self._data[self.primaryKey]) \\\n            .delete(durability=self.durability).run(self._conn)\n        return True",
    "docstring": "Deletes the current instance. This assumes that we know what we're\n        doing, and have a primary key in our data already. If this is a new\n        instance, then we'll let the user know with an Exception"
  },
  {
    "code": "def _response_item_to_object(self, resp_item):\n        item_cls = resources.get_model_class(self.resource_type)\n        properties_dict = resp_item[self.resource_type]\n        new_dict = helpers.remove_properties_containing_None(properties_dict)\n        obj = item_cls(new_dict)\n        return obj",
    "docstring": "take json and make a resource out of it"
  },
  {
    "code": "def add_pool(self, pool, match=None):\n        if match is None:\n            self.default_pool = pool\n        else:\n            self.pools.append((match, pool))",
    "docstring": "Adds a new account pool. If the given match argument is\n        None, the pool the default pool. Otherwise, the match argument is\n        a callback function that is invoked to decide whether or not the\n        given pool should be used for a host.\n\n        When Exscript logs into a host, the account is chosen in the following\n        order:\n\n            # Exscript checks whether an account was attached to the\n            :class:`Host` object using :class:`Host.set_account()`), and uses that.\n\n            # If the :class:`Host` has no account attached, Exscript walks\n            through all pools that were passed to :class:`Queue.add_account_pool()`.\n            For each pool, it passes the :class:`Host` to the function in the\n            given match argument. If the return value is True, the account\n            pool is used to acquire an account.\n            (Accounts within each pool are taken in a round-robin\n            fashion.)\n\n            # If no matching account pool is found, an account is taken\n            from the default account pool.\n\n            # Finally, if all that fails and the default account pool\n            contains no accounts, an error is raised.\n\n        Example usage::\n\n            def do_nothing(conn):\n                conn.autoinit()\n\n            def use_this_pool(host):\n                return host.get_name().startswith('foo')\n\n            default_pool = AccountPool()\n            default_pool.add_account(Account('default-user', 'password'))\n\n            other_pool = AccountPool()\n            other_pool.add_account(Account('user', 'password'))\n\n            queue = Queue()\n            queue.account_manager.add_pool(default_pool)\n            queue.account_manager.add_pool(other_pool, use_this_pool)\n\n            host = Host('localhost')\n            queue.run(host, do_nothing)\n\n        In the example code, the host has no account attached. As a result,\n        the queue checks whether use_this_pool() returns True. Because the\n        hostname does not start with 'foo', the function returns False, and\n        Exscript takes the 'default-user' account from the default pool.\n\n        :type  pool: AccountPool\n        :param pool: The account pool that is added.\n        :type  match: callable\n        :param match: A callback to check if the pool should be used."
  },
  {
    "code": "def realpath(path):\n    if path == '~':\n        return userdir\n    if path == '/':\n        return sysroot\n    if path.startswith('/'):\n        return os.path.abspath(path)\n    if path.startswith('~/'):\n        return os.path.expanduser(path)\n    if path.startswith('./'):\n        return os.path.abspath(os.path.join(os.path.curdir, path[2:]))\n    return os.path.abspath(path)",
    "docstring": "Create the real absolute path for the given path.\n\n    Add supports for userdir & / supports.\n\n    Args:\n        * path: pathname to use for realpath.\n\n    Returns:\n        Platform independent real absolute path."
  },
  {
    "code": "def load_and_check(self, base_settings, prompt=None):\n        checker = Checker(self.file_name, self.section, self.registry, self.strategy_type, prompt)\n        settings = self.load(base_settings)\n        if checker.check(settings):\n            return settings, True\n        return None, False",
    "docstring": "Load settings and check them.\n\n        Loads the settings from ``base_settings``, then checks them.\n\n        Returns:\n            (merged settings, True) on success\n            (None, False) on failure"
  },
  {
    "code": "def _parameter_sweep(self, parameter_space, kernel_options, device_options, tuning_options):\n        results = []\n        parameter_space = list(parameter_space)\n        random.shuffle(parameter_space)\n        work_per_thread = int(numpy.ceil(len(parameter_space) / float(self.max_threads)))\n        chunks = _chunk_list(parameter_space, work_per_thread)\n        for chunk in chunks:\n            chunked_result = self._run_chunk(chunk, kernel_options, device_options, tuning_options)\n            results.append(lift(chunked_result))\n        return gather(*results)",
    "docstring": "Build a Noodles workflow by sweeping the parameter space"
  },
  {
    "code": "def _ParseSourcePathOption(self, options):\n    self._source_path = self.ParseStringOption(options, self._SOURCE_OPTION)\n    if not self._source_path:\n      raise errors.BadConfigOption('Missing source path.')\n    self._source_path = os.path.abspath(self._source_path)",
    "docstring": "Parses the source path option.\n\n    Args:\n      options (argparse.Namespace): command line arguments.\n\n    Raises:\n      BadConfigOption: if the options are invalid."
  },
  {
    "code": "def json(self):\n        try:\n            return json.loads(self.text)\n        except Exception as e:\n            raise ContentDecodingError(e)",
    "docstring": "Load response body as json.\n\n        :raises: :class:`ContentDecodingError`"
  },
  {
    "code": "def email_secure(self):\n        email = self._email\n        if not email: return ''\n        address, host = email.split('@')\n        if len(address) <= 2: return ('*' * len(address)) + '@' + host\n        import re\n        host = '@' + host\n        obfuscated = re.sub(r'[a-zA-z0-9]', '*', address[1:-1])\n        return address[:1] + obfuscated + address[-1:] + host",
    "docstring": "Obfuscated email used for display"
  },
  {
    "code": "def _download_datasets():\n    def filepath(*args):\n        return abspath(join(dirname(__file__), '..', 'vega_datasets', *args))\n    dataset_listing = {}\n    for name in DATASETS_TO_DOWNLOAD:\n        data = Dataset(name)\n        url = data.url\n        filename = filepath('_data', data.filename)\n        print(\"retrieving data {0} -> {1}\".format(url, filename))\n        urlretrieve(url, filename)\n        dataset_listing[name] = '_data/{0}'.format(data.filename)\n    with open(filepath('local_datasets.json'), 'w') as f:\n        json.dump(dataset_listing, f, indent=2, sort_keys=True)",
    "docstring": "Utility to download datasets into package source"
  },
  {
    "code": "def _timed_process(self, *args, **kwargs):\n        for processor in self._processors:\n            start_time = _time.process_time()\n            processor.process(*args, **kwargs)\n            process_time = int(round((_time.process_time() - start_time) * 1000, 2))\n            self.process_times[processor.__class__.__name__] = process_time",
    "docstring": "Track Processor execution time for benchmarking."
  },
  {
    "code": "def _clean_doc(self, doc=None):\n        if doc is None:\n            doc = self.doc\n        resources = doc['Resources']\n        for arg in ['startline', 'headerlines', 'encoding']:\n            for e in list(resources.args):\n                if e.lower() == arg:\n                    resources.args.remove(e)\n        for term in resources:\n            term['startline'] = None\n            term['headerlines'] = None\n            term['encoding'] = None\n        schema = doc['Schema']\n        for arg in ['altname', 'transform']:\n            for e in list(schema.args):\n                if e.lower() == arg:\n                    schema.args.remove(e)\n        for table in self.doc.find('Root.Table'):\n            for col in table.find('Column'):\n                try:\n                    col.value = col['altname'].value\n                except:\n                    pass\n                col['altname'] = None\n                col['transform'] = None\n        return doc",
    "docstring": "Clean the doc before writing it, removing unnecessary properties and doing other operations."
  },
  {
    "code": "def visit_extslice(self, node, parent):\n        newnode = nodes.ExtSlice(parent=parent)\n        newnode.postinit([self.visit(dim, newnode) for dim in node.dims])\n        return newnode",
    "docstring": "visit an ExtSlice node by returning a fresh instance of it"
  },
  {
    "code": "def get_cp2k_structure(atoms):\n    from cp2k_tools.generator import dict2cp2k\n    cp2k_cell = {sym: ('[angstrom]',) + tuple(coords) for sym, coords in zip(('a', 'b', 'c'), atoms.get_cell()*Bohr)}\n    cp2k_cell['periodic'] = 'XYZ'\n    cp2k_coord = {\n        'scaled': True,\n        '*': [[sym] + list(coord) for sym, coord in zip(atoms.get_chemical_symbols(), atoms.get_scaled_positions())],\n        }\n    return dict2cp2k(\n        {\n            'global': {\n                'run_type': 'ENERGY_FORCE',\n                },\n            'force_eval': {\n                'subsys': {\n                    'cell': cp2k_cell,\n                    'coord': cp2k_coord,\n                    },\n                'print': {\n                    'forces': {\n                        'filename': 'forces',\n                        },\n                    },\n                },\n            }\n        )",
    "docstring": "Convert the atoms structure to a CP2K input file skeleton string"
  },
  {
    "code": "def begin_commit():\n    session_token = request.headers['session_token']\n    repository    = request.headers['repository']\n    current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)\n    if current_user is False: return fail(user_auth_fail_msg)\n    repository_path = config['repositories'][repository]['path']\n    def with_exclusive_lock():\n        if not can_aquire_user_lock(repository_path, session_token): return fail(lock_fail_msg)\n        data_store = versioned_storage(repository_path)\n        if data_store.get_head() != request.headers[\"previous_revision\"]: return fail(need_to_update_msg)\n        if data_store.have_active_commit(): data_store.rollback()\n        data_store.begin()\n        update_user_lock(repository_path, session_token)\n        return success()\n    return lock_access(repository_path, with_exclusive_lock)",
    "docstring": "Allow a client to begin a commit and acquire the write lock"
  },
  {
    "code": "def ensure_all_columns_are_used(num_vars_accounted_for,\n                                dataframe,\n                                data_title='long_data'):\n    dataframe_vars = set(dataframe.columns.tolist())\n    num_dataframe_vars = len(dataframe_vars)\n    if num_vars_accounted_for == num_dataframe_vars:\n        pass\n    elif num_vars_accounted_for < num_dataframe_vars:\n        msg = \"Note, there are {:,} variables in {} but the inputs\"\n        msg_2 = \" ind_vars, alt_specific_vars, and subset_specific_vars only\"\n        msg_3 = \" account for {:,} variables.\"\n        warnings.warn(msg.format(num_dataframe_vars, data_title) +\n                      msg_2 + msg_3.format(num_vars_accounted_for))\n    else:\n        msg = \"There are more variable specified in ind_vars, \"\n        msg_2 = \"alt_specific_vars, and subset_specific_vars ({:,}) than there\"\n        msg_3 = \" are variables in {} ({:,})\"\n        warnings.warn(msg +\n                      msg_2.format(num_vars_accounted_for) +\n                      msg_3.format(data_title, num_dataframe_vars))\n    return None",
    "docstring": "Ensure that all of the columns from dataframe are in the list of used_cols.\n    Will raise a helpful UserWarning if otherwise.\n\n    Parameters\n    ----------\n    num_vars_accounted_for : int.\n        Denotes the number of variables used in one's function.\n    dataframe : pandas dataframe.\n        Contains all of the data to be converted from one format to another.\n    data_title : str, optional.\n        Denotes the title by which `dataframe` should be referred in the\n        UserWarning.\n\n    Returns\n    -------\n    None."
  },
  {
    "code": "def _BuildPluginRequest(self, app_id, challenge_data, origin):\n    client_data_map = {}\n    encoded_challenges = []\n    app_id_hash_encoded = self._Base64Encode(self._SHA256(app_id))\n    for challenge_item in challenge_data:\n      key = challenge_item['key']\n      key_handle_encoded = self._Base64Encode(key.key_handle)\n      raw_challenge = challenge_item['challenge']\n      client_data_json = model.ClientData(\n          model.ClientData.TYP_AUTHENTICATION,\n          raw_challenge,\n          origin).GetJson()\n      challenge_hash_encoded = self._Base64Encode(\n          self._SHA256(client_data_json))\n      encoded_challenges.append({\n          'appIdHash': app_id_hash_encoded,\n          'challengeHash': challenge_hash_encoded,\n          'keyHandle': key_handle_encoded,\n          'version': key.version,\n      })\n      key_challenge_pair = (key_handle_encoded, challenge_hash_encoded)\n      client_data_map[key_challenge_pair] = client_data_json\n    signing_request = {\n        'type': 'sign_helper_request',\n        'signData': encoded_challenges,\n        'timeoutSeconds': U2F_SIGNATURE_TIMEOUT_SECONDS,\n        'localAlways': True\n    }\n    return client_data_map, json.dumps(signing_request)",
    "docstring": "Builds a JSON request in the form that the plugin expects."
  },
  {
    "code": "def render_embed_css(self, css_embed: Iterable[bytes]) -> bytes:\n        return b'<style type=\"text/css\">\\n' + b\"\\n\".join(css_embed) + b\"\\n</style>\"",
    "docstring": "Default method used to render the final embedded css for the\n        rendered webpage.\n\n        Override this method in a sub-classed controller to change the output."
  },
  {
    "code": "def clean_asciidoc(text):\n    r\n    text = re.sub(r'(\\b|^)[\\[_*]{1,2}([a-zA-Z0-9])', r'\"\\2', text)\n    text = re.sub(r'([a-zA-Z0-9])[\\]_*]{1,2}', r'\\1\"', text)\n    return text",
    "docstring": "r\"\"\" Transform asciidoc text into ASCII text that NL parsers can handle\n\n    TODO:\n      Tag lines and words with meta data like italics, underlined, bold, title, heading 1, etc\n\n    >>> clean_asciidoc('**Hello** _world_!')\n    '\"Hello\" \"world\"!'"
  },
  {
    "code": "def apply_template(template, *args, **kw):\n    if six.callable(template):\n        return template(*args, **kw)\n    if isinstance(template, six.string_types):\n        return template\n    if isinstance(template, collections.Mapping):\n        return template.__class__((k, apply_template(v, *args, **kw)) for k, v in template.items())\n    if isinstance(template, collections.Iterable):\n        return template.__class__(apply_template(v, *args, **kw) for v in template)\n    return template",
    "docstring": "Applies every callable in any Mapping or Iterable"
  },
  {
    "code": "def describe_page_numbers(current_page, total_count, per_page, page_numbers_at_ends=3, pages_numbers_around_current=3):\n    if total_count:\n        page_count = int(math.ceil(1.0 * total_count / per_page))\n        if page_count < current_page:\n            raise PageNumberOutOfBounds\n        page_numbers = get_page_numbers(\n            current_page=current_page,\n            num_pages=page_count,\n            extremes=page_numbers_at_ends,\n            arounds=pages_numbers_around_current,\n        )\n        current_items_start = (current_page * per_page) - per_page + 1\n        current_items_end = (current_items_start + per_page) - 1\n        if current_items_end > total_count:\n            current_items_end = total_count\n    else:\n        page_count = 0\n        page_numbers = []\n        current_items_start = 0\n        current_items_end = 0\n    return {\n        'numbers': [num for num in page_numbers if not isinstance(num, six.string_types)],\n        'has_previous': 'previous' in page_numbers,\n        'has_next': 'next' in page_numbers,\n        'current_page': current_page,\n        'previous_page': current_page - 1,\n        'next_page': current_page + 1,\n        'total_count': total_count,\n        'page_count': page_count,\n        'per_page': per_page,\n        'current_items_start': current_items_start,\n        'current_items_end': current_items_end,\n    }",
    "docstring": "Produces a description of how to display a paginated list's page numbers. Rather than just\n    spitting out a list of every page available, the page numbers returned will be trimmed\n    to display only the immediate numbers around the start, end, and the current page.\n\n    :param current_page: the current page number (page numbers should start at 1)\n    :param total_count: the total number of items that are being paginated\n    :param per_page: the number of items that are displayed per page\n    :param page_numbers_at_ends: the amount of page numbers to display at the beginning and end of the list\n    :param pages_numbers_around_current: the amount of page numbers to display around the currently selected page\n\n    :return: a dictionary describing the page numbers, relative to the current page"
  },
  {
    "code": "def _merge_pool_kwargs(self, override):\n        base_pool_kwargs = self.connection_pool_kw.copy()\n        if override:\n            for key, value in override.items():\n                if value is None:\n                    try:\n                        del base_pool_kwargs[key]\n                    except KeyError:\n                        pass\n                else:\n                    base_pool_kwargs[key] = value\n        return base_pool_kwargs",
    "docstring": "Merge a dictionary of override values for self.connection_pool_kw.\n\n        This does not modify self.connection_pool_kw and returns a new dict.\n        Any keys in the override dictionary with a value of ``None`` are\n        removed from the merged dictionary."
  },
  {
    "code": "def canonicalize_clusters(clusters: DefaultDict[int, List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]:\n    merged_clusters: List[Set[Tuple[int, int]]] = []\n    for cluster in clusters.values():\n        cluster_with_overlapping_mention = None\n        for mention in cluster:\n            for cluster2 in merged_clusters:\n                if mention in cluster2:\n                    cluster_with_overlapping_mention = cluster2\n                    break\n            if cluster_with_overlapping_mention is not None:\n                break\n        if cluster_with_overlapping_mention is not None:\n            cluster_with_overlapping_mention.update(cluster)\n        else:\n            merged_clusters.append(set(cluster))\n    return [list(c) for c in merged_clusters]",
    "docstring": "The CONLL 2012 data includes 2 annotated spans which are identical,\n    but have different ids. This checks all clusters for spans which are\n    identical, and if it finds any, merges the clusters containing the\n    identical spans."
  },
  {
    "code": "def yaml_force_unicode():\n        if sys.version_info[0] == 2:\n            def construct_func(self, node):\n                return self.construct_scalar(node)\n            yaml.Loader.add_constructor(U('tag:yaml.org,2002:str'), construct_func)\n            yaml.SafeLoader.add_constructor(U('tag:yaml.org,2002:str'), construct_func)",
    "docstring": "Force pyyaml to return unicode values."
  },
  {
    "code": "def try_to_set_up_global_logging():\n    root = logging.getLogger()\n    root.setLevel(logging.DEBUG)\n    formatter = logging.Formatter(\n        '%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d [%(filename)s:%(funcName)s():%(lineno)s] %(message)s')\n    if env.is_debug():\n        handler = logging.StreamHandler()\n        handler.setLevel(logging.DEBUG)\n        handler.setFormatter(formatter)\n        root.addHandler(handler)\n    try:\n        handler = logging.FileHandler(GLOBAL_LOG_FNAME, mode='w')\n        handler.setLevel(logging.DEBUG)\n        handler.setFormatter(formatter)\n        root.addHandler(handler)\n    except IOError as e:\n        termerror('Failed to set up logging: {}'.format(e))\n        return False\n    return True",
    "docstring": "Try to set up global W&B debug log that gets re-written by every W&B process.\n\n    It may fail (and return False) eg. if the current directory isn't user-writable"
  },
  {
    "code": "def list_members(self, name, type=\"USER\", recurse=True, max_results=1000):\n        results = self.client.service.getListMembership(\n            name, type, recurse, max_results, self.proxy_id,\n        )\n        return [item[\"member\"] for item in results]",
    "docstring": "Look up all the members of a list.\n\n        Args:\n            name (str): The name of the list\n            type (str): The type of results to return. \"USER\" to get users,\n                \"LIST\" to get lists.\n            recurse (bool): Presumably, whether to recurse into member lists\n                when retrieving users.\n            max_results (int): Maximum number of results to return.\n\n        Returns:\n            list of strings: names of the members of the list"
  },
  {
    "code": "def getPeer(self, url):\n        peers = filter(lambda x: x.getUrl() == url, self.getPeers())\n        if len(peers) == 0:\n            raise exceptions.PeerNotFoundException(url)\n        return peers[0]",
    "docstring": "Select the first peer in the datarepo with the given url simulating\n        the behavior of selecting by URL. This is only used during testing."
  },
  {
    "code": "def _conv(self, data):\n        if isinstance(data, pd.Series):\n            if data.name is None:\n                data = data.to_frame(name='')\n            else:\n                data = data.to_frame()\n        data = data.fillna('NaN')\n        return data",
    "docstring": "Convert each input to appropriate for table outplot"
  },
  {
    "code": "def _send_command_list(self, commands):\n        output = \"\"\n        for command in commands:\n            output += self.device.send_command(\n                command, strip_prompt=False, strip_command=False\n            )\n        return output",
    "docstring": "Wrapper for Netmiko's send_command method (for list of commands."
  },
  {
    "code": "def process_tomography_programs(process, qubits=None,\n                                pre_rotation_generator=tomography.default_rotations,\n                                post_rotation_generator=tomography.default_rotations):\n    if qubits is None:\n        qubits = process.get_qubits()\n    for tomographic_pre_rotation in pre_rotation_generator(*qubits):\n        for tomography_post_rotation in post_rotation_generator(*qubits):\n            process_tomography_program = Program(Pragma(\"PRESERVE_BLOCK\"))\n            process_tomography_program.inst(tomographic_pre_rotation)\n            process_tomography_program.inst(process)\n            process_tomography_program.inst(tomography_post_rotation)\n            process_tomography_program.inst(Pragma(\"END_PRESERVE_BLOCK\"))\n            yield process_tomography_program",
    "docstring": "Generator that yields tomographic sequences that wrap a process encoded by a QUIL program `proc`\n    in tomographic rotations on the specified `qubits`.\n\n    If `qubits is None`, it assumes all qubits in the program should be\n    tomographically rotated.\n\n    :param Program process: A Quil program\n    :param list|NoneType qubits: The specific qubits for which to generate the tomographic sequences\n    :param pre_rotation_generator: A generator that yields tomographic pre-rotations to perform.\n    :param post_rotation_generator: A generator that yields tomographic post-rotations to perform.\n    :return: Program for process tomography.\n    :rtype: Program"
  },
  {
    "code": "def WSDLUriToVersion(self, uri):\n        value = self._wsdl_uri_mapping.get(uri)\n        if value is not None:\n            return value\n        raise ValueError(\n            'Unsupported SOAP envelope uri: %s' % uri\n            )",
    "docstring": "Return the WSDL version related to a WSDL namespace uri."
  },
  {
    "code": "def closeEvent(self, event):\n        max_dataset_history = self.value('max_dataset_history')\n        keep_recent_datasets(max_dataset_history, self.info)\n        settings.setValue('window/geometry', self.saveGeometry())\n        settings.setValue('window/state', self.saveState())\n        event.accept()",
    "docstring": "save the name of the last open dataset."
  },
  {
    "code": "def get_package_info_from_line(tpip_pkg, line):\n    lower_line = line.lower()\n    try:\n        metadata_key, metadata_value = lower_line.split(':', 1)\n    except ValueError:\n        return\n    metadata_key = metadata_key.strip()\n    metadata_value = metadata_value.strip()\n    if metadata_value == 'unknown':\n        return\n    if metadata_key in TPIP_FIELD_MAPPINGS:\n        tpip_pkg[TPIP_FIELD_MAPPINGS[metadata_key]] = metadata_value\n        return\n    if metadata_key.startswith('version') and not tpip_pkg.get('PkgVersion'):\n        tpip_pkg['PkgVersion'] = metadata_value\n        return\n    if 'licen' in lower_line:\n        if metadata_key.startswith('classifier') or '::' in metadata_value:\n            license = lower_line.rsplit(':')[-1].strip().lower()\n            license = license_cleanup(license)\n            if license:\n                tpip_pkg.setdefault('PkgLicenses', []).append(license)",
    "docstring": "Given a line of text from metadata, extract semantic info"
  },
  {
    "code": "def _module_iterator(root, recursive=True):\n    yield root\n    stack = collections.deque((root,))\n    while stack:\n        package = stack.popleft()\n        paths = getattr(package, '__path__', [])\n        for path in paths:\n            modules = pkgutil.iter_modules([path])\n            for finder, name, is_package in modules:\n                module_name = '%s.%s' % (package.__name__, name)\n                module = sys.modules.get(module_name, None)\n                if module is None:\n                    module = _load_module(finder, module_name)\n                if is_package:\n                    if recursive:\n                        stack.append(module)\n                        yield module\n                else:\n                    yield module",
    "docstring": "Iterate over modules."
  },
  {
    "code": "def get_constant_state(self):\n    ret = self.constant_states[self.next_constant_state]\n    self.next_constant_state += 1\n    return ret",
    "docstring": "Read state that was written in \"first_part\" mode.\n\n    Returns:\n      a structure"
  },
  {
    "code": "def delete(self, url, headers=None, **kwargs):\n        if headers is None: headers = []\n        if kwargs:\n            url = url + UrlEncoded('?' + _encode(**kwargs), skip_encode=True)\n        message = {\n            'method': \"DELETE\",\n            'headers': headers,\n        }\n        return self.request(url, message)",
    "docstring": "Sends a DELETE request to a URL.\n\n        :param url: The URL.\n        :type url: ``string``\n        :param headers: A list of pairs specifying the headers for the HTTP\n            response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``).\n        :type headers: ``list``\n        :param kwargs: Additional keyword arguments (optional). These arguments\n            are interpreted as the query part of the URL. The order of keyword\n            arguments is not preserved in the request, but the keywords and\n            their arguments will be URL encoded.\n        :type kwargs: ``dict``\n        :returns: A dictionary describing the response (see :class:`HttpLib` for\n            its structure).\n        :rtype: ``dict``"
  },
  {
    "code": "def convert_to_vertexlist(geometry, **kwargs):\n    if util.is_instance_named(geometry, 'Trimesh'):\n        return mesh_to_vertexlist(geometry, **kwargs)\n    elif util.is_instance_named(geometry, 'Path'):\n        return path_to_vertexlist(geometry, **kwargs)\n    elif util.is_instance_named(geometry, 'PointCloud'):\n        return points_to_vertexlist(geometry.vertices,\n                                    colors=geometry.colors,\n                                    **kwargs)\n    elif util.is_instance_named(geometry, 'ndarray'):\n        return points_to_vertexlist(geometry, **kwargs)\n    else:\n        raise ValueError('Geometry passed is not a viewable type!')",
    "docstring": "Try to convert various geometry objects to the constructor\n    args for a pyglet indexed vertex list.\n\n    Parameters\n    ------------\n    obj : Trimesh, Path2D, Path3D, (n,2) float, (n,3) float\n      Object to render\n\n    Returns\n    ------------\n    args : tuple\n      Args to be passed to pyglet indexed vertex list\n      constructor."
  },
  {
    "code": "def condition_on_par_knowledge(cov,par_knowledge_dict):\n    missing = []\n    for parnme in par_knowledge_dict.keys():\n        if parnme not in cov.row_names:\n            missing.append(parnme)\n    if len(missing):\n        raise Exception(\"par knowledge dict parameters not found: {0}\".\\\n                        format(','.join(missing)))\n    sel = cov.zero2d\n    sigma_ep = cov.zero2d\n    for parnme,var in par_knowledge_dict.items():\n        idx = cov.row_names.index(parnme)\n        sel.x[idx,idx] = 1.0\n        sigma_ep.x[idx,idx] = var\n    print(sel)\n    term2 = sel * cov * sel.T\n    print(term2)\n    term2 = term2.inv\n    term2 *= sel\n    term2 *= cov\n    new_cov = cov - term2\n    return new_cov",
    "docstring": "experimental function to include conditional prior information\n    for one or more parameters in a full covariance matrix"
  },
  {
    "code": "def add_scroller_widget(self, ref, left=1, top=1, right=20, bottom=1, direction=\"h\", speed=1, text=\"Message\"):     \n        if ref not in self.widgets:   \n            widget = ScrollerWidget(screen=self, ref=ref, left=left, top=top, right=right, bottom=bottom, direction=direction, speed=speed, text=text)\n            self.widgets[ref] = widget\n            return self.widgets[ref]",
    "docstring": "Add Scroller Widget"
  },
  {
    "code": "def enable_disable(self):\n        if self.enabled:\n            self.data['enabled'] = False\n        else:\n            self.data['enabled'] = True\n        self.update()",
    "docstring": "Enable or disable this endpoint. If enabled, it will be disabled\n        and vice versa.\n\n        :return: None"
  },
  {
    "code": "def get_experiment_status(port):\n    result, response = check_rest_server_quick(port)\n    if result:\n        return json.loads(response.text).get('status')\n    return None",
    "docstring": "get the status of an experiment"
  },
  {
    "code": "def filename( self, node ):\n        if not node.directory:\n            return None\n        if node.filename == '~':\n            return None\n        return os.path.join(node.directory, node.filename)",
    "docstring": "Extension to squaremap api to provide \"what file is this\" information"
  },
  {
    "code": "def Reorder(x, params, output=None, **kwargs):\n  del params, kwargs\n  if output is None:\n    return x\n  return base.nested_map(output, lambda i: x[i])",
    "docstring": "Reorder a tuple into another tuple.\n\n  For example, we can re-order (x, y) into (y, x) or even (y, (x, y), y).\n  The output argument specifies how to re-order, using integers that refer\n  to indices in the input tuple. For example, if\n\n    input = (x, y, z)\n\n  then\n\n    Reorder(input, output=(1, 0, 2))   = (y, x, z)\n    Reorder(input, output=(0, 0))      = (x, x)\n    Reorder(input, output=(0, (1, 1))) = (x, (y, y))\n    Reorder(input, output=((2, 0), (1, 1))) = ((z, x), (y, y))\n\n  By default (if no output is given) Reorder does nothing (Identity).\n\n  Args:\n    x: the input tuple to re-order.\n    params: layer parameters (unused).\n    output: the specification of the output tuple: a nested tuple of ints.\n    **kwargs: other arguments (unused).\n\n  Returns:\n    The re-ordered tuple with the same shape as output."
  },
  {
    "code": "def _ratio_scores(parameters_value, clusteringmodel_gmm_good, clusteringmodel_gmm_bad):\n    ratio = clusteringmodel_gmm_good.score([parameters_value]) / clusteringmodel_gmm_bad.score([parameters_value])\n    sigma = 0\n    return ratio, sigma",
    "docstring": "The ratio is smaller the better"
  },
  {
    "code": "def size(pathname):\n    if os.path.isfile(pathname):\n        return os.path.getsize(pathname)\n    return sum([size('{}/{}'.format(pathname, name)) for name in get_content_list(pathname)])",
    "docstring": "Returns size of a file or folder in Bytes\n\n    :param pathname: path to file or folder to be sized\n    :type pathname: str\n    :return: size of file or folder in Bytes\n    :rtype: int\n    :raises: os.error if file is not accessible"
  },
  {
    "code": "def delete(self):\n        with self._qpart:\n            for cursor in self.cursors():\n                if cursor.hasSelection():\n                    cursor.deleteChar()",
    "docstring": "Del or Backspace pressed. Delete selection"
  },
  {
    "code": "def getratio(self, code) :\n\t\tif len(code) == 0 : return 0\n\t\tcode_replaced = self.prog.sub('', code)\n\t\treturn (len(code) - len(code_replaced)) / len(code)",
    "docstring": "Get ratio of code and pattern matched"
  },
  {
    "code": "def _cla_adder_unit(a, b, cin):\n    gen = a & b\n    prop = a ^ b\n    assert(len(prop) == len(gen))\n    carry = [gen[0] | prop[0] & cin]\n    sum_bit = prop[0] ^ cin\n    cur_gen = gen[0]\n    cur_prop = prop[0]\n    for i in range(1, len(prop)):\n        cur_gen = gen[i] | (prop[i] & cur_gen)\n        cur_prop = cur_prop & prop[i]\n        sum_bit = pyrtl.concat(prop[i] ^ carry[i - 1], sum_bit)\n        carry.append(gen[i] | (prop[i] & carry[i-1]))\n    cout = cur_gen | (cur_prop & cin)\n    return sum_bit, cout",
    "docstring": "Carry generation and propogation signals will be calculated only using\n    the inputs; their values don't rely on the sum.  Every unit generates\n    a cout signal which is used as cin for the next unit."
  },
  {
    "code": "def _has_role(self, organisation_id, role):\n        if organisation_id is None:\n            return False\n        try:\n            org = self.organisations.get(organisation_id, {})\n            user_role = org.get('role')\n            state = org.get('state')\n        except AttributeError:\n            return False\n        return user_role == role.value and state == State.approved.name",
    "docstring": "Check the user's role for the organisation"
  },
  {
    "code": "def _retryable_read_command(self, command, value=1, check=True,\n                allowable_errors=None, read_preference=None,\n                codec_options=DEFAULT_CODEC_OPTIONS, session=None, **kwargs):\n        if read_preference is None:\n            read_preference = ((session and session._txn_read_preference())\n                               or ReadPreference.PRIMARY)\n        def _cmd(session, server, sock_info, slave_ok):\n            return self._command(sock_info, command, slave_ok, value,\n                                 check, allowable_errors, read_preference,\n                                 codec_options, session=session, **kwargs)\n        return self.__client._retryable_read(\n            _cmd, read_preference, session)",
    "docstring": "Same as command but used for retryable read commands."
  },
  {
    "code": "def add_field(self, name, fragment_size=150, number_of_fragments=3, fragment_offset=None, order=\"score\", type=None):\n        data = {}\n        if fragment_size:\n            data['fragment_size'] = fragment_size\n        if number_of_fragments is not None:\n            data['number_of_fragments'] = number_of_fragments\n        if fragment_offset is not None:\n            data['fragment_offset'] = fragment_offset\n        if type is not None:\n            data['type'] = type\n        data['order'] = order\n        self.fields[name] = data",
    "docstring": "Add a field to Highlinghter"
  },
  {
    "code": "def get_instance(self, payload):\n        return WorkflowInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], )",
    "docstring": "Build an instance of WorkflowInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance\n        :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance"
  },
  {
    "code": "def dump(self):\n        return dict(\n            self.other, name=self.name, url=self.url,\n            credentials=self.credentials, description=self.description,\n        )",
    "docstring": "Return a dict of fields that can be used to recreate this profile.\n\n        For example::\n\n          >>> profile = Profile(name=\"foobar\", ...)\n          >>> profile == Profile(**profile.dump())\n          True\n\n        Use this value when persisting a profile."
  },
  {
    "code": "def append(self, entry):\n        if not self.is_appendable(entry):\n            raise ValueError('entry not appendable')\n        self.data += entry.data",
    "docstring": "Append an entry to self"
  },
  {
    "code": "def get_importer(path_item):\n    try:\n        importer = sys.path_importer_cache[path_item]\n    except KeyError:\n        for path_hook in sys.path_hooks:\n            try:\n                importer = path_hook(path_item)\n                break\n            except ImportError:\n                pass\n        else:\n            importer = None\n        sys.path_importer_cache.setdefault(path_item, importer)\n    if importer is None:\n        try:\n            importer = ImpImporter(path_item)\n        except ImportError:\n            importer = None\n    return importer",
    "docstring": "Retrieve a PEP 302 importer for the given path item\n\n    The returned importer is cached in sys.path_importer_cache\n    if it was newly created by a path hook.\n\n    If there is no importer, a wrapper around the basic import\n    machinery is returned. This wrapper is never inserted into\n    the importer cache (None is inserted instead).\n\n    The cache (or part of it) can be cleared manually if a\n    rescan of sys.path_hooks is necessary."
  },
  {
    "code": "def get_apis(self):\n        out = set(x.api for x in self.types.values() if x.api)\n        for ft in self.features.values():\n            out.update(ft.get_apis())\n        for ext in self.extensions.values():\n            out.update(ext.get_apis())\n        return out",
    "docstring": "Returns set of api names referenced in this Registry\n\n        :return: set of api name strings"
  },
  {
    "code": "def file_can_be_written(path):\n    if path is None:\n        return False\n    try:\n        with io.open(path, \"wb\") as test_file:\n            pass\n        delete_file(None, path)\n        return True\n    except (IOError, OSError):\n        pass\n    return False",
    "docstring": "Return ``True`` if a file can be written at the given ``path``.\n\n    :param string path: the file path\n    :rtype: bool\n\n    .. warning:: This function will attempt to open the given ``path``\n                 in write mode, possibly destroying the file previously existing there.\n\n    .. versionadded:: 1.4.0"
  },
  {
    "code": "def readlines(self, timeout=1):\n        lines = []\n        while 1:\n            line = self.readline(timeout=timeout)\n            if line:\n                lines.append(line)\n            if not line or line[-1:] != '\\n':\n                break\n        return lines",
    "docstring": "read all lines that are available. abort after timeout\n        when no more data arrives."
  },
  {
    "code": "def onStart(self, event):\n        c = event.container\n        print '+' * 5, 'started:', c\n        kv = lambda s: s.split('=', 1)\n        env = {k: v for (k, v) in (kv(s) for s in c.attrs['Config']['Env'])}\n        print env",
    "docstring": "Display the environment of a started container"
  },
  {
    "code": "def refresh(self) -> None:\n        logger.info('refreshing sources')\n        for source in list(self):\n            self.unload(source)\n        if not os.path.exists(self.__registry_fn):\n            return\n        with open(self.__registry_fn, 'r') as f:\n            registry = yaml.load(f)\n        assert isinstance(registry, list)\n        for source_description in registry:\n            source = Source.from_dict(source_description)\n            self.load(source)\n        logger.info('refreshed sources')",
    "docstring": "Reloads all sources that are registered with this server."
  },
  {
    "code": "def run_locally(self):\n        self.thread = threading.Thread(target=self.execute_locally)\n        self.thread.daemon = True\n        self.thread.start()",
    "docstring": "A convenience method to run the same result as a SLURM job\n        but locally in a non-blocking way. Useful for testing."
  },
  {
    "code": "def find_existing(self):\n        instances = self.consul.find_servers(self.tags)\n        maxnames = len(instances)\n        while instances:\n            i = instances.pop(0)\n            server_id = i[A.server.ID]\n            if self.namespace.add_if_unique(server_id):\n                log.info('Found existing server, %s' % server_id)\n                self.server_attrs = i\n                break\n            if len(self.namespace.names) >= maxnames:\n                break\n            instances.append(i)",
    "docstring": "Searches for existing server instances with matching tags.  To match,\n        the existing instances must also be \"running\"."
  },
  {
    "code": "def walkSignalPorts(rootPort: LPort):\n    if rootPort.children:\n        for ch in rootPort.children:\n            yield from walkSignalPorts(ch)\n    else:\n        yield rootPort",
    "docstring": "recursively walk ports without any children"
  },
  {
    "code": "def handler(ca_file=None):\n    def request(url, message, **kwargs):\n        scheme, host, port, path = spliturl(url)\n        if scheme != \"https\": \n            ValueError(\"unsupported scheme: %s\" % scheme)\n        connection = HTTPSConnection(host, port, ca_file)\n        try:\n            body = message.get('body', \"\")\n            headers = dict(message.get('headers', []))\n            connection.request(message['method'], path, body, headers)\n            response = connection.getresponse()\n        finally:\n            connection.close()\n        return {\n            'status': response.status,\n            'reason': response.reason,\n            'headers': response.getheaders(),\n            'body': BytesIO(response.read())\n        }\n    return request",
    "docstring": "Returns an HTTP request handler configured with the given ca_file."
  },
  {
    "code": "def addlayer(self, name, srs, geomType):\n        self.vector.CreateLayer(name, srs, geomType)\n        self.init_layer()",
    "docstring": "add a layer to the vector layer\n\n        Parameters\n        ----------\n        name: str\n            the layer name\n        srs: int, str or :osgeo:class:`osr.SpatialReference`\n            the spatial reference system. See :func:`spatialist.auxil.crsConvert` for options.\n        geomType: int\n            an OGR well-known binary data type.\n            See `Module ogr <https://gdal.org/python/osgeo.ogr-module.html>`_.\n\n        Returns\n        -------"
  },
  {
    "code": "def bit_reversal(qubits: List[int]) -> Program:\n    p = Program()\n    n = len(qubits)\n    for i in range(int(n / 2)):\n        p.inst(SWAP(qubits[i], qubits[-i - 1]))\n    return p",
    "docstring": "Generate a circuit to do bit reversal.\n\n    :param qubits: Qubits to do bit reversal with.\n    :return: A program to do bit reversal."
  },
  {
    "code": "def get_input(prompt, check, *, redo_prompt=None, repeat_prompt=False):\n    if isinstance(check, str):\n        check = (check,)\n    to_join = []\n    for item in check:\n        if item:\n            to_join.append(str(item))\n        else:\n            to_join.append(\"''\")\n    prompt += \" [{}]: \".format('/'.join(to_join))\n    if repeat_prompt:\n        redo_prompt = prompt\n    elif not redo_prompt:\n        redo_prompt = \"Incorrect input, please choose from {}: \" \\\n                      \"\".format(str(check))\n    if callable(check):\n        def _checker(r): return check(r)\n    elif isinstance(check, tuple):\n        def _checker(r): return r in check\n    else:\n        raise ValueError(RESPONSES_ERROR.format(type(check)))\n    response = input(prompt)\n    while not _checker(response):\n        print(response, type(response))\n        response = input(redo_prompt if redo_prompt else prompt)\n    return response",
    "docstring": "Ask the user to input something on the terminal level, check their response\n    and ask again if they didn't answer correctly"
  },
  {
    "code": "def get_client_properties_per_page(self, per_page=1000, page=1, params=None):\n        return self._get_resource_per_page(\n            resource=CLIENT_PROPERTIES,\n            per_page=per_page,\n            page=page,\n            params=params\n        )",
    "docstring": "Get client properties per page\n\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :param params: Search parameters. Default: {}\n        :return: list"
  },
  {
    "code": "def class_name_str(obj, skip_parent=False):\n    rt = str(type(obj)).split(\" \")[1][1:-2]\n    if skip_parent:\n        rt = rt.split(\".\")[-1]\n    return rt",
    "docstring": "return's object's class name as string"
  },
  {
    "code": "def ecb(base, target):\n    api_url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'\n    resp = requests.get(api_url, timeout=1)\n    text = resp.text\n    def _find_rate(symbol):\n        if symbol == 'EUR':\n            return decimal.Decimal(1.00)\n        m = re.findall(r\"currency='%s' rate='([0-9\\.]+)'\" % symbol, text)\n        return decimal.Decimal(m[0])\n    return _find_rate(target) / _find_rate(base)",
    "docstring": "Parse data from European Central Bank."
  },
  {
    "code": "def create_prj_model(self, ):\n        prjs = djadapter.projects.all()\n        rootdata = treemodel.ListItemData(['Name', 'Short', 'Rootpath'])\n        prjroot = treemodel.TreeItem(rootdata)\n        for prj in prjs:\n            prjdata = djitemdata.ProjectItemData(prj)\n            treemodel.TreeItem(prjdata, prjroot)\n        prjmodel = treemodel.TreeModel(prjroot)\n        return prjmodel",
    "docstring": "Create and return a tree model that represents a list of projects\n\n        :returns: the creeated model\n        :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel`\n        :raises: None"
  },
  {
    "code": "def _hash_data(hasher, data):\n    _hasher = hasher.copy()\n    _hasher.update(data)\n    return _hasher.finalize()",
    "docstring": "Generate hash of data using provided hash type.\n\n    :param hasher: Hasher instance to use as a base for calculating hash\n    :type hasher: cryptography.hazmat.primitives.hashes.Hash\n    :param bytes data: Data to sign\n    :returns: Hash of data\n    :rtype: bytes"
  },
  {
    "code": "def _ensure_filepath(filename):\n        filepath = os.path.dirname(filename)\n        if not os.path.exists(filepath):\n            os.makedirs(filepath)",
    "docstring": "Ensure that the directory exists before trying to write to the file."
  },
  {
    "code": "def total_count(self, total_count):\n        if total_count is None:\n            raise ValueError(\"Invalid value for `total_count`, must not be `None`\")\n        if total_count is not None and total_count < 0:\n            raise ValueError(\"Invalid value for `total_count`, must be a value greater than or equal to `0`\")\n        self._total_count = total_count",
    "docstring": "Sets the total_count of this ServicePackageQuotaHistoryResponse.\n        Sum of all quota history entries that should be returned\n\n        :param total_count: The total_count of this ServicePackageQuotaHistoryResponse.\n        :type: int"
  },
  {
    "code": "def get_pattern_actual_step(self, patternnumber):\n        _checkPatternNumber(patternnumber)\n        address = _calculateRegisterAddress('actualstep', patternnumber)\n        return self.read_register(address, 0)",
    "docstring": "Get the 'actual step' parameter for a given pattern.\n\n        Args:\n            patternnumber (integer): 0-7\n\n        Returns:\n            The 'actual step' parameter (int)."
  },
  {
    "code": "def load_plugin(module_name: str) -> bool:\n    try:\n        module = importlib.import_module(module_name)\n        name = getattr(module, '__plugin_name__', None)\n        usage = getattr(module, '__plugin_usage__', None)\n        _plugins.add(Plugin(module, name, usage))\n        logger.info(f'Succeeded to import \"{module_name}\"')\n        return True\n    except Exception as e:\n        logger.error(f'Failed to import \"{module_name}\", error: {e}')\n        logger.exception(e)\n        return False",
    "docstring": "Load a module as a plugin.\n\n    :param module_name: name of module to import\n    :return: successful or not"
  },
  {
    "code": "def remove_cts_record(file_name, map, position):\n    db = XonoticDB.load_path(file_name)\n    db.remove_cts_record(map, position)\n    db.save(file_name)",
    "docstring": "Remove cts record on MAP and POSITION"
  },
  {
    "code": "def update(self, device_json=None, info_json=None, settings_json=None,\n               avatar_json=None):\n        if device_json:\n            UTILS.update(self._device_json, device_json)\n        if avatar_json:\n            UTILS.update(self._avatar_json, avatar_json)\n        if info_json:\n            UTILS.update(self._info_json, info_json)\n        if settings_json:\n            UTILS.update(self._settings_json, settings_json)",
    "docstring": "Update the internal device json data."
  },
  {
    "code": "def clear_dead_threads(self):\n        for tid in self.get_thread_ids():\n            aThread = self.get_thread(tid)\n            if not aThread.is_alive():\n                self._del_thread(aThread)",
    "docstring": "Remove Thread objects from the snapshot\n        referring to threads no longer running."
  },
  {
    "code": "def _create_session(self, username, password):\n    session = requests.Session()\n    session.verify = False\n    try:\n      response = session.get(self.host_url)\n    except requests.exceptions.ConnectionError:\n      return False\n    soup = BeautifulSoup(response.text, 'html.parser')\n    csrf_token = soup.find('input', dict(name='csrf_token'))['value']\n    login_data = dict(username=username, password=password)\n    session.headers.update({\n        'x-csrftoken': csrf_token,\n        'referer': self.host_url\n    })\n    _ = session.post('{0:s}/login/'.format(self.host_url), data=login_data)\n    return session",
    "docstring": "Create HTTP session.\n\n    Args:\n      username (str): Timesketch username\n      password (str): Timesketch password\n\n    Returns:\n      requests.Session: Session object."
  },
  {
    "code": "def focusedWindow(cls):\n        x, y, w, h = PlatformManager.getWindowRect(PlatformManager.getForegroundWindow())\n        return Region(x, y, w, h)",
    "docstring": "Returns a Region corresponding to whatever window is in the foreground"
  },
  {
    "code": "def orchestrate_show_sls(mods,\n                         saltenv='base',\n                         test=None,\n                         queue=False,\n                         pillar=None,\n                         pillarenv=None,\n                         pillar_enc=None):\n    if pillar is not None and not isinstance(pillar, dict):\n        raise SaltInvocationError(\n            'Pillar data must be formatted as a dictionary')\n    __opts__['file_client'] = 'local'\n    minion = salt.minion.MasterMinion(__opts__)\n    running = minion.functions['state.show_sls'](\n        mods,\n        test,\n        queue,\n        pillar=pillar,\n        pillarenv=pillarenv,\n        pillar_enc=pillar_enc,\n        saltenv=saltenv)\n    ret = {minion.opts['id']: running}\n    return ret",
    "docstring": "Display the state data from a specific sls, or list of sls files, after\n    being render using the master minion.\n\n    Note, the master minion adds a \"_master\" suffix to it's minion id.\n\n    .. seealso:: The state.show_sls module function\n\n    CLI Example:\n    .. code-block:: bash\n\n        salt-run state.orch_show_sls my-orch-formula.my-orch-state 'pillar={ nodegroup: ng1 }'"
  },
  {
    "code": "def get_meta(self):\n        rdf = self.get_meta_rdf(fmt='n3')\n        return PointMeta(self, rdf, self._client.default_lang, fmt='n3')",
    "docstring": "Get the metadata object for this Point\n\n        Returns a [PointMeta](PointMeta.m.html#IoticAgent.IOT.PointMeta.PointMeta) object - OR -\n\n        Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)\n        containing the error if the infrastructure detects a problem\n\n        Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)\n        if there is a communications problem between you and the infrastructure"
  },
  {
    "code": "def connect(self):\n        connection = _mssql.connect(user=self.user,\n                                    password=self.password,\n                                    server=self.host,\n                                    port=self.port,\n                                    database=self.database)\n        return connection",
    "docstring": "Create a SQL Server connection and return a connection object"
  },
  {
    "code": "def run(path, code=None, params=None, **meta):\n        import _ast\n        builtins = params.get(\"builtins\", \"\")\n        if builtins:\n            builtins = builtins.split(\",\")\n        tree = compile(code, path, \"exec\", _ast.PyCF_ONLY_AST)\n        w = checker.Checker(tree, path, builtins=builtins)\n        w.messages = sorted(w.messages, key=lambda m: m.lineno)\n        return [{\n            'lnum': m.lineno,\n            'text': m.message % m.message_args,\n            'type': m.message[0]\n        } for m in w.messages]",
    "docstring": "Check code with pyflakes.\n\n        :return list: List of errors."
  },
  {
    "code": "def stop(self):\n        self._target = self.position\n        self.log.info('Stopping movement after user request.')\n        return self.target, self.position",
    "docstring": "Stops the motor and returns the new target and position, which are equal"
  },
  {
    "code": "def call_heat(tstat):\n    current_hsp, current_csp = tstat.heating_setpoint, tstat.cooling_setpoint\n    current_temp = tstat.temperature\n    tstat.write({\n        'heating_setpoint': current_temp+10,\n        'cooling_setpoint': current_temp+20,\n        'mode': HEAT,\n    })\n    def restore():\n        tstat.write({\n            'heating_setpoint': current_hsp,\n            'cooling_setpoint': current_csp,\n            'mode': AUTO,\n        })\n    return restore",
    "docstring": "Adjusts the temperature setpoints in order to call for heating. Returns\n    a handler to call when you want to reset the thermostat"
  },
  {
    "code": "def CollectionItemToClientPath(item, client_id=None):\n  if isinstance(item, rdf_flows.GrrMessage):\n    client_id = item.source\n    item = item.payload\n  elif isinstance(item, rdf_flow_objects.FlowResult):\n    client_id = item.client_id\n    item = item.payload\n  if client_id is None:\n    raise ValueError(\"Could not determine client_id.\")\n  elif isinstance(client_id, rdfvalue.RDFURN):\n    client_id = client_id.Basename()\n  if isinstance(item, rdf_client_fs.StatEntry):\n    return db.ClientPath.FromPathSpec(client_id, item.pathspec)\n  elif isinstance(item, rdf_file_finder.FileFinderResult):\n    return db.ClientPath.FromPathSpec(client_id, item.stat_entry.pathspec)\n  elif isinstance(item, collectors.ArtifactFilesDownloaderResult):\n    if item.HasField(\"downloaded_file\"):\n      return db.ClientPath.FromPathSpec(client_id,\n                                        item.downloaded_file.pathspec)\n  raise ItemNotExportableError(item)",
    "docstring": "Converts given RDFValue to a ClientPath of a file to be downloaded."
  },
  {
    "code": "def make_save_locals_impl():\n    try:\n        if '__pypy__' in sys.builtin_module_names:\n            import __pypy__\n            save_locals = __pypy__.locals_to_fast\n    except:\n        pass\n    else:\n        if '__pypy__' in sys.builtin_module_names:\n            def save_locals_pypy_impl(frame):\n                save_locals(frame)\n            return save_locals_pypy_impl\n    try:\n        import ctypes\n        locals_to_fast = ctypes.pythonapi.PyFrame_LocalsToFast\n    except:\n        pass\n    else:\n        def save_locals_ctypes_impl(frame):\n            locals_to_fast(ctypes.py_object(frame), ctypes.c_int(0))\n        return save_locals_ctypes_impl\n    return None",
    "docstring": "Factory for the 'save_locals_impl' method. This may seem like a complicated pattern but it is essential that the method is created at\n    module load time. Inner imports after module load time would cause an occasional debugger deadlock due to the importer lock and debugger\n    lock being taken in different order in  different threads."
  },
  {
    "code": "def exportable(self):\n        if 'ExportableCertification' in self._signature.subpackets:\n            return bool(next(iter(self._signature.subpackets['ExportableCertification'])))\n        return True",
    "docstring": "``False`` if this signature is marked as being not exportable. Otherwise, ``True``."
  },
  {
    "code": "def save(self, *objects):\n        if len(objects) > 0:\n            self.session.add_all(objects)\n        self.session.commit()",
    "docstring": "Add all the objects to the session and commit them.\n\n        This only needs to be done for networks and participants."
  },
  {
    "code": "def converge(f, step, tol, max_h):\n    g = f(0)\n    dx = 10000\n    h = step\n    while (dx > tol):\n        g2 = f(h)\n        dx = abs(g - g2)\n        g = g2\n        h += step\n        if h > max_h:\n            raise Exception(\"Did not converge before {}\".format(h))\n    return g",
    "docstring": "simple newton iteration based convergence function"
  },
  {
    "code": "def _clone(self, *args, **kwargs):\n        for attr in (\"_search_terms\", \"_search_fields\", \"_search_ordered\"):\n            kwargs[attr] = getattr(self, attr)\n        return super(SearchableQuerySet, self)._clone(*args, **kwargs)",
    "docstring": "Ensure attributes are copied to subsequent queries."
  },
  {
    "code": "def to_xml(self):\n        for n, v in { \"amount\": self.amount, \"date\": self.date,\n                     \"method\":self.method}.items():\n            if is_empty_or_none(v):\n                raise PaymentError(\"'%s' attribute cannot be empty or \" \\\n                                       \"None.\" % n)\n        doc = Document()\n        root = doc.createElement(\"payment\")\n        super(Payment, self).to_xml(root)\n        self._create_text_node(root, \"amount\", self.amount)\n        self._create_text_node(root, \"method\", self.method)\n        self._create_text_node(root, \"reference\", self.ref, True)\n        self._create_text_node(root, \"date\", self.date)\n        return root",
    "docstring": "Returns a DOM representation of the payment.\n        @return: Element"
  },
  {
    "code": "def _enqueue_eor_msg(self, sor):\n        if self._protocol.is_enhanced_rr_cap_valid() and not sor.eor_sent:\n            afi = sor.afi\n            safi = sor.safi\n            eor = BGPRouteRefresh(afi, safi, demarcation=2)\n            self.enque_outgoing_msg(eor)\n            sor.eor_sent = True",
    "docstring": "Enqueues Enhanced RR EOR if for given SOR a EOR is not already\n        sent."
  },
  {
    "code": "def encode(input, output_filename):\n    coder = rs.RSCoder(255,223)\n    output = []\n    while True:\n        block = input.read(223)\n        if not block: break\n        code = coder.encode_fast(block)\n        output.append(code)\n        sys.stderr.write(\".\")\n    sys.stderr.write(\"\\n\")\n    out = Image.new(\"L\", (rowstride,len(output)))\n    out.putdata(\"\".join(output))\n    out.save(output_filename)",
    "docstring": "Encodes the input data with reed-solomon error correction in 223 byte\n    blocks, and outputs each block along with 32 parity bytes to a new file by\n    the given filename.\n\n    input is a file-like object\n\n    The outputted image will be in png format, and will be 255 by x pixels with\n    one color channel. X is the number of 255 byte blocks from the input. Each\n    block of data will be one row, therefore, the data can be recovered if no\n    more than 16 pixels per row are altered."
  },
  {
    "code": "def transfer(self, name, cache_key=None):\n        if cache_key is None:\n            cache_key = self.get_cache_key(name)\n        return self.task.delay(name, cache_key,\n                               self.local_path, self.remote_path,\n                               self.local_options, self.remote_options)",
    "docstring": "Transfers the file with the given name to the remote storage\n        backend by queuing the task.\n\n        :param name: file name\n        :type name: str\n        :param cache_key: the cache key to set after a successful task run\n        :type cache_key: str\n        :rtype: task result"
  },
  {
    "code": "def _load_all_link_database(self):\n        _LOGGER.debug(\"Starting: _load_all_link_database\")\n        self.devices.state = 'loading'\n        self._get_first_all_link_record()\n        _LOGGER.debug(\"Ending: _load_all_link_database\")",
    "docstring": "Load the ALL-Link Database into object."
  },
  {
    "code": "def load_from_docinfo(self, docinfo, delete_missing=False, raise_failure=False):\n        for uri, shortkey, docinfo_name, converter in self.DOCINFO_MAPPING:\n            qname = QName(uri, shortkey)\n            val = docinfo.get(str(docinfo_name))\n            if val is None:\n                if delete_missing and qname in self:\n                    del self[qname]\n                continue\n            try:\n                val = str(val)\n                if converter:\n                    val = converter.xmp_from_docinfo(val)\n                if not val:\n                    continue\n                self[qname] = val\n            except (ValueError, AttributeError) as e:\n                msg = \"The metadata field {} could not be copied to XMP\".format(\n                    docinfo_name\n                )\n                if raise_failure:\n                    raise ValueError(msg) from e\n                else:\n                    warn(msg)",
    "docstring": "Populate the XMP metadata object with DocumentInfo\n\n        Arguments:\n            docinfo: a DocumentInfo, e.g pdf.docinfo\n            delete_missing: if the entry is not DocumentInfo, delete the equivalent\n                from XMP\n            raise_failure: if True, raise any failure to convert docinfo;\n                otherwise warn and continue\n\n        A few entries in the deprecated DocumentInfo dictionary are considered\n        approximately equivalent to certain XMP records. This method copies\n        those entries into the XMP metadata."
  },
  {
    "code": "def g_reuss(self):\n        return 15. / (8. * self.compliance_tensor.voigt[:3, :3].trace() -\n                      4. * np.triu(self.compliance_tensor.voigt[:3, :3]).sum() +\n                      3. * self.compliance_tensor.voigt[3:, 3:].trace())",
    "docstring": "returns the G_r shear modulus"
  },
  {
    "code": "def _get_and_assert_slice_param(url_dict, param_name, default_int):\n    param_str = url_dict['query'].get(param_name, default_int)\n    try:\n        n = int(param_str)\n    except ValueError:\n        raise d1_common.types.exceptions.InvalidRequest(\n            0,\n            'Slice parameter is not a valid integer. {}=\"{}\"'.format(\n                param_name, param_str\n            ),\n        )\n    if n < 0:\n        raise d1_common.types.exceptions.InvalidRequest(\n            0,\n            'Slice parameter cannot be a negative number. {}=\"{}\"'.format(\n                param_name, param_str\n            ),\n        )\n    return n",
    "docstring": "Return ``param_str`` converted to an int.\n\n    If str cannot be converted to int or int is not zero or positive, raise\n    InvalidRequest."
  },
  {
    "code": "def get_oxi_state_decorated_structure(self, structure):\n        s = structure.copy()\n        if s.is_ordered:\n            valences = self.get_valences(s)\n            s.add_oxidation_state_by_site(valences)\n        else:\n            valences = self.get_valences(s)\n            s = add_oxidation_state_by_site_fraction(s, valences)\n        return s",
    "docstring": "Get an oxidation state decorated structure. This currently works only\n        for ordered structures only.\n\n        Args:\n            structure: Structure to analyze\n\n        Returns:\n            A modified structure that is oxidation state decorated.\n\n        Raises:\n            ValueError if the valences cannot be determined."
  },
  {
    "code": "def delete_object(container_name, object_name, profile, **libcloud_kwargs):\n    conn = _get_driver(profile=profile)\n    libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs)\n    obj = conn.get_object(container_name, object_name, **libcloud_kwargs)\n    return conn.delete_object(obj)",
    "docstring": "Delete an object in the cloud\n\n    :param container_name: Container name\n    :type  container_name: ``str``\n\n    :param object_name: Object name\n    :type  object_name: ``str``\n\n    :param profile: The profile key\n    :type  profile: ``str``\n\n    :param libcloud_kwargs: Extra arguments for the driver's delete_object method\n    :type  libcloud_kwargs: ``dict``\n\n    :return: True if an object has been successfully deleted, False\n                otherwise.\n    :rtype: ``bool``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion libcloud_storage.delete_object MyFolder me.jpg profile1"
  },
  {
    "code": "def conf_int(self, alpha=0.05, **kwargs):\n        r\n        return self.arima_res_.conf_int(alpha=alpha, **kwargs)",
    "docstring": "r\"\"\"Returns the confidence interval of the fitted parameters.\n\n        Returns\n        -------\n        alpha : float, optional (default=0.05)\n            The significance level for the confidence interval. ie.,\n            the default alpha = .05 returns a 95% confidence interval.\n\n        **kwargs : keyword args or dict\n            Keyword arguments to pass to the confidence interval function.\n            Could include 'cols' or 'method'"
  },
  {
    "code": "def dumps(data):\n    if not isinstance(data, _TOMLDocument) and isinstance(data, dict):\n        data = item(data)\n    return data.as_string()",
    "docstring": "Dumps a TOMLDocument into a string."
  },
  {
    "code": "def users_setPresence(self, *, presence: str, **kwargs) -> SlackResponse:\n        kwargs.update({\"presence\": presence})\n        return self.api_call(\"users.setPresence\", json=kwargs)",
    "docstring": "Manually sets user presence.\n\n        Args:\n            presence (str): Either 'auto' or 'away'."
  },
  {
    "code": "def read_pid_file(pidfile_path):\n    try:\n        fin = open(pidfile_path, \"r\")\n    except Exception, e:\n        return None\n    else:\n        pid_data = fin.read().strip()\n        fin.close()\n        try:\n            pid = int(pid_data)\n            return pid\n        except:\n            return None",
    "docstring": "Read the PID from the PID file"
  },
  {
    "code": "def _charSummary(self, char_count, block_count=None):\n        if not self._display['omit_summary']:\n            if block_count is None:\n                print('Total code points:', char_count)\n            else:\n                print('Total {0} code point{1} in {2} block{3}'.format(\n                    char_count,\n                    's' if char_count != 1 else '',\n                    block_count,\n                    's' if block_count != 1 else ''\n                ))",
    "docstring": "Displays characters summary."
  },
  {
    "code": "def transform(self, X, lenscale=None):\n        N, D = X.shape\n        lenscale = self._check_dim(D, lenscale)[:, np.newaxis]\n        WX = np.dot(X, self.W / lenscale)\n        return np.hstack((np.cos(WX), np.sin(WX))) / np.sqrt(self.n)",
    "docstring": "Apply the random basis to X.\n\n        Parameters\n        ----------\n        X: ndarray\n            (N, d) array of observations where N is the number of samples, and\n            d is the dimensionality of X.\n        lenscale: scalar or ndarray, optional\n            scalar or array of shape (d,) length scales (one for each dimension\n            of X). If not input, this uses the value of the initial length\n            scale.\n\n        Returns\n        -------\n        ndarray:\n            of shape (N, 2*nbases) where nbases is number of random bases to\n            use, given in the constructor."
  },
  {
    "code": "def keep_segments(self, segments_to_keep, preserve_segmentation=True):\n        v_ind, f_ind = self.vertex_indices_in_segments(segments_to_keep, ret_face_indices=True)\n        self.segm = {name: self.segm[name] for name in segments_to_keep}\n        if not preserve_segmentation:\n            self.segm = None\n            self.f = self.f[f_ind]\n            if self.ft is not None:\n                self.ft = self.ft[f_ind]\n        self.keep_vertices(v_ind)",
    "docstring": "Keep the faces and vertices for given segments, discarding all others.\n        When preserve_segmentation is false self.segm is discarded for speed."
  },
  {
    "code": "def build_image(image_path, image_name, build_args=None, dockerfile_path=None):\n    cmd = ['docker', 'build', '-t', image_name, image_path]\n    if dockerfile_path:\n        cmd.extend(['-f', dockerfile_path])\n    for k, v in (build_args or {}).items():\n        cmd += ['--build-arg', '{}={}'.format(k, v)]\n    check_call(cmd)",
    "docstring": "Build an image\n\n    Args:\n    image_path (str): the path to the image directory\n    image_name (str): image 'name:tag' to build\n    build_args (dict, optional): dict of docker build arguments\n    dockerfile_path (str, optional):\n        path to dockerfile relative to image_path\n        if not `image_path/Dockerfile`."
  },
  {
    "code": "def draw_image(self, video_name, image_name, out, start, end, x, y,\n                   verbose=False):\n        cfilter = (r\"[0] [1] overlay=x={x}: y={y}:\"\n                   \"enable='between(t, {start}, {end}')\")\\\n            .format(x=x, y=y, start=start, end=end)\n        call(['ffmpeg', '-i', video_name, '-i', image_name, '-c:v', 'huffyuv',\n              '-y', '-preset', 'veryslow', '-filter_complex', cfilter, out])",
    "docstring": "Draws an image over the video\n        @param video_name : name of video input file\n        @param image_name: name of image input file\n        @param out : name of video output file\n        @param start : when to start overlay\n        @param end : when to end overlay\n        @param x : x pos of image\n        @param y : y pos of image"
  },
  {
    "code": "def _get_sts_token(self):\n        logger.debug(\"Connecting to STS in region %s\", self.region)\n        sts = boto3.client('sts', region_name=self.region)\n        arn = \"arn:aws:iam::%s:role/%s\" % (self.account_id, self.account_role)\n        logger.debug(\"STS assume role for %s\", arn)\n        assume_kwargs = {\n            'RoleArn': arn,\n            'RoleSessionName': 'awslimitchecker'\n        }\n        if self.external_id is not None:\n            assume_kwargs['ExternalId'] = self.external_id\n        if self.mfa_serial_number is not None:\n            assume_kwargs['SerialNumber'] = self.mfa_serial_number\n        if self.mfa_token is not None:\n            assume_kwargs['TokenCode'] = self.mfa_token\n        role = sts.assume_role(**assume_kwargs)\n        creds = ConnectableCredentials(role)\n        creds.account_id = self.account_id\n        logger.debug(\"Got STS credentials for role; access_key_id=%s \"\n                     \"(account_id=%s)\", creds.access_key, creds.account_id)\n        return creds",
    "docstring": "Assume a role via STS and return the credentials.\n\n        First connect to STS via :py:func:`boto3.client`, then\n        assume a role using `boto3.STS.Client.assume_role <https://boto3.readthe\n        docs.org/en/latest/reference/services/sts.html#STS.Client.assume_role>`_\n        using ``self.account_id`` and ``self.account_role`` (and optionally\n        ``self.external_id``, ``self.mfa_serial_number``, ``self.mfa_token``).\n        Return the resulting :py:class:`~.ConnectableCredentials`\n        object.\n\n        :returns: STS assumed role credentials\n        :rtype: :py:class:`~.ConnectableCredentials`"
  },
  {
    "code": "def _can_send_eth(irs):\n        for ir in irs:\n            if isinstance(ir, (HighLevelCall, LowLevelCall, Transfer, Send)):\n                if ir.call_value:\n                    return True\n        return False",
    "docstring": "Detect if the node can send eth"
  },
  {
    "code": "def insert_pattern(pattern, model, index=0):\n        if not pattern:\n            return False\n        pattern = pattern.replace(QChar(QChar.ParagraphSeparator), QString(\"\\n\"))\n        pattern = foundations.common.get_first_item(foundations.strings.to_string(pattern).split(\"\\n\"))\n        model.insert_pattern(foundations.strings.to_string(pattern), index)\n        return True",
    "docstring": "Inserts given pattern into given Model.\n\n        :param pattern: Pattern.\n        :type pattern: unicode\n        :param model: Model.\n        :type model: PatternsModel\n        :param index: Insertion indes.\n        :type index: int\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def upload_buffer(self, target_id, page, address, buff):\n        count = 0\n        pk = CRTPPacket()\n        pk.set_header(0xFF, 0xFF)\n        pk.data = struct.pack('=BBHH', target_id, 0x14, page, address)\n        for i in range(0, len(buff)):\n            pk.data.append(buff[i])\n            count += 1\n            if count > 24:\n                self.link.send_packet(pk)\n                count = 0\n                pk = CRTPPacket()\n                pk.set_header(0xFF, 0xFF)\n                pk.data = struct.pack('=BBHH', target_id, 0x14, page,\n                                      i + address + 1)\n        self.link.send_packet(pk)",
    "docstring": "Upload data into a buffer on the Crazyflie"
  },
  {
    "code": "def scan_for_spec(keyword):\n    keyword = keyword.lstrip('(').rstrip(')')\n    matches = release_line_re.findall(keyword)\n    if matches:\n        return Spec(\">={}\".format(matches[0]))\n    try:\n        return Spec(keyword)\n    except ValueError:\n        return None",
    "docstring": "Attempt to return some sort of Spec from given keyword value.\n\n    Returns None if one could not be derived."
  },
  {
    "code": "def _get_bib_element(bibitem, element):\n    lst = [i.strip() for i in bibitem.split(\"\\n\")]\n    for i in lst:\n        if i.startswith(element):\n            value = i.split(\"=\", 1)[-1]\n            value = value.strip()\n            while value.endswith(','):\n                value = value[:-1]\n            while value.startswith('{') or value.startswith('\"'):\n                value = value[1:-1]\n            return value\n    return None",
    "docstring": "Return element from bibitem or None.\n\n    Paramteters\n    -----------\n    bibitem :\n    element :\n\n    Returns\n    -------"
  },
  {
    "code": "def sentiment(self):\n        if self._sentiment is None:\n            results = self._xml.xpath('/root/document/sentences')\n            self._sentiment = float(results[0].get(\"averageSentiment\", 0)) if len(results) > 0 else None\n        return self._sentiment",
    "docstring": "Returns average sentiment of document. Must have sentiment enabled in XML output.\n\n        :getter: returns average sentiment of the document\n        :type: float"
  },
  {
    "code": "def change_column(self, table, column_name, field):\n        operations = [self.alter_change_column(table, column_name, field)]\n        if not field.null:\n            operations.extend([self.add_not_null(table, column_name)])\n        return operations",
    "docstring": "Change column."
  },
  {
    "code": "def _format_changes(changes, orchestration=False):\n    if not changes:\n        return False, ''\n    if orchestration:\n        return True, _nested_changes(changes)\n    if not isinstance(changes, dict):\n        return True, 'Invalid Changes data: {0}'.format(changes)\n    ret = changes.get('ret')\n    if ret is not None and changes.get('out') == 'highstate':\n        ctext = ''\n        changed = False\n        for host, hostdata in six.iteritems(ret):\n            s, c = _format_host(host, hostdata)\n            ctext += '\\n' + '\\n'.join((' ' * 14 + l) for l in s.splitlines())\n            changed = changed or c\n    else:\n        changed = True\n        ctext = _nested_changes(changes)\n    return changed, ctext",
    "docstring": "Format the changes dict based on what the data is"
  },
  {
    "code": "def visit_call(self, node):\n        expr_str = self._precedence_parens(node, node.func)\n        args = [arg.accept(self) for arg in node.args]\n        if node.keywords:\n            keywords = [kwarg.accept(self) for kwarg in node.keywords]\n        else:\n            keywords = []\n        args.extend(keywords)\n        return \"%s(%s)\" % (expr_str, \", \".join(args))",
    "docstring": "return an astroid.Call node as string"
  },
  {
    "code": "def ledger_transactions(self, ledger_id, cursor=None, order='asc', include_failed=False, limit=10):\n        endpoint = '/ledgers/{ledger_id}/transactions'.format(\n            ledger_id=ledger_id)\n        params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed)\n        return self.query(endpoint, params)",
    "docstring": "This endpoint represents all transactions in a given ledger.\n\n        `GET /ledgers/{id}/transactions{?cursor,limit,order}\n        <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-for-ledger.html>`_\n\n        :param int ledger_id: The id of the ledger to look up.\n        :param int cursor: A paging token, specifying where to start returning records from.\n        :param str order: The order in which to return rows, \"asc\" or \"desc\".\n        :param int limit: Maximum number of records to return.\n        :param bool include_failed: Set to `True` to include failed transactions in results.\n        :return: The transactions contained in a single ledger.\n        :rtype: dict"
  },
  {
    "code": "def expect_optional_token(lexer: Lexer, kind: TokenKind) -> Optional[Token]:\n    token = lexer.token\n    if token.kind == kind:\n        lexer.advance()\n        return token\n    return None",
    "docstring": "Expect the next token optionally to be of the given kind.\n\n    If the next token is of the given kind, return that token after advancing the lexer.\n    Otherwise, do not change the parser state and return None."
  },
  {
    "code": "def endpointlist_post_save(instance, *args, **kwargs):\n    with open(instance.upload.file.name, mode='rb') as f:\n        lines = f.readlines()\n    for url in lines:\n        if len(url) > 255:\n            LOGGER.debug('Skipping this endpoint, as it is more than 255 characters: %s' % url)\n        else:\n            if Endpoint.objects.filter(url=url, catalog=instance.catalog).count() == 0:\n                endpoint = Endpoint(url=url, endpoint_list=instance)\n                endpoint.catalog = instance.catalog\n                endpoint.save()\n    if not settings.REGISTRY_SKIP_CELERY:\n        update_endpoints.delay(instance.id)\n    else:\n        update_endpoints(instance.id)",
    "docstring": "Used to process the lines of the endpoint list."
  },
  {
    "code": "def prefix_search(self, job_name_prefix):\n        json = self._fetch_json()\n        jobs = json['response']\n        for job in jobs:\n            if job.startswith(job_name_prefix):\n                yield self._build_results(jobs, job)",
    "docstring": "Searches for jobs matching the given ``job_name_prefix``."
  },
  {
    "code": "def build_extension(extensions: Sequence[ExtensionHeader]) -> str:\n    return \", \".join(\n        build_extension_item(name, parameters) for name, parameters in extensions\n    )",
    "docstring": "Unparse a ``Sec-WebSocket-Extensions`` header.\n\n    This is the reverse of :func:`parse_extension`."
  },
  {
    "code": "def count_resources(domain, token):\n    resources = get_resources(domain, token)\n    return dict(Counter([r['resource']['type'] for r in resources if r['resource']['type'] != 'story']))",
    "docstring": "Given the domain in question, generates counts for that domain of each of the different data types.\n\n    Parameters\n    ----------\n    domain: str\n        A Socrata data portal domain. \"data.seattle.gov\" or \"data.cityofnewyork.us\" for example.\n    token: str\n        A Socrata application token. Application tokens can be registered by going onto the Socrata portal in\n        question, creating an account, logging in, going to developer tools, and spawning a token.\n\n    Returns\n    -------\n    A dict with counts of the different endpoint types classifiable as published public datasets."
  },
  {
    "code": "def row_number(expr, sort=None, ascending=True):\n    return _rank_op(expr, RowNumber, types.int64, sort=sort, ascending=ascending)",
    "docstring": "Calculate row number of a sequence expression.\n\n    :param expr: expression for calculation\n    :param sort: name of the sort column\n    :param ascending: whether to sort in ascending order\n    :return: calculated column"
  },
  {
    "code": "def mime(self):\n\t\tauthor = self.author\n\t\tsender = self.sender\n\t\tif not author:\n\t\t\traise ValueError(\"You must specify an author.\")\n\t\tif not self.subject:\n\t\t\traise ValueError(\"You must specify a subject.\")\n\t\tif len(self.recipients) == 0:\n\t\t\traise ValueError(\"You must specify at least one recipient.\")\n\t\tif not self.plain:\n\t\t\traise ValueError(\"You must provide plain text content.\")\n\t\tif not self._dirty and self._processed:\n\t\t\treturn self._mime\n\t\tself._processed = False\n\t\tplain = MIMEText(self._callable(self.plain), 'plain', self.encoding)\n\t\trich = None\n\t\tif self.rich:\n\t\t\trich = MIMEText(self._callable(self.rich), 'html', self.encoding)\n\t\tmessage = self._mime_document(plain, rich)\n\t\theaders = self._build_header_list(author, sender)\n\t\tself._add_headers_to_message(message, headers)\n\t\tself._mime = message\n\t\tself._processed = True\n\t\tself._dirty = False\n\t\treturn message",
    "docstring": "Produce the final MIME message."
  },
  {
    "code": "def _select_root_port(self):\n        root_port = None\n        for port in self.ports.values():\n            root_msg = (self.root_priority if root_port is None\n                        else root_port.designated_priority)\n            port_msg = port.designated_priority\n            if port.state is PORT_STATE_DISABLE or port_msg is None:\n                continue\n            if root_msg.root_id.value > port_msg.root_id.value:\n                result = SUPERIOR\n            elif root_msg.root_id.value == port_msg.root_id.value:\n                if root_msg.designated_bridge_id is None:\n                    result = INFERIOR\n                else:\n                    result = Stp.compare_root_path(\n                        port_msg.root_path_cost,\n                        root_msg.root_path_cost,\n                        port_msg.designated_bridge_id.value,\n                        root_msg.designated_bridge_id.value,\n                        port_msg.designated_port_id.value,\n                        root_msg.designated_port_id.value)\n            else:\n                result = INFERIOR\n            if result is SUPERIOR:\n                root_port = port\n        return root_port",
    "docstring": "ROOT_PORT is the nearest port to a root bridge.\n            It is determined by the cost of path, etc."
  },
  {
    "code": "def _make_text_block(name, content, content_type=None):\n    if content_type == 'xhtml':\n        return u'<%s type=\"xhtml\"><div xmlns=\"%s\">%s</div></%s>\\n' % \\\n               (name, XHTML_NAMESPACE, content, name)\n    if not content_type:\n        return u'<%s>%s</%s>\\n' % (name, escape(content), name)\n    return u'<%s type=\"%s\">%s</%s>\\n' % (name, content_type,\n                                         escape(content), name)",
    "docstring": "Helper function for the builder that creates an XML text block."
  },
  {
    "code": "def rest(url, req=\"GET\", data=None):\n    load_variables()\n    return _rest(base_url + url, req, data)",
    "docstring": "Main function to be called from this module.\n\n    send a request using method 'req' and to the url. the _rest() function\n    will add the base_url to this, so 'url' should be something like '/ips'."
  },
  {
    "code": "def batch_query_state_changes(\n            self,\n            batch_size: int,\n            filters: List[Tuple[str, Any]] = None,\n            logical_and: bool = True,\n    ) -> Iterator[List[StateChangeRecord]]:\n        limit = batch_size\n        offset = 0\n        result_length = 1\n        while result_length != 0:\n            result = self._get_state_changes(\n                limit=limit,\n                offset=offset,\n                filters=filters,\n                logical_and=logical_and,\n            )\n            result_length = len(result)\n            offset += result_length\n            yield result",
    "docstring": "Batch query state change records with a given batch size and an optional filter\n\n        This is a generator function returning each batch to the caller to work with."
  },
  {
    "code": "def run_notebook_hook(notebook_type, action, *args, **kw):\n    if notebook_type not in _HOOKS:\n        raise RuntimeError(\"no display hook installed for notebook type %r\" % notebook_type)\n    if _HOOKS[notebook_type][action] is None:\n        raise RuntimeError(\"notebook hook for %r did not install %r action\" % notebook_type, action)\n    return _HOOKS[notebook_type][action](*args, **kw)",
    "docstring": "Run an installed notebook hook with supplied arguments.\n\n    Args:\n        noteboook_type (str) :\n            Name of an existing installed notebook hook\n\n        actions (str) :\n            Name of the hook action to execute, ``'doc'`` or ``'app'``\n\n    All other arguments and keyword arguments are passed to the hook action\n    exactly as supplied.\n\n    Returns:\n        Result of the hook action, as-is\n\n    Raises:\n        RuntimeError\n            If the hook or specific action is not installed"
  },
  {
    "code": "def set_prompt(scope, prompt=None):\n    conn = scope.get('__connection__')\n    conn.set_prompt(prompt)\n    return True",
    "docstring": "Defines the pattern that is recognized at any future time when Exscript\n    needs to wait for a prompt.\n    In other words, whenever Exscript waits for a prompt, it searches the\n    response of the host for the given pattern and continues as soon as the\n    pattern is found.\n\n    Exscript waits for a prompt whenever it sends a command (unless the send()\n    method was used). set_prompt() redefines as to what is recognized as a\n    prompt.\n\n    :type  prompt: regex\n    :param prompt: The prompt pattern."
  },
  {
    "code": "def add_command(self, cmd_name, *args):\n        self.__commands.append(Command(cmd_name, args))",
    "docstring": "Add command to action."
  },
  {
    "code": "def iter_all_users(self, number=-1, etag=None, per_page=None):\n        url = self._build_url('users')\n        return self._iter(int(number), url, User,\n                          params={'per_page': per_page}, etag=etag)",
    "docstring": "Iterate over every user in the order they signed up for GitHub.\n\n        :param int number: (optional), number of users to return. Default: -1,\n            returns all of them\n        :param str etag: (optional), ETag from a previous request to the same\n            endpoint\n        :param int per_page: (optional), number of users to list per request\n        :returns: generator of :class:`User <github3.users.User>`"
  },
  {
    "code": "def logs(self, **kwargs):\n        return self.client.api.logs(self.id, **kwargs)",
    "docstring": "Get logs from this container. Similar to the ``docker logs`` command.\n\n        The ``stream`` parameter makes the ``logs`` function return a blocking\n        generator you can iterate over to retrieve log output as it happens.\n\n        Args:\n            stdout (bool): Get ``STDOUT``. Default ``True``\n            stderr (bool): Get ``STDERR``. Default ``True``\n            stream (bool): Stream the response. Default ``False``\n            timestamps (bool): Show timestamps. Default ``False``\n            tail (str or int): Output specified number of lines at the end of\n                logs. Either an integer of number of lines or the string\n                ``all``. Default ``all``\n            since (datetime or int): Show logs since a given datetime or\n                integer epoch (in seconds)\n            follow (bool): Follow log output. Default ``False``\n            until (datetime or int): Show logs that occurred before the given\n                datetime or integer epoch (in seconds)\n\n        Returns:\n            (generator or str): Logs from the container.\n\n        Raises:\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def delete_account(self, account):\n        try:\n            luser = self._get_account(account.username)\n            groups = luser['groups'].load(database=self._database)\n            for group in groups:\n                changes = changeset(group, {})\n                changes = group.remove_member(changes, luser)\n                save(changes, database=self._database)\n            delete(luser, database=self._database)\n        except ObjectDoesNotExist:\n            pass",
    "docstring": "Account was deleted."
  },
  {
    "code": "def mark_done(task_id):\n  task = Task.get_by_id(task_id)\n  if task is None:\n    raise ValueError('Task with id %d does not exist' % task_id)\n  task.done = True\n  task.put()",
    "docstring": "Marks a task as done.\n\n  Args:\n    task_id: The integer id of the task to update.\n\n  Raises:\n    ValueError: if the requested task doesn't exist."
  },
  {
    "code": "def translate(\n        nucleotide_sequence,\n        first_codon_is_start=True,\n        to_stop=True,\n        truncate=False):\n    if not isinstance(nucleotide_sequence, Seq):\n        nucleotide_sequence = Seq(nucleotide_sequence)\n    if truncate:\n        n_nucleotides = int(len(nucleotide_sequence) / 3) * 3\n        nucleotide_sequence = nucleotide_sequence[:n_nucleotides]\n    else:\n        n_nucleotides = len(nucleotide_sequence)\n    assert n_nucleotides % 3 == 0, \\\n        (\"Expected nucleotide sequence to be multiple of 3\"\n         \" but got %s of length %d\") % (\n            nucleotide_sequence,\n            n_nucleotides)\n    protein_sequence = nucleotide_sequence.translate(to_stop=to_stop, cds=False)\n    if first_codon_is_start and (\n            len(protein_sequence) == 0 or protein_sequence[0] != \"M\"):\n        if nucleotide_sequence[:3] in START_CODONS:\n            return \"M\" + protein_sequence[1:]\n        else:\n            raise ValueError(\n                (\"Expected first codon of %s to be start codon\"\n                 \" (one of %s) but got %s\") % (\n                    protein_sequence[:10],\n                    START_CODONS,\n                    nucleotide_sequence))\n    return protein_sequence",
    "docstring": "Translates cDNA coding sequence into amino acid protein sequence.\n\n    Should typically start with a start codon but allowing non-methionine\n    first residues since the CDS we're translating might have been affected\n    by a start loss mutation.\n\n    The sequence may include the 3' UTR but will stop translation at the first\n    encountered stop codon.\n\n    Parameters\n    ----------\n    nucleotide_sequence : BioPython Seq\n        cDNA sequence\n\n    first_codon_is_start : bool\n        Treat the beginning of nucleotide_sequence (translates methionin)\n\n    truncate : bool\n        Truncate sequence if it's not a multiple of 3 (default = False)\n    Returns BioPython Seq of amino acids"
  },
  {
    "code": "def _get_callable(self, classname, cname):\n        callable = None\n        if classname in self.provregs:\n            provClass = self.provregs[classname]\n            if hasattr(provClass, cname):\n                callable = getattr(provClass, cname)\n        elif hasattr(self.provmod, cname):\n            callable = getattr(self.provmod, cname)\n        if callable is None:\n            raise pywbem.CIMError(\n                pywbem.CIM_ERR_FAILED,\n                \"No provider registered for %s or no callable for %s:%s on \" \\\n                \"provider %s\" % (classname, classname, cname, self.provid))\n        return callable",
    "docstring": "Return a function or method object appropriate to fulfill a request\n\n        classname -- The CIM class name associated with the request.\n        cname -- The function or method name to look for."
  },
  {
    "code": "def compile_rules(self):\n        output = []\n        for key_name, section in self.config.items():\n            rule = self.compile_section(section)\n            if rule is not None:\n                output.append(rule)\n        return output",
    "docstring": "Compile alert rules\n        @rtype list of Rules"
  },
  {
    "code": "def _move_to_store(self, srcpath, objhash):\n        destpath = self.object_path(objhash)\n        if os.path.exists(destpath):\n            os.chmod(destpath, S_IWUSR)\n            os.remove(destpath)\n        os.chmod(srcpath, S_IRUSR | S_IRGRP | S_IROTH)\n        move(srcpath, destpath)",
    "docstring": "Make the object read-only and move it to the store."
  },
  {
    "code": "def bi_square(xx, idx=None):\n    ans = np.zeros(xx.shape)\n    ans[idx] = (1-xx[idx]**2)**2\n    return ans",
    "docstring": "The bi-square weight function calculated over values of xx\n\n    Parameters\n    ----------\n    xx: float array\n\n    Notes\n    -----\n    This is the first equation on page 831 of [Cleveland79]."
  },
  {
    "code": "def alias_log(self, log_id, alias_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.alias_catalog(catalog_id=log_id, alias_id=alias_id)\n        self._alias_id(primary_id=log_id, equivalent_id=alias_id)",
    "docstring": "Adds an ``Id`` to a ``Log`` for the purpose of creating compatibility.\n\n        The primary ``Id`` of the ``Log`` is determined by the provider.\n        The new ``Id`` performs as an alias to the primary ``Id``. If\n        the alias is a pointer to another log, it is reassigned to the\n        given log ``Id``.\n\n        arg:    log_id (osid.id.Id): the ``Id`` of a ``Log``\n        arg:    alias_id (osid.id.Id): the alias ``Id``\n        raise:  AlreadyExists - ``alias_id`` is already assigned\n        raise:  NotFound - ``log_id`` not found\n        raise:  NullArgument - ``log_id`` or ``alias_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def update(self, iterable):\n        if iterable:\n            return PBag(reduce(_add_to_counters, iterable, self._counts))\n        return self",
    "docstring": "Update bag with all elements in iterable.\n\n        >>> s = pbag([1])\n        >>> s.update([1, 2])\n        pbag([1, 1, 2])"
  },
  {
    "code": "def get_data_home(data_home=None):\n    data_home_default = Path(__file__).ancestor(3).child('demos',\n                                                         '_revrand_data')\n    if data_home is None:\n        data_home = os.environ.get('REVRAND_DATA', data_home_default)\n    if not os.path.exists(data_home):\n        os.makedirs(data_home)\n    return data_home",
    "docstring": "Return the path of the revrand data dir.\n\n    This folder is used by some large dataset loaders to avoid\n    downloading the data several times.\n\n    By default the data dir is set to a folder named 'revrand_data'\n    in the user home folder.\n\n    Alternatively, it can be set by the 'REVRAND_DATA' environment\n    variable or programmatically by giving an explicit folder path. The\n    '~' symbol is expanded to the user home folder.\n\n    If the folder does not already exist, it is automatically created."
  },
  {
    "code": "def get_config(name=__name__):\n    cfg = ConfigParser()\n    path = os.environ.get('%s_CONFIG_FILE' % name.upper())\n    if path is None or path == \"\":\n        fname = '/etc/tapp/%s.ini' % name\n        if isfile(fname):\n            path = fname\n        elif isfile('cfg.ini'):\n            path = 'cfg.ini'\n        else:\n            raise ValueError(\"Unable to get configuration for tapp %s\" % name)\n    cfg.read(path)\n    return cfg",
    "docstring": "Get a configuration parser for a given TAPP name.\n    Reads config.ini files only, not in-database configuration records.\n\n    :param name: The tapp name to get a configuration for.\n    :rtype: ConfigParser\n    :return: A config parser matching the given name"
  },
  {
    "code": "def _detect_term_type():\n        if os.name == 'nt':\n            if os.environ.get('TERM') == 'xterm':\n                return 'mintty'\n            else:\n                return 'nt'\n        if platform.system().upper().startswith('CYGWIN'):\n            return 'cygwin'\n        return 'posix'",
    "docstring": "Detect the type of the terminal."
  },
  {
    "code": "def get_env_variable(var_name, default=None):\n    try:\n        return os.environ[var_name]\n    except KeyError:\n        if default is not None:\n            return default\n        else:\n            error_msg = 'The environment variable {} was missing, abort...'\\\n                        .format(var_name)\n            raise EnvironmentError(error_msg)",
    "docstring": "Get the environment variable or raise exception."
  },
  {
    "code": "def get_intra_edges(self, time_slice=0):\n        if not isinstance(time_slice, int) or time_slice < 0:\n            raise ValueError(\"The timeslice should be a positive value greater than or equal to zero\")\n        return [tuple((x[0], time_slice) for x in edge) for edge in self.edges() if edge[0][1] == edge[1][1] == 0]",
    "docstring": "Returns the intra slice edges present in the 2-TBN.\n\n        Parameter\n        ---------\n        time_slice: int (whole number)\n                The time slice for which to get intra edges. The timeslice\n                should be a positive value or zero.\n\n        Examples\n        --------\n        >>> from pgmpy.models import DynamicBayesianNetwork as DBN\n        >>> dbn = DBN()\n        >>> dbn.add_nodes_from(['D', 'G', 'I', 'S', 'L'])\n        >>> dbn.add_edges_from([(('D', 0), ('G', 0)), (('I', 0), ('G', 0)),\n        ...                     (('G', 0), ('L', 0)), (('D', 0), ('D', 1)),\n        ...                     (('I', 0), ('I', 1)), (('G', 0), ('G', 1)),\n        ...                     (('G', 0), ('L', 1)), (('L', 0), ('L', 1))])\n        >>> dbn.get_intra_edges()\n        [(('D', 0), ('G', 0)), (('G', 0), ('L', 0)), (('I', 0), ('G', 0))"
  },
  {
    "code": "def is_newer_than(after, seconds):\n    if isinstance(after, six.string_types):\n        after = parse_strtime(after).replace(tzinfo=None)\n    else:\n        after = after.replace(tzinfo=None)\n    return after - utcnow() > datetime.timedelta(seconds=seconds)",
    "docstring": "Return True if after is newer than seconds."
  },
  {
    "code": "def verify(self, byts, sign):\n        try:\n            chosen_hash = c_hashes.SHA256()\n            hasher = c_hashes.Hash(chosen_hash, default_backend())\n            hasher.update(byts)\n            digest = hasher.finalize()\n            self.publ.verify(sign,\n                             digest,\n                             c_ec.ECDSA(c_utils.Prehashed(chosen_hash))\n                             )\n            return True\n        except InvalidSignature:\n            logger.exception('Error in publ.verify')\n            return False",
    "docstring": "Verify the signature for the given bytes using the ECC\n        public key.\n\n        Args:\n            byts (bytes): The data bytes.\n            sign (bytes): The signature bytes.\n\n        Returns:\n            bool: True if the data was verified, False otherwise."
  },
  {
    "code": "def item_names(self):\n        if \"item_names\" not in self.attrs.keys():\n            self.attrs[\"item_names\"] = np.array([], dtype=\"S\")\n        return tuple(n.decode() for n in self.attrs[\"item_names\"])",
    "docstring": "Item names."
  },
  {
    "code": "def load_backend(build_configuration, backend_package):\n  backend_module = backend_package + '.register'\n  try:\n    module = importlib.import_module(backend_module)\n  except ImportError as e:\n    traceback.print_exc()\n    raise BackendConfigurationError('Failed to load the {backend} backend: {error}'\n                                    .format(backend=backend_module, error=e))\n  def invoke_entrypoint(name):\n    entrypoint = getattr(module, name, lambda: None)\n    try:\n      return entrypoint()\n    except TypeError as e:\n      traceback.print_exc()\n      raise BackendConfigurationError(\n          'Entrypoint {entrypoint} in {backend} must be a zero-arg callable: {error}'\n          .format(entrypoint=name, backend=backend_module, error=e))\n  build_file_aliases = invoke_entrypoint('build_file_aliases')\n  if build_file_aliases:\n    build_configuration.register_aliases(build_file_aliases)\n  subsystems = invoke_entrypoint('global_subsystems')\n  if subsystems:\n    build_configuration.register_optionables(subsystems)\n  rules = invoke_entrypoint('rules')\n  if rules:\n    build_configuration.register_rules(rules)\n  invoke_entrypoint('register_goals')",
    "docstring": "Installs the given backend package into the build configuration.\n\n  :param build_configuration the :class:``pants.build_graph.build_configuration.BuildConfiguration`` to\n    install the backend plugin into.\n  :param string backend_package: the package name containing the backend plugin register module that\n    provides the plugin entrypoints.\n  :raises: :class:``pants.base.exceptions.BuildConfigurationError`` if there is a problem loading\n    the build configuration."
  },
  {
    "code": "def get_rows_by_cols(self, matching_dict):\n        result = []\n        for i in range(self.num_rows):\n            row = self._table[i+1]\n            matching = True\n            for key, val in matching_dict.items():\n                if row[key] != val:\n                    matching = False\n                    break\n            if matching:\n                result.append(row)\n        return result",
    "docstring": "Return all rows where the cols match the elements given in the matching_dict\n\n        Parameters\n        ----------\n        matching_dict: :obj:'dict'\n            Desired dictionary of col values.\n\n        Returns\n        -------\n        :obj:`list`\n            A list of rows that satisfy the matching_dict"
  },
  {
    "code": "def get_int(byte_array, signed=True):\n    return int.from_bytes(byte_array, byteorder='big', signed=signed)",
    "docstring": "Gets the specified integer from its byte array.\n    This should be used by this module alone, as it works with big endian.\n\n    :param byte_array: the byte array representing th integer.\n    :param signed: whether the number is signed or not.\n    :return: the integer representing the given byte array."
  },
  {
    "code": "def _multicomplex2(f, fx, x, h):\n        n = len(x)\n        ee = np.diag(h)\n        hess = np.outer(h, h)\n        cmplx_wrap = Bicomplex.__array_wrap__\n        for i in range(n):\n            for j in range(i, n):\n                zph = Bicomplex(x + 1j * ee[i, :], ee[j, :])\n                hess[i, j] = cmplx_wrap(f(zph)).imag12 / hess[j, i]\n                hess[j, i] = hess[i, j]\n        return hess",
    "docstring": "Calculate Hessian with Bicomplex-step derivative approximation"
  },
  {
    "code": "def filter_304_headers(headers):\n    return [(k, v) for k, v in headers if k.lower() not in _filter_from_304]",
    "docstring": "Filter a list of headers to include in a \"304 Not Modified\" response."
  },
  {
    "code": "def convert_PDF_to_plaintext(fpath, keep_layout=False):\n    if not os.path.isfile(CFG_PATH_PDFTOTEXT):\n        raise IOError('Missing pdftotext executable')\n    if keep_layout:\n        layout_option = \"-layout\"\n    else:\n        layout_option = \"-raw\"\n    doclines = []\n    p_break_in_line = re.compile(ur'^\\s*\\f(.+)$', re.UNICODE)\n    cmd_pdftotext = [CFG_PATH_PDFTOTEXT, layout_option, \"-q\",\n                     \"-enc\", \"UTF-8\", fpath, \"-\"]\n    LOGGER.debug(u\"%s\", ' '.join(cmd_pdftotext))\n    pipe_pdftotext = subprocess.Popen(cmd_pdftotext, stdout=subprocess.PIPE)\n    for docline in pipe_pdftotext.stdout:\n        unicodeline = docline.decode(\"utf-8\")\n        m_break_in_line = p_break_in_line.match(unicodeline)\n        if m_break_in_line is None:\n            doclines.append(unicodeline)\n        else:\n            doclines.append(u\"\\f\")\n            doclines.append(m_break_in_line.group(1))\n    LOGGER.debug(u\"convert_PDF_to_plaintext found: %s lines of text\", len(doclines))\n    return doclines",
    "docstring": "Convert PDF to txt using pdftotext\n\n    Take the path to a PDF file and run pdftotext for this file, capturing\n    the output.\n    @param fpath: (string) path to the PDF file\n    @return: (list) of unicode strings (contents of the PDF file translated\n    into plaintext; each string is a line in the document.)"
  },
  {
    "code": "def to_representation(self, obj):\n        value = self.model_field.__get__(obj, None)\n        return smart_text(value, strings_only=True)",
    "docstring": "convert value to representation.\n\n        DRF ModelField uses ``value_to_string`` for this purpose. Mongoengine fields do not have such method.\n\n        This implementation uses ``django.utils.encoding.smart_text`` to convert everything to text, while keeping json-safe types intact.\n\n        NB: The argument is whole object, instead of attribute value. This is upstream feature.\n        Probably because the field can be represented by a complicated method with nontrivial way to extract data."
  },
  {
    "code": "def from_file(cls, filename, **kwargs):\n        filename = os.path.expanduser(filename)\n        if not os.path.isfile(filename):\n            raise exceptions.PyKubeError(\"Configuration file {} not found\".format(filename))\n        with open(filename) as f:\n            doc = yaml.safe_load(f.read())\n        self = cls(doc, **kwargs)\n        self.filename = filename\n        return self",
    "docstring": "Creates an instance of the KubeConfig class from a kubeconfig file.\n\n        :Parameters:\n           - `filename`: The full path to the configuration file"
  },
  {
    "code": "def filter_rows(filters, rows):\n    for row in rows:\n        if all(condition(row, row.get(col))\n               for (cols, condition) in filters\n               for col in cols\n               if col is None or col in row):\n            yield row",
    "docstring": "Yield rows matching all applicable filters.\n\n    Filter functions have binary arity (e.g. `filter(row, col)`) where\n    the first parameter is the dictionary of row data, and the second\n    parameter is the data at one particular column.\n\n    Args:\n        filters: a tuple of (cols, filter_func) where filter_func will\n            be tested (filter_func(row, col)) for each col in cols where\n            col exists in the row\n        rows: an iterable of rows to filter\n    Yields:\n        Rows matching all applicable filters\n\n    .. deprecated:: v0.7.0"
  },
  {
    "code": "def invers(self):\n        if self._columns != self._rows:\n            raise ValueError(\"A square matrix is needed\")\n        mArray = self.get_array(False)\n        appList = [0] * self._columns\n        for col in xrange(self._columns):\n            mArray.append(appList[:])\n            mArray[self._columns + col][col] = 1\n        exMatrix = Matrix.from_two_dim_array(2 * self._columns, self._rows, mArray)\n        gjResult = exMatrix.gauss_jordan()\n        gjResult.matrix = gjResult.matrix[self._columns:]\n        gjResult._columns = len(gjResult.matrix)\n        return gjResult",
    "docstring": "Return the invers matrix, if it can be calculated\n\n        :return:    Returns a new Matrix containing the invers\n        :rtype:     Matrix\n\n        :raise:     Raises an :py:exc:`ValueError` if the matrix is not inversible\n\n        :note:      Only a squared matrix with a determinant != 0 can be inverted.\n        :todo:      Reduce amount of create and copy operations"
  },
  {
    "code": "def _unfold_map(self, display_text_map):\n        from ..type.primitives import Type\n        lt_identifier = Id(display_text_map['languageTypeId']).get_identifier()\n        st_identifier = Id(display_text_map['scriptTypeId']).get_identifier()\n        ft_identifier = Id(display_text_map['formatTypeId']).get_identifier()\n        try:\n            self._language_type = Type(**language_types.get_type_data(lt_identifier))\n        except AttributeError:\n            raise NotFound('Language Type: ' + lt_identifier)\n        try:\n            self._script_type = Type(**script_types.get_type_data(st_identifier))\n        except AttributeError:\n            raise NotFound('Script Type: ' + st_identifier)\n        try:\n            self._format_type = Type(**format_types.get_type_data(ft_identifier))\n        except AttributeError:\n            raise NotFound('Format Type: ' + ft_identifier)\n        self._text = display_text_map['text']",
    "docstring": "Parses a display text dictionary map."
  },
  {
    "code": "def currencies(self) -> CurrenciesAggregate:\n        if not self.__currencies_aggregate:\n            self.__currencies_aggregate = CurrenciesAggregate(self.book)\n        return self.__currencies_aggregate",
    "docstring": "Returns the Currencies aggregate"
  },
  {
    "code": "def is_group(value):\n    if type(value) == str:\n        try:\n            entry = grp.getgrnam(value)\n            value = entry.gr_gid\n        except KeyError:\n            err_message = ('{0}: No such group.'.format(value))\n            raise validate.VdtValueError(err_message)\n        return value\n    elif type(value) == int:\n        try:\n            grp.getgrgid(value)\n        except KeyError:\n            err_message = ('{0}: No such group.'.format(value))\n            raise validate.VdtValueError(err_message)\n        return value\n    else:\n        err_message = ('Please, use str or int to \"user\" parameter.')\n        raise validate.VdtTypeError(err_message)",
    "docstring": "Check whether groupname or gid as argument exists.\n    if this function recieved groupname, convert gid and exec validation."
  },
  {
    "code": "def signal_stop(self, mode):\n        if self.is_single_user:\n            logger.warning(\"Cannot stop server; single-user server is running (PID: {0})\".format(self.pid))\n            return False\n        try:\n            self.send_signal(STOP_SIGNALS[mode])\n        except psutil.NoSuchProcess:\n            return True\n        except psutil.AccessDenied as e:\n            logger.warning(\"Could not send stop signal to PostgreSQL (error: {0})\".format(e))\n            return False\n        return None",
    "docstring": "Signal postmaster process to stop\n\n        :returns None if signaled, True if process is already gone, False if error"
  },
  {
    "code": "def within_duration(events, time, limits):\n    min_dur = max_dur = ones(events.shape[0], dtype=bool)\n    if limits[0] is not None:\n        min_dur = time[events[:, -1] - 1] - time[events[:, 0]] >= limits[0]\n    if limits[1] is not None:\n        max_dur = time[events[:, -1] - 1] - time[events[:, 0]] <= limits[1]\n    return events[min_dur & max_dur, :]",
    "docstring": "Check whether event is within time limits.\n\n    Parameters\n    ----------\n    events : ndarray (dtype='int')\n        N x M matrix with start sample first and end samples last on M\n    time : ndarray (dtype='float')\n        vector with time points\n    limits : tuple of float\n        low and high limit for spindle duration\n\n    Returns\n    -------\n    ndarray (dtype='int')\n        N x M matrix with start sample first and end samples last on M"
  },
  {
    "code": "def listunion(ListOfLists):\n    u = []\n    for s in ListOfLists:\n        if s != None:\n            u.extend(s)\n    return u",
    "docstring": "Take the union of a list of lists.\n\n    Take a Python list of Python lists::\n\n            [[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]]\n\n    and return the aggregated list::\n\n            [l11,l12, ..., l21, l22 , ...]\n\n    For a list of two lists, e.g. `[a, b]`, this is like::\n\n            a.extend(b)\n\n    **Parameters**\n\n            **ListOfLists** :  Python list\n\n                    Python list of Python lists.\n\n    **Returns**\n\n            **u** :  Python list\n\n                    Python list created by taking the union of the\n                    lists in `ListOfLists`."
  },
  {
    "code": "def lookup_matching(self, urls):\n        hosts = (urlparse(u).hostname for u in urls)\n        for val in hosts:\n            item = self.lookup(val)\n            if item is not None:\n                yield item",
    "docstring": "Get matching hosts for the given URLs.\n\n        :param urls: an iterable containing URLs\n        :returns: instances of AddressListItem representing listed\n        hosts matching the ones used by the given URLs\n        :raises InvalidURLError: if there are any invalid URLs in\n        the sequence"
  },
  {
    "code": "def uninstall_all_visa_handlers(self, session):\n        if session is not None:\n            self.__uninstall_all_handlers_helper(session)\n        else:\n            for session in list(self.handlers):\n                self.__uninstall_all_handlers_helper(session)",
    "docstring": "Uninstalls all previously installed handlers for a particular session.\n\n        :param session: Unique logical identifier to a session. If None, operates on all sessions."
  },
  {
    "code": "def tqdm_hook(t):\n    last_b = [0]\n    def update_to(b=1, bsize=1, tsize=None):\n        if tsize is not None:\n            t.total = tsize\n        t.update((b - last_b[0]) * bsize)\n        last_b[0] = b\n    return update_to",
    "docstring": "Wraps tqdm instance.\n\n    Don't forget to close() or __exit__()\n    the tqdm instance once you're done with it (easiest using `with` syntax).\n    Example\n    -------\n    >>> with tqdm(...) as t:\n    ...     reporthook = my_hook(t)\n    ...     urllib.urlretrieve(..., reporthook=reporthook)"
  },
  {
    "code": "def calc_model(cortex, model_argument, model_hemi=Ellipsis, radius=np.pi/3):\n    if pimms.is_str(model_argument):\n        h = cortex.chirality if model_hemi is Ellipsis else \\\n            None             if model_hemi is None     else \\\n            model_hemi\n        model = retinotopy_model(model_argument, hemi=h, radius=radius)\n    else:\n        model = model_argument\n    if not isinstance(model, RegisteredRetinotopyModel):\n        raise ValueError('model must be a RegisteredRetinotopyModel')\n    return model",
    "docstring": "calc_model loads the appropriate model object given the model argument, which may given the name\n    of the model or a model object itself.\n\n    Required afferent parameters:\n      @ model_argument Must be either a RegisteredRetinotopyModel object or the name of a model that\n        can be loaded.\n\n    Optional afferent parameters:\n      @ model_hemi May be used to specify the hemisphere of the model; this is usually only used\n        when the fsaverage_sym hemisphere is desired, in which case this should be set to None; if\n        left at the default value (Ellipsis), then it will use the hemisphere of the cortex param.\n\n    Provided efferent values:\n      @ model Will be the RegisteredRetinotopyModel object to which the mesh should be registered."
  },
  {
    "code": "def __prepare_args(self, args):\n        ret = []\n        for a in args:\n            if isinstance(a, six.binary_type):\n                if self.__size_expr.match(a):\n                    ret += [a]\n                else:\n                    ret += [b'\"' + a + b'\"']\n                continue\n            ret += [bytes(str(a).encode(\"utf-8\"))]\n        return ret",
    "docstring": "Format command arguments before sending them.\n\n        Command arguments of type string must be quoted, the only\n        exception concerns size indication (of the form {\\d\\+?}).\n\n        :param args: list of arguments\n        :return: a list for transformed arguments"
  },
  {
    "code": "def delete_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False):\n        res = fw_const.DCNM_OUT_PART_DEL_SUCCESS\n        tenant_name = fw_dict.get('tenant_name')\n        ret = True\n        try:\n            self._delete_partition(tenant_id, tenant_name)\n        except Exception as exc:\n            LOG.error(\"deletion of Out Partition failed for tenant \"\n                      \"%(tenant)s, Exception %(exc)s\",\n                      {'tenant': tenant_id, 'exc': str(exc)})\n            res = fw_const.DCNM_OUT_PART_DEL_FAIL\n            ret = False\n        self.update_fw_db_result(tenant_id, dcnm_status=res)\n        LOG.info(\"Out partition deleted\")\n        return ret",
    "docstring": "Delete the DCNM OUT partition and update the result."
  },
  {
    "code": "def login(self, username=None, password=None):\n        if username is None:\n            username = self.username\n        if password is None:\n            password = self.password\n        logger.debug(\"Logging into server\")\n        self.sc.sessionManager.Login(userName=username, password=password)\n        self._logged_in = True",
    "docstring": "Login to a vSphere server.\n\n        >>> client.login(username='Administrator', password='strongpass')\n\n        :param username: The username to authenticate as.\n        :type username: str\n        :param password: The password to authenticate with.\n        :type password: str"
  },
  {
    "code": "def set_data_length(self, length):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('El Torito Entry not initialized')\n        self.sector_count = utils.ceiling_div(length, 512)",
    "docstring": "A method to set the length of data for this El Torito Entry.\n\n        Parameters:\n         length - The new length for the El Torito Entry.\n        Returns:\n         Nothing."
  },
  {
    "code": "def _record_values_for_fit_summary_and_statsmodels(self):\n        needed_attributes = [\"fitted_probs\",\n                             \"params\",\n                             \"log_likelihood\",\n                             \"standard_errors\"]\n        try:\n            assert all([hasattr(self, attr) for attr in needed_attributes])\n            assert all([getattr(self, attr) is not None\n                        for attr in needed_attributes])\n        except AssertionError:\n            msg = \"Call this function only after setting/calculating all other\"\n            msg_2 = \" estimation results attributes\"\n            raise NotImplementedError(msg + msg_2)\n        self.nobs = self.fitted_probs.shape[0]\n        self.df_model = self.params.shape[0]\n        self.df_resid = self.nobs - self.df_model\n        self.llf = self.log_likelihood\n        self.bse = self.standard_errors\n        self.aic = compute_aic(self)\n        self.bic = compute_bic(self)\n        return None",
    "docstring": "Store the various estimation results that are used to describe how well\n        the estimated model fits the given dataset, and record the values that\n        are needed for the statsmodels estimation results table. All values are\n        stored on the model instance.\n\n        Returns\n        -------\n        None."
  },
  {
    "code": "def codemirror_field_js_bundle(field):\n    manifesto = CodemirrorAssetTagRender()\n    manifesto.register_from_fields(field)\n    try:\n        bundle_name = manifesto.js_bundle_names()[0]\n    except IndexError:\n        msg = (\"Given field with configuration name '{}' does not have a \"\n               \"Javascript bundle name\")\n        raise CodeMirrorFieldBundleError(msg.format(field.config_name))\n    return bundle_name",
    "docstring": "Filter to get CodeMirror Javascript bundle name needed for a single field.\n\n    Example:\n        ::\n\n        {% load djangocodemirror_tags %}\n        {{ form.myfield|codemirror_field_js_bundle }}\n\n    Arguments:\n        field (django.forms.fields.Field): A form field that contains a widget\n            :class:`djangocodemirror.widget.CodeMirrorWidget`.\n\n    Raises:\n        CodeMirrorFieldBundleError: If Codemirror configuration form field\n        does not have a bundle name.\n\n    Returns:\n        string: Bundle name to load with webassets."
  },
  {
    "code": "def set_default_headers(self):\n        mod_opts = self.application.mod_opts\n        if mod_opts.get('cors_origin'):\n            origin = self.request.headers.get('Origin')\n            allowed_origin = _check_cors_origin(origin, mod_opts['cors_origin'])\n            if allowed_origin:\n                self.set_header(\"Access-Control-Allow-Origin\", allowed_origin)",
    "docstring": "Set default CORS headers"
  },
  {
    "code": "def instruction_path(cls, project, instruction):\n        return google.api_core.path_template.expand(\n            \"projects/{project}/instructions/{instruction}\",\n            project=project,\n            instruction=instruction,\n        )",
    "docstring": "Return a fully-qualified instruction string."
  },
  {
    "code": "def probe_check(name, status, device_type):\n    status_string = PROBE_STATE.get(int(status), \"unknown\")\n    if status_string == \"ok\":\n        return ok, \"{} '{}': {}\".format(device_type, name, status_string)\n    if status_string == \"unknown\":\n        return unknown, \"{} '{}': {}\".format(device_type, name, status_string)\n    return critical, \"{} '{}': {}\".format(device_type, name, status_string)",
    "docstring": "if the status is \"ok\" in the PROBE_STATE dict, return ok + string\n    if the status is not \"ok\", return critical + string"
  },
  {
    "code": "def _include_term(self, term):\n        ref_needed = False\n        if term.relations:\n            for k,v in six.iteritems(term.relations):\n                for i,t in enumerate(v):\n                    try:\n                        if t.id not in self:\n                            self._include_term(t)\n                        v[i] = t.id\n                    except AttributeError:\n                        pass\n                    ref_needed = True\n        self.terms[term.id] = term\n        return ref_needed",
    "docstring": "Add a single term to the current ontology.\n\n        It is needed to dereference any term in the term's relationship\n        and then to build the reference again to make sure the other\n        terms referenced in the term's relations are the one contained\n        in the ontology (to make sure changes to one term in the ontology\n        will be applied to every other term related to that term)."
  },
  {
    "code": "def _dilated_conv_layer(self, output_channels, dilation_rate, apply_relu,\n                          name):\n    layer_components = [\n        conv.Conv2D(\n            output_channels, [3, 3],\n            initializers=self._initializers,\n            regularizers=self._regularizers,\n            rate=dilation_rate,\n            name=\"dilated_conv_\" + name),\n    ]\n    if apply_relu:\n      layer_components.append(lambda net: tf.nn.relu(net, name=\"relu_\" + name))\n    return sequential.Sequential(layer_components, name=name)",
    "docstring": "Create a dilated convolution layer.\n\n    Args:\n      output_channels: int. Number of output channels for each pixel.\n      dilation_rate: int. Represents how many pixels each stride offset will\n        move. A value of 1 indicates a standard convolution.\n      apply_relu: bool. If True, a ReLU non-linearlity is added.\n      name: string. Name for layer.\n\n    Returns:\n      a sonnet Module for a dilated convolution."
  },
  {
    "code": "def mod_watch(name,\n              restart=True,\n              update=False,\n              user=None,\n              conf_file=None,\n              bin_env=None,\n              **kwargs):\n    return running(\n        name,\n        restart=restart,\n        update=update,\n        user=user,\n        conf_file=conf_file,\n        bin_env=bin_env\n    )",
    "docstring": "The supervisord watcher, called to invoke the watch command.\n    Always restart on watch\n\n    .. note::\n        This state exists to support special handling of the ``watch``\n        :ref:`requisite <requisites>`. It should not be called directly.\n\n        Parameters for this function should be set by the state being triggered."
  },
  {
    "code": "def raise_from(exc, cause):\n    context_tb = sys.exc_info()[2]\n    incorrect_cause = not (\n        (isinstance(cause, type) and issubclass(cause, Exception)) or\n        isinstance(cause, BaseException) or\n        cause is None\n    )\n    if incorrect_cause:\n        raise TypeError(\"exception causes must derive from BaseException\")\n    if cause is not None:\n        if not getattr(cause, \"__pep3134__\", False):\n            try:\n                raise_(cause)\n            except:\n                cause = sys.exc_info()[1]\n        cause.__fixed_traceback__ = context_tb\n    try:\n        raise_(exc)\n    except:\n        exc = sys.exc_info()[1]\n    exc.__original_exception__.__suppress_context__ = True\n    exc.__original_exception__.__cause__ = cause\n    exc.__original_exception__.__context__ = None\n    raise exc",
    "docstring": "Does the same as ``raise LALALA from BLABLABLA`` does in Python 3.\n    But works in Python 2 also!\n\n    Please checkout README on https://github.com/9seconds/pep3134\n    to get an idea about possible pitfals. But short story is: please\n    be pretty carefull with tracebacks. If it is possible, use sys.exc_info\n    instead. But in most cases it will work as you expect."
  },
  {
    "code": "def standby(self):\n        register = self.MMA8452Q_Register['CTRL_REG1']\n        self.board.i2c_read_request(self.address, register, 1,\n                                    Constants.I2C_READ | Constants.I2C_END_TX_MASK,\n                                    self.data_val, Constants.CB_TYPE_DIRECT)\n        ctrl1 = self.wait_for_read_result()\n        ctrl1 = (ctrl1[self.data_start]) & ~0x01\n        self.callback_data = []\n        self.board.i2c_write_request(self.address, [register, ctrl1])",
    "docstring": "Put the device into standby mode so that the registers can be set.\n        @return: No return value"
  },
  {
    "code": "def drop_columns(records, slices):\n    for record in records:\n        drop = set(i for slice in slices\n                   for i in range(*slice.indices(len(record))))\n        keep = [i not in drop for i in range(len(record))]\n        record.seq = Seq(''.join(itertools.compress(record.seq, keep)), record.seq.alphabet)\n        yield record",
    "docstring": "Drop all columns present in ``slices`` from records"
  },
  {
    "code": "def response(self, text, response_type='ephemeral', attachments=None):\n        from flask import jsonify\n        if attachments is None:\n            attachments = []\n        data = {\n            'response_type': response_type,\n            'text': text,\n            'attachments': attachments,\n        }\n        return jsonify(**data)",
    "docstring": "Return a response with json format\n\n        :param text: the text returned to the client\n        :param response_type: optional. When `in_channel` is assigned,\n                              both the response message and the initial\n                              message typed by the user will be shared\n                              in the channel.\n                              When `ephemeral` is assigned, the response\n                              message will be visible only to the user\n                              that issued the command.\n        :param attachments: optional. A list of additional messages\n                            for rich response."
  },
  {
    "code": "def reverse_dependencies(self, ireqs):\n        ireqs_as_cache_values = [self.as_cache_key(ireq) for ireq in ireqs]\n        return self._reverse_dependencies(ireqs_as_cache_values)",
    "docstring": "Returns a lookup table of reverse dependencies for all the given ireqs.\n\n        Since this is all static, it only works if the dependency cache\n        contains the complete data, otherwise you end up with a partial view.\n        This is typically no problem if you use this function after the entire\n        dependency tree is resolved."
  },
  {
    "code": "async def delete(self):\n        await r.table_name(self.table_name) \\\n            .get(self.id) \\\n            .delete() \\\n            .run(await conn.get())",
    "docstring": "Deletes the model from the database."
  },
  {
    "code": "def check(self):\n        pathfinder = Pathfinder(True)\n        if pathfinder.add_path(pathfinder['superfamily']) is None:\n            raise RuntimeError(\"'superfamily' data directory is missing\")\n        for tool in ('hmmscan', 'phmmer', 'mast', 'blastp', 'ass3.pl', 'hmmscan.pl'):\n            if not pathfinder.exists(tool):\n                raise RuntimeError('Dependency {} is missing'.format(tool))",
    "docstring": "Check if data and third party tools, necessary to run the classification, are available\n\n        :raises: RuntimeError"
  },
  {
    "code": "def jenkins_last_build_sha():\n        job_url = os.getenv('JOB_URL')\n        job_json_url = \"{0}/api/json\".format(job_url)\n        response = urllib.urlopen(job_json_url)\n        job_data = json.loads(response.read())\n        last_completed_build_url = job_data['lastCompletedBuild']['url']\n        last_complete_build_json_url = \"{0}/api/json\".format(last_completed_build_url)\n        response = urllib.urlopen(last_complete_build_json_url)\n        last_completed_build = json.loads(response.read())\n        return last_completed_build[1]['lastBuiltRevision']['SHA1']",
    "docstring": "Returns the sha of the last completed jenkins build for this project.\n        Expects JOB_URL in environment"
  },
  {
    "code": "def fmt_cut(cut):\n    return 'Cut {from_nodes} {symbol} {to_nodes}'.format(\n        from_nodes=fmt_mechanism(cut.from_nodes, cut.node_labels),\n        symbol=CUT_SYMBOL,\n        to_nodes=fmt_mechanism(cut.to_nodes, cut.node_labels))",
    "docstring": "Format a |Cut|."
  },
  {
    "code": "def _check_rel(attrs, rel_whitelist, rel_blacklist):\n        rels = attrs.get('rel', [None])\n        if rel_blacklist:\n            for rel in rels:\n                if rel in rel_blacklist:\n                    return False\n        if rel_whitelist:\n            for rel in rels:\n                if rel in rel_whitelist:\n                    return True\n            return False\n        return True",
    "docstring": "Check a link's relations against the whitelist or blacklist.\n\n        First, this will reject based on blacklist.\n\n        Next, if there is a whitelist, there must be at least one rel that matches.\n        To explicitly allow links without a rel you can add None to the whitelist\n        (e.g. ['in-reply-to',None])"
  },
  {
    "code": "def save(self, path, compress=True):\n        with aux.PartiallySafeReplace() as msr:\n            filename = self.info['name'] + '.proteindb'\n            filepath = aux.joinpath(path, filename)\n            with msr.open(filepath, mode='w+b') as openfile:\n                self._writeContainer(openfile, compress=compress)",
    "docstring": "Writes the ``.proteins`` and ``.peptides`` entries to the hard disk\n        as a ``proteindb`` file.\n\n        .. note::\n            If ``.save()`` is called and no ``proteindb`` file is present in the\n            specified path a new files is generated, otherwise the old file is\n            replaced.\n\n        :param path: filedirectory to which the ``proteindb`` file is written.\n            The output file name is specified by ``self.info['name']``\n        :param compress: bool, True to use zip file compression"
  },
  {
    "code": "def _makeIndentFromWidth(self, width):\n        if self._indenter.useTabs:\n            tabCount, spaceCount = divmod(width, self._indenter.width)\n            return ('\\t' * tabCount) + (' ' * spaceCount)\n        else:\n            return ' ' * width",
    "docstring": "Make indent text with specified with.\n        Contains width count of spaces, or tabs and spaces"
  },
  {
    "code": "def merge_bed_by_name(bt):\n    name_lines = dict()\n    for r in bt:\n        name = r.name\n        name_lines[name] = name_lines.get(name, []) + [[r.chrom, r.start, \n                                                         r.end, r.name,\n                                                         r.strand]]\n    new_lines = []\n    for name in name_lines.keys():\n        new_lines += _merge_interval_list(name_lines[name])\n    new_lines = ['\\t'.join(map(str, x)) for x in new_lines]\n    return pbt.BedTool('\\n'.join(new_lines) + '\\n', from_string=True)",
    "docstring": "Merge intervals in a bed file when the intervals have the same name.\n    Intervals with the same name must be adjacent in the bed file."
  },
  {
    "code": "def load(target, source_module=None):\n    module, klass, function = _get_module(target)\n    if not module and source_module:\n        module = source_module\n    if not module:\n        raise MissingModule(\n            \"No module name supplied or source_module provided.\")\n    actual_module = sys.modules[module]\n    if not klass:\n        return getattr(actual_module, function)\n    class_object = getattr(actual_module, klass)\n    if function:\n        return getattr(class_object, function)\n    return class_object",
    "docstring": "Get the actual implementation of the target."
  },
  {
    "code": "def sorted_groupby(df, groupby):\n    start = 0\n    prev = df[groupby].iloc[start]\n    for i, x in enumerate(df[groupby]):\n        if x != prev:\n            yield prev, df.iloc[start:i]\n            prev = x\n            start = i\n    yield prev, df.iloc[start:]",
    "docstring": "Perform a groupby on a DataFrame using a specific column\n    and assuming that that column is sorted.\n\n    Parameters\n    ----------\n    df : pandas.DataFrame\n    groupby : object\n        Column name on which to groupby. This column must be sorted.\n\n    Returns\n    -------\n    generator\n        Yields pairs of group_name, DataFrame."
  },
  {
    "code": "def redirect(view=None, url=None, **kwargs):\n    if view:\n        if url:\n            kwargs[\"url\"] = url\n        url = flask.url_for(view, **kwargs)\n    current_context.exit(flask.redirect(url))",
    "docstring": "Redirects to the specified view or url"
  },
  {
    "code": "def pixel_coord(self):\n        return self.get_pixel_coordinates(self.reading.pix_coord, self.reading.get_ccd_num())",
    "docstring": "Return the coordinates of the source in the cutout reference frame.\n        @return:"
  },
  {
    "code": "def fullConn (self, preCellsTags, postCellsTags, connParam):\n    from .. import sim\n    if sim.cfg.verbose: print('Generating set of all-to-all connections (rule: %s) ...' % (connParam['label']))\n    paramsStrFunc = [param for param in [p+'Func' for p in self.connStringFuncParams] if param in connParam] \n    for paramStrFunc in paramsStrFunc:\n        connParam[paramStrFunc[:-4]+'List'] = {(preGid,postGid): connParam[paramStrFunc](**{k:v if isinstance(v, Number) else v(preCellTags,postCellTags) for k,v in connParam[paramStrFunc+'Vars'].items()})  \n            for preGid,preCellTags in preCellsTags.items() for postGid,postCellTags in postCellsTags.items()}\n    for postCellGid in postCellsTags:\n        if postCellGid in self.gid2lid:\n            for preCellGid, preCellTags in preCellsTags.items():\n                self._addCellConn(connParam, preCellGid, postCellGid)",
    "docstring": "Generates connections between all pre and post-syn cells"
  },
  {
    "code": "def has_neigh(tag_name, params=None, content=None, left=True):\n    def has_neigh_closure(element):\n        if not element.parent \\\n           or not (element.isTag() and not element.isEndTag()):\n            return False\n        childs = element.parent.childs\n        childs = filter(\n            lambda x: (x.isTag() and not x.isEndTag()) \\\n                      or x.getContent().strip() or x is element,\n            childs\n        )\n        if len(childs) <= 1:\n            return False\n        ioe = childs.index(element)\n        if left and ioe > 0:\n            return is_equal_tag(childs[ioe - 1], tag_name, params, content)\n        if not left and ioe + 1 < len(childs):\n            return is_equal_tag(childs[ioe + 1], tag_name, params, content)\n        return False\n    return has_neigh_closure",
    "docstring": "This function generates functions, which matches all tags with neighbours\n    defined by parameters.\n\n    Args:\n        tag_name (str): Tag has to have neighbour with this tagname.\n        params (dict): Tag has to have neighbour with this parameters.\n        params (str): Tag has to have neighbour with this content.\n        left (bool, default True): Tag has to have neigbour on the left, or\n                                   right (set to ``False``).\n\n    Returns:\n        bool: True for every matching tag.\n\n    Note:\n        This function can be used as parameter for ``.find()`` method in\n        HTMLElement."
  },
  {
    "code": "def fix_style(style='basic', ax=None, **kwargs):\n    style = _read_style(style)\n    for s in style:\n        if not s in style_params.keys():\n            avail = [f.replace('.mplstyle', '') for f in os.listdir(\n                _get_lib()) if f.endswith('.mplstyle')]\n            raise ValueError('{0} is not a valid style. '.format(s) +\n                             'Please pick a style from the list available in ' +\n                             '{0}: {1}'.format(_get_lib(), avail))\n    _fix_style(style, ax, **kwargs)",
    "docstring": "Add an extra formatting layer to an axe, that couldn't be changed directly \n    in matplotlib.rcParams or with styles. Apply this function to every axe \n    you created.\n\n    Parameters\n    ----------    \n    ax: a matplotlib axe. \n        If None, the last axe generated is used \n    style: string or list of string\n        ['basic', 'article', 'poster', 'B&W','talk','origin'] \n        one of the styles previously defined. It should match the style you \n        chose in set_style but nothing forces you to.\n    kwargs: dict\n        edit any of the style_params keys. ex:\n            \n        >>> tight_layout=False\n\n    Examples\n    --------\n    plb.set_style('poster')\n    plt.plot(a,np.cos(a))\n    plb.fix_style('poster',**{'draggable_legend':False})    \n    \n    See Also\n    --------\n    \n    :func:`~publib.publib.set_style`\n    :func:`~publib.tools.tools.reset_defaults`"
  },
  {
    "code": "def edit_view(self, request, object_id):\n        kwargs = {'model_admin': self, 'object_id': object_id}\n        view_class = self.edit_view_class\n        return view_class.as_view(**kwargs)(request)",
    "docstring": "Instantiates a class-based view to provide 'edit' functionality for the\n        assigned model, or redirect to Wagtail's edit view if the assigned\n        model extends 'Page'. The view class used can be overridden by changing\n        the  'edit_view_class' attribute."
  },
  {
    "code": "def trim(self):\n        return\n        for l in self._levels[-2::-1]:\n            for n in l:\n                if n.is_leaf:\n                    n.parent.remove_child(n.label)\n        self._clear_all_leaves()",
    "docstring": "Trims leaves from tree that are not observed at highest-resolution level\n\n        This is a bit hacky-- what it does is"
  },
  {
    "code": "def update_confirmation(self, confirmation_id, confirmation_dict):\n        return self._create_put_request(\n            resource=CONFIRMATIONS,\n            billomat_id=confirmation_id,\n            send_data=confirmation_dict\n        )",
    "docstring": "Updates a confirmation\n\n        :param confirmation_id: the confirmation id\n        :param confirmation_dict: dict\n        :return: dict"
  },
  {
    "code": "def _cast_to_type(self, value):\n        if not isinstance(value, list):\n            self.fail('invalid', value=value)\n        return value",
    "docstring": "Raise error if the value is not a list"
  },
  {
    "code": "def update_os_version(self):\n        self.chain.connection.log(\"Detecting os version\")\n        os_version = self.driver.get_os_version(self.version_text)\n        if os_version:\n            self.chain.connection.log(\"SW Version: {}\".format(os_version))\n            self.os_version = os_version",
    "docstring": "Update os_version attribute."
  },
  {
    "code": "def fromHTML(html, *args, **kwargs):\n        source = BeautifulSoup(html, 'html.parser', *args, **kwargs)\n        return TOC('[document]',\n            source=source,\n            descendants=source.children)",
    "docstring": "Creates abstraction using HTML\n\n        :param str html: HTML\n        :return: TreeOfContents object"
  },
  {
    "code": "def plot(self,bins=10,facecolor='0.5',plot_cols=None,\n                    filename=\"ensemble.pdf\",func_dict = None,\n                    **kwargs):\n        ensemble_helper(self,bins=bins,facecolor=facecolor,plot_cols=plot_cols,\n                        filename=filename)",
    "docstring": "plot ensemble histograms to multipage pdf\n\n        Parameters\n        ----------\n        bins : int\n            number of bins\n        facecolor : str\n            color\n        plot_cols : list of str\n            subset of ensemble columns to plot.  If None, all are plotted.\n            Default is None\n        filename : str\n            pdf filename. Default is \"ensemble.pdf\"\n        func_dict : dict\n            a dict of functions to apply to specific columns (e.g., np.log10)\n\n        **kwargs : dict\n            keyword args to pass to plot_utils.ensemble_helper()\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def datatable_df(self):\r\n        data = self._all_datatable_data()\r\n        adf = pd.DataFrame(data)\r\n        adf.columns = self.dt_all_cols\r\n        return self._finish_df(adf, 'ALL')",
    "docstring": "returns the dataframe representation of the symbol's final data"
  },
  {
    "code": "def _cleanup_markers(context_id, task_ids):\n    logging.debug(\"Cleanup %d markers for Context %s\",\n                  len(task_ids), context_id)\n    delete_entities = [ndb.Key(FuriousAsyncMarker, id) for id in task_ids]\n    delete_entities.append(ndb.Key(FuriousCompletionMarker, context_id))\n    ndb.delete_multi(delete_entities)\n    logging.debug(\"Markers cleaned.\")",
    "docstring": "Delete the FuriousAsyncMarker entities corresponding to ids."
  },
  {
    "code": "def cancel(self, job):\n        if isinstance(job, self.job_class):\n            self.connection.zrem(self.scheduled_jobs_key, job.id)\n        else:\n            self.connection.zrem(self.scheduled_jobs_key, job)",
    "docstring": "Pulls a job from the scheduler queue. This function accepts either a\n        job_id or a job instance."
  },
  {
    "code": "def include_yaml(self, node):\n        filename = self.construct_scalar(node)\n        if not filename.startswith('/'):\n            if self._root is None:\n                raise Exception('!include_yaml %s is a relative path, '\n                                'but stream lacks path' % filename)\n            filename = os.path.join(self._root, self.construct_scalar(node))\n        with self.open(filename, 'r') as fin:\n            return yaml.load(fin, Loader)",
    "docstring": "load another yaml file from the path specified by node's value"
  },
  {
    "code": "def day_interval(year, month, day, milliseconds=False, return_string=False):\n    if milliseconds:\n        delta = timedelta(milliseconds=1)\n    else:\n        delta = timedelta(seconds=1)\n    start = datetime(year, month, day)\n    end = datetime(year, month, day) + timedelta(days=1) - delta\n    if not return_string:\n        return start, end\n    else:\n        return str(start), str(end)",
    "docstring": "Return a start datetime and end datetime of a day.\n\n    :param milliseconds: Minimum time resolution.\n    :param return_string: If you want string instead of datetime, set True\n\n    Usage Example::\n\n        >>> start, end = rolex.day_interval(2014, 6, 17)\n        >>> start\n        datetime(2014, 6, 17, 0, 0, 0)\n\n        >>> end\n        datetime(2014, 6, 17, 23, 59, 59)"
  },
  {
    "code": "def token(self, token_address: Address) -> Token:\n        if not is_binary_address(token_address):\n            raise ValueError('token_address must be a valid address')\n        with self._token_creation_lock:\n            if token_address not in self.address_to_token:\n                self.address_to_token[token_address] = Token(\n                    jsonrpc_client=self.client,\n                    token_address=token_address,\n                    contract_manager=self.contract_manager,\n                )\n        return self.address_to_token[token_address]",
    "docstring": "Return a proxy to interact with a token."
  },
  {
    "code": "def _run_tool(cmd, use_container=True, work_dir=None, log_file=None):\n    if isinstance(cmd, (list, tuple)):\n        cmd = \" \".join([str(x) for x in cmd])\n    cmd = utils.local_path_export(at_start=use_container) + cmd\n    if log_file:\n        cmd += \" 2>&1 | tee -a %s\" % log_file\n    try:\n        print(\"Running: %s\" % cmd)\n        subprocess.check_call(cmd, shell=True)\n    finally:\n        if use_container and work_dir:\n            _chown_workdir(work_dir)",
    "docstring": "Run with injection of bcbio path.\n\n    Place at end for runs without containers to avoid overriding other\n    bcbio installations."
  },
  {
    "code": "def text(self, value):\n        self._text = value\n        self.timestamps.edited = datetime.datetime.utcnow()\n        self.touch(True)",
    "docstring": "Set the text value.\n\n        Args:\n            value (str): Text value."
  },
  {
    "code": "def _get_nblock_regions(in_file, min_n_size, ref_regions):\n    out_lines = []\n    called_contigs = set([])\n    with utils.open_gzipsafe(in_file) as in_handle:\n        for line in in_handle:\n            contig, start, end, ctype = line.rstrip().split()\n            called_contigs.add(contig)\n            if (ctype in [\"REF_N\", \"NO_COVERAGE\", \"EXCESSIVE_COVERAGE\", \"LOW_COVERAGE\"] and\n                  int(end) - int(start) > min_n_size):\n                out_lines.append(\"%s\\t%s\\t%s\\n\" % (contig, start, end))\n    for refr in ref_regions:\n        if refr.chrom not in called_contigs:\n            out_lines.append(\"%s\\t%s\\t%s\\n\" % (refr.chrom, 0, refr.stop))\n    return pybedtools.BedTool(\"\\n\".join(out_lines), from_string=True)",
    "docstring": "Retrieve coordinates of regions in reference genome with no mapping.\n    These are potential breakpoints for parallelizing analysis."
  },
  {
    "code": "def estimate_pos_and_err_parabolic(tsvals):\n    a = tsvals[2] - tsvals[0]\n    bc = 2. * tsvals[1] - tsvals[0] - tsvals[2]\n    s = a / (2 * bc)\n    err = np.sqrt(2 / bc)\n    return s, err",
    "docstring": "Solve for the position and uncertainty of source in one dimension\n         assuming that you are near the maximum and the errors are parabolic\n\n    Parameters\n    ----------\n    tsvals  :  `~numpy.ndarray`\n       The TS values at the maximum TS, and for each pixel on either side\n\n    Returns\n    -------\n    The position and uncertainty of the source, in pixel units\n    w.r.t. the center of the maximum pixel"
  },
  {
    "code": "def walk(self):\n        if conf.core.snapshots is not None:\n            return self.snaps[conf.core.snapshots]\n        elif conf.core.timesteps is not None:\n            return self.steps[conf.core.timesteps]\n        return self.snaps[-1:]",
    "docstring": "Return view on configured steps slice.\n\n        Other Parameters:\n            conf.core.snapshots: the slice of snapshots.\n            conf.core.timesteps: the slice of timesteps."
  },
  {
    "code": "def reformat_cmd(self, text):\n        text = text.replace('az', '')\n        if text and SELECT_SYMBOL['scope'] == text[0:2]:\n            text = text.replace(SELECT_SYMBOL['scope'], \"\")\n        if self.shell_ctx.default_command:\n            text = self.shell_ctx.default_command + ' ' + text\n        return text",
    "docstring": "reformat the text to be stripped of noise"
  },
  {
    "code": "def peek(self, fmt):\n        pos_before = self._pos\n        value = self.read(fmt)\n        self._pos = pos_before\n        return value",
    "docstring": "Interpret next bits according to format string and return result.\n\n        fmt -- Token string describing how to interpret the next bits.\n\n        The position in the bitstring is not changed. If not enough bits are\n        available then all bits to the end of the bitstring will be used.\n\n        Raises ReadError if not enough bits are available.\n        Raises ValueError if the format is not understood.\n\n        See the docstring for 'read' for token examples."
  },
  {
    "code": "def read_chunks(self):\n        if self.reading_chunks and self.got_chunk:\n            logger.debug(\"Fast-Path detected, returning...\")\n            return\n        while not self.got_request:\n            self.reading_chunks = True\n            self.got_chunk = False\n            self.httpstream.read_until(\"\\r\\n\", self._chunk_length)\n            self.reading_chunks = False\n            if self.got_chunk:\n                logger.debug(\"Fast-Path detected, iterating...\")\n                continue\n            else:\n                break\n        return",
    "docstring": "Read chunks from the HTTP client"
  },
  {
    "code": "def info(self):\n        ddoc_info = self.r_session.get(\n            '/'.join([self.document_url, '_info']))\n        ddoc_info.raise_for_status()\n        return response_to_json_dict(ddoc_info)",
    "docstring": "Retrieves the design document view information data, returns dictionary\n\n        GET databasename/_design/{ddoc}/_info"
  },
  {
    "code": "def path_helper(self, path, view, **kwargs):\n        super(FlaskRestyPlugin, self).path_helper(\n            path=path,\n            view=view,\n            **kwargs\n        )\n        resource = self.get_state().views[view]\n        rule = self._rules[resource.rule]\n        operations = defaultdict(Operation)\n        view_instance = view()\n        view_instance.spec_declaration(view, operations, self)\n        parameters = []\n        for arg in rule.arguments:\n            parameters.append({\n                'name': arg,\n                'in': 'path',\n                'required': True,\n                'type': 'string',\n            })\n        if parameters:\n            operations['parameters'] = parameters\n        path.path = FlaskPlugin.flaskpath2openapi(resource.rule)\n        path.operations = dict(**operations)",
    "docstring": "Path helper for Flask-RESTy views.\n\n        :param view: An `ApiView` object."
  },
  {
    "code": "def with_blob(self, blob):\n        content = json.loads(blob.content)\n        self.partition_id = content[\"partition_id\"]\n        self.owner = content[\"owner\"]\n        self.token = content[\"token\"]\n        self.epoch = content[\"epoch\"]\n        self.offset = content[\"offset\"]\n        self.sequence_number = content[\"sequence_number\"]\n        self.event_processor_context = content.get(\"event_processor_context\")",
    "docstring": "Init Azure Blob Lease with existing blob."
  },
  {
    "code": "def create_exception_by_error_code(\n    errorCode,\n    detailCode='0',\n    description='',\n    traceInformation=None,\n    identifier=None,\n    nodeId=None,\n):\n    try:\n        dataone_exception = ERROR_CODE_TO_EXCEPTION_DICT[errorCode]\n    except LookupError:\n        dataone_exception = ServiceFailure\n    return dataone_exception(\n        detailCode, description, traceInformation, identifier, nodeId\n    )",
    "docstring": "Create a DataONE Exception object by errorCode.\n\n    See Also:   For args, see: ``DataONEException()``"
  },
  {
    "code": "def batch_message(cls, batch, request_ids):\n        assert isinstance(batch, Batch)\n        if not cls.allow_batches:\n            raise ProtocolError.invalid_request(\n                'protocol does not permit batches')\n        id_iter = iter(request_ids)\n        rm = cls.request_message\n        nm = cls.notification_message\n        parts = (rm(request, next(id_iter)) if isinstance(request, Request)\n                 else nm(request) for request in batch)\n        return cls.batch_message_from_parts(parts)",
    "docstring": "Convert a request Batch to a message."
  },
  {
    "code": "def _try_assign_utc_time(self, raw_time, time_base):\n        if raw_time != IOTileEvent.InvalidRawTime and (raw_time & (1 << 31)):\n            y2k_offset = self.raw_time ^ (1 << 31)\n            return self._Y2KReference + datetime.timedelta(seconds=y2k_offset)\n        if time_base is not None:\n            return time_base + datetime.timedelta(seconds=raw_time)\n        return None",
    "docstring": "Try to assign a UTC time to this reading."
  },
  {
    "code": "def copy(self):\n    self_copy = self.dup()\n    self_copy._scopes = copy.copy(self._scopes)\n    return self_copy",
    "docstring": "Return a copy of this object."
  },
  {
    "code": "def _param_types_to_shape(self, param_types: Optional[str]) -> Sequence[int]:\n        param_types = [] if param_types is None else param_types\n        shape = tuple(self.object_table[ptype]['size'] for ptype in param_types)\n        return shape",
    "docstring": "Returns the fluent shape given its `param_types`."
  },
  {
    "code": "def pip(usr_pswd=None):\n\ttry: cmd('which pip')\n\texcept:\n\t\treturn\n\tprint('-[pip]----------')\n\tp = cmd('pip list --outdated')\n\tif not p: return\n\tpkgs = getPackages(p)\n\tfor i, p in enumerate(pkgs):\n\t\tif p in ['pip', 'setuptools']:\n\t\t\tcmd('pip install -U ' + p, usr_pwd=usr_pswd, run=global_run)\n\t\t\tpkgs.pop(i)\n\tfor p in pkgs:\n\t\tcmd('pip install -U ' + p, usr_pwd=usr_pswd, run=global_run)",
    "docstring": "This updates one package at a time.\n\n\tCould do all at once:\n\t\tpip list --outdated | cut -d' ' -f1 | xargs pip install --upgrade"
  },
  {
    "code": "def interpolate_single(start, end, coefficient, how='linear'):\n    return INTERP_SINGLE_DICT[how](start, end, coefficient)",
    "docstring": "Interpolate single value between start and end in given number of steps"
  },
  {
    "code": "def seek(self, pos=0):\n        if pos - self.pos >= 0:\n            blocks, remainder = divmod(pos - self.pos, self.bufsize)\n            for i in range(blocks):\n                self.read(self.bufsize)\n            self.read(remainder)\n        else:\n            raise StreamError(\"seeking backwards is not allowed\")\n        return self.pos",
    "docstring": "Set the stream's file pointer to pos. Negative seeking\n           is forbidden."
  },
  {
    "code": "def _update_aes(self):\n        if salt.master.SMaster.secrets['aes']['secret'].value != self.crypticle.key_string:\n            self.crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets['aes']['secret'].value)\n            return True\n        return False",
    "docstring": "Check to see if a fresh AES key is available and update the components\n        of the worker"
  },
  {
    "code": "def uninstall(cert_name,\n              keychain=\"/Library/Keychains/System.keychain\",\n              keychain_password=None):\n    if keychain_password is not None:\n        unlock_keychain(keychain, keychain_password)\n    cmd = 'security delete-certificate -c \"{0}\" {1}'.format(cert_name, keychain)\n    return __salt__['cmd.run'](cmd)",
    "docstring": "Uninstall a certificate from a keychain\n\n    cert_name\n        The name of the certificate to remove\n\n    keychain\n        The keychain to install the certificate to, this defaults to\n        /Library/Keychains/System.keychain\n\n    keychain_password\n        If your keychain is likely to be locked pass the password and it will be unlocked\n        before running the import\n\n        Note: The password given here will show up as plaintext in the returned job\n        info.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' keychain.install test.p12 test123"
  },
  {
    "code": "def append(self, listname, xy_idx, var_name, element_name):\n        self.resize()\n        string = '{0} {1}'\n        if listname not in ['unamex', 'unamey', 'fnamex', 'fnamey']:\n            logger.error('Wrong list name for varname.')\n            return\n        elif listname in ['fnamex', 'fnamey']:\n            string = '${0}\\\\ {1}$'\n        if isinstance(element_name, list):\n            for i, j in zip(xy_idx, element_name):\n                if listname == 'fnamex' or listname == 'fnamey':\n                    j = j.replace(' ', '\\\\ ')\n                self.__dict__[listname][i] = string.format(var_name, j)\n        elif isinstance(element_name, int):\n            self.__dict__[listname][xy_idx] = string.format(\n                var_name, element_name)\n        else:\n            logger.warning(\n                'Unknown element_name type while building varname')",
    "docstring": "Append variable names to the name lists"
  },
  {
    "code": "def user_pass(self, func=None, location=None, **rkwargs):\n        def wrapper(view):\n            view = to_coroutine(view)\n            @functools.wraps(view)\n            async def handler(request, *args, **kwargs):\n                await self.check_user(request, func, location, **rkwargs)\n                return await view(request, *args, **kwargs)\n            return handler\n        return wrapper",
    "docstring": "Decorator ensures that user pass the given func."
  },
  {
    "code": "def before_content(self):\n        ChapelObject.before_content(self)\n        if self.names:\n            self.env.temp_data['chpl:class'] = self.names[0][0]\n            self.clsname_set = True",
    "docstring": "Called before parsing content. Push the class name onto the class name\n        stack. Used to construct the full name for members."
  },
  {
    "code": "def execute(self, query_string, params=None):\n    cr = self.connection.cursor()\n    logger.info(\"SQL: %s (%s)\", query_string, params)\n    self.last_query = (query_string, params)\n    t0 = time.time()\n    cr.execute(query_string, params or self.core.empty_params)\n    ms = (time.time() - t0) * 1000\n    logger.info(\"RUNTIME: %.2f ms\", ms)\n    self._update_cursor_stats(cr)\n    return cr",
    "docstring": "Executes a query. Returns the resulting cursor.\n\n    :query_string: the parameterized query string\n    :params: can be either a tuple or a dictionary, and must match the parameterization style of the\n             query\n    :return: a cursor object"
  },
  {
    "code": "def prepare_for_negotiated_authenticate(\n            self, entityid=None, relay_state=\"\", binding=None, vorg=\"\",\n            nameid_format=None, scoping=None, consent=None, extensions=None,\n            sign=None, response_binding=saml2.BINDING_HTTP_POST, **kwargs):\n        expected_binding = binding\n        for binding in [BINDING_HTTP_REDIRECT, BINDING_HTTP_POST]:\n            if expected_binding and binding != expected_binding:\n                continue\n            destination = self._sso_location(entityid, binding)\n            logger.info(\"destination to provider: %s\", destination)\n            reqid, request = self.create_authn_request(\n                destination, vorg, scoping, response_binding, nameid_format,\n                consent=consent, extensions=extensions, sign=sign,\n                **kwargs)\n            _req_str = str(request)\n            logger.info(\"AuthNReq: %s\", _req_str)\n            try:\n                args = {'sigalg': kwargs[\"sigalg\"]}\n            except KeyError:\n                args = {}\n            http_info = self.apply_binding(binding, _req_str, destination,\n                                           relay_state, sign=sign, **args)\n            return reqid, binding, http_info\n        else:\n            raise SignOnError(\n                \"No supported bindings available for authentication\")",
    "docstring": "Makes all necessary preparations for an authentication request\n        that negotiates which binding to use for authentication.\n\n        :param entityid: The entity ID of the IdP to send the request to\n        :param relay_state: To where the user should be returned after\n            successfull log in.\n        :param binding: Which binding to use for sending the request\n        :param vorg: The entity_id of the virtual organization I'm a member of\n        :param nameid_format:\n        :param scoping: For which IdPs this query are aimed.\n        :param consent: Whether the principal have given her consent\n        :param extensions: Possible extensions\n        :param sign: Whether the request should be signed or not.\n        :param response_binding: Which binding to use for receiving the response\n        :param kwargs: Extra key word arguments\n        :return: session id and AuthnRequest info"
  },
  {
    "code": "def replace_in_files(dirname, replace):\n    filepath = os.path.abspath(dirname / \"requirements.in\")\n    if os.path.isfile(filepath) and header_footer_exists(filepath):\n        replaced = re.sub(Utils.exp, replace, get_file_string(filepath))\n        with open(filepath, \"w\") as f:\n            f.write(replaced)\n        print(color(\n            \"Written to file: {}\".format(filepath),\n            fg='magenta', style='bold'))",
    "docstring": "Replace current version with new version in requirements files."
  },
  {
    "code": "def get_path(self, dir=None):\n        if not dir:\n            dir = self.fs.getcwd()\n        if self == dir:\n            return '.'\n        path_elems = self.get_path_elements()\n        pathname = ''\n        try: i = path_elems.index(dir)\n        except ValueError:\n            for p in path_elems[:-1]:\n                pathname += p.dirname\n        else:\n            for p in path_elems[i+1:-1]:\n                pathname += p.dirname\n        return pathname + path_elems[-1].name",
    "docstring": "Return path relative to the current working directory of the\n        Node.FS.Base object that owns us."
  },
  {
    "code": "def get_stage_events(cls, crawler, stage_name, start, end, level=None):\n        key = make_key(crawler, \"events\", stage_name, level)\n        return cls.event_list(key, start, end)",
    "docstring": "events from a particular stage"
  },
  {
    "code": "async def _reset_protocol(self, exc=None):\n        protocol = await self._get_protocol()\n        await protocol.shutdown()\n        self._protocol = None\n        for ob_error in self._observations_err_callbacks:\n            ob_error(exc)\n        self._observations_err_callbacks.clear()",
    "docstring": "Reset the protocol if an error occurs."
  },
  {
    "code": "def fire(self, *args, **kargs):\n        self._time_secs_old = time.time()\n        with self._hlock:\n            handler_list = copy.copy(self._handler_list)\n        result_list = []\n        for handler in handler_list:\n            if self._sync_mode:\n                result = self._execute(handler, *args, **kargs)\n                if isinstance(result, tuple) and len(result) == 3 and isinstance(result[1], Exception):\n                    one_res_tuple = (False, self._error(result), handler)\n                else:\n                    one_res_tuple = (True, result, handler)\n            else:\n                EventSystem._async_queue.put((handler, args, kargs))\n                one_res_tuple = (None, None, handler)\n            result_list.append(one_res_tuple)\n        time_secs_new = time.time()\n        self.duration_secs = time_secs_new - self._time_secs_old\n        self._time_secs_old = time_secs_new\n        return result_list",
    "docstring": "collects results of all executed handlers"
  },
  {
    "code": "def thesauri(self, token: dict = None, prot: str = \"https\") -> dict:\n        thez_url = \"{}://v1.{}.isogeo.com/thesauri\".format(prot, self.api_url)\n        thez_req = self.get(\n            thez_url, headers=self.header, proxies=self.proxies, verify=self.ssl\n        )\n        checker.check_api_response(thez_req)\n        return thez_req.json()",
    "docstring": "Get list of available thesauri.\n\n        :param str token: API auth token\n        :param str prot: https [DEFAULT] or http\n         (use it only for dev and tracking needs)."
  },
  {
    "code": "def list_parse(name_list):\n    if name_list and name_list[0] == '@':\n        value = name_list[1:]\n        if not os.path.exists(value):\n            log.warning('The file %s does not exist' % value)\n            return\n        try:\n            return [v.strip() for v in open(value, 'r').readlines()]\n        except IOError as e:\n            log.warning('reading %s failed: %s; ignoring this file' %\n                        (value, e))\n    else:\n        return [v.strip() for v in name_list.split(',')]",
    "docstring": "Parse a comma-separated list of values, or a filename (starting with @)\n    containing a list value on each line."
  },
  {
    "code": "def _make_fn_text(self):\r\n        if not self._f:\r\n            text = \"(not loaded)\"\r\n        elif self._f.filename:\r\n            text = os.path.relpath(self._f.filename, \".\")\r\n        else:\r\n            text = \"(filename not set)\"\r\n        return text",
    "docstring": "Makes filename text"
  },
  {
    "code": "def _convert_args(args):\n    converted = []\n    for arg in args:\n        if isinstance(arg, dict):\n            for key in list(arg.keys()):\n                if key == '__kwarg__':\n                    continue\n                converted.append('{0}={1}'.format(key, arg[key]))\n        else:\n            converted.append(arg)\n    return converted",
    "docstring": "Take a list of args, and convert any dicts inside the list to keyword\n    args in the form of `key=value`, ready to be passed to salt-ssh"
  },
  {
    "code": "def layers(self):\n        if self._layers is None:\n            self.__init()\n        lyrs = []\n        for lyr in self._layers:\n            lyr['object'] = GlobeServiceLayer(url=self._url + \"/%s\" % lyr['id'],\n                                              securityHandler=self._securityHandler,\n                                              proxy_port=self._proxy_port,\n                                              proxy_url=self._proxy_url)\n            lyrs.append(lyr)\n        return lyrs",
    "docstring": "gets the globe service layers"
  },
  {
    "code": "def _update_range(self, data, **kwargs):\n        self._client.update_range(data=data, **kwargs)",
    "docstring": "Update range with data\n\n        Args:\n            data (bytes): data."
  },
  {
    "code": "def get_next_tag(cls, el):\n        sibling = el.next_sibling\n        while not cls.is_tag(sibling) and sibling is not None:\n            sibling = sibling.next_sibling\n        return sibling",
    "docstring": "Get next sibling tag."
  },
  {
    "code": "def assemble_flash_code(self, asm):\n\t\tstream = StringIO(asm)\n\t\tworker = assembler.Assembler(self.processor, stream)\n\t\ttry:\n\t\t\tresult = worker.assemble()\n\t\texcept BaseException as e:\n\t\t\treturn e, None\n\t\tself.flash.program(result)\n\t\treturn None, result",
    "docstring": "assemble the given code and program the Flash"
  },
  {
    "code": "def colorize_format(self, fmt, style=DEFAULT_FORMAT_STYLE):\n        result = []\n        parser = FormatStringParser(style=style)\n        for group in parser.get_grouped_pairs(fmt):\n            applicable_styles = [self.nn.get(self.field_styles, token.name) for token in group if token.name]\n            if sum(map(bool, applicable_styles)) == 1:\n                result.append(ansi_wrap(\n                    ''.join(token.text for token in group),\n                    **next(s for s in applicable_styles if s)\n                ))\n            else:\n                for token in group:\n                    text = token.text\n                    if token.name:\n                        field_styles = self.nn.get(self.field_styles, token.name)\n                        if field_styles:\n                            text = ansi_wrap(text, **field_styles)\n                    result.append(text)\n        return ''.join(result)",
    "docstring": "Rewrite a logging format string to inject ANSI escape sequences.\n\n        :param fmt: The log format string.\n        :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to\n                      :data:`DEFAULT_FORMAT_STYLE`).\n        :returns: The logging format string with ANSI escape sequences.\n\n        This method takes a logging format string like the ones you give to\n        :class:`logging.Formatter` and processes it as follows:\n\n        1. First the logging format string is separated into formatting\n           directives versus surrounding text (according to the given `style`).\n\n        2. Then formatting directives and surrounding text are grouped\n           based on whitespace delimiters (in the surrounding text).\n\n        3. For each group styling is selected as follows:\n\n           1. If the group contains a single formatting directive that has\n              a style defined then the whole group is styled accordingly.\n\n           2. If the group contains multiple formatting directives that\n              have styles defined then each formatting directive is styled\n              individually and surrounding text isn't styled.\n\n        As an example consider the default log format (:data:`DEFAULT_LOG_FORMAT`)::\n\n         %(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s\n\n        The default field styles (:data:`DEFAULT_FIELD_STYLES`) define a style for the\n        `name` field but not for the `process` field, however because both fields\n        are part of the same whitespace delimited token they'll be highlighted\n        together in the style defined for the `name` field."
  },
  {
    "code": "def backspace(self):\n        if self._cx + self._cw >= 0:\n            self.erase()\n            self._cx -= self._cw\n        self.flush()",
    "docstring": "Moves the cursor one place to the left, erasing the character at the\n        current position. Cannot move beyond column zero, nor onto the\n        previous line."
  },
  {
    "code": "def price_dec(raw_price, default=_not_defined):\n    try:\n        price = price_str(raw_price)\n        return decimal.Decimal(price)\n    except ValueError as err:\n        if default == _not_defined:\n            raise err\n    return default",
    "docstring": "Price decimal value from raw string.\n\n    Extract price value from input raw string and\n    present as Decimal number.\n\n    If raw price does not contain valid price value or contains\n    more than one price value, then return default value.\n    If default value not set, then raise ValueError.\n\n    :param str raw_price: string that contains price value.\n    :param default: value that will be returned if raw price not valid.\n    :return: Decimal price value.\n    :raise ValueError: error if raw price not valid and default value not set."
  },
  {
    "code": "def mtf_range(mesh, dim, dtype, name=None):\n  dim = convert_to_dimension(dim)\n  with tf.variable_scope(name, default_name=\"range\"):\n    if dtype == tf.bfloat16:\n      tf_range = tf.cast(tf.range(dim.size), tf.bfloat16)\n    else:\n      tf_range = tf.range(dim.size, dtype=dtype)\n    return import_tf_tensor(mesh, tf_range, shape=Shape([dim]))",
    "docstring": "Create a 1d mesh tensor with a range from [0, dim.size).\n\n  Call externally as mtf.range()\n\n  Args:\n    mesh: a Mesh\n    dim: a Dimension\n    dtype: a tf.DType\n    name: an optional string\n\n  Returns:\n    a Tensor"
  },
  {
    "code": "def _dead_assignment_elimination(self, function, data_graph):\n        register_pvs = set()\n        for node in data_graph.nodes():\n            if isinstance(node.variable, SimRegisterVariable) and \\\n                    node.variable.reg is not None and \\\n                    node.variable.reg < 40:\n                register_pvs.add(node)\n        for reg in register_pvs:\n            out_edges = data_graph.out_edges(reg, data=True)\n            consumers = [ ]\n            killers = [ ]\n            for _, _, data in out_edges:\n                if 'type' in data and data['type'] == 'kill':\n                    killers.append(data)\n                else:\n                    consumers.append(data)\n            if not consumers and killers:\n                da = DeadAssignment(reg)\n                self.dead_assignments.append(da)",
    "docstring": "Remove assignments to registers that has no consumers, but immediately killed.\n\n        BROKEN - DO NOT USE IT\n\n        :param angr.knowledge.Function function:\n        :param networkx.MultiDiGraph data_graph:\n        :return: None"
  },
  {
    "code": "def lock_resource_for_update(cls, resource_id, db_session):\n        db_session = get_db_session(db_session)\n        query = db_session.query(cls.model)\n        query = query.filter(cls.model.resource_id == resource_id)\n        query = query.with_for_update()\n        return query.first()",
    "docstring": "Selects resource for update - locking access for other transactions\n\n        :param resource_id:\n        :param db_session:\n        :return:"
  },
  {
    "code": "def load_ui_type(uifile):\n    import pysideuic\n    import xml.etree.ElementTree as ElementTree\n    from cStringIO import StringIO\n    parsed = ElementTree.parse(uifile)\n    widget_class = parsed.find('widget').get('class')\n    form_class = parsed.find('class').text\n    with open(uifile, 'r') as f:\n        o = StringIO()\n        frame = {}\n        pysideuic.compileUi(f, o, indent=0)\n        pyc = compile(o.getvalue(), '<string>', 'exec')\n        exec(pyc) in frame\n        form_class = frame['Ui_%s' % form_class]\n        base_class = eval('QtWidgets.%s' % widget_class)\n    return form_class, base_class",
    "docstring": "Pyside equivalent for the loadUiType function in PyQt.\n\n    From the PyQt4 documentation:\n        Load a Qt Designer .ui file and return a tuple of the generated form\n        class and the Qt base class. These can then be used to create any\n        number of instances of the user interface without having to parse the\n        .ui file more than once.\n\n    Note:\n        Pyside lacks the \"loadUiType\" command, so we have to convert the ui\n        file to py code in-memory first and then execute it in a special frame\n        to retrieve the form_class.\n\n    Args:\n        uifile (str): Absolute path to .ui file\n\n\n    Returns:\n        tuple: the generated form class, the Qt base class"
  },
  {
    "code": "def _handle_continuations(self, response, cache_key):\n        rcontinue = response.get('continue')\n        listen = ['blcontinue', 'cmcontinue', 'plcontinue']\n        cparams = {}\n        if rcontinue:\n            for flag in listen:\n                if rcontinue.get(flag):\n                    cparams[flag] = rcontinue.get(flag)\n        if cparams:\n            self.data['continue'] = cparams\n            del self.cache[cache_key]\n        else:\n            if 'continue' in self.data:\n                del self.data['continue']",
    "docstring": "Select continue params and clear cache or last continue params"
  },
  {
    "code": "def image_resources(package=None, directory='resources'):\n    if not package:\n        package = calling_package()\n    package_dir = '.'.join([package, directory])\n    images = []\n    for i in resource_listdir(package, directory):\n        if i.startswith('__') or i.endswith('.egg-info'):\n            continue\n        fname = resource_filename(package_dir, i)\n        if resource_isdir(package_dir, i):\n            images.extend(image_resources(package_dir, i))\n        elif what(fname):\n            images.append(fname)\n    return images",
    "docstring": "Returns all images under the directory relative to a package path. If no directory or package is specified then the\n    resources module of the calling package will be used. Images are recursively discovered.\n\n    :param package: package name in dotted format.\n    :param directory: path relative to package path of the resources directory.\n    :return: a list of images under the specified resources path."
  },
  {
    "code": "def async_save_result(self):\n        if hasattr(self, \"_async_future\") and self._async_future.done():\n            self._async_future.result()\n            return True\n        else:\n            return False",
    "docstring": "Retrieves the result of this subject's asynchronous save.\n\n        - Returns `True` if the subject was saved successfully.\n        - Raises `concurrent.futures.CancelledError` if the save was cancelled.\n        - If the save failed, raises the relevant exception.\n        - Returns `False` if the subject hasn't finished saving or if the\n          subject has not been queued for asynchronous save."
  },
  {
    "code": "def before_sample(analysis_request):\n    if not analysis_request.getDateSampled():\n        analysis_request.setDateSampled(DateTime())\n    if not analysis_request.getSampler():\n        analysis_request.setSampler(api.get_current_user().id)",
    "docstring": "Method triggered before \"sample\" transition for the Analysis Request\n    passed in is performed"
  },
  {
    "code": "def _init_from_file(self, filename):\n        if not filename.endswith(\"detx\"):\n            raise NotImplementedError('Only the detx format is supported.')\n        self._open_file(filename)\n        self._extract_comments()\n        self._parse_header()\n        self._parse_doms()\n        self._det_file.close()",
    "docstring": "Create detector from detx file."
  },
  {
    "code": "def create_pattern(cls, userdata):\n        empty = cls.create_empty(None)\n        userdata_dict = cls.normalize(empty, userdata)\n        return Userdata(userdata_dict)",
    "docstring": "Create a user data instance with all values the same."
  },
  {
    "code": "def average(old_avg, current_value, count):\n    if old_avg is None:\n        return current_value\n    return (float(old_avg) * count + current_value) / (count + 1)",
    "docstring": "Calculate the average. Count must start with 0\n\n    >>> average(None, 3.23, 0)\n    3.23\n    >>> average(0, 1, 0)\n    1.0\n    >>> average(2.5, 5, 4)\n    3.0"
  },
  {
    "code": "def createDocument(self, nsuri, qname, doctype=None):\n        impl = xml.dom.minidom.getDOMImplementation()\n        return impl.createDocument(nsuri, qname, doctype)",
    "docstring": "Create a new writable DOM document object."
  },
  {
    "code": "def name(self) -> str:\n        if self.is_platform:\n            if self._data[\"publicCode\"]:\n                return self._data['name'] + \" Platform \" + \\\n                       self._data[\"publicCode\"]\n            else:\n                return self._data['name'] + \" Platform \" + \\\n                       self.place_id.split(':')[-1]\n        else:\n            return self._data['name']",
    "docstring": "Friendly name for the stop place or platform"
  },
  {
    "code": "def add_summary_stats_to_table(table_in, table_out, colnames):\n    for col in colnames:\n        col_in = table_in[col]\n        stats = collect_summary_stats(col_in.data)\n        for k, v in stats.items():\n            out_name = \"%s_%s\" % (col, k)\n            col_out = Column(data=np.vstack(\n                [v]), name=out_name, dtype=col_in.dtype, shape=v.shape, unit=col_in.unit)\n            table_out.add_column(col_out)",
    "docstring": "Collect summary statisitics from an input table and add them to an output table\n\n     Parameters\n    ----------\n\n    table_in : `astropy.table.Table`\n        Table with the input data.\n\n    table_out : `astropy.table.Table`\n        Table with the output data.\n\n    colnames : list\n        List of the column names to get summary statistics for."
  },
  {
    "code": "def _fast_dataset(\n    variables: 'OrderedDict[Any, Variable]',\n    coord_variables: Mapping[Any, Variable],\n) -> 'Dataset':\n    from .dataset import Dataset\n    variables.update(coord_variables)\n    coord_names = set(coord_variables)\n    return Dataset._from_vars_and_coord_names(variables, coord_names)",
    "docstring": "Create a dataset as quickly as possible.\n\n    Beware: the `variables` OrderedDict is modified INPLACE."
  },
  {
    "code": "def _hydrate_pivot_relation(self, models):\n        for model in models:\n            pivot = self.new_existing_pivot(self._clean_pivot_attributes(model))\n            model.set_relation(\"pivot\", pivot)",
    "docstring": "Hydrate the pivot table relationship on the models.\n\n        :type models: list"
  },
  {
    "code": "def parse_mysql_cnf(dbinfo):\n    read_default_file = dbinfo.get('OPTIONS', {}).get('read_default_file')\n    if read_default_file:\n        config = configparser.RawConfigParser({\n            'user': '',\n            'password': '',\n            'database': '',\n            'host': '',\n            'port': '',\n            'socket': '',\n        })\n        import os\n        config.read(os.path.expanduser(read_default_file))\n        try:\n            user = config.get('client', 'user')\n            password = config.get('client', 'password')\n            database_name = config.get('client', 'database')\n            database_host = config.get('client', 'host')\n            database_port = config.get('client', 'port')\n            socket = config.get('client', 'socket')\n            if database_host == 'localhost' and socket:\n                database_host = socket\n            return user, password, database_name, database_host, database_port\n        except configparser.NoSectionError:\n            pass\n    return '', '', '', '', ''",
    "docstring": "Attempt to parse mysql database config file for connection settings.\n    Ideally we would hook into django's code to do this, but read_default_file is handled by the mysql C libs\n    so we have to emulate the behaviour\n\n    Settings that are missing will return ''\n    returns (user, password, database_name, database_host, database_port)"
  },
  {
    "code": "def gen_csv(sc, filename):\n    datafile = open(filename, 'wb')\n    csvfile = csv.writer(datafile)\n    csvfile.writerow(['Software Package Name', 'Count'])\n    debug.write('Generating %s: ' % filename)\n    fparams = {'fobj': csvfile}\n    sc.query('listsoftware', func=writer, func_params=fparams)\n    debug.write('\\n')\n    datafile.close()",
    "docstring": "csv SecurityCenterObj, EmailAddress"
  },
  {
    "code": "def _convert_addrinfo(cls, results: List[tuple]) -> Iterable[AddressInfo]:\n        for result in results:\n            family = result[0]\n            address = result[4]\n            ip_address = address[0]\n            if family == socket.AF_INET6:\n                flow_info = address[2]\n                control_id = address[3]\n            else:\n                flow_info = None\n                control_id = None\n            yield AddressInfo(ip_address, family, flow_info, control_id)",
    "docstring": "Convert the result list to address info."
  },
  {
    "code": "def devno_alloc(self):\n        devno_int = self._devno_pool.alloc()\n        devno = \"{:04X}\".format(devno_int)\n        return devno",
    "docstring": "Allocates a device number unique to this partition, in the range of\n        0x8000 to 0xFFFF.\n\n        Returns:\n          string: The device number as four hexadecimal digits in upper case.\n\n        Raises:\n          ValueError: No more device numbers available in that range."
  },
  {
    "code": "def match_filter(self, idx_list, pattern, dict_type=False,\n                     dict_key='name'):\n        if dict_type is False:\n            return self._return_deque([\n                obj for obj in idx_list\n                if re.search(pattern, obj)\n            ])\n        elif dict_type is True:\n            return self._return_deque([\n                obj for obj in idx_list\n                if re.search(pattern, obj.get(dict_key))\n            ])\n        else:\n            return self._return_deque()",
    "docstring": "Return Matched items in indexed files.\n\n        :param idx_list:\n        :return list"
  },
  {
    "code": "def has_duplicate_max(x):\n    if not isinstance(x, (np.ndarray, pd.Series)):\n        x = np.asarray(x)\n    return np.sum(x == np.max(x)) >= 2",
    "docstring": "Checks if the maximum value of x is observed more than once\n\n    :param x: the time series to calculate the feature of\n    :type x: numpy.ndarray\n    :return: the value of this feature\n    :return type: bool"
  },
  {
    "code": "def StartCli(args, adb_commands, extra=None, **device_kwargs):\n    try:\n        dev = adb_commands()\n        dev.ConnectDevice(port_path=args.port_path, serial=args.serial, default_timeout_ms=args.timeout_ms,\n                          **device_kwargs)\n    except usb_exceptions.DeviceNotFoundError as e:\n        print('No device found: {}'.format(e), file=sys.stderr)\n        return 1\n    except usb_exceptions.CommonUsbError as e:\n        print('Could not connect to device: {}'.format(e), file=sys.stderr)\n        return 1\n    try:\n        return _RunMethod(dev, args, extra or {})\n    except Exception as e:\n        sys.stdout.write(str(e))\n        return 1\n    finally:\n        dev.Close()",
    "docstring": "Starts a common CLI interface for this usb path and protocol."
  },
  {
    "code": "def validate_obj(keys, obj):\n    msg = ''\n    for k in keys:\n        if isinstance(k, str):\n            if k not in obj or (not isinstance(obj[k], list) and not obj[k]):\n                if msg:\n                    msg = \"%s,\" % msg\n                msg = \"%s%s\" % (msg, k)\n        elif isinstance(k, list):\n            found = False\n            for k_a in k:\n                if k_a in obj:\n                    found = True\n            if not found:\n                if msg:\n                    msg = \"%s,\" % msg\n                msg = \"%s(%s\" % (msg, ','.join(k))\n    if msg:\n        msg = \"%s missing\" % msg\n    return msg",
    "docstring": "Super simple \"object\" validation."
  },
  {
    "code": "def guess(cls, sample):\n        if isinstance(sample, TypeEngine):\n            return sample\n        if isinstance(sample, bool):\n            return cls.boolean\n        elif isinstance(sample, int):\n            return cls.integer\n        elif isinstance(sample, float):\n            return cls.float\n        elif isinstance(sample, datetime):\n            return cls.datetime\n        elif isinstance(sample, date):\n            return cls.date\n        return cls.text",
    "docstring": "Given a single sample, guess the column type for the field.\n\n        If the sample is an instance of an SQLAlchemy type, the type will be\n        used instead."
  },
  {
    "code": "def _get_file_paths(cur):\n    out = []\n    if isinstance(cur, (list, tuple)):\n        for x in cur:\n            new = _get_file_paths(x)\n            if new:\n                out.extend(new)\n    elif isinstance(cur, dict):\n        if \"class\" in cur:\n            out.append(cur[\"path\"])\n        else:\n            for k, v in cur.items():\n                new = _get_file_paths(v)\n                if new:\n                    out.extend(new)\n    return out",
    "docstring": "Retrieve a list of file paths, recursively traversing the"
  },
  {
    "code": "def hdel(self, key, *fields):\n        if not fields:\n            future = concurrent.TracebackFuture()\n            future.set_result(0)\n        else:\n            future = self._execute([b'HDEL', key] + list(fields))\n        return future",
    "docstring": "Remove the specified fields from the hash stored at `key`.\n\n        Specified fields that do not exist within this hash are ignored.\n        If `key` does not exist, it is treated as an empty hash and this\n        command returns zero.\n\n        :param key: The key of the hash\n        :type key: :class:`str`, :class:`bytes`\n        :param fields: iterable of field names to retrieve\n        :returns: the number of fields that were removed from the hash,\n            not including specified by non-existing fields.\n        :rtype: int"
  },
  {
    "code": "def get_too_few_non_zero_degree_day_warning(\n    model_type, balance_point, degree_day_type, degree_days, minimum_non_zero\n):\n    warnings = []\n    n_non_zero = int((degree_days > 0).sum())\n    if n_non_zero < minimum_non_zero:\n        warnings.append(\n            EEMeterWarning(\n                qualified_name=(\n                    \"eemeter.caltrack_daily.{model_type}.too_few_non_zero_{degree_day_type}\".format(\n                        model_type=model_type, degree_day_type=degree_day_type\n                    )\n                ),\n                description=(\n                    \"Number of non-zero daily {degree_day_type} values below accepted minimum.\"\n                    \" Candidate fit not attempted.\".format(\n                        degree_day_type=degree_day_type.upper()\n                    )\n                ),\n                data={\n                    \"n_non_zero_{degree_day_type}\".format(\n                        degree_day_type=degree_day_type\n                    ): n_non_zero,\n                    \"minimum_non_zero_{degree_day_type}\".format(\n                        degree_day_type=degree_day_type\n                    ): minimum_non_zero,\n                    \"{degree_day_type}_balance_point\".format(\n                        degree_day_type=degree_day_type\n                    ): balance_point,\n                },\n            )\n        )\n    return warnings",
    "docstring": "Return an empty list or a single warning wrapped in a list regarding\n    non-zero degree days for a set of degree days.\n\n    Parameters\n    ----------\n    model_type : :any:`str`\n        Model type (e.g., ``'cdd_hdd'``).\n    balance_point : :any:`float`\n        The balance point in question.\n    degree_day_type : :any:`str`\n        The type of degree days (``'cdd'`` or ``'hdd'``).\n    degree_days : :any:`pandas.Series`\n        A series of degree day values.\n    minimum_non_zero : :any:`int`\n        Minimum allowable number of non-zero degree day values.\n\n    Returns\n    -------\n    warnings : :any:`list` of :any:`eemeter.EEMeterWarning`\n        Empty list or list of single warning."
  },
  {
    "code": "def docid(url, encoding='ascii'):\n    if not isinstance(url, bytes):\n        url = url.encode(encoding)\n    parser = _URL_PARSER\n    idx = 0\n    for _c in url:\n        if _c not in _HEX:\n            if not (_c == _SYM_MINUS and (idx == _DOMAINID_LENGTH\n                                          or idx == _HOSTID_LENGTH + 1)):\n                return parser.parse(url, idx)\n        idx += 1\n        if idx > 4:\n            break\n    _l = len(url)\n    if _l == _DOCID_LENGTH:\n        parser = _DOCID_PARSER\n    elif _l == _READABLE_DOCID_LENGTH \\\n            and url[_DOMAINID_LENGTH] == _SYM_MINUS \\\n            and url[_HOSTID_LENGTH + 1] == _SYM_MINUS:\n        parser = _R_DOCID_PARSER\n    else:\n        parser = _PARSER\n    return parser.parse(url, idx)",
    "docstring": "Get DocID from URL.\n\n    DocID generation depends on bytes of the URL string.\n    So, if non-ascii charactors in the URL, encoding should\n    be considered properly.\n\n    Args:\n        url (str or bytes): Pre-encoded bytes or string will be encoded with the\n            'encoding' argument.\n        encoding (str, optional): Defaults to 'ascii'. Used to encode url argument\n            if it is not pre-encoded into bytes.\n\n    Returns:\n        DocID: The DocID object.\n\n    Examples:\n\n        >>> from os_docid import docid\n\n        >>> docid('http://www.google.com/')\n        1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd\n\n        >>> docid('1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd')\n        1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd\n\n        >>> docid('1d5920f4b44b27a8ed646a3334ca891fff90821feeb2b02a33a6f9fc8e5f3fcd')\n        1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd\n\n        >>> docid('abc')  \n        NotImplementedError: Not supported data format"
  },
  {
    "code": "def Element(self, elem, **params):\n        res = self.__call__(deepcopy(elem), **params)\n        if len(res) > 0: \n            return res[0]\n        else:\n            return None",
    "docstring": "Ensure that the input element is immutable by the transformation. Returns a single element."
  },
  {
    "code": "def _compute_a22_factor(self, imt):\n        if imt.name == 'PGV':\n            return 0.0\n        period = imt.period\n        if period < 2.0:\n            return 0.0\n        else:\n            return 0.0625 * (period - 2.0)",
    "docstring": "Compute and return the a22 factor, equation 20, page 80."
  },
  {
    "code": "async def executescript(self, sql_script: str) -> Cursor:\n        cursor = await self._execute(self._conn.executescript, sql_script)\n        return Cursor(self, cursor)",
    "docstring": "Helper to create a cursor and execute a user script."
  },
  {
    "code": "def listDatasetParents(self, dataset=''):\n        try:\n            return self.dbsDataset.listDatasetParents(dataset)\n        except dbsException as de:\n            dbsExceptionHandler(de.eCode, de.message, self.logger.exception, de.serverError)\n        except Exception as ex:\n            sError = \"DBSReaderModel/listDatasetParents. %s\\n. Exception trace: \\n %s\" \\\n                    % (ex, traceback.format_exc())\n            dbsExceptionHandler('dbsException-server-error', dbsExceptionCode['dbsException-server-error'], self.logger.exception, sError)",
    "docstring": "API to list A datasets parents in DBS.\n\n        :param dataset: dataset (Required)\n        :type dataset: str\n        :returns: List of dictionaries containing the following keys (this_dataset, parent_dataset_id, parent_dataset)\n        :rtype: list of dicts"
  },
  {
    "code": "def parse_entry(source, loc, tokens):\n    type_ = tokens[1].lower()\n    entry_type = structures.TypeRegistry.get_type(type_)\n    if entry_type is None or not issubclass(entry_type, structures.Entry):\n        raise exceptions.UnsupportedEntryType(\n                \"%s is not a supported entry type\" % type_\n            )\n    new_entry = entry_type()\n    new_entry.name = tokens[3]\n    for key, value in [t for t in tokens[4:-1] if t != ',']:\n        new_entry[key] = value\n    return new_entry",
    "docstring": "Converts the tokens of an entry into an Entry instance. If no applicable\n    type is available, an UnsupportedEntryType exception is raised."
  },
  {
    "code": "def send_request(req=None, method=None, requires_response=True):\n    if req is None:\n        return functools.partial(send_request, method=method,\n                                 requires_response=requires_response)\n    @functools.wraps(req)\n    def wrapper(self, *args, **kwargs):\n        params = req(self, *args, **kwargs)\n        _id = self.send(method, params, requires_response)\n        return _id\n    wrapper._sends = method\n    return wrapper",
    "docstring": "Call function req and then send its results via ZMQ."
  },
  {
    "code": "def _parse_document(document: Path, system: System = None, profile=EProfile.FULL):\n        logger.debug('parse document: {0}'.format(document))\n        stream = FileStream(str(document), encoding='utf-8')\n        system = FileSystem._parse_stream(stream, system, document, profile)\n        FileSystem.merge_annotations(system, document.stripext() + '.yaml')\n        return system",
    "docstring": "Parses a document and returns the resulting domain system\n\n        :param path: document path to parse\n        :param system: system to be used (optional)"
  },
  {
    "code": "def rcts(self, command, *args, **kwargs):\r\n        cls = self.__class__\r\n        name = kwargs.pop('name','')\r\n        date = kwargs.pop('date',None)\r\n        data = kwargs.pop('data',None)\r\n        kwargs.pop('bycolumn',None)\r\n        ts  = cls(name=name,date=date,data=data)\r\n        ts._ts = self.rc(command, *args, **kwargs)\r\n        return ts",
    "docstring": "General function for applying a rolling R function to a timeserie"
  },
  {
    "code": "def update_indel(self, nucmer_snp):\n        new_variant = Variant(nucmer_snp)\n        if self.var_type not in [INS, DEL] \\\n          or self.var_type != new_variant.var_type \\\n          or self.qry_name != new_variant.qry_name \\\n          or self.ref_name != new_variant.ref_name \\\n          or self.reverse != new_variant.reverse:\n            return False\n        if self.var_type == INS \\\n          and self.ref_start == new_variant.ref_start \\\n          and self.qry_end + 1 == new_variant.qry_start:\n            self.qry_base += new_variant.qry_base\n            self.qry_end += 1\n            return True\n        if self.var_type == DEL \\\n          and self.qry_start == new_variant.qry_start \\\n          and self.ref_end + 1 == new_variant.ref_start:\n            self.ref_base += new_variant.ref_base\n            self.ref_end += 1\n            return True\n        return False",
    "docstring": "Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False"
  },
  {
    "code": "def save(self, output=''):\n        self.file = self._get_output_file(output)\n        with open(self.file, 'w', encoding='utf-8') as f:\n            self.write(f)",
    "docstring": "Save the document.\n        If no output is provided the file will be saved in the same location. Otherwise output\n        can determine a target directory or file."
  },
  {
    "code": "def _write_incron_lines(user, lines):\n    if user == 'system':\n        ret = {}\n        ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines))\n        return ret\n    else:\n        path = salt.utils.files.mkstemp()\n        with salt.utils.files.fopen(path, 'wb') as fp_:\n            fp_.writelines(salt.utils.data.encode(lines))\n        if __grains__['os_family'] == 'Solaris' and user != \"root\":\n            __salt__['cmd.run']('chown {0} {1}'.format(user, path), python_shell=False)\n        ret = __salt__['cmd.run_all'](_get_incron_cmdstr(path), runas=user, python_shell=False)\n        os.remove(path)\n        return ret",
    "docstring": "Takes a list of lines to be committed to a user's incrontab and writes it"
  },
  {
    "code": "def collections(self):\n        if self.cache:\n            return self.cache.get(\n                self.app.config['COLLECTIONS_CACHE_KEY'])",
    "docstring": "Get list of collections."
  },
  {
    "code": "def packet_get_samples_per_frame(data, fs):\n    data_pointer = ctypes.c_char_p(data)\n    result = _packet_get_nb_frames(data_pointer, ctypes.c_int(fs))\n    if result < 0:\n        raise OpusError(result)\n    return result",
    "docstring": "Gets the number of samples per frame from an Opus packet"
  },
  {
    "code": "def dict_hist(item_list, weight_list=None, ordered=False, labels=None):\n    r\n    if labels is None:\n        hist_ = defaultdict(int)\n    else:\n        hist_ = {k: 0 for k in labels}\n    if weight_list is None:\n        for item in item_list:\n            hist_[item] += 1\n    else:\n        for item, weight in zip(item_list, weight_list):\n            hist_[item] += weight\n    if ordered:\n        getval = op.itemgetter(1)\n        key_order = [key for (key, value) in sorted(hist_.items(), key=getval)]\n        hist_ = order_dict_by(hist_, key_order)\n    return hist_",
    "docstring": "r\"\"\"\n    Builds a histogram of items in item_list\n\n    Args:\n        item_list (list): list with hashable items (usually containing duplicates)\n\n    Returns:\n        dict : dictionary where the keys are items in item_list, and the values\n          are the number of times the item appears in item_list.\n\n    CommandLine:\n        python -m utool.util_dict --test-dict_hist\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_dict import *  # NOQA\n        >>> import utool as ut\n        >>> item_list = [1, 2, 39, 900, 1232, 900, 1232, 2, 2, 2, 900]\n        >>> hist_ = dict_hist(item_list)\n        >>> result = ut.repr2(hist_)\n        >>> print(result)\n        {1: 1, 2: 4, 39: 1, 900: 3, 1232: 2}"
  },
  {
    "code": "def updatePassword(self,\n                       user,\n                       currentPassword,\n                       newPassword):\n        return self.__post('/api/updatePassword',\n                           data={\n                               'user': user,\n                               'currentPassword': currentPassword,\n                               'newPassword': newPassword\n                           })",
    "docstring": "Change the password of a user."
  },
  {
    "code": "def parseStr(self, html):\n        self.reset()\n        if isinstance(html, bytes):\n            self.feed(html.decode(self.encoding))\n        else:\n            self.feed(html)",
    "docstring": "parseStr - Parses a string and creates the DOM tree and indexes.\n\n                @param html <str> - valid HTML"
  },
  {
    "code": "def delete(self, ids):\n        url = build_uri_with_ids('api/v3/networkv4/%s/', ids)\n        return super(ApiNetworkIPv4, self).delete(url)",
    "docstring": "Method to delete network-ipv4's by their ids\n\n        :param ids: Identifiers of network-ipv4's\n        :return: None"
  },
  {
    "code": "def get_nadir(self, channel=0) -> tuple:\n        if isinstance(channel, int):\n            channel_index = channel\n        elif isinstance(channel, str):\n            channel_index = self.channel_names.index(channel)\n        else:\n            raise TypeError(\"channel: expected {int, str}, got %s\" % type(channel))\n        channel = self.channels[channel_index]\n        idx = channel.argmin()\n        return tuple(a[idx] for a in self._axes)",
    "docstring": "Get the coordinates, in units, of the minimum in a channel.\n\n        Parameters\n        ----------\n        channel : int or str (optional)\n            Channel. Default is 0.\n\n        Returns\n        -------\n        generator of numbers\n            Coordinates in units for each axis."
  },
  {
    "code": "def _AnalyzeKeywords(self, keywords):\n    start_time = rdfvalue.RDFDatetime.Now() - rdfvalue.Duration(\"180d\")\n    filtered_keywords = []\n    for k in keywords:\n      if k.startswith(self.START_TIME_PREFIX):\n        try:\n          start_time = rdfvalue.RDFDatetime.FromHumanReadable(\n              k[self.START_TIME_PREFIX_LEN:])\n        except ValueError:\n          pass\n      else:\n        filtered_keywords.append(k)\n    if not filtered_keywords:\n      filtered_keywords.append(\".\")\n    return start_time, filtered_keywords",
    "docstring": "Extracts a start time from a list of keywords if present."
  },
  {
    "code": "def meta_request(func):\n    def inner(self, resource, *args, **kwargs):\n        serialize_response = kwargs.pop('serialize', True)\n        try:\n            resp = func(self, resource, *args, **kwargs)\n        except ApiException as e:\n            raise api_exception(e)\n        if serialize_response:\n            return serialize(resource, resp)\n        return resp\n    return inner",
    "docstring": "Handles parsing response structure and translating API Exceptions"
  },
  {
    "code": "def __get_last_update_time():\n    now = datetime.datetime.utcnow()\n    first_tuesday = __get_first_tuesday(now)\n    if first_tuesday < now:\n        return first_tuesday\n    else:\n        first_of_month = datetime.datetime(now.year, now.month, 1)\n        last_month = first_of_month + datetime.timedelta(days=-1)\n        return __get_first_tuesday(last_month)",
    "docstring": "Returns last FTP site update time"
  },
  {
    "code": "def _jit_pairwise_distances(pos1, pos2):\n        n1 = pos1.shape[0]\n        n2 = pos2.shape[0]\n        D = np.empty((n1, n2))\n        for i in range(n1):\n            for j in range(n2):\n                D[i, j] = np.sqrt(((pos1[i] - pos2[j])**2).sum())\n        return D",
    "docstring": "Optimized function for calculating the distance between each pair\n        of points in positions1 and positions2.\n\n        Does use python mode as fallback, if a scalar and not an array is\n        given."
  },
  {
    "code": "def maxDepth(self, currentDepth=0):\n        if not any((self.left, self.right)):\n            return currentDepth\n        result = 0\n        for child in (self.left, self.right):\n            if child:\n                result = max(result, child.maxDepth(currentDepth + 1))\n        return result",
    "docstring": "Compute the depth of the longest branch of the tree"
  },
  {
    "code": "def add_path(tdict, path):\n    t = tdict\n    for step in path[:-2]:\n        try:\n            t = t[step]\n        except KeyError:\n            t[step] = {}\n            t = t[step]\n    t[path[-2]] = path[-1]\n    return tdict",
    "docstring": "Create or extend an argument tree `tdict` from `path`.\n\n    :param tdict: a dictionary representing a argument tree\n    :param path: a path list\n    :return: a dictionary\n\n    Convert a list of items in a 'path' into a nested dict, where the\n    second to last item becomes the key for the final item. The remaining\n    items in the path become keys in the nested dict around that final pair\n    of items.\n\n    For example, for input values of:\n        tdict={}\n        path = ['assertion', 'subject', 'subject_confirmation',\n                'method', 'urn:oasis:names:tc:SAML:2.0:cm:bearer']\n\n        Returns an output value of:\n           {'assertion': {'subject': {'subject_confirmation':\n                         {'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'}}}}\n\n    Another example, this time with a non-empty tdict input:\n\n        tdict={'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'},\n        path=['subject_confirmation_data', 'in_response_to', '_012345']\n\n        Returns an output value of:\n            {'subject_confirmation_data': {'in_response_to': '_012345'},\n             'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'}"
  },
  {
    "code": "def find_one_by_id(self, _id):\n        document = (yield self.collection.find_one({\"_id\": ObjectId(_id)}))\n        raise Return(self._obj_cursor_to_dictionary(document))",
    "docstring": "Find a single document by id\n\n        :param str _id: BSON string repreentation of the Id\n        :return: a signle object\n        :rtype: dict"
  },
  {
    "code": "def dataReceived(self, data):\n        self.connection._iobuf.write(data)\n        self.connection.handle_read()",
    "docstring": "Callback function that is called when data has been received\n        on the connection.\n\n        Reaches back to the Connection object and queues the data for\n        processing."
  },
  {
    "code": "def suggest(self, *replies):\n        chips = []\n        for r in replies:\n            chips.append({\"title\": r})\n        self._messages.append(\n            {\"platform\": \"ACTIONS_ON_GOOGLE\", \"suggestions\": {\"suggestions\": chips}}\n        )\n        return self",
    "docstring": "Use suggestion chips to hint at responses to continue or pivot the conversation"
  },
  {
    "code": "def generate_look_up_table():\n    poly = 0xA001\n    table = []\n    for index in range(256):\n        data = index << 1\n        crc = 0\n        for _ in range(8, 0, -1):\n            data >>= 1\n            if (data ^ crc) & 0x0001:\n                crc = (crc >> 1) ^ poly\n            else:\n                crc >>= 1\n        table.append(crc)\n    return table",
    "docstring": "Generate look up table.\n\n    :return: List"
  },
  {
    "code": "def get_hash(name, password=None):\n    if '.p12' in name[-4:]:\n        cmd = 'openssl pkcs12 -in {0} -passin pass:{1} -passout pass:{1}'.format(name, password)\n    else:\n        cmd = 'security find-certificate -c \"{0}\" -m -p'.format(name)\n    out = __salt__['cmd.run'](cmd)\n    matches = re.search('-----BEGIN CERTIFICATE-----(.*)-----END CERTIFICATE-----', out, re.DOTALL | re.MULTILINE)\n    if matches:\n        return matches.group(1)\n    else:\n        return False",
    "docstring": "Returns the hash of a certificate in the keychain.\n\n    name\n        The name of the certificate (which you can get from keychain.get_friendly_name) or the\n        location of a p12 file.\n\n    password\n        The password that is used in the certificate. Only required if your passing a p12 file.\n        Note: This will be outputted to logs\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' keychain.get_hash /tmp/test.p12 test123"
  },
  {
    "code": "def url_to_tile(url):\n        info = url.strip('/').split('/')\n        name = ''.join(info[-7: -4])\n        date = '-'.join(info[-4: -1])\n        return name, date, int(info[-1])",
    "docstring": "Extracts tile name, date and AWS index from tile url on AWS.\n\n        :param url: class input parameter 'metafiles'\n        :type url: str\n        :return: Name of tile, date and AWS index which uniquely identifies tile on AWS\n        :rtype: (str, str, int)"
  },
  {
    "code": "def remove_xml_element_string(name, content):\n    ET.register_namespace(\"\", \"http://soap.sforce.com/2006/04/metadata\")\n    tree = ET.fromstring(content)\n    tree = remove_xml_element(name, tree)\n    clean_content = ET.tostring(tree, encoding=UTF8)\n    return clean_content",
    "docstring": "Remove XML elements from a string"
  },
  {
    "code": "def get_processor_description(self, cpu_id):\n        if not isinstance(cpu_id, baseinteger):\n            raise TypeError(\"cpu_id can only be an instance of type baseinteger\")\n        description = self._call(\"getProcessorDescription\",\n                     in_p=[cpu_id])\n        return description",
    "docstring": "Query the model string of a specified host CPU.\n\n        in cpu_id of type int\n            Identifier of the CPU.\n            \n            The current implementation might not necessarily return the\n            description for this exact CPU.\n\n        return description of type str\n            Model string. An empty string is returned if value is not known or\n            @a cpuId is invalid."
  },
  {
    "code": "def open_gif(self, filename):\n        if filename[-3:] != 'gif':\n            raise Exception('Unsupported filetype.  Must end in .gif')\n        if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename):\n            filename = os.path.join(vtki.FIGURE_PATH, filename)\n        self._gif_filename = os.path.abspath(filename)\n        self.mwriter = imageio.get_writer(filename, mode='I')",
    "docstring": "Open a gif file.\n\n        Parameters\n        ----------\n        filename : str\n            Filename of the gif to open.  Filename must end in gif."
  },
  {
    "code": "def set_func(self, name, func):\n        self.func_name = name\n        self.func = func",
    "docstring": "Set the processing function to use for this node.\n\n        Args:\n            name (str): The name of the function to use.  This is\n                just stored for reference in case we need to serialize\n                the node later.\n            func (callable): A function that is called to process inputs\n                for this node.  It should have the following signature:\n                callable(input1_walker, input2_walker, ...)\n                It should return a list of IOTileReadings that are then pushed into\n                the node's output stream"
  },
  {
    "code": "def fit(self, X):\n        U, V = self.split_matrix(X)\n        self.tau = stats.kendalltau(U, V)[0]\n        self.theta = self.compute_theta()\n        self.check_theta()",
    "docstring": "Fit a model to the data updating the parameters.\n\n        Args:\n            X: `np.ndarray` of shape (,2).\n\n        Return:\n            None"
  },
  {
    "code": "def set_context_menu(self, context_menu):\n        self.context_menu = context_menu\n        self.context_menu.tree_view = self\n        self.context_menu.init_actions()\n        for action in self.context_menu.actions():\n            self.addAction(action)",
    "docstring": "Sets the context menu of the tree view.\n\n        :param context_menu: QMenu"
  },
  {
    "code": "def _getSyntaxByLanguageName(self, syntaxName):\n        xmlFileName = self._syntaxNameToXmlFileName[syntaxName]\n        return self._getSyntaxByXmlFileName(xmlFileName)",
    "docstring": "Get syntax by its name. Name is defined in the xml file"
  },
  {
    "code": "def get_voms_proxy_user():\n    out = _voms_proxy_info([\"--identity\"])[1].strip()\n    try:\n        return re.match(r\".*\\/CN\\=([^\\/]+).*\", out.strip()).group(1)\n    except:\n        raise Exception(\"no valid identity found in voms proxy: {}\".format(out))",
    "docstring": "Returns the owner of the voms proxy."
  },
  {
    "code": "def EndVector(self, vectorNumElems):\n        self.assertNested()\n        self.nested = False\n        self.PlaceUOffsetT(vectorNumElems)\n        return self.Offset()",
    "docstring": "EndVector writes data necessary to finish vector construction."
  },
  {
    "code": "def page_not_found(request, template_name=\"errors/404.html\"):\n    context = {\n        \"STATIC_URL\": settings.STATIC_URL,\n        \"request_path\": request.path,\n    }\n    t = get_template(template_name)\n    return HttpResponseNotFound(t.render(context, request))",
    "docstring": "Mimics Django's 404 handler but with a different template path."
  },
  {
    "code": "def validate_unwrap(self, value):\n        if not isinstance(value, list):\n            self._fail_validation_type(value, list)\n        for value_dict in value:\n            if not isinstance(value_dict, dict):\n                cause = BadValueException('', value_dict, 'Values in a KVField list must be dicts')\n                self._fail_validation(value, 'Values in a KVField list must be dicts', cause=cause)\n            k = value_dict.get('k')\n            v = value_dict.get('v')\n            if k is None:\n                self._fail_validation(value, 'Value had None for a key')\n            try:\n                self.key_type.validate_unwrap(k)\n            except BadValueException as bve:\n                self._fail_validation(value, 'Bad value for KVField key %s' % k, cause=bve)\n            try:\n                self.value_type.validate_unwrap(v)\n            except BadValueException as bve:\n                self._fail_validation(value, 'Bad value for KFVield value %s' % k, cause=bve)\n        return True",
    "docstring": "Expects a list of dictionaries with ``k`` and ``v`` set to the\n            keys and values that will be unwrapped into the output python\n            dictionary should have"
  },
  {
    "code": "def reverse_hash(hash, hex_format=True):\n    if not hex_format:\n        hash = hexlify(hash)\n    return \"\".join(reversed([hash[i:i+2] for i in range(0, len(hash), 2)]))",
    "docstring": "hash is in hex or binary format"
  },
  {
    "code": "def pipeline_counter(self):\n        if 'pipeline_counter' in self.data and self.data.pipeline_counter:\n            return self.data.get('pipeline_counter')\n        elif self.stage.pipeline is not None:\n            return self.stage.pipeline.data.counter\n        else:\n            return self.stage.data.pipeline_counter",
    "docstring": "Get pipeline counter of current job instance.\n\n        Because instantiating job instance could be performed in different ways and those return different results,\n        we have to check where from to get counter of the pipeline.\n\n        :return: pipeline counter."
  },
  {
    "code": "def _get_arch():\n    try:\n        si = GetNativeSystemInfo()\n    except Exception:\n        si = GetSystemInfo()\n    try:\n        return _arch_map[si.id.w.wProcessorArchitecture]\n    except KeyError:\n        return ARCH_UNKNOWN",
    "docstring": "Determines the current processor architecture.\n\n    @rtype: str\n    @return:\n        On error, returns:\n\n         - L{ARCH_UNKNOWN} (C{\"unknown\"}) meaning the architecture could not be detected or is not known to WinAppDbg.\n\n        On success, returns one of the following values:\n\n         - L{ARCH_I386} (C{\"i386\"}) for Intel 32-bit x86 processor or compatible.\n         - L{ARCH_AMD64} (C{\"amd64\"}) for Intel 64-bit x86_64 processor or compatible.\n\n        May also return one of the following values if you get both Python and\n        WinAppDbg to work in such machines... let me know if you do! :)\n\n         - L{ARCH_MIPS} (C{\"mips\"}) for MIPS compatible processors.\n         - L{ARCH_ALPHA} (C{\"alpha\"}) for Alpha processors.\n         - L{ARCH_PPC} (C{\"ppc\"}) for PowerPC compatible processors.\n         - L{ARCH_SHX} (C{\"shx\"}) for Hitachi SH processors.\n         - L{ARCH_ARM} (C{\"arm\"}) for ARM compatible processors.\n         - L{ARCH_IA64} (C{\"ia64\"}) for Intel Itanium processor or compatible.\n         - L{ARCH_ALPHA64} (C{\"alpha64\"}) for Alpha64 processors.\n         - L{ARCH_MSIL} (C{\"msil\"}) for the .NET virtual machine.\n         - L{ARCH_SPARC} (C{\"sparc\"}) for Sun Sparc processors.\n\n        Probably IronPython returns C{ARCH_MSIL} but I haven't tried it. Python\n        on Windows CE and Windows Mobile should return C{ARCH_ARM}. Python on\n        Solaris using Wine would return C{ARCH_SPARC}. Python in an Itanium\n        machine should return C{ARCH_IA64} both on Wine and proper Windows.\n        All other values should only be returned on Linux using Wine."
  },
  {
    "code": "def _execute_single_level_task(self):\n        self.log(u\"Executing single level task...\")\n        try:\n            self._step_begin(u\"extract MFCC real wave\")\n            real_wave_mfcc = self._extract_mfcc(\n                file_path=self.task.audio_file_path_absolute,\n                file_format=None,\n            )\n            self._step_end()\n            self._step_begin(u\"compute head tail\")\n            (head_length, process_length, tail_length) = self._compute_head_process_tail(real_wave_mfcc)\n            real_wave_mfcc.set_head_middle_tail(head_length, process_length, tail_length)\n            self._step_end()\n            self._set_synthesizer()\n            sync_root = Tree()\n            self._execute_inner(\n                real_wave_mfcc,\n                self.task.text_file,\n                sync_root=sync_root,\n                force_aba_auto=False,\n                log=True,\n                leaf_level=True\n            )\n            self._clear_cache_synthesizer()\n            self._step_begin(u\"create sync map\")\n            self._create_sync_map(sync_root=sync_root)\n            self._step_end()\n            self._step_total()\n            self.log(u\"Executing single level task... done\")\n        except Exception as exc:\n            self._step_failure(exc)",
    "docstring": "Execute a single-level task"
  },
  {
    "code": "def edge_index(self):\n        return dict((edge, index) for index, edge in enumerate(self.edges))",
    "docstring": "A map to look up the index of a edge"
  },
  {
    "code": "def listen(self):\n        with Consumer(self.connection, queues=self.queue, on_message=self.on_message,\n                      auto_declare=False):\n            for _ in eventloop(self.connection, timeout=1, ignore_timeouts=True):\n                    pass",
    "docstring": "Listens to messages"
  },
  {
    "code": "def children(self):\n        if isinstance(self.content, list):\n            return self.content\n        elif isinstance(self.content, Element):\n            return [self.content]\n        else:\n            return []",
    "docstring": "Returns all of the children elements."
  },
  {
    "code": "def get_buckets(self, bucket_type=None, timeout=None):\n        msg_code = riak.pb.messages.MSG_CODE_LIST_BUCKETS_REQ\n        codec = self._get_codec(msg_code)\n        msg = codec.encode_get_buckets(bucket_type,\n                                       timeout, streaming=False)\n        resp_code, resp = self._request(msg, codec)\n        return resp.buckets",
    "docstring": "Serialize bucket listing request and deserialize response"
  },
  {
    "code": "def load_from_file(self, fname=None):\n        fname = fname or psyplot_fname()\n        if fname and os.path.exists(fname):\n            with open(fname) as f:\n                d = yaml.load(f)\n                self.update(d)\n                if (d.get('project.plotters.user') and\n                        'project.plotters' in self):\n                    self['project.plotters'].update(d['project.plotters.user'])",
    "docstring": "Update rcParams from user-defined settings\n\n        This function updates the instance with what is found in `fname`\n\n        Parameters\n        ----------\n        fname: str\n            Path to the yaml configuration file. Possible keys of the\n            dictionary are defined by :data:`config.rcsetup.defaultParams`.\n            If None, the :func:`config.rcsetup.psyplot_fname` function is used.\n\n        See Also\n        --------\n        dump_to_file, psyplot_fname"
  },
  {
    "code": "def similar_email(anon, obj, field, val):\n    return val if 'betterworks.com' in val else '@'.join([anon.faker.user_name(field=field), val.split('@')[-1]])",
    "docstring": "Generate a random email address using the same domain."
  },
  {
    "code": "def vector_is_zero(vector_in, tol=10e-8):\n    if not isinstance(vector_in, (list, tuple)):\n        raise TypeError(\"Input vector must be a list or a tuple\")\n    res = [False for _ in range(len(vector_in))]\n    for idx in range(len(vector_in)):\n        if abs(vector_in[idx]) < tol:\n            res[idx] = True\n    return all(res)",
    "docstring": "Checks if the input vector is a zero vector.\n\n    :param vector_in: input vector\n    :type vector_in: list, tuple\n    :param tol: tolerance value\n    :type tol: float\n    :return: True if the input vector is zero, False otherwise\n    :rtype: bool"
  },
  {
    "code": "def rws_call(ctx, method, default_attr=None):\n    try:\n        response = ctx.obj['RWS'].send_request(method)\n        if ctx.obj['RAW']:\n            result = ctx.obj['RWS'].last_result.text\n        elif default_attr is not None:\n            result = \"\"\n            for item in response:\n                result = result + item.__dict__[default_attr] + \"\\n\"\n        else:\n            result = ctx.obj['RWS'].last_result.text\n        if ctx.obj['OUTPUT']:\n            ctx.obj['OUTPUT'].write(result.encode('utf-8'))\n        else:\n            click.echo(result)\n    except RWSException as e:\n        click.echo(str(e))",
    "docstring": "Make request to RWS"
  },
  {
    "code": "def product_url(self, product):\n        url = 'product/%s' % product\n        return posixpath.join(self.url, url)",
    "docstring": "Return a human-friendly URL for this product.\n\n        :param product: str, eg. \"ceph\"\n        :returns: str, URL"
  },
  {
    "code": "def read_string(buff, byteorder='big'):\r\n    length = read_numeric(USHORT, buff, byteorder)\r\n    return buff.read(length).decode('utf-8')",
    "docstring": "Read a string from a file-like object."
  },
  {
    "code": "def _validate_depedencies(batches):\n    transaction_ids = set()\n    for batch in batches:\n        for txn in batch.transactions:\n            txn_header = TransactionHeader()\n            txn_header.ParseFromString(txn.header)\n            if txn_header.dependencies:\n                unsatisfied_deps = [\n                    id for id in txn_header.dependencies\n                    if id not in transaction_ids\n                ]\n                if unsatisfied_deps:\n                    raise CliException(\n                        'Unsatisfied dependency in given transactions:'\n                        ' {}'.format(unsatisfied_deps))\n            transaction_ids.add(txn.header_signature)",
    "docstring": "Validates the transaction dependencies for the transactions contained\n    within the sequence of batches. Given that all the batches are expected to\n    to be executed for the genesis blocks, it is assumed that any dependent\n    transaction will proceed the depending transaction."
  },
  {
    "code": "def info(self, msg):\n        self._execActions('info', msg)\n        msg = self._execFilters('info', msg)\n        self._processMsg('info', msg)\n        self._sendMsg('info', msg)",
    "docstring": "Log Info Messages"
  },
  {
    "code": "def check(cls, status):\n        assert cls.trigger is not None, 'Invalid ErrorTrap, trigger not set'\n        assert cls.error is not None, 'Invalid ErrorTrap, error not set'\n        if status == cls.trigger:\n            raise cls.error()",
    "docstring": "Checks if a status enum matches the trigger originally set, and\n        if so, raises the appropriate error.\n\n        Args:\n            status (int, enum): A protobuf enum response status to check.\n\n        Raises:\n            AssertionError: If trigger or error were not set.\n            _ApiError: If the statuses don't match. Do not catch. Will be\n                caught automatically and sent back to the client."
  },
  {
    "code": "def set_desired_state(self, state):\n        if state not in self._STATES:\n            raise ValueError(\n                'state must be one of: {0}'.format(\n                    self._STATES\n                ))\n        self._data['desiredState'] = state\n        if self._is_live():\n            self._update('_data', self._client.set_unit_desired_state(self.name, self.desiredState))\n        return self._data['desiredState']",
    "docstring": "Update the desired state of a unit.\n\n        Args:\n            state (str): The desired state for the unit, must be one of ``_STATES``\n\n        Returns:\n            str: The updated state\n\n         Raises:\n            fleet.v1.errors.APIError: Fleet returned a response code >= 400\n            ValueError: An invalid value for ``state`` was provided"
  },
  {
    "code": "def visit_statements(self, nodes):\n    primals, adjoints = [], collections.deque()\n    for node in nodes:\n      primal, adjoint = self.visit(node)\n      if not isinstance(primal, list):\n        primal = [primal]\n      if not isinstance(adjoint, list):\n        adjoint = [adjoint]\n      primals.extend(filter(None, primal))\n      adjoints.extendleft(filter(None, adjoint[::-1]))\n    return primals, list(adjoints)",
    "docstring": "Generate the adjoint of a series of statements."
  },
  {
    "code": "def _check_user(user, group):\n    err = ''\n    if user:\n        uid = __salt__['file.user_to_uid'](user)\n        if uid == '':\n            err += 'User {0} is not available '.format(user)\n    if group:\n        gid = __salt__['file.group_to_gid'](group)\n        if gid == '':\n            err += 'Group {0} is not available'.format(group)\n    return err",
    "docstring": "Checks if the named user and group are present on the minion"
  },
  {
    "code": "def getEdges(self, edges, inEdges = True, outEdges = True, rawResults = False) :\n        try :\n            return edges.getEdges(self, inEdges, outEdges, rawResults)\n        except AttributeError :\n            raise AttributeError(\"%s does not seem to be a valid Edges object\" % edges)",
    "docstring": "returns in, out, or both edges linked to self belonging the collection 'edges'.\n        If rawResults a arango results will be return as fetched, if false, will return a liste of Edge objects"
  },
  {
    "code": "def heartbeat(self):\n        logger.debug('Heartbeating %s (ttl = %s)', self.jid, self.ttl)\n        try:\n            self.expires_at = float(self.client('heartbeat', self.jid,\n            self.client.worker_name, json.dumps(self.data)) or 0)\n        except QlessException:\n            raise LostLockException(self.jid)\n        logger.debug('Heartbeated %s (ttl = %s)', self.jid, self.ttl)\n        return self.expires_at",
    "docstring": "Renew the heartbeat, if possible, and optionally update the job's\n        user data."
  },
  {
    "code": "def send_voice(self, voice, **options):\n        return self.bot.api_call(\n            \"sendVoice\", chat_id=str(self.id), voice=voice, **options\n        )",
    "docstring": "Send an OPUS-encoded .ogg audio file.\n\n        :param voice: Object containing the audio data\n        :param options: Additional sendVoice options (see\n            https://core.telegram.org/bots/api#sendvoice)\n\n        :Example:\n\n        >>> with open(\"voice.ogg\", \"rb\") as f:\n        >>>     await chat.send_voice(f)"
  },
  {
    "code": "def get_resource(self, request, filename):\n        filename = join(\"shared\", basename(filename))\n        try:\n            data = pkgutil.get_data(__package__, filename)\n        except OSError:\n            data = None\n        if data is not None:\n            mimetype = mimetypes.guess_type(filename)[0] or \"application/octet-stream\"\n            return Response(data, mimetype=mimetype)\n        return Response(\"Not Found\", status=404)",
    "docstring": "Return a static resource from the shared folder."
  },
  {
    "code": "def get_permission_groups(self, username):\n        if not self.organization or not self.username or not self.access_token:\n            return []\n        elif (self.username_prefix and\n                not username.startswith(self.username_prefix)):\n            return []\n        data = self._fetch_groups()\n        if not data:\n            self.log.error(\"No cached groups from GitHub available\")\n            return []\n        else:\n            return data.get(username[len(self.username_prefix):], [])",
    "docstring": "Return a list of names of the groups that the user with the specified\n        name is a member of. Implements an `IPermissionGroupProvider` API.\n\n        This specific implementation connects to GitHub with a dedicated user,\n        fetches and caches the teams and their users configured at GitHub and\n        converts the data into a format usable for easy access by username."
  },
  {
    "code": "def mesh_axis_to_cumprod(self, tensor_shape):\n    tensor_layout = self.tensor_layout(tensor_shape)\n    ma2ta = tensor_layout.mesh_axis_to_tensor_axis(self.ndims)\n    ta2cumprod = tensor_shape.cumprod\n    return [None if ta is None else ta2cumprod[ta] for ta in ma2ta]",
    "docstring": "For each mesh axis, give the product of previous tensor axes.\n\n    Args:\n      tensor_shape: Shape.\n\n    Returns:\n      list with length self.ndims where each element is an integer or None."
  },
  {
    "code": "def update(cwd, targets=None, user=None, username=None, password=None, *opts):\n    if targets:\n        opts += tuple(salt.utils.args.shlex_split(targets))\n    return _run_svn('update', cwd, user, username, password, opts)",
    "docstring": "Update the current directory, files, or directories from\n    the remote Subversion repository\n\n    cwd\n        The path to the Subversion repository\n\n    targets : None\n        files and directories to pass to the command as arguments\n        Default: svn uses '.'\n\n    user : None\n        Run svn as a user other than what the minion runs as\n\n    password : None\n        Connect to the Subversion server with this password\n\n        .. versionadded:: 0.17.0\n\n    username : None\n        Connect to the Subversion server as another user\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' svn.update /path/to/repo"
  },
  {
    "code": "def compute_logarithmic_scale(min_, max_, min_scale, max_scale):\n    if max_ <= 0 or min_ <= 0:\n        return []\n    min_order = int(floor(log10(min_)))\n    max_order = int(ceil(log10(max_)))\n    positions = []\n    amplitude = max_order - min_order\n    if amplitude <= 1:\n        return []\n    detail = 10.\n    while amplitude * detail < min_scale * 5:\n        detail *= 2\n    while amplitude * detail > max_scale * 3:\n        detail /= 2\n    for order in range(min_order, max_order + 1):\n        for i in range(int(detail)):\n            tick = (10 * i / detail or 1) * 10**order\n            tick = round_to_scale(tick, tick)\n            if min_ <= tick <= max_ and tick not in positions:\n                positions.append(tick)\n    return positions",
    "docstring": "Compute an optimal scale for logarithmic"
  },
  {
    "code": "def create_view(self, request):\n        kwargs = {'model_admin': self}\n        view_class = self.create_view_class\n        return view_class.as_view(**kwargs)(request)",
    "docstring": "Instantiates a class-based view to provide 'creation' functionality for\n        the assigned model, or redirect to Wagtail's create view if the\n        assigned model extends 'Page'. The view class used can be overridden by\n        changing the 'create_view_class' attribute."
  },
  {
    "code": "def _validate_name(name):\n    name = six.text_type(name)\n    name_length = len(name)\n    regex = re.compile(r'^[a-zA-Z0-9][A-Za-z0-9_-]*[a-zA-Z0-9]$')\n    if name_length < 3 or name_length > 48:\n        ret = False\n    elif not re.match(regex, name):\n        ret = False\n    else:\n        ret = True\n    if ret is False:\n        log.warning(\n            'A Linode label may only contain ASCII letters or numbers, dashes, and '\n            'underscores, must begin and end with letters or numbers, and be at least '\n            'three characters in length.'\n        )\n    return ret",
    "docstring": "Checks if the provided name fits Linode's labeling parameters.\n\n    .. versionadded:: 2015.5.6\n\n    name\n        The VM name to validate"
  },
  {
    "code": "def _initialize(self, boto_session, sagemaker_client, sagemaker_runtime_client):\n        self.boto_session = boto_session or boto3.Session()\n        self._region_name = self.boto_session.region_name\n        if self._region_name is None:\n            raise ValueError('Must setup local AWS configuration with a region supported by SageMaker.')\n        self.sagemaker_client = LocalSagemakerClient(self)\n        self.sagemaker_runtime_client = LocalSagemakerRuntimeClient(self.config)\n        self.local_mode = True",
    "docstring": "Initialize this Local SageMaker Session."
  },
  {
    "code": "def _installer(self, package_list, install_string=None):\n        packages = ' '.join(package_list)\n        if install_string is None:\n            self.install_string = self.install_process[self.distro] % packages\n        else:\n            self.install_string = install_string\n        output, outcome = self.shell.run_command(command=self.install_string)\n        if outcome is False:\n            raise IOError(output)",
    "docstring": "Install operating system packages for the system.\n\n        :param: package_list: ``list``\n        :param install_string: ``str``"
  },
  {
    "code": "def libvlc_audio_output_list_release(p_list):\n    f = _Cfunctions.get('libvlc_audio_output_list_release', None) or \\\n        _Cfunction('libvlc_audio_output_list_release', ((1,),), None,\n                    None, ctypes.POINTER(AudioOutput))\n    return f(p_list)",
    "docstring": "Frees the list of available audio output modules.\n    @param p_list: list with audio outputs for release."
  },
  {
    "code": "def restore_sampler(fname):\n    hf = tables.open_file(fname)\n    fnode = hf.root.__sampler__\n    import pickle\n    sampler = pickle.load(fnode)\n    return sampler",
    "docstring": "Creates a new sampler from an hdf5 database."
  },
  {
    "code": "def check_is_injectable(func):\n    @wraps(func)\n    def wrapper(**kwargs):\n        name = kwargs['inj_name']\n        if not orca.is_injectable(name):\n            abort(404)\n        return func(**kwargs)\n    return wrapper",
    "docstring": "Decorator that will check whether the \"inj_name\" keyword argument to\n    the wrapped function matches a registered Orca injectable."
  },
  {
    "code": "def rdfs_classes(rdf):\n    upperclasses = {}\n    for s, o in rdf.subject_objects(RDFS.subClassOf):\n        upperclasses.setdefault(s, set())\n        for uc in rdf.transitive_objects(s, RDFS.subClassOf):\n            if uc != s:\n                upperclasses[s].add(uc)\n    for s, ucs in upperclasses.items():\n        logging.debug(\"setting superclass types: %s -> %s\", s, str(ucs))\n        for res in rdf.subjects(RDF.type, s):\n            for uc in ucs:\n                rdf.add((res, RDF.type, uc))",
    "docstring": "Perform RDFS subclass inference.\n\n    Mark all resources with a subclass type with the upper class."
  },
  {
    "code": "def _set_available_combinations(self):\n        available = set()\n        combinations_map = {}\n        whitelist = None\n        if self.output_combinations:\n            whitelist = self.output_combinations.split(\"|\")\n        self.max_width = 0\n        for output in range(len(self.layout[\"connected\"])):\n            for comb in combinations(self.layout[\"connected\"], output + 1):\n                for mode in [\"clone\", \"extend\"]:\n                    string = self._get_string_and_set_width(comb, mode)\n                    if whitelist and string not in whitelist:\n                        continue\n                    if len(comb) == 1:\n                        combinations_map[string] = (comb, None)\n                    else:\n                        combinations_map[string] = (comb, mode)\n                    available.add(string)\n        if whitelist:\n            available = reversed([comb for comb in whitelist if comb in available])\n        self.available_combinations = deque(available)\n        self.combinations_map = combinations_map",
    "docstring": "Generate all connected outputs combinations and\n        set the max display width while iterating."
  },
  {
    "code": "def available_streams():\n    sds = kp.db.StreamDS()\n    print(\"Available streams: \")\n    print(', '.join(sorted(sds.streams)))",
    "docstring": "Show a short list of available streams."
  },
  {
    "code": "def resolve_model(self, model):\n        if not model:\n            raise ValueError('Unsupported model specifications')\n        if isinstance(model, basestring):\n            classname = model\n        elif isinstance(model, dict) and 'class' in model:\n            classname = model['class']\n        else:\n            raise ValueError('Unsupported model specifications')\n        try:\n            return get_document(classname)\n        except self.NotRegistered:\n            message = 'Model \"{0}\" does not exist'.format(classname)\n            raise ValueError(message)",
    "docstring": "Resolve a model given a name or dict with `class` entry.\n\n        :raises ValueError: model specification is wrong or does not exists"
  },
  {
    "code": "def generate_rst_docs(directory, classes, missing_objects=None):\n    doc_by_filename = _generate_rst_docs(classes=classes, missing_objects=missing_objects)\n    for filename, doc in doc_by_filename:\n        with open(directory + filename, 'w') as f2:\n            f2.write(doc)",
    "docstring": "Generate documentation for tri.declarative APIs\n\n    :param directory: directory to write the .rst files into\n    :param classes: list of classes to generate documentation for\n    :param missing_objects: tuple of objects to count as missing markers, if applicable"
  },
  {
    "code": "def override(cls):\n    def check_override(method):\n        if method.__name__ not in dir(cls):\n            raise NameError(\"{} does not override any method of {}\".format(\n                method, cls))\n        return method\n    return check_override",
    "docstring": "Annotation for documenting method overrides.\n\n    Arguments:\n        cls (type): The superclass that provides the overriden method. If this\n            cls does not actually have the method, an error is raised."
  },
  {
    "code": "def gcv(data, channels=None):\n    if channels is None:\n        data_stats = data\n    else:\n        data_stats = data[:, channels]\n    return np.sqrt(np.exp(np.std(np.log(data_stats), axis=0)**2) - 1)",
    "docstring": "Calculate the geometric CV of the events in an FCSData object.\n\n    Parameters\n    ----------\n    data : FCSData or numpy array\n        NxD flow cytometry data where N is the number of events and D is\n        the number of parameters (aka channels).\n    channels : int or str or list of int or list of str, optional\n        Channels on which to calculate the statistic. If None, use all\n        channels.\n\n    Returns\n    -------\n    float or numpy array\n        The geometric coefficient of variation of the events in the\n        specified channels of `data`."
  },
  {
    "code": "def synchronized(*args):\n    if callable(args[0]):\n        return decorate_synchronized(args[0], _synchronized_lock)\n    else:\n        def wrap(function):\n            return decorate_synchronized(function, args[0])\n        return wrap",
    "docstring": "A synchronized function prevents two or more callers to interleave\n    its execution preventing race conditions.\n\n    The synchronized decorator accepts as optional parameter a Lock, RLock or\n    Semaphore object which will be employed to ensure the function's atomicity.\n\n    If no synchronization object is given, a single threading.Lock will be used.\n    This implies that between different decorated function only one at a time\n    will be executed."
  },
  {
    "code": "def policy_version_exists(policyName, policyVersionId,\n           region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        policy = conn.get_policy_version(policyName=policyName,\n                                         policyversionId=policyVersionId)\n        return {'exists': bool(policy)}\n    except ClientError as e:\n        err = __utils__['boto3.get_error'](e)\n        if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':\n            return {'exists': False}\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Given a policy name and version ID, check to see if the given policy version exists.\n\n    Returns True if the given policy version exists and returns False if the given\n    policy version does not exist.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_iot.policy_version_exists mypolicy versionid"
  },
  {
    "code": "def averageSize(self):\n        cm = self.centerOfMass()\n        coords = self.coordinates(copy=False)\n        if not len(coords):\n            return 0\n        s, c = 0.0, 0.0\n        n = len(coords)\n        step = int(n / 10000.0) + 1\n        for i in np.arange(0, n, step):\n            s += utils.mag(coords[i] - cm)\n            c += 1\n        return s / c",
    "docstring": "Calculate the average size of a mesh.\n        This is the mean of the vertex distances from the center of mass."
  },
  {
    "code": "def replication_connection_string_and_slot_using_pgpass(target_node_info):\n    connection_info, slot = connection_info_and_slot(target_node_info)\n    connection_info[\"dbname\"] = \"replication\"\n    connection_info[\"replication\"] = \"true\"\n    connection_string = create_pgpass_file(connection_info)\n    return connection_string, slot",
    "docstring": "Like `connection_string_and_slot_using_pgpass` but returns a\n    connection string for a replication connection."
  },
  {
    "code": "def compare_last_two_snapshots(obj, raw=False):\n    if get_snapshot_count(obj) < 2:\n        return {}\n    version = get_version(obj)\n    snap1 = get_snapshot_by_version(obj, version - 1)\n    snap2 = get_snapshot_by_version(obj, version)\n    return compare_snapshots(snap1, snap2, raw=raw)",
    "docstring": "Helper to compare the last two snapshots directly"
  },
  {
    "code": "def print_info(self, obj=None, buf=sys.stdout):\n        if not obj:\n            self._print_info(buf)\n            return True\n        b = False\n        for fn in (self._print_tool_info,\n                   self._print_package_info,\n                   self._print_suite_info,\n                   self._print_context_info):\n            b_ = fn(obj, buf, b)\n            b |= b_\n            if b_:\n                print >> buf, ''\n        if not b:\n            print >> buf, \"Rez does not know what '%s' is\" % obj\n        return b",
    "docstring": "Print a status message about the given object.\n\n        If an object is not provided, status info is shown about the current\n        environment - what the active context is if any, and what suites are\n        visible.\n\n        Args:\n            obj (str): String which may be one of the following:\n                - A tool name;\n                - A package name, possibly versioned;\n                - A context filepath;\n                - A suite filepath;\n                - The name of a context in a visible suite."
  },
  {
    "code": "def get_item(self, key):\n        keys = list(self.keys())\n        if not key in keys:\n            self.print_message(\"ERROR: '\"+str(key)+\"' not found.\")\n            return None\n        try:\n            x = eval(self.get_value(1,keys.index(key)))\n            return x\n        except:\n            self.print_message(\"ERROR: '\"+str(self.get_value(1,keys.index(key)))+\"' cannot be evaluated.\")\n            return None",
    "docstring": "Returns the value associated with the key."
  },
  {
    "code": "def create_seq(self, project):\n        dialog = SequenceCreatorDialog(project=project, parent=self)\n        dialog.exec_()\n        seq = dialog.sequence\n        return seq",
    "docstring": "Create and return a new sequence\n\n        :param project: the project for the sequence\n        :type deps: :class:`jukeboxcore.djadapter.models.Project`\n        :returns: The created sequence or None\n        :rtype: None | :class:`jukeboxcore.djadapter.models.Sequence`\n        :raises: None"
  },
  {
    "code": "def main():\n    settings.init()\n    configuration_details = shell.how_to_configure()\n    if (\n        configuration_details and\n        configuration_details.can_configure_automatically\n    ):\n        if _is_already_configured(configuration_details):\n            logs.already_configured(configuration_details)\n            return\n        elif _is_second_run():\n            _configure(configuration_details)\n            logs.configured_successfully(configuration_details)\n            return\n        else:\n            _record_first_run()\n    logs.how_to_configure_alias(configuration_details)",
    "docstring": "Shows useful information about how-to configure alias on a first run\n    and configure automatically on a second.\n\n    It'll be only visible when user type fuck and when alias isn't configured."
  },
  {
    "code": "def validate_query(self, query):\n        if query is None:\n            return query\n        query = self.update_reading_list(query)\n        return query",
    "docstring": "Confirm query exists given common filters."
  },
  {
    "code": "def getElementsByTagName(self, tagName):\n        ret = TagCollection()\n        if len(self) == 0:\n            return ret\n        tagName = tagName.lower()\n        _cmpFunc = lambda tag : bool(tag.tagName == tagName)\n        for tag in self:\n            TagCollection._subset(ret, _cmpFunc, tag)\n        return ret",
    "docstring": "getElementsByTagName - Gets elements within this collection having a specific tag name\n\n            @param tagName - String of tag name\n\n            @return - TagCollection of unique elements within this collection with given tag name"
  },
  {
    "code": "def filter_featured_apps(admin_apps, request):\n    featured_apps = []\n    for orig_app_spec in appsettings.DASHBOARD_FEATURED_APPS:\n        app_spec = orig_app_spec.copy()\n        if \"verbose_name\" in app_spec:\n            warnings.warn(\n                \"DASHBOARD_FEATURED_APPS[]['verbose_name'] = '%s' is deprecated. \"\n                \"Use 'name' instead)\" % app_spec['verbose_name'],\n                DeprecationWarning, stacklevel=2\n            )\n            app_spec['name'] = app_spec['verbose_name']\n        if hasattr(app_spec['models'], 'items'):\n            warnings.warn(\n                \"DASHBOARD_FEATURED_APPS[]['models'] for '%s' should now be a \"\n                \"list of tuples, not a dict.\" % app_spec['name'],\n                DeprecationWarning, stacklevel=2\n            )\n            app_spec['models'] = app_spec['models'].items()\n        app_spec['models'] = _build_app_models(\n            request, admin_apps, app_spec['models']\n        )\n        if app_spec['models']:\n            featured_apps.append(app_spec)\n    return featured_apps",
    "docstring": "Given a list of apps return a set of pseudo-apps considered featured.\n\n    Apps are considered featured if the are defined in the settings\n    property called `DASHBOARD_FEATURED_APPS` which contains a list of the apps\n    that are considered to be featured.\n\n    :param admin_apps: A list of apps.\n    :param request: Django request.\n    :return: Subset of app like objects that are listed in\n    the settings `DASHBOARD_FEATURED_APPS` setting."
  },
  {
    "code": "def get_alias(self, using=None, **kwargs):\n        return self._get_connection(using).indices.get_alias(index=self._name, **kwargs)",
    "docstring": "Retrieve a specified alias.\n\n        Any additional keyword arguments will be passed to\n        ``Elasticsearch.indices.get_alias`` unchanged."
  },
  {
    "code": "def create(cls, **kwargs):\n        try:\n            return cls.add(cls.new(**kwargs))\n        except:\n            cls.session.rollback()\n            raise",
    "docstring": "Initializes a new instance, adds it to the db and commits\n        the transaction.\n\n        Args:\n\n            **kwargs: The keyword arguments for the init constructor.\n\n        Examples:\n\n            >>> user = User.create(name=\"Vicky\", email=\"vicky@h.com\")\n            >>> user.id\n            35"
  },
  {
    "code": "def server_by_name(self, name):\n        return self.server_show_libcloud(\n            self.server_list().get(name, {}).get('id', '')\n        )",
    "docstring": "Find a server by its name"
  },
  {
    "code": "def padto8(data):\n    length = len(data)\n    return data + b'\\xdb' * (roundto8(length) - length)",
    "docstring": "Pads data to the multiplies of 8 bytes.\n\n       This makes x86_64 faster and prevents\n       undefined behavior on other platforms"
  },
  {
    "code": "def eprint(*args, **kwargs):\n    end = kwargs.get(\"end\", \"\\n\")\n    sep = kwargs.get(\"sep\", \" \")\n    (filename, lineno) = inspect.stack()[1][1:3]\n    print(\"{}:{}: \".format(filename, lineno), end=\"\")\n    print(*args, end=end, file=sys.stderr, sep=sep)",
    "docstring": "Print an error message to standard error, prefixing it with\n    file name and line number from which method was called."
  },
  {
    "code": "def mx_page_trees(self, mx_page):\n        resp = dict()\n        for tree_name, tree in self.scheduler.timetable.trees.items():\n            if tree.mx_page == mx_page:\n                rest_tree = self._get_tree_details(tree_name)\n                resp[tree.tree_name] = rest_tree.document\n        return resp",
    "docstring": "return trees assigned to given MX Page"
  },
  {
    "code": "def nan_circstd(samples, high=2.0*np.pi, low=0.0, axis=None):\n    samples = np.asarray(samples)\n    samples = samples[~np.isnan(samples)]\n    if samples.size == 0:\n        return np.nan\n    ang = (samples - low) * 2.0 * np.pi / (high - low)\n    smean = np.sin(ang).mean(axis=axis)\n    cmean = np.cos(ang).mean(axis=axis)\n    rmean = np.sqrt(smean**2 + cmean**2)\n    circstd = (high - low) * np.sqrt(-2.0 * np.log(rmean)) / (2.0 * np.pi)\n    return circstd",
    "docstring": "NaN insensitive version of scipy's circular standard deviation routine\n\n    Parameters\n    -----------\n    samples : array_like\n        Input array\n    low : float or int\n        Lower boundary for circular standard deviation range (default=0)\n    high: float or int\n        Upper boundary for circular standard deviation range (default=2 pi)\n    axis : int or NoneType\n        Axis along which standard deviations are computed.  The default is to\n        compute the standard deviation of the flattened array\n\n    Returns\n    --------\n    circstd : float\n        Circular standard deviation"
  },
  {
    "code": "def ping_hub(self):\n        if self.plugin is not None:\n            try:\n                self.plugin.execute(self.plugin.hub_name, 'ping', timeout_s=1,\n                                    silent=True)\n            except IOError:\n                self.on_heartbeat_error()\n            else:\n                self.heartbeat_alive_timestamp = datetime.now()\n                logger.debug('Hub connection alive as of %s',\n                             self.heartbeat_alive_timestamp)\n                return True",
    "docstring": "Attempt to ping the ZeroMQ plugin hub to verify connection is alive.\n\n        If ping is successful, record timestamp.\n        If ping is unsuccessful, call `on_heartbeat_error` method."
  },
  {
    "code": "def start_container(self, cls, **kwargs):\n        kwargs = self._replace_stylename(kwargs)\n        container = cls(**kwargs)\n        self._containers.append(container)",
    "docstring": "Append a new container."
  },
  {
    "code": "def validate_commit_range(repo_dir, old_commit, new_commit):\n    try:\n        commits = get_commits(repo_dir, old_commit, new_commit)\n    except Exception:\n        commits = []\n    if len(commits) == 0:\n        try:\n            commits = get_commits(repo_dir, new_commit, old_commit)\n        except Exception:\n            commits = []\n        if len(commits) == 0:\n            msg = (\"The commit range {0}..{1} is invalid for {2}.\"\n                   \"You may need to use the --update option to fetch the \"\n                   \"latest updates to the git repositories stored on your \"\n                   \"local computer.\".format(old_commit, new_commit, repo_dir))\n            raise exceptions.InvalidCommitRangeException(msg)\n        else:\n            return 'flip'\n    return True",
    "docstring": "Check if commit range is valid. Flip it if needed."
  },
  {
    "code": "def _compute_projection(self, X, W):\n        X = check_array(X)\n        D = np.diag(W.sum(1))\n        L = D - W\n        evals, evecs = eigh_robust(np.dot(X.T, np.dot(L, X)),\n                                   np.dot(X.T, np.dot(D, X)),\n                                   eigvals=(0, self.n_components - 1))\n        return evecs",
    "docstring": "Compute the LPP projection matrix\n\n        Parameters\n        ----------\n        X : array_like, (n_samples, n_features)\n            The input data\n        W : array_like or sparse matrix, (n_samples, n_samples)\n            The precomputed adjacency matrix\n\n        Returns\n        -------\n        P : ndarray, (n_features, self.n_components)\n            The matrix encoding the locality preserving projection"
  },
  {
    "code": "def attrget(self, groupname, attrname, rownr):\n        return self._attrget(groupname, attrname, rownr)",
    "docstring": "Get the value of an attribute in the given row in a group."
  },
  {
    "code": "def get_container(cls, scheduler):\n        if scheduler in cls._container_cache:\n            return cls._container_cache[scheduler]\n        else:\n            c = cls(scheduler)\n            cls._container_cache[scheduler] = c\n            return c",
    "docstring": "Create temporary instance for helper functions"
  },
  {
    "code": "def _on_access_token(self, future, response):\n        LOGGER.info(response.body)\n        content = escape.json_decode(response.body)\n        if 'error' in content:\n            LOGGER.error('Error fetching access token: %s', content['error'])\n            future.set_exception(auth.AuthError('StackExchange auth error: %s' %\n                                                str(content['error'])))\n            return\n        callback = self.async_callback(self._on_stackexchange_user, future,\n                                       content['access_token'])\n        self.stackexchange_request('me', callback, content['access_token'])",
    "docstring": "Invoked as a callback when StackExchange has returned a response to\n        the access token request.\n\n        :param method future: The callback method to pass along\n        :param tornado.httpclient.HTTPResponse response: The HTTP response"
  },
  {
    "code": "def get_parallel_regions(batch):\n    samples = [utils.to_single_data(d) for d in batch]\n    regions = _get_parallel_regions(samples[0])\n    return [{\"region\": \"%s:%s-%s\" % (c, s, e)} for c, s, e in regions]",
    "docstring": "CWL target to retrieve a list of callable regions for parallelization."
  },
  {
    "code": "def perform(self, node, inputs, output_storage):\n        x = inputs[0]\n        z = output_storage[0]\n        z[0] = np.asarray(self.operator(x))",
    "docstring": "Evaluate this node's computation.\n\n        Parameters\n        ----------\n        node : `theano.gof.graph.Apply`\n            The node of this Op in the computation graph.\n        inputs : 1-element list of arrays\n            Contains an array (usually `numpy.ndarray`) of concrete values\n            supplied for the symbolic input variable ``x``.\n        output_storage : 1-element list of 1-element lists\n            The single 1-element list contained in ``output_storage``\n            by default contains only ``None``. This value must be replaced\n            by the result of the application of `odl_op`.\n\n        Examples\n        --------\n        Perform a matrix multiplication:\n\n        >>> space = odl.rn(3)\n        >>> matrix = np.array([[1, 0, 1],\n        ...                    [0, 1, 1]], dtype=float)\n        >>> op = odl.MatrixOperator(matrix, domain=space)\n        >>> matrix_op = TheanoOperator(op)\n        >>> x = theano.tensor.dvector()\n        >>> op_x = matrix_op(x)\n        >>> op_func = theano.function([x], op_x)\n        >>> op_func([1, 2, 3])\n        array([ 4.,  5.])\n\n        Evaluate a functional, i.e., an operator with scalar output:\n\n        >>> space = odl.rn(3)\n        >>> functional = odl.solvers.L2NormSquared(space)\n        >>> func_op = TheanoOperator(functional)\n        >>> x = theano.tensor.dvector()\n        >>> op_x = func_op(x)\n        >>> op_func = theano.function([x], op_x)\n        >>> op_func([1, 2, 3])\n        array(14.0)"
  },
  {
    "code": "def binaryEntropy(x):\n  entropy = - x*x.log2() - (1-x)*(1-x).log2()\n  entropy[x*(1 - x) == 0] = 0\n  return entropy, entropy.sum()",
    "docstring": "Calculate entropy for a list of binary random variables\n\n  :param x: (torch tensor) the probability of the variable to be 1.\n  :return: entropy: (torch tensor) entropy, sum(entropy)"
  },
  {
    "code": "def get_microversion_for_features(service, features, wrapper_class,\n                                  min_ver, max_ver):\n    feature_versions = get_requested_versions(service, features)\n    if not feature_versions:\n        return None\n    for version in feature_versions:\n        microversion = wrapper_class(version)\n        if microversion.matches(min_ver, max_ver):\n            return microversion\n    return None",
    "docstring": "Retrieves that highest known functional microversion for features"
  },
  {
    "code": "def set_scheme(self, scheme_name):\n        self.stack.setCurrentIndex(self.order.index(scheme_name))\n        self.last_used_scheme = scheme_name",
    "docstring": "Set the current stack by 'scheme_name'."
  },
  {
    "code": "def update_batches(self, X_batch, L, Min):\n        self.X_batch = X_batch\n        if X_batch is not None:\n            self.r_x0, self.s_x0 = self._hammer_function_precompute(X_batch, L, Min, self.model)",
    "docstring": "Updates the batches internally and pre-computes the"
  },
  {
    "code": "def get_dG_at_T(seq, temp):\n    r_cal = scipy.constants.R / scipy.constants.calorie\n    seq = ssbio.protein.sequence.utils.cast_to_str(seq)\n    oobatake = {}\n    for t in range(20, 51):\n        oobatake[t] = calculate_oobatake_dG(seq, t)\n    stable = [i for i in oobatake.values() if i > 0]\n    if len(stable) == 0:\n        dG = 0.238846 * calculate_dill_dG(len(seq), temp)\n        method='Dill'\n    else:\n        dG = oobatake[temp]\n        method='Oobatake'\n    keq = math.exp(-1 * dG / (r_cal * (temp + 273.15)))\n    return dG, keq, method",
    "docstring": "Predict dG at temperature T, using best predictions from Dill or Oobatake methods.\n\n    Args:\n        seq (str, Seq, SeqRecord): Amino acid sequence\n        temp (float): Temperature in degrees C\n\n    Returns:\n        (tuple): tuple containing:\n\n            dG (float) Free energy of unfolding dG (cal/mol)\n            keq (float): Equilibrium constant Keq\n            method (str): Method used to calculate"
  },
  {
    "code": "async def _send_typing(self, request: Request, stack: Stack):\n        t = stack.get_layer(lyr.Typing)\n        if t.active:\n            await self.call(\n                'sendChatAction',\n                chat_id=request.message.get_chat_id(),\n                action='typing',\n            )",
    "docstring": "In telegram, the typing stops when the message is received. Thus, there\n        is no \"typing stops\" messages to send. The API is only called when\n        typing must start."
  },
  {
    "code": "def _check_timeindex(self, timeseries):\n        try:\n            timeseries.loc[self.edisgo.network.timeseries.timeindex]\n        except:\n            message = 'Time index of storage time series does not match ' \\\n                      'with load and feed-in time series.'\n            logging.error(message)\n            raise KeyError(message)",
    "docstring": "Raises an error if time index of storage time series does not\n        comply with the time index of load and feed-in time series.\n\n        Parameters\n        -----------\n        timeseries : :pandas:`pandas.DataFrame<dataframe>`\n            DataFrame containing active power the storage is charged (negative)\n            and discharged (positive) with in kW in column 'p' and\n            reactive power in kVA in column 'q'."
  },
  {
    "code": "def match(self, string):\n        if self.casesensitive:\n            return self.pattern == os.path.normcase(string)\n        else:\n            return self.pattern.lower() == os.path.normcase(string).lower()",
    "docstring": "Returns True if the argument matches the constant."
  },
  {
    "code": "def takes_instance_or_queryset(func):\n    @wraps(func)\n    def decorated_function(self, request, queryset):\n        if not isinstance(queryset, QuerySet):\n            try:\n                queryset = self.get_queryset(request).filter(pk=queryset.pk)\n            except AttributeError:\n                try:\n                    model = queryset._meta.model\n                except AttributeError:\n                    model = queryset._meta.concrete_model\n                queryset = model.objects.filter(pk=queryset.pk)\n        return func(self, request, queryset)\n    return decorated_function",
    "docstring": "Decorator that makes standard Django admin actions compatible."
  },
  {
    "code": "def apply_change(self):\n        changes = self.input['change']\n        key = self.current.task_data['role_id']\n        role = RoleModel.objects.get(key=key)\n        for change in changes:\n            permission = PermissionModel.objects.get(code=change['id'])\n            if change['checked'] is True:\n                role.add_permission(permission)\n            else:\n                role.remove_permission(permission)\n        role.save()",
    "docstring": "Applies changes to the permissions of the role.\n\n        To make a change to the permission of the role, a request\n        in the following format should be sent:\n\n        .. code-block:: python\n            {\n                'change':\n                    {\n                        'id': 'workflow2.lane1.task1',\n                        'checked': false\n                    },\n            }\n\n        The 'id' field of the change is the id of the tree element\n        that was sent to the UI (see `Permissions.edit_permissions`).\n        'checked' field is the new state of the element."
  },
  {
    "code": "def enrolled_device_id(self, enrolled_device_id):\n        if enrolled_device_id is None:\n            raise ValueError(\"Invalid value for `enrolled_device_id`, must not be `None`\")\n        if enrolled_device_id is not None and not re.search('^[A-Za-z0-9]{32}', enrolled_device_id):\n            raise ValueError(\"Invalid value for `enrolled_device_id`, must be a follow pattern or equal to `/^[A-Za-z0-9]{32}/`\")\n        self._enrolled_device_id = enrolled_device_id",
    "docstring": "Sets the enrolled_device_id of this EnrollmentIdentity.\n        The ID of the device in the Device Directory once it has been registered.\n\n        :param enrolled_device_id: The enrolled_device_id of this EnrollmentIdentity.\n        :type: str"
  },
  {
    "code": "def create_entry(self, text=\"\", sensitive=\"False\"):\n        text_entry = Gtk.Entry()\n        text_entry.set_sensitive(sensitive)\n        text_entry.set_text(text)\n        return text_entry",
    "docstring": "Function creates an Entry with corresponding text"
  },
  {
    "code": "def exec_command(\n        self,\n        command,\n        bufsize=-1,\n        timeout=None,\n        get_pty=False,\n        environment=None,\n    ):\n        chan = self._transport.open_session(timeout=timeout)\n        if get_pty:\n            chan.get_pty()\n        chan.settimeout(timeout)\n        if environment:\n            chan.update_environment(environment)\n        chan.exec_command(command)\n        stdin = chan.makefile(\"wb\", bufsize)\n        stdout = chan.makefile(\"r\", bufsize)\n        stderr = chan.makefile_stderr(\"r\", bufsize)\n        return stdin, stdout, stderr",
    "docstring": "Execute a command on the SSH server.  A new `.Channel` is opened and\n        the requested command is executed.  The command's input and output\n        streams are returned as Python ``file``-like objects representing\n        stdin, stdout, and stderr.\n\n        :param str command: the command to execute\n        :param int bufsize:\n            interpreted the same way as by the built-in ``file()`` function in\n            Python\n        :param int timeout:\n            set command's channel timeout. See `.Channel.settimeout`\n        :param bool get_pty:\n            Request a pseudo-terminal from the server (default ``False``).\n            See `.Channel.get_pty`\n        :param dict environment:\n            a dict of shell environment variables, to be merged into the\n            default environment that the remote command executes within.\n\n            .. warning::\n                Servers may silently reject some environment variables; see the\n                warning in `.Channel.set_environment_variable` for details.\n\n        :return:\n            the stdin, stdout, and stderr of the executing command, as a\n            3-tuple\n\n        :raises: `.SSHException` -- if the server fails to execute the command\n\n        .. versionchanged:: 1.10\n            Added the ``get_pty`` kwarg."
  },
  {
    "code": "def close_fileoutput (self):\n        if self.fd is not None:\n            try:\n                self.flush()\n            except IOError:\n                pass\n            if self.close_fd:\n                try:\n                    self.fd.close()\n                except IOError:\n                    pass\n            self.fd = None",
    "docstring": "Flush and close the file output denoted by self.fd."
  },
  {
    "code": "def _init_hdrgos(self, hdrgos_dflt, hdrgos_usr=None, add_dflt=True):\n        if (hdrgos_usr is None or hdrgos_usr is False) and not self.sections:\n            return set(hdrgos_dflt)\n        hdrgos_init = set()\n        if hdrgos_usr:\n            chk_goids(hdrgos_usr, \"User-provided GO group headers\")\n            hdrgos_init |= set(hdrgos_usr)\n        if self.sections:\n            self._chk_sections(self.sections)\n            hdrgos_sec = set([hg for _, hdrgos in self.sections for hg in hdrgos])\n            chk_goids(hdrgos_sec, \"User-provided GO group headers in sections\")\n            hdrgos_init |= hdrgos_sec\n        if add_dflt:\n            return set(hdrgos_init).union(hdrgos_dflt)\n        return hdrgos_init",
    "docstring": "Initialize GO high"
  },
  {
    "code": "def hsetnx(self, key, field, value):\n        return self._execute([b'HSETNX', key, field, value])",
    "docstring": "Sets `field` in the hash stored at `key` only if it does not exist.\n\n        Sets `field` in the hash stored at `key` only if `field` does not\n        yet exist.  If `key` does not exist, a new key holding a hash is\n        created.  If `field` already exists, this operation has no effect.\n\n        .. note::\n\n           *Time complexity*: ``O(1)``\n\n        :param key: The key of the hash\n        :type key: :class:`str`, :class:`bytes`\n        :param field: The field in the hash to set\n        :type key: :class:`str`, :class:`bytes`\n        :param value: The value to set the field to\n        :returns: ``1`` if `field` is a new field in the hash and `value`\n            was set.  ``0`` if `field` already exists in the hash and\n            no operation was performed\n        :rtype: int"
  },
  {
    "code": "def _generate_components(self, X):\n        rs = check_random_state(self.random_state)\n        if (self._use_mlp_input):\n            self._compute_biases(rs)\n            self._compute_weights(X, rs)\n        if (self._use_rbf_input):\n            self._compute_centers(X, sp.issparse(X), rs)\n            self._compute_radii()",
    "docstring": "Generate components of hidden layer given X"
  },
  {
    "code": "def get_value_for_expr(self, expr, target):\n        if expr in LOGICAL_OPERATORS.values():\n            return None\n        rvalue = expr['value']\n        if rvalue == HISTORICAL:\n            history = self.history[target]\n            if len(history) < self.history_size:\n                return None\n            rvalue = sum(history) / float(len(history))\n        rvalue = expr['mod'](rvalue)\n        return rvalue",
    "docstring": "I have no idea."
  },
  {
    "code": "def image_undo():\n    if len(image_undo_list) <= 0:\n        print(\"no undos in memory\")\n        return\n    [image, Z] = image_undo_list.pop(-1)\n    image.set_array(Z)\n    _pylab.draw()",
    "docstring": "Undoes the last coarsen or smooth command."
  },
  {
    "code": "def _newer(a, b):\n    if not os.path.exists(a):\n        return False\n    if not os.path.exists(b):\n        return True\n    return os.path.getmtime(a) >= os.path.getmtime(b)",
    "docstring": "Inquire whether file a was written since file b."
  },
  {
    "code": "def open_acqdata(filename, user='unknown', filemode='w-'):\n    if filename.lower().endswith((\".hdf5\", \".h5\")):\n        return HDF5Data(filename, user, filemode)\n    elif filename.lower().endswith((\".pst\", \".raw\")):\n        return BatlabData(filename, user, filemode)\n    else:\n        print \"File format not supported: \", filename",
    "docstring": "Opens and returns the correct AcquisitionData object according to filename extention.\n\n    Supported extentions:\n    * .hdf5, .h5 for sparkle data\n    * .pst, .raw for batlab data. Both the .pst and .raw file must be co-located and share the same base file name, but only one should be provided to this function\n    \n    see :class:`AcquisitionData<sparkle.data.acqdata.AcquisitionData>`\n\n    examples (if data file already exists)::\n\n        data = open_acqdata('myexperiment.hdf5', filemode='r')\n        print data.dataset_names()\n\n    for batlab data::\n\n        data = open('mouse666.raw', filemode='r')\n        print data.dataset_names()"
  },
  {
    "code": "def Imm(extended_map, s, lmax):\n    import numpy as np\n    extended_map = np.ascontiguousarray(extended_map, dtype=np.complex128)\n    NImm = (2*lmax + 1)**2\n    imm = np.empty(NImm, dtype=np.complex128)\n    _Imm(extended_map, imm, s, lmax)\n    return imm",
    "docstring": "Take the fft of the theta extended map, then zero pad and reorganize it\n\n    This is mostly an internal function, included here for backwards compatibility.  See map2salm\n    and salm2map for more useful functions."
  },
  {
    "code": "def fit(self, X, y=None, **kwargs):\n        if self.tagset == \"penn_treebank\":\n            self.pos_tag_counts_ = self._penn_tag_map()\n            self._handle_treebank(X)\n        elif self.tagset == \"universal\":\n            self.pos_tag_counts_ = self._uni_tag_map()\n            self._handle_universal(X)\n        self.draw()\n        return self",
    "docstring": "Fits the corpus to the appropriate tag map.\n        Text documents must be tokenized & tagged before passing to fit.\n\n        Parameters\n        ----------\n        X : list or generator\n            Should be provided as a list of documents or a generator\n            that yields a list of documents that contain a list of\n            sentences that contain (token, tag) tuples.\n\n        y : ndarray or Series of length n\n            An optional array of target values that are ignored by the\n            visualizer.\n\n        kwargs : dict\n            Pass generic arguments to the drawing method\n\n        Returns\n        -------\n        self : instance\n            Returns the instance of the transformer/visualizer"
  },
  {
    "code": "def parse(self):\n        self._options, self._arguments = self._parse_args()\n        self._arguments = self._arguments or ['.']\n        if not self._validate_options(self._options):\n            raise IllegalConfiguration()\n        self._run_conf = self._create_run_config(self._options)\n        config = self._create_check_config(self._options, use_defaults=False)\n        self._override_by_cli = config",
    "docstring": "Parse the configuration.\n\n        If one of `BASE_ERROR_SELECTION_OPTIONS` was selected, overrides all\n        error codes to check and disregards any error code related\n        configurations from the configuration files."
  },
  {
    "code": "def scale_up_dyno(self, process, quantity, size):\n        self._run(\n            [\n                \"heroku\",\n                \"ps:scale\",\n                \"{}={}:{}\".format(process, quantity, size),\n                \"--app\",\n                self.name,\n            ]\n        )",
    "docstring": "Scale up a dyno."
  },
  {
    "code": "def load(self, dataset_keys, previous_datasets=None):\n        all_datasets = previous_datasets or DatasetDict()\n        datasets = DatasetDict()\n        dsids = [self.get_dataset_key(ds_key) for ds_key in dataset_keys]\n        coordinates = self._get_coordinates_for_dataset_keys(dsids)\n        all_dsids = list(set().union(*coordinates.values())) + dsids\n        for dsid in all_dsids:\n            if dsid in all_datasets:\n                continue\n            coords = [all_datasets.get(cid, None)\n                      for cid in coordinates.get(dsid, [])]\n            ds = self._load_dataset_with_area(dsid, coords)\n            if ds is not None:\n                all_datasets[dsid] = ds\n                if dsid in dsids:\n                    datasets[dsid] = ds\n        self._load_ancillary_variables(all_datasets)\n        return datasets",
    "docstring": "Load `dataset_keys`.\n\n        If `previous_datasets` is provided, do not reload those."
  },
  {
    "code": "def set_default_encoder_parameters():\n    cparams = CompressionParametersType()\n    argtypes = [ctypes.POINTER(CompressionParametersType)]\n    OPENJPEG.opj_set_default_encoder_parameters.argtypes = argtypes\n    OPENJPEG.opj_set_default_encoder_parameters(ctypes.byref(cparams))\n    return cparams",
    "docstring": "Wrapper for openjpeg library function opj_set_default_encoder_parameters."
  },
  {
    "code": "def read_elastic_tensor(self):\n        header_pattern = r\"TOTAL ELASTIC MODULI \\(kBar\\)\\s+\" \\\n                         r\"Direction\\s+([X-Z][X-Z]\\s+)+\" \\\n                         r\"\\-+\"\n        row_pattern = r\"[X-Z][X-Z]\\s+\" + r\"\\s+\".join([r\"(\\-*[\\.\\d]+)\"] * 6)\n        footer_pattern = r\"\\-+\"\n        et_table = self.read_table_pattern(header_pattern, row_pattern,\n                                           footer_pattern, postprocess=float)\n        self.data[\"elastic_tensor\"] = et_table",
    "docstring": "Parse the elastic tensor data.\n\n        Returns:\n            6x6 array corresponding to the elastic tensor from the OUTCAR."
  },
  {
    "code": "def save_config(self, data: dict) -> Path:\n        out_dir = Path(self.families_dir) / data['family']\n        out_dir.mkdir(parents=True, exist_ok=True)\n        out_path = out_dir / 'pedigree.yaml'\n        dump = ruamel.yaml.round_trip_dump(data, indent=4, block_seq_indent=2)\n        out_path.write_text(dump)\n        return out_path",
    "docstring": "Save a config to the expected location."
  },
  {
    "code": "def parent_of(self, name):\n        if not self._in_tag(name):\n            return\n        node = self.cur_node\n        while node.tag != name:\n            node = node.getparent()\n        self.cur_node = node.getparent()",
    "docstring": "go to parent of node with name, and set as cur_node.  Useful\n        for creating new paragraphs"
  },
  {
    "code": "def _load_data(self):\n        ipa_canonical_string_to_ascii_str = dict()\n        for line in load_data_file(\n            file_path=self.DATA_FILE_PATH,\n            file_path_is_relative=True,\n            line_format=u\"sxA\"\n        ):\n            i_desc, i_ascii = line\n            if len(i_ascii) == 0:\n                raise ValueError(\"Data file '%s' contains a bad line: '%s'\" % (self.DATA_FILE_PATH, line))\n            key = (variant_to_canonical_string(i_desc),)\n            ipa_canonical_string_to_ascii_str[key] = i_ascii[0]\n        return ipa_canonical_string_to_ascii_str",
    "docstring": "Load the Kirshenbaum ASCII IPA data from the built-in database."
  },
  {
    "code": "def clone_exception(error, args):\n        new_error = error.__class__(*args)\n        new_error.__dict__ = error.__dict__\n        return new_error",
    "docstring": "return a new cloned error\n\n        when do:\n\n        ```\n        try:\n            do_sth()\n        except BaseException as e:\n            handle(e)\n\n        def handle(error):\n            # do sth with error\n            raise e  # <- won't work!\n\n        This can generate a new cloned error of the same class\n\n        Parameters\n        ----------\n        error: the caught error\n        args: the new args to init the cloned error\n\n        Returns\n        -------\n        new error of the same class"
  },
  {
    "code": "def is_last_child(self, child_pid):\n        last_child = self.last_child\n        if last_child is None:\n            return False\n        return last_child == child_pid",
    "docstring": "Determine if 'pid' is the latest version of a resource.\n\n        Resolves True for Versioned PIDs which are the oldest of its siblings.\n        False otherwise, also for Head PIDs."
  },
  {
    "code": "def onSiliconCheck(ra_deg, dec_deg, FovObj, padding_pix=DEFAULT_PADDING):\n    dist = angSepVincenty(FovObj.ra0_deg, FovObj.dec0_deg, ra_deg, dec_deg)\n    if dist >= 90.:\n        return False\n    return FovObj.isOnSilicon(ra_deg, dec_deg, padding_pix=padding_pix)",
    "docstring": "Check a single position."
  },
  {
    "code": "def vlm_change_media(self, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop):\n        return libvlc_vlm_change_media(self, str_to_bytes(psz_name), str_to_bytes(psz_input), str_to_bytes(psz_output), i_options, ppsz_options, b_enabled, b_loop)",
    "docstring": "Edit the parameters of a media. This will delete all existing inputs and\n        add the specified one.\n        @param psz_name: the name of the new broadcast.\n        @param psz_input: the input MRL.\n        @param psz_output: the output MRL (the parameter to the \"sout\" variable).\n        @param i_options: number of additional options.\n        @param ppsz_options: additional options.\n        @param b_enabled: boolean for enabling the new broadcast.\n        @param b_loop: Should this broadcast be played in loop ?\n        @return: 0 on success, -1 on error."
  },
  {
    "code": "def encode_utf8(s, f):\n    encode = codecs.getencoder('utf8')\n    encoded_str_bytes, num_encoded_chars = encode(s)\n    num_encoded_str_bytes = len(encoded_str_bytes)\n    assert 0 <= num_encoded_str_bytes <= 2**16-1\n    num_encoded_bytes = num_encoded_str_bytes + 2\n    f.write(FIELD_U8.pack((num_encoded_str_bytes & 0xff00) >> 8))\n    f.write(FIELD_U8.pack(num_encoded_str_bytes & 0x00ff))\n    f.write(encoded_str_bytes)\n    return num_encoded_bytes",
    "docstring": "UTF-8 encodes string `s` to file-like object `f` according to\n    the MQTT Version 3.1.1 specification in section 1.5.3.\n\n    The maximum length for the encoded string is 2**16-1 (65535) bytes.\n    An assertion error will result if the encoded string is longer.\n\n    Parameters\n    ----------\n    s: str\n        String to be encoded.\n    f: file\n        File-like object.\n\n    Returns\n    -------\n    int\n        Number of bytes written to f."
  },
  {
    "code": "def pfadd(self, key, value, *values):\n        return self.execute(b'PFADD', key, value, *values)",
    "docstring": "Adds the specified elements to the specified HyperLogLog."
  },
  {
    "code": "def check_move(new, old, t):\n        if (t <= 0) or numpy.isclose(t, 0.0):\n            return False\n        K_BOLTZ = 1.9872041E-003\n        if new < old:\n            return True\n        else:\n            move_prob = math.exp(-(new - old) / (K_BOLTZ * t))\n            if move_prob > random.uniform(0, 1):\n                return True\n        return False",
    "docstring": "Determines if a model will be accepted."
  },
  {
    "code": "def do_output(self, *args):\n        if args:\n            action, params = args[0], args[1:]\n            log.debug(\"Pass %s directly to output with %s\", action, params)\n            function = getattr(self.output, \"do_\" + action, None)\n            if function:\n                function(*params)",
    "docstring": "Pass a command directly to the current output processor"
  },
  {
    "code": "def expire(self, name, time):\n        with self.pipe as pipe:\n            return pipe.expire(self.redis_key(name), time)",
    "docstring": "Allow the key to expire after ``time`` seconds.\n\n        :param name: str     the name of the redis key\n        :param time: time expressed in seconds.\n        :return: Future()"
  },
  {
    "code": "def write_slide_list(self, logname, slides):\n        with open('%s/%s' % (self.cache, logname), 'w') as logfile:\n            for slide in slides:\n                heading = slide['heading']['text']\n                filename = self.get_image_name(heading)\n                print('%s,%d' % (filename, slide.get('time', 0)),\n                      file=logfile)",
    "docstring": "Write list of slides to logfile"
  },
  {
    "code": "def upstream(self, f, n=1):\n        if f.strand == -1:\n            return self.right(f, n)\n        return self.left(f, n)",
    "docstring": "find n upstream features where upstream is determined by\n        the strand of the query Feature f\n        Overlapping features are not considered.\n\n        f: a Feature object\n        n: the number of features to return"
  },
  {
    "code": "def _get_filename(self):\n        self.filename = expanduser(\n            os.path.join(self.rsr_dir, 'rsr_{0}_{1}.h5'.format(self.instrument,\n                                                               self.platform_name)))\n        LOG.debug('Filename: %s', str(self.filename))\n        if not os.path.exists(self.filename) or not os.path.isfile(self.filename):\n            LOG.warning(\"No rsr file %s on disk\", self.filename)\n            if self._rsr_data_version_uptodate:\n                LOG.info(\"RSR data up to date, so seems there is no support for this platform and sensor\")\n            else:\n                if self.do_download:\n                    LOG.info(\"Will download from internet...\")\n                    download_rsr()\n                    if self._get_rsr_data_version() == RSR_DATA_VERSION:\n                        self._rsr_data_version_uptodate = True\n        if not self._rsr_data_version_uptodate:\n            LOG.warning(\"rsr data may not be up to date: %s\", self.filename)\n            if self.do_download:\n                LOG.info(\"Will download from internet...\")\n                download_rsr()",
    "docstring": "Get the rsr filname from platform and instrument names, and download if not\n           available."
  },
  {
    "code": "def save_current(self):\n        if self.current_widget() is not None:\n            editor = self.current_widget()\n            self._save(editor)",
    "docstring": "Save current editor. If the editor.file.path is None, a save as dialog\n        will be shown."
  },
  {
    "code": "def set_umask(mask):\n    if mask is None or salt.utils.platform.is_windows():\n        yield\n    else:\n        try:\n            orig_mask = os.umask(mask)\n            yield\n        finally:\n            os.umask(orig_mask)",
    "docstring": "Temporarily set the umask and restore once the contextmanager exits"
  },
  {
    "code": "def decode(self, litmap):\n        return Or(*[And(*[litmap[idx] for idx in clause])\n                    for clause in self.clauses])",
    "docstring": "Convert the DNF to an expression."
  },
  {
    "code": "def __read(self):\n        self._socket.setblocking(0)\n        while not self._stop_event.is_set():\n            ready = select.select([self._socket], [], [], 1)\n            if ready[0]:\n                data, sender = self._socket.recvfrom(1024)\n                try:\n                    self._handle_heartbeat(sender, data)\n                except Exception as ex:\n                    _logger.exception(\"Error handling the heart beat: %s\", ex)",
    "docstring": "Reads packets from the socket"
  },
  {
    "code": "def refresh_index(meta, index) -> None:\n    projection_keys = set.union(meta.keys, index.keys)\n    proj = index.projection\n    mode = proj[\"mode\"]\n    if mode == \"keys\":\n        proj[\"included\"] = projection_keys\n    elif mode == \"all\":\n        proj[\"included\"] = meta.columns\n    elif mode == \"include\":\n        if all(isinstance(p, str) for p in proj[\"included\"]):\n            proj[\"included\"] = set(meta.columns_by_name[n] for n in proj[\"included\"])\n        else:\n            proj[\"included\"] = set(proj[\"included\"])\n        proj[\"included\"].update(projection_keys)\n    if proj[\"strict\"]:\n        proj[\"available\"] = proj[\"included\"]\n    else:\n        proj[\"available\"] = meta.columns",
    "docstring": "Recalculate the projection, hash_key, and range_key for the given index.\n\n    :param meta: model.Meta to find columns by name\n    :param index: The index to refresh"
  },
  {
    "code": "def path(value,\n         allow_empty = False,\n         **kwargs):\n    if not value and not allow_empty:\n        raise errors.EmptyValueError('value (%s) was empty' % value)\n    elif not value:\n        return None\n    if hasattr(os, 'PathLike'):\n        if not isinstance(value, (str, bytes, int, os.PathLike)):\n            raise errors.NotPathlikeError('value (%s) is path-like' % value)\n    else:\n        if not isinstance(value, int):\n            try:\n                os.path.exists(value)\n            except TypeError:\n                raise errors.NotPathlikeError('value (%s) is not path-like' % value)\n    return value",
    "docstring": "Validate that ``value`` is a valid path-like object.\n\n    :param value: The value to validate.\n\n    :param allow_empty: If ``True``, returns :obj:`None <python:None>` if\n      ``value`` is empty. If ``False``, raises a\n      :class:`EmptyValueError <validator_collection.errors.EmptyValueError>`\n      if ``value`` is empty. Defaults to ``False``.\n    :type allow_empty: :class:`bool <python:bool>`\n\n    :returns: The path represented by ``value``.\n    :rtype: Path-like object / :obj:`None <python:None>`\n\n    :raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty\n    :raises NotPathlikeError: if ``value`` is not a valid path-like object"
  },
  {
    "code": "def output_datacenter(gandi, datacenter, output_keys, justify=14):\n    output_generic(gandi, datacenter, output_keys, justify)\n    if 'dc_name' in output_keys:\n        output_line(gandi, 'datacenter', datacenter['name'], justify)\n    if 'status' in output_keys:\n        deactivate_at = datacenter.get('deactivate_at')\n        if deactivate_at:\n            output_line(gandi, 'closing on',\n                        deactivate_at.strftime('%d/%m/%Y'), justify)\n        closing = []\n        iaas_closed_for = datacenter.get('iaas_closed_for')\n        if iaas_closed_for == 'ALL':\n            closing.append('vm')\n        paas_closed_for = datacenter.get('paas_closed_for')\n        if paas_closed_for == 'ALL':\n            closing.append('paas')\n        if closing:\n            output_line(gandi, 'closed for', ', '.join(closing), justify)",
    "docstring": "Helper to output datacenter information."
  },
  {
    "code": "def _infer_transform_options(transform):\n    TransformOptions = collections.namedtuple(\"TransformOptions\",\n                                              ['CB', 'dual_index', 'triple_index', 'MB', 'SB'])\n    CB = False\n    SB = False\n    MB = False\n    dual_index = False\n    triple_index = False\n    for rx in transform.values():\n        if not rx:\n            continue\n        if \"CB1\" in rx:\n            if \"CB3\" in rx:\n                triple_index = True\n            else:\n                dual_index = True\n        if \"SB\" in rx:\n            SB = True\n        if \"CB\" in rx:\n            CB = True\n        if \"MB\" in rx:\n            MB = True\n    return TransformOptions(CB=CB, dual_index=dual_index, triple_index=triple_index, MB=MB, SB=SB)",
    "docstring": "figure out what transform options should be by examining the provided\n    regexes for keywords"
  },
  {
    "code": "def list_vms_sub(access_token, subscription_id):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/providers/Microsoft.Compute/virtualMachines',\n                        '?api-version=', COMP_API])\n    return do_get_next(endpoint, access_token)",
    "docstring": "List VMs in a subscription.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n\n    Returns:\n        HTTP response. JSON body of a list of VM model views."
  },
  {
    "code": "def install(source, package_id):\n    if is_installed(package_id):\n        return True\n    uri = urllib.parse.urlparse(source)\n    if not uri.scheme == '':\n        msg = 'Unsupported scheme for source uri: {0}'.format(uri.scheme)\n        raise SaltInvocationError(msg)\n    _install_from_path(source)\n    return is_installed(package_id)",
    "docstring": "Install a .pkg from an URI or an absolute path.\n\n    :param str source: The path to a package.\n\n    :param str package_id: The package ID\n\n    :return: True if successful, otherwise False\n    :rtype: bool\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' pkgutil.install source=/vagrant/build_essentials.pkg package_id=com.apple.pkg.gcc4.2Leo"
  },
  {
    "code": "def iteritems_sorted(dict_):\n    if isinstance(dict_, OrderedDict):\n        return six.iteritems(dict_)\n    else:\n        return iter(sorted(six.iteritems(dict_)))",
    "docstring": "change to iteritems ordered"
  },
  {
    "code": "def new_scope(self, new_scope={}):\n        old_scopes, self.scopes = self.scopes, self.scopes.new_child(new_scope)\n        yield\n        self.scopes = old_scopes",
    "docstring": "Add a new innermost scope for the duration of the with block.\n\n        Args:\n            new_scope (dict-like): The scope to add."
  },
  {
    "code": "def end(self):\n        for depth in xrange(len(self.names) - 1, -1, -1):\n            self.out_f.write('{0}}}\\n'.format(self.prefix(depth)))",
    "docstring": "Generate the closing part"
  },
  {
    "code": "def rename(self, names, inplace=False):\n        if (type(names) is not dict):\n            raise TypeError('names must be a dictionary: oldname -> newname')\n        all_columns = set(self.column_names())\n        for k in names:\n            if not k in all_columns:\n                raise ValueError('Cannot find column %s in the SFrame' % k)\n        if inplace:\n            ret = self\n        else:\n            ret = self.copy()\n        with cython_context():\n            for k in names:\n                colid = ret.column_names().index(k)\n                ret.__proxy__.set_column_name(colid, names[k])\n        ret._cache = None\n        return ret",
    "docstring": "Returns an SFrame with columns renamed. ``names`` is expected to be a\n        dict specifying the old and new names. This changes the names of the\n        columns given as the keys and replaces them with the names given as the\n        values.\n\n        If inplace == False (default) this operation does not modify the\n        current SFrame, returning a new SFrame.\n\n        If inplace == True, this operation modifies the current\n        SFrame, returning self.\n\n        Parameters\n        ----------\n        names : dict [string, string]\n            Dictionary of [old_name, new_name]\n\n        inplace : bool, optional. Defaults to False.\n            Whether the SFrame is modified in place.\n\n        Returns\n        -------\n        out : SFrame\n            The current SFrame.\n\n        See Also\n        --------\n        column_names\n\n        Examples\n        --------\n        >>> sf = SFrame({'X1': ['Alice','Bob'],\n        ...              'X2': ['123 Fake Street','456 Fake Street']})\n        >>> res = sf.rename({'X1': 'name', 'X2':'address'})\n        >>> res\n        +-------+-----------------+\n        |  name |     address     |\n        +-------+-----------------+\n        | Alice | 123 Fake Street |\n        |  Bob  | 456 Fake Street |\n        +-------+-----------------+\n        [2 rows x 2 columns]"
  },
  {
    "code": "def need_summary(self, now, max_updates, max_age):\n        if self.summarized is True and self.last_summarize_ts + max_age <= now:\n            return True\n        return self.summarized is False and self.updates >= max_updates",
    "docstring": "Helper method to determine if a \"summarize\" record should be\n        added.\n\n        :param now: The current time.\n        :param max_updates: Maximum number of updates before a\n                            summarize is required.\n        :param max_age: Maximum age of the last summarize record.\n                        This is used in the case where a summarize\n                        request has been lost by the compactor.\n\n        :returns: True if a \"summarize\" record should be added, False\n                  otherwise."
  },
  {
    "code": "def dummy_signatures(self):\n        if not self.signing_algorithm:\n            return []\n        algo_id = {'sha1': 1, 'sha384': 2}[self.signing_algorithm]\n        signature = make_dummy_signature(algo_id)\n        return [(algo_id, signature)]",
    "docstring": "Create a dummy signature.\n\n        This is used when initially writing the MAR header and we don't know\n        what the final signature data will be.\n\n        Returns:\n            Fake signature data suitable for writing to the header with\n            .write_signatures()"
  },
  {
    "code": "def get_cart_deformed_cell(base_cryst, axis=0, size=1):\n    cryst = Atoms(base_cryst)\n    uc = base_cryst.get_cell()\n    s = size/100.0\n    L = diag(ones(3))\n    if axis < 3:\n        L[axis, axis] += s\n    else:\n        if axis == 3:\n            L[1, 2] += s\n        elif axis == 4:\n            L[0, 2] += s\n        else:\n            L[0, 1] += s\n    uc = dot(uc, L)\n    cryst.set_cell(uc, scale_atoms=True)\n    return cryst",
    "docstring": "Return the cell deformed along one of the cartesian directions\n\n    Creates new deformed structure. The deformation is based on the\n    base structure and is performed along single axis. The axis is\n    specified as follows: 0,1,2 = x,y,z ; sheers: 3,4,5 = yz, xz, xy.\n    The size of the deformation is in percent and degrees, respectively.\n\n    :param base_cryst: structure to be deformed\n    :param axis: direction of deformation\n    :param size: size of the deformation\n\n    :returns: new, deformed structure"
  },
  {
    "code": "def _playsoundOSX(sound, block = True):\n    from AppKit     import NSSound\n    from Foundation import NSURL\n    from time       import sleep\n    if '://' not in sound:\n        if not sound.startswith('/'):\n            from os import getcwd\n            sound = getcwd() + '/' + sound\n        sound = 'file://' + sound\n    url   = NSURL.URLWithString_(sound)\n    nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True)\n    if not nssound:\n        raise IOError('Unable to load sound named: ' + sound)\n    nssound.play()\n    if block:\n        sleep(nssound.duration())",
    "docstring": "Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on\n    OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports.\n    Probably works on OS X 10.5 and newer. Probably works with all versions of\n    Python.\n\n    Inspired by (but not copied from) Aaron's Stack Overflow answer here:\n    http://stackoverflow.com/a/34568298/901641\n\n    I never would have tried using AppKit.NSSound without seeing his code."
  },
  {
    "code": "def acquire(self):\n        self.lock = retry_call(\n            self._attempt,\n            retries=float('inf'),\n            trap=zc.lockfile.LockError,\n            cleanup=functools.partial(self._check_timeout, timing.Stopwatch()),\n        )",
    "docstring": "Attempt to acquire the lock every `delay` seconds until the\n        lock is acquired or until `timeout` has expired.\n\n        Raises FileLockTimeout if the timeout is exceeded.\n\n        Errors opening the lock file (other than if it exists) are\n        passed through."
  },
  {
    "code": "def _run_driver(self, item_session: ItemSession, request, response):\n        _logger.debug('Started PhantomJS processing.')\n        session = PhantomJSCoprocessorSession(\n            self._phantomjs_driver_factory, self._root_path,\n            self._processing_rule, self._file_writer_session,\n            request, response,\n            item_session, self._phantomjs_params, self._warc_recorder\n        )\n        with contextlib.closing(session):\n            yield from session.run()\n        _logger.debug('Ended PhantomJS processing.')",
    "docstring": "Start PhantomJS processing."
  },
  {
    "code": "def count_trackbacks_handler(sender, **kwargs):\n    entry = kwargs['entry']\n    entry.trackback_count = F('trackback_count') + 1\n    entry.save(update_fields=['trackback_count'])",
    "docstring": "Update Entry.trackback_count when a trackback was posted."
  },
  {
    "code": "def make_multi_cols(self, num_class, name):\n        cols = ['c' + str(i) + '_' for i in xrange(num_class)]\n        cols = map(lambda x: x + name, cols)\n        return cols",
    "docstring": "make cols for multi-class predictions"
  },
  {
    "code": "def confidential_interval(x, alpha=0.98):\n    from scipy.stats import t\n    if x.ndim == 1:\n        df = len(x) - 1\n        cv = t.interval(alpha, df)\n        std = np.std(x)\n    else:\n        df = len(x[0]) - 1\n        cv = t.interval(alpha, df)[1]\n        std = np.std(x, axis=1)\n    return std * cv / np.sqrt(df)",
    "docstring": "Return a numpy array of column confidential interval\n\n    Parameters\n    ----------\n    x : ndarray\n        A numpy array instance\n    alpha : float\n        Alpha value of confidential interval\n\n    Returns\n    -------\n    ndarray\n        A 1 x n numpy array which indicate the each difference from sample\n        average point to confidential interval point"
  },
  {
    "code": "def join_locale(comps):\n    loc = comps['language']\n    if comps.get('territory'):\n        loc += '_' + comps['territory']\n    if comps.get('codeset'):\n        loc += '.' + comps['codeset']\n    if comps.get('modifier'):\n        loc += '@' + comps['modifier']\n    if comps.get('charmap'):\n        loc += ' ' + comps['charmap']\n    return loc",
    "docstring": "Join a locale specifier split in the format returned by split_locale."
  },
  {
    "code": "def timestamp(value):\n    value = value if timezone.is_naive(value) else timezone.localtime(value)\n    return value.strftime(settings.DATE_FORMAT)",
    "docstring": "Return the timestamp of a datetime.datetime object.\n\n    :param value: a datetime object\n    :type value: datetime.datetime\n\n    :return: the timestamp\n    :rtype: str"
  },
  {
    "code": "def voted_me_witness(self, account=None, limit=100):\n        if not account:\n            account = self.mainaccount\n        self.has_voted = []\n        self.has_not_voted = []\n        following = self.following(account, limit)\n        for f in following:\n            wv = self.account(f)['witness_votes']\n            voted = False\n            for w in wv:\n                if w == account:\n                    self.has_voted.append(f)\n                    voted = True\n            if not voted:\n                self.has_not_voted.append(f)\n        return self.has_voted",
    "docstring": "Fetches all those a given account is\n        following and sees if they have voted that\n        account as witness."
  },
  {
    "code": "def xlim(self, low, high):\n        self.chart['xAxis'][0]['min'] = low\n        self.chart['xAxis'][0]['max'] = high\n        return self",
    "docstring": "Set xaxis limits\n\n        Parameters\n        ----------\n        low : number\n        high : number\n\n        Returns\n        -------\n        Chart"
  },
  {
    "code": "def _cursor_up(self, value):\n        value = int(value)\n        if value == 0:\n            value = 1\n        self._cursor.clearSelection()\n        self._cursor.movePosition(self._cursor.Up, self._cursor.MoveAnchor, value)\n        self._last_cursor_pos = self._cursor.position()",
    "docstring": "Moves the cursor up by ``value``."
  },
  {
    "code": "def npz_generator(npz_path):\n    npz_data = np.load(npz_path)\n    X = npz_data['X']\n    y = npz_data['Y']\n    n = X.shape[0]\n    while True:\n        i = np.random.randint(0, n)\n        yield {'X': X[i], 'Y': y[i]}",
    "docstring": "Generate data from an npz file."
  },
  {
    "code": "def settrace_forked():\n    from _pydevd_bundle.pydevd_constants import GlobalDebuggerHolder\n    GlobalDebuggerHolder.global_dbg = None\n    threading.current_thread().additional_info = None\n    from _pydevd_frame_eval.pydevd_frame_eval_main import clear_thread_local_info\n    host, port = dispatch()\n    import pydevd_tracing\n    pydevd_tracing.restore_sys_set_trace_func()\n    if port is not None:\n        global connected\n        connected = False\n        global forked\n        forked = True\n        custom_frames_container_init()\n        if clear_thread_local_info is not None:\n            clear_thread_local_info()\n        settrace(\n                host,\n                port=port,\n                suspend=False,\n                trace_only_current_thread=False,\n                overwrite_prev_trace=True,\n                patch_multiprocessing=True,\n        )",
    "docstring": "When creating a fork from a process in the debugger, we need to reset the whole debugger environment!"
  },
  {
    "code": "def parse_pattern(format_string, env, wrapper=lambda x, y: y):\n    formatter = Formatter()\n    fields = [x[1] for x in formatter.parse(format_string) if x[1] is not None]\n    prepared_env = {}\n    for field in fields:\n        for field_alt in (x.strip() for x in field.split('|')):\n            if field_alt[0] in '\\'\"' and field_alt[-1] in '\\'\"':\n                field_values = field_alt[1:-1]\n            else:\n                field_values = env.get(field_alt)\n            if field_values is not None:\n                break\n        else:\n            field_values = []\n        if not isinstance(field_values, list):\n            field_values = [field_values]\n        prepared_env[field] = wrapper(field_alt, field_values)\n    return prepared_env",
    "docstring": "Parse the format_string and return prepared data according to the env.\n\n    Pick each field found in the format_string from the env(ironment), apply\n    the wrapper on each data and return a mapping between field-to-replace and\n    values for each."
  },
  {
    "code": "def requires_genesis(self):\n        genesis_file = os.path.join(self._data_dir, 'genesis.batch')\n        has_genesis_batches = Path(genesis_file).is_file()\n        LOGGER.debug('genesis_batch_file: %s',\n                     genesis_file if has_genesis_batches else 'not found')\n        chain_head = self._block_store.chain_head\n        has_chain_head = chain_head is not None\n        if has_chain_head:\n            LOGGER.debug('chain_head: %s', chain_head)\n        block_chain_id = self._chain_id_manager.get_block_chain_id()\n        is_genesis_node = block_chain_id is None\n        LOGGER.debug(\n            'block_chain_id: %s',\n            block_chain_id if not is_genesis_node else 'not yet specified')\n        if has_genesis_batches and has_chain_head:\n            raise InvalidGenesisStateError(\n                'Cannot have a genesis_batch_file and an existing chain')\n        if has_genesis_batches and not is_genesis_node:\n            raise InvalidGenesisStateError(\n                'Cannot have a genesis_batch_file and join an existing network'\n            )\n        if not has_genesis_batches and not has_chain_head:\n            LOGGER.info('No chain head and not the genesis node: '\n                        'starting in peering mode')\n        return has_genesis_batches and not has_chain_head and is_genesis_node",
    "docstring": "Determines if the system should be put in genesis mode\n\n        Returns:\n            bool: return whether or not a genesis block is required to be\n                generated.\n\n        Raises:\n            InvalidGenesisStateError: raises this error if there is invalid\n                combination of the following: genesis.batch, existing chain\n                head, and block chain id."
  },
  {
    "code": "def execute(self, conn, acquisition_era_name,end_date, transaction = False):\n\tif not conn:\n\t    dbsExceptionHandler(\"dbsException-failed-connect2host\", \"dbs/dao/Oracle/AcquisitionEra/updateEndDate expects db connection from upper layer.\", self.logger.exception)\n        binds = { \"acquisition_era_name\" :acquisition_era_name  , \"end_date\" : end_date  }\n        result = self.dbi.processData(self.sql, binds, conn, transaction)",
    "docstring": "for a given block_id"
  },
  {
    "code": "def _ReadPaddingDataTypeDefinition(\n      self, definitions_registry, definition_values, definition_name,\n      is_member=False):\n    if not is_member:\n      error_message = 'data type only supported as member'\n      raise errors.DefinitionReaderError(definition_name, error_message)\n    definition_object = self._ReadDataTypeDefinition(\n        definitions_registry, definition_values, data_types.PaddingDefinition,\n        definition_name, self._SUPPORTED_DEFINITION_VALUES_PADDING)\n    alignment_size = definition_values.get('alignment_size', None)\n    if not alignment_size:\n      error_message = 'missing alignment_size'\n      raise errors.DefinitionReaderError(definition_name, error_message)\n    try:\n      int(alignment_size)\n    except ValueError:\n      error_message = 'unuspported alignment size attribute: {0!s}'.format(\n          alignment_size)\n      raise errors.DefinitionReaderError(definition_name, error_message)\n    if alignment_size not in (2, 4, 8, 16):\n      error_message = 'unuspported alignment size value: {0!s}'.format(\n          alignment_size)\n      raise errors.DefinitionReaderError(definition_name, error_message)\n    definition_object.alignment_size = alignment_size\n    return definition_object",
    "docstring": "Reads a padding data type definition.\n\n    Args:\n      definitions_registry (DataTypeDefinitionsRegistry): data type definitions\n          registry.\n      definition_values (dict[str, object]): definition values.\n      definition_name (str): name of the definition.\n      is_member (Optional[bool]): True if the data type definition is a member\n          data type definition.\n\n    Returns:\n      PaddingtDefinition: padding definition.\n\n    Raises:\n      DefinitionReaderError: if the definitions values are missing or if\n          the format is incorrect."
  },
  {
    "code": "def to_tree(self):\n        tree = TreeLibTree()\n        for node in self:\n            tree.create_node(node, node.node_id, parent=node.parent)\n        return tree",
    "docstring": "returns a TreeLib tree"
  },
  {
    "code": "def _process_open(self):\n        click.launch(self._format_issue_url())\n        if not click.confirm('Did it work?', default=True):\n            click.echo()\n            self._process_print()\n            click.secho(\n                '\\nOpen the line manually and copy the text above\\n',\n                fg='yellow'\n            )\n            click.secho(\n                '  ' + self.REPO_URL + self.ISSUE_SUFFIX + '\\n', bold=True\n            )",
    "docstring": "Open link in a browser."
  },
  {
    "code": "def project_role(self, project, id):\n        if isinstance(id, Number):\n            id = \"%s\" % id\n        return self._find_for_resource(Role, (project, id))",
    "docstring": "Get a role Resource.\n\n        :param project: ID or key of the project to get the role from\n        :param id: ID of the role to get"
  },
  {
    "code": "def readSTYLECHANGERECORD(self, states, fill_bits, line_bits, level = 1):\n        return SWFShapeRecordStyleChange(self, states, fill_bits, line_bits, level)",
    "docstring": "Read a SWFShapeRecordStyleChange"
  },
  {
    "code": "def get_plot_dims(signal, ann_samp):\n    \"Figure out the number of plot channels\"\n    if signal is not None:\n        if signal.ndim == 1:\n            sig_len = len(signal)\n            n_sig = 1\n        else:\n            sig_len = signal.shape[0]\n            n_sig = signal.shape[1]\n    else:\n        sig_len = 0\n        n_sig = 0\n    if ann_samp is not None:\n        n_annot = len(ann_samp)\n    else:\n        n_annot = 0\n    return sig_len, n_sig, n_annot, max(n_sig, n_annot)",
    "docstring": "Figure out the number of plot channels"
  },
  {
    "code": "def update(self):\n        del self.ma.coefs\n        del self.arma.ma_coefs\n        del self.arma.ar_coefs\n        if self.primary_parameters_complete:\n            self.calc_secondary_parameters()\n        else:\n            for secpar in self._SECONDARY_PARAMETERS.values():\n                secpar.__delete__(self)",
    "docstring": "Delete the coefficients of the pure MA model and also all MA and\n        AR coefficients of the ARMA model.  Also calculate or delete the values\n        of all secondary iuh parameters, depending on the completeness of the\n        values of the primary parameters."
  },
  {
    "code": "def add_transition(self, source: str, dest: str):\n        self._transitions[source].append(dest)",
    "docstring": "Adds a transition from one state to another.\n\n        Args:\n          source (str): the name of the state from where the transition starts\n          dest (str): the name of the state where the transition ends"
  },
  {
    "code": "def connect(self):\n        \"Connects to the Redis server if not already connected\"\n        if self._sock:\n            return\n        try:\n            sock = self._connect()\n        except socket.timeout:\n            raise TimeoutError(\"Timeout connecting to server\")\n        except socket.error:\n            e = sys.exc_info()[1]\n            raise ConnectionError(self._error_message(e))\n        self._sock = sock\n        self._selector = DefaultSelector(sock)\n        try:\n            self.on_connect()\n        except RedisError:\n            self.disconnect()\n            raise\n        for callback in self._connect_callbacks:\n            callback(self)",
    "docstring": "Connects to the Redis server if not already connected"
  },
  {
    "code": "def train(input_dir, batch_size, max_steps, output_dir, checkpoint):\n    from google.datalab.utils import LambdaJob\n    if checkpoint is None:\n      checkpoint = _util._DEFAULT_CHECKPOINT_GSURL\n    labels = _util.get_labels(input_dir)\n    model = _model.Model(labels, 0.5, checkpoint)\n    task_data = {'type': 'master', 'index': 0}\n    task = type('TaskSpec', (object,), task_data)\n    job = LambdaJob(lambda: _trainer.Trainer(input_dir, batch_size, max_steps, output_dir,\n                                             model, None, task).run_training(), 'training')\n    return job",
    "docstring": "Train model locally."
  },
  {
    "code": "def page_data(self, idx, offset):\n        size = self.screen.page_size\n        while offset < 0 and idx:\n            offset += size\n            idx -= 1\n        offset = max(0, offset)\n        while offset >= size:\n            offset -= size\n            idx += 1\n        if idx == self.last_page:\n            offset = 0\n        idx = min(max(0, idx), self.last_page)\n        start = (idx * self.screen.page_size) + offset\n        end = start + self.screen.page_size\n        return (idx, offset), self._page_data[start:end]",
    "docstring": "Return character data for page of given index and offset.\n\n        :param idx: page index.\n        :type idx: int\n        :param offset: scrolling region offset of current page.\n        :type offset: int\n        :returns: list of tuples in form of ``(ucs, name)``\n        :rtype: list[(unicode, unicode)]"
  },
  {
    "code": "def registrar_for_scope(cls, goal):\n    type_name = '{}_{}'.format(cls.__name__, goal)\n    if PY2:\n      type_name = type_name.encode('utf-8')\n    return type(type_name, (cls, ), {'options_scope': goal})",
    "docstring": "Returns a subclass of this registrar suitable for registering on the specified goal.\n\n    Allows reuse of the same registrar for multiple goals, and also allows us to decouple task\n    code from knowing which goal(s) the task is to be registered in."
  },
  {
    "code": "def get_obj_in_upper_tree(element, cls):\n    if not hasattr(element, '_parent'):\n        raise ValueError('The top of the tree was reached without finding a {}'\n                         .format(cls))\n    parent = element._parent\n    if not isinstance(parent, cls):\n        return get_obj_in_upper_tree(parent, cls)\n    return parent",
    "docstring": "Return the first object in the parent tree of class `cls`."
  },
  {
    "code": "def get_file(cls, path):\n        depot_name, file_id = path.split('/', 1)\n        depot = cls.get(depot_name)\n        return depot.get(file_id)",
    "docstring": "Retrieves a file by storage name and fileid in the form of a path\n\n        Path is expected to be ``storage_name/fileid``."
  },
  {
    "code": "def set_objective(self, measured_metabolites):\n        self.clean_objective()\n        for k, v in measured_metabolites.items():\n            m = self.model.metabolites.get_by_id(k)\n            total_stoichiometry = m.total_stoichiometry(\n                self.without_transports)\n            for r in m.producers(self.without_transports):\n                update_rate = v * r.metabolites[m] / total_stoichiometry\n                r.objective_coefficient += update_rate",
    "docstring": "Updates objective function for given measured metabolites.\n\n        :param dict measured_metabolites: dict in which keys are metabolite names \n            and values are float numbers represent fold changes in metabolites."
  },
  {
    "code": "def _resolve_input(variable, variable_name, config_key, config):\n    if variable is None:\n        try:\n            variable = config.get(PROFILE, config_key)\n        except NoOptionError:\n            raise ValueError((\n                'no {} found - either provide a command line argument or '\n                'set up a default by running `apparate configure`'\n            ).format(variable_name))\n    return variable",
    "docstring": "Resolve input entered as option values with config values\n\n    If option values are provided (passed in as `variable`), then they are\n     returned unchanged. If `variable` is None, then we first look for a config\n     value to use.\n    If no config value is found, then raise an error.\n\n    Parameters\n    ----------\n    variable: string or numeric\n        value passed in as input by the user\n    variable_name: string\n        name of the variable, for clarity in the error message\n    config_key: string\n        key in the config whose value could be used to fill in the variable\n    config: ConfigParser\n        contains keys/values in .apparatecfg"
  },
  {
    "code": "def get_conf_attr(self, attr, default=None):\n        if attr in self.conf:\n            return self.conf[attr]\n        else:\n            return default",
    "docstring": "Get the value of a attribute in the configuration\n\n        :param attr: The attribute\n        :param default: If the attribute doesn't appear in the configuration\n            return this value\n        :return: The value of attribute in the configuration or the default\n            value"
  },
  {
    "code": "def next(self):\n        if self.iter == None:\n            self.iter = iter(self.objs)\n        try:\n            return self.iter.next()\n        except StopIteration:\n            self.iter = None\n            self.objs = []\n            if int(self.page) < int(self.total_pages):\n                self.page += 1\n                self._connection.get_response(self.action, self.params, self.page, self)\n                return self.next()\n            else:\n                raise",
    "docstring": "Special paging functionality"
  },
  {
    "code": "def labels(self):\n        labelings = OrderedDict()\n        for tree in self:\n            for label, line in tree.to_labeled_lines():\n                labelings[line] = label\n        return labelings",
    "docstring": "Construct a dictionary of string -> labels\n\n        Returns:\n        --------\n            OrderedDict<str, int> : string label pairs."
  },
  {
    "code": "def sync(self):\n        self.elk.send(cp_encode())\n        self.get_descriptions(TextDescriptions.SETTING.value)",
    "docstring": "Retrieve custom values from ElkM1"
  },
  {
    "code": "def load_layer_with_provider(layer_uri, provider, layer_name='tmp'):\n    if provider in RASTER_DRIVERS:\n        return QgsRasterLayer(layer_uri, layer_name, provider)\n    elif provider in VECTOR_DRIVERS:\n        return QgsVectorLayer(layer_uri, layer_name, provider)\n    else:\n        return None",
    "docstring": "Load a layer with a specific driver.\n\n    :param layer_uri: Layer URI that will be used by QGIS to load the layer.\n    :type layer_uri: basestring\n\n    :param provider: Provider name to use.\n    :type provider: basestring\n\n    :param layer_name: Layer name to use. Default to 'tmp'.\n    :type layer_name: basestring\n\n    :return: The layer or None if it's failed.\n    :rtype: QgsMapLayer"
  },
  {
    "code": "def threadsafe_event_trigger(self, event_type):\n        readfd, writefd = os.pipe()\n        self.readers.append(readfd)\n        def callback(**kwargs):\n            self.queued_interrupting_events.append(event_type(**kwargs))\n            logger.warning('added event to events list %r', self.queued_interrupting_events)\n            os.write(writefd, b'interrupting event!')\n        return callback",
    "docstring": "Returns a callback to creates events, interrupting current event requests.\n\n        Returned callback function will create an event of type event_type\n        which will interrupt an event request if one\n        is concurrently occuring, otherwise adding the event to a queue\n        that will be checked on the next event request."
  },
  {
    "code": "def hash(self):\n        if self._hash is None:\n            tohash = [self.path.name]\n            tohash.append(hashfile(self.path, blocksize=65536, count=20))\n            self._hash = hashobj(tohash)\n        return self._hash",
    "docstring": "Hash value based on file name and content"
  },
  {
    "code": "def classification_tikhonov(G, y, M, tau=0):\n    r\n    y[M == False] = 0\n    Y = _to_logits(y.astype(np.int))\n    return regression_tikhonov(G, Y, M, tau)",
    "docstring": "r\"\"\"Solve a classification problem on graph via Tikhonov minimization.\n\n    The function first transforms :math:`y` in logits :math:`Y`, then solves\n\n    .. math:: \\operatorname*{arg min}_X \\| M X - Y \\|_2^2 + \\tau \\ tr(X^T L X)\n\n    if :math:`\\tau > 0`, and\n\n    .. math:: \\operatorname*{arg min}_X tr(X^T L X) \\ \\text{ s. t. } \\ Y = M X\n\n    otherwise, where :math:`X` and :math:`Y` are logits.\n    The function returns the maximum of the logits.\n\n    Parameters\n    ----------\n    G : :class:`pygsp.graphs.Graph`\n    y : array, length G.n_vertices\n        Measurements.\n    M : array of boolean, length G.n_vertices\n        Masking vector.\n    tau : float\n        Regularization parameter.\n\n    Returns\n    -------\n    logits : array, length G.n_vertices\n        The logits :math:`X`.\n\n    Examples\n    --------\n    >>> from pygsp import graphs, learning\n    >>> import matplotlib.pyplot as plt\n    >>>\n    >>> G = graphs.Logo()\n\n    Create a ground truth signal:\n\n    >>> signal = np.zeros(G.n_vertices)\n    >>> signal[G.info['idx_s']] = 1\n    >>> signal[G.info['idx_p']] = 2\n\n    Construct a measurement signal from a binary mask:\n\n    >>> rs = np.random.RandomState(42)\n    >>> mask = rs.uniform(0, 1, G.n_vertices) > 0.5\n    >>> measures = signal.copy()\n    >>> measures[~mask] = np.nan\n\n    Solve the classification problem by reconstructing the signal:\n\n    >>> recovery = learning.classification_tikhonov(G, measures, mask, tau=0)\n\n    Plot the results.\n    Note that we recover the class with ``np.argmax(recovery, axis=1)``.\n\n    >>> prediction = np.argmax(recovery, axis=1)\n    >>> fig, ax = plt.subplots(2, 3, sharey=True, figsize=(10, 6))\n    >>> _ = G.plot_signal(signal, ax=ax[0, 0], title='Ground truth')\n    >>> _ = G.plot_signal(measures, ax=ax[0, 1], title='Measurements')\n    >>> _ = G.plot_signal(prediction, ax=ax[0, 2], title='Recovered class')\n    >>> _ = G.plot_signal(recovery[:, 0], ax=ax[1, 0], title='Logit 0')\n    >>> _ = G.plot_signal(recovery[:, 1], ax=ax[1, 1], title='Logit 1')\n    >>> _ = G.plot_signal(recovery[:, 2], ax=ax[1, 2], title='Logit 2')\n    >>> _ = fig.tight_layout()"
  },
  {
    "code": "def _ps(self, search=''):\n        if not self.available:\n            return\n        result = []\n        ps = self.adb_streaming_shell('ps')\n        try:\n            for bad_line in ps:\n                for line in bad_line.splitlines():\n                    if search in line:\n                        result.append(line.strip().rsplit(' ', 1)[-1])\n            return result\n        except InvalidChecksumError as e:\n            print(e)\n            self.connect()\n            raise IOError",
    "docstring": "Perform a ps command with optional filtering.\n\n        :param search: Check for this substring.\n        :returns: List of matching fields"
  },
  {
    "code": "def get_nowait(self):\n        new_get = Future()\n        with self._lock:\n            if not self._get.done():\n                raise QueueEmpty\n            get, self._get = self._get, new_get\n        hole = get.result()\n        if not hole.done():\n            new_get.set_result(hole)\n            raise QueueEmpty\n        node = hole.result()\n        value = node.value\n        new_hole, node.next = node.next, None\n        new_get.set_result(new_hole)\n        return value",
    "docstring": "Returns a value from the queue without waiting.\n\n        Raises ``QueueEmpty`` if no values are available right now."
  },
  {
    "code": "def put_website(Bucket, ErrorDocument=None, IndexDocument=None,\n           RedirectAllRequestsTo=None, RoutingRules=None,\n           region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        WebsiteConfiguration = {}\n        for key in ('ErrorDocument', 'IndexDocument',\n                    'RedirectAllRequestsTo', 'RoutingRules'):\n            val = locals()[key]\n            if val is not None:\n                if isinstance(val, six.string_types):\n                    WebsiteConfiguration[key] = salt.utils.json.loads(val)\n                else:\n                    WebsiteConfiguration[key] = val\n        conn.put_bucket_website(Bucket=Bucket,\n                WebsiteConfiguration=WebsiteConfiguration)\n        return {'updated': True, 'name': Bucket}\n    except ClientError as e:\n        return {'updated': False, 'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Given a valid config, update the website configuration for a bucket.\n\n    Returns {updated: true} if website configuration was updated and returns\n    {updated: False} if website configuration was not updated.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{\"Suffix\":\"index.html\"}'"
  },
  {
    "code": "def spawn_reader_writer(get_data_fn, put_data_fn):\n    def _reader_thread():\n        while True:\n            out = get_data_fn()\n            put_data_fn(out)\n            if not out:\n                break\n    t = threading.Thread(target=_reader_thread)\n    t.daemon = True\n    t.start()\n    return t",
    "docstring": "Spawn a thread that reads from a data source and writes to a sink.\n\n    The thread will terminate if it receives a Falsey value from the source.\n\n    Args:\n        get_data_fn: Data-reading function. Called repeatedly until it returns\n            False-y to indicate that the thread should terminate.\n        put_data_fn: Data-writing function.\n    Returns: threading.Thread"
  },
  {
    "code": "def prepareToCalcEndOfPrdvP(self):\n        aNrmNow     = np.asarray(self.aXtraGrid) + self.BoroCnstNat\n        ShkCount    = self.TranShkValsNext.size\n        aNrm_temp   = np.tile(aNrmNow,(ShkCount,1))\n        aNrmCount         = aNrmNow.shape[0]\n        PermShkVals_temp  = (np.tile(self.PermShkValsNext,(aNrmCount,1))).transpose()\n        TranShkVals_temp  = (np.tile(self.TranShkValsNext,(aNrmCount,1))).transpose()\n        ShkPrbs_temp      = (np.tile(self.ShkPrbsNext,(aNrmCount,1))).transpose()\n        mNrmNext          = self.Rfree/(self.PermGroFac*PermShkVals_temp)*aNrm_temp + TranShkVals_temp\n        self.PermShkVals_temp  = PermShkVals_temp\n        self.ShkPrbs_temp      = ShkPrbs_temp\n        self.mNrmNext          = mNrmNext\n        self.aNrmNow           = aNrmNow\n        return aNrmNow",
    "docstring": "Prepare to calculate end-of-period marginal value by creating an array\n        of market resources that the agent could have next period, considering\n        the grid of end-of-period assets and the distribution of shocks he might\n        experience next period.\n\n        Parameters\n        ----------\n        none\n\n        Returns\n        -------\n        aNrmNow : np.array\n            A 1D array of end-of-period assets; also stored as attribute of self."
  },
  {
    "code": "def build_interactions(self, data):\n        interactions = _IncrementalCOOMatrix(self.interactions_shape(), np.int32)\n        weights = _IncrementalCOOMatrix(self.interactions_shape(), np.float32)\n        for datum in data:\n            user_idx, item_idx, weight = self._unpack_datum(datum)\n            interactions.append(user_idx, item_idx, 1)\n            weights.append(user_idx, item_idx, weight)\n        return (interactions.tocoo(), weights.tocoo())",
    "docstring": "Build an interaction matrix.\n\n        Two matrices will be returned: a (num_users, num_items)\n        COO matrix with interactions, and a (num_users, num_items)\n        matrix with the corresponding interaction weights.\n\n        Parameters\n        ----------\n\n        data: iterable of (user_id, item_id) or (user_id, item_id, weight)\n            An iterable of interactions. The user and item ids will be\n            translated to internal model indices using the mappings\n            constructed during the fit call. If weights are not provided\n            they will be assumed to be 1.0.\n\n        Returns\n        -------\n\n        (interactions, weights): COO matrix, COO matrix\n            Two COO matrices: the interactions matrix\n            and the corresponding weights matrix."
  },
  {
    "code": "def button_count(self):\n        if self._buttons_count is None:\n            if isinstance(self.reply_markup, (\n                    types.ReplyInlineMarkup, types.ReplyKeyboardMarkup)):\n                self._buttons_count = sum(\n                    len(row.buttons) for row in self.reply_markup.rows)\n            else:\n                self._buttons_count = 0\n        return self._buttons_count",
    "docstring": "Returns the total button count."
  },
  {
    "code": "def get_beacon():\n    \"Get a beacon socket\"\n    s = _socket.socket(_socket.AF_INET, _socket.SOCK_DGRAM)\n    s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, True)\n    s.setsockopt(_socket.SOL_SOCKET, _socket.SO_BROADCAST, True)\n    return s",
    "docstring": "Get a beacon socket"
  },
  {
    "code": "def field2write_only(self, field, **kwargs):\n        attributes = {}\n        if field.load_only and self.openapi_version.major >= 3:\n            attributes[\"writeOnly\"] = True\n        return attributes",
    "docstring": "Return the dictionary of OpenAPI field attributes for a load_only field.\n\n        :param Field field: A marshmallow field.\n        :rtype: dict"
  },
  {
    "code": "def name(self, value):\n        if not isinstance(value, six.string_types):\n            raise ValueError(\"Pass a string\")\n        self._properties[\"id\"] = value",
    "docstring": "Update name of the change set.\n\n        :type value: str\n        :param value: New name for the changeset."
  },
  {
    "code": "def _check_device_number(self, devices):\n        if len(devices) < 2 or len(devices) > 4:\n            msg = 'The number of devices to cluster is not supported.'\n            raise ClusterNotSupported(msg)",
    "docstring": "Check if number of devices is between 2 and 4\n\n        :param kwargs: dict -- keyword args in dict"
  },
  {
    "code": "def main():\n    config.parse_args()\n    if cfg.CONF.kafka_metrics.enabled:\n        prepare_processes(cfg.CONF.kafka_metrics,\n                          cfg.CONF.repositories.metrics_driver)\n    if cfg.CONF.kafka_alarm_history.enabled:\n        prepare_processes(cfg.CONF.kafka_alarm_history,\n                          cfg.CONF.repositories.alarm_state_history_driver)\n    if cfg.CONF.kafka_events.enabled:\n        prepare_processes(cfg.CONF.kafka_events,\n                          cfg.CONF.repositories.events_driver)\n    try:\n        LOG.info(\n)\n        for process in processors:\n            process.start()\n        signal.signal(signal.SIGCHLD, clean_exit)\n        signal.signal(signal.SIGINT, clean_exit)\n        signal.signal(signal.SIGTERM, clean_exit)\n        while True:\n            time.sleep(10)\n    except Exception:\n        LOG.exception('Error! Exiting.')\n        clean_exit(signal.SIGKILL)",
    "docstring": "Start persister."
  },
  {
    "code": "def delete(self, key):\n        obj = self._get_content()\n        obj.pop(key, None)\n        self.write_data(self.path, obj)",
    "docstring": "Removes the specified key from the database."
  },
  {
    "code": "def get_upload_token(mail, pwd):\n    try:\n        params = urllib.urlencode({\"email\": mail, \"password\": pwd})\n        response = urllib.urlopen(LOGIN_URL, params)\n    except:\n        return None\n    resp = json.loads(response.read())\n    if not resp or 'token' not in resp:\n        return None\n    return resp['token']",
    "docstring": "Get upload token"
  },
  {
    "code": "def __check_config_key(self, key):\n        try:\n            section, option = key.split('.')\n        except (AttributeError, ValueError):\n            return False\n        if not section or not option:\n            return False\n        return section in Config.CONFIG_OPTIONS and\\\n            option in Config.CONFIG_OPTIONS[section]",
    "docstring": "Check whether the key is valid.\n\n        A valid key has the schema <section>.<option>. Keys supported\n        are listed in CONFIG_OPTIONS dict.\n\n        :param key: <section>.<option> key"
  },
  {
    "code": "def _init_usrgos(self, goids):\n        usrgos = set()\n        goids_missing = set()\n        _go2obj = self.gosubdag.go2obj\n        for goid in goids:\n            if goid in _go2obj:\n                usrgos.add(goid)\n            else:\n                goids_missing.add(goid)\n        if goids_missing:\n            print(\"MISSING GO IDs: {GOs}\".format(GOs=goids_missing))\n            print(\"{N} of {M} GO IDs ARE MISSING\".format(N=len(goids_missing), M=len(goids)))\n        return usrgos",
    "docstring": "Return user GO IDs which have GO Terms."
  },
  {
    "code": "def upgrade_db(conn, pkg_name='openquake.server.db.schema.upgrades',\n               skip_versions=()):\n    upgrader = UpgradeManager.instance(conn, pkg_name)\n    t0 = time.time()\n    try:\n        versions_applied = upgrader.upgrade(conn, skip_versions)\n    except:\n        conn.rollback()\n        raise\n    else:\n        conn.commit()\n    dt = time.time() - t0\n    logging.info('Upgrade completed in %s seconds', dt)\n    return versions_applied",
    "docstring": "Upgrade a database by running several scripts in a single transaction.\n\n    :param conn: a DB API 2 connection\n    :param str pkg_name: the name of the package with the upgrade scripts\n    :param list skip_versions: the versions to skip\n    :returns: the version numbers of the new scripts applied the database"
  },
  {
    "code": "def _bind(self):\n        credentials = pika.PlainCredentials(self.user, self.password)\n        params = pika.ConnectionParameters(credentials=credentials,\n                                           host=self.server,\n                                           virtual_host=self.vhost,\n                                           port=self.port)\n        self.connection = pika.BlockingConnection(params)\n        self.channel = self.connection.channel()\n        self.channel.exchange_declare(exchange=self.topic_exchange,\n                                      exchange_type=\"topic\")",
    "docstring": "Create  socket and bind"
  },
  {
    "code": "def mock_cmd(self, release, *cmd, **kwargs):\n        fmt = '{mock_cmd}'\n        if kwargs.get('new_chroot') is True:\n            fmt +=' --new-chroot'\n        fmt += ' --configdir={mock_dir}'\n        return self.call(fmt.format(**release).split()\n                         + list(cmd))",
    "docstring": "Run a mock command in the chroot for a given release"
  },
  {
    "code": "def parse_human_datetime(s):\n    if not s:\n        return None\n    try:\n        dttm = parse(s)\n    except Exception:\n        try:\n            cal = parsedatetime.Calendar()\n            parsed_dttm, parsed_flags = cal.parseDT(s)\n            if parsed_flags & 2 == 0:\n                parsed_dttm = parsed_dttm.replace(hour=0, minute=0, second=0)\n            dttm = dttm_from_timtuple(parsed_dttm.utctimetuple())\n        except Exception as e:\n            logging.exception(e)\n            raise ValueError(\"Couldn't parse date string [{}]\".format(s))\n    return dttm",
    "docstring": "Returns ``datetime.datetime`` from human readable strings\n\n    >>> from datetime import date, timedelta\n    >>> from dateutil.relativedelta import relativedelta\n    >>> parse_human_datetime('2015-04-03')\n    datetime.datetime(2015, 4, 3, 0, 0)\n    >>> parse_human_datetime('2/3/1969')\n    datetime.datetime(1969, 2, 3, 0, 0)\n    >>> parse_human_datetime('now') <= datetime.now()\n    True\n    >>> parse_human_datetime('yesterday') <= datetime.now()\n    True\n    >>> date.today() - timedelta(1) == parse_human_datetime('yesterday').date()\n    True\n    >>> year_ago_1 = parse_human_datetime('one year ago').date()\n    >>> year_ago_2 = (datetime.now() - relativedelta(years=1) ).date()\n    >>> year_ago_1 == year_ago_2\n    True"
  },
  {
    "code": "def compare_dict(da, db):\n    sa = set(da.items())\n    sb = set(db.items())\n    diff = sa & sb\n    return dict(sa - diff), dict(sb - diff)",
    "docstring": "Compare differencs from two dicts"
  },
  {
    "code": "def dateindex(self, col: str):\n        df = self._dateindex(col)\n        if df is None:\n            self.err(\"Can not create date index\")\n            return\n        self.df = df\n        self.ok(\"Added a datetime index from column\", col)",
    "docstring": "Set a datetime index from a column\n\n        :param col: column name where to index the date from\n        :type col: str\n\n        :example: ``ds.dateindex(\"mycol\")``"
  },
  {
    "code": "def add_reshape(self, name, input_name, output_name, target_shape, mode):\n        spec = self.spec\n        nn_spec = self.nn_spec\n        spec_layer = nn_spec.layers.add()\n        spec_layer.name = name\n        spec_layer.input.append(input_name)\n        spec_layer.output.append(output_name)\n        spec_layer_params = spec_layer.reshape\n        spec_layer_params.targetShape.extend(target_shape)\n        if mode == 0:\n            spec_layer_params.mode = \\\n                    _NeuralNetwork_pb2.ReshapeLayerParams.ReshapeOrder.Value('CHANNEL_FIRST')\n        else:\n            spec_layer_params.mode = \\\n                    _NeuralNetwork_pb2.ReshapeLayerParams.ReshapeOrder.Value('CHANNEL_LAST')\n        if len(target_shape) != 4 and len(target_shape) != 3:\n            raise ValueError(\"Length of the 'target-shape' parameter must be equal to 3 or 4\")",
    "docstring": "Add a reshape layer. Kindly refer to NeuralNetwork.proto for details.\n\n        Parameters\n        ----------\n        name: str\n            The name of this layer.\n        target_shape: tuple\n            Shape of the output blob. The product of target_shape must be equal\n            to the shape of the input blob.\n            Can be either length 3 (C,H,W) or length 4 (Seq,C,H,W).\n        mode: int\n\n            - If mode == 0, the reshape layer is in CHANNEL_FIRST mode.\n            - If mode == 1, the reshape layer is in CHANNEL_LAST mode.\n\n        input_name: str\n            The input blob name of this layer.\n        output_name: str\n            The output blob name of this layer.\n\n        See Also\n        --------\n        add_flatten, add_permute"
  },
  {
    "code": "def make_choices_tuple(choices, get_display_name):\n    assert callable(get_display_name)\n    return tuple((x, get_display_name(x)) for x in choices)",
    "docstring": "Make a tuple for the choices parameter for a data model field.\n\n    :param choices: sequence of valid values for the model field\n    :param get_display_name: callable that returns the human-readable name for a choice\n\n    :return: A tuple of 2-tuples (choice, display_name) suitable for the choices parameter"
  },
  {
    "code": "def _execute_install_command(cmd, parse_output, errors, parsed_packages):\n    out = __salt__['cmd.run_all'](\n        cmd,\n        output_loglevel='trace',\n        python_shell=False\n    )\n    if out['retcode'] != 0:\n        if out['stderr']:\n            errors.append(out['stderr'])\n        else:\n            errors.append(out['stdout'])\n    elif parse_output:\n        parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))",
    "docstring": "Executes a command for the install operation.\n    If the command fails, its error output will be appended to the errors list.\n    If the command succeeds and parse_output is true, updated packages will be appended\n    to the parsed_packages dictionary."
  },
  {
    "code": "def cli(obj, show_userinfo):\n    client = obj['client']\n    userinfo = client.userinfo()\n    if show_userinfo:\n        for k, v in userinfo.items():\n            if isinstance(v, list):\n                v = ', '.join(v)\n            click.echo('{:20}: {}'.format(k, v))\n    else:\n        click.echo(userinfo['preferred_username'])",
    "docstring": "Display logged in user or full userinfo."
  },
  {
    "code": "def add_system_classpath():\n    if 'CLASSPATH' in os.environ:\n        parts = os.environ['CLASSPATH'].split(os.pathsep)\n        for part in parts:\n            javabridge.JARS.append(part)",
    "docstring": "Adds the system's classpath to the JVM's classpath."
  },
  {
    "code": "def has_translation(self, language_code=None, related_name=None):\n        if language_code is None:\n            language_code = self._current_language\n            if language_code is None:\n                raise ValueError(get_null_language_error())\n        meta = self._parler_meta._get_extension_by_related_name(related_name)\n        try:\n            return not is_missing(self._translations_cache[meta.model][language_code])\n        except KeyError:\n            if language_code in self._read_prefetched_translations(meta=meta):\n                return True\n            object = get_cached_translation(self, language_code, related_name=related_name, use_fallback=True)\n            if object is not None:\n                return object.language_code == language_code\n            try:\n                self._get_translated_model(language_code, use_fallback=False, auto_create=False, meta=meta)\n            except meta.model.DoesNotExist:\n                return False\n            else:\n                return True",
    "docstring": "Return whether a translation for the given language exists.\n        Defaults to the current language code.\n\n        .. versionadded 1.2 Added the ``related_name`` parameter."
  },
  {
    "code": "def get_context_data(self, **kwargs):\n        context = super(BaseAuthorDetail, self).get_context_data(**kwargs)\n        context['author'] = self.author\n        return context",
    "docstring": "Add the current author in context."
  },
  {
    "code": "def route_method(method_name, extra_part=False):\n    def wrapper(callable_obj):\n        if method_name.lower() not in DEFAULT_ROUTES:\n            raise HandlerHTTPMethodError(\n                'Invalid http method in method: {}'.format(method_name)\n            )\n        callable_obj.http_method = method_name.upper()\n        callable_obj.url_extra_part = callable_obj.__name__ if extra_part\\\n            else None\n        return classmethod(callable_obj)\n    return wrapper",
    "docstring": "Custom handler routing decorator.\n    Signs a web handler callable with the http method as attribute.\n\n    Args:\n        method_name (str): HTTP method name (i.e GET, POST)\n        extra_part (bool): Indicates if wrapped callable name should be a part\n                           of the actual endpoint.\n\n    Returns:\n        A wrapped handler callable.\n\n    examples:\n        >>> @route_method('GET')\n        ... def method():\n        ...     return \"Hello!\"\n        ...\n        >>> method.http_method\n        'GET'\n        >>> method.url_extra_part\n        None"
  },
  {
    "code": "def find_ips_by_equip(self, id_equip):\n        url = 'ip/getbyequip/' + str(id_equip) + \"/\"\n        code, xml = self.submit(None, 'GET', url)\n        return self.response(code, xml, ['ipv4', 'ipv6'])",
    "docstring": "Get Ips related to equipment by its identifier\n\n        :param id_equip: Equipment identifier. Integer value and greater than zero.\n\n        :return: Dictionary with the following structure:\n\n            { ips: { ipv4:[\n            id: <id_ip4>,\n            oct1: <oct1>,\n            oct2: <oct2>,\n            oct3: <oct3>,\n            oct4: <oct4>,\n            descricao: <descricao> ]\n            ipv6:[\n            id: <id_ip6>,\n            block1: <block1>,\n            block2: <block2>,\n            block3: <block3>,\n            block4: <block4>,\n            block5: <block5>,\n            block6: <block6>,\n            block7: <block7>,\n            block8: <block8>,\n            descricao: <descricao> ] } }\n\n        :raise UserNotAuthorizedError: User dont have permission to list ips.\n        :raise InvalidParameterError: Equipment identifier is none or invalid.\n        :raise XMLError: Networkapi failed to generate the XML response.\n        :raise DataBaseError: Networkapi failed to access the database."
  },
  {
    "code": "def money(s, thousand_sep=\".\", decimal_sep=\",\"):\n        s = s.replace(thousand_sep, \"\")\n        s = s.replace(decimal_sep, \".\")\n        return Decimal(s)",
    "docstring": "Converts money amount in string to a Decimal object.\n\n        With the default arguments, the format is expected to be\n        ``-38.500,00``, where dots separate thousands and comma the decimals.\n\n        Args:\n            thousand_sep: Separator for thousands.\n            decimal_sep: Separator for decimals.\n\n        Returns:\n            A ``Decimal`` object of the string encoded money amount."
  },
  {
    "code": "def _package_transform(package, fqdn, start=1, *args, **kwargs):\n    node = _obj_getattr(package, fqdn, start)\n    if node is not None and hasattr(node, \"__call__\"):\n        return node(*args, **kwargs)\n    else:\n        return args",
    "docstring": "Applies the specified package transform with `fqdn` to the package.\n\n    Args:\n        package: imported package object.\n        fqdn (str): fully-qualified domain name of function in the package. If it\n          does not include the package name, then set `start=0`.\n        start (int): in the '.'-split list of identifiers in `fqdn`, where to start\n          looking in the package. E.g., `numpy.linalg.norm` has `start=1` since\n          `package=numpy`; however, `linalg.norm` would have `start=0`."
  },
  {
    "code": "def encode(precision, with_z):\n    logger = logging.getLogger('geobuf')\n    stdin = click.get_text_stream('stdin')\n    sink = click.get_binary_stream('stdout')\n    try:\n        data = json.load(stdin)\n        pbf = geobuf.encode(\n            data,\n            precision if precision >= 0 else 6,\n            3 if with_z else 2)\n        sink.write(pbf)\n        sys.exit(0)\n    except Exception:\n        logger.exception(\"Failed. Exception caught\")\n        sys.exit(1)",
    "docstring": "Given GeoJSON on stdin, writes a geobuf file to stdout."
  },
  {
    "code": "def interpolate_psd(psd_f, psd_amp, deltaF):\n    new_psd_f = []\n    new_psd_amp = []\n    fcurr = psd_f[0]\n    for i in range(len(psd_f) - 1):\n        f_low = psd_f[i]\n        f_high = psd_f[i+1]\n        amp_low = psd_amp[i]\n        amp_high = psd_amp[i+1]\n        while(1):\n            if fcurr > f_high:\n                break\n            new_psd_f.append(fcurr)\n            gradient = (amp_high - amp_low) / (f_high - f_low)\n            fDiff = fcurr - f_low\n            new_psd_amp.append(amp_low + fDiff * gradient)\n            fcurr = fcurr + deltaF\n    return numpy.asarray(new_psd_f), numpy.asarray(new_psd_amp)",
    "docstring": "Function to interpolate a PSD to a different value of deltaF. Uses linear\n    interpolation.\n\n    Parameters\n    ----------\n    psd_f : numpy.array or list or similar\n        List of the frequencies contained within the PSD.\n    psd_amp : numpy.array or list or similar\n        List of the PSD values at the frequencies in psd_f.\n    deltaF : float\n        Value of deltaF to interpolate the PSD to.\n\n    Returns\n    --------\n    new_psd_f : numpy.array\n       Array of the frequencies contained within the interpolated PSD\n    new_psd_amp : numpy.array\n       Array of the interpolated PSD values at the frequencies in new_psd_f."
  },
  {
    "code": "def depth(args):\n    p = OptionParser(depth.__doc__)\n    p.set_outfile()\n    opts, args = p.parse_args(args)\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n    readsbed, featsbed = args\n    fp = open(featsbed)\n    nargs = len(fp.readline().split(\"\\t\"))\n    keepcols = \",\".join(str(x) for x in range(1, nargs + 1))\n    cmd = \"coverageBed -a {0} -b {1} -d\".format(readsbed, featsbed)\n    cmd += \" | groupBy -g {0} -c {1} -o mean\".format(keepcols, nargs + 2)\n    sh(cmd, outfile=opts.outfile)",
    "docstring": "%prog depth reads.bed features.bed\n\n    Calculate depth depth per feature using coverageBed."
  },
  {
    "code": "def get_feature_variable_string(self, feature_key, variable_key, user_id, attributes=None):\n    variable_type = entities.Variable.Type.STRING\n    return self._get_feature_variable_for_type(feature_key, variable_key, variable_type, user_id, attributes)",
    "docstring": "Returns value for a certain string variable attached to a feature.\n\n    Args:\n      feature_key: Key of the feature whose variable's value is being accessed.\n      variable_key: Key of the variable whose value is to be accessed.\n      user_id: ID for user.\n      attributes: Dict representing user attributes.\n\n    Returns:\n      String value of the variable. None if:\n      - Feature key is invalid.\n      - Variable key is invalid.\n      - Mismatch with type of variable."
  },
  {
    "code": "def write_can_msg(self, channel, can_msg):\n        c_can_msg = (CanMsg * len(can_msg))(*can_msg)\n        c_count = DWORD(len(can_msg))\n        UcanWriteCanMsgEx(self._handle, channel, c_can_msg, c_count)\n        return c_count",
    "docstring": "Transmits one ore more CAN messages through the specified CAN channel of the device.\n\n        :param int channel:\n            CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).\n        :param list(CanMsg) can_msg: List of CAN message structure (see structure :class:`CanMsg`).\n        :return: The number of successfully transmitted CAN messages.\n        :rtype: int"
  },
  {
    "code": "def _set_state(self, new_state, diag=None):\n        old_state = self._session_state\n        LOG.info(\"[BFD][%s][STATE] State changed from %s to %s.\",\n                 hex(self._local_discr),\n                 bfd.BFD_STATE_NAME[old_state],\n                 bfd.BFD_STATE_NAME[new_state])\n        self._session_state = new_state\n        if new_state == bfd.BFD_STATE_DOWN:\n            if diag is not None:\n                self._local_diag = diag\n            self._desired_min_tx_interval = 1000000\n            self._is_polling = True\n            self._update_xmit_period()\n        elif new_state == bfd.BFD_STATE_UP:\n            self._desired_min_tx_interval = self._cfg_desired_min_tx_interval\n            self._is_polling = True\n            self._update_xmit_period()\n        self.app.send_event_to_observers(\n            EventBFDSessionStateChanged(self, old_state, new_state))",
    "docstring": "Set the state of the BFD session."
  },
  {
    "code": "def mpub(self, topic, *messages):\n        return self.send(constants.MPUB + ' ' + topic, messages)",
    "docstring": "Publish multiple messages to a topic"
  },
  {
    "code": "def multi_to_dict(multi):\n    return dict(\n        (key, value[0] if len(value) == 1 else value)\n        for key, value in multi.to_dict(False).items()\n    )",
    "docstring": "Transform a Werkzeug multidictionnary into a flat dictionnary"
  },
  {
    "code": "def post_versions_list(self, updater_name=None, updater_id=None,\n                           post_id=None, start_id=None):\n        params = {\n            'search[updater_name]': updater_name,\n            'search[updater_id]': updater_id,\n            'search[post_id]': post_id,\n            'search[start_id]': start_id\n            }\n        return self._get('post_versions.json', params)",
    "docstring": "Get list of post versions.\n\n        Parameters:\n            updater_name (str):\n            updater_id (int):\n            post_id (int):\n            start_id (int):"
  },
  {
    "code": "def get_all_events(self):\n        self.all_events = {}\n        events = self.tree.execute(\"$.events.frames\")\n        if events is None:\n            return\n        for e in events:\n            event_type = e.get('type')\n            frame_id = e.get('frame_id')\n            try:\n                self.all_events[event_type].append(frame_id)\n            except KeyError:\n                self.all_events[event_type] = [frame_id]",
    "docstring": "Gather all event IDs in the REACH output by type.\n\n        These IDs are stored in the self.all_events dict."
  },
  {
    "code": "def py_func_grad(func, inp, Tout, stateful=True, name=None, grad=None):\n  rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8))\n  tf.RegisterGradient(rnd_name)(grad)\n  g = tf.get_default_graph()\n  with g.gradient_override_map({\"PyFunc\": rnd_name,\n                                \"PyFuncStateless\": rnd_name}):\n    return tf.py_func(func, inp, Tout, stateful=stateful, name=name)",
    "docstring": "Custom py_func with gradient support"
  },
  {
    "code": "def _scale_back_response(bqm, response, scalar, ignored_interactions,\n                         ignored_variables, ignore_offset):\n    if len(ignored_interactions) + len(\n            ignored_variables) + ignore_offset == 0:\n        response.record.energy = np.divide(response.record.energy, scalar)\n    else:\n        response.record.energy = bqm.energies((response.record.sample,\n                                               response.variables))\n    return response",
    "docstring": "Helper function to scale back the response of sample method"
  },
  {
    "code": "def count(tex):\n    soup = TexSoup(tex)\n    labels = set(label.string for label in soup.find_all('label'))\n    return dict((label, soup.find_all('\\ref{%s}' % label)) for label in labels)",
    "docstring": "Extract all labels, then count the number of times each is referenced in\n    the provided file. Does not follow \\includes."
  },
  {
    "code": "def nn_x(self, x, k=1, radius=np.inf, eps=0.0, p=2):\n        assert len(x) == self.dim_x\n        k_x = min(k, self.size)\n        return self._nn(DATA_X, x, k=k_x, radius=radius, eps=eps, p=p)",
    "docstring": "Find the k nearest neighbors of x in the observed input data\n        @see Databag.nn() for argument description\n        @return  distance and indexes of found nearest neighbors."
  },
  {
    "code": "def exists_using_casper(self, filename):\n        casper_results = casper.Casper(self.connection[\"jss\"])\n        distribution_servers = casper_results.find(\"distributionservers\")\n        all_packages = []\n        for distribution_server in distribution_servers:\n            packages = set()\n            for package in distribution_server.findall(\"packages/package\"):\n                packages.add(os.path.basename(package.find(\"fileURL\").text))\n            all_packages.append(packages)\n        base_set = all_packages.pop()\n        for packages in all_packages:\n            base_set = base_set.intersection(packages)\n        return filename in base_set",
    "docstring": "Check for the existence of a package file.\n\n        Unlike other DistributionPoint types, JDS and CDP types have no\n        documented interface for checking whether the server and its\n        children have a complete copy of a file. The best we can do is\n        check for an object using the API /packages URL--JSS.Package()\n        or /scripts and look for matches on the filename.\n\n        If this is not enough, this method uses the results of the\n        casper.jxml page to determine if a package exists. This is an\n        undocumented feature and as such should probably not be relied\n        upon. Please note, scripts are not listed per-distributionserver\n        like packages. For scripts, the best you can do is use the\n        regular exists method.\n\n        It will test for whether the file exists on ALL configured\n        distribution servers. This may register False if the JDS is busy\n        syncing them."
  },
  {
    "code": "def progressbar(length, label):\n    return click.progressbar(length=length, label=label, show_pos=True)",
    "docstring": "Creates a progressbar\n\n    Parameters\n    ----------\n    length int\n        Length of the ProgressBar\n    label str\n        Label to give to the progressbar\n\n    Returns\n    -------\n    click.progressbar\n        Progressbar"
  },
  {
    "code": "def score(self, phone_number, account_lifecycle_event, **params):\n        return self.post(SCORE_RESOURCE.format(phone_number=phone_number),\n                         account_lifecycle_event=account_lifecycle_event,\n                         **params)",
    "docstring": "Score is an API that delivers reputation scoring based on phone number intelligence, traffic patterns, machine\n        learning, and a global data consortium.\n\n        See https://developer.telesign.com/docs/score-api for detailed API documentation."
  },
  {
    "code": "def backfill_previous_messages(self, reverse=False, limit=10):\n        res = self.client.api.get_room_messages(self.room_id, self.prev_batch,\n                                                direction=\"b\", limit=limit)\n        events = res[\"chunk\"]\n        if not reverse:\n            events = reversed(events)\n        for event in events:\n            self._put_event(event)",
    "docstring": "Backfill handling of previous messages.\n\n        Args:\n            reverse (bool): When false messages will be backfilled in their original\n                order (old to new), otherwise the order will be reversed (new to old).\n            limit (int): Number of messages to go back."
  },
  {
    "code": "def add_link(app, pagename, templatename, context, doctree):\n    context['show_slidelink'] = (\n        app.config.slide_link_html_to_slides and\n        hasattr(app.builder, 'get_outfilename')\n    )\n    if context['show_slidelink']:\n        context['slide_path'] = slide_path(app.builder, pagename)",
    "docstring": "Add the slides link to the HTML context."
  },
  {
    "code": "def next(self):\n        if self._current_index < len(self._collection):\n            value = self._collection[self._current_index]\n            self._current_index += 1\n            return value\n        elif self._next_cursor:\n            self.__fetch_next()\n            return self.next()\n        else:\n            self._current_index = 0\n            raise StopIteration",
    "docstring": "Returns the next item in the cursor."
  },
  {
    "code": "def delete_existing_cname(env, zone_id, dns_name):\n    client = boto3.Session(profile_name=env).client('route53')\n    startrecord = None\n    newrecord_name = dns_name\n    startrecord = find_existing_record(env, zone_id, newrecord_name, check_key='Type', check_value='CNAME')\n    if startrecord:\n        LOG.info(\"Deleting old record: %s\", newrecord_name)\n        _response = client.change_resource_record_sets(\n            HostedZoneId=zone_id, ChangeBatch={'Changes': [{\n                'Action': 'DELETE',\n                'ResourceRecordSet': startrecord\n            }]})\n        LOG.debug('Response from deleting %s: %s', dns_name, _response)",
    "docstring": "Delete an existing CNAME record.\n\n    This is used when updating to multi-region for deleting old records. The\n    record can not just be upserted since it changes types.\n\n    Args:\n        env (str): Deployment environment.\n        zone_id (str): Route53 zone id.\n        dns_name (str): FQDN of application's dns entry to add/update."
  },
  {
    "code": "def all_pairs_normalized_distances_reference(X):\n    n_samples, n_cols = X.shape\n    D = np.ones((n_samples, n_samples), dtype=\"float32\") * np.inf\n    for i in range(n_samples):\n        diffs = X - X[i, :].reshape((1, n_cols))\n        missing_diffs = np.isnan(diffs)\n        missing_counts_per_row = missing_diffs.sum(axis=1)\n        valid_rows = missing_counts_per_row < n_cols\n        D[i, valid_rows] = np.nanmean(\n            diffs[valid_rows, :] ** 2,\n            axis=1)\n    return D",
    "docstring": "Reference implementation of normalized all-pairs distance, used\n    for testing the more efficient implementation above for equivalence."
  },
  {
    "code": "def _weighted_formula(form, weight_func):\n    for e, mf in form.items():\n        if e == Atom.H:\n            continue\n        yield e, mf, weight_func(e)",
    "docstring": "Yield weight of each formula element."
  },
  {
    "code": "def _get_table_names(statement):\n    parts = statement.to_unicode().split()\n    tables = set()\n    for i, token in enumerate(parts):\n        if token.lower() == 'from' or token.lower().endswith('join'):\n            tables.add(parts[i + 1].rstrip(';'))\n    return list(tables)",
    "docstring": "Returns table names found in the query.\n\n    NOTE. This routine would use the sqlparse parse tree, but vnames don't parse very well.\n\n    Args:\n        statement (sqlparse.sql.Statement): parsed by sqlparse sql statement.\n\n    Returns:\n        list of str"
  },
  {
    "code": "def has_metadata(self, name):\n        return self.has_implementation(name) or \\\n            name in self.non_returning or \\\n            name in self.prototypes",
    "docstring": "Check if a function has either an implementation or any metadata associated with it\n\n        :param name:    The name of the function as a string\n        :return:        A bool indicating if anything is known about the function"
  },
  {
    "code": "def resolve_remote(self, uri):\n        try:\n            return super(LocalRefResolver, self).resolve_remote(uri)\n        except ValueError:\n            return super(LocalRefResolver, self).resolve_remote(\n                'file://' + get_schema_path(uri.rsplit('.json', 1)[0])\n            )",
    "docstring": "Resolve a uri or relative path to a schema."
  },
  {
    "code": "def transformer_clean():\n  hparams = transformer_base_v2()\n  hparams.label_smoothing = 0.0\n  hparams.layer_prepostprocess_dropout = 0.0\n  hparams.attention_dropout = 0.0\n  hparams.relu_dropout = 0.0\n  hparams.max_length = 0\n  return hparams",
    "docstring": "No dropout, label smoothing, max_length."
  },
  {
    "code": "def set_db_attribute(self, table, record, column, value, key=None):\n        if key is not None:\n            column = '%s:%s' % (column, key)\n        command = ovs_vsctl.VSCtlCommand(\n            'set', (table, record, '%s=%s' % (column, value)))\n        self.run_command([command])",
    "docstring": "Sets 'value' into 'column' in 'record' in 'table'.\n\n        This method is corresponding to the following ovs-vsctl command::\n\n            $ ovs-vsctl set TBL REC COL[:KEY]=VALUE"
  },
  {
    "code": "def histogram_day_counts(\n    df,\n    variable\n    ):\n    if not df.index.dtype in [\"datetime64[ns]\", \"<M8[ns]\", \">M8[ns]\"]:\n        log.error(\"index is not datetime\")\n        return False\n    counts = df.groupby(df.index.weekday_name)[variable].count().reindex(calendar.day_name[0:])\n    counts.plot(kind = \"bar\", width = 1, rot = 0, alpha = 0.7)",
    "docstring": "Create a week-long histogram of counts of the variable for each day. It is\n    assumed that the DataFrame index is datetime and that the variable\n    `weekday_name` exists."
  },
  {
    "code": "def filter_time_nearest(self, time, regex=None):\n        return min(self._get_datasets_with_times(regex),\n                   key=lambda i: abs((i[0] - time).total_seconds()))[-1]",
    "docstring": "Filter keys for an item closest to the desired time.\n\n        Loops over all keys in the collection and uses `regex` to extract and build\n        `datetime`s. The collection of `datetime`s is compared to `start` and the value that\n        has a `datetime` closest to that requested is returned.If none of the keys in the\n        collection match the regex, indicating that the keys are not date/time-based,\n        a ``ValueError`` is raised.\n\n        Parameters\n        ----------\n        time : ``datetime.datetime``\n            The desired time\n        regex : str, optional\n            The regular expression to use to extract date/time information from the key. If\n            given, this should contain named groups: 'year', 'month', 'day', 'hour', 'minute',\n            'second', and 'microsecond', as appropriate. When a match is found, any of those\n            groups missing from the pattern will be assigned a value of 0. The default pattern\n            looks for patterns like: 20171118_2356.\n\n        Returns\n        -------\n            The value with a time closest to that desired"
  },
  {
    "code": "def load_py(stream, filepath=None):\n    with add_sys_paths(config.package_definition_build_python_paths):\n        return _load_py(stream, filepath=filepath)",
    "docstring": "Load python-formatted data from a stream.\n\n    Args:\n        stream (file-like object).\n\n    Returns:\n        dict."
  },
  {
    "code": "def _quote(str, LegalChars=_LegalChars):\n    r\n    if all(c in LegalChars for c in str):\n        return str\n    else:\n        return '\"' + _nulljoin(_Translator.get(s, s) for s in str) + '\"'",
    "docstring": "r\"\"\"Quote a string for use in a cookie header.\n\n    If the string does not need to be double-quoted, then just return the\n    string.  Otherwise, surround the string in doublequotes and quote\n    (with a \\) special characters."
  },
  {
    "code": "async def is_pairwise_exists(wallet_handle: int,\n                             their_did: str) -> bool:\n    logger = logging.getLogger(__name__)\n    logger.debug(\"is_pairwise_exists: >>> wallet_handle: %r, their_did: %r\",\n                 wallet_handle,\n                 their_did)\n    if not hasattr(is_pairwise_exists, \"cb\"):\n        logger.debug(\"is_pairwise_exists: Creating callback\")\n        is_pairwise_exists.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_bool))\n    c_wallet_handle = c_int32(wallet_handle)\n    c_their_did = c_char_p(their_did.encode('utf-8'))\n    res = await do_call('indy_is_pairwise_exists',\n                        c_wallet_handle,\n                        c_their_did,\n                        is_pairwise_exists.cb)\n    logger.debug(\"is_pairwise_exists: <<< res: %r\", res)\n    return res",
    "docstring": "Check if pairwise is exists.\n\n    :param wallet_handle: wallet handler (created by open_wallet).\n    :param their_did: encoded Did.\n    :return: true - if pairwise is exists, false - otherwise"
  },
  {
    "code": "def executions(self):\n        if self._executions is None:\n            self._executions = ExecutionList(self._version, flow_sid=self._solution['sid'], )\n        return self._executions",
    "docstring": "Access the executions\n\n        :returns: twilio.rest.studio.v1.flow.execution.ExecutionList\n        :rtype: twilio.rest.studio.v1.flow.execution.ExecutionList"
  },
  {
    "code": "def pending():\n    upgrader = InvenioUpgrader()\n    logger = upgrader.get_logger()\n    try:\n        upgrades = upgrader.get_upgrades()\n        if not upgrades:\n            logger.info(\"All upgrades have been applied.\")\n            return\n        logger.info(\"Following upgrade(s) are ready to be applied:\")\n        for u in upgrades:\n            logger.info(\n                \" * {0} {1}\".format(u.name, u.info))\n    except RuntimeError as e:\n        for msg in e.args:\n            logger.error(unicode(msg))\n        raise",
    "docstring": "Command for showing upgrades ready to be applied."
  },
  {
    "code": "def get_utt_regions(self):\n        regions = []\n        current_offset = 0\n        for utt_idx in sorted(self.utt_ids):\n            offset = current_offset\n            num_frames = []\n            refs = []\n            for cnt in self.containers:\n                num_frames.append(cnt.get(utt_idx).shape[0])\n                refs.append(cnt.get(utt_idx, mem_map=True))\n            if len(set(num_frames)) != 1:\n                raise ValueError('Utterance {} has not the same number of frames in all containers!'.format(utt_idx))\n            num_chunks = math.ceil(num_frames[0] / float(self.frames_per_chunk))\n            region = (offset, num_chunks, refs)\n            regions.append(region)\n            current_offset += num_chunks\n        return regions",
    "docstring": "Return the regions of all utterances, assuming all utterances are concatenated.\n        It is assumed that the utterances are sorted in ascending order for concatenation.\n\n        A region is defined by offset (in chunks), length (num-chunks) and\n        a list of references to the utterance datasets in the containers.\n\n        Returns:\n            list: List of with a tuple for every utterances containing the region info."
  },
  {
    "code": "def tempput(local_path=None, remote_path=None, use_sudo=False,\n            mirror_local_mode=False, mode=None):\n    import warnings\n    warnings.simplefilter('ignore', RuntimeWarning)\n    if remote_path is None:\n        remote_path = os.tempnam()\n    put(local_path, remote_path, use_sudo, mirror_local_mode, mode)\n    yield remote_path\n    run(\"rm '{}'\".format(remote_path))",
    "docstring": "Put a file to remote and remove it afterwards"
  },
  {
    "code": "def GetQueryValuesFromDict(cls, d, version=sorted(_SERVICE_MAP.keys())[-1]):\n    return [{\n        'key': key,\n        'value': cls.GetValueRepresentation(value, version)\n    } for key, value in d.iteritems()]",
    "docstring": "Converts a dict of python types into a list of PQL types.\n\n    Args:\n      d: A dictionary of variable names to python types.\n      version: A string identifying the Ad Manager version the values object\n          is compatible with. This defaults to what is currently the latest\n          version. This will be updated in future releases to point to what is\n          then the latest version.\n\n    Returns:\n      A list of variables formatted for PQL statements which are compatible with\n      a particular API version."
  },
  {
    "code": "def _selectedLinesRange(self):\n        (startLine, startCol), (endLine, endCol) = self._qpart.selectedPosition\n        start = min(startLine, endLine)\n        end = max(startLine, endLine)\n        return start, end",
    "docstring": "Selected lines range for line manipulation methods"
  },
  {
    "code": "def getBitmap(self):\n        return PlatformManager.getBitmapFromRect(self.x, self.y, self.w, self.h)",
    "docstring": "Captures screen area of this region, at least the part that is on the screen\n\n        Returns image as numpy array"
  },
  {
    "code": "def _typedef_code(t, base=0, refs=None, kind=_kind_static, heap=False):\n    v = _Typedef(base=_basicsize(t, base=base),\n                 refs=refs,\n                 both=False, kind=kind, type=t)\n    v.save(t, base=base, heap=heap)\n    return v",
    "docstring": "Add new typedef for code only."
  },
  {
    "code": "def get_tags(self, name):\n        tags = list()\n        for tag in self._tags:\n            if tag[0] == name:\n                tags.append(tag[1])\n        return tags",
    "docstring": "Returns a list of tags.\n\n        @param str name: The name of the tag.\n\n        :rtype: list[str]"
  },
  {
    "code": "def set_goterm(self, go2obj):\n        if self.GO in go2obj:\n            goterm = go2obj[self.GO]\n            self.goterm = goterm\n            self.name = goterm.name\n            self.depth = goterm.depth\n            self.NS = self.namespace2NS[self.goterm.namespace]",
    "docstring": "Set goterm and copy GOTerm's name and namespace."
  },
  {
    "code": "def fdfilter(data, *filt, **kwargs):\n    inplace = kwargs.pop('inplace', False)\n    analog = kwargs.pop('analog', False)\n    fs = kwargs.pop('sample_rate', None)\n    if kwargs:\n        raise TypeError(\"filter() got an unexpected keyword argument '%s'\"\n                        % list(kwargs.keys())[0])\n    if fs is None:\n        fs = 2 * (data.shape[-1] * data.df).to('Hz').value\n    form, filt = parse_filter(filt, analog=analog, sample_rate=fs)\n    lti = signal.lti(*filt)\n    freqs = data.frequencies.value.copy()\n    fresp = numpy.nan_to_num(abs(lti.freqresp(w=freqs)[1]))\n    if inplace:\n        data *= fresp\n        return data\n    new = data * fresp\n    return new",
    "docstring": "Filter a frequency-domain data object\n\n    See Also\n    --------\n    gwpy.frequencyseries.FrequencySeries.filter\n    gwpy.spectrogram.Spectrogram.filter"
  },
  {
    "code": "def callback(self):\n        if self._callback_func and callable(self._callback_func):\n            self._callback_func(self)",
    "docstring": "Run callback."
  },
  {
    "code": "def build_param_schema(schema, param_type):\n    properties = filter_params_by_type(schema, param_type)\n    if not properties:\n        return\n    return {\n        'type': 'object',\n        'properties': dict((p['name'], p) for p in properties),\n        'additionalProperties': param_type == 'header',\n    }",
    "docstring": "Turn a swagger endpoint schema into an equivalent one to validate our\n    request.\n\n    As an example, this would take this swagger schema:\n        {\n            \"paramType\": \"query\",\n            \"name\": \"query\",\n            \"description\": \"Location to query\",\n            \"type\": \"string\",\n            \"required\": true\n        }\n    To this jsonschema:\n        {\n            \"type\": \"object\",\n            \"additionalProperties\": \"False\",\n            \"properties:\": {\n                \"description\": \"Location to query\",\n                \"type\": \"string\",\n                \"required\": true\n            }\n        }\n    Which we can then validate against a JSON object we construct from the\n    pyramid request."
  },
  {
    "code": "def find_tie_breaker(self, candidate_ids):\n        for candidate_aggregates in reversed(self.round_candidate_aggregates):\n            candidates_on_vote = defaultdict(int)\n            for candidate_id in candidate_ids:\n                votes = candidate_aggregates.get_vote_count(candidate_id)\n                candidates_on_vote[votes] += 1\n            if max(candidates_on_vote.values()) == 1:\n                return candidate_aggregates",
    "docstring": "finds a round in the count history in which the candidate_ids each had different vote counts\n        if no such round exists, returns None"
  },
  {
    "code": "def clear_cache(self):\n        self.raw_packet_cache = None\n        for _, fval in six.iteritems(self.fields):\n            if isinstance(fval, Packet):\n                fval.clear_cache()\n        self.payload.clear_cache()",
    "docstring": "Clear the raw packet cache for the field and all its subfields"
  },
  {
    "code": "def predict(self, text):\n        pred = self.predict_proba(text)\n        tags = self._get_tags(pred)\n        return tags",
    "docstring": "Predict using the model.\n\n        Args:\n            text: string, the input text.\n\n        Returns:\n            tags: list, shape = (num_words,)\n            Returns predicted values."
  },
  {
    "code": "def quick_send(self, send, echo=None, loglevel=logging.INFO):\n\t\tshutit = self.shutit\n\t\tshutit.log('Quick send: ' + send, level=loglevel)\n\t\tres = self.sendline(ShutItSendSpec(self,\n\t\t                                    send=send,\n\t\t                                    check_exit=False,\n\t\t                                    echo=echo,\n\t\t                                    fail_on_empty_before=False,\n\t\t                                    record_command=False,\n\t\t                                    ignore_background=True))\n\t\tif not res:\n\t\t\tself.expect(self.default_expect)",
    "docstring": "Quick and dirty send that ignores background tasks. Intended for internal use."
  },
  {
    "code": "def requiredIdr(self,\n                    idr: Identifier=None,\n                    alias: str=None):\n        if idr:\n            if ':' in idr:\n                idr = idr.split(':')[1]\n        else:\n            idr = self.aliasesToIds[alias] if alias else self.defaultId\n        if not idr:\n            raise EmptyIdentifier\n        return idr",
    "docstring": "Checks whether signer identifier specified, or can it be\n        inferred from alias or can be default used instead\n\n        :param idr:\n        :param alias:\n        :param other:\n\n        :return: signer identifier"
  },
  {
    "code": "def load_newsgroups():\n    dataset = datasets.fetch_20newsgroups()\n    return Dataset(load_newsgroups.__doc__, np.array(dataset.data), dataset.target,\n                   accuracy_score, stratify=True)",
    "docstring": "20 News Groups Dataset.\n\n    The data of this dataset is a 1d numpy array vector containing the texts\n    from 11314 newsgroups posts, and the target is a 1d numpy integer array\n    containing the label of one of the 20 topics that they are about."
  },
  {
    "code": "def get_market_tops(symbols=None, **kwargs):\r\n    import warnings\r\n    warnings.warn(WNG_MSG % (\"get_market_tops\", \"iexdata.get_tops\"))\r\n    return TOPS(symbols, **kwargs).fetch()",
    "docstring": "MOVED to iexfinance.iexdata.get_tops"
  },
  {
    "code": "def opens(self, date=\"\", page=1, page_size=1000, order_field=\"date\", order_direction=\"asc\"):\n        params = {\n            \"date\": date,\n            \"page\": page,\n            \"pagesize\": page_size,\n            \"orderfield\": order_field,\n            \"orderdirection\": order_direction}\n        response = self._get(self.uri_for(\"opens\"), params=params)\n        return json_to_py(response)",
    "docstring": "Retrieves the opens for this campaign."
  },
  {
    "code": "def fix_insert_size(in_bam, config):\n    fixed_file = os.path.splitext(in_bam)[0] + \".pi_fixed.bam\"\n    if file_exists(fixed_file):\n        return fixed_file\n    header_file = os.path.splitext(in_bam)[0] + \".header.sam\"\n    read_length = bam.estimate_read_length(in_bam)\n    bam_handle= bam.open_samfile(in_bam)\n    header = bam_handle.header.copy()\n    rg_dict = header['RG'][0]\n    if 'PI' not in rg_dict:\n        return in_bam\n    PI = int(rg_dict.get('PI'))\n    PI = PI + 2*read_length\n    rg_dict['PI'] = PI\n    header['RG'][0] = rg_dict\n    with pysam.Samfile(header_file, \"wb\", header=header) as out_handle:\n        with bam.open_samfile(in_bam) as in_handle:\n            for record in in_handle:\n                out_handle.write(record)\n    shutil.move(header_file, fixed_file)\n    return fixed_file",
    "docstring": "Tophat sets PI in the RG to be the inner distance size, but the SAM spec\n    states should be the insert size. This fixes the RG in the alignment\n    file generated by Tophat header to match the spec"
  },
  {
    "code": "def call_closers(self, client, clients_list):\n        for func in self.closers:\n            func(client, clients_list)",
    "docstring": "Calls closers callbacks"
  },
  {
    "code": "def _extract_command_with_args(cmd):\n    def _isint(value):\n        try:\n            int(value)\n            return True\n        except ValueError:\n            return False\n    equal_sign = cmd.find('=')\n    if equal_sign == -1:\n        return cmd, []\n    command = cmd[0:equal_sign]\n    args = cmd[equal_sign+1:].split(',')\n    converted = [x if not _isint(x) else int(x) for x in args]\n    return command, converted",
    "docstring": "Parse input command with arguments.\n\n    Parses the input command in such a way that the user may\n    provide additional argument to the command. The format used is this:\n      command=arg1,arg2,arg3,...\n    all the additional arguments are passed as arguments to the target\n    method."
  },
  {
    "code": "def _calcCTRBUF(self):\n        self.ctr_cks = self.encrypt(struct.pack(\"Q\", self.ctr_iv))\n        self.ctr_iv += 1\n        self.ctr_pos = 0",
    "docstring": "Calculates one block of CTR keystream"
  },
  {
    "code": "def translate(\n        self,\n        values,\n        target_language=None,\n        format_=None,\n        source_language=None,\n        customization_ids=(),\n        model=None,\n    ):\n        single_value = False\n        if isinstance(values, six.string_types):\n            single_value = True\n            values = [values]\n        if target_language is None:\n            target_language = self.target_language\n        if isinstance(customization_ids, six.string_types):\n            customization_ids = [customization_ids]\n        data = {\n            \"target\": target_language,\n            \"q\": values,\n            \"cid\": customization_ids,\n            \"format\": format_,\n            \"source\": source_language,\n            \"model\": model,\n        }\n        response = self._connection.api_request(method=\"POST\", path=\"\", data=data)\n        translations = response.get(\"data\", {}).get(\"translations\", ())\n        if len(values) != len(translations):\n            raise ValueError(\n                \"Expected iterations to have same length\", values, translations\n            )\n        for value, translation in six.moves.zip(values, translations):\n            translation[\"input\"] = value\n        if single_value:\n            return translations[0]\n        else:\n            return translations",
    "docstring": "Translate a string or list of strings.\n\n        See https://cloud.google.com/translate/docs/translating-text\n\n        :type values: str or list\n        :param values: String or list of strings to translate.\n\n        :type target_language: str\n        :param target_language: The language to translate results into. This\n                                is required by the API and defaults to\n                                the target language of the current instance.\n\n        :type format_: str\n        :param format_: (Optional) One of ``text`` or ``html``, to specify\n                        if the input text is plain text or HTML.\n\n        :type source_language: str\n        :param source_language: (Optional) The language of the text to\n                                be translated.\n\n        :type customization_ids: str or list\n        :param customization_ids: (Optional) ID or list of customization IDs\n                                  for translation. Sets the ``cid`` parameter\n                                  in the query.\n\n        :type model: str\n        :param model: (Optional) The model used to translate the text, such\n                      as ``'base'`` or ``'nmt'``.\n\n        :rtype: str or list\n        :returns: A list of dictionaries for each queried value. Each\n                  dictionary typically contains three keys (though not\n                  all will be present in all cases)\n\n                  * ``detectedSourceLanguage``: The detected language (as an\n                    ISO 639-1 language code) of the text.\n                  * ``translatedText``: The translation of the text into the\n                    target language.\n                  * ``input``: The corresponding input value.\n                  * ``model``: The model used to translate the text.\n\n                  If only a single value is passed, then only a single\n                  dictionary will be returned.\n        :raises: :class:`~exceptions.ValueError` if the number of\n                 values and translations differ."
  },
  {
    "code": "def true_num_genes(model, custom_spont_id=None):\n    true_num = 0\n    for gene in model.genes:\n        if not is_spontaneous(gene, custom_id=custom_spont_id):\n            true_num += 1\n    return true_num",
    "docstring": "Return the number of genes in a model ignoring spontaneously labeled genes.\n\n    Args:\n        model (Model):\n        custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001``\n\n    Returns:\n        int: Number of genes excluding spontaneous genes"
  },
  {
    "code": "def load_data(self):\r\n        for index in reversed(self.stack_history):\r\n            text = self.tabs.tabText(index)\r\n            text = text.replace('&', '')\r\n            item = QListWidgetItem(ima.icon('TextFileIcon'), text)\r\n            self.addItem(item)",
    "docstring": "Fill ListWidget with the tabs texts.\r\n\r\n        Add elements in inverse order of stack_history."
  },
  {
    "code": "def status_delete(self, id):\n        id = self.__unpack_id(id)\n        url = '/api/v1/statuses/{0}'.format(str(id))\n        self.__api_request('DELETE', url)",
    "docstring": "Delete a status"
  },
  {
    "code": "def children(self, **kwargs):\n        if not kwargs:\n            if not self._cached_children:\n                self._cached_children = list(self._client.parts(parent=self.id, category=self.category))\n            return self._cached_children\n        else:\n            return self._client.parts(parent=self.id, category=self.category, **kwargs)",
    "docstring": "Retrieve the children of this `Part` as `Partset`.\n\n        When you call the :func:`Part.children()` method without any additional filtering options for the children,\n        the children are cached to help speed up subsequent calls to retrieve the children. The cached children are\n        returned as a list and not as a `Partset`.\n\n        When you *do provide* additional keyword arguments (kwargs) that act as a specific children filter, the\n        cached children are _not_ used and a separate API call is made to retrieve only those children.\n\n        :param kwargs: Additional search arguments to search for, check :class:`pykechain.Client.parts`\n                       for additional info\n        :type kwargs: dict\n        :return: a set of `Parts` as a :class:`PartSet`. Will be empty if no children. Will be a `List` if the\n                 children are retrieved from the cached children.\n        :raises APIError: When an error occurs.\n\n        Example\n        -------\n\n        A normal call, which caches all children of the bike. If you call `bike.children` twice only 1 API call is made.\n\n        >>> bike = project.part('Bike')\n        >>> direct_descendants_of_bike = bike.children()\n\n        An example with providing additional part search parameters 'name__icontains'. Children are retrieved from the\n        API, not the bike's internal (already cached in previous example) cache.\n\n        >>> bike = project.part('Bike')\n        >>> wheel_children_of_bike = bike.children(name__icontains='wheel')"
  },
  {
    "code": "def scale_v2(vec, amount):\n    return Vec2(vec.x * amount, vec.y * amount)",
    "docstring": "Return a new Vec2 with x and y from vec and multiplied by amount."
  },
  {
    "code": "def spectrum_to_xyz100(spectrum, observer):\n    lambda_o, data_o = observer\n    lambda_s, data_s = spectrum\n    lmbda = numpy.sort(numpy.unique(numpy.concatenate([lambda_o, lambda_s])))\n    assert lmbda[0] < 361e-9\n    assert lmbda[-1] > 829e-9\n    idata_o = numpy.array([numpy.interp(lmbda, lambda_o, dt) for dt in data_o])\n    idata_s = numpy.interp(lmbda, lambda_s, data_s)\n    delta = numpy.zeros(len(lmbda))\n    diff = lmbda[1:] - lmbda[:-1]\n    delta[1:] += diff\n    delta[:-1] += diff\n    delta /= 2\n    values = numpy.dot(idata_o, idata_s * delta)\n    return values * 100",
    "docstring": "Computes the tristimulus values XYZ from a given spectrum for a given\n    observer via\n\n    X_i = int_lambda spectrum_i(lambda) * observer_i(lambda) dlambda.\n\n    In section 7, the technical report CIE Standard Illuminants for\n    Colorimetry, 1999, gives a recommendation on how to perform the\n    computation."
  },
  {
    "code": "def infix(tokens, operator_table):\n    operator, matched_tokens = operator_table.infix.match(tokens)\n    if operator:\n        return TokenMatch(operator, None, matched_tokens)",
    "docstring": "Match an infix of an operator."
  },
  {
    "code": "def repr(tick, pack=False):\n    if tick == 0x7fffffffffffffff:\n        return '?'\n    dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(milliseconds=tick)\n    millis = dt.microsecond / 1000\n    if pack:\n        return '%d%.2d%.2d%.2d%.2d%.2d%.3d' % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, millis)\n    return '%d/%.2d/%.2d %.2d:%.2d:%.2d.%.3d' % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, millis)",
    "docstring": "Return a date string for an epoch-millis timestamp.\n\n    Args:\n        tick (int): The timestamp in milliseconds since the epoch.\n\n    Returns:\n        (str):  A date time string"
  },
  {
    "code": "def _check_rename_constraints(self, old_key, new_key):\n        if new_key in self.relations:\n            dbt.exceptions.raise_cache_inconsistent(\n                'in rename, new key {} already in cache: {}'\n                .format(new_key, list(self.relations.keys()))\n            )\n        if old_key not in self.relations:\n            logger.debug(\n                'old key {} not found in self.relations, assuming temporary'\n                .format(old_key)\n            )\n            return False\n        return True",
    "docstring": "Check the rename constraints, and return whether or not the rename\n        can proceed.\n\n        If the new key is already present, that is an error.\n        If the old key is absent, we debug log and return False, assuming it's\n        a temp table being renamed.\n\n        :param _ReferenceKey old_key: The existing key, to rename from.\n        :param _ReferenceKey new_key: The new key, to rename to.\n        :return bool: If the old relation exists for renaming.\n        :raises InternalError: If the new key is already present."
  },
  {
    "code": "def addCallback(cls, eventType, func, record=None, once=False):\n        callbacks = cls.callbacks()\n        callbacks.setdefault(eventType, [])\n        callbacks[eventType].append((func, record, once))",
    "docstring": "Adds a callback method to the class.  When an event of the given type is triggered, any registered\n        callback will be executed.\n\n        :param  eventType: <str>\n        :param  func: <callable>"
  },
  {
    "code": "def delete_grade_entry(self, grade_entry_id):\n        collection = JSONClientValidated('grading',\n                                         collection='GradeEntry',\n                                         runtime=self._runtime)\n        if not isinstance(grade_entry_id, ABCId):\n            raise errors.InvalidArgument('the argument is not a valid OSID Id')\n        grade_entry_map = collection.find_one(\n            dict({'_id': ObjectId(grade_entry_id.get_identifier())},\n                 **self._view_filter()))\n        objects.GradeEntry(osid_object_map=grade_entry_map, runtime=self._runtime, proxy=self._proxy)._delete()\n        collection.delete_one({'_id': ObjectId(grade_entry_id.get_identifier())})",
    "docstring": "Deletes the ``GradeEntry`` identified by the given ``Id``.\n\n        arg:    grade_entry_id (osid.id.Id): the ``Id`` of the\n                ``GradeEntry`` to delete\n        raise:  NotFound - a ``GradeEntry`` was not found identified by\n                the given ``Id``\n        raise:  NullArgument - ``grade_entry_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def addDelay(self, urlPattern=\"\", delay=0, httpMethod=None):\n        print(\"addDelay is deprecated please use delays instead\")\n        delay = {\"urlPattern\": urlPattern, \"delay\": delay}\n        if httpMethod:\n            delay[\"httpMethod\"] = httpMethod\n        return self.delays(delays={\"data\": [delay]})",
    "docstring": "Adds delays."
  },
  {
    "code": "def query_versions_pypi(self, package_name):\n        if not package_name in self.pkg_list:\n            self.logger.debug(\"Package %s not in cache, querying PyPI...\" \\\n                    % package_name)\n            self.fetch_pkg_list()\n        versions = []\n        for pypi_pkg in self.pkg_list:\n            if pypi_pkg.lower() == package_name.lower():\n                if self.debug:\n                    self.logger.debug(\"DEBUG: %s\" % package_name)\n                versions = self.package_releases(pypi_pkg)\n                package_name = pypi_pkg\n                break\n        return (package_name, versions)",
    "docstring": "Fetch list of available versions for a package from The CheeseShop"
  },
  {
    "code": "def _get_freq(freqfunc, m1, m2, s1z, s2z):\n    m1kg = float(m1) * lal.MSUN_SI\n    m2kg = float(m2) * lal.MSUN_SI\n    return lalsimulation.SimInspiralGetFrequency(\n        m1kg, m2kg, 0, 0, float(s1z), 0, 0, float(s2z), int(freqfunc))",
    "docstring": "Wrapper of the LALSimulation function returning the frequency\n    for a given frequency function and template parameters.\n\n    Parameters\n    ----------\n    freqfunc : lalsimulation FrequencyFunction wrapped object e.g.\n        lalsimulation.fEOBNRv2RD\n    m1 : float-ish, i.e. castable to float\n        First component mass in solar masses\n    m2 : float-ish\n        Second component mass in solar masses\n    s1z : float-ish\n        First component dimensionless spin S_1/m_1^2 projected onto L\n    s2z : float-ish\n        Second component dimensionless spin S_2/m_2^2 projected onto L\n\n    Returns\n    -------\n    f : float\n        Frequency in Hz"
  },
  {
    "code": "def build_docs(directory):\n    os.chdir(directory)\n    process = subprocess.Popen([\"make\", \"html\"], cwd=directory)\n    process.communicate()",
    "docstring": "Builds sphinx docs from a given directory."
  },
  {
    "code": "def imap_unordered(self, jobs, timeout=0.5):\n        timeout = max(timeout, 0.5)\n        jobs_iter = iter(jobs)\n        out_jobs = 0\n        job = None\n        while True:\n            if not self.closed and job is None:\n                try:\n                    job = jobs_iter.next()\n                except StopIteration:\n                    job = None\n                    self.close()\n            if job is not None:\n                try:\n                    self.put(job, True, timeout)\n                except Queue.Full:\n                    pass\n                else:\n                    job = None\n            for result in self.get_finished():\n                yield result\n            if self.closed and self._items == 0:\n                break\n            sleep(timeout)",
    "docstring": "A iterator over a set of jobs.\n\n        :param jobs: the items to pass through our function\n        :param timeout: timeout between polling queues\n\n        Results are yielded as soon as they are available in the output\n        queue (up to the discretisation provided by timeout). Since the\n        queues can be specified to have a maximum length, the consumption\n        of both the input jobs iterable and memory use in the output\n        queues are controlled."
  },
  {
    "code": "def add_predicate(self, pred_obj):\n        pred_id = pred_obj.get_id()\n        if not pred_id in self.idx:\n            pred_node = pred_obj.get_node()\n            self.node.append(pred_node)\n            self.idx[pred_id] = pred_node\n        else:\n            print('Error: trying to add new element, but id has already been given')",
    "docstring": "Adds a predicate object to the layer\n        @type pred_obj: L{Cpredicate}\n        @param pred_obj: the predicate object"
  },
  {
    "code": "def fuzzy_index_match(possiblities, label, **kwargs):\n    possibilities = list(possiblities)\n    if isinstance(label, basestring):\n        return fuzzy_get(possibilities, label, **kwargs)\n    if isinstance(label, int):\n        return possibilities[label]\n    if isinstance(label, list):\n        return [fuzzy_get(possibilities, lbl) for lbl in label]",
    "docstring": "Find the closest matching column label, key, or integer indexed value\n\n    Returns:\n      type(label): sequence of immutable objects corresponding to best matches to each object in label\n              if label is an int returns the object (value) in the list of possibilities at that index\n              if label is a str returns the closest str match in possibilities\n\n    >>> from collections import OrderedDict as odict\n    >>> fuzzy_index_match(pd.DataFrame(pd.np.random.randn(9,4), columns=list('ABCD'), index=range(9)), 'b')\n    'B'\n    >>> fuzzy_index_match(odict(zip('12345','ABCDE')), 'r2d2')\n    '2'\n    >>> fuzzy_index_match(odict(zip('12345','ABCDE')), 1)\n    '2'\n    >>> fuzzy_index_match(odict(zip('12345','ABCDE')), -1)\n    '5'\n    >>> fuzzy_index_match(odict(zip(range(4),'FOUR')), -4)\n    0"
  },
  {
    "code": "def call_pre_hook(awsclient, cloudformation):\n    if not hasattr(cloudformation, 'pre_hook'):\n        return\n    hook_func = getattr(cloudformation, 'pre_hook')\n    if not hook_func.func_code.co_argcount:\n        hook_func()\n    else:\n        log.error('pre_hock can not have any arguments. The pre_hook it is ' +\n                  'executed BEFORE config is read')",
    "docstring": "Invoke the pre_hook BEFORE the config is read.\n\n    :param awsclient:\n    :param cloudformation:"
  },
  {
    "code": "def get_targets(self, config):\n        return {urllib.parse.urljoin(self.url, attrs['href'])\n                for attrs in self._targets\n                if self._check_rel(attrs, config.rel_whitelist, config.rel_blacklist)\n                and self._domain_differs(attrs['href'])}",
    "docstring": "Given an Entry object, return all of the outgoing links."
  },
  {
    "code": "def center_of_mass(self):\n        weights = [s.species.weight for s in self]\n        center_of_mass = np.average(self.frac_coords,\n                                    weights=weights, axis=0)\n        return center_of_mass",
    "docstring": "Calculates the center of mass of the slab"
  },
  {
    "code": "def get_argument_parser():\n    desc = 'Filter FASTA file by chromosome names.'\n    parser = cli.get_argument_parser(desc=desc)\n    parser.add_argument(\n        '-f', '--fasta-file', default='-', type=str, help=textwrap.dedent(\n))\n    parser.add_argument(\n        '-s', '--species', type=str,\n        choices=sorted(ensembl.SPECIES_CHROMPAT.keys()),\n        default='human', help=textwrap.dedent(\n)\n    )\n    parser.add_argument(\n        '-c', '--chromosome-pattern', type=str, required=False,\n        default=None, help=textwrap.dedent(\n)\n    )\n    parser.add_argument(\n        '-o', '--output-file', type=str, required=True,\n        help=textwrap.dedent(\n))\n    parser = cli.add_reporting_args(parser)\n    return parser",
    "docstring": "Returns an argument parser object for the script."
  },
  {
    "code": "def get_web_auth_session_key(self, url, token=\"\"):\n        session_key, _username = self.get_web_auth_session_key_username(url, token)\n        return session_key",
    "docstring": "Retrieves the session key of a web authorization process by its URL."
  },
  {
    "code": "def _to_json_default(obj):\n    if isinstance(obj, datetime.datetime):\n        return obj.isoformat()\n    if isinstance(obj, uuid.UUID):\n        return str(obj)\n    if hasattr(obj, 'item'):\n        return obj.item()\n    try:\n        return obj.id\n    except Exception:\n        raise TypeError('{obj} is not JSON serializable'.format(obj=repr(obj)))",
    "docstring": "Helper to convert non default objects to json.\n\n    Usage:\n        simplejson.dumps(data, default=_to_json_default)"
  },
  {
    "code": "async def _send_sysex(self, sysex_command, sysex_data=None):\n        if not sysex_data:\n            sysex_data = []\n        sysex_message = chr(PrivateConstants.START_SYSEX)\n        sysex_message += chr(sysex_command)\n        if len(sysex_data):\n            for d in sysex_data:\n                sysex_message += chr(d)\n        sysex_message += chr(PrivateConstants.END_SYSEX)\n        for data in sysex_message:\n            await self.write(data)",
    "docstring": "This is a private utility method.\n        This method sends a sysex command to Firmata.\n\n        :param sysex_command: sysex command\n\n        :param sysex_data: data for command\n\n        :returns : No return value."
  },
  {
    "code": "def _extract_lookup(self, key):\n        parts = key.split('__')\n        op = 'exact' if len(parts) == 1 else parts[1]\n        return parts[0], self.get_lookup(op)",
    "docstring": "Extract lookup method based on key name format"
  },
  {
    "code": "def S(Document, *fields):\n\tresult = []\n\tfor field in fields:\n\t\tif isinstance(field, tuple):\n\t\t\tfield, direction = field\n\t\t\tresult.append((field, direction))\n\t\t\tcontinue\n\t\tdirection = ASCENDING\n\t\tif not field.startswith('__'):\n\t\t\tfield = field.replace('__', '.')\n\t\tif field[0] == '-':\n\t\t\tdirection = DESCENDING\n\t\tif field[0] in ('+', '-'):\n\t\t\tfield = field[1:]\n\t\t_field = traverse(Document, field, default=None)\n\t\tresult.append(((~_field) if _field else field, direction))\n\treturn result",
    "docstring": "Generate a MongoDB sort order list using the Django ORM style."
  },
  {
    "code": "def write(self, pkt):\n        if isinstance(pkt, bytes):\n            if not self.header_present:\n                self._write_header(pkt)\n            self._write_packet(pkt)\n        else:\n            pkt = pkt.__iter__()\n            for p in pkt:\n                if not self.header_present:\n                    self._write_header(p)\n                self._write_packet(p)",
    "docstring": "Writes a Packet or bytes to a pcap file.\n\n        :param pkt: Packet(s) to write (one record for each Packet), or raw\n                    bytes to write (as one record).\n        :type pkt: iterable[Packet], Packet or bytes"
  },
  {
    "code": "def _send_batch(self):\n        if (not self._batch_reqs) or self._batch_send_d:\n            return\n        requests, self._batch_reqs = self._batch_reqs, []\n        self._waitingByteCount = 0\n        self._waitingMsgCount = 0\n        d_list = []\n        for req in requests:\n            d_list.append(self._next_partition(req.topic, req.key))\n        d = self._batch_send_d = Deferred()\n        d.addCallback(lambda r: DeferredList(d_list, consumeErrors=True))\n        d.addCallback(self._send_requests, requests)\n        d.addBoth(self._complete_batch_send)\n        d.addBoth(self._check_send_batch)\n        d.callback(None)",
    "docstring": "Send the waiting messages, if there are any, and we can...\n\n        This is called by our LoopingCall every send_every_t interval, and\n        from send_messages everytime we have enough messages to send.\n        This is also called from py:method:`send_messages` via\n        py:method:`_check_send_batch` if there are enough messages/bytes\n        to require a send.\n        Note, the send will be delayed (triggered by completion or failure of\n        previous) if we are currently trying to complete the last batch send."
  },
  {
    "code": "def register_user_type(self, keyspace, user_type, klass):\n        if self.protocol_version < 3:\n            log.warning(\"User Type serialization is only supported in native protocol version 3+ (%d in use). \"\n                        \"CQL encoding for simple statements will still work, but named tuples will \"\n                        \"be returned when reading type %s.%s.\", self.protocol_version, keyspace, user_type)\n        self._user_types[keyspace][user_type] = klass\n        for session in tuple(self.sessions):\n            session.user_type_registered(keyspace, user_type, klass)\n        UserType.evict_udt_class(keyspace, user_type)",
    "docstring": "Registers a class to use to represent a particular user-defined type.\n        Query parameters for this user-defined type will be assumed to be\n        instances of `klass`.  Result sets for this user-defined type will\n        be instances of `klass`.  If no class is registered for a user-defined\n        type, a namedtuple will be used for result sets, and non-prepared\n        statements may not encode parameters for this type correctly.\n\n        `keyspace` is the name of the keyspace that the UDT is defined in.\n\n        `user_type` is the string name of the UDT to register the mapping\n        for.\n\n        `klass` should be a class with attributes whose names match the\n        fields of the user-defined type.  The constructor must accepts kwargs\n        for each of the fields in the UDT.\n\n        This method should only be called after the type has been created\n        within Cassandra.\n\n        Example::\n\n            cluster = Cluster(protocol_version=3)\n            session = cluster.connect()\n            session.set_keyspace('mykeyspace')\n            session.execute(\"CREATE TYPE address (street text, zipcode int)\")\n            session.execute(\"CREATE TABLE users (id int PRIMARY KEY, location address)\")\n\n            # create a class to map to the \"address\" UDT\n            class Address(object):\n\n                def __init__(self, street, zipcode):\n                    self.street = street\n                    self.zipcode = zipcode\n\n            cluster.register_user_type('mykeyspace', 'address', Address)\n\n            # insert a row using an instance of Address\n            session.execute(\"INSERT INTO users (id, location) VALUES (%s, %s)\",\n                            (0, Address(\"123 Main St.\", 78723)))\n\n            # results will include Address instances\n            results = session.execute(\"SELECT * FROM users\")\n            row = results[0]\n            print row.id, row.location.street, row.location.zipcode"
  },
  {
    "code": "def transform(self, Y):\n        r\n        check_is_fitted(self, 'X_fit_')\n        n_samples_x, n_features = self.X_fit_.shape\n        Y = numpy.asarray(Y)\n        if Y.shape[1] != n_features:\n            raise ValueError('expected array with %d features, but got %d' % (n_features, Y.shape[1]))\n        n_samples_y = Y.shape[0]\n        mat = numpy.zeros((n_samples_y, n_samples_x), dtype=float)\n        continuous_ordinal_kernel_with_ranges(Y[:, self._numeric_columns].astype(numpy.float64),\n                                              self.X_fit_[:, self._numeric_columns].astype(numpy.float64),\n                                              self._numeric_ranges, mat)\n        if len(self._nominal_columns) > 0:\n            _nominal_kernel(Y[:, self._nominal_columns],\n                            self.X_fit_[:, self._nominal_columns],\n                            mat)\n        mat /= n_features\n        return mat",
    "docstring": "r\"\"\"Compute all pairwise distances between `self.X_fit_` and `Y`.\n\n        Parameters\n        ----------\n        y : array-like, shape = (n_samples_y, n_features)\n\n        Returns\n        -------\n        kernel : ndarray, shape = (n_samples_y, n_samples_X_fit\\_)\n            Kernel matrix. Values are normalized to lie within [0, 1]."
  },
  {
    "code": "def _compute_nearest_weights_edge(idcs, ndist, variant):\n    lo = (ndist < 0)\n    hi = (ndist > 1)\n    if variant == 'left':\n        w_lo = np.where(ndist <= 0.5, 1.0, 0.0)\n    else:\n        w_lo = np.where(ndist < 0.5, 1.0, 0.0)\n    w_lo[lo] = 0\n    w_lo[hi] = 1\n    if variant == 'left':\n        w_hi = np.where(ndist <= 0.5, 0.0, 1.0)\n    else:\n        w_hi = np.where(ndist < 0.5, 0.0, 1.0)\n    w_hi[lo] = 1\n    w_hi[hi] = 0\n    edge = [idcs, idcs + 1]\n    edge[0][hi] = -1\n    edge[1][lo] = 0\n    return w_lo, w_hi, edge",
    "docstring": "Helper for nearest interpolation mimicing the linear case."
  },
  {
    "code": "def setOverlayFlag(self, ulOverlayHandle, eOverlayFlag, bEnabled):\n        fn = self.function_table.setOverlayFlag\n        result = fn(ulOverlayHandle, eOverlayFlag, bEnabled)\n        return result",
    "docstring": "Specify flag setting for a given overlay"
  },
  {
    "code": "def valid_backbone_bond_lengths(self, atol=0.1):\n        bond_lengths = self.backbone_bond_lengths\n        a1 = numpy.allclose(bond_lengths['n_ca'],\n                            [ideal_backbone_bond_lengths['n_ca']] * len(self),\n                            atol=atol)\n        a2 = numpy.allclose(bond_lengths['ca_c'],\n                            [ideal_backbone_bond_lengths['ca_c']] * len(self),\n                            atol=atol)\n        a3 = numpy.allclose(bond_lengths['c_o'],\n                            [ideal_backbone_bond_lengths['c_o']] * len(self),\n                            atol=atol)\n        a4 = numpy.allclose(bond_lengths['c_n'],\n                            [ideal_backbone_bond_lengths['c_n']] *\n                            (len(self) - 1),\n                            atol=atol)\n        return all([a1, a2, a3, a4])",
    "docstring": "True if all backbone bonds are within atol Angstroms of the expected distance.\n\n        Notes\n        -----\n        Ideal bond lengths taken from [1].\n\n        References\n        ----------\n        .. [1] Schulz, G. E, and R. Heiner Schirmer. Principles Of\n           Protein Structure. New York: Springer-Verlag, 1979.\n\n        Parameters\n        ----------\n        atol : float, optional\n            Tolerance value in Angstoms for the absolute deviation\n            away from ideal backbone bond lengths."
  },
  {
    "code": "def postprocess_periodical(marc_xml, mods, uuid, counter, url):\n    dom = double_linked_dom(mods)\n    add_missing_xml_attributes(dom, counter)\n    if uuid:\n        add_uuid(dom, uuid)\n    return dom.prettify()",
    "docstring": "Some basic postprocessing of the periodical publications.\n\n    Args:\n        marc_xml (str): Original Aleph record.\n        mods (str): XML string generated by XSLT template.\n        uuid (str): UUID of the package.\n        counter (int): Number of record, is added to XML headers.\n        url (str): URL of the publication (public or not).\n\n    Returns:\n        str: Updated XML."
  },
  {
    "code": "def _get_nsymop(self):\n        if self.centrosymmetric:\n            return 2 * len(self._rotations) * len(self._subtrans)\n        else:\n            return len(self._rotations) * len(self._subtrans)",
    "docstring": "Returns total number of symmetry operations."
  },
  {
    "code": "def find_path(self, test_function=None, on_targets=False):\n        assert self.has_referential_domain(), \"need context set\"\n        if not test_function:\n            test_function = lambda x, y: True\n        def find_path_inner(part, prefix):\n            name, structure = part\n            if test_function(name, structure):\n                yield prefix + [name]\n            if isinstance(structure, DictCell):\n                for sub_structure in structure:\n                    for prefix2 in find_path_inner(sub_structure,\\\n                            prefix[:] + [name]):\n                        yield prefix2\n        prefix = []\n        if on_targets:\n            results = []\n            for _, instance in self.iter_singleton_referents():\n                for part in instance:\n                    for entry in find_path_inner(part, prefix[:]):\n                        results.append(['target'] + entry)\n                while results:\n                    yield results.pop()\n                break\n        else:\n            for part in self:\n                for entry in find_path_inner(part, prefix[:]):\n                    yield entry",
    "docstring": "General helper method that iterates breadth-first over the referential_domain's\n        cells and returns a path where the test_function is True"
  },
  {
    "code": "def tags():\n    \"Get a set of tags for the current git repo.\"\n    result = [t.decode('ascii') for t in subprocess.check_output([\n        'git', 'tag'\n    ]).split(b\"\\n\")]\n    assert len(set(result)) == len(result)\n    return set(result)",
    "docstring": "Get a set of tags for the current git repo."
  },
  {
    "code": "def closeTab(self, item):\n        index = self.indexOf(item)\n        if index != -1:\n            self.tabCloseRequested.emit(index)",
    "docstring": "Requests a close for the inputed tab item.\n\n        :param      item | <XViewPanelItem>"
  },
  {
    "code": "def create(self, verbose=None):\n        if not self.email_enabled:\n            raise EmailNotEnabledError(\"See settings.EMAIL_ENABLED\")\n        response = requests.post(\n            self.api_url,\n            auth=(\"api\", self.api_key),\n            data={\n                \"address\": self.address,\n                \"name\": self.name,\n                \"description\": self.display_name,\n            },\n        )\n        if verbose:\n            sys.stdout.write(\n                f\"Creating mailing list {self.address}. \"\n                f\"Got response={response.status_code}.\\n\"\n            )\n        return response",
    "docstring": "Returns a response after attempting to create the list."
  },
  {
    "code": "def refreshLabels( self ):\r\n        itemCount = self.itemCount()\r\n        title = self.itemsTitle()\r\n        if ( not itemCount ):\r\n            self._itemsLabel.setText(' %s per page' % title)\r\n        else:\r\n            msg = ' %s per page, %i %s total' % (title, itemCount, title)\r\n            self._itemsLabel.setText(msg)",
    "docstring": "Refreshes the labels to display the proper title and count information."
  },
  {
    "code": "def parent(self):\n        if self == root or self == empty:\n            raise NoParent\n        return Name(self.labels[1:])",
    "docstring": "Return the parent of the name.\n        @rtype: dns.name.Name object\n        @raises NoParent: the name is either the root name or the empty name,\n        and thus has no parent."
  },
  {
    "code": "def sync(self, expectedThreads=0):\n        'Wait for all but expectedThreads async threads to finish.'\n        while len(self.unfinishedThreads) > expectedThreads:\n            time.sleep(.3)\n            self.checkForFinishedThreads()",
    "docstring": "Wait for all but expectedThreads async threads to finish."
  },
  {
    "code": "def delete(self, force=False):\n        if force:\n            RecordsBuckets.query.filter_by(\n                record=self.model,\n                bucket=self.files.bucket\n            ).delete()\n        return super(Record, self).delete(force)",
    "docstring": "Delete a record and also remove the RecordsBuckets if necessary.\n\n        :param force: True to remove also the\n            :class:`~invenio_records_files.models.RecordsBuckets` object.\n        :returns: Deleted record."
  },
  {
    "code": "def start(self):\n        self.is_collocated = bool(socket.gethostname() == self.config.slaveinput['cov_master_host'] and\n                                  self.topdir == self.config.slaveinput['cov_master_topdir'])\n        if not self.is_collocated:\n            master_topdir = self.config.slaveinput['cov_master_topdir']\n            slave_topdir = self.topdir\n            self.cov_source = [source.replace(master_topdir, slave_topdir) for source in self.cov_source]\n            self.cov_data_file = self.cov_data_file.replace(master_topdir, slave_topdir)\n            self.cov_config = self.cov_config.replace(master_topdir, slave_topdir)\n        self.cov_data_file += '.%s' % self.nodeid\n        self.cov = coverage.coverage(source=self.cov_source,\n                                     data_file=self.cov_data_file,\n                                     config_file=self.cov_config)\n        self.cov.erase()\n        self.cov.start()\n        self.set_env()",
    "docstring": "Determine what data file and suffix to contribute to and start coverage."
  },
  {
    "code": "def iter_features(self, stanza=None):\n        return itertools.chain(\n            iter(self.STATIC_FEATURES),\n            iter(self._features)\n        )",
    "docstring": "Return an iterator which yields the features of the node.\n\n        :param stanza: The IQ request stanza\n        :type stanza: :class:`~aioxmpp.IQ`\n        :rtype: iterable of :class:`str`\n        :return: :xep:`30` features of this node\n\n        `stanza` is the :class:`aioxmpp.IQ` stanza of the request. This can be\n        used to filter the list according to who is asking (not recommended).\n\n        `stanza` may be :data:`None` if the features are queried without\n        a specific request context. In that case, implementors should assume\n        that the result is visible to everybody.\n\n        .. note::\n\n           Subclasses must allow :data:`None` for `stanza` and default it to\n           :data:`None`.\n\n        The features are returned as strings. The features demanded by\n        :xep:`30` are always returned."
  },
  {
    "code": "def clean_new_password2(self):\n        password1 = self.cleaned_data.get('new_password1')\n        password2 = self.cleaned_data.get('new_password2')\n        if password1 or password2:\n            if password1 != password2:\n                raise forms.ValidationError(\n                    self.error_messages['password_mismatch'],\n                    code='password_mismatch',\n                )\n            password_validation.validate_password(password2, self.instance)\n        return password2",
    "docstring": "Validate password when set"
  },
  {
    "code": "def disable_constant(parameterized):\n    params = parameterized.params().values()\n    constants = [p.constant for p in params]\n    for p in params:\n        p.constant = False\n    try:\n        yield\n    except:\n        raise\n    finally:\n        for (p, const) in zip(params, constants):\n            p.constant = const",
    "docstring": "Temporarily set parameters on Parameterized object to\n    constant=False."
  },
  {
    "code": "def zrange(key, start, stop, host=None, port=None, db=None, password=None):\n    server = _connect(host, port, db, password)\n    return server.zrange(key, start, stop)",
    "docstring": "Get a range of values from a sorted set in Redis by index\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' redis.zrange foo_sorted 0 10"
  },
  {
    "code": "def cached(cache, key=keys.hashkey, lock=None):\n    def decorator(func):\n        if cache is None:\n            def wrapper(*args, **kwargs):\n                return func(*args, **kwargs)\n        elif lock is None:\n            def wrapper(*args, **kwargs):\n                k = key(*args, **kwargs)\n                try:\n                    return cache[k]\n                except KeyError:\n                    pass\n                v = func(*args, **kwargs)\n                try:\n                    cache[k] = v\n                except ValueError:\n                    pass\n                return v\n        else:\n            def wrapper(*args, **kwargs):\n                k = key(*args, **kwargs)\n                try:\n                    with lock:\n                        return cache[k]\n                except KeyError:\n                    pass\n                v = func(*args, **kwargs)\n                try:\n                    with lock:\n                        cache[k] = v\n                except ValueError:\n                    pass\n                return v\n        return _update_wrapper(wrapper, func)\n    return decorator",
    "docstring": "Decorator to wrap a function with a memoizing callable that saves\n    results in a cache."
  },
  {
    "code": "def validate_wavetable(self):\n        wave = self._wavetable\n        if N.any(wave <= 0):\n            wrong = N.where(wave <= 0)[0]\n            raise exceptions.ZeroWavelength(\n                'Negative or Zero wavelength occurs in wavelength array',\n                rows=wrong)\n        sorted = N.sort(wave)\n        if not N.alltrue(sorted == wave):\n            if N.alltrue(sorted[::-1] == wave):\n                pass\n            else:\n                wrong = N.where(sorted != wave)[0]\n                raise exceptions.UnsortedWavelength(\n                    'Wavelength array is not monotonic', rows=wrong)\n        dw = sorted[1:] - sorted[:-1]\n        if N.any(dw == 0):\n            wrong = N.where(dw == 0)[0]\n            raise exceptions.DuplicateWavelength(\n                \"Wavelength array contains duplicate entries\", rows=wrong)",
    "docstring": "Enforce monotonic, ascending wavelength array with no zero or\n        negative values.\n\n        Raises\n        ------\n        pysynphot.exceptions.DuplicateWavelength\n            Wavelength array contains duplicate entries.\n\n        pysynphot.exceptions.UnsortedWavelength\n            Wavelength array is not monotonic ascending or descending.\n\n        pysynphot.exceptions.ZeroWavelength\n            Wavelength array has zero or negative value(s)."
  },
  {
    "code": "def str_cast(maybe_bytes, encoding='utf-8'):\n    if isinstance(maybe_bytes, bytes_):\n        return maybe_bytes.decode(encoding)\n    else:\n        return maybe_bytes",
    "docstring": "Converts any bytes-like input to a string-like output, with respect to\n    python version\n\n    Parameters\n    ----------\n    maybe_bytes : if this is a bytes-like object, it will be converted to a string\n    encoding  : str, default='utf-8'\n        encoding to be used when decoding bytes"
  },
  {
    "code": "def split_sequence_as_iterable(self, values):\n        print(self.count)\n        s = iter(self.index.sorter)\n        for c in self.count:\n            yield (values[i] for i in itertools.islice(s, int(c)))",
    "docstring": "Group sequence into iterables\n\n        Parameters\n        ----------\n        values : iterable of length equal to keys\n            iterable of values to be grouped\n\n        Yields\n        ------\n        iterable of items in values\n\n        Notes\n        -----\n        This is the preferred method if values has random access, but we dont want it completely in memory.\n        Like a big memory mapped file, for instance"
  },
  {
    "code": "def attr(**context):\n    def decorator(func):\n        def wrapped_func(*args, **kwargs):\n            for key, value in context.items():\n                print key, value\n            return func(*args, **kwargs)\n        return wraps(func)(decorator)\n    return decorator",
    "docstring": "Decorator that add attributes into func.\n\n    Added attributes can be access outside via function's `func_dict` property."
  },
  {
    "code": "def get_response_headers(self, *args, **kwargs):\n        if self.response_headers:\n            return self._unpack_headers(self.response_headers)",
    "docstring": "A convenience method for obtaining the headers that were sent from the\n        S3 server.\n\n        The AWS S3 API depends upon setting headers. This method is used by the\n        head_object API call for getting a S3 object's metadata."
  },
  {
    "code": "def lookup_string(conn, kstr):\n    if kstr in keysyms:\n        return get_keycode(conn, keysyms[kstr])\n    elif len(kstr) > 1 and kstr.capitalize() in keysyms:\n        return get_keycode(conn, keysyms[kstr.capitalize()])\n    return None",
    "docstring": "Finds the keycode associated with a string representation of a keysym.\n\n    :param kstr: English representation of a keysym.\n    :return: Keycode, if one exists.\n    :rtype: int"
  },
  {
    "code": "def all(cls):\n        queues = {x: 0 for x in Queue.get_queues_config()}\n        stats = list(context.connections.mongodb_jobs.mrq_jobs.aggregate([\n            {\"$match\": {\"status\": \"queued\"}},\n            {\"$group\": {\"_id\": \"$queue\", \"jobs\": {\"$sum\": 1}}}\n        ]))\n        queues.update({x[\"_id\"]: x[\"jobs\"] for x in stats})\n        return queues",
    "docstring": "List all queues in MongoDB via aggregation, with their queued jobs counts. Might be slow."
  },
  {
    "code": "def import_private_key_from_file(filename, passphrase=None):\n    with open(filename, \"rb\") as key_file:\n        private_key = serialization.load_pem_private_key(\n            key_file.read(),\n            password=passphrase,\n            backend=default_backend())\n    return private_key",
    "docstring": "Read a private Elliptic Curve key from a PEM file.\n\n    :param filename: The name of the file\n    :param passphrase: A pass phrase to use to unpack the PEM file.\n    :return: A\n        cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey\n        instance"
  },
  {
    "code": "def _str_desc(self, reader):\n        data_version = reader.data_version\n        if data_version is not None:\n            data_version = data_version.replace(\"releases/\", \"\")\n        desc = \"{OBO}: fmt({FMT}) rel({REL}) {N:,} GO Terms\".format(\n            OBO=reader.obo_file, FMT=reader.format_version,\n            REL=data_version, N=len(self))\n        if reader.optobj:\n            desc = \"{D}; optional_attrs({A})\".format(D=desc, A=\" \".join(sorted(reader.optobj.optional_attrs)))\n        return desc",
    "docstring": "String containing information about the current GO DAG."
  },
  {
    "code": "def repay_funding(self, amount, currency):\n        params = {\n            'amount': amount,\n            'currency': currency\n            }\n        return self._send_message('post', '/funding/repay',\n                                  data=json.dumps(params))",
    "docstring": "Repay funding. Repays the older funding records first.\n\n        Args:\n            amount (int): Amount of currency to repay\n            currency (str): The currency, example USD\n\n        Returns:\n            Not specified by cbpro."
  },
  {
    "code": "def _serialize_v1(self, macaroon):\n        serialized = {\n            'identifier': utils.convert_to_string(macaroon.identifier),\n            'signature': macaroon.signature,\n        }\n        if macaroon.location:\n            serialized['location'] = macaroon.location\n        if macaroon.caveats:\n            serialized['caveats'] = [\n                _caveat_v1_to_dict(caveat) for caveat in macaroon.caveats\n            ]\n        return json.dumps(serialized)",
    "docstring": "Serialize the macaroon in JSON format v1.\n\n        @param macaroon the macaroon to serialize.\n        @return JSON macaroon."
  },
  {
    "code": "def ssh_check_mic(self, mic_token, session_id, username=None):\n        self._session_id = session_id\n        self._username = username\n        if username is not None:\n            mic_field = self._ssh_build_mic(\n                self._session_id,\n                self._username,\n                self._service,\n                self._auth_method,\n            )\n            self._gss_srv_ctxt.verify(mic_field, mic_token)\n        else:\n            self._gss_ctxt.verify(self._session_id, mic_token)",
    "docstring": "Verify the MIC token for a SSH2 message.\n\n        :param str mic_token: The MIC token received from the client\n        :param str session_id: The SSH session ID\n        :param str username: The name of the user who attempts to login\n        :return: None if the MIC check was successful\n        :raises: ``sspi.error`` -- if the MIC check failed"
  },
  {
    "code": "def bootstrap(array):\n    reg_func = lambda a: N.linalg.svd(a,full_matrices=False)[2][2]\n    beta_boots = bootstrap(array, func=reg_func)\n    return yhat, yhat_boots",
    "docstring": "Provides a bootstrap resampling of an array. Provides another\n    statistical method to estimate the variance of a dataset.\n\n    For a `PCA` object in this library, it should be applied to\n    `Orientation.array` method."
  },
  {
    "code": "def _encode(self, value):\n        \"Return a bytestring representation of the value. Taken from redis-py connection.py\"\n        if isinstance(value, bytes):\n            return value\n        elif isinstance(value, (int, long)):\n            value = str(value).encode('utf-8')\n        elif isinstance(value, float):\n            value = repr(value).encode('utf-8')\n        elif not isinstance(value, basestring):\n            value = str(value).encode('utf-8')\n        else:\n            value = value.encode('utf-8', 'strict')\n        return value",
    "docstring": "Return a bytestring representation of the value. Taken from redis-py connection.py"
  },
  {
    "code": "def addPointScalars(self, scalars, name):\n        poly = self.polydata(False)\n        if len(scalars) != poly.GetNumberOfPoints():\n            colors.printc('~times pointScalars Error: Number of scalars != nr. of points',\n                          len(scalars), poly.GetNumberOfPoints(), c=1)\n            exit()\n        arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True)\n        arr.SetName(name)\n        poly.GetPointData().AddArray(arr)\n        poly.GetPointData().SetActiveScalars(name)\n        self.mapper.SetScalarRange(np.min(scalars), np.max(scalars))\n        self.mapper.ScalarVisibilityOn()\n        return self",
    "docstring": "Add point scalars to the actor's polydata assigning it a name.\n\n        .. hint:: |mesh_coloring| |mesh_coloring.py|_"
  },
  {
    "code": "def sbo_list():\n    sbo_packages = []\n    for pkg in os.listdir(_meta_.pkg_path):\n        if pkg.endswith(\"_SBo\"):\n            sbo_packages.append(pkg)\n    return sbo_packages",
    "docstring": "Return all SBo packages"
  },
  {
    "code": "def validate(self, model, validator=None):\n    for filter_ in self.filters:\n      if not filter_(model):\n        return True\n    is_valid, message = self.is_valid(model, validator)\n    if not is_valid:\n      model.add_error(self.pretty_property_name or self.property_name, message)\n    return is_valid",
    "docstring": "Checks the model against all filters, and if it shoud be validated, runs the validation. if\n    the model is invalid, an error is added to the model. Then the validity value is returned."
  },
  {
    "code": "def fingerprint(value):\n  h = hashlib.sha256()\n  _digest(value, h)\n  return h.digest().encode('hex')",
    "docstring": "Return a hash value that uniquely identifies the GCL value."
  },
  {
    "code": "def to_date_or_datetime(value, ctx):\n    if isinstance(value, str):\n        temporal = ctx.get_date_parser().auto(value)\n        if temporal is not None:\n            return temporal\n    elif type(value) == datetime.date:\n        return value\n    elif isinstance(value, datetime.datetime):\n        return value.astimezone(ctx.timezone)\n    raise EvaluationError(\"Can't convert '%s' to a date or datetime\" % str(value))",
    "docstring": "Tries conversion of any value to a date or datetime"
  },
  {
    "code": "def sort(x, axis=-1, reverse=False, with_index=False, only_index=False):\n    from .function_bases import sort as sort_base\n    n_outputs = 2 if with_index and not only_index else 1\n    return sort_base(x, axis, reverse, with_index, only_index, n_outputs)",
    "docstring": "Sorts the elements of `x` along a given `axis` in ascending order\n    by value. A negative `axis` counts from the last dimension of `x`,\n    so the default of -1 sorts along the last dimension. If `reverse`\n    is True, then the elements are soreted in descending order.\n\n    If `with_index` is True, result is a tuple ``(sorted, indices)``\n    or only ``indices`` if `only_index` is True. Setting `only_index`\n    to True implies that `with_index` is also True.\n\n    .. code-block:: python\n\n        import numpy as np\n        import nnabla as nn\n        import nnabla.functions as F\n\n        nn.set_auto_forward(True)\n        x = nn.Variable.from_numpy_array(np.random.rand(2, 3, 4))\n\n        sorted = F.sort(x)\n        assert np.allclose(sorted.d, np.sort(x.d))\n\n        sorted, indices = F.sort(x, with_index=True)\n        assert np.allclose(sorted.d, np.sort(x.d))\n        assert np.all(indices.d == np.argsort(x.d))\n\n        indices = F.sort(x, only_index=True)\n        assert np.all(indices.d == np.argsort(x.d))\n\n    Args:\n        x(~nnabla.Variable): N-D array\n        axis(int): Axis along which to sort.\n        reverse(bool): Sort in descending order.\n        with_index(bool): Return sorted values and index.\n        only_index(bool): Return only the sort index.\n\n    Returns: :obj:`~nnabla.Variable` `sorted` or :obj:`~nnabla.Variable` `indices` or (:obj:`~nnabla.Variable` `sorted`, :obj:`~nnabla.Variable` `indices`)"
  },
  {
    "code": "def put(self, uri, data, **kwargs):\n        return self.request(\"PUT\", uri, data=data, **kwargs)",
    "docstring": "PUT the provided data to the specified path\n\n        See :meth:`request` for additional details.  The `data` parameter here is\n        expected to be a string type."
  },
  {
    "code": "def getIndicesFromBigIndex(self, bigIndex):\n        indices = numpy.array([0 for i in range(self.ndims)])\n        for i in range(self.ndims):\n            indices[i] = bigIndex // self.dimProd[i] % self.dims[i]\n        return indices",
    "docstring": "Get index set from given big index\n        @param bigIndex\n        @return index set\n        @note no checks are performed to ensure that the returned\n        big index is valid"
  },
  {
    "code": "def openCurrentItem(self):\n        logger.debug(\"openCurrentItem\")\n        _currentItem, currentIndex = self.getCurrentItem()\n        if not currentIndex.isValid():\n            return\n        self.expand(currentIndex)",
    "docstring": "Opens the current item in the repository."
  },
  {
    "code": "def fill_in_table(self, table, worksheet, flags):\n        max_row = 0\n        min_row = sys.maxint\n        for row in table:\n            if len(row) > max_row:\n                max_row = len(row)\n            if len(row) < min_row:\n                min_row = len(row)\n        if max_row != min_row:\n            for row in table:\n                if len(row) < max_row:\n                    row.extend([None]*(max_row-len(row)))",
    "docstring": "Fills in any rows with missing right hand side data with empty cells."
  },
  {
    "code": "def create_objects(self, raw_objects):\n        types_creations = self.__class__.types_creations\n        early_created_types = self.__class__.early_created_types\n        logger.info(\"Creating objects...\")\n        self.add_self_defined_objects(raw_objects)\n        for o_type in sorted(types_creations):\n            if o_type not in early_created_types:\n                self.create_objects_for_type(raw_objects, o_type)\n        logger.info(\"Done\")",
    "docstring": "Create all the objects got after the post configuration file initialization\n\n        :param raw_objects:  dict with all object with str values\n        :type raw_objects: dict\n        :return: None"
  },
  {
    "code": "async def get_link_secret_label(self) -> str:\n        LOGGER.debug('Wallet.get_link_secret_label >>>')\n        if not self.handle:\n            LOGGER.debug('Wallet.get_link_secret <!< Wallet %s is closed', self.name)\n            raise WalletState('Wallet {} is closed'.format(self.name))\n        rv = None\n        records = await self.get_non_secret(TYPE_LINK_SECRET_LABEL)\n        if records:\n            rv = records[str(max(int(k) for k in records))].value\n        LOGGER.debug('Wallet.get_link_secret_label <<< %s', rv)\n        return rv",
    "docstring": "Get current link secret label from non-secret storage records; return None for no match.\n\n        :return: latest non-secret storage record for link secret label"
  },
  {
    "code": "def datefmt_to_regex(datefmt):\n    new_string = datefmt\n    for pat, reg in PATTERN_MATCHNG:\n        new_string = new_string.replace(pat, reg)\n    return re.compile(r'(%s)' % new_string)",
    "docstring": "Convert a strftime format string to a regex.\n\n    :param datefmt: strftime format string\n    :type datefmt: ``str``\n\n    :returns: Equivalent regex\n    :rtype: ``re.compite``"
  },
  {
    "code": "def _save_trace(self):\n        stack_trace = stack()\n        try:\n            self.trace = []\n            for frm in stack_trace[5:]:\n                self.trace.insert(0, frm[1:])\n        finally:\n            del stack_trace",
    "docstring": "Save current stack trace as formatted string."
  },
  {
    "code": "def _inner_take_over_or_update(self, full_values=None, current_values=None, value_indices=None):\n        for key in current_values.keys():\n            if value_indices is not None and key in value_indices:\n                index = value_indices[key]\n            else:\n                index = slice(None)\n            if key in full_values:\n                try:\n                    full_values[key][index] += current_values[key]\n                except:\n                    full_values[key] += current_values[key]\n            else:\n                full_values[key] = current_values[key]",
    "docstring": "This is for automatic updates of values in the inner loop of missing\n        data handling. Both arguments are dictionaries and the values in\n        full_values will be updated by the current_gradients.\n\n        If a key from current_values does not exist in full_values, it will be\n        initialized to the value in current_values.\n\n        If there is indices needed for the update, value_indices can be used for\n        that. If value_indices has the same key, as current_values, the update\n        in full_values will be indexed by the indices in value_indices.\n\n        grads:\n            dictionary of standing gradients (you will have to carefully make sure, that\n            the ordering is right!). The values in here will be updated such that\n            full_values[key] += current_values[key]  forall key in full_gradients.keys()\n\n        gradients:\n            dictionary of gradients in the current set of parameters.\n\n        value_indices:\n            dictionary holding indices for the update in full_values.\n            if the key exists the update rule is:def df(x):\n            full_values[key][value_indices[key]] += current_values[key]"
  },
  {
    "code": "def _lock(self):\n    lockfile = '{}.lock'.format(self._get_cookie_file())\n    safe_mkdir_for(lockfile)\n    return OwnerPrintingInterProcessFileLock(lockfile)",
    "docstring": "An identity-keyed inter-process lock around the cookie file."
  },
  {
    "code": "def copy(self, object_version=None, key=None):\n        return ObjectVersionTag.create(\n            self.object_version if object_version is None else object_version,\n            key or self.key,\n            self.value\n        )",
    "docstring": "Copy a tag to a given object version.\n\n        :param object_version: The object version instance to copy the tag to.\n            Default: current object version.\n        :param key: Key of destination tag.\n            Default: current tag key.\n        :return: The copied object version tag."
  },
  {
    "code": "def apply_clicked(self, button):\n        if isinstance(self.model.state, LibraryState):\n            return\n        self.set_script_text(self.view.get_text())",
    "docstring": "Triggered when the Apply-Shortcut in the editor is triggered."
  },
  {
    "code": "def int(self, length, name, value=None, align=None):\n        self._add_field(Int(length, name, value, align=align))",
    "docstring": "Add an signed integer to template.\n\n        `length` is given in bytes and `value` is optional. `align` can be used\n        to align the field to longer byte length.\n        Signed integer uses twos-complement with bits numbered in big-endian.\n\n        Examples:\n        | int | 2 | foo |\n        | int | 2 | foo | 42 |\n        | int | 2 | fourByteFoo | 42 | align=4 |"
  },
  {
    "code": "def example_stats(filename):\n    nd = results.load_nd_from_pickle(filename=filename)\n    nodes_df, edges_df = nd.to_dataframe()\n    stats = results.calculate_mvgd_stats(nd)\n    stations = nodes_df[nodes_df['type'] == 'LV Station']\n    f, axarr = plt.subplots(2, sharex=True)\n    f.suptitle(\"Peak load (top) / peak generation capacity (bottom) at LV \"\n               \"substations in kW\")\n    stations['peak_load'].hist(bins=20, alpha=0.5, ax=axarr[0])\n    axarr[0].set_title(\"Peak load in kW\")\n    stations['generation_capacity'].hist(bins=20, alpha=0.5, ax=axarr[1])\n    axarr[1].set_title(\"Peak generation capacity in kW\")\n    plt.show()\n    print(\"You are analyzing MV grid district {mvgd}\\n\".format(\n        mvgd=int(stats.index.values)))\n    with option_context('display.max_rows', None,\n                        'display.max_columns', None,\n                        'display.max_colwidth', -1):\n        print(stats.T)",
    "docstring": "Obtain statistics from create grid topology\n\n    Prints some statistical numbers and produces exemplary figures"
  },
  {
    "code": "def RGB_color_picker(obj):\n    digest = hashlib.sha384(str(obj).encode('utf-8')).hexdigest()\n    subsize = int(len(digest) / 3)\n    splitted_digest = [digest[i * subsize: (i + 1) * subsize]\n                       for i in range(3)]\n    max_value = float(int(\"f\" * subsize, 16))\n    components = (\n        int(d, 16)\n        / max_value\n        for d in splitted_digest)\n    return Color(rgb2hex(components))",
    "docstring": "Build a color representation from the string representation of an object\n\n    This allows to quickly get a color from some data, with the\n    additional benefit that the color will be the same as long as the\n    (string representation of the) data is the same::\n\n        >>> from colour import RGB_color_picker, Color\n\n    Same inputs produce the same result::\n\n        >>> RGB_color_picker(\"Something\") == RGB_color_picker(\"Something\")\n        True\n\n    ... but different inputs produce different colors::\n\n        >>> RGB_color_picker(\"Something\") != RGB_color_picker(\"Something else\")\n        True\n\n    In any case, we still get a ``Color`` object::\n\n        >>> isinstance(RGB_color_picker(\"Something\"), Color)\n        True"
  },
  {
    "code": "def subcommand(self, description='', arguments={}):\n        def decorator(func):\n            self.register_subparser(\n                func,\n                func.__name__.replace('_', '-'),\n                description=description,\n                arguments=arguments,\n            )\n            return func\n        return decorator",
    "docstring": "Decorator for quickly adding subcommands to the omnic CLI"
  },
  {
    "code": "def experiments_predictions_upsert_property(self, experiment_id, run_id, properties):\n        if self.experiments_predictions_get(experiment_id, run_id) is None:\n            return None\n        return self.predictions.upsert_object_property(run_id, properties)",
    "docstring": "Upsert property of a prodiction for an experiment.\n\n        Raises ValueError if given property dictionary results in an illegal\n        operation.\n\n        Parameters\n        ----------\n        experiment_id : string\n            Unique experiment identifier\n        run_id : string\n            Unique model run identifier\n        properties : Dictionary()\n            Dictionary of property names and their new values.\n\n        Returns\n        -------\n        ModelRunHandle\n            Handle for updated object of None if object doesn't exist"
  },
  {
    "code": "def add(self, piece_uid, index):\n        if self.occupancy[index]:\n            raise OccupiedPosition\n        if self.exposed_territory[index]:\n            raise VulnerablePosition\n        klass = PIECE_CLASSES[piece_uid]\n        piece = klass(self, index)\n        territory = piece.territory\n        for i in self.indexes:\n            if self.occupancy[i] and territory[i]:\n                raise AttackablePiece\n        self.pieces.add(piece)\n        self.occupancy[index] = True\n        self.exposed_territory = list(\n            map(or_, self.exposed_territory, territory))",
    "docstring": "Add a piece to the board at the provided linear position."
  },
  {
    "code": "def import_keybase(useropt):\n    public_key = None\n    u_bits = useropt.split(':')\n    username = u_bits[0]\n    if len(u_bits) == 1:\n        public_key = cryptorito.key_from_keybase(username)\n    else:\n        fingerprint = u_bits[1]\n        public_key = cryptorito.key_from_keybase(username, fingerprint)\n    if cryptorito.has_gpg_key(public_key['fingerprint']):\n        sys.exit(2)\n    cryptorito.import_gpg_key(public_key['bundle'].encode('ascii'))\n    sys.exit(0)",
    "docstring": "Imports a public GPG key from Keybase"
  },
  {
    "code": "def blocks(self, *args, **kwargs):\n    return Stream(blocks(iter(self), *args, **kwargs))",
    "docstring": "Interface to apply audiolazy.blocks directly in a stream, returning\n    another stream. Use keyword args."
  },
  {
    "code": "def get_scoped_variable_from_name(self, name):\n        for scoped_variable_id, scoped_variable in self.scoped_variables.items():\n            if scoped_variable.name == name:\n                return scoped_variable_id\n        raise AttributeError(\"Name %s is not in scoped_variables dictionary\", name)",
    "docstring": "Get the scoped variable for a unique name\n\n        :param name: the unique name of the scoped variable\n        :return: the scoped variable specified by the name\n        :raises exceptions.AttributeError: if the name is not in the the scoped_variables dictionary"
  },
  {
    "code": "def get_public_ip_validator():\n    from msrestazure.tools import is_valid_resource_id, resource_id\n    def simple_validator(cmd, namespace):\n        if namespace.public_ip_address:\n            is_list = isinstance(namespace.public_ip_address, list)\n            def _validate_name_or_id(public_ip):\n                is_id = is_valid_resource_id(public_ip)\n                return public_ip if is_id else resource_id(\n                    subscription=get_subscription_id(cmd.cli_ctx),\n                    resource_group=namespace.resource_group_name,\n                    namespace='Microsoft.Network',\n                    type='publicIPAddresses',\n                    name=public_ip)\n            if is_list:\n                for i, public_ip in enumerate(namespace.public_ip_address):\n                    namespace.public_ip_address[i] = _validate_name_or_id(public_ip)\n            else:\n                namespace.public_ip_address = _validate_name_or_id(namespace.public_ip_address)\n    return simple_validator",
    "docstring": "Retrieves a validator for public IP address. Accepting all defaults will perform a check\n    for an existing name or ID with no ARM-required -type parameter."
  },
  {
    "code": "def start2(self, yes):\n        if yes:\n            self.write_message(1)\n            self.hints[3].used = True\n            self.lamp_turns = 1000\n        self.oldloc2 = self.oldloc = self.loc = self.rooms[1]\n        self.dwarves = [ Dwarf(self.rooms[n]) for n in (19, 27, 33, 44, 64) ]\n        self.pirate = Pirate(self.chest_room)\n        treasures = self.treasures\n        self.treasures_not_found = len(treasures)\n        for treasure in treasures:\n            treasure.prop = -1\n        self.describe_location()",
    "docstring": "Display instructions if the user wants them."
  },
  {
    "code": "def sub_filter(self, subset, filter, inplace=True):\n        full_query = ''.join(('not (', subset, ') or not (', filter, ')'))\n        with LogDataChanges(self, filter_action='filter', filter_query=filter):\n            result = self.data.query(full_query, inplace=inplace)\n        return result",
    "docstring": "Apply a filter to subset of the data\n\n        Examples\n        --------\n\n        ::\n\n            .subquery(\n                'timestep == 2',\n                'R > 4',\n            )"
  },
  {
    "code": "def _function_add_fakeret_edge(self, addr, src_node, src_func_addr, confirmed=None):\n        target_node = self._nodes.get(addr, None)\n        if target_node is None:\n            target_snippet = self._to_snippet(addr=addr, base_state=self._base_state)\n        else:\n            target_snippet = self._to_snippet(cfg_node=target_node)\n        if src_node is None:\n            self.kb.functions._add_node(src_func_addr, target_snippet)\n        else:\n            src_snippet = self._to_snippet(cfg_node=src_node)\n            self.kb.functions._add_fakeret_to(src_func_addr, src_snippet, target_snippet, confirmed=confirmed)",
    "docstring": "Generate CodeNodes for target and source, if no source node add node\n        for function, otherwise creates fake return to in function manager\n\n        :param int addr: target address\n        :param angr.analyses.CFGNode src_node: source node\n        :param int src_func_addr: address of function\n        :param confirmed: used as attribute on eventual digraph\n        :return: None"
  },
  {
    "code": "def _parse_standard_flag(read_buffer, mask_length):\n    mask_format = {1: 'B', 2: 'H', 4: 'I'}[mask_length]\n    num_standard_flags, = struct.unpack_from('>H', read_buffer, offset=0)\n    fmt = '>' + ('H' + mask_format) * num_standard_flags\n    data = struct.unpack_from(fmt, read_buffer, offset=2)\n    standard_flag = data[0:num_standard_flags * 2:2]\n    standard_mask = data[1:num_standard_flags * 2:2]\n    return standard_flag, standard_mask",
    "docstring": "Construct standard flag, standard mask data from the file.\n\n    Specifically working on Reader Requirements box.\n\n    Parameters\n    ----------\n    fptr : file object\n        File object for JP2K file.\n    mask_length : int\n        Length of standard mask flag"
  },
  {
    "code": "def getDatetimeAxis():\n  dataSet = 'nyc_taxi'\n  filePath = './data/' + dataSet + '.csv'\n  data = pd.read_csv(filePath, header=0, skiprows=[1, 2],\n                     names=['datetime', 'value', 'timeofday', 'dayofweek'])\n  xaxisDate = pd.to_datetime(data['datetime'])\n  return xaxisDate",
    "docstring": "use datetime as x-axis"
  },
  {
    "code": "def get_channelstate_settling(\n        chain_state: ChainState,\n        payment_network_id: PaymentNetworkID,\n        token_address: TokenAddress,\n) -> List[NettingChannelState]:\n    return get_channelstate_filter(\n        chain_state,\n        payment_network_id,\n        token_address,\n        lambda channel_state: channel.get_status(channel_state) == CHANNEL_STATE_SETTLING,\n    )",
    "docstring": "Return the state of settling channels in a token network."
  },
  {
    "code": "def create(url, name, subject_id, image_group_id, properties):\n        obj_props = [{'key':'name','value':name}]\n        if not properties is None:\n            try:\n                for key in properties:\n                    if key != 'name':\n                        obj_props.append({'key':key, 'value':properties[key]})\n            except TypeError as ex:\n                raise ValueError('invalid property set')\n        body = {\n            'subject' : subject_id,\n            'images' : image_group_id,\n            'properties' : obj_props\n        }\n        try:\n            req = urllib2.Request(url)\n            req.add_header('Content-Type', 'application/json')\n            response = urllib2.urlopen(req, json.dumps(body))\n        except urllib2.URLError as ex:\n            raise ValueError(str(ex))\n        return references_to_dict(json.load(response)['links'])[REF_SELF]",
    "docstring": "Create a new experiment using the given SCO-API create experiment Url.\n\n        Parameters\n        ----------\n        url : string\n            Url to POST experiment create request\n        name : string\n            User-defined name for experiment\n        subject_id : string\n            Unique identifier for subject at given SCO-API\n        image_group_id : string\n            Unique identifier for image group at given SCO-API\n        properties : Dictionary\n            Set of additional properties for created experiment. Argument may be\n            None. Given name will override name property in this set (if present).\n\n        Returns\n        -------\n        string\n            Url of created experiment resource"
  },
  {
    "code": "def render(self):\n        self.screen.reset()\n        self.screen.blit(self.corners)\n        self.screen.blit(self.lines, (1, 1))\n        self.screen.blit(self.rects, (int(self.screen.width / 2) + 1, 1))\n        self.screen.blit(self.circle, (0, int(self.screen.height / 2) + 1))\n        self.screen.blit(self.filled, (int(self.screen.width / 2) + 1,\n                                       int(self.screen.height / 2) + 1))\n        self.screen.update()\n        self.clock.tick()",
    "docstring": "Send the current screen content to Mate Light."
  },
  {
    "code": "def weigh_users(X_test, model, classifier_type=\"LinearSVC\"):\n    if classifier_type == \"LinearSVC\":\n        decision_weights = model.decision_function(X_test)\n    elif classifier_type == \"LogisticRegression\":\n        decision_weights = model.predict_proba(X_test)\n    elif classifier_type == \"RandomForest\":\n        if issparse(X_test):\n            decision_weights = model.predict_proba(X_test.tocsr())\n        else:\n            decision_weights = model.predict_proba(X_test)\n    else:\n        print(\"Invalid classifier type.\")\n        raise RuntimeError\n    return decision_weights",
    "docstring": "Uses a trained model and the unlabelled features to produce a user-to-label distance matrix.\n\n    Inputs:  - feature_matrix: The graph based-features in either NumPy or SciPy sparse array format.\n             - model: A trained scikit-learn One-vs-All multi-label scheme of linear SVC models.\n             - classifier_type: A string to be chosen among: * LinearSVC (LibLinear)\n                                                             * LogisticRegression (LibLinear)\n                                                             * RandomForest\n\n    Output:  - decision_weights: A NumPy array containing the distance of each user from each label discriminator."
  },
  {
    "code": "def crls(self):\n        if not self._allow_fetching:\n            return self._crls\n        output = []\n        for issuer_serial in self._fetched_crls:\n            output.extend(self._fetched_crls[issuer_serial])\n        return output",
    "docstring": "A list of all cached asn1crypto.crl.CertificateList objects"
  },
  {
    "code": "def visit_If(self, node):\n        self.visit(node.test)\n        old_range = self.result\n        self.result = old_range.copy()\n        for stmt in node.body:\n            self.visit(stmt)\n        body_range = self.result\n        self.result = old_range.copy()\n        for stmt in node.orelse:\n            self.visit(stmt)\n        orelse_range = self.result\n        self.result = body_range\n        for k, v in orelse_range.items():\n            if k in self.result:\n                self.result[k] = self.result[k].union(v)\n            else:\n                self.result[k] = v",
    "docstring": "Handle iterate variable across branches\n\n        >>> import gast as ast\n        >>> from pythran import passmanager, backend\n        >>> node = ast.parse('''\n        ... def foo(a):\n        ...     if a > 1: b = 1\n        ...     else: b = 3''')\n\n        >>> pm = passmanager.PassManager(\"test\")\n        >>> res = pm.gather(RangeValues, node)\n        >>> res['b']\n        Interval(low=1, high=3)"
  },
  {
    "code": "def standard_deviation(x):\n    if x.ndim > 1 and len(x[0]) > 1:\n        return np.std(x, axis=1)\n    return np.std(x)",
    "docstring": "Return a numpy array of column standard deviation\n\n    Parameters\n    ----------\n    x : ndarray\n        A numpy array instance\n\n    Returns\n    -------\n    ndarray\n        A 1 x n numpy array instance of column standard deviation\n\n    Examples\n    --------\n    >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n    >>> np.testing.assert_array_almost_equal(\n    ...     standard_deviation(a),\n    ...     [0.816496, 0.816496, 0.816496])\n    >>> a = np.array([1, 2, 3])\n    >>> np.testing.assert_array_almost_equal(\n    ...     standard_deviation(a),\n    ...     0.816496)"
  },
  {
    "code": "def parseFile(self, filename):\n        modname = self.filenameToModname(filename)\n        module = Module(modname, filename)\n        self.modules[modname] = module\n        if self.trackUnusedNames:\n            module.imported_names, module.unused_names = \\\n                find_imports_and_track_names(filename,\n                                             self.warn_about_duplicates,\n                                             self.verbose)\n        else:\n            module.imported_names = find_imports(filename)\n            module.unused_names = None\n        dir = os.path.dirname(filename)\n        module.imports = set(\n            [self.findModuleOfName(imp.name, imp.level, filename, dir)\n             for imp in module.imported_names])",
    "docstring": "Parse a single file."
  },
  {
    "code": "def antiscia(self):\n        obj = self.copy()\n        obj.type = const.OBJ_GENERIC\n        obj.relocate(360 - obj.lon + 180)\n        return obj",
    "docstring": "Returns antiscia object."
  },
  {
    "code": "def highlight_code(self, ontospy_entity):\n        try:\n            pygments_code = highlight(ontospy_entity.rdf_source(),\n                                      TurtleLexer(), HtmlFormatter())\n            pygments_code_css = HtmlFormatter().get_style_defs('.highlight')\n            return {\n                \"pygments_code\": pygments_code,\n                \"pygments_code_css\": pygments_code_css\n            }\n        except Exception as e:\n            printDebug(\"Error: Pygmentize Failed\", \"red\")\n            return {}",
    "docstring": "produce an html version of Turtle code with syntax highlighted\n        using Pygments CSS"
  },
  {
    "code": "def setup(parser):\n    parser.add_argument(\n        '-p', '--paramfile', type=str, required=True,\n        help='Parameter Range File')\n    parser.add_argument(\n        '-o', '--output', type=str, required=True, help='Output File')\n    parser.add_argument(\n        '-s', '--seed', type=int, required=False, default=None,\n        help='Random Seed')\n    parser.add_argument(\n        '--delimiter', type=str, required=False, default=' ',\n        help='Column delimiter')\n    parser.add_argument('--precision', type=int, required=False,\n                        default=8, help='Output floating-point precision')\n    return parser",
    "docstring": "Add common sampling options to CLI parser.\n\n    Parameters\n    ----------\n    parser : argparse object\n\n    Returns\n    ----------\n    Updated argparse object"
  },
  {
    "code": "def _run_parallel_process_with_profiling(self, start_path, stop_path, queue, filename):\n        runctx('Engine._run_parallel_process(self,  start_path, stop_path, queue)', globals(), locals(), filename)",
    "docstring": "wrapper for usage of profiling"
  },
  {
    "code": "def merge_into_adjustments_for_all_sids(self,\n                                            all_adjustments_for_sid,\n                                            col_to_all_adjustments):\n        for col_name in all_adjustments_for_sid:\n            if col_name not in col_to_all_adjustments:\n                col_to_all_adjustments[col_name] = {}\n            for ts in all_adjustments_for_sid[col_name]:\n                adjs = all_adjustments_for_sid[col_name][ts]\n                add_new_adjustments(col_to_all_adjustments,\n                                    adjs,\n                                    col_name,\n                                    ts)",
    "docstring": "Merge adjustments for a particular sid into a dictionary containing\n        adjustments for all sids.\n\n        Parameters\n        ----------\n        all_adjustments_for_sid : dict[int -> AdjustedArray]\n            All adjustments for a particular sid.\n        col_to_all_adjustments : dict[int -> AdjustedArray]\n            All adjustments for all sids."
  },
  {
    "code": "def _def_lookup(self, variable):\n        prevdefs = {}\n        for code_loc in self._live_defs.lookup_defs(variable):\n            if isinstance(variable, SimMemoryVariable):\n                type_ = 'mem'\n            elif isinstance(variable, SimRegisterVariable):\n                type_ = 'reg'\n            else:\n                raise AngrDDGError('Unknown variable type %s' % type(variable))\n            prevdefs[code_loc] = {\n                'type': type_,\n                'data': variable\n            }\n        return prevdefs",
    "docstring": "This is a backward lookup in the previous defs. Note that, as we are using VSA, it is possible that `variable`\n        is affected by several definitions.\n\n        :param angr.analyses.ddg.LiveDefinitions live_defs:\n                            The collection of live definitions.\n        :param SimVariable: The variable to lookup for definitions.\n        :returns:           A dict {stmt:labels} where label is the number of individual addresses of `addr_list` (or\n                            the actual set of addresses depending on the keep_addrs flag) that are definted by stmt."
  },
  {
    "code": "def do_loop_turn(self):\n        self.check_and_del_zombie_modules()\n        if self.watch_for_new_conf(timeout=0.05):\n            logger.info(\"I got a new configuration...\")\n            self.setup_new_conf()\n        _t0 = time.time()\n        self.get_objects_from_from_queues()\n        statsmgr.timer('core.get-objects-from-queues', time.time() - _t0)\n        _t0 = time.time()\n        self.get_external_commands_from_arbiters()\n        statsmgr.timer('external-commands.got.time', time.time() - _t0)\n        statsmgr.gauge('external-commands.got.count', len(self.unprocessed_external_commands))\n        _t0 = time.time()\n        self.push_external_commands_to_schedulers()\n        statsmgr.timer('external-commands.pushed.time', time.time() - _t0)\n        _t0 = time.time()\n        self.hook_point('tick')\n        statsmgr.timer('hook.tick', time.time() - _t0)",
    "docstring": "Receiver daemon main loop\n\n        :return: None"
  },
  {
    "code": "def iter_window(iterable, size=2, step=1, wrap=False):\n    r\n    iter_list = it.tee(iterable, size)\n    if wrap:\n        iter_list = [iter_list[0]] + list(map(it.cycle, iter_list[1:]))\n    try:\n        for count, iter_ in enumerate(iter_list[1:], start=1):\n            for _ in range(count):\n                six.next(iter_)\n    except StopIteration:\n        return iter(())\n    else:\n        _window_iter = zip(*iter_list)\n        window_iter = it.islice(_window_iter, 0, None, step)\n        return window_iter",
    "docstring": "r\"\"\"\n    iterates through iterable with a window size\n    generalizeation of itertwo\n\n    Args:\n        iterable (iter): an iterable sequence\n        size (int): window size (default = 2)\n        wrap (bool): wraparound (default = False)\n\n    Returns:\n        iter: returns windows in a sequence\n\n    CommandLine:\n        python -m utool.util_iter --exec-iter_window\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_iter import *  # NOQA\n        >>> iterable = [1, 2, 3, 4, 5, 6]\n        >>> size, step, wrap = 3, 1, True\n        >>> window_iter = iter_window(iterable, size, step, wrap)\n        >>> window_list = list(window_iter)\n        >>> result = ('window_list = %r' % (window_list,))\n        >>> print(result)\n        window_list = [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 1), (6, 1, 2)]\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_iter import *  # NOQA\n        >>> iterable = [1, 2, 3, 4, 5, 6]\n        >>> size, step, wrap = 3, 2, True\n        >>> window_iter = iter_window(iterable, size, step, wrap)\n        >>> window_list = list(window_iter)\n        >>> result = ('window_list = %r' % (window_list,))\n        >>> print(result)\n        window_list = [(1, 2, 3), (3, 4, 5), (5, 6, 1)]"
  },
  {
    "code": "def map_floor(continent_id, floor, lang=\"en\"):\n    cache_name = \"map_floor.%s-%s.%s.json\" % (continent_id, floor, lang)\n    params = {\"continent_id\": continent_id, \"floor\": floor, \"lang\": lang}\n    return get_cached(\"map_floor.json\", cache_name, params=params)",
    "docstring": "This resource returns details about a map floor, used to populate a\n    world map. All coordinates are map coordinates.\n\n    The returned data only contains static content. Dynamic content, such as\n    vendors, is not currently available.\n\n    :param continent_id: The continent.\n    :param floor: The map floor.\n    :param lang: Show localized texts in the specified language.\n\n    The response is an object with the following properties:\n\n    texture_dims (dimension)\n        The dimensions of the texture.\n\n    clamped_view (rect)\n        If present, it represents a rectangle of downloadable textures. Every\n        tile coordinate outside this rectangle is not available on the tile\n        server.\n\n    regions (object)\n        A mapping from region id to an object.\n\n    Each region object contains the following properties:\n\n    name (string)\n        The region name.\n\n    label_coord (coordinate)\n        The coordinates of the region label.\n\n    maps (object)\n        A mapping from the map id to an object.\n\n        Each map object contains the following properties:\n\n        name (string)\n            The map name.\n\n        min_level (number)\n            The minimum level of the map.\n\n        max_level (number)\n            The maximum level of the map.\n\n        default_floor (number)\n            The default floor of the map.\n\n        map_rect (rect)\n            The dimensions of the map.\n\n        continent_rect (rect)\n            The dimensions of the map within the continent coordinate system.\n\n        points_of_interest (list)\n            A list of points of interest (landmarks, waypoints and vistas)\n\n            Each points of interest object contains the following properties:\n\n            poi_id (number)\n                The point of interest id.\n\n            name (string)\n                The name of the point of interest.\n\n            type (string)\n                The type. This can be either \"landmark\" for actual points of\n                interest, \"waypoint\" for waypoints, or \"vista\" for vistas.\n\n            floor (number)\n                The floor of this object.\n\n            coord (coordinate)\n                The coordinates of this object.\n\n        tasks (list)\n            A list of renown hearts.\n\n            Each task object contains the following properties:\n\n            task_id (number)\n                The renown heart id.\n\n            objective (string)\n                The objective or name of the heart.\n\n            level (number)\n                The level of the heart.\n\n            coord (coordinate)\n                The coordinates where it takes place.\n\n        skill_challenges (list)\n            A list of skill challenges.\n\n            Each skill challenge object contains the following properties:\n\n            coord (coordinate)\n                The coordinates of this skill challenge.\n\n        sectors (list)\n            A list of areas within the map.\n\n            Each sector object contains the following properties:\n\n            sector_id (number)\n                The area id.\n\n            name (string)\n                The name of the area.\n\n            level (number)\n                The level of the area.\n\n            coord (coordinate)\n                The coordinates of this area (this is usually the center\n                position).\n\n    Special types:\n    Dimension properties are two-element lists of width and height.\n    Coordinate properties are two-element lists of the x and y position.\n    Rect properties are two-element lists of coordinates of the upper-left and\n    lower-right coordinates."
  },
  {
    "code": "def filter_active(self, *args, **kwargs):\n        grace = getattr(settings, 'HITCOUNT_KEEP_HIT_ACTIVE', {'days': 7})\n        period = timezone.now() - timedelta(**grace)\n        return self.filter(created__gte=period).filter(*args, **kwargs)",
    "docstring": "Return only the 'active' hits.\n\n        How you count a hit/view will depend on personal choice: Should the\n        same user/visitor *ever* be counted twice?  After a week, or a month,\n        or a year, should their view be counted again?\n\n        The defaulf is to consider a visitor's hit still 'active' if they\n        return within a the last seven days..  After that the hit\n        will be counted again.  So if one person visits once a week for a year,\n        they will add 52 hits to a given object.\n\n        Change how long the expiration is by adding to settings.py:\n\n        HITCOUNT_KEEP_HIT_ACTIVE  = {'days' : 30, 'minutes' : 30}\n\n        Accepts days, seconds, microseconds, milliseconds, minutes,\n        hours, and weeks.  It's creating a datetime.timedelta object."
  },
  {
    "code": "def load_yaml_config(conf_file):\n    global g_config\n    with open(conf_file) as fp:\n        g_config = util.yaml_load(fp)\n        src_dir = get_path('src_dir', None)\n        if src_dir is not None:\n            sys.path.insert(0, src_dir)\n        for cmd in get('commands', []):\n            _import(cmd)",
    "docstring": "Load a YAML configuration.\n\n    This will not update the configuration but replace it entirely.\n\n    Args:\n        conf_file (str):\n            Path to the YAML config. This function will not check the file name\n            or extension and will just crash if the given file does not exist or\n            is not a valid YAML file."
  },
  {
    "code": "def setContent(self, type_, value):\n        if type_ in [self.CONTENT_TYPE_TXT, self.CONTENT_TYPE_URL,\n                     self.CONTENT_TYPE_FILE]:\n            if type_ == self.CONTENT_TYPE_FILE:\n                self._file = {}\n                self._file = {'doc': open(value, 'rb')}\n            else:\n                self.addParam(type_, value)",
    "docstring": "Sets the content that's going to be sent to analyze according to its type\n\n        :param type_:\n            Type of the content (text, file or url)\n        :param value:\n            Value of the content"
  },
  {
    "code": "def _initialize_from_model(self, model):\n        for name, value in model.__dict__.items():\n            if name in self._properties:\n                setattr(self, name, value)",
    "docstring": "Loads a model from"
  },
  {
    "code": "def merge(self, parent=None):\n        if parent is None:\n            parent = self.parent\n        if parent is None:\n            return\n        self.sources = parent.sources + self.sources\n        data = copy.deepcopy(parent.data)\n        for key, value in sorted(self.data.items()):\n            if key.endswith('+'):\n                key = key.rstrip('+')\n                if key in data:\n                    if type(data[key]) == type(value) == dict:\n                        data[key].update(value)\n                        continue\n                    try:\n                        value = data[key] + value\n                    except TypeError as error:\n                        raise utils.MergeError(\n                            \"MergeError: Key '{0}' in {1} ({2}).\".format(\n                                key, self.name, str(error)))\n            data[key] = value\n        self.data = data",
    "docstring": "Merge parent data"
  },
  {
    "code": "def _transform_col(self, x, i):\n        return x.fillna(NAN_INT).map(self.label_encoders[i]).fillna(0)",
    "docstring": "Encode one categorical column into labels.\n\n        Args:\n            x (pandas.Series): a categorical column to encode\n            i (int): column index\n\n        Returns:\n            x (pandas.Series): a column with labels."
  },
  {
    "code": "def remove_child(self, index):\n        if index < 0:\n            index = index + len(self)\n        self.__children = self.__children[0:index] + self.__children[(index + 1):]",
    "docstring": "Remove the child at the given index\n        from the current list of children.\n\n        :param int index: the index of the child to be removed"
  },
  {
    "code": "def _create_relational_field(self, attr, options):\n        options['entity_class'] = attr.py_type\n        options['allow_empty'] = not attr.is_required\n        return EntityField, options",
    "docstring": "Creates the form element for working with entity relationships."
  },
  {
    "code": "def is_valid_endpoint_host(interfaces, endpoint):\n        result = urlparse(endpoint)\n        hostname = result.hostname\n        if hostname is None:\n            return False\n        for interface in interfaces:\n            if interface == hostname:\n                return False\n        return True",
    "docstring": "An endpoint host name is valid if it is a URL and if the\n        host is not the name of a network interface."
  },
  {
    "code": "def get_tree_members(self):\r\n        members = []\r\n        queue = deque()\r\n        queue.appendleft(self)\r\n        visited = set()\r\n        while len(queue):\r\n            node = queue.popleft()\r\n            if node not in visited:\r\n                members.extend(node.get_member_info())\r\n                queue.extendleft(node.get_children())\r\n                visited.add(node)\r\n        return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]",
    "docstring": "Retrieves all members from this node of the tree down."
  },
  {
    "code": "def check_infile_and_wp(curinf, curwp):\n        if not os.path.exists(curinf):\n            if curwp is None:\n                TauDEM.error('You must specify one of the workspace and the '\n                             'full path of input file!')\n            curinf = curwp + os.sep + curinf\n            curinf = os.path.abspath(curinf)\n            if not os.path.exists(curinf):\n                TauDEM.error('Input files parameter %s is not existed!' % curinf)\n        else:\n            curinf = os.path.abspath(curinf)\n            if curwp is None:\n                curwp = os.path.dirname(curinf)\n        return curinf, curwp",
    "docstring": "Check the existence of the given file and directory path.\n           1. Raise Runtime exception of both not existed.\n           2. If the ``curwp`` is None, the set the base folder of ``curinf`` to it."
  },
  {
    "code": "def load_settings_sizes():\n    page_size = AGNOCOMPLETE_DEFAULT_PAGESIZE\n    settings_page_size = getattr(\n        settings, 'AGNOCOMPLETE_DEFAULT_PAGESIZE', None)\n    page_size = settings_page_size or page_size\n    page_size_min = AGNOCOMPLETE_MIN_PAGESIZE\n    settings_page_size_min = getattr(\n        settings, 'AGNOCOMPLETE_MIN_PAGESIZE', None)\n    page_size_min = settings_page_size_min or page_size_min\n    page_size_max = AGNOCOMPLETE_MAX_PAGESIZE\n    settings_page_size_max = getattr(\n        settings, 'AGNOCOMPLETE_MAX_PAGESIZE', None)\n    page_size_max = settings_page_size_max or page_size_max\n    query_size = AGNOCOMPLETE_DEFAULT_QUERYSIZE\n    settings_query_size = getattr(\n        settings, 'AGNOCOMPLETE_DEFAULT_QUERYSIZE', None)\n    query_size = settings_query_size or query_size\n    query_size_min = AGNOCOMPLETE_MIN_QUERYSIZE\n    settings_query_size_min = getattr(\n        settings, 'AGNOCOMPLETE_MIN_QUERYSIZE', None)\n    query_size_min = settings_query_size_min or query_size_min\n    return (\n        page_size, page_size_min, page_size_max,\n        query_size, query_size_min,\n    )",
    "docstring": "Load sizes from settings or fallback to the module constants"
  },
  {
    "code": "def bloch_vector_from_state_vector(state: Sequence, index: int) -> np.ndarray:\n    rho = density_matrix_from_state_vector(state, [index])\n    v = np.zeros(3, dtype=np.float32)\n    v[0] = 2*np.real(rho[0][1])\n    v[1] = 2*np.imag(rho[1][0])\n    v[2] = np.real(rho[0][0] - rho[1][1])\n    return v",
    "docstring": "Returns the bloch vector of a qubit.\n\n    Calculates the bloch vector of the qubit at index\n    in the wavefunction given by state, assuming state follows\n    the standard Kronecker convention of numpy.kron.\n\n    Args:\n        state: A sequence representing a wave function in which\n            the ordering mapping to qubits follows the standard Kronecker\n            convention of numpy.kron.\n        index: index of qubit who's bloch vector we want to find.\n            follows the standard Kronecker convention of numpy.kron.\n\n    Returns:\n        A length 3 numpy array representing the qubit's bloch vector.\n\n    Raises:\n        ValueError: if the size of state is not a power of 2.\n        ValueError: if the size of the state represents more than 25 qubits.\n        IndexError: if index is out of range for the number of qubits\n            corresponding to the state."
  },
  {
    "code": "def create_albaran_automatic(pk, list_lines):\n        line_bd = SalesLineAlbaran.objects.filter(line_order__pk__in=list_lines).values_list('line_order__pk')\n        if line_bd.count() == 0 or len(list_lines) != len(line_bd[0]):\n            if line_bd.count() != 0:\n                for x in line_bd[0]:\n                    list_lines.pop(list_lines.index(x))\n            GenLineProduct.create_albaran_from_order(pk, list_lines)",
    "docstring": "creamos de forma automatica el albaran"
  },
  {
    "code": "def _deallocator(self):\n        lookup = {\n            \"c_bool\": \"logical\",\n            \"c_double\": \"double\",\n            \"c_double_complex\": \"complex\",\n            \"c_char\": \"char\",\n            \"c_int\": \"int\",\n            \"c_float\": \"float\",\n            \"c_short\": \"short\",\n            \"c_long\": \"long\"            \n        }\n        ctype = type(self.pointer).__name__.replace(\"LP_\", \"\").lower()\n        if ctype in lookup:\n            return \"dealloc_{0}_{1:d}d\".format(lookup[ctype], len(self.indices))\n        else:\n            return None",
    "docstring": "Returns the name of the subroutine in ftypes_dealloc.f90 that can\n        deallocate the array for this Ftype's pointer.\n\n        :arg ctype: the string c-type of the variable."
  },
  {
    "code": "def collected(self, group, filename=None, host=None, location=None, move=True, all=True):\n        ret = {\n            'name': 'support.collected',\n            'changes': {},\n            'result': True,\n            'comment': '',\n        }\n        location = location or tempfile.gettempdir()\n        self.check_destination(location, group)\n        ret['changes'] = __salt__['support.sync'](group, name=filename, host=host,\n                                                  location=location, move=move, all=all)\n        return ret",
    "docstring": "Sync archives to a central place.\n\n        :param name:\n        :param group:\n        :param filename:\n        :param host:\n        :param location:\n        :param move:\n        :param all:\n        :return:"
  },
  {
    "code": "def _compute_fixed(self):\n        try:\n            lon, lat = np.meshgrid(self.lon, self.lat)\n        except:\n            lat = self.lat\n        phi = np.deg2rad(lat)\n        try:\n            albedo = self.a0 + self.a2 * P2(np.sin(phi))\n        except:\n            albedo = np.zeros_like(phi)\n        dom = next(iter(self.domains.values()))\n        self.albedo = Field(albedo, domain=dom)",
    "docstring": "Recompute any fixed quantities after a change in parameters"
  },
  {
    "code": "def get(self,coordinate_system):\n        if coordinate_system == 'DA-DIR' or coordinate_system == 'specimen':\n            return self.pars\n        elif coordinate_system == 'DA-DIR-GEO' or coordinate_system == 'geographic':\n            return self.geopars\n        elif coordinate_system == 'DA-DIR-TILT' or coordinate_system == 'tilt-corrected':\n            return self.tiltpars\n        else:\n            print(\"-E- no such parameters to fetch for \" + coordinate_system + \" in fit: \" + self.name)\n            return None",
    "docstring": "Return the pmagpy paramters dictionary associated with this fit and the given\n        coordinate system\n        @param: coordinate_system -> the coordinate system who's parameters to return"
  },
  {
    "code": "def LoadConfig(config_obj,\n               config_file=None,\n               config_fd=None,\n               secondary_configs=None,\n               contexts=None,\n               reset=False,\n               parser=ConfigFileParser):\n  if config_obj is None or reset:\n    config_obj = _CONFIG.MakeNewConfig()\n  if config_file is not None:\n    config_obj.Initialize(filename=config_file, must_exist=True, parser=parser)\n  elif config_fd is not None:\n    config_obj.Initialize(fd=config_fd, parser=parser)\n  if secondary_configs:\n    for config_file in secondary_configs:\n      config_obj.LoadSecondaryConfig(config_file)\n  if contexts:\n    for context in contexts:\n      config_obj.AddContext(context)\n  return config_obj",
    "docstring": "Initialize a ConfigManager with the specified options.\n\n  Args:\n    config_obj: The ConfigManager object to use and update. If None, one will be\n      created.\n    config_file: Filename to read the config from.\n    config_fd: A file-like object to read config data from.\n    secondary_configs: A list of secondary config URLs to load.\n    contexts: Add these contexts to the config object.\n    reset: Completely wipe previous config before doing the load.\n    parser: Specify which parser to use.\n\n  Returns:\n    The resulting config object. The one passed in, unless None was specified."
  },
  {
    "code": "def build_list_marker_log(parser: str = 'github',\n                          list_marker: str = '.') -> list:\n    r\n    if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'\n            or parser == 'commonmarker' or parser == 'redcarpet'):\n        assert list_marker in md_parser[parser]['list']['ordered'][\n            'closing_markers']\n    list_marker_log = list()\n    if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'\n            or parser == 'commonmarker'):\n        list_marker_log = [\n            str(md_parser['github']['list']['ordered']['min_marker_number']) +\n            list_marker\n            for i in range(0, md_parser['github']['header']['max_levels'])\n        ]\n    elif parser == 'redcarpet':\n        pass\n    return list_marker_log",
    "docstring": "r\"\"\"Create a data structure that holds list marker information.\n\n    :parameter parser: decides rules on how compute indentations.\n         Defaults to ``github``.\n    :parameter list_marker: a string that contains some of the first\n         characters of the list element. Defaults to ``-``.\n    :type parser: str\n    :type list_marker: str\n    :returns: list_marker_log, the data structure.\n    :rtype: list\n    :raises: a built-in exception.\n\n    .. note::\n         This function makes sense for ordered lists only."
  },
  {
    "code": "def _check_import_source():\n        path_rel = '~/cltk_data/greek/software/greek_software_tlgu/tlgu.h'\n        path = os.path.expanduser(path_rel)\n        if not os.path.isfile(path):\n            try:\n                corpus_importer = CorpusImporter('greek')\n                corpus_importer.import_corpus('greek_software_tlgu')\n            except Exception as exc:\n                logger.error('Failed to import TLGU: %s', exc)\n                raise",
    "docstring": "Check if tlgu imported, if not import it."
  },
  {
    "code": "def img(self, id):\r\n        return self._serve_file(os.path.join(media_path, 'img', id))",
    "docstring": "Serve Pylons' stock images"
  },
  {
    "code": "def next(self, timeout=None):\n        try:\n            apply_result = self._collector._get_result(self._idx, timeout)\n        except IndexError:\n            self._idx = 0\n            raise StopIteration\n        except:\n            self._idx = 0\n            raise\n        self._idx += 1\n        assert apply_result.ready()\n        return apply_result.get(0)",
    "docstring": "Return the next result value in the sequence. Raise\n        StopIteration at the end. Can raise the exception raised by\n        the Job"
  },
  {
    "code": "def filter_service_by_regex_host_name(regex):\n    host_re = re.compile(regex)\n    def inner_filter(items):\n        service = items[\"service\"]\n        host = items[\"hosts\"][service.host]\n        if service is None or host is None:\n            return False\n        return host_re.match(host.host_name) is not None\n    return inner_filter",
    "docstring": "Filter for service\n    Filter on regex host_name\n\n    :param regex: regex to filter\n    :type regex: str\n    :return: Filter\n    :rtype: bool"
  },
  {
    "code": "def append_provenance_step(self, title, description, timestamp=None):\n        step_time = self._provenance.append_step(title, description, timestamp)\n        if step_time > self.last_update:\n            self.last_update = step_time",
    "docstring": "Add a step to the provenance of the metadata\n\n        :param title: The title of the step.\n        :type title: str\n\n        :param description: The content of the step\n        :type description: str\n\n        :param timestamp: the time of the step\n        :type timestamp: datetime, str"
  },
  {
    "code": "def add_license(key):\n    result = {\n        'result': False,\n        'retcode': -1,\n        'output': ''\n    }\n    if not has_powerpath():\n        result['output'] = 'PowerPath is not installed'\n        return result\n    cmd = '/sbin/emcpreg -add {0}'.format(key)\n    ret = __salt__['cmd.run_all'](cmd, python_shell=True)\n    result['retcode'] = ret['retcode']\n    if ret['retcode'] != 0:\n        result['output'] = ret['stderr']\n    else:\n        result['output'] = ret['stdout']\n        result['result'] = True\n    return result",
    "docstring": "Add a license"
  },
  {
    "code": "def MakePartialStat(self, fd):\n    is_dir = \"Container\" in fd.behaviours\n    return {\n        \"pathspec\": fd.Get(fd.Schema.PATHSPEC, \"\"),\n        \"st_atime\": fd.Get(fd.Schema.LAST, 0),\n        \"st_blksize\": 0,\n        \"st_blocks\": 0,\n        \"st_ctime\": 0,\n        \"st_dev\": 0,\n        \"st_gid\": 0,\n        \"st_ino\": 0,\n        \"st_mode\": self.default_dir_mode if is_dir else self.default_file_mode,\n        \"st_mtime\": 0,\n        \"st_nlink\": 0,\n        \"st_rdev\": 0,\n        \"st_size\": fd.Get(fd.Schema.SIZE, 0),\n        \"st_uid\": 0\n    }",
    "docstring": "Try and give a 'stat' for something not in the data store.\n\n    Args:\n      fd: The object with no stat.\n\n    Returns:\n      A dictionary corresponding to what we'll say the 'stat' is\n      for objects which are not actually files, so have no OS level stat."
  },
  {
    "code": "def list_catalogs(results=30, start=0):\n    result = util.callm(\"%s/%s\" % ('catalog', 'list'), {'results': results, 'start': start})\n    cats = [Catalog(**util.fix(d)) for d in result['response']['catalogs']]\n    start = result['response']['start']\n    total = result['response']['total']\n    return ResultList(cats, start, total)",
    "docstring": "Returns list of all catalogs created on this API key\n\n    Args:\n\n    Kwargs:\n        results (int): An integer number of results to return\n\n        start (int): An integer starting value for the result set\n\n    Returns:\n        A list of catalog objects\n\n    Example:\n\n    >>> catalog.list_catalogs()\n    [<catalog - test_artist_catalog>, <catalog - test_song_catalog>, <catalog - my_songs>]\n    >>>"
  },
  {
    "code": "def selectionComponents(self):\n        comps = []\n        model = self.model()\n        for comp in self._selectedComponents:\n            index = model.indexByComponent(comp)\n            if index is not None:\n                comps.append(comp)\n        return comps",
    "docstring": "Returns the names of the component types in this selection"
  },
  {
    "code": "def _parse_qcd_segment(self, fptr):\n        offset = fptr.tell() - 2\n        read_buffer = fptr.read(3)\n        length, sqcd = struct.unpack('>HB', read_buffer)\n        spqcd = fptr.read(length - 3)\n        return QCDsegment(sqcd, spqcd, length, offset)",
    "docstring": "Parse the QCD segment.\n\n        Parameters\n        ----------\n        fptr : file\n            Open file object.\n\n        Returns\n        -------\n        QCDSegment\n            The current QCD segment."
  },
  {
    "code": "def get_template(file):\n    pattern = str(file).lower()\n    while len(pattern) and not Lean.is_registered(pattern):\n      pattern = os.path.basename(pattern)\n      pattern = re.sub(r'^[^.]*\\.?','',pattern)\n    preferred_klass = Lean.preferred_mappings[pattern] if Lean.preferred_mappings.has_key(pattern) else None\n    if preferred_klass:\n  \t\treturn preferred_klass\n    klasses = Lean.template_mappings[pattern]\n    template = None\n    for klass in klasses:\n  \t\tif hasattr(klass,'is_engine_initialized') and callable(klass.is_engine_initialized):\n  \t\t\tif klass.is_engine_initialized():\n  \t\t\t\ttemplate = klass\n  \t\t\t\tbreak\n \t\tif template:\n \t\t\treturn template\n    first_failure = None\n    for klass in klasses:\n      try:\n        return klass\n      except Exception, e:\n        if not first_failure:\n          first_failure = e\n   \tif first_failure:\n   \t\traise Exception(first_failure)",
    "docstring": "Lookup a template class for the given filename or file\n        extension. Return nil when no implementation is found."
  },
  {
    "code": "def set_last_hop_errors(self, last_hop):\n        if last_hop.is_error:\n            self.last_hop_errors.append(last_hop.error_message)\n            return\n        for packet in last_hop.packets:\n            if packet.is_error:\n                self.last_hop_errors.append(packet.error_message)",
    "docstring": "Sets the last hop's errors."
  },
  {
    "code": "def close(self):\n        try:\n            self.parent_fd.fileno()\n        except io.UnsupportedOperation:\n            logger.debug(\"Not closing parent_fd - reusing existing\")\n        else:\n            self.parent_fd.close()",
    "docstring": "Close file, see file.close"
  },
  {
    "code": "def spin_gen(particles, index, gauge=1):\n    mat = np.zeros((2**particles, 2**particles))\n    flipper = 2**index\n    for i in range(2**particles):\n        ispin = btest(i, index)\n        if ispin == 1:\n            mat[i ^ flipper, i] = 1\n        else:\n            mat[i ^ flipper, i] = gauge\n    return mat",
    "docstring": "Generates the generic spin operator in z basis for a system of\n        N=particles and for the selected spin index name. where index=0..N-1\n        The gauge term sets the behavoir for a system away from half-filling"
  },
  {
    "code": "def get_or_create_pull(github_repo, title, body, head, base, *, none_if_no_commit=False):\n    try:\n        return github_repo.create_pull(\n            title=title,\n            body=body,\n            head=head,\n            base=base\n        )\n    except GithubException as err:\n        err_message = err.data['errors'][0].get('message', '')\n        if err.status == 422 and err_message.startswith('A pull request already exists'):\n            _LOGGER.info('PR already exists, get this PR')\n            return list(github_repo.get_pulls(\n                head=head,\n                base=base\n            ))[0]\n        elif none_if_no_commit and err.status == 422 and err_message.startswith('No commits between'):\n            _LOGGER.info('No PR possible since head %s and base %s are the same',\n                         head,\n                         base)\n            return None\n        else:\n            _LOGGER.warning(\"Unable to create PR:\\n%s\", err.data)\n            raise\n    except Exception as err:\n        response = traceback.format_exc()\n        _LOGGER.warning(\"Unable to create PR:\\n%s\", response)\n        raise",
    "docstring": "Try to create the PR. If the PR exists, try to find it instead. Raises otherwise.\n\n    You should always use the complete head syntax \"org:branch\", since the syntax is required\n    in case of listing.\n\n    if \"none_if_no_commit\" is set, return None instead of raising exception if the problem\n    is that head and base are the same."
  },
  {
    "code": "def __set_cache(self, tokens):\n        if DefaultCompleter._DefaultCompleter__tokens.get(self.__language):\n            return\n        DefaultCompleter._DefaultCompleter__tokens[self.__language] = tokens",
    "docstring": "Sets the tokens cache.\n\n        :param tokens: Completer tokens list.\n        :type tokens: tuple or list"
  },
  {
    "code": "def update_wrapper(wrapper,\n                   wrapped,\n                   assigned = functools.WRAPPER_ASSIGNMENTS,\n                   updated = functools.WRAPPER_UPDATES):\n    assigned = tuple(attr for attr in assigned if hasattr(wrapped, attr))\n    wrapper = functools.update_wrapper(wrapper, wrapped, assigned, updated)\n    wrapper.__wrapped__ = wrapped\n    return wrapper",
    "docstring": "Patch two bugs in functools.update_wrapper."
  },
  {
    "code": "def update_state_success(self, model_output):\n        response = requests.post(\n            self.links[REF_UPDATE_STATE_SUCCESS],\n            files={'file': open(model_output, 'rb')}\n        )\n        if response.status_code != 200:\n            try:\n                raise ValueError(json.loads(response.text)['message'])\n            except ValueError as ex:\n                raise ValueError('invalid state change: ' + str(response.text))\n        return self.refresh()",
    "docstring": "Update the state of the model run to 'SUCCESS'. Expects a model\n        output result file. Will upload the file before changing the model\n        run state.\n\n        Raises an exception if update fails or resource is unknown.\n\n        Parameters\n        ----------\n        model_output : string\n            Path to model run output file\n\n        Returns\n        -------\n        ModelRunHandle\n            Refreshed run handle."
  },
  {
    "code": "def get_base_layout(figs):\n\tlayout={}\n\tfor fig in figs:\n\t\tif not isinstance(fig,dict):\n\t\t\tfig=fig.to_dict()\n\t\tfor k,v in list(fig['layout'].items()):\n\t\t\tlayout[k]=v\n\treturn layout",
    "docstring": "Generates a layout with the union of all properties of multiple\n\tfigures' layouts\n\n\tParameters:\n\t-----------\n\t\tfig : list(Figures)\n\t\t\tList of Plotly Figures"
  },
  {
    "code": "def clear_file_systems(self):\n        self._source_url = None\n        self.dataset.config.library.source.url = None\n        self._source_fs = None\n        self._build_url = None\n        self.dataset.config.library.build.url = None\n        self._build_fs = None\n        self.dataset.commit()",
    "docstring": "Remove references to build and source file systems, reverting to the defaults"
  },
  {
    "code": "def write_additional(self, productversion, channel):\n        self.fileobj.seek(self.additional_offset)\n        extras = extras_header.build(dict(\n            count=1,\n            sections=[dict(\n                channel=six.u(channel),\n                productversion=six.u(productversion),\n                size=len(channel) + len(productversion) + 2 + 8,\n                padding=b'',\n            )],\n        ))\n        self.fileobj.write(extras)\n        self.last_offset = self.fileobj.tell()",
    "docstring": "Write the additional information to the MAR header.\n\n        Args:\n            productversion (str): product and version string\n            channel (str): channel string"
  },
  {
    "code": "def dict_filter(*args, **kwargs):\n    result = {}\n    for arg in itertools.chain(args, (kwargs,)):\n        dict_filter_update(result, arg)\n    return result",
    "docstring": "Merge all values into a single dict with all None values removed."
  },
  {
    "code": "def __update_state(self):\n    if self._state.active:\n      self._state = self.__get_state_by_id(self.job_config.job_id)",
    "docstring": "Fetches most up to date state from db."
  },
  {
    "code": "def fixed(ctx, number, decimals=2, no_commas=False):\n    value = _round(ctx, number, decimals)\n    format_str = '{:f}' if no_commas else '{:,f}'\n    return format_str.format(value)",
    "docstring": "Formats the given number in decimal format using a period and commas"
  },
  {
    "code": "def extract_tar(tar_path, target_folder):\n    with tarfile.open(tar_path, 'r') as archive:\n        archive.extractall(target_folder)",
    "docstring": "Extract the content of the tar-file at `tar_path` into `target_folder`."
  },
  {
    "code": "def run_program(self, name, arguments=[], timeout=30, exclusive=False):\n        logger.debug(\"Running program ...\")\n        if exclusive:\n            kill_longrunning(self.config)\n        prog = RunningProgram(self, name, arguments, timeout)\n        return prog.expect_end()",
    "docstring": "Runs a program in the working directory to completion.\n\n        Args:\n            name (str):        The name of the program to be executed.\n            arguments (tuple): Command-line arguments for the program.\n            timeout (int):     The timeout for execution.\n            exclusive (bool):  Prevent parallel validation runs on the\n                               test machines, e.g. when doing performance\n                               measurements for submitted code.\n\n        Returns:\n            tuple: A tuple of the exit code, as reported by the operating system,\n            and the output produced during the execution."
  },
  {
    "code": "def show_schema(self, tables=None):\n        tables = tables if tables else self.tables\n        for t in tables:\n            self._printer('\\t{0}'.format(t))\n            for col in self.get_schema(t, True):\n                self._printer('\\t\\t{0:30} {1:15} {2:10} {3:10} {4:10} {5:10}'.format(*col))",
    "docstring": "Print schema information."
  },
  {
    "code": "def filter_url(url, **kwargs):\n    d = parse_url_to_dict(url)\n    d.update(kwargs)\n    return unparse_url_dict({k: v for k, v in list(d.items()) if v})",
    "docstring": "filter a URL by returning a URL with only the parts specified in the keywords"
  },
  {
    "code": "def resize_file(fobj, diff, BUFFER_SIZE=2 ** 16):\n    fobj.seek(0, 2)\n    filesize = fobj.tell()\n    if diff < 0:\n        if filesize + diff < 0:\n            raise ValueError\n        fobj.truncate(filesize + diff)\n    elif diff > 0:\n        try:\n            while diff:\n                addsize = min(BUFFER_SIZE, diff)\n                fobj.write(b\"\\x00\" * addsize)\n                diff -= addsize\n            fobj.flush()\n        except IOError as e:\n            if e.errno == errno.ENOSPC:\n                fobj.truncate(filesize)\n            raise",
    "docstring": "Resize a file by `diff`.\n\n    New space will be filled with zeros.\n\n    Args:\n        fobj (fileobj)\n        diff (int): amount of size to change\n    Raises:\n        IOError"
  },
  {
    "code": "def _attacher(self, key, value, attributes, timed):\n        id, extra = self._get_attach_id(key, value, attributes)\n        record = self._create_attach_record(id, timed)\n        if extra:\n            record.update(extra)\n        return record",
    "docstring": "Create a full attachment record payload."
  },
  {
    "code": "def install_yum_priorities(distro, _yum=None):\n    yum = _yum or pkg_managers.yum\n    package_name = 'yum-plugin-priorities'\n    if distro.normalized_name == 'centos':\n        if distro.release[0] != '6':\n            package_name = 'yum-priorities'\n    yum(distro.conn, package_name)",
    "docstring": "EPEL started packaging Ceph so we need to make sure that the ceph.repo we\n    install has a higher priority than the EPEL repo so that when installing\n    Ceph it will come from the repo file we create.\n\n    The name of the package changed back and forth (!) since CentOS 4:\n\n    From the CentOS wiki::\n\n        Note: This plugin has carried at least two differing names over time.\n        It is named yum-priorities on CentOS-5 but was named\n        yum-plugin-priorities on CentOS-4. CentOS-6 has reverted to\n        yum-plugin-priorities.\n\n    :params _yum: Used for testing, so we can inject a fake yum"
  },
  {
    "code": "def get_lacp_mode(self, name):\n        members = self.get_members(name)\n        if not members:\n            return DEFAULT_LACP_MODE\n        for member in self.get_members(name):\n            match = re.search(r'channel-group\\s\\d+\\smode\\s(?P<value>.+)',\n                              self.get_block('^interface %s' % member))\n            return match.group('value')",
    "docstring": "Returns the LACP mode for the specified Port-Channel interface\n\n        Args:\n            name(str): The Port-Channel interface name to return the LACP\n                mode for from the configuration\n\n        Returns:\n            The configured LACP mode for the interface.  Valid mode values\n                are 'on', 'passive', 'active'"
  },
  {
    "code": "def get_asset_temporal_session_for_repository(self, repository_id=None):\n        if not repository_id:\n            raise NullArgument()\n        if not self.supports_asset_temporal():\n            raise Unimplemented()\n        try:\n            from . import sessions\n        except ImportError:\n            raise OperationFailed('import error')\n        try:\n            session = sessions.AssetTemporalSession(repository_id,\n                                                    proxy=self._proxy,\n                                                    runtime=self._runtime)\n        except AttributeError:\n            raise OperationFailed('attribute error')\n        return session",
    "docstring": "Gets the session for retrieving temporal coverage of an asset\n        for the given repository.\n\n        arg:    repository_id (osid.id.Id): the Id of the repository\n        return: (osid.repository.AssetTemporalSession) - an\n                AssetTemporalSession\n        raise:  NotFound - repository_id not found\n        raise:  NullArgument - repository_id is null\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - supports_asset_temporal() or\n                supports_visible_federation() is false\n        compliance: optional - This method must be implemented if\n                    supports_asset_temporal() and\n                    supports_visible_federation() are true."
  },
  {
    "code": "def endpoints_minima(self, slope_cutoff=5e-3):\n        energies = self.energies\n        try:\n            sp = self.spline()\n        except:\n            print(\"Energy spline failed.\")\n            return None\n        der = sp.derivative()\n        der_energies = der(range(len(energies)))\n        return {\"polar\": abs(der_energies[-1]) <= slope_cutoff,\n                \"nonpolar\": abs(der_energies[0]) <= slope_cutoff}",
    "docstring": "Test if spline endpoints are at minima for a given slope cutoff."
  },
  {
    "code": "def get_package_version():\n    base = os.path.abspath(os.path.dirname(__file__))\n    with open(os.path.join(base, 'policy', '__init__.py'),\n              mode='rt',\n              encoding='utf-8') as initf:\n        for line in initf:\n            m = version.match(line.strip())\n            if not m:\n                continue\n            return m.groups()[0]",
    "docstring": "return package version without importing it"
  },
  {
    "code": "def _create_wx_app():\n    wxapp = wx.GetApp()\n    if wxapp is None:\n        wxapp = wx.App(False)\n        wxapp.SetExitOnFrameDelete(True)\n        _create_wx_app.theWxApp = wxapp",
    "docstring": "Creates a wx.App instance if it has not been created sofar."
  },
  {
    "code": "def infer_type(self, in_type):\n        return in_type, [in_type[0]]*len(self.list_outputs()), \\\n            [in_type[0]]*len(self.list_auxiliary_states())",
    "docstring": "infer_type interface. override to create new operators\n\n        Parameters\n        ----------\n        in_type : list of np.dtype\n            list of argument types in the same order as\n            declared in list_arguments.\n\n        Returns\n        -------\n        in_type : list\n            list of argument types. Can be modified from in_type.\n        out_type : list\n            list of output types calculated from in_type,\n            in the same order as declared in list_outputs.\n        aux_type : Optional, list\n            list of aux types calculated from in_type,\n            in the same order as declared in list_auxiliary_states."
  },
  {
    "code": "def fix_errors(config, validation):\n    for e in flatten_errors(config, validation):\n        sections, key, err = e\n        sec = config\n        for section in sections:\n            sec = sec[section]\n        if key is not None:\n            sec[key] = sec.default_values.get(key, sec[key])\n        else:\n            sec.walk(set_to_default)\n    return config",
    "docstring": "Replace errors with their default values\n\n    :param config: a validated ConfigObj to fix\n    :type config: ConfigObj\n    :param validation: the resuts of the validation\n    :type validation: ConfigObj\n    :returns: The altered config (does alter it in place though)\n    :raises: None"
  },
  {
    "code": "def flush(self, auth, resource, options=None, defer=False):\n        args = [resource]\n        if options is not None:\n            args.append(options)\n        return self._call('flush', auth, args, defer)",
    "docstring": "Empties the specified resource of data per specified constraints.\n\n        Args:\n            auth: <cik>\n            resource: resource to empty.\n            options: Time limits."
  },
  {
    "code": "def set(self, key, value):\n        if hasattr(value, 'labels'):\n            if 'VARIABLE' in env.config['SOS_DEBUG'] or 'ALL' in env.config[\n                    'SOS_DEBUG']:\n                env.log_to_file(\n                    'VARIABLE',\n                    f\"Set {key} to {short_repr(value)} with labels {short_repr(value.labels)}\"\n                )\n        else:\n            if 'VARIABLE' in env.config['SOS_DEBUG'] or 'ALL' in env.config[\n                    'SOS_DEBUG']:\n                env.log_to_file(\n                    'VARIABLE',\n                    f\"Set {key} to {short_repr(value)} of type {value.__class__.__name__}\"\n                )\n        self._dict[key] = value",
    "docstring": "A short cut to set value to key without triggering any logging\n        or warning message."
  },
  {
    "code": "def init(self, initial):\n        if initial <= 0:\n            return False\n        step = initial // BLOCK_SIZE\n        with self._lock:\n            init = self._atomic_long.compare_and_set(0, step + 1).result()\n            if init:\n                self._local = step\n                self._residue = (initial % BLOCK_SIZE) + 1\n            return init",
    "docstring": "Try to initialize this IdGenerator instance with the given id. The first generated id will be 1 greater than id.\n\n        :param initial: (long), the given id.\n        :return: (bool), ``true`` if initialization succeeded, ``false`` if id is less than 0."
  },
  {
    "code": "def delete_token():\n    username = get_admin()[0]\n    admins = get_couchdb_admins()\n    if username in admins:\n        print 'I delete {} CouchDB user'.format(username)\n        delete_couchdb_admin(username)\n    if os.path.isfile(LOGIN_FILENAME):\n        print 'I delete {} token file'.format(LOGIN_FILENAME)\n        os.remove(LOGIN_FILENAME)",
    "docstring": "Delete current token, file & CouchDB admin user"
  },
  {
    "code": "def dollars_to_cents(s, allow_negative=False):\n    if not s:\n        return\n    if isinstance(s, string_types):\n        s = ''.join(RE_NUMBER.findall(s))\n    dollars = int(round(float(s) * 100))\n    if not allow_negative and dollars < 0:\n        raise ValueError('Negative values not permitted.')\n    return dollars",
    "docstring": "Given a string or integer representing dollars, return an integer of\n    equivalent cents, in an input-resilient way.\n    \n    This works by stripping any non-numeric characters before attempting to\n    cast the value.\n\n    Examples::\n\n        >>> dollars_to_cents('$1')\n        100\n        >>> dollars_to_cents('1')\n        100\n        >>> dollars_to_cents(1)\n        100\n        >>> dollars_to_cents('1e2')\n        10000\n        >>> dollars_to_cents('-1$', allow_negative=True)\n        -100\n        >>> dollars_to_cents('1 dollar')\n        100"
  },
  {
    "code": "def add_child_bin(self, bin_id, child_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.add_child_catalog(catalog_id=bin_id, child_id=child_id)\n        return self._hierarchy_session.add_child(id_=bin_id, child_id=child_id)",
    "docstring": "Adds a child to a bin.\n\n        arg:    bin_id (osid.id.Id): the ``Id`` of a bin\n        arg:    child_id (osid.id.Id): the ``Id`` of the new child\n        raise:  AlreadyExists - ``bin_id`` is already a parent of\n                ``child_id``\n        raise:  NotFound - ``bin_id`` or ``child_id`` not found\n        raise:  NullArgument - ``bin_id`` or ``child_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def start_compress(codec, image, stream):\n    OPENJP2.opj_start_compress.argtypes = [CODEC_TYPE,\n                                           ctypes.POINTER(ImageType),\n                                           STREAM_TYPE_P]\n    OPENJP2.opj_start_compress.restype = check_error\n    OPENJP2.opj_start_compress(codec, image, stream)",
    "docstring": "Wraps openjp2 library function opj_start_compress.\n\n    Start to compress the current image.\n\n    Parameters\n    ----------\n    codec : CODEC_TYPE\n        Compressor handle.\n    image : pointer to ImageType\n        Input filled image.\n    stream : STREAM_TYPE_P\n        Input stream.\n\n    Raises\n    ------\n    RuntimeError\n        If the OpenJPEG library routine opj_start_compress fails."
  },
  {
    "code": "def from_global_id(global_id):\n    unbased_global_id = unbase64(global_id)\n    _type, _id = unbased_global_id.split(':', 1)\n    return _type, _id",
    "docstring": "Takes the \"global ID\" created by toGlobalID, and retuns the type name and ID\n    used to create it."
  },
  {
    "code": "def column_summary_data(self):\n        assembled_summary = self._to_cluster_summary_assembled()\n        pct_id, read_depth = self._pc_id_and_read_depth_of_longest()\n        columns = {\n            'assembled': self._to_cluster_summary_assembled(),\n            'match': self._has_match(assembled_summary),\n            'ref_seq': self.ref_name,\n            'pct_id': str(pct_id),\n            'ctg_cov': str(read_depth),\n            'known_var': self._to_cluster_summary_has_known_nonsynonymous(assembled_summary),\n            'novel_var': self._to_cluster_summary_has_novel_nonsynonymous(assembled_summary)\n        }\n        return columns",
    "docstring": "Returns a dictionary of column name -> value, for cluster-level results"
  },
  {
    "code": "def update(self, **kwargs):\n        for arg in kwargs:\n            if hasattr(self, arg):\n                setattr(self, arg, kwargs[arg])\n            else:\n                raise ValueError(\"Invalid RayParams parameter in\"\n                                 \" update: %s\" % arg)\n        self._check_usage()",
    "docstring": "Update the settings according to the keyword arguments.\n\n        Args:\n            kwargs: The keyword arguments to set corresponding fields."
  },
  {
    "code": "def count_leases_by_owner(self, leases):\n        owners = [l.owner for l in leases]\n        return dict(Counter(owners))",
    "docstring": "Returns a dictionary of leases by current owner."
  },
  {
    "code": "def get_uri(self, ncname: str) -> Optional[str]:\n        uri = cu.expand_uri(ncname + ':', self.curi_maps)\n        return uri if uri and uri.startswith('http') else None",
    "docstring": "Get the URI associated with ncname\n\n        @param ncname:"
  },
  {
    "code": "def guessFormat(self):\n        c = [ord(x) for x in self.quals]\n        mi, ma = min(c), max(c)\n        r = []\n        for entry_format, v in iteritems(RANGES):\n            m1, m2 = v\n            if mi >= m1 and ma < m2:\n                r.append(entry_format)\n        return r",
    "docstring": "return quality score format -\n        might return several if ambiguous."
  },
  {
    "code": "def set_features(self):\n        self.scores = {}\n        for t_or_d, feats in zip(['target', 'decoy'], [self.target,\n                                                       self.decoy]):\n            self.scores[t_or_d] = {}\n            self.scores[t_or_d]['scores'] = self.score_get_fun(\n                feats, self.featuretype, self.prepare_percolator_output)\n            self.scores[t_or_d]['fn'] = '{}_qvality_input.txt'.format(t_or_d)\n            writers.write_qvality_input(self.scores[t_or_d]['scores'],\n                                        self.scores[t_or_d]['fn'])",
    "docstring": "Creates scorefiles for qvality's target and decoy distributions"
  },
  {
    "code": "def gethash(compiled):\n    lines = compiled.splitlines()\n    if len(lines) < 3 or not lines[2].startswith(hash_prefix):\n        return None\n    else:\n        return lines[2][len(hash_prefix):]",
    "docstring": "Retrieve a hash from a header."
  },
  {
    "code": "def delete_job(job_id,\n               deployment_name,\n               token_manager=None,\n               app_url=defaults.APP_URL):\n    headers = token_manager.get_access_token_headers()\n    data_url = get_data_url_for_job(job_id,\n                                    deployment_name,\n                                    token_manager=token_manager,\n                                    app_url=app_url)\n    url = '%s/api/v1/jobs/%s' % (data_url, job_id)\n    response = requests.delete(url, headers=headers)\n    if response.status_code != 200:\n        raise JutException('Error %s: %s' % (response.status_code, response.text))",
    "docstring": "delete a job with a specific job id"
  },
  {
    "code": "def plugins():\n    plugins = current_app.config['PLUGINS']\n    for name, description in entrypoints.ENTRYPOINTS.items():\n        echo('{0} ({1})'.format(white(description), name))\n        if name == 'udata.themes':\n            actives = [current_app.config['THEME']]\n        elif name == 'udata.avatars':\n            actives = [avatar_config('provider')]\n        else:\n            actives = plugins\n        for ep in sorted(entrypoints.iter_all(name), key=by_name):\n            echo('> {0}: {1}'.format(ep.name, is_active(ep, actives)))",
    "docstring": "Display some details about the local plugins"
  },
  {
    "code": "def _check_asset_node_def(node_def):\n  if node_def.op != \"Const\":\n    raise TypeError(\"Asset node must be of type constant.\")\n  if tf.as_dtype(node_def.attr[\"dtype\"].type) != tf.string:\n    raise TypeError(\"Asset node must be of dtype string.\")\n  if len(node_def.attr[\"value\"].tensor.string_val) != 1:\n    raise TypeError(\"Asset node must be a scalar.\")",
    "docstring": "Raises TypeError if `node_def` does not match the expectations."
  },
  {
    "code": "def get_task_trackers(properties=None, hadoop_conf_dir=None, offline=False):\n    if offline:\n        if not hadoop_conf_dir:\n            hadoop_conf_dir = pydoop.hadoop_conf()\n            slaves = os.path.join(hadoop_conf_dir, \"slaves\")\n        try:\n            with open(slaves) as f:\n                task_trackers = [(l.strip(), 0) for l in f]\n        except IOError:\n            task_trackers = []\n    else:\n        stdout = run_class(\n            \"org.apache.hadoop.mapred.JobClient\", [\"-list-active-trackers\"],\n            properties=properties, hadoop_conf_dir=hadoop_conf_dir,\n            keep_streams=True\n        )\n        task_trackers = []\n        for line in stdout.splitlines():\n            if not line:\n                continue\n            line = line.split(\":\")\n            task_trackers.append((line[0].split(\"_\")[1], int(line[-1])))\n    return task_trackers",
    "docstring": "Get the list of task trackers in the Hadoop cluster.\n\n    Each element in the returned list is in the ``(host, port)`` format.\n    All arguments are passed to :func:`run_class`.\n\n    If ``offline`` is :obj:`True`, try getting the list of task trackers from\n    the ``slaves`` file in Hadoop's configuration directory (no attempt is\n    made to contact the Hadoop daemons).  In this case, ports are set to 0."
  },
  {
    "code": "def StringIO(*args, **kwargs):\n    raw = sync_io.StringIO(*args, **kwargs)\n    return AsyncStringIOWrapper(raw)",
    "docstring": "StringIO constructor shim for the async wrapper."
  },
  {
    "code": "def setFixedHeight(self, height):\n        super(XViewPanelBar, self).setFixedHeight(height)\n        if self.layout():\n            for i in xrange(self.layout().count()):\n                try:\n                    self.layout().itemAt(i).widget().setFixedHeight(height)\n                except StandardError:\n                    continue",
    "docstring": "Sets the fixed height for this bar to the inputed height.\n\n        :param      height | <int>"
  },
  {
    "code": "async def getTempCortex(mods=None):\n    with s_common.getTempDir() as dirn:\n        async with await Cortex.anit(dirn) as core:\n            if mods:\n                for mod in mods:\n                    await core.loadCoreModule(mod)\n            async with core.getLocalProxy() as prox:\n                yield prox",
    "docstring": "Get a proxy to a cortex backed by a temporary directory.\n\n    Args:\n        mods (list): A list of modules which are loaded into the cortex.\n\n    Notes:\n        The cortex and temporary directory are town down on exit.\n        This should only be called from synchronous code.\n\n    Returns:\n        Proxy to the cortex."
  },
  {
    "code": "def _load_attributes(new_class):\n        for field_name, field_obj in new_class.meta_.declared_fields.items():\n            new_class.meta_.attributes[field_obj.get_attribute_name()] = field_obj",
    "docstring": "Load list of attributes from declared fields"
  },
  {
    "code": "def _init_threading(self, function, params={}, num_threads=10):\n        q = Queue(maxsize=0)\n        for i in range(num_threads):\n            worker = Thread(target=function, args=(q, params))\n            worker.setDaemon(True)\n            worker.start()\n        return q",
    "docstring": "Initialize queue and threads\n\n        :param function:\n        :param params:\n        :param num_threads:\n        :return:"
  },
  {
    "code": "def get_configuration(form, out):\n    config = configuration.Configuration()\n    config[\"recursionlevel\"] = int(formvalue(form, \"level\"))\n    config[\"logger\"] = config.logger_new('html', fd=out, encoding=HTML_ENCODING)\n    config[\"threads\"] = 2\n    if \"anchors\" in form:\n        config[\"enabledplugins\"].append(\"AnchorCheck\")\n    if \"errors\" not in form:\n        config[\"verbose\"] = True\n    pat = \"!^%s$\" % urlutil.safe_url_pattern\n    config[\"externlinks\"].append(get_link_pat(pat, strict=True))\n    config.sanitize()\n    return config",
    "docstring": "Initialize a CGI configuration."
  },
  {
    "code": "def _filter_image(self, url):\n        \"The param is the image URL, which is returned if it passes all the filters.\"\n        return reduce(lambda f, g: f and g(f), \n        [\n            filters.AdblockURLFilter()(url),\n            filters.NoImageFilter(),\n            filters.SizeImageFilter(),\n            filters.MonoImageFilter(),\n            filters.FormatImageFilter(),\n        ])",
    "docstring": "The param is the image URL, which is returned if it passes all the filters."
  },
  {
    "code": "def inject_trace_header(headers, entity):\n    if not entity:\n        return\n    if hasattr(entity, 'type') and entity.type == 'subsegment':\n        header = entity.parent_segment.get_origin_trace_header()\n    else:\n        header = entity.get_origin_trace_header()\n    data = header.data if header else None\n    to_insert = TraceHeader(\n        root=entity.trace_id,\n        parent=entity.id,\n        sampled=entity.sampled,\n        data=data,\n    )\n    value = to_insert.to_header_str()\n    headers[http.XRAY_HEADER] = value",
    "docstring": "Extract trace id, entity id and sampling decision\n    from the input entity and inject these information\n    to headers.\n\n    :param dict headers: http headers to inject\n    :param Entity entity: trace entity that the trace header\n        value generated from."
  },
  {
    "code": "def remove_draft_child(self):\n        if self.draft_child:\n            with db.session.begin_nested():\n                super(PIDNodeVersioning, self).remove_child(self.draft_child,\n                                                            reorder=True)",
    "docstring": "Remove the draft child from versioning."
  },
  {
    "code": "def link_head(self, node):\n        assert not node.tail\n        old_head = self.head\n        if old_head:\n            assert old_head.tail == self\n            old_head.tail = node\n            node.head = old_head\n        node.tail = self\n        self.head = node",
    "docstring": "Add a node to the head."
  },
  {
    "code": "def close(self):\n        gevent.killall(self._tasks, block=True)\n        self._tasks = []\n        self._ssh.close()",
    "docstring": "Terminate a bridge session"
  },
  {
    "code": "def no_operation(self, onerror = None):\n        request.NoOperation(display = self.display,\n                            onerror = onerror)",
    "docstring": "Do nothing but send a request to the server."
  },
  {
    "code": "def get_settings(all,key):\n    with Database(\"settings\") as s:\n        if all:\n            for k, v in zip(list(s.keys()), list(s.values())):\n                print(\"{} = {}\".format(k, v))\n        elif key:\n            print(\"{} = {}\".format(key, s[key]))\n        else:\n            print(\"Don't know what you want? Try --all\")",
    "docstring": "View Hitman internal settings. Use 'all' for all keys"
  },
  {
    "code": "def create_dn_in_filter(filter_class, filter_value, helper):\n    in_filter = FilterFilter()\n    in_filter.AddChild(create_dn_wcard_filter(filter_class, filter_value))\n    return in_filter",
    "docstring": "Creates filter object for given class name, and DN values."
  },
  {
    "code": "def control(self) -> Optional[HTMLElement]:\n        id = self.getAttribute('for')\n        if id:\n            if self.ownerDocument:\n                return self.ownerDocument.getElementById(id)\n            elif isinstance(id, str):\n                from wdom.document import getElementById\n                return getElementById(id)\n            else:\n                raise TypeError('\"for\" attribute must be string')\n        return None",
    "docstring": "Return related HTMLElement object."
  },
  {
    "code": "def MakeUniformPmf(low, high, n):\n    pmf = Pmf()\n    for x in numpy.linspace(low, high, n):\n        pmf.Set(x, 1)\n    pmf.Normalize()\n    return pmf",
    "docstring": "Make a uniform Pmf.\n\n    low: lowest value (inclusive)\n    high: highest value (inclusize)\n    n: number of values"
  },
  {
    "code": "def colorspace(im, bw=False, replace_alpha=False, **kwargs):\n    if im.mode == 'I':\n        im = im.point(list(_points_table()), 'L')\n    is_transparent = utils.is_transparent(im)\n    is_grayscale = im.mode in ('L', 'LA')\n    new_mode = im.mode\n    if is_grayscale or bw:\n        new_mode = 'L'\n    else:\n        new_mode = 'RGB'\n    if is_transparent:\n        if replace_alpha:\n            if im.mode != 'RGBA':\n                im = im.convert('RGBA')\n            base = Image.new('RGBA', im.size, replace_alpha)\n            base.paste(im, mask=im)\n            im = base\n        else:\n            new_mode = new_mode + 'A'\n    if im.mode != new_mode:\n        im = im.convert(new_mode)\n    return im",
    "docstring": "Convert images to the correct color space.\n\n    A passive option (i.e. always processed) of this method is that all images\n    (unless grayscale) are converted to RGB colorspace.\n\n    This processor should be listed before :func:`scale_and_crop` so palette is\n    changed before the image is resized.\n\n    bw\n        Make the thumbnail grayscale (not really just black & white).\n\n    replace_alpha\n        Replace any transparency layer with a solid color. For example,\n        ``replace_alpha='#fff'`` would replace the transparency layer with\n        white."
  },
  {
    "code": "def hexblock_byte(cls, data,                                address = None,\n                                                                   bits = None,\n                                                              separator = ' ',\n                                                                  width = 16):\n        return cls.hexblock_cb(cls.hexadecimal, data,\n                               address, bits, width,\n                               cb_kwargs = {'separator': separator})",
    "docstring": "Dump a block of hexadecimal BYTEs from binary data.\n\n        @type  data: str\n        @param data: Binary data.\n\n        @type  address: str\n        @param address: Memory address where the data was read from.\n\n        @type  bits: int\n        @param bits:\n            (Optional) Number of bits of the target architecture.\n            The default is platform dependent. See: L{HexDump.address_size}\n\n        @type  separator: str\n        @param separator:\n            Separator between the hexadecimal representation of each BYTE.\n\n        @type  width: int\n        @param width:\n            (Optional) Maximum number of BYTEs to convert per text line.\n\n        @rtype:  str\n        @return: Multiline output text."
  },
  {
    "code": "def get_dicts(self):\n        reader = csv.DictReader(open(self.path, \"r\", encoding=self.encoding))\n        for row in reader:\n            if row:\n                yield row",
    "docstring": "Gets dicts in file\n\n        :return: (generator of) of dicts with data from .csv file"
  },
  {
    "code": "def xdifference(self, to):\n        x,y = 0,1\n        assert self.level == to.level\n        self_tile = list(self.to_tile()[0])\n        to_tile = list(to.to_tile()[0])\n        if self_tile[x] >= to_tile[x] and self_tile[y] <= self_tile[y]:\n            ne_tile, sw_tile = self_tile, to_tile\n        else:\n            sw_tile, ne_tile = self_tile, to_tile\n        cur = ne_tile[:]\n        while cur[x] >= sw_tile[x]:\n            while cur[y] <= sw_tile[y]:\n                yield from_tile(tuple(cur), self.level)\n                cur[y] += 1\n            cur[x] -= 1\n            cur[y] = ne_tile[y]",
    "docstring": "Generator\n            Gives the difference of quadkeys between self and to\n            Generator in case done on a low level\n            Only works with quadkeys of same level"
  },
  {
    "code": "def strip_filter(value):\n    if isinstance(value, basestring):\n        value = bleach.clean(value, tags=ALLOWED_TAGS,\n                             attributes=ALLOWED_ATTRIBUTES, \n                             styles=ALLOWED_STYLES, strip=True)\n    return value",
    "docstring": "Strips HTML tags from strings according to SANITIZER_ALLOWED_TAGS,\n    SANITIZER_ALLOWED_ATTRIBUTES and SANITIZER_ALLOWED_STYLES variables in\n    settings.\n\n    Example usage:\n\n    {% load sanitizer %}\n    {{ post.content|strip_html }}"
  },
  {
    "code": "def random(game):\n    game.valid_moves = tuple(sorted(game.valid_moves, key=lambda _: rand.random()))",
    "docstring": "Prefers moves randomly.\n\n    :param Game game: game to play\n    :return: None"
  },
  {
    "code": "def wait_for_browser_close(b):\n    if b:\n        if not __ACTIVE:\n            wait_failover(wait_for_browser_close)\n            return\n        wait_for_frame(b.GetBrowserImp().GetMainFrame())",
    "docstring": "Can be used to wait until a TBrowser is closed"
  },
  {
    "code": "def log_startup_info():\n    LOG.always(\"Starting mongo-connector version: %s\", __version__)\n    if \"dev\" in __version__:\n        LOG.warning(\n            \"This is a development version (%s) of mongo-connector\", __version__\n        )\n    LOG.always(\"Python version: %s\", sys.version)\n    LOG.always(\"Platform: %s\", platform.platform())\n    if hasattr(pymongo, \"__version__\"):\n        pymongo_version = pymongo.__version__\n    else:\n        pymongo_version = pymongo.version\n    LOG.always(\"pymongo version: %s\", pymongo_version)\n    if not pymongo.has_c():\n        LOG.warning(\n            \"pymongo version %s was installed without the C extensions. \"\n            '\"InvalidBSON: Date value out of range\" errors may occur if '\n            \"there are documents with BSON Datetimes that represent times \"\n            \"outside of Python's datetime limit.\",\n            pymongo.__version__,\n        )",
    "docstring": "Log info about the current environment."
  },
  {
    "code": "def format_terminal_row(headers, example_row):\n    def format_column(col):\n        if isinstance(col, str):\n            return '{{:{w}.{w}}}'\n        return '{{:<{w}}}'\n    widths = [max(len(h), len(str(d))) for h, d in zip(headers, example_row)]\n    original_last_width = widths[-1]\n    if sys.stdout.isatty():\n        widths[-1] = max(\n            len(headers[-1]),\n            tty.width() - sum(w + 2 for w in widths[0:-1]) - 3)\n    cols = [format_column(c).format(w=w) for c, w in zip(example_row, widths)]\n    format_string = '  '.join(cols)\n    if original_last_width > widths[-1]:\n        format_string += '...'\n    return format_string",
    "docstring": "Uses headers and a row of example data to generate a format string\n    for printing a single row of data.\n\n    Args:\n        headers (tuple of strings): The headers for each column of data\n        example_row (tuple): A representative tuple of strings or ints\n\n    Returns\n        string: A format string with a size for each column"
  },
  {
    "code": "def __content_type_matches(self, content_type, available_content_types):\n        if content_type is None:\n            return False\n        if content_type in available_content_types:\n            return True\n        for available_content_type in available_content_types:\n            if available_content_type in content_type:\n                return True\n        return False",
    "docstring": "Check if the given content type matches one of the available content types.\n\n        Args:\n            content_type (str): The given content type.\n            available_content_types list(str): All the available content types.\n\n        Returns:\n            bool: True if a match was found, False otherwise."
  },
  {
    "code": "def get_root_repositories(self):\n        if self._catalog_session is not None:\n            return self._catalog_session.get_root_catalogs()\n        return RepositoryLookupSession(\n            self._proxy,\n            self._runtime).get_repositories_by_ids(list(self.get_root_repository_ids()))",
    "docstring": "Gets the root repositories in the repository hierarchy.\n\n        A node with no parents is an orphan. While all repository\n        ``Ids`` are known to the hierarchy, an orphan does not appear in\n        the hierarchy unless explicitly added as a root node or child of\n        another node.\n\n        return: (osid.repository.RepositoryList) - the root repositories\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method is must be implemented.*"
  },
  {
    "code": "def derive(self, new_version: Union[tuple, list]=None) -> \"Model\":\n        meta = self.meta\n        first_time = self._initial_version == self.version\n        if new_version is None:\n            new_version = meta[\"version\"]\n            new_version[-1] += 1\n        if not isinstance(new_version, (tuple, list)):\n            raise ValueError(\"new_version must be either a list or a tuple, got %s\"\n                             % type(new_version))\n        meta[\"version\"] = list(new_version)\n        if first_time:\n            meta[\"parent\"] = meta[\"uuid\"]\n        meta[\"uuid\"] = str(uuid.uuid4())\n        return self",
    "docstring": "Inherit the new model from the current one - used for versioning. \\\n        This operation is in-place.\n\n        :param new_version: The version of the new model.\n        :return: The derived model - self."
  },
  {
    "code": "def connect(host, port, username, password):\n        session = ftplib.FTP()\n        session.connect(host, port)\n        session.login(username, password)\n        return session",
    "docstring": "Connect and login to an FTP server and return ftplib.FTP object."
  },
  {
    "code": "def _get_chart_info(df, vtype, cat, prep, callers):\n    maxval_raw = max(list(df[\"value.floor\"]))\n    curdf = df[(df[\"variant.type\"] == vtype) & (df[\"category\"] == cat)\n               & (df[\"bamprep\"] == prep)]\n    vals = []\n    labels = []\n    for c in callers:\n        row = curdf[df[\"caller\"] == c]\n        if len(row) > 0:\n            vals.append(list(row[\"value.floor\"])[0])\n            labels.append(list(row[\"value\"])[0])\n        else:\n            vals.append(1)\n            labels.append(\"\")\n    return vals, labels, maxval_raw",
    "docstring": "Retrieve values for a specific variant type, category and prep method."
  },
  {
    "code": "def list_after(self, message_id, limit=None):\n        return self.list(after_id=message_id, limit=limit)",
    "docstring": "Return a page of group messages created after a message.\n\n        This is used to page forwards through messages.\n\n        :param str message_id: the ID of a message\n        :param int limit: maximum number of messages per page\n        :return: group messages\n        :rtype: :class:`~groupy.pagers.MessageList`"
  },
  {
    "code": "def _slice2rows(self, start, stop, step=None):\n        nrows = self._info['nrows']\n        if start is None:\n            start = 0\n        if stop is None:\n            stop = nrows\n        if step is None:\n            step = 1\n        tstart = self._fix_range(start)\n        tstop = self._fix_range(stop)\n        if tstart == 0 and tstop == nrows:\n            return None\n        if stop < start:\n            raise ValueError(\"start is greater than stop in slice\")\n        return numpy.arange(tstart, tstop, step, dtype='i8')",
    "docstring": "Convert a slice to an explicit array of rows"
  },
  {
    "code": "def _read_repos(conf_file, repos, filename, regex):\n    for line in conf_file:\n        line = salt.utils.stringutils.to_unicode(line)\n        if not regex.search(line):\n            continue\n        repo = _create_repo(line, filename)\n        if repo['uri'] not in repos:\n            repos[repo['uri']] = [repo]",
    "docstring": "Read repos from configuration file"
  },
  {
    "code": "def _ToJsonName(name):\n  capitalize_next = False\n  result = []\n  for c in name:\n    if c == '_':\n      capitalize_next = True\n    elif capitalize_next:\n      result.append(c.upper())\n      capitalize_next = False\n    else:\n      result += c\n  return ''.join(result)",
    "docstring": "Converts name to Json name and returns it."
  },
  {
    "code": "def install_time(self):\n        time1970 = self.__mod_time1970\n        try:\n            date_string, item_type = \\\n                win32api.RegQueryValueEx(self.__reg_uninstall_handle, 'InstallDate')\n        except pywintypes.error as exc:\n            if exc.winerror == winerror.ERROR_FILE_NOT_FOUND:\n                return time1970\n            else:\n                raise\n        if item_type == win32con.REG_SZ:\n            try:\n                date_object = datetime.datetime.strptime(date_string, \"%Y%m%d\")\n                time1970 = time.mktime(date_object.timetuple())\n            except ValueError:\n                pass\n        return time1970",
    "docstring": "Return the install time, or provide an estimate of install time.\n\n        Installers or even self upgrading software must/should update the date\n        held within InstallDate field when they change versions. Some installers\n        do not set ``InstallDate`` at all so we use the last modified time on the\n        registry key.\n\n        Returns:\n            int: Seconds since 1970 UTC."
  },
  {
    "code": "def query(self):\n        if not self.b64_query:\n            return None\n        s = QSerializer(base64=True)\n        return s.loads(self.b64_query)",
    "docstring": "De-serialize, decode and return an ORM query stored in b64_query."
  },
  {
    "code": "def commit(self, session=None):\n        if self.__cleared:\n            return\n        if self._parent:\n            self._commit_parent()\n        else:\n            self._commit_repository()\n        self._clear()",
    "docstring": "Merge modified objects into parent transaction.\n\n        Once commited a transaction object is not usable anymore\n\n        :param:session: current sqlalchemy Session"
  },
  {
    "code": "def configure(self, transport, auth, address, port):\n        self.transport = transport\n        self.username = auth.username\n        self.address = address\n        self.port = port",
    "docstring": "Connect paramiko transport\n\n        :type auth: :py:class`margaritashotgun.auth.AuthMethods`\n        :param auth: authentication object\n        :type address: str\n        :param address: remote server ip or hostname\n        :type port: int\n        :param port: remote server port\n        :type hostkey: :py:class:`paramiko.key.HostKey`\n        :param hostkey: remote host ssh server key"
  },
  {
    "code": "def get_workflow_actions(obj):\n    def translate(id):\n        return t(PMF(id + \"_transition_title\"))\n    transids = getAllowedTransitions(obj)\n    actions = [{'id': it, 'title': translate(it)} for it in transids]\n    return actions",
    "docstring": "Compile a list of possible workflow transitions for this object"
  },
  {
    "code": "def home(self) -> 'InstrumentContext':\n        def home_dummy(mount): pass\n        cmds.do_publish(self.broker, cmds.home, home_dummy,\n                        'before', None, None, self._mount.name.lower())\n        self._hw_manager.hardware.home_z(self._mount)\n        self._hw_manager.hardware.home_plunger(self._mount)\n        cmds.do_publish(self.broker, cmds.home, home_dummy,\n                        'after', self, None, self._mount.name.lower())\n        return self",
    "docstring": "Home the robot.\n\n        :returns: This instance."
  },
  {
    "code": "def combine_inputs(self, args, kw, ignore_args):\n        \"Combines the args and kw in a unique way, such that ordering of kwargs does not lead to recompute\"\n        inputs= args + tuple(c[1] for c in sorted(kw.items(), key=lambda x: x[0]))\n        return [a for i,a in enumerate(inputs) if i not in ignore_args]",
    "docstring": "Combines the args and kw in a unique way, such that ordering of kwargs does not lead to recompute"
  },
  {
    "code": "def _ParseIdentifierMappingsTable(self, parser_mediator, esedb_table):\n    identifier_mappings = {}\n    for esedb_record in esedb_table.records:\n      if parser_mediator.abort:\n        break\n      identifier, mapped_value = self._ParseIdentifierMappingRecord(\n          parser_mediator, esedb_table.name, esedb_record)\n      if identifier is None or mapped_value is None:\n        continue\n      if identifier in identifier_mappings:\n        parser_mediator.ProduceExtractionWarning(\n            'identifier: {0:d} already exists in mappings.'.format(identifier))\n        continue\n      identifier_mappings[identifier] = mapped_value\n    return identifier_mappings",
    "docstring": "Extracts identifier mappings from the SruDbIdMapTable table.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      esedb_table (pyesedb.table): table.\n\n    Returns:\n      dict[int, str]: mapping of numeric identifiers to their string\n          representation."
  },
  {
    "code": "def enqueue_data(self, event_type, data):\n        with self.lock:\n            listeners = self.listeners.values()\n            for listener in listeners:\n                listener.enqueue(event_type, data)\n                self.must_process = True",
    "docstring": "Enqueue a data item for specific event type"
  },
  {
    "code": "def _collapse_to_cwl_record_single(data, want_attrs, input_files):\n    out = {}\n    for key in want_attrs:\n        key_parts = key.split(\"__\")\n        out[key] = _to_cwl(tz.get_in(key_parts, data), input_files)\n    return out",
    "docstring": "Convert a single sample into a CWL record."
  },
  {
    "code": "def set_string(self, option, value):\n        if not isinstance(value, str):\n            raise TypeError(\"%s must be a string\" % option)\n        self.options[option] = value",
    "docstring": "Set a string option.\n\n            Args:\n                option (str): name of option.\n                value (str): value of the option.\n\n            Raises:\n                TypeError: Value must be a string."
  },
  {
    "code": "def preprocess_topics(source_groupid, source_topics, dest_groupid, topics_dest_group):\n    common_topics = [topic for topic in topics_dest_group if topic in source_topics]\n    if common_topics:\n        print(\n            \"Error: Consumer Group ID: {groupid} is already \"\n            \"subscribed to following topics: {topic}.\\nPlease delete this \"\n            \"topics from new group before re-running the \"\n            \"command.\".format(\n                groupid=dest_groupid,\n                topic=', '.join(common_topics),\n            ),\n            file=sys.stderr,\n        )\n        sys.exit(1)\n    if topics_dest_group:\n        in_str = (\n            \"New Consumer Group: {dest_groupid} already \"\n            \"exists.\\nTopics subscribed to by the consumer groups are listed \"\n            \"below:\\n{source_groupid}: {source_group_topics}\\n\"\n            \"{dest_groupid}: {dest_group_topics}\\nDo you intend to copy into\"\n            \"existing consumer destination-group? (y/n)\".format(\n                source_groupid=source_groupid,\n                source_group_topics=source_topics,\n                dest_groupid=dest_groupid,\n                dest_group_topics=topics_dest_group,\n            )\n        )\n        prompt_user_input(in_str)",
    "docstring": "Pre-process the topics in source and destination group for duplicates."
  },
  {
    "code": "def import_file(self, filepath, filterindex):\n        post_command_event(self.main_window, self.ContentChangedMsg)\n        if filterindex == 0:\n            return self._import_csv(filepath)\n        elif filterindex == 1:\n            return self._import_txt(filepath)\n        else:\n            msg = _(\"Unknown import choice {choice}.\")\n            msg = msg.format(choice=filterindex)\n            short_msg = _('Error reading CSV file')\n            self.main_window.interfaces.display_warning(msg, short_msg)",
    "docstring": "Imports external file\n\n        Parameters\n        ----------\n\n        filepath: String\n        \\tPath of import file\n        filterindex: Integer\n        \\tIndex for type of file, 0: csv, 1: tab-delimited text file"
  },
  {
    "code": "def init_default(self):\n        import f311\n        if self.default_filename is None:\n            raise RuntimeError(\"Class '{}' has no default filename\".format(self.__class__.__name__))\n        fullpath = f311.get_default_data_path(self.default_filename, class_=self.__class__)\n        self.load(fullpath)\n        self.filename = None",
    "docstring": "Initializes object with its default values\n\n        Tries to load self.default_filename from default\n        data directory. For safety, filename is reset to None so that it doesn't point to the\n        original file."
  },
  {
    "code": "def get_sequence_rules_by_genus_type(self, sequence_rule_genus_type):\n        collection = JSONClientValidated('assessment_authoring',\n                                         collection='SequenceRule',\n                                         runtime=self._runtime)\n        result = collection.find(\n            dict({'genusTypeId': str(sequence_rule_genus_type)},\n                 **self._view_filter())).sort('_id', DESCENDING)\n        return objects.SequenceRuleList(result, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets a ``SequenceRuleList`` corresponding to the given sequence rule genus ``Type`` which does not include sequence rule of genus types derived from the specified ``Type``.\n\n        arg:    sequence_rule_genus_type (osid.type.Type): a sequence\n                rule genus type\n        return: (osid.assessment.authoring.SequenceRuleList) - the\n                returned ``SequenceRule`` list\n        raise:  NullArgument - ``sequence_rule_genus_type`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def descendants(self):\n        for i in self.current_item.items:\n            self.move_to(i)\n            if i.type == TYPE_COLLECTION:\n                for c in self.children:\n                    yield c\n            else:\n                yield i\n            self.move_up()",
    "docstring": "Recursively return every dataset below current item."
  },
  {
    "code": "def check_type_of_nest_spec_keys_and_values(nest_spec):\n    try:\n        assert all([isinstance(k, str) for k in nest_spec])\n        assert all([isinstance(nest_spec[k], list) for k in nest_spec])\n    except AssertionError:\n        msg = \"All nest_spec keys/values must be strings/lists.\"\n        raise TypeError(msg)\n    return None",
    "docstring": "Ensures that the keys and values of `nest_spec` are strings and lists.\n    Raises a helpful ValueError if they are.\n\n    Parameters\n    ----------\n    nest_spec : OrderedDict, or None, optional.\n        Keys are strings that define the name of the nests. Values are lists of\n        alternative ids, denoting which alternatives belong to which nests.\n        Each alternative id must only be associated with a single nest!\n        Default == None.\n\n    Returns\n    -------\n    None."
  },
  {
    "code": "def _update_nonce_explicit(self):\n        ne = self.nonce_explicit + 1\n        self.nonce_explicit = ne % 2**(self.nonce_explicit_len * 8)",
    "docstring": "Increment the explicit nonce while avoiding any overflow."
  },
  {
    "code": "def prepare_destruction(self):\n        self._tool = None\n        self._painter = None\n        self.relieve_model(self._selection)\n        self._selection = None\n        self._Observer__PROP_TO_METHS.clear()\n        self._Observer__METH_TO_PROPS.clear()\n        self._Observer__PAT_TO_METHS.clear()\n        self._Observer__METH_TO_PAT.clear()\n        self._Observer__PAT_METH_TO_KWARGS.clear()",
    "docstring": "Get rid of circular references"
  },
  {
    "code": "def _expand_to_beam_size(tensor, beam_size):\n  tensor = tf.expand_dims(tensor, axis=1)\n  tile_dims = [1] * tensor.shape.ndims\n  tile_dims[1] = beam_size\n  return tf.tile(tensor, tile_dims)",
    "docstring": "Tiles a given tensor by beam_size.\n\n  Args:\n    tensor: tensor to tile [batch_size, ...]\n    beam_size: How much to tile the tensor by.\n\n  Returns:\n    Tiled tensor [batch_size, beam_size, ...]"
  },
  {
    "code": "def AddShowToTVLibrary(self, showName):\n    goodlogging.Log.Info(\"DB\", \"Adding {0} to TV library\".format(showName), verbosity=self.logVerbosity)\n    currentShowValues = self.SearchTVLibrary(showName = showName)\n    if currentShowValues is None:\n      self._ActionDatabase(\"INSERT INTO TVLibrary (ShowName) VALUES (?)\", (showName, ))\n      showID = self._ActionDatabase(\"SELECT (ShowID) FROM TVLibrary WHERE ShowName=?\", (showName, ))[0][0]\n      return showID\n    else:\n      goodlogging.Log.Fatal(\"DB\", \"An entry for {0} already exists in the TV library\".format(showName))",
    "docstring": "Add show to TVLibrary table. If the show already exists in the table\n    a fatal error is raised.\n\n    Parameters\n    ----------\n      showName : string\n        Show name to add to TV library table.\n\n    Returns\n    ----------\n      int\n        Unique show id generated for show when it is added to the table. Used\n        across the database to reference this show."
  },
  {
    "code": "def is_step_visible(self, step):\n        return self.idempotent_dict.get(step, True) or \\\n            step not in self.storage.validated_step_data",
    "docstring": "Returns whether the given `step` should be included in the wizard; it\n        is included if either the form is idempotent or not filled in before."
  },
  {
    "code": "def split_cmdline(cmdline):\n    path, cmd = os.path.split(cmdline[0])\n    arguments = ' '.join(cmdline[1:])\n    return path, cmd, arguments",
    "docstring": "Return path, cmd and arguments for a process cmdline."
  },
  {
    "code": "def _get_field_mapping(self, schema):\n        if 'mapping' in schema:\n            return schema['mapping']\n        elif schema['type'] == 'dict' and 'schema' in schema:\n            return self._get_mapping(schema['schema'])\n        elif schema['type'] == 'list' and 'schema' in schema.get('schema', {}):\n            return self._get_mapping(schema['schema']['schema'])\n        elif schema['type'] == 'datetime':\n            return {'type': 'date'}\n        elif schema['type'] == 'string' and schema.get('unique'):\n            return {'type': 'string', 'index': 'not_analyzed'}",
    "docstring": "Get mapping for single field schema.\n\n        :param schema: field schema"
  },
  {
    "code": "def rebuild( self ):\r\n        plugins.init()\r\n        self.blockSignals(True)\r\n        self.setUpdatesEnabled(False)\r\n        if ( self._editor ):\r\n            self._editor.close()\r\n            self._editor.setParent(None)\r\n            self._editor.deleteLater()\r\n            self._editor = None\r\n        plugin_class = plugins.widgets.get(self._columnType)\r\n        if ( plugin_class ):\r\n            self._editor = plugin_class(self)\r\n            self.layout().addWidget(self._editor)\r\n        self.blockSignals(False)\r\n        self.setUpdatesEnabled(True)",
    "docstring": "Clears out all the child widgets from this widget and creates the \r\n        widget that best matches the column properties for this edit."
  },
  {
    "code": "def load(self, infile):\n        model = pickle.load(infile)\n        self.__dict__.update(model.__dict__)",
    "docstring": "Deserialize a model from a stored file.\n\n        By default, unpickle an entire object. If `dump` is overridden to\n        use a different storage format, `load` should be as well.\n\n        :param file outfile: A file-like object from which to retrieve the\n            serialized model."
  },
  {
    "code": "def setmem(vm_, memory, config=False, **kwargs):\n    conn = __get_conn(**kwargs)\n    dom = _get_domain(conn, vm_)\n    if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown':\n        return False\n    flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM\n    if config:\n        flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG\n    ret1 = dom.setMemoryFlags(memory * 1024, flags)\n    ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT)\n    conn.close()\n    return ret1 == ret2 == 0",
    "docstring": "Changes the amount of memory allocated to VM. The VM must be shutdown\n    for this to work.\n\n    :param vm_: name of the domain\n    :param memory: memory amount to set in MB\n    :param config: if True then libvirt will be asked to modify the config as well\n    :param connection: libvirt connection URI, overriding defaults\n\n        .. versionadded:: 2019.2.0\n    :param username: username to connect with, overriding defaults\n\n        .. versionadded:: 2019.2.0\n    :param password: password to connect with, overriding defaults\n\n        .. versionadded:: 2019.2.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' virt.setmem <domain> <size>\n        salt '*' virt.setmem my_domain 768"
  },
  {
    "code": "def in6_getLocalUniquePrefix():\n    tod = time.time()\n    i = int(tod)\n    j = int((tod - i) * (2**32))\n    tod = struct.pack(\"!II\", i, j)\n    mac = RandMAC()\n    eui64 = inet_pton(socket.AF_INET6, '::' + in6_mactoifaceid(mac))[8:]\n    import hashlib\n    globalid = hashlib.sha1(tod + eui64).digest()[:5]\n    return inet_ntop(socket.AF_INET6, b'\\xfd' + globalid + b'\\x00' * 10)",
    "docstring": "Returns a pseudo-randomly generated Local Unique prefix. Function\n    follows recommendation of Section 3.2.2 of RFC 4193 for prefix\n    generation."
  },
  {
    "code": "def _get_token():\n    username = __opts__.get('rallydev', {}).get('username', None)\n    password = __opts__.get('rallydev', {}).get('password', None)\n    path = 'https://rally1.rallydev.com/slm/webservice/v2.0/security/authorize'\n    result = salt.utils.http.query(\n        path,\n        decode=True,\n        decode_type='json',\n        text=True,\n        status=True,\n        username=username,\n        password=password,\n        cookies=True,\n        persist_session=True,\n        opts=__opts__,\n    )\n    if 'dict' not in result:\n        return None\n    return result['dict']['OperationResult']['SecurityToken']",
    "docstring": "Get an auth token"
  },
  {
    "code": "def draw(self, **kwargs):\n        x = self.n_feature_subsets_\n        means = self.cv_scores_.mean(axis=1)\n        sigmas = self.cv_scores_.std(axis=1)\n        self.ax.fill_between(x, means - sigmas, means+sigmas, alpha=0.25)\n        self.ax.plot(x, means, 'o-')\n        self.ax.axvline(\n            self.n_features_, c='k', ls='--',\n            label=\"n_features = {}\\nscore = {:0.3f}\".format(\n                self.n_features_, self.cv_scores_.mean(axis=1).max()\n            )\n        )\n        return self.ax",
    "docstring": "Renders the rfecv curve."
  },
  {
    "code": "def charm_dir():\n    d = os.environ.get('JUJU_CHARM_DIR')\n    if d is not None:\n        return d\n    return os.environ.get('CHARM_DIR')",
    "docstring": "Return the root directory of the current charm"
  },
  {
    "code": "def gid_exists(gid):\n    try:\n        grp.getgrgid(gid)\n        gid_exists = True\n    except KeyError:\n        gid_exists = False\n    return gid_exists",
    "docstring": "Check if a gid exists"
  },
  {
    "code": "def create_changelog(project_dir=os.curdir, bugtracker_url='',\n                     rpm_format=False):\n    pkg_info_file = os.path.join(project_dir, 'PKG-INFO')\n    if os.path.exists(pkg_info_file):\n        return\n    with open('CHANGELOG', 'wb') as changelog_fd:\n        changelog_fd.write(\n            get_changelog(\n                project_dir=project_dir,\n                bugtracker_url=bugtracker_url,\n                rpm_format=rpm_format,\n            ).encode('utf-8')\n        )",
    "docstring": "Creates the changelog file, if not in a package.\n\n    :param project_dir: Path to the git repo of the project.\n    :type project_dir: str\n    :param bugtracker_url: Url to the bug tracker for the issues.\n    :type bugtracker_url: str\n    :param rpm_format: if set to True, will make the changelog rpm-compatible.\n    :type rpm_format: bool\n    :rises RuntimeError: If the changelog could not be retrieved"
  },
  {
    "code": "def track(*fields):\n    def inner(cls):\n        _track_class(cls, fields)\n        _add_get_tracking_url(cls)\n        return cls\n    return inner",
    "docstring": "Decorator used to track changes on Model's fields.\n\n       :Example:\n       >>> @track('name')\n       ... class Human(models.Model):\n       ...     name = models.CharField(max_length=30)"
  },
  {
    "code": "def master_pub(self):\n        return _get_master_uri(self.opts['master_ip'],\n                               self.publish_port,\n                               source_ip=self.opts.get('source_ip'),\n                               source_port=self.opts.get('source_publish_port'))",
    "docstring": "Return the master publish port"
  },
  {
    "code": "def get_all_current_trains(self, train_type=None, direction=None):\n        params = None\n        if train_type:\n            url = self.api_base_url + 'getCurrentTrainsXML_WithTrainType'\n            params = {\n                'TrainType': STATION_TYPE_TO_CODE_DICT[train_type]\n            }\n        else:\n            url = self.api_base_url + 'getCurrentTrainsXML'\n        response = requests.get(\n            url, params=params, timeout=10)\n        if response.status_code != 200:\n            return []\n        trains = self._parse_all_train_data(response.content)\n        if direction is not None:\n            return self._prune_trains(trains, direction=direction)\n        return trains",
    "docstring": "Returns all trains that are due to start in the next 10 minutes\n        @param train_type: ['mainline', 'suburban', 'dart']"
  },
  {
    "code": "def safe_version(version):\n    try:\n        return str(packaging.version.Version(version))\n    except packaging.version.InvalidVersion:\n        version = version.replace(' ', '.')\n        return re.sub('[^A-Za-z0-9.]+', '-', version)",
    "docstring": "Convert an arbitrary string to a standard version string"
  },
  {
    "code": "def tiles_are_equal(tile_data_1, tile_data_2, fmt):\n    if fmt and fmt == zip_format:\n        return metatiles_are_equal(tile_data_1, tile_data_2)\n    else:\n        return tile_data_1 == tile_data_2",
    "docstring": "Returns True if the tile data is equal in tile_data_1 and tile_data_2. For\n    most formats, this is a simple byte-wise equality check. For zipped\n    metatiles, we need to check the contents, as the zip format includes\n    metadata such as timestamps and doesn't control file ordering."
  },
  {
    "code": "def where(self, predicate):\n        if self.closed():\n            raise ValueError(\"Attempt to call where() on a closed Queryable.\")\n        if not is_callable(predicate):\n            raise TypeError(\"where() parameter predicate={predicate} is not \"\n                                  \"callable\".format(predicate=repr(predicate)))\n        return self._create(ifilter(predicate, self))",
    "docstring": "Filters elements according to whether they match a predicate.\n\n        Note: This method uses deferred execution.\n\n        Args:\n            predicate: A unary function which is applied to each element in the\n                source sequence. Source elements for which the predicate\n                returns True will be present in the result.\n\n        Returns:\n            A Queryable over those elements of the source sequence for which\n            the predicate is True.\n\n        Raises:\n            ValueError: If the Queryable is closed.\n            TypeError: If the predicate is not callable."
  },
  {
    "code": "def watch(self, selector, callback):\n        if selector not in self._monitors:\n            self._monitors[selector] = set()\n        self._monitors[selector].add(callback)",
    "docstring": "Call a function whenever a stream changes.\n\n        Args:\n            selector (DataStreamSelector): The selector to watch.\n                If this is None, it is treated as a wildcard selector\n                that matches every stream.\n            callback (callable): The function to call when a new\n                reading is pushed.  Callback is called as:\n                callback(stream, value)"
  },
  {
    "code": "def sign_statement(self, statement, node_name, key=None, key_file=None, node_id=None, id_attr=''):\n        if not id_attr:\n            id_attr = self.id_attr\n        if not key_file and key:\n            _, key_file = make_temp(str(key).encode(), '.pem')\n        if not key and not key_file:\n            key_file = self.key_file\n        return self.crypto.sign_statement(\n                statement,\n                node_name,\n                key_file,\n                node_id,\n                id_attr)",
    "docstring": "Sign a SAML statement.\n\n        :param statement: The statement to be signed\n        :param node_name: string like 'urn:oasis:names:...:Assertion'\n        :param key: The key to be used for the signing, either this or\n        :param key_file: The file where the key can be found\n        :param node_id:\n        :param id_attr: The attribute name for the identifier, normally one of\n            'id','Id' or 'ID'\n        :return: The signed statement"
  },
  {
    "code": "def load(self, data, many=None, partial=None):\n        result = super(ResumptionTokenSchema, self).load(\n            data, many=many, partial=partial\n        )\n        result.data.update(\n            result.data.get('resumptionToken', {}).get('kwargs', {})\n        )\n        return result",
    "docstring": "Deserialize a data structure to an object."
  },
  {
    "code": "def post_build(self, pkt, pay):\n        if self.length is None:\n            pkt = pkt[:4] + chb(len(pay)) + pkt[5:]\n        return pkt + pay",
    "docstring": "This will set the ByteField 'length' to the correct value."
  },
  {
    "code": "def bar(h: Histogram2D, *,\n        barmode: str = DEFAULT_BARMODE,\n        alpha: float = DEFAULT_ALPHA,\n        **kwargs):\n    get_data_kwargs = pop_many(kwargs, \"density\", \"cumulative\", \"flatten\")\n    data = [go.Bar(\n        x=histogram.bin_centers,\n        y=get_data(histogram, **get_data_kwargs),\n        width=histogram.bin_widths,\n        name=histogram.name,\n        opacity=alpha,\n        **kwargs\n    ) for histogram in h]\n    layout = go.Layout(barmode=barmode)\n    _add_ticks(layout.xaxis, h[0], kwargs)\n    figure = go.Figure(data=data, layout=layout)\n    return figure",
    "docstring": "Bar plot.\n\n    Parameters\n    ----------\n    alpha: Opacity (0.0 - 1.0)\n    barmode : \"overlay\" | \"group\" | \"stack\""
  },
  {
    "code": "def mkdir(self, pathobj, _):\n        if not pathobj.drive or not pathobj.root:\n            raise RuntimeError(\"Full path required: '%s'\" % str(pathobj))\n        if pathobj.exists():\n            raise OSError(17, \"File exists: '%s'\" % str(pathobj))\n        url = str(pathobj) + '/'\n        text, code = self.rest_put(url, session=pathobj.session, verify=pathobj.verify, cert=pathobj.cert)\n        if not code == 201:\n            raise RuntimeError(\"%s %d\" % (text, code))",
    "docstring": "Creates remote directory\n        Note that this operation is not recursive"
  },
  {
    "code": "def _query_select_options(self, query, select_columns=None):\n        if select_columns:\n            _load_options = list()\n            for column in select_columns:\n                if \".\" in column:\n                    model_relation = self.get_related_model(column.split(\".\")[0])\n                    if not self.is_model_already_joinded(query, model_relation):\n                        query = query.join(model_relation)\n                    _load_options.append(\n                        Load(model_relation).load_only(column.split(\".\")[1])\n                    )\n                else:\n                    if not self.is_relation(column) and not hasattr(\n                        getattr(self.obj, column), \"__call__\"\n                    ):\n                        _load_options.append(Load(self.obj).load_only(column))\n                    else:\n                        _load_options.append(Load(self.obj))\n            query = query.options(*tuple(_load_options))\n        return query",
    "docstring": "Add select load options to query. The goal\n            is to only SQL select what is requested\n\n        :param query: SQLAlchemy Query obj\n        :param select_columns: (list) of columns\n        :return: SQLAlchemy Query obj"
  },
  {
    "code": "def put_cache(self, minions):\n        self.cupd_out.send(self.serial.dumps(minions))",
    "docstring": "published the given minions to the ConCache"
  },
  {
    "code": "def coarse_grain(G, ncg):\n        if ncg <= 1:\n            return G\n        G = numpy.asarray(G)\n        nbin, remainder = divmod(G.shape[-1], ncg)\n        if remainder != 0:\n            nbin += 1\n        return numpy.transpose([\n            numpy.sum(G[..., i:i+ncg], axis=-1) / G[..., i:i+ncg].shape[-1]\n            for i in numpy.arange(0, ncg * nbin, ncg)\n            ])",
    "docstring": "Coarse-grain last index of array ``G``.\n\n        Bin the last index of array ``G`` in bins of width ``ncg``, and\n        replace each bin by its average. Return the binned results.\n\n        Args:\n            G: Array to be coarse-grained.\n            ncg: Bin width for coarse-graining."
  },
  {
    "code": "def check_bidi(chars):\n    if not chars:\n        return\n    has_RandALCat = any(is_RandALCat(c) for c in chars)\n    if not has_RandALCat:\n        return\n    has_LCat = any(is_LCat(c) for c in chars)\n    if has_LCat:\n        raise ValueError(\"L and R/AL characters must not occur in the same\"\n                         \" string\")\n    if not is_RandALCat(chars[0]) or not is_RandALCat(chars[-1]):\n        raise ValueError(\"R/AL string must start and end with R/AL character.\")",
    "docstring": "Check proper bidirectionality as per stringprep. Operates on a list of\n    unicode characters provided in `chars`."
  },
  {
    "code": "def _add_finder(importer, finder):\n  existing_finder = _get_finder(importer)\n  if not existing_finder:\n    pkg_resources.register_finder(importer, finder)\n  else:\n    pkg_resources.register_finder(importer, ChainedFinder.of(existing_finder, finder))",
    "docstring": "Register a new pkg_resources path finder that does not replace the existing finder."
  },
  {
    "code": "def grid_reload_from_ids(oargrid_jobids):\n    gk = get_api_client()\n    jobs = []\n    for site, job_id in oargrid_jobids:\n        jobs.append(gk.sites[site].jobs[job_id])\n    return jobs",
    "docstring": "Reload all running or pending jobs of Grid'5000 from their ids\n\n    Args:\n        oargrid_jobids (list): list of ``(site, oar_jobid)`` identifying the\n            jobs on each site\n\n    Returns:\n        The list of python-grid5000 jobs retrieved"
  },
  {
    "code": "def list_files(start_path):\n    s = u'\\n'\n    for root, dirs, files in os.walk(start_path):\n        level = root.replace(start_path, '').count(os.sep)\n        indent = ' ' * 4 * level\n        s += u'{}{}/\\n'.format(indent, os.path.basename(root))\n        sub_indent = ' ' * 4 * (level + 1)\n        for f in files:\n            s += u'{}{}\\n'.format(sub_indent, f)\n    return s",
    "docstring": "tree unix command replacement."
  },
  {
    "code": "def remove_gaps(A, B):\n    a_seq, b_seq = [], []\n    for a, b in zip(list(A), list(B)):\n        if a == '-' or a == '.' or b == '-' or b == '.':\n            continue\n        a_seq.append(a)\n        b_seq.append(b)\n    return ''.join(a_seq), ''.join(b_seq)",
    "docstring": "skip column if either is a gap"
  },
  {
    "code": "def channels_kick(self, room_id, user_id, **kwargs):\n        return self.__call_api_post('channels.kick', roomId=room_id, userId=user_id, kwargs=kwargs)",
    "docstring": "Removes a user from the channel."
  },
  {
    "code": "def _assemble_complex(stmt):\n    member_strs = [_assemble_agent_str(m) for m in stmt.members]\n    stmt_str = member_strs[0] + ' binds ' + _join_list(member_strs[1:])\n    return _make_sentence(stmt_str)",
    "docstring": "Assemble Complex statements into text."
  },
  {
    "code": "def is_micropython_usb_device(port):\n    if type(port).__name__ == 'Device':\n        if ('ID_BUS' not in port or port['ID_BUS'] != 'usb' or\n            'SUBSYSTEM' not in port or port['SUBSYSTEM'] != 'tty'):\n            return False\n        usb_id = 'usb vid:pid={}:{}'.format(port['ID_VENDOR_ID'], port['ID_MODEL_ID'])\n    else:\n        usb_id = port[2].lower()\n    if usb_id.startswith('usb vid:pid=f055:980'):\n        return True\n    if usb_id.startswith('usb vid:pid=16c0:0483'):\n        return True\n    return False",
    "docstring": "Checks a USB device to see if it looks like a MicroPython device."
  },
  {
    "code": "def read_stats(self):\n        self.statistics = TgnObjectsDict()\n        for port in self.session.ports.values():\n            self.statistics[port] = port.read_port_stats()\n        return self.statistics",
    "docstring": "Read current ports statistics from chassis.\n\n        :return: dictionary {port name {group name, {stat name: stat value}}}"
  },
  {
    "code": "def generateRandomSymbol(numColumns, sparseCols):\n  symbol = list()\n  remainingCols = sparseCols\n  while remainingCols > 0:\n    col = random.randrange(numColumns)\n    if col not in symbol:\n      symbol.append(col)\n      remainingCols -= 1\n  return symbol",
    "docstring": "Generates a random SDR with sparseCols number of active columns\n  \n  @param numColumns (int) number of columns in the temporal memory\n  @param sparseCols (int) number of sparse columns for desired SDR  \n  @return symbol (list) SDR"
  },
  {
    "code": "def addParameter( self, k, r ):\n        if isinstance(r, six.string_types) or not isinstance(r, collections.Iterable):\n            r = [ r ]\n        else:\n            if isinstance(r, collections.Iterable):\n                r = list(r)\n        self._parameters[k] = r",
    "docstring": "Add a parameter to the experiment's parameter space. k is the\n        parameter name, and r is its range.\n\n        :param k: parameter name\n        :param r: parameter range"
  },
  {
    "code": "def read_jp2_image(filename):\n    image = read_image(filename)\n    with open(filename, 'rb') as file:\n        bit_depth = get_jp2_bit_depth(file)\n    return fix_jp2_image(image, bit_depth)",
    "docstring": "Read data from JPEG2000 file\n\n    :param filename: name of JPEG2000 file to be read\n    :type filename: str\n    :return: data stored in JPEG2000 file"
  },
  {
    "code": "async def add(client: Client, identity_signed_raw: str) -> ClientResponse:\n    return await client.post(MODULE + '/add', {'identity': identity_signed_raw}, rtype=RESPONSE_AIOHTTP)",
    "docstring": "POST identity raw document\n\n    :param client: Client to connect to the api\n    :param identity_signed_raw: Identity raw document\n    :return:"
  },
  {
    "code": "def get_states(self, config_ids):\n        return itertools.chain.from_iterable(self.generate_config_states(config_id)\n                                             for config_id in config_ids)",
    "docstring": "Generates state information for the selected containers.\n\n        :param config_ids: List of MapConfigId tuples.\n        :type config_ids: list[dockermap.map.input.MapConfigId]\n        :return: Iterable of configuration states.\n        :rtype: collections.Iterable[dockermap.map.state.ConfigState]"
  },
  {
    "code": "def gpg_version():\n    cmd = flatten([gnupg_bin(), \"--version\"])\n    output = stderr_output(cmd)\n    output = output \\\n        .split('\\n')[0] \\\n        .split(\" \")[2] \\\n        .split('.')\n    return tuple([int(x) for x in output])",
    "docstring": "Returns the GPG version"
  },
  {
    "code": "def close(self):\n        if not self._process:\n            return\n        if self._process.returncode is not None:\n            return\n        _logger.debug('Terminate process.')\n        try:\n            self._process.terminate()\n        except OSError as error:\n            if error.errno != errno.ESRCH:\n                raise\n        for dummy in range(10):\n            if self._process.returncode is not None:\n                return\n            time.sleep(0.05)\n        _logger.debug('Failed to terminate. Killing.')\n        try:\n            self._process.kill()\n        except OSError as error:\n            if error.errno != errno.ESRCH:\n                raise",
    "docstring": "Terminate or kill the subprocess.\n\n        This function is blocking."
  },
  {
    "code": "async def send_rpc_message(self, message, context):\n        conn_string = message.get('connection_string')\n        rpc_id = message.get('rpc_id')\n        address = message.get('address')\n        timeout = message.get('timeout')\n        payload = message.get('payload')\n        client_id = context.user_data\n        self._logger.debug(\"Calling RPC %d:0x%04X with payload %s on %s\",\n                           address, rpc_id, payload, conn_string)\n        response = bytes()\n        err = None\n        try:\n            response = await self.send_rpc(client_id, conn_string, address, rpc_id, payload, timeout=timeout)\n        except VALID_RPC_EXCEPTIONS as internal_err:\n            err = internal_err\n        except (DeviceAdapterError, DeviceServerError):\n            raise\n        except Exception as internal_err:\n            self._logger.warning(\"Unexpected exception calling RPC %d:0x%04x\", address, rpc_id, exc_info=True)\n            raise ServerCommandError('send_rpc', str(internal_err)) from internal_err\n        status, response = pack_rpc_response(response, err)\n        return {\n            'status': status,\n            'payload': base64.b64encode(response)\n        }",
    "docstring": "Handle a send_rpc message.\n\n        See :meth:`AbstractDeviceAdapter.send_rpc`."
  },
  {
    "code": "def get_last_modified_timestamp(self):\n        cmd = \"find . -print0 | xargs -0 stat -f '%T@ %p' | sort -n | tail -1 | cut -f2- -d' '\"\n        ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)\n        output = ps.communicate()[0]\n        print output",
    "docstring": "Looks at the files in a git root directory and grabs the last modified timestamp"
  },
  {
    "code": "def subvolume_deleted(name, device, commit=False, __dest=None):\n    ret = {\n        'name': name,\n        'result': False,\n        'changes': {},\n        'comment': [],\n    }\n    path = os.path.join(__dest, name)\n    exists = __salt__['btrfs.subvolume_exists'](path)\n    if not exists:\n        ret['comment'].append('Subvolume {} already missing'.format(name))\n    if __opts__['test']:\n        ret['result'] = None\n        if exists:\n            ret['comment'].append('Subvolume {} will be removed'.format(name))\n        return ret\n    commit = 'after' if commit else None\n    if not exists:\n        try:\n            __salt__['btrfs.subvolume_delete'](path, commit=commit)\n        except CommandExecutionError:\n            ret['comment'].append('Error removing subvolume {}'.format(name))\n            return ret\n        ret['changes'][name] = 'Removed subvolume {}'.format(name)\n    ret['result'] = True\n    return ret",
    "docstring": "Makes sure that a btrfs subvolume is removed.\n\n    name\n        Name of the subvolume to remove\n\n    device\n        Device where to remove the subvolume\n\n    commit\n        Wait until the transaction is over"
  },
  {
    "code": "def dRV(self, dt, band='g'):\n        return (self.orbpop.dRV_1(dt)*self.A_brighter(band) +\n                self.orbpop.dRV_2(dt)*self.BC_brighter(band))",
    "docstring": "Returns dRV of star A, if A is brighter than B+C, or of star B if B+C is brighter"
  },
  {
    "code": "def convertforinput(self,filepath, metadata):\n        assert isinstance(metadata, CLAMMetaData)\n        if not metadata.__class__ in self.acceptforinput:\n            raise Exception(\"Convertor \" + self.__class__.__name__ + \" can not convert input files to \" + metadata.__class__.__name__ + \"!\")\n        return False",
    "docstring": "Convert from target format into one of the source formats. Relevant if converters are used in InputTemplates. Metadata already is metadata for the to-be-generated file. 'filepath' is both the source and the target file, the source file will be erased and overwritten with the conversion result!"
  },
  {
    "code": "def _set_current(self, new_current):\n        new_cur_full_path = self.join(new_current)\n        if not os.path.exists(new_cur_full_path):\n            raise PrefixNotFound(\n                'Prefix \"%s\" does not exist in workdir %s' %\n                (new_current, self.path)\n            )\n        if os.path.lexists(self.join('current')):\n            os.unlink(self.join('current'))\n        os.symlink(new_current, self.join('current'))\n        self.current = new_current",
    "docstring": "Change the current default prefix, for internal usage\n\n        Args:\n            new_current(str): Name of the new current prefix, it must already\n                exist\n\n        Returns:\n            None\n\n        Raises:\n            PrefixNotFound: if the given prefix name does not exist in the\n                workdir"
  },
  {
    "code": "def _call(self, x, out=None):\n        if out is None:\n            out = self.range.element()\n        out.lincomb(self.a, x[0], self.b, x[1])\n        return out",
    "docstring": "Linearly combine ``x`` and write to ``out`` if given."
  },
  {
    "code": "def _call(self, path, method, body=None, headers=None):\n        try:\n            resp = self.http.do_call(path, method, body, headers)\n        except http.HTTPError as err:\n            if err.status == 401:\n                raise PermissionError('Insufficient permissions to query ' +\n                    '%s with user %s :%s' % (path, self.user, err))\n            raise\n        return resp",
    "docstring": "Wrapper around http.do_call that transforms some HTTPError into\n        our own exceptions"
  },
  {
    "code": "def convert_instancenorm(node, **kwargs):\n    name, input_nodes, attrs = get_inputs(node, kwargs)\n    eps = float(attrs.get(\"eps\", 0.001))\n    node = onnx.helper.make_node(\n        'InstanceNormalization',\n        inputs=input_nodes,\n        outputs=[name],\n        name=name,\n        epsilon=eps)\n    return [node]",
    "docstring": "Map MXNet's InstanceNorm operator attributes to onnx's InstanceNormalization operator\n    based on the input node's attributes and return the created node."
  },
  {
    "code": "def cmd_devid(self, args):\n        for p in self.mav_param.keys():\n            if p.startswith('COMPASS_DEV_ID'):\n                mp_util.decode_devid(self.mav_param[p], p)\n            if p.startswith('INS_') and p.endswith('_ID'):\n                mp_util.decode_devid(self.mav_param[p], p)",
    "docstring": "decode device IDs from parameters"
  },
  {
    "code": "def getInfo(sign, lon):\n    return {\n        'ruler': ruler(sign),\n        'exalt': exalt(sign),\n        'dayTrip': dayTrip(sign),\n        'nightTrip': nightTrip(sign),\n        'partTrip': partTrip(sign),\n        'term': term(sign, lon),\n        'face': face(sign, lon),\n        'exile': exile(sign),\n        'fall': fall(sign)\n    }",
    "docstring": "Returns the complete essential dignities\n    for a sign and longitude."
  },
  {
    "code": "def get_attr_filters(self):\n        for f in self.data.keys():\n            if f not in self.multi_attrs:\n                continue\n            fv = self.data[f]\n            if isinstance(fv, dict):\n                fv['key'] = f\n            else:\n                fv = {f: fv}\n            vf = ValueFilter(fv)\n            vf.annotate = False\n            yield vf",
    "docstring": "Return an iterator resource attribute filters configured."
  },
  {
    "code": "def get_link_text_from_selector(selector):\n    if selector.startswith('link='):\n        return selector.split('link=')[1]\n    elif selector.startswith('link_text='):\n        return selector.split('link_text=')[1]\n    return selector",
    "docstring": "A basic method to get the link text from a link text selector."
  },
  {
    "code": "def strip_html(text):\n    def reply_to(text):\n        replying_to = []\n        split_text = text.split()\n        for index, token in enumerate(split_text):\n            if token.startswith('@'): replying_to.append(token[1:])\n            else:\n                message = split_text[index:]\n                break\n        rply_msg = \"\"\n        if len(replying_to) > 0:\n            rply_msg = \"Replying to \"\n            for token in replying_to[:-1]: rply_msg += token+\",\"                \n            if len(replying_to)>1: rply_msg += 'and '\n            rply_msg += replying_to[-1]+\". \"\n        return rply_msg + \" \".join(message)\n    text = reply_to(text)      \n    text = text.replace('@', ' ')\n    return \" \".join([token for token in text.split() \n                     if  ('http:' not in token) and ('https:' not in token)])",
    "docstring": "Get rid of ugly twitter html"
  },
  {
    "code": "def select_slice(self, row_slc, col_slc, add_to_selected=False):\n        if not add_to_selected:\n            self.grid.ClearSelection()\n        if row_slc == row_slc == slice(None, None, None):\n            self.grid.SelectAll()\n        elif row_slc.stop is None and col_slc.stop is None:\n            self.grid.SelectBlock(row_slc.start, col_slc.start,\n                                  row_slc.stop - 1, col_slc.stop - 1)\n        else:\n            for row in xrange(row_slc.start, row_slc.stop, row_slc.step):\n                for col in xrange(col_slc.start, col_slc.stop, col_slc.step):\n                    self.select_cell(row, col, add_to_selected=True)",
    "docstring": "Selects a slice of cells\n\n        Parameters\n        ----------\n         * row_slc: Integer or Slice\n        \\tRows to be selected\n         * col_slc: Integer or Slice\n        \\tColumns to be selected\n         * add_to_selected: Bool, defaults to False\n        \\tOld selections are cleared if False"
  },
  {
    "code": "def fact(name, puppet=False):\n    opt_puppet = '--puppet' if puppet else ''\n    ret = __salt__['cmd.run_all'](\n            'facter {0} {1}'.format(opt_puppet, name),\n            python_shell=False)\n    if ret['retcode'] != 0:\n        raise CommandExecutionError(ret['stderr'])\n    if not ret['stdout']:\n        return ''\n    return ret['stdout']",
    "docstring": "Run facter for a specific fact\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' puppet.fact kernel"
  },
  {
    "code": "def addIDs(self, asfield=False):\n        ids = vtk.vtkIdFilter()\n        ids.SetInputData(self.poly)\n        ids.PointIdsOn()\n        ids.CellIdsOn()\n        if asfield:\n            ids.FieldDataOn()\n        else:\n            ids.FieldDataOff()\n        ids.Update()\n        return self.updateMesh(ids.GetOutput())",
    "docstring": "Generate point and cell ids.\n\n        :param bool asfield: flag to control whether to generate scalar or field data."
  },
  {
    "code": "def _dump_multilinestring(obj, decimals):\n    coords = obj['coordinates']\n    mlls = 'MULTILINESTRING (%s)'\n    linestrs = ('(%s)' % ', '.join(' '.join(_round_and_pad(c, decimals)\n                for c in pt) for pt in linestr) for linestr in coords)\n    mlls %= ', '.join(ls for ls in linestrs)\n    return mlls",
    "docstring": "Dump a GeoJSON-like MultiLineString object to WKT.\n\n    Input parameters and return value are the MULTILINESTRING equivalent to\n    :func:`_dump_point`."
  },
  {
    "code": "def _update(self):\n        self.dataChanged.emit(self.createIndex(0, 0), self.createIndex(\n            len(self.collection), len(self.header)))",
    "docstring": "Emit dataChanged signal on all cells"
  },
  {
    "code": "def open(self, new=False):\n        self._db.new() if new else self._db.open()\n        self._run_init_queries()",
    "docstring": "Init the database, if required."
  },
  {
    "code": "def interrupt(self):\r\n        if self._database and self._databaseThreadId:\r\n            try:\r\n                self._database.interrupt(self._databaseThreadId)\r\n            except AttributeError:\r\n                pass\r\n        self._database = None\r\n        self._databaseThreadId = 0",
    "docstring": "Interrupts the current database from processing."
  },
  {
    "code": "def _get_parsers(self, name):\n        parserlist = BaseParser.__subclasses__()\n        forced = name is None\n        if isinstance(name, (six.text_type, six.binary_type)):\n            parserlist = [p for p in parserlist if p.__name__ == name]\n            if not parserlist:\n                raise ValueError(\"could not find parser: {}\".format(name))\n        elif name is not None:\n            raise TypeError(\"parser must be {types} or None, not {actual}\".format(\n                types=\" or \".join([six.text_type.__name__, six.binary_type.__name__]),\n                actual=type(parser).__name__,\n            ))\n        return not forced, parserlist",
    "docstring": "Return the appropriate parser asked by the user.\n\n        Todo:\n            Change `Ontology._get_parsers` behaviour to look for parsers\n            through a setuptools entrypoint instead of mere subclasses."
  },
  {
    "code": "def onPollCreated(\n        self,\n        mid=None,\n        poll=None,\n        author_id=None,\n        thread_id=None,\n        thread_type=None,\n        ts=None,\n        metadata=None,\n        msg=None,\n    ):\n        log.info(\n            \"{} created poll {} in {} ({})\".format(\n                author_id, poll, thread_id, thread_type.name\n            )\n        )",
    "docstring": "Called when the client is listening, and somebody creates a group poll\n\n        :param mid: The action ID\n        :param poll: Created poll\n        :param author_id: The ID of the person who created the poll\n        :param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`\n        :param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`\n        :param ts: A timestamp of the action\n        :param metadata: Extra metadata about the action\n        :param msg: A full set of the data recieved\n        :type poll: models.Poll\n        :type thread_type: models.ThreadType"
  },
  {
    "code": "def get_trainer(name):\n    name = name.lower()\n    return int(hashlib.md5(name.encode('utf-8')).hexdigest(), 16) % 10**8",
    "docstring": "return the unique id for a trainer, determined by the md5 sum"
  },
  {
    "code": "def state_view_for_block(block_wrapper, state_view_factory):\n        state_root_hash = \\\n            block_wrapper.state_root_hash \\\n            if block_wrapper is not None else None\n        return state_view_factory.create_view(state_root_hash)",
    "docstring": "Returns the state view for an arbitrary block.\n\n        Args:\n            block_wrapper (BlockWrapper): The block for which a state\n                view is to be returned\n            state_view_factory (StateViewFactory): The state view factory\n                used to create the StateView object\n\n        Returns:\n            StateView object associated with the block"
  },
  {
    "code": "def sort(expr, field = None, keytype=None, ascending=True):\n    weld_obj = WeldObject(encoder_, decoder_)\n    expr_var = weld_obj.update(expr)\n    if isinstance(expr, WeldObject):\n        expr_var = expr.obj_id\n        weld_obj.dependencies[expr_var] = expr\n    if field is not None:\n        key_str = \"x.$%s\" % field\n    else:\n        key_str = \"x\"\n    if not ascending:\n        key_str = key_str + \"* %s(-1)\" % keytype\n    weld_template =\n    weld_obj.weld_code = weld_template % {\"expr\":expr_var, \"key\":key_str}\n    return weld_obj",
    "docstring": "Sorts the vector.\n    If the field parameter is provided then the sort\n    operators on a vector of structs where the sort key\n    is the field of the struct.\n\n    Args:\n      expr (WeldObject)\n      field (Int)"
  },
  {
    "code": "def _match_item(item, any_all=any, ignore_case=False, normalize_values=False, **kwargs):\n\tit = get_item_tags(item)\n\treturn any_all(\n\t\t_match_field(\n\t\t\tget_field(it, field), pattern, ignore_case=ignore_case, normalize_values=normalize_values\n\t\t) for field, patterns in kwargs.items() for pattern in patterns\n\t)",
    "docstring": "Match items by metadata.\n\n\tNote:\n\t\tMetadata values are lowercased when ``normalized_values`` is ``True``,\n\t\tso ``ignore_case`` is automatically set to ``True``.\n\n\tParameters:\n\t\titem (~collections.abc.Mapping, str, os.PathLike): Item dict or filepath.\n\t\tany_all (callable): A callable to determine if any or all filters must match to match item.\n\t\t\tExpected values :obj:`any` (default) or :obj:`all`.\n\t\tignore_case (bool): Perform case-insensitive matching.\n\t\t\tDefault: ``False``\n\t\tnormalize_values (bool): Normalize metadata values to remove common differences between sources.\n\t\t\tDefault: ``False``\n\t\tkwargs (list): Lists of values to match the given metadata field.\n\n\tReturns:\n\t\tbool: True if matched, False if not."
  },
  {
    "code": "def to_json(self):\n        obj = {\n            \"vertices\": [\n                {\n                    \"id\": vertex.id,\n                    \"annotation\": vertex.annotation,\n                }\n                for vertex in self.vertices\n            ],\n            \"edges\": [\n                {\n                    \"id\": edge.id,\n                    \"annotation\": edge.annotation,\n                    \"head\": edge.head,\n                    \"tail\": edge.tail,\n                }\n                for edge in self._edges\n            ],\n        }\n        return six.text_type(json.dumps(obj, ensure_ascii=False))",
    "docstring": "Convert to a JSON string."
  },
  {
    "code": "def to_wea(self, file_path, hoys=None):\n        hoys = hoys or xrange(len(self.direct_normal_radiation.datetimes))\n        if not file_path.lower().endswith('.wea'):\n            file_path += '.wea'\n        originally_ip = False\n        if self.is_ip is True:\n            self.convert_to_si()\n            originally_ip = True\n        lines = [self._get_wea_header()]\n        datetimes = self.direct_normal_radiation.datetimes\n        for hoy in hoys:\n            dir_rad = self.direct_normal_radiation[hoy]\n            dif_rad = self.diffuse_horizontal_radiation[hoy]\n            line = \"%d %d %.3f %d %d\\n\" \\\n                % (datetimes[hoy].month,\n                   datetimes[hoy].day,\n                   datetimes[hoy].hour + 0.5,\n                   dir_rad, dif_rad)\n            lines.append(line)\n        file_data = ''.join(lines)\n        write_to_file(file_path, file_data, True)\n        if originally_ip is True:\n            self.convert_to_ip()\n        return file_path",
    "docstring": "Write an wea file from the epw file.\n\n        WEA carries radiation values from epw. Gendaymtx uses these values to\n        generate the sky. For an annual analysis it is identical to using epw2wea.\n\n        args:\n            file_path: Full file path for output file.\n            hoys: List of hours of the year. Default is 0-8759."
  },
  {
    "code": "def get_owner(obj_name, obj_type='file'):\n    r\n    try:\n        obj_type_flag = flags().obj_type[obj_type.lower()]\n    except KeyError:\n        raise SaltInvocationError(\n            'Invalid \"obj_type\" passed: {0}'.format(obj_type))\n    if obj_type in ['registry', 'registry32']:\n        obj_name = dacl().get_reg_name(obj_name)\n    try:\n        security_descriptor = win32security.GetNamedSecurityInfo(\n            obj_name, obj_type_flag, win32security.OWNER_SECURITY_INFORMATION)\n        owner_sid = security_descriptor.GetSecurityDescriptorOwner()\n    except MemoryError:\n        owner_sid = 'S-1-0-0'\n    except pywintypes.error as exc:\n        if exc.winerror == 1 or exc.winerror == 50:\n            owner_sid = 'S-1-0-0'\n        else:\n            log.exception('Failed to get the owner: %s', obj_name)\n            raise CommandExecutionError(\n                'Failed to get owner: {0}'.format(obj_name), exc.strerror)\n    return get_name(owner_sid)",
    "docstring": "r'''\n    Gets the owner of the passed object\n\n    Args:\n\n        obj_name (str):\n            The path for which to obtain owner information. The format of this\n            parameter is different depending on the ``obj_type``\n\n        obj_type (str):\n            The type of object to query. This value changes the format of the\n            ``obj_name`` parameter as follows:\n\n            - file: indicates a file or directory\n                - a relative path, such as ``FileName.txt`` or ``..\\FileName``\n                - an absolute path, such as ``C:\\DirName\\FileName.txt``\n                - A UNC name, such as ``\\\\ServerName\\ShareName\\FileName.txt``\n            - service: indicates the name of a Windows service\n            - printer: indicates the name of a printer\n            - registry: indicates a registry key\n                - Uses the following literal strings to denote the hive:\n                    - HKEY_LOCAL_MACHINE\n                    - MACHINE\n                    - HKLM\n                    - HKEY_USERS\n                    - USERS\n                    - HKU\n                    - HKEY_CURRENT_USER\n                    - CURRENT_USER\n                    - HKCU\n                    - HKEY_CLASSES_ROOT\n                    - CLASSES_ROOT\n                    - HKCR\n                - Should be in the format of ``HIVE\\Path\\To\\Key``. For example,\n                    ``HKLM\\SOFTWARE\\Windows``\n            - registry32: indicates a registry key under WOW64. Formatting is\n                the same as it is for ``registry``\n            - share: indicates a network share\n\n    Returns:\n        str: The owner (group or user)\n\n    Usage:\n\n    .. code-block:: python\n\n        salt.utils.win_dacl.get_owner('c:\\\\file')"
  },
  {
    "code": "def install_package(package,\n                    wheels_path,\n                    venv=None,\n                    requirement_files=None,\n                    upgrade=False,\n                    install_args=None):\n    requirement_files = requirement_files or []\n    logger.info('Installing %s...', package)\n    if venv and not os.path.isdir(venv):\n        raise WagonError('virtualenv {0} does not exist'.format(venv))\n    pip_command = _construct_pip_command(\n        package,\n        wheels_path,\n        venv,\n        requirement_files,\n        upgrade,\n        install_args)\n    if IS_VIRTUALENV and not venv:\n        logger.info('Installing within current virtualenv')\n    result = _run(pip_command)\n    if not result.returncode == 0:\n        raise WagonError('Could not install package: {0} ({1})'.format(\n            package, result.aggr_stderr))",
    "docstring": "Install a Python package.\n\n    Can specify a specific version.\n    Can specify a prerelease.\n    Can specify a venv to install in.\n    Can specify a list of paths or urls to requirement txt files.\n    Can specify a local wheels_path to use for offline installation.\n    Can request an upgrade."
  },
  {
    "code": "def remove_if_exists(filename):\n    try:\n        os.unlink(filename)\n    except OSError as ex:\n        if ex.errno != errno.ENOENT:\n            raise",
    "docstring": "Remove file.\n\n    This is like :func:`os.remove` (or :func:`os.unlink`), except that no\n    error is raised if the file does not exist."
  },
  {
    "code": "def get_project_groups_roles(request, project):\n    groups_roles = collections.defaultdict(list)\n    project_role_assignments = role_assignments_list(request,\n                                                     project=project)\n    for role_assignment in project_role_assignments:\n        if not hasattr(role_assignment, 'group'):\n            continue\n        group_id = role_assignment.group['id']\n        role_id = role_assignment.role['id']\n        if ('project' in role_assignment.scope and\n                role_assignment.scope['project']['id'] == project):\n            groups_roles[group_id].append(role_id)\n    return groups_roles",
    "docstring": "Gets the groups roles in a given project.\n\n    :param request: the request entity containing the login user information\n    :param project: the project to filter the groups roles. It accepts both\n                    project object resource or project ID\n\n    :returns group_roles: a dictionary mapping the groups and their roles in\n                          given project"
  },
  {
    "code": "def _ScanFileSystemForWindowsDirectory(self, path_resolver):\n    result = False\n    for windows_path in self._WINDOWS_DIRECTORIES:\n      windows_path_spec = path_resolver.ResolvePath(windows_path)\n      result = windows_path_spec is not None\n      if result:\n        self._windows_directory = windows_path\n        break\n    return result",
    "docstring": "Scans a file system for a known Windows directory.\n\n    Args:\n      path_resolver (WindowsPathResolver): Windows path resolver.\n\n    Returns:\n      bool: True if a known Windows directory was found."
  },
  {
    "code": "def get_trust_id(self):\n        if not bool(self._my_map['trustId']):\n            raise errors.IllegalState('this Authorization has no trust')\n        else:\n            return Id(self._my_map['trustId'])",
    "docstring": "Gets the ``Trust``  ``Id`` for this authorization.\n\n        return: (osid.id.Id) - the trust ``Id``\n        raise:  IllegalState - ``has_trust()`` is ``false``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_postgresql_args(db_config, extra_args=None):\n    db = db_config['NAME']\n    mapping = [('--username={0}', db_config.get('USER')),\n               ('--host={0}', db_config.get('HOST')),\n               ('--port={0}', db_config.get('PORT'))]\n    args = apply_arg_values(mapping)\n    if extra_args is not None:\n        args.extend(shlex.split(extra_args))\n    args.append(db)\n    return args",
    "docstring": "Returns an array of argument values that will be passed to a `psql` or\n    `pg_dump` process when it is started based on the given database\n    configuration."
  },
  {
    "code": "def setControl(\n            self, request_type, request, value, index, buffer_or_len,\n            callback=None, user_data=None, timeout=0):\n        if self.__submitted:\n            raise ValueError('Cannot alter a submitted transfer')\n        if self.__doomed:\n            raise DoomedTransferError('Cannot reuse a doomed transfer')\n        if isinstance(buffer_or_len, (int, long)):\n            length = buffer_or_len\n            string_buffer, transfer_py_buffer = create_binary_buffer(\n                length + CONTROL_SETUP_SIZE,\n            )\n        else:\n            length = len(buffer_or_len)\n            string_buffer, transfer_py_buffer = create_binary_buffer(\n                CONTROL_SETUP + buffer_or_len,\n            )\n        self.__initialized = False\n        self.__transfer_buffer = string_buffer\n        self.__transfer_py_buffer = integer_memoryview(\n            transfer_py_buffer,\n        )[CONTROL_SETUP_SIZE:]\n        self.__user_data = user_data\n        libusb1.libusb_fill_control_setup(\n            string_buffer, request_type, request, value, index, length)\n        libusb1.libusb_fill_control_transfer(\n            self.__transfer, self.__handle, string_buffer,\n            self.__ctypesCallbackWrapper, None, timeout)\n        self.__callback = callback\n        self.__initialized = True",
    "docstring": "Setup transfer for control use.\n\n        request_type, request, value, index\n            See USBDeviceHandle.controlWrite.\n            request_type defines transfer direction (see\n            ENDPOINT_OUT and ENDPOINT_IN)).\n        buffer_or_len\n            Either a string (when sending data), or expected data length (when\n            receiving data).\n        callback\n            Callback function to be invoked on transfer completion.\n            Called with transfer as parameter, return value ignored.\n        user_data\n            User data to pass to callback function.\n        timeout\n            Transfer timeout in milliseconds. 0 to disable."
  },
  {
    "code": "def _send_solr_command(self, core_url, json_command):\n        url = _get_url(core_url, \"update\")\n        try:\n            response = self.req_session.post(url, data=json_command, headers={'Content-Type': 'application/json'})\n            response.raise_for_status()\n        except requests.RequestException as e:\n            logger.error(\"Failed to send update to Solr endpoint [%s]: %s\", core_url, e, exc_info=True)\n            raise SolrException(\"Failed to send command to Solr [%s]: %s\" % (core_url, e,))\n        return True",
    "docstring": "Sends JSON string to Solr instance"
  },
  {
    "code": "def arch(self):\n    if self.machine in [\"x86_64\", \"AMD64\", \"i686\"]:\n      if self.architecture == \"32bit\":\n        return \"i386\"\n      return \"amd64\"\n    elif self.machine == \"x86\":\n      return \"i386\"\n    return self.machine",
    "docstring": "Return a more standard representation of the architecture."
  },
  {
    "code": "def to_array(self, *args, **kwargs):\n        from root_numpy import tree2array\n        return tree2array(self, *args, **kwargs)",
    "docstring": "Convert this tree into a NumPy structured array"
  },
  {
    "code": "def post(self, command, data=None):\n        now = calendar.timegm(datetime.datetime.now().timetuple())\n        if now > self.expiration:\n            auth = self.__open(\"/oauth/token\", data=self.oauth)\n            self.__sethead(auth['access_token'])\n        return self.__open(\"%s%s\" % (self.api, command),\n                           headers=self.head, data=data)",
    "docstring": "Post data to API."
  },
  {
    "code": "def analyze(problem, X, Y, second_order=False, print_to_console=False,\n            seed=None):\n    if seed:\n        np.random.seed(seed)\n    problem = extend_bounds(problem)\n    num_vars = problem['num_vars']\n    X = generate_contrast(problem)\n    main_effect = (1. / (2 * num_vars)) * np.dot(Y, X)\n    Si = ResultDict((k, [None] * num_vars)\n                    for k in ['names', 'ME'])\n    Si['ME'] = main_effect\n    Si['names'] = problem['names']\n    if print_to_console:\n        print(\"Parameter ME\")\n        for j in range(num_vars):\n            print(\"%s %f\" % (problem['names'][j], Si['ME'][j]))\n    if second_order:\n        interaction_names, interaction_effects = interactions(problem,\n                                                              Y,\n                                                              print_to_console)\n        Si['interaction_names'] = interaction_names\n        Si['IE'] = interaction_effects\n    Si.to_df = MethodType(to_df, Si)\n    return Si",
    "docstring": "Perform a fractional factorial analysis\n\n    Returns a dictionary with keys 'ME' (main effect) and 'IE' (interaction\n    effect). The techniques bulks out the number of parameters with dummy\n    parameters to the nearest 2**n.  Any results involving dummy parameters\n    could indicate a problem with the model runs.\n\n    Arguments\n    ---------\n    problem: dict\n        The problem definition\n    X: numpy.matrix\n        The NumPy matrix containing the model inputs\n    Y: numpy.array\n        The NumPy array containing the model outputs\n    second_order: bool, default=False\n        Include interaction effects\n    print_to_console: bool, default=False\n        Print results directly to console\n\n    Returns\n    -------\n    Si: dict\n        A dictionary of sensitivity indices, including main effects ``ME``,\n        and interaction effects ``IE`` (if ``second_order`` is True)\n\n    Examples\n    --------\n    >>> X = sample(problem)\n    >>> Y = X[:, 0] + (0.1 * X[:, 1]) + ((1.2 * X[:, 2]) * (0.2 + X[:, 0]))\n    >>> analyze(problem, X, Y, second_order=True, print_to_console=True)"
  },
  {
    "code": "def _buffer(self, event: Message):\n        if isinstance(event, BytesMessage):\n            self._byte_buffer.write(event.data)\n        elif isinstance(event, TextMessage):\n            self._string_buffer.write(event.data)",
    "docstring": "Buffers an event, if applicable."
  },
  {
    "code": "def included_length(self):\n        return sum([shot.length for shot in self.shots if shot.is_included])",
    "docstring": "Surveyed length, not including \"excluded\" shots"
  },
  {
    "code": "def _maybe_cast_slice_bound(self, label, side, kind):\n        if isinstance(label, str):\n            parsed, resolution = _parse_iso8601_with_reso(self.date_type,\n                                                          label)\n            start, end = _parsed_string_to_bounds(self.date_type, resolution,\n                                                  parsed)\n            if self.is_monotonic_decreasing and len(self) > 1:\n                return end if side == 'left' else start\n            return start if side == 'left' else end\n        else:\n            return label",
    "docstring": "Adapted from\n        pandas.tseries.index.DatetimeIndex._maybe_cast_slice_bound"
  },
  {
    "code": "def class_parameters(decorator):\n    def decorate(the_class):\n        if not isclass(the_class):\n            raise TypeError(\n                'class_parameters(the_class=%s) you must pass a class' % (\n                    the_class\n                )\n            )\n        for attr in the_class.__dict__:\n            if callable(\n                getattr(\n                    the_class, attr)):\n                setattr(\n                    the_class, \n                    attr, \n                    decorator(\n                        getattr(the_class, attr)))\n        return the_class\n    return decorate",
    "docstring": "To wrap all class methods with static_parameters decorator"
  },
  {
    "code": "def calc_exp(skydir, ltc, event_class, event_types,\n             egy, cth_bins, npts=None):\n    if npts is None:\n        npts = int(np.ceil(np.max(cth_bins[1:] - cth_bins[:-1]) / 0.025))\n    exp = np.zeros((len(egy), len(cth_bins) - 1))\n    cth_bins = utils.split_bin_edges(cth_bins, npts)\n    cth = edge_to_center(cth_bins)\n    ltw = ltc.get_skydir_lthist(skydir, cth_bins).reshape(-1, npts)\n    for et in event_types:\n        aeff = create_aeff(event_class, et, egy, cth)\n        aeff = aeff.reshape(exp.shape + (npts,))\n        exp += np.sum(aeff * ltw[np.newaxis, :, :], axis=-1)\n    return exp",
    "docstring": "Calculate the exposure on a 2D grid of energy and incidence angle.\n\n    Parameters\n    ----------\n    npts : int    \n        Number of points by which to sample the response in each\n        incidence angle bin.  If None then npts will be automatically\n        set such that incidence angle is sampled on intervals of <\n        0.05 in Cos(Theta).\n\n    Returns\n    -------\n    exp : `~numpy.ndarray`\n        2D Array of exposures vs. energy and incidence angle."
  },
  {
    "code": "def _is_in_restart(self, x, y):\n        x1, y1, x2, y2 = self._new_game\n        return x1 <= x < x2 and y1 <= y < y2",
    "docstring": "Checks if the game is to be restarted by request."
  },
  {
    "code": "def commit(self, f):\n        if self._overwrite:\n            replace_atomic(f.name, self._path)\n        else:\n            move_atomic(f.name, self._path)",
    "docstring": "Move the temporary file to the target location."
  },
  {
    "code": "def get_thermostability(self, at_temp):\n        import ssbio.protein.sequence.properties.thermostability as ts\n        dG = ts.get_dG_at_T(seq=self, temp=at_temp)\n        self.annotations['thermostability_{}_C-{}'.format(at_temp, dG[2].lower())] = (dG[0], dG[1])",
    "docstring": "Run the thermostability calculator using either the Dill or Oobatake methods.\n\n        Stores calculated (dG, Keq) tuple in the ``annotations`` attribute, under the key\n        `thermostability_<TEMP>-<METHOD_USED>`.\n\n        See :func:`ssbio.protein.sequence.properties.thermostability.get_dG_at_T` for instructions and details."
  },
  {
    "code": "def deploy_snmp(snmp, host=None, admin_username=None,\n                admin_password=None, module=None):\n    return __execute_cmd('deploy -v SNMPv2 {0} ro'.format(snmp),\n                         host=host,\n                         admin_username=admin_username,\n                         admin_password=admin_password,\n                         module=module)",
    "docstring": "Change the QuickDeploy SNMP community string, used for switches as well\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt dell dracr.deploy_snmp SNMP_STRING\n            host=<remote DRAC or CMC> admin_username=<DRAC user>\n            admin_password=<DRAC PW>\n        salt dell dracr.deploy_password diana secret"
  },
  {
    "code": "def loadJson(d):\n    with codecs.open(jsonFn(d), 'r', 'utf-8') as f:\n        return json.load(f)",
    "docstring": "Return JSON data."
  },
  {
    "code": "def extract_keywords(cls, line, items):\n        unprocessed = list(reversed(line.split('=')))\n        while unprocessed:\n            chunk = unprocessed.pop()\n            key = None\n            if chunk.strip() in cls.allowed:\n                key = chunk.strip()\n            else:\n                raise SyntaxError(\"Invalid keyword: %s\" % chunk.strip())\n            value = unprocessed.pop().strip()\n            if len(unprocessed) != 0:\n                for option in cls.allowed:\n                    if value.endswith(option):\n                        value = value[:-len(option)].strip()\n                        unprocessed.append(option)\n                        break\n                else:\n                    raise SyntaxError(\"Invalid keyword: %s\" % value.split()[-1])\n            keyword = '%s=%s' % (key, value)\n            try:\n                items.update(eval('dict(%s)' % keyword))\n            except:\n                raise SyntaxError(\"Could not evaluate keyword: %s\" % keyword)\n        return items",
    "docstring": "Given the keyword string, parse a dictionary of options."
  },
  {
    "code": "def _send_and_wait(self, **kwargs):\n        frame_id = self.next_frame_id\n        kwargs.update(dict(frame_id=frame_id))\n        self._send(**kwargs)\n        timeout = datetime.now() + const.RX_TIMEOUT\n        while datetime.now() < timeout:\n            try:\n                frame = self._rx_frames.pop(frame_id)\n                raise_if_error(frame)\n                return frame\n            except KeyError:\n                sleep(0.1)\n                continue\n        _LOGGER.exception(\n            \"Did not receive response within configured timeout period.\")\n        raise exceptions.ZigBeeResponseTimeout()",
    "docstring": "Send a frame to either the local ZigBee or a remote device and wait\n        for a pre-defined amount of time for its response."
  },
  {
    "code": "def get(self, url, ignore_access_time=False):\n        key = hashlib.md5(url).hexdigest()\n        accessed = self._cache_meta_get(key)\n        if not accessed:\n            self.debug(\"From inet {}\".format(url))\n            return None, None\n        if isinstance(accessed, dict):\n            cached = CacheInfo.from_dict(accessed)\n        else:\n            cached = CacheInfo(accessed)\n        now = now_utc()\n        if now - cached.access_time > self.duration and not ignore_access_time:\n            self.debug(\"From inet (expired) {}\".format(url))\n            return None, cached\n        try:\n            res = self._cache_get(key)\n        except:\n            self.exception(\"Failed to read cache\")\n            self.debug(\"From inet (failure) {}\".format(url))\n            return None, None\n        self.debug(\"From cache {}\".format(url))\n        return res, cached",
    "docstring": "Try to retrieve url from cache if available\n\n        :param url: Url to retrieve\n        :type url: str | unicode\n        :param ignore_access_time: Should ignore the access time\n        :type ignore_access_time: bool\n        :return: (data, CacheInfo)\n            None, None -> not found in cache\n            None, CacheInfo -> found, but is expired\n            data, CacheInfo -> found in cache\n        :rtype: (None | str | unicode, None | floscraper.models.CacheInfo)"
  },
  {
    "code": "def django_url(step, url=None):\n    base_url = step.test.live_server_url\n    if url:\n        return urljoin(base_url, url)\n    else:\n        return base_url",
    "docstring": "The URL for a page from the test server.\n\n    :param step: A Gherkin step\n    :param url: If specified, the relative URL to append."
  },
  {
    "code": "def read_be_array(fmt, count, fp):\n    arr = array.array(str(fmt))\n    if hasattr(arr, 'frombytes'):\n        arr.frombytes(fp.read(count * arr.itemsize))\n    else:\n        arr.fromstring(fp.read(count * arr.itemsize))\n    return fix_byteorder(arr)",
    "docstring": "Reads an array from a file with big-endian data."
  },
  {
    "code": "def _is_viable_phone_number(number):\n    if len(number) < _MIN_LENGTH_FOR_NSN:\n        return False\n    match = fullmatch(_VALID_PHONE_NUMBER_PATTERN, number)\n    return bool(match)",
    "docstring": "Checks to see if a string could possibly be a phone number.\n\n    At the moment, checks to see that the string begins with at least 2\n    digits, ignoring any punctuation commonly found in phone numbers.  This\n    method does not require the number to be normalized in advance - but does\n    assume that leading non-number symbols have been removed, such as by the\n    method _extract_possible_number.\n\n    Arguments:\n    number -- string to be checked for viability as a phone number\n\n    Returns True if the number could be a phone number of some sort, otherwise\n    False"
  },
  {
    "code": "def attached_socket(self, *args, **kwargs):\n        try:\n            sock = self.attach(*args, **kwargs)\n            yield sock\n        finally:\n            sock.shutdown(socket.SHUT_RDWR)\n            sock.close()",
    "docstring": "Opens a raw socket in a ``with`` block to write data to Splunk.\n\n        The arguments are identical to those for :meth:`attach`. The socket is\n        automatically closed at the end of the ``with`` block, even if an\n        exception is raised in the block.\n\n        :param host: The host value for events written to the stream.\n        :type host: ``string``\n        :param source: The source value for events written to the stream.\n        :type source: ``string``\n        :param sourcetype: The sourcetype value for events written to the\n            stream.\n        :type sourcetype: ``string``\n\n        :returns: Nothing.\n\n        **Example**::\n\n            import splunklib.client as client\n            s = client.connect(...)\n            index = s.indexes['some_index']\n            with index.attached_socket(sourcetype='test') as sock:\n                sock.send('Test event\\\\r\\\\n')"
  },
  {
    "code": "def _get(self, *args, **kwargs):\n        all_messages = []\n        for storage in self.storages:\n            messages, all_retrieved = storage._get()\n            if messages is None:\n                break\n            if messages:\n                self._used_storages.add(storage)\n            all_messages.extend(messages)\n            if all_retrieved:\n                break\n        return all_messages, all_retrieved",
    "docstring": "Gets a single list of messages from all storage backends."
  },
  {
    "code": "def send(self, obj_id):\n        response = self._client.session.post(\n            '{url}/{id}/send'.format(\n                url=self.endpoint_url, id=obj_id\n            )\n        )\n        return self.process_response(response)",
    "docstring": "Send email to the assigned lists\n\n        :param obj_id: int\n        :return: dict|str"
  },
  {
    "code": "def fill_in_arguments(config, modules, args):\n    def work_in(config, module, name):\n        rkeys = getattr(module, 'runtime_keys', {})\n        for (attr, cname) in iteritems(rkeys):\n            v = args.get(attr, None)\n            if v is not None:\n                config[cname] = v\n    if not isinstance(args, collections.Mapping):\n        args = vars(args)\n    return _walk_config(config, modules, work_in)",
    "docstring": "Fill in configuration fields from command-line arguments.\n\n    `config` is a dictionary holding the initial configuration,\n    probably the result of :func:`assemble_default_config`.  It reads\n    through `modules`, and for each, fills in any configuration values\n    that are provided in `args`.\n\n    `config` is modified in place.  `args` may be either a dictionary\n    or an object (as the result of :mod:`argparse`).\n\n    :param dict config: configuration tree to update\n    :param modules: modules or Configurable instances to use\n    :type modules: iterable of :class:`~yakonfig.configurable.Configurable`\n    :param args: command-line objects\n    :paramtype args: dict or object\n    :return: config"
  },
  {
    "code": "def purge_bad_timestamp_files(file_list):\n        \"Given a list of image files, find bad frames, remove them and modify file_list\"\n        MAX_INITIAL_BAD_FRAMES = 15\n        bad_ts = Kinect.detect_bad_timestamps(Kinect.timestamps_from_file_list(file_list))\n        if not bad_ts:\n            return file_list\n        last_bad = max(bad_ts)\n        if last_bad >= MAX_INITIAL_BAD_FRAMES:\n            raise Exception('Only 15 initial bad frames are allowed, but last bad frame is %d' % last_bad)\n        for i in range(last_bad + 1):\n            os.remove(file_list[i])\n        file_list = file_list[last_bad+1:]\n        return file_list",
    "docstring": "Given a list of image files, find bad frames, remove them and modify file_list"
  },
  {
    "code": "def layer_from_element(element, style_function=None):\n    from telluric.collections import BaseCollection\n    if isinstance(element, BaseCollection):\n        styled_element = element.map(lambda feat: style_element(feat, style_function))\n    else:\n        styled_element = style_element(element, style_function)\n    return GeoJSON(data=mapping(styled_element), name='GeoJSON')",
    "docstring": "Return Leaflet layer from shape.\n\n    Parameters\n    ----------\n    element : telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection\n        Data to plot."
  },
  {
    "code": "def add_special(self, name):\n        self.undeclared.discard(name)\n        self.declared.add(name)",
    "docstring": "Register a special name like `loop`."
  },
  {
    "code": "def request_goto(self, tc=None):\n        if not tc:\n            tc = TextHelper(self.editor).word_under_cursor(\n                select_whole_word=True)\n        if not self._definition or isinstance(self.sender(), QAction):\n            self.select_word(tc)\n        if self._definition is not None:\n            QTimer.singleShot(100, self._goto_def)",
    "docstring": "Request a go to assignment.\n\n        :param tc: Text cursor which contains the text that we must look for\n                   its assignment. Can be None to go to the text that is under\n                   the text cursor.\n        :type tc: QtGui.QTextCursor"
  },
  {
    "code": "def _generate_encryption_data_dict(kek, cek, iv):\n    wrapped_cek = kek.wrap_key(cek)\n    wrapped_content_key = OrderedDict()\n    wrapped_content_key['KeyId'] = kek.get_kid()\n    wrapped_content_key['EncryptedKey'] = _encode_base64(wrapped_cek)\n    wrapped_content_key['Algorithm'] = kek.get_key_wrap_algorithm()\n    encryption_agent = OrderedDict()\n    encryption_agent['Protocol'] = _ENCRYPTION_PROTOCOL_V1\n    encryption_agent['EncryptionAlgorithm'] = _EncryptionAlgorithm.AES_CBC_256\n    encryption_data_dict = OrderedDict()\n    encryption_data_dict['WrappedContentKey'] = wrapped_content_key\n    encryption_data_dict['EncryptionAgent'] = encryption_agent\n    encryption_data_dict['ContentEncryptionIV'] = _encode_base64(iv)\n    encryption_data_dict['KeyWrappingMetadata'] = {'EncryptionLibrary': 'Python ' + __version__}\n    return encryption_data_dict",
    "docstring": "Generates and returns the encryption metadata as a dict.\n\n    :param object kek: The key encryption key. See calling functions for more information.\n    :param bytes cek: The content encryption key.\n    :param bytes iv: The initialization vector.\n    :return: A dict containing all the encryption metadata.\n    :rtype: dict"
  },
  {
    "code": "def commit(self):\n        self.logger.debug(\"Starting injections...\")\n        self.logger.debug(\"Injections dict is:\")\n        self.logger.debug(self.inject_dict)\n        self.logger.debug(\"Clear list is:\")\n        self.logger.debug(self.clear_set)\n        for filename, content in self.inject_dict.items():\n            content = _unicode(content)\n            self.logger.debug(\"Injecting values into %s...\" % filename)\n            self.destructive_inject(filename, content)\n        for filename in self.clear_set:\n            self.logger.debug(\"Clearing injection from %s...\" % filename)\n            self.destructive_clear(filename)",
    "docstring": "commit the injections desired, overwriting any previous injections in the file."
  },
  {
    "code": "def get_compute(self, compute=None, **kwargs):\n        if compute is not None:\n            kwargs['compute'] = compute\n        kwargs['context'] = 'compute'\n        return self.filter(**kwargs)",
    "docstring": "Filter in the 'compute' context\n\n        :parameter str compute: name of the compute options (optional)\n        :parameter **kwargs: any other tags to do the filter\n            (except compute or context)\n        :return: :class:`phoebe.parameters.parameters.ParameterSet`"
  },
  {
    "code": "def _create_axes(filenames, file_dict):\n    try:\n        f = iter(f for tup in file_dict.itervalues()\n            for f in tup if f is not None).next()\n    except StopIteration as e:\n        raise (ValueError(\"No FITS files were found. \"\n            \"Searched filenames: '{f}'.\" .format(\n                f=filenames.values())),\n                    None, sys.exc_info()[2])\n    axes = FitsAxes(f[0].header)\n    for i, u in enumerate(axes.cunit):\n        if u == 'DEG':\n            axes.cunit[i] = 'RAD'\n            axes.set_axis_scale(i, np.pi/180.0)\n    return axes",
    "docstring": "Create a FitsAxes object"
  },
  {
    "code": "def simulate(self, T):\n        x = []\n        for t in range(T):\n            law_x = self.PX0() if t == 0 else self.PX(t, x[-1])\n            x.append(law_x.rvs(size=1))\n        y = self.simulate_given_x(x)\n        return x, y",
    "docstring": "Simulate state and observation processes. \n\n        Parameters\n        ----------\n        T: int\n            processes are simulated from time 0 to time T-1\n\n        Returns\n        -------\n        x, y: lists\n            lists of length T"
  },
  {
    "code": "def similar(self, address_line, max_results=None):\n        params = {\"term\": address_line,\n                  \"max_results\": max_results or self.max_results}\n        return self._make_request('/address/getSimilar', params)",
    "docstring": "Gets a list of valid addresses that are similar to the given term, can\n        be used to match invalid addresses to valid addresses."
  },
  {
    "code": "def delete_record(self, identifier=None, rtype=None, name=None, content=None, **kwargs):\n        if not rtype and kwargs.get('type'):\n            warnings.warn('Parameter \"type\" is deprecated, use \"rtype\" instead.',\n                          DeprecationWarning)\n            rtype = kwargs.get('type')\n        return self._delete_record(identifier=identifier, rtype=rtype, name=name, content=content)",
    "docstring": "Delete an existing record.\n        If record does not exist, do nothing.\n        If an identifier is specified, use it, otherwise do a lookup using type, name and content."
  },
  {
    "code": "def listFieldsFromSource(self, template_source):\n        ast = self.environment.parse(template_source)\n        return jinja2.meta.find_undeclared_variables(ast)",
    "docstring": "List all the attributes to be rendered directly from template\n        source\n\n        :param template_source: the template source (usually represents the\n            template content in string format)\n        :return: a :class:`set` contains all the needed attributes\n        :rtype: set"
  },
  {
    "code": "def _mark_target(type, item):\n    if type not in ('input', 'output'):\n        msg = 'Error (7D74X): Type is not valid: {0}'.format(type)\n        raise ValueError(msg)\n    orig_item = item\n    if isinstance(item, list):\n        item_s = item\n    else:\n        item_s = [item]\n    for item in item_s:\n        if isinstance(item, str) and os.path.isabs(item):\n            msg = (\n                'Error (5VWOZ): Given path is not relative path: {0}.'\n            ).format(item)\n            raise ValueError(msg)\n    return _ItemWrapper(type=type, item=orig_item)",
    "docstring": "Wrap given item as input or output target that should be added to task.\n\n    Wrapper object will be handled specially in \\\n    :paramref:`create_cmd_task.parts`.\n\n    :param type: Target type.\n\n        Allowed values:\n            - 'input'\n            - 'output'\n\n    :param item: Item to mark as input or output target.\n\n        Allowed values:\n            - Relative path relative to top directory.\n            - Node object.\n            - List of these.\n\n    :return: Wrapper object."
  },
  {
    "code": "def _get_select_commands(self, source, tables):\n        row_queries = {tbl: self.select_all(tbl, execute=False) for tbl in\n                       tqdm(tables, total=len(tables), desc='Getting {0} select queries'.format(source))}\n        for tbl, command in row_queries.items():\n            if isinstance(command, str):\n                row_queries[tbl] = [command]\n        return [(tbl, cmd) for tbl, cmds in row_queries.items() for cmd in cmds]",
    "docstring": "Create select queries for all of the tables from a source database.\n\n        :param source: Source database name\n        :param tables: Iterable of table names\n        :return: Dictionary of table keys, command values"
  },
  {
    "code": "def lexical_parent(self):\n        if not hasattr(self, '_lexical_parent'):\n            self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self)\n        return self._lexical_parent",
    "docstring": "Return the lexical parent for this cursor."
  },
  {
    "code": "def user_has_access(self, user):\n        if ROLE_ADMIN in user.roles:\n            return True\n        if self.enabled:\n            if not self.required_roles:\n                return True\n            for role in self.required_roles:\n                if role in user.roles:\n                    return True\n        return False",
    "docstring": "Check if a user has access to view information for the account\n\n        Args:\n            user (:obj:`User`): User object to check\n\n        Returns:\n            True if user has access to the account, else false"
  },
  {
    "code": "def _linear_predictor(self, X=None, modelmat=None, b=None, term=-1):\n        if modelmat is None:\n            modelmat = self._modelmat(X, term=term)\n        if b is None:\n            b = self.coef_[self.terms.get_coef_indices(term)]\n        return modelmat.dot(b).flatten()",
    "docstring": "linear predictor\n        compute the linear predictor portion of the model\n        ie multiply the model matrix by the spline basis coefficients\n\n        Parameters\n        ---------\n        at least 1 of (X, modelmat)\n            and\n        at least 1 of (b, feature)\n\n        X : array-like of shape (n_samples, m_features) or None, optional\n            containing the input dataset\n            if None, will attempt to use modelmat\n\n        modelmat : array-like or None, optional\n            contains the spline basis for each feature evaluated at the input\n            values for each feature, ie model matrix\n            if None, will attempt to construct the model matrix from X\n\n        b : array-like or None, optional\n            contains the spline coefficients\n            if None, will use current model coefficients\n\n        feature : int, optional\n                  feature for which to compute the linear prediction\n                  if -1, will compute for all features\n\n        Returns\n        -------\n        lp : np.array of shape (n_samples,)"
  },
  {
    "code": "def set_file(name, source, template=None, context=None, defaults=None, **kwargs):\n    ret = {'name': name,\n           'changes': {},\n           'result': True,\n           'comment': ''}\n    if context is None:\n        context = {}\n    elif not isinstance(context, dict):\n        ret['result'] = False\n        ret['comment'] = 'Context must be formed as a dict'\n        return ret\n    if defaults is None:\n        defaults = {}\n    elif not isinstance(defaults, dict):\n        ret['result'] = False\n        ret['comment'] = 'Defaults must be formed as a dict'\n        return ret\n    if __opts__['test']:\n        ret['result'] = None\n        ret['comment'] = 'Debconf selections would have been set.'\n        return ret\n    if template:\n        result = __salt__['debconf.set_template'](source, template, context, defaults, **kwargs)\n    else:\n        result = __salt__['debconf.set_file'](source, **kwargs)\n    if result:\n        ret['comment'] = 'Debconf selections were set.'\n    else:\n        ret['result'] = False\n        ret['comment'] = 'Unable to set debconf selections from file.'\n    return ret",
    "docstring": "Set debconf selections from a file or a template\n\n    .. code-block:: yaml\n\n        <state_id>:\n          debconf.set_file:\n            - source: salt://pathto/pkg.selections\n\n        <state_id>:\n          debconf.set_file:\n            - source: salt://pathto/pkg.selections?saltenv=myenvironment\n\n        <state_id>:\n          debconf.set_file:\n            - source: salt://pathto/pkg.selections.jinja2\n            - template: jinja\n            - context:\n                some_value: \"false\"\n\n    source:\n        The location of the file containing the package selections\n\n    template\n        If this setting is applied then the named templating engine will be\n        used to render the package selections file, currently jinja, mako, and\n        wempy are supported\n\n    context\n        Overrides default context variables passed to the template.\n\n    defaults\n        Default context passed to the template."
  },
  {
    "code": "def set_attr(self, name, val, dval=None, dtype=None, reset=False):\n        if dval is not None and val is None:\n            val = dval\n        if dtype is not None and val is not None:\n            if isinstance(dtype, type):\n                val = dtype(val)\n            else:\n                val = dtype.type(val)\n        if reset or not hasattr(self, name) or \\\n           (hasattr(self, name) and getattr(self, name) is None):\n            setattr(self, name, val)",
    "docstring": "Set an object attribute by its name. The attribute value\n        can be specified as a primary value `val`, and as default\n        value 'dval` that will be used if the primary value is None.\n        This arrangement allows an attribute to be set from an entry\n        in an options object, passed as `val`, while specifying a\n        default value to use, passed as `dval` in the event that the\n        options entry is None. Unless `reset` is True, the attribute\n        is only set if it doesn't exist, or if it exists with value\n        None. This arrangement allows for attributes to be set in\n        both base and derived class initialisers, with the derived\n        class value taking preference.\n\n        Parameters\n        ----------\n        name : string\n          Attribute name\n        val : any\n          Primary attribute value\n        dval : any\n          Default attribute value in case `val` is None\n        dtype : data-type, optional (default None)\n          If the `dtype` parameter is not None, the attribute `name` is\n          set to `val` (which is assumed to be of numeric type) after\n          conversion to the specified type.\n        reset : bool, optional (default False)\n          Flag indicating whether attribute assignment should be\n          conditional on the attribute not existing or having value None.\n          If False, an attribute value other than None will not be\n          overwritten."
  },
  {
    "code": "def get_verse(self, v=1):\n        verse_count = len(self.verses)\n        if v - 1 < verse_count:\n            return self.verses[v - 1]",
    "docstring": "Get a specific verse."
  },
  {
    "code": "def search(session, query):\n    flat_query = \"\".join(query.split())\n    artists = session.query(Artist).filter(\n            or_(Artist.name.ilike(f\"%%{query}%%\"),\n                Artist.name.ilike(f\"%%{flat_query}%%\"))\n               ).all()\n    albums = session.query(Album).filter(\n            Album.title.ilike(f\"%%{query}%%\")).all()\n    tracks = session.query(Track).filter(\n            Track.title.ilike(f\"%%{query}%%\")).all()\n    return dict(artists=artists,\n                albums=albums,\n                tracks=tracks)",
    "docstring": "Naive search of the database for `query`.\n\n    :return: A dict with keys 'artists', 'albums', and 'tracks'. Each containing a list\n             of the respective ORM type."
  },
  {
    "code": "def timeout_queue_add(self, item, cache_time=0):\n        self.timeout_add_queue.append((item, cache_time))\n        if self.timeout_due is None or cache_time < self.timeout_due:\n            self.update_request.set()",
    "docstring": "Add a item to be run at a future time.\n        This must be a Module, I3statusModule or a Task"
  },
  {
    "code": "def raw_data_engine(**kwargs):\n    logger.debug(\"cycles_engine\")\n    raise NotImplementedError\n    experiments = kwargs[\"experiments\"]\n    farms = []\n    barn = \"raw_dir\"\n    for experiment in experiments:\n        farms.append([])\n    return farms, barn",
    "docstring": "engine to extract raw data"
  },
  {
    "code": "def lambda_A_calc(classes, table, P, POP):\n    try:\n        result = 0\n        maxreference = max(list(P.values()))\n        length = POP\n        for i in classes:\n            col = []\n            for col_item in table.values():\n                col.append(col_item[i])\n            result += max(col)\n        result = (result - maxreference) / (length - maxreference)\n        return result\n    except Exception:\n        return \"None\"",
    "docstring": "Calculate Goodman and Kruskal's lambda A.\n\n    :param classes: confusion matrix classes\n    :type classes : list\n    :param table: confusion matrix table\n    :type table : dict\n    :param P: condition positive\n    :type P : dict\n    :param POP: population\n    :type POP : int\n    :return: Goodman and Kruskal's lambda A as float"
  },
  {
    "code": "def fix_germline_samplename(in_file, sample_name, data):\n    out_file = \"%s-fixnames%s\" % utils.splitext_plus(in_file)\n    if not utils.file_exists(out_file):\n        with file_transaction(data, out_file) as tx_out_file:\n            sample_file = \"%s-samples.txt\" % utils.splitext_plus(tx_out_file)[0]\n            with open(sample_file, \"w\") as out_handle:\n                out_handle.write(\"%s\\n\" % sample_name)\n            cmd = (\"bcftools reheader -s {sample_file} {in_file} -o {tx_out_file}\")\n            do.run(cmd.format(**locals()), \"Fix germline samplename: %s\" % sample_name)\n    return vcfutils.bgzip_and_index(out_file, data[\"config\"])",
    "docstring": "Replace germline sample names, originally from normal BAM file."
  },
  {
    "code": "def write(gmt, out_path):\n    with open(out_path, 'w') as f:\n        for _, each_dict in enumerate(gmt):\n            f.write(each_dict[SET_IDENTIFIER_FIELD] + '\\t')\n            f.write(each_dict[SET_DESC_FIELD] + '\\t')\n            f.write('\\t'.join([str(entry) for entry in each_dict[SET_MEMBERS_FIELD]]))\n            f.write('\\n')",
    "docstring": "Write a GMT to a text file.\n\n    Args:\n        gmt (GMT object): list of dicts\n        out_path (string): output path\n\n    Returns:\n        None"
  },
  {
    "code": "def check_required_keys(self, required_keys):\n        h = self._contents_hash\n        for key in required_keys:\n            if key not in h:\n                raise InsufficientGraftMPackageException(\"Package missing key %s\" % key)",
    "docstring": "raise InsufficientGraftMPackageException if this package does not\n        conform to the standard of the given package"
  },
  {
    "code": "def _read_atlas_zonefile( zonefile_path, zonefile_hash ):\n    with open(zonefile_path, \"rb\") as f:\n        data = f.read()\n    if zonefile_hash is not None:\n        if not verify_zonefile( data, zonefile_hash ):\n            log.debug(\"Corrupt zonefile '%s'\" % zonefile_hash)\n            return None\n    return data",
    "docstring": "Read and verify an atlas zone file"
  },
  {
    "code": "def triangulate(points):  \n    seen = set() \n    uniqpoints = [ p for p in points if str( p[:2] ) not in seen and not seen.add( str( p[:2] ) )]\n    classpoints = [_Point(*point[:2]) for point in uniqpoints]\n    triangle_ids = tesselator.computeDelaunayTriangulation(classpoints)\n    triangles = [[uniqpoints[i] for i in triangle] for triangle in triangle_ids]\n    return triangles",
    "docstring": "Connects an input list of xy tuples with lines forming a set of \n    smallest possible Delauney triangles between them.\n\n    Arguments:\n\n    - **points**: A list of xy or xyz point tuples to triangulate. \n\n    Returns:\n\n    - A list of triangle polygons. If the input coordinate points contained\n        a third z value then the output triangles will also have these z values."
  },
  {
    "code": "def save(self):\n        if not self._new:\n            data = self._data.copy()\n            ID = data.pop(self.primaryKey)\n            reply = r.table(self.table).get(ID) \\\n                .update(data,\n                        durability=self.durability,\n                        non_atomic=self.non_atomic) \\\n                .run(self._conn)\n        else:\n            reply = r.table(self.table) \\\n                .insert(self._data,\n                        durability=self.durability,\n                        upsert=self.upsert) \\\n                .run(self._conn)\n            self._new = False\n        if \"generated_keys\" in reply and reply[\"generated_keys\"]:\n            self._data[self.primaryKey] = reply[\"generated_keys\"][0]\n        if \"errors\" in reply and reply[\"errors\"] > 0:\n            raise Exception(\"Could not insert entry: %s\"\n                            % reply[\"first_error\"])\n        return True",
    "docstring": "If an id exists in the database, we assume we'll update it, and if not\n        then we'll insert it. This could be a problem with creating your own\n        id's on new objects, however luckily, we keep track of if this is a new\n        object through a private _new variable, and use that to determine if we\n        insert or update."
  },
  {
    "code": "def energy(self):\n        e = 0\n        for i in range(len(self.state)):\n            e += self.distance_matrix[self.state[i-1]][self.state[i]]\n        return e",
    "docstring": "Calculates the length of the route."
  },
  {
    "code": "def get_unspents(address, blockchain_client=BlockchainInfoClient()):\n    if isinstance(blockchain_client, BlockcypherClient):\n        return blockcypher.get_unspents(address, blockchain_client)\n    elif isinstance(blockchain_client, BlockchainInfoClient):\n        return blockchain_info.get_unspents(address, blockchain_client)\n    elif isinstance(blockchain_client, ChainComClient):\n        return chain_com.get_unspents(address, blockchain_client)\n    elif isinstance(blockchain_client, (BitcoindClient, AuthServiceProxy)):\n        return bitcoind.get_unspents(address, blockchain_client)\n    elif hasattr(blockchain_client, \"get_unspents\"):\n        return blockchain_client.get_unspents( address )\n    elif isinstance(blockchain_client, BlockchainClient):\n        raise Exception('That blockchain interface is not supported.')\n    else:\n        raise Exception('A BlockchainClient object is required')",
    "docstring": "Gets the unspent outputs for a given address."
  },
  {
    "code": "def increase_last(self, k):\r\n        idx = self._last_idx\r\n        if idx is not None:\r\n            self.results[idx] += k",
    "docstring": "Increase the last result by k."
  },
  {
    "code": "def compile(file):\n    log(_(\"compiling {} into byte code...\").format(file))\n    try:\n        py_compile.compile(file, doraise=True)\n    except py_compile.PyCompileError as e:\n        log(_(\"Exception raised: \"))\n        for line in e.msg.splitlines():\n            log(line)\n        raise Failure(_(\"{} raised while compiling {} (rerun with --log for more details)\").format(e.exc_type_name, file))",
    "docstring": "Compile a Python program into byte code\n\n    :param file: file to be compiled\n    :raises check50.Failure: if compilation fails e.g. if there is a SyntaxError"
  },
  {
    "code": "def _scatter_list(self, data, owner):\n        rank = self.comm.rank\n        size = self.comm.size\n        subject_submatrices = []\n        nblocks = self.comm.bcast(len(data)\n                                  if rank == owner else None, root=owner)\n        for idx in range(0, nblocks, size):\n            padded = None\n            extra = max(0, idx+size - nblocks)\n            if data is not None:\n                padded = data[idx:idx+size]\n                if extra > 0:\n                    padded = padded + [None]*extra\n            mytrans = self.comm.scatter(padded, root=owner)\n            if mytrans is not None:\n                subject_submatrices += [mytrans]\n        return subject_submatrices",
    "docstring": "Distribute a list from one rank to other ranks in a cyclic manner\n\n        Parameters\n        ----------\n\n        data: list of pickle-able data\n\n        owner: rank that owns the data\n\n        Returns\n        -------\n\n        A list containing the data in a cyclic layout across ranks"
  },
  {
    "code": "def _change_mode(self, mode, major, minor):\n        if self._mode:\n            if self._mode != mode:\n                raise RuntimeError('Can\\'t change mode (from %s to %s)' % (self._mode, mode))\n        self._require_version(major=major, minor=minor)\n        self._mode = mode\n        self.ticket_flags = YubiKeyConfigBits(0x0)\n        self.config_flags = YubiKeyConfigBits(0x0)\n        self.extended_flags = YubiKeyConfigBits(0x0)\n        if mode != 'YUBIKEY_OTP':\n            self.ticket_flag(mode, True)",
    "docstring": "Change mode of operation, with some sanity checks."
  },
  {
    "code": "def job_from_file(job_ini, job_id, username, **kw):\n    hc_id = kw.get('hazard_calculation_id')\n    try:\n        oq = readinput.get_oqparam(job_ini, hc_id=hc_id)\n    except Exception:\n        logs.dbcmd('finish', job_id, 'failed')\n        raise\n    if 'calculation_mode' in kw:\n        oq.calculation_mode = kw.pop('calculation_mode')\n    if 'description' in kw:\n        oq.description = kw.pop('description')\n    if 'exposure_file' in kw:\n        fnames = kw.pop('exposure_file').split()\n        if fnames:\n            oq.inputs['exposure'] = fnames\n        elif 'exposure' in oq.inputs:\n            del oq.inputs['exposure']\n    logs.dbcmd('update_job', job_id,\n               dict(calculation_mode=oq.calculation_mode,\n                    description=oq.description,\n                    user_name=username,\n                    hazard_calculation_id=hc_id))\n    return oq",
    "docstring": "Create a full job profile from a job config file.\n\n    :param job_ini:\n        Path to a job.ini file\n    :param job_id:\n        ID of the created job\n    :param username:\n        The user who will own this job profile and all results\n    :param kw:\n         Extra parameters including `calculation_mode` and `exposure_file`\n    :returns:\n        an oqparam instance"
  },
  {
    "code": "def pixelate(x, severity=1):\n  c = [0.6, 0.5, 0.4, 0.3, 0.25][severity - 1]\n  shape = x.shape\n  x = tfds.core.lazy_imports.PIL_Image.fromarray(x.astype(np.uint8))\n  x = x.resize((int(shape[1] * c), int(shape[0] * c)))\n  x = x.resize((shape[1], shape[0]))\n  return np.asarray(x)",
    "docstring": "Pixelate images.\n\n  Conduct pixelating corruptions to images by first shrinking the images and\n  then resizing to original size.\n\n  Args:\n    x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].\n    severity: integer, severity of corruption.\n\n  Returns:\n    numpy array, image with uint8 pixels in [0,255]. Applied pixelating\n    corruption."
  },
  {
    "code": "def constant_coefficients(d, timelines, constant=True, independent=0):\n    return time_varying_coefficients(d, timelines, constant, independent=independent, randgen=random.normal)",
    "docstring": "Proportional hazards model.\n\n    d: the dimension of the dataset\n    timelines: the observational times\n    constant: True for constant coefficients\n    independent: the number of coffients to set to 0 (covariate is ind of survival), or\n      a list of covariates to make indepent.\n\n    returns a matrix (t,d+1) of coefficients"
  },
  {
    "code": "def may_be_null_is_nullable():\n    repo = GIRepository()\n    repo.require(\"GLib\", \"2.0\", 0)\n    info = repo.find_by_name(\"GLib\", \"spawn_sync\")\n    return not info.get_arg(8).may_be_null",
    "docstring": "If may_be_null returns nullable or if NULL can be passed in.\n\n    This can still be wrong if the specific typelib is older than the linked\n    libgirepository.\n\n    https://bugzilla.gnome.org/show_bug.cgi?id=660879#c47"
  },
  {
    "code": "def list_parameters(self, parameter_type=None, page_size=None):\n        params = {'details': True}\n        if parameter_type is not None:\n            params['type'] = parameter_type\n        if page_size is not None:\n            params['limit'] = page_size\n        return pagination.Iterator(\n            client=self._client,\n            path='/mdb/{}/parameters'.format(self._instance),\n            params=params,\n            response_class=mdb_pb2.ListParametersResponse,\n            items_key='parameter',\n            item_mapper=Parameter,\n        )",
    "docstring": "Lists the parameters visible to this client.\n\n        Parameters are returned in lexicographical order.\n\n        :param str parameter_type: The type of parameter\n        :rtype: :class:`.Parameter` iterator"
  },
  {
    "code": "def fit(self, pairs, y, calibration_params=None):\n    calibration_params = (calibration_params if calibration_params is not\n                          None else dict())\n    self._validate_calibration_params(**calibration_params)\n    self._fit(pairs, y)\n    self.calibrate_threshold(pairs, y, **calibration_params)\n    return self",
    "docstring": "Learn the MMC model.\n\n    The threshold will be calibrated on the trainset using the parameters\n    `calibration_params`.\n\n    Parameters\n    ----------\n    pairs : array-like, shape=(n_constraints, 2, n_features) or\n           (n_constraints, 2)\n        3D Array of pairs with each row corresponding to two points,\n        or 2D array of indices of pairs if the metric learner uses a\n        preprocessor.\n    y : array-like, of shape (n_constraints,)\n        Labels of constraints. Should be -1 for dissimilar pair, 1 for similar.\n    calibration_params : `dict` or `None`\n        Dictionary of parameters to give to `calibrate_threshold` for the\n        threshold calibration step done at the end of `fit`. If `None` is\n        given, `calibrate_threshold` will use the default parameters.\n    Returns\n    -------\n    self : object\n        Returns the instance."
  },
  {
    "code": "def _send_to_timeseries(self, message):\n        logging.debug(\"MESSAGE=\" + str(message))\n        result = None\n        try:\n            ws = self._get_websocket()\n            ws.send(json.dumps(message))\n            result = ws.recv()\n        except (websocket.WebSocketConnectionClosedException, Exception) as e:\n            logging.debug(\"Connection failed, will try again.\")\n            logging.debug(e)\n            ws = self._get_websocket(reuse=False)\n            ws.send(json.dumps(message))\n            result = ws.recv()\n        logging.debug(\"RESULT=\" + str(result))\n        return result",
    "docstring": "Establish or reuse socket connection and send\n        the given message to the timeseries service."
  },
  {
    "code": "def install_package(self, client, package):\n        install_cmd = \"{sudo} '{install} {package}'\".format(\n            sudo=self.get_sudo_exec_wrapper(),\n            install=self.get_install_cmd(),\n            package=package\n        )\n        try:\n            out = ipa_utils.execute_ssh_command(\n                client,\n                install_cmd\n            )\n        except Exception as error:\n            raise IpaDistroException(\n                'An error occurred installing package {package} '\n                'on instance: {error}'.format(\n                    package=package,\n                    error=error\n                )\n            )\n        else:\n            return out",
    "docstring": "Install package on instance."
  },
  {
    "code": "def GuinierPorodGuinier(q, G, Rg1, alpha, Rg2):\n    return GuinierPorodMulti(q, G, Rg1, alpha, Rg2)",
    "docstring": "Empirical Guinier-Porod-Guinier scattering\n\n    Inputs:\n    -------\n        ``q``: independent variable\n        ``G``: factor for the first Guinier-branch\n        ``Rg1``: the first radius of gyration\n        ``alpha``: the power-law exponent\n        ``Rg2``: the second radius of gyration\n\n    Formula:\n    --------\n        ``G*exp(-q^2*Rg1^2/3)`` if ``q<q_sep1``.\n        ``A*q^alpha`` if ``q_sep1 <= q  <=q_sep2``.\n        ``G2*exp(-q^2*Rg2^2/3)`` if ``q_sep2<q``.\n        The parameters ``A``,``G2``, ``q_sep1``, ``q_sep2`` are determined\n        from conditions of smoothness at the cross-overs.\n\n    Literature:\n    -----------\n        B. Hammouda: A new Guinier-Porod model. J. Appl. Crystallogr. (2010) 43,\n            716-719."
  },
  {
    "code": "def add_interval(self, start, end, data=None):\n        if (end - start) <= 0:\n            return\n        if self.single_interval is None:\n            self.single_interval = (start, end, data)\n        elif self.single_interval == 0:\n            self._add_interval(start, end, data)\n        else:\n            self._add_interval(*self.single_interval)\n            self.single_interval = 0\n            self._add_interval(start, end, data)",
    "docstring": "Inserts an interval to the tree. \n        Note that when inserting we do not maintain appropriate sorting of the \"mid\" data structure.\n        This should be done after all intervals are inserted."
  },
  {
    "code": "def record_to_objects(self):\n        from ambry.orm import SourceTable\n        bsfile = self.record\n        failures = set()\n        for row in bsfile.dict_row_reader:\n            st = self._dataset.source_table(row['table'])\n            if st:\n                st.columns[:] = []\n        self._dataset.commit()\n        for row in bsfile.dict_row_reader:\n            st = self._dataset.source_table(row['table'])\n            if not st:\n                st = self._dataset.new_source_table(row['table'])\n            if 'datatype' not in row:\n                row['datatype'] = 'unknown'\n            del row['table']\n            st.add_column(**row)\n        if failures:\n            raise ConfigurationError('Failed to load source schema, missing sources: {} '.format(failures))\n        self._dataset.commit()",
    "docstring": "Write from the stored file data to the source records"
  },
  {
    "code": "def init_db_conn(connection_name, connection_string, scopefunc=None):\n    engine = create_engine(connection_string)\n    session = scoped_session(sessionmaker(), scopefunc=scopefunc)\n    session.configure(bind=engine)\n    pool.connections[connection_name] = Connection(engine, session)",
    "docstring": "Initialize a postgresql connection by each connection string\n    defined in the configuration file"
  },
  {
    "code": "def _collect_headers(self):\n        res = []\n        for prop in self.get_sorted_columns():\n            main_infos = self._get_prop_infos(prop)\n            if self._is_excluded(prop, main_infos):\n                continue\n            if isinstance(prop, RelationshipProperty):\n                main_infos = self._collect_relationship(main_infos, prop, res)\n                if not main_infos:\n                    print(\"Maybe there's missing some informations \\\nabout a relationship\")\n                    continue\n            else:\n                main_infos = self._merge_many_to_one_field_from_fkey(\n                    main_infos, prop, res\n                )\n                if not main_infos:\n                    continue\n            if isinstance(main_infos, (list, tuple)):\n                res.extend(main_infos)\n            else:\n                res.append(main_infos)\n        return res",
    "docstring": "Collect headers from the models attribute info col"
  },
  {
    "code": "def get_name(self, plugin):\n        for name, val in self._name2plugin.items():\n            if plugin == val:\n                return name",
    "docstring": "Return name for registered plugin or None if not registered."
  },
  {
    "code": "def default_memcache_timeout_policy(key):\n    timeout = None\n    if key is not None and isinstance(key, model.Key):\n      modelclass = model.Model._kind_map.get(key.kind())\n      if modelclass is not None:\n        policy = getattr(modelclass, '_memcache_timeout', None)\n        if policy is not None:\n          if isinstance(policy, (int, long)):\n            timeout = policy\n          else:\n            timeout = policy(key)\n    return timeout",
    "docstring": "Default memcache timeout policy.\n\n    This defers to _memcache_timeout on the Model class.\n\n    Args:\n      key: Key instance.\n\n    Returns:\n      Memcache timeout to use (integer), or None."
  },
  {
    "code": "def create_sequence_readers(sources: List[str], target: str,\n                            vocab_sources: List[vocab.Vocab],\n                            vocab_target: vocab.Vocab) -> Tuple[List[SequenceReader], SequenceReader]:\n    source_sequence_readers = [SequenceReader(source, vocab, add_eos=True) for source, vocab in\n                               zip(sources, vocab_sources)]\n    target_sequence_reader = SequenceReader(target, vocab_target, add_bos=True)\n    return source_sequence_readers, target_sequence_reader",
    "docstring": "Create source readers with EOS and target readers with BOS.\n\n    :param sources: The file names of source data and factors.\n    :param target: The file name of the target data.\n    :param vocab_sources: The source vocabularies.\n    :param vocab_target: The target vocabularies.\n    :return: The source sequence readers and the target reader."
  },
  {
    "code": "def _send(self, *messages):\n        if not self.transport:\n            return False\n        messages = [message.encode('ascii') for message in messages]\n        data = b''\n        while messages:\n            message = messages.pop(0)\n            if len(data + message) + 1 > self.parent.cfg.maxudpsize:\n                self.transport.sendto(data)\n                data = b''\n            data += message + b'\\n'\n        if data:\n            self.transport.sendto(data)",
    "docstring": "Send message."
  },
  {
    "code": "def raise_exception(self, exception, tup=None):\n        if tup:\n            message = (\n                \"Python {exception_name} raised while processing Tuple \"\n                \"{tup!r}\\n{traceback}\"\n            )\n        else:\n            message = \"Python {exception_name} raised\\n{traceback}\"\n        message = message.format(\n            exception_name=exception.__class__.__name__, tup=tup, traceback=format_exc()\n        )\n        self.send_message({\"command\": \"error\", \"msg\": str(message)})\n        self.send_message({\"command\": \"sync\"})",
    "docstring": "Report an exception back to Storm via logging.\n\n        :param exception: a Python exception.\n        :param tup: a :class:`Tuple` object."
  },
  {
    "code": "def set_state_view(self, request):\n        if not request.user.has_perm('experiments.change_experiment'):\n            return HttpResponseForbidden()\n        try:\n            state = int(request.POST.get(\"state\", \"\"))\n        except ValueError:\n            return HttpResponseBadRequest()\n        try:\n            experiment = Experiment.objects.get(name=request.POST.get(\"experiment\"))\n        except Experiment.DoesNotExist:\n            return HttpResponseBadRequest()\n        experiment.state = state\n        if state == 0:\n            experiment.end_date = timezone.now()\n        else:\n            experiment.end_date = None\n        experiment.save()\n        return HttpResponse()",
    "docstring": "Changes the experiment state"
  },
  {
    "code": "def basic_qos(self, prefetch_size, prefetch_count, a_global):\n        args = AMQPWriter()\n        args.write_long(prefetch_size)\n        args.write_short(prefetch_count)\n        args.write_bit(a_global)\n        self._send_method((60, 10), args)\n        return self.wait(allowed_methods=[\n            (60, 11),\n        ])",
    "docstring": "Specify quality of service\n\n        This method requests a specific quality of service.  The QoS\n        can be specified for the current channel or for all channels\n        on the connection.  The particular properties and semantics of\n        a qos method always depend on the content class semantics.\n        Though the qos method could in principle apply to both peers,\n        it is currently meaningful only for the server.\n\n        PARAMETERS:\n            prefetch_size: long\n\n                prefetch window in octets\n\n                The client can request that messages be sent in\n                advance so that when the client finishes processing a\n                message, the following message is already held\n                locally, rather than needing to be sent down the\n                channel.  Prefetching gives a performance improvement.\n                This field specifies the prefetch window size in\n                octets.  The server will send a message in advance if\n                it is equal to or smaller in size than the available\n                prefetch size (and also falls into other prefetch\n                limits). May be set to zero, meaning \"no specific\n                limit\", although other prefetch limits may still\n                apply. The prefetch-size is ignored if the no-ack\n                option is set.\n\n                RULE:\n\n                    The server MUST ignore this setting when the\n                    client is not processing any messages - i.e. the\n                    prefetch size does not limit the transfer of\n                    single messages to a client, only the sending in\n                    advance of more messages while the client still\n                    has one or more unacknowledged messages.\n\n            prefetch_count: short\n\n                prefetch window in messages\n\n                Specifies a prefetch window in terms of whole\n                messages.  This field may be used in combination with\n                the prefetch-size field; a message will only be sent\n                in advance if both prefetch windows (and those at the\n                channel and connection level) allow it. The prefetch-\n                count is ignored if the no-ack option is set.\n\n                RULE:\n\n                    The server MAY send less data in advance than\n                    allowed by the client's specified prefetch windows\n                    but it MUST NOT send more.\n\n            a_global: boolean\n\n                apply to entire connection\n\n                By default the QoS settings apply to the current\n                channel only.  If this field is set, they are applied\n                to the entire connection."
  },
  {
    "code": "def calc_A(Ys):\n    return sum(np.dot(np.reshape(Y, (3,1)), np.reshape(Y, (1, 3)))\n            for Y in Ys)",
    "docstring": "Return the matrix A from a list of Y vectors."
  },
  {
    "code": "def set_stream_id(self, stream_id):\n        stream_id = validate_type(stream_id, type(None), *six.string_types)\n        if stream_id is not None:\n            stream_id = stream_id.lstrip('/')\n        self._stream_id = stream_id",
    "docstring": "Set the stream id associated with this data point"
  },
  {
    "code": "def from_gps(cls, gps, Name = None):\n\t\tself = cls(AttributesImpl({u\"Type\": u\"GPS\"}))\n\t\tif Name is not None:\n\t\t\tself.Name = Name\n\t\tself.pcdata = gps\n\t\treturn self",
    "docstring": "Instantiate a Time element initialized to the value of the\n\t\tgiven GPS time.  The Name attribute will be set to the\n\t\tvalue of the Name parameter if given.\n\n\t\tNote:  the new Time element holds a reference to the GPS\n\t\ttime, not a copy of it.  Subsequent modification of the GPS\n\t\ttime object will be reflected in what gets written to disk."
  },
  {
    "code": "def is_base_and_derived(based, derived):\n    assert isinstance(based, class_declaration.class_t)\n    assert isinstance(derived, (class_declaration.class_t, tuple))\n    if isinstance(derived, class_declaration.class_t):\n        all_derived = ([derived])\n    else:\n        all_derived = derived\n    for derived_cls in all_derived:\n        for base_desc in derived_cls.recursive_bases:\n            if base_desc.related_class == based:\n                return True\n    return False",
    "docstring": "returns True, if there is \"base and derived\" relationship between\n    classes, False otherwise"
  },
  {
    "code": "def adjust_doy_calendar(source, target):\n    doy_max_source = source.dayofyear.max()\n    doy_max = infer_doy_max(target)\n    if doy_max_source == doy_max:\n        return source\n    return _interpolate_doy_calendar(source, doy_max)",
    "docstring": "Interpolate from one set of dayofyear range to another calendar.\n\n    Interpolate an array defined over a `dayofyear` range (say 1 to 360) to another `dayofyear` range (say 1\n    to 365).\n\n    Parameters\n    ----------\n    source : xarray.DataArray\n      Array with `dayofyear` coordinates.\n    target : xarray.DataArray\n      Array with `time` coordinate.\n\n    Returns\n    -------\n    xarray.DataArray\n      Interpolated source array over coordinates spanning the target `dayofyear` range."
  },
  {
    "code": "def validate_int(datum, **kwargs):\n    return (\n            (isinstance(datum, (int, long, numbers.Integral))\n             and INT_MIN_VALUE <= datum <= INT_MAX_VALUE\n             and not isinstance(datum, bool))\n            or isinstance(\n                datum, (datetime.time, datetime.datetime, datetime.date)\n            )\n    )",
    "docstring": "Check that the data value is a non floating\n    point number with size less that Int32.\n    Also support for logicalType timestamp validation with datetime.\n\n    Int32 = -2147483648<=datum<=2147483647\n\n    conditional python types\n    (int, long, numbers.Integral,\n    datetime.time, datetime.datetime, datetime.date)\n\n    Parameters\n    ----------\n    datum: Any\n        Data being validated\n    kwargs: Any\n        Unused kwargs"
  },
  {
    "code": "def generate_ul(self, a_list):\n        return len(a_list) > 0 and (isinstance(a_list[0], Rule) or\n                                    isinstance(a_list[0], LabelDecl))",
    "docstring": "Determines if we should generate th 'ul' around the list 'a_list'"
  },
  {
    "code": "def consult_robots_txt(self, request: HTTPRequest) -> bool:\n        if not self._robots_txt_checker:\n            return True\n        result = yield from self._robots_txt_checker.can_fetch(request)\n        return result",
    "docstring": "Consult by fetching robots.txt as needed.\n\n        Args:\n            request: The request to be made\n                to get the file.\n\n        Returns:\n            True if can fetch\n\n        Coroutine"
  },
  {
    "code": "def import_cfg(file_name, **kwargs):\n    def callback(data):\n        return libconf.loads(data)\n    try:\n        import libconf\n    except ImportError:\n        raise exch.GeomdlException(\"Please install 'libconf' package to use libconfig format: pip install libconf\")\n    delta = kwargs.get('delta', -1.0)\n    use_template = kwargs.get('jinja2', False)\n    file_src = exch.read_file(file_name)\n    return exch.import_dict_str(file_src=file_src, delta=delta, callback=callback, tmpl=use_template)",
    "docstring": "Imports curves and surfaces from files in libconfig format.\n\n    .. note::\n\n        Requires `libconf <https://pypi.org/project/libconf/>`_ package.\n\n    Use ``jinja2=True`` to activate Jinja2 template processing. Please refer to the documentation for details.\n\n    :param file_name: name of the input file\n    :type file_name: str\n    :return: a list of rational spline geometries\n    :rtype: list\n    :raises GeomdlException: an error occurred writing the file"
  },
  {
    "code": "def get_dyndns_records(login, password):\n    params = dict(action='getdyndns', sha=get_auth_key(login, password))\n    response = requests.get('http://freedns.afraid.org/api/', params=params, timeout=timeout)\n    raw_records = (line.split('|') for line in response.content.split())\n    try:\n        records = frozenset(DnsRecord(*record) for record in raw_records)\n    except TypeError:\n        raise ApiError(\"Couldn't parse the server's response\",\n                response.content)\n    return records",
    "docstring": "Gets the set of dynamic DNS records associated with this account"
  },
  {
    "code": "def begin(self):\n\t\tmid = self._device.readU16BE(MCP9808_REG_MANUF_ID)\n\t\tdid = self._device.readU16BE(MCP9808_REG_DEVICE_ID)\n\t\tself._logger.debug('Read manufacturer ID: {0:04X}'.format(mid))\n\t\tself._logger.debug('Read device ID: {0:04X}'.format(did))\n\t\treturn mid == 0x0054 and did == 0x0400",
    "docstring": "Start taking temperature measurements. Returns True if the device is \n\t\tintialized, False otherwise."
  },
  {
    "code": "def _dash_f_e_to_dict(self, info_filename, tree_filename):\n        with open(info_filename) as fl:\n            models, likelihood, partition_params = self._dash_f_e_parser.parseFile(fl).asList()\n        with open(tree_filename) as fl:\n            tree = fl.read()\n        d = {'likelihood': likelihood, 'ml_tree': tree, 'partitions': {}}\n        for model, params in zip(models, partition_params):\n            subdict = {}\n            index, name, _, alpha, rates, freqs = params\n            subdict['alpha'] = alpha\n            subdict['name'] = name\n            subdict['rates'] = rates\n            subdict['frequencies'] = freqs\n            subdict['model'] = model\n            d['partitions'][index] = subdict\n        return d",
    "docstring": "Raxml provides an option to fit model params to a tree,\n        selected with -f e.\n        The output is different and needs a different parser."
  },
  {
    "code": "def update_by_token(self, token, **kwargs):\n        _sid = self.handler.sid(token)\n        return self.update(_sid, **kwargs)",
    "docstring": "Updated the session info. Any type of known token can be used\n\n        :param token: code/access token/refresh token/...\n        :param kwargs: Key word arguements"
  },
  {
    "code": "def handle_input(self, code):\n        if not self.prompt.multiline:\n            if not should_indent(code):\n                try:\n                    return self.comp.parse_block(code)\n                except CoconutException:\n                    pass\n            while True:\n                line = self.get_input(more=True)\n                if line is None:\n                    return None\n                elif line:\n                    code += \"\\n\" + line\n                else:\n                    break\n        try:\n            return self.comp.parse_block(code)\n        except CoconutException:\n            logger.display_exc()\n        return None",
    "docstring": "Compile Coconut interpreter input."
  },
  {
    "code": "def DbGetAliasAttribute(self, argin):\n        self._log.debug(\"In DbGetAliasAttribute()\")\n        alias_name = argin[0]\n        return self.db.get_alias_attribute(alias_name)",
    "docstring": "Get the attribute name from the given alias.\n        If the given alias is not found in database, returns an empty string\n\n        :param argin: The attribute alias\n        :type: tango.DevString\n        :return: The attribute name (dev_name/att_name)\n        :rtype: tango.DevString"
  },
  {
    "code": "def dispatch(self, request, *args, **kwargs):\n        self.wizard_name = self.get_wizard_name()\n        self.prefix = self.get_prefix()\n        self.storage = get_storage(self.storage_name, self.prefix, request,\n            getattr(self, 'file_storage', None))\n        self.steps = StepsHelper(self)\n        response = super(WizardView, self).dispatch(request, *args, **kwargs)\n        self.storage.update_response(response)\n        return response",
    "docstring": "This method gets called by the routing engine. The first argument is\n        `request` which contains a `HttpRequest` instance.\n        The request is stored in `self.request` for later use. The storage\n        instance is stored in `self.storage`.\n\n        After processing the request using the `dispatch` method, the\n        response gets updated by the storage engine (for example add cookies)."
  },
  {
    "code": "def _validate_dtype(self, dtype):\n        if dtype is not None:\n            dtype = pandas_dtype(dtype)\n            if dtype.kind == 'V':\n                raise NotImplementedError(\"compound dtypes are not implemented\"\n                                          \" in the {0} constructor\"\n                                          .format(self.__class__.__name__))\n        return dtype",
    "docstring": "validate the passed dtype"
  },
  {
    "code": "def removeUnreferencedIDs(referencedIDs, identifiedElements):\n    global _num_ids_removed\n    keepTags = ['font']\n    num = 0\n    for id in identifiedElements:\n        node = identifiedElements[id]\n        if id not in referencedIDs and node.nodeName not in keepTags:\n            node.removeAttribute('id')\n            _num_ids_removed += 1\n            num += 1\n    return num",
    "docstring": "Removes the unreferenced ID attributes.\n\n    Returns the number of ID attributes removed"
  },
  {
    "code": "def get_username(sciper):\n    attribute = 'uid'\n    response = LDAP_search(\n        pattern_search='(uniqueIdentifier={})'.format(sciper),\n        attribute=attribute\n    )\n    try:\n        username = get_attribute(response, attribute)\n    except Exception:\n        raise EpflLdapException(\"No username corresponds to sciper {}\".format(sciper))\n    return username",
    "docstring": "Return username of user"
  },
  {
    "code": "def get_n_tail(tmax, tail_temps):\n    t_index = 0\n    adj_tmax = 0\n    if tmax < tail_temps[0]:\n        return 0\n    try:\n        t_index = list(tail_temps).index(tmax)\n    except:\n        for temp in tail_temps:\n            if temp <= tmax:\n                adj_tmax = temp\n        t_index = list(tail_temps).index(adj_tmax)\n    incl_temps = tail_temps[0:t_index+1]\n    return len(incl_temps)",
    "docstring": "determines number of included tail checks in best fit segment"
  },
  {
    "code": "def _get_drive_type_and_speed(self):\n        disk_details = self._get_physical_drive_resource()\n        drive_hdd = False\n        drive_ssd = False\n        drive_details = {}\n        speed_const_list = [4800, 5400, 7200, 10000, 15000]\n        if disk_details:\n            for item in disk_details:\n                value = item['MediaType']\n                if value == \"HDD\":\n                    drive_hdd = True\n                    speed = item['RotationalSpeedRpm']\n                    if speed in speed_const_list:\n                        var = 'rotational_drive_' + str(speed) + '_rpm'\n                        drive_details.update({var: 'true'})\n                else:\n                    drive_ssd = True\n        if drive_hdd:\n            drive_details.update({'has_rotational': 'true'})\n        if drive_ssd:\n            drive_details.update({'has_ssd': 'true'})\n        return drive_details if len(drive_details.keys()) > 0 else None",
    "docstring": "Gets the disk drive type.\n\n        :returns: A dictionary with the following keys:\n            - has_rotational: True/False. It is True if atleast one\n            rotational disk is attached.\n            - has_ssd: True/False. It is True if at least one SSD disk is\n            attached.\n            - drive_rotational_<speed>_rpm: These are set to true as\n              per the speed of the rotational disks.\n        :raises: IloCommandNotSupportedError if the PhysicalDrives resource\n            doesn't exist.\n        :raises: IloError, on an error from iLO."
  },
  {
    "code": "def binary_fraction(self,query='mass_A >= 0'):\n        subdf = self.stars.query(query)\n        nbinaries = (subdf['mass_B'] > 0).sum()\n        frac = nbinaries/len(subdf)\n        return frac, frac/np.sqrt(nbinaries)",
    "docstring": "Binary fraction of stars passing given query\n\n        :param query:\n            Query to pass to stars ``DataFrame``."
  },
  {
    "code": "def submit_populator_batch(self, column_name, batch):\n        if not set(column_name).issubset(_allowedCustomDimensionChars):\n            raise ValueError('Invalid custom dimension name \"%s\": must only contain letters, digits, and underscores' % column_name)\n        if len(column_name) < 3 or len(column_name) > 20:\n            raise ValueError('Invalid value \"%s\": must be between 3-20 characters' % column_name)\n        url = '%s/api/v5/batch/customdimensions/%s/populators' % (self.base_url, column_name)\n        resp_json_dict = self._submit_batch(url, batch)\n        if resp_json_dict.get('error') is not None:\n            raise RuntimeError('Error received from server: %s' % resp_json_dict['error'])\n        return resp_json_dict['guid']",
    "docstring": "Submit a populator batch\n\n        Submit a populator batch as a series of HTTP requests in small chunks,\n        returning the batch GUID, or raising exception on error."
  },
  {
    "code": "def printd(*args, **kwargs):\n    global settings\n    if settings['PRINT_DEBUG_STATE']:\n        print(*args, **kwargs)\n        return True\n    return False",
    "docstring": "Print if PRINT_DEBUG_STATE is True"
  },
  {
    "code": "def mpixel(self, z, n=0):\n        z = z * z + self.c\n        if (abs(z) > 2.0):\n            return self.color(n)\n        n += 1\n        if (n > self.max_iter):\n            return None\n        return self.mpixel(z, n)",
    "docstring": "Iteration in Mandlebrot coordinate z."
  },
  {
    "code": "def _check_reset_and_type_change(self, name, orig_ctr):\n    if name in orig_ctr:\n      tf.logging.warning(\"Overwriting hparam %s\", name)\n    ctr_names = [\n        (self._categorical_params, \"categorical\"),\n        (self._discrete_params, \"discrete\"),\n        (self._float_params, \"float\"),\n        (self._int_params, \"int\"),\n    ]\n    ctrs, names = list(zip(*ctr_names))\n    orig_name = names[ctrs.index(orig_ctr)]\n    for ctr, ctr_name in ctr_names:\n      if ctr is orig_ctr:\n        continue\n      if name in ctr:\n        raise ValueError(\"Setting hyperparameter %s as type %s, but a \"\n                         \"hyperparemeter of the same name was originally \"\n                         \"registered as type %s\" % (name, ctr_name, orig_name))",
    "docstring": "Check if name is in orig_ctr or in one of the other type containers."
  },
  {
    "code": "def _loadFromRow(self, result, fields, cursor):\n        position = 0\n        for elem in fields:\n            value = result[position]\n            valueType = cursor.description[position][1]\n            if hasattr(self._dbModule, 'BOOLEAN') and \\\n                       valueType == self._dbModule.BOOLEAN and \\\n                       (value is not True or value is not False):\n                value = value and True or False\n            if value and self._userClasses.has_key(elem):\n                userClass = self._userClasses[elem]\n                value = userClass(value)\n            self._values[elem] = value\n            position += 1",
    "docstring": "Load from a database row, described by fields.\n\n        ``fields`` should be the attribute names that\n        will be set. Note that userclasses will be\n        created (but not loaded)."
  },
  {
    "code": "def _fS1(self, pos_pairs, A):\n    dim = pos_pairs.shape[2]\n    diff = pos_pairs[:, 0, :] - pos_pairs[:, 1, :]\n    return np.einsum('ij,ik->jk', diff, diff)",
    "docstring": "The gradient of the similarity constraint function w.r.t. A.\n\n    f = \\sum_{ij}(x_i-x_j)A(x_i-x_j)' = \\sum_{ij}d_ij*A*d_ij'\n    df/dA = d(d_ij*A*d_ij')/dA\n\n    Note that d_ij*A*d_ij' = tr(d_ij*A*d_ij') = tr(d_ij'*d_ij*A)\n    so, d(d_ij*A*d_ij')/dA = d_ij'*d_ij"
  },
  {
    "code": "def connect_input(self, wire):\n        self._input = wire\n        wire.sinks.append(self)",
    "docstring": "Probe the specified wire."
  },
  {
    "code": "def pckfrm(pck, ids):\n    pck = stypes.stringToCharP(pck)\n    assert isinstance(ids, stypes.SpiceCell)\n    assert ids.dtype == 2\n    libspice.pckfrm_c(pck, ctypes.byref(ids))",
    "docstring": "Find the set of reference frame class ID codes of all frames\n    in a specified binary PCK file.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pckfrm_c.html\n\n    :param pck: Name of PCK file.\n    :type pck: str\n    :param ids: Set of frame class ID codes of frames in PCK file.\n    :type ids: SpiceCell"
  },
  {
    "code": "def insert(self, optional_root_locations_path):\n        encountered_simple_optional = False\n        parent_location = self._root_location\n        for optional_root_location in optional_root_locations_path:\n            if encountered_simple_optional:\n                raise AssertionError(u'Encountered simple optional root location {} in path, but'\n                                     u'further locations are present. This should not happen: {}'\n                                     .format(optional_root_location, optional_root_locations_path))\n            if optional_root_location not in self._location_to_children:\n                encountered_simple_optional = True\n            else:\n                self._location_to_children[parent_location].add(optional_root_location)\n                parent_location = optional_root_location",
    "docstring": "Insert a path of optional Locations into the tree.\n\n        Each OptionalTraversalTree object contains child Location objects as keys mapping to\n        other OptionalTraversalTree objects.\n\n        Args:\n            optional_root_locations_path: list of optional root Locations all except the last\n                                          of which must be present in complex_optional_roots"
  },
  {
    "code": "def check(name, port=None, **kwargs):\n    host = name\n    ret = {'name': name,\n           'result': True,\n           'changes': {},\n           'comment': ''}\n    if 'test' not in kwargs:\n        kwargs['test'] = __opts__.get('test', False)\n    if kwargs['test']:\n        ret['result'] = True\n        ret['comment'] = 'The connection will be tested'\n    else:\n        results = __salt__['network.connect'](host, port, **kwargs)\n        ret['result'] = results['result']\n        ret['comment'] = results['comment']\n    return ret",
    "docstring": "Checks if there is an open connection from the minion to the defined\n    host on a specific port.\n\n    name\n      host name or ip address to test connection to\n\n    port\n      The port to test the connection on\n\n    kwargs\n      Additional parameters, parameters allowed are:\n        proto (tcp or udp)\n        family (ipv4 or ipv6)\n        timeout\n\n    .. code-block:: yaml\n\n      testgoogle:\n        firewall.check:\n          - name: 'google.com'\n          - port: 80\n          - proto: 'tcp'"
  },
  {
    "code": "def next_media_partname(self, ext):\n        def first_available_media_idx():\n            media_idxs = sorted([\n                part.partname.idx for part in self.iter_parts()\n                if part.partname.startswith('/ppt/media/media')\n            ])\n            for i, media_idx in enumerate(media_idxs):\n                idx = i + 1\n                if idx < media_idx:\n                    return idx\n            return len(media_idxs)+1\n        idx = first_available_media_idx()\n        return PackURI('/ppt/media/media%d.%s' % (idx, ext))",
    "docstring": "Return |PackURI| instance for next available media partname.\n\n        Partname is first available, starting at sequence number 1. Empty\n        sequence numbers are reused. *ext* is used as the extension on the\n        returned partname."
  },
  {
    "code": "def codon2aa(codon, trans_table):\n    return Seq(''.join(codon), IUPAC.ambiguous_dna).translate(table = trans_table)[0]",
    "docstring": "convert codon to amino acid"
  },
  {
    "code": "def parse(self, name):\n\t\tname = name.strip()\n\t\tgroups = self._parseFedora(name)\n\t\tif groups:\n\t\t\tself._signature = DistributionNameSignature(\"Fedora\", groups.group(1))\n\t\t\treturn self\n\t\traise ValueError(\"Distribution name '%s' not recognized\" % name)",
    "docstring": "Parse distribution string\n\n\t\t:param name: distribution string, e.g. \"Fedora 23\"\n\t\t:type  name: string"
  },
  {
    "code": "def emit(self, record):\n        try:\n            msg = self.format(record)\n            pri = self.map_priority(record.levelno)\n            extras = self._extra.copy()\n            if record.exc_text:\n                extras['EXCEPTION_TEXT'] = record.exc_text\n            if record.exc_info:\n                extras['EXCEPTION_INFO'] = record.exc_info\n            if record.args:\n                extras['CODE_ARGS'] = str(record.args)\n            extras.update(record.__dict__)\n            self.send(msg,\n                      PRIORITY=format(pri),\n                      LOGGER=record.name,\n                      THREAD_NAME=record.threadName,\n                      PROCESS_NAME=record.processName,\n                      CODE_FILE=record.pathname,\n                      CODE_LINE=record.lineno,\n                      CODE_FUNC=record.funcName,\n                      **extras)\n        except Exception:\n            self.handleError(record)",
    "docstring": "Write `record` as a journal event.\n\n        MESSAGE is taken from the message provided by the user, and PRIORITY,\n        LOGGER, THREAD_NAME, CODE_{FILE,LINE,FUNC} fields are appended\n        automatically. In addition, record.MESSAGE_ID will be used if present."
  },
  {
    "code": "def _dayofmonth(hardday, month, year):\n    newday = hardday\n    daysinmonth = calendar.monthrange(year, month)[1]\n    if newday < 0:\n        newday = daysinmonth + hardday + 1\n    newday = max(1, min(newday, daysinmonth))\n    return newday",
    "docstring": "Returns a valid day of the month given the desired value.\n\n    Negative values are interpreted as offset backwards from the last day of the month, with -1 representing the\n    last day of the month.  Out-of-range values are clamped to the first or last day of the month."
  },
  {
    "code": "def _read_mode_tcpao(self, size, kind):\n        key_ = self._read_unpack(1)\n        rkey = self._read_unpack(1)\n        mac_ = self._read_fileng(size - 2)\n        data = dict(\n            kind=kind,\n            length=size,\n            keyid=key_,\n            rnextkeyid=rkey,\n            mac=mac_,\n        )\n        return data",
    "docstring": "Read Authentication option.\n\n        Positional arguments:\n            * size - int, length of option\n            * kind - int, 29 (TCP Authentication Option)\n\n        Returns:\n            * dict -- extracted Authentication (AO) option\n\n        Structure of TCP AOopt [RFC 5925]:\n            +------------+------------+------------+------------+\n            |  Kind=29   |   Length   |   KeyID    | RNextKeyID |\n            +------------+------------+------------+------------+\n            |                     MAC           ...\n            +-----------------------------------...\n\n            ...-----------------+\n            ...  MAC (con't)    |\n            ...-----------------+\n\n            Octets      Bits        Name                    Description\n              0           0     tcp.ao.kind             Kind (29)\n              1           8     tcp.ao.length           Length\n              2          16     tcp.ao.keyid            KeyID\n              3          24     tcp.ao.rnextkeyid       RNextKeyID\n              4          32     tcp.ao.mac              Message Authentication Code"
  },
  {
    "code": "def _type_container(self, value, _type):\n        ' apply type to all values in the list '\n        if value is None:\n            return []\n        elif not isinstance(value, list):\n            raise ValueError(\"expected list type, got: %s\" % type(value))\n        else:\n            return sorted(self._type_single(item, _type) for item in value)",
    "docstring": "apply type to all values in the list"
  },
  {
    "code": "def setOverlayNeighbor(self, eDirection, ulFrom, ulTo):\n        fn = self.function_table.setOverlayNeighbor\n        result = fn(eDirection, ulFrom, ulTo)\n        return result",
    "docstring": "Sets an overlay's neighbor. This will also set the neighbor of the \"to\" overlay\n        to point back to the \"from\" overlay. If an overlay's neighbor is set to invalid both\n        ends will be cleared"
  },
  {
    "code": "def init_app(self, app=None, blueprint=None, additional_blueprints=None):\n        if app is not None:\n            self.app = app\n        if blueprint is not None:\n            self.blueprint = blueprint\n        for resource in self.resources:\n            self.route(resource['resource'],\n                       resource['view'],\n                       *resource['urls'],\n                       url_rule_options=resource['url_rule_options'])\n        if self.blueprint is not None:\n            self.app.register_blueprint(self.blueprint)\n        if additional_blueprints is not None:\n            for blueprint in additional_blueprints:\n                self.app.register_blueprint(blueprint)\n        self.app.config.setdefault('PAGE_SIZE', 30)",
    "docstring": "Update flask application with our api\n\n        :param Application app: a flask application"
  },
  {
    "code": "def add_option(self, opt_name, otype, hidden=False):\n        if self.has_option(opt_name):\n            raise ValueError(\"The option is already present !\")\n        opt = ValueOption.FromType(opt_name, otype)\n        opt.hidden = hidden\n        self._options[opt_name] = opt",
    "docstring": "Add an option to the object\n\n        :param opt_name: option name\n        :type opt_name: str\n        :param otype: option type\n        :type otype: subclass of :class:`.GenericType`\n        :param hidden: if True the option will be hidden\n        :type hidden: bool"
  },
  {
    "code": "def cli(dirty, stash):\n    _setup_logging()\n    LOGGER.info('EPAB %s', __version__)\n    LOGGER.info('Running in %s', os.getcwd())\n    CTX.repo = epab.utils.Repo()\n    CTX.repo.ensure()\n    CTX.stash = stash\n    for filename in _GIT_IGNORE:\n        epab.utils.add_to_gitignore(filename)\n    if not dirty and CTX.repo.is_dirty():\n        LOGGER.error('Repository is dirty')\n        sys.exit(-1)",
    "docstring": "This is a tool that handles all the tasks to build a Python application\n\n    This tool is installed as a setuptools entry point, which means it should be accessible from your terminal once\n    this application is installed in develop mode."
  },
  {
    "code": "def bake(self):\n        self.unbake()\n        for key in self.dct:\n            self.get_absolute_time(key)\n        self.is_baked = True",
    "docstring": "Find absolute times for all keys.\n\n        Absolute time is stored in the KeyFrame dictionary as the variable\n        __abs_time__."
  },
  {
    "code": "def set_affiliation(self, mucjid, jid, affiliation, *, reason=None):\n        if mucjid is None or not mucjid.is_bare:\n            raise ValueError(\"mucjid must be bare JID\")\n        if jid is None:\n            raise ValueError(\"jid must not be None\")\n        if affiliation is None:\n            raise ValueError(\"affiliation must not be None\")\n        iq = aioxmpp.stanza.IQ(\n            type_=aioxmpp.structs.IQType.SET,\n            to=mucjid\n        )\n        iq.payload = muc_xso.AdminQuery(\n            items=[\n                muc_xso.AdminItem(jid=jid,\n                                  reason=reason,\n                                  affiliation=affiliation)\n            ]\n        )\n        yield from self.client.send(iq)",
    "docstring": "Change the affiliation of an entity with a MUC.\n\n        :param mucjid: The bare JID identifying the MUC.\n        :type mucjid: :class:`~aioxmpp.JID`\n        :param jid: The bare JID of the entity whose affiliation shall be\n            changed.\n        :type jid: :class:`~aioxmpp.JID`\n        :param affiliation: The new affiliation for the entity.\n        :type affiliation: :class:`str`\n        :param reason: Optional reason for the affiliation change.\n        :type reason: :class:`str` or :data:`None`\n\n        Change the affiliation of the given `jid` with the MUC identified by\n        the bare `mucjid` to the given new `affiliation`. Optionally, a\n        `reason` can be given.\n\n        If you are joined in the MUC, :meth:`Room.muc_set_affiliation` may be\n        more convenient, but it is possible to modify the affiliations of a MUC\n        without being joined, given sufficient privilegues.\n\n        Setting the different affiliations require different privilegues of the\n        local user. The details can be checked in :xep:`0045` and are enforced\n        solely by the server, not local code.\n\n        The coroutine returns when the change in affiliation has been\n        acknowledged by the server. If the server returns an error, an\n        appropriate :class:`aioxmpp.errors.XMPPError` subclass is raised."
  },
  {
    "code": "def durations(self) -> List[datetime.timedelta]:\n        return [x.duration() for x in self.intervals]",
    "docstring": "Returns a list of ``datetime.timedelta`` objects representing the\n        durations of each interval in our list."
  },
  {
    "code": "def get_repeated_menu_item(\n        self, current_page, current_site, apply_active_classes,\n        original_menu_tag, request=None, use_absolute_page_urls=False,\n    ):\n        menuitem = copy(self)\n        menuitem.text = self.get_text_for_repeated_menu_item(\n            request, current_site, original_menu_tag\n        )\n        if use_absolute_page_urls:\n            url = self.get_full_url(request=request)\n        else:\n            url = self.relative_url(current_site)\n        menuitem.href = url\n        if apply_active_classes and self == current_page:\n            menuitem.active_class = settings.ACTIVE_CLASS\n        else:\n            menuitem.active_class = ''\n        menuitem.has_children_in_menu = False\n        menuitem.sub_menu = None\n        return menuitem",
    "docstring": "Return something that can be used to display a 'repeated' menu item\n        for this specific page."
  },
  {
    "code": "def can_delete_post(self, post, user):\n        checker = self._get_checker(user)\n        is_author = self._is_post_author(post, user)\n        can_delete = (\n            user.is_superuser or\n            (is_author and checker.has_perm('can_delete_own_posts', post.topic.forum)) or\n            checker.has_perm('can_delete_posts', post.topic.forum)\n        )\n        return can_delete",
    "docstring": "Given a forum post, checks whether the user can delete the latter."
  },
  {
    "code": "def payload(self):\n    try:\n      rdf_cls = self.classes.get(self.name)\n      if rdf_cls:\n        value = rdf_cls.FromSerializedString(self.data)\n        value.age = self.embedded_age\n        return value\n    except TypeError:\n      return None",
    "docstring": "Extracts and returns the serialized object."
  },
  {
    "code": "def make_posthook(self):\n        print(id(self.posthook), self.posthook)\n        print(id(super(self.__class__, self).posthook), super(self.__class__, self).posthook)\n        import ipdb;ipdb.set_trace()\n        if self.posthook:\n            os.chdir(self.project_name)\n            self.posthook()",
    "docstring": "Run the post hook into the project directory."
  },
  {
    "code": "def fill_A(A, right_eigenvectors):\n    num_micro, num_eigen = right_eigenvectors.shape\n    A = A.copy()\n    A[1:, 0] = -1 * A[1:, 1:].sum(1)\n    A[0] = -1 * dot(right_eigenvectors[:, 1:].real, A[1:]).min(0)\n    A /= A[0].sum()\n    return A",
    "docstring": "Construct feasible initial guess for transformation matrix A.\n\n\n    Parameters\n    ----------\n    A : ndarray\n        Possibly non-feasible transformation matrix.\n    right_eigenvectors :  ndarray\n        Right eigenvectors of transition matrix\n\n    Returns\n    -------\n    A : ndarray\n        Feasible transformation matrix."
  },
  {
    "code": "def maximize(self, reaction):\n        self._prob.set_objective(self.flux_expr(reaction))\n        self._solve()",
    "docstring": "Solve the model by maximizing the given reaction.\n\n        If reaction is a dictionary object, each entry is interpreted as a\n        weight on the objective for that reaction (non-existent reaction will\n        have zero weight)."
  },
  {
    "code": "def options(allow_partial=False, read=False):\n    global _options\n    if allow_partial:\n        opts, extras = _options_parser.parse_known_args()\n        if opts.run_dir:\n            mkdirp(opts.run_dir)\n        return opts\n    if _options is None:\n        _options_parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,\n                                     help='show this help message and exit')\n        _options = _options_parser.parse_args()\n        if _options.run_dir:\n            mkdirp(_options.run_dir, overwrite=_options.overwrite or read)\n        if not read:\n            options_dump = vars(_options)\n            del options_dump['overwrite']\n            del options_dump['config']\n            dump_pretty(options_dump, 'config.json')\n    return _options",
    "docstring": "Get the object containing the values of the parsed command line options.\n\n    :param bool allow_partial: If `True`, ignore unrecognized arguments and allow\n        the options to be re-parsed next time `options` is called. This\n        also suppresses overwrite checking (the check is performed the first\n        time `options` is called with `allow_partial=False`).\n    :param bool read: If `True`, do not create or overwrite a `config.json`\n        file, and do not check whether such file already exists. Use for scripts\n        that read from the run directory rather than/in addition to writing to it.\n\n    :return argparse.Namespace: An object storing the values of the options specified\n        to the parser returned by `get_options_parser()`."
  },
  {
    "code": "def _config_options(self):\n        self._config_sortable(self._sortable)\n        self._config_drag_cols(self._drag_cols)",
    "docstring": "Apply options set in attributes to Treeview"
  },
  {
    "code": "def get_template_by_name(name,**kwargs):\n    try:\n        tmpl_i = db.DBSession.query(Template).filter(Template.name == name).options(joinedload_all('templatetypes.typeattrs.default_dataset.metadata')).one()\n        return tmpl_i\n    except NoResultFound:\n        log.info(\"%s is not a valid identifier for a template\",name)\n        raise HydraError('Template \"%s\" not found'%name)",
    "docstring": "Get a specific resource template, by name."
  },
  {
    "code": "def bar_(self, label=None, style=None, opts=None, options={}):\n\t\ttry:\n\t\t\treturn self._get_chart(\"bar\", style=style, opts=opts, label=label,\n\t\t\t\t\t\t\t\t   options=options)\n\t\texcept Exception as e:\n\t\t\tself.err(e, self.bar_, \"Can not draw bar chart\")",
    "docstring": "Get a bar chart"
  },
  {
    "code": "def engage(self, height: float = None, offset: float = None):\n        if height:\n            dist = height\n        elif self.labware and self.labware.magdeck_engage_height is not None:\n            dist = self.labware.magdeck_engage_height\n            if offset:\n                dist += offset\n        else:\n            raise ValueError(\n                \"Currently loaded labware {} does not have a known engage \"\n                \"height; please specify explicitly with the height param\"\n                .format(self.labware))\n        self._module.engage(dist)",
    "docstring": "Raise the Magnetic Module's magnets.\n\n        The destination of the magnets can be specified in several different\n        ways, based on internally stored default heights for labware:\n\n           - If neither `height` nor `offset` is specified, the magnets will\n             raise to a reasonable default height based on the specified\n             labware.\n           - If `height` is specified, it should be a distance in mm from the\n             home position of the magnets.\n           - If `offset` is specified, it should be an offset in mm from the\n             default position. A positive number moves the magnets higher and\n             a negative number moves the magnets lower.\n\n        Only certain labwares have defined engage heights for the Magnetic\n        Module. If a labware that does not have a defined engage height is\n        loaded on the Magnetic Module (or if no labware is loaded), then\n        `height` must be specified.\n\n        :param height: The height to raise the magnets to, in mm from home.\n        :param offset: An offset relative to the default height for the labware\n                       in mm"
  },
  {
    "code": "def log_init(level):\n    log = logging.getLogger()\n    hdlr = logging.StreamHandler()\n    formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')\n    hdlr.setFormatter(formatter)\n    log.addHandler(hdlr)\n    log.setLevel(level)",
    "docstring": "Set up a logger that catches all channels and logs it to stdout.\n    \n    This is used to set up logging when testing."
  },
  {
    "code": "def _get_document_data(database, document):\n        try:\n            return document.get_data()\n        except xapian.DatabaseModifiedError:\n            database.reopen()\n            return document.get_data()",
    "docstring": "A safer version of Xapian.document.get_data\n\n        Simply wraps the Xapian version and catches any `Xapian.DatabaseModifiedError`,\n        attempting a `database.reopen` as needed.\n\n        Required arguments:\n            `database` -- The database to be read\n            `document` -- An instance of an Xapian.document object"
  },
  {
    "code": "def format_info(info_list):\n    max_lengths = []\n    if info_list:\n        nr_columns = len(info_list[0])\n    else:\n        nr_columns = 0\n    for i in range(nr_columns):\n        max_lengths.append(max([len(info[i]) for info in info_list]))\n    flattened_info_list = []\n    for info_id in range(len(info_list)):\n        info = info_list[info_id]\n        for str_id in range(len(info) - 1):\n            orig_str = info[str_id]\n            indent = max_lengths[str_id] - len(orig_str)\n            info[str_id] = orig_str + indent * b' '\n        flattened_info_list.append(b' '.join(info) + b'\\n')\n    return flattened_info_list",
    "docstring": "Turn a 2-dimension list of bytes into a 1-dimension list of bytes with\n    correct spacing"
  },
  {
    "code": "def _html_image(page):\n    source = _image(page)\n    if not source:\n        return\n    alt = page.data.get('label') or page.data.get('title')\n    img = \"<img src=\\\"%s\\\"\" % source\n    img += \" alt=\\\"%s\\\" title=\\\"%s\\\" \" % (alt, alt)\n    img += \"align=\\\"right\\\" width=\\\"240\\\">\"\n    return img",
    "docstring": "returns HTML img tag"
  },
  {
    "code": "def init(port=8813, numRetries=10, host=\"localhost\", label=\"default\"):\n    _connections[label] = connect(port, numRetries, host)\n    switch(label)\n    return getVersion()",
    "docstring": "Establish a connection to a TraCI-Server and store it under the given\n    label. This method is not thread-safe. It accesses the connection\n    pool concurrently."
  },
  {
    "code": "def _send(self, command):\n        command = command.encode('utf-8')\n        log.debug('>> ' + command)\n        self.conn.oqueue.put(command)",
    "docstring": "Sends a raw line to the server.\n\n        :param command: line to send.\n        :type command: unicode"
  },
  {
    "code": "def _ReadEventDataIntoEvent(self, event):\n    if self._storage_type != definitions.STORAGE_TYPE_SESSION:\n      return\n    event_data_identifier = event.GetEventDataIdentifier()\n    if event_data_identifier:\n      lookup_key = event_data_identifier.CopyToString()\n      event_data = self._event_data[lookup_key]\n      for attribute_name, attribute_value in event_data.GetAttributes():\n        setattr(event, attribute_name, attribute_value)",
    "docstring": "Reads the data into the event.\n\n    This function is intended to offer backwards compatible event behavior.\n\n    Args:\n      event (EventObject): event."
  },
  {
    "code": "def get_results(self) -> Iterable[PluginScanResult]:\n        for _ in range(self._get_current_processes_nb()):\n            self._task_queue.put(None)\n        for hostname, hostname_queue in self._hostname_queues_dict.items():\n            for i in range(len(self._processes_dict[hostname])):\n                hostname_queue.put(None)\n        received_task_results = 0\n        expected_task_results = self._queued_tasks_nb + self._get_current_processes_nb()\n        while received_task_results != expected_task_results:\n            result = self._result_queue.get()\n            self._result_queue.task_done()\n            received_task_results += 1\n            if result is None:\n                pass\n            else:\n                yield result\n        self._task_queue.join()\n        self._result_queue.join()\n        for hostname_queue in self._hostname_queues_dict.values():\n            hostname_queue.join()\n        for process_list in self._processes_dict.values():\n            for process in process_list:\n                process.join()",
    "docstring": "Return the result of previously queued scan commands; new commands cannot be queued once this is called.\n\n        Returns:\n            The results of all the scan commands previously queued. Each result will be an instance of the scan\n            corresponding command's PluginScanResult subclass. If there was an unexpected error while running the scan\n            command, it will be a 'PluginRaisedExceptionScanResult' instance instead."
  },
  {
    "code": "def chocolatey_version():\n    if 'chocolatey._version' in __context__:\n        return __context__['chocolatey._version']\n    cmd = [_find_chocolatey(__context__, __salt__)]\n    cmd.append('-v')\n    out = __salt__['cmd.run'](cmd, python_shell=False)\n    __context__['chocolatey._version'] = out\n    return __context__['chocolatey._version']",
    "docstring": "Returns the version of Chocolatey installed on the minion.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' chocolatey.chocolatey_version"
  },
  {
    "code": "def register_command(parent_command, name):\n    def wrapper(func):\n        c = command(name)(func)\n        parent_command.add_subcommand(c)\n    return wrapper",
    "docstring": "Create and register a command with a parent command.\n\n    Args\n    ----\n    parent_comand : Command\n        The parent command.\n    name : str\n        Name given to the created Command instance.\n\n    Example\n    -------\n    .. testcode::\n\n       mygit = Command(name='status')\n\n       @register_command(mygit, 'status')\n       def status():\n           print 'Nothing to commit.'\n\n    .. doctest::\n       :hide:\n\n       >>> mygit.init()\n       >>> mygit.parse_args(['status'])\n       Nothing to commit."
  },
  {
    "code": "def select_many_with_correspondence(\n            self,\n            collection_selector=identity,\n            result_selector=KeyedElement):\n        if self.closed():\n            raise ValueError(\"Attempt to call \"\n                \"select_many_with_correspondence() on a closed Queryable.\")\n        if not is_callable(collection_selector):\n            raise TypeError(\"select_many_with_correspondence() parameter \"\n             \"projector={0} is not callable\".format(repr(collection_selector)))\n        if not is_callable(result_selector):\n            raise TypeError(\"select_many_with_correspondence() parameter \"\n                \"selector={0} is not callable\".format(repr(result_selector)))\n        return self._create(\n            self._generate_select_many_with_correspondence(collection_selector,\n                                                           result_selector))",
    "docstring": "Projects each element of a sequence to an intermediate new sequence,\n        and flattens the resulting sequence, into one sequence and uses a\n        selector function to incorporate the corresponding source for each item\n        in the result sequence.\n\n        Note: This method uses deferred execution.\n\n        Args:\n            collection_selector: A unary function mapping each element of the\n                source iterable into an intermediate sequence. The single\n                argument of the collection_selector is the value of an element\n                from the source sequence. The return value should be an\n                iterable derived from that element value. The default\n                collection_selector, which is the identity function, assumes\n                that each element of the source sequence is itself iterable.\n\n            result_selector:\n                An optional binary function mapping the elements in the\n                flattened intermediate sequence together with their\n                corresponding source elements to elements of the result\n                sequence. The two positional arguments of the result_selector\n                are, first the source element corresponding to an element from\n                the intermediate sequence, and second the actual element from\n                the intermediate sequence. The return value should be the\n                corresponding value in the result sequence. If no\n                result_selector function is provided, the elements of the\n                result sequence are KeyedElement namedtuples.\n\n        Returns:\n            A Queryable over a generated sequence whose elements are the result\n            of applying the one-to-many collection_selector to each element of\n            the source sequence, concatenating the results into an intermediate\n            sequence, and then mapping each of those elements through the\n            result_selector which incorporates the corresponding source element\n            into the result sequence.\n\n        Raises:\n            ValueError: If this Queryable has been closed.\n            TypeError: If projector or selector are not callable."
  },
  {
    "code": "def _FindInFileEntry(self, file_entry, find_specs, search_depth):\n    sub_find_specs = []\n    for find_spec in find_specs:\n      match, location_match = find_spec.Matches(file_entry, search_depth)\n      if match:\n        yield file_entry.path_spec\n      if location_match != False and not find_spec.AtMaximumDepth(search_depth):\n        sub_find_specs.append(find_spec)\n    if not sub_find_specs:\n      return\n    search_depth += 1\n    try:\n      for sub_file_entry in file_entry.sub_file_entries:\n        for matching_path_spec in self._FindInFileEntry(\n            sub_file_entry, sub_find_specs, search_depth):\n          yield matching_path_spec\n    except errors.AccessError:\n      pass",
    "docstring": "Searches for matching file entries within the file entry.\n\n    Args:\n      file_entry (FileEntry): file entry.\n      find_specs (list[FindSpec]): find specifications.\n      search_depth (int): number of location path segments to compare.\n\n    Yields:\n      PathSpec: path specification of a matching file entry."
  },
  {
    "code": "def decrease_exponent_to(self, new_exp):\n        if new_exp > self.exponent:\n            raise ValueError('New exponent %i should be more negative than '\n                             'old exponent %i' % (new_exp, self.exponent))\n        multiplied = self * pow(EncodedNumber.BASE, self.exponent - new_exp)\n        multiplied.exponent = new_exp\n        return multiplied",
    "docstring": "Return an EncryptedNumber with same value but lower exponent.\n\n        If we multiply the encoded value by :attr:`EncodedNumber.BASE` and\n        decrement :attr:`exponent`, then the decoded value does not change.\n        Thus we can almost arbitrarily ratchet down the exponent of an\n        `EncryptedNumber` - we only run into trouble when the encoded\n        integer overflows. There may not be a warning if this happens.\n\n        When adding `EncryptedNumber` instances, their exponents must\n        match.\n\n        This method is also useful for hiding information about the\n        precision of numbers - e.g. a protocol can fix the exponent of\n        all transmitted `EncryptedNumber` instances to some lower bound(s).\n\n        Args:\n          new_exp (int): the desired exponent.\n\n        Returns:\n          EncryptedNumber: Instance with the same plaintext and desired\n            exponent.\n\n        Raises:\n          ValueError: You tried to increase the exponent."
  },
  {
    "code": "def _apply_filters(self):\n        filters = []\n        for f in self._filters:\n            filters.append('{}{}{}'.format(f['name'], f['operator'], f['value']))\n        self.tcex.log.debug(u'filters: {}'.format(filters))\n        if filters:\n            self._request.add_payload('filters', ','.join(filters))",
    "docstring": "Apply any filters added to the resource."
  },
  {
    "code": "def senqueue(trg_queue, item_s, *args, **kwargs):\n    return vsenqueue(trg_queue, item_s, args, **kwargs)",
    "docstring": "Enqueue a string, or string-like object to queue with arbitrary\n       arguments, senqueue is to enqueue what sprintf is to printf, senqueue\n       is to vsenqueue what sprintf is to vsprintf."
  },
  {
    "code": "def upload_all_books(book_id_start, book_id_end, rdf_library=None):\n    logger.info(\n        \"starting a gitberg mass upload: {0} -> {1}\".format(\n            book_id_start, book_id_end\n        )\n    )\n    for book_id in range(int(book_id_start), int(book_id_end) + 1):\n        cache = {}\n        errors = 0\n        try:\n            if int(book_id) in missing_pgid:\n                print(u'missing\\t{}'.format(book_id))\n                continue\n            upload_book(book_id, rdf_library=rdf_library, cache=cache)\n        except Exception as e:\n            print(u'error\\t{}'.format(book_id))\n            logger.error(u\"Error processing: {}\\r{}\".format(book_id, e))\n            errors += 1\n            if errors > 10:\n                print('error limit reached!')\n                break",
    "docstring": "Uses the fetch, make, push subcommands to\n        mirror Project Gutenberg to a github3 api"
  },
  {
    "code": "def add_request_type_view(request):\n    form = RequestTypeForm(request.POST or None)\n    if form.is_valid():\n        rtype = form.save()\n        messages.add_message(request, messages.SUCCESS,\n                             MESSAGES['REQUEST_TYPE_ADDED'].format(typeName=rtype.name))\n        return HttpResponseRedirect(reverse('managers:manage_request_types'))\n    return render_to_response('edit_request_type.html', {\n        'page_name': \"Admin - Add Request Type\",\n        'request_types': RequestType.objects.all(),\n        'form': form,\n        }, context_instance=RequestContext(request))",
    "docstring": "View to add a new request type.  Restricted to presidents and superadmins."
  },
  {
    "code": "def _get_project_types(self):\r\n        project_types = get_available_project_types()\r\n        projects = []\r\n        for project in project_types:\r\n            projects.append(project.PROJECT_TYPE_NAME)\r\n        return projects",
    "docstring": "Get all available project types."
  },
  {
    "code": "def delete_attachment(cls, session, attachment):\n        return super(Conversations, cls).delete(\n            session,\n            attachment,\n            endpoint_override='/attachments/%s.json' % attachment.id,\n            out_type=Attachment,\n        )",
    "docstring": "Delete an attachment.\n\n        Args:\n            session (requests.sessions.Session): Authenticated session.\n            attachment (helpscout.models.Attachment): The attachment to\n                be deleted.\n\n        Returns:\n            NoneType: Nothing."
  },
  {
    "code": "def _save_xls(self, filepath):\n        Interface = self.type2interface[\"xls\"]\n        workbook = xlwt.Workbook()\n        interface = Interface(self.grid.code_array, workbook)\n        interface.from_code_array()\n        try:\n            workbook.save(filepath)\n        except IOError, err:\n            try:\n                post_command_event(self.main_window, self.StatusBarMsg,\n                                   text=err)\n            except TypeError:\n                pass",
    "docstring": "Saves file as xls workbook\n\n        Parameters\n        ----------\n\n        filepath: String\n        \\tTarget file path for xls file"
  },
  {
    "code": "def _skip(self, cnt):\n        while cnt > 0:\n            if self._cur_avail == 0:\n                if not self._open_next():\n                    break\n            if cnt > self._cur_avail:\n                cnt -= self._cur_avail\n                self._remain -= self._cur_avail\n                self._cur_avail = 0\n            else:\n                self._fd.seek(cnt, 1)\n                self._cur_avail -= cnt\n                self._remain -= cnt\n                cnt = 0",
    "docstring": "RAR Seek, skipping through rar files to get to correct position"
  },
  {
    "code": "def update_default(self, new_default, respect_none=False):\n        if new_default is not None:\n            self.default = new_default\n        elif new_default is None and respect_none:\n            self.default = None",
    "docstring": "Update our current default with the new_default.\n\n        Args:\n            new_default: New default to set.\n            respect_none: Flag to determine if ``None`` is a valid value."
  },
  {
    "code": "def __get_default_settings(self):\n        LOGGER.debug(\"> Accessing '{0}' default settings file!\".format(UiConstants.settings_file))\n        self.__default_settings = QSettings(\n            umbra.ui.common.get_resource_path(UiConstants.settings_file), QSettings.IniFormat)",
    "docstring": "Gets the default settings."
  },
  {
    "code": "def parse_event_files_spec(logdir):\n  files = {}\n  if logdir is None:\n    return files\n  uri_pattern = re.compile('[a-zA-Z][0-9a-zA-Z.]*://.*')\n  for specification in logdir.split(','):\n    if (uri_pattern.match(specification) is None and ':' in specification and\n        specification[0] != '/' and not os.path.splitdrive(specification)[0]):\n      run_name, _, path = specification.partition(':')\n    else:\n      run_name = None\n      path = specification\n    if uri_pattern.match(path) is None:\n      path = os.path.realpath(os.path.expanduser(path))\n    files[path] = run_name\n  return files",
    "docstring": "Parses `logdir` into a map from paths to run group names.\n\n  The events files flag format is a comma-separated list of path specifications.\n  A path specification either looks like 'group_name:/path/to/directory' or\n  '/path/to/directory'; in the latter case, the group is unnamed. Group names\n  cannot start with a forward slash: /foo:bar/baz will be interpreted as a\n  spec with no name and path '/foo:bar/baz'.\n\n  Globs are not supported.\n\n  Args:\n    logdir: A comma-separated list of run specifications.\n  Returns:\n    A dict mapping directory paths to names like {'/path/to/directory': 'name'}.\n    Groups without an explicit name are named after their path. If logdir is\n    None, returns an empty dict, which is helpful for testing things that don't\n    require any valid runs."
  },
  {
    "code": "def submit_unseal_key(self, key=None, reset=False, migrate=False):\n        params = {\n            'migrate': migrate,\n        }\n        if not reset and key is not None:\n            params['key'] = key\n        elif reset:\n            params['reset'] = reset\n        api_path = '/v1/sys/unseal'\n        response = self._adapter.put(\n            url=api_path,\n            json=params,\n        )\n        return response.json()",
    "docstring": "Enter a single master key share to progress the unsealing of the Vault.\n\n        If the threshold number of master key shares is reached, Vault will attempt to unseal the Vault. Otherwise, this\n        API must be called multiple times until that threshold is met.\n\n        Either the key or reset parameter must be provided; if both are provided, reset takes precedence.\n\n        Supported methods:\n            PUT: /sys/unseal. Produces: 200 application/json\n\n        :param key: Specifies a single master key share. This is required unless reset is true.\n        :type key: str | unicode\n        :param reset: Specifies if previously-provided unseal keys are discarded and the unseal process is reset.\n        :type reset: bool\n        :param migrate: Available in 1.0 Beta - Used to migrate the seal from shamir to autoseal or autoseal to shamir.\n            Must be provided on all unseal key calls.\n        :type: migrate: bool\n        :return: The JSON response of the request.\n        :rtype: dict"
  },
  {
    "code": "def load_creds_file(self, path, profile=None):\n        config_cls = self.get_creds_reader()\n        return config_cls.load_config(self, path, profile=profile)",
    "docstring": "Load the credentials config file."
  },
  {
    "code": "def get_instance(self, payload):\n        return AvailableAddOnExtensionInstance(\n            self._version,\n            payload,\n            available_add_on_sid=self._solution['available_add_on_sid'],\n        )",
    "docstring": "Build an instance of AvailableAddOnExtensionInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance\n        :rtype: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionInstance"
  },
  {
    "code": "def get_capture_handler_config_by_name(self, name):\n        handler_confs = []\n        for address, stream_capturer in self._stream_capturers.iteritems():\n            handler_data = stream_capturer[0].dump_handler_config_data()\n            for h in handler_data:\n                if h['handler']['name'] == name:\n                    handler_confs.append(h)\n        return handler_confs",
    "docstring": "Return data for handlers of a given name.\n\n        Args:\n            name:\n                Name of the capture handler(s) to return config data for.\n\n        Returns:\n            Dictionary dump from the named capture handler as given by\n            the :func:`SocketStreamCapturer.dump_handler_config_data` method."
  },
  {
    "code": "def process(self):\n        children = len(self.living_children)\n        LOGGER.debug('%i active child%s',\n                     children, '' if children == 1 else 'ren')",
    "docstring": "Check up on child processes and make sure everything is running as\n        it should be."
  },
  {
    "code": "def count(self, objectType, *args, **coolArgs) :\n\t\treturn self._makeLoadQuery(objectType, *args, **coolArgs).count()",
    "docstring": "Returns the number of elements satisfying the query"
  },
  {
    "code": "def start(name, call=None):\n    if call != 'action':\n        raise SaltCloudException(\n            'The start action must be called with -a or --action.'\n        )\n    node_id = get_linode_id_from_name(name)\n    node = get_linode(kwargs={'linode_id': node_id})\n    if node['STATUS'] == 1:\n        return {'success': True,\n                'action': 'start',\n                'state': 'Running',\n                'msg': 'Machine already running'}\n    response = _query('linode', 'boot', args={'LinodeID': node_id})['DATA']\n    if _wait_for_job(node_id, response['JobID']):\n        return {'state': 'Running',\n                'action': 'start',\n                'success': True}\n    else:\n        return {'action': 'start',\n                'success': False}",
    "docstring": "Start a VM in Linode.\n\n    name\n        The name of the VM to start.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -a stop vm_name"
  },
  {
    "code": "def apply(self, doc):\n        if not isinstance(doc, Document):\n            raise TypeError(\n                \"Input Contexts to MentionFigures.apply() must be of type Document\"\n            )\n        for figure in doc.figures:\n            if self.types is None or any(\n                figure.url.lower().endswith(type) for type in self.types\n            ):\n                yield TemporaryFigureMention(figure)",
    "docstring": "Generate MentionFigures from a Document by parsing all of its Figures.\n\n        :param doc: The ``Document`` to parse.\n        :type doc: ``Document``\n        :raises TypeError: If the input doc is not of type ``Document``."
  },
  {
    "code": "def distinct(expr, on=None, *ons):\n    on = on or list()\n    if not isinstance(on, list):\n        on = [on, ]\n    on = on + list(ons)\n    on = [it(expr) if inspect.isfunction(it) else it for it in on]\n    return DistinctCollectionExpr(expr, _unique_fields=on, _all=(len(on) == 0))",
    "docstring": "Get collection with duplicate rows removed, optionally only considering certain columns\n\n    :param expr: collection\n    :param on: sequence or sequences\n    :return: dinstinct collection\n\n    :Example:\n\n    >>> df.distinct(['name', 'id'])\n    >>> df['name', 'id'].distinct()"
  },
  {
    "code": "def get_email_subject(email, default):\n  s = get_settings(string=\"OVP_EMAILS\")\n  email_settings = s.get(email, {})\n  title = email_settings.get(\"subject\", default)\n  return _(title)",
    "docstring": "Allows for email subject overriding from settings.py"
  },
  {
    "code": "def _parse_line(line):\n    line, timestamp = line.rsplit(\",\", 1)\n    line, command = line.rsplit(\",\", 1)\n    path, username = line.rsplit(\",\", 1)\n    return {\n        \"timestamp\": timestamp.strip(),\n        \"command\": command.strip(),\n        \"username\": username.strip(),\n        \"path\": path,\n    }",
    "docstring": "Convert one line from the extended log to dict.\n\n    Args:\n        line (str): Line which will be converted.\n\n    Returns:\n        dict: dict with ``timestamp``, ``command``, ``username`` and ``path`` \\\n              keys.\n\n    Note:\n        Typical line looks like this::\n\n            /home/ftp/xex/asd bsd.dat, xex, STOR, 1398351777\n\n        Filename may contain ``,`` character, so I am ``rsplitting`` the line\n        from the end to the beginning."
  },
  {
    "code": "def find_actions(namespace, action_prefix):\n    actions = {}\n    for key, value in iteritems(namespace):\n        if key.startswith(action_prefix):\n            actions[key[len(action_prefix):]] = analyse_action(value)\n    return actions",
    "docstring": "Find all the actions in the namespace."
  },
  {
    "code": "def run(self):\n        try:\n            while True:\n                input_chunks = [input.get() for input in self.input_queues]\n                for input in self.input_queues:\n                    input.task_done()\n                if any(chunk is QUEUE_ABORT for chunk in input_chunks):\n                    self.abort()\n                    return\n                if any(chunk is QUEUE_FINISHED for chunk in input_chunks):\n                    break\n                self.output(self.process_chunks(input_chunks))\n            self.output(self.finalise())\n        except:\n            self.abort()\n            raise\n        else:\n            for queue in self.output_queues:\n                queue.put(QUEUE_FINISHED)",
    "docstring": "Process the input queues in lock-step, and push any results to\n        the registered output queues."
  },
  {
    "code": "def owner(path):\n    stat = os.stat(path)\n    username = pwd.getpwuid(stat.st_uid)[0]\n    groupname = grp.getgrgid(stat.st_gid)[0]\n    return username, groupname",
    "docstring": "Returns a tuple containing the username & groupname owning the path.\n\n    :param str path: the string path to retrieve the ownership\n    :return tuple(str, str): A (username, groupname) tuple containing the\n                             name of the user and group owning the path.\n    :raises OSError: if the specified path does not exist"
  },
  {
    "code": "def timed_cache(**timed_cache_kwargs):\n    def _wrapper(f):\n        maxsize = timed_cache_kwargs.pop('maxsize', 128)\n        typed = timed_cache_kwargs.pop('typed', False)\n        update_delta = timedelta(**timed_cache_kwargs)\n        d = {'next_update': datetime.utcnow() - update_delta}\n        try:\n            f = functools.lru_cache(maxsize=maxsize, typed=typed)(f)\n        except AttributeError:\n            print(\n                \"LRU caching is not available in Pyton 2.7, \"\n                \"this will have no effect!\"\n            )\n            pass\n        @functools.wraps(f)\n        def _wrapped(*args, **kwargs):\n            now = datetime.utcnow()\n            if now >= d['next_update']:\n                try:\n                    f.cache_clear()\n                except AttributeError:\n                    pass\n                d['next_update'] = now + update_delta\n            return f(*args, **kwargs)\n        return _wrapped\n    return _wrapper",
    "docstring": "LRU cache decorator with timeout.\n\n    Parameters\n    ----------\n    days: int\n    seconds: int\n    microseconds: int\n    milliseconds: int\n    minutes: int\n    hours: int\n    weeks: int\n    maxsise: int [default: 128]\n    typed: bool [default: False]"
  },
  {
    "code": "def sorted_migrations(self):\n        if not self._sorted_migrations:\n            self._sorted_migrations = sorted(\n                self.migration_registry.items(),\n                key=lambda migration_tuple: migration_tuple[0])\n        return self._sorted_migrations",
    "docstring": "Sort migrations if necessary and store in self._sorted_migrations"
  },
  {
    "code": "def add_inverse_distances(self, indices, periodic=True, indices2=None):\n        from .distances import InverseDistanceFeature\n        atom_pairs = _parse_pairwise_input(\n            indices, indices2, self.logger, fname='add_inverse_distances()')\n        atom_pairs = self._check_indices(atom_pairs)\n        f = InverseDistanceFeature(self.topology, atom_pairs, periodic=periodic)\n        self.__add_feature(f)",
    "docstring": "Adds the inverse distances between atoms to the feature list.\n\n        Parameters\n        ----------\n        indices : can be of two types:\n\n                ndarray((n, 2), dtype=int):\n                    n x 2 array with the pairs of atoms between which the inverse distances shall be computed\n\n                iterable of integers (either list or ndarray(n, dtype=int)):\n                    indices (not pairs of indices) of the atoms between which the inverse distances shall be computed.\n\n        periodic : optional, boolean, default is True\n            If periodic is True and the trajectory contains unitcell information,\n            distances will be computed under the minimum image convention.\n\n        indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:\n                    Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,\n                    only the inverse distances between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.\n\n\n        .. note::\n            When using the *iterable of integers* input, :py:obj:`indices` and :py:obj:`indices2`\n            will be sorted numerically and made unique before converting them to a pairlist.\n            Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added."
  },
  {
    "code": "def wr_long(f, x):\n    if PYTHON3:\n        f.write(bytes([x        & 0xff]))\n        f.write(bytes([(x >> 8)  & 0xff]))\n        f.write(bytes([(x >> 16) & 0xff]))\n        f.write(bytes([(x >> 24) & 0xff]))\n    else:\n        f.write(chr( x        & 0xff))\n        f.write(chr((x >> 8)  & 0xff))\n        f.write(chr((x >> 16) & 0xff))\n        f.write(chr((x >> 24) & 0xff))",
    "docstring": "Internal; write a 32-bit int to a file in little-endian order."
  },
  {
    "code": "def html_header():\n    file_path = resources_path('header.html')\n    with codecs.open(file_path, 'r', encoding='utf8') as header_file:\n        content = header_file.read()\n        content = content.replace('PATH', resources_path())\n    return content",
    "docstring": "Get a standard html header for wrapping content in.\n\n    :returns: A header containing a web page preamble in html - up to and\n        including the body open tag.\n    :rtype: str"
  },
  {
    "code": "def my_func(version):\n    class MyClass(object):\n        if version == 2:\n            import docs.support.python2_module as pm\n        else:\n            import docs.support.python3_module as pm\n        def __init__(self, value):\n            self._value = value\n        def _get_value(self):\n            return self._value\n        value = property(_get_value, pm._set_value, None, \"Value property\")",
    "docstring": "Enclosing function."
  },
  {
    "code": "def _getFirmwareVersion(self, device):\n        cmd = self._COMMAND.get('get-fw-version')\n        self._writeData(cmd, device)\n        try:\n            result = self._serial.read(size=1)\n            result = int(result)\n        except serial.SerialException as e:\n            self._log and self._log.error(\"Error: %s\", e, exc_info=True)\n            raise e\n        except ValueError as e:\n            result = None\n        return result",
    "docstring": "Get the firmware version.\n\n        :Parameters:\n          device : `int`\n            The device is the integer number of the hardware devices ID and\n            is only used with the Pololu Protocol.\n\n        :Returns:\n          An integer indicating the version number."
  },
  {
    "code": "def merge_report(self, otherself):\n        self.notices += otherself.notices\n        self.warnings += otherself.warnings\n        self.errors += otherself.errors",
    "docstring": "Merge another report into this one."
  },
  {
    "code": "def get_value(self):\n        def get_element_value():\n            if self.tag_name() == 'input':\n                return self.get_attribute('value')\n            elif self.tag_name() == 'select':\n                selected_options = self.element.all_selected_options\n                if len(selected_options) > 1:\n                    raise ValueError(\n                        'Select {} has multiple selected options, only one selected '\n                        'option is valid for this method'.format(self)\n                    )\n                return selected_options[0].get_attribute('value')\n            else:\n                raise ValueError('Can not get the value of elements or type \"{}\"'.format(self.tag_name()))\n        return self.execute_and_handle_webelement_exceptions(get_element_value, name_of_action='get value')",
    "docstring": "Gets the value of a select or input element\n\n        @rtype: str\n        @return: The value of the element\n        @raise: ValueError if element is not of type input or select, or has multiple selected options"
  },
  {
    "code": "def add(self, user, password):\n        if self.__contains__(user):\n            raise UserExists\n        self.new_users[user] = self._encrypt_password(password) + \"\\n\"",
    "docstring": "Adds a user with password"
  },
  {
    "code": "def apply_order(self):\n    self._ensure_modification_is_safe()\n    if len(self.query.orders) > 0:\n      self._iterable = Order.sorted(self._iterable, self.query.orders)",
    "docstring": "Naively apply query orders."
  },
  {
    "code": "def correlation(left, right, where=None, how='sample'):\n    expr = ops.Correlation(left, right, how, where).to_expr()\n    return expr",
    "docstring": "Compute correlation of two numeric array\n\n    Parameters\n    ----------\n    how : {'sample', 'pop'}, default 'sample'\n\n    Returns\n    -------\n    corr : double scalar"
  },
  {
    "code": "def terminate(self):\n        logger.info('Sending SIGTERM to task {0}'.format(self.name))\n        if hasattr(self, 'remote_client') and self.remote_client is not None:\n            self.terminate_sent = True\n            self.remote_client.close()\n            return\n        if not self.process:\n            raise DagobahError('task does not have a running process')\n        self.terminate_sent = True\n        self.process.terminate()",
    "docstring": "Send SIGTERM to the task's process."
  },
  {
    "code": "def parentLayer(self):\n        if self._parentLayer is None:\n            from ..agol.services import FeatureService\n            self.__init()\n            url = os.path.dirname(self._url)\n            self._parentLayer = FeatureService(url=url,\n                                               securityHandler=self._securityHandler,\n                                               proxy_url=self._proxy_url,\n                                               proxy_port=self._proxy_port)\n        return self._parentLayer",
    "docstring": "returns information about the parent"
  },
  {
    "code": "def valid_at(self, valid_date):\n        is_valid = db.Q(validity__end__gt=valid_date,\n                        validity__start__lte=valid_date)\n        no_validity = db.Q(validity=None)\n        return self(is_valid | no_validity)",
    "docstring": "Limit current QuerySet to zone valid at a given date"
  },
  {
    "code": "def draw_timeline(self):\n        self.clear_timeline()\n        self.create_scroll_region()\n        self._timeline.config(width=self.pixel_width)\n        self._canvas_scroll.config(width=self._width, height=self._height)\n        self.draw_separators()\n        self.draw_markers()\n        self.draw_ticks()\n        self.draw_time_marker()",
    "docstring": "Draw the contents of the whole TimeLine Canvas"
  },
  {
    "code": "def set_password(cls, instance, raw_password):\n        hash_callable = getattr(\n            instance.passwordmanager, \"hash\", instance.passwordmanager.encrypt\n        )\n        password = hash_callable(raw_password)\n        if six.PY2:\n            instance.user_password = password.decode(\"utf8\")\n        else:\n            instance.user_password = password\n        cls.regenerate_security_code(instance)",
    "docstring": "sets new password on a user using password manager\n\n        :param instance:\n        :param raw_password:\n        :return:"
  },
  {
    "code": "def from_text_list(name, ttl, rdclass, rdtype, text_rdatas):\n    if isinstance(name, (str, unicode)):\n        name = dns.name.from_text(name, None)\n    if isinstance(rdclass, (str, unicode)):\n        rdclass = dns.rdataclass.from_text(rdclass)\n    if isinstance(rdtype, (str, unicode)):\n        rdtype = dns.rdatatype.from_text(rdtype)\n    r = RRset(name, rdclass, rdtype)\n    r.update_ttl(ttl)\n    for t in text_rdatas:\n        rd = dns.rdata.from_text(r.rdclass, r.rdtype, t)\n        r.add(rd)\n    return r",
    "docstring": "Create an RRset with the specified name, TTL, class, and type, and with\n    the specified list of rdatas in text format.\n\n    @rtype: dns.rrset.RRset object"
  },
  {
    "code": "def _parse_reset(self, ref):\n        from_ = self._get_from()\n        return commands.ResetCommand(ref, from_)",
    "docstring": "Parse a reset command."
  },
  {
    "code": "def cmd_status_codes_counter(self):\n        status_codes = defaultdict(int)\n        for line in self._valid_lines:\n            status_codes[line.status_code] += 1\n        return status_codes",
    "docstring": "Generate statistics about HTTP status codes. 404, 500 and so on."
  },
  {
    "code": "def setReturnParameter(self, name, type, namespace=None, element_type=0):\n        parameter = ParameterInfo(name, type, namespace, element_type)\n        self.retval = parameter\n        return parameter",
    "docstring": "Set the return parameter description for the call info."
  },
  {
    "code": "def get_filter_list(p_expression):\n    result = []\n    for arg in p_expression:\n        is_negated = len(arg) > 1 and arg[0] == '-'\n        arg = arg[1:] if is_negated else arg\n        argfilter = None\n        for match, _filter in MATCHES:\n            if re.match(match, arg):\n                argfilter = _filter(arg)\n                break\n        if not argfilter:\n            argfilter = GrepFilter(arg)\n        if is_negated:\n            argfilter = NegationFilter(argfilter)\n        result.append(argfilter)\n    return result",
    "docstring": "Returns a list of GrepFilters, OrdinalTagFilters or NegationFilters based\n    on the given filter expression.\n\n    The filter expression is a list of strings."
  },
  {
    "code": "def clear(self):\n        for n in self.nodes():\n            if self.nodes[n][\"type\"] == \"variable\":\n                self.nodes[n][\"value\"] = None\n            elif self.nodes[n][\"type\"] == \"function\":\n                self.nodes[n][\"func_visited\"] = False",
    "docstring": "Clear variable nodes for next computation."
  },
  {
    "code": "def _ExtractMetadataFromFileEntry(self, mediator, file_entry, data_stream):\n    if file_entry.IsRoot() and file_entry.type_indicator not in (\n        self._TYPES_WITH_ROOT_METADATA):\n      return\n    if data_stream and not data_stream.IsDefault():\n      return\n    display_name = mediator.GetDisplayName()\n    logger.debug(\n        '[ExtractMetadataFromFileEntry] processing file entry: {0:s}'.format(\n            display_name))\n    self.processing_status = definitions.STATUS_INDICATOR_EXTRACTING\n    if self._processing_profiler:\n      self._processing_profiler.StartTiming('extracting')\n    self._event_extractor.ParseFileEntryMetadata(mediator, file_entry)\n    if self._processing_profiler:\n      self._processing_profiler.StopTiming('extracting')\n    self.processing_status = definitions.STATUS_INDICATOR_RUNNING",
    "docstring": "Extracts metadata from a file entry.\n\n    Args:\n      mediator (ParserMediator): mediates the interactions between\n          parsers and other components, such as storage and abort signals.\n      file_entry (dfvfs.FileEntry): file entry to extract metadata from.\n      data_stream (dfvfs.DataStream): data stream or None if the file entry\n          has no data stream."
  },
  {
    "code": "def _prepare_persistence_engine(self):\n        if self._persistence_engine:\n            return\n        persistence_engine = self._options.get('persistence_engine')\n        if persistence_engine:\n            self._persistence_engine = path_to_reference(persistence_engine)\n            return\n        from furious.config import get_default_persistence_engine\n        self._persistence_engine = get_default_persistence_engine()",
    "docstring": "Load the specified persistence engine, or the default if none is\n        set."
  },
  {
    "code": "def sizeof(self, fields):\n        if type(fields) in [tuple, list]:\n            str = ','.join(fields)\n        else:\n            str = fields\n        n = _C.VSsizeof(self._id, str)\n        _checkErr('sizeof', n, \"cannot retrieve field sizes\")\n        return n",
    "docstring": "Retrieve the size in bytes of the given fields.\n\n        Args::\n\n          fields   sequence of field names to query\n\n        Returns::\n\n          total size of the fields in bytes\n\n        C library equivalent : VSsizeof"
  },
  {
    "code": "def height(self):\n        if self.__children_:\n            return max([child.height for child in self.__children_]) + 1\n        else:\n            return 0",
    "docstring": "Number of edges on the longest path to a leaf `Node`.\n\n        >>> from anytree import Node\n        >>> udo = Node(\"Udo\")\n        >>> marc = Node(\"Marc\", parent=udo)\n        >>> lian = Node(\"Lian\", parent=marc)\n        >>> udo.height\n        2\n        >>> marc.height\n        1\n        >>> lian.height\n        0"
  },
  {
    "code": "def _get_svc_list(service_status):\n    prefix = '/etc/rc.d/'\n    ret = set()\n    lines = glob.glob('{0}*'.format(prefix))\n    for line in lines:\n        svc = _get_svc(line, service_status)\n        if svc is not None:\n            ret.add(svc)\n    return sorted(ret)",
    "docstring": "Returns all service statuses"
  },
  {
    "code": "def _strip_trailing_zeros(value):\n        return list(\n           reversed(\n              list(itertools.dropwhile(lambda x: x == 0, reversed(value)))\n           )\n        )",
    "docstring": "Strip trailing zeros from a list of ints.\n\n        :param value: the value to be stripped\n        :type value: list of str\n\n        :returns: list with trailing zeros stripped\n        :rtype: list of int"
  },
  {
    "code": "def asDictionary(self):\n        feat_dict = {}\n        if self._geom is not None:\n            if 'feature' in self._dict:\n                feat_dict['geometry'] = self._dict['feature']['geometry']\n            elif 'geometry' in self._dict:\n                feat_dict['geometry'] =  self._dict['geometry']\n        if 'feature' in self._dict:\n            feat_dict['attributes'] = self._dict['feature']['attributes']\n        else:\n            feat_dict['attributes'] = self._dict['attributes']\n        return self._dict",
    "docstring": "returns the feature as a dictionary"
  },
  {
    "code": "def stop_led_flash(self):\n        if self._led_flashing:\n            self._led_flash = (0, 0)\n            self._led_flashing = False\n            self._control()\n            self._control()",
    "docstring": "Stops flashing the LED."
  },
  {
    "code": "def get_module_constant(module, symbol, default=-1, paths=None):\n    try:\n        f, path, (suffix, mode, kind) = find_module(module, paths)\n    except ImportError:\n        return None\n    try:\n        if kind == PY_COMPILED:\n            f.read(8)\n            code = marshal.load(f)\n        elif kind == PY_FROZEN:\n            code = imp.get_frozen_object(module)\n        elif kind == PY_SOURCE:\n            code = compile(f.read(), path, 'exec')\n        else:\n            if module not in sys.modules:\n                imp.load_module(module, f, path, (suffix, mode, kind))\n            return getattr(sys.modules[module], symbol, None)\n    finally:\n        if f:\n            f.close()\n    return extract_constant(code, symbol, default)",
    "docstring": "Find 'module' by searching 'paths', and extract 'symbol'\n\n    Return 'None' if 'module' does not exist on 'paths', or it does not define\n    'symbol'.  If the module defines 'symbol' as a constant, return the\n    constant.  Otherwise, return 'default'."
  },
  {
    "code": "def verse_lookup(self, book_name, book_chapter, verse, cache_chapter = True):\n        verses_list = self.get_chapter(\n            book_name,\n            str(book_chapter),\n            cache_chapter = cache_chapter)\n        return verses_list[int(verse) - 1]",
    "docstring": "Looks up a verse from online.recoveryversion.bible, then returns it."
  },
  {
    "code": "def Entry(self, name, directory=None, create=1):\n        return self._create_node(name, self.env.fs.Entry, directory, create)",
    "docstring": "Create `SCons.Node.FS.Entry`"
  },
  {
    "code": "def remove_yaml_frontmatter(source, return_frontmatter=False):\n    if source.startswith(\"---\\n\"):\n        frontmatter_end = source.find(\"\\n---\\n\", 4)\n        if frontmatter_end == -1:\n            frontmatter = source\n            source = \"\"\n        else:\n            frontmatter = source[0:frontmatter_end]\n            source = source[frontmatter_end + 5:]\n        if return_frontmatter:\n            return (source, frontmatter)\n        return source\n    if return_frontmatter:\n        return (source, None)\n    return source",
    "docstring": "If there's one, remove the YAML front-matter from the source"
  },
  {
    "code": "def create_delete_model(record):\n    data = cloudwatch.get_historical_base_info(record)\n    group_id = cloudwatch.filter_request_parameters('groupId', record)\n    arn = get_arn(group_id, cloudwatch.get_region(record), record['account'])\n    LOG.debug(f'[-] Deleting Dynamodb Records. Hash Key: {arn}')\n    data.update({'configuration': {}})\n    items = list(CurrentSecurityGroupModel.query(arn, limit=1))\n    if items:\n        model_dict = items[0].__dict__['attribute_values'].copy()\n        model_dict.update(data)\n        model = CurrentSecurityGroupModel(**model_dict)\n        model.save()\n        return model\n    return None",
    "docstring": "Create a security group model from a record."
  },
  {
    "code": "def serialize_non_framed_open(algorithm, iv, plaintext_length, signer=None):\n    body_start_format = (\">\" \"{iv_length}s\" \"Q\").format(iv_length=algorithm.iv_len)\n    body_start = struct.pack(body_start_format, iv, plaintext_length)\n    if signer:\n        signer.update(body_start)\n    return body_start",
    "docstring": "Serializes the opening block for a non-framed message body.\n\n    :param algorithm: Algorithm to use for encryption\n    :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n    :param bytes iv: IV value used to encrypt body\n    :param int plaintext_length: Length of plaintext (and thus ciphertext) in body\n    :param signer: Cryptographic signer object (optional)\n    :type signer: aws_encryption_sdk.internal.crypto.Signer\n    :returns: Serialized body start block\n    :rtype: bytes"
  },
  {
    "code": "def process_result(self, new_sia, min_sia):\n        if new_sia.phi == 0:\n            self.done = True\n            return new_sia\n        elif new_sia < min_sia:\n            return new_sia\n        return min_sia",
    "docstring": "Check if the new SIA has smaller |big_phi| than the standing\n        result."
  },
  {
    "code": "def get_raster_array(image):\n    if isinstance(image, RGB):\n        rgb = image.rgb\n        data = np.dstack([np.flipud(rgb.dimension_values(d, flat=False))\n                          for d in rgb.vdims])\n    else:\n        data = image.dimension_values(2, flat=False)\n        if type(image) is Raster:\n            data = data.T\n        else:\n            data = np.flipud(data)\n    return data",
    "docstring": "Return the array data from any Raster or Image type"
  },
  {
    "code": "def to_outgoing_transaction(self, using, created=None, deleted=None):\n        OutgoingTransaction = django_apps.get_model(\n            \"django_collect_offline\", \"OutgoingTransaction\"\n        )\n        created = True if created is None else created\n        action = INSERT if created else UPDATE\n        timestamp_datetime = (\n            self.instance.created if created else self.instance.modified\n        )\n        if not timestamp_datetime:\n            timestamp_datetime = get_utcnow()\n        if deleted:\n            timestamp_datetime = get_utcnow()\n            action = DELETE\n        outgoing_transaction = None\n        if self.is_serialized:\n            hostname = socket.gethostname()\n            outgoing_transaction = OutgoingTransaction.objects.using(using).create(\n                tx_name=self.instance._meta.label_lower,\n                tx_pk=getattr(self.instance, self.primary_key_field.name),\n                tx=self.encrypted_json(),\n                timestamp=timestamp_datetime.strftime(\"%Y%m%d%H%M%S%f\"),\n                producer=f\"{hostname}-{using}\",\n                action=action,\n                using=using,\n            )\n        return outgoing_transaction",
    "docstring": "Serialize the model instance to an AES encrypted json object\n        and saves the json object to the OutgoingTransaction model."
  },
  {
    "code": "def dataset_metrics(uuid, **kwargs):\n\tdef getdata(x, **kwargs):\n\t\turl = gbif_baseurl + 'dataset/' + x + '/metrics'\n\t\treturn gbif_GET(url, {}, **kwargs)\n\tif len2(uuid) == 1:\n\t\treturn getdata(uuid)\n\telse:\n\t\treturn [getdata(x) for x in uuid]",
    "docstring": "Get details on a GBIF dataset.\n\n\t:param uuid: [str] One or more dataset UUIDs. See examples.\n\n\tReferences: http://www.gbif.org/developer/registry#datasetMetrics\n\n\tUsage::\n\n\t\t\tfrom pygbif import registry\n\t\t\tregistry.dataset_metrics(uuid='3f8a1297-3259-4700-91fc-acc4170b27ce')\n\t\t\tregistry.dataset_metrics(uuid='66dd0960-2d7d-46ee-a491-87b9adcfe7b1')\n\t\t\tregistry.dataset_metrics(uuid=['3f8a1297-3259-4700-91fc-acc4170b27ce', '66dd0960-2d7d-46ee-a491-87b9adcfe7b1'])"
  },
  {
    "code": "def boto_client(self, service, *args, **kwargs):\n        return self.boto_session.client(service, *args, **self.configure_boto_session_method_kwargs(service, kwargs))",
    "docstring": "A wrapper to apply configuration options to boto clients"
  },
  {
    "code": "def get_inputs_from_cm(index, cm):\n    return tuple(i for i in range(cm.shape[0]) if cm[i][index])",
    "docstring": "Return indices of inputs to the node with the given index."
  },
  {
    "code": "def configure_create(self, ns, definition):\n        @self.add_route(ns.collection_path, Operation.Create, ns)\n        @request(definition.request_schema)\n        @response(definition.response_schema)\n        @wraps(definition.func)\n        def create(**path_data):\n            request_data = load_request_data(definition.request_schema)\n            response_data = definition.func(**merge_data(path_data, request_data))\n            headers = encode_id_header(response_data)\n            definition.header_func(headers, response_data)\n            response_format = self.negotiate_response_content(definition.response_formats)\n            return dump_response_data(\n                definition.response_schema,\n                response_data,\n                status_code=Operation.Create.value.default_code,\n                headers=headers,\n                response_format=response_format,\n            )\n        create.__doc__ = \"Create a new {}\".format(ns.subject_name)",
    "docstring": "Register a create endpoint.\n\n        The definition's func should be a create function, which must:\n        - accept kwargs for the request and path data\n        - return a new item\n\n        :param ns: the namespace\n        :param definition: the endpoint definition"
  },
  {
    "code": "def reactive_power_mode(self):\n        if self._reactive_power_mode is None:\n            if isinstance(self.grid, MVGrid):\n                self._reactive_power_mode = self.grid.network.config[\n                    'reactive_power_mode']['mv_load']\n            elif isinstance(self.grid, LVGrid):\n                self._reactive_power_mode = self.grid.network.config[\n                    'reactive_power_mode']['lv_load']\n        return self._reactive_power_mode",
    "docstring": "Power factor mode of Load.\n\n        This information is necessary to make the load behave in an inductive\n        or capacitive manner. Essentially this changes the sign of the reactive\n        power.\n\n        The convention used here in a load is that:\n        - when `reactive_power_mode` is 'inductive' then Q is positive\n        - when `reactive_power_mode` is 'capacitive' then Q is negative\n\n        Parameters\n        ----------\n        reactive_power_mode : :obj:`str` or None\n            Possible options are 'inductive', 'capacitive' and\n            'not_applicable'. In the case of 'not_applicable' a reactive\n            power time series must be given.\n\n        Returns\n        -------\n        :obj:`str`\n            In the case that this attribute is not set, it is retrieved from\n            the network config object depending on the voltage level the load\n            is in."
  },
  {
    "code": "def get_ip_prefixes_from_bird(filename):\n    prefixes = []\n    with open(filename, 'r') as bird_conf:\n        lines = bird_conf.read()\n    for line in lines.splitlines():\n        line = line.strip(', ')\n        if valid_ip_prefix(line):\n            prefixes.append(line)\n    return prefixes",
    "docstring": "Build a list of IP prefixes found in Bird configuration.\n\n    Arguments:\n        filename (str): The absolute path of the Bird configuration file.\n\n    Notes:\n        It can only parse a file with the following format\n\n            define ACAST_PS_ADVERTISE =\n                [\n                    10.189.200.155/32,\n                    10.189.200.255/32\n                ];\n\n    Returns:\n        A list of IP prefixes."
  },
  {
    "code": "def extract_surface(self, pass_pointid=True, pass_cellid=True, inplace=False):\n        surf_filter = vtk.vtkDataSetSurfaceFilter()\n        surf_filter.SetInputData(self)\n        if pass_pointid:\n            surf_filter.PassThroughCellIdsOn()\n        if pass_cellid:\n            surf_filter.PassThroughPointIdsOn()\n        surf_filter.Update()\n        mesh = _get_output(surf_filter)\n        if inplace:\n            self.overwrite(mesh)\n        else:\n            return mesh",
    "docstring": "Extract surface mesh of the grid\n\n        Parameters\n        ----------\n        pass_pointid : bool, optional\n            Adds a point scalar \"vtkOriginalPointIds\" that idenfities which\n            original points these surface points correspond to\n\n        pass_cellid : bool, optional\n            Adds a cell scalar \"vtkOriginalPointIds\" that idenfities which\n            original cells these surface cells correspond to\n\n        inplace : bool, optional\n            Return new mesh or overwrite input.\n\n        Returns\n        -------\n        extsurf : vtki.PolyData\n            Surface mesh of the grid"
  },
  {
    "code": "def areaBetween(requestContext, *seriesLists):\n    if len(seriesLists) == 1:\n        [seriesLists] = seriesLists\n    assert len(seriesLists) == 2, (\"areaBetween series argument must \"\n                                   \"reference *exactly* 2 series\")\n    lower, upper = seriesLists\n    if len(lower) == 1:\n        [lower] = lower\n    if len(upper) == 1:\n        [upper] = upper\n    lower.options['stacked'] = True\n    lower.options['invisible'] = True\n    upper.options['stacked'] = True\n    lower.name = upper.name = \"areaBetween(%s)\" % upper.pathExpression\n    return [lower, upper]",
    "docstring": "Draws the vertical area in between the two series in seriesList. Useful for\n    visualizing a range such as the minimum and maximum latency for a service.\n\n    areaBetween expects **exactly one argument** that results in exactly two\n    series (see example below). The order of the lower and higher values\n    series does not matter. The visualization only works when used in\n    conjunction with ``areaMode=stacked``.\n\n    Most likely use case is to provide a band within which another metric\n    should move. In such case applying an ``alpha()``, as in the second\n    example, gives best visual results.\n\n    Example::\n\n      &target=areaBetween(service.latency.{min,max})&areaMode=stacked\n\n      &target=alpha(areaBetween(service.latency.{min,max}),0.3)&areaMode=stacked\n\n    If for instance, you need to build a seriesList, you should use the\n    ``group`` function, like so::\n\n      &target=areaBetween(group(minSeries(a.*.min),maxSeries(a.*.max)))"
  },
  {
    "code": "def maxCtxContextualSubtable(maxCtx, st, ruleType, chain=''):\n    if st.Format == 1:\n        for ruleset in getattr(st, '%s%sRuleSet' % (chain, ruleType)):\n            if ruleset is None:\n                continue\n            for rule in getattr(ruleset, '%s%sRule' % (chain, ruleType)):\n                if rule is None:\n                    continue\n                maxCtx = maxCtxContextualRule(maxCtx, rule, chain)\n    elif st.Format == 2:\n        for ruleset in getattr(st, '%s%sClassSet' % (chain, ruleType)):\n            if ruleset is None:\n                continue\n            for rule in getattr(ruleset, '%s%sClassRule' % (chain, ruleType)):\n                if rule is None:\n                    continue\n                maxCtx = maxCtxContextualRule(maxCtx, rule, chain)\n    elif st.Format == 3:\n        maxCtx = maxCtxContextualRule(maxCtx, st, chain)\n    return maxCtx",
    "docstring": "Calculate usMaxContext based on a contextual feature subtable."
  },
  {
    "code": "def _log_submission(submission, student_item):\n    logger.info(\n        u\"Created submission uuid={submission_uuid} for \"\n        u\"(course_id={course_id}, item_id={item_id}, \"\n        u\"anonymous_student_id={anonymous_student_id})\"\n        .format(\n            submission_uuid=submission[\"uuid\"],\n            course_id=student_item[\"course_id\"],\n            item_id=student_item[\"item_id\"],\n            anonymous_student_id=student_item[\"student_id\"]\n        )\n    )",
    "docstring": "Log the creation of a submission.\n\n    Args:\n        submission (dict): The serialized submission model.\n        student_item (dict): The serialized student item model.\n\n    Returns:\n        None"
  },
  {
    "code": "def move(self, source, dest):\n        source = self._item_path(source)\n        dest = self._item_path(dest)\n        if not (contains_array(self._store, source) or\n                contains_group(self._store, source)):\n            raise ValueError('The source, \"%s\", does not exist.' % source)\n        if contains_array(self._store, dest) or contains_group(self._store, dest):\n            raise ValueError('The dest, \"%s\", already exists.' % dest)\n        if \"/\" in dest:\n            self.require_group(\"/\" + dest.rsplit(\"/\", 1)[0])\n        self._write_op(self._move_nosync, source, dest)",
    "docstring": "Move contents from one path to another relative to the Group.\n\n        Parameters\n        ----------\n        source : string\n            Name or path to a Zarr object to move.\n        dest : string\n            New name or path of the Zarr object."
  },
  {
    "code": "def collect(self):\n        instances = {}\n        for device in os.listdir('/dev/'):\n            instances.update(self.match_device(device, '/dev/'))\n        for device_id in os.listdir('/dev/disk/by-id/'):\n            instances.update(self.match_device(device, '/dev/disk/by-id/'))\n        metrics = {}\n        for device, p in instances.items():\n            output = p.communicate()[0].strip()\n            try:\n                metrics[device + \".Temperature\"] = float(output)\n            except:\n                self.log.warn('Disk temperature retrieval failed on ' + device)\n        for metric in metrics.keys():\n            self.publish(metric, metrics[metric])",
    "docstring": "Collect and publish disk temperatures"
  },
  {
    "code": "def replace_col(self, line, ndx):\n        for row in range(len(line)):\n            self.set_tile(row, ndx, line[row])",
    "docstring": "replace a grids column at index 'ndx' with 'line'"
  },
  {
    "code": "def cache(*depends_on):\n    def cache_decorator(fn):\n        @memoize\n        @wraps(fn)\n        def wrapper(*args, **kwargs):\n            if cache.disabled:\n                return fn(*args, **kwargs)\n            else:\n                return _cache.get_value(fn, depends_on, args, kwargs)\n        return wrapper\n    return cache_decorator",
    "docstring": "Caches function result in temporary file.\n\n    Cache will be expired when modification date of files from `depends_on`\n    will be changed.\n\n    Only functions should be wrapped in `cache`, not methods."
  },
  {
    "code": "def list_rules(self, chainname):\n        data = self.__run([self.__iptables_save, '-t', self.__name, '-c'])\n        return netfilter.parser.parse_rules(data, chainname)",
    "docstring": "Returns a list of Rules in the specified chain."
  },
  {
    "code": "def set(self, safe_len=False, **kwds):\n        if kwds:\n            d = self.kwds()\n            d.update(kwds)\n            self.reset(**d)\n        if safe_len and self.item:\n            self.leng = _len",
    "docstring": "Set one or more attributes."
  },
  {
    "code": "def flatten(iterable):\n    if isiterable(iterable):\n        flat = []\n        for item in list(iterable):\n            item = flatten(item)\n            if not isiterable(item):\n                item = [item]\n            flat += item\n        return flat\n    else:\n        return iterable",
    "docstring": "convenience tool to flatten any nested iterable\n\n    example:\n\n        flatten([[[],[4]],[[[5,[6,7, []]]]]])\n        >>> [4, 5, 6, 7]\n\n        flatten('hello')\n        >>> 'hello'\n\n    Parameters\n    ----------\n    iterable\n\n    Returns\n    -------\n    flattened object"
  },
  {
    "code": "def process_update(self, update):\n        data = json.loads(update)\n        NetworkTables.getEntry(data[\"k\"]).setValue(data[\"v\"])",
    "docstring": "Process an incoming update from a remote NetworkTables"
  },
  {
    "code": "def cleanup_cuts(self, hist: Hist, cut_axes: Iterable[HistAxisRange]) -> None:\n        for axis in cut_axes:\n            axis.axis(hist).SetRange(1, axis.axis(hist).GetNbins())",
    "docstring": "Cleanup applied cuts by resetting the axis to the full range.\n\n        Inspired by: https://github.com/matplo/rootutils/blob/master/python/2.7/THnSparseWrapper.py\n\n        Args:\n            hist: Histogram for which the axes should be reset.\n            cut_axes: List of axis cuts, which correspond to axes that should be reset."
  },
  {
    "code": "def add_paths(G, paths, bidirectional=False):\n    osm_oneway_values = ['yes', 'true', '1', '-1']\n    for data in paths.values():\n        if ('oneway' in data and data['oneway'] in osm_oneway_values) and not bidirectional:\n            if data['oneway'] == '-1':\n                data['nodes'] = list(reversed(data['nodes']))\n            add_path(G, data, one_way=True)\n        elif ('junction' in data and data['junction'] == 'roundabout') and not bidirectional:\n            add_path(G, data, one_way=True)\n        else:\n            add_path(G, data, one_way=False)\n    return G",
    "docstring": "Add a collection of paths to the graph.\n\n    Parameters\n    ----------\n    G : networkx multidigraph\n    paths : dict\n        the paths from OSM\n    bidirectional : bool\n        if True, create bidirectional edges for one-way streets\n\n\n    Returns\n    -------\n    None"
  },
  {
    "code": "def wipe_db(self):\n        logger.warning(\"Wiping the whole database\")\n        self.client.drop_database(self.db_name)\n        logger.debug(\"Database wiped\")",
    "docstring": "Wipe the whole database"
  },
  {
    "code": "def verboselogs_class_transform(cls):\n    if cls.name == 'RootLogger':\n        for meth in ['notice', 'spam', 'success', 'verbose']:\n            cls.locals[meth] = [scoped_nodes.Function(meth, None)]",
    "docstring": "Make Pylint aware of our custom logger methods."
  },
  {
    "code": "async def change_user_password(self, username, password):\n        user_facade = client.UserManagerFacade.from_connection(\n            self.connection())\n        entity = client.EntityPassword(password, tag.user(username))\n        return await user_facade.SetPassword([entity])",
    "docstring": "Change the password for a user in this controller.\n\n        :param str username: Username\n        :param str password: New password"
  },
  {
    "code": "def getconf(self, path, conf=None, logger=None):\n        result = conf\n        pathconf = None\n        rscpaths = self.rscpaths(path=path)\n        for rscpath in rscpaths:\n            pathconf = self._getconf(rscpath=rscpath, logger=logger, conf=conf)\n            if pathconf is not None:\n                if result is None:\n                    result = pathconf\n                else:\n                    result.update(pathconf)\n        return result",
    "docstring": "Parse a configuration path with input conf and returns\n        parameters by param name.\n\n        :param str path: conf resource path to parse and from get parameters.\n        :param Configuration conf: conf to fill with path values and\n            conf param names.\n        :param Logger logger: logger to use in order to trace\n            information/error.\n        :rtype: Configuration"
  },
  {
    "code": "def to_config(self, k, v):\n        if k == \"setup\":\n            return base.to_commandline(v)\n        return super(DataGenerator, self).to_config(k, v)",
    "docstring": "Hook method that allows conversion of individual options.\n\n        :param k: the key of the option\n        :type k: str\n        :param v: the value\n        :type v: object\n        :return: the potentially processed value\n        :rtype: object"
  },
  {
    "code": "async def async_get_camera_image(self, image_name, username=None, password=None):\n        try:\n            data = await self.async_fetch_image_data(\n                image_name, username, password)\n            if data is None:\n                raise XeomaError('Unable to authenticate with Xeoma web '\n                                 'server')\n            return data\n        except asyncio.TimeoutError:\n            raise XeomaError('Connection timeout while fetching camera image.')\n        except aiohttp.ClientError as e:\n            raise XeomaError('Unable to fetch image: {}'.format(e))",
    "docstring": "Grab a single image from the Xeoma web server\n\n            Arguments:\n                image_name: the name of the image to fetch (i.e. image01)\n                username: the username to directly access this image\n                password: the password to directly access this image"
  },
  {
    "code": "def get_interfaces_counters(self):\n        query = junos_views.junos_iface_counter_table(self.device)\n        query.get()\n        interface_counters = {}\n        for interface, counters in query.items():\n            interface_counters[interface] = {\n                k: v if v is not None else -1 for k, v in counters\n            }\n        return interface_counters",
    "docstring": "Return interfaces counters."
  },
  {
    "code": "def get_annotations(self):\n        try:\n            obj_list = self.__dict__['annotations']\n            return [Annotation(i) for i in obj_list]\n        except KeyError:\n            self._lazy_load()\n            obj_list = self.__dict__['annotations']\n            return [Annotation(i) for i in obj_list]",
    "docstring": "Fetch the annotations field if it does not exist."
  },
  {
    "code": "def flag_message(current):\n    current.output = {'status': 'Created', 'code': 201}\n    FlaggedMessage.objects.get_or_create(user_id=current.user_id,\n                                         message_id=current.input['key'])",
    "docstring": "Flag inappropriate messages\n\n    .. code-block:: python\n\n        # request:\n        {\n            'view':'_zops_flag_message',\n            'message_key': key,\n        }\n        # response:\n            {\n            '\n            'status': 'Created',\n            'code': 201,\n            }"
  },
  {
    "code": "def exists(self, path):\n        import hdfs\n        try:\n            self.client.status(path)\n            return True\n        except hdfs.util.HdfsError as e:\n            if str(e).startswith('File does not exist: '):\n                return False\n            else:\n                raise e",
    "docstring": "Returns true if the path exists and false otherwise."
  },
  {
    "code": "def master(self):\n        if len(self.mav_master) == 0:\n              return None\n        if self.settings.link > len(self.mav_master):\n            self.settings.link = 1\n        if not self.mav_master[self.settings.link-1].linkerror:\n            return self.mav_master[self.settings.link-1]\n        for m in self.mav_master:\n            if not m.linkerror:\n                return m\n        return self.mav_master[self.settings.link-1]",
    "docstring": "return the currently chosen mavlink master object"
  },
  {
    "code": "def derive_fields(self):\n        if self.fields:\n            return list(self.fields)\n        else:\n            fields = []\n            for field in self.object._meta.fields:\n                fields.append(field.name)\n            exclude = self.derive_exclude()\n            fields = [field for field in fields if field not in exclude]\n            return fields",
    "docstring": "Derives our fields.  We first default to using our 'fields' variable if available,\n        otherwise we figure it out from our object."
  },
  {
    "code": "def get_tokendefs(cls):\n        tokens = {}\n        inheritable = {}\n        for c in cls.__mro__:\n            toks = c.__dict__.get('tokens', {})\n            for state, items in iteritems(toks):\n                curitems = tokens.get(state)\n                if curitems is None:\n                    tokens[state] = items\n                    try:\n                        inherit_ndx = items.index(inherit)\n                    except ValueError:\n                        continue\n                    inheritable[state] = inherit_ndx\n                    continue\n                inherit_ndx = inheritable.pop(state, None)\n                if inherit_ndx is None:\n                    continue\n                curitems[inherit_ndx:inherit_ndx+1] = items\n                try:\n                    new_inh_ndx = items.index(inherit)\n                except ValueError:\n                    pass\n                else:\n                    inheritable[state] = inherit_ndx + new_inh_ndx\n        return tokens",
    "docstring": "Merge tokens from superclasses in MRO order, returning a single tokendef\n        dictionary.\n\n        Any state that is not defined by a subclass will be inherited\n        automatically.  States that *are* defined by subclasses will, by\n        default, override that state in the superclass.  If a subclass wishes to\n        inherit definitions from a superclass, it can use the special value\n        \"inherit\", which will cause the superclass' state definition to be\n        included at that point in the state."
  },
  {
    "code": "def on_intent(intent_request, session):\n    print(\"on_intent requestId=\" + intent_request['requestId'] +\n          \", sessionId=\" + session['sessionId'])\n    intent = intent_request['intent']\n    intent_name = intent_request['intent']['name']\n    if intent_name == \"MyColorIsIntent\":\n        return set_color_in_session(intent, session)\n    elif intent_name == \"WhatsMyColorIntent\":\n        return get_color_from_session(intent, session)\n    elif intent_name == \"AMAZON.HelpIntent\":\n        return get_welcome_response()\n    elif intent_name == \"AMAZON.CancelIntent\" or intent_name == \"AMAZON.StopIntent\":\n        return handle_session_end_request()\n    else:\n        raise ValueError(\"Invalid intent\")",
    "docstring": "Called when the user specifies an intent for this skill"
  },
  {
    "code": "def datetime_from_iso(iso_string):\n    try:\n        assert datetime_regex.datetime.datetime.match(iso_string).groups()[0]\n    except (ValueError, AssertionError, IndexError, AttributeError):\n        raise TypeError(\"String is not in ISO format\")\n    try:\n        return datetime.datetime.strptime(iso_string, \"%Y-%m-%dT%H:%M:%S.%f\")\n    except ValueError:\n        return datetime.datetime.strptime(iso_string, \"%Y-%m-%dT%H:%M:%S\")",
    "docstring": "Create a DateTime object from a ISO string\n\n    .. code :: python\n\n        reusables.datetime_from_iso('2017-03-10T12:56:55.031863')\n        datetime.datetime(2017, 3, 10, 12, 56, 55, 31863)\n\n    :param iso_string: string of an ISO datetime\n    :return: DateTime object"
  },
  {
    "code": "def format_epilog_section(self, section, text):\n        try:\n            func = self._epilog_formatters[self.epilog_formatter]\n        except KeyError:\n            if not callable(self.epilog_formatter):\n                raise\n            func = self.epilog_formatter\n        return func(section, text)",
    "docstring": "Format a section for the epilog by inserting a format"
  },
  {
    "code": "def sync(self, force=None):\n        try:\n            if force:\n                sd = force\n            else:\n                sd = self.sync_dir()\n            if sd == self.SYNC_DIR.FILE_TO_RECORD:\n                if force and not self.exists():\n                    return None\n                self.fs_to_record()\n            elif sd == self.SYNC_DIR.RECORD_TO_FILE:\n                self.record_to_fs()\n            else:\n                return None\n            self._dataset.config.sync[self.file_const][sd] = time.time()\n            return sd\n        except Exception as e:\n            self._bundle.rollback()\n            self._bundle.error(\"Failed to sync '{}': {}\".format(self.file_const, e))\n            raise",
    "docstring": "Synchronize between the file in the file system and the field record"
  },
  {
    "code": "def user_remove(name, user=None, password=None, host=None, port=None,\n                database='admin', authdb=None):\n    conn = _connect(user, password, host, port)\n    if not conn:\n        return 'Failed to connect to mongo database'\n    try:\n        log.info('Removing user %s', name)\n        mdb = pymongo.database.Database(conn, database)\n        mdb.remove_user(name)\n    except pymongo.errors.PyMongoError as err:\n        log.error('Creating database %s failed with error: %s', name, err)\n        return six.text_type(err)\n    return True",
    "docstring": "Remove a MongoDB user\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' mongodb.user_remove <name> <user> <password> <host> <port> <database>"
  },
  {
    "code": "def create_rule(self):\n        return BlockRule(\n            self.networkapi_url,\n            self.user,\n            self.password,\n            self.user_ldap)",
    "docstring": "Get an instance of block rule services facade."
  },
  {
    "code": "def del_current_vrf(self):\n        vrf_id = int(request.json['vrf_id'])\n        if vrf_id in session['current_vrfs']:\n            del session['current_vrfs'][vrf_id]\n            session.save()\n        return json.dumps(session.get('current_vrfs', {}))",
    "docstring": "Remove VRF to filter list session variable"
  },
  {
    "code": "def update_score(self, node, addToScore):\n        current_score = 0\n        score_string = self.parser.getAttribute(node, 'gravityScore')\n        if score_string:\n            current_score = int(score_string)\n        new_score = current_score + addToScore\n        self.parser.setAttribute(node, \"gravityScore\", str(new_score))",
    "docstring": "\\\n        adds a score to the gravityScore Attribute we put on divs\n        we'll get the current score then add the score\n        we're passing in to the current"
  },
  {
    "code": "def get_long_description():\n    import codecs \n    with codecs.open('README.rst', encoding='UTF-8') as f:\n        readme = [line for line in f if not line.startswith('.. contents::')]\n        return ''.join(readme)",
    "docstring": "Strip the content index from the long description."
  },
  {
    "code": "def hashing_type(self, cluster='main'):\n        if not self.config.has_section(cluster):\n            raise SystemExit(\"Cluster '%s' not defined in %s\"\n                             % (cluster, self.config_file))\n        hashing_type = 'carbon_ch'\n        try:\n            return self.config.get(cluster, 'hashing_type')\n        except NoOptionError:\n            return hashing_type",
    "docstring": "Hashing type of cluster."
  },
  {
    "code": "def import_symbol(name=None, path=None, typename=None, base_path=None):\n    _, symbol = _import(name or typename, path or base_path)\n    return symbol",
    "docstring": "Import a module, or a typename within a module from its name.\n\n    Arguments:\n\n    name: An absolute or relative (starts with a .) Python path\n    path: If name is relative, path is prepended to it.\n    base_path: (DEPRECATED) Same as path\n    typename: (DEPRECATED) Same as path"
  },
  {
    "code": "def execute_sql(self, sql):\n        cursor = self.get_cursor()\n        cursor.execute(sql)\n        return cursor",
    "docstring": "Executes SQL and returns cursor for it"
  },
  {
    "code": "def facets_boundary(self):\n        edges = self.edges_sorted.reshape((-1, 6))\n        edges_facet = [edges[i].reshape((-1, 2)) for i in self.facets]\n        edges_boundary = np.array([i[grouping.group_rows(i, require_count=1)]\n                                   for i in edges_facet])\n        return edges_boundary",
    "docstring": "Return the edges which represent the boundary of each facet\n\n        Returns\n        ---------\n        edges_boundary : sequence of (n, 2) int\n          Indices of self.vertices"
  },
  {
    "code": "def smartfields_get_field_status(self, field_name):\n        manager = self._smartfields_managers.get(field_name, None)\n        if manager is not None:\n            return manager.get_status(self)\n        return {'state': 'ready'}",
    "docstring": "A way to find out a status of a filed."
  },
  {
    "code": "def create_connection(cls, address, timeout=None, source_address=None):\n        sock = socket.create_connection(address, timeout, source_address)\n        return cls(sock)",
    "docstring": "Create a SlipSocket connection.\n\n        This convenience method creates a connection to the the specified address\n        using the :func:`socket.create_connection` function.\n        The socket that is returned from that call is automatically wrapped in\n        a :class:`SlipSocket` object.\n\n        .. note::\n            The :meth:`create_connection` method does not magically turn the\n            socket at the remote address into a SlipSocket.\n            For the connection to work properly,\n            the remote socket must already\n            have been configured to use the SLIP protocol."
  },
  {
    "code": "def _reverse_convert(x, factor1, factor2):\n        return x * factor1 / ((1-x) * factor2 + x * factor1)",
    "docstring": "Converts mixing ratio x in c1 - c2 tie line to that in\n        comp1 - comp2 tie line.\n\n        Args:\n            x (float): Mixing ratio x in c1 - c2 tie line, a float between\n                0 and 1.\n            factor1 (float): Compositional ratio between composition c1 and\n                processed composition comp1. E.g., factor for\n                Composition('SiO2') and Composition('O') is 2.\n            factor2 (float): Compositional ratio between composition c2 and\n                processed composition comp2.\n\n        Returns:\n            Mixing ratio in comp1 - comp2 tie line, a float between 0 and 1."
  },
  {
    "code": "def do_placeholder(parser, token):\n    name, params = parse_placeholder(parser, token)\n    return PlaceholderNode(name, **params)",
    "docstring": "Method that parse the placeholder template tag.\n\n    Syntax::\n\n        {% placeholder <name> [on <page>] [with <widget>] \\\n[parsed] [as <varname>] %}\n\n    Example usage::\n\n        {% placeholder about %}\n        {% placeholder body with TextArea as body_text %}\n        {% placeholder welcome with TextArea parsed as welcome_text %}\n        {% placeholder teaser on next_page with TextArea parsed %}"
  },
  {
    "code": "def export(datastore_key, calc_id=-1, exports='csv', export_dir='.'):\n    dstore = util.read(calc_id)\n    parent_id = dstore['oqparam'].hazard_calculation_id\n    if parent_id:\n        dstore.parent = util.read(parent_id)\n    dstore.export_dir = export_dir\n    with performance.Monitor('export', measuremem=True) as mon:\n        for fmt in exports.split(','):\n            fnames = export_((datastore_key, fmt), dstore)\n            nbytes = sum(os.path.getsize(f) for f in fnames)\n            print('Exported %s in %s' % (general.humansize(nbytes), fnames))\n    if mon.duration > 1:\n        print(mon)\n    dstore.close()",
    "docstring": "Export an output from the datastore."
  },
  {
    "code": "def get_oauth_request(self):\n        try:\n            method = os.environ['REQUEST_METHOD']\n        except:\n            method = 'GET'\n        postdata = None\n        if method in ('POST', 'PUT'):\n            postdata = self.request.body\n        return oauth.Request.from_request(method, self.request.uri,\n            headers=self.request.headers, query_string=postdata)",
    "docstring": "Return an OAuth Request object for the current request."
  },
  {
    "code": "def plugins(self):\n        if self._plugins is None:\n            self._plugins = {}\n            for _, plugin in self.load_extensions('iotile.plugin'):\n                links = plugin()\n                for name, value in links:\n                    self._plugins[name] = value\n        return self._plugins",
    "docstring": "Lazily load iotile plugins only on demand.\n\n        This is a slow operation on computers with a slow FS and is rarely\n        accessed information, so only compute it when it is actually asked\n        for."
  },
  {
    "code": "def yield_sorted_by_type(*typelist):\n    def decorate(fun):\n        @wraps(fun)\n        def decorated(*args, **kwds):\n            return iterate_by_type(fun(*args, **kwds), typelist)\n        return decorated\n    return decorate",
    "docstring": "a useful decorator for the collect_impl method of SuperChange\n    subclasses. Caches the yielded changes, and re-emits them\n    collected by their type. The order of the types can be specified\n    by listing the types as arguments to this decorator. Unlisted\n    types will be yielded last in no guaranteed order.\n\n    Grouping happens by exact type match only. Inheritance is not\n    taken into consideration for grouping."
  },
  {
    "code": "def dry_run_scan(self, scan_id, targets):\n        os.setsid()\n        for _, target in enumerate(targets):\n            host = resolve_hostname(target[0])\n            if host is None:\n                logger.info(\"Couldn't resolve %s.\", target[0])\n                continue\n            port = self.get_scan_ports(scan_id, target=target[0])\n            logger.info(\"%s:%s: Dry run mode.\", host, port)\n            self.add_scan_log(scan_id, name='', host=host,\n                              value='Dry run result')\n        self.finish_scan(scan_id)",
    "docstring": "Dry runs a scan."
  },
  {
    "code": "def get_attribute_selected(self, attribute):\n        items_list = self.get_options()\n        return next(iter([item.get_attribute(attribute) for item in items_list if item.is_selected()]), None)",
    "docstring": "Performs search of selected item from Web List\n        Return attribute of selected item\n\n        @params attribute - string attribute name"
  },
  {
    "code": "def get_dm_online(self):\n        if not requests:\n            return False\n        try:\n            req = requests.get(\"https://earthref.org/MagIC/data-models/3.0.json\", timeout=3)\n            if not req.ok:\n                return False\n            return req\n        except (requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError,\n                requests.exceptions.ReadTimeout):\n            return False",
    "docstring": "Use requests module to get data model from Earthref.\n        If this fails or times out, return false.\n\n        Returns\n        ---------\n        result : requests.models.Response, False if unsuccessful"
  },
  {
    "code": "def get_content_dict(vocabularies, content_vocab):\n    if vocabularies.get(content_vocab, None) is None:\n        raise UNTLFormException(\n            'Could not retrieve content vocabulary \"%s\" for the form.'\n            % (content_vocab)\n        )\n    else:\n        return vocabularies.get(content_vocab)",
    "docstring": "Get the content dictionary based on the element's content\n    vocabulary."
  },
  {
    "code": "def get_edited(self, subreddit='mod', *args, **kwargs):\n        url = self.config['edited'].format(subreddit=six.text_type(subreddit))\n        return self.get_content(url, *args, **kwargs)",
    "docstring": "Return a get_content generator of edited items.\n\n        :param subreddit: Either a Subreddit object or the name of the\n            subreddit to return the edited items for. Defaults to `mod` which\n            includes items for all the subreddits you moderate.\n\n        The additional parameters are passed directly into\n        :meth:`.get_content`. Note: the `url` parameter cannot be altered."
  },
  {
    "code": "def flush(self):\n    self.acquire()\n    try:\n      self.stream.flush()\n    except (EnvironmentError, ValueError):\n      pass\n    finally:\n      self.release()",
    "docstring": "Flushes all log files."
  },
  {
    "code": "def listdir_matches(match):\n    import os\n    last_slash = match.rfind('/')\n    if last_slash == -1:\n        dirname = '.'\n        match_prefix = match\n        result_prefix = ''\n    else:\n        match_prefix = match[last_slash + 1:]\n        if last_slash == 0:\n            dirname = '/'\n            result_prefix = '/'\n        else:\n            dirname = match[0:last_slash]\n            result_prefix = dirname + '/'\n    def add_suffix_if_dir(filename):\n        try:\n            if (os.stat(filename)[0] & 0x4000) != 0:\n                return filename + '/'\n        except FileNotFoundError:\n            pass\n        return filename\n    matches = [add_suffix_if_dir(result_prefix + filename)\n               for filename in os.listdir(dirname) if filename.startswith(match_prefix)]\n    return matches",
    "docstring": "Returns a list of filenames contained in the named directory.\n       Only filenames which start with `match` will be returned.\n       Directories will have a trailing slash."
  },
  {
    "code": "def loadTextureD3D11_Async(self, textureId, pD3D11Device):\n        fn = self.function_table.loadTextureD3D11_Async\n        ppD3D11Texture2D = c_void_p()\n        result = fn(textureId, pD3D11Device, byref(ppD3D11Texture2D))\n        return result, ppD3D11Texture2D.value",
    "docstring": "Creates a D3D11 texture and loads data into it."
  },
  {
    "code": "def OECDas(self, to='name_short'):\n        if isinstance(to, str):\n            to = [to]\n        return self.data[self.data.OECD > 0][to]",
    "docstring": "Return OECD member states in the specified classification\n\n        Parameters\n        ----------\n        to : str, optional\n            Output classification (valid str for an index of\n            country_data file), default: name_short\n\n        Returns\n        -------\n        Pandas DataFrame"
  },
  {
    "code": "def add_field(self, key, field):\n    if key in self._fields:\n      raise PayloadFieldAlreadyDefinedError(\n        'Key {key} is already set on this payload. The existing field was {existing_field}.'\n        ' Tried to set new field {field}.'\n        .format(key=key, existing_field=self._fields[key], field=field))\n    elif self._frozen:\n      raise PayloadFrozenError(\n        'Payload is frozen, field with key {key} cannot be added to it.'\n        .format(key=key))\n    else:\n      self._fields[key] = field\n      self._fingerprint_memo = None",
    "docstring": "Add a field to the Payload.\n\n    :API: public\n\n    :param string key:  The key for the field.  Fields can be accessed using attribute access as\n      well as `get_field` using `key`.\n    :param PayloadField field:  A PayloadField instance.  None is an allowable value for `field`,\n      in which case it will be skipped during hashing."
  },
  {
    "code": "async def _get_person_json(self, id_, url_params=None):\n        url = self.url_builder(\n            'person/{person_id}',\n            dict(person_id=id_),\n            url_params=url_params or OrderedDict(),\n        )\n        data = await self.get_data(url)\n        return data",
    "docstring": "Retrieve raw person JSON by ID.\n\n        Arguments:\n          id_ (:py:class:`int`): The person's TMDb ID.\n          url_params (:py:class:`dict`): Any additional URL parameters.\n\n        Returns:\n          :py:class:`dict`: The JSON data."
  },
  {
    "code": "def container(self, name, length, type, *parameters):\n        self.new_struct('Container', name, 'length=%s' % length)\n        BuiltIn().run_keyword(type, *parameters)\n        self.end_struct()",
    "docstring": "Define a container with given length.\n\n        This is a convenience method creating a `Struct` with `length` containing fields defined in `type`."
  },
  {
    "code": "def request(self, requests):\n        logging.info('Request resources from Mesos')\n        return self.driver.requestResources(map(encode, requests))",
    "docstring": "Requests resources from Mesos.\n\n        (see mesos.proto for a description of Request and how, for example, to\n        request resources from specific slaves.)\n\n        Any resources available are offered to the framework via\n        Scheduler.resourceOffers callback, asynchronously."
  },
  {
    "code": "def ship_move(ship, x, y, speed):\n    click.echo('Moving ship %s to %s,%s with speed %s' % (ship, x, y, speed))",
    "docstring": "Moves SHIP to the new location X,Y."
  },
  {
    "code": "def check_alert(self, text):\n    try:\n        alert = Alert(world.browser)\n        if alert.text != text:\n            raise AssertionError(\n                \"Alert text expected to be {!r}, got {!r}.\".format(\n                    text, alert.text))\n    except WebDriverException:\n        pass",
    "docstring": "Assert an alert is showing with the given text."
  },
  {
    "code": "def collect_metrics():\n    def _register(action):\n        handler = Handler.get(action)\n        handler.add_predicate(partial(_restricted_hook, 'collect-metrics'))\n        return action\n    return _register",
    "docstring": "Register the decorated function to run for the collect_metrics hook."
  },
  {
    "code": "def verify_signature(self, signature_filename, data_filename,\n                         keystore=None):\n        if not self.gpg:\n            raise DistlibException('verification unavailable because gpg '\n                                   'unavailable')\n        cmd = self.get_verify_command(signature_filename, data_filename,\n                                      keystore)\n        rc, stdout, stderr = self.run_command(cmd)\n        if rc not in (0, 1):\n            raise DistlibException('verify command failed with error '\n                             'code %s' % rc)\n        return rc == 0",
    "docstring": "Verify a signature for a file.\n\n        :param signature_filename: The pathname to the file containing the\n                                   signature.\n        :param data_filename: The pathname to the file containing the\n                              signed data.\n        :param keystore: The path to a directory which contains the keys\n                         used in verification. If not specified, the\n                         instance's ``gpg_home`` attribute is used instead.\n        :return: True if the signature was verified, else False."
  },
  {
    "code": "def write(entries):\n    try:\n        with open(get_rc_path(), 'w') as rc:\n            rc.writelines(entries)\n    except IOError:\n        print('Error writing your ~/.vacationrc file!')",
    "docstring": "Write an entire rc file."
  },
  {
    "code": "def update(self, resource, timeout=-1):\n        self.__set_default_values(resource)\n        uri = self._client.build_uri(resource['logicalSwitch']['uri'])\n        return self._client.update(resource, uri=uri, timeout=timeout)",
    "docstring": "Updates a Logical Switch.\n\n        Args:\n            resource (dict): Object to update.\n            timeout:\n                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n                in OneView, just stop waiting for its completion.\n\n        Returns:\n            dict: Updated resource."
  },
  {
    "code": "def main() -> None:\n    _ =\n    testdata = [\n        \"hello\",\n        1,\n        [\"bongos\", \"today\"],\n    ]\n    for data in testdata:\n        compare_python_to_reference_murmur3_32(data, seed=0)\n        compare_python_to_reference_murmur3_64(data, seed=0)\n    print(\"All OK\")",
    "docstring": "Command-line validation checks."
  },
  {
    "code": "def _expand_subsystems(self, scope_infos):\n    def subsys_deps(subsystem_client_cls):\n      for dep in subsystem_client_cls.subsystem_dependencies_iter():\n        if dep.scope != GLOBAL_SCOPE:\n          yield self._scope_to_info[dep.options_scope]\n          for x in subsys_deps(dep.subsystem_cls):\n            yield x\n    for scope_info in scope_infos:\n      yield scope_info\n      if scope_info.optionable_cls is not None:\n        if issubclass(scope_info.optionable_cls, GlobalOptionsRegistrar):\n          for scope, info in self._scope_to_info.items():\n            if info.category == ScopeInfo.SUBSYSTEM and enclosing_scope(scope) == GLOBAL_SCOPE:\n              yield info\n              for subsys_dep in subsys_deps(info.optionable_cls):\n                yield subsys_dep\n        elif issubclass(scope_info.optionable_cls, SubsystemClientMixin):\n          for subsys_dep in subsys_deps(scope_info.optionable_cls):\n            yield subsys_dep",
    "docstring": "Add all subsystems tied to a scope, right after that scope."
  },
  {
    "code": "def message(self):\n        if self.type == 'cleartext':\n            return self.bytes_to_text(self._message)\n        if self.type == 'literal':\n            return self._message.contents\n        if self.type == 'encrypted':\n            return self._message",
    "docstring": "The message contents"
  },
  {
    "code": "def _get_id(self, id_, pkg_name):\n        collection = JSONClientValidated('id',\n                                         collection=pkg_name + 'Ids',\n                                         runtime=self._runtime)\n        try:\n            result = collection.find_one({'aliasIds': {'$in': [str(id_)]}})\n        except errors.NotFound:\n            return id_\n        else:\n            return Id(result['_id'])",
    "docstring": "Returns the primary id given an alias.\n\n        If the id provided is not in the alias table, it will simply be\n        returned as is.\n\n        Only looks within the Id Alias namespace for the session package"
  },
  {
    "code": "def handle_api_exception(error):\n    _mp_track(\n        type=\"exception\",\n        status_code=error.status_code,\n        message=error.message,\n    )\n    response = jsonify(dict(\n        message=error.message\n    ))\n    response.status_code = error.status_code\n    return response",
    "docstring": "Converts an API exception into an error response."
  },
  {
    "code": "def np2str(value):\n    if hasattr(value, 'dtype') and \\\n            issubclass(value.dtype.type, (np.string_, np.object_)) and value.size == 1:\n        value = np.asscalar(value)\n        if not isinstance(value, str):\n            value = value.decode()\n        return value\n    else:\n        raise ValueError(\"Array is not a string type or is larger than 1\")",
    "docstring": "Convert an `numpy.string_` to str.\n\n    Args:\n        value (ndarray): scalar or 1-element numpy array to convert\n\n    Raises:\n        ValueError: if value is array larger than 1-element or it is not of\n                    type `numpy.string_` or it is not a numpy array"
  },
  {
    "code": "def DeregisterAnalyzer(cls, analyzer_class):\n    analyzer_name = analyzer_class.NAME.lower()\n    if analyzer_name not in cls._analyzer_classes:\n      raise KeyError('analyzer class not set for name: {0:s}'.format(\n          analyzer_class.NAME))\n    del cls._analyzer_classes[analyzer_name]",
    "docstring": "Deregisters a analyzer class.\n\n    The analyzer classes are identified based on their lower case name.\n\n    Args:\n      analyzer_class (type): class object of the analyzer.\n\n    Raises:\n      KeyError: if analyzer class is not set for the corresponding name."
  },
  {
    "code": "def add_callback(self, fn, *args, **kwargs):\n        if not callable(fn):\n            raise ValueError(\"Value for argument 'fn' is {0} and is not a callable object.\".format(type(fn)))\n        self._callbacks.append((fn, args, kwargs))",
    "docstring": "Add a function and arguments to be passed to it to be executed after the batch executes.\n\n        A batch can support multiple callbacks.\n\n        Note, that if the batch does not execute, the callbacks are not executed.\n        A callback, thus, is an \"on batch success\" handler.\n\n        :param fn: Callable object\n        :type fn: callable\n        :param \\*args: Positional arguments to be passed to the callback at the time of execution\n        :param \\*\\*kwargs: Named arguments to be passed to the callback at the time of execution"
  },
  {
    "code": "def get_snapshot_policy(self, name, view=None):\n    return self._get(\"snapshots/policies/%s\" % name, ApiSnapshotPolicy,\n        params=view and dict(view=view) or None, api_version=6)",
    "docstring": "Retrieve a single snapshot policy.\n\n    @param name: The name of the snapshot policy to retrieve.\n    @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'.\n    @return: The requested snapshot policy.\n    @since: API v6"
  },
  {
    "code": "def get_vectors_loss(ops, docs, prediction, objective=\"L2\"):\n    ids = ops.flatten([doc.to_array(ID).ravel() for doc in docs])\n    target = docs[0].vocab.vectors.data[ids]\n    if objective == \"L2\":\n        d_target = prediction - target\n        loss = (d_target ** 2).sum()\n    elif objective == \"cosine\":\n        loss, d_target = get_cossim_loss(prediction, target)\n    return loss, d_target",
    "docstring": "Compute a mean-squared error loss between the documents' vectors and\n    the prediction.\n\n    Note that this is ripe for customization! We could compute the vectors\n    in some other word, e.g. with an LSTM language model, or use some other\n    type of objective."
  },
  {
    "code": "def create_game(\n      self,\n      map_name,\n      bot_difficulty=sc_pb.VeryEasy,\n      bot_race=sc_common.Random,\n      bot_first=False):\n    self._controller.ping()\n    map_inst = maps.get(map_name)\n    map_data = map_inst.data(self._run_config)\n    if map_name not in self._saved_maps:\n      self._controller.save_map(map_inst.path, map_data)\n      self._saved_maps.add(map_name)\n    create = sc_pb.RequestCreateGame(\n        local_map=sc_pb.LocalMap(map_path=map_inst.path, map_data=map_data),\n        disable_fog=False)\n    if not bot_first:\n      create.player_setup.add(type=sc_pb.Participant)\n    create.player_setup.add(\n        type=sc_pb.Computer, race=bot_race, difficulty=bot_difficulty)\n    if bot_first:\n      create.player_setup.add(type=sc_pb.Participant)\n    self._controller.create_game(create)",
    "docstring": "Create a game, one remote agent vs the specified bot.\n\n    Args:\n      map_name: The map to use.\n      bot_difficulty: The difficulty of the bot to play against.\n      bot_race: The race for the bot.\n      bot_first: Whether the bot should be player 1 (else is player 2)."
  },
  {
    "code": "def filter(self, *args, **kwargs):\n        if args or kwargs:\n            self.q_filters = Q(self.q_filters & Q(*args, **kwargs))\n        return self",
    "docstring": "Apply filters to the existing nodes in the set.\n\n        :param kwargs: filter parameters\n\n            Filters mimic Django's syntax with the double '__' to separate field and operators.\n\n            e.g `.filter(salary__gt=20000)` results in `salary > 20000`.\n\n            The following operators are available:\n\n             * 'lt': less than\n             * 'gt': greater than\n             * 'lte': less than or equal to\n             * 'gte': greater than or equal to\n             * 'ne': not equal to\n             * 'in': matches one of list (or tuple)\n             * 'isnull': is null\n             * 'regex': matches supplied regex (neo4j regex format)\n             * 'exact': exactly match string (just '=')\n             * 'iexact': case insensitive match string\n             * 'contains': contains string\n             * 'icontains': case insensitive contains\n             * 'startswith': string starts with\n             * 'istartswith': case insensitive string starts with\n             * 'endswith': string ends with\n             * 'iendswith': case insensitive string ends with\n\n        :return: self"
  },
  {
    "code": "def get_connection_params(self):\n        return {\n            'uri': self.settings_dict['NAME'],\n            'tls': self.settings_dict.get('TLS', False),\n            'bind_dn': self.settings_dict['USER'],\n            'bind_pw': self.settings_dict['PASSWORD'],\n            'retry_max': self.settings_dict.get('RETRY_MAX', 1),\n            'retry_delay': self.settings_dict.get('RETRY_DELAY', 60.0),\n            'options': {\n                k if isinstance(k, int) else k.lower(): v\n                for k, v in self.settings_dict.get('CONNECTION_OPTIONS', {}).items()\n            },\n        }",
    "docstring": "Compute appropriate parameters for establishing a new connection.\n\n        Computed at system startup."
  },
  {
    "code": "def multi_pop(d, *args):\n    retval = {}\n    for key in args:\n        if key in d:\n            retval[key] = d.pop(key)\n    return retval",
    "docstring": "pops multiple keys off a dict like object"
  },
  {
    "code": "def parse_input(self, text):\n        parts = util.split(text)\n        command = parts[0] if text and parts else None\n        command = command.lower() if command else None\n        args = parts[1:] if len(parts) > 1 else []\n        return (command, args)",
    "docstring": "Parse ctl user input. Double quotes are used\n        to group together multi words arguments."
  },
  {
    "code": "def get_json(self):\n        try:\n            usernotes = self.subreddit.wiki[self.page_name].content_md\n            notes = json.loads(usernotes)\n        except NotFound:\n            self._init_notes()\n        else:\n            if notes['ver'] != self.schema:\n                raise RuntimeError(\n                    'Usernotes schema is v{0}, puni requires v{1}'.\n                    format(notes['ver'], self.schema)\n                )\n            self.cached_json = self._expand_json(notes)\n        return self.cached_json",
    "docstring": "Get the JSON stored on the usernotes wiki page.\n\n        Returns a dict representation of the usernotes (with the notes BLOB\n        decoded).\n\n        Raises:\n            RuntimeError if the usernotes version is incompatible with this\n                version of puni."
  },
  {
    "code": "def get_error_code_msg(cls, full_error_message):\n        for pattern in cls.ERROR_PATTERNS:\n            match = pattern.match(full_error_message)\n            if match:\n                return int(match.group('code')), match.group('msg').strip()\n        return 0, full_error_message",
    "docstring": "Extract the code and message of the exception that clickhouse-server generated.\n\n        See the list of error codes here:\n        https://github.com/yandex/ClickHouse/blob/master/dbms/src/Common/ErrorCodes.cpp"
  },
  {
    "code": "def read_json(file_path):\n    try:\n        with open(file_path, 'r') as f:\n            config = json_tricks.load(f)\n    except ValueError:\n        print('    '+'!'*58)\n        print('    Woops! Looks the JSON syntax is not valid in:')\n        print('        {}'.format(file_path))\n        print('    Note: commonly this is a result of having a trailing comma \\n    in the file')\n        print('    '+'!'*58)\n        raise\n    return config",
    "docstring": "Read in a json file and return a dictionary representation"
  },
  {
    "code": "def set_encode_key_value(self, value, store_type=PUBLIC_KEY_STORE_TYPE_BASE64):\n        if store_type == PUBLIC_KEY_STORE_TYPE_PEM:\n            PublicKeyBase.set_encode_key_value(self, value.exportKey('PEM').decode(), store_type)\n        else:\n            PublicKeyBase.set_encode_key_value(self, value.exportKey('DER'), store_type)",
    "docstring": "Set the value based on the type of encoding supported by RSA."
  },
  {
    "code": "def init_body_buffer(self, method, headers):\n        content_length = headers.get(\"CONTENT-LENGTH\", None)\n        if method in (HTTPMethod.POST, HTTPMethod.PUT):\n            if content_length is None:\n                raise HTTPErrorBadRequest(\"HTTP Method requires a CONTENT-LENGTH header\")\n            self.content_length = int(content_length)\n            self.body_buffer = bytearray(0)\n        elif content_length is not None:\n            raise HTTPErrorBadRequest(\n                \"HTTP method %s may NOT have a CONTENT-LENGTH header\"\n            )",
    "docstring": "Sets up the body_buffer and content_length attributes based\n        on method and headers."
  },
  {
    "code": "def to_cloudformation(self, **kwargs):\n        resources = []\n        function = kwargs.get('function')\n        if not function:\n            raise TypeError(\"Missing required keyword argument: function\")\n        if self.Method is not None:\n            self.Method = self.Method.lower()\n        resources.extend(self._get_permissions(kwargs))\n        explicit_api = kwargs['explicit_api']\n        if explicit_api.get(\"__MANAGE_SWAGGER\"):\n            self._add_swagger_integration(explicit_api, function)\n        return resources",
    "docstring": "If the Api event source has a RestApi property, then simply return the Lambda Permission resource allowing\n        API Gateway to call the function. If no RestApi is provided, then additionally inject the path, method, and the\n        x-amazon-apigateway-integration into the Swagger body for a provided implicit API.\n\n        :param dict kwargs: a dict containing the implicit RestApi to be modified, should no explicit RestApi \\\n                be provided.\n        :returns: a list of vanilla CloudFormation Resources, to which this Api event expands\n        :rtype: list"
  },
  {
    "code": "def read(self):\n        try:\n            f = urllib.request.urlopen(self.url)\n        except urllib.error.HTTPError as err:\n            if err.code in (401, 403):\n                self.disallow_all = True\n            elif err.code >= 400:\n                self.allow_all = True\n        else:\n            raw = f.read()\n            self.parse(raw.decode(\"utf-8\").splitlines())",
    "docstring": "Reads the robots.txt URL and feeds it to the parser."
  },
  {
    "code": "def predict(self, dataset,\n                new_observation_data=None, new_user_data=None, new_item_data=None):\n        if new_observation_data is None:\n            new_observation_data = _SFrame()\n        if new_user_data is None:\n            new_user_data = _SFrame()\n        if new_item_data is None:\n            new_item_data = _SFrame()\n        dataset = self.__prepare_dataset_parameter(dataset)\n        def check_type(arg, arg_name, required_type, allowed_types):\n            if not isinstance(arg, required_type):\n                raise TypeError(\"Parameter \" + arg_name + \" must be of type(s) \"\n                                + (\", \".join(allowed_types))\n                                + \"; Type '\" + str(type(arg)) + \"' not recognized.\")\n        check_type(new_observation_data, \"new_observation_data\", _SFrame, [\"SFrame\"])\n        check_type(new_user_data, \"new_user_data\", _SFrame, [\"SFrame\"])\n        check_type(new_item_data, \"new_item_data\", _SFrame, [\"SFrame\"])\n        response = self.__proxy__.predict(dataset, new_user_data, new_item_data)\n        return response['prediction']",
    "docstring": "Return a score prediction for the user ids and item ids in the provided\n        data set.\n\n        Parameters\n        ----------\n        dataset : SFrame\n            Dataset in the same form used for training.\n\n        new_observation_data : SFrame, optional\n            ``new_observation_data`` gives additional observation data\n            to the model, which may be used by the models to improve\n            score accuracy.  Must be in the same format as the\n            observation data passed to ``create``.  How this data is\n            used varies by model.\n\n        new_user_data : SFrame, optional\n            ``new_user_data`` may give additional user data to the\n            model.  If present, scoring is done with reference to this\n            new information.  If there is any overlap with the side\n            information present at training time, then this new side\n            data is preferred.  Must be in the same format as the user\n            data passed to ``create``.\n\n        new_item_data : SFrame, optional\n            ``new_item_data`` may give additional item data to the\n            model.  If present, scoring is done with reference to this\n            new information.  If there is any overlap with the side\n            information present at training time, then this new side\n            data is preferred.  Must be in the same format as the item\n            data passed to ``create``.\n\n        Returns\n        -------\n        out : SArray\n            An SArray with predicted scores for each given observation\n            predicted by the model.\n\n        See Also\n        --------\n        recommend, evaluate"
  },
  {
    "code": "def get_log_entry_log_session(self, proxy):\n        if not self.supports_log_entry_log():\n            raise errors.Unimplemented()\n        return sessions.LogEntryLogSession(proxy=proxy, runtime=self._runtime)",
    "docstring": "Gets the session for retrieving log entry to log mappings.\n\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.logging.LogEntryLogSession) - a\n                ``LogEntryLogSession``\n        raise:  NullArgument - ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_log_entry_log()`` is\n                ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_log_entry_log()`` is ``true``.*"
  },
  {
    "code": "def get_property(self, property_key: str) -> str:\n        self._check_object_exists()\n        return DB.get_hash_value(self.key, property_key)",
    "docstring": "Get a scheduling object property."
  },
  {
    "code": "def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):\n        self.name = name\n        self.fileExtension = extension\n        with open(path, 'r') as f:\n            self.text = f.read()",
    "docstring": "Generic File Read from File Method"
  },
  {
    "code": "def to_frequencies(self, fill=np.nan):\n        an = np.sum(self, axis=1)[:, None]\n        with ignore_invalid():\n            af = np.where(an > 0, self / an, fill)\n        return af",
    "docstring": "Compute allele frequencies.\n\n        Parameters\n        ----------\n        fill : float, optional\n            Value to use when number of allele calls is 0.\n\n        Returns\n        -------\n        af : ndarray, float, shape (n_variants, n_alleles)\n\n        Examples\n        --------\n\n        >>> import allel\n        >>> g = allel.GenotypeArray([[[0, 0], [0, 1]],\n        ...                          [[0, 2], [1, 1]],\n        ...                          [[2, 2], [-1, -1]]])\n        >>> ac = g.count_alleles()\n        >>> ac.to_frequencies()\n        array([[0.75, 0.25, 0.  ],\n               [0.25, 0.5 , 0.25],\n               [0.  , 0.  , 1.  ]])"
  },
  {
    "code": "def LessThan(self, value):\n    self._awql = self._CreateSingleValueCondition(value, '<')\n    return self._query_builder",
    "docstring": "Sets the type of the WHERE clause as \"less than\".\n\n    Args:\n      value: The value to be used in the WHERE condition.\n\n    Returns:\n      The query builder that this WHERE builder links to."
  },
  {
    "code": "def set_output(self, outfile):\n        if self._orig_stdout:\n            sys.stdout = self._orig_stdout\n        self._stream = outfile\n        sys.stdout = _LineWriter(self, self._stream, self.default)",
    "docstring": "Set's the output file, currently only useful with context-managers.\n\n            Note:\n                This function is experimental and may not last."
  },
  {
    "code": "def register_scope(self, scope):\n        if not isinstance(scope, Scope):\n            raise TypeError(\"Invalid scope type.\")\n        assert scope.id not in self.scopes\n        self.scopes[scope.id] = scope",
    "docstring": "Register a scope.\n\n        :param scope: A :class:`invenio_oauth2server.models.Scope` instance."
  },
  {
    "code": "def spkuds(descr):\n    assert len(descr) is 5\n    descr = stypes.toDoubleVector(descr)\n    body = ctypes.c_int()\n    center = ctypes.c_int()\n    framenum = ctypes.c_int()\n    typenum = ctypes.c_int()\n    first = ctypes.c_double()\n    last = ctypes.c_double()\n    begin = ctypes.c_int()\n    end = ctypes.c_int()\n    libspice.spkuds_c(descr, ctypes.byref(body), ctypes.byref(center),\n                      ctypes.byref(framenum), ctypes.byref(typenum),\n                      ctypes.byref(first), ctypes.byref(last),\n                      ctypes.byref(begin), ctypes.byref(end))\n    return body.value, center.value, framenum.value, typenum.value, \\\n           first.value, last.value, begin.value, end.value",
    "docstring": "Unpack the contents of an SPK segment descriptor.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkuds_c.html\n\n    :param descr: An SPK segment descriptor.\n    :type descr: 5-Element Array of floats\n    :return:\n            The NAIF ID code for the body of the segment,\n            The center of motion for body,\n            The ID code for the frame of this segment,\n            The type of SPK segment,\n            The first epoch for which the segment is valid,\n            The last  epoch for which the segment is valid,\n            Beginning DAF address of the segment,\n            Ending DAF address of the segment.\n    :rtype: tuple"
  },
  {
    "code": "def add_nio(self, nio, port_number):\n        if port_number in self._nios:\n            raise DynamipsError(\"Port {} isn't free\".format(port_number))\n        yield from self._hypervisor.send('ethsw add_nio \"{name}\" {nio}'.format(name=self._name, nio=nio))\n        log.info('Ethernet switch \"{name}\" [{id}]: NIO {nio} bound to port {port}'.format(name=self._name,\n                                                                                          id=self._id,\n                                                                                          nio=nio,\n                                                                                          port=port_number))\n        self._nios[port_number] = nio\n        for port_settings in self._ports:\n            if port_settings[\"port_number\"] == port_number:\n                yield from self.set_port_settings(port_number, port_settings)\n                break",
    "docstring": "Adds a NIO as new port on Ethernet switch.\n\n        :param nio: NIO instance to add\n        :param port_number: port to allocate for the NIO"
  },
  {
    "code": "def monkey_patch():\n    reset()\n    time_mod.time = time\n    time_mod.sleep = sleep\n    time_mod.gmtime = gmtime\n    time_mod.localtime = localtime\n    time_mod.ctime = ctime\n    time_mod.asctime = asctime\n    time_mod.strftime = strftime",
    "docstring": "monkey patch `time` module to use out versions"
  },
  {
    "code": "def get_function_for_aws_event(self, record):\n        if 's3' in record:\n            if ':' in record['s3']['configurationId']:\n                return record['s3']['configurationId'].split(':')[-1]\n        arn = None\n        if 'Sns' in record:\n            try:\n                message = json.loads(record['Sns']['Message'])\n                if message.get('command'):\n                    return message['command']\n            except ValueError:\n                pass\n            arn = record['Sns'].get('TopicArn')\n        elif 'dynamodb' in record or 'kinesis' in record:\n            arn = record.get('eventSourceARN')\n        elif 'eventSource' in record and record.get('eventSource') == 'aws:sqs':\n            arn = record.get('eventSourceARN')\n        elif 's3' in record:\n            arn = record['s3']['bucket']['arn']\n        if arn:\n            return self.settings.AWS_EVENT_MAPPING.get(arn)\n        return None",
    "docstring": "Get the associated function to execute for a triggered AWS event\n\n        Support S3, SNS, DynamoDB, kinesis and SQS events"
  },
  {
    "code": "def run_script(pycode):\n    if pycode[0] == \"\\n\":\n        pycode = pycode[1:]\n    pycode.rstrip()\n    pycode = textwrap.dedent(pycode)\n    globs = {}\n    six.exec_(pycode, globs, globs)\n    return globs",
    "docstring": "Run the Python in `pycode`, and return a dict of the resulting globals."
  },
  {
    "code": "def embedding(self, sentences, oov_way='avg'):\n        data_iter = self.data_loader(sentences=sentences)\n        batches = []\n        for token_ids, valid_length, token_types in data_iter:\n            token_ids = token_ids.as_in_context(self.ctx)\n            valid_length = valid_length.as_in_context(self.ctx)\n            token_types = token_types.as_in_context(self.ctx)\n            sequence_outputs = self.bert(token_ids, token_types,\n                                         valid_length.astype(self.dtype))\n            for token_id, sequence_output in zip(token_ids.asnumpy(),\n                                                 sequence_outputs.asnumpy()):\n                batches.append((token_id, sequence_output))\n        return self.oov(batches, oov_way)",
    "docstring": "Get tokens, tokens embedding\n\n        Parameters\n        ----------\n        sentences : List[str]\n            sentences for encoding.\n        oov_way : str, default avg.\n            use **avg**, **sum** or **last** to get token embedding for those out of\n            vocabulary words\n\n        Returns\n        -------\n        List[(List[str], List[ndarray])]\n            List of tokens, and tokens embedding"
  },
  {
    "code": "def extract(self, name):\n        if type(name) == type(''):\n            ndx = self.toc.find(name)\n            if ndx == -1:\n                return None\n        else:\n            ndx = name\n        (dpos, dlen, ulen, flag, typcd, nm) = self.toc.get(ndx)\n        self.lib.seek(self.pkgstart+dpos)\n        rslt = self.lib.read(dlen)\n        if flag == 2:\n            global AES\n            import AES\n            key = rslt[:32]\n            rslt = AES.new(key, AES.MODE_CFB, \"\\0\"*AES.block_size).decrypt(rslt[32:])\n        if flag == 1 or flag == 2:\n            rslt = zlib.decompress(rslt)\n        if typcd == 'M':\n            return (1, rslt)\n        return (0, rslt)",
    "docstring": "Get the contents of an entry.\n\n           NAME is an entry name.\n           Return the tuple (ispkg, contents).\n           For non-Python resoures, ispkg is meaningless (and 0).\n           Used by the import mechanism."
  },
  {
    "code": "def isDone(self):\n        done = pydaq.bool32()\n        self.IsTaskDone(ctypes.byref(done))\n        return done.value",
    "docstring": "Returns true if task is done."
  },
  {
    "code": "def rh45(msg):\n    d = hex2bin(data(msg))\n    if d[38] == '0':\n        return None\n    rh = bin2int(d[39:51]) * 16\n    return rh",
    "docstring": "Radio height.\n\n    Args:\n        msg (String): 28 bytes hexadecimal message string\n\n    Returns:\n        int: radio height in ft"
  },
  {
    "code": "def _original_path(self, path):\n        def components_to_path():\n            if len(path_components) > len(normalized_components):\n                normalized_components.extend(\n                    path_components[len(normalized_components):])\n            sep = self._path_separator(path)\n            normalized_path = sep.join(normalized_components)\n            if path.startswith(sep) and not normalized_path.startswith(sep):\n                normalized_path = sep + normalized_path\n            return normalized_path\n        if self.is_case_sensitive or not path:\n            return path\n        path_components = self._path_components(path)\n        normalized_components = []\n        current_dir = self.root\n        for component in path_components:\n            if not isinstance(current_dir, FakeDirectory):\n                return components_to_path()\n            dir_name, current_dir = self._directory_content(\n                current_dir, component)\n            if current_dir is None or (\n                            isinstance(current_dir, FakeDirectory) and\n                            current_dir._byte_contents is None and\n                            current_dir.st_size == 0):\n                return components_to_path()\n            normalized_components.append(dir_name)\n        return components_to_path()",
    "docstring": "Return a normalized case version of the given path for\n        case-insensitive file systems. For case-sensitive file systems,\n        return path unchanged.\n\n        Args:\n            path: the file path to be transformed\n\n        Returns:\n            A version of path matching the case of existing path elements."
  },
  {
    "code": "def build(self, stmts=None, set_check_var=True, invert=False):\n        out = \"\"\n        if set_check_var:\n            out += self.check_var + \" = False\\n\"\n        out += self.out()\n        if stmts is not None:\n            out += \"if \" + (\"not \" if invert else \"\") + self.check_var + \":\" + \"\\n\" + openindent + \"\".join(stmts) + closeindent\n        return out",
    "docstring": "Construct code for performing the match then executing stmts."
  },
  {
    "code": "def copy(self):\n        new = type(self)(str(self))\n        new._init_from_channel(self)\n        return new",
    "docstring": "Returns a copy of this channel"
  },
  {
    "code": "def canonical_stylename(font):\n  from fontbakery.constants import (STATIC_STYLE_NAMES,\n                                    VARFONT_SUFFIXES)\n  from fontbakery.profiles.shared_conditions import is_variable_font\n  from fontTools.ttLib import TTFont\n  valid_style_suffixes = [name.replace(' ', '') for name in STATIC_STYLE_NAMES]\n  filename = os.path.basename(font)\n  basename = os.path.splitext(filename)[0]\n  s = suffix(font)\n  varfont = os.path.exists(font) and is_variable_font(TTFont(font))\n  if ('-' in basename and\n      (s in VARFONT_SUFFIXES and varfont)\n      or (s in valid_style_suffixes and not varfont)):\n    return s",
    "docstring": "Returns the canonical stylename of a given font."
  },
  {
    "code": "def process_parameters(parameters):\n    if not parameters:\n        return {}\n    params = copy.copy(parameters)\n    for param_name in parameters:\n        value = parameters[param_name]\n        server_param_name = re.sub(r'_(\\w)', lambda m: m.group(1).upper(), param_name)\n        if isinstance(value, dict):\n            value = process_parameters(value)\n        params[server_param_name] = value\n        if server_param_name != param_name:\n            del params[param_name]\n    return params",
    "docstring": "Allows the use of Pythonic-style parameters with underscores instead of camel-case.\n\n    :param parameters: The parameters object.\n    :type parameters: dict\n    :return: The processed parameters.\n    :rtype: dict"
  },
  {
    "code": "def fill_n_todo(self):\n        left = self.left\n        right = self.right\n        top = self.top\n        bottom = self.bottom\n        for i in xrange(self.n_chunks):\n            self.n_todo.ravel()[i] = np.sum([left.ravel()[i].n_todo,\n                                            right.ravel()[i].n_todo,\n                                            top.ravel()[i].n_todo,\n                                            bottom.ravel()[i].n_todo])",
    "docstring": "Calculate and record the number of edge pixels left to do on each tile"
  },
  {
    "code": "def primary_key_field(self):\n        return [field for field in self.instance._meta.fields if field.primary_key][0]",
    "docstring": "Return the primary key field.\n\n        Is `id` in most cases. Is `history_id` for Historical models."
  },
  {
    "code": "def available_domains(self):\n        if not hasattr(self, '_available_domains'):\n            url = 'http://{0}/request/domains/format/json/'.format(\n                self.api_domain)\n            req = requests.get(url)\n            domains = req.json()\n            setattr(self, '_available_domains', domains)\n        return self._available_domains",
    "docstring": "Return list of available domains for use in email address."
  },
  {
    "code": "async def update(self, fields=''):\n    path = 'Users/{{UserId}}/Items/{}'.format(self.id)\n    info = await self.connector.getJson(path,\n                                        remote=False,\n                                        Fields='Path,Overview,'+fields\n    )\n    self.object_dict.update(info)\n    self.extras = {}\n    return self",
    "docstring": "reload object info from emby\n\n    |coro|\n\n    Parameters\n    ----------\n    fields : str\n      additional fields to request when updating\n\n    See Also\n    --------\n      refresh : same thing\n      send :\n      post :"
  },
  {
    "code": "def guess_project_dir():\n    projname = settings.SETTINGS_MODULE.split(\".\",1)[0]\n    projmod = import_module(projname)\n    projdir = os.path.dirname(projmod.__file__)\n    if os.path.isfile(os.path.join(projdir,\"manage.py\")):\n        return projdir\n    projdir = os.path.abspath(os.path.join(projdir, os.path.pardir))\n    if os.path.isfile(os.path.join(projdir,\"manage.py\")):\n        return projdir\n    msg = \"Unable to determine the Django project directory;\"\\\n          \" use --project-dir to specify it\"\n    raise RuntimeError(msg)",
    "docstring": "Find the top-level Django project directory.\n\n    This function guesses the top-level Django project directory based on\n    the current environment.  It looks for module containing the currently-\n    active settings module, in both pre-1.4 and post-1.4 layours."
  },
  {
    "code": "def collect(self):\n        from dvc.scm import SCM\n        from dvc.utils import is_binary\n        from dvc.repo import Repo\n        from dvc.exceptions import NotDvcRepoError\n        self.info[self.PARAM_DVC_VERSION] = __version__\n        self.info[self.PARAM_IS_BINARY] = is_binary()\n        self.info[self.PARAM_USER_ID] = self._get_user_id()\n        self.info[self.PARAM_SYSTEM_INFO] = self._collect_system_info()\n        try:\n            scm = SCM(root_dir=Repo.find_root())\n            self.info[self.PARAM_SCM_CLASS] = type(scm).__name__\n        except NotDvcRepoError:\n            pass",
    "docstring": "Collect analytics report."
  },
  {
    "code": "def remote_delete(self, remote_path, r_st):\n        if S_ISDIR(r_st.st_mode):\n            for item in self.sftp.listdir_attr(remote_path):\n                full_path = path_join(remote_path, item.filename)\n                self.remote_delete(full_path, item)\n            self.sftp.rmdir(remote_path)\n        else:\n            try:\n                self.sftp.remove(remote_path)\n            except FileNotFoundError as e:\n                self.logger.error(\n                    \"error while removing {}. trace: {}\".format(remote_path, e)\n                )",
    "docstring": "Remove the remote directory node."
  },
  {
    "code": "def _generate(self):\n        part = creator.Particle(\n            [random.uniform(-1, 1)\n             for _ in range(len(self.value_means))])\n        part.speed = [\n            random.uniform(-self.max_speed, self.max_speed)\n            for _ in range(len(self.value_means))]\n        part.smin = -self.max_speed\n        part.smax = self.max_speed\n        part.ident = None\n        part.neighbours = None\n        return part",
    "docstring": "Generates a particle using the creator function.\n\n        Notes\n        -----\n        Position and speed are uniformly randomly seeded within\n        allowed bounds. The particle also has speed limit settings\n        taken from global values.\n\n        Returns\n        -------\n        part : particle object\n            A particle used during optimisation."
  },
  {
    "code": "def _process_assignments(self, anexec, contents, mode=\"insert\"):\n        for assign in self.RE_ASSIGN.finditer(contents):\n            assignee = assign.group(\"assignee\").strip()\n            target = re.split(r\"[(%\\s]\", assignee)[0].lower()\n            if target in self._intrinsic:\n                continue\n            if target in anexec.members or \\\n               target in anexec.parameters or \\\n               (isinstance(anexec, Function) and target.lower() == anexec.name.lower()):\n                if mode == \"insert\":\n                    anexec.add_assignment(re.split(r\"[(\\s]\", assignee)[0])\n                elif mode == \"delete\":\n                    try:\n                        index = element.assignments.index(assign)\n                        del element.assignments[index]\n                    except ValueError:\n                        pass",
    "docstring": "Extracts all variable assignments from the body of the executable.\n\n        :arg mode: for real-time update; either 'insert', 'delete' or 'replace'."
  },
  {
    "code": "def delete(self, doc_id: str) -> bool:\n        try:\n            self.instance.delete(self.index, self.doc_type, doc_id)\n        except RequestError as ex:\n            logging.error(ex)\n            return False\n        else:\n            return True",
    "docstring": "Delete a document with id."
  },
  {
    "code": "def parse_game_event(self, ge):\n        if ge.name == \"dota_combatlog\":\n            if ge.keys[\"type\"] == 4:\n                try:\n                    source = self.dp.combat_log_names.get(ge.keys[\"sourcename\"],\n                                                          \"unknown\")\n                    target = self.dp.combat_log_names.get(ge.keys[\"targetname\"],\n                                                          \"unknown\")\n                    target_illusion = ge.keys[\"targetillusion\"]\n                    timestamp = ge.keys[\"timestamp\"]\n                    if (target.startswith(\"npc_dota_hero\") and not\n                        target_illusion):\n                        self.kills.append({\n                            \"target\": target,\n                            \"source\": source,\n                            \"timestamp\": timestamp,\n                            \"tick\": self.tick,\n                            })\n                    elif source.startswith(\"npc_dota_hero\"):\n                        self.heroes[source].creep_kill(target, timestamp)\n                except KeyError:\n                    pass",
    "docstring": "Game events contain the combat log as well as 'chase_hero' events which\n        could be interesting"
  },
  {
    "code": "async def stop(self, _task=None):\n        self._logger.info(\"Stopping adapter wrapper\")\n        if self._task.stopped:\n            return\n        for task in self._task.subtasks:\n            await task.stop()\n        self._logger.debug(\"Stopping underlying adapter %s\", self._adapter.__class__.__name__)\n        await self._execute(self._adapter.stop_sync)",
    "docstring": "Stop the device adapter.\n\n        See :meth:`AbstractDeviceAdapter.stop`."
  },
  {
    "code": "def join(self, distbase, location):\n        sep = ''\n        if distbase and distbase[-1] not in (':', '/'):\n            sep = '/'\n        return distbase + sep + location",
    "docstring": "Join 'distbase' and 'location' in such way that the\n        result is a valid scp destination."
  },
  {
    "code": "def Transfer(self, wallet, from_addr, to_addr, amount, tx_attributes=None):\n        if not tx_attributes:\n            tx_attributes = []\n        sb = ScriptBuilder()\n        sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'transfer',\n                                           [PromptUtils.parse_param(from_addr, wallet), PromptUtils.parse_param(to_addr, wallet),\n                                            PromptUtils.parse_param(amount)])\n        tx, fee, results, num_ops, engine_success = test_invoke(sb.ToArray(), wallet, [], from_addr=from_addr, invoke_attrs=tx_attributes)\n        return tx, fee, results",
    "docstring": "Transfer a specified amount of the NEP5Token to another address.\n\n        Args:\n            wallet (neo.Wallets.Wallet): a wallet instance.\n            from_addr (str): public address of the account to transfer the given amount from.\n            to_addr (str): public address of the account to transfer the given amount to.\n            amount (int): quantity to send.\n            tx_attributes (list): a list of TransactionAtribute objects.\n\n        Returns:\n            tuple:\n                InvocationTransaction: the transaction.\n                int: the transaction fee.\n                list: the neo VM evaluationstack results."
  },
  {
    "code": "def has_ext(path_name, *, multiple=None, if_all_ext=False):\n    base = os.path.basename(path_name)\n    count = base.count(EXT)\n    if not if_all_ext and base[0] == EXT and count != 0:\n        count -= 1\n    if multiple is None:\n        return count >= 1\n    elif multiple:\n        return count > 1\n    else:\n        return count == 1",
    "docstring": "Determine if the given path name has an extension"
  },
  {
    "code": "def sample_binned(self, wavelengths=None, flux_unit=None, **kwargs):\n        x = self._validate_binned_wavelengths(wavelengths)\n        i = np.searchsorted(self.binset, x)\n        if not np.allclose(self.binset[i].value, x.value):\n            raise exceptions.InterpolationNotAllowed(\n                'Some or all wavelength values are not in binset.')\n        y = self.binflux[i]\n        if flux_unit is None:\n            flux = y\n        else:\n            flux = units.convert_flux(x, y, flux_unit, **kwargs)\n        return flux",
    "docstring": "Sample binned observation without interpolation.\n\n        To sample unbinned data, use ``__call__``.\n\n        Parameters\n        ----------\n        wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`\n            Wavelength values for sampling.\n            If not a Quantity, assumed to be in Angstrom.\n            If `None`, `binset` is used.\n\n        flux_unit : str or `~astropy.units.core.Unit` or `None`\n            Flux is converted to this unit.\n            If not given, internal unit is used.\n\n        kwargs : dict\n            Keywords acceptable by :func:`~synphot.units.convert_flux`.\n\n        Returns\n        -------\n        flux : `~astropy.units.quantity.Quantity`\n            Binned flux in given unit.\n\n        Raises\n        ------\n        synphot.exceptions.InterpolationNotAllowed\n            Interpolation of binned data is not allowed."
  },
  {
    "code": "def docs_client(self):\n        if not hasattr(self, '_docs_client'):\n            client = DocsClient()\n            client.ClientLogin(self.google_user, self.google_password,\n                               SOURCE_NAME)\n            self._docs_client = client\n        return self._docs_client",
    "docstring": "A DocsClient singleton, used to look up spreadsheets\n        by name."
  },
  {
    "code": "def unpack_rpc_response(status, response=None, rpc_id=0, address=0):\n    status_code = status & ((1 << 6) - 1)\n    if address == 8:\n        status_code &= ~(1 << 7)\n    if status == 0:\n        raise BusyRPCResponse()\n    elif status == 2:\n        raise RPCNotFoundError(\"rpc %d:%04X not found\" % (address, rpc_id))\n    elif status == 3:\n        raise RPCErrorCode(status_code)\n    elif status == 0xFF:\n        raise TileNotFoundError(\"tile %d not found\" % address)\n    elif status_code != 0:\n        raise RPCErrorCode(status_code)\n    if response is None:\n        response = b''\n    return response",
    "docstring": "Unpack an RPC status back in to payload or exception."
  },
  {
    "code": "def render( self, tag, single, between, kwargs ):\n        out = \"<%s\" % tag\n        for key, value in list( kwargs.items( ) ):\n            if value is not None:\n                key = key.strip('_')\n                if key == 'http_equiv':\n                    key = 'http-equiv'\n                elif key == 'accept_charset':\n                    key = 'accept-charset'\n                out = \"%s %s=\\\"%s\\\"\" % ( out, key, escape( value ) )\n            else:\n                out = \"%s %s\" % ( out, key )\n        if between is not None:\n            out = \"%s>%s</%s>\" % ( out, between, tag )\n        else:\n            if single:\n                out = \"%s />\" % out\n            else:\n                out = \"%s>\" % out\n        if self.parent is not None:\n            self.parent.content.append( out )\n        else:\n            return out",
    "docstring": "Append the actual tags to content."
  },
  {
    "code": "def get_command(self, command_input, docker_object=None, buffer=None, size=None):\n        logger.debug(\"get command for command input %r\", command_input)\n        if not command_input:\n            return\n        if command_input[0] in [\"/\"]:\n            command_name = command_input[0]\n            unparsed_command_args = shlex.split(command_input[1:])\n        else:\n            command_input_list = shlex.split(command_input)\n            command_name = command_input_list[0]\n            unparsed_command_args = command_input_list[1:]\n        try:\n            CommandClass = commands_mapping[command_name]\n        except KeyError:\n            logger.info(\"no such command: %r\", command_name)\n            raise NoSuchCommand(\"There is no such command: %s\" % command_name)\n        else:\n            cmd = CommandClass(ui=self.ui, docker_backend=self.docker_backend,\n                               docker_object=docker_object, buffer=buffer, size=size)\n            cmd.process_args(unparsed_command_args)\n            return cmd",
    "docstring": "return command instance which is the actual command to be executed\n\n        :param command_input: str, command name and its args: \"command arg arg2=val opt\"\n        :param docker_object:\n        :param buffer:\n        :param size: tuple, so we can call urwid.keypress(size, ...)\n        :return: instance of Command"
  },
  {
    "code": "def p2x(self, p):\n        if hasattr(p, 'keys'):\n            dp = BufferDict(p, keys=self.g.keys())._buf[:self.meanflat.size] - self.meanflat\n        else:\n            dp = numpy.asarray(p).reshape(-1) - self.meanflat\n        return self.vec_isig.dot(dp)",
    "docstring": "Map parameters ``p`` to vector in x-space.\n\n        x-space is a vector space of dimension ``p.size``. Its axes are\n        in the directions specified by the eigenvectors of ``p``'s covariance\n        matrix, and distance along an axis is in units of the standard\n        deviation in that direction."
  },
  {
    "code": "def parse_multi_object_delete_response(data):\n    root = S3Element.fromstring('MultiObjectDeleteResult', data)\n    return [\n        MultiDeleteError(errtag.get_child_text('Key'),\n                         errtag.get_child_text('Code'),\n                         errtag.get_child_text('Message'))\n        for errtag in root.findall('Error')\n    ]",
    "docstring": "Parser for Multi-Object Delete API response.\n\n    :param data: XML response body content from service.\n\n    :return: Returns list of error objects for each delete object that\n    had an error."
  },
  {
    "code": "def has_read_permission(self, request, path):\n        user = request.user\n        if not user.is_authenticated():\n            return False\n        elif user.is_superuser:\n            return True\n        elif user.is_staff:\n            return True\n        else:\n            return False",
    "docstring": "Just return True if the user is an authenticated staff member.\n        Extensions could base the permissions on the path too."
  },
  {
    "code": "def tofile(self, filepath=None):\n        if filepath is None:\n            with NamedTemporaryFile(prefix='%s_' % self.alias, suffix='.ini', delete=False) as f:\n                filepath = f.name\n        else:\n            filepath = os.path.abspath(filepath)\n            if os.path.isdir(filepath):\n                filepath = os.path.join(filepath, '%s.ini' % self.alias)\n        with open(filepath, 'w') as target_file:\n            target_file.write(self.format())\n            target_file.flush()\n        return filepath",
    "docstring": "Saves configuration into a file and returns its path.\n\n        Convenience method.\n\n        :param str|unicode filepath: Filepath to save configuration into.\n            If not provided a temporary file will be automatically generated.\n\n        :rtype: str|unicode"
  },
  {
    "code": "def _api_path(self, item):\n        if self.base_url is None:\n            raise NotImplementedError(\"base_url not set\")\n        path = \"/\".join([x.blob[\"id\"] for x in item.path])\n        return \"/\".join([self.base_url, path])",
    "docstring": "Get the API path for the current cursor position."
  },
  {
    "code": "def xml_to_str(tree, encoding=None, xml_declaration=False):\n    if xml_declaration and not encoding:\n        raise ValueError(\"'xml_declaration' is not supported when 'encoding' is None\")\n    if encoding:\n        return tostring(tree, encoding=encoding, xml_declaration=True)\n    return tostring(tree, encoding=text_type, xml_declaration=False)",
    "docstring": "Serialize an XML tree. Returns unicode if 'encoding' is None. Otherwise, we return encoded 'bytes'."
  },
  {
    "code": "def is_little_endian(array):\n    if numpy.little_endian:\n        machine_little = True\n    else:\n        machine_little = False\n    byteorder = array.dtype.base.byteorder\n    return (byteorder == '<') or (machine_little and byteorder == '=')",
    "docstring": "Return True if array is little endian, False otherwise.\n\n    Parameters\n    ----------\n    array: numpy array\n        A numerical python array.\n\n    Returns\n    -------\n    Truth value:\n        True for little-endian\n\n    Notes\n    -----\n    Strings are neither big or little endian.  The input must be a simple numpy\n    array, not an array with fields."
  },
  {
    "code": "def versioned_bucket_lister(bucket, prefix='', delimiter='',\n                            key_marker='', version_id_marker='', headers=None):\n    more_results = True\n    k = None\n    while more_results:\n        rs = bucket.get_all_versions(prefix=prefix, key_marker=key_marker,\n                                     version_id_marker=version_id_marker,\n                                     delimiter=delimiter, headers=headers,\n                                     max_keys=999)\n        for k in rs:\n            yield k\n        key_marker = rs.next_key_marker\n        version_id_marker = rs.next_version_id_marker\n        more_results= rs.is_truncated",
    "docstring": "A generator function for listing versions in a bucket."
  },
  {
    "code": "def call_cur(f):\n  \"decorator for opening a connection and passing a cursor to the function\"\n  @functools.wraps(f)\n  def f2(self, *args, **kwargs):\n    with self.withcur() as cur:\n      return f(self, cur, *args, **kwargs)\n  return f2",
    "docstring": "decorator for opening a connection and passing a cursor to the function"
  },
  {
    "code": "def selectrangeopenleft(table, field, minv, maxv, complement=False):\n    minv = Comparable(minv)\n    maxv = Comparable(maxv)\n    return select(table, field, lambda v: minv <= v < maxv,\n                  complement=complement)",
    "docstring": "Select rows where the given field is greater than or equal to `minv` and\n    less than `maxv`."
  },
  {
    "code": "def __notify(self, sender, content):\n        if self.handle_message is not None:\n            try:\n                self.handle_message(sender, content)\n            except Exception as ex:\n                logging.exception(\"Error calling message listener: %s\", ex)",
    "docstring": "Calls back listener when a message is received"
  },
  {
    "code": "def stub_batch(cls, size, **kwargs):\n        return [cls.stub(**kwargs) for _ in range(size)]",
    "docstring": "Stub a batch of instances of the given class, with overriden attrs.\n\n        Args:\n            size (int): the number of instances to stub\n\n        Returns:\n            object list: the stubbed instances"
  },
  {
    "code": "def _decrypt_object(obj, translate_newlines=False):\n    if salt.utils.stringio.is_readable(obj):\n        return _decrypt_object(obj.getvalue(), translate_newlines)\n    if isinstance(obj, six.string_types):\n        try:\n            return _decrypt_ciphertext(obj,\n                                       translate_newlines=translate_newlines)\n        except (fernet.InvalidToken, TypeError):\n            return obj\n    elif isinstance(obj, dict):\n        for key, value in six.iteritems(obj):\n            obj[key] = _decrypt_object(value,\n                                       translate_newlines=translate_newlines)\n        return obj\n    elif isinstance(obj, list):\n        for key, value in enumerate(obj):\n            obj[key] = _decrypt_object(value,\n                                       translate_newlines=translate_newlines)\n        return obj\n    else:\n        return obj",
    "docstring": "Recursively try to decrypt any object.\n    Recur on objects that are not strings.\n    Decrypt strings that are valid Fernet tokens.\n    Return the rest unchanged."
  },
  {
    "code": "def generate_host_passthrough(self, vcpu_num):\n        cpu = ET.Element('cpu', mode='host-passthrough')\n        cpu.append(self.generate_topology(vcpu_num))\n        if vcpu_num > 1:\n            cpu.append(self.generate_numa(vcpu_num))\n        return cpu",
    "docstring": "Generate host-passthrough XML cpu node\n\n        Args:\n            vcpu_num(str): number of virtual CPUs\n\n        Returns:\n            lxml.etree.Element: CPU XML node"
  },
  {
    "code": "def database_to_excel(engine, excel_file_path):\n    from sqlalchemy import MetaData, select\n    metadata = MetaData()\n    metadata.reflect(engine)\n    writer = pd.ExcelWriter(excel_file_path)\n    for table in metadata.tables.values():\n        sql = select([table])\n        df = pd.read_sql(sql, engine)\n        df.to_excel(writer, table.name, index=False)\n    writer.save()",
    "docstring": "Export database to excel.\n\n    :param engine: \n    :param excel_file_path:"
  },
  {
    "code": "def _set_WorkingDir(self, path):\n        self._curr_working_dir = path\n        try:\n            mkdir(self.WorkingDir)\n        except OSError:\n            pass",
    "docstring": "Sets the working directory"
  },
  {
    "code": "def _get_nonce(self, url):\n        action = LOG_JWS_GET_NONCE()\n        if len(self._nonces) > 0:\n            with action:\n                nonce = self._nonces.pop()\n                action.add_success_fields(nonce=nonce)\n                return succeed(nonce)\n        else:\n            with action.context():\n                return (\n                    DeferredContext(self.head(url))\n                    .addCallback(self._add_nonce)\n                    .addCallback(lambda _: self._nonces.pop())\n                    .addCallback(tap(\n                        lambda nonce: action.add_success_fields(nonce=nonce)))\n                    .addActionFinish())",
    "docstring": "Get a nonce to use in a request, removing it from the nonces on hand."
  },
  {
    "code": "def validate_auth_mechanism_properties(option, value):\n    value = validate_string(option, value)\n    props = {}\n    for opt in value.split(','):\n        try:\n            key, val = opt.split(':')\n        except ValueError:\n            raise ValueError(\"auth mechanism properties must be \"\n                             \"key:value pairs like SERVICE_NAME:\"\n                             \"mongodb, not %s.\" % (opt,))\n        if key not in _MECHANISM_PROPS:\n            raise ValueError(\"%s is not a supported auth \"\n                             \"mechanism property. Must be one of \"\n                             \"%s.\" % (key, tuple(_MECHANISM_PROPS)))\n        if key == 'CANONICALIZE_HOST_NAME':\n            props[key] = validate_boolean_or_string(key, val)\n        else:\n            props[key] = val\n    return props",
    "docstring": "Validate authMechanismProperties."
  },
  {
    "code": "def draw_scores(self):\n        x1, y1 = self.WIDTH - self.BORDER - 200 - 2 * self.BORDER, self.BORDER\n        width, height = 100, 60\n        self.screen.fill((255, 255, 255), (x1, 0, self.WIDTH - x1, height + y1))\n        self._draw_score_box(self.score_label, self.score, (x1, y1), (width, height))\n        x2 = x1 + width + self.BORDER\n        self._draw_score_box(self.best_label, self.manager.score, (x2, y1), (width, height))\n        return (x1, y1), (x2, y1), width, height",
    "docstring": "Draw the current and best score"
  },
  {
    "code": "def render(opts, functions, states=None, proxy=None, context=None):\n    if context is None:\n        context = {}\n    pack = {'__salt__': functions,\n            '__grains__': opts.get('grains', {}),\n            '__context__': context}\n    if states:\n        pack['__states__'] = states\n    pack['__proxy__'] = proxy or {}\n    ret = LazyLoader(\n        _module_dirs(\n            opts,\n            'renderers',\n            'render',\n            ext_type_dirs='render_dirs',\n        ),\n        opts,\n        tag='render',\n        pack=pack,\n    )\n    rend = FilterDictWrapper(ret, '.render')\n    if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']):\n        err = ('The renderer {0} is unavailable, this error is often because '\n               'the needed software is unavailable'.format(opts['renderer']))\n        log.critical(err)\n        raise LoaderError(err)\n    return rend",
    "docstring": "Returns the render modules"
  },
  {
    "code": "def get_dates_file(path):\n    with open(path) as f:\n        dates = f.readlines()\n    return [(convert_time_string(date_string.split(\" \")[0]), float(date_string.split(\" \")[1]))\n            for date_string in dates]",
    "docstring": "parse dates file of dates and probability of choosing"
  },
  {
    "code": "def thread_setup(read_and_decode_fn, example_serialized, num_threads):\n        decoded_data = list()\n        for _ in range(num_threads):\n            decoded_data.append(read_and_decode_fn(example_serialized))\n        return decoded_data",
    "docstring": "Sets up the threads within each reader"
  },
  {
    "code": "def _get_index(self, beacon_config, label):\n        indexes = [index for index, item in enumerate(beacon_config) if label in item]\n        if not indexes:\n            return -1\n        else:\n            return indexes[0]",
    "docstring": "Return the index of a labeled config item in the beacon config, -1 if the index is not found"
  },
  {
    "code": "def edges(self, tail_head_iter):\n        edge = self._edge_plain\n        quote = self._quote_edge\n        lines = (edge % (quote(t), quote(h)) for t, h in tail_head_iter)\n        self.body.extend(lines)",
    "docstring": "Create a bunch of edges.\n\n        Args:\n            tail_head_iter: Iterable of ``(tail_name, head_name)`` pairs."
  },
  {
    "code": "def cmd_led(self, args):\n        if len(args) < 3:\n            print(\"Usage: led RED GREEN BLUE <RATE>\")\n            return\n        pattern = [0] * 24\n        pattern[0] = int(args[0])\n        pattern[1] = int(args[1])\n        pattern[2] = int(args[2])\n        if len(args) == 4:\n            plen = 4\n            pattern[3] = int(args[3])\n        else:\n            plen = 3\n        self.master.mav.led_control_send(self.settings.target_system,\n                                         self.settings.target_component,\n                                         0, 0, plen, pattern)",
    "docstring": "send LED pattern as override"
  },
  {
    "code": "def _wait_for_js(self):\n    if not hasattr(self, 'browser'):\n        return\n    if hasattr(self, '_js_vars') and self._js_vars:\n        EmptyPromise(\n            lambda: _are_js_vars_defined(self.browser, self._js_vars),\n            u\"JavaScript variables defined: {0}\".format(\", \".join(self._js_vars))\n        ).fulfill()\n    if hasattr(self, '_requirejs_deps') and self._requirejs_deps:\n        EmptyPromise(\n            lambda: _are_requirejs_deps_loaded(self.browser, self._requirejs_deps),\n            u\"RequireJS dependencies loaded: {0}\".format(\", \".join(self._requirejs_deps)),\n            try_limit=5\n        ).fulfill()",
    "docstring": "Class method added by the decorators to allow\n    decorated classes to manually re-check JavaScript\n    dependencies.\n\n    Expect that `self` is a class that:\n    1) Has been decorated with either `js_defined` or `requirejs`\n    2) Has a `browser` property\n\n    If either (1) or (2) is not satisfied, then do nothing."
  },
  {
    "code": "def iter_starred(self, sort=None, direction=None, number=-1, etag=None):\n        from .repos import Repository\n        params = {'sort': sort, 'direction': direction}\n        self._remove_none(params)\n        url = self.starred_urlt.expand(owner=None, repo=None)\n        return self._iter(int(number), url, Repository, params, etag)",
    "docstring": "Iterate over repositories starred by this user.\n\n        .. versionchanged:: 0.5\n           Added sort and direction parameters (optional) as per the change in\n           GitHub's API.\n\n        :param int number: (optional), number of starred repos to return.\n            Default: -1, returns all available repos\n        :param str sort: (optional), either 'created' (when the star was\n            created) or 'updated' (when the repository was last pushed to)\n        :param str direction: (optional), either 'asc' or 'desc'. Default:\n            'desc'\n        :param str etag: (optional), ETag from a previous request to the same\n            endpoint\n        :returns: generator of :class:`Repository <github3.repos.Repository>`"
  },
  {
    "code": "def on_draw(self):\n        if self.program:\n            self.program.draw(self.gl_primitive_type)\n        else:\n            logger.debug(\"Skipping drawing visual `%s` because the program \"\n                         \"has not been built yet.\", self)",
    "docstring": "Draw the visual."
  },
  {
    "code": "def fit(self, features, classes):\n        classes = self.le.fit_transform(classes)\n        X = []\n        self.mu = []\n        self.Z = []\n        for i in np.unique(classes):\n            X.append(features[classes == i])\n            self.mu.append(np.mean(X[i],axis=0))\n            if self.d == 'mahalanobis':\n                self.Z.append(np.cov(X[i].transpose()))\n        return self",
    "docstring": "Constructs the DistanceClassifier from the provided training data\n\n        Parameters\n        ----------\n        features: array-like {n_samples, n_features}\n            Feature matrix\n        classes: array-like {n_samples}\n            List of class labels for prediction\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "async def mark_fixed(self, *, comment: str = None):\n        params = {\n            \"system_id\": self.system_id\n        }\n        if comment:\n            params[\"comment\"] = comment\n        self._data = await self._handler.mark_fixed(**params)\n        return self",
    "docstring": "Mark fixes.\n\n        :param comment: Reason machine is fixed.\n        :type comment: `str`"
  },
  {
    "code": "def parents(self) -> List[str]:\n        parents = []\n        for p in self._c_object.parents:\n            parents.append(p.hexsha)\n        return parents",
    "docstring": "Return the list of parents SHAs.\n\n        :return: List[str] parents"
  },
  {
    "code": "def genhash(self, package, code):\n        return hex(checksum(\n            hash_sep.join(\n                str(item) for item in (VERSION_STR,)\n                + self.__reduce__()[1]\n                + (package, code)\n            ).encode(default_encoding),\n        ))",
    "docstring": "Generate a hash from code."
  },
  {
    "code": "def total(self):\n        url = \"/stats/total\"\n        result = self._get(url)\n        return StatModel.parse(result)",
    "docstring": "Get a list of counts for all of Unsplash\n\n        :return [Stat]: The Unsplash Stat."
  },
  {
    "code": "def _get_files(self) -> Iterator[str]:\n        path = os.path.abspath(self.path)\n        if os.path.isfile(path):\n            path = os.path.dirname(path)\n        for path in self._get_parents(path):\n            for file_path in self._get_files_from_dir(path):\n                yield file_path",
    "docstring": "Return paths to all requirements files"
  },
  {
    "code": "def get_users():\n    try:\n        recs = psutil.users()\n        return [dict(x._asdict()) for x in recs]\n    except AttributeError:\n        try:\n            import utmp\n            result = []\n            while True:\n                rec = utmp.utmpaccess.getutent()\n                if rec is None:\n                    return result\n                elif rec[0] == 7:\n                    started = rec[8]\n                    if isinstance(started, tuple):\n                        started = started[0]\n                    result.append({'name': rec[4], 'terminal': rec[2],\n                                   'started': started, 'host': rec[5]})\n        except ImportError:\n            return False",
    "docstring": "Return logged-in users.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' ps.get_users"
  },
  {
    "code": "def suspend(self):\n        status = yield from self.get_status()\n        if status == \"running\":\n            yield from self._hypervisor.send('vm suspend \"{name}\"'.format(name=self._name))\n            self.status = \"suspended\"\n            log.info('Router \"{name}\" [{id}] has been suspended'.format(name=self._name, id=self._id))",
    "docstring": "Suspends this router."
  },
  {
    "code": "def render_linked_js(self, js_files: Iterable[str]) -> str:\n        paths = []\n        unique_paths = set()\n        for path in js_files:\n            if not is_absolute(path):\n                path = self.static_url(path)\n            if path not in unique_paths:\n                paths.append(path)\n                unique_paths.add(path)\n        return \"\".join(\n            '<script src=\"'\n            + escape.xhtml_escape(p)\n            + '\" type=\"text/javascript\"></script>'\n            for p in paths\n        )",
    "docstring": "Default method used to render the final js links for the\n        rendered webpage.\n\n        Override this method in a sub-classed controller to change the output."
  },
  {
    "code": "def tables_list(self, dataset_name, max_results=0, page_token=None):\n    url = Api._ENDPOINT +\\\n        (Api._TABLES_PATH % (dataset_name.project_id, dataset_name.dataset_id, '', ''))\n    args = {}\n    if max_results != 0:\n      args['maxResults'] = max_results\n    if page_token is not None:\n      args['pageToken'] = page_token\n    return google.datalab.utils.Http.request(url, args=args, credentials=self.credentials)",
    "docstring": "Issues a request to retrieve a list of tables.\n\n    Args:\n      dataset_name: the name of the dataset to enumerate.\n      max_results: an optional maximum number of tables to retrieve.\n      page_token: an optional token to continue the retrieval.\n    Returns:\n      A parsed result object.\n    Raises:\n      Exception if there is an error performing the operation."
  },
  {
    "code": "async def _sasl_abort(self, timeout=False):\n        if timeout:\n            self.logger.error('SASL authentication timed out: aborting.')\n        else:\n            self.logger.error('SASL authentication aborted.')\n        if self._sasl_timer:\n            self._sasl_timer.cancel()\n            self._sasl_timer = None\n        await self.rawmsg('AUTHENTICATE', ABORT_MESSAGE)\n        await self._capability_negotiated('sasl')",
    "docstring": "Abort SASL authentication."
  },
  {
    "code": "def interpolate(self, df):\n        f0 = self.f0.decompose().value\n        N = (self.size - 1) * (self.df.decompose().value / df) + 1\n        fsamples = numpy.arange(0, numpy.rint(N), dtype=self.dtype) * df + f0\n        out = type(self)(numpy.interp(fsamples, self.frequencies.value,\n                                      self.value))\n        out.__array_finalize__(self)\n        out.f0 = f0\n        out.df = df\n        return out",
    "docstring": "Interpolate this `FrequencySeries` to a new resolution.\n\n        Parameters\n        ----------\n        df : `float`\n            desired frequency resolution of the interpolated `FrequencySeries`,\n            in Hz\n\n        Returns\n        -------\n        out : `FrequencySeries`\n            the interpolated version of the input `FrequencySeries`\n\n        See Also\n        --------\n        numpy.interp\n            for the underlying 1-D linear interpolation scheme"
  },
  {
    "code": "def register_onchain_secret(\n        channel_state: NettingChannelState,\n        secret: Secret,\n        secrethash: SecretHash,\n        secret_reveal_block_number: BlockNumber,\n        delete_lock: bool = True,\n) -> None:\n    our_state = channel_state.our_state\n    partner_state = channel_state.partner_state\n    register_onchain_secret_endstate(\n        our_state,\n        secret,\n        secrethash,\n        secret_reveal_block_number,\n        delete_lock,\n    )\n    register_onchain_secret_endstate(\n        partner_state,\n        secret,\n        secrethash,\n        secret_reveal_block_number,\n        delete_lock,\n    )",
    "docstring": "This will register the onchain secret and set the lock to the unlocked stated.\n\n    Even though the lock is unlocked it is *not* claimed. The capacity will\n    increase once the next balance proof is received."
  },
  {
    "code": "def messages(self):\n        return int(math.floor(((self.limit.unit_value - self.level) /\n                               self.limit.unit_value) * self.limit.value))",
    "docstring": "Return remaining messages before limiting."
  },
  {
    "code": "def parent(self):\n        if TextBlockHelper.get_fold_lvl(self._trigger) > 0 and \\\n                self._trigger.blockNumber():\n            block = self._trigger.previous()\n            ref_lvl = self.trigger_level - 1\n            while (block.blockNumber() and\n                    (not TextBlockHelper.is_fold_trigger(block) or\n                     TextBlockHelper.get_fold_lvl(block) > ref_lvl)):\n                block = block.previous()\n            try:\n                return FoldScope(block)\n            except ValueError:\n                return None\n        return None",
    "docstring": "Return the parent scope.\n\n        :return: FoldScope or None"
  },
  {
    "code": "def clean_file(configuration, filename):\n    pofile = polib.pofile(filename)\n    if pofile.header.find(EDX_MARKER) != -1:\n        new_header = get_new_header(configuration, pofile)\n        new = pofile.header.replace(EDX_MARKER, new_header)\n        pofile.header = new\n        pofile.save()",
    "docstring": "Strips out the warning from a translated po file about being an English source file.\n    Replaces warning with a note about coming from Transifex."
  },
  {
    "code": "def setnx(self, key, value):\n        fut = self.execute(b'SETNX', key, value)\n        return wait_convert(fut, bool)",
    "docstring": "Set the value of a key, only if the key does not exist."
  },
  {
    "code": "def flatten_list(l: List[list]) -> list:\n    return [v for inner_l in l for v in inner_l]",
    "docstring": "takes a list of lists, l and returns a flat list"
  },
  {
    "code": "def __label_cmp(self, other):\n        if other is None:\n            return -1\n        label_name = strip_accents(self.name).lower()\n        other_name = strip_accents(other.name).lower()\n        if label_name < other_name:\n            return -1\n        elif label_name == other_name:\n            return 0\n        else:\n            return 1\n        if self.get_color_str() < other.get_color_str():\n            return -1\n        elif self.get_color_str() == other.get_color_str():\n            return 0\n        else:\n            return 1",
    "docstring": "Comparaison function. Can be used to sort labels alphabetically."
  },
  {
    "code": "def setup_db(self, couch, dbname):\n        my_db = None\n        self.log.debug('Setting up DB: %s' % dbname)\n        if dbname not in couch:\n            self.log.info(\"DB doesn't exist so creating DB: %s\", dbname)\n            try:\n                my_db = couch.create(dbname)\n            except:\n                self.log.critical(\"Race condition caught\")\n                raise RuntimeError(\"Race condition caught when creating DB\")\n            try:\n                auth_doc = {}\n                auth_doc['_id'] = '_design/auth'\n                auth_doc['language'] = 'javascript'\n                auth_doc['validate_doc_update'] =\n                my_db.save(auth_doc)\n            except:\n                self.log.error('Could not set permissions of %s' % dbname)\n        else:\n            my_db = couch[dbname]\n        return my_db",
    "docstring": "Setup and configure DB"
  },
  {
    "code": "def property(self, property_name, default=Ellipsis):\n        try:\n            return self._a_tags[property_name]\n        except KeyError:\n            if default != Ellipsis:\n                return default\n            else:\n                raise",
    "docstring": "Returns a property value\n\n        :param: default will return that value if the property is not found,\n               else, will raise a KeyError."
  },
  {
    "code": "def do_aprint(self, statement):\n        self.poutput('aprint was called with argument: {!r}'.format(statement))\n        self.poutput('statement.raw = {!r}'.format(statement.raw))\n        self.poutput('statement.argv = {!r}'.format(statement.argv))\n        self.poutput('statement.command = {!r}'.format(statement.command))",
    "docstring": "Print the argument string this basic command is called with."
  },
  {
    "code": "def set_attribute(self, name, value):\n        js_executor = self.driver_wrapper.js_executor\n        def set_attribute_element():\n            js_executor.execute_template('setAttributeTemplate', {\n                'attribute_name': str(name),\n                'attribute_value': str(value)}, self.element)\n            return True\n        self.execute_and_handle_webelement_exceptions(set_attribute_element,\n                                                      'set attribute \"' + str(name) + '\" to \"' + str(value) + '\"')\n        return self",
    "docstring": "Sets the attribute of the element to a specified value\n\n        @type name:     str\n        @param name:    the name of the attribute\n        @type value:    str\n        @param value:   the attribute of the value"
  },
  {
    "code": "def predict(rf_model, features):\n    import numpy as np\n    from upsilon.extract_features.feature_set import get_feature_set\n    feature_set = get_feature_set()\n    cols = [feature for feature in features if feature in feature_set]\n    cols = sorted(cols)\n    filtered_features = []\n    for i in range(len(cols)):\n        filtered_features.append(features[cols[i]])\n    filtered_features = np.array(filtered_features).reshape(1, -1)\n    classes = rf_model.classes_\n    probabilities = rf_model.predict_proba(filtered_features)[0]\n    flag = 0\n    if features['period_SNR'] < 20. or is_period_alias(features['period']):\n        flag = 1\n    max_index = np.where(probabilities == np.max(probabilities))\n    return classes[max_index][0], probabilities[max_index][0], flag",
    "docstring": "Return label and probability estimated.\n\n    Parameters\n    ----------\n    rf_model : sklearn.ensemble.RandomForestClassifier\n        The UPSILoN random forests model.\n    features : array_like\n        A list of features estimated by UPSILoN.\n\n    Returns\n    -------\n    label : str\n        A predicted label (i.e. class).\n    probability : float\n        Class probability.\n    flag : int\n        Classification flag."
  },
  {
    "code": "def before_request():\n    if not request.path.startswith('/saml') and not request.path.startswith('/auth'):\n        if 'accounts' not in session:\n            logger.debug('Missing \\'accounts\\' from session object, sending user to login page')\n            return BaseView.make_unauth_response()\n        if request.method in ('POST', 'PUT', 'DELETE',):\n            if session['csrf_token'] != request.headers.get('X-Csrf-Token'):\n                logger.info('CSRF Token is missing or incorrect, sending user to login page')\n                abort(403)",
    "docstring": "Checks to ensure that the session is valid and validates the users CSRF token is present\n\n    Returns:\n        `None`"
  },
  {
    "code": "def load_local_config(filename):\n    if not filename:\n        return imp.new_module('local_pylint_config')\n    module = imp.load_source('local_pylint_config', filename)\n    return module",
    "docstring": "Loads the pylint.config.py file.\n\n    Args:\n        filename (str): The python file containing the local configuration.\n\n    Returns:\n        module: The loaded Python module."
  },
  {
    "code": "def update_firewall(self, firewall, body=None):\n        return self.put(self.firewall_path % (firewall), body=body)",
    "docstring": "Updates a firewall."
  },
  {
    "code": "def postComponents(self, name, status, **kwargs):\n        kwargs['name'] = name\n        kwargs['status'] = status\n        return self.__postRequest('/components', kwargs)",
    "docstring": "Create a new component.\n\n        :param name: Name of the component\n        :param status: Status of the component; 1-4\n        :param description: (optional) Description of the component\n        :param link: (optional) A hyperlink to the component\n        :param order: (optional) Order of the component\n        :param group_id: (optional) The group id that the component is within\n        :param enabled: (optional)\n        :return: :class:`Response <Response>` object\n        :rtype: requests.Response"
  },
  {
    "code": "def get_distance(a, b, xaxis=True):\n    if xaxis:\n        arange = (\"0\", a.qstart, a.qstop, a.orientation)\n        brange = (\"0\", b.qstart, b.qstop, b.orientation)\n    else:\n        arange = (\"0\", a.sstart, a.sstop, a.orientation)\n        brange = (\"0\", b.sstart, b.sstop, b.orientation)\n    dist, oo = range_distance(arange, brange, distmode=\"ee\")\n    dist = abs(dist)\n    return dist",
    "docstring": "Returns the distance between two blast HSPs."
  },
  {
    "code": "def reload(self, *fields, **kw):\n\t\tDoc, collection, query, options = self._prepare_find(id=self.id, projection=fields, **kw)\n\t\tresult = collection.find_one(query, **options)\n\t\tif fields:\n\t\t\tfor k in result:\n\t\t\t\tif k == ~Doc.id: continue\n\t\t\t\tself.__data__[k] = result[k]\n\t\telse:\n\t\t\tself.__data__ = result\n\t\treturn self",
    "docstring": "Reload the entire document from the database, or refresh specific named top-level fields."
  },
  {
    "code": "def create_tags(self, entry):\n        tag_list = [t.lower().strip() for t in entry.tag_string.split(',')]\n        for t in tag_list:\n            tag, created = self.get_or_create(name=t)\n            entry.tags.add(tag)",
    "docstring": "Inspects an ``Entry`` instance, and builds associates ``Tag``\n        objects based on the values in the ``Entry``'s ``tag_string``."
  },
  {
    "code": "def genesis(chain_class: BaseChain,\n            db: BaseAtomicDB=None,\n            params: Dict[str, HeaderParams]=None,\n            state: GeneralState=None) -> BaseChain:\n    if state is None:\n        genesis_state = {}\n    else:\n        genesis_state = _fill_and_normalize_state(state)\n    genesis_params_defaults = _get_default_genesis_params(genesis_state)\n    if params is None:\n        genesis_params = genesis_params_defaults\n    else:\n        genesis_params = merge(genesis_params_defaults, params)\n    if db is None:\n        base_db = AtomicDB()\n    else:\n        base_db = db\n    return chain_class.from_genesis(base_db, genesis_params, genesis_state)",
    "docstring": "Initialize the given chain class with the given genesis header parameters\n    and chain state."
  },
  {
    "code": "def run_file(self, path, all_errors_exit=True):\n        path = fixpath(path)\n        with self.handling_errors(all_errors_exit):\n            module_vars = run_file(path)\n            self.vars.update(module_vars)\n            self.store(\"from \" + splitname(path)[1] + \" import *\")",
    "docstring": "Execute a Python file."
  },
  {
    "code": "def Distance(lat0, lng0, lat1, lng1):\n  deg2rad = math.pi / 180.0\n  lat0 = lat0 * deg2rad\n  lng0 = lng0 * deg2rad\n  lat1 = lat1 * deg2rad\n  lng1 = lng1 * deg2rad\n  dlng = lng1 - lng0\n  dlat = lat1 - lat0\n  a = math.sin(dlat*0.5)\n  b = math.sin(dlng*0.5)\n  a = a * a + math.cos(lat0) * math.cos(lat1) * b * b\n  c = 2.0 * math.atan2(math.sqrt(a), math.sqrt(1.0 - a))\n  return 6367000.0 * c",
    "docstring": "Compute the geodesic distance in meters between two points on the\n  surface of the Earth.  The latitude and longitude angles are in\n  degrees.\n\n  Approximate geodesic distance function (Haversine Formula) assuming\n  a perfect sphere of radius 6367 km (see \"What are some algorithms\n  for calculating the distance between 2 points?\" in the GIS Faq at\n  http://www.census.gov/geo/www/faq-index.html).  The approximate\n  radius is adequate for our needs here, but a more sophisticated\n  geodesic function should be used if greater accuracy is required\n  (see \"When is it NOT okay to assume the Earth is a sphere?\" in the\n  same faq)."
  },
  {
    "code": "def parse_bulk_create(prs, conn):\n    prs_create = prs.add_parser(\n        'bulk_create', help='create bulk records of specific zone')\n    set_option(prs_create, 'infile')\n    conn_options(prs_create, conn)\n    prs_create.add_argument('--domain', action='store',\n                            help='create records with specify zone')\n    prs_create.set_defaults(func=create)",
    "docstring": "Create bulk_records.\n\n    Arguments:\n\n        prs:  parser object of argparse\n        conn: dictionary of connection information"
  },
  {
    "code": "def complete_opt_display(self, text, *_):\n        return [t + \" \" for t in DISPLAYS if t.startswith(text)]",
    "docstring": "Autocomplete for display option"
  },
  {
    "code": "def get_child(self, child_name):\n        child = self.children.get(child_name, None)\n        if child:\n            return child\n        raise ValueError(\"Value {} not in this tree\".format(child_name))",
    "docstring": "returns the object with the name supplied"
  },
  {
    "code": "def run_program(program, *args):\n    real_args = [program]\n    real_args.extend(args)\n    logging.debug(_('check_output arguments: %s'), real_args)\n    check_output(real_args, universal_newlines=True)",
    "docstring": "Wrap subprocess.check_output to make life easier."
  },
  {
    "code": "def should_close(http_version, connection_field):\n    connection_field = (connection_field or '').lower()\n    if http_version == 'HTTP/1.0':\n        return connection_field.replace('-', '') != 'keepalive'\n    else:\n        return connection_field == 'close'",
    "docstring": "Return whether the connection should be closed.\n\n    Args:\n        http_version (str): The HTTP version string like ``HTTP/1.0``.\n        connection_field (str): The value for the ``Connection`` header."
  },
  {
    "code": "def has_verified_email(self):\n        url = (self._imgur._base_url + \"/3/account/{0}/\"\n               \"verifyemail\".format(self.name))\n        return self._imgur._send_request(url, needs_auth=True)",
    "docstring": "Has the user verified that the email he has given is legit?\n\n        Verified e-mail is required to the gallery. Confirmation happens by\n        sending an email to the user and the owner of the email user verifying\n        that he is the same as the Imgur user."
  },
  {
    "code": "def single_violation(self, column=None, value=None, **kwargs):\n        return self._resolve_call('PCS_SINGLE_EVENT_VIOL', column,\n                                  value, **kwargs)",
    "docstring": "A single event violation is a one-time event that occurred on a fixed\n        date, and is associated with one permitted facility.\n\n        >>> PCS().single_violation('single_event_viol_date', '16-MAR-01')"
  },
  {
    "code": "def eval_one(self, e, **kwargs):\n        try:\n            return self.eval_exact(e, 1, **{k: v for (k, v) in kwargs.items() if k != 'default'})[0]\n        except (SimUnsatError, SimValueError, SimSolverModeError):\n            if 'default' in kwargs:\n                return kwargs.pop('default')\n            raise",
    "docstring": "Evaluate an expression to get the only possible solution. Errors if either no or more than one solution is\n        returned. A kwarg parameter `default` can be specified to be returned instead of failure!\n\n        :param e: the expression to get a solution for\n        :param default: A value can be passed as a kwarg here. It will be returned in case of failure.\n        :param kwargs: Any additional kwargs will be passed down to `eval_upto`\n        :raise SimUnsatError: if no solution could be found satisfying the given constraints\n        :raise SimValueError: if more than one solution was found to satisfy the given constraints\n        :return: The value for `e`"
  },
  {
    "code": "def potcar_spec( filename ):\n    p_spec = {}\n    with open( filename, 'r' ) as f:\n        potcars = re.split('(End of Dataset\\n)', f.read() )\n    potcar_md5sums = [ md5sum( ''.join( pair ) ) for pair in zip( potcars[::2], potcars[1:-1:2] ) ]\n    for this_md5sum in potcar_md5sums:\n        for ps in potcar_sets:\n            for p, p_md5sum in potcar_md5sum_data[ ps ].items():\n                if this_md5sum == p_md5sum:\n                    p_spec[ p ] = ps\n    if len( p_spec ) != len( potcar_md5sums ):\n        raise ValueError( 'One or more POTCARs did not have matching md5 hashes' )\n    return p_spec",
    "docstring": "Returns a dictionary specifying the pseudopotentials contained in a POTCAR file.\n\n    Args:\n        filename (Str): The name of the POTCAR file to process.\n\n    Returns:\n        (Dict): A dictionary of pseudopotential filename: dataset pairs, e.g.\n                { 'Fe_pv': 'PBE_54', 'O', 'PBE_54' }"
  },
  {
    "code": "def update(self, conf_dict):\n        if isinstance(conf_dict, dict):\n            iterator = six.iteritems(conf_dict)\n        else:\n            iterator = iter(conf_dict)\n        for k, v in iterator:\n            if not IDENTIFIER.match(k):\n                raise ValueError('\\'%s\\' is not a valid indentifier' % k)\n            cur_val = self.__values__.get(k)\n            if isinstance(cur_val, Config):\n                cur_val.update(conf_dict[k])\n            else:\n                self[k] = conf_dict[k]",
    "docstring": "Updates this configuration with a dictionary.\n\n        :param conf_dict: A python dictionary to update this configuration\n                          with."
  },
  {
    "code": "def enable_mp_crash_reporting():\n    global mp_crash_reporting_enabled\n    multiprocessing.Process = multiprocessing.process.Process = CrashReportingProcess\n    mp_crash_reporting_enabled = True",
    "docstring": "Monkey-patch the multiprocessing.Process class with our own CrashReportingProcess.\n    Any subsequent imports of multiprocessing.Process will reference CrashReportingProcess instead.\n\n    This function must be called before any imports to mulitprocessing in order for the monkey-patching to work."
  },
  {
    "code": "def transform_series(series, force_list=False, buffers=None):\n    if isinstance(series, pd.PeriodIndex):\n        vals = series.to_timestamp().values\n    else:\n        vals = series.values\n    return transform_array(vals, force_list=force_list, buffers=buffers)",
    "docstring": "Transforms a Pandas series into serialized form\n\n    Args:\n        series (pd.Series) : the Pandas series to transform\n        force_list (bool, optional) : whether to only output to standard lists\n            This function can encode some dtypes using a binary encoding, but\n            setting this argument to True will override that and cause only\n            standard Python lists to be emitted. (default: False)\n\n        buffers (set, optional) :\n            If binary buffers are desired, the buffers parameter may be\n            provided, and any columns that may be sent as binary buffers\n            will be added to the set. If None, then only base64 encoding\n            will be used (default: None)\n\n            If force_list is True, then this value will be ignored, and\n            no buffers will be generated.\n\n            **This is an \"out\" parameter**. The values it contains will be\n            modified in-place.\n\n    Returns:\n        list or dict"
  },
  {
    "code": "def as_cache_key(self, ireq):\n        extras = tuple(sorted(ireq.extras))\n        if not extras:\n            extras_string = \"\"\n        else:\n            extras_string = \"[{}]\".format(\",\".join(extras))\n        name = key_from_req(ireq.req)\n        version = get_pinned_version(ireq)\n        return name, \"{}{}\".format(version, extras_string)",
    "docstring": "Given a requirement, return its cache key.\n\n        This behavior is a little weird in order to allow backwards\n        compatibility with cache files. For a requirement without extras, this\n        will return, for example::\n\n            (\"ipython\", \"2.1.0\")\n\n        For a requirement with extras, the extras will be comma-separated and\n        appended to the version, inside brackets, like so::\n\n            (\"ipython\", \"2.1.0[nbconvert,notebook]\")"
  },
  {
    "code": "def end_timing(self):\n        if self._callback != None:\n            elapsed = time.perf_counter() * 1000 - self._start\n            self._callback.end_timing(self._counter, elapsed)",
    "docstring": "Ends timing of an execution block, calculates elapsed time and updates the associated counter."
  },
  {
    "code": "def parse_value(cls, value: int, default: T = None) -> T:\n        return next((item for item in cls if value == item.value), default)",
    "docstring": "Parse specified value for IntEnum; return default if not found."
  },
  {
    "code": "def _defaultdict(dct, fallback=_illegal_character):\n    out = defaultdict(lambda: fallback)\n    for k, v in six.iteritems(dct):\n        out[k] = v\n    return out",
    "docstring": "Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is\n    accessed."
  },
  {
    "code": "def vb_get_max_network_slots():\n    sysprops = vb_get_box().systemProperties\n    totals = [\n        sysprops.getMaxNetworkAdapters(adapter_type)\n        for adapter_type in [\n            1,\n            2\n        ]\n        ]\n    return sum(totals)",
    "docstring": "Max number of slots any machine can have\n    @return:\n    @rtype: number"
  },
  {
    "code": "def get_socket(self):\n        import eventlet\n        socket_args = {}\n        for arg in ('backlog', 'family'):\n            try:\n                socket_args[arg] = self.options.pop(arg)\n            except KeyError:\n                pass\n        ssl_args = {}\n        for arg in ('keyfile', 'certfile', 'server_side', 'cert_reqs',\n                    'ssl_version', 'ca_certs', 'do_handshake_on_connect',\n                    'suppress_ragged_eofs', 'ciphers'):\n            try:\n                ssl_args[arg] = self.options.pop(arg)\n            except KeyError:\n                pass\n        address = (self.host, self.port)\n        try:\n            sock = eventlet.listen(address, **socket_args)\n        except TypeError:\n            sock = eventlet.listen(address)\n        if ssl_args:\n            sock = eventlet.wrap_ssl(sock, **ssl_args)\n        return sock",
    "docstring": "Create listener socket based on bottle server parameters."
  },
  {
    "code": "def aux_dict(self):\n        if self._aux_dict is None:\n            self._aux_dict = Executor._get_dict(\n                self._symbol.list_auxiliary_states(), self.aux_arrays)\n        return self._aux_dict",
    "docstring": "Get dictionary representation of auxiliary states arrays.\n\n        Returns\n        -------\n        aux_dict : dict of str to NDArray\n            The dictionary that maps name of auxiliary states to NDArrays.\n\n        Raises\n        ------\n        ValueError : if there are duplicated names in the auxiliary states."
  },
  {
    "code": "def list_inputs(self):\n        doc = []\n        for inp, typ in self.input_types.items():\n            if isinstance(typ, six.string_types):\n                typ = \"'{}'\".format(typ)\n            doc.append('{}: {}'.format(inp, typ))\n        return '\\n'.join(doc)",
    "docstring": "Return a string listing all the Step's input names and their types.\n\n        The types are returned in a copy/pastable format, so if the type is\n        `string`, `'string'` (with single quotes) is returned.\n\n        Returns:\n            str containing all input names and types."
  },
  {
    "code": "def set_color(self, group, color, pct=1):\n        if not self.leds:\n            return\n        color_tuple = color\n        if isinstance(color, str):\n            assert color in self.led_colors, \\\n                \"%s is an invalid LED color, valid choices are %s\" % \\\n                (color, ', '.join(self.led_colors.keys()))\n            color_tuple = self.led_colors[color]\n        assert group in self.led_groups, \\\n            \"%s is an invalid LED group, valid choices are %s\" % \\\n            (group, ', '.join(self.led_groups.keys()))\n        for led, value in zip(self.led_groups[group], color_tuple):\n            led.brightness_pct = value * pct",
    "docstring": "Sets brightness of LEDs in the given group to the values specified in\n        color tuple. When percentage is specified, brightness of each LED is\n        reduced proportionally.\n\n        Example::\n\n            my_leds = Leds()\n            my_leds.set_color('LEFT', 'AMBER')\n\n        With a custom color::\n\n            my_leds = Leds()\n            my_leds.set_color('LEFT', (0.5, 0.3))"
  },
  {
    "code": "def dump(self, stream):\n        items = (\n            ('time', self.time),\n            ('inc', self.inc),\n        )\n        ts = collections.OrderedDict(items)\n        json.dump(dict(ts=ts), stream)",
    "docstring": "Serialize self to text stream.\n\n        Matches convention of mongooplog."
  },
  {
    "code": "def cursor():\n    try:\n        cur = conn.cursor()\n        yield cur\n    except (db.Error, Exception) as e:\n        cur.close()\n        if conn:\n            conn.rollback()\n        print(e.message)\n        raise\n    else:\n        conn.commit()\n        cur.close()",
    "docstring": "Database cursor generator. Commit on context exit."
  },
  {
    "code": "def randomZ(maximum=None, bits=256):\n    result = BigInt()\n    if maximum:\n        maximum = coerceBigInt(maximum)\n        librelic.bn_rand_mod(byref(result), byref(maximum))\n    else:\n        librelic.bn_rand_abi(byref(result), BigInt.POSITIVE_FLAG, c_int(bits))\n    return result",
    "docstring": "Retrieve a random BigInt.\n    @maximum: If specified, the value will be no larger than this modulus.\n    @bits: If no maximum is specified, the value will have @bits."
  },
  {
    "code": "def get_filename(self, year):\n        res = self.fldr + os.sep + self.type + year + '.' + self.user \n        return res",
    "docstring": "returns the filename"
  },
  {
    "code": "def set_prewarp(self, prewarp):\n        prewarp = _convert_to_charp(prewarp)\n        self._set_prewarp_func(self.alpr_pointer, prewarp)",
    "docstring": "Updates the prewarp configuration used to skew images in OpenALPR before\n        processing.\n\n        :param prewarp: A unicode/ascii string (Python 2/3) or bytes array (Python 3)\n        :return: None"
  },
  {
    "code": "def simBirth(self,which_agents):\n        IndShockConsumerType.simBirth(self,which_agents)\n        if not self.global_markov:\n            N = np.sum(which_agents)\n            base_draws = drawUniform(N,seed=self.RNG.randint(0,2**31-1))\n            Cutoffs = np.cumsum(np.array(self.MrkvPrbsInit))\n            self.MrkvNow[which_agents] = np.searchsorted(Cutoffs,base_draws).astype(int)",
    "docstring": "Makes new Markov consumer by drawing initial normalized assets, permanent income levels, and\n        discrete states. Calls IndShockConsumerType.simBirth, then draws from initial Markov distribution.\n\n        Parameters\n        ----------\n        which_agents : np.array(Bool)\n            Boolean array of size self.AgentCount indicating which agents should be \"born\".\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def add_watcher(self, issue, watcher):\n        url = self._get_url('issue/' + str(issue) + '/watchers')\n        self._session.post(\n            url, data=json.dumps(watcher))",
    "docstring": "Add a user to an issue's watchers list.\n\n        :param issue: ID or key of the issue affected\n        :param watcher: username of the user to add to the watchers list"
  },
  {
    "code": "def check_client_key(self, client_key):\n        lower, upper = self.client_key_length\n        return (set(client_key) <= self.safe_characters and\n                lower <= len(client_key) <= upper)",
    "docstring": "Check that the client key only contains safe characters\n        and is no shorter than lower and no longer than upper."
  },
  {
    "code": "def liveReceivers(receivers):\n    for receiver in receivers:\n        if isinstance( receiver, WEAKREF_TYPES):\n            receiver = receiver()\n            if receiver is not None:\n                yield receiver\n        else:\n            yield receiver",
    "docstring": "Filter sequence of receivers to get resolved, live receivers\n\n    This is a generator which will iterate over\n    the passed sequence, checking for weak references\n    and resolving them, then returning all live\n    receivers."
  },
  {
    "code": "def call(self, action_name, container, instances=None, map_name=None, **kwargs):\n        return self.run_actions(action_name, container, instances=instances, map_name=map_name, **kwargs)",
    "docstring": "Generic function for running container actions based on a policy.\n\n        :param action_name: Action name.\n        :type action_name: unicode | str\n        :param container: Container name.\n        :type container: unicode | str\n        :param instances: Instance names to remove. If not specified, runs on all instances as specified in the\n         configuration (or just one default instance).\n        :type instances: collections.Iterable[unicode | str | NoneType]\n        :param map_name: Container map name. Optional - if not provided the default map is used.\n        :type map_name: unicode | str\n        :param kwargs: Additional kwargs for the policy method.\n        :return: Return values of actions.\n        :rtype: list[dockermap.map.runner.ActionOutput]"
  },
  {
    "code": "def as_poly(self, margin_width=0, margin_height=0):\n        v_hor = (self.width/2 + margin_width)*np.array([np.cos(self.angle), np.sin(self.angle)])\n        v_vert = (self.height/2 + margin_height)*np.array([-np.sin(self.angle), np.cos(self.angle)])\n        c = np.array([self.cx, self.cy])\n        return np.vstack([c - v_hor - v_vert, c + v_hor - v_vert, c + v_hor + v_vert, c - v_hor + v_vert])",
    "docstring": "Converts this box to a polygon, i.e. 4x2 array, representing the four corners starting from lower left to upper left counterclockwise.\n\n        :param margin_width: The additional \"margin\" that will be added to the box along its width dimension (from both sides) before conversion.\n        :param margin_height: The additional \"margin\" that will be added to the box along its height dimension (from both sides) before conversion.\n\n        >>> RotatedBox([0, 0], 4, 2, 0).as_poly()\n        array([[-2., -1.],\n               [ 2., -1.],\n               [ 2.,  1.],\n               [-2.,  1.]])\n        >>> RotatedBox([0, 0], 4, 2, np.pi/4).as_poly()\n        array([[-0.707..., -2.121...],\n               [ 2.121...,  0.707...],\n               [ 0.707...,  2.121...],\n               [-2.121..., -0.707...]])\n        >>> RotatedBox([0, 0], 4, 2, np.pi/2).as_poly()\n        array([[ 1., -2.],\n               [ 1.,  2.],\n               [-1.,  2.],\n               [-1., -2.]])\n        >>> RotatedBox([0, 0], 0, 0, np.pi/2).as_poly(2, 1)\n        array([[ 1., -2.],\n               [ 1.,  2.],\n               [-1.,  2.],\n               [-1., -2.]])"
  },
  {
    "code": "def clear(self):\n        self.redis_conn.delete(self.window_key)\n        self.redis_conn.delete(self.moderate_key)\n        self.queue.clear()",
    "docstring": "Clears all data associated with the throttled queue"
  },
  {
    "code": "def routes(cls, application=None):\n        if application:\n            for route in cls._routes:\n                application.add_handlers(route['host'], route['spec'])\n        else:\n            return [route['spec'] for route in cls._routes]",
    "docstring": "Method for adding the routes to the `tornado.web.Application`."
  },
  {
    "code": "def do_grep(self, path, match):\n        try:\n            children = self.get_children(path)\n        except (NoNodeError, NoAuthError):\n            children = []\n        for child in children:\n            full_path = os.path.join(path, child)\n            try:\n                value, _ = self.get(full_path)\n            except (NoNodeError, NoAuthError):\n                value = \"\"\n            if value is not None:\n                matches = [line for line in value.split(\"\\n\") if match.search(line)]\n                if len(matches) > 0:\n                    yield (full_path, matches)\n            for mpath, matches in self.do_grep(full_path, match):\n                yield (mpath, matches)",
    "docstring": "grep's work horse"
  },
  {
    "code": "def grad_desc_update(x, a, c, step=0.01):\n    return x - step * gradient(x,a,c)",
    "docstring": "Given a value of x, return a better x \n    using gradient descent"
  },
  {
    "code": "def build_embedding_weights(word_index, embeddings_index):\n    logger.info('Loading embeddings for all words in the corpus')\n    embedding_dim = list(embeddings_index.values())[0].shape[-1]\n    embedding_weights = np.zeros((len(word_index), embedding_dim))\n    for word, i in word_index.items():\n        word_vector = embeddings_index.get(word)\n        if word_vector is not None:\n            embedding_weights[i] = word_vector\n    return embedding_weights",
    "docstring": "Builds an embedding matrix for all words in vocab using embeddings_index"
  },
  {
    "code": "def friendly_format(self):\n        if self.description is not None:\n            msg = self.description\n        else:\n            msg = 'errorCode: {} / detailCode: {}'.format(\n                self.errorCode, self.detailCode\n            )\n        return self._fmt(self.name, msg)",
    "docstring": "Serialize to a format more suitable for displaying to end users."
  },
  {
    "code": "def _search_for_files(parts):\n    file_parts = []\n    for part in parts:\n        if isinstance(part, list):\n            file_parts.extend(_search_for_files(part))\n        elif isinstance(part, FileToken):\n            file_parts.append(part)\n    return file_parts",
    "docstring": "Given a list of parts, return all of the nested file parts."
  },
  {
    "code": "def rbinomial(n, p, size=None):\n    if not size:\n        size = None\n    return np.random.binomial(np.ravel(n), np.ravel(p), size)",
    "docstring": "Random binomial variates."
  },
  {
    "code": "def insert_sort(node, target):\n    sort = target.sort\n    lang = target.lang\n    collator = Collator.createInstance(Locale(lang) if lang else Locale())\n    for child in target.tree:\n        if collator.compare(sort(child) or '', sort(node) or '') > 0:\n            child.addprevious(node)\n            break\n    else:\n        target.tree.append(node)",
    "docstring": "Insert node into sorted position in target tree.\n\n    Uses sort function and language from target"
  },
  {
    "code": "def append_metrics(self, metrics, df_name):\n        dataframe = self._dataframes[df_name]\n        _add_new_columns(dataframe, metrics)\n        dataframe.loc[len(dataframe)] = metrics",
    "docstring": "Append new metrics to selected dataframes.\n\n        Parameters\n        ----------\n        metrics : metric.EvalMetric\n            New metrics to be added.\n        df_name : str\n            Name of the dataframe to be modified."
  },
  {
    "code": "def command(self, command, raw=False, timeout_ms=None):\n    return ''.join(self.streaming_command(command, raw, timeout_ms))",
    "docstring": "Run the given command and return the output."
  },
  {
    "code": "def eval_py(self, _globals, _locals):\n        try:\n            params = eval(self.script, _globals, _locals)\n        except NameError as e:\n            raise Exception(\n                'Failed to evaluate parameters: {}'\n                .format(str(e))\n            )\n        except ResolutionError as e:\n            raise Exception('GetOutput: {}'.format(str(e)))\n        return params",
    "docstring": "Evaluates a file containing a Python params dictionary."
  },
  {
    "code": "def delete_budget(self, model_uuid):\n        return make_request(\n            '{}model/{}/budget'.format(self.url, model_uuid),\n            method='DELETE',\n            timeout=self.timeout,\n            client=self._client)",
    "docstring": "Delete a budget.\n\n        @param the name of the wallet.\n        @param the model UUID.\n        @return a success string from the plans server.\n        @raise ServerError via make_request."
  },
  {
    "code": "def get_theme_dir():\n    return os.path.abspath(os.path.join(os.path.dirname(__file__), \"theme\"))",
    "docstring": "Returns path to directory containing this package's theme.\n    \n    This is designed to be used when setting the ``html_theme_path``\n    option within Sphinx's ``conf.py`` file."
  },
  {
    "code": "def GaussianBlur(X, ksize_width, ksize_height, sigma_x, sigma_y):\n    return image_transform(\n        X,\n        cv2.GaussianBlur,\n        ksize=(ksize_width, ksize_height),\n        sigmaX=sigma_x,\n        sigmaY=sigma_y\n    )",
    "docstring": "Apply Gaussian blur to the given data.\n\n    Args:\n        X: data to blur\n        kernel_size: Gaussian kernel size\n        stddev: Gaussian kernel standard deviation (in both X and Y directions)"
  },
  {
    "code": "def __validate_required_fields(self, document):\n        try:\n            required = set(field for field, definition in self.schema.items()\n                           if self._resolve_rules_set(definition).\n                           get('required') is True)\n        except AttributeError:\n            if self.is_child and self.schema_path[-1] == 'schema':\n                raise _SchemaRuleTypeError\n            else:\n                raise\n        required -= self._unrequired_by_excludes\n        missing = required - set(field for field in document\n                                 if document.get(field) is not None or\n                                 not self.ignore_none_values)\n        for field in missing:\n            self._error(field, errors.REQUIRED_FIELD)\n        if self._unrequired_by_excludes:\n            fields = set(field for field in document\n                         if document.get(field) is not None)\n            if self._unrequired_by_excludes.isdisjoint(fields):\n                for field in self._unrequired_by_excludes - fields:\n                    self._error(field, errors.REQUIRED_FIELD)",
    "docstring": "Validates that required fields are not missing.\n\n        :param document: The document being validated."
  },
  {
    "code": "def cancelMktData(self, contract: Contract):\n        ticker = self.ticker(contract)\n        reqId = self.wrapper.endTicker(ticker, 'mktData')\n        if reqId:\n            self.client.cancelMktData(reqId)\n        else:\n            self._logger.error(\n                'cancelMktData: ' f'No reqId found for contract {contract}')",
    "docstring": "Unsubscribe from realtime streaming tick data.\n\n        Args:\n            contract: The exact contract object that was used to\n                subscribe with."
  },
  {
    "code": "def untrace_modules(self, modules):\n        for module in modules:\n            foundations.trace.untrace_module(module)\n        self.__model__refresh_attributes()\n        return True",
    "docstring": "Untraces given modules.\n\n        :param modules: Modules to untrace.\n        :type modules: list\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def open_target_group_for_form(self, form):\n        target = self.first_container_with_errors(form.errors.keys())\n        if target is None:\n            target = self.fields[0]\n            if not getattr(target, '_active_originally_included', None):\n                target.active = True\n            return target\n        target.active = True\n        return target",
    "docstring": "Makes sure that the first group that should be open is open.\n        This is either the first group with errors or the first group\n        in the container, unless that first group was originally set to\n        active=False."
  },
  {
    "code": "def column(self, key):\n        for row in self.rows:\n            if key in row:\n                yield row[key]",
    "docstring": "Iterator over a given column, skipping steps that don't have that key"
  },
  {
    "code": "def structure_results(res):\n    out = {'hits': {'hits': []}}\n    keys = [u'admin1_code', u'admin2_code', u'admin3_code', u'admin4_code',\n            u'alternativenames', u'asciiname', u'cc2', u'coordinates',\n            u'country_code2', u'country_code3', u'dem', u'elevation',\n            u'feature_class', u'feature_code', u'geonameid',\n            u'modification_date', u'name', u'population', u'timezone']\n    for i in res:\n        i_out = {}\n        for k in keys:\n            i_out[k] = i[k]\n        out['hits']['hits'].append(i_out)\n    return out",
    "docstring": "Format Elasticsearch result as Python dictionary"
  },
  {
    "code": "def _create_list_of_array_controllers(self):\n        headers, array_uri, array_settings = (\n            self._get_array_controller_resource())\n        array_uri_links = []\n        if ('links' in array_settings and\n                'Member' in array_settings['links']):\n            array_uri_links = array_settings['links']['Member']\n        else:\n            msg = ('\"links/Member\" section in ArrayControllers'\n                   ' does not exist')\n            raise exception.IloCommandNotSupportedError(msg)\n        return array_uri_links",
    "docstring": "Creates the list of Array Controller URIs.\n\n        :raises: IloCommandNotSupportedError if the ArrayControllers\n            doesnt have member \"Member\".\n        :returns list of ArrayControllers."
  },
  {
    "code": "def _expand_qname(self, qname):\n        if type(qname) is not rt.URIRef:\n            raise TypeError(\"Cannot expand qname of type {}, must be URIRef\"\n                            .format(type(qname)))\n        for ns in self.graph.namespaces():\n            if ns[0] == qname.split(':')[0]:\n                return rt.URIRef(\"%s%s\" % (ns[1], qname.split(':')[-1]))\n        return qname",
    "docstring": "expand a qualified name's namespace prefix to include the resolved\n        namespace root url"
  },
  {
    "code": "def slice_sequence(self,start,end):\n     l = self.length\n     indexstart = start\n     indexend = end\n     ns = []\n     tot = 0\n     for r in self._rngs:\n        tot += r.length\n        n = r.copy()\n        if indexstart > r.length:  \n           indexstart-=r.length\n           continue\n        n.start = n.start+indexstart\n        if tot > end: \n           diff = tot-end\n           n.end -= diff\n           tot = end\n        indexstart = 0\n        ns.append(n)\n        if tot == end: break\n     if len(ns)==0: return None\n     return MappingGeneric(ns,self._options)",
    "docstring": "Slice the mapping by the position in the sequence\n        \n        First coordinate is 0-indexed start\n        Second coordinate is 1-indexed finish"
  },
  {
    "code": "def _did_retrieve(self, connection):\n        response = connection.response\n        try:\n            self.from_dict(response.data[0])\n        except:\n            pass\n        return self._did_perform_standard_operation(connection)",
    "docstring": "Callback called after fetching the object"
  },
  {
    "code": "def abs_path_from_base(base_path, rel_path):\n    return os.path.abspath(\n        os.path.join(\n            os.path.dirname(sys._getframe(1).f_code.co_filename), base_path, rel_path\n        )\n    )",
    "docstring": "Join a base and a relative path and return an absolute path to the resulting\n    location.\n\n    Args:\n      base_path: str\n        Relative or absolute path to prepend to ``rel_path``.\n\n      rel_path: str\n        Path relative to the location of the module file from which this function is called.\n\n    Returns:\n        str : Absolute path to the location specified by ``rel_path``."
  },
  {
    "code": "def estimate(self, upgrades):\n        val = 0\n        for u in upgrades:\n            val += u.estimate()\n        return val",
    "docstring": "Estimate the time needed to apply upgrades.\n\n        If an upgrades does not specify and estimate it is assumed to be\n        in the order of 1 second.\n\n        :param upgrades: List of upgrades sorted in topological order."
  },
  {
    "code": "def write_summary(summary: dict, cache_dir: str):\n    summary['accessed'] = time()\n    with open(join(cache_dir, 'summary.json'), 'w') as summary_file:\n        summary_file.write(json.dumps(summary, indent=4, sort_keys=True))",
    "docstring": "Write the `summary` JSON to `cache_dir`.\n\n    Updated the accessed timestamp to now before writing."
  },
  {
    "code": "def pld3(pos, line_vertex, line_dir):\n    pos = np.atleast_2d(pos)\n    line_vertex = np.atleast_1d(line_vertex)\n    line_dir = np.atleast_1d(line_dir)\n    c = np.cross(line_dir, line_vertex - pos)\n    n1 = np.linalg.norm(c, axis=1)\n    n2 = np.linalg.norm(line_dir)\n    out = n1 / n2\n    if out.ndim == 1 and len(out) == 1:\n        return out[0]\n    return out",
    "docstring": "Calculate the point-line-distance for given point and line."
  },
  {
    "code": "def _frombuffer(ptr, frames, channels, dtype):\n    framesize = channels * dtype.itemsize\n    data = np.frombuffer(ffi.buffer(ptr, frames * framesize), dtype=dtype)\n    data.shape = -1, channels\n    return data",
    "docstring": "Create NumPy array from a pointer to some memory."
  },
  {
    "code": "def validate_object_id(object_id):\n    result = re.match(OBJECT_ID_RE, str(object_id))\n    if not result:\n        print(\"'%s' appears not to be a valid 990 object_id\" % object_id)\n        raise RuntimeError(OBJECT_ID_MSG)\n    return object_id",
    "docstring": "It's easy to make a mistake entering these, validate the format"
  },
  {
    "code": "def update_terms(self, project_id, data, fuzzy_trigger=None):\n        kwargs = {}\n        if fuzzy_trigger is not None:\n            kwargs['fuzzy_trigger'] = fuzzy_trigger\n        data = self._run(\n            url_path=\"terms/update\",\n            id=project_id,\n            data=json.dumps(data),\n            **kwargs\n        )\n        return data['result']['terms']",
    "docstring": "Updates project terms. Lets you change the text, context, reference, plural and tags.\n\n        >>> data = [\n                {\n                    \"term\": \"Add new list\",\n                    \"context\": \"\",\n                    \"new_term\": \"Save list\",\n                    \"new_context\": \"\",\n                    \"reference\": \"\\/projects\",\n                    \"plural\": \"\",\n                    \"comment\": \"\",\n                    \"tags\": [\n                        \"first_tag\",\n                        \"second_tag\"\n                    ]\n                },\n                {\n                    \"term\": \"Display list\",\n                    \"context\": \"\",\n                    \"new_term\": \"Show list\",\n                    \"new_context\": \"\"\n                }\n            ]"
  },
  {
    "code": "def clean_stale_refs(self, local_refs=None):\n        try:\n            if pygit2.GIT_FETCH_PRUNE:\n                return []\n        except AttributeError:\n            pass\n        if self.credentials is not None:\n            log.debug(\n                'The installed version of pygit2 (%s) does not support '\n                'detecting stale refs for authenticated remotes, saltenvs '\n                'will not reflect branches/tags removed from remote \\'%s\\'',\n                PYGIT2_VERSION, self.id\n            )\n            return []\n        return super(Pygit2, self).clean_stale_refs()",
    "docstring": "Clean stale local refs so they don't appear as fileserver environments"
  },
  {
    "code": "def drop_right(self, n):\n        return self._transform(transformations.CACHE_T, transformations.drop_right_t(n))",
    "docstring": "Drops the last n elements of the sequence.\n\n        >>> seq([1, 2, 3, 4, 5]).drop_right(2)\n        [1, 2, 3]\n\n        :param n: number of elements to drop\n        :return: sequence with last n elements dropped"
  },
  {
    "code": "def hold(self, policy=\"combine\"):\n        if self._hold is not None and self._hold != policy:\n            log.warning(\"hold already active with '%s', ignoring '%s'\" % (self._hold, policy))\n            return\n        if policy not in HoldPolicy:\n            raise ValueError(\"Unknown hold policy %r\" % policy)\n        self._hold = policy",
    "docstring": "Activate a document hold.\n\n        While a hold is active, no model changes will be applied, or trigger\n        callbacks. Once ``unhold`` is called, the events collected during the\n        hold will be applied according to the hold policy.\n\n        Args:\n            hold ('combine' or 'collect', optional)\n                Whether events collected during a hold should attempt to be\n                combined (default: 'combine')\n\n                When set to ``'collect'`` all events will be collected and\n                replayed in order as-is when ``unhold`` is called.\n\n                When set to ``'combine'`` Bokeh will attempt to combine\n                compatible events together. Typically, different events that\n                change the same property on the same mode can be combined.\n                For example, if the following sequence occurs:\n\n                .. code-block:: python\n\n                    doc.hold('combine')\n                    slider.value = 10\n                    slider.value = 11\n                    slider.value = 12\n\n                Then only *one* callback, for the last ``slider.value = 12``\n                will be triggered.\n\n        Returns:\n            None\n\n        .. note::\n            ``hold`` only applies to document change events, i.e. setting\n            properties on models. It does not apply to events such as\n            ``ButtonClick``, etc."
  },
  {
    "code": "def kill(self):\n        for process in list(self.processes):\n            process[\"subprocess\"].send_signal(signal.SIGKILL)\n        self.stop_watch()",
    "docstring": "Kills the processes right now with a SIGKILL"
  },
  {
    "code": "def pull_tag_dict(data):\n    tags = data.pop('Tags', {}) or {}\n    if tags:\n        proper_tags = {}\n        for tag in tags:\n            proper_tags[tag['Key']] = tag['Value']\n        tags = proper_tags\n    return tags",
    "docstring": "This will pull out a list of Tag Name-Value objects, and return it as a dictionary.\n\n    :param data: The dict collected from the collector.\n    :returns dict: A dict of the tag names and their corresponding values."
  },
  {
    "code": "def fromTFExample(bytestr):\n  example = tf.train.Example()\n  example.ParseFromString(bytestr)\n  return example",
    "docstring": "Deserializes a TFExample from a byte string"
  },
  {
    "code": "def job_error_message(self, job, queue, to_be_requeued, exception, trace=None):\n        return '[%s|%s|%s] error: %s [%s]' % (queue._cached_name,\n                             job.pk.get(),\n                             job._cached_identifier,\n                             str(exception),\n                             'requeued' if to_be_requeued else 'NOT requeued')",
    "docstring": "Return the message to log when a job raised an error"
  },
  {
    "code": "def http_datetime_str_from_dt(dt):\n    epoch_seconds = ts_from_dt(dt)\n    return email.utils.formatdate(epoch_seconds, localtime=False, usegmt=True)",
    "docstring": "Format datetime to HTTP Full Date format.\n\n    Args:\n      dt : datetime\n\n        - tz-aware: Used in the formatted string.\n        - tz-naive: Assumed to be in UTC.\n\n    Returns:\n      str\n        The returned format is a is fixed-length subset of that defined by RFC 1123 and\n        is\n        the preferred format for use in the HTTP Date header. E.g.:\n\n        ``Sat, 02 Jan 1999 03:04:05 GMT``\n\n    See Also:\n      - http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1"
  },
  {
    "code": "def int_to_bytes(i, minlen=1, order='big'):\n        blen = max(minlen, PGPObject.int_byte_len(i), 1)\n        if six.PY2:\n            r = iter(_ * 8 for _ in (range(blen) if order == 'little' else range(blen - 1, -1, -1)))\n            return bytes(bytearray((i >> c) & 0xff for c in r))\n        return i.to_bytes(blen, order)",
    "docstring": "convert integer to bytes"
  },
  {
    "code": "def quick_response(self, status_code):\r\n        translator = Translator(environ=self.environ)\r\n        if status_code == 404:\r\n            self.status(404)\r\n            self.message(translator.trans('http_messages.404'))\r\n        elif status_code == 401:\r\n            self.status(401)\r\n            self.message(translator.trans('http_messages.401'))\r\n        elif status_code == 400:\r\n            self.status(400)\r\n            self.message(translator.trans('http_messages.400'))\r\n        elif status_code == 200:\r\n            self.status(200)\r\n            self.message(translator.trans('http_messages.200'))",
    "docstring": "Quickly construct response using a status code"
  },
  {
    "code": "def add_range(self, name, min=None, max=None):\n        self._ranges.append(_mk_range_bucket(name, 'min', 'max', min, max))\n        return self",
    "docstring": "Add a numeric range.\n\n        :param str name:\n            the name by which the range is accessed in the results\n        :param int | float min: Lower range bound\n        :param int | float max: Upper range bound\n        :return: This object; suitable for method chaining"
  },
  {
    "code": "def _map_in_out(self, inside_var_name):\n        for out_name, in_name in self.outside_name_map.items():\n            if inside_var_name == in_name:\n                return out_name\n        return None",
    "docstring": "Return the external name of a variable mapped from inside."
  },
  {
    "code": "def generate_tokens(doc, regex=CRE_TOKEN, strip=True, nonwords=False):\n    r\n    if isinstance(regex, basestring):\n        regex = re.compile(regex)\n    for w in regex.finditer(doc):\n        if w:\n            w = w.group()\n            if strip:\n                w = w.strip(r'-_*`()}{' + r\"'\")\n            if w and (nonwords or not re.match(r'^' + RE_NONWORD + '$', w)):\n                yield w",
    "docstring": "r\"\"\"Return a sequence of words or tokens, using a re.match iteratively through the str\n\n    >>> doc = \"John D. Rock\\n\\nObjective: \\n\\tSeeking a position as Software --Architect-- / _Project Lead_ that can utilize my expertise and\"\n    >>> doc += \" experiences in business application development and proven records in delivering 90's software. \\n\\nSummary: \\n\\tSoftware Architect\"\n    >>> doc += \" who has gone through several full product-delivery life cycles from requirements gathering to deployment / production, and\"\n    >>> doc += \" skilled in all areas of software development from client-side JavaScript to database modeling. With strong experiences in:\"\n    >>> doc += \" \\n\\tRequirements gathering and analysis.\"\n    >>> len(list(generate_tokens(doc, strip=False, nonwords=True)))\n    82\n    >>> seq = list(generate_tokens(doc, strip=False, nonwords=False))\n    >>> len(seq)\n    70\n    >>> '.' in seq or ':' in seq\n    False\n    >>> s = set(generate_tokens(doc, strip=False, nonwords=True))\n    >>> all(t in s for t in ('D', '.', ':', '_Project', 'Lead_', \"90's\", \"Architect\", \"product-delivery\"))\n    True"
  },
  {
    "code": "def _start_vibration_win(self, left_motor, right_motor):\n        xinput_set_state = self.manager.xinput.XInputSetState\n        xinput_set_state.argtypes = [\n            ctypes.c_uint, ctypes.POINTER(XinputVibration)]\n        xinput_set_state.restype = ctypes.c_uint\n        vibration = XinputVibration(\n            int(left_motor * 65535), int(right_motor * 65535))\n        xinput_set_state(self.__device_number, ctypes.byref(vibration))",
    "docstring": "Start the vibration, which will run until stopped."
  },
  {
    "code": "def register(self, event, keys):\n        if self.running:\n            raise RuntimeError(\"Can't register while running\")\n        handler = self._handlers.get(event, None)\n        if handler is not None:\n            raise ValueError(\"Event {} already registered\".format(event))\n        self._handlers[event] = EventHandler(event, keys, loop=self.loop)",
    "docstring": "Register a new event with available keys.\n        Raises ValueError when the event has already been registered.\n\n        Usage:\n\n            dispatch.register(\"my_event\", [\"foo\", \"bar\", \"baz\"])"
  },
  {
    "code": "def collect_and_report(self):\n        logger.debug(\"Metric reporting thread is now alive\")\n        def metric_work():\n            self.process()\n            if self.agent.is_timed_out():\n                logger.warn(\"Host agent offline for >1 min.  Going to sit in a corner...\")\n                self.agent.reset()\n                return False\n            return True\n        every(1, metric_work, \"Metrics Collection\")",
    "docstring": "Target function for the metric reporting thread.  This is a simple loop to\n        collect and report entity data every 1 second."
  },
  {
    "code": "def get_topic_partition_metadata(hosts):\n    kafka_client = KafkaToolClient(hosts, timeout=10)\n    kafka_client.load_metadata_for_topics()\n    topic_partitions = kafka_client.topic_partitions\n    resp = kafka_client.send_metadata_request()\n    for _, topic, partitions in resp.topics:\n        for partition_error, partition, leader, replicas, isr in partitions:\n            if topic_partitions.get(topic, {}).get(partition) is not None:\n                topic_partitions[topic][partition] = PartitionMetadata(topic, partition, leader,\n                                                                       replicas, isr, partition_error)\n    return topic_partitions",
    "docstring": "Returns topic-partition metadata from Kafka broker.\n\n    kafka-python 1.3+ doesn't include partition metadata information in\n    topic_partitions so we extract it from metadata ourselves."
  },
  {
    "code": "def _parse_launch_error(data):\n        return LaunchFailure(\n            data.get(ERROR_REASON, None),\n            data.get(APP_ID),\n            data.get(REQUEST_ID),\n        )",
    "docstring": "Parses a LAUNCH_ERROR message and returns a LaunchFailure object.\n\n        :type data: dict\n        :rtype: LaunchFailure"
  },
  {
    "code": "def _raw_predict(self, Xnew, full_cov=False, kern=None):\n        mu, var = self.posterior._raw_predict(kern=self.kern if kern is None else kern, Xnew=Xnew,\n                                              pred_var=self._predictive_variable, full_cov=full_cov)\n        if self.mean_function is not None:\n            mu += self.mean_function.f(Xnew)\n        return mu, var",
    "docstring": "For making predictions, does not account for normalization or likelihood\n\n        full_cov is a boolean which defines whether the full covariance matrix\n        of the prediction is computed. If full_cov is False (default), only the\n        diagonal of the covariance is returned.\n\n        .. math::\n            p(f*|X*, X, Y) = \\int^{\\inf}_{\\inf} p(f*|f,X*)p(f|X,Y) df\n                        = MVN\\left(\\nu + N,f*| K_{x*x}(K_{xx})^{-1}Y,\n                        \\frac{\\nu + \\beta - 2}{\\nu + N - 2}K_{x*x*} - K_{xx*}(K_{xx})^{-1}K_{xx*}\\right)\n            \\nu := \\texttt{Degrees of freedom}"
  },
  {
    "code": "def AgregarReceptor(self, cod_caracter, **kwargs):\n        \"Agrego los datos del receptor a la liq.\"\n        d = {'codCaracter': cod_caracter}\n        self.solicitud['receptor'].update(d)\n        return True",
    "docstring": "Agrego los datos del receptor a la liq."
  },
  {
    "code": "def sparse_arrays(self, value):\n        if not isinstance(value, bool):\n            raise TypeError('sparse_arrays attribute must be a logical type.')\n        self._sparse_arrays = value",
    "docstring": "Validate and enable spare arrays."
  },
  {
    "code": "def push(self, key, value, *, section=DataStoreDocumentSection.Data):\n        key_notation = '.'.join([section, key])\n        result = self._collection.update_one(\n            {\"_id\": ObjectId(self._workflow_id)},\n            {\n                \"$push\": {\n                    key_notation: self._encode_value(value)\n                },\n                \"$currentDate\": {\"lastModified\": True}\n            }\n        )\n        return result.modified_count == 1",
    "docstring": "Appends a value to a list in the specified section of the document.\n\n        Args:\n            key (str): The key pointing to the value that should be stored/updated.\n                It supports MongoDB's dot notation for nested fields.\n            value: The value that should be appended to a list in the data store.\n            section (DataStoreDocumentSection): The section from which the data should\n                be retrieved.\n\n        Returns:\n            bool: ``True`` if the value could be appended, otherwise ``False``."
  },
  {
    "code": "def dump(self, path):\n    with open(path, 'w') as props:\n      Properties.dump(self._props, props)",
    "docstring": "Saves the pushdb as a properties file to the given path."
  },
  {
    "code": "def percentile(self, percentile):\n        out = scipy.percentile(self.value, percentile, axis=0)\n        if self.name is not None:\n            name = '{}: {} percentile'.format(self.name, _ordinal(percentile))\n        else:\n            name = None\n        return FrequencySeries(out, epoch=self.epoch, channel=self.channel,\n                               name=name, f0=self.f0, df=self.df,\n                               frequencies=(hasattr(self, '_frequencies') and\n                                            self.frequencies or None))",
    "docstring": "Calculate a given spectral percentile for this `Spectrogram`.\n\n        Parameters\n        ----------\n        percentile : `float`\n            percentile (0 - 100) of the bins to compute\n\n        Returns\n        -------\n        spectrum : `~gwpy.frequencyseries.FrequencySeries`\n            the given percentile `FrequencySeries` calculated from this\n            `SpectralVaraicence`"
  },
  {
    "code": "def _GetWinevtRcDatabaseReader(self):\n    if not self._winevt_database_reader and self._data_location:\n      database_path = os.path.join(\n          self._data_location, self._WINEVT_RC_DATABASE)\n      if not os.path.isfile(database_path):\n        return None\n      self._winevt_database_reader = (\n          winevt_rc.WinevtResourcesSqlite3DatabaseReader())\n      if not self._winevt_database_reader.Open(database_path):\n        self._winevt_database_reader = None\n    return self._winevt_database_reader",
    "docstring": "Opens the Windows Event Log resource database reader.\n\n    Returns:\n      WinevtResourcesSqlite3DatabaseReader: Windows Event Log resource\n          database reader or None."
  },
  {
    "code": "def set_pause_param(self, autoneg, rx_pause, tx_pause):\n        ecmd = array.array('B', struct.pack('IIII',\n            ETHTOOL_SPAUSEPARAM, bool(autoneg), bool(rx_pause), bool(tx_pause)))\n        buf_addr, _buf_len = ecmd.buffer_info()\n        ifreq = struct.pack('16sP', self.name, buf_addr)\n        fcntl.ioctl(sockfd, SIOCETHTOOL, ifreq)",
    "docstring": "Ethernet has flow control! The inter-frame pause can be adjusted, by\n        auto-negotiation through an ethernet frame type with a simple two-field\n        payload, and by setting it explicitly.\n\n        http://en.wikipedia.org/wiki/Ethernet_flow_control"
  },
  {
    "code": "def shutdown(at_time=None):\n    cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')]\n    ret = __salt__['cmd.run'](cmd, python_shell=False)\n    return ret",
    "docstring": "Shutdown a running system\n\n    at_time\n        The wait time in minutes before the system will be shutdown.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' system.shutdown 5"
  },
  {
    "code": "def compute_voltages(grid, configs_raw, potentials_raw):\n    voltages = []\n    for config, potentials in zip(configs_raw, potentials_raw):\n        print('config', config)\n        e3_node = grid.get_electrode_node(config[2])\n        e4_node = grid.get_electrode_node(config[3])\n        print(e3_node, e4_node)\n        print('pot1', potentials[e3_node])\n        print('pot2', potentials[e4_node])\n        voltage = potentials[e3_node] - potentials[e4_node]\n        voltages.append(voltage)\n    return voltages",
    "docstring": "Given a list of potential distribution and corresponding four-point\n    spreads, compute the voltages\n\n    Parameters\n    ----------\n    grid:\n        crt_grid object the grid is used to infer electrode positions\n    configs_raw: Nx4 array\n        containing the measurement configs (1-indexed)\n    potentials_raw: list with N entries\n        corresponding to each measurement, containing the node potentials of\n        each injection dipole."
  },
  {
    "code": "def icons(self, strip_ext=False):\n        result =  [f for f in self._stripped_files if self._icons_pattern.match(f)]\n        if strip_ext:\n            result = [strip_suffix(f, '\\.({ext})'.format(ext=self._icons_ext), regex=True) for f in result]\n        return result",
    "docstring": "Get all icons in this DAP, optionally strip extensions"
  },
  {
    "code": "def HA1(realm, username, password, algorithm):\n    if not realm:\n        realm = u''\n    return H(b\":\".join([username.encode('utf-8'),\n                           realm.encode('utf-8'),\n                           password.encode('utf-8')]), algorithm)",
    "docstring": "Create HA1 hash by realm, username, password\n\n    HA1 = md5(A1) = MD5(username:realm:password)"
  },
  {
    "code": "def get_icon(self, iconset):\n        theme = iconset.attrib.get('theme')\n        if theme is not None:\n            return self._object_factory.createQObject(\"QIcon.fromTheme\",\n                    'icon', (self._object_factory.asString(theme), ),\n                    is_attribute=False)\n        if iconset.text is None:\n            return None\n        iset = _IconSet(iconset, self._base_dir)\n        try:\n            idx = self._cache.index(iset)\n        except ValueError:\n            idx = -1\n        if idx >= 0:\n            iset = self._cache[idx]\n        else:\n            name = 'icon'\n            idx = len(self._cache)\n            if idx > 0:\n                name += str(idx)\n            icon = self._object_factory.createQObject(\"QIcon\", name, (),\n                    is_attribute=False)\n            iset.set_icon(icon, self._qtgui_module)\n            self._cache.append(iset)\n        return iset.icon",
    "docstring": "Return an icon described by the given iconset tag."
  },
  {
    "code": "def exit(self, code=None, msg=None):\n        if code is None:\n            code = self.tcex.exit_code\n            if code == 3:\n                self.tcex.log.info(u'Changing exit code from 3 to 0.')\n                code = 0\n        elif code not in [0, 1]:\n            code = 1\n        self.tcex.exit(code, msg)",
    "docstring": "Playbook wrapper on TcEx exit method\n\n        Playbooks do not support partial failures so we change the exit method from 3 to 1 and call\n        it a partial success instead.\n\n        Args:\n            code (Optional [integer]): The exit code value for the app."
  },
  {
    "code": "def generate_index(fn, cols=None, names=None, sep=\" \"):\n    assert cols is not None, \"'cols' was not set\"\n    assert names is not None, \"'names' was not set\"\n    assert len(cols) == len(names)\n    bgzip, open_func = get_open_func(fn, return_fmt=True)\n    data = pd.read_csv(fn, sep=sep, engine=\"c\", usecols=cols, names=names,\n                       compression=\"gzip\" if bgzip else None)\n    f = open_func(fn, \"rb\")\n    data[\"seek\"] = np.fromiter(_seek_generator(f), dtype=np.uint)[:-1]\n    f.close()\n    write_index(get_index_fn(fn), data)\n    return data",
    "docstring": "Build a index for the given file.\n\n    Args:\n        fn (str): the name of the file.\n        cols (list): a list containing column to keep (as int).\n        names (list): the name corresponding to the column to keep (as str).\n        sep (str): the field separator.\n\n    Returns:\n        pandas.DataFrame: the index."
  },
  {
    "code": "def func(self):\n        fn = self.engine.query.sense_func_get(\n            self.observer.name,\n            self.sensename,\n            *self.engine._btt()\n        )\n        if fn is not None:\n            return SenseFuncWrap(self.observer, fn)",
    "docstring": "Return the function most recently associated with this sense."
  },
  {
    "code": "def get_default_connection():\n  tid = id(threading.current_thread())\n  conn = _conn_holder.get(tid)\n  if not conn:\n    with(_rlock):\n      if 'project_endpoint' not in _options and 'project_id' not in _options:\n        _options['project_endpoint'] = helper.get_project_endpoint_from_env()\n      if 'credentials' not in _options:\n        _options['credentials'] = helper.get_credentials_from_env()\n      _conn_holder[tid] = conn = connection.Datastore(**_options)\n  return conn",
    "docstring": "Returns the default datastore connection.\n\n  Defaults endpoint to helper.get_project_endpoint_from_env() and\n  credentials to helper.get_credentials_from_env().\n\n  Use set_options to override defaults."
  },
  {
    "code": "def get_container_version():\n    root_dir = os.path.dirname(os.path.realpath(sys.argv[0]))\n    version_file = os.path.join(root_dir, 'VERSION')\n    if os.path.exists(version_file):\n        with open(version_file) as f:\n            return f.read()\n    return ''",
    "docstring": "Return the version of the docker container running the present server,\n    or '' if not in a container"
  },
  {
    "code": "def contains_peroxide(structure, relative_cutoff=1.1):\n    ox_type = oxide_type(structure, relative_cutoff)\n    if ox_type == \"peroxide\":\n        return True\n    else:\n        return False",
    "docstring": "Determines if a structure contains peroxide anions.\n\n    Args:\n        structure (Structure): Input structure.\n        relative_cutoff: The peroxide bond distance is 1.49 Angstrom.\n            Relative_cutoff * 1.49 stipulates the maximum distance two O\n            atoms must be to each other to be considered a peroxide.\n\n    Returns:\n        Boolean indicating if structure contains a peroxide anion."
  },
  {
    "code": "def files(self):\n        for header in (r\"(.*)\\t\\[\\[\\[1\\n\", r\"^(\\d+)\\n$\"):\n            header = re.compile(header)\n            filename = None\n            self.fd.seek(0)\n            line = self.readline()\n            while line:\n                m = header.match(line)\n                if m is not None:\n                    filename = m.group(1)\n                    try:\n                        filelines = int(self.readline().rstrip())\n                    except ValueError:\n                        raise ArchiveError('invalid archive format')\n                    filestart = self.fd.tell()\n                    yield (filename, filelines, filestart)\n                line = self.readline()\n            if filename is not None:\n                break",
    "docstring": "Yields archive file information."
  },
  {
    "code": "def wrap_viscm(cmap, dpi=100, saveplot=False):\n    from viscm import viscm\n    viscm(cmap)\n    fig = plt.gcf()\n    fig.set_size_inches(22, 10)\n    plt.show()\n    if saveplot:\n        fig.savefig('figures/eval_' + cmap.name + '.png', bbox_inches='tight', dpi=dpi)\n        fig.savefig('figures/eval_' + cmap.name + '.pdf', bbox_inches='tight', dpi=dpi)",
    "docstring": "Evaluate goodness of colormap using perceptual deltas.\n\n    :param cmap: Colormap instance.\n    :param dpi=100: dpi for saved image.\n    :param saveplot=False: Whether to save the plot or not."
  },
  {
    "code": "def predict(self, test_X):\n        with self.tf_graph.as_default():\n            with tf.Session() as self.tf_session:\n                self.tf_saver.restore(self.tf_session, self.model_path)\n                feed = {\n                    self.input_data: test_X,\n                    self.keep_prob: 1\n                }\n                return self.mod_y.eval(feed)",
    "docstring": "Predict the labels for the test set.\n\n        Parameters\n        ----------\n\n        test_X : array_like, shape (n_samples, n_features)\n            Test data.\n\n        Returns\n        -------\n\n        array_like, shape (n_samples,) : predicted labels."
  },
  {
    "code": "def reshuffle(expr, by=None, sort=None, ascending=True):\n    by = by or RandomScalar()\n    grouped = expr.groupby(by)\n    if sort:\n        grouped = grouped.sort_values(sort, ascending=ascending)\n    return ReshuffledCollectionExpr(_input=grouped, _schema=expr._schema)",
    "docstring": "Reshuffle data.\n\n    :param expr:\n    :param by: the sequence or scalar to shuffle by. RandomScalar as default\n    :param sort: the sequence or scalar to sort.\n    :param ascending: True if ascending else False\n    :return: collection"
  },
  {
    "code": "def datetime_to_httpdate(dt):\n    if isinstance(dt, (int, float)):\n        return format_date_time(dt)\n    elif isinstance(dt, datetime):\n        return format_date_time(datetime_to_timestamp(dt))\n    else:\n        raise TypeError(\"expected datetime.datetime or timestamp (int/float),\"\n                        \" got '%s'\" % dt)",
    "docstring": "Convert datetime.datetime or Unix timestamp to HTTP date."
  },
  {
    "code": "def _update_health_monitor_with_new_ips(route_spec, all_ips,\n                                        q_monitor_ips):\n    new_all_ips = \\\n        sorted(set(itertools.chain.from_iterable(route_spec.values())))\n    if new_all_ips != all_ips:\n        logging.debug(\"New route spec detected. Updating \"\n                      \"health-monitor with: %s\" %\n                      \",\".join(new_all_ips))\n        all_ips = new_all_ips\n        q_monitor_ips.put(all_ips)\n    else:\n        logging.debug(\"New route spec detected. No changes in \"\n                      \"IP address list, not sending update to \"\n                      \"health-monitor.\")\n    return all_ips",
    "docstring": "Take the current route spec and compare to the current list of known IP\n    addresses. If the route spec mentiones a different set of IPs, update the\n    monitoring thread with that new list.\n\n    Return the current set of IPs mentioned in the route spec."
  },
  {
    "code": "def closedopen(lower_value, upper_value):\n    return Interval(Interval.CLOSED, lower_value, upper_value, Interval.OPEN)",
    "docstring": "Helper function to construct an interval object with a closed lower and open upper.\n\n    For example:\n\n    >>> closedopen(100.2, 800.9)\n    [100.2, 800.9)"
  },
  {
    "code": "def to_ufo_glyph_background(self, glyph, layer):\n    if not layer.hasBackground:\n        return\n    background = layer.background\n    ufo_layer = self.to_ufo_background_layer(glyph)\n    new_glyph = ufo_layer.newGlyph(glyph.name)\n    width = background.userData[BACKGROUND_WIDTH_KEY]\n    if width is not None:\n        new_glyph.width = width\n    self.to_ufo_background_image(new_glyph, background)\n    self.to_ufo_paths(new_glyph, background)\n    self.to_ufo_components(new_glyph, background)\n    self.to_ufo_glyph_anchors(new_glyph, background.anchors)\n    self.to_ufo_guidelines(new_glyph, background)",
    "docstring": "Set glyph background."
  },
  {
    "code": "def nl_socket_alloc(cb=None):\n    cb = cb or nl_cb_alloc(default_cb)\n    if not cb:\n        return None\n    sk = nl_sock()\n    sk.s_cb = cb\n    sk.s_local.nl_family = getattr(socket, 'AF_NETLINK', -1)\n    sk.s_peer.nl_family = getattr(socket, 'AF_NETLINK', -1)\n    sk.s_seq_expect = sk.s_seq_next = int(time.time())\n    sk.s_flags = NL_OWN_PORT\n    nl_socket_get_local_port(sk)\n    return sk",
    "docstring": "Allocate new Netlink socket. Does not yet actually open a socket.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L206\n\n    Also has code for generating local port once.\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L123\n\n    Keyword arguments:\n    cb -- custom callback handler.\n\n    Returns:\n    Newly allocated Netlink socket (nl_sock class instance) or None."
  },
  {
    "code": "def on_receive_request_vote_response(self, data):\n        if data.get('vote_granted'):\n            self.vote_count += 1\n            if self.state.is_majority(self.vote_count):\n                self.state.to_leader()",
    "docstring": "Receives response for vote request.\n        If the vote was granted then check if we got majority and may become Leader"
  },
  {
    "code": "def stop_capture(self):\n        super(Treal, self).stop_capture()\n        if self._machine:\n            self._machine.close()\n        self._stopped()",
    "docstring": "Stop listening for output from the stenotype machine."
  },
  {
    "code": "def add_beacon(self, name, beacon_data):\n        data = {}\n        data[name] = beacon_data\n        if name in self._get_beacons(include_opts=False):\n            comment = 'Cannot update beacon item {0}, ' \\\n                      'because it is configured in pillar.'.format(name)\n            complete = False\n        else:\n            if name in self.opts['beacons']:\n                comment = 'Updating settings for beacon ' \\\n                          'item: {0}'.format(name)\n            else:\n                comment = 'Added new beacon item: {0}'.format(name)\n            complete = True\n            self.opts['beacons'].update(data)\n        evt = salt.utils.event.get_event('minion', opts=self.opts)\n        evt.fire_event({'complete': complete, 'comment': comment,\n                        'beacons': self.opts['beacons']},\n                       tag='/salt/minion/minion_beacon_add_complete')\n        return True",
    "docstring": "Add a beacon item"
  },
  {
    "code": "def _get_source_chunks(self, input_text, language=None):\n    chunks = ChunkList()\n    seek = 0\n    result = self._get_annotations(input_text, language=language)\n    tokens = result['tokens']\n    language = result['language']\n    for i, token in enumerate(tokens):\n      word = token['text']['content']\n      begin_offset = token['text']['beginOffset']\n      label = token['dependencyEdge']['label']\n      pos = token['partOfSpeech']['tag']\n      if begin_offset > seek:\n        chunks.append(Chunk.space())\n        seek = begin_offset\n      chunk = Chunk(word, pos, label)\n      if chunk.label in _DEPENDENT_LABEL:\n        chunk.dependency = i < token['dependencyEdge']['headTokenIndex']\n      if chunk.is_punct():\n        chunk.dependency = chunk.is_open_punct()\n      chunks.append(chunk)\n      seek += len(word)\n    return chunks, language",
    "docstring": "Returns a chunk list retrieved from Syntax Analysis results.\n\n    Args:\n      input_text (str): Text to annotate.\n      language (:obj:`str`, optional): Language of the text.\n\n    Returns:\n      A chunk list. (:obj:`budou.chunk.ChunkList`)"
  },
  {
    "code": "def lookup_hostname(self, ip):\n\t\tres = self.lookup_by_lease(ip=ip)\n\t\tif \"client-hostname\" not in res:\n\t\t\traise OmapiErrorAttributeNotFound()\n\t\treturn res[\"client-hostname\"].decode('utf-8')",
    "docstring": "Look up a lease object with given ip address and return the associated client hostname.\n\n\t\t@type ip: str\n\t\t@rtype: str or None\n\t\t@raises ValueError:\n\t\t@raises OmapiError:\n\t\t@raises OmapiErrorNotFound: if no lease object with the given ip address could be found\n\t\t@raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks a hostname\n\t\t@raises socket.error:"
  },
  {
    "code": "def dashes_cleanup(records, prune_chars='.:?~'):\n    logging.info(\n        \"Applying _dashes_cleanup: converting any of '{}' to '-'.\".format(prune_chars))\n    translation_table = {ord(c): '-' for c in prune_chars}\n    for record in records:\n        record.seq = Seq(str(record.seq).translate(translation_table),\n                         record.seq.alphabet)\n        yield record",
    "docstring": "Take an alignment and convert any undesirable characters such as ? or ~ to\n    -."
  },
  {
    "code": "def _get_unicode(data, force=False):\n    if isinstance(data, binary_type):\n        return data.decode('utf-8')\n    elif data is None:\n        return ''\n    elif force:\n        if PY2:\n            return unicode(data)\n        else:\n            return str(data)\n    else:\n        return data",
    "docstring": "Try to return a text aka unicode object from the given data."
  },
  {
    "code": "def _get_arguments_for_execution(self, function_name, serialized_args):\n        arguments = []\n        for (i, arg) in enumerate(serialized_args):\n            if isinstance(arg, ObjectID):\n                argument = self.get_object([arg])[0]\n                if isinstance(argument, RayError):\n                    raise argument\n            else:\n                argument = arg\n            arguments.append(argument)\n        return arguments",
    "docstring": "Retrieve the arguments for the remote function.\n\n        This retrieves the values for the arguments to the remote function that\n        were passed in as object IDs. Arguments that were passed by value are\n        not changed. This is called by the worker that is executing the remote\n        function.\n\n        Args:\n            function_name (str): The name of the remote function whose\n                arguments are being retrieved.\n            serialized_args (List): The arguments to the function. These are\n                either strings representing serialized objects passed by value\n                or they are ray.ObjectIDs.\n\n        Returns:\n            The retrieved arguments in addition to the arguments that were\n                passed by value.\n\n        Raises:\n            RayError: This exception is raised if a task that\n                created one of the arguments failed."
  },
  {
    "code": "def get_chalk(level):\n    if level >= logging.ERROR:\n        _chalk = chalk.red\n    elif level >= logging.WARNING:\n        _chalk = chalk.yellow\n    elif level >= logging.INFO:\n        _chalk = chalk.blue\n    elif level >= logging.DEBUG:\n        _chalk = chalk.green\n    else:\n        _chalk = chalk.white\n    return _chalk",
    "docstring": "Gets the appropriate piece of chalk for the logging level"
  },
  {
    "code": "def pdftotext_conversion_is_bad(txtlines):\n    numWords = numSpaces = 0\n    p_space = re.compile(unicode(r'(\\s)'), re.UNICODE)\n    p_noSpace = re.compile(unicode(r'(\\S+)'), re.UNICODE)\n    for txtline in txtlines:\n        numWords = numWords + len(p_noSpace.findall(txtline.strip()))\n        numSpaces = numSpaces + len(p_space.findall(txtline.strip()))\n    if numSpaces >= (numWords * 3):\n        return True\n    else:\n        return False",
    "docstring": "Check if conversion after pdftotext is bad.\n\n    Sometimes pdftotext performs a bad conversion which consists of many\n    spaces and garbage characters.\n\n    This method takes a list of strings obtained from a pdftotext conversion\n    and examines them to see if they are likely to be the result of a bad\n    conversion.\n\n    :param txtlines: (list) of unicode strings obtained from pdftotext\n    conversion.\n    :return: (integer) - 1 if bad conversion; 0 if good conversion."
  },
  {
    "code": "def check_initial_web_request(self, item_session: ItemSession, request: HTTPRequest) -> Tuple[bool, str]:\n        verdict, reason, test_info = self.consult_filters(item_session.request.url_info, item_session.url_record)\n        if verdict and self._robots_txt_checker:\n            can_fetch = yield from self.consult_robots_txt(request)\n            if not can_fetch:\n                verdict = False\n                reason = 'robotstxt'\n        verdict, reason = self.consult_hook(\n            item_session, verdict, reason, test_info\n        )\n        return verdict, reason",
    "docstring": "Check robots.txt, URL filters, and scripting hook.\n\n        Returns:\n            tuple: (bool, str)\n\n        Coroutine."
  },
  {
    "code": "def _parse_perfdata(self, s):\n        metrics = []\n        counters = re.findall(self.TOKENIZER_RE, s)\n        if counters is None:\n            self.log.warning(\"Failed to parse performance data: {s}\".format(\n                s=s))\n            return metrics\n        for (key, value, uom, warn, crit, min, max) in counters:\n            try:\n                norm_value = self._normalize_to_unit(float(value), uom)\n                metrics.append((key, norm_value))\n            except ValueError:\n                self.log.warning(\n                    \"Couldn't convert value '{value}' to float\".format(\n                        value=value))\n        return metrics",
    "docstring": "Parse performance data from a perfdata string"
  },
  {
    "code": "def is_valid_scalar(self, node: ValueNode) -> None:\n        location_type = self.context.get_input_type()\n        if not location_type:\n            return\n        type_ = get_named_type(location_type)\n        if not is_scalar_type(type_):\n            self.report_error(\n                GraphQLError(\n                    bad_value_message(\n                        location_type,\n                        print_ast(node),\n                        enum_type_suggestion(type_, node),\n                    ),\n                    node,\n                )\n            )\n            return\n        type_ = cast(GraphQLScalarType, type_)\n        try:\n            parse_result = type_.parse_literal(node)\n            if is_invalid(parse_result):\n                self.report_error(\n                    GraphQLError(\n                        bad_value_message(location_type, print_ast(node)), node\n                    )\n                )\n        except Exception as error:\n            self.report_error(\n                GraphQLError(\n                    bad_value_message(location_type, print_ast(node), str(error)),\n                    node,\n                    original_error=error,\n                )\n            )",
    "docstring": "Check whether this is a valid scalar.\n\n        Any value literal may be a valid representation of a Scalar, depending on that\n        scalar type."
  },
  {
    "code": "def convert_slice_axis(node, **kwargs):\n    name, input_nodes, attrs = get_inputs(node, kwargs)\n    axes = int(attrs.get(\"axis\"))\n    starts = int(attrs.get(\"begin\"))\n    ends = int(attrs.get(\"end\", None))\n    if not ends:\n        raise ValueError(\"Slice: ONNX doesnt't support 'None' in 'end' attribute\")\n    node = onnx.helper.make_node(\n        \"Slice\",\n        input_nodes,\n        [name],\n        axes=[axes],\n        starts=[starts],\n        ends=[ends],\n        name=name,\n    )\n    return [node]",
    "docstring": "Map MXNet's slice_axis operator attributes to onnx's Slice operator\n    and return the created node."
  },
  {
    "code": "def default(self, user_input):\n        try:\n            for i in self._cs.disasm(unhexlify(self.cleanup(user_input)), self.base_address):\n                print(\"0x%08x:\\t%s\\t%s\" %(i.address, i.mnemonic, i.op_str))\n        except CsError as e:\n            print(\"Error: %s\" %e)",
    "docstring": "if no other command was invoked"
  },
  {
    "code": "def get_parents(docgraph, child_node, strict=True):\n    parents = []\n    for src, _, edge_attrs in docgraph.in_edges(child_node, data=True):\n        if edge_attrs['edge_type'] == EdgeTypes.dominance_relation:\n            parents.append(src)\n    if strict and len(parents) > 1:\n        raise ValueError((\"In a syntax tree, a node can't be \"\n                          \"dominated by more than one parent\"))\n    return parents",
    "docstring": "Return a list of parent nodes that dominate this child.\n\n    In a 'syntax tree' a node never has more than one parent node\n    dominating it. To enforce this, set strict=True.\n\n    Parameters\n    ----------\n    docgraph : DiscourseDocumentGraph\n        a document graph\n    strict : bool\n        If True, raise a ValueError if a child node is dominated\n        by more than one parent node.\n\n    Returns\n    -------\n    parents : list\n        a list of (parent) node IDs."
  },
  {
    "code": "def from_file(cls, name: str, mod_path: Tuple[str] = (\".\",),\n                  description: str = None) -> \"DataModel\":\n        with open(name, encoding=\"utf-8\") as infile:\n            yltxt = infile.read()\n        return cls(yltxt, mod_path, description)",
    "docstring": "Initialize the data model from a file with YANG library data.\n\n        Args:\n            name: Name of a file with YANG library data.\n            mod_path: Tuple of directories where to look for YANG modules.\n            description:  Optional description of the data model.\n\n        Returns:\n            The data model instance.\n\n        Raises:\n            The same exceptions as the class constructor above."
  },
  {
    "code": "def _getEnumValues(self, data):\n        enumstr = data.attrib.get('enumValues')\n        if not enumstr:\n            return None\n        if ':' in enumstr:\n            return {self._cast(k): v for k, v in [kv.split(':') for kv in enumstr.split('|')]}\n        return enumstr.split('|')",
    "docstring": "Returns a list of dictionary of valis value for this setting."
  },
  {
    "code": "def _get_converter(self, convert_to=None):\n        conversion = self._get_conversion_type(convert_to)\n        if conversion == \"singularity\":\n            return self.docker2singularity\n        return self.singularity2docker",
    "docstring": "see convert and save. This is a helper function that returns \n           the proper conversion function, but doesn't call it. We do this\n           so that in the case of convert, we do the conversion and return\n           a string. In the case of save, we save the recipe to file for the \n           user.\n\n           Parameters\n           ==========\n           convert_to: a string either docker or singularity, if a different\n\n           Returns\n           =======\n           converter: the function to do the conversion"
  },
  {
    "code": "def convert_sed_cols(tab):\n    for colname in list(tab.columns.keys()):\n        newname = colname.lower()\n        newname = newname.replace('dfde', 'dnde')\n        if tab.columns[colname].name == newname:\n            continue\n        tab.columns[colname].name = newname\n    return tab",
    "docstring": "Cast SED column names to lowercase."
  },
  {
    "code": "def create_stream(name, **header):\n    assert isinstance(name, basestring), name\n    return CreateStream(parent=None, name=name, group=False, header=header)",
    "docstring": "Create a stream for publishing messages.\n\n    All keyword arguments will be used to form the header."
  },
  {
    "code": "def one_of(*validators):\n    def validate(value, should_raise=True):\n        if any(validate(value, should_raise=False) for validate in validators):\n            return True\n        if should_raise:\n            raise TypeError(\"value did not match any allowable type\")\n        return False\n    return validate",
    "docstring": "Returns a validator function that succeeds only if the input passes at least one of the provided validators.\n\n    :param callable validators: the validator functions\n    :returns: a function which returns True its input passes at least one of the validators, and raises TypeError\n              otherwise\n    :rtype: callable"
  },
  {
    "code": "def update_security_of_password(self, ID, data):\n        log.info('Update security of password %s with %s' % (ID, data))\n        self.put('passwords/%s/security.json' % ID, data)",
    "docstring": "Update security of a password."
  },
  {
    "code": "def _get_spades_circular_nodes(self, fastg):\n        seq_reader = pyfastaq.sequences.file_reader(fastg)\n        names = set([x.id.rstrip(';') for x in seq_reader if ':' in x.id])\n        found_fwd = set()\n        found_rev = set()\n        for name in names:\n            l = name.split(':')\n            if len(l) != 2:\n                continue\n            if l[0] == l[1]:\n                if l[0][-1] == \"'\":\n                    found_rev.add(l[0][:-1])\n                else:\n                    found_fwd.add(l[0])\n        return found_fwd.intersection(found_rev)",
    "docstring": "Returns set of names of nodes in SPAdes fastg file that are circular. Names will match those in spades fasta file"
  },
  {
    "code": "def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None):\n        if type(rdata) is not list:\n            rdata = [rdata]\n        rrset = {\"ttl\": ttl, \"rdata\": rdata}\n        if profile:\n            rrset[\"profile\"] = profile\n        uri = \"/v1/zones/\" + zone_name + \"/rrsets/\" + rtype + \"/\" + owner_name\n        return self.rest_api_connection.put(uri, json.dumps(rrset))",
    "docstring": "Updates an existing RRSet in the specified zone.\n\n        Arguments:\n        zone_name -- The zone that contains the RRSet.  The trailing dot is optional.\n        rtype -- The type of the RRSet.  This can be numeric (1) or\n                 if a well-known name is defined for the type (A), you can use it instead.\n        owner_name -- The owner name for the RRSet.\n                      If no trailing dot is supplied, the owner_name is assumed to be relative (foo).\n                      If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.)\n        ttl -- The updated TTL value for the RRSet.\n        rdata -- The updated BIND data for the RRSet as a string.\n                 If there is a single resource record in the RRSet, you can pass in the single string.\n                 If there are multiple resource records  in this RRSet, pass in a list of strings.\n        profile -- The profile info if this is updating a resource pool"
  },
  {
    "code": "def unresolve_filename(self, package_dir, filename):\n        filename, _ = os.path.splitext(filename)\n        if self.strip_extension:\n            for ext in ('.scss', '.sass'):\n                test_path = os.path.join(\n                    package_dir, self.sass_path, filename + ext,\n                )\n                if os.path.exists(test_path):\n                    return filename + ext\n            else:\n                return filename + '.scss'\n        else:\n            return filename",
    "docstring": "Retrieves the probable source path from the output filename.  Pass\n        in a .css path to get out a .scss path.\n\n        :param package_dir: the path of the package directory\n        :type package_dir: :class:`str`\n        :param filename: the css filename\n        :type filename: :class:`str`\n        :returns: the scss filename\n        :rtype: :class:`str`"
  },
  {
    "code": "def _check_and_apply_deprecations(self, scope, values):\n    si = self.known_scope_to_info[scope]\n    if si.removal_version:\n      explicit_keys = self.for_scope(scope, inherit_from_enclosing_scope=False).get_explicit_keys()\n      if explicit_keys:\n        warn_or_error(\n            removal_version=si.removal_version,\n            deprecated_entity_description='scope {}'.format(scope),\n            hint=si.removal_hint,\n          )\n    deprecated_scope = si.deprecated_scope\n    if deprecated_scope is not None and scope != deprecated_scope:\n      explicit_keys = self.for_scope(deprecated_scope,\n                                     inherit_from_enclosing_scope=False).get_explicit_keys()\n      if explicit_keys:\n        values.update(self.for_scope(deprecated_scope))\n        warn_or_error(\n            removal_version=self.known_scope_to_info[scope].deprecated_scope_removal_version,\n            deprecated_entity_description='scope {}'.format(deprecated_scope),\n            hint='Use scope {} instead (options: {})'.format(scope, ', '.join(explicit_keys))\n          )",
    "docstring": "Checks whether a ScopeInfo has options specified in a deprecated scope.\n\n    There are two related cases here. Either:\n      1) The ScopeInfo has an associated deprecated_scope that was replaced with a non-deprecated\n         scope, meaning that the options temporarily live in two locations.\n      2) The entire ScopeInfo is deprecated (as in the case of deprecated SubsystemDependencies),\n         meaning that the options live in one location.\n\n    In the first case, this method has the sideeffect of merging options values from deprecated\n    scopes into the given values."
  },
  {
    "code": "def to_string(type):\n        if type == None:\n            return \"unknown\"\n        elif type == TypeCode.Unknown:\n            return \"unknown\"\n        elif type == TypeCode.String:\n            return \"string\"\n        elif type == TypeCode.Integer:\n            return \"integer\"\n        elif type == TypeCode.Long:\n            return \"long\"\n        elif type == TypeCode.Float:\n            return \"float\"\n        elif type == TypeCode.Double:\n            return \"double\"\n        elif type == TypeCode.Duration:\n            return \"duration\"\n        elif type == TypeCode.DateTime:\n            return \"datetime\"\n        elif type == TypeCode.Object:\n            return \"object\"\n        elif type == TypeCode.Enum:\n            return \"enum\"\n        elif type == TypeCode.Array:\n            return \"array\"\n        elif type == TypeCode.Map:\n            return \"map\"\n        else:\n            return \"unknown\"",
    "docstring": "Converts a TypeCode into its string name.\n\n        :param type: the TypeCode to convert into a string.\n\n        :return: the name of the TypeCode passed as a string value."
  },
  {
    "code": "def manage_submissions(self):\n        if not hasattr(self, 'submissions') or len(self.submissions) == 1:\n            self.submissions = []\n            if self.options['mode'] == 'front':\n                if self.options['password'] and self.options['username']:\n                    self.login()\n                url = 'http://reddit.com/.json?sort={0}'.format(self.options['sort'])\n                self.submissions = self.get_submissions(url)\n            elif self.options['mode'] == 'subreddit':\n                for subreddit in self.options['subreddits']:\n                    url = 'http://reddit.com/r/{0}/.json?sort={1}'.format(\n                        subreddit, self.options['limit'])\n                    self.submissions += self.get_submissions(url)\n        else:\n            return",
    "docstring": "If there are no or only one submissions left, get new submissions.\n        This function manages URL creation and the specifics for front page\n        or subreddit mode."
  },
  {
    "code": "def sle(actual, predicted):\n    return (np.power(np.log(np.array(actual)+1) - \n            np.log(np.array(predicted)+1), 2))",
    "docstring": "Computes the squared log error.\n\n    This function computes the squared log error between two numbers,\n    or for element between a pair of lists or numpy arrays.\n\n    Parameters\n    ----------\n    actual : int, float, list of numbers, numpy array\n             The ground truth value\n    predicted : same type as actual\n                The predicted value\n\n    Returns\n    -------\n    score : double or list of doubles\n            The squared log error between actual and predicted"
  },
  {
    "code": "def _local_install(self, args, pkg_name=None):\n        if len(args) < 2:\n            raise SPMInvocationError('A package file must be specified')\n        self._install(args)",
    "docstring": "Install a package from a file"
  },
  {
    "code": "def teardown_websocket(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:\n        handler = ensure_coroutine(func)\n        self.teardown_websocket_funcs[name].append(handler)\n        return func",
    "docstring": "Add a teardown websocket function.\n\n        This is designed to be used as a decorator. An example usage,\n\n        .. code-block:: python\n\n            @app.teardown_websocket\n            def func():\n                ...\n\n        Arguments:\n            func: The teardown websocket function itself.\n            name: Optional blueprint key name."
  },
  {
    "code": "async def remove(self, von_wallet: Wallet) -> None:\n        LOGGER.debug('WalletManager.remove >>> wallet %s', von_wallet)\n        await von_wallet.remove()\n        LOGGER.debug('WalletManager.remove <<<')",
    "docstring": "Remove serialized wallet if it exists. Raise WalletState if wallet is open.\n\n        :param von_wallet: (closed) wallet to remove"
  },
  {
    "code": "def send(self, data, sample_rate=None):\n        if self._disabled:\n            self.logger.debug('Connection disabled, not sending data')\n            return False\n        if sample_rate is None:\n            sample_rate = self._sample_rate\n        sampled_data = {}\n        if sample_rate < 1:\n            if random.random() <= sample_rate:\n                for stat, value in compat.iter_dict(data):\n                    sampled_data[stat] = '%s|@%s' % (data[stat], sample_rate)\n        else:\n            sampled_data = data\n        try:\n            for stat, value in compat.iter_dict(sampled_data):\n                send_data = ('%s:%s' % (stat, value)).encode(\"utf-8\")\n                self.udp_sock.send(send_data)\n            return True\n        except Exception as e:\n            self.logger.exception('unexpected error %r while sending data', e)\n            return False",
    "docstring": "Send the data over UDP while taking the sample_rate in account\n\n        The sample rate should be a number between `0` and `1` which indicates\n        the probability that a message will be sent. The sample_rate is also\n        communicated to `statsd` so it knows what multiplier to use.\n\n        :keyword data: The data to send\n        :type data: dict\n        :keyword sample_rate: The sample rate, defaults to `1` (meaning always)\n        :type sample_rate: int"
  },
  {
    "code": "def getHTML(self):\n        root = self.getRoot()\n        if root is None:\n            raise ValueError('Did not parse anything. Use parseFile or parseStr')\n        if self.doctype:\n            doctypeStr = '<!%s>\\n' %(self.doctype)\n        else:\n            doctypeStr = ''\n        rootNode = self.getRoot()\n        if rootNode.tagName == INVISIBLE_ROOT_TAG:\n            return doctypeStr + rootNode.innerHTML\n        else:\n            return doctypeStr + rootNode.outerHTML",
    "docstring": "getHTML - Get the full HTML as contained within this tree.\n\n                If parsed from a document, this will contain the original whitespacing.\n\n                @returns - <str> of html\n\n                    @see getFormattedHTML\n\n                    @see getMiniHTML"
  },
  {
    "code": "def to_decimal(number, strip='- '):\n    if isinstance(number, six.integer_types):\n        return str(number)\n    number = str(number)\n    number = re.sub(r'[%s]' % re.escape(strip), '', number)\n    if number.startswith('0x'):\n        return to_decimal(int(number[2:], 16))\n    elif number.startswith('o'):\n        return to_decimal(int(number[1:], 8))\n    elif number.startswith('b'):\n        return to_decimal(int(number[1:], 2))\n    else:\n        return str(int(number))",
    "docstring": "Converts a number to a string of decimals in base 10.\n\n    >>> to_decimal(123)\n    '123'\n    >>> to_decimal('o123')\n    '83'\n    >>> to_decimal('b101010')\n    '42'\n    >>> to_decimal('0x2a')\n    '42'"
  },
  {
    "code": "def compile_jobgroups_from_joblist(joblist, jgprefix, sgegroupsize):\n    jobcmds = defaultdict(list)\n    for job in joblist:\n        jobcmds[job.command.split(' ', 1)[0]].append(job.command)\n    jobgroups = []\n    for cmds in list(jobcmds.items()):\n        sublists = split_seq(cmds[1], sgegroupsize)\n        count = 0\n        for sublist in sublists:\n            count += 1\n            sge_jobcmdlist = ['\\\"%s\\\"' % jc for jc in sublist]\n            jobgroups.append(JobGroup(\"%s_%d\" % (jgprefix, count),\n                                      \"$cmds\",\n                                      arguments={'cmds': sge_jobcmdlist}))\n    return jobgroups",
    "docstring": "Return list of jobgroups, rather than list of jobs."
  },
  {
    "code": "def fetch(self, remote=None, refspec=None, verbose=False, tags=True):\n        return git_fetch(self.repo_dir, remote=remote,\n                         refspec=refspec, verbose=verbose, tags=tags)",
    "docstring": "Do a git fetch of `refspec`."
  },
  {
    "code": "def _MergeEntities(self, a, b):\n    scheme = {'price': self._MergeIdentical,\n              'currency_type': self._MergeIdentical,\n              'payment_method': self._MergeIdentical,\n              'transfers': self._MergeIdentical,\n              'transfer_duration': self._MergeIdentical}\n    return self._SchemedMerge(scheme, a, b)",
    "docstring": "Merges the fares if all the attributes are the same."
  },
  {
    "code": "def _compute_delta_beta(self, df, events, start, stop, weights):\n        score_residuals = self._compute_residuals(df, events, start, stop, weights) * weights[:, None]\n        naive_var = inv(self._hessian_)\n        delta_betas = -score_residuals.dot(naive_var) / self._norm_std.values\n        return delta_betas",
    "docstring": "approximate change in betas as a result of excluding ith row"
  },
  {
    "code": "def get_loglevel(level):\n    if level == 'debug':\n        return logging.DEBUG\n    elif level == 'notice':\n        return logging.INFO\n    elif level == 'info':\n        return logging.INFO\n    elif level == 'warning' or level == 'warn':\n        return logging.WARNING\n    elif level == 'error' or level == 'err':\n        return logging.ERROR\n    elif level == 'critical' or level == 'crit':\n        return logging.CRITICAL\n    elif level == 'alert':\n        return logging.CRITICAL\n    elif level == 'emergency' or level == 'emerg':\n        return logging.CRITICAL\n    else:\n        return logging.INFO",
    "docstring": "return logging level object\n    corresponding to a given level passed as\n    a string\n    @str level: name of a syslog log level\n    @rtype: logging, logging level from logging module"
  },
  {
    "code": "def connect(self, dsn):\n        self.con = psycopg2.connect(dsn)\n        self.cur = self.con.cursor(cursor_factory=psycopg2.extras.DictCursor)\n        self.con.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)",
    "docstring": "Connect to DB.\n\n        dbname: the database name user: user name used to authenticate password:\n        password used to authenticate host: database host address (defaults to UNIX\n        socket if not provided) port: connection port number (defaults to 5432 if not\n        provided)"
  },
  {
    "code": "def summary(self):\n        if not self.translations:\n            self.update()\n        return [summary.taf(trans) for trans in self.translations.forecast]",
    "docstring": "Condensed summary for each forecast created from translations"
  },
  {
    "code": "def visit_create_library_command(element, compiler, **kw):\n    query =\n    bindparams = [\n        sa.bindparam(\n            'location',\n            value=element.location,\n            type_=sa.String,\n        ),\n        sa.bindparam(\n            'credentials',\n            value=element.credentials,\n            type_=sa.String,\n        ),\n    ]\n    if element.region is not None:\n        bindparams.append(sa.bindparam(\n            'region',\n            value=element.region,\n            type_=sa.String,\n        ))\n    quoted_lib_name = compiler.preparer.quote_identifier(element.library_name)\n    query = query.format(name=quoted_lib_name,\n                         or_replace='OR REPLACE' if element.replace else '',\n                         region='REGION :region' if element.region else '')\n    return compiler.process(sa.text(query).bindparams(*bindparams), **kw)",
    "docstring": "Returns the actual sql query for the CreateLibraryCommand class."
  },
  {
    "code": "def reload(self):\n        utt_ids = sorted(self.utt_ids)\n        if self.shuffle:\n            self.rand.shuffle(utt_ids)\n        partitions = []\n        current_partition = PartitionInfo()\n        for utt_id in utt_ids:\n            utt_size = self.utt_sizes[utt_id]\n            utt_lengths = self.utt_lengths[utt_id]\n            if current_partition.size + utt_size > self.partition_size:\n                partitions.append(current_partition)\n                current_partition = PartitionInfo()\n            current_partition.utt_ids.append(utt_id)\n            current_partition.utt_lengths.append(utt_lengths)\n            current_partition.size += utt_size\n        if current_partition.size > 0:\n            partitions.append(current_partition)\n        self.partitions = partitions\n        return self.partitions",
    "docstring": "Create a new partition scheme. A scheme defines which utterances are in which partition.\n        The scheme only changes after every call if ``self.shuffle == True``.\n\n        Returns:\n            list: List of PartitionInfo objects, defining the new partitions (same as ``self.partitions``)"
  },
  {
    "code": "def compile_resource(resource):\n    return re.compile(\"^\" + trim_resource(re.sub(r\":(\\w+)\", r\"(?P<\\1>[\\w-]+?)\",\n                      resource)) + r\"(\\?(?P<querystring>.*))?$\")",
    "docstring": "Return compiled regex for resource matching"
  },
  {
    "code": "def serialize_yaml_tofile(filename, resource):\n    stream = file(filename, \"w\")\n    yaml.dump(resource, stream, default_flow_style=False)",
    "docstring": "Serializes a K8S resource to YAML-formatted file."
  },
  {
    "code": "def mequg(m1, nr, nc):\n    m1 = stypes.toDoubleMatrix(m1)\n    mout = stypes.emptyDoubleMatrix(x=nc, y=nr)\n    nc = ctypes.c_int(nc)\n    nr = ctypes.c_int(nr)\n    libspice.mequg_c(m1, nc, nr, mout)\n    return stypes.cMatrixToNumpy(mout)",
    "docstring": "Set one double precision matrix of arbitrary size equal to another.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mequg_c.html\n\n    :param m1: Input matrix.\n    :type m1: NxM-Element Array of floats\n    :param nr: Row dimension of m1.\n    :type nr: int\n    :param nc: Column dimension of m1.\n    :type nc: int\n    :return: Output matrix equal to m1\n    :rtype: NxM-Element Array of floats"
  },
  {
    "code": "def run(self, *args):\n        self.parser.parse_args(args)\n        code = self.affiliate()\n        return code",
    "docstring": "Affiliate unique identities to organizations."
  },
  {
    "code": "def print_config(_run):\n    final_config = _run.config\n    config_mods = _run.config_modifications\n    print(_format_config(final_config, config_mods))",
    "docstring": "Print the updated configuration and exit.\n\n    Text is highlighted:\n      green:  value modified\n      blue:   value added\n      red:    value modified but type changed"
  },
  {
    "code": "def reset( self ):\n        dataSet = self.dataSet()\n        if ( not dataSet ):\n            dataSet = XScheme()\n        dataSet.reset()",
    "docstring": "Resets the colors to the default settings."
  },
  {
    "code": "def string_for_count(dictionary, count):\n    string_to_print = \"\"\n    if count is not None:\n        if count == 0:\n            return \"\"\n        ranger = count\n    else:\n        ranger = 2\n    for index in range(ranger):\n        string_to_print += \"{} \".format(get_random_word(dictionary))\n    return string_to_print.strip()",
    "docstring": "Create a random string of N=`count` words"
  },
  {
    "code": "def _set_program_defaults(cls, programs):\n        for program in programs:\n            val = getattr(cls, program.__name__) \\\n                and extern.does_external_program_run(program.__name__,\n                                                     Settings.verbose)\n            setattr(cls, program.__name__, val)",
    "docstring": "Run the external program tester on the required binaries."
  },
  {
    "code": "def avhrr(scans_nb, scan_points,\n          scan_angle=55.37, frequency=1 / 6.0, apply_offset=True):\n    avhrr_inst = np.vstack(((scan_points / 1023.5 - 1)\n                            * np.deg2rad(-scan_angle),\n                            np.zeros((len(scan_points),))))\n    avhrr_inst = np.tile(\n        avhrr_inst[:, np.newaxis, :], [1, np.int(scans_nb), 1])\n    times = np.tile(scan_points * 0.000025, [np.int(scans_nb), 1])\n    if apply_offset:\n        offset = np.arange(np.int(scans_nb)) * frequency\n        times += np.expand_dims(offset, 1)\n    return ScanGeometry(avhrr_inst, times)",
    "docstring": "Definition of the avhrr instrument.\n\n    Source: NOAA KLM User's Guide, Appendix J\n    http://www.ncdc.noaa.gov/oa/pod-guide/ncdc/docs/klm/html/j/app-j.htm"
  },
  {
    "code": "def build_parameter(name, properties):\n    p = Parameter(name, Type=properties.get(\"type\"))\n    for name, attr in PARAMETER_PROPERTIES.items():\n        if name in properties:\n            setattr(p, attr, properties[name])\n    return p",
    "docstring": "Builds a troposphere Parameter with the given properties.\n\n    Args:\n        name (string): The name of the parameter.\n        properties (dict): Contains the properties that will be applied to the\n            parameter. See:\n            http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html\n\n    Returns:\n        :class:`troposphere.Parameter`: The created parameter object."
  },
  {
    "code": "def PushEventSource(self, event_source):\n    if event_source.file_entry_type == (\n        dfvfs_definitions.FILE_ENTRY_TYPE_DIRECTORY):\n      weight = 1\n    else:\n      weight = 100\n    heap_values = (weight, time.time(), event_source)\n    heapq.heappush(self._heap, heap_values)",
    "docstring": "Pushes an event source onto the heap.\n\n    Args:\n      event_source (EventSource): event source."
  },
  {
    "code": "def export_elements(self, filename='export_elements.zip', typeof='all'):\n        valid_types = ['all', 'nw', 'ips', 'sv', 'rb', 'al', 'vpn']\n        if typeof not in valid_types:\n            typeof = 'all'\n        return Task.download(self, 'export_elements', filename,\n            params={'recursive': True, 'type': typeof})",
    "docstring": "Export elements from SMC.\n\n        Valid types are:\n        all (All Elements)|nw (Network Elements)|ips (IPS Elements)|\n        sv (Services)|rb (Security Policies)|al (Alerts)|\n        vpn (VPN Elements)\n\n        :param type: type of element\n        :param filename: Name of file for export\n        :raises TaskRunFailed: failure during export with reason\n        :rtype: DownloadTask"
  },
  {
    "code": "def read_until_regex(self, regex: bytes, max_bytes: int = None) -> Awaitable[bytes]:\n        future = self._start_read()\n        self._read_regex = re.compile(regex)\n        self._read_max_bytes = max_bytes\n        try:\n            self._try_inline_read()\n        except UnsatisfiableReadError as e:\n            gen_log.info(\"Unsatisfiable read, closing connection: %s\" % e)\n            self.close(exc_info=e)\n            return future\n        except:\n            future.add_done_callback(lambda f: f.exception())\n            raise\n        return future",
    "docstring": "Asynchronously read until we have matched the given regex.\n\n        The result includes the data that matches the regex and anything\n        that came before it.\n\n        If ``max_bytes`` is not None, the connection will be closed\n        if more than ``max_bytes`` bytes have been read and the regex is\n        not satisfied.\n\n        .. versionchanged:: 4.0\n            Added the ``max_bytes`` argument.  The ``callback`` argument is\n            now optional and a `.Future` will be returned if it is omitted.\n\n        .. versionchanged:: 6.0\n\n           The ``callback`` argument was removed. Use the returned\n           `.Future` instead."
  },
  {
    "code": "def pickle_compress(obj, print_compression_info=False):\n    p = pickle.dumps(obj)\n    c = zlib.compress(p)\n    if print_compression_info:\n        print (\"len = {:,d} compr={:,d} ratio:{:.6f}\".format(len(p), len(c), float(len(c))/len(p)))\n    return c",
    "docstring": "pickle and compress an object"
  },
  {
    "code": "def from_string(cls, dataset_id, default_project=None):\n        output_dataset_id = dataset_id\n        output_project_id = default_project\n        parts = dataset_id.split(\".\")\n        if len(parts) == 1 and not default_project:\n            raise ValueError(\n                \"When default_project is not set, dataset_id must be a \"\n                \"fully-qualified dataset ID in standard SQL format. \"\n                'e.g. \"project.dataset_id\", got {}'.format(dataset_id)\n            )\n        elif len(parts) == 2:\n            output_project_id, output_dataset_id = parts\n        elif len(parts) > 2:\n            raise ValueError(\n                \"Too many parts in dataset_id. Expected a fully-qualified \"\n                \"dataset ID in standard SQL format. e.g. \"\n                '\"project.dataset_id\", got {}'.format(dataset_id)\n            )\n        return cls(output_project_id, output_dataset_id)",
    "docstring": "Construct a dataset reference from dataset ID string.\n\n        Args:\n            dataset_id (str):\n                A dataset ID in standard SQL format. If ``default_project``\n                is not specified, this must included both the project ID and\n                the dataset ID, separated by ``.``.\n            default_project (str):\n                Optional. The project ID to use when ``dataset_id`` does not\n                include a project ID.\n\n        Returns:\n            DatasetReference:\n                Dataset reference parsed from ``dataset_id``.\n\n        Examples:\n            >>> DatasetReference.from_string('my-project-id.some_dataset')\n            DatasetReference('my-project-id', 'some_dataset')\n\n        Raises:\n            ValueError:\n                If ``dataset_id`` is not a fully-qualified dataset ID in\n                standard SQL format."
  },
  {
    "code": "def _range_check(self, value, min_value, max_value):\n        if value < min_value or value > max_value:\n            raise ValueError('%s out of range - %s is not between %s and %s' % (self.__class__.__name__, value, min_value, max_value))",
    "docstring": "Utility method to check that the given value is between min_value and max_value."
  },
  {
    "code": "def createDocument(self, initDict = None) :\n        if initDict is not None :\n            return self.createDocument_(initDict)\n        else :\n            if self._validation[\"on_load\"] :\n                self._validation[\"on_load\"] = False\n                return self.createDocument_(self.defaultDocument)\n                self._validation[\"on_load\"] = True\n            else :\n                return self.createDocument_(self.defaultDocument)",
    "docstring": "create and returns a document populated with the defaults or with the values in initDict"
  },
  {
    "code": "def categories_percent(s, categories):\n    count = 0\n    s = to_unicode(s, precise=True)\n    for c in s:\n        if unicodedata.category(c) in categories:\n            count += 1\n    return 100 * float(count) / len(s) if len(s) else 0",
    "docstring": "Returns category characters percent.\n\n    >>> categories_percent(\"qqq ggg hhh\", [\"Po\"])\n    0.0\n    >>> categories_percent(\"q,w.\", [\"Po\"])\n    50.0\n    >>> categories_percent(\"qqq ggg hhh\", [\"Nd\"])\n    0.0\n    >>> categories_percent(\"q5\", [\"Nd\"])\n    50.0\n    >>> categories_percent(\"s.s,5s\", [\"Po\", \"Nd\"])\n    50.0"
  },
  {
    "code": "def send_vdp_vnic_down(self, port_uuid=None, vsiid=None, mgrid=None,\n                           typeid=None, typeid_ver=None,\n                           vsiid_frmt=vdp_const.VDP_VSIFRMT_UUID,\n                           filter_frmt=vdp_const.VDP_FILTER_GIDMACVID,\n                           gid=0, mac=\"\", vlan=0, oui=\"\"):\n        try:\n            with self.mutex_lock:\n                self.send_vdp_deassoc(vsiid=vsiid, mgrid=mgrid, typeid=typeid,\n                                      typeid_ver=typeid_ver,\n                                      vsiid_frmt=vsiid_frmt,\n                                      filter_frmt=filter_frmt, gid=gid,\n                                      mac=mac, vlan=vlan)\n                self.clear_vdp_vsi(port_uuid)\n        except Exception as e:\n            LOG.error(\"VNIC Down exception %s\", e)",
    "docstring": "Interface function to apps, called for a vNIC DOWN.\n\n        This currently sends an VDP dis-associate message.\n        Please refer http://www.ieee802.org/1/pages/802.1bg.html VDP\n        Section for more detailed information\n        :param uuid: uuid of the vNIC\n        :param vsiid: VSI value, Only UUID supported for now\n        :param mgrid: MGR ID\n        :param typeid: Type ID\n        :param typeid_ver: Version of the Type ID\n        :param vsiid_frmt: Format of the following VSI argument\n        :param filter_frmt: Filter Format. Only <GID,MAC,VID> supported for now\n        :param gid: Group ID the vNIC belongs to\n        :param mac: MAC Address of the vNIC\n        :param vlan: VLAN of the vNIC\n        :param oui_id: OUI Type\n        :param oui_data: OUI Data\n        :param sw_resp: Flag indicating if response is required from the daemon"
  },
  {
    "code": "def UpsertUserDefinedFunction(self, collection_link, udf, options=None):\n        if options is None:\n            options = {}\n        collection_id, path, udf = self._GetContainerIdWithPathForUDF(collection_link, udf)\n        return self.Upsert(udf,\n                           path,\n                           'udfs',\n                           collection_id,\n                           None,\n                           options)",
    "docstring": "Upserts a user defined function in a collection.\n\n        :param str collection_link:\n            The link to the collection.\n        :param str udf:\n        :param dict options:\n            The request options for the request.\n\n        :return:\n            The upserted UDF.\n        :rtype:\n            dict"
  },
  {
    "code": "def json(self):\n        try:\n            return self._json\n        except AttributeError:\n            try:\n                self._json = json.loads(self.text)\n                return self._json\n            except:\n                raise RequestInvalidJSON(\"Invalid JSON received\")",
    "docstring": "Return an object representing the return json for the request"
  },
  {
    "code": "def parse_sql(self, asql):\n        import sqlparse\n        statements = sqlparse.parse(sqlparse.format(asql, strip_comments=True))\n        parsed_statements = []\n        for statement in statements:\n            statement_str = statement.to_unicode().strip()\n            for preprocessor in self._backend.sql_processors():\n                statement_str = preprocessor(statement_str, self._library, self._backend, self.connection)\n            parsed_statements.append(statement_str)\n        return parsed_statements",
    "docstring": "Executes all sql statements from asql.\n\n        Args:\n            library (library.Library):\n            asql (str): ambry sql query - see https://github.com/CivicKnowledge/ambry/issues/140 for details."
  },
  {
    "code": "def snow_depth(self, value=999.0):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type float '\n                                 'for field `snow_depth`'.format(value))\n        self._snow_depth = value",
    "docstring": "Corresponds to IDD Field `snow_depth`\n\n        Args:\n            value (float): value for IDD Field `snow_depth`\n                Unit: cm\n                Missing value: 999.0\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def shuffle_columns( a ):\n    mask = range( a.text_size )\n    random.shuffle( mask )\n    for c in a.components:\n        c.text = ''.join( [ c.text[i] for i in mask ] )",
    "docstring": "Randomize the columns of an alignment"
  },
  {
    "code": "def write(self, group_id, handle):\n        name = self.name.encode('utf-8')\n        handle.write(struct.pack('bb', len(name), group_id))\n        handle.write(name)\n        handle.write(struct.pack('<h', self.binary_size() - 2 - len(name)))\n        handle.write(struct.pack('b', self.bytes_per_element))\n        handle.write(struct.pack('B', len(self.dimensions)))\n        handle.write(struct.pack('B' * len(self.dimensions), *self.dimensions))\n        if self.bytes:\n            handle.write(self.bytes)\n        desc = self.desc.encode('utf-8')\n        handle.write(struct.pack('B', len(desc)))\n        handle.write(desc)",
    "docstring": "Write binary data for this parameter to a file handle.\n\n        Parameters\n        ----------\n        group_id : int\n            The numerical ID of the group that holds this parameter.\n        handle : file handle\n            An open, writable, binary file handle."
  },
  {
    "code": "def _waitForIP(cls, instance):\n        logger.debug('Waiting for ip...')\n        while True:\n            time.sleep(a_short_time)\n            instance.update()\n            if instance.ip_address or instance.public_dns_name or instance.private_ip_address:\n                logger.debug('...got ip')\n                break",
    "docstring": "Wait until the instances has a public IP address assigned to it.\n\n        :type instance: boto.ec2.instance.Instance"
  },
  {
    "code": "def single(C, namespace=None):\n        if namespace is None:\n            B = C()._\n        else:\n            B = C(default=namespace, _=namespace)._\n        return B",
    "docstring": "An element maker with a single namespace that uses that namespace as the default"
  },
  {
    "code": "def get_all_users(self, path_prefix='/', marker=None, max_items=None):\n        params = {'PathPrefix' : path_prefix}\n        if marker:\n            params['Marker'] = marker\n        if max_items:\n            params['MaxItems'] = max_items\n        return self.get_response('ListUsers', params, list_marker='Users')",
    "docstring": "List the users that have the specified path prefix.\n\n        :type path_prefix: string\n        :param path_prefix: If provided, only users whose paths match\n                            the provided prefix will be returned.\n\n        :type marker: string\n        :param marker: Use this only when paginating results and only in\n                       follow-up request after you've received a response\n                       where the results are truncated.  Set this to the\n                       value of the Marker element in the response you\n                       just received.\n\n        :type max_items: int\n        :param max_items: Use this only when paginating results to indicate\n                          the maximum number of groups you want in the\n                          response."
  },
  {
    "code": "def explain_weights_lightning(estimator, vec=None, top=20, target_names=None,\n                              targets=None, feature_names=None,\n                              coef_scale=None):\n    return explain_weights_lightning_not_supported(estimator)",
    "docstring": "Return an explanation of a lightning estimator weights"
  },
  {
    "code": "def wait_for_thrift_interface(self, **kwargs):\n        if self.cluster.version() >= '4':\n            return;\n        self.watch_log_for(\"Listening for thrift clients...\", **kwargs)\n        thrift_itf = self.network_interfaces['thrift']\n        if not common.check_socket_listening(thrift_itf, timeout=30):\n            warnings.warn(\"Thrift interface {}:{} is not listening after 30 seconds, node may have failed to start.\".format(thrift_itf[0], thrift_itf[1]))",
    "docstring": "Waits for the Thrift interface to be listening.\n\n        Emits a warning if not listening after 30 seconds."
  },
  {
    "code": "def get_encoding(headers, content):\n    encoding = None\n    content_type = headers.get('content-type')\n    if content_type:\n        _, params = cgi.parse_header(content_type)\n        if 'charset' in params:\n            encoding = params['charset'].strip(\"'\\\"\")\n    if not encoding:\n        content = utils.pretty_unicode(content[:1000]) if six.PY3 else content\n        charset_re = re.compile(r'<meta.*?charset=[\"\\']*(.+?)[\"\\'>]',\n                                flags=re.I)\n        pragma_re = re.compile(r'<meta.*?content=[\"\\']*;?charset=(.+?)[\"\\'>]',\n                               flags=re.I)\n        xml_re = re.compile(r'^<\\?xml.*?encoding=[\"\\']*(.+?)[\"\\'>]')\n        encoding = (charset_re.findall(content) +\n                    pragma_re.findall(content) +\n                    xml_re.findall(content))\n        encoding = encoding and encoding[0] or None\n    return encoding",
    "docstring": "Get encoding from request headers or page head."
  },
  {
    "code": "def conv_stride2_multistep(x, nbr_steps, output_filters, name=None, reuse=None):\n  with tf.variable_scope(\n      name, default_name=\"conv_stride2_multistep\", values=[x], reuse=reuse):\n    if nbr_steps == 0:\n      out = conv(x, output_filters, (1, 1))\n      return out, [out]\n    hidden_layers = [x]\n    for i in range(nbr_steps):\n      hidden_layers.append(\n          conv(\n              hidden_layers[-1],\n              output_filters, (2, 2),\n              strides=2,\n              activation=tf.nn.relu,\n              name=\"conv\" + str(i)))\n    return hidden_layers[-1], hidden_layers",
    "docstring": "Use a strided convolution to downsample x by 2, `nbr_steps` times.\n\n  We use stride and filter size 2 to avoid the checkerboard problem of deconvs.\n  As detailed in http://distill.pub/2016/deconv-checkerboard/.\n\n  Args:\n    x: a `Tensor` with shape `[batch, spatial, depth]` or\n     `[batch, spatial_1, spatial_2, depth]`\n    nbr_steps: number of halving downsample rounds to apply\n    output_filters: an int specifying the filter count for the convolutions\n    name: a string\n    reuse: a boolean\n\n  Returns:\n    a `Tensor` with shape `[batch, spatial / (2**nbr_steps), output_filters]` or\n     `[batch, spatial_1 / (2**nbr_steps), spatial_2 / (2**nbr_steps),\n       output_filters]`"
  },
  {
    "code": "def draw_dot(self, pos, color):\n        if 0 <= pos[0] < self.width and 0 <= pos[1] < self.height:\n            self.matrix[pos[0]][pos[1]] = color",
    "docstring": "Draw one single dot with the given color on the screen.\n\n        :param pos: Position of the dot\n        :param color: COlor for the dot\n        :type pos: tuple\n        :type color: tuple"
  },
  {
    "code": "def garbage_graph(index):\n    graph = _compute_garbage_graphs()[int(index)]\n    reduce_graph = bottle.request.GET.get('reduce', '')\n    if reduce_graph:\n        graph = graph.reduce_to_cycles()\n    if not graph:\n        return None\n    filename = 'garbage%so%s.png' % (index, reduce_graph)\n    rendered_file = _get_graph(graph, filename)\n    if rendered_file:\n        bottle.send_file(rendered_file, root=server.tmpdir)\n    else:\n        return None",
    "docstring": "Get graph representation of reference cycle."
  },
  {
    "code": "def _get_parsed_url(url):\n    try:\n        parsed = urllib3_parse(url)\n    except ValueError:\n        scheme, _, url = url.partition(\"://\")\n        auth, _, url = url.rpartition(\"@\")\n        url = \"{scheme}://{url}\".format(scheme=scheme, url=url)\n        parsed = urllib3_parse(url)._replace(auth=auth)\n    return parsed",
    "docstring": "This is a stand-in function for `urllib3.util.parse_url`\n\n    The orignal function doesn't handle special characters very well, this simply splits\n    out the authentication section, creates the parsed url, then puts the authentication\n    section back in, bypassing validation.\n\n    :return: The new, parsed URL object\n    :rtype: :class:`~urllib3.util.url.Url`"
  },
  {
    "code": "def _reversePoints(points):\n    points = _copyPoints(points)\n    firstOnCurve = None\n    for index, point in enumerate(points):\n        if point.segmentType is not None:\n            firstOnCurve = index\n            break\n    lastSegmentType = points[firstOnCurve].segmentType\n    points = reversed(points)\n    final = []\n    for point in points:\n        segmentType = point.segmentType\n        if segmentType is not None:\n            point.segmentType = lastSegmentType\n            lastSegmentType = segmentType\n        final.append(point)\n    _prepPointsForSegments(final)\n    return final",
    "docstring": "Reverse the points. This differs from the\n    reversal point pen in RoboFab in that it doesn't\n    worry about maintaing the start point position.\n    That has no benefit within the context of this module."
  },
  {
    "code": "def login(config, username=None, password=None, email=None, url=None, client=None, *args, **kwargs):\n    try:\n        c = (_get_client(config) if not client else client)\n        lg = c.login(username, password, email, url)\n        print \"%s logged to %s\"%(username,(url if url else \"default hub\"))\n    except Exception as e:\n        utils.error(\"%s can't login to repo %s: %s\"%(username,(url if url else \"default repo\"),e))\n        return False\n    return True",
    "docstring": "Wrapper to the docker.py login method"
  },
  {
    "code": "def profile_form_factory():\n    if current_app.config['USERPROFILES_EMAIL_ENABLED']:\n        return EmailProfileForm(\n            formdata=None,\n            username=current_userprofile.username,\n            full_name=current_userprofile.full_name,\n            email=current_user.email,\n            email_repeat=current_user.email,\n            prefix='profile', )\n    else:\n        return ProfileForm(\n            formdata=None,\n            obj=current_userprofile,\n            prefix='profile', )",
    "docstring": "Create a profile form."
  },
  {
    "code": "def fwriter(filename, gz=False, bz=False):\n    if filename.endswith('.gz'):\n        gz = True\n    elif filename.endswith('.bz2'):\n        bz = True\n    if gz:\n        if not filename.endswith('.gz'):\n            filename += '.gz'\n        return gzip.open(filename, 'wb')\n    elif bz:\n        if not filename.endswith('.bz2'):\n            filename += '.bz2'\n        return bz2.BZ2File(filename, 'w')\n    else:\n        return open(filename, 'w')",
    "docstring": "Returns a filewriter object that can write plain or gzipped output.\n    If gzip or bzip2 compression is asked for then the usual filename extension will be added."
  },
  {
    "code": "def _pop_digits(char_list):\n    logger.debug('_pop_digits(%s)', char_list)\n    digits = []\n    while len(char_list) != 0 and char_list[0].isdigit():\n        digits.append(char_list.pop(0))\n    logger.debug('got digits: %s', digits)\n    logger.debug('updated char list: %s', char_list)\n    return digits",
    "docstring": "Pop consecutive digits from the front of list and return them\n\n    Pops any and all consecutive digits from the start of the provided\n    character list and returns them as a list of string digits.\n    Operates on (and possibly alters) the passed list.\n\n    :param list char_list: a list of characters\n    :return: a list of string digits\n    :rtype: list"
  },
  {
    "code": "def update_edge_todo(self, elev_fn, dem_proc):\n        for key in self.edges[elev_fn].keys():\n            self.edges[elev_fn][key].set_data('todo', data=dem_proc.edge_todo)",
    "docstring": "Can figure out how to update the todo based on the elev filename"
  },
  {
    "code": "def dump(data, out, ac_parser=None, **options):\n    ioi = anyconfig.ioinfo.make(out)\n    psr = find(ioi, forced_type=ac_parser)\n    LOGGER.info(\"Dumping: %s\", ioi.path)\n    psr.dump(data, ioi, **options)",
    "docstring": "Save 'data' to 'out'.\n\n    :param data: A mapping object may have configurations data to dump\n    :param out:\n        An output file path, a file, a file-like object, :class:`pathlib.Path`\n        object represents the file or a namedtuple 'anyconfig.globals.IOInfo'\n        object represents output to dump some data to.\n    :param ac_parser: Forced parser type or parser object\n    :param options:\n        Backend specific optional arguments, e.g. {\"indent\": 2} for JSON\n        loader/dumper backend\n\n    :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError"
  },
  {
    "code": "def initialize_dbs(settings):\n    global _MAIN_SETTINGS, _MAIN_SITEURL, _MAIN_LANG, _SUBSITE_QUEUE\n    _MAIN_SETTINGS = settings\n    _MAIN_LANG = settings['DEFAULT_LANG']\n    _MAIN_SITEURL = settings['SITEURL']\n    _SUBSITE_QUEUE = settings.get('I18N_SUBSITES', {}).copy()\n    prepare_site_db_and_overrides()\n    _SITES_RELPATH_DB.clear()\n    _NATIVE_CONTENT_URL_DB.clear()\n    _GENERATOR_DB.clear()",
    "docstring": "Initialize internal DBs using the Pelican settings dict\n\n    This clears the DBs for e.g. autoreload mode to work"
  },
  {
    "code": "def watched(self, option):\n    params = join_params(self.parameters, {\"watched\": option})\n    return self.__class__(**params)",
    "docstring": "Set whether to filter by a user's watchlist. Options available are\n    user.ONLY, user.NOT, and None; default is None."
  },
  {
    "code": "def _check_r(self, r):\n        if abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \\\n            abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \\\n            abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \\\n            np.dot(r[:, 0], r[:, 1]) > eps or \\\n            np.dot(r[:, 1], r[:, 2]) > eps or \\\n            np.dot(r[:, 2], r[:, 0]) > eps:\n            raise ValueError(\"The rotation matrix is significantly non-orthonormal.\")",
    "docstring": "the columns must orthogonal"
  },
  {
    "code": "def ads_use_dev_spaces(cluster_name, resource_group_name, update=False, space_name=None, do_not_prompt=False):\n    azds_cli = _install_dev_spaces_cli(update)\n    use_command_arguments = [azds_cli, 'use', '--name', cluster_name,\n                             '--resource-group', resource_group_name]\n    if space_name is not None:\n        use_command_arguments.append('--space')\n        use_command_arguments.append(space_name)\n    if do_not_prompt:\n        use_command_arguments.append('-y')\n    subprocess.call(\n        use_command_arguments, universal_newlines=True)",
    "docstring": "Use Azure Dev Spaces with a managed Kubernetes cluster.\n\n    :param cluster_name: Name of the managed cluster.\n    :type cluster_name: String\n    :param resource_group_name: Name of resource group. You can configure the default group. \\\n    Using 'az configure --defaults group=<name>'.\n    :type resource_group_name: String\n    :param update: Update to the latest Azure Dev Spaces client components.\n    :type update: bool\n    :param space_name: Name of the new or existing dev space to select. Defaults to an interactive selection experience.\n    :type space_name: String\n    :param do_not_prompt: Do not prompt for confirmation. Requires --space.\n    :type do_not_prompt: bool"
  },
  {
    "code": "def _populate_audio_file(self):\n        self.log(u\"Populate audio file...\")\n        if self.audio_file_path_absolute is not None:\n            self.log([u\"audio_file_path_absolute is '%s'\", self.audio_file_path_absolute])\n            self.audio_file = AudioFile(\n                file_path=self.audio_file_path_absolute,\n                logger=self.logger\n            )\n            self.audio_file.read_properties()\n        else:\n            self.log(u\"audio_file_path_absolute is None\")\n        self.log(u\"Populate audio file... done\")",
    "docstring": "Create the ``self.audio_file`` object by reading\n        the audio file at ``self.audio_file_path_absolute``."
  },
  {
    "code": "def skip(self):\n        buflen = len(self.buf)\n        while True:\n            self.buf = self.buf.lstrip()\n            if self.buf == '':\n                self.readline()\n                buflen = len(self.buf)\n            else:\n                self.offset += (buflen - len(self.buf))\n                break\n        if not self.keep_comments:\n            if self.buf[0] == '/':\n                if self.buf[1] == '/':\n                    self.readline()\n                    return self.skip()\n                elif self.buf[1] == '*':\n                    i = self.buf.find('*/')\n                    while i == -1:\n                        self.readline()\n                        i = self.buf.find('*/')\n                    self.set_buf(i+2)\n                    return self.skip()",
    "docstring": "Skip whitespace and count position"
  },
  {
    "code": "def mean_squared_error(data, ground_truth, mask=None,\n                       normalized=False, force_lower_is_better=True):\n    r\n    if not hasattr(data, 'space'):\n        data = odl.vector(data)\n    space = data.space\n    ground_truth = space.element(ground_truth)\n    l2norm = odl.solvers.L2Norm(space)\n    if mask is not None:\n        data = data * mask\n        ground_truth = ground_truth * mask\n    diff = data - ground_truth\n    fom = l2norm(diff) ** 2\n    if normalized:\n        fom /= (l2norm(data) + l2norm(ground_truth)) ** 2\n    else:\n        fom /= l2norm(space.one()) ** 2\n    return fom",
    "docstring": "r\"\"\"Return mean squared L2 distance between ``data`` and ``ground_truth``.\n\n    See also `this Wikipedia article\n    <https://en.wikipedia.org/wiki/Mean_squared_error>`_.\n\n    Parameters\n    ----------\n    data : `Tensor` or `array-like`\n        Input data to compare to the ground truth. If not a `Tensor`, an\n        unweighted tensor space will be assumed.\n    ground_truth : `array-like`\n        Reference to which ``data`` should be compared.\n    mask : `array-like`, optional\n        If given, ``data * mask`` is compared to ``ground_truth * mask``.\n    normalized  : bool, optional\n        If ``True``, the output values are mapped to the interval\n        :math:`[0, 1]` (see `Notes` for details).\n    force_lower_is_better : bool, optional\n        If ``True``, it is ensured that lower values correspond to better\n        matches. For the mean squared error, this is already the case, and\n        the flag is only present for compatibility to other figures of merit.\n\n    Returns\n    -------\n    mse : float\n        FOM value, where a lower value means a better match.\n\n    Notes\n    -----\n    The FOM evaluates\n\n    .. math::\n        \\mathrm{MSE}(f, g) = \\frac{\\| f - g \\|_2^2}{\\| 1 \\|_2^2},\n\n    where :math:`\\| 1 \\|^2_2` is the volume of the domain of definition\n    of the functions. For :math:`\\mathbb{R}^n` type spaces, this is equal\n    to the number of elements :math:`n`.\n\n    The normalized form is\n\n    .. math::\n        \\mathrm{MSE_N} = \\frac{\\| f - g \\|_2^2}{(\\| f \\|_2 + \\| g \\|_2)^2}.\n\n    The normalized variant takes values in :math:`[0, 1]`."
  },
  {
    "code": "def summary(self, title=None, complexity=False):\n        if title is None:\n            return javabridge.call(\n                self.jobject, \"toSummaryString\", \"()Ljava/lang/String;\")\n        else:\n            return javabridge.call(\n                self.jobject, \"toSummaryString\", \"(Ljava/lang/String;Z)Ljava/lang/String;\", title, complexity)",
    "docstring": "Generates a summary.\n\n        :param title: optional title\n        :type title: str\n        :param complexity: whether to print the complexity information as well\n        :type complexity: bool\n        :return: the summary\n        :rtype: str"
  },
  {
    "code": "def find_course_by_crn(self, crn):\n        for name, course in self.courses.iteritems():\n            if crn in course:\n                return course\n        return None",
    "docstring": "Searches all courses by CRNs. Not particularly efficient.\n        Returns None if not found."
  },
  {
    "code": "def normalizer(text, exclusion=OPERATIONS_EXCLUSION, lower=True, separate_char='-', **kwargs):\n    clean_str = re.sub(r'[^\\w{}]'.format(\n        \"\".join(exclusion)), separate_char, text.strip()) or ''\n    clean_lowerbar = clean_str_without_accents = strip_accents(clean_str)\n    if '_' not in exclusion:\n        clean_lowerbar = re.sub(r'\\_', separate_char, clean_str_without_accents.strip())\n    limit_guion = re.sub(r'\\-+', separate_char, clean_lowerbar.strip())\n    if limit_guion and separate_char and separate_char in limit_guion[0]:\n        limit_guion = limit_guion[1:]\n    if limit_guion and separate_char and separate_char in limit_guion[-1]:\n        limit_guion = limit_guion[:-1]\n    if lower:\n        limit_guion = limit_guion.lower()\n    return limit_guion",
    "docstring": "Clean text string of simbols only alphanumeric chars."
  },
  {
    "code": "def reroot(self, s):\n        o_s1 = self.first_lookup[s]\n        splice1 = self.tour[1:o_s1]\n        rest = self.tour[o_s1 + 1:]\n        new_tour = [s] + rest + splice1 + [s]\n        new_tree = TestETT.from_tour(new_tour, fast=self.fast)\n        return new_tree",
    "docstring": "s = 3\n        s = 'B'\n\n        Let os denote any occurrence of s.\n        Splice out the first part of the sequence ending with the occurrence before os,\n        remove its first occurrence (or),\n        and tack this on to the end of the sequence which now begins with os.\n        Add a new occurrence os to the end."
  },
  {
    "code": "def _query(self, *criterion):\n        return self.session.query(\n            self.model_class\n        ).filter(\n            *criterion\n        )",
    "docstring": "Construct a query for the model."
  },
  {
    "code": "def mount_rate_limit_adapters(cls, session=None,\n                                  rls_config=None, **kwargs):\n        session = session or HTTP_SESSION\n        if rls_config is None:\n            rls_config = RateLimiter.get_configs()\n        for name, rl_conf in rls_config.items():\n            urls = rl_conf.get('urls', [])\n            if not urls:\n                continue\n            rl_adapter = RLRequestAdapter(name, config=rls_config, **kwargs)\n            for url in urls:\n                session.mount(url, rl_adapter)",
    "docstring": "Mount rate-limits adapters on the specified `requests.Session`\n        object.\n\n        :param py:class:`requests.Session` session:\n          Session to mount. If not specified, then use the global\n          `HTTP_SESSION`.\n\n        :param dict rls_config:\n          Rate-limits configuration. If not specified, then\n          use the one defined at application level.\n\n        :param kwargs:\n          Additional keywords argument given to\n          py:class:`docido_sdk.toolbox.rate_limits.RLRequestAdapter`\n          constructor."
  },
  {
    "code": "def C_array2dict(C):\n    d = OrderedDict()\n    i=0\n    for k in C_keys:\n        s = C_keys_shape[k]\n        if s == 1:\n            j = i+1\n            d[k] = C[i]\n        else:\n            j = i \\\n      + reduce(operator.mul, s, 1)\n            d[k] = C[i:j].reshape(s)\n        i = j\n    return d",
    "docstring": "Convert a 1D array containing C values to a dictionary."
  },
  {
    "code": "def read(self):\n        def ds(data_element):\n            value = self._str_filter.ToStringPair(data_element.GetTag())\n            if value[1]:\n                return DataElement(data_element, value[0].strip(), value[1].strip())\n        results = [data for data in self.walk(ds) if data is not None]\n        return results",
    "docstring": "Returns array of dictionaries containing all the data elements in\n        the DICOM file."
  },
  {
    "code": "def _recursive_gh_get(href, items):\n    response = _request('GET', href)\n    response.raise_for_status()\n    items.extend(response.json())\n    if \"link\" not in response.headers:\n        return\n    links = link_header.parse(response.headers[\"link\"])\n    rels = {link.rel: link.href for link in links.links}\n    if \"next\" in rels:\n        _recursive_gh_get(rels[\"next\"], items)",
    "docstring": "Recursively get list of GitHub objects.\n\n    See https://developer.github.com/v3/guides/traversing-with-pagination/"
  },
  {
    "code": "def generateSensorimotorSequence(self, sequenceLength):\n    motorSequence = []\n    sensorySequence = []\n    sensorimotorSequence = []\n    currentEyeLoc = self.nupicRandomChoice(self.spatialConfig)\n    for i in xrange(sequenceLength):\n      currentSensoryInput = self.spatialMap[tuple(currentEyeLoc)]\n      nextEyeLoc, currentEyeV = self.getNextEyeLocation(currentEyeLoc)\n      if self.verbosity:\n          print \"sensory input = \", currentSensoryInput, \\\n            \"eye location = \", currentEyeLoc, \\\n            \" motor command = \", currentEyeV\n      sensoryInput = self.encodeSensoryInput(currentSensoryInput)\n      motorInput = self.encodeMotorInput(list(currentEyeV))\n      sensorimotorInput = numpy.concatenate((sensoryInput, motorInput))\n      sensorySequence.append(sensoryInput)\n      motorSequence.append(motorInput)\n      sensorimotorSequence.append(sensorimotorInput)\n      currentEyeLoc = nextEyeLoc\n    return (sensorySequence, motorSequence, sensorimotorSequence)",
    "docstring": "Generate sensorimotor sequences of length sequenceLength.\n\n    @param sequenceLength (int)\n        Length of the sensorimotor sequence.\n\n    @return (tuple) Contains:\n            sensorySequence       (list)\n                Encoded sensory input for whole sequence.\n\n            motorSequence         (list)\n                Encoded motor input for whole sequence.\n\n            sensorimotorSequence  (list)\n                Encoder sensorimotor input for whole sequence. This is useful\n                when you want to give external input to temporal memory."
  },
  {
    "code": "def to_pandas(self):\n        agedepthdf = pd.DataFrame(self.age, index=self.data.depth)\n        agedepthdf.columns = list(range(self.n_members()))\n        out = (agedepthdf.join(self.data.set_index('depth'))\n               .reset_index()\n               .melt(id_vars=self.data.columns.values, var_name='mciter', value_name='age'))\n        out['mciter'] = pd.to_numeric(out.loc[:, 'mciter'])\n        if self.n_members() == 1:\n            out = out.drop('mciter', axis=1)\n        return out",
    "docstring": "Convert record to pandas.DataFrame"
  },
  {
    "code": "def _get_entity(service_instance, entity):\n    log.trace('Retrieving entity: %s', entity)\n    if entity['type'] == 'cluster':\n        dc_ref = salt.utils.vmware.get_datacenter(service_instance,\n                                                  entity['datacenter'])\n        return salt.utils.vmware.get_cluster(dc_ref, entity['cluster'])\n    elif entity['type'] == 'vcenter':\n        return None\n    raise ArgumentValueError('Unsupported entity type \\'{0}\\''\n                             ''.format(entity['type']))",
    "docstring": "Returns the entity associated with the entity dict representation\n\n    Supported entities: cluster, vcenter\n\n    Expected entity format:\n\n    .. code-block:: python\n\n        cluster:\n            {'type': 'cluster',\n             'datacenter': <datacenter_name>,\n             'cluster': <cluster_name>}\n        vcenter:\n            {'type': 'vcenter'}\n\n    service_instance\n        Service instance (vim.ServiceInstance) of the vCenter.\n\n    entity\n        Entity dict in the format above"
  },
  {
    "code": "def send(self, channel, payload):\n        with track('send_channel=' + channel):\n            with track('create event'):\n                Event.objects.create(\n                    group=self,\n                    channel=channel,\n                    value=payload)\n            ChannelGroup(str(self.pk)).send(\n                    {'text': json.dumps({\n                        'channel': channel,\n                        'payload': payload\n                    })})",
    "docstring": "Send a message with the given payload on the given channel.\n        Messages are broadcast to all players in the group."
  },
  {
    "code": "def check() -> Result:\n        try:\n            with Connection(conf.get('CELERY_BROKER_URL')) as conn:\n                conn.connect()\n        except ConnectionRefusedError:\n            return Result(message='Service unable to connect, \"Connection was refused\".',\n                          severity=Result.ERROR)\n        except AccessRefused:\n            return Result(message='Service unable to connect, \"Authentication error\".',\n                          severity=Result.ERROR)\n        except IOError:\n            return Result(message='Service has an \"IOError\".', severity=Result.ERROR)\n        except Exception as e:\n            return Result(message='Service has an \"{}\" error.'.format(e), severity=Result.ERROR)\n        else:\n            return Result()",
    "docstring": "Open and close the broker channel."
  },
  {
    "code": "def collapse_nested(self, cats, max_nestedness=10):\n        children = []\n        removed = set()\n        nestedness = max_nestedness\n        old = list(self.widget.options.values())\n        nested = [cat for cat in old if getattr(cat, 'cat') is not None]\n        parents = {cat.cat for cat in nested}\n        parents_to_remove = cats\n        while len(parents_to_remove) > 0 and nestedness > 0:\n            for cat in nested:\n                if cat.cat in parents_to_remove:\n                    children.append(cat)\n            removed = removed.union(parents_to_remove)\n            nested = [cat for cat in nested if cat not in children]\n            parents_to_remove = {c for c in children if c in parents - removed}\n            nestedness -= 1\n        self.remove(children)",
    "docstring": "Collapse any items that are nested under cats.\n        `max_nestedness` acts as a fail-safe to prevent infinite looping."
  },
  {
    "code": "def accept_freeware_license():\n    ntab = 3 if version().startswith('6.6.') else 2\n    for _ in range(ntab):\n        EasyProcess('xdotool key KP_Tab').call()\n        time.sleep(0.5)\n    EasyProcess('xdotool key KP_Space').call()\n    time.sleep(0.5)\n    EasyProcess('xdotool key KP_Space').call()",
    "docstring": "different Eagle versions need differnt TAB count.\n    6.5  -> 2\n    6.6  -> 3\n    7.4  -> 2"
  },
  {
    "code": "async def is_ready(self):\n        async def slave_task(addr, timeout):\n            try:\n                r_manager = await self.env.connect(addr, timeout=timeout)\n                ready = await r_manager.is_ready()\n                if not ready:\n                    return False\n            except:\n                return False\n            return True\n        if not self.env.is_ready():\n            return False\n        if not self.check_ready():\n            return False\n        rets = await create_tasks(slave_task, self.addrs, 0.5)\n        if not all(rets):\n            return False\n        return True",
    "docstring": "Check if the multi-environment has been fully initialized.\n\n        This calls each slave environment managers' :py:meth:`is_ready` and\n        checks if the multi-environment itself is ready by calling\n        :py:meth:`~creamas.mp.MultiEnvironment.check_ready`.\n\n        .. seealso::\n\n            :py:meth:`creamas.core.environment.Environment.is_ready`"
  },
  {
    "code": "def live_dirs(self):\n    if self.has_results_dir:\n      yield self.results_dir\n      yield self.current_results_dir\n      if self.has_previous_results_dir:\n        yield self.previous_results_dir",
    "docstring": "Yields directories that must exist for this VersionedTarget to function."
  },
  {
    "code": "def query_foursquare(point, max_distance, client_id, client_secret):\n    if not client_id:\n        return []\n    if not client_secret:\n        return []\n    if from_cache(FS_CACHE, point, max_distance):\n        return from_cache(FS_CACHE, point, max_distance)\n    url = FOURSQUARE_URL % (client_id, client_secret, point.lat, point.lon, max_distance)\n    req = requests.get(url)\n    if req.status_code != 200:\n        return []\n    response = req.json()\n    result = []\n    venues = response['response']['venues']\n    for venue in venues:\n        name = venue['name']\n        distance = venue['location']['distance']\n        categories = [c['shortName'] for c in venue['categories']]\n        result.append({\n            'label': name,\n            'distance': distance,\n            'types': categories,\n            'suggestion_type': 'FOURSQUARE'\n        })\n    foursquare_insert_cache(point, result)\n    return result",
    "docstring": "Queries Squarespace API for a location\n\n    Args:\n        point (:obj:`Point`): Point location to query\n        max_distance (float): Search radius, in meters\n        client_id (str): Valid Foursquare client id\n        client_secret (str): Valid Foursquare client secret\n    Returns:\n        :obj:`list` of :obj:`dict`: List of locations with the following format:\n            {\n                'label': 'Coffee house',\n                'distance': 19,\n                'types': 'Commerce',\n                'suggestion_type': 'FOURSQUARE'\n            }"
  },
  {
    "code": "def wcwidth(wc):\n    r\n    ucs = ord(wc)\n    if (ucs == 0 or\n            ucs == 0x034F or\n            0x200B <= ucs <= 0x200F or\n            ucs == 0x2028 or\n            ucs == 0x2029 or\n            0x202A <= ucs <= 0x202E or\n            0x2060 <= ucs <= 0x2063):\n        return 0\n    if ucs < 32 or 0x07F <= ucs < 0x0A0:\n        return -1\n    if _bisearch(ucs, ZERO_WIDTH):\n        return 0\n    return 1 + _bisearch(ucs, WIDE_EASTASIAN)",
    "docstring": "r\"\"\"\n    Given one unicode character, return its printable length on a terminal.\n\n    The wcwidth() function returns 0 if the wc argument has no printable effect\n    on a terminal (such as NUL '\\0'), -1 if wc is not printable, or has an\n    indeterminate effect on the terminal, such as a control character.\n    Otherwise, the number of column positions the character occupies on a\n    graphic terminal (1 or 2) is returned.\n\n    The following have a column width of -1:\n\n        - C0 control characters (U+001 through U+01F).\n\n        - C1 control characters and DEL (U+07F through U+0A0).\n\n    The following have a column width of 0:\n\n        - Non-spacing and enclosing combining characters (general\n          category code Mn or Me in the Unicode database).\n\n        - NULL (U+0000, 0).\n\n        - COMBINING GRAPHEME JOINER (U+034F).\n\n        - ZERO WIDTH SPACE (U+200B) through\n          RIGHT-TO-LEFT MARK (U+200F).\n\n        - LINE SEPERATOR (U+2028) and\n          PARAGRAPH SEPERATOR (U+2029).\n\n        - LEFT-TO-RIGHT EMBEDDING (U+202A) through\n          RIGHT-TO-LEFT OVERRIDE (U+202E).\n\n        - WORD JOINER (U+2060) through\n          INVISIBLE SEPARATOR (U+2063).\n\n    The following have a column width of 1:\n\n        - SOFT HYPHEN (U+00AD) has a column width of 1.\n\n        - All remaining characters (including all printable\n          ISO 8859-1 and WGL4 characters, Unicode control characters,\n          etc.) have a column width of 1.\n\n    The following have a column width of 2:\n\n        - Spacing characters in the East Asian Wide (W) or East Asian\n          Full-width (F) category as defined in Unicode Technical\n          Report #11 have a column width of 2."
  },
  {
    "code": "def _get_repo_info(alias, repos_cfg=None, root=None):\n    try:\n        meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))\n        meta['alias'] = alias\n        for key, val in six.iteritems(meta):\n            if val in ['0', '1']:\n                meta[key] = int(meta[key]) == 1\n            elif val == 'NONE':\n                meta[key] = None\n        return meta\n    except (ValueError, configparser.NoSectionError):\n        return {}",
    "docstring": "Get one repo meta-data."
  },
  {
    "code": "def multitaper_cross_spectrum(self, clm, slm, k, convention='power',\n                                  unit='per_l', **kwargs):\n        return self._multitaper_cross_spectrum(clm, slm, k,\n                                               convention=convention,\n                                               unit=unit, **kwargs)",
    "docstring": "Return the multitaper cross-spectrum estimate and standard error.\n\n        Usage\n        -----\n        mtse, sd = x.multitaper_cross_spectrum(clm, slm, k, [convention, unit,\n                                                             lmax, taper_wt,\n                                                             clat, clon,\n                                                             coord_degrees])\n\n        Returns\n        -------\n        mtse : ndarray, shape (lmax-lwin+1)\n            The localized multitaper cross-spectrum estimate, where lmax is the\n            smaller of the two spherical-harmonic bandwidths of clm and slm,\n            and lwin is the spherical-harmonic bandwidth of the localization\n            windows.\n        sd : ndarray, shape (lmax-lwin+1)\n            The standard error of the localized multitaper cross-spectrum\n            estimate.\n\n        Parameters\n        ----------\n        clm : SHCoeffs class instance\n            SHCoeffs class instance containing the spherical harmonic\n            coefficients of the first global field to analyze.\n        slm : SHCoeffs class instance\n            SHCoeffs class instance containing the spherical harmonic\n            coefficients of the second global field to analyze.\n        k : int\n            The number of tapers to be utilized in performing the multitaper\n            spectral analysis.\n        convention : str, optional, default = 'power'\n            The type of output spectra: 'power' for power spectra, and\n            'energy' for energy spectra.\n        unit : str, optional, default = 'per_l'\n            The units of the output spectra. If 'per_l', the spectra contain\n            the total contribution for each spherical harmonic degree l. If\n            'per_lm', the spectra contain the average contribution for each\n            coefficient at spherical harmonic degree l.\n        lmax : int, optional, default = min(clm.lmax, slm.lmax)\n            The maximum spherical-harmonic degree of the input coefficients\n            to use.\n        taper_wt : ndarray, optional, default = None\n            The weights used in calculating the multitaper cross-spectral\n            estimates and standard error.\n        clat, clon : float, optional, default = 90., 0.\n            Latitude and longitude of the center of the spherical-cap\n            localization windows.\n        coord_degrees : bool, optional, default = True\n            True if clat and clon are in degrees."
  },
  {
    "code": "def exp_backoff(attempt, cap=3600, base=300):\n    max_attempts = math.log(cap / base, 2)\n    if attempt <= max_attempts:\n        return base * 2 ** attempt\n    return cap",
    "docstring": "Exponential backoff time"
  },
  {
    "code": "def create_boots_layer(aspect, ip):\n    layer = []\n    if 'BOOTS' in aspect:\n        layer = pgnreader.parse_pagan_file(FILE_BOOTS, ip, invert=False, sym=True)\n    return layer",
    "docstring": "Reads the BOOTS.pgn file and creates\n    the boots layer."
  },
  {
    "code": "def make_instance(cls, id, client, parent_id=None, json=None):\n        make_cls = CLASS_MAP.get(id)\n        if make_cls is None:\n            return None\n        real_json = json['data']\n        real_id = real_json['id']\n        return Base.make(real_id, client, make_cls, parent_id=None, json=real_json)",
    "docstring": "Overrides Base's ``make_instance`` to allow dynamic creation of objects\n        based on the defined type in the response json.\n\n        :param cls: The class this was called on\n        :param id: The id of the instance to create\n        :param client: The client to use for this instance\n        :param parent_id: The parent id for derived classes\n        :param json: The JSON to populate the instance with\n\n        :returns: A new instance of this type, populated with json"
  },
  {
    "code": "def _parse_cod_segment(cls, fptr):\n        offset = fptr.tell() - 2\n        read_buffer = fptr.read(2)\n        length, = struct.unpack('>H', read_buffer)\n        read_buffer = fptr.read(length - 2)\n        lst = struct.unpack_from('>BBHBBBBBB', read_buffer, offset=0)\n        scod, prog, nlayers, mct, nr, xcb, ycb, cstyle, xform = lst\n        if len(read_buffer) > 10:\n            precinct_size = _parse_precinct_size(read_buffer[10:])\n        else:\n            precinct_size = None\n        sop = (scod & 2) > 0\n        eph = (scod & 4) > 0\n        if sop or eph:\n            cls._parse_tpart_flag = True\n        else:\n            cls._parse_tpart_flag = False\n        pargs = (scod, prog, nlayers, mct, nr, xcb, ycb, cstyle, xform,\n                 precinct_size)\n        return CODsegment(*pargs, length=length, offset=offset)",
    "docstring": "Parse the COD segment.\n\n        Parameters\n        ----------\n        fptr : file\n            Open file object.\n\n        Returns\n        -------\n        CODSegment\n            The current COD segment."
  },
  {
    "code": "def _get_auth(self, force_console=False):\n        if not self.target:\n            raise ValueError(\"Unspecified target ({!r})\".format(self.target))\n        elif not force_console and self.URL_RE.match(self.target):\n            auth_url = urlparse(self.target)\n            source = 'url'\n            if auth_url.username:\n                self.user = auth_url.username\n            if auth_url.password:\n                self.password = auth_url.password\n            if not self.auth_valid():\n                source = self._get_auth_from_keyring()\n            if not self.auth_valid():\n                source = self._get_auth_from_netrc(auth_url.hostname)\n            if not self.auth_valid():\n                source = self._get_auth_from_console(self.target)\n        else:\n            source = self._get_auth_from_console(self.target)\n        if self.auth_valid():\n            self.source = source",
    "docstring": "Try to get login auth from known sources."
  },
  {
    "code": "def add_chunk(self, chunk_obj):\n        if chunk_obj.get_id() in self.idx:\n            raise ValueError(\"Chunk with id {} already exists!\"\n                             .format(chunk_obj.get_id()))\n        self.node.append(chunk_obj.get_node())\n        self.idx[chunk_obj.get_id()] = chunk_obj",
    "docstring": "Adds a chunk object to the layer\n        @type chunk_obj: L{Cchunk}\n        @param chunk_obj: the chunk object"
  },
  {
    "code": "def get_model_choices():\n    result = []\n    for ct in ContentType.objects.order_by('app_label', 'model'):\n        try:\n            if issubclass(ct.model_class(), TranslatableModel):\n                result.append(\n                    ('{} - {}'.format(ct.app_label, ct.model.lower()),\n                     '{} - {}'.format(ct.app_label.capitalize(), ct.model_class()._meta.verbose_name_plural))\n                )\n        except TypeError:\n            continue\n    return result",
    "docstring": "Get the select options for the model selector\n\n    :return:"
  },
  {
    "code": "def remove_datastore(datastore, service_instance=None):\n    log.trace('Removing datastore \\'%s\\'', datastore)\n    target = _get_proxy_target(service_instance)\n    datastores = salt.utils.vmware.get_datastores(\n        service_instance,\n        reference=target,\n        datastore_names=[datastore])\n    if not datastores:\n        raise VMwareObjectRetrievalError(\n            'Datastore \\'{0}\\' was not found'.format(datastore))\n    if len(datastores) > 1:\n        raise VMwareObjectRetrievalError(\n            'Multiple datastores \\'{0}\\' were found'.format(datastore))\n    salt.utils.vmware.remove_datastore(service_instance, datastores[0])\n    return True",
    "docstring": "Removes a datastore. If multiple datastores an error is raised.\n\n    datastore\n        Datastore name\n\n    service_instance\n        Service instance (vim.ServiceInstance) of the vCenter/ESXi host.\n        Default is None.\n\n    .. code-block:: bash\n\n        salt '*' vsphere.remove_datastore ds_name"
  },
  {
    "code": "def get_stoplist(language):\n    file_path = os.path.join(\"stoplists\", \"%s.txt\" % language)\n    try:\n        stopwords = pkgutil.get_data(\"justext\", file_path)\n    except IOError:\n        raise ValueError(\n            \"Stoplist for language '%s' is missing. \"\n            \"Please use function 'get_stoplists' for complete list of stoplists \"\n            \"and feel free to contribute by your own stoplist.\" % language\n        )\n    return frozenset(w.decode(\"utf8\").lower() for w in stopwords.splitlines())",
    "docstring": "Returns an built-in stop-list for the language as a set of words."
  },
  {
    "code": "def _create_stdout_logger(logging_level):\n    out_hdlr = logging.StreamHandler(sys.stdout)\n    out_hdlr.setFormatter(logging.Formatter(\n        '[%(asctime)s] %(message)s', \"%H:%M:%S\"\n    ))\n    out_hdlr.setLevel(logging_level)\n    for name in LOGGING_NAMES:\n        log = logging.getLogger(name)\n        log.addHandler(out_hdlr)\n        log.setLevel(logging_level)",
    "docstring": "create a logger to stdout. This creates logger for a series\n    of module we would like to log information on."
  },
  {
    "code": "def get_last_doc(self):\n        def docs_by_ts():\n            for meta_collection_name in self._meta_collections():\n                meta_coll = self.meta_database[meta_collection_name]\n                for ts_ns_doc in meta_coll.find(limit=-1).sort(\"_ts\", -1):\n                    yield ts_ns_doc\n        return max(docs_by_ts(), key=lambda x: x[\"_ts\"])",
    "docstring": "Returns the last document stored in Mongo."
  },
  {
    "code": "def on_service_add(self, service):\n        self.launch_thread(service.name, self.check_loop, service)",
    "docstring": "When a new service is added, a worker thread is launched to\n        periodically run the checks for that service."
  },
  {
    "code": "def make_server(\n        server_class, handler_class, authorizer_class, filesystem_class,\n        host_port, file_access_user=None, **handler_options):\n    from . import compat\n    if isinstance(handler_class, compat.string_type):\n        handler_class = import_class(handler_class)\n    if isinstance(authorizer_class, compat.string_type):\n        authorizer_class = import_class(authorizer_class)\n    if isinstance(filesystem_class, compat.string_type):\n        filesystem_class = import_class(filesystem_class)\n    authorizer = authorizer_class(file_access_user)\n    handler = handler_class\n    for key, value in handler_options.items():\n        setattr(handler, key, value)\n    handler.authorizer = authorizer\n    if filesystem_class is not None:\n        handler.abstracted_fs = filesystem_class\n    return server_class(host_port, handler)",
    "docstring": "make server instance\n\n    :host_port: (host, port)\n    :file_access_user: 'spam'\n\n    handler_options:\n\n      * timeout\n      * passive_ports\n      * masquerade_address\n      * certfile\n      * keyfile"
  },
  {
    "code": "def get_playlist_songs(self, playlist_id, limit=1000):\n        url = 'http://music.163.com/weapi/v3/playlist/detail?csrf_token='\n        csrf = ''\n        params = {'id': playlist_id, 'offset': 0, 'total': True,\n                  'limit': limit, 'n': 1000, 'csrf_token': csrf}\n        result = self.post_request(url, params)\n        songs = result['playlist']['tracks']\n        songs = [Song(song['id'], song['name']) for song in songs]\n        return songs",
    "docstring": "Get a playlists's all songs.\n\n        :params playlist_id: playlist id.\n        :params limit: length of result returned by weapi.\n        :return: a list of Song object."
  },
  {
    "code": "def check_or(state, *tests):\n    success = False\n    first_feedback = None\n    for test in iter_tests(tests):\n        try:\n            multi(state, test)\n            success = True\n        except TestFail as e:\n            if not first_feedback:\n                first_feedback = e.feedback\n        if success:\n            return state\n    state.report(first_feedback)",
    "docstring": "Test whether at least one SCT passes.\n\n    If all of the tests fail, the feedback of the first test will be presented to the student.\n\n    Args:\n        state: State instance describing student and solution code, can be omitted if used with Ex()\n        tests: one or more sub-SCTs to run\n\n    :Example:\n        The SCT below tests that the student typed either 'SELECT' or 'WHERE' (or both).. ::\n\n            Ex().check_or(\n                has_code('SELECT'),\n                has_code('WHERE')\n            )\n\n        The SCT below checks that a SELECT statement has at least a WHERE c or LIMIT clause.. ::\n\n            Ex().check_node('SelectStmt', 0).check_or(\n                check_edge('where_clause'),\n                check_edge('limit_clause')\n            )"
  },
  {
    "code": "def publish(idx=None):\n    if idx is None:\n        idx = ''\n    else:\n        idx = '-r ' + idx\n    run('python setup.py register {}'.format(idx))\n    run('twine upload {} dist/*.whl dist/*.egg dist/*.tar.gz'.format(idx))",
    "docstring": "Publish packaged distributions to pypi index"
  },
  {
    "code": "def is_on_curve(self, point):\n        X, Y = point.X, point.Y\n        return (\n                pow(Y, 2, self.P) - pow(X, 3, self.P) - self.a * X - self.b\n            ) % self.P == 0",
    "docstring": "Checks whether a point is on the curve.\n\n        Args:\n            point (AffinePoint): Point to be checked.\n\n        Returns:\n            bool: True if point is on the curve, False otherwise."
  },
  {
    "code": "def picard_fixmate(picard, align_bam):\n    base, ext = os.path.splitext(align_bam)\n    out_file = \"%s-sort%s\" % (base, ext)\n    if not file_exists(out_file):\n        with tx_tmpdir(picard._config) as tmp_dir:\n            with file_transaction(picard._config, out_file) as tx_out_file:\n                opts = [(\"INPUT\", align_bam),\n                        (\"OUTPUT\", tx_out_file),\n                        (\"TMP_DIR\", tmp_dir),\n                        (\"SORT_ORDER\", \"coordinate\")]\n                picard.run(\"FixMateInformation\", opts)\n    return out_file",
    "docstring": "Run Picard's FixMateInformation generating an aligned output file."
  },
  {
    "code": "def parse(self):\n        self.cmd = None\n        self.comments = []\n        self.entrypoint = None\n        self.environ = []\n        self.files = []\n        self.install = []\n        self.labels = []\n        self.ports = []\n        self.test = None\n        self.volumes = []\n        if self.recipe:\n            self.lines = read_file(self.recipe)\n            if hasattr(self, '_parse'):\n                self._parse()",
    "docstring": "parse is the base function for parsing the recipe, whether it be\n           a Dockerfile or Singularity recipe. The recipe is read in as lines,\n           and saved to a list if needed for the future. If the client has\n           it, the recipe type specific _parse function is called.\n\n           Instructions for making a client subparser:\n\n               It should have a main function _parse that parses a list of lines\n               from some recipe text file into the appropriate sections, e.g.,\n               \n               self.fromHeader\n               self.environ\n               self.labels\n               self.install\n               self.files\n               self.test\n               self.entrypoint"
  },
  {
    "code": "def install(module):\n    ret = {\n        'old': None,\n        'new': None,\n    }\n    old_info = show(module)\n    cmd = 'cpan -i {0}'.format(module)\n    out = __salt__['cmd.run'](cmd)\n    if \"don't know what it is\" in out:\n        ret['error'] = 'CPAN cannot identify this package'\n        return ret\n    new_info = show(module)\n    ret['old'] = old_info.get('installed version', None)\n    ret['new'] = new_info['installed version']\n    return ret",
    "docstring": "Install a Perl module from CPAN\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' cpan.install Template::Alloy"
  },
  {
    "code": "def persistant_error(request, message, extra_tags='', fail_silently=False, *args, **kwargs):\n    add_message(request, ERROR_PERSISTENT, message, extra_tags=extra_tags,\n                fail_silently=fail_silently, *args, **kwargs)",
    "docstring": "Adds a persistant message with the ``ERROR`` level."
  },
  {
    "code": "def get_port_binding_level(filters):\n    session = db.get_reader_session()\n    with session.begin():\n        return (session.query(ml2_models.PortBindingLevel).\n                filter_by(**filters).\n                order_by(ml2_models.PortBindingLevel.level).\n                all())",
    "docstring": "Returns entries from PortBindingLevel based on the specified filters."
  },
  {
    "code": "def list(self):\n    import IPython\n    data = [{'name': version['name'].split()[-1],\n             'deploymentUri': version['deploymentUri'], 'createTime': version['createTime']}\n            for version in self.get_iterator()]\n    IPython.display.display(\n        datalab.utils.commands.render_dictionary(data, ['name', 'deploymentUri', 'createTime']))",
    "docstring": "List versions under the current model in a table view.\n\n    Raises:\n      Exception if it is called in a non-IPython environment."
  },
  {
    "code": "def wgs84_to_pixel(lng, lat, transform, utm_epsg=None, truncate=True):\n    east, north = wgs84_to_utm(lng, lat, utm_epsg)\n    row, column = utm_to_pixel(east, north, transform, truncate=truncate)\n    return row, column",
    "docstring": "Convert WGS84 coordinates to pixel image coordinates given transform and UTM CRS. If no CRS is given it will be\n    calculated it automatically.\n\n    :param lng: longitude of point\n    :type lng: float\n    :param lat: latitude of point\n    :type lat: float\n    :param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`\n    :type transform: tuple or list\n    :param utm_epsg: UTM coordinate reference system enum constants\n    :type utm_epsg: constants.CRS or None\n    :param truncate: Whether to truncate pixel coordinates. Default is ``True``\n    :type truncate: bool\n    :return: row and column pixel image coordinates\n    :rtype: float, float or int, int"
  },
  {
    "code": "def _get_broadcast_shape(shape1, shape2):\n    if shape1 == shape2:\n        return shape1\n    length1 = len(shape1)\n    length2 = len(shape2)\n    if length1 > length2:\n        shape = list(shape1)\n    else:\n        shape = list(shape2)\n    i = max(length1, length2) - 1\n    for a, b in zip(shape1[::-1], shape2[::-1]):\n        if a != 1 and b != 1 and a != b:\n            raise ValueError('shape1=%s is not broadcastable to shape2=%s' % (shape1, shape2))\n        shape[i] = max(a, b)\n        i -= 1\n    return tuple(shape)",
    "docstring": "Given two shapes that are not identical, find the shape\n    that both input shapes can broadcast to."
  },
  {
    "code": "def _calculate(self, field):\n        base_offset = 0\n        if self.base_field is not None:\n            base_offset = self.base_field.offset\n        target_offset = self._field.offset\n        if (target_offset is None) or (base_offset is None):\n            return 0\n        return target_offset - base_offset",
    "docstring": "If the offset is unknown, return 0"
  },
  {
    "code": "def list(self, mask=None):\n        if mask is None:\n            mask = \"mask[id, name, createDate, rule, guestCount, backendRouter[id, hostname]]\"\n        groups = self.client.call('Account', 'getPlacementGroups', mask=mask, iter=True)\n        return groups",
    "docstring": "List existing placement groups\n\n        Calls SoftLayer_Account::getPlacementGroups"
  },
  {
    "code": "def run(self, code: str) -> Output:\n        output = self._execute(code)\n        if self.echo and output.text:\n            print(output.text)\n        if self.check:\n            output.raise_for_status()\n        return output",
    "docstring": "Run some code in the managed Spark session.\n\n        :param code: The code to run."
  },
  {
    "code": "def _decompress_into_buffer(self, out_buffer):\n        zresult = lib.ZSTD_decompressStream(self._decompressor._dctx,\n                                            out_buffer, self._in_buffer)\n        if self._in_buffer.pos == self._in_buffer.size:\n            self._in_buffer.src = ffi.NULL\n            self._in_buffer.pos = 0\n            self._in_buffer.size = 0\n            self._source_buffer = None\n            if not hasattr(self._source, 'read'):\n                self._finished_input = True\n        if lib.ZSTD_isError(zresult):\n            raise ZstdError('zstd decompress error: %s' %\n                            _zstd_error(zresult))\n        return (out_buffer.pos and\n                (out_buffer.pos == out_buffer.size or\n                 zresult == 0 and not self._read_across_frames))",
    "docstring": "Decompress available input into an output buffer.\n\n        Returns True if data in output buffer should be emitted."
  },
  {
    "code": "def click_exists(self, timeout=0):\n        e = self.get(timeout=timeout, raise_error=False)\n        if e is None:\n            return False\n        e.click()\n        return True",
    "docstring": "Wait element and perform click\n\n        Args:\n            timeout (float): timeout for wait\n        \n        Returns:\n            bool: if successfully clicked"
  },
  {
    "code": "def string(s):\n    @Parser\n    def string_parser(text, index=0):\n        slen, tlen = len(s), len(text)\n        if text[index:index + slen] == s:\n            return Value.success(index + slen, s)\n        else:\n            matched = 0\n            while matched < slen and index + matched < tlen and text[index + matched] == s[matched]:\n                matched = matched + 1\n            return Value.failure(index + matched, s)\n    return string_parser",
    "docstring": "Parser a string."
  },
  {
    "code": "def tags(self):\n        result = []\n        a = javabridge.call(self.jobject, \"getTags\", \"()Lweka/core/Tag;]\")\n        length = javabridge.get_env().get_array_length(a)\n        wrapped = javabridge.get_env().get_object_array_elements(a)\n        for i in range(length):\n            result.append(Tag(javabridge.get_env().get_string(wrapped[i])))\n        return result",
    "docstring": "Returns the associated tags.\n\n        :return: the list of Tag objects\n        :rtype: list"
  },
  {
    "code": "def handle_template(self, template, subdir):\n        if template is None:\n            return six.text_type(os.path.join(yacms.__path__[0], subdir))\n        return super(Command, self).handle_template(template, subdir)",
    "docstring": "Use yacms's project template by default. The method of\n        picking the default directory is copied from Django's\n        TemplateCommand."
  },
  {
    "code": "def import_gwf_library(library, package=__package__):\n    try:\n        return importlib.import_module('.%s' % library, package=package)\n    except ImportError as exc:\n        exc.args = ('Cannot import %s frame API: %s' % (library, str(exc)),)\n        raise",
    "docstring": "Utility method to import the relevant timeseries.io.gwf frame API\n\n    This is just a wrapper around :meth:`importlib.import_module` with\n    a slightly nicer error message"
  },
  {
    "code": "def teetext(table, source=None, encoding=None, errors='strict', template=None,\n            prologue=None, epilogue=None):\n    assert template is not None, 'template is required'\n    return TeeTextView(table, source=source, encoding=encoding, errors=errors,\n                       template=template, prologue=prologue, epilogue=epilogue)",
    "docstring": "Return a table that writes rows to a text file as they are iterated over."
  },
  {
    "code": "def log_error(self, message, *args, **kwargs):\n        self._service.log(logging.ERROR, message, *args, **kwargs)",
    "docstring": "Log server error"
  },
  {
    "code": "def init_with_instance(self, instance):\n        self._uid = api.get_uid(instance)\n        self._brain = None\n        self._catalog = self.get_catalog_for(instance)\n        self._instance = instance",
    "docstring": "Initialize with an instance object"
  },
  {
    "code": "def string_to_identity(identity_str):\n    m = _identity_regexp.match(identity_str)\n    result = m.groupdict()\n    log.debug('parsed identity: %s', result)\n    return {k: v for k, v in result.items() if v}",
    "docstring": "Parse string into Identity dictionary."
  },
  {
    "code": "def object_properties_count(self, o):\n        o_type = type(o)\n        if isinstance(o, (dict, list, tuple, set)):\n            return len(o)\n        elif isinstance(o, (type(None), bool, float, \n                            str, int, \n                            bytes, types.ModuleType, \n                            types.MethodType, types.FunctionType)):\n            return 0\n        else:\n            try:\n                if hasattr(o, '__dict__'):\n                    count = len([m_name for m_name, m_value in o.__dict__.items()\n                                  if not m_name.startswith('__') \n                                    and not type(m_value) in (types.ModuleType, \n                                                              types.MethodType, \n                                                              types.FunctionType,) ])\n                else:\n                    count = 0\n            except:\n                count = 0\n            return count",
    "docstring": "returns the number of user browsable properties of an object."
  },
  {
    "code": "def dir_list(directory):\n    try:\n        content = listdir(directory)\n        return content\n    except WindowsError as winErr:\n        print(\"Directory error: \" + str((winErr)))",
    "docstring": "Returns the list of all files in the directory."
  },
  {
    "code": "def find_field(item_list, cond, comparator, target_field):\n    for item in item_list:\n        if comparator(item, cond) and target_field in item:\n            return item[target_field]\n    return None",
    "docstring": "Finds the value of a field in a dict object that satisfies certain\n    conditions.\n\n    Args:\n        item_list: A list of dict objects.\n        cond: A param that defines the condition.\n        comparator: A function that checks if an dict satisfies the condition.\n        target_field: Name of the field whose value to be returned if an item\n            satisfies the condition.\n\n    Returns:\n        Target value or None if no item satisfies the condition."
  },
  {
    "code": "def create_insert_func(self, wb_url,\n                           wb_prefix,\n                           host_prefix,\n                           top_url,\n                           env,\n                           is_framed,\n                           coll='',\n                           include_ts=True,\n                           **kwargs):\n        params = kwargs\n        params['host_prefix'] = host_prefix\n        params['wb_prefix'] = wb_prefix\n        params['wb_url'] = wb_url\n        params['top_url'] = top_url\n        params['coll'] = coll\n        params['is_framed'] = is_framed\n        def make_head_insert(rule, cdx):\n            params['wombat_ts'] = cdx['timestamp'] if include_ts else ''\n            params['wombat_sec'] = timestamp_to_sec(cdx['timestamp'])\n            params['is_live'] = cdx.get('is_live')\n            if self.banner_view:\n                banner_html = self.banner_view.render_to_string(env, cdx=cdx, **params)\n                params['banner_html'] = banner_html\n            return self.render_to_string(env, cdx=cdx, **params)\n        return make_head_insert",
    "docstring": "Create the function used to render the header insert template for the current request.\n\n        :param rewrite.wburl.WbUrl wb_url: The WbUrl for the request this template is being rendered for\n        :param str wb_prefix: The URL prefix pywb is serving the content using (e.g. http://localhost:8080/live/)\n        :param str host_prefix: The host URL prefix pywb is running on (e.g. http://localhost:8080)\n        :param str top_url: The full URL for this request (e.g. http://localhost:8080/live/http://example.com)\n        :param dict env: The WSGI environment dictionary for this request\n        :param bool is_framed: Is pywb or a specific collection running in framed mode\n        :param str coll: The name of the collection this request is associated with\n        :param bool include_ts: Should a timestamp be included in the rendered template\n        :param kwargs: Additional keyword arguments to be supplied to the Jninja template render method\n        :return: A function to be used to render the header insert for the request this template is being rendered for\n        :rtype: callable"
  },
  {
    "code": "def _finish(self):\n        if self._process.returncode is None:\n            self._process.stdin.flush()\n            self._process.stdin.close()\n            self._process.wait()\n            self.closed = True",
    "docstring": "Closes and waits for subprocess to exit."
  },
  {
    "code": "def collect_single_file(self, file_path):\n        lines = FileToList.to_list(file_path)\n        file_anchors = {}\n        file_duplicates = []\n        for i in range(len(lines)):\n            self._try_switches(lines, i)\n            if self._no_switches_on():\n                for s in self._strategies:\n                    if s.test(lines, i):\n                        tag, convert_me = s.get(lines, i)\n                        if tag in file_anchors:\n                            file_duplicates.append((tag, i + 1,\n                                                    file_anchors[tag]))\n                        else:\n                            anchor = self._converter(convert_me, file_anchors)\n                            file_anchors[tag] = anchor\n            self._arm_switches()\n        return file_anchors, file_duplicates",
    "docstring": "Takes in a list of strings, usually the lines in a text file,\n        and collects the AnchorHub tags and auto-generated anchors for the\n        file according to the  Collector's converter, strategies, and switches\n\n        :param file_path: string file path of file to examine\n        :return: A dictionary mapping AnchorHub tags to auto-generated\n            anchors, and a list of containing an entry for each duplicate tag\n            found on the page."
  },
  {
    "code": "def _can_for_object(self, func_name, object_id, method_name):\n        can_for_session = self._can(func_name)\n        if (can_for_session or\n                self._object_catalog_session is None or\n                self._override_lookup_session is None):\n            return can_for_session\n        override_auths = self._override_lookup_session.get_authorizations_for_agent_and_function(\n            self.get_effective_agent_id(),\n            self._get_function_id(func_name))\n        if not override_auths.available():\n            return False\n        if self._object_catalog_session is not None:\n            catalog_ids = list(getattr(self._object_catalog_session, method_name)(object_id))\n            for auth in override_auths:\n                if auth.get_qualifier_id() in catalog_ids:\n                    return True\n        return False",
    "docstring": "Checks if agent can perform function for object"
  },
  {
    "code": "def bootstrap_methods(self) -> BootstrapMethod:\n        bootstrap = self.attributes.find_one(name='BootstrapMethods')\n        if bootstrap is None:\n            bootstrap = self.attributes.create(\n                ATTRIBUTE_CLASSES['BootstrapMethods']\n            )\n        return bootstrap.table",
    "docstring": "Returns the bootstrap methods table from the BootstrapMethods attribute,\n        if one exists. If it does not, one will be created.\n\n        :returns: Table of `BootstrapMethod` objects."
  },
  {
    "code": "def uniquify_list(L):\n    return [e for i, e in enumerate(L) if L.index(e) == i]",
    "docstring": "Same order unique list using only a list compression."
  },
  {
    "code": "def drop(self, ex):\r\n    \"helper for apply_sql in DropX case\"\r\n    if ex.name not in self:\r\n      if ex.ifexists: return\r\n      raise KeyError(ex.name)\r\n    table_ = self[ex.name]\r\n    parent = table_.parent_table\r\n    if table_.child_tables:\r\n      if not ex.cascade:\r\n        raise table.IntegrityError('delete_parent_without_cascade',ex.name)\r\n      self.cascade_delete(ex.name)\r\n    else: del self[ex.name]\r\n    if parent: parent.child_tables.remove(table_)",
    "docstring": "helper for apply_sql in DropX case"
  },
  {
    "code": "def on_trial_complete(self,\n                          trial_id,\n                          result=None,\n                          error=False,\n                          early_terminated=False):\n        skopt_trial_info = self._live_trial_mapping.pop(trial_id)\n        if result:\n            self._skopt_opt.tell(skopt_trial_info, -result[self._reward_attr])",
    "docstring": "Passes the result to skopt unless early terminated or errored.\n\n        The result is internally negated when interacting with Skopt\n        so that Skopt Optimizers can \"maximize\" this value,\n        as it minimizes on default."
  },
  {
    "code": "def kill(self) -> None:\n        self._proc.kill()\n        self._loop.run_in_executor(None, self._proc.communicate)",
    "docstring": "Kill ffmpeg job."
  },
  {
    "code": "def set_result(self, result):\n        for future in self.traverse():\n            future.set_result(result)\n        if not self.done():\n            super().set_result(result)",
    "docstring": "Complete all tasks."
  },
  {
    "code": "def ecdsa_sign_compact(msg32, seckey):\n    output64 = ffi.new(\"unsigned char[65]\")\n    recid = ffi.new(\"int *\")\n    lib.secp256k1_ecdsa_recoverable_signature_serialize_compact(\n        ctx,\n        output64,\n        recid,\n        _ecdsa_sign_recoverable(msg32, seckey)\n    )\n    r = ffi.buffer(output64)[:64] + struct.pack(\"B\", recid[0])\n    assert len(r) == 65, len(r)\n    return r",
    "docstring": "Takes the same message and seckey as _ecdsa_sign_recoverable\n        Returns an unsigned char array of length 65 containing the signed message"
  },
  {
    "code": "def nz(value, none_value, strict=True):\n    if not DEBUG:\n        debug = False\n    else:\n        debug = False\n    if debug: print(\"START nz frameworkutilities.py ----------------------\\n\")\n    if value is None and strict:\n        return_val = none_value\n    elif strict and value is not None:\n        return_val = value\n    elif not strict and not is_not_null(value):\n        return_val = none_value\n    else:\n        return_val = value\n    if debug: print(\"value: %s | none_value: %s | return_val: %s\" %\n        (value, none_value, return_val))\n    if debug: print(\"END nz frameworkutilities.py ----------------------\\n\")\n    return return_val",
    "docstring": "This function is named after an old VBA function. It returns a default\n        value if the passed in value is None. If strict is False it will\n        treat an empty string as None as well.\n\n        example:\n        x = None\n        nz(x,\"hello\")\n        --> \"hello\"\n        nz(x,\"\")\n        --> \"\"\n        y = \"\"\n        nz(y,\"hello\")\n        --> \"\"\n        nz(y,\"hello\", False)\n        --> \"hello\""
  },
  {
    "code": "def contrail_error_handler(f):\n    @wraps(f)\n    def wrapper(*args, **kwargs):\n        try:\n            return f(*args, **kwargs)\n        except HttpError as e:\n            if e.details:\n                e.message, e.details = e.details, e.message\n                e.args = (\"%s (HTTP %s)\" % (e.message, e.http_status),)\n            raise\n    return wrapper",
    "docstring": "Handle HTTP errors returned by the API server"
  },
  {
    "code": "def load_eidos_curation_table():\n    url = 'https://raw.githubusercontent.com/clulab/eidos/master/' + \\\n        'src/main/resources/org/clulab/wm/eidos/english/confidence/' + \\\n        'rule_summary.tsv'\n    res = StringIO(requests.get(url).text)\n    table = pandas.read_table(res, sep='\\t')\n    table = table.drop(table.index[len(table)-1])\n    return table",
    "docstring": "Return a pandas table of Eidos curation data."
  },
  {
    "code": "def _hexencode(bytestring, insert_spaces = False):\n    _checkString(bytestring, description='byte string')\n    separator = '' if not insert_spaces else ' '\n    byte_representions = []\n    for c in bytestring:\n        byte_representions.append( '{0:02X}'.format(ord(c)) )\n    return separator.join(byte_representions).strip()",
    "docstring": "Convert a byte string to a hex encoded string.\n\n    For example 'J' will return '4A', and ``'\\\\x04'`` will return '04'.\n\n    Args:\n        bytestring (str): Can be for example ``'A\\\\x01B\\\\x45'``.\n        insert_spaces (bool): Insert space characters between pair of characters to increase readability.\n\n    Returns:\n        A string of twice the length, with characters in the range '0' to '9' and 'A' to 'F'.\n        The string will be longer if spaces are inserted.\n\n    Raises:\n        TypeError, ValueError"
  },
  {
    "code": "def get_param_arg(param, idx, klass, arg, attr='id'):\n    if isinstance(arg, klass):\n        return getattr(arg, attr)\n    elif isinstance(arg, (int, str)):\n        return arg\n    else:\n        raise TypeError(\n            \"%s[%d] must be int, str, or %s, not %s\" % (\n                param, idx, klass.__name__, type(arg).__name__))",
    "docstring": "Return the correct value for a fabric from `arg`."
  },
  {
    "code": "def unpackb(packed, **kwargs):\n    unpacker = Unpacker(None, **kwargs)\n    unpacker.feed(packed)\n    try:\n        ret = unpacker._unpack()\n    except OutOfData:\n        raise UnpackValueError(\"Data is not enough.\")\n    if unpacker._got_extradata():\n        raise ExtraData(ret, unpacker._get_extradata())\n    return ret",
    "docstring": "Unpack an object from `packed`.\n\n    Raises `ExtraData` when `packed` contains extra bytes.\n    See :class:`Unpacker` for options."
  },
  {
    "code": "def checksum(digits):\n    sum_mod11 = sum(map(operator.mul, digits, Provider.scale1)) % 11\n    if sum_mod11 < 10:\n        return sum_mod11\n    sum_mod11 = sum(map(operator.mul, digits, Provider.scale2)) % 11\n    return 0 if sum_mod11 == 10 else sum_mod11",
    "docstring": "Calculate checksum of Estonian personal identity code.\n\n    Checksum is calculated with \"Modulo 11\" method using level I or II scale:\n    Level I scale: 1 2 3 4 5 6 7 8 9 1\n    Level II scale: 3 4 5 6 7 8 9 1 2 3\n\n    The digits of the personal code are multiplied by level I scale and summed;\n    if remainder of modulo 11 of the sum is less than 10, checksum is the\n    remainder.\n    If remainder is 10, then level II scale is used; checksum is remainder if\n    remainder < 10 or 0 if remainder is 10.\n\n    See also https://et.wikipedia.org/wiki/Isikukood"
  },
  {
    "code": "def get_temperature_from_pressure(self):\n        self._init_pressure()\n        temp = 0\n        data = self._pressure.pressureRead()\n        if (data[2]):\n            temp = data[3]\n        return temp",
    "docstring": "Returns the temperature in Celsius from the pressure sensor"
  },
  {
    "code": "def compute_actor_handle_id_non_forked(actor_handle_id, current_task_id):\n    assert isinstance(actor_handle_id, ActorHandleID)\n    assert isinstance(current_task_id, TaskID)\n    handle_id_hash = hashlib.sha1()\n    handle_id_hash.update(actor_handle_id.binary())\n    handle_id_hash.update(current_task_id.binary())\n    handle_id = handle_id_hash.digest()\n    return ActorHandleID(handle_id)",
    "docstring": "Deterministically compute an actor handle ID in the non-forked case.\n\n    This code path is used whenever an actor handle is pickled and unpickled\n    (for example, if a remote function closes over an actor handle). Then,\n    whenever the actor handle is used, a new actor handle ID will be generated\n    on the fly as a deterministic function of the actor ID, the previous actor\n    handle ID and the current task ID.\n\n    TODO(rkn): It may be possible to cause problems by closing over multiple\n    actor handles in a remote function, which then get unpickled and give rise\n    to the same actor handle IDs.\n\n    Args:\n        actor_handle_id: The original actor handle ID.\n        current_task_id: The ID of the task that is unpickling the handle.\n\n    Returns:\n        An ID for the new actor handle."
  },
  {
    "code": "def list_vmss_sub(access_token, subscription_id):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/providers/Microsoft.Compute/virtualMachineScaleSets',\n                        '?api-version=', COMP_API])\n    return do_get_next(endpoint, access_token)",
    "docstring": "List VM Scale Sets in a subscription.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n\n    Returns:\n        HTTP response. JSON body of VM scale sets."
  },
  {
    "code": "def unpack_bytes(self, obj_bytes, encoding=None):\n        assert self.bytes_to_dict or self.string_to_dict\n        encoding = encoding or self.default_encoding\n        LOGGER.debug('%r decoding %d bytes with encoding of %s',\n                     self, len(obj_bytes), encoding)\n        if self.bytes_to_dict:\n            return escape.recursive_unicode(self.bytes_to_dict(obj_bytes))\n        return self.string_to_dict(obj_bytes.decode(encoding))",
    "docstring": "Unpack a byte stream into a dictionary."
  },
  {
    "code": "def load(fnames, tag=None, sat_id=None, \n         fake_daily_files_from_monthly=False,\n         flatten_twod=True):\n    import pysatCDF\n    if len(fnames) <= 0 :\n        return pysat.DataFrame(None), None\n    else:\n        if fake_daily_files_from_monthly:\n            fname = fnames[0][0:-11]\n            date = pysat.datetime.strptime(fnames[0][-10:], '%Y-%m-%d')\n            with pysatCDF.CDF(fname) as cdf:\n                data, meta = cdf.to_pysat(flatten_twod=flatten_twod)\n                data = data.ix[date:date+pds.DateOffset(days=1) - pds.DateOffset(microseconds=1),:]\n                return data, meta     \n        else:\n            with pysatCDF.CDF(fnames[0]) as cdf:     \n                return cdf.to_pysat(flatten_twod=flatten_twod)",
    "docstring": "Load NASA CDAWeb CDF files.\n    \n    This routine is intended to be used by pysat instrument modules supporting\n    a particular NASA CDAWeb dataset.\n\n    Parameters\n    ------------\n    fnames : (pandas.Series)\n        Series of filenames\n    tag : (str or NoneType)\n        tag or None (default=None)\n    sat_id : (str or NoneType)\n        satellite id or None (default=None)\n    fake_daily_files_from_monthly : bool\n        Some CDAWeb instrument data files are stored by month, interfering\n        with pysat's functionality of loading by day. This flag, when true,\n        parses of daily dates to monthly files that were added internally\n        by the list_files routine, when flagged. These dates are\n        used here to provide data by day. \n\n    Returns\n    ---------\n    data : (pandas.DataFrame)\n        Object containing satellite data\n    meta : (pysat.Meta)\n        Object containing metadata such as column names and units\n        \n    Examples\n    --------\n    ::\n    \n        # within the new instrument module, at the top level define\n        # a new variable named load, and set it equal to this load method\n        # code below taken from cnofs_ivm.py.\n        \n        # support load routine\n        # use the default CDAWeb method\n        load = cdw.load"
  },
  {
    "code": "def main(dbfile, pidfile, mode):\n    Inspector(dbfile, pidfile).reuse_snapshot().snapshot(mode)",
    "docstring": "Main analyzer routine."
  },
  {
    "code": "def schedule(ident, cron=None, minute='*', hour='*',\n             day_of_week='*', day_of_month='*', month_of_year='*'):\n    source = get_source(ident)\n    if cron:\n        minute, hour, day_of_month, month_of_year, day_of_week = cron.split()\n    crontab = PeriodicTask.Crontab(\n        minute=str(minute),\n        hour=str(hour),\n        day_of_week=str(day_of_week),\n        day_of_month=str(day_of_month),\n        month_of_year=str(month_of_year)\n    )\n    if source.periodic_task:\n        source.periodic_task.modify(crontab=crontab)\n    else:\n        source.modify(periodic_task=PeriodicTask.objects.create(\n            task='harvest',\n            name='Harvest {0}'.format(source.name),\n            description='Periodic Harvesting',\n            enabled=True,\n            args=[str(source.id)],\n            crontab=crontab,\n        ))\n    signals.harvest_source_scheduled.send(source)\n    return source",
    "docstring": "Schedule an harvesting on a source given a crontab"
  },
  {
    "code": "def stop(self):\n        if ( self.dev == None ): return ''\n        buf = [REPORT_ID, ord('p'), 0, 0, 0, 0, 0, 0, 0]\n        return self.write(buf);",
    "docstring": "Stop internal color pattern playing"
  },
  {
    "code": "def _get_column_ends(self):\n        ends = collections.Counter()\n        for line in self.text.splitlines():\n            for matchobj in re.finditer('\\s{2,}', line.lstrip()):\n                ends[matchobj.end()] += 1\n        return ends",
    "docstring": "Guess where the ends of the columns lie."
  },
  {
    "code": "def _print_routes(api_provider, host, port):\n        grouped_api_configs = {}\n        for api in api_provider.get_all():\n            key = \"{}-{}\".format(api.function_name, api.path)\n            config = grouped_api_configs.get(key, {})\n            config.setdefault(\"methods\", [])\n            config[\"function_name\"] = api.function_name\n            config[\"path\"] = api.path\n            config[\"methods\"].append(api.method)\n            grouped_api_configs[key] = config\n        print_lines = []\n        for _, config in grouped_api_configs.items():\n            methods_str = \"[{}]\".format(', '.join(config[\"methods\"]))\n            output = \"Mounting {} at http://{}:{}{} {}\".format(\n                         config[\"function_name\"],\n                         host,\n                         port,\n                         config[\"path\"],\n                         methods_str)\n            print_lines.append(output)\n            LOG.info(output)\n        return print_lines",
    "docstring": "Helper method to print the APIs that will be mounted. This method is purely for printing purposes.\n        This method takes in a list of Route Configurations and prints out the Routes grouped by path.\n        Grouping routes by Function Name + Path is the bulk of the logic.\n\n        Example output:\n            Mounting Product at http://127.0.0.1:3000/path1/bar [GET, POST, DELETE]\n            Mounting Product at http://127.0.0.1:3000/path2/bar [HEAD]\n\n        :param samcli.commands.local.lib.provider.ApiProvider api_provider: API Provider that can return a list of APIs\n        :param string host: Host name where the service is running\n        :param int port: Port number where the service is running\n        :returns list(string): List of lines that were printed to the console. Helps with testing"
  },
  {
    "code": "def get_driver(secret_key=config.DEFAULT_SECRET_KEY, userid=config.DEFAULT_USERID,\n               provider=config.DEFAULT_PROVIDER):\n    if hasattr(config, 'get_driver'):\n        logger.debug('get_driver %s' % config.get_driver)\n        return config.get_driver()\n    else:\n        logger.debug('get_driver {0}@{1}'.format(userid, provider))\n        return libcloud.compute.providers.get_driver(\n            config.PROVIDERS[provider])(userid, secret_key)",
    "docstring": "A driver represents successful authentication.  They become\n    stale, so obtain them as late as possible, and don't cache them."
  },
  {
    "code": "def _sanitize_url_components(comp_list, field):\n    if not comp_list:\n        return ''\n    elif comp_list[0].startswith('{0}='.format(field)):\n        ret = '{0}=XXXXXXXXXX&'.format(field)\n        comp_list.remove(comp_list[0])\n        return ret + _sanitize_url_components(comp_list, field)\n    else:\n        ret = '{0}&'.format(comp_list[0])\n        comp_list.remove(comp_list[0])\n        return ret + _sanitize_url_components(comp_list, field)",
    "docstring": "Recursive function to sanitize each component of the url."
  },
  {
    "code": "def register(self, src, trg, trg_mask=None, src_mask=None):\n        ccreg = registration.CrossCorr()\n        model = ccreg.fit(src, reference=trg)\n        translation = [-x for x in model.toarray().tolist()[0]]\n        warp_matrix = np.eye(2, 3)\n        warp_matrix[0, 2] = translation[1]\n        warp_matrix[1, 2] = translation[0]\n        return warp_matrix",
    "docstring": "Implementation of pair-wise registration using thunder-registration\n\n        For more information on the model estimation, refer to https://github.com/thunder-project/thunder-registration\n        This function takes two 2D single channel images and estimates a 2D translation that best aligns the pair. The\n        estimation is done by maximising the correlation of the Fourier transforms of the images. Once, the translation\n        is estimated, it is applied to the (multi-channel) image to warp and, possibly, ot hte ground-truth. Different\n        interpolations schemes could be more suitable for images and ground-truth values (or masks).\n\n        :param src: 2D single channel source moving image\n        :param trg: 2D single channel target reference image\n        :param src_mask: Mask of source image. Not used in this method.\n        :param trg_mask: Mask of target image. Not used in this method.\n        :return: Estimated 2D transformation matrix of shape 2x3"
  },
  {
    "code": "def update_ports(self, ports, id_or_uri):\n        ports = merge_default_values(ports, {'type': 'port'})\n        uri = self._client.build_uri(id_or_uri) + \"/update-ports\"\n        return self._client.update(uri=uri, resource=ports)",
    "docstring": "Updates the switch ports. Only the ports under the management of OneView and those that are unlinked are\n        supported for update.\n\n        Note:\n            This method is available for API version 300 or later.\n\n        Args:\n            ports: List of Switch Ports.\n            id_or_uri: Can be either the switch id or the switch uri.\n\n        Returns:\n            dict: Switch"
  },
  {
    "code": "def interpolate_xml_array(data, low_res_coords, shape, chunks):\n        xpoints, ypoints = low_res_coords\n        return interpolate_xarray_linear(xpoints, ypoints, data, shape, chunks=chunks)",
    "docstring": "Interpolate arbitrary size dataset to a full sized grid."
  },
  {
    "code": "def stop(self):\n        self._flush()\n        filesize = self.file.tell()\n        super(BLFWriter, self).stop()\n        header = [b\"LOGG\", FILE_HEADER_SIZE,\n                  APPLICATION_ID, 0, 0, 0, 2, 6, 8, 1]\n        header.extend([filesize, self.uncompressed_size,\n                       self.count_of_objects, 0])\n        header.extend(timestamp_to_systemtime(self.start_timestamp))\n        header.extend(timestamp_to_systemtime(self.stop_timestamp))\n        with open(self.file.name, \"r+b\") as f:\n            f.write(FILE_HEADER_STRUCT.pack(*header))",
    "docstring": "Stops logging and closes the file."
  },
  {
    "code": "def error_leader(self, infile=None, lineno=None):\n        \"Emit a C-compiler-like, Emacs-friendly error-message leader.\"\n        if infile is None:\n            infile = self.infile\n        if lineno is None:\n            lineno = self.lineno\n        return \"\\\"%s\\\", line %d: \" % (infile, lineno)",
    "docstring": "Emit a C-compiler-like, Emacs-friendly error-message leader."
  },
  {
    "code": "def run(self):\n        while self.should_run:\n            try:\n                self.logger.debug('Sending heartbeat, seq ' + last_sequence)\n                self.ws.send(json.dumps({\n                    'op': 1,\n                    'd': last_sequence\n                }))\n            except Exception as e:\n                self.logger.error(f'Got error in heartbeat: {str(e)}')\n            finally:\n                elapsed = 0.0\n                while elapsed < self.interval and self.should_run:\n                    time.sleep(self.TICK_INTERVAL)\n                    elapsed += self.TICK_INTERVAL",
    "docstring": "Runs the thread\n\n        This method handles sending the heartbeat to the Discord websocket server, so the connection\n        can remain open and the bot remain online for those commands that require it to be.\n\n        Args:\n            None"
  },
  {
    "code": "def drawing_end(self):\n        from MAVProxy.modules.mavproxy_map import mp_slipmap\n        if self.draw_callback is None:\n            return\n        self.draw_callback(self.draw_line)\n        self.draw_callback = None\n        self.map.add_object(mp_slipmap.SlipDefaultPopup(self.default_popup, combine=True))\n        self.map.add_object(mp_slipmap.SlipClearLayer('Drawing'))",
    "docstring": "end line drawing"
  },
  {
    "code": "def readrows(self):\n        num_rows = 0\n        while True:\n            for row in self.log_reader.readrows():\n                yield self.replace_timestamp(row)\n                time.sleep(next(self.eps_timer))\n                num_rows += 1\n                if self.max_rows and (num_rows >= self.max_rows):\n                    return",
    "docstring": "Using the BroLogReader this method yields each row of the log file\n           replacing timestamps, looping and emitting rows based on EPS rate"
  },
  {
    "code": "def plot_f(self, plot_limits=None, fixed_inputs=None,\n              resolution=None,\n              apply_link=False,\n              which_data_ycols='all', which_data_rows='all',\n              visible_dims=None,\n              levels=20, samples=0, lower=2.5, upper=97.5,\n              plot_density=False,\n              plot_data=True, plot_inducing=True,\n              projection='2d', legend=True,\n              predict_kw=None,\n              **kwargs):\n    return plot(self, plot_limits, fixed_inputs, resolution, True,\n         apply_link, which_data_ycols, which_data_rows,\n         visible_dims, levels, samples, 0,\n         lower, upper, plot_data, plot_inducing,\n         plot_density, predict_kw, projection, legend, **kwargs)",
    "docstring": "Convinience function for plotting the fit of a GP.\n    This is the same as plot, except it plots the latent function fit of the GP!\n\n    If you want fine graned control use the specific plotting functions supplied in the model.\n\n    You can deactivate the legend for this one plot by supplying None to label.\n\n    Give the Y_metadata in the predict_kw if you need it.\n\n\n    :param plot_limits: The limits of the plot. If 1D [xmin,xmax], if 2D [[xmin,ymin],[xmax,ymax]]. Defaluts to data limits\n    :type plot_limits: np.array\n    :param fixed_inputs: a list of tuple [(i,v), (i,v)...], specifying that input dimension i should be set to value v.\n    :type fixed_inputs: a list of tuples\n    :param int resolution: The resolution of the prediction [default:200]\n    :param bool apply_link: whether to apply the link function of the GP to the raw prediction.\n    :param which_data_ycols: when the data has several columns (independant outputs), only plot these\n    :type which_data_ycols: 'all' or a list of integers\n    :param which_data_rows: which of the training data to plot (default all)\n    :type which_data_rows: 'all' or a slice object to slice self.X, self.Y\n    :param array-like visible_dims: an array specifying the input dimensions to plot (maximum two)\n    :param int levels: the number of levels in the density (number bigger then 1, where 35 is smooth and 1 is the same as plot_confidence). You can go higher then 50 if the result is not smooth enough for you.\n    :param int samples: the number of samples to draw from the GP and plot into the plot. This will allways be samples from the latent function.\n    :param float lower: the lower percentile to plot\n    :param float upper: the upper percentile to plot\n    :param bool plot_data: plot the data into the plot?\n    :param bool plot_inducing: plot inducing inputs?\n    :param bool plot_density: plot density instead of the confidence interval?\n    :param dict predict_kw: the keyword arguments for the prediction. If you want to plot a specific kernel give dict(kern=<specific kernel>) in here\n    :param dict error_kwargs: kwargs for the error plot for the plotting library you are using\n    :param kwargs plot_kwargs: kwargs for the data plot for the plotting library you are using"
  },
  {
    "code": "def get(self, key, default):\n        with self._lock:\n            try:\n                return self._dict[key].copy()\n            except KeyError:\n                return default",
    "docstring": "If the key is set, return a copy of the list stored at key.\n        Otherwise return default."
  },
  {
    "code": "def _parent_tile(tiles):\n    parent = None\n    for t in tiles:\n        if parent is None:\n            parent = t\n        else:\n            parent = common_parent(parent, t)\n    return parent",
    "docstring": "Find the common parent tile for a sequence of tiles."
  },
  {
    "code": "def get_outcome_group(self, group):\n        from canvasapi.outcome import OutcomeGroup\n        outcome_group_id = obj_or_id(group, \"group\", (OutcomeGroup,))\n        response = self.__requester.request(\n            'GET',\n            'global/outcome_groups/{}'.format(outcome_group_id)\n        )\n        return OutcomeGroup(self.__requester, response.json())",
    "docstring": "Returns the details of the Outcome Group with the given id.\n\n        :calls: `GET /api/v1/global/outcome_groups/:id \\\n            <https://canvas.instructure.com/doc/api/outcome_groups.html#method.outcome_groups_api.show>`_\n\n        :param group: The outcome group object or ID to return.\n        :type group: :class:`canvasapi.outcome.OutcomeGroup` or int\n\n        :returns: An outcome group object.\n        :rtype: :class:`canvasapi.outcome.OutcomeGroup`"
  },
  {
    "code": "def compile_msg_payload(self, invite):\n        self.l.info(\"Compiling the outbound message payload\")\n        update_invite = False\n        if \"to_addr\" in invite.invite:\n            to_addr = invite.invite[\"to_addr\"]\n        else:\n            update_invite = True\n            to_addr = get_identity_address(invite.identity)\n        if \"content\" in invite.invite:\n            content = invite.invite[\"content\"]\n        else:\n            update_invite = True\n            content = settings.INVITE_TEXT\n        if \"metadata\" in invite.invite:\n            metadata = invite.invite[\"metadata\"]\n        else:\n            update_invite = True\n            metadata = {}\n        msg_payload = {\n            \"to_addr\": to_addr,\n            \"content\": content,\n            \"metadata\": metadata\n        }\n        if update_invite is True:\n            self.l.info(\"Updating the invite.invite field\")\n            invite.invite = msg_payload\n            invite.save()\n        self.l.info(\"Compiled the outbound message payload\")\n        return msg_payload",
    "docstring": "Determine recipient, message content, return it as\n        a dict that can be Posted to the message sender"
  },
  {
    "code": "def star_expr_check(self, original, loc, tokens):\n        return self.check_py(\"35\", \"star unpacking (add 'match' to front to produce universal code)\", original, loc, tokens)",
    "docstring": "Check for Python 3.5 star unpacking."
  },
  {
    "code": "def convex_conj(self):\n        r\n        if self.operator is None:\n            tmp = IndicatorZero(space=self.domain, constant=-self.constant)\n            if self.vector is None:\n                return tmp\n            else:\n                return tmp.translated(self.vector)\n        if self.vector is None:\n            return QuadraticForm(operator=self.operator.inverse,\n                                 constant=-self.constant)\n        else:\n            opinv = self.operator.inverse\n            vector = -opinv.adjoint(self.vector) - opinv(self.vector)\n            constant = self.vector.inner(opinv(self.vector)) - self.constant\n            return QuadraticForm(operator=opinv,\n                                 vector=vector,\n                                 constant=constant)",
    "docstring": "r\"\"\"The convex conjugate functional of the quadratic form.\n\n        Notes\n        -----\n        The convex conjugate of the quadratic form :math:`<x, Ax> + <b, x> + c`\n        is given by\n\n        .. math::\n            (<x, Ax> + <b, x> + c)^* (x) =\n            <(x - b), A^-1 (x - b)> - c =\n            <x , A^-1 x> - <x, A^-* b> - <x, A^-1 b> + <b, A^-1 b> - c.\n\n        If the quadratic part of the functional is zero it is instead given\n        by a translated indicator function on zero, i.e., if\n\n        .. math::\n            f(x) = <b, x> + c,\n\n        then\n\n        .. math::\n            f^*(x^*) =\n            \\begin{cases}\n                -c & \\text{if } x^* = b \\\\\n                \\infty & \\text{else.}\n            \\end{cases}\n\n        See Also\n        --------\n        IndicatorZero"
  },
  {
    "code": "def _get_app_path(url):\n    app_path = urlparse(url).path.rstrip(\"/\")\n    if not app_path.startswith(\"/\"):\n        app_path = \"/\" + app_path\n    return app_path",
    "docstring": "Extract the app path from a Bokeh server URL\n\n    Args:\n        url (str) :\n\n    Returns:\n        str"
  },
  {
    "code": "def sysinit(systype, conf, project):\n    click.secho(get_config(\n        systype,\n        conf=ConfModule(conf).configurations[0],\n        conf_path=conf,\n        project_name=project,\n    ))",
    "docstring": "Outputs configuration for system initialization subsystem."
  },
  {
    "code": "def _RunInTransaction(self, function, readonly=False):\n    start_query = \"START TRANSACTION;\"\n    if readonly:\n      start_query = \"START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLY;\"\n    for retry_count in range(_MAX_RETRY_COUNT):\n      with contextlib.closing(self.pool.get()) as connection:\n        try:\n          with contextlib.closing(connection.cursor()) as cursor:\n            cursor.execute(start_query)\n          ret = function(connection)\n          if not readonly:\n            connection.commit()\n          return ret\n        except MySQLdb.OperationalError as e:\n          connection.rollback()\n          if retry_count >= _MAX_RETRY_COUNT or not _IsRetryable(e):\n            raise\n      time.sleep(random.uniform(1.0, 2.0) * math.pow(1.5, retry_count))\n    raise Exception(\"Looped ended early - last exception swallowed.\")",
    "docstring": "Runs function within a transaction.\n\n    Allocates a connection, begins a transaction on it and passes the connection\n    to function.\n\n    If function finishes without raising, the transaction is committed.\n\n    If function raises, the transaction will be rolled back, if a retryable\n    database error is raised, the operation may be repeated.\n\n    Args:\n      function: A function to be run, must accept a single MySQLdb.connection\n        parameter.\n      readonly: Indicates that only a readonly (snapshot) transaction is\n        required.\n\n    Returns:\n      The value returned by the last call to function.\n\n    Raises: Any exception raised by function."
  },
  {
    "code": "def set_dry_run(xml_root, value=True):\n    value_str = str(value).lower()\n    assert value_str in (\"true\", \"false\")\n    if xml_root.tag == \"testsuites\":\n        _set_property(xml_root, \"polarion-dry-run\", value_str)\n    elif xml_root.tag in (\"testcases\", \"requirements\"):\n        _set_property(xml_root, \"dry-run\", value_str)\n    else:\n        raise Dump2PolarionException(_NOT_EXPECTED_FORMAT_MSG)",
    "docstring": "Sets dry-run so records are not updated, only log file is produced."
  },
  {
    "code": "def crit_met(self):\n        if True in (self.pulls < 3):\n            return False\n        else:\n            return self.criteria[self.criterion](self.stop_value)",
    "docstring": "Determine if stopping criterion has been met.\n\n        Returns\n        -------\n        bool"
  },
  {
    "code": "def _bfs_from_cluster_tree(tree, bfs_root):\n    result = []\n    to_process = [bfs_root]\n    while to_process:\n        result.extend(to_process)\n        to_process = tree['child'][np.in1d(tree['parent'], to_process)].tolist()\n    return result",
    "docstring": "Perform a breadth first search on a tree in condensed tree format"
  },
  {
    "code": "def read_inquiry_mode(sock):\n    old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)\n    flt = bluez.hci_filter_new()\n    opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL, \n            bluez.OCF_READ_INQUIRY_MODE)\n    bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)\n    bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE);\n    bluez.hci_filter_set_opcode(flt, opcode)\n    sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )\n    bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL, \n            bluez.OCF_READ_INQUIRY_MODE )\n    pkt = sock.recv(255)\n    status,mode = struct.unpack(\"xxxxxxBB\", pkt)\n    if status != 0: mode = -1\n    sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )\n    return mode",
    "docstring": "returns the current mode, or -1 on failure"
  },
  {
    "code": "def wait_while_exceptions(\n        predicate,\n        timeout_seconds=120,\n        sleep_seconds=1,\n        noisy=False):\n    start_time = time_module.time()\n    timeout = Deadline.create_deadline(timeout_seconds)\n    while True:\n        try:\n            result = predicate()\n            return result\n        except Exception as e:\n            if noisy:\n                logger.exception(\"Ignoring error during wait.\")\n        if timeout.is_expired():\n            funname = __stringify_predicate(predicate)\n            raise TimeoutExpired(timeout_seconds, funname)\n        if noisy:\n            header = '{}[{}/{}]'.format(\n                shakedown.cli.helpers.fchr('>>'),\n                pretty_duration(time_module.time() - start_time),\n                pretty_duration(timeout_seconds)\n            )\n            print('{} spinning...'.format(header))\n        time_module.sleep(sleep_seconds)",
    "docstring": "waits for a predicate, ignoring exceptions, returning the result.\n        Predicate is a function.\n        Exceptions will trigger the sleep and retry; any non-exception result\n        will be returned.\n        A timeout will throw a TimeoutExpired Exception."
  },
  {
    "code": "def _validate_type_scalar(self, value):\n        if isinstance(\n            value, _int_types + (_str_type, float, date, datetime, bool)\n        ):\n            return True",
    "docstring": "Is not a list or a dict"
  },
  {
    "code": "def _new_temp_file(self, hint='warcrecsess'):\n        return wpull.body.new_temp_file(\n            directory=self._temp_dir, hint=hint\n        )",
    "docstring": "Return new temp file."
  },
  {
    "code": "def cmd(self, cmd_name):\n        return \"{0}.tube.{1}:{2}\".format(self.queue.lua_queue_name, self.name, cmd_name)",
    "docstring": "Returns tarantool queue command name for current tube."
  },
  {
    "code": "def edges_to_path(edges):\n    if not edges:\n        return None\n    G = edges_to_graph(edges)\n    path = nx.topological_sort(G)\n    return path",
    "docstring": "Connect edges and return a path."
  },
  {
    "code": "def zoomset_cb(self, setting, value, chviewer, info):\n        return self.zoomset(chviewer, info.chinfo)",
    "docstring": "This callback is called when a channel window is zoomed."
  },
  {
    "code": "def go_to(self, x, y, z, yaw, duration_s, relative=False,\n              group_mask=ALL_GROUPS):\n        self._send_packet(struct.pack('<BBBfffff',\n                                      self.COMMAND_GO_TO,\n                                      group_mask,\n                                      relative,\n                                      x, y, z,\n                                      yaw,\n                                      duration_s))",
    "docstring": "Go to an absolute or relative position\n\n        :param x: x (m)\n        :param y: y (m)\n        :param z: z (m)\n        :param yaw: yaw (radians)\n        :param duration_s: time it should take to reach the position (s)\n        :param relative: True if x, y, z is relative to the current position\n        :param group_mask: mask for which CFs this should apply to"
  },
  {
    "code": "def create_db_instance(self, params):\n        if not self.connect_to_aws_rds():\n            return False\n        try:\n            database = self.rdsc.create_dbinstance(\n                id=params['id'],\n                allocated_storage=params['size'],\n                instance_class='db.t1.micro',\n                engine='MySQL',\n                master_username=params['username'],\n                master_password=params['password'],\n                db_name=params['dbname'],\n                multi_az=False\n            )\n        except:\n            return False\n        else:\n            return True",
    "docstring": "Create db instance"
  },
  {
    "code": "def inject_closure_values(func, **kwargs):\n    wrapped_by = None\n    if isinstance(func, property):\n        fget, fset, fdel = func.fget, func.fset, func.fdel\n        if fget: fget = fix_func(fget, **kwargs)\n        if fset: fset = fix_func(fset, **kwargs)\n        if fdel: fdel = fix_func(fdel, **kwargs)\n        wrapped_by = type(func)\n        return wrapped_by(fget, fset, fdel)\n    elif isinstance(func, (staticmethod, classmethod)):\n        func = func.__func__\n        wrapped_by = type(func)\n    newfunc = _inject_closure_values(func, **kwargs)\n    if wrapped_by:\n        newfunc = wrapped_by(newfunc)\n    return newfunc",
    "docstring": "Returns a new function identical to the previous one except that it acts as\n    though global variables named in `kwargs` have been closed over with the\n    values specified in the `kwargs` dictionary.\n\n    Works on properties, class/static methods and functions.\n\n    This can be useful for mocking and other nefarious activities."
  },
  {
    "code": "def iterateBlocksBackFrom(block):\n        count = 0\n        while block.isValid() and count < MAX_SEARCH_OFFSET_LINES:\n            yield block\n            block = block.previous()\n            count += 1",
    "docstring": "Generator, which iterates QTextBlocks from block until the Start of a document\n        But, yields not more than MAX_SEARCH_OFFSET_LINES"
  },
  {
    "code": "def _cron_profile():\n    from os import path\n    cronpath = path.expanduser(\"~/.cron_profile\")\n    if not path.isfile(cronpath):\n        from os import getenv\n        xmlpath = getenv(\"PYCI_XML\")    \n        contents = ['source /usr/local/bin/virtualenvwrapper.sh',\n                    'export PYCI_XML=\"{}\"'.format(xmlpath)]\n        with open(cronpath, 'w') as f:\n            f.write('\\n'.join(contents))",
    "docstring": "Sets up the .cron_profile file if it does not already exist."
  },
  {
    "code": "def save(self, filename, strip_prefix=''):\n        arg_dict = {}\n        for param in self.values():\n            weight = param._reduce()\n            if not param.name.startswith(strip_prefix):\n                raise ValueError(\n                    \"Prefix '%s' is to be striped before saving, but Parameter's \"\n                    \"name '%s' does not start with '%s'. \"\n                    \"this may be due to your Block shares parameters from other \"\n                    \"Blocks or you forgot to use 'with name_scope()' when creating \"\n                    \"child blocks. For more info on naming, please see \"\n                    \"http://mxnet.incubator.apache.org/tutorials/basic/naming.html\"%(\n                        strip_prefix, param.name, strip_prefix))\n            arg_dict[param.name[len(strip_prefix):]] = weight\n        ndarray.save(filename, arg_dict)",
    "docstring": "Save parameters to file.\n\n        Parameters\n        ----------\n        filename : str\n            Path to parameter file.\n        strip_prefix : str, default ''\n            Strip prefix from parameter names before saving."
  },
  {
    "code": "def models_of_config(config):\n    resources = resources_of_config(config)\n    models = []\n    for resource in resources:\n        if not hasattr(resource, '__table__') and hasattr(resource, 'model'):\n            models.append(resource.model)\n        else:\n            models.append(resource)\n    return models",
    "docstring": "Return list of models from all resources in config."
  },
  {
    "code": "def _deduplicate_items(cls, items):\n        \"Deduplicates assigned paths by incrementing numbering\"\n        counter = Counter([path[:i] for path, _ in items for i in range(1, len(path)+1)])\n        if sum(counter.values()) == len(counter):\n            return items\n        new_items = []\n        counts = defaultdict(lambda: 0)\n        for i, (path, item) in enumerate(items):\n            if counter[path] > 1:\n                path = path + (util.int_to_roman(counts[path]+1),)\n            elif counts[path]:\n                path = path[:-1] + (util.int_to_roman(counts[path]+1),)\n            new_items.append((path, item))\n            counts[path] += 1\n        return new_items",
    "docstring": "Deduplicates assigned paths by incrementing numbering"
  },
  {
    "code": "def get_day(self):\n        year = super(BuildableDayArchiveView, self).get_year()\n        month = super(BuildableDayArchiveView, self).get_month()\n        day = super(BuildableDayArchiveView, self).get_day()\n        fmt = self.get_day_format()\n        dt = date(int(year), int(month), int(day))\n        return dt.strftime(fmt)",
    "docstring": "Return the day from the database in the format expected by the URL."
  },
  {
    "code": "def path_fraction_id_offset(points, fraction, relative_offset=False):\n    if not (0. <= fraction <= 1.0):\n        raise ValueError(\"Invalid fraction: %.3f\" % fraction)\n    pts = np.array(points)[:, COLS.XYZ]\n    lengths = np.linalg.norm(np.diff(pts, axis=0), axis=1)\n    cum_lengths = np.cumsum(lengths)\n    offset = cum_lengths[-1] * fraction\n    seg_id = np.argmin(cum_lengths < offset)\n    if seg_id > 0:\n        offset -= cum_lengths[seg_id - 1]\n    if relative_offset:\n        offset /= lengths[seg_id]\n    return seg_id, offset",
    "docstring": "Find the segment which corresponds to the fraction\n    of the path length along the piecewise linear curve which\n    is constructed from the set of points.\n\n    Args:\n        points: an iterable of indexable objects with indices\n        0, 1, 2 correspoding to 3D cartesian coordinates\n        fraction: path length fraction (0.0 <= fraction <= 1.0)\n        relative_offset: return absolute or relative segment distance\n\n    Returns:\n        (segment ID, segment offset) pair."
  },
  {
    "code": "def ginput(self, data_set=0, **kwargs):\n        import warnings\n        import matplotlib.cbook\n        warnings.filterwarnings(\"ignore\",category=matplotlib.cbook.mplDeprecation)\n        _s.tweaks.raise_figure_window(data_set+self['first_figure'])\n        return _p.ginput(**kwargs)",
    "docstring": "Pops up the figure for the specified data set.\n\n        Returns value from pylab.ginput().\n\n        kwargs are sent to pylab.ginput()"
  },
  {
    "code": "def read_count(self, space, start, end):\n        read_counts = 0\n        for read in self._bam.fetch(space, start, end):\n            read_counts += 1\n        return self._normalize(read_counts, self._total)",
    "docstring": "Retrieve the normalized read count in the provided region."
  },
  {
    "code": "def _play(self):\n        while True:\n            if self._buffered:\n                self._source.push(self._buffer.get())",
    "docstring": "Relay buffer to app source."
  },
  {
    "code": "def _select_phase_left_bound(self, epoch_number):\n        idx = bisect.bisect_left(self.ladder, epoch_number)\n        if idx >= len(self.ladder):\n            return len(self.ladder) - 1\n        elif self.ladder[idx] > epoch_number:\n            return idx - 1\n        else:\n            return idx",
    "docstring": "Return number of current phase.\n        Return index of first phase not done after all up to epoch_number were done."
  },
  {
    "code": "def npedln(a, b, c, linept, linedr):\n    a = ctypes.c_double(a)\n    b = ctypes.c_double(b)\n    c = ctypes.c_double(c)\n    linept = stypes.toDoubleVector(linept)\n    linedr = stypes.toDoubleVector(linedr)\n    pnear = stypes.emptyDoubleVector(3)\n    dist = ctypes.c_double()\n    libspice.npedln_c(a, b, c, linept, linedr, pnear, ctypes.byref(dist))\n    return stypes.cVectorToPython(pnear), dist.value",
    "docstring": "Find nearest point on a triaxial ellipsoid to a specified\n    line and the distance from the ellipsoid to the line.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/npedln_c.html\n\n    :param a: Length of ellipsoid's semi-axis in the x direction\n    :type a: float\n    :param b: Length of ellipsoid's semi-axis in the y direction\n    :type b: float\n    :param c: Length of ellipsoid's semi-axis in the z direction\n    :type c: float\n    :param linept: Length of ellipsoid's semi-axis in the z direction\n    :type linept: 3-Element Array of floats\n    :param linedr: Direction vector of line\n    :type linedr: 3-Element Array of floats\n    :return: Nearest point on ellipsoid to line, Distance of ellipsoid from line\n    :rtype: tuple"
  },
  {
    "code": "def get_results_as_xarray(self, parameter_space,\n                              result_parsing_function,\n                              output_labels, runs):\n        np_array = np.array(\n            self.get_space(\n                self.db.get_complete_results(), {},\n                collections.OrderedDict([(k, v) for k, v in\n                                         parameter_space.items()]),\n                runs, result_parsing_function))\n        clean_parameter_space = collections.OrderedDict(\n            [(k, v) for k, v in parameter_space.items()])\n        clean_parameter_space['runs'] = range(runs)\n        if isinstance(output_labels, list):\n            clean_parameter_space['metrics'] = output_labels\n        xr_array = xr.DataArray(np_array, coords=clean_parameter_space,\n                                dims=list(clean_parameter_space.keys()))\n        return xr_array",
    "docstring": "Return the results relative to the desired parameter space in the form\n        of an xarray data structure.\n\n        Args:\n            parameter_space (dict): The space of parameters to export.\n            result_parsing_function (function): user-defined function, taking a\n                result dictionary as argument, that can be used to parse the\n                result files and return a list of values.\n            output_labels (list): a list of labels to apply to the results\n                dimensions, output by the result_parsing_function.\n            runs (int): the number of runs to export for each parameter\n                combination."
  },
  {
    "code": "def convertShape(shapeString):\n    cshape = []\n    for pointString in shapeString.split():\n        p = [float(e) for e in pointString.split(\",\")]\n        if len(p) == 2:\n            cshape.append((p[0], p[1], 0.))\n        elif len(p) == 3:\n            cshape.append(tuple(p))\n        else:\n            raise ValueError(\n                'Invalid shape point \"%s\", should be either 2d or 3d' % pointString)\n    return cshape",
    "docstring": "Convert xml shape string into float tuples.\n\n    This method converts the 2d or 3d shape string from SUMO's xml file\n    into a list containing 3d float-tuples. Non existant z coordinates default\n    to zero. If shapeString is empty, an empty list will be returned."
  },
  {
    "code": "def get_xid_device(device_number):\n    scanner = XidScanner()\n    com = scanner.device_at_index(device_number)\n    com.open()\n    return XidDevice(com)",
    "docstring": "returns device at a given index.\n\n    Raises ValueError if the device at the passed in index doesn't\n    exist."
  },
  {
    "code": "def DeleteAttributes(self,\n                       subject,\n                       attributes,\n                       start=None,\n                       end=None,\n                       sync=True):\n    _ = sync\n    if not attributes:\n      return\n    if isinstance(attributes, string_types):\n      raise ValueError(\n          \"String passed to DeleteAttributes (non string iterable expected).\")\n    for attribute in attributes:\n      timestamp = self._MakeTimestamp(start, end)\n      attribute = utils.SmartUnicode(attribute)\n      queries = self._BuildDelete(subject, attribute, timestamp)\n      self._ExecuteQueries(queries)",
    "docstring": "Remove some attributes from a subject."
  },
  {
    "code": "def get_grounded_agent(gene_name):\n    db_refs = {'TEXT': gene_name}\n    if gene_name in hgnc_map:\n        gene_name = hgnc_map[gene_name]\n    hgnc_id = hgnc_client.get_hgnc_id(gene_name)\n    if hgnc_id:\n        db_refs['HGNC'] = hgnc_id\n        up_id = hgnc_client.get_uniprot_id(hgnc_id)\n        if up_id:\n            db_refs['UP'] = up_id\n    agent = Agent(gene_name, db_refs=db_refs)\n    return agent",
    "docstring": "Return a grounded Agent based on an HGNC symbol."
  },
  {
    "code": "def expect(obj, strict=None,\n           times=None, atleast=None, atmost=None, between=None):\n    if strict is None:\n        strict = True\n    theMock = _get_mock(obj, strict=strict)\n    verification_fn = _get_wanted_verification(\n        times=times, atleast=atleast, atmost=atmost, between=between)\n    class Expect(object):\n        def __getattr__(self, method_name):\n            return invocation.StubbedInvocation(\n                theMock, method_name, verification=verification_fn,\n                strict=strict)\n    return Expect()",
    "docstring": "Stub a function call, and set up an expected call count.\n\n    Usage::\n\n        # Given `dog` is an instance of a `Dog`\n        expect(dog, times=1).bark('Wuff').thenReturn('Miau')\n        dog.bark('Wuff')\n        dog.bark('Wuff')  # will throw at call time: too many invocations\n\n        # maybe if you need to ensure that `dog.bark()` was called at all\n        verifyNoUnwantedInteractions()\n\n    .. note:: You must :func:`unstub` after stubbing, or use `with`\n        statement.\n\n    See :func:`when`, :func:`when2`, :func:`verifyNoUnwantedInteractions`"
  },
  {
    "code": "def update_edges(self, elev_fn, dem_proc):\n        interp = self.build_interpolator(dem_proc)\n        self.update_edge_todo(elev_fn, dem_proc)\n        self.set_neighbor_data(elev_fn, dem_proc, interp)",
    "docstring": "After finishing a calculation, this will update the neighbors and the\n        todo for that tile"
  },
  {
    "code": "def visit_BoolOp(self, node: ast.BoolOp) -> Any:\n        values = [self.visit(value_node) for value_node in node.values]\n        if isinstance(node.op, ast.And):\n            result = functools.reduce(lambda left, right: left and right, values, True)\n        elif isinstance(node.op, ast.Or):\n            result = functools.reduce(lambda left, right: left or right, values, True)\n        else:\n            raise NotImplementedError(\"Unhandled op of {}: {}\".format(node, node.op))\n        self.recomputed_values[node] = result\n        return result",
    "docstring": "Recursively visit the operands and apply the operation on them."
  },
  {
    "code": "def to_date(ts: float) -> datetime.date:\n    return datetime.datetime.fromtimestamp(\n        ts, tz=datetime.timezone.utc).date()",
    "docstring": "Convert timestamp to date.\n\n    >>> to_date(978393600.0)\n    datetime.date(2001, 1, 2)"
  },
  {
    "code": "def _check_if_downloaded(self):\n        if not os.path.isfile(self.path + self.file_name):\n            print(\"\")\n            self.msg.template(78)\n            print(\"| Download '{0}' file [ {1}FAILED{2} ]\".format(\n                self.file_name, self.meta.color[\"RED\"],\n                self.meta.color[\"ENDC\"]))\n            self.msg.template(78)\n            print(\"\")\n            if not self.msg.answer() in [\"y\", \"Y\"]:\n                raise SystemExit()",
    "docstring": "Check if file downloaded"
  },
  {
    "code": "def llen(key, host=None, port=None, db=None, password=None):\n    server = _connect(host, port, db, password)\n    return server.llen(key)",
    "docstring": "Get the length of a list in Redis\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' redis.llen foo_list"
  },
  {
    "code": "def write_template_to_file(conf, template_body):\n    template_file_name = _get_stack_name(conf) + '-generated-cf-template.json'\n    with open(template_file_name, 'w') as opened_file:\n        opened_file.write(template_body)\n    print('wrote cf-template for %s to disk: %s' % (\n        get_env(), template_file_name))\n    return template_file_name",
    "docstring": "Writes the template to disk"
  },
  {
    "code": "def targets_by_artifact_set(self, targets):\n    sets_to_targets = defaultdict(list)\n    for target in targets:\n      sets_to_targets[self.for_target(target)].append(target)\n    return dict(sets_to_targets)",
    "docstring": "Partitions the input targets by the sets of pinned artifacts they are managed by.\n\n    :param collections.Iterable targets: the input targets (typically just JarLibrary targets).\n    :return: a mapping of PinnedJarArtifactSet -> list of targets.\n    :rtype: dict"
  },
  {
    "code": "def record_prefix(required_type, factory):\n    field = record_type(required_type)\n    field += factory.get_rule('transaction_sequence_n')\n    field += factory.get_rule('record_sequence_n')\n    return field",
    "docstring": "Creates a record prefix for the specified record type.\n\n    :param required_type: the type of the record using this prefix\n    :param factory: field factory\n    :return: the record prefix"
  },
  {
    "code": "def extraterrestrial_direct_normal_radiation(self, value=9999.0):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError(\n                    'value {} need to be of type float '\n                    'for field `extraterrestrial_direct_normal_radiation`'.format(value))\n            if value < 0.0:\n                raise ValueError(\n                    'value need to be greater or equal 0.0 '\n                    'for field `extraterrestrial_direct_normal_radiation`')\n        self._extraterrestrial_direct_normal_radiation = value",
    "docstring": "Corresponds to IDD Field `extraterrestrial_direct_normal_radiation`\n\n        Args:\n            value (float): value for IDD Field `extraterrestrial_direct_normal_radiation`\n                Unit: Wh/m2\n                value >= 0.0\n                Missing value: 9999.0\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def update_context(self, context, app=None):\n        if (app is None and self._context is _CONTEXT_MISSING\n                and not in_app_context()):\n            raise RuntimeError(\"Attempted to update component context without\"\n                               \" a bound app context or eager app set! Please\"\n                               \" pass the related app you want to update the\"\n                               \" context for!\")\n        if self._context is not _CONTEXT_MISSING:\n            self._context = ImmutableDict(context)\n        else:\n            key = self._get_context_name(app=app)\n            setattr(_CONTEXT_LOCALS, key, ImmutableDict(context))",
    "docstring": "Replace the component's context with a new one.\n\n        Args:\n            context (dict): The new context to set this component's context to.\n\n        Keyword Args:\n            app (flask.Flask, optional): The app to update this context for. If\n                not provided, the result of ``Component.app`` will be used."
  },
  {
    "code": "def create(self, client=None, project=None, location=None):\n        if self.user_project is not None:\n            raise ValueError(\"Cannot create bucket with 'user_project' set.\")\n        client = self._require_client(client)\n        if project is None:\n            project = client.project\n        if project is None:\n            raise ValueError(\"Client project not set:  pass an explicit project.\")\n        query_params = {\"project\": project}\n        properties = {key: self._properties[key] for key in self._changes}\n        properties[\"name\"] = self.name\n        if location is not None:\n            properties[\"location\"] = location\n        api_response = client._connection.api_request(\n            method=\"POST\",\n            path=\"/b\",\n            query_params=query_params,\n            data=properties,\n            _target_object=self,\n        )\n        self._set_properties(api_response)",
    "docstring": "Creates current bucket.\n\n        If the bucket already exists, will raise\n        :class:`google.cloud.exceptions.Conflict`.\n\n        This implements \"storage.buckets.insert\".\n\n        If :attr:`user_project` is set, bills the API request to that project.\n\n        :type client: :class:`~google.cloud.storage.client.Client` or\n                      ``NoneType``\n        :param client: Optional. The client to use. If not passed, falls back\n                       to the ``client`` stored on the current bucket.\n\n        :type project: str\n        :param project: Optional. The project under which the bucket is to\n                        be created. If not passed, uses the project set on\n                        the client.\n        :raises ValueError: if :attr:`user_project` is set.\n        :raises ValueError: if ``project`` is None and client's\n                            :attr:`project` is also None.\n\n        :type location: str\n        :param location: Optional. The location of the bucket. If not passed,\n                         the default location, US, will be used. See\n                         https://cloud.google.com/storage/docs/bucket-locations"
  },
  {
    "code": "def rlmb_grid(rhp):\n  rhp.set_categorical(\"loop.game\", [\"breakout\", \"pong\", \"freeway\"])\n  base = 100000\n  medium = base // 2\n  small = medium // 2\n  rhp.set_discrete(\"loop.num_real_env_frames\", [base, medium, small])\n  rhp.set_discrete(\"model.moe_loss_coef\", list(range(5)))",
    "docstring": "Grid over games and frames, and 5 runs each for variance."
  },
  {
    "code": "def properties(self):\n        props = {}\n        for line in self.adb_shell(['getprop']).splitlines():\n            m = _PROP_PATTERN.match(line)\n            if m:\n                props[m.group('key')] = m.group('value')\n        return props",
    "docstring": "Android Properties, extracted from `adb shell getprop`\n\n        Returns:\n            dict of props, for\n            example:\n\n                {'ro.bluetooth.dun': 'true'}"
  },
  {
    "code": "def print_summaries(self):\n        if hasattr(self, \"fit_summary\") and hasattr(self, \"summary\"):\n            print(\"\\n\")\n            print(self.fit_summary)\n            print(\"=\" * 30)\n            print(self.summary)\n        else:\n            msg = \"This {} object has not yet been estimated so there \"\n            msg_2 = \"are no estimation summaries to print.\"\n            raise NotImplementedError(msg.format(self.model_type) + msg_2)\n        return None",
    "docstring": "Returns None. Will print the measures of fit and the estimation results\n        for the  model."
  },
  {
    "code": "def cat_acc(y, z):\n    weights = _cat_sample_weights(y)\n    _acc = K.cast(K.equal(K.argmax(y, axis=-1),\n                          K.argmax(z, axis=-1)),\n                  K.floatx())\n    _acc = K.sum(_acc * weights) / K.sum(weights)\n    return _acc",
    "docstring": "Classification accuracy for multi-categorical case"
  },
  {
    "code": "def srt_formatter(subtitles, padding_before=0, padding_after=0):\n    sub_rip_file = pysrt.SubRipFile()\n    for i, ((start, end), text) in enumerate(subtitles, start=1):\n        item = pysrt.SubRipItem()\n        item.index = i\n        item.text = six.text_type(text)\n        item.start.seconds = max(0, start - padding_before)\n        item.end.seconds = end + padding_after\n        sub_rip_file.append(item)\n    return '\\n'.join(six.text_type(item) for item in sub_rip_file)",
    "docstring": "Serialize a list of subtitles according to the SRT format, with optional time padding."
  },
  {
    "code": "def cli(env, account_id, origin_id):\n    manager = SoftLayer.CDNManager(env.client)\n    manager.remove_origin(account_id, origin_id)",
    "docstring": "Remove an origin pull mapping."
  },
  {
    "code": "def _imread(self, file):\n        img = skimage_io.imread(file, as_gray=self.as_gray, plugin='imageio')\n        if img is not None and len(img.shape) != 2:\n            img = skimage_io.imread(file, as_gray=self.as_gray, plugin='matplotlib')\n        return img",
    "docstring": "Proxy to skimage.io.imread with some fixes."
  },
  {
    "code": "def contrib_phone(contrib_tag):\n    phone = None\n    if raw_parser.phone(contrib_tag):\n        phone = first(raw_parser.phone(contrib_tag)).text\n    return phone",
    "docstring": "Given a contrib tag, look for an phone tag"
  },
  {
    "code": "def start(environment, opts):\n    environment.require_data()\n    if environment.fully_running():\n        print 'Already running at {0}'.format(environment.web_address())\n        return\n    reload_(environment, opts)",
    "docstring": "Create containers and start serving environment\n\nUsage:\n  datacats start [-b] [--site-url SITE_URL] [-p|--no-watch] [-s NAME]\n                 [-i] [--syslog] [--address=IP] [ENVIRONMENT [PORT]]\n  datacats start -r [-b] [--site-url SITE_URL] [-s NAME] [--syslog]\n                 [-i] [--address=IP] [ENVIRONMENT]\n\nOptions:\n  --address=IP          Address to listen on (Linux-only)\n  -b --background       Don't wait for response from web server\n  --no-watch            Do not automatically reload templates and .py files on change\n  -i --interactive      Calls out to docker via the command line, allowing\n                        for interactivity with the web image.\n  -p --production       Start with apache and debug=false\n  -s --site=NAME        Specify a site to start [default: primary]\n  --syslog              Log to the syslog\n  --site-url SITE_URL   The site_url to use in API responses. Defaults to old setting or\n                        will attempt to determine it. (e.g. http://example.org:{port}/)\n\nENVIRONMENT may be an environment name or a path to an environment directory.\nDefault: '.'"
  },
  {
    "code": "def upgrade_tools(name, reboot=False, call=None):\n    if call != 'action':\n        raise SaltCloudSystemExit(\n            'The upgrade_tools action must be called with '\n            '-a or --action.'\n        )\n    vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name)\n    return _upg_tools_helper(vm_ref, reboot)",
    "docstring": "To upgrade VMware Tools on a specified virtual machine.\n\n    .. note::\n\n        If the virtual machine is running Windows OS, use ``reboot=True``\n        to reboot the virtual machine after VMware tools upgrade. Default\n        is ``reboot=False``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -a upgrade_tools vmname\n        salt-cloud -a upgrade_tools vmname reboot=True"
  },
  {
    "code": "def newBuild(self, requests):\n        b = self.buildClass(requests)\n        b.useProgress = self.useProgress\n        b.workdir = self.workdir\n        b.setStepFactories(self.steps)\n        return b",
    "docstring": "Create a new Build instance.\n\n        @param requests: a list of buildrequest dictionaries describing what is\n        to be built"
  },
  {
    "code": "def search(self, search_phrase, limit=None):\n        from ambry.identity import ObjectNumber\n        from ambry.orm.exc import NotFoundError\n        from ambry.library.search_backends.base import SearchTermParser\n        results = []\n        stp = SearchTermParser()\n        parsed_terms = stp.parse(search_phrase)\n        for r in self.search_datasets(search_phrase, limit):\n            vid = r.vid or ObjectNumber.parse(next(iter(r.partitions))).as_dataset\n            r.vid = vid\n            try:\n                r.bundle = self.library.bundle(r.vid)\n                if 'source' not in parsed_terms or parsed_terms['source'] in r.bundle.dataset.source:\n                    results.append(r)\n            except NotFoundError:\n                pass\n        return sorted(results, key=lambda r : r.score, reverse=True)",
    "docstring": "Search for datasets, and expand to database records"
  },
  {
    "code": "def looks_like_a_filename(kernel_source):\n    logging.debug('looks_like_a_filename called')\n    result = False\n    if isinstance(kernel_source, str):\n        result = True\n        if len(kernel_source) > 250:\n            result = False\n        for c in \"();{}\\\\\":\n            if c in kernel_source:\n                result = False\n        for s in [\"__global__ \", \"__kernel \", \"void \", \"float \"]:\n            if s in kernel_source:\n                result = False\n        result = result and any([s in kernel_source for s in (\".c\", \".opencl\", \".F\")])\n    logging.debug('kernel_source is a filename: %s' % str(result))\n    return result",
    "docstring": "attempt to detect whether source code or a filename was passed"
  },
  {
    "code": "def is_valid(file_path):\n    from os import path, stat\n    can_open = False\n    try:\n        with open(file_path) as fp:\n            can_open = True\n    except IOError:\n        return False\n    is_file = path.isfile(file_path)\n    return path.exists(file_path) and is_file and stat(file_path).st_size > 0",
    "docstring": "Check to see if a file exists or is empty."
  },
  {
    "code": "def factory(obj, field, source_text, lang, context=\"\"):\n\t\tobj_classname = obj.__class__.__name__\n\t\tobj_module = obj.__module__\n\t\tsource_md5 = checksum(source_text)\n\t\ttranslation = \"\"\n\t\tfield_lang = trans_attr(field,lang)\n\t\tif hasattr(obj,field_lang) and getattr(obj,field_lang)!=\"\":\n\t\t\ttranslation = getattr(obj,field_lang)\n\t\tis_fuzzy = True\n\t\tis_fuzzy_lang = trans_is_fuzzy_attr(field,lang)\n\t\tif hasattr(obj,is_fuzzy_lang):\n\t\t\tis_fuzzy = getattr(obj,is_fuzzy_lang)\n\t\ttrans = FieldTranslation(module=obj_module, model=obj_classname, object_id=obj.id,\n\t\t                         field=field, lang=lang, source_text=source_text, source_md5=source_md5,\n\t\t                         translation=translation, is_fuzzy=is_fuzzy, context=context)\n\t\treturn trans",
    "docstring": "Static method that constructs a translation based on its contents."
  },
  {
    "code": "def setup_shot_signals(self, ):\n        log.debug(\"Setting up shot page signals.\")\n        self.shot_prj_view_pb.clicked.connect(self.shot_view_prj)\n        self.shot_seq_view_pb.clicked.connect(self.shot_view_seq)\n        self.shot_asset_view_pb.clicked.connect(self.shot_view_asset)\n        self.shot_asset_create_pb.clicked.connect(self.shot_create_asset)\n        self.shot_asset_add_pb.clicked.connect(self.shot_add_asset)\n        self.shot_asset_remove_pb.clicked.connect(self.shot_remove_asset)\n        self.shot_task_view_pb.clicked.connect(self.shot_view_task)\n        self.shot_task_create_pb.clicked.connect(self.shot_create_task)\n        self.shot_start_sb.valueChanged.connect(self.shot_save)\n        self.shot_end_sb.valueChanged.connect(self.shot_save)\n        self.shot_handle_sb.valueChanged.connect(self.shot_save)\n        self.shot_desc_pte.textChanged.connect(self.shot_save)",
    "docstring": "Setup the signals for the shot page\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def remove_available_work_units(self, work_spec_name, work_unit_names):\n        return self._remove_some_work_units(\n            work_spec_name, work_unit_names, priority_max=time.time())",
    "docstring": "Remove some work units in the available queue.\n\n        If `work_unit_names` is :const:`None` (which must be passed\n        explicitly), all available work units in `work_spec_name` are\n        removed; otherwise only the specific named work units will be.\n\n        :param str work_spec_name: name of the work spec\n        :param list work_unit_names: names of the work units, or\n          :const:`None` for all in `work_spec_name`\n        :return: number of work units removed"
  },
  {
    "code": "def check_election_status(self, config):\n        try:\n            record = self._get_record(\n                config.get(\"record_kind\", \"\"), config.get(\"record_name\", \"\"), config.get(\"record_namespace\", \"\")\n            )\n            self._report_status(config, record)\n        except Exception as e:\n            self.warning(\"Cannot retrieve leader election record {}: {}\".format(config.get(\"record_name\", \"\"), e))",
    "docstring": "Retrieves the leader-election annotation from a given object, and\n        submits metrics and a service check.\n\n        An integration warning is sent if the object is not retrievable,\n        or no record is found. Monitors on the service-check should have\n        no-data alerts enabled to account for this.\n\n        The config objet requires the following fields:\n            namespace (prefix for the metrics and check)\n            record_kind (endpoints or configmap)\n            record_name\n            record_namespace\n            tags (optional)\n\n        It reads the following agent configuration:\n            kubernetes_kubeconfig_path: defaut is to use in-cluster config"
  },
  {
    "code": "def _stringify_val(val):\n        if isinstance(val, list):\n            return \" \".join([str(i) for i in val])\n        else:\n            return str(val)",
    "docstring": "Convert the given value to string."
  },
  {
    "code": "def set_sampler_info(self, sample):\n        if sample.getSampler() and sample.getDateSampled():\n            return True\n        sampler = self.get_form_value(\"Sampler\", sample, sample.getSampler())\n        sampled = self.get_form_value(\"getDateSampled\", sample,\n                                      sample.getDateSampled())\n        if not all([sampler, sampled]):\n            return False\n        sample.setSampler(sampler)\n        sample.setDateSampled(DateTime(sampled))\n        return True",
    "docstring": "Updates the Sampler and the Sample Date with the values provided in\n        the request. If neither Sampler nor SampleDate are present in the\n        request, returns False"
  },
  {
    "code": "def save(self):\n        for exp, d in dict(self).items():\n            if isinstance(d, dict):\n                project_path = self.projects[d['project']]['root']\n                d = self.rel_paths(copy.deepcopy(d))\n                fname = osp.join(project_path, '.project', exp + '.yml')\n                if not osp.exists(osp.dirname(fname)):\n                    os.makedirs(osp.dirname(fname))\n                safe_dump(d, fname, default_flow_style=False)\n        exp_file = self.exp_file\n        lock = fasteners.InterProcessLock(exp_file + '.lck')\n        lock.acquire()\n        safe_dump(OrderedDict((exp, val if isinstance(val, Archive) else None)\n                              for exp, val in self.items()),\n                  exp_file, default_flow_style=False)\n        lock.release()",
    "docstring": "Save the experiment configuration\n\n        This method stores the configuration of each of the experiments in a\n        file ``'<project-dir>/.project/<experiment>.yml'``, where\n        ``'<project-dir>'`` corresponds to the project directory of the\n        specific ``'<experiment>'``. Furthermore it dumps all experiments to\n        the :attr:`exp_file` configuration file."
  },
  {
    "code": "def update_connected(self, status):\n        self._client['connected'] = status\n        _LOGGER.info('updated connected status to %s on %s', status, self.friendly_name)\n        self.callback()",
    "docstring": "Update connected."
  },
  {
    "code": "def num_examples(self):\n        if self.is_list:\n            return len(self.list_or_slice)\n        else:\n            start, stop, step = self.slice_to_numerical_args(\n                self.list_or_slice, self.original_num_examples)\n            return stop - start",
    "docstring": "The number of examples this subset spans."
  },
  {
    "code": "def change_password(self, usrname, oldpwd, newpwd, callback=None):\n        params = {'usrName': usrname,\n                  'oldPwd' : oldpwd,\n                  'newPwd' : newpwd,\n                 }\n        return self.execute_command('changePassword',\n                                    params, callback=callback)",
    "docstring": "Change password."
  },
  {
    "code": "def from_dict(cls, entries, **kwargs):\n        from dask.base import tokenize\n        cat = cls(**kwargs)\n        cat._entries = entries\n        cat._tok = tokenize(kwargs, entries)\n        return cat",
    "docstring": "Create Catalog from the given set of entries\n\n        Parameters\n        ----------\n        entries : dict-like\n            A mapping of name:entry which supports dict-like functionality,\n            e.g., is derived from ``collections.abc.Mapping``.\n        kwargs : passed on the constructor\n            Things like metadata, name; see ``__init__``.\n\n        Returns\n        -------\n        Catalog instance"
  },
  {
    "code": "def setActivities(self, *args, **kwargs):\n        def activityDate(activity):\n            try:\n                return activity['activity']['timestamp']\n            except KeyError as kerr:\n                return None\n        try:\n            activities = self.mambuactivitiesclass(groupId=self['encodedKey'], *args, **kwargs)\n        except AttributeError as ae:\n            from .mambuactivity import MambuActivities\n            self.mambuactivitiesclass = MambuActivities\n            activities = self.mambuactivitiesclass(groupId=self['encodedKey'], *args, **kwargs)\n        activities.attrs = sorted(activities.attrs, key=activityDate)\n        self['activities'] = activities\n        return 1",
    "docstring": "Adds the activities for this group to a 'activities' field.\n\n        Activities are MambuActivity objects.\n\n        Activities get sorted by activity timestamp.\n\n        Returns the number of requests done to Mambu."
  },
  {
    "code": "def display_replica_imbalance(cluster_topologies):\n    assert cluster_topologies\n    rg_ids = list(next(six.itervalues(cluster_topologies)).rgs.keys())\n    assert all(\n        set(rg_ids) == set(cluster_topology.rgs.keys())\n        for cluster_topology in six.itervalues(cluster_topologies)\n    )\n    rg_imbalances = [\n        stats.get_replication_group_imbalance_stats(\n            list(cluster_topology.rgs.values()),\n            list(cluster_topology.partitions.values()),\n        )\n        for cluster_topology in six.itervalues(cluster_topologies)\n    ]\n    _display_table_title_multicolumn(\n        'Extra Replica Count',\n        'Replication Group',\n        rg_ids,\n        list(cluster_topologies.keys()),\n        [\n            [erc[rg_id] for rg_id in rg_ids]\n            for _, erc in rg_imbalances\n        ],\n    )\n    for name, imbalance in zip(\n            six.iterkeys(cluster_topologies),\n            (imbalance for imbalance, _ in rg_imbalances)\n    ):\n        print(\n            '\\n'\n            '{name}'\n            'Total extra replica count: {imbalance}'\n            .format(\n                name='' if len(cluster_topologies) == 1 else name + '\\n',\n                imbalance=imbalance,\n            )\n        )",
    "docstring": "Display replica replication-group distribution imbalance statistics.\n\n    :param cluster_topologies: A dictionary mapping a string name to a\n        ClusterTopology object."
  },
  {
    "code": "def set_and_get(self, new_value):\n        return self._encode_invoke(atomic_reference_set_and_get_codec,\n                                   new_value=self._to_data(new_value))",
    "docstring": "Sets and gets the value.\n\n        :param new_value: (object), the new value.\n        :return: (object), the new value."
  },
  {
    "code": "def ping(self):\n        msg = StandardSend(self._address, COMMAND_PING_0X0F_0X00)\n        self._send_msg(msg)",
    "docstring": "Ping a device."
  },
  {
    "code": "def read_d1_letter(fin_txt):\n    go2letter = {}\n    re_goid = re.compile(r\"(GO:\\d{7})\")\n    with open(fin_txt) as ifstrm:\n        for line in ifstrm:\n            mtch = re_goid.search(line)\n            if mtch and line[:1] != ' ':\n                go2letter[mtch.group(1)] = line[:1]\n    return go2letter",
    "docstring": "Reads letter aliases from a text file created by GoDepth1LettersWr."
  },
  {
    "code": "def get_operation_output_names(self, operation_name):\n    for output_tensor in self._name_to_operation(operation_name).outputs:\n      yield output_tensor.name",
    "docstring": "Generates the names of all output tensors of an operation.\n\n    Args:\n      operation_name: a string, the name of an operation in the graph.\n\n    Yields:\n      a string, the name of an output tensor."
  },
  {
    "code": "def lp7(self, reaction_subset):\n        if self._zl is None:\n            self._add_maximization_vars()\n        positive = set(reaction_subset) - self._flipped\n        negative = set(reaction_subset) & self._flipped\n        v = self._v.set(positive)\n        zl = self._zl.set(positive)\n        cs = self._prob.add_linear_constraints(v >= zl)\n        self._temp_constr.extend(cs)\n        v = self._v.set(negative)\n        zl = self._zl.set(negative)\n        cs = self._prob.add_linear_constraints(v <= -zl)\n        self._temp_constr.extend(cs)\n        self._prob.set_objective(self._zl.sum(reaction_subset))\n        self._solve()",
    "docstring": "Approximately maximize the number of reaction with flux.\n\n        This is similar to FBA but approximately maximizing the number of\n        reactions in subset with flux > epsilon, instead of just maximizing the\n        flux of one particular reaction. LP7 prefers \"flux splitting\" over\n        \"flux concentrating\"."
  },
  {
    "code": "def read(self, length=-1):\n        if 0 <= length < len(self):\n            newpos = self.pos + length\n            data = self.buf[self.pos:newpos]\n            self.pos = newpos\n            self.__discard()\n            return data\n        data = self.buf[self.pos:]\n        self.clear()\n        return data",
    "docstring": "Reads from the FIFO.\n\n        Reads as much data as possible from the FIFO up to the specified\n        length. If the length argument is negative or ommited all data\n        currently available in the FIFO will be read. If there is no data\n        available in the FIFO an empty string is returned.\n\n        Args:\n            length: The amount of data to read from the FIFO. Defaults to -1."
  },
  {
    "code": "def refresh_instruments(self):\n        def list_access_nested_dict(dict, somelist):\n            return reduce(operator.getitem, somelist, dict)\n        def update(item):\n            if item.isExpanded():\n                for index in range(item.childCount()):\n                    child = item.child(index)\n                    if child.childCount() == 0:\n                        instrument, path_to_instrument = child.get_instrument()\n                        path_to_instrument.reverse()\n                        try:\n                            value = instrument.read_probes(path_to_instrument[-1])\n                        except AssertionError:\n                            value = list_access_nested_dict(instrument.settings, path_to_instrument)\n                        child.value = value\n                    else:\n                        update(child)\n        self.tree_settings.blockSignals(True)\n        for index in range(self.tree_settings.topLevelItemCount()):\n            instrument = self.tree_settings.topLevelItem(index)\n            update(instrument)\n        self.tree_settings.blockSignals(False)",
    "docstring": "if self.tree_settings has been expanded, ask instruments for their actual values"
  },
  {
    "code": "def fetch(self, plan_id, data={}, **kwargs):\n        return super(Plan, self).fetch(plan_id, data, **kwargs)",
    "docstring": "Fetch Plan for given Id\n\n        Args:\n            plan_id : Id for which Plan object has to be retrieved\n\n        Returns:\n            Plan dict for given subscription Id"
  },
  {
    "code": "def add_scheduling_block(config):\n    try:\n        DB.add_sbi(config)\n    except jsonschema.ValidationError as error:\n        error_dict = error.__dict__\n        for key in error_dict:\n            error_dict[key] = error_dict[key].__str__()\n        error_response = dict(message=\"Failed to add scheduling block\",\n                              reason=\"JSON validation error\",\n                              details=error_dict)\n        return error_response, HTTPStatus.BAD_REQUEST\n    response = dict(config=config,\n                    message='Successfully registered scheduling block '\n                            'instance with ID: {}'.format(config['id']))\n    response['links'] = {\n        'self': '{}scheduling-block/{}'.format(request.url_root,\n                                               config['id']),\n        'list': '{}'.format(request.url),\n        'home': '{}'.format(request.url_root)\n    }\n    return response, HTTPStatus.ACCEPTED",
    "docstring": "Adds a scheduling block to the database, returning a response object"
  },
  {
    "code": "def filter_data(self, pattern=''):\r\n        filtered_profiles = {}\r\n        with open(self.abspath) as fobj:\r\n            for idx, line in enumerate(fobj):\r\n                if 'TIME SERIES' in line:\r\n                    break\r\n                if pattern in line and (idx-self._attributes['CATALOG']-1) > 0:\r\n                    filtered_profiles[idx-self._attributes['CATALOG']-1] = line\r\n        return filtered_profiles",
    "docstring": "Filter available varaibles"
  },
  {
    "code": "def multizone_member_removed(self, member_uuid):\n        casts = self._casts\n        if member_uuid not in casts:\n            casts[member_uuid] = {'listeners': [], 'groups': set()}\n        casts[member_uuid]['groups'].discard(self._group_uuid)\n        for listener in list(casts[member_uuid]['listeners']):\n            listener.removed_from_multizone(self._group_uuid)",
    "docstring": "Handle removed audio group member."
  },
  {
    "code": "def display(self):\n        for pkg in self.binary:\n            name = GetFromInstalled(pkg).name()\n            ver = GetFromInstalled(pkg).version()\n            find = find_package(\"{0}{1}{2}\".format(name, ver, self.meta.sp),\n                                self.meta.pkg_path)\n            if find:\n                package = Utils().read_file(\n                    self.meta.pkg_path + \"\".join(find))\n                print(package)\n            else:\n                message = \"Can't dislpay\"\n                if len(self.binary) > 1:\n                    bol = eol = \"\"\n                else:\n                    bol = eol = \"\\n\"\n                self.msg.pkg_not_found(bol, pkg, message, eol)\n                raise SystemExit(1)",
    "docstring": "Print the Slackware packages contents"
  },
  {
    "code": "def to_strings(self):\n        result = []\n        if not self.expansions:\n            result.append(self.name)\n        else:\n            for expansion in self.expansions:\n                result.extend('{}.{}'.format(self.name, es) for es in expansion.to_strings())\n        return result",
    "docstring": "Convert the expansion node to a list of expansion strings.\n\n        :return: a list of expansion strings that represent the leaf nodes of the expansion tree.\n        :rtype: list[union[str, unicode]]"
  },
  {
    "code": "def from_dataframe(df, name='df', client=None):\n    if client is None:\n        return connect({name: df}).table(name)\n    client.dictionary[name] = df\n    return client.table(name)",
    "docstring": "convenience function to construct an ibis table\n    from a DataFrame\n\n    EXPERIMENTAL API\n\n    Parameters\n    ----------\n    df : DataFrame\n    name : str, default 'df'\n    client : Client, default new PandasClient\n        client dictionary will be mutated with the\n        name of the DataFrame\n\n    Returns\n    -------\n    Table"
  },
  {
    "code": "def get_doc_from_docid(self, docid, doc_type_name=None, inst=True):\n        assert(docid is not None)\n        if docid in self._docs_by_id:\n            return self._docs_by_id[docid]\n        if not inst:\n            return None\n        doc = self.__inst_doc(docid, doc_type_name)\n        if doc is None:\n            return None\n        self._docs_by_id[docid] = doc\n        return doc",
    "docstring": "Try to find a document based on its document id. if inst=True, if it\n        hasn't been instantiated yet, it will be."
  },
  {
    "code": "def send_command(self, cmd):\n        logger.debug('Sending {0} command.'.format(cmd))\n        self.comm_chan.sendall(cmd + '\\n')",
    "docstring": "Send a command to the remote SSH server.\n\n        :param cmd: The command to send"
  },
  {
    "code": "def display_notes(self, notes):\n        hassyntastic = bool(int(self._vim.eval('exists(\":SyntasticCheck\")')))\n        if hassyntastic:\n            self.__display_notes_with_syntastic(notes)\n        else:\n            self.__display_notes(notes)\n        self._vim.command('redraw!')",
    "docstring": "Renders \"notes\" reported by ENSIME, such as typecheck errors."
  },
  {
    "code": "def generators(self):\n        if not self._generators:\n            generators = list(self.graph.nodes_by_attribute('generator'))\n            generators.extend(list(self.graph.nodes_by_attribute(\n                'generator_aggr')))\n            return generators\n        else:\n            return self._generators",
    "docstring": "Connected Generators within the grid\n\n        Returns\n        -------\n        list\n            List of Generator Objects"
  },
  {
    "code": "def get(self):\n        attachment = {}\n        if self.file_content is not None:\n            attachment[\"content\"] = self.file_content.get()\n        if self.file_type is not None:\n            attachment[\"type\"] = self.file_type.get()\n        if self.file_name is not None:\n            attachment[\"filename\"] = self.file_name.get()\n        if self.disposition is not None:\n            attachment[\"disposition\"] = self.disposition.get()\n        if self.content_id is not None:\n            attachment[\"content_id\"] = self.content_id.get()\n        return attachment",
    "docstring": "Get a JSON-ready representation of this Attachment.\n\n        :returns: This Attachment, ready for use in a request body.\n        :rtype: dict"
  },
  {
    "code": "def get_threshold(self):\n        if self.threshold.startswith('+'):\n            if self.threshold[1:].isdigit():\n                self._threshold = int(self.threshold[1:])\n                self._upper = True\n        elif self.threshold.startswith('-'):\n            if self.threshold[1:].isdigit():\n                self._threshold = int(self.threshold[1:])\n                self._upper = False\n        else:\n            if self.threshold.isdigit():\n                self._threshold = int(self.threshold)\n                self._upper = True\n        if not hasattr(self, '_threshold'):\n            raise ValueError('Invalid threshold')",
    "docstring": "Get and validate raw RMS value from threshold"
  },
  {
    "code": "def find_by_name(collection, name, exact=True):\n    params = {'filter[]': ['name==%s' % name]}\n    found = collection.index(params=params)\n    if not exact and len(found) > 0:\n        return found\n    for f in found:\n        if f.soul['name'] == name:\n            return f",
    "docstring": "Searches collection by resource name.\n\n    :param rightscale.ResourceCollection collection: The collection in which to\n        look for :attr:`name`.\n\n    :param str name: The name to look for in collection.\n\n    :param bool exact: A RightScale ``index`` search with a :attr:`name` filter\n        can return multiple results because it does a substring match on\n        resource names.  So any resource that contains the specified name will\n        be returned.  The :attr:`exact` flag controls whether to attempt to\n        find an exact match for the given name.  If :attr:`exact` is ``False``,\n        this will return a list of all the matches.  The default behaviour is\n        to perform an exact match and return a single result.\n\n    Returns ``None`` if no resources are found with a matching name."
  },
  {
    "code": "def to_primitive(self, load_rels=None, sparse_fields=None, *args,\n                     **kwargs):\n        if load_rels:\n            for rel in load_rels:\n                getattr(self, rel).load()\n        data = super(Model, self).to_primitive(*args, **kwargs)\n        if sparse_fields:\n            for key in data.keys():\n                if key not in sparse_fields:\n                    del data[key]\n        return data",
    "docstring": "Override the schematics native to_primitive method\n\n        :param loads_rels:\n            List of field names that are relationships that should\n            be loaded for the serialization process. This needs\n            to be run before the native schematics to_primitive is\n            run so the proper data is serialized.\n\n        :param sparse_fields:\n            List of field names that can be provided which limits\n            the serialization to ONLY those field names. A whitelist\n            effectively."
  },
  {
    "code": "def create_comment_browser(self, layout):\n        brws = CommentBrowser(1, headers=['Comments:'])\n        layout.insertWidget(1, brws)\n        return brws",
    "docstring": "Create a comment browser and insert it into the given layout\n\n        :param layout: the layout to insert the browser into\n        :type layout: QLayout\n        :returns: the created browser\n        :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser`\n        :raises: None"
  },
  {
    "code": "def getModifiers(chart):\n    modifiers = []\n    asc = chart.getAngle(const.ASC)\n    ascRulerID = essential.ruler(asc.sign)\n    ascRuler = chart.getObject(ascRulerID)\n    moon = chart.getObject(const.MOON)\n    factors = [\n        [MOD_ASC, asc],\n        [MOD_ASC_RULER, ascRuler],\n        [MOD_MOON, moon]\n    ]\n    mars = chart.getObject(const.MARS)\n    saturn = chart.getObject(const.SATURN)\n    sun = chart.getObject(const.SUN)\n    affect = [\n        [mars, [0, 90, 180]],\n        [saturn, [0, 90, 180]],\n        [sun, [0]]     \n    ]\n    for affectingObj, affectingAsps in affect:\n        for factor, affectedObj in factors:\n            modf = modifierFactor(chart, \n                                  factor, \n                                  affectedObj, \n                                  affectingObj, \n                                  affectingAsps)\n            if modf:\n                modifiers.append(modf)\n    return modifiers",
    "docstring": "Returns the factors of the temperament modifiers."
  },
  {
    "code": "def update_invoice(self, invoice_id, invoice_dict):\n        return self._create_put_request(resource=INVOICES, billomat_id=invoice_id, send_data=invoice_dict)",
    "docstring": "Updates an invoice\n\n        :param invoice_id: the invoice id\n        :param invoice_dict: dict\n        :return: dict"
  },
  {
    "code": "def _get_cached_file_name(bucket_name, saltenv, path):\n    file_path = os.path.join(_get_cache_dir(), saltenv, bucket_name, path)\n    if not os.path.exists(os.path.dirname(file_path)):\n        os.makedirs(os.path.dirname(file_path))\n    return file_path",
    "docstring": "Return the cached file name for a bucket path file"
  },
  {
    "code": "def build_evenly_discretised_mfd(mfd):\n    occur_rates = Node(\"occurRates\", text=mfd.occurrence_rates)\n    return Node(\"incrementalMFD\",\n                {\"binWidth\": mfd.bin_width, \"minMag\": mfd.min_mag},\n                nodes=[occur_rates])",
    "docstring": "Returns the evenly discretized MFD as a Node\n\n    :param mfd:\n        MFD as instance of :class:\n        `openquake.hazardlib.mfd.evenly_discretized.EvenlyDiscretizedMFD`\n    :returns:\n        Instance of :class:`openquake.baselib.node.Node`"
  },
  {
    "code": "def create_post(self, post_type, post_folders, post_subject, post_content, is_announcement=0, bypass_email=0, anonymous=False):\n        params = {\n            \"anonymous\": \"yes\" if anonymous else \"no\",\n            \"subject\": post_subject,\n            \"content\": post_content,\n            \"folders\": post_folders,\n            \"type\": post_type,\n            \"config\": {\n                \"bypass_email\": bypass_email,\n                \"is_announcement\": is_announcement\n            }\n        }\n        return self._rpc.content_create(params)",
    "docstring": "Create a post\n\n        It seems like if the post has `<p>` tags, then it's treated as HTML,\n        but is treated as text otherwise. You'll want to provide `content`\n        accordingly.\n\n        :type post_type: str\n        :param post_type: 'note', 'question'\n        :type post_folders: str\n        :param post_folders: Folder to put post into\n        :type post_subject: str\n        :param post_subject: Subject string\n        :type post_content: str\n        :param post_content: Content string\n        :type is_announcement: bool\n        :param is_announcement:\n        :type bypass_email: bool\n        :param bypass_email:\n        :type anonymous: bool\n        :param anonymous:\n        :rtype: dict\n        :returns: Dictionary with information about the created post."
  },
  {
    "code": "def color_text_boxes(ax, labels, colors, color_arrow=True):\n    assert len(labels) == len(colors), \\\n        \"Equal no. of colors and lables must be given\"\n    boxes = ax.findobj(mpl.text.Annotation)\n    box_labels = lineid_plot.unique_labels(labels)\n    for box in boxes:\n        l = box.get_label()\n        try:\n            loc = box_labels.index(l)\n        except ValueError:\n            continue\n        box.set_color(colors[loc])\n        if color_arrow:\n            box.arrow_patch.set_color(colors[loc])\n    ax.figure.canvas.draw()",
    "docstring": "Color text boxes.\n\n    Instead of this function, one can pass annotate_kwargs and plot_kwargs to\n    plot_line_ids function."
  },
  {
    "code": "def solvate_bilayer(self):\n        solvent_number_density = self.solvent.n_particles / np.prod(self.solvent.periodicity)\n        lengths = self.lipid_box.lengths\n        water_box_z = self.solvent_per_layer / (lengths[0] * lengths[1] * solvent_number_density)\n        mins = self.lipid_box.mins\n        maxs = self.lipid_box.maxs\n        bilayer_solvent_box = mb.Box(mins=[mins[0], mins[1], maxs[2]],\n                                     maxs=[maxs[0], maxs[1], maxs[2] + 2 * water_box_z])\n        self.solvent_components.add(mb.fill_box(self.solvent, bilayer_solvent_box))",
    "docstring": "Solvate the constructed bilayer."
  },
  {
    "code": "def pass_verbosity(f):\n    def new_func(*args, **kwargs):\n        kwargs['verbosity'] = click.get_current_context().verbosity\n        return f(*args, **kwargs)\n    return update_wrapper(new_func, f)",
    "docstring": "Marks a callback as wanting to receive the verbosity as a keyword argument."
  },
  {
    "code": "def fromimportreg(cls, bundle, import_reg):\n        exc = import_reg.get_exception()\n        if exc:\n            return RemoteServiceAdminEvent(\n                RemoteServiceAdminEvent.IMPORT_ERROR,\n                bundle,\n                import_reg.get_import_container_id(),\n                import_reg.get_remoteservice_id(),\n                None,\n                None,\n                exc,\n                import_reg.get_description(),\n            )\n        return RemoteServiceAdminEvent(\n            RemoteServiceAdminEvent.IMPORT_REGISTRATION,\n            bundle,\n            import_reg.get_import_container_id(),\n            import_reg.get_remoteservice_id(),\n            import_reg.get_import_reference(),\n            None,\n            None,\n            import_reg.get_description(),\n        )",
    "docstring": "Creates a RemoteServiceAdminEvent object from an ImportRegistration"
  },
  {
    "code": "def _struct_get_field(expr, field_name):\n    return ops.StructField(expr, field_name).to_expr().name(field_name)",
    "docstring": "Get the `field_name` field from the ``Struct`` expression `expr`.\n\n    Parameters\n    ----------\n    field_name : str\n        The name of the field to access from the ``Struct`` typed expression\n        `expr`. Must be a Python ``str`` type; programmatic struct field\n        access is not yet supported.\n\n    Returns\n    -------\n    value_expr : ibis.expr.types.ValueExpr\n        An expression with the type of the field being accessed."
  },
  {
    "code": "def get_flattened(dct, names, path_joiner=\"_\"):\n  new_dct = dict()\n  for key, val in dct.items():\n    if key in names:\n      child = {path_joiner.join(k): v for k, v in flatten_dict(val, (key, ))}\n      new_dct.update(child)\n    else:\n      new_dct[key] = dct[key]\n  return new_dct",
    "docstring": "Flatten a child dicts, whose resulting keys are joined by path_joiner.\n\n  E.G. { \"valuation\": { \"currency\": \"USD\", \"amount\": \"100\" } } ->\n       { \"valuation_currency\": \"USD\", \"valuation_amount\": \"100\" }"
  },
  {
    "code": "def expire_file(filepath):\n    load_message.cache_clear()\n    orm.delete(pa for pa in model.PathAlias if pa.entry.file_path == filepath)\n    orm.delete(item for item in model.Entry if item.file_path == filepath)\n    orm.commit()",
    "docstring": "Expire a record for a missing file"
  },
  {
    "code": "def _merge_args_opts(args_opts_dict, **kwargs):\n    merged = []\n    if not args_opts_dict:\n        return merged\n    for arg, opt in args_opts_dict.items():\n        if not _is_sequence(opt):\n            opt = shlex.split(opt or '')\n        merged += opt\n        if not arg:\n            continue\n        if 'add_input_option' in kwargs:\n            merged.append('-i')\n        merged.append(arg)\n    return merged",
    "docstring": "Merge options with their corresponding arguments.\n\n    Iterates over the dictionary holding arguments (keys) and options (values). Merges each\n    options string with its corresponding argument.\n\n    :param dict args_opts_dict: a dictionary of arguments and options\n    :param dict kwargs: *input_option* - if specified prepends ``-i`` to input argument\n    :return: merged list of strings with arguments and their corresponding options\n    :rtype: list"
  },
  {
    "code": "def render(self):\n        if not self.validate():\n            raise ValidationError\n        self.process_request()\n        self.clean()\n        return self.response",
    "docstring": "Validate, process, clean and return the result of the call."
  },
  {
    "code": "def retry(exception_processor=generic_exception_processor, max_retries=100):\n    max_retries = int(os.getenv('WALE_RETRIES', max_retries))\n    def yield_new_function_from(f):\n        def shim(*args, **kwargs):\n            exc_processor_cxt = None\n            retries = 0\n            while True:\n                gevent.sleep(0.1)\n                try:\n                    return f(*args, **kwargs)\n                except KeyboardInterrupt:\n                    raise\n                except Exception:\n                    exception_info_tuple = None\n                    retries += 1\n                    if max_retries >= 1 and retries >= max_retries:\n                        raise\n                    try:\n                        exception_info_tuple = sys.exc_info()\n                        exc_processor_cxt = exception_processor(\n                            exception_info_tuple,\n                            exc_processor_cxt=exc_processor_cxt)\n                    finally:\n                        del exception_info_tuple\n                    duration = min(120, (2 ** retries)) / 2\n                    gevent.sleep(duration + random.randint(0, duration))\n        return functools.wraps(f)(shim)\n    return yield_new_function_from",
    "docstring": "Generic retry decorator\n\n    Tries to call the decorated function.  Should no exception be\n    raised, the value is simply returned, otherwise, call an\n    exception_processor function with the exception (type, value,\n    traceback) tuple (with the intention that it could raise the\n    exception without losing the traceback) and the exception\n    processor's optionally usable context value (exc_processor_cxt).\n\n    It's recommended to delete all references to the traceback passed\n    to the exception_processor to speed up garbage collector via the\n    'del' operator.\n\n    This context value is passed to and returned from every invocation\n    of the exception processor.  This can be used to more conveniently\n    (vs. an object with __call__ defined) implement exception\n    processors that have some state, such as the 'number of attempts'.\n    The first invocation will pass None.\n\n    :param f: A function to be retried.\n    :type f: function\n\n    :param exception_processor: A function to process raised\n                                exceptions.\n    :type exception_processor: function\n\n    :param max_retries: An integer representing the maximum\n                        number of retry attempts.\n    :type max_retries: integer"
  },
  {
    "code": "def _onGlobal(self, name, line, pos, absPosition, level):\n        for item in self.globals:\n            if item.name == name:\n                return\n        self.globals.append(Global(name, line, pos, absPosition))",
    "docstring": "Memorizes a global variable"
  },
  {
    "code": "def show_setup(self):\n        shell = os.getenv('SHELL')\n        if not shell:\n            raise SystemError(\"No $SHELL env var found\")\n        shell = os.path.basename(shell)\n        if shell not in self.script_body:\n            raise SystemError(\"Unsupported shell: %s\" % shell)\n        tplvars = {\n            \"prog\": '-'.join(self.prog.split()[:-1]),\n            \"shell\": shell,\n            \"name\": self.name\n        }\n        print(self.trim(self.script_header % tplvars))\n        print(self.trim(self.script_body[shell] % tplvars))\n        print(self.trim(self.script_footer % tplvars))",
    "docstring": "Provide a helper script for the user to setup completion."
  },
  {
    "code": "def run(items, background=None):\n    if not background: background = []\n    background_bams = []\n    paired = vcfutils.get_paired_bams([x[\"align_bam\"] for x in items], items)\n    if paired:\n        inputs = [paired.tumor_data]\n        if paired.normal_bam:\n            background = [paired.normal_data]\n            background_bams = [paired.normal_bam]\n    else:\n        assert not background\n        inputs, background = shared.find_case_control(items)\n        background_bams = [x[\"align_bam\"] for x in background]\n    orig_vcf = _run_wham(inputs, background_bams)\n    out = []\n    for data in inputs:\n        if \"sv\" not in data:\n            data[\"sv\"] = []\n        final_vcf = shared.finalize_sv(orig_vcf, data, items)\n        data[\"sv\"].append({\"variantcaller\": \"wham\", \"vrn_file\": final_vcf})\n        out.append(data)\n    return out",
    "docstring": "Detect copy number variations from batched set of samples using WHAM."
  },
  {
    "code": "def prepare_relationship(config, model_name, raml_resource):\n    if get_existing_model(model_name) is None:\n        plural_route = '/' + pluralize(model_name.lower())\n        route = '/' + model_name.lower()\n        for res in raml_resource.root.resources:\n            if res.method.upper() != 'POST':\n                continue\n            if res.path.endswith(plural_route) or res.path.endswith(route):\n                break\n        else:\n            raise ValueError('Model `{}` used in relationship is not '\n                             'defined'.format(model_name))\n        setup_data_model(config, res, model_name)",
    "docstring": "Create referenced model if it doesn't exist.\n\n    When preparing a relationship, we check to see if the model that will be\n    referenced already exists. If not, it is created so that it will be possible\n    to use it in a relationship. Thus the first usage of this model in RAML file\n    must provide its schema in POST method resource body schema.\n\n    :param model_name: Name of model which should be generated.\n    :param raml_resource: Instance of ramlfications.raml.ResourceNode for\n        which :model_name: will be defined."
  },
  {
    "code": "def get_display_types():\n    display_types = OrderedDict()\n    for namespace in get_supported_libraries():\n        display_types[namespace] = get_choices('luma.{0}.device'.format(\n            namespace))\n    return display_types",
    "docstring": "Get ordered dict containing available display types from available luma\n    sub-projects.\n\n    :rtype: collections.OrderedDict"
  },
  {
    "code": "def _check_with_retry(self):\n        address = self._server_description.address\n        retry = True\n        if self._server_description.server_type == SERVER_TYPE.Unknown:\n            retry = False\n        start = _time()\n        try:\n            return self._check_once()\n        except ReferenceError:\n            raise\n        except Exception as error:\n            error_time = _time() - start\n            if self._publish:\n                self._listeners.publish_server_heartbeat_failed(\n                    address, error_time, error)\n            self._topology.reset_pool(address)\n            default = ServerDescription(address, error=error)\n            if not retry:\n                self._avg_round_trip_time.reset()\n                return default\n            start = _time()\n            try:\n                return self._check_once()\n            except ReferenceError:\n                raise\n            except Exception as error:\n                error_time = _time() - start\n                if self._publish:\n                    self._listeners.publish_server_heartbeat_failed(\n                        address, error_time, error)\n                self._avg_round_trip_time.reset()\n                return default",
    "docstring": "Call ismaster once or twice. Reset server's pool on error.\n\n        Returns a ServerDescription."
  },
  {
    "code": "def kill_all_process(self):\n    if (runtime.get_active_config(\"cleanup_pending_process\",False)):\n      for process in self.get_processes():\n        self.terminate(process.unique_id)",
    "docstring": "Terminates all the running processes. By default it is set to false.\n    Users can set to true in config once the method to get_pid is done deterministically\n    either using pid_file or an accurate keyword"
  },
  {
    "code": "def kick_job(self, job_id):\n        if hasattr(job_id, 'job_id'):\n            job_id = job_id.job_id\n        with self._sock_ctx() as socket:\n            self._send_message('kick-job {0}'.format(job_id), socket)\n            self._receive_word(socket, b'KICKED')",
    "docstring": "Kick the given job id. The job must either be in the DELAYED or BURIED state and will be immediately moved to\n        the READY state."
  },
  {
    "code": "def profile(script, argv, profiler_factory,\n            pickle_protocol, dump_filename, mono):\n    filename, code, globals_ = script\n    sys.argv[:] = [filename] + list(argv)\n    __profile__(filename, code, globals_, profiler_factory,\n                pickle_protocol=pickle_protocol, dump_filename=dump_filename,\n                mono=mono)",
    "docstring": "Profile a Python script."
  },
  {
    "code": "def update_workspace_config(namespace, workspace, cnamespace, configname, body):\n    uri = \"workspaces/{0}/{1}/method_configs/{2}/{3}\".format(namespace,\n                                        workspace, cnamespace, configname)\n    return __post(uri, json=body)",
    "docstring": "Update method configuration in workspace.\n\n    Args:\n        namespace  (str): project to which workspace belongs\n        workspace  (str): Workspace name\n        cnamespace (str): Configuration namespace\n        configname (str): Configuration name\n        body      (json): new body (definition) of the method config\n\n    Swagger:\n        https://api.firecloud.org/#!/Method_Configurations/updateWorkspaceMethodConfig"
  },
  {
    "code": "def iterator(self):\n        for obj in (self.execute().json().get(\"items\") or []):\n            yield self.api_obj_class(self.api, obj)",
    "docstring": "Execute the API request and return an iterator over the objects. This\n        method does not use the query cache."
  },
  {
    "code": "def natural_name(self) -> str:\n        name = self.expression.strip()\n        for op in operators:\n            name = name.replace(op, operator_to_identifier[op])\n        return wt_kit.string2identifier(name)",
    "docstring": "Valid python identifier representation of the expession."
  },
  {
    "code": "def to_integer(value, ctx):\n    if isinstance(value, bool):\n        return 1 if value else 0\n    elif isinstance(value, int):\n        return value\n    elif isinstance(value, Decimal):\n        try:\n            val = int(value.to_integral_exact(ROUND_HALF_UP))\n            if isinstance(val, int):\n                return val\n        except ArithmeticError:\n            pass\n    elif isinstance(value, str):\n        try:\n            return int(value)\n        except ValueError:\n            pass\n    raise EvaluationError(\"Can't convert '%s' to an integer\" % str(value))",
    "docstring": "Tries conversion of any value to an integer"
  },
  {
    "code": "def get_identifier(identifier, module_globals, module_name):\n    if isinstance(identifier, six.string_types):\n        fn = module_globals.get(identifier)\n        if fn is None:\n            raise ValueError('Unknown {}: {}'.format(module_name, identifier))\n        return fn\n    elif callable(identifier):\n        return identifier\n    else:\n        raise ValueError('Could not interpret identifier')",
    "docstring": "Helper utility to retrieve the callable function associated with a string identifier.\n\n    Args:\n        identifier: The identifier. Could be a string or function.\n        module_globals: The global objects of the module.\n        module_name: The module name\n\n    Returns:\n        The callable associated with the identifier."
  },
  {
    "code": "def toy_rbf_1d(seed=default_seed, num_samples=500):\n    np.random.seed(seed=seed)\n    num_in = 1\n    X = np.random.uniform(low= -1.0, high=1.0, size=(num_samples, num_in))\n    X.sort(axis=0)\n    rbf = GPy.kern.RBF(num_in, variance=1., lengthscale=np.array((0.25,)))\n    white = GPy.kern.White(num_in, variance=1e-2)\n    kernel = rbf + white\n    K = kernel.K(X)\n    y = np.reshape(np.random.multivariate_normal(np.zeros(num_samples), K), (num_samples, 1))\n    return {'X':X, 'Y':y, 'info': \"Sampled \" + str(num_samples) + \" values of a function from an RBF covariance with very small noise for inputs uniformly distributed between -1 and 1.\"}",
    "docstring": "Samples values of a function from an RBF covariance with very small noise for inputs uniformly distributed between -1 and 1.\n\n    :param seed: seed to use for random sampling.\n    :type seed: int\n    :param num_samples: number of samples to sample in the function (default 500).\n    :type num_samples: int"
  },
  {
    "code": "def rm_(name, force=False, volumes=False, **kwargs):\n    kwargs = __utils__['args.clean_kwargs'](**kwargs)\n    stop_ = kwargs.pop('stop', False)\n    timeout = kwargs.pop('timeout', None)\n    auto_remove = False\n    if kwargs:\n        __utils__['args.invalid_kwargs'](kwargs)\n    if state(name) == 'running' and not (force or stop_):\n        raise CommandExecutionError(\n            'Container \\'{0}\\' is running, use force=True to forcibly '\n            'remove this container'.format(name)\n        )\n    if stop_ and not force:\n        inspect_results = inspect_container(name)\n        try:\n            auto_remove = inspect_results['HostConfig']['AutoRemove']\n        except KeyError:\n            log.error(\n                'Failed to find AutoRemove in inspect results, Docker API may '\n                'have changed. Full results: %s', inspect_results\n            )\n        stop(name, timeout=timeout)\n    pre = ps_(all=True)\n    if not auto_remove:\n        _client_wrapper('remove_container', name, v=volumes, force=force)\n    _clear_context()\n    return [x for x in pre if x not in ps_(all=True)]",
    "docstring": "Removes a container\n\n    name\n        Container name or ID\n\n    force : False\n        If ``True``, the container will be killed first before removal, as the\n        Docker API will not permit a running container to be removed. This\n        option is set to ``False`` by default to prevent accidental removal of\n        a running container.\n\n    stop : False\n        If ``True``, the container will be stopped first before removal, as the\n        Docker API will not permit a running container to be removed. This\n        option is set to ``False`` by default to prevent accidental removal of\n        a running container.\n\n        .. versionadded:: 2017.7.0\n\n    timeout\n        Optional timeout to be passed to :py:func:`docker.stop\n        <salt.modules.dockermod.stop>` if stopping the container.\n\n        .. versionadded:: 2018.3.0\n\n    volumes : False\n        Also remove volumes associated with container\n\n\n    **RETURN DATA**\n\n    A list of the IDs of containers which were removed\n\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion docker.rm mycontainer\n        salt myminion docker.rm mycontainer force=True"
  },
  {
    "code": "def _get_synonym(self, line):\n        mtch = self.attr2cmp['synonym'].match(line)\n        text, scope, typename, dbxrefs, _ = mtch.groups()\n        typename = typename.strip()\n        dbxrefs = set(dbxrefs.split(', ')) if dbxrefs else set()\n        return self.attr2cmp['synonym nt']._make([text, scope, typename, dbxrefs])",
    "docstring": "Given line, return optional attribute synonym value in a namedtuple.\n\n        Example synonym and its storage in a namedtuple:\n        synonym: \"The other white meat\" EXACT MARKETING_SLOGAN [MEAT:00324, BACONBASE:03021]\n          text:     \"The other white meat\"\n          scope:    EXACT\n          typename: MARKETING_SLOGAN\n          dbxrefs:  set([\"MEAT:00324\", \"BACONBASE:03021\"])\n\n        Example synonyms:\n          \"peptidase inhibitor complex\" EXACT [GOC:bf, GOC:pr]\n          \"regulation of postsynaptic cytosolic calcium levels\" EXACT syngo_official_label []\n          \"tocopherol 13-hydroxylase activity\" EXACT systematic_synonym []"
  },
  {
    "code": "def register_backend(self, name, backend):\n        if not hasattr(backend, 'send') or not callable(backend.send):\n            raise ValueError('Backend %s does not have a callable \"send\" method.' % backend.__class__.__name__)\n        else:\n            self.backends[name] = backend",
    "docstring": "Register a new backend that will be called for each processed event.\n\n        Note that backends are called in the order that they are registered."
  },
  {
    "code": "def serialize_properties(properties):\n    new_properties = properties.copy()\n    for attr_name, attr_value in new_properties.items():\n        if isinstance(attr_value, datetime):\n            new_properties[attr_name] = attr_value.isoformat()\n        elif not isinstance(attr_value, (dict, list, tuple, str, int, float, bool, type(None))):\n            new_properties[attr_name] = str(attr_value)\n    return new_properties",
    "docstring": "Serialize properties.\n\n    Parameters\n    ----------\n    properties : dict\n        Properties to serialize."
  },
  {
    "code": "def sleep(self):\n        if self.next_time and time.time() < self.next_time:\n            time.sleep(self.next_time - time.time())",
    "docstring": "Wait for the sleep time of the last response, to avoid being rate\n        limited."
  },
  {
    "code": "def get_content(self, zipbundle):\n        for content, filename in self.get_zip_content(zipbundle):\n            with io.BytesIO(content) as b:\n                encoding = self._analyze_file(b)\n                if encoding is None:\n                    encoding = self.default_encoding\n                b.seek(0)\n                text = b.read().decode(encoding)\n            yield text, filename, encoding",
    "docstring": "Get content."
  },
  {
    "code": "def disable_hyperthread(self):\n        to_disable = []\n        online_cpus = self.__get_ranges(\"online\")\n        for cpu in online_cpus:\n            fpath = path.join(\"cpu%i\"%cpu,\"topology\",\"thread_siblings_list\")\n            to_disable += self.__get_ranges(fpath)[1:]\n        to_disable = set(to_disable) & set(online_cpus)\n        for cpu in to_disable:\n            fpath = path.join(\"cpu%i\"%cpu,\"online\")\n            self.__write_cpu_file(fpath, b\"0\")",
    "docstring": "Disable all threads attached to the same core"
  },
  {
    "code": "def maybe_infer_freq(freq):\n    freq_infer = False\n    if not isinstance(freq, DateOffset):\n        if freq != 'infer':\n            freq = frequencies.to_offset(freq)\n        else:\n            freq_infer = True\n            freq = None\n    return freq, freq_infer",
    "docstring": "Comparing a DateOffset to the string \"infer\" raises, so we need to\n    be careful about comparisons.  Make a dummy variable `freq_infer` to\n    signify the case where the given freq is \"infer\" and set freq to None\n    to avoid comparison trouble later on.\n\n    Parameters\n    ----------\n    freq : {DateOffset, None, str}\n\n    Returns\n    -------\n    freq : {DateOffset, None}\n    freq_infer : bool"
  },
  {
    "code": "def _get_xml_rpc():\n    vm_ = get_configured_provider()\n    xml_rpc = config.get_cloud_config_value(\n        'xml_rpc', vm_, __opts__, search_global=False\n    )\n    user = config.get_cloud_config_value(\n        'user', vm_, __opts__, search_global=False\n    )\n    password = config.get_cloud_config_value(\n        'password', vm_, __opts__, search_global=False\n    )\n    server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)\n    return server, user, password",
    "docstring": "Uses the OpenNebula cloud provider configurations to connect to the\n    OpenNebula API.\n\n    Returns the server connection created as well as the user and password\n    values from the cloud provider config file used to make the connection."
  },
  {
    "code": "def nla_put_u64(msg, attrtype, value):\n    data = bytearray(value if isinstance(value, c_uint64) else c_uint64(value))\n    return nla_put(msg, attrtype, SIZEOF_U64, data)",
    "docstring": "Add 64 bit integer attribute to Netlink message.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L638\n\n    Positional arguments:\n    msg -- Netlink message (nl_msg class instance).\n    attrtype -- attribute type (integer).\n    value -- numeric value to store as payload (int() or c_uint64()).\n\n    Returns:\n    0 on success or a negative error code."
  },
  {
    "code": "def _get_linewidth(tree, linewidth, diameter_scale):\n    if diameter_scale is not None and tree:\n        linewidth = [2 * segment_radius(s) * diameter_scale\n                     for s in iter_segments(tree)]\n    return linewidth",
    "docstring": "calculate the desired linewidth based on tree contents\n\n    If diameter_scale exists, it is used to scale the diameter of each of the segments\n    in the tree\n    If diameter_scale is None, the linewidth is used."
  },
  {
    "code": "def _comparator_eq(filter_value, tested_value):\n    if isinstance(tested_value, ITERABLES):\n        for value in tested_value:\n            if not is_string(value):\n                value = repr(value)\n            if filter_value == value:\n                return True\n    elif not is_string(tested_value):\n        return filter_value == repr(tested_value)\n    else:\n        return filter_value == tested_value\n    return False",
    "docstring": "Tests if the filter value is equal to the tested value"
  },
  {
    "code": "def update_json_analysis(analysis, j):\n    def _analyze_list(l, parent=\"\"):\n        for v in l:\n            if isinstance(v, (dict, CaseInsensitiveDict)):\n                _analyze_json(v, parent=parent)\n            elif isinstance(v, list):\n                _analyze_list(v, parent=parent+\"[]\")\n            else:\n                analysis[parent].add(v)\n    def _analyze_json(d, parent=\"\"):\n        for k, v in d.iteritems():\n            if parent:\n                path = \".\".join([parent, k])\n            else:\n                path = k\n            if isinstance(v, (dict, CaseInsensitiveDict)):\n                _analyze_json(v, parent=path)\n            elif isinstance(v, list):\n                _analyze_list(v, parent=path+\"[]\")\n            else:\n                analysis[path].add(v)\n    if isinstance(j, list):\n        _analyze_list(j)\n    if isinstance(j, (dict, CaseInsensitiveDict)):\n        _analyze_json(j)",
    "docstring": "Step through the items in a piece of json, and update an analysis dict\n    with the values found."
  },
  {
    "code": "def get_args(method_or_func):\n    try:\n        args = list(inspect.signature(method_or_func).parameters.keys())\n    except AttributeError:\n        args = inspect.getargspec(method_or_func).args\n    return args",
    "docstring": "Returns method or function arguments."
  },
  {
    "code": "def _parse_engine(self):\n        if self._parser.has_option('storage', 'engine'):\n            engine = str(self._parser.get('storage', 'engine'))\n        else:\n            engine = ENGINE_DROPBOX\n        assert isinstance(engine, str)\n        if engine not in [ENGINE_DROPBOX,\n                          ENGINE_GDRIVE,\n                          ENGINE_COPY,\n                          ENGINE_ICLOUD,\n                          ENGINE_BOX,\n                          ENGINE_FS]:\n            raise ConfigError('Unknown storage engine: {}'.format(engine))\n        return str(engine)",
    "docstring": "Parse the storage engine in the config.\n\n        Returns:\n            str"
  },
  {
    "code": "def alphanumeric(text):\n    return \"\".join([c for c in text if re.match(r'\\w', c)])",
    "docstring": "Make an ultra-safe, ASCII version a string.\n    For instance for use as a filename.\n    \\w matches any alphanumeric character and the underscore."
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'tones' in _dict:\n            args['tones'] = [\n                ToneScore._from_dict(x) for x in (_dict.get('tones'))\n            ]\n        else:\n            raise ValueError(\n                'Required property \\'tones\\' not present in ToneCategory JSON')\n        if 'category_id' in _dict:\n            args['category_id'] = _dict.get('category_id')\n        else:\n            raise ValueError(\n                'Required property \\'category_id\\' not present in ToneCategory JSON'\n            )\n        if 'category_name' in _dict:\n            args['category_name'] = _dict.get('category_name')\n        else:\n            raise ValueError(\n                'Required property \\'category_name\\' not present in ToneCategory JSON'\n            )\n        return cls(**args)",
    "docstring": "Initialize a ToneCategory object from a json dictionary."
  },
  {
    "code": "def is_resource_class_member_attribute(rc, attr_name):\n    attr = get_resource_class_attribute(rc, attr_name)\n    return attr.kind == RESOURCE_ATTRIBUTE_KINDS.MEMBER",
    "docstring": "Checks if the given attribute name is a member attribute of the given\n    registered resource."
  },
  {
    "code": "def master_tops(self):\n        log.debug(\n            'The _ext_nodes master function has been renamed to _master_tops. '\n            'To ensure compatibility when using older Salt masters we will '\n            'continue to invoke the function as _ext_nodes until the '\n            'Magnesium release.'\n        )\n        load = {'cmd': '_ext_nodes',\n                'id': self.opts['id'],\n                'opts': self.opts}\n        if self.auth:\n            load['tok'] = self.auth.gen_token(b'salt')\n        return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \\\n            else self.channel.send(load)",
    "docstring": "Return the metadata derived from the master_tops system"
  },
  {
    "code": "def meet_challenge(self, challenge):\n        chunk_size = min(1024, self.file_size // 10)\n        seed = challenge.seed\n        h = hashlib.sha256()\n        self.file_object.seek(challenge.block)\n        if challenge.block > (self.file_size - chunk_size):\n            end_slice = (\n                challenge.block - (self.file_size - chunk_size)\n            )\n            h.update(self.file_object.read(end_slice))\n            self.file_object.seek(0)\n            h.update(self.file_object.read(chunk_size - end_slice))\n        else:\n            h.update(self.file_object.read(chunk_size))\n        h.update(seed)\n        return h.digest()",
    "docstring": "Get the SHA256 hash of a specific file block plus the provided\n        seed. The default block size is one tenth of the file. If the file is\n        larger than 10KB, 1KB is used as the block size.\n\n        :param challenge: challenge as a `Challenge <heartbeat.Challenge>`\n        object"
  },
  {
    "code": "def global_add(self, key: str, value: Any) -> None:\n        self.global_context[key] = value",
    "docstring": "Adds a key and value to the global dictionary"
  },
  {
    "code": "def begin_transaction(self):\n        self.ensure_connected()\n        self._transaction_nesting_level += 1\n        if self._transaction_nesting_level == 1:\n            self._driver.begin_transaction()\n        elif self._nest_transactions_with_savepoints:\n            self.create_savepoint(self._get_nested_transaction_savepoint_name())",
    "docstring": "Starts a transaction by suspending auto-commit mode."
  },
  {
    "code": "def deregister(self, subscriber):\r\n        try:\r\n            logger.debug('Subscriber left')\r\n            self.subscribers.remove(subscriber)\r\n        except KeyError:\r\n            logger.debug(\r\n                'Error removing subscriber: ' +\r\n                str(subscriber))",
    "docstring": "Stop publishing to a subscriber."
  },
  {
    "code": "def get_padding_bias(x):\n  with tf.name_scope(\"attention_bias\"):\n    padding = get_padding(x)\n    attention_bias = padding * _NEG_INF\n    attention_bias = tf.expand_dims(\n        tf.expand_dims(attention_bias, axis=1), axis=1)\n  return attention_bias",
    "docstring": "Calculate bias tensor from padding values in tensor.\n\n  Bias tensor that is added to the pre-softmax multi-headed attention logits,\n  which has shape [batch_size, num_heads, length, length]. The tensor is zero at\n  non-padding locations, and -1e9 (negative infinity) at padding locations.\n\n  Args:\n    x: int tensor with shape [batch_size, length]\n\n  Returns:\n    Attention bias tensor of shape [batch_size, 1, 1, length]."
  },
  {
    "code": "def editpermissions_user_view(self, request, user_id, forum_id=None):\n        user_model = get_user_model()\n        user = get_object_or_404(user_model, pk=user_id)\n        forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None\n        context = self.get_forum_perms_base_context(request, forum)\n        context['forum'] = forum\n        context['title'] = '{} - {}'.format(_('Forum permissions'), user)\n        context['form'] = self._get_permissions_form(\n            request, UserForumPermission, {'forum': forum, 'user': user},\n        )\n        return render(request, self.editpermissions_user_view_template_name, context)",
    "docstring": "Allows to edit user permissions for the considered forum.\n\n        The view displays a form to define which permissions are granted for the given user for the\n        considered forum."
  },
  {
    "code": "def monitor(args):\n    filename = args.get('MDFILE')\n    if not filename:\n        print col('Need file argument', 2)\n        raise SystemExit\n    last_err = ''\n    last_stat = 0\n    while True:\n        if not os.path.exists(filename):\n            last_err = 'File %s not found. Will continue trying.' % filename\n        else:\n            try:\n                stat = os.stat(filename)[8]\n                if stat != last_stat:\n                    parsed = run_args(args)\n                    print parsed\n                    last_stat = stat\n                last_err = ''\n            except Exception, ex:\n                last_err = str(ex)\n        if last_err:\n            print 'Error: %s' % last_err\n        sleep()",
    "docstring": "file monitor mode"
  },
  {
    "code": "def rename_dimension(x, old_name, new_name):\n  return reshape(x, x.shape.rename_dimension(old_name, new_name))",
    "docstring": "Reshape a Tensor, renaming one dimension.\n\n  Args:\n    x: a Tensor\n    old_name: a string\n    new_name: a string\n\n  Returns:\n    a Tensor"
  },
  {
    "code": "def find_or_create_role(self, name, **kwargs):\n        kwargs[\"name\"] = name\n        return self.find_role(name) or self.create_role(**kwargs)",
    "docstring": "Returns a role matching the given name or creates it with any\n        additionally provided parameters."
  },
  {
    "code": "def search_by_name(cls, name):\n        records = aleph.downloadRecords(\n            aleph.searchInAleph(\"aut\", name, False, \"wau\")\n        )\n        for record in records:\n            marc = MARCXMLRecord(record)\n            author = cls.parse_author(marc)\n            if author:\n                yield author",
    "docstring": "Look for author in NK Aleph authority base by `name`.\n\n        Args:\n            name (str): Author's name.\n\n        Yields:\n            obj: :class:`Author` instances."
  },
  {
    "code": "def addReadGroupSet(self, readGroupSet):\n        id_ = readGroupSet.getId()\n        self._readGroupSetIdMap[id_] = readGroupSet\n        self._readGroupSetNameMap[readGroupSet.getLocalId()] = readGroupSet\n        self._readGroupSetIds.append(id_)",
    "docstring": "Adds the specified readGroupSet to this dataset."
  },
  {
    "code": "def append(self, row_dict):\n        entry = self.client.InsertRow(row_dict, self.key, self.worksheet)\n        self.feed.entry.append(entry)\n        return GDataRow(entry, sheet=self, deferred_save=self.deferred_save)",
    "docstring": "Add a row to the spreadsheet, returns the new row"
  },
  {
    "code": "def shadow(self,new_root,visitor) :\n        for n in self.walk() :\n            sn = n.clone(new_root)\n            if n.isdir() :\n                visitor.process_dir(n,sn)\n            else :\n                visitor.process_file(n,sn)",
    "docstring": "Runs through the query, creating a clone directory structure in the new_root. Then applies process"
  },
  {
    "code": "def print_total_timer():\n    if len(_TOTAL_TIMER_DATA) == 0:\n        return\n    for k, v in six.iteritems(_TOTAL_TIMER_DATA):\n        logger.info(\"Total Time: {} -> {:.2f} sec, {} times, {:.3g} sec/time\".format(\n            k, v.sum, v.count, v.average))",
    "docstring": "Print the content of the TotalTimer, if it's not empty. This function will automatically get\n    called when program exits."
  },
  {
    "code": "def POINTER(obj):\n    p = ctypes.POINTER(obj)\n    if not isinstance(p.from_param, classmethod):\n        def from_param(cls, x):\n            if x is None:\n                return cls()\n            else:\n                return x\n        p.from_param = classmethod(from_param)\n    return p",
    "docstring": "Create ctypes pointer to object.\n\n    Notes\n    -----\n    This function converts None to a real NULL pointer because of bug\n    in how ctypes handles None on 64-bit platforms."
  },
  {
    "code": "def _post_tags(self, fileobj):\n        page = OggPage.find_last(fileobj, self.serial, finishing=True)\n        if page is None:\n            raise OggVorbisHeaderError\n        self.length = page.position / float(self.sample_rate)",
    "docstring": "Raises ogg.error"
  },
  {
    "code": "def broker_url(self):\n        return 'amqp://{}:{}@{}/{}'.format(\n            self.user, self.password, self.name, self.vhost)",
    "docstring": "Returns a \"broker URL\" for use with Celery."
  },
  {
    "code": "def __make_scubadir(self):\n        self.__scubadir_hostpath = tempfile.mkdtemp(prefix='scubadir')\n        self.__scubadir_contpath = '/.scuba'\n        self.add_volume(self.__scubadir_hostpath, self.__scubadir_contpath)",
    "docstring": "Make temp directory where all ancillary files are bind-mounted"
  },
  {
    "code": "def clean_uri(self):\n        if self.instance.fixed:\n            return self.instance.uri\n        uri = self.cleaned_data['uri']\n        return uri",
    "docstring": "Validates the URI"
  },
  {
    "code": "def _set_cache_(self, attr):\n        if attr == \"size\":\n            oinfo = self.repo.odb.info(self.binsha)\n            self.size = oinfo.size\n        else:\n            super(Object, self)._set_cache_(attr)",
    "docstring": "Retrieve object information"
  },
  {
    "code": "def json2pb(cls, json, strict=False):\n    return dict2pb(cls, simplejson.loads(json), strict)",
    "docstring": "Takes a class representing the Protobuf Message and fills it with data from\n    the json string."
  },
  {
    "code": "def collides_axisaligned_rect(self, other):\n        self_shifted = RotoOriginRect(self.width, self.height, -self.angle)\n        s_a = self.sin_a()\n        c_a = self.cos_a()\n        center_x = self.x + self.width / 2.0 * c_a - self.height / 2.0 * s_a\n        center_y = self.y - self.height / 2.0 * c_a - self.width / 2.0 * s_a\n        other_shifted = Rect(other.x - center_x, other.y - center_y,\n                             other.width, other.height)\n        return self_shifted.collides(other_shifted)",
    "docstring": "Returns collision with axis aligned other rect"
  },
  {
    "code": "def pipool(name, ivals):\n    name = stypes.stringToCharP(name)\n    n = ctypes.c_int(len(ivals))\n    ivals = stypes.toIntVector(ivals)\n    libspice.pipool_c(name, n, ivals)",
    "docstring": "This entry point provides toolkit programmers a method for\n    programmatically inserting integer data into the kernel pool.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pipool_c.html\n\n    :param name: The kernel pool name to associate with values.\n    :type name: str\n    :param ivals: An array of integers to insert into the pool.\n    :type ivals: Array of ints"
  },
  {
    "code": "def routeargs(path, host = None, vhost = None, method = [b'POST'], **kwargs):\n        \"For extra arguments, see Dispatcher.routeargs. They must be specified by keyword arguments\"\n        def decorator(func):\n            func.routemode = 'routeargs'\n            func.route_path = path\n            func.route_host = host\n            func.route_vhost = vhost\n            func.route_method = method\n            func.route_kwargs = kwargs\n            return func\n        return decorator",
    "docstring": "For extra arguments, see Dispatcher.routeargs. They must be specified by keyword arguments"
  },
  {
    "code": "def make_predicate_object_combinator(function, p, o):\n    def predicate_object_combinator(subject):\n        return function(subject, p, o)\n    return predicate_object_combinator",
    "docstring": "Combinator to hold predicate object pairs until a subject is supplied and then\n        call a function that accepts a subject, predicate, and object.\n\n        Create a combinator to defer production of a triple until the missing pieces are supplied.\n        Note that the naming here tells you what is stored IN the combinator. The argument to the\n        combinator is the piece that is missing."
  },
  {
    "code": "def get_controller_info_records(self):\n        info_records = []\n        for controller_module_name in self._controller_objects.keys():\n            with expects.expect_no_raises(\n                    'Failed to collect controller info from %s' %\n                    controller_module_name):\n                record = self._create_controller_info_record(\n                    controller_module_name)\n                if record:\n                    info_records.append(record)\n        return info_records",
    "docstring": "Get the info records for all the controller objects in the manager.\n\n        New info records for each controller object are created for every call\n        so the latest info is included.\n\n        Returns:\n            List of records.ControllerInfoRecord objects. Each opject conatins\n            the info of a type of controller"
  },
  {
    "code": "def error(self, **kwargs):\n        exception_header_width = 100\n        e = Error(**kwargs)\n        e.module = self.__class__.__name__\n        self.errors.append(e)\n        if e.exception:\n            sys.stderr.write(\"\\n\" + e.module + \" Exception: \" + str(e.exception) + \"\\n\")\n            sys.stderr.write(\"-\" * exception_header_width + \"\\n\")\n            traceback.print_exc(file=sys.stderr)\n            sys.stderr.write(\"-\" * exception_header_width + \"\\n\\n\")\n        elif e.description:\n            sys.stderr.write(\"\\n\" + e.module + \" Error: \" + e.description + \"\\n\\n\")",
    "docstring": "Stores the specified error in self.errors.\n\n        Accepts the same kwargs as the binwalk.core.module.Error class.\n\n        Returns None."
  },
  {
    "code": "def get_start_date(self):\n        sdate = self._my_map['startDate']\n        return DateTime(\n            sdate.year,\n            sdate.month,\n            sdate.day,\n            sdate.hour,\n            sdate.minute,\n            sdate.second,\n            sdate.microsecond)",
    "docstring": "Gets the start date.\n\n        return: (osid.calendaring.DateTime) - the start date\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def serializable_dict(d):\n    newd = {}\n    for k in d.keys():\n        if isinstance(d[k], type({})):\n            newd[k] = serializable_dict(d[k])\n            continue\n        try:\n            json.dumps({'k': d[k]})\n            newd[k] = d[k]\n        except:\n            pass\n    return newd",
    "docstring": "Return a dict like d, but with any un-json-serializable elements removed."
  },
  {
    "code": "def get_user(self, name):\n        r = self.kraken_request('GET', 'user/' + name)\n        return models.User.wrap_get_user(r)",
    "docstring": "Get the user for the given name\n\n        :param name: The username\n        :type name: :class:`str`\n        :returns: the user instance\n        :rtype: :class:`models.User`\n        :raises: None"
  },
  {
    "code": "def login(self, username, password, application, application_url):\n        logger.debug(str((username, application, application_url)))\n        method = self._anaconda_client_api.authenticate\n        return self._create_worker(method, username, password, application,\n                                   application_url)",
    "docstring": "Login to anaconda cloud."
  },
  {
    "code": "def median(ls):\n    ls = sorted(ls)\n    return ls[int(floor(len(ls)/2.0))]",
    "docstring": "Takes a list and returns the median."
  },
  {
    "code": "def PyParseIntCast(string, location, tokens):\n  for index, token in enumerate(tokens):\n    try:\n      tokens[index] = int(token)\n    except ValueError:\n      logger.error('Unable to cast [{0:s}] to an int, setting to 0'.format(\n          token))\n      tokens[index] = 0\n  for key in tokens.keys():\n    try:\n      tokens[key] = int(tokens[key], 10)\n    except ValueError:\n      logger.error(\n          'Unable to cast [{0:s} = {1:d}] to an int, setting to 0'.format(\n              key, tokens[key]))\n      tokens[key] = 0",
    "docstring": "Return an integer from a string.\n\n  This is a pyparsing callback method that converts the matched\n  string into an integer.\n\n  The method modifies the content of the tokens list and converts\n  them all to an integer value.\n\n  Args:\n    string (str): original string.\n    location (int): location in the string where the match was made.\n    tokens (list[str]): extracted tokens, where the string to be converted\n        is stored."
  },
  {
    "code": "def has_operator_manifest(self):\n        dockerfile = df_parser(self.workflow.builder.df_path, workflow=self.workflow)\n        labels = Labels(dockerfile.labels)\n        try:\n            _, operator_label = labels.get_name_and_value(Labels.LABEL_TYPE_OPERATOR_MANIFESTS)\n        except KeyError:\n            operator_label = 'false'\n        return operator_label.lower() == 'true'",
    "docstring": "Check if Dockerfile sets the operator manifest label\n\n        :return: bool"
  },
  {
    "code": "def dump(filename, options, out=sys.stdout):\n    with open(filename, 'rb') as file_obj:\n        return _dump(file_obj, options=options, out=out)",
    "docstring": "Dump parquet file with given filename using options to `out`."
  },
  {
    "code": "def predict(self, data, unkown=None):\n        assert self.classifier is not None, 'not calibrated'\n        bmus = self._som.bmus(data)\n        return self._predict_from_bmus(bmus, unkown)",
    "docstring": "\\\n        Classify data according to previous calibration.\n\n        :param data: sparse input matrix (ideal dtype is `numpy.float32`)\n        :type data: :class:`scipy.sparse.csr_matrix`\n        :param unkown: the label to attribute if no label is known\n        :returns: the labels guessed for data\n        :rtype: `numpy.array`"
  },
  {
    "code": "def display_vega(vega_data: dict, display: bool = True) -> Union['Vega', dict]:\n    if VEGA_IPYTHON_PLUGIN_ENABLED and display:\n        from vega3 import Vega\n        return Vega(vega_data)\n    else:\n        return vega_data",
    "docstring": "Optionally display vega dictionary.\n\n    Parameters\n    ----------\n    vega_data : Valid vega data as dictionary\n    display: Whether to try in-line display in IPython"
  },
  {
    "code": "def _apply_snap_off(self, queue=None):\n        r\n        net = self.project.network\n        phase = self.project.find_phase(self)\n        snap_off = self.settings['snap_off']\n        if queue is None:\n            queue = self.queue[0]\n        try:\n            Pc_snap_off = phase[snap_off]\n            logger.info(\"Adding snap off pressures to queue\")\n            for T in net.throats():\n                if not np.isnan(Pc_snap_off[T]):\n                    hq.heappush(queue, [Pc_snap_off[T], T, 'throat'])\n        except KeyError:\n            logger.warning(\"Phase \" + phase.name + \" doesn't have \" +\n                           \"property \" + snap_off)",
    "docstring": "r\"\"\"\n        Add all the throats to the queue with snap off pressure\n        This is probably wrong!!!! Each one needs to start a new cluster."
  },
  {
    "code": "def _ExtractJQuery(self, jquery_raw):\n    data_part = ''\n    if not jquery_raw:\n      return {}\n    if '[' in jquery_raw:\n      _, _, first_part = jquery_raw.partition('[')\n      data_part, _, _ = first_part.partition(']')\n    elif jquery_raw.startswith('//'):\n      _, _, first_part = jquery_raw.partition('{')\n      data_part = '{{{0:s}'.format(first_part)\n    elif '({' in jquery_raw:\n      _, _, first_part = jquery_raw.partition('(')\n      data_part, _, _ = first_part.rpartition(')')\n    if not data_part:\n      return {}\n    try:\n      data_dict = json.loads(data_part)\n    except ValueError:\n      return {}\n    return data_dict",
    "docstring": "Extracts values from a JQuery string.\n\n    Args:\n      jquery_raw (str): JQuery string.\n\n    Returns:\n      dict[str, str]: extracted values."
  },
  {
    "code": "def rfftn(a, s=None, axes=None, norm=None):\n    unitary = _unitary(norm)\n    if unitary:\n        a = asarray(a)\n        s, axes = _cook_nd_args(a, s, axes)\n    output = mkl_fft.rfftn_numpy(a, s, axes)\n    if unitary:\n        n_tot = prod(asarray(s, dtype=output.dtype))\n        output *= 1 / sqrt(n_tot)\n    return output",
    "docstring": "Compute the N-dimensional discrete Fourier Transform for real input.\n\n    This function computes the N-dimensional discrete Fourier Transform over\n    any number of axes in an M-dimensional real array by means of the Fast\n    Fourier Transform (FFT).  By default, all axes are transformed, with the\n    real transform performed over the last axis, while the remaining\n    transforms are complex.\n\n    Parameters\n    ----------\n    a : array_like\n        Input array, taken to be real.\n    s : sequence of ints, optional\n        Shape (length along each transformed axis) to use from the input.\n        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).\n        The final element of `s` corresponds to `n` for ``rfft(x, n)``, while\n        for the remaining axes, it corresponds to `n` for ``fft(x, n)``.\n        Along any axis, if the given shape is smaller than that of the input,\n        the input is cropped.  If it is larger, the input is padded with zeros.\n        if `s` is not given, the shape of the input along the axes specified\n        by `axes` is used.\n    axes : sequence of ints, optional\n        Axes over which to compute the FFT.  If not given, the last ``len(s)``\n        axes are used, or all axes if `s` is also not specified.\n    norm : {None, \"ortho\"}, optional\n        .. versionadded:: 1.10.0\n        Normalization mode (see `numpy.fft`). Default is None.\n\n    Returns\n    -------\n    out : complex ndarray\n        The truncated or zero-padded input, transformed along the axes\n        indicated by `axes`, or by a combination of `s` and `a`,\n        as explained in the parameters section above.\n        The length of the last axis transformed will be ``s[-1]//2+1``,\n        while the remaining transformed axes will have lengths according to\n        `s`, or unchanged from the input.\n\n    Raises\n    ------\n    ValueError\n        If `s` and `axes` have different length.\n    IndexError\n        If an element of `axes` is larger than than the number of axes of `a`.\n\n    See Also\n    --------\n    irfftn : The inverse of `rfftn`, i.e. the inverse of the n-dimensional FFT\n         of real input.\n    fft : The one-dimensional FFT, with definitions and conventions used.\n    rfft : The one-dimensional FFT of real input.\n    fftn : The n-dimensional FFT.\n    rfft2 : The two-dimensional FFT of real input.\n\n    Notes\n    -----\n    The transform for real input is performed over the last transformation\n    axis, as by `rfft`, then the transform over the remaining axes is\n    performed as by `fftn`.  The order of the output is as for `rfft` for the\n    final transformation axis, and as for `fftn` for the remaining\n    transformation axes.\n\n    See `fft` for details, definitions and conventions used.\n\n    Examples\n    --------\n    >>> a = np.ones((2, 2, 2))\n    >>> np.fft.rfftn(a)\n    array([[[ 8.+0.j,  0.+0.j],\n            [ 0.+0.j,  0.+0.j]],\n           [[ 0.+0.j,  0.+0.j],\n            [ 0.+0.j,  0.+0.j]]])\n\n    >>> np.fft.rfftn(a, axes=(2, 0))\n    array([[[ 4.+0.j,  0.+0.j],\n            [ 4.+0.j,  0.+0.j]],\n           [[ 0.+0.j,  0.+0.j],\n            [ 0.+0.j,  0.+0.j]]])"
  },
  {
    "code": "def prepare_dependencies(self):\n        attrs = [\n            ('bsources', 'bsourcesigs'),\n            ('bdepends', 'bdependsigs'),\n            ('bimplicit', 'bimplicitsigs'),\n        ]\n        for (nattr, sattr) in attrs:\n            try:\n                strings = getattr(self, nattr)\n                nodeinfos = getattr(self, sattr)\n            except AttributeError:\n                continue\n            if strings is None or nodeinfos is None:\n                continue\n            nodes = []\n            for s, ni in zip(strings, nodeinfos):\n                if not isinstance(s, SCons.Node.Node):\n                    s = ni.str_to_node(s)\n                nodes.append(s)\n            setattr(self, nattr, nodes)",
    "docstring": "Prepares a FileBuildInfo object for explaining what changed\n\n        The bsources, bdepends and bimplicit lists have all been\n        stored on disk as paths relative to the top-level SConstruct\n        directory.  Convert the strings to actual Nodes (for use by the\n        --debug=explain code and --implicit-cache)."
  },
  {
    "code": "def unpack(data):\n    size, position = decoder._DecodeVarint(data, 0)\n    envelope = wire.Envelope() \n    envelope.ParseFromString(data[position:position+size])\n    return envelope",
    "docstring": "unpack from delimited data"
  },
  {
    "code": "def app(config, src, dst, features, reload, force):\n    config = Path(config)\n    if reload:\n        argv = sys.argv.copy()\n        argv.remove('--reload')\n        monitor(config.dirname(), src, dst, argv)\n    else:\n        run(config, src, dst, force)",
    "docstring": "Takes several files or directories as src and generates the code\n    in the given dst directory."
  },
  {
    "code": "def cache_request_user(user_cls, request, user_id):\n    pk_field = user_cls.pk_field()\n    user = getattr(request, '_user', None)\n    if user is None or getattr(user, pk_field, None) != user_id:\n        request._user = user_cls.get_item(**{pk_field: user_id})",
    "docstring": "Helper function to cache currently logged in user.\n\n    User is cached at `request._user`. Caching happens only only\n    if user is not already cached or if cached user's pk does not\n    match `user_id`.\n\n    :param user_cls: User model class to use for user lookup.\n    :param request: Pyramid Request instance.\n    :user_id: Current user primary key field value."
  },
  {
    "code": "def delete(self):\n        response = self.hv.delete_request('people/' + str(self.id))\n        return response",
    "docstring": "Deletes the person immediately."
  },
  {
    "code": "def df_first_row_to_dict(df):\n        if df is not None:\n            return [dict(r) for i, r in df.head(1).iterrows()][0]",
    "docstring": "First DataFrame row to list of dict\n\n        Args:\n            df (pandas.DataFrame): A DataFrame with at least one row\n\n        Returns:\n            A list of dict that looks like:\n\n                [{'C1': 'x'}, {'C2': 'y'}, {'C3': 'z'}]\n\n            from a DataFrame that looks like:\n\n                    C1  C2  C3\n                1   x   y   z\n\n            Else if `df` is `None`, returns `None`"
  },
  {
    "code": "def parseGeometry(self, geometry):\n        self.coordinates = []\n        self.index = []\n        self.position = 0\n        self.lastX = 0 \n        self.lastY = 0\n        self.isPoly = False\n        self.isPoint = True;\n        self.dropped = 0;\n        self.first = True\n        self._current_string = geometry\n        reader = _ExtendedUnPacker(geometry)\n        self._dispatchNextType(reader)",
    "docstring": "A factory method for creating objects of the correct OpenGIS type."
  },
  {
    "code": "def owners(self):\n        result = set()\n        for role in self._OWNER_ROLES:\n            for member in self._bindings.get(role, ()):\n                result.add(member)\n        return frozenset(result)",
    "docstring": "Legacy access to owner role.\n\n        DEPRECATED:  use ``policy[\"roles/owners\"]`` instead."
  },
  {
    "code": "def projC(gamma, q):\n    return np.multiply(gamma, q / np.maximum(np.sum(gamma, axis=0), 1e-10))",
    "docstring": "return the KL projection on the column constrints"
  },
  {
    "code": "def get_widget_title(tab_label_text):\n    title = ''\n    title_list = tab_label_text.split('_')\n    for word in title_list:\n        title += word.upper() + ' '\n    title.strip()\n    return title",
    "docstring": "Transform Notebook tab label to title by replacing underscores with white spaces and capitalizing the first\n    letter of each word.\n\n    :param tab_label_text: The string of the tab label to be transformed\n    :return: The transformed title as a string"
  },
  {
    "code": "def apply_constraint(self,constraint,selectfrac_skip=False,\n                         distribution_skip=False,overwrite=False):\n        constraints = self.constraints\n        my_selectfrac_skip = self.selectfrac_skip\n        my_distribution_skip = self.distribution_skip\n        if constraint.name in constraints and not overwrite:\n            logging.warning('constraint already applied: {}'.format(constraint.name))\n            return\n        constraints[constraint.name] = constraint\n        if selectfrac_skip:\n            my_selectfrac_skip.append(constraint.name)\n        if distribution_skip:\n            my_distribution_skip.append(constraint.name)\n        if hasattr(self, '_make_kde'):\n            self._make_kde()\n        self.constraints = constraints\n        self.selectfrac_skip = my_selectfrac_skip\n        self.distribution_skip = my_distribution_skip",
    "docstring": "Apply a constraint to the population\n\n        :param constraint:\n            Constraint to apply.\n        :type constraint:\n            :class:`Constraint`\n\n        :param selectfrac_skip: (optional)\n            If ``True``, then this constraint will not be considered\n            towards diminishing the"
  },
  {
    "code": "def getWmg2(self, prefcounts, ordering, state, normalize=False):\n        wmgMap = dict()\n        for cand in state:\n            wmgMap[cand] = dict()\n        for cand1, cand2 in itertools.combinations(state, 2):\n            wmgMap[cand1][cand2] = 0\n            wmgMap[cand2][cand1] = 0\n        for i in range(0, len(prefcounts)):\n            for cand1, cand2 in itertools.combinations(ordering[i], 2):\n                wmgMap[cand1][cand2] += prefcounts[i]\n        if normalize == True:\n            maxEdge = float('-inf')\n            for cand in wmgMap.keys():\n                maxEdge = max(maxEdge, max(wmgMap[cand].values()))\n            for cand1 in wmgMap.keys():\n                for cand2 in wmgMap[cand1].keys():\n                    wmgMap[cand1][cand2] = float(wmgMap[cand1][cand2]) / maxEdge\n        return wmgMap",
    "docstring": "Generate a weighted majority graph that represents the whole profile. The function will\n        return a two-dimensional dictionary that associates integer representations of each pair of\n        candidates, cand1 and cand2, with the number of times cand1 is ranked above cand2 minus the\n        number of times cand2 is ranked above cand1.\n\n        :ivar bool normalize: If normalize is True, the function will return a normalized graph\n            where each edge has been divided by the value of the largest edge."
  },
  {
    "code": "def prompt_for_password(url, user=None, default_user=None):\n    if user is None:\n        default_user = default_user or getpass.getuser()\n        while user is None:\n            user = compat.console_input(\n                \"Enter username for {} [{}]: \".format(url, default_user)\n            )\n            if user.strip() == \"\" and default_user:\n                user = default_user\n    if user:\n        pw = getpass.getpass(\n            \"Enter password for {}@{} (Ctrl+C to abort): \".format(user, url)\n        )\n        if pw or pw == \"\":\n            return (user, pw)\n    return None",
    "docstring": "Prompt for username and password.\n\n    If a user name is passed, only prompt for a password.\n    Args:\n        url (str): hostname\n        user (str, optional):\n            Pass a valid name to skip prompting for a user name\n        default_user (str, optional):\n            Pass a valid name that is used as default when prompting\n            for a user name\n    Raises:\n        KeyboardInterrupt if user hits Ctrl-C\n    Returns:\n        (username, password) or None"
  },
  {
    "code": "def save_conf(fn=None):\n    if fn is None:\n        fn = cfile()\n    try:\n        os.makedirs(os.path.dirname(fn))\n    except (OSError, IOError):\n        pass\n    with open(fn, 'w') as f:\n        yaml.dump(conf, f)",
    "docstring": "Save current configuration to file as YAML\n\n    If not given, uses current config directory, ``confdir``, which can be\n    set by INTAKE_CONF_DIR."
  },
  {
    "code": "def groupby(xs, key_fn):\n    result = defaultdict(list)\n    for x in xs:\n        key = key_fn(x)\n        result[key].append(x)\n    return result",
    "docstring": "Group elements of the list `xs` by keys generated from calling `key_fn`.\n\n    Returns a dictionary which maps keys to sub-lists of `xs`."
  },
  {
    "code": "def arrows_at(self, x, y):\n        for arrow in self.arrows():\n            if arrow.collide_point(x, y):\n                yield arrow",
    "docstring": "Iterate over arrows that collide the given point."
  },
  {
    "code": "def set_property(self, key, value):\n        self.properties[key] = value\n        self.sync_properties()",
    "docstring": "Update only one property in the dict"
  },
  {
    "code": "def console_input(default, validation=None, allow_empty=False):\n    value = raw_input(\"> \") or default\n    if value == \"\" and not allow_empty:\n        print \"Invalid: Empty value is not permitted.\"\n        return console_input(default, validation)\n    if validation:\n        try:\n            return validation(value)\n        except ValidationError, e:\n            print \"Invalid: \", e\n            return console_input(default, validation)\n    return value",
    "docstring": "Get user input value from stdin\n\n    Parameters\n    ----------\n    default : string\n        A default value. It will be used when user input nothing.\n    validation : callable\n        A validation function. The validation function must raise an error\n        when validation has failed.\n\n    Returns\n    -------\n    string or any\n        A user input string or validated value"
  },
  {
    "code": "def decompress(data, compression, width, height, depth, version=1):\n    length = width * height * depth // 8\n    result = None\n    if compression == Compression.RAW:\n        result = data[:length]\n    elif compression == Compression.PACK_BITS:\n        result = decode_packbits(data, height, version)\n    elif compression == Compression.ZIP:\n        result = zlib.decompress(data)\n    else:\n        decompressed = zlib.decompress(data)\n        result = decode_prediction(decompressed, width, height, depth)\n    assert len(result) == length, 'len=%d, expected=%d' % (\n        len(result), length\n    )\n    return result",
    "docstring": "Decompress raw data.\n\n    :param data: compressed data bytes.\n    :param compression: compression type,\n            see :py:class:`~psd_tools.constants.Compression`.\n    :param width: width.\n    :param height: height.\n    :param depth: bit depth of the pixel.\n    :param version: psd file version.\n    :return: decompressed data bytes."
  },
  {
    "code": "def fake_chars_or_choice(self, field_name):\n        return self.djipsum_fields().randomCharField(\n            self.model_class(),\n            field_name=field_name\n        )",
    "docstring": "Return fake chars or choice it if the `field_name` has choices.\n        Then, returning random value from it.\n        This specially for `CharField`.\n\n        Usage:\n            faker.fake_chars_or_choice('field_name')\n\n        Example for field:\n            TYPE_CHOICES = (\n              ('project', 'I wanna to talk about project'),\n              ('feedback', 'I want to report a bugs or give feedback'),\n              ('hello', 'I just want to say hello')\n            )\n            type = models.CharField(max_length=200, choices=TYPE_CHOICES)"
  },
  {
    "code": "def configure_roles_on_host(api, host):\n  for role_ref in host.roleRefs:\n    if role_ref.get('clusterName') is None:\n      continue\n    role = api.get_cluster(role_ref['clusterName'])\\\n              .get_service(role_ref['serviceName'])\\\n              .get_role(role_ref['roleName'])\n    LOG.debug(\"Evaluating %s (%s)\" % (role.name, host.hostname))\n    config = None\n    if role.type == 'DATANODE':\n      config = DATANODE_CONF\n    elif role.type == 'TASKTRACKER':\n      config = TASKTRACKER_CONF\n    elif role.type == 'REGIONSERVER':\n      config = REGIONSERVER_CONF\n    else:\n      continue\n    LOG.info(\"Configuring %s (%s)\" % (role.name, host.hostname))\n    role.update_config(config)",
    "docstring": "Go through all the roles on this host, and configure them if they\n  match the role types that we care about."
  },
  {
    "code": "def Task(func, *args, **kwargs):\n    future = Future()\n    def handle_exception(typ, value, tb):\n        if future.done():\n            return False\n        future.set_exc_info((typ, value, tb))\n        return True\n    def set_result(result):\n        if future.done():\n            return\n        future.set_result(result)\n    with stack_context.ExceptionStackContext(handle_exception):\n        func(*args, callback=_argument_adapter(set_result), **kwargs)\n    return future",
    "docstring": "Adapts a callback-based asynchronous function for use in coroutines.\n\n    Takes a function (and optional additional arguments) and runs it with\n    those arguments plus a ``callback`` keyword argument.  The argument passed\n    to the callback is returned as the result of the yield expression.\n\n    .. versionchanged:: 4.0\n       ``gen.Task`` is now a function that returns a `.Future`, instead of\n       a subclass of `YieldPoint`.  It still behaves the same way when\n       yielded."
  },
  {
    "code": "def contains(self, location):\n    return self.almostEqual(\n      sum([coord ** 2 for coord in location]), self.radius ** 2\n    )",
    "docstring": "Checks that the provided point is on the sphere."
  },
  {
    "code": "def uploads(self):\n        if self._resources is None:\n            self.__init()\n        if \"uploads\" in self._resources:\n            url = self._url + \"/uploads\"\n            return _uploads.Uploads(url=url,\n                                    securityHandler=self._securityHandler,\n                                    proxy_url=self._proxy_url,\n                                    proxy_port=self._proxy_port,\n                                    initialize=True)\n        else:\n            return None",
    "docstring": "returns an object to work with the site uploads"
  },
  {
    "code": "def delete_queue(name, region, opts=None, user=None):\n    queues = list_queues(region, opts, user)\n    url_map = _parse_queue_list(queues)\n    log.debug('map %s', url_map)\n    if name in url_map:\n        delete = {'queue-url': url_map[name]}\n        rtn = _run_aws(\n            'delete-queue',\n            region=region,\n            opts=opts,\n            user=user,\n            **delete)\n        success = True\n        err = ''\n        out = '{0} deleted'.format(name)\n    else:\n        out = ''\n        err = \"Delete failed\"\n        success = False\n    ret = {\n        'retcode': 0 if success else 1,\n        'stdout': out,\n        'stderr': err,\n    }\n    return ret",
    "docstring": "Deletes a queue in the region.\n\n    name\n        Name of the SQS queue to deletes\n    region\n        Name of the region to delete the queue from\n\n    opts : None\n        Any additional options to add to the command line\n\n    user : None\n        Run hg as a user other than what the minion runs as\n\n    CLI Example:\n\n        salt '*' aws_sqs.delete_queue <sqs queue> <region>"
  },
  {
    "code": "def serialize(self, data):\n        self.set_header('Content-Type', self.content_type)\n        return self.dumper(data)",
    "docstring": "Serlialize the output based on the Accept header"
  },
  {
    "code": "def get_indexable(cls):\n        model = cls.get_model()\n        return model.objects.order_by('id').values_list('id', flat=True)",
    "docstring": "Returns the queryset of ids of all things to be indexed.\n\n        Defaults to::\n\n            cls.get_model().objects.order_by('id').values_list(\n                'id', flat=True)\n\n        :returns: iterable of ids of objects to be indexed"
  },
  {
    "code": "def add_attribute(self, name, value):\n        if not issubclass(value.__class__, Attribute):\n            raise foundations.exceptions.NodeAttributeTypeError(\n                \"Node attribute value must be a '{0}' class instance!\".format(Attribute.__class__.__name__))\n        if self.attribute_exists(name):\n            raise foundations.exceptions.NodeAttributeExistsError(\"Node attribute '{0}' already exists!\".format(name))\n        self[name] = value\n        return True",
    "docstring": "Adds given attribute to the node.\n\n        Usage::\n\n            >>>\tnode_a = AbstractNode()\n            >>> node_a.add_attribute(\"attributeA\", Attribute())\n            True\n            >>> node_a.list_attributes()\n            [u'attributeA']\n\n        :param name: Attribute name.\n        :type name: unicode\n        :param value: Attribute value.\n        :type value: Attribute\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def get_active_channels_by_year_quarter(\n            self, channel_type, year, quarter, expires=None):\n        if expires is None:\n            expires = datetime.combine(datetime.utcnow().date(), time.min)\n        return self.search_channels(\n            type=channel_type, tag_year=year, tag_quarter=quarter,\n            expires_after=expires.isoformat())",
    "docstring": "Search for all active channels by year and quarter"
  },
  {
    "code": "def shutdown(self):\n        if not self._exited:\n            self._exited = True\n            if self._task_runner.is_alive():\n                self._task_runner.terminate()\n                if self._command_server.is_alive():\n                    if self._task_runner.is_alive():\n                        self._task_runner.join()\n            _shutdown_pipe(self._pipe)\n            self._task.stop()",
    "docstring": "Shuts down the daemon process."
  },
  {
    "code": "def iterable(self, iterable_name, *, collection, attribute, word, func=None,\n                 operation=None):\n        if func is None and operation is None:\n            raise ValueError('Provide a function or an operation to apply')\n        elif func is not None and operation is not None:\n            raise ValueError(\n                'Provide either a function or an operation but not both')\n        current_att = self._attribute\n        self._attribute = iterable_name\n        word = self._parse_filter_word(word)\n        collection = self._get_mapping(collection)\n        attribute = self._get_mapping(attribute)\n        if func is not None:\n            sentence = self._prepare_function(func, attribute, word)\n        else:\n            sentence = self._prepare_sentence(attribute, operation, word)\n        filter_str, attrs = sentence\n        filter_data = '{}/{}(a:a/{})'.format(collection, iterable_name, filter_str), attrs\n        self._add_filter(*filter_data)\n        self._attribute = current_att\n        return self",
    "docstring": "Performs a filter with the OData 'iterable_name' keyword\n        on the collection\n\n        For example:\n        q.iterable('any', collection='email_addresses', attribute='address',\n        operation='eq', word='george@best.com')\n\n        will transform to a filter such as:\n        emailAddresses/any(a:a/address eq 'george@best.com')\n\n        :param str iterable_name: the OData name of the iterable\n        :param str collection: the collection to apply the any keyword on\n        :param str attribute: the attribute of the collection to check\n        :param str word: the word to check\n        :param str func: the logical function to apply to the attribute inside\n         the collection\n        :param str operation: the logical operation to apply to the attribute\n         inside the collection\n        :rtype: Query"
  },
  {
    "code": "def get_assigned_services_uids(self):\n        services = self.get_assigned_services()\n        uids = map(api.get_uid, services)\n        return list(set(uids))",
    "docstring": "Get the current assigned services UIDs of this Worksheet"
  },
  {
    "code": "def write (self, s, **args):\n        if self.filename is not None:\n            self.start_fileoutput()\n        if self.fd is None:\n            log.warn(LOG_CHECK, \"writing to unitialized or closed file\")\n        else:\n            try:\n                self.fd.write(s, **args)\n            except IOError:\n                msg = sys.exc_info()[1]\n                log.warn(LOG_CHECK,\n                    \"Could not write to output file: %s\\n\"\n                    \"Disabling log output of %s\", msg, self)\n                self.close_fileoutput()\n                self.fd = dummy.Dummy()\n                self.is_active = False",
    "docstring": "Write string to output descriptor. Strips control characters\n        from string before writing."
  },
  {
    "code": "def get_unused_node_id(graph, initial_guess='unknown', _format='{}<%d>'):\n    has_node = graph.has_node\n    n = counter()\n    node_id_format = _format.format(initial_guess)\n    node_id = initial_guess\n    while has_node(node_id):\n        node_id = node_id_format % n()\n    return node_id",
    "docstring": "Finds an unused node id in `graph`.\n\n    :param graph:\n        A directed graph.\n    :type graph: networkx.classes.digraph.DiGraph\n\n    :param initial_guess:\n        Initial node id guess.\n    :type initial_guess: str, optional\n\n    :param _format:\n        Format to generate the new node id if the given is already used.\n    :type _format: str, optional\n\n    :return:\n        An unused node id.\n    :rtype: str"
  },
  {
    "code": "def _apply_backwards_compatibility(df):\n    df.row_count = types.MethodType(lambda self: len(self.index), df)\n    df.col_count = types.MethodType(lambda self: len(self.columns), df)\n    df.dataframe = df",
    "docstring": "Attach properties to the Dataframe to make it backwards compatible with older versions of this library\n\n    :param df: The dataframe to be modified"
  },
  {
    "code": "def valid_env_vars() -> bool:\n    for envvar in _REQUIRED_ENV_VARS:\n        try:\n            _check_env_var(envvar)\n        except KeyError as ex:\n            LOG.error(ex)\n            sys.exit(1)\n    return True",
    "docstring": "Validate that required env vars exist.\n\n    :returns: True if required env vars exist.\n\n    .. versionadded:: 0.0.12"
  },
  {
    "code": "def parse_torrent_file(torrent):\n    link_re = re.compile(r'^(http?s|ftp)')\n    if link_re.match(torrent):\n        response = requests.get(torrent, headers=HEADERS, timeout=20)\n        data = parse_torrent_buffer(response.content)\n    elif os.path.isfile(torrent):\n        with open(torrent, 'rb') as f:\n            data = parse_torrent_buffer(f.read())\n    else:\n        data = None\n    return data",
    "docstring": "parse local or remote torrent file"
  },
  {
    "code": "def set_call_back(self, func):\n        self.timer.add_callback(func)\n        self.timer.start()",
    "docstring": "sets callback function for updating the plot.\n        in the callback function implement the logic of reading of serial input\n        also the further processing of the signal if necessary has to be done\n        in this\n        callbak function."
  },
  {
    "code": "def qteRemoveKey(self, keysequence: QtmacsKeysequence):\n        keyMap = self\n        keyMapRef = keyMap\n        keysequence = keysequence.toQtKeylist()\n        for key in keysequence[:-1]:\n            if key not in keyMap:\n                return\n            keyMap = keyMap[key]\n        if keysequence[-1] not in keyMap:\n            return\n        else:\n            keyMap.pop(keysequence[-1])\n        keysequence = keysequence[:-1]\n        while(len(keysequence)):\n            keyMap = keyMapRef\n            for key in keysequence[:-1]:\n                keyMap = keyMap[key]\n            if len(keyMap[key]):\n                return\n            else:\n                keyMap.pop(key)",
    "docstring": "Remove ``keysequence`` from this key map.\n\n        |Args|\n\n        * ``keysequence`` (**QtmacsKeysequence**): key sequence to\n          remove from this key map.\n\n        |Returns|\n\n        **None**\n\n        |Raises|\n\n        * **QtmacsArgumentError** if at least one argument has an invalid type."
  },
  {
    "code": "def get_user_id_by_user(self, username):\n        response, status_code = self.__pod__.Users.get_v2_user(\n            sessionToken=self.__session__,\n            username=username\n        ).result()\n        self.logger.debug('%s: %s' % (status_code, response))\n        return status_code, response",
    "docstring": "get user id by username"
  },
  {
    "code": "def deleted_records(endpoint):\n    @utils.for_each_value\n    def _deleted_records(self, key, value):\n        deleted_recid = maybe_int(value.get('a'))\n        if deleted_recid:\n            return get_record_ref(deleted_recid, endpoint)\n    return _deleted_records",
    "docstring": "Populate the ``deleted_records`` key."
  },
  {
    "code": "def format_to_http_prompt(context, excluded_options=None):\n    cmds = _extract_httpie_options(context, quote=True, join_key_value=True,\n                                   excluded_keys=excluded_options)\n    cmds.append('cd ' + smart_quote(context.url))\n    cmds += _extract_httpie_request_items(context, quote=True)\n    return '\\n'.join(cmds) + '\\n'",
    "docstring": "Format a Context object to HTTP Prompt commands."
  },
  {
    "code": "def set_type(self, type, header='Content-Type', requote=True):\n        if not type.count('/') == 1:\n            raise ValueError\n        if header.lower() == 'content-type':\n            del self['mime-version']\n            self['MIME-Version'] = '1.0'\n        if header not in self:\n            self[header] = type\n            return\n        params = self.get_params(header=header, unquote=requote)\n        del self[header]\n        self[header] = type\n        for p, v in params[1:]:\n            self.set_param(p, v, header, requote)",
    "docstring": "Set the main type and subtype for the Content-Type header.\n\n        type must be a string in the form \"maintype/subtype\", otherwise a\n        ValueError is raised.\n\n        This method replaces the Content-Type header, keeping all the\n        parameters in place.  If requote is False, this leaves the existing\n        header's quoting as is.  Otherwise, the parameters will be quoted (the\n        default).\n\n        An alternative header can be specified in the header argument.  When\n        the Content-Type header is set, we'll always also add a MIME-Version\n        header."
  },
  {
    "code": "def cpp_app_builder(build_context, target):\n    yprint(build_context.conf, 'Build CppApp', target)\n    if target.props.executable and target.props.main:\n        raise KeyError(\n            '`main` and `executable` arguments are mutually exclusive')\n    if target.props.executable:\n        if target.props.executable not in target.artifacts.get(AT.app):\n            target.artifacts.add(AT.app, target.props.executable)\n        entrypoint = [target.props.executable]\n    elif target.props.main:\n        prog = build_context.targets[target.props.main]\n        binary = list(prog.artifacts.get(AT.binary).keys())[0]\n        entrypoint = ['/usr/src/bin/' + binary]\n    else:\n        raise KeyError('Must specify either `main` or `executable` argument')\n    build_app_docker_and_bin(\n        build_context, target, entrypoint=entrypoint)",
    "docstring": "Pack a C++ binary as a Docker image with its runtime dependencies.\n\n    TODO(itamar): Dynamically analyze the binary and copy shared objects\n    from its buildenv image to the runtime image, unless they're installed."
  },
  {
    "code": "def do_keys(self, keys):\n        for inst in keys:\n            typ = inst[\"kty\"]\n            try:\n                _usage = harmonize_usage(inst['use'])\n            except KeyError:\n                _usage = ['']\n            else:\n                del inst['use']\n            flag = 0\n            for _use in _usage:\n                for _typ in [typ, typ.lower(), typ.upper()]:\n                    try:\n                        _key = K2C[_typ](use=_use, **inst)\n                    except KeyError:\n                        continue\n                    except JWKException as err:\n                        logger.warning('While loading keys: {}'.format(err))\n                    else:\n                        if _key not in self._keys:\n                            self._keys.append(_key)\n                        flag = 1\n                        break\n            if not flag:\n                logger.warning(\n                    'While loading keys, UnknownKeyType: {}'.format(typ))",
    "docstring": "Go from JWK description to binary keys\n\n        :param keys:\n        :return:"
  },
  {
    "code": "def create_event_permission(self, lambda_name, principal, source_arn):\n        logger.debug('Adding new permission to invoke Lambda function: {}'.format(lambda_name))\n        permission_response = self.lambda_client.add_permission(\n            FunctionName=lambda_name,\n            StatementId=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)),\n            Action='lambda:InvokeFunction',\n            Principal=principal,\n            SourceArn=source_arn,\n        )\n        if permission_response['ResponseMetadata']['HTTPStatusCode'] != 201:\n            print('Problem creating permission to invoke Lambda function')\n            return None\n        return permission_response",
    "docstring": "Create permissions to link to an event.\n\n        Related: http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-configure-event-source.html"
  },
  {
    "code": "def construct(path, name=None):\n    \"Selects an appropriate CGroup subclass for the given CGroup path.\"\n    name = name if name else path.split(\"/\")[4]\n    classes = {\"memory\": Memory,\n               \"cpu\": CPU,\n               \"cpuacct\": CPUAcct}\n    constructor = classes.get(name, CGroup)\n    log.debug(\"Chose %s for: %s\", constructor.__name__, path)\n    return constructor(path, name)",
    "docstring": "Selects an appropriate CGroup subclass for the given CGroup path."
  },
  {
    "code": "def memory_used(self):\n        if self._end_memory:\n            memory_used = self._end_memory - self._start_memory\n            return memory_used\n        else:\n            return None",
    "docstring": "To know the allocated memory at function termination.\n\n        ..versionadded:: 4.1\n\n        This property might return None if the function is still running.\n\n        This function should help to show memory leaks or ram greedy code."
  },
  {
    "code": "def samples(self, anystring, limit=None, offset=None, sortby=None):\n        uri = self._uris['samples'].format(anystring)\n        params = {'limit': limit, 'offset': offset, 'sortby': sortby}\n        return self.get_parse(uri, params)",
    "docstring": "Return an object representing the samples identified by the input domain, IP, or URL"
  },
  {
    "code": "def get_waiter(self, waiter_name):\n        config = self._get_waiter_config()\n        if not config:\n            raise ValueError(\"Waiter does not exist: %s\" % waiter_name)\n        model = waiter.WaiterModel(config)\n        mapping = {}\n        for name in model.waiter_names:\n            mapping[xform_name(name)] = name\n        if waiter_name not in mapping:\n            raise ValueError(\"Waiter does not exist: %s\" % waiter_name)\n        return waiter.create_waiter_with_client(\n            mapping[waiter_name], model, self, loop=self._loop)",
    "docstring": "Returns an object that can wait for some condition.\n\n        :type waiter_name: str\n        :param waiter_name: The name of the waiter to get. See the waiters\n            section of the service docs for a list of available waiters.\n\n        :returns: The specified waiter object.\n        :rtype: botocore.waiter.Waiter"
  },
  {
    "code": "def _buckets_nearly_equal(a_dist, b_dist):\n    a_type, a_buckets = _detect_bucket_option(a_dist)\n    b_type, b_buckets = _detect_bucket_option(b_dist)\n    if a_type != b_type:\n        return False\n    elif a_type == u'linearBuckets':\n        return _linear_buckets_nearly_equal(a_buckets, b_buckets)\n    elif a_type == u'exponentialBuckets':\n        return _exponential_buckets_nearly_equal(a_buckets, b_buckets)\n    elif a_type == u'explicitBuckets':\n        return _explicit_buckets_nearly_equal(a_buckets, b_buckets)\n    else:\n        return False",
    "docstring": "Determines whether two `Distributions` are nearly equal.\n\n    Args:\n      a_dist (:class:`Distribution`): an instance\n      b_dist (:class:`Distribution`): another instance\n\n    Return:\n      boolean: `True` if the two instances are approximately equal, otherwise\n        False"
  },
  {
    "code": "def to_24bit_gray(mat: np.ndarray):\n    return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2)",
    "docstring": "returns a matrix that contains RGB channels, and colors scaled\n    from 0 to 255"
  },
  {
    "code": "def checkpoint_filepath(checkpoint, pm):\n    if isinstance(checkpoint, str):\n        if os.path.isabs(checkpoint):\n            if is_in_file_tree(checkpoint, pm.outfolder):\n                return checkpoint\n            else:\n                raise ValueError(\n                    \"Absolute checkpoint path '{}' is not in pipeline output \"\n                    \"folder '{}'\".format(checkpoint, pm.outfolder))\n        _, ext = os.path.splitext(checkpoint)\n        if ext == CHECKPOINT_EXTENSION:\n            return pipeline_filepath(pm, filename=checkpoint)\n    try:\n        pm = pm.manager\n    except AttributeError:\n        pass\n    chkpt_name = checkpoint_filename(checkpoint, pipeline_name=pm.name)\n    return pipeline_filepath(pm, filename=chkpt_name)",
    "docstring": "Create filepath for indicated checkpoint.\n\n    :param str | pypiper.Stage checkpoint: Pipeline phase/stage or one's name\n    :param pypiper.PipelineManager | pypiper.Pipeline pm: manager of a pipeline\n        instance, relevant for output folder path.\n    :return str: standardized checkpoint name for file, plus extension\n    :raise ValueError: if the checkpoint is given as absolute path that does\n        not point within pipeline output folder"
  },
  {
    "code": "def _get_coordinatenames(self):\n        validnames = (\"direction\", \"spectral\", \"linear\", \"stokes\", \"tabular\")\n        self._names = [\"\"] * len(validnames)\n        n = 0\n        for key in self._csys.keys():\n            for name in validnames:\n                if key.startswith(name):\n                    idx = int(key[len(name):])\n                    self._names[idx] = name\n                    n += 1\n        self._names = self._names[:n][::-1]\n        if len(self._names) == 0:\n            raise LookupError(\"Coordinate record doesn't contain valid coordinates\")",
    "docstring": "Create ordered list of coordinate names"
  },
  {
    "code": "def set(self, path, value):\n        _log.debug(\n            \"ZK: Setting {path} to {value}\".format(path=path, value=value)\n        )\n        return self.zk.set(path, value)",
    "docstring": "Sets and returns new data for the specified node."
  },
  {
    "code": "def get_obj(path):\n    if not isinstance(path, str):\n        return path\n    if path.startswith('.'):\n        raise TypeError('relative imports are not supported')\n    parts = path.split('.')\n    head, tail = parts[0], parts[1:]\n    obj = importlib.import_module(head)\n    for i, name in enumerate(tail):\n        try:\n            obj = getattr(obj, name)\n        except AttributeError:\n            module = '.'.join([head] + tail[:i])\n            try:\n                importlib.import_module(module)\n            except ImportError:\n                raise AttributeError(\n                    \"object '%s' has no attribute '%s'\" % (module, name))\n            else:\n                raise AttributeError(\n                    \"module '%s' has no attribute '%s'\" % (module, name))\n    return obj",
    "docstring": "Return obj for given dotted path.\n\n    Typical inputs for `path` are 'os' or 'os.path' in which case you get a\n    module; or 'os.path.exists' in which case you get a function from that\n    module.\n\n    Just returns the given input in case it is not a str.\n\n    Note: Relative imports not supported.\n    Raises ImportError or AttributeError as appropriate."
  },
  {
    "code": "def get_stats(self, request, context):\n        _log_request(request, context)\n        m = self.listener.memory\n        return clearly_pb2.StatsMessage(\n            task_count=m.task_count,\n            event_count=m.event_count,\n            len_tasks=len(m.tasks),\n            len_workers=len(m.workers)\n        )",
    "docstring": "Returns the server statistics."
  },
  {
    "code": "def retrieve_data(self):\n        url = self.config.get('url')\n        timeout = float(self.config.get('timeout', 10))\n        self.data = requests.get(url, verify=self.verify_ssl, timeout=timeout).content",
    "docstring": "retrieve data from an HTTP URL"
  },
  {
    "code": "def pretty_xml(data):\n    parsed_string = minidom.parseString(data.decode('utf-8'))\n    return parsed_string.toprettyxml(indent='\\t', encoding='utf-8')",
    "docstring": "Return a pretty formated xml"
  },
  {
    "code": "def get_urls(self):\n        urlpatterns = super(TranslatableAdmin, self).get_urls()\n        if not self._has_translatable_model():\n            return urlpatterns\n        else:\n            opts = self.model._meta\n            info = opts.app_label, opts.model_name\n            return [url(\n                r'^(.+)/change/delete-translation/(.+)/$',\n                self.admin_site.admin_view(self.delete_translation),\n                name='{0}_{1}_delete_translation'.format(*info)\n            )] + urlpatterns",
    "docstring": "Add a delete-translation view."
  },
  {
    "code": "def hash_tree(filepath: str) -> str:\n    if isfile(filepath):\n        return hash_file(filepath)\n    if isdir(filepath):\n        base_dir = filepath\n        md5 = hashlib.md5()\n        for root, dirs, files in walk(base_dir):\n            dirs.sort()\n            for fname in sorted(files):\n                filepath = join(root, fname)\n                md5.update(relpath(filepath, base_dir)\n                           .replace('\\\\', '/').encode('utf8'))\n                acc_hash(filepath, md5)\n        return md5.hexdigest()\n    return None",
    "docstring": "Return the hexdigest MD5 hash of file or directory at `filepath`.\n\n    If file - just hash file content.\n    If directory - walk the directory, and accumulate hashes of all the\n    relative paths + contents of files under the directory."
  },
  {
    "code": "def process_event(self, event):\n        new_event = event\n        if self._absolute:\n            new_event.y -= self._canvas.start_line\n        if self.is_mouse_over(new_event) and event.buttons != 0:\n            self._set_pos((new_event.y - self._y) / (self._height - 1))\n            return True\n        return False",
    "docstring": "Handle input on the scroll bar.\n\n        :param event: the event to be processed.\n\n        :returns: True if the scroll bar handled the event."
  },
  {
    "code": "def findentry(self, item):\n        if not isinstance(item, str):\n            raise TypeError(\n                'Members of this object must be strings. '\n                'You supplied \\\"%s\\\"' % type(item))\n        for entry in self:\n            if item.lower() == entry.lower():\n                return entry\n        return None",
    "docstring": "A caseless way of checking if an item is in the list or not.\n        It returns None or the entry."
  },
  {
    "code": "def _try_import(module_name):\n  try:\n    mod = importlib.import_module(module_name)\n    return mod\n  except ImportError:\n    err_msg = (\"Tried importing %s but failed. See setup.py extras_require. \"\n               \"The dataset you are trying to use may have additional \"\n               \"dependencies.\")\n    utils.reraise(err_msg)",
    "docstring": "Try importing a module, with an informative error message on failure."
  },
  {
    "code": "def get_data(conn_objs, providers):\n    cld_svc_map = {\"aws\": nodes_aws,\n                   \"azure\": nodes_az,\n                   \"gcp\": nodes_gcp,\n                   \"alicloud\": nodes_ali}\n    sys.stdout.write(\"\\rCollecting Info:  \")\n    sys.stdout.flush()\n    busy_obj = busy_disp_on()\n    collec_fn = [[cld_svc_map[x.rstrip('1234567890')], conn_objs[x]]\n                 for x in providers]\n    ngroup = Group()\n    node_list = []\n    node_list = ngroup.map(get_nodes, collec_fn)\n    ngroup.join()\n    busy_disp_off(dobj=busy_obj)\n    sys.stdout.write(\"\\r                                                 \\r\")\n    sys.stdout.write(\"\\033[?25h\")\n    sys.stdout.flush()\n    return node_list",
    "docstring": "Refresh node data using existing connection-objects."
  },
  {
    "code": "def linkChunk(key, chunk):\n    linkType = chunk[1].strip().split()[0]\n    if linkType == 'DX':\n        result = xSectionLink(chunk)\n    elif linkType == 'STRUCTURE':\n        result = structureLink(chunk)\n    elif linkType in ('RESERVOIR', 'LAKE'):\n        result = reservoirLink(chunk)\n    return result",
    "docstring": "Parse LINK Chunk Method"
  },
  {
    "code": "def DeleteNotifications(self, session_ids, start=None, end=None):\n    if not session_ids:\n      return\n    for session_id in session_ids:\n      if not isinstance(session_id, rdfvalue.SessionID):\n        raise RuntimeError(\n            \"Can only delete notifications for rdfvalue.SessionIDs.\")\n    if start is None:\n      start = 0\n    else:\n      start = int(start)\n    if end is None:\n      end = self.frozen_timestamp or rdfvalue.RDFDatetime.Now()\n    for queue, ids in iteritems(\n        collection.Group(session_ids, lambda session_id: session_id.Queue())):\n      queue_shards = self.GetAllNotificationShards(queue)\n      self.data_store.DeleteNotifications(queue_shards, ids, start, end)",
    "docstring": "This deletes the notification when all messages have been processed."
  },
  {
    "code": "def dominant_sharp_ninth(note):\n    res = dominant_ninth(note)\n    res[4] = notes.augment(intervals.major_second(note))\n    return res",
    "docstring": "Build a dominant sharp ninth chord on note.\n\n    Example:\n    >>> dominant_ninth('C')\n    ['C', 'E', 'G', 'Bb', 'D#']"
  },
  {
    "code": "def _make_sampling_sequence(n):\n    seq = list(range(5))\n    i = 50\n    while len(seq) < n:\n        seq.append(i)\n        i += 50\n    return seq",
    "docstring": "Return a list containing the proposed call event sampling sequence.\n\n    Return events are paired with call events and not counted separately.\n\n    This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc.\n\n    The total list size is n."
  },
  {
    "code": "def fractional_from_cartesian(coordinate, lattice_array):\n    deorthogonalisation_M = np.matrix(np.linalg.inv(lattice_array))\n    fractional = deorthogonalisation_M * coordinate.reshape(-1, 1)\n    return np.array(fractional.reshape(1, -1))",
    "docstring": "Return a fractional coordinate from a cartesian one."
  },
  {
    "code": "def spellcheck(contents, technical_terms=None, spellcheck_cache=None):\n    contents = spelling.filter_nonspellcheckable_tokens(contents)\n    contents = _filter_disabled_regions(contents)\n    lines = contents.splitlines(True)\n    user_words, valid_words = valid_words_dictionary.create(spellcheck_cache)\n    technical_words = technical_words_dictionary.create(technical_terms,\n                                                        spellcheck_cache)\n    return sorted([e for e in spellcheck_region(lines,\n                                                valid_words,\n                                                technical_words,\n                                                user_words)])",
    "docstring": "Run spellcheck on the contents of a file.\n\n    :technical_terms: is a path to a file containing a list of \"technical\"\n    terms. These may be symbols as collected from files by using\n    the generic linter or other such symbols. If a symbol-like term is\n    used within contents and it does not appear in :technical_terms: then\n    an error will result.\n\n    :spellcheck_cache: is a path to a directory where graph files generated\n    by the spellchecking engine should be stored. It is used for caching\n    purposes between invocations, since generating the spellchecking\n    graph is an expensive operation which can take a few seconds to complete."
  },
  {
    "code": "def setting(self, setting_name, default=None):\n        keys = setting_name.split(\".\")\n        config = self._content\n        for key in keys:\n            if key not in config:\n                return default\n            config = config[key]\n        return config",
    "docstring": "Retrieve a setting value."
  },
  {
    "code": "def validate_value(self, string_value):\n        specs = self.specs\n        if 'type' in specs:\n            value = specs['type'](string_value)\n        else:\n            value = string_value\n        if 'min' in specs and value < specs['min']:\n            raise ValueError\n        if 'max' in specs and value > specs['max']:\n            raise ValueError\n        if 'valid' in specs and value not in specs['valid']:\n            raise ValueError\n        return value",
    "docstring": "Validate that a value match the Property specs."
  },
  {
    "code": "def redirectLoggerStreamHandlers(oldStream, newStream):\n    for handler in list(logger.handlers):\n        if handler.stream == oldStream:\n            handler.close()\n            logger.removeHandler(handler)\n    for handler in logger.handlers:\n        if handler.stream == newStream:\n           return\n    logger.addHandler(logging.StreamHandler(newStream))",
    "docstring": "Redirect the stream of a stream handler to a different stream"
  },
  {
    "code": "def summary(args):\n    from jcvi.graphics.histogram import loghistogram\n    p = OptionParser(summary.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(not p.print_help())\n    clstrfile, = args\n    cf = ClstrFile(clstrfile)\n    data = list(cf.iter_sizes())\n    loghistogram(data, summary=True)",
    "docstring": "%prog summary cdhit.clstr\n\n    Parse cdhit.clstr file to get distribution of cluster sizes."
  },
  {
    "code": "def _set_launcher_property(self, driver_arg_key, spark_property_key):\n        value = self._spark_launcher_args.get(driver_arg_key, self.conf._conf_dict.get(spark_property_key))\n        if value:\n            self._spark_launcher_args[driver_arg_key] = value\n            self.conf[spark_property_key] = value",
    "docstring": "Handler for a special property that exists in both the launcher arguments and the spark conf dictionary.\n\n        This will use the launcher argument if set falling back to the spark conf argument.  If neither are set this is\n        a noop (which means that the standard spark defaults will be used).\n\n        Since `spark.driver.memory` (eg) can be set erroneously by a user on the standard spark conf, we want to be able\n        to use that value if present. If we do not have this fall-back behavior then these settings are IGNORED when\n        starting up the spark driver JVM under client mode (standalone, local, yarn-client or mesos-client).\n\n        Parameters\n        ----------\n        driver_arg_key : string\n            Eg: \"driver-memory\"\n        spark_property_key : string\n            Eg: \"spark.driver.memory\""
  },
  {
    "code": "def order_by_header(table, headers):\n    ordered_table = []\n    for row in table:\n        row = {k:v for k,v in row.items() if k in headers}\n        for h in headers:\n            if h not in row:\n                row[h] = ''\n        ordered_row = OrderedDict(sorted(row.items(),\n                                         key=lambda x:headers.index(x[0])))\n        ordered_table.append(ordered_row)\n    return ordered_table",
    "docstring": "Convert a list of dicts to a list or OrderedDicts ordered by headers"
  },
  {
    "code": "def releaseNetToMs():\n    a = TpPd(pd=0x3)\n    b = MessageType(mesType=0x2d)\n    c = CauseHdr(ieiC=0x08, eightBitC=0x0)\n    d = CauseHdr(ieiC=0x08, eightBitC=0x0)\n    e = FacilityHdr(ieiF=0x1C, eightBitF=0x0)\n    f = UserUserHdr(ieiUU=0x7E, eightBitUU=0x0)\n    packet = a / b / c / d / e / f\n    return packet",
    "docstring": "RELEASE Section 9.3.18.1"
  },
  {
    "code": "def make_chain(fns):\n    chain = lambda x: x\n    for fn in reversed(fns):\n        chain = fn(chain)\n    def validator(v):\n        try:\n            return chain(v)\n        except ReturnEarly:\n            return v\n    return validator",
    "docstring": "Take a list of chainable validators and return a chained validator\n\n    The functions should be decorated with ``chainable`` decorator.\n\n    Any exceptions raised by any of the validators are propagated except for\n    ``ReturnEarly`` exception which is trapped. When ``ReturnEarly`` exception\n    is trapped, the original value passed to the chained validator is returned\n    as is."
  },
  {
    "code": "def _run_bcbio_variation(vrn_file, rm_file, rm_interval_file, base_dir, sample, caller, data):\n    val_config_file = _create_validate_config_file(vrn_file, rm_file, rm_interval_file,\n                                                   base_dir, data)\n    work_dir = os.path.join(base_dir, \"work\")\n    out = {\"summary\": os.path.join(work_dir, \"validate-summary.csv\"),\n           \"grading\": os.path.join(work_dir, \"validate-grading.yaml\"),\n           \"discordant\": os.path.join(work_dir, \"%s-eval-ref-discordance-annotate.vcf\" % sample)}\n    if not utils.file_exists(out[\"discordant\"]) or not utils.file_exists(out[\"grading\"]):\n        bcbio_variation_comparison(val_config_file, base_dir, data)\n    out[\"concordant\"] = filter(os.path.exists,\n                                [os.path.join(work_dir, \"%s-%s-concordance.vcf\" % (sample, x))\n                                 for x in [\"eval-ref\", \"ref-eval\"]])[0]\n    return out",
    "docstring": "Run validation of a caller against the truth set using bcbio.variation."
  },
  {
    "code": "def rotate(self, shift):\n        self.child_corners.values[:] = np.roll(self.child_corners\n                                                 .values, shift, axis=0)\n        self.update_transform()",
    "docstring": "Rotate 90 degrees clockwise `shift` times.  If `shift` is negative,\n        rotate counter-clockwise."
  },
  {
    "code": "def _get_kind_name(param_type, is_list):\n    if issubclass(param_type, bool):\n      typename = 'bool'\n    elif issubclass(param_type, six.integer_types):\n      typename = 'int64'\n    elif issubclass(param_type, (six.string_types, six.binary_type)):\n      typename = 'bytes'\n    elif issubclass(param_type, float):\n      typename = 'float'\n    else:\n      raise ValueError('Unsupported parameter type: %s' % str(param_type))\n    suffix = 'list' if is_list else 'value'\n    return '_'.join([typename, suffix])",
    "docstring": "Returns the field name given parameter type and is_list.\n\n    Args:\n      param_type: Data type of the hparam.\n      is_list: Whether this is a list.\n\n    Returns:\n      A string representation of the field name.\n\n    Raises:\n      ValueError: If parameter type is not recognized."
  },
  {
    "code": "def _GetSerializedPartitionList(self):\n        partition_list = list()\n        for part in self.partitions:\n            partition_list.append((part.node, unpack(\"<L\", part.hash_value)[0]))\n        return partition_list",
    "docstring": "Gets the serialized version of the ConsistentRing. \n        Added this helper for the test code."
  },
  {
    "code": "def get_line_number(line_map, offset):\n    for lineno, line_offset in enumerate(line_map, start=1):\n        if line_offset > offset:\n            return lineno\n    return -1",
    "docstring": "Find a line number, given a line map and a character offset."
  },
  {
    "code": "def create_xml_path(path, **kwargs):\n    try:\n        with salt.utils.files.fopen(path, 'r') as fp_:\n            return create_xml_str(\n                salt.utils.stringutils.to_unicode(fp_.read()),\n                **kwargs\n            )\n    except (OSError, IOError):\n        return False",
    "docstring": "Start a transient domain based on the XML-file path passed to the function\n\n    :param path: path to a file containing the libvirt XML definition of the domain\n    :param connection: libvirt connection URI, overriding defaults\n\n        .. versionadded:: 2019.2.0\n    :param username: username to connect with, overriding defaults\n\n        .. versionadded:: 2019.2.0\n    :param password: password to connect with, overriding defaults\n\n        .. versionadded:: 2019.2.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' virt.create_xml_path <path to XML file on the node>"
  },
  {
    "code": "def encode_safely(self, data):\n        encoder = self.base_encoder\n        result = settings.null\n        try:\n            result = encoder(pickle.dumps(data))\n        except:\n            warnings.warn(\"Data could not be serialized.\", RuntimeWarning)\n        return result",
    "docstring": "Encode the data."
  },
  {
    "code": "def get_response_attribute_filter(self, template_filter, template_model=None):\n        if template_filter is None:\n            return None\n        if 'Prestans-Response-Attribute-List' not in self.headers:\n            return None\n        attribute_list_str = self.headers['Prestans-Response-Attribute-List']\n        json_deserializer = deserializer.JSON()\n        attribute_list_dictionary = json_deserializer.loads(attribute_list_str)\n        attribute_filter = AttributeFilter(\n            from_dictionary=attribute_list_dictionary,\n            template_model=template_model\n        )\n        evaluated_filter = attribute_filter.conforms_to_template_filter(template_filter)\n        return evaluated_filter",
    "docstring": "Prestans-Response-Attribute-List can contain a client's requested\n        definition for attributes required in the response. This should match\n        the response_attribute_filter_template?\n\n        :param template_filter:\n        :param template_model: the expected model that this filter corresponds to\n        :return:\n        :rtype: None | AttributeFilter"
  },
  {
    "code": "def bake(self):\n        options = self.options\n        default_exclude_list = options.pop('default_exclude')\n        options_exclude_list = options.pop('exclude')\n        excludes = default_exclude_list + options_exclude_list\n        x_list = options.pop('x')\n        exclude_args = ['--exclude={}'.format(exclude) for exclude in excludes]\n        x_args = tuple(('-x', x) for x in x_list)\n        self._ansible_lint_command = sh.ansible_lint.bake(\n            options,\n            exclude_args,\n            sum(x_args, ()),\n            self._playbook,\n            _env=self.env,\n            _out=LOG.out,\n            _err=LOG.error)",
    "docstring": "Bake an `ansible-lint` command so it's ready to execute and returns\n        None.\n\n        :return: None"
  },
  {
    "code": "def reopen(args):\n    if not args.isadmin:\n        return \"Nope, not gonna do it.\"\n    msg = args.msg.split()\n    if not msg:\n        return \"Syntax: !poll reopen <pollnum>\"\n    if not msg[0].isdigit():\n        return \"Not a valid positve integer.\"\n    pid = int(msg[0])\n    poll = get_open_poll(args.session, pid)\n    if poll is None:\n        return \"That poll doesn't exist or has been deleted!\"\n    poll.active = 1\n    return \"Poll %d reopened!\" % pid",
    "docstring": "reopens a closed poll."
  },
  {
    "code": "def run_deferred(self, deferred):\n        for handler, scope, offset in deferred:\n            self.scope_stack = scope\n            self.offset = offset\n            handler()",
    "docstring": "Run the callables in deferred using their associated scope stack."
  },
  {
    "code": "def get_version(self):\n        _, version = misc.get_version(self.confdir)\n        if version is None:\n            return \"Can't get the version.\"\n        else:\n            return \"cslbot - %s\" % version",
    "docstring": "Get the version."
  },
  {
    "code": "def state_args(id_, state, high):\n    args = set()\n    if id_ not in high:\n        return args\n    if state not in high[id_]:\n        return args\n    for item in high[id_][state]:\n        if not isinstance(item, dict):\n            continue\n        if len(item) != 1:\n            continue\n        args.add(next(iter(item)))\n    return args",
    "docstring": "Return a set of the arguments passed to the named state"
  },
  {
    "code": "def set(self) -> None:\n        if not self._value:\n            self._value = True\n            for fut in self._waiters:\n                if not fut.done():\n                    fut.set_result(None)",
    "docstring": "Set the internal flag to ``True``. All waiters are awakened.\n\n        Calling `.wait` once the flag is set will not block."
  },
  {
    "code": "def build_select_fields(self):\n        field_sql = []\n        for table in self.tables:\n            field_sql += table.get_field_sql()\n        for join_item in self.joins:\n            field_sql += join_item.right_table.get_field_sql()\n        sql = 'SELECT {0}{1} '.format(self.get_distinct_sql(), ', '.join(field_sql))\n        return sql",
    "docstring": "Generates the sql for the SELECT portion of the query\n\n        :return: the SELECT portion of the query\n        :rtype: str"
  },
  {
    "code": "def patch(self, patch):\n        data = apply_patch(dict(self), patch)\n        return self.__class__(data, model=self.model)",
    "docstring": "Patch record metadata.\n\n        :params patch: Dictionary of record metadata.\n        :returns: A new :class:`Record` instance."
  },
  {
    "code": "def set(self, value = True):\n        value = value in (True,1) or ( (isinstance(value, str) or (sys.version < '3' and isinstance(value, unicode))) and (value.lower() in (\"1\",\"yes\",\"true\",\"enabled\")))\n        return super(BooleanParameter,self).set(value)",
    "docstring": "Set the boolean parameter"
  },
  {
    "code": "def predict(self, sequences, y=None):\n        predictions = []\n        check_iter_of_sequences(sequences, allow_trajectory=self._allow_trajectory)\n        for X in sequences:\n            predictions.append(self.partial_predict(X))\n        return predictions",
    "docstring": "Predict the closest cluster each sample in each sequence in\n        sequences belongs to.\n\n        In the vector quantization literature, `cluster_centers_` is called\n        the code book and each value returned by `predict` is the index of\n        the closest code in the code book.\n\n        Parameters\n        ----------\n        sequences : list of array-like, each of shape [sequence_length, n_features]\n            A list of multivariate timeseries. Each sequence may have\n            a different length, but they all must have the same number\n            of features.\n\n        Returns\n        -------\n        Y : list of arrays, each of shape [sequence_length,]\n            Index of the closest center each sample belongs to."
  },
  {
    "code": "def _strip_value(value, lookup='exact'):\n    if lookup == 'in':\n        stripped_value = [_strip_object(el) for el in value]\n    else:\n        stripped_value = _strip_object(value)\n    return stripped_value",
    "docstring": "Helper function to remove the branch and version information from the given value,\n    which could be a single object or a list."
  },
  {
    "code": "def set_dtreat_indt(self, t=None, indt=None):\n        lC = [indt is not None, t is not None]\n        if all(lC):\n            msg = \"Please provide either t or indt (or none)!\"\n            raise Exception(msg)\n        if lC[1]:\n            ind = self.select_t(t=t, out=bool)\n        else:\n            ind = _format_ind(indt, n=self._ddataRef['nt'])\n        self._dtreat['indt'] = ind\n        self._ddata['uptodate'] = False",
    "docstring": "Store the desired index array for the time vector\n\n        If an array of indices (refering to self.ddataRef['t'] is not provided,\n        uses self.select_t(t=t) to produce it"
  },
  {
    "code": "def close(self):\n        if self._device is not None:\n            ibsta = self._lib.ibonl(self._device, 0)\n            self._check_status(ibsta)\n            self._device = None",
    "docstring": "Closes the gpib transport."
  },
  {
    "code": "def _string_width(string, *, _IS_ASCII=_IS_ASCII):\n    match = _IS_ASCII.match(string)\n    if match:\n        return match.endpos\n    UNICODE_WIDE_CHAR_TYPE = 'WFA'\n    width = 0\n    func = unicodedata.east_asian_width\n    for char in string:\n        width += 2 if func(char) in UNICODE_WIDE_CHAR_TYPE else 1\n    return width",
    "docstring": "Returns string's width."
  },
  {
    "code": "def get_matchers():\n    from . import matchers\n    def is_matcher_func(member):\n        return inspect.isfunction(member) and member.__name__.endswith(\"_matcher\")\n    members = inspect.getmembers(matchers, is_matcher_func)\n    for name, func in members:\n        yield func",
    "docstring": "Get matcher functions from treeherder.autoclassify.matchers\n\n    We classify matchers as any function treeherder.autoclassify.matchers with\n    a name ending in _matcher.  This is currently overkill but protects against\n    the unwarey engineer adding new functions to the matchers module that\n    shouldn't be treated as matchers."
  },
  {
    "code": "def show_data_file(fname):\n    txt = '<H2>' + fname + '</H2>'\n    print (fname)\n    txt += web.read_csv_to_html_table(fname, 'Y')\n    txt += '</div>\\n'\n    return txt",
    "docstring": "shows a data file in CSV format - all files live in CORE folder"
  },
  {
    "code": "def create_toolbutton(entries, parent=None):\n    btn = QtGui.QToolButton(parent)\n    menu = QtGui.QMenu()\n    actions = []\n    for label, slot in entries:\n        action = add_menu_action(menu, label, slot)\n        actions.append(action)\n    btn.setPopupMode(QtGui.QToolButton.MenuButtonPopup)\n    btn.setDefaultAction(actions[0])\n    btn.setMenu(menu)\n    return btn, actions",
    "docstring": "Create a toolbutton.\n\n    Args:\n        entries: List of (label, slot) tuples.\n\n    Returns:\n        `QtGui.QToolBar`."
  },
  {
    "code": "def redirect_to_unlocalized(*args, **kwargs):\n    endpoint = request.endpoint.replace('_redirect', '')\n    kwargs = multi_to_dict(request.args)\n    kwargs.update(request.view_args)\n    kwargs.pop('lang_code', None)\n    return redirect(url_for(endpoint, **kwargs))",
    "docstring": "Redirect lang-prefixed urls to no prefixed URL."
  },
  {
    "code": "def polygon(self):\n            points = []\n            for fp in self.points[1:]:\n                    points.append((fp.lat, fp.lng))\n            return points",
    "docstring": "return a polygon for the fence"
  },
  {
    "code": "def register_event(self, event):\n        self.log('Registering event hook:', event.cmd, event.thing,\n                 pretty=True, lvl=verbose)\n        self.hooks[event.cmd] = event.thing",
    "docstring": "Registers a new command line interface event hook as command"
  },
  {
    "code": "def find(basedir, string):\n    matches = []\n    for root, dirnames, filenames in os.walk(basedir):\n        for filename in fnmatch.filter(filenames, string):\n            matches.append(os.path.join(root, filename))\n    return matches",
    "docstring": "walk basedir and return all files matching string"
  },
  {
    "code": "def _copy_chunk(src, dst, length):\n    \"Copy length bytes from file src to file dst.\"\n    BUFSIZE = 128 * 1024\n    while length > 0:\n        l = min(BUFSIZE, length)\n        buf = src.read(l)\n        assert len(buf) == l\n        dst.write(buf)\n        length -= l",
    "docstring": "Copy length bytes from file src to file dst."
  },
  {
    "code": "def parse_rest_response(self, records, rowcount, row_type=list):\n        if self.is_plain_count:\n            assert list(records) == []\n            yield rowcount\n        else:\n            while True:\n                for row_deep in records:\n                    assert self.is_aggregation == (row_deep['attributes']['type'] == 'AggregateResult')\n                    row_flat = self._make_flat(row_deep, path=(), subroots=self.subroots)\n                    assert all(not isinstance(x, dict) or x['done'] for x in row_flat)\n                    if issubclass(row_type, dict):\n                        yield {k: fix_data_type(row_flat[k.lower()]) for k in self.aliases}\n                    else:\n                        yield [fix_data_type(row_flat[k.lower()]) for k in self.aliases]\n                break",
    "docstring": "Parse the REST API response to DB API cursor flat response"
  },
  {
    "code": "def _layout(self):\n        if not self.hist:\n            self.ax\n            return\n        if make_axes_locatable is None:\n            raise YellowbrickValueError((\n                \"joint plot histograms requires matplotlib 2.0.2 or greater \"\n                \"please upgrade matplotlib or set hist=False on the visualizer\"\n            ))\n        divider = make_axes_locatable(self.ax)\n        self._xhax = divider.append_axes(\"top\", size=1, pad=0.1, sharex=self.ax)\n        self._yhax = divider.append_axes(\"right\", size=1, pad=0.1, sharey=self.ax)\n        self._xhax.xaxis.tick_top()\n        self._yhax.yaxis.tick_right()\n        self._xhax.grid(False, axis='y')\n        self._yhax.grid(False, axis='x')",
    "docstring": "Creates the grid layout for the joint plot, adding new axes for the histograms\n        if necessary and modifying the aspect ratio. Does not modify the axes or the\n        layout if self.hist is False or None."
  },
  {
    "code": "def cross(self, vector):\n        return Vector((self.y * vector.z - self.z * vector.y),\n                      (self.z * vector.x - self.x * vector.z),\n                      (self.x * vector.y - self.y * vector.x))",
    "docstring": "Return a Vector instance as the cross product of two vectors"
  },
  {
    "code": "def validate_property_directives(directives):\n    for directive_name in six.iterkeys(directives):\n        if directive_name in VERTEX_ONLY_DIRECTIVES:\n            raise GraphQLCompilationError(\n                u'Found vertex-only directive {} set on property.'.format(directive_name))",
    "docstring": "Validate the directives that appear at a property field."
  },
  {
    "code": "def create_user(self, username, password, admin=False):\n        text = \"CREATE USER {0} WITH PASSWORD {1}\".format(\n            quote_ident(username), quote_literal(password))\n        if admin:\n            text += ' WITH ALL PRIVILEGES'\n        self.query(text, method=\"POST\")",
    "docstring": "Create a new user in InfluxDB.\n\n        :param username: the new username to create\n        :type username: str\n        :param password: the password for the new user\n        :type password: str\n        :param admin: whether the user should have cluster administration\n            privileges or not\n        :type admin: boolean"
  },
  {
    "code": "def _string_to_byte_list(self, data):\n        bytes_length = 16\n        m = self.digest()\n        m.update(str.encode(data))\n        hex_digest = m.hexdigest()\n        return list(int(hex_digest[num * 2:num * 2 + 2], bytes_length)\n                    for num in range(bytes_length))",
    "docstring": "Creates a hex digest of the input string given to create the image,\n        if it's not already hexadecimal\n\n        Returns:\n            Length 16 list of rgb value range integers\n            (each representing a byte of the hex digest)"
  },
  {
    "code": "def setup(self,\n            artifacts, use_tsk,\n            reason, grr_server_url, grr_username, grr_password, approvers=None,\n            verify=True):\n    super(GRRHuntArtifactCollector, self).setup(\n        reason, grr_server_url, grr_username, grr_password,\n        approvers=approvers, verify=verify)\n    self.artifacts = [item.strip() for item in artifacts.strip().split(',')]\n    if not artifacts:\n      self.state.add_error('No artifacts were specified.', critical=True)\n    self.use_tsk = use_tsk",
    "docstring": "Initializes a GRR Hunt artifact collector.\n\n    Args:\n      artifacts: str, comma-separated list of GRR-defined artifacts.\n      use_tsk: toggle for use_tsk flag.\n      reason: justification for GRR access.\n      grr_server_url: GRR server URL.\n      grr_username: GRR username.\n      grr_password: GRR password.\n      approvers: str, comma-separated list of GRR approval recipients.\n      verify: boolean, whether to verify the GRR server's x509 certificate."
  },
  {
    "code": "def match_grade_system_id(self, grade_system_id, match):\n        self._add_match('gradeSystemId', str(grade_system_id), bool(match))",
    "docstring": "Sets the grade system ``Id`` for this query.\n\n        arg:    grade_system_id (osid.id.Id): a grade system ``Id``\n        arg:    match (boolean): ``true`` for a positive match,\n                ``false`` for a negative match\n        raise:  NullArgument - ``grade_system_id`` is ``null``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def is_equivalent(self, other, ignore=False):\n        def is_equivalent_to_list_of_ipachars(other):\n            my_ipa_chars = self.canonical_representation.ipa_chars\n            if len(my_ipa_chars) != len(other):\n                return False\n            for i in range(len(my_ipa_chars)):\n                if not my_ipa_chars[i].is_equivalent(other[i]):\n                    return False\n            return True\n        if is_unicode_string(other):\n            try:\n                return is_equivalent_to_list_of_ipachars(IPAString(unicode_string=other, ignore=ignore).ipa_chars)\n            except:\n                return False\n        if is_list_of_ipachars(other):\n            try:\n                return is_equivalent_to_list_of_ipachars(other) \n            except:\n                return False\n        if isinstance(other, IPAString):\n            return is_equivalent_to_list_of_ipachars(other.canonical_representation.ipa_chars)\n        return False",
    "docstring": "Return ``True`` if the IPA string is equivalent to the ``other`` object.\n\n        The ``other`` object can be:\n\n        1. a Unicode string,\n        2. a list of IPAChar objects, and\n        3. another IPAString.\n\n        :param variant other: the object to be compared against\n        :param bool ignore: if other is a Unicode string, ignore Unicode characters not IPA valid\n        :rtype: bool"
  },
  {
    "code": "def cart2pol(x, y):\n    theta = np.arctan2(y, x)\n    rho = np.hypot(x, y)\n    return theta, rho",
    "docstring": "Cartesian to Polar coordinates conversion."
  },
  {
    "code": "def decode_base64(data: str) -> bytes:\n    missing_padding = len(data) % 4\n    if missing_padding != 0:\n        data += \"=\" * (4 - missing_padding)\n    return base64.decodebytes(data.encode(\"utf-8\"))",
    "docstring": "Decode base64, padding being optional.\n\n    :param data: Base64 data as an ASCII byte string\n    :returns: The decoded byte string."
  },
  {
    "code": "def approx_eq(val: Any, other: Any, *, atol: Union[int, float] = 1e-8) -> bool:\n    approx_eq_getter = getattr(val, '_approx_eq_', None)\n    if approx_eq_getter is not None:\n        result = approx_eq_getter(other, atol)\n        if result is not NotImplemented:\n            return result\n    other_approx_eq_getter = getattr(other, '_approx_eq_', None)\n    if other_approx_eq_getter is not None:\n        result = other_approx_eq_getter(val, atol)\n        if result is not NotImplemented:\n            return result\n    if isinstance(val, (int, float)):\n        if not isinstance(other, (int, float)):\n            return False\n        return _isclose(val, other, atol=atol)\n    if isinstance(val, complex):\n        if not isinstance(other, complex):\n            return False\n        return _isclose(val, other, atol=atol)\n    result = _approx_eq_iterables(val, other, atol=atol)\n    if result is NotImplemented:\n        return val == other\n    return result",
    "docstring": "Approximately compares two objects.\n\n    If `val` implements SupportsApproxEquality protocol then it is invoked and\n    takes precedence over all other checks:\n     - For primitive numeric types `int` and `float` approximate equality is\n       delegated to math.isclose().\n     - For complex primitive type the real and imaginary parts are treated\n       independently and compared using math.isclose().\n     - For `val` and `other` both iterable of the same length, consecutive\n       elements are compared recursively. Types of `val` and `other` does not\n       necessarily needs to match each other. They just need to be iterable and\n       have the same structure.\n\n    Args:\n        val: Source object for approximate comparison.\n        other: Target object for approximate comparison.\n        atol: The minimum absolute tolerance. See np.isclose() documentation for\n              details. Defaults to 1e-8 which matches np.isclose() default\n              absolute tolerance.\n\n    Returns:\n        True if objects are approximately equal, False otherwise."
  },
  {
    "code": "def inclusion_tag(self, name, context_class=Context, takes_context=False):\n        def tag_decorator(tag_func):\n            @wraps(tag_func)\n            def tag_wrapper(parser, token):\n                class InclusionTagNode(template.Node):\n                    def render(self, context):\n                        if not getattr(self, \"nodelist\", False):\n                            try:\n                                request = context[\"request\"]\n                            except KeyError:\n                                t = get_template(name)\n                            else:\n                                ts = templates_for_device(request, name)\n                                t = select_template(ts)\n                            self.template = t\n                        parts = [template.Variable(part).resolve(context)\n                                 for part in token.split_contents()[1:]]\n                        if takes_context:\n                            parts.insert(0, context)\n                        result = tag_func(*parts)\n                        autoescape = context.autoescape\n                        context = context_class(result, autoescape=autoescape)\n                        return self.template.render(context)\n                return InclusionTagNode()\n            return self.tag(tag_wrapper)\n        return tag_decorator",
    "docstring": "Replacement for Django's ``inclusion_tag`` which looks up device\n        specific templates at render time."
  },
  {
    "code": "def run_checks(number_samples, k_choices):\n        assert isinstance(k_choices, int), \\\n            \"Number of optimal trajectories should be an integer\"\n        if k_choices < 2:\n            raise ValueError(\n                \"The number of optimal trajectories must be set to 2 or more.\")\n        if k_choices >= number_samples:\n            msg = \"The number of optimal trajectories should be less than the \\\n                    number of samples\"\n            raise ValueError(msg)",
    "docstring": "Runs checks on `k_choices`"
  },
  {
    "code": "def remove_unused_links(self, used):\n        unused = []\n        self._execute(\"SELECT * FROM {}\".format(self.LINK_STATE_TABLE))\n        for row in self.cursor:\n            relpath, inode, mtime = row\n            inode = self._from_sqlite(inode)\n            path = os.path.join(self.root_dir, relpath)\n            if path in used:\n                continue\n            if not os.path.exists(path):\n                continue\n            actual_inode = get_inode(path)\n            actual_mtime, _ = get_mtime_and_size(path)\n            if inode == actual_inode and mtime == actual_mtime:\n                logger.debug(\"Removing '{}' as unused link.\".format(path))\n                remove(path)\n                unused.append(relpath)\n        for relpath in unused:\n            cmd = 'DELETE FROM {} WHERE path = \"{}\"'\n            self._execute(cmd.format(self.LINK_STATE_TABLE, relpath))",
    "docstring": "Removes all saved links except the ones that are used.\n\n        Args:\n            used (list): list of used links that should not be removed."
  },
  {
    "code": "def show(self, baseAppInstance):\n        self.from_dict_to_fields(self.configDict)\n        super(ProjectConfigurationDialog, self).show(baseAppInstance)",
    "docstring": "Allows to show the widget as root window"
  },
  {
    "code": "def getDataAtOffset(self, offset, size):\n        data = str(self)\n        return data[offset:offset+size]",
    "docstring": "Gets binary data at a given offset.\n        \n        @type offset: int\n        @param offset: The offset to get the data from.\n        \n        @type size: int\n        @param size: The size of the data to be obtained.\n        \n        @rtype: str\n        @return: The data obtained at the given offset."
  },
  {
    "code": "def _parse_jing_output(output):\n    output = output.strip()\n    values = [_parse_jing_line(l) for l in output.split('\\n') if l]\n    return tuple(values)",
    "docstring": "Parse the jing output into a tuple of line, column, type and message."
  },
  {
    "code": "def getExpressionLevels(\n            self, threshold=0.0, names=[], startIndex=0, maxResults=0):\n        rnaQuantificationId = self.getLocalId()\n        with self._db as dataSource:\n            expressionsReturned = dataSource.searchExpressionLevelsInDb(\n                rnaQuantificationId,\n                names=names,\n                threshold=threshold,\n                startIndex=startIndex,\n                maxResults=maxResults)\n            expressionLevels = [\n                SqliteExpressionLevel(self, expressionEntry) for\n                expressionEntry in expressionsReturned]\n            return expressionLevels",
    "docstring": "Returns the list of ExpressionLevels in this RNA Quantification."
  },
  {
    "code": "def detect(byte_str):\n    if not isinstance(byte_str, bytearray):\n        if not isinstance(byte_str, bytes):\n            raise TypeError('Expected object of type bytes or bytearray, got: '\n                            '{0}'.format(type(byte_str)))\n        else:\n            byte_str = bytearray(byte_str)\n    detector = UniversalDetector()\n    detector.feed(byte_str)\n    return detector.close()",
    "docstring": "Detect the encoding of the given byte string.\n\n    :param byte_str:     The byte sequence to examine.\n    :type byte_str:      ``bytes`` or ``bytearray``"
  },
  {
    "code": "def security_label_pivot(self, security_label_resource):\n        resource = self.copy()\n        resource._request_uri = '{}/{}'.format(\n            security_label_resource.request_uri, resource._request_uri\n        )\n        return resource",
    "docstring": "Pivot point on security labels for this resource.\n\n        This method will return all *resources* (group, indicators, task,\n        victims, etc) for this resource that have the provided security\n        label applied.\n\n        **Example Endpoints URI's**\n\n        +--------------+----------------------------------------------------------------------+\n        | HTTP Method  | API Endpoint URI's                                                   |\n        +==============+======================================================================+\n        | GET          | /v2/securityLabels/{resourceId}/groups/{resourceType}                |\n        +--------------+----------------------------------------------------------------------+\n        | GET          | /v2/securityLabels/{resourceId}/groups/{resourceType}/{uniqueId}     |\n        +--------------+----------------------------------------------------------------------+\n        | GET          | /v2/securityLabels/{resourceId}/indicators/{resourceType}            |\n        +--------------+----------------------------------------------------------------------+\n        | GET          | /v2/securityLabels/{resourceId}/indicators/{resourceType}/{uniqueId} |\n        +--------------+----------------------------------------------------------------------+\n\n        Args:\n            resource_id (string): The resource pivot id (security label name)."
  },
  {
    "code": "def _get_sorted_cond_keys(self, keys_list):\n        cond_list = []\n        for key in keys_list:\n            if key.startswith('analysisservice-'):\n                cond_list.append(key)\n        cond_list.sort()\n        return cond_list",
    "docstring": "This function returns only the elements starting with\n        'analysisservice-' in 'keys_list'. The returned list is sorted by the\n        index appended to the end of each element"
  },
  {
    "code": "def get_writer_position(self, name):\n        cursor = self.cursor\n        cursor.execute('SELECT timestamp FROM gauged_writer_history '\n                       'WHERE id = %s', (name,))\n        result = cursor.fetchone()\n        return result[0] if result else 0",
    "docstring": "Get the current writer position"
  },
  {
    "code": "def cat(dataset, query, bounds, indent, compact, dst_crs, pagesize, sortby):\n    dump_kwds = {\"sort_keys\": True}\n    if indent:\n        dump_kwds[\"indent\"] = indent\n    if compact:\n        dump_kwds[\"separators\"] = (\",\", \":\")\n    table = bcdata.validate_name(dataset)\n    for feat in bcdata.get_features(\n        table, query=query, bounds=bounds, sortby=sortby, crs=dst_crs\n    ):\n        click.echo(json.dumps(feat, **dump_kwds))",
    "docstring": "Write DataBC features to stdout as GeoJSON feature objects."
  },
  {
    "code": "def create_vip(self):\n        return Vip(\n            self.networkapi_url,\n            self.user,\n            self.password,\n            self.user_ldap)",
    "docstring": "Get an instance of vip services facade."
  },
  {
    "code": "def authorization_link(self, redirect_uri):\n        args = '?client_id=%s&redirect_uri=%s' % (\n            self.app_key,\n            redirect_uri\n        )\n        uri = \"/\".join([BASE_URL, API_VERSION, OAUTH, args])\n        return uri",
    "docstring": "Construct OAuth2 authorization link.\n\n        Params:    redirect_uri -> URI for receiving callback with token\n        Returns authorization URL as string"
  },
  {
    "code": "def append(self, objects):\n        if not isinstance(objects, (list, tuple)):\n            objects = (objects,)\n        for child in objects:\n            if isinstance(child, Element):\n                self.children.append(child)\n                child.parent = self\n                continue\n            if isinstance(child, Attribute):\n                self.attributes.append(child)\n                child.parent = self\n                continue\n            raise Exception(\"append %s not-valid\" %\n                (child.__class__.__name__,))\n        return self",
    "docstring": "Append the specified child based on whether it is an element or an\n        attribute.\n\n        @param objects: A (single|collection) of attribute(s) or element(s) to\n            be added as children.\n        @type objects: (L{Element}|L{Attribute})\n        @return: self\n        @rtype: L{Element}"
  },
  {
    "code": "def clear_annotation_data(self):\n        self.genes = set()\n        self.annotations = []\n        self.term_annotations = {}\n        self.gene_annotations = {}",
    "docstring": "Clear annotation data.\n\n        Parameters\n        ----------\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def uptime():\n    from datetime import timedelta\n    with open('/proc/uptime', 'r') as f:\n        uptime_seconds = float(f.readline().split()[0])\n        uptime_string = str(timedelta(seconds=uptime_seconds))\n    bob.says(uptime_string)",
    "docstring": "Uptime of the host machine"
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'expansions' in _dict:\n            args['expansions'] = [\n                Expansion._from_dict(x) for x in (_dict.get('expansions'))\n            ]\n        else:\n            raise ValueError(\n                'Required property \\'expansions\\' not present in Expansions JSON'\n            )\n        return cls(**args)",
    "docstring": "Initialize a Expansions object from a json dictionary."
  },
  {
    "code": "def replay(journal_entry, function, *args, **kwargs):\n    section = fiber.WovenSection()\n    section.enter()\n    journal_mode = section.state.get(RECMODE_TAG, None)\n    is_first = journal_mode is None\n    if is_first:\n        section.state[RECMODE_TAG] = JournalMode.replay\n        section.state[JOURNAL_ENTRY_TAG] = IJournalReplayEntry(journal_entry)\n    result = function(*args, **kwargs)\n    section.abort(result)\n    return result",
    "docstring": "Calls method in replay context so that no journal entries are created,\n    expected_side_effects are checked, and no asynchronous task is started.\n    The journal entry is only used to fetch side-effects results."
  },
  {
    "code": "def resolve(checks, lazy, quiet):\n    root = get_root()\n    if 'all' in checks:\n        checks = os.listdir(root)\n    for check_name in sorted(checks):\n        pinned_reqs_file = os.path.join(root, check_name, 'requirements.in')\n        resolved_reqs_file = os.path.join(root, check_name, 'requirements.txt')\n        if os.path.isfile(pinned_reqs_file):\n            if not quiet:\n                echo_info('Check `{}`:'.format(check_name))\n            if not quiet:\n                echo_waiting('    Resolving dependencies...')\n            pre_packages = read_packages(resolved_reqs_file)\n            result = resolve_requirements(pinned_reqs_file, resolved_reqs_file, lazy=lazy)\n            if result.code:\n                abort(result.stdout + result.stderr)\n            if not quiet:\n                post_packages = read_packages(resolved_reqs_file)\n                display_package_changes(pre_packages, post_packages, indent='    ')",
    "docstring": "Resolve transient dependencies for any number of checks.\n    If you want to do this en masse, put `all`."
  },
  {
    "code": "def get_package(repo_url, pkg_name, timeout=1):\n    url = repo_url + \"/packages/\" + pkg_name\n    headers = {'accept': 'application/json'}\n    resp = requests.get(url, headers=headers, timeout=timeout)\n    if resp.status_code == 404:\n        return None\n    return resp.json()",
    "docstring": "Retrieve package information from a Bower registry at repo_url.\n\n       Returns a dict of package data."
  },
  {
    "code": "def basic_consume(self, queue='', consumer_tag='', no_local=False,\n        no_ack=False, exclusive=False, nowait=False,\n        callback=None, ticket=None):\n        args = AMQPWriter()\n        if ticket is not None:\n            args.write_short(ticket)\n        else:\n            args.write_short(self.default_ticket)\n        args.write_shortstr(queue)\n        args.write_shortstr(consumer_tag)\n        args.write_bit(no_local)\n        args.write_bit(no_ack)\n        args.write_bit(exclusive)\n        args.write_bit(nowait)\n        self._send_method((60, 20), args)\n        if not nowait:\n            consumer_tag = self.wait(allowed_methods=[\n                              (60, 21),\n                            ])\n        self.callbacks[consumer_tag] = callback\n        return consumer_tag",
    "docstring": "start a queue consumer\n\n        This method asks the server to start a \"consumer\", which is a\n        transient request for messages from a specific queue.\n        Consumers last as long as the channel they were created on, or\n        until the client cancels them.\n\n        RULE:\n\n            The server SHOULD support at least 16 consumers per queue,\n            unless the queue was declared as private, and ideally,\n            impose no limit except as defined by available resources.\n\n        PARAMETERS:\n            queue: shortstr\n\n                Specifies the name of the queue to consume from.  If\n                the queue name is null, refers to the current queue\n                for the channel, which is the last declared queue.\n\n                RULE:\n\n                    If the client did not previously declare a queue,\n                    and the queue name in this method is empty, the\n                    server MUST raise a connection exception with\n                    reply code 530 (not allowed).\n\n            consumer_tag: shortstr\n\n                Specifies the identifier for the consumer. The\n                consumer tag is local to a connection, so two clients\n                can use the same consumer tags. If this field is empty\n                the server will generate a unique tag.\n\n                RULE:\n\n                    The tag MUST NOT refer to an existing consumer. If\n                    the client attempts to create two consumers with\n                    the same non-empty tag the server MUST raise a\n                    connection exception with reply code 530 (not\n                    allowed).\n\n            no_local: boolean\n\n                do not deliver own messages\n\n                If the no-local field is set the server will not send\n                messages to the client that published them.\n\n            no_ack: boolean\n\n                no acknowledgement needed\n\n                If this field is set the server does not expect\n                acknowledgments for messages.  That is, when a message\n                is delivered to the client the server automatically and\n                silently acknowledges it on behalf of the client.  This\n                functionality increases performance but at the cost of\n                reliability.  Messages can get lost if a client dies\n                before it can deliver them to the application.\n\n            exclusive: boolean\n\n                request exclusive access\n\n                Request exclusive consumer access, meaning only this\n                consumer can access the queue.\n\n                RULE:\n\n                    If the server cannot grant exclusive access to the\n                    queue when asked, - because there are other\n                    consumers active - it MUST raise a channel\n                    exception with return code 403 (access refused).\n\n            nowait: boolean\n\n                do not send a reply method\n\n                If set, the server will not respond to the method. The\n                client should not wait for a reply method.  If the\n                server could not complete the method it will raise a\n                channel or connection exception.\n\n            callback: Python callable\n\n                function/method called with each delivered message\n\n                For each message delivered by the broker, the\n                callable will be called with a Message object\n                as the single argument.  If no callable is specified,\n                messages are quietly discarded, no_ack should probably\n                be set to True in that case.\n\n            ticket: short\n\n                RULE:\n\n                    The client MUST provide a valid access ticket\n                    giving \"read\" access rights to the realm for the\n                    queue."
  },
  {
    "code": "def run(self):\n        kwargs = {'query': self.get_data()}\n        if self.data_type == \"ip\":\n            kwargs.update({'query_type': 'ip'})\n        elif self.data_type == \"network\":\n            kwargs.update({'query_type': 'network'})\n        elif self.data_type == 'autonomous-system':\n            kwargs.update({'query_type': 'asn'})\n        elif self.data_type == 'port':\n            kwargs.update({'query_type': 'port'})\n        else:\n            self.notSupported()\n            return False\n        if self.service == 'observations':\n            response = self.bs.get_observations(**kwargs)\n            self.report(response)\n        elif self.service == 'enrichment':\n            response = self.bs.enrich(**kwargs)\n            self.report(response)\n        else:\n            self.report({'error': 'Invalid service defined.'})",
    "docstring": "Run the process to get observation data from Backscatter.io."
  },
  {
    "code": "def url(self, filename, external=False):\n        if filename.startswith('/'):\n            filename = filename[1:]\n        if self.has_url:\n            return self.base_url + filename\n        else:\n            return url_for('fs.get_file', fs=self.name, filename=filename, _external=external)",
    "docstring": "This function gets the URL a file uploaded to this set would be\n        accessed at. It doesn't check whether said file exists.\n\n        :param string filename: The filename to return the URL for.\n        :param bool external: If True, returns an absolute URL"
  },
  {
    "code": "def _end_of_decade(self):\n        year = self.year - self.year % YEARS_PER_DECADE + YEARS_PER_DECADE - 1\n        return self.set(year, 12, 31)",
    "docstring": "Reset the date to the last day of the decade.\n\n        :rtype: Date"
  },
  {
    "code": "def get_album(self, id):\n        url = self._base_url + \"/3/album/{0}\".format(id)\n        json = self._send_request(url)\n        return Album(json, self)",
    "docstring": "Return information about this album."
  },
  {
    "code": "def second_order_score(y, mean, scale, shape, skewness):\n        return ((shape+1)/shape)*(y-mean)/(np.power(scale,2) + (np.power(y-mean,2)/shape))/((shape+1)*((np.power(scale,2)*shape) - np.power(y-mean,2))/np.power((np.power(scale,2)*shape) + np.power(y-mean,2),2))",
    "docstring": "GAS t Update term potentially using second-order information - native Python function\n\n        Parameters\n        ----------\n        y : float\n            datapoint for the time series\n\n        mean : float\n            location parameter for the t distribution\n\n        scale : float\n            scale parameter for the t distribution\n\n        shape : float\n            tail thickness parameter for the t distribution\n\n        skewness : float\n            skewness parameter for the t distribution\n\n        Returns\n        ----------\n        - Adjusted score of the t family"
  },
  {
    "code": "def join_field(path):\n    output = \".\".join([f.replace(\".\", \"\\\\.\") for f in path if f != None])\n    return output if output else \".\"",
    "docstring": "RETURN field SEQUENCE AS STRING"
  },
  {
    "code": "def populate_request_data(self, request_args):\n        request_args['auth'] = HTTPBasicAuth(\n            self._username, self._password)\n        return request_args",
    "docstring": "Add the authentication info to the supplied dictionary.\n\n        We use the `requests.HTTPBasicAuth` class as the `auth` param.\n\n        Args:\n            `request_args`: The arguments that will be passed to the request.\n        Returns:\n            The updated arguments for the request."
  },
  {
    "code": "def save_default_values(self):\n        for parameter_container in self.default_value_parameter_containers:\n            parameters = parameter_container.get_parameters()\n            for parameter in parameters:\n                set_inasafe_default_value_qsetting(\n                    self.settings,\n                    GLOBAL,\n                    parameter.guid,\n                    parameter.value\n                )",
    "docstring": "Save InaSAFE default values."
  },
  {
    "code": "def stop(self):\n\t\tlogger.debug(\"Stopping playback\")\n\t\tself.clock.stop()\n\t\tself.status = READY",
    "docstring": "Stops the video stream and resets the clock."
  },
  {
    "code": "def is_appendable_to(self, group):\n        return (group.attrs['format'] == self.dformat and\n                group[self.name].dtype == self.dtype and\n                self._group_dim(group) == self.dim)",
    "docstring": "Return True if features are appendable to a HDF5 group"
  },
  {
    "code": "def average_loss(lc):\n    losses, poes = (lc['loss'], lc['poe']) if lc.dtype.names else lc\n    return -pairwise_diff(losses) @ pairwise_mean(poes)",
    "docstring": "Given a loss curve array with `poe` and `loss` fields,\n    computes the average loss on a period of time.\n\n    :note: As the loss curve is supposed to be piecewise linear as it\n           is a result of a linear interpolation, we compute an exact\n           integral by using the trapeizodal rule with the width given by the\n           loss bin width."
  },
  {
    "code": "def _is_allowed_abbr(self, tokens):\n        if len(tokens) <= 2:\n            abbr_text = ''.join(tokens)\n            if self.abbr_min <= len(abbr_text) <= self.abbr_max and bracket_level(abbr_text) == 0:\n                if abbr_text[0].isalnum() and any(c.isalpha() for c in abbr_text):\n                    if re.match('^\\d+(\\.\\d+)?(g|m[lL]|cm)$', abbr_text):\n                        return False\n                    return True\n        return False",
    "docstring": "Return True if text is an allowed abbreviation."
  },
  {
    "code": "def _SetRow(self, new_values, row=0):\n        if not row:\n            row = self._row_index\n        if row > self.size:\n            raise TableError(\"Entry %s beyond table size %s.\" % (row, self.size))\n        self._table[row].values = new_values",
    "docstring": "Sets the current row to new list.\n\n    Args:\n      new_values: List|dict of new values to insert into row.\n      row: int, Row to insert values into.\n\n    Raises:\n      TableError: If number of new values is not equal to row size."
  },
  {
    "code": "def console_set_char_foreground(\n    con: tcod.console.Console, x: int, y: int, col: Tuple[int, int, int]\n) -> None:\n    lib.TCOD_console_set_char_foreground(_console(con), x, y, col)",
    "docstring": "Change the foreground color of x,y to col.\n\n    Args:\n        con (Console): Any Console instance.\n        x (int): Character x position from the left.\n        y (int): Character y position from the top.\n        col (Union[Tuple[int, int, int], Sequence[int]]):\n            An (r, g, b) sequence or Color instance.\n\n    .. deprecated:: 8.4\n        Array access performs significantly faster than using this function.\n        See :any:`Console.fg`."
  },
  {
    "code": "def _get_pretty_string(obj):\n    sio = StringIO()\n    pprint.pprint(obj, stream=sio)\n    return sio.getvalue()",
    "docstring": "Return a prettier version of obj\n\n    Parameters\n    ----------\n    obj : object\n        Object to pretty print\n\n    Returns\n    -------\n    s : str\n        Pretty print object repr"
  },
  {
    "code": "def content_location(self) -> Optional[UnstructuredHeader]:\n        try:\n            return cast(UnstructuredHeader, self[b'content-location'][0])\n        except (KeyError, IndexError):\n            return None",
    "docstring": "The ``Content-Location`` header."
  },
  {
    "code": "def get_empty_dirs(self, path):\n        empty_dirs = []\n        for i in os.listdir(path):\n            child_path = os.path.join(path, i)\n            if i == '.git' or os.path.isfile(child_path) or os.path.islink(child_path):\n                continue\n            if self.path_only_contains_dirs(child_path):\n                empty_dirs.append(i)\n        return empty_dirs",
    "docstring": "Return a list of empty directories in path."
  },
  {
    "code": "def _purge(dir, pattern, reason=''):\n    for f in os.listdir(dir):\n        if re.search(pattern, f):\n            print \"Purging file {0}. {1}\".format(f, reason)\n            os.remove(os.path.join(dir, f))",
    "docstring": "delete files in dir that match pattern"
  },
  {
    "code": "def add_wirevector(self, wirevector):\n        self.sanity_check_wirevector(wirevector)\n        self.wirevector_set.add(wirevector)\n        self.wirevector_by_name[wirevector.name] = wirevector",
    "docstring": "Add a wirevector object to the block."
  },
  {
    "code": "def run_vardict(align_bams, items, ref_file, assoc_files, region=None,\n                out_file=None):\n    items = shared.add_highdepth_genome_exclusion(items)\n    if vcfutils.is_paired_analysis(align_bams, items):\n        call_file = _run_vardict_paired(align_bams, items, ref_file,\n                                        assoc_files, region, out_file)\n    else:\n        vcfutils.check_paired_problems(items)\n        call_file = _run_vardict_caller(align_bams, items, ref_file,\n                                        assoc_files, region, out_file)\n    return call_file",
    "docstring": "Run VarDict variant calling."
  },
  {
    "code": "def backup_file(*, file, host):\n    if not _has_init:\n        raise RuntimeError(\"This driver has not been properly initialised!\")\n    try:\n        if not _dry_run:\n            bucket = _boto_conn.get_bucket(_bucket_name)\n    except boto.exception.S3ResponseError:\n        log.msg_warn(\"Bucket '{bucket_name}' does not exist!, creating it...\"\n                     .format(bucket_name=_bucket_name))\n        if not _dry_run:\n            bucket = _boto_conn.create_bucket(_bucket_name)\n        log.msg(\"Created bucket '{bucket}'\".format(bucket=_bucket_name))\n    key_path = \"{key}/{file}\".format(key=host, file=ntpath.basename(file))\n    if not _dry_run:\n        k = boto.s3.key.Key(bucket)\n        k.key = key_path\n    log.msg(\"Uploading '{key_path}' to bucket '{bucket_name}' ...\"\n            .format(key_path=key_path, bucket_name=_bucket_name))\n    if not _dry_run:\n        k.set_contents_from_filename(file, encrypt_key=True)\n    log.msg(\"The file '{key_path}' has been successfully uploaded to S3!\"\n            .format(key_path=key_path))",
    "docstring": "Backup a file on S3\n\n    :param file: full path to the file to be backed up\n    :param host: this will be used to locate the file on S3\n    :raises TypeError: if an argument in kwargs does not have the type expected\n    :raises ValueError: if an argument within kwargs has an invalid value"
  },
  {
    "code": "def start(self, *args):\n        if self._is_verbose:\n            return self\n        self.writeln('start', *args)\n        self._indent += 1\n        return self",
    "docstring": "Start a nested log."
  },
  {
    "code": "def to_dict(self):\n        return dict(\n            host=self.host,\n            port=self.port,\n            database=self.database,\n            username=self.username,\n            password=self.password,\n        )",
    "docstring": "Convert credentials into a dict."
  },
  {
    "code": "def get_child_book_ids(self, book_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.get_child_catalog_ids(catalog_id=book_id)\n        return self._hierarchy_session.get_children(id_=book_id)",
    "docstring": "Gets the child ``Ids`` of the given book.\n\n        arg:    book_id (osid.id.Id): the ``Id`` to query\n        return: (osid.id.IdList) - the children of the book\n        raise:  NotFound - ``book_id`` is not found\n        raise:  NullArgument - ``book_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _flush(self):\n        d = os.path.dirname(self.path)\n        if not os.path.isdir(d):\n            os.makedirs(d)\n        with io.open(self.path, 'w', encoding='utf8') as f:\n            yaml.safe_dump(self._data, f, default_flow_style=False, encoding=None)",
    "docstring": "Save the contents of data to the file on disk. You should not need to call this manually."
  },
  {
    "code": "def percent(self, value) -> 'Gap':\n        raise_not_number(value)\n        self.gap = '{}%'.format(value)\n        return self",
    "docstring": "Set the margin as a percentage."
  },
  {
    "code": "def build_row(row, left, center, right):\n    if not row or not row[0]:\n        yield combine((), left, center, right)\n        return\n    for row_index in range(len(row[0])):\n        yield combine((c[row_index] for c in row), left, center, right)",
    "docstring": "Combine single or multi-lined cells into a single row of list of lists including borders.\n\n    Row must already be padded and extended so each cell has the same number of lines.\n\n    Example return value:\n    [\n        ['>', 'Left ', '|', 'Center', '|', 'Right', '<'],\n        ['>', 'Cell1', '|', 'Cell2 ', '|', 'Cell3', '<'],\n    ]\n\n    :param iter row: List of cells for one row.\n    :param str left: Left border.\n    :param str center: Column separator.\n    :param str right: Right border.\n\n    :return: Yields other generators that yield strings.\n    :rtype: iter"
  },
  {
    "code": "def _convert_bin_to_datelike_type(bins, dtype):\n    if is_datetime64tz_dtype(dtype):\n        bins = to_datetime(bins.astype(np.int64),\n                           utc=True).tz_convert(dtype.tz)\n    elif is_datetime_or_timedelta_dtype(dtype):\n        bins = Index(bins.astype(np.int64), dtype=dtype)\n    return bins",
    "docstring": "Convert bins to a DatetimeIndex or TimedeltaIndex if the orginal dtype is\n    datelike\n\n    Parameters\n    ----------\n    bins : list-like of bins\n    dtype : dtype of data\n\n    Returns\n    -------\n    bins : Array-like of bins, DatetimeIndex or TimedeltaIndex if dtype is\n           datelike"
  },
  {
    "code": "def ReadAllClientGraphSeries(\n      self,\n      client_label,\n      report_type,\n      time_range = None,\n      cursor=None):\n    query =\n    args = [client_label, report_type.SerializeToDataStore()]\n    if time_range is not None:\n      query += \"AND `timestamp` BETWEEN FROM_UNIXTIME(%s) AND FROM_UNIXTIME(%s)\"\n      args += [\n          mysql_utils.RDFDatetimeToTimestamp(time_range.start),\n          mysql_utils.RDFDatetimeToTimestamp(time_range.end)\n      ]\n    cursor.execute(query, args)\n    results = {}\n    for timestamp, raw_series in cursor.fetchall():\n      timestamp = cast(rdfvalue.RDFDatetime,\n                       mysql_utils.TimestampToRDFDatetime(timestamp))\n      series = rdf_stats.ClientGraphSeries.FromSerializedString(raw_series)\n      results[timestamp] = series\n    return results",
    "docstring": "Reads graph series for the given label and report-type from the DB."
  },
  {
    "code": "def formatter_class(klass):\n    def decorator(func):\n        adaptor = ScriptAdaptor._get_adaptor(func)\n        adaptor.formatter_class = klass\n        return func\n    return decorator",
    "docstring": "Decorator used to specify the formatter class for the console\n    script.\n\n    :param klass: The formatter class to use."
  },
  {
    "code": "def add_neighbours(self):\n        ipix = self._best_res_pixels()\n        hp = HEALPix(nside=(1 << self.max_order), order='nested')\n        extend_ipix = AbstractMOC._neighbour_pixels(hp, ipix)\n        neigh_ipix = np.setdiff1d(extend_ipix, ipix)\n        shift = 2 * (AbstractMOC.HPY_MAX_NORDER - self.max_order)\n        neigh_itv = np.vstack((neigh_ipix << shift, (neigh_ipix + 1) << shift)).T\n        self._interval_set = self._interval_set.union(IntervalSet(neigh_itv))\n        return self",
    "docstring": "Extends the MOC instance so that it includes the HEALPix cells touching its border.\n\n        The depth of the HEALPix cells added at the border is equal to the maximum depth of the MOC instance.\n\n        Returns\n        -------\n        moc : `~mocpy.moc.MOC`\n            self extended by one degree of neighbours."
  },
  {
    "code": "def process(self, user, timestamp, data=None):\n        event = Event(user, mwtypes.Timestamp(timestamp), self.event_i, data)\n        self.event_i += 1\n        for user, events in self._clear_expired(event.timestamp):\n            yield Session(user, unpack_events(events))\n        if event.user in self.active_users:\n            events = self.active_users[event.user]\n        else:\n            events = []\n            self.active_users[event.user] = events\n            active_session = ActiveSession(event.timestamp, event.i, events)\n            self.recently_active.push(active_session)\n        events.append(event)",
    "docstring": "Processes a user event.\n\n        :Parameters:\n            user : `hashable`\n                A hashable value to identify a user (`int` or `str` are OK)\n            timestamp : :class:`mwtypes.Timestamp`\n                The timestamp of the event\n            data : `mixed`\n                Event meta data\n\n        :Returns:\n            A generator of :class:`~mwsessions.Session` expired after\n            processing the user event."
  },
  {
    "code": "def seek(self, pos):\n        if self.debug:\n            logging.debug('seek: %r' % pos)\n        self.fp.seek(pos)\n        self.bufpos = pos\n        self.buf = b''\n        self.charpos = 0\n        self._parse1 = self._parse_main\n        self._curtoken = b''\n        self._curtokenpos = 0\n        self._tokens = []\n        return",
    "docstring": "Seeks the parser to the given position."
  },
  {
    "code": "def get_shared_people(self):\n        people = []\n        output = self._get_data()\n        self._logger.debug(output)\n        shared_entries = output[0] or []\n        for info in shared_entries:\n            try:\n                people.append(Person(info))\n            except InvalidData:\n                self._logger.debug('Missing location or other info, dropping person with info: %s', info)\n        return people",
    "docstring": "Retrieves all people that share their location with this account"
  },
  {
    "code": "def in_batches(iterable, batch_size):\n    items = list(iterable)\n    size = len(items)\n    for i in range(0, size, batch_size):\n        yield items[i:min(i + batch_size, size)]",
    "docstring": "Split the given iterable into batches.\n\n    Args:\n        iterable (Iterable[Any]):\n            The iterable you want to split into batches.\n        batch_size (int):\n            The size of each bach. The last batch will be probably smaller (if\n            the number of elements cannot be equally divided.\n\n    Returns:\n        Generator[list[Any]]: Will yield all items in batches of **batch_size**\n            size.\n\n    Example:\n\n        >>> from peltak.core import util\n        >>>\n        >>> batches = util.in_batches([1, 2, 3, 4, 5, 6, 7], 3)\n        >>> batches = list(batches)     # so we can query for lenght\n        >>> len(batches)\n        3\n        >>> batches\n        [[1, 2, 3], [4, 5, 6], [7]]"
  },
  {
    "code": "def options(self, urls=None, **overrides):\n        if urls is not None:\n            overrides['urls'] = urls\n        return self.where(accept='OPTIONS', **overrides)",
    "docstring": "Sets the acceptable HTTP method to OPTIONS"
  },
  {
    "code": "def has_option(self, section, option):\n        if section not in self.sections():\n            return False\n        else:\n            option = self.optionxform(option)\n            return option in self[section]",
    "docstring": "Checks for the existence of a given option in a given section.\n\n        Args:\n            section (str): name of section\n            option (str): name of option\n\n        Returns:\n            bool: whether the option exists in the given section"
  },
  {
    "code": "def resolve_aliases(self, target, scope=None):\n    for declared in target.dependencies:\n      if scope is not None and declared.scope != scope:\n        continue\n      elif type(declared) in (AliasTarget, Target):\n        for r, _ in self.resolve_aliases(declared, scope=scope):\n          yield r, declared\n      else:\n        yield declared, None",
    "docstring": "Resolve aliases in the direct dependencies of the target.\n\n    :param target: The direct dependencies of this target are included.\n    :param scope: When specified, only deps with this scope are included. This is more\n      than a filter, because it prunes the subgraphs represented by aliases with\n      un-matched scopes.\n    :returns: An iterator of (resolved_dependency, resolved_from) tuples.\n      `resolved_from` is the top level target alias that depends on `resolved_dependency`,\n      and `None` if `resolved_dependency` is not a dependency of a target alias."
  },
  {
    "code": "def tomof(self, maxline=MAX_MOF_LINE):\n        mof = []\n        mof.append(_qualifiers_tomof(self.qualifiers, MOF_INDENT, maxline))\n        mof.append(u'class ')\n        mof.append(self.classname)\n        mof.append(u' ')\n        if self.superclass is not None:\n            mof.append(u': ')\n            mof.append(self.superclass)\n            mof.append(u' ')\n        mof.append(u'{\\n')\n        for p in self.properties.itervalues():\n            mof.append(u'\\n')\n            mof.append(p.tomof(False, MOF_INDENT, maxline))\n        for m in self.methods.itervalues():\n            mof.append(u'\\n')\n            mof.append(m.tomof(MOF_INDENT, maxline))\n        mof.append(u'\\n};\\n')\n        return u''.join(mof)",
    "docstring": "Return a MOF string with the declaration of this CIM class.\n\n        The returned MOF string conforms to the ``classDeclaration``\n        ABNF rule defined in :term:`DSP0004`.\n\n        The order of properties, methods, parameters, and qualifiers is\n        preserved.\n\n        The :attr:`~pywbem.CIMClass.path` attribute of this object will not be\n        included in the returned MOF string.\n\n        Consistent with that, class path information is not included in the\n        returned MOF string.\n\n        Returns:\n\n          :term:`unicode string`: MOF string."
  },
  {
    "code": "def check_bam(bam, samtype=\"bam\"):\n    ut.check_existance(bam)\n    samfile = pysam.AlignmentFile(bam, \"rb\")\n    if not samfile.has_index():\n        pysam.index(bam)\n        samfile = pysam.AlignmentFile(bam, \"rb\")\n        logging.info(\"Nanoget: No index for bam file could be found, created index.\")\n    if not samfile.header['HD']['SO'] == 'coordinate':\n        logging.error(\"Nanoget: Bam file {} not sorted by coordinate!.\".format(bam))\n        sys.exit(\"Please use a bam file sorted by coordinate.\")\n    if samtype == \"bam\":\n        logging.info(\"Nanoget: Bam file {} contains {} mapped and {} unmapped reads.\".format(\n            bam, samfile.mapped, samfile.unmapped))\n        if samfile.mapped == 0:\n            logging.error(\"Nanoget: Bam file {} does not contain aligned reads.\".format(bam))\n            sys.exit(\"FATAL: not a single read was mapped in bam file {}\".format(bam))\n    return samfile",
    "docstring": "Check if bam file is valid.\n\n    Bam file should:\n    - exists\n    - has an index (create if necessary)\n    - is sorted by coordinate\n    - has at least one mapped read"
  },
  {
    "code": "def get_basic_profile(self, user_id, scope='profile/public'):\n        profile = _get(\n            token=self.oauth.get_app_token(scope),\n            uri='/user/profile/' + urllib.quote(user_id)\n        )\n        try:\n            return json.loads(profile)\n        except:\n            raise MxitAPIException('Error parsing profile data')",
    "docstring": "Retrieve the Mxit user's basic profile\n        No user authentication required"
  },
  {
    "code": "def last_midnight():\n    now = datetime.now()\n    return datetime(now.year, now.month, now.day)",
    "docstring": "return a datetime of last mid-night"
  },
  {
    "code": "def check_list(self, node_list, pattern_list):\n        if len(node_list) != len(pattern_list):\n            return False\n        else:\n            return all(Check(node_elt,\n                             self.placeholders).visit(pattern_list[i])\n                       for i, node_elt in enumerate(node_list))",
    "docstring": "Check if list of node are equal."
  },
  {
    "code": "def build(self):\n        if self.is_built():\n            return\n        with _wait_signal(self.loadFinished, 20):\n            self.rebuild()\n        self._built = True",
    "docstring": "Build the full HTML source."
  },
  {
    "code": "def _determine_selected_stencil(stencil_set, stencil_definition):\n    if 'stencil' not in stencil_definition:\n        selected_stencil_name = stencil_set.manifest.get('default_stencil')\n    else:\n        selected_stencil_name = stencil_definition.get('stencil')\n    if not selected_stencil_name:\n        raise ValueError(\"No stencil name, within stencil set %s, specified.\"\n                         % stencil_definition['name'])\n    return selected_stencil_name",
    "docstring": "Determine appropriate stencil name for stencil definition.\n\n    Given a fastfood.json stencil definition with a stencil set, figure out\n    what the name of the stencil within the set should be, or use the default"
  },
  {
    "code": "def set_execution_context(self, execution_context):\n        if self._execution_context:\n            raise errors.AlreadyInContextError\n        self._execution_context = execution_context",
    "docstring": "Set the ExecutionContext this async is executing under."
  },
  {
    "code": "def load_config_key():\n    global api_token\n    try:\n        api_token = os.environ['SOCCER_CLI_API_TOKEN']\n    except KeyError:\n        home = os.path.expanduser(\"~\")\n        config = os.path.join(home, \".soccer-cli.ini\")\n        if not os.path.exists(config):\n            with open(config, \"w\") as cfile:\n                key = get_input_key()\n                cfile.write(key)\n        else:\n            with open(config, \"r\") as cfile:\n                key = cfile.read()\n        if key:\n            api_token = key\n        else:\n            os.remove(config)\n            click.secho('No API Token detected. '\n                        'Please visit {0} and get an API Token, '\n                        'which will be used by Soccer CLI '\n                        'to get access to the data.'\n                        .format(RequestHandler.BASE_URL), fg=\"red\", bold=True)\n            sys.exit(1)\n    return api_token",
    "docstring": "Load API key from config file, write if needed"
  },
  {
    "code": "def start(self, phase, stage, **kwargs):\n        return ProgressSection(self, self._session, phase, stage, self._logger, **kwargs)",
    "docstring": "Start a new routine, stage or phase"
  },
  {
    "code": "def plot(self, data, height=1000, render_large_data=False):\n    import IPython\n    if not isinstance(data, pd.DataFrame):\n      raise ValueError('Expect a DataFrame.')\n    if (len(data) > 10000 and not render_large_data):\n      raise ValueError('Facets dive may not work well with more than 10000 rows. ' +\n                       'Reduce data or set \"render_large_data\" to True.')\n    jsonstr = data.to_json(orient='records')\n    html_id = 'f' + datalab.utils.commands.Html.next_id()\n    HTML_TEMPLATE =\n    html = HTML_TEMPLATE.format(html_id=html_id, jsonstr=jsonstr, height=height)\n    return IPython.core.display.HTML(html)",
    "docstring": "Plots a detail view of data.\n\n    Args:\n      data: a Pandas dataframe.\n      height: the height of the output."
  },
  {
    "code": "def load_ply(file_obj,\n             resolver=None,\n             fix_texture=True,\n             *args,\n             **kwargs):\n    elements, is_ascii, image_name = parse_header(file_obj)\n    if is_ascii:\n        ply_ascii(elements, file_obj)\n    else:\n        ply_binary(elements, file_obj)\n    image = None\n    if image_name is not None:\n        try:\n            data = resolver.get(image_name)\n            image = PIL.Image.open(util.wrap_as_stream(data))\n        except BaseException:\n            log.warning('unable to load image!',\n                        exc_info=True)\n    kwargs = elements_to_kwargs(elements,\n                                fix_texture=fix_texture,\n                                image=image)\n    return kwargs",
    "docstring": "Load a PLY file from an open file object.\n\n    Parameters\n    ---------\n    file_obj : an open file- like object\n      Source data, ASCII or binary PLY\n    resolver : trimesh.visual.resolvers.Resolver\n      Object which can resolve assets\n    fix_texture : bool\n      If True, will re- index vertices and faces\n      so vertices with different UV coordinates\n      are disconnected.\n\n    Returns\n    ---------\n    mesh_kwargs : dict\n      Data which can be passed to\n      Trimesh constructor, eg: a = Trimesh(**mesh_kwargs)"
  },
  {
    "code": "def render_reverse(self, inst=None, context=None):\n        rendered = self.render(inst=inst, context=context)\n        parts = rendered.split('/')\n        if parts[-1] in ['index.html', 'index.htm']:\n            return ('/'.join(parts[:-1])) + '/'\n        return rendered",
    "docstring": "Renders the reverse URL for this path."
  },
  {
    "code": "def get_errors(error_string):\n    lines = error_string.splitlines()\n    error_lines = tuple(line for line in lines if line.find('Error') >= 0)\n    if len(error_lines) > 0:\n        return '\\n'.join(error_lines)\n    else:\n        return error_string.strip()",
    "docstring": "returns all lines in the error_string that start with the string \"error\""
  },
  {
    "code": "def get_node(self, element):\n        r\n        ns, tag = self.split_namespace(element.tag)\n        return {'tag': tag, 'value': (element.text or '').strip(), 'attr': element.attrib, 'namespace': ns}",
    "docstring": "r\"\"\"Get node info.\n\n        Parse element and get the element tag info. Include tag name, value, attribute, namespace.\n\n        :param element: an :class:`~xml.etree.ElementTree.Element` instance\n        :rtype: dict"
  },
  {
    "code": "def _gather(self, *args, **kwargs):\n        propagate = kwargs.pop('propagate', True)\n        return (self.to_python(reply, propagate=propagate)\n                for reply in self.actor._collect_replies(*args, **kwargs))",
    "docstring": "Generator over the results"
  },
  {
    "code": "def etag(self):\n        value = []\n        for option in self.options:\n            if option.number == defines.OptionRegistry.ETAG.number:\n                value.append(option.value)\n        return value",
    "docstring": "Get the ETag option of the message.\n\n        :rtype: list\n        :return: the ETag values or [] if not specified by the request"
  },
  {
    "code": "def Validate(self):\n    ValidateMultiple(self.probe, \"Method has invalid probes\")\n    Validate(self.target, \"Method has invalid target\")\n    Validate(self.hint, \"Method has invalid hint\")",
    "docstring": "Check the Method is well constructed."
  },
  {
    "code": "def set_bit(bitmask, bit, is_on):\n    bitshift = bit - 1\n    if is_on:\n        return bitmask | (1 << bitshift)\n    return bitmask & (0xff & ~(1 << bitshift))",
    "docstring": "Set the value of a bit in a bitmask on or off.\n\n    Uses the low bit is 1 and the high bit is 8."
  },
  {
    "code": "def mkdir_p(*args, **kwargs):\n    try:\n        return os.mkdir(*args, **kwargs)\n    except OSError as exc:\n        if exc.errno != errno.EEXIST:\n            raise",
    "docstring": "Like `mkdir`, but does not raise an exception if the\n    directory already exists."
  },
  {
    "code": "def set_bool(_bytearray, byte_index, bool_index, value):\n    assert value in [0, 1, True, False]\n    current_value = get_bool(_bytearray, byte_index, bool_index)\n    index_value = 1 << bool_index\n    if current_value == value:\n        return\n    if value:\n        _bytearray[byte_index] += index_value\n    else:\n        _bytearray[byte_index] -= index_value",
    "docstring": "Set boolean value on location in bytearray"
  },
  {
    "code": "def get_components_for_species( alignment, species ):\n    if len( alignment.components ) < len( species ): return None\n    index = dict( [ ( c.src.split( '.' )[0], c ) for c in alignment.components ] )\n    try: return [ index[s] for s in species ]\n    except: return None",
    "docstring": "Return the component for each species in the list `species` or None"
  },
  {
    "code": "def __traces_url(self):\n        path = AGENT_TRACES_PATH % self.from_.pid\n        return \"http://%s:%s/%s\" % (self.host, self.port, path)",
    "docstring": "URL for posting traces to the host agent.  Only valid when announced."
  },
  {
    "code": "def build_type(field):\n  if field.type_id == 'string':\n    if 'size' in field.options:\n      return \"builder.putString(%s, %d)\" % (field.identifier, field.options['size'].value)\n    else:\n      return \"builder.putString(%s)\" % field.identifier\n  elif field.type_id in JAVA_TYPE_MAP:\n    return \"builder.put%s(%s)\" % (field.type_id.capitalize(), field.identifier)\n  if field.type_id == 'array':\n    t = field.options['fill'].value\n    if t in JAVA_TYPE_MAP:\n      if 'size' in field.options:\n        return \"builder.putArrayof%s(%s, %d)\" % (t.capitalize(),\n                                                 field.identifier,\n                                                 field.options['size'].value)\n      else:\n        return \"builder.putArrayof%s(%s)\" % (t.capitalize(), field.identifier)\n    else:\n      if 'size' in field.options:\n        return \"builder.putArray(%s, %d)\" % (field.identifier, field.options['size'].value)\n      else:\n        return \"builder.putArray(%s)\" % field.identifier\n  else:\n    return \"%s.build(builder)\" % field.identifier",
    "docstring": "Function to pack a type into the binary payload."
  },
  {
    "code": "def get_bounding_box(points):\n    assert len(points) > 0, \"At least one point has to be given.\"\n    min_x, max_x = points[0]['x'], points[0]['x']\n    min_y, max_y = points[0]['y'], points[0]['y']\n    for point in points:\n        min_x, max_x = min(min_x, point['x']), max(max_x, point['x'])\n        min_y, max_y = min(min_y, point['y']), max(max_y, point['y'])\n    p1 = Point(min_x, min_y)\n    p2 = Point(max_x, max_y)\n    return BoundingBox(p1, p2)",
    "docstring": "Get the bounding box of a list of points.\n\n    Parameters\n    ----------\n    points : list of points\n\n    Returns\n    -------\n    BoundingBox"
  },
  {
    "code": "def do_copy(self, subcmd, opts, *args):\n        print \"'svn %s' opts: %s\" % (subcmd, opts)\n        print \"'svn %s' args: %s\" % (subcmd, args)",
    "docstring": "Duplicate something in working copy or repository, remembering history.\n\n        usage:\n            copy SRC DST\n        \n        SRC and DST can each be either a working copy (WC) path or URL:\n          WC  -> WC:   copy and schedule for addition (with history)\n          WC  -> URL:  immediately commit a copy of WC to URL\n          URL -> WC:   check out URL into WC, schedule for addition\n          URL -> URL:  complete server-side copy;  used to branch & tag\n\n        ${cmd_option_list}"
  },
  {
    "code": "def max_width(self):\n        value, unit = float(self._width_str[:-1]), self._width_str[-1]\n        ensure(unit in [\"c\", \"%\"], ValueError,\n               \"Width unit must be either 'c' or '%'\")\n        if unit == \"c\":\n            ensure(value <= self.columns, ValueError,\n                   \"Terminal only has {} columns, cannot draw \"\n                   \"bar of size {}.\".format(self.columns, value))\n            retval = value\n        else:\n            ensure(0 < value <= 100, ValueError,\n                   \"value=={} does not satisfy 0 < value <= 100\".format(value))\n            dec = value / 100\n            retval = dec * self.columns\n        return floor(retval)",
    "docstring": "Get maximum width of progress bar\n\n        :rtype: int\n        :returns: Maximum column width of progress bar"
  },
  {
    "code": "def retrieve_records(self, timeperiod, include_running,\n                         include_processed, include_noop, include_failed, include_disabled):\n        resp = dict()\n        resp.update(self._search_by_level(COLLECTION_JOB_HOURLY, timeperiod, include_running,\n                                          include_processed, include_noop, include_failed, include_disabled))\n        resp.update(self._search_by_level(COLLECTION_JOB_DAILY, timeperiod, include_running,\n                                          include_processed, include_noop, include_failed, include_disabled))\n        timeperiod = time_helper.cast_to_time_qualifier(QUALIFIER_MONTHLY, timeperiod)\n        resp.update(self._search_by_level(COLLECTION_JOB_MONTHLY, timeperiod, include_running,\n                                          include_processed, include_noop, include_failed, include_disabled))\n        timeperiod = time_helper.cast_to_time_qualifier(QUALIFIER_YEARLY, timeperiod)\n        resp.update(self._search_by_level(COLLECTION_JOB_YEARLY, timeperiod, include_running,\n                                          include_processed, include_noop, include_failed, include_disabled))\n        return resp",
    "docstring": "method looks for suitable job records in all Job collections and returns them as a dict"
  },
  {
    "code": "def delete_permission(self, username, virtual_host):\n        virtual_host = quote(virtual_host, '')\n        return self.http_client.delete(\n            API_USER_VIRTUAL_HOST_PERMISSIONS %\n            (\n                virtual_host,\n                username\n            ))",
    "docstring": "Delete User permissions for the configured virtual host.\n\n        :param str username: Username\n        :param str virtual_host: Virtual host name\n\n        :raises ApiError: Raises if the remote server encountered an error.\n        :raises ApiConnectionError: Raises if there was a connectivity issue.\n\n        :rtype: dict"
  },
  {
    "code": "def get_raw_data(self, times=5):\n        self._validate_measure_count(times)\n        data_list = []\n        while len(data_list) < times:\n            data = self._read()\n            if data not in [False, -1]:\n                data_list.append(data)\n        return data_list",
    "docstring": "do some readings and aggregate them using the defined statistics function\n\n        :param times: how many measures to aggregate\n        :type times: int\n        :return: the aggregate of the measured values\n        :rtype float"
  },
  {
    "code": "def _cryptography_encrypt(cipher_factory, plaintext, key, iv):\n    encryptor = cipher_factory(key, iv).encryptor()\n    return encryptor.update(plaintext) + encryptor.finalize()",
    "docstring": "Use a cryptography cipher factory to encrypt data.\n\n    :param cipher_factory: Factory callable that builds a cryptography Cipher\n        instance based on the key and IV\n    :type cipher_factory: callable\n    :param bytes plaintext: Plaintext data to encrypt\n    :param bytes key: Encryption key\n    :param bytes IV: Initialization vector\n    :returns: Encrypted ciphertext\n    :rtype: bytes"
  },
  {
    "code": "def create_or_clear(self, path, **kwargs):\n        try:\n            yield self.create(path, **kwargs)\n        except NodeExistsException:\n            children = yield self.get_children(path)\n            for name in children:\n                yield self.recursive_delete(path + \"/\" + name)",
    "docstring": "Create path and recursively clear contents."
  },
  {
    "code": "def _render(self):\n        p_char = ''\n        if not self.done and self.remainder:\n            p_style = self._comp_style\n            if self.partial_char_extra_style:\n                if p_style is str:\n                    p_style = self.partial_char_extra_style\n                else:\n                    p_style = p_style + self.partial_char_extra_style\n            p_char = p_style(self.partial_chars[self.remainder])\n            self._num_empty_chars -= 1\n        cm_chars = self._comp_style(self.icons[_ic] * self._num_complete_chars)\n        em_chars = self._empt_style(self.icons[_ie] * self._num_empty_chars)\n        return f'{self._first}{cm_chars}{p_char}{em_chars}{self._last} {self._lbl}'",
    "docstring": "figure partial character"
  },
  {
    "code": "def lrem(self, name, value, num=1):\n        with self.pipe as pipe:\n            value = self.valueparse.encode(value)\n            return pipe.execute_command('LREM', self.redis_key(name),\n                                        num, value)",
    "docstring": "Remove first occurrence of value.\n\n        Can't use redis-py interface. It's inconstistent between\n        redis.Redis and redis.StrictRedis in terms of the kwargs.\n        Better to use the underlying execute_command instead.\n\n        :param name: str     the name of the redis key\n        :param num:\n        :param value:\n        :return: Future()"
  },
  {
    "code": "def filter_sequences(self, seq_type):\n        return DictList(x for x in self.sequences if isinstance(x, seq_type))",
    "docstring": "Return a DictList of only specified types in the sequences attribute.\n\n        Args:\n            seq_type (SeqProp): Object type\n\n        Returns:\n            DictList: A filtered DictList of specified object type only"
  },
  {
    "code": "def head_values(self):\n        values = set()\n        for head in self._heads:\n            values.add(head.value)\n        return values",
    "docstring": "Return set of the head values"
  },
  {
    "code": "def _interact(self, location, error_info, payload):\n        if (self._interaction_methods is None or\n                len(self._interaction_methods) == 0):\n            raise InteractionError('interaction required but not possible')\n        if error_info.info.interaction_methods is None and \\\n                error_info.info.visit_url is not None:\n            return None, self._legacy_interact(location, error_info)\n        for interactor in self._interaction_methods:\n            found = error_info.info.interaction_methods.get(interactor.kind())\n            if found is None:\n                continue\n            try:\n                token = interactor.interact(self, location, error_info)\n            except InteractionMethodNotFound:\n                continue\n            if token is None:\n                raise InteractionError('interaction method returned an empty '\n                                       'token')\n            return token, None\n        raise InteractionError('no supported interaction method')",
    "docstring": "Gathers a macaroon by directing the user to interact with a\n        web page. The error_info argument holds the interaction-required\n        error response.\n        @return DischargeToken, bakery.Macaroon"
  },
  {
    "code": "def received(self, data):\n        self.logger.debug('Data received: {}'.format(data))\n        message_type = None\n        if 'type' in data:\n            message_type = data['type']\n        if message_type == 'confirm_subscription':\n            self._subscribed()\n        elif message_type == 'reject_subscription':\n            self._rejected()\n        elif self.receive_callback is not None and 'message' in data:\n            self.receive_callback(data['message'])\n        else:\n            self.logger.warning('Message type unknown. ({})'.format(message_type))",
    "docstring": "API for the connection to forward\n        information to this subscription instance.\n\n        :param data: The JSON data which was received.\n        :type data: Message"
  },
  {
    "code": "def _as_dict(self):\n        values = self._dynamic_columns or {}\n        for name, col in self._columns.items():\n            values[name] = col.to_database(getattr(self, name, None))\n        return values",
    "docstring": "Returns a map of column names to cleaned values"
  },
  {
    "code": "def asset(path):\n    commit = bitcaster.get_full_version()\n    return mark_safe('{0}?{1}'.format(_static(path), commit))",
    "docstring": "Join the given path with the STATIC_URL setting.\n\n    Usage::\n\n        {% static path [as varname] %}\n\n    Examples::\n\n        {% static \"myapp/css/base.css\" %}\n        {% static variable_with_path %}\n        {% static \"myapp/css/base.css\" as admin_base_css %}\n        {% static variable_with_path as varname %}"
  },
  {
    "code": "def get_total_size(self, entries):\n        size = 0\n        for entry in entries:\n            if entry['response']['bodySize'] > 0:\n                size += entry['response']['bodySize']\n        return size",
    "docstring": "Returns the total size of a collection of entries.\n\n        :param entries: ``list`` of entries to calculate the total size of."
  },
  {
    "code": "def _to_desired_dates(self, arr):\n        times = utils.times.extract_months(\n            arr[internal_names.TIME_STR], self.months\n        )\n        return arr.sel(time=times)",
    "docstring": "Restrict the xarray DataArray or Dataset to the desired months."
  },
  {
    "code": "def nrefs(self, tag):\n        n = _C.Vnrefs(self._id, tag)\n        _checkErr('nrefs', n, \"bad arguments\")\n        return n",
    "docstring": "Determine the number of tags of a given type in a vgroup.\n\n        Args::\n\n          tag    tag type to look for in the vgroup\n\n        Returns::\n\n          number of members identified by this tag type\n\n        C library equivalent : Vnrefs"
  },
  {
    "code": "def is_hosting_device_reachable(self, hosting_device):\n        ret_val = False\n        hd = hosting_device\n        hd_id = hosting_device['id']\n        hd_mgmt_ip = hosting_device['management_ip_address']\n        dead_hd_list = self.get_dead_hosting_devices_info()\n        if hd_id in dead_hd_list:\n            LOG.debug(\"Hosting device: %(hd_id)s@%(ip)s is already marked as\"\n                      \" Dead. It is assigned as non-reachable\",\n                      {'hd_id': hd_id, 'ip': hd_mgmt_ip})\n            return False\n        if not isinstance(hd['created_at'], datetime.datetime):\n            hd['created_at'] = datetime.datetime.strptime(hd['created_at'],\n                                                          '%Y-%m-%d %H:%M:%S')\n        if _is_pingable(hd_mgmt_ip):\n            LOG.debug(\"Hosting device: %(hd_id)s@%(ip)s is reachable.\",\n                      {'hd_id': hd_id, 'ip': hd_mgmt_ip})\n            hd['hd_state'] = cc.HD_ACTIVE\n            ret_val = True\n        else:\n            LOG.debug(\"Hosting device: %(hd_id)s@%(ip)s is NOT reachable.\",\n                      {'hd_id': hd_id, 'ip': hd_mgmt_ip})\n            hd['hd_state'] = cc.HD_NOT_RESPONDING\n            ret_val = False\n        if self.enable_heartbeat is True or ret_val is False:\n            self.backlog_hosting_device(hd)\n        return ret_val",
    "docstring": "Check the hosting device which hosts this resource is reachable.\n\n        If the resource is not reachable, it is added to the backlog.\n\n        * heartbeat revision\n\n        We want to enqueue all hosting-devices into the backlog for\n        monitoring purposes\n\n        adds key/value pairs to  hd (aka hosting_device dictionary)\n\n        _is_pingable : if it returns true,\n            hd['hd_state']='Active'\n        _is_pingable : if it returns false,\n            hd['hd_state']='Unknown'\n\n        :param hosting_device : dict of the hosting device\n        :returns: True if device is reachable, else None"
  },
  {
    "code": "def random_word(self, length, prefix=0, start=False, end=False,\n                    flatten=False):\n        if start:\n            word = \">\"\n            length += 1\n            return self._extend_word(word, length, prefix=prefix, end=end,\n                                     flatten=flatten)[1:]\n        else:\n            first_letters = list(k for k in self if len(k) == 1 and k != \">\")\n            while True:\n                word = random.choice(first_letters)\n                try:\n                    word = self._extend_word(word, length, prefix=prefix,\n                                             end=end, flatten=flatten)\n                    return word\n                except GenerationError:\n                    first_letters.remove(word[0])",
    "docstring": "Generate a random word of length from this table.\n\n        :param length: the length of the generated word; >= 1;\n        :param prefix: if greater than 0, the maximum length of the prefix to\n                       consider to choose the next character;\n        :param start: if True, the generated word starts as a word of table;\n        :param end: if True, the generated word ends as a word of table;\n        :param flatten: whether or not consider the table as flattened;\n        :return: a random word of length generated from table.\n        :raises GenerationError: if no word of length can be generated."
  },
  {
    "code": "def _validate(wdl_file):\n    start_dir = os.getcwd()\n    os.chdir(os.path.dirname(wdl_file))\n    print(\"Validating\", wdl_file)\n    subprocess.check_call([\"wdltool\", \"validate\", wdl_file])\n    os.chdir(start_dir)",
    "docstring": "Run validation on the generated WDL output using wdltool."
  },
  {
    "code": "def _new_from_cdata(cls, cdata: Any) -> \"Random\":\n        self = object.__new__(cls)\n        self.random_c = cdata\n        return self",
    "docstring": "Return a new instance encapsulating this cdata."
  },
  {
    "code": "def find_tags(self, tag_name, **attribute_filter):\n        all_tags = [\n            self.find_tags_from_xml(\n                i, tag_name, **attribute_filter\n            )\n            for i in self.xml\n        ]\n        return [tag for tag_list in all_tags for tag in tag_list]",
    "docstring": "Return a list of all the matched tags in all available xml\n\n        :param str tag: specify the tag name"
  },
  {
    "code": "def set_ssl_logging(self, enable=False, func=_ssl_logging_cb):\n        u\n        if enable:\n            SSL_CTX_set_info_callback(self._ctx, func)\n        else:\n            SSL_CTX_set_info_callback(self._ctx, 0)",
    "docstring": "u''' Enable or disable SSL logging\n\n        :param True | False enable: Enable or disable SSL logging\n        :param func: Callback function for logging"
  },
  {
    "code": "def send(self, cumulative_counters=None, gauges=None, counters=None):\n        if not gauges and not cumulative_counters and not counters:\n            return\n        data = {\n            'cumulative_counter': cumulative_counters,\n            'gauge': gauges,\n            'counter': counters,\n        }\n        _logger.debug('Sending datapoints to SignalFx: %s', data)\n        for metric_type, datapoints in data.items():\n            if not datapoints:\n                continue\n            if not isinstance(datapoints, list):\n                raise TypeError('Datapoints not of type list %s', datapoints)\n            for datapoint in datapoints:\n                self._add_extra_dimensions(datapoint)\n                self._add_to_queue(metric_type, datapoint)\n        self._start_thread()",
    "docstring": "Send the given metrics to SignalFx.\n\n        Args:\n            cumulative_counters (list): a list of dictionaries representing the\n                cumulative counters to report.\n            gauges (list): a list of dictionaries representing the gauges to\n                report.\n            counters (list): a list of dictionaries representing the counters\n                to report."
  },
  {
    "code": "def check_cache(resource_type):\n    def decorator(func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            try:\n                adapter = args[0]\n                key, val = list(kwargs.items())[0]\n            except IndexError:\n                logger.warning(\"Couldn't generate full index key, skipping cache\")\n            else:\n                index_key = (resource_type, key, val)\n                try:\n                    cached_record = adapter._swimlane.resources_cache[index_key]\n                except KeyError:\n                    logger.debug('Cache miss: `{!r}`'.format(index_key))\n                else:\n                    logger.debug('Cache hit: `{!r}`'.format(cached_record))\n                    return cached_record\n            return func(*args, **kwargs)\n        return wrapper\n    return decorator",
    "docstring": "Decorator for adapter methods to check cache for resource before normally sending requests to retrieve data\n\n    Only works with single kwargs, almost always used with @one_of_keyword_only decorator\n\n    Args:\n        resource_type (type(APIResource)): Subclass of APIResource of cache to be checked when called"
  },
  {
    "code": "def get_account_details(self, account):\n        result = self.get_user(account.username)\n        if result is None:\n            result = {}\n        return result",
    "docstring": "Get the account details"
  },
  {
    "code": "def outbox_folder(self):\n        return self.folder_constructor(parent=self, name='Outbox',\n                                       folder_id=OutlookWellKnowFolderNames\n                                       .OUTBOX.value)",
    "docstring": "Shortcut to get Outbox Folder instance\n\n        :rtype: mailbox.Folder"
  },
  {
    "code": "def removeRow(self, triggered):\n        if triggered:\n            model = self.tableView.model()\n            selection = self.tableView.selectedIndexes()\n            rows = [index.row() for index in selection]\n            model.removeDataFrameRows(set(rows))\n            self.sender().setChecked(False)",
    "docstring": "Removes a row to the model.\n\n        This method is also a slot.\n\n        Args:\n            triggered (bool): If the corresponding button was\n                activated, the selected row will be removed\n                from the model."
  },
  {
    "code": "def _get_other_names(self, line):\n        m = re.search(self.compound_regex['other_names'][0], line, re.IGNORECASE)\n        if m:\n            self.other_names.append(m.group(1).strip())",
    "docstring": "Parse and extract any other names that might be recorded for the compound\n\n        Args:\n             line (str): line of the msp file"
  },
  {
    "code": "def exc_handle(url, out, testing):\n    quiet_exceptions = [ConnectionError, ReadTimeout, ConnectTimeout,\n            TooManyRedirects]\n    type, value, _ = sys.exc_info()\n    if type not in quiet_exceptions or testing:\n        exc = traceback.format_exc()\n        exc_string = (\"Line '%s' raised:\\n\" % url) + exc\n        out.warn(exc_string, whitespace_strp=False)\n        if testing:\n            print(exc)\n    else:\n        exc_string = \"Line %s '%s: %s'\" % (url, type, value)\n        out.warn(exc_string)",
    "docstring": "Handle exception. If of a determinate subset, it is stored into a file as a\n    single type. Otherwise, full stack is stored. Furthermore, if testing, stack\n    is always shown.\n    @param url: url which was being scanned when exception was thrown.\n    @param out: Output object, usually self.out.\n    @param testing: whether we are currently running unit tests."
  },
  {
    "code": "def async_iter(func, args_iter, **kwargs):\n    iter_count = len(args_iter)\n    iter_group = uuid()[1]\n    options = kwargs.get('q_options', kwargs)\n    options.pop('hook', None)\n    options['broker'] = options.get('broker', get_broker())\n    options['group'] = iter_group\n    options['iter_count'] = iter_count\n    if options.get('cached', None):\n        options['iter_cached'] = options['cached']\n    options['cached'] = True\n    broker = options['broker']\n    broker.cache.set('{}:{}:args'.format(broker.list_key, iter_group), SignedPackage.dumps(args_iter))\n    for args in args_iter:\n        if not isinstance(args, tuple):\n            args = (args,)\n        async_task(func, *args, **options)\n    return iter_group",
    "docstring": "enqueues a function with iterable arguments"
  },
  {
    "code": "def children_with_values(self):\n        childs = []\n        for attribute in self._get_all_c_children_with_order():\n            member = getattr(self, attribute)\n            if member is None or member == []:\n                pass\n            elif isinstance(member, list):\n                for instance in member:\n                    childs.append(instance)\n            else:\n                childs.append(member)\n        return childs",
    "docstring": "Returns all children that has values\n\n        :return: Possibly empty list of children."
  },
  {
    "code": "def model_m2m_changed(sender, instance, action, **kwargs):\n    if sender._meta.app_label == 'rest_framework_reactive':\n        return\n    def notify():\n        table = sender._meta.db_table\n        if action == 'post_add':\n            notify_observers(table, ORM_NOTIFY_KIND_CREATE)\n        elif action in ('post_remove', 'post_clear'):\n            notify_observers(table, ORM_NOTIFY_KIND_DELETE)\n    transaction.on_commit(notify)",
    "docstring": "Signal emitted after any M2M relation changes via Django ORM.\n\n    :param sender: M2M intermediate model\n    :param instance: The actual instance that was saved\n    :param action: M2M action"
  },
  {
    "code": "def url_ok(match_tuple: MatchTuple) -> bool:\n    try:\n        result = requests.get(match_tuple.link, timeout=5)\n        return result.ok\n    except (requests.ConnectionError, requests.Timeout):\n        return False",
    "docstring": "Check if a URL is reachable."
  },
  {
    "code": "def _getFromDate(l, date):\r\n    try:\r\n        date = _toDate(date)\r\n        i = _insertDateIndex(date, l) - 1\r\n        if i == -1:\r\n            return l[0]\r\n        return l[i]\r\n    except (ValueError, TypeError):\r\n        return l[0]",
    "docstring": "returns the index of given or best fitting date"
  },
  {
    "code": "def _fill_col_borders(self):\n        first = True\n        last = True\n        if self.col_indices[0] == self.hcol_indices[0]:\n            first = False\n        if self.col_indices[-1] == self.hcol_indices[-1]:\n            last = False\n        for num, data in enumerate(self.tie_data):\n            self.tie_data[num] = self._extrapolate_cols(data, first, last)\n        if first and last:\n            self.col_indices = np.concatenate((np.array([self.hcol_indices[0]]),\n                                               self.col_indices,\n                                               np.array([self.hcol_indices[-1]])))\n        elif first:\n            self.col_indices = np.concatenate((np.array([self.hcol_indices[0]]),\n                                               self.col_indices))\n        elif last:\n            self.col_indices = np.concatenate((self.col_indices,\n                                               np.array([self.hcol_indices[-1]])))",
    "docstring": "Add the first and last column to the data by extrapolation."
  },
  {
    "code": "def from_gpx(gpx_track_point):\n        return Point(\n            lat=gpx_track_point.latitude,\n            lon=gpx_track_point.longitude,\n            time=gpx_track_point.time\n        )",
    "docstring": "Creates a point from GPX representation\n\n        Arguments:\n            gpx_track_point (:obj:`gpxpy.GPXTrackPoint`)\n        Returns:\n            :obj:`Point`"
  },
  {
    "code": "def create_eager_metrics_for_problem(problem, model_hparams):\n  metric_fns = problem.eval_metric_fns(model_hparams)\n  problem_hparams = problem.get_hparams(model_hparams)\n  target_modality = problem_hparams.modality[\"targets\"]\n  weights_fn = model_hparams.weights_fn.get(\n      \"targets\",\n      modalities.get_weights_fn(target_modality))\n  return create_eager_metrics_internal(metric_fns, weights_fn=weights_fn)",
    "docstring": "See create_eager_metrics."
  },
  {
    "code": "def echo(msg, *args, **kwargs):\n    file = kwargs.pop('file', None)\n    nl = kwargs.pop('nl', True)\n    err = kwargs.pop('err', False)\n    color = kwargs.pop('color', None)\n    msg = safe_unicode(msg).format(*args, **kwargs)\n    click.echo(msg, file=file, nl=nl, err=err, color=color)",
    "docstring": "Wraps click.echo, handles formatting and check encoding"
  },
  {
    "code": "def parallel_split_combine(args, split_fn, parallel_fn,\n                           parallel_name, combiner,\n                           file_key, combine_arg_keys, split_outfile_i=-1):\n    args = [x[0] for x in args]\n    split_args, combine_map, finished_out, extras = _get_split_tasks(args, split_fn, file_key,\n                                                                     split_outfile_i)\n    split_output = parallel_fn(parallel_name, split_args)\n    if isinstance(combiner, six.string_types):\n        combine_args, final_args = _organize_output(split_output, combine_map,\n                                                    file_key, combine_arg_keys)\n        parallel_fn(combiner, combine_args)\n    elif callable(combiner):\n        final_args = combiner(split_output, combine_map, file_key)\n    return finished_out + final_args + extras",
    "docstring": "Split, run split items in parallel then combine to output file.\n\n    split_fn: Split an input file into parts for processing. Returns\n      the name of the combined output file along with the individual\n      split output names and arguments for the parallel function.\n    parallel_fn: Reference to run_parallel function that will run\n      single core, multicore, or distributed as needed.\n    parallel_name: The name of the function, defined in\n      bcbio.distributed.tasks/multitasks/ipythontasks to run in parallel.\n    combiner: The name of the function, also from tasks, that combines\n      the split output files into a final ready to run file. Can also\n      be a callable function if combining is delayed.\n    split_outfile_i: the location of the output file in the arguments\n      generated by the split function. Defaults to the last item in the list."
  },
  {
    "code": "async def _close(self):\n        try:\n            if self._hb_inbox_sid is not None:\n                await self._nc.unsubscribe(self._hb_inbox_sid)\n                self._hb_inbox = None\n                self._hb_inbox_sid = None\n            if self._ack_subject_sid is not None:\n                await self._nc.unsubscribe(self._ack_subject_sid)\n                self._ack_subject = None\n                self._ack_subject_sid = None\n        except:\n            pass\n        for _, sub in self._sub_map.items():\n            if sub._msgs_task is not None:\n                sub._msgs_task.cancel()\n            try:\n                await self._nc.unsubscribe(sub.sid)\n            except:\n                continue\n        self._sub_map = {}",
    "docstring": "Removes any present internal state from the client."
  },
  {
    "code": "async def unsubscribe(self, topic):\n        if self.socket_type not in {SUB, XSUB}:\n            raise AssertionError(\n                \"A %s socket cannot unsubscribe.\" % self.socket_type.decode(),\n            )\n        self._subscriptions.remove(topic)\n        tasks = [\n            asyncio.ensure_future(\n                peer.connection.local_unsubscribe(topic),\n                loop=self.loop,\n            )\n            for peer in self._peers\n            if peer.connection\n        ]\n        if tasks:\n            try:\n                await asyncio.wait(tasks, loop=self.loop)\n            finally:\n                for task in tasks:\n                    task.cancel()",
    "docstring": "Unsubscribe the socket from the specified topic.\n\n        :param topic: The topic to unsubscribe from."
  },
  {
    "code": "def _deploy_and_remember(\n            self,\n            contract_name: str,\n            arguments: List,\n            deployed_contracts: 'DeployedContracts',\n    ) -> Contract:\n        receipt = self.deploy(contract_name, arguments)\n        deployed_contracts['contracts'][contract_name] = _deployed_data_from_receipt(\n            receipt=receipt,\n            constructor_arguments=arguments,\n        )\n        return self.web3.eth.contract(\n            abi=self.contract_manager.get_contract_abi(contract_name),\n            address=deployed_contracts['contracts'][contract_name]['address'],\n        )",
    "docstring": "Deploys contract_name with arguments and store the result in deployed_contracts."
  },
  {
    "code": "def get(self, telescope, band):\n        klass = self._bpass_classes.get(telescope)\n        if klass is None:\n            raise NotDefinedError('bandpass data for %s not defined', telescope)\n        bp = klass()\n        bp.registry = self\n        bp.telescope = telescope\n        bp.band = band\n        return bp",
    "docstring": "Get a Bandpass object for a known telescope and filter."
  },
  {
    "code": "def _merge(self, a, b):\n        for k, v in a.items():\n            if isinstance(v, dict):\n                item = b.setdefault(k, {})\n                self._merge(v, item)\n            elif isinstance(v, list):\n                item = b.setdefault(k, [{}])\n                if len(v) == 1 and isinstance(v[0], dict):\n                    self._merge(v[0], item[0])\n                else:\n                    b[k] = v\n            else:\n                b[k] = v\n        return b",
    "docstring": "Merges a into b."
  },
  {
    "code": "def integer_squareroot(value: int) -> int:\n    if not isinstance(value, int) or isinstance(value, bool):\n        raise ValueError(\n            \"Value must be an integer: Got: {0}\".format(\n                type(value),\n            )\n        )\n    if value < 0:\n        raise ValueError(\n            \"Value cannot be negative: Got: {0}\".format(\n                value,\n            )\n        )\n    with decimal.localcontext() as ctx:\n        ctx.prec = 128\n        return int(decimal.Decimal(value).sqrt())",
    "docstring": "Return the integer square root of ``value``.\n\n    Uses Python's decimal module to compute the square root of ``value`` with\n    a precision of 128-bits. The value 128 is chosen since the largest square\n    root of a 256-bit integer is a 128-bit integer."
  },
  {
    "code": "def order_transforms(transforms):\n    outputs = set().union(*[t.outputs for t in transforms])\n    out = []\n    remaining = [t for t in transforms]\n    while remaining:\n        leftover = []\n        for t in remaining:\n            if t.inputs.isdisjoint(outputs):\n                out.append(t)\n                outputs -= t.outputs\n            else:\n                leftover.append(t)\n        remaining = leftover\n    return out",
    "docstring": "Orders transforms to ensure proper chaining.\n\n    For example, if `transforms = [B, A, C]`, and `A` produces outputs needed\n    by `B`, the transforms will be re-rorderd to `[A, B, C]`.\n\n    Parameters\n    ----------\n    transforms : list\n        List of transform instances to order.\n\n    Outputs\n    -------\n    list :\n        List of transformed ordered such that forward transforms can be carried\n        out without error."
  },
  {
    "code": "def add_job(self, id, func, **kwargs):\n        job_def = dict(kwargs)\n        job_def['id'] = id\n        job_def['func'] = func\n        job_def['name'] = job_def.get('name') or id\n        fix_job_def(job_def)\n        return self._scheduler.add_job(**job_def)",
    "docstring": "Add the given job to the job list and wakes up the scheduler if it's already running.\n\n        :param str id: explicit identifier for the job (for modifying it later)\n        :param func: callable (or a textual reference to one) to run at the given time"
  },
  {
    "code": "def _find_geophysical_vars(self, ds, refresh=False):\n        if self._geophysical_vars.get(ds, None) and refresh is False:\n            return self._geophysical_vars[ds]\n        self._geophysical_vars[ds] = cfutil.get_geophysical_variables(ds)\n        return self._geophysical_vars[ds]",
    "docstring": "Returns a list of geophysical variables.  Modifies\n        `self._geophysical_vars`\n\n        :param netCDF4.Dataset ds: An open netCDF dataset\n        :param bool refresh: if refresh is set to True, the cache is\n                             invalidated.\n        :rtype: list\n        :return: A list containing strings with geophysical variable\n                 names."
  },
  {
    "code": "def get_template_loader(self, subdir='templates'):\n        if self.request is None:\n            raise ValueError(\"this method can only be called after the view middleware is run. Check that `django_mako_plus.middleware` is in MIDDLEWARE.\")\n        dmp = apps.get_app_config('django_mako_plus')\n        return dmp.engine.get_template_loader(self.app, subdir)",
    "docstring": "App-specific function to get the current app's template loader"
  },
  {
    "code": "def get_data(self):\n        data = []\n        ntobj = cx.namedtuple(\"NtGoCnt\", \"Depth_Level BP_D MF_D CC_D BP_L MF_L CC_L\")\n        cnts = self.get_cnts_levels_depths_recs(set(self.obo.values()))\n        max_val = max(max(dep for dep in cnts['depth']), max(lev for lev in cnts['level']))\n        for i in range(max_val+1):\n            vals = [i] + [cnts[desc][i][ns] for desc in cnts for ns in self.nss]\n            data.append(ntobj._make(vals))\n        return data",
    "docstring": "Collect counts of GO terms at all levels and depths."
  },
  {
    "code": "def bootstrap_auc(df, col, pred_col, n_bootstrap=1000):\n    scores = np.zeros(n_bootstrap)\n    old_len = len(df)\n    df.dropna(subset=[col], inplace=True)\n    new_len = len(df)\n    if new_len < old_len:\n        logger.info(\"Dropping NaN values in %s to go from %d to %d rows\" % (col, old_len, new_len))\n    preds = df[pred_col].astype(int)\n    for i in range(n_bootstrap):\n        sampled_counts, sampled_pred = resample(df[col], preds)\n        if is_single_class(sampled_pred, col=pred_col):\n            continue\n        scores[i] = roc_auc_score(sampled_pred, sampled_counts)\n    return scores",
    "docstring": "Calculate the boostrapped AUC for a given col trying to predict a pred_col.\n\n    Parameters\n    ----------\n    df : pandas.DataFrame\n    col : str\n        column to retrieve the values from\n    pred_col : str\n        the column we're trying to predict\n    n_boostrap : int\n        the number of bootstrap samples\n\n    Returns\n    -------\n    list : AUCs for each sampling"
  },
  {
    "code": "def decompile(f):\n    co = f.__code__\n    args, kwonly, varargs, varkwargs = paramnames(co)\n    annotations = f.__annotations__ or {}\n    defaults = list(f.__defaults__ or ())\n    kw_defaults = f.__kwdefaults__ or {}\n    if f.__name__ == '<lambda>':\n        node = ast.Lambda\n        body = pycode_to_body(co, DecompilationContext(in_lambda=True))[0]\n        extra_kwargs = {}\n    else:\n        node = ast.FunctionDef\n        body = pycode_to_body(co, DecompilationContext(in_function_block=True))\n        extra_kwargs = {\n            'decorator_list': [],\n            'returns': annotations.get('return')\n        }\n    return node(\n        name=f.__name__,\n        args=make_function_arguments(\n            args=args,\n            kwonly=kwonly,\n            varargs=varargs,\n            varkwargs=varkwargs,\n            defaults=defaults,\n            kw_defaults=kw_defaults,\n            annotations=annotations,\n        ),\n        body=body,\n        **extra_kwargs\n    )",
    "docstring": "Decompile a function.\n\n    Parameters\n    ----------\n    f : function\n        The function to decompile.\n\n    Returns\n    -------\n    ast : ast.FunctionDef\n        A FunctionDef node that compiles to f."
  },
  {
    "code": "def _get_prefixes(self):\n        prefixes = {\n            \"@\": \"o\",\n            \"+\": \"v\",\n        }\n        feature_prefixes = self.server.features.get('PREFIX')\n        if feature_prefixes:\n            modes = feature_prefixes[1:len(feature_prefixes)//2]\n            symbols = feature_prefixes[len(feature_prefixes)//2+1:]\n            prefixes = dict(zip(symbols, modes))\n        return prefixes",
    "docstring": "Get the possible nick prefixes and associated modes for a client."
  },
  {
    "code": "def set_level_for_logger_and_its_handlers(log: logging.Logger,\n                                          level: int) -> None:\n    log.setLevel(level)\n    for h in log.handlers:\n        h.setLevel(level)",
    "docstring": "Set a log level for a log and all its handlers.\n\n    Args:\n        log: log to modify\n        level: log level to set"
  },
  {
    "code": "def workspace(show_values: bool = True, show_types: bool = True):\n    r = _get_report()\n    data = {}\n    for key, value in r.project.shared.fetch(None).items():\n        if key.startswith('__cauldron_'):\n            continue\n        data[key] = value\n    r.append_body(render.status(data, values=show_values, types=show_types))",
    "docstring": "Adds a list of the shared variables currently stored in the project\n    workspace.\n\n    :param show_values:\n        When true the values for each variable will be shown in addition to\n        their name.\n    :param show_types:\n        When true the data types for each shared variable will be shown in\n        addition to their name."
  },
  {
    "code": "def blurring_kernel(shape=None):\n    name = 'motionblur.mat'\n    url = URL_CAM + name\n    dct = get_data(name, subset=DATA_SUBSET, url=url)\n    return convert(255 - dct['im'], shape, normalize='sum')",
    "docstring": "Blurring kernel for convolution simulations.\n\n    The kernel is scaled to sum to one.\n\n    Returns\n    -------\n    An image with the following properties:\n        image type: gray scales\n        size: [100, 100] (if not specified by `size`)\n        scale: [0, 1]\n        type: float64"
  },
  {
    "code": "def get_element_coors(self, ig=None):\n        cc = self.coors\n        n_ep_max = self.n_e_ps.max()\n        coors = nm.empty((self.n_el, n_ep_max, self.dim), dtype=cc.dtype)\n        for ig, conn in enumerate(self.conns):\n            i1, i2 = self.el_offsets[ig], self.el_offsets[ig + 1]\n            coors[i1:i2, :conn.shape[1], :] = cc[conn]\n        return coors",
    "docstring": "Get the coordinates of vertices elements in group `ig`.\n\n        Parameters\n        ----------\n        ig : int, optional\n            The element group. If None, the coordinates for all groups\n            are returned, filled with zeros at places of missing\n            vertices, i.e. where elements having less then the full number\n            of vertices (`n_ep_max`) are.\n\n        Returns\n        -------\n        coors : array\n            The coordinates in an array of shape `(n_el, n_ep_max, dim)`."
  },
  {
    "code": "def verify_indices_all_unique(obj):\n    axis_names = [\n        ('index',),\n        ('index', 'columns'),\n        ('items', 'major_axis', 'minor_axis')\n    ][obj.ndim - 1]\n    for axis_name, index in zip(axis_names, obj.axes):\n        if index.is_unique:\n            continue\n        raise ValueError(\n            \"Duplicate entries in {type}.{axis}: {dupes}.\".format(\n                type=type(obj).__name__,\n                axis=axis_name,\n                dupes=sorted(index[index.duplicated()]),\n            )\n        )\n    return obj",
    "docstring": "Check that all axes of a pandas object are unique.\n\n    Parameters\n    ----------\n    obj : pd.Series / pd.DataFrame / pd.Panel\n        The object to validate.\n\n    Returns\n    -------\n    obj : pd.Series / pd.DataFrame / pd.Panel\n        The validated object, unchanged.\n\n    Raises\n    ------\n    ValueError\n        If any axis has duplicate entries."
  },
  {
    "code": "def delete_resource_scenario(scenario_id, resource_attr_id, quiet=False, **kwargs):\n    _check_can_edit_scenario(scenario_id, kwargs['user_id'])\n    _delete_resourcescenario(scenario_id, resource_attr_id, suppress_error=quiet)",
    "docstring": "Remove the data associated with a resource in a scenario."
  },
  {
    "code": "def format(self):\n        if self._format:\n            return self._format\n        elif self.pil_image:\n            return self.pil_image.format",
    "docstring": "The format of the image file.\n\n        An uppercase string corresponding to the\n        :attr:`PIL.ImageFile.ImageFile.format` attribute.  Valid values include\n        ``\"JPEG\"`` and ``\"PNG\"``."
  },
  {
    "code": "def checkin_bundle(self, db_path, replace=True, cb=None):\n        from ambry.orm.exc import NotFoundError\n        db = Database('sqlite:///{}'.format(db_path))\n        db.open()\n        if len(db.datasets) == 0:\n            raise NotFoundError(\"Did not get a dataset in the {} bundle\".format(db_path))\n        ds = db.dataset(db.datasets[0].vid)\n        assert ds is not None\n        assert ds._database\n        try:\n            b = self.bundle(ds.vid)\n            self.logger.info(\n                \"Removing old bundle before checking in new one of same number: '{}'\"\n                .format(ds.vid))\n            self.remove(b)\n        except NotFoundError:\n            pass\n        try:\n            self.dataset(ds.vid)\n        except NotFoundError:\n            self.database.copy_dataset(ds, cb=cb)\n        b = self.bundle(ds.vid)\n        b.commit()\n        self.search.index_bundle(b)\n        return b",
    "docstring": "Add a bundle, as a Sqlite file, to this library"
  },
  {
    "code": "def _get_target_from_package_name(self, target, package_name, file_path):\n    address_path = self.parse_file_path(file_path)\n    if not address_path:\n      return None\n    dep_spec_path = os.path.normpath(os.path.join(target.address.spec_path, address_path))\n    for dep in target.dependencies:\n      if dep.package_name == package_name and dep.address.spec_path == dep_spec_path:\n        return dep\n    return None",
    "docstring": "Get a dependent target given the package name and relative file path.\n\n    This will only traverse direct dependencies of the passed target. It is not necessary\n    to traverse further than that because transitive dependencies will be resolved under the\n    direct dependencies and every direct dependencies is symlinked to the target.\n\n    Returns `None` if the target does not exist.\n\n    :param NodePackage target: A subclass of NodePackage\n    :param string package_name: A package.json name that is required to be the same as the target name\n    :param string file_path: Relative filepath from target to the package in the format 'file:<address_path>'"
  },
  {
    "code": "def out(self, obj, formatter=None, out_file=None):\n        if not isinstance(obj, CommandResultItem):\n            raise TypeError('Expected {} got {}'.format(CommandResultItem.__name__, type(obj)))\n        import platform\n        import colorama\n        if platform.system() == 'Windows':\n            out_file = colorama.AnsiToWin32(out_file).stream\n        output = formatter(obj)\n        try:\n            print(output, file=out_file, end='')\n        except IOError as ex:\n            if ex.errno == errno.EPIPE:\n                pass\n            else:\n                raise\n        except UnicodeEncodeError:\n            print(output.encode('ascii', 'ignore').decode('utf-8', 'ignore'),\n                  file=out_file, end='')",
    "docstring": "Produces the output using the command result.\n            The method does not return a result as the output is written straight to the output file.\n\n        :param obj: The command result\n        :type obj: knack.util.CommandResultItem\n        :param formatter: The formatter we should use for the command result\n        :type formatter: function\n        :param out_file: The file to write output to\n        :type out_file: file-like object"
  },
  {
    "code": "def weld_cast_array(array, weld_type, to_weld_type):\n    if not is_numeric(weld_type) or not is_numeric(to_weld_type):\n        raise TypeError('Cannot cast array of type={} to type={}'.format(weld_type, to_weld_type))\n    obj_id, weld_obj = create_weld_object(array)\n    weld_template =\n    weld_obj.weld_code = weld_template.format(array=obj_id,\n                                              type=weld_type,\n                                              to=to_weld_type)\n    return weld_obj",
    "docstring": "Cast array to a different type.\n\n    Parameters\n    ----------\n    array : numpy.ndarray or WeldObject\n        Input data.\n    weld_type : WeldType\n        Type of each element in the input array.\n    to_weld_type : WeldType\n        Desired type.\n\n    Returns\n    -------\n    WeldObject\n        Representation of this computation."
  },
  {
    "code": "def _get_zipped_rows(self, soup):\r\n        table = soup.findChildren('table')[2]\r\n        rows = table.findChildren(['tr'])[:-2]\r\n        spacing = range(2, len(rows), 3)\r\n        rows = [row for (i, row) in enumerate(rows) if (i not in spacing)]\r\n        info = [row for (i, row) in enumerate(rows) if (i % 2 == 0)]\r\n        detail = [row for (i, row) in enumerate(rows) if (i % 2 != 0)]\r\n        return zip(info, detail)",
    "docstring": "Returns all 'tr' tag rows as a list of tuples. Each tuple is for\r\n        a single story."
  },
  {
    "code": "def _get_fw(self, msg, updates, req_fw_type=None, req_fw_ver=None):\n        fw_type = None\n        fw_ver = None\n        if not isinstance(updates, tuple):\n            updates = (updates, )\n        for store in updates:\n            fw_id = store.pop(msg.node_id, None)\n            if fw_id is not None:\n                fw_type, fw_ver = fw_id\n                updates[-1][msg.node_id] = fw_id\n                break\n        if fw_type is None or fw_ver is None:\n            _LOGGER.debug(\n                'Node %s is not set for firmware update', msg.node_id)\n            return None, None, None\n        if req_fw_type is not None and req_fw_ver is not None:\n            fw_type, fw_ver = req_fw_type, req_fw_ver\n        fware = self.firmware.get((fw_type, fw_ver))\n        if fware is None:\n            _LOGGER.debug(\n                'No firmware of type %s and version %s found',\n                fw_type, fw_ver)\n            return None, None, None\n        return fw_type, fw_ver, fware",
    "docstring": "Get firmware type, version and a dict holding binary data."
  },
  {
    "code": "def converts_values(self):\n        return self.convert_value is not Formatter.convert_value or \\\n               self.convert_column is not Formatter.convert_column",
    "docstring": "Whether this Formatter also converts values."
  },
  {
    "code": "def reindex_axis(self, labels, axis=0, **kwargs):\n        if axis != 0:\n            raise ValueError(\"cannot reindex series on non-zero axis!\")\n        msg = (\"'.reindex_axis' is deprecated and will be removed in a future \"\n               \"version. Use '.reindex' instead.\")\n        warnings.warn(msg, FutureWarning, stacklevel=2)\n        return self.reindex(index=labels, **kwargs)",
    "docstring": "Conform Series to new index with optional filling logic.\n\n        .. deprecated:: 0.21.0\n            Use ``Series.reindex`` instead."
  },
  {
    "code": "def colorize(occurence,maxoccurence,minoccurence):\n    if occurence == maxoccurence:\n        color = (255,0,0)\n    elif occurence == minoccurence:\n        color = (0,0,255)\n    else:\n        color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence*255))\n    return color",
    "docstring": "A formula for determining colors."
  },
  {
    "code": "def _GetPkgResources(package_name, filepath):\n  requirement = pkg_resources.Requirement.parse(package_name)\n  try:\n    return pkg_resources.resource_filename(requirement, filepath)\n  except pkg_resources.DistributionNotFound:\n    pkg_resources.working_set = pkg_resources.WorkingSet()\n    try:\n      return pkg_resources.resource_filename(requirement, filepath)\n    except pkg_resources.DistributionNotFound:\n      logging.error(\"Distribution %s not found. Is it installed?\", package_name)\n      return None",
    "docstring": "A wrapper for the `pkg_resource.resource_filename` function."
  },
  {
    "code": "def from_inline(cls: Type[UnlockType], inline: str) -> UnlockType:\n        data = Unlock.re_inline.match(inline)\n        if data is None:\n            raise MalformedDocumentError(\"Inline input\")\n        index = int(data.group(1))\n        parameters_str = data.group(2).split(' ')\n        parameters = []\n        for p in parameters_str:\n            param = UnlockParameter.from_parameter(p)\n            if param:\n                parameters.append(param)\n        return cls(index, parameters)",
    "docstring": "Return an Unlock instance from inline string format\n\n        :param inline: Inline string format\n\n        :return:"
  },
  {
    "code": "def extract_match(self, list_title_matches):\n        list_title_matches_set = set(list_title_matches)\n        list_title_count = []\n        for match in list_title_matches_set:\n            list_title_count.append((list_title_matches.count(match), match))\n        if list_title_count and max(list_title_count)[0] != min(list_title_count)[0]:\n            return max(list_title_count)[1]\n        return None",
    "docstring": "Extract the title with the most matches from the list.\n\n        :param list_title_matches: A list, the extracted titles which match with others\n        :return: A string, the most frequently extracted title."
  },
  {
    "code": "def show_domain_record(self, domain_id, record_id):\n        json = self.request('/domains/%s/records/%s' % (domain_id, record_id),\n                            method='GET')\n        status = json.get('status')\n        if status == 'OK':\n            domain_record_json = json.get('record')\n            domain_record = Record.from_json(domain_record_json)\n            return domain_record\n        else:\n            message = json.get('message')\n            raise DOPException('[%s]: %s' % (status, message))",
    "docstring": "This method returns the specified domain record.\n\n        Required parameters\n\n            domain_id:\n                Integer or Domain Name (e.g. domain.com), specifies the domain\n                for which to retrieve a record.\n\n            record_id:\n                Integer, specifies the record_id to retrieve."
  },
  {
    "code": "def random(self, namespace=0):\n        query = self.LIST.substitute(\n            WIKI=self.uri,\n            ENDPOINT=self.endpoint,\n            LIST='random')\n        query += \"&rnlimit=1&rnnamespace=%d\" % namespace\n        emoji = [\n            u'\\U0001f32f',\n            u'\\U0001f355',\n            u'\\U0001f35c',\n            u'\\U0001f363',\n            u'\\U0001f369',\n            u'\\U0001f36a',\n            u'\\U0001f36d',\n            u'\\U0001f370',\n        ]\n        action = 'random'\n        if namespace:\n            action = 'random:%d' % namespace\n        self.set_status(action, random.choice(emoji))\n        return query",
    "docstring": "Returns query string for random page"
  },
  {
    "code": "def message(self, msg):\n        for broker in self.message_brokers:\n            try:\n                broker(msg)\n            except Exception as exc:\n                utils.error(exc)",
    "docstring": "Send a message to third party applications"
  },
  {
    "code": "def set_riskfree_rate(self, rf):\n        self.rf = rf\n        self._update(self.prices)",
    "docstring": "Set annual risk-free rate property and calculate properly annualized\n        monthly and daily rates. Then performance stats are recalculated.\n        Affects only this instance of the PerformanceStats.\n\n        Args:\n            * rf (float): Annual `risk-free rate <https://www.investopedia.com/terms/r/risk-freerate.asp>`_"
  },
  {
    "code": "def attach_const_node(node, name, value):\n    if name not in node.special_attributes:\n        _attach_local_node(node, nodes.const_factory(value), name)",
    "docstring": "create a Const node and register it in the locals of the given\n    node with the specified name"
  },
  {
    "code": "def _reconstruct(self, path_to_root):\n        item_pattern = re.compile('\\d+\\\\]')\n        dot_pattern = re.compile('\\\\.|\\\\[')\n        path_segments = dot_pattern.split(path_to_root)\n        schema_endpoint = self.schema\n        if path_segments[1]:\n            for i in range(1,len(path_segments)):\n                if item_pattern.match(path_segments[i]):\n                    schema_endpoint = schema_endpoint[0]\n                else:\n                    schema_endpoint = schema_endpoint[path_segments[i]]\n        return schema_endpoint",
    "docstring": "a helper method for finding the schema endpoint from a path to root\n\n        :param path_to_root: string with dot path to root from\n        :return: list, dict, string, number, or boolean at path to root"
  },
  {
    "code": "def max_frequency (sig,FS):\n    f, fs = plotfft(sig, FS, doplot=False)    \n    t = cumsum(fs)\n    ind_mag = find (t>t[-1]*0.95)[0]\n    f_max=f[ind_mag]\n    return f_max",
    "docstring": "Compute max frequency along the specified axes.\n\n    Parameters\n    ----------\n    sig: ndarray\n        input from which max frequency is computed.\n    FS: int\n        sampling frequency    \n    Returns\n    -------\n    f_max: int\n       0.95 of max_frequency using cumsum."
  },
  {
    "code": "def get(self, key):\n    value = None\n    for store in self._stores:\n      value = store.get(key)\n      if value is not None:\n        break\n    if value is not None:\n      for store2 in self._stores:\n        if store == store2:\n          break\n        store2.put(key, value)\n    return value",
    "docstring": "Return the object named by key. Checks each datastore in order."
  },
  {
    "code": "def drop_udf(\n        self,\n        name,\n        input_types=None,\n        database=None,\n        force=False,\n        aggregate=False,\n    ):\n        if not input_types:\n            if not database:\n                database = self.current_database\n            result = self.list_udfs(database=database, like=name)\n            if len(result) > 1:\n                if force:\n                    for func in result:\n                        self._drop_single_function(\n                            func.name,\n                            func.inputs,\n                            database=database,\n                            aggregate=aggregate,\n                        )\n                    return\n                else:\n                    raise Exception(\n                        \"More than one function \"\n                        + \"with {0} found.\".format(name)\n                        + \"Please specify force=True\"\n                    )\n            elif len(result) == 1:\n                func = result.pop()\n                self._drop_single_function(\n                    func.name,\n                    func.inputs,\n                    database=database,\n                    aggregate=aggregate,\n                )\n                return\n            else:\n                raise Exception(\"No function found with name {0}\".format(name))\n        self._drop_single_function(\n            name, input_types, database=database, aggregate=aggregate\n        )",
    "docstring": "Drops a UDF\n        If only name is given, this will search\n        for the relevant UDF and drop it.\n        To delete an overloaded UDF, give only a name and force=True\n\n        Parameters\n        ----------\n        name : string\n        input_types : list of strings (optional)\n        force : boolean, default False Must be set to true to\n                drop overloaded UDFs\n        database : string, default None\n        aggregate : boolean, default False"
  },
  {
    "code": "def get_screen_settings(self, screen_id):\n        if not isinstance(screen_id, baseinteger):\n            raise TypeError(\"screen_id can only be an instance of type baseinteger\")\n        record_screen_settings = self._call(\"getScreenSettings\",\n                     in_p=[screen_id])\n        record_screen_settings = IRecordingScreenSettings(record_screen_settings)\n        return record_screen_settings",
    "docstring": "Returns the recording settings for a particular screen.\n\n        in screen_id of type int\n            Screen ID to retrieve recording screen settings for.\n\n        return record_screen_settings of type :class:`IRecordingScreenSettings`\n            Recording screen settings for the requested screen."
  },
  {
    "code": "def commit_format(self):\n        formatted_analyses = []\n        for analyze in self.analysis['messages']:\n            formatted_analyses.append({\n                'message': f\"{analyze['source']}: {analyze['message']}. Code: {analyze['code']}\",\n                'file': analyze['location']['path'],\n                'line': analyze['location']['line'],\n            })\n        return formatted_analyses",
    "docstring": "Formats the analysis into a simpler dictionary with the line, file and message values to\n            be commented on a commit.\n        Returns a list of dictionaries"
  },
  {
    "code": "def true_false_returns(func):\n    @functools.wraps(func)\n    def _execute(*args, **kwargs):\n        try:\n            func(*args, **kwargs)\n            return True\n        except:\n            return False\n    return _execute",
    "docstring": "Executes function, if error returns False, else True\n\n    :param func: function to call\n    :return: True iff ok, else False"
  },
  {
    "code": "def m_quadratic_sum(A, B, max_it=50):\n    r\n    gamma1 = solve_discrete_lyapunov(A, B, max_it)\n    return gamma1",
    "docstring": "r\"\"\"\n    Computes the quadratic sum\n\n    .. math::\n\n        V = \\sum_{j=0}^{\\infty} A^j B A^{j'}\n\n    V is computed by solving the corresponding discrete lyapunov\n    equation using the doubling algorithm.  See the documentation of\n    `util.solve_discrete_lyapunov` for more information.\n\n    Parameters\n    ----------\n    A : array_like(float, ndim=2)\n        An n x n matrix as described above.  We assume in order for\n        convergence that the eigenvalues of :math:`A` have moduli bounded by\n        unity\n    B : array_like(float, ndim=2)\n        An n x n matrix as described above.  We assume in order for\n        convergence that the eigenvalues of :math:`A` have moduli bounded by\n        unity\n    max_it : scalar(int), optional(default=50)\n        The maximum number of iterations\n\n    Returns\n    ========\n    gamma1: array_like(float, ndim=2)\n        Represents the value :math:`V`"
  },
  {
    "code": "def dispatch_url(self, url_string):\n        url, url_adapter, query_args = self.parse_url(url_string)\n        try:\n            endpoint, kwargs = url_adapter.match()\n        except NotFound:\n            raise NotSupported(url_string)\n        except RequestRedirect as e:\n            new_url = \"{0.new_url}?{1}\".format(e, url_encode(query_args))\n            return self.dispatch_url(new_url)\n        try:\n            handler = import_string(endpoint)\n            request = Request(url=url, args=query_args)\n            return handler(request, **kwargs)\n        except RequestRedirect as e:\n            return self.dispatch_url(e.new_url)",
    "docstring": "Dispatch the URL string to the target endpoint function.\n\n        :param url_string: the origin URL string.\n        :returns: the return value of calling dispatched function."
  },
  {
    "code": "def _build(self, inputs):\n    shape_inputs = inputs.get_shape().as_list()\n    rank = len(shape_inputs)\n    max_dim = np.max(self._dims) + 1\n    if rank < max_dim:\n      raise ValueError(\"Rank of inputs must be at least {}.\".format(max_dim))\n    full_begin = [0] * rank\n    full_size = [-1] * rank\n    for dim, begin, size in zip(self._dims, self._begin, self._size):\n      full_begin[dim] = begin\n      full_size[dim] = size\n    return tf.slice(inputs, begin=full_begin, size=full_size)",
    "docstring": "Connects the SliceByDim module into the graph.\n\n    Args:\n      inputs: `Tensor` to slice. Its rank must be greater than the maximum\n          dimension specified in `dims` (plus one as python is 0 indexed).\n\n    Returns:\n      The sliced tensor.\n\n    Raises:\n      ValueError: If `inputs` tensor has insufficient rank."
  },
  {
    "code": "def clean_registration_ids(self, registration_ids=[]):\n        valid_registration_ids = []\n        for registration_id in registration_ids:\n            details = self.registration_info_request(registration_id)\n            if details.status_code == 200:\n                valid_registration_ids.append(registration_id)\n        return valid_registration_ids",
    "docstring": "Checks registration ids and excludes inactive ids\n\n        Args:\n            registration_ids (list, optional): list of ids to be cleaned\n\n        Returns:\n            list: cleaned registration ids"
  },
  {
    "code": "def from_array(array):\n        if array is None or not array:\n            return None\n        assert_type_or_raise(array, dict, parameter_name=\"array\")\n        data = {}\n        data['label'] = u(array.get('label'))\n        data['amount'] = int(array.get('amount'))\n        instance = LabeledPrice(**data)\n        instance._raw = array\n        return instance",
    "docstring": "Deserialize a new LabeledPrice from a given dictionary.\n\n        :return: new LabeledPrice instance.\n        :rtype: LabeledPrice"
  },
  {
    "code": "def on_view_not_found(\n            self,\n            environ: Dict[str, Any],\n            start_response: Callable[[str, List[Tuple[str, str]]], None],\n    ) -> Iterable[bytes]:\n        start_response('404 Not Found', [('Content-type', 'text/plain')])\n        return [b'Not found']",
    "docstring": "called when views not found"
  },
  {
    "code": "def findWCSExtn(filename):\n    rootname,extroot = fileutil.parseFilename(filename)\n    extnum = None\n    if extroot is None:\n        fimg = fits.open(rootname, memmap=False)\n        for i,extn in enumerate(fimg):\n            if 'crval1' in extn.header:\n                refwcs = wcsutil.HSTWCS('{}[{}]'.format(rootname,i))\n                if refwcs.wcs.has_cd():\n                    extnum = '{}'.format(i)\n                    break\n        fimg.close()\n    else:\n        try:\n            refwcs = wcsutil.HSTWCS(filename)\n            if refwcs.wcs.has_cd():\n                extnum = extroot\n        except:\n            extnum = None\n    return extnum",
    "docstring": "Return new filename with extension that points to an extension with a\n        valid WCS.\n\n        Returns\n        =======\n        extnum : str, None\n            Value of extension name as a string either as provided by the user\n            or based on the extension number for the first extension which\n            contains a valid HSTWCS object.  Returns None if no extension can be\n            found with a valid WCS.\n\n        Notes\n        =====\n        The return value from this function can be used as input to\n            create another HSTWCS with the syntax::\n\n                `HSTWCS('{}[{}]'.format(filename,extnum))"
  },
  {
    "code": "def lockfile(path):\n    with genfile(path) as fd:\n        fcntl.lockf(fd, fcntl.LOCK_EX)\n        yield None",
    "docstring": "A file lock with-block helper.\n\n    Args:\n        path (str): A path to a lock file.\n\n    Examples:\n\n        Get the lock on a file and dostuff while having the lock::\n\n            path = '/hehe/haha.lock'\n            with lockfile(path):\n                dostuff()\n\n    Notes:\n        This is curently based on fcntl.lockf(), and as such, it is purely\n        advisory locking. If multiple processes are attempting to obtain a\n        lock on the same file, this will block until the process which has\n        the current lock releases it.\n\n    Yields:\n        None"
  },
  {
    "code": "def new_request(sender, request=None, notify=True, **kwargs):\n    if current_app.config['COMMUNITIES_MAIL_ENABLED'] and notify:\n        send_community_request_email(request)",
    "docstring": "New request for inclusion."
  },
  {
    "code": "def observed(self, band, corrected=True):\n        if band not in 'ugriz':\n            raise ValueError(\"band='{0}' not recognized\".format(band))\n        i = 'ugriz'.find(band)\n        t, y, dy = self.lcdata.get_lightcurve(self.lcid, return_1d=False)\n        if corrected:\n            ext = self.obsmeta['rExt'] * self.ext_correction[band]\n        else:\n            ext = 0\n        return t[:, i], y[:, i] - ext, dy[:, i]",
    "docstring": "Return observed values in the given band\n\n        Parameters\n        ----------\n        band : str\n            desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z']\n        corrected : bool (optional)\n            If true, correct for extinction\n\n        Returns\n        -------\n        t, mag, dmag : ndarrays\n            The times, magnitudes, and magnitude errors for the specified band."
  },
  {
    "code": "def _FormatOtherFileToken(self, token_data):\n    timestamp = token_data.microseconds + (\n        token_data.timestamp * definitions.MICROSECONDS_PER_SECOND)\n    date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(\n        timestamp=timestamp)\n    date_time_string = date_time.CopyToDateTimeString()\n    return {\n        'string': token_data.name.rstrip('\\x00'),\n        'timestamp': date_time_string}",
    "docstring": "Formats an other file token as a dictionary of values.\n\n    Args:\n      token_data (bsm_token_data_other_file32): AUT_OTHER_FILE32 token data.\n\n    Returns:\n      dict[str, str]: token values."
  },
  {
    "code": "async def generate_wallet_key(config: Optional[str]) -> str:\n    logger = logging.getLogger(__name__)\n    logger.debug(\"generate_wallet_key: >>> config: %r\",\n                 config)\n    if not hasattr(generate_wallet_key, \"cb\"):\n        logger.debug(\"generate_wallet_key: Creating callback\")\n        generate_wallet_key.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_char_p))\n    c_config = c_char_p(config.encode('utf-8')) if config is not None else None\n    key = await do_call('indy_generate_wallet_key',\n                        c_config,\n                        generate_wallet_key.cb)\n    res = key.decode()\n    logger.debug(\"generate_wallet_key: <<< res: %r\", res)\n    return res",
    "docstring": "Generate wallet master key.\n    Returned key is compatible with \"RAW\" key derivation method.\n    It allows to avoid expensive key derivation for use cases when wallet keys can be stored in a secure enclave.\n\n    :param config: (optional) key configuration json.\n     {\n        \"seed\": string, (optional) Seed that allows deterministic key creation (if not set random one will be created).\n                                   Can be UTF-8, base64 or hex string.\n     }\n    :return: Error code"
  },
  {
    "code": "def info(self, message, domain=None):\n        if domain is None:\n            domain = self.extension_name\n        info(message, domain)",
    "docstring": "Shortcut function for `utils.loggable.info`\n\n        Args:\n            message: see `utils.loggable.info`\n            domain: see `utils.loggable.info`"
  },
  {
    "code": "def get_multipart_md5(self, filename, chunk_size=8 * 1024 * 1024):\n        md5s = []\n        with open(filename, 'rb') as fp:\n            while True:\n                data = fp.read(chunk_size)\n                if not data:\n                    break\n                md5s.append(hashlib.md5(data))\n        digests = b\"\".join(m.digest() for m in md5s)\n        new_md5 = hashlib.md5(digests)\n        new_etag = '\"%s-%s\"' % (new_md5.hexdigest(), len(md5s))\n        return new_etag.strip('\"').strip(\"'\")",
    "docstring": "Returns the md5 checksum of the provided file name after breaking it into chunks.\n\n        This is done to mirror the method used by Amazon S3 after a multipart upload."
  },
  {
    "code": "def update_logo_preview(self):\n        logo_path = self.organisation_logo_path_line_edit.text()\n        if os.path.exists(logo_path):\n            icon = QPixmap(logo_path)\n            label_size = self.organisation_logo_label.size()\n            label_size.setHeight(label_size.height() - 2)\n            label_size.setWidth(label_size.width() - 2)\n            scaled_icon = icon.scaled(\n                label_size, Qt.KeepAspectRatio)\n            self.organisation_logo_label.setPixmap(scaled_icon)\n        else:\n            self.organisation_logo_label.setText(tr(\"Logo not found\"))",
    "docstring": "Update logo based on the current logo path."
  },
  {
    "code": "def get(ctx, key):\n    file = ctx.obj['FILE']\n    stored_value = get_key(file, key)\n    if stored_value:\n        click.echo('%s=%s' % (key, stored_value))\n    else:\n        exit(1)",
    "docstring": "Retrieve the value for the given key."
  },
  {
    "code": "def map_to_matype(self, matype):\n        try:\n            value = int(matype)\n            if abs(value) > len(AlphaVantage._ALPHA_VANTAGE_MATH_MAP):\n                raise ValueError(\"The value {} is not supported\".format(value))\n        except ValueError:\n            value = AlphaVantage._ALPHA_VANTAGE_MATH_MAP.index(matype)\n        return value",
    "docstring": "Convert to the alpha vantage math type integer. It returns an\n        integer correspondent to the type of math to apply to a function. It\n        raises ValueError if an integer greater than the supported math types\n        is given.\n\n        Keyword Arguments:\n            matype:  The math type of the alpha vantage api. It accepts\n            integers or a string representing the math type.\n\n                * 0 = Simple Moving Average (SMA),\n                * 1 = Exponential Moving Average (EMA),\n                * 2 = Weighted Moving Average (WMA),\n                * 3 = Double Exponential Moving Average (DEMA),\n                * 4 = Triple Exponential Moving Average (TEMA),\n                * 5 = Triangular Moving Average (TRIMA),\n                * 6 = T3 Moving Average,\n                * 7 = Kaufman Adaptive Moving Average (KAMA),\n                * 8 = MESA Adaptive Moving Average (MAMA)"
  },
  {
    "code": "def particles(category=None):\n    filepath = os.path.join(os.path.dirname(__file__), './particles.json')\n    with open(filepath) as f:\n        try:\n            particles = json.load(f)\n        except ValueError as e:\n            log.error('Bad json format in \"{}\"'.format(filepath))\n        else:\n            if category:\n                if category in particles:\n                    return particles[category]\n                else:\n                    log.warn('Category \"{}\" not contained in particle dictionary!'.format(category))\n            return particles",
    "docstring": "Returns a dict containing old greek particles grouped by category."
  },
  {
    "code": "def create_gp(self):\n        nb_bams = len(self.bams)\n        gp_parts = [\n            textwrap.dedent(\n            ),\n            os.linesep.join([self._gp_style_func(i, nb_bams) for i in range(nb_bams)]),\n            textwrap.dedent(\n            ),\n            os.linesep.join(self.gp_plots)\n        ]\n        gp_src = os.linesep.join(gp_parts)\n        with open(self._gp_fn, \"w+\") as f:\n            f.write(gp_src)",
    "docstring": "Create GnuPlot file."
  },
  {
    "code": "def _fail(self, message, text, i):\n        raise ValueError(\"{}:\\n{}\".format(message, text[i : i + 79]))",
    "docstring": "Raise an exception with given message and text at i."
  },
  {
    "code": "def load(cls, fname, args):\n    if args.type == JSON:\n        if fname.endswith('.bz2'):\n            open_ = bz2.open\n        else:\n            open_ = open\n        if args.progress:\n            print('Loading JSON data...')\n        with open_(fname, 'rt') as fp:\n            storage = JsonStorage.load(fp)\n    else:\n        storage = SqliteStorage.load(fname)\n    if args.settings is not None:\n        extend(storage.settings, args.settings)\n    return cls.from_storage(storage)",
    "docstring": "Load a generator.\n\n    Parameters\n    ----------\n    cls : `type`\n        Generator class.\n    fname : `str`\n        Input file path.\n    args : `argparse.Namespace`\n        Command arguments.\n\n    Returns\n    -------\n    `cls`"
  },
  {
    "code": "def get_column_list_prefixed(self):\n        return map(\n            lambda x: \".\".join([self.name, x]),\n            self.columns\n        )",
    "docstring": "Returns a list of columns"
  },
  {
    "code": "def est_covariance_mtx(self, corr=False):\n        cov = self.particle_covariance_mtx(self.particle_weights,\n                                           self.particle_locations)\n        if corr:\n            dstd = np.sqrt(np.diag(cov))\n            cov /= (np.outer(dstd, dstd))\n        return cov",
    "docstring": "Returns the full-rank covariance matrix of the current particle\n        distribution.\n\n        :param bool corr: If `True`, the covariance matrix is normalized\n            by the outer product of the square root diagonal of the covariance matrix,\n            i.e. the correlation matrix is returned instead.\n\n        :rtype: :class:`numpy.ndarray`, shape\n            ``(n_modelparams, n_modelparams)``.\n        :returns: An array containing the estimated covariance matrix."
  },
  {
    "code": "def _check_and_assign_normalization_members(self, normalization_ctor,\n                                              normalization_kwargs):\n    if isinstance(normalization_ctor, six.string_types):\n      normalization_ctor = util.parse_string_to_constructor(normalization_ctor)\n    if normalization_ctor is not None and not callable(normalization_ctor):\n      raise ValueError(\n          \"normalization_ctor must be a callable or a string that specifies \"\n          \"a callable, got {}.\".format(normalization_ctor))\n    self._normalization_ctor = normalization_ctor\n    self._normalization_kwargs = normalization_kwargs",
    "docstring": "Checks that the normalization constructor is callable."
  },
  {
    "code": "def reference_index(self):\n        if self._db_location:\n            ref_indices = glob.glob(os.path.join(self._db_location, \"*\", self._REF_INDEX))\n            if ref_indices:\n                return ref_indices[0]",
    "docstring": "Absolute path to the BWA index for EricScript reference data."
  },
  {
    "code": "def debug_dump(message, file_prefix=\"dump\"):\n    global index\n    index += 1\n    with open(\"%s_%s.dump\" % (file_prefix, index), 'w') as f:\n        f.write(message.SerializeToString())\n        f.close()",
    "docstring": "Utility while developing to dump message data to play with in the\n    interpreter"
  },
  {
    "code": "def _validate_required(self, item, name):\n        if self.required is True and item is None:\n            raise ArgumentError(name, \"This argument is required.\")",
    "docstring": "Validate that the item is present if it's required."
  },
  {
    "code": "def _ifelse(expr, true_expr, false_expr):\n    tps = (SequenceExpr, Scalar)\n    if not isinstance(true_expr, tps):\n        true_expr = Scalar(_value=true_expr)\n    if not isinstance(false_expr, tps):\n        false_expr = Scalar(_value=false_expr)\n    output_type = utils.highest_precedence_data_type(\n            *[true_expr.dtype, false_expr.dtype])\n    is_sequence = isinstance(expr, SequenceExpr) or \\\n                  isinstance(true_expr, SequenceExpr) or \\\n                  isinstance(false_expr, SequenceExpr)\n    if is_sequence:\n        return IfElse(_input=expr, _then=true_expr, _else=false_expr,\n                      _data_type=output_type)\n    else:\n        return IfElse(_input=expr, _then=true_expr, _else=false_expr,\n                      _value_type=output_type)",
    "docstring": "Given a boolean sequence or scalar, if true will return the left, else return the right one.\n\n    :param expr: sequence or scalar\n    :param true_expr:\n    :param false_expr:\n    :return: sequence or scalar\n\n    :Example:\n\n    >>> (df.id == 3).ifelse(df.id, df.fid.astype('int'))\n    >>> df.isMale.ifelse(df.male_count, df.female_count)"
  },
  {
    "code": "def _countWhereGreaterEqualInRows(sparseMatrix, rows, threshold):\n  return sum(sparseMatrix.countWhereGreaterOrEqual(row, row+1,\n                                                   0, sparseMatrix.nCols(),\n                                                   threshold)\n             for row in rows)",
    "docstring": "Like countWhereGreaterOrEqual, but for an arbitrary selection of rows, and\n  without any column filtering."
  },
  {
    "code": "def dot(a, b):\n    if hasattr(a, '__dot__'):\n        return a.__dot__(b)\n    if a is None:\n        return b\n    else:\n        raise ValueError(\n            'Dot is waiting for two TT-vectors or two TT-    matrices')",
    "docstring": "Dot product of two TT-matrices or two TT-vectors"
  },
  {
    "code": "def yesterday(date=None):\n    if not date:\n        return _date - datetime.timedelta(days=1)\n    else:\n        current_date = parse(date)\n        return current_date - datetime.timedelta(days=1)",
    "docstring": "yesterday once more"
  },
  {
    "code": "def _absolute_path(path, relative_to=None):\n    if path and os.path.isabs(path):\n        return path\n    if path and relative_to is not None:\n        _abspath = os.path.join(relative_to, path)\n        if os.path.isfile(_abspath):\n            log.debug(\n                'Relative path \\'%s\\' converted to existing absolute path '\n                '\\'%s\\'', path, _abspath\n            )\n            return _abspath\n    return path",
    "docstring": "Return an absolute path. In case ``relative_to`` is passed and ``path`` is\n    not an absolute path, we try to prepend ``relative_to`` to ``path``and if\n    that path exists, return that one"
  },
  {
    "code": "def get_func_name(func):\n    func_name = getattr(func, '__name__', func.__class__.__name__)\n    module_name = func.__module__\n    if module_name is not None:\n        module_name = func.__module__\n        return '{}.{}'.format(module_name, func_name)\n    return func_name",
    "docstring": "Return a name which includes the module name and function name."
  },
  {
    "code": "def set_sleep_on_power_button(enabled):\n    state = salt.utils.mac_utils.validate_enabled(enabled)\n    cmd = 'systemsetup -setallowpowerbuttontosleepcomputer {0}'.format(state)\n    salt.utils.mac_utils.execute_return_success(cmd)\n    return salt.utils.mac_utils.confirm_updated(\n        state,\n        get_sleep_on_power_button,\n    )",
    "docstring": "Set whether or not the power button can sleep the computer.\n\n    :param bool enabled: True to enable, False to disable. \"On\" and \"Off\" are\n        also acceptable values. Additionally you can pass 1 and 0 to represent\n        True and False respectively\n\n    :return: True if successful, False if not\n    :rtype: bool\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' power.set_sleep_on_power_button True"
  },
  {
    "code": "def run(self, messages):\n        statistics = {}\n        statistics['time'] = str(datetime.now())\n        statistics['time-utc'] = str(datetime.utcnow())\n        statistics['unlock'] = self.args.unlock\n        if self.args.question:\n            statistics['question'] = [t.name for t in self.assignment.specified_tests]\n            statistics['requested-questions'] = self.args.question\n            if self.args.suite:\n                statistics['requested-suite'] = self.args.suite\n            if self.args.case:\n                statistics['requested-case'] = self.args.case\n        messages['analytics'] = statistics\n        self.log_run(messages)",
    "docstring": "Returns some analytics about this autograder run."
  },
  {
    "code": "def setup(self):\n        super().setup()\n        self._start_time = self.clock.time\n        self.initialize_simulants()",
    "docstring": "Setup the simulation and initialize its population."
  },
  {
    "code": "def write_pid(self, pid=None):\n    pid = pid or os.getpid()\n    self.write_metadata_by_name(self._name, 'pid', str(pid))",
    "docstring": "Write the current processes PID to the pidfile location"
  },
  {
    "code": "def start(track_file,\n          twitter_api_key,\n          twitter_api_secret,\n          twitter_access_token,\n          twitter_access_token_secret,\n          poll_interval=15,\n          unfiltered=False,\n          languages=None,\n          debug=False,\n          outfile=None):\n    listener = construct_listener(outfile)\n    checker = BasicFileTermChecker(track_file, listener)\n    auth = get_tweepy_auth(twitter_api_key,\n                           twitter_api_secret,\n                           twitter_access_token,\n                           twitter_access_token_secret)\n    stream = DynamicTwitterStream(auth, listener, checker, unfiltered=unfiltered, languages=languages)\n    set_terminate_listeners(stream)\n    if debug:\n        set_debug_listener(stream)\n    begin_stream_loop(stream, poll_interval)",
    "docstring": "Start the stream."
  },
  {
    "code": "def setOverlayTransformTrackedDeviceComponent(self, ulOverlayHandle, unDeviceIndex, pchComponentName):\n        fn = self.function_table.setOverlayTransformTrackedDeviceComponent\n        result = fn(ulOverlayHandle, unDeviceIndex, pchComponentName)\n        return result",
    "docstring": "Sets the transform to draw the overlay on a rendermodel component mesh instead of a quad. This will only draw when the system is\n        drawing the device. Overlays with this transform type cannot receive mouse events."
  },
  {
    "code": "def _process_deprecated(attrib, deprecated_attrib, kwargs):\n        if deprecated_attrib not in DEPRECATIONS:\n            raise ValueError('{0} not included in deprecations list'\n                             .format(deprecated_attrib))\n        if deprecated_attrib in kwargs:\n            warnings.warn(\"'{0}' is DEPRECATED use '{1}' instead\"\n                          .format(deprecated_attrib,\n                                  DEPRECATIONS[deprecated_attrib]),\n                          DeprecationWarning)\n            if attrib:\n                raise ValueError(\"You can't use both '{0}' and '{1}'. \"\n                                 \"Please only use one of them\"\n                                 .format(deprecated_attrib,\n                                         DEPRECATIONS[deprecated_attrib]))\n            else:\n                return kwargs.pop(deprecated_attrib)\n        return attrib",
    "docstring": "Processes optional deprecate arguments"
  },
  {
    "code": "def Map(self, function):\n        new_table = self.__class__()\n        new_table._table = [self.header]\n        for row in self:\n            filtered_row = function(row)\n            if filtered_row:\n                new_table.Append(filtered_row)\n        return new_table",
    "docstring": "Applies the function to every row in the table.\n\n    Args:\n      function: A function applied to each row.\n\n    Returns:\n      A new TextTable()\n\n    Raises:\n      TableError: When transform is not invalid row entry. The transform\n                  must be compatible with Append()."
  },
  {
    "code": "def details_for_given_date_in_gradebook_history_for_this_course(self, date, course_id):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"course_id\"] = course_id\r\n        path[\"date\"] = date\r\n        self.logger.debug(\"GET /api/v1/courses/{course_id}/gradebook_history/{date} with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"GET\", \"/api/v1/courses/{course_id}/gradebook_history/{date}\".format(**path), data=data, params=params, all_pages=True)",
    "docstring": "Details for a given date in gradebook history for this course.\r\n\r\n        Returns the graders who worked on this day, along with the assignments they worked on.\r\n        More details can be obtained by selecting a grader and assignment and calling the\r\n        'submissions' api endpoint for a given date."
  },
  {
    "code": "def _db_remove_prefix(self, spec, recursive = False):\n        if recursive:\n            prefix = spec['prefix']\n            del spec['prefix']\n            where, params = self._expand_prefix_spec(spec)\n            spec['prefix'] = prefix\n            params['prefix'] = prefix\n            where = 'prefix <<= %(prefix)s AND ' + where\n        else:\n            where, params = self._expand_prefix_spec(spec)\n        sql = \"DELETE FROM ip_net_plan AS p WHERE %s\" % where\n        self._execute(sql, params)",
    "docstring": "Do the underlying database operations to delete a prefix"
  },
  {
    "code": "def _store_object(self, obj_name, content, etag=None, chunked=False,\n            chunk_size=None, headers=None):\n        head_etag = headers.pop(\"ETag\", \"\")\n        if chunked:\n            headers.pop(\"Content-Length\", \"\")\n            headers[\"Transfer-Encoding\"] = \"chunked\"\n        elif etag is None and content is not None:\n            etag = utils.get_checksum(content)\n        if etag:\n            headers[\"ETag\"] = etag\n        if not headers.get(\"Content-Type\"):\n            headers[\"Content-Type\"] = None\n        uri = \"/%s/%s\" % (self.uri_base, obj_name)\n        resp, resp_body = self.api.method_put(uri, data=content,\n                headers=headers)",
    "docstring": "Handles the low-level creation of a storage object and the uploading of\n        the contents of that object."
  },
  {
    "code": "def remove_from_parent(self):\n        if self.parent:\n            self.parent._children.remove(self)\n            self.parent._invalidate_time_caches()\n            self.parent = None",
    "docstring": "Removes this frame from its parent, and nulls the parent link"
  },
  {
    "code": "def retrieve_order(self, order_id):\n        response = self.request(E.retrieveOrderSslCertRequest(\n            E.id(order_id)\n        ))\n        return response.as_model(SSLOrder)",
    "docstring": "Retrieve details on a single order."
  },
  {
    "code": "def fap_davies(Z, fmax, t, y, dy, normalization='standard'):\n    N = len(t)\n    fap_s = fap_single(Z, N, normalization=normalization)\n    tau = tau_davies(Z, fmax, t, y, dy, normalization=normalization)\n    return fap_s + tau",
    "docstring": "Davies upper-bound to the false alarm probability\n\n    (Eqn 5 of Baluev 2008)"
  },
  {
    "code": "def _error_dm(self, m, dm, s):\n        pred = self.fmodel.predict_given_context(np.hstack((m, dm)), s, range(len(s)))\n        err_v  = pred - self.goal\n        error = sum(e*e for e in err_v)\n        return error",
    "docstring": "Error function.\n        Once self.goal has been defined, compute the error\n        of input using the generalized forward model."
  },
  {
    "code": "def issueCommand(self, command, *args):\n        result = Deferred()\n        self._dq.append(result)\n        self.sendLine(b\" \".join([command] + list(args)))\n        return result",
    "docstring": "Issue the given Assuan command and return a Deferred that will fire\n        with the response."
  },
  {
    "code": "def get_fun_prop(f, k):\n    if not has_fun_prop(f, k):\n        raise InternalError(\"Function %s has no property %s\" % (str(f), k))\n    return getattr(f, _FUN_PROPS)[k]",
    "docstring": "Get the value of property `k` from function `f`.\n\n    We define properties as annotations added to a function throughout\n    the process of defining a function for verification, e.g. the\n    argument types.  If `f` does not have a property named `k`, this\n    throws an error.  If `f` has the property named `k`, it returns\n    the value of it.\n\n    Users should never access this function directly."
  },
  {
    "code": "def create_request(self, reset_gpd_iterator=False):\n        if reset_gpd_iterator:\n            self.gpd_iterator = None\n        gpd_service = GeopediaImageService()\n        self.download_list = gpd_service.get_request(self)\n        self.gpd_iterator = gpd_service.get_gpd_iterator()",
    "docstring": "Set a list of download requests\n\n        Set a list of DownloadRequests for all images that are under the\n        given property of the Geopedia's Vector layer.\n\n        :param reset_gpd_iterator: When re-running the method this flag is used to reset/keep existing ``gpd_iterator``\n            (i.e. instance of ``GeopediaFeatureIterator`` class). If the iterator is not reset you don't have to\n            repeat a service call but tiles and dates will stay the same.\n        :type reset_gpd_iterator: bool"
  },
  {
    "code": "def _boto_conn_kwargs(self):\n        kwargs = {'region_name': self.region}\n        if self.account_id is not None:\n            logger.debug(\"Connecting for account %s role '%s' with STS \"\n                         \"(region: %s)\", self.account_id, self.account_role,\n                         self.region)\n            credentials = self._get_sts_token()\n            kwargs['aws_access_key_id'] = credentials.access_key\n            kwargs['aws_secret_access_key'] = credentials.secret_key\n            kwargs['aws_session_token'] = credentials.session_token\n        elif self.profile_name is not None:\n            logger.debug(\"Using credentials profile: %s\", self.profile_name)\n            session = boto3.Session(profile_name=self.profile_name)\n            credentials = session._session.get_credentials()\n            kwargs['aws_access_key_id'] = credentials.access_key\n            kwargs['aws_secret_access_key'] = credentials.secret_key\n            kwargs['aws_session_token'] = credentials.token\n        else:\n            logger.debug(\"Connecting to region %s\", self.region)\n        return kwargs",
    "docstring": "Generate keyword arguments for boto3 connection functions.\n\n        If ``self.account_id`` is defined, this will call\n        :py:meth:`~._get_sts_token` to get STS token credentials using\n        `boto3.STS.Client.assume_role <https://boto3.readthedocs.org/en/\n        latest/reference/services/sts.html#STS.Client.assume_role>`_ and include\n        those credentials in the return value.\n\n        If ``self.profile_name`` is defined, this will call `boto3.Session()\n        <http://boto3.readthedocs.io/en/latest/reference/core/session.html>`\n        with that profile and include those credentials in the return value.\n\n        :return: keyword arguments for boto3 connection functions\n        :rtype: dict"
  },
  {
    "code": "def _parse_output_for_errors(data, command, **kwargs):\n    if re.search('% Invalid', data):\n        raise CommandExecutionError({\n            'rejected_input': command,\n            'message': 'CLI excution error',\n            'code': '400',\n            'cli_error': data.lstrip(),\n        })\n    if kwargs.get('error_pattern') is not None:\n        for re_line in kwargs.get('error_pattern'):\n            if re.search(re_line, data):\n                raise CommandExecutionError({\n                    'rejected_input': command,\n                    'message': 'CLI excution error',\n                    'code': '400',\n                    'cli_error': data.lstrip(),\n                })",
    "docstring": "Helper method to parse command output for error information"
  },
  {
    "code": "def tx2genefile(gtf, out_file=None):\n    installed_tx2gene = os.path.join(os.path.dirname(gtf), \"tx2gene.csv\")\n    if file_exists(installed_tx2gene):\n        return installed_tx2gene\n    if file_exists(out_file):\n        return out_file\n    with file_transaction(out_file) as tx_out_file:\n        with open(tx_out_file, \"w\") as out_handle:\n            for k, v in transcript_to_gene(gtf).items():\n                out_handle.write(\",\".join([k, v]) + \"\\n\")\n    return out_file",
    "docstring": "write out a file of transcript->gene mappings.\n    use the installed tx2gene.csv if it exists, else write a new one out"
  },
  {
    "code": "def one_of(*generators):\n    class OneOfGenerators(ArbitraryInterface):\n        @classmethod\n        def arbitrary(cls):\n            return arbitrary(random.choice(generators))\n    OneOfGenerators.__name__ = ''.join([\n        'one_of(', ', '.join(generator.__name__ for generator in generators),\n        ')'\n    ])\n    return OneOfGenerators",
    "docstring": "Generates an arbitrary value of one of the specified generators.\n    This is a class factory, it makes a class which is a closure around the\n    specified generators."
  },
  {
    "code": "def from_str(cls, version_str: str):\n        o = cls()\n        o.version = version_str\n        return o",
    "docstring": "Alternate constructor that accepts a string SemVer."
  },
  {
    "code": "def set(self, folder: str, subscribed: bool) -> None:\n        if subscribed:\n            self.add(folder)\n        else:\n            self.remove(folder)",
    "docstring": "Set the subscribed status of a folder."
  },
  {
    "code": "def reaction_formula(reaction, compound_formula):\n    def multiply_formula(compound_list):\n        for compound, count in compound_list:\n            yield count * compound_formula[compound.name]\n    for compound, _ in reaction.compounds:\n        if compound.name not in compound_formula:\n            return None\n    else:\n        left_form = reduce(\n            operator.or_, multiply_formula(reaction.left), Formula())\n        right_form = reduce(\n            operator.or_, multiply_formula(reaction.right), Formula())\n    return left_form, right_form",
    "docstring": "Calculate formula compositions for both sides of the specified reaction.\n\n    If the compounds in the reaction all have formula, then calculate and\n    return the chemical compositions for both sides, otherwise return `None`.\n\n    Args:\n        reaction: :class:`psamm.reaction.Reaction`.\n        compound_formula: a map from compound id to formula."
  },
  {
    "code": "def upload_marcxml(self, marcxml, mode):\n        if mode not in [\"-i\", \"-r\", \"-c\", \"-a\", \"-ir\"]:\n            raise NameError(\"Incorrect mode \" + str(mode))\n        return requests.post(self.server_url + \"/batchuploader/robotupload\",\n                             data={'file': marcxml, 'mode': mode},\n                             headers={'User-Agent': CFG_USER_AGENT})",
    "docstring": "Upload a record to the server.\n\n        :param marcxml: the XML to upload.\n        :param mode: the mode to use for the upload.\n            - \"-i\" insert new records\n            - \"-r\" replace existing records\n            - \"-c\" correct fields of records\n            - \"-a\" append fields to records\n            - \"-ir\" insert record or replace if it exists"
  },
  {
    "code": "def message(self, message, source, point, ln):\n        if message is None:\n            message = \"parsing failed\"\n        if ln is not None:\n            message += \" (line \" + str(ln) + \")\"\n        if source:\n            if point is None:\n                message += \"\\n\" + \" \" * taberrfmt + clean(source)\n            else:\n                part = clean(source.splitlines()[lineno(point, source) - 1], False).lstrip()\n                point -= len(source) - len(part)\n                part = part.rstrip()\n                message += \"\\n\" + \" \" * taberrfmt + part\n                if point > 0:\n                    if point >= len(part):\n                        point = len(part) - 1\n                    message += \"\\n\" + \" \" * (taberrfmt + point) + \"^\"\n        return message",
    "docstring": "Creates a SyntaxError-like message."
  },
  {
    "code": "def freeze(self, freeze: bool = True):\n        for topic in self._topics.values():\n            topic.freeze()\n        self._frozen = freeze",
    "docstring": "Freezing the hub means that each topic has to be assigned and no\n        new topics can be created after this point."
  },
  {
    "code": "def load_credential_file(self, path):\n        c_data = StringIO.StringIO()\n        c_data.write(\"[Credentials]\\n\")\n        for line in open(path, \"r\").readlines():\n            c_data.write(line.replace(\"AWSAccessKeyId\", \"aws_access_key_id\").replace(\"AWSSecretKey\", \"aws_secret_access_key\"))\n        c_data.seek(0)\n        self.readfp(c_data)",
    "docstring": "Load a credential file as is setup like the Java utilities"
  },
  {
    "code": "def RemoveObject(self, identifier):\n    if identifier not in self._values:\n      raise KeyError('Missing cached object for identifier: {0:s}'.format(\n          identifier))\n    del self._values[identifier]",
    "docstring": "Removes a cached object based on the identifier.\n\n    This method ignores the cache value reference count.\n\n    Args:\n      identifier (str): VFS object identifier.\n\n    Raises:\n      KeyError: if the VFS object is not found in the cache."
  },
  {
    "code": "def get_custom_query(self):\n        query = {}\n        q = req.get_query()\n        if q:\n            query[\"SearchableText\"] = q\n        path = req.get_path()\n        if path:\n            query[\"path\"] = {'query': path, 'depth': req.get_depth()}\n        recent_created = req.get_recent_created()\n        if recent_created:\n            date = api.calculate_delta_date(recent_created)\n            query[\"created\"] = {'query': date, 'range': 'min'}\n        recent_modified = req.get_recent_modified()\n        if recent_modified:\n            date = api.calculate_delta_date(recent_modified)\n            query[\"modified\"] = {'query': date, 'range': 'min'}\n        return query",
    "docstring": "Extracts custom query keys from the index.\n\n        Parameters which get extracted from the request:\n\n            `q`: Passes the value to the `SearchableText`\n            `path`: Creates a path query\n            `recent_created`: Creates a date query\n            `recent_modified`: Creates a date query\n\n        :param catalog: The catalog to build the query for\n        :type catalog: ZCatalog\n        :returns: Catalog query\n        :rtype: dict"
  },
  {
    "code": "def rmdir(path, dir_fd=None):\n    system = get_instance(path)\n    system.remove(system.ensure_dir_path(path))",
    "docstring": "Remove a directory.\n\n    Equivalent to \"os.rmdir\".\n\n    Args:\n        path (path-like object): Path or URL.\n        dir_fd: directory descriptors;\n            see the os.rmdir() description for how it is interpreted.\n            Not supported on cloud storage objects."
  },
  {
    "code": "def get_dvcs_info():\n    cmd = \"git rev-list --count HEAD\"\n    commit_count = str(\n        int(subprocess.check_output(shlex.split(cmd)).decode(\"utf8\").strip())\n    )\n    cmd = \"git rev-parse HEAD\"\n    commit = str(subprocess.check_output(shlex.split(cmd)).decode(\"utf8\").strip())\n    return {Constants.COMMIT_FIELD: commit, Constants.COMMIT_COUNT_FIELD: commit_count}",
    "docstring": "Gets current repository info from git"
  },
  {
    "code": "def generate_metadata_entry(self, entry_point, toolchain, spec):\n        export_target = spec['export_target']\n        toolchain_bases = trace_toolchain(toolchain)\n        toolchain_bin_path = spec.get(TOOLCHAIN_BIN_PATH)\n        toolchain_bin = ([\n            basename(toolchain_bin_path),\n            get_bin_version_str(toolchain_bin_path),\n        ] if toolchain_bin_path else [])\n        return {basename(export_target): {\n            'toolchain_bases': toolchain_bases,\n            'toolchain_bin': toolchain_bin,\n            'builder': '%s:%s' % (\n                entry_point.module_name, '.'.join(entry_point.attrs)),\n        }}",
    "docstring": "After the toolchain and spec have been executed, this may be\n        called to generate the artifact export entry for persistence\n        into the metadata file."
  },
  {
    "code": "def child(self, fragment):\n        return os.path.join(self.path, FS(fragment).path)",
    "docstring": "Returns a path of a child item represented by `fragment`."
  },
  {
    "code": "def build_self_reference(filename, clean_wcs=False):\n    if 'sipwcs' in filename:\n        sciname = 'sipwcs'\n    else:\n        sciname = 'sci'\n    wcslin = build_reference_wcs([filename], sciname=sciname)\n    if clean_wcs:\n        wcsbase = wcslin.wcs\n        customwcs = build_hstwcs(wcsbase.crval[0], wcsbase.crval[1], wcsbase.crpix[0],\n                                 wcsbase.crpix[1], wcslin._naxis1, wcslin._naxis2,\n                                 wcslin.pscale, wcslin.orientat)\n    else:\n        customwcs = wcslin\n    return customwcs",
    "docstring": "This function creates a reference, undistorted WCS that can be used to\n    apply a correction to the WCS of the input file.\n\n    Parameters\n    ----------\n    filename : str\n        Filename of image which will be corrected, and which will form the basis\n        of the undistorted WCS.\n\n    clean_wcs : bool\n        Specify whether or not to return the WCS object without any distortion\n        information, or any history of the original input image.  This converts\n        the output from `utils.output_wcs()` into a pristine `~stwcs.wcsutils.HSTWCS` object.\n\n    Returns\n    -------\n    customwcs : `stwcs.wcsutils.HSTWCS`\n        HSTWCS object which contains the undistorted WCS representing the entire\n        field-of-view for the input image.\n\n    Examples\n    --------\n    This function can be used with the following syntax to apply a shift/rot/scale\n    change to the same image:\n\n    >>> import buildref\n    >>> from drizzlepac import updatehdr\n    >>> filename = \"jce501erq_flc.fits\"\n    >>> wcslin = buildref.build_self_reference(filename)\n    >>> updatehdr.updatewcs_with_shift(filename, wcslin, xsh=49.5694,\n    ... ysh=19.2203, rot = 359.998, scale = 0.9999964)"
  },
  {
    "code": "def _setup_core_modules(self):\n        self.ir_emulator = None\n        self.smt_solver = None\n        self.smt_translator = None\n        if self.arch_info:\n            self.ir_emulator = ReilEmulator(self.arch_info)\n            self.smt_solver = None\n            if SMT_SOLVER not in (\"Z3\", \"CVC4\"):\n                raise Exception(\"{} SMT solver not supported.\".format(SMT_SOLVER))\n            try:\n                if SMT_SOLVER == \"Z3\":\n                    self.smt_solver = Z3Solver()\n                elif SMT_SOLVER == \"CVC4\":\n                    self.smt_solver = CVC4Solver()\n            except SmtSolverNotFound:\n                logger.warn(\"{} Solver is not installed. Run 'barf-install-solvers.sh' to install it.\".format(SMT_SOLVER))\n            self.smt_translator = None\n            if self.smt_solver:\n                self.smt_translator = SmtTranslator(self.smt_solver, self.arch_info.address_size)\n                self.smt_translator.set_arch_alias_mapper(self.arch_info.alias_mapper)\n                self.smt_translator.set_arch_registers_size(self.arch_info.registers_size)",
    "docstring": "Set up core modules."
  },
  {
    "code": "def create_prefetch(self, addresses):\n        with self._lock:\n            for add in addresses:\n                self._state[add] = _ContextFuture(address=add,\n                                                  wait_for_tree=True)",
    "docstring": "Create futures needed before starting the process of reading the\n        address's value from the merkle tree.\n\n        Args:\n            addresses (list of str): addresses in the txn's inputs that\n                aren't in any base context (or any in the chain)."
  },
  {
    "code": "def is_user_in_group(self, user, group):\n        search_url = \"%s/%s/%s/%s/%s\" % (self.url, \"group\", group,\n                                         \"user\", user)\n        response = self.jss.get(search_url)\n        length = len(response)\n        result = False\n        if length == 1:\n            pass\n        elif length == 2:\n            if response.findtext(\"ldap_user/username\") == user:\n                if response.findtext(\"ldap_user/is_member\") == \"Yes\":\n                    result = True\n        elif len(response) >= 2:\n            raise JSSGetError(\"Unexpected response.\")\n        return result",
    "docstring": "Test for whether a user is in a group.\n\n        There is also the ability in the API to test for whether\n        multiple users are members of an LDAP group, but you should just\n        call is_user_in_group over an enumerated list of users.\n\n        Args:\n            user: String username.\n            group: String group name.\n\n        Returns bool."
  },
  {
    "code": "def add_perm(self, subj_str, perm_str):\n        self._assert_valid_permission(perm_str)\n        self._perm_dict.setdefault(perm_str, set()).add(subj_str)",
    "docstring": "Add a permission for a subject.\n\n        Args:\n          subj_str : str\n            Subject for which to add permission(s)\n\n          perm_str : str\n            Permission to add. Implicitly adds all lower permissions. E.g., ``write``\n            will also add ``read``."
  },
  {
    "code": "def _process_args_as_rows_or_columns(self, arg, unpack=False):\n        flags = set()\n        if isinstance(arg, (tuple, list, numpy.ndarray)):\n            if isstring(arg[0]):\n                result = arg\n            else:\n                result = arg\n                flags.add('isrows')\n        elif isstring(arg):\n            result = arg\n        elif isinstance(arg, slice):\n            if unpack:\n                flags.add('isrows')\n                result = self._slice2rows(arg.start, arg.stop, arg.step)\n            else:\n                flags.add('isrows')\n                flags.add('isslice')\n                result = self._process_slice(arg)\n        else:\n            result = arg\n            flags.add('isrows')\n            if numpy.ndim(arg) == 0:\n                flags.add('isscalar')\n        return result, flags",
    "docstring": "We must be able to interpret the args as as either a column name or\n        row number, or sequences thereof.  Numpy arrays and slices are also\n        fine.\n\n        Examples:\n            'field'\n            35\n            [35,55,86]\n            ['f1',f2',...]\n        Can also be tuples or arrays."
  },
  {
    "code": "def _sort_column(self, column, reverse):\n        if tk.DISABLED in self.state():\n            return\n        l = [(self.set(child, column), child) for child in self.get_children('')]\n        l.sort(reverse=reverse, key=lambda x: self._column_types[column](x[0]))\n        for index, (val, child) in enumerate(l):\n            self.move(child, \"\", index)\n        self.heading(column, command=lambda: self._sort_column(column, not reverse))",
    "docstring": "Sort a column by its values"
  },
  {
    "code": "def num(string):\n    if not isinstance(string, type('')):\n        raise ValueError(type(''))\n    try:\n        string = re.sub('[^a-zA-Z0-9\\.\\-]', '', string)\n        number = re.findall(r\"[-+]?\\d*\\.\\d+|[-+]?\\d+\", string)\n        return float(number[0])\n    except Exception as e:\n        logger = logging.getLogger('tradingAPI.utils.num')\n        logger.debug(\"number not found in %s\" % string)\n        logger.debug(e)\n        return None",
    "docstring": "convert a string to float"
  },
  {
    "code": "def reversed_blocks(handle, blocksize=4096):\n    handle.seek(0, os.SEEK_END)\n    here = handle.tell()\n    while 0 < here:\n        delta = min(blocksize, here)\n        here -= delta\n        handle.seek(here, os.SEEK_SET)\n        yield handle.read(delta)",
    "docstring": "Generate blocks of file's contents in reverse order."
  },
  {
    "code": "def handle_pubcomp(self):\n        self.logger.info(\"PUBCOMP received\")\n        ret, mid = self.in_packet.read_uint16()\n        if ret != NC.ERR_SUCCESS:\n            return ret\n        evt = event.EventPubcomp(mid)\n        self.push_event(evt)\n        return NC.ERR_SUCCESS",
    "docstring": "Handle incoming PUBCOMP packet."
  },
  {
    "code": "def auto(self, enabled=True, **kwargs):\n        self.namespace = self.get_namespace()\n        self.notebook_name = \"{notebook}\"\n        self._timestamp = tuple(time.localtime())\n        kernel = r'var kernel = IPython.notebook.kernel; '\n        nbname = r\"var nbname = IPython.notebook.get_notebook_name(); \"\n        nbcmd = (r\"var name_cmd = '%s.notebook_name = \\\"' + nbname + '\\\"'; \" % self.namespace)\n        cmd = (kernel + nbname + nbcmd + \"kernel.execute(name_cmd); \")\n        display(Javascript(cmd))\n        time.sleep(0.5)\n        self._auto=enabled\n        self.param.set_param(**kwargs)\n        tstamp = time.strftime(\" [%Y-%m-%d %H:%M:%S]\", self._timestamp)\n        print(\"Automatic capture is now %s.%s\"\n              % ('enabled' if enabled else 'disabled',\n                 tstamp if enabled else ''))",
    "docstring": "Method to enable or disable automatic capture, allowing you to\n        simultaneously set the instance parameters."
  },
  {
    "code": "def _copytoscratch(self, maps):\n        try:\n            for p in self.inputs:\n                self._scratch[p][:] = maps[p]\n        except ValueError:\n            invals = maps[list(self.inputs)[0]]\n            if isinstance(invals, numpy.ndarray):\n                shape = invals.shape\n            else:\n                shape = len(invals)\n            self._createscratch(shape)\n            for p in self.inputs:\n                self._scratch[p][:] = maps[p]",
    "docstring": "Copies the data in maps to the scratch space.\n\n        If the maps contain arrays that are not the same shape as the scratch\n        space, a new scratch space will be created."
  },
  {
    "code": "def create_adjusted_model_for_percentages(model_src, model_use):\n    shutil.copyfile(model_src, model_use)\n    with open(model_src) as f:\n        content = f.read()\n    content = content.replace(\"logreg\", \"sigmoid\")\n    with open(model_use, \"w\") as f:\n        f.write(content)",
    "docstring": "Replace logreg layer by sigmoid to get probabilities."
  },
  {
    "code": "def setdefault(msg_or_dict, key, value):\n    if not get(msg_or_dict, key, default=None):\n        set(msg_or_dict, key, value)",
    "docstring": "Set the key on a protobuf Message or dictionary to a given value if the\n    current value is falsy.\n\n    Because protobuf Messages do not distinguish between unset values and\n    falsy ones particularly well (by design), this method treats any falsy\n    value (e.g. 0, empty list) as a target to be overwritten, on both Messages\n    and dictionaries.\n\n    Args:\n        msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the\n            object.\n        key (str): The key on the object in question.\n        value (Any): The value to set.\n\n    Raises:\n        TypeError: If ``msg_or_dict`` is not a Message or dictionary."
  },
  {
    "code": "def serialize(self, m):\n        from pymacaroons import macaroon\n        if m.version == macaroon.MACAROON_V1:\n            return self._serialize_v1(m)\n        return self._serialize_v2(m)",
    "docstring": "Serialize the macaroon in JSON format indicated by the version field.\n\n        @param macaroon the macaroon to serialize.\n        @return JSON macaroon."
  },
  {
    "code": "def add_col_features(self, col=None, degree=None):\n        if not col and not degree:\n            return\n        else:\n            if isinstance(col, list) and isinstance(degree, list):\n                if len(col) != len(degree):\n                    print('col len: ', len(col))\n                    print('degree len: ', len(degree))\n                    raise ValueError('col and degree should have equal length.')\n                else:\n                    if self.preprocessed_data.empty:\n                        data = self.original_data\n                    else:\n                        data = self.preprocessed_data\n                    for i in range(len(col)):\n                        data.loc[:,col[i]+str(degree[i])] = pow(data.loc[:,col[i]],degree[i]) / pow(10,degree[i]-1)\n                    self.preprocessed_data = data\n            else:\n                raise TypeError('col and degree should be lists.')",
    "docstring": "Exponentiate columns of dataframe.\n\n        Basically this function squares/cubes a column. \n        e.g. df[col^2] = pow(df[col], degree) where degree=2.\n\n        Parameters\n        ----------\n        col     : list(str)\n            Column to exponentiate.\n        degree  : list(str)\n            Exponentiation degree."
  },
  {
    "code": "def as_repository(resource):\n    reg = get_current_registry()\n    if IInterface in provided_by(resource):\n        resource = reg.getUtility(resource, name='collection-class')\n    return reg.getAdapter(resource, IRepository)",
    "docstring": "Adapts the given registered resource to its configured repository.\n\n    :return: object implementing\n      :class:`everest.repositories.interfaces.IRepository`."
  },
  {
    "code": "def addfield(self, name, type, width=10):\n        fieldDefn = ogr.FieldDefn(name, type)\n        if type == ogr.OFTString:\n            fieldDefn.SetWidth(width)\n        self.layer.CreateField(fieldDefn)",
    "docstring": "add a field to the vector layer\n\n        Parameters\n        ----------\n        name: str\n            the field name\n        type: int\n            the OGR Field Type (OFT), e.g. ogr.OFTString.\n            See `Module ogr <https://gdal.org/python/osgeo.ogr-module.html>`_.\n        width: int\n            the width of the new field (only for ogr.OFTString fields)\n\n        Returns\n        -------"
  },
  {
    "code": "def get_lxc_version():\n    runner = functools.partial(\n        subprocess.check_output,\n        stderr=subprocess.STDOUT,\n        universal_newlines=True,\n    )\n    try:\n        result = runner(['lxc-version']).rstrip()\n        return parse_version(result.replace(\"lxc version: \", \"\"))\n    except (OSError, subprocess.CalledProcessError):\n        pass\n    return parse_version(runner(['lxc-start', '--version']).rstrip())",
    "docstring": "Asks the current host what version of LXC it has.  Returns it as a\n    string. If LXC is not installed, raises subprocess.CalledProcessError"
  },
  {
    "code": "def processGif(searchStr):\n    searchStr.replace('| ', ' ')\n    searchStr.replace('|', ' ')\n    searchStr.replace(', ', ' ')\n    searchStr.replace(',', ' ')\n    searchStr.rstrip()\n    searchStr = searchStr.strip('./?\\'!,')\n    searchStr = searchStr.replace(' ', '+')\n    if searchStr is None or searchStr == '':\n        print(\"No search parameters specified!\")\n        return no_search_params\n    api_url = 'http://api.giphy.com/v1/gifs/search'\n    api_key = 'dc6zaTOxFJmzC'\n    payload = {\n        'q': searchStr,\n        'limit': 1,\n        'api_key': api_key,\n    }\n    r = requests.get(api_url, params=payload)\n    parsed_json = json.loads(r.text)\n    if len(parsed_json['data']) == 0:\n        print(\"Couldn't find suitable match for gif! :(\")\n        return -1\n    else:\n        imgURL = parsed_json['data'][0]['images']['fixed_height']['url']\n        return imgURL",
    "docstring": "This function returns the url of the gif searched for\n    with the given search parameters using the Giphy API.\n    Thanks!\n\n    Fails gracefully when it can't find a gif by returning an \n    appropriate image url with the failure message on it."
  },
  {
    "code": "def _decode_region(decoder, region, corrections, shrink):\n    with _decoded_matrix_region(decoder, region, corrections) as msg:\n        if msg:\n            p00 = DmtxVector2()\n            p11 = DmtxVector2(1.0, 1.0)\n            dmtxMatrix3VMultiplyBy(\n                p00,\n                region.contents.fit2raw\n            )\n            dmtxMatrix3VMultiplyBy(p11, region.contents.fit2raw)\n            x0 = int((shrink * p00.X) + 0.5)\n            y0 = int((shrink * p00.Y) + 0.5)\n            x1 = int((shrink * p11.X) + 0.5)\n            y1 = int((shrink * p11.Y) + 0.5)\n            return Decoded(\n                string_at(msg.contents.output),\n                Rect(x0, y0, x1 - x0, y1 - y0)\n            )\n        else:\n            return None",
    "docstring": "Decodes and returns the value in a region.\n\n    Args:\n        region (DmtxRegion):\n\n    Yields:\n        Decoded or None: The decoded value."
  },
  {
    "code": "def send(self, event):\n        data = b\"\"\n        if isinstance(event, Request):\n            data += self._initiate_connection(event)\n        elif isinstance(event, AcceptConnection):\n            data += self._accept(event)\n        elif isinstance(event, RejectConnection):\n            data += self._reject(event)\n        elif isinstance(event, RejectData):\n            data += self._send_reject_data(event)\n        else:\n            raise LocalProtocolError(\n                \"Event {} cannot be sent during the handshake\".format(event)\n            )\n        return data",
    "docstring": "Send an event to the remote.\n\n        This will return the bytes to send based on the event or raise\n        a LocalProtocolError if the event is not valid given the\n        state."
  },
  {
    "code": "def spawn(func, kwargs):\n    t = threading.Thread(target=func, kwargs=kwargs)\n    t.start()\n    yield\n    t.join()",
    "docstring": "Spawn a thread, and join it after the context is over."
  },
  {
    "code": "def setCurveModel(self, model):\n        self.stimModel = model\n        self.ui.curveWidget.setModel(model)",
    "docstring": "Sets the stimulus model for the calibration curve test\n\n        :param model: Stimulus model that has a tone curve configured\n        :type model: :class:`StimulusModel <sparkle.stim.stimulus_model.StimulusModel>`"
  },
  {
    "code": "def _nested_unary_mul(nested_a, p):\n  def mul_with_broadcast(tensor):\n    ndims = tensor.shape.ndims\n    if ndims != 2:\n      p_reshaped = tf.reshape(p, [-1] + [1] * (ndims - 1))\n      return p_reshaped * tensor\n    else:\n      return p * tensor\n  return nest.map(mul_with_broadcast, nested_a)",
    "docstring": "Multiply `Tensors` in arbitrarily nested `Tensor` `nested_a` with `p`."
  },
  {
    "code": "def dominant_flat_five(note):\n    res = dominant_seventh(note)\n    res[2] = notes.diminish(res[2])\n    return res",
    "docstring": "Build a dominant flat five chord on note.\n\n    Example:\n    >>> dominant_flat_five('C')\n    ['C', 'E', 'Gb', 'Bb']"
  },
  {
    "code": "def presigned_get_object(self, bucket_name, object_name,\n                             expires=timedelta(days=7),\n                             response_headers=None,\n                             request_date=None):\n        return self.presigned_url('GET',\n                                  bucket_name,\n                                  object_name,\n                                  expires,\n                                  response_headers=response_headers,\n                                  request_date=request_date)",
    "docstring": "Presigns a get object request and provides a url\n\n        Example:\n\n            from datetime import timedelta\n\n            presignedURL = presigned_get_object('bucket_name',\n                                                'object_name',\n                                                timedelta(days=7))\n            print(presignedURL)\n\n        :param bucket_name: Bucket for the presigned url.\n        :param object_name: Object for which presigned url is generated.\n        :param expires: Optional expires argument to specify timedelta.\n           Defaults to 7days.\n        :params response_headers: Optional response_headers argument to\n                                  specify response fields like date, size,\n                                  type of file, data about server, etc.\n        :params request_date: Optional request_date argument to\n                              specify a different request date. Default is\n                              current date.\n        :return: Presigned url."
  },
  {
    "code": "def generate_np(self, x_val, **kwargs):\n    _, feedable, _feedable_types, hash_key = self.construct_variables(kwargs)\n    if hash_key not in self.graphs:\n      with tf.variable_scope(None, 'attack_%d' % len(self.graphs)):\n        with tf.device('/gpu:0'):\n          x = tf.placeholder(tf.float32, shape=x_val.shape, name='x')\n        inputs, outputs = self.generate(x, **kwargs)\n        from runner import RunnerMultiGPU\n        runner = RunnerMultiGPU(inputs, outputs, sess=self.sess)\n        self.graphs[hash_key] = runner\n    runner = self.graphs[hash_key]\n    feed_dict = {'x': x_val}\n    for name in feedable:\n      feed_dict[name] = feedable[name]\n    fvals = runner.run(feed_dict)\n    while not runner.is_finished():\n      fvals = runner.run()\n    return fvals['adv_x']",
    "docstring": "Facilitates testing this attack."
  },
  {
    "code": "def get_arrive_stop(self, **kwargs):\n        params = {\n            'idStop': kwargs.get('stop_number'),\n            'cultureInfo': util.language_code(kwargs.get('lang'))\n        }\n        result = self.make_request('geo', 'get_arrive_stop', **params)\n        if not util.check_result(result, 'arrives'):\n            return False, 'UNKNOWN ERROR'\n        values = util.response_list(result, 'arrives')\n        return True, [emtype.Arrival(**a) for a in values]",
    "docstring": "Obtain bus arrival info in target stop.\n\n        Args:\n            stop_number (int): Stop number to query.\n            lang (str): Language code (*es* or *en*).\n\n        Returns:\n            Status boolean and parsed response (list[Arrival]), or message string\n            in case of error."
  },
  {
    "code": "def get_swstat_bits(frame_filenames, swstat_channel_name, start_time, end_time):\n    swstat = frame.read_frame(frame_filenames, swstat_channel_name,\n                      start_time=start_time, end_time=end_time)\n    bits = bin(int(swstat[0]))\n    filterbank_off = False\n    if len(bits) < 14 or int(bits[-13]) == 0 or int(bits[-11]) == 0:\n        filterbank_off = True\n    return bits[-10:], filterbank_off",
    "docstring": "This function just checks the first time in the SWSTAT channel\n    to see if the filter was on, it doesn't check times beyond that.\n\n    This is just for a first test on a small chunck of data.\n\n    To read the SWSTAT bits, reference: https://dcc.ligo.org/DocDB/0107/T1300711/001/LIGO-T1300711-v1.pdf\n\n    Bit 0-9 = Filter on/off switches for the 10 filters in an SFM.\n    Bit 10 = Filter module input switch on/off\n    Bit 11 = Filter module offset switch on/off\n    Bit 12 = Filter module output switch on/off\n    Bit 13 = Filter module limit switch on/off\n    Bit 14 = Filter module history reset momentary switch"
  },
  {
    "code": "def collect_filtered_models(discard, *input_values):\n    ids = set([])\n    collected = []\n    queued = []\n    def queue_one(obj):\n        if obj.id not in ids and not (callable(discard) and discard(obj)):\n            queued.append(obj)\n    for value in input_values:\n        _visit_value_and_its_immediate_references(value, queue_one)\n    while queued:\n        obj = queued.pop(0)\n        if obj.id not in ids:\n            ids.add(obj.id)\n            collected.append(obj)\n            _visit_immediate_value_references(obj, queue_one)\n    return collected",
    "docstring": "Collect a duplicate-free list of all other Bokeh models referred to by\n    this model, or by any of its references, etc, unless filtered-out by the\n    provided callable.\n\n    Iterate over ``input_values`` and descend through their structure\n    collecting all nested ``Models`` on the go.\n\n    Args:\n        *discard (Callable[[Model], bool])\n            a callable which accepts a *Model* instance as its single argument\n            and returns a boolean stating whether to discard the instance. The\n            latter means that the instance will not be added to collected\n            models nor will its references be explored.\n\n        *input_values (Model)\n            Bokeh models to collect other models from\n\n    Returns:\n        None"
  },
  {
    "code": "def shorten(string, maxlen):\n    if 1 < maxlen < len(string):\n        string = string[:maxlen - 1] + u'…'\n    return string[:maxlen]",
    "docstring": "shortens string if longer than maxlen, appending ellipsis"
  },
  {
    "code": "def _check_embedded_object(embedded_object, type, value, element_kind,\n                           element_name):\n    if embedded_object not in ('instance', 'object'):\n        raise ValueError(\n            _format(\"{0} {1!A} specifies an invalid value for \"\n                    \"embedded_object: {2!A} (must be 'instance' or 'object')\",\n                    element_kind, element_name, embedded_object))\n    if type != 'string':\n        raise ValueError(\n            _format(\"{0} {1!A} specifies embedded_object {2!A} but its CIM \"\n                    \"type is invalid: {3!A} (must be 'string')\",\n                    element_kind, element_name, embedded_object, type))\n    if value is not None:\n        if isinstance(value, list):\n            if value:\n                v0 = value[0]\n                if v0 is not None and \\\n                        not isinstance(v0, (CIMInstance, CIMClass)):\n                    raise ValueError(\n                        _format(\"Array {0} {1!A} specifies embedded_object \"\n                                \"{2!A} but the Python type of its first array \"\n                                \"value is invalid: {3} (must be CIMInstance \"\n                                \"or CIMClass)\",\n                                element_kind, element_name, embedded_object,\n                                builtin_type(v0)))\n        else:\n            if not isinstance(value, (CIMInstance, CIMClass)):\n                raise ValueError(\n                    _format(\"{0} {1!A} specifies embedded_object {2!A} but \"\n                            \"the Python type of its value is invalid: {3} \"\n                            \"(must be CIMInstance or CIMClass)\",\n                            element_kind, element_name, embedded_object,\n                            builtin_type(value)))",
    "docstring": "Check whether embedded-object-related parameters are ok."
  },
  {
    "code": "def at(self, hour, minute=0, second=0, microsecond=0):\n        return self.set(\n            hour=hour, minute=minute, second=second, microsecond=microsecond\n        )",
    "docstring": "Returns a new instance with the current time to a different time.\n\n        :param hour: The hour\n        :type hour: int\n\n        :param minute: The minute\n        :type minute: int\n\n        :param second: The second\n        :type second: int\n\n        :param microsecond: The microsecond\n        :type microsecond: int\n\n        :rtype: DateTime"
  },
  {
    "code": "def refresh(self):\n        r = fapi.get_workspace(self.namespace, self.name, self.api_url)\n        fapi._check_response_code(r, 200)\n        self.data = r.json()\n        return self",
    "docstring": "Reload workspace metadata from firecloud.\n\n        Workspace metadata is cached in the data attribute of a Workspace,\n        and may become stale, requiring a refresh()."
  },
  {
    "code": "def fit(self, X):\n        self.n_samples_fit = X.shape[0]\n        if self.metric_kwds is None:\n            metric_kwds = {}\n        else:\n            metric_kwds = self.metric_kwds\n        self.pynndescent_ = NNDescent(\n            X,\n            self.metric,\n            metric_kwds,\n            self.n_neighbors,\n            self.n_trees,\n            self.leaf_size,\n            self.pruning_level,\n            self.tree_init,\n            self.random_state,\n            self.algorithm,\n            self.max_candidates,\n            self.n_iters,\n            self.early_termination_value,\n            self.sampling_rate,\n        )\n        return self",
    "docstring": "Fit the PyNNDescent transformer to build KNN graphs with\n        neighbors given by the dataset X.\n\n        Parameters\n        ----------\n        X : array-like, shape (n_samples, n_features)\n            Sample data\n\n        Returns\n        -------\n        transformer : PyNNDescentTransformer\n            The trained transformer"
  },
  {
    "code": "def create_audit_event(self, code='AUDIT'):\n        event = self._meta.event_model(\n            code=code,\n            model=self.__class__.__name__,\n        )\n        if current_user:\n            event.created_by = current_user.get_id()\n        self.copy_foreign_keys(event)\n        self.populate_audit_fields(event)\n        return event",
    "docstring": "Creates a generic auditing Event logging the changes between saves\n        and the initial data in creates.\n\n        Kwargs:\n            code (str): The code to set the new Event to.\n\n        Returns:\n            Event: A new event with relevant info inserted into it"
  },
  {
    "code": "def dot_eth_label(name):\n    label = name_to_label(name, registrar='eth')\n    if len(label) < MIN_ETH_LABEL_LENGTH:\n        raise InvalidLabel('name %r is too short' % label)\n    else:\n        return label",
    "docstring": "Convert from a name, like 'ethfinex.eth', to a label, like 'ethfinex'\n    If name is already a label, this should be a noop, except for converting to a string\n    and validating the name syntax."
  },
  {
    "code": "def _wrapped(self):\n        assignments = tuple(\n            a for a in functools.WRAPPER_ASSIGNMENTS if a != '__name__' and a != '__module__')\n        @functools.wraps(self.func, assigned=assignments)\n        def wrapper(*args):\n            return self(*args)\n        wrapper.__name__ = self._name\n        wrapper.__module__ = (self.func.__module__ if hasattr(self.func, '__module__')\n                              else self.func.__class__.__module__)\n        wrapper.func = self.func\n        wrapper.returnType = self.returnType\n        wrapper.evalType = self.evalType\n        wrapper.deterministic = self.deterministic\n        wrapper.asNondeterministic = functools.wraps(\n            self.asNondeterministic)(lambda: self.asNondeterministic()._wrapped())\n        return wrapper",
    "docstring": "Wrap this udf with a function and attach docstring from func"
  },
  {
    "code": "def evaluate_stream(self, stream: StreamWrapper) -> None:\n        self._run_epoch(stream=stream, train=False)",
    "docstring": "Evaluate the given stream.\n\n        :param stream: stream to be evaluated\n        :param stream_name: stream name"
  },
  {
    "code": "def destroy_decompress(dinfo):\n    argtypes = [ctypes.POINTER(DecompressionInfoType)]\n    OPENJPEG.opj_destroy_decompress.argtypes = argtypes\n    OPENJPEG.opj_destroy_decompress(dinfo)",
    "docstring": "Wraps openjpeg library function opj_destroy_decompress."
  },
  {
    "code": "def write(self, char):\n        char = str(char).lower()\n        self.segments.write(self.font[char])",
    "docstring": "Display a single character on the display\n\n        :type char: str or int\n        :param char: Character to display"
  },
  {
    "code": "def _get_response_ms(self):\n        response_timedelta = now() - self.log['requested_at']\n        response_ms = int(response_timedelta.total_seconds() * 1000)\n        return max(response_ms, 0)",
    "docstring": "Get the duration of the request response cycle is milliseconds.\n        In case of negative duration 0 is returned."
  },
  {
    "code": "def tag_remove(self, *tags):\n        return View({**self.spec, 'tag': list(set(self.tags) - set(tags))})",
    "docstring": "Return a view with the specified tags removed"
  },
  {
    "code": "def sign(mv):\n    md5 = hashlib.md5()\n    update_hash(md5, mv)\n    return md5.digest()",
    "docstring": "Obtains a signature for a `MetricValue`\n\n    Args:\n       mv (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricValue`): a\n         MetricValue that's part of an operation\n\n    Returns:\n       string: a unique signature for that operation"
  },
  {
    "code": "def processWhileRunning(self):\n        work = self.step()\n        for result, more in work:\n            yield result\n            if not self.running:\n                break\n            if more:\n                delay = 0.1\n            else:\n                delay = 10.0\n            yield task.deferLater(reactor, delay, lambda: None)",
    "docstring": "Run tasks until stopService is called."
  },
  {
    "code": "def clear(self):\n        while True:\n            try:\n                session = self._sessions.get(block=False)\n            except queue.Empty:\n                break\n            else:\n                session.delete()",
    "docstring": "Delete all sessions in the pool."
  },
  {
    "code": "def __decode_ext_desc(self, value_type, value):\n        if value_type == 0:\n            return self.__decode_string(value)\n        elif value_type == 1:\n            return value\n        elif 1 < value_type < 6:\n            return _bytes_to_int_le(value)",
    "docstring": "decode ASF_EXTENDED_CONTENT_DESCRIPTION_OBJECT values"
  },
  {
    "code": "def relay_events_from(self, originator, event_type, *more_event_types):\n        handlers = {\n                event_type: lambda *args, **kwargs: \\\n                    self.dispatch_event(event_type, *args, **kwargs)\n                for event_type in (event_type,) + more_event_types\n        }\n        originator.set_handlers(**handlers)",
    "docstring": "Configure this handler to re-dispatch events from another handler.\n\n        This method configures this handler dispatch an event of type \n        *event_type* whenever *originator* dispatches events of the same type \n        or any of the types in *more_event_types*.  Any arguments passed to the \n        original event are copied to the new event.\n\n        This method is mean to be useful for creating composite widgets that \n        want to present a simple API by making it seem like the events being \n        generated by their children are actually coming from them.  See the \n        `/composing_widgets` tutorial for an example."
  },
  {
    "code": "def set_window_user_pointer(window, pointer):\n    data = (False, pointer)\n    if not isinstance(pointer, ctypes.c_void_p):\n        data = (True, pointer)\n        pointer = ctypes.cast(ctypes.pointer(ctypes.py_object(pointer)), ctypes.c_void_p)\n    window_addr = ctypes.cast(ctypes.pointer(window),\n                              ctypes.POINTER(ctypes.c_long)).contents.value\n    _window_user_data_repository[window_addr] = data\n    _glfw.glfwSetWindowUserPointer(window, pointer)",
    "docstring": "Sets the user pointer of the specified window. You may pass a normal python object into this function and it will\n    be wrapped automatically. The object will be kept in existence until the pointer is set to something else or\n    until the window is destroyed.\n\n    Wrapper for:\n        void glfwSetWindowUserPointer(GLFWwindow* window, void* pointer);"
  },
  {
    "code": "def _validate_ids(self, resource_ids):\n        for resource_id in resource_ids:\n            if self._id_regex.fullmatch(resource_id) is None:\n                LOGGER.debug('Invalid resource id requested: %s', resource_id)\n                raise _ResponseFailed(self._status.INVALID_ID)",
    "docstring": "Validates a list of ids, raising a ResponseFailed error if invalid.\n\n        Args:\n            resource_id (list of str): The ids to validate\n\n        Raises:\n            ResponseFailed: The id was invalid, and a status of INVALID_ID\n                will be sent with the response."
  },
  {
    "code": "def log(client, revision, format, no_output, paths):\n    graph = Graph(client)\n    if not paths:\n        start, is_range, stop = revision.partition('..')\n        if not is_range:\n            stop = start\n        elif not stop:\n            stop = 'HEAD'\n        commit = client.repo.rev_parse(stop)\n        paths = (\n            str(client.path / item.a_path)\n            for item in commit.diff(commit.parents or NULL_TREE)\n        )\n    graph.build(paths=paths, revision=revision, can_be_cwl=no_output)\n    FORMATS[format](graph)",
    "docstring": "Show logs for a file."
  },
  {
    "code": "def zGetUpdate(self):\n        status,ret = -998, None\n        ret = self._sendDDEcommand(\"GetUpdate\")\n        if ret != None:\n            status = int(ret)\n        return status",
    "docstring": "Update the lens"
  },
  {
    "code": "def send_offset_commit_request(self, group, payloads=None,\n                                   fail_on_error=True, callback=None,\n                                   group_generation_id=-1,\n                                   consumer_id=''):\n        group = _coerce_consumer_group(group)\n        encoder = partial(KafkaCodec.encode_offset_commit_request,\n                          group=group, group_generation_id=group_generation_id,\n                          consumer_id=consumer_id)\n        decoder = KafkaCodec.decode_offset_commit_response\n        resps = yield self._send_broker_aware_request(\n            payloads, encoder, decoder, consumer_group=group)\n        returnValue(self._handle_responses(\n            resps, fail_on_error, callback, group))",
    "docstring": "Send a list of OffsetCommitRequests to the Kafka broker for the\n        given consumer group.\n\n        Args:\n          group (str): The consumer group to which to commit the offsets\n          payloads ([OffsetCommitRequest]): List of topic, partition, offsets\n            to commit.\n          fail_on_error (bool): Whether to raise an exception if a response\n            from the Kafka broker indicates an error\n          callback (callable): a function to call with each of the responses\n            before returning the returned value to the caller.\n          group_generation_id (int): Must currently always be -1\n          consumer_id (str): Must currently always be empty string\n        Returns:\n          [OffsetCommitResponse]: List of OffsetCommitResponse objects.\n          Will raise KafkaError for failed requests if fail_on_error is True"
  },
  {
    "code": "def resolve_primary_keys_in_schema(sql_tokens: List[str],\n                                   schema: Dict[str, List[TableColumn]]) -> List[str]:\n    primary_keys_for_tables = {name: max(columns, key=lambda x: x.is_primary_key).name\n                               for name, columns in schema.items()}\n    resolved_tokens = []\n    for i, token in enumerate(sql_tokens):\n        if i > 2:\n            table_name = sql_tokens[i - 2]\n            if token == \"ID\" and table_name in primary_keys_for_tables.keys():\n                token = primary_keys_for_tables[table_name]\n        resolved_tokens.append(token)\n    return resolved_tokens",
    "docstring": "Some examples in the text2sql datasets use ID as a column reference to the\n    column of a table which has a primary key. This causes problems if you are trying\n    to constrain a grammar to only produce the column names directly, because you don't\n    know what ID refers to. So instead of dealing with that, we just replace it."
  },
  {
    "code": "def grist (self):\n        path = self.path ()\n        if path:\n            return 'p' + path\n        else:\n            project_location = self.project_.get ('location')\n            path_components = b2.util.path.split(project_location)\n            location_grist = '!'.join (path_components)\n            if self.action_:\n                ps = self.action_.properties ()\n                property_grist = ps.as_path ()\n                if property_grist:\n                    location_grist = location_grist + '/' + property_grist\n            return 'l' + location_grist",
    "docstring": "Helper to 'actual_name', above. Compute unique prefix used to distinguish\n            this target from other targets with the same name which create different\n            file."
  },
  {
    "code": "def findfirst(f, coll):\r\n    result = list(dropwhile(f, coll))\r\n    return result[0] if result else None",
    "docstring": "Return first occurrence matching f, otherwise None"
  },
  {
    "code": "def make_edge_vectors(adjacency_matrix, num_edge_types, depth, name=None):\n  with tf.variable_scope(name, default_name=\"edge_vectors\"):\n    att_adj_vectors_shape = [num_edge_types, depth]\n    adjacency_matrix_shape = common_layers.shape_list(adjacency_matrix)\n    adj_vectors = (\n        tf.get_variable(\n            \"adj_vectors\",\n            att_adj_vectors_shape,\n            initializer=tf.random_normal_initializer(0, depth**-0.5)) *\n        (depth**0.5))\n    adjacency_matrix_one_hot = tf.one_hot(adjacency_matrix, num_edge_types)\n    att_adj_vectors = tf.matmul(\n        tf.reshape(tf.to_float(adjacency_matrix_one_hot), [-1, num_edge_types]),\n        adj_vectors)\n    return tf.reshape(att_adj_vectors,\n                      [adjacency_matrix_shape[0], adjacency_matrix_shape[1],\n                       adjacency_matrix_shape[2], depth])",
    "docstring": "Gets edge vectors for the edge types in the adjacency matrix.\n\n  Args:\n    adjacency_matrix: A [batch, num_nodes, num_nodes] tensor of ints.\n    num_edge_types: Number of different edge types\n    depth: Number of channels\n    name: a string\n  Returns:\n    A [batch, num_nodes, num_nodes, depth] vector of tensors"
  },
  {
    "code": "def open(self, results=False):\n        webbrowser.open(self.results_url if results else self.url)",
    "docstring": "Open the strawpoll in a browser. Can specify to open the main or results page.\n\n        :param results: True/False"
  },
  {
    "code": "def _checkType(self, obj, identifier):\n        if not isinstance(obj, basestring):\n            raise TypeError(\"expected %s '%s' to be a string (was '%s')\" %\n                            (identifier, obj, type(obj).__name__))",
    "docstring": "Assert that an object is of type str."
  },
  {
    "code": "def maskIndex(self):\n        if isinstance(self.mask, bool):\n            return np.full(self.data.shape, self.mask, dtype=np.bool)\n        else:\n            return self.mask",
    "docstring": "Returns a boolean index with True if the value is masked.\n\n            Always has the same shape as the maksedArray.data, event if the mask is a single boolan."
  },
  {
    "code": "def parse_xmlsec_output(output):\n    for line in output.splitlines():\n        if line == 'OK':\n            return True\n        elif line == 'FAIL':\n            raise XmlsecError(output)\n    raise XmlsecError(output)",
    "docstring": "Parse the output from xmlsec to try to find out if the\n    command was successfull or not.\n\n    :param output: The output from Popen\n    :return: A boolean; True if the command was a success otherwise False"
  },
  {
    "code": "def _get_indices_and_signs(hasher, terms):\n    X = _transform_terms(hasher, terms)\n    indices = X.nonzero()[1]\n    signs = X.sum(axis=1).A.ravel()\n    return indices, signs",
    "docstring": "For each term from ``terms`` return its column index and sign,\n    as assigned by FeatureHasher ``hasher``."
  },
  {
    "code": "def get_char_range(self, start, end, increment=None):\n        increment = int(increment) if increment else 1\n        if increment < 0:\n            increment = -increment\n        if increment == 0:\n            increment = 1\n        inverse = start > end\n        alpha = _nalpha if inverse else _alpha\n        start = alpha.index(start)\n        end = alpha.index(end)\n        if start < end:\n            return (c for c in alpha[start:end + 1:increment])\n        else:\n            return (c for c in alpha[end:start + 1:increment])",
    "docstring": "Get a range of alphabetic characters."
  },
  {
    "code": "def get_len(self, key):\r\n        data = self.model.get_data()\r\n        return len(data[key])",
    "docstring": "Return sequence length"
  },
  {
    "code": "def _get_external_network_dict(self, context, port_db):\n        if port_db.device_owner == DEVICE_OWNER_ROUTER_GW:\n            network = self._core_plugin.get_network(context,\n                port_db.network_id)\n        else:\n            router = self.l3_plugin.get_router(context,\n                port_db.device_id)\n            ext_gw_info = router.get(EXTERNAL_GW_INFO)\n            if not ext_gw_info:\n                return {}, None\n            network = self._core_plugin.get_network(context,\n                ext_gw_info['network_id'])\n        external_network = self.get_ext_net_name(network['name'])\n        transit_net = self.transit_nets_cfg.get(\n            external_network) or self._default_ext_dict\n        transit_net['network_name'] = external_network\n        return transit_net, network",
    "docstring": "Get external network information\n\n        Get the information about the external network,\n        so that it can be used to create the hidden port,\n        subnet, and network."
  },
  {
    "code": "def exists(self):\n        if self.driver == 'sqlite' and not os.path.exists(self.path):\n            return False\n        self.engine\n        try:\n            from sqlalchemy.engine.reflection import Inspector\n            inspector = Inspector.from_engine(self.engine)\n            if 'config' in inspector.get_table_names(schema=self._schema):\n                return True\n            else:\n                return False\n        finally:\n            self.close_connection()",
    "docstring": "Return True if the database exists, or for Sqlite, which will create the file on the\n        first reference, the file has been initialized with the root config"
  },
  {
    "code": "def add_paths_to_os(self, key=None, update=None):\n        if key is not None:\n            allpaths = key if isinstance(key, list) else [key]\n        else:\n            allpaths = [k for k in self.environ.keys() if 'default' not in k]\n        for key in allpaths:\n            paths = self.get_paths(key)\n            self.check_paths(paths, update=update)",
    "docstring": "Add the paths in tree environ into the os environ\n\n        This code goes through the tree environ and checks\n        for existence in the os environ, then adds them\n\n        Parameters:\n            key (str):\n                The section name to check against / add\n            update (bool):\n                If True, overwrites existing tree environment variables in your\n                local environment.  Default is False."
  },
  {
    "code": "def remove_file_filters(self, file_filters):\n        self.file_filters = util.remove_from_list(self.file_filters,\n                                                  file_filters)",
    "docstring": "Removes the `file_filters` from the internal state.\n        `file_filters` can be a single object or an iterable."
  },
  {
    "code": "def getTypesModuleName(self):\n        if self.types_module_name is not None:\n            return self.types_module_name\n        name = GetModuleBaseNameFromWSDL(self._wsdl)\n        if not name:\n            raise WsdlGeneratorError, 'could not determine a service name'\n        if self.types_module_suffix is None:\n            return name\n        return '%s%s' %(name, self.types_module_suffix)",
    "docstring": "types module name."
  },
  {
    "code": "def cmp_ast(node1, node2):\n    if type(node1) != type(node2):\n        return False\n    if isinstance(node1, (list, tuple)):\n        if len(node1) != len(node2):\n            return False\n        for left, right in zip(node1, node2):\n            if not cmp_ast(left, right):\n                return False\n    elif isinstance(node1, ast.AST):\n        for field in node1._fields:\n            left = getattr(node1, field, Undedined)\n            right = getattr(node2, field, Undedined)\n            if not cmp_ast(left, right):\n                return False\n    else:\n        return node1 == node2\n    return True",
    "docstring": "Compare if two nodes are equal."
  },
  {
    "code": "def _encode(data):\n    if not isinstance(data, bytes_types):\n        data = six.b(str(data))\n    return base64.b64encode(data).decode(\"utf-8\")",
    "docstring": "Encode the given data using base-64\n\n    :param data:\n    :return: base-64 encoded string"
  },
  {
    "code": "def ulocalized_time(time, long_format=None, time_only=None, context=None,\n                    request=None):\n    time = get_date(context, time)\n    if not time or not isinstance(time, DateTime):\n        return ''\n    if time.second() + time.minute() + time.hour() == 0:\n        long_format = False\n    try:\n        time_str = _ut(time, long_format, time_only, context, 'senaite.core', request)\n    except ValueError:\n        err_msg = traceback.format_exc() + '\\n'\n        logger.warn(\n            err_msg + '\\n' +\n            \"Error converting '{}' time to string in {}.\"\n            .format(time, context))\n        time_str = ''\n    return time_str",
    "docstring": "This function gets ans string as time or a DateTime objects and returns a\n    string with the time formatted\n\n    :param time: The time to process\n    :type time: str/DateTime\n    :param long_format:  If True, return time in ling format\n    :type portal_type: boolean/null\n    :param time_only: If True, only returns time.\n    :type title: boolean/null\n    :param context: The current context\n    :type context: ATContentType\n    :param request: The current request\n    :type request: HTTPRequest object\n    :returns: The formatted date as string\n    :rtype: string"
  },
  {
    "code": "def is_balance_proof_safe_for_onchain_operations(\n        balance_proof: BalanceProofSignedState,\n) -> bool:\n    total_amount = balance_proof.transferred_amount + balance_proof.locked_amount\n    return total_amount <= UINT256_MAX",
    "docstring": "Check if the balance proof would overflow onchain."
  },
  {
    "code": "def _start_beacon(port=None):\n    global _beacon\n    if _beacon is None:\n        _logger.debug(\"About to start beacon with port %s\", port)\n        try:\n            _beacon = _Beacon(port)\n        except (OSError, socket.error) as exc:\n            if exc.errno == errno.EADDRINUSE:\n                _logger.warn(\"Beacon already active on this machine\")\n                _beacon = _remote_beacon\n            else:\n                raise\n        else:\n            _beacon.start()",
    "docstring": "Start a beacon thread within this process if no beacon is currently\n    running on this machine.\n    \n    In general this is called automatically when an attempt is made to\n    advertise or discover. It might be convenient, though, to call this\n    function directly if you want to have a process whose only job is\n    to host this beacon so that it doesn't shut down when other processes\n    shut down."
  },
  {
    "code": "def build_output(self, fout):\n        fout.write('\\n'.join([s for s in self.out]))",
    "docstring": "Squash self.out into string.\n\n        Join every line in self.out with a new line and write the\n        result to the output file."
  },
  {
    "code": "def match(self, expression=None, xpath=None, namespaces=None): \n        class MatchObject(Dict):\n            pass\n        def _match(function):\n            self.matches.append(\n                MatchObject(expression=expression, xpath=xpath, function=function, namespaces=namespaces))\n            def wrapper(self, *args, **params):\n                return function(self, *args, **params)\n            return wrapper\n        return _match",
    "docstring": "decorator that allows us to match by expression or by xpath for each transformation method"
  },
  {
    "code": "def to_html(self):\n        uri = resource_url(\n            resources_path('img', 'logos', 'inasafe-logo-white.png'))\n        snippet = (\n            '<div class=\"branding\">'\n            '<img src=\"%s\" title=\"%s\" alt=\"%s\" %s/></div>') % (\n                uri,\n                'InaSAFE',\n                'InaSAFE',\n                self.html_attributes())\n        return snippet",
    "docstring": "Render as html."
  },
  {
    "code": "def getTaskTypes(self):\n        types = [\n            ('Calibration', safe_unicode(_('Calibration')).encode('utf-8')),\n            ('Enhancement', safe_unicode(_('Enhancement')).encode('utf-8')),\n            ('Preventive', safe_unicode(_('Preventive')).encode('utf-8')),\n            ('Repair', safe_unicode(_('Repair')).encode('utf-8')),\n            ('Validation', safe_unicode(_('Validation')).encode('utf-8')),\n        ]\n        return DisplayList(types)",
    "docstring": "Return the current list of task types"
  },
  {
    "code": "def get_element_child_info(doc, attr):\n    props = []\n    for child in doc:\n        if child.tag not in [\"author_signature\", \"parent_author_signature\"]:\n            props.append(getattr(child, attr))\n    return props",
    "docstring": "Get information from child elements of this elementas a list since order is important.\n\n    Don't include signature tags.\n\n    :param doc: XML element\n    :param attr: Attribute to get from the elements, for example \"tag\" or \"text\"."
  },
  {
    "code": "def version(self):\n        cmd = b\"version\\r\\n\"\n        results = self._misc_cmd([cmd], b'version', False)\n        before, _, after = results[0].partition(b' ')\n        if before != b'VERSION':\n            raise MemcacheUnknownError(\n                \"Received unexpected response: %s\" % results[0])\n        return after",
    "docstring": "The memcached \"version\" command.\n\n        Returns:\n            A string of the memcached version."
  },
  {
    "code": "def _n_onset_midi(patterns):\n    return len([o_m for pat in patterns for occ in pat for o_m in occ])",
    "docstring": "Computes the number of onset_midi objects in a pattern\n\n    Parameters\n    ----------\n    patterns :\n        A list of patterns using the format returned by\n        :func:`mir_eval.io.load_patterns()`\n\n    Returns\n    -------\n    n_onsets : int\n        Number of onsets within the pattern."
  },
  {
    "code": "def __try_read_byte_prev(self, address):\n        if address not in self.__memory_prev:\n            return False, None\n        return True, self.__memory_prev[address]",
    "docstring": "Read previous value for memory location.\n\n        Return a tuple (True, Byte) in case of successful read,\n        (False, None) otherwise."
  },
  {
    "code": "def is_active(self, name):\n        if name in self._plugins.keys():\n            return self._plugins[\"name\"].active\n        return None",
    "docstring": "Returns True if plugin exists and is active.\n        If plugin does not exist, it returns None\n\n        :param name: plugin name\n        :return: boolean or None"
  },
  {
    "code": "def t_insert_dict_if_new(self, tblname, d, PKfields, fields=None):\n        SQL, values = self._insert_dict_if_new_inner(tblname, d, PKfields, fields=fields)\n        if SQL != False:\n            self.execute_select(SQL, parameters=values, locked=True)\n            return True, d\n        return False, values",
    "docstring": "A version of insertDictIfNew for transactions. This does not call commit."
  },
  {
    "code": "def _put_bucket_lifecycle(self):\n        status = 'deleted'\n        if self.s3props['lifecycle']['enabled']:\n            lifecycle_config = {\n                'Rules': self.s3props['lifecycle']['lifecycle_rules']\n            }\n            LOG.debug('Lifecycle Config: %s', lifecycle_config)\n            _response = self.s3client.put_bucket_lifecycle_configuration(Bucket=self.bucket,\n                                                                         LifecycleConfiguration=lifecycle_config)\n            status = 'applied'\n        else:\n            _response = self.s3client.delete_bucket_lifecycle(Bucket=self.bucket)\n        LOG.debug('Response setting up S3 lifecycle: %s', _response)\n        LOG.info('S3 lifecycle configuration %s', status)",
    "docstring": "Adds bucket lifecycle configuration."
  },
  {
    "code": "def push_state(self):\n        new = dict(self.states[-1])\n        self.states.append(new)\n        return self.state",
    "docstring": "Push a copy of the topmost state on top of the state stack,\n        returns the new top."
  },
  {
    "code": "def start(self):\n        setproctitle('oq-zworkerpool %s' % self.ctrl_url[6:])\n        self.workers = []\n        for _ in range(self.num_workers):\n            sock = z.Socket(self.task_out_port, z.zmq.PULL, 'connect')\n            proc = multiprocessing.Process(target=self.worker, args=(sock,))\n            proc.start()\n            sock.pid = proc.pid\n            self.workers.append(sock)\n        with z.Socket(self.ctrl_url, z.zmq.REP, 'bind') as ctrlsock:\n            for cmd in ctrlsock:\n                if cmd in ('stop', 'kill'):\n                    msg = getattr(self, cmd)()\n                    ctrlsock.send(msg)\n                    break\n                elif cmd == 'getpid':\n                    ctrlsock.send(self.pid)\n                elif cmd == 'get_num_workers':\n                    ctrlsock.send(self.num_workers)",
    "docstring": "Start worker processes and a control loop"
  },
  {
    "code": "def to_coo(self, fp=None, vartype_header=False):\n        import dimod.serialization.coo as coo\n        if fp is None:\n            return coo.dumps(self, vartype_header)\n        else:\n            coo.dump(self, fp, vartype_header)",
    "docstring": "Serialize the binary quadratic model to a COOrdinate_ format encoding.\n\n        .. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO)\n\n        Args:\n            fp (file, optional):\n                `.write()`-supporting `file object`_ to save the linear and quadratic biases\n                of a binary quadratic model to. The model is stored as a list of 3-tuples,\n                (i, j, bias), where :math:`i=j` for linear biases. If not provided,\n                returns a string.\n\n            vartype_header (bool, optional, default=False):\n                If true, the binary quadratic model's variable type as prepended to the\n                string or file as a header.\n\n        .. _file object: https://docs.python.org/3/glossary.html#term-file-object\n\n        .. note:: Variables must use index lables (numeric lables). Binary quadratic\n            models saved to COOrdinate format encoding do not preserve offsets.\n\n        Examples:\n            This is an example of a binary quadratic model encoded in COOrdinate format.\n\n            .. code-block:: none\n\n                0 0 0.50000\n                0 1 0.50000\n                1 1 -1.50000\n\n            The Coordinate format with a header\n\n            .. code-block:: none\n\n                # vartype=SPIN\n                0 0 0.50000\n                0 1 0.50000\n                1 1 -1.50000\n\n            This is an example of writing a binary quadratic model to a COOrdinate-format\n            file.\n\n            >>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.SPIN)\n            >>> with open('tmp.ising', 'w') as file:  # doctest: +SKIP\n            ...     bqm.to_coo(file)\n\n            This is an example of writing a binary quadratic model to a COOrdinate-format string.\n\n            >>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.SPIN)\n            >>> bqm.to_coo()  # doctest: +SKIP\n            0 0 -1.000000\n            0 1 -1.000000\n            1 1 1.000000"
  },
  {
    "code": "def glyph_has_ink(font: TTFont, name: Text) -> bool:\n  if 'glyf' in font:\n    return ttf_glyph_has_ink(font, name)\n  elif ('CFF ' in font) or ('CFF2' in font):\n    return cff_glyph_has_ink(font, name)\n  else:\n    raise Exception(\"Could not find 'glyf', 'CFF ', or 'CFF2' table.\")",
    "docstring": "Checks if specified glyph has any ink.\n\n  That is, that it has at least one defined contour associated.\n  Composites are considered to have ink if any of their components have ink.\n  Args:\n      font:       the font\n      glyph_name: The name of the glyph to check for ink.\n  Returns:\n      True if the font has at least one contour associated with it."
  },
  {
    "code": "def extract_mime(self, mime, def_mime='unk'):\n        self['mime'] = def_mime\n        if mime:\n            self['mime'] = self.MIME_RE.split(mime, 1)[0]\n            self['_content_type'] = mime",
    "docstring": "Utility function to extract mimetype only\n        from a full content type, removing charset settings"
  },
  {
    "code": "def run_details(self, run):\n        run_data = dict(run=run)\n        req = urllib.request.Request(\"%s/nglims/api_run_details\" % self._base_url,\n                urllib.parse.urlencode(run_data))\n        response = urllib.request.urlopen(req)\n        info = json.loads(response.read())\n        if \"error\" in info:\n            raise ValueError(\"Problem retrieving info: %s\" % info[\"error\"])\n        else:\n            return info[\"details\"]",
    "docstring": "Retrieve sequencing run details as a dictionary."
  },
  {
    "code": "def validate(cls, **kwargs):\n        errors = ValidationErrors()\n        obj = cls()\n        redis = cls.get_redis()\n        for fieldname, field in obj.proxy:\n            if not field.fillable:\n                value = field.default\n            else:\n                try:\n                    value = field.validate(kwargs.get(fieldname), redis)\n                except BadField as e:\n                    errors.append(e)\n                    continue\n            setattr(\n                obj,\n                fieldname,\n                value\n            )\n        for fieldname in dir(cls):\n            rule = getattr(cls, fieldname)\n            if hasattr(rule, '_is_validation_rule') and rule._is_validation_rule:\n                try:\n                    rule(obj)\n                except BadField as e:\n                    errors.append(e)\n        if errors.has_errors():\n            raise errors\n        return obj",
    "docstring": "Validates the data received as keyword arguments whose name match\n        this class attributes."
  },
  {
    "code": "def get_ref(profile, ref):\n    resource = \"/refs/\" + ref\n    data = api.get_request(profile, resource)\n    return prepare(data)",
    "docstring": "Fetch a ref.\n\n    Args:\n\n        profile\n            A profile generated from ``simplygithub.authentication.profile``.\n            Such profiles tell this module (i) the ``repo`` to connect to,\n            and (ii) the ``token`` to connect with.\n\n        ref\n            The ref to fetch, e.g., ``heads/my-feature-branch``.\n\n    Returns\n        A dict with data about the ref."
  },
  {
    "code": "def qsize(self, qname):\n        if qname in self._queues:\n            return self._queues[qname].qsize()\n        else:\n            raise ValueError(_(\"queue %s is not defined\"), qname)",
    "docstring": "Return the approximate size of the queue."
  },
  {
    "code": "def _joint_calling(items):\n    jointcaller = tz.get_in((\"config\", \"algorithm\", \"jointcaller\"), items[0])\n    if jointcaller:\n        assert len(items) == 1, \"Can only do joint calling preparation with GATK with single samples\"\n        assert tz.get_in((\"metadata\", \"batch\"), items[0]) is not None, \\\n            \"Joint calling requires batched samples, %s has no metadata batch.\" % dd.get_sample_name(items[0])\n    return jointcaller",
    "docstring": "Determine if this call feeds downstream into joint calls."
  },
  {
    "code": "def run_step(context):\n    logger.debug(\"started\")\n    context.assert_key_has_value(key='defaults', caller=__name__)\n    context.set_defaults(context['defaults'])\n    logger.info(f\"set {len(context['defaults'])} context item defaults.\")\n    logger.debug(\"done\")",
    "docstring": "Set hierarchy into context with substitutions if it doesn't exist yet.\n\n    context is a dictionary or dictionary-like.\n    context['defaults'] must exist. It's a dictionary.\n\n    Will iterate context['defaults'] and add these as new values where\n    their keys don't already exist. While it's doing so, it will leave\n    all other values in the existing hierarchy untouched.\n\n    List merging is purely additive, with no checks for uniqueness or already\n    existing list items. E.g context [0,1,2] with contextMerge=[2,3,4]\n    will result in [0,1,2,2,3,4]\n\n    Keep this in mind especially where complex types like\n    dicts nest inside a list - a merge will always add a new dict list item,\n    not merge it into whatever dicts might exist on the list already.\n\n    For example, say input context is:\n        key1: value1\n        key2: value2\n        key3:\n            k31: value31\n            k32: value32\n        defaults:\n            key2: 'aaa_{key1}_zzz'\n            key3:\n                k33: value33\n            key4: 'bbb_{key2}_yyy'\n\n    This will result in return context:\n        key1: value1\n        key2: value2\n        key3:\n            k31: value31\n            k32: value32\n            k33: value33\n        key4: bbb_value2_yyy"
  },
  {
    "code": "def _get_names(dirs):\n  alphabets = set()\n  label_names = {}\n  for d in dirs:\n    for example in _walk_omniglot_dir(d):\n      alphabet, alphabet_char_id, label, _ = example\n      alphabets.add(alphabet)\n      label_name = \"%s_%d\" % (alphabet, alphabet_char_id)\n      if label in label_names:\n        assert label_names[label] == label_name\n      else:\n        label_names[label] = label_name\n  label_names = [label_names[k] for k in sorted(label_names)]\n  return alphabets, label_names",
    "docstring": "Get alphabet and label names, union across all dirs."
  },
  {
    "code": "def xread_group(self, group_name, consumer_name, streams, timeout=0,\n                    count=None, latest_ids=None):\n        args = self._xread(streams, timeout, count, latest_ids)\n        fut = self.execute(\n            b'XREADGROUP', b'GROUP', group_name, consumer_name, *args\n        )\n        return wait_convert(fut, parse_messages_by_stream)",
    "docstring": "Perform a blocking read on the given stream as part of a consumer group\n\n        :raises ValueError: if the length of streams and latest_ids do\n                            not match"
  },
  {
    "code": "def adjust_bounding_box(bbox):\n    for i in range(0, 4):\n        if i in bounding_box:\n            bbox[i] = bounding_box[i]\n        else:\n            bbox[i] += delta_bounding_box[i]\n    return bbox",
    "docstring": "Adjust the bounding box as specified by user.\n    Returns the adjusted bounding box.\n\n    - bbox: Bounding box computed from the canvas drawings.\n    It must be a four-tuple of numbers."
  },
  {
    "code": "def configure(root_url, **kwargs):\n    default = kwargs.pop('default', True)\n    kwargs['client_agent'] = 'example-client/' + __version__\n    if 'headers' not in kwargs:\n        kwargs['headers'] = {}\n    kwargs['headers']['Accept-Type'] = 'application/json'\n    if default:\n        default_config.reset(root_url, **kwargs)\n    else:\n        Client.config = wac.Config(root_url, **kwargs)",
    "docstring": "Notice that `configure` can either apply to the default configuration or\n    `Client.config`, which is the  configuration used by the current thread\n    since `Client` inherits form `threading.local`."
  },
  {
    "code": "def _ParseTriggerStartTime(self, parser_mediator, trigger):\n    time_elements_tuple = (\n        trigger.start_date.year, trigger.start_date.month,\n        trigger.start_date.day_of_month, trigger.start_time.hours,\n        trigger.start_time.minutes, 0)\n    date_time = None\n    if time_elements_tuple != (0, 0, 0, 0, 0, 0):\n      try:\n        date_time = dfdatetime_time_elements.TimeElements(\n            time_elements_tuple=time_elements_tuple)\n        date_time.is_local_time = True\n        date_time._precision = dfdatetime_definitions.PRECISION_1_MINUTE\n      except ValueError:\n        parser_mediator.ProduceExtractionWarning(\n            'invalid trigger start time: {0!s}'.format(time_elements_tuple))\n    return date_time",
    "docstring": "Parses the start time from a trigger.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      trigger (job_trigger): a trigger.\n\n    Returns:\n      dfdatetime.DateTimeValues: last run date and time or None if not\n          available."
  },
  {
    "code": "def _call_zincrby(self, command, value, *args, **kwargs):\n        if self.indexable:\n            self.index([value])\n        return self._traverse_command(command, value, *args, **kwargs)",
    "docstring": "This command update a score of a given value. But it can be a new value\n        of the sorted set, so we index it."
  },
  {
    "code": "def find_module(self, fullname, path=None):\n        root, base, target = fullname.partition(self.root_name + '.')\n        if root:\n            return\n        if not any(map(target.startswith, self.vendored_names)):\n            return\n        return self",
    "docstring": "Return self when fullname starts with root_name and the\n        target module is one vendored through this importer."
  },
  {
    "code": "def add_repository(self, name, repository_type, repository_class,\n                       aggregate_class, make_default, configuration):\n        repo_mgr = self.get_registered_utility(IRepositoryManager)\n        if name is None:\n            name = REPOSITORY_DOMAINS.ROOT\n        repo = repo_mgr.new(repository_type, name=name,\n                            make_default=make_default,\n                            repository_class=repository_class,\n                            aggregate_class=aggregate_class,\n                            configuration=configuration)\n        repo_mgr.set(repo)",
    "docstring": "Generic method for adding a repository."
  },
  {
    "code": "def add_genes(in_file, data, max_distance=10000, work_dir=None):\n    gene_file = regions.get_sv_bed(data, \"exons\", out_dir=os.path.dirname(in_file))\n    if gene_file and utils.file_exists(in_file):\n        out_file = \"%s-annotated.bed\" % utils.splitext_plus(in_file)[0]\n        if work_dir:\n            out_file = os.path.join(work_dir, os.path.basename(out_file))\n        if not utils.file_uptodate(out_file, in_file):\n            fai_file = ref.fasta_idx(dd.get_ref_file(data))\n            with file_transaction(data, out_file) as tx_out_file:\n                _add_genes_to_bed(in_file, gene_file, fai_file, tx_out_file, data, max_distance)\n        return out_file\n    else:\n        return in_file",
    "docstring": "Add gene annotations to a BED file from pre-prepared RNA-seq data.\n\n    max_distance -- only keep annotations within this distance of event"
  },
  {
    "code": "def to_fs_path(uri):\n    scheme, netloc, path, _params, _query, _fragment = urlparse(uri)\n    if netloc and path and scheme == 'file':\n        value = \"//{}{}\".format(netloc, path)\n    elif RE_DRIVE_LETTER_PATH.match(path):\n        value = path[1].lower() + path[2:]\n    else:\n        value = path\n    if IS_WIN:\n        value = value.replace('/', '\\\\')\n    return value",
    "docstring": "Returns the filesystem path of the given URI.\n\n    Will handle UNC paths and normalize windows drive letters to lower-case. Also\n    uses the platform specific path separator. Will *not* validate the path for\n    invalid characters and semantics. Will *not* look at the scheme of this URI."
  },
  {
    "code": "def from_url(cls, url, db=None, **kwargs):\n        connection_pool = ConnectionPool.from_url(url, db=db, **kwargs)\n        return cls(connection_pool=connection_pool)",
    "docstring": "Return a Redis client object configured from the given URL\n\n        For example::\n\n            redis://[:password]@localhost:6379/0\n            rediss://[:password]@localhost:6379/0\n            unix://[:password]@/path/to/socket.sock?db=0\n\n        Three URL schemes are supported:\n\n        - ```redis://``\n          <http://www.iana.org/assignments/uri-schemes/prov/redis>`_ creates a\n          normal TCP socket connection\n        - ```rediss://``\n          <http://www.iana.org/assignments/uri-schemes/prov/rediss>`_ creates a\n          SSL wrapped TCP socket connection\n        - ``unix://`` creates a Unix Domain Socket connection\n\n        There are several ways to specify a database number. The parse function\n        will return the first specified option:\n            1. A ``db`` querystring option, e.g. redis://localhost?db=0\n            2. If using the redis:// scheme, the path argument of the url, e.g.\n               redis://localhost/0\n            3. The ``db`` argument to this function.\n\n        If none of these options are specified, db=0 is used.\n\n        Any additional querystring arguments and keyword arguments will be\n        passed along to the ConnectionPool class's initializer. In the case\n        of conflicting arguments, querystring arguments always win."
  },
  {
    "code": "def _post(self, uri, data, headers=None):\n        if not headers:\n            headers = self._get_headers()\n        logging.debug(\"URI=\" + str(uri))\n        logging.debug(\"HEADERS=\" + str(headers))\n        logging.debug(\"BODY=\" + str(data))\n        response = self.session.post(uri, headers=headers,\n                data=json.dumps(data))\n        logging.debug(\"STATUS=\" + str(response.status_code))\n        if response.status_code in [200, 201]:\n            return response.json()\n        else:\n            logging.error(b\"ERROR=\" + response.content)\n            response.raise_for_status()",
    "docstring": "Simple POST request for a given uri path."
  },
  {
    "code": "def parse_torrent_properties(table_datas):\n        output = {'category': table_datas[0].text, 'subcategory': None, 'quality': None, 'language': None}\n        for i in range(1, len(table_datas)):\n            td = table_datas[i]\n            url = td.get('href')\n            params = Parser.get_params(url)\n            if Parser.is_subcategory(params) and not output['subcategory']:\n                output['subcategory'] = td.text\n            elif Parser.is_quality(params) and not output['quality']:\n                output['quality'] = td.text\n            elif Parser.is_language(params) and not output['language']:\n                output['language'] = td.text\n        return output",
    "docstring": "Static method that parses a given list of table data elements and using helper methods\n        `Parser.is_subcategory`, `Parser.is_quality`, `Parser.is_language`, collects torrent properties.\n\n        :param list lxml.HtmlElement table_datas: table_datas to parse\n        :return: identified category, subcategory, quality and languages.\n        :rtype: dict"
  },
  {
    "code": "def is_executable(path):\n    return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE]\n            or stat.S_IXGRP & os.stat(path)[stat.ST_MODE]\n            or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])",
    "docstring": "is the given path executable?"
  },
  {
    "code": "def kill(self):\n    self._killed.set()\n    if not self.is_alive():\n      logging.debug('Cannot kill thread that is no longer running.')\n      return\n    if not self._is_thread_proc_running():\n      logging.debug(\"Thread's _thread_proc function is no longer running, \"\n                    'will not kill; letting thread exit gracefully.')\n      return\n    self.async_raise(ThreadTerminationError)",
    "docstring": "Terminates the current thread by raising an error."
  },
  {
    "code": "def cache_info(self):\n        return {\n            'single_node_repertoire':\n                self._single_node_repertoire_cache.info(),\n            'repertoire': self._repertoire_cache.info(),\n            'mice': self._mice_cache.info()\n        }",
    "docstring": "Report repertoire cache statistics."
  },
  {
    "code": "def mset_list(item, index, value):\n    'set mulitple items via index of int, slice or list'\n    if isinstance(index, (int, slice)):\n        item[index] = value\n    else:\n        map(item.__setitem__, index, value)",
    "docstring": "set mulitple items via index of int, slice or list"
  },
  {
    "code": "def write_packets(self):\n        while self.running:\n            if len(self.write_queue) > 0:\n                self.write_queue[0].send(self.client)\n                self.write_queue.pop(0)",
    "docstring": "Write packets from the queue"
  },
  {
    "code": "def getAssociationFilename(self, server_url, handle):\n        if server_url.find('://') == -1:\n            raise ValueError('Bad server URL: %r' % server_url)\n        proto, rest = server_url.split('://', 1)\n        domain = _filenameEscape(rest.split('/', 1)[0])\n        url_hash = _safe64(server_url)\n        if handle:\n            handle_hash = _safe64(handle)\n        else:\n            handle_hash = ''\n        filename = '%s-%s-%s-%s' % (proto, domain, url_hash, handle_hash)\n        return os.path.join(self.association_dir, filename)",
    "docstring": "Create a unique filename for a given server url and\n        handle. This implementation does not assume anything about the\n        format of the handle. The filename that is returned will\n        contain the domain name from the server URL for ease of human\n        inspection of the data directory.\n\n        (str, str) -> str"
  },
  {
    "code": "def send_faucet_coins(address_to_fund, satoshis, api_key, coin_symbol='bcy'):\n    assert coin_symbol in ('bcy', 'btc-testnet')\n    assert is_valid_address_for_coinsymbol(b58_address=address_to_fund, coin_symbol=coin_symbol)\n    assert satoshis > 0\n    assert api_key, 'api_key required'\n    url = make_url(coin_symbol, 'faucet')\n    data = {\n            'address': address_to_fund,\n            'amount': satoshis,\n            }\n    params = {'token': api_key}\n    r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)\n    return get_valid_json(r)",
    "docstring": "Send yourself test coins on the bitcoin or blockcypher testnet\n\n    You can see your balance info at:\n    - https://live.blockcypher.com/bcy/ for BCY\n    - https://live.blockcypher.com/btc-testnet/ for BTC Testnet"
  },
  {
    "code": "def is_enabled():\n    cmd = 'service -e'\n    services = __salt__['cmd.run'](cmd, python_shell=False)\n    for service in services.split('\\\\n'):\n        if re.search('jail', service):\n            return True\n    return False",
    "docstring": "See if jail service is actually enabled on boot\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' jail.is_enabled <jail name>"
  },
  {
    "code": "def delete(self):\n        self.__dmlquery__(self.__class__, self,\n                          batch=self._batch,\n                          timestamp=self._timestamp,\n                          consistency=self.__consistency__,\n                          timeout=self._timeout).delete()",
    "docstring": "Deletes this instance"
  },
  {
    "code": "def mark_all_as_read(self, recipient=None):\n        qset = self.unread(True)\n        if recipient:\n            qset = qset.filter(recipient=recipient)\n        return qset.update(unread=False)",
    "docstring": "Mark as read any unread messages in the current queryset.\n\n        Optionally, filter these by recipient first."
  },
  {
    "code": "def trim_core(self):\n        for i in range(self.trim):\n            self.oracle.solve(assumptions=self.core)\n            new_core = self.oracle.get_core()\n            if len(new_core) == len(self.core):\n                break\n            self.core = new_core",
    "docstring": "This method trims a previously extracted unsatisfiable\n            core at most a given number of times. If a fixed point is\n            reached before that, the method returns."
  },
  {
    "code": "def url_to_text(self, url):\n        path, headers = urllib.request.urlretrieve(url)\n        return self.path_to_text(path)",
    "docstring": "Download PDF file and transform its document to string.\n\n        Args:\n            url:   PDF url.\n\n        Returns:\n            string."
  },
  {
    "code": "def batch_contains_deleted(self):\n        \"Check if current batch contains already deleted images.\"\n        if not self._duplicates: return False\n        imgs = [self._all_images[:self._batch_size][0][1], self._all_images[:self._batch_size][1][1]]\n        return any(img in self._deleted_fns for img in imgs)",
    "docstring": "Check if current batch contains already deleted images."
  },
  {
    "code": "def remove_forms(self, form_names):\n        for form in form_names:\n            try:\n                self.parentApp.removeForm(form)\n            except Exception as e:\n                pass\n        return",
    "docstring": "Remove all forms supplied"
  },
  {
    "code": "def remote_evb_cfgd_uneq_store(self, remote_evb_cfgd):\n        if remote_evb_cfgd != self.remote_evb_cfgd:\n            self.remote_evb_cfgd = remote_evb_cfgd\n            return True\n        return False",
    "docstring": "This saves the EVB cfg, if it is not the same as stored."
  },
  {
    "code": "def drop(manager: Manager, network_id: Optional[int], yes):\n    if network_id:\n        manager.drop_network_by_id(network_id)\n    elif yes or click.confirm('Drop all networks?'):\n        manager.drop_networks()",
    "docstring": "Drop a network by its identifier or drop all networks."
  },
  {
    "code": "def start_stress(self, stress_cmd):\n        with open(os.devnull, 'w') as dev_null:\n            try:\n                stress_proc = subprocess.Popen(stress_cmd, stdout=dev_null,\n                                               stderr=dev_null)\n                self.set_stress_process(psutil.Process(stress_proc.pid))\n            except OSError:\n                logging.debug(\"Unable to start stress\")",
    "docstring": "Starts a new stress process with a given cmd"
  },
  {
    "code": "def _serialize(self):\n        if self._defcode is None:\n            raise exceptions.UnboundResponse()\n        resp = self.response_class(request=self.req, status=self.code,\n                                   headerlist=self._headers.items())\n        if self.result:\n            resp.content_type = self.content_type\n            resp.body = self.serializer(self.result)\n        return resp",
    "docstring": "Serialize the ResponseObject.  Returns a webob `Response`\n        object."
  },
  {
    "code": "def unlock_kinetis(jlink):\n    if not jlink.connected():\n        raise ValueError('No target to unlock.')\n    method = UNLOCK_METHODS.get(jlink.tif, None)\n    if method is None:\n        raise NotImplementedError('Unsupported target interface for unlock.')\n    return method(jlink)",
    "docstring": "Unlock for Freescale Kinetis K40 or K60 device.\n\n    Args:\n      jlink (JLink): an instance of a J-Link that is connected to a target.\n\n    Returns:\n      ``True`` if the device was successfully unlocked, otherwise ``False``.\n\n    Raises:\n      ValueError: if the J-Link is not connected to a target."
  },
  {
    "code": "def create():\n    if request.method == \"POST\":\n        title = request.form[\"title\"]\n        body = request.form[\"body\"]\n        error = None\n        if not title:\n            error = \"Title is required.\"\n        if error is not None:\n            flash(error)\n        else:\n            db.session.add(Post(title=title, body=body, author=g.user))\n            db.session.commit()\n            return redirect(url_for(\"blog.index\"))\n    return render_template(\"blog/create.html\")",
    "docstring": "Create a new post for the current user."
  },
  {
    "code": "def position_for_index(self, index):\n        if not self.elements:\n            return 0\n        start = 0\n        end = int(len(self.elements) / 2)\n        slice_length = end - start\n        pivot_point = int(slice_length / 2)\n        pivot_index = self.elements[pivot_point * 2]\n        while slice_length > 1:\n            if pivot_index < index:\n                start = pivot_point\n            elif pivot_index > index:\n                end = pivot_point\n            else:\n                break\n            slice_length = end - start\n            pivot_point = start + int(slice_length / 2)\n            pivot_index = self.elements[pivot_point * 2]\n        if pivot_index == index:\n            return pivot_point * 2\n        elif pivot_index > index:\n            return pivot_point * 2\n        else:\n            return (pivot_point + 1) * 2",
    "docstring": "Calculates the position within the vector to insert a given index.\n\n        This is used internally by insert and upsert. If there are duplicate\n        indexes then the position is returned as if the value for that index\n        were to be updated, but it is the callers responsibility to check\n        whether there is a duplicate at that index"
  },
  {
    "code": "def network_traffic_ports(instance):\n    for key, obj in instance['objects'].items():\n        if ('type' in obj and obj['type'] == 'network-traffic' and\n                ('src_port' not in obj or 'dst_port' not in obj)):\n            yield JSONError(\"The Network Traffic object '%s' should contain \"\n                            \"both the 'src_port' and 'dst_port' properties.\"\n                            % key, instance['id'], 'network-traffic-ports')",
    "docstring": "Ensure network-traffic objects contain both src_port and dst_port."
  },
  {
    "code": "def resource_create(resource_id, resource_type, resource_options=None, cibfile=None):\n    return item_create(item='resource',\n                       item_id=resource_id,\n                       item_type=resource_type,\n                       extra_args=resource_options,\n                       cibfile=cibfile)",
    "docstring": "Create a resource via pcs command\n\n    resource_id\n        name for the resource\n    resource_type\n        resource type (f.e. ocf:heartbeat:IPaddr2 or VirtualIP)\n    resource_options\n        additional options for creating the resource\n    cibfile\n        use cibfile instead of the live CIB for manipulation\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' pcs.resource_create resource_id='galera' resource_type='ocf:heartbeat:galera' resource_options=\"['wsrep_cluster_address=gcomm://node1.example.org,node2.example.org,node3.example.org', '--master']\" cibfile='/tmp/cib_for_galera.cib'"
  },
  {
    "code": "def format_output(func):\n    return func\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        try:\n            response = func(*args, **kwargs)\n        except Exception as error:\n            print(colored(error, 'red'), file=sys.stderr)\n            sys.exit(1)\n        else:\n            print(response)\n            sys.exit(0)\n    return wrapper",
    "docstring": "Format output."
  },
  {
    "code": "def n_chunks(self):\n        return self._data_source.n_chunks(self.chunksize, stride=self.stride, skip=self.skip)",
    "docstring": "rough estimate of how many chunks will be processed"
  },
  {
    "code": "def do_batch(args):\n    if args.subcommand == 'list':\n        do_batch_list(args)\n    if args.subcommand == 'show':\n        do_batch_show(args)\n    if args.subcommand == 'status':\n        do_batch_status(args)\n    if args.subcommand == 'submit':\n        do_batch_submit(args)",
    "docstring": "Runs the batch list, batch show or batch status command, printing output\n    to the console\n\n        Args:\n            args: The parsed arguments sent to the command at runtime"
  },
  {
    "code": "def connect(self, listener, pass_signal=False):\n        info = listenerinfo(listener, pass_signal)\n        self._listeners.append(info)\n        _logger.debug(\"connect %r to %r\", str(listener), self._name)\n        if inspect.ismethod(listener):\n            listener_object = listener.__self__\n            if not hasattr(listener_object, \"__listeners__\"):\n                listener_object.__listeners__ = collections.defaultdict(list)\n            listener_object.__listeners__[listener].append(self)",
    "docstring": "Connect a new listener to this signal\n\n        :param listener:\n            The listener (callable) to add\n        :param pass_signal:\n            An optional argument that controls if the signal object is\n            explicitly passed to this listener when it is being fired.\n            If enabled, a ``signal=`` keyword argument is passed to the\n            listener function.\n        :returns:\n            None\n\n        The listener will be called whenever :meth:`fire()` or\n        :meth:`__call__()` are called.  The listener is appended to the list of\n        listeners. Duplicates are not checked and if a listener is added twice\n        it gets called twice."
  },
  {
    "code": "def split(expr, frac, seed=None):\n    if hasattr(expr, '_xflow_split'):\n        return expr._xflow_split(frac, seed=seed)\n    else:\n        return _split(expr, frac, seed=seed)",
    "docstring": "Split the current column into two column objects with certain ratio.\n\n    :param float frac: Split ratio\n\n    :return: two split DataFrame objects"
  },
  {
    "code": "def nla_for_each_attr(head, len_, rem):\n    pos = head\n    rem.value = len_\n    while nla_ok(pos, rem):\n        yield pos\n        pos = nla_next(pos, rem)",
    "docstring": "Iterate over a stream of attributes.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/attr.h#L262\n\n    Positional arguments:\n    head -- first nlattr with more in its bytearray payload (nlattr class instance).\n    len_ -- length of attribute stream (integer).\n    rem -- initialized to len, holds bytes currently remaining in stream (c_int).\n\n    Returns:\n    Generator yielding nlattr instances."
  },
  {
    "code": "def register(self, email, username, password, first_name, last_name, birthday=\"1974-11-20\", captcha_result=None):\n        self.username = username\n        self.password = password\n        register_message = sign_up.RegisterRequest(email, username, password, first_name, last_name, birthday, captcha_result,\n                                                   self.device_id_override, self.android_id_override)\n        log.info(\"[+] Sending sign up request (name: {} {}, email: {})...\".format(first_name, last_name, email))\n        return self._send_xmpp_element(register_message)",
    "docstring": "Sends a register request to sign up a new user to kik with the given details."
  },
  {
    "code": "def get(self, alias, target=None):\n        for target_part in reversed(list(self._get_targets(target))):\n            options = self._get(target_part, alias)\n            if options:\n                return options",
    "docstring": "Get a dictionary of aliased options.\n\n        :param alias: The name of the aliased options.\n        :param target: Get alias for this specific target (optional).\n\n        If no matching alias is found, returns ``None``."
  },
  {
    "code": "def footnotemap(self, cache=True):\n        if self.__footnotemap is not None and cache==True:\n            return self.__footnotemap\n        else:\n            x = self.xml(src='word/footnotes.xml')\n            d = Dict()\n            if x is None: return d\n            for footnote in x.root.xpath(\"w:footnote\", namespaces=self.NS):\n                id = footnote.get(\"{%(w)s}id\" % self.NS)\n                typ = footnote.get(\"{%(w)s}type\" % self.NS)\n                d[id] = Dict(id=id, type=typ, elem=footnote)\n            if cache==True: self.__footnotemap = d\n            return d",
    "docstring": "return the footnotes from the docx, keyed to string id."
  },
  {
    "code": "def nth(lst, n):\n    expect_type(n, (String, Number), unit=None)\n    if isinstance(n, String):\n        if n.value.lower() == 'first':\n            i = 0\n        elif n.value.lower() == 'last':\n            i = -1\n        else:\n            raise ValueError(\"Invalid index %r\" % (n,))\n    else:\n        i = n.to_python_index(len(lst), circular=True)\n    return lst[i]",
    "docstring": "Return the nth item in the list."
  },
  {
    "code": "def write(self, string):\n        self.make_dir()\n        with open(self.path, \"w\") as f:\n            if not string.endswith(\"\\n\"):\n                return f.write(string + \"\\n\")\n            else:\n                return f.write(string)",
    "docstring": "Write string to file."
  },
  {
    "code": "def save_pkl(self, filename):\n        with open(filename, 'wb') as fout:\n            pickle.dump(self, fout)",
    "docstring": "Pickles TransitSignal."
  },
  {
    "code": "def validateDayOfWeek(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, dayNames=ENGLISH_DAYS_OF_WEEK, excMsg=None):\n    try:\n        return validateMonth(value, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes, monthNames=ENGLISH_DAYS_OF_WEEK)\n    except:\n        _raiseValidationException(_('%r is not a day of the week') % (_errstr(value)), excMsg)",
    "docstring": "Raises ValidationException if value is not a day of the week, such as 'Mon' or 'Friday'.\n    Returns the titlecased day of the week.\n\n    * value (str): The value being validated as a day of the week.\n    * blank (bool):  If True, a blank string will be accepted. Defaults to False.\n    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.\n    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.\n    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.\n    * dayNames (Mapping): A mapping of uppercase day abbreviations to day names, i.e. {'SUN': 'Sunday', ...} The default provides English day names.\n    * excMsg (str): A custom message to use in the raised ValidationException.\n\n    >>> import pysimplevalidate as pysv\n    >>> pysv.validateDayOfWeek('mon')\n    'Monday'\n    >>> pysv.validateDayOfWeek('THURSday')\n    'Thursday'"
  },
  {
    "code": "def set_y(self, y):\n        \"Set y position and reset x\"\n        self.x=self.l_margin\n        if(y>=0):\n            self.y=y\n        else:\n            self.y=self.h+y",
    "docstring": "Set y position and reset x"
  },
  {
    "code": "def _write_cpr(self, f, cType, parameter) -> int:\n        f.seek(0, 2)\n        byte_loc = f.tell()\n        block_size = CDF.CPR_BASE_SIZE64 + 4\n        section_type = CDF.CPR_\n        rfuA = 0\n        pCount = 1\n        cpr = bytearray(block_size)\n        cpr[0:8] = struct.pack('>q', block_size)\n        cpr[8:12] = struct.pack('>i', section_type)\n        cpr[12:16] = struct.pack('>i', cType)\n        cpr[16:20] = struct.pack('>i', rfuA)\n        cpr[20:24] = struct.pack('>i', pCount)\n        cpr[24:28] = struct.pack('>i', parameter)\n        f.write(cpr)\n        return byte_loc",
    "docstring": "Write compression info to the end of the file in a CPR."
  },
  {
    "code": "def leaders(self, current_page, **options):\n        return self.leaders_in(self.leaderboard_name, current_page, **options)",
    "docstring": "Retrieve a page of leaders from the leaderboard.\n\n        @param current_page [int] Page to retrieve from the leaderboard.\n        @param options [Hash] Options to be used when retrieving the page from the leaderboard.\n        @return a page of leaders from the leaderboard."
  },
  {
    "code": "def soviet_checksum(code):\n    def sum_digits(code, offset=1):\n        total = 0\n        for digit, index in zip(code[:7], count(offset)):\n            total += int(digit) * index\n        summed = (total / 11 * 11)\n        return total - summed\n    check = sum_digits(code, 1)\n    if check == 10:\n        check = sum_digits(code, 3)\n        if check == 10:\n            return code + '0'\n    return code + str(check)",
    "docstring": "Courtesy of Sir Vlad Lavrov."
  },
  {
    "code": "def _instance_parser(self, plugins):\n        plugins = util.return_list(plugins)\n        for instance in plugins:\n            if inspect.isclass(instance):\n                self._handle_class_instance(instance)\n            else:\n                self._handle_object_instance(instance)",
    "docstring": "internal method to parse instances of plugins.\n\n        Determines if each class is a class instance or\n        object instance and calls the appropiate handler\n        method."
  },
  {
    "code": "def get_connect_redirect_url(self, request, socialaccount):\n        assert request.user.is_authenticated\n        url = reverse('socialaccount_connections')\n        return url",
    "docstring": "Returns the default URL to redirect to after successfully\n        connecting a social account."
  },
  {
    "code": "def _consolidate_classpath(self, targets, classpath_products):\n    entries_map = defaultdict(list)\n    for (cp, target) in classpath_products.get_product_target_mappings_for_targets(targets, True):\n      entries_map[target].append(cp)\n    with self.invalidated(targets=targets, invalidate_dependents=True) as invalidation:\n      for vt in invalidation.all_vts:\n        entries = entries_map.get(vt.target, [])\n        for index, (conf, entry) in enumerate(entries):\n          if ClasspathUtil.is_dir(entry.path):\n            jarpath = os.path.join(vt.results_dir, 'output-{}.jar'.format(index))\n            if not vt.valid:\n              with self.open_jar(jarpath, overwrite=True, compressed=False) as jar:\n                jar.write(entry.path)\n            classpath_products.remove_for_target(vt.target, [(conf, entry.path)])\n            classpath_products.add_for_target(vt.target, [(conf, jarpath)])",
    "docstring": "Convert loose directories in classpath_products into jars."
  },
  {
    "code": "def reportProgress(self, state, action, text=None, tick=None):\n        if self.progressFunc is not None:\n            self.progressFunc(state=state, action=action, text=text, tick=tick)",
    "docstring": "If we want to keep other code updated about our progress.\n\n            state:      'prep'      reading sources\n                        'generate'  making instances\n                        'done'      wrapping up\n                        'error'     reporting a problem\n\n            action:     'start'     begin generating\n                        'stop'      end generating\n                        'source'    which ufo we're reading\n\n            text:       <file.ufo>  ufoname (for instance)\n            tick:       a float between 0 and 1 indicating progress."
  },
  {
    "code": "def _always_running_service(name):\n    service_info = show(name)\n    try:\n        keep_alive = service_info['plist']['KeepAlive']\n    except KeyError:\n        return False\n    if isinstance(keep_alive, dict):\n        for _file, value in six.iteritems(keep_alive.get('PathState', {})):\n            if value is True and os.path.exists(_file):\n                return True\n            elif value is False and not os.path.exists(_file):\n                return True\n    if keep_alive is True:\n        return True\n    return False",
    "docstring": "Check if the service should always be running based on the KeepAlive Key\n    in the service plist.\n\n    :param str name: Service label, file name, or full path\n\n    :return: True if the KeepAlive key is set to True, False if set to False or\n        not set in the plist at all.\n\n    :rtype: bool\n\n    .. versionadded:: 2019.2.0"
  },
  {
    "code": "def total_area_per_neurite(neurites, neurite_type=NeuriteType.all):\n    return [neurite.area for neurite in iter_neurites(neurites, filt=is_type(neurite_type))]",
    "docstring": "Surface area in a collection of neurites.\n\n    The area is defined as the sum of the area of the sections."
  },
  {
    "code": "def dragDrop(self, target, target2=None, modifiers=\"\"):\n        if modifiers != \"\":\n            keyboard.keyDown(modifiers)\n        if target2 is None:\n            dragFrom = self._lastMatch\n            dragTo = target\n        else:\n            dragFrom = target\n            dragTo = target2\n        self.drag(dragFrom)\n        time.sleep(Settings.DelayBeforeDrag)\n        self.dropAt(dragTo)\n        if modifiers != \"\":\n            keyboard.keyUp(modifiers)",
    "docstring": "Performs a dragDrop operation.\n\n        Holds down the mouse button on ``dragFrom``, moves the mouse to ``dragTo``, and releases\n        the mouse button.\n\n        ``modifiers`` may be a typeKeys() compatible string. The specified keys will be held\n        during the drag-drop operation."
  },
  {
    "code": "def parse_json(raw_data):\n    orig_data = raw_data\n    data = filter_leading_non_json_lines(raw_data)\n    try:\n        return json.loads(data)\n    except:\n        results = {}\n        try:\n            tokens = shlex.split(data)\n        except:\n            print \"failed to parse json: \"+ data\n            raise\n        for t in tokens:\n            if t.find(\"=\") == -1:\n                raise errors.AnsibleError(\"failed to parse: %s\" % orig_data)\n            (key,value) = t.split(\"=\", 1)\n            if key == 'changed' or 'failed':\n                if value.lower() in [ 'true', '1' ]:\n                    value = True\n                elif value.lower() in [ 'false', '0' ]:\n                    value = False\n            if key == 'rc':\n                value = int(value)\n            results[key] = value\n        if len(results.keys()) == 0:\n            return { \"failed\" : True, \"parsed\" : False, \"msg\" : orig_data }\n        return results",
    "docstring": "this version for module return data only"
  },
  {
    "code": "def taskotron_changed_outcome(config, message):\n    if not taskotron_result_new(config, message):\n        return False\n    outcome = message['msg']['result'].get('outcome')\n    prev_outcome = message['msg']['result'].get('prev_outcome')\n    return prev_outcome is not None and outcome != prev_outcome",
    "docstring": "Taskotron task outcome changed\n\n    With this rule, you can limit messages to only those task results\n    with changed outcomes. This is useful when an object (a build,\n    an update, etc) gets retested and either the object itself or the\n    environment changes and the task outcome is now different (e.g.\n    FAILED -> PASSED)."
  },
  {
    "code": "def is_not_blocked(self, item: str) -> bool:\n        assert item is not None\n        item = self._encode_item(item)\n        connection = self.__get_connection()\n        key = self.__redis_conf['blacklist_template'].format(item)\n        value = connection.get(key)\n        if value is None:\n            BlackRed.__release_connection(connection)\n            return True\n        if self.__redis_conf['blacklist_refresh_ttl']:\n            connection.expire(key, self.__redis_conf['blacklist_ttl'])\n        BlackRed.__release_connection(connection)\n        return False",
    "docstring": "Check if an item is _not_ already on the blacklist\n\n        :param str item: The item to check\n        :return: True, when the item is _not_ on the blacklist\n        :rtype: bool"
  },
  {
    "code": "def _finished_callback(self, batch_fut, todo):\n    self._running.remove(batch_fut)\n    err = batch_fut.get_exception()\n    if err is not None:\n      tb = batch_fut.get_traceback()\n      for (fut, _) in todo:\n        if not fut.done():\n          fut.set_exception(err, tb)",
    "docstring": "Passes exception along.\n\n    Args:\n      batch_fut: the batch future returned by running todo_tasklet.\n      todo: (fut, option) pair. fut is the future return by each add() call.\n\n    If the batch fut was successful, it has already called fut.set_result()\n    on other individual futs. This method only handles when the batch fut\n    encountered an exception."
  },
  {
    "code": "def load_config_vars(target_config, source_config):\n    for attr in dir(source_config):\n        if attr.startswith('_'):\n            continue\n        val = getattr(source_config, attr)\n        if val is not None:\n            setattr(target_config, attr, val)",
    "docstring": "Loads all attributes from source config into target config\n\n    @type target_config: TestRunConfigManager\n    @param target_config: Config to dump variables into\n    @type source_config: TestRunConfigManager\n    @param source_config: The other config\n    @return: True"
  },
  {
    "code": "def list_policies(self):\n        api_path = '/v1/sys/policy'\n        response = self._adapter.get(\n            url=api_path,\n        )\n        return response.json()",
    "docstring": "List all configured policies.\n\n        Supported methods:\n            GET: /sys/policy. Produces: 200 application/json\n\n        :return: The JSON response of the request.\n        :rtype: dict"
  },
  {
    "code": "def remove_note(self, note, octave=-1):\n        res = []\n        for x in self.notes:\n            if type(note) == str:\n                if x.name != note:\n                    res.append(x)\n                else:\n                    if x.octave != octave and octave != -1:\n                        res.append(x)\n            else:\n                if x != note:\n                    res.append(x)\n        self.notes = res\n        return res",
    "docstring": "Remove note from container.\n\n        The note can either be a Note object or a string representing the\n        note's name. If no specific octave is given, the note gets removed\n        in every octave."
  },
  {
    "code": "async def get_googlecast_settings(self) -> List[Setting]:\n        return [\n            Setting.make(**x)\n            for x in await self.services[\"system\"][\"getWuTangInfo\"]({})\n        ]",
    "docstring": "Get Googlecast settings."
  },
  {
    "code": "def handle_command(editor, input_string):\n    m = COMMAND_GRAMMAR.match(input_string)\n    if m is None:\n        return\n    variables = m.variables()\n    command = variables.get('command')\n    go_to_line = variables.get('go_to_line')\n    shell_command = variables.get('shell_command')\n    if go_to_line is not None:\n        _go_to_line(editor, go_to_line)\n    elif shell_command is not None:\n        editor.application.run_system_command(shell_command)\n    elif has_command_handler(command):\n        call_command_handler(command, editor, variables)\n    else:\n        editor.show_message('Not an editor command: %s' % input_string)\n        return\n    editor.sync_with_prompt_toolkit()",
    "docstring": "Handle commands entered on the Vi command line."
  },
  {
    "code": "def data_directory():\n    package_directory = os.path.abspath(os.path.dirname(__file__))\n    return os.path.join(package_directory, \"data\")",
    "docstring": "Return the absolute path to the directory containing the package data."
  },
  {
    "code": "def offer_pdf(self, offer_id):\n        return self._create_get_request(resource=OFFERS, billomat_id=offer_id, command=PDF)",
    "docstring": "Opens a pdf of an offer\n\n        :param offer_id: the offer id\n        :return: dict"
  },
  {
    "code": "def get_site_amplification(self, C, sites):\n        ampl = np.zeros(sites.vs30.shape)\n        ampl[sites.vs30measured] = (C[\"d0_obs\"] + C[\"d1_obs\"] *\n                                    np.log(sites.vs30[sites.vs30measured]))\n        idx = np.logical_not(sites.vs30measured)\n        ampl[idx] = (C[\"d0_inf\"] + C[\"d1_inf\"] * np.log(sites.vs30[idx]))\n        return ampl",
    "docstring": "Returns the linear site amplification term depending on whether the\n        Vs30 is observed of inferred"
  },
  {
    "code": "def handle_overrides(graph, overrides):\n    for key in overrides:\n        levels = key.split('.')\n        part = graph\n        for lvl in levels[:-1]:\n            try:\n                part = part[lvl]\n            except KeyError:\n                raise KeyError(\"'%s' override failed at '%s'\", (key, lvl))\n        try:\n            part[levels[-1]] = overrides[key]\n        except KeyError:\n            raise KeyError(\"'%s' override failed at '%s'\", (key, levels[-1]))",
    "docstring": "Handle any overrides for this model configuration.\n\n    Parameters\n    ----------\n    graph : dict or object\n        A dictionary (or an ObjectProxy) containing the object graph\n        loaded from a YAML file.\n    overrides : dict\n        A dictionary containing overrides to apply. The location of\n        the override is specified in the key as a dot-delimited path\n        to the desired parameter, e.g. \"model.corruptor.corruption_level\"."
  },
  {
    "code": "def summary_permutation(context_counts,\n                        context_to_mut,\n                        seq_context,\n                        gene_seq,\n                        score_dir,\n                        num_permutations=10000,\n                        min_frac=0.0,\n                        min_recur=2,\n                        drop_silent=False):\n    mycontexts = context_counts.index.tolist()\n    somatic_base = [base\n                    for one_context in mycontexts\n                    for base in context_to_mut[one_context]]\n    tmp_contxt_pos = seq_context.random_pos(context_counts.iteritems(),\n                                            num_permutations)\n    tmp_mut_pos = np.hstack(pos_array for base, pos_array in tmp_contxt_pos)\n    gene_name = gene_seq.bed.gene_name\n    gene_len = gene_seq.bed.cds_len\n    summary_info_list = []\n    for i, row in enumerate(tmp_mut_pos):\n        tmp_mut_info = mc.get_aa_mut_info(row,\n                                          somatic_base,\n                                          gene_seq)\n        tmp_summary = cutils.calc_summary_info(tmp_mut_info['Reference AA'],\n                                               tmp_mut_info['Somatic AA'],\n                                               tmp_mut_info['Codon Pos'],\n                                               gene_name,\n                                               score_dir,\n                                               min_frac=min_frac,\n                                               min_recur=min_recur)\n        if drop_silent:\n            tmp_summary[1] = 0\n        summary_info_list.append([gene_name, i+1, gene_len]+tmp_summary)\n    return summary_info_list",
    "docstring": "Performs null-permutations and summarizes the results as features over\n    the gene.\n\n    Parameters\n    ----------\n    context_counts : pd.Series\n        number of mutations for each context\n    context_to_mut : dict\n        dictionary mapping nucleotide context to a list of observed\n        somatic base changes.\n    seq_context : SequenceContext\n        Sequence context for the entire gene sequence (regardless\n        of where mutations occur). The nucleotide contexts are\n        identified at positions along the gene.\n    gene_seq : GeneSequence\n        Sequence of gene of interest\n    num_permutations : int, default: 10000\n        number of permutations to create for null\n    drop_silent : bool, default=False\n        Flage on whether to drop all silent mutations. Some data sources\n        do not report silent mutations, and the simulations should match this.\n\n    Returns\n    -------\n    summary_info_list : list of lists\n        list of non-silent and silent mutation counts under the null along\n        with information on recurrent missense counts and missense positional\n        entropy."
  },
  {
    "code": "def add_role(ctx, role):\n    if role is None:\n        log('Specify the role with --role')\n        return\n    if ctx.obj['username'] is None:\n        log('Specify the username with --username')\n        return\n    change_user = ctx.obj['db'].objectmodels['user'].find_one({\n        'name': ctx.obj['username']\n    })\n    if role not in change_user.roles:\n        change_user.roles.append(role)\n        change_user.save()\n        log('Done')\n    else:\n        log('User already has that role!', lvl=warn)",
    "docstring": "Grant a role to an existing user"
  },
  {
    "code": "def group(self, indent: int = DEFAULT_INDENT, add_line: bool = True) -> _TextGroup:\n        return _TextGroup(self, indent, add_line)",
    "docstring": "Returns a context manager which adds an indentation before each line.\n\n        :param indent: Number of spaces to print.\n        :param add_line: If True, a new line will be printed after the group.\n        :return: A TextGroup context manager."
  },
  {
    "code": "def estimateAbsoluteMagnitude(spectralType):\n    from .astroclasses import SpectralType\n    specType = SpectralType(spectralType)\n    if specType.classLetter == '':\n        return np.nan\n    elif specType.classNumber == '':\n        specType.classNumber = 5\n    if specType.lumType == '':\n        specType.lumType = 'V'\n    LNum = LClassRef[specType.lumType]\n    classNum = specType.classNumber\n    classLet = specType.classLetter\n    try:\n        return absMagDict[classLet][classNum][LNum]\n    except (KeyError, IndexError):\n        try:\n            classLookup = absMagDict[classLet]\n            values = np.array(list(classLookup.values()))[\n                :, LNum]\n            return np.interp(classNum, list(classLookup.keys()), values)\n        except (KeyError, ValueError):\n            return np.nan",
    "docstring": "Uses the spectral type to lookup an approximate absolute magnitude for\n    the star."
  },
  {
    "code": "def revoke(self, target, **prefs):\n        hash_algo = prefs.pop('hash', None)\n        if isinstance(target, PGPUID):\n            sig_type = SignatureType.CertRevocation\n        elif isinstance(target, PGPKey):\n            if target.is_primary:\n                sig_type = SignatureType.KeyRevocation\n            else:\n                sig_type = SignatureType.SubkeyRevocation\n        else:\n            raise TypeError\n        sig = PGPSignature.new(sig_type, self.key_algorithm, hash_algo, self.fingerprint.keyid)\n        reason = prefs.pop('reason', RevocationReason.NotSpecified)\n        comment = prefs.pop('comment', \"\")\n        sig._signature.subpackets.addnew('ReasonForRevocation', hashed=True, code=reason, string=comment)\n        return self._sign(target, sig, **prefs)",
    "docstring": "Revoke a key, a subkey, or all current certification signatures of a User ID that were generated by this key so far.\n\n        :param target: The key to revoke\n        :type target: :py:obj:`PGPKey`, :py:obj:`PGPUID`\n        :raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked\n        :raises: :py:exc:`~pgpy.errors.PGPError` if the key is public\n        :returns: :py:obj:`PGPSignature`\n\n        In addition to the optional keyword arguments accepted by :py:meth:`PGPKey.sign`, the following optional\n        keyword arguments can be used with :py:meth:`PGPKey.revoke`.\n\n        :keyword reason: Defaults to :py:obj:`constants.RevocationReason.NotSpecified`\n        :type reason: One of :py:obj:`constants.RevocationReason`.\n        :keyword comment: Defaults to an empty string.\n        :type comment: ``str``"
  },
  {
    "code": "def execute_and_commit(*args, **kwargs):\n        db, cursor = CoyoteDb.execute(*args, **kwargs)\n        db.commit()\n        return cursor",
    "docstring": "Executes and commits the sql statement\n\n        @return: None"
  },
  {
    "code": "def get_archiver(self, kind):\n    archivers = {\n        'tar': TarArchiver,\n        'tbz2': Tbz2Archiver,\n        'tgz': TgzArchiver,\n        'zip': ZipArchiver,\n    }\n    return archivers[kind]()",
    "docstring": "Returns instance of archiver class specific to given kind\n\n    :param kind: archive kind"
  },
  {
    "code": "def checkscript(self, content):\n        if \"VERSION\" not in self.__capabilities:\n            raise NotImplementedError(\n                \"server does not support CHECKSCRIPT command\")\n        content = tools.to_bytes(content)\n        content = tools.to_bytes(\"{%d+}\" % len(content)) + CRLF + content\n        code, data = self.__send_command(\"CHECKSCRIPT\", [content])\n        if code == \"OK\":\n            return True\n        return False",
    "docstring": "Check whether a script is valid\n\n        See MANAGESIEVE specifications, section 2.12\n\n        :param name: script's content\n        :rtype: boolean"
  },
  {
    "code": "def decompose(miz_file: Path, output_folder: Path):\n        mission_folder, assets_folder = NewMiz._get_subfolders(output_folder)\n        NewMiz._wipe_folders(mission_folder, assets_folder)\n        LOGGER.info('unzipping mission file')\n        with Miz(miz_file) as miz:\n            version = miz.mission.d['version']\n            LOGGER.debug(f'mission version: \"%s\"', version)\n            LOGGER.info('copying assets to: \"%s\"', assets_folder)\n            ignore = shutil.ignore_patterns('mission')\n            shutil.copytree(str(miz.temp_dir), str(assets_folder), ignore=ignore)\n            NewMiz._reorder_warehouses(assets_folder)\n            LOGGER.info('decomposing mission table into: \"%s\" (this will take a while)', mission_folder)\n            NewMiz._decompose_dict(miz.mission.d, 'base_info', mission_folder, version, miz)",
    "docstring": "Decompose this Miz into json\n\n        Args:\n            output_folder: folder to output the json structure as a Path\n            miz_file: MIZ file path as a Path"
  },
  {
    "code": "def from_val(val_schema):\n    definition = getattr(val_schema, \"definition\", val_schema) if isinstance(\n        val_schema, BaseSchema) else val_schema\n    if isinstance(definition, dict):\n        return _dict_to_teleport(definition)\n    if isinstance(definition, list):\n        if len(definition) == 1:\n            return {\"Array\": from_val(definition[0])}\n    if definition in VAL_PRIMITIVES:\n        return VAL_PRIMITIVES[definition]\n    raise SerializationError(\n        \"Serializing %r not (yet) supported.\" % definition)",
    "docstring": "Serialize a val schema to teleport."
  },
  {
    "code": "def deserialize_encryption_context(serialized_encryption_context):\n    if len(serialized_encryption_context) > aws_encryption_sdk.internal.defaults.MAX_BYTE_ARRAY_SIZE:\n        raise SerializationError(\"Serialized context is too long.\")\n    if serialized_encryption_context == b\"\":\n        _LOGGER.debug(\"No encryption context data found\")\n        return {}\n    deserialized_size = 0\n    encryption_context = {}\n    dict_size, deserialized_size = read_short(source=serialized_encryption_context, offset=deserialized_size)\n    _LOGGER.debug(\"Found %d keys\", dict_size)\n    for _ in range(dict_size):\n        key_size, deserialized_size = read_short(source=serialized_encryption_context, offset=deserialized_size)\n        key, deserialized_size = read_string(\n            source=serialized_encryption_context, offset=deserialized_size, length=key_size\n        )\n        value_size, deserialized_size = read_short(source=serialized_encryption_context, offset=deserialized_size)\n        value, deserialized_size = read_string(\n            source=serialized_encryption_context, offset=deserialized_size, length=value_size\n        )\n        if key in encryption_context:\n            raise SerializationError(\"Duplicate key in serialized context.\")\n        encryption_context[key] = value\n    if deserialized_size != len(serialized_encryption_context):\n        raise SerializationError(\"Formatting error: Extra data in serialized context.\")\n    return encryption_context",
    "docstring": "Deserializes the contents of a byte string into a dictionary.\n\n    :param bytes serialized_encryption_context: Source byte string containing serialized dictionary\n    :returns: Deserialized encryption context\n    :rtype: dict\n    :raises SerializationError: if serialized encryption context is too large\n    :raises SerializationError: if duplicate key found in serialized encryption context\n    :raises SerializationError: if malformed data found in serialized encryption context"
  },
  {
    "code": "def is_taps_aff(self):\n        request = requests.get('https://www.taps-aff.co.uk/api/%s' % self.location)\n        if request.status_code == 200:\n            try:\n                taps = request.json()['taps']['status']\n                if taps == 'aff':\n                    return True\n                elif taps == 'oan':\n                    return False\n                else:\n                    raise RuntimeError(\"Unexpected taps value: %s\" % taps)\n            except ValueError:\n                raise RuntimeError(\"Unexpected response from service\")\n        else:\n            raise IOError(\"Failure downloading from Api\")",
    "docstring": "Returns True if taps aff for this location"
  },
  {
    "code": "def checkAndCreate(self, key, payload,\n                       hostgroupConf,\n                       hostgroupParent,\n                       puppetClassesId):\n        if key not in self:\n            self[key] = payload\n        oid = self[key]['id']\n        if not oid:\n            return False\n        if 'classes' in hostgroupConf.keys():\n            classList = list()\n            for c in hostgroupConf['classes']:\n                classList.append(puppetClassesId[c])\n            if not self[key].checkAndCreateClasses(classList):\n                print(\"Failed in classes\")\n                return False\n        if 'params' in hostgroupConf.keys():\n            if not self[key].checkAndCreateParams(hostgroupConf['params']):\n                print(\"Failed in params\")\n                return False\n        return oid",
    "docstring": "Function checkAndCreate\n        check And Create procedure for an hostgroup\n        - check the hostgroup is not existing\n        - create the hostgroup\n        - Add puppet classes from puppetClassesId\n        - Add params from hostgroupConf\n\n        @param key: The hostgroup name or ID\n        @param payload: The description of the hostgroup\n        @param hostgroupConf: The configuration of the host group from the\n                              foreman.conf\n        @param hostgroupParent: The id of the parent hostgroup\n        @param puppetClassesId: The dict of puppet classes ids in foreman\n        @return RETURN: The ItemHostsGroup object of an host"
  },
  {
    "code": "def instance(*args, **kwargs):\n        if not hasattr(Config, \"_instance\") or Config._instance is None:\n            Config._instance = Config(*args, **kwargs)\n        return Config._instance",
    "docstring": "Singleton to return only one instance of Config.\n\n        :returns: instance of Config"
  },
  {
    "code": "def deploy_ext(self):\n        if self.mods.get('file'):\n            self.shell.send(\n                self.mods['file'],\n                os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),\n            )\n        return True",
    "docstring": "Deploy the ext_mods tarball"
  },
  {
    "code": "def in_to_out(self, in_path, out_path=None):\n        if is_same_file(in_path, out_path):\n            logger.debug(\n                \"in path and out path are the same file. writing to temp \"\n                \"file and then replacing in path with the temp file.\")\n            out_path = None\n        logger.debug(f\"opening source file: {in_path}\")\n        with open(in_path) as infile:\n            obj = self.object_representer.load(infile)\n        if out_path:\n            logger.debug(\n                f\"opening destination file for writing: {out_path}\")\n            ensure_dir(out_path)\n            with open(out_path, 'w') as outfile:\n                self.object_representer.dump(outfile, self.formatter(obj))\n            return\n        else:\n            logger.debug(\"opening temp file for writing...\")\n            with NamedTemporaryFile(mode='w+t',\n                                    dir=os.path.dirname(in_path),\n                                    delete=False) as outfile:\n                self.object_representer.dump(outfile, self.formatter(obj))\n            logger.debug(f\"moving temp file to: {in_path}\")\n            move_temp_file(outfile.name, infile.name)",
    "docstring": "Load file into object, formats, writes object to out.\n\n        If in_path and out_path point to the same thing it will in-place edit\n        and overwrite the in path. Even easier, if you do want to edit a file\n        in place, don't specify out_path, or set it to None.\n\n        Args:\n            in_path: str or path-like. Must refer to a single existing file.\n            out_path: str or path-like. Must refer to a single destination file\n                      location. will create directory structure if it doesn't\n                      exist.\n                      If out_path is not specified or None, will in-place edit\n                      and overwrite the in-files.\n\n        Returns:\n            None."
  },
  {
    "code": "def get_meta_references(self, datas):\n        rule = datas.get(RULE_META_REFERENCES, {})\n        if not rule:\n            msg = \"Manifest lacks of '.{}' or is empty\"\n            raise SerializerError(msg.format(RULE_META_REFERENCES))\n        else:\n            if rule.get('names', None):\n                names = rule.get('names').split(\" \")\n            elif rule.get('auto', None):\n                names = self.get_available_references(datas)\n            else:\n                msg = (\"'.{}' either require '--names' or '--auto' variable \"\n                       \"to be defined\")\n                raise SerializerError(msg.format(RULE_META_REFERENCES))\n        for item in names:\n            self.validate_rule_name(item)\n        return names",
    "docstring": "Get manifest enabled references declaration\n\n        This required declaration is readed from\n        ``styleguide-metas-references`` rule that require either a ``--names``\n        or ``--auto`` variable, each one define the mode to enable reference:\n\n        Manually\n            Using ``--names`` which define a list of names to enable, every\n            other non enabled rule will be ignored.\n\n            Section name (and so Reference name also) must not contains special\n            character nor ``-`` so they still be valid variable name for almost\n            any languages. For word separator inside name, use ``_``.\n        Automatic\n            Using ``--auto`` variable every reference rules will be enabled.\n            The value of this variable is not important since it is not empty.\n\n        If both of these variables are defined, the manual enable mode is used.\n\n        Arguments:\n            datas (dict): Data where to search for meta references declaration.\n                This is commonly the fully parsed manifest.\n\n        Returns:\n            list: A list of reference names."
  },
  {
    "code": "def _pretrain_layer_and_gen_feed(self, layer_obj, set_params_func,\n                                     train_set, validation_set, graph):\n        layer_obj.fit(train_set, train_set,\n                      validation_set, validation_set, graph=graph)\n        with graph.as_default():\n            set_params_func(layer_obj, graph)\n            next_train = layer_obj.transform(train_set, graph=graph)\n            if validation_set is not None:\n                next_valid = layer_obj.transform(validation_set, graph=graph)\n            else:\n                next_valid = None\n        return next_train, next_valid",
    "docstring": "Pretrain a single autoencoder and encode the data for the next layer.\n\n        :param layer_obj: layer model\n        :param set_params_func: function used to set the parameters after\n            pretraining\n        :param train_set: training set\n        :param validation_set: validation set\n        :param graph: tf object for the rbm\n        :return: encoded train data, encoded validation data"
  },
  {
    "code": "async def release_key(self, key, chat=None, user=None):\n        if not self.storage.has_bucket():\n            raise RuntimeError('This storage does not provide Leaky Bucket')\n        if user is None and chat is None:\n            user = types.User.get_current()\n            chat = types.Chat.get_current()\n        bucket = await self.storage.get_bucket(chat=chat, user=user)\n        if bucket and key in bucket:\n            del bucket['key']\n            await self.storage.set_bucket(chat=chat, user=user, bucket=bucket)\n            return True\n        return False",
    "docstring": "Release blocked key\n\n        :param key:\n        :param chat:\n        :param user:\n        :return:"
  },
  {
    "code": "def _get_cursor(self):\n        _options = self._get_options()\n        conn = MySQLdb.connect(host=_options['host'],\n                               user=_options['user'],\n                               passwd=_options['pass'],\n                               db=_options['db'], port=_options['port'],\n                               ssl=_options['ssl'])\n        cursor = conn.cursor()\n        try:\n            yield cursor\n        except MySQLdb.DatabaseError as err:\n            log.exception('Error in ext_pillar MySQL: %s', err.args)\n        finally:\n            conn.close()",
    "docstring": "Yield a MySQL cursor"
  },
  {
    "code": "def titles2marc(self, key, values):\n    first, rest = values[0], values[1:]\n    self.setdefault('245', []).append({\n        'a': first.get('title'),\n        'b': first.get('subtitle'),\n        '9': first.get('source'),\n    })\n    return [\n        {\n            'a': value.get('title'),\n            'b': value.get('subtitle'),\n            '9': value.get('source'),\n        } for value in rest\n    ]",
    "docstring": "Populate the ``246`` MARC field.\n\n    Also populates the ``245`` MARC field through side effects."
  },
  {
    "code": "def complete_pool_members(arg):\n    res = []\n    for member in Prefix.list({ 'pool_id': pool.id }):\n        res.append(member.prefix)\n    return _complete_string(arg, res)",
    "docstring": "Complete member prefixes of pool"
  },
  {
    "code": "def main():\n    command = Command.lookup(args.get(0))\n    if len(args) == 0 or args.contains(('-h', '--help', 'help')):\n        display_info(args)\n        sys.exit(1)\n    elif args.contains(('-v', '--version')):\n        display_version()\n        sys.exit(1)\n    elif command:\n        arg = args.get(0)\n        args.remove(arg)\n        command.__call__(command, args)\n        sys.exit()\n    else:\n        show_error(colored.red('Error! Unknown command \\'{0}\\'.\\n'\n                               .format(args.get(0))))\n        display_info(args)\n        sys.exit(1)",
    "docstring": "Primary Tarbell command dispatch."
  },
  {
    "code": "def _ioctl(self, func, arg):\n        if self._fd is None:\n            raise WatchdogError(\"Watchdog device is closed\")\n        if os.name != 'nt':\n            import fcntl\n            fcntl.ioctl(self._fd, func, arg, True)",
    "docstring": "Runs the specified ioctl on the underlying fd.\n\n        Raises WatchdogError if the device is closed.\n        Raises OSError or IOError (Python 2) when the ioctl fails."
  },
  {
    "code": "def get_state(self, sls, saltenv, cachedir=None):\n        if '.' in sls:\n            sls = sls.replace('.', '/')\n        sls_url = salt.utils.url.create(sls + '.sls')\n        init_url = salt.utils.url.create(sls + '/init.sls')\n        for path in [sls_url, init_url]:\n            dest = self.cache_file(path, saltenv, cachedir=cachedir)\n            if dest:\n                return {'source': path, 'dest': dest}\n        return {}",
    "docstring": "Get a state file from the master and store it in the local minion\n        cache; return the location of the file"
  },
  {
    "code": "def add_child(self, id_, child_id):\n        if bool(self._rls.get_relationships_by_genus_type_for_peers(id_, child_id, self._relationship_type).available()):\n            raise errors.AlreadyExists()\n        rfc = self._ras.get_relationship_form_for_create(id_, child_id, [])\n        rfc.set_display_name(str(id_) + ' to ' + str(child_id) + ' Parent-Child Relationship')\n        rfc.set_description(self._relationship_type.get_display_name().get_text() + ' relationship for parent: ' + str(id_) + ' and child: ' + str(child_id))\n        rfc.set_genus_type(self._relationship_type)\n        self._ras.create_relationship(rfc)",
    "docstring": "Adds a child to a ``Id``.\n\n        arg:    id (osid.id.Id): the ``Id`` of the node\n        arg:    child_id (osid.id.Id): the ``Id`` of the new child\n        raise:  AlreadyExists - ``child_id`` is already a child of\n                ``id``\n        raise:  NotFound - ``id`` or ``child_id`` not found\n        raise:  NullArgument - ``id`` or ``child_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def steal_page(self, page):\n        if page.doc == self:\n            return\n        self.fs.mkdir_p(self.path)\n        new_page = ImgPage(self, self.nb_pages)\n        logger.info(\"%s --> %s\" % (str(page), str(new_page)))\n        new_page._steal_content(page)",
    "docstring": "Steal a page from another document"
  },
  {
    "code": "def get_dataset_meta(label):\n    data_url = data_urls[label]\n    if type(data_url) == str:\n        data_url = [data_url]\n    if type(data_url) == list:\n        data_url.extend([None, None, None, None])\n        data_url = data_url[:4]\n        url, expected_hash, hash_path, relative_donwload_dir = data_url\n        if hash_path is None:\n            hash_path = label\n    return data_url, url, expected_hash, hash_path, relative_donwload_dir",
    "docstring": "Gives you metadata for dataset chosen via 'label' param\n\n    :param label: label = key in data_url dict (that big dict containing all possible datasets)\n    :return: tuple (data_url, url, expected_hash, hash_path, relative_download_dir)\n    relative_download_dir says where will be downloaded the file from url and eventually unzipped"
  },
  {
    "code": "async def async_delete_device(self, device_id: int) -> None:\n        device = self._devices[device_id]\n        response = await self._protocol.async_execute(\n            GetDeviceCommand(device.category, device.group_number, device.unit_number))\n        if isinstance(response, DeviceInfoResponse):\n            response = await self._protocol.async_execute(\n                DeleteDeviceCommand(device.category, response.index))\n            if isinstance(response, DeviceDeletedResponse):\n                self._devices._delete(device)\n                if self._on_device_deleted:\n                    try:\n                        self._on_device_deleted(self, device)\n                    except Exception:\n                        _LOGGER.error(\n                            \"Unhandled exception in on_device_deleted callback\",\n                            exc_info=True)\n        if isinstance(response, DeviceNotFoundResponse):\n            raise ValueError(\"Device to be deleted was not found\")",
    "docstring": "Delete an enrolled device.\n\n        :param device_id: unique identifier for the device to be deleted"
  },
  {
    "code": "def hbar_stack(self, stackers, **kw):\n        result = []\n        for kw in _double_stack(stackers, \"left\", \"right\", **kw):\n            result.append(self.hbar(**kw))\n        return result",
    "docstring": "Generate multiple ``HBar`` renderers for levels stacked left to right.\n\n        Args:\n            stackers (seq[str]) : a list of data source field names to stack\n                successively for ``left`` and ``right`` bar coordinates.\n\n                Additionally, the ``name`` of the renderer will be set to\n                the value of each successive stacker (this is useful with the\n                special hover variable ``$name``)\n\n        Any additional keyword arguments are passed to each call to ``hbar``.\n        If a keyword value is a list or tuple, then each call will get one\n        value from the sequence.\n\n        Returns:\n            list[GlyphRenderer]\n\n        Examples:\n\n            Assuming a ``ColumnDataSource`` named ``source`` with columns\n            *2106* and *2017*, then the following call to ``hbar_stack`` will\n            will create two ``HBar`` renderers that stack:\n\n            .. code-block:: python\n\n                p.hbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source)\n\n            This is equivalent to the following two separate calls:\n\n            .. code-block:: python\n\n                p.hbar(bottom=stack(),       top=stack('2016'),         x=10, width=0.9, color='blue', source=source, name='2016')\n                p.hbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red',  source=source, name='2017')"
  },
  {
    "code": "def initialize(self, size=0):\n        fs, path = self._get_fs()\n        if fs.exists(path):\n            fp = fs.open(path, mode='r+b')\n        else:\n            fp = fs.open(path, mode='wb')\n        try:\n            fp.truncate(size)\n        except Exception:\n            fp.close()\n            self.delete()\n            raise\n        finally:\n            fp.close()\n        self._size = size\n        return self.fileurl, size, None",
    "docstring": "Initialize file on storage and truncate to given size."
  },
  {
    "code": "def geopy_geolocator():\n    global geolocator\n    if geolocator is None:\n        try:\n            from geopy.geocoders import Nominatim\n        except ImportError:\n            return None\n        geolocator = Nominatim(user_agent=geolocator_user_agent)\n        return geolocator\n    return geolocator",
    "docstring": "Lazy loader for geocoder from geopy. This currently loads the \n    `Nominatim` geocode and returns an instance of it, taking ~2 us."
  },
  {
    "code": "def set_buf_size(fd):\n    if OS_PIPE_SZ and hasattr(fcntl, 'F_SETPIPE_SZ'):\n        fcntl.fcntl(fd, fcntl.F_SETPIPE_SZ, OS_PIPE_SZ)",
    "docstring": "Set up os pipe buffer size, if applicable"
  },
  {
    "code": "def eat_string(self, string):\n        pos = self.pos\n        if self.eos or pos + len(string) > self.length:\n            return None\n        col = self.col\n        row = self.row\n        for char in string:\n            col += 1\n            pos += 1\n            if char == '\\n':\n                col = 0\n                row += 1\n        self.pos = pos\n        self.col = col\n        self.row = row\n        if not self.has_space():\n            self.eos = 1",
    "docstring": "Move current position by length of string and count lines by \\n."
  },
  {
    "code": "def list():\n  infos = manager.get_all()\n  if not infos:\n    print(\"No known TensorBoard instances running.\")\n    return\n  print(\"Known TensorBoard instances:\")\n  for info in infos:\n    template = \"  - port {port}: {data_source} (started {delta} ago; pid {pid})\"\n    print(template.format(\n        port=info.port,\n        data_source=manager.data_source_from_info(info),\n        delta=_time_delta_from_info(info),\n        pid=info.pid,\n    ))",
    "docstring": "Print a listing of known running TensorBoard instances.\n\n  TensorBoard instances that were killed uncleanly (e.g., with SIGKILL\n  or SIGQUIT) may appear in this list even if they are no longer\n  running. Conversely, this list may be missing some entries if your\n  operating system's temporary directory has been cleared since a\n  still-running TensorBoard instance started."
  },
  {
    "code": "def clear(self):\n        self.log(u\"Clearing cache...\")\n        for file_handler, file_info in self.cache.values():\n            self.log([u\"  Removing file '%s'\", file_info])\n            gf.delete_file(file_handler, file_info)\n        self._initialize_cache()\n        self.log(u\"Clearing cache... done\")",
    "docstring": "Clear the cache and remove all the files from disk."
  },
  {
    "code": "def associate(self, floating_ip_id, port_id):\n        pid, ip_address = port_id.split('_', 1)\n        update_dict = {'port_id': pid,\n                       'fixed_ip_address': ip_address}\n        self.client.update_floatingip(floating_ip_id,\n                                      {'floatingip': update_dict})",
    "docstring": "Associates the floating IP to the port.\n\n        ``port_id`` represents a VNIC of an instance.\n        ``port_id`` argument is different from a normal neutron port ID.\n        A value passed as ``port_id`` must be one of target_id returned by\n        ``list_targets``, ``get_target_by_instance`` or\n        ``list_targets_by_instance`` method."
  },
  {
    "code": "def items(self, offset=None, limit=20, since=None, before=None, *args, **kwargs):\n        return ItemList(self, offset=offset, limit=limit, since=since, before=before, cached=self.is_cached)",
    "docstring": "Get a feed's items.\n\n        :param offset: Amount of items to skip before returning data\n        :param since:  Return items added after this id (ordered old -> new)\n        :param before: Return items added before this id (ordered new -> old)\n        :param limit: Amount of items to return"
  },
  {
    "code": "def add_note(self, content):\n        args = {\n            'project_id': self.id,\n            'content': content\n        }\n        _perform_command(self.owner, 'note_add', args)",
    "docstring": "Add a note to the project.\n\n        .. warning:: Requires Todoist premium.\n\n        :param content: The note content.\n        :type content: str\n\n        >>> from pytodoist import todoist\n        >>> user = todoist.login('john.doe@gmail.com', 'password')\n        >>> project = user.get_project('PyTodoist')\n        >>> project.add_note('Remember to update to the latest version.')"
  },
  {
    "code": "def Sign(self, data, signing_key, verify_key=None):\n    if signing_key.KeyLen() < 2048:\n      logging.warning(\"signing key is too short.\")\n    self.signature = signing_key.Sign(data)\n    self.signature_type = self.SignatureType.RSA_PKCS1v15\n    self.digest = hashlib.sha256(data).digest()\n    self.digest_type = self.HashType.SHA256\n    self.data = data\n    if verify_key is None:\n      verify_key = signing_key.GetPublicKey()\n    self.Verify(verify_key)\n    return self",
    "docstring": "Use the data to sign this blob.\n\n    Args:\n      data: String containing the blob data.\n      signing_key: The key to sign with.\n      verify_key: Key to verify with. If None we assume the signing key also\n        contains the public key.\n\n    Returns:\n      self for call chaining."
  },
  {
    "code": "def log_normal(self, x):\n        d = self.mu.shape[0]\n        xc = x - self.mu\n        if len(x.shape) == 1:\n            exp_term = numpy.sum(numpy.multiply(xc, numpy.dot(self.inv, xc)))\n        else:\n            exp_term = numpy.sum(numpy.multiply(xc, numpy.dot(xc, self.inv)), axis=1)\n        return -.5 * (d * numpy.log(2 * numpy.pi) + numpy.log(self.det) + exp_term)",
    "docstring": "Returns the log density of probability of x or the one dimensional\n        array of all log probabilities if many vectors are given.\n\n        @param x : may be of (n,) shape"
  },
  {
    "code": "def _validate_alias_command_level(alias, command):\n    alias_collision_table = AliasManager.build_collision_table([alias])\n    if not alias_collision_table:\n        return\n    command_collision_table = AliasManager.build_collision_table([command])\n    alias_collision_levels = alias_collision_table.get(alias.split()[0], [])\n    command_collision_levels = command_collision_table.get(command.split()[0], [])\n    if set(alias_collision_levels) & set(command_collision_levels):\n        raise CLIError(COMMAND_LVL_ERROR.format(alias, command))",
    "docstring": "Make sure that if the alias is a reserved command, the command that the alias points to\n    in the command tree does not conflict in levels.\n\n    e.g. 'dns' -> 'network dns' is valid because dns is a level 2 command and network dns starts at level 1.\n    However, 'list' -> 'show' is not valid because list and show are both reserved commands at level 2.\n\n    Args:\n        alias: The name of the alias.\n        command: The command that the alias points to."
  },
  {
    "code": "def asarray2d(a):\n    arr = np.asarray(a)\n    if arr.ndim == 1:\n        arr = arr.reshape(-1, 1)\n    return arr",
    "docstring": "Cast to 2d array"
  },
  {
    "code": "def metadata_to_double_percent_options(metadata):\n    options = []\n    if 'cell_depth' in metadata:\n        options.append('%' * metadata.pop('cell_depth'))\n    if 'title' in metadata:\n        options.append(metadata.pop('title'))\n    if 'cell_type' in metadata:\n        options.append('[{}]'.format(metadata.pop('cell_type')))\n    metadata = metadata_to_json_options(metadata)\n    if metadata != '{}':\n        options.append(metadata)\n    return ' '.join(options)",
    "docstring": "Metadata to double percent lines"
  },
  {
    "code": "def external_dependencies(self):\n        found = []\n        for dep in self.dependent_images:\n            if isinstance(dep, six.string_types):\n                if dep not in found:\n                    yield dep\n                    found.append(dep)",
    "docstring": "Return all the external images this Dockerfile will depend on\n\n        These are images from self.dependent_images that aren't defined in this configuration."
  },
  {
    "code": "def lock(self):\n        component = self.component\n        while True:\n            if isinstance(\n                    component,\n                    smartcard.pcsc.PCSCCardConnection.PCSCCardConnection):\n                hresult = SCardBeginTransaction(component.hcard)\n                if 0 != hresult:\n                    raise CardConnectionException(\n                        'Failed to lock with SCardBeginTransaction: ' +\n                        SCardGetErrorMessage(hresult))\n                else:\n                    pass\n                break\n            if hasattr(component, 'component'):\n                component = component.component\n            else:\n                break",
    "docstring": "Lock card with SCardBeginTransaction."
  },
  {
    "code": "def load_train_file(config_file_path):\n    from pylearn2.config import yaml_parse\n    suffix_to_strip = '.yaml'\n    if config_file_path.endswith(suffix_to_strip):\n        config_file_full_stem = config_file_path[0:-len(suffix_to_strip)]\n    else:\n        config_file_full_stem = config_file_path\n    for varname in [\"PYLEARN2_TRAIN_FILE_NAME\",\n            \"PYLEARN2_TRAIN_FILE_FULL_STEM\"]:\n        environ.putenv(varname, config_file_full_stem)\n    directory = config_file_path.split('/')[:-1]\n    directory = '/'.join(directory)\n    if directory != '':\n        directory += '/'\n    environ.putenv(\"PYLEARN2_TRAIN_DIR\", directory)\n    environ.putenv(\"PYLEARN2_TRAIN_BASE_NAME\", config_file_path.split('/')[-1] )\n    environ.putenv(\"PYLEARN2_TRAIN_FILE_STEM\", config_file_full_stem.split('/')[-1] )\n    return yaml_parse.load_path(config_file_path)",
    "docstring": "Loads and parses a yaml file for a Train object.\n    Publishes the relevant training environment variables"
  },
  {
    "code": "def chainproperty(func):\n    func = assertionproperty(func)\n    setattr(AssertionBuilder, func.fget.__name__, func)\n    return func",
    "docstring": "Extend sure with a custom chain property."
  },
  {
    "code": "def config_insync(self):\n        status = self.get('config/insync').get('configInSync', False)\n        if status is None:\n            status = False\n        return status",
    "docstring": "Returns whether the config is in sync, i.e. whether the running\n            configuration is the same as that on disk.\n\n            Returns:\n                bool"
  },
  {
    "code": "def create_hammersley_samples(order, dim=1, burnin=-1, primes=()):\n    if dim == 1:\n        return create_halton_samples(\n            order=order, dim=1, burnin=burnin, primes=primes)\n    out = numpy.empty((dim, order), dtype=float)\n    out[:dim-1] = create_halton_samples(\n        order=order, dim=dim-1, burnin=burnin, primes=primes)\n    out[dim-1] = numpy.linspace(0, 1, order+2)[1:-1]\n    return out",
    "docstring": "Create samples from the Hammersley set.\n\n    For ``dim == 1`` the sequence falls back to Van Der Corput sequence.\n\n    Args:\n        order (int):\n            The order of the Hammersley sequence. Defines the number of samples.\n        dim (int):\n            The number of dimensions in the Hammersley sequence.\n        burnin (int):\n            Skip the first ``burnin`` samples. If negative, the maximum of\n            ``primes`` is used.\n        primes (tuple):\n            The (non-)prime base to calculate values along each axis. If\n            empty, growing prime values starting from 2 will be used.\n\n    Returns:\n        (numpy.ndarray):\n            Hammersley set with ``shape == (dim, order)``."
  },
  {
    "code": "def _parse_roles(self):\n        roles = {}\n        for keystone_role, flask_role in self.config.roles.items():\n            roles.setdefault(flask_role, set()).add(keystone_role)\n        return roles",
    "docstring": "Generate a dictionary for configured roles from oslo_config.\n\n        Due to limitations in ini format, it's necessary to specify\n        roles in a flatter format than a standard dictionary. This\n        function serves to transform these roles into a standard\n        python dictionary."
  },
  {
    "code": "def memoized_property(fget):\n    attr_name = '_{}'.format(fget.__name__)\n    @functools.wraps(fget)\n    def fget_memoized(self):\n        if not hasattr(self, attr_name):\n            setattr(self, attr_name, fget(self))\n        return getattr(self, attr_name)\n    return property(fget_memoized)",
    "docstring": "Decorator to create memoized properties."
  },
  {
    "code": "def amplitude(self, caldb, calv, atten=0):\n        amp = (10 ** (float(self._intensity+atten-caldb)/20)*calv)\n        return amp",
    "docstring": "Calculates the voltage amplitude for this stimulus, using\n        internal intensity value and the given reference intensity & voltage\n\n        :param caldb: calibration intensity in dbSPL\n        :type caldb: float\n        :param calv: calibration voltage that was used to record the intensity provided\n        :type calv: float"
  },
  {
    "code": "def get_override_votes(self, obj):\n        if hasattr(obj, \"meta\"):\n            if obj.meta.override_ap_votes:\n                all_votes = None\n                for ce in obj.candidate_elections.all():\n                    if all_votes:\n                        all_votes = all_votes | ce.votes.all()\n                    else:\n                        all_votes = ce.votes.all()\n                return VotesSerializer(all_votes, many=True).data\n        return False",
    "docstring": "Votes entered into backend.\n        Only used if ``override_ap_votes = True``."
  },
  {
    "code": "def get_ssl(database):\n    if database['engine'] == 'postgresql':\n        keys = ['sslmode', 'sslcert', 'sslkey',\n                'sslrootcert', 'sslcrl', 'sslcompression']\n    else:\n        keys = ['ssl_ca', 'ssl_capath', 'ssl_cert', 'ssl_key',\n                'ssl_cipher', 'ssl_check_hostname']\n    ssl = {}\n    for key in keys:\n        value = database.get(key, None)\n        if value is not None:\n            ssl[key] = value\n    return ssl",
    "docstring": "Returns SSL options for the selected engine"
  },
  {
    "code": "def agent_heartbeat(self, agent_id, metrics, run_states):\n        mutation = gql(\n)\n        try:\n            response = self.gql(mutation, variable_values={\n                'id': agent_id,\n                'metrics': json.dumps(metrics),\n                'runState': json.dumps(run_states)})\n        except Exception as e:\n            message = ast.literal_eval(e.args[0])[\"message\"]\n            logger.error('Error communicating with W&B: %s', message)\n            return []\n        else:\n            return json.loads(response['agentHeartbeat']['commands'])",
    "docstring": "Notify server about agent state, receive commands.\n\n        Args:\n            agent_id (str): agent_id\n            metrics (dict): system metrics\n            run_states (dict): run_id: state mapping\n        Returns:\n            List of commands to execute."
  },
  {
    "code": "def _finalise_figure(fig, **kwargs):\n    title = kwargs.get(\"title\") or None\n    show = kwargs.get(\"show\") or False\n    save = kwargs.get(\"save\") or False\n    savefile = kwargs.get(\"savefile\") or \"EQcorrscan_figure.png\"\n    return_fig = kwargs.get(\"return_figure\") or False\n    if title:\n        fig.suptitle(title)\n    if show:\n        fig.show()\n    if save:\n        fig.savefig(savefile)\n        print(\"Saved figure to {0}\".format(savefile))\n    if return_fig:\n        return fig\n    return None",
    "docstring": "Internal function to wrap up a figure.\n\n    Possible arguments:\n    :type title: str\n    :type show: bool\n    :type save: bool\n    :type savefile: str\n    :type return_figure: bool"
  },
  {
    "code": "def _pad_block(self, handle):\n        extra = handle.tell() % 512\n        if extra:\n            handle.write(b'\\x00' * (512 - extra))",
    "docstring": "Pad the file with 0s to the end of the next block boundary."
  },
  {
    "code": "def add(self, doc):\n        array = doc.to_array(self.attrs)\n        if len(array.shape) == 1:\n            array = array.reshape((array.shape[0], 1))\n        self.tokens.append(array)\n        spaces = doc.to_array(SPACY)\n        assert array.shape[0] == spaces.shape[0]\n        spaces = spaces.reshape((spaces.shape[0], 1))\n        self.spaces.append(numpy.asarray(spaces, dtype=bool))\n        self.strings.update(w.text for w in doc)",
    "docstring": "Add a doc's annotations to the binder for serialization."
  },
  {
    "code": "def flush(cls, *args):\n        return _remove_keys([], [(cls._make_key(args) if args else cls.PREFIX) + '*'])",
    "docstring": "Removes all keys of this namespace\n        Without args, clears all keys starting with cls.PREFIX\n        if called with args, clears keys starting with given cls.PREFIX + args\n\n        Args:\n            *args: Arbitrary number of arguments.\n\n        Returns:\n            List of removed keys."
  },
  {
    "code": "def get_default_project_directory():\n    server_config = Config.instance().get_section_config(\"Server\")\n    path = os.path.expanduser(server_config.get(\"projects_path\", \"~/GNS3/projects\"))\n    path = os.path.normpath(path)\n    try:\n        os.makedirs(path, exist_ok=True)\n    except OSError as e:\n        raise aiohttp.web.HTTPInternalServerError(text=\"Could not create project directory: {}\".format(e))\n    return path",
    "docstring": "Return the default location for the project directory\n    depending of the operating system"
  },
  {
    "code": "def _mask(self, tensor, length, padding_value=0):\n    with tf.name_scope('mask'):\n      range_ = tf.range(tensor.shape[1].value)\n      mask = range_[None, :] < length[:, None]\n      if tensor.shape.ndims > 2:\n        for _ in range(tensor.shape.ndims - 2):\n          mask = mask[..., None]\n        mask = tf.tile(mask, [1, 1] + tensor.shape[2:].as_list())\n      masked = tf.where(mask, tensor, padding_value * tf.ones_like(tensor))\n      return tf.check_numerics(masked, 'masked')",
    "docstring": "Set padding elements of a batch of sequences to a constant.\n\n    Useful for setting padding elements to zero before summing along the time\n    dimension, or for preventing infinite results in padding elements.\n\n    Args:\n      tensor: Tensor of sequences.\n      length: Batch of sequence lengths.\n      padding_value: Value to write into padding elements.\n\n    Returns:\n      Masked sequences."
  },
  {
    "code": "def zeros(shape, dtype=None, **kwargs):\n    if dtype is None:\n        dtype = _numpy.float32\n    return _internal._zeros(shape=shape, dtype=dtype, **kwargs)",
    "docstring": "Returns a new symbol of given shape and type, filled with zeros.\n\n    Parameters\n    ----------\n    shape :  int or sequence of ints\n        Shape of the new array.\n    dtype : str or numpy.dtype, optional\n        The value type of the inner value, default to ``np.float32``.\n\n    Returns\n    -------\n    out : Symbol\n        The created Symbol."
  },
  {
    "code": "def register_pb_devices(num_pbs: int = 100):\n    tango_db = Database()\n    LOG.info(\"Registering PB devices:\")\n    dev_info = DbDevInfo()\n    dev_info._class = 'ProcessingBlockDevice'\n    dev_info.server = 'processing_block_ds/1'\n    for index in range(num_pbs):\n        dev_info.name = 'sip_sdp/pb/{:05d}'.format(index)\n        LOG.info(\"\\t%s\", dev_info.name)\n        tango_db.add_device(dev_info)",
    "docstring": "Register PBs devices.\n\n    Note(BMo): Ideally we do not want to register any devices here. There\n    does not seem to be a way to create a device server with no registered\n    devices in Tango. This is (probably) because Tango devices must have been\n    registered before the server starts ..."
  },
  {
    "code": "def prepare_intervals(data, region_file, work_dir):\n    target_file = os.path.join(work_dir, \"%s-target.interval_list\" % dd.get_sample_name(data))\n    if not utils.file_uptodate(target_file, region_file):\n        with file_transaction(data, target_file) as tx_out_file:\n            params = [\"-T\", \"PreprocessIntervals\", \"-R\", dd.get_ref_file(data),\n                      \"--interval-merging-rule\", \"OVERLAPPING_ONLY\",\n                      \"-O\", tx_out_file]\n            if dd.get_coverage_interval(data) == \"genome\":\n                params += [\"--bin-length\", \"1000\", \"--padding\", \"0\"]\n            else:\n                params += [\"-L\", region_file, \"--bin-length\", \"0\", \"--padding\", \"250\"]\n            _run_with_memory_scaling(params, tx_out_file, data)\n    return target_file",
    "docstring": "Prepare interval regions for targeted and gene based regions."
  },
  {
    "code": "def dir_list(self, tgt_env):\n        ret = set()\n        tree = self.get_tree(tgt_env)\n        if not tree:\n            return ret\n        if self.root(tgt_env):\n            try:\n                tree = tree / self.root(tgt_env)\n            except KeyError:\n                return ret\n            relpath = lambda path: os.path.relpath(path, self.root(tgt_env))\n        else:\n            relpath = lambda path: path\n        add_mountpoint = lambda path: salt.utils.path.join(\n            self.mountpoint(tgt_env), path, use_posixpath=True)\n        for blob in tree.traverse():\n            if isinstance(blob, git.Tree):\n                ret.add(add_mountpoint(relpath(blob.path)))\n        if self.mountpoint(tgt_env):\n            ret.add(self.mountpoint(tgt_env))\n        return ret",
    "docstring": "Get list of directories for the target environment using GitPython"
  },
  {
    "code": "def add_frequency(self, name, value):\n        logger.debug(\"Adding frequency {0} with value {1} to variant {2}\".format(\n            name, value, self['variant_id']))\n        self['frequencies'].append({'label': name, 'value': value})",
    "docstring": "Add a frequency that will be displayed on the variant level\n\n            Args:\n                name (str): The name of the frequency field"
  },
  {
    "code": "def set_partition(self, partition):\n        assert len(partition) == self.numgrp\n        self.partition, self.prev_partition = partition, self.partition",
    "docstring": "Store the partition in self.partition, and\n        move the old self.partition into self.prev_partition"
  },
  {
    "code": "def get_restored(self):\n        return self._header.initial.restore_time > 0, self._header.initial.restore_time",
    "docstring": "Check for restored game."
  },
  {
    "code": "def stream_subsegments(self):\n        segment = self.current_segment()\n        if self.streaming.is_eligible(segment):\n            self.streaming.stream(segment, self._stream_subsegment_out)",
    "docstring": "Stream all closed subsegments to the daemon\n        and remove reference to the parent segment.\n        No-op for a not sampled segment."
  },
  {
    "code": "def prefix_iter(self, ns_uri):\n        ni = self.__lookup_uri(ns_uri)\n        return iter(ni.prefixes)",
    "docstring": "Gets an iterator over the prefixes for the given namespace."
  },
  {
    "code": "def pad(self, sid, date):\n        table = self._ensure_ctable(sid)\n        last_date = self.last_date_in_output_for_sid(sid)\n        tds = self._session_labels\n        if date <= last_date or date < tds[0]:\n            return\n        if last_date == pd.NaT:\n            days_to_zerofill = tds[tds.slice_indexer(end=date)]\n        else:\n            days_to_zerofill = tds[tds.slice_indexer(\n                start=last_date + tds.freq,\n                end=date)]\n        self._zerofill(table, len(days_to_zerofill))\n        new_last_date = self.last_date_in_output_for_sid(sid)\n        assert new_last_date == date, \"new_last_date={0} != date={1}\".format(\n            new_last_date, date)",
    "docstring": "Fill sid container with empty data through the specified date.\n\n        If the last recorded trade is not at the close, then that day will be\n        padded with zeros until its close. Any day after that (up to and\n        including the specified date) will be padded with `minute_per_day`\n        worth of zeros\n\n        Parameters\n        ----------\n        sid : int\n            The asset identifier for the data being written.\n        date : datetime-like\n            The date used to calculate how many slots to be pad.\n            The padding is done through the date, i.e. after the padding is\n            done the `last_date_in_output_for_sid` will be equal to `date`"
  },
  {
    "code": "def __format_error(self, error_list_tag):\n    error = {'domain': self.domain(),\n             'reason': self.reason(),\n             'message': self.message()}\n    error.update(self.extra_fields() or {})\n    return {'error': {error_list_tag: [error],\n                      'code': self.status_code(),\n                      'message': self.message()}}",
    "docstring": "Format this error into a JSON response.\n\n    Args:\n      error_list_tag: A string specifying the name of the tag to use for the\n        error list.\n\n    Returns:\n      A dict containing the reformatted JSON error response."
  },
  {
    "code": "def cache_node_list(nodes, provider, opts):\n    if 'update_cachedir' not in opts or not opts['update_cachedir']:\n        return\n    base = os.path.join(init_cachedir(), 'active')\n    driver = next(six.iterkeys(opts['providers'][provider]))\n    prov_dir = os.path.join(base, driver, provider)\n    if not os.path.exists(prov_dir):\n        os.makedirs(prov_dir)\n    missing_node_cache(prov_dir, nodes, provider, opts)\n    for node in nodes:\n        diff_node_cache(prov_dir, node, nodes[node], opts)\n        path = os.path.join(prov_dir, '{0}.p'.format(node))\n        mode = 'wb' if six.PY3 else 'w'\n        with salt.utils.files.fopen(path, mode) as fh_:\n            salt.utils.msgpack.dump(nodes[node], fh_, encoding=MSGPACK_ENCODING)",
    "docstring": "If configured to do so, update the cloud cachedir with the current list of\n    nodes. Also fires configured events pertaining to the node list.\n\n    .. versionadded:: 2014.7.0"
  },
  {
    "code": "def copy(self):\n        copy = JunctionTree(self.edges())\n        copy.add_nodes_from(self.nodes())\n        if self.factors:\n            factors_copy = [factor.copy() for factor in self.factors]\n            copy.add_factors(*factors_copy)\n        return copy",
    "docstring": "Returns a copy of JunctionTree.\n\n        Returns\n        -------\n        JunctionTree : copy of JunctionTree\n\n        Examples\n        --------\n        >>> import numpy as np\n        >>> from pgmpy.factors.discrete import DiscreteFactor\n        >>> from pgmpy.models import JunctionTree\n        >>> G = JunctionTree()\n        >>> G.add_edges_from([(('a', 'b', 'c'), ('a', 'b')), (('a', 'b', 'c'), ('a', 'c'))])\n        >>> phi1 = DiscreteFactor(['a', 'b'], [1, 2], np.random.rand(2))\n        >>> phi2 = DiscreteFactor(['a', 'c'], [1, 2], np.random.rand(2))\n        >>> G.add_factors(phi1,phi2)\n        >>> modelCopy = G.copy()\n        >>> modelCopy.edges()\n        [(('a', 'b'), ('a', 'b', 'c')), (('a', 'c'), ('a', 'b', 'c'))]\n        >>> G.factors\n        [<DiscreteFactor representing phi(a:1, b:2) at 0xb720ee4c>,\n         <DiscreteFactor representing phi(a:1, c:2) at 0xb4e1e06c>]\n        >>> modelCopy.factors\n        [<DiscreteFactor representing phi(a:1, b:2) at 0xb4bd11ec>,\n         <DiscreteFactor representing phi(a:1, c:2) at 0xb4bd138c>]"
  },
  {
    "code": "def play_sound(self, sound_file):\n        self.stop_sound()\n        if sound_file:\n            cmd = self.check_commands([\"ffplay\", \"paplay\", \"play\"])\n            if cmd:\n                if cmd == \"ffplay\":\n                    cmd = \"ffplay -autoexit -nodisp -loglevel 0\"\n                sound_file = os.path.expanduser(sound_file)\n                c = shlex.split(\"{} {}\".format(cmd, sound_file))\n                self._audio = Popen(c)",
    "docstring": "Plays sound_file if possible."
  },
  {
    "code": "def from_array(cls, arr, index=None, name=None, dtype=None, copy=False,\n                   fastpath=False):\n        warnings.warn(\"'from_array' is deprecated and will be removed in a \"\n                      \"future version. Please use the pd.Series(..) \"\n                      \"constructor instead.\", FutureWarning, stacklevel=2)\n        if isinstance(arr, ABCSparseArray):\n            from pandas.core.sparse.series import SparseSeries\n            cls = SparseSeries\n        return cls(arr, index=index, name=name, dtype=dtype,\n                   copy=copy, fastpath=fastpath)",
    "docstring": "Construct Series from array.\n\n        .. deprecated :: 0.23.0\n            Use pd.Series(..) constructor instead."
  },
  {
    "code": "def countdown_timer(seconds=10):\n    tick = 0.1\n    n_ticks = int(seconds / tick)\n    widgets = ['Pause for panic: ', progressbar.ETA(), ' ', progressbar.Bar()]\n    pbar = progressbar.ProgressBar(\n        widgets=widgets, max_value=n_ticks\n    ).start()\n    for i in range(n_ticks):\n        pbar.update(i)\n        sleep(tick)\n    pbar.finish()",
    "docstring": "Show a simple countdown progress bar\n\n    Parameters\n    ----------\n    seconds\n        Period of time the progress bar takes to reach zero."
  },
  {
    "code": "def rm_field(self, name):\n        if not name in self._fields:\n            raise ValueError\n        self._fields.remove(name)\n        del self.__dict__[name]",
    "docstring": "Remove a field from the datamat.\n\n        Parameters:\n            name : string\n                Name of the field to be removed"
  },
  {
    "code": "def createproject(self, name, **kwargs):\n        data = {'name': name}\n        if kwargs:\n            data.update(kwargs)\n        request = requests.post(\n            self.projects_url, headers=self.headers, data=data,\n            verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)\n        if request.status_code == 201:\n            return request.json()\n        elif request.status_code == 403:\n            if 'Your own projects limit is 0' in request.text:\n                print(request.text)\n                return False\n        else:\n            return False",
    "docstring": "Creates a new project owned by the authenticated user.\n\n        :param name: new project name\n        :param path: custom repository name for new project. By default generated based on name\n        :param namespace_id: namespace for the new project (defaults to user)\n        :param description: short project description\n        :param issues_enabled:\n        :param merge_requests_enabled:\n        :param wiki_enabled:\n        :param snippets_enabled:\n        :param public: if true same as setting visibility_level = 20\n        :param visibility_level:\n        :param sudo:\n        :param import_url:\n        :return:"
  },
  {
    "code": "def int_input(message, low, high, show_range = True):\n    int_in = low - 1\n    while (int_in < low) or (int_in > high):\n        if show_range:\n            suffix = ' (integer between ' + str(low) + ' and ' + str(high) + ')'\n        else:\n            suffix = ''\n        inp = input('Enter a ' + message + suffix + ': ')\n        if re.match('^-?[0-9]+$', inp) is not None:\n            int_in = int(inp)\n        else:\n            print(colored('Must be an integer, try again!', 'red'))\n    return int_in",
    "docstring": "Ask a user for a int input between two values\n\n    args:\n        message (str): Prompt for user\n        low (int): Low value, user entered value must be > this value to be accepted\n        high (int): High value, user entered value must be < this value to be accepted\n        show_range (boolean, Default True): Print hint to user the range\n\n    returns:\n        int_in (int): Input integer"
  },
  {
    "code": "def setup_logging(self):\n        is_custom_logging = len(self.options.logging_config) > 0\n        is_custom_logging = is_custom_logging and os.path.isfile(self.options.logging_config)\n        is_custom_logging = is_custom_logging and not self.options.dry_run\n        if is_custom_logging:\n            Logger.configure_by_file(self.options.logging_config)\n        else:\n            logging_format = \"%(asctime)-15s - %(name)s - %(message)s\"\n            if self.options.dry_run:\n                logging_format = \"%(name)s - %(message)s\"\n            Logger.configure_default(logging_format, self.logging_level)",
    "docstring": "Setup of application logging."
  },
  {
    "code": "def append_row(self, index, value):\n        if index in self._index:\n            raise IndexError('index already in Series')\n        self._index.append(index)\n        self._data.append(value)",
    "docstring": "Appends a row of value to the end of the data. Be very careful with this function as for sorted Series it will \n        not enforce sort order. Use this only for speed when needed, be careful.\n\n        :param index: index\n        :param value: value\n        :return: nothing"
  },
  {
    "code": "def view_as_consumer(\n        wrapped_view: typing.Callable[[HttpRequest], HttpResponse],\n        mapped_actions: typing.Optional[\n            typing.Dict[str, str]\n        ]=None) -> Type[AsyncConsumer]:\n    if mapped_actions is None:\n        mapped_actions = {\n            'create': 'PUT',\n            'update': 'PATCH',\n            'list': 'GET',\n            'retrieve': 'GET'\n        }\n    class DjangoViewWrapper(DjangoViewAsConsumer):\n        view = wrapped_view\n        actions = mapped_actions\n    return DjangoViewWrapper",
    "docstring": "Wrap a django View so that it will be triggered by actions over this json\n     websocket consumer."
  },
  {
    "code": "def get_sourcefile(self):\n        buff = self.get_attribute(\"SourceFile\")\n        if buff is None:\n            return None\n        with unpack(buff) as up:\n            (ref,) = up.unpack_struct(_H)\n        return self.deref_const(ref)",
    "docstring": "the name of thie file this class was compiled from, or None if not\n        indicated\n\n        reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.10"
  },
  {
    "code": "def on_person_new(self, people):\n        self.debug(\"()\")\n        changed = []\n        with self._people_lock:\n            for p in people:\n                person = Person.from_person(p)\n                if person.id in self._people:\n                    self.warning(\n                        u\"{} already in audience\".format(person.id)\n                    )\n                self._people[person.id] = person\n                changed.append(person)\n        for plugin in self.plugins:\n            try:\n                plugin.on_person_new(changed)\n            except:\n                self.exception(\n                    u\"Failed to send new people to {}\".format(plugin.name)\n                )",
    "docstring": "New people joined the audience\n\n        :param people: People that just joined the audience\n        :type people: list[paps.person.Person]\n        :rtype: None"
  },
  {
    "code": "def suspendJustTabProviders(installation):\n    if installation.suspended:\n        raise RuntimeError(\"Installation already suspended\")\n    powerups = list(installation.allPowerups)\n    for p in powerups:\n        if INavigableElement.providedBy(p):\n            p.store.powerDown(p, INavigableElement)\n            sne = SuspendedNavigableElement(store=p.store, originalNE=p)\n            p.store.powerUp(sne, INavigableElement)\n            p.store.powerUp(sne, ISuspender)\n    installation.suspended = True",
    "docstring": "Replace INavigableElements with facades that indicate their suspension."
  },
  {
    "code": "def sendto(self, transport, addr):\n        msg = bytes(self) + b'\\r\\n'\n        logger.debug(\"%s:%s < %s\", *(addr + (self,)))\n        transport.sendto(msg, addr)",
    "docstring": "Send request to a given address via given transport.\n\n        Args:\n            transport (asyncio.DatagramTransport):\n                Write transport to send the message on.\n            addr (Tuple[str, int]):\n                IP address and port pair to send the message to."
  },
  {
    "code": "def readFILTER(self):\n        filterId = self.readUI8()\n        filter = SWFFilterFactory.create(filterId)\n        filter.parse(self)\n        return filter",
    "docstring": "Read a SWFFilter"
  },
  {
    "code": "def load_HEP_data(\n    ROOT_filename            = \"output.root\",\n    tree_name                = \"nominal\",\n    maximum_number_of_events = None\n    ):\n    ROOT_file        = open_ROOT_file(ROOT_filename)\n    tree             = ROOT_file.Get(tree_name)\n    number_of_events = tree.GetEntries()\n    data             = datavision.Dataset()\n    progress = shijian.Progress()\n    progress.engage_quick_calculation_mode()\n    number_of_events_loaded = 0\n    log.info(\"\")\n    index = 0\n    for event in tree:\n        if maximum_number_of_events is not None and\\\n            number_of_events_loaded >= int(maximum_number_of_events):\n            log.info(\n                \"loaded maximum requested number of events \" +\n                \"({maximum_number_of_events})\\r\".format(\n                    maximum_number_of_events = maximum_number_of_events\n                )\n            )\n            break\n        print progress.add_datum(fraction = (index + 2) / number_of_events),\n        if select_event(event):\n            index += 1\n            data.variable(index = index, name = \"el_1_pt\",            value = event.el_pt[0])\n            number_of_events_loaded += 1\n    log.info(\"\")\n    return data",
    "docstring": "Load HEP data and return dataset."
  },
  {
    "code": "def _get_fname_len(self, bufflen=128):\n        buff = self.meta.peek(bufflen)\n        strlen = buff.find('\\0')\n        for i, b in enumerate(buff[strlen:]):\n            if b != '\\0':\n                return strlen+i\n        return bufflen",
    "docstring": "Returns the number of bytes designated for the filename."
  },
  {
    "code": "def export(self, id, exclude_captures=False):\n        return self.service.export(self.base, id, params={'exclude_captures': exclude_captures})",
    "docstring": "Export a result.\n\n        :param id: Result ID as an int.\n        :param exclude_captures: If bool `True`, don't export capture files\n        :rtype: tuple `(io.BytesIO, 'filename')`"
  },
  {
    "code": "def delete(gandi, domain, zone_id, name, type, value):\n    if not zone_id:\n        result = gandi.domain.info(domain)\n        zone_id = result['zone_id']\n    if not zone_id:\n        gandi.echo('No zone records found, domain %s doesn\\'t seems to be '\n                   'managed at Gandi.' % domain)\n        return\n    if not name and not type and not value:\n        proceed = click.confirm('This command without parameters --type, '\n                                '--name or --value will remove all records'\n                                ' in this zone file. Are you sur to '\n                                'perform this action ?')\n        if not proceed:\n            return\n    record = {'name': name, 'type': type, 'value': value}\n    result = gandi.record.delete(zone_id, record)\n    return result",
    "docstring": "Delete a record entry for a domain"
  },
  {
    "code": "def check_errors(self, response):\n        \" Check some common errors.\"\n        content = response.content\n        if 'status' not in content:\n            raise self.GeneralError('We expect a status field.')\n        if content['status'] == 'success':\n            response._content = content\n            return\n        if 'msgs' not in content:\n            raise self.GeneralError('We expcet messages in case of error.')\n        try:\n            messages = list(content['msgs'])\n        except:\n            raise self.GeneralError(\"Messages must be a list.\")\n        for msg in messages:\n            if 'LVL' in msg and msg['LVL'] == 'ERROR':\n                if msg['ERR_CD'] == 'NOT_FOUND':\n                    raise self.NotFoundError(msg['INFO'])\n                elif msg['ERR_CD'] == 'TARGET_EXISTS':\n                    raise self.TargetExistsError(msg['INFO'])\n                else:\n                    raise self.DynectError(msg['INFO'])\n        raise self.GeneralError(\"We need at least one error message.\")",
    "docstring": "Check some common errors."
  },
  {
    "code": "async def on_isupport_excepts(self, value):\n        if not value:\n            value = BAN_EXCEPT_MODE\n        self._channel_modes.add(value)\n        self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_LIST].add(value)",
    "docstring": "Server allows ban exceptions."
  },
  {
    "code": "def remove_network_from_dhcp_agent(self, dhcp_agent, network_id):\n        return self.delete((self.agent_path + self.DHCP_NETS + \"/%s\") % (\n            dhcp_agent, network_id))",
    "docstring": "Remove a network from dhcp agent."
  },
  {
    "code": "def save_token(self, access_token):\n        self.write(access_token.token, access_token.__dict__)\n        unique_token_key = self._unique_token_key(access_token.client_id,\n                                                  access_token.grant_type,\n                                                  access_token.user_id)\n        self.write(unique_token_key, access_token.__dict__)\n        if access_token.refresh_token is not None:\n            self.write(access_token.refresh_token, access_token.__dict__)",
    "docstring": "Stores the access token and additional data in redis.\n\n        See :class:`oauth2.store.AccessTokenStore`."
  },
  {
    "code": "def mark_good(self, server_addr):\n        self.list[server_addr].update({'quality': CMServerList.Good, 'timestamp': time()})",
    "docstring": "Mark server address as good\n\n        :param server_addr: (ip, port) tuple\n        :type server_addr: :class:`tuple`"
  },
  {
    "code": "def get_par_box(domain, last=False):\n    u_range = domain[0]\n    v_range = domain[1]\n    verts = [(u_range[0], v_range[0]), (u_range[1], v_range[0]), (u_range[1], v_range[1]), (u_range[0], v_range[1])]\n    if last:\n        verts.append(verts[0])\n    return tuple(verts)",
    "docstring": "Returns the bounding box of the surface parametric domain in ccw direction.\n\n    :param domain: parametric domain\n    :type domain: list, tuple\n    :param last: if True, adds the first vertex to the end of the return list\n    :type last: bool\n    :return: edges of the parametric domain\n    :rtype: tuple"
  },
  {
    "code": "def delete_service_settings_on_service_delete(sender, instance, **kwargs):\n    service = instance\n    try:\n        service_settings = service.settings\n    except ServiceSettings.DoesNotExist:\n        return\n    if not service_settings.shared:\n        service.settings.delete()",
    "docstring": "Delete not shared service settings without services"
  },
  {
    "code": "def get_nodesitemtypeinsertion(cls, itemgroup, indent) -> str:\n        blanks = ' ' * (indent * 4)\n        subs = [\n            f'{blanks}<complexType name=\"nodes_{itemgroup}Type\">',\n            f'{blanks}    <sequence>',\n            f'{blanks}        <element ref=\"hpcb:selections\"',\n            f'{blanks}                 minOccurs=\"0\"/>',\n            f'{blanks}        <element ref=\"hpcb:devices\"',\n            f'{blanks}                 minOccurs=\"0\"/>']\n        type_ = 'getitemType' if itemgroup == 'getitems' else 'setitemType'\n        for name in ('sim', 'obs', 'sim.series', 'obs.series'):\n            subs.extend([\n                f'{blanks}        <element name=\"{name}\"',\n                f'{blanks}                 type=\"hpcb:{type_}\"',\n                f'{blanks}                 minOccurs=\"0\"',\n                f'{blanks}                 maxOccurs=\"unbounded\"/>'])\n        subs.extend([\n            f'{blanks}    </sequence>',\n            f'{blanks}</complexType>',\n            f''])\n        return '\\n'.join(subs)",
    "docstring": "Return a string defining the required types for the given\n        combination of an exchange item group and |Node| objects.\n\n        >>> from hydpy.auxs.xmltools import XSDWriter\n        >>> print(XSDWriter.get_nodesitemtypeinsertion(\n        ...     'setitems', 1))    # doctest: +ELLIPSIS\n            <complexType name=\"nodes_setitemsType\">\n                <sequence>\n                    <element ref=\"hpcb:selections\"\n                             minOccurs=\"0\"/>\n                    <element ref=\"hpcb:devices\"\n                             minOccurs=\"0\"/>\n                    <element name=\"sim\"\n                             type=\"hpcb:setitemType\"\n                             minOccurs=\"0\"\n                             maxOccurs=\"unbounded\"/>\n                    <element name=\"obs\"\n                             type=\"hpcb:setitemType\"\n                             minOccurs=\"0\"\n                             maxOccurs=\"unbounded\"/>\n                    <element name=\"sim.series\"\n                             type=\"hpcb:setitemType\"\n                             minOccurs=\"0\"\n                             maxOccurs=\"unbounded\"/>\n                    <element name=\"obs.series\"\n                             type=\"hpcb:setitemType\"\n                             minOccurs=\"0\"\n                             maxOccurs=\"unbounded\"/>\n                </sequence>\n            </complexType>\n        <BLANKLINE>"
  },
  {
    "code": "def dump_image_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):\n    if root is None:\n        root = {}\n    root['vtkClass'] = 'vtkImageData'\n    container = root\n    container['spacing'] = dataset.GetSpacing()\n    container['origin'] = dataset.GetOrigin()\n    container['extent'] = dataset.GetExtent()\n    dump_all_arrays(dataset_dir, data_dir, dataset, container, compress)\n    return root",
    "docstring": "Dump image data object to vtkjs"
  },
  {
    "code": "def sanitize_mimetype(mimetype, filename=None):\n    if mimetype in MIMETYPE_WHITELIST:\n        return mimetype\n    if mimetype in MIMETYPE_PLAINTEXT or \\\n            (filename and filename.lower() in MIMETYPE_TEXTFILES):\n        return 'text/plain'\n    return 'application/octet-stream'",
    "docstring": "Sanitize a MIME type so the browser does not render the file."
  },
  {
    "code": "def check_hash(path, checksum, hash_type='md5'):\n    actual_checksum = file_hash(path, hash_type)\n    if checksum != actual_checksum:\n        raise ChecksumError(\"'%s' != '%s'\" % (checksum, actual_checksum))",
    "docstring": "Validate a file using a cryptographic checksum.\n\n    :param str checksum: Value of the checksum used to validate the file.\n    :param str hash_type: Hash algorithm used to generate `checksum`.\n        Can be any hash alrgorithm supported by :mod:`hashlib`,\n        such as md5, sha1, sha256, sha512, etc.\n    :raises ChecksumError: If the file fails the checksum"
  },
  {
    "code": "def _create_path(self):\n        if self.driver == 'sqlite' and 'memory' not in self.dsn and self.dsn != 'sqlite://':\n            dir_ = os.path.dirname(self.path)\n            if dir_ and not os.path.exists(dir_):\n                try:\n                    os.makedirs(dir_)\n                except Exception:\n                    pass\n                if not os.path.exists(dir_):\n                    raise Exception(\"Couldn't create directory \" + dir_)",
    "docstring": "Create the path to hold the database, if one wwas specified."
  },
  {
    "code": "def set_list(self, mutagen_file, values):\n        self.store(mutagen_file, [self.serialize(value) for value in values])",
    "docstring": "Set all values for the field using this style. `values`\n        should be an iterable."
  },
  {
    "code": "def detect(self):\n        if PY3:\n            import subprocess\n        else:\n            import commands as subprocess\n        try:\n            theip = subprocess.getoutput(self.opts_command)\n        except Exception:\n            theip = None\n        self.set_current_value(theip)\n        return theip",
    "docstring": "Detect and return the IP address."
  },
  {
    "code": "def fullName(self):\n        if self.parentName and self.name:\n            return self.parentName + '_' + self.name\n        return self.name or self.parentName",
    "docstring": "A full name, intended to uniquely identify a parameter"
  },
  {
    "code": "def getGrid(self, use_mask=True):\n        grid_card_name = \"WATERSHED_MASK\"\n        if not use_mask:\n            grid_card_name = \"ELEVATION\"\n        return self.getGridByCard(grid_card_name)",
    "docstring": "Returns GDALGrid object of GSSHA model bounds\n\n        Paramters:\n            use_mask(bool): If True, uses watershed mask. Otherwise, it uses the elevaiton grid.\n\n        Returns:\n            GDALGrid"
  },
  {
    "code": "def substitute(search, replace, text):\n    'Regex substitution function. Replaces regex ``search`` with ``replace`` in ``text``'\n    return re.sub(re.compile(str(search)), replace, text)",
    "docstring": "Regex substitution function. Replaces regex ``search`` with ``replace`` in ``text``"
  },
  {
    "code": "def to_database(self, manager=None):\n        network = pybel.to_database(self.model, manager=manager)\n        return network",
    "docstring": "Send the model to the PyBEL database\n\n        This function wraps :py:func:`pybel.to_database`.\n\n        Parameters\n        ----------\n        manager : Optional[pybel.manager.Manager]\n            A PyBEL database manager. If none, first checks the PyBEL\n            configuration for ``PYBEL_CONNECTION`` then checks the\n            environment variable ``PYBEL_REMOTE_HOST``. Finally,\n            defaults to using SQLite database in PyBEL data directory\n            (automatically configured by PyBEL)\n\n        Returns\n        -------\n        network : Optional[pybel.manager.models.Network]\n            The SQLAlchemy model representing the network that was uploaded.\n            Returns None if upload fails."
  },
  {
    "code": "def get_ranges_from_array(arr, append_last=True):\n    right = arr[1:]\n    if append_last:\n        left = arr[:]\n        right = np.append(right, None)\n    else:\n        left = arr[:-1]\n    return np.column_stack((left, right))",
    "docstring": "Takes an array and calculates ranges [start, stop[. The last range end is none to keep the same length.\n\n    Parameters\n    ----------\n    arr : array like\n    append_last: bool\n        If True, append item with a pair of last array item and None.\n\n    Returns\n    -------\n    numpy.array\n        The array formed by pairs of values by the given array.\n\n    Example\n    -------\n    >>> a = np.array((1,2,3,4))\n    >>> get_ranges_from_array(a, append_last=True)\n    array([[1, 2],\n           [2, 3],\n           [3, 4],\n           [4, None]])\n    >>> get_ranges_from_array(a, append_last=False)\n    array([[1, 2],\n           [2, 3],\n           [3, 4]])"
  },
  {
    "code": "def predict(self, X):\n        if np.any(X < self.grid[:, 0]) or np.any(X > self.grid[:, -1]):\n            raise ValueError('data out of min/max bounds')\n        binassign = np.zeros((self.n_features, len(X)), dtype=int)\n        for i in range(self.n_features):\n            binassign[i] = np.digitize(X[:, i], self.grid[i]) - 1\n        labels = np.dot(self.n_bins_per_feature ** np.arange(self.n_features), binassign)\n        assert np.max(labels) < self.n_bins\n        return labels",
    "docstring": "Get the index of the grid cell containing each sample in X\n\n        Parameters\n        ----------\n        X : array-like, shape = [n_samples, n_features]\n            New data\n\n        Returns\n        -------\n        y : array, shape = [n_samples,]\n            Index of the grid cell containing each sample"
  },
  {
    "code": "def series2df(Series, layer=2, split_sign = '_'):\n    try:\n        Series.columns\n        Series = Series.iloc[:,0]\n    except:\n        pass\n    def _helper(x, layer=2):\n        try:\n            return flatten_dict(ast.literal_eval(x), layers=layer, split_sign=split_sign)\n        except:\n            try:\n                return flatten_dict(x, layers=layer, split_sign=split_sign)\n            except:\n                return x\n    df=pd.DataFrame(Series.apply(_helper).tolist())\n    return df",
    "docstring": "expect pass a series that each row is string formated Json data with the same structure"
  },
  {
    "code": "def get_times(self):\n        if not self.n:\n            return []\n        self.times = list(mul(self.u1, self.t1)) + \\\n            list(mul(self.u2, self.t2)) + \\\n            list(mul(self.u3, self.t3)) + \\\n            list(mul(self.u4, self.t4))\n        self.times = matrix(list(set(self.times)))\n        self.times = list(self.times) + list(self.times - 1e-6)\n        return self.times",
    "docstring": "Return all the action times and times-1e-6 in a list"
  },
  {
    "code": "def pairwise(iterable):\n    iterable = iter(iterable)\n    left = next(iterable)\n    for right in iterable:\n        yield left, right\n        left = right",
    "docstring": "Pair each element with its neighbors.\n\n    Arguments\n    ---------\n    iterable : iterable\n\n    Returns\n    -------\n    The generator produces a tuple containing a pairing of each element with\n    its neighbor."
  },
  {
    "code": "def verify_dependencies(self):\n        for i in range(1, len(self.deps)):\n            assert(not (isinstance(self.deps[i], Transformation) and\n                   isinstance(self.deps[i - 1], Analysis))\n                   ), \"invalid dep order for %s\" % self",
    "docstring": "Checks no analysis are called before a transformation,\n        as the transformation could invalidate the analysis."
  },
  {
    "code": "def route(obj, rule, *args, **kwargs):\n    def decorator(cls):\n        endpoint = kwargs.get('endpoint', camel_to_snake(cls.__name__))\n        kwargs['view_func'] = cls.as_view(endpoint)\n        obj.add_url_rule(rule, *args, **kwargs)\n        return cls\n    return decorator",
    "docstring": "Decorator for the View classes."
  },
  {
    "code": "def print_plugins(folders, exit_code=0):\n    modules = plugins.get_plugin_modules(folders)\n    pluginclasses = sorted(plugins.get_plugin_classes(modules), key=lambda x: x.__name__)\n    for pluginclass in pluginclasses:\n        print(pluginclass.__name__)\n        doc = strformat.wrap(pluginclass.__doc__, 80)\n        print(strformat.indent(doc))\n        print()\n    sys.exit(exit_code)",
    "docstring": "Print available plugins and exit."
  },
  {
    "code": "def marginalization_bins(self):\n        log_mean = np.log10(self.mean())\n        return np.logspace(-1. + log_mean, 1. + log_mean, 1001)/self._j_ref",
    "docstring": "Binning to use to do the marginalization integrals"
  },
  {
    "code": "def GetMessages(self, files):\n    result = {}\n    for file_name in files:\n      file_desc = self.pool.FindFileByName(file_name)\n      for desc in file_desc.message_types_by_name.values():\n        result[desc.full_name] = self.GetPrototype(desc)\n      for extension in file_desc.extensions_by_name.values():\n        if extension.containing_type.full_name not in self._classes:\n          self.GetPrototype(extension.containing_type)\n        extended_class = self._classes[extension.containing_type.full_name]\n        extended_class.RegisterExtension(extension)\n    return result",
    "docstring": "Gets all the messages from a specified file.\n\n    This will find and resolve dependencies, failing if the descriptor\n    pool cannot satisfy them.\n\n    Args:\n      files: The file names to extract messages from.\n\n    Returns:\n      A dictionary mapping proto names to the message classes. This will include\n      any dependent messages as well as any messages defined in the same file as\n      a specified message."
  },
  {
    "code": "def clone_wire(old_wire, name=None):\n    if isinstance(old_wire, Const):\n        return Const(old_wire.val, old_wire.bitwidth)\n    else:\n        if name is None:\n            return old_wire.__class__(old_wire.bitwidth, name=old_wire.name)\n        return old_wire.__class__(old_wire.bitwidth, name=name)",
    "docstring": "Makes a copy of any existing wire\n\n    :param old_wire: The wire to clone\n    :param name: a name fo rhte new wire\n\n    Note that this function is mainly intended to be used when the\n    two wires are from different blocks. Making two wires with the\n    same name in the same block is not allowed"
  },
  {
    "code": "def sequence_to_string(\n    a_list,\n    open_bracket_char='[',\n    close_bracket_char=']',\n    delimiter=\", \"\n):\n    return \"%s%s%s\" % (\n        open_bracket_char,\n        delimiter.join(\n            local_to_str(x)\n            for x in a_list\n        ),\n        close_bracket_char\n    )",
    "docstring": "a dedicated function that turns a list into a comma delimited string\n    of items converted.  This method will flatten nested lists."
  },
  {
    "code": "def check_dist_restriction(options, check_target=False):\n    dist_restriction_set = any([\n        options.python_version,\n        options.platform,\n        options.abi,\n        options.implementation,\n    ])\n    binary_only = FormatControl(set(), {':all:'})\n    sdist_dependencies_allowed = (\n        options.format_control != binary_only and\n        not options.ignore_dependencies\n    )\n    if dist_restriction_set and sdist_dependencies_allowed:\n        raise CommandError(\n            \"When restricting platform and interpreter constraints using \"\n            \"--python-version, --platform, --abi, or --implementation, \"\n            \"either --no-deps must be set, or --only-binary=:all: must be \"\n            \"set and --no-binary must not be set (or must be set to \"\n            \":none:).\"\n        )\n    if check_target:\n        if dist_restriction_set and not options.target_dir:\n            raise CommandError(\n                \"Can not use any platform or abi specific options unless \"\n                \"installing via '--target'\"\n            )",
    "docstring": "Function for determining if custom platform options are allowed.\n\n    :param options: The OptionParser options.\n    :param check_target: Whether or not to check if --target is being used."
  },
  {
    "code": "def _GetDirectory(self):\n    if self.entry_type != definitions.FILE_ENTRY_TYPE_DIRECTORY:\n      return None\n    return LVMDirectory(self._file_system, self.path_spec)",
    "docstring": "Retrieves the directory.\n\n    Returns:\n      LVMDirectory: a directory or None if not available."
  },
  {
    "code": "def get(self, name: Text, final: C) -> C:\n        return Caller(self, name, final)",
    "docstring": "Get the function to call which will run all middlewares.\n\n        :param name: Name of the function to be called\n        :param final: Function to call at the bottom of the stack (that's the\n                      one provided by the implementer).\n        :return:"
  },
  {
    "code": "def refractory(times, refract=0.002):\n\ttimes_refract = []\n\ttimes_refract.append(times[0])\n\tfor i in range(1,len(times)):\n\t\tif times_refract[-1]+refract <= times[i]:\n\t\t\ttimes_refract.append(times[i])        \n\treturn times_refract",
    "docstring": "Removes spikes in times list that do not satisfy refractor period\n\n\t:param times: list(float) of spike times in seconds\n\t:type times: list(float)\n\t:param refract: Refractory period in seconds\n\t:type refract: float\n\t:returns: list(float) of spike times in seconds\n\n\tFor every interspike interval < refract, \n\tremoves the second spike time in list and returns the result"
  },
  {
    "code": "def _get_resource_hash(zone_name, record):\n        record_data = defaultdict(int, record)\n        if type(record_data['GeoLocation']) == dict:\n            record_data['GeoLocation'] = \":\".join([\"{}={}\".format(k, v) for k, v in record_data['GeoLocation'].items()])\n        args = [\n            zone_name,\n            record_data['Name'],\n            record_data['Type'],\n            record_data['Weight'],\n            record_data['Region'],\n            record_data['GeoLocation'],\n            record_data['Failover'],\n            record_data['HealthCheckId'],\n            record_data['TrafficPolicyInstanceId']\n        ]\n        return get_resource_id('r53r', args)",
    "docstring": "Returns the last ten digits of the sha256 hash of the combined arguments. Useful for generating unique\n        resource IDs\n\n        Args:\n            zone_name (`str`): The name of the DNS Zone the record belongs to\n            record (`dict`): A record dict to generate the hash from\n\n        Returns:\n            `str`"
  },
  {
    "code": "def open(self, mode):\n        if self.hdf5 == ():\n            kw = dict(mode=mode, libver='latest')\n            if mode == 'r':\n                kw['swmr'] = True\n            try:\n                self.hdf5 = hdf5.File(self.filename, **kw)\n            except OSError as exc:\n                raise OSError('%s in %s' % (exc, self.filename))",
    "docstring": "Open the underlying .hdf5 file and the parent, if any"
  },
  {
    "code": "def filter_using_summary(fq, args):\n    data = {entry[0]: entry[1] for entry in process_summary(\n        summaryfile=args.summary,\n        threads=\"NA\",\n        readtype=args.readtype,\n        barcoded=False)[\n        [\"readIDs\", \"quals\"]].itertuples(index=False)}\n    try:\n        for record in SeqIO.parse(fq, \"fastq\"):\n            if data[record.id] > args.quality \\\n                    and args.length <= len(record) <= args.maxlength:\n                print(record[args.headcrop:args.tailcrop].format(\"fastq\"), end=\"\")\n    except KeyError:\n        logging.error(\"mismatch between summary and fastq: \\\n                       {} was not found in the summary file.\".format(record.id))\n        sys.exit('\\nERROR: mismatch between sequencing_summary and fastq file: \\\n                 {} was not found in the summary file.\\nQuitting.'.format(record.id))",
    "docstring": "Use quality scores from albacore summary file for filtering\n\n    Use the summary file from albacore for more accurate quality estimate\n    Get the dataframe from nanoget, convert to dictionary"
  },
  {
    "code": "def rollback(self) -> None:\n        if len(self._transactions) == 0:\n            raise RuntimeError(\"rollback called outside transaction\")\n        _debug(\"rollback:\", self._transactions[-1])\n        try:\n            for on_rollback in self._transactions[-1]:\n                _debug(\"--> rolling back\", on_rollback)\n                self._do_with_retry(on_rollback)\n        except:\n            _debug(\"--> rollback failed\")\n            exc_class, exc, tb = sys.exc_info()\n            raise tldap.exceptions.RollbackError(\n                \"FATAL Unrecoverable rollback error: %r\" % exc)\n        finally:\n            _debug(\"--> rollback success\")\n            self.reset()",
    "docstring": "Roll back to previous database state. However stay inside transaction\n        management."
  },
  {
    "code": "def make_sh_output(value, output_script, witness=False):\n    return _make_output(\n        value=utils.i2le_padded(value, 8),\n        output_script=make_sh_output_script(output_script, witness))",
    "docstring": "int, str -> TxOut"
  },
  {
    "code": "def are_equivalent_pyxb(a_pyxb, b_pyxb, ignore_timestamps=False):\n    normalize_in_place(a_pyxb, ignore_timestamps)\n    normalize_in_place(b_pyxb, ignore_timestamps)\n    a_xml = d1_common.xml.serialize_to_xml_str(a_pyxb)\n    b_xml = d1_common.xml.serialize_to_xml_str(b_pyxb)\n    are_equivalent = d1_common.xml.are_equivalent(a_xml, b_xml)\n    if not are_equivalent:\n        logger.debug('XML documents not equivalent:')\n        logger.debug(d1_common.xml.format_diff_xml(a_xml, b_xml))\n    return are_equivalent",
    "docstring": "Determine if SystemMetadata PyXB objects are semantically equivalent.\n\n    Normalize then compare SystemMetadata PyXB objects for equivalency.\n\n    Args:\n      a_pyxb, b_pyxb : SystemMetadata PyXB objects to compare\n\n      reset_timestamps: bool\n        ``True``: Timestamps in the SystemMetadata are set to a standard value so that\n        objects that are compared after normalization register as equivalent if only\n        their timestamps differ.\n\n    Returns:\n      bool: **True** if SystemMetadata PyXB objects are semantically equivalent.\n\n    Notes:\n      The SystemMetadata is normalized by removing any redundant information and\n      ordering all sections where there are no semantics associated with the order. The\n      normalized SystemMetadata is intended to be semantically equivalent to the\n      un-normalized one."
  },
  {
    "code": "def addJunctionPos(shape, fromPos, toPos):\n    result = list(shape)\n    if fromPos != shape[0]:\n        result = [fromPos] + result\n    if toPos != shape[-1]:\n        result.append(toPos)\n    return result",
    "docstring": "Extends shape with the given positions in case they differ from the\n    existing endpoints. assumes that shape and positions have the same dimensionality"
  },
  {
    "code": "def Async(f, n=None, timeout=None):\n    return threads(n=n, timeout=timeout)(f)",
    "docstring": "Concise usage for pool.submit.\n\n    Basic Usage Asnyc & threads ::\n\n        from torequests.main import Async, threads\n        import time\n\n\n        def use_submit(i):\n            time.sleep(i)\n            result = 'use_submit: %s' % i\n            print(result)\n            return result\n\n\n        @threads()\n        def use_decorator(i):\n            time.sleep(i)\n            result = 'use_decorator: %s' % i\n            print(result)\n            return result\n\n\n        new_use_submit = Async(use_submit)\n        tasks = [new_use_submit(i) for i in (2, 1, 0)\n                ] + [use_decorator(i) for i in (2, 1, 0)]\n        print([type(i) for i in tasks])\n        results = [i.x for i in tasks]\n        print(results)\n\n        # use_submit: 0\n        # use_decorator: 0\n        # [<class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>]\n        # use_submit: 1\n        # use_decorator: 1\n        # use_submit: 2\n        # use_decorator: 2\n        # ['use_submit: 2', 'use_submit: 1', 'use_submit: 0', 'use_decorator: 2', 'use_decorator: 1', 'use_decorator: 0']"
  },
  {
    "code": "def service_create(name, service_type, description=None, profile=None,\n                   **connection_args):\n    kstone = auth(profile, **connection_args)\n    service = kstone.services.create(name, service_type, description=description)\n    return service_get(service.id, profile=profile, **connection_args)",
    "docstring": "Add service to Keystone service catalog\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt '*' keystone.service_create nova compute \\\n'OpenStack Compute Service'"
  },
  {
    "code": "def read_losc_hdf5_state(f, path='quality/simple', start=None, end=None,\n                         copy=False):\n    dataset = io_hdf5.find_dataset(f, '%s/DQmask' % path)\n    maskset = io_hdf5.find_dataset(f, '%s/DQDescriptions' % path)\n    nddata = dataset[()]\n    bits = [bytes.decode(bytes(b), 'utf-8') for b in maskset[()]]\n    epoch = dataset.attrs['Xstart']\n    try:\n        dt = dataset.attrs['Xspacing']\n    except KeyError:\n        dt = Quantity(1, 's')\n    else:\n        xunit = parse_unit(dataset.attrs['Xunits'])\n        dt = Quantity(dt, xunit)\n    return StateVector(nddata, bits=bits, t0=epoch, name='Data quality',\n                       dx=dt, copy=copy).crop(start=start, end=end)",
    "docstring": "Read a `StateVector` from a LOSC-format HDF file.\n\n    Parameters\n    ----------\n    f : `str`, `h5py.HLObject`\n        path of HDF5 file, or open `H5File`\n\n    path : `str`\n        path of HDF5 dataset to read.\n\n    start : `Time`, `~gwpy.time.LIGOTimeGPS`, optional\n        start GPS time of desired data\n\n    end : `Time`, `~gwpy.time.LIGOTimeGPS`, optional\n        end GPS time of desired data\n\n    copy : `bool`, default: `False`\n        create a fresh-memory copy of the underlying array\n\n    Returns\n    -------\n    data : `~gwpy.timeseries.TimeSeries`\n        a new `TimeSeries` containing the data read from disk"
  },
  {
    "code": "def nvrtcGetProgramLog(self, prog):\n        size = c_size_t()\n        code = self._lib.nvrtcGetProgramLogSize(prog, byref(size))\n        self._throw_on_error(code)\n        buf = create_string_buffer(size.value)\n        code = self._lib.nvrtcGetProgramLog(prog, buf)\n        self._throw_on_error(code)\n        return buf.value.decode('utf-8')",
    "docstring": "Returns the log for the NVRTC program object.\n\n        Only useful after calls to nvrtcCompileProgram or nvrtcVerifyProgram."
  },
  {
    "code": "def _folder_item_method(self, analysis_brain, item):\n        is_editable = self.is_analysis_edition_allowed(analysis_brain)\n        method_title = analysis_brain.getMethodTitle\n        item['Method'] = method_title or ''\n        if is_editable:\n            method_vocabulary = self.get_methods_vocabulary(analysis_brain)\n            if method_vocabulary:\n                item['Method'] = analysis_brain.getMethodUID\n                item['choices']['Method'] = method_vocabulary\n                item['allow_edit'].append('Method')\n                self.show_methodinstr_columns = True\n        elif method_title:\n            item['replace']['Method'] = get_link(analysis_brain.getMethodURL,\n                                                 method_title)\n            self.show_methodinstr_columns = True",
    "docstring": "Fills the analysis' method to the item passed in.\n\n        :param analysis_brain: Brain that represents an analysis\n        :param item: analysis' dictionary counterpart that represents a row"
  },
  {
    "code": "def print_graph(self, format: str = 'turtle') -> str:\n        print(self.g.serialize(format=format).decode('utf-8'))",
    "docstring": "prints serialized formated rdflib Graph"
  },
  {
    "code": "def serve_forever(self):\n        self.start_cmd_loop()\n        try:\n            while not self.done:\n                self.handle_request()\n        except KeyboardInterrupt:\n            if log_file == sys.stderr:\n                log_file.write(\"\\n\")\n        finally:\n            if self._clean_up_call is not None:\n                self._clean_up_call()\n            self.done = True",
    "docstring": "Starts the server handling commands and HTTP requests.\n           The server will loop until done is True or a KeyboardInterrupt is\n           received."
  },
  {
    "code": "def resource_string(self):\n        if self._resources_initialized:\n            res_str = \"{} CPUs, {} GPUs\".format(self._avail_resources.cpu,\n                                                self._avail_resources.gpu)\n            if self._avail_resources.custom_resources:\n                custom = \", \".join(\n                    \"{} {}\".format(\n                        self._avail_resources.get_res_total(name), name)\n                    for name in self._avail_resources.custom_resources)\n                res_str += \" ({})\".format(custom)\n            return res_str\n        else:\n            return \"? CPUs, ? GPUs\"",
    "docstring": "Returns a string describing the total resources available."
  },
  {
    "code": "def parse_int_arg(name, default):\n    return default if request.args.get(name) is None \\\n        else int(request.args.get(name))",
    "docstring": "Return a given URL parameter as int or return the default value."
  },
  {
    "code": "def normalize(self):\n        if self.tz is None or timezones.is_utc(self.tz):\n            not_null = ~self.isna()\n            DAY_NS = ccalendar.DAY_SECONDS * 1000000000\n            new_values = self.asi8.copy()\n            adjustment = (new_values[not_null] % DAY_NS)\n            new_values[not_null] = new_values[not_null] - adjustment\n        else:\n            new_values = conversion.normalize_i8_timestamps(self.asi8, self.tz)\n        return type(self)._from_sequence(new_values,\n                                         freq='infer').tz_localize(self.tz)",
    "docstring": "Convert times to midnight.\n\n        The time component of the date-time is converted to midnight i.e.\n        00:00:00. This is useful in cases, when the time does not matter.\n        Length is unaltered. The timezones are unaffected.\n\n        This method is available on Series with datetime values under\n        the ``.dt`` accessor, and directly on Datetime Array/Index.\n\n        Returns\n        -------\n        DatetimeArray, DatetimeIndex or Series\n            The same type as the original data. Series will have the same\n            name and index. DatetimeIndex will have the same name.\n\n        See Also\n        --------\n        floor : Floor the datetimes to the specified freq.\n        ceil : Ceil the datetimes to the specified freq.\n        round : Round the datetimes to the specified freq.\n\n        Examples\n        --------\n        >>> idx = pd.date_range(start='2014-08-01 10:00', freq='H',\n        ...                     periods=3, tz='Asia/Calcutta')\n        >>> idx\n        DatetimeIndex(['2014-08-01 10:00:00+05:30',\n                       '2014-08-01 11:00:00+05:30',\n                       '2014-08-01 12:00:00+05:30'],\n                        dtype='datetime64[ns, Asia/Calcutta]', freq='H')\n        >>> idx.normalize()\n        DatetimeIndex(['2014-08-01 00:00:00+05:30',\n                       '2014-08-01 00:00:00+05:30',\n                       '2014-08-01 00:00:00+05:30'],\n                       dtype='datetime64[ns, Asia/Calcutta]', freq=None)"
  },
  {
    "code": "def get_raw_tag_data(filename):\n    \"Return the ID3 tag in FILENAME as a raw byte string.\"\n    with open(filename, \"rb\") as file:\n        try:\n            (cls, offset, length) = stagger.tags.detect_tag(file)\n        except stagger.NoTagError:\n            return bytes()\n        file.seek(offset)\n        return file.read(length)",
    "docstring": "Return the ID3 tag in FILENAME as a raw byte string."
  },
  {
    "code": "def update_wallet(self, wallet_name, limit):\n        request = {\n            'update': {\n                'limit': str(limit),\n            }\n        }\n        return make_request(\n            '{}wallet/{}'.format(self.url, wallet_name),\n            method='PATCH',\n            body=request,\n            timeout=self.timeout,\n            client=self._client)",
    "docstring": "Update a wallet with a new limit.\n\n        @param the name of the wallet.\n        @param the new value of the limit.\n        @return a success string from the plans server.\n        @raise ServerError via make_request."
  },
  {
    "code": "def login_required(fn):\n    @wraps(fn)\n    def login_wrapper(ctx, *args, **kwargs):\n        base_url = os.environ.get(\"ONE_CODEX_API_BASE\", \"https://app.onecodex.com\")\n        api_kwargs = {\"telemetry\": ctx.obj[\"TELEMETRY\"]}\n        api_key_prior_login = ctx.obj.get(\"API_KEY\")\n        bearer_token_env = os.environ.get(\"ONE_CODEX_BEARER_TOKEN\")\n        api_key_env = os.environ.get(\"ONE_CODEX_API_KEY\")\n        api_key_creds_file = _login(base_url, silent=True)\n        if api_key_prior_login is not None:\n            api_kwargs[\"api_key\"] = api_key_prior_login\n        elif bearer_token_env is not None:\n            api_kwargs[\"bearer_token\"] = bearer_token_env\n        elif api_key_env is not None:\n            api_kwargs[\"api_key\"] = api_key_env\n        elif api_key_creds_file is not None:\n            api_kwargs[\"api_key\"] = api_key_creds_file\n        else:\n            click.echo(\n                \"The command you specified requires authentication. Please login first.\\n\", err=True\n            )\n            ctx.exit()\n        ctx.obj[\"API\"] = Api(**api_kwargs)\n        return fn(ctx, *args, **kwargs)\n    return login_wrapper",
    "docstring": "Requires login before proceeding, but does not prompt the user to login. Decorator should\n    be used only on Click CLI commands.\n\n    Notes\n    -----\n    Different means of authentication will be attempted in this order:\n        1. An API key present in the Click context object from a previous successful authentication.\n        2. A bearer token (ONE_CODEX_BEARER_TOKEN) in the environment.\n        3. An API key (ONE_CODEX_API_KEY) in the environment.\n        4. An API key in the credentials file (~/.onecodex)."
  },
  {
    "code": "def create(self, sid):\n        data = values.of({'Sid': sid, })\n        payload = self._version.create(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], )",
    "docstring": "Create a new ShortCodeInstance\n\n        :param unicode sid: The SID of a Twilio ShortCode resource\n\n        :returns: Newly created ShortCodeInstance\n        :rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeInstance"
  },
  {
    "code": "def call_lights(*args, **kwargs):\n    res = dict()\n    lights = _get_lights()\n    for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()):\n        if lights.get(six.text_type(dev_id)):\n            res[dev_id] = lights[six.text_type(dev_id)]\n    return res or False",
    "docstring": "Get info about all available lamps.\n\n    Options:\n\n    * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' hue.lights\n        salt '*' hue.lights id=1\n        salt '*' hue.lights id=1,2,3"
  },
  {
    "code": "def set_log_file_extension(self, logFileExtension):\n        assert isinstance(logFileExtension, basestring), \"logFileExtension must be a basestring\"\n        assert len(logFileExtension), \"logFileExtension can't be empty\"\n        if logFileExtension[0] == \".\":\n            logFileExtension = logFileExtension[1:]\n        assert len(logFileExtension), \"logFileExtension is not allowed to be single dot\"\n        if logFileExtension[-1] == \".\":\n            logFileExtension = logFileExtension[:-1]\n        assert len(logFileExtension), \"logFileExtension is not allowed to be double dots\"\n        self.__logFileExtension = logFileExtension\n        self.__set_log_file_name()",
    "docstring": "Set the log file extension.\n\n        :Parameters:\n           #. logFileExtension (string): Logging file extension. A logging file full name is\n              set as logFileBasename.logFileExtension"
  },
  {
    "code": "def createJsbConfig(self):\n        tempdir = mkdtemp()\n        tempfile = join(tempdir, 'app.jsb3')\n        cmd = ['sencha', 'create', 'jsb', '-a', self.url, '-p', tempfile]\n        log.debug('Running: %s', ' '.join(cmd))\n        call(cmd)\n        jsb3 = open(tempfile).read()\n        rmtree(tempdir)\n        return jsb3",
    "docstring": "Create JSB config file using ``sencha create jsb``.\n\n        :return: The created jsb3 config as a string."
  },
  {
    "code": "def zadd(self, name, mapping, nx=False, xx=False, ch=False, incr=False):\n        if not mapping:\n            raise DataError(\"ZADD requires at least one element/score pair\")\n        if nx and xx:\n            raise DataError(\"ZADD allows either 'nx' or 'xx', not both\")\n        if incr and len(mapping) != 1:\n            raise DataError(\"ZADD option 'incr' only works when passing a \"\n                            \"single element/score pair\")\n        pieces = []\n        options = {}\n        if nx:\n            pieces.append(Token.get_token('NX'))\n        if xx:\n            pieces.append(Token.get_token('XX'))\n        if ch:\n            pieces.append(Token.get_token('CH'))\n        if incr:\n            pieces.append(Token.get_token('INCR'))\n            options['as_score'] = True\n        for pair in iteritems(mapping):\n            pieces.append(pair[1])\n            pieces.append(pair[0])\n        return self.execute_command('ZADD', name, *pieces, **options)",
    "docstring": "Set any number of element-name, score pairs to the key ``name``. Pairs\n        are specified as a dict of element-names keys to score values.\n\n        ``nx`` forces ZADD to only create new elements and not to update\n        scores for elements that already exist.\n\n        ``xx`` forces ZADD to only update scores of elements that already\n        exist. New elements will not be added.\n\n        ``ch`` modifies the return value to be the numbers of elements changed.\n        Changed elements include new elements that were added and elements\n        whose scores changed.\n\n        ``incr`` modifies ZADD to behave like ZINCRBY. In this mode only a\n        single element/score pair can be specified and the score is the amount\n        the existing score will be incremented by. When using this mode the\n        return value of ZADD will be the new score of the element.\n\n        The return value of ZADD varies based on the mode specified. With no\n        options, ZADD returns the number of new elements added to the sorted\n        set."
  },
  {
    "code": "def _delete_device_from_device_group(self, device):\n        device_name = get_device_info(device).name\n        dg = pollster(self._get_device_group)(device)\n        device_to_remove = dg.devices_s.devices.load(\n            name=device_name, partition=self.partition\n        )\n        device_to_remove.delete()",
    "docstring": "Remove device from device service cluster group.\n\n        :param device: ManagementRoot object -- device to delete from group"
  },
  {
    "code": "def paint(self, iconic, painter, rect, mode, state, options):\n        for opt in options:\n            self._paint_icon(iconic, painter, rect, mode, state, opt)",
    "docstring": "Main paint method."
  },
  {
    "code": "def submit_error(url, user, project, area, description,\n                 extra=None, default_message=None):\n    LOG.debug('Creating new BugzScout instance.')\n    client = bugzscout.BugzScout(\n        url, user, project, area)\n    LOG.debug('Submitting BugzScout error.')\n    client.submit_error(\n        description, extra=extra, default_message=default_message)",
    "docstring": "Celery task for submitting errors asynchronously.\n\n    :param url: string URL for bugzscout\n    :param user: string fogbugz user to designate when submitting\n                 via bugzscout\n    :param project: string fogbugz project to designate for cases\n    :param area: string fogbugz area to designate for cases\n    :param description: string description for error\n    :param extra: string details for error\n    :param default_message: string default message to return in responses"
  },
  {
    "code": "def is_block(bin_list):\n    id_set = set((my_bin[1] for my_bin in bin_list))\n    start_id, end_id = min(id_set), max(id_set)\n    return id_set == set(range(start_id, end_id + 1))",
    "docstring": "Check if a bin list has exclusively consecutive bin ids."
  },
  {
    "code": "def failed_hosts(self) -> Dict[str, \"MultiResult\"]:\n        return {k: v for k, v in self.result.items() if v.failed}",
    "docstring": "Hosts that failed to complete the task"
  },
  {
    "code": "def has_throttled(self):\n        for file, value in self.cpu_throttle_count.items():\n            try:\n                new_value = int(util.read_file(file))\n                if new_value > value:\n                    return True\n            except Exception as e:\n                logging.warning('Cannot read throttling count of CPU from kernel: %s', e)\n        return False",
    "docstring": "Check whether any of the CPU cores monitored by this instance has\n        throttled since this instance was created.\n        @return a boolean value"
  },
  {
    "code": "def field_match(self, node_field, pattern_field):\n        is_good_list = (isinstance(pattern_field, list) and\n                        self.check_list(node_field, pattern_field))\n        is_good_node = (isinstance(pattern_field, AST) and\n                        Check(node_field,\n                              self.placeholders).visit(pattern_field))\n        def strict_eq(f0, f1):\n            try:\n                return f0 == f1 or (isnan(f0) and isnan(f1))\n            except TypeError:\n                return f0 == f1\n        is_same = strict_eq(pattern_field, node_field)\n        return is_good_list or is_good_node or is_same",
    "docstring": "Check if two fields match.\n\n        Field match if:\n            - If it is a list, all values have to match.\n            - If if is a node, recursively check it.\n            - Otherwise, check values are equal."
  },
  {
    "code": "def _initialize_monitoring_services_queue(self, chain_state: ChainState):\n        msg = (\n            'Transport was started before the monitoring service queue was updated. '\n            'This can lead to safety issue. node:{self!r}'\n        )\n        assert not self.transport, msg\n        msg = (\n            'The node state was not yet recovered, cant read balance proofs. node:{self!r}'\n        )\n        assert self.wal, msg\n        current_balance_proofs = views.detect_balance_proof_change(\n            old_state=ChainState(\n                pseudo_random_generator=chain_state.pseudo_random_generator,\n                block_number=GENESIS_BLOCK_NUMBER,\n                block_hash=constants.EMPTY_HASH,\n                our_address=chain_state.our_address,\n                chain_id=chain_state.chain_id,\n            ),\n            current_state=chain_state,\n        )\n        for balance_proof in current_balance_proofs:\n            update_services_from_balance_proof(self, chain_state, balance_proof)",
    "docstring": "Send the monitoring requests for all current balance proofs.\n\n        Note:\n            The node must always send the *received* balance proof to the\n            monitoring service, *before* sending its own locked transfer\n            forward. If the monitoring service is updated after, then the\n            following can happen:\n\n            For a transfer A-B-C where this node is B\n\n            - B receives T1 from A and processes it\n            - B forwards its T2 to C\n            * B crashes (the monitoring service is not updated)\n\n            For the above scenario, the monitoring service would not have the\n            latest balance proof received by B from A available with the lock\n            for T1, but C would. If the channel B-C is closed and B does not\n            come back online in time, the funds for the lock L1 can be lost.\n\n            During restarts the rationale from above has to be replicated.\n            Because the initialization code *is not* the same as the event\n            handler. This means the balance proof updates must be done prior to\n            the processing of the message queues."
  },
  {
    "code": "def encloses(self,\n                 location: FileLocation\n                 ) -> Optional[FunctionDesc]:\n        for func in self.in_file(location.filename):\n            if location in func.location:\n                return func\n        return None",
    "docstring": "Returns the function, if any, that encloses a given location."
  },
  {
    "code": "def processing_blocks(self):\n        pb_list = ProcessingBlockList()\n        return json.dumps(dict(active=pb_list.active,\n                               completed=pb_list.completed,\n                               aborted=pb_list.aborted))",
    "docstring": "Return the a JSON dict encoding the PBs known to SDP."
  },
  {
    "code": "def reset_spyder(self):\r\n        answer = QMessageBox.warning(self, _(\"Warning\"),\r\n             _(\"Spyder will restart and reset to default settings: <br><br>\"\r\n               \"Do you want to continue?\"),\r\n             QMessageBox.Yes | QMessageBox.No)\r\n        if answer == QMessageBox.Yes:\r\n            self.restart(reset=True)",
    "docstring": "Quit and reset Spyder and then Restart application."
  },
  {
    "code": "def connect(self):\n        self.connection = Connection(self.broker_url)\n        e = Exchange('mease', type='fanout', durable=False, delivery_mode=1)\n        self.exchange = e(self.connection.default_channel)\n        self.exchange.declare()",
    "docstring": "Connects to RabbitMQ"
  },
  {
    "code": "def validate(self, data):\n        for prop in self.properties:\n            if prop.id in data:\n                if prop.type == 'string':\n                    if not isinstance(data[prop.id], basestring):\n                        raise PresetFieldTypeException(\"property '{}' must be of type string\".format(prop.id))\n                elif prop.type == 'enum':\n                    if not isinstance(data[prop.id], basestring):\n                        raise PresetFieldTypeException(\"property '{}' must be of type string\".format(prop.id))\n                    if data[prop.id] not in prop.values:\n                        raise PresetException(\"property '{}' can be one of {}\".format(prop.id, prop.values))\n            else:\n                if prop.required:\n                    raise PresetMissingFieldException(\"missing required property: '{}'\".format(prop.id))",
    "docstring": "Checks if `data` respects this preset specification\n\n        It will check that every required property is present and\n        for every property type it will make some specific control."
  },
  {
    "code": "def _translate(self, x, y):\n        return self.parent._translate((x + self.x), (y + self.y))",
    "docstring": "Convertion x and y to their position on the root Console"
  },
  {
    "code": "def call(self, phone_number, message, message_type, **params):\n        return self.post(VOICE_RESOURCE,\n                         phone_number=phone_number,\n                         message=message,\n                         message_type=message_type,\n                         **params)",
    "docstring": "Send a voice call to the target phone_number.\n\n        See https://developer.telesign.com/docs/voice-api for detailed API documentation."
  },
  {
    "code": "def fuse_list( mafs ):\n    last = None\n    for m in mafs:\n        if last is None:\n            last = m\n        else:\n            fused = fuse( last, m )\n            if fused:\n                last = fused\n            else:\n                yield last\n                last = m\n    if last:\n        yield last",
    "docstring": "Try to fuse a list of blocks by progressively fusing each adjacent pair."
  },
  {
    "code": "def ckm_standard(t12, t13, t23, delta):\n    r\n    c12 = cos(t12)\n    c13 = cos(t13)\n    c23 = cos(t23)\n    s12 = sin(t12)\n    s13 = sin(t13)\n    s23 = sin(t23)\n    return np.array([[c12*c13,\n        c13*s12,\n        s13/exp(1j*delta)],\n        [-(c23*s12) - c12*exp(1j*delta)*s13*s23,\n        c12*c23 - exp(1j*delta)*s12*s13*s23,\n        c13*s23],\n        [-(c12*c23*exp(1j*delta)*s13) + s12*s23,\n        -(c23*exp(1j*delta)*s12*s13) - c12*s23,\n        c13*c23]])",
    "docstring": "r\"\"\"CKM matrix in the standard parametrization and standard phase\n    convention.\n\n    Parameters\n    ----------\n\n    - `t12`: CKM angle $\\theta_{12}$ in radians\n    - `t13`: CKM angle $\\theta_{13}$ in radians\n    - `t23`: CKM angle $\\theta_{23}$ in radians\n    - `delta`: CKM phase $\\delta=\\gamma$ in radians"
  },
  {
    "code": "def check_feasibility(x_bounds, lowerbound, upperbound):\n    x_bounds_lowerbound = sum([x_bound[0] for x_bound in x_bounds])\n    x_bounds_upperbound = sum([x_bound[-1] for x_bound in x_bounds])\n    return (x_bounds_lowerbound <= lowerbound <= x_bounds_upperbound) or \\\n           (x_bounds_lowerbound <= upperbound <= x_bounds_upperbound)",
    "docstring": "This can have false positives.\n    For examples, parameters can only be 0 or 5, and the summation constraint is between 6 and 7."
  },
  {
    "code": "def delete_resource_view(self, resource_view):\n        if isinstance(resource_view, str):\n            if is_valid_uuid(resource_view) is False:\n                raise HDXError('%s is not a valid resource view id!' % resource_view)\n            resource_view = ResourceView({'id': resource_view}, configuration=self.configuration)\n        else:\n            resource_view = self._get_resource_view(resource_view)\n            if 'id' not in resource_view:\n                found = False\n                title = resource_view.get('title')\n                for rv in self.get_resource_views():\n                    if resource_view['title'] == rv['title']:\n                        resource_view = rv\n                        found = True\n                        break\n                if not found:\n                    raise HDXError('No resource views have title %s in this resource!' % title)\n        resource_view.delete_from_hdx()",
    "docstring": "Delete a resource view from the resource and HDX\n\n        Args:\n            resource_view (Union[ResourceView,Dict,str]): Either a resource view id or resource view metadata either from a ResourceView object or a dictionary\n\n        Returns:\n            None"
  },
  {
    "code": "def readmarheader(filename):\n    with open(filename, 'rb') as f:\n        intheader = np.fromstring(f.read(10 * 4), np.int32)\n        floatheader = np.fromstring(f.read(15 * 4), '<f4')\n        strheader = f.read(24)\n        f.read(4)\n        otherstrings = [f.read(16) for i in range(29)]\n    return {'Xsize': intheader[0], 'Ysize': intheader[1], 'MeasTime': intheader[8],\n            'BeamPosX': floatheader[7], 'BeamPosY': floatheader[8],\n            'Wavelength': floatheader[9], 'Dist': floatheader[10],\n            '__Origin__': 'MarResearch .image', 'recordlength': intheader[2],\n            'highintensitypixels': intheader[4],\n            'highintensityrecords': intheader[5],\n            'Date': dateutil.parser.parse(strheader),\n            'Detector': 'MARCCD', '__particle__': 'photon'}",
    "docstring": "Read a header from a MarResearch .image file."
  },
  {
    "code": "def EnumerateQualifiers(self, *args, **kwargs):\n        if self.conn is not None:\n            rv = self.conn.EnumerateQualifiers(*args, **kwargs)\n        else:\n            rv = []\n        try:\n            rv += list(self.qualifiers[self.default_namespace].values())\n        except KeyError:\n            pass\n        return rv",
    "docstring": "Enumerate the qualifier types in the local repository of this class.\n\n        For a description of the parameters, see\n        :meth:`pywbem.WBEMConnection.EnumerateQualifiers`."
  },
  {
    "code": "def crsConvert(crsIn, crsOut):\n    if isinstance(crsIn, osr.SpatialReference):\n        srs = crsIn.Clone()\n    else:\n        srs = osr.SpatialReference()\n        if isinstance(crsIn, int):\n            crsIn = 'EPSG:{}'.format(crsIn)\n        if isinstance(crsIn, str):\n            try:\n                srs.SetFromUserInput(crsIn)\n            except RuntimeError:\n                raise TypeError('crsIn not recognized; must be of type WKT, PROJ4 or EPSG')\n        else:\n            raise TypeError('crsIn must be of type int, str or osr.SpatialReference')\n    if crsOut == 'wkt':\n        return srs.ExportToWkt()\n    elif crsOut == 'prettyWkt':\n        return srs.ExportToPrettyWkt()\n    elif crsOut == 'proj4':\n        return srs.ExportToProj4()\n    elif crsOut == 'epsg':\n        srs.AutoIdentifyEPSG()\n        return int(srs.GetAuthorityCode(None))\n    elif crsOut == 'opengis':\n        srs.AutoIdentifyEPSG()\n        return 'http://www.opengis.net/def/crs/EPSG/0/{}'.format(srs.GetAuthorityCode(None))\n    elif crsOut == 'osr':\n        return srs\n    else:\n        raise ValueError('crsOut not recognized; must be either wkt, proj4, opengis or epsg')",
    "docstring": "convert between different types of spatial references\n\n    Parameters\n    ----------\n    crsIn: int, str or :osgeo:class:`osr.SpatialReference`\n        the input CRS\n    crsOut: {'wkt', 'proj4', 'epsg', 'osr', 'opengis' or 'prettyWkt'}\n        the output CRS type\n\n    Returns\n    -------\n    int, str or :osgeo:class:`osr.SpatialReference`\n        the output CRS\n\n    Examples\n    --------\n    convert an integer EPSG code to PROJ4:\n\n    >>> crsConvert(4326, 'proj4')\n    '+proj=longlat +datum=WGS84 +no_defs '\n\n    convert a PROJ4 string to an opengis URL:\n\n    >>> crsConvert('+proj=longlat +datum=WGS84 +no_defs ', 'opengis')\n    'http://www.opengis.net/def/crs/EPSG/0/4326'\n\n    convert the opengis URL back to EPSG:\n\n    >>> crsConvert('http://www.opengis.net/def/crs/EPSG/0/4326', 'epsg')\n    4326\n    \n    convert an EPSG compound CRS (WGS84 horizontal + EGM96 vertical)\n    \n    >>> crsConvert('EPSG:4326+5773', 'proj4')\n    '+proj=longlat +datum=WGS84 +geoidgrids=egm96_15.gtx +vunits=m +no_defs '"
  },
  {
    "code": "def pretty_print_model(devicemodel):\n    PRETTY_PRINT_MODEL =\n    logging.info(PRETTY_PRINT_MODEL % devicemodel)\n    if 'traits' in devicemodel:\n        for trait in devicemodel['traits']:\n            logging.info('        Trait %s' % trait)\n    else:\n        logging.info('No traits')\n    logging.info('')",
    "docstring": "Prints out a device model in the terminal by parsing dict."
  },
  {
    "code": "def _normalized_levenshtein_distance(s1, s2, acceptable_differences):\n    if len(s1) > len(s2):\n        s1, s2 = s2, s1\n        acceptable_differences = set(-i for i in acceptable_differences)\n    distances = range(len(s1) + 1)\n    for index2, num2 in enumerate(s2):\n        new_distances = [index2 + 1]\n        for index1, num1 in enumerate(s1):\n            if num2 - num1 in acceptable_differences:\n                new_distances.append(distances[index1])\n            else:\n                new_distances.append(1 + min((distances[index1],\n                                             distances[index1+1],\n                                             new_distances[-1])))\n        distances = new_distances\n    return distances[-1]",
    "docstring": "This function calculates the levenshtein distance but allows for elements in the lists to be different by any number\n    in the set acceptable_differences.\n\n    :param s1:                      A list.\n    :param s2:                      Another list.\n    :param acceptable_differences:  A set of numbers. If (s2[i]-s1[i]) is in the set then they are considered equal.\n    :returns:"
  },
  {
    "code": "def dl_files(db, dl_dir, files, keep_subdirs=True, overwrite=False):\n    db_url = posixpath.join(config.db_index_url, db)\n    response = requests.get(db_url)\n    response.raise_for_status()\n    dl_inputs = [(os.path.split(file)[1], os.path.split(file)[0], db, dl_dir, keep_subdirs, overwrite) for file in files]\n    make_local_dirs(dl_dir, dl_inputs, keep_subdirs)\n    print('Downloading files...')\n    pool = multiprocessing.Pool(processes=2)\n    pool.map(dl_pb_file, dl_inputs)\n    print('Finished downloading files')\n    return",
    "docstring": "Download specified files from a Physiobank database.\n\n    Parameters\n    ----------\n    db : str\n        The Physiobank database directory to download. eg. For database:\n        'http://physionet.org/physiobank/database/mitdb', db='mitdb'.\n    dl_dir : str\n        The full local directory path in which to download the files.\n    files : list\n        A list of strings specifying the file names to download relative to the\n        database base directory.\n    keep_subdirs : bool, optional\n        Whether to keep the relative subdirectories of downloaded files as they\n        are organized in Physiobank (True), or to download all files into the\n        same base directory (False).\n    overwrite : bool, optional\n        If True, all files will be redownloaded regardless. If False, existing\n        files with the same name and relative subdirectory will be checked.\n        If the local file is the same size as the online file, the download is\n        skipped. If the local file is larger, it will be deleted and the file\n        will be redownloaded. If the local file is smaller, the file will be\n        assumed to be partially downloaded and the remaining bytes will be\n        downloaded and appended.\n\n    Examples\n    --------\n    >>> wfdb.dl_files('ahadb', os.getcwd(),\n                      ['STAFF-Studies-bibliography-2016.pdf', 'data/001a.hea',\n                      'data/001a.dat'])"
  },
  {
    "code": "def _ParseCshVariables(self, lines):\n    paths = {}\n    for line in lines:\n      if len(line) < 2:\n        continue\n      action = line[0]\n      if action == \"setenv\":\n        target = line[1]\n        path_vals = []\n        if line[2:]:\n          path_vals = line[2].split(\":\")\n        self._ExpandPath(target, path_vals, paths)\n      elif action == \"set\":\n        set_vals = self._CSH_SET_RE.search(\" \".join(line[1:]))\n        if set_vals:\n          target, vals = set_vals.groups()\n          if target in (\"path\", \"term\", \"user\"):\n            target = target.upper()\n          path_vals = vals.split()\n          self._ExpandPath(target, path_vals, paths)\n    return paths",
    "docstring": "Extract env_var and path values from csh derivative shells.\n\n    Path attributes can be set several ways:\n    - setenv takes the form \"setenv PATH_NAME COLON:SEPARATED:LIST\"\n    - set takes the form \"set path_name=(space separated list)\" and is\n      automatically exported for several types of files.\n\n    The first entry in each stanza is used to decide what context to use.\n    Other entries are used to identify the path name and any assigned values.\n\n    Args:\n      lines: A list of lines, each of which is a list of space separated words.\n\n    Returns:\n      a dictionary of path names and values."
  },
  {
    "code": "def last_commit():\n    try:\n        root = subprocess.check_output(\n            ['hg', 'parent', '--template={node}'],\n            stderr=subprocess.STDOUT).strip()\n        return root.decode('utf-8')\n    except subprocess.CalledProcessError:\n        return None",
    "docstring": "Returns the SHA1 of the last commit."
  },
  {
    "code": "def run_command(cmd, debug=False):\n    if debug:\n        msg = '  PWD: {}'.format(os.getcwd())\n        print_warn(msg)\n        msg = '  COMMAND: {}'.format(cmd)\n        print_warn(msg)\n    cmd()",
    "docstring": "Execute the given command and return None.\n\n    :param cmd: A `sh.Command` object to execute.\n    :param debug: An optional bool to toggle debug output.\n    :return: None"
  },
  {
    "code": "def classify_host(host):\n    if isinstance(host, (IPv4Address, IPv6Address)):\n        return host\n    if is_valid_hostname(host):\n        return host\n    return ip_address(host)",
    "docstring": "Host is an IPv4Address, IPv6Address or a string.\n\n    If an IPv4Address or IPv6Address return it.  Otherwise convert the string to an\n    IPv4Address or IPv6Address object if possible and return it.  Otherwise return the\n    original string if it is a valid hostname.\n\n    Raise ValueError if a string cannot be interpreted as an IP address and it is not\n    a valid hostname."
  },
  {
    "code": "def list_wallet_names(api_key, is_hd_wallet=False, coin_symbol='btc'):\n    assert is_valid_coin_symbol(coin_symbol), coin_symbol\n    assert api_key\n    params = {'token': api_key}\n    kwargs = dict(wallets='hd' if is_hd_wallet else '')\n    url = make_url(coin_symbol, **kwargs)\n    r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)\n    return get_valid_json(r)",
    "docstring": "Get all the wallets belonging to an API key"
  },
  {
    "code": "def html_page_context(app, pagename, templatename, context, doctree):\n    rendered_toc = get_rendered_toctree(app.builder, pagename)\n    context['toc'] = rendered_toc\n    context['display_toc'] = True\n    if \"toctree\" not in context:\n        return\n    def make_toctree(collapse=True):\n        return get_rendered_toctree(app.builder,\n                                    pagename,\n                                    prune=False,\n                                    collapse=collapse,\n                                    )\n    context['toctree'] = make_toctree",
    "docstring": "Event handler for the html-page-context signal.\n    Modifies the context directly.\n     - Replaces the 'toc' value created by the HTML builder with one\n       that shows all document titles and the local table of contents.\n     - Sets display_toc to True so the table of contents is always\n       displayed, even on empty pages.\n     - Replaces the 'toctree' function with one that uses the entire\n       document structure, ignores the maxdepth argument, and uses\n       only prune and collapse."
  },
  {
    "code": "def get_permission_required(cls):\n        if cls.permission_required is None:\n            raise ImproperlyConfigured(\n                \"{0} is missing the permission_required attribute. \"\n                \"Define {0}.permission_required, or override \"\n                \"{0}.get_permission_required().\".format(cls.__name__)\n            )\n        if isinstance(cls.permission_required, six.string_types):\n            if cls.permission_required != \"\":\n                perms = (cls.permission_required,)\n            else:\n                perms = ()\n        else:\n            perms = cls.permission_required\n        return perms",
    "docstring": "Get permission required property.\n        Must return an iterable."
  },
  {
    "code": "def delete(fun):\n    if __opts__['file_client'] == 'local':\n        data = __salt__['data.get']('mine_cache')\n        if isinstance(data, dict) and fun in data:\n            del data[fun]\n        return __salt__['data.update']('mine_cache', data)\n    load = {\n            'cmd': '_mine_delete',\n            'id': __opts__['id'],\n            'fun': fun,\n    }\n    return _mine_send(load, __opts__)",
    "docstring": "Remove specific function contents of minion. Returns True on success.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' mine.delete 'network.interfaces'"
  },
  {
    "code": "def skipgram_batch(centers, contexts, num_tokens, dtype, index_dtype):\n    contexts = mx.nd.array(contexts[2], dtype=index_dtype)\n    indptr = mx.nd.arange(len(centers) + 1)\n    centers = mx.nd.array(centers, dtype=index_dtype)\n    centers_csr = mx.nd.sparse.csr_matrix(\n        (mx.nd.ones(centers.shape), centers, indptr), dtype=dtype,\n        shape=(len(centers), num_tokens))\n    return centers_csr, contexts, centers",
    "docstring": "Create a batch for SG training objective."
  },
  {
    "code": "def assert_not_present(self, selector, testid=None, **kwargs):\n        self.info_log(\n            \"Assert not present selector(%s) testid(%s)\" %\n            (selector, testid)\n        )\n        wait_until_not_present = kwargs.get(\n            'wait_until_not_present',\n            BROME_CONFIG['proxy_driver']['wait_until_not_present_before_assert_not_present']\n        )\n        self.debug_log(\n            \"effective wait_until_not_present: %s\" % wait_until_not_present\n        )\n        if wait_until_not_present:\n            ret = self.wait_until_not_present(selector, raise_exception=False)\n        else:\n            ret = not self.is_present(selector)\n        if ret:\n            if testid is not None:\n                self.create_test_result(testid, True)\n            return True\n        else:\n            if testid is not None:\n                self.create_test_result(testid, False)\n            return False",
    "docstring": "Assert that the element is not present in the dom\n\n        Args:\n            selector (str): the selector used to find the element\n            test_id (str): the test_id or a str\n\n        Kwargs:\n            wait_until_not_present (bool)\n\n        Returns:\n            bool: True is the assertion succeed; False otherwise."
  },
  {
    "code": "def deploy(self, unique_id, configs=None):\n    self.install(unique_id, configs)\n    self.start(unique_id, configs)",
    "docstring": "Deploys the service to the host.  This should at least perform the same actions as install and start\n    but may perform additional tasks as needed.\n\n    :Parameter unique_id: the name of the process\n    :Parameter configs: a mao of configs the deployer may use to modify the deployment"
  },
  {
    "code": "def gen(self, text, start=0):\n        for cc in self.chunkComment(text, start):\n            c = self.extractChunkContent(cc)\n            cc = ''.join(cc)\n            m = self.matchComment(c)\n            idx = text.index(cc, start)\n            e = idx + len(cc)\n            if m:\n                assert text[idx:e] == cc\n                try:\n                    end = text.index('\\n\\n', e - 1) + 1\n                except ValueError:\n                    end = len(text)\n                text = text[:e] + text[end:]\n                new = self.genOutputs(self.code(text), m)\n                new = ''.join(new)\n                text = text[:e] + new + text[e:]\n                return self.gen(text, e + len(new))\n        return text",
    "docstring": "Return the source code in text, filled with autogenerated code\n        starting at start."
  },
  {
    "code": "def significance_fdr(p, alpha):\n    i = np.argsort(p, axis=None)\n    m = i.size - np.sum(np.isnan(p))\n    j = np.empty(p.shape, int)\n    j.flat[i] = np.arange(1, i.size + 1)\n    mask = p <= alpha * j / m\n    if np.sum(mask) == 0:\n        return mask\n    k = np.max(j[mask])\n    s = j <= k\n    return s",
    "docstring": "Calculate significance by controlling for the false discovery rate.\n\n    This function determines which of the p-values in `p` can be considered\n    significant. Correction for multiple comparisons is performed by\n    controlling the false discovery rate (FDR). The FDR is the maximum fraction\n    of p-values that are wrongly considered significant [1]_.\n\n    Parameters\n    ----------\n    p : array, shape (channels, channels, nfft)\n        p-values.\n    alpha : float\n        Maximum false discovery rate.\n\n    Returns\n    -------\n    s : array, dtype=bool, shape (channels, channels, nfft)\n        Significance of each p-value.\n\n    References\n    ----------\n    .. [1] Y. Benjamini, Y. Hochberg. Controlling the false discovery rate: a\n           practical and powerful approach to multiple testing. J. Royal Stat.\n           Soc. Series B 57(1): 289-300, 1995."
  },
  {
    "code": "def api_list(cls, api_key=djstripe_settings.STRIPE_SECRET_KEY, **kwargs):\n\t\treturn cls.stripe_class.list(api_key=api_key, **kwargs).auto_paging_iter()",
    "docstring": "Call the stripe API's list operation for this model.\n\n\t\t:param api_key: The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.\n\t\t:type api_key: string\n\n\t\tSee Stripe documentation for accepted kwargs for each object.\n\n\t\t:returns: an iterator over all items in the query"
  },
  {
    "code": "def List(self, name, initial=None):\n        return types.List(name, self.api, initial=initial)",
    "docstring": "The list datatype.\n\n        :param name: The name of the list.\n        :keyword initial: Initial contents of the list.\n\n        See :class:`redish.types.List`."
  },
  {
    "code": "def fullversion():\n    ret = {}\n    cmd = 'lvm version'\n    out = __salt__['cmd.run'](cmd).splitlines()\n    for line in out:\n        comps = line.split(':')\n        ret[comps[0].strip()] = comps[1].strip()\n    return ret",
    "docstring": "Return all version info from lvm version\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' lvm.fullversion"
  },
  {
    "code": "def pop(self):\n        if not self._containers:\n            raise KittyException('no container to pop')\n        self._containers.pop()\n        if self._container():\n            self._container().pop()",
    "docstring": "Remove a the top container from the container stack"
  },
  {
    "code": "def compile_mof_string(self, mof_str, namespace=None, search_paths=None,\n                           verbose=None):\n        namespace = namespace or self.default_namespace\n        self._validate_namespace(namespace)\n        mofcomp = MOFCompiler(_MockMOFWBEMConnection(self),\n                              search_paths=search_paths,\n                              verbose=verbose)\n        mofcomp.compile_string(mof_str, namespace)",
    "docstring": "Compile the MOF definitions in the specified string and add the\n        resulting CIM objects to the specified CIM namespace of the mock\n        repository.\n\n        If the namespace does not exist, :exc:`~pywbem.CIMError` with status\n        CIM_ERR_INVALID_NAMESPACE is raised.\n\n        This method supports all MOF pragmas, and specifically the include\n        pragma.\n\n        If a CIM class or CIM qualifier type to be added already exists in the\n        target namespace with the same name (comparing case insensitively),\n        this method  raises :exc:`~pywbem.CIMError`.\n\n        If a CIM instance to be added already exists in the target namespace\n        with the same keybinding values, this method raises\n        :exc:`~pywbem.CIMError`.\n\n        In all cases where this method raises an exception, the mock repository\n        remains unchanged.\n\n        Parameters:\n\n          mof_str (:term:`string`):\n            A string with the MOF definitions to be compiled.\n\n          namespace (:term:`string`):\n            The name of the target CIM namespace in the mock repository. This\n            namespace is also used for lookup of any existing or dependent\n            CIM objects. If `None`, the default namespace of the connection is\n            used.\n\n          search_paths (:term:`py:iterable` of :term:`string`):\n            An iterable of directory path names where MOF dependent files will\n            be looked up.\n            See the description of the `search_path` init parameter of the\n            :class:`~pywbem.MOFCompiler` class for more information on MOF\n            dependent files.\n\n          verbose (:class:`py:bool`):\n            Controls whether to issue more detailed compiler messages.\n\n        Raises:\n\n          IOError: MOF file not found.\n          :exc:`~pywbem.MOFParseError`: Compile error in the MOF.\n          :exc:`~pywbem.CIMError`: CIM_ERR_INVALID_NAMESPACE: Namespace does\n            not exist.\n          :exc:`~pywbem.CIMError`: Failure related to the CIM objects in the\n            mock repository."
  },
  {
    "code": "def delete_io( hash ):\n    global CACHE_\n    load_cache(True)\n    record_used('cache', hash)\n    num_deleted = len(CACHE_['cache'].get(hash, []))\n    if hash in CACHE_['cache']:\n        del CACHE_['cache'][hash]\n    write_out()\n    return num_deleted",
    "docstring": "Deletes records associated with a particular hash\n\n    :param str hash: The hash\n\n    :rtype int: The number of records deleted"
  },
  {
    "code": "def set_allocated_time(self, time):\n        if self.get_allocated_time_metadata().is_read_only():\n            raise errors.NoAccess()\n        if not self._is_valid_duration(\n                time,\n                self.get_allocated_time_metadata()):\n            raise errors.InvalidArgument()\n        map = dict()\n        map['days'] = time.days\n        map['seconds'] = time.seconds\n        map['microseconds'] = time.microseconds\n        self._my_map['allocatedTime'] = map",
    "docstring": "Sets the allocated time.\n\n        arg:    time (osid.calendaring.Duration): the allocated time\n        raise:  InvalidArgument - ``time`` is invalid\n        raise:  NoAccess - ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def csv_import(self, csv_source, encoding='utf-8', transforms=None, row_class=DataObject, **kwargs):\n        reader_args = dict((k, v) for k, v in kwargs.items() if k not in ['encoding',\n                                                                          'csv_source',\n                                                                          'transforms',\n                                                                          'row_class'])\n        reader = lambda src: csv.DictReader(src, **reader_args)\n        return self._import(csv_source, encoding, transforms, reader=reader, row_class=row_class)",
    "docstring": "Imports the contents of a CSV-formatted file into this table.\n           @param csv_source: CSV file - if a string is given, the file with that name will be\n               opened, read, and closed; if a file object is given, then that object\n               will be read as-is, and left for the caller to be closed.\n           @type csv_source: string or file\n           @param encoding: encoding to be used for reading source text if C{csv_source} is\n               passed as a string filename\n           @type encoding: string (default='UTF-8')\n           @param transforms: dict of functions by attribute name; if given, each\n               attribute will be transformed using the corresponding transform; if there is no\n               matching transform, the attribute will be read as a string (default); the\n               transform function can also be defined as a (function, default-value) tuple; if\n               there is an Exception raised by the transform function, then the attribute will\n               be set to the given default value\n           @type transforms: dict (optional)\n           @param kwargs: additional constructor arguments for csv C{DictReader} objects, such as C{delimiter}\n               or C{fieldnames}; these are passed directly through to the csv C{DictReader} constructor\n           @type kwargs: named arguments (optional)"
  },
  {
    "code": "def _strip_ctype(name, ctype, protocol=2):\n    try:\n        name, ctypestr = name.rsplit(',', 1)\n    except ValueError:\n        pass\n    else:\n        ctype = Nds2ChannelType.find(ctypestr).value\n        if protocol == 1 and ctype in (\n                Nds2ChannelType.STREND.value,\n                Nds2ChannelType.MTREND.value\n        ):\n            name += ',{0}'.format(ctypestr)\n    return name, ctype",
    "docstring": "Strip the ctype from a channel name for the given nds server version\n\n    This is needed because NDS1 servers store trend channels _including_\n    the suffix, but not raw channels, and NDS2 doesn't do this."
  },
  {
    "code": "def grab_project_data(prj):\n    if not prj:\n        return {}\n    data = {}\n    for section in SAMPLE_INDEPENDENT_PROJECT_SECTIONS:\n        try:\n            data[section] = getattr(prj, section)\n        except AttributeError:\n            _LOGGER.debug(\"Project lacks section '%s', skipping\", section)\n    return data",
    "docstring": "From the given Project, grab Sample-independent data.\n\n    There are some aspects of a Project of which it's beneficial for a Sample\n    to be aware, particularly for post-hoc analysis. Since Sample objects\n    within a Project are mutually independent, though, each doesn't need to\n    know about any of the others. A Project manages its, Sample instances,\n    so for each Sample knowledge of Project data is limited. This method\n    facilitates adoption of that conceptual model.\n\n    :param Project prj: Project from which to grab data\n    :return Mapping: Sample-independent data sections from given Project"
  },
  {
    "code": "def from_coords(cls, x, y):\n        x_bytes = int(math.ceil(math.log(x, 2) / 8.0))\n        y_bytes = int(math.ceil(math.log(y, 2) / 8.0))\n        num_bytes = max(x_bytes, y_bytes)\n        byte_string = b'\\x04'\n        byte_string += int_to_bytes(x, width=num_bytes)\n        byte_string += int_to_bytes(y, width=num_bytes)\n        return cls(byte_string)",
    "docstring": "Creates an ECPoint object from the X and Y integer coordinates of the\n        point\n\n        :param x:\n            The X coordinate, as an integer\n\n        :param y:\n            The Y coordinate, as an integer\n\n        :return:\n            An ECPoint object"
  },
  {
    "code": "def py_doc_trim(docstring):\n    if not docstring:\n        return ''\n    lines = docstring.expandtabs().splitlines()\n    indent = sys.maxint\n    for line in lines[1:]:\n        stripped = line.lstrip()\n        if stripped:\n            indent = min(indent, len(line) - len(stripped))\n    trimmed = [lines[0].strip()]\n    if indent < sys.maxint:\n        for line in lines[1:]:\n            trimmed.append(line[indent:].rstrip())\n    while trimmed and not trimmed[-1]:\n        trimmed.pop()\n    while trimmed and not trimmed[0]:\n        trimmed.pop(0)\n    joined = '\\n'.join(trimmed)\n    return newline_substitution_regex.sub(\" \", joined)",
    "docstring": "Trim a python doc string.\n\n    This example is nipped from https://www.python.org/dev/peps/pep-0257/,\n    which describes how to conventionally format and trim docstrings.\n\n    It has been modified to replace single newlines with a space, but leave\n    multiple consecutive newlines in tact."
  },
  {
    "code": "def get_parameters(self):\n        parameter_names = self.PARAMETERS.keys()\n        parameter_values = [getattr(processor, n) for n in parameter_names]\n        return dict(zip(parameter_names, parameter_values))",
    "docstring": "returns a dictionary with the processor's stored parameters"
  },
  {
    "code": "def _set_response_headers(self, response):\n        options = self._get_local_options()\n        self._set_feature_headers(response.headers, options)\n        self._set_frame_options_headers(response.headers, options)\n        self._set_content_security_policy_headers(response.headers, options)\n        self._set_hsts_headers(response.headers)\n        self._set_referrer_policy_headers(response.headers)\n        return response",
    "docstring": "Applies all configured headers to the given response."
  },
  {
    "code": "def _make_complex(self):\n        rcomplex_coeffs = _shtools.SHrtoc(self.coeffs,\n                                          convention=1, switchcs=0)\n        complex_coeffs = _np.zeros((2, self.lmax+1, self.lmax+1),\n                                   dtype='complex')\n        complex_coeffs[0, :, :] = (rcomplex_coeffs[0, :, :] + 1j *\n                                   rcomplex_coeffs[1, :, :])\n        complex_coeffs[1, :, :] = complex_coeffs[0, :, :].conjugate()\n        for m in self.degrees():\n            if m % 2 == 1:\n                complex_coeffs[1, :, m] = - complex_coeffs[1, :, m]\n        return SHCoeffs.from_array(complex_coeffs,\n                                   normalization=self.normalization,\n                                   csphase=self.csphase, copy=False)",
    "docstring": "Convert the real SHCoeffs class to the complex class."
  },
  {
    "code": "def top_level(self):\n        output = {}\n        if isinstance(self.obj, dict):\n            for name, item in self.obj.items():\n                if isinstance(item, dict):\n                    if item:\n                        output[name] = StrReprWrapper('{...}')\n                    else:\n                        output[name] = StrReprWrapper('{}')\n                elif isinstance(item, list):\n                    if item:\n                        output[name] = StrReprWrapper('[...]')\n                    else:\n                        output[name] = StrReprWrapper('[]')\n                else:\n                    output[name] = item\n            return output\n        else:\n            return self.obj",
    "docstring": "Print just the top level of an object, being sure to show where\n        it goes deeper"
  },
  {
    "code": "def process_requests(self):\n        while True:\n            id, args, kwargs = self.request_queue.get()\n            try:\n                response = self._make_request(*args, **kwargs)\n            except Exception as e:\n                response = e\n            self.results[id] = response",
    "docstring": "Loop that runs in a thread to process requests synchronously."
  },
  {
    "code": "def get_edges_as_list(self):\n        my_edges = []\n        for edge_node in self.__get_edge_nodes():\n            my_edges.append(Cedge(edge_node))\n        return my_edges",
    "docstring": "Iterator that returns all the edge objects\n        @rtype: L{Cedge}\n        @return: terminal objects (iterator)"
  },
  {
    "code": "def hideFromPublicBundle(self, otpk_pub):\n        self.__checkSPKTimestamp()\n        for otpk in self.__otpks:\n            if otpk.pub == otpk_pub:\n                self.__otpks.remove(otpk)\n                self.__hidden_otpks.append(otpk)\n                self.__refillOTPKs()",
    "docstring": "Hide a one-time pre key from the public bundle.\n\n        :param otpk_pub: The public key of the one-time pre key to hide, encoded as a\n            bytes-like object."
  },
  {
    "code": "def detect(args):\n  for l in args.input:\n    if l.strip():\n      _print(\"{:<20}{}\".format(Detector(l).language.name, l.strip()))",
    "docstring": "Detect the language of each line."
  },
  {
    "code": "def delete_folder(self, id, force=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"id\"] = id\r\n        if force is not None:\r\n            params[\"force\"] = force\r\n        self.logger.debug(\"DELETE /api/v1/folders/{id} with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"DELETE\", \"/api/v1/folders/{id}\".format(**path), data=data, params=params, no_data=True)",
    "docstring": "Delete folder.\r\n\r\n        Remove the specified folder. You can only delete empty folders unless you\r\n        set the 'force' flag"
  },
  {
    "code": "def maybe_from_tuple(tup_or_range):\n    if isinstance(tup_or_range, tuple):\n        return from_tuple(tup_or_range)\n    elif isinstance(tup_or_range, range):\n        return tup_or_range\n    raise ValueError(\n        'maybe_from_tuple expects a tuple or range, got %r: %r' % (\n            type(tup_or_range).__name__,\n            tup_or_range,\n        ),\n    )",
    "docstring": "Convert a tuple into a range but pass ranges through silently.\n\n    This is useful to ensure that input is a range so that attributes may\n    be accessed with `.start`, `.stop` or so that containment checks are\n    constant time.\n\n    Parameters\n    ----------\n    tup_or_range : tuple or range\n        A tuple to pass to from_tuple or a range to return.\n\n    Returns\n    -------\n    range : range\n        The input to convert to a range.\n\n    Raises\n    ------\n    ValueError\n        Raised when the input is not a tuple or a range. ValueError is also\n        raised if the input is a tuple whose length is not 2 or 3."
  },
  {
    "code": "def authorization_code(self, code, redirect_uri):\n        return self._token_request(grant_type='authorization_code', code=code,\n                                   redirect_uri=redirect_uri)",
    "docstring": "Retrieve access token by `authorization_code` grant.\n\n        https://tools.ietf.org/html/rfc6749#section-4.1.3\n\n        :param str code: The authorization code received from the authorization\n            server.\n        :param str redirect_uri: the identical value of the \"redirect_uri\"\n            parameter in the authorization request.\n        :rtype: dict\n        :return: Access token response"
  },
  {
    "code": "def get(self, sid):\n        return TranscriptionContext(self._version, account_sid=self._solution['account_sid'], sid=sid, )",
    "docstring": "Constructs a TranscriptionContext\n\n        :param sid: The unique string that identifies the resource\n\n        :returns: twilio.rest.api.v2010.account.transcription.TranscriptionContext\n        :rtype: twilio.rest.api.v2010.account.transcription.TranscriptionContext"
  },
  {
    "code": "def _check_devices(self):\n        \"Enumerate OpenVR tracked devices and check whether any need to be initialized\"\n        for i in range(1, len(self.poses)):\n            pose = self.poses[i]\n            if not pose.bDeviceIsConnected:\n                continue\n            if not pose.bPoseIsValid:\n                continue\n            if self.show_controllers_only:\n                device_class = openvr.VRSystem().getTrackedDeviceClass(i)\n                if not device_class == openvr.TrackedDeviceClass_Controller:\n                    continue\n            model_name = openvr.VRSystem().getStringTrackedDeviceProperty(i, openvr.Prop_RenderModelName_String)\n            if model_name not in self.meshes:\n                self.meshes[model_name] = TrackedDeviceMesh(model_name)",
    "docstring": "Enumerate OpenVR tracked devices and check whether any need to be initialized"
  },
  {
    "code": "def _get_container_infos(config, container):\n    client = _get_client(config)\n    infos = None\n    try:\n        infos = _set_id(client.inspect_container(container))\n    except Exception:\n        pass\n    return infos",
    "docstring": "Get container infos\n\n    container\n        Image Id / grain name\n\n    return: dict"
  },
  {
    "code": "def fromProfileName(cls, name):\n        session = bones.SessionAPI.fromProfileName(name)\n        return cls(session)",
    "docstring": "Return an `Origin` from a given configuration profile name.\n\n        :see: `ProfileStore`."
  },
  {
    "code": "def _read(path, encoding=\"utf-8\", comment=\";;;\"):\n    if path:\n        if isinstance(path, basestring) and os.path.exists(path):\n            if PY2:\n                f = codecs.open(path, 'r', encoding='utf-8')\n            else:\n                f = open(path, 'r', encoding='utf-8')\n        elif isinstance(path, basestring):\n            f = path.splitlines()\n        else:\n            f = path\n        for i, line in enumerate(f):\n            line = line.strip(codecs.BOM_UTF8) if i == 0 and isinstance(line, binary_type) else line\n            line = line.strip()\n            line = decode_utf8(line, encoding)\n            if not line or (comment and line.startswith(comment)):\n                continue\n            yield line\n    return",
    "docstring": "Returns an iterator over the lines in the file at the given path,\n        strippping comments and decoding each line to Unicode."
  },
  {
    "code": "def check_version(current_version: str):\n    app_version = parse_version(current_version)\n    while True:\n        try:\n            _do_check_version(app_version)\n        except requests.exceptions.HTTPError as herr:\n            click.secho('Error while checking for version', fg='red')\n            print(herr)\n        except ValueError as verr:\n            click.secho('Error while checking the version', fg='red')\n            print(verr)\n        finally:\n            gevent.sleep(CHECK_VERSION_INTERVAL)",
    "docstring": "Check periodically for a new release"
  },
  {
    "code": "def get_swift_codename(version):\n    codenames = [k for k, v in six.iteritems(SWIFT_CODENAMES) if version in v]\n    if len(codenames) > 1:\n        for codename in reversed(codenames):\n            releases = UBUNTU_OPENSTACK_RELEASE\n            release = [k for k, v in six.iteritems(releases) if codename in v]\n            ret = subprocess.check_output(['apt-cache', 'policy', 'swift'])\n            if six.PY3:\n                ret = ret.decode('UTF-8')\n            if codename in ret or release[0] in ret:\n                return codename\n    elif len(codenames) == 1:\n        return codenames[0]\n    match = re.match(r'^(\\d+)\\.(\\d+)', version)\n    if match:\n        major_minor_version = match.group(0)\n        for codename, versions in six.iteritems(SWIFT_CODENAMES):\n            for release_version in versions:\n                if release_version.startswith(major_minor_version):\n                    return codename\n    return None",
    "docstring": "Determine OpenStack codename that corresponds to swift version."
  },
  {
    "code": "def reverseCommit(self):\n        self.baseClass.setText(self.oldText)\n        self.qteWidget.SCISetStylingEx(0, 0, self.style)",
    "docstring": "Replace the current widget content with the original text.\n        Note that the original text has styling information available,\n        whereas the new text does not."
  },
  {
    "code": "def schema_import(conn, dbpath):\n    conn.execute(\n        \"ATTACH DATABASE ? AS source\", (str(dbpath),))\n    conn.execute(\n        \"INSERT OR IGNORE INTO profiles (name, data)\"\n        \" SELECT name, data FROM source.profiles\"\n        \" WHERE data IS NOT NULL\")\n    conn.commit()\n    conn.execute(\n        \"DETACH DATABASE source\")",
    "docstring": "Import profiles from another database.\n\n    This does not overwrite existing profiles in the target database. Profiles\n    in the source database that share names with those in the target database\n    are ignored.\n\n    :param conn: A connection to an SQLite3 database into which to copy\n        profiles.\n    :param dbpath: The filesystem path to the source SQLite3 database."
  },
  {
    "code": "def close(self, status=1000, reason=u''):\n        try:\n            if self.closed is False:\n                close_msg = bytearray()\n                close_msg.extend(struct.pack(\"!H\", status))\n                if _check_unicode(reason):\n                    close_msg.extend(reason.encode('utf-8'))\n                else:\n                    close_msg.extend(reason)\n                self._send_message(False, CLOSE, close_msg)\n        finally:\n            self.closed = True",
    "docstring": "Send Close frame to the client. The underlying socket is only closed\n           when the client acknowledges the Close frame.\n\n           status is the closing identifier.\n           reason is the reason for the close."
  },
  {
    "code": "def _get_annotation_heading(self, handler, route, heading=None):\n        if hasattr(handler, '_doctor_heading'):\n            return handler._doctor_heading\n        heading = ''\n        handler_path = str(handler)\n        try:\n            handler_file_name = handler_path.split('.')[-2]\n        except IndexError:\n            handler_file_name = 'handler'\n        if handler_file_name.startswith('handler'):\n            class_name = handler_path.split('.')[-1]\n            internal = False\n            for word in CAMEL_CASE_RE.findall(class_name):\n                if word == 'Internal':\n                    internal = True\n                    continue\n                elif word.startswith(('List', 'Handler', 'Resource')):\n                    break\n                heading += '%s ' % (word,)\n            if internal:\n                heading = heading.strip()\n                heading += ' (Internal)'\n        else:\n            heading = ' '.join(handler_file_name.split('_')).title()\n            if 'internal' in route:\n                heading += ' (Internal)'\n        return heading.strip()",
    "docstring": "Returns the heading text for an annotation.\n\n        Attempts to get the name of the heading from the handler attribute\n        `schematic_title` first.\n\n        If `schematic_title` it is not present, it attempts to generate\n        the title from the class path.\n        This path: advertiser_api.handlers.foo_bar.FooListHandler\n        would translate to 'Foo Bar'\n\n        If the file name with the resource is generically named handlers.py\n        or it doesn't have a full path then we attempt to get the resource\n        name from the class name.\n        So FooListHandler and FooHandler would translate to 'Foo'.\n        If the handler class name starts with 'Internal', then that will\n        be appended to the heading.\n        So InternalFooListHandler would translate to 'Foo (Internal)'\n\n        :param mixed handler: The handler class.  Will be a flask resource class\n        :param str route: The route to the handler.\n        :returns: The text for the heading as a string."
  },
  {
    "code": "def scene_add(frames):\n        reader = MessageReader(frames)\n        results = reader.string(\"command\").uint32(\"animation_id\").string(\"name\").uint8_3(\"color\").uint32(\"velocity\").string(\"config\").get()\n        if results.command != \"scene.add\":\n            raise MessageParserError(\"Command is not 'scene.add'\")\n        return (results.animation_id, results.name, np.array([results.color[0]/255, results.color[1]/255, results.color[2]/255]),\n                results.velocity/1000, results.config)",
    "docstring": "parse a scene.add message"
  },
  {
    "code": "def WriteHuntOutputPluginsStates(self, hunt_id, states, cursor=None):\n    columns = \", \".join(_HUNT_OUTPUT_PLUGINS_STATES_COLUMNS)\n    placeholders = mysql_utils.Placeholders(\n        2 + len(_HUNT_OUTPUT_PLUGINS_STATES_COLUMNS))\n    hunt_id_int = db_utils.HuntIDToInt(hunt_id)\n    for index, state in enumerate(states):\n      query = (\"INSERT INTO hunt_output_plugins_states \"\n               \"(hunt_id, plugin_id, {columns}) \"\n               \"VALUES {placeholders}\".format(\n                   columns=columns, placeholders=placeholders))\n      args = [hunt_id_int, index, state.plugin_descriptor.plugin_name]\n      if state.plugin_descriptor.plugin_args is None:\n        args.append(None)\n      else:\n        args.append(state.plugin_descriptor.plugin_args.SerializeToString())\n      args.append(state.plugin_state.SerializeToString())\n      try:\n        cursor.execute(query, args)\n      except MySQLdb.IntegrityError as e:\n        raise db.UnknownHuntError(hunt_id=hunt_id, cause=e)",
    "docstring": "Writes hunt output plugin states for a given hunt."
  },
  {
    "code": "def get_samples(self, init_points_count):\n        init_points_count = self._adjust_init_points_count(init_points_count)\n        samples = np.empty((init_points_count, self.space.dimensionality))\n        random_design = RandomDesign(self.space)\n        random_design.fill_noncontinous_variables(samples)\n        if self.space.has_continuous():\n            X_design = multigrid(self.space.get_continuous_bounds(), self.data_per_dimension)\n            samples[:,self.space.get_continuous_dims()] = X_design\n        return samples",
    "docstring": "This method may return less points than requested.\n        The total number of generated points is the smallest closest integer of n^d to the selected amount of points."
  },
  {
    "code": "def _load(self, **kwargs):\n        if 'uri' in self._meta_data:\n            error = \"There was an attempt to assign a new uri to this \"\\\n                    \"resource, the _meta_data['uri'] is %s and it should\"\\\n                    \" not be changed.\" % (self._meta_data['uri'])\n            raise URICreationCollision(error)\n        requests_params = self._handle_requests_params(kwargs)\n        self._check_load_parameters(**kwargs)\n        kwargs['uri_as_parts'] = True\n        refresh_session = self._meta_data['bigip']._meta_data['icr_session']\n        base_uri = self._meta_data['container']._meta_data['uri']\n        kwargs.update(requests_params)\n        for key1, key2 in self._meta_data['reduction_forcing_pairs']:\n            kwargs = self._reduce_boolean_pair(kwargs, key1, key2)\n        kwargs = self._check_for_python_keywords(kwargs)\n        response = refresh_session.get(base_uri, **kwargs)\n        return self._produce_instance(response)",
    "docstring": "wrapped with load, override that in a subclass to customize"
  },
  {
    "code": "def s_find_first(pred, first, lst):\n    if pred(first):\n        return first\n    elif lst:\n        return s_find_first(pred, unquote(lst[0]), lst[1:])\n    else:\n        return None",
    "docstring": "Evaluate `first`; if predicate `pred` succeeds on the result of `first`,\n    return the result; otherwise recur on the first element of `lst`.\n\n    :param pred: a predicate.\n    :param first: a promise.\n    :param lst: a list of quoted promises.\n    :return: the first element for which predicate is true."
  },
  {
    "code": "def _getDefaultCombinedL4Params(self, numInputBits, inputSize,\n                                  numExternalInputBits, externalInputSize,\n                                  L2CellCount):\n    sampleSize = numExternalInputBits + numInputBits\n    activationThreshold = int(max(numExternalInputBits, numInputBits) * .6)\n    minThreshold = activationThreshold\n    return {\n      \"columnCount\": inputSize,\n      \"cellsPerColumn\": 16,\n      \"learn\": True,\n      \"learnOnOneCell\": False,\n      \"initialPermanence\": 0.41,\n      \"connectedPermanence\": 0.6,\n      \"permanenceIncrement\": 0.1,\n      \"permanenceDecrement\": 0.02,\n      \"minThreshold\": minThreshold,\n      \"basalPredictedSegmentDecrement\": 0.001,\n      \"apicalPredictedSegmentDecrement\": 0.0,\n      \"reducedBasalThreshold\": int(activationThreshold*0.6),\n      \"activationThreshold\": activationThreshold,\n      \"sampleSize\": sampleSize,\n      \"implementation\": \"ApicalTiebreak\",\n      \"seed\": self.seed,\n      \"basalInputWidth\": inputSize*16 + externalInputSize,\n      \"apicalInputWidth\": L2CellCount,\n    }",
    "docstring": "Returns a good default set of parameters to use in a combined L4 region."
  },
  {
    "code": "def get_attribute(self, node, column):\n        if column > 0 and column < len(self.__horizontal_headers):\n            return node.get(self.__horizontal_headers[self.__horizontal_headers.keys()[column]], None)",
    "docstring": "Returns the given Node attribute associated to the given column.\n\n        :param node: Node.\n        :type node: AbstractCompositeNode or GraphModelNode\n        :param column: Column.\n        :type column: int\n        :return: Attribute.\n        :rtype: Attribute"
  },
  {
    "code": "def stop_playback(self):\n        self._sink.flush()\n        self._sink.stop()\n        self._playing = False",
    "docstring": "Stop playback from the audio sink."
  },
  {
    "code": "def instruction_size(op, opc):\n    if op < opc.HAVE_ARGUMENT:\n        return 2 if opc.version >= 3.6 else 1\n    else:\n        return 2 if opc.version >= 3.6 else 3",
    "docstring": "For a given opcode, `op`, in opcode module `opc`,\n    return the size, in bytes, of an `op` instruction.\n\n    This is the size of the opcode (1 byte) and any operand it has. In\n    Python before version 3.6 this will be either 1 or 3 bytes.  In\n    Python 3.6 or later, it is 2 bytes or a \"word\"."
  },
  {
    "code": "def convert(cls, obj, parent):\n        replacement_type = cls._type_mapping.get(type(obj))\n        if replacement_type is not None:\n            new = replacement_type(obj)\n            new.parent = parent\n            return new\n        return obj",
    "docstring": "Converts objects to registered tracked types\n\n        This checks the type of the given object against the registered tracked\n        types. When a match is found, the given object will be converted to the\n        tracked type, its parent set to the provided parent, and returned.\n\n        If its type does not occur in the registered types mapping, the object\n        is returned unchanged."
  },
  {
    "code": "def do_cleanup(cleanup):\n    log.info('Cleaning up after exception')\n    for leftover in cleanup:\n        what = leftover['what']\n        item = leftover['item']\n        if what == 'domain':\n            log.info('Cleaning up %s %s', what, item.name())\n            try:\n                item.destroy()\n                log.debug('%s %s forced off', what, item.name())\n            except libvirtError:\n                pass\n            try:\n                item.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE+\n                                   libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA+\n                                   libvirt.VIR_DOMAIN_UNDEFINE_NVRAM)\n                log.debug('%s %s undefined', what, item.name())\n            except libvirtError:\n                pass\n        if what == 'volume':\n            try:\n                item.delete()\n                log.debug('%s %s cleaned up', what, item.name())\n            except libvirtError:\n                pass",
    "docstring": "Clean up clone domain leftovers as much as possible.\n\n    Extra robust clean up in order to deal with some small changes in libvirt\n    behavior over time. Passed in volumes and domains are deleted, any errors\n    are ignored. Used when cloning/provisioning a domain fails.\n\n    :param cleanup: list containing dictonaries with two keys: 'what' and 'item'.\n                    If 'what' is domain the 'item' is a libvirt domain object.\n                    If 'what' is volume then the item is a libvirt volume object.\n\n    Returns:\n        none\n\n    .. versionadded: 2017.7.3"
  },
  {
    "code": "def update(self):\r\n        if self.single_channel:\r\n            self.im.set_data(self.data[self.ind, :, :])\r\n        else:\r\n            self.im.set_data(self.data[self.ind, :, :, :])\r\n        self.ax.set_ylabel('time frame %s' % self.ind)\r\n        self.im.axes.figure.canvas.draw()",
    "docstring": "Updates image to be displayed with new time frame."
  },
  {
    "code": "def register_views(*args):\n    config = args[0]\n    settings = config.get_settings()\n    pages_config = settings[CONFIG_MODELS]\n    resources = resources_of_config(pages_config)\n    for resource in resources:\n        if hasattr(resource, '__table__')\\\n                and not hasattr(resource, 'model'):\n            continue\n        resource.model.pyramid_pages_template = resource.template\n        config.add_view(resource.view,\n                        attr=resource.attr,\n                        route_name=PREFIX_PAGE,\n                        renderer=resource.template,\n                        context=resource,\n                        permission=PREFIX_PAGE)",
    "docstring": "Registration view for each resource from config."
  },
  {
    "code": "def statuses_show(self, id, trim_user=None, include_my_retweet=None,\n                      include_entities=None):\n        params = {'id': id}\n        set_bool_param(params, 'trim_user', trim_user)\n        set_bool_param(params, 'include_my_retweet', include_my_retweet)\n        set_bool_param(params, 'include_entities', include_entities)\n        return self._get_api('statuses/show.json', params)",
    "docstring": "Returns a single Tweet, specified by the id parameter.\n\n        https://dev.twitter.com/docs/api/1.1/get/statuses/show/%3Aid\n\n        :param str id:\n            (*required*) The numerical ID of the desired tweet.\n\n        :param bool trim_user:\n            When set to ``True``, the tweet's user object includes only the\n            status author's numerical ID.\n\n        :param bool include_my_retweet:\n            When set to ``True``, any Tweet returned that has been retweeted by\n            the authenticating user will include an additional\n            ``current_user_retweet`` node, containing the ID of the source\n            status for the retweet.\n\n        :param bool include_entities:\n            When set to ``False``, the ``entities`` node will not be included.\n\n        :returns: A tweet dict."
  },
  {
    "code": "def get_culprit(omit_top_frames=1):\n    try:\n        caller_stack = stack()[omit_top_frames:]\n        while len(caller_stack) > 0:\n            frame = caller_stack.pop(0)\n            filename = frame[1]\n            if '<decorator' in filename or __file__ in filename:\n                continue\n            else:\n                break\n        lineno = frame[2]\n        del caller_stack, frame\n    except OSError:\n        filename = 'unknown'\n        lineno = -1\n    return filename, lineno",
    "docstring": "get the filename and line number calling this.\n\n    Parameters\n    ----------\n    omit_top_frames: int, default=1\n        omit n frames from top of stack stack. Purpose is to get the real\n        culprit and not intermediate functions on the stack.\n    Returns\n    -------\n    (filename: str, fileno: int)\n    filename and line number of the culprit."
  },
  {
    "code": "def su(self) -> 'Gate':\n        rank = 2**self.qubit_nb\n        U = asarray(self.asoperator())\n        U /= np.linalg.det(U) ** (1/rank)\n        return Gate(tensor=U, qubits=self.qubits)",
    "docstring": "Convert gate tensor to the special unitary group."
  },
  {
    "code": "def output_size(self) -> Tuple[Sequence[Shape], Sequence[Shape], Sequence[Shape], int]:\n        return self._cell.output_size",
    "docstring": "Returns the simulation output size."
  },
  {
    "code": "def value_to_sql_str(v):\n    if v is None:\n        return 'null'\n    if type(v) in (types.IntType, types.FloatType, types.LongType):\n        return str(v)\n    if type(v) in (types.StringType, types.UnicodeType):\n        return \"'%s'\" %(v.replace(u\"'\", u\"\\\\'\"))\n    if isinstance(v, datetime):\n        return \"'%s'\" %(v.strftime(\"%Y-%m-%d %H:%M:%S\"))\n    if isinstance(v, date):\n        return \"'%s'\" %(v.strftime(\"%Y-%m-%d\"))\n    return str(v)",
    "docstring": "transform a python variable to the appropriate representation in SQL"
  },
  {
    "code": "def _GetTableNames(self, database):\n    table_names = []\n    for esedb_table in database.tables:\n      table_names.append(esedb_table.name)\n    return table_names",
    "docstring": "Retrieves the table names in a database.\n\n    Args:\n      database (pyesedb.file): ESE database.\n\n    Returns:\n      list[str]: table names."
  },
  {
    "code": "def calculate_file_access_time(workflow_workspace):\n    access_times = {}\n    for subdir, dirs, files in os.walk(workflow_workspace):\n        for file in files:\n            file_path = os.path.join(subdir, file)\n            access_times[file_path] = os.stat(file_path).st_atime\n    return access_times",
    "docstring": "Calculate access times of files in workspace."
  },
  {
    "code": "def get_file_extension(filepath):\n    _ext = os.path.splitext(filepath)[-1]\n    if _ext:\n        return _ext[1:] if _ext.startswith('.') else _ext\n    return ''",
    "docstring": "Copy if anyconfig.utils.get_file_extension is not available.\n\n    >>> get_file_extension(\"/a/b/c\")\n    ''\n    >>> get_file_extension(\"/a/b.txt\")\n    'txt'\n    >>> get_file_extension(\"/a/b/c.tar.xz\")\n    'xz'"
  },
  {
    "code": "def start_msstitch(exec_drivers, sysargs):\n    parser = populate_parser(exec_drivers)\n    args = parser.parse_args(sysargs[1:])\n    args.func(**vars(args))",
    "docstring": "Passed all drivers of executable, checks which command is passed to\n    the executable and then gets the options for a driver, parses them from\n    command line and runs the driver"
  },
  {
    "code": "def fit_df(self, dfs, pstate_col=PSTATE_COL):\n        obs_cols = list(self.emission_name)\n        obs = [df[df.columns.difference([pstate_col])][obs_cols].values for df in dfs]\n        pstates = [df[pstate_col].values for df in dfs]\n        return self.fit(obs, pstates)",
    "docstring": "Convenience function to fit a model from a list of dataframes"
  },
  {
    "code": "def pick(self, req_authn_context=None):\n        if req_authn_context is None:\n            return self._pick_by_class_ref(UNSPECIFIED, \"minimum\")\n        if req_authn_context.authn_context_class_ref:\n            if req_authn_context.comparison:\n                _cmp = req_authn_context.comparison\n            else:\n                _cmp = \"exact\"\n            if _cmp == 'exact':\n                res = []\n                for cls_ref in req_authn_context.authn_context_class_ref:\n                    res += (self._pick_by_class_ref(cls_ref.text, _cmp))\n                return res\n            else:\n                return self._pick_by_class_ref(\n                    req_authn_context.authn_context_class_ref[0].text, _cmp)\n        elif req_authn_context.authn_context_decl_ref:\n            if req_authn_context.comparison:\n                _cmp = req_authn_context.comparison\n            else:\n                _cmp = \"exact\"\n            return self._pick_by_class_ref(\n                req_authn_context.authn_context_decl_ref, _cmp)",
    "docstring": "Given the authentication context find zero or more places where\n        the user could be sent next. Ordered according to security level.\n\n        :param req_authn_context: The requested context as an\n            RequestedAuthnContext instance\n        :return: An URL"
  },
  {
    "code": "def get(self, sid):\n        return AuthCallsIpAccessControlListMappingContext(\n            self._version,\n            account_sid=self._solution['account_sid'],\n            domain_sid=self._solution['domain_sid'],\n            sid=sid,\n        )",
    "docstring": "Constructs a AuthCallsIpAccessControlListMappingContext\n\n        :param sid: The unique string that identifies the resource\n\n        :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingContext\n        :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_ip_access_control_list_mapping.AuthCallsIpAccessControlListMappingContext"
  },
  {
    "code": "def set_custom_getter_compose(custom_getter):\n  tf.get_variable_scope().set_custom_getter(\n      _compose_custom_getters(tf.get_variable_scope().custom_getter,\n                              custom_getter))",
    "docstring": "Set a custom getter in the current variable scope.\n\n  Do not overwrite the existing custom getter - rather compose with it.\n\n  Args:\n    custom_getter: a custom getter."
  },
  {
    "code": "def help(*args):\n    from . import commands\n    parser = argparse.ArgumentParser(prog=\"%s %s\" % (__package__, help.__name__), description=help.__doc__)\n    parser.add_argument('COMMAND', help=\"command to show help for\", nargs=\"?\", choices=__all__)\n    args = parser.parse_args(args)\n    if args.COMMAND:\n        for l in getattr(commands, args.COMMAND)('-h'):\n            yield l\n    else:\n        parser.parse_args(['-h'])",
    "docstring": "Prints help."
  },
  {
    "code": "def rotate_image(filename, line, sdir, image_list):\n    file_loc = get_image_location(filename, sdir, image_list)\n    degrees = re.findall('(angle=[-\\\\d]+|rotate=[-\\\\d]+)', line)\n    if len(degrees) < 1:\n        return False\n    degrees = degrees[0].split('=')[-1].strip()\n    if file_loc is None or file_loc == 'ERROR' or\\\n            not re.match('-*\\\\d+', degrees):\n        return False\n    if degrees:\n        try:\n            degrees = int(degrees)\n        except (ValueError, TypeError):\n            return False\n        if not os.path.exists(file_loc):\n            return False\n        with Image(filename=file_loc) as image:\n            with image.clone() as rotated:\n                rotated.rotate(degrees)\n                rotated.save(filename=file_loc)\n        return True\n    return False",
    "docstring": "Rotate a image.\n\n    Given a filename and a line, figure out what it is that the author\n    wanted to do wrt changing the rotation of the image and convert the\n    file so that this rotation is reflected in its presentation.\n\n    :param: filename (string): the name of the file as specified in the TeX\n    :param: line (string): the line where the rotate command was found\n\n    :output: the image file rotated in accordance with the rotate command\n    :return: True if something was rotated"
  },
  {
    "code": "def hashmodel(model, library=None):\r\n    library = library or 'python-stdnet'\r\n    meta = model._meta\r\n    sha = hashlib.sha1(to_bytes('{0}({1})'.format(library, meta)))\r\n    hash = sha.hexdigest()[:8]\r\n    meta.hash = hash\r\n    if hash in _model_dict:\r\n        raise KeyError('Model \"{0}\" already in hash table.\\\r\n Rename your model or the module containing the model.'.format(meta))\r\n    _model_dict[hash] = model",
    "docstring": "Calculate the Hash id of metaclass ``meta``"
  },
  {
    "code": "def fit_transform(self, X, y, step_size=0.1, init_weights=None, warm_start=False):\n        self.fit(X=X, y=y, step_size=step_size, init_weights=init_weights, warm_start=warm_start)\n        return self.transform(X=X)",
    "docstring": "Fit optimizer to X, then transforms X. See `fit` and `transform` for further explanation."
  },
  {
    "code": "def send_event(self, name, *args, **kwargs):\n        n = len(self._bridge_queue)\n        self._bridge_queue.append((name, args))\n        if n == 0:\n            self._bridge_last_scheduled = time()\n            self.deferred_call(self._bridge_send)\n            return\n        elif kwargs.get('now'):\n            self._bridge_send(now=True)\n            return\n        dt = time() - self._bridge_last_scheduled\n        if dt > self._bridge_max_delay:\n            self._bridge_send(now=True)",
    "docstring": "Send an event to the native handler. This call is queued and \n        batched.\n\n        Parameters\n        ----------\n        name : str\n            The event name to be processed by MainActivity.processMessages.\n        *args: args\n            The arguments required by the event.\n        **kwargs: kwargs\n            Options for sending. These are:\n\n            now: boolean\n                Send the event now"
  },
  {
    "code": "def approx_contains(self, other, atol):\n        other = np.atleast_1d(other)\n        return (other.shape == (self.ndim,) and\n                all(np.any(np.isclose(vector, coord, atol=atol, rtol=0.0))\n                    for vector, coord in zip(self.coord_vectors, other)))",
    "docstring": "Test if ``other`` belongs to this grid up to a tolerance.\n\n        Parameters\n        ----------\n        other : `array-like` or float\n            The object to test for membership in this grid\n        atol : float\n            Allow deviations up to this number in absolute value\n            per vector entry.\n\n        Examples\n        --------\n        >>> g = RectGrid([0, 1], [-1, 0, 2])\n        >>> g.approx_contains([0, 0], atol=0.0)\n        True\n        >>> [0, 0] in g  # equivalent\n        True\n        >>> g.approx_contains([0.1, -0.1], atol=0.0)\n        False\n        >>> g.approx_contains([0.1, -0.1], atol=0.15)\n        True"
  },
  {
    "code": "def repo(name: str, owner: str) -> snug.Query[dict]:\n    request = snug.GET(f'https://api.github.com/repos/{owner}/{name}')\n    response = yield request\n    return json.loads(response.content)",
    "docstring": "a repo lookup by owner and name"
  },
  {
    "code": "def _check_span_id(self, span_id):\n        if span_id is None:\n            return None\n        assert isinstance(span_id, six.string_types)\n        if span_id is INVALID_SPAN_ID:\n            logging.warning(\n                'Span_id {} is invalid (cannot be all zero)'.format(span_id))\n            self.from_header = False\n            return None\n        match = SPAN_ID_PATTERN.match(span_id)\n        if match:\n            return span_id\n        else:\n            logging.warning(\n                'Span_id {} does not the match the '\n                'required format'.format(span_id))\n            self.from_header = False\n            return None",
    "docstring": "Check the format of the span_id to ensure it is 16-character hex\n        value representing a 64-bit number. If span_id is invalid, logs a\n        warning message and returns None\n\n        :type span_id: str\n        :param span_id: Identifier for the span, unique within a span.\n\n        :rtype: str\n        :returns: Span_id for the current span."
  },
  {
    "code": "def events(self):\n        if not self.event_reflector:\n            return []\n        events = []\n        for event in self.event_reflector.events:\n            if event.involved_object.name != self.pod_name:\n                continue\n            if self._last_event and event.metadata.uid == self._last_event:\n                events = []\n            else:\n                events.append(event)\n        return events",
    "docstring": "Filter event-reflector to just our events\n\n        Returns list of all events that match our pod_name\n        since our ._last_event (if defined).\n        ._last_event is set at the beginning of .start()."
  },
  {
    "code": "def main(ctx, connection):\n    ctx.obj = Manager(connection=connection)\n    ctx.obj.bind()",
    "docstring": "Command line interface for PyBEL."
  },
  {
    "code": "def run_stop_backup(cls):\n        def handler(popen):\n            assert popen.returncode != 0\n            raise UserException('Could not stop hot backup')\n        return cls._dict_transform(psql_csv_run(\n                \"SELECT file_name, \"\n                \"  lpad(file_offset::text, 8, '0') AS file_offset \"\n                \"FROM pg_{0}file_name_offset(\"\n                \"  pg_stop_backup())\".format(cls._wal_name()),\n                error_handler=handler))",
    "docstring": "Stop a hot backup, if it was running, or error\n\n        Return the last WAL file name and position that is required to\n        gain consistency on the captured heap."
  },
  {
    "code": "def get_out_of_order(list_of_numbers):\n  result = []\n  for i in range(len(list_of_numbers)):\n    if i == 0:\n      continue\n    if list_of_numbers[i] < list_of_numbers[i - 1]:\n      result.append((list_of_numbers[i - 1], list_of_numbers[i]))\n  return result",
    "docstring": "Returns elements that break the monotonically non-decreasing trend.\n\n  This is used to find instances of global step values that are \"out-of-order\",\n  which may trigger TensorBoard event discarding logic.\n\n  Args:\n    list_of_numbers: A list of numbers.\n\n  Returns:\n    A list of tuples in which each tuple are two elements are adjacent, but the\n    second element is lower than the first."
  },
  {
    "code": "def _choose_capture_side(self):\n        ALWAYS_RUNNING_NODES_TYPE = (\"cloud\", \"nat\", \"ethernet_switch\", \"ethernet_hub\")\n        for node in self._nodes:\n            if node[\"node\"].compute.id == \"local\" and node[\"node\"].node_type in ALWAYS_RUNNING_NODES_TYPE and node[\"node\"].status == \"started\":\n                return node\n        for node in self._nodes:\n            if node[\"node\"].node_type in ALWAYS_RUNNING_NODES_TYPE and node[\"node\"].status == \"started\":\n                return node\n        for node in self._nodes:\n            if node[\"node\"].compute.id == \"local\" and node[\"node\"].status == \"started\":\n                return node\n        for node in self._nodes:\n            if node[\"node\"].node_type and node[\"node\"].status == \"started\":\n                return node\n        raise aiohttp.web.HTTPConflict(text=\"Cannot capture because there is no running device on this link\")",
    "docstring": "Run capture on the best candidate.\n\n        The ideal candidate is a node who on controller server and always\n        running (capture will not be cut off)\n\n        :returns: Node where the capture should run"
  },
  {
    "code": "def verify(path):\n        valid = False\n        try:\n            zf = zipfile.ZipFile(path)\n        except (zipfile.BadZipfile, IsADirectoryError):\n            pass\n        else:\n            names = sorted(zf.namelist())\n            names = [nn for nn in names if nn.endswith(\".tif\")]\n            names = [nn for nn in names if nn.startswith(\"SID PHA\")]\n            for name in names:\n                with zf.open(name) as pt:\n                    fd = io.BytesIO(pt.read())\n                    if SingleTifPhasics.verify(fd):\n                        valid = True\n                        break\n            zf.close()\n        return valid",
    "docstring": "Verify that `path` is a zip file with Phasics TIFF files"
  },
  {
    "code": "def visit_global(self, node, parent):\n        newnode = nodes.Global(\n            node.names,\n            getattr(node, \"lineno\", None),\n            getattr(node, \"col_offset\", None),\n            parent,\n        )\n        if self._global_names:\n            for name in node.names:\n                self._global_names[-1].setdefault(name, []).append(newnode)\n        return newnode",
    "docstring": "visit a Global node to become astroid"
  },
  {
    "code": "def _decrypt_entity(entity, encrypted_properties_list, content_encryption_key, entityIV, isJavaV1):\n    _validate_not_none('entity', entity)\n    decrypted_entity = deepcopy(entity)\n    try:\n        for property in entity.keys():\n            if property in encrypted_properties_list:\n                value = entity[property]\n                propertyIV = _generate_property_iv(entityIV,\n                                                   entity['PartitionKey'], entity['RowKey'],\n                                                   property, isJavaV1)\n                cipher = _generate_AES_CBC_cipher(content_encryption_key,\n                                                  propertyIV)\n                decryptor = cipher.decryptor()\n                decrypted_data = (decryptor.update(value.value) + decryptor.finalize())\n                unpadder = PKCS7(128).unpadder()\n                decrypted_data = (unpadder.update(decrypted_data) + unpadder.finalize())\n                decrypted_data = decrypted_data.decode('utf-8')\n                decrypted_entity[property] = decrypted_data\n        decrypted_entity.pop('_ClientEncryptionMetadata1')\n        decrypted_entity.pop('_ClientEncryptionMetadata2')\n        return decrypted_entity\n    except:\n        raise AzureException(_ERROR_DECRYPTION_FAILURE)",
    "docstring": "Decrypts the specified entity using AES256 in CBC mode with 128 bit padding. Unwraps the CEK \n    using either the specified KEK or the key returned by the key_resolver. Properties \n    specified in the encrypted_properties_list, will be decrypted and decoded to utf-8 strings.\n\n    :param entity:\n        The entity being retrieved and decrypted. Could be a dict or an entity object.\n    :param list encrypted_properties_list:\n        The encrypted list of all the properties that are encrypted.\n    :param bytes[] content_encryption_key:\n        The key used internally to encrypt the entity. Extrated from the entity metadata.\n    :param bytes[] entityIV:\n        The intialization vector used to seed the encryption algorithm. Extracted from the\n        entity metadata.\n    :return: The decrypted entity\n    :rtype: Entity"
  },
  {
    "code": "def parse_feature(obj):\n    if hasattr(obj, '__geo_interface__'):\n        gi = obj.__geo_interface__\n        if gi['type'] in geom_types:\n            return wrap_geom(gi)\n        elif gi['type'] == 'Feature':\n            return gi\n    try:\n        shape = wkt.loads(obj)\n        return wrap_geom(shape.__geo_interface__)\n    except (ReadingError, TypeError, AttributeError):\n        pass\n    try:\n        shape = wkb.loads(obj)\n        return wrap_geom(shape.__geo_interface__)\n    except (ReadingError, TypeError):\n        pass\n    try:\n        if obj['type'] in geom_types:\n            return wrap_geom(obj)\n        elif obj['type'] == 'Feature':\n            return obj\n    except (AssertionError, TypeError):\n        pass\n    raise ValueError(\"Can't parse %s as a geojson Feature object\" % obj)",
    "docstring": "Given a python object\n    attemp to a GeoJSON-like Feature from it"
  },
  {
    "code": "def complete_contexts(self):\n        if self._complete_contexts:\n            return self._complete_contexts\n        self.context()\n        return self._complete_contexts",
    "docstring": "Return a list of interfaces that have satisfied contexts."
  },
  {
    "code": "def remove_component(self, entity, component_type):\n        relation = self._get_relation(component_type)\n        del relation[entity]\n        self._entities_with(component_type).remove(entity)",
    "docstring": "Remove the component of component_type from entity.\n\n        Long-hand for :func:`essence.Entity.remove`.\n\n        :param entity: entity to associate\n        :type entity: :class:`essence.Entity`\n        :param component_type: Type of component\n        :type component_type: The :class:`type` of a :class:`Component` subclass"
  },
  {
    "code": "def run_check(self, check, argument_names):\n        arguments = []\n        for name in argument_names:\n            arguments.append(getattr(self, name))\n        return check(*arguments)",
    "docstring": "Run a check plugin."
  },
  {
    "code": "def dem(bounds, src_crs, dst_crs, out_file, resolution):\n    if not dst_crs:\n        dst_crs = \"EPSG:3005\"\n    bcdata.get_dem(bounds, out_file=out_file, src_crs=src_crs, dst_crs=dst_crs, resolution=resolution)",
    "docstring": "Dump BC DEM to TIFF"
  },
  {
    "code": "def attach(self,\n               image_in,\n               sampler=None,\n               show=True):\n        if len(image_in.shape) < 3:\n            raise ValueError('Image must be atleast 3D')\n        if sampler is None:\n            temp_sampler = self.sampler\n        else:\n            temp_sampler = sampler\n        slicer = SlicePicker(image_in=image_in,\n                             view_set=self.view_set,\n                             num_slices=self.num_slices,\n                             sampler=temp_sampler)\n        try:\n            for img_obj, slice_data in zip(self.images, slicer.get_slices()):\n                img_obj.set_data(slice_data)\n        except:\n            self._data_attached = False\n            raise ValueError('unable to attach the given image data to current collage')\n        else:\n            self._data_attached = True\n        if show:\n            self.show()",
    "docstring": "Attaches the relevant cross-sections to each axis.\n\n        Parameters\n        ----------\n\n        attach_image : ndarray\n            The image to be attached to the collage, once it is created.\n            Must be atleast 3d.\n\n        sampler : str or list or callable\n            selection strategy: to identify the type of sampling done to select the slices to return.\n            All sampling is done between the first and last non-empty slice in that view/dimension.\n\n            - if 'linear' : linearly spaced slices\n            - if list, it is treated as set of percentages at which slices to be sampled\n                (must be in the range of [1-100], not [0-1]).\n                This could be used to more/all slices in the middle e.g. range(40, 60, 5)\n                    or at the end e.g. [ 5, 10, 15, 85, 90, 95]\n            - if callable, it must take a 2D image of arbitray size, return True/False\n                to indicate whether to select that slice or not.\n                Only non-empty slices (atleas one non-zero voxel) are provided as input.\n                Simple examples for callable could be based on\n                1) percentage of non-zero voxels > x etc\n                2) presence of desired texture ?\n                3) certain properties of distribution (skewe: dark/bright, energy etc) etc\n\n                If the sampler returns more than requested `num_slices`,\n                    only the first num_slices will be selected.\n\n        show : bool\n            Flag to request immediate display of collage"
  },
  {
    "code": "def install(self, pip_args=None):\n        if path.isdir(self.env):\n            print_pretty(\"<FG_RED>This seems to already be installed.<END>\")\n        else:\n            print_pretty(\"<FG_BLUE>Creating environment {}...<END>\\n\".format(self.env))\n            self.create_env()\n            self.install_program(pip_args)\n            self.create_links()",
    "docstring": "Install the program and put links in place."
  },
  {
    "code": "async def create_virtual_environment(loop=None):\n    tmp_dir = tempfile.mkdtemp()\n    venv_dir = os.path.join(tmp_dir, VENV_NAME)\n    proc1 = await asyncio.create_subprocess_shell(\n        'virtualenv {}'.format(venv_dir), loop=loop)\n    await proc1.communicate()\n    if sys.platform == 'win32':\n        python = os.path.join(venv_dir, 'Scripts', 'python.exe')\n    else:\n        python = os.path.join(venv_dir, 'bin', 'python')\n    venv_site_pkgs = install_dependencies(python)\n    log.info(\"Created virtual environment at {}\".format(venv_dir))\n    return venv_dir, python, venv_site_pkgs",
    "docstring": "Create a virtual environment, and return the path to the virtual env\n    directory, which should contain a \"bin\" directory with the `python` and\n    `pip` binaries that can be used to a test install of a software package.\n\n    :return: the path to the virtual environment, its python, and its site pkgs"
  },
  {
    "code": "def run(self, messages, env=None):\n        if self.args.score or self.args.unlock or self.args.testing:\n            return\n        tests = self.assignment.specified_tests\n        for test in tests:\n            if self.args.suite and hasattr(test, 'suites'):\n                test.run_only = int(self.args.suite)\n                try:\n                    suite = test.suites[int(self.args.suite) - 1]\n                except IndexError as e:\n                    sys.exit(('python3 ok: error: '\n                        'Suite number must be valid.({})'.format(len(test.suites))))\n                if self.args.case:\n                    suite.run_only = [int(c) for c in self.args.case]\n        grade(tests, messages, env, verbose=self.args.verbose)",
    "docstring": "Run gradeable tests and print results and return analytics.\n\n        RETURNS:\n        dict; a mapping of test name -> JSON-serializable object. It is up to\n        each test to determine what kind of data it wants to return as\n        significant for analytics. However, all tests must include the number\n        passed, the number of locked tests and the number of failed tests."
  },
  {
    "code": "def get_external_account(resource_root, name, view=None):\n  return call(resource_root.get,\n      EXTERNAL_ACCOUNT_FETCH_PATH % (\"account\", name,),\n      ApiExternalAccount, False, params=view and dict(view=view) or None)",
    "docstring": "Lookup an external account by name\n  @param resource_root: The root Resource object.\n  @param name: Account name\n  @param view: View\n  @return: An ApiExternalAccount object"
  },
  {
    "code": "def stop(self):\n        self.working = False\n        for w in self.workers:\n            w.join()\n        self.workers = []",
    "docstring": "Stops the worker threads and waits for them to finish"
  },
  {
    "code": "def focus(self, force_first=False, force_last=False, force_column=None,\n              force_widget=None):\n        self._has_focus = True\n        if force_widget is not None and force_column is not None:\n            self._live_col = force_column\n            self._live_widget = force_widget\n        elif force_first:\n            self._live_col = 0\n            self._live_widget = -1\n            self._find_next_widget(1)\n        elif force_last:\n            self._live_col = len(self._columns) - 1\n            self._live_widget = len(self._columns[self._live_col])\n            self._find_next_widget(-1)\n        self._columns[self._live_col][self._live_widget].focus()",
    "docstring": "Call this to give this Layout the input focus.\n\n        :param force_first: Optional parameter to force focus to first widget.\n        :param force_last: Optional parameter to force focus to last widget.\n        :param force_column: Optional parameter to mandate the new column index.\n        :param force_widget: Optional parameter to mandate the new widget index.\n\n        The force_column and force_widget parameters must both be set together or they will\n        otherwise be ignored.\n\n        :raises IndexError: if a force option specifies a bad column or widget, or if the whole\n            Layout is readonly."
  },
  {
    "code": "def get_query_schema(self, job_id):\n        query_reply = self.get_query_results(job_id, offset=0, limit=0)\n        if not query_reply['jobComplete']:\n            logger.warning('BigQuery job %s not complete' % job_id)\n            raise UnfinishedQueryException()\n        return query_reply['schema']['fields']",
    "docstring": "Retrieve the schema of a query by job id.\n\n        Parameters\n        ----------\n        job_id : str\n            The job_id that references a BigQuery query\n\n        Returns\n        -------\n        list\n            A ``list`` of ``dict`` objects that represent the schema."
  },
  {
    "code": "def dbmax_stddev(self, value=None):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type float '\n                                 'for field `dbmax_stddev`'.format(value))\n        self._dbmax_stddev = value",
    "docstring": "Corresponds to IDD Field `dbmax_stddev`\n        Standard deviation of extreme annual maximum dry-bulb temperature\n\n        Args:\n            value (float): value for IDD Field `dbmax_stddev`\n                Unit: C\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def attachable(name, path=None):\n    cachekey = 'lxc.attachable{0}{1}'.format(name, path)\n    try:\n        return __context__[cachekey]\n    except KeyError:\n        _ensure_exists(name, path=path)\n        log.debug('Checking if LXC container %s is attachable', name)\n        cmd = 'lxc-attach'\n        if path:\n            cmd += ' -P {0}'.format(pipes.quote(path))\n        cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)\n        result = __salt__['cmd.retcode'](cmd,\n                                         python_shell=False,\n                                         output_loglevel='quiet',\n                                         ignore_retcode=True) == 0\n        __context__[cachekey] = result\n    return __context__[cachekey]",
    "docstring": "Return True if the named container can be attached to via the lxc-attach\n    command\n\n    path\n        path to the container parent\n        default: /var/lib/lxc (system default)\n\n        .. versionadded:: 2015.8.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'minion' lxc.attachable ubuntu"
  },
  {
    "code": "def _try_fetch(self, size=None):\n        if self._query_job is None:\n            raise exceptions.InterfaceError(\n                \"No query results: execute() must be called before fetch.\"\n            )\n        is_dml = (\n            self._query_job.statement_type\n            and self._query_job.statement_type.upper() != \"SELECT\"\n        )\n        if is_dml:\n            self._query_data = iter([])\n            return\n        if self._query_data is None:\n            client = self.connection._client\n            rows_iter = client.list_rows(\n                self._query_job.destination,\n                selected_fields=self._query_job._query_results.schema,\n                page_size=self.arraysize,\n            )\n            self._query_data = iter(rows_iter)",
    "docstring": "Try to start fetching data, if not yet started.\n\n        Mutates self to indicate that iteration has started."
  },
  {
    "code": "def conj(self, out=None):\n        if out is None:\n            return self.space.element(self.tensor.conj())\n        else:\n            self.tensor.conj(out=out.tensor)\n            return out",
    "docstring": "Complex conjugate of this element.\n\n        Parameters\n        ----------\n        out : `DiscreteLpElement`, optional\n            Element to which the complex conjugate is written.\n            Must be an element of this element's space.\n\n        Returns\n        -------\n        out : `DiscreteLpElement`\n            The complex conjugate element. If ``out`` is provided,\n            the returned object is a reference to it.\n\n        Examples\n        --------\n        >>> discr = uniform_discr(0, 1, 4, dtype=complex)\n        >>> x = discr.element([5+1j, 3, 2-2j, 1j])\n        >>> y = x.conj()\n        >>> print(y)\n        [ 5.-1.j,  3.-0.j,  2.+2.j,  0.-1.j]\n\n        The out parameter allows you to avoid a copy:\n\n        >>> z = discr.element()\n        >>> z_out = x.conj(out=z)\n        >>> print(z)\n        [ 5.-1.j,  3.-0.j,  2.+2.j,  0.-1.j]\n        >>> z_out is z\n        True\n\n        It can also be used for in-place conjugation:\n\n        >>> x_out = x.conj(out=x)\n        >>> print(x)\n        [ 5.-1.j,  3.-0.j,  2.+2.j,  0.-1.j]\n        >>> x_out is x\n        True"
  },
  {
    "code": "def unpack_rgb(packed):\n    orig_shape = None\n    if isinstance(packed, np.ndarray):\n        assert packed.dtype == int\n        orig_shape = packed.shape\n        packed = packed.reshape((-1, 1))\n    rgb = ((packed >> 16) & 0xff,\n           (packed >> 8) & 0xff,\n           (packed) & 0xff)\n    if orig_shape is None:\n        return rgb\n    else:\n        return np.hstack(rgb).reshape(orig_shape + (3,))",
    "docstring": "Unpacks a single integer or array of integers into one or more\n24-bit RGB values."
  },
  {
    "code": "def as_string(self):\n        if self.headers_only:\n            self.msgobj = self._get_content()\n        from email.generator import Generator\n        fp = StringIO()\n        g = Generator(fp, maxheaderlen=60)\n        g.flatten(self.msgobj)\n        text = fp.getvalue()\n        return text",
    "docstring": "Get the underlying message object as a string"
  },
  {
    "code": "def _initLayerCtors(self):\n        ctors = {\n            'lmdb': s_lmdblayer.LmdbLayer,\n            'remote': s_remotelayer.RemoteLayer,\n        }\n        self.layrctors.update(**ctors)",
    "docstring": "Registration for built-in Layer ctors"
  },
  {
    "code": "def parse_multipart_upload_result(data):\n    root = S3Element.fromstring('CompleteMultipartUploadResult', data)\n    return MultipartUploadResult(\n        root.get_child_text('Bucket'),\n        root.get_child_text('Key'),\n        root.get_child_text('Location'),\n        root.get_etag_elem()\n    )",
    "docstring": "Parser for complete multipart upload response.\n\n    :param data: Response data for complete multipart upload.\n    :return: :class:`MultipartUploadResult <MultipartUploadResult>`."
  },
  {
    "code": "def integrate(self, function, lower_bound, upper_bound):\n        ret = 0.0\n        n = self.nsteps\n        xStep = (float(upper_bound) - float(lower_bound)) / float(n)\n        self.log_info(\"xStep\" + str(xStep))\n        x = lower_bound\n        val1 = function(x)\n        self.log_info(\"val1: \" + str(val1))\n        for i in range(n):\n            x = (i + 1) * xStep + lower_bound\n            self.log_info(\"x: \" + str(x))\n            val2 = function(x)\n            self.log_info(\"val2: \" + str(val2))\n            ret += 0.5 * xStep * (val1 + val2)\n            val1 = val2\n        return ret",
    "docstring": "Calculates the integral of the given one dimensional function\n        in the interval from lower_bound to upper_bound, with the simplex integration method."
  },
  {
    "code": "def drdlat(r, lon, lat):\n    r = ctypes.c_double(r)\n    lon = ctypes.c_double(lon)\n    lat = ctypes.c_double(lat)\n    jacobi = stypes.emptyDoubleMatrix()\n    libspice.drdlat_c(r, lon, lat, jacobi)\n    return stypes.cMatrixToNumpy(jacobi)",
    "docstring": "Compute the Jacobian of the transformation from latitudinal to\n    rectangular coordinates.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdlat_c.html\n\n    :param r: Distance of a point from the origin.\n    :type r: float\n    :param lon: Angle of the point from the XZ plane in radians.\n    :type lon: float\n    :param lat: Angle of the point from the XY plane in radians.\n    :type lat: float\n    :return: Matrix of partial derivatives.\n    :rtype: 3x3-Element Array of floats"
  },
  {
    "code": "def aa_counts(aln, weights=None, gap_chars='-.'):\n    if weights is None:\n        counts = Counter()\n        for rec in aln:\n            seq_counts = Counter(str(rec.seq))\n            counts.update(seq_counts)\n    else:\n        if weights == True:\n            weights = sequence_weights(aln)\n        else:\n            assert len(weights) == len(aln), (\n                \"Length mismatch: weights = %d, alignment = %d\"\n                % (len(weights), len(aln)))\n        counts = defaultdict(float)\n        for col in zip(*aln):\n            for aa, wt in zip(col, weights):\n                counts[aa] += wt\n    for gap_char in gap_chars:\n        if gap_char in counts:\n            del counts[gap_char]\n    return counts",
    "docstring": "Calculate the amino acid frequencies in a set of SeqRecords.\n\n    Weights for each sequence in the alignment can be given as a list/tuple,\n    usually calculated with the sequence_weights function. For convenience, you\n    can also pass \"weights=True\" and the weights will be calculated with\n    sequence_weights here."
  },
  {
    "code": "def join(self, timeout_s=None):\n    if not self.thread:\n      return False\n    self.thread.join(timeout_s)\n    return self.running",
    "docstring": "Joins blocking until the interval ends or until timeout is reached.\n\n    Args:\n      timeout_s: The time in seconds to wait, defaults to forever.\n    Returns:\n      True if the interval is still running and we reached the timeout."
  },
  {
    "code": "def to_text(sentence):\n    text = \"\"\n    for i, tok in enumerate(sentence.token):\n        if i != 0:\n            text += tok.before\n        text += tok.word\n    return text",
    "docstring": "Helper routine that converts a Sentence protobuf to a string from\n    its tokens."
  },
  {
    "code": "def login(self, username, password=None, blob=None, zeroconf=None):\n        username = utils.to_char(username)\n        if password is not None:\n            password = utils.to_char(password)\n            spotifyconnect.Error.maybe_raise(\n                lib.SpConnectionLoginPassword(\n                    username, password))\n        elif blob is not None:\n            blob = utils.to_char(blob)\n            spotifyconnect.Error.maybe_raise(\n                lib.SpConnectionLoginBlob(username, blob))\n        elif zeroconf is not None:\n            spotifyconnect.Error.maybe_raise(\n                lib.SpConnectionLoginZeroConf(\n                    username, *zeroconf))\n        else:\n            raise AttributeError(\n                \"Must specify a login method (password, blob or zeroconf)\")",
    "docstring": "Authenticate to Spotify's servers.\n\n        You can login with one of three combinations:\n\n        - ``username`` and ``password``\n        - ``username`` and ``blob``\n        - ``username`` and ``zeroconf``\n\n        To get the ``blob`` string, you must once log in with ``username`` and\n        ``password``. You'll then get the ``blob`` string passed to the\n        :attr:`~ConnectionCallbacks.new_credentials` callback."
  },
  {
    "code": "def get_labels(self, depth=None):\n        labels = libCopy.deepcopy(self.labels)\n        if depth is None or depth > 0:\n            for element in self.elements:\n                if isinstance(element, CellReference):\n                    labels.extend(\n                        element.get_labels(None if depth is None else depth -\n                                           1))\n                elif isinstance(element, CellArray):\n                    labels.extend(\n                        element.get_labels(None if depth is None else depth -\n                                           1))\n        return labels",
    "docstring": "Returns a list with a copy of the labels in this cell.\n\n        Parameters\n        ----------\n        depth : integer or ``None``\n            If not ``None``, defines from how many reference levels to\n            retrieve labels from.\n\n        Returns\n        -------\n        out : list of ``Label``\n            List containing the labels in this cell and its references."
  },
  {
    "code": "def get(self, name, hint):\n        if name:\n            return name\n        if hint not in self._counter:\n            self._counter[hint] = 0\n        name = '%s%d' % (hint, self._counter[hint])\n        self._counter[hint] += 1\n        return name",
    "docstring": "Get the canonical name for a symbol.\n\n        This is the default implementation.\n        If the user specifies a name,\n        the user-specified name will be used.\n\n        When user does not specify a name, we automatically generate a\n        name based on the hint string.\n\n        Parameters\n        ----------\n        name : str or None\n            The name specified by the user.\n\n        hint : str\n            A hint string, which can be used to generate name.\n\n        Returns\n        -------\n        full_name : str\n            A canonical name for the symbol."
  },
  {
    "code": "def distill(p, K):\n    q = p.reshape(p.shape[0], -1)\n    for _ in range(K):\n        _accupy.distill(q)\n    return q.reshape(p.shape)",
    "docstring": "Algorithm 4.3. Error-free vector transformation for summation.\n\n    The vector p is transformed without changing the sum, and p_n is replaced\n    by float(sum(p)). Kahan [21] calls this a 'distillation algorithm.'"
  },
  {
    "code": "def reset(self):\n        self._components = OrderedDict()\n        self.clear_selections()\n        self._logger.info(\"<block: %s> reset component list\" % (self.name))",
    "docstring": "Removes all the components of the block"
  },
  {
    "code": "def handle_call_response(self, result, node):\n        if not result[0]:\n            log.warning(\"no response from %s, removing from router\", node)\n            self.router.remove_contact(node)\n            return result\n        log.info(\"got successful response from %s\", node)\n        self.welcome_if_new(node)\n        return result",
    "docstring": "If we get a response, add the node to the routing table.  If\n        we get no response, make sure it's removed from the routing table."
  },
  {
    "code": "def pop_event(self):\n    with self.lock:\n      if not self.events:\n        raise ValueError('no events queued')\n      return self.events.popleft()",
    "docstring": "Pop the next queued event from the queue.\n\n    :raise ValueError: If there is no event queued."
  },
  {
    "code": "def create_env_section(pairs, name):\n    section = ['%' + name ]\n    for pair in pairs:\n        section.append(\"export %s\" %pair)\n    return section",
    "docstring": "environment key value pairs need to be joined by an equal, and \n       exported at the end.\n\n      Parameters\n      ==========\n      section: the list of values to return as a parsed list of lines\n      name: the name of the section to write (e.g., files)"
  },
  {
    "code": "def decimal_format(value, TWOPLACES=Decimal(100) ** -2):\n    'Format a decimal.Decimal like to 2 decimal places.'\n    if not isinstance(value, Decimal):\n        value = Decimal(str(value))\n    return value.quantize(TWOPLACES)",
    "docstring": "Format a decimal.Decimal like to 2 decimal places."
  },
  {
    "code": "def expiring_memoize(obj):\n    cache = obj.cache = {}\n    last_access = obj.last_access = defaultdict(int)\n    @wraps(obj)\n    def memoizer(*args, **kwargs):\n        key = str(args) + str(kwargs)\n        if last_access[key] and last_access[key] + 10 < time():\n            if key in cache:\n                del cache[key]\n        last_access[key] = time()\n        if key not in cache:\n            cache[key] = obj(*args, **kwargs)\n        return cache[key]\n    return memoizer",
    "docstring": "Like memoize, but forgets after 10 seconds."
  },
  {
    "code": "def run_simulation(c1, c2):\n    print('running simulation...')\n    traits = character.CharacterCollection(character.fldr)\n    c1 = traits.generate_random_character()\n    c2 = traits.generate_random_character()\n    print(c1)\n    print(c2)\n    rules = battle.BattleRules(battle.rules_file)\n    b = battle.Battle(c1, c2, traits, rules, print_console='Yes')\n    print(b.status)",
    "docstring": "using character and planet, run the simulation"
  },
  {
    "code": "def extract_sort(self, params):\n        sorts = params.pop('sort', [])\n        sorts = [sorts] if isinstance(sorts, basestring) else sorts\n        sorts = [(s[1:], 'desc')\n                 if s.startswith('-') else (s, 'asc')\n                 for s in sorts]\n        self.sorts = [\n            {self.adapter.sorts[s]: d}\n            for s, d in sorts if s in self.adapter.sorts\n        ]",
    "docstring": "Extract and build sort query from parameters"
  },
  {
    "code": "def results(self, use_cache=True, dialect=None, billing_tier=None):\n    return self._materialization.results(use_cache=use_cache, dialect=dialect,\n                                         billing_tier=billing_tier)",
    "docstring": "Materialize the view synchronously.\n\n    If you require more control over the execution, use execute() or execute_async().\n\n    Args:\n      use_cache: whether to use cached results or not.\n      dialect : {'legacy', 'standard'}, default 'legacy'\n          'legacy' : Use BigQuery's legacy SQL dialect.\n          'standard' : Use BigQuery's standard SQL (beta), which is\n          compliant with the SQL 2011 standard.\n      billing_tier: Limits the billing tier for this job. Queries that have resource\n          usage beyond this tier will fail (without incurring a charge). If unspecified, this\n          will be set to your project default. This can also be used to override your\n          project-wide default billing tier on a per-query basis.\n    Returns:\n      A QueryResultsTable containing the result set.\n    Raises:\n      Exception if the query could not be executed or query response was malformed."
  },
  {
    "code": "def minifyspace(parser, token):\n    nodelist = parser.parse(('endminifyspace',))\n    parser.delete_first_token()\n    return MinifiedNode(nodelist)",
    "docstring": "Removes whitespace including tab and newline characters.\n\n    Do not use this if you are using a <pre> tag.\n\n    Example usage::\n\n        {% minifyspace %}\n            <p>\n                <a title=\"foo\"\n                   href=\"foo/\">\n                     Foo\n                </a>\n            </p>\n        {% endminifyspace %}\n\n    This example would return this HTML::\n\n        <p><a title=\"foo\" href=\"foo/\">Foo</a></p>"
  },
  {
    "code": "def _drop_remaining_rules(self, *rules):\n        if rules:\n            for rule in rules:\n                try:\n                    self._remaining_rules.remove(rule)\n                except ValueError:\n                    pass\n        else:\n            self._remaining_rules = []",
    "docstring": "Drops rules from the queue of the rules that still need to be\n            evaluated for the currently processed field.\n            If no arguments are given, the whole queue is emptied."
  },
  {
    "code": "def outer_product_sum(A, B=None):\n    if B is None:\n        B = A\n    outer = np.einsum('ij,ik->ijk', A, B)\n    return np.sum(outer, axis=0)",
    "docstring": "Computes the sum of the outer products of the rows in A and B\n\n        P = \\Sum {A[i] B[i].T} for i in 0..N\n\n        Notionally:\n\n        P = 0\n        for y in A:\n            P += np.outer(y, y)\n\n    This is a standard computation for sigma points used in the UKF, ensemble\n    Kalman filter, etc., where A would be the residual of the sigma points\n    and the filter's state or measurement.\n\n    The computation is vectorized, so it is much faster than the for loop\n    for large A.\n\n    Parameters\n    ----------\n    A : np.array, shape (M, N)\n        rows of N-vectors to have the outer product summed\n\n    B : np.array, shape (M, N)\n        rows of N-vectors to have the outer product summed\n        If it is `None`, it is set to A.\n\n    Returns\n    -------\n    P : np.array, shape(N, N)\n        sum of the outer product of the rows of A and B\n\n    Examples\n    --------\n\n    Here sigmas is of shape (M, N), and x is of shape (N). The two sets of\n    code compute the same thing.\n\n    >>> P = outer_product_sum(sigmas - x)\n    >>>\n    >>> P = 0\n    >>> for s in sigmas:\n    >>>     y = s - x\n    >>>     P += np.outer(y, y)"
  },
  {
    "code": "def iterate(self):\n        if not self._inLoop:\n            raise RuntimeError('run loop not started')\n        elif self._driverLoop:\n            raise RuntimeError('iterate not valid in driver run loop')\n        self.proxy.iterate()",
    "docstring": "Must be called regularly when using an external event loop."
  },
  {
    "code": "def is_super_admin(self, req):\n        return req.headers.get('x-auth-admin-user') == '.super_admin' and \\\n            self.super_admin_key and \\\n            req.headers.get('x-auth-admin-key') == self.super_admin_key",
    "docstring": "Returns True if the admin specified in the request represents the\n        .super_admin.\n\n        :param req: The swob.Request to check.\n        :param returns: True if .super_admin."
  },
  {
    "code": "def has_parent_vaults(self, vault_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.has_parent_catalogs(catalog_id=vault_id)\n        return self._hierarchy_session.has_parents(id_=vault_id)",
    "docstring": "Tests if the ``Vault`` has any parents.\n\n        arg:    vault_id (osid.id.Id): a vault ``Id``\n        return: (boolean) - ``true`` if the vault has parents, ``false``\n                otherwise\n        raise:  NotFound - ``vault_id`` is not found\n        raise:  NullArgument - ``vault_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def encrypt_account(self, id):\n        for key in self.secured_field_names:\n            value = self.parser.get(id, key)\n            self.parser.set_secure(id, key, value)\n        return self",
    "docstring": "Make sure that certain fields are encrypted."
  },
  {
    "code": "def get_clamav_conf(filename):\n    if os.path.isfile(filename):\n        return ClamavConfig(filename)\n    log.warn(LOG_PLUGIN, \"No ClamAV config file found at %r.\", filename)",
    "docstring": "Initialize clamav configuration."
  },
  {
    "code": "def _parse(root):\n    if root.tag == \"nil-classes\":\n        return []\n    elif root.get(\"type\") == \"array\":\n        return [_parse(child) for child in root]\n    d = {}\n    for child in root:\n        type = child.get(\"type\") or \"string\"\n        if child.get(\"nil\"):\n            value = None\n        elif type == \"boolean\":\n            value = True if child.text.lower() == \"true\" else False\n        elif type == \"dateTime\":\n            value = iso8601.parse_date(child.text)\n        elif type == \"decimal\":\n            value = decimal.Decimal(child.text)\n        elif type == \"integer\":\n            value = int(child.text)\n        else:\n            value = child.text\n        d[child.tag] = value\n    return d",
    "docstring": "Recursively convert an Element into python data types"
  },
  {
    "code": "def _check_vbox_port_forwarding(self):\n        result = yield from self._execute(\"showvminfo\", [self._vmname, \"--machinereadable\"])\n        for info in result.splitlines():\n            if '=' in info:\n                name, value = info.split('=', 1)\n                if name.startswith(\"Forwarding\") and value.strip('\"').startswith(\"GNS3VM\"):\n                    return True\n        return False",
    "docstring": "Checks if the NAT port forwarding rule exists.\n\n        :returns: boolean"
  },
  {
    "code": "def delete_feed(self, pid):\n        logger.info(\"delete_feed(pid=\\\"%s\\\") [lid=%s]\", pid, self.__lid)\n        return self.__delete_point(R_FEED, pid)",
    "docstring": "Delete a feed, identified by its local id.\n\n        Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)\n        containing the error if the infrastructure detects a problem\n\n        Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)\n        if there is a communications problem between you and the infrastructure\n\n        `pid` (required) (string) local identifier of your feed you want to delete"
  },
  {
    "code": "def active():\n    result = __salt__['cmd.run']('tuned-adm active')\n    pattern = re.compile(r)\n    match = re.match(pattern, result)\n    return '{0}'.format(match.group('profile'))",
    "docstring": "Return current active profile\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' tuned.active"
  },
  {
    "code": "def _set_tz(values, tz, preserve_UTC=False, coerce=False):\n    if tz is not None:\n        name = getattr(values, 'name', None)\n        values = values.ravel()\n        tz = timezones.get_timezone(_ensure_decoded(tz))\n        values = DatetimeIndex(values, name=name)\n        if values.tz is None:\n            values = values.tz_localize('UTC').tz_convert(tz)\n        if preserve_UTC:\n            if tz == 'UTC':\n                values = list(values)\n    elif coerce:\n        values = np.asarray(values, dtype='M8[ns]')\n    return values",
    "docstring": "coerce the values to a DatetimeIndex if tz is set\n    preserve the input shape if possible\n\n    Parameters\n    ----------\n    values : ndarray\n    tz : string/pickled tz object\n    preserve_UTC : boolean,\n        preserve the UTC of the result\n    coerce : if we do not have a passed timezone, coerce to M8[ns] ndarray"
  },
  {
    "code": "def search_metadata(self, query):\n        query_url = ('/catalog/search?' +\n                     urlencode((('metadata', query),)))\n        resp = self.api_request(query_url)\n        return ItemGroup(resp['items'], self)",
    "docstring": "Submit a search query to the server and retrieve the results\n\n        :type query: String\n        :param query: the search query\n\n        :rtype: ItemGroup\n        :returns: the search results\n\n        :raises: APIError if the API request is not successful"
  },
  {
    "code": "def pddet(A):\n    L = jitchol(A)\n    logdetA = 2*sum(np.log(np.diag(L)))\n    return logdetA",
    "docstring": "Determinant of a positive definite matrix, only symmetric matricies though"
  },
  {
    "code": "def _get_rank(self, team):\n        rank = None\n        rank_field = team('span[class=\"pollrank\"]')\n        if len(rank_field) > 0:\n            rank = re.findall(r'\\(\\d+\\)', str(rank_field))[0]\n            rank = int(rank.replace('(', '').replace(')', ''))\n        return rank",
    "docstring": "Find the team's rank when applicable.\n\n        If a team is ranked, it will showup in a separate <span> tag with the\n        actual rank embedded between parentheses. When a team is ranked, the\n        integer value representing their ranking should be returned. For teams\n        that are not ranked, None should be returned.\n\n        Parameters\n        ----------\n        team : PyQuery object\n            A PyQuery object of a team's HTML tag in the boxscore.\n\n        Returns\n        -------\n        int\n            Returns an integer representing the team's ranking when applicable,\n            or None if the team is not ranked."
  },
  {
    "code": "def Genra(request):\n\tschool = request.GET['school']\n\tc = Course(school=school)\n\treturn JsonResponse(c.getGenra(), safe=False)",
    "docstring": "Generate dict of Dept and its grade."
  },
  {
    "code": "def fromstr(cls, s, *, strict=True):\n        nodedomain, sep, resource = s.partition(\"/\")\n        if not sep:\n            resource = None\n        localpart, sep, domain = nodedomain.partition(\"@\")\n        if not sep:\n            domain = localpart\n            localpart = None\n        return cls(localpart, domain, resource, strict=strict)",
    "docstring": "Construct a JID out of a string containing it.\n\n        :param s: The string to parse.\n        :type s: :class:`str`\n        :param strict: Whether to enable strict parsing.\n        :type strict: :class:`bool`\n        :raises: See :class:`JID`\n        :return: The parsed JID\n        :rtype: :class:`JID`\n\n        See the :class:`JID` class level documentation for the semantics of\n        `strict`."
  },
  {
    "code": "def _get_autoreload_programs(self,cfg_file):\n        cfg = RawConfigParser()\n        cfg.readfp(cfg_file)\n        reload_progs = []\n        for section in cfg.sections():\n            if section.startswith(\"program:\"):\n                try:\n                    if cfg.getboolean(section,\"autoreload\"):\n                        reload_progs.append(section.split(\":\",1)[1])\n                except NoOptionError:\n                    pass\n        return reload_progs",
    "docstring": "Get the set of programs to auto-reload when code changes.\n\n        Such programs will have autoreload=true in their config section.\n        This can be affected by config file sections or command-line\n        arguments, so we need to read it out of the merged config."
  },
  {
    "code": "def _reldiff(a, b):\n    a = float(a)\n    b = float(b)\n    aa = abs(a)\n    ba = abs(b)\n    if a == 0.0 and b == 0.0:\n        return 0.0\n    elif a == 0 or b == 0.0:\n        return float('inf')\n    return abs(a - b) / min(aa, ba)",
    "docstring": "Computes the relative difference of two floating-point numbers\n\n    rel = abs(a-b)/min(abs(a), abs(b))\n\n    If a == 0 and b == 0, then 0.0 is returned\n    Otherwise if a or b is 0.0, inf is returned."
  },
  {
    "code": "def initialize(self):\n        if 'EnErrorStyle' not in self._vim.vars:\n            self._vim.vars['EnErrorStyle'] = 'EnError'\n        self._vim.command('highlight EnErrorStyle ctermbg=red gui=underline')\n        self._vim.command('set omnifunc=EnCompleteFunc')\n        self._vim.command(\n            'autocmd FileType package_info nnoremap <buffer> <Space> :call EnPackageDecl()<CR>')\n        self._vim.command('autocmd FileType package_info setlocal splitright')",
    "docstring": "Sets up initial ensime-vim editor settings."
  },
  {
    "code": "def get_definition(self):\n        match = self._bracket_exact_var(self.context.exact_match)\n        if match is None:\n           match = self._bracket_exact_exec(self.context.exact_match)\n        return match",
    "docstring": "Checks variable and executable code elements based on the current\n        context for a code element whose name matches context.exact_match\n        perfectly."
  },
  {
    "code": "def schedule_in(secs, target=None, args=(), kwargs=None):\n    return schedule_at(time.time() + secs, target, args, kwargs)",
    "docstring": "insert a greenlet into the scheduler to run after a set time\n\n    If provided a function, it is wrapped in a new greenlet\n\n    :param secs: the number of seconds to wait before running the target\n    :type unixtime: int or float\n    :param target: what to schedule\n    :type target: function or greenlet\n    :param args:\n        arguments for the function (only used if ``target`` is a function)\n    :type args: tuple\n    :param kwargs:\n        keyword arguments for the function (only used if ``target`` is a\n        function)\n    :type kwargs: dict or None\n\n    :returns: the ``target`` argument\n\n    This function can also be used as a decorator:\n\n    >>> @schedule_in(30)\n    >>> def f():\n    ...     print 'hello from f'\n\n    and args/kwargs can also be preloaded:\n\n    >>> @schedule_in(30, args=('world',))\n    >>> def f(name):\n    ...     print 'hello %s' % name"
  },
  {
    "code": "def get_stats(self):\n        stats = yield from self._hypervisor.send(\"nio get_stats {}\".format(self._name))\n        return stats[0]",
    "docstring": "Gets statistics for this NIO.\n\n        :returns: NIO statistics (string with packets in, packets out, bytes in, bytes out)"
  },
  {
    "code": "def _get_data(data_source, context):\n    try:\n        data = data_source.source(context)\n        if data is None:\n            raise ValueError(\"'None' returned from \"\n                \"data source '{n}'\".format(n=context.name))\n        elif not isinstance(data, np.ndarray):\n            raise TypeError(\"Data source '{n}' did not \"\n                \"return a numpy array, returned a '{t}'\".format(\n                    t=type(data)))\n        elif data.shape != context.shape or data.dtype != context.dtype:\n            raise ValueError(\"Expected data of shape '{esh}' and \"\n                \"dtype '{edt}' for data source '{n}', but \"\n                \"shape '{rsh}' and '{rdt}' was found instead\".format(\n                    n=context.name, esh=context.shape, edt=context.dtype,\n                    rsh=data.shape, rdt=data.dtype))\n        return data\n    except Exception as e:\n        ex = ValueError(\"An exception occurred while \"\n            \"obtaining data from data source '{ds}'\\n\\n\"\n            \"{e}\\n\\n\"\n            \"{help}\".format(ds=context.name,\n                e=str(e), help=context.help()))\n        raise ex, None, sys.exc_info()[2]",
    "docstring": "Get data from the data source, checking the return values"
  },
  {
    "code": "def system_error(self, msg_id=None, message=None, description=None,\n                     validation_timeout=False, exc_info=None, **kw):\n        if exc_info:\n            if (isinstance(exc_info[1], validator.ValidationTimeout) and\n                    msg_id != 'validation_timeout'):\n                raise exc_info[1]\n            log.error('Unexpected error during validation: %s: %s'\n                      % (exc_info[0].__name__, exc_info[1]),\n                      exc_info=exc_info)\n        full_id = ('validator', 'unexpected_exception')\n        if msg_id:\n            full_id += (msg_id,)\n        self.error(full_id,\n                   message or 'An unexpected error has occurred.',\n                   description or\n                   ('Validation was unable to complete successfully due '\n                    'to an unexpected error.',\n                    'The error has been logged, but please consider '\n                    'filing an issue report here: '\n                    'https://bit.ly/1POrYYU'),\n                   tier=1, **kw)\n        self.errors.insert(0, self.errors.pop())",
    "docstring": "Add an error message for an unexpected exception in validator\n        code, and move it to the front of the error message list. If\n        `exc_info` is supplied, the error will be logged.\n\n        If the error is a validation timeout, it is re-raised unless\n        `msg_id` is \"validation_timeout\"."
  },
  {
    "code": "def getGroupsURL(certfile, group):\n    GMS = \"https://\" + _SERVER + _GMS\n    certfile.seek(0)\n    buf = certfile.read()\n    x509 = crypto.load_certificate(crypto.FILETYPE_PEM, buf)\n    sep = \"\"\n    dn = \"\"\n    parts = []\n    for i in x509.get_issuer().get_components():\n        if i[0] in parts:\n            continue\n        parts.append(i[0])\n        dn = i[0] + \"=\" + i[1] + sep + dn\n        sep = \",\"\n    return GMS + \"/\" + group + \"/\" + urllib.quote(dn)",
    "docstring": "given a certfile load a list of groups that user is a member of"
  },
  {
    "code": "def async_refresh_state(self):\n        _LOGGER.debug('Setting up extended status')\n        ext_status = ExtendedSend(\n            address=self._address,\n            commandtuple=COMMAND_EXTENDED_GET_SET_0X2E_0X00,\n            cmd2=0x02,\n            userdata=Userdata())\n        ext_status.set_crc()\n        _LOGGER.debug('Sending ext status: %s', ext_status)\n        self._send_msg(ext_status)\n        _LOGGER.debug('Sending temp status request')\n        self.temperature.async_refresh_state()",
    "docstring": "Request each state to provide status update."
  },
  {
    "code": "def encrypt(self, plaintext, nonce, encoder=encoding.RawEncoder):\n        if len(nonce) != self.NONCE_SIZE:\n            raise ValueError(\"The nonce must be exactly %s bytes long\" %\n                             self.NONCE_SIZE)\n        ciphertext = libnacl.crypto_box_afternm(\n            plaintext,\n            nonce,\n            self._shared_key,\n        )\n        encoded_nonce = encoder.encode(nonce)\n        encoded_ciphertext = encoder.encode(ciphertext)\n        return EncryptedMessage._from_parts(\n            encoded_nonce,\n            encoded_ciphertext,\n            encoder.encode(nonce + ciphertext),\n        )",
    "docstring": "Encrypts the plaintext message using the given `nonce` and returns\n        the ciphertext encoded with the encoder.\n\n        .. warning:: It is **VITALLY** important that the nonce is a nonce,\n            i.e. it is a number used only once for any given key. If you fail\n            to do this, you compromise the privacy of the messages encrypted.\n\n        :param plaintext: [:class:`bytes`] The plaintext message to encrypt\n        :param nonce: [:class:`bytes`] The nonce to use in the encryption\n        :param encoder: The encoder to use to encode the ciphertext\n        :rtype: [:class:`nacl.utils.EncryptedMessage`]"
  },
  {
    "code": "def checkpoint(self, interval):\n        self.is_checkpointed = True\n        self._jdstream.checkpoint(self._ssc._jduration(interval))\n        return self",
    "docstring": "Enable periodic checkpointing of RDDs of this DStream\n\n        @param interval: time in seconds, after each period of that, generated\n                         RDD will be checkpointed"
  },
  {
    "code": "def validate(self):\n        if self.dosHeader.e_magic.value != consts.MZ_SIGNATURE:\n            raise excep.PEException(\"Invalid MZ signature. Found %d instead of %d.\" % (self.dosHeader.magic.value, consts.MZ_SIGNATURE))\n        if self.dosHeader.e_lfanew.value > len(self):\n            raise excep.PEException(\"Invalid e_lfanew value. Probably not a PE file.\")\n        if self.ntHeaders.signature.value != consts.PE_SIGNATURE: \n            raise excep.PEException(\"Invalid PE signature. Found %d instead of %d.\" % (self.ntHeaders.optionaHeader.signature.value, consts.PE_SIGNATURE))\n        if self.ntHeaders.optionalHeader.numberOfRvaAndSizes.value > 0x10:\n            print excep.PEWarning(\"Suspicious value for NumberOfRvaAndSizes: %d.\" % self.ntHeaders.optionaHeader.numberOfRvaAndSizes.value)",
    "docstring": "Performs validations over some fields of the PE structure to determine if the loaded file has a valid PE format.\n        \n        @raise PEException: If an invalid value is found into the PE instance."
  },
  {
    "code": "def generate_headers(self, token):\n        headers = {}\n        token = self.encode_token(token)\n        if self.config[\"header\"]:\n            headers[self.config[\"header\"]] = token\n        if self.config[\"cookie\"]:\n            headers[\"Set-Cookie\"] = dump_cookie(\n                self.config[\"cookie\"], token, httponly=True,\n                max_age=self.config[\"expiration\"]\n            )\n        return headers",
    "docstring": "Generate auth headers"
  },
  {
    "code": "def get_instances(self):\n        with self.__instances_lock:\n            return sorted(\n                (name, stored_instance.factory_name, stored_instance.state)\n                for name, stored_instance in self.__instances.items()\n            )",
    "docstring": "Retrieves the list of the currently registered component instances\n\n        :return: A list of (name, factory name, state) tuples."
  },
  {
    "code": "def _parse_motion_sensor(self, sensor_xml):\n    return MotionSensor(self._lutron,\n                        name=sensor_xml.get('Name'),\n                        integration_id=int(sensor_xml.get('IntegrationID')))",
    "docstring": "Parses a motion sensor object.\n\n    TODO: We don't actually do anything with these yet. There's a lot of info\n    that needs to be managed to do this right. We'd have to manage the occupancy\n    groups, what's assigned to them, and when they go (un)occupied. We'll handle\n    this later."
  },
  {
    "code": "def get_db_references(cls, entry):\n        db_refs = []\n        for db_ref in entry.iterfind(\"./dbReference\"):\n            db_ref_dict = {'identifier': db_ref.attrib['id'], 'type_': db_ref.attrib['type']}\n            db_refs.append(models.DbReference(**db_ref_dict))\n        return db_refs",
    "docstring": "get list of `models.DbReference` from XML node entry\n\n        :param entry: XML node entry\n        :return: list of :class:`pyuniprot.manager.models.DbReference`"
  },
  {
    "code": "def valid(self):\n        now = timezone.now()\n        return self.filter(revoked=False, expires__gt=now, valid_from__lt=now)",
    "docstring": "Return valid certificates."
  },
  {
    "code": "def getGraphFieldList(self, graph_name):\n        graph = self._getGraph(graph_name, True)\n        return graph.getFieldList()",
    "docstring": "Returns list of names of fields for graph with name graph_name.\n        \n        @param graph_name: Graph Name\n        @return:           List of field names for graph."
  },
  {
    "code": "def request_type(self):\n        if self.static and not self.uses_request:\n            return getattr(xenon_pb2, 'Empty')\n        if not self.uses_request:\n            return None\n        return getattr(xenon_pb2, self.request_name)",
    "docstring": "Retrieve the type of the request, by fetching it from\n        `xenon.proto.xenon_pb2`."
  },
  {
    "code": "def decrypt_file(filename, set_env=True, override_env=False):\n    data = json.load(open(filename))\n    results = {}\n    for key, v in data.iteritems():\n        v_decrypt = decrypt_secret(v)\n        results[key] = v_decrypt\n        if set_env:\n            if key in os.environ and not override_env:\n                break\n            os.environ[str(key)] = v_decrypt\n    return results",
    "docstring": "Decrypts a JSON file containing encrypted secrets. This file should contain an object mapping the key names to\n    encrypted secrets. This encrypted file can be created using `credkeep.encrypt_file` or the commandline utility.\n\n    :param filename:  filename of the JSON file\n    :param set_env: If True, an environment variable representing the key is created.\n    :param override_env: If True, an existing environment variable with the same key name will be overridden with the\n        new decrypted value. If False, the environment variable will not be set.\n    :return: Dict containing the decrypted keys"
  },
  {
    "code": "def _process_response(self, response):\n        assert self._state == self._STATE_RUNNING, \"Should be running if processing response\"\n        cols = None\n        data = []\n        for r in response:\n            if not cols:\n                cols = [(f, r._fields[f].db_type) for f in r._fields]\n            data.append([getattr(r, f) for f in r._fields])\n        self._data = data\n        self._columns = cols\n        self._state = self._STATE_FINISHED",
    "docstring": "Update the internal state with the data from the response"
  },
  {
    "code": "def _GetSocket(self):\n    try:\n      return socket.create_connection(\n          (self._host, self._port), self._SOCKET_TIMEOUT)\n    except socket.error as exception:\n      logger.error(\n          'Unable to connect to nsrlsvr with error: {0!s}.'.format(exception))",
    "docstring": "Establishes a connection to an nsrlsvr instance.\n\n    Returns:\n      socket._socketobject: socket connected to an nsrlsvr instance or None if\n          a connection cannot be established."
  },
  {
    "code": "def analysis2working(self,a):\n        \"Convert back from the analysis color space to the working space.\"\n        a = self.swap_polar_HSVorder[self.analysis_space](a)\n        return self.colorspace.convert(self.analysis_space, self.working_space, a)",
    "docstring": "Convert back from the analysis color space to the working space."
  },
  {
    "code": "def main():\n    try:\n        device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))\n        device.on_message += handle_message\n        with device.open(baudrate=BAUDRATE):\n            while True:\n                time.sleep(1)\n    except Exception as ex:\n        print('Exception:', ex)",
    "docstring": "Example application that opens a serial device and prints messages to the terminal."
  },
  {
    "code": "def get_votes(self):\n        candidate_elections = CandidateElection.objects.filter(election=self)\n        votes = None\n        for ce in candidate_elections:\n            votes = votes | ce.votes.all()\n        return votes",
    "docstring": "Get all votes for this election."
  },
  {
    "code": "def set_privilege(self, name, value=None):\n        cmd = 'username %s' % name\n        if value is not None:\n            if not isprivilege(value):\n                raise TypeError('priviledge value must be between 0 and 15')\n            cmd += ' privilege %s' % value\n        else:\n            cmd += ' privilege 1'\n        return self.configure(cmd)",
    "docstring": "Configures the user privilege value in EOS\n\n        Args:\n            name (str): The name of the user to craete\n\n            value (int): The privilege value to assign to the user.  Valid\n                values are in the range of 0 to 15\n\n        Returns:\n            True if the operation was successful otherwise False\n\n        Raises:\n            TypeError: if the value is not in the valid range"
  },
  {
    "code": "def get_full_basenames(bases, basenames):\n    for base, basename in zip(bases, basenames):\n        yield get_full_basename(base, basename)",
    "docstring": "Resolve the base nodes and partial names of a class to full names.\n\n    :param bases: The astroid node representing something that a class\n        inherits from.\n    :type bases: iterable(astroid.NodeNG)\n    :param basenames: The partial name of something that a class inherits from.\n    :type basenames: iterable(str)\n\n    :returns: The full names.\n    :rtype: iterable(str)"
  },
  {
    "code": "def auto_kwargs(function):\n    supported = introspect.arguments(function)\n    @wraps(function)\n    def call_function(*args, **kwargs):\n        return function(*args, **{key: value for key, value in kwargs.items() if key in supported})\n    return call_function",
    "docstring": "Modifies the provided function to support kwargs by only passing along kwargs for parameters it accepts"
  },
  {
    "code": "def is_admin(controller, client, actor):\n    config = controller.config\n    if not config.has_section(\"admins\"):\n        logging.debug(\"Ignoring is_admin check - no [admins] config found.\")\n        return False\n    for key,val in config.items(\"admins\"):\n        if actor == User(key):\n            logging.debug(\"is_admin: %r matches admin %r\", actor, key)\n            return True\n        if actor.nick.lower() == key.lower() and actor.host.lower() == val.lower():\n            logging.debug(\"is_admin: %r matches admin %r=%r\", actor, key, val)\n            return True\n    logging.debug(\"is_admin: %r is not an admin.\", actor)\n    return False",
    "docstring": "Used to determine whether someone issuing a command is an admin.\n\n    By default, checks to see if there's a line of the type nick=host that\n    matches the command's actor in the [admins] section of the config file,\n    or a key that matches the entire mask (e.g. \"foo@bar\" or \"foo@bar=1\")."
  },
  {
    "code": "def _get_filter(sdk_filter, attr_map):\n    if not isinstance(sdk_filter, dict):\n        raise CloudValueError('filter value must be a dictionary, was %r' % (sdk_filter,))\n    custom = sdk_filter.pop('custom_attributes', {})\n    new_filter = _normalise_key_values(filter_obj=sdk_filter, attr_map=attr_map)\n    new_filter.update({\n        'custom_attributes__%s' % k: v for k, v in _normalise_key_values(filter_obj=custom).items()\n    })\n    return new_filter",
    "docstring": "Common functionality for filter structures\n\n    :param sdk_filter: {field:constraint, field:{operator:constraint}, ...}\n    :return: {field__operator: constraint, ...}"
  },
  {
    "code": "def requestCheckDockerIo(origAppliance, imageName, tag):\n    if '/' not in imageName:\n        imageName = 'library/' + imageName\n    token_url = 'https://auth.docker.io/token?service=registry.docker.io&scope=repository:{repo}:pull'.format(repo=imageName)\n    requests_url = 'https://registry-1.docker.io/v2/{repo}/manifests/{tag}'.format(repo=imageName, tag=tag)\n    token = requests.get(token_url)\n    jsonToken = token.json()\n    bearer = jsonToken[\"token\"]\n    response = requests.head(requests_url, headers={'Authorization': 'Bearer {}'.format(bearer)})\n    if not response.ok:\n        raise ApplianceImageNotFound(origAppliance, requests_url, response.status_code)\n    else:\n        return origAppliance",
    "docstring": "Checks docker.io to see if an image exists using the requests library.\n\n    URL is based on the docker v2 schema.  Requires that an access token be fetched first.\n\n    :param str origAppliance: The full url of the docker image originally\n                              specified by the user (or the default).  e.g. \"ubuntu:latest\"\n    :param str imageName: The image, including path and excluding the tag. e.g. \"ubuntu\"\n    :param str tag: The tag used at that docker image's registry.  e.g. \"latest\"\n    :return: Return True if match found.  Raise otherwise."
  },
  {
    "code": "def returner(ret):\n    serv = _get_serv(ret)\n    minion = ret['id']\n    jid = ret['jid']\n    fun = ret['fun']\n    rets = salt.utils.json.dumps(ret)\n    serv.set('{0}:{1}'.format(jid, minion), rets)\n    serv.set('{0}:{1}'.format(fun, minion), rets)\n    _append_list(serv, 'minions', minion)\n    _append_list(serv, 'jids', jid)",
    "docstring": "Return data to a memcache data store"
  },
  {
    "code": "def import_csv(file_name, **kwargs):\n    sep = kwargs.get('separator', \",\")\n    content = exch.read_file(file_name, skip_lines=1)\n    return exch.import_text_data(content, sep)",
    "docstring": "Reads control points from a CSV file and generates a 1-dimensional list of control points.\n\n    It is possible to use a different value separator via ``separator`` keyword argument. The following code segment\n    illustrates the usage of ``separator`` keyword argument.\n\n    .. code-block:: python\n        :linenos:\n\n        # By default, import_csv uses 'comma' as the value separator\n        ctrlpts = exchange.import_csv(\"control_points.csv\")\n\n        # Alternatively, it is possible to import a file containing tab-separated values\n        ctrlpts = exchange.import_csv(\"control_points.csv\", separator=\"\\\\t\")\n\n    The only difference of this function from :py:func:`.exchange.import_txt()` is skipping the first line of the input\n    file which generally contains the column headings.\n\n    :param file_name: file name of the text file\n    :type file_name: str\n    :return: list of control points\n    :rtype: list\n    :raises GeomdlException: an error occurred reading the file"
  },
  {
    "code": "def drawAxis( self, painter ):\r\n        pen = QPen(self.axisColor())\r\n        pen.setWidth(4)\r\n        painter.setPen(pen)\r\n        painter.drawLines(self._buildData['axis_lines'])\r\n        for rect, text in self._buildData['grid_h_notches']:\r\n            painter.drawText(rect, Qt.AlignTop | Qt.AlignRight, text)\r\n        for rect, text in self._buildData['grid_v_notches']:\r\n            painter.drawText(rect, Qt.AlignCenter, text)",
    "docstring": "Draws the axis for this system."
  },
  {
    "code": "def sscan(self, key, cursor=0, match=None, count=None):\n        tokens = [key, cursor]\n        match is not None and tokens.extend([b'MATCH', match])\n        count is not None and tokens.extend([b'COUNT', count])\n        fut = self.execute(b'SSCAN', *tokens)\n        return wait_convert(fut, lambda obj: (int(obj[0]), obj[1]))",
    "docstring": "Incrementally iterate Set elements."
  },
  {
    "code": "def invalidate(cls, inst, name):\n        inst_cls = inst.__class__\n        if not hasattr(inst, '__dict__'):\n            raise AttributeError(\"'%s' object has no attribute '__dict__'\"\n                                 % (inst_cls.__name__,))\n        if name.startswith('__') and not name.endswith('__'):\n            name = '_%s%s' % (inst_cls.__name__, name)\n        if not isinstance(getattr(inst_cls, name), cls):\n            raise AttributeError(\"'%s.%s' is not a %s attribute\"\n                                 % (inst_cls.__name__, name, cls.__name__))\n        if name in inst.__dict__:\n            del inst.__dict__[name]",
    "docstring": "Invalidate a lazy attribute.\n\n        This obviously violates the lazy contract. A subclass of lazy\n        may however have a contract where invalidation is appropriate."
  },
  {
    "code": "def _compute_diff(existing, expected):\n    diff = {}\n    for key in ['location', 'contact', 'chassis_id']:\n        if existing.get(key) != expected.get(key):\n            _create_diff(diff,\n                         _valid_str,\n                         key,\n                         existing.get(key),\n                         expected.get(key))\n    for key in ['community']:\n        if existing.get(key) != expected.get(key):\n            _create_diff(diff,\n                         _valid_dict,\n                         key,\n                         existing.get(key),\n                         expected.get(key))\n    return diff",
    "docstring": "Computes the differences between the existing and the expected SNMP config."
  },
  {
    "code": "def _gen_hash(self, password, salt):\n        h = hashlib.sha1()\n        h.update(salt)\n        h.update(password)\n        return h.hexdigest()",
    "docstring": "Generate password hash."
  },
  {
    "code": "def parse_dest(*args, **kwargs):\n    explicit_dest = kwargs.get('dest')\n    if explicit_dest:\n      return explicit_dest\n    arg = next((a for a in args if a.startswith('--')), args[0])\n    return arg.lstrip('-').replace('-', '_')",
    "docstring": "Select the dest name for an option registration.\n\n    If an explicit `dest` is specified, returns that and otherwise derives a default from the\n    option flags where '--foo-bar' -> 'foo_bar' and '-x' -> 'x'."
  },
  {
    "code": "def hash_name(name, script_pubkey, register_addr=None):\n   bin_name = b40_to_bin(name)\n   name_and_pubkey = bin_name + unhexlify(script_pubkey)\n   if register_addr is not None:\n       name_and_pubkey += str(register_addr)\n   return hex_hash160(name_and_pubkey)",
    "docstring": "Generate the hash over a name and hex-string script pubkey"
  },
  {
    "code": "def _create_metric_extractor(metric_name):\n  def extractor_fn(session_or_group):\n    metric_value = _find_metric_value(session_or_group,\n                                      metric_name)\n    return metric_value.value if metric_value else None\n  return extractor_fn",
    "docstring": "Returns function that extracts a metric from a session group or a session.\n\n  Args:\n    metric_name: tensorboard.hparams.MetricName protobuffer. Identifies the\n    metric to extract from the session group.\n  Returns:\n    A function that takes a tensorboard.hparams.SessionGroup or\n    tensorborad.hparams.Session protobuffer and returns the value of the metric\n    identified by 'metric_name' or None if the value doesn't exist."
  },
  {
    "code": "def to_param_dict(self):\r\n        param_dict = {}\r\n        for index, dictionary in enumerate(self.value):\r\n            for key, value in dictionary.items():\r\n                param_name = '{param_name}[{index}][{key}]'.format(\r\n                                                    param_name=self.param_name,\r\n                                                    index=index,\r\n                                                    key=key)\r\n                param_dict[param_name] = value\r\n        return OrderedDict(sorted(param_dict.items()))",
    "docstring": "Sorts to ensure Order is consistent for Testing"
  },
  {
    "code": "def get_objanno(fin_anno, anno_type=None, **kws):\n    anno_type = get_anno_desc(fin_anno, anno_type)\n    if anno_type is not None:\n        if anno_type == 'gene2go':\n            return Gene2GoReader(fin_anno, **kws)\n        if anno_type == 'gaf':\n            return GafReader(fin_anno,\n                             hdr_only=kws.get('hdr_only', False),\n                             prt=kws.get('prt', sys.stdout),\n                             allow_missing_symbol=kws.get('allow_missing_symbol', False))\n        if anno_type == 'gpad':\n            hdr_only = kws.get('hdr_only', False)\n            return GpadReader(fin_anno, hdr_only)\n        if anno_type == 'id2gos':\n            return IdToGosReader(fin_anno)\n    raise RuntimeError('UNEXPECTED ANNOTATION FILE FORMAT: {F} {D}'.format(\n        F=fin_anno, D=anno_type))",
    "docstring": "Read annotations in GAF, GPAD, Entrez gene2go, or text format."
  },
  {
    "code": "async def change_url(self, url: str, description: str = None):\n        await self._change(url=url, description=description)",
    "docstring": "change the url of that attachment\n\n        |methcoro|\n\n        Args:\n            url: url you want to change\n            description: *optional* description for your attachment\n\n        Raises:\n            ValueError: url must not be None\n            APIException"
  },
  {
    "code": "def get_pwm_list(pwm_id_list, pseudocountProb=0.0001):\n    l = load_motif_db(ATTRACT_PWM)\n    l = {k.split()[0]: v for k, v in l.items()}\n    pwm_list = [PWM(l[str(m)] + pseudocountProb, name=m) for m in pwm_id_list]\n    return pwm_list",
    "docstring": "Get a list of Attract PWM's.\n\n    # Arguments\n        pwm_id_list: List of id's from the `PWM_id` column in `get_metadata()` table\n        pseudocountProb: Added pseudocount probabilities to the PWM\n\n    # Returns\n        List of `concise.utils.pwm.PWM` instances."
  },
  {
    "code": "def compute_qpi(self):\n        kwargs = self.model_kwargs.copy()\n        kwargs[\"radius\"] = self.radius\n        kwargs[\"sphere_index\"] = self.sphere_index\n        kwargs[\"center\"] = [self.posx_offset, self.posy_offset]\n        qpi = self.sphere_method(**kwargs)\n        bg_data = np.ones(qpi.shape) * -self.pha_offset\n        qpi.set_bg_data(bg_data=bg_data, which_data=\"phase\")\n        return qpi",
    "docstring": "Compute model data with current parameters\n\n        Returns\n        -------\n        qpi: qpimage.QPImage\n            Modeled phase data\n\n        Notes\n        -----\n        The model image might deviate from the fitted image\n        because of interpolation during the fitting process."
  },
  {
    "code": "def retry(retry_count=5, delay=2):\n    if retry_count <= 0:\n        raise ValueError(\"retry_count have to be positive\")\n    def decorator(f):\n        @functools.wraps(f)\n        def wrapper(*args, **kwargs):\n            for i in range(retry_count, 0, -1):\n                try:\n                    return f(*args, **kwargs)\n                except Exception:\n                    if i <= 1:\n                        raise\n                time.sleep(delay)\n        return wrapper\n    return decorator",
    "docstring": "Use as decorator to retry functions few times with delays\n\n    Exception will be raised if last call fails\n\n    :param retry_count: int could of retries in case of failures. It must be\n                        a positive number\n    :param delay: int delay between retries"
  },
  {
    "code": "def database_path(self):\n        filename = self.database_filename\n        db_path = \":memory:\" if filename == \":memory:\" else (\n            path.abspath(path.join(__file__, \"../..\", \"..\", \"data\", filename)))\n        return db_path",
    "docstring": "Full database path. Includes the default location + the database filename."
  },
  {
    "code": "def draw(graph, fname):\n    ag = networkx.nx_agraph.to_agraph(graph)\n    ag.draw(fname, prog='dot')",
    "docstring": "Draw a graph and save it into a file"
  },
  {
    "code": "def processBED(fh, genome_alig, window_size, window_centre,\n               mi_seqs=MissingSequenceHandler.TREAT_AS_ALL_GAPS, species=None,\n               verbose=False):\n  mean_profile = []\n  while len(mean_profile) < window_size:\n    mean_profile.append(RollingMean())\n  for e in BEDIterator(fh, verbose=verbose, scoreType=float,\n                       sortedby=ITERATOR_SORTED_START):\n    transform_locus(e, window_centre, window_size)\n    new_profile = conservtion_profile_pid(e, genome_alig, mi_seqs, species)\n    merge_profile(mean_profile, new_profile)\n  return [m.mean for m in mean_profile]",
    "docstring": "Process BED file, produce profile of conservation using whole genome alig.\n\n  :param fh:\n  :param genome_alig:   the whole-genome alignment to use to compute\n                        conservation scores\n  :param window_size:   length of the profile.\n  :param window_center: which part of each interval to place at the center\n                        of the profile. Acceptable values are in the module\n                        constant WINDOW_CENTRE_OPTIONS.\n  :param miss_seqs:     how to treat sequence with no actual sequence data for\n                        the column.\n  :param verbose:       if True, output progress messages to stderr.\n\n  :return:"
  },
  {
    "code": "def chemical_element(self, name_only: bool = True) -> Union[dict, str]:\n        elements = self._data['chemical_element']\n        nm, sm, an = self.random.choice(elements).split('|')\n        if not name_only:\n            return {\n                'name': nm.strip(),\n                'symbol': sm.strip(),\n                'atomic_number': an.strip(),\n            }\n        return nm.strip()",
    "docstring": "Generate a random chemical element.\n\n        :param name_only: If False then will be returned dict.\n        :return: Name of chemical element or dict.\n        :rtype: dict or str\n\n        :Example:\n            {'Symbol': 'S', 'Name': 'Sulfur', 'Atomic number': '16'}"
  },
  {
    "code": "def pymodule(line, cell=None):\n  parser = _commands.CommandParser.create('pymodule')\n  parser.add_argument('-n', '--name',\n                      help='the name of the python module to create and import')\n  parser.set_defaults(func=_pymodule_cell)\n  return _utils.handle_magic_line(line, cell, parser)",
    "docstring": "Creates and subsequently auto-imports a python module."
  },
  {
    "code": "def get_visible_child(self, parent, locator, params=None, timeout=None):\n        return self.get_present_child(parent, locator, params, timeout, True)",
    "docstring": "Get child-element both present AND visible in the DOM.\n\n        If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise\n        TimeoutException should the element not be found.\n\n        :param parent: parent-element\n        :param locator: locator tuple\n        :param params: (optional) locator params\n        :param timeout: (optional) time to wait for element (default: self._explicit_wait)\n        :return: WebElement instance"
  },
  {
    "code": "def synchronized(sync_lock):\n    def wrapper(f):\n        @functools.wraps(f)\n        def inner_wrapper(*args, **kw):\n            with sync_lock:\n                return f(*args, **kw)\n        return inner_wrapper\n    return wrapper",
    "docstring": "A decorator synchronizing multi-process access to a resource."
  },
  {
    "code": "def all_ends_of_turn(self, root):\n        if root.parent:\n            raise ValueError('Unexpectedly received a node with a parent for'\n                             ' root:\\n{}'.format(root))\n        jobs = [root]\n        while jobs:\n            random_job_index = random.randint(0, len(jobs) - 1)\n            start_eot = jobs.pop(random_job_index)\n            if start_eot is root:\n                kw_root = {'root': start_eot}\n            else:\n                kw_root = {'root_eot': start_eot}\n            for eot in self.ends_of_one_state(**kw_root):\n                if not eot.is_mana_drain:\n                    jobs.append(eot)\n                yield eot",
    "docstring": "Simulate the root and continue generating ends of turn until\n        everything has reached mana drain.\n\n        Warning on random fill:\n        If random fill is used together with this method, it will generate\n        basically forever due to the huge number of possibilities it\n        introduces.\n\n        Arguments:\n        root: a start state with no parent\n\n        Note on mana drain:\n        Generates but does not continue simulation of mana drains.\n\n        Note on run time:\n        This simulates a complete turn for each eot provided, rather than\n        just one branch at a time. The method will only stop generating\n        when all possibilities have been simulated or filtered."
  },
  {
    "code": "def describe(**kwargs):\n    if isinstance(kwargs.get(\"paths\"), string_type):\n        kwargs[\"paths\"] = [kwargs[\"paths\"]]\n    if isinstance(kwargs.get(\"methods\"), string_type):\n        kwargs[\"methods\"] = [kwargs[\"methods\"]]\n    attrs = TransmuteAttributes(**kwargs)\n    def decorator(f):\n        if hasattr(f, \"transmute\"):\n            f.transmute = f.transmute | attrs\n        else:\n            f.transmute = attrs\n        return f\n    return decorator",
    "docstring": "describe is a decorator to customize the rest API\n    that transmute generates, such as choosing\n    certain arguments to be query parameters or\n    body parameters, or a different method.\n\n    :param list(str) paths: the path(s) for the handler to represent (using swagger's syntax for a path)\n\n    :param list(str) methods: the methods this function should respond to. if non is set, transmute defaults to a GET.\n\n    :param list(str) query_parameters: the names of arguments that\n           should be query parameters. By default, all arguments are query_or path parameters for a GET request.\n\n    :param body_parameters: the names of arguments that should be body parameters.\n           By default, all arguments are either body or path parameters for a non-GET request.\n\n           in the case of a single string, the whole body is validated against a single object.\n\n    :type body_parameters: List[str] or str\n\n    :param list(str) header_parameters: the arguments that should be passed into the header.\n\n    :param list(str) path_parameters: the arguments that are specified by the path. By default, arguments\n            that are found in the path are used first before the query_parameters and body_parameters.\n\n    :param list(str) parameter_descriptions: descriptions for each parameter, keyed by attribute name.\n            this will appear in the swagger documentation."
  },
  {
    "code": "def is_admin(self, user):\n        return True if self.organization_users.filter(\n            user=user, is_admin=True\n        ) else False",
    "docstring": "Returns True is user is an admin in the organization, otherwise false"
  },
  {
    "code": "def next_batch(self, n=1):\n        if len(self.queue) == 0:\n            return []\n        batch = list(reversed((self.queue[-n:])))\n        self.queue = self.queue[:-n]\n        return batch",
    "docstring": "Return the next requests that should be dispatched."
  },
  {
    "code": "def _merge_csv_model(models, pc, csvs):\n    logger_csvs.info(\"enter merge_csv_model\")\n    try:\n        for _name, _model in models.items():\n            if \"summaryTable\" in _model:\n                models[_name][\"summaryTable\"] = _merge_csv_table(_model[\"summaryTable\"], pc, csvs)\n            if \"ensembleTable\" in _model:\n                models[_name][\"ensembleTable\"] = _merge_csv_table(_model[\"ensembleTable\"], pc, csvs)\n            if \"distributionTable\" in _model:\n                models[_name][\"distributionTable\"] = _merge_csv_table(_model[\"distributionTable\"], pc, csvs)\n    except Exception as e:\n        logger_csvs.error(\"merge_csv_model: {}\",format(e))\n    logger_csvs.info(\"exit merge_csv_model\")\n    return models",
    "docstring": "Add csv data to each column in chron model\n\n    :param dict models: Metadata\n    :return dict models: Metadata"
  },
  {
    "code": "async def is_change_done(self, zone, change_id):\n        zone_id = self.get_managed_zone(zone)\n        url = f'{self._base_url}/managedZones/{zone_id}/changes/{change_id}'\n        resp = await self.get_json(url)\n        return resp['status'] == self.DNS_CHANGES_DONE",
    "docstring": "Check if a DNS change has completed.\n\n        Args:\n            zone (str): DNS zone of the change.\n            change_id (str): Identifier of the change.\n        Returns:\n            Boolean"
  },
  {
    "code": "def parse_bossURI(self, uri):\n        t = uri.split(\"://\")[1].split(\"/\")\n        if len(t) is 3:\n            return self.get_channel(t[2], t[0], t[1])\n        raise ValueError(\"Cannot parse URI \" + uri + \".\")",
    "docstring": "Parse a bossDB URI and handle malform errors.\n\n        Arguments:\n            uri (str): URI of the form bossdb://<collection>/<experiment>/<channel>\n\n        Returns:\n            Resource"
  },
  {
    "code": "def _execute(self, execute_inputs, execute_outputs, backward_execution=False):\n        self._script.build_module()\n        outcome_item = self._script.execute(self, execute_inputs, execute_outputs, backward_execution)\n        if backward_execution:\n            return\n        if self.preempted:\n            return Outcome(-2, \"preempted\")\n        if outcome_item in self.outcomes:\n            return self.outcomes[outcome_item]\n        for outcome_id, outcome in self.outcomes.items():\n            if outcome.name == outcome_item:\n                return self.outcomes[outcome_id]\n        logger.error(\"Returned outcome of {0} not existing: {1}\".format(self, outcome_item))\n        return Outcome(-1, \"aborted\")",
    "docstring": "Calls the custom execute function of the script.py of the state"
  },
  {
    "code": "def process(self, key, val):\n        for field in self.fields:\n            if field.check(key, val):\n                return\n        for field in self.optional:\n            if field.check(key, val):\n                return",
    "docstring": "Try to look for `key` in all required and optional fields. If found,\n        set the `val`."
  },
  {
    "code": "def reset(self, old_scene=None, screen=None):\n        for effect in self._effects:\n            effect.reset()\n        if old_scene:\n            for old_effect in old_scene.effects:\n                try:\n                    old_effect.clone(screen, self)\n                except AttributeError:\n                    pass",
    "docstring": "Reset the scene ready for playing.\n\n        :param old_scene: The previous version of this Scene that was running before the\n            application reset - e.g. due to a screen resize.\n        :param screen: New screen to use if old_scene is not None."
  },
  {
    "code": "def get(self, dash_id):\n        data = json.loads(r_db.hmget(config.DASH_CONTENT_KEY, dash_id)[0])\n        return build_response(dict(data=data, code=200))",
    "docstring": "Read dashboard content.\n\n        Args:\n            dash_id: dashboard id.\n\n        Returns:\n            A dict containing the content of that dashboard, not include the meta info."
  },
  {
    "code": "def _read_field(self):\n        ftype = self._input[self._pos]\n        self._pos += 1\n        reader = self.field_type_map.get(ftype)\n        if reader:\n            return reader(self)\n        raise Reader.FieldError('Unknown field type %s', ftype)",
    "docstring": "Read a single byte for field type, then read the value."
  },
  {
    "code": "def save(self, data, fname, header=None):\n        write_csv(fname, data, self.sep, self.fmt, header)\n        self.fnames.add(getattr(fname, 'name', fname))",
    "docstring": "Save data on fname.\n\n        :param data: numpy array or list of lists\n        :param fname: path name\n        :param header: header to use"
  },
  {
    "code": "def auth_string(self):\n        username_token = '{username}:{token}'.format(username=self.username, token=self.token)\n        b64encoded_string = b64encode(username_token)\n        auth_string = 'Token {b64}'.format(b64=b64encoded_string)\n        return auth_string",
    "docstring": "Authenticate based on username and token which is base64-encoded"
  },
  {
    "code": "def formfield_for_manytomany(self, db_field, request, **kwargs):\n        if db_field.name == 'authors':\n            kwargs['queryset'] = Author.objects.filter(\n                Q(is_staff=True) | Q(entries__isnull=False)\n                ).distinct()\n        return super(EntryAdmin, self).formfield_for_manytomany(\n            db_field, request, **kwargs)",
    "docstring": "Filter the disposable authors."
  },
  {
    "code": "def is_valid_program(self,p):\n        arities = list(a.arity[a.in_type] for a in p)\n        accu_arities = list(accumulate(arities))\n        accu_len = list(np.arange(len(p))+1)\n        check = list(a < b for a,b in zip(accu_arities,accu_len))\n        return all(check) and sum(a.arity[a.in_type] for a in p) +1 == len(p) and len(p)>0",
    "docstring": "checks whether program p makes a syntactically valid tree.\n\n        checks that the accumulated program length is always greater than the\n        accumulated arities, indicating that the appropriate number of arguments is\n        alway present for functions. It then checks that the sum of arties +1\n        exactly equals the length of the stack, indicating that there are no\n        missing arguments."
  },
  {
    "code": "def max_heapify(arr, end, simulation, iteration):\n    last_parent = (end - 1) // 2\n    for parent in range(last_parent, -1, -1):\n        current_parent = parent\n        while current_parent <= last_parent:\n            child = 2 * current_parent + 1\n            if child + 1 <= end and arr[child] < arr[child + 1]:\n                child = child + 1\n            if arr[child] > arr[current_parent]:\n                arr[current_parent], arr[child] = arr[child], arr[current_parent]\n                current_parent = child\n                if simulation:\n                    iteration = iteration + 1\n                    print(\"iteration\",iteration,\":\",*arr)\n            else:\n                break\n    arr[0], arr[end] = arr[end], arr[0]\n    return iteration",
    "docstring": "Max heapify helper for max_heap_sort"
  },
  {
    "code": "def setup_oauth_client(self, url=None):\n        if url and \"://\" in url:\n            server, endpoint = self._deconstruct_url(url)\n        else:\n            server = self.client.server\n        if server not in self._server_cache:\n            self._add_client(server)\n        if server == self.client.server:\n            self.oauth = OAuth1(\n                client_key=self.store[\"client-key\"],\n                client_secret=self.store[\"client-secret\"],\n                resource_owner_key=self.store[\"oauth-access-token\"],\n                resource_owner_secret=self.store[\"oauth-access-secret\"],\n            )\n            return self.oauth\n        else:\n            return OAuth1(\n                client_key=self._server_cache[server].key,\n                client_secret=self._server_cache[server].secret,\n            )",
    "docstring": "Sets up client for requests to pump"
  },
  {
    "code": "def go_right(self):\n        start, end = self._interval\n        delay = (end - start) * .2\n        self.shift(delay)",
    "docstring": "Go to right."
  },
  {
    "code": "def group_keys(self):\n        for key in sorted(listdir(self._store, self._path)):\n            path = self._key_prefix + key\n            if contains_group(self._store, path):\n                yield key",
    "docstring": "Return an iterator over member names for groups only.\n\n        Examples\n        --------\n        >>> import zarr\n        >>> g1 = zarr.group()\n        >>> g2 = g1.create_group('foo')\n        >>> g3 = g1.create_group('bar')\n        >>> d1 = g1.create_dataset('baz', shape=100, chunks=10)\n        >>> d2 = g1.create_dataset('quux', shape=200, chunks=20)\n        >>> sorted(g1.group_keys())\n        ['bar', 'foo']"
  },
  {
    "code": "def _ensure_object_id(cls, id):\n        if isinstance(id, ObjectId):\n            return id\n        if isinstance(id, basestring) and OBJECTIDEXPR.match(id):\n            return ObjectId(id)\n        return id",
    "docstring": "Checks whether the given id is an ObjectId instance, and if not wraps it."
  },
  {
    "code": "def _dstr(degrees, places=1, signed=False):\n    r\n    if isnan(degrees):\n        return 'nan'\n    sgn, d, m, s, etc = _sexagesimalize_to_int(degrees, places)\n    sign = '-' if sgn < 0.0 else '+' if signed else ''\n    return '%s%02ddeg %02d\\' %02d.%0*d\"' % (sign, d, m, s, places, etc)",
    "docstring": "r\"\"\"Convert floating point `degrees` into a sexagesimal string.\n\n    >>> _dstr(181.875)\n    '181deg 52\\' 30.0\"'\n    >>> _dstr(181.875, places=3)\n    '181deg 52\\' 30.000\"'\n    >>> _dstr(181.875, signed=True)\n    '+181deg 52\\' 30.0\"'\n    >>> _dstr(float('nan'))\n    'nan'"
  },
  {
    "code": "def kem(request):\n\tkeyword = request.GET['keyword']\n\tlang = request.GET['lang']\n\tontology = 'ontology' if 'ontology' in request.GET and bool(json.loads(request.GET['ontology'].lower())) else 'origin'\n\tresult = multilanguage_model[lang][ontology].most_similar(keyword, int(request.GET['num']) if 'num' in request.GET else 10)\n\treturn JsonResponse(result, safe=False)",
    "docstring": "due to the base directory settings of django, the model_path needs to be different when\n\ttesting with this section."
  },
  {
    "code": "def what():\n    if not self.isactive():\n        lib.echo(\"No topic\")\n        sys.exit(lib.USER_ERROR)\n    lib.echo(os.environ.get(\"BE_TOPICS\", \"This is a bug\"))",
    "docstring": "Print current topics"
  },
  {
    "code": "def add(self, widget, condition=lambda: 42):\n        assert callable(condition)\n        assert isinstance(widget, BaseWidget)\n        self._widgets.append((widget, condition))\n        return widget",
    "docstring": "Add a widget to the widows.\n\n        The widget will auto render. You can use the function like that if you want to keep the widget accecible :\n            self.my_widget = self.add(my_widget)"
  },
  {
    "code": "def set_preferred(node):\n    if node < 0 or node > get_max_node():\n        raise ValueError(node)\n    libnuma.numa_set_preferred(node)",
    "docstring": "Sets  the preferred node for the current thread to node.\n\n    The preferred node is the node on which memory is preferably allocated before falling back to other\n    nodes. The default is to use the node on which the process is currently running (local policy).\n\n    @param node: node idx\n    @type node: C{int}"
  },
  {
    "code": "def setup():\n        name = \"Poisson\"\n        link = np.exp\n        scale = False\n        shape = False\n        skewness = False\n        mean_transform = np.log\n        cythonized = True\n        return name, link, scale, shape, skewness, mean_transform, cythonized",
    "docstring": "Returns the attributes of this family\n\n        Notes\n        ----------\n        - scale notes whether family has a variance parameter (sigma)\n        - shape notes whether family has a tail thickness parameter (nu)\n        - skewness notes whether family has a skewness parameter (gamma)\n        - mean_transform is a function which transforms the location parameter\n        - cythonized notes whether the family has cythonized routines\n        \n        Returns\n        ----------\n        - model name, link function, scale, shape, skewness, mean_transform, cythonized"
  },
  {
    "code": "def common(self):\n        res = {\"kty\": self.kty}\n        if self.use:\n            res[\"use\"] = self.use\n        if self.kid:\n            res[\"kid\"] = self.kid\n        if self.alg:\n            res[\"alg\"] = self.alg\n        return res",
    "docstring": "Return the set of parameters that are common to all types of keys.\n\n        :return: Dictionary"
  },
  {
    "code": "def start(self):\n        def cb():\n            time_ = time.time()\n            log.debug('Step {}'.format(time_))\n            for d in self._dstreams:\n                d._step(time_)\n        self._pcb = PeriodicCallback(cb, self.batch_duration * 1000.0)\n        self._pcb.start()\n        self._on_stop_cb.append(self._pcb.stop)\n        StreamingContext._activeContext = self",
    "docstring": "Start processing streams."
  },
  {
    "code": "def Cpu():\n    cpu = 'Unknown'\n    try:\n        cpu = str(multiprocessing.cpu_count())\n    except Exception as e:\n        logger.error(\"Can't access CPU count' \" + str(e))\n    return cpu",
    "docstring": "Get number of available CPUs"
  },
  {
    "code": "def migrate_into_triple(belstr: str) -> str:\n    bo.ast = bel.lang.partialparse.get_ast_obj(belstr, \"2.0.0\")\n    return migrate_ast(bo.ast).to_triple()",
    "docstring": "Migrate BEL1 assertion into BEL 2.0.0 SRO triple"
  },
  {
    "code": "def init():\n    if \"_\" not in builtins.__dict__:\n        os.environ[\"LANGUAGE\"] = inginious.input.get_lang()\n        if inginious.DEBUG:\n            gettext.install(\"messages\", get_lang_dir_path())\n        else:\n            gettext.install(\"messages\", get_lang_dir_path())",
    "docstring": "Install gettext with the default parameters"
  },
  {
    "code": "def add_path(self, path):\n        if os.path.exists(path):\n            self.paths.add(path)\n            return path\n        else:\n            return None",
    "docstring": "Adds a new path to the list of searchable paths\n\n        :param path: new path"
  },
  {
    "code": "def check_if_ok_to_update(self):\n        current_time = int(time.time())\n        last_refresh = self.last_refresh\n        if last_refresh is None:\n            last_refresh = 0\n        if current_time >= (last_refresh + self.refresh_rate):\n            return True\n        return False",
    "docstring": "Check if it is ok to perform an http request."
  },
  {
    "code": "def release(no_master, release_type):\n    try:\n        locale.setlocale(locale.LC_ALL, '')\n    except:\n        print(\"Warning: Unable to set locale.  Expect encoding problems.\")\n    git.is_repo_clean(master=(not no_master))\n    config = utils.get_config()\n    config.update(utils.get_dist_metadata())\n    config['project_dir'] = Path(os.getcwd())\n    config['release_type'] = release_type\n    with tempfile.TemporaryDirectory(prefix='ap_tmp') as tmp_dir:\n        config['tmp_dir'] = tmp_dir\n        values = release_ui(config)\n        if type(values) is not str:\n            utils.release(project_name=config['project_name'], tmp_dir=tmp_dir,\n                          project_dir=config['project_dir'],\n                          pypi_servers=config['pypi_servers'], **values)\n            print('New release options:')\n            pprint.pprint(values)\n        else:\n            print(values)",
    "docstring": "Releases a new version"
  },
  {
    "code": "def stratify_by_features(features, n_strata, **kwargs):\n    n_items = features.shape[0]\n    km = KMeans(n_clusters=n_strata, **kwargs)\n    allocations = km.fit_predict(X=features)\n    return Strata(allocations)",
    "docstring": "Stratify by clustering the items in feature space\n\n    Parameters\n    ----------\n    features : array-like, shape=(n_items,n_features)\n        feature matrix for the pool, where rows correspond to items and columns\n        correspond to features.\n\n    n_strata : int\n        number of strata to create.\n\n    **kwargs :\n        passed to sklearn.cluster.KMeans\n\n    Returns\n    -------\n    Strata instance"
  },
  {
    "code": "def sub_working_days(self, day, delta,\n                         extra_working_days=None, extra_holidays=None,\n                         keep_datetime=False):\n        delta = abs(delta)\n        return self.add_working_days(\n            day, -delta,\n            extra_working_days, extra_holidays, keep_datetime=keep_datetime)",
    "docstring": "Substract `delta` working days to the date.\n\n        This method is a shortcut / helper. Users may want to use either::\n\n            cal.add_working_days(my_date, -7)\n            cal.sub_working_days(my_date, 7)\n\n        The other parameters are to be used exactly as in the\n        ``add_working_days`` method.\n\n        A negative ``delta`` argument will be converted into its absolute\n        value. Hence, the two following calls are equivalent::\n\n            cal.sub_working_days(my_date, -7)\n            cal.sub_working_days(my_date, 7)\n\n        As in ``add_working_days()`` you can set the parameter\n        ``keep_datetime`` to ``True`` to make sure that if your ``day``\n        argument is a ``datetime``, the returned date will also be a\n        ``datetime`` object."
  },
  {
    "code": "def _set_suffix_links(self):\n        self._suffix_links_set = True\n        for current, parent in self.bfs():\n            if parent is None:\n                continue\n            current.longest_prefix = parent.longest_prefix\n            if parent.has_value:\n                current.longest_prefix = parent\n            if current.has_suffix:\n                continue\n            suffix = parent\n            while True:\n                if not suffix.has_suffix:\n                    current.suffix = self.root\n                    break\n                else:\n                    suffix = suffix.suffix\n                if current.uplink in suffix:\n                    current.suffix = suffix[current.uplink]\n                    break\n            suffix = current.suffix\n            while not suffix.has_value and suffix.has_suffix:\n                suffix = suffix.suffix\n            if suffix.has_value:\n                current.dict_suffix = suffix",
    "docstring": "Sets all suffix links in all nodes in this trie."
  },
  {
    "code": "def compose(*fs):\n    ensure_argcount(fs, min_=1)\n    fs = list(imap(ensure_callable, fs))\n    if len(fs) == 1:\n        return fs[0]\n    if len(fs) == 2:\n        f1, f2 = fs\n        return lambda *args, **kwargs: f1(f2(*args, **kwargs))\n    if len(fs) == 3:\n        f1, f2, f3 = fs\n        return lambda *args, **kwargs: f1(f2(f3(*args, **kwargs)))\n    fs.reverse()\n    def g(*args, **kwargs):\n        x = fs[0](*args, **kwargs)\n        for f in fs[1:]:\n            x = f(x)\n        return x\n    return g",
    "docstring": "Creates composition of the functions passed in.\n\n    :param fs: One-argument functions, with the possible exception of last one\n               that can accept arbitrary arguments\n\n    :return: Function returning a result of functions from ``fs``\n             applied consecutively to the argument(s), in reverse order"
  },
  {
    "code": "def set(self, instance, value, **kw):\n        value = str(value).decode(\"base64\")\n        if \"filename\" not in kw:\n            logger.debug(\"FielFieldManager::set: No Filename detected \"\n                         \"-> using title or id\")\n            kw[\"filename\"] = kw.get(\"id\") or kw.get(\"title\")\n        self._set(instance, value, **kw)",
    "docstring": "Decodes base64 value and set the file object"
  },
  {
    "code": "def ActiveDates(self):\n    (earliest, latest) = self.GetDateRange()\n    if earliest is None:\n      return []\n    dates = []\n    date_it = util.DateStringToDateObject(earliest)\n    date_end = util.DateStringToDateObject(latest)\n    delta = datetime.timedelta(days=1)\n    while date_it <= date_end:\n      date_it_string = date_it.strftime(\"%Y%m%d\")\n      if self.IsActiveOn(date_it_string, date_it):\n        dates.append(date_it_string)\n      date_it = date_it + delta\n    return dates",
    "docstring": "Return dates this service period is active as a list of \"YYYYMMDD\"."
  },
  {
    "code": "def sync(self, data):\n        for k, v in data.get('billing', {}).items():\n            setattr(self, k, v)\n        self.card_number = data.get('credit_card', {}).get('card_number',\n                                                           self.card_number)\n        self.save(sync=False)",
    "docstring": "Overwrite local customer payment profile data with remote data"
  },
  {
    "code": "def apply(self, arr):\n        for t in self.cpu_transforms:\n            arr = t.apply(arr)\n        return arr",
    "docstring": "Apply all CPU transforms on an array."
  },
  {
    "code": "def log_likelihood(covariance, precision):\n    assert covariance.shape == precision.shape\n    dim, _ = precision.shape\n    log_likelihood_ = (\n        -np.sum(covariance * precision)\n        + fast_logdet(precision)\n        - dim * np.log(2 * np.pi)\n    )\n    log_likelihood_ /= 2.\n    return log_likelihood_",
    "docstring": "Computes the log-likelihood between the covariance and precision\n    estimate.\n\n    Parameters\n    ----------\n    covariance : 2D ndarray (n_features, n_features)\n        Maximum Likelihood Estimator of covariance\n\n    precision : 2D ndarray (n_features, n_features)\n        The precision matrix of the covariance model to be tested\n\n    Returns\n    -------\n    log-likelihood"
  },
  {
    "code": "def setup_default_permissions(session, instance):\n    if instance not in session.new or not isinstance(instance, Entity):\n        return\n    if not current_app:\n        return\n    _setup_default_permissions(instance)",
    "docstring": "Setup default permissions on newly created entities according to.\n\n    :attr:`Entity.__default_permissions__`."
  },
  {
    "code": "def RattributesBM(dataset,database,host=rbiomart_host):\n    biomaRt = importr(\"biomaRt\")\n    ensemblMart=biomaRt.useMart(database, host=rbiomart_host)\n    ensembl=biomaRt.useDataset(dataset, mart=ensemblMart)\n    print(biomaRt.listAttributes(ensembl))",
    "docstring": "Lists BioMart attributes through a RPY2 connection.\n\n    :param dataset: a dataset listed in RdatasetsBM()\n    :param database: a database listed in RdatabasesBM()\n    :param host: address of the host server, default='www.ensembl.org'\n\n    :returns: nothing"
  },
  {
    "code": "def delete_file_or_tree(*args):\n    for f in args:\n        try:\n            os.unlink(f)\n        except OSError:\n            shutil.rmtree(f, ignore_errors=True)",
    "docstring": "For every path in args, try to delete it as a file or a directory\n    tree. Ignores deletion errors."
  },
  {
    "code": "def _estimate_runner_memory(json_file):\n    with open(json_file) as in_handle:\n        sinfo = json.load(in_handle)\n    num_parallel = 1\n    for key in [\"config__algorithm__variantcaller\", \"description\"]:\n        item_counts = []\n        n = 0\n        for val in (sinfo.get(key) or []):\n            n += 1\n            if val:\n                if isinstance(val, (list, tuple)):\n                    item_counts.append(len(val))\n                else:\n                    item_counts.append(1)\n        print(key, n, item_counts)\n        if n and item_counts:\n            num_parallel = n * max(item_counts)\n            break\n    if num_parallel < 25:\n        return \"3g\"\n    if num_parallel < 150:\n        return \"6g\"\n    elif num_parallel < 500:\n        return \"12g\"\n    else:\n        return \"24g\"",
    "docstring": "Estimate Java memory requirements based on number of samples.\n\n    A rough approach to selecting correct allocated memory for Cromwell."
  },
  {
    "code": "def min_ems(self, value: float) -> 'Size':\n        raise_not_number(value)\n        self.minimum = '{}em'.format(value)\n        return self",
    "docstring": "Set the minimum size in ems."
  },
  {
    "code": "def generate_all_aliases(fieldfile, include_global):\n    all_options = aliases.all(fieldfile, include_global=include_global)\n    if all_options:\n        thumbnailer = get_thumbnailer(fieldfile)\n        for key, options in six.iteritems(all_options):\n            options['ALIAS'] = key\n            thumbnailer.get_thumbnail(options)",
    "docstring": "Generate all of a file's aliases.\n\n    :param fieldfile: A ``FieldFile`` instance.\n    :param include_global: A boolean which determines whether to generate\n        thumbnails for project-wide aliases in addition to field, model, and\n        app specific aliases."
  },
  {
    "code": "def add_bookmark(self, url, favorite=False, archive=False, allow_duplicates=True):\n        rdb_url = self._generate_url('bookmarks')\n        params = {\n            \"url\": url,\n            \"favorite\": int(favorite),\n            \"archive\": int(archive),\n            \"allow_duplicates\": int(allow_duplicates)\n        }\n        return self.post(rdb_url, params)",
    "docstring": "Adds given bookmark to the authenticated user.\n\n        :param url: URL of the article to bookmark\n        :param favorite: whether or not the bookmark should be favorited\n        :param archive: whether or not the bookmark should be archived\n        :param allow_duplicates: whether or not to allow duplicate bookmarks to\n            be created for a given url"
  },
  {
    "code": "def set(self, document_data, merge=False):\n        batch = self._client.batch()\n        batch.set(self, document_data, merge=merge)\n        write_results = batch.commit()\n        return _first_write_result(write_results)",
    "docstring": "Replace the current document in the Firestore database.\n\n        A write ``option`` can be specified to indicate preconditions of\n        the \"set\" operation. If no ``option`` is specified and this document\n        doesn't exist yet, this method will create it.\n\n        Overwrites all content for the document with the fields in\n        ``document_data``. This method performs almost the same functionality\n        as :meth:`create`. The only difference is that this method doesn't\n        make any requirements on the existence of the document (unless\n        ``option`` is used), whereas as :meth:`create` will fail if the\n        document already exists.\n\n        Args:\n            document_data (dict): Property names and values to use for\n                replacing a document.\n            merge (Optional[bool] or Optional[List<apispec>]):\n                If True, apply merging instead of overwriting the state\n                of the document.\n\n        Returns:\n            google.cloud.firestore_v1beta1.types.WriteResult: The\n            write result corresponding to the committed document. A write\n            result contains an ``update_time`` field."
  },
  {
    "code": "def set_block_name(self, index, name):\n        if name is None:\n            return\n        self.GetMetaData(index).Set(vtk.vtkCompositeDataSet.NAME(), name)\n        self.Modified()",
    "docstring": "Set a block's string name at the specified index"
  },
  {
    "code": "def dimension(self):\n        self.dim = 0\n        self._slices = {}\n        for stochastic in self.stochastics:\n            if isinstance(stochastic.value, np.matrix):\n                p_len = len(stochastic.value.A.ravel())\n            elif isinstance(stochastic.value, np.ndarray):\n                p_len = len(stochastic.value.ravel())\n            else:\n                p_len = 1\n            self._slices[stochastic] = slice(self.dim, self.dim + p_len)\n            self.dim += p_len",
    "docstring": "Compute the dimension of the sampling space and identify the slices\n        belonging to each stochastic."
  },
  {
    "code": "def write_values(self):\n        return dict(((k, v.value) for k, v in self._inputs.items() if not v.is_secret and not v.is_empty(False)))",
    "docstring": "Return the dictionary with which to write values"
  },
  {
    "code": "def push_tx(self, crypto, tx_hex):\n        url = \"%s/pushtx\" % self.base_url\n        return self.post_url(url, {'hex': tx_hex}).content",
    "docstring": "This method is untested."
  },
  {
    "code": "def GetConfiguredUsers(self):\n    if os.path.exists(self.google_users_file):\n      users = open(self.google_users_file).readlines()\n    else:\n      users = []\n    return [user.strip() for user in users]",
    "docstring": "Retrieve the list of configured Google user accounts.\n\n    Returns:\n      list, the username strings of users congfigured by Google."
  },
  {
    "code": "def extract_date(cls, date_str):\n        if not date_str:\n            raise DateTimeFormatterException('date_str must a valid string {}.'.format(date_str))\n        try:\n            return cls._extract_timestamp(date_str, cls.DATE_FORMAT)\n        except (TypeError, ValueError):\n            raise DateTimeFormatterException('Invalid date string {}.'.format(date_str))",
    "docstring": "Tries to extract a `datetime` object from the given string, expecting\n        date information only.\n\n        Raises `DateTimeFormatterException` if the extraction fails."
  },
  {
    "code": "def _get_basin_response_term(self, C, z2pt5):\n        f_sed = np.zeros(len(z2pt5))\n        idx = z2pt5 < 1.0\n        f_sed[idx] = (C[\"c14\"] + C[\"c15\"] * float(self.CONSTS[\"SJ\"])) *\\\n            (z2pt5[idx] - 1.0)\n        idx = z2pt5 > 3.0\n        f_sed[idx] = C[\"c16\"] * C[\"k3\"] * exp(-0.75) *\\\n            (1.0 - np.exp(-0.25 * (z2pt5[idx] - 3.0)))\n        return f_sed",
    "docstring": "Returns the basin response term defined in equation 20"
  },
  {
    "code": "def _get_case_file_paths(tmp_dir, case, training_fraction=0.95):\n  paths = tf.gfile.Glob(\"%s/*.jpg\" % tmp_dir)\n  if not paths:\n    raise ValueError(\"Search of tmp_dir (%s) \" % tmp_dir,\n                     \"for subimage paths yielded an empty list, \",\n                     \"can't proceed with returning training/eval split.\")\n  split_index = int(math.floor(len(paths)*training_fraction))\n  if split_index >= len(paths):\n    raise ValueError(\"For a path list of size %s \"\n                     \"and a training_fraction of %s \"\n                     \"the resulting split_index of the paths list, \"\n                     \"%s, would leave no elements for the eval \"\n                     \"condition.\" % (len(paths),\n                                     training_fraction,\n                                     split_index))\n  if case:\n    return paths[:split_index]\n  else:\n    return paths[split_index:]",
    "docstring": "Obtain a list of image paths corresponding to training or eval case.\n\n  Args:\n    tmp_dir: str, the root path to which raw images were written, at the\n      top level having meta/ and raw/ subdirs.\n    case: bool, whether obtaining file paths for training (true) or eval\n      (false).\n    training_fraction: float, the fraction of the sub-image path list to\n      consider as the basis for training examples.\n\n  Returns:\n    list: A list of file paths.\n\n  Raises:\n    ValueError: if images not found in tmp_dir, or if training_fraction would\n      leave no examples for eval."
  },
  {
    "code": "def debug(self, msg, *args, **kwargs) -> Task:\n        return self._make_log_task(logging.DEBUG, msg, args, **kwargs)",
    "docstring": "Log msg with severity 'DEBUG'.\n\n        To pass exception information, use the keyword argument exc_info with\n        a true value, e.g.\n\n        await logger.debug(\"Houston, we have a %s\", \"thorny problem\", exc_info=1)"
  },
  {
    "code": "def calculate_output(self, variable_name, period):\n        variable = self.tax_benefit_system.get_variable(variable_name, check_existence = True)\n        if variable.calculate_output is None:\n            return self.calculate(variable_name, period)\n        return variable.calculate_output(self, variable_name, period)",
    "docstring": "Calculate the value of a variable using the ``calculate_output`` attribute of the variable."
  },
  {
    "code": "def evaluate_dir(sample_dir):\n    results = []\n    if sample_dir[-1] == \"/\":\n        sample_dir = sample_dir[:-1]\n    for filename in glob.glob(\"%s/*.inkml\" % sample_dir):\n        results.append(evaluate_inkml(filename))\n    return results",
    "docstring": "Evaluate all recordings in `sample_dir`.\n\n    Parameters\n    ----------\n    sample_dir : string\n        The path to a directory with *.inkml files.\n\n    Returns\n    -------\n    list of dictionaries\n        Each dictionary contains the keys 'filename' and 'results', where\n        'results' itself is a list of dictionaries. Each of the results has\n        the keys 'latex' and 'probability'"
  },
  {
    "code": "def cleanup(logger, *args):\n    for obj in args:\n        if obj is not None and hasattr(obj, 'cleanup'):\n            try:\n                obj.cleanup()\n            except NotImplementedError:\n                pass\n            except Exception:\n                logger.exception(\"Unable to cleanup %s object\", obj)",
    "docstring": "Environment's cleanup routine."
  },
  {
    "code": "def compress(data, compresslevel=9):\n    buf = BytesIO()\n    with open_fileobj(buf, 'wb', compresslevel) as ogz:\n        if six.PY3 and not isinstance(data, bytes):\n            data = data.encode(__salt_system_encoding__)\n        ogz.write(data)\n    compressed = buf.getvalue()\n    return compressed",
    "docstring": "Returns the data compressed at gzip level compression."
  },
  {
    "code": "def prepare(self, data_batch, sparse_row_id_fn=None):\n        super(SVRGModule, self).prepare(data_batch, sparse_row_id_fn=sparse_row_id_fn)\n        self._mod_aux.prepare(data_batch, sparse_row_id_fn=sparse_row_id_fn)",
    "docstring": "Prepares two modules for processing a data batch.\n\n        Usually involves switching bucket and reshaping.\n        For modules that contain `row_sparse` parameters in KVStore,\n        it prepares the `row_sparse` parameters based on the sparse_row_id_fn.\n\n        When KVStore is used to update parameters for multi-device or multi-machine training,\n        a copy of the parameters are stored in KVStore. Note that for `row_sparse` parameters,\n        the `update()` updates the copy of parameters in KVStore, but doesn't broadcast\n        the updated parameters to all devices / machines. The `prepare` function is used to\n        broadcast `row_sparse` parameters with the next batch of data.\n\n        Parameters\n        ----------\n        data_batch : DataBatch\n            The current batch of data for forward computation.\n\n        sparse_row_id_fn : A callback function\n            The function  takes `data_batch` as an input and returns a dict of\n            str -> NDArray. The resulting dict is used for pulling row_sparse\n            parameters from the kvstore, where the str key is the name of the param,\n            and the value is the row id of the param to pull."
  },
  {
    "code": "def statistic_recommend(classes, P):\n    if imbalance_check(P):\n        return IMBALANCED_RECOMMEND\n    if binary_check(classes):\n        return BINARY_RECOMMEND\n    return MULTICLASS_RECOMMEND",
    "docstring": "Return recommend parameters which are more suitable due to the input dataset characteristics.\n\n    :param classes:  all classes name\n    :type classes : list\n    :param P: condition positive\n    :type P : dict\n    :return: recommendation_list as list"
  },
  {
    "code": "def _load_scalar_fit(self, fit_key=None, h5file=None, fit_data=None):\n        if (fit_key is None) ^ (h5file is None):\n            raise ValueError(\"Either specify both fit_key and h5file, or\"\n                \" neither\")\n        if not ((fit_key is None) ^ (fit_data is None)):\n            raise ValueError(\"Specify exactly one of fit_key and fit_data.\")\n        if fit_data is None:\n            fit_data = self._read_dict(h5file[fit_key])\n        if 'fitType' in fit_data.keys() and fit_data['fitType'] == 'GPR':\n            fit = _eval_pysur.evaluate_fit.getGPRFitAndErrorEvaluator(fit_data)\n        else:\n            fit = _eval_pysur.evaluate_fit.getFitEvaluator(fit_data)\n        return fit",
    "docstring": "Loads a single fit"
  },
  {
    "code": "async def lock(self, container = None):\n        \"Wait for lock acquire\"\n        if container is None:\n            container = RoutineContainer.get_container(self.scheduler)\n        if self.locked:\n            pass\n        elif self.lockroutine:\n            await LockedEvent.createMatcher(self)\n        else:\n            await container.wait_for_send(LockEvent(self.context, self.key, self))\n            self.locked = True",
    "docstring": "Wait for lock acquire"
  },
  {
    "code": "def restore(self):\n        'Restore the file'\n        if not self.deleted:\n            raise JFSError('Tried to restore a not deleted file')\n        raise NotImplementedError('Jottacloud has changed the restore API. Please use jottacloud.com in a browser, for now.')\n        url = 'https://www.jottacloud.com/rest/webrest/%s/action/restore' % self.jfs.username\n        data = {'paths[]': self.path.replace(JFS_ROOT, ''),\n                'web': 'true',\n                'ts': int(time.time()),\n                'authToken': 0}\n        r = self.jfs.post(url, content=data)\n        return r",
    "docstring": "Restore the file"
  },
  {
    "code": "def iam_device_info(self, apdu):\n        if _debug: DeviceInfoCache._debug(\"iam_device_info %r\", apdu)\n        if not isinstance(apdu, IAmRequest):\n            raise ValueError(\"not an IAmRequest: %r\" % (apdu,))\n        device_instance = apdu.iAmDeviceIdentifier[1]\n        device_info = self.cache.get(device_instance, None)\n        if not device_info:\n            device_info = self.cache.get(apdu.pduSource, None)\n        if not device_info:\n            device_info = self.device_info_class(device_instance, apdu.pduSource)\n        device_info.deviceIdentifier = device_instance\n        device_info.address = apdu.pduSource\n        device_info.maxApduLengthAccepted = apdu.maxAPDULengthAccepted\n        device_info.segmentationSupported = apdu.segmentationSupported\n        device_info.vendorID = apdu.vendorID\n        self.update_device_info(device_info)",
    "docstring": "Create a device information record based on the contents of an\n        IAmRequest and put it in the cache."
  },
  {
    "code": "def get_point_cloud(self, pair):\n        disparity = self.block_matcher.get_disparity(pair)\n        points = self.block_matcher.get_3d(disparity,\n                                           self.calibration.disp_to_depth_mat)\n        colors = cv2.cvtColor(pair[0], cv2.COLOR_BGR2RGB)\n        return PointCloud(points, colors)",
    "docstring": "Get 3D point cloud from image pair."
  },
  {
    "code": "def send_text(self, text, **options):\n        return self.bot.send_message(self.id, text, **options)",
    "docstring": "Send a text message to the chat.\n\n        :param str text: Text of the message to send\n        :param options: Additional sendMessage options (see\n            https://core.telegram.org/bots/api#sendmessage"
  },
  {
    "code": "def generate_proto(source, require = True):\n  if not require and not os.path.exists(source):\n    return\n  output = source.replace(\".proto\", \"_pb2.py\").replace(\"../src/\", \"\")\n  if (not os.path.exists(output) or\n      (os.path.exists(source) and\n       os.path.getmtime(source) > os.path.getmtime(output))):\n    print(\"Generating %s...\" % output)\n    if not os.path.exists(source):\n      sys.stderr.write(\"Can't find required file: %s\\n\" % source)\n      sys.exit(-1)\n    if protoc is None:\n      sys.stderr.write(\n          \"protoc is not installed nor found in ../src.  Please compile it \"\n          \"or install the binary package.\\n\")\n      sys.exit(-1)\n    protoc_command = [ protoc, \"-I../src\", \"-I.\", \"--python_out=.\", source ]\n    if subprocess.call(protoc_command) != 0:\n      sys.exit(-1)",
    "docstring": "Invokes the Protocol Compiler to generate a _pb2.py from the given\n  .proto file.  Does nothing if the output already exists and is newer than\n  the input."
  },
  {
    "code": "def race(iterable, loop=None, timeout=None, *args, **kw):\n    assert_iter(iterable=iterable)\n    coros = []\n    resolved = False\n    result = None\n    @asyncio.coroutine\n    def resolver(index, coro):\n        nonlocal result\n        nonlocal resolved\n        value = yield from coro\n        if not resolved:\n            resolved = True\n            result = value\n            for _index, future in enumerate(coros):\n                if _index != index:\n                    future.cancel()\n    for index, coro in enumerate(iterable):\n        isfunction = asyncio.iscoroutinefunction(coro)\n        if not isfunction and not asyncio.iscoroutine(coro):\n            raise TypeError(\n                'paco: coro must be a coroutine or coroutine function')\n        if isfunction:\n            coro = coro(*args, **kw)\n        coros.append(ensure_future(resolver(index, coro)))\n    yield from asyncio.wait(coros, timeout=timeout, loop=loop)\n    return result",
    "docstring": "Runs coroutines from a given iterable concurrently without waiting until\n    the previous one has completed.\n\n    Once any of the tasks completes, the main coroutine\n    is immediately resolved, yielding the first resolved value.\n\n    All coroutines will be executed in the same loop.\n\n    This function is a coroutine.\n\n    Arguments:\n        iterable (iterable): an iterable collection yielding\n            coroutines functions or coroutine objects.\n        *args (mixed): mixed variadic arguments to pass to coroutines.\n        loop (asyncio.BaseEventLoop): optional event loop to use.\n        timeout (int|float): timeout can be used to control the maximum number\n            of seconds to wait before returning. timeout can be an int or\n            float. If timeout is not specified or None, there is no limit to\n            the wait time.\n        *args (mixed): optional variadic argument to pass to coroutine\n            function, if provided.\n\n    Raises:\n        TypeError: if ``iterable`` argument is not iterable.\n        asyncio.TimoutError: if wait timeout is exceeded.\n\n    Returns:\n        filtered values (list): ordered list of resultant values.\n\n    Usage::\n\n        async def coro1():\n            await asyncio.sleep(2)\n            return 1\n\n        async def coro2():\n            return 2\n\n        async def coro3():\n            await asyncio.sleep(1)\n            return 3\n\n        await paco.race([coro1, coro2, coro3])\n        # => 2"
  },
  {
    "code": "def stretch(image, mask=None):\n    image = np.array(image, float)\n    if np.product(image.shape) == 0:\n        return image\n    if mask is None:\n        minval = np.min(image)\n        maxval = np.max(image)\n        if minval == maxval:\n            if minval < 0:\n                return np.zeros_like(image)\n            elif minval > 1:\n                return np.ones_like(image)\n            return image\n        else:\n            return (image - minval) / (maxval - minval)\n    else:\n        significant_pixels = image[mask]\n        if significant_pixels.size == 0:\n            return image\n        minval = np.min(significant_pixels)\n        maxval = np.max(significant_pixels)\n        if minval == maxval:\n            transformed_image = minval\n        else:\n            transformed_image = ((significant_pixels - minval) /\n                                 (maxval - minval))\n        result = image.copy()\n        image[mask] = transformed_image\n        return image",
    "docstring": "Normalize an image to make the minimum zero and maximum one\n\n    image - pixel data to be normalized\n    mask  - optional mask of relevant pixels. None = don't mask\n\n    returns the stretched image"
  },
  {
    "code": "def cn(shape, dtype=None, impl='numpy', **kwargs):\n    cn_cls = tensor_space_impl(impl)\n    if dtype is None:\n        dtype = cn_cls.default_dtype(ComplexNumbers())\n    cn = cn_cls(shape=shape, dtype=dtype, **kwargs)\n    if not cn.is_complex:\n        raise ValueError('data type {!r} not a complex floating-point type.'\n                         ''.format(dtype))\n    return cn",
    "docstring": "Return a space of complex tensors.\n\n    Parameters\n    ----------\n    shape : positive int or sequence of positive ints\n        Number of entries per axis for elements in this space. A\n        single integer results in a space with 1 axis.\n    dtype : optional\n        Data type of each element. Can be provided in any way the\n        `numpy.dtype` function understands, e.g. as built-in type or\n        as a string. Only complex floating-point data types are allowed.\n        For ``None``, the `TensorSpace.default_dtype` of the\n        created space is used in the form\n        ``default_dtype(ComplexNumbers())``.\n    impl : str, optional\n        Impmlementation back-end for the space. See\n        `odl.space.entry_points.tensor_space_impl_names` for available\n        options.\n    kwargs :\n        Extra keyword arguments passed to the space constructor.\n\n    Returns\n    -------\n    cn : `TensorSpace`\n\n    Examples\n    --------\n    Space of complex 3-tuples with ``complex64`` entries:\n\n    >>> odl.cn(3, dtype='complex64')\n    cn(3, dtype='complex64')\n\n    Complex 2x3 tensors with ``complex64`` entries:\n\n    >>> odl.cn((2, 3), dtype='complex64')\n    cn((2, 3), dtype='complex64')\n\n    The default data type depends on the implementation. For\n    ``impl='numpy'``, it is ``'complex128'``:\n\n    >>> space = odl.cn((2, 3))\n    >>> space\n    cn((2, 3))\n    >>> space.dtype\n    dtype('complex128')\n\n    See Also\n    --------\n    tensor_space : Space of tensors with arbitrary scalar data type.\n    rn : Real tensor space."
  },
  {
    "code": "def ns(ns):\n    def setup_ns(cls):\n        setattr(cls, ENTITY_DEFAULT_NS_ATTR, ns)\n        return cls\n    return setup_ns",
    "docstring": "Class decorator that sets default tags namespace to use with its\n    instances."
  },
  {
    "code": "def _maybe_apply_time_shift(da, time_offset=None, **DataAttrs):\n        if time_offset is not None:\n            time = times.apply_time_offset(da[TIME_STR], **time_offset)\n            da[TIME_STR] = time\n        else:\n            if DataAttrs['dtype_in_time'] == 'inst':\n                if DataAttrs['intvl_in'].endswith('hr'):\n                    offset = -1 * int(DataAttrs['intvl_in'][0])\n                else:\n                    offset = 0\n                time = times.apply_time_offset(da[TIME_STR], hours=offset)\n                da[TIME_STR] = time\n        return da",
    "docstring": "Correct off-by-one error in GFDL instantaneous model data.\n\n        Instantaneous data that is outputted by GFDL models is generally off by\n        one timestep.  For example, a netCDF file that is supposed to\n        correspond to 6 hourly data for the month of January, will have its\n        last time value be in February."
  },
  {
    "code": "def parse_command(self, string):\n        possible_command, _, rest = string.partition(\" \")\n        possible_command = possible_command.lower()\n        if possible_command not in self.commands:\n            return None, None\n        event = self.commands[possible_command][\"event\"]\n        args = shlex.split(rest.strip())\n        return event, args",
    "docstring": "Parse out any possible valid command from an input string."
  },
  {
    "code": "def _get_initial_request(self):\n        if self._leaser is not None:\n            lease_ids = list(self._leaser.ack_ids)\n        else:\n            lease_ids = []\n        request = types.StreamingPullRequest(\n            modify_deadline_ack_ids=list(lease_ids),\n            modify_deadline_seconds=[self.ack_deadline] * len(lease_ids),\n            stream_ack_deadline_seconds=self.ack_histogram.percentile(99),\n            subscription=self._subscription,\n        )\n        return request",
    "docstring": "Return the initial request for the RPC.\n\n        This defines the initial request that must always be sent to Pub/Sub\n        immediately upon opening the subscription.\n\n        Returns:\n            google.cloud.pubsub_v1.types.StreamingPullRequest: A request\n            suitable for being the first request on the stream (and not\n            suitable for any other purpose)."
  },
  {
    "code": "def convert_dicts(d, to_class=AttrDictWrapper, from_class=dict):\n    d_ = to_class()\n    for key, value in d.iteritems():\n        if isinstance(value, from_class):\n            d_[key] = convert_dicts(value, to_class=to_class,\n                                    from_class=from_class)\n        else:\n            d_[key] = value\n    return d_",
    "docstring": "Recursively convert dict and UserDict types.\n\n    Note that `d` is unchanged.\n\n    Args:\n        to_class (type): Dict-like type to convert values to, usually UserDict\n            subclass, or dict.\n        from_class (type): Dict-like type to convert values from. If a tuple,\n            multiple types are converted.\n\n    Returns:\n        Converted data as `to_class` instance."
  },
  {
    "code": "def get_medium_attachment(self, name, controller_port, device):\n        if not isinstance(name, basestring):\n            raise TypeError(\"name can only be an instance of type basestring\")\n        if not isinstance(controller_port, baseinteger):\n            raise TypeError(\"controller_port can only be an instance of type baseinteger\")\n        if not isinstance(device, baseinteger):\n            raise TypeError(\"device can only be an instance of type baseinteger\")\n        attachment = self._call(\"getMediumAttachment\",\n                     in_p=[name, controller_port, device])\n        attachment = IMediumAttachment(attachment)\n        return attachment",
    "docstring": "Returns a medium attachment which corresponds to the controller with\n        the given name, on the given port and device slot.\n\n        in name of type str\n\n        in controller_port of type int\n\n        in device of type int\n\n        return attachment of type :class:`IMediumAttachment`\n\n        raises :class:`VBoxErrorObjectNotFound`\n            No attachment exists for the given controller/port/device combination."
  },
  {
    "code": "async def body(self):\n        if not isinstance(self._body, bytes):\n            self._body = await self._body\n        return self._body",
    "docstring": "A helper function which blocks until the body has been read\n        completely.\n        Returns the bytes of the body which the user should decode.\n\n        If the request does not have a body part (i.e. it is a GET\n        request) this function returns None."
  },
  {
    "code": "def _pprint(dic):\n    for key, value in dic.items():\n        print(\"        {0}: {1}\".format(key, value))",
    "docstring": "Prints a dictionary with one indentation level"
  },
  {
    "code": "def friendly_load(parser, token):\n    bits = token.contents.split()\n    if len(bits) >= 4 and bits[-2] == \"from\":\n        name = bits[-1]\n        try:\n            lib = find_library(parser, name)\n            subset = load_from_library(lib, name, bits[1:-2])\n            parser.add_library(subset)\n        except TemplateSyntaxError:\n            pass\n    else:\n        for name in bits[1:]:\n            try:\n                lib = find_library(parser, name)\n                parser.add_library(lib)\n            except TemplateSyntaxError:\n                pass\n    return LoadNode()",
    "docstring": "Tries to load a custom template tag set. Non existing tag libraries\n    are ignored.\n\n    This means that, if used in conjunction with ``if_has_tag``, you can try to\n    load the comments template tag library to enable comments even if the\n    comments framework is not installed.\n\n    For example::\n\n        {% load friendly_loader %}\n        {% friendly_load comments webdesign %}\n\n        {% if_has_tag render_comment_list %}\n            {% render_comment_list for obj %}\n        {% else %}\n            {% if_has_tag lorem %}\n                {% lorem %}\n            {% endif_has_tag %}\n        {% endif_has_tag %}"
  },
  {
    "code": "def fit(self, X, y, **kwargs):\n        self.estimator.fit(X, y, **kwargs)\n        self.draw()\n        return self",
    "docstring": "A simple pass-through method; calls fit on the estimator and then\n        draws the alpha-error plot."
  },
  {
    "code": "def tarball_files(work_dir, tar_name, uuid=None, files=None):\n    with tarfile.open(os.path.join(work_dir, tar_name), 'w:gz') as f_out:\n        for fname in files:\n            if uuid:\n                f_out.add(os.path.join(work_dir, fname), arcname=uuid + '.' + fname)\n            else:\n                f_out.add(os.path.join(work_dir, fname), arcname=fname)",
    "docstring": "Tars a group of files together into a tarball\n\n    work_dir: str       Current Working Directory\n    tar_name: str       Name of tarball\n    uuid: str           UUID to stamp files with\n    files: str(s)       List of filenames to place in the tarball from working directory"
  },
  {
    "code": "def safe_request(fct):\n    def inner(*args, **kwargs):\n        try:\n            _data = fct(*args, **kwargs)\n        except requests.exceptions.ConnectionError as error:\n            return {'error': str(error), 'status': 404}\n        if _data.ok:\n            if _data.content:\n                safe_data = _data.json()\n            else:\n                safe_data = {'success': True}\n        else:\n            safe_data = {'error': _data.reason, 'status': _data.status_code}\n        return safe_data\n    return inner",
    "docstring": "Return json messages instead of raising errors"
  },
  {
    "code": "def write_to_fitsfile(self, fitsfile, clobber=True):\n        from fermipy.skymap import Map\n        hpx_header = self._hpx.make_header()\n        index_map = Map(self.ipixs, self.wcs)\n        mult_map = Map(self.mult_val, self.wcs)\n        prim_hdu = index_map.create_primary_hdu()\n        mult_hdu = index_map.create_image_hdu()\n        for key in ['COORDSYS', 'ORDERING', 'PIXTYPE',\n                    'ORDERING', 'ORDER', 'NSIDE',\n                    'FIRSTPIX', 'LASTPIX']:\n            prim_hdu.header[key] = hpx_header[key]\n            mult_hdu.header[key] = hpx_header[key]\n        hdulist = fits.HDUList([prim_hdu, mult_hdu])\n        hdulist.writeto(fitsfile, overwrite=clobber)",
    "docstring": "Write this mapping to a FITS file, to avoid having to recompute it"
  },
  {
    "code": "def install_via_requirements(requirements_str, force=False):\n    if requirements_str[0] == '@':\n        path = requirements_str[1:]\n        if os.path.isfile(path):\n            yaml_data = load_yaml(path)\n            if 'packages' not in yaml_data.keys():\n                raise CommandException('Error in {filename}: missing \"packages\" node'.format(filename=path))\n        else:\n            raise CommandException(\"Requirements file not found: {filename}\".format(filename=path))\n    else:\n        yaml_data = yaml.safe_load(requirements_str)\n    for pkginfo in yaml_data['packages']:\n        info = parse_package_extended(pkginfo)\n        install(info.full_name, info.hash, info.version, info.tag, force=force)",
    "docstring": "Download multiple Quilt data packages via quilt.xml requirements file."
  },
  {
    "code": "def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']):\n    return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:])",
    "docstring": "Returns a human readable string reprentation of bytes"
  },
  {
    "code": "def category_count(self):\n        category_dict = self.categories\n        count_dict = {category: len(\n            category_dict[category]) for category in category_dict}\n        return count_dict",
    "docstring": "Returns the number of categories in `categories`."
  },
  {
    "code": "def _filter_filecommands(self, filecmd_iter):\n        if self.includes is None and self.excludes is None:\n            return list(filecmd_iter())\n        result = []\n        for fc in filecmd_iter():\n            if (isinstance(fc, commands.FileModifyCommand) or\n                isinstance(fc, commands.FileDeleteCommand)):\n                if self._path_to_be_kept(fc.path):\n                    fc.path = self._adjust_for_new_root(fc.path)\n                else:\n                    continue\n            elif isinstance(fc, commands.FileDeleteAllCommand):\n                pass\n            elif isinstance(fc, commands.FileRenameCommand):\n                fc = self._convert_rename(fc)\n            elif isinstance(fc, commands.FileCopyCommand):\n                fc = self._convert_copy(fc)\n            else:\n                self.warning(\"cannot handle FileCommands of class %s - ignoring\",\n                        fc.__class__)\n                continue\n            if fc is not None:\n                result.append(fc)\n        return result",
    "docstring": "Return the filecommands filtered by includes & excludes.\n\n        :return: a list of FileCommand objects"
  },
  {
    "code": "def notify_change(self, change):\n        name = change['name']\n        if self.comm is not None and self.comm.kernel is not None:\n            if name in self.keys and self._should_send_property(name, getattr(self, name)):\n                self.send_state(key=name)\n        super(Widget, self).notify_change(change)",
    "docstring": "Called when a property has changed."
  },
  {
    "code": "def tanimoto_coefficient(a, b):\n    return sum(map(lambda (x,y): float(x)*float(y), zip(a,b))) / sum([\n          -sum(map(lambda (x,y): float(x)*float(y), zip(a,b))),\n           sum(map(lambda x: float(x)**2, a)),\n           sum(map(lambda x: float(x)**2, b))])",
    "docstring": "Measured similarity between two points in a multi-dimensional space.\n\n    Returns:\n        1.0 if the two points completely overlap,\n        0.0 if the two points are infinitely far apart."
  },
  {
    "code": "def dump_engines(target=sys.stderr):\n    print(\"Available templating engines:\", file=target)\n    width = max(len(engine) for engine in engines.engines)\n    for handle, engine in sorted(engines.engines.items()):\n        description = engine.__doc__.split('\\n', 0)[0]\n        print(\"  %-*s  -  %s\" % (width, handle, description), file=target)",
    "docstring": "Print successfully imported templating engines."
  },
  {
    "code": "def get_points(self, measurement=None, tags=None):\n        if not isinstance(measurement,\n                          (bytes, type(b''.decode()), type(None))):\n            raise TypeError('measurement must be an str or None')\n        for series in self._get_series():\n            series_name = series.get('measurement',\n                                     series.get('name', 'results'))\n            if series_name is None:\n                if tags is None:\n                    for item in self._get_points_for_series(series):\n                        yield item\n            elif measurement in (None, series_name):\n                series_tags = series.get('tags', {})\n                for item in self._get_points_for_series(series):\n                    if tags is None or \\\n                            self._tag_matches(item, tags) or \\\n                            self._tag_matches(series_tags, tags):\n                        yield item",
    "docstring": "Return a generator for all the points that match the given filters.\n\n        :param measurement: The measurement name\n        :type measurement: str\n\n        :param tags: Tags to look for\n        :type tags: dict\n\n        :return: Points generator"
  },
  {
    "code": "def split_bits(value, *bits):\n    result = []\n    for b in reversed(bits):\n        mask = (1 << b) - 1\n        result.append(value & mask)\n        value = value >> b\n    assert value == 0\n    result.reverse()\n    return result",
    "docstring": "Split integer value into list of ints, according to `bits` list.\n\n    For example, split_bits(0x1234, 4, 8, 4) == [0x1, 0x23, 0x4]"
  },
  {
    "code": "def is_excluded_path(args, filepath):\n    for regexp_exclude_path in args.regexp:\n        if re.match(regexp_exclude_path, filepath):\n            return True\n    abspath = os.path.abspath(filepath)\n    if args.include:\n        out_of_include_dirs = True\n        for incl_path in args.include:\n            absolute_include_path = os.path.abspath(os.path.join(args.root, incl_path))\n            if is_child_dir(absolute_include_path, abspath):\n                out_of_include_dirs = False\n                break\n        if out_of_include_dirs:\n            return True\n    excl_rules = create_exclude_rules(args)\n    for i, rule in enumerate(excl_rules):\n        if rule[0] == abspath:\n            return rule[1]\n        if is_child_dir(rule[0], abspath):\n            last_result = rule[1]\n            for j in range(i + 1, len(excl_rules)):\n                rule_deep = excl_rules[j]\n                if not is_child_dir(rule_deep[0], abspath):\n                    break\n                last_result = rule_deep[1]\n            return last_result\n    return False",
    "docstring": "Returns true if the filepath is under the one of the exclude path."
  },
  {
    "code": "def search(self, **kwargs):\n        return super(ApiVlan, self).get(self.prepare_url('api/v3/vlan/',\n                                                         kwargs))",
    "docstring": "Method to search vlan's based on extends search.\n\n        :param search: Dict containing QuerySets to find vlan's.\n        :param include: Array containing fields to include on response.\n        :param exclude: Array containing fields to exclude on response.\n        :param fields:  Array containing fields to override default fields.\n        :param kind: Determine if result will be detailed ('detail') or basic ('basic').\n        :return: Dict containing vlan's"
  },
  {
    "code": "def expected_h(nvals, fit=\"RANSAC\"):\n  rsvals = [expected_rs(n) for n in nvals]\n  poly = poly_fit(np.log(nvals), np.log(rsvals), 1, fit=fit)\n  return poly[0]",
    "docstring": "Uses expected_rs to calculate the expected value for the Hurst exponent h\n  based on the values of n used for the calculation.\n\n  Args:\n    nvals (iterable of int):\n      the values of n used to calculate the individual (R/S)_n\n\n  KWargs:\n    fit (str):\n      the fitting method to use for the line fit, either 'poly' for normal\n      least squares polynomial fitting or 'RANSAC' for RANSAC-fitting which\n      is more robust to outliers\n\n  Returns:\n    float:\n      expected h for white noise"
  },
  {
    "code": "def _process_string_token(self, token, start_row, start_col):\n        for i, char in enumerate(token):\n            if char in QUOTES:\n                break\n        norm_quote = token[i:]\n        if len(norm_quote) >= 3 and norm_quote[:3] in TRIPLE_QUOTE_OPTS.values():\n            self._tokenized_triple_quotes[start_row] = (token, norm_quote[:3], start_row, start_col)\n            return\n        preferred_quote = SMART_QUOTE_OPTS.get(self.config.string_quote)\n        if self.config.string_quote in SMART_CONFIG_OPTS:\n            other_quote = next(q for q in QUOTES if q != preferred_quote)\n            if preferred_quote in token[i + 1:-1] and other_quote not in token[i + 1:-1]:\n                preferred_quote = other_quote\n        if norm_quote[0] != preferred_quote:\n            self._invalid_string_quote(\n                quote=norm_quote[0],\n                row=start_row,\n                correct_quote=preferred_quote,\n                col=start_col,\n            )",
    "docstring": "Internal method for identifying and checking string tokens\n        from the token stream.\n\n        Args:\n            token: the token to check.\n            start_row: the line on which the token was found.\n            start_col: the column on which the token was found."
  },
  {
    "code": "def dataset_list_cli(self,\n                         sort_by=None,\n                         size=None,\n                         file_type=None,\n                         license_name=None,\n                         tag_ids=None,\n                         search=None,\n                         user=None,\n                         mine=False,\n                         page=1,\n                         csv_display=False):\n        datasets = self.dataset_list(sort_by, size, file_type, license_name,\n                                     tag_ids, search, user, mine, page)\n        fields = ['ref', 'title', 'size', 'lastUpdated', 'downloadCount']\n        if datasets:\n            if csv_display:\n                self.print_csv(datasets, fields)\n            else:\n                self.print_table(datasets, fields)\n        else:\n            print('No datasets found')",
    "docstring": "a wrapper to datasets_list for the client. Additional parameters\n            are described here, see dataset_list for others.\n\n            Parameters\n            ==========\n            sort_by: how to sort the result, see valid_sort_bys for options\n            size: the size of the dataset, see valid_sizes for string options\n            file_type: the format, see valid_file_types for string options\n            license_name: string descriptor for license, see valid_license_names\n            tag_ids: tag identifiers to filter the search\n            search: a search term to use (default is empty string)\n            user: username to filter the search to\n            mine: boolean if True, group is changed to \"my\" to return personal\n            page: the page to return (default is 1)\n            csv_display: if True, print comma separated values instead of table"
  },
  {
    "code": "def close(self):\n        if self.message_handler:\n            self.message_handler.destroy()\n            self.message_handler = None\n        self._shutdown = True\n        if self._keep_alive_thread:\n            self._keep_alive_thread.join()\n            self._keep_alive_thread = None\n        if not self._session:\n            return\n        if not self._connection.cbs:\n            _logger.debug(\"Closing non-CBS session.\")\n            self._session.destroy()\n        else:\n            _logger.debug(\"CBS session pending.\")\n        self._session = None\n        if not self._ext_connection:\n            _logger.debug(\"Closing exclusive connection.\")\n            self._connection.destroy()\n        else:\n            _logger.debug(\"Shared connection remaining open.\")\n        self._connection = None",
    "docstring": "Close the client. This includes closing the Session\n        and CBS authentication layer as well as the Connection.\n        If the client was opened using an external Connection,\n        this will be left intact.\n\n        No further messages can be sent or received and the client\n        cannot be re-opened.\n\n        All pending, unsent messages will remain uncleared to allow\n        them to be inspected and queued to a new client."
  },
  {
    "code": "def monitor(app):\n    heroku_app = HerokuApp(dallinger_uid=app)\n    webbrowser.open(heroku_app.dashboard_url)\n    webbrowser.open(\"https://requester.mturk.com/mturk/manageHITs\")\n    heroku_app.open_logs()\n    check_call([\"open\", heroku_app.db_uri])\n    while _keep_running():\n        summary = get_summary(app)\n        click.clear()\n        click.echo(header)\n        click.echo(\"\\nExperiment {}\\n\".format(app))\n        click.echo(summary)\n        time.sleep(10)",
    "docstring": "Set up application monitoring."
  },
  {
    "code": "def multi_split(txt, delims):\n    res = [txt]\n    for delimChar in delims:\n        txt, res = res, []\n        for word in txt:\n            if len(word) > 1:\n                res += word.split(delimChar)\n    return res",
    "docstring": "split by multiple delimiters"
  },
  {
    "code": "def derive_key_block(self, master_secret, server_random,\n                         client_random, req_len):\n        seed = server_random + client_random\n        if self.tls_version <= 0x0300:\n            return self.prf(master_secret, seed, req_len)\n        else:\n            return self.prf(master_secret, b\"key expansion\", seed, req_len)",
    "docstring": "Perform the derivation of master_secret into a key_block of req_len\n        requested length. See RFC 5246, section 6.3."
  },
  {
    "code": "def get_templates_per_page(self, per_page=1000, page=1, params=None):\n        return self._get_resource_per_page(resource=TEMPLATES, per_page=per_page, page=page, params=params)",
    "docstring": "Get templates per page\n\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :param params: Search parameters. Default: {}\n        :return: list"
  },
  {
    "code": "def list_inactive_vms(**kwargs):\n    vms = []\n    conn = __get_conn(**kwargs)\n    for dom in _get_domain(conn, iterable=True, active=False):\n        vms.append(dom.name())\n    conn.close()\n    return vms",
    "docstring": "Return a list of names for inactive virtual machine on the minion\n\n    :param connection: libvirt connection URI, overriding defaults\n\n        .. versionadded:: 2019.2.0\n    :param username: username to connect with, overriding defaults\n\n        .. versionadded:: 2019.2.0\n    :param password: password to connect with, overriding defaults\n\n        .. versionadded:: 2019.2.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' virt.list_inactive_vms"
  },
  {
    "code": "def join_group_with_token(self, group_hashtag, group_jid, join_token):\n        log.info(\"[+] Trying to join the group '{}' with JID {}\".format(group_hashtag, group_jid))\n        return self._send_xmpp_element(roster.GroupJoinRequest(group_hashtag, join_token, group_jid))",
    "docstring": "Tries to join into a specific group, using a cryptographic token that was received earlier from a search\n\n        :param group_hashtag: The public hashtag of the group into which to join (like '#Music')\n        :param group_jid: The JID of the same group\n        :param join_token: a token that can be extracted in the callback on_group_search_response, after calling\n                           search_group()"
  },
  {
    "code": "def _get_association_classes(self, namespace):\n        class_repo = self._get_class_repo(namespace)\n        for cl in six.itervalues(class_repo):\n            if 'Association' in cl.qualifiers:\n                yield cl\n        return",
    "docstring": "Return iterator of associator classes from the class repo\n\n        Returns the classes that have associations qualifier.\n        Does NOT copy so these are what is in repository. User functions\n        MUST NOT modify these classes.\n\n        Returns: Returns generator where each yield returns a single\n                 association class"
  },
  {
    "code": "def gui_repaint(self, drawDC=None):\n        DEBUG_MSG(\"gui_repaint()\", 1, self)\n        if self.IsShownOnScreen():\n            if drawDC is None:\n                drawDC=wx.ClientDC(self)\n            drawDC.DrawBitmap(self.bitmap, 0, 0)\n        else:\n            pass",
    "docstring": "Performs update of the displayed image on the GUI canvas, using the\n        supplied device context.  If drawDC is None, a ClientDC will be used to\n        redraw the image."
  },
  {
    "code": "def create_atomic_wrapper(cls, wrapped_func):\n        def _create_atomic_wrapper(*args, **kwargs):\n            with transaction.atomic():\n                return wrapped_func(*args, **kwargs)\n        return _create_atomic_wrapper",
    "docstring": "Returns a wrapped function."
  },
  {
    "code": "def averaged_sgd_entropic_transport(a, b, M, reg, numItermax=300000, lr=None):\n    if lr is None:\n        lr = 1. / max(a / reg)\n    n_source = np.shape(M)[0]\n    n_target = np.shape(M)[1]\n    cur_beta = np.zeros(n_target)\n    ave_beta = np.zeros(n_target)\n    for cur_iter in range(numItermax):\n        k = cur_iter + 1\n        i = np.random.randint(n_source)\n        cur_coord_grad = coordinate_grad_semi_dual(b, M, reg, cur_beta, i)\n        cur_beta += (lr / np.sqrt(k)) * cur_coord_grad\n        ave_beta = (1. / k) * cur_beta + (1 - 1. / k) * ave_beta\n    return ave_beta",
    "docstring": "Compute the ASGD algorithm to solve the regularized semi continous measures optimal transport max problem\n\n    The function solves the following optimization problem:\n\n    .. math::\n        \\gamma = arg\\min_\\gamma <\\gamma,M>_F + reg\\cdot\\Omega(\\gamma)\n\n        s.t. \\gamma 1 = a\n\n             \\gamma^T 1= b\n\n             \\gamma \\geq 0\n\n    Where :\n\n    - M is the (ns,nt) metric cost matrix\n    - :math:`\\Omega` is the entropic regularization term with :math:`\\Omega(\\gamma)=\\sum_{i,j} \\gamma_{i,j}\\log(\\gamma_{i,j})`\n    - a and b are source and target weights (sum to 1)\n\n    The algorithm used for solving the problem is the ASGD algorithm\n    as proposed in [18]_ [alg.2]\n\n\n    Parameters\n    ----------\n\n    b : np.ndarray(nt,)\n        target measure\n    M : np.ndarray(ns, nt)\n        cost matrix\n    reg : float number\n        Regularization term > 0\n    numItermax : int number\n        number of iteration\n    lr : float number\n        learning rate\n\n\n    Returns\n    -------\n\n    ave_v : np.ndarray(nt,)\n        dual variable\n\n    Examples\n    --------\n\n    >>> n_source = 7\n    >>> n_target = 4\n    >>> reg = 1\n    >>> numItermax = 300000\n    >>> a = ot.utils.unif(n_source)\n    >>> b = ot.utils.unif(n_target)\n    >>> rng = np.random.RandomState(0)\n    >>> X_source = rng.randn(n_source, 2)\n    >>> Y_target = rng.randn(n_target, 2)\n    >>> M = ot.dist(X_source, Y_target)\n    >>> method = \"ASGD\"\n    >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,\n                                                      method, numItermax)\n    >>> print(asgd_pi)\n\n    References\n    ----------\n\n    [Genevay et al., 2016] :\n                    Stochastic Optimization for Large-scale Optimal Transport,\n                     Advances in Neural Information Processing Systems (2016),\n                      arXiv preprint arxiv:1605.08527."
  },
  {
    "code": "def recompile_all(path):\n    import os\n    if os.path.isdir(path):\n        for root, dirs, files in os.walk(path):\n            for name in files:\n                if name.endswith('.py'):\n                    filename = os.path.abspath(os.path.join(root, name))\n                    print >> sys.stderr, filename\n                    recompile(filename)\n    else:\n        filename = os.path.abspath(path)\n        recompile(filename)",
    "docstring": "recursively recompile all .py files in the directory"
  },
  {
    "code": "def as_dict(self):\n        tags_dict = dict(self)\n        tags_dict['@module'] = self.__class__.__module__\n        tags_dict['@class'] = self.__class__.__name__\n        return tags_dict",
    "docstring": "Dict representation.\n\n        Returns:\n            Dictionary of parameters from fefftags object"
  },
  {
    "code": "def _get_content(self, url):\n        \"Get HTML content\"\n        target_url = self._db_url + '/' + unquote(url)\n        log.debug(\"Opening '{0}'\".format(target_url))\n        try:\n            f = self.opener.open(target_url)\n        except HTTPError as e:\n            log.error(\"HTTP error, your session may be expired.\")\n            log.error(e)\n            if input(\"Request new permanent session and retry? (y/n)\") in 'yY':\n                self.request_permanent_session()\n                return self._get_content(url)\n            else:\n                return None\n        log.debug(\"Accessing '{0}'\".format(target_url))\n        try:\n            content = f.read()\n        except IncompleteRead as icread:\n            log.critical(\n                \"Incomplete data received from the DB, \" +\n                \"the data could be corrupted.\"\n            )\n            content = icread.partial\n        log.debug(\"Got {0} bytes of data.\".format(len(content)))\n        return content.decode('utf-8')",
    "docstring": "Get HTML content"
  },
  {
    "code": "def log(self, branch, remote):\r\n        log_hook = self.settings['rebase.log-hook']\r\n        if log_hook:\r\n            if ON_WINDOWS:\n                log_hook = re.sub(r'\\$(\\d+)', r'%\\1', log_hook)\r\n                log_hook = re.sub(r'%(?!\\d)', '%%', log_hook)\r\n                log_hook = re.sub(r'; ?', r'\\n', log_hook)\r\n                with NamedTemporaryFile(\r\n                        prefix='PyGitUp.', suffix='.bat', delete=False\r\n                ) as bat_file:\r\n                    bat_file.file.write(b'@echo off\\n')\r\n                    bat_file.file.write(log_hook.encode('utf-8'))\r\n                state = subprocess.call(\r\n                    [bat_file.name, branch.name, remote.name]\r\n                )\r\n                os.remove(bat_file.name)\r\n            else:\n                state = subprocess.call(\r\n                    [log_hook, 'git-up', branch.name, remote.name],\r\n                    shell=True\r\n                )\r\n            if self.testing:\r\n                assert state == 0, 'log_hook returned != 0'",
    "docstring": "Call a log-command, if set by git-up.fetch.all."
  },
  {
    "code": "def on_channel_open(self, channel):\n        self._logger.debug('Channel opened')\n        self._channel = channel\n        self._channel.parent_client = self\n        self.add_on_channel_close_callback()\n        self.setup_exchange(self._exchange)",
    "docstring": "Invoked by pika when the channel has been opened.\n        The channel object is passed in so we can make use of it.\n\n        Since the channel is now open, we'll declare the exchange to use.\n\n        :param pika.channel.Channel channel: The channel object"
  },
  {
    "code": "def update_col_from_series(self, column_name, series, cast=False):\n        logger.debug('updating column {!r} in table {!r}'.format(\n            column_name, self.name))\n        col_dtype = self.local[column_name].dtype\n        if series.dtype != col_dtype:\n            if cast:\n                series = series.astype(col_dtype)\n            else:\n                err_msg = \"Data type mismatch, existing:{}, update:{}\"\n                err_msg = err_msg.format(col_dtype, series.dtype)\n                raise ValueError(err_msg)\n        self.local.loc[series.index, column_name] = series",
    "docstring": "Update existing values in a column from another series.\n        Index values must match in both column and series. Optionally\n        casts data type to match the existing column.\n\n        Parameters\n        ---------------\n        column_name : str\n        series : panas.Series\n        cast: bool, optional, default False"
  },
  {
    "code": "def read(self, size=None):\n        if not self._open:\n            raise pycdlibexception.PyCdlibInvalidInput('I/O operation on closed file.')\n        if self._offset >= self._length:\n            return b''\n        if size is None or size < 0:\n            data = self.readall()\n        else:\n            readsize = min(self._length - self._offset, size)\n            data = self._fp.read(readsize)\n            self._offset += readsize\n        return data",
    "docstring": "A method to read and return up to size bytes.\n\n        Parameters:\n         size - Optional parameter to read size number of bytes; if None or\n                negative, all remaining bytes in the file will be read\n        Returns:\n         The number of bytes requested or the rest of the data left in the file,\n         whichever is smaller.  If the file is at or past EOF, returns an empty\n         bytestring."
  },
  {
    "code": "def find_args(event, arg_type):\n    args = event.get('arguments', {})\n    obj_tags = [arg for arg in args if arg['type'] == arg_type]\n    if obj_tags:\n        return [o['value']['@id'] for o in obj_tags]\n    else:\n        return []",
    "docstring": "Return IDs of all arguments of a given type"
  },
  {
    "code": "def _check_base_classes(base_classes, check_for_type):\n    return_value = False\n    for base in base_classes:\n        if base.__name__ == check_for_type:\n            return_value = True\n            break\n        else:\n            return_value = _check_base_classes(base.__bases__, check_for_type)\n            if return_value is True:\n                break\n    return return_value",
    "docstring": "Indicate whether ``check_for_type`` exists in ``base_classes``."
  },
  {
    "code": "def _json_column(**kwargs):\n    return db.Column(\n        JSONType().with_variant(\n            postgresql.JSON(none_as_null=True),\n            'postgresql',\n        ),\n        nullable=True,\n        **kwargs\n    )",
    "docstring": "Return JSON column."
  },
  {
    "code": "def get_pool_context(self):\n        context = {self.current.lane_id: self.current.role, 'self': self.current.role}\n        for lane_id, role_id in self.current.pool.items():\n            if role_id:\n                context[lane_id] = lazy_object_proxy.Proxy(\n                    lambda: self.role_model(super_context).objects.get(role_id))\n        return context",
    "docstring": "Builds context for the WF pool.\n\n        Returns:\n            Context dict."
  },
  {
    "code": "async def install_mediaroom_protocol(responses_callback, box_ip=None):\n    from . import version\n    _LOGGER.debug(version)\n    loop = asyncio.get_event_loop()\n    mediaroom_protocol = MediaroomProtocol(responses_callback, box_ip)\n    sock = create_socket()\n    await loop.create_datagram_endpoint(lambda: mediaroom_protocol, sock=sock)\n    return mediaroom_protocol",
    "docstring": "Install an asyncio protocol to process NOTIFY messages."
  },
  {
    "code": "def build(self, x, h, mask=None):\n        xw = tf.split(tf.matmul(x, self.w_matrix) + self.bias, 3, 1)\n        hu = tf.split(tf.matmul(h, self.U), 3, 1)\n        r = tf.sigmoid(xw[0] + hu[0])\n        z = tf.sigmoid(xw[1] + hu[1])\n        h1 = tf.tanh(xw[2] + r * hu[2])\n        next_h = h1 * (1 - z) + h * z\n        if mask is not None:\n            next_h = next_h * mask + h * (1 - mask)\n        return next_h",
    "docstring": "Build the GRU cell."
  },
  {
    "code": "def __create_header(self, command, command_string, session_id, reply_id):\n        buf = pack('<4H', command, 0, session_id, reply_id) + command_string\n        buf = unpack('8B' + '%sB' % len(command_string), buf)\n        checksum = unpack('H', self.__create_checksum(buf))[0]\n        reply_id += 1\n        if reply_id >= const.USHRT_MAX:\n            reply_id -= const.USHRT_MAX\n        buf = pack('<4H', command, checksum, session_id, reply_id)\n        return buf + command_string",
    "docstring": "Puts a the parts that make up a packet together and packs them into a byte string"
  },
  {
    "code": "async def jsk_vc_pause(self, ctx: commands.Context):\n        voice = ctx.guild.voice_client\n        if voice.is_paused():\n            return await ctx.send(\"Audio is already paused.\")\n        voice.pause()\n        await ctx.send(f\"Paused audio in {voice.channel.name}.\")",
    "docstring": "Pauses a running audio source, if there is one."
  },
  {
    "code": "def transformer_librispeech_tpu_v2():\n  hparams = transformer_librispeech_v2()\n  update_hparams_for_tpu(hparams)\n  hparams.batch_size = 16\n  librispeech.set_librispeech_length_hparams(hparams)\n  return hparams",
    "docstring": "HParams for training ASR model on Librispeech on TPU v2."
  },
  {
    "code": "def set_description(self):\n        if self.device_info['type'] == 'Router':\n            self.node['description'] = '%s %s' % (self.device_info['type'],\n                                                  self.device_info['model'])\n        else:\n            self.node['description'] = self.device_info['desc']",
    "docstring": "Set the node description"
  },
  {
    "code": "def _create_service(self, parameters={}, **kwargs):\n        logging.debug(\"_create_service()\")\n        logging.debug(str.join(',', [self.service_name, self.plan_name,\n            self.name, str(parameters)]))\n        return self.service.create_service(self.service_name, self.plan_name,\n                self.name, parameters, **kwargs)",
    "docstring": "Create a Cloud Foundry service that has custom parameters."
  },
  {
    "code": "def destroySingleton(cls):\n        singleton_key = '_{0}__singleton'.format(cls.__name__)\n        singleton = getattr(cls, singleton_key, None)\n        if singleton is not None:\n            setattr(cls, singleton_key, None)\n            singleton.close()\n            singleton.deleteLater()",
    "docstring": "Destroys the singleton instance of this class, if one exists."
  },
  {
    "code": "def format(self, fmt, locale=None):\n        return self._formatter.format(self, fmt, locale)",
    "docstring": "Formats the instance using the given format.\n\n        :param fmt: The format to use\n        :type fmt: str\n\n        :param locale: The locale to use\n        :type locale: str or None\n\n        :rtype: str"
  },
  {
    "code": "def join(self, pad=None, gap=None):\n        if not self:\n            return self.EntryClass(numpy.empty((0,) * self.EntryClass._ndim))\n        self.sort(key=lambda t: t.epoch.gps)\n        out = self[0].copy()\n        for series in self[1:]:\n            out.append(series, gap=gap, pad=pad)\n        return out",
    "docstring": "Concatenate all of the elements of this list into a single object\n\n        Parameters\n        ----------\n        pad : `float`, optional, default: `0.0`\n            value with which to pad gaps\n\n        gap : `str`, optional, default: `'raise'`\n            what to do if there are gaps in the data, one of\n\n            - ``'raise'`` - raise a `ValueError`\n            - ``'ignore'`` - remove gap and join data\n            - ``'pad'`` - pad gap with zeros\n\n            If `pad` is given and is not `None`, the default is ``'pad'``,\n            otherwise ``'raise'``.\n\n        Returns\n        -------\n        series : `gwpy.types.TimeSeriesBase` subclass\n             a single series containing all data from each entry in this list\n\n        See Also\n        --------\n        TimeSeries.append\n            for details on how the individual series are concatenated together"
  },
  {
    "code": "def establish_scp_conn(self):\n        ssh_connect_params = self.ssh_ctl_chan._connect_params_dict()\n        self.scp_conn = self.ssh_ctl_chan._build_ssh_client()\n        self.scp_conn.connect(**ssh_connect_params)\n        self.scp_client = scp.SCPClient(self.scp_conn.get_transport())",
    "docstring": "Establish the secure copy connection."
  },
  {
    "code": "def ConvertMessage(self, value, message):\n    message_descriptor = message.DESCRIPTOR\n    full_name = message_descriptor.full_name\n    if _IsWrapperMessage(message_descriptor):\n      self._ConvertWrapperMessage(value, message)\n    elif full_name in _WKTJSONMETHODS:\n      methodcaller(_WKTJSONMETHODS[full_name][1], value, message)(self)\n    else:\n      self._ConvertFieldValuePair(value, message)",
    "docstring": "Convert a JSON object into a message.\n\n    Args:\n      value: A JSON object.\n      message: A WKT or regular protocol message to record the data.\n\n    Raises:\n      ParseError: In case of convert problems."
  },
  {
    "code": "def update(self, series_list):\n        if not series_list:\n            self.series_notebook.AddPage(wx.Panel(self, -1), _(\"+\"))\n            return\n        self.updating = True\n        self.series_notebook.DeleteAllPages()\n        for page, attrdict in enumerate(series_list):\n            series_panel = SeriesPanel(self.grid, attrdict)\n            name = \"Series\"\n            self.series_notebook.InsertPage(page, series_panel, name)\n        self.series_notebook.AddPage(wx.Panel(self, -1), _(\"+\"))\n        self.updating = False",
    "docstring": "Updates widget content from series_list\n\n        Parameters\n        ----------\n        series_list: List of dict\n        \\tList of dicts with data from all series"
  },
  {
    "code": "def save(self, filename):\n        with io.open(filename,'w',encoding='utf-8') as f:\n            f.write(self.xml())",
    "docstring": "Save metadata to XML file"
  },
  {
    "code": "def get_expression_engine(self, name):\n        try:\n            return self.expression_engines[name]\n        except KeyError:\n            raise InvalidEngineError(\"Unsupported expression engine: {}\".format(name))",
    "docstring": "Return an expression engine instance."
  },
  {
    "code": "def normalizeFileFormatVersion(value):\n    if not isinstance(value, int):\n        raise TypeError(\"File format versions must be instances of \"\n                        \":ref:`type-int`, not %s.\"\n                        % type(value).__name__)\n    return value",
    "docstring": "Normalizes a font's file format version.\n\n    * **value** must be a :ref:`type-int`.\n    * Returned value will be a ``int``."
  },
  {
    "code": "def double_click(self):\n        self.scroll_to()\n        ActionChains(self.parent.driver).double_click(self._element).perform()",
    "docstring": "Performs a double click in the element.\n\n        Currently works only on Chrome driver."
  },
  {
    "code": "def _add_somatic_opts(opts, paired):\n    if \"--min-alternate-fraction\" not in opts and \"-F\" not in opts:\n        min_af = float(utils.get_in(paired.tumor_config, (\"algorithm\",\n                                                          \"min_allele_fraction\"), 10)) / 100.0\n        opts += \" --min-alternate-fraction %s\" % min_af\n    opts += (\" --pooled-discrete --pooled-continuous \"\n             \"--report-genotype-likelihood-max --allele-balance-priors-off\")\n    return opts",
    "docstring": "Add somatic options to current set. See _run_freebayes_paired for references."
  },
  {
    "code": "def set_status(self, new_status):\n        if new_status not in Report.allowed_statuses:\n            raise Exception('status must be one of: %s' % (', '.join(Report.allowed_statuses)))\n        self._data_fields['status'] = new_status.lower()",
    "docstring": "Set the status of the report.\n\n        :param new_status: the new status of the report (either PASSED, FAILED or ERROR)"
  },
  {
    "code": "def get_next_invoke_id(self, addr):\n        if _debug: StateMachineAccessPoint._debug(\"get_next_invoke_id\")\n        initialID = self.nextInvokeID\n        while 1:\n            invokeID = self.nextInvokeID\n            self.nextInvokeID = (self.nextInvokeID + 1) % 256\n            if initialID == self.nextInvokeID:\n                raise RuntimeError(\"no available invoke ID\")\n            for tr in self.clientTransactions:\n                if (invokeID == tr.invokeID) and (addr == tr.pdu_address):\n                    break\n            else:\n                break\n        return invokeID",
    "docstring": "Called by clients to get an unused invoke ID."
  },
  {
    "code": "def view_list(self):\n        done = set()\n        ret = []\n        while len(done) != self.count():\n            p = self.view_indexes(done)\n            if len(p) > 0:\n                ret.append(p)\n        return ret",
    "docstring": "return a list of polygon indexes lists for the waypoints"
  },
  {
    "code": "def token_delete(remote, token=''):\n    session_key = token_session_key(remote.name)\n    return session.pop(session_key, None)",
    "docstring": "Remove OAuth access tokens from session.\n\n    :param remote: The remote application.\n    :param token: Type of token to get. Data passed from ``oauth.request()`` to\n        identify which token to retrieve. (Default: ``''``)\n    :returns: The token."
  },
  {
    "code": "def from_dict(cls, d):\n        return cls(\n            d['rargname'],\n            d['value'],\n            list(d.get('properties', {}).items()),\n            d.get('optional', False)\n        )",
    "docstring": "Instantiate a Role from a dictionary representation."
  },
  {
    "code": "def _imm_delattr(self, name):\n    if _imm_is_persist(self):\n        values = _imm_value_data(self)\n        if name in values:\n            dd = object.__getattribute__(self, '__dict__')\n            if name in dd:\n                del dd[name]\n                if name in _imm_const_data(self): _imm_check(imm, [name])\n        else:\n            raise TypeError('Attempt to reset parameter \\'%s\\' of non-transient immutable' % name)\n    else:\n        return _imm_trans_delattr(self, name)",
    "docstring": "A persistent immutable's delattr allows the object's value-caches to be invalidated, otherwise\n    raises an exception."
  },
  {
    "code": "def GET_savedgetitemvalues(self) -> None:\n        dict_ = state.getitemvalues.get(self._id)\n        if dict_ is None:\n            self.GET_getitemvalues()\n        else:\n            for name, value in dict_.items():\n                self._outputs[name] = value",
    "docstring": "Get the previously saved values of all |GetItem| objects."
  },
  {
    "code": "def _generate_html(data, out):\n    print('<html>', file=out)\n    print('<body>', file=out)\n    _generate_html_table(data, out, 0)\n    print('</body>', file=out)\n    print('</html>', file=out)",
    "docstring": "Generate report data as HTML"
  },
  {
    "code": "def transitDurationCircular(P, R_s, R_p, a, i):\n    r\n    if i is nan:\n        i = 90 * aq.deg\n    i = i.rescale(aq.rad)\n    k = R_p / R_s\n    b = (a * cos(i)) / R_s\n    duration = (P / pi) * arcsin(((R_s * sqrt((1 + k) **\n                                              2 - b ** 2)) / (a * sin(i))).simplified)\n    return duration.rescale(aq.min)",
    "docstring": "r\"\"\"Estimation of the primary transit time. Assumes a circular orbit.\n\n    .. math::\n        T_\\text{dur} = \\frac{P}{\\pi}\\sin^{-1}\n        \\left[\\frac{R_\\star}{a}\\frac{\\sqrt{(1+k)^2 + b^2}}{\\sin{a}} \\right]\n\n    Where :math:`T_\\text{dur}` transit duration, P orbital period,\n    :math:`R_\\star` radius of the star, a is the semi-major axis,\n    k is :math:`\\frac{R_p}{R_s}`, b is :math:`\\frac{a}{R_*} \\cos{i}`\n\n    (Seager & Mallen-Ornelas 2003)"
  },
  {
    "code": "def timestamp(datetime_obj):\n    start_of_time = datetime.datetime(1970, 1, 1)\n    diff = datetime_obj - start_of_time\n    return diff.total_seconds()",
    "docstring": "Return Unix timestamp as float.\n\n    The number of seconds that have elapsed since January 1, 1970."
  },
  {
    "code": "def _parse_player_data(self, player_data):\n        for field in self.__dict__:\n            short_field = str(field)[1:]\n            if short_field == 'player_id' or \\\n               short_field == 'index' or \\\n               short_field == 'most_recent_season' or \\\n               short_field == 'name' or \\\n               short_field == 'weight' or \\\n               short_field == 'height' or \\\n               short_field == 'season':\n                continue\n            field_stats = []\n            if type(player_data) == dict:\n                for year, data in player_data.items():\n                    stats = pq(data['data'])\n                    value = self._parse_value(stats, short_field)\n                    field_stats.append(value)\n            else:\n                stats = pq(player_data)\n                value = self._parse_value(stats, short_field)\n                field_stats.append(value)\n            setattr(self, field, field_stats)",
    "docstring": "Parse all player information and set attributes.\n\n        Iterate through each class attribute to parse the data from the HTML\n        page and set the attribute value with the result.\n\n        Parameters\n        ----------\n        player_data : dictionary or string\n            If this class is inherited from the ``Player`` class, player_data\n            will be a dictionary where each key is a string representing the\n            season and each value contains the HTML data as a string. If this\n            class is inherited from the ``BoxscorePlayer`` class, player_data\n            will be a string representing the player's game statistics in HTML\n            format."
  },
  {
    "code": "def separate_namespace(qname):\n    \"Separates the namespace from the element\"\n    import re\n    try:\n        namespace, element_name = re.search('^{(.+)}(.+)$', qname).groups()\n    except:\n        namespace = None\n        element_name = qname\n    return namespace, element_name",
    "docstring": "Separates the namespace from the element"
  },
  {
    "code": "def _extract_player_stats(self, table, player_dict, home_or_away):\n        for row in table('tbody tr').items():\n            player_id = self._find_player_id(row)\n            if not player_id:\n                continue\n            name = self._find_player_name(row)\n            try:\n                player_dict[player_id]['data'] += str(row).strip()\n            except KeyError:\n                player_dict[player_id] = {\n                    'name': name,\n                    'data': str(row).strip(),\n                    'team': home_or_away\n                }\n        return player_dict",
    "docstring": "Combine all player stats into a single object.\n\n        Since each player generally has a couple of rows worth of stats (one\n        for basic stats and another for advanced stats) on the boxscore page,\n        both rows should be combined into a single string object to easily\n        query all fields from a single object instead of determining which row\n        to pull metrics from.\n\n        Parameters\n        ----------\n        table : PyQuery object\n            A PyQuery object of a single boxscore table, such as the home\n            team's advanced stats or the away team's basic stats.\n        player_dict : dictionary\n            A dictionary where each key is a string of the player's ID and each\n            value is a dictionary where the values contain the player's name,\n            HTML data, and a string constant indicating which team the player\n            is a member of.\n        home_or_away : string constant\n            A string constant indicating whether the player plays for the home\n            or away team.\n\n        Returns\n        -------\n        dictionary\n            Returns a ``dictionary`` where each key is a string of the player's\n            ID and each value is a dictionary where the values contain the\n            player's name, HTML data, and a string constant indicating which\n            team the player is a member of."
  },
  {
    "code": "async def click(self, entity, reply_to=None,\n                    silent=False, clear_draft=False, hide_via=False):\n        entity = await self._client.get_input_entity(entity)\n        reply_id = None if reply_to is None else utils.get_message_id(reply_to)\n        req = functions.messages.SendInlineBotResultRequest(\n            peer=entity,\n            query_id=self._query_id,\n            id=self.result.id,\n            silent=silent,\n            clear_draft=clear_draft,\n            hide_via=hide_via,\n            reply_to_msg_id=reply_id\n        )\n        return self._client._get_response_message(\n            req, await self._client(req), entity)",
    "docstring": "Clicks this result and sends the associated `message`.\n\n        Args:\n            entity (`entity`):\n                The entity to which the message of this result should be sent.\n\n            reply_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional):\n                If present, the sent message will reply to this ID or message.\n\n            silent (`bool`, optional):\n                If ``True``, the sent message will not notify the user(s).\n\n            clear_draft (`bool`, optional):\n                Whether the draft should be removed after sending the\n                message from this result or not. Defaults to ``False``.\n            \n            hide_via (`bool`, optional):\n                Whether the \"via @bot\" should be hidden or not.\n                Only works with certain bots (like @bing or @gif)."
  },
  {
    "code": "def _get_esxdatacenter_proxy_details():\n    det = __salt__['esxdatacenter.get_details']()\n    return det.get('vcenter'), det.get('username'), det.get('password'), \\\n            det.get('protocol'), det.get('port'), det.get('mechanism'), \\\n            det.get('principal'), det.get('domain'), det.get('datacenter')",
    "docstring": "Returns the running esxdatacenter's proxy details"
  },
  {
    "code": "def _validate_str_list(arg):\n    if isinstance(arg, six.binary_type):\n        ret = [salt.utils.stringutils.to_unicode(arg)]\n    elif isinstance(arg, six.string_types):\n        ret = [arg]\n    elif isinstance(arg, Iterable) and not isinstance(arg, Mapping):\n        ret = []\n        for item in arg:\n            if isinstance(item, six.string_types):\n                ret.append(item)\n            else:\n                ret.append(six.text_type(item))\n    else:\n        ret = [six.text_type(arg)]\n    return ret",
    "docstring": "ensure ``arg`` is a list of strings"
  },
  {
    "code": "def fbank(signal,samplerate=16000,winlen=0.025,winstep=0.01,\n          nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97,\n          winfunc=lambda x:numpy.ones((x,))):\n    highfreq= highfreq or samplerate/2\n    signal = sigproc.preemphasis(signal,preemph)\n    frames = sigproc.framesig(signal, winlen*samplerate, winstep*samplerate, winfunc)\n    pspec = sigproc.powspec(frames,nfft)\n    energy = numpy.sum(pspec,1)\n    energy = numpy.where(energy == 0,numpy.finfo(float).eps,energy)\n    fb = get_filterbanks(nfilt,nfft,samplerate,lowfreq,highfreq)\n    feat = numpy.dot(pspec,fb.T)\n    feat = numpy.where(feat == 0,numpy.finfo(float).eps,feat)\n    return feat,energy",
    "docstring": "Compute Mel-filterbank energy features from an audio signal.\n\n    :param signal: the audio signal from which to compute features. Should be an N*1 array\n    :param samplerate: the sample rate of the signal we are working with, in Hz.\n    :param winlen: the length of the analysis window in seconds. Default is 0.025s (25 milliseconds)\n    :param winstep: the step between successive windows in seconds. Default is 0.01s (10 milliseconds)\n    :param nfilt: the number of filters in the filterbank, default 26.\n    :param nfft: the FFT size. Default is 512.\n    :param lowfreq: lowest band edge of mel filters. In Hz, default is 0.\n    :param highfreq: highest band edge of mel filters. In Hz, default is samplerate/2\n    :param preemph: apply preemphasis filter with preemph as coefficient. 0 is no filter. Default is 0.97.\n    :param winfunc: the analysis window to apply to each frame. By default no window is applied. You can use numpy window functions here e.g. winfunc=numpy.hamming\n    :returns: 2 values. The first is a numpy array of size (NUMFRAMES by nfilt) containing features. Each row holds 1 feature vector. The\n        second return value is the energy in each frame (total energy, unwindowed)"
  },
  {
    "code": "def _update_ret(ret, goids, go2color):\n        if goids:\n            ret['GOs'].update(goids)\n        if go2color:\n            for goid, color in go2color.items():\n                ret['go2color'][goid] = color",
    "docstring": "Update 'GOs' and 'go2color' in dict with goids and go2color."
  },
  {
    "code": "def fei_metadata(self):\n        if not self.is_fei:\n            return None\n        tags = self.pages[0].tags\n        if 'FEI_SFEG' in tags:\n            return tags['FEI_SFEG'].value\n        if 'FEI_HELIOS' in tags:\n            return tags['FEI_HELIOS'].value\n        return None",
    "docstring": "Return FEI metadata from SFEG or HELIOS tags as dict."
  },
  {
    "code": "def formatargvalues(args, varargs, varkw, locals,\n                    formatarg=str,\n                    formatvarargs=lambda name: '*' + name,\n                    formatvarkw=lambda name: '**' + name,\n                    formatvalue=lambda value: '=' + repr(value),\n                    join=joinseq):\n    def convert(name, locals=locals,\n                formatarg=formatarg, formatvalue=formatvalue):\n        return formatarg(name) + formatvalue(locals[name])\n    specs = []\n    for i in range(len(args)):\n        specs.append(strseq(args[i], convert, join))\n    if varargs:\n        specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))\n    if varkw:\n        specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))\n    return '(' + string.join(specs, ', ') + ')'",
    "docstring": "Format an argument spec from the 4 values returned by getargvalues.\n\n    The first four arguments are (args, varargs, varkw, locals).  The\n    next four arguments are the corresponding optional formatting functions\n    that are called to turn names and values into strings.  The ninth\n    argument is an optional function to format the sequence of arguments."
  },
  {
    "code": "def get_storage(self, id_or_uri):\n        uri = self.URI + \"/{}/storage\".format(extract_id_from_uri(id_or_uri))\n        return self._client.get(uri)",
    "docstring": "Get storage details of an OS Volume.\n\n        Args:\n            id_or_uri: ID or URI of the OS Volume.\n\n        Returns:\n            dict: Storage details"
  },
  {
    "code": "def random_point_triangle(triangle, use_int_coords=True):\n        xs, ys = triangle.exterior.coords.xy\n        A, B, C = zip(xs[:-1], ys[:-1])\n        r1, r2 = np.random.rand(), np.random.rand()\n        rx, ry = (1 - sqrt(r1)) * np.asarray(A) + sqrt(r1) * (1 - r2) * np.asarray(B) + sqrt(r1) * r2 * np.asarray(C)\n        if use_int_coords:\n            rx, ry = round(rx), round(ry)\n            return Point(int(rx), int(ry))\n        return Point(rx, ry)",
    "docstring": "Selects a random point in interior of a triangle"
  },
  {
    "code": "def update(self, **kwargs):\n        tmos_version = self._meta_data['bigip'].tmos_version\n        if LooseVersion(tmos_version) > LooseVersion('12.0.0'):\n            msg = \"Update() is unsupported for User on version %s. \" \\\n                  \"Utilize Modify() method instead\" % tmos_version\n            raise UnsupportedOperation(msg)\n        else:\n            self._update(**kwargs)",
    "docstring": "Due to a password decryption bug\n\n        we will disable update() method for 12.1.0 and up"
  },
  {
    "code": "def free_processed_queue(self):\n        with self._lock:\n            if len(self._processed_coordinators) > 0:\n                for _coordinator in self._processed_coordinators:\n                    _coordinator.free_resources()\n                self._processed_coordinators = []",
    "docstring": "call the Aspera sdk to freeup resources"
  },
  {
    "code": "def _get_conda_channels(conda_bin):\n    channels = [\"bioconda\", \"conda-forge\"]\n    out = []\n    config = yaml.safe_load(subprocess.check_output([conda_bin, \"config\", \"--show\"]))\n    for c in channels:\n        present = False\n        for orig_c in config.get(\"channels\") or []:\n            if orig_c.endswith((c, \"%s/\" % c)):\n                present = True\n                break\n        if not present:\n            out += [\"-c\", c]\n    return out",
    "docstring": "Retrieve default conda channels, checking if they are pre-specified in config.\n\n    This allows users to override defaults with specific mirrors in their .condarc"
  },
  {
    "code": "def select_uri_implementation(ecore_model_path):\n    if URL_PATTERN.match(ecore_model_path):\n        return pyecore.resources.resource.HttpURI\n    return pyecore.resources.URI",
    "docstring": "Select the right URI implementation regarding the Ecore model path schema."
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'contentItems' in _dict:\n            args['content_items'] = [\n                ContentItem._from_dict(x) for x in (_dict.get('contentItems'))\n            ]\n        else:\n            raise ValueError(\n                'Required property \\'contentItems\\' not present in Content JSON'\n            )\n        return cls(**args)",
    "docstring": "Initialize a Content object from a json dictionary."
  },
  {
    "code": "def medial_axis(self, resolution=None, clip=None):\n        if resolution is None:\n            resolution = self.scale / 1000.0\n        from .exchange.misc import edges_to_path\n        edge_vert = [polygons.medial_axis(i, resolution, clip)\n                     for i in self.polygons_full]\n        medials = [Path2D(**edges_to_path(\n            edges=e, vertices=v)) for e, v in edge_vert]\n        medial = concatenate(medials)\n        return medial",
    "docstring": "Find the approximate medial axis based\n        on a voronoi diagram of evenly spaced points on the\n        boundary of the polygon.\n\n        Parameters\n        ----------\n        resolution : None or float\n          Distance between each sample on the polygon boundary\n        clip : None, or (2,) float\n          Min, max number of samples\n\n        Returns\n        ----------\n        medial : Path2D object\n          Contains only medial axis of Path"
  },
  {
    "code": "def get_option_as_list(self, optionname, delimiter=\",\", default=None):\n        option = self.get_option(optionname)\n        try:\n            opt_list = [opt.strip() for opt in option.split(delimiter)]\n            return list(filter(None, opt_list))\n        except Exception:\n            return default",
    "docstring": "Will try to return the option as a list separated by the\n        delimiter."
  },
  {
    "code": "def cached_query(qs, timeout=None):\n    cache_key = generate_cache_key(qs)\n    return get_cached(cache_key, list, args=(qs,), timeout=None)",
    "docstring": "Auto cached queryset and generate results."
  },
  {
    "code": "def deep_copy(item_original):\n    item = copy.copy(item_original)\n    item._id = uuid.uuid4().hex\n    if hasattr(item, '_children') and len(item._children) > 0:\n        children_new = collections.OrderedDict()\n        for subitem_original in item._children.values():\n            subitem = deep_copy(subitem_original)\n            subitem._parent = item\n            children_new[subitem.get_name()] = subitem\n        item._children = children_new\n    return item",
    "docstring": "Return a recursive deep-copy of item where each copy has a new ID."
  },
  {
    "code": "def clean(self, value):\n        if value:\n            value = value.replace('-', '').replace(' ', '')\n            self.card_type = verify_credit_card(value)\n            if self.card_type is None:\n                raise forms.ValidationError(\"Invalid credit card number.\")\n        return value",
    "docstring": "Raises a ValidationError if the card is not valid and stashes card type."
  },
  {
    "code": "def _max_weight_operator(ops: Iterable[PauliTerm]) -> Union[None, PauliTerm]:\n    mapping = dict()\n    for op in ops:\n        for idx, op_str in op:\n            if idx in mapping:\n                if mapping[idx] != op_str:\n                    return None\n            else:\n                mapping[idx] = op_str\n    op = functools.reduce(mul, (PauliTerm(op, q) for q, op in mapping.items()), sI())\n    return op",
    "docstring": "Construct a PauliTerm operator by taking the non-identity single-qubit operator at each\n    qubit position.\n\n    This function will return ``None`` if the input operators do not share a natural tensor\n    product basis.\n\n    For example, the max_weight_operator of [\"XI\", \"IZ\"] is \"XZ\". Asking for the max weight\n    operator of something like [\"XI\", \"ZI\"] will return None."
  },
  {
    "code": "def get_cairo_export_info(self, filetype):\n        export_dlg = CairoExportDialog(self.main_window, filetype=filetype)\n        if export_dlg.ShowModal() == wx.ID_OK:\n            info = export_dlg.get_info()\n            export_dlg.Destroy()\n            return info\n        else:\n            export_dlg.Destroy()",
    "docstring": "Shows Cairo export dialog and returns info\n\n        Parameters\n        ----------\n        filetype: String in [\"pdf\", \"svg\"]\n        \\tFile type for which export info is gathered"
  },
  {
    "code": "def _validate_rel(param, rels):\n    if param.field.count('/') > 1:\n        raise InvalidQueryParams(**{\n            'detail': 'The filter query param of \"%s\" is attempting to '\n                      'filter on a nested relationship which is not '\n                      'currently supported.' % param,\n            'links': LINK,\n            'parameter': PARAM,\n        })\n    elif '/' in param.field:\n        model_field = param.field.split('/')[0]\n        if model_field not in rels:\n            raise InvalidQueryParams(**{\n                'detail': 'The filter query param of \"%s\" is attempting to '\n                          'filter on a relationship but the \"%s\" field is '\n                          'NOT a relationship field.' % (param, model_field),\n                'links': LINK,\n                'parameter': PARAM,\n            })",
    "docstring": "Validate relationship based filters\n\n    We don't support nested filters currently.\n\n    FIX: Ensure the relationship filter field exists on the\n         relationships model!"
  },
  {
    "code": "def profile_create(name, config=None, devices=None, description=None,\n                   remote_addr=None,\n                   cert=None, key=None, verify_cert=True):\n    client = pylxd_client_get(remote_addr, cert, key, verify_cert)\n    config, devices = normalize_input_values(\n        config,\n        devices\n    )\n    try:\n        profile = client.profiles.create(name, config, devices)\n    except pylxd.exceptions.LXDAPIException as e:\n        raise CommandExecutionError(six.text_type(e))\n    if description is not None:\n        profile.description = description\n        pylxd_save_object(profile)\n    return _pylxd_model_to_dict(profile)",
    "docstring": "Creates a profile.\n\n        name :\n            The name of the profile to get.\n\n        config :\n            A config dict or None (None = unset).\n\n            Can also be a list:\n                [{'key': 'boot.autostart', 'value': 1},\n                 {'key': 'security.privileged', 'value': '1'}]\n\n        devices :\n            A device dict or None (None = unset).\n\n        description :\n            A description string or None (None = unset).\n\n        remote_addr :\n            An URL to a remote Server, you also have to give cert and key if\n            you provide remote_addr and its a TCP Address!\n\n            Examples:\n                https://myserver.lan:8443\n                /var/lib/mysocket.sock\n\n        cert :\n            PEM Formatted SSL Certificate.\n\n            Examples:\n                ~/.config/lxc/client.crt\n\n        key :\n            PEM Formatted SSL Key.\n\n            Examples:\n                ~/.config/lxc/client.key\n\n        verify_cert : True\n            Wherever to verify the cert, this is by default True\n            but in the most cases you want to set it off as LXD\n            normaly uses self-signed certificates.\n\n        CLI Examples:\n\n        .. code-block:: bash\n\n            $ salt '*' lxd.profile_create autostart config=\"{boot.autostart: 1, boot.autostart.delay: 2, boot.autostart.priority: 1}\"\n            $ salt '*' lxd.profile_create shared_mounts devices=\"{shared_mount: {type: 'disk', source: '/home/shared', path: '/home/shared'}}\"\n\n        See the `lxd-docs`_ for the details about the config and devices dicts.\n\n        .. _lxd-docs: https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-10"
  },
  {
    "code": "def get(self, obj, **kwargs):\n        assert self.getter is not None, \"Getter accessor is not specified.\"\n        if callable(self.getter):\n            return self.getter(obj, **_get_context(self._getter_argspec, kwargs))\n        assert isinstance(self.getter, string_types), \"Accessor must be a function or a dot-separated string.\"\n        for attr in self.getter.split(\".\"):\n            if isinstance(obj, dict):\n                obj = obj[attr]\n            else:\n                obj = getattr(obj, attr)\n        if callable(obj):\n            return obj()\n        return obj",
    "docstring": "Get an attribute from a value.\n\n        :param obj: Object to get the attribute value from.\n        :return: Value of object's attribute."
  },
  {
    "code": "def add_network(self, network, netmask, area=0):\n        if network == '' or netmask == '':\n            raise ValueError('network and mask values '\n                             'may not be empty')\n        cmd = 'network {}/{} area {}'.format(network, netmask, area)\n        return self.configure_ospf(cmd)",
    "docstring": "Adds a network to be advertised by OSPF\n\n           Args:\n               network (str):  The network to be advertised in dotted decimal\n                               notation\n               netmask (str):  The netmask to configure\n               area (str):  The area the network belongs to.\n                            By default this value is 0\n           Returns:\n               bool: True if the command completes successfully\n           Exception:\n               ValueError: This will get raised if network or netmask\n                           are not passed to the method"
  },
  {
    "code": "def deck_issue_mode(proto: DeckSpawnProto) -> Iterable[str]:\n    if proto.issue_mode == 0:\n        yield \"NONE\"\n        return\n    for mode, value in proto.MODE.items():\n        if value > proto.issue_mode:\n            continue\n        if value & proto.issue_mode:\n            yield mode",
    "docstring": "interpret issue mode bitfeg"
  },
  {
    "code": "def _extract_specs_dependencies(specs):\n    deps = set()\n    for signatures in specs.functions.values():\n        for signature in signatures:\n            for t in signature:\n                deps.update(pytype_to_deps(t))\n    for signature in specs.capsules.values():\n        for t in signature:\n            deps.update(pytype_to_deps(t))\n    return sorted(deps, key=lambda x: \"include\" not in x)",
    "docstring": "Extract types dependencies from specs for each exported signature."
  },
  {
    "code": "def get_attribute_from_config(config, section, attribute):\n    section = config.get(section)\n    if section:\n        option = section.get(attribute)\n        if option:\n            return option\n    raise ConfigurationError(\"Config file badly formed!\\n\"\n                             \"Failed to get attribute '{}' from section '{}'!\"\n                             .format(attribute, section))",
    "docstring": "Try to parse an attribute of the config file.\n\n    Args:\n        config (defaultdict): A defaultdict.\n        section (str): The section of the config file to get information from.\n        attribute (str): The attribute of the section to fetch.\n    Returns:\n        str: The string corresponding to the section and attribute.\n    Raises:\n        ConfigurationError"
  },
  {
    "code": "def pin_add(self, path, *paths, **kwargs):\n        if \"recursive\" in kwargs:\n            kwargs.setdefault(\"opts\", {\"recursive\": kwargs.pop(\"recursive\")})\n        args = (path,) + paths\n        return self._client.request('/pin/add', args, decoder='json', **kwargs)",
    "docstring": "Pins objects to local storage.\n\n        Stores an IPFS object(s) from a given path locally to disk.\n\n        .. code-block:: python\n\n            >>> c.pin_add(\"QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d\")\n            {'Pins': ['QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d']}\n\n        Parameters\n        ----------\n        path : str\n            Path to object(s) to be pinned\n        recursive : bool\n            Recursively unpin the object linked to by the specified object(s)\n\n        Returns\n        -------\n            dict : List of IPFS objects that have been pinned"
  },
  {
    "code": "def _convert_datetime_str(response):\n    if response:\n        return dict([(k, '{0}'.format(v)) if isinstance(v, datetime.date) else (k, v) for k, v in six.iteritems(response)])\n    return None",
    "docstring": "modify any key-value pair where value is a datetime object to a string."
  },
  {
    "code": "def marching_cubes(self):\n        meshed = matrix_to_marching_cubes(matrix=self.matrix,\n                                          pitch=self.pitch,\n                                          origin=self.origin)\n        return meshed",
    "docstring": "A marching cubes Trimesh representation of the voxels.\n\n        No effort was made to clean or smooth the result in any way;\n        it is merely the result of applying the scikit-image\n        measure.marching_cubes function to self.matrix.\n\n        Returns\n        ---------\n        meshed: Trimesh object representing the current voxel\n                        object, as returned by marching cubes algorithm."
  },
  {
    "code": "def cross_product_compare(start, candidate1, candidate2):\n    delta1 = candidate1 - start\n    delta2 = candidate2 - start\n    return cross_product(delta1, delta2)",
    "docstring": "Compare two relative changes by their cross-product.\n\n    This is meant to be a way to determine which vector is more \"inside\"\n    relative to ``start``.\n\n    .. note::\n\n       This is a helper for :func:`_simple_convex_hull`.\n\n    Args:\n        start (numpy.ndarray): The start vector (as 1D NumPy array with\n            2 elements).\n        candidate1 (numpy.ndarray): The first candidate vector (as 1D\n            NumPy array with 2 elements).\n        candidate2 (numpy.ndarray): The second candidate vector (as 1D\n            NumPy array with 2 elements).\n\n    Returns:\n        float: The cross product of the two differences."
  },
  {
    "code": "async def stop(self, **kwargs):\n        _LOGGER.debug('Shutting down pairing server')\n        if self._web_server is not None:\n            await self._web_server.shutdown()\n            self._server.close()\n        if self._server is not None:\n            await self._server.wait_closed()",
    "docstring": "Stop pairing server and unpublish service."
  },
  {
    "code": "def _combined_grouping_values(grouping_name,collection_a,collection_b):\n    new_grouping= collection_a.groupings.get(grouping_name,{}).copy()\n    new_grouping.update(collection_b.groupings.get(grouping_name,{}))\n    return new_grouping",
    "docstring": "returns a dict with values from both collections for a given grouping name\n\n    Warning: collection2 overrides collection1 if there is a group_key conflict"
  },
  {
    "code": "def import_localities(path, delimiter=';'):\n    creates = []\n    updates = []\n    with open(path, mode=\"r\") as infile:\n        reader = csv.DictReader(infile, delimiter=str(delimiter))\n        with atomic():\n            for row in reader:\n                row['point'] = Point(float(row['longitude']),\n                                     float(row['latitude']))\n                locality, created = Locality.objects.update_or_create(\n                    id=row['id'],\n                    defaults=row\n                )\n                if created:\n                    creates.append(locality)\n                else:\n                    updates.append(locality)\n    return creates, updates",
    "docstring": "Import localities from a CSV file.\n\n    :param path: Path to the CSV file containing the localities."
  },
  {
    "code": "def merge_graphs(main_graph, addition_graph):\n    node_mapping = {}\n    edge_mapping = {}\n    for node in addition_graph.get_all_node_objects():\n        node_id = node['id']\n        new_id = main_graph.new_node()\n        node_mapping[node_id] = new_id\n    for edge in addition_graph.get_all_edge_objects():\n        edge_id = edge['id']\n        old_vertex_a_id, old_vertex_b_id = edge['vertices']\n        new_vertex_a_id = node_mapping[old_vertex_a_id]\n        new_vertex_b_id = node_mapping[old_vertex_b_id]\n        new_edge_id = main_graph.new_edge(new_vertex_a_id, new_vertex_b_id)\n        edge_mapping[edge_id] = new_edge_id\n    return node_mapping, edge_mapping",
    "docstring": "Merges an ''addition_graph'' into the ''main_graph''.\n    Returns a tuple of dictionaries, mapping old node ids and edge ids to new ids."
  },
  {
    "code": "def generate_legacy_webfinger(template=None, *args, **kwargs):\n    if template == \"diaspora\":\n        webfinger = DiasporaWebFinger(*args, **kwargs)\n    else:\n        webfinger = BaseLegacyWebFinger(*args, **kwargs)\n    return webfinger.render()",
    "docstring": "Generate a legacy webfinger XRD document.\n\n    Template specific key-value pairs need to be passed as ``kwargs``, see classes.\n\n    :arg template: Ready template to fill with args, for example \"diaspora\" (optional)\n    :returns: Rendered XRD document (str)"
  },
  {
    "code": "def Acf(poly, dist, N=None, **kws):\n    if N is None:\n        N = len(poly)/2 + 1\n    corr = Corr(poly, dist, **kws)\n    out = numpy.empty(N)\n    for n in range(N):\n        out[n] = numpy.mean(corr.diagonal(n), 0)\n    return out",
    "docstring": "Auto-correlation function.\n\n    Args:\n        poly (Poly):\n            Polynomial of interest. Must have ``len(poly) > N``.\n        dist (Dist):\n            Defines the space the correlation is taken on.\n        N (int):\n            The number of time steps appart included. If omited set to\n            ``len(poly)/2+1``.\n\n    Returns:\n        (numpy.ndarray) :\n            Auto-correlation of ``poly`` with shape ``(N,)``. Note that by\n            definition ``Q[0]=1``.\n\n    Examples:\n        >>> poly = chaospy.prange(10)[1:]\n        >>> Z = chaospy.Uniform()\n        >>> print(numpy.around(chaospy.Acf(poly, Z, 5), 4))\n        [1.     0.9915 0.9722 0.9457 0.9127]"
  },
  {
    "code": "def new_registry_ont_id_transaction(self, ont_id: str, pub_key: str or bytes, b58_payer_address: str,\n                                        gas_limit: int, gas_price: int) -> Transaction:\n        if isinstance(pub_key, str):\n            bytes_ctrl_pub_key = bytes.fromhex(pub_key)\n        elif isinstance(pub_key, bytes):\n            bytes_ctrl_pub_key = pub_key\n        else:\n            raise SDKException(ErrorCode.param_err('a bytes or str type of public key is required.'))\n        args = dict(ontid=ont_id.encode('utf-8'), ctrl_pk=bytes_ctrl_pub_key)\n        tx = self.__generate_transaction('regIDWithPublicKey', args, b58_payer_address, gas_limit, gas_price)\n        return tx",
    "docstring": "This interface is used to generate a Transaction object which is used to register ONT ID.\n\n        :param ont_id: OntId.\n        :param pub_key: the hexadecimal public key in the form of string.\n        :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction.\n        :param gas_limit: an int value that indicate the gas limit.\n        :param gas_price: an int value that indicate the gas price.\n        :return: a Transaction object which is used to register ONT ID."
  },
  {
    "code": "def scrap(self,\n              url=None, scheme=None, timeout=None,\n              html_parser=None, cache_ext=None\n    ):\n        if not url:\n            url = self.url\n        if not scheme:\n            scheme = self.scheme\n        if not timeout:\n            timeout = self.timeout\n        if not html_parser:\n            html_parser = self.html_parser\n        if not scheme:\n            raise WEBParameterException(\"Missing scheme definition\")\n        if not url:\n            raise WEBParameterException(\"Missing url definition\")\n        resp = self.get(url, timeout, cache_ext=cache_ext)\n        soup = BeautifulSoup(resp.html, html_parser)\n        resp.scraped = self._parse_scheme(soup, scheme)\n        return resp",
    "docstring": "Scrap a url and parse the content according to scheme\n\n        :param url: Url to parse (default: self._url)\n        :type url: str\n        :param scheme: Scheme to apply to html (default: self._scheme)\n        :type scheme: dict\n        :param timeout: Timeout for http operation (default: self._timout)\n        :type timeout: float\n        :param html_parser: What html parser to use (default: self._html_parser)\n        :type html_parser: str | unicode\n        :param cache_ext: External cache info\n        :type cache_ext: floscraper.models.CacheInfo\n        :return: Response data from url and parsed info\n        :rtype: floscraper.models.Response\n        :raises WEBConnectException: HTTP get failed\n        :raises WEBParameterException: Missing scheme or url"
  },
  {
    "code": "def example_generator(self, encoder, tmp_dir, task_id):\n    filepaths = self.text_filepaths_for_task(tmp_dir, task_id)\n    if task_id >= self.num_train_shards:\n      max_chars_per_file = self.max_dev_chars // (\n          self.num_dev_shards * len(filepaths))\n    else:\n      max_chars_per_file = None\n    tokens = []\n    for ftext in self.file_generator(\n        filepaths, max_chars_per_file=max_chars_per_file):\n      tokens.extend(encoder.encode(ftext))\n      pos = 0\n      while pos + self.sequence_length <= len(tokens):\n        yield {\"targets\": tokens[pos:pos + self.sequence_length]}\n        pos += self.sequence_length\n      if pos > 0:\n        tokens = tokens[pos:]\n    if self.remainder_policy == \"pad\":\n      if tokens:\n        targets = tokens + [0] * (self.sequence_length - len(tokens))\n        yield {\"targets\": targets}\n    else:\n      assert self.remainder_policy == \"drop\"",
    "docstring": "Generator for examples.\n\n    Args:\n      encoder: a TextEncoder\n      tmp_dir: a string\n      task_id: an integer\n    Yields:\n      feature dictionaries"
  },
  {
    "code": "def setup_data(self, data, params):\n        check_required_aesthetics(\n            self.REQUIRED_AES,\n            data.columns,\n            self.__class__.__name__)\n        return data",
    "docstring": "Verify & return data"
  },
  {
    "code": "def finalize_env(env):\n    keys = _PLATFORM_ENV_KEYS.get(sys.platform, [])\n    if 'PATH' not in keys:\n        keys.append('PATH')\n    results = {\n        key: os.environ.get(key, '') for key in keys\n    }\n    results.update(env)\n    return results",
    "docstring": "Produce a platform specific env for passing into subprocess.Popen\n    family of external process calling methods, and the supplied env\n    will be updated on top of it.  Returns a new env."
  },
  {
    "code": "def symmetric_difference_update(self, other):\n        r\n        other = self._as_multiset(other)\n        elements = set(self.distinct_elements()) | set(other.distinct_elements())\n        for element in elements:\n            multiplicity = self[element]\n            other_count = other[element]\n            self[element] = (multiplicity - other_count if multiplicity > other_count else other_count - multiplicity)",
    "docstring": "r\"\"\"Update the multiset to contain only elements in either this multiset or the other but not both.\n\n        >>> ms = Multiset('aab')\n        >>> ms.symmetric_difference_update('abc')\n        >>> sorted(ms)\n        ['a', 'c']\n\n        You can also use the ``^=`` operator for the same effect. However, the operator version\n        will only accept a set as other operator, not any iterable, to avoid errors.\n\n        >>> ms = Multiset('aabbbc')\n        >>> ms ^= Multiset('abd')\n        >>> sorted(ms)\n        ['a', 'b', 'b', 'c', 'd']\n\n        For a variant of the operation which does not modify the multiset, but returns a new\n        multiset instead see :meth:`symmetric_difference`.\n\n        Args:\n            other: The other set to take the symmetric difference with. Can also be any :class:`~typing.Iterable`\\[~T]\n                or :class:`~typing.Mapping`\\[~T, :class:`int`] which are then converted to :class:`Multiset`\\[~T]."
  },
  {
    "code": "def best_precursor(clus, loci):\n    data_loci = sort_precursor(clus, loci)\n    current_size = data_loci[0][5]\n    best = 0\n    for item, locus in enumerate(data_loci):\n        if locus[3] - locus[2] > 70:\n            if locus[5] > current_size * 0.8:\n                best = item\n                break\n    best_loci = data_loci[best]\n    del data_loci[best]\n    data_loci.insert(0, best_loci)\n    return data_loci",
    "docstring": "Select best precursor asuming size around 100 nt"
  },
  {
    "code": "def hgetall(self, key):\n        def format_response(value):\n            return dict(zip(value[::2], value[1::2]))\n        return self._execute(\n            [b'HGETALL', key], format_callback=format_response)",
    "docstring": "Returns all fields and values of the has stored at `key`.\n\n        The underlying redis `HGETALL`_ command returns an array of\n        pairs.  This method converts that to a Python :class:`dict`.\n        It will return an empty :class:`dict` when the key is not\n        found.\n\n        .. note::\n\n           **Time complexity**: ``O(N)`` where ``N`` is the size\n           of the hash.\n\n        :param key: The key of the hash\n        :type key: :class:`str`, :class:`bytes`\n        :returns: a :class:`dict` of key to value mappings for all\n            fields in the hash\n\n        .. _HGETALL: http://redis.io/commands/hgetall"
  },
  {
    "code": "def set_rule(self, name, properties):\n        self._rule_attrs.append(name)\n        setattr(self, name, properties)",
    "docstring": "Set a rules as object attribute.\n\n        Arguments:\n            name (string): Rule name to set as attribute name.\n            properties (dict): Dictionnary of properties."
  },
  {
    "code": "def is_ignored(resource):\n    ignored_domains = current_app.config['LINKCHECKING_IGNORE_DOMAINS']\n    url = resource.url\n    if url:\n        parsed_url = urlparse(url)\n        return parsed_url.netloc in ignored_domains\n    return True",
    "docstring": "Check of the resource's URL is part of LINKCHECKING_IGNORE_DOMAINS"
  },
  {
    "code": "def pre_process_method_headers(method, headers):\n    method = method.lower()\n    _wsgi_headers = [\"content_length\", \"content_type\", \"query_string\",\n                     \"remote_addr\", \"remote_host\", \"remote_user\",\n                     \"request_method\", \"server_name\", \"server_port\"]\n    _transformed_headers = {}\n    for header, value in headers.items():\n        header = header.replace(\"-\", \"_\")\n        header = \"http_{header}\".format(\n            header=header) if header.lower() not in _wsgi_headers else header\n        _transformed_headers.update({header.upper(): value})\n    return method, _transformed_headers",
    "docstring": "Returns the lowered method.\n        Capitalize headers, prepend HTTP_ and change - to _."
  },
  {
    "code": "def dump_all(documents, stream=None, Dumper=Dumper,\n        default_style=None, default_flow_style=None,\n        canonical=None, indent=None, width=None,\n        allow_unicode=None, line_break=None,\n        encoding='utf-8', explicit_start=None, explicit_end=None,\n        version=None, tags=None):\n    getvalue = None\n    if stream is None:\n        if encoding is None:\n            from StringIO import StringIO\n        else:\n            from cStringIO import StringIO\n        stream = StringIO()\n        getvalue = stream.getvalue\n    dumper = Dumper(stream, default_style=default_style,\n            default_flow_style=default_flow_style,\n            canonical=canonical, indent=indent, width=width,\n            allow_unicode=allow_unicode, line_break=line_break,\n            encoding=encoding, version=version, tags=tags,\n            explicit_start=explicit_start, explicit_end=explicit_end)\n    try:\n        dumper.open()\n        for data in documents:\n            dumper.represent(data)\n        dumper.close()\n    finally:\n        dumper.dispose()\n    if getvalue:\n        return getvalue()",
    "docstring": "Serialize a sequence of Python objects into a YAML stream.\n    If stream is None, return the produced string instead."
  },
  {
    "code": "def characterSet(self, charset: str) -> None:\n        charset_node = self._find_charset_node() or Meta(parent=self.head)\n        charset_node.setAttribute('charset', charset)",
    "docstring": "Set character set of this document."
  },
  {
    "code": "def parse_line(self, line: str) -> None:\n        if line[0].isspace():\n            if self._last_key is None:\n                raise HTTPInputError(\"first header line cannot start with whitespace\")\n            new_part = \" \" + line.lstrip()\n            self._as_list[self._last_key][-1] += new_part\n            self._dict[self._last_key] += new_part\n        else:\n            try:\n                name, value = line.split(\":\", 1)\n            except ValueError:\n                raise HTTPInputError(\"no colon in header line\")\n            self.add(name, value.strip())",
    "docstring": "Updates the dictionary with a single header line.\n\n        >>> h = HTTPHeaders()\n        >>> h.parse_line(\"Content-Type: text/html\")\n        >>> h.get('content-type')\n        'text/html'"
  },
  {
    "code": "def amdf(lag, size):\n  filt = (1 - z ** -lag).linearize()\n  @tostream\n  def amdf_filter(sig, zero=0.):\n    return maverage(size)(abs(filt(sig, zero=zero)), zero=zero)\n  return amdf_filter",
    "docstring": "Average Magnitude Difference Function non-linear filter for a given\n  size and a fixed lag.\n\n  Parameters\n  ----------\n  lag :\n    Time lag, in samples. See ``freq2lag`` if needs conversion from\n    frequency values.\n  size :\n    Moving average size.\n\n  Returns\n  -------\n  A callable that accepts two parameters: a signal ``sig`` and the starting\n  memory element ``zero`` that behaves like the ``LinearFilter.__call__``\n  arguments. The output from that callable is a Stream instance, and has\n  no decimation applied.\n\n  See Also\n  --------\n  freq2lag :\n    Frequency (in rad/sample) to lag (in samples) converter."
  },
  {
    "code": "def addcommenttocommit(self, project_id, author, sha, path, line, note):\n        data = {\n            'author': author,\n            'note': note,\n            'path': path,\n            'line': line,\n            'line_type': 'new'\n        }\n        request = requests.post(\n            '{0}/{1}/repository/commits/{2}/comments'.format(self.projects_url, project_id, sha),\n            headers=self.headers, data=data, verify=self.verify_ssl)\n        if request.status_code == 201:\n            return True\n        else:\n            return False",
    "docstring": "Adds an inline comment to a specific commit\n\n        :param project_id: project id\n        :param author: The author info as returned by create mergerequest\n        :param sha: The name of a repository branch or tag or if not given the default branch\n        :param path: The file path\n        :param line: The line number\n        :param note: Text of comment\n        :return: True or False"
  },
  {
    "code": "def _reverse_index(self):\n        if self.y == 0:\n            self.display = [u\" \" * self.size[1]] + self.display[:-1]\n        else:\n            self.y -= 1",
    "docstring": "Move the cursor up one row in the same column. If the cursor is at the\n        first row, create a new row at the top."
  },
  {
    "code": "def tables(self):\n        with self.conn.cursor() as cur:\n            cur.execute(self.TABLES_QUERY)\n            for row in cur:\n                yield row",
    "docstring": "Yields table names."
  },
  {
    "code": "def union(self, other):\n        if self._slideDuration != other._slideDuration:\n            raise ValueError(\"the two DStream should have same slide duration\")\n        return self.transformWith(lambda a, b: a.union(b), other, True)",
    "docstring": "Return a new DStream by unifying data of another DStream with this DStream.\n\n        @param other: Another DStream having the same interval (i.e., slideDuration)\n                     as this DStream."
  },
  {
    "code": "def next(self):\n        if not self._cache:\n            self._cache = self._get_results()\n            self._retrieved += len(self._cache)\n        if not self._cache:\n            raise StopIteration()\n        return self._cache.pop(0)",
    "docstring": "Provide iteration capabilities\n\n        Use a small object cache for performance"
  },
  {
    "code": "def manage_request_types_view(request):\n    request_types = RequestType.objects.all()\n    return render_to_response('manage_request_types.html', {\n        'page_name': \"Admin - Manage Request Types\",\n        'request_types': request_types\n        }, context_instance=RequestContext(request))",
    "docstring": "Manage requests.  Display a list of request types with links to edit them.\n    Also display a link to add a new request type.  Restricted to presidents and superadmins."
  },
  {
    "code": "def run(self, stop):\n        _LOGGER.info(\"Starting a new pipeline on group %s\", self._group)\n        self._group.bridge.incr_active()\n        for i, stage in enumerate(self._pipe):\n            self._execute_stage(i, stage, stop)\n        _LOGGER.info(\"Finished pipeline on group %s\", self._group)\n        self._group.bridge.decr_active()",
    "docstring": "Run the pipeline.\n\n        :param stop: Stop event"
  },
  {
    "code": "def via_scan():\n    import socket\n    import ipaddress\n    import httpfind\n    bridges_from_scan = []\n    hosts = socket.gethostbyname_ex(socket.gethostname())[2]\n    for host in hosts:\n        bridges_from_scan += httpfind.survey(\n            ipaddress.ip_interface(host+'/24').network,\n            path='description.xml',\n            pattern='(P|p)hilips')\n        logger.info('Scan on %s', host)\n    logger.info('Scan returned %d Hue bridges(s).', len(bridges_from_scan))\n    found_bridges = {}\n    for bridge in bridges_from_scan:\n        serial, bridge_info = parse_description_xml(bridge)\n        if serial:\n            found_bridges[serial] = bridge_info\n    logger.debug('%s', found_bridges)\n    if found_bridges:\n        return found_bridges\n    else:\n        raise DiscoveryError('Scan returned nothing')",
    "docstring": "IP scan - now implemented"
  },
  {
    "code": "def freeze(self, tmp_dir):\n        for sfile in self.secrets():\n            src_file = hard_path(sfile, self.opt.secrets)\n            if not os.path.exists(src_file):\n                raise aomi_excep.IceFile(\"%s secret not found at %s\" %\n                                         (self, src_file))\n            dest_file = \"%s/%s\" % (tmp_dir, sfile)\n            dest_dir = os.path.dirname(dest_file)\n            if not os.path.isdir(dest_dir):\n                os.mkdir(dest_dir, 0o700)\n            shutil.copy(src_file, dest_file)\n            LOG.debug(\"Froze %s %s\", self, sfile)",
    "docstring": "Copies a secret into a particular location"
  },
  {
    "code": "def _delegate_required(self, path):\n        fs = self._delegate(path)\n        if fs is None:\n            raise errors.ResourceNotFound(path)\n        return fs",
    "docstring": "Check that there is a filesystem with the given ``path``."
  },
  {
    "code": "def Define_TreeTable(self, heads, heads2=None):\n        display_heads = []\n        display_heads.append(tuple(heads[2:]))\n        self.tree_table = TreeTable()\n        self.tree_table.append_from_list(display_heads, fill_title=True)\n        if heads2 is not None:\n            heads2_color = heads2[1]\n            row_widget = gui.TableRow()\n            for index, field in enumerate(heads2[2:]):\n                row_item = gui.TableItem(text=field,\n                                         style={'background-color': heads2_color})\n                row_widget.append(row_item, field)\n            self.tree_table.append(row_widget, heads2[0])\n        self.wid.append(self.tree_table)",
    "docstring": "Define a TreeTable with a heading row\n            and optionally a second heading row."
  },
  {
    "code": "def is_translocated(graph: BELGraph, node: BaseEntity) -> bool:\n    return _node_has_modifier(graph, node, TRANSLOCATION)",
    "docstring": "Return true if over any of the node's edges, it is translocated."
  },
  {
    "code": "def DeserializeUnsigned(self, reader):\n        self.Version = reader.ReadUInt32()\n        self.PrevHash = reader.ReadUInt256()\n        self.MerkleRoot = reader.ReadUInt256()\n        self.Timestamp = reader.ReadUInt32()\n        self.Index = reader.ReadUInt32()\n        self.ConsensusData = reader.ReadUInt64()\n        self.NextConsensus = reader.ReadUInt160()",
    "docstring": "Deserialize unsigned data only.\n\n        Args:\n            reader (neo.IO.BinaryReader):"
  },
  {
    "code": "def _on_github_request(self, future, response):\n        try:\n            content = escape.json_decode(response.body)\n        except ValueError as error:\n            future.set_exception(Exception('Github error: %s' %\n                                           response.body))\n            return\n        if 'error' in content:\n            future.set_exception(Exception('Github error: %s' %\n                                           str(content['error'])))\n            return\n        future.set_result(content)",
    "docstring": "Invoked as a response to the GitHub API request. Will decode the\n        response and set the result for the future to return the callback or\n        raise an exception"
  },
  {
    "code": "def dry_run(self):\n        if self.database_current_migration is None:\n            self.printer(\n                    u'~> Woulda initialized: %s\\n' % self.name_for_printing())\n            return u'inited'\n        migrations_to_run = self.migrations_to_run()\n        if migrations_to_run:\n            self.printer(\n                u'~> Woulda updated %s:\\n' % self.name_for_printing())\n            for migration_number, migration_func in migrations_to_run():\n                self.printer(\n                    u'   + Would update %s, \"%s\"\\n' % (\n                        migration_number, migration_func.func_name))\n            return u'migrated'",
    "docstring": "Print out a dry run of what we would have upgraded."
  },
  {
    "code": "def _create_worker(self, method, *args, **kwargs):\n        thread = QThread()\n        worker = ClientWorker(method, args, kwargs)\n        worker.moveToThread(thread)\n        worker.sig_finished.connect(self._start)\n        worker.sig_finished.connect(thread.quit)\n        thread.started.connect(worker.start)\n        self._queue.append(thread)\n        self._threads.append(thread)\n        self._workers.append(worker)\n        self._start()\n        return worker",
    "docstring": "Create a worker for this client to be run in a separate thread."
  },
  {
    "code": "def repoExitError(message):\n    wrapper = textwrap.TextWrapper(\n        break_on_hyphens=False, break_long_words=False)\n    formatted = wrapper.fill(\"{}: error: {}\".format(sys.argv[0], message))\n    sys.exit(formatted)",
    "docstring": "Exits the repo manager with error status."
  },
  {
    "code": "def get_instance(self, payload):\n        return FactorInstance(\n            self._version,\n            payload,\n            service_sid=self._solution['service_sid'],\n            identity=self._solution['identity'],\n        )",
    "docstring": "Build an instance of FactorInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.authy.v1.service.entity.factor.FactorInstance\n        :rtype: twilio.rest.authy.v1.service.entity.factor.FactorInstance"
  },
  {
    "code": "def start_pymol(quiet=False, options='-p', run=False):\n    import pymol\n    pymol.pymol_argv = ['pymol', '%s' % options] + sys.argv[1:]\n    if run:\n        initialize_pymol(options)\n    if quiet:\n        pymol.cmd.feedback('disable', 'all', 'everything')",
    "docstring": "Starts up PyMOL and sets general options. Quiet mode suppresses all PyMOL output.\n    Command line options can be passed as the second argument."
  },
  {
    "code": "def to_even_columns(data, headers=None):\n    result = ''\n    col_width = max(len(word) for row in data for word in row) + 2\n    if headers:\n        header_width = max(len(word) for row in headers for word in row) + 2\n        if header_width > col_width:\n            col_width = header_width\n        result += \"\".join(word.ljust(col_width) for word in headers) + \"\\n\"\n        result += '-' * col_width * len(headers) + \"\\n\"\n    for row in data:\n        result += \"\".join(word.ljust(col_width) for word in row) + \"\\n\"\n    return result",
    "docstring": "Nicely format the 2-dimensional list into evenly spaced columns"
  },
  {
    "code": "def has_bitshifts(self):\n        def _has_bitshifts(expr):\n            if isinstance(expr, pyvex.IRExpr.Binop):\n                return expr.op.startswith(\"Iop_Shl\") or expr.op.startswith(\"Iop_Shr\") \\\n                       or expr.op.startswith(\"Iop_Sar\")\n            return False\n        found_bitops = False\n        for block in self._function.blocks:\n            if block.size == 0:\n                continue\n            for stmt in block.vex.statements:\n                if isinstance(stmt, pyvex.IRStmt.Put):\n                    found_bitops = found_bitops or _has_bitshifts(stmt.data)\n                elif isinstance(stmt, pyvex.IRStmt.WrTmp):\n                    found_bitops = found_bitops or _has_bitshifts(stmt.data)\n            if found_bitops:\n                break\n        if found_bitops:\n            return { CodeTags.HAS_BITSHIFTS }\n        return None",
    "docstring": "Detects if there is any bitwise operation in the function.\n\n        :return: Tags."
  },
  {
    "code": "def _get_raw_data(self, is_valid_key, data_key):\n        result = None\n        if self._read_imu():\n            data = self._imu.getIMUData()\n            if data[is_valid_key]:\n                raw = data[data_key]\n                result = {\n                    'x': raw[0],\n                    'y': raw[1],\n                    'z': raw[2]\n                }\n        return result",
    "docstring": "Internal. Returns the specified raw data from the IMU when valid"
  },
  {
    "code": "def add_string_as_file(self, content, filename, pred=None):\n        summary = content.splitlines()[0] if content else ''\n        if not isinstance(summary, six.string_types):\n            summary = content.decode('utf8', 'ignore')\n        if not self.test_predicate(cmd=False, pred=pred):\n            self._log_info(\"skipped string ...'%s' due to predicate (%s)\" %\n                           (summary, self.get_predicate(pred=pred)))\n            return\n        self.copy_strings.append((content, filename))\n        self._log_debug(\"added string ...'%s' as '%s'\" % (summary, filename))",
    "docstring": "Add a string to the archive as a file named `filename`"
  },
  {
    "code": "def check_video(video, languages=None, age=None, undefined=False):\n    if languages and not (languages - video.subtitle_languages):\n        logger.debug('All languages %r exist', languages)\n        return False\n    if age and video.age > age:\n        logger.debug('Video is older than %r', age)\n        return False\n    if undefined and Language('und') in video.subtitle_languages:\n        logger.debug('Undefined language found')\n        return False\n    return True",
    "docstring": "Perform some checks on the `video`.\n\n    All the checks are optional. Return `False` if any of this check fails:\n\n        * `languages` already exist in `video`'s :attr:`~subliminal.video.Video.subtitle_languages`.\n        * `video` is older than `age`.\n        * `video` has an `undefined` language in :attr:`~subliminal.video.Video.subtitle_languages`.\n\n    :param video: video to check.\n    :type video: :class:`~subliminal.video.Video`\n    :param languages: desired languages.\n    :type languages: set of :class:`~babelfish.language.Language`\n    :param datetime.timedelta age: maximum age of the video.\n    :param bool undefined: fail on existing undefined language.\n    :return: `True` if the video passes the checks, `False` otherwise.\n    :rtype: bool"
  },
  {
    "code": "def getTotalPrice(self):\n        price = self.getPrice()\n        vat = self.getVAT()\n        price = price and price or 0\n        vat = vat and vat or 0\n        return float(price) + (float(price) * float(vat)) / 100",
    "docstring": "Compute total price including VAT"
  },
  {
    "code": "def _check_delay(self):\n        if self._previous_request_at:\n            dif = round(time.time() - self._previous_request_at,\n                        2) * 1000\n            if dif < self.requests_delay:\n                time.sleep(\n                    (self.requests_delay - dif) / 1000)\n        self._previous_request_at = time.time()",
    "docstring": "Checks if a delay is needed between requests and sleeps if True"
  },
  {
    "code": "def get_selinux_status():\n    getenforce_command_exists()\n    o = run_cmd([\"getenforce\"], return_output=True).strip()\n    logger.debug(\"SELinux is %r\", o)\n    return o",
    "docstring": "get SELinux status of host\n\n    :return: string, one of Enforced, Permissive, Disabled"
  },
  {
    "code": "def finish(self, value):\n        if self._done.is_set():\n            raise errors.AlreadyComplete()\n        self._value = value\n        for cb in self._cbacks:\n            backend.schedule(cb, args=(value,))\n        self._cbacks = None\n        for wait in list(self._waits):\n            wait.finish(self)\n        self._waits = None\n        for child in self._children:\n            child = child()\n            if child is None:\n                continue\n            child._incoming(self, value)\n        self._children = None\n        self._done.set()",
    "docstring": "Give the future it's value and trigger any associated callbacks\n\n        :param value: the new value for the future\n        :raises:\n            :class:`AlreadyComplete <junction.errors.AlreadyComplete>` if\n            already complete"
  },
  {
    "code": "def find_safe_starting_point(self):\n        y = random.randint(2,self.grid_height-4)\n        x = random.randint(2,self.grid_width-4)\n        return y, x",
    "docstring": "finds a place on the grid which is clear on all sides \n        to avoid starting in the middle of a blockage"
  },
  {
    "code": "def get_principal_credit_string_metadata(self):\n        metadata = dict(self._mdata['principal_credit_string'])\n        metadata.update({'existing_string_values': self._my_map['principalCreditString']})\n        return Metadata(**metadata)",
    "docstring": "Gets the metadata for the principal credit string.\n\n        return: (osid.Metadata) - metadata for the credit string\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def cluster(list_of_texts, num_clusters=3):\n    pipeline = Pipeline([\n        (\"vect\", CountVectorizer()),\n        (\"tfidf\", TfidfTransformer()),\n        (\"clust\", KMeans(n_clusters=num_clusters))\n    ])\n    try:\n        clusters = pipeline.fit_predict(list_of_texts)\n    except ValueError:\n        clusters = list(range(len(list_of_texts)))\n    return clusters",
    "docstring": "Cluster a list of texts into a predefined number of clusters.\n\n    :param list_of_texts: a list of untokenized texts\n    :param num_clusters: the predefined number of clusters\n    :return: a list with the cluster id for each text, e.g. [0,1,0,0,2,2,1]"
  },
  {
    "code": "def read(self, fileobj):\n        fileobj.seek(self._dataoffset, 0)\n        data = fileobj.read(self.datalength)\n        return len(data) == self.datalength, data",
    "docstring": "Return if all data could be read and the atom payload"
  },
  {
    "code": "def _parseupload(self, node):\n        if not isinstance(node,ElementTree._Element):\n            try:\n                node = clam.common.data.parsexmlstring(node)\n            except:\n                raise Exception(node)\n        if node.tag != 'clamupload':\n            raise Exception(\"Not a valid CLAM upload response\")\n        for node2 in node:\n            if node2.tag == 'upload':\n                for subnode in node2:\n                    if subnode.tag == 'error':\n                        raise clam.common.data.UploadError(subnode.text)\n                    if subnode.tag == 'parameters':\n                        if 'errors' in subnode.attrib and subnode.attrib['errors'] == 'yes':\n                            errormsg = \"The submitted metadata did not validate properly\"\n                            for parameternode in subnode:\n                                if 'error' in parameternode.attrib:\n                                    errormsg = parameternode.attrib['error']\n                                    raise clam.common.data.ParameterError(errormsg + \" (parameter=\"+parameternode.attrib['id']+\")\")\n                            raise clam.common.data.ParameterError(errormsg)\n        return True",
    "docstring": "Parse CLAM Upload XML Responses. For internal use"
  },
  {
    "code": "def _mem(self):\n        value = int(psutil.virtual_memory().percent)\n        set_metric(\"memory\", value, category=self.category)\n        gauge(\"memory\", value)",
    "docstring": "Record Memory usage."
  },
  {
    "code": "def last_available_business_date(self, asset_manager_id, asset_ids, page_no=None, page_size=None):\n        self.logger.info('Retrieving last available business dates for assets')\n        url = '%s/last-available-business-date' % self.endpoint\n        params = {'asset_manager_ids': [asset_manager_id],\n                  'asset_ids': ','.join(asset_ids)}\n        if page_no:\n            params['page_no'] = page_no\n        if page_size:\n            params['page_size'] = page_size\n        response = self.session.get(url, params=params)\n        if response.ok:\n            self.logger.info(\"Received %s assets' last available business date\", len(response.json()))\n            return response.json()\n        else:\n            self.logger.error(response.text)\n            response.raise_for_status()",
    "docstring": "Returns the last available business date for the assets so we know the \n        starting date for new data which needs to be downloaded from data providers.\n        \n        This method can only be invoked by system user"
  },
  {
    "code": "def append(self, items):\n        resp = self.client.add_to_item_list(items, self.url())\n        self.refresh()\n        return resp",
    "docstring": "Add some items to this ItemList and save the changes to the server\n\n        :param items: the items to add, either as a List of Item objects, an\n            ItemList, a List of item URLs as Strings, a single item URL as a\n            String, or a single Item object\n\n        :rtype: String\n        :returns: the server success message\n\n        :raises: APIError if the API request is not successful"
  },
  {
    "code": "def addClass(self, cn):\n        if cn:\n            if isinstance(cn, (tuple, list, set, frozenset)):\n                add = self.addClass\n                for c in cn:\n                    add(c)\n            else:\n                classes = self._classes\n                if classes is None:\n                    self._extra['classes'] = classes = set()\n                add = classes.add\n                for cn in cn.split():\n                    add(slugify(cn))\n        return self",
    "docstring": "Add the specific class names to the class set and return ``self``."
  },
  {
    "code": "def compare(self, dn, attr, value):\n        return self.connection.compare_s(dn, attr, value) == 1",
    "docstring": "Compare the ``attr`` of the entry ``dn`` with given ``value``.\n\n        This is a convenience wrapper for the ldap library's ``compare``\n        function that returns a boolean value instead of 1 or 0."
  },
  {
    "code": "def destroy(self, folder=None):\n        ameans = [(0, 0, 0) for _ in range(3)]\n        ret = [self.save_info(folder, ameans)]\n        aiomas.run(until=self.stop_slaves(folder))\n        self._pool.close()\n        self._pool.terminate()\n        self._pool.join()\n        self._env.shutdown()\n        return ret",
    "docstring": "Destroy the environment and the subprocesses."
  },
  {
    "code": "def check_secret(self, secret):\n        try:\n            return hmac.compare_digest(secret, self.secret)\n        except AttributeError:\n            return secret == self.secret",
    "docstring": "Checks if the secret string used in the authentication attempt\n        matches the \"known\" secret string. Some mechanisms will override this\n        method to control how this comparison is made.\n\n        Args:\n            secret: The secret string to compare against what was used in the\n                authentication attempt.\n\n        Returns:\n            True if the given secret matches the authentication attempt."
  },
  {
    "code": "def usable_cpu_count():\n    try:\n        result = len(os.sched_getaffinity(0))\n    except AttributeError:\n        try:\n            result = len(psutil.Process().cpu_affinity())\n        except AttributeError:\n            result = os.cpu_count()\n    return result",
    "docstring": "Get number of CPUs usable by the current process.\n\n    Takes into consideration cpusets restrictions.\n\n    Returns\n    -------\n    int"
  },
  {
    "code": "def scroll_down (self):\n        s = self.scroll_row_start - 1\n        e = self.scroll_row_end - 1\n        self.w[s+1:e+1] = copy.deepcopy(self.w[s:e])",
    "docstring": "Scroll display down one line."
  },
  {
    "code": "def loads(self, src):\n        assert isinstance(src, (unicode_, bytes_))\n        nodes = self.scan(src.strip())\n        self.parse(nodes)\n        return ''.join(map(str, nodes))",
    "docstring": "Compile css from scss string."
  },
  {
    "code": "def waitForAllConnectionsToClose(self):\n        if not self._connections:\n            return self._stop()\n        return self._allConnectionsClosed.deferred().addBoth(self._stop)",
    "docstring": "Wait for all currently-open connections to enter the 'CLOSED' state.\n        Currently this is only usable from test fixtures."
  },
  {
    "code": "def statistical_distances(samples1, samples2, earth_mover_dist=True,\n                          energy_dist=True):\n    out = []\n    temp = scipy.stats.ks_2samp(samples1, samples2)\n    out.append(temp.pvalue)\n    out.append(temp.statistic)\n    if earth_mover_dist:\n        out.append(scipy.stats.wasserstein_distance(samples1, samples2))\n    if energy_dist:\n        out.append(scipy.stats.energy_distance(samples1, samples2))\n    return np.asarray(out)",
    "docstring": "Compute measures of the statistical distance between samples.\n\n    Parameters\n    ----------\n    samples1: 1d array\n    samples2: 1d array\n    earth_mover_dist: bool, optional\n        Whether or not to compute the Earth mover's distance between the\n        samples.\n    energy_dist: bool, optional\n        Whether or not to compute the energy distance between the samples.\n\n    Returns\n    -------\n    1d array"
  },
  {
    "code": "def check(self):\n    try:\n      si, uninterp = self.interpolate()\n    except (Object.CoercionError, MustacheParser.Uninterpolatable) as e:\n      return TypeCheck(False, \"Unable to interpolate: %s\" % e)\n    return self.checker(si)",
    "docstring": "Type check this object."
  },
  {
    "code": "def init_region_config(self, region):\n        self.regions[region] = self.region_config_class(region_name = region, resource_types = self.resource_types)",
    "docstring": "Initialize the region's configuration\n\n        :param region:                  Name of the region"
  },
  {
    "code": "def _forward(self, x_dot_parameters):\n        return forward(self._lattice, x_dot_parameters, \n                       self.state_machine.n_states)",
    "docstring": "Helper to calculate the forward weights."
  },
  {
    "code": "def should_display_warnings_for(to_type):\n    if not hasattr(to_type, '__module__'):\n        return True\n    elif to_type.__module__ in {'builtins'} or to_type.__module__.startswith('parsyfiles') \\\n            or to_type.__name__ in {'DataFrame'}:\n        return False\n    elif issubclass(to_type, int) or issubclass(to_type, str) \\\n            or issubclass(to_type, float) or issubclass(to_type, bool):\n        return False\n    else:\n        return True",
    "docstring": "Central method where we control whether warnings should be displayed"
  },
  {
    "code": "def max_length_discard(records, max_length):\n    logging.info('Applying _max_length_discard generator: '\n                 'discarding records longer than '\n                 '.')\n    for record in records:\n        if len(record) > max_length:\n            logging.debug('Discarding long sequence: %s, length=%d',\n                record.id, len(record))\n        else:\n            yield record",
    "docstring": "Discard any records that are longer than max_length."
  },
  {
    "code": "def put(self, ndef_message, timeout=1.0):\n        if not self.socket:\n            try:\n                self.connect('urn:nfc:sn:snep')\n            except nfc.llcp.ConnectRefused:\n                return False\n            else:\n                self.release_connection = True\n        else:\n            self.release_connection = False\n        try:\n            ndef_msgsize = struct.pack('>L', len(str(ndef_message)))\n            snep_request = b'\\x10\\x02' + ndef_msgsize + str(ndef_message)\n            if send_request(self.socket, snep_request, self.send_miu):\n                response = recv_response(self.socket, 0, timeout)\n                if response is not None:\n                    if response[1] != 0x81:\n                        raise SnepError(response[1])\n                    return True\n            return False\n        finally:\n            if self.release_connection:\n                self.close()",
    "docstring": "Send an NDEF message to the server. Temporarily connects to\n        the default SNEP server if the client is not yet connected.\n\n        .. deprecated:: 0.13\n           Use :meth:`put_records` or :meth:`put_octets`."
  },
  {
    "code": "def check_for_lane_permission(self):\n        if self.current.lane_permission:\n            log.debug(\"HAS LANE PERM: %s\" % self.current.lane_permission)\n            perm = self.current.lane_permission\n            if not self.current.has_permission(perm):\n                raise HTTPError(403, \"You don't have required lane permission: %s\" % perm)\n        if self.current.lane_relations:\n            context = self.get_pool_context()\n            log.debug(\"HAS LANE RELS: %s\" % self.current.lane_relations)\n            try:\n                cond_result = eval(self.current.lane_relations, context)\n            except:\n                log.exception(\"CONDITION EVAL ERROR : %s || %s\" % (\n                    self.current.lane_relations, context))\n                raise\n            if not cond_result:\n                log.debug(\"LANE RELATION ERR: %s %s\" % (self.current.lane_relations, context))\n                raise HTTPError(403, \"You aren't qualified for this lane: %s\" %\n                                self.current.lane_relations)",
    "docstring": "One or more permissions can be associated with a lane\n        of a workflow. In a similar way, a lane can be\n        restricted with relation to other lanes of the workflow.\n\n        This method called on lane changes and checks user has\n        required permissions and relations.\n\n        Raises:\n             HTTPForbidden: if the current user hasn't got the\n              required permissions and proper relations"
  },
  {
    "code": "def _operator(self, op, close_group=False):\n        op = op.upper().strip()\n        if op not in OP_LIST:\n            raise ValueError(\"Error: '{}' is not a valid operator.\".format(op))\n        else:\n            if close_group:\n                op = \") \" + op + \" (\"\n            else:\n                op = \" \" + op + \" \"\n            self.__query[\"q\"] += op\n        return self",
    "docstring": "Add an operator between terms.\n        There must be a term added before using this method.\n        All operators have helpers, so this method is usually not necessary to directly invoke.\n\n        Arguments:\n            op (str): The operator to add. Must be in the OP_LIST.\n            close_group (bool): If ``True``, will end the current parenthetical\n                group and start a new one.\n                If ``False``, will continue current group.\n\n                Example::\n                    \"(foo AND bar)\" is one group.\n                    \"(foo) AND (bar)\" is two groups.\n\n        Returns:\n            SearchHelper: Self"
  },
  {
    "code": "def update_subnet(self, subnet, body=None):\n        return self.put(self.subnet_path % (subnet), body=body)",
    "docstring": "Updates a subnet."
  },
  {
    "code": "def price(self, from_=None, **kwargs):\n        if from_:\n            kwargs[\"from\"] = from_\n        uri = \"%s/%s\" % (self.uri, \"price\")\n        response, instance = self.request(\"GET\", uri, params=kwargs)\n        return instance",
    "docstring": "Check pricing for a new outbound message.\n        An useful synonym for \"message\" command with \"dummy\" parameters set to true.\n\n        :Example:\n\n        message = client.messages.price(from_=\"447624800500\", phones=\"999000001\", text=\"Hello!\", lists=\"1909100\")\n\n        :param str from:         One of allowed Sender ID (phone number or alphanumeric sender ID).\n        :param str text:         Message text. Required if templateId is not set.\n        :param str templateId:   Template used instead of message text. Required if text is not set.\n        :param str sendingTime:  Message sending time in unix timestamp format. Default is now.\n                                 Optional (required with rrule set).\n        :param str contacts:     Contacts ids, separated by comma, message will be sent to.\n        :param str lists:        Lists ids, separated by comma, message will be sent to.\n        :param str phones:       Phone numbers, separated by comma, message will be sent to.\n        :param int cutExtra:     Should sending method cut extra characters\n                                 which not fit supplied partsCount or return 400 Bad request response instead.\n                                 Default is false.\n        :param int partsCount:   Maximum message parts count (TextMagic allows sending 1 to 6 message parts).\n                                 Default is 6.\n        :param str referenceId:  Custom message reference id which can be used in your application infrastructure.\n        :param str rrule:        iCal RRULE parameter to create recurrent scheduled messages.\n                                 When used, sendingTime is mandatory as start point of sending.\n        :param int dummy:        If 1, just return message pricing. Message will not send."
  },
  {
    "code": "def intersection(self,other):\n        if self.everything:\n            if other.everything:\n                return DiscreteSet()\n            else:\n                return DiscreteSet(other.elements)\n        else:\n            if other.everything:\n                return DiscreteSet(self.elements)\n            else:\n                return DiscreteSet(self.elements.intersection(other.elements))",
    "docstring": "Return a new DiscreteSet with the intersection of the two sets, i.e.\n        all elements that are in both self and other.\n\n        :param DiscreteSet other: Set to intersect with\n        :rtype: DiscreteSet"
  },
  {
    "code": "def write_nochr_reads(in_file, out_file, config):\n    if not file_exists(out_file):\n        with file_transaction(config, out_file) as tx_out_file:\n            samtools = config_utils.get_program(\"samtools\", config)\n            cmd = \"{samtools} view -b -f 4 {in_file} > {tx_out_file}\"\n            do.run(cmd.format(**locals()), \"Select unmapped reads\")\n    return out_file",
    "docstring": "Write a BAM file of reads that are not mapped on a reference chromosome.\n\n    This is useful for maintaining non-mapped reads in parallel processes\n    that split processing by chromosome."
  },
  {
    "code": "def load_images(url, format='auto', with_path=True, recursive=True, ignore_failure=True, random_order=False):\n    from ... import extensions as _extensions\n    from ...util import _make_internal_url\n    return _extensions.load_images(url, format, with_path,\n                                     recursive, ignore_failure, random_order)",
    "docstring": "Loads images from a directory. JPEG and PNG images are supported.\n\n    Parameters\n    ----------\n    url : str\n        The string of the path where all the images are stored.\n\n    format : {'PNG' | 'JPG' | 'auto'}, optional\n        The format of the images in the directory. The default 'auto' parameter\n        value tries to infer the image type from the file extension. If a\n        format is specified, all images must be of that format.\n\n    with_path : bool, optional\n        Indicates whether a path column is added to the SFrame. If 'with_path'\n        is set to True,  the returned SFrame contains a 'path' column, which\n        holds a path string for each Image object.\n\n    recursive : bool, optional\n        Indicates whether 'load_images' should do recursive directory traversal,\n        or a flat directory traversal.\n\n    ignore_failure : bool, optional\n        If true, prints warning for failed images and keep loading the rest of\n        the images.\n\n    random_order : bool, optional\n        Load images in random order.\n\n    Returns\n    -------\n    out : SFrame\n        Returns an SFrame with either an 'image' column or both an 'image' and\n        a 'path' column. The 'image' column is a column of Image objects. If\n        with_path is True, there is also a 'path' column which contains the image\n        path for each of each corresponding Image object.\n\n    Examples\n    --------\n\n    >>> url ='https://static.turi.com/datasets/images/nested'\n    >>> image_sframe = turicreate.image_analysis.load_images(url, \"auto\", with_path=False,\n    ...                                                       recursive=True)"
  },
  {
    "code": "def Header(self):\n    _ = [option.OnGetValue() for option in self.options]\n    return self.name",
    "docstring": "Fetch the header name of this Value."
  },
  {
    "code": "def publish(self, topic, *args, **kwargs):\n        return self._async_session.publish(topic, *args, **kwargs)",
    "docstring": "Publish an event to a topic.\n\n        Replace :meth:`autobahn.wamp.interface.IApplicationSession.publish`"
  },
  {
    "code": "def convert_tensor(input_, device=None, non_blocking=False):\n    def _func(tensor):\n        return tensor.to(device=device, non_blocking=non_blocking) if device else tensor\n    return apply_to_tensor(input_, _func)",
    "docstring": "Move tensors to relevant device."
  },
  {
    "code": "def make_empty(self, axes=None):\n        if axes is None:\n            axes = [ensure_index([])] + [ensure_index(a)\n                                         for a in self.axes[1:]]\n        if self.ndim == 1:\n            blocks = np.array([], dtype=self.array_dtype)\n        else:\n            blocks = []\n        return self.__class__(blocks, axes)",
    "docstring": "return an empty BlockManager with the items axis of len 0"
  },
  {
    "code": "def _match(filtered, matcher):\n    def match_filtered_identities(x, ids, matcher):\n        for y in ids:\n            if x.uuid == y.uuid:\n                return True\n            if matcher.match_filtered_identities(x, y):\n                return True\n        return False\n    matched = []\n    while filtered:\n        candidates = []\n        no_match = []\n        x = filtered.pop(0)\n        while matched:\n            ids = matched.pop(0)\n            if match_filtered_identities(x, ids, matcher):\n                candidates += ids\n            else:\n                no_match.append(ids)\n        candidates.append(x)\n        matched = [candidates] + no_match\n    return matched",
    "docstring": "Old method to find matches in a set of filtered identities."
  },
  {
    "code": "def _kick(self):\n        xyz_init = self.xyz\n        for particle in self.particles():\n            particle.pos += (np.random.rand(3,) - 0.5) / 100\n        self._update_port_locations(xyz_init)",
    "docstring": "Slightly adjust all coordinates in a Compound\n\n        Provides a slight adjustment to coordinates to kick them out of local\n        energy minima."
  },
  {
    "code": "def _cal_color(self, value, color_index):\n        range_min_p = self._domain[color_index]\n        range_p = self._domain[color_index + 1] - range_min_p\n        try:\n            factor = (value - range_min_p) / range_p\n        except ZeroDivisionError:\n            factor = 0\n        min_color = self.colors[color_index]\n        max_color = self.colors[color_index + 1]\n        red = round(factor * (max_color.r - min_color.r) + min_color.r)\n        green = round(factor * (max_color.g - min_color.g) + min_color.g)\n        blue = round(factor * (max_color.b - min_color.b) + min_color.b)\n        return Color(red, green, blue)",
    "docstring": "Blend between two colors based on input value."
  },
  {
    "code": "def add_node(self, binary_descriptor):\n        try:\n            node_string = parse_binary_descriptor(binary_descriptor)\n        except:\n            self._logger.exception(\"Error parsing binary node descriptor: %s\", binary_descriptor)\n            return _pack_sgerror(SensorGraphError.INVALID_NODE_STREAM)\n        try:\n            self.graph.add_node(node_string)\n        except NodeConnectionError:\n            return _pack_sgerror(SensorGraphError.STREAM_NOT_IN_USE)\n        except ProcessingFunctionError:\n            return _pack_sgerror(SensorGraphError.INVALID_PROCESSING_FUNCTION)\n        except ResourceUsageError:\n            return _pack_sgerror(SensorGraphError.NO_NODE_SPACE_AVAILABLE)\n        return Error.NO_ERROR",
    "docstring": "Add a node to the sensor_graph using a binary node descriptor.\n\n        Args:\n            binary_descriptor (bytes): An encoded binary node descriptor.\n\n        Returns:\n            int: A packed error code."
  },
  {
    "code": "def main():\n    windows_libraries = list(pylink.Library.find_library_windows())\n    latest_library = None\n    for lib in windows_libraries:\n        if os.path.dirname(lib).endswith('JLinkARM'):\n            latest_library = lib\n            break\n        elif latest_library is None:\n            latest_library = lib\n        elif os.path.dirname(lib) > os.path.dirname(latest_library):\n            latest_library = lib\n    if latest_library is None:\n        raise OSError('No J-Link library found.')\n    library = pylink.Library(latest_library)\n    jlink = pylink.JLink(lib=library)\n    print('Found version: %s' % jlink.version)\n    for emu in jlink.connected_emulators():\n        jlink.disable_dialog_boxes()\n        jlink.open(serial_no=emu.SerialNumber)\n        jlink.sync_firmware()\n        print('Updated emulator with serial number %s' % emu.SerialNumber)\n    return None",
    "docstring": "Upgrades the firmware of the J-Links connected to a Windows device.\n\n    Returns:\n      None.\n\n    Raises:\n      OSError: if there are no J-Link software packages."
  },
  {
    "code": "def _get_graphics(dom):\n    out = {'autoport': 'None',\n           'keymap': 'None',\n           'listen': 'None',\n           'port': 'None',\n           'type': 'None'}\n    doc = ElementTree.fromstring(dom.XMLDesc(0))\n    for g_node in doc.findall('devices/graphics'):\n        for key, value in six.iteritems(g_node.attrib):\n            out[key] = value\n    return out",
    "docstring": "Get domain graphics from a libvirt domain object."
  },
  {
    "code": "def init_with_context(self, context):\n        site_name = get_admin_site_name(context)\n        self.children += [\n            items.MenuItem(_('Dashboard'), reverse('{0}:index'.format(site_name))),\n            items.Bookmarks(),\n        ]\n        for title, kwargs in get_application_groups():\n            if kwargs.get('enabled', True):\n                self.children.append(CmsModelList(title, **kwargs))\n        self.children += [\n            ReturnToSiteItem()\n        ]",
    "docstring": "Initialize the menu items."
  },
  {
    "code": "def make_random_gaussians_table(n_sources, param_ranges, random_state=None):\n    sources = make_random_models_table(n_sources, param_ranges,\n                                       random_state=random_state)\n    if 'flux' in param_ranges and 'amplitude' not in param_ranges:\n        model = Gaussian2D(x_stddev=1, y_stddev=1)\n        if 'x_stddev' in sources.colnames:\n            xstd = sources['x_stddev']\n        else:\n            xstd = model.x_stddev.value\n        if 'y_stddev' in sources.colnames:\n            ystd = sources['y_stddev']\n        else:\n            ystd = model.y_stddev.value\n        sources = sources.copy()\n        sources['amplitude'] = sources['flux'] / (2. * np.pi * xstd * ystd)\n    return sources",
    "docstring": "Make a `~astropy.table.Table` containing randomly generated\n    parameters for 2D Gaussian sources.\n\n    Each row of the table corresponds to a Gaussian source whose\n    parameters are defined by the column names.  The parameters are\n    drawn from a uniform distribution over the specified input ranges.\n\n    The output table can be input into\n    :func:`make_gaussian_sources_image` to create an image containing\n    the 2D Gaussian sources.\n\n    Parameters\n    ----------\n    n_sources : float\n        The number of random Gaussian sources to generate.\n\n    param_ranges : dict\n        The lower and upper boundaries for each of the\n        `~astropy.modeling.functional_models.Gaussian2D` parameters as a\n        `dict` mapping the parameter name to its ``(lower, upper)``\n        bounds.  The dictionary keys must be valid\n        `~astropy.modeling.functional_models.Gaussian2D` parameter names\n        or ``'flux'``.  If ``'flux'`` is specified, but not\n        ``'amplitude'`` then the 2D Gaussian amplitudes will be\n        calculated and placed in the output table.  If both ``'flux'``\n        and ``'amplitude'`` are specified, then ``'flux'`` will be\n        ignored.  Model parameters not defined in ``param_ranges`` will\n        be set to the default value.\n\n    random_state : int or `~numpy.random.RandomState`, optional\n        Pseudo-random number generator state used for random sampling.\n\n    Returns\n    -------\n    table : `~astropy.table.Table`\n        A table of parameters for the randomly generated Gaussian\n        sources.  Each row of the table corresponds to a Gaussian source\n        whose parameters are defined by the column names.\n\n    See Also\n    --------\n    make_random_models_table, make_gaussian_sources_image\n\n    Notes\n    -----\n    To generate identical parameter values from separate function calls,\n    ``param_ranges`` must be input as an `~collections.OrderedDict` with\n    the same parameter ranges and ``random_state`` must be the same.\n\n\n    Examples\n    --------\n    >>> from collections import OrderedDict\n    >>> from photutils.datasets import make_random_gaussians_table\n    >>> n_sources = 5\n    >>> param_ranges = [('amplitude', [500, 1000]),\n    ...                 ('x_mean', [0, 500]),\n    ...                 ('y_mean', [0, 300]),\n    ...                 ('x_stddev', [1, 5]),\n    ...                 ('y_stddev', [1, 5]),\n    ...                 ('theta', [0, np.pi])]\n    >>> param_ranges = OrderedDict(param_ranges)\n    >>> sources = make_random_gaussians_table(n_sources, param_ranges,\n    ...                                       random_state=12345)\n    >>> for col in sources.colnames:\n    ...     sources[col].info.format = '%.8g'  # for consistent table output\n    >>> print(sources)\n    amplitude   x_mean    y_mean   x_stddev  y_stddev   theta\n    --------- --------- --------- --------- --------- ----------\n    964.80805 297.77235 224.31444 3.6256447 3.5699013  2.2923859\n    658.18778 482.25726 288.39202 4.2392502 3.8698145  3.1227889\n    591.95941 326.58855 2.5164894 4.4887037  2.870396  2.1264615\n    602.28014 374.45332 31.933313 4.8585904 2.3023387  2.4844422\n    783.86251 326.78494 89.611114 3.8947414 2.7585784 0.53694298\n\n    To specifying the flux range instead of the amplitude range:\n\n    >>> param_ranges = [('flux', [500, 1000]),\n    ...                 ('x_mean', [0, 500]),\n    ...                 ('y_mean', [0, 300]),\n    ...                 ('x_stddev', [1, 5]),\n    ...                 ('y_stddev', [1, 5]),\n    ...                 ('theta', [0, np.pi])]\n    >>> param_ranges = OrderedDict(param_ranges)\n    >>> sources = make_random_gaussians_table(n_sources, param_ranges,\n    ...                                       random_state=12345)\n    >>> for col in sources.colnames:\n    ...     sources[col].info.format = '%.8g'  # for consistent table output\n    >>> print(sources)\n       flux     x_mean    y_mean   x_stddev  y_stddev   theta    amplitude\n    --------- --------- --------- --------- --------- ---------- ---------\n    964.80805 297.77235 224.31444 3.6256447 3.5699013  2.2923859 11.863685\n    658.18778 482.25726 288.39202 4.2392502 3.8698145  3.1227889 6.3854388\n    591.95941 326.58855 2.5164894 4.4887037  2.870396  2.1264615 7.3122209\n    602.28014 374.45332 31.933313 4.8585904 2.3023387  2.4844422 8.5691781\n    783.86251 326.78494 89.611114 3.8947414 2.7585784 0.53694298 11.611707\n\n    Note that in this case the output table contains both a flux and\n    amplitude column.  The flux column will be ignored when generating\n    an image of the models using :func:`make_gaussian_sources_image`."
  },
  {
    "code": "def verify_url_path(url_path, query_args, secret_key, salt_arg='_', max_expiry=None, digest=None):\n    try:\n        supplied_signature = query_args.pop('signature')\n    except KeyError:\n        raise SigningError(\"Signature missing.\")\n    if salt_arg is not None and salt_arg not in query_args:\n        raise SigningError(\"No salt used.\")\n    if max_expiry is not None and 'expires' not in query_args:\n        raise SigningError(\"Expiry time is required.\")\n    signature = _generate_signature(url_path, secret_key, query_args, digest)\n    if not hmac.compare_digest(signature, supplied_signature):\n        raise SigningError('Signature not valid.')\n    try:\n        expiry_time = int(query_args.pop('expires'))\n    except KeyError:\n        pass\n    except ValueError:\n        raise SigningError(\"Invalid expiry value.\")\n    else:\n        expiry_delta = expiry_time - time()\n        if expiry_delta < 0:\n            raise SigningError(\"Signature has expired.\")\n        if max_expiry and expiry_delta > max_expiry:\n            raise SigningError(\"Expiry time out of range.\")\n    return True",
    "docstring": "Verify a URL path is correctly signed.\n\n    :param url_path: URL path\n    :param secret_key: Signing key\n    :param query_args: Arguments that make up the query string\n    :param salt_arg: Argument required for salt (set to None to disable)\n    :param max_expiry: Maximum length of time an expiry value can be for (set to None to disable)\n    :param digest: Specify the digest function to use; default is sha256 from hashlib\n    :rtype: bool\n    :raises: URLError"
  },
  {
    "code": "def query_records_no_auth(self, name, query=''):\n        req = requests.get(self.api_server + '/api/' + name + \"/\" + query)\n        return req",
    "docstring": "Query records without authorization"
  },
  {
    "code": "def reset_all(self, suppress_logging=False):\n        pool_names = list(self.pools)\n        for name in pool_names:\n            self.reset(name, suppress_logging)",
    "docstring": "iterates thru the list of established connections and resets them by disconnecting and reconnecting"
  },
  {
    "code": "def debug(self):\n        url = '{}/debug/status'.format(self.url)\n        data = self._get(url)\n        return data.json()",
    "docstring": "Retrieve the debug information from the charmstore."
  },
  {
    "code": "def _to_dict(objects):\n    try:\n        if isinstance(objects, six.string_types):\n            objects = salt.utils.json.loads(objects)\n    except ValueError as err:\n        log.error(\"Could not parse objects: %s\", err)\n        raise err\n    return objects",
    "docstring": "Potentially interprets a string as JSON for usage with mongo"
  },
  {
    "code": "def _set_id_field(new_class):\n        if new_class.meta_.declared_fields:\n            try:\n                new_class.meta_.id_field = next(\n                    field for _, field in new_class.meta_.declared_fields.items()\n                    if field.identifier)\n            except StopIteration:\n                new_class._create_id_field()",
    "docstring": "Lookup the id field for this entity and assign"
  },
  {
    "code": "def _cmpFormatRanges(a, b):\n    if a.format == b.format and \\\n       a.start == b.start and \\\n       a.length == b.length:\n        return 0\n    else:\n        return cmp(id(a), id(b))",
    "docstring": "PyQt does not define proper comparison for QTextLayout.FormatRange\n    Define it to check correctly, if formats has changed.\n    It is important for the performance"
  },
  {
    "code": "def _check_compatible_with(\n            self,\n            other: Union[Period, Timestamp, Timedelta, NaTType],\n    ) -> None:\n        raise AbstractMethodError(self)",
    "docstring": "Verify that `self` and `other` are compatible.\n\n        * DatetimeArray verifies that the timezones (if any) match\n        * PeriodArray verifies that the freq matches\n        * Timedelta has no verification\n\n        In each case, NaT is considered compatible.\n\n        Parameters\n        ----------\n        other\n\n        Raises\n        ------\n        Exception"
  },
  {
    "code": "def _ParseTimestamp(self, parser_mediator, row):\n    timestamp = row.get('timestamp', None)\n    if timestamp is not None:\n      try:\n        timestamp = int(timestamp, 10)\n      except (ValueError, TypeError):\n        parser_mediator.ProduceExtractionWarning(\n            'Unable to parse timestamp value: {0!s}'.format(timestamp))\n      return dfdatetime_posix_time.PosixTime(timestamp=timestamp)\n    try:\n      return self._ConvertToTimestamp(row['date'], row['time'])\n    except ValueError as exception:\n      parser_mediator.ProduceExtractionWarning((\n          'Unable to parse time string: \"{0:s} {1:s}\" with error: '\n          '{2!s}').format(repr(row['date']), repr(row['time']), exception))",
    "docstring": "Provides a timestamp for the given row.\n\n    If the Trend Micro log comes from a version that provides a POSIX timestamp,\n    use that directly; it provides the advantages of UTC and of second\n    precision. Otherwise fall back onto the local-timezone date and time.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      row (dict[str, str]): fields of a single row, as specified in COLUMNS.\n\n    Returns:\n      dfdatetime.interface.DateTimeValue: date and time value."
  },
  {
    "code": "def range(self, value):\n        self._buffer.append(abs(value))\n        mean = sum(self._buffer) / len(self._buffer)\n        estimate = next(\n            (r for r in self.ranges if mean < self.scale * r),\n            self.ranges[-1]\n        )\n        if self._mapping:\n            return self._mapping[estimate]\n        else:\n            return estimate",
    "docstring": "Estimates an appropriate sensitivity range."
  },
  {
    "code": "def wildcards_overlap(name1, name2):\n    if not name1 and not name2:\n        return True\n    if not name1 or not name2:\n        return False\n    for matched1, matched2 in _character_matches(name1, name2):\n        if wildcards_overlap(name1[matched1:], name2[matched2:]):\n            return True\n    return False",
    "docstring": "Return true if two wildcard patterns can match the same string."
  },
  {
    "code": "def get_fetch_response(self, res):\n        res.code = res.status_code\n        res.headers = Headers(res.headers)\n        res._body = None\n        res.body = ''\n        body = res.content\n        if body:\n            if self.is_json(res.headers):\n                res._body = res.json()\n            else:\n                res._body = body\n            res.body = String(body, res.encoding)\n        return res",
    "docstring": "the goal of this method is to make the requests object more endpoints like\n\n        res -- requests Response -- the native requests response instance, we manipulate\n            it a bit to make it look a bit more like the internal endpoints.Response object"
  },
  {
    "code": "def get_custom_fields(self):\n        return CustomField.objects.filter(\n            content_type=ContentType.objects.get_for_model(self))",
    "docstring": "Return a list of custom fields for this model"
  },
  {
    "code": "def evpn_prefix_del(self, route_type, route_dist, esi=0,\n                        ethernet_tag_id=None, mac_addr=None, ip_addr=None,\n                        ip_prefix=None):\n        func_name = 'evpn_prefix.delete_local'\n        kwargs = {EVPN_ROUTE_TYPE: route_type,\n                  ROUTE_DISTINGUISHER: route_dist}\n        if route_type == EVPN_ETH_AUTO_DISCOVERY:\n            kwargs.update({\n                EVPN_ESI: esi,\n                EVPN_ETHERNET_TAG_ID: ethernet_tag_id,\n            })\n        elif route_type == EVPN_MAC_IP_ADV_ROUTE:\n            kwargs.update({\n                EVPN_ETHERNET_TAG_ID: ethernet_tag_id,\n                MAC_ADDR: mac_addr,\n                IP_ADDR: ip_addr,\n            })\n        elif route_type == EVPN_MULTICAST_ETAG_ROUTE:\n            kwargs.update({\n                EVPN_ETHERNET_TAG_ID: ethernet_tag_id,\n                IP_ADDR: ip_addr,\n            })\n        elif route_type == EVPN_ETH_SEGMENT:\n            kwargs.update({\n                EVPN_ESI: esi,\n                IP_ADDR: ip_addr,\n            })\n        elif route_type == EVPN_IP_PREFIX_ROUTE:\n            kwargs.update({\n                EVPN_ETHERNET_TAG_ID: ethernet_tag_id,\n                IP_PREFIX: ip_prefix,\n            })\n        else:\n            raise ValueError('Unsupported EVPN route type: %s' % route_type)\n        call(func_name, **kwargs)",
    "docstring": "This method deletes an advertised EVPN route.\n\n        ``route_type`` specifies one of the EVPN route type name.\n\n        ``route_dist`` specifies a route distinguisher value.\n\n        ``esi`` is an value to specify the Ethernet Segment Identifier.\n\n        ``ethernet_tag_id`` specifies the Ethernet Tag ID.\n\n        ``mac_addr`` specifies a MAC address to advertise.\n\n        ``ip_addr`` specifies an IPv4 or IPv6 address to advertise.\n\n        ``ip_prefix`` specifies an IPv4 or IPv6 prefix to advertise."
  },
  {
    "code": "def hashable(val):\n    if val is None:\n        return val\n    try:\n        hash(val)\n    except TypeError:\n        return repr(val)\n    else:\n        return val",
    "docstring": "Test if `val` is hashable and if not, get it's string representation\n\n    Parameters\n    ----------\n    val: object\n        Any (possibly not hashable) python object\n\n    Returns\n    -------\n    val or string\n        The given `val` if it is hashable or it's string representation"
  },
  {
    "code": "def _render_resource(self, resource):\n        if not resource:\n            return None\n        if not isinstance(resource, self.model):\n            raise TypeError(\n                'Resource(s) type must be the same as the serializer model type.')\n        top_level_members = {}\n        try:\n            top_level_members['id'] = str(getattr(resource, self.primary_key))\n        except AttributeError:\n            raise\n        top_level_members['type'] = resource.__tablename__\n        top_level_members['attributes'] = self._render_attributes(resource)\n        top_level_members['relationships'] = self._render_relationships(\n                                                resource)\n        return top_level_members",
    "docstring": "Renders a resource's top level members based on json-api spec.\n\n        Top level members include:\n            'id', 'type', 'attributes', 'relationships'"
  },
  {
    "code": "def matching_line(freq, data, tref, bin_size=1):\n    template_line = line_model(freq, data, tref=tref)\n    _, amp, phi = avg_inner_product(data, template_line,\n                                    bin_size=bin_size)\n    return line_model(freq, data, tref=tref, amp=amp, phi=phi)",
    "docstring": "Find the parameter of the line with frequency 'freq' in the data.\n\n    Parameters\n    ----------\n    freq: float\n        Frequency of the line to find in the data.\n    data: pycbc.types.TimeSeries\n        Data from which the line wants to be measured.\n    tref: float\n        Reference time for the frequency line.\n    bin_size: {1, float}, optional\n        Duration of the bins the data will be divided into for averaging.\n\n    Returns\n    -------\n    line_model: pycbc.types.TimeSeries\n        A timeseries containing the frequency line with the amplitude\n        and phase measured from the data."
  },
  {
    "code": "def safe_mkdir(folder_name, force_perm=None):\n    if os.path.exists(folder_name):\n        return\n    intermediary_folders = folder_name.split(os.path.sep)\n    if intermediary_folders[-1] == \"\":\n        intermediary_folders = intermediary_folders[:-1]\n    if force_perm:\n        force_perm_path = folder_name.split(os.path.sep)\n        if force_perm_path[-1] == \"\":\n            force_perm_path = force_perm_path[:-1]\n    for i in range(1, len(intermediary_folders)):\n        folder_to_create = os.path.sep.join(intermediary_folders[:i + 1])\n        if os.path.exists(folder_to_create):\n            continue\n        os.mkdir(folder_to_create)\n        if force_perm:\n            os.chmod(folder_to_create, force_perm)",
    "docstring": "Create the specified folder.\n\n    If the parent folders do not exist, they are also created.\n    If the folder already exists, nothing is done.\n\n    Parameters\n    ----------\n    folder_name : str\n        Name of the folder to create.\n    force_perm : str\n        Mode to use for folder creation."
  },
  {
    "code": "def apply(self, model):\n        model.medium = {row.exchange: row.uptake\n                        for row in self.data.itertuples(index=False)}",
    "docstring": "Set the defined medium on the given model."
  },
  {
    "code": "def _pair_exp_cov(X, Y, span=180):\n    covariation = (X - X.mean()) * (Y - Y.mean())\n    if span < 10:\n        warnings.warn(\"it is recommended to use a higher span, e.g 30 days\")\n    return covariation.ewm(span=span).mean()[-1]",
    "docstring": "Calculate the exponential covariance between two timeseries of returns.\n\n    :param X: first time series of returns\n    :type X: pd.Series\n    :param Y: second time series of returns\n    :type Y: pd.Series\n    :param span: the span of the exponential weighting function, defaults to 180\n    :type span: int, optional\n    :return: the exponential covariance between X and Y\n    :rtype: float"
  },
  {
    "code": "async def execute_command(\n        self, *args: bytes, timeout: DefaultNumType = _default\n    ) -> SMTPResponse:\n        if timeout is _default:\n            timeout = self.timeout\n        self._raise_error_if_disconnected()\n        try:\n            response = await self.protocol.execute_command(\n                *args, timeout=timeout\n            )\n        except SMTPServerDisconnected:\n            self.close()\n            raise\n        if response.code == SMTPStatus.domain_unavailable:\n            self.close()\n        return response",
    "docstring": "Check that we're connected, if we got a timeout value, and then\n        pass the command to the protocol.\n\n        :raises SMTPServerDisconnected: connection lost"
  },
  {
    "code": "def checkout_task(current_target):\n    try:\n        scm = _make_scm(current_target)\n        src_dir = current_target.config.get(\"dp.src_dir\")\n        shared_dir = current_target.config.get(\"dp.src_dir_shared\")\n        scm.checkout(repo_dir=src_dir, shared_dir=shared_dir)\n        scm.update(repo_dir=src_dir)\n    except devpipeline_core.toolsupport.MissingToolKey as mtk:\n        current_target.executor.warning(mtk)",
    "docstring": "Update or a local checkout.\n\n    Arguments\n    target - The target to operate on."
  },
  {
    "code": "def initialize_fields(self):\n        for name, field in self.instance._meta.fields.items():\n            if getattr(field, 'primary_key', False):\n                continue\n            self._meta.fields[name] = self.convert_field(name, field)\n        for name in dir(type(self.instance)):\n            field = getattr(type(self.instance), name, None)\n            if isinstance(field, ManyToManyField):\n                self._meta.fields[name] = self.convert_field(name, field)\n        super().initialize_fields()",
    "docstring": "Convert all model fields to validator fields.\n        Then call the parent so that overwrites can happen if necessary for manually defined fields.\n\n        :return: None"
  },
  {
    "code": "def plot_iso(axis, step, var):\n    xmesh, ymesh, fld = get_meshes_fld(step, var)\n    if conf.field.shift:\n        fld = np.roll(fld, conf.field.shift, axis=0)\n    axis.contour(xmesh, ymesh, fld, linewidths=1)",
    "docstring": "Plot isocontours of scalar field.\n\n    Args:\n        axis (:class:`matplotlib.axes.Axes`): the axis handler of an\n            existing matplotlib figure where the isocontours should\n            be plotted.\n        step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData\n            instance.\n        var (str): the scalar field name."
  },
  {
    "code": "def _ensure_env(self, env: Union[jinja2.Environment, None]):\n        if not env:\n            env = jinja2.Environment()\n        if not env.loader:\n            env.loader = jinja2.FunctionLoader(lambda filename: self._cache[filename])\n        if 'faker' not in env.globals:\n            faker = Faker()\n            faker.seed(1234)\n            env.globals['faker'] = faker\n        if 'random_model' not in env.globals:\n            env.globals['random_model'] = jinja2.contextfunction(random_model)\n        if 'random_models' not in env.globals:\n            env.globals['random_models'] = jinja2.contextfunction(random_models)\n        return env",
    "docstring": "Make sure the jinja environment is minimally configured."
  },
  {
    "code": "def blocks_to_mark_complete_on_view(self, blocks):\n        blocks = {block for block in blocks if self.can_mark_block_complete_on_view(block)}\n        completions = self.get_completions({block.location for block in blocks})\n        return {block for block in blocks if completions.get(block.location, 0) < 1.0}",
    "docstring": "Returns a set of blocks which should be marked complete on view and haven't been yet."
  },
  {
    "code": "def exponential_terms(order, variables, data):\n    variables_exp = OrderedDict()\n    data_exp = OrderedDict()\n    if 1 in order:\n        data_exp[1] = data[variables]\n        variables_exp[1] = variables\n        order = set(order) - set([1])\n    for o in order:\n        variables_exp[o] = ['{}_power{}'.format(v, o) for v in variables]\n        data_exp[o] = data[variables]**o\n    variables_exp = reduce((lambda x, y: x + y), variables_exp.values())\n    data_exp = pd.DataFrame(columns=variables_exp,\n                            data=np.concatenate([*data_exp.values()], axis=1))\n    return (variables_exp, data_exp)",
    "docstring": "Compute exponential expansions.\n\n    Parameters\n    ----------\n    order: range or list(int)\n        A list of exponential terms to include. For instance, [1, 2]\n        indicates that the first and second exponential terms should be added.\n        To retain the original terms, 1 *must* be included in the list.\n    variables: list(str)\n        List of variables for which exponential terms should be computed.\n    data: pandas DataFrame object\n        Table of values of all observations of all variables.\n\n    Returns\n    -------\n    variables_exp: list\n        A list of variables to include in the final data frame after adding\n        the specified exponential terms.\n    data_exp: pandas DataFrame object\n        Table of values of all observations of all variables, including any\n        specified exponential terms."
  },
  {
    "code": "def locations(self):\n        req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/locations')\n        locations = req.get().json()\n        return locations",
    "docstring": "Available locations to be used when creating a new machine.\n\n        :returns: A list of available locations."
  },
  {
    "code": "def do_session(self, args):\n        filename = 'Not specified' if self.__session.filename is None \\\n            else self.__session.filename\n        print('{0: <30}: {1}'.format('Filename', filename))",
    "docstring": "Print current session information"
  },
  {
    "code": "def encode_jwt_token(\n            self, user,\n            override_access_lifespan=None, override_refresh_lifespan=None,\n            **custom_claims\n    ):\n        ClaimCollisionError.require_condition(\n            set(custom_claims.keys()).isdisjoint(RESERVED_CLAIMS),\n            \"The custom claims collide with required claims\",\n        )\n        self._check_user(user)\n        moment = pendulum.now('UTC')\n        if override_refresh_lifespan is None:\n            refresh_lifespan = self.refresh_lifespan\n        else:\n            refresh_lifespan = override_refresh_lifespan\n        refresh_expiration = (moment + refresh_lifespan).int_timestamp\n        if override_access_lifespan is None:\n            access_lifespan = self.access_lifespan\n        else:\n            access_lifespan = override_access_lifespan\n        access_expiration = min(\n            (moment + access_lifespan).int_timestamp,\n            refresh_expiration,\n        )\n        payload_parts = dict(\n            iat=moment.int_timestamp,\n            exp=access_expiration,\n            rf_exp=refresh_expiration,\n            jti=str(uuid.uuid4()),\n            id=user.identity,\n            rls=','.join(user.rolenames),\n            **custom_claims\n        )\n        return jwt.encode(\n            payload_parts, self.encode_key, self.encode_algorithm,\n        ).decode('utf-8')",
    "docstring": "Encodes user data into a jwt token that can be used for authorization\n        at protected endpoints\n\n        :param: override_access_lifespan:  Override's the instance's access\n                                           lifespan to set a custom duration\n                                           after which the new token's\n                                           accessability will expire. May not\n                                           exceed the refresh_lifespan\n        :param: override_refresh_lifespan: Override's the instance's refresh\n                                           lifespan to set a custom duration\n                                           after which the new token's\n                                           refreshability will expire.\n        :param: custom_claims:             Additional claims that should\n                                           be packed in the payload. Note that\n                                           any claims supplied here must be\n                                           JSON compatible types"
  },
  {
    "code": "def remove_callback(instance, prop, callback):\n    p = getattr(type(instance), prop)\n    if not isinstance(p, CallbackProperty):\n        raise TypeError(\"%s is not a CallbackProperty\" % prop)\n    p.remove_callback(instance, callback)",
    "docstring": "Remove a callback function from a property in an instance\n\n    Parameters\n    ----------\n    instance\n        The instance to detach the callback from\n    prop : str\n        Name of callback property in `instance`\n    callback : func\n        The callback function to remove"
  },
  {
    "code": "def bounter(size_mb=None, need_iteration=True, need_counts=True, log_counting=None):\n    if not need_counts:\n        return CardinalityEstimator()\n    if size_mb is None:\n        raise ValueError(\"Max size in MB must be provided.\")\n    if need_iteration:\n        if log_counting:\n            raise ValueError(\"Log counting is only supported with CMS implementation (need_iteration=False).\")\n        return HashTable(size_mb=size_mb)\n    else:\n        return CountMinSketch(size_mb=size_mb, log_counting=log_counting)",
    "docstring": "Factory method for bounter implementation.\n\n    Args:\n            size_mb (int): Desired memory footprint of the counter.\n            need_iteration (Bool): With `True`, create a `HashTable` implementation which can\n                iterate over inserted key/value pairs.\n                With `False`, create a `CountMinSketch` implementation which performs better in limited-memory scenarios,\n                but does not support iteration over elements.\n            need_counts (Bool): With `True`, construct the structure normally. With `False`, ignore all remaining\n                parameters and create a minimalistic cardinality counter based on hyperloglog which only takes 64KB memory.\n            log_counting (int): Counting to use with `CountMinSketch` implementation. Accepted values are\n                `None` (default counting with 32-bit integers), 1024 (16-bit), 8 (8-bit).\n                See `CountMinSketch` documentation for details.\n                Raise ValueError if not `None `and `need_iteration` is `True`."
  },
  {
    "code": "def change_in_longitude(lat, miles):\n    r = earth_radius * math.cos(lat * degrees_to_radians)\n    return (miles / r) * radians_to_degrees",
    "docstring": "Given a latitude and a distance west, return the change in longitude."
  },
  {
    "code": "def process_tokens(self, tokens):\n        for tok_type, token, (start_row, start_col), _, _ in tokens:\n            if tok_type == tokenize.STRING:\n                self._process_string_token(token, start_row, start_col)",
    "docstring": "Process the token stream.\n\n        This is required to override the parent class' implementation.\n\n        Args:\n            tokens: the tokens from the token stream to process."
  },
  {
    "code": "def set_location(self, time, latitude, longitude):\n        if isinstance(time, datetime.datetime):\n            tzinfo = time.tzinfo\n        else:\n            tzinfo = time.tz\n        if tzinfo is None:\n            self.location = Location(latitude, longitude)\n        else:\n            self.location = Location(latitude, longitude, tz=tzinfo)",
    "docstring": "Sets the location for the query.\n\n        Parameters\n        ----------\n        time: datetime or DatetimeIndex\n            Time range of the query."
  },
  {
    "code": "def get_properties(self):\n        variables = self.model.nodes()\n        property_tag = {}\n        for variable in sorted(variables):\n            properties = self.model.node[variable]\n            properties = collections.OrderedDict(sorted(properties.items()))\n            property_tag[variable] = []\n            for prop, val in properties.items():\n                property_tag[variable].append(str(prop) + \" = \" + str(val))\n        return property_tag",
    "docstring": "Add property to variables in BIF\n\n        Returns\n        -------\n        dict: dict of type {variable: list of properties }\n\n        Example\n        -------\n        >>> from pgmpy.readwrite import BIFReader, BIFWriter\n        >>> model = BIFReader('dog-problem.bif').get_model()\n        >>> writer = BIFWriter(model)\n        >>> writer.get_properties()\n        {'bowel-problem': ['position = (335, 99)'],\n         'dog-out': ['position = (300, 195)'],\n         'family-out': ['position = (257, 99)'],\n         'hear-bark': ['position = (296, 268)'],\n         'light-on': ['position = (218, 195)']}"
  },
  {
    "code": "def set_model(self, m):\n        self._model = m\n        self.new_root.emit(QtCore.QModelIndex())\n        self.model_changed(m)",
    "docstring": "Set the model for the level\n\n        :param m: the model that the level should use\n        :type m: QtCore.QAbstractItemModel\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def join_pretty_tensors(tensors, output, join_function=None, name='join'):\n  if not tensors:\n    raise ValueError('pretty_tensors must be a non-empty sequence.')\n  with output.g.name_scope(name):\n    if join_function is None:\n      last_dim = len(tensors[0].shape) - 1\n      return output.with_tensor(tf.concat(tensors, last_dim))\n    else:\n      return output.with_tensor(join_function(tensors))",
    "docstring": "Joins the list of pretty_tensors and sets head of output_pretty_tensor.\n\n  Args:\n    tensors: A sequence of Layers or SequentialLayerBuilders to join.\n    output: A pretty_tensor to set the head with the result.\n    join_function: A function to join the tensors, defaults to concat on the\n      last dimension.\n    name: A name that is used for the name_scope\n  Returns:\n    The result of calling with_tensor on output\n  Raises:\n    ValueError: if pretty_tensors is None or empty."
  },
  {
    "code": "def getSymbols(self):\n        symbollist = []\n        for rule in self.productions:\n            for symbol in rule.leftside + rule.rightside:\n                if symbol not in symbollist:\n                    symbollist.append(symbol)\n        symbollist += self.terminal_symbols\n        return symbollist",
    "docstring": "Returns every symbol"
  },
  {
    "code": "def reset(self):\n        status = self.m_objPCANBasic.Reset(self.m_PcanHandle)\n        return status == PCAN_ERROR_OK",
    "docstring": "Command the PCAN driver to reset the bus after an error."
  },
  {
    "code": "def selected_canvas_hazlayer(self):\n        if self.lstCanvasHazLayers.selectedItems():\n            item = self.lstCanvasHazLayers.currentItem()\n        else:\n            return None\n        try:\n            layer_id = item.data(Qt.UserRole)\n        except (AttributeError, NameError):\n            layer_id = None\n        layer = QgsProject.instance().mapLayer(layer_id)\n        return layer",
    "docstring": "Obtain the canvas layer selected by user.\n\n        :returns: The currently selected map layer in the list.\n        :rtype: QgsMapLayer"
  },
  {
    "code": "def runtime_error(self, msg, method):\n        if self.testing:\n            self._py3_wrapper.report_exception(msg)\n            raise KeyboardInterrupt\n        if self.error_hide:\n            self.hide_errors()\n            return\n        msg = msg.splitlines()[0]\n        errors = [self.module_nice_name, u\"{}: {}\".format(self.module_nice_name, msg)]\n        if self.error_messages != errors:\n            self.error_messages = errors\n            self.error_index = 0\n        self.error_output(self.error_messages[self.error_index], method)",
    "docstring": "Show the error in the bar"
  },
  {
    "code": "def _get_serializer(self, _type):\n        if _type in _serializers:\n            return _serializers[_type]\n        elif _type == 'array':\n            return self._get_array_serializer()\n        elif _type == 'object':\n            return self._get_object_serializer()\n        raise ValueError('Unknown type: {}'.format(_type))",
    "docstring": "Gets a serializer for a particular type. For primitives, returns the\n        serializer from the module-level serializers.\n        For arrays and objects, uses the special _get_T_serializer methods to\n        build the encoders and decoders."
  },
  {
    "code": "def login(username, password, development_mode=False):\n        retval = None\n        try:\n            user = User.fetch_by(username=username)\n            if user and (development_mode or user.verify_password(password)):\n                retval = user\n        except OperationalError:\n            pass\n        return retval",
    "docstring": "Return the user if successful, None otherwise"
  },
  {
    "code": "async def migrate_redis1_to_redis2(storage1: RedisStorage, storage2: RedisStorage2):\n    if not isinstance(storage1, RedisStorage):\n        raise TypeError(f\"{type(storage1)} is not RedisStorage instance.\")\n    if not isinstance(storage2, RedisStorage):\n        raise TypeError(f\"{type(storage2)} is not RedisStorage instance.\")\n    log = logging.getLogger('aiogram.RedisStorage')\n    for chat, user in await storage1.get_states_list():\n        state = await storage1.get_state(chat=chat, user=user)\n        await storage2.set_state(chat=chat, user=user, state=state)\n        data = await storage1.get_data(chat=chat, user=user)\n        await storage2.set_data(chat=chat, user=user, data=data)\n        bucket = await storage1.get_bucket(chat=chat, user=user)\n        await storage2.set_bucket(chat=chat, user=user, bucket=bucket)\n        log.info(f\"Migrated user {user} in chat {chat}\")",
    "docstring": "Helper for migrating from RedisStorage to RedisStorage2\n\n    :param storage1: instance of RedisStorage\n    :param storage2: instance of RedisStorage2\n    :return:"
  },
  {
    "code": "def load_object(target, namespace=None):\n    if namespace and ':' not in target:\n        allowable = dict((i.name,  i) for i in pkg_resources.iter_entry_points(namespace))\n        if target not in allowable:\n            raise ValueError('Unknown plugin \"' + target + '\"; found: ' + ', '.join(allowable))\n        return allowable[target].load()\n    parts, target = target.split(':') if ':' in target else (target, None)\n    module = __import__(parts)\n    for part in parts.split('.')[1:] + ([target] if target else []):\n        module = getattr(module, part)\n    return module",
    "docstring": "This helper function loads an object identified by a dotted-notation string.\n\n    For example:\n\n        # Load class Foo from example.objects\n        load_object('example.objects:Foo')\n\n    If a plugin namespace is provided simple name references are allowed.  For example:\n\n        # Load the plugin named 'routing' from the 'web.dispatch' namespace\n        load_object('routing', 'web.dispatch')\n\n    Providing a namespace does not prevent full object lookup (dot-colon notation) from working."
  },
  {
    "code": "def update_metadata(self):\n        if self._data_directory is None:\n            raise Exception('Need to call `api.set_data_directory` first.')\n        metadata_url = 'https://repo.continuum.io/pkgs/metadata.json'\n        filepath = os.sep.join([self._data_directory, 'metadata.json'])\n        worker = self.download_requests(metadata_url, filepath)\n        return worker",
    "docstring": "Update the metadata available for packages in repo.continuum.io.\n\n        Returns a download worker."
  },
  {
    "code": "def create(self, request, *args, **kwargs):\n        bulk_payload = self._get_bulk_payload(request)\n        if bulk_payload:\n            return self._create_many(bulk_payload)\n        return super(DynamicModelViewSet, self).create(\n            request, *args, **kwargs)",
    "docstring": "Either create a single or many model instances in bulk\n        using the Serializer's many=True ability from Django REST >= 2.2.5.\n\n        The data can be represented by the serializer name (single or plural\n        forms), dict or list.\n\n        Examples:\n\n        POST /dogs/\n        {\n          \"name\": \"Fido\",\n          \"age\": 2\n        }\n\n        POST /dogs/\n        {\n          \"dog\": {\n            \"name\": \"Lucky\",\n            \"age\": 3\n          }\n        }\n\n        POST /dogs/\n        {\n          \"dogs\": [\n            {\"name\": \"Fido\", \"age\": 2},\n            {\"name\": \"Lucky\", \"age\": 3}\n          ]\n        }\n\n        POST /dogs/\n        [\n            {\"name\": \"Fido\", \"age\": 2},\n            {\"name\": \"Lucky\", \"age\": 3}\n        ]"
  },
  {
    "code": "def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,\n                group_keys=True, squeeze=False):\n        from sparklingpandas.groupby import GroupBy\n        return GroupBy(self, by=by, axis=axis, level=level, as_index=as_index,\n                       sort=sort, group_keys=group_keys, squeeze=squeeze)",
    "docstring": "Returns a groupby on the schema rdd. This returns a GroupBy object.\n        Note that grouping by a column name will be faster than most other\n        options due to implementation."
  },
  {
    "code": "def _rem(self, command, *args, **kwargs):\n        if self.indexable:\n            self.deindex(args)\n        return self._traverse_command(command, *args, **kwargs)",
    "docstring": "Shortcut for commands that only remove values from the field.\n        Removed values will be deindexed."
  },
  {
    "code": "def get_filter_item(name: str, operation: bytes, value: bytes) -> bytes:\n    assert isinstance(name, str)\n    assert isinstance(value, bytes)\n    if operation is None:\n        return filter_format(b\"(%s=%s)\", [name, value])\n    elif operation == \"contains\":\n        assert value != \"\"\n        return filter_format(b\"(%s=*%s*)\", [name, value])\n    else:\n        raise ValueError(\"Unknown search operation %s\" % operation)",
    "docstring": "A field could be found for this term, try to get filter string for it."
  },
  {
    "code": "def make_mesh( coor, ngroups, conns, mesh_in ):\n    mat_ids = []\n    for ii, conn in enumerate( conns ):\n        mat_id = nm.empty( (conn.shape[0],), dtype = nm.int32 )\n        mat_id.fill( mesh_in.mat_ids[ii][0] )\n        mat_ids.append( mat_id )\n    mesh_out = Mesh.from_data( 'merged mesh', coor, ngroups, conns,\n                               mat_ids, mesh_in.descs )\n    return mesh_out",
    "docstring": "Create a mesh reusing mat_ids and descs of mesh_in."
  },
  {
    "code": "def label_subplot(ax=None, x=0.5, y=-0.25, text=\"(a)\", **kwargs):\n    if ax is None:\n        ax = plt.gca()\n    ax.text(x=x, y=y, s=text, transform=ax.transAxes,\n            horizontalalignment=\"center\", verticalalignment=\"top\", **kwargs)",
    "docstring": "Create a subplot label."
  },
  {
    "code": "def data_fetch(self, url, task):\n        self.on_fetch('data', task)\n        result = {}\n        result['orig_url'] = url\n        result['content'] = dataurl.decode(url)\n        result['headers'] = {}\n        result['status_code'] = 200\n        result['url'] = url\n        result['cookies'] = {}\n        result['time'] = 0\n        result['save'] = task.get('fetch', {}).get('save')\n        if len(result['content']) < 70:\n            logger.info(\"[200] %s:%s %s 0s\", task.get('project'), task.get('taskid'), url)\n        else:\n            logger.info(\n                \"[200] %s:%s data:,%s...[content:%d] 0s\",\n                task.get('project'), task.get('taskid'),\n                result['content'][:70],\n                len(result['content'])\n            )\n        return result",
    "docstring": "A fake fetcher for dataurl"
  },
  {
    "code": "def _qnwcheb1(n, a, b):\n    nodes = (b+a)/2 - (b-a)/2 * np.cos(np.pi/n * np.linspace(0.5, n-0.5, n))\n    t1 = np.arange(1, n+1) - 0.5\n    t2 = np.arange(0.0, n, 2)\n    t3 = np.concatenate((np.array([1.0]),\n                        -2.0/(np.arange(1.0, n-1, 2)*np.arange(3.0, n+1, 2))))\n    weights = ((b-a)/n)*np.cos(np.pi/n*np.outer(t1, t2)) @ t3\n    return nodes, weights",
    "docstring": "Compute univariate Guass-Checbychev quadrature nodes and weights\n\n    Parameters\n    ----------\n    n : int\n        The number of nodes\n\n    a : int\n        The lower endpoint\n\n    b : int\n        The upper endpoint\n\n    Returns\n    -------\n    nodes : np.ndarray(dtype=float)\n        An n element array of nodes\n\n    nodes : np.ndarray(dtype=float)\n        An n element array of weights\n\n    Notes\n    -----\n    Based of original function ``qnwcheb1`` in CompEcon toolbox by\n    Miranda and Fackler\n\n    References\n    ----------\n    Miranda, Mario J, and Paul L Fackler. Applied Computational\n    Economics and Finance, MIT Press, 2002."
  },
  {
    "code": "def pickle_dump(self):\n        if self.has_chrooted:\n            warnings.warn(\"Cannot pickle_dump since we have chrooted from %s\" % self.has_chrooted)\n            return -1\n        protocol = self.pickle_protocol\n        with FileLock(self.pickle_file):\n            with AtomicFile(self.pickle_file, mode=\"wb\") as fh:\n                pmg_pickle_dump(self, fh, protocol=protocol)\n        return 0",
    "docstring": "Save the status of the object in pickle format.\n        Returns 0 if success"
  },
  {
    "code": "def rpc_get_refactor_options(self, filename, start, end=None):\n        try:\n            from elpy import refactor\n        except:\n            raise ImportError(\"Rope not installed, refactorings unavailable\")\n        ref = refactor.Refactor(self.project_root, filename)\n        return ref.get_refactor_options(start, end)",
    "docstring": "Return a list of possible refactoring options.\n\n        This list will be filtered depending on whether it's\n        applicable at the point START and possibly the region between\n        START and END."
  },
  {
    "code": "def claim_new(self) -> Iterable[str]:\n        new_subdir = self._paths['new']\n        cur_subdir = self._paths['cur']\n        for name in os.listdir(new_subdir):\n            new_path = os.path.join(new_subdir, name)\n            cur_path = os.path.join(cur_subdir, name)\n            try:\n                os.rename(new_path, cur_path)\n            except FileNotFoundError:\n                pass\n            else:\n                yield name.rsplit(self.colon, 1)[0]",
    "docstring": "Checks for messages in the ``new`` subdirectory, moving them to\n        ``cur`` and returning their keys."
  },
  {
    "code": "def declare_var(self, key, val):\n        if val is not None:\n            line = \"export \" + key + '=' + str(val)\n        else:\n            line = \"unset \" + key\n        self._add(line)",
    "docstring": "Declare a env variable. If val is None the variable is unset."
  },
  {
    "code": "def clear(self):\n    self.__init__(size=self.size, alpha=self.alpha, clock=self.clock)",
    "docstring": "Clear the samples."
  },
  {
    "code": "def check_for_period_error(data, period):\n    period = int(period)\n    data_len = len(data)\n    if data_len < period:\n        raise Exception(\"Error: data_len < period\")",
    "docstring": "Check for Period Error.\n\n    This method checks if the developer is trying to enter a period that is\n    larger than the data set being entered. If that is the case an exception is\n    raised with a custom message that informs the developer that their period\n    is greater than the data set."
  },
  {
    "code": "def _classification_fetch(self, skip_missing=None):\n        skip_missing = skip_missing if skip_missing else self._kwargs[\"skip_missing\"]\n        new_classifications = []\n        for a in self._res_list:\n            if a.__class__.__name__ == \"Samples\":\n                c = a.primary_classification\n            elif a.__class__.__name__ == \"Classifications\":\n                c = a\n            else:\n                raise OneCodexException(\n                    \"Objects in SampleCollection must be one of: Classifications, Samples\"\n                )\n            if skip_missing and not c.success:\n                warnings.warn(\"Classification {} not successful. Skipping.\".format(c.id))\n                continue\n            new_classifications.append(c)\n        self._cached[\"classifications\"] = new_classifications",
    "docstring": "Turns a list of objects associated with a classification result into a list of\n        Classifications objects.\n\n        Parameters\n        ----------\n        skip_missing : `bool`\n            If an analysis was not successful, exclude it, warn, and keep going\n\n        Returns\n        -------\n        None, but stores a result in self._cached."
  },
  {
    "code": "def _init_idxs_strpat(self, usr_hdrs):\n        strpat = self.strpat_hdrs.keys()\n        self.idxs_strpat = [\n            Idx for Hdr, Idx in self.hdr2idx.items() if Hdr in usr_hdrs and Hdr in strpat]",
    "docstring": "List of indexes whose values will be strings."
  },
  {
    "code": "def _pop(self, key, default=None):\n        path = self.__path_of(key)\n        value = None\n        try:\n            raw_value, _ = self.connection.retry(self.connection.get, path)\n            value = self.encoding.decode(raw_value)\n        except self.no_node_error:\n            if default:\n                return default\n            else:\n                raise KeyError\n        try:\n            self.connection.retry(self.connection.delete, path)\n            self.__increment_last_updated()\n        except self.no_node_error:\n            pass\n        return value",
    "docstring": "If ``key`` is present in Zookeeper, removes it from Zookeeper and\n        returns the value.  If key is not in Zookeper and ``default`` argument\n        is provided, ``default`` is returned.  If ``default`` argument is not\n        provided, ``KeyError`` is raised.\n\n        :param key: Key to remove from Zookeeper\n        :type key: string\n        :param default: Default object to return if ``key`` is not present.\n        :type default: object"
  },
  {
    "code": "def remove_tmp_prefix_from_filename(filename):\n    if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):\n        raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename})\n    return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):]",
    "docstring": "Remove tmp prefix from filename."
  },
  {
    "code": "def _makeResponse(self, urllib2_response):\n        resp = HTTPResponse()\n        resp.body = urllib2_response.read(MAX_RESPONSE_KB * 1024)\n        resp.final_url = urllib2_response.geturl()\n        resp.headers = self._lowerCaseKeys(\n            dict(list(urllib2_response.info().items())))\n        if hasattr(urllib2_response, 'code'):\n            resp.status = urllib2_response.code\n        else:\n            resp.status = 200\n        _, extra_dict = self._parseHeaderValue(\n            resp.headers.get(\"content-type\", \"\"))\n        charset = extra_dict.get('charset', 'latin1')\n        try:\n            resp.body = resp.body.decode(charset)\n        except Exception:\n            pass\n        return resp",
    "docstring": "Construct an HTTPResponse from the the urllib response. Attempt to\n        decode the response body from bytes to str if the necessary information\n        is available."
  },
  {
    "code": "def _get_regex_pattern(label):\n    parts = _split_by_punctuation.split(label)\n    for index, part in enumerate(parts):\n        if index % 2 == 0:\n            if not parts[index].isdigit() and len(parts[index]) > 1:\n                parts[index] = _convert_word(parts[index])\n        else:\n            if not parts[index + 1]:\n                parts[index] = _convert_punctuation(\n                    parts[index],\n                    current_app.config[\"CLASSIFIER_SYMBOLS\"]\n                )\n            else:\n                parts[index] = _convert_punctuation(\n                    parts[index],\n                    current_app.config[\"CLASSIFIER_SEPARATORS\"]\n                )\n    return \"\".join(parts)",
    "docstring": "Return a regular expression of the label.\n\n    This takes care of plural and different kinds of separators."
  },
  {
    "code": "def _update_failure_type(self):\n        note = JobNote.objects.filter(job=self.job).order_by('-created').first()\n        if note:\n            self.job.failure_classification_id = note.failure_classification.id\n        else:\n            self.job.failure_classification_id = FailureClassification.objects.get(name='not classified').id\n        self.job.save()",
    "docstring": "Updates the failure type of this Note's Job.\n\n        Set the linked Job's failure type to that of the most recent JobNote or\n        set to Not Classified if there are no JobNotes.\n\n        This is called when JobNotes are created (via .save()) and deleted (via\n        .delete()) and is used to resolved the FailureClassification which has\n        been denormalised onto Job."
  },
  {
    "code": "def extract_words(string):\n    return re.findall(r'[%s]+[%s\\.]*[%s]+' % (A, A, A), string, flags=FLAGS)",
    "docstring": "Extract all alphabetic syllabified forms from 'string'."
  },
  {
    "code": "def set_level(logger, level):\n    if isinstance(logger, str):\n        logger = logging.getLogger(logger)\n    original = logger.level\n    logger.setLevel(level)\n    try:\n        yield\n    finally:\n        logger.setLevel(original)",
    "docstring": "Temporarily change log level of logger.\n\n    Parameters\n    ----------\n    logger : str or ~logging.Logger\n        Logger name or logger whose log level to change.\n    level : int\n        Log level to set.\n\n    Examples\n    --------\n    >>> with set_level('sqlalchemy.engine', logging.INFO):\n    ...     pass  # sqlalchemy log level is set to INFO in this block"
  },
  {
    "code": "def proc_check_guard(self, instance, sql):\n        self.open_db_connections(instance, self.PROC_GUARD_DB_KEY)\n        cursor = self.get_cursor(instance, self.PROC_GUARD_DB_KEY)\n        should_run = False\n        try:\n            cursor.execute(sql, ())\n            result = cursor.fetchone()\n            should_run = result[0] == 1\n        except Exception as e:\n            self.log.error(\"Failed to run proc_only_if sql {} : {}\".format(sql, e))\n        self.close_cursor(cursor)\n        self.close_db_connections(instance, self.PROC_GUARD_DB_KEY)\n        return should_run",
    "docstring": "check to see if the guard SQL returns a single column containing 0 or 1\n        We return true if 1, else False"
  },
  {
    "code": "def get(self):\n        if len(self) < 1:\n            return \"wow\"\n        if self.index >= len(self):\n            self.index = 0\n        step = random.randint(1, min(self.step, len(self)))\n        res = self[0]\n        self.index += step\n        self.rotate(step)\n        return res",
    "docstring": "Get one item and prepare to get an item with lower\n        rank on the next call."
  },
  {
    "code": "def dump(cls, filename, objects, properties, bools, encoding):\n        if encoding is None:\n            encoding = cls.encoding\n        source = cls.dumps(objects, properties, bools)\n        if PY2:\n            source = unicode(source)\n        with io.open(filename, 'w', encoding=encoding) as fd:\n            fd.write(source)",
    "docstring": "Write serialized objects, properties, bools to file."
  },
  {
    "code": "def column_vectors(self):\n        a, b, c, d, e, f, _, _, _ = self\n        return (a, d), (b, e), (c, f)",
    "docstring": "The values of the transform as three 2D column vectors"
  },
  {
    "code": "def get_pages(self):\n        pages = []\n        page = []\n        for i, item in enumerate(self.get_rows):\n            if i > 0 and i % self.objects_per_page == 0:\n                pages.append(page)\n                page = []\n            page.append(item)\n        pages.append(page)\n        return pages",
    "docstring": "returns pages with rows"
  },
  {
    "code": "def is_valid_int(value):\n        if 0 <= value <= Parameter.MAX:\n            return True\n        if value == Parameter.UNKNOWN_VALUE:\n            return True\n        if value == Parameter.CURRENT_POSITION:\n            return True\n        return False",
    "docstring": "Test if value can be rendered out of int."
  },
  {
    "code": "def parsehttpdate(string_):\n    try:\n        t = time.strptime(string_, \"%a, %d %b %Y %H:%M:%S %Z\")\n    except ValueError:\n        return None\n    return datetime.datetime(*t[:6])",
    "docstring": "Parses an HTTP date into a datetime object.\n\n        >>> parsehttpdate('Thu, 01 Jan 1970 01:01:01 GMT')\n        datetime.datetime(1970, 1, 1, 1, 1, 1)"
  },
  {
    "code": "def _get_global_color_table(colors):\n    global_color_table = b''.join(c[0] for c in colors.most_common())\n    full_table_size = 2**(1+int(get_color_table_size(len(colors)), 2))\n    repeats = 3 * (full_table_size - len(colors))\n    zeros = struct.pack('<{}x'.format(repeats))\n    return global_color_table + zeros",
    "docstring": "Return a color table sorted in descending order of count."
  },
  {
    "code": "def store_initial_k2k_session(auth_url, request, scoped_auth_ref,\n                              unscoped_auth_ref):\n    keystone_provider_id = request.session.get('keystone_provider_id', None)\n    if keystone_provider_id:\n        return None\n    providers = getattr(scoped_auth_ref, 'service_providers', None)\n    if providers:\n        providers = getattr(providers, '_service_providers', None)\n    if providers:\n        keystone_idp_name = getattr(settings, 'KEYSTONE_PROVIDER_IDP_NAME',\n                                    'Local Keystone')\n        keystone_idp_id = getattr(\n            settings, 'KEYSTONE_PROVIDER_IDP_ID', 'localkeystone')\n        keystone_identity_provider = {'name': keystone_idp_name,\n                                      'id': keystone_idp_id}\n        keystone_providers = [\n            {'name': provider_id, 'id': provider_id}\n            for provider_id in providers]\n        keystone_providers.append(keystone_identity_provider)\n        request.session['keystone_provider_id'] = keystone_idp_id\n        request.session['keystone_providers'] = keystone_providers\n        request.session['k2k_base_unscoped_token'] =\\\n            unscoped_auth_ref.auth_token\n        request.session['k2k_auth_url'] = auth_url",
    "docstring": "Stores session variables if there are k2k service providers\n\n    This stores variables related to Keystone2Keystone federation. This\n    function gets skipped if there are no Keystone service providers.\n    An unscoped token to the identity provider keystone gets stored\n    so that it can be used to do federated login into the service\n    providers when switching keystone providers.\n    The settings file can be configured to set the display name\n    of the local (identity provider) keystone by setting\n    KEYSTONE_PROVIDER_IDP_NAME. The KEYSTONE_PROVIDER_IDP_ID settings\n    variable is used for comparison against the service providers.\n    It should not conflict with any of the service provider ids.\n\n    :param auth_url: base token auth url\n    :param request: Django http request object\n    :param scoped_auth_ref: Scoped Keystone access info object\n    :param unscoped_auth_ref: Unscoped Keystone access info object"
  },
  {
    "code": "def authenticate_with_email_and_pwd(user_email, user_password):\n    if user_email is None or user_password is None:\n        raise ValueError(\n            'Could not authenticate user. Missing username or password')\n    upload_token = uploader.get_upload_token(user_email, user_password)\n    if not upload_token:\n        print(\"Authentication failed for user name \" +\n              user_name + \", please try again.\")\n        sys.exit(1)\n    user_key = get_user_key(user_name)\n    if not user_key:\n        print(\"User name {} does not exist, please try again or contact Mapillary user support.\".format(\n            user_name))\n        sys.exit(1)\n    user_permission_hash, user_signature_hash = get_user_hashes(\n        user_key, upload_token)\n    user_items[\"MAPSettingsUsername\"] = section\n    user_items[\"MAPSettingsUserKey\"] = user_key\n    user_items[\"user_upload_token\"] = upload_token\n    user_items[\"user_permission_hash\"] = user_permission_hash\n    user_items[\"user_signature_hash\"] = user_signature_hash\n    return user_items",
    "docstring": "Authenticate the user by passing the email and password.\n    This function avoids prompting the command line for user credentials and is useful for calling tools programmatically"
  },
  {
    "code": "def dumpfile(self, fd):\n        self.start()\n        dump = DumpFile(fd)\n        self.queue.append(dump)",
    "docstring": "Dump a file through a Spin instance."
  },
  {
    "code": "def is_valid(self):\n        validity = True\n        for element in self._validity_map:\n            if self._validity_map[element] is not VALID:\n                validity = False\n        return validity",
    "docstring": "Tests if ths form is in a valid state for submission.\n\n        A form is valid if all required data has been supplied compliant\n        with any constraints.\n\n        return: (boolean) - false if there is a known error in this\n                form, true otherwise\n        raise:  OperationFailed - attempt to perform validation failed\n        compliance: mandatory - This method must be implemented."
  },
  {
    "code": "def from_record(self, record):\n        kwargs = self.get_field_kwargs(record)\n        return self.sequenced_item_class(**kwargs)",
    "docstring": "Constructs and returns a sequenced item object, from given ORM object."
  },
  {
    "code": "def get_accelerometer_raw(self):\n        raw = self._get_raw_data('accelValid', 'accel')\n        if raw is not None:\n            self._last_accel_raw = raw\n        return deepcopy(self._last_accel_raw)",
    "docstring": "Accelerometer x y z raw data in Gs"
  },
  {
    "code": "def add_dockwidget(self, child):\r\n        dockwidget, location = child.create_dockwidget()\r\n        if CONF.get('main', 'vertical_dockwidget_titlebars'):\r\n            dockwidget.setFeatures(dockwidget.features()|\r\n                                   QDockWidget.DockWidgetVerticalTitleBar)\r\n        self.addDockWidget(location, dockwidget)\r\n        self.widgetlist.append(child)",
    "docstring": "Add QDockWidget and toggleViewAction"
  },
  {
    "code": "def clear_recovery_range(working_dir):\n    recovery_range_path = os.path.join(working_dir, '.recovery')\n    if os.path.exists(recovery_range_path):\n        os.unlink(recovery_range_path)",
    "docstring": "Clear out our recovery hint"
  },
  {
    "code": "def nearest_neighbour_delta_E( self ):\n        delta_nn = self.final_site.nn_occupation() - self.initial_site.nn_occupation() - 1\n        return ( delta_nn * self.nearest_neighbour_energy )",
    "docstring": "Nearest-neighbour interaction contribution to the change in system energy if this jump were accepted.\n\n        Args:\n            None\n\n        Returns:\n            (Float): delta E (nearest-neighbour)"
  },
  {
    "code": "def update_dois(csv_source, write_file=True):\n    _dois_arr = []\n    _dois_raw = []\n    with open(csv_source, \"r\") as f:\n        reader = csv.reader(f)\n        for row in reader:\n            _dois_arr.append(row[0])\n    for _doi in _dois_arr:\n        _dois_raw.append(_update_doi(_doi))\n    if write_file:\n        new_filename = os.path.splitext(csv_source)[0]\n        write_json_to_file(_dois_raw, new_filename)\n    else:\n        print(json.dumps(_dois_raw, indent=2))\n    return",
    "docstring": "Get DOI publication info for a batch of DOIs. This is LiPD-independent and only requires a CSV file with all DOIs\n    listed in a single column. The output is LiPD-formatted publication data for each entry.\n\n    :param str csv_source: Local path to CSV file\n    :param bool write_file: Write output data to JSON file (True), OR pretty print output to console (False)\n    :return none:"
  },
  {
    "code": "def has_previous_assessment_section(self, assessment_section_id):\n        try:\n            self.get_previous_assessment_section(assessment_section_id)\n        except errors.IllegalState:\n            return False\n        else:\n            return True",
    "docstring": "Tests if there is a previous assessment section in the assessment following the given assessment section ``Id``.\n\n        arg:    assessment_section_id (osid.id.Id): ``Id`` of the\n                ``AssessmentSection``\n        return: (boolean) - ``true`` if there is a previous assessment\n                section, ``false`` otherwise\n        raise:  IllegalState - ``has_assessment_begun()`` is ``false``\n        raise:  NotFound - ``assessment_section_id`` is not found\n        raise:  NullArgument - ``assessment_section_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _maybe_null_out(result, axis, mask, min_count=1):\n    if hasattr(axis, '__len__'):\n        raise ValueError('min_count is not available for reduction '\n                         'with more than one dimensions.')\n    if axis is not None and getattr(result, 'ndim', False):\n        null_mask = (mask.shape[axis] - mask.sum(axis) - min_count) < 0\n        if null_mask.any():\n            dtype, fill_value = dtypes.maybe_promote(result.dtype)\n            result = result.astype(dtype)\n            result[null_mask] = fill_value\n    elif getattr(result, 'dtype', None) not in dtypes.NAT_TYPES:\n        null_mask = mask.size - mask.sum()\n        if null_mask < min_count:\n            result = np.nan\n    return result",
    "docstring": "xarray version of pandas.core.nanops._maybe_null_out"
  },
  {
    "code": "def rss_create(channel, articles):\n    channel = channel.copy()\n    articles = list(articles)\n    rss = ET.Element('rss')\n    rss.set('version', '2.0')\n    channel_node = ET.SubElement(rss, 'channel')\n    element_from_dict(channel_node, channel, 'title')\n    element_from_dict(channel_node, channel, 'link')\n    element_from_dict(channel_node, channel, 'description')\n    element_from_dict(channel_node, channel, 'language')\n    for article in articles:\n        item = ET.SubElement(channel_node, 'item')\n        element_from_dict(item, article, 'title')\n        element_from_dict(item, article, 'description')\n        element_from_dict(item, article, 'link')\n        for key in article:\n            complex_el_from_dict(item, article, key)\n    return ET.ElementTree(rss)",
    "docstring": "Create RSS xml feed.\n\n    :param channel: channel info [title, link, description, language]\n    :type channel: dict(str, str)\n    :param articles: list of articles, an article is a dictionary with some \\\n    required fields [title, description, link] and any optional, which will \\\n    result to `<dict_key>dict_value</dict_key>`\n    :type articles: list(dict(str,str))\n    :return: root element\n    :rtype: ElementTree.Element"
  },
  {
    "code": "def zeta(x, context=None):\n    return _apply_function_in_current_context(\n        BigFloat,\n        mpfr.mpfr_zeta,\n        (BigFloat._implicit_convert(x),),\n        context,\n    )",
    "docstring": "Return the value of the Riemann zeta function on x."
  },
  {
    "code": "def match_process(pid, name, cmdline, exe, cfg):\n    if cfg['selfmon'] and pid == os.getpid():\n        return True\n    for exe_re in cfg['exe']:\n        if exe_re.search(exe):\n            return True\n    for name_re in cfg['name']:\n        if name_re.search(name):\n            return True\n    for cmdline_re in cfg['cmdline']:\n        if cmdline_re.search(' '.join(cmdline)):\n            return True\n    return False",
    "docstring": "Decides whether a process matches with a given process descriptor\n\n    :param pid: process pid\n    :param exe: process executable\n    :param name: process name\n    :param cmdline: process cmdline\n    :param cfg: the dictionary from processes that describes with the\n        process group we're testing for\n    :return: True if it matches\n    :rtype: bool"
  },
  {
    "code": "def _createtoken(self, type_, value, flags=None):\n        pos = None\n        assert len(self._positions) >= 2, (type_, value)\n        p2 = self._positions.pop()\n        p1 = self._positions.pop()\n        pos = [p1, p2]\n        return token(type_, value, pos, flags)",
    "docstring": "create a token with position information"
  },
  {
    "code": "def create_reward_encoder():\n        last_reward = tf.Variable(0, name=\"last_reward\", trainable=False, dtype=tf.float32)\n        new_reward = tf.placeholder(shape=[], dtype=tf.float32, name='new_reward')\n        update_reward = tf.assign(last_reward, new_reward)\n        return last_reward, new_reward, update_reward",
    "docstring": "Creates TF ops to track and increment recent average cumulative reward."
  },
  {
    "code": "def hsl_to_rgb(self, h, s, l):\n        h = h % 1.0\n        s = min(max(s, 0.0), 1.0)\n        l = min(max(l, 0.0), 1.0)\n        if l <= 0.5:\n            m2 = l*(s + 1.0)\n        else:\n            m2 = l + s - l*s\n        m1 = l*2.0 - m2\n        r = self._hue_to_rgb(m1, m2, h + 1.0/3.0)\n        g = self._hue_to_rgb(m1, m2, h)\n        b = self._hue_to_rgb(m1, m2, h - 1.0/3.0)\n        r **= self.gamma\n        g **= self.gamma\n        b **= self.gamma\n        return (r, g, b)",
    "docstring": "Convert a color from HSL color-model to RGB.\n\n        See also:\n        - http://www.w3.org/TR/css3-color/#hsl-color"
  },
  {
    "code": "def get(self, timeout=None, block=True):\n        _vv and IOLOG.debug('%r.get(timeout=%r, block=%r)',\n                            self, timeout, block)\n        self._lock.acquire()\n        try:\n            if self.closed:\n                raise LatchError()\n            i = len(self._sleeping)\n            if len(self._queue) > i:\n                _vv and IOLOG.debug('%r.get() -> %r', self, self._queue[i])\n                return self._queue.pop(i)\n            if not block:\n                raise TimeoutError()\n            rsock, wsock = self._get_socketpair()\n            cookie = self._make_cookie()\n            self._sleeping.append((wsock, cookie))\n        finally:\n            self._lock.release()\n        poller = self.poller_class()\n        poller.start_receive(rsock.fileno())\n        try:\n            return self._get_sleep(poller, timeout, block, rsock, wsock, cookie)\n        finally:\n            poller.close()",
    "docstring": "Return the next enqueued object, or sleep waiting for one.\n\n        :param float timeout:\n            If not :data:`None`, specifies a timeout in seconds.\n\n        :param bool block:\n            If :data:`False`, immediately raise\n            :class:`mitogen.core.TimeoutError` if the latch is empty.\n\n        :raises mitogen.core.LatchError:\n            :meth:`close` has been called, and the object is no longer valid.\n\n        :raises mitogen.core.TimeoutError:\n            Timeout was reached.\n\n        :returns:\n            The de-queued object."
  },
  {
    "code": "def append_field(self, field_name, list_value):\n    return self._single_list_field_operation(field_name, list_value, prepend=False)",
    "docstring": "Return a copy of this object with `list_value` appended to the field named `field_name`."
  },
  {
    "code": "def build_css(minimize=True):\n  print('Build CSS')\n  args = {}\n  args['style'] = 'compressed' if minimize else 'nested'\n  cmd = CMD_SASS.format(**args)\n  run(cmd)",
    "docstring": "Builds CSS from SASS."
  },
  {
    "code": "def format_ubuntu_dialog(df):\n    s = ''\n    for i, record in df.iterrows():\n        statement = list(split_turns(record.Context))[-1]\n        reply = list(split_turns(record.Utterance))[-1]\n        s += 'Statement: {}\\n'.format(statement)\n        s += 'Reply: {}\\n\\n'.format(reply)\n    return s",
    "docstring": "Print statements paired with replies, formatted for easy review"
  },
  {
    "code": "def marquee(text=\"\", width=78, mark='*'):\n    if not text:\n        return (mark*width)[:width]\n    nmark = (width-len(text)-2)//len(mark)//2\n    if nmark < 0: \n        nmark = 0\n    marks = mark * nmark\n    return '%s %s %s' % (marks, text, marks)",
    "docstring": "Return the input string centered in a 'marquee'.\n\n    Args:\n        text (str): Input string\n        width (int): Width of final output string.\n        mark (str): Character used to fill string.\n\n    :Examples:\n\n    >>> marquee('A test', width=40)\n    '**************** A test ****************'\n\n    >>> marquee('A test', width=40, mark='-')\n    '---------------- A test ----------------'\n\n    marquee('A test',40, ' ')\n    '                 A test                 '"
  },
  {
    "code": "def dt2str(dt, flagSeconds=True):\r\n    if isinstance(dt, str):\r\n        return dt\r\n    return dt.strftime(_FMTS if flagSeconds else _FMT)",
    "docstring": "Converts datetime object to str if not yet an str."
  },
  {
    "code": "def get_protein_id_list(df, level=0):\n    protein_list = []\n    for s in df.index.get_level_values(level):\n        protein_list.extend( get_protein_ids(s) )\n    return list(set(protein_list))",
    "docstring": "Return a complete list of shortform IDs from a DataFrame\n\n    Extract all protein IDs from a dataframe from multiple rows containing\n    protein IDs in MaxQuant output format: e.g. P07830;P63267;Q54A44;P63268\n\n    Long names (containing species information) are eliminated (split on ' ') and\n    isoforms are removed (split on '_').\n\n    :param df: DataFrame\n    :type df: pandas.DataFrame\n    :param level: Level of DataFrame index to extract IDs from\n    :type level: int or str\n    :return: list of string ids"
  },
  {
    "code": "def readInstance(self, key, makeGlyphs=True, makeKerning=True, makeInfo=True):\n        attrib, value = key\n        for instanceElement in self.root.findall('.instances/instance'):\n            if instanceElement.attrib.get(attrib) == value:\n                self._readSingleInstanceElement(instanceElement, makeGlyphs=makeGlyphs, makeKerning=makeKerning, makeInfo=makeInfo)\n                return\n        raise MutatorError(\"No instance found with key: (%s, %s).\" % key)",
    "docstring": "Read a single instance element.\n\n            key: an (attribute, value) tuple used to find the requested instance.\n\n        ::\n\n            <instance familyname=\"SuperFamily\" filename=\"OutputNameInstance1.ufo\" location=\"location-token-aaa\" stylename=\"Regular\">"
  },
  {
    "code": "def check_socket(host, port):\n    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:\n        return sock.connect_ex((host, port)) == 0",
    "docstring": "Checks if port is open on host. This is used to check if the\n    Xenon-GRPC server is running."
  },
  {
    "code": "def list_files(dir_pathname,\n               recursive=True,\n               topdown=True,\n               followlinks=False):\n    for root, dirnames, filenames\\\n    in walk(dir_pathname, recursive, topdown, followlinks):\n        for filename in filenames:\n            yield absolute_path(os.path.join(root, filename))",
    "docstring": "Enlists all the files using their absolute paths within the specified\n    directory, optionally recursively.\n\n    :param dir_pathname:\n        The directory to traverse.\n    :param recursive:\n        ``True`` for walking recursively through the directory tree;\n        ``False`` otherwise.\n    :param topdown:\n        Please see the documentation for :func:`os.walk`\n    :param followlinks:\n        Please see the documentation for :func:`os.walk`"
  },
  {
    "code": "def convert_time(time):\n    split_time = time.split()\n    try:\n        am_pm = split_time[1].replace('.', '')\n        time_str = '{0} {1}'.format(split_time[0], am_pm)\n    except IndexError:\n        return time\n    try:\n        time_obj = datetime.strptime(time_str, '%I:%M %p')\n    except ValueError:\n        time_obj = datetime.strptime(time_str, '%I %p')\n    return time_obj.strftime('%H:%M %p')",
    "docstring": "Convert a time string into 24-hour time."
  },
  {
    "code": "def _get_elem_names(self):\n        import nuutils as u\n        element_name = self.elements_names\n        u.give_zip_element_z_and_names(element_name)\n        self.z_of_element_name = u.index_z_for_elements",
    "docstring": "returns for one cycle an element name dictionary."
  },
  {
    "code": "def convert_ipynbs(directory):\n    for root, subfolders, files in os.walk(os.path.abspath(directory)):\n        for f in files:\n            if \".ipynb_checkpoints\" not in root:\n                if f.endswith(\"ipynb\"):\n                    ipynb_to_rst(root, f)",
    "docstring": "Recursively converts all ipynb files in a directory into rst files in\n    the same directory."
  },
  {
    "code": "def extract_sponsor(bill):\n    logger.debug(\"Extracting Sponsor\")\n    sponsor_map = []\n    sponsor = bill.get('sponsor', None)\n    if sponsor:\n        sponsor_map.append(sponsor.get('type'))\n        sponsor_map.append(sponsor.get('thomas_id'))\n        sponsor_map.append(bill.get('bill_id'))\n        sponsor_map.append(sponsor.get('district'))\n        sponsor_map.append(sponsor.get('state'))\n    logger.debug(\"END Extracting Sponsor\")\n    return sponsor_map if sponsor_map else None",
    "docstring": "Return a list of the fields we need to map a sponser to a bill"
  },
  {
    "code": "def print_name_version(self):\n        if self.use_sys:\n            self.print_generic(u\"%s v%s\" % (self.NAME, aeneas_version))\n        return self.exit(self.HELP_EXIT_CODE)",
    "docstring": "Print program name and version and exit.\n\n        :rtype: int"
  },
  {
    "code": "def to_ufos(\n    font,\n    include_instances=False,\n    family_name=None,\n    propagate_anchors=True,\n    ufo_module=defcon,\n    minimize_glyphs_diffs=False,\n    generate_GDEF=True,\n    store_editor_state=True,\n):\n    builder = UFOBuilder(\n        font,\n        ufo_module=ufo_module,\n        family_name=family_name,\n        propagate_anchors=propagate_anchors,\n        minimize_glyphs_diffs=minimize_glyphs_diffs,\n        generate_GDEF=generate_GDEF,\n        store_editor_state=store_editor_state,\n    )\n    result = list(builder.masters)\n    if include_instances:\n        return result, builder.instance_data\n    return result",
    "docstring": "Take a GSFont object and convert it into one UFO per master.\n\n    Takes in data as Glyphs.app-compatible classes, as documented at\n    https://docu.glyphsapp.com/\n\n    If include_instances is True, also returns the parsed instance data.\n\n    If family_name is provided, the master UFOs will be given this name and\n    only instances with this name will be returned.\n\n    If generate_GDEF is True, write a `table GDEF {...}` statement in the\n    UFO's features.fea, containing GlyphClassDef and LigatureCaretByPos."
  },
  {
    "code": "def get_s3_buckets(api_client, s3_info, s3_params):\n    manage_dictionary(s3_info, 'buckets', {})\n    buckets = api_client[get_s3_list_region(s3_params['selected_regions'])].list_buckets()['Buckets']\n    targets = []\n    for b in buckets:\n        if (b['Name'] in s3_params['skipped_buckets']) or (len(s3_params['checked_buckets']) and b['Name'] not in s3_params['checked_buckets']):\n            continue\n        targets.append(b)\n    s3_info['buckets_count'] = len(targets)\n    s3_params['api_clients'] = api_client\n    s3_params['s3_info'] = s3_info\n    thread_work(targets, get_s3_bucket, params = s3_params, num_threads = 30)\n    show_status(s3_info)\n    s3_info['buckets_count'] = len(s3_info['buckets'])\n    return s3_info",
    "docstring": "List all available buckets\n\n    :param api_client:\n    :param s3_info:\n    :param s3_params:\n    :return:"
  },
  {
    "code": "def load_commands_from_entry_point(self, specifier):\n        for ep in pkg_resources.iter_entry_points(specifier):\n            module = ep.load()\n            command.discover_and_call(module, self.command)",
    "docstring": "Load commands defined within a pkg_resources entry point.\n\n        Each entry will be a module that should be searched for functions\n        decorated with the :func:`subparse.command` decorator. This\n        operation is not recursive."
  },
  {
    "code": "def convert_from_sliced_object(data):\n    if data.base is not None and isinstance(data, np.ndarray) and isinstance(data.base, np.ndarray):\n        if not data.flags.c_contiguous:\n            warnings.warn(\"Usage of np.ndarray subset (sliced data) is not recommended \"\n                          \"due to it will double the peak memory cost in LightGBM.\")\n            return np.copy(data)\n    return data",
    "docstring": "Fix the memory of multi-dimensional sliced object."
  },
  {
    "code": "def real_main(start_url=None,\n              ignore_prefixes=None,\n              upload_build_id=None,\n              upload_release_name=None):\n    coordinator = workers.get_coordinator()\n    fetch_worker.register(coordinator)\n    coordinator.start()\n    item = SiteDiff(\n        start_url=start_url,\n        ignore_prefixes=ignore_prefixes,\n        upload_build_id=upload_build_id,\n        upload_release_name=upload_release_name,\n        heartbeat=workers.PrintWorkflow)\n    item.root = True\n    coordinator.input_queue.put(item)\n    coordinator.wait_one()\n    coordinator.stop()\n    coordinator.join()",
    "docstring": "Runs the site_diff."
  },
  {
    "code": "def out_of_bag_mae(self):\n        if not self._out_of_bag_mae_clean:\n            try:\n                self._out_of_bag_mae = self.test(self.out_of_bag_samples)\n                self._out_of_bag_mae_clean = True\n            except NodeNotReadyToPredict:\n                return\n        return self._out_of_bag_mae.copy()",
    "docstring": "Returns the mean absolute error for predictions on the out-of-bag\n        samples."
  },
  {
    "code": "def _update_eof(self):\n        self._aftermathmp()\n        self._ifile.close()\n        self._flag_e = True",
    "docstring": "Update EOF flag."
  },
  {
    "code": "def get_statements(self):\n        stmt_lists = [v for k, v in self.stmts.items()]\n        stmts = []\n        for s in stmt_lists:\n            stmts += s\n        return stmts",
    "docstring": "Return a list of all Statements in a single list.\n\n        Returns\n        -------\n        stmts : list[indra.statements.Statement]\n            A list of all the INDRA Statements in the model."
  },
  {
    "code": "def order_snapshot_space(self, volume_id, capacity, tier,\n                             upgrade, **kwargs):\n        block_mask = 'id,billingItem[location,hourlyFlag],'\\\n            'storageType[keyName],storageTierLevel,provisionedIops,'\\\n            'staasVersion,hasEncryptionAtRest'\n        block_volume = self.get_block_volume_details(volume_id,\n                                                     mask=block_mask,\n                                                     **kwargs)\n        order = storage_utils.prepare_snapshot_order_object(\n            self, block_volume, capacity, tier, upgrade)\n        return self.client.call('Product_Order', 'placeOrder', order)",
    "docstring": "Orders snapshot space for the given block volume.\n\n        :param integer volume_id: The id of the volume\n        :param integer capacity: The capacity to order, in GB\n        :param float tier: The tier level of the block volume, in IOPS per GB\n        :param boolean upgrade: Flag to indicate if this order is an upgrade\n        :return: Returns a SoftLayer_Container_Product_Order_Receipt"
  },
  {
    "code": "def loadIntoTextureD3D11_Async(self, textureId, pDstTexture):\n        fn = self.function_table.loadIntoTextureD3D11_Async\n        result = fn(textureId, pDstTexture)\n        return result",
    "docstring": "Helper function to copy the bits into an existing texture."
  },
  {
    "code": "def ensure_connected(self):\n        if not self.is_connected():\n            if not self._auto_connect:\n                raise DBALConnectionError.connection_closed()\n            self.connect()",
    "docstring": "Ensures database connection is still open."
  },
  {
    "code": "def write(self, s):\n        for line in re.split(r'\\n+', s):\n            if line != '':\n                self._logger.log(self._level, line)",
    "docstring": "Write message to logger."
  },
  {
    "code": "def load_cli(subparsers):\n    for command_name in available_commands():\n        module = '{}.{}'.format(__package__, command_name)\n        loader, description = _import_loader(module)\n        parser = subparsers.add_parser(command_name,\n                                       description=description)\n        command = loader(parser)\n        if command is None:\n            raise RuntimeError('Failed to load \"{}\".'.format(command_name))\n        parser.set_defaults(cmmd=command)",
    "docstring": "Given a parser, load the CLI subcommands"
  },
  {
    "code": "def _cleandoc(doc):\n    indent_length = lambda s: len(s) - len(s.lstrip(\" \"))\n    not_empty = lambda s: s != \"\"\n    lines = doc.split(\"\\n\")\n    indent = min(map(indent_length, filter(not_empty, lines)))\n    return \"\\n\".join(s[indent:] for s in lines)",
    "docstring": "Remove uniform indents from ``doc`` lines that are not empty\n\n    :returns: Cleaned ``doc``"
  },
  {
    "code": "def _getPOS( self, token, onlyFirst = True ):\r\n        if onlyFirst:\r\n            return token[ANALYSIS][0][POSTAG]\r\n        else:\r\n            return [ a[POSTAG] for a in token[ANALYSIS] ]",
    "docstring": "Returns POS of the current token."
  },
  {
    "code": "def _parse(res, params, n, api, **kwds):\n    cursor = \"cursor\" in params\n    if not cursor:\n        start = params[\"start\"]\n    if n == 0:\n        return \"\"\n    _json = res.get('search-results', {}).get('entry', [])\n    while n > 0:\n        n -= params[\"count\"]\n        if cursor:\n            pointer = res['search-results']['cursor'].get('@next')\n            params.update({'cursor': pointer})\n        else:\n            start += params[\"count\"]\n            params.update({'start': start})\n        res = download(url=URL[api], params=params, accept=\"json\", **kwds).json()\n        _json.extend(res.get('search-results', {}).get('entry', []))\n    return _json",
    "docstring": "Auxiliary function to download results and parse json."
  },
  {
    "code": "def get_connection_by_node(self, node):\n        self._checkpid()\n        self.nodes.set_node_name(node)\n        try:\n            connection = self._available_connections.get(node[\"name\"], []).pop()\n        except IndexError:\n            connection = self.make_connection(node)\n        self._in_use_connections.setdefault(node[\"name\"], set()).add(connection)\n        return connection",
    "docstring": "get a connection by node"
  },
  {
    "code": "def rescale_variables(\n    df,\n    variables_include = [],\n    variables_exclude = []\n    ):\n    variables_not_rescale = variables_exclude\n    variables_not_rescale.extend(df.columns[df.isna().any()].tolist())\n    variables_not_rescale.extend(df.select_dtypes(include = [\"object\", \"datetime\", \"timedelta\"]).columns)\n    variables_rescale = list(set(df.columns) - set(variables_not_rescale))\n    variables_rescale.extend(variables_include)\n    scaler = MinMaxScaler()\n    df[variables_rescale] = scaler.fit_transform(df[variables_rescale])\n    return df",
    "docstring": "Rescale variables in a DataFrame, excluding variables with NaNs and strings,\n    excluding specified variables, and including specified variables."
  },
  {
    "code": "def helper(self, name, *args):\n        py_name = ast.Name(\"@dessert_ar\", ast.Load())\n        attr = ast.Attribute(py_name, \"_\" + name, ast.Load())\n        return ast_Call(attr, list(args), [])",
    "docstring": "Call a helper in this module."
  },
  {
    "code": "def belongs_to_module(t, module_name):\n    \"Check if `t` belongs to `module_name`.\"\n    if hasattr(t, '__func__'): return belongs_to_module(t.__func__, module_name)\n    if not inspect.getmodule(t): return False\n    return inspect.getmodule(t).__name__.startswith(module_name)",
    "docstring": "Check if `t` belongs to `module_name`."
  },
  {
    "code": "def update_configuration(self, timeout=-1):\n        uri = \"{}/configuration\".format(self.data[\"uri\"])\n        return self._helper.update(None, uri=uri, timeout=timeout)",
    "docstring": "Asynchronously applies or re-applies the logical interconnect configuration to all managed interconnects.\n\n        Args:\n            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n                in OneView; it just stops waiting for its completion.\n\n        Returns:\n            dict: Logical Interconnect."
  },
  {
    "code": "def get_structure_by_formula(self, formula, **kwargs):\n        structures = []\n        sql = 'select file, sg from data where formula=\"- %s -\"' % \\\n              Composition(formula).hill_formula\n        text = self.query(sql).split(\"\\n\")\n        text.pop(0)\n        for l in text:\n            if l.strip():\n                cod_id, sg = l.split(\"\\t\")\n                r = requests.get(\"http://www.crystallography.net/cod/%s.cif\"\n                                 % cod_id.strip())\n                try:\n                    s = Structure.from_str(r.text, fmt=\"cif\", **kwargs)\n                    structures.append({\"structure\": s, \"cod_id\": int(cod_id),\n                                       \"sg\": sg})\n                except Exception:\n                    import warnings\n                    warnings.warn(\"\\nStructure.from_str failed while parsing CIF file:\\n%s\" % r.text)\n                    raise\n        return structures",
    "docstring": "Queries the COD for structures by formula. Requires mysql executable to\n        be in the path.\n\n        Args:\n            cod_id (int): COD id.\n            kwargs: All kwargs supported by\n                :func:`pymatgen.core.structure.Structure.from_str`.\n\n        Returns:\n            A list of dict of the format\n            [{\"structure\": Structure, \"cod_id\": cod_id, \"sg\": \"P n m a\"}]"
  },
  {
    "code": "def url2fs(url):\n    uri, extension = posixpath.splitext(url)\n    return safe64.dir(uri) + extension",
    "docstring": "encode a URL to be safe as a filename"
  },
  {
    "code": "def _split_generators(self, dl_manager):\n    path = dl_manager.download_and_extract(_DOWNLOAD_URL)\n    return [\n        tfds.core.SplitGenerator(\n            name=tfds.Split.TEST,\n            num_shards=1,\n            gen_kwargs={'data_dir': os.path.join(path, _DIRNAME)})\n    ]",
    "docstring": "Return the test split of Cifar10.\n\n    Args:\n      dl_manager: download manager object.\n\n    Returns:\n      test split."
  },
  {
    "code": "def remove_service_listener(self, listener):\n        for browser in self.browsers:\n            if browser.listener == listener:\n                browser.cancel()\n                del(browser)",
    "docstring": "Removes a listener from the set that is currently listening."
  },
  {
    "code": "def paste(self, key, data):\n        data_gen = self._get_paste_data_gen(key, data)\n        self.grid.actions.paste(key[:2], data_gen, freq=1000)\n        self.main_window.grid.ForceRefresh()",
    "docstring": "Pastes data into grid\n\n        Parameters\n        ----------\n\n        key: 2-Tuple of Integer\n        \\tTop left cell\n        data: String or wx.Bitmap\n        \\tTab separated string of paste data\n        \\tor paste data image"
  },
  {
    "code": "def document_path_path(cls, project, database, document_path):\n        return google.api_core.path_template.expand(\n            \"projects/{project}/databases/{database}/documents/{document_path=**}\",\n            project=project,\n            database=database,\n            document_path=document_path,\n        )",
    "docstring": "Return a fully-qualified document_path string."
  },
  {
    "code": "def _BinsToQuery(self, bins, column_name):\n    result = []\n    for prev_b, next_b in zip([0] + bins[:-1], bins[:-1] + [None]):\n      query = \"COUNT(CASE WHEN %s >= %f\" % (column_name, prev_b)\n      if next_b is not None:\n        query += \" AND %s < %f\" % (column_name, next_b)\n      query += \" THEN 1 END)\"\n      result.append(query)\n    return \", \".join(result)",
    "docstring": "Builds an SQL query part to fetch counts corresponding to given bins."
  },
  {
    "code": "def _minimum_one_is_missing(self, **kwargs):\n        rqset = self._meta_data['minimum_additional_parameters']\n        if rqset:\n            kwarg_set = set(iterkeys(kwargs))\n            if kwarg_set.isdisjoint(rqset):\n                args = sorted(rqset)\n                error_message = 'This resource requires at least one of the ' \\\n                                'mandatory additional ' \\\n                                'parameters to be provided: %s' % ', '.join(args)\n                raise MissingRequiredCreationParameter(error_message)",
    "docstring": "Helper function to do operation on sets\n\n        Verify if at least one of the elements\n        is present in **kwargs. If no items of rqset\n        are contained in **kwargs  the function\n        raises exception.\n\n        This check will only trigger if rqset is not empty.\n\n        Raises:\n             MissingRequiredCreationParameter"
  },
  {
    "code": "def prepare_request(self, request):\n        try:\n            request_id = local.request_id\n        except AttributeError:\n            request_id = NO_REQUEST_ID\n        if self.request_id_header and request_id != NO_REQUEST_ID:\n            request.headers[self.request_id_header] = request_id\n        return super(Session, self).prepare_request(request)",
    "docstring": "Include the request ID, if available, in the outgoing request"
  },
  {
    "code": "def fetch(self, invoice_id, data={}, **kwargs):\n        return super(Invoice, self).fetch(invoice_id, data, **kwargs)",
    "docstring": "Fetch Invoice for given Id\n\n        Args:\n            invoice_id : Id for which invoice object has to be retrieved\n\n        Returns:\n            Invoice dict for given invoice Id"
  },
  {
    "code": "def get_neg_one_task_agent(generators, market, nOffer, maxSteps):\n    env = pyreto.discrete.MarketEnvironment(generators, market, nOffer)\n    task = pyreto.discrete.ProfitTask(env, maxSteps=maxSteps)\n    agent = pyreto.util.NegOneAgent(env.outdim, env.indim)\n    return task, agent",
    "docstring": "Returns a task-agent tuple whose action is always minus one."
  },
  {
    "code": "def get(cls, rkey):\n        if rkey in cls._cached:\n            logger.info('Resource %s is in cache.' % rkey)\n            return cls._cached[rkey]\n        if rkey in cls._stock:\n            img = cls._load_image(rkey)\n            return img\n        else:\n            raise StockImageException('StockImage: %s not registered.' % rkey)",
    "docstring": "Get image previously registered with key rkey.\n        If key not exist, raise StockImageException"
  },
  {
    "code": "def away_abbreviation(self):\n        abbr = re.sub(r'.*/teams/', '', str(self._away_name))\n        abbr = re.sub(r'/.*', '', abbr)\n        return abbr",
    "docstring": "Returns a ``string`` of the away team's abbreviation, such as 'NWE'."
  },
  {
    "code": "def get_assessments_offered_by_ids(self, assessment_offered_ids):\n        collection = JSONClientValidated('assessment',\n                                         collection='AssessmentOffered',\n                                         runtime=self._runtime)\n        object_id_list = []\n        for i in assessment_offered_ids:\n            object_id_list.append(ObjectId(self._get_id(i, 'assessment').get_identifier()))\n        result = collection.find(\n            dict({'_id': {'$in': object_id_list}},\n                 **self._view_filter()))\n        result = list(result)\n        sorted_result = []\n        for object_id in object_id_list:\n            for object_map in result:\n                if object_map['_id'] == object_id:\n                    sorted_result.append(object_map)\n                    break\n        return objects.AssessmentOfferedList(sorted_result, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets an ``AssessmentOfferedList`` corresponding to the given ``IdList``.\n\n        In plenary mode, the returned list contains all of the\n        assessments specified in the ``Id`` list, in the order of the\n        list, including duplicates, or an error results if an ``Id`` in\n        the supplied list is not found or inaccessible. Otherwise,\n        inaccessible ``AssessmentOffered`` objects may be omitted from\n        the list and may present the elements in any order including\n        returning a unique set.\n\n        arg:    assessment_offered_ids (osid.id.IdList): the list of\n                ``Ids`` to retrieve\n        return: (osid.assessment.AssessmentOfferedList) - the returned\n                ``AssessmentOffered`` list\n        raise:  NotFound - an ``Id was`` not found\n        raise:  NullArgument - ``assessment_offered_ids`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - assessment failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def parse_slab_stats(slab_stats):\n    stats_dict = {'slabs': defaultdict(lambda: {})}\n    for line in slab_stats.splitlines():\n        if line == 'END':\n            break\n        cmd, key, value = line.split(' ')\n        if cmd != 'STAT':\n            continue\n        if \":\" not in key:\n            stats_dict[key] = int(value)\n            continue\n        slab, key = key.split(':')\n        stats_dict['slabs'][int(slab)][key] = int(value)\n    return stats_dict",
    "docstring": "Convert output from memcached's `stats slabs` into a Python dict.\n\n    Newlines are returned by memcached along with carriage returns\n    (i.e. '\\r\\n').\n\n    >>> parse_slab_stats(\n            \"STAT 1:chunk_size 96\\r\\nSTAT 1:chunks_per_page 10922\\r\\nSTAT \"\n            \"active_slabs 1\\r\\nSTAT total_malloced 1048512\\r\\nEND\\r\\n\")\n    {\n        'slabs': {\n            1: {\n                'chunk_size': 96,\n                'chunks_per_page': 10922,\n                # ...\n            },\n        },\n        'active_slabs': 1,\n        'total_malloced': 1048512,\n    }"
  },
  {
    "code": "def get_value(self, instance):\n        return instance.values.get(self.alias, self.default)",
    "docstring": "Get value for the current object instance\n\n        :param instance:\n        :return:"
  },
  {
    "code": "def CopyFromDateTimeString(self, time_string):\n    date_time_values = self._CopyDateTimeFromString(time_string)\n    year = date_time_values.get('year', 0)\n    month = date_time_values.get('month', 0)\n    day_of_month = date_time_values.get('day_of_month', 0)\n    hours = date_time_values.get('hours', 0)\n    minutes = date_time_values.get('minutes', 0)\n    seconds = date_time_values.get('seconds', 0)\n    self._normalized_timestamp = None\n    self._number_of_seconds = self._GetNumberOfSecondsFromElements(\n        year, month, day_of_month, hours, minutes, seconds)\n    self._microseconds = date_time_values.get('microseconds', None)\n    self.is_local_time = False",
    "docstring": "Copies a fake timestamp from a date and time string.\n\n    Args:\n      time_string (str): date and time value formatted as:\n          YYYY-MM-DD hh:mm:ss.######[+-]##:##\n\n          Where # are numeric digits ranging from 0 to 9 and the seconds\n          fraction can be either 3 or 6 digits. The time of day, seconds\n          fraction and time zone offset are optional. The default time zone\n          is UTC."
  },
  {
    "code": "def parse(self):\n        try:\n            self.parsed_data = json.loads(self.data)\n        except UnicodeError as e:\n            self.parsed_data = json.loads(self.data.decode('latin1'))\n        except Exception as e:\n            raise Exception('Error while converting response from JSON to python. %s' % e)\n        if self.parsed_data.get('type', '') != 'FeatureCollection':\n            raise Exception('GeoJson synchronizer expects a FeatureCollection object at root level')\n        self.parsed_data = self.parsed_data['features']",
    "docstring": "parse geojson and ensure is collection"
  },
  {
    "code": "def _convert_to_unicode(string):\n    codepoints = []\n    for character in string.split('-'):\n        if character in BLACKLIST_UNICODE:\n            next\n        codepoints.append(\n            '\\U{0:0>8}'.format(character).decode('unicode-escape')\n        )\n    return codepoints",
    "docstring": "This method should work with both Python 2 and 3 with the caveat\n    that they need to be compiled with wide unicode character support.\n\n    If there isn't wide unicode character support it'll blow up with a\n    warning."
  },
  {
    "code": "def printed_out(self, name):\n        opt = self.variables().optional_namestring()\n        req = self.variables().required_namestring()\n        out = ''\n        out += '|   |\\n'\n        out += '|   |---{}({}{})\\n'.format(name, req, opt)\n        if self.description:\n            out += '|   |       {}\\n'.format(self.description)\n        return out",
    "docstring": "Create a string representation of the action"
  },
  {
    "code": "def create_as(access_token, subscription_id, resource_group, as_name,\n              update_domains, fault_domains, location):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/resourceGroups/', resource_group,\n                        '/providers/Microsoft.Compute/availabilitySets/', as_name,\n                        '?api-version=', COMP_API])\n    as_body = {'location': location}\n    properties = {'platformUpdateDomainCount': update_domains}\n    properties['platformFaultDomainCount'] = fault_domains\n    as_body['properties'] = properties\n    body = json.dumps(as_body)\n    return do_put(endpoint, body, access_token)",
    "docstring": "Create availability set.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n        resource_group (str): Azure resource group name.\n        as_name (str): Name of the new availability set.\n        update_domains (int): Number of update domains.\n        fault_domains (int): Number of fault domains.\n        location (str): Azure data center location. E.g. westus.\n\n    Returns:\n        HTTP response. JSON body of the availability set properties."
  },
  {
    "code": "def data_filler_customer(self, number_of_rows, cursor, conn):\n        customer_data = []\n        try:\n            for i in range(0, number_of_rows):\n                customer_data.append((\n                    rnd_id_generator(self), self.faker.first_name(), self.faker.last_name(), self.faker.address(),\n                    self.faker.country(), self.faker.city(), self.faker.date(pattern=\"%d-%m-%Y\"),\n                    self.faker.date(pattern=\"%d-%m-%Y\"), self.faker.safe_email(), self.faker.phone_number(),\n                    self.faker.locale()))\n            customer_payload = (\"INSERT INTO customer \"\n                                \"(id, name, lastname, address, country, city, registry_date, birthdate, email, \"\n                                \"phone_number, locale)\"\n                                \"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\")\n            cursor.executemany(customer_payload, customer_data)\n            conn.commit()\n            logger.warning('detailed_registration Commits are successful after write job!', extra=extra_information)\n        except Exception as e:\n            logger.error(e, extra=extra_information)",
    "docstring": "creates and fills the table with customer"
  },
  {
    "code": "def get_notifications(self, start=None, stop=None, *args, **kwargs):\n        filter_kwargs = {}\n        if start is not None:\n            filter_kwargs['%s__gte' % self.notification_id_name] = start + 1\n        if stop is not None:\n            filter_kwargs['%s__lt' % self.notification_id_name] = stop + 1\n        objects = self.record_class.objects.filter(**filter_kwargs)\n        if hasattr(self.record_class, 'application_name'):\n            objects = objects.filter(application_name=self.application_name)\n        if hasattr(self.record_class, 'pipeline_id'):\n            objects = objects.filter(pipeline_id=self.pipeline_id)\n        objects = objects.order_by('%s' % self.notification_id_name)\n        return objects.all()",
    "docstring": "Returns all records in the table."
  },
  {
    "code": "def fingerprint_relaxation(T, p0, obs, tau=1, k=None, ncv=None):\n    r\n    T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric')\n    n = T.shape[0]\n    if not is_reversible(T):\n        raise ValueError('Fingerprint calculation is not supported for nonreversible transition matrices. ')\n    p0 = _types.ensure_ndarray(p0, ndim=1, size=n, kind='numeric')\n    obs = _types.ensure_ndarray(obs, ndim=1, size=n, kind='numeric')\n    if _issparse(T):\n        return sparse.fingerprints.fingerprint_relaxation(T, p0, obs, tau=tau, k=k, ncv=ncv)\n    else:\n        return dense.fingerprints.fingerprint_relaxation(T, p0, obs, tau=tau, k=k)",
    "docstring": "r\"\"\"Dynamical fingerprint for relaxation experiment.\n\n    The dynamical fingerprint is given by the implied time-scale\n    spectrum together with the corresponding amplitudes.\n\n    Parameters\n    ----------\n    T : (M, M) ndarray or scipy.sparse matrix\n        Transition matrix\n    obs1 : (M,) ndarray\n        Observable, represented as vector on state space\n    obs2 : (M,) ndarray (optional)\n        Second observable, for cross-correlations\n    k : int (optional)\n        Number of time-scales and amplitudes to compute\n    tau : int (optional)\n        Lag time of given transition matrix, for correct time-scales\n    ncv : int (optional)\n        The number of Lanczos vectors generated, `ncv` must be greater than k;\n        it is recommended that ncv > 2*k\n\n    Returns\n    -------\n    timescales : (N,) ndarray\n        Time-scales of the transition matrix\n    amplitudes : (N,) ndarray\n        Amplitudes for the relaxation experiment\n\n    See also\n    --------\n    relaxation, fingerprint_correlation\n\n    References\n    ----------\n    .. [1] Noe, F, S Doose, I Daidone, M Loellmann, M Sauer, J D\n        Chodera and J Smith. 2010. Dynamical fingerprints for probing\n        individual relaxation processes in biomolecular dynamics with\n        simulations and kinetic experiments. PNAS 108 (12): 4822-4827.\n\n    Notes\n    -----\n    Fingerprints are a combination of time-scale and amplitude spectrum for\n    a equilibrium correlation or a non-equilibrium relaxation experiment.\n\n    **Relaxation**\n\n    A relaxation experiment looks at the time dependent expectation\n    value of an observable for a system out of equilibrium\n\n    .. math:: \\mathbb{E}_{w_{0}}[a(x, t)]=\\sum_x w_0(x) a(x, t)=\\sum_x w_0(x) \\sum_y p^t(x, y) a(y).\n\n    The fingerprint amplitudes :math:`\\gamma_i` are given by\n\n    .. math:: \\gamma_i=\\langle w_0, r_i\\rangle \\langle l_i, a \\rangle.\n\n    And the fingerprint time scales :math:`t_i` are given by\n\n    .. math:: t_i=-\\frac{\\tau}{\\log \\lvert \\lambda_i \\rvert}.\n\n    Examples\n    --------\n\n    >>> import numpy as np\n    >>> from msmtools.analysis import fingerprint_relaxation\n\n    >>> T = np.array([[0.9, 0.1, 0.0], [0.5, 0.0, 0.5], [0.0, 0.1, 0.9]])\n    >>> p0 = np.array([1.0, 0.0, 0.0])\n    >>> a = np.array([1.0, 0.0, 0.0])\n    >>> ts, amp = fingerprint_relaxation(T, p0, a)\n\n    >>> ts\n    array([        inf,  9.49122158,  0.43429448])\n\n    >>> amp\n    array([ 0.45454545,  0.5       ,  0.04545455])"
  },
  {
    "code": "def get_block_from_consensus( self, consensus_hash ):\n        query = 'SELECT block_id FROM snapshots WHERE consensus_hash = ?;'\n        args = (consensus_hash,)\n        con = self.db_open(self.impl, self.working_dir)\n        rows = self.db_query_execute(con, query, args, verbose=False)\n        res = None\n        for r in rows:\n            res = r['block_id']\n        con.close()\n        return res",
    "docstring": "Get the block number with the given consensus hash.\n        Return None if there is no such block."
  },
  {
    "code": "def send_mass_template_mail(subject_template, body_template, recipients, context=None):\n    if context:\n        subject, body = render_mail_template(subject_template, body_template, context)\n    else:\n        subject, body = subject_template, body_template\n    message_tuples = [(subject, body, conf.get('DEFAULT_FROM_EMAIL'), [r]) for r in recipients]\n    send_mass_mail(message_tuples)",
    "docstring": "Renders an email subject and body using the given templates and context,\n    then sends it to the given recipients list.\n\n    The emails are send one-by-one."
  },
  {
    "code": "def bookmark_list():\n    client = get_client()\n    bookmark_iterator = client.bookmark_list()\n    def get_ep_name(item):\n        ep_id = item[\"endpoint_id\"]\n        try:\n            ep_doc = client.get_endpoint(ep_id)\n            return display_name_or_cname(ep_doc)\n        except TransferAPIError as err:\n            if err.code == \"EndpointDeleted\":\n                return \"[DELETED ENDPOINT]\"\n            else:\n                raise err\n    formatted_print(\n        bookmark_iterator,\n        fields=[\n            (\"Name\", \"name\"),\n            (\"Bookmark ID\", \"id\"),\n            (\"Endpoint ID\", \"endpoint_id\"),\n            (\"Endpoint Name\", get_ep_name),\n            (\"Path\", \"path\"),\n        ],\n        response_key=\"DATA\",\n        json_converter=iterable_response_to_dict,\n    )",
    "docstring": "Executor for `globus bookmark list`"
  },
  {
    "code": "def _load_audio_file(self):\n        self._step_begin(u\"load audio file\")\n        audio_file = AudioFile(\n            file_path=self.task.audio_file_path_absolute,\n            file_format=None,\n            rconf=self.rconf,\n            logger=self.logger\n        )\n        audio_file.read_samples_from_file()\n        self._step_end()\n        return audio_file",
    "docstring": "Load audio in memory.\n\n        :rtype: :class:`~aeneas.audiofile.AudioFile`"
  },
  {
    "code": "def save_method(elements, module_path):\n    for elem, signature in elements.items():\n        if isinstance(signature, dict):\n            save_method(signature, module_path + (elem,))\n        elif isinstance(signature, Class):\n            save_method(signature.fields, module_path + (elem,))\n        elif signature.ismethod():\n            if elem in methods and module_path[0] != '__dispatch__':\n                assert elem in MODULES['__dispatch__']\n                path = ('__dispatch__',)\n                methods[elem] = (path, MODULES['__dispatch__'][elem])\n            else:\n                methods[elem] = (module_path, signature)",
    "docstring": "Recursively save methods with module name and signature."
  },
  {
    "code": "def link(self):\n        if self.linked:\n            return self\n        self.linked = True\n        included_modules = []\n        for include in self.includes.values():\n            included_modules.append(include.link().surface)\n        self.scope.add_surface('__includes__', tuple(included_modules))\n        self.scope.add_surface('__thrift_source__', self.thrift_source)\n        for linker in LINKERS:\n            linker(self.scope).link()\n        self.scope.add_surface('loads', Deserializer(self.protocol))\n        self.scope.add_surface('dumps', Serializer(self.protocol))\n        return self",
    "docstring": "Link all the types in this module and all included modules."
  },
  {
    "code": "def _get(self, word1, word2):\n        key = self._WSEP.join([self._sanitize(word1), self._sanitize(word2)])\n        key = key.lower()\n        if key not in self._db:\n            return\n        return sample(self._db[key], 1)[0]",
    "docstring": "Return a possible next word after ``word1`` and ``word2``, or ``None``\n        if there's no possibility."
  },
  {
    "code": "def hue(self, hue):\n        if hue < 0 or hue > 1:\n            raise ValueError(\"Hue must be a percentage \"\n                             \"represented as decimal 0-1.0\")\n        self._hue = hue\n        cmd = self.command_set.hue(hue)\n        self.send(cmd)",
    "docstring": "Set the group hue.\n\n        :param hue: Hue in decimal percent (0.0-1.0)."
  },
  {
    "code": "def text(self, path, compression=None, lineSep=None):\n        self._set_opts(compression=compression, lineSep=lineSep)\n        self._jwrite.text(path)",
    "docstring": "Saves the content of the DataFrame in a text file at the specified path.\n        The text files will be encoded as UTF-8.\n\n        :param path: the path in any Hadoop supported file system\n        :param compression: compression codec to use when saving to file. This can be one of the\n                            known case-insensitive shorten names (none, bzip2, gzip, lz4,\n                            snappy and deflate).\n        :param lineSep: defines the line separator that should be used for writing. If None is\n                        set, it uses the default value, ``\\\\n``.\n\n        The DataFrame must have only one column that is of string type.\n        Each row becomes a new line in the output file."
  },
  {
    "code": "def render_context_with_title(self, context):\n        if \"page_title\" not in context:\n            con = template.Context(context)\n            temp = template.Template(encoding.force_text(self.page_title))\n            context[\"page_title\"] = temp.render(con)\n        return context",
    "docstring": "Render a page title and insert it into the context.\n\n        This function takes in a context dict and uses it to render the\n        page_title variable. It then appends this title to the context using\n        the 'page_title' key. If there is already a page_title key defined in\n        context received then this function will do nothing."
  },
  {
    "code": "def _generate_badge(self, subject, status):\n        url = 'https://img.shields.io/badge/%s-%s-brightgreen.svg' \\\n              '?style=flat&maxAge=3600' % (subject, status)\n        logger.debug(\"Getting badge for %s => %s (%s)\", subject, status, url)\n        res = requests.get(url)\n        if res.status_code != 200:\n            raise Exception(\"Error: got status %s for shields.io badge: %s\",\n                            res.status_code, res.text)\n        logger.debug('Got %d character response from shields.io', len(res.text))\n        return res.text",
    "docstring": "Generate SVG for one badge via shields.io.\n\n        :param subject: subject; left-hand side of badge\n        :type subject: str\n        :param status: status; right-hand side of badge\n        :type status: str\n        :return: badge SVG\n        :rtype: str"
  },
  {
    "code": "def handshake(self):\n        if self._socket is None:\n            self._socket = self._connect()\n        return self.call('handshake', {\"Version\": 1}, expect_body=False)",
    "docstring": "Sets up the connection with the Serf agent and does the\n        initial handshake."
  },
  {
    "code": "def get_repository_owner_and_name() -> Tuple[str, str]:\n    check_repo()\n    url = repo.remote('origin').url\n    parts = re.search(r'([^/:]+)/([^/]+).git$', url)\n    if not parts:\n        raise HvcsRepoParseError\n    debug('get_repository_owner_and_name', parts)\n    return parts.group(1), parts.group(2)",
    "docstring": "Checks the origin remote to get the owner and name of the remote repository.\n\n    :return: A tuple of the owner and name."
  },
  {
    "code": "def assert_is_instance(obj, cls, msg_fmt=\"{msg}\"):\n    if not isinstance(obj, cls):\n        msg = \"{!r} is an instance of {!r}, expected {!r}\".format(\n            obj, obj.__class__, cls\n        )\n        types = cls if isinstance(cls, tuple) else (cls,)\n        fail(msg_fmt.format(msg=msg, obj=obj, types=types))",
    "docstring": "Fail if an object is not an instance of a class or tuple of classes.\n\n    >>> assert_is_instance(5, int)\n    >>> assert_is_instance('foo', (str, bytes))\n    >>> assert_is_instance(5, str)\n    Traceback (most recent call last):\n        ...\n    AssertionError: 5 is an instance of <class 'int'>, expected <class 'str'>\n\n    The following msg_fmt arguments are supported:\n    * msg - the default error message\n    * obj - object to test\n    * types - tuple of types tested against"
  },
  {
    "code": "def add_service_port(service, port):\n    if service not in get_services(permanent=True):\n        raise CommandExecutionError('The service does not exist.')\n    cmd = '--permanent --service={0} --add-port={1}'.format(service, port)\n    return __firewall_cmd(cmd)",
    "docstring": "Add a new port to the specified service.\n\n    .. versionadded:: 2016.11.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' firewalld.add_service_port zone 80"
  },
  {
    "code": "def _remember_avatarness(\n            self, character, graph, node,\n            is_avatar=True, branch=None, turn=None,\n            tick=None\n    ):\n        branch = branch or self.branch\n        turn = turn or self.turn\n        tick = tick or self.tick\n        self._avatarness_cache.store(\n            character,\n            graph,\n            node,\n            branch,\n            turn,\n            tick,\n            is_avatar\n        )\n        self.query.avatar_set(\n            character,\n            graph,\n            node,\n            branch,\n            turn,\n            tick,\n            is_avatar\n        )",
    "docstring": "Use this to record a change in avatarness.\n\n        Should be called whenever a node that wasn't an avatar of a\n        character now is, and whenever a node that was an avatar of a\n        character now isn't.\n\n        ``character`` is the one using the node as an avatar,\n        ``graph`` is the character the node is in."
  },
  {
    "code": "def _check(self, file):\n        if not os.path.exists(file):\n            raise Error(\"file \\\"{}\\\" not found\".format(file))\n        _, extension = os.path.splitext(file)\n        try:\n            check = self.extension_map[extension[1:]]\n        except KeyError:\n            magic_type = magic.from_file(file)\n            for name, cls in self.magic_map.items():\n                if name in magic_type:\n                    check = cls\n                    break\n            else:\n                raise Error(\"unknown file type \\\"{}\\\", skipping...\".format(file))\n        try:\n            with open(file) as f:\n                code = \"\\n\".join(line.rstrip() for line in f)\n        except UnicodeDecodeError:\n            raise Error(\"file does not seem to contain text, skipping...\")\n        try:\n            if code[-1] != '\\n':\n                code += '\\n'\n        except IndexError:\n            pass\n        return check(code)",
    "docstring": "Run apropriate check based on `file`'s extension and return it,\n        otherwise raise an Error"
  },
  {
    "code": "def resource_to_url(resource, request=None, quote=False):\n    if request is None:\n        request = get_current_request()\n    reg = get_current_registry()\n    cnv = reg.getAdapter(request, IResourceUrlConverter)\n    return cnv.resource_to_url(resource, quote=quote)",
    "docstring": "Converts the given resource to a URL.\n\n    :param request: Request object (required for the host name part of the\n      URL). If this is not given, the current request is used.\n    :param bool quote: If set, the URL returned will be quoted."
  },
  {
    "code": "def compute_gas_limit_bounds(parent: BlockHeader) -> Tuple[int, int]:\n    boundary_range = parent.gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR\n    upper_bound = parent.gas_limit + boundary_range\n    lower_bound = max(GAS_LIMIT_MINIMUM, parent.gas_limit - boundary_range)\n    return lower_bound, upper_bound",
    "docstring": "Compute the boundaries for the block gas limit based on the parent block."
  },
  {
    "code": "def _search_indicators_page_generator(self, search_term=None,\n                                          enclave_ids=None,\n                                          from_time=None,\n                                          to_time=None,\n                                          indicator_types=None,\n                                          tags=None,\n                                          excluded_tags=None,\n                                          start_page=0,\n                                          page_size=None):\n        get_page = functools.partial(self.search_indicators_page, search_term, enclave_ids,\n                                     from_time, to_time, indicator_types, tags, excluded_tags)\n        return Page.get_page_generator(get_page, start_page, page_size)",
    "docstring": "Creates a generator from the |search_indicators_page| method that returns each successive page.\n\n        :param str search_term: The term to search for.  If empty, no search term will be applied.  Otherwise, must\n            be at least 3 characters.\n        :param list(str) enclave_ids: list of enclave ids used to restrict indicators to specific enclaves (optional - by\n            default indicators from all of user's enclaves are returned)\n        :param int from_time: start of time window in milliseconds since epoch (optional)\n        :param int to_time: end of time window in milliseconds since epoch (optional)\n        :param list(str) indicator_types: a list of indicator types to filter by (optional)\n        :param list(str) tags: Name (or list of names) of tag(s) to filter indicators by.  Only indicators containing\n            ALL of these tags will be returned. (optional)\n        :param list(str) excluded_tags: Indicators containing ANY of these tags will be excluded from the results.\n        :param int start_page: The page to start on.\n        :param page_size: The size of each page.\n        :return: The generator."
  },
  {
    "code": "def has_foreign_key(self, name):\n        name = self._normalize_identifier(name)\n        return name in self._fk_constraints",
    "docstring": "Returns whether this table has a foreign key constraint with the given name.\n\n        :param name: The constraint name\n        :type name: str\n\n        :rtype: bool"
  },
  {
    "code": "def cart_to_polar(arr_c):\n    if arr_c.shape[-1] == 1:\n        arr_p = arr_c.copy()\n    elif arr_c.shape[-1] == 2:\n        arr_p = np.empty_like(arr_c)\n        arr_p[..., 0] = vector_mag(arr_c)\n        arr_p[..., 1] = np.arctan2(arr_c[..., 1], arr_c[..., 0])\n    elif arr_c.shape[-1] == 3:\n        arr_p = np.empty_like(arr_c)\n        arr_p[..., 0] = vector_mag(arr_c)\n        arr_p[..., 1] = np.arccos(arr_c[..., 2] / arr_p[..., 0])\n        arr_p[..., 2] = np.arctan2(arr_c[..., 1], arr_c[..., 0])\n    else:\n        raise Exception('Invalid vector for polar representation')\n    return arr_p",
    "docstring": "Return cartesian vectors in their polar representation.\n\n    Parameters\n    ----------\n    arr_c: array, shape (a1, a2, ..., d)\n        Cartesian vectors, with last axis indexing the dimension.\n\n    Returns\n    -------\n    arr_p: array, shape of arr_c\n        Polar vectors, using (radius, inclination, azimuth) convention."
  },
  {
    "code": "def mock_decorator_with_params(*oargs, **okwargs):\n    def inner(fn, *iargs, **ikwargs):\n        if hasattr(fn, '__call__'):\n            return fn\n        return Mock()\n    return inner",
    "docstring": "Optionally mock a decorator that takes parameters\n\n    E.g.:\n\n    @blah(stuff=True)\n    def things():\n        pass"
  },
  {
    "code": "def first_return():\n\twalk = randwalk() >> drop(1) >> takewhile(lambda v: v != Origin) >> list\n\treturn len(walk)",
    "docstring": "Generate a random walk and return its length upto the moment\n\tthat the walker first returns to the origin.\n\n\tIt is mathematically provable that the walker will eventually return,\n\tmeaning that the function call will halt, although it may take\n\ta *very* long time and your computer may run out of memory!\n\tThus, try this interactively only."
  },
  {
    "code": "def clean(self):\n        if self.cleaners:\n            yield from asyncio.wait([x() for x in self.cleaners],\n                                    loop=self.loop)",
    "docstring": "Run all of the cleaners added by the user."
  },
  {
    "code": "def __set_token_expired(self, value):\n        self._token_expired = datetime.datetime.now() + datetime.timedelta(seconds=value)\n        return",
    "docstring": "Internal helper for oauth code"
  },
  {
    "code": "def fetch(self):\n        params = values.of({})\n        payload = self._version.fetch(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return AvailablePhoneNumberCountryInstance(\n            self._version,\n            payload,\n            account_sid=self._solution['account_sid'],\n            country_code=self._solution['country_code'],\n        )",
    "docstring": "Fetch a AvailablePhoneNumberCountryInstance\n\n        :returns: Fetched AvailablePhoneNumberCountryInstance\n        :rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryInstance"
  },
  {
    "code": "def NotEqualTo(self, value):\n    self._awql = self._CreateSingleValueCondition(value, '!=')\n    return self._query_builder",
    "docstring": "Sets the type of the WHERE clause as \"not equal to\".\n\n    Args:\n      value: The value to be used in the WHERE condition.\n\n    Returns:\n      The query builder that this WHERE builder links to."
  },
  {
    "code": "def merge(directory=None, revisions='', message=None, branch_label=None,\n          rev_id=None):\n    if alembic_version >= (0, 7, 0):\n        config = current_app.extensions['migrate'].migrate.get_config(\n            directory)\n        command.merge(config, revisions, message=message,\n                      branch_label=branch_label, rev_id=rev_id)\n    else:\n        raise RuntimeError('Alembic 0.7.0 or greater is required')",
    "docstring": "Merge two revisions together.  Creates a new migration file"
  },
  {
    "code": "def handle_os_exceptions():\n    try:\n        yield\n    except ObjectException:\n        exc_type, exc_value, _ = exc_info()\n        raise _OS_EXCEPTIONS.get(exc_type, OSError)(exc_value)\n    except (OSError, same_file_error, UnsupportedOperation):\n        raise\n    except Exception:\n        exc_type, exc_value, _ = exc_info()\n        raise OSError('%s%s' % (\n            exc_type, (', %s' % exc_value) if exc_value else ''))",
    "docstring": "Handles pycosio exceptions and raise standard OS exceptions."
  },
  {
    "code": "def deep_del(data, fn):\n    result = {}\n    for k, v in data.iteritems():\n        if not fn(v):\n            if isinstance(v, dict):\n                result[k] = deep_del(v, fn)\n            else:\n                result[k] = v\n    return result",
    "docstring": "Create dict copy with removed items.\n\n    Recursively remove items where fn(value) is True.\n\n    Returns:\n        dict: New dict with matching items removed."
  },
  {
    "code": "def get_search_scores(query, choices, ignore_case=True, template='{}',\n                      valid_only=False, sort=False):\n    query = query.replace(' ', '')\n    pattern = get_search_regex(query, ignore_case)\n    results = []\n    for choice in choices:\n        r = re.search(pattern, choice)\n        if query and r:\n            result = get_search_score(query, choice, ignore_case=ignore_case,\n                                      apply_regex=False, template=template)\n        else:\n            if query:\n                result = (choice, choice, NOT_FOUND_SCORE)\n            else:\n                result = (choice, choice, NO_SCORE)\n        if valid_only:\n            if result[-1] != NOT_FOUND_SCORE:\n                results.append(result)\n        else:\n            results.append(result)\n    if sort:\n        results = sorted(results, key=lambda row: row[-1])\n    return results",
    "docstring": "Search for query inside choices and return a list of tuples.\n\n    Returns a list of tuples of text with the enriched text (if a template is\n    provided) and a score for the match. Lower scores imply a better match.\n\n    Parameters\n    ----------\n    query : str\n        String with letters to search in each choice (in order of appearance).\n    choices : list of str\n        List of sentences/words in which to search for the 'query' letters.\n    ignore_case : bool, optional\n        Optional value perform a case insensitive search (True by default).\n    template : str, optional\n        Optional template string to surround letters found in choices. This is\n        useful when using a rich text editor ('{}' by default).\n        Examples: '<b>{}</b>', '<code>{}</code>', '<i>{}</i>'\n\n    Returns\n    -------\n    results : list of tuples\n        List of tuples where the first item is the text (enriched if a\n        template was used) and a search score. Lower scores means better match."
  },
  {
    "code": "def prepare_inputseries(self, ramflag: bool = True) -> None:\n        for element in printtools.progressbar(self):\n            element.prepare_inputseries(ramflag)",
    "docstring": "Call method |Element.prepare_inputseries| of all handled\n        |Element| objects."
  },
  {
    "code": "def data_in_label(intvl_in, dtype_in_time, dtype_in_vert=False):\n    intvl_lbl = intvl_in\n    time_lbl = dtype_in_time\n    lbl = '_'.join(['from', intvl_lbl, time_lbl]).replace('__', '_')\n    vert_lbl = dtype_in_vert if dtype_in_vert else False\n    if vert_lbl:\n        lbl = '_'.join([lbl, vert_lbl]).replace('__', '_')\n    return lbl",
    "docstring": "Create string label specifying the input data of a calculation."
  },
  {
    "code": "def crypto_secretstream_xchacha20poly1305_init_push(state, key):\n    ensure(\n        isinstance(state, crypto_secretstream_xchacha20poly1305_state),\n        'State must be a crypto_secretstream_xchacha20poly1305_state object',\n        raising=exc.TypeError,\n    )\n    ensure(\n        isinstance(key, bytes),\n        'Key must be a bytes sequence',\n        raising=exc.TypeError,\n    )\n    ensure(\n        len(key) == crypto_secretstream_xchacha20poly1305_KEYBYTES,\n        'Invalid key length',\n        raising=exc.ValueError,\n    )\n    headerbuf = ffi.new(\n        \"unsigned char []\",\n        crypto_secretstream_xchacha20poly1305_HEADERBYTES,\n    )\n    rc = lib.crypto_secretstream_xchacha20poly1305_init_push(\n        state.statebuf, headerbuf, key)\n    ensure(rc == 0, 'Unexpected failure', raising=exc.RuntimeError)\n    return ffi.buffer(headerbuf)[:]",
    "docstring": "Initialize a crypto_secretstream_xchacha20poly1305 encryption buffer.\n\n    :param state: a secretstream state object\n    :type state: crypto_secretstream_xchacha20poly1305_state\n    :param key: must be\n                :data:`.crypto_secretstream_xchacha20poly1305_KEYBYTES` long\n    :type key: bytes\n    :return: header\n    :rtype: bytes"
  },
  {
    "code": "def get_forwarding_information_base(self, filter=''):\n        uri = \"{}{}\".format(self.data[\"uri\"], self.FORWARDING_INFORMATION_PATH)\n        return self._helper.get_collection(uri, filter=filter)",
    "docstring": "Gets the forwarding information base data for a logical interconnect. A maximum of 100 entries is returned.\n        Optional filtering criteria might be specified.\n\n        Args:\n            filter (list or str):\n                Filtering criteria may be specified using supported attributes: interconnectUri, macAddress,\n                internalVlan, externalVlan, and supported relation = (Equals). macAddress is 12 hexadecimal digits with\n                a colon between each pair of digits (upper case or lower case).\n                The default is no filter; all resources are returned.\n\n        Returns:\n            list: A set of interconnect MAC address entries."
  },
  {
    "code": "def is_installable_dir(path):\n    if not os.path.isdir(path):\n        return False\n    setup_py = os.path.join(path, \"setup.py\")\n    if os.path.isfile(setup_py):\n        return True\n    return False",
    "docstring": "Return True if `path` is a directory containing a setup.py file."
  },
  {
    "code": "def fixed_indexer(self):\n        isfixed = self.pst.parameter_data.partrans.\\\n            apply(lambda x : x in [\"fixed\",\"tied\"])\n        return isfixed.values",
    "docstring": "indexer for fixed status\n\n        Returns\n        -------\n        fixed_indexer : pandas.Series"
  },
  {
    "code": "def scan(cls, path):\n        result = []\n        try:\n            for _p in listdir(path):\n                try:\n                    result.append(Template(_p, op.join(path, _p)))\n                except ValueError:\n                    continue\n        except OSError:\n            pass\n        return result",
    "docstring": "Scan directory for templates."
  },
  {
    "code": "def _generate_sequences_for_texts(self, l1, t1, l2, t2, ngrams):\n        self._reverse_substitutes = dict((v, k) for k, v in\n                                         self._substitutes.items())\n        sequences = []\n        covered_spans = [[], []]\n        for ngram in ngrams:\n            sequences.extend(self._generate_sequences_for_ngram(\n                t1, t2, ngram, covered_spans))\n        if sequences:\n            sequences.sort(key=lambda x: x.start_index)\n            context = {'l1': l1, 'l2': l2, 'sequences': sequences}\n            report_name = '{}-{}.html'.format(l1, l2)\n            os.makedirs(self._output_dir, exist_ok=True)\n            self._write(context, self._output_dir, report_name)",
    "docstring": "Generates and outputs aligned sequences for the texts `t1` and `t2`\n        from `ngrams`.\n\n        :param l1: label of first witness\n        :type l1: `str`\n        :param t1: text content of first witness\n        :type t1: `str`\n        :param l2: label of second witness\n        :type l2: `str`\n        :param t2: text content of second witness\n        :type t2: `str`\n        :param ngrams: n-grams to base sequences on\n        :type ngrams: `list` of `str`"
  },
  {
    "code": "def kill_processes(self):\n        LOGGER.critical('Max shutdown exceeded, forcibly exiting')\n        processes = self.active_processes(False)\n        while processes:\n            for proc in self.active_processes(False):\n                if int(proc.pid) != int(os.getpid()):\n                    LOGGER.warning('Killing %s (%s)', proc.name, proc.pid)\n                    try:\n                        os.kill(int(proc.pid), signal.SIGKILL)\n                    except OSError:\n                        pass\n                else:\n                    LOGGER.warning('Cowardly refusing kill self (%s, %s)',\n                                   proc.pid, os.getpid())\n            time.sleep(0.5)\n            processes = self.active_processes(False)\n        LOGGER.info('Killed all children')\n        return self.set_state(self.STATE_STOPPED)",
    "docstring": "Gets called on shutdown by the timer when too much time has gone by,\n        calling the terminate method instead of nicely asking for the consumers\n        to stop."
  },
  {
    "code": "def checkout_with_fetch(git_folder, refspec, repository=\"origin\"):\n    _LOGGER.info(\"Trying to fetch and checkout %s\", refspec)\n    repo = Repo(str(git_folder))\n    repo.git.fetch(repository, refspec)\n    repo.git.checkout(\"FETCH_HEAD\")\n    _LOGGER.info(\"Fetch and checkout success for %s\", refspec)",
    "docstring": "Fetch the refspec, and checkout FETCH_HEAD.\n    Beware that you will ne in detached head mode."
  },
  {
    "code": "def xyz(self, arrnx3):\n        if not self.children:\n            if not arrnx3.shape[0] == 1:\n                raise ValueError(\n                    'Trying to set position of {} with more than one'\n                    'coordinate: {}'.format(\n                        self, arrnx3))\n            self.pos = np.squeeze(arrnx3)\n        else:\n            for atom, coords in zip(\n                self._particles(\n                    include_ports=False), arrnx3):\n                atom.pos = coords",
    "docstring": "Set the positions of the particles in the Compound, excluding the Ports.\n\n        This function does not set the position of the ports.\n\n        Parameters\n        ----------\n        arrnx3 : np.ndarray, shape=(n,3), dtype=float\n            The new particle positions"
  },
  {
    "code": "def get_formats(function_types=None):\n    if function_types is None:\n        return {k: v['display'] for k, v in _converter_map.items()}\n    ftypes = [x.lower() for x in function_types]\n    ftypes = set(ftypes)\n    ret = []\n    for fmt, v in _converter_map.items():\n        if v['valid'] is None or ftypes <= v['valid']:\n            ret.append(fmt)\n    return ret",
    "docstring": "Returns the available formats mapped to display name.\n\n    This is returned as an ordered dictionary, with the most common\n    at the top, followed by the rest in alphabetical order\n\n    If a list is specified for function_types, only those formats\n    supporting the given function types will be returned."
  },
  {
    "code": "def extract_original_links(base_url, bs4):\n    valid_url = convert_invalid_url(base_url)\n    url = urlparse(valid_url)\n    base_url = '{}://{}'.format(url.scheme, url.netloc)\n    base_url_with_www = '{}://www.{}'.format(url.scheme, url.netloc)\n    links = extract_links(bs4)\n    result_links = [anchor for anchor in links if anchor.startswith(base_url)]\n    result_links_www = [anchor for anchor in links if anchor.startswith(base_url_with_www)]\n    return list(set(result_links + result_links_www))",
    "docstring": "Extracting links that contains specific url from BeautifulSoup object\n\n    :param base_url: `str` specific url that matched with the links\n    :param bs4: `BeautifulSoup`\n    :return: `list` List of links"
  },
  {
    "code": "def remove(self, priority, observer, callble):\n        self.flush()\n        for i in range(len(self) - 1, -1, -1):\n            p,o,c = self[i]\n            if priority==p and observer==o and callble==c:\n                del self._poc[i]",
    "docstring": "Remove one observer, which had priority and callble."
  },
  {
    "code": "def GetAccounts(self):\n    selector = {\n        'fields': ['CustomerId', 'CanManageClients']\n    }\n    accounts = self.client.GetService('ManagedCustomerService').get(selector)\n    return accounts['entries']",
    "docstring": "Return the client accounts associated with the user's manager account.\n\n    Returns:\n      list List of ManagedCustomer data objects."
  },
  {
    "code": "def send_ether_over_wpa(self, pkt, **kwargs):\n        payload = LLC() / SNAP() / pkt[Ether].payload\n        dest = pkt.dst\n        if dest == \"ff:ff:ff:ff:ff:ff\":\n            self.send_wpa_to_group(payload, dest)\n        else:\n            assert dest == self.client\n            self.send_wpa_to_client(payload)",
    "docstring": "Send an Ethernet packet using the WPA channel\n        Extra arguments will be ignored, and are just left for compatibility"
  },
  {
    "code": "def add(self, pattern, start):\n        \"Recursively adds a linear pattern to the AC automaton\"\n        if not pattern:\n            return [start]\n        if isinstance(pattern[0], tuple):\n            match_nodes = []\n            for alternative in pattern[0]:\n                end_nodes = self.add(alternative, start=start)\n                for end in end_nodes:\n                    match_nodes.extend(self.add(pattern[1:], end))\n            return match_nodes\n        else:\n            if pattern[0] not in start.transition_table:\n                next_node = BMNode()\n                start.transition_table[pattern[0]] = next_node\n            else:\n                next_node = start.transition_table[pattern[0]]\n            if pattern[1:]:\n                end_nodes = self.add(pattern[1:], start=next_node)\n            else:\n                end_nodes = [next_node]\n            return end_nodes",
    "docstring": "Recursively adds a linear pattern to the AC automaton"
  },
  {
    "code": "def identical(self, o):\n        return self.bits == o.bits and self.stride == o.stride and self.lower_bound == o.lower_bound and self.upper_bound == o.upper_bound",
    "docstring": "Used to make exact comparisons between two StridedIntervals. Usually it is only used in test cases.\n\n        :param o: The other StridedInterval to compare with.\n        :return: True if they are exactly same, False otherwise."
  },
  {
    "code": "def connect_output(self, node):\n        if len(self.outputs) == self.max_outputs:\n            raise TooManyOutputsError(\"Attempted to connect too many nodes to the output of a node\", max_outputs=self.max_outputs, stream=self.stream)\n        self.outputs.append(node)",
    "docstring": "Connect another node to our output.\n\n        This downstream node will automatically be triggered when we update\n        our output.\n\n        Args:\n            node (SGNode): The node that should receive our output"
  },
  {
    "code": "def full_load(self):\n        self.parse_data_directories()\n        class RichHeader(object):\n            pass\n        rich_header = self.parse_rich_header()\n        if rich_header:\n            self.RICH_HEADER = RichHeader()\n            self.RICH_HEADER.checksum = rich_header.get('checksum', None)\n            self.RICH_HEADER.values = rich_header.get('values', None)\n            self.RICH_HEADER.key = rich_header.get('key', None)\n            self.RICH_HEADER.raw_data = rich_header.get('raw_data', None)\n            self.RICH_HEADER.clear_data = rich_header.get('clear_data', None)\n        else:\n            self.RICH_HEADER = None",
    "docstring": "Process the data directories.\n\n        This method will load the data directories which might not have\n        been loaded if the \"fast_load\" option was used."
  },
  {
    "code": "def is_scalar(value: Any) -> bool:\n    return (\n        getattr(value, 'ndim', None) == 0 or\n        isinstance(value, (str, bytes)) or not\n        isinstance(value, (Iterable, ) + dask_array_type))",
    "docstring": "Whether to treat a value as a scalar.\n\n    Any non-iterable, string, or 0-D array"
  },
  {
    "code": "def add(self, element):\n        if not isinstance(element, six.string_types):\n            raise TypeError(\"Hll elements can only be strings\")\n        self._adds.add(element)",
    "docstring": "Adds an element to the HyperLogLog. Datatype cardinality will\n        be updated when the object is saved.\n\n        :param element: the element to add\n        :type element: str"
  },
  {
    "code": "def remove_zero_points(self):\n        points_of_interest = np.where((np.linalg.norm(self.point_cloud.data, axis=0) != 0.0)  &\n                                      (np.linalg.norm(self.normal_cloud.data, axis=0) != 0.0) &\n                                      (np.isfinite(self.normal_cloud.data[0,:])))[0]\n        self.point_cloud._data = self.point_cloud.data[:, points_of_interest]\n        self.normal_cloud._data = self.normal_cloud.data[:, points_of_interest]",
    "docstring": "Remove all elements where the norms and points are zero.\n\n        Note\n        ----\n        This returns nothing and updates the NormalCloud in-place."
  },
  {
    "code": "def create(cls, name, md5_password=None, connect_retry=120,\n               session_hold_timer=180, session_keep_alive=60):\n        json = {'name': name,\n                'connect': connect_retry,\n                'session_hold_timer': session_hold_timer,\n                'session_keep_alive': session_keep_alive}\n        if md5_password:\n            json.update(md5_password=md5_password)\n        return ElementCreator(cls, json)",
    "docstring": "Create a new BGP Connection Profile.\n\n        :param str name: name of profile\n        :param str md5_password: optional md5 password\n        :param int connect_retry: The connect retry timer, in seconds\n        :param int session_hold_timer: The session hold timer, in seconds\n        :param int session_keep_alive: The session keep alive timer, in seconds\n        :raises CreateElementFailed: failed creating profile\n        :return: instance with meta\n        :rtype: BGPConnectionProfile"
  },
  {
    "code": "def events(cls, filters):\n        current = filters.pop('current', False)\n        current_params = []\n        if current:\n            current_params = [('current', 'true')]\n        filter_url = uparse.urlencode(sorted(list(filters.items())) + current_params)\n        events = cls.json_get('%s/events?%s' % (cls.api_url, filter_url),\n                              empty_key=True, send_key=False)\n        return events",
    "docstring": "Retrieve events details from status.gandi.net."
  },
  {
    "code": "def runTemplate(id, data={}):\n        conn = Qubole.agent()\n        path = str(id) + \"/run\"\n        res = conn.post(Template.element_path(path), data)\n        cmdType = res['command_type']\n        cmdId = res['id']\n        cmdClass = eval(cmdType)\n        cmd = cmdClass.find(cmdId)\n        while not Command.is_done(cmd.status):\n            time.sleep(Qubole.poll_interval)\n            cmd = cmdClass.find(cmd.id)\n        return Template.getResult(cmdClass, cmd)",
    "docstring": "Run an existing Template and waits for the Result.\n        Prints result to stdout. \n\n        Args:\n            `id`: ID of the template to run\n            `data`: json data containing the input_vars\n        \n        Returns:  \n            An integer as status (0: success, 1: failure)"
  },
  {
    "code": "def _replace_property(property_key, property_value, resource, logical_id):\n        if property_key and property_value:\n            resource.get(PROPERTIES_KEY, {})[property_key] = property_value\n        elif property_key or property_value:\n            LOG.info(\"WARNING: Ignoring Metadata for Resource %s. Metadata contains only aws:asset:path or \"\n                     \"aws:assert:property but not both\", logical_id)",
    "docstring": "Replace a property with an asset on a given resource\n\n        This method will mutate the template\n\n        Parameters\n        ----------\n        property str\n            The property to replace on the resource\n        property_value str\n            The new value of the property\n        resource dict\n            Dictionary representing the Resource to change\n        logical_id str\n            LogicalId of the Resource"
  },
  {
    "code": "def define_log_renderer(fmt, fpath, quiet):\n    if fmt:\n        return structlog.processors.JSONRenderer()\n    if fpath is not None:\n        return structlog.processors.JSONRenderer()\n    if sys.stderr.isatty() and not quiet:\n        return structlog.dev.ConsoleRenderer()\n    return structlog.processors.JSONRenderer()",
    "docstring": "the final log processor that structlog requires to render."
  },
  {
    "code": "def run_task(factory, **kwargs):\n    context = TaskContext(factory, **kwargs)\n    pstats_dir = kwargs.get(\"pstats_dir\", os.getenv(PSTATS_DIR))\n    if pstats_dir:\n        import cProfile\n        import tempfile\n        import pydoop.hdfs as hdfs\n        hdfs.mkdir(pstats_dir)\n        fd, pstats_fn = tempfile.mkstemp(suffix=\".pstats\")\n        os.close(fd)\n        cProfile.runctx(\n            \"_run(context, **kwargs)\", globals(), locals(),\n            filename=pstats_fn\n        )\n        pstats_fmt = kwargs.get(\n            \"pstats_fmt\",\n            os.getenv(PSTATS_FMT, DEFAULT_PSTATS_FMT)\n        )\n        name = pstats_fmt % (\n            context.task_type,\n            context.get_task_partition(),\n            os.path.basename(pstats_fn)\n        )\n        hdfs.put(pstats_fn, hdfs.path.join(pstats_dir, name))\n    else:\n        _run(context, **kwargs)",
    "docstring": "\\\n    Run a MapReduce task.\n\n    Available keyword arguments:\n\n    * ``raw_keys`` (default: :obj:`False`): pass map input keys to context\n      as byte strings (ignore any type information)\n    * ``raw_values`` (default: :obj:`False`): pass map input values to context\n      as byte strings (ignore any type information)\n    * ``private_encoding`` (default: :obj:`True`): automatically serialize map\n      output k/v and deserialize reduce input k/v (pickle)\n    * ``auto_serialize`` (default: :obj:`True`): automatically serialize reduce\n      output (map output in map-only jobs) k/v (call str/unicode then encode as\n      utf-8)\n\n    Advanced keyword arguments:\n\n    * ``pstats_dir``: run the task with cProfile and store stats in this dir\n    * ``pstats_fmt``: use this pattern for pstats filenames (experts only)\n\n    The pstats dir and filename pattern can also be provided via ``pydoop\n    submit`` arguments, with lower precedence in case of clashes."
  },
  {
    "code": "def run_strelka(job, tumor_bam, normal_bam, univ_options, strelka_options, split=True):\n    if strelka_options['chromosomes']:\n        chromosomes = strelka_options['chromosomes']\n    else:\n        chromosomes = sample_chromosomes(job, strelka_options['genome_fai'])\n    num_cores = min(len(chromosomes), univ_options['max_cores'])\n    strelka = job.wrapJobFn(run_strelka_full, tumor_bam, normal_bam, univ_options,\n                            strelka_options,\n                            disk=PromisedRequirement(strelka_disk,\n                                                     tumor_bam['tumor_dna_fix_pg_sorted.bam'],\n                                                     normal_bam['normal_dna_fix_pg_sorted.bam'],\n                                                     strelka_options['genome_fasta']),\n                            memory='6G',\n                            cores=num_cores)\n    job.addChild(strelka)\n    if split:\n        unmerge_strelka = job.wrapJobFn(wrap_unmerge, strelka.rv(), chromosomes, strelka_options,\n                                        univ_options).encapsulate()\n        strelka.addChild(unmerge_strelka)\n        return unmerge_strelka.rv()\n    else:\n        return strelka.rv()",
    "docstring": "Run the strelka subgraph on the DNA bams.  Optionally split the results into per-chromosome\n    vcfs.\n\n    :param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq\n    :param dict normal_bam: Dict of bam and bai for normal DNA-Seq\n    :param dict univ_options: Dict of universal options used by almost all tools\n    :param dict strelka_options: Options specific to strelka\n    :param bool split: Should the results be split into perchrom vcfs?\n    :return: Either the fsID to the genome-level vcf or a dict of results from running strelka\n             on every chromosome\n             perchrom_strelka:\n                 |- 'chr1':\n                 |      |-'snvs': fsID\n                 |      +-'indels': fsID\n                 |- 'chr2':\n                 |      |-'snvs': fsID\n                 |      +-'indels': fsID\n                 |-...\n                 |\n                 +- 'chrM':\n                        |-'snvs': fsID\n                        +-'indels': fsID\n    :rtype: toil.fileStore.FileID|dict"
  },
  {
    "code": "def _to_str(dumped_val, encoding='utf-8', ordered=True):\n    _dict = OrderedDict if ordered else dict\n    if isinstance(dumped_val, dict):\n        return OrderedDict((k, _to_str(v, encoding)) for k,v in dumped_val.items())\n    elif isinstance(dumped_val, (list, tuple)):\n        return [_to_str(v, encoding) for v in dumped_val]\n    elif isinstance(dumped_val, bytes):\n        try:\n            d = dumped_val.decode('utf-8')\n        except Exception:\n            d = repr(dumped_val)\n        return d\n    else:\n        return dumped_val",
    "docstring": "Convert bytes in a dump value to str, allowing json encode"
  },
  {
    "code": "def _check_psutil(self, instance):\n        custom_tags = instance.get('tags', [])\n        if self._collect_cx_state:\n            self._cx_state_psutil(tags=custom_tags)\n        self._cx_counters_psutil(tags=custom_tags)",
    "docstring": "Gather metrics about connections states and interfaces counters\n        using psutil facilities"
  },
  {
    "code": "def set_primary_parameters(self, **kwargs):\n        given = sorted(kwargs.keys())\n        required = sorted(self._PRIMARY_PARAMETERS)\n        if given == required:\n            for (key, value) in kwargs.items():\n                setattr(self, key, value)\n        else:\n            raise ValueError(\n                'When passing primary parameter values as initialization '\n                'arguments of the instantaneous unit hydrograph class `%s`, '\n                'or when using method `set_primary_parameters, one has to '\n                'to define all values at once via keyword arguments.  '\n                'But instead of the primary parameter names `%s` the '\n                'following keywords were given: %s.'\n                % (objecttools.classname(self),\n                   ', '.join(required), ', '.join(given)))",
    "docstring": "Set all primary parameters at once."
  },
  {
    "code": "def encode_chain_list(in_strings):\n    out_bytes = b\"\"\n    for in_s in in_strings:\n        out_bytes+=in_s.encode('ascii')\n        for i in range(mmtf.utils.constants.CHAIN_LEN -len(in_s)):\n            out_bytes+= mmtf.utils.constants.NULL_BYTE.encode('ascii')\n    return out_bytes",
    "docstring": "Convert a list of strings to a list of byte arrays.\n\n    :param in_strings: the input strings\n    :return the encoded list of byte arrays"
  },
  {
    "code": "def function(self, addr=None, name=None, create=False, syscall=False, plt=None):\n        if addr is not None:\n            try:\n                f = self._function_map.get(addr)\n                if plt is None or f.is_plt == plt:\n                    return f\n            except KeyError:\n                if create:\n                    f = self._function_map[addr]\n                    if name is not None:\n                        f.name = name\n                    if syscall:\n                        f.is_syscall=True\n                    return f\n        elif name is not None:\n            for func in self._function_map.values():\n                if func.name == name:\n                    if plt is None or func.is_plt == plt:\n                        return func\n        return None",
    "docstring": "Get a function object from the function manager.\n\n        Pass either `addr` or `name` with the appropriate values.\n\n        :param int addr: Address of the function.\n        :param str name: Name of the function.\n        :param bool create: Whether to create the function or not if the function does not exist.\n        :param bool syscall: True to create the function as a syscall, False otherwise.\n        :param bool or None plt: True to find the PLT stub, False to find a non-PLT stub, None to disable this\n                                 restriction.\n        :return: The Function instance, or None if the function is not found and create is False.\n        :rtype: Function or None"
  },
  {
    "code": "def process_global(name, val=None, setval=False):\n    p = current_process()\n    if not hasattr(p, '_pulsar_globals'):\n        p._pulsar_globals = {'lock': Lock()}\n    if setval:\n        p._pulsar_globals[name] = val\n    else:\n        return p._pulsar_globals.get(name)",
    "docstring": "Access and set global variables for the current process."
  },
  {
    "code": "def retire_asset_ddo(self, did):\n        response = self.requests_session.delete(f'{self.url}/{did}', headers=self._headers)\n        if response.status_code == 200:\n            logging.debug(f'Removed asset DID: {did} from metadata store')\n            return response\n        raise AquariusGenericError(f'Unable to remove DID: {response}')",
    "docstring": "Retire asset ddo of Aquarius.\n\n        :param did: Asset DID string\n        :return: API response (depends on implementation)"
  },
  {
    "code": "def check_server_running(pid):\n    if pid == os.getpid():\n        return False\n    try:\n        os.kill(pid, 0)\n        return True\n    except OSError as oe:\n        if oe.errno == errno.ESRCH:\n            return False\n        else:\n            raise",
    "docstring": "Determine if the given process is running"
  },
  {
    "code": "def info(msg, *args, **kw):\n    if len(args) or len(kw):\n        msg = msg.format(*args, **kw)\n    shell.cprint('-- <32>{}<0>'.format(msg))",
    "docstring": "Print sys message to stdout.\n\n    System messages should inform about the flow of the script. This should\n    be a major milestones during the build."
  },
  {
    "code": "def _AppendRecord(self):\n    if not self.values:\n      return\n    cur_record = []\n    for value in self.values:\n      try:\n        value.OnSaveRecord()\n      except SkipRecord:\n        self._ClearRecord()\n        return\n      except SkipValue:\n        continue\n      cur_record.append(value.value)\n    if len(cur_record) == (cur_record.count(None) + cur_record.count([])):\n      return\n    while None in cur_record:\n      cur_record[cur_record.index(None)] = ''\n    self._result.append(cur_record)\n    self._ClearRecord()",
    "docstring": "Adds current record to result if well formed."
  },
  {
    "code": "def register_serialization_method(self, name, serialize_func):\n        if name in self._default_serialization_methods:\n            raise ValueError(\"Can't replace original %s serialization method\")\n        self._serialization_methods[name] = serialize_func",
    "docstring": "Register a custom serialization method that can be\n        used via schema configuration"
  },
  {
    "code": "def loads(string, filename=None, includedir=''):\n    try:\n        f = io.StringIO(string)\n    except TypeError:\n        raise TypeError(\"libconf.loads() input string must by unicode\")\n    return load(f, filename=filename, includedir=includedir)",
    "docstring": "Load the contents of ``string`` to a Python object\n\n    The returned object is a subclass of ``dict`` that exposes string keys as\n    attributes as well.\n\n    Example:\n\n        >>> config = libconf.loads('window: { title: \"libconfig example\"; };')\n        >>> config['window']['title']\n        'libconfig example'\n        >>> config.window.title\n        'libconfig example'"
  },
  {
    "code": "def get_mmax(self, mfd_conf, msr, rake, area):\n        if mfd_conf['Maximum_Magnitude']:\n            self.mmax = mfd_conf['Maximum_Magnitude']\n        else:\n            self.mmax = msr.get_median_mag(area, rake)\n        if ('Maximum_Magnitude_Uncertainty' in mfd_conf and\n                mfd_conf['Maximum_Magnitude_Uncertainty']):\n            self.mmax_sigma = mfd_conf['Maximum_Magnitude_Uncertainty']\n        else:\n            self.mmax_sigma = msr.get_std_dev_mag(rake)",
    "docstring": "Gets the mmax for the fault - reading directly from the config file\n        or using the msr otherwise\n\n        :param dict mfd_config:\n            Configuration file (see setUp for paramters)\n\n        :param msr:\n            Instance of :class:`nhlib.scalerel`\n\n        :param float rake:\n            Rake of the fault (in range -180 to 180)\n\n        :param float area:\n            Area of the fault surface (km^2)"
  },
  {
    "code": "def profile(model_specification, results_directory, process):\n    model_specification = Path(model_specification)\n    results_directory = Path(results_directory)\n    out_stats_file = results_directory / f'{model_specification.name}'.replace('yaml', 'stats')\n    command = f'run_simulation(\"{model_specification}\", \"{results_directory}\")'\n    cProfile.runctx(command, globals=globals(), locals=locals(), filename=out_stats_file)\n    if process:\n        out_txt_file = results_directory / (out_stats_file.name + '.txt')\n        with open(out_txt_file, 'w') as f:\n            p = pstats.Stats(str(out_stats_file), stream=f)\n            p.sort_stats('cumulative')\n            p.print_stats()",
    "docstring": "Run a simulation based on the provided MODEL_SPECIFICATION and profile\n    the run."
  },
  {
    "code": "def count(self, q):\n        q = \"SELECT COUNT(*) %s\"%q\n        return int(self.quick(q).split(\"\\n\")[1])",
    "docstring": "Shorthand for counting the results of a specific query.\n\n        ## Arguments\n\n        * `q` (str): The query to count. This will be executed as:\n          `\"SELECT COUNT(*) %s\" % q`.\n\n        ## Returns\n\n        * `count` (int): The resulting count."
  },
  {
    "code": "def as_fs(self):\n        fs = []\n        fs.append(\"cpe:2.3:\")\n        for i in range(0, len(CPEComponent.ordered_comp_parts)):\n            ck = CPEComponent.ordered_comp_parts[i]\n            lc = self._get_attribute_components(ck)\n            if len(lc) > 1:\n                errmsg = \"Incompatible version {0} with formatted string\".format(\n                    self.VERSION)\n                raise TypeError(errmsg)\n            else:\n                comp = lc[0]\n                if (isinstance(comp, CPEComponentUndefined) or\n                   isinstance(comp, CPEComponentEmpty) or\n                   isinstance(comp, CPEComponentAnyValue)):\n                    v = CPEComponent2_3_FS.VALUE_ANY\n                elif isinstance(comp, CPEComponentNotApplicable):\n                    v = CPEComponent2_3_FS.VALUE_NA\n                else:\n                    v = comp.as_fs()\n            fs.append(v)\n            fs.append(CPEComponent2_3_FS.SEPARATOR_COMP)\n        return CPE._trim(\"\".join(fs[:-1]))",
    "docstring": "Returns the CPE Name as formatted string of version 2.3.\n\n        :returns: CPE Name as formatted string\n        :rtype: string\n        :exception: TypeError - incompatible version"
  },
  {
    "code": "def get(self, id, service='facebook', type='analysis'):\n        return self.request.get(service + '/task/' + type + '/' + id)",
    "docstring": "Get a given Pylon task\n\n            :param id: The ID of the task\n            :type id: str\n            :param service: The PYLON service (facebook)\n            :type service: str\n            :return: dict of REST API output with headers attached\n            :rtype: :class:`~datasift.request.DictResponse`\n            :raises: :class:`~datasift.exceptions.DataSiftApiException`,\n                :class:`requests.exceptions.HTTPError`"
  },
  {
    "code": "def ping(self, timeout=0, **kwargs):\n        def rand_id(size=8, chars=string.ascii_uppercase + string.digits):\n            return ''.join(random.choice(chars) for _ in range(size))\n        payload = rand_id()\n        self.ws.ping(payload)\n        opcode, data = self.recv_raw(timeout, [websocket.ABNF.OPCODE_PONG], **kwargs)\n        if data != payload:\n            raise IOError(\"Pinged server but did not receive correct pong\")",
    "docstring": "THIS DOES NOT WORK, UWSGI DOES NOT RESPOND TO PINGS"
  },
  {
    "code": "def GetRadioButtonSelect(selectList, title=\"Select\", msg=\"\"):\n    root = tkinter.Tk()\n    root.title(title)\n    val = tkinter.IntVar()\n    val.set(0)\n    if msg != \"\":\n        tkinter.Label(root, text=msg).pack()\n    index = 0\n    for item in selectList:\n        tkinter.Radiobutton(root, text=item, variable=val,\n                            value=index).pack(anchor=tkinter.W)\n        index += 1\n    tkinter.Button(root, text=\"OK\", fg=\"black\", command=root.quit).pack()\n    root.mainloop()\n    root.destroy()\n    print(selectList[val.get()] + \" is selected\")\n    return (selectList[val.get()], val.get())",
    "docstring": "Create radio button window for option selection\n\n    title: Window name\n    mag: Label of the radio button\n\n    return (seldctedItem, selectedindex)"
  },
  {
    "code": "def create_rack(self):\n        return Rack(\n            self.networkapi_url,\n            self.user,\n            self.password,\n            self.user_ldap)",
    "docstring": "Get an instance of rack services facade."
  },
  {
    "code": "def get_queryset(self):\n        if self.queryset is None:\n            raise ImproperlyConfigured(\n                \"'%s' must define 'queryset'\" % self.__class__.__name__)\n        return self.queryset()",
    "docstring": "Check that the queryset is defined and call it."
  },
  {
    "code": "def compile_all():\n    print(\"Compiling for PyQt4: style.qrc -> pyqt_style_rc.py\")\n    os.system(\"pyrcc4 -py3 style.qrc -o pyqt_style_rc.py\")\n    print(\"Compiling for PyQt5: style.qrc -> pyqt5_style_rc.py\")\n    os.system(\"pyrcc5 style.qrc -o pyqt5_style_rc.py\")\n    print(\"Compiling for PySide: style.qrc -> pyside_style_rc.py\")\n    os.system(\"pyside-rcc -py3 style.qrc -o pyside_style_rc.py\")",
    "docstring": "Compile style.qrc using rcc, pyside-rcc and pyrcc4"
  },
  {
    "code": "def _time_from_iso8601_time_naive(value):\n    if len(value) == 8:\n        fmt = _TIMEONLY_NO_FRACTION\n    elif len(value) == 15:\n        fmt = _TIMEONLY_W_MICROS\n    else:\n        raise ValueError(\"Unknown time format: {}\".format(value))\n    return datetime.datetime.strptime(value, fmt).time()",
    "docstring": "Convert a zoneless ISO8601 time string to naive datetime time\n\n    :type value: str\n    :param value: The time string to convert\n\n    :rtype: :class:`datetime.time`\n    :returns: A datetime time object created from the string\n    :raises ValueError: if the value does not match a known format."
  },
  {
    "code": "def from_request(cls, request):\n        request_headers = HeaderDict()\n        other_headers = ['CONTENT_TYPE', 'CONTENT_LENGTH']\n        for header, value in iteritems(request.META):\n            is_header = header.startswith('HTTP_') or header in other_headers\n            normalized_header = cls._normalize_django_header_name(header)\n            if is_header and value:\n                request_headers[normalized_header] = value\n        return request_headers",
    "docstring": "Generate a HeaderDict based on django request object meta data."
  },
  {
    "code": "def generateCertificate(cls):\n        key = generate_key()\n        cert = generate_certificate(key)\n        return cls(key=key, cert=cert)",
    "docstring": "Create and return an X.509 certificate and corresponding private key.\n\n        :rtype: RTCCertificate"
  },
  {
    "code": "def _CSI(self, cmd):\n        sys.stdout.write('\\x1b[')\n        sys.stdout.write(cmd)",
    "docstring": "Control sequence introducer"
  },
  {
    "code": "def recurrence(self, recurrence):\n        if not is_valid_recurrence(recurrence):\n            raise KeyError(\"'%s' is not a valid recurrence value\" % recurrence)\n        self._recurrence = recurrence",
    "docstring": "See `recurrence`."
  },
  {
    "code": "def safe_wraps(wrapper, *args, **kwargs):\n    while isinstance(wrapper, functools.partial):\n        wrapper = wrapper.func\n    return functools.wraps(wrapper, *args, **kwargs)",
    "docstring": "Safely wraps partial functions."
  },
  {
    "code": "def folderitems(self):\n        items = super(AnalysisRequestAnalysesView, self).folderitems()\n        self.categories.sort()\n        return items",
    "docstring": "XXX refactor if possible to non-classic mode"
  },
  {
    "code": "def get_ip_address():\n  try:\n    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n    s.connect((\"8.8.8.8\", 80))\n    ip_address = s.getsockname()[0]\n  except socket_error as sockerr:\n    if sockerr.errno != errno.ENETUNREACH:\n      raise sockerr\n    ip_address = socket.gethostbyname(socket.getfqdn())\n  finally:\n    s.close()\n  return ip_address",
    "docstring": "Simple utility to get host IP address."
  },
  {
    "code": "def validate_password(entry, username, check_function, password=None, retries=1, save_on_success=True, prompt=None, **check_args):\n    if password is None:\n        password = get_password(entry, username, prompt)\n    for _ in xrange(retries + 1):\n        if check_function(username, password, **check_args):\n            if save_on_success:\n                save_password(entry, password, username)\n            return True\n        log.error(\"Couldn't successfully authenticate your username & password..\")\n        password = get_password(entry, username, prompt, always_ask=True)\n    return False",
    "docstring": "Validate a password with a check function & retry if the password is incorrect.\n\n      Useful for after a user has changed their password in LDAP, but their local keychain entry is then out of sync.\n\n      :param str entry: The keychain entry to fetch a password from.\n      :param str username: The username to authenticate\n      :param func check_function: Check function to use. Should take (username, password, **check_args)\n      :param str password: The password to validate. If `None`, the user will be prompted.\n      :param int retries: Number of retries to prompt the user for.\n      :param bool save_on_success: Save the password if the validation was successful.\n      :param str prompt: Alternate prompt to use when asking for the user's password.\n\n      :returns: `True` on successful authentication. `False` otherwise.\n      :rtype: bool"
  },
  {
    "code": "def start(self):\n        resp = self.post('start')\n        if resp.is_fail():\n            return None\n        if 'result' not in resp.data:\n            return None\n        result = resp.data['result']\n        return {\n            'user': result['user'],\n            'ws_host': result['ws_host'],\n        }",
    "docstring": "Gets the rtm ws_host and user information\n\n        Returns:\n            None if request failed,\n            else a dict containing \"user\"(User) and \"ws_host\""
  },
  {
    "code": "def _validate_alias_file_path(alias_file_path):\n    if not os.path.exists(alias_file_path):\n        raise CLIError(ALIAS_FILE_NOT_FOUND_ERROR)\n    if os.path.isdir(alias_file_path):\n        raise CLIError(ALIAS_FILE_DIR_ERROR.format(alias_file_path))",
    "docstring": "Make sure the alias file path is neither non-existant nor a directory\n\n    Args:\n        The alias file path to import aliases from."
  },
  {
    "code": "def pytype_to_deps(t):\n    res = set()\n    for hpp_dep in pytype_to_deps_hpp(t):\n        res.add(os.path.join('pythonic', 'types', hpp_dep))\n        res.add(os.path.join('pythonic', 'include', 'types', hpp_dep))\n    return res",
    "docstring": "python -> pythonic type header full path."
  },
  {
    "code": "def build_input_table(cls, name='inputTableName', input_name='input'):\n        obj = cls(name)\n        obj.exporter = 'get_input_table_name'\n        obj.input_name = input_name\n        return obj",
    "docstring": "Build an input table parameter\n\n        :param name: parameter name\n        :type name: str\n        :param input_name: bind input port name\n        :param input_name: str\n        :return: input description\n        :rtype: ParamDef"
  },
  {
    "code": "def _read_all_from_socket(self, timeout):\n        pkts = []\n        try:\n            self._sock.settimeout(timeout)\n            while True:\n                p = self._sock.recv(64)\n                pkts.append((bytearray(p), time.time()))\n                self._sock.settimeout(0)\n        except socket.timeout:\n            pass\n        except socket.error as e:\n            if e.errno == errno.EWOULDBLOCK:\n                pass\n            else:\n                raise\n        if self._ipv6_address_present:\n            try:\n                self._sock6.settimeout(timeout)\n                while True:\n                    p = self._sock6.recv(128)\n                    pkts.append((bytearray(p), time.time()))\n                    self._sock6.settimeout(0)\n            except socket.timeout:\n                pass\n            except socket.error as e:\n                if e.errno == errno.EWOULDBLOCK:\n                    pass\n                else:\n                    raise\n        return pkts",
    "docstring": "Read all packets we currently can on the socket.\n\n        Returns list of tuples. Each tuple contains a packet and the time at\n        which it was received. NOTE: The receive time is the time when our\n        recv() call returned, which greatly depends on when it was called. The\n        time is NOT the time at which the packet arrived at our host, but it's\n        the closest we can come to the real ping time.\n\n        If nothing was received within the timeout time, the return list is\n        empty.\n\n        First read is blocking with timeout, so we'll wait at least that long.\n        Then, in case any more packets have arrived, we read everything we can\n        from the socket in non-blocking mode."
  },
  {
    "code": "def insert_colorpoint(self, position=0.5, color1=[1.0,1.0,0.0], color2=[1.0,1.0,0.0]):\n        L = self._colorpoint_list\n        if   position <= 0.0:\n            L.insert(0,[0.0,color1,color2])\n        elif position >= 1.0:\n            L.append([1.0,color1,color2])\n        else:\n            for n in range(len(self._colorpoint_list)):\n                if position <= L[n+1][0]:\n                    L.insert(n+1,[position,color1,color2])\n                    break\n        self.update_image()\n        return self",
    "docstring": "Inserts the specified color into the list."
  },
  {
    "code": "def _oxford_comma_separator(i, length):\n    if length == 1:\n        return None\n    elif length < 3 and i == 0:\n        return ' and '\n    elif i < length - 2:\n        return ', '\n    elif i == length - 2:\n        return ', and '\n    else:\n        return None",
    "docstring": "Make a separator for a prose-like list with `,` between items except\n    for `, and` after the second to last item."
  },
  {
    "code": "def get_handler_name(route: Route, logic: Callable) -> str:\n    if route.handler_name is not None:\n        return route.handler_name\n    if any(m for m in route.methods if m.method.lower() == 'post'):\n        if route.heading != 'API':\n            return '{}ListHandler'.format(get_valid_class_name(route.heading))\n        return '{}ListHandler'.format(get_valid_class_name(logic.__name__))\n    if route.heading != 'API':\n        return '{}Handler'.format(get_valid_class_name(route.heading))\n    return '{}Handler'.format(get_valid_class_name(logic.__name__))",
    "docstring": "Gets the handler name.\n\n    :param route: A Route instance.\n    :param logic: The logic function.\n    :returns: A handler class name."
  },
  {
    "code": "def key_func(*keys, **kwargs):\n    ensure_argcount(keys, min_=1)\n    ensure_keyword_args(kwargs, optional=('default',))\n    keys = list(map(ensure_string, keys))\n    if 'default' in kwargs:\n        default = kwargs['default']\n        def getitems(obj):\n            for key in keys:\n                try:\n                    obj = obj[key]\n                except KeyError:\n                    return default\n            return obj\n    else:\n        if len(keys) == 1:\n            getitems = operator.itemgetter(keys[0])\n        else:\n            def getitems(obj):\n                for key in keys:\n                    obj = obj[key]\n                return obj\n    return getitems",
    "docstring": "Creates a \"key function\" based on given keys.\n\n    Resulting function will perform lookup using specified keys, in order,\n    on the object passed to it as an argument.\n    For example, ``key_func('a', 'b')(foo)`` is equivalent to ``foo['a']['b']``.\n\n    :param keys: Lookup keys\n    :param default: Optional keyword argument specifying default value\n                    that will be returned when some lookup key is not present\n\n    :return: Unary key function"
  },
  {
    "code": "def notification_preference(obj_type, profile):\n    default_alert_value = True\n    if not profile:\n        alerts_on = True\n    else:\n        notifications = profile.get('notifications', {})\n        alerts_on = notifications.get(obj_type, default_alert_value)\n    return dict(alerts_on=alerts_on, obj_type=obj_type)",
    "docstring": "Display two radio buttons for turning notifications on or off.\n    The default value is is have alerts_on = True."
  },
  {
    "code": "def interpolate(self, lon, lat, egy=None, interp_log=True):\n        if self.data.ndim == 1:\n            theta = np.pi / 2. - np.radians(lat)\n            phi = np.radians(lon)\n            return hp.pixelfunc.get_interp_val(self.counts, theta,\n                                               phi, nest=self.hpx.nest)\n        else:\n            return self._interpolate_cube(lon, lat, egy, interp_log)",
    "docstring": "Interpolate map values.\n\n        Parameters\n        ----------\n        interp_log : bool\n            Interpolate the z-coordinate in logspace."
  },
  {
    "code": "def getSampleFrequencies(self):\n        return np.array([round(self.samplefrequency(chn))\n                         for chn in np.arange(self.signals_in_file)])",
    "docstring": "Returns  samplefrequencies of all signals.\n\n        Parameters\n        ----------\n        None\n\n        Examples\n        --------\n        >>> import pyedflib\n        >>> f = pyedflib.data.test_generator()\n        >>> all(f.getSampleFrequencies()==200.0)\n        True\n        >>> f._close()\n        >>> del f"
  },
  {
    "code": "def _tokenize_latex(self, exp):\n        tokens = []\n        prevexp = \"\"\n        while exp:\n            t, exp = self._get_next_token(exp)\n            if t.strip() != \"\":\n                tokens.append(t)\n            if prevexp == exp:\n                break\n            prevexp = exp\n        return tokens",
    "docstring": "Internal method to tokenize latex"
  },
  {
    "code": "def add_densities(density1, density2):\n    return {spin: np.array(density1[spin]) + np.array(density2[spin])\n            for spin in density1.keys()}",
    "docstring": "Method to sum two densities.\n\n    Args:\n        density1: First density.\n        density2: Second density.\n\n    Returns:\n        Dict of {spin: density}."
  },
  {
    "code": "def register(self, target):\n        for rule, options in self.url_rules:\n            target.add_url_rule(rule, self.name, self.dispatch_request, **options)",
    "docstring": "Registers url_rules on the blueprint"
  },
  {
    "code": "def addCategory(self, categoryUri, weight):\n        assert isinstance(weight, (float, int)), \"weight value has to be a positive or negative integer\"\n        self.topicPage[\"categories\"].append({\"uri\": categoryUri, \"wgt\": weight})",
    "docstring": "add a relevant category to the topic page\n        @param categoryUri: uri of the category to be added\n        @param weight: importance of the provided category (typically in range 1 - 50)"
  },
  {
    "code": "def format_vk(vk):\n    for ext in get_extensions_filtered(vk):\n        req = ext['require']\n        if not isinstance(req, list):\n            ext['require'] = [req]",
    "docstring": "Format vk before using it"
  },
  {
    "code": "def add(self, path):\n        with salt.utils.files.fopen(path, 'rb') as ifile:\n            for chunk in iter(lambda: ifile.read(self.__buff), b''):\n                self.__digest.update(chunk)",
    "docstring": "Update digest with the file content by path.\n\n        :param path:\n        :return:"
  },
  {
    "code": "def smart_object(self):\n        if not hasattr(self, '_smart_object'):\n            self._smart_object = SmartObject(self)\n        return self._smart_object",
    "docstring": "Associated smart object.\n\n        :return: :py:class:`~psd_tools.api.smart_object.SmartObject`."
  },
  {
    "code": "def file2abspath(filename, this_file=__file__):\n    return os.path.abspath(\n        os.path.join(os.path.dirname(os.path.abspath(this_file)), filename))",
    "docstring": "generate absolute path for the given file and base dir"
  },
  {
    "code": "def send_datagram(self, message):\n        if not self.stopped.isSet():\n            host, port = message.destination\n            logger.debug(\"send_datagram - \" + str(message))\n            serializer = Serializer()\n            message = serializer.serialize(message)\n            self._socket.sendto(message, (host, port))",
    "docstring": "Send a message through the udp socket.\n\n        :type message: Message\n        :param message: the message to send"
  },
  {
    "code": "def assert_is_not(expected, actual, message=None, extra=None):\n    assert expected is not actual, _assert_fail_message(\n        message, expected, actual, \"is\", extra\n    )",
    "docstring": "Raises an AssertionError if expected is actual."
  },
  {
    "code": "def get_instance(self, payload):\n        return TodayInstance(self._version, payload, account_sid=self._solution['account_sid'], )",
    "docstring": "Build an instance of TodayInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.api.v2010.account.usage.record.today.TodayInstance\n        :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayInstance"
  },
  {
    "code": "def shift_and_pad(tensor, shift, axis=0):\n  shape = tensor.shape\n  rank = len(shape)\n  assert 0 <= abs(axis) < rank\n  length = int(shape[axis])\n  assert 0 <= abs(shift) < length\n  paddings = [(0, 0)] * rank\n  begin = [0] * rank\n  size = [-1] * rank\n  if shift > 0:\n    paddings[axis] = (shift, 0)\n    size[axis] = length - shift\n  elif shift < 0:\n    paddings[axis] = (0, -shift)\n    begin[axis] = -shift\n  ret = tf.pad(tf.slice(tensor, begin, size), paddings)\n  return ret",
    "docstring": "Shifts and pads with zero along an axis.\n\n  Example:\n    shift_and_pad([1, 2, 3, 4], 2)  --> [0, 0, 1, 2]\n    shift_and_pad([1, 2, 3, 4], -2) --> [3, 4, 0, 0]\n\n  Args:\n    tensor: Tensor; to be shifted and padded.\n    shift: int; number of positions to shift by.\n    axis: int; along which axis to shift and pad.\n\n  Returns:\n    A Tensor with the same shape as the input tensor."
  },
  {
    "code": "def _nix_env():\n    nixhome = os.path.join(os.path.expanduser('~{0}'.format(__opts__['user'])), '.nix-profile/bin/')\n    return [os.path.join(nixhome, 'nix-env')]",
    "docstring": "nix-env with quiet option. By default, nix is extremely verbose and prints the build log of every package to stderr. This tells nix to\n    only show changes."
  },
  {
    "code": "def get_chromecasts(tries=None, retry_wait=None, timeout=None,\n                    blocking=True, callback=None):\n    if blocking:\n        hosts = discover_chromecasts()\n        cc_list = []\n        for host in hosts:\n            try:\n                cc_list.append(_get_chromecast_from_host(\n                    host, tries=tries, retry_wait=retry_wait, timeout=timeout,\n                    blocking=blocking))\n            except ChromecastConnectionError:\n                pass\n        return cc_list\n    else:\n        if not callable(callback):\n            raise ValueError(\n                \"Nonblocking discovery requires a callback function.\")\n        def internal_callback(name):\n            try:\n                callback(_get_chromecast_from_host(\n                    listener.services[name], tries=tries,\n                    retry_wait=retry_wait, timeout=timeout, blocking=blocking))\n            except ChromecastConnectionError:\n                pass\n        def internal_stop():\n            stop_discovery(browser)\n        listener, browser = start_discovery(internal_callback)\n        return internal_stop",
    "docstring": "Searches the network for chromecast devices.\n\n    If blocking = True, returns a list of discovered chromecast devices.\n    If blocking = False, triggers a callback for each discovered chromecast,\n                         and returns a function which can be executed to stop\n                         discovery.\n\n    May return an empty list if no chromecasts were found.\n\n    Tries is specified if you want to limit the number of times the\n    underlying socket associated with your Chromecast objects will\n    retry connecting if connection is lost or it fails to connect\n    in the first place. The number of seconds spent between each retry\n    can be defined by passing the retry_wait parameter, the default is\n    to wait 5 seconds."
  },
  {
    "code": "def _run_bunny(args):\n    main_file, json_file, project_name = _get_main_and_json(args.directory)\n    work_dir = utils.safe_makedir(os.path.join(os.getcwd(), \"bunny_work\"))\n    flags = [\"-b\", work_dir]\n    log_file = os.path.join(work_dir, \"%s-bunny.log\" % project_name)\n    if os.path.exists(work_dir):\n        caches = [os.path.join(work_dir, d) for d in os.listdir(work_dir)\n                  if os.path.isdir(os.path.join(work_dir, d))]\n        if caches:\n            flags += [\"--cache-dir\", max(caches, key=os.path.getmtime)]\n    if args.no_container:\n        _remove_bcbiovm_path()\n        flags += [\"--no-container\"]\n    cmd = [\"rabix\"] + flags + [main_file, json_file]\n    with utils.chdir(work_dir):\n        _run_tool(cmd, not args.no_container, work_dir, log_file)",
    "docstring": "Run CWL with rabix bunny."
  },
  {
    "code": "def user_has_permission(self, user, name):\n        targetRecord = AuthMembership.objects(creator=self.client, user=user).first()\n        if not targetRecord:\n            return False\n        for group in targetRecord.groups:\n            if self.has_permission(group.role, name):\n                return True\n        return False",
    "docstring": "verify user has permission"
  },
  {
    "code": "def pairwise(\n    iterable: Iterable,\n    default_value: Any,\n) -> Iterable[Tuple[Any, Any]]:\n    a, b = tee(iterable)\n    _ = next(b, default_value)\n    return zip_longest(a, b, fillvalue=default_value)",
    "docstring": "Return pairs of items from `iterable`.\n\n    pairwise([1, 2, 3], default_value=None) -> (1, 2) (2, 3), (3, None)"
  },
  {
    "code": "def load_bookmark(self, slot_num):\r\n        bookmarks = CONF.get('editor', 'bookmarks')\r\n        if slot_num in bookmarks:\r\n            filename, line_num, column = bookmarks[slot_num]\r\n        else:\r\n            return\r\n        if not osp.isfile(filename):\r\n            self.last_edit_cursor_pos = None\r\n            return\r\n        self.load(filename)\r\n        editor = self.get_current_editor()\r\n        if line_num < editor.document().lineCount():\r\n            linelength = len(editor.document()\r\n                             .findBlockByNumber(line_num).text())\r\n            if column <= linelength:\r\n                editor.go_to_line(line_num + 1, column)\r\n            else:\r\n                editor.go_to_line(line_num + 1, linelength)",
    "docstring": "Set cursor to bookmarked file and position."
  },
  {
    "code": "def encode(self, value):\n        if value is None and self._default is not None:\n            value = self._default\n        for encoder in self._encoders:\n            try:\n                return encoder(value)\n            except ValueError as ex:\n                pass\n        raise ValueError('Value \\'{}\\' is invalid. {}'\n                         .format(value, ex.message))",
    "docstring": "The encoder for this schema.\n        Tries each encoder in order of the types specified for this schema."
  },
  {
    "code": "def work(self, interval=5):\n        self._setproctitle(\"Starting\")\n        logger.info(\"starting\")\n        self.startup()\n        while True:\n            if self._shutdown:\n                logger.info('shutdown scheduled')\n                break\n            self.register_worker()\n            job = self.reserve(interval)\n            if job:\n                self.fork_worker(job)\n            else:\n                if interval == 0:\n                    break\n                self._setproctitle(\"Waiting\")\n        self.unregister_worker()",
    "docstring": "Invoked by ``run`` method. ``work`` listens on a list of queues and sleeps\n        for ``interval`` time.\n\n        ``interval`` -- Number of seconds the worker will wait until processing the next job. Default is \"5\".\n\n        Whenever a worker finds a job on the queue it first calls ``reserve`` on\n        that job to make sure another worker won't run it, then *forks* itself to\n        work on that job."
  },
  {
    "code": "def getSignificance(wk1, wk2, nout, ofac):\n  expy = exp(-wk2)\n  effm = 2.0*(nout)/ofac\n  sig = effm*expy\n  ind = (sig > 0.01).nonzero()\n  sig[ind] = 1.0-(1.0-expy[ind])**effm\n  return sig",
    "docstring": "returns the peak false alarm probabilities\n  Hence the lower is the probability and the more significant is the peak"
  },
  {
    "code": "def xray(im, direction='X'):\n    r\n    im = sp.array(~im, dtype=int)\n    if direction in ['Y', 'y']:\n        im = sp.transpose(im, axes=[1, 0, 2])\n    if direction in ['Z', 'z']:\n        im = sp.transpose(im, axes=[2, 1, 0])\n    im = sp.sum(im, axis=0)\n    return im",
    "docstring": "r\"\"\"\n    Simulates an X-ray radiograph looking through the porouls material in the\n    specfied direction.  The resulting image is colored according to the amount\n    of attenuation an X-ray would experience, so regions with more solid will\n    appear darker.\n\n    Parameters\n    ----------\n    im : array_like\n        ND-image of the porous material with the solid phase marked as 1 or\n        True\n\n    direction : string\n        Specify the axis along which the camera will point.  Options are\n        'X', 'Y', and 'Z'.\n\n    Returns\n    -------\n    image : 2D-array\n        A 2D greyscale image suitable for use in matplotlib\\'s ```imshow```\n        function."
  },
  {
    "code": "def get(self):\n        header = ''\n        while len(header) < self.HEADER_LENGTH:\n            chunk = self._sock.recv(self.HEADER_LENGTH - len(header))\n            chunk = chunk.decode() if self._encode else chunk\n            if chunk == '':\n                return None\n            header += chunk\n        length = int(header)\n        message = ''\n        while len(message) < length:\n            chunk = self._sock.recv(length - len(message))\n            chunk = chunk.decode() if self._encode else chunk\n            if chunk == '':\n                return None\n            message += chunk\n        return message",
    "docstring": "Receive a message.\n        Return the message upon successful reception, or None upon failure."
  },
  {
    "code": "def yticksize(self, size, index=1):\n        self.layout['yaxis' + str(index)]['tickfont']['size'] = size\n        return self",
    "docstring": "Set the tick font size.\n\n        Parameters\n        ----------\n        size : int\n\n        Returns\n        -------\n        Chart"
  },
  {
    "code": "def delete_webhook(webhook_id):\n    webhook = get_data_or_404('webhook', webhook_id)\n    action = get_data_or_404('action', webhook['action_id'])\n    project = get_data_or_404('project', action['project_id'])\n    if project['owner_id'] != get_current_user_id():\n        return jsonify(message='forbidden'), 403\n    delete_instance('webhook', action['id'])\n    return jsonify({})",
    "docstring": "Delete webhook."
  },
  {
    "code": "def upsert(self, _id, dct, attribute=\"_id\"):\n        mongo_response = yield self.update(_id, dct, upsert=True, attribute=attribute)\n        raise Return(mongo_response)",
    "docstring": "Update or Insert a new document\n\n        :param str _id: The document id\n        :param dict dct: The dictionary to set on the document\n        :param str attribute: The attribute to query for to find the object to set this data on\n        :returns: JSON Mongo client response including the \"n\" key to show number of objects effected"
  },
  {
    "code": "def uniform_cost(problem, graph_search=False, viewer=None):\n    return _search(problem,\n                   BoundedPriorityQueue(),\n                   graph_search=graph_search,\n                   node_factory=SearchNodeCostOrdered,\n                   graph_replace_when_better=True,\n                   viewer=viewer)",
    "docstring": "Uniform cost search.\n\n    If graph_search=True, will avoid exploring repeated states.\n    Requires: SearchProblem.actions, SearchProblem.result,\n    SearchProblem.is_goal, and SearchProblem.cost."
  },
  {
    "code": "def f1_score(y_true, y_pred, average='micro', suffix=False):\n    true_entities = set(get_entities(y_true, suffix))\n    pred_entities = set(get_entities(y_pred, suffix))\n    nb_correct = len(true_entities & pred_entities)\n    nb_pred = len(pred_entities)\n    nb_true = len(true_entities)\n    p = nb_correct / nb_pred if nb_pred > 0 else 0\n    r = nb_correct / nb_true if nb_true > 0 else 0\n    score = 2 * p * r / (p + r) if p + r > 0 else 0\n    return score",
    "docstring": "Compute the F1 score.\n\n    The F1 score can be interpreted as a weighted average of the precision and\n    recall, where an F1 score reaches its best value at 1 and worst score at 0.\n    The relative contribution of precision and recall to the F1 score are\n    equal. The formula for the F1 score is::\n\n        F1 = 2 * (precision * recall) / (precision + recall)\n\n    Args:\n        y_true : 2d array. Ground truth (correct) target values.\n        y_pred : 2d array. Estimated targets as returned by a tagger.\n\n    Returns:\n        score : float.\n\n    Example:\n        >>> from seqeval.metrics import f1_score\n        >>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]\n        >>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]\n        >>> f1_score(y_true, y_pred)\n        0.50"
  },
  {
    "code": "def _initialize_table(self, column_count):\n        header = [''] * column_count\n        alignment = [self.default_alignment] * column_count\n        width = [0] * column_count\n        padding = [self.default_padding] * column_count\n        self._column_count = column_count\n        self._column_headers = HeaderData(self, header)\n        self._column_alignments = AlignmentMetaData(self, alignment)\n        self._column_widths = PositiveIntegerMetaData(self, width)\n        self._left_padding_widths = PositiveIntegerMetaData(self, padding)\n        self._right_padding_widths = PositiveIntegerMetaData(self, padding)",
    "docstring": "Sets the column count of the table.\n\n        This method is called to set the number of columns for the first time.\n\n        Parameters\n        ----------\n        column_count : int\n            number of columns in the table"
  },
  {
    "code": "def get_random_label():\n    return ''.join(random.choice(string.ascii_uppercase + string.digits) \\\n                   for _ in range(15))",
    "docstring": "Get a random label string to use when clustering jobs."
  },
  {
    "code": "def contains(self, rect):\n        return (rect.y >= self.y and \\\n                rect.x >= self.x and \\\n                rect.y+rect.height <= self.y+self.height and \\\n                rect.x+rect.width  <= self.x+self.width)",
    "docstring": "Tests if another rectangle is contained by this one\n\n        Arguments:\n            rect (Rectangle): The other rectangle\n\n        Returns:\n            bool: True if it is container, False otherwise"
  },
  {
    "code": "def typedefs(\n            self,\n            name=None,\n            function=None,\n            header_dir=None,\n            header_file=None,\n            recursive=None,\n            allow_empty=None):\n        return (\n            self._find_multiple(\n                self._impl_matchers[scopedef_t.typedef],\n                name=name,\n                function=function,\n                decl_type=self._impl_decl_types[\n                    scopedef_t.typedef],\n                header_dir=header_dir,\n                header_file=header_file,\n                recursive=recursive,\n                allow_empty=allow_empty)\n        )",
    "docstring": "returns a set of typedef declarations, that are matched\n        defined criteria"
  },
  {
    "code": "def mustExposeRequest(self, service_request):\n        expose_request = service_request.service.mustExposeRequest(service_request)\n        if expose_request is None:\n            if self.expose_request is None:\n                return False\n            return self.expose_request\n        return expose_request",
    "docstring": "Decides whether the underlying http request should be exposed as the\n        first argument to the method call. This is granular, looking at the\n        service method first, then at the service level and finally checking\n        the gateway.\n\n        @rtype: C{bool}"
  },
  {
    "code": "def sample(self, num):\n        if num > len(self):\n            return self.copy()\n        elif num < 0:\n            raise IndexError(\"Cannot sample a negative number of rows \"\n                             \"from a DataTable\")\n        random_row_mask = ([True] * num) + ([False] * (len(self) - num))\n        shuffle(random_row_mask)\n        sampled_table = self.mask(random_row_mask)\n        random_col_name = 'random_sorting_column'\n        while random_col_name in sampled_table:\n            random_col_name = '%030x' % randrange(16**30)\n        sampled_table[random_col_name] = [random()\n                                          for _ in xrange(len(sampled_table))]\n        sampled_table.sort(random_col_name, inplace=True)\n        del sampled_table[random_col_name]\n        return sampled_table",
    "docstring": "Returns a new table with rows randomly sampled.\n\n        We create a mask with `num` True bools, and fill it with False bools\n        until it is the length of the table. We shuffle it, and apply that\n        mask to the table."
  },
  {
    "code": "def _GetClientLibCallback(args, client_func=_GetClientLib):\n  client_paths = client_func(\n      args.service, args.language, args.output, args.build_system,\n      hostname=args.hostname, application_path=args.application)\n  for client_path in client_paths:\n    print 'API client library written to %s' % client_path",
    "docstring": "Generate discovery docs and client libraries to files.\n\n  Args:\n    args: An argparse.Namespace object to extract parameters from.\n    client_func: A function that generates client libraries and stores them to\n      files, accepting a list of service names, a client library language,\n      an output directory, a build system for the client library language, and\n      a hostname."
  },
  {
    "code": "def _get_magnitude_term(self, C, mag):\n        f_mag = C[\"c0\"] + C[\"c1\"] * mag\n        if (mag > 4.5) and (mag <= 5.5):\n            return f_mag + (C[\"c2\"] * (mag - 4.5))\n        elif (mag > 5.5) and (mag <= 6.5):\n            return f_mag + (C[\"c2\"] * (mag - 4.5)) + (C[\"c3\"] * (mag - 5.5))\n        elif mag > 6.5:\n            return f_mag + (C[\"c2\"] * (mag - 4.5)) + (C[\"c3\"] * (mag - 5.5)) +\\\n                (C[\"c4\"] * (mag - 6.5))\n        else:\n            return f_mag",
    "docstring": "Returns the magnitude scaling term defined in equation 2"
  },
  {
    "code": "def oauth_manager(self, oauth_manager):\n        @self.app.before_request\n        def before_request():\n            endpoint = request.endpoint\n            resource = self.app.view_functions[endpoint].view_class\n            if not getattr(resource, 'disable_oauth'):\n                scopes = request.args.get('scopes')\n                if getattr(resource, 'schema'):\n                    scopes = [self.build_scope(resource, request.method)]\n                elif scopes:\n                    scopes = scopes.split(',')\n                    if scopes:\n                        scopes = scopes.split(',')\n                valid, req = oauth_manager.verify_request(scopes)\n                for func in oauth_manager._after_request_funcs:\n                    valid, req = func(valid, req)\n                if not valid:\n                    if oauth_manager._invalid_response:\n                        return oauth_manager._invalid_response(req)\n                    return abort(401)\n                request.oauth = req",
    "docstring": "Use the oauth manager to enable oauth for API\n\n        :param oauth_manager: the oauth manager"
  },
  {
    "code": "def _parse_ergodic_cutoff(self):\n        ec_is_str = isinstance(self.ergodic_cutoff, str)\n        if ec_is_str and self.ergodic_cutoff.lower() == 'on':\n            if self.sliding_window:\n                return 1.0 / self.lag_time\n            else:\n                return 1.0\n        elif ec_is_str and self.ergodic_cutoff.lower() == 'off':\n            return 0.0\n        else:\n            return self.ergodic_cutoff",
    "docstring": "Get a numeric value from the ergodic_cutoff input,\n        which can be 'on' or 'off'."
  },
  {
    "code": "def checkFuelPosition(obs, agent_host):\n    for i in range(1,39):\n        key = 'InventorySlot_'+str(i)+'_item'\n        if key in obs:\n            item = obs[key]\n            if item == 'coal':\n                agent_host.sendCommand(\"swapInventoryItems 0 \" + str(i))\n                return",
    "docstring": "Make sure our coal, if we have any, is in slot 0."
  },
  {
    "code": "def calc_file_md5(filepath, chunk_size=None):\n    if chunk_size is None:\n        chunk_size = 256 * 1024\n    md5sum = hashlib.md5()\n    with io.open(filepath, 'r+b') as f:\n        datachunk = f.read(chunk_size)\n        while datachunk is not None and len(datachunk) > 0:\n            md5sum.update(datachunk)\n            datachunk = f.read(chunk_size)\n    return md5sum.hexdigest()",
    "docstring": "Calculate a file's md5 checksum. Use the specified chunk_size for IO or the\n    default 256KB\n\n    :param filepath:\n    :param chunk_size:\n    :return:"
  },
  {
    "code": "async def get_kernel_options(cls) -> typing.Optional[str]:\n        data = await cls.get_config(\"kernel_opts\")\n        return None if data is None or data == \"\" else data",
    "docstring": "Kernel options.\n\n        Boot parameters to pass to the kernel by default."
  },
  {
    "code": "def print_modules(self):\n\t\tshutit_global.shutit_global_object.yield_to_draw()\n\t\tcfg = self.cfg\n\t\tmodule_string = ''\n\t\tmodule_string += 'Modules: \\n'\n\t\tmodule_string += '    Run order    Build    Remove    Module ID\\n'\n\t\tfor module_id in self.module_ids():\n\t\t\tmodule_string += '    ' + str(self.shutit_map[module_id].run_order) + '        ' + str(\n\t\t\t\tcfg[module_id]['shutit.core.module.build']) + '    ' + str(\n\t\t\t\tcfg[module_id]['shutit.core.module.remove']) + '    ' + module_id + '\\n'\n\t\treturn module_string",
    "docstring": "Returns a string table representing the modules in the ShutIt module map."
  },
  {
    "code": "def create_connection_model(service):\n    services = service._services\n    bases = (BaseModel,)\n    attributes = {model_service_name(service): fields.CharField() for service in services}\n    return type(BaseModel)(connection_service_name(service), bases, attributes)",
    "docstring": "Create an SQL Alchemy table that connects the provides services"
  },
  {
    "code": "def clear_genus_type(self):\n        if (self.get_genus_type_metadata().is_read_only() or\n                self.get_genus_type_metadata().is_required()):\n            raise errors.NoAccess()\n        self._my_map['genusTypeId'] = self._genus_type_default",
    "docstring": "Clears the genus type.\n\n        raise:  NoAccess - ``Metadata.isRequired()`` or\n                ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def install_caller_instruction(self, token_type=\"Unrestricted\",\n                                   transaction_id=None):\n        response = self.install_payment_instruction(\"MyRole=='Caller';\",\n                                                    token_type=token_type,\n                                                    transaction_id=transaction_id)\n        body = response.read()\n        if(response.status == 200):\n            rs = ResultSet()\n            h = handler.XmlHandler(rs, self)\n            xml.sax.parseString(body, h)\n            caller_token = rs.TokenId\n            try:\n                boto.config.save_system_option(\"FPS\", \"caller_token\",\n                                               caller_token)\n            except(IOError):\n                boto.config.save_user_option(\"FPS\", \"caller_token\",\n                                             caller_token)\n            return caller_token\n        else:\n            raise FPSResponseError(response.status, response.reason, body)",
    "docstring": "Set us up as a caller\n        This will install a new caller_token into the FPS section.\n        This should really only be called to regenerate the caller token."
  },
  {
    "code": "def get_values(self, attr_name):\n        ret = list(self._attr_value_cdist[attr_name].keys()) \\\n            + list(self._attr_value_counts[attr_name].keys()) \\\n            + list(self._branches.keys())\n        ret = set(ret)\n        return ret",
    "docstring": "Retrieves the unique set of values seen for the given attribute\n        at this node."
  },
  {
    "code": "def size(self):\n\t\twidth = c_double(0)\n\t\theight = c_double(0)\n\t\trc = self._libinput.libinput_device_get_size(\n\t\t\tself._handle, byref(width), byref(height))\n\t\tassert rc == 0, 'This device does not provide size information'\n\t\treturn width.value, height.value",
    "docstring": "The physical size of a device in mm, where meaningful.\n\n\t\tThis property is only valid on devices with the required data, i.e.\n\t\ttablets, touchpads and touchscreens. For other devices this property\n\t\traises :exc:`AssertionError`.\n\n\t\tReturns:\n\t\t\t(float, float): (Width, Height) in mm.\n\t\tRaises:\n\t\t\tAssertionError"
  },
  {
    "code": "def add_dataset(data_type, val, unit_id=None, metadata={}, name=\"\", user_id=None, flush=False):\n    d = Dataset()\n    d.type  = data_type\n    d.value = val\n    d.set_metadata(metadata)\n    d.unit_id  = unit_id\n    d.name  = name\n    d.created_by = user_id\n    d.hash  = d.set_hash()\n    try:\n        existing_dataset = db.DBSession.query(Dataset).filter(Dataset.hash==d.hash).one()\n        if existing_dataset.check_user(user_id):\n            d = existing_dataset\n        else:\n            d.set_metadata({'created_at': datetime.datetime.now()})\n            d.set_hash()\n            db.DBSession.add(d)\n    except NoResultFound:\n        db.DBSession.add(d)\n    if flush == True:\n        db.DBSession.flush()\n    return d",
    "docstring": "Data can exist without scenarios. This is the mechanism whereby\n        single pieces of data can be added without doing it through a scenario.\n\n        A typical use of this would be for setting default values on types."
  },
  {
    "code": "def _copy_binder_notebooks(app):\n    gallery_conf = app.config.sphinx_gallery_conf\n    gallery_dirs = gallery_conf.get('gallery_dirs')\n    binder_conf = gallery_conf.get('binder')\n    notebooks_dir = os.path.join(app.outdir, binder_conf.get('notebooks_dir'))\n    shutil.rmtree(notebooks_dir, ignore_errors=True)\n    os.makedirs(notebooks_dir)\n    if not isinstance(gallery_dirs, (list, tuple)):\n        gallery_dirs = [gallery_dirs]\n    iterator = sphinx_compatibility.status_iterator(\n        gallery_dirs, 'copying binder notebooks...', length=len(gallery_dirs))\n    for i_folder in iterator:\n        shutil.copytree(os.path.join(app.srcdir, i_folder),\n                        os.path.join(notebooks_dir, i_folder),\n                        ignore=_remove_ipynb_files)",
    "docstring": "Copy Jupyter notebooks to the binder notebooks directory.\n\n    Copy each output gallery directory structure but only including the\n    Jupyter notebook files."
  },
  {
    "code": "def on(self, state):\n        self._on = state\n        cmd = self.command_set.off()\n        if state:\n            cmd = self.command_set.on()\n        self.send(cmd)",
    "docstring": "Turn on or off.\n\n        :param state: True (on) or False (off)."
  },
  {
    "code": "def destroyCommit(self, varBind, **context):\n        name, val = varBind\n        (debug.logger & debug.FLAG_INS and\n         debug.logger('%s: destroyCommit(%s, %r)' % (self, name, val)))\n        instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})\n        idx = context['idx']\n        try:\n            instances[self.ST_DESTROY][-idx - 1] = self._vars.pop(name)\n        except KeyError:\n            pass\n        cbFun = context['cbFun']\n        cbFun(varBind, **context)",
    "docstring": "Destroy Managed Object Instance.\n\n        Implements the second of the multi-step workflow similar to the SNMP SET\n        command processing (:RFC:`1905#section-4.2.5`).\n\n        The goal of the second phase is to actually remove requested Managed\n        Object Instance from the MIB tree. When multiple Managed Objects Instances\n        are destroyed/modified at once (likely coming all in one SNMP PDU), each\n        of them has to run through the second (*commit*) phase successfully for\n        the system to transition to the third (*cleanup*) phase. If any single\n        *commit* step fails, the system transitions into the *undo* state for\n        each of Managed Objects Instances being processed at once.\n\n        The role of this object in the MIB tree is non-terminal. It does not\n        access the actual Managed Object Instance, but just traverses one level\n        down the MIB tree and hands off the query to the underlying objects.\n\n        Parameters\n        ----------\n        varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing\n            new Managed Object Instance value to destroy\n\n        Other Parameters\n        ----------------\n        \\*\\*context:\n\n            Query parameters:\n\n            * `cbFun` (callable) - user-supplied callable that is invoked to\n              pass the new value of the Managed Object Instance or an error.\n\n            * `instances` (dict): user-supplied dict for temporarily holding\n              Managed Objects Instances being destroyed.\n\n        Notes\n        -----\n        The callback functions (e.g. `cbFun`) have the same signature as this\n        method where `varBind` contains the new Managed Object Instance value.\n\n        In case of an error, the `error` key in the `context` dict will contain\n        an exception object."
  },
  {
    "code": "def get_hessian(self):\n        force_const = self.fields.get(\"Cartesian Force Constants\")\n        if force_const is None:\n            return None\n        N = len(self.molecule.numbers)\n        result = np.zeros((3*N, 3*N), float)\n        counter = 0\n        for row in range(3*N):\n            result[row, :row+1] = force_const[counter:counter+row+1]\n            result[:row+1, row] = force_const[counter:counter+row+1]\n            counter += row + 1\n        return result",
    "docstring": "Return the hessian"
  },
  {
    "code": "def _build_params_from_kwargs(self, **kwargs):\n        api_methods = self.get_api_params()\n        required_methods = self.get_api_required_params()\n        ret_kwargs = {}\n        for key, val in kwargs.items():\n            if key not in api_methods:\n                warnings.warn(\n                    'Passed uknown parameter [{}]'.format(key),\n                    Warning\n                )\n                continue\n            if key not in required_methods and val is None:\n                continue\n            if type(val) != api_methods[key]['type']:\n                raise ValueError(\n                    \"Invalid type specified to param: {}\".format(key)\n                )\n            if 'max_len' in api_methods[key]:\n                if len(val) > api_methods[key]['max_len']:\n                    raise ValueError(\n                        \"Lenght of parameter [{}] more than \"\n                        \"allowed length\".format(key)\n                    )\n            ret_kwargs[api_methods[key]['param']] = val\n        for item in required_methods:\n            if item not in ret_kwargs:\n                raise pushalot.exc.PushalotException(\n                    \"Parameter [{}] required, but not set\".format(item)\n                )\n        return ret_kwargs",
    "docstring": "Builds parameters from passed arguments\n\n        Search passed parameters in available methods,\n        prepend specified API key, and return dictionary\n        which can be sent directly to API server.\n\n\n        :param kwargs:\n        :type param: dict\n        :raises ValueError: If type of specified parameter doesn't match\n                            the expected type. Also raised if some basic\n                            validation of passed parameter fails.\n        :raises PushalotException: If required parameter not set.\n        :return: Dictionary with params which can be\n                 sent to API server\n        :rtype: dict"
  },
  {
    "code": "def beginning_of_history(self):\n        u\r\n        self.history_cursor = 0\r\n        if len(self.history) > 0:\r\n            self.l_buffer = self.history[0]",
    "docstring": "u'''Move to the first line in the history."
  },
  {
    "code": "def _validate_sleep(minutes):\n    if isinstance(minutes, six.string_types):\n        if minutes.lower() in ['never', 'off']:\n            return 'Never'\n        else:\n            msg = 'Invalid String Value for Minutes.\\n' \\\n                  'String values must be \"Never\" or \"Off\".\\n' \\\n                  'Passed: {0}'.format(minutes)\n            raise SaltInvocationError(msg)\n    elif isinstance(minutes, bool):\n        if minutes:\n            msg = 'Invalid Boolean Value for Minutes.\\n' \\\n                  'Boolean value \"On\" or \"True\" is not allowed.\\n' \\\n                  'Salt CLI converts \"On\" to boolean True.\\n' \\\n                  'Passed: {0}'.format(minutes)\n            raise SaltInvocationError(msg)\n        else:\n            return 'Never'\n    elif isinstance(minutes, int):\n        if minutes in range(1, 181):\n            return minutes\n        else:\n            msg = 'Invalid Integer Value for Minutes.\\n' \\\n                  'Integer values must be between 1 and 180.\\n' \\\n                  'Passed: {0}'.format(minutes)\n            raise SaltInvocationError(msg)\n    else:\n        msg = 'Unknown Variable Type Passed for Minutes.\\n' \\\n              'Passed: {0}'.format(minutes)\n        raise SaltInvocationError(msg)",
    "docstring": "Helper function that validates the minutes parameter. Can be any number\n    between 1 and 180. Can also be the string values \"Never\" and \"Off\".\n\n    Because \"On\" and \"Off\" get converted to boolean values on the command line\n    it will error if \"On\" is passed\n\n    Returns: The value to be passed to the command"
  },
  {
    "code": "def delete_group_cached(group_id, broker=None):\n    if not broker:\n        broker = get_broker()\n    group_key = '{}:{}:keys'.format(broker.list_key, group_id)\n    group_list = broker.cache.get(group_key)\n    broker.cache.delete_many(group_list)\n    broker.cache.delete(group_key)",
    "docstring": "Delete a group from the cache backend"
  },
  {
    "code": "def LoadServerCertificate(self, server_certificate=None, ca_certificate=None):\n    try:\n      server_certificate.Verify(ca_certificate.GetPublicKey())\n    except rdf_crypto.VerificationError as e:\n      self.server_name = None\n      raise IOError(\"Server cert is invalid: %s\" % e)\n    server_cert_serial = server_certificate.GetSerialNumber()\n    if server_cert_serial < config.CONFIG[\"Client.server_serial_number\"]:\n      raise IOError(\"Server certificate serial number is too old.\")\n    elif server_cert_serial > config.CONFIG[\"Client.server_serial_number\"]:\n      logging.info(\"Server serial number updated to %s\", server_cert_serial)\n      config.CONFIG.Set(\"Client.server_serial_number\", server_cert_serial)\n      config.CONFIG.Write()\n    self.server_name = server_certificate.GetCN()\n    self.server_certificate = server_certificate\n    self.ca_certificate = ca_certificate\n    self.server_public_key = server_certificate.GetPublicKey()\n    self._ClearServerCipherCache()",
    "docstring": "Loads and verifies the server certificate."
  },
  {
    "code": "def IsDirectory(self):\n    if self._stat_object is None:\n      self._stat_object = self._GetStat()\n    if self._stat_object is not None:\n      self.entry_type = self._stat_object.type\n    return self.entry_type == definitions.FILE_ENTRY_TYPE_DIRECTORY",
    "docstring": "Determines if the file entry is a directory.\n\n    Returns:\n      bool: True if the file entry is a directory."
  },
  {
    "code": "def base_id(self):\n        if self._base_id is not None:\n            return self._base_id\n        self.send(Packet(PACKET.COMMON_COMMAND, data=[0x08]))\n        for i in range(0, 10):\n            try:\n                packet = self.receive.get(block=True, timeout=0.1)\n                if packet.packet_type == PACKET.RESPONSE and packet.response == RETURN_CODE.OK and len(packet.response_data) == 4:\n                    self._base_id = packet.response_data\n                    self.receive.put(packet)\n                    break\n                self.receive.put(packet)\n            except queue.Empty:\n                continue\n        return self._base_id",
    "docstring": "Fetches Base ID from the transmitter, if required. Otherwise returns the currently set Base ID."
  },
  {
    "code": "def writer(f):\n    return unicodecsv.writer(f, encoding='utf-8', delimiter=b',', quotechar=b'\"')",
    "docstring": "CSV writer factory for CADA format"
  },
  {
    "code": "def get_day_of_month(datestring):\n    get_day = re.compile(r\"\\d{1,2}(st|nd|rd|th)?\", re.IGNORECASE)\n    day = get_day.search(datestring)\n    the_day = None\n    if day:\n        if bool(re.search(r\"[st|nd|rd|th]\", day.group().lower())):\n            the_day = day.group()[:-2]\n        else:\n            the_day = day.group()\n        if int(the_day) < 10:\n            the_day = add_zero(the_day)\n    return str(the_day)",
    "docstring": "Transforms an ordinal number into plain number with padding zero.\n\n    E.g. 3rd -> 03, or 12th -> 12\n\n    Keyword arguments:\n    datestring -- a string\n\n    Returns:\n    String, or None if the transformation fails"
  },
  {
    "code": "def initialize(**kwargs):\n    global config\n    config_opts = kwargs.setdefault('config',{})\n    if isinstance(config_opts,basestring):\n        config_opts = {'config_filename':config_opts}\n        kwargs['config'] = config_opts\n    if 'environment' in kwargs:\n        config_opts['environment'] = kwargs['environment']\n    config.load_config(**config_opts)\n    if kwargs.get('name'):\n        subconfig = config.get(kwargs.get('name'),{})\n        config.overlay_add(subconfig)\n    config.overlay_add(app_config)",
    "docstring": "Loads the globally shared YAML configuration"
  },
  {
    "code": "def get_asset_content_lookup_session_for_repository(self, repository_id=None):\n        return AssetContentLookupSession(\n            self._provider_manager.get_asset_content_lookup_session_for_repository(repository_id),\n            self._config_map)",
    "docstring": "Gets the ``OsidSession`` associated with the asset content lookup service for\n        the given repository.\n\n        arg:    repository_id (osid.id.Id): the ``Id`` of the repository\n        return: (osid.repository.AssetLookupSession) - the new\n                ``AssetLookupSession``\n        raise:  NotFound - ``repository_id`` not found\n        raise:  NullArgument - ``repository_id`` is ``null``\n        raise:  OperationFailed - ``unable to complete request``\n        raise:  Unimplemented - ``supports_asset_lookup()`` or\n                ``supports_visible_federation()`` is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_asset_lookup()`` and\n        ``supports_visible_federation()`` are ``true``.*"
  },
  {
    "code": "def get_non_magic_cols(self):\n        table_dm = self.data_model.dm[self.dtype]\n        approved_cols = table_dm.index\n        unrecognized_cols = (set(self.df.columns) - set(approved_cols))\n        return unrecognized_cols",
    "docstring": "Find all columns in self.df that are not real MagIC 3 columns.\n\n        Returns\n        --------\n        unrecognized_cols : list"
  },
  {
    "code": "def _process_dimension_kwargs(direction, kwargs):\n    acceptable_keys = ['unit', 'pad', 'lim', 'label']\n    processed_kwargs = {}\n    for k,v in kwargs.items():\n        if k.startswith(direction):\n            processed_key = k.lstrip(direction)\n        else:\n            processed_key = k\n        if processed_key in acceptable_keys:\n            processed_kwargs[processed_key] = v\n    return processed_kwargs",
    "docstring": "process kwargs for AxDimension instances by stripping off the prefix\n    for the appropriate direction"
  },
  {
    "code": "def execute(self, operation, parameters=None, job_id=None):\n        self._query_data = None\n        self._query_job = None\n        client = self.connection._client\n        formatted_operation = _format_operation(operation, parameters=parameters)\n        query_parameters = _helpers.to_query_parameters(parameters)\n        config = job.QueryJobConfig()\n        config.query_parameters = query_parameters\n        config.use_legacy_sql = False\n        self._query_job = client.query(\n            formatted_operation, job_config=config, job_id=job_id\n        )\n        try:\n            self._query_job.result()\n        except google.cloud.exceptions.GoogleCloudError as exc:\n            raise exceptions.DatabaseError(exc)\n        query_results = self._query_job._query_results\n        self._set_rowcount(query_results)\n        self._set_description(query_results.schema)",
    "docstring": "Prepare and execute a database operation.\n\n        .. note::\n            When setting query parameters, values which are \"text\"\n            (``unicode`` in Python2, ``str`` in Python3) will use\n            the 'STRING' BigQuery type. Values which are \"bytes\" (``str`` in\n            Python2, ``bytes`` in Python3), will use using the 'BYTES' type.\n\n            A `~datetime.datetime` parameter without timezone information uses\n            the 'DATETIME' BigQuery type (example: Global Pi Day Celebration\n            March 14, 2017 at 1:59pm). A `~datetime.datetime` parameter with\n            timezone information uses the 'TIMESTAMP' BigQuery type (example:\n            a wedding on April 29, 2011 at 11am, British Summer Time).\n\n            For more information about BigQuery data types, see:\n            https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types\n\n            ``STRUCT``/``RECORD`` and ``REPEATED`` query parameters are not\n            yet supported. See:\n            https://github.com/GoogleCloudPlatform/google-cloud-python/issues/3524\n\n        :type operation: str\n        :param operation: A Google BigQuery query string.\n\n        :type parameters: Mapping[str, Any] or Sequence[Any]\n        :param parameters:\n            (Optional) dictionary or sequence of parameter values.\n\n        :type job_id: str\n        :param job_id: (Optional) The job_id to use. If not set, a job ID\n            is generated at random."
  },
  {
    "code": "def MGMT_ANNOUNCE_BEGIN(self, sAddr, xCommissionerSessionId, listChannelMask, xCount, xPeriod):\n        print '%s call MGMT_ANNOUNCE_BEGIN' % self.port\n        channelMask = ''\n        channelMask = self.__ChannelMaskListToStr(listChannelMask)\n        try:\n            cmd = WPANCTL_CMD + 'commissioner announce-begin %s %s %s %s' % (channelMask, xCount, xPeriod, sAddr)\n            print cmd\n            return self.__sendCommand(cmd) != 'Fail'\n        except Exception, e:\n            ModuleHelper.WriteIntoDebugLogger('MGMT_ANNOUNCE_BEGIN() error: ' + str(e))",
    "docstring": "send MGMT_ANNOUNCE_BEGIN message to a given destination\n\n        Returns:\n            True: successful to send MGMT_ANNOUNCE_BEGIN message.\n            False: fail to send MGMT_ANNOUNCE_BEGIN message."
  },
  {
    "code": "def handle_joined(self, connection, event):\n        nicknames = [s.lstrip(\"@+\") for s in event.arguments()[-1].split()]\n        for nickname in nicknames:\n            self.joined[nickname] = datetime.now()",
    "docstring": "Store join times for current nicknames when we first join."
  },
  {
    "code": "def describe_snapshots(self, *snapshot_ids):\n        snapshot_set = {}\n        for pos, snapshot_id in enumerate(snapshot_ids):\n            snapshot_set[\"SnapshotId.%d\" % (pos + 1)] = snapshot_id\n        query = self.query_factory(\n            action=\"DescribeSnapshots\", creds=self.creds,\n            endpoint=self.endpoint, other_params=snapshot_set)\n        d = query.submit()\n        return d.addCallback(self.parser.snapshots)",
    "docstring": "Describe available snapshots.\n\n        TODO: ownerSet, restorableBySet"
  },
  {
    "code": "def upgradedb(options):\n    version = options.get('version')\n    if version in ['1.1', '1.2']:\n        sh(\"python manage.py migrate maps 0001 --fake\")\n        sh(\"python manage.py migrate avatar 0001 --fake\")\n    elif version is None:\n        print \"Please specify your GeoNode version\"\n    else:\n        print \"Upgrades from version %s are not yet supported.\" % version",
    "docstring": "Add 'fake' data migrations for existing tables from legacy GeoNode versions"
  },
  {
    "code": "def answer_shipping_query(self, shipping_query_id, ok, shipping_options=None, error_message=None):\n        from pytgbot.api_types.sendable.payments import ShippingOption\n        assert_type_or_raise(shipping_query_id, unicode_type, parameter_name=\"shipping_query_id\")\n        assert_type_or_raise(ok, bool, parameter_name=\"ok\")\n        assert_type_or_raise(shipping_options, None, list, parameter_name=\"shipping_options\")\n        assert_type_or_raise(error_message, None, unicode_type, parameter_name=\"error_message\")\n        result = self.do(\"answerShippingQuery\", shipping_query_id=shipping_query_id, ok=ok, shipping_options=shipping_options, error_message=error_message)\n        if self.return_python_objects:\n            logger.debug(\"Trying to parse {data}\".format(data=repr(result)))\n            try:\n                return from_array_list(bool, result, list_level=0, is_builtin=True)\n            except TgApiParseException:\n                logger.debug(\"Failed parsing as primitive bool\", exc_info=True)\n            raise TgApiParseException(\"Could not parse result.\")\n        return result",
    "docstring": "If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.\n\n        https://core.telegram.org/bots/api#answershippingquery\n\n        \n        Parameters:\n        \n        :param shipping_query_id: Unique identifier for the query to be answered\n        :type  shipping_query_id: str|unicode\n        \n        :param ok: Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)\n        :type  ok: bool\n        \n        \n        Optional keyword parameters:\n        \n        :param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options.\n        :type  shipping_options: list of pytgbot.api_types.sendable.payments.ShippingOption\n        \n        :param error_message: Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. \"Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user.\n        :type  error_message: str|unicode\n        \n        Returns:\n\n        :return: On success, True is returned\n        :rtype:  bool"
  },
  {
    "code": "def vars_args(parser):\n    parser.add_argument('--extra-vars',\n                        dest='extra_vars',\n                        help='Extra template variables',\n                        default=[],\n                        type=str,\n                        action='append')\n    parser.add_argument('--extra-vars-file',\n                        dest='extra_vars_file',\n                        help='YAML files full of variables',\n                        default=[],\n                        type=str,\n                        action='append')",
    "docstring": "Add various command line options for external vars"
  },
  {
    "code": "async def get_power_parameters(self):\n        data = await self._handler.power_parameters(system_id=self.system_id)\n        return data",
    "docstring": "Get the power paramters for this node."
  },
  {
    "code": "def __PrintAdditionalImports(self, imports):\n        google_imports = [x for x in imports if 'google' in x]\n        other_imports = [x for x in imports if 'google' not in x]\n        if other_imports:\n            for import_ in sorted(other_imports):\n                self.__printer(import_)\n            self.__printer()\n        if google_imports:\n            for import_ in sorted(google_imports):\n                self.__printer(import_)\n            self.__printer()",
    "docstring": "Print additional imports needed for protorpc."
  },
  {
    "code": "def collectLocations(self):\n        pts = []\n        for l, (value, deltaName) in self.items():\n            pts.append(Location(l))\n        return pts",
    "docstring": "Return a dictionary with all objects."
  },
  {
    "code": "def createbranch(self, project_id, branch, ref):\n        data = {\"id\": project_id, \"branch_name\": branch, \"ref\": ref}\n        request = requests.post(\n            '{0}/{1}/repository/branches'.format(self.projects_url, project_id),\n            headers=self.headers, data=data, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)\n        if request.status_code == 201:\n            return request.json()\n        else:\n            return False",
    "docstring": "Create branch from commit SHA or existing branch\n\n        :param project_id:  The ID of a project\n        :param branch: The name of the branch\n        :param ref: Create branch from commit SHA or existing branch\n        :return: True if success, False if not"
  },
  {
    "code": "def _get_roles_for_request(request, application):\n        roles = application.get_roles_for_person(request.user)\n        if common.is_admin(request):\n            roles.add(\"is_admin\")\n            roles.add('is_authorised')\n        return roles",
    "docstring": "Check the authentication of the current user."
  },
  {
    "code": "def msw(self):\n        return (t for t, c in self.tcmap().items() if len(c) > 1)",
    "docstring": "Return a generator of tokens with more than one sense."
  },
  {
    "code": "def make_executable(script_path):\n    status = os.stat(script_path)\n    os.chmod(script_path, status.st_mode | stat.S_IEXEC)",
    "docstring": "Make `script_path` executable.\n\n    :param script_path: The file to change"
  },
  {
    "code": "def do(cmdline, runas=None, env=None):\n    if not cmdline:\n        raise SaltInvocationError('Command must be specified')\n    path = _rbenv_path(runas)\n    if not env:\n        env = {}\n    env[str('PATH')] = salt.utils.stringutils.to_str(\n        os.pathsep.join((\n            salt.utils.path.join(path, 'shims'),\n            salt.utils.stringutils.to_unicode(os.environ['PATH'])\n        ))\n    )\n    try:\n        cmdline = salt.utils.args.shlex_split(cmdline)\n    except AttributeError:\n        cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline))\n    result = __salt__['cmd.run_all'](\n        cmdline,\n        runas=runas,\n        env=env,\n        python_shell=False\n    )\n    if result['retcode'] == 0:\n        rehash(runas=runas)\n        return result['stdout']\n    else:\n        return False",
    "docstring": "Execute a ruby command with rbenv's shims from the user or the system\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rbenv.do 'gem list bundler'\n        salt '*' rbenv.do 'gem list bundler' deploy"
  },
  {
    "code": "def _WsdlHasMethod(self, method_name):\n    return method_name in self.suds_client.wsdl.services[0].ports[0].methods",
    "docstring": "Determine if the wsdl contains a method.\n\n    Args:\n      method_name: The name of the method to search.\n\n    Returns:\n      True if the method is in the WSDL, otherwise False."
  },
  {
    "code": "def adjust_white_for_scc(cls, rgb_p, rgb_b, rgb_w, p):\n        p_rgb = rgb_p / rgb_b\n        rgb_w = rgb_w * (((1 - p) * p_rgb + (1 + p) / p_rgb) ** 0.5) / (((1 + p) * p_rgb + (1 - p) / p_rgb) ** 0.5)\n        return rgb_w",
    "docstring": "Adjust the white point for simultaneous chromatic contrast.\n\n        :param rgb_p: Cone signals of proxima field.\n        :param rgb_b: Cone signals of background.\n        :param rgb_w: Cone signals of reference white.\n        :param p: Simultaneous contrast/assimilation parameter.\n        :return: Adjusted cone signals for reference white."
  },
  {
    "code": "def ConvertToTemplate(server,template,password=None,alias=None):\n\t\tif alias is None:  alias = clc.v1.Account.GetAlias()\n\t\tif password is None:  password = clc.v1.Server.GetCredentials([server,],alias)[0]['Password']\n\t\tr = clc.v1.API.Call('post','Server/ConvertServerToTemplate', \n\t\t                    { 'AccountAlias': alias, 'Name': server, 'Password': password, 'TemplateAlias': template })\n\t\treturn(r)",
    "docstring": "Converts an existing server into a template.\n\n\t\thttp://www.centurylinkcloud.com/api-docs/v1/#server-convert-server-to-template\n\n\t\t:param server: source server to convert\n\t\t:param template: name of destination template\n\t\t:param password: source server password (optional - will lookup password if None)\n\t\t:param alias: short code for a particular account.  If none will use account's default alias"
  },
  {
    "code": "def run(self):\n        \"Run each middleware function on files\"\n        files = self.get_files()\n        for func in self.middleware:\n            func(files, self)\n        self.files.update(files)\n        return files",
    "docstring": "Run each middleware function on files"
  },
  {
    "code": "def save(self, out, kind=None, **kw):\n        writers.save(self.matrix, self._version, out, kind, **kw)",
    "docstring": "\\\n        Serializes the QR Code in one of the supported formats.\n        The serialization format depends on the filename extension.\n\n        **Common keywords**\n\n\n        ==========    ==============================================================\n        Name          Description\n        ==========    ==============================================================\n        scale         Integer or float indicating the size of a single module.\n                      Default: 1. The interpretation of the scaling factor depends\n                      on the serializer. For pixel-based output (like PNG) the\n                      scaling factor is interepreted as pixel-size (1 = 1 pixel).\n                      EPS interprets ``1`` as 1 point (1/72 inch) per module.\n                      Some serializers (like SVG) accept float values. If the\n                      serializer does not accept float values, the value will be\n                      converted to an integer value (note: int(1.6) == 1).\n        border        Integer indicating the size of the quiet zone.\n                      If set to ``None`` (default), the recommended border size\n                      will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).\n        color         A string or tuple representing a color value for the dark\n                      modules. The default value is \"black\".  The color can be\n                      provided as ``(R, G, B)`` tuple, as web color name\n                      (like \"red\") or in hexadecimal format (``#RGB`` or\n                      ``#RRGGBB``). Some serializers (SVG and PNG) accept an alpha\n                      transparency value like ``#RRGGBBAA``.\n        background    A string or tuple representing a color for the light modules\n                      or background. See \"color\" for valid values.\n                      The default value depends on the serializer. SVG uses no\n                      background color (``None``) by default, other serializers\n                      use \"white\" as default background color.\n        ==========    ==============================================================\n\n\n        **Scalable Vector Graphics (SVG)**\n\n        =============    ==============================================================\n        Name             Description\n        =============    ==============================================================\n        out              Filename or io.BytesIO\n        kind             \"svg\" or \"svgz\" (to create a gzip compressed SVG)\n        scale            integer or float\n        color            Default: \"#000\" (black)\n                         ``None`` is a valid value. If set to ``None``, the resulting\n                         path won't have a \"stroke\" attribute. The \"stroke\" attribute\n                         may be defined via CSS (external).\n                         If an alpha channel is defined, the output depends of the\n                         used SVG version. For SVG versions >= 2.0, the \"stroke\"\n                         attribute will have a value like \"rgba(R, G, B, A)\", otherwise\n                         the path gets another attribute \"stroke-opacity\" to emulate\n                         the alpha channel.\n                         To minimize the document size, the SVG serializer uses\n                         automatically the shortest color representation: If\n                         a value like \"#000000\" is provided, the resulting\n                         document will have a color value of \"#000\". If the color\n                         is \"#FF0000\", the resulting color is not \"#F00\", but\n                         the web color name \"red\".\n        background       Default value ``None``. If this paramater is set to another\n                         value, the resulting image will have another path which\n                         is used to define the background color.\n                         If an alpha channel is used, the resulting path may\n                         have a \"fill-opacity\" attribute (for SVG version < 2.0)\n                         or the \"fill\" attribute has a \"rgba(R, G, B, A)\" value.\n                         See keyword \"color\" for further details.\n        xmldecl          Boolean value (default: ``True``) indicating whether the\n                         document should have an XML declaration header.\n                         Set to ``False`` to omit the header.\n        svgns            Boolean value (default: ``True``) indicating whether the\n                         document should have an explicit SVG namespace declaration.\n                         Set to ``False`` to omit the namespace declaration.\n                         The latter might be useful if the document should be\n                         embedded into a HTML 5 document where the SVG namespace\n                         is implicitly defined.\n        title            String (default: ``None``) Optional title of the generated\n                         SVG document.\n        desc             String (default: ``None``) Optional description of the\n                         generated SVG document.\n        svgid            A string indicating the ID of the SVG document\n                         (if set to ``None`` (default), the SVG element won't have\n                         an ID).\n        svgclass         Default: \"segno\". The CSS class of the SVG document\n                         (if set to ``None``, the SVG element won't have a class).\n        lineclass        Default: \"qrline\". The CSS class of the path element\n                         (which draws the dark modules (if set to ``None``, the path\n                         won't have a class).\n        omitsize         Indicates if width and height attributes should be\n                         omitted (default: ``False``). If these attributes are\n                         omitted, a ``viewBox`` attribute will be added to the\n                         document.\n        unit             Default: ``None``\n                         Inidctaes the unit for width / height and other coordinates.\n                         By default, the unit is unspecified and all values are\n                         in the user space.\n                         Valid values: em, ex, px, pt, pc, cm, mm, in, and percentages\n                         (any string is accepted, this parameter is not validated\n                         by the serializer)\n        encoding         Encoding of the XML document. \"utf-8\" by default.\n        svgversion       SVG version (default: ``None``). If specified (a float),\n                         the resulting document has an explicit \"version\" attribute.\n                         If set to ``None``, the document won't have a \"version\"\n                         attribute. This parameter is not validated.\n        compresslevel    Default: 9. This parameter is only valid, if a compressed\n                         SVG document should be created (file extension \"svgz\").\n                         1 is fastest and produces the least compression, 9 is slowest\n                         and produces the most. 0 is no compression.\n        =============    ==============================================================\n\n\n        **Portable Network Graphics (PNG)**\n\n        =============    ==============================================================\n        Name             Description\n        =============    ==============================================================\n        out              Filename or io.BytesIO\n        kind             \"png\"\n        scale            integer\n        color            Default: \"#000\" (black)\n                         ``None`` is a valid value iff background is not ``None``.\n        background       Default value ``#fff`` (white)\n                         See keyword \"color\" for further details.\n        compresslevel    Default: 9. Integer indicating the compression level\n                         for the ``IDAT`` (data) chunk.\n                         1 is fastest and produces the least compression, 9 is slowest\n                         and produces the most. 0 is no compression.\n        dpi              Default: None. Specifies the DPI value for the image.\n                         By default, the DPI value is unspecified. Please note\n                         that the DPI value is converted into meters (maybe with\n                         rounding errors) since PNG does not support the unit\n                         \"dots per inch\".\n        addad            Boolean value (default: True) to (dis-)allow a \"Software\"\n                         comment indicating that the file was created by Segno.\n        =============    ==============================================================\n\n\n        **Encapsulated PostScript (EPS)**\n\n        =============    ==============================================================\n        Name             Description\n        =============    ==============================================================\n        out              Filename or io.StringIO\n        kind             \"eps\"\n        scale            integer or float\n        color            Default: \"#000\" (black)\n        background       Default value: ``None`` (no background)\n        =============    ==============================================================\n\n\n        **Portable Document Format (PDF)**\n\n        =============    ==============================================================\n        Name             Description\n        =============    ==============================================================\n        out              Filename or io.BytesIO\n        kind             \"pdf\"\n        scale            integer or float\n        compresslevel    Default: 9. Integer indicating the compression level.\n                         1 is fastest and produces the least compression, 9 is slowest\n                         and produces the most. 0 is no compression.\n        =============    ==============================================================\n\n\n        **Text (TXT)**\n\n        Does not support the \"scale\" keyword!\n\n        =============    ==============================================================\n        Name             Description\n        =============    ==============================================================\n        out              Filename or io.StringIO\n        kind             \"txt\"\n        color            Default: \"1\"\n        background       Default: \"0\"\n        =============    ==============================================================\n\n\n        **ANSI escape code**\n\n        Supports the \"border\" keyword, only!\n\n        =============    ==============================================================\n        Name             Description\n        =============    ==============================================================\n        kind             \"ans\"\n        =============    ==============================================================\n\n\n        **Portable Bitmap (PBM)**\n\n        =============    ==============================================================\n        Name             Description\n        =============    ==============================================================\n        out              Filename or io.BytesIO\n        kind             \"pbm\"\n        scale            integer\n        plain            Default: False. Boolean to switch between the P4 and P1 format.\n                         If set to ``True``, the (outdated) P1 serialization format is\n                         used.\n        =============    ==============================================================\n\n\n        **Portable Arbitrary Map (PAM)**\n\n        =============    ==============================================================\n        Name             Description\n        =============    ==============================================================\n        out              Filename or io.BytesIO\n        kind             \"pam\"\n        scale            integer\n        color            Default: \"#000\" (black).\n        background       Default value ``#fff`` (white). Use ``None`` for a transparent\n                         background.\n        =============    ==============================================================\n\n\n        **LaTeX / PGF/TikZ**\n\n        To use the output of this serializer, the ``PGF/TikZ`` (and optionally\n        ``hyperref``) package is required in the LaTeX environment. The\n        serializer itself does not depend on any external packages.\n\n        =============    ==============================================================\n        Name             Description\n        =============    ==============================================================\n        out              Filename or io.StringIO\n        kind             \"tex\"\n        scale            integer or float\n        color            LaTeX color name (default: \"black\"). The color is written\n                         \"at it is\", so ensure that the color is a standard color or it\n                         has been defined in the enclosing LaTeX document.\n        url              Default: ``None``. Optional URL where the QR Code should\n                         point to. Requires the ``hyperref`` package in your LaTeX\n                         environment.\n        =============    ==============================================================\n\n\n        **X BitMap (XBM)**\n\n        =============    ==============================================================\n        Name             Description\n        =============    ==============================================================\n        out              Filename or io.StringIO\n        kind             \"xbm\"\n        scale            integer\n        name             Name of the variable (default: \"img\")\n        =============    ==============================================================\n\n\n        **X PixMap (XPM)**\n\n        =============    ==============================================================\n        Name             Description\n        =============    ==============================================================\n        out              Filename or io.StringIO\n        kind             \"xpm\"\n        scale            integer\n        color            Default: \"#000\" (black).\n        background       Default value ``#fff`` (white)\n                         ``None`` indicates a transparent background.\n        name             Name of the variable (default: \"img\")\n        =============    ==============================================================\n\n\n        :param out: A filename or a writable file-like object with a\n                ``name`` attribute. Use the `kind` parameter if `out` is\n                a :py:class:`io.ByteIO` or :py:class:`io.StringIO` stream which\n                don't have a ``name`` attribute.\n        :param kind: If the desired output format cannot be determined from\n                the ``out`` parameter, this parameter can be used to indicate the\n                serialization format (i.e. \"svg\" to enforce SVG output)\n        :param kw: Any of the supported keywords by the specific serialization\n                method."
  },
  {
    "code": "def _macaroons_for_domain(cookies, domain):\n    req = urllib.request.Request('https://' + domain + '/')\n    cookies.add_cookie_header(req)\n    return httpbakery.extract_macaroons(req)",
    "docstring": "Return any macaroons from the given cookie jar that\n    apply to the given domain name."
  },
  {
    "code": "def cuts_outside(self):\n        for index in self.cut_site:\n            if index < 0 or index > len(self.recognition_site) + 1:\n                return True\n        return False",
    "docstring": "Report whether the enzyme cuts outside its recognition site.\n        Cutting at the very end of the site returns True.\n\n        :returns: Whether the enzyme will cut outside its recognition site.\n        :rtype: bool"
  },
  {
    "code": "def get_example(config, exam_lex):\n    if config.BOOLEAN_STATES[config.config.get('Layout', 'examples')]:\n        return Window(\n            content=BufferControl(\n                buffer_name=\"examples\",\n                lexer=exam_lex))\n    return get_empty()",
    "docstring": "example description window"
  },
  {
    "code": "def get_gene2aart(gene2section2gos, sec2chr):\n        geneid2str = {}\n        for geneid, section2gos_gene in gene2section2gos.items():\n            letters = [abc if s in section2gos_gene else \".\" for s, abc in sec2chr.items()]\n            geneid2str[geneid] = \"\".join(letters)\n        return geneid2str",
    "docstring": "Return a string for each gene representing GO section membership."
  },
  {
    "code": "def extended_sys_state_send(self, vtol_state, landed_state, force_mavlink1=False):\n                return self.send(self.extended_sys_state_encode(vtol_state, landed_state), force_mavlink1=force_mavlink1)",
    "docstring": "Provides state for additional features\n\n                vtol_state                : The VTOL state if applicable. Is set to MAV_VTOL_STATE_UNDEFINED if UAV is not in VTOL configuration. (uint8_t)\n                landed_state              : The landed state. Is set to MAV_LANDED_STATE_UNDEFINED if landed state is unknown. (uint8_t)"
  },
  {
    "code": "def _verify(self, rj, token):\n        keys = self.key_jar.get_jwt_verify_keys(rj.jwt)\n        return rj.verify_compact(token, keys)",
    "docstring": "Verify a signed JSON Web Token\n\n        :param rj: A :py:class:`cryptojwt.jws.JWS` instance\n        :param token: The signed JSON Web Token\n        :return: A verified message"
  },
  {
    "code": "def _trim_zeros_complex(str_complexes, na_rep='NaN'):\n    def separate_and_trim(str_complex, na_rep):\n        num_arr = str_complex.split('+')\n        return (_trim_zeros_float([num_arr[0]], na_rep) +\n                ['+'] +\n                _trim_zeros_float([num_arr[1][:-1]], na_rep) +\n                ['j'])\n    return [''.join(separate_and_trim(x, na_rep)) for x in str_complexes]",
    "docstring": "Separates the real and imaginary parts from the complex number, and\n    executes the _trim_zeros_float method on each of those."
  },
  {
    "code": "def delete(community):\n    deleteform = DeleteCommunityForm(formdata=request.values)\n    ctx = mycommunities_ctx()\n    ctx.update({\n        'deleteform': deleteform,\n        'is_new': False,\n        'community': community,\n    })\n    if deleteform.validate_on_submit():\n        community.delete()\n        db.session.commit()\n        flash(\"Community was deleted.\", category='success')\n        return redirect(url_for('.index'))\n    else:\n        flash(\"Community could not be deleted.\", category='warning')\n        return redirect(url_for('.edit', community_id=community.id))",
    "docstring": "Delete a community."
  },
  {
    "code": "def write_log(self, message):\n        if self.stream_log and not self.ended:\n            self.stream_log.write(message)\n            return True",
    "docstring": "Proxy method for GeneralLogger."
  },
  {
    "code": "def convert(cls, tree):\n        if isinstance(tree, Tree):\n            children = [cls.convert(child) for child in tree]\n            if isinstance(tree, MetricalTree):\n                return cls(tree._cat, children, tree._dep, tree._lstress)\n            elif isinstance(tree, DependencyTree):\n                return cls(tree._cat, children, tree._dep)\n            else:\n                return cls(tree._label, children)\n        else:\n            return tree",
    "docstring": "Convert a tree between different subtypes of Tree.  ``cls`` determines\n        which class will be used to encode the new tree.\n\n        :type tree: Tree\n        :param tree: The tree that should be converted.\n        :return: The new Tree."
  },
  {
    "code": "def create_report(self):\n        data = self.create_data()\n        try:\n            json_string = json.dumps(data)\n        except UnicodeDecodeError as e:\n            log.error('ERROR: While preparing JSON:', exc_info=e)\n            self.debug_bad_encoding(data)\n            raise\n        log_string = re.sub(r'\"repo_token\": \"(.+?)\"',\n                            '\"repo_token\": \"[secure]\"', json_string)\n        log.debug(log_string)\n        log.debug('==\\nReporting %s files\\n==\\n', len(data['source_files']))\n        for source_file in data['source_files']:\n            log.debug('%s - %s/%s', source_file['name'],\n                      sum(filter(None, source_file['coverage'])),\n                      len(source_file['coverage']))\n        return json_string",
    "docstring": "Generate json dumped report for coveralls api."
  },
  {
    "code": "def count_init(self):\n        if self.hidden_state_trajectories is None:\n            raise RuntimeError('HMM model does not have a hidden state trajectory.')\n        n = [traj[0] for traj in self.hidden_state_trajectories]\n        return np.bincount(n, minlength=self.nstates)",
    "docstring": "Compute the counts at the first time step\n\n        Returns\n        -------\n        n : ndarray(nstates)\n            n[i] is the number of trajectories starting in state i"
  },
  {
    "code": "def f_inv(self, z, max_iterations=250, y=None):\n        z = z.copy()\n        y = np.ones_like(z)\n        it = 0\n        update = np.inf\n        while np.abs(update).sum() > 1e-10 and it < max_iterations:\n            fy = self.f(y)\n            fgrady = self.fgrad_y(y)\n            update = (fy - z) / fgrady\n            y -= self.rate * update\n            it += 1\n        return y",
    "docstring": "Calculate the numerical inverse of f. This should be\n        overwritten for specific warping functions where the\n        inverse can be found in closed form.\n\n        :param max_iterations: maximum number of N.R. iterations"
  },
  {
    "code": "def get_error(self):\n        col_offset = -1\n        if self.node is not None:\n            try:\n                col_offset = self.node.col_offset\n            except AttributeError:\n                pass\n        try:\n            exc_name = self.exc.__name__\n        except AttributeError:\n            exc_name = str(self.exc)\n        if exc_name in (None, 'None'):\n            exc_name = 'UnknownError'\n        out = [\"   %s\" % self.expr]\n        if col_offset > 0:\n            out.append(\"    %s^^^\" % ((col_offset)*' '))\n        out.append(str(self.msg))\n        return (exc_name, '\\n'.join(out))",
    "docstring": "Retrieve error data."
  },
  {
    "code": "def rAsciiLine(ifile):\n    _line = ifile.readline().strip()\n    while len(_line) == 0:\n        _line = ifile.readline().strip()\n    return _line",
    "docstring": "Returns the next non-blank line in an ASCII file."
  },
  {
    "code": "def mime_type(self, type_: Optional[MimeType] = None) -> str:\n        key = self._validate_enum(item=type_, enum=MimeType)\n        types = MIME_TYPES[key]\n        return self.random.choice(types)",
    "docstring": "Get a random mime type from list.\n\n        :param type_: Enum object MimeType.\n        :return: Mime type."
  },
  {
    "code": "def inverse(self):\n        result = self.__class__()\n        result.forward = copy.copy(self.reverse)\n        result.reverse = copy.copy(self.forward)\n        return result",
    "docstring": "Returns the inverse bijection."
  },
  {
    "code": "def imports(symbol_file, input_names, param_file=None, ctx=None):\n        sym = symbol.load(symbol_file)\n        if isinstance(input_names, str):\n            input_names = [input_names]\n        inputs = [symbol.var(i) for i in input_names]\n        ret = SymbolBlock(sym, inputs)\n        if param_file is not None:\n            ret.collect_params().load(param_file, ctx=ctx)\n        return ret",
    "docstring": "Import model previously saved by `HybridBlock.export` or\n        `Module.save_checkpoint` as a SymbolBlock for use in Gluon.\n\n        Parameters\n        ----------\n        symbol_file : str\n            Path to symbol file.\n        input_names : list of str\n            List of input variable names\n        param_file : str, optional\n            Path to parameter file.\n        ctx : Context, default None\n            The context to initialize SymbolBlock on.\n\n        Returns\n        -------\n        SymbolBlock\n            SymbolBlock loaded from symbol and parameter files.\n\n        Examples\n        --------\n        >>> net1 = gluon.model_zoo.vision.resnet18_v1(\n        ...     prefix='resnet', pretrained=True)\n        >>> net1.hybridize()\n        >>> x = mx.nd.random.normal(shape=(1, 3, 32, 32))\n        >>> out1 = net1(x)\n        >>> net1.export('net1', epoch=1)\n        >>>\n        >>> net2 = gluon.SymbolBlock.imports(\n        ...     'net1-symbol.json', ['data'], 'net1-0001.params')\n        >>> out2 = net2(x)"
  },
  {
    "code": "def list_roles(self, mount_point=DEFAULT_MOUNT_POINT):\n        api_path = '/v1/auth/{mount_point}/roles'.format(mount_point=mount_point)\n        response = self._adapter.list(\n            url=api_path\n        )\n        return response.json().get('data')",
    "docstring": "List all the roles that are registered with the plugin.\n\n        Supported methods:\n            LIST: /auth/{mount_point}/roles. Produces: 200 application/json\n\n\n        :param mount_point: The \"path\" the azure auth method was mounted on.\n        :type mount_point: str | unicode\n        :return: The \"data\" key from the JSON response of the request.\n        :rtype: dict"
  },
  {
    "code": "def takeoff(self):\n        self.send(at.REF(at.REF.input.start))",
    "docstring": "Sends the takeoff command."
  },
  {
    "code": "def getStringTrackedDeviceProperty(self, unDeviceIndex, prop):\n        fn = self.function_table.getStringTrackedDeviceProperty\n        pError = ETrackedPropertyError()\n        unRequiredBufferLen = fn( unDeviceIndex, prop, None, 0, byref(pError) )\n        if unRequiredBufferLen == 0:\n            return b\"\"\n        pchBuffer = ctypes.create_string_buffer(unRequiredBufferLen)\n        fn( unDeviceIndex, prop, pchBuffer, unRequiredBufferLen, byref(pError) )\n        if pError.value != TrackedProp_Success:\n            raise OpenVRError(str(pError))\n        sResult = bytes(pchBuffer.value)\n        return sResult",
    "docstring": "Returns a string property. If the device index is not valid or the property is not a string type this function will \n        return 0. Otherwise it returns the length of the number of bytes necessary to hold this string including the trailing\n        null. Strings will always fit in buffers of k_unMaxPropertyStringSize characters."
  },
  {
    "code": "def show(self, username):\n        filter = ['(objectclass=posixAccount)', \"(uid={})\".format(username)]\n        return self.client.search(filter)",
    "docstring": "Return a specific user's info in LDIF format."
  },
  {
    "code": "def split_arg_string(string):\n    rv = []\n    for match in re.finditer(r\"('([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'\"\n                             r'|\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"'\n                             r'|\\S+)\\s*', string, re.S):\n        arg = match.group().strip()\n        if arg[:1] == arg[-1:] and arg[:1] in '\"\\'':\n            arg = arg[1:-1].encode('ascii', 'backslashreplace') \\\n                .decode('unicode-escape')\n        try:\n            arg = type(string)(arg)\n        except UnicodeError:\n            pass\n        rv.append(arg)\n    return rv",
    "docstring": "Given an argument string this attempts to split it into small parts."
  },
  {
    "code": "def batch_persist(dfs, tables, *args, **kwargs):\n        from .delay import Delay\n        if 'async' in kwargs:\n            kwargs['async_'] = kwargs['async']\n        execute_keys = ('ui', 'async_', 'n_parallel', 'timeout', 'close_and_notify')\n        execute_kw = dict((k, v) for k, v in six.iteritems(kwargs) if k in execute_keys)\n        persist_kw = dict((k, v) for k, v in six.iteritems(kwargs) if k not in execute_keys)\n        delay = Delay()\n        persist_kw['delay'] = delay\n        for df, table in izip(dfs, tables):\n            if isinstance(table, tuple):\n                table, partition = table\n            else:\n                partition = None\n            df.persist(table, partition=partition, *args, **persist_kw)\n        return delay.execute(**execute_kw)",
    "docstring": "Persist multiple DataFrames into ODPS.\n\n        :param dfs: DataFrames to persist.\n        :param tables: Table names to persist to. Use (table, partition) tuple to store to a table partition.\n        :param args: args for Expr.persist\n        :param kwargs: kwargs for Expr.persist\n\n        :Examples:\n        >>> DataFrame.batch_persist([df1, df2], ['table_name1', ('table_name2', 'partition_name2')], lifecycle=1)"
  },
  {
    "code": "def delete(self, del_id):\n        if MReply2User.delete(del_id):\n            output = {'del_zan': 1}\n        else:\n            output = {'del_zan': 0}\n        return json.dump(output, self)",
    "docstring": "Delete the id"
  },
  {
    "code": "def latlon_round(latlon, spacing=1000):\n    g = latlon_to_grid(latlon)\n    g.easting = (g.easting // spacing) * spacing\n    g.northing = (g.northing // spacing) * spacing\n    return g.latlon()",
    "docstring": "round to nearest grid corner"
  },
  {
    "code": "def load_transactions(input_file, **kwargs):\n    delimiter = kwargs.get('delimiter', '\\t')\n    for transaction in csv.reader(input_file, delimiter=delimiter):\n        yield transaction if transaction else ['']",
    "docstring": "Load transactions and returns a generator for transactions.\n\n    Arguments:\n        input_file -- An input file.\n\n    Keyword arguments:\n        delimiter -- The delimiter of the transaction."
  },
  {
    "code": "def update(self):\n        if not self._remap:\n            return\n        with self._remap_lock:\n            if not self._remap:\n                return\n            self._rules.sort(key=lambda x: x.match_compare_key())\n            for rules in itervalues(self._rules_by_endpoint):\n                rules.sort(key=lambda x: x.build_compare_key())\n            self._remap = False",
    "docstring": "Called before matching and building to keep the compiled rules\n        in the correct order after things changed."
  },
  {
    "code": "def DeleteCampaignFeed(client, campaign_feed):\n  campaign_feed_service = client.GetService('CampaignFeedService', 'v201809')\n  operation = {\n      'operand': campaign_feed,\n      'operator': 'REMOVE'\n  }\n  campaign_feed_service.mutate([operation])",
    "docstring": "Deletes a campaign feed.\n\n  Args:\n    client: an AdWordsClient instance.\n    campaign_feed: the campaign feed to delete."
  },
  {
    "code": "def ruamel_structure(data, validator=None):\n    if isinstance(data, dict):\n        if len(data) == 0:\n            raise exceptions.CannotBuildDocumentsFromEmptyDictOrList(\n                \"Document must be built with non-empty dicts and lists\"\n            )\n        return CommentedMap(\n            [\n                (ruamel_structure(key), ruamel_structure(value))\n                for key, value in data.items()\n            ]\n        )\n    elif isinstance(data, list):\n        if len(data) == 0:\n            raise exceptions.CannotBuildDocumentsFromEmptyDictOrList(\n                \"Document must be built with non-empty dicts and lists\"\n            )\n        return CommentedSeq([ruamel_structure(item) for item in data])\n    elif isinstance(data, bool):\n        return u\"yes\" if data else u\"no\"\n    elif isinstance(data, (int, float)):\n        return str(data)\n    else:\n        if not is_string(data):\n            raise exceptions.CannotBuildDocumentFromInvalidData(\n                (\n                    \"Document must be built from a combination of:\\n\"\n                    \"string, int, float, bool or nonempty list/dict\\n\\n\"\n                    \"Instead, found variable with type '{}': '{}'\"\n                ).format(type(data).__name__, data)\n            )\n        return data",
    "docstring": "Take dicts and lists and return a ruamel.yaml style\n    structure of CommentedMaps, CommentedSeqs and\n    data.\n\n    If a validator is presented and the type is unknown,\n    it is checked against the validator to see if it will\n    turn it back in to YAML."
  },
  {
    "code": "def save(self, path=\"speech\"):\n        if self._data is None:\n            raise Exception(\"There's nothing to save\")\n        extension = \".\" + self.__params[\"format\"]\n        if os.path.splitext(path)[1] != extension:\n            path += extension\n        with open(path, \"wb\") as f:\n            for d in self._data:\n                f.write(d)\n        return path",
    "docstring": "Save data in file.\n\n        Args:\n            path (optional): A path to save file. Defaults to \"speech\".\n                File extension is optional. Absolute path is allowed.\n\n        Returns:\n            The path to the saved file."
  },
  {
    "code": "def date_time_between_dates(\n            self,\n            datetime_start=None,\n            datetime_end=None,\n            tzinfo=None):\n        if datetime_start is None:\n            datetime_start = datetime.now(tzinfo)\n        if datetime_end is None:\n            datetime_end = datetime.now(tzinfo)\n        timestamp = self.generator.random.randint(\n            datetime_to_timestamp(datetime_start),\n            datetime_to_timestamp(datetime_end),\n        )\n        try:\n            if tzinfo is None:\n                pick = datetime.fromtimestamp(timestamp, tzlocal())\n                pick = pick.astimezone(tzutc()).replace(tzinfo=None)\n            else:\n                pick = datetime.fromtimestamp(timestamp, tzinfo)\n        except OverflowError:\n            raise OverflowError(\n                \"You specified an end date with a timestamp bigger than the maximum allowed on this\"\n                \" system. Please specify an earlier date.\",\n            )\n        return pick",
    "docstring": "Takes two DateTime objects and returns a random datetime between the two\n        given datetimes.\n        Accepts DateTime objects.\n\n        :param datetime_start: DateTime\n        :param datetime_end: DateTime\n        :param tzinfo: timezone, instance of datetime.tzinfo subclass\n        :example DateTime('1999-02-02 11:42:52')\n        :return DateTime"
  },
  {
    "code": "def get_queryset(self):\n        kwargs = {}\n        if self.start_at:\n            kwargs.update({'%s__gte' % self.date_field: self.start_at})\n        return super(DateRangeMixin, self).get_queryset().filter(**kwargs)",
    "docstring": "Implements date range filtering on ``created_at``"
  },
  {
    "code": "def pair_tree_creator(meta_id):\n    chunks = []\n    for x in range(0, len(meta_id)):\n        if x % 2:\n            continue\n        if (len(meta_id) - 1) == x:\n            chunk = meta_id[x]\n        else:\n            chunk = meta_id[x: x + 2]\n        chunks.append(chunk)\n    return os.sep + os.sep.join(chunks) + os.sep",
    "docstring": "Splits string into a pairtree path."
  },
  {
    "code": "def _init_predictor(self, input_shapes, type_dict=None):\n        shapes = {name: self.arg_params[name].shape for name in self.arg_params}\n        shapes.update(dict(input_shapes))\n        if self._pred_exec is not None:\n            arg_shapes, _, _ = self.symbol.infer_shape(**shapes)\n            assert arg_shapes is not None, \"Incomplete input shapes\"\n            pred_shapes = [x.shape for x in self._pred_exec.arg_arrays]\n            if arg_shapes == pred_shapes:\n                return\n        pred_exec = self.symbol.simple_bind(\n            self.ctx[0], grad_req='null', type_dict=type_dict, **shapes)\n        pred_exec.copy_params_from(self.arg_params, self.aux_params)\n        _check_arguments(self.symbol)\n        self._pred_exec = pred_exec",
    "docstring": "Initialize the predictor module for running prediction."
  },
  {
    "code": "def get_image(path, search_path):\n    if path.startswith('@'):\n        return StaticImage(path[1:], search_path)\n    if path.startswith('//') or '://' in path:\n        return RemoteImage(path, search_path)\n    if os.path.isabs(path):\n        file_path = utils.find_file(os.path.relpath(\n            path, '/'), config.content_folder)\n    else:\n        file_path = utils.find_file(path, search_path)\n    if not file_path:\n        return ImageNotFound(path, search_path)\n    record = _get_asset(file_path)\n    if record.is_asset:\n        return FileAsset(record, search_path)\n    return LocalImage(record, search_path)",
    "docstring": "Get an Image object. If the path is given as absolute, it will be\n    relative to the content directory; otherwise it will be relative to the\n    search path.\n\n    path -- the image's filename\n    search_path -- a search path for the image (string or list of strings)"
  },
  {
    "code": "async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):\n        start = time.monotonic()\n        loads = loads_fn or self._serializer.loads\n        ns_key = self.build_key(key, namespace=namespace)\n        value = loads(await self._get(ns_key, encoding=self.serializer.encoding, _conn=_conn))\n        logger.debug(\"GET %s %s (%.4f)s\", ns_key, value is not None, time.monotonic() - start)\n        return value if value is not None else default",
    "docstring": "Get a value from the cache. Returns default if not found.\n\n        :param key: str\n        :param default: obj to return when key is not found\n        :param loads_fn: callable alternative to use as loads function\n        :param namespace: str alternative namespace to use\n        :param timeout: int or float in seconds specifying maximum timeout\n            for the operations to last\n        :returns: obj loaded\n        :raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout"
  },
  {
    "code": "def unique(enumeration):\n    duplicates = []\n    for name, member in enumeration.__members__.items():\n        if name != member.name:\n            duplicates.append((name, member.name))\n    if duplicates:\n        duplicate_names = ', '.join(\n                [\"%s -> %s\" % (alias, name) for (alias, name) in duplicates]\n                )\n        raise ValueError('duplicate names found in %r: %s' %\n                (enumeration, duplicate_names)\n                )\n    return enumeration",
    "docstring": "Class decorator that ensures only unique members exist in an enumeration."
  },
  {
    "code": "def _gen_delta_per_sec(self, path, value_delta, time_delta, multiplier,\n                           prettyname, device):\n        if time_delta < 0:\n            return\n        value = (value_delta / time_delta) * multiplier\n        if value > 0.0:\n            self._replace_and_publish(path, prettyname, value, device)",
    "docstring": "Calulates the difference between to point, and scales is to per second."
  },
  {
    "code": "def files_info(self, area_uuid, file_list):\n        path = \"/area/{uuid}/files_info\".format(uuid=area_uuid)\n        file_list = [urlparse.quote(filename) for filename in file_list]\n        response = self._make_request('put', path=path, json=file_list)\n        return response.json()",
    "docstring": "Get information about files\n\n        :param str area_uuid: A RFC4122-compliant ID for the upload area\n        :param list file_list: The names the files in the Upload Area about which we want information\n        :return: an array of file information dicts\n        :rtype: list of dicts\n        :raises UploadApiException: if information could not be obtained"
  },
  {
    "code": "def serialize(self, include_class=True, save_dynamic=False, **kwargs):\n        registry = kwargs.pop('registry', None)\n        if registry is None:\n            registry = dict()\n        if not registry:\n            root = True\n            registry.update({'__root__': self.uid})\n        else:\n            root = False\n        key = self.uid\n        if key not in registry:\n            registry.update({key: None})\n            registry.update({key: super(HasUID, self).serialize(\n                registry=registry,\n                include_class=include_class,\n                save_dynamic=save_dynamic,\n                **kwargs\n            )})\n        if root:\n            return registry\n        return key",
    "docstring": "Serialize nested HasUID instances to a flat dictionary\n\n        **Parameters**:\n\n        * **include_class** - If True (the default), the name of the class\n          will also be saved to the serialized dictionary under key\n          :code:`'__class__'`\n        * **save_dynamic** - If True, dynamic properties are written to\n          the serialized dict (default: False).\n        * You may also specify a **registry** - This is the flat dictionary\n          where UID/HasUID pairs are stored. By default, no registry need\n          be provided; a new dictionary will be created.\n        * Any other keyword arguments will be passed through to the Property\n          serializers."
  },
  {
    "code": "def set_maxrad(self,newrad):\n        if not isinstance(newrad, Quantity):\n            newrad = newrad * u.arcsec\n        for pop in self.poplist:\n            if not pop.is_specific:\n                try:\n                    pop.maxrad = newrad\n                except AttributeError:\n                    pass",
    "docstring": "Sets max allowed radius in populations.\n\n        Doesn't operate via the :class:`stars.Constraint`\n        protocol; rather just rescales the sky positions\n        for the background objects and recalculates\n        sky area, etc."
  },
  {
    "code": "def get_family_nodes(self, family_id, ancestor_levels, descendant_levels, include_siblings):\n        return objects.FamilyNode(self.get_family_node_ids(\n            family_id=family_id,\n            ancestor_levels=ancestor_levels,\n            descendant_levels=descendant_levels,\n            include_siblings=include_siblings)._my_map, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets a portion of the hierarchy for the given family.\n\n        arg:    family_id (osid.id.Id): the ``Id`` to query\n        arg:    ancestor_levels (cardinal): the maximum number of\n                ancestor levels to include. A value of 0 returns no\n                parents in the node.\n        arg:    descendant_levels (cardinal): the maximum number of\n                descendant levels to include. A value of 0 returns no\n                children in the node.\n        arg:    include_siblings (boolean): ``true`` to include the\n                siblings of the given node, ``false`` to omit the\n                siblings\n        return: (osid.relationship.FamilyNode) - a family node\n        raise:  NotFound - ``family_id`` is not found\n        raise:  NullArgument - ``family_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def FreqDist_chart (self):\n        pdata = {}\n        for idx, s_name in enumerate(self.tagdir_data['FreqDistribution']):\n            pdata[s_name] = {}\n            for x, y in self.tagdir_data['FreqDistribution'][s_name].items():\n                try:\n                    pdata[s_name][math.log(float(x))] = y\n                except ValueError:\n                    pass\n        pconfig = {\n            'id': 'FreqDistribution',\n            'title': 'Frequency Distribution',\n            'ylab': 'Fraction of Reads',\n            'xlab': 'Log10(Distance between regions)',\n            'data_labels': ['Reads', 'Percent'],\n            'smooth_points': 500,\n            'smooth_points_sumcounts': False,\n            'yLog' : True\n        }\n        return linegraph.plot(pdata, pconfig)",
    "docstring": "Make the petag.FreqDistribution_1000 plot"
  },
  {
    "code": "def OnAdjustVolume(self, event):\n        self.volume = self.player.audio_get_volume()\n        if event.GetWheelRotation() < 0:\n            self.volume = max(0, self.volume-10)\n        elif event.GetWheelRotation() > 0:\n            self.volume = min(200, self.volume+10)\n        self.player.audio_set_volume(self.volume)",
    "docstring": "Changes video volume"
  },
  {
    "code": "def peek(rlp, index, sedes=None):\n    ll = decode_lazy(rlp)\n    if not isinstance(index, Iterable):\n        index = [index]\n    for i in index:\n        if isinstance(ll, Atomic):\n            raise IndexError('Too many indices given')\n        ll = ll[i]\n    if sedes:\n        return sedes.deserialize(ll)\n    else:\n        return ll",
    "docstring": "Get a specific element from an rlp encoded nested list.\n\n    This function uses :func:`rlp.decode_lazy` and, thus, decodes only the\n    necessary parts of the string.\n\n    Usage example::\n\n        >>> import rlp\n        >>> rlpdata = rlp.encode([1, 2, [3, [4, 5]]])\n        >>> rlp.peek(rlpdata, 0, rlp.sedes.big_endian_int)\n        1\n        >>> rlp.peek(rlpdata, [2, 0], rlp.sedes.big_endian_int)\n        3\n\n    :param rlp: the rlp string\n    :param index: the index of the element to peek at (can be a list for\n                  nested data)\n    :param sedes: a sedes used to deserialize the peeked at object, or `None`\n                  if no deserialization should be performed\n    :raises: :exc:`IndexError` if `index` is invalid (out of range or too many\n             levels)"
  },
  {
    "code": "def fake_KATCP_client_resource_container_factory(\n        KATCPClientResourceContainerClass, fake_options, resources_spec,\n        *args, **kwargs):\n    allow_any_request = fake_options.get('allow_any_request', False)\n    class FakeKATCPClientResourceContainer(KATCPClientResourceContainerClass):\n        def __init__(self, *args, **kwargs):\n            self.fake_client_resource_managers = {}\n            super(FakeKATCPClientResourceContainer, self).__init__(*args, **kwargs)\n        def client_resource_factory(self, res_spec, parent, logger):\n            real_instance = (super(FakeKATCPClientResourceContainer, self)\n                             .client_resource_factory(res_spec, parent, logger) )\n            fkcr, fkcr_manager = fake_KATCP_client_resource_factory(\n                real_instance.__class__, fake_options,\n                res_spec, parent=self, logger=logger)\n            self.fake_client_resource_managers[\n                resource.escape_name(fkcr.name)] = fkcr_manager\n            return fkcr\n    fkcrc = FakeKATCPClientResourceContainer(resources_spec, *args, **kwargs)\n    fkcrc_manager = FakeKATCPClientResourceContainerManager(fkcrc)\n    return (fkcrc, fkcrc_manager)",
    "docstring": "Create a fake KATCPClientResourceContainer-like class and a fake-manager\n\n    Parameters\n    ----------\n    KATCPClientResourceContainerClass : class\n        Subclass of :class:`katcp.resource_client.KATCPClientResourceContainer`\n    fake_options : dict\n        Options for the faking process. Keys:\n            allow_any_request : bool, default False\n            (TODO not implemented behaves as if it were True)\n    resources_spec, *args, **kwargs : passed to KATCPClientResourceContainerClass\n\n    A subclass of the passed-in KATCPClientResourceClassContainer is created that replaces the\n    KATCPClientResource child instances with fakes using fake_KATCP_client_resource_factory()\n    based on the KATCPClientResource class used by `KATCPClientResourceContainerClass`.\n\n    Returns\n    -------\n    (fake_katcp_client_resource_container, fake_katcp_client_resource_container_manager):\n\n    fake_katcp_client_resource_container : instance of faked subclass of\n                                           KATCPClientResourceContainerClass\n    fake_katcp_client_resource_manager : :class:`FakeKATCPClientResourceContainerManager`\n                                         instance\n        Bound to the `fake_katcp_client_resource_container` instance."
  },
  {
    "code": "def get_subspace(self, dims):\n        subspace = []\n        k = 0\n        for variable in self.space_expanded:\n            if k in dims:\n                subspace.append(variable)\n            k += variable.dimensionality_in_model\n        return subspace",
    "docstring": "Extracts subspace from the reference of a list of variables in the inputs\n        of the model."
  },
  {
    "code": "async def open_websocket_client(sock: anyio.abc.SocketStream,\n                                addr,\n                                path: str,\n                                headers: Optional[list] = None,\n                                subprotocols: Optional[list] = None):\n    ws = await create_websocket_client(\n        sock, addr=addr, path=path, headers=headers, subprotocols=subprotocols)\n    try:\n        yield ws\n    finally:\n        await ws.close()",
    "docstring": "Create a websocket on top of a socket."
  },
  {
    "code": "def _linux_nqn():\n    ret = []\n    initiator = '/etc/nvme/hostnqn'\n    try:\n        with salt.utils.files.fopen(initiator, 'r') as _nvme:\n            for line in _nvme:\n                line = line.strip()\n                if line.startswith('nqn.'):\n                    ret.append(line)\n    except IOError as ex:\n        if ex.errno != errno.ENOENT:\n            log.debug(\"Error while accessing '%s': %s\", initiator, ex)\n    return ret",
    "docstring": "Return NVMe NQN from a Linux host."
  },
  {
    "code": "def get_all_instances(include_fastboot=False):\n    if include_fastboot:\n        serial_list = list_adb_devices() + list_fastboot_devices()\n        return get_instances(serial_list)\n    return get_instances(list_adb_devices())",
    "docstring": "Create AndroidDevice instances for all attached android devices.\n\n    Args:\n        include_fastboot: Whether to include devices in bootloader mode or not.\n\n    Returns:\n        A list of AndroidDevice objects each representing an android device\n        attached to the computer."
  },
  {
    "code": "def _convert_markup_basic(self, soup):\n        meta = soup.new_tag('meta', charset='UTF-8')\n        soup.insert(0, meta)\n        css = \"\".join([\n            INSTRUCTIONS_HTML_INJECTION_PRE,\n            self._mathjax_cdn_url,\n            INSTRUCTIONS_HTML_INJECTION_AFTER])\n        css_soup = BeautifulSoup(css)\n        soup.append(css_soup)\n        while soup.find('text'):\n            soup.find('text').name = 'p'\n        while soup.find('heading'):\n            heading = soup.find('heading')\n            heading.name = 'h%s' % heading.attrs.get('level', '1')\n        while soup.find('code'):\n            soup.find('code').name = 'pre'\n        while soup.find('list'):\n            list_ = soup.find('list')\n            type_ = list_.attrs.get('bullettype', 'numbers')\n            list_.name = 'ol' if type_ == 'numbers' else 'ul'",
    "docstring": "Perform basic conversion of instructions markup. This includes\n        replacement of several textual markup tags with their HTML equivalents.\n\n        @param soup: BeautifulSoup instance.\n        @type soup: BeautifulSoup"
  },
  {
    "code": "def create_feature_map(features, feature_indices, output_dir):\n  feature_map = []\n  for name, info in feature_indices:\n    transform_name = features[name]['transform']\n    source_column = features[name]['source_column']\n    if transform_name in [IDENTITY_TRANSFORM, SCALE_TRANSFORM]:\n      feature_map.append((info['index_start'], name))\n    elif transform_name in [ONE_HOT_TRANSFORM, MULTI_HOT_TRANSFORM]:\n      vocab, _ = read_vocab_file(\n          os.path.join(output_dir, VOCAB_ANALYSIS_FILE % source_column))\n      for i, word in enumerate(vocab):\n        if transform_name == ONE_HOT_TRANSFORM:\n          feature_map.append((info['index_start'] + i, '%s=%s' % (source_column, word)))\n        elif transform_name == MULTI_HOT_TRANSFORM:\n          feature_map.append((info['index_start'] + i, '%s has \"%s\"' % (source_column, word)))\n    elif transform_name == IMAGE_TRANSFORM:\n      for i in range(info['size']):\n        feature_map.append((info['index_start'] + i, '%s image feature %d' % (source_column, i)))\n  return feature_map",
    "docstring": "Returns feature_map about the transformed features.\n\n  feature_map includes information such as:\n    1, cat1=0\n    2, cat1=1\n    3, numeric1\n    ...\n  Returns:\n    List in the from\n    [(index, feature_description)]"
  },
  {
    "code": "def hasFeature(featureList, feature):\n    for f in featureList:\n        if f[0] == feature or Features[f[0]] == feature:\n            return f[1]",
    "docstring": "return the controlCode for a feature or None\n\n    @param feature:     feature to look for\n    @param featureList: feature list as returned by L{getFeatureRequest()}\n\n    @return: feature value or None"
  },
  {
    "code": "def update(self, other, **kwargs):\n        from itertools import chain\n        if hasattr(other, 'items'):\n            other = other.items()\n        for (k, v) in chain(other, kwargs.items()):\n            if (\n                    k not in self or\n                    self[k] != v\n            ):\n                self[k] = v",
    "docstring": "Version of ``update`` that doesn't clobber the database so much"
  },
  {
    "code": "def get_thermostat_state_by_name(self, name):\n        self._validate_thermostat_state_name(name)\n        return next((state for state in self.thermostat_states\n                     if state.name.lower() == name.lower()), None)",
    "docstring": "Retrieves a thermostat state object by its assigned name\n\n        :param name: The name of the thermostat state\n        :return: The thermostat state object"
  },
  {
    "code": "def handle_captcha(self, query_params: dict,\n                       html: str,\n                       login_data: dict) -> requests.Response:\n        check_url = get_base_url(html)\n        captcha_url = '{}?s={}&sid={}'.format(self.CAPTCHA_URI,\n                                              query_params['s'],\n                                              query_params['sid'])\n        login_data['captcha_sid'] = query_params['sid']\n        login_data['captcha_key'] = input(self.CAPTCHA_INPUT_PROMPT\n                                          .format(captcha_url))\n        return self.post(check_url, login_data)",
    "docstring": "Handling CAPTCHA request"
  },
  {
    "code": "def channels_history(self, room_id, **kwargs):\n        return self.__call_api_get('channels.history', roomId=room_id, kwargs=kwargs)",
    "docstring": "Retrieves the messages from a channel."
  },
  {
    "code": "def create_cluster_meta(cluster_groups):\n    meta = ClusterMeta()\n    meta.add_field('group')\n    cluster_groups = cluster_groups or {}\n    data = {c: {'group': v} for c, v in cluster_groups.items()}\n    meta.from_dict(data)\n    return meta",
    "docstring": "Return a ClusterMeta instance with cluster group support."
  },
  {
    "code": "def convert_stress_to_mass(q, width, length, gravity):\n    mass = q * width * length / gravity\n    return mass",
    "docstring": "Converts a foundation stress to an equivalent mass.\n\n    :param q: applied stress [Pa]\n    :param width: foundation width [m]\n    :param length: foundation length [m]\n    :param gravity: applied gravitational acceleration [m/s2]\n    :return:"
  },
  {
    "code": "def is_instance_avg_req_latency_too_high(self, inst_id):\n        avg_lat, avg_lat_others = self.getLatencies()\n        if not avg_lat or not avg_lat_others:\n            return False\n        d = avg_lat - avg_lat_others\n        if d < self.Omega:\n            return False\n        if inst_id == self.instances.masterId:\n            logger.info(\"{}{} found difference between master's and \"\n                        \"backups's avg latency {} to be higher than the \"\n                        \"threshold\".format(MONITORING_PREFIX, self, d))\n            logger.trace(\n                \"{}'s master's avg request latency is {} and backup's \"\n                \"avg request latency is {}\".format(self, avg_lat, avg_lat_others))\n        return True",
    "docstring": "Return whether the average request latency of an instance is\n        greater than the acceptable threshold"
  },
  {
    "code": "def _infer_precision(base_precision, bins):\n    for precision in range(base_precision, 20):\n        levels = [_round_frac(b, precision) for b in bins]\n        if algos.unique(levels).size == bins.size:\n            return precision\n    return base_precision",
    "docstring": "Infer an appropriate precision for _round_frac"
  },
  {
    "code": "def gene_id_check(genes, errors, columns, row_number):\n    message = (\"Gene '{value}' in column {col} and row {row} does not \"\n               \"appear in the metabolic model.\")\n    for column in columns:\n        if \"gene\" in column['header'] and column['value'] not in genes:\n            message = message.format(\n                value=column['value'],\n                row=row_number,\n                col=column['number'])\n            errors.append({\n                'code': 'bad-value',\n                'message': message,\n                'row-number': row_number,\n                'column-number': column['number'],\n            })",
    "docstring": "Validate gene identifiers against a known set.\n\n    Parameters\n    ----------\n    genes : set\n        The known set of gene identifiers.\n    errors :\n        Passed by goodtables.\n    columns :\n        Passed by goodtables.\n    row_number :\n        Passed by goodtables."
  },
  {
    "code": "def match_keyword(self, keyword, string_match_type=DEFAULT_STRING_MATCH_TYPE, match=True):\n        match_value = self._get_string_match_value(keyword, string_match_type)\n        for field_name in self._keyword_fields:\n            if field_name not in self._keyword_terms:\n                self._keyword_terms[field_name] = {'$in': list()}\n            self._keyword_terms[field_name]['$in'].append(match_value)",
    "docstring": "Adds a keyword to match.\n\n        Multiple keywords can be added to perform a boolean ``OR`` among\n        them. A keyword may be applied to any of the elements defined in\n        this object such as the display name, description or any method\n        defined in an interface implemented by this object.\n\n        arg:    keyword (string): keyword to match\n        arg:    string_match_type (osid.type.Type): the string match\n                type\n        arg:    match (boolean): ``true`` for a positive match,\n                ``false`` for a negative match\n        raise:  InvalidArgument - ``keyword`` is not of\n                ``string_match_type``\n        raise:  NullArgument - ``keyword`` or ``string_match_type`` is\n                ``null``\n        raise:  Unsupported -\n                ``supports_string_match_type(string_match_type)`` is\n                ``false``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def write_iocs(self, directory=None, source=None):\n        if not source:\n            source = self.iocs_10\n        if len(source) < 1:\n            log.error('no iocs available to write out')\n            return False\n        if not directory:\n            directory = os.getcwd()\n        if os.path.isfile(directory):\n            log.error('cannot writes iocs to a directory')\n            return False\n        source_iocs = set(source.keys())\n        source_iocs = source_iocs.difference(self.pruned_11_iocs)\n        source_iocs = source_iocs.difference(self.null_pruned_iocs)\n        if not source_iocs:\n            log.error('no iocs available to write out after removing pruned/null iocs')\n            return False\n        utils.safe_makedirs(directory)\n        output_dir = os.path.abspath(directory)\n        log.info('Writing IOCs to %s' % (str(output_dir)))\n        for iocid in source_iocs:\n            ioc_obj = source[iocid]\n            ioc_obj.write_ioc_to_file(output_dir=output_dir, force=True)\n        return True",
    "docstring": "Serializes IOCs to a directory.\n\n        :param directory: Directory to write IOCs to.  If not provided, the current working directory is used.\n        :param source: Dictionary contianing iocid -> IOC mapping.  Defaults to self.iocs_10. This is not normally modifed by a user for this class.\n        :return:"
  },
  {
    "code": "def _group(tlist, cls, match,\n           valid_prev=lambda t: True,\n           valid_next=lambda t: True,\n           post=None,\n           extend=True,\n           recurse=True\n           ):\n    tidx_offset = 0\n    pidx, prev_ = None, None\n    for idx, token in enumerate(list(tlist)):\n        tidx = idx - tidx_offset\n        if token.is_whitespace:\n            continue\n        if recurse and token.is_group and not isinstance(token, cls):\n            _group(token, cls, match, valid_prev, valid_next, post, extend)\n        if match(token):\n            nidx, next_ = tlist.token_next(tidx)\n            if prev_ and valid_prev(prev_) and valid_next(next_):\n                from_idx, to_idx = post(tlist, pidx, tidx, nidx)\n                grp = tlist.group_tokens(cls, from_idx, to_idx, extend=extend)\n                tidx_offset += to_idx - from_idx\n                pidx, prev_ = from_idx, grp\n                continue\n        pidx, prev_ = tidx, token",
    "docstring": "Groups together tokens that are joined by a middle token. i.e. x < y"
  },
  {
    "code": "def dumps(obj, preserve=False):\n    f = StringIO()\n    dump(obj, f, preserve)\n    return f.getvalue()",
    "docstring": "Stringifies a dict as toml\n\n    :param obj: the object to be dumped into toml\n    :param preserve: optional flag to preserve the inline table in result"
  },
  {
    "code": "def read_id_list(filepath):\n    if not filepath:\n        return None\n    id_list = []\n    with open(filepath) as f:\n        for line in f:\n            line = line.rstrip()\n            if not re.match('^[0-9]{8}$', line):\n                raise('Each line in whitelist or blacklist is expected '\n                      'to contain an eight digit ID, and nothing else.')\n            else:\n                id_list.append(line)\n    return id_list",
    "docstring": "Get project member id from a file.\n\n    :param filepath: This field is the path of file to read."
  },
  {
    "code": "def blacked_out(self):\n        if self.state is ConnectionStates.DISCONNECTED:\n            if time.time() < self.last_attempt + self._reconnect_backoff:\n                return True\n        return False",
    "docstring": "Return true if we are disconnected from the given node and can't\n        re-establish a connection yet"
  },
  {
    "code": "def content_get(self, cid, nid=None):\n        r = self.request(\n            method=\"content.get\",\n            data={\"cid\": cid},\n            nid=nid\n        )\n        return self._handle_error(r, \"Could not get post {}.\".format(cid))",
    "docstring": "Get data from post `cid` in network `nid`\n\n        :type  nid: str\n        :param nid: This is the ID of the network (or class) from which\n            to query posts. This is optional and only to override the existing\n            `network_id` entered when created the class\n        :type  cid: str|int\n        :param cid: This is the post ID which we grab\n        :returns: Python object containing returned data"
  },
  {
    "code": "def request(self, message, timeout=False, *args, **kwargs):\n        if not self.connection_pool.full():\n            self.connection_pool.put(self._register_socket())\n        _socket = self.connection_pool.get()\n        if timeout or timeout is None:\n            _socket.settimeout(timeout)\n        data = self.send_and_receive(_socket, message, *args, **kwargs)\n        if self.connection.proto in Socket.streams:\n            _socket.shutdown(socket.SHUT_RDWR)\n        return Response(data, None, None)",
    "docstring": "Populate connection pool, send message, return BytesIO, and cleanup"
  },
  {
    "code": "def stylize(ax, name, feature):\n    ax.set_ylabel(feature)\n    ax.set_title(name, fontsize='small')",
    "docstring": "Stylization modifications to the plots"
  },
  {
    "code": "def current_arg_text(self) -> str:\n        if self._current_arg_text is None:\n            self._current_arg_text = Message(\n                self.current_arg).extract_plain_text()\n        return self._current_arg_text",
    "docstring": "Plain text part in the current argument, without any CQ codes."
  },
  {
    "code": "def VariantDir(self, variant_dir, src_dir, duplicate=1):\n        if not isinstance(src_dir, SCons.Node.Node):\n            src_dir = self.Dir(src_dir)\n        if not isinstance(variant_dir, SCons.Node.Node):\n            variant_dir = self.Dir(variant_dir)\n        if src_dir.is_under(variant_dir):\n            raise SCons.Errors.UserError(\"Source directory cannot be under variant directory.\")\n        if variant_dir.srcdir:\n            if variant_dir.srcdir == src_dir:\n                return\n            raise SCons.Errors.UserError(\"'%s' already has a source directory: '%s'.\"%(variant_dir, variant_dir.srcdir))\n        variant_dir.link(src_dir, duplicate)",
    "docstring": "Link the supplied variant directory to the source directory\n        for purposes of building files."
  },
  {
    "code": "def CallFunction(self):\n    if self._xmlrpc_proxy is None:\n      return None\n    rpc_call = getattr(self._xmlrpc_proxy, self._RPC_FUNCTION_NAME, None)\n    if rpc_call is None:\n      return None\n    try:\n      return rpc_call()\n    except (\n        expat.ExpatError, SocketServer.socket.error,\n        xmlrpclib.Fault) as exception:\n      logger.warning('Unable to make RPC call with error: {0!s}'.format(\n          exception))\n      return None",
    "docstring": "Calls the function via RPC."
  },
  {
    "code": "def name_tree(tree):\n    existing_names = Counter((_.name for _ in tree.traverse() if _.name))\n    if sum(1 for _ in tree.traverse()) == len(existing_names):\n        return\n    i = 0\n    existing_names = Counter()\n    for node in tree.traverse('preorder'):\n        name = node.name if node.is_leaf() else ('root' if node.is_root() else None)\n        while name is None or name in existing_names:\n            name = '{}{}'.format('t' if node.is_leaf() else 'n', i)\n            i += 1\n        node.name = name\n        existing_names[name] += 1",
    "docstring": "Names all the tree nodes that are not named or have non-unique names, with unique names.\n\n    :param tree: tree to be named\n    :type tree: ete3.Tree\n\n    :return: void, modifies the original tree"
  },
  {
    "code": "def attr(self, name, lineno=None):\n        return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)",
    "docstring": "Return an attribute node for the current extension.  This is useful\n        to pass constants on extensions to generated template code.\n\n        ::\n\n            self.attr('_my_attribute', lineno=lineno)"
  },
  {
    "code": "def get_user(self) -> FacebookUser:\n        return FacebookUser(\n            self._event['sender']['id'],\n            self.get_page_id(),\n            self._facebook,\n            self,\n        )",
    "docstring": "Generate a Facebook user instance"
  },
  {
    "code": "def find_table_links(self):\n        html = urlopen(self.model_url).read()\n        doc = lh.fromstring(html)\n        href_list = [area.attrib['href'] for area in doc.cssselect('map area')]\n        tables = self._inception_table_links(href_list)\n        return tables",
    "docstring": "When given a url, this function will find all the available table names\n        for that EPA dataset."
  },
  {
    "code": "def get_input_stream(environ, safe_fallback=True):\n    stream = environ['wsgi.input']\n    content_length = get_content_length(environ)\n    if environ.get('wsgi.input_terminated'):\n        return stream\n    if content_length is None:\n        return safe_fallback and _empty_stream or stream\n    return LimitedStream(stream, content_length)",
    "docstring": "Returns the input stream from the WSGI environment and wraps it\n    in the most sensible way possible.  The stream returned is not the\n    raw WSGI stream in most cases but one that is safe to read from\n    without taking into account the content length.\n\n    .. versionadded:: 0.9\n\n    :param environ: the WSGI environ to fetch the stream from.\n    :param safe: indicates weather the function should use an empty\n                 stream as safe fallback or just return the original\n                 WSGI input stream if it can't wrap it safely.  The\n                 default is to return an empty string in those cases."
  },
  {
    "code": "def stop_animation(self, sprites):\n        if isinstance(sprites, list) is False:\n            sprites = [sprites]\n        for sprite in sprites:\n            self.tweener.kill_tweens(sprite)",
    "docstring": "stop animation without firing on_complete"
  },
  {
    "code": "def scp(cls, project):\n        if project is None:\n            _scp(None)\n            cls.oncpchange.emit(gcp())\n        elif not project.is_main:\n            if project.main is not _current_project:\n                _scp(project.main, True)\n                cls.oncpchange.emit(project.main)\n            _scp(project)\n            cls.oncpchange.emit(project)\n        else:\n            _scp(project, True)\n            cls.oncpchange.emit(project)\n            sp = project[:]\n            _scp(sp)\n            cls.oncpchange.emit(sp)",
    "docstring": "Set the current project\n\n        Parameters\n        ----------\n        project: Project or None\n            The project to set. If it is None, the current subproject is set\n            to empty. If it is a sub project (see:attr:`Project.is_main`),\n            the current subproject is set to this project. Otherwise it\n            replaces the current main project\n\n        See Also\n        --------\n        scp: The global version for setting the current project\n        gcp: Returns the current project\n        project: Creates a new project"
  },
  {
    "code": "def marshal(self, values):\n        if values is not None:\n            return [super(EntityCollection, self).marshal(v) for v in values]",
    "docstring": "Turn a list of entities into a list of dictionaries.\n\n        :param values: The entities to serialize.\n        :type values: List[stravalib.model.BaseEntity]\n        :return: List of dictionaries of attributes\n        :rtype: List[Dict[str, Any]]"
  },
  {
    "code": "def generate(self, signature_data):\n        result = Result()\n        for rule in self.pipeline:\n            rule_name = rule.__class__.__name__\n            try:\n                if rule.predicate(signature_data, result):\n                    rule.action(signature_data, result)\n            except Exception as exc:\n                if self.error_handler:\n                    self.error_handler(\n                        signature_data,\n                        exc_info=sys.exc_info(),\n                        extra={'rule': rule_name}\n                    )\n                result.info(rule_name, 'Rule failed: %s', exc)\n        return result",
    "docstring": "Takes data and returns a signature\n\n        :arg dict signature_data: data to use to generate a signature\n\n        :returns: ``Result`` instance"
  },
  {
    "code": "def build(self):\n        if self.json['sys']['type'] == 'Array':\n            return self._build_array()\n        return self._build_item(self.json)",
    "docstring": "Creates the objects from the JSON response."
  },
  {
    "code": "def validate(self, value, model=None, context=None):\n        length = len(str(value))\n        params = dict(min=self.min, max=self.max)\n        if self.min and self.max is None:\n            if length < self.min:\n                return Error(self.too_short, params)\n        if self.max and self.min is None:\n            if length > self.max:\n                return Error(self.too_long, params)\n        if self.min and self.max:\n            if length < self.min or length > self.max:\n                return Error(self.not_in_range, params)\n        return Error()",
    "docstring": "Validate\n        Perform value validation against validation settings and return\n        simple result object\n\n        :param value:           str, value to check\n        :param model:           parent model being validated\n        :param context:         object or None, validation context\n        :return:                shiftschema.results.SimpleResult"
  },
  {
    "code": "def _search(self):\n        results = []\n        for _id in self.doc_dict:\n            entry = self.doc_dict[_id]\n            if entry.doc is not None:\n                results.append(entry.merged_dict)\n        return results",
    "docstring": "Returns all documents in the doc dict.\n\n        This function is not a part of the DocManager API, and is only used\n        to simulate searching all documents from a backend."
  },
  {
    "code": "def get_new_names_by_old():\n        newdict = {}\n        for label_type, label_names in Labels.LABEL_NAMES.items():\n            for oldname in label_names[1:]:\n                newdict[oldname] = Labels.LABEL_NAMES[label_type][0]\n        return newdict",
    "docstring": "Return dictionary, new label name indexed by old label name."
  },
  {
    "code": "def check_sim_out(self):\n        now = time.time()\n        if now - self.last_sim_send_time < 0.02 or self.rc_channels_scaled is None:\n            return\n        self.last_sim_send_time = now\n        servos = []\n        for ch in range(1,9):\n            servos.append(self.scale_channel(ch, getattr(self.rc_channels_scaled, 'chan%u_scaled' % ch)))\n        servos.extend([0,0,0, 0,0,0])\n        buf = struct.pack('<14H', *servos)\n        try:\n            self.sim_out.send(buf)\n        except socket.error as e:\n            if not e.errno in [ errno.ECONNREFUSED ]:\n                raise\n            return",
    "docstring": "check if we should send new servos to flightgear"
  },
  {
    "code": "def osPaste(self):\n        from .InputEmulation import Keyboard\n        k = Keyboard()\n        k.keyDown(\"{CTRL}\")\n        k.type(\"v\")\n        k.keyUp(\"{CTRL}\")",
    "docstring": "Triggers the OS \"paste\" keyboard shortcut"
  },
  {
    "code": "def randmatrix(m, n, random_seed=None):\n    val = np.sqrt(6.0 / (m + n))\n    np.random.seed(random_seed)\n    return np.random.uniform(-val, val, size=(m, n))",
    "docstring": "Creates an m x n matrix of random values drawn using\n    the Xavier Glorot method."
  },
  {
    "code": "def empowerment(iface, priority=0):\n    def _deco(cls):\n        cls.powerupInterfaces = (\n            tuple(getattr(cls, 'powerupInterfaces', ())) +\n            ((iface, priority),))\n        implementer(iface)(cls)\n        return cls\n    return _deco",
    "docstring": "Class decorator for indicating a powerup's powerup interfaces.\n\n    The class will also be declared as implementing the interface.\n\n    @type iface: L{zope.interface.Interface}\n    @param iface: The powerup interface.\n\n    @type priority: int\n    @param priority: The priority the powerup will be installed at."
  },
  {
    "code": "def add_reporter(self, reporter):\n        with self._lock:\n            reporter.init(list(self.metrics.values()))\n            self._reporters.append(reporter)",
    "docstring": "Add a MetricReporter"
  },
  {
    "code": "def create_env(self):\n        virtualenv(self.env, _err=sys.stderr)\n        os.mkdir(self.env_bin)",
    "docstring": "Create a virtual environment."
  },
  {
    "code": "def _SyncAttributes(self):\n    for attribute, value_array in iteritems(self.new_attributes):\n      if not attribute.versioned or self.age_policy == NEWEST_TIME:\n        value = value_array[-1]\n        self.synced_attributes[attribute] = [\n            LazyDecoder(decoded=value, age=value.age)\n        ]\n      else:\n        synced_value_array = self.synced_attributes.setdefault(attribute, [])\n        for value in value_array:\n          synced_value_array.append(LazyDecoder(decoded=value, age=value.age))\n        synced_value_array.sort(key=lambda x: x.age, reverse=True)\n    self.new_attributes = {}\n    self._to_delete.clear()\n    self._dirty = False\n    self._new_version = False",
    "docstring": "Sync the new attributes to the synced attribute cache.\n\n    This maintains object validity."
  },
  {
    "code": "def notify(self, instance=None, **kwargs):\n        notified = {}\n        for notification_cls in self.registry.values():\n            notification = notification_cls()\n            if notification.notify(instance=instance, **kwargs):\n                notified.update({notification_cls.name: instance._meta.label_lower})\n        return notified",
    "docstring": "A wrapper to call notification.notify for each notification\n        class associated with the given model instance.\n\n        Returns a dictionary of {notification.name: model, ...}\n        including only notifications sent."
  },
  {
    "code": "def login(self):\n        authtype = self.lookup(self.profile, 'authtype')\n        if authtype is None:\n            cert = self.lookup(self.profile, 'cert')\n            if cert and os.path.isfile(os.path.expanduser(cert)):\n                authtype = 'ssl'\n        if authtype == 'kerberos':\n            result = yield self._gssapi_login()\n        elif authtype == 'ssl':\n            result = yield self._ssl_login()\n        else:\n            raise NotImplementedError('unsupported auth: %s' % authtype)\n        self.session_id = result['session-id']\n        self.session_key = result['session-key']\n        self.callnum = 0\n        defer.returnValue(True)",
    "docstring": "Return True if we successfully logged into this Koji hub.\n\n        We support GSSAPI and SSL Client authentication (not the old-style\n        krb-over-xmlrpc krbLogin method).\n\n        :returns: deferred that when fired returns True"
  },
  {
    "code": "def setUpClassDef(self, service):\n        assert isinstance(service, WSDLTools.Service), \\\n            'expecting WSDLTools.Service instance'\n        s = self._services[service.name].classdef\n        print >>s, 'class %s(%s):' %(self.getClassName(service.name), self.base_class_name)\n        print >>s, '%ssoapAction = {}' % self.getIndent(level=1)\n        print >>s, '%swsAction = {}' % self.getIndent(level=1)\n        print >>s, '%sroot = {}' % self.getIndent(level=1)",
    "docstring": "use soapAction dict for WS-Action input, setup wsAction\n        dict for grabbing WS-Action output values."
  },
  {
    "code": "def add_codes(err_cls):\n    class ErrorsWithCodes(object):\n        def __getattribute__(self, code):\n            msg = getattr(err_cls, code)\n            return '[{code}] {msg}'.format(code=code, msg=msg)\n    return ErrorsWithCodes()",
    "docstring": "Add error codes to string messages via class attribute names."
  },
  {
    "code": "def restore(self, state):\n        storage_data = state.get(u'storage_data', [])\n        streaming_data = state.get(u'streaming_data', [])\n        if len(storage_data) > self.storage_length or len(streaming_data) > self.streaming_length:\n            raise ArgumentError(\"Cannot restore InMemoryStorageEngine, too many readings\",\n                                storage_size=len(storage_data), storage_max=self.storage_length,\n                                streaming_size=len(streaming_data), streaming_max=self.streaming_length)\n        self.storage_data = [IOTileReading.FromDict(x) for x in storage_data]\n        self.streaming_data = [IOTileReading.FromDict(x) for x in streaming_data]",
    "docstring": "Restore the state of this InMemoryStorageEngine from a dict."
  },
  {
    "code": "def _call(self, x, out=None):\n        wrapped_x = self.prod_op.domain.element([x], cast=False)\n        return self.prod_op(wrapped_x, out=out)",
    "docstring": "Evaluate all operators in ``x`` and broadcast."
  },
  {
    "code": "def restart(self, *args, **kwargs):\n        self.stop()\n        try:\n            self.start(*args, **kwargs)\n        except IOError:\n            raise",
    "docstring": "Restart the daemon"
  },
  {
    "code": "def find_free_port():\n    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:\n        sock.bind(('', 0))\n        return sock.getsockname()[1]",
    "docstring": "Finds a free port."
  },
  {
    "code": "def file_or_token(value):\n    if isfile(value):\n        with open(value) as fd:\n            return fd.read().strip()\n    if any(char in value for char in '/\\\\.'):\n        raise ValueError()\n    return value",
    "docstring": "If value is a file path and the file exists its contents are stripped and returned,\n    otherwise value is returned."
  },
  {
    "code": "def unwatch_zone(self, zone_id):\n        self._watched_zones.remove(zone_id)\n        return (yield from\n                self._send_cmd(\"WATCH %s OFF\" % (zone_id.device_str(), )))",
    "docstring": "Remove a zone from the watchlist."
  },
  {
    "code": "def assistant_from_yaml(cls, source, y, superassistant, fully_loaded=True,\n                            role=settings.DEFAULT_ASSISTANT_ROLE):\n        name = os.path.splitext(os.path.basename(source))[0]\n        yaml_checker.check(source, y)\n        assistant = yaml_assistant.YamlAssistant(name, y, source, superassistant,\n            fully_loaded=fully_loaded, role=role)\n        return assistant",
    "docstring": "Constructs instance of YamlAssistant loaded from given structure y, loaded\n        from source file source.\n\n        Args:\n            source: path to assistant source file\n            y: loaded yaml structure\n            superassistant: superassistant of this assistant\n        Returns:\n            YamlAssistant instance constructed from y with source file source\n        Raises:\n            YamlError: if the assistant is malformed"
  },
  {
    "code": "def get_file_row_generator(file_path, separator, encoding=None):\n    with open(file_path, encoding=encoding) as file_object:\n        for line in file_object:\n            words = line.strip().split(separator)\n            yield words",
    "docstring": "Reads an separated value file row by row.\n\n    Inputs: - file_path: The path of the separated value format file.\n            - separator: The delimiter among values (e.g. \",\", \"\\t\", \" \")\n            - encoding: The encoding used in the stored text.\n\n    Yields: - words: A list of strings corresponding to each of the file's rows."
  },
  {
    "code": "def hitail(E: np.ndarray, diffnumflux: np.ndarray, isimE0: np.ndarray, E0: np.ndarray,\n           Bhf: np.ndarray, bh: float, verbose: int = 0):\n    Bh = np.empty_like(E0)\n    for iE0 in np.arange(E0.size):\n        Bh[iE0] = Bhf[iE0]*diffnumflux[isimE0[iE0], iE0]\n    het = Bh*(E[:, None] / E0)**-bh\n    het[E[:, None] < E0] = 0.\n    if verbose > 0:\n        print('Bh: ' + (' '.join('{:0.1f}'.format(b) for b in Bh)))\n    return het",
    "docstring": "strickland 1993 said 0.2, but 0.145 gives better match to peak flux at 2500 = E0"
  },
  {
    "code": "def update_vrf_table_links(self, vrf_table, new_imp_rts,\n                               removed_imp_rts):\n        assert vrf_table\n        if new_imp_rts:\n            self._link_vrf_table(vrf_table, new_imp_rts)\n        if removed_imp_rts:\n            self._remove_links_to_vrf_table_for_rts(vrf_table,\n                                                    removed_imp_rts)",
    "docstring": "Update mapping from RT to VRF table."
  },
  {
    "code": "def dtdEntity(self, name):\n        ret = libxml2mod.xmlGetDtdEntity(self._o, name)\n        if ret is None:raise treeError('xmlGetDtdEntity() failed')\n        __tmp = xmlEntity(_obj=ret)\n        return __tmp",
    "docstring": "Do an entity lookup in the DTD entity hash table and"
  },
  {
    "code": "def get_average_voltage(self, min_voltage=None, max_voltage=None):\n        pairs_in_range = self._select_in_voltage_range(min_voltage,\n                                                       max_voltage)\n        if len(pairs_in_range) == 0:\n            return 0\n        total_cap_in_range = sum([p.mAh for p in pairs_in_range])\n        total_edens_in_range = sum([p.mAh * p.voltage for p in pairs_in_range])\n        return total_edens_in_range / total_cap_in_range",
    "docstring": "Average voltage for path satisfying between a min and max voltage.\n\n        Args:\n            min_voltage (float): The minimum allowable voltage for a given\n                step.\n            max_voltage (float): The maximum allowable voltage allowable for a\n                given step.\n\n        Returns:\n            Average voltage in V across the insertion path (a subset of the\n            path can be chosen by the optional arguments)"
  },
  {
    "code": "def mediated_transfer_async(\n            self,\n            token_network_identifier: TokenNetworkID,\n            amount: PaymentAmount,\n            target: TargetAddress,\n            identifier: PaymentID,\n            fee: FeeAmount = MEDIATION_FEE,\n            secret: Secret = None,\n            secret_hash: SecretHash = None,\n    ) -> PaymentStatus:\n        if secret is None:\n            if secret_hash is None:\n                secret = random_secret()\n            else:\n                secret = EMPTY_SECRET\n        payment_status = self.start_mediated_transfer_with_secret(\n            token_network_identifier=token_network_identifier,\n            amount=amount,\n            fee=fee,\n            target=target,\n            identifier=identifier,\n            secret=secret,\n            secret_hash=secret_hash,\n        )\n        return payment_status",
    "docstring": "Transfer `amount` between this node and `target`.\n\n        This method will start an asynchronous transfer, the transfer might fail\n        or succeed depending on a couple of factors:\n\n            - Existence of a path that can be used, through the usage of direct\n              or intermediary channels.\n            - Network speed, making the transfer sufficiently fast so it doesn't\n              expire."
  },
  {
    "code": "def write_events(self, outname):\n        self.make_output_dir(outname)\n        if '.hdf' in outname:\n            self.write_to_hdf(outname)\n        else:\n            raise ValueError('Cannot write to this format')",
    "docstring": "Write the found events to a sngl inspiral table"
  },
  {
    "code": "def declare_string(self, value):\n        byte_s = BytesIO(str(value).encode(ENCODING))\n        data_file = self.research_object.add_data_file(byte_s, content_type=TEXT_PLAIN)\n        checksum = posixpath.basename(data_file)\n        data_id = \"data:%s\" % posixpath.split(data_file)[1]\n        entity = self.document.entity(\n            data_id, {provM.PROV_TYPE: WFPROV[\"Artifact\"],\n                      provM.PROV_VALUE: str(value)})\n        return entity, checksum",
    "docstring": "Save as string in UTF-8."
  },
  {
    "code": "def match_path(rule, path):\n    split_rule = split_by_slash(rule)\n    split_path = split_by_slash(path)\n    url_vars = {}\n    if len(split_rule) != len(split_path):\n        return False, {}\n    for r, p in zip(split_rule, split_path):\n        if r.startswith('{') and r.endswith('}'):\n            url_vars[r[1:-1]] = p\n            continue\n        if r != p:\n            return False, {}\n    return True, url_vars",
    "docstring": "Match path.\n\n    >>> match_path('/foo', '/foo')\n    (True, {})\n    >>> match_path('/foo', '/bar')\n    (False, {})\n    >>> match_path('/users/{user_id}', '/users/1')\n    (True, {'user_id': '1'})\n    >>> match_path('/users/{user_id}', '/users/not-integer')\n    (True, {'user_id': 'not-integer'})"
  },
  {
    "code": "def decode_nibbles(value):\n    nibbles_with_flag = bytes_to_nibbles(value)\n    flag = nibbles_with_flag[0]\n    needs_terminator = flag in {HP_FLAG_2, HP_FLAG_2 + 1}\n    is_odd_length = flag in {HP_FLAG_0 + 1, HP_FLAG_2 + 1}\n    if is_odd_length:\n        raw_nibbles = nibbles_with_flag[1:]\n    else:\n        raw_nibbles = nibbles_with_flag[2:]\n    if needs_terminator:\n        nibbles = add_nibbles_terminator(raw_nibbles)\n    else:\n        nibbles = raw_nibbles\n    return nibbles",
    "docstring": "The inverse of the Hex Prefix function"
  },
  {
    "code": "def set_edist_powerlaw(self, emin_mev, emax_mev, delta, ne_cc):\n        if not (emin_mev >= 0):\n            raise ValueError('must have emin_mev >= 0; got %r' % (emin_mev,))\n        if not (emax_mev >= emin_mev):\n            raise ValueError('must have emax_mev >= emin_mev; got %r, %r' % (emax_mev, emin_mev))\n        if not (delta >= 0):\n            raise ValueError('must have delta >= 0; got %r, %r' % (delta,))\n        if not (ne_cc >= 0):\n            raise ValueError('must have ne_cc >= 0; got %r, %r' % (ne_cc,))\n        self.in_vals[IN_VAL_EDIST] = EDIST_PLW\n        self.in_vals[IN_VAL_EMIN] = emin_mev\n        self.in_vals[IN_VAL_EMAX] = emax_mev\n        self.in_vals[IN_VAL_DELTA1] = delta\n        self.in_vals[IN_VAL_NB] = ne_cc\n        return self",
    "docstring": "Set the energy distribution function to a power law.\n\n        **Call signature**\n\n        *emin_mev*\n          The minimum energy of the distribution, in MeV\n        *emax_mev*\n          The maximum energy of the distribution, in MeV\n        *delta*\n          The power-law index of the distribution\n        *ne_cc*\n          The number density of energetic electrons, in cm^-3.\n        Returns\n          *self* for convenience in chaining."
  },
  {
    "code": "def get_ts_stats_significance(self, x, ts, stat_ts_func, null_ts_func, B=1000, permute_fast=False, label_ts=''):\n        stats_ts, pvals, nums = ts_stats_significance(\n            ts, stat_ts_func, null_ts_func, B=B, permute_fast=permute_fast)\n        return stats_ts, pvals, nums",
    "docstring": "Returns the statistics, pvalues and the actual number of bootstrap\n            samples."
  },
  {
    "code": "def _wrapper(func, *vect_args, **vect_kwargs):\n        if not hasattr(func, '__name__'):\n            func.__name__ = '{}.__call__'.format(func.__class__.__name__)\n        return wraps(func)(_NumpyVectorizeWrapper(func, *vect_args,\n                                                  **vect_kwargs))",
    "docstring": "Return the vectorized wrapper function."
  },
  {
    "code": "def _format_title_string(self, title_string):\n        if \"StreamTitle='\" in title_string:\n            tmp = title_string[title_string.find(\"StreamTitle='\"):].replace(\"StreamTitle='\", self.icy_title_prefix)\n            ret_string = tmp[:tmp.find(\"';\")]\n        else:\n            ret_string = title_string\n        if '\"artist\":\"' in ret_string:\n            ret_string = self.icy_title_prefix + ret_string[ret_string.find('\"artist\":')+10:].replace('\",\"title\":\"', ' - ').replace('\"}\\';', '')\n        return self._title_string_format_text_tag(ret_string)",
    "docstring": "format mplayer's title"
  },
  {
    "code": "def register(listener):\n    if not isinstance(listener, _EventListener):\n        raise TypeError(\"Listeners for %s must be either a \"\n                        \"CommandListener, ServerHeartbeatListener, \"\n                        \"ServerListener, or TopologyListener.\" % (listener,))\n    if isinstance(listener, CommandListener):\n        _LISTENERS.command_listeners.append(listener)\n    if isinstance(listener, ServerHeartbeatListener):\n        _LISTENERS.server_heartbeat_listeners.append(listener)\n    if isinstance(listener, ServerListener):\n        _LISTENERS.server_listeners.append(listener)\n    if isinstance(listener, TopologyListener):\n        _LISTENERS.topology_listeners.append(listener)",
    "docstring": "Register a global event listener.\n\n    :Parameters:\n      - `listener`: A subclasses of :class:`CommandListener`,\n        :class:`ServerHeartbeatListener`, :class:`ServerListener`, or\n        :class:`TopologyListener`."
  },
  {
    "code": "def _batch_entry(self):\n        try:\n            while True:\n                self._batch_entry_run()\n        except:\n            self.exc_info = sys.exc_info()\n            os.kill(self.pid, signal.SIGUSR1)",
    "docstring": "Entry point for the batcher thread."
  },
  {
    "code": "def _untag_sentence(tagged_sentence):\n    untagged_sentence = TAG_PATT.sub('\\\\2', tagged_sentence)\n    clean_sentence = JUNK_PATT.sub('', untagged_sentence)\n    return clean_sentence.strip()",
    "docstring": "Removes all tags in the sentence, returning the original sentence\n    without Medscan annotations.\n\n    Parameters\n    ----------\n    tagged_sentence : str\n        The tagged sentence\n\n    Returns\n    -------\n    untagged_sentence : str\n        Sentence with tags and annotations stripped out"
  },
  {
    "code": "def srfrec(body, longitude, latitude):\n    body = ctypes.c_int(body)\n    longitude = ctypes.c_double(longitude)\n    latitude = ctypes.c_double(latitude)\n    rectan = stypes.emptyDoubleVector(3)\n    libspice.srfrec_c(body, longitude, latitude, rectan)\n    return stypes.cVectorToPython(rectan)",
    "docstring": "Convert planetocentric latitude and longitude of a surface\n    point on a specified body to rectangular coordinates.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/srfrec_c.html\n\n    :param body: NAIF integer code of an extended body.\n    :type body: int\n    :param longitude: Longitude of point in radians.\n    :type longitude: float\n    :param latitude: Latitude of point in radians.\n    :type latitude: float\n    :return: Rectangular coordinates of the point.\n    :rtype: 3-Element Array of floats"
  },
  {
    "code": "def create_box(self, orientation=Gtk.Orientation.HORIZONTAL, spacing=0):\n        h_box = Gtk.Box(orientation=orientation, spacing=spacing)\n        h_box.set_homogeneous(False)\n        return h_box",
    "docstring": "Function creates box. Based on orientation\n            it can be either HORIZONTAL or VERTICAL"
  },
  {
    "code": "def GetCoinAssets(self):\n        assets = set()\n        for coin in self.GetCoins():\n            assets.add(coin.Output.AssetId)\n        return list(assets)",
    "docstring": "Get asset ids of all coins present in the wallet.\n\n        Returns:\n            list: of UInt256 asset id's."
  },
  {
    "code": "def find_project_by_short_name(short_name, pbclient, all=None):\n    try:\n        response = pbclient.find_project(short_name=short_name, all=all)\n        check_api_error(response)\n        if (len(response) == 0):\n            msg = '%s not found! You can use the all=1 argument to \\\n                   search in all the server.'\n            error = 'Project Not Found'\n            raise ProjectNotFound(msg, error)\n        return response[0]\n    except exceptions.ConnectionError:\n        raise\n    except ProjectNotFound:\n        raise",
    "docstring": "Return project by short_name."
  },
  {
    "code": "def import_dashboards(path, recursive):\n    p = Path(path)\n    files = []\n    if p.is_file():\n        files.append(p)\n    elif p.exists() and not recursive:\n        files.extend(p.glob('*.json'))\n    elif p.exists() and recursive:\n        files.extend(p.rglob('*.json'))\n    for f in files:\n        logging.info('Importing dashboard from file %s', f)\n        try:\n            with f.open() as data_stream:\n                dashboard_import_export.import_dashboards(\n                    db.session, data_stream)\n        except Exception as e:\n            logging.error('Error when importing dashboard from file %s', f)\n            logging.error(e)",
    "docstring": "Import dashboards from JSON"
  },
  {
    "code": "def commit_or_abort(self, ctx, timeout=None, metadata=None,\n                        credentials=None):\n        return self.stub.CommitOrAbort(ctx, timeout=timeout, metadata=metadata,\n                                       credentials=credentials)",
    "docstring": "Runs commit or abort operation."
  },
  {
    "code": "def hook_scope(self, name=\"\"):\n        assert not self.revision\n        self.cursor.execute(\n            'insert into hooks (hook, date) values (?, ?)',\n            (name or sys.argv[0],\n             datetime.datetime.utcnow().isoformat()))\n        self.revision = self.cursor.lastrowid\n        try:\n            yield self.revision\n            self.revision = None\n        except Exception:\n            self.flush(False)\n            self.revision = None\n            raise\n        else:\n            self.flush()",
    "docstring": "Scope all future interactions to the current hook execution\n        revision."
  },
  {
    "code": "async def _wait(self):\n        for buid in self.otherbldgbuids:\n            nodeevnt = self.allbldgbuids.get(buid)\n            if nodeevnt is None:\n                continue\n            await nodeevnt[1].wait()",
    "docstring": "Wait on the other editatoms who are constructing nodes my new nodes refer to"
  },
  {
    "code": "def get_service_packages(self):\n        api = self._get_api(billing.DefaultApi)\n        package_response = api.get_service_packages()\n        packages = []\n        for state in PACKAGE_STATES:\n            items = getattr(package_response, state) or []\n            for item in ensure_listable(items):\n                params = item.to_dict()\n                params['state'] = state\n                packages.append(ServicePackage(params))\n        return packages",
    "docstring": "Get all service packages"
  },
  {
    "code": "def database_current_migration(self):\n        if not self.migration_table.exists(self.session.bind):\n            return None\n        if self.migration_data is None:\n            return None\n        return self.migration_data.version",
    "docstring": "Return the current migration in the database."
  },
  {
    "code": "def _gcd(a, b):\n    while b:\n        a, b = b, (a % b)\n    return a",
    "docstring": "Calculate the Greatest Common Divisor of a and b.\n\n    Unless b==0, the result will have the same sign as b (so that when\n    b is divided by it, the result comes out positive)."
  },
  {
    "code": "def _cast_repr(self, caster, *args, **kwargs):\n        if self.__repr_content is None:\n            self.__repr_content = hash_and_truncate(self)\n            assert self.__uses_default_repr\n        return caster(self.__repr_content, *args, **kwargs)",
    "docstring": "Will cast this constant with the provided caster, passing args and kwargs.\n\n        If there is no registered representation, will hash the name using sha512 and use the first 8 bytes\n        of the digest."
  },
  {
    "code": "def convertLatLngToPixelXY(self, lat, lng, level):\n        mapSize = self.getMapDimensionsByZoomLevel(level)\n        lat = self.clipValue(lat, self.min_lat, self.max_lat)\n        lng = self.clipValue(lng, self.min_lng, self.max_lng)\n        x = (lng + 180) / 360\n        sinlat = math.sin(lat * math.pi / 180)\n        y = 0.5 - math.log((1 + sinlat) / (1 - sinlat)) / (4 * math.pi)\n        pixelX = int(self.clipValue(x * mapSize + 0.5, 0, mapSize - 1))\n        pixelY = int(self.clipValue(y * mapSize + 0.5, 0, mapSize - 1))\n        return (pixelX, pixelY)",
    "docstring": "returns the x and y values of the pixel corresponding to a latitude\n        and longitude."
  },
  {
    "code": "def indent(text, amount, ch=' '):\n    padding = amount * ch\n    return ''.join(padding+line for line in text.splitlines(True))",
    "docstring": "Indents a string by the given amount of characters."
  },
  {
    "code": "def _get_svc_path(name='*', status=None):\n    if not SERVICE_DIR:\n        raise CommandExecutionError('Could not find service directory.')\n    ena = set()\n    for el in glob.glob(os.path.join(SERVICE_DIR, name)):\n        if _is_svc(el):\n            ena.add(os.readlink(el))\n            log.trace('found enabled service path: %s', el)\n    if status == 'ENABLED':\n        return sorted(ena)\n    ava = set()\n    for d in AVAIL_SVR_DIRS:\n        for el in glob.glob(os.path.join(d, name)):\n            if _is_svc(el):\n                ava.add(el)\n                log.trace('found available service path: %s', el)\n    if status == 'DISABLED':\n        ret = ava.difference(ena)\n    else:\n        ret = ava.union(ena)\n    return sorted(ret)",
    "docstring": "Return a list of paths to services with ``name`` that have the specified ``status``\n\n    name\n        a glob for service name. default is '*'\n\n    status\n        None       : all services (no filter, default choice)\n        'DISABLED' : available service(s) that is not enabled\n        'ENABLED'  : enabled service (whether started on boot or not)"
  },
  {
    "code": "def inner(self, x1, x2):\n        if x1 not in self:\n            raise LinearSpaceTypeError('`x1` {!r} is not an element of '\n                                       '{!r}'.format(x1, self))\n        if x2 not in self:\n            raise LinearSpaceTypeError('`x2` {!r} is not an element of '\n                                       '{!r}'.format(x2, self))\n        inner = self._inner(x1, x2)\n        if self.field is None:\n            return inner\n        else:\n            return self.field.element(self._inner(x1, x2))",
    "docstring": "Return the inner product of ``x1`` and ``x2``.\n\n        Parameters\n        ----------\n        x1, x2 : `LinearSpaceElement`\n            Elements whose inner product to compute.\n\n        Returns\n        -------\n        inner : `LinearSpace.field` element\n            Inner product of ``x1`` and ``x2``."
  },
  {
    "code": "def delete_from_all_link_group(self, group):\n        msg = StandardSend(self._address,\n                           COMMAND_DELETE_FROM_ALL_LINK_GROUP_0X02_NONE,\n                           cmd2=group)\n        self._send_msg(msg)",
    "docstring": "Delete a device to an All-Link Group."
  },
  {
    "code": "def _join_domain(domain,\n                 username=None,\n                 password=None,\n                 account_ou=None,\n                 account_exists=False):\n    NETSETUP_JOIN_DOMAIN = 0x1\n    NETSETUP_ACCOUNT_CREATE = 0x2\n    NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20\n    NETSETUP_JOIN_WITH_NEW_NAME = 0x400\n    join_options = 0x0\n    join_options |= NETSETUP_JOIN_DOMAIN\n    join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED\n    join_options |= NETSETUP_JOIN_WITH_NEW_NAME\n    if not account_exists:\n        join_options |= NETSETUP_ACCOUNT_CREATE\n    with salt.utils.winapi.Com():\n        conn = wmi.WMI()\n    comp = conn.Win32_ComputerSystem()[0]\n    return comp.JoinDomainOrWorkgroup(\n        Name=domain, Password=password, UserName=username, AccountOU=account_ou,\n        FJoinOptions=join_options)[0]",
    "docstring": "Helper function to join the domain.\n\n    Args:\n        domain (str): The domain to which the computer should be joined, e.g.\n            ``example.com``\n\n        username (str): Username of an account which is authorized to join\n            computers to the specified domain. Need to be either fully qualified\n            like ``user@domain.tld`` or simply ``user``\n\n        password (str): Password of the specified user\n\n        account_ou (str): The DN of the OU below which the account for this\n            computer should be created when joining the domain, e.g.\n            ``ou=computers,ou=departm_432,dc=my-company,dc=com``\n\n        account_exists (bool): If set to ``True`` the computer will only join\n            the domain if the account already exists. If set to ``False`` the\n            computer account will be created if it does not exist, otherwise it\n            will use the existing account. Default is False.\n\n    Returns:\n        int:\n\n    :param domain:\n    :param username:\n    :param password:\n    :param account_ou:\n    :param account_exists:\n    :return:"
  },
  {
    "code": "def close(self):\n        if not self._closed:\n            try:\n                self._cursor.close()\n            except Exception:\n                pass\n            self._closed = True",
    "docstring": "Close the tough cursor.\n\n        It will not complain if you close it more than once."
  },
  {
    "code": "def reload_module(self, module_name):\n        module = self.loaded_modules.get(module_name)\n        if module:\n            module.stop(reloading=True)\n        else:\n            _log.info(\"Reload loading new module module '%s'\",\n                         module_name)\n        success = self.load_module(module_name)\n        if success:\n            _log.info(\"Successfully (re)loaded module '%s'.\", module_name)\n        elif module:\n            _log.error(\"Unable to reload module '%s', reusing existing.\",\n                       module_name)\n        else:\n            _log.error(\"Failed to load module '%s'.\", module_name)\n            return False\n        self.loaded_modules[module_name].start(reloading=True)\n        return success",
    "docstring": "Reloads the specified module without changing its ordering.\n\n        1. Calls stop(reloading=True) on the module\n        2. Reloads the Module object into .loaded_modules\n        3. Calls start(reloading=True) on the new object\n        \n        If called with a module name that is not currently loaded, it will load it.\n\n        Returns True if the module was successfully reloaded, otherwise False."
  },
  {
    "code": "def seek_to_end(self, *partitions):\n        if not all([isinstance(p, TopicPartition) for p in partitions]):\n            raise TypeError('partitions must be TopicPartition namedtuples')\n        if not partitions:\n            partitions = self._subscription.assigned_partitions()\n            assert partitions, 'No partitions are currently assigned'\n        else:\n            for p in partitions:\n                assert p in self._subscription.assigned_partitions(), 'Unassigned partition'\n        for tp in partitions:\n            log.debug(\"Seeking to end of partition %s\", tp)\n            self._subscription.need_offset_reset(tp, OffsetResetStrategy.LATEST)",
    "docstring": "Seek to the most recent available offset for partitions.\n\n        Arguments:\n            *partitions: Optionally provide specific TopicPartitions, otherwise\n                default to all assigned partitions.\n\n        Raises:\n            AssertionError: If any partition is not currently assigned, or if\n                no partitions are assigned."
  },
  {
    "code": "def get_gene_count_tab(infile,\n                       bc_getter=None):\n    gene = None\n    counts = collections.Counter()\n    for line in infile:\n        values = line.strip().split(\"\\t\")\n        assert len(values) == 2, \"line: %s does not contain 2 columns\" % line\n        read_id, assigned_gene = values\n        if assigned_gene != gene:\n            if gene:\n                yield gene, counts\n            gene = assigned_gene\n            counts = collections.defaultdict(collections.Counter)\n        cell, umi = bc_getter(read_id)\n        counts[cell][umi] += 1\n    yield gene, counts",
    "docstring": "Yields the counts per umi for each gene\n\n    bc_getter: method to get umi (plus optionally, cell barcode) from\n    read, e.g get_umi_read_id or get_umi_tag\n\n\n    TODO: ADD FOLLOWING OPTION\n\n    skip_regex: skip genes matching this regex. Useful to ignore\n                unassigned reads (as per get_bundles class above)"
  },
  {
    "code": "def sprinkler_reaches_cell(x, y, sx, sy, r):\n    dx = sx - x\n    dy = sy - y\n    return math.sqrt(dx ** 2 + dy ** 2) <= r",
    "docstring": "Return whether a cell is within the radius of the sprinkler.\n\n    x:  column index of cell\n    y:  row index of cell\n    sx:  column index of sprinkler\n    sy:  row index of sprinkler\n    r:  sprinkler radius"
  },
  {
    "code": "def selected_purpose(self):\n        item = self.lstCategories.currentItem()\n        try:\n            return definition(item.data(QtCore.Qt.UserRole))\n        except (AttributeError, NameError):\n            return None",
    "docstring": "Obtain the layer purpose selected by user.\n\n        :returns: Metadata of the selected layer purpose.\n        :rtype: dict, None"
  },
  {
    "code": "def get_current_user(with_domain=True):\n    try:\n        user_name = win32api.GetUserNameEx(win32api.NameSamCompatible)\n        if user_name[-1] == '$':\n            test_user = win32api.GetUserName()\n            if test_user == 'SYSTEM':\n                user_name = 'SYSTEM'\n            elif get_sid_from_name(test_user) == 'S-1-5-18':\n                user_name = 'SYSTEM'\n        elif not with_domain:\n            user_name = win32api.GetUserName()\n    except pywintypes.error as exc:\n        raise CommandExecutionError(\n            'Failed to get current user: {0}'.format(exc))\n    if not user_name:\n        return False\n    return user_name",
    "docstring": "Gets the user executing the process\n\n    Args:\n\n        with_domain (bool):\n            ``True`` will prepend the user name with the machine name or domain\n            separated by a backslash\n\n    Returns:\n        str: The user name"
  },
  {
    "code": "def _checkAndConvertIndex(self, index):\n        if index < 0:\n            index = len(self) + index\n        if index < 0 or index >= self._doc.blockCount():\n            raise IndexError('Invalid block index', index)\n        return index",
    "docstring": "Check integer index, convert from less than zero notation"
  },
  {
    "code": "def audio_open(path, backends=None):\n    if backends is None:\n        backends = available_backends()\n    for BackendClass in backends:\n        try:\n            return BackendClass(path)\n        except DecodeError:\n            pass\n    raise NoBackendError()",
    "docstring": "Open an audio file using a library that is available on this\n    system.\n\n    The optional `backends` parameter can be a list of audio file\n    classes to try opening the file with. If it is not provided,\n    `audio_open` tries all available backends. If you call this function\n    many times, you can avoid the cost of checking for available\n    backends every time by calling `available_backends` once and passing\n    the result to each `audio_open` call.\n\n    If all backends fail to read the file, a NoBackendError exception is\n    raised."
  },
  {
    "code": "def kind(self):\n        with self._mutex:\n            kind = self._obj.get_kind()\n            if kind == RTC.PERIODIC:\n                return self.PERIODIC\n            elif kind == RTC.EVENT_DRIVEN:\n                return self.EVENT_DRIVEN\n            else:\n                return self.OTHER",
    "docstring": "The kind of this execution context."
  },
  {
    "code": "def get_m2m_widget(cls, field):\n        return functools.partial(\n            widgets.ManyToManyWidget,\n            model=get_related_model(field))",
    "docstring": "Prepare widget for m2m field"
  },
  {
    "code": "def _product_filter(products) -> str:\n    _filter = 0\n    for product in {PRODUCTS[p] for p in products}:\n        _filter += product\n    return format(_filter, \"b\")[::-1]",
    "docstring": "Calculate the product filter."
  },
  {
    "code": "def collect_results(self) -> Optional[Tuple[int, Dict[str, float]]]:\n        self.wait_to_finish()\n        if self.decoder_metric_queue.empty():\n            if self._results_pending:\n                self._any_process_died = True\n            self._results_pending = False\n            return None\n        decoded_checkpoint, decoder_metrics = self.decoder_metric_queue.get()\n        assert self.decoder_metric_queue.empty()\n        self._results_pending = False\n        logger.info(\"Decoder-%d finished: %s\", decoded_checkpoint, decoder_metrics)\n        return decoded_checkpoint, decoder_metrics",
    "docstring": "Returns the decoded checkpoint and the decoder metrics or None if the queue is empty."
  },
  {
    "code": "def generate_gap_bed(fname, outname):\n    f = Fasta(fname)\n    with open(outname, \"w\") as bed:\n        for chrom in f.keys():\n            for m in re.finditer(r'N+', f[chrom][:].seq):\n                bed.write(\"{}\\t{}\\t{}\\n\".format(chrom, m.start(0), m.end(0)))",
    "docstring": "Generate a BED file with gap locations.\n\n    Parameters\n    ----------\n    fname : str\n        Filename of input FASTA file.\n\n    outname : str\n        Filename of output BED file."
  },
  {
    "code": "def zoom_fit(self):\n        zoom = self.grid.grid_renderer.zoom\n        grid_width, grid_height = self.grid.GetSize()\n        rows_height = self._get_rows_height() + \\\n            (float(self.grid.GetColLabelSize()) / zoom)\n        cols_width = self._get_cols_width() + \\\n            (float(self.grid.GetRowLabelSize()) / zoom)\n        zoom_height = float(grid_height) / rows_height\n        zoom_width = float(grid_width) / cols_width\n        target_zoom = min(zoom_height, zoom_width)\n        if config[\"minimum_zoom\"] < target_zoom < config[\"maximum_zoom\"]:\n            self.zoom(target_zoom)",
    "docstring": "Zooms the rid to fit the window.\n\n        Only has an effect if the resulting zoom level is between\n        minimum and maximum zoom level."
  },
  {
    "code": "def total_power(self):\n        power = self.average_current * self.voltage\n        return round(power, self.sr)",
    "docstring": "Total power used."
  },
  {
    "code": "def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,\n                 keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    if name.startswith('sg-'):\n        log.debug('group %s is a group id. get_group_id not called.', name)\n        return name\n    group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,\n                       region=region, key=key, keyid=keyid, profile=profile)\n    return getattr(group, 'id', None)",
    "docstring": "Get a Group ID given a Group Name or Group Name and VPC ID\n\n    CLI example::\n\n        salt myminion boto_secgroup.get_group_id mysecgroup"
  },
  {
    "code": "def _rewrite_f(self, q):\n        if isinstance(q, models.F):\n            q.name = rewrite_lookup_key(self.model, q.name)\n            return q\n        if isinstance(q, Node):\n            q.children = list(map(self._rewrite_f, q.children))\n        if hasattr(q, 'lhs'):\n            q.lhs = self._rewrite_f(q.lhs)\n        if hasattr(q, 'rhs'):\n            q.rhs = self._rewrite_f(q.rhs)\n        return q",
    "docstring": "Rewrite field names inside F call."
  },
  {
    "code": "def squared_error(eval_data, predictions, scores='ignored', learner='ignored'):\n    return [np.sum((np.array(pred) - np.array(inst.output)) ** 2)\n            for inst, pred in zip(eval_data, predictions)]",
    "docstring": "Return the squared error of each prediction in `predictions` with respect\n    to the correct output in `eval_data`.\n\n    >>> data = [Instance('input', (0., 0., 1.)),\n    ...         Instance('input', (0., 1., 1.)),\n    ...         Instance('input', (1., 0., 0.))]\n    >>> squared_error(data, [(0., 1., 1.), (0., 1., 1.), (-1., 1., 0.)])\n    [1.0, 0.0, 5.0]"
  },
  {
    "code": "def update(self, report: str = None) -> bool:\n        if report is not None:\n            self.raw = report\n        else:\n            raw = self.service.fetch(self.station)\n            if raw == self.raw:\n                return False\n            self.raw = raw\n        self.data, self.units = metar.parse(self.station, self.raw)\n        self.translations = translate.metar(self.data, self.units)\n        self.last_updated = datetime.utcnow()\n        return True",
    "docstring": "Updates raw, data, and translations by fetching and parsing the METAR report\n\n        Returns True is a new report is available, else False"
  },
  {
    "code": "def btc_tx_script_to_asm( script_hex ):\n    if len(script_hex) == 0:\n        return \"\"\n    try:\n        script_array = btc_script_deserialize(script_hex)\n    except:\n        log.error(\"Failed to convert '%s' to assembler\" % script_hex)\n        raise\n    script_tokens = []\n    for token in script_array:\n        if token is None:\n            token = 0\n        token_name = None\n        if type(token) in [int,long]:\n            token_name = OPCODE_NAMES.get(token, None)\n            if token_name is None:\n                token_name = str(token)\n        else:\n            token_name = token\n        script_tokens.append(token_name)\n    return \" \".join(script_tokens)",
    "docstring": "Decode a script into assembler"
  },
  {
    "code": "def not_empty(value,\n              allow_empty = False,\n              **kwargs):\n    if not value and allow_empty:\n        return None\n    elif not value:\n        raise errors.EmptyValueError('value was empty')\n    return value",
    "docstring": "Validate that ``value`` is not empty.\n\n    :param value: The value to validate.\n\n    :param allow_empty: If ``True``, returns :obj:`None <python:None>` if\n      ``value`` is empty. If ``False``, raises a\n      :class:`EmptyValueError <validator_collection.errors.EmptyValueError>`\n      if ``value`` is empty. Defaults to ``False``.\n    :type allow_empty: :class:`bool <python:bool>`\n\n    :returns: ``value`` / :obj:`None <python:None>`\n\n    :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``"
  },
  {
    "code": "def _get_pgtiou(pgt):\n    pgtIou = None\n    retries_left = 5\n    if not settings.CAS_PGT_FETCH_WAIT:\n        retries_left = 1\n    while not pgtIou and retries_left:\n        try:\n            return PgtIOU.objects.get(tgt=pgt)\n        except PgtIOU.DoesNotExist:\n            if settings.CAS_PGT_FETCH_WAIT:\n                time.sleep(1)\n            retries_left -= 1\n            logger.info('Did not fetch ticket, trying again.  {tries} tries left.'.format(\n                tries=retries_left\n            ))\n    raise CasTicketException(\"Could not find pgtIou for pgt %s\" % pgt)",
    "docstring": "Returns a PgtIOU object given a pgt.\n\n    The PgtIOU (tgt) is set by the CAS server in a different request\n    that has completed before this call, however, it may not be found in\n    the database by this calling thread, hence the attempt to get the\n    ticket is retried for up to 5 seconds. This should be handled some\n    better way.\n\n    Users can opt out of this waiting period by setting CAS_PGT_FETCH_WAIT = False\n\n    :param: pgt"
  },
  {
    "code": "def FindProxies():\n  sc = objc.SystemConfiguration()\n  settings = sc.dll.SCDynamicStoreCopyProxies(None)\n  if not settings:\n    return []\n  try:\n    cf_http_enabled = sc.CFDictRetrieve(settings, \"kSCPropNetProxiesHTTPEnable\")\n    if cf_http_enabled and bool(sc.CFNumToInt32(cf_http_enabled)):\n      cfproxy = sc.CFDictRetrieve(settings, \"kSCPropNetProxiesHTTPProxy\")\n      cfport = sc.CFDictRetrieve(settings, \"kSCPropNetProxiesHTTPPort\")\n      if cfproxy and cfport:\n        proxy = sc.CFStringToPystring(cfproxy)\n        port = sc.CFNumToInt32(cfport)\n        return [\"http://%s:%d/\" % (proxy, port)]\n    cf_auto_enabled = sc.CFDictRetrieve(\n        settings, \"kSCPropNetProxiesProxyAutoConfigEnable\")\n    if cf_auto_enabled and bool(sc.CFNumToInt32(cf_auto_enabled)):\n      cfurl = sc.CFDictRetrieve(settings,\n                                \"kSCPropNetProxiesProxyAutoConfigURLString\")\n      if cfurl:\n        unused_url = sc.CFStringToPystring(cfurl)\n        return []\n  finally:\n    sc.dll.CFRelease(settings)\n  return []",
    "docstring": "This reads the OSX system configuration and gets the proxies."
  },
  {
    "code": "def passphrase_file(passphrase=None):\n    cmd = []\n    pass_file = None\n    if not passphrase and 'CRYPTORITO_PASSPHRASE_FILE' in os.environ:\n        pass_file = os.environ['CRYPTORITO_PASSPHRASE_FILE']\n        if not os.path.isfile(pass_file):\n            raise CryptoritoError('CRYPTORITO_PASSPHRASE_FILE is invalid')\n    elif passphrase:\n        tmpdir = ensure_tmpdir()\n        pass_file = \"%s/p_pass\" % tmpdir\n        p_handle = open(pass_file, 'w')\n        p_handle.write(passphrase)\n        p_handle.close()\n    if pass_file:\n        cmd = cmd + [\"--batch\", \"--passphrase-file\", pass_file]\n        vsn = gpg_version()\n        if vsn[0] >= 2 and vsn[1] >= 1:\n            cmd = cmd + [\"--pinentry-mode\", \"loopback\"]\n    return cmd",
    "docstring": "Read passphrase from a file. This should only ever be\n    used by our built in integration tests. At this time,\n    during normal operation, only pinentry is supported for\n    entry of passwords."
  },
  {
    "code": "def associate_psds_to_single_ifo_segments(opt, fd_segments, gwstrain, flen,\n                                          delta_f, flow, ifo,\n                                          dyn_range_factor=1., precision=None):\n    single_det_opt = copy_opts_for_single_ifo(opt, ifo)\n    associate_psds_to_segments(single_det_opt, fd_segments, gwstrain, flen,\n                               delta_f, flow, dyn_range_factor=dyn_range_factor,\n                               precision=precision)",
    "docstring": "Associate PSDs to segments for a single ifo when using the multi-detector\n    CLI"
  },
  {
    "code": "def make_gating_node(workflow, datafind_files, outdir=None, tags=None):\n    cp = workflow.cp\n    if tags is None:\n        tags = []\n    condition_strain_class = select_generic_executable(workflow,\n                                                       \"condition_strain\")\n    condition_strain_nodes = []\n    condition_strain_outs = FileList([])\n    for ifo in workflow.ifos:\n        input_files = FileList([datafind_file for datafind_file in \\\n                                datafind_files if datafind_file.ifo == ifo])\n        condition_strain_jobs = condition_strain_class(cp, \"condition_strain\",\n                ifo=ifo, out_dir=outdir, tags=tags)\n        condition_strain_node, condition_strain_out = \\\n                condition_strain_jobs.create_node(input_files, tags=tags)\n        condition_strain_nodes.append(condition_strain_node)\n        condition_strain_outs.extend(FileList([condition_strain_out]))\n    return condition_strain_nodes, condition_strain_outs",
    "docstring": "Generate jobs for autogating the data for PyGRB runs.\n\n    Parameters\n    ----------\n    workflow: pycbc.workflow.core.Workflow\n        An instanced class that manages the constructed workflow.\n    datafind_files : pycbc.workflow.core.FileList\n        A FileList containing the frame files to be gated.\n    outdir : string\n        Path of the output directory\n    tags : list of strings\n        If given these tags are used to uniquely name and identify output files\n        that would be produced in multiple calls to this function.\n\n    Returns\n    --------\n    condition_strain_nodes : list\n        List containing the pycbc.workflow.core.Node objects representing the\n        autogating jobs.\n    condition_strain_outs : pycbc.workflow.core.FileList\n        FileList containing the pycbc.workflow.core.File objects representing\n        the gated frame files."
  },
  {
    "code": "def _load_version(cls, state, version):\n        assert(version == cls._PYTHON_NN_CLASSIFIER_MODEL_VERSION)\n        knn_model = _tc.nearest_neighbors.NearestNeighborsModel(state['knn_model'])\n        del state['knn_model']\n        state['_target_type'] = eval(state['_target_type'])\n        return cls(knn_model, state)",
    "docstring": "A function to load a previously saved NearestNeighborClassifier model.\n\n        Parameters\n        ----------\n        unpickler : GLUnpickler\n            A GLUnpickler file handler.\n\n        version : int\n            Version number maintained by the class writer."
  },
  {
    "code": "def ModuleLogger(globs):\n    if not globs.has_key('_debug'):\n        raise RuntimeError(\"define _debug before creating a module logger\")\n    logger_name = globs['__name__']\n    logger = logging.getLogger(logger_name)\n    logger.globs = globs\n    if '.' not in logger_name:\n        hdlr = logging.StreamHandler()\n        hdlr.setLevel(logging.WARNING)\n        hdlr.setFormatter(logging.Formatter(logging.BASIC_FORMAT, None))\n        logger.addHandler(hdlr)\n    return logger",
    "docstring": "Create a module level logger.\n\n    To debug a module, create a _debug variable in the module, then use the\n    ModuleLogger function to create a \"module level\" logger.  When a handler\n    is added to this logger or a child of this logger, the _debug variable will\n    be incremented.\n\n    All of the calls within functions or class methods within the module should\n    first check to see if _debug is set to prevent calls to formatter objects\n    that aren't necessary."
  },
  {
    "code": "def _merge_inplace(self, other):\n        if other is None:\n            yield\n        else:\n            priority_vars = OrderedDict(\n                kv for kv in self.variables.items() if kv[0] not in self.dims)\n            variables = merge_coords_for_inplace_math(\n                [self.variables, other.variables], priority_vars=priority_vars)\n            yield\n            self._update_coords(variables)",
    "docstring": "For use with in-place binary arithmetic."
  },
  {
    "code": "def validate(opts):\n    if hasattr(opts, 'extensions'):\n        return _validate(opts.extensions)\n    elif isinstance(opts, list):\n        return _validate(opts)\n    else:\n        raise ValueError(\"Value passed into extension validation must either \"\n                         \"be a list of strings or a namespace with an \"\n                         \"attribute of 'extensions'\")",
    "docstring": "Client-facing validate method. Checks to see if the passed in opts\n    argument is either a list or a namespace containing the attribute\n    'extensions' and runs validations on it accordingly. If opts is neither\n    of those things, this will raise a ValueError\n\n    :param opts: either a list of strings or a namespace with the attribute\n        'extensions'\n    :raises ValueError: if the value passed in is not a list or a namespace\n        with the attribute 'extensions'\n    :raises ValidationException: if the extensions fail validations\n    :return: True if extensions pass the validations"
  },
  {
    "code": "def __populate_sections(self):\n        if not self._ptr:\n            raise BfdException(\"BFD not initialized\")\n        for section in _bfd.get_sections_list(self._ptr):\n            try:\n                bfd_section = BfdSection(self._ptr, section)\n                self._sections[bfd_section.name] = bfd_section\n            except BfdSectionException, err:\n                pass",
    "docstring": "Get a list of the section present in the bfd to populate our\n        internal list."
  },
  {
    "code": "def as_euler_angles(q):\n    alpha_beta_gamma = np.empty(q.shape + (3,), dtype=np.float)\n    n = np.norm(q)\n    q = as_float_array(q)\n    alpha_beta_gamma[..., 0] = np.arctan2(q[..., 3], q[..., 0]) + np.arctan2(-q[..., 1], q[..., 2])\n    alpha_beta_gamma[..., 1] = 2*np.arccos(np.sqrt((q[..., 0]**2 + q[..., 3]**2)/n))\n    alpha_beta_gamma[..., 2] = np.arctan2(q[..., 3], q[..., 0]) - np.arctan2(-q[..., 1], q[..., 2])\n    return alpha_beta_gamma",
    "docstring": "Open Pandora's Box\n\n    If somebody is trying to make you use Euler angles, tell them no, and\n    walk away, and go and tell your mum.\n\n    You don't want to use Euler angles.  They are awful.  Stay away.  It's\n    one thing to convert from Euler angles to quaternions; at least you're\n    moving in the right direction.  But to go the other way?!  It's just not\n    right.\n\n    Assumes the Euler angles correspond to the quaternion R via\n\n        R = exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)\n\n    The angles are naturally in radians.\n\n    NOTE: Before opening an issue reporting something \"wrong\" with this\n    function, be sure to read all of the following page, *especially* the\n    very last section about opening issues or pull requests.\n    <https://github.com/moble/quaternion/wiki/Euler-angles-are-horrible>\n\n    Parameters\n    ----------\n    q: quaternion or array of quaternions\n        The quaternion(s) need not be normalized, but must all be nonzero\n\n    Returns\n    -------\n    alpha_beta_gamma: float array\n        Output shape is q.shape+(3,).  These represent the angles (alpha,\n        beta, gamma) in radians, where the normalized input quaternion\n        represents `exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)`.\n\n    Raises\n    ------\n    AllHell\n        ...if you try to actually use Euler angles, when you could have\n        been using quaternions like a sensible person."
  },
  {
    "code": "def chunks(event_list, chunk_size):\n    for i in range(0, len(event_list), chunk_size):\n        yield event_list[i:i + chunk_size]",
    "docstring": "Yield successive n-sized chunks from the event list."
  },
  {
    "code": "def move_notes(self, noteids, folderid):\n        if self.standard_grant_type is not \"authorization_code\":\n            raise DeviantartError(\"Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.\")\n        response = self._req('/notes/move', post_data={\n            'noteids[]' : noteids,\n            'folderid' : folderid\n        })\n        return response",
    "docstring": "Move notes to a folder\n\n        :param noteids: The noteids to move\n        :param folderid: The folderid to move notes to"
  },
  {
    "code": "def make_python_name(s, default=None, number_prefix='N',encoding=\"utf-8\"):\n    if s in ('', None):\n        s = default\n    s = str(s)\n    s = re.sub(\"[^a-zA-Z0-9_]\", \"_\", s)\n    if not re.match('\\d', s) is None:\n        s = number_prefix+s\n    return unicode(s, encoding)",
    "docstring": "Returns a unicode string that can be used as a legal python identifier.\n\n    :Arguments:\n      *s*\n         string\n      *default*\n         use *default* if *s* is ``None``\n      *number_prefix*\n         string to prepend if *s* starts with a number"
  },
  {
    "code": "def is_datetime_arraylike(arr):\n    if isinstance(arr, ABCDatetimeIndex):\n        return True\n    elif isinstance(arr, (np.ndarray, ABCSeries)):\n        return (is_object_dtype(arr.dtype)\n                and lib.infer_dtype(arr, skipna=False) == 'datetime')\n    return getattr(arr, 'inferred_type', None) == 'datetime'",
    "docstring": "Check whether an array-like is a datetime array-like or DatetimeIndex.\n\n    Parameters\n    ----------\n    arr : array-like\n        The array-like to check.\n\n    Returns\n    -------\n    boolean\n        Whether or not the array-like is a datetime array-like or\n        DatetimeIndex.\n\n    Examples\n    --------\n    >>> is_datetime_arraylike([1, 2, 3])\n    False\n    >>> is_datetime_arraylike(pd.Index([1, 2, 3]))\n    False\n    >>> is_datetime_arraylike(pd.DatetimeIndex([1, 2, 3]))\n    True"
  },
  {
    "code": "def describe_connection(self):\n        if self.device==None:\n            return \"%s [disconnected]\" % (self.name)\n        else:\n            return \"%s connected to %s %s version: %s [serial: %s]\" % (self.name, \n                self.vendor_name, self.product_name,\n                self.version_number, self.serial_number)",
    "docstring": "Return string representation of the device, including\n        the connection state"
  },
  {
    "code": "def run(items):\n    items = [utils.to_single_data(x) for x in items]\n    work_dir = _sv_workdir(items[0])\n    input_backs = list(set(filter(lambda x: x is not None,\n                                  [dd.get_background_cnv_reference(d, \"seq2c\") for d in items])))\n    coverage_file = _combine_coverages(items, work_dir, input_backs)\n    read_mapping_file = _calculate_mapping_reads(items, work_dir, input_backs)\n    normal_names = []\n    if input_backs:\n        with open(input_backs[0]) as in_handle:\n            for line in in_handle:\n                if len(line.split()) == 2:\n                    normal_names.append(line.split()[0])\n    normal_names += [dd.get_sample_name(x) for x in items if population.get_affected_status(x) == 1]\n    seq2c_calls_file = _call_cnv(items, work_dir, read_mapping_file, coverage_file, normal_names)\n    items = _split_cnv(items, seq2c_calls_file, read_mapping_file, coverage_file)\n    return items",
    "docstring": "Normalization and log2 ratio calculation plus CNV calling for full cohort.\n\n    - Combine coverage of each region for each sample\n    - Prepare read counts for each sample\n    - Normalize coverages in cohort by gene and sample, and calculate log2 ratios\n    - Call amplifications and deletions"
  },
  {
    "code": "def computeISI(spikeTrains):\n  zeroCount = 0\n  isi = []\n  cells = 0\n  for i in range(np.shape(spikeTrains)[0]):\n    if cells > 0 and cells % 250 == 0:\n      print str(cells) + \" cells processed\"\n    for j in range(np.shape(spikeTrains)[1]):\n      if spikeTrains[i][j] == 0:\n        zeroCount += 1\n      elif zeroCount > 0:\n        isi.append(zeroCount)\n        zeroCount = 0\n    zeroCount = 0\n    cells += 1\n  print \"**All cells processed**\"\n  return isi",
    "docstring": "Estimates the inter-spike interval from a spike train matrix.\n  \n  @param spikeTrains (array) matrix of spike trains\n  @return isi (array) matrix with the inter-spike interval obtained from the spike train.\n          Each entry in this matrix represents the number of time-steps in-between 2 spikes\n          as the algorithm scans the spike train matrix."
  },
  {
    "code": "def color(colors, export_type, output_file=None):\n    all_colors = flatten_colors(colors)\n    template_name = get_export_type(export_type)\n    template_file = os.path.join(MODULE_DIR, \"templates\", template_name)\n    output_file = output_file or os.path.join(CACHE_DIR, template_name)\n    if os.path.isfile(template_file):\n        template(all_colors, template_file, output_file)\n        logging.info(\"Exported %s.\", export_type)\n    else:\n        logging.warning(\"Template '%s' doesn't exist.\", export_type)",
    "docstring": "Export a single template file."
  },
  {
    "code": "def export(self, remote_function):\n        if self._worker.mode is None:\n            self._functions_to_export.append(remote_function)\n            return\n        if self._worker.mode != ray.worker.SCRIPT_MODE:\n            return\n        self._do_export(remote_function)",
    "docstring": "Export a remote function.\n\n        Args:\n            remote_function: the RemoteFunction object."
  },
  {
    "code": "def serialize(self, value):\n        if isinstance(value, float) and self.as_type is six.text_type:\n            value = u'{0:.{1}f}'.format(value, self.float_places)\n            value = self.as_type(value)\n        elif self.as_type is six.text_type:\n            if isinstance(value, bool):\n                value = six.text_type(int(bool(value)))\n            elif isinstance(value, bytes):\n                value = value.decode('utf-8', 'ignore')\n            else:\n                value = six.text_type(value)\n        else:\n            value = self.as_type(value)\n        if self.suffix:\n            value += self.suffix\n        return value",
    "docstring": "Convert the external Python value to a type that is suitable for\n        storing in a Mutagen file object."
  },
  {
    "code": "def listen_to_node(self, id_):\n        if r_client.get(id_) is None:\n            return\n        else:\n            self.toredis.subscribe(_pubsub_key(id_), callback=self.callback)\n            self._listening_to[_pubsub_key(id_)] = id_\n            return id_",
    "docstring": "Attach a callback on the job pubsub if it exists"
  },
  {
    "code": "def _validate(self):\n        probably_good_to_go = True\n        sheet = self.table\n        identity = self.db_sheet_cols.id\n        id_col = sheet.loc[:, identity]\n        if any(id_col.duplicated()):\n            warnings.warn(\n                \"your database is corrupt: duplicates\"\n                \" encountered in the srno-column\")\n            logger.debug(\"srno duplicates:\\n\" + str(\n                id_col.duplicated()))\n            probably_good_to_go = False\n        return probably_good_to_go",
    "docstring": "Checks that the db-file is ok\n\n        Returns:\n            True if OK, False if not."
  },
  {
    "code": "def chunkWidgets(self, group):\r\n        ui_groups = []\r\n        subgroup = []\r\n        for index, item in enumerate(group['items']):\r\n            if getin(item, ['options', 'full_width'], False):\r\n                ui_groups.append(subgroup)\r\n                ui_groups.append([item])\r\n                subgroup = []\r\n            else:\r\n                subgroup.append(item)\r\n            if len(subgroup) == getin(group, ['options', 'columns'], 2) \\\r\n                    or item == group['items'][-1]:\r\n                ui_groups.append(subgroup)\r\n                subgroup = []\r\n        return ui_groups",
    "docstring": "chunk the widgets up into groups based on their sizing hints"
  },
  {
    "code": "def get_buckets(self, bucket_type=None, timeout=None):\n        bucket_type = self._get_bucket_type(bucket_type)\n        url = self.bucket_list_path(bucket_type=bucket_type,\n                                    timeout=timeout)\n        status, headers, body = self._request('GET', url)\n        if status == 200:\n            props = json.loads(bytes_to_str(body))\n            return props['buckets']\n        else:\n            raise RiakError('Error getting buckets.')",
    "docstring": "Fetch a list of all buckets"
  },
  {
    "code": "def display(port=None, height=None):\n  _display(port=port, height=height, print_message=True, display_handle=None)",
    "docstring": "Display a TensorBoard instance already running on this machine.\n\n  Args:\n    port: The port on which the TensorBoard server is listening, as an\n      `int`, or `None` to automatically select the most recently\n      launched TensorBoard.\n    height: The height of the frame into which to render the TensorBoard\n      UI, as an `int` number of pixels, or `None` to use a default value\n      (currently 800)."
  },
  {
    "code": "def get_interpolated_value(self, energy):\n        f = {}\n        for spin in self.densities.keys():\n            f[spin] = get_linear_interpolated_value(self.energies,\n                                                    self.densities[spin],\n                                                    energy)\n        return f",
    "docstring": "Returns interpolated density for a particular energy.\n\n        Args:\n            energy: Energy to return the density for."
  },
  {
    "code": "def generate_wavelengths(minwave=500, maxwave=26000, num=10000, delta=None,\n                         log=True, wave_unit=u.AA):\n    wave_unit = units.validate_unit(wave_unit)\n    if delta is not None:\n        num = None\n    waveset_str = 'Min: {0}, Max: {1}, Num: {2}, Delta: {3}, Log: {4}'.format(\n        minwave, maxwave, num, delta, log)\n    if log:\n        logmin = np.log10(minwave)\n        logmax = np.log10(maxwave)\n        if delta is None:\n            waveset = np.logspace(logmin, logmax, num, endpoint=False)\n        else:\n            waveset = 10 ** np.arange(logmin, logmax, delta)\n    else:\n        if delta is None:\n            waveset = np.linspace(minwave, maxwave, num, endpoint=False)\n        else:\n            waveset = np.arange(minwave, maxwave, delta)\n    return waveset.astype(np.float64) * wave_unit, waveset_str",
    "docstring": "Generate wavelength array to be used for spectrum sampling.\n\n    .. math::\n\n        minwave \\\\le \\\\lambda < maxwave\n\n    Parameters\n    ----------\n    minwave, maxwave : float\n        Lower and upper limits of the wavelengths.\n        These must be values in linear space regardless of ``log``.\n\n    num : int\n        The number of wavelength values.\n        This is only used when ``delta=None``.\n\n    delta : float or `None`\n        Delta between wavelength values.\n        When ``log=True``, this is the spacing in log space.\n\n    log : bool\n        If `True`, the wavelength values are evenly spaced in log scale.\n        Otherwise, spacing is linear.\n\n    wave_unit : str or `~astropy.units.core.Unit`\n        Wavelength unit. Default is Angstrom.\n\n    Returns\n    -------\n    waveset : `~astropy.units.quantity.Quantity`\n        Generated wavelength set.\n\n    waveset_str : str\n        Info string associated with the result."
  },
  {
    "code": "def statcast(start_dt=None, end_dt=None, team=None, verbose=True):\n    start_dt, end_dt = sanitize_input(start_dt, end_dt)\n    small_query_threshold = 5\n    if start_dt and end_dt:\n        date_format = \"%Y-%m-%d\"\n        d1 = datetime.datetime.strptime(start_dt, date_format)\n        d2 = datetime.datetime.strptime(end_dt, date_format)\n        days_in_query = (d2 - d1).days\n        if days_in_query <= small_query_threshold:\n            data = small_request(start_dt,end_dt)\n        else:\n            data = large_request(start_dt,end_dt,d1,d2,step=small_query_threshold,verbose=verbose)\n        data = postprocessing(data, team)\n        return data",
    "docstring": "Pulls statcast play-level data from Baseball Savant for a given date range.\n\n    INPUTS:\n    start_dt: YYYY-MM-DD : the first date for which you want statcast data\n    end_dt: YYYY-MM-DD : the last date for which you want statcast data\n    team: optional (defaults to None) : city abbreviation of the team you want data for (e.g. SEA or BOS)\n\n    If no arguments are provided, this will return yesterday's statcast data. If one date is provided, it will return that date's statcast data."
  },
  {
    "code": "def zdiffstore(self, dest, keys, withscores=False):\r\n        keys = (dest,) + tuple(keys)\r\n        wscores = 'withscores' if withscores else ''\r\n        return self.execute_script('zdiffstore', keys, wscores,\r\n                                   withscores=withscores)",
    "docstring": "Compute the difference of multiple sorted.\r\n\r\n        The difference of sets specified by ``keys`` into a new sorted set\r\n        in ``dest``."
  },
  {
    "code": "def get_data_len(self):\n        padding_len = self.getfieldval('padlen')\n        fld, fval = self.getfield_and_val('padlen')\n        padding_len_len = fld.i2len(self, fval)\n        ret = self.s_len - padding_len_len - padding_len\n        assert(ret >= 0)\n        return ret",
    "docstring": "get_data_len computes the length of the data field\n\n        To do this computation, the length of the padlen field and the actual\n        padding is subtracted to the string that was provided to the pre_dissect  # noqa: E501\n        fun of the pkt parameter\n        @return int; length of the data part of the HTTP/2 frame packet provided as parameter  # noqa: E501\n        @raise AssertionError"
  },
  {
    "code": "def RawBytesToScriptHash(raw):\n        rawh = binascii.unhexlify(raw)\n        rawhashstr = binascii.unhexlify(bytes(Crypto.Hash160(rawh), encoding='utf-8'))\n        return UInt160(data=rawhashstr)",
    "docstring": "Get a hash of the provided raw bytes using the ripemd160 algorithm.\n\n        Args:\n            raw (bytes): byte array of raw bytes. e.g. b'\\xAA\\xBB\\xCC'\n\n        Returns:\n            UInt160:"
  },
  {
    "code": "def dumplist(args):\n  from .query import Database\n  db = Database()\n  r = db.objects(\n      protocol=args.protocol,\n      purposes=args.purpose,\n      model_ids=(args.client,),\n      groups=args.group,\n      classes=args.sclass\n  )\n  output = sys.stdout\n  if args.selftest:\n    from bob.db.utils import null\n    output = null()\n  for f in r:\n    output.write('%s\\n' % (f.make_path(args.directory, args.extension),))\n  return 0",
    "docstring": "Dumps lists of files based on your criteria"
  },
  {
    "code": "def flg(self, name, help, abbrev=None):\n        abbrev = abbrev or '-' + name[0]\n        longname = '--' + name.replace('_', '-')\n        self._add(name, abbrev, longname, action='store_true', help=help)",
    "docstring": "Describe a flag"
  },
  {
    "code": "def GetValue(\n        self,\n        Channel,\n        Parameter):\n        try:\n            if Parameter == PCAN_API_VERSION or Parameter == PCAN_HARDWARE_NAME or Parameter == PCAN_CHANNEL_VERSION or Parameter == PCAN_LOG_LOCATION or Parameter == PCAN_TRACE_LOCATION or Parameter == PCAN_BITRATE_INFO_FD or Parameter == PCAN_IP_ADDRESS:\n                mybuffer = create_string_buffer(256)\n            else:\n                mybuffer = c_int(0)\n            res = self.__m_dllBasic.CAN_GetValue(Channel,Parameter,byref(mybuffer),sizeof(mybuffer))\n            return TPCANStatus(res),mybuffer.value\n        except:\n            logger.error(\"Exception on PCANBasic.GetValue\")\n            raise",
    "docstring": "Retrieves a PCAN Channel value\n\n        Remarks:\n          Parameters can be present or not according with the kind\n          of Hardware (PCAN Channel) being used. If a parameter is not available,\n          a PCAN_ERROR_ILLPARAMTYPE error will be returned.\n\n          The return value of this method is a 2-touple, where\n          the first value is the result (TPCANStatus) of the method and\n          the second one, the asked value\n\n        Parameters:\n          Channel   : A TPCANHandle representing a PCAN Channel\n          Parameter : The TPCANParameter parameter to get\n\n        Returns:\n          A touple with 2 values"
  },
  {
    "code": "def run_missing_simulations(self, param_list, runs=None):\n        if isinstance(param_list, dict):\n            param_list = list_param_combinations(param_list)\n        self.run_simulations(\n            self.get_missing_simulations(param_list, runs))",
    "docstring": "Run the simulations from the parameter list that are not yet available\n        in the database.\n\n        This function also makes sure that we have at least runs replications\n        for each parameter combination.\n\n        Additionally, param_list can either be a list containing the desired\n        parameter combinations or a dictionary containing multiple values for\n        each parameter, to be expanded into a list.\n\n        Args:\n            param_list (list, dict): either a list of parameter combinations or\n                a dictionary to be expanded into a list through the\n                list_param_combinations function.\n            runs (int): the number of runs to perform for each parameter\n                combination. This parameter is only allowed if the param_list\n                specification doesn't feature an 'RngRun' key already."
  },
  {
    "code": "def sync_experiments_from_spec(filename):\n    redis = oz.redis.create_connection()\n    with open(filename, \"r\") as f:\n        schema = escape.json_decode(f.read())\n    oz.bandit.sync_from_spec(redis, schema)",
    "docstring": "Takes the path to a JSON file declaring experiment specifications, and\n    modifies the experiments stored in redis to match the spec.\n\n    A spec looks like this:\n    {\n       \"experiment 1\": [\"choice 1\", \"choice 2\", \"choice 3\"],\n       \"experiment 2\": [\"choice 1\", \"choice 2\"]\n    }"
  },
  {
    "code": "def sup_of_layouts(layout1, layout2):\n        if len(layout1) > len(layout2):\n                layout1, layout2 = layout2, layout1\n        if len(layout1) < len(layout2):\n                layout1 += [0] * (len(layout2) - len(layout1))\n        return [max(layout1[i], layout2[i]) for i in xrange(len(layout1))]",
    "docstring": "Return the least layout compatible with layout1 and layout2"
  },
  {
    "code": "def autoescape(context, nodelist, setting):\n    old_setting = context.autoescape\n    context.autoescape = setting\n    output = nodelist.render(context)\n    context.autoescape = old_setting\n    if setting:\n        return mark_safe(output)\n    else:\n        return output",
    "docstring": "Force autoescape behaviour for this block."
  },
  {
    "code": "def _fetch_chunker(self, uri, chunk_size, size, obj_size):\n        pos = 0\n        total_bytes = 0\n        size = size or obj_size\n        max_size = min(size, obj_size)\n        while True:\n            endpos = min(obj_size, pos + chunk_size - 1)\n            headers = {\"Range\": \"bytes=%s-%s\" % (pos, endpos)}\n            resp, resp_body = self.api.method_get(uri, headers=headers,\n                    raw_content=True)\n            pos = endpos + 1\n            if not resp_body:\n                return\n            yield resp_body\n            total_bytes += len(resp_body)\n            if total_bytes >= max_size:\n                return",
    "docstring": "Returns a generator that returns an object in chunks."
  },
  {
    "code": "def incrementSub(self, amount=1):\n        self._subProgressBar.setValue(self.subValue() + amount)\r\n        QApplication.instance().processEvents()",
    "docstring": "Increments the sub-progress bar by amount."
  },
  {
    "code": "def terminate_jobflows(self, jobflow_ids):\n        params = {}\n        self.build_list_params(params, jobflow_ids, 'JobFlowIds.member')\n        return self.get_status('TerminateJobFlows', params, verb='POST')",
    "docstring": "Terminate an Elastic MapReduce job flow\n\n        :type jobflow_ids: list\n        :param jobflow_ids: A list of job flow IDs"
  },
  {
    "code": "def sessions_info(self, hosts):\n        info_by_id = {}\n        for server_endpoint, dump in self.dump_by_server(hosts).items():\n            server_ip, server_port = server_endpoint\n            for line in dump.split(\"\\n\"):\n                mat = self.IP_PORT_REGEX.match(line)\n                if mat is None:\n                    continue\n                ip, port, sid = mat.groups()\n                info_by_id[sid] = ClientInfo(sid, ip, port, server_ip, server_port)\n        return info_by_id",
    "docstring": "Returns ClientInfo per session.\n\n        :param hosts: comma separated lists of members of the ZK ensemble.\n        :returns: A dictionary of (session_id, ClientInfo)."
  },
  {
    "code": "def transform_flask_bare_import(node):\n    new_names = []\n    for (name, as_name) in node.names:\n        match = re.match(r'flask\\.ext\\.(.*)', name)\n        from_name = match.group(1)\n        actual_module_name = 'flask_{}'.format(from_name)\n        new_names.append((actual_module_name, as_name))\n    new_node = nodes.Import()\n    copy_node_info(node, new_node)\n    new_node.names = new_names\n    mark_transformed(new_node)\n    return new_node",
    "docstring": "Translates a flask.ext.wtf bare import into a non-magical import.\n\n    Translates:\n        import flask.ext.admin as admin\n    Into:\n        import flask_admin as admin"
  },
  {
    "code": "def find_sdk_dir(self):\n        if not SCons.Util.can_read_reg:\n            debug('find_sdk_dir(): can not read registry')\n            return None\n        hkey = self.HKEY_FMT % self.hkey_data\n        debug('find_sdk_dir(): checking registry:{}'.format(hkey))\n        try:\n            sdk_dir = common.read_reg(hkey)\n        except SCons.Util.WinError as e:\n            debug('find_sdk_dir(): no SDK registry key {}'.format(repr(hkey)))\n            return None\n        debug('find_sdk_dir(): Trying SDK Dir: {}'.format(sdk_dir))\n        if not os.path.exists(sdk_dir):\n            debug('find_sdk_dir():  {} not on file system'.format(sdk_dir))\n            return None\n        ftc = os.path.join(sdk_dir, self.sanity_check_file)\n        if not os.path.exists(ftc):\n            debug(\"find_sdk_dir(): sanity check {} not found\".format(ftc))\n            return None\n        return sdk_dir",
    "docstring": "Try to find the MS SDK from the registry.\n\n        Return None if failed or the directory does not exist."
  },
  {
    "code": "def _eta_from_phi(self):\n        self.eta = scipy.ndarray(N_NT - 1, dtype='float')\n        etaprod = 1.0\n        for w in range(N_NT - 1):\n            self.eta[w] = 1.0 - self.phi[w] / etaprod\n            etaprod *= self.eta[w]\n        _checkParam('eta', self.eta, self.PARAMLIMITS, self.PARAMTYPES)",
    "docstring": "Update `eta` using current `phi`."
  },
  {
    "code": "def data_from_bytes(self, byte_representation):\n        text = byte_representation.decode(self.encoding)\n        return self.data_from_string(text)",
    "docstring": "Converts the given bytes representation to resource data."
  },
  {
    "code": "def _resolve_atomtypes(topology):\n    for atom in topology.atoms():\n        atomtype = [rule_name for rule_name in atom.whitelist - atom.blacklist]\n        if len(atomtype) == 1:\n            atom.id = atomtype[0]\n        elif len(atomtype) > 1:\n            raise FoyerError(\"Found multiple types for atom {} ({}): {}.\".format(\n                atom.index, atom.element.name, atomtype))\n        else:\n            raise FoyerError(\"Found no types for atom {} ({}).\".format(\n                atom.index, atom.element.name))",
    "docstring": "Determine the final atomtypes from the white- and blacklists."
  },
  {
    "code": "def pop(self, key=__marker, default=__marker):\n        heap = self._heap\n        position = self._position\n        if key is self.__marker:\n            if not heap:\n                raise KeyError('pqdict is empty')\n            key = heap[0].key\n            del self[key]\n            return key\n        try:\n            pos = position.pop(key)\n        except KeyError:\n            if default is self.__marker:\n                raise\n            return default\n        else:\n            node_to_delete = heap[pos]\n            end = heap.pop()\n            if end is not node_to_delete:\n                heap[pos] = end\n                position[end.key] = pos\n                self._reheapify(pos)\n            value = node_to_delete.value\n            del node_to_delete\n            return value",
    "docstring": "If ``key`` is in the pqdict, remove it and return its priority value,\n        else return ``default``. If ``default`` is not provided and ``key`` is\n        not in the pqdict, raise a ``KeyError``.\n\n        If ``key`` is not provided, remove the top item and return its key, or\n        raise ``KeyError`` if the pqdict is empty."
  },
  {
    "code": "def post_collection(self, collection, body):\n        assert isinstance(body, (list)), \"POST requires body to be a list\"\n        assert collection.startswith('/'), \"Collections must start with /\"\n        uri = self.uri + '/v1' + collection\n        return self.service._post(uri, body)",
    "docstring": "Creates a new collection.  This is mostly just transport layer\n        and passes collection and body along.  It presumes the body\n        already has generated.\n\n        The collection is *not* expected to have the id."
  },
  {
    "code": "def init_vagrant(self, vagrant_file):\n        if self.inherit_image:\n            image_name, image_tag = str(self.inherit_image).split(\":\")\n        else:\n            image_name = self.get_arca_base_name()\n            image_tag = self.get_python_base_tag(self.get_python_version())\n        logger.info(\"Creating Vagrantfile located in %s, base image %s:%s\", vagrant_file, image_name, image_tag)\n        repos_dir = (Path(self._arca.base_dir) / 'repos').resolve()\n        vagrant_file.parent.mkdir(exist_ok=True, parents=True)\n        vagrant_file.write_text(dedent(f\n))\n        (vagrant_file.parent / \"runner.py\").write_text(self.RUNNER.read_text())",
    "docstring": "Creates a Vagrantfile in the target dir, with only the base image pulled.\n            Copies the runner script to the directory so it's accessible from the VM."
  },
  {
    "code": "def _join_list(lst, oxford=False):\n    if len(lst) > 2:\n        s = ', '.join(lst[:-1])\n        if oxford:\n            s += ','\n        s += ' and ' + lst[-1]\n    elif len(lst) == 2:\n        s = lst[0] + ' and ' + lst[1]\n    elif len(lst) == 1:\n        s = lst[0]\n    else:\n        s = ''\n    return s",
    "docstring": "Join a list of words in a gramatically correct way."
  },
  {
    "code": "def Start(self):\n    self.state.shadows = []\n    self.state.raw_device = None\n    self.CallClient(\n        server_stubs.WmiQuery,\n        query=\"SELECT * FROM Win32_ShadowCopy\",\n        next_state=\"ListDeviceDirectories\")",
    "docstring": "Query the client for available Volume Shadow Copies using a WMI query."
  },
  {
    "code": "def parse_manifest(template_lines):\n    manifest_files = distutils.filelist.FileList()\n    for line in template_lines:\n        if line.strip():\n            manifest_files.process_template_line(line)\n    return manifest_files.files",
    "docstring": "List of file names included by the MANIFEST.in template lines."
  },
  {
    "code": "def _merge_user_attrs(self, attrs_backend, attrs_out, backend_name):\n        for attr in attrs_backend:\n            if attr in self.attributes.backend_attributes[backend_name]:\n                attrid = self.attributes.backend_attributes[backend_name][attr]\n                if attrid not in attrs_out:\n                    attrs_out[attrid] = attrs_backend[attr]",
    "docstring": "merge attributes from one backend search to the attributes dict\n        output"
  },
  {
    "code": "def get_estimates_without_scope_in_month(self, customer):\n        estimates = self.get_price_estimates_for_customer(customer)\n        if not estimates:\n            return []\n        tables = {model: collections.defaultdict(list)\n                  for model in self.get_estimated_models()}\n        dates = set()\n        for estimate in estimates:\n            date = (estimate.year, estimate.month)\n            dates.add(date)\n            cls = estimate.content_type.model_class()\n            for model, table in tables.items():\n                if issubclass(cls, model):\n                    table[date].append(estimate)\n                    break\n        invalid_estimates = []\n        for date in dates:\n            if any(map(lambda table: len(table[date]) == 0, tables.values())):\n                for table in tables.values():\n                    invalid_estimates.extend(table[date])\n        print(invalid_estimates)\n        return invalid_estimates",
    "docstring": "It is expected that valid row for each month contains at least one\n        price estimate for customer, service setting, service,\n        service project link, project and resource.\n        Otherwise all price estimates in the row should be deleted."
  },
  {
    "code": "def only_path(self):\n        start = [v for v in self.nodes if self.nodes[v].get('start', False)]\n        if len(start) != 1: \n            raise ValueError(\"graph does not have exactly one start node\")\n        path = []\n        [v] = start\n        while True:\n            path.append(v)\n            u = v\n            vs = self.edges.get(u, ())\n            if len(vs) == 0:\n                break\n            elif len(vs) > 1:\n                raise ValueError(\"graph does not have exactly one path\")\n            [v] = vs\n        return path",
    "docstring": "Finds the only path from the start node. If there is more than one,\n        raises ValueError."
  },
  {
    "code": "def ean_13(name=None):\n    if name is None:\n        name = 'EAN 13 Field'\n    field = basic.numeric(13)\n    field = field.setName(name)\n    return field.setResultsName('ean_13')",
    "docstring": "Creates the grammar for an EAN 13 code.\n\n    These are the codes on thirteen digits barcodes.\n\n    :param name: name for the field\n    :return: grammar for an EAN 13 field"
  },
  {
    "code": "def get_correlation_table(self, chain=0, parameters=None, caption=\"Parameter Correlations\",\n                              label=\"tab:parameter_correlations\"):\n        parameters, cor = self.get_correlations(chain=chain, parameters=parameters)\n        return self._get_2d_latex_table(parameters, cor, caption, label)",
    "docstring": "Gets a LaTeX table of parameter correlations.\n\n        Parameters\n        ----------\n        chain : int|str, optional\n            The chain index or name. Defaults to first chain.\n        parameters : list[str], optional\n            The list of parameters to compute correlations. Defaults to all parameters\n            for the given chain.\n        caption : str, optional\n            The LaTeX table caption.\n        label : str, optional\n            The LaTeX table label.\n\n        Returns\n        -------\n            str\n                The LaTeX table ready to go!"
  },
  {
    "code": "def get_virtualenv_path(self, requirements_option: RequirementsOptions, requirements_hash: Optional[str]) -> Path:\n        if requirements_option == RequirementsOptions.no_requirements:\n            venv_name = \"no_requirements\"\n        else:\n            venv_name = requirements_hash\n        return Path(self._arca.base_dir) / \"venvs\" / venv_name",
    "docstring": "Returns the path to the virtualenv the current state of the repository."
  },
  {
    "code": "def neighborhood(self, node, degree=4):\n    assert self.by_name[node.name] == node\n    already_visited = frontier = set([node.name])\n    for _ in range(degree):\n      neighbor_names = set()\n      for node_name in frontier:\n        outgoing = set(n.name for n in self.by_input[node_name])\n        incoming = set(self.by_name[node_name].input)\n        neighbor_names |= incoming | outgoing\n      frontier = neighbor_names - already_visited\n      already_visited |= neighbor_names\n    return [self.by_name[name] for name in already_visited]",
    "docstring": "Am I really handcoding graph traversal please no"
  },
  {
    "code": "async def _assert_link_secret(self, action: str) -> str:\n        rv = await self.wallet.get_link_secret_label()\n        if rv is None:\n            LOGGER.debug('HolderProver._assert_link_secret: action %s requires link secret but it is not set', action)\n            raise AbsentLinkSecret('Action {} requires link secret but it is not set'.format(action))\n        return rv",
    "docstring": "Return current wallet link secret label. Raise AbsentLinkSecret if link secret is not set.\n\n        :param action: action requiring link secret"
  },
  {
    "code": "def sort(self, values):\n        for level in self:\n            for wire1, wire2 in level:\n                if values[wire1] > values[wire2]:\n                    values[wire1], values[wire2] = values[wire2], values[wire1]",
    "docstring": "Sort the values in-place based on the connectors in the network."
  },
  {
    "code": "def add_child(self, child):\n        if not isinstance(child, DependencyNode):\n            raise TypeError('\"child\" must be a DependencyNode')\n        self._children.append(child)",
    "docstring": "Add a child node"
  },
  {
    "code": "def fmt_row(self, columns, dimensions, row, **settings):\n        cells = []\n        i = 0\n        for column in columns:\n            cells.append(self.fmt_cell(\n                    row[i],\n                    dimensions[i],\n                    column,\n                    **settings[self.SETTING_TEXT_FORMATING]\n                )\n            )\n            i += 1\n        return self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING]) + \\\n               self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING]).join(cells) + \\\n               self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING])",
    "docstring": "Format single table row."
  },
  {
    "code": "def addUser(self, username, password,\n                firstname, lastname,\n                email, role):\n        self._invites.append({\n            \"username\":username,\n            \"password\":password,\n            \"firstname\":firstname,\n            \"lastname\":lastname,\n            \"fullname\":\"%s %s\" % (firstname, lastname),\n            \"email\":email,\n            \"role\":role\n        })",
    "docstring": "adds a user to the invitation list"
  },
  {
    "code": "async def post(self):\n        self.validate_ip()\n        dispatcher = self.get_dispatcher()\n        update = await self.parse_update(dispatcher.bot)\n        results = await self.process_update(update)\n        response = self.get_response(results)\n        if response:\n            web_response = response.get_web_response()\n        else:\n            web_response = web.Response(text='ok')\n        if self.request.app.get('RETRY_AFTER', None):\n            web_response.headers['Retry-After'] = self.request.app['RETRY_AFTER']\n        return web_response",
    "docstring": "Process POST request\n\n        if one of handler returns instance of :class:`aiogram.dispatcher.webhook.BaseResponse` return it to webhook.\n        Otherwise do nothing (return 'ok')\n\n        :return: :class:`aiohttp.web.Response`"
  },
  {
    "code": "def sign_message(message, private_key, public_key=None):\n    if public_key is None:\n        public_key = private_to_public_key(private_key)\n    return ed25519_blake2.signature_unsafe(message, private_key, public_key)",
    "docstring": "Signs a `message` using `private_key` and `public_key`\n\n    .. warning:: Not safe to use with secret keys or secret data. See module\n                 docstring.  This function should be used for testing only.\n\n    :param message: the message to sign\n    :type message: bytes\n\n    :param private_key: private key used to sign message\n    :type private_key: bytes\n\n    :param public_key: public key used to sign message\n    :type public_key: bytes\n\n    :return: the signature of the signed message\n    :rtype: bytes"
  },
  {
    "code": "def _get_paths():\n    import os\n    base_path = os.path.dirname(os.path.abspath(__file__))\n    test_data_dir = os.path.join(base_path, 'tests', 'data', 'Plate01')\n    test_data_file = os.path.join(test_data_dir, 'RFP_Well_A3.fcs')\n    return test_data_dir, test_data_file",
    "docstring": "Generate paths to test data. Done in a function to protect namespace a bit."
  },
  {
    "code": "def get_model(self):\n        if hasattr(self, 'model') and self.model:\n            return self.model\n        try:\n            none = self.get_queryset().none()\n            return none.model\n        except Exception:\n            raise ImproperlyConfigured(\n                \"Integrator: Unable to determine the model with this queryset.\"\n                \" Please add a `model` property\")",
    "docstring": "Return the class Model used by this Agnocomplete"
  },
  {
    "code": "def json_description(shape, **metadata):\n    metadata.update(shape=shape)\n    return json.dumps(metadata)",
    "docstring": "Return JSON image description from data shape and other metadata.\n\n    Return UTF-8 encoded JSON.\n\n    >>> json_description((256, 256, 3), axes='YXS')  # doctest: +SKIP\n    b'{\"shape\": [256, 256, 3], \"axes\": \"YXS\"}'"
  },
  {
    "code": "def serialize(self):\n        try:\n            return jsonpickle.encode(self, unpicklable=False)\n        except Exception:\n            log.exception(\"got an exception during serialization\")",
    "docstring": "Serialize to JSON document that can be accepted by the\n        X-Ray backend service. It uses jsonpickle to perform\n        serialization."
  },
  {
    "code": "def older_message(m, lastm):\n    atts = {'time_boot_ms' : 1.0e-3,\n            'time_unix_usec' : 1.0e-6,\n            'time_usec' : 1.0e-6}\n    for a in atts.keys():\n        if hasattr(m, a):\n            mul = atts[a]\n            t1 = m.getattr(a) * mul\n            t2 = lastm.getattr(a) * mul\n            if t2 >= t1 and t2 - t1 < 60:\n                return True\n    return False",
    "docstring": "return true if m is older than lastm by timestamp"
  },
  {
    "code": "def load_image(self, imagepath, width=None, height=None):\n        if width:\n            self.width = width\n            self.canvas[\"width\"] = width\n        if height:\n            self.height = height\n            self.canvas[\"height\"] = height\n        self.image = imagepath\n        size = (self.width, self.height)\n        load_image(self.canvas, self.image, bounds=size)\n        self.canvas.update_idletasks()",
    "docstring": "Loads new image into canvas, updating size if needed."
  },
  {
    "code": "def _setup_ipc(self):\n        log.debug('Setting up the internal IPC proxy')\n        self.ctx = zmq.Context()\n        self.sub = self.ctx.socket(zmq.SUB)\n        self.sub.bind(PUB_PX_IPC_URL)\n        self.sub.setsockopt(zmq.SUBSCRIBE, b'')\n        log.debug('Setting HWM for the proxy frontend: %d', self.hwm)\n        try:\n            self.sub.setsockopt(zmq.HWM, self.hwm)\n        except AttributeError:\n            self.sub.setsockopt(zmq.SNDHWM, self.hwm)\n        self.pub = self.ctx.socket(zmq.PUB)\n        self.pub.bind(PUB_IPC_URL)\n        log.debug('Setting HWM for the proxy backend: %d', self.hwm)\n        try:\n            self.pub.setsockopt(zmq.HWM, self.hwm)\n        except AttributeError:\n            self.pub.setsockopt(zmq.SNDHWM, self.hwm)",
    "docstring": "Setup the IPC PUB and SUB sockets for the proxy."
  },
  {
    "code": "def prepare_injection_directions(self):\n        if hasattr(self, 'pop_injection_directions') and self.pop_injection_directions:\n            ValueError(\"Looks like a bug in calling order/logics\")\n        ary = []\n        if (isinstance(self.adapt_sigma, CMAAdaptSigmaTPA) or\n                self.opts['mean_shift_line_samples']):\n            ary.append(self.mean - self.mean_old)\n            ary.append(self.mean_old - self.mean)\n            if ary[-1][0] == 0.0:\n                _print_warning('zero mean shift encountered which ',\n                               'prepare_injection_directions',\n                               'CMAEvolutionStrategy', self.countiter)\n        if self.opts['pc_line_samples']:\n            ary.append(self.pc.copy())\n        if self.sp.lam_mirr and self.opts['CMA_mirrormethod'] == 2:\n            if self.pop_sorted is None:\n                _print_warning('pop_sorted attribute not found, mirrors obmitted',\n                               'prepare_injection_directions',\n                               iteration=self.countiter)\n            else:\n                ary += self.get_selective_mirrors()\n        self.pop_injection_directions = ary\n        return ary",
    "docstring": "provide genotypic directions for TPA and selective mirroring,\n        with no specific length normalization, to be used in the\n        coming iteration.\n\n        Details:\n        This method is called in the end of `tell`. The result is\n        assigned to ``self.pop_injection_directions`` and used in\n        `ask_geno`.\n\n        TODO: should be rather appended?"
  },
  {
    "code": "def process_message(self, message, *args, **kwargs):\n        if not message.level in PERSISTENT_MESSAGE_LEVELS:\n            return message\n        user = kwargs.get(\"user\") or self.get_user()\n        try:\n            anonymous = user.is_anonymous()\n        except TypeError:\n            anonymous = user.is_anonymous\n        if anonymous:\n            raise NotImplementedError('Persistent message levels cannot be used for anonymous users.')\n        message_persistent = PersistentMessage()\n        message_persistent.level = message.level\n        message_persistent.message = message.message\n        message_persistent.extra_tags = message.extra_tags\n        message_persistent.user = user\n        if \"expires\" in kwargs:\n            message_persistent.expires = kwargs[\"expires\"]\n        message_persistent.save()\n        return None",
    "docstring": "If its level is into persist levels, convert the message to models and save it"
  },
  {
    "code": "def add(self, client_id, email_address, name, access_level, password):\n        body = {\n            \"EmailAddress\": email_address,\n            \"Name\": name,\n            \"AccessLevel\": access_level,\n            \"Password\": password}\n        response = self._post(\"/clients/%s/people.json\" %\n                              client_id, json.dumps(body))\n        return json_to_py(response)",
    "docstring": "Adds a person to a client. Password is optional and if not supplied, an invitation will be emailed to the person"
  },
  {
    "code": "def invalid_return_type_error(\n    return_type: GraphQLObjectType, result: Any, field_nodes: List[FieldNode]\n) -> GraphQLError:\n    return GraphQLError(\n        f\"Expected value of type '{return_type.name}' but got: {inspect(result)}.\",\n        field_nodes,\n    )",
    "docstring": "Create a GraphQLError for an invalid return type."
  },
  {
    "code": "def _dims2shape(*dims):\n    if not dims:\n        raise ValueError(\"expected at least one dimension spec\")\n    shape = list()\n    for dim in dims:\n        if isinstance(dim, int):\n            dim = (0, dim)\n        if isinstance(dim, tuple) and len(dim) == 2:\n            if dim[0] < 0:\n                raise ValueError(\"expected low dimension to be >= 0\")\n            if dim[1] < 0:\n                raise ValueError(\"expected high dimension to be >= 0\")\n            if dim[0] > dim[1]:\n                raise ValueError(\"expected low <= high dimensions\")\n            start, stop = dim\n        else:\n            raise TypeError(\"expected dimension to be int or (int, int)\")\n        shape.append((start, stop))\n    return tuple(shape)",
    "docstring": "Convert input dimensions to a shape."
  },
  {
    "code": "def status_server(self, port):\n        if self.status_server_started == False:\n            self.status_server_started = True\n            try:\n                self.status_service = binwalk.core.statuserver.StatusServer(port, self)\n            except Exception as e:\n                binwalk.core.common.warning(\"Failed to start status server on port %d: %s\" % (port, str(e)))",
    "docstring": "Starts the progress bar TCP service on the specified port.\n        This service will only be started once per instance, regardless of the\n        number of times this method is invoked.\n\n        Failure to start the status service is considered non-critical; that is,\n        a warning will be displayed to the user, but normal operation will proceed."
  },
  {
    "code": "def validateIP(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):\n    _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)\n    returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)\n    if returnNow:\n        return value\n    try:\n        try:\n            if validateRegex(value=value, regex=IPV4_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes):\n                return value\n        except:\n            pass\n        if validateRegex(value=value, regex=IPV6_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes):\n            return value\n    except ValidationException:\n        _raiseValidationException(_('%r is not a valid IP address.') % (_errstr(value)), excMsg)",
    "docstring": "Raises ValidationException if value is not an IPv4 or IPv6 address.\n    Returns the value argument.\n\n    * value (str): The value being validated as an IP address.\n    * blank (bool): If True, a blank string will be accepted. Defaults to False.\n    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.\n    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.\n    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.\n    * excMsg (str): A custom message to use in the raised ValidationException.\n\n    >>> import pysimplevalidate as pysv\n    >>> pysv.validateIP('127.0.0.1')\n    '127.0.0.1'\n    >>> pysv.validateIP('255.255.255.255')\n    '255.255.255.255'\n    >>> pysv.validateIP('256.256.256.256')\n    Traceback (most recent call last):\n    pysimplevalidate.ValidationException: '256.256.256.256' is not a valid IP address.\n    >>> pysv.validateIP('1:2:3:4:5:6:7:8')\n    '1:2:3:4:5:6:7:8'\n    >>> pysv.validateIP('1::8')\n    '1::8'\n    >>> pysv.validateIP('fe80::7:8%eth0')\n    'fe80::7:8%eth0'\n    >>> pysv.validateIP('::255.255.255.255')\n    '::255.255.255.255'"
  },
  {
    "code": "def get_performance_data(self, project, **params):\n        results = self._get_json(self.PERFORMANCE_DATA_ENDPOINT, project, **params)\n        return {k: PerformanceSeries(v) for k, v in results.items()}",
    "docstring": "Gets a dictionary of PerformanceSeries objects\n\n        You can specify which signatures to get by passing signature to this function"
  },
  {
    "code": "def partial(self, fn, *user_args, **user_kwargs):\n        self.get_annotations(fn)\n        def lazy_injection_fn(*run_args, **run_kwargs):\n            arg_pack = getattr(lazy_injection_fn, 'arg_pack', None)\n            if arg_pack is not None:\n                pack_args, pack_kwargs = arg_pack\n            else:\n                jeni_args, jeni_kwargs = self.prepare_callable(fn, partial=True)\n                pack_args = jeni_args + user_args\n                pack_kwargs = {}\n                pack_kwargs.update(jeni_kwargs)\n                pack_kwargs.update(user_kwargs)\n                lazy_injection_fn.arg_pack = (pack_args, pack_kwargs)\n            final_args = pack_args + run_args\n            final_kwargs = {}\n            final_kwargs.update(pack_kwargs)\n            final_kwargs.update(run_kwargs)\n            return fn(*final_args, **final_kwargs)\n        return lazy_injection_fn",
    "docstring": "Return function with closure to lazily inject annotated callable.\n\n        Repeat calls to the resulting function will reuse injections from the\n        first call.\n\n        Positional arguments are provided in this order:\n\n        1. positional arguments provided by injector\n        2. positional arguments provided in `partial_fn = partial(fn, *args)`\n        3. positional arguments provided in `partial_fn(*args)`\n\n        Keyword arguments are resolved in this order (later override earlier):\n\n        1. keyword arguments provided by injector\n        2. keyword arguments provided in `partial_fn = partial(fn, **kwargs)`\n        3. keyword arguments provided in `partial_fn(**kargs)`\n\n        Note that Python function annotations (in Python 3) are injected as\n        keyword arguments, as documented in `annotate`, which affects the\n        argument order here.\n\n        `annotate.partial` accepts arguments in same manner as this `partial`."
  },
  {
    "code": "def sample(self, probs, _covs, idxs, epsilons):\n        self.set_distribution(epsilons)\n        return self.distribution.sample(self.loss_ratios, probs)",
    "docstring": "Sample the .loss_ratios with the given probabilities.\n\n        :param probs:\n           array of E' floats\n        :param _covs:\n           ignored, it is there only for API consistency\n        :param idxs:\n           array of E booleans with E >= E'\n        :param epsilons:\n           array of E floats\n        :returns:\n           array of E' probabilities"
  },
  {
    "code": "def Scale(self, factor):\n        new = self.Copy()\n        new.xs = [x * factor for x in self.xs]\n        return new",
    "docstring": "Multiplies the xs by a factor.\n\n        factor: what to multiply by"
  },
  {
    "code": "def is_disconnected(self, node_id):\n        conn = self._conns.get(node_id)\n        if conn is None:\n            return False\n        return conn.disconnected()",
    "docstring": "Check whether the node connection has been disconnected or failed.\n\n        A disconnected node has either been closed or has failed. Connection\n        failures are usually transient and can be resumed in the next ready()\n        call, but there are cases where transient failures need to be caught\n        and re-acted upon.\n\n        Arguments:\n            node_id (int): the id of the node to check\n\n        Returns:\n            bool: True iff the node exists and is disconnected"
  },
  {
    "code": "def get_fw_dev_map(self, fw_id):\n        for cnt in self.res:\n            if fw_id in self.res.get(cnt).get('fw_id_lst'):\n                return self.res[cnt].get('obj_dict'), (\n                    self.res[cnt].get('mgmt_ip'))\n        return None, None",
    "docstring": "Return the object dict and mgmt ip for a firewall."
  },
  {
    "code": "def title(self, gender: Optional[Gender] = None,\n              title_type: Optional[TitleType] = None) -> str:\n        gender_key = self._validate_enum(gender, Gender)\n        title_key = self._validate_enum(title_type, TitleType)\n        titles = self._data['title'][gender_key][title_key]\n        return self.random.choice(titles)",
    "docstring": "Generate a random title for name.\n\n        You can generate random prefix or suffix\n        for name using this method.\n\n        :param gender: The gender.\n        :param title_type: TitleType enum object.\n        :return: The title.\n        :raises NonEnumerableError: if gender or title_type in incorrect format.\n\n        :Example:\n            PhD."
  },
  {
    "code": "def line( loc, strg ):\n    lastCR = strg.rfind(\"\\n\", 0, loc)\n    nextCR = strg.find(\"\\n\", loc)\n    if nextCR >= 0:\n        return strg[lastCR+1:nextCR]\n    else:\n        return strg[lastCR+1:]",
    "docstring": "Returns the line of text containing loc within a string, counting newlines as line separators."
  },
  {
    "code": "def close(self, code: int = None, reason: str = None) -> None:\n        if self.ws_connection:\n            self.ws_connection.close(code, reason)\n            self.ws_connection = None",
    "docstring": "Closes this Web Socket.\n\n        Once the close handshake is successful the socket will be closed.\n\n        ``code`` may be a numeric status code, taken from the values\n        defined in `RFC 6455 section 7.4.1\n        <https://tools.ietf.org/html/rfc6455#section-7.4.1>`_.\n        ``reason`` may be a textual message about why the connection is\n        closing.  These values are made available to the client, but are\n        not otherwise interpreted by the websocket protocol.\n\n        .. versionchanged:: 4.0\n\n           Added the ``code`` and ``reason`` arguments."
  },
  {
    "code": "def quoted_split(string, sep, quotes='\"'):\n    start = None\n    escape = False\n    quote = False\n    for i, c in enumerate(string):\n        if start is None:\n            start = i\n        if escape:\n            escape = False\n        elif quote:\n            if c == '\\\\':\n                escape = True\n            elif c == quote:\n                quote = False\n        elif c == sep:\n            yield string[start:i]\n            start = None\n        elif c in quotes:\n            quote = c\n    if start is not None:\n        yield string[start:]",
    "docstring": "Split a string on the given separation character, but respecting\n    double-quoted sections of the string.  Returns an iterator.\n\n    :param string: The string to split.\n    :param sep: The character separating sections of the string.\n    :param quotes: A string specifying all legal quote characters.\n\n    :returns: An iterator which will iterate over each element of the\n              string separated by the designated separator."
  },
  {
    "code": "def file_mtime(file_path):\n    if not os.path.isfile(file_path):\n        raise IOError('File \"%s\" does not exist.' % file_path)\n    ut = subprocess.check_output(['git', 'log', '-1', '--format=%ct',\n        file_path]).strip()\n    return datetime.fromtimestamp(int(ut))",
    "docstring": "Returns the file modified time. This is with regards to the last\n    modification the file has had in the droopescan repo, rather than actual\n    file modification time in the filesystem.\n    @param file_path: file path relative to the executable.\n    @return datetime.datetime object."
  },
  {
    "code": "def DeserializeMessage(self, response_type, data):\n        try:\n            message = encoding.JsonToMessage(response_type, data)\n        except (exceptions.InvalidDataFromServerError,\n                messages.ValidationError, ValueError) as e:\n            raise exceptions.InvalidDataFromServerError(\n                'Error decoding response \"%s\" as type %s: %s' % (\n                    data, response_type.__name__, e))\n        return message",
    "docstring": "Deserialize the given data as method_config.response_type."
  },
  {
    "code": "def overwrite_docs(self, doc):\n        for i in range(len(self.docstring)):\n            if (self.docstring[i].doctype == doc.doctype and\n                self.docstring[i].pointsto == doc.pointsto):\n                del self.docstring[i]\n                break\n        self.docstring.append(doc)",
    "docstring": "Adds the specified DocElement to the docstring list. However, if an\n        element with the same xml tag and pointsto value already exists, it\n        will be overwritten."
  },
  {
    "code": "def start(self, device):\n        super(NativeBLEVirtualInterface, self).start(device)\n        self.set_advertising(True)",
    "docstring": "Start serving access to this VirtualIOTileDevice\n\n        Args:\n            device (VirtualIOTileDevice): The device we will be providing access to"
  },
  {
    "code": "def get_all_project_owners(project_ids=None, **kwargs):\n    projowner_qry = db.DBSession.query(ProjectOwner)\n    if project_ids is not None:\n       projowner_qry = projowner_qry.filter(ProjectOwner.project_id.in_(project_ids))\n    project_owners_i = projowner_qry.all()\n    return [JSONObject(project_owner_i) for project_owner_i in project_owners_i]",
    "docstring": "Get the project owner entries for all the requested projects.\n        If the project_ids argument is None, return all the owner entries\n        for ALL projects"
  },
  {
    "code": "def process_order(self, order):\n        try:\n            dt_orders = self._orders_by_modified[order.dt]\n        except KeyError:\n            self._orders_by_modified[order.dt] = OrderedDict([\n                (order.id, order),\n            ])\n            self._orders_by_id[order.id] = order\n        else:\n            self._orders_by_id[order.id] = dt_orders[order.id] = order\n            move_to_end(dt_orders, order.id, last=True)\n        move_to_end(self._orders_by_id, order.id, last=True)",
    "docstring": "Keep track of an order that was placed.\n\n        Parameters\n        ----------\n        order : zp.Order\n            The order to record."
  },
  {
    "code": "def service_list():\n    r = salt.utils.http.query(DETAILS['url']+'service/list', decode_type='json', decode=True)\n    return r['dict']",
    "docstring": "List \"services\" on the REST server"
  },
  {
    "code": "def _depth_first_search(self, target_id, layer_id_list, node_list):\n        assert len(node_list) <= self.n_nodes\n        u = node_list[-1]\n        if u == target_id:\n            return True\n        for v, layer_id in self.adj_list[u]:\n            layer_id_list.append(layer_id)\n            node_list.append(v)\n            if self._depth_first_search(target_id, layer_id_list, node_list):\n                return True\n            layer_id_list.pop()\n            node_list.pop()\n        return False",
    "docstring": "Search for all the layers and nodes down the path.\n        A recursive function to search all the layers and nodes between the node in the node_list\n            and the node with target_id."
  },
  {
    "code": "def calc_qdga2_v1(self):\n    der = self.parameters.derived.fastaccess\n    old = self.sequences.states.fastaccess_old\n    new = self.sequences.states.fastaccess_new\n    if der.kd2 <= 0.:\n        new.qdga2 = new.qdgz2\n    elif der.kd2 > 1e200:\n        new.qdga2 = old.qdga2+new.qdgz2-old.qdgz2\n    else:\n        d_temp = (1.-modelutils.exp(-1./der.kd2))\n        new.qdga2 = (old.qdga2 +\n                     (old.qdgz2-old.qdga2)*d_temp +\n                     (new.qdgz2-old.qdgz2)*(1.-der.kd2*d_temp))",
    "docstring": "Perform the runoff concentration calculation for \"fast\" direct runoff.\n\n    The working equation is the analytical solution of the linear storage\n    equation under the assumption of constant change in inflow during\n    the simulation time step.\n\n    Required derived parameter:\n      |KD2|\n\n    Required state sequence:\n      |QDGZ2|\n\n    Calculated state sequence:\n      |QDGA2|\n\n    Basic equation:\n       :math:`QDGA2_{neu} = QDGA2_{alt} +\n       (QDGZ2_{alt}-QDGA2_{alt}) \\\\cdot (1-exp(-KD2^{-1})) +\n       (QDGZ2_{neu}-QDGZ2_{alt}) \\\\cdot (1-KD2\\\\cdot(1-exp(-KD2^{-1})))`\n\n    Examples:\n\n        A normal test case:\n\n        >>> from hydpy.models.lland import *\n        >>> parameterstep()\n        >>> derived.kd2(0.1)\n        >>> states.qdgz2.old = 2.0\n        >>> states.qdgz2.new = 4.0\n        >>> states.qdga2.old = 3.0\n        >>> model.calc_qdga2_v1()\n        >>> states.qdga2\n        qdga2(3.800054)\n\n        First extreme test case (zero division is circumvented):\n\n        >>> derived.kd2(0.0)\n        >>> model.calc_qdga2_v1()\n        >>> states.qdga2\n        qdga2(4.0)\n\n        Second extreme test case (numerical overflow is circumvented):\n\n        >>> derived.kd2(1e500)\n        >>> model.calc_qdga2_v1()\n        >>> states.qdga2\n        qdga2(5.0)"
  },
  {
    "code": "def untrack(context, file_names):\n    context.obj.find_repo_type()\n    for fn in file_names:\n        if context.obj.vc_name == 'git':\n            context.obj.call(['git', 'rm', '--cached', fn])\n        elif context.obj.vc_name == 'hg':\n            context.obj.call(['hg', 'forget', fn])",
    "docstring": "Forget about tracking each file in the list file_names\n\n    Tracking does not create or delete the actual file, it only tells the\n    version control system whether to maintain versions (to keep track) of\n    the file."
  },
  {
    "code": "def update_bgp_peer(self, bgp_peer_id, body=None):\n        return self.put(self.bgp_peer_path % bgp_peer_id, body=body)",
    "docstring": "Update a BGP peer."
  },
  {
    "code": "def get_sunrise_time(self, timeformat='unix'):\n        if self._sunrise_time is None:\n            return None\n        return timeformatutils.timeformat(self._sunrise_time, timeformat)",
    "docstring": "Returns the GMT time of sunrise\n\n        :param timeformat: the format for the time value. May be:\n            '*unix*' (default) for UNIX time or '*iso*' for ISO8601-formatted\n            string in the format ``YYYY-MM-DD HH:MM:SS+00``\n        :type timeformat: str\n        :returns: an int or a str or None\n        :raises: ValueError"
  },
  {
    "code": "def build_vec(self):\n        for item in all_calls:\n            self.__dict__[item] = []\n        for dev in self.devices:\n            for item in all_calls:\n                if self.system.__dict__[dev].n == 0:\n                    val = False\n                else:\n                    val = self.system.__dict__[dev].calls.get(item, False)\n                self.__dict__[item].append(val)",
    "docstring": "build call validity vector for each device"
  },
  {
    "code": "def _pdf(self, phi):\n        pdf = np.inner(self._vn, np.cos(np.outer(phi, self._n)))\n        pdf *= 2.\n        pdf += 1.\n        return pdf",
    "docstring": "Evaluate the _unnormalized_ flow PDF."
  },
  {
    "code": "def get_projected_player_game_stats_by_team(self, season, week, team_id):\n        result = self._method_call(\"PlayerGameProjectionStatsByTeam/{season}/{week}/{team_id}\", \"projections\", season=season, week=week, team_id=team_id)\n        return result",
    "docstring": "Projected Player Game Stats by Team"
  },
  {
    "code": "def mask_image_data(data):\n    if data.bands.size in (2, 4):\n        if not np.issubdtype(data.dtype, np.integer):\n            raise ValueError(\"Only integer datatypes can be used as a mask.\")\n        mask = data.data[-1, :, :] == np.iinfo(data.dtype).min\n        data = data.astype(np.float64)\n        masked_data = da.stack([da.where(mask, np.nan, data.data[i, :, :])\n                                for i in range(data.shape[0])])\n        data.data = masked_data\n        data = data.sel(bands=BANDS[data.bands.size - 1])\n    return data",
    "docstring": "Mask image data if alpha channel is present."
  },
  {
    "code": "def validate_format(self, allowed_formats):\n        if self.format in allowed_formats:\n            return\n        ui.error(\"Export type '{0}' does not accept '{1}' format, only: \"\n                 \"{2}\".format(self.type, self.format, allowed_formats))\n        sys.exit(1)",
    "docstring": "Validate the allowed formats for a specific type."
  },
  {
    "code": "def to_base64(self, skip=()):\n        return base64.b64encode(\n            ensure_bytes(\n                self.to_json(skip=skip),\n                encoding='utf-8',\n            )\n        )",
    "docstring": "Construct from base64-encoded JSON."
  },
  {
    "code": "def set (self, id, param, value):\n        assert isinstance(id, basestring)\n        assert isinstance(param, basestring)\n        assert is_iterable_typed(value, basestring)\n        self.params_.setdefault(param, {})[id] = value",
    "docstring": "Sets the value of a configuration parameter."
  },
  {
    "code": "def child(self):\n        return self.stream.directory[self.child_id] \\\n            if self.child_id != NOSTREAM else None",
    "docstring": "Root entry object has only one child entry and no siblings."
  },
  {
    "code": "def iter(self, query, *parameters, **kwargs):\n        cursor = self._cursor()\n        try:\n            self._execute(cursor, query, parameters or None, kwargs)\n            if cursor.description:\n                column_names = [column.name for column in cursor.description]\n                while True:\n                    record = cursor.fetchone()\n                    if not record:\n                        break\n                    yield Row(zip(column_names, record))\n            raise StopIteration\n        except:\n            cursor.close()\n            raise",
    "docstring": "Returns a generator for records from the query."
  },
  {
    "code": "def _set_result_from_operation(self):\n        with self._completion_lock:\n            if not self._operation.done or self._result_set:\n                return\n            if self._operation.HasField(\"response\"):\n                response = protobuf_helpers.from_any_pb(\n                    self._result_type, self._operation.response\n                )\n                self.set_result(response)\n            elif self._operation.HasField(\"error\"):\n                exception = exceptions.GoogleAPICallError(\n                    self._operation.error.message,\n                    errors=(self._operation.error,),\n                    response=self._operation,\n                )\n                self.set_exception(exception)\n            else:\n                exception = exceptions.GoogleAPICallError(\n                    \"Unexpected state: Long-running operation had neither \"\n                    \"response nor error set.\"\n                )\n                self.set_exception(exception)",
    "docstring": "Set the result or exception from the operation if it is complete."
  },
  {
    "code": "def load_from_JSON(json_filename):\n        try:\n            jsonfilecontent = json.loads(open(json_filename, 'r').read())\n        except ValueError as exc:\n            raise CredentialsFormatError(msg=\"Invalid JSON syntax: \"+str(exc))\n        instance = PIDClientCredentials(credentials_filename=json_filename,**jsonfilecontent)\n        return instance",
    "docstring": "Create a new instance of a PIDClientCredentials with information read\n        from a local JSON file.\n\n        :param json_filename: The path to the json credentials file. The json\n            file should have the following format:\n\n                .. code:: json\n\n                    {\n                        \"handle_server_url\": \"https://url.to.your.handle.server\",\n                        \"username\": \"index:prefix/suffix\",\n                        \"password\": \"ZZZZZZZ\",\n                        \"prefix\": \"prefix_to_use_for_writing_handles\",\n                        \"handleowner\": \"username_to_own_handles\"\n                    }\n\n            Any additional key-value-pairs are stored in the instance as\n            config.\n        :raises: :exc:`~b2handle.handleexceptions.CredentialsFormatError`\n        :raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`\n        :return: An instance."
  },
  {
    "code": "def create_ports(port, mpi, rank):\n        if port == \"random\" or port is None:\n            ports = {}\n        else:\n            port = int(port)\n            ports = {\n                \"REQ\": port + 0,\n                \"PUSH\": port + 1,\n                \"SUB\": port + 2\n            }\n        if mpi == 'all':\n            for port in ports:\n                ports[port] += (rank * 3)\n        return ports",
    "docstring": "create a list of ports for the current rank"
  },
  {
    "code": "def write_header(self):\n        self.fileobj.seek(0)\n        header = mar_header.build(dict(index_offset=self.last_offset))\n        self.fileobj.write(header)",
    "docstring": "Write the MAR header to the file.\n\n        The MAR header includes the MAR magic bytes as well as the offset to\n        where the index data can be found."
  },
  {
    "code": "def pull_dependencies(self, nodes):\n        visitor = DependencyFinderVisitor()\n        for node in nodes:\n            visitor.visit(node)\n        for dependency in 'filters', 'tests':\n            mapping = getattr(self, dependency)\n            for name in getattr(visitor, dependency):\n                if name not in mapping:\n                    mapping[name] = self.temporary_identifier()\n                self.writeline('%s = environment.%s[%r]' %\n                               (mapping[name], dependency, name))",
    "docstring": "Pull all the dependencies."
  },
  {
    "code": "def splittermixerfieldlists(data, commdct, objkey):\n    objkey = objkey.upper()\n    objindex = data.dtls.index(objkey)\n    objcomms = commdct[objindex]\n    theobjects = data.dt[objkey]\n    fieldlists = []\n    for theobject in theobjects:\n        fieldlist = list(range(1, len(theobject)))\n        fieldlists.append(fieldlist)\n    return fieldlists",
    "docstring": "docstring for splittermixerfieldlists"
  },
  {
    "code": "def render(self, surf):\n        pos, size = self.topleft, self.size\n        if not self.flags & self.NO_SHADOW:\n            if self.flags & self.NO_ROUNDING:\n                pygame.draw.rect(surf, LIGHT_GREY, (pos + self._bg_delta, size))\n            else:\n                roundrect(surf, (pos + self._bg_delta, size), LIGHT_GREY + (100,), 5)\n        if self.flags & self.NO_ROUNDING:\n            pygame.draw.rect(surf, self._get_color(), (pos + self._front_delta, size))\n        else:\n            roundrect(surf, (pos + self._front_delta, size), self._get_color(), 5)\n        self.text.center = self.center + self._front_delta\n        self.text.render(surf)",
    "docstring": "Render the button on a surface."
  },
  {
    "code": "def fit_model(y, x, yMaxLag, xMaxLag, includesOriginalX=True, noIntercept=False, sc=None):\n    assert sc != None, \"Missing SparkContext\"\n    jvm = sc._jvm\n    jmodel = jvm.com.cloudera.sparkts.models.AutoregressionX.fitModel(_nparray2breezevector(sc, y.toArray()), _nparray2breezematrix(sc, x.toArray()), yMaxLag, xMaxLag, includesOriginalX, noIntercept)\n    return ARXModel(jmodel=jmodel, sc=sc)",
    "docstring": "Fit an autoregressive model with additional exogenous variables. The model predicts a value\n    at time t of a dependent variable, Y, as a function of previous values of Y, and a combination\n    of previous values of exogenous regressors X_i, and current values of exogenous regressors X_i.\n    This is a generalization of an AR model, which is simply an ARX with no exogenous regressors.\n    The fitting procedure here is the same, using least squares. Note that all lags up to the\n    maxlag are included. In the case of the dependent variable the max lag is 'yMaxLag', while\n    for the exogenous variables the max lag is 'xMaxLag', with which each column in the original\n    matrix provided is lagged accordingly.\n\n    Parameters\n    ----------\n    y:\n            the dependent variable, time series as a Numpy array\n    x:\n            a matrix of exogenous variables as a Numpy array\n    yMaxLag:\n            the maximum lag order for the dependent variable\n    xMaxLag:\n            the maximum lag order for exogenous variables\n    includesOriginalX:\n            a boolean flag indicating if the non-lagged exogenous variables should\n            be included. Default is true\n    noIntercept:\n            a boolean flag indicating if the intercept should be dropped. Default is\n            false\n        \n    Returns an ARXModel, which is an autoregressive model with exogenous variables."
  },
  {
    "code": "def merge_task_lists(runset_results, tasks):\n    for runset in runset_results:\n        dic = dict([(run_result.task_id, run_result) for run_result in reversed(runset.results)])\n        runset.results = []\n        for task in tasks:\n            run_result = dic.get(task)\n            if run_result is None:\n                logging.info(\"    No result for task '%s' in '%s'.\",\n                             task[0], Util.prettylist(runset.attributes['filename']))\n                run_result = RunResult(task, None, result.CATEGORY_MISSING, None, None,\n                                       runset.columns, [None]*len(runset.columns))\n            runset.results.append(run_result)",
    "docstring": "Set the filelists of all RunSetResult elements so that they contain the same files\n    in the same order. For missing files a dummy element is inserted."
  },
  {
    "code": "def _wrap_element(self, element):\n        def dirty_callback():\n            self._set_dirty()\n        if isinstance(element, list):\n            element = ProxyList(element, dirty_callback=dirty_callback)\n        elif isinstance(element, dict):\n            element = ProxyDict(element, dirty_callback=dirty_callback)\n        elif getattr(element, '_dirty_callback', self._sentinel) is not self._sentinel:\n            if not callable(element._dirty_callback):\n                element._dirty_callback = dirty_callback\n        return element",
    "docstring": "We want to know if an item is modified that is stored in this dict. If the element is a list or dict,\n        we wrap it in a ProxyList or ProxyDict, and if it is modified execute a callback that updates this\n        instance. If it is a ZenpyObject, then the callback updates the parent object."
  },
  {
    "code": "def iter_subscriptions(self, login=None, number=-1, etag=None):\n        if login:\n            return self.user(login).iter_subscriptions()\n        url = self._build_url('user', 'subscriptions')\n        return self._iter(int(number), url, Repository, etag=etag)",
    "docstring": "Iterate over repositories subscribed to by ``login`` or the\n        authenticated user.\n\n        :param str login: (optional), name of user whose subscriptions you want\n            to see\n        :param int number: (optional), number of repositories to return.\n            Default: -1 returns all repositories\n        :param str etag: (optional), ETag from a previous request to the same\n            endpoint\n        :returns: generator of :class:`Repository <github3.repos.Repository>`"
  },
  {
    "code": "def get_queryset(self):\n        \"Restrict to a single kind of event, if any, and include Venue data.\"\n        qs = super().get_queryset()\n        kind = self.get_event_kind()\n        if kind is not None:\n            qs = qs.filter(kind=kind)\n        qs = qs.select_related('venue')\n        return qs",
    "docstring": "Restrict to a single kind of event, if any, and include Venue data."
  },
  {
    "code": "def good_classmethod_decorator(decorator):\n    def new_decorator(cls, f):\n        g = decorator(cls, f)\n        g.__name__ = f.__name__\n        g.__doc__ = f.__doc__\n        g.__dict__.update(f.__dict__)\n        return g\n    new_decorator.__name__ = decorator.__name__\n    new_decorator.__doc__ = decorator.__doc__\n    new_decorator.__dict__.update(decorator.__dict__)\n    return new_decorator",
    "docstring": "This decorator makes class method decorators behave well wrt\n    to decorated class method names, doc, etc."
  },
  {
    "code": "def list_firmware_images(self, **kwargs):\n        kwargs = self._verify_sort_options(kwargs)\n        kwargs = self._verify_filters(kwargs, FirmwareImage, True)\n        api = self._get_api(update_service.DefaultApi)\n        return PaginatedResponse(api.firmware_image_list, lwrap_type=FirmwareImage, **kwargs)",
    "docstring": "List all firmware images.\n\n        :param int limit: number of firmware images to retrieve\n        :param str order: ordering of images when ordered by time. 'desc' or 'asc'\n        :param str after: get firmware images after given `image_id`\n        :param dict filters: Dictionary of filters to apply\n        :return: list of :py:class:`FirmwareImage` objects\n        :rtype: PaginatedResponse"
  },
  {
    "code": "def docs_cli(ctx, recreate, gen_index, run_doctests):\n    if ctx.invoked_subcommand:\n        return\n    from peltak.logic import docs\n    docs.docs(recreate, gen_index, run_doctests)",
    "docstring": "Build project documentation.\n\n    This command will run sphinx-refdoc first to generate the reference\n    documentation for the code base. Then it will run sphinx to generate the\n    final docs. You can configure the directory that stores the docs source\n    (index.rst, conf.py, etc.) using the DOC_SRC_PATH conf variable. In case you\n    need it, the sphinx build directory is located in ``BUILD_DIR/docs``.\n\n    The reference documentation will be generated for all directories listed\n    under 'REFDOC_PATHS conf variable. By default it is empty so no reference\n    docs are generated.\n\n    Sample Config::\n\n        \\b\n        build_dir: '.build'\n\n        docs:\n          path: 'docs'\n          reference:\n            - 'src/mypkg'\n\n    Examples::\n\n        \\b\n        $ peltak docs                           # Generate docs for the project\n        $ peltak docs --no-index                # Skip main reference index\n        $ peltak docs --recreate --no-index     # Build docs from clean slate"
  },
  {
    "code": "def network_pf(network, snapshots=None, skip_pre=False, x_tol=1e-6, use_seed=False):\n    return _network_prepare_and_run_pf(network, snapshots, skip_pre, linear=False, x_tol=x_tol, use_seed=use_seed)",
    "docstring": "Full non-linear power flow for generic network.\n\n    Parameters\n    ----------\n    snapshots : list-like|single snapshot\n        A subset or an elements of network.snapshots on which to run\n        the power flow, defaults to network.snapshots\n    skip_pre: bool, default False\n        Skip the preliminary steps of computing topology, calculating dependent values and finding bus controls.\n    x_tol: float\n        Tolerance for Newton-Raphson power flow.\n    use_seed : bool, default False\n        Use a seed for the initial guess for the Newton-Raphson algorithm.\n\n    Returns\n    -------\n    Dictionary with keys 'n_iter', 'converged', 'error' and dataframe\n    values indicating number of iterations, convergence status, and\n    iteration error for each snapshot (rows) and sub_network (columns)"
  },
  {
    "code": "def smoothEstimate(self, nodeShape, estimatedNodeCount):\n        weightedEstimate = (1 - self.betaInertia) * estimatedNodeCount + \\\n                           self.betaInertia * self.previousWeightedEstimate[nodeShape]\n        self.previousWeightedEstimate[nodeShape] = weightedEstimate\n        return self._round(weightedEstimate)",
    "docstring": "Smooth out fluctuations in the estimate for this node compared to\n        previous runs. Returns an integer."
  },
  {
    "code": "def get_dataset_split(tmp_dir, split, use_control_set):\n  if not use_control_set:\n    dataset_split = {\n        problem.DatasetSplit.TRAIN: [\n            f for f in tf.gfile.Glob(\n                os.path.join(tmp_dir, \"train-novels/*/*.txt\"))\n        ],\n        problem.DatasetSplit.EVAL: [\n            os.path.join(tmp_dir, \"lambada_development_plain_text.txt\")\n        ],\n        problem.DatasetSplit.TEST: [\n            os.path.join(tmp_dir, \"lambada_test_plain_text.txt\")\n        ]\n    }\n  else:\n    dataset_split = {\n        problem.DatasetSplit.TRAIN: [\n            f for f in tf.gfile.Glob(\n                os.path.join(tmp_dir, \"train-novels/*/*.txt\"))\n        ],\n        problem.DatasetSplit.EVAL: [\n            os.path.join(tmp_dir, \"lambada_control_test_data_plain_text.txt\")\n        ],\n    }\n  return dataset_split[split]",
    "docstring": "Gives the file paths with regards to the given split.\n\n  Args:\n    tmp_dir: temp directory\n    split: dataset split\n    use_control_set: uses control dataset if true.\n\n  Returns:\n    list of file paths."
  },
  {
    "code": "def shift(self, periods, axis=0, fill_value=None):\n        new_values, fill_value = maybe_upcast(self.values, fill_value)\n        f_ordered = new_values.flags.f_contiguous\n        if f_ordered:\n            new_values = new_values.T\n            axis = new_values.ndim - axis - 1\n        if np.prod(new_values.shape):\n            new_values = np.roll(new_values, ensure_platform_int(periods),\n                                 axis=axis)\n        axis_indexer = [slice(None)] * self.ndim\n        if periods > 0:\n            axis_indexer[axis] = slice(None, periods)\n        else:\n            axis_indexer[axis] = slice(periods, None)\n        new_values[tuple(axis_indexer)] = fill_value\n        if f_ordered:\n            new_values = new_values.T\n        return [self.make_block(new_values)]",
    "docstring": "shift the block by periods, possibly upcast"
  },
  {
    "code": "def md_to_pdf(input_name, output_name):\n    if output_name[-4:] == '.pdf':\n        os.system(\"pandoc \" + input_name + \" -o \" + output_name)\n    else:\n        os.system(\"pandoc \" + input_name + \" -o \" + output_name + \".pdf\" )",
    "docstring": "Converts an input MarkDown file to a PDF of the given output name.\n\n    Parameters\n    ==========\n    input_name : String\n    Relative file location of the input file to where this function is being called.\n\n    output_name : String\n    Relative file location of the output file to where this function is being called. Note that .pdf can be omitted.\n\n    Examples\n    ========\n    Suppose we have a directory as follows:\n    data/\n        doc.md\n    \n    To convert the document:\n    >>> from aide_document import convert\n    >>> convert.md_to_pdf('data/doc.md', 'data/doc.pdf')\n\n    .pdf can also be omitted from the second argument."
  },
  {
    "code": "def get_display_name(value):\n    display_name = DisplayName()\n    token, value = get_phrase(value)\n    display_name.extend(token[:])\n    display_name.defects = token.defects[:]\n    return display_name, value",
    "docstring": "display-name = phrase\n\n    Because this is simply a name-rule, we don't return a display-name\n    token containing a phrase, but rather a display-name token with\n    the content of the phrase."
  },
  {
    "code": "def from_emcee(sampler=None, *, var_names=None, arg_names=None, coords=None, dims=None):\n    return EmceeConverter(\n        sampler=sampler, var_names=var_names, arg_names=arg_names, coords=coords, dims=dims\n    ).to_inference_data()",
    "docstring": "Convert emcee data into an InferenceData object.\n\n    Parameters\n    ----------\n    sampler : emcee.EnsembleSampler\n        Fitted sampler from emcee.\n    var_names : list[str] (Optional)\n        A list of names for variables in the sampler\n    arg_names : list[str] (Optional)\n        A list of names for args in the sampler\n    coords : dict[str] -> list[str]\n        Map of dimensions to coordinates\n    dims : dict[str] -> list[str]\n        Map variable names to their coordinates\n\n    Returns\n    -------\n    InferenceData\n\n    Examples\n    --------\n    Passing an ``emcee.EnsembleSampler`` object to ``az.from_emcee`` converts it\n    to an InferenceData object. Start defining the model and running the sampler:\n\n    .. plot::\n        :context: close-figs\n\n        >>> import emcee\n        >>> import numpy as np\n        >>> import arviz as az\n        >>> J = 8\n        >>> y_obs = np.array([28.0, 8.0, -3.0, 7.0, -1.0, 1.0, 18.0, 12.0])\n        >>> sigma = np.array([15.0, 10.0, 16.0, 11.0, 9.0, 11.0, 10.0, 18.0])\n        >>> def log_prior_8school(theta):\n        >>>     mu, tau, eta = theta[0], theta[1], theta[2:]\n        >>>     # Half-cauchy prior, hwhm=25\n        >>>     if tau < 0:\n        >>>         return -np.inf\n        >>>     prior_tau = -np.log(tau ** 2 + 25 ** 2)\n        >>>     prior_mu = -(mu / 10) ** 2  # normal prior, loc=0, scale=10\n        >>>     prior_eta = -np.sum(eta ** 2)  # normal prior, loc=0, scale=1\n        >>>     return prior_mu + prior_tau + prior_eta\n        >>> def log_likelihood_8school(theta, y, s):\n        >>>     mu, tau, eta = theta[0], theta[1], theta[2:]\n        >>>     return -((mu + tau * eta - y) / s) ** 2\n        >>> def lnprob_8school(theta, y, s):\n        >>>     prior = log_prior_8school(theta)\n        >>>     like_vect = log_likelihood_8school(theta, y, s)\n        >>>     like = np.sum(like_vect)\n        >>>     return like + prior\n        >>> nwalkers, draws = 50, 7000\n        >>> ndim = J + 2\n        >>> pos = np.random.normal(size=(nwalkers, ndim))\n        >>> pos[:, 1] = np.absolute(pos[:, 1])\n        >>> sampler = emcee.EnsembleSampler(\n        >>>     nwalkers,\n        >>>     ndim,\n        >>>     lnprob_8school,\n        >>>     args=(y_obs, sigma)\n        >>> )\n        >>> sampler.run_mcmc(pos, draws);\n\n    And convert the sampler to an InferenceData object. As emcee does not store variable\n    names, they must be passed to the converter in order to have them:\n\n    .. plot::\n        :context: close-figs\n\n        >>> var_names = ['mu', 'tau']+['eta{}'.format(i) for i in range(J)]\n        >>> emcee_data = az.from_emcee(sampler, var_names=var_names)\n\n    From an InferenceData object, ArviZ's native data structure, the posterior plot\n    of the first 3 variables can be done in one line:\n\n    .. plot::\n        :context: close-figs\n\n        >>> az.plot_posterior(emcee_data, var_names=var_names[:3])\n\n    And the trace:\n\n    .. plot::\n        :context: close-figs\n\n        >>> az.plot_trace(emcee_data, var_names=['mu'])\n\n    Emcee is an Affine Invariant MCMC Ensemble Sampler, thus, its chains are **not**\n    independent, which means that many ArviZ functions can not be used, at least directly.\n    However, it is possible to combine emcee and ArviZ and use most of ArviZ\n    functionalities. The first step is to modify the probability function to use the\n    ``blobs`` and store the log_likelihood, then rerun the sampler using the new function:\n\n    .. plot::\n        :context: close-figs\n\n\n        >>> def lnprob_8school_blobs(theta, y, s):\n        >>>     prior = log_prior_8school(theta)\n        >>>     like_vect = log_likelihood_8school(theta, y, s)\n        >>>     like = np.sum(like_vect)\n        >>>     return like + prior, like_vect\n        >>> sampler_blobs = emcee.EnsembleSampler(\n        >>>     nwalkers,\n        >>>     ndim,\n        >>>     lnprob_8school_blobs,\n        >>>     args=(y_obs, sigma)\n        >>> )\n        >>> sampler_blobs.run_mcmc(pos, draws);\n\n    ArviZ has no support for the ``blobs`` functionality yet, but a workaround can be\n    created. First make sure that the dimensions are in the order\n    ``(chain, draw, *shape)``. It may also be a good idea to apply a burn-in period\n    and to thin the draw dimension (which due to the correlations between chains and\n    consecutive draws, won't reduce the effective sample size if the value is small enough).\n    Then convert the numpy arrays to InferenceData, in this case using ``az.from_dict``:\n\n    .. plot::\n        :context: close-figs\n\n        >>> burnin, thin = 500, 10\n        >>> blobs = np.swapaxes(np.array(sampler_blobs.blobs), 0, 1)[:, burnin::thin, :]\n        >>> chain = sampler_blobs.chain[:, burnin::thin, :]\n        >>> posterior_dict = {\"mu\": chain[:, :, 0], \"tau\": chain[:, :, 1], \"eta\": chain[:, :, 2:]}\n        >>> stats_dict = {\"log_likelihood\": blobs}\n        >>> emcee_data = az.from_dict(\n        >>>     posterior=posterior_dict,\n        >>>     sample_stats=stats_dict,\n        >>>     coords={\"school\": range(8)},\n        >>>     dims={\"eta\": [\"school\"], \"log_likelihood\": [\"school\"]}\n        >>> )\n\n    To calculate the effective sample size emcee's functions must be used. There are\n    many changes in emcee's API from version 2 to 3, thus, the calculation is different\n    depending on the version. In addition, in version 2, the autocorrelation time raises\n    an error if the chain is not long enough.\n\n    .. plot::\n        :context: close-figs\n\n        >>> if emcee.__version__[0] == '3':\n        >>>     ess=(draws-burnin)/sampler.get_autocorr_time(quiet=True, discard=burnin, thin=thin)\n        >>> else:\n        >>>     # to avoid error while generating the docs, the ess value is hard coded, it\n        >>>     # should be calculated with:\n        >>>     # ess = chain.shape[1] / emcee.autocorr.integrated_time(chain)\n        >>>     ess = (draws-burnin)/30\n        >>> reff = np.mean(ess) / (nwalkers * chain.shape[1])\n\n    This value can afterwards be used to estimate the leave-one-out cross-validation using\n    Pareto smoothed importance sampling with ArviZ and plot the results:\n\n    .. plot::\n        :context: close-figs\n\n        >>> loo_stats = az.loo(emcee_data, reff=reff, pointwise=True)\n        >>> az.plot_khat(loo_stats.pareto_k)"
  },
  {
    "code": "def make_gym_env(env_id, num_env=2, seed=123, wrapper_kwargs=None, start_index=0):\n    if wrapper_kwargs is None:\n        wrapper_kwargs = {}\n    def make_env(rank):\n        def _thunk():\n            env = gym.make(env_id)\n            env.seed(seed + rank)\n            return env\n        return _thunk\n    set_global_seeds(seed)\n    return SubprocVecEnv([make_env(i + start_index) for i in range(num_env)])",
    "docstring": "Create a wrapped, SubprocVecEnv for Gym Environments."
  },
  {
    "code": "def __exportUsers(self, sort, limit=0):\n        position = 1\n        dataUsers = self.getSortedUsers(sort)\n        if limit:\n            dataUsers = dataUsers[:limit]\n        exportedUsers = []\n        for u in dataUsers:\n            userExported = u.export()\n            userExported[\"position\"] = position\n            exportedUsers.append(userExported)\n            if position < len(dataUsers):\n                userExported[\"comma\"] = True\n            position += 1\n        return exportedUsers",
    "docstring": "Export the users to a dictionary.\n\n        :param sort: field to sort the users\n        :type sort: str.\n        :return: exported users.\n        :rtype: dict."
  },
  {
    "code": "def subscribe(self, topic, qos=0):\n        result, mid = self.client.subscribe(topic=topic, qos=qos)\n        if result == MQTT_ERR_SUCCESS:\n            self.topics[topic] = TopicQos(topic=topic, qos=qos)\n            logger.debug('Subscribed to topic: {0}, qos: {1}'\n                         .format(topic, qos))\n        else:\n            logger.error('Error {0} subscribing to topic: {1}'\n                         .format(result, topic))\n        return (result, mid)",
    "docstring": "Subscribe to a certain topic.\n\n        :param topic: a string specifying the subscription topic to\n            subscribe to.\n        :param qos: the desired quality of service level for the subscription.\n                    Defaults to 0.\n\n        :rtype: (int, int)\n        :result: (result, mid)\n\n        A topic is a UTF-8 string, which is used by the broker to filter\n        messages for each connected client. A topic consists of one or more\n        topic levels. Each topic level is separated by a forward slash\n        (topic level separator).\n\n        The function returns a tuple (result, mid), where result is\n        MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the\n        client is not currently connected.  mid is the message ID for the\n        subscribe request. The mid value can be used to track the subscribe\n        request by checking against the mid argument in the on_subscribe()\n        callback if it is defined.\n\n        **Topic example:** `myhome/groundfloor/livingroom/temperature`"
  },
  {
    "code": "def clear(self):\n        if self.default_value is None:\n            self.current_value = bytearray()\n        else:\n            self.current_value = bytearray(self.default_value)",
    "docstring": "Clear this config variable to its reset value."
  },
  {
    "code": "def get_parents(obj, **kwargs):\n    num_of_mro = kwargs.get(\"num_of_mro\", 5)\n    mro = getmro(obj.__class__)\n    mro_string = ', '.join([extract_type(str(t)) for t in mro[:num_of_mro]])\n    return \"Hierarchy: {}\".format(mro_string)",
    "docstring": "Return the MRO of an object. Do regex on each element to remove the \"<class...\" bit."
  },
  {
    "code": "def rpop(self, key, *, encoding=_NOTSET):\n        return self.execute(b'RPOP', key, encoding=encoding)",
    "docstring": "Removes and returns the last element of the list stored at key."
  },
  {
    "code": "def getitem_column_array(self, key):\n        numeric_indices = list(self.columns.get_indexer_for(key))\n        def getitem(df, internal_indices=[]):\n            return df.iloc[:, internal_indices]\n        result = self.data.apply_func_to_select_indices(\n            0, getitem, numeric_indices, keep_remaining=False\n        )\n        new_columns = self.columns[numeric_indices]\n        new_dtypes = self.dtypes[numeric_indices]\n        return self.__constructor__(result, self.index, new_columns, new_dtypes)",
    "docstring": "Get column data for target labels.\n\n        Args:\n            key: Target labels by which to retrieve data.\n\n        Returns:\n            A new QueryCompiler."
  },
  {
    "code": "def memory_usage(self, **kwargs):\n        def memory_usage_builder(df, **kwargs):\n            return df.memory_usage(**kwargs)\n        func = self._build_mapreduce_func(memory_usage_builder, **kwargs)\n        return self._full_axis_reduce(0, func)",
    "docstring": "Returns the memory usage of each column.\n\n        Returns:\n            A new QueryCompiler object containing the memory usage of each column."
  },
  {
    "code": "def on_click(self, event):\n        if event['button'] == 1 and 'button1' in self.options:\n            subprocess.call(self.options['button1'].split())\n        elif event['button'] == 2 and 'button2' in self.options:\n            subprocess.call(self.options['button2'].split())\n        elif event['button'] == 3 and 'button3' in self.options:\n            subprocess.call(self.options['button3'].split())",
    "docstring": "A function that should be overwritten by a plugin that wishes to react\n        to events, if it wants to perform any action other than running the\n        supplied command related to a button.\n\n        event: A dictionary passed from i3bar (after being decoded from JSON)\n        that has the folowing format:\n\n        event = {'name': 'my_plugin', 'x': 231, 'y': 423}\n        Note: It is also possible to have an instance key, but i3situation\n        doesn't set it."
  },
  {
    "code": "def get_summary(session):\n    profile = get_profile(session)\n    return {\n        'user': {\n            'email': profile['userProfile']['eMail'],\n            'name': '{} {}'.format(profile['userProfile']['firstName'],\n                                   profile['userProfile']['lastName'])\n        },\n        'vehicles': [\n            {\n                'vin': vehicle['vin'],\n                'year': vehicle['year'],\n                'make': vehicle['make'],\n                'model': _get_model(vehicle),\n                'odometer': vehicle['odometerMileage']\n            } for vehicle in profile['vehicles']\n        ]\n    }",
    "docstring": "Get vehicle summary."
  },
  {
    "code": "def init(directory):\n    username = click.prompt(\"Input your username\")\n    password = click.prompt(\"Input your password\", hide_input=True,\n                            confirmation_prompt=True)\n    log_directory = click.prompt(\"Input your log directory\")\n    if not path.exists(log_directory):\n        sys.exit(\"Invalid log directory, please have a check.\")\n    config_file_path = path.join(directory, 'v2ex_config.json')\n    config = {\n        \"username\": username,\n        \"password\": password,\n        \"log_directory\": path.abspath(log_directory)\n    }\n    with open(config_file_path, 'w') as f:\n        json.dump(config, f)\n    click.echo(\"Init the config file at: {0}\".format(config_file_path))",
    "docstring": "Init the config fle."
  },
  {
    "code": "def select(table, cols=\"*\", where=(), group=\"\", order=(), limit=(), **kwargs):\r\n    where = dict(where, **kwargs).items()\r\n    sql, args = makeSQL(\"SELECT\", table, cols, where, group, order, limit)\r\n    return execute(sql, args)",
    "docstring": "Convenience wrapper for database SELECT."
  },
  {
    "code": "def set_token(self, token):\n        self.token = token\n        self.set_header(\n            'Authorization',\n            \"Bearer {}\".format(token)\n        )",
    "docstring": "Set the token for the v20 context\n\n        Args:\n            token: The token used to access the v20 REST api"
  },
  {
    "code": "def sg_input(shape=None, dtype=sg_floatx, name=None):\n    r\n    if shape is None:\n        return tf.placeholder(dtype, shape=None, name=name)\n    else:\n        if not isinstance(shape, (list, tuple)):\n            shape = [shape]\n        return tf.placeholder(dtype, shape=[None] + list(shape), name=name)",
    "docstring": "r\"\"\"Creates a placeholder.\n\n    Args:\n      shape: A tuple/list of integers. If an integers is given, it will turn to a list.\n      dtype: A data type. Default is float32.\n      name: A name for the placeholder.\n\n    Returns:\n      A wrapped placeholder `Tensor`."
  },
  {
    "code": "def add_column(self, func, name=None, show=True):\n        assert func\n        name = name or func.__name__\n        if name == '<lambda>':\n            raise ValueError(\"Please provide a valid name for \" + name)\n        d = {'func': func,\n             'show': show,\n             }\n        self._columns[name] = d\n        data = _create_json_dict(cols=self.column_names,\n                                 )\n        self.eval_js('table.setHeaders({});'.format(data))\n        return func",
    "docstring": "Add a column function which takes an id as argument and\n        returns a value."
  },
  {
    "code": "def makeCys(segID, N, CA, C, O, geo):\n    CA_CB_length=geo.CA_CB_length\n    C_CA_CB_angle=geo.C_CA_CB_angle\n    N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle\n    CB_SG_length= geo.CB_SG_length\n    CA_CB_SG_angle= geo.CA_CB_SG_angle\n    N_CA_CB_SG_diangle= geo.N_CA_CB_SG_diangle\n    carbon_b= calculateCoordinates(N, C, CA, CA_CB_length, C_CA_CB_angle, N_C_CA_CB_diangle)\n    CB= Atom(\"CB\", carbon_b, 0.0 , 1.0, \" \",\" CB\", 0,\"C\")\n    sulfur_g= calculateCoordinates(N, CA, CB, CB_SG_length, CA_CB_SG_angle, N_CA_CB_SG_diangle)\n    SG= Atom(\"SG\", sulfur_g, 0.0, 1.0, \" \", \" SG\", 0, \"S\")\n    res= Residue((' ', segID, ' '), \"CYS\", '    ')\n    res.add(N)\n    res.add(CA)\n    res.add(C)\n    res.add(O)\n    res.add(CB)\n    res.add(SG)\n    return res",
    "docstring": "Creates a Cysteine residue"
  },
  {
    "code": "def get_brizo_url(config):\n        brizo_url = 'http://localhost:8030'\n        if config.has_option('resources', 'brizo.url'):\n            brizo_url = config.get('resources', 'brizo.url') or brizo_url\n        brizo_path = '/api/v1/brizo'\n        return f'{brizo_url}{brizo_path}'",
    "docstring": "Return the Brizo component url.\n\n        :param config: Config\n        :return: Url, str"
  },
  {
    "code": "def destroy(self):\n        if self.client:\n            self.client.setWebView(self.widget, None)\n            del self.client\n        super(AndroidWebView, self).destroy()",
    "docstring": "Destroy the client"
  },
  {
    "code": "def transform_aglistener_output(result):\n    from collections import OrderedDict\n    from msrestazure.tools import parse_resource_id\n    try:\n        resource_group = getattr(result, 'resource_group', None) or parse_resource_id(result.id)['resource_group']\n        output = OrderedDict([('id', result.id),\n                              ('name', result.name),\n                              ('provisioningState', result.provisioning_state),\n                              ('port', result.port),\n                              ('resourceGroup', resource_group)])\n        if result.load_balancer_configurations is not None:\n            output['loadBalancerConfigurations'] = format_load_balancer_configuration_list(result.load_balancer_configurations)\n        return output\n    except AttributeError:\n        return result",
    "docstring": "Transforms the result of Availability Group Listener to eliminate unnecessary parameters."
  },
  {
    "code": "def dist(x1, x2=None, metric='sqeuclidean', to_numpy=True):\n    if x2 is None:\n        x2 = x1\n    if metric == \"sqeuclidean\":\n        return euclidean_distances(x1, x2, squared=True, to_numpy=to_numpy)\n    elif metric == \"euclidean\":\n        return euclidean_distances(x1, x2, squared=False, to_numpy=to_numpy)\n    else:\n        raise NotImplementedError",
    "docstring": "Compute distance between samples in x1 and x2 on gpu\n\n    Parameters\n    ----------\n\n    x1 : np.array (n1,d)\n        matrix with n1 samples of size d\n    x2 : np.array (n2,d), optional\n        matrix with n2 samples of size d (if None then x2=x1)\n    metric : str\n        Metric from 'sqeuclidean', 'euclidean',\n\n\n    Returns\n    -------\n\n    M : np.array (n1,n2)\n        distance matrix computed with given metric"
  },
  {
    "code": "def get_network(self):\n        ref_key = self.ref_key\n        if ref_key == 'NETWORK':\n            return self.network\n        elif ref_key == 'NODE':\n            return self.node.network\n        elif ref_key == 'LINK':\n            return self.link.network\n        elif ref_key == 'GROUP':\n            return self.group.network\n        elif ref_key == 'PROJECT':\n            return None",
    "docstring": "Get the network that this resource attribute is in."
  },
  {
    "code": "def setup_address(self, name, address=default, transact={}):\n        owner = self.setup_owner(name, transact=transact)\n        self._assert_control(owner, name)\n        if is_none_or_zero_address(address):\n            address = None\n        elif address is default:\n            address = owner\n        elif is_binary_address(address):\n            address = to_checksum_address(address)\n        elif not is_checksum_address(address):\n            raise ValueError(\"You must supply the address in checksum format\")\n        if self.address(name) == address:\n            return None\n        if address is None:\n            address = EMPTY_ADDR_HEX\n        transact['from'] = owner\n        resolver = self._set_resolver(name, transact=transact)\n        return resolver.functions.setAddr(raw_name_to_hash(name), address).transact(transact)",
    "docstring": "Set up the name to point to the supplied address.\n        The sender of the transaction must own the name, or\n        its parent name.\n\n        Example: If the caller owns ``parentname.eth`` with no subdomains\n        and calls this method with ``sub.parentname.eth``,\n        then ``sub`` will be created as part of this call.\n\n        :param str name: ENS name to set up\n        :param str address: name will point to this address, in checksum format. If ``None``,\n            erase the record. If not specified, name will point to the owner's address.\n        :param dict transact: the transaction configuration, like in\n            :meth:`~web3.eth.Eth.sendTransaction`\n        :raises InvalidName: if ``name`` has invalid syntax\n        :raises UnauthorizedError: if ``'from'`` in `transact` does not own `name`"
  },
  {
    "code": "def plot_point(self, x, y, visible=True, color='black', size=5):\n        xp = (self.px_x * (x - self.x_min)) / self.x_tick\n        yp = (self.px_y * (self.y_max - y)) / self.y_tick\n        coord = 50 + xp, 50 + yp\n        if visible:\n            size = int(size/2) if int(size/2) > 1 else 1\n            x, y = coord\n            self.canvas.create_oval(\n                x-size, y-size,\n                x+size, y+size,\n                fill=color\n            )\n        return coord",
    "docstring": "Places a single point on the grid\n\n        :param x: the x coordinate\n        :param y: the y coordinate\n        :param visible: True if the individual point should be visible\n        :param color: the color of the point\n        :param size: the point size in pixels\n        :return: The absolute coordinates as a tuple"
  },
  {
    "code": "def load_fileobj(fileobj, gz = None, xmldoc = None, contenthandler = None):\n\tfileobj = MD5File(fileobj)\n\tmd5obj = fileobj.md5obj\n\tif gz or gz is None:\n\t\tfileobj = RewindableInputFile(fileobj)\n\t\tmagic = fileobj.read(2)\n\t\tfileobj.seek(0, os.SEEK_SET)\n\t\tif gz or magic == '\\037\\213':\n\t\t\tfileobj = gzip.GzipFile(mode = \"rb\", fileobj = fileobj)\n\tif xmldoc is None:\n\t\txmldoc = ligolw.Document()\n\tligolw.make_parser(contenthandler(xmldoc)).parse(fileobj)\n\treturn xmldoc, md5obj.hexdigest()",
    "docstring": "Parse the contents of the file object fileobj, and return the\n\tcontents as a LIGO Light Weight document tree.  The file object\n\tdoes not need to be seekable.\n\n\tIf the gz parameter is None (the default) then gzip compressed data\n\twill be automatically detected and decompressed, otherwise\n\tdecompression can be forced on or off by setting gz to True or\n\tFalse respectively.\n\n\tIf the optional xmldoc argument is provided and not None, the\n\tparsed XML tree will be appended to that document, otherwise a new\n\tdocument will be created.  The return value is a tuple, the first\n\telement of the tuple is the XML document and the second is a string\n\tcontaining the MD5 digest in hex digits of the bytestream that was\n\tparsed.\n\n\tExample:\n\n\t>>> from pycbc_glue.ligolw import ligolw\n\t>>> import StringIO\n\t>>> f = StringIO.StringIO('<?xml version=\"1.0\" encoding=\"utf-8\" ?><!DOCTYPE LIGO_LW SYSTEM \"http://ldas-sw.ligo.caltech.edu/doc/ligolwAPI/html/ligolw_dtd.txt\"><LIGO_LW><Table Name=\"demo:table\"><Column Name=\"name\" Type=\"lstring\"/><Column Name=\"value\" Type=\"real8\"/><Stream Name=\"demo:table\" Type=\"Local\" Delimiter=\",\">\"mass\",0.5,\"velocity\",34</Stream></Table></LIGO_LW>')\n\t>>> xmldoc, digest = load_fileobj(f, contenthandler = ligolw.LIGOLWContentHandler)\n\t>>> digest\n\t'6bdcc4726b892aad913531684024ed8e'\n\n\tThe contenthandler argument specifies the SAX content handler to\n\tuse when parsing the document.  The contenthandler is a required\n\targument.  See the pycbc_glue.ligolw package documentation for typical\n\tparsing scenario involving a custom content handler.  See\n\tpycbc_glue.ligolw.ligolw.PartialLIGOLWContentHandler and\n\tpycbc_glue.ligolw.ligolw.FilteringLIGOLWContentHandler for examples of\n\tcustom content handlers used to load subsets of documents into\n\tmemory."
  },
  {
    "code": "def _get_client_fqdn(self, client_info_contents):\n    yamldict = yaml.safe_load(client_info_contents)\n    fqdn = yamldict['system_info']['fqdn']\n    client_id = yamldict['client_id'].split('/')[1]\n    return client_id, fqdn",
    "docstring": "Extracts a GRR client's FQDN from its client_info.yaml file.\n\n    Args:\n      client_info_contents: The contents of the client_info.yaml file.\n\n    Returns:\n      A (str, str) tuple representing client ID and client FQDN."
  },
  {
    "code": "def set(self, instance, value, **kw):\n        ref = []\n        if api.is_uid(value):\n            ref.append(value)\n        if u.is_dict(value):\n            ref = ref.append(value.get(\"uid\"))\n        if api.is_at_content(value):\n            ref.append(value)\n        if u.is_list(value):\n            for item in value:\n                if api.is_uid(item):\n                    ref.append(item)\n                elif u.is_dict(item):\n                    uid = item.get('uid', None)\n                    if uid:\n                        ref.append(uid)\n        if not self.multi_valued:\n            if len(ref) > 1:\n                raise ValueError(\"Multiple values given for single valued \"\n                                 \"field {}\".format(repr(self.field)))\n            else:\n                ref = ref[0]\n        return self._set(instance, ref, **kw)",
    "docstring": "Set the value of the uid reference field"
  },
  {
    "code": "def scale(cls, *scaling):\n        if len(scaling) == 1:\n            sx = sy = float(scaling[0])\n        else:\n            sx, sy = scaling\n        return tuple.__new__(cls, (sx, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 1.0))",
    "docstring": "Create a scaling transform from a scalar or vector.\n\n        :param scaling: The scaling factor. A scalar value will\n            scale in both dimensions equally. A vector scaling\n            value scales the dimensions independently.\n        :type scaling: float or sequence\n        :rtype: Affine"
  },
  {
    "code": "def certs(self):\n        certstack = libcrypto.CMS_get1_certs(self.ptr)\n        if certstack is None:\n            raise CMSError(\"getting certs\")\n        return StackOfX509(ptr=certstack, disposable=True)",
    "docstring": "List of the certificates contained in the structure"
  },
  {
    "code": "def find_multiplex_by_name(self, multiplex_name: str) -> Multiplex:\n        for multiplex in self.multiplexes:\n            if multiplex.name == multiplex_name:\n                return multiplex\n        raise AttributeError(f'multiplex \"{multiplex_name}\" does not exist')",
    "docstring": "Find and return a multiplex in the influence graph with the given name.\n        Raise an AttributeError if there is no multiplex in the graph with the given name."
  },
  {
    "code": "def check_data(self):\n        assert os.path.exists(self.data_fp)\n        if gis:\n            with fiona.drivers():\n                with fiona.open(self.faces_fp) as src:\n                    assert src.meta\n        gpkg_hash = json.load(open(self.data_fp))['metadata']['sha256']\n        assert gpkg_hash == sha256(self.faces_fp)",
    "docstring": "Check that definitions file is present, and that faces file is readable."
  },
  {
    "code": "def read_raw_parser_conf(data: str) -> dict:\n    config = configparser.ConfigParser(allow_no_value=True)\n    config.read_string(data)\n    try:\n        _data: dict = dict(config[\"commitizen\"])\n        if \"files\" in _data:\n            files = _data[\"files\"]\n            _f = json.loads(files)\n            _data.update({\"files\": _f})\n        return _data\n    except KeyError:\n        return {}",
    "docstring": "We expect to have a section like this\n\n    ```\n    [commitizen]\n    name = cz_jira\n    files = [\n        \"commitizen/__version__.py\",\n        \"pyproject.toml\"\n        ]  # this tab at the end is important\n    ```"
  },
  {
    "code": "def to_path_globs(self, relpath, conjunction):\n    return PathGlobs(\n      include=tuple(os.path.join(relpath, glob) for glob in self._file_globs),\n      exclude=tuple(os.path.join(relpath, exclude) for exclude in self._excluded_file_globs),\n      conjunction=conjunction)",
    "docstring": "Return a PathGlobs representing the included and excluded Files for these patterns."
  },
  {
    "code": "def __create_image(self, inpt, hashfun):\n        if hashfun not in generator.HASHES.keys():\n            print (\"Unknown or unsupported hash function. Using default: %s\"\n                   % self.DEFAULT_HASHFUN)\n            algo = self.DEFAULT_HASHFUN\n        else:\n            algo = hashfun\n        return generator.generate(inpt, algo)",
    "docstring": "Creates the avatar based on the input and\n        the chosen hash function."
  },
  {
    "code": "def abort(self, count=2, timeout=60):\n        for counter in xrange(0, count):\n            self.putc(CAN, timeout)",
    "docstring": "Send an abort sequence using CAN bytes."
  },
  {
    "code": "def read_requirements():\n    reqs_path = os.path.join('.', 'requirements.txt')\n    install_reqs = parse_requirements(reqs_path, session=PipSession())\n    reqs = [str(ir.req) for ir in install_reqs]\n    return reqs",
    "docstring": "parses requirements from requirements.txt"
  },
  {
    "code": "def main():\n    if not sys.platform.startswith(\"win\"):\n        if \"--daemon\" in sys.argv:\n            daemonize()\n    from gns3server.run import run\n    run()",
    "docstring": "Entry point for GNS3 server"
  },
  {
    "code": "async def prover_get_credentials(wallet_handle: int,\n                                 filter_json: str) -> str:\n    logger = logging.getLogger(__name__)\n    logger.debug(\"prover_get_credentials: >>> wallet_handle: %r, filter_json: %r\",\n                 wallet_handle,\n                 filter_json)\n    if not hasattr(prover_get_credentials, \"cb\"):\n        logger.debug(\"prover_get_credentials: Creating callback\")\n        prover_get_credentials.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_char_p))\n    c_wallet_handle = c_int32(wallet_handle)\n    c_filter_json = c_char_p(filter_json.encode('utf-8'))\n    credentials_json = await do_call('indy_prover_get_credentials',\n                                     c_wallet_handle,\n                                     c_filter_json,\n                                     prover_get_credentials.cb)\n    res = credentials_json.decode()\n    logger.debug(\"prover_get_credentials: <<< res: %r\", res)\n    return res",
    "docstring": "Gets human readable credentials according to the filter.\n    If filter is NULL, then all credentials are returned.\n    Credentials can be filtered by tags created during saving of credential.\n\n    NOTE: This method is deprecated because immediately returns all fetched credentials.\n    Use <prover_search_credentials> to fetch records by small batches.\n\n    :param wallet_handle: wallet handler (created by open_wallet).\n    :param filter_json: filter for credentials\n        {\n            \"schema_id\": string, (Optional)\n            \"schema_issuer_did\": string, (Optional)\n            \"schema_name\": string, (Optional)\n            \"schema_version\": string, (Optional)\n            \"issuer_did\": string, (Optional)\n            \"cred_def_id\": string, (Optional)\n        }\n    :return:  credentials json\n     [{\n         \"referent\": string, // cred_id in the wallet\n         \"attrs\": {\"key1\":\"raw_value1\", \"key2\":\"raw_value2\"},\n         \"schema_id\": string,\n         \"cred_def_id\": string,\n         \"rev_reg_id\": Optional<string>,\n         \"cred_rev_id\": Optional<string>\n     }]"
  },
  {
    "code": "def looks_like_xml(text):\n    if xml_decl_re.match(text):\n        return True\n    key = hash(text)\n    try:\n        return _looks_like_xml_cache[key]\n    except KeyError:\n        m = doctype_lookup_re.match(text)\n        if m is not None:\n            return True\n        rv = tag_re.search(text[:1000]) is not None\n        _looks_like_xml_cache[key] = rv\n        return rv",
    "docstring": "Check if a doctype exists or if we have some tags."
  },
  {
    "code": "def _update_message_request(self, message):\n        for each in self.row_keys:\n            message.rows.row_keys.append(_to_bytes(each))\n        for each in self.row_ranges:\n            r_kwrags = each.get_range_kwargs()\n            message.rows.row_ranges.add(**r_kwrags)",
    "docstring": "Add row keys and row range to given request message\n\n        :type message: class:`data_messages_v2_pb2.ReadRowsRequest`\n        :param message: The ``ReadRowsRequest`` protobuf"
  },
  {
    "code": "def to_internal(self, attribute_profile, external_dict):\n        internal_dict = {}\n        for internal_attribute_name, mapping in self.from_internal_attributes.items():\n            if attribute_profile not in mapping:\n                logger.debug(\"no attribute mapping found for internal attribute '%s' the attribute profile '%s'\" % (\n                    internal_attribute_name, attribute_profile))\n                continue\n            external_attribute_name = mapping[attribute_profile]\n            attribute_values = self._collate_attribute_values_by_priority_order(external_attribute_name,\n                                                                                external_dict)\n            if attribute_values:\n                logger.debug(\"backend attribute '%s' mapped to %s\" % (external_attribute_name,\n                                                            internal_attribute_name))\n                internal_dict[internal_attribute_name] = attribute_values\n            else:\n                logger.debug(\"skipped backend attribute '%s': no value found\", external_attribute_name)\n        internal_dict = self._handle_template_attributes(attribute_profile, internal_dict)\n        return internal_dict",
    "docstring": "Converts the external data from \"type\" to internal\n\n        :type attribute_profile: str\n        :type external_dict: dict[str, str]\n        :rtype: dict[str, str]\n\n        :param attribute_profile: From which external type to convert (ex: oidc, saml, ...)\n        :param external_dict: Attributes in the external format\n        :return: Attributes in the internal format"
  },
  {
    "code": "def disconnect(self):\n        self.connState = Client.DISCONNECTED\n        if self.conn is not None:\n            self._logger.info('Disconnecting')\n            self.conn.disconnect()\n            self.wrapper.connectionClosed()\n            self.reset()",
    "docstring": "Disconnect from IB connection."
  },
  {
    "code": "def get_client_settings_env(**_):\n    return {\n        'proxy': os.environ.get('https_proxy'),\n        'username': os.environ.get('SL_USERNAME'),\n        'api_key': os.environ.get('SL_API_KEY'),\n    }",
    "docstring": "Retrieve client settings from environment settings.\n\n        :param \\\\*\\\\*kwargs: Arguments that are passed into the client instance"
  },
  {
    "code": "def to_regular_array(self, A):\n        return A.view((int, len(A.dtype.names))).reshape(A.shape + (-1,))",
    "docstring": "Converts from an array of type `self.dtype` to an array\n        of type `int` with an additional index labeling the\n        tuple indeces.\n\n        :param np.ndarray A: An `np.array` of type `self.dtype`.\n\n        :rtype: `np.ndarray`"
  },
  {
    "code": "def save_grade_system(self, grade_system_form, *args, **kwargs):\n        if grade_system_form.is_for_update():\n            return self.update_grade_system(grade_system_form, *args, **kwargs)\n        else:\n            return self.create_grade_system(grade_system_form, *args, **kwargs)",
    "docstring": "Pass through to provider GradeSystemAdminSession.update_grade_system"
  },
  {
    "code": "def encipher_shift(plaintext, plain_vocab, shift):\n  ciphertext = []\n  cipher = ShiftEncryptionLayer(plain_vocab, shift)\n  for _, sentence in enumerate(plaintext):\n    cipher_sentence = []\n    for _, character in enumerate(sentence):\n      encrypted_char = cipher.encrypt_character(character)\n      cipher_sentence.append(encrypted_char)\n    ciphertext.append(cipher_sentence)\n  return ciphertext",
    "docstring": "Encrypt plain text with a single shift layer.\n\n  Args:\n    plaintext (list of list of Strings): a list of plain text to encrypt.\n    plain_vocab (list of Integer): unique vocabularies being used.\n    shift (Integer): number of shift, shift to the right if shift is positive.\n  Returns:\n    ciphertext (list of Strings): encrypted plain text."
  },
  {
    "code": "def escapePlaceholders(self,inputString):\n        escaped = inputString.replace(MapConstants.placeholder,'\\\\'+MapConstants.placeholder)\n        escaped = escaped.replace(MapConstants.placeholderFileName,'\\\\'+MapConstants.placeholderFileName)\n        escaped = escaped.replace(MapConstants.placeholderPath,'\\\\'+MapConstants.placeholderPath)\n        escaped = escaped.replace(MapConstants.placeholderExtension,'\\\\'+MapConstants.placeholderExtension)\n        escaped = escaped.replace(MapConstants.placeholderCounter,'\\\\'+MapConstants.placeholderCounter)\n        return escaped",
    "docstring": "This is an internal method that escapes all the placeholders\n        defined in MapConstants.py."
  },
  {
    "code": "def serve_forever(self, poll_interval=0.5):\n        self.__is_shut_down.clear()\n        try:\n            while not self.__shutdown_request:\n                r, w, e = _eintr_retry(select.select, [self], [], [], poll_interval)\n                if self in r:\n                    self._handle_request_noblock()\n        finally:\n            self.__shutdown_request = False\n            self.__is_shut_down.set()",
    "docstring": "Handle one request at a time until shutdown.\n        Polls for shutdown every poll_interval seconds. Ignores\n        self.timeout. If you need to do periodic tasks, do them in\n        another thread."
  },
  {
    "code": "def txinfo(self, txid: str) -> dict:\n        return cast(dict, self.ext_fetch('txinfo/' + txid))",
    "docstring": "Returns information about given transaction."
  },
  {
    "code": "def adjust_for_triggers(self):\n        triggers = self.template['spec'].get('triggers', [])\n        remove_plugins = [\n            (\"prebuild_plugins\", \"check_and_set_rebuild\"),\n            (\"prebuild_plugins\", \"stop_autorebuild_if_disabled\"),\n        ]\n        should_remove = False\n        if triggers and (self.is_custom_base_image() or self.is_from_scratch_image()):\n            if self.is_custom_base_image():\n                msg = \"removing %s from request because custom base image\"\n            elif self.is_from_scratch_image():\n                msg = 'removing %s from request because FROM scratch image'\n            del self.template['spec']['triggers']\n            should_remove = True\n        elif not triggers:\n            msg = \"removing %s from request because there are no triggers\"\n            should_remove = True\n        if should_remove:\n            for when, which in remove_plugins:\n                logger.info(msg, which)\n                self.dj.remove_plugin(when, which)",
    "docstring": "Remove trigger-related plugins when needed\n\n        If there are no triggers defined, it's assumed the\n        feature is disabled and all trigger-related plugins\n        are removed.\n\n        If there are triggers defined, and this is a custom\n        base image, some trigger-related plugins do not apply.\n\n        Additionally, this method ensures that custom base\n        images never have triggers since triggering a base\n        image rebuild is not a valid scenario."
  },
  {
    "code": "def execute_cmd(self, userid, cmdStr):\n        LOG.debug(\"executing cmd: %s\", cmdStr)\n        return self._smtclient.execute_cmd(userid, cmdStr)",
    "docstring": "Execute commands on the guest vm."
  },
  {
    "code": "def config_mode(self, config_command=\"configure\", pattern=r\"[edit]\"):\n        return super(VyOSSSH, self).config_mode(\n            config_command=config_command, pattern=pattern\n        )",
    "docstring": "Enter configuration mode."
  },
  {
    "code": "def _alpha2rho0(self, theta_Rs, Rs):\n        rho0 = theta_Rs / (4. * Rs ** 2 * (1. + np.log(1. / 2.)))\n        return rho0",
    "docstring": "convert angle at Rs into rho0"
  },
  {
    "code": "def remove_line_breaks(text):\n    return unicode(text, 'utf-8').replace('\\f', '').replace('\\n', '') \\\n        .replace('\\r', '').replace(u'\\xe2\\x80\\xa8', '') \\\n        .replace(u'\\xe2\\x80\\xa9', '').replace(u'\\xc2\\x85', '') \\\n        .encode('utf-8')",
    "docstring": "Remove line breaks from input.\n\n    Including unicode 'line separator', 'paragraph separator',\n    and 'next line' characters."
  },
  {
    "code": "def stop(self):\n        self.state = False\n        with display_manager(self.display) as d:\n            d.record_disable_context(self.ctx)\n            d.ungrab_keyboard(X.CurrentTime)\n        with display_manager(self.display2):\n            d.record_disable_context(self.ctx)\n            d.ungrab_keyboard(X.CurrentTime)",
    "docstring": "Stop listening for keyboard input events."
  },
  {
    "code": "def add_section(self, section):\n        if not issubclass(section.__class__, _AbstractSection):\n            raise TypeError(\"argument should be a subclass of Section\")\n        self.sections[section.get_key_name()] = section\n        return section",
    "docstring": "Add a new Section object to the config. Should be a subclass of\n        _AbstractSection."
  },
  {
    "code": "def real(self):\n        def re(val):\n            if hasattr(val, 'real'):\n                return val.real\n            elif hasattr(val, 'as_real_imag'):\n                return val.as_real_imag()[0]\n            elif hasattr(val, 'conjugate'):\n                return (val.conjugate() + val) / 2\n            else:\n                raise NoConjugateMatrix(\n                    \"Matrix entry %s contains has no defined \"\n                    \"conjugate\" % str(val))\n        return self.element_wise(re)",
    "docstring": "Element-wise real part\n\n        Raises:\n            NoConjugateMatrix: if entries have no `conjugate` method and no\n                other way to determine the real part\n\n        Note:\n            A mathematically equivalent way to obtain a real matrix from a\n            complex matrix ``M`` is::\n\n                (M.conjugate() + M) / 2\n\n            However, the result may not be identical to ``M.real``, as the\n            latter tries to convert elements of the matrix to real values\n            directly, if possible, and only uses the conjugate as a fall-back"
  },
  {
    "code": "def assignParameters(self,solution_next,DiscFac,LivPrb,CRRA,Rfree,PermGroFac):\n        self.solution_next  = solution_next\n        self.DiscFac        = DiscFac\n        self.LivPrb         = LivPrb\n        self.CRRA           = CRRA\n        self.Rfree          = Rfree\n        self.PermGroFac     = PermGroFac",
    "docstring": "Saves necessary parameters as attributes of self for use by other methods.\n\n        Parameters\n        ----------\n        solution_next : ConsumerSolution\n            The solution to next period's one period problem.\n        DiscFac : float\n            Intertemporal discount factor for future utility.\n        LivPrb : float\n            Survival probability; likelihood of being alive at the beginning of\n            the succeeding period.\n        CRRA : float\n            Coefficient of relative risk aversion.\n        Rfree : float\n            Risk free interest factor on end-of-period assets.\n        PermGroFac : float\n            Expected permanent income growth factor at the end of this period.\n\n        Returns\n        -------\n        none"
  },
  {
    "code": "def re_run_file(self):\r\n        if self.get_option('save_all_before_run'):\r\n            self.save_all()\r\n        if self.__last_ec_exec is None:\r\n            return\r\n        (fname, wdir, args, interact, debug,\r\n         python, python_args, current, systerm,\r\n         post_mortem, clear_namespace) = self.__last_ec_exec\r\n        if not systerm:\r\n            self.run_in_current_ipyclient.emit(fname, wdir, args,\r\n                                               debug, post_mortem,\r\n                                               current, clear_namespace)\r\n        else:\r\n            self.main.open_external_console(fname, wdir, args, interact,\r\n                                            debug, python, python_args,\r\n                                            systerm, post_mortem)",
    "docstring": "Re-run last script"
  },
  {
    "code": "def merge_entity(self, table_name, entity, if_match='*', timeout=None):\n        _validate_not_none('table_name', table_name)\n        request = _merge_entity(entity, if_match, self.require_encryption,\n                                self.key_encryption_key)\n        request.host_locations = self._get_host_locations()\n        request.query['timeout'] = _int_to_str(timeout)\n        request.path = _get_entity_path(table_name, entity['PartitionKey'], entity['RowKey'])\n        return self._perform_request(request, _extract_etag)",
    "docstring": "Updates an existing entity by merging the entity's properties. Throws \n        if the entity does not exist. \n        \n        This operation does not replace the existing entity as the update_entity\n        operation does. A property cannot be removed with merge_entity.\n        \n        Any properties with null values are ignored. All other properties will be \n        updated or added.\n\n        :param str table_name:\n            The name of the table containing the entity to merge.\n        :param entity:\n            The entity to merge. Could be a dict or an entity object. \n            Must contain a PartitionKey and a RowKey.\n        :type entity: dict or :class:`~azure.storage.table.models.Entity`\n        :param str if_match:\n            The client may specify the ETag for the entity on the \n            request in order to compare to the ETag maintained by the service \n            for the purpose of optimistic concurrency. The merge operation \n            will be performed only if the ETag sent by the client matches the \n            value maintained by the server, indicating that the entity has \n            not been modified since it was retrieved by the client. To force \n            an unconditional merge, set If-Match to the wildcard character (*).\n        :param int timeout:\n            The server timeout, expressed in seconds.\n        :return: The etag of the entity.\n        :rtype: str"
  },
  {
    "code": "def _generate_rpc_method(self, method):\n        def _(**kwargs):\n            msg_id = self.get_unique_msg_id()\n            params = encode_data(kwargs)\n            payload = {\n                'method': method,\n                'params': params,\n                'jsonrpc': '2.0',\n                'id': msg_id\n            }\n            response = requests.post(self.url, data=json.dumps(payload), headers=self.headers).json()\n            if ('error' in response):\n                if response['error']['code'] == JSONRPC_NO_RESULT:\n                    return None\n                raise Exception('Got error from RPC server when called \"%s\" error: %s' % (method, response['error']))\n            if 'result' in response:\n                result = decode_data(response['result'])\n                return result\n        return _",
    "docstring": "Generate a function that performs rpc call\n\n        :param method: method name\n        :return: rpc function"
  },
  {
    "code": "def _archive_single_dir(archive):\n    common_root = None\n    for info in _list_archive_members(archive):\n        fn = _info_name(info)\n        if fn in set(['.', '/']):\n            continue\n        sep = None\n        if '/' in fn:\n            sep = '/'\n        elif '\\\\' in fn:\n            sep = '\\\\'\n        if sep is None:\n            root_dir = fn\n        else:\n            root_dir, _ = fn.split(sep, 1)\n        if common_root is None:\n            common_root = root_dir\n        else:\n            if common_root != root_dir:\n                return None\n    return common_root",
    "docstring": "Check if all members of the archive are in a single top-level directory\n\n    :param archive:\n        An archive from _open_archive()\n\n    :return:\n        None if not a single top level directory in archive, otherwise a\n        unicode string of the top level directory name"
  },
  {
    "code": "def add_handler(cls, level, fmt, colorful, **kwargs):\n    global g_logger\n    if isinstance(level, str):\n        level = getattr(logging, level.upper(), logging.DEBUG)\n    handler = cls(**kwargs)\n    handler.setLevel(level)\n    if colorful:\n        formatter = ColoredFormatter(fmt, datefmt='%Y-%m-%d %H:%M:%S')\n    else:\n        formatter = logging.Formatter(fmt, datefmt='%Y-%m-%d %H:%M:%S')\n    handler.setFormatter(formatter)\n    g_logger.addHandler(handler)\n    return handler",
    "docstring": "Add a configured handler to the global logger."
  },
  {
    "code": "def _get_load_ramping_construct(self):\n        bus_no = integer.setResultsName(\"bus_no\")\n        s_rating = real.setResultsName(\"s_rating\")\n        up_rate = real.setResultsName(\"up_rate\")\n        down_rate = real.setResultsName(\"down_rate\")\n        min_up_time = real.setResultsName(\"min_up_time\")\n        min_down_time = real.setResultsName(\"min_down_time\")\n        n_period_up = integer.setResultsName(\"n_period_up\")\n        n_period_down = integer.setResultsName(\"n_period_down\")\n        status = boolean.setResultsName(\"status\")\n        l_ramp_data = bus_no + s_rating + up_rate + down_rate + \\\n            min_up_time + min_down_time + n_period_up + \\\n            n_period_down + status + scolon\n        l_ramp_array = Literal(\"Rmpl.con\") + \"=\" + \"[\" + \\\n            ZeroOrMore(l_ramp_data + Optional(\"]\" + scolon))\n        return l_ramp_array",
    "docstring": "Returns a construct for an array of load ramping data."
  },
  {
    "code": "def _find_files(root, includes, excludes, follow_symlinks):\n    root = os.path.abspath(root)\n    file_set = formic.FileSet(\n        directory=root, include=includes,\n        exclude=excludes, symlinks=follow_symlinks,\n    )\n    for filename in file_set.qualified_files(absolute=False):\n        yield filename",
    "docstring": "List files inside a directory based on include and exclude rules.\n\n    This is a more advanced version of `glob.glob`, that accepts multiple\n    complex patterns.\n\n    Args:\n        root (str): base directory to list files from.\n        includes (list[str]): inclusion patterns. Only files matching those\n            patterns will be included in the result.\n        excludes (list[str]): exclusion patterns. Files matching those\n            patterns will be excluded from the result. Exclusions take\n            precedence over inclusions.\n        follow_symlinks (bool): If true, symlinks will be included in the\n            resulting zip file\n\n    Yields:\n        str: a file name relative to the root.\n\n    Note:\n        Documentation for the patterns can be found at\n        http://www.aviser.asia/formic/doc/index.html"
  },
  {
    "code": "def _apply_xheaders(self, headers: httputil.HTTPHeaders) -> None:\n        ip = headers.get(\"X-Forwarded-For\", self.remote_ip)\n        for ip in (cand.strip() for cand in reversed(ip.split(\",\"))):\n            if ip not in self.trusted_downstream:\n                break\n        ip = headers.get(\"X-Real-Ip\", ip)\n        if netutil.is_valid_ip(ip):\n            self.remote_ip = ip\n        proto_header = headers.get(\n            \"X-Scheme\", headers.get(\"X-Forwarded-Proto\", self.protocol)\n        )\n        if proto_header:\n            proto_header = proto_header.split(\",\")[-1].strip()\n        if proto_header in (\"http\", \"https\"):\n            self.protocol = proto_header",
    "docstring": "Rewrite the ``remote_ip`` and ``protocol`` fields."
  },
  {
    "code": "def get_alt_description(self):\n        if 'altDescription' in self.attributes and bool(self.attributes['altDescription'].strip()):\n            return self.attributes['altDescription']\n        else:\n            return None",
    "docstring": "Returns the alternate description of a parameter.\n        Only pipeline prompt-when-run parameters\n        can have alternate names and alternate descriptions"
  },
  {
    "code": "def rename_to_tmp_name(self):\n        self.client.rename(\n            self.id,\n            '%s_%s' % (self.short_id, self.name)\n        )",
    "docstring": "Rename the container to a hopefully unique temporary container name\n        by prepending the short id."
  },
  {
    "code": "def wait_for_element_by_selector(self, selector, seconds):\n    def assert_element_present():\n        if not find_elements_by_jquery(world.browser, selector):\n            raise AssertionError(\"Expected a matching element.\")\n    wait_for(assert_element_present)(timeout=int(seconds))",
    "docstring": "Assert an element exists matching the given selector within the given time\n    period."
  },
  {
    "code": "def parse_services(rule):\n    parser = argparse.ArgumentParser()\n    rules = shlex.split(rule)\n    rules.pop(0)\n    parser.add_argument('--disabled', dest='disabled', action='store')\n    parser.add_argument('--enabled', dest='enabled', action='store')\n    args = clean_args(vars(parser.parse_args(rules)))\n    parser = None\n    return args",
    "docstring": "Parse the services line"
  },
  {
    "code": "def replace_variables(sentence: List[str],\n                      sentence_variables: Dict[str, str]) -> Tuple[List[str], List[str]]:\n    tokens = []\n    tags = []\n    for token in sentence:\n        if token not in sentence_variables:\n            tokens.append(token)\n            tags.append(\"O\")\n        else:\n            for word in sentence_variables[token].split():\n                tokens.append(word)\n                tags.append(token)\n    return tokens, tags",
    "docstring": "Replaces abstract variables in text with their concrete counterparts."
  },
  {
    "code": "def get_local_environnement(self):\n        local_env = os.environ.copy()\n        for local_var in self.env:\n            local_env[local_var] = self.env[local_var]\n        return local_env",
    "docstring": "Mix the environment and the environment variables into a new local\n        environment dictionary\n\n        Note: We cannot just update the global os.environ because this\n        would effect all other checks.\n\n        :return: local environment variables\n        :rtype: dict"
  },
  {
    "code": "def add_behave_arguments(parser):\n    conflicts = [\n        '--no-color',\n        '--version',\n        '-c',\n        '-k',\n        '-v',\n        '-S',\n        '--simple',\n    ]\n    parser.add_argument(\n        'paths',\n        action='store',\n        nargs='*',\n        help=\"Feature directory, file or file location (FILE:LINE).\"\n    )\n    for fixed, keywords in behave_options:\n        keywords = keywords.copy()\n        if not fixed:\n            continue\n        option_strings = []\n        for option in fixed:\n            if option in conflicts:\n                prefix = '--' if option.startswith('--') else '-'\n                option = option.replace(prefix, '--behave-', 1)\n            option_strings.append(option)\n        if 'config_help' in keywords:\n            keywords['help'] = keywords['config_help']\n            del keywords['config_help']\n        parser.add_argument(*option_strings, **keywords)",
    "docstring": "Additional command line arguments extracted directly from behave"
  },
  {
    "code": "def sget_steptime(self, cycle, step, dataset_number=None):\n        dataset_number = self._validate_dataset_number(dataset_number)\n        if dataset_number is None:\n            self._report_empty_dataset()\n            return\n        cycle_index_header = self.headers_normal.cycle_index_txt\n        step_time_header = self.headers_normal.step_time_txt\n        step_index_header = self.headers_normal.step_index_txt\n        test = self.datasets[dataset_number].dfdata\n        if isinstance(step, (list, tuple)):\n            warnings.warn(f\"The varialbe step is a list.\"\n                          f\"Should be an integer.\"\n                          f\"{step}\")\n            step = step[0]\n        c = test.loc[\n            (test[cycle_index_header] == cycle) &\n            (test[step_index_header] == step), :\n        ]\n        if not self.is_empty(c):\n            t = c[step_time_header]\n            return t\n        else:\n            return None",
    "docstring": "Returns step time for cycle, step.\n\n        Convinience function; same as issuing\n           dfdata[(dfdata[cycle_index_header] == cycle) &\n                 (dfdata[step_index_header] == step)][step_time_header]\n\n        Args:\n            cycle: cycle number\n            step: step number\n            dataset_number: the dataset number (automatic selection if None)\n\n        Returns:\n            pandas.Series or None if empty"
  },
  {
    "code": "def _get_jwt_for_audience(self, audience):\n        token, expiry = self._cache.get(audience, (None, None))\n        if token is None or expiry < _helpers.utcnow():\n            token, expiry = self._make_jwt_for_audience(audience)\n            self._cache[audience] = token, expiry\n        return token",
    "docstring": "Get a JWT For a given audience.\n\n        If there is already an existing, non-expired token in the cache for\n        the audience, that token is used. Otherwise, a new token will be\n        created.\n\n        Args:\n            audience (str): The intended audience.\n\n        Returns:\n            bytes: The encoded JWT."
  },
  {
    "code": "def subvolume_find_new(name, last_gen):\n    cmd = ['btrfs', 'subvolume', 'find-new', name, last_gen]\n    res = __salt__['cmd.run_all'](cmd)\n    salt.utils.fsutils._verify_run(res)\n    lines = res['stdout'].splitlines()\n    files = [l.split()[-1] for l in lines if l.startswith('inode')]\n    transid = lines[-1].split()[-1]\n    return {\n        'files': files,\n        'transid': transid,\n    }",
    "docstring": "List the recently modified files in a subvolume\n\n    name\n        Name of the subvolume\n\n    last_gen\n        Last transid marker from where to compare\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' btrfs.subvolume_find_new /var/volumes/tmp 1024"
  },
  {
    "code": "def _apply_over_vars_with_dim(func, self, dim=None, **kwargs):\n    ds = type(self)(coords=self.coords, attrs=self.attrs)\n    for name, var in self.data_vars.items():\n        if dim in var.dims:\n            ds[name] = func(var, dim=dim, **kwargs)\n        else:\n            ds[name] = var\n    return ds",
    "docstring": "wrapper for datasets"
  },
  {
    "code": "def substring_search(query, list_of_strings, limit_results=DEFAULT_LIMIT):\n    matching = []\n    query_words = query.split(' ')\n    query_words.sort(key=len, reverse=True)\n    counter = 0\n    for s in list_of_strings:\n        target_words = s.split(' ')\n        if(anyword_substring_search(target_words, query_words)):\n            matching.append(s)\n            counter += 1\n            if(counter == limit_results):\n                break\n    return matching",
    "docstring": "main function to call for searching"
  },
  {
    "code": "def use_comparative_sequence_rule_enabler_view(self):\n        self._object_views['sequence_rule_enabler'] = COMPARATIVE\n        for session in self._get_provider_sessions():\n            try:\n                session.use_comparative_sequence_rule_enabler_view()\n            except AttributeError:\n                pass",
    "docstring": "Pass through to provider SequenceRuleEnablerLookupSession.use_comparative_sequence_rule_enabler_view"
  },
  {
    "code": "def _get_event_cls(view_obj, events_map):\n    request = view_obj.request\n    view_method = getattr(view_obj, request.action)\n    event_action = (\n        getattr(view_method, '_event_action', None) or\n        request.action)\n    return events_map[event_action]",
    "docstring": "Helper function to get event class.\n\n    :param view_obj: Instance of View that processes the request.\n    :param events_map: Map of events from which event class should be\n        picked.\n    :returns: Found event class."
  },
  {
    "code": "def is_cleanly_mergable(*dicts: Dict[Any, Any]) -> bool:\n    if len(dicts) <= 1:\n        return True\n    elif len(dicts) == 2:\n        if not all(isinstance(d, Mapping) for d in dicts):\n            return False\n        else:\n            shared_keys = set(dicts[0].keys()) & set(dicts[1].keys())\n            return all(is_cleanly_mergable(dicts[0][key], dicts[1][key]) for key in shared_keys)\n    else:\n        dict_combinations = itertools.combinations(dicts, 2)\n        return all(is_cleanly_mergable(*combination) for combination in dict_combinations)",
    "docstring": "Check that nothing will be overwritten when dictionaries are merged using `deep_merge`.\n\n    Examples:\n\n        >>> is_cleanly_mergable({\"a\": 1}, {\"b\": 2}, {\"c\": 3})\n        True\n        >>> is_cleanly_mergable({\"a\": 1}, {\"b\": 2}, {\"a\": 0, c\": 3})\n        False\n        >>> is_cleanly_mergable({\"a\": 1, \"b\": {\"ba\": 2}}, {\"c\": 3, {\"b\": {\"bb\": 4}})\n        True\n        >>> is_cleanly_mergable({\"a\": 1, \"b\": {\"ba\": 2}}, {\"b\": {\"ba\": 4}})\n        False"
  },
  {
    "code": "def _dedent(text):\n        lines = text.split('\\n')\n        if len(lines) == 1:\n            indent = 0\n        elif lines[0].strip():\n            raise ValueError('when multiple lines, first line must be blank')\n        elif lines[-1].strip():\n            raise ValueError('last line must only contain indent whitespace')\n        else:\n            indent = len(lines[-1])\n            if any(line[:indent].strip() for line in lines):\n                raise ValueError(\n                    'indents must equal or exceed indent in last line')\n            lines = [line[indent:] for line in lines][1:-1]\n        return indent, '\\n'.join(lines)",
    "docstring": "Remove common indentation from each line in a text block.\n\n        When text block is a single line, return text block. Otherwise\n        determine common indentation from last line, strip common\n        indentation from each line, and return text block consisting of\n        inner lines (don't include first and last lines since they either\n        empty or contain whitespace and are present in baselined\n        string to make them pretty and delineate the common indentation).\n\n        :param str text: text block\n        :returns: text block with common indentation removed\n        :rtype: str\n        :raises ValueError: when text block violates whitespace rules"
  },
  {
    "code": "def revnet(inputs, hparams, reuse=None):\n  training = hparams.mode == tf.estimator.ModeKeys.TRAIN\n  with tf.variable_scope('RevNet', reuse=reuse):\n    x1, x2 = init(inputs,\n                  num_channels=hparams.num_channels_init_block,\n                  dim=hparams.dim,\n                  kernel_size=hparams.init_kernel_size,\n                  maxpool=hparams.init_maxpool,\n                  stride=hparams.init_stride,\n                  training=training)\n    for block_num in range(len(hparams.num_layers_per_block)):\n      block = {'depth': hparams.num_channels[block_num],\n               'num_layers': hparams.num_layers_per_block[block_num],\n               'first_batch_norm': hparams.first_batch_norm[block_num],\n               'stride': hparams.strides[block_num],\n               'bottleneck': hparams.bottleneck}\n      x1, x2 = unit(x1, x2, block_num, dim=hparams.dim, training=training,\n                    **block)\n    pre_logits = final_block(x1, x2, dim=hparams.dim, training=training)\n    return pre_logits",
    "docstring": "Uses Tensor2Tensor memory optimized RevNet block to build a RevNet.\n\n  Args:\n    inputs: [NxHxWx3] tensor of input images to the model.\n    hparams: HParams object that contains the following parameters,\n      in addition to the parameters contained in the basic_params1() object in\n      the common_hparams module:\n        num_channels_first - A Python list where each element represents the\n          depth of the first and third convolutional layers in the bottleneck\n          residual unit for a given block.\n        num_channels_second - A Python list where each element represents the\n          depth of the second convolutional layer in the bottleneck residual\n          unit for a given block.\n        num_layers_per_block - A Python list containing the number of RevNet\n          layers for each block.\n        first_batch_norm - A Python list containing booleans representing the\n          presence of a batch norm layer at the beginning of a given block.\n        strides - A Python list containing integers representing the stride of\n          the residual function for each block.\n        num_channels_init_block - An integer representing the number of channels\n          for the convolutional layer in the initial block.\n        dimension - A string (either \"2d\" or \"3d\") that decides if the RevNet is\n          2-dimensional or 3-dimensional.\n    reuse: Whether to reuse the default variable scope.\n\n  Returns:\n    [batch_size, hidden_dim] pre-logits tensor from the bottleneck RevNet."
  },
  {
    "code": "def _json_safe(cls, value):\n        if type(value) == date:\n            return str(value)\n        elif type(value) == datetime:\n            return value.strftime('%Y-%m-%d %H:%M:%S')\n        elif isinstance(value, ObjectId):\n            return str(value)\n        elif isinstance(value, _BaseFrame):\n            return value.to_json_type()\n        elif isinstance(value, (list, tuple)):\n            return [cls._json_safe(v) for v in value]\n        elif isinstance(value, dict):\n            return {k:cls._json_safe(v) for k, v in value.items()}\n        return value",
    "docstring": "Return a JSON safe value"
  },
  {
    "code": "def _package_conf_file_to_dir(file_name):\n    if file_name in SUPPORTED_CONFS:\n        path = BASE_PATH.format(file_name)\n        if os.path.exists(path):\n            if os.path.isdir(path):\n                return False\n            else:\n                os.rename(path, path + '.tmpbak')\n                os.mkdir(path, 0o755)\n                os.rename(path + '.tmpbak', os.path.join(path, 'tmp'))\n                return True\n        else:\n            os.mkdir(path, 0o755)\n            return True",
    "docstring": "Convert a config file to a config directory."
  },
  {
    "code": "def from_representation(self, data):\n        if data in self._TRUE_VALUES:\n            return True\n        elif data in self._FALSE_VALUES:\n            return False\n        else:\n            raise ValueError(\n                \"{type} type value must be one of {values}\".format(\n                    type=self.type,\n                    values=self._TRUE_VALUES.union(self._FALSE_VALUES)\n                )\n            )",
    "docstring": "Convert representation value to ``bool`` if it has expected form."
  },
  {
    "code": "def add_term(self, t):\n        if t not in self.terms:\n            if t.parent_term_lc == 'root':\n                self.terms.append(t)\n                self.doc.add_term(t, add_section=False)\n                t.set_ownership()\n            else:\n                raise GenerateError(\"Can only add or move root-level terms. Term '{}' parent is '{}' \"\n                                    .format(t, t.parent_term_lc))\n        assert t.section or t.join_lc == 'root.root', t",
    "docstring": "Add a term to this section and set it's ownership. Should only be used on root level terms"
  },
  {
    "code": "def isom(self,coolingFactor=None,EdgeAttribute=None,initialAdaptation=None,\\\n\t\tmaxEpoch=None,minAdaptation=None,minRadius=None,network=None,NodeAttribute=None,\\\n\t\tnodeList=None,radius=None,radiusConstantTime=None,singlePartition=None,\\\n\t\tsizeFactor=None,verbose=None):\n\t\tnetwork=check_network(self,network,verbose=verbose)\n\t\tPARAMS=set_param(['coolingFactor','EdgeAttribute','initialAdaptation',\\\n\t\t'maxEpoch','minAdaptation','minRadius','network','NodeAttribute','nodeList',\\\n\t\t'radius','radiusConstantTime','singlePartition','sizeFactor'],[coolingFactor,\\\n\t\tEdgeAttribute,initialAdaptation,maxEpoch,minAdaptation,minRadius,network,\\\n\t\tNodeAttribute,nodeList,radius,radiusConstantTime,singlePartition,sizeFactor])\n\t\tresponse=api(url=self.__url+\"/isom\", PARAMS=PARAMS, method=\"POST\", verbose=verbose)\n\t\treturn response",
    "docstring": "Execute the Inverted Self-Organizing Map Layout on a network.\n\n\t\t:param coolingFactor (string, optional): Cooling factor, in numeric value\n\t\t:param EdgeAttribute (string, optional): The name of the edge column contai\n\t\t\tning numeric values that will be used as weights in the layout algor\n\t\t\tithm. Only columns containing numeric values are shown\n\t\t:param initialAdaptation (string, optional): Initial adaptation, in numeric\n\t\t\t\tvalue\n\t\t:param maxEpoch (string, optional): Number of iterations, in numeric value\n\t\t:param minAdaptation (string, optional): Minimum adaptation value, in numer\n\t\t\tic value\n\t\t:param minRadius (string, optional): Minimum radius, in numeric value\n\t\t:param network (string, optional): Specifies a network by name, or by SUID\n\t\t\tif the prefix SUID: is used. The keyword CURRENT, or a blank value c\n\t\t\tan also be used to specify the current network.\n\t\t:param NodeAttribute (string, optional): The name of the node column contai\n\t\t\tning numeric values that will be used as weights in the layout algor\n\t\t\tithm. Only columns containing numeric values are shown\n\t\t:param nodeList (string, optional): Specifies a list of nodes. The keywords\n\t\t\t\tall, selected, or unselected can be used to specify nodes by their\n\t\t\tselection state. The pattern COLUMN:VALUE sets this parameter to any\n\t\t\t\trows that contain the specified column value; if the COLUMN prefix\n\t\t\tis not used, the NAME column is matched by default. A list of COLUMN\n\t\t\t:VALUE pairs of the format COLUMN1:VALUE1,COLUMN2:VALUE2,... can be\n\t\t\tused to match multiple values.\n\t\t:param radius (string, optional): Radius, in numeric value\n\t\t:param radiusConstantTime (string, optional): Radius constant, in numeric v\n\t\t\talue\n\t\t:param singlePartition (string, optional): Don't partition graph before lay\n\t\t\tout; boolean values only, true or false; defaults to false\n\t\t:param sizeFactor (string, optional): Size factor, in numeric value"
  },
  {
    "code": "def _should_set(self, key, mode):\n        if mode is None or mode not in [\"nx\", \"xx\"]:\n            return True\n        if mode == \"nx\":\n            if key in self.redis:\n                return False\n        elif key not in self.redis:\n            return False\n        return True",
    "docstring": "Determine if it is okay to set a key.\n\n        If the mode is None, returns True, otherwise, returns True of false based on\n        the value of ``key`` and the ``mode`` (nx | xx)."
  },
  {
    "code": "def decorate_event_js(js_code):\n    def add_annotation(method):\n        setattr(method, \"__is_event\", True )\n        setattr(method, \"_js_code\", js_code )\n        return method\n    return add_annotation",
    "docstring": "setup a method as an event, adding also javascript code to generate\n\n    Args:\n        js_code (str): javascript code to generate the event client-side.\n            js_code is added to the widget html as \n            widget.attributes['onclick'] = js_code%{'emitter_identifier':widget.identifier, 'event_name':'onclick'}"
  },
  {
    "code": "def get_position_searchable(self):\n        ids = gkr.list_item_ids_sync(self.keyring)\n        position_searchable = {}\n        for i in ids:\n            item_attrs = gkr.item_get_attributes_sync(self.keyring, i)\n            position_searchable[i] = item_attrs['searchable'] \n        return position_searchable",
    "docstring": "Return dict of the position and corrasponding searchable str"
  },
  {
    "code": "def _clear(self, pipe=None):\n        redis = self.redis if pipe is None else pipe\n        redis.delete(self.key)",
    "docstring": "Helper for clear operations.\n\n        :param pipe: Redis pipe in case update is performed as a part\n                     of transaction.\n        :type pipe: :class:`redis.client.StrictPipeline` or\n                    :class:`redis.client.StrictRedis`"
  },
  {
    "code": "def discharge_coefficient_to_K(D, Do, C):\n    r\n    beta = Do/D\n    beta2 = beta*beta\n    beta4 = beta2*beta2\n    return ((1.0 - beta4*(1.0 - C*C))**0.5/(C*beta2) - 1.0)**2",
    "docstring": "r'''Converts a discharge coefficient to a standard loss coefficient,\n    for use in computation of the actual pressure drop of an orifice or other\n    device.\n\n    .. math::\n        K = \\left[\\frac{\\sqrt{1-\\beta^4(1-C^2)}}{C\\beta^2} - 1\\right]^2\n        \n    Parameters\n    ----------\n    D : float\n        Upstream internal pipe diameter, [m]\n    Do : float\n        Diameter of orifice at flow conditions, [m]\n    C : float\n        Coefficient of discharge of the orifice, [-]\n\n    Returns\n    -------\n    K : float\n        Loss coefficient with respect to the velocity and density of the fluid\n        just upstream of the orifice, [-]\n\n    Notes\n    -----\n    If expansibility is used in the orifice calculation, the result will not\n    match with the specified pressure drop formula in [1]_; it can almost\n    be matched by dividing the calculated mass flow by the expansibility factor\n    and using that mass flow with the loss coefficient. \n    \n    Examples\n    --------\n    >>> discharge_coefficient_to_K(D=0.07366, Do=0.05, C=0.61512)\n    5.2314291729754\n    \n    References\n    ----------\n    .. [1] American Society of Mechanical Engineers. Mfc-3M-2004 Measurement \n       Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2001.\n    .. [2] ISO 5167-2:2003 - Measurement of Fluid Flow by Means of Pressure \n       Differential Devices Inserted in Circular Cross-Section Conduits Running\n       Full -- Part 2: Orifice Plates."
  },
  {
    "code": "def get_table_info(self, tablename):\n        conn = self.__get_conn()\n        ret = a99.get_table_info(conn, tablename)\n        if len(ret) == 0:\n            raise RuntimeError(\"Cannot get info for table '{}'\".format(tablename))\n        more = self.gui_info.get(tablename)\n        for row in ret.values():\n            caption, tooltip = None, None\n            if more:\n                info = more.get(row[\"name\"])\n                if info:\n                    caption, tooltip = info\n            row[\"caption\"] = caption\n            row[\"tooltip\"] = tooltip\n        return ret",
    "docstring": "Returns information about fields of a specific table\n\n        Returns:  OrderedDict((\"fieldname\", MyDBRow), ...))\n\n        **Note** Fields \"caption\" and \"tooltip\" are added to rows using information in moldb.gui_info"
  },
  {
    "code": "def train(self, conversation):\n        previous_statement_text = None\n        previous_statement_search_text = ''\n        statements_to_create = []\n        for conversation_count, text in enumerate(conversation):\n            if self.show_training_progress:\n                utils.print_progress_bar(\n                    'List Trainer',\n                    conversation_count + 1, len(conversation)\n                )\n            statement_search_text = self.chatbot.storage.tagger.get_bigram_pair_string(text)\n            statement = self.get_preprocessed_statement(\n                Statement(\n                    text=text,\n                    search_text=statement_search_text,\n                    in_response_to=previous_statement_text,\n                    search_in_response_to=previous_statement_search_text,\n                    conversation='training'\n                )\n            )\n            previous_statement_text = statement.text\n            previous_statement_search_text = statement_search_text\n            statements_to_create.append(statement)\n        self.chatbot.storage.create_many(statements_to_create)",
    "docstring": "Train the chat bot based on the provided list of\n        statements that represents a single conversation."
  },
  {
    "code": "def cancel_expired_invitations(invitations=None):\n    expiration_date = timezone.now() - settings.WALDUR_CORE['INVITATION_LIFETIME']\n    if not invitations:\n        invitations = models.Invitation.objects.filter(state=models.Invitation.State.PENDING)\n    invitations = invitations.filter(created__lte=expiration_date)\n    invitations.update(state=models.Invitation.State.EXPIRED)",
    "docstring": "Invitation lifetime must be specified in Waldur Core settings with parameter\n    \"INVITATION_LIFETIME\". If invitation creation time is less than expiration time, the invitation will set as expired."
  },
  {
    "code": "def copyNode(node, children=False, parent=False):\n    if parent is not False:\n        element = SubElement(\n            parent,\n            node.tag,\n            attrib=node.attrib,\n            nsmap={None: \"http://www.tei-c.org/ns/1.0\"}\n        )\n    else:\n        element = Element(\n            node.tag,\n            attrib=node.attrib,\n            nsmap={None: \"http://www.tei-c.org/ns/1.0\"}\n        )\n    if children:\n        if node.text:\n            element._setText(node.text)\n        for child in xmliter(node):\n            element.append(copy(child))\n    return element",
    "docstring": "Copy an XML Node\n\n    :param node: Etree Node\n    :param children: Copy children nodes is set to True\n    :param parent: Append copied node to parent if given\n    :return: New Element"
  },
  {
    "code": "def week_to_datetime(iso_year, iso_week):\n    \"datetime instance for the start of the given ISO year and week\"\n    gregorian = iso_to_gregorian(iso_year, iso_week, 0)\n    return datetime.datetime.combine(gregorian, datetime.time(0))",
    "docstring": "datetime instance for the start of the given ISO year and week"
  },
  {
    "code": "def LDAP_search(pattern_search, attribute):\n    connection, ldap_base = _get_LDAP_connection()\n    connection.search(\n        search_base=ldap_base,\n        search_filter=pattern_search,\n        attributes=[attribute]\n    )\n    return connection.response",
    "docstring": "Do a LDAP search"
  },
  {
    "code": "def _clean_streams(repo, mapped_streams):\n    for stream_name in ('stdout', 'stderr'):\n        stream = mapped_streams.get(stream_name)\n        if not stream:\n            continue\n        path = os.path.relpath(stream, start=repo.working_dir)\n        if (path, 0) not in repo.index.entries:\n            os.remove(stream)\n        else:\n            blob = repo.index.entries[(path, 0)].to_blob(repo)\n            with open(path, 'wb') as fp:\n                fp.write(blob.data_stream.read())",
    "docstring": "Clean mapped standard streams."
  },
  {
    "code": "def put_logging(Bucket,\n           TargetBucket=None, TargetPrefix=None, TargetGrants=None,\n           region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        logstate = {}\n        targets = {'TargetBucket': TargetBucket,\n                   'TargetGrants': TargetGrants,\n                   'TargetPrefix': TargetPrefix}\n        for key, val in six.iteritems(targets):\n            if val is not None:\n                logstate[key] = val\n        if logstate:\n            logstatus = {'LoggingEnabled': logstate}\n        else:\n            logstatus = {}\n        if TargetGrants is not None and isinstance(TargetGrants, six.string_types):\n            TargetGrants = salt.utils.json.loads(TargetGrants)\n        conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)\n        return {'updated': True, 'name': Bucket}\n    except ClientError as e:\n        return {'updated': False, 'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Given a valid config, update the logging parameters for a bucket.\n\n    Returns {updated: true} if parameters were updated and returns\n    {updated: False} if parameters were not updated.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix"
  },
  {
    "code": "def removeLayer(self, layer):\n        if isinstance(layer, BaseGlyph):\n            layer = layer.layer.name\n        layerName = layer\n        layerName = normalizers.normalizeLayerName(layerName)\n        if self._getLayer(layerName).layer.name == layerName:\n            self._removeLayer(layerName)",
    "docstring": "Remove ``layer`` from this glyph.\n\n            >>> glyph.removeLayer(\"background\")\n\n        Layer can be a :ref:`type-glyph-layer` or a :ref:`type-string`\n        representing a layer name."
  },
  {
    "code": "def getStartTag(self):\n        attributeStrings = []\n        for name, val in self._attributes.items():\n            if val:\n                val = tostr(val)\n            if val or name not in TAG_ITEM_BINARY_ATTRIBUTES:\n                val = escapeQuotes(val)\n                attributeStrings.append('%s=\"%s\"' %(name, val) )\n            else:\n                attributeStrings.append(name)\n        if attributeStrings:\n            attributeString = ' ' + ' '.join(attributeStrings)\n        else:\n            attributeString = ''\n        if self.isSelfClosing is False:\n            return \"%s<%s%s >\" %(self._indent, self.tagName, attributeString)\n        else:\n            return \"%s<%s%s />\" %(self._indent, self.tagName, attributeString)",
    "docstring": "getStartTag - Returns the start tag represented as HTML\n\n            @return - String of start tag with attributes"
  },
  {
    "code": "def _try_dump_cnt(self):\n        now = time.time()\n        if now - self._last_dump_cnt > 60:\n            self._last_dump_cnt = now\n            self._dump_cnt()\n            self._print_counter_log()",
    "docstring": "Dump counters every 60 seconds"
  },
  {
    "code": "def put(self, device_id: int) -> Device:\n        device = self._get_or_abort(device_id)\n        self.update(device)\n        session.commit()\n        session.add(device)\n        return device",
    "docstring": "Updates the Device Resource with the\n        name."
  },
  {
    "code": "def make(self):\n        logger.debug(\"preparing to add all git files\")\n        num_added = self.local_repo.add_all_files()\n        if num_added:\n            self.local_repo.commit(\"Initial import from Project Gutenberg\")\n        file_handler = NewFilesHandler(self)\n        file_handler.add_new_files()\n        num_added = self.local_repo.add_all_files()\n        if num_added:\n            self.local_repo.commit(\n                \"Updates Readme, contributing, license files, cover, metadata.\"\n            )",
    "docstring": "turn fetched files into a local repo, make auxiliary files"
  },
  {
    "code": "def get_s2_pixel_cloud_detector(threshold=0.4, average_over=4, dilation_size=2, all_bands=True):\n    return S2PixelCloudDetector(threshold=threshold,\n                                average_over=average_over,\n                                dilation_size=dilation_size,\n                                all_bands=all_bands)",
    "docstring": "Wrapper function for pixel-based S2 cloud detector `S2PixelCloudDetector`"
  },
  {
    "code": "def chdir(path):\n    cur_cwd = os.getcwd()\n    os.chdir(path)\n    try:\n        yield\n    finally:\n        os.chdir(cur_cwd)",
    "docstring": "Change the working directory to `path` for the duration of this context\n    manager.\n\n    :param str path: The path to change to"
  },
  {
    "code": "def inside_softimage():\n    try:\n        import maya\n        return False\n    except ImportError:\n        pass\n    try:\n        from win32com.client import Dispatch as disp\n        disp('XSI.Application')\n        return True\n    except:\n        return False",
    "docstring": "Returns a boolean indicating if the code is executed inside softimage."
  },
  {
    "code": "def constructor(\n            self,\n            name=None,\n            function=None,\n            return_type=None,\n            arg_types=None,\n            header_dir=None,\n            header_file=None,\n            recursive=None):\n        return (\n            self._find_single(\n                self._impl_matchers[scopedef_t.constructor],\n                name=name,\n                function=function,\n                decl_type=self._impl_decl_types[\n                    scopedef_t.constructor],\n                return_type=return_type,\n                arg_types=arg_types,\n                header_dir=header_dir,\n                header_file=header_file,\n                recursive=recursive)\n        )",
    "docstring": "returns reference to constructor declaration, that is matched\n        defined criteria"
  },
  {
    "code": "def body(self):\n        body = self.get_parameters_by_location(['body'])\n        return self.root.schemas.get(body[0].type) if body else None",
    "docstring": "Return body request parameter\n\n        :return: Body parameter\n        :rtype: Parameter or None"
  },
  {
    "code": "def _on_scale(self, event):\n        self._entry.delete(0, tk.END)\n        self._entry.insert(0, str(self._variable.get()))",
    "docstring": "Callback for the Scale widget, inserts an int value into the Entry.\n\n        :param event: Tkinter event"
  },
  {
    "code": "def get_midi_data(self):\n        tracks = [t.get_midi_data() for t in self.tracks if t.track_data != '']\n        return self.header() + ''.join(tracks)",
    "docstring": "Collect and return the raw, binary MIDI data from the tracks."
  },
  {
    "code": "def stop_tuning_job(self, name):\n        try:\n            LOGGER.info('Stopping tuning job: {}'.format(name))\n            self.sagemaker_client.stop_hyper_parameter_tuning_job(HyperParameterTuningJobName=name)\n        except ClientError as e:\n            error_code = e.response['Error']['Code']\n            if error_code == 'ValidationException':\n                LOGGER.info('Tuning job: {} is already stopped or not running.'.format(name))\n            else:\n                LOGGER.error('Error occurred while attempting to stop tuning job: {}. Please try again.'.format(name))\n                raise",
    "docstring": "Stop the Amazon SageMaker hyperparameter tuning job with the specified name.\n\n        Args:\n            name (str): Name of the Amazon SageMaker hyperparameter tuning job.\n\n        Raises:\n            ClientError: If an error occurs while trying to stop the hyperparameter tuning job."
  },
  {
    "code": "def get_factory_object_name(namespace):\n    \"Returns the correct factory object for a given namespace\"\n    factory_map = {\n        'http://www.opengis.net/kml/2.2': 'KML',\n        'http://www.w3.org/2005/Atom': 'ATOM',\n        'http://www.google.com/kml/ext/2.2': 'GX'\n    }\n    if namespace:\n        if factory_map.has_key(namespace):\n            factory_object_name = factory_map[namespace]\n        else:\n            factory_object_name = None\n    else:\n        factory_object_name = 'KML'\n    return factory_object_name",
    "docstring": "Returns the correct factory object for a given namespace"
  },
  {
    "code": "def main_view(request, ident, stateless=False, cache_id=None, **kwargs):\n    'Main view for a dash app'\n    _, app = DashApp.locate_item(ident, stateless, cache_id=cache_id)\n    view_func = app.locate_endpoint_function()\n    resp = view_func()\n    return HttpResponse(resp)",
    "docstring": "Main view for a dash app"
  },
  {
    "code": "def load(self, filename=None):\n        if not filename:\n            for name in self.find_default(\".pelix.conf\"):\n                self.load(name)\n        else:\n            with open(filename, \"r\") as filep:\n                self.__parse(json.load(filep))",
    "docstring": "Loads the given file and adds its content to the current state.\n        This method can be called multiple times to merge different files.\n\n        If no filename is given, this method loads all default files found.\n        It returns False if no default configuration file has been found\n\n        :param filename: The file to load\n        :return: True if the file has been correctly parsed, False if no file\n                 was given and no default file exist\n        :raise IOError: Error loading file"
  },
  {
    "code": "def DbGetDeviceAttributePropertyHist(self, argin):\n        self._log.debug(\"In DbGetDeviceAttributePropertyHist()\")\n        dev_name = argin[0]\n        attribute = replace_wildcard(argin[1])\n        prop_name = replace_wildcard(argin[2])\n        return self.db.get_device_attribute_property_hist(dev_name, attribute, prop_name)",
    "docstring": "Retrieve device attribute property history\n\n        :param argin: Str[0] = Device name\n        Str[1] = Attribute name\n        Str[2] = Property name\n        :type: tango.DevVarStringArray\n        :return: Str[0] = Attribute name\n        Str[1] = Property name\n        Str[2] = date\n        Str[3] = Property value number (array case)\n        Str[4] = Property value 1\n        Str[n] = Property value n\n        :rtype: tango.DevVarStringArray"
  },
  {
    "code": "def interval_diff(progression1, progression2, interval):\n    i = numeral_intervals[numerals.index(progression1)]\n    j = numeral_intervals[numerals.index(progression2)]\n    acc = 0\n    if j < i:\n        j += 12\n    while j - i > interval:\n        acc -= 1\n        j -= 1\n    while j - i < interval:\n        acc += 1\n        j += 1\n    return acc",
    "docstring": "Return the number of half steps progression2 needs to be diminished or\n    augmented until the interval between progression1 and progression2 is\n    interval."
  },
  {
    "code": "def delete_project(self, tenant_name, part_name):\n        res = self._delete_partition(tenant_name, part_name)\n        if res and res.status_code in self._resp_ok:\n            LOG.debug(\"Deleted %s partition in DCNM.\", part_name)\n        else:\n            LOG.error(\"Failed to delete %(part)s partition in DCNM.\"\n                      \"Response: %(res)s\", {'part': part_name, 'res': res})\n            raise dexc.DfaClientRequestFailed(reason=res)\n        res = self._delete_org(tenant_name)\n        if res and res.status_code in self._resp_ok:\n            LOG.debug(\"Deleted %s organization in DCNM.\", tenant_name)\n        else:\n            LOG.error(\"Failed to delete %(org)s organization in DCNM.\"\n                      \"Response: %(res)s\", {'org': tenant_name, 'res': res})\n            raise dexc.DfaClientRequestFailed(reason=res)",
    "docstring": "Delete project on the DCNM.\n\n        :param tenant_name: name of project.\n        :param part_name: name of partition."
  },
  {
    "code": "def str(self,local):\n        s = self.start_time.str(local) \\\n            + u\" to \" \\\n            + self.end_time.str(local)\n        return s",
    "docstring": "Return the string representation of the time range\n\n            :param local: if False [default] use UTC datetime. If True use localtz"
  },
  {
    "code": "def get_header(self, elem, style, node):\n        font_size = style\n        if hasattr(elem, 'possible_header'):\n            if elem.possible_header:\n                return 'h1'\n        if not style:\n            return 'h6'\n        if hasattr(style, 'style_id'):\n            font_size = _get_font_size(self.doc, style)\n        try:\n            if font_size in self.doc.possible_headers_style:\n                return 'h{}'.format(self.doc.possible_headers_style.index(font_size)+1)\n            return 'h{}'.format(self.doc.possible_headers.index(font_size)+1)\n        except ValueError:\n            return 'h6'",
    "docstring": "Returns HTML tag representing specific header for this element.\n\n        :Returns:\n          String representation of HTML tag."
  },
  {
    "code": "def _compile_state(sls_opts, mods=None):\n    st_ = HighState(sls_opts)\n    if not mods:\n        return st_.compile_low_chunks()\n    high_data, errors = st_.render_highstate({sls_opts['saltenv']: mods})\n    high_data, ext_errors = st_.state.reconcile_extend(high_data)\n    errors += ext_errors\n    errors += st_.state.verify_high(high_data)\n    if errors:\n        return errors\n    high_data, req_in_errors = st_.state.requisite_in(high_data)\n    errors += req_in_errors\n    high_data = st_.state.apply_exclude(high_data)\n    if errors:\n        return errors\n    return st_.state.compile_high_data(high_data)",
    "docstring": "Generates the chunks of lowdata from the list of modules"
  },
  {
    "code": "def DeviceSensorsGet(self, device_id, parameters):\r\n        if self.__SenseApiCall__('/devices/{0}/sensors.json'.format(device_id), 'GET', parameters = parameters):\r\n            return True\r\n        else:\r\n            self.__error__ = \"api call unsuccessful\"\r\n            return False",
    "docstring": "Obtain a list of all sensors attached to a device.\r\n\r\n            @param device_id (int) - Device for which to retrieve sensors\r\n            @param parameters (dict) - Search parameters\r\n\r\n            @return (bool) - Boolean indicating whether DeviceSensorsGet was succesful."
  },
  {
    "code": "def _update_data(self, name, value, timestamp, interval, config, conn):\n    i_time = config['i_calc'].to_bucket(timestamp)\n    if not config['coarse']:\n      r_time = config['r_calc'].to_bucket(timestamp)\n    else:\n      r_time = None\n    stmt = self._table.update().where(\n      and_(\n        self._table.c.name==name,\n        self._table.c.interval==interval,\n        self._table.c.i_time==i_time,\n        self._table.c.r_time==r_time)\n    ).values({self._table.c.value: value})\n    rval = conn.execute( stmt )\n    return rval.rowcount",
    "docstring": "Support function for insert. Should be called within a transaction"
  },
  {
    "code": "def fluoview_metadata(self):\n        if not self.is_fluoview:\n            return None\n        result = {}\n        page = self.pages[0]\n        result.update(page.tags['MM_Header'].value)\n        result['Stamp'] = page.tags['MM_Stamp'].value\n        return result",
    "docstring": "Return consolidated FluoView metadata as dict."
  },
  {
    "code": "def rebase(self, qemu_img, base_image):\n        if not os.path.exists(base_image):\n            raise FileNotFoundError(base_image)\n        command = [qemu_img, \"rebase\", \"-u\", \"-b\", base_image, self._path]\n        process = yield from asyncio.create_subprocess_exec(*command)\n        retcode = yield from process.wait()\n        if retcode != 0:\n            raise Qcow2Error(\"Could not rebase the image\")\n        self._reload()",
    "docstring": "Rebase a linked clone in order to use the correct disk\n\n        :param qemu_img: Path to the qemu-img binary\n        :param base_image: Path to the base image"
  },
  {
    "code": "def post(self, data):\n        uri = '{}/sinkhole'.format(self.client.remote)\n        self.logger.debug(uri)\n        if PYVERSION == 2:\n            try:\n                data = data.decode('utf-8')\n            except Exception:\n                data = data.decode('latin-1')\n        data = {\n            'message': data\n        }\n        body = self.client.post(uri, data)\n        return body",
    "docstring": "POSTs a raw SMTP message to the Sinkhole API\n\n        :param data: raw content to be submitted [STRING]\n        :return: { list of predictions }"
  },
  {
    "code": "def restart(name, runas=None):\n    return prlctl('restart', salt.utils.data.decode(name), runas=runas)",
    "docstring": "Restart a VM by gracefully shutting it down and then restarting\n    it\n\n    :param str name:\n        Name/ID of VM to restart\n\n    :param str runas:\n        The user that the prlctl command will be run as\n\n    Example:\n\n    .. code-block:: bash\n\n        salt '*' parallels.restart macvm runas=macdev"
  },
  {
    "code": "def file_exists(self, fid):\n        res = self.get_file_size(fid)\n        if res is not None:\n            return True\n        return False",
    "docstring": "Checks if file with provided fid exists\n\n        Args:\n            **fid**: File identifier <volume_id>,<file_name_hash>\n\n        Returns:\n            True if file exists. False if not."
  },
  {
    "code": "def __inst_doc(self, docid, doc_type_name=None):\n        doc = None\n        docpath = self.fs.join(self.rootdir, docid)\n        if not self.fs.exists(docpath):\n            return None\n        if doc_type_name is not None:\n            for (is_doc_type, doc_type_name_b, doc_type) in DOC_TYPE_LIST:\n                if (doc_type_name_b == doc_type_name):\n                    doc = doc_type(self.fs, docpath, docid)\n            if not doc:\n                logger.warning(\n                    (\"Warning: unknown doc type found in the index: %s\") %\n                    doc_type_name\n                )\n        if not doc:\n            for (is_doc_type, doc_type_name, doc_type) in DOC_TYPE_LIST:\n                if is_doc_type(self.fs, docpath):\n                    doc = doc_type(self.fs, docpath, docid)\n                    break\n        if not doc:\n            logger.warning(\"Warning: unknown doc type for doc '%s'\" % docid)\n        return doc",
    "docstring": "Instantiate a document based on its document id.\n        The information are taken from the whoosh index."
  },
  {
    "code": "def order_by_index(seq, index, iter=False):\n    return (seq[i] for i in index) if iter else [seq[i] for i in index]",
    "docstring": "Order a given sequence by an index sequence.\n\n    The output of `index_natsorted` is a\n    sequence of integers (index) that correspond to how its input\n    sequence **would** be sorted. The idea is that this index can\n    be used to reorder multiple sequences by the sorted order of the\n    first sequence. This function is a convenient wrapper to\n    apply this ordering to a sequence.\n\n    Parameters\n    ----------\n    seq : sequence\n        The sequence to order.\n\n    index : iterable\n        The iterable that indicates how to order `seq`.\n        It should be the same length as `seq` and consist\n        of integers only.\n\n    iter : {{True, False}}, optional\n        If `True`, the ordered sequence is returned as a\n        iterator; otherwise it is returned as a\n        list. The default is `False`.\n\n    Returns\n    -------\n    out : {{list, iterator}}\n        The sequence ordered by `index`, as a `list` or as an\n        iterator (depending on the value of `iter`).\n\n    See Also\n    --------\n    index_natsorted\n    index_humansorted\n    index_realsorted\n\n    Examples\n    --------\n\n    `order_by_index` is a convenience function that helps you apply\n    the result of `index_natsorted`::\n\n        >>> a = ['num3', 'num5', 'num2']\n        >>> b = ['foo', 'bar', 'baz']\n        >>> index = index_natsorted(a)\n        >>> index\n        [2, 0, 1]\n        >>> # Sort both lists by the sort order of a\n        >>> order_by_index(a, index)\n        [{u}'num2', {u}'num3', {u}'num5']\n        >>> order_by_index(b, index)\n        [{u}'baz', {u}'foo', {u}'bar']"
  },
  {
    "code": "def resolve_content_type(type_resolvers, request):\n    for resolver in type_resolvers:\n        content_type = parse_content_type(resolver(request))\n        if content_type:\n            return content_type",
    "docstring": "Resolve content types from a request."
  },
  {
    "code": "def remove_namespace(attribute, namespace_splitter=NAMESPACE_SPLITTER, root_only=False):\n    attribute_tokens = attribute.split(namespace_splitter)\n    stripped_attribute = root_only and namespace_splitter.join(attribute_tokens[1:]) or \\\n                         attribute_tokens[len(attribute_tokens) - 1]\n    LOGGER.debug(\"> Attribute: '{0}', stripped attribute: '{1}'.\".format(attribute, stripped_attribute))\n    return stripped_attribute",
    "docstring": "Returns attribute with stripped foundations.namespace.\n\n    Usage::\n\n        >>> remove_namespace(\"grandParent|parent|child\")\n        u'child'\n        >>> remove_namespace(\"grandParent|parent|child\", root_only=True)\n        u'parent|child'\n\n    :param attribute: Attribute.\n    :type attribute: unicode\n    :param namespace_splitter: Namespace splitter character.\n    :type namespace_splitter: unicode\n    :param root_only: Remove only root foundations.namespace.\n    :type root_only: bool\n    :return: Attribute without foundations.namespace.\n    :rtype: unicode"
  },
  {
    "code": "def _process_data(self, **data) -> dict:\n        env_prefix = data.pop(\"env_prefix\", None)\n        environs = self._get_environs(env_prefix)\n        if environs:\n            data = merge_dicts(data, environs)\n        data = self._merge_defaults(data)\n        self._validate_data(data)\n        data = self._validate_data_dependencies(data)\n        data = self._prepare_data(data)\n        return data",
    "docstring": "The main method that process all resources data. Validates schema, gets environs, validates data, prepares\n         it via provider requirements, merges defaults and check for data dependencies\n\n        :param data: The raw data passed by the notifiers client\n        :return: Processed data"
  },
  {
    "code": "def get_states(self):\n        outcome_tag = {}\n        cpds = self.model.get_cpds()\n        for cpd in cpds:\n            var = cpd.variable\n            outcome_tag[var] = []\n            if cpd.state_names is None or cpd.state_names.get(var) is None:\n                states = range(cpd.get_cardinality([var])[var])\n            else:\n                states = cpd.state_names[var]\n            for state in states:\n                state_tag = etree.SubElement(self.variables[var], \"OUTCOME\")\n                state_tag.text = self._make_valid_state_name(state)\n                outcome_tag[var].append(state_tag)\n        return outcome_tag",
    "docstring": "Add outcome to variables of XMLBIF\n\n        Return\n        ------\n        dict: dict of type {variable: outcome tags}\n\n        Examples\n        --------\n        >>> writer = XMLBIFWriter(model)\n        >>> writer.get_states()\n        {'dog-out': [<Element OUTCOME at 0x7ffbabfcdec8>, <Element OUTCOME at 0x7ffbabfcdf08>],\n         'family-out': [<Element OUTCOME at 0x7ffbabfd4108>, <Element OUTCOME at 0x7ffbabfd4148>],\n         'bowel-problem': [<Element OUTCOME at 0x7ffbabfd4088>, <Element OUTCOME at 0x7ffbabfd40c8>],\n         'hear-bark': [<Element OUTCOME at 0x7ffbabfcdf48>, <Element OUTCOME at 0x7ffbabfcdf88>],\n         'light-on': [<Element OUTCOME at 0x7ffbabfcdfc8>, <Element OUTCOME at 0x7ffbabfd4048>]}"
  },
  {
    "code": "def setup(self):\n        r = self.call_ext_prog(self.get_option(\"script\"))\n        if r['status'] == 0:\n            tarfile = \"\"\n            for line in r['output']:\n                line = line.strip()\n                tarfile = self.do_regex_find_all(r\"ftp (.*tar.gz)\", line)\n            if len(tarfile) == 1:\n                self.add_copy_spec(tarfile[0])",
    "docstring": "interface with vrtsexplorer to capture veritas related data"
  },
  {
    "code": "def get_SCAT(points, low_bound, high_bound, x_max, y_max):\n    SCAT = True\n    for point in points:\n        result = in_SCAT_box(point[0], point[1], low_bound, high_bound, x_max, y_max)\n        if result == False:\n            SCAT = False\n    return SCAT",
    "docstring": "runs SCAT test and returns boolean"
  },
  {
    "code": "def __texUpdate(self, frame):\n\t\tif self.texture_locked:\n\t\t\treturn\n\t\tself.buffer = frame\n\t\tself.texUpdated = True",
    "docstring": "Update the texture with the newly supplied frame."
  },
  {
    "code": "def cdn_url(request):\n    cdn_url, ssl_url = _get_container_urls(CumulusStorage())\n    static_url = settings.STATIC_URL\n    return {\n        \"CDN_URL\": cdn_url + static_url,\n        \"CDN_SSL_URL\": ssl_url + static_url,\n    }",
    "docstring": "A context processor that exposes the full CDN URL in templates."
  },
  {
    "code": "def trackers(self):\n        announce_list = self.metainfo.get('announce-list', None)\n        if not announce_list:\n            announce = self.metainfo.get('announce', None)\n            if announce:\n                return [[announce]]\n        else:\n            return announce_list",
    "docstring": "List of tiers of announce URLs or ``None`` for no trackers\n\n        A tier is either a single announce URL (:class:`str`) or an\n        :class:`~collections.abc.Iterable` (e.g. :class:`list`) of announce\n        URLs.\n\n        Setting this property sets or removes ``announce`` and ``announce-list``\n        in :attr:`metainfo`. ``announce`` is set to the first tracker of the\n        first tier.\n\n        :raises URLError: if any of the announce URLs is invalid"
  },
  {
    "code": "def _make_actor_method_executor(self, method_name, method, actor_imported):\n        def actor_method_executor(dummy_return_id, actor, *args):\n            self._worker.actor_task_counter += 1\n            try:\n                if is_class_method(method):\n                    method_returns = method(*args)\n                else:\n                    method_returns = method(actor, *args)\n            except Exception as e:\n                if (isinstance(actor, ray.actor.Checkpointable)\n                        and self._worker.actor_task_counter != 1):\n                    self._save_and_log_checkpoint(actor)\n                raise e\n            else:\n                if isinstance(actor, ray.actor.Checkpointable):\n                    if self._worker.actor_task_counter == 1:\n                        if actor_imported:\n                            self._restore_and_log_checkpoint(actor)\n                    else:\n                        self._save_and_log_checkpoint(actor)\n                return method_returns\n        return actor_method_executor",
    "docstring": "Make an executor that wraps a user-defined actor method.\n\n        The wrapped method updates the worker's internal state and performs any\n        necessary checkpointing operations.\n\n        Args:\n            method_name (str): The name of the actor method.\n            method (instancemethod): The actor method to wrap. This should be a\n                method defined on the actor class and should therefore take an\n                instance of the actor as the first argument.\n            actor_imported (bool): Whether the actor has been imported.\n                Checkpointing operations will not be run if this is set to\n                False.\n\n        Returns:\n            A function that executes the given actor method on the worker's\n                stored instance of the actor. The function also updates the\n                worker's internal state to record the executed method."
  },
  {
    "code": "def keyPressEvent(self, event):\r\n        if event.key() == Qt.Key_Delete:\r\n            self.remove_item()\r\n        elif event.key() == Qt.Key_F2:\r\n            self.rename_item()\r\n        elif event == QKeySequence.Copy:\r\n            self.copy()\r\n        elif event == QKeySequence.Paste:\r\n            self.paste()\r\n        else:\r\n            QTableView.keyPressEvent(self, event)",
    "docstring": "Reimplement Qt methods"
  },
  {
    "code": "def is_method_call(node, method_name):\n    if not isinstance(node, nodes.Call):\n        return False\n    if isinstance(node.node, nodes.Getattr):\n        method = node.node.attr\n    elif isinstance(node.node, nodes.Name):\n        method = node.node.name\n    elif isinstance(node.node, nodes.Getitem):\n        method = node.node.arg.value\n    else:\n        return False\n    if isinstance(method_name, (list, tuple)):\n        return method in method_name\n    return method == method_name",
    "docstring": "Returns True if `node` is a method call for `method_name`. `method_name`\n    can be either a string or an iterable of strings."
  },
  {
    "code": "def SaveResourceUsage(self, status):\n    user_cpu = status.cpu_time_used.user_cpu_time\n    system_cpu = status.cpu_time_used.system_cpu_time\n    self.rdf_flow.cpu_time_used.user_cpu_time += user_cpu\n    self.rdf_flow.cpu_time_used.system_cpu_time += system_cpu\n    self.rdf_flow.network_bytes_sent += status.network_bytes_sent\n    if self.rdf_flow.cpu_limit:\n      user_cpu_total = self.rdf_flow.cpu_time_used.user_cpu_time\n      system_cpu_total = self.rdf_flow.cpu_time_used.system_cpu_time\n      if self.rdf_flow.cpu_limit < (user_cpu_total + system_cpu_total):\n        raise flow.FlowError(\"CPU limit exceeded for {} {}.\".format(\n            self.rdf_flow.flow_class_name, self.rdf_flow.flow_id))\n    if (self.rdf_flow.network_bytes_limit and\n        self.rdf_flow.network_bytes_limit < self.rdf_flow.network_bytes_sent):\n      raise flow.FlowError(\"Network bytes limit exceeded {} {}.\".format(\n          self.rdf_flow.flow_class_name, self.rdf_flow.flow_id))",
    "docstring": "Method to tally resources."
  },
  {
    "code": "def enable_reporting(self):\n        if self.mode is not INPUT:\n            raise IOError(\"{0} is not an input and can therefore not report\".format(self))\n        if self.type == ANALOG:\n            self.reporting = True\n            msg = bytearray([REPORT_ANALOG + self.pin_number, 1])\n            self.board.sp.write(msg)\n        else:\n            self.port.enable_reporting()",
    "docstring": "Set an input pin to report values."
  },
  {
    "code": "def cancelall(ctx, market, account):\n    market = Market(market)\n    ctx.bitshares.bundle = True\n    market.cancel([x[\"id\"] for x in market.accountopenorders(account)], account=account)\n    print_tx(ctx.bitshares.txbuffer.broadcast())",
    "docstring": "Cancel all orders of an account in a market"
  },
  {
    "code": "def show_file(file_):\n    file_ = (models.File.query.get(file_))\n    if file_ is None:\n        abort(404)\n    return render_template('file.html', file_=file_)",
    "docstring": "Returns details of a file"
  },
  {
    "code": "def _request_helper(self, url, request_body):\n        response = None\n        try:\n            response = self.session.post(\n                url, data=request_body, **self.request_defaults)\n            response.encoding = 'UTF-8'\n            if self._cookiejar is not None:\n                for cookie in response.cookies:\n                    self._cookiejar.set_cookie(cookie)\n                if self._cookiejar.filename is not None:\n                    self._cookiejar.save()\n            response.raise_for_status()\n            return self.parse_response(response)\n        except requests.RequestException as e:\n            if not response:\n                raise\n            raise ProtocolError(\n                url, response.status_code, str(e), response.headers)\n        except Fault:\n            raise\n        except Exception:\n            e = BugzillaError(str(sys.exc_info()[1]))\n            e.__traceback__ = sys.exc_info()[2]\n            raise e",
    "docstring": "A helper method to assist in making a request and provide a parsed\n        response."
  },
  {
    "code": "def _ray_step(self, x, y, alpha_x, alpha_y, delta_T):\n        x_ = x + alpha_x * delta_T\n        y_ = y + alpha_y * delta_T\n        return x_, y_",
    "docstring": "ray propagation with small angle approximation\n\n        :param x: co-moving x-position\n        :param y: co-moving y-position\n        :param alpha_x: deflection angle in x-direction at (x, y)\n        :param alpha_y: deflection angle in y-direction at (x, y)\n        :param delta_T: transversal angular diameter distance to the next step\n        :return:"
  },
  {
    "code": "def delete_thing(self, lid):\n        logger.info(\"delete_thing(lid=\\\"%s\\\")\", lid)\n        evt = self.delete_thing_async(lid)\n        self._wait_and_except_if_failed(evt)",
    "docstring": "Delete a Thing\n\n        Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)\n        containing the error if the infrastructure detects a problem\n\n        Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)\n        if there is a communications problem between you and the infrastructure\n\n        `lid` (required) (string) local identifier of the Thing you want to delete"
  },
  {
    "code": "def render_from_string(content, context=None, globals=None):\n    yaml_resolver = resolver.TYamlResolver.new_from_string(content)\n    return yaml_resolver.resolve(Context(context), globals)._data",
    "docstring": "Renders a templated yaml document from a string.\n\n    :param content: The yaml string to evaluate.\n    :param context: A context to overlay on the yaml file.  This will override any yaml values.\n    :param globals: A dictionary of globally-accessible objects within the rendered template.\n    :return: A dict with the final overlayed configuration."
  },
  {
    "code": "def Validate(self, value, **_):\n    if isinstance(value, rdfvalue.RDFString):\n      return Text(value)\n    if isinstance(value, Text):\n      return value\n    if isinstance(value, bytes):\n      return value.decode(\"utf-8\")\n    raise type_info.TypeValueError(\"Not a valid unicode string: %r\" % value)",
    "docstring": "Validates a python format representation of the value."
  },
  {
    "code": "def dict_to_json(xcol, ycols, labels, value_columns):\n    json_data = dict()\n    json_data['cols'] = [{'id': xcol,\n                          'label': as_unicode(labels[xcol]),\n                          'type': 'string'}]\n    for ycol in ycols:\n        json_data['cols'].append({'id': ycol,\n                                  'label': as_unicode(labels[ycol]),\n                                  'type': 'number'})\n    json_data['rows'] = []\n    for value in value_columns:\n        row = {'c': []}\n        if isinstance(value[xcol], datetime.date):\n            row['c'].append({'v': (str(value[xcol]))})\n        else:\n            row['c'].append({'v': (value[xcol])})\n        for ycol in ycols:\n            if value[ycol]:\n                row['c'].append({'v': (value[ycol])})\n            else:\n                row['c'].append({'v': 0})\n        json_data['rows'].append(row)\n    return json_data",
    "docstring": "Converts a list of dicts from datamodel query results\n        to google chart json data.\n\n        :param xcol:\n            The name of a string column to be used has X axis on chart\n        :param ycols:\n            A list with the names of series cols, that can be used as numeric\n        :param labels:\n            A dict with the columns labels.\n        :param value_columns:\n            A list of dicts with the values to convert"
  },
  {
    "code": "def validate_sort_fields(self):\n        sort_fields = ','.join(self.options.sort_fields)\n        if sort_fields == '*':\n            sort_fields = self.get_output_fields()\n        return formatting.validate_sort_fields(sort_fields or config.sort_fields)",
    "docstring": "Take care of sorting."
  },
  {
    "code": "def get_stride(self):\n        fftlength = float(self.args.secpfft)\n        overlap = fftlength * self.args.overlap\n        stride = fftlength - overlap\n        nfft = self.duration / stride\n        ffps = int(nfft / (self.width * 0.8))\n        if ffps > 3:\n            return max(2 * fftlength, ffps * stride + fftlength - 1)\n        return None",
    "docstring": "Calculate the stride for the spectrogram\n\n        This method returns the stride as a `float`, or `None` to indicate\n        selected usage of `TimeSeries.spectrogram2`."
  },
  {
    "code": "def write(self)->None:\n        \"Writes model gradient statistics to Tensorboard.\"\n        if len(self.gradients) == 0: return\n        norms = [x.data.norm() for x in self.gradients]\n        self._write_avg_norm(norms=norms)\n        self._write_median_norm(norms=norms)\n        self._write_max_norm(norms=norms)\n        self._write_min_norm(norms=norms)\n        self._write_num_zeros()\n        self._write_avg_gradient()\n        self._write_median_gradient()\n        self._write_max_gradient()\n        self._write_min_gradient()",
    "docstring": "Writes model gradient statistics to Tensorboard."
  },
  {
    "code": "def protected_adminview_factory(base_class):\n    class ProtectedAdminView(base_class):\n        def _handle_view(self, name, **kwargs):\n            invenio_app = current_app.extensions.get('invenio-app', None)\n            if invenio_app:\n                setattr(invenio_app.talisman.local_options,\n                        'content_security_policy', None)\n            return super(ProtectedAdminView, self)._handle_view(name, **kwargs)\n        def is_accessible(self):\n            return current_user.is_authenticated and \\\n                   current_admin.permission_factory(self).can() and \\\n                   super(ProtectedAdminView, self).is_accessible()\n        def inaccessible_callback(self, name, **kwargs):\n            if not current_user.is_authenticated:\n                return redirect(url_for(\n                    current_app.config['ADMIN_LOGIN_ENDPOINT'],\n                    next=request.url))\n            super(ProtectedAdminView, self).inaccessible_callback(\n                name, **kwargs)\n    return ProtectedAdminView",
    "docstring": "Factory for creating protected admin view classes.\n\n    The factory will ensure that the admin view will check if a user is\n    authenticated and has the necessary permissions (as defined by the\n    permission factory).\n    The factory creates a new class using the provided class as base class\n    and overwrites ``is_accessible()`` and ``inaccessible_callback()``\n    methods. Super is called for both methods, so the base class can implement\n    further restrictions if needed.\n\n    :param base_class: Class to use as base class.\n    :type base_class: :class:`flask_admin.base.BaseView`\n    :returns: Admin view class which provides authentication and authorization."
  },
  {
    "code": "def sanitize_type(raw_type):\n    cleaned = get_printable(raw_type).strip()\n    for bad in [\n            r'__drv_aliasesMem', r'__drv_freesMem',\n            r'__drv_strictTypeMatch\\(\\w+\\)',\n            r'__out_data_source\\(\\w+\\)',\n            r'_In_NLS_string_\\(\\w+\\)',\n            r'_Frees_ptr_', r'_Frees_ptr_opt_', r'opt_',\n            r'\\(Mem\\) '\n    ]:\n        cleaned = re.sub(bad, '', cleaned).strip()\n    if cleaned in ['_EXCEPTION_RECORD *', '_EXCEPTION_POINTERS *']:\n        cleaned = cleaned.strip('_')\n    cleaned = cleaned.replace('[]', '*')\n    return cleaned",
    "docstring": "Sanitize the raw type string."
  },
  {
    "code": "def flatpages_link_list(request):\n    from django.contrib.flatpages.models import FlatPage\n    link_list = [(page.title, page.url) for page in FlatPage.objects.all()]\n    return render_to_link_list(link_list)",
    "docstring": "Returns a HttpResponse whose content is a Javascript file representing a\n    list of links to flatpages."
  },
  {
    "code": "def parse(self, text):\n        self._parsed_list = []\n        self._most_recent_report = []\n        self._token_list = text.lower().split()\n        modifier_index_list = []\n        for item in self._token_list:\n            if(self._is_token_data_callback(item)):\n                self._parsed_list.append(self._clean_data_callback(item))\n            if item in self._tasks:\n                d = {}\n                d['context'] = self._tasks[item]['context']\n                d['rule'] = self._tasks[item]['rule']\n                d['task'] = item\n                self._parsed_list.append(d)\n            if item in self._modifiers:\n                modifier_index_list.append((len(self._parsed_list), item))\n        self._apply_modifiers(modifier_index_list)\n        return self._evaluate()",
    "docstring": "Parse the string `text` and return a tuple of left over Data fields.\n\n        Parameters\n        ----------\n        text : str\n            A string to be parsed\n\n        Returns\n        -------\n        result : tuple\n            A tuple of left over Data after processing"
  },
  {
    "code": "def _update_index_on_df(df, index_names):\n    if index_names:\n        df = df.set_index(index_names)\n        index_names = _denormalize_index_names(index_names)\n        df.index.names = index_names\n    return df",
    "docstring": "Helper function to restore index information after collection. Doesn't\n    use self so we can serialize this."
  },
  {
    "code": "def configure_logger(name, log_stream=sys.stdout, log_file=None,\n                     log_level=logging.INFO, keep_old_handlers=False,\n                     propagate=False):\n    logger = logging.getLogger(name)\n    logger.setLevel(log_level)\n    logger.propagate = propagate\n    if not keep_old_handlers:\n        logger.handlers = []\n    log_fmt = '[%(asctime)s] %(levelname)s: %(message)s'\n    log_datefmt = '%Y-%m-%d %H:%M:%S'\n    formatter = logging.Formatter(log_fmt, log_datefmt)\n    if log_stream is not None:\n        stream_handler = logging.StreamHandler(log_stream)\n        stream_handler.setFormatter(formatter)\n        logger.addHandler(stream_handler)\n    if log_file is not None:\n        file_handler = logging.FileHandler(log_file)\n        file_handler.setFormatter(formatter)\n        logger.addHandler(file_handler)\n    if log_stream is None and log_file is None:\n        logger.addHandler(logging.NullHandler())\n    return logger",
    "docstring": "Configures and returns a logger.\n\n    This function serves to simplify the configuration of a logger that\n    writes to a file and/or to a stream (e.g., stdout).\n\n    Parameters\n    ----------\n    name: str\n        The name of the logger. Typically set to ``__name__``.\n    log_stream: a stream object, optional\n        The stream to write log messages to. If ``None``, do not write to any\n        stream. The default value is `sys.stdout`.\n    log_file: str, optional\n        The path of a file to write log messages to. If None, do not write to\n        any file. The default value is ``None``.\n    log_level: int, optional\n        A logging level as `defined`__ in Python's logging module. The default\n        value is `logging.INFO`.\n    keep_old_handlers: bool, optional\n        If set to ``True``, keep any pre-existing handlers that are attached to\n        the logger. The default value is ``False``.\n    propagate: bool, optional\n        If set to ``True``, propagate the loggers messages to the parent\n        logger. The default value is ``False``.\n\n    Returns\n    -------\n    `logging.Logger`\n        The logger.\n\n    Notes\n    -----\n    Note that if ``log_stream`` and ``log_file`` are both ``None``, no handlers\n    will be created.\n\n    __ loglvl_\n\n    .. _loglvl: https://docs.python.org/2/library/logging.html#logging-levels"
  },
  {
    "code": "def feed(self, url_template, keyword, offset, max_num, page_step):\n        for i in range(offset, offset + max_num, page_step):\n            url = url_template.format(keyword, i)\n            self.out_queue.put(url)\n            self.logger.debug('put url to url_queue: {}'.format(url))",
    "docstring": "Feed urls once\n\n        Args:\n            url_template: A string with parameters replaced with \"{}\".\n            keyword: A string indicating the searching keyword.\n            offset: An integer indicating the starting index.\n            max_num: An integer indicating the max number of images to be crawled.\n            page_step: An integer added to offset after each iteration."
  },
  {
    "code": "def playstate(state):\n    if state is None:\n        return const.PLAY_STATE_NO_MEDIA\n    if state == 0:\n        return const.PLAY_STATE_IDLE\n    if state == 1:\n        return const.PLAY_STATE_LOADING\n    if state == 3:\n        return const.PLAY_STATE_PAUSED\n    if state == 4:\n        return const.PLAY_STATE_PLAYING\n    if state == 5:\n        return const.PLAY_STATE_FAST_FORWARD\n    if state == 6:\n        return const.PLAY_STATE_FAST_BACKWARD\n    raise exceptions.UnknownPlayState('Unknown playstate: ' + str(state))",
    "docstring": "Convert iTunes playstate to API representation."
  },
  {
    "code": "def std_byte(self):\n        try:\n            return self.std_name[self.pos]\n        except IndexError:\n            self.failed = 1\n            return ord('?')",
    "docstring": "Copy byte from 8-bit representation."
  },
  {
    "code": "def get_cache_item(self):\n        if settings.DEBUG:\n            raise AttributeError('Caching disabled in DEBUG mode')\n        return getattr(self.template, self.options['template_cache_key'])",
    "docstring": "Gets the cached item. Raises AttributeError if it hasn't been set."
  },
  {
    "code": "def pixel_to_q(self, row: float, column: float):\n        qrow = 4 * np.pi * np.sin(\n            0.5 * np.arctan(\n                (row - float(self.header.beamcentery)) *\n                float(self.header.pixelsizey) /\n                float(self.header.distance))) / float(self.header.wavelength)\n        qcol = 4 * np.pi * np.sin(0.5 * np.arctan(\n                (column - float(self.header.beamcenterx)) *\n                float(self.header.pixelsizex) /\n                float(self.header.distance))) / float(self.header.wavelength)\n        return qrow, qcol",
    "docstring": "Return the q coordinates of a given pixel.\n\n        Inputs:\n            row: float\n                the row (vertical) coordinate of the pixel\n            column: float\n                the column (horizontal) coordinate of the pixel\n\n        Coordinates are 0-based and calculated from the top left corner."
  },
  {
    "code": "def set_bucket_props(self, bucket, props):\n        if not self.pb_all_bucket_props():\n            for key in props:\n                if key not in ('n_val', 'allow_mult'):\n                    raise NotImplementedError('Server only supports n_val and '\n                                              'allow_mult properties over PBC')\n        msg_code = riak.pb.messages.MSG_CODE_SET_BUCKET_REQ\n        codec = self._get_codec(msg_code)\n        msg = codec.encode_set_bucket_props(bucket, props)\n        resp_code, resp = self._request(msg, codec)\n        return True",
    "docstring": "Serialize set bucket property request and deserialize response"
  },
  {
    "code": "def get_autoflow(cls, obj, name):\n        if not isinstance(name, str):\n            raise ValueError('Name must be string.')\n        prefix = cls.__autoflow_prefix__\n        autoflow_name = prefix + name\n        store = misc.get_attribute(obj, autoflow_name, allow_fail=True, default={})\n        if not store:\n            setattr(obj, autoflow_name, store)\n        return store",
    "docstring": "Extracts from an object existing dictionary with tensors specified by name.\n        If there is no such object then new one will be created. Intenally, it appends\n        autoflow prefix to the name and saves it as an attribute.\n\n        :param obj: target GPflow object.\n        :param name: unique part of autoflow attribute's name.\n\n        :raises: ValueError exception if `name` is not a string."
  },
  {
    "code": "def update_fw(self, nids, fw_type, fw_ver, fw_path=None):\n        fw_bin = None\n        if fw_path:\n            fw_bin = load_fw(fw_path)\n            if not fw_bin:\n                return\n        self.ota.make_update(nids, fw_type, fw_ver, fw_bin)",
    "docstring": "Update firwmare of all node_ids in nids."
  },
  {
    "code": "def ok(self, event=None):\n        if not self.check_input():\n            self.initial_focus.focus_set()\n            return\n        self.withdraw()\n        self.update_idletasks()\n        try:\n            self.execute()\n        finally:\n            self.cancel()",
    "docstring": "Function called when OK-button is clicked.\n\n        This method calls check_input(), and if that returns ok it calls\n        execute(), and then destroys the dialog."
  },
  {
    "code": "def super_basis(self):\n        labels_ops = [(bnl + \"^T (x) \" + bml, qt.sprepost(bm, bn)) for (bnl, bn), (bml, bm) in\n                      itertools.product(self, self)]\n        return OperatorBasis(labels_ops)",
    "docstring": "Generate the superoperator basis in which the Choi matrix can be represented.\n\n        The follows the definition in\n        `Chow et al. <https://doi.org/10.1103/PhysRevLett.109.060501>`_\n\n\n        :return (OperatorBasis): The super basis as an OperatorBasis object."
  },
  {
    "code": "def cast(self, topic, value):\n        datatype_key = topic.meta.get('datatype', 'none')\n        result = self._datatypes[datatype_key].cast(topic, value)\n        validate_dt = topic.meta.get('validate', None)\n        if validate_dt:\n            result = self._datatypes[validate_dt].cast(topic, result)\n        return result",
    "docstring": "Cast a string to the value based on the datatype"
  },
  {
    "code": "def delete_widget(self, index):\n        widgets = self.widgets()\n        if len(widgets) == 0:\n            raise ValueError(\"This customization has no widgets\")\n        widgets.pop(index)\n        self._save_customization(widgets)",
    "docstring": "Delete widgets by index.\n\n        The widgets are saved to KE-chain.\n\n        :param index: The index of the widget to be deleted in the self.widgets\n        :type index: int\n        :raises ValueError: if the customization has no widgets"
  },
  {
    "code": "def backup(self):\n        try:\n            self.backup_df = self.df.copy()\n        except Exception as e:\n            self.err(e, \"Can not backup data\")\n            return\n        self.ok(\"Dataframe backed up\")",
    "docstring": "Backup the main dataframe"
  },
  {
    "code": "def fair_max(x):\n    value = max(x)\n    i = [x.index(v) for v in x if v == value]\n    idx = random.choice(i)\n    return idx, value",
    "docstring": "Takes a single iterable as an argument and returns the same output as\n    the built-in function max with two output parameters, except that where\n    the maximum value occurs at more than one position in the  vector, the\n    index is chosen randomly from these positions as opposed to just choosing\n    the first occurance."
  },
  {
    "code": "def most_similar_cosmul(positive: List[str], negative: List[str]):\n    return _MODEL.most_similar_cosmul(positive=positive, negative=negative)",
    "docstring": "Word arithmetic operations\n    If a word is not in the vocabulary, KeyError will be raised.\n\n    :param list positive: a list of words to add\n    :param list negative: a list of words to substract\n\n    :return: the cosine similarity between the two word vectors"
  },
  {
    "code": "def _make_image_predict_fn(self, labels, instance, column_to_explain):\n        def _predict_fn(perturbed_image):\n            predict_input = []\n            for x in perturbed_image:\n                instance_copy = dict(instance)\n                instance_copy[column_to_explain] = Image.fromarray(x)\n                predict_input.append(instance_copy)\n            df = _local_predict.get_prediction_results(\n                self._model_dir, predict_input, self._headers,\n                img_cols=self._image_columns, with_source=False)\n            probs = _local_predict.get_probs_for_labels(labels, df)\n            return np.asarray(probs)\n        return _predict_fn",
    "docstring": "Create a predict_fn that can be used by LIME image explainer."
  },
  {
    "code": "def _find_new_forms(self, forms, num, data, files, locale, tz):\n        fullname = self._get_fullname(num)\n        while has_data(data, fullname) or has_data(files, fullname):\n            f = self._form_class(\n                data, files=files, locale=locale, tz=tz,\n                prefix=fullname, backref=self._backref\n            )\n            forms.append(f)\n            num += 1\n            fullname = self._get_fullname(num)\n        return forms",
    "docstring": "Acknowledge new forms created client-side."
  },
  {
    "code": "def check_solution(solution, signal, ab, msrc, mrec):\n    r\n    if solution not in ['fs', 'dfs', 'dhs', 'dsplit', 'dtetm']:\n        print(\"* ERROR   :: Solution must be one of ['fs', 'dfs', 'dhs', \" +\n              \"'dsplit', 'dtetm']; <solution> provided: \" + solution)\n        raise ValueError('solution')\n    if solution[0] == 'd' and (msrc or mrec):\n        print('* ERROR   :: Diffusive solution is only implemented for ' +\n              'electric sources and electric receivers, <ab> provided: ' +\n              str(ab))\n        raise ValueError('ab')\n    if solution == 'fs' and signal is not None:\n        print('* ERROR   :: Full fullspace solution is only implemented for ' +\n              'the frequency domain, <signal> provided: ' + str(signal))\n        raise ValueError('signal')",
    "docstring": "r\"\"\"Check required solution with parameters.\n\n    This check-function is called from one of the modelling routines in\n    :mod:`model`. Consult these modelling routines for a detailed description\n    of the input parameters.\n\n    Parameters\n    ----------\n    solution : str\n        String to define analytical solution.\n\n    signal : {None, 0, 1, -1}\n        Source signal:\n            - None: Frequency-domain response\n            - -1 : Switch-off time-domain response\n            - 0 : Impulse time-domain response\n            - +1 : Switch-on time-domain response\n\n    msrc, mrec : bool\n        True if src/rec is magnetic, else False."
  },
  {
    "code": "def master_key_from_seed(seed):\n        S = get_bytes(seed)\n        I = hmac.new(b\"Bitcoin seed\", S, hashlib.sha512).digest()\n        Il, Ir = I[:32], I[32:]\n        parse_Il = int.from_bytes(Il, 'big')\n        if parse_Il == 0 or parse_Il >= bitcoin_curve.n:\n            raise ValueError(\"Bad seed, resulting in invalid key!\")\n        return HDPrivateKey(key=parse_Il, chain_code=Ir, index=0, depth=0)",
    "docstring": "Generates a master key from a provided seed.\n\n        Args:\n            seed (bytes or str): a string of bytes or a hex string\n\n        Returns:\n            HDPrivateKey: the master private key."
  },
  {
    "code": "def poll(self, timeout=None):\n        if not isinstance(timeout, (int, float, type(None))):\n            raise TypeError(\"Invalid timeout type, should be integer, float, or None.\")\n        p = select.epoll()\n        p.register(self._fd, select.EPOLLIN | select.EPOLLET | select.EPOLLPRI)\n        for _ in range(2):\n            events = p.poll(timeout)\n        if events:\n            try:\n                os.lseek(self._fd, 0, os.SEEK_SET)\n            except OSError as e:\n                raise GPIOError(e.errno, \"Rewinding GPIO: \" + e.strerror)\n            return True\n        return False",
    "docstring": "Poll a GPIO for the edge event configured with the .edge property.\n\n        `timeout` can be a positive number for a timeout in seconds, 0 for a\n        non-blocking poll, or negative or None for a blocking poll. Defaults to\n        blocking poll.\n\n        Args:\n            timeout (int, float, None): timeout duration in seconds.\n\n        Returns:\n            bool: ``True`` if an edge event occurred, ``False`` on timeout.\n\n        Raises:\n            GPIOError: if an I/O or OS error occurs.\n            TypeError: if `timeout` type is not None or int."
  },
  {
    "code": "def get_primitive_name(schema):\n    try:\n        return {\n            const.COMPILED_TYPE.LITERAL: six.text_type,\n            const.COMPILED_TYPE.TYPE: get_type_name,\n            const.COMPILED_TYPE.ENUM: get_type_name,\n            const.COMPILED_TYPE.CALLABLE: get_callable_name,\n            const.COMPILED_TYPE.ITERABLE: lambda x: _(u'{type}[{content}]').format(type=get_type_name(list), content=_(u'...') if x else _(u'-')),\n            const.COMPILED_TYPE.MAPPING:  lambda x: _(u'{type}[{content}]').format(type=get_type_name(dict), content=_(u'...') if x else _(u'-')),\n        }[primitive_type(schema)](schema)\n    except KeyError:\n        return six.text_type(repr(schema))",
    "docstring": "Get a human-friendly name for the given primitive.\n\n    :param schema: Schema\n    :type schema: *\n    :rtype: unicode"
  },
  {
    "code": "def create_thumbnail(uuid, thumbnail_width):\n    size = thumbnail_width + ','\n    thumbnail = IIIFImageAPI.get('v2', uuid, size, 0, 'default', 'jpg')",
    "docstring": "Create the thumbnail for an image."
  },
  {
    "code": "def del_unused_keyframes(self):\n        skl = self.key_frame_list.sorted_key_list()\n        unused_keys = [k for k in self.dct['keys']\n                       if k not in skl]\n        for k in unused_keys:\n            del self.dct['keys'][k]",
    "docstring": "Scans through list of keyframes in the channel and removes those\n        which are not in self.key_frame_list."
  },
  {
    "code": "def get_targets(self):\n        if self.xml_root.tag == \"testcases\":\n            self.submit_target = self.config.get(\"testcase_taget\")\n            self.queue_url = self.config.get(\"testcase_queue\")\n            self.log_url = self.config.get(\"testcase_log\")\n        elif self.xml_root.tag == \"testsuites\":\n            self.submit_target = self.config.get(\"xunit_target\")\n            self.queue_url = self.config.get(\"xunit_queue\")\n            self.log_url = self.config.get(\"xunit_log\")\n        elif self.xml_root.tag == \"requirements\":\n            self.submit_target = self.config.get(\"requirement_target\")\n            self.queue_url = self.config.get(\"requirement_queue\")\n            self.log_url = self.config.get(\"requirement_log\")\n        else:\n            raise Dump2PolarionException(\"Failed to submit to Polarion - submit target not found\")",
    "docstring": "Sets targets."
  },
  {
    "code": "def change_last_time_step(self, **replace_time_step_kwargs):\n    assert self._time_steps\n    self._time_steps[-1] = self._time_steps[-1].replace(\n        **replace_time_step_kwargs)",
    "docstring": "Replace the last time-steps with the given kwargs."
  },
  {
    "code": "def _get_setting(self, key, default_value=None, value_type=str):\n        try:\n            state_entry = self._state_view.get(\n                SettingsView.setting_address(key))\n        except KeyError:\n            return default_value\n        if state_entry is not None:\n            setting = Setting()\n            setting.ParseFromString(state_entry)\n            for setting_entry in setting.entries:\n                if setting_entry.key == key:\n                    return value_type(setting_entry.value)\n        return default_value",
    "docstring": "Get the setting stored at the given key.\n\n        Args:\n            key (str): the setting key\n            default_value (str, optional): The default value, if none is\n                found. Defaults to None.\n            value_type (function, optional): The type of a setting value.\n                Defaults to `str`.\n\n        Returns:\n            str: The value of the setting if found, default_value\n            otherwise."
  },
  {
    "code": "def _wikipedia_known_port_ranges():\n    req = urllib2.Request(WIKIPEDIA_PAGE, headers={'User-Agent' : \"Magic Browser\"})\n    page = urllib2.urlopen(req).read().decode('utf8')\n    ports = re.findall('<td>((\\d+)(\\W(\\d+))?)</td>', page, re.U)\n    return ((int(p[1]), int(p[3] if p[3] else p[1])) for p in ports)",
    "docstring": "Returns used port ranges according to Wikipedia page.\n    This page contains unofficial well-known ports."
  },
  {
    "code": "def fake_keypress(self, key, repeat=1):\n        for _ in range(repeat):\n            self.mediator.fake_keypress(key)",
    "docstring": "Fake a keypress\n\n        Usage: C{keyboard.fake_keypress(key, repeat=1)}\n\n        Uses XTest to 'fake' a keypress. This is useful to send keypresses to some\n        applications which won't respond to keyboard.send_key()\n\n        @param key: they key to be sent (e.g. \"s\" or \"<enter>\")\n        @param repeat: number of times to repeat the key event"
  },
  {
    "code": "def play_alert(zones, alert_uri, alert_volume=20, alert_duration=0, fade_back=False):\n    for zone in zones:\n        zone.snap = Snapshot(zone)\n        zone.snap.snapshot()\n        print('snapshot of zone: {}'.format(zone.player_name))\n    for zone in zones:\n        if zone.is_coordinator:\n            if not zone.is_playing_tv:\n                trans_state = zone.get_current_transport_info()\n                if trans_state['current_transport_state'] == 'PLAYING':\n                    zone.pause()\n        zone.volume = alert_volume\n        zone.mute = False\n    print('will play: {} on all coordinators'.format(alert_uri))\n    for zone in zones:\n        if zone.is_coordinator:\n            zone.play_uri(uri=alert_uri, title='Sonos Alert')\n    time.sleep(alert_duration)\n    for zone in zones:\n        print('restoring {}'.format(zone.player_name))\n        zone.snap.restore(fade=fade_back)",
    "docstring": "Demo function using soco.snapshot across multiple Sonos players.\n\n    Args:\n        zones (set): a set of SoCo objects\n        alert_uri (str): uri that Sonos can play as an alert\n        alert_volume (int): volume level for playing alert (0 tp 100)\n        alert_duration (int): length of alert (if zero then length of track)\n        fade_back (bool): on reinstating the zones fade up the sound?"
  },
  {
    "code": "def selected_hazard_category(self):\n        item = self.lstHazardCategories.currentItem()\n        try:\n            return definition(item.data(QtCore.Qt.UserRole))\n        except (AttributeError, NameError):\n            return None",
    "docstring": "Obtain the hazard category selected by user.\n\n        :returns: Metadata of the selected hazard category.\n        :rtype: dict, None"
  },
  {
    "code": "def coupleTo_vswitch(userid, vswitch_name):\n    print(\"\\nCoupleing to vswitch for %s ...\" % userid)\n    vswitch_info = client.send_request('guest_nic_couple_to_vswitch', \n                                       userid, '1000', vswitch_name)\n    if vswitch_info['overallRC']:\n        raise RuntimeError(\"Failed to couple to vswitch for guest %s!\\n%s\" % \n                           (userid, vswitch_info))\n    else:\n        print(\"Succeeded to couple to vswitch for guest %s!\" % userid)",
    "docstring": "Couple to vswitch.\n\n    Input parameters:\n    :userid:            USERID of the guest, last 8 if length > 8\n    :network_info:      dict of network info"
  },
  {
    "code": "def status(self):\n        if self.request_list.conflict:\n            return SolverStatus.failed\n        if self.callback_return == SolverCallbackReturn.fail:\n            return SolverStatus.failed\n        st = self.phase_stack[-1].status\n        if st == SolverStatus.cyclic:\n            return SolverStatus.failed\n        elif len(self.phase_stack) > 1:\n            if st == SolverStatus.solved:\n                return SolverStatus.solved\n            else:\n                return SolverStatus.unsolved\n        elif st in (SolverStatus.pending, SolverStatus.exhausted):\n            return SolverStatus.unsolved\n        else:\n            return st",
    "docstring": "Return the current status of the solve.\n\n        Returns:\n          SolverStatus: Enum representation of the state of the solver."
  },
  {
    "code": "def _extract_scexe_file(self, target_file, extract_path):\n    unpack_cmd = '--unpack=' + extract_path\n    cmd = [target_file, unpack_cmd]\n    out, err = utils.trycmd(*cmd)",
    "docstring": "Extracts the scexe file.\n\n    :param target_file: the firmware file to be extracted from\n    :param extract_path: the path where extraction is supposed to happen"
  },
  {
    "code": "def detect_and_visualize(self, im_list, root_dir=None, extension=None,\n                             classes=[], thresh=0.6, show_timer=False):\n        dets = self.im_detect(im_list, root_dir, extension, show_timer=show_timer)\n        if not isinstance(im_list, list):\n            im_list = [im_list]\n        assert len(dets) == len(im_list)\n        for k, det in enumerate(dets):\n            img = cv2.imread(im_list[k])\n            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n            self.visualize_detection(img, det, classes, thresh)",
    "docstring": "wrapper for im_detect and visualize_detection\n\n        Parameters:\n        ----------\n        im_list : list of str or str\n            image path or list of image paths\n        root_dir : str or None\n            directory of input images, optional if image path already\n            has full directory information\n        extension : str or None\n            image extension, eg. \".jpg\", optional\n\n        Returns:\n        ----------"
  },
  {
    "code": "def _getbugfields(self):\n        r = self._proxy.Bug.fields({'include_fields': ['name']})\n        return [f['name'] for f in r['fields']]",
    "docstring": "Get the list of valid fields for Bug objects"
  },
  {
    "code": "def get_permissions_app_name():\n    global permissions_app_name\n    if not permissions_app_name:\n        permissions_app_name = getattr(settings, 'PERMISSIONS_APP', None)\n        if not permissions_app_name:\n            app_names_with_models = [a.name for a in apps.get_app_configs() if a.models_module is not None]\n            if app_names_with_models:\n                permissions_app_name = app_names_with_models[-1]\n    return permissions_app_name",
    "docstring": "Gets the app after which smartmin permissions should be installed. This can be specified by PERMISSIONS_APP in the\n    Django settings or defaults to the last app with models"
  },
  {
    "code": "def pprint_blockers(blockers):\n    pprinted = []\n    for blocker in sorted(blockers, key=lambda x: tuple(reversed(x))):\n        buf = [blocker[0]]\n        if len(blocker) > 1:\n            buf.append(' (which is blocking ')\n            buf.append(', which is blocking '.join(blocker[1:]))\n            buf.append(')')\n        pprinted.append(''.join(buf))\n    return pprinted",
    "docstring": "Pretty print blockers into a sequence of strings.\n\n    Results will be sorted by top-level project name. This means that if a\n    project is blocking another project then the dependent project will be\n    what is used in the sorting, not the project at the bottom of the\n    dependency graph."
  },
  {
    "code": "def create_view(operations, operation):\n    operations.execute(\"CREATE VIEW %s AS %s\" % (\n        operation.target.name,\n        operation.target.sqltext\n    ))",
    "docstring": "Implements ``CREATE VIEW``.\n\n    Args:\n        operations: instance of ``alembic.operations.base.Operations``\n        operation: instance of :class:`.ReversibleOp`\n\n    Returns:\n        ``None``"
  },
  {
    "code": "def normalize(self):\n        if not self.subfilters:\n            return None\n        new_filters = []\n        for subfilter in self.subfilters:\n            norm_filter = subfilter.normalize()\n            if norm_filter is not None and norm_filter not in new_filters:\n                new_filters.append(norm_filter)\n        self.subfilters = new_filters\n        size = len(self.subfilters)\n        if size > 1 or self.operator == NOT:\n            return self\n        return self.subfilters[0].normalize()",
    "docstring": "Returns the first meaningful object in this filter."
  },
  {
    "code": "def get(self, **kwargs):\n        url = '%s/%s' % (self.base_url, kwargs['notification_id'])\n        resp = self.client.list(path=url)\n        return resp",
    "docstring": "Get the details for a specific notification."
  },
  {
    "code": "def login(self, username, password):\n        response = self.request(\n            ACCESS_TOKEN,\n            {\n                'x_auth_mode': 'client_auth',\n                'x_auth_username': username,\n                'x_auth_password': password\n            },\n            returns_json=False\n        )\n        token = dict(parse_qsl(response['data'].decode()))\n        self.token = oauth.Token(\n            token['oauth_token'], token['oauth_token_secret'])\n        self.oauth_client = oauth.Client(self.consumer, self.token)",
    "docstring": "Authenticate using XAuth variant of OAuth.\n\n        :param str username: Username or email address for the relevant account\n        :param str password: Password for the account"
  },
  {
    "code": "def max(self, key=None):\n        if key is None:\n            return self.reduce(max)\n        return self.reduce(lambda a, b: max(a, b, key=key))",
    "docstring": "Find the maximum item in this RDD.\n\n        :param key: A function used to generate key for comparing\n\n        >>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0])\n        >>> rdd.max()\n        43.0\n        >>> rdd.max(key=str)\n        5.0"
  },
  {
    "code": "def error_keys_not_found(self, keys):\n        try:\n            log.error(\"Filename: {0}\".format(self['meta']['location']))\n        except:\n            log.error(\"Filename: {0}\".format(self['location']))\n        log.error(\"Key '{0}' does not exist\".format('.'.join(keys)))\n        indent = \"\"\n        last_index = len(keys) - 1\n        for i, k in enumerate(keys):\n            if i == last_index:\n                log.error(indent + k + \": <- this value is missing\")\n            else:\n                log.error(indent + k + \":\")\n            indent += \"    \"",
    "docstring": "Check if the requested keys are found in the dict.\n\n        :param keys: keys to be looked for"
  },
  {
    "code": "def apply(patch):\n    settings = Settings() if patch.settings is None else patch.settings\n    try:\n        target = get_attribute(patch.destination, patch.name)\n    except AttributeError:\n        pass\n    else:\n        if not settings.allow_hit:\n            raise RuntimeError(\n                \"An attribute named '%s' already exists at the destination \"\n                \"'%s'. Set a different name through the patch object to avoid \"\n                \"a name clash or set the setting 'allow_hit' to True to \"\n                \"overwrite the attribute. In the latter case, it is \"\n                \"recommended to also set the 'store_hit' setting to True in \"\n                \"order to store the original attribute under a different \"\n                \"name so it can still be accessed.\"\n                % (patch.name, patch.destination.__name__))\n        if settings.store_hit:\n            original_name = _ORIGINAL_NAME % (patch.name,)\n            if not hasattr(patch.destination, original_name):\n                setattr(patch.destination, original_name, target)\n    setattr(patch.destination, patch.name, patch.obj)",
    "docstring": "Apply a patch.\n\n    The patch's :attr:`~Patch.obj` attribute is injected into the patch's\n    :attr:`~Patch.destination` under the patch's :attr:`~Patch.name`.\n\n    This is a wrapper around calling\n    ``setattr(patch.destination, patch.name, patch.obj)``.\n\n    Parameters\n    ----------\n    patch : gorilla.Patch\n        Patch.\n\n    Raises\n    ------\n    RuntimeError\n        Overwriting an existing attribute is not allowed when the setting\n        :attr:`Settings.allow_hit` is set to ``True``.\n\n    Note\n    ----\n    If both the attributes :attr:`Settings.allow_hit` and\n    :attr:`Settings.store_hit` are ``True`` but that the target attribute seems\n    to have already been stored, then it won't be stored again to avoid losing\n    the original attribute that was stored the first time around."
  },
  {
    "code": "def write(self, fptr):\n        self._validate(writing=True)\n        self._write_superbox(fptr, b'ftbl')",
    "docstring": "Write a fragment table box to file."
  },
  {
    "code": "def attach_volume(node_id, volume_id, profile, device=None, **libcloud_kwargs):\n    conn = _get_driver(profile=profile)\n    libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs)\n    volume = _get_by_id(conn.list_volumes(), volume_id)\n    node = _get_by_id(conn.list_nodes(), node_id)\n    return conn.attach_volume(node, volume, device=device, **libcloud_kwargs)",
    "docstring": "Attaches volume to node.\n\n    :param node_id:  Node ID to target\n    :type  node_id: ``str``\n\n    :param volume_id:  Volume ID from which to attach\n    :type  volume_id: ``str``\n\n    :param profile: The profile key\n    :type  profile: ``str``\n\n    :param device: Where the device is exposed, e.g. '/dev/sdb'\n    :type device: ``str``\n\n    :param libcloud_kwargs: Extra arguments for the driver's attach_volume method\n    :type  libcloud_kwargs: ``dict``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion libcloud_compute.detach_volume vol1 profile1"
  },
  {
    "code": "def subn_filter(s, find, replace, count=0):\n    return re.gsub(find, replace, count, s)",
    "docstring": "A non-optimal implementation of a regex filter"
  },
  {
    "code": "def tokenizer(self):\n        domain = 0\n        if domain not in self.domains:\n            self.register_domain(domain=domain)\n        return self.domains[domain].tokenizer",
    "docstring": "A property to link into IntentEngine's tokenizer.\n\n        Warning: this is only for backwards compatiblility and should not be used if you\n            intend on using domains.\n\n        Return: the domains tokenizer from its IntentEngine"
  },
  {
    "code": "def update_redirect(self):\n        if self.last_child:\n            self._resolved_pid.redirect(self.last_child)\n        elif any(map(lambda pid: pid.status not in [PIDStatus.DELETED,\n                                                    PIDStatus.REGISTERED,\n                                                    PIDStatus.RESERVED],\n                     super(PIDNodeVersioning, self).children.all())):\n            raise PIDRelationConsistencyError(\n                \"Invalid relation state. Only REGISTERED, RESERVED \"\n                \"and DELETED PIDs are supported.\"\n            )",
    "docstring": "Update the parent redirect to the current last child.\n\n        This method should be called on the parent PID node.\n\n        Use this method when the status of a PID changed (ex: draft changed\n        from RESERVED to REGISTERED)"
  },
  {
    "code": "def ReadItems(self, collection_link, feed_options=None):\n        if feed_options is None:\n            feed_options = {}\n        return self.QueryItems(collection_link, None, feed_options)",
    "docstring": "Reads all documents in a collection.\n\n        :param str collection_link:\n            The link to the document collection.\n        :param dict feed_options:\n\n        :return:\n            Query Iterable of Documents.\n        :rtype:\n            query_iterable.QueryIterable"
  },
  {
    "code": "def object(self, key):\n    return _object.Object(self._name, key, context=self._context)",
    "docstring": "Retrieves a Storage Object for the specified key in this bucket.\n\n    The object need not exist.\n\n    Args:\n      key: the key of the object within the bucket.\n    Returns:\n      An Object instance representing the specified key."
  },
  {
    "code": "def _get_distance_term(self, C, rrup, backarc):\n        distance_scale = -np.log10(np.sqrt(rrup ** 2 + 3600.0))\n        distance_scale[backarc] += (C[\"c2\"] * rrup[backarc])\n        idx = np.logical_not(backarc)\n        distance_scale[idx] += (C[\"c1\"] * rrup[idx])\n        return distance_scale",
    "docstring": "Returns the distance scaling term, which varies depending on whether\n        the site is in the forearc or the backarc"
  },
  {
    "code": "def appendContour(self, contour, offset=None):\n        contour = normalizers.normalizeContour(contour)\n        if offset is None:\n            offset = (0, 0)\n        offset = normalizers.normalizeTransformationOffset(offset)\n        return self._appendContour(contour, offset)",
    "docstring": "Append a contour containing the same data as ``contour``\n        to this glyph.\n\n            >>> contour = glyph.appendContour(contour)\n\n        This will return a :class:`BaseContour` object representing\n        the new contour in the glyph. ``offset`` indicates the x and\n        y shift values that should be applied to the appended data.\n        It must be a :ref:`type-coordinate` value or ``None``. If\n        ``None`` is given, the offset will be ``(0, 0)``.\n\n            >>> contour = glyph.appendContour(contour, (100, 0))"
  },
  {
    "code": "def delete_dataset(self, dataset):\n        uri = URITemplate(self.baseuri + '/{owner}/{id}').expand(\n            owner=self.username, id=dataset)\n        return self.session.delete(uri)",
    "docstring": "Deletes a single dataset, including all of the features that it contains.\n\n        Parameters\n        ----------\n        dataset : str\n            The dataset id.\n\n        Returns\n        -------\n        HTTP status code."
  },
  {
    "code": "def is_equal(self, another, limit=0.8):\n        if another is None:\n            raise Exception(\"Parameter another is null\")\n        if isinstance(another, int):\n            distance = self.hamming_distance(another)\n        elif isinstance(another, Simhash):\n            assert self.hash_bit_number == another.hash_bit_number\n            distance = self.hamming_distance(another.hash)\n        else:\n            raise Exception(\"Unsupported parameter type %s\" % type(another))\n        similarity = float(self.hash_bit_number - distance) / self.hash_bit_number\n        if similarity > limit:\n            return True\n        return False",
    "docstring": "Determine two simhash are similar or not similar.\n\n        :param another: another simhash.\n        :param limit: a limit of the similarity.\n        :return: if similarity greater than limit return true and else return false."
  },
  {
    "code": "def exit(self):\n        if self.nvml_ready:\n            try:\n                pynvml.nvmlShutdown()\n            except Exception as e:\n                logger.debug(\"pynvml failed to shutdown correctly ({})\".format(e))\n        super(Plugin, self).exit()",
    "docstring": "Overwrite the exit method to close the GPU API."
  },
  {
    "code": "def _translate_limit(self, len_, start, num):\n        if start > len_ or num <= 0:\n            return 0, 0\n        return min(start, len_), num",
    "docstring": "Translate limit to valid bounds."
  },
  {
    "code": "def get_remote_executors(hub_ip, port = 4444):\r\n        resp = requests.get(\"http://%s:%s/grid/console\" %(hub_ip, port))\r\n        remote_hosts = ()\r\n        if resp.status_code == 200:\r\n            remote_hosts = re.findall(\"remoteHost: ([\\w/\\.:]+)\",resp.text)\r\n        return [host + \"/wd/hub\" for host in remote_hosts]",
    "docstring": "Get remote hosts from Selenium Grid Hub Console\r\n        @param hub_ip: hub ip of selenium grid hub\r\n        @param port: hub port of selenium grid hub"
  },
  {
    "code": "def set_quality_index(self):\n        window_start = self.parent.value('window_start')\n        window_length = self.parent.value('window_length')\n        qual = self.annot.get_stage_for_epoch(window_start, window_length,\n                                              attr='quality')\n        if qual is None:\n            self.idx_quality.setCurrentIndex(-1)\n        else:\n            self.idx_quality.setCurrentIndex(QUALIFIERS.index(qual))",
    "docstring": "Set the current signal quality in combobox."
  },
  {
    "code": "def send_slack_message(channel, text):\n    http = httplib2.Http()\n    return http.request(SLACK_MESSAGE_URL, 'POST', body=json.dumps({\n        'channel': channel,\n        'text': text,\n    }))",
    "docstring": "Send a message to Slack"
  },
  {
    "code": "def make_datastore_api(client):\n    parse_result = six.moves.urllib_parse.urlparse(client._base_url)\n    host = parse_result.netloc\n    if parse_result.scheme == \"https\":\n        channel = make_secure_channel(client._credentials, DEFAULT_USER_AGENT, host)\n    else:\n        channel = insecure_channel(host)\n    return datastore_client.DatastoreClient(\n        channel=channel,\n        client_info=client_info.ClientInfo(\n            client_library_version=__version__, gapic_version=__version__\n        ),\n    )",
    "docstring": "Create an instance of the GAPIC Datastore API.\n\n    :type client: :class:`~google.cloud.datastore.client.Client`\n    :param client: The client that holds configuration details.\n\n    :rtype: :class:`.datastore.v1.datastore_client.DatastoreClient`\n    :returns: A datastore API instance with the proper credentials."
  },
  {
    "code": "def get_all_keys(self):\n        all_keys = []\n        for keys in self._index.values():\n            all_keys.extend(keys)\n        return all_keys",
    "docstring": "Get all keys indexed.\n\n        :return: All keys\n        :rtype: list(str)"
  },
  {
    "code": "def get_service_uid_from(self, analysis):\n        analysis = api.get_object(analysis)\n        return api.get_uid(analysis.getAnalysisService())",
    "docstring": "Return the service from the analysis"
  },
  {
    "code": "def table(self, name=DEFAULT_TABLE, **options):\n        if name in self._table_cache:\n            return self._table_cache[name]\n        table_class = options.pop('table_class', self._cls_table)\n        table = table_class(self._cls_storage_proxy(self._storage, name), name, **options)\n        self._table_cache[name] = table\n        return table",
    "docstring": "Get access to a specific table.\n\n        Creates a new table, if it hasn't been created before, otherwise it\n        returns the cached :class:`~tinydb.Table` object.\n\n        :param name: The name of the table.\n        :type name: str\n        :param cache_size: How many query results to cache.\n        :param table_class: Which table class to use."
  },
  {
    "code": "def search(self, title=None, libtype=None, **kwargs):\n        args = {}\n        if title:\n            args['title'] = title\n        if libtype:\n            args['type'] = utils.searchType(libtype)\n        for attr, value in kwargs.items():\n            args[attr] = value\n        key = '/library/all%s' % utils.joinArgs(args)\n        return self.fetchItems(key)",
    "docstring": "Searching within a library section is much more powerful. It seems certain\n            attributes on the media objects can be targeted to filter this search down\n            a bit, but I havent found the documentation for it.\n\n            Example: \"studio=Comedy%20Central\" or \"year=1999\" \"title=Kung Fu\" all work. Other items\n            such as actor=<id> seem to work, but require you already know the id of the actor.\n            TLDR: This is untested but seems to work. Use library section search when you can."
  },
  {
    "code": "def get_all_netting_channel_events(\n        chain: BlockChainService,\n        token_network_address: TokenNetworkAddress,\n        netting_channel_identifier: ChannelID,\n        contract_manager: ContractManager,\n        from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,\n        to_block: BlockSpecification = 'latest',\n) -> List[Dict]:\n    filter_args = get_filter_args_for_all_events_from_channel(\n        token_network_address=token_network_address,\n        channel_identifier=netting_channel_identifier,\n        contract_manager=contract_manager,\n        from_block=from_block,\n        to_block=to_block,\n    )\n    return get_contract_events(\n        chain,\n        contract_manager.get_contract_abi(CONTRACT_TOKEN_NETWORK),\n        typing.Address(token_network_address),\n        filter_args['topics'],\n        from_block,\n        to_block,\n    )",
    "docstring": "Helper to get all events of a NettingChannelContract."
  },
  {
    "code": "def _and_join(self, close_group=False):\n        if not self.initialized:\n            raise ValueError(\"You must add a search term before adding an operator.\")\n        else:\n            self._operator(\"AND\", close_group=close_group)\n        return self",
    "docstring": "Combine terms with AND.\n        There must be a term added before using this method.\n\n        Arguments:\n            close_group (bool): If ``True``, will end the current group and start a new one.\n                    If ``False``, will continue current group.\n\n                    Example::\n\n                        If the current query is \"(term1\"\n                        .and(close_group=True) => \"(term1) AND (\"\n                        .and(close_group=False) => \"(term1 AND \"\n\n        Returns:\n            SearchHelper: Self"
  },
  {
    "code": "def copy_model_instance(obj):\n    meta = getattr(obj, '_meta')\n    return {f.name: getattr(obj, f.name)\n            for f in meta.get_fields(include_parents=False)\n            if not f.auto_created}",
    "docstring": "Copy Django model instance as a dictionary excluding automatically created\n    fields like an auto-generated sequence as a primary key or an auto-created\n    many-to-one reverse relation.\n\n    :param obj: Django model object\n    :return: copy of model instance as dictionary"
  },
  {
    "code": "def listen(manifest, config, model_mock=False):\n    config['manifest'] = manifest\n    config['model_mock'] = model_mock\n    IRC = IrcBot(config)\n    try:\n        IRC.start()\n    except KeyboardInterrupt:\n        pass",
    "docstring": "IRC listening process."
  },
  {
    "code": "def _fix_syscall_ip(state):\n        try:\n            bypass = o.BYPASS_UNSUPPORTED_SYSCALL in state.options\n            stub = state.project.simos.syscall(state, allow_unsupported=bypass)\n            if stub:\n                state.ip = stub.addr\n        except AngrUnsupportedSyscallError:\n            pass",
    "docstring": "Resolve syscall information from the state, get the IP address of the syscall SimProcedure, and set the IP of\n        the state accordingly. Don't do anything if the resolution fails.\n\n        :param SimState state: the program state.\n        :return: None"
  },
  {
    "code": "def rolling_count(self, window_start, window_end):\n        agg_op = '__builtin__nonnull__count__'\n        return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, 0))",
    "docstring": "Count the number of non-NULL values of different subsets over this\n        SArray.\n\n        The subset that the count is executed on is defined as an inclusive\n        range relative to the position to each value in the SArray, using\n        `window_start` and `window_end`. For a better understanding of this,\n        see the examples below.\n\n        Parameters\n        ----------\n        window_start : int\n            The start of the subset to count relative to the current value.\n\n        window_end : int\n            The end of the subset to count relative to the current value. Must\n            be greater than `window_start`.\n\n        Returns\n        -------\n        out : SArray\n\n        Examples\n        --------\n        >>> import pandas\n        >>> sa = SArray([1,2,3,None,5])\n        >>> series = pandas.Series([1,2,3,None,5])\n\n        A rolling count with a window including the previous 2 entries including\n        the current:\n        >>> sa.rolling_count(-2,0)\n        dtype: int\n        Rows: 5\n        [1, 2, 3, 2, 2]\n\n        Pandas equivalent:\n        >>> pandas.rolling_count(series, 3)\n        0     1\n        1     2\n        2     3\n        3     2\n        4     2\n        dtype: float64\n\n        A rolling count with a size of 3, centered around the current:\n        >>> sa.rolling_count(-1,1)\n        dtype: int\n        Rows: 5\n        [2, 3, 2, 2, 1]\n\n        Pandas equivalent:\n        >>> pandas.rolling_count(series, 3, center=True)\n        0    2\n        1    3\n        2    2\n        3    2\n        4    1\n        dtype: float64\n\n        A rolling count with a window including the current and the 2 entries\n        following:\n        >>> sa.rolling_count(0,2)\n        dtype: int\n        Rows: 5\n        [3, 2, 2, 1, 1]\n\n        A rolling count with a window including the previous 2 entries NOT\n        including the current:\n        >>> sa.rolling_count(-2,-1)\n        dtype: int\n        Rows: 5\n        [0, 1, 2, 2, 1]"
  },
  {
    "code": "async def _get(self, key: Text) -> Dict[Text, Any]:\n        try:\n            with await self.pool as r:\n                return ujson.loads(await r.get(self.register_key(key)))\n        except (ValueError, TypeError):\n            return {}",
    "docstring": "Get the value for the key. It is automatically deserialized from JSON\n        and returns an empty dictionary by default."
  },
  {
    "code": "def require_int(self, key: str) -> int:\n        v = self.get_int(key)\n        if v is None:\n            raise ConfigMissingError(self.full_key(key))\n        return v",
    "docstring": "Returns a configuration value, as an int, by its given key.  If it doesn't exist, or the\n        configuration value is not a legal int, an error is thrown.\n\n        :param str key: The requested configuration key.\n        :return: The configuration key's value.\n        :rtype: int\n        :raises ConfigMissingError: The configuration value did not exist.\n        :raises ConfigTypeError: The configuration value existed but couldn't be coerced to int."
  },
  {
    "code": "def create(self, port, value, timestamp=None):\n        session = self._session\n        datapoint_class = self._datapoint_class\n        attributes = {\n            'port': port,\n            'value': value,\n        }\n        if timestamp is not None:\n            attributes['timestamp'] = to_iso_date(timestamp)\n        attributes = build_request_body('data-point', None,\n                                        attributes=attributes)\n        def _process(json):\n            data = json.get('data')\n            return datapoint_class(data, session)\n        return session.post(self._base_url, CB.json(201, _process),\n                            json=attributes)",
    "docstring": "Post a new reading to a timeseries.\n\n        A reading is comprised of a `port`, a `value` and a timestamp.\n\n        A port is like a tag for the given reading and gives an\n        indication of the meaning of the value.\n\n        The value of the reading can be any valid json value.\n\n        The timestamp is considered the time the reading was taken, as\n        opposed to the `created` time of the data-point which\n        represents when the data-point was stored in the Helium\n        API. If the timestamp is not given the server will construct a\n        timestemp upon receiving the new reading.\n\n        Args:\n\n            port(string): The port to use for the new data-point\n            value: The value for the new data-point\n\n        Keyword Args:\n\n            timestamp(:class:`datetime`): An optional :class:`datetime` object"
  },
  {
    "code": "def rebuildtable(cls):\n        cls._closure_model.objects.all().delete()\n        cls._closure_model.objects.bulk_create([cls._closure_model(\n            parent_id=x['pk'],\n            child_id=x['pk'],\n            depth=0\n        ) for x in cls.objects.values(\"pk\")])\n        for node in cls.objects.all():\n            node._closure_createlink()",
    "docstring": "Regenerate the entire closuretree."
  },
  {
    "code": "def _create_column(data, col, value):\n    with suppress(AttributeError):\n        if not value.index.equals(data.index):\n            if len(value) == len(data):\n                value.index = data.index\n            else:\n                value.reset_index(drop=True, inplace=True)\n    if data.index.empty:\n        try:\n            len(value)\n        except TypeError:\n            scalar = True\n        else:\n            scalar = isinstance(value, str)\n        if scalar:\n            value = [value]\n    data[col] = value\n    return data",
    "docstring": "Create column in dataframe\n\n    Helper method meant to deal with problematic\n    column values. e.g When the series index does\n    not match that of the data.\n\n    Parameters\n    ----------\n    data : pandas.DataFrame\n        dataframe in which to insert value\n    col : column label\n        Column name\n    value : object\n        Value to assign to column\n\n    Returns\n    -------\n    data : pandas.DataFrame\n        Modified original dataframe\n\n    >>> df = pd.DataFrame({'x': [1, 2, 3]})\n    >>> y = pd.Series([11, 12, 13], index=[21, 22, 23])\n\n    Data index and value index do not match\n\n    >>> _create_column(df, 'y', y)\n       x   y\n    0  1  11\n    1  2  12\n    2  3  13\n\n    Non-empty dataframe, scalar value\n\n    >>> _create_column(df, 'z', 3)\n       x   y  z\n    0  1  11  3\n    1  2  12  3\n    2  3  13  3\n\n    Empty dataframe, scalar value\n\n    >>> df = pd.DataFrame()\n    >>> _create_column(df, 'w', 3)\n       w\n    0  3\n    >>> _create_column(df, 'z', 'abc')\n       w    z\n    0  3  abc"
  },
  {
    "code": "def read_sources_from_numpy_file(npfile):\n    srcs = np.load(npfile).flat[0]['sources']\n    roi = ROIModel()\n    roi.load_sources(srcs.values())\n    return roi.create_table()",
    "docstring": "Open a numpy pickle file and read all the new sources into a dictionary\n\n    Parameters\n    ----------\n    npfile : file name\n       The input numpy pickle file\n\n    Returns\n    -------\n    tab : `~astropy.table.Table`"
  },
  {
    "code": "def windowed_run_count_ufunc(x, window):\n    return xr.apply_ufunc(windowed_run_count_1d,\n                          x,\n                          input_core_dims=[['time'], ],\n                          vectorize=True,\n                          dask='parallelized',\n                          output_dtypes=[np.int, ],\n                          keep_attrs=True,\n                          kwargs={'window': window})",
    "docstring": "Dask-parallel version of windowed_run_count_1d, ie the number of consecutive true values in\n    array for runs at least as long as given duration.\n\n    Parameters\n    ----------\n    x : bool array\n      Input array\n    window : int\n      Minimum duration of consecutive run to accumulate values.\n\n    Returns\n    -------\n    out : func\n      A function operating along the time dimension of a dask-array."
  },
  {
    "code": "def reset_tag(self, name):\n        id_ = str(uuid.uuid4()).replace('-', '')\n        self._store.forever(self.tag_key(name), id_)\n        return id_",
    "docstring": "Reset the tag and return the new tag identifier.\n\n        :param name: The tag\n        :type name: str\n\n        :rtype: str"
  },
  {
    "code": "def remove_boards_gui(hwpack=''):\n    if not hwpack:\n        if len(hwpack_names()) > 1:\n            hwpack = psidialogs.choice(hwpack_names(),\n                                       'select hardware package to select board from!',\n                                       title='select')\n        else:\n            hwpack = hwpack_names()[0]\n    print('%s selected' % hwpack)\n    if hwpack:\n        sel = psidialogs.multi_choice(board_names(hwpack),\n                                      'select boards to remove from %s!' % boards_txt(\n                                          hwpack),\n                                      title='remove boards')\n        print('%s selected' % sel)\n        if sel:\n            for x in sel:\n                remove_board(x)\n                print('%s was removed' % x)",
    "docstring": "remove boards by GUI."
  },
  {
    "code": "def shutdown(self):\n        if self.sock:\n            self.sock.close()\n            self.sock = None\n            self.connected = False",
    "docstring": "close socket, immediately."
  },
  {
    "code": "def _get_zoom_mat(sw:float, sh:float, c:float, r:float)->AffineMatrix:\n    \"`sw`,`sh` scale width,height - `c`,`r` focus col,row.\"\n    return [[sw, 0,  c],\n            [0, sh,  r],\n            [0,  0, 1.]]",
    "docstring": "`sw`,`sh` scale width,height - `c`,`r` focus col,row."
  },
  {
    "code": "def create_logger(name, formatter=None, handler=None, level=None):\n    logger = logging.getLogger(name)\n    logger.handlers = []\n    if handler is None:\n        handler = logging.StreamHandler(sys.stdout)\n    if formatter is not None:\n        handler.setFormatter(formatter)\n    if level is None:\n        level = logging.DEBUG\n    handler.setLevel(level)\n    logger.setLevel(level)\n    logger.addHandler(handler)\n    return logger",
    "docstring": "Returns a new logger for the specified name."
  },
  {
    "code": "def _handle_exc(exception):\n    bugzscout.ext.celery_app.submit_error.delay(\n        'http://fogbugz/scoutSubmit.asp',\n        'error-user',\n        'MyAppProject',\n        'Errors',\n        'An error occurred in MyApp: {0}'.format(exception.message),\n        extra=traceback.extract_tb(*sys.exc_info()))\n    return ['']",
    "docstring": "Record exception with stack trace to FogBugz via BugzScout,\n    asynchronously. Returns an empty string.\n\n    Note that this will not be reported to FogBugz until a celery worker\n    processes this task.\n\n    :param exception: uncaught exception thrown in app"
  },
  {
    "code": "def format_label(self, field, counter):\n        return '<label for=\"id_formfield_%s\" %s>%s</label>' % (\n            counter, field.field.required and 'class=\"required\"', field.label)",
    "docstring": "Format the label for each field"
  },
  {
    "code": "def range(self, count):\n        if count <= 1:\n            raise ValueError(\"Range size must be greater than 1.\")\n        dom = self._domain\n        distance = dom[-1] - dom[0]\n        props = [ self(dom[0] + distance * float(x)/(count-1))\n            for x in range(count) ]\n        return props",
    "docstring": "Create a list of colors evenly spaced along this scale's domain.\n\n        :param int count: The number of colors to return.\n\n        :rtype: list\n        :returns: A list of spectra.Color objects."
  },
  {
    "code": "def add(self, value):\n        added = self.redis.sadd(\n            self.key,\n            value\n        )\n        if self.redis.scard(self.key) < 2:\n            self.redis.expire(self.key, self.expire)\n        return added",
    "docstring": "Add value to set."
  },
  {
    "code": "def get_grade_system_ids_by_gradebooks(self, gradebook_ids):\n        id_list = []\n        for grade_system in self.get_grade_systems_by_gradebooks(gradebook_ids):\n            id_list.append(grade_system.get_id())\n        return IdList(id_list)",
    "docstring": "Gets the list of ``GradeSystem Ids`` corresponding to a list of ``Gradebooks``.\n\n        arg:    gradebook_ids (osid.id.IdList): list of gradebook\n                ``Ids``\n        return: (osid.id.IdList) - list of grade systems ``Ids``\n        raise:  NullArgument - ``gradebook_ids`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def nsuriLogic(self):\n        if self.parentClass:\n            return 'ns = %s.%s.schema' %(self.parentClass, self.getClassName())\n        return 'ns = %s.%s.schema' %(self.getNSAlias(), self.getClassName())",
    "docstring": "set a variable \"ns\" that represents the targetNamespace in\n        which this item is defined.  Used for namespacing local elements."
  },
  {
    "code": "def flip(self, reactions):\n        for reaction in reactions:\n            if reaction in self._flipped:\n                self._flipped.remove(reaction)\n            else:\n                self._flipped.add(reaction)",
    "docstring": "Flip the specified reactions."
  },
  {
    "code": "def setup_fields_processors(config, model_cls, schema):\n    properties = schema.get('properties', {})\n    for field_name, props in properties.items():\n        if not props:\n            continue\n        processors = props.get('_processors')\n        backref_processors = props.get('_backref_processors')\n        if processors:\n            processors = [resolve_to_callable(val) for val in processors]\n            setup_kwargs = {'model': model_cls, 'field': field_name}\n            config.add_field_processors(processors, **setup_kwargs)\n        if backref_processors:\n            db_settings = props.get('_db_settings', {})\n            is_relationship = db_settings.get('type') == 'relationship'\n            document = db_settings.get('document')\n            backref_name = db_settings.get('backref_name')\n            if not (is_relationship and document and backref_name):\n                continue\n            backref_processors = [\n                resolve_to_callable(val) for val in backref_processors]\n            setup_kwargs = {\n                'model': engine.get_document_cls(document),\n                'field': backref_name\n            }\n            config.add_field_processors(\n                backref_processors, **setup_kwargs)",
    "docstring": "Set up model fields' processors.\n\n    :param config: Pyramid Configurator instance.\n    :param model_cls: Model class for field of which processors should be\n        set up.\n    :param schema: Dict of model JSON schema."
  },
  {
    "code": "def usernames(\n        self\n        ):\n        try:\n            return list(set([tweet.username for tweet in self]))\n        except:\n            log.error(\"error -- possibly a problem with tweets stored\")",
    "docstring": "This function returns the list of unique usernames corresponding to the\n        tweets stored in self."
  },
  {
    "code": "def _ProcessGrepSource(self, source):\n    attributes = source.base_source.attributes\n    paths = artifact_utils.InterpolateListKbAttributes(\n        attributes[\"paths\"], self.knowledge_base,\n        self.ignore_interpolation_errors)\n    regex = utils.RegexListDisjunction(attributes[\"content_regex_list\"])\n    condition = rdf_file_finder.FileFinderCondition.ContentsRegexMatch(\n        regex=regex, mode=\"ALL_HITS\")\n    file_finder_action = rdf_file_finder.FileFinderAction.Stat()\n    request = rdf_file_finder.FileFinderArgs(\n        paths=paths,\n        action=file_finder_action,\n        conditions=[condition],\n        follow_links=True)\n    action = file_finder.FileFinderOSFromClient\n    yield action, request",
    "docstring": "Find files fulfilling regex conditions."
  },
  {
    "code": "def get_consumers(self, _Consumer, channel):\n        return [_Consumer(queues=[self.queue(channel)], callbacks=[self.main_callback], prefetch_count=self.prefetch_count)]",
    "docstring": "| ConsumerMixin requirement.\n        | Get the consumers list.\n\n        :returns: All the consumers.\n        :rtype: list."
  },
  {
    "code": "def list_labels(self, bucket):\n        for name in self.z.namelist():\n            container, label = self._nf(name.encode(\"utf-8\"))\n            if container == bucket and label != MD_FILE:\n                yield label",
    "docstring": "List labels for the given bucket. Due to zipfiles inherent arbitrary ordering,\n        this is an expensive operation, as it walks the entire archive searching for individual\n        'buckets'\n\n        :param bucket: bucket to list labels for.\n        :return: iterator for the labels in the specified bucket."
  },
  {
    "code": "def advice_dcv_method(cls, csr, package, altnames, dcv_method,\n                          cert_id=None):\n        params = {'csr': csr, 'package': package, 'dcv_method': dcv_method}\n        if cert_id:\n            params['cert_id'] = cert_id\n        result = cls.call('cert.get_dcv_params', params)\n        if dcv_method == 'dns':\n            cls.echo('You have to add these records in your domain zone :')\n        cls.echo('\\n'.join(result['message']))",
    "docstring": "Display dcv_method information."
  },
  {
    "code": "def auth(username, password):\n    django_auth_path = __opts__['django_auth_path']\n    if django_auth_path not in sys.path:\n        sys.path.append(django_auth_path)\n    os.environ.setdefault('DJANGO_SETTINGS_MODULE', __opts__['django_auth_settings'])\n    __django_auth_setup()\n    if not is_connection_usable():\n        connection.close()\n    import django.contrib.auth\n    user = django.contrib.auth.authenticate(username=username, password=password)\n    if user is not None:\n        if user.is_active:\n            log.debug('Django authentication successful')\n            return True\n        else:\n            log.debug('Django authentication: the password is valid but the account is disabled.')\n    else:\n        log.debug('Django authentication failed.')\n    return False",
    "docstring": "Simple Django auth"
  },
  {
    "code": "def _handle_tag_scriptlimits(self):\n        obj = _make_object(\"ScriptLimits\")\n        obj.MaxRecursionDepth = unpack_ui16(self._src)\n        obj.ScriptTimeoutSeconds = unpack_ui16(self._src)\n        return obj",
    "docstring": "Handle the ScriptLimits tag."
  },
  {
    "code": "def _make_bridge_request_msg(self, channel, netfn, command):\n        head = bytearray((constants.IPMI_BMC_ADDRESS,\n                          constants.netfn_codes['application'] << 2))\n        check_sum = _checksum(*head)\n        boday = bytearray((0x81, self.seqlun, constants.IPMI_SEND_MESSAGE_CMD,\n                           0x40 | channel))\n        self._add_request_entry((constants.netfn_codes['application'] + 1,\n                                 self.seqlun, constants.IPMI_SEND_MESSAGE_CMD))\n        return head + bytearray((check_sum,)) + boday",
    "docstring": "This function generate message for bridge request. It is a\n        part of ipmi payload."
  },
  {
    "code": "def _route(self, attr, args, kwargs, **fkwargs):\n        return self.cluster.hosts.keys()",
    "docstring": "Perform routing and return db_nums"
  },
  {
    "code": "def find_cached_job(jid):\n    serial = salt.payload.Serial(__opts__)\n    proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')\n    job_dir = os.path.join(proc_dir, six.text_type(jid))\n    if not os.path.isdir(job_dir):\n        if not __opts__.get('cache_jobs'):\n            return ('Local jobs cache directory not found; you may need to'\n                    ' enable cache_jobs on this minion')\n        else:\n            return 'Local jobs cache directory {0} not found'.format(job_dir)\n    path = os.path.join(job_dir, 'return.p')\n    with salt.utils.files.fopen(path, 'rb') as fp_:\n        buf = fp_.read()\n    if buf:\n        try:\n            data = serial.loads(buf)\n        except NameError:\n            pass\n        else:\n            if isinstance(data, dict):\n                return data\n    return None",
    "docstring": "Return the data for a specific cached job id. Note this only works if\n    cache_jobs has previously been set to True on the minion.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' saltutil.find_cached_job <job id>"
  },
  {
    "code": "def apply_ants_transform(transform, data, data_type=\"point\", reference=None, **kwargs):\n    return transform.apply(data, data_type, reference, **kwargs)",
    "docstring": "Apply ANTsTransform to data\n\n    ANTsR function: `applyAntsrTransform`\n\n    Arguments\n    ---------\n    transform : ANTsTransform\n        transform to apply to image\n\n    data : ndarray/list/tuple\n        data to which transform will be applied\n\n    data_type : string\n        type of data\n        Options :\n            'point'\n            'vector'\n            'image'\n\n    reference : ANTsImage\n        target space for transforming image\n\n    kwargs : kwargs\n        additional options passed to `apply_ants_transform_to_image`\n\n    Returns\n    -------\n    ANTsImage if data_type == 'point'\n    OR\n    tuple if data_type == 'point' or data_type == 'vector'"
  },
  {
    "code": "def dirichlet_like(x, theta):\n    R\n    x = np.atleast_2d(x)\n    theta = np.atleast_2d(theta)\n    if (np.shape(x)[-1] + 1) != np.shape(theta)[-1]:\n        raise ValueError('The dimension of x in dirichlet_like must be k-1.')\n    return flib.dirichlet(x, theta)",
    "docstring": "R\"\"\"\n    Dirichlet log-likelihood.\n\n    This is a multivariate continuous distribution.\n\n    .. math::\n        f(\\mathbf{x}) = \\frac{\\Gamma(\\sum_{i=1}^k \\theta_i)}{\\prod \\Gamma(\\theta_i)}\\prod_{i=1}^{k-1} x_i^{\\theta_i - 1}\n        \\cdot\\left(1-\\sum_{i=1}^{k-1}x_i\\right)^\\theta_k\n\n    :Parameters:\n      x : (n, k-1) array\n        Array of shape (n, k-1) where `n` is the number of samples\n        and `k` the dimension.\n        :math:`0 < x_i < 1`,  :math:`\\sum_{i=1}^{k-1} x_i < 1`\n      theta : array\n        An (n,k) or (1,k) array > 0.\n\n    .. note::\n        Only the first `k-1` elements of `x` are expected. Can be used\n        as a parent of Multinomial and Categorical nevertheless."
  },
  {
    "code": "def SetValue(self, row, col, value, refresh=True):\n        value = \"\".join(value.split(\"\\n\"))\n        key = row, col, self.grid.current_table\n        old_code = self.grid.code_array(key)\n        if old_code is None:\n            old_code = \"\"\n        if value != old_code:\n            self.grid.actions.set_code(key, value)",
    "docstring": "Set the value of a cell, merge line breaks"
  },
  {
    "code": "def dictionary_merge(a, b):\n    for key, value in b.items():\n        if key in a and isinstance(a[key], dict) and isinstance(value, dict):\n            dictionary_merge(a[key], b[key])\n            continue\n        a[key] = b[key]\n    return a",
    "docstring": "merges dictionary b into a\n       Like dict.update, but recursive"
  },
  {
    "code": "def add(self, word):\n        if not word or word.strip() == '':\n            return\n        self.words[word]=word",
    "docstring": "Add a word to the dictionary"
  },
  {
    "code": "def saveVarsInMat(filename, varNamesStr, outOf=None, **opts):\n    from mlabwrap import mlab\n    filename, varnames, outOf = __saveVarsHelper(\n        filename, varNamesStr, outOf, '.mat', **opts)\n    try:\n        for varname in varnames:\n            mlab._set(varname, outOf[varname])\n        mlab._do(\"save('%s','%s')\" % (filename, \"', '\".join(varnames)), nout=0)\n    finally:\n        assert varnames\n        mlab._do(\"clear('%s')\" % \"', '\".join(varnames), nout=0)",
    "docstring": "Hacky convinience function to dump a couple of python variables in a\n       .mat file. See `awmstools.saveVars`."
  },
  {
    "code": "def set_disk_timeout(timeout, power='ac', scheme=None):\n    return _set_powercfg_value(\n        scheme=scheme,\n        sub_group='SUB_DISK',\n        setting_guid='DISKIDLE',\n        power=power,\n        value=timeout)",
    "docstring": "Set the disk timeout in minutes for the given power scheme\n\n    Args:\n        timeout (int):\n            The amount of time in minutes before the disk will timeout\n\n        power (str):\n            Set the value for AC or DC power. Default is ``ac``. Valid options\n            are:\n\n                - ``ac`` (AC Power)\n                - ``dc`` (Battery)\n\n        scheme (str):\n            The scheme to use, leave as ``None`` to use the current. Default is\n            ``None``. This can be the GUID or the Alias for the Scheme. Known\n            Aliases are:\n\n                - ``SCHEME_BALANCED`` - Balanced\n                - ``SCHEME_MAX`` - Power saver\n                - ``SCHEME_MIN`` - High performance\n\n    Returns:\n        bool: ``True`` if successful, otherwise ``False``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        # Sets the disk timeout to 30 minutes on battery\n        salt '*' powercfg.set_disk_timeout 30 power=dc"
  },
  {
    "code": "def __setRouterSelectionJitter(self, iRouterJitter):\n        print 'call _setRouterSelectionJitter'\n        try:\n            cmd = 'routerselectionjitter %s' % str(iRouterJitter)\n            print cmd\n            return self.__sendCommand(cmd) == 'Done'\n        except Exception, e:\n            ModuleHelper.WriteIntoDebugLogger(\"setRouterSelectionJitter() Error: \" + str(e))",
    "docstring": "set ROUTER_SELECTION_JITTER parameter for REED to upgrade to Router\n\n        Args:\n            iRouterJitter: a random period prior to request Router ID for REED\n\n        Returns:\n            True: successful to set the ROUTER_SELECTION_JITTER\n            False: fail to set ROUTER_SELECTION_JITTER"
  },
  {
    "code": "def GetNumberOfRows(self):\n    if not self._database_object:\n      raise IOError('Not opened.')\n    if self._number_of_rows is None:\n      self._number_of_rows = self._database_object.GetNumberOfRows(\n          self._table_name)\n    return self._number_of_rows",
    "docstring": "Retrieves the number of rows of the table.\n\n    Returns:\n      int: number of rows.\n\n    Raises:\n      IOError: if the file-like object has not been opened.\n      OSError: if the file-like object has not been opened."
  },
  {
    "code": "def parse_statements(self, end_tokens, drop_needle=False):\n        self.stream.skip_if('colon')\n        self.stream.expect('block_end')\n        result = self.subparse(end_tokens)\n        if self.stream.current.type == 'eof':\n            self.fail_eof(end_tokens)\n        if drop_needle:\n            next(self.stream)\n        return result",
    "docstring": "Parse multiple statements into a list until one of the end tokens\n        is reached.  This is used to parse the body of statements as it also\n        parses template data if appropriate.  The parser checks first if the\n        current token is a colon and skips it if there is one.  Then it checks\n        for the block end and parses until if one of the `end_tokens` is\n        reached.  Per default the active token in the stream at the end of\n        the call is the matched end token.  If this is not wanted `drop_needle`\n        can be set to `True` and the end token is removed."
  },
  {
    "code": "def _translate_str(self, oprnd1, oprnd2, oprnd3):\n        assert oprnd1.size and oprnd3.size\n        op1_var = self._translate_src_oprnd(oprnd1)\n        op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)\n        if oprnd3.size > oprnd1.size:\n            result = smtfunction.zero_extend(op1_var, op3_var.size)\n        elif oprnd3.size < oprnd1.size:\n            result = smtfunction.extract(op1_var, 0, op3_var.size)\n        else:\n            result = op1_var\n        return [op3_var == result] + op3_var_constrs",
    "docstring": "Return a formula representation of a STR instruction."
  },
  {
    "code": "def write_error(self, status_code, **kwargs):\n        message = default_message = httplib.responses.get(status_code, '')\n        if 'exc_info' in kwargs:\n            (_, exc, _) = kwargs['exc_info']\n            if hasattr(exc, 'log_message'):\n                message = str(exc.log_message) or default_message\n        self.logvalue('halt_reason', message)\n        title = \"{}: {}\".format(status_code, default_message)\n        body = \"{}: {}\".format(status_code, message)\n        self.finish(\"<html><title>\" + title + \"</title>\"\n                    \"<body>\" + body + \"</body></html>\")",
    "docstring": "Log halt_reason in service log and output error page"
  },
  {
    "code": "def issue(self, issuance_spec, metadata, fees):\n        inputs, total_amount = self._collect_uncolored_outputs(\n            issuance_spec.unspent_outputs, 2 * self._dust_amount + fees)\n        return bitcoin.core.CTransaction(\n            vin=[bitcoin.core.CTxIn(item.out_point, item.output.script) for item in inputs],\n            vout=[\n                self._get_colored_output(issuance_spec.to_script),\n                self._get_marker_output([issuance_spec.amount], metadata),\n                self._get_uncolored_output(issuance_spec.change_script, total_amount - self._dust_amount - fees)\n            ]\n        )",
    "docstring": "Creates a transaction for issuing an asset.\n\n        :param TransferParameters issuance_spec: The parameters of the issuance.\n        :param bytes metadata: The metadata to be embedded in the transaction.\n        :param int fees: The fees to include in the transaction.\n        :return: An unsigned transaction for issuing an asset.\n        :rtype: CTransaction"
  },
  {
    "code": "def _event_to_pb(event):\n        if isinstance(event, (TaskData, Task)):\n            key, klass = 'task', clearly_pb2.TaskMessage\n        elif isinstance(event, (WorkerData, Worker)):\n            key, klass = 'worker', clearly_pb2.WorkerMessage\n        else:\n            raise ValueError('unknown event')\n        keys = klass.DESCRIPTOR.fields_by_name.keys()\n        data = {k: v for k, v in\n                getattr(event, '_asdict',\n                        lambda: {f: getattr(event, f) for f in event._fields})\n                ().items() if k in keys}\n        return key, klass(**data)",
    "docstring": "Supports converting internal TaskData and WorkerData, as well as\n        celery Task and Worker to proto buffers messages.\n\n        Args:\n            event (Union[TaskData|Task|WorkerData|Worker]):\n\n        Returns:\n            ProtoBuf object"
  },
  {
    "code": "def get_queryset(self):\n        qs = super().get_queryset()\n        qs = qs.filter(approved=True)\n        return qs",
    "docstring": "Returns all the approved topics or posts."
  },
  {
    "code": "def chunks(data, chunk_size):\n    for i in xrange(0, len(data), chunk_size):\n        yield data[i:i+chunk_size]",
    "docstring": "Yield chunk_size chunks from data."
  },
  {
    "code": "def add_header(self, name, value):\n        self._headers.setdefault(_hkey(name), []).append(_hval(value))",
    "docstring": "Add an additional response header, not removing duplicates."
  },
  {
    "code": "def _put_attributes_using_post(self, domain_or_name, item_name, attributes,\n                               replace=True, expected_value=None):\n    domain, domain_name = self.get_domain_and_name(domain_or_name)\n    params = {'DomainName': domain_name,\n              'ItemName': item_name}\n    self._build_name_value_list(params, attributes, replace)\n    if expected_value:\n        self._build_expected_value(params, expected_value)\n    return self.get_status('PutAttributes', params, verb='POST')",
    "docstring": "Monkey-patched version of SDBConnection.put_attributes that uses POST instead of GET\n\n    The GET version is subject to the URL length limit which kicks in before the 256 x 1024 limit\n    for attribute values. Using POST prevents that.\n\n    https://github.com/BD2KGenomics/toil/issues/502"
  },
  {
    "code": "def request_exception(sender, request, **kwargs):\n    if not isinstance(request, WSGIRequest):\n        logger = logging.getLogger(__name__)\n        level = CRITICAL if request.status_code <= 500 else WARNING\n        logger.log(level, '%s exception occured (%s)',\n                   request.status_code, request.reason_phrase)\n    else:\n        logger = logging.getLogger(__name__)\n        logger.log(WARNING, 'WSGIResponse exception occured')",
    "docstring": "Automated request exception logging.\n\n    The function can also return an WSGIRequest exception,\n    which does not supply either status_code or reason_phrase."
  },
  {
    "code": "def do_gh(self, arg):\n        if self.cmdprefix:\n            raise CmdError(\"prefix not allowed\")\n        if arg:\n            raise CmdError(\"too many arguments\")\n        if self.lastEvent:\n            self.lastEvent.continueStatus = win32.DBG_EXCEPTION_HANDLED\n        return self.do_go(arg)",
    "docstring": "gh - go with exception handled"
  },
  {
    "code": "def set_params(self, arg_params, aux_params, allow_extra=False):\n        for exec_ in self.execs:\n            exec_.copy_params_from(arg_params, aux_params, allow_extra_params=allow_extra)",
    "docstring": "Assign, i.e. copy parameters to all the executors.\n\n        Parameters\n        ----------\n        arg_params : dict\n            A dictionary of name to `NDArray` parameter mapping.\n        aux_params : dict\n            A dictionary of name to `NDArray` auxiliary variable mapping.\n        allow_extra : boolean, optional\n            Whether allow extra parameters that are not needed by symbol.\n            If this is True, no error will be thrown when arg_params or aux_params\n            contain extra parameters that is not needed by the executor."
  },
  {
    "code": "def from_file(cls, file_path, compressed=False, encoded=False):\n        file_id = '.'.join(path.basename(file_path).split('.')[:-1])\n        file_format = file_path.split('.')[-1]\n        content = cls(file_id, file_format, compressed, encoded)\n        content.file_exists = True\n        content._location = path.dirname(file_path)\n        return content",
    "docstring": "Create a content object from a file path."
  },
  {
    "code": "def write_ply(self, output_file):\n        points = np.hstack([self.coordinates, self.colors])\n        with open(output_file, 'w') as outfile:\n            outfile.write(self.ply_header.format(\n                                            vertex_count=len(self.coordinates)))\n            np.savetxt(outfile, points, '%f %f %f %d %d %d')",
    "docstring": "Export ``PointCloud`` to PLY file for viewing in MeshLab."
  },
  {
    "code": "def render(self, doc):\n        d = defer.succeed(doc)\n        for element in self._elements:\n            d.addCallback(element.render)\n        return d",
    "docstring": "Render all elements using specified document.\n        @param doc: the writable document to render to.\n        @type doc: document.IWritableDocument\n        @return: a deferred fired with the specified document\n                 when the rendering is done.\n        @rtype: defer.Deferred"
  },
  {
    "code": "def __cancel_timer(self):\n        if self.__timer is not None:\n            self.__timer.cancel()\n            self.__unbind_call(True)\n        self.__timer_args = None\n        self.__timer = None",
    "docstring": "Cancels the timer, and calls its target method immediately"
  },
  {
    "code": "def post_change_receiver(self, instance: Model, action: Action, **kwargs):\n        try:\n            old_group_names = instance.__instance_groups.observers[self]\n        except (ValueError, KeyError):\n            old_group_names = set()\n        if action == Action.DELETE:\n            new_group_names = set()\n        else:\n            new_group_names = set(self.group_names(instance))\n        self.send_messages(\n            instance,\n            old_group_names - new_group_names,\n            Action.DELETE,\n            **kwargs\n        )\n        self.send_messages(\n            instance,\n            old_group_names & new_group_names,\n            Action.UPDATE,\n            **kwargs\n        )\n        self.send_messages(\n            instance,\n            new_group_names - old_group_names,\n            Action.CREATE,\n            **kwargs\n        )",
    "docstring": "Triggers the old_binding to possibly send to its group."
  },
  {
    "code": "def dependencies(self, kwargs=None, expand_only=False):\n        if not kwargs:\n            kwargs = {}\n        self.proper_kwargs('dependencies', kwargs)\n        sections = self._get_dependency_sections_to_use(kwargs)\n        deps = []\n        for sect in sections:\n            if expand_only:\n                deps.extend(lang.expand_dependencies_section(sect, kwargs))\n            else:\n                deps.extend(lang.dependencies_section(sect, kwargs, runner=self))\n        return deps",
    "docstring": "Returns all dependencies of this assistant with regards to specified kwargs.\n\n        If expand_only == False, this method returns list of mappings of dependency types\n        to actual dependencies (keeps order, types can repeat), e.g.\n        Example:\n        [{'rpm', ['rubygems']}, {'gem', ['mygem']}, {'rpm', ['spam']}, ...]\n        If expand_only == True, this method returns a structure that can be used as\n        \"dependencies\" section and has all the \"use: foo\" commands expanded (but conditions\n        are left untouched and variables are not substituted)."
  },
  {
    "code": "def get_output_error(cmd):\n    if not isinstance(cmd, list):\n        cmd = [cmd]\n    logging.debug(\"Running: %s\", ' '.join(map(quote, cmd)))\n    try:\n        result = Popen(cmd, stdout=PIPE, stderr=PIPE)\n    except IOError as e:\n        return -1, u(''), u('Failed to run %r: %r' % (cmd, e))\n    so, se = result.communicate()\n    so = so.decode('utf8', 'replace')\n    se = se.decode('utf8', 'replace')\n    return result.returncode, so, se",
    "docstring": "Return the exit status, stdout, stderr of a command"
  },
  {
    "code": "def spop(self, name, count=None):\n        \"Remove and return a random member of set ``name``\"\n        args = (count is not None) and [count] or []\n        return self.execute_command('SPOP', name, *args)",
    "docstring": "Remove and return a random member of set ``name``"
  },
  {
    "code": "def register(self):\n        self._queue.put(hello_packet(socket.gethostname(), mac(), __version__))\n        self._queue.put(request_packet(MSG_SERVER_SETTINGS))\n        self._queue.put(request_packet(MSG_SAMPLE_FORMAT))\n        self._queue.put(request_packet(MSG_HEADER))",
    "docstring": "Transact with server."
  },
  {
    "code": "def close(self):\n        self.log.warning('Closing connection to AVR')\n        self._closing = True\n        if self.protocol.transport:\n            self.protocol.transport.close()",
    "docstring": "Close the AVR device connection and don't try to reconnect."
  },
  {
    "code": "def __insert_action(self, revision):\n        revision[\"patch\"][\"_id\"] = ObjectId(revision.get(\"master_id\"))\n        insert_response = yield self.collection.insert(revision.get(\"patch\"))\n        if not isinstance(insert_response, str):\n            raise DocumentRevisionInsertFailed()",
    "docstring": "Handle the insert action type.\n\n        Creates new document to be created in this collection.\n        This allows you to stage a creation of an object\n\n        :param dict revision: The revision dictionary"
  },
  {
    "code": "def update_payment_request(self, tid, currency=None, amount=None,\n                               action=None, ledger=None, callback_uri=None,\n                               display_message_uri=None, capture_id=None,\n                               additional_amount=None, text=None, refund_id=None,\n                               required_scope=None, required_scope_text=None, line_items=None):\n        arguments = {'ledger': ledger,\n                     'display_message_uri': display_message_uri,\n                     'callback_uri': callback_uri,\n                     'currency': currency,\n                     'amount': amount,\n                     'additional_amount': additional_amount,\n                     'capture_id': capture_id,\n                     'action': action,\n                     'text': text,\n                     'refund_id': refund_id}\n        if required_scope:\n            arguments['required_scope'] = required_scope\n            arguments['required_scope_text'] = required_scope_text\n        if line_items:\n            arguments['line_items'] = line_items\n        arguments = {k: v for k, v in arguments.items() if v is not None}\n        return self.do_req('PUT',\n                           self.merchant_api_base_url + '/payment_request/' +\n                           tid + '/', arguments)",
    "docstring": "Update payment request, reauthorize, capture, release or abort\n\n        It is possible to update ledger and the callback URIs for a payment\n        request. Changes are always appended to the open report of a ledger,\n        and notifications are sent to the callback registered at the time of\n        notification.\n\n        Capturing an authorized payment or reauthorizing is done with the\n        action field.\n\n        The call is idempotent; that is, if one posts the same amount,\n        additional_amount and capture_id twice with action CAPTURE, only one\n        capture is performed. Similarly, if one posts twice with action CAPTURE\n        without any amount stated, to capture the full amount, only one full\n        capture is performed.\n\n        Arguments:\n            ledger:\n                Log entries will be added to the open report on the specified\n                ledger\n            display_message_uri:\n                Messages that can be used to inform the POS operator about the\n                progress of the payment request will be POSTed to this URI if\n                provided\n            callback_uri:\n                If provided, mCASH will POST to this URI when the status of the\n                payment request changes, using the message mechanism described\n                in the introduction. The data in the \"object\" part of the\n                message is the same as what can be retrieved by calling GET on\n                the \"/payment_request/<tid>/outcome/\" resource URI.\n            currency:\n                3 chars https://en.wikipedia.org/wiki/ISO_4217\n            amount:\n                The base amount of the payment\n            additional_amount:\n                Typically cash withdrawal or gratuity\n            capture_id:\n                Local id for capture. Must be set if amount is set, otherwise\n                capture_id must be unset.\n            tid:\n                Transaction id assigned by mCASH\n            refund_id:\n                Refund id needed when doing partial refund\n            text:\n                For example reason for refund.\n            action:\n                Action to perform.\n            required_scope:\n                Scopes required to fulfill payment\n            line_items:\n                An updated line_items. Will fail if line_items\n                already set in the payment request or if the sum of the totals\n                is different from the original amount.\n            required_scope_text:\n                Text that is shown to user when asked for permission."
  },
  {
    "code": "def fromML(vec):\n        if isinstance(vec, newlinalg.DenseVector):\n            return DenseVector(vec.array)\n        elif isinstance(vec, newlinalg.SparseVector):\n            return SparseVector(vec.size, vec.indices, vec.values)\n        else:\n            raise TypeError(\"Unsupported vector type %s\" % type(vec))",
    "docstring": "Convert a vector from the new mllib-local representation.\n        This does NOT copy the data; it copies references.\n\n        :param vec: a :py:class:`pyspark.ml.linalg.Vector`\n        :return: a :py:class:`pyspark.mllib.linalg.Vector`\n\n        .. versionadded:: 2.0.0"
  },
  {
    "code": "def AsRegEx(self):\n    parts = self.__class__.REGEX_SPLIT_PATTERN.split(self._value)\n    result = u\"\".join(self._ReplaceRegExPart(p) for p in parts)\n    return rdf_standard.RegularExpression(u\"(?i)\\\\A%s\\\\Z\" % result)",
    "docstring": "Return the current glob as a simple regex.\n\n    Note: No interpolation is performed.\n\n    Returns:\n      A RegularExpression() object."
  },
  {
    "code": "def get_form_kwargs(self):\n        kwargs = super(ApiFormView, self).get_form_kwargs()\n        kwargs['data'] = kwargs.get('initial')\n        return kwargs",
    "docstring": "Add the 'data' to the form args so you can validate the form\n        data on a get request."
  },
  {
    "code": "def is_pk_descriptor(descriptor, include_alt=False):\n    if descriptor.pk is True or type(descriptor.pk) is int:\n        return True\n    if include_alt:\n        return descriptor.alt_pk is True or type(descriptor.alt_pk) is int\n    else:\n        return False",
    "docstring": "Return true if `descriptor` is a primary key."
  },
  {
    "code": "def create_parameter_group(name, db_parameter_group_family, description,\n                           tags=None, region=None, key=None, keyid=None,\n                           profile=None):\n    res = __salt__['boto_rds.parameter_group_exists'](name, tags, region, key,\n                                                      keyid, profile)\n    if res.get('exists'):\n        return {'exists': bool(res)}\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        if not conn:\n            return {'results': bool(conn)}\n        taglist = _tag_doc(tags)\n        rds = conn.create_db_parameter_group(DBParameterGroupName=name,\n                                             DBParameterGroupFamily=db_parameter_group_family,\n                                             Description=description,\n                                             Tags=taglist)\n        if not rds:\n            return {'created': False, 'message':\n                    'Failed to create RDS parameter group {0}'.format(name)}\n        return {'exists': bool(rds), 'message':\n                'Created RDS parameter group {0}'.format(name)}\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Create an RDS parameter group\n\n    CLI example to create an RDS parameter group::\n\n        salt myminion boto_rds.create_parameter_group my-param-group mysql5.6 \\\n                \"group description\""
  },
  {
    "code": "def set_nest_transactions_with_savepoints(self, nest_transactions_with_savepoints):\n        if self._transaction_nesting_level > 0:\n            raise DBALConnectionError.may_not_alter_nested_transaction_with_savepoints_in_transaction()\n        if not self._platform.is_savepoints_supported():\n            raise DBALConnectionError.savepoints_not_supported()\n        self._nest_transactions_with_savepoints = bool(nest_transactions_with_savepoints)",
    "docstring": "Sets if nested transactions should use savepoints.\n\n        :param nest_transactions_with_savepoints: `True` or `False`"
  },
  {
    "code": "def _build_fluent_table(self):\n        self.fluent_table = collections.OrderedDict()\n        for name, size in zip(self.domain.non_fluent_ordering, self.non_fluent_size):\n            non_fluent = self.domain.non_fluents[name]\n            self.fluent_table[name] = (non_fluent, size)\n        for name, size in zip(self.domain.state_fluent_ordering, self.state_size):\n            fluent = self.domain.state_fluents[name]\n            self.fluent_table[name] = (fluent, size)\n        for name, size in zip(self.domain.action_fluent_ordering, self.action_size):\n            fluent = self.domain.action_fluents[name]\n            self.fluent_table[name] = (fluent, size)\n        for name, size in zip(self.domain.interm_fluent_ordering, self.interm_size):\n            fluent = self.domain.intermediate_fluents[name]\n            self.fluent_table[name] = (fluent, size)",
    "docstring": "Builds the fluent table for each RDDL pvariable."
  },
  {
    "code": "def connection_lost(self, exc: Optional[Exception]) -> None:\n        logger.debug(\"%s - event = connection_lost(%s)\", self.side, exc)\n        self.state = State.CLOSED\n        logger.debug(\"%s - state = CLOSED\", self.side)\n        if not hasattr(self, \"close_code\"):\n            self.close_code = 1006\n        if not hasattr(self, \"close_reason\"):\n            self.close_reason = \"\"\n        logger.debug(\n            \"%s x code = %d, reason = %s\",\n            self.side,\n            self.close_code,\n            self.close_reason or \"[no reason]\",\n        )\n        self.abort_keepalive_pings()\n        self.connection_lost_waiter.set_result(None)\n        super().connection_lost(exc)",
    "docstring": "7.1.4. The WebSocket Connection is Closed."
  },
  {
    "code": "def allocate_stack(size=DEFAULT_STACK_SIZE):\n    base = libc.mmap(\n        None,\n        size + GUARD_PAGE_SIZE,\n        libc.PROT_READ | libc.PROT_WRITE,\n        libc.MAP_PRIVATE | libc.MAP_ANONYMOUS | libc.MAP_GROWSDOWN | libc.MAP_STACK,\n        -1, 0)\n    try:\n        libc.mprotect(base, GUARD_PAGE_SIZE, libc.PROT_NONE)\n        yield ctypes.c_void_p(base + size + GUARD_PAGE_SIZE)\n    finally:\n        libc.munmap(base, size + GUARD_PAGE_SIZE)",
    "docstring": "Allocate some memory that can be used as a stack.\n    @return: a ctypes void pointer to the *top* of the stack."
  },
  {
    "code": "def predict_from_variants(\n            self,\n            variants,\n            transcript_expression_dict=None,\n            gene_expression_dict=None):\n        variants = apply_variant_expression_filters(\n            variants,\n            transcript_expression_dict=transcript_expression_dict,\n            transcript_expression_threshold=self.min_transcript_expression,\n            gene_expression_dict=gene_expression_dict,\n            gene_expression_threshold=self.min_gene_expression)\n        effects = variants.effects(raise_on_error=self.raise_on_error)\n        return self.predict_from_mutation_effects(\n            effects=effects,\n            transcript_expression_dict=transcript_expression_dict,\n            gene_expression_dict=gene_expression_dict)",
    "docstring": "Predict epitopes from a Variant collection, filtering options, and\n        optional gene and transcript expression data.\n\n        Parameters\n        ----------\n        variants : varcode.VariantCollection\n\n        transcript_expression_dict : dict\n            Maps from Ensembl transcript IDs to FPKM expression values.\n\n        gene_expression_dict : dict, optional\n            Maps from Ensembl gene IDs to FPKM expression values.\n\n        Returns DataFrame with the following columns:\n            - variant\n            - gene\n            - gene_id\n            - transcript_id\n            - transcript_name\n            - effect\n            - effect_type\n            - peptide\n            - peptide_offset\n            - peptide_length\n            - allele\n            - affinity\n            - percentile_rank\n            - prediction_method_name\n            - contains_mutant_residues\n            - mutation_start_in_peptide\n            - mutation_end_in_peptide\n\n        Optionall will also include the following columns if corresponding\n        expression dictionary inputs are provided:\n            - gene_expression\n            - transcript_expression"
  },
  {
    "code": "def ParseMessage(descriptor, byte_str):\n  result_class = MakeClass(descriptor)\n  new_msg = result_class()\n  new_msg.ParseFromString(byte_str)\n  return new_msg",
    "docstring": "Generate a new Message instance from this Descriptor and a byte string.\n\n  Args:\n    descriptor: Protobuf Descriptor object\n    byte_str: Serialized protocol buffer byte string\n\n  Returns:\n    Newly created protobuf Message object."
  },
  {
    "code": "def get(self, block=True, timeout=None):\n        _, node_id = self.inner.get(block=block, timeout=timeout)\n        with self.lock:\n            self._mark_in_progress(node_id)\n        return self.get_node(node_id)",
    "docstring": "Get a node off the inner priority queue. By default, this blocks.\n\n        This takes the lock, but only for part of it.\n\n        :param bool block: If True, block until the inner queue has data\n        :param Optional[float] timeout: If set, block for timeout seconds\n            waiting for data.\n        :return ParsedNode: The node as present in the manifest.\n\n        See `queue.PriorityQueue` for more information on `get()` behavior and\n        exceptions."
  },
  {
    "code": "def find_all(self, prefix):\n        prefix = ip_network(prefix)\n        if not self.prefix.overlaps(prefix) \\\n        or self.prefix[0] > prefix[0] \\\n        or self.prefix[-1] < prefix[-1]:\n            raise NotAuthoritativeError('This node is not authoritative for %r'\n                                        % prefix)\n        matches = set()\n        for child in self.children:\n            if prefix.overlaps(child.prefix):\n                matches.add(child)\n        return matches",
    "docstring": "Find everything in the given prefix"
  },
  {
    "code": "def show_message(self, message, timeout=0):\n        self.main.statusBar().showMessage(message, timeout)",
    "docstring": "Show message in main window's status bar"
  },
  {
    "code": "def grabEmails(emails=None, emailsFile=None, nicks=None, nicksFile=None, domains=EMAIL_DOMAINS, excludeDomains=[]):\n    email_candidates = []\n    if emails != None:\n        email_candidates = emails\n    elif emailsFile != None:\n        with open(emailsFile, \"r\") as iF:\n            email_candidates = iF.read().splitlines()\n    elif nicks != None:\n        for n in nicks:\n            for d in domains:\n                if d not in excludeDomains:\n                    email_candidates.append(n+\"@\"+d)\n    elif nicksFile != None:\n        with open(nicksFile, \"r\") as iF:\n            nicks = iF.read().splitlines()\n            for n in nicks:\n                for d in domains:\n                    if d not in excludeDomains:\n                        email_candidates.append(n+\"@\"+d)\n    return email_candidates",
    "docstring": "Method that generates a list of emails.\n\n    Args:\n    -----\n        emails: Any premade list of emails.\n        emailsFile: Filepath to the emails file (one per line).\n        nicks: A list of aliases.\n        nicksFile: Filepath to the aliases file (one per line).\n        domains: Domains where the aliases will be tested.\n        excludeDomains: Domains to be excluded from the created list.\n\n    Returns:\n    --------\n        list: the list of emails that will be verified."
  },
  {
    "code": "def get_en2fr(url='http://www.manythings.org/anki/fra-eng.zip'):\n    download_unzip(url)\n    return pd.read_table(url, compression='zip', header=None, skip_blank_lines=True, sep='\\t', skiprows=0, names='en fr'.split())",
    "docstring": "Download and parse English->French translation dataset used in Keras seq2seq example"
  },
  {
    "code": "def gff3_to_dataframe(path, attributes=None, region=None, score_fill=-1,\n                      phase_fill=-1, attributes_fill='.', tabix='tabix', **kwargs):\n    import pandas\n    recs = list(iter_gff3(path, attributes=attributes, region=region,\n                          score_fill=score_fill, phase_fill=phase_fill,\n                          attributes_fill=attributes_fill, tabix=tabix))\n    columns = ['seqid', 'source', 'type', 'start', 'end', 'score', 'strand', 'phase']\n    if attributes:\n        columns += list(attributes)\n    df = pandas.DataFrame.from_records(recs, columns=columns, **kwargs)\n    return df",
    "docstring": "Load data from a GFF3 into a pandas DataFrame.\n\n    Parameters\n    ----------\n    path : string\n        Path to input file.\n    attributes : list of strings, optional\n        List of columns to extract from the \"attributes\" field.\n    region : string, optional\n        Genome region to extract. If given, file must be position\n        sorted, bgzipped and tabix indexed. Tabix must also be installed\n        and on the system path.\n    score_fill : int, optional\n        Value to use where score field has a missing value.\n    phase_fill : int, optional\n        Value to use where phase field has a missing value.\n    attributes_fill : object or list of objects, optional\n        Value(s) to use where attribute field(s) have a missing value.\n    tabix : string, optional\n        Tabix command.\n\n    Returns\n    -------\n    pandas.DataFrame"
  },
  {
    "code": "def abbreviate(s, maxlength=25):\n    assert maxlength >= 4\n    skip = False\n    abbrv = None\n    i = 0\n    for j, c in enumerate(s):\n        if c == '\\033':\n            skip = True\n        elif skip:\n            if c == 'm':\n                skip = False\n        else:\n            i += 1\n        if i == maxlength - 1:\n            abbrv = s[:j] + '\\033[0m...'\n        elif i > maxlength:\n            break\n    if i <= maxlength:\n        return s\n    else:\n        return abbrv",
    "docstring": "Color-aware abbreviator"
  },
  {
    "code": "def run(self, *args):\n        params = self.parser.parse_args(args)\n        api_token = params.api_token\n        genderize_all = params.genderize_all\n        code = self.autogender(api_token=api_token,\n                               genderize_all=genderize_all)\n        return code",
    "docstring": "Autocomplete gender information."
  },
  {
    "code": "def pspawn_wrapper(self, sh, escape, cmd, args, env):\n        return self.pspawn(sh, escape, cmd, args, env, self.logstream, self.logstream)",
    "docstring": "Wrapper function for handling piped spawns.\n\n        This looks to the calling interface (in Action.py) like a \"normal\"\n        spawn, but associates the call with the PSPAWN variable from\n        the construction environment and with the streams to which we\n        want the output logged.  This gets slid into the construction\n        environment as the SPAWN variable so Action.py doesn't have to\n        know or care whether it's spawning a piped command or not."
  },
  {
    "code": "def write(self, filename):\n        with open(filename, 'w') as f:\n            f.write(self.ascii)\n        self.print(\"Detector file saved as '{0}'\".format(filename))",
    "docstring": "Save detx file."
  },
  {
    "code": "def is_required(self, name):\n        return self.schema_element(name).repetition_type == parquet_thrift.FieldRepetitionType.REQUIRED",
    "docstring": "Return true iff the schema element with the given name is required."
  },
  {
    "code": "def sysidpath(ignore_options=False):\n    failover = Path('/tmp/machine-id')\n    if not ignore_options:\n        options = (\n            Path('/etc/machine-id'),\n            failover,\n        )\n        for option in options:\n            if (option.exists() and\n                os.access(option, os.R_OK) and\n                option.stat().st_size > 0):\n                    return option\n    uuid = uuid4()\n    with open(failover, 'wt') as f:\n        f.write(uuid.hex)\n    return failover",
    "docstring": "get a unique identifier for the machine running this function"
  },
  {
    "code": "def get_msgbuf(self):\n        values = []\n        for i in range(len(self.fmt.columns)):\n            if i >= len(self.fmt.msg_mults):\n                continue\n            mul = self.fmt.msg_mults[i]\n            name = self.fmt.columns[i]\n            if name == 'Mode' and 'ModeNum' in self.fmt.columns:\n                name = 'ModeNum'\n            v = self.__getattr__(name)\n            if mul is not None:\n                v /= mul\n            values.append(v)\n        return struct.pack(\"BBB\", 0xA3, 0x95, self.fmt.type) + struct.pack(self.fmt.msg_struct, *values)",
    "docstring": "create a binary message buffer for a message"
  },
  {
    "code": "def get(self, key, *, encoding=_NOTSET):\n        return self.execute(b'GET', key, encoding=encoding)",
    "docstring": "Get the value of a key."
  },
  {
    "code": "def get_session(self, app_path, session_id):\n        if app_path not in self._applications:\n            raise ValueError(\"Application %s does not exist on this server\" % app_path)\n        return self._applications[app_path].get_session(session_id)",
    "docstring": "Get an active a session by name application path and session ID.\n\n        Args:\n            app_path (str) :\n                The configured application path for the application to return\n                a session for.\n\n            session_id (str) :\n                The session ID of the session to retrieve.\n\n        Returns:\n            ServerSession"
  },
  {
    "code": "def _get_kmeans_lookup_table_and_weight(nbits, w, init='k-means++', tol=1e-2, n_init=1, rand_seed=0):\n    if _HAS_SKLEARN:\n        from sklearn.cluster import KMeans\n    else:\n        raise Exception('sklearn package required for k-means quantization')\n    units = _np.prod(w.shape)\n    lut_len = 1 << nbits\n    n_clusters = units if (units < lut_len) else lut_len\n    wf = w.reshape(-1, 1)\n    kmeans = KMeans(n_clusters=n_clusters, init=init, tol=tol, n_init=n_init, random_state=rand_seed).fit(wf)\n    wq = kmeans.labels_[:units]\n    lut = _np.zeros(lut_len)\n    lut[:n_clusters] = kmeans.cluster_centers_.flatten()\n    return lut, wq",
    "docstring": "Generate K-Means lookup table given a weight parameter field\n\n    :param nbits:\n        Number of bits for quantization\n\n    :param w:\n        Weight as numpy array\n\n    Returns\n    -------\n    lut: numpy.array\n        Lookup table, numpy array of shape (1 << nbits, );\n    wq: numpy.array\n        Quantized weight of type numpy.uint8"
  },
  {
    "code": "def get_response_page(request, return_type, template_location, response_page_type):\n    try:\n        page = models.ResponsePage.objects.get(\n            is_active=True,\n            type=response_page_type,\n        )\n        template = loader.get_template(template_location)\n        content_type = None\n        body = template.render(\n            RequestContext(request, {'request_path': request.path, 'page': page, })\n        )\n        return return_type(body, content_type=content_type)\n    except models.ResponsePage.DoesNotExist:\n        return None",
    "docstring": "Helper function to get an appropriate response page if it exists.\n\n    This function is not designed to be used directly as a view. It is\n    a helper function which can be called to check if a ResponsePage\n    exists for a ResponsePage type (which is also active).\n\n    :param request:\n    :param return_type:\n    :param template_location:\n    :param response_page_type:\n    :return:"
  },
  {
    "code": "def load_filter_plugins(entrypoint_group: str) -> Iterable[Filter]:\n    global loaded_filter_plugins\n    enabled_plugins: List[str] = []\n    config = BandersnatchConfig().config\n    try:\n        config_blacklist_plugins = config[\"blacklist\"][\"plugins\"]\n        split_plugins = config_blacklist_plugins.split(\"\\n\")\n        if \"all\" in split_plugins:\n            enabled_plugins = [\"all\"]\n        else:\n            for plugin in split_plugins:\n                if not plugin:\n                    continue\n                enabled_plugins.append(plugin)\n    except KeyError:\n        pass\n    cached_plugins = loaded_filter_plugins.get(entrypoint_group)\n    if cached_plugins:\n        return cached_plugins\n    plugins = set()\n    for entry_point in pkg_resources.iter_entry_points(group=entrypoint_group):\n        plugin_class = entry_point.load()\n        plugin_instance = plugin_class()\n        if \"all\" in enabled_plugins or plugin_instance.name in enabled_plugins:\n            plugins.add(plugin_instance)\n    loaded_filter_plugins[entrypoint_group] = list(plugins)\n    return plugins",
    "docstring": "Load all blacklist plugins that are registered with pkg_resources\n\n    Parameters\n    ==========\n    entrypoint_group: str\n        The entrypoint group name to load plugins from\n\n    Returns\n    =======\n    List of Blacklist:\n        A list of objects derived from the Blacklist class"
  },
  {
    "code": "def first(self):\n        results = self.rpc_model.search_read(\n            self.domain, None, 1, self._order_by, self.fields,\n            context=self.context\n        )\n        return results and results[0] or None",
    "docstring": "Return the first result of this Query or None if the result\n        doesn't contain any row."
  },
  {
    "code": "def load_global_config(config_path):\n    config = configparser.RawConfigParser()\n    if os.path.exists(config_path):\n        logger.debug(\"Checking and setting global parameters...\")\n        config.read(config_path)\n    else:\n        _initial_run()\n        logger.info(\"Unable to find a global sprinter configuration!\")\n        logger.info(\"Creating one now. Please answer some questions\" +\n                    \" about what you would like sprinter to do.\")\n        logger.info(\"\")\n    if not config.has_section('global'):\n        config.add_section('global')\n    configure_config(config)\n    write_config(config, config_path)\n    return config",
    "docstring": "Load a global configuration object, and query for any required variables along the way"
  },
  {
    "code": "def check_data_health(self, props=[], element=None):\n        r\n        health = HealthDict()\n        if props == []:\n            props = self.props(element)\n        else:\n            if type(props) == str:\n                props = [props]\n        for item in props:\n            health[item] = []\n            if self[item].dtype == 'O':\n                health[item] = 'No checks on object'\n            elif sp.sum(sp.isnan(self[item])) > 0:\n                health[item] = 'Has NaNs'\n            elif sp.shape(self[item])[0] != self._count(item.split('.')[0]):\n                health[item] = 'Wrong Length'\n        return health",
    "docstring": "r\"\"\"\n        Check the health of pore and throat data arrays.\n\n        Parameters\n        ----------\n        element : string, optional\n            Can be either 'pore' or 'throat', which will limit the checks to\n            only those data arrays.\n\n        props : list of pore (or throat) properties, optional\n            If given, will limit the health checks to only the specfied\n            properties.  Also useful for checking existance.\n\n        Returns\n        -------\n        Returns a HealthDict object which a basic dictionary with an added\n        ``health`` attribute that is True is all entries in the dict are\n        deemed healthy (empty lists), or False otherwise.\n\n        Examples\n        --------\n        >>> import openpnm\n        >>> pn = openpnm.network.Cubic(shape=[5, 5, 5])\n        >>> h = pn.check_data_health()\n        >>> h.health\n        True"
  },
  {
    "code": "def material_to_texture(material):\n    if hasattr(material, 'image'):\n        img = material.image\n    else:\n        img = material.baseColorTexture\n    if img is None:\n        return None\n    with util.BytesIO() as f:\n        img.save(f, format='png')\n        f.seek(0)\n        gl_image = pyglet.image.load(filename='.png', file=f)\n    texture = gl_image.get_texture()\n    return texture",
    "docstring": "Convert a trimesh.visual.texture.Material object into\n    a pyglet- compatible texture object.\n\n    Parameters\n    --------------\n    material : trimesh.visual.texture.Material\n      Material to be converted\n\n    Returns\n    ---------------\n    texture : pyglet.image.Texture\n      Texture loaded into pyglet form"
  },
  {
    "code": "def visit_ExtSlice(self, node: ast.ExtSlice) -> Tuple[Any, ...]:\n        result = tuple(self.visit(node=dim) for dim in node.dims)\n        self.recomputed_values[node] = result\n        return result",
    "docstring": "Visit each dimension of the advanced slicing and assemble the dimensions in a tuple."
  },
  {
    "code": "def findSynonyms(self, word, num):\n        if not isinstance(word, basestring):\n            word = _convert_to_vector(word)\n        words, similarity = self.call(\"findSynonyms\", word, num)\n        return zip(words, similarity)",
    "docstring": "Find synonyms of a word\n\n        :param word: a word or a vector representation of word\n        :param num: number of synonyms to find\n        :return: array of (word, cosineSimilarity)\n\n        .. note:: Local use only"
  },
  {
    "code": "def sort_flavor_list(request, flavors, with_menu_label=True):\n    def get_key(flavor, sort_key):\n        try:\n            return getattr(flavor, sort_key)\n        except AttributeError:\n            LOG.warning('Could not find sort key \"%s\". Using the default '\n                        '\"ram\" instead.', sort_key)\n            return getattr(flavor, 'ram')\n    try:\n        flavor_sort = getattr(settings, 'CREATE_INSTANCE_FLAVOR_SORT', {})\n        sort_key = flavor_sort.get('key', 'ram')\n        rev = flavor_sort.get('reverse', False)\n        if not callable(sort_key):\n            def key(flavor):\n                return get_key(flavor, sort_key)\n        else:\n            key = sort_key\n        if with_menu_label:\n            flavor_list = [(flavor.id, '%s' % flavor.name)\n                           for flavor in sorted(flavors, key=key, reverse=rev)]\n        else:\n            flavor_list = sorted(flavors, key=key, reverse=rev)\n        return flavor_list\n    except Exception:\n        exceptions.handle(request,\n                          _('Unable to sort instance flavors.'))\n        return []",
    "docstring": "Utility method to sort a list of flavors.\n\n    By default, returns the available flavors, sorted by RAM usage (ascending).\n    Override these behaviours with a ``CREATE_INSTANCE_FLAVOR_SORT`` dict\n    in ``local_settings.py``."
  },
  {
    "code": "def get(self):\n        attrs = (\"networks\",\n                 \"security_groups\",\n                 \"floating_ips\",\n                 \"routers\",\n                 \"internet_gateways\")\n        for attr in attrs:\n            setattr(self, attr, eval(\"self.get_{}()\". format(attr)))",
    "docstring": "Get quota from Cloud Provider."
  },
  {
    "code": "def unsubscribe(self, destination=None, id=None, headers=None, **keyword_headers):\n        assert id is not None or destination is not None, \"'id' or 'destination' is required\"\n        headers = utils.merge_headers([headers, keyword_headers])\n        if id:\n            headers[HDR_ID] = id\n        if destination:\n            headers[HDR_DESTINATION] = destination\n        self.send_frame(CMD_UNSUBSCRIBE, headers)",
    "docstring": "Unsubscribe from a destination by either id or the destination name.\n\n        :param str destination: the name of the topic or queue to unsubscribe from\n        :param str id: the unique identifier of the topic or queue to unsubscribe from\n        :param dict headers: a map of any additional headers the broker requires\n        :param keyword_headers: any additional headers the broker requires"
  },
  {
    "code": "def find_saas_endurance_space_price(package, size, tier_level):\n    if tier_level != 0.25:\n        tier_level = int(tier_level)\n    key_name = 'STORAGE_SPACE_FOR_{0}_IOPS_PER_GB'.format(tier_level)\n    key_name = key_name.replace(\".\", \"_\")\n    for item in package['items']:\n        if key_name not in item['keyName']:\n            continue\n        if 'capacityMinimum' not in item or 'capacityMaximum' not in item:\n            continue\n        capacity_minimum = int(item['capacityMinimum'])\n        capacity_maximum = int(item['capacityMaximum'])\n        if size < capacity_minimum or size > capacity_maximum:\n            continue\n        price_id = _find_price_id(item['prices'], 'performance_storage_space')\n        if price_id:\n            return price_id\n    raise ValueError(\"Could not find price for endurance storage space\")",
    "docstring": "Find the SaaS endurance storage space price for the size and tier\n\n    :param package: The Storage As A Service product package\n    :param size: The volume size for which a price is desired\n    :param tier_level: The endurance tier for which a price is desired\n    :return: Returns the price for the size and tier, or an error if not found"
  },
  {
    "code": "def get_command_from_result(script, result, debug=False):\n    if not debug:\n        command = \"python waf --run \\\"\" + script + \" \" + \" \".join(\n            ['--%s=%s' % (param, value) for param, value in\n             result['params'].items()]) + \"\\\"\"\n    else:\n        command = \"python waf --run \" + script + \" --command-template=\\\"\" +\\\n            \"gdb --args %s \" + \" \".join(['--%s=%s' % (param, value) for\n                                         param, value in\n                                         result['params'].items()]) + \"\\\"\"\n    return command",
    "docstring": "Return the command that is needed to obtain a certain result.\n\n    Args:\n        params (dict): Dictionary containing parameter: value pairs.\n        debug (bool): Whether the command should include the debugging\n            template."
  },
  {
    "code": "def generate_security_data(self):\n        timestamp = int(time.time())\n        security_dict = {\n            'content_type': str(self.target_object._meta),\n            'object_pk': str(self.target_object._get_pk_val()),\n            'timestamp': str(timestamp),\n            'security_hash': self.initial_security_hash(timestamp),\n        }\n        return security_dict",
    "docstring": "Generate a dict of security data for \"initial\" data."
  },
  {
    "code": "def unsticky(self):\n        url = self.reddit_session.config['sticky_submission']\n        data = {'id': self.fullname, 'state': False}\n        return self.reddit_session.request_json(url, data=data)",
    "docstring": "Unsticky this post.\n\n        :returns: The json response from the server"
  },
  {
    "code": "def has_access(user, required_roles, match_all=True):\n    if ROLE_ADMIN in user.roles:\n        return True\n    if isinstance(required_roles, str):\n        if required_roles in user.roles:\n            return True\n        return False\n    if match_all:\n        for role in required_roles:\n            if role not in user.roles:\n                return False\n        return True\n    else:\n        for role in required_roles:\n            if role in user.roles:\n                return True\n        return False",
    "docstring": "Check if the user meets the role requirements. If mode is set to AND, all the provided roles must apply\n\n    Args:\n        user (:obj:`User`): User object\n        required_roles (`list` of `str`): List of roles that the user must have applied\n        match_all (`bool`): If true, all the required_roles must be applied to the user, else any one match will\n         return `True`\n\n    Returns:\n        `bool`"
  },
  {
    "code": "def get_settings():\n    settings = {}\n    for config_file in config_files():\n        config_contents = load_config(config_file)\n        if config_contents is not None:\n            settings = deep_merge(settings, config_contents)\n    return settings",
    "docstring": "Get all currently loaded settings."
  },
  {
    "code": "def wafer_form_helper(context, helper_name):\n    request = context.request\n    module, class_name = helper_name.rsplit('.', 1)\n    if module not in sys.modules:\n        __import__(module)\n    mod = sys.modules[module]\n    class_ = getattr(mod, class_name)\n    return class_(request=request)",
    "docstring": "Find the specified Crispy FormHelper and instantiate it.\n    Handy when you are crispyifying other apps' forms."
  },
  {
    "code": "def deprecate_option(key, msg=None, rkey=None, removal_ver=None):\n    key = key.lower()\n    if key in _deprecated_options:\n        msg = \"Option '{key}' has already been defined as deprecated.\"\n        raise OptionError(msg.format(key=key))\n    _deprecated_options[key] = DeprecatedOption(key, msg, rkey, removal_ver)",
    "docstring": "Mark option `key` as deprecated, if code attempts to access this option,\n    a warning will be produced, using `msg` if given, or a default message\n    if not.\n    if `rkey` is given, any access to the key will be re-routed to `rkey`.\n\n    Neither the existence of `key` nor that if `rkey` is checked. If they\n    do not exist, any subsequence access will fail as usual, after the\n    deprecation warning is given.\n\n    Parameters\n    ----------\n    key - the name of the option to be deprecated. must be a fully-qualified\n          option name (e.g \"x.y.z.rkey\").\n\n    msg - (Optional) a warning message to output when the key is referenced.\n          if no message is given a default message will be emitted.\n\n    rkey - (Optional) the name of an option to reroute access to.\n           If specified, any referenced `key` will be re-routed to `rkey`\n           including set/get/reset.\n           rkey must be a fully-qualified option name (e.g \"x.y.z.rkey\").\n           used by the default message if no `msg` is specified.\n\n    removal_ver - (Optional) specifies the version in which this option will\n                  be removed. used by the default message if no `msg`\n                  is specified.\n\n    Returns\n    -------\n    Nothing\n\n    Raises\n    ------\n    OptionError - if key has already been deprecated."
  },
  {
    "code": "def refresh(self, module=None):\n        module = module._mdl if module is not None else ffi.NULL\n        lib.EnvRefreshAgenda(self._env, module)",
    "docstring": "Recompute the salience values of the Activations on the Agenda\n        and then reorder the agenda.\n\n        The Python equivalent of the CLIPS refresh-agenda command.\n\n        If no Module is specified, the current one is used."
  },
  {
    "code": "def get_tuple_version(name,\n                      default=DEFAULT_TUPLE_NOT_FOUND,\n                      allow_ambiguous=True):\n    def _prefer_int(x):\n        try:\n            return int(x)\n        except ValueError:\n            return x\n    version = get_string_version(name, default=default,\n                                 allow_ambiguous=allow_ambiguous)\n    if isinstance(version, tuple):\n        return version\n    return tuple(map(_prefer_int, version.split('.')))",
    "docstring": "Get tuple version from installed package information for easy handling.\n\n    It will return :attr:`default` value when the named package is not\n    installed.\n\n    Parameters\n    -----------\n    name : string\n        An application name used to install via setuptools.\n    default : tuple\n        A default returning value used when the named application is not\n        installed yet\n    allow_ambiguous : boolean\n        ``True`` for allowing ambiguous version information.\n\n    Returns\n    --------\n    string\n        A version tuple\n\n    Examples\n    --------\n    >>> v = get_tuple_version('app_version', allow_ambiguous=True)\n    >>> len(v) >= 3\n    True\n    >>> isinstance(v[0], int)\n    True\n    >>> isinstance(v[1], int)\n    True\n    >>> isinstance(v[2], int)\n    True\n    >>> get_tuple_version('distribution_which_is_not_installed')\n    (0, 0, 0)"
  },
  {
    "code": "def fetch_31(self):\n        today = datetime.datetime.today()\n        before = today - datetime.timedelta(days=60)\n        self.fetch_from(before.year, before.month)\n        self.data = self.data[-31:]\n        return self.data",
    "docstring": "Fetch 31 days data"
  },
  {
    "code": "def _get_add_trustee_cmd(self, trustee):\n        trustee_info = pollster(get_device_info)(trustee)\n        username = trustee._meta_data['username']\n        password = trustee._meta_data['password']\n        return 'tmsh::modify cm trust-domain Root ca-devices add ' \\\n            '\\\\{ %s \\\\} name %s username %s password %s' % \\\n            (trustee_info.managementIp, trustee_info.name, username, password)",
    "docstring": "Get tmsh command to add a trusted device.\n\n        :param trustee: ManagementRoot object -- device to add as trusted\n        :returns: str -- tmsh command to add trustee"
  },
  {
    "code": "def create_continuous_query(self, name, select, database=None,\n                                resample_opts=None):\n        r\n        query_string = (\n            \"CREATE CONTINUOUS QUERY {0} ON {1}{2} BEGIN {3} END\"\n        ).format(quote_ident(name), quote_ident(database or self._database),\n                 ' RESAMPLE ' + resample_opts if resample_opts else '', select)\n        self.query(query_string)",
    "docstring": "r\"\"\"Create a continuous query for a database.\n\n        :param name: the name of continuous query to create\n        :type name: str\n        :param select: select statement for the continuous query\n        :type select: str\n        :param database: the database for which the continuous query is\n            created. Defaults to current client's database\n        :type database: str\n        :param resample_opts: resample options\n        :type resample_opts: str\n\n        :Example:\n\n        ::\n\n            >> select_clause = 'SELECT mean(\"value\") INTO \"cpu_mean\" ' \\\n            ...                 'FROM \"cpu\" GROUP BY time(1m)'\n            >> client.create_continuous_query(\n            ...     'cpu_mean', select_clause, 'db_name', 'EVERY 10s FOR 2m'\n            ... )\n            >> client.get_list_continuous_queries()\n            [\n                {\n                    'db_name': [\n                        {\n                            'name': 'cpu_mean',\n                            'query': 'CREATE CONTINUOUS QUERY \"cpu_mean\" '\n                                    'ON \"db_name\" '\n                                    'RESAMPLE EVERY 10s FOR 2m '\n                                    'BEGIN SELECT mean(\"value\") '\n                                    'INTO \"cpu_mean\" FROM \"cpu\" '\n                                    'GROUP BY time(1m) END'\n                        }\n                    ]\n                }\n            ]"
  },
  {
    "code": "def has_autolog(self, user_id):\n        try:\n            with open(\"local/init\", \"rb\") as f:\n                s = f.read()\n                s = security.protege_data(s, False)\n                self.autolog = json.loads(s).get(\"autolog\", {})\n        except FileNotFoundError:\n            return\n        mdp = self.autolog.get(user_id, None)\n        return mdp",
    "docstring": "Read auto-connection parameters and returns local password or None"
  },
  {
    "code": "def convert_celeba_aligned_cropped(directory, output_directory,\n                                   output_filename=OUTPUT_FILENAME):\n    output_path = os.path.join(output_directory, output_filename)\n    h5file = _initialize_conversion(directory, output_path, (218, 178))\n    features_dataset = h5file['features']\n    image_file_path = os.path.join(directory, IMAGE_FILE)\n    with zipfile.ZipFile(image_file_path, 'r') as image_file:\n        with progress_bar('images', NUM_EXAMPLES) as bar:\n            for i in range(NUM_EXAMPLES):\n                image_name = 'img_align_celeba/{:06d}.jpg'.format(i + 1)\n                features_dataset[i] = numpy.asarray(\n                    Image.open(\n                        image_file.open(image_name, 'r'))).transpose(2, 0, 1)\n                bar.update(i + 1)\n    h5file.flush()\n    h5file.close()\n    return (output_path,)",
    "docstring": "Converts the aligned and cropped CelebA dataset to HDF5.\n\n    Converts the CelebA dataset to an HDF5 dataset compatible with\n    :class:`fuel.datasets.CelebA`. The converted dataset is saved as\n    'celeba_aligned_cropped.hdf5'.\n\n    It assumes the existence of the following files:\n\n    * `img_align_celeba.zip`\n    * `list_attr_celeba.txt`\n\n    Parameters\n    ----------\n    directory : str\n        Directory in which input files reside.\n    output_directory : str\n        Directory in which to save the converted dataset.\n    output_filename : str, optional\n        Name of the saved dataset. Defaults to\n        'celeba_aligned_cropped.hdf5'.\n\n    Returns\n    -------\n    output_paths : tuple of str\n        Single-element tuple containing the path to the converted\n        dataset."
  },
  {
    "code": "def get_radians(self):\n        if not self: raise NullVectorError()\n        return math.atan2(self.y, self.x)",
    "docstring": "Return the angle between this vector and the positive x-axis \n        measured in radians. Result will be between -pi and pi."
  },
  {
    "code": "def form_valid(self, form):\n        self.object = form.save(commit=False)\n        self.pre_save()\n        self.object.save()\n        if hasattr(form, 'save_m2m'):\n            form.save_m2m()\n        self.post_save()\n        if self.request.is_ajax():\n            return self.render_json_response(self.get_success_result())\n        return HttpResponseRedirect(self.get_success_url())",
    "docstring": "If the request is ajax, save the form and return a json response.\n        Otherwise return super as expected."
  },
  {
    "code": "def deliver_message(self, timeout=None):\n        deliver_task = asyncio.ensure_future(self._handler.mqtt_deliver_next_message(), loop=self._loop)\n        self.client_tasks.append(deliver_task)\n        self.logger.debug(\"Waiting message delivery\")\n        done, pending = yield from asyncio.wait([deliver_task], loop=self._loop, return_when=asyncio.FIRST_EXCEPTION, timeout=timeout)\n        if deliver_task in done:\n            if deliver_task.exception() is not None:\n                raise deliver_task.exception()\n            self.client_tasks.pop()\n            return deliver_task.result()\n        else:\n            deliver_task.cancel()\n            raise asyncio.TimeoutError",
    "docstring": "Deliver next received message.\n\n            Deliver next message received from the broker. If no message is available, this methods waits until next message arrives or ``timeout`` occurs.\n\n            This method is a *coroutine*.\n\n            :param timeout: maximum number of seconds to wait before returning. If timeout is not specified or None, there is no limit to the wait time until next message arrives.\n            :return: instance of :class:`hbmqtt.session.ApplicationMessage` containing received message information flow.\n            :raises: :class:`asyncio.TimeoutError` if timeout occurs before a message is delivered"
  },
  {
    "code": "def get_all_vpn_gateways(self, vpn_gateway_ids=None, filters=None):\n        params = {}\n        if vpn_gateway_ids:\n            self.build_list_params(params, vpn_gateway_ids, 'VpnGatewayId')\n        if filters:\n            i = 1\n            for filter in filters:\n                params[('Filter.%d.Name' % i)] = filter[0]\n                params[('Filter.%d.Value.1')] = filter[1]\n                i += 1\n        return self.get_list('DescribeVpnGateways', params, [('item', VpnGateway)])",
    "docstring": "Retrieve information about your VpnGateways.  You can filter results to\n        return information only about those VpnGateways that match your search\n        parameters.  Otherwise, all VpnGateways associated with your account\n        are returned.\n\n        :type vpn_gateway_ids: list\n        :param vpn_gateway_ids: A list of strings with the desired VpnGateway ID's\n\n        :type filters: list of tuples\n        :param filters: A list of tuples containing filters.  Each tuple\n                        consists of a filter key and a filter value.\n                        Possible filter keys are:\n\n                        - *state*, the state of the VpnGateway\n                          (pending,available,deleting,deleted)\n                        - *type*, the type of customer gateway (ipsec.1)\n                        - *availabilityZone*, the Availability zone the\n                          VPN gateway is in.\n\n        :rtype: list\n        :return: A list of :class:`boto.vpc.customergateway.VpnGateway`"
  },
  {
    "code": "def loads(s, filename=None, loader=None, implicit_tuple=True, env={}, schema=None):\n  ast = reads(s, filename=filename, loader=loader, implicit_tuple=implicit_tuple)\n  if not isinstance(env, framework.Environment):\n    env = framework.Environment(dict(_default_bindings, **env))\n  obj = framework.eval(ast, env)\n  return mod_schema.validate(obj, schema)",
    "docstring": "Load and evaluate a GCL expression from a string."
  },
  {
    "code": "def showDescription( self ):\r\n        plugin = self.currentPlugin()\r\n        if ( not plugin ):\r\n            self.uiDescriptionTXT.setText('')\r\n        else:\r\n            self.uiDescriptionTXT.setText(plugin.description())",
    "docstring": "Shows the description for the current plugin in the interface."
  },
  {
    "code": "def _update_data(self, *data_dict, **kwargs):\n        self.errors = {}\n        for data in data_dict:\n            if not isinstance(data, dict):\n                raise AssertionError(\n                    f'Positional argument \"{data}\" passed must be a dict.'\n                    f'This argument serves as a template for loading common '\n                    f'values.'\n                )\n            for field_name, val in data.items():\n                setattr(self, field_name, val)\n        for field_name, val in kwargs.items():\n            setattr(self, field_name, val)\n        if self.errors:\n            raise ValidationError(self.errors)",
    "docstring": "A private method to process and update entity values correctly.\n\n        :param data: A dictionary of values to be updated for the entity\n        :param kwargs: keyword arguments with key-value pairs to be updated"
  },
  {
    "code": "def drag(self, dragFrom=None):\n        if dragFrom is None:\n            dragFrom = self._lastMatch or self\n        dragFromLocation = None\n        if isinstance(dragFrom, Pattern):\n            dragFromLocation = self.find(dragFrom).getTarget()\n        elif isinstance(dragFrom, basestring):\n            dragFromLocation = self.find(dragFrom).getTarget()\n        elif isinstance(dragFrom, Match):\n            dragFromLocation = dragFrom.getTarget()\n        elif isinstance(dragFrom, Region):\n            dragFromLocation = dragFrom.getCenter()\n        elif isinstance(dragFrom, Location):\n            dragFromLocation = dragFrom\n        else:\n            raise TypeError(\"drag expected dragFrom to be Pattern, String, Match, Region, or Location object\")\n        Mouse.moveSpeed(dragFromLocation, Settings.MoveMouseDelay)\n        time.sleep(Settings.DelayBeforeMouseDown)\n        Mouse.buttonDown()\n        Debug.history(\"Began drag at {}\".format(dragFromLocation))",
    "docstring": "Starts a dragDrop operation.\n\n        Moves the cursor to the target location and clicks the mouse in preparation to drag\n        a screen element"
  },
  {
    "code": "def normalizeBoolean(value):\n    if isinstance(value, int) and value in (0, 1):\n        value = bool(value)\n    if not isinstance(value, bool):\n        raise ValueError(\"Boolean values must be True or False, not '%s'.\"\n                         % value)\n    return value",
    "docstring": "Normalizes a boolean.\n\n    * **value** must be an ``int`` with value of 0 or 1, or a ``bool``.\n    * Returned value will be a boolean."
  },
  {
    "code": "def build_config(config, filename=None):\n    for clr in ('color', 'background'):\n        val = config.pop(clr, None)\n        if val in ('transparent', 'trans'):\n            config[clr] = None\n        elif val:\n            config[clr] = val\n    for name in ('svgid', 'svgclass', 'lineclass'):\n        if config.get(name, None) is None:\n            config.pop(name, None)\n    if config.pop('no_classes', False):\n        config['svgclass'] = None\n        config['lineclass'] = None\n    if filename is not None:\n        ext = filename[filename.rfind('.') + 1:].lower()\n        if ext == 'svgz':\n            ext = 'svg'\n        supported_args = _EXT_TO_KW_MAPPING.get(ext, ())\n        for k in list(config):\n            if k not in supported_args:\n                del config[k]\n    return config",
    "docstring": "\\\n    Builds a configuration and returns it. The config contains only keywords,\n    which are supported by the serializer. Unsupported values are ignored."
  },
  {
    "code": "def mpi(value):\n    bits = value.bit_length()\n    data_size = (bits + 7) // 8\n    data_bytes = bytearray(data_size)\n    for i in range(data_size):\n        data_bytes[i] = value & 0xFF\n        value = value >> 8\n    data_bytes.reverse()\n    return struct.pack('>H', bits) + bytes(data_bytes)",
    "docstring": "Serialize multipresicion integer using GPG format."
  },
  {
    "code": "def get_iobuf(self, p, x, y):\n        return self.get_iobuf_bytes(p, x, y).decode(\"utf-8\")",
    "docstring": "Read the messages ``io_printf``'d into the ``IOBUF`` buffer on a\n        specified core.\n\n        See also: :py:meth:`.get_iobuf_bytes` which returns the undecoded raw\n        bytes in the ``IOBUF``. Useful if the IOBUF contains non-text or\n        non-UTF-8 encoded text.\n\n        Returns\n        -------\n        str\n            The string in the ``IOBUF``, decoded from UTF-8."
  },
  {
    "code": "def applyJSONFilters(actions, source, format=\"\"):\n    doc = json.loads(source)\n    if 'meta' in doc:\n        meta = doc['meta']\n    elif doc[0]:\n        meta = doc[0]['unMeta']\n    else:\n        meta = {}\n    altered = doc\n    for action in actions:\n        altered = walk(altered, action, format, meta)\n    return json.dumps(altered)",
    "docstring": "Walk through JSON structure and apply filters\n\n    This:\n\n    * reads a JSON-formatted pandoc document from a source string\n    * transforms it by walking the tree and performing the actions\n    * returns a new JSON-formatted pandoc document as a string\n\n    The `actions` argument is a list of functions (see `walk`\n    for a full description).\n\n    The argument `source` is a string encoded JSON object.\n\n    The argument `format` is a string describing the output format.\n\n    Returns a the new JSON-formatted pandoc document."
  },
  {
    "code": "def request(self, tree, **kwargs):\n        apirequest = lxml.etree.tostring(\n            E.openXML(\n                E.credentials(\n                    E.username(self.username),\n                    OE('password', self.password),\n                    OE('hash', self.password_hash),\n                ),\n                tree\n            ),\n            method='c14n'\n        )\n        try:\n            apiresponse = self.session.post(self.url, data=apirequest)\n            apiresponse.raise_for_status()\n        except requests.RequestException as e:\n            raise ServiceUnavailable(str(e))\n        tree = lxml.objectify.fromstring(apiresponse.content)\n        if tree.reply.code == 0:\n            return Response(tree)\n        else:\n            klass = from_code(tree.reply.code)\n            desc = tree.reply.desc\n            code = tree.reply.code\n            data = getattr(tree.reply, 'data', '')\n            raise klass(u\"{0} ({1}) {2}\".format(desc, code, data), code)",
    "docstring": "Construct a new request with the given tree as its contents, then ship\n        it to the OpenProvider API."
  },
  {
    "code": "def make_multisig_segwit_wallet( m, n ):\n    pks = []\n    for i in xrange(0, n):\n        pk = BitcoinPrivateKey(compressed=True).to_wif()\n        pks.append(pk)\n    return make_multisig_segwit_info(m, pks)",
    "docstring": "Create a bundle of information\n    that can be used to generate an\n    m-of-n multisig witness script."
  },
  {
    "code": "def codepoint_included(self, codepoint):\n        if self.codepoints == None:\n            return True\n        for cp in self.codepoints:\n            mismatch = False\n            for i in range(len(cp)):\n                if (cp[i] is not None) and (cp[i] != codepoint[i]):\n                    mismatch = True\n                    break\n            if not mismatch:\n                return True\n        return False",
    "docstring": "Check if codepoint matches any of the defined codepoints."
  },
  {
    "code": "def probes(self, **kwargs):\n        for key in kwargs:\n            if key not in ['limit', 'offset', 'onlyactive', 'includedeleted']:\n                sys.stderr.write(\"'%s'\" % key + ' is not a valid argument ' +\n                                 'of probes()\\n')\n        return self.request(\"GET\", \"probes\", kwargs).json()['probes']",
    "docstring": "Returns a list of all Pingdom probe servers\n\n        Parameters:\n\n            * limit -- Limits the number of returned probes to the specified\n                quantity\n                    Type: Integer\n\n            * offset -- Offset for listing (requires limit).\n                    Type: Integer\n                    Default: 0\n\n            * onlyactive -- Return only active probes\n                    Type: Boolean\n                    Default: False\n\n            * includedeleted -- Include old probes that are no longer in use\n                    Type: Boolean\n                    Default: False\n\n        Returned structure:\n        [\n            {\n                'id'        : <Integer> Unique probe id\n                'country'   : <String> Country\n                'city'      : <String> City\n                'name'      : <String> Name\n                'active'    : <Boolean> True if probe is active\n                'hostname'  : <String> DNS name\n                'ip'        : <String> IP address\n                'countryiso': <String> Country ISO code\n            },\n            ...\n        ]"
  },
  {
    "code": "def register_resource(self, viewset, namespace=None):\n        try:\n            serializer = viewset.serializer_class()\n            resource_key = serializer.get_resource_key()\n            resource_name = serializer.get_name()\n            path_name = serializer.get_plural_name()\n        except:\n            import traceback\n            traceback.print_exc()\n            raise Exception(\n                \"Failed to extract resource name from viewset: '%s'.\"\n                \" It, or its serializer, may not be DREST-compatible.\" % (\n                    viewset\n                )\n            )\n        if namespace:\n            namespace = namespace.rstrip('/') + '/'\n        base_path = namespace or ''\n        base_path = r'%s' % base_path + path_name\n        self.register(base_path, viewset)\n        if resource_key in resource_map:\n            raise Exception(\n                \"The resource '%s' has already been mapped to '%s'.\"\n                \" Each resource can only be mapped to one canonical\"\n                \" path. \" % (\n                    resource_key,\n                    resource_map[resource_key]['path']\n                )\n            )\n        resource_map[resource_key] = {\n            'path': base_path,\n            'viewset': viewset\n        }\n        if resource_name in resource_name_map:\n            resource_key = resource_name_map[resource_name]\n            raise Exception(\n                \"The resource name '%s' has already been mapped to '%s'.\"\n                \" A resource name can only be used once.\" % (\n                    resource_name,\n                    resource_map[resource_key]['path']\n                )\n            )\n        resource_name_map[resource_name] = resource_key",
    "docstring": "Register a viewset that should be considered the canonical\n        endpoint for a particular resource. In addition to generating\n        and registering the route, it adds the route in a reverse map\n        to allow DREST to build the canonical URL for a given resource.\n\n        Arguments:\n            viewset - viewset class, should have `serializer_class` attr.\n            namespace - (optional) URL namespace, e.g. 'v3'."
  },
  {
    "code": "def get_threats_lists(self):\n        response = self.service.threatLists().list().execute()\n        self.set_wait_duration(response.get('minimumWaitDuration'))\n        return response['threatLists']",
    "docstring": "Retrieve all available threat lists"
  },
  {
    "code": "def _evaluate_expressions(self, expression_engine, step_id, values, context):\n        if expression_engine is None:\n            return values\n        processed = {}\n        for name, value in values.items():\n            if isinstance(value, str):\n                value = value.strip()\n                try:\n                    expression = expression_engine.get_inline_expression(value)\n                    if expression is not None:\n                        value = expression_engine.evaluate_inline(expression, context)\n                    else:\n                        value = expression_engine.evaluate_block(value, context)\n                except EvaluationError as error:\n                    raise ExecutionError('Error while evaluating expression for step \"{}\":\\n{}'.format(\n                        step_id, error\n                    ))\n            elif isinstance(value, dict):\n                value = self._evaluate_expressions(expression_engine, step_id, value, context)\n            processed[name] = value\n        return processed",
    "docstring": "Recursively evaluate expressions in a dictionary of values."
  },
  {
    "code": "def parse_crop(self, crop, original_size, size):\n        if crop is None:\n            return None\n        crop = crop.split(' ')\n        if len(crop) == 1:\n            crop = crop[0]\n            x_crop = 50\n            y_crop = 50\n            if crop in CROP_ALIASES['x']:\n                x_crop = CROP_ALIASES['x'][crop]\n            elif crop in CROP_ALIASES['y']:\n                y_crop = CROP_ALIASES['y'][crop]\n        x_offset = self.calculate_offset(x_crop, original_size[0], size[0])\n        y_offset = self.calculate_offset(y_crop, original_size[1], size[1])\n        return int(x_offset), int(y_offset)",
    "docstring": "Parses crop into a tuple usable by the crop function.\n\n        :param crop: String with the crop settings.\n        :param original_size: A tuple of size of the image that should be cropped.\n        :param size: A tuple of the wanted size.\n        :return: Tuple of two integers with crop settings\n        :rtype: tuple"
  },
  {
    "code": "def delete_color_scheme_stack(self, scheme_name):\n        self.set_scheme(scheme_name)\n        widget = self.stack.currentWidget()\n        self.stack.removeWidget(widget)\n        index = self.order.index(scheme_name)\n        self.order.pop(index)",
    "docstring": "Remove stack widget by 'scheme_name'."
  },
  {
    "code": "def hexedit(pktlist):\n    f = get_temp_file()\n    wrpcap(f, pktlist)\n    with ContextManagerSubprocess(\"hexedit()\", conf.prog.hexedit):\n        subprocess.call([conf.prog.hexedit, f])\n    pktlist = rdpcap(f)\n    os.unlink(f)\n    return pktlist",
    "docstring": "Run hexedit on a list of packets, then return the edited packets."
  },
  {
    "code": "def from_sqlite(cls, database_path, base_url, version='auto', client_id='ghost-admin'):\n        import os\n        import sqlite3\n        fd = os.open(database_path, os.O_RDONLY)\n        connection = sqlite3.connect('/dev/fd/%d' % fd)\n        os.close(fd)\n        try:\n            row = connection.execute(\n                'SELECT secret FROM clients WHERE slug = ?',\n                (client_id,)\n            ).fetchone()\n            if row:\n                return cls(\n                    base_url, version=version,\n                    client_id=client_id, client_secret=row[0]\n                )\n            else:\n                raise GhostException(401, [{\n                    'errorType': 'InternalError',\n                    'message': 'No client_secret found for client_id: %s' % client_id\n                }])\n        finally:\n            connection.close()",
    "docstring": "Initialize a new Ghost API client,\n        reading the client ID and secret from the SQlite database.\n\n        :param database_path: The path to the database file.\n        :param base_url: The base url of the server\n        :param version: The server version to use (default: `auto`)\n        :param client_id: The client ID to look for in the database\n        :return: A new Ghost API client instance"
  },
  {
    "code": "def generate_contentinfo_from_channeldir(self, args, options):\n        LOGGER.info('Generating Content.csv rows folders and file in channeldir')\n        file_path = get_metadata_file_path(self.channeldir, self.contentinfo)\n        with open(file_path, 'a') as csv_file:\n            csvwriter = csv.DictWriter(csv_file, CONTENT_INFO_HEADER)\n            channeldir = args['channeldir']\n            if channeldir.endswith(os.path.sep):\n                channeldir.rstrip(os.path.sep)\n            content_folders = sorted(os.walk(channeldir))\n            _ = content_folders.pop(0)\n            for rel_path, _subfolders, filenames in content_folders:\n                LOGGER.info('processing folder ' + str(rel_path))\n                sorted_filenames = sorted(filenames)\n                self.generate_contentinfo_from_folder(csvwriter, rel_path, sorted_filenames)\n        LOGGER.info('Generted {} row for all folders and files in {}'.format(self.contentinfo, self.channeldir))",
    "docstring": "Create rows in Content.csv for each folder and file in `self.channeldir`."
  },
  {
    "code": "def coinbase_withdraw(self, amount, currency, coinbase_account_id):\n        params = {'amount': amount,\n                  'currency': currency,\n                  'coinbase_account_id': coinbase_account_id}\n        return self._send_message('post', '/withdrawals/coinbase-account',\n                                  data=json.dumps(params))",
    "docstring": "Withdraw funds to a coinbase account.\n\n        You can move funds between your Coinbase accounts and your cbpro\n        trading accounts within your daily limits. Moving funds between\n        Coinbase and cbpro is instant and free.\n\n        See AuthenticatedClient.get_coinbase_accounts() to receive\n        information regarding your coinbase_accounts.\n\n        Args:\n            amount (Decimal): The amount to withdraw.\n            currency (str): The type of currency (eg. 'BTC')\n            coinbase_account_id (str): ID of the coinbase account.\n\n        Returns:\n            dict: Information about the deposit. Example::\n                {\n                    \"id\":\"593533d2-ff31-46e0-b22e-ca754147a96a\",\n                    \"amount\":\"10.00\",\n                    \"currency\": \"BTC\",\n                }"
  },
  {
    "code": "def fromordinal(cls, ordinal):\n        if ordinal < 1:\n            raise ValueError(\"ordinal must be >= 1\")\n        return super(Week, cls).__new__(cls, *(date.fromordinal((ordinal-1) * 7 + 1).isocalendar()[:2]))",
    "docstring": "Return the week corresponding to the proleptic Gregorian ordinal,\n        where January 1 of year 1 starts the week with ordinal 1."
  },
  {
    "code": "def insert(self, inst):\n        if isinstance(inst, VD):\n            id = inst._id\n        elif isinstance(inst, VG):\n            id = inst._id\n        else:\n            raise HDF4Error(\"insrt: bad argument\")\n        index = _C.Vinsert(self._id, id)\n        _checkErr('insert', index, \"cannot insert in vgroup\")\n        return index",
    "docstring": "Insert a vdata or a vgroup in the vgroup.\n\n        Args::\n\n          inst  vdata or vgroup instance to add\n\n        Returns::\n\n          index of the inserted vdata or vgroup (0 based)\n\n        C library equivalent : Vinsert"
  },
  {
    "code": "def stack_files(files, hemi, source, target):\n  import csv\n  import os\n  import numpy as np\n  fname = \"sdist_%s_%s_%s.csv\" % (hemi, source, target)\n  filename = os.path.join(os.getcwd(),fname)\n  alldist = []\n  for dfile in files:\n    alldist.append(np.genfromtxt(dfile, delimiter=','))\n  alldist = np.array(alldist)\n  alldist.tofile(filename,\",\")\n  return filename",
    "docstring": "This function takes a list of files as input and vstacks them"
  },
  {
    "code": "def insert_text(self, text, at_end=False, error=False, prompt=False):\r\n        if at_end:\r\n            self.append_text_to_shell(text, error, prompt)\r\n        else:\r\n            ConsoleBaseWidget.insert_text(self, text)",
    "docstring": "Insert text at the current cursor position\r\n        or at the end of the command line"
  },
  {
    "code": "def _add_extra_fields(gelf_dict, record):\n        skip_list = (\n            'args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename',\n            'funcName', 'id', 'levelname', 'levelno', 'lineno', 'module',\n            'msecs', 'message', 'msg', 'name', 'pathname', 'process',\n            'processName', 'relativeCreated', 'thread', 'threadName')\n        for key, value in record.__dict__.items():\n            if key not in skip_list and not key.startswith('_'):\n                gelf_dict['_%s' % key] = value",
    "docstring": "Add extra fields to the given ``gelf_dict``\n\n        However, this does not add additional fields in to ``message_dict``\n        that are either duplicated from standard :class:`logging.LogRecord`\n        attributes, duplicated from the python logging module source\n        (e.g. ``exc_text``), or violate GLEF format (i.e. ``id``).\n\n        .. seealso::\n\n            The list of standard :class:`logging.LogRecord` attributes can be\n            found at:\n\n                http://docs.python.org/library/logging.html#logrecord-attributes\n\n        :param gelf_dict: dictionary representation of a GELF log.\n        :type gelf_dict: dict\n\n        :param record: :class:`logging.LogRecord` to extract extra fields\n            from to insert into the given ``gelf_dict``.\n        :type record: logging.LogRecord"
  },
  {
    "code": "def get_names(self):\n        names = [id for id in self.ecrm_P1_is_identified_by if id.uri == surf.ns.EFRBROO['F12_Name']]\n        self.names = []\n        for name in names:\n            for variant in name.rdfs_label:\n                self.names.append((variant.language,variant.title()))\n        return self.names",
    "docstring": "Returns a dict where key is the language and value is the name in that language.\n\n        Example:\n            {'it':\"Sofocle\"}"
  },
  {
    "code": "def get_http(base_url, function, opts):\n    url = (os.path.join(base_url, function) + '/?' + urlencode(opts))\n    data = urlopen(url)\n    if data.code != 200:\n        raise ValueError(\"Random.rg returned server code: \" + str(data.code))\n    return data.read()",
    "docstring": "HTTP request generator."
  },
  {
    "code": "def value(self):\n        v = self.file\n        return v.open(\"rb\").read() if v is not None else v",
    "docstring": "Binary value content."
  },
  {
    "code": "def preparse(output_format):\n    try:\n        return templating.preparse(output_format, lambda path: os.path.join(config.config_dir, \"templates\", path))\n    except ImportError as exc:\n        if \"tempita\" in str(exc):\n            raise error.UserError(\"To be able to use Tempita templates, install the 'tempita' package (%s)\\n\"\n                \"    Possibly USING THE FOLLOWING COMMAND:\\n\"\n                \"        %s/easy_install tempita\" % (exc, os.path.dirname(sys.executable)))\n        raise\n    except IOError as exc:\n        raise error.LoggableError(\"Cannot read template: {}\".format(exc))",
    "docstring": "Do any special processing of a template, and return the result."
  },
  {
    "code": "def _parse_mut(mut):\n    multiplier = 1\n    if mut.startswith(\"-\"):\n        mut = mut[1:]\n        multiplier = -1\n    nt = mut.strip('0123456789')\n    pos = int(mut[:-2]) * multiplier\n    return nt, pos",
    "docstring": "Parse mutation field to get position and nts."
  },
  {
    "code": "def _null_ac_sia(transition, direction, alpha=0.0):\n    return AcSystemIrreducibilityAnalysis(\n        transition=transition,\n        direction=direction,\n        alpha=alpha,\n        account=(),\n        partitioned_account=()\n    )",
    "docstring": "Return an |AcSystemIrreducibilityAnalysis| with zero |big_alpha| and\n    empty accounts."
  },
  {
    "code": "def put(self, locator = None, component = None):\n        if component == None:\n            raise Exception(\"Component cannot be null\")\n        self._lock.acquire()\n        try:\n            self._references.append(Reference(locator, component))\n        finally:\n            self._lock.release()",
    "docstring": "Puts a new reference into this reference map.\n\n        :param locator: a component reference to be added.\n\n        :param component: a locator to find the reference by."
  },
  {
    "code": "def convolve_comb_lines(lines_wave, lines_flux, sigma,\n                        crpix1, crval1, cdelt1, naxis1):\n    xwave = crval1 + (np.arange(naxis1) + 1 - crpix1) * cdelt1\n    spectrum = np.zeros(naxis1)\n    for wave, flux in zip(lines_wave, lines_flux):\n        sp_tmp = gauss_box_model(x=xwave, amplitude=flux, mean=wave,\n                                 stddev=sigma)\n        spectrum += sp_tmp\n    return xwave, spectrum",
    "docstring": "Convolve a set of lines of known wavelengths and flux.\n\n    Parameters\n    ----------\n    lines_wave : array like\n        Input array with wavelengths\n    lines_flux : array like\n        Input array with fluxes\n    sigma : float\n        Sigma of the broadening gaussian to be applied.\n    crpix1 : float\n        CRPIX1 of the desired wavelength calibration.\n    crval1 : float\n        CRVAL1 of the desired wavelength calibration.\n    cdelt1 : float\n        CDELT1 of the desired wavelength calibration.\n    naxis1 : integer\n        NAXIS1 of the output spectrum.\n\n    Returns\n    -------\n    xwave : array like\n        Array with wavelengths for the output spectrum.\n    spectrum : array like\n        Array with the expected fluxes at each pixel."
  },
  {
    "code": "def show_config(config):\n    print(\"\\nCurrent Configuration:\\n\")\n    for k, v in sorted(config.config.items()):\n        print(\"{0:15}: {1}\".format(k, v))",
    "docstring": "Show the current configuration."
  },
  {
    "code": "def enable_logging(self):\n        handler = logging.FileHandler(self.log_fname)\n        handler.setLevel(logging.INFO)\n        run_id = self.id\n        class WBFilter(logging.Filter):\n            def filter(self, record):\n                record.run_id = run_id\n                return True\n        formatter = logging.Formatter(\n            '%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d [%(run_id)s:%(filename)s:%(funcName)s():%(lineno)s] %(message)s')\n        handler.setFormatter(formatter)\n        handler.addFilter(WBFilter())\n        root = logging.getLogger()\n        root.addHandler(handler)",
    "docstring": "Enable logging to the global debug log.  This adds a run_id to the log,\n        in case of muliple processes on the same machine.\n\n        Currently no way to disable logging after it's enabled."
  },
  {
    "code": "def quantile_binning(data=None, bins=10, *, qrange=(0.0, 1.0), **kwargs) -> StaticBinning:\n    if np.isscalar(bins):\n        bins = np.linspace(qrange[0] * 100, qrange[1] * 100, bins + 1)\n    bins = np.percentile(data, bins)\n    return static_binning(bins=make_bin_array(bins), includes_right_edge=True)",
    "docstring": "Binning schema based on quantile ranges.\n\n    This binning finds equally spaced quantiles. This should lead to\n    all bins having roughly the same frequencies.\n\n    Note: weights are not (yet) take into account for calculating\n    quantiles.\n\n    Parameters\n    ----------\n    bins: sequence or Optional[int]\n        Number of bins\n    qrange: Optional[tuple]\n        Two floats as minimum and maximum quantile (default: 0.0, 1.0)\n\n    Returns\n    -------\n    StaticBinning"
  },
  {
    "code": "def group_default_invalidator(self, obj):\n        user_pks = User.objects.values_list('pk', flat=True)\n        return [('User', pk, False) for pk in user_pks]",
    "docstring": "Invalidated cached items when the Group changes."
  },
  {
    "code": "def get_best_match(text_log_error):\n    score_cut_off = 0.7\n    return (text_log_error.matches.filter(score__gt=score_cut_off)\n                                  .order_by(\"-score\", \"-classified_failure_id\")\n                                  .select_related('classified_failure')\n                                  .first())",
    "docstring": "Get the best TextLogErrorMatch for a given TextLogErrorMatch.\n\n    Matches are further filtered by the score cut off."
  },
  {
    "code": "def bypass(*inputs, copy=False):\n    if len(inputs) == 1:\n        inputs = inputs[0]\n    return _copy.deepcopy(inputs) if copy else inputs",
    "docstring": "Returns the same arguments.\n\n    :param inputs:\n        Inputs values.\n    :type inputs: T\n\n    :param copy:\n        If True, it returns a deepcopy of input values.\n    :type copy: bool, optional\n\n    :return:\n        Same input values.\n    :rtype: (T, ...), T\n\n    Example::\n\n        >>> bypass('a', 'b', 'c')\n        ('a', 'b', 'c')\n        >>> bypass('a')\n        'a'"
  },
  {
    "code": "def process_action(self):\n        if self.publish_version == self.UNPUBLISH_CHOICE:\n            actioned = self._unpublish()\n        else:\n            actioned = self._publish()\n        if actioned:\n            self._log_action()\n        return actioned",
    "docstring": "Process the action and update the related object, returns a boolean if a change is made."
  },
  {
    "code": "def _rnd_date(start, end):\n    return date.fromordinal(random.randint(start.toordinal(), end.toordinal()))",
    "docstring": "Internal random date generator."
  },
  {
    "code": "def get_scheduler_info():\n    scheduler = current_app.apscheduler\n    d = OrderedDict([\n        ('current_host', scheduler.host_name),\n        ('allowed_hosts', scheduler.allowed_hosts),\n        ('running', scheduler.running)\n    ])\n    return jsonify(d)",
    "docstring": "Gets the scheduler info."
  },
  {
    "code": "def reqRealTimeBars(\n            self, contract: Contract, barSize: int,\n            whatToShow: str, useRTH: bool,\n            realTimeBarsOptions: List[TagValue] = None) -> RealTimeBarList:\n        reqId = self.client.getReqId()\n        bars = RealTimeBarList()\n        bars.reqId = reqId\n        bars.contract = contract\n        bars.barSize = barSize\n        bars.whatToShow = whatToShow\n        bars.useRTH = useRTH\n        bars.realTimeBarsOptions = realTimeBarsOptions\n        self.wrapper.startSubscription(reqId, bars, contract)\n        self.client.reqRealTimeBars(\n            reqId, contract, barSize, whatToShow, useRTH, realTimeBarsOptions)\n        return bars",
    "docstring": "Request realtime 5 second bars.\n\n        https://interactivebrokers.github.io/tws-api/realtime_bars.html\n\n        Args:\n            contract: Contract of interest.\n            barSize: Must be 5.\n            whatToShow: Specifies the source for constructing bars.\n                Can be 'TRADES', 'MIDPOINT', 'BID' or 'ASK'.\n            useRTH: If True then only show data from within Regular\n                Trading Hours, if False then show all data.\n            realTimeBarsOptions: Unknown."
  },
  {
    "code": "def migrate(ctx,):\n    adapter = ctx.obj['adapter']\n    start_time = datetime.now()\n    nr_updated = migrate_database(adapter)\n    LOG.info(\"All variants updated, time to complete migration: {}\".format(\n        datetime.now() - start_time))\n    LOG.info(\"Nr variants that where updated: %s\", nr_updated)",
    "docstring": "Migrate an old loqusdb instance to 1.0"
  },
  {
    "code": "def get_appliances(self, start=0, count=-1, filter='', fields='', query='', sort='', view=''):\n        uri = self.URI + '/image-streamer-appliances'\n        return self._client.get_all(start, count, filter=filter, sort=sort, query=query, fields=fields, view=view,\n                                    uri=uri)",
    "docstring": "Gets a list of all the Image Streamer resources based on optional sorting and filtering, and constrained\n        by start and count parameters.\n\n        Args:\n            start:\n                The first item to return, using 0-based indexing.\n                If not specified, the default is 0 - start with the first available item.\n            count:\n                The number of resources to return. A count of -1 requests all items.\n                The actual number of items in the response might differ from the requested\n                count if the sum of start and count exceeds the total number of items.\n            filter (list or str):\n                A general filter/query string to narrow the list of items returned. The\n                default is no filter; all resources are returned.\n            fields:\n                Specifies which fields should be returned in the result set.\n            query:\n                 A general query string to narrow the list of resources returned. The default\n                 is no query - all resources are returned.\n            sort:\n                The sort order of the returned data set. By default, the sort order is based\n                on create time with the oldest entry first.\n            view:\n                Return a specific subset of the attributes of the resource or collection, by\n                specifying the name of a predefined view. The default view is expand - show all\n                attributes of the resource and all elements of collections of resources.\n\n        Returns:\n             list: Image Streamer resources associated with the Deployment Servers."
  },
  {
    "code": "def create_db_info():\n        result = {}\n        result['instrument'] = ''\n        result['uuid'] = ''\n        result['tags'] = {}\n        result['type'] = ''\n        result['mode'] = ''\n        result['observation_date'] = \"\"\n        result['origin'] = {}\n        return result",
    "docstring": "Create metadata structure"
  },
  {
    "code": "def _expanded_sql(self):\n    if not self._sql:\n      self._sql = UDF._build_udf(self._name, self._code, self._return_type, self._params,\n                                 self._language, self._imports)\n    return self._sql",
    "docstring": "Get the expanded BigQuery SQL string of this UDF\n\n    Returns\n      The expanded SQL string of this UDF"
  },
  {
    "code": "def  set_led(self, colorcode):\n        data = []\n        data.append(0x0A)\n        data.append(self.servoid)\n        data.append(RAM_WRITE_REQ)\n        data.append(LED_CONTROL_RAM)\n        data.append(0x01)\n        data.append(colorcode)\n        send_data(data)",
    "docstring": "Set the LED Color of Herkulex\n\n        Args:\n            colorcode (int): The code for colors\n                            (0x00-OFF\n                             0x02-BLUE\n                             0x03-CYAN\n                             0x04-RED\n                             0x05-ORANGE\n                             0x06-VIOLET\n                             0x07-WHITE"
  },
  {
    "code": "def execute_phase(self, phase):\n    repeat_count = 1\n    repeat_limit = phase.options.repeat_limit or sys.maxsize\n    while not self._stopping.is_set():\n      is_last_repeat = repeat_count >= repeat_limit\n      phase_execution_outcome = self._execute_phase_once(phase, is_last_repeat)\n      if phase_execution_outcome.is_repeat and not is_last_repeat:\n        repeat_count += 1\n        continue\n      return phase_execution_outcome\n    return PhaseExecutionOutcome(None)",
    "docstring": "Executes a phase or skips it, yielding PhaseExecutionOutcome instances.\n\n    Args:\n      phase: Phase to execute.\n\n    Returns:\n      The final PhaseExecutionOutcome that wraps the phase return value\n      (or exception) of the final phase run. All intermediary results, if any,\n      are REPEAT and handled internally. Returning REPEAT here means the phase\n      hit its limit for repetitions."
  },
  {
    "code": "def _control(self, state):\n        if not self._subscription_is_recent():\n            self._subscribe()\n        cmd = MAGIC + CONTROL + self._mac + PADDING_1 + PADDING_2 + state\n        _LOGGER.debug(\"Sending new state to %s: %s\", self.host, ord(state))\n        ack_state = self._udp_transact(cmd, self._control_resp, state)\n        if ack_state is None:\n            raise S20Exception(\n                \"Device didn't acknowledge control request: {}\".format(\n                    self.host))",
    "docstring": "Control device state.\n\n        Possible states are ON or OFF.\n\n        :param state: Switch to this state."
  },
  {
    "code": "def db_exists(name, user=None, password=None, host=None, port=None, authdb=None):\n    dbs = db_list(user, password, host, port, authdb=authdb)\n    if isinstance(dbs, six.string_types):\n        return False\n    return name in dbs",
    "docstring": "Checks if a database exists in MongoDB\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' mongodb.db_exists <name> <user> <password> <host> <port>"
  },
  {
    "code": "def _get_extra_args(extra_args, arg_keys):\n    single_keys = set([\"sam_ref\", \"config\"])\n    out = []\n    for i, arg_key in enumerate(arg_keys):\n        vals = [xs[i] for xs in extra_args]\n        if arg_key in single_keys:\n            out.append(vals[-1])\n        else:\n            out.append(vals)\n    return out",
    "docstring": "Retrieve extra arguments to pass along to combine function.\n\n    Special cases like reference files and configuration information\n    are passed as single items, the rest as lists mapping to each data\n    item combined."
  },
  {
    "code": "def _convert_string_array(data, encoding, errors, itemsize=None):\n    if encoding is not None and len(data):\n        data = Series(data.ravel()).str.encode(\n            encoding, errors).values.reshape(data.shape)\n    if itemsize is None:\n        ensured = ensure_object(data.ravel())\n        itemsize = max(1, libwriters.max_len_string_array(ensured))\n    data = np.asarray(data, dtype=\"S{size}\".format(size=itemsize))\n    return data",
    "docstring": "we take a string-like that is object dtype and coerce to a fixed size\n    string type\n\n    Parameters\n    ----------\n    data : a numpy array of object dtype\n    encoding : None or string-encoding\n    errors : handler for encoding errors\n    itemsize : integer, optional, defaults to the max length of the strings\n\n    Returns\n    -------\n    data in a fixed-length string dtype, encoded to bytes if needed"
  },
  {
    "code": "def _prepare_init_params_from_job_description(cls, job_details):\n        init_params = dict()\n        init_params['model_name'] = job_details['ModelName']\n        init_params['instance_count'] = job_details['TransformResources']['InstanceCount']\n        init_params['instance_type'] = job_details['TransformResources']['InstanceType']\n        init_params['volume_kms_key'] = job_details['TransformResources'].get('VolumeKmsKeyId')\n        init_params['strategy'] = job_details.get('BatchStrategy')\n        init_params['assemble_with'] = job_details['TransformOutput'].get('AssembleWith')\n        init_params['output_path'] = job_details['TransformOutput']['S3OutputPath']\n        init_params['output_kms_key'] = job_details['TransformOutput'].get('KmsKeyId')\n        init_params['accept'] = job_details['TransformOutput'].get('Accept')\n        init_params['max_concurrent_transforms'] = job_details.get('MaxConcurrentTransforms')\n        init_params['max_payload'] = job_details.get('MaxPayloadInMB')\n        init_params['base_transform_job_name'] = job_details['TransformJobName']\n        return init_params",
    "docstring": "Convert the transform job description to init params that can be handled by the class constructor\n\n        Args:\n            job_details (dict): the returned job details from a describe_transform_job API call.\n\n        Returns:\n            dict: The transformed init_params"
  },
  {
    "code": "def mbar_objective_and_gradient(u_kn, N_k, f_k):\n    u_kn, N_k, f_k = validate_inputs(u_kn, N_k, f_k)\n    log_denominator_n = logsumexp(f_k - u_kn.T, b=N_k, axis=1)\n    log_numerator_k = logsumexp(-log_denominator_n - u_kn, axis=1)\n    grad = -1 * N_k * (1.0 - np.exp(f_k + log_numerator_k))\n    obj = math.fsum(log_denominator_n) - N_k.dot(f_k)\n    return obj, grad",
    "docstring": "Calculates both objective function and gradient for MBAR.\n\n    Parameters\n    ----------\n    u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'\n        The reduced potential energies, i.e. -log unnormalized probabilities\n    N_k : np.ndarray, shape=(n_states), dtype='int'\n        The number of samples in each state\n    f_k : np.ndarray, shape=(n_states), dtype='float'\n        The reduced free energies of each state\n\n\n    Returns\n    -------\n    obj : float\n        Objective function\n    grad : np.ndarray, dtype=float, shape=(n_states)\n        Gradient of objective function\n\n    Notes\n    -----\n    This objective function is essentially a doubly-summed partition function and is\n    quite sensitive to precision loss from both overflow and underflow. For optimal\n    results, u_kn can be preconditioned by subtracting out a `n` dependent\n    vector.\n\n    More optimal precision, the objective function uses math.fsum for the\n    outermost sum and logsumexp for the inner sum.\n    \n    The gradient is equation C6 in the JCP MBAR paper; the objective\n    function is its integral."
  },
  {
    "code": "def path(self, *names):\n        path = [self]\n        for name in names:\n            path.append(path[-1][name, ])\n        return path[1:]",
    "docstring": "Look up and return the complete path of an atom.\n\n        For example, atoms.path('moov', 'udta', 'meta') will return a\n        list of three atoms, corresponding to the moov, udta, and meta\n        atoms."
  },
  {
    "code": "def status(self, agreement_id):\n        condition_ids = self._keeper.agreement_manager.get_agreement(agreement_id).condition_ids\n        result = {\"agreementId\": agreement_id}\n        conditions = dict()\n        for i in condition_ids:\n            conditions[self._keeper.get_condition_name_by_address(\n                self._keeper.condition_manager.get_condition(\n                    i).type_ref)] = self._keeper.condition_manager.get_condition_state(i)\n        result[\"conditions\"] = conditions\n        return result",
    "docstring": "Get the status of a service agreement.\n\n        :param agreement_id: id of the agreement, hex str\n        :return: dict with condition status of each of the agreement's conditions or None if the\n        agreement is invalid."
  },
  {
    "code": "def get_ip_address(ifname):\n    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n    return socket.inet_ntoa(fcntl.ioctl(\n        s.fileno(),\n        0x8915,\n        struct.pack('256s', ifname[:15])\n    )[20:24])",
    "docstring": "Hack to get IP address from the interface"
  },
  {
    "code": "def make_iterable(value):\n    if sys.version_info <= (3, 0):\n        if isinstance(value, unicode):\n            value = str(value)\n    if isinstance(value, str) or isinstance(value, dict):\n        value = [value]\n    if not isinstance(value, collections.Iterable):\n        raise TypeError('value must be an iterable object')\n    return value",
    "docstring": "Converts the supplied value to a list object\n\n    This function will inspect the supplied value and return an\n    iterable in the form of a list.\n\n    Args:\n        value (object): An valid Python object\n\n    Returns:\n        An iterable object of type list"
  },
  {
    "code": "def hash_tags(text, hashes):\n    def sub(match):\n        hashed = hash_text(match.group(0), 'tag')\n        hashes[hashed] = match.group(0)\n        return hashed\n    return re_tag.sub(sub, text)",
    "docstring": "Hashes any non-block tags.\n\n    Only the tags themselves are hashed -- the contains surrounded\n    by tags are not touched. Indeed, there is no notion of \"contained\"\n    text for non-block tags.\n\n    Inline tags that are to be hashed are not white-listed, which\n    allows users to define their own tags. These user-defined tags\n    will also be preserved in their original form until the controller\n    (see link.py) is applied to them."
  },
  {
    "code": "def _load_secret(self, creds_file):\n        try:\n            with open(creds_file) as fp:\n                creds = json.load(fp)\n            return creds\n        except Exception as e:\n            sys.stderr.write(\"Error loading oauth secret from local file called '{0}'\\n\".format(creds_file))\n            sys.stderr.write(\"\\tThere should be a local OAuth credentials file \\n\")\n            sys.stderr.write(\"\\twhich has contents like this:\\n\")\n            sys.stderr.write(\n)\n            sys.stderr.write(\"\\n\")\n            raise e",
    "docstring": "read the oauth secrets and account ID from a credentials configuration file"
  },
  {
    "code": "def prepare(self, params):\n        jsonparams = json.dumps(params)\n        payload = base64.b64encode(jsonparams.encode())\n        signature = hmac.new(self.secret_key.encode(), payload,\n                             hashlib.sha384).hexdigest()\n        return {'X-GEMINI-APIKEY': self.api_key,\n                'X-GEMINI-PAYLOAD': payload,\n                'X-GEMINI-SIGNATURE': signature}",
    "docstring": "Prepare, return the required HTTP headers.\n\n        Base 64 encode the parameters, sign it with the secret key,\n        create the HTTP headers, return the whole payload.\n\n        Arguments:\n        params -- a dictionary of parameters"
  },
  {
    "code": "def default_settings(params):\n    def _default_settings(fn, command):\n        for k, w in params.items():\n            settings.setdefault(k, w)\n        return fn(command)\n    return decorator(_default_settings)",
    "docstring": "Adds default values to settings if it not presented.\n\n    Usage:\n\n        @default_settings({'apt': '/usr/bin/apt'})\n        def match(command):\n            print(settings.apt)"
  },
  {
    "code": "def fric(FlowRate, Diam, Nu, PipeRough):\n    ut.check_range([PipeRough, \"0-1\", \"Pipe roughness\"])\n    if re_pipe(FlowRate, Diam, Nu) >= RE_TRANSITION_PIPE:\n        f = (0.25 / (np.log10(PipeRough / (3.7 * Diam)\n                              + 5.74 / re_pipe(FlowRate, Diam, Nu) ** 0.9\n                              )\n                     ) ** 2\n             )\n    else:\n        f = 64 / re_pipe(FlowRate, Diam, Nu)\n    return f",
    "docstring": "Return the friction factor for pipe flow.\n\n    This equation applies to both laminar and turbulent flows."
  },
  {
    "code": "def plot_target(target, ax):\n    ax.scatter(target[0], target[1], target[2], c=\"red\", s=80)",
    "docstring": "Ajoute la target au plot"
  },
  {
    "code": "def _MakeMethodDescriptor(self, method_proto, service_name, package, scope,\n                            index):\n    full_name = '.'.join((service_name, method_proto.name))\n    input_type = self._GetTypeFromScope(\n        package, method_proto.input_type, scope)\n    output_type = self._GetTypeFromScope(\n        package, method_proto.output_type, scope)\n    return descriptor.MethodDescriptor(name=method_proto.name,\n                                       full_name=full_name,\n                                       index=index,\n                                       containing_service=None,\n                                       input_type=input_type,\n                                       output_type=output_type,\n                                       options=_OptionsOrNone(method_proto))",
    "docstring": "Creates a method descriptor from a MethodDescriptorProto.\n\n    Args:\n      method_proto: The proto describing the method.\n      service_name: The name of the containing service.\n      package: Optional package name to look up for types.\n      scope: Scope containing available types.\n      index: Index of the method in the service.\n\n    Returns:\n      An initialized MethodDescriptor object."
  },
  {
    "code": "def clear_candidates(self, clear_env=True):\n        async def slave_task(addr):\n            r_manager = await self.env.connect(addr)\n            return await r_manager.clear_candidates()\n        self._candidates = []\n        if clear_env:\n            if self._single_env:\n                self.env.clear_candidates()\n            else:\n                mgrs = self.get_managers()\n                run(create_tasks(slave_task, mgrs))",
    "docstring": "Clear the current candidates.\n\n        :param bool clear_env:\n            If ``True``, clears also environment's (or its underlying slave\n            environments') candidates."
  },
  {
    "code": "def page_not_found(request, template_name='404.html'):\n    response = render_in_page(request, template_name)\n    if response:\n        return response\n    template = Template(\n        '<h1>Not Found</h1>'\n        '<p>The requested URL {{ request_path }} was not found on this server.</p>')\n    body = template.render(RequestContext(\n        request, {'request_path': request.path}))\n    return http.HttpResponseNotFound(body, content_type=CONTENT_TYPE)",
    "docstring": "Default 404 handler.\n\n    Templates: :template:`404.html`\n    Context:\n        request_path\n            The path of the requested URL (e.g., '/app/pages/bad_page/')"
  },
  {
    "code": "def landsat_c1_toa_cloud_mask(input_img, snow_flag=False, cirrus_flag=False,\n                              cloud_confidence=2, shadow_confidence=3,\n                              snow_confidence=3, cirrus_confidence=3):\n    qa_img = input_img.select(['BQA'])\n    cloud_mask = qa_img.rightShift(4).bitwiseAnd(1).neq(0)\\\n        .And(qa_img.rightShift(5).bitwiseAnd(3).gte(cloud_confidence))\\\n        .Or(qa_img.rightShift(7).bitwiseAnd(3).gte(shadow_confidence))\n    if snow_flag:\n        cloud_mask = cloud_mask.Or(\n            qa_img.rightShift(9).bitwiseAnd(3).gte(snow_confidence))\n    if cirrus_flag:\n        cloud_mask = cloud_mask.Or(\n            qa_img.rightShift(11).bitwiseAnd(3).gte(cirrus_confidence))\n    return cloud_mask.Not()",
    "docstring": "Extract cloud mask from the Landsat Collection 1 TOA BQA band\n\n    Parameters\n    ----------\n    input_img : ee.Image\n        Image from a Landsat Collection 1 TOA collection with a BQA band\n        (e.g. LANDSAT/LE07/C01/T1_TOA).\n    snow_flag : bool\n        If true, mask snow pixels (the default is False).\n    cirrus_flag : bool\n        If true, mask cirrus pixels (the default is False).\n        Note, cirrus bits are only set for Landsat 8 (OLI) images.\n    cloud_confidence : int\n        Minimum cloud confidence value (the default is 2).\n    shadow_confidence : int\n        Minimum cloud confidence value (the default is 3).\n    snow_confidence : int\n        Minimum snow confidence value (the default is 3).  Only used if\n        snow_flag is True.\n    cirrus_confidence : int\n        Minimum cirrus confidence value (the default is 3).  Only used if\n        cirrus_flag is True.\n\n    Returns\n    -------\n    ee.Image\n\n    Notes\n    -----\n    Output image is structured to be applied directly with updateMask()\n        i.e. 0 is cloud, 1 is cloud free\n\n    Assuming Cloud must be set to check Cloud Confidence\n\n    Bits\n        0:     Designated Fill\n        1:     Terrain Occlusion (OLI) / Dropped Pixel (TM, ETM+)\n        2-3:   Radiometric Saturation\n        4:     Cloud\n        5-6:   Cloud Confidence\n        7-8:   Cloud Shadow Confidence\n        9-10:  Snow/Ice Confidence\n        11-12: Cirrus Confidence (Landsat 8 only)\n\n    Confidence values\n        00: \"Not Determined\", algorithm did not determine the status of this\n            condition\n        01: \"No\", algorithm has low to no confidence that this condition exists\n            (0-33 percent confidence)\n        10: \"Maybe\", algorithm has medium confidence that this condition exists\n            (34-66 percent confidence)\n        11: \"Yes\", algorithm has high confidence that this condition exists\n            (67-100 percent confidence)\n\n    References\n    ----------\n    https://landsat.usgs.gov/collectionqualityband"
  },
  {
    "code": "def check_read_permission(self, user_id, do_raise=True):\n        if _is_admin(user_id):\n            return True\n        if int(self.created_by) == int(user_id):\n            return True\n        for owner in self.owners:\n            if int(owner.user_id) == int(user_id):\n                if owner.view == 'Y':\n                    break\n        else:\n            if do_raise is True:\n                raise PermissionError(\"Permission denied. User %s does not have read\"\n                             \" access on network %s\" %\n                             (user_id, self.id))\n            else:\n                return False\n        return True",
    "docstring": "Check whether this user can read this network"
  },
  {
    "code": "def get_leads(self, *guids, **options):\n        original_options = options\n        options = self.camelcase_search_options(options.copy())\n        params = {}\n        for i in xrange(len(guids)):\n            params['guids[%s]'%i] = guids[i]\n        for k in options.keys():\n            if k in SEARCH_OPTIONS:\n                params[k] = options[k]\n                del options[k]\n        leads = self._call('list/', params, **options)\n        self.log.info(\"retrieved %s leads through API ( %soptions=%s )\" % \n                (len(leads), guids and 'guids=%s, '%guids or '', original_options))\n        return leads",
    "docstring": "Supports all the search parameters in the API as well as python underscored variants"
  },
  {
    "code": "def geturl(self):\n        if self.retries is not None and len(self.retries.history):\n            return self.retries.history[-1].redirect_location\n        else:\n            return self._request_url",
    "docstring": "Returns the URL that was the source of this response.\n        If the request that generated this response redirected, this method\n        will return the final redirect location."
  },
  {
    "code": "def clone_and_merge_sub(self, key):\n        new_comp = copy.deepcopy(self)\n        new_comp.components = None\n        new_comp.comp_key = key\n        return new_comp",
    "docstring": "Clones self and merges clone with sub-component specific information\n\n        Parameters\n        ----------\n\n        key : str\n            Key specifying which sub-component\n\n        Returns `ModelComponentInfo` object"
  },
  {
    "code": "def out_degree(self, nbunch=None, t=None):\n        if nbunch in self:\n            return next(self.out_degree_iter(nbunch, t))[1]\n        else:\n            return dict(self.out_degree_iter(nbunch, t))",
    "docstring": "Return the out degree of a node or nodes at time t.\n\n        The node degree is the number of interaction outgoing from that node in a given time frame.\n\n        Parameters\n        ----------\n        nbunch : iterable container, optional (default=all nodes)\n            A container of nodes.  The container will be iterated\n            through once.\n\n        t : snapshot id (default=None)\n            If None will be returned the degree of nodes on the flattened graph.\n\n\n        Returns\n        -------\n        nd : dictionary, or number\n            A dictionary with nodes as keys and degree as values or\n            a number if a single node is specified.\n\n        Examples\n        --------\n        >>> G = dn.DynDiGraph()\n        >>> G.add_interactions(0,1, t=0)\n        >>> G.add_interactions(1,2, t=0)\n        >>> G.add_interactions(2,3, t=0)\n        >>> G.out_degree(0, t=0)\n        1\n        >>> G.out_degree([0,1], t=1)\n        {0: 0, 1: 0}\n        >>> list(G.out_degree([0,1], t=0).values())\n        [1, 2]"
  },
  {
    "code": "def stripArgs(args, blacklist):\n\t\tblacklist = [b.lower() for b in blacklist]\n\t\treturn list([arg for arg in args if arg.lower() not in blacklist])",
    "docstring": "Removes any arguments in the supplied list that are contained in the specified blacklist"
  },
  {
    "code": "def role_required(role_name=None):\n    def _role_required(http_method_handler):\n        @wraps(http_method_handler)\n        def secure_http_method_handler(self, *args, **kwargs):\n            if role_name is None:\n                _message = \"Role name must be provided\"\n                authorization_error = prestans.exception.AuthorizationError(_message)\n                authorization_error.request = self.request\n                raise authorization_error\n            if not self.__provider_config__.authentication:\n                _message = \"Service available to authenticated users only, no auth context provider set in handler\"\n                authentication_error = prestans.exception.AuthenticationError(_message)\n                authentication_error.request = self.request\n                raise authentication_error\n            if not self.__provider_config__.authentication.current_user_has_role(role_name):\n                authorization_error = prestans.exception.AuthorizationError(role_name)\n                authorization_error.request = self.request\n                raise authorization_error\n            http_method_handler(self, *args, **kwargs)\n        return wraps(http_method_handler)(secure_http_method_handler)\n    return _role_required",
    "docstring": "Authenticates a HTTP method handler based on a provided role\n\n    With a little help from Peter Cole's Blog\n    http://mrcoles.com/blog/3-decorator-examples-and-awesome-python/"
  },
  {
    "code": "def run_hook(hook_name, project_dir, context):\n    script = find_hook(hook_name)\n    if script is None:\n        logger.debug('No {} hook found'.format(hook_name))\n        return\n    logger.debug('Running hook {}'.format(hook_name))\n    run_script_with_context(script, project_dir, context)",
    "docstring": "Try to find and execute a hook from the specified project directory.\n\n    :param hook_name: The hook to execute.\n    :param project_dir: The directory to execute the script from.\n    :param context: Cookiecutter project context."
  },
  {
    "code": "def bqsr_table(data):\n    in_file = dd.get_align_bam(data)\n    out_file = \"%s-recal-table.txt\" % utils.splitext_plus(in_file)[0]\n    if not utils.file_uptodate(out_file, in_file):\n        with file_transaction(data, out_file) as tx_out_file:\n            assoc_files = dd.get_variation_resources(data)\n            known = \"-k %s\" % (assoc_files.get(\"dbsnp\")) if \"dbsnp\" in assoc_files else \"\"\n            license = license_export(data)\n            cores = dd.get_num_cores(data)\n            ref_file = dd.get_ref_file(data)\n            cmd = (\"{license}sentieon driver -t {cores} -r {ref_file} \"\n                   \"-i {in_file} --algo QualCal {known} {tx_out_file}\")\n            do.run(cmd.format(**locals()), \"Sentieon QualCal generate table\")\n    return out_file",
    "docstring": "Generate recalibration tables as inputs to BQSR."
  },
  {
    "code": "def get_user(self):\n        query =\n        data = self.raw_query(query, authorization=True)['data']['user']\n        utils.replace(data, \"insertedAt\", utils.parse_datetime_string)\n        utils.replace(data, \"availableUsd\", utils.parse_float_string)\n        utils.replace(data, \"availableNmr\", utils.parse_float_string)\n        return data",
    "docstring": "Get all information about you!\n\n        Returns:\n            dict: user information including the following fields:\n\n                * assignedEthAddress (`str`)\n                * availableNmr (`decimal.Decimal`)\n                * availableUsd (`decimal.Decimal`)\n                * banned (`bool`)\n                * email (`str`)\n                * id (`str`)\n                * insertedAt (`datetime`)\n                * mfaEnabled (`bool`)\n                * status (`str`)\n                * username (`str`)\n                * country (`str)\n                * phoneNumber (`str`)\n                * apiTokens (`list`) each with the following fields:\n                 * name (`str`)\n                 * public_id (`str`)\n                 * scopes (`list of str`)\n\n        Example:\n            >>> api = NumerAPI(secret_key=\"..\", public_id=\"..\")\n            >>> api.get_user()\n            {'apiTokens': [\n                    {'name': 'tokenname',\n                     'public_id': 'BLABLA',\n                     'scopes': ['upload_submission', 'stake', ..]\n                     }, ..],\n             'assignedEthAddress': '0x0000000000000000000000000001',\n             'availableNmr': Decimal('99.01'),\n             'availableUsd': Decimal('9.47'),\n             'banned': False,\n             'email': 'username@example.com',\n             'phoneNumber': '0123456',\n             'country': 'US',\n             'id': '1234-ABC..',\n             'insertedAt': datetime.datetime(2018, 1, 1, 2, 16, 48),\n             'mfaEnabled': False,\n             'status': 'VERIFIED',\n             'username': 'cool username'\n             }"
  },
  {
    "code": "def get_igraph_from_adjacency(adjacency, directed=None):\n    import igraph as ig\n    sources, targets = adjacency.nonzero()\n    weights = adjacency[sources, targets]\n    if isinstance(weights, np.matrix):\n        weights = weights.A1\n    g = ig.Graph(directed=directed)\n    g.add_vertices(adjacency.shape[0])\n    g.add_edges(list(zip(sources, targets)))\n    try:\n        g.es['weight'] = weights\n    except:\n        pass\n    if g.vcount() != adjacency.shape[0]:\n        logg.warn('The constructed graph has only {} nodes. '\n                  'Your adjacency matrix contained redundant nodes.'\n                  .format(g.vcount()))\n    return g",
    "docstring": "Get igraph graph from adjacency matrix."
  },
  {
    "code": "def _resize(self):\n        lines = self.text.split('\\n')\n        xsize, ysize = 0, 0\n        for line in lines:\n            size = self.textctrl.GetTextExtent(line)\n            xsize = max(xsize, size[0])\n            ysize = ysize + size[1]\n        xsize = int(xsize*1.2)\n        self.textctrl.SetSize((xsize, ysize))\n        self.textctrl.SetMinSize((xsize, ysize))",
    "docstring": "calculate and set text size, handling multi-line"
  },
  {
    "code": "def fetch_meta_by_name(name, filter_context=None, exact_match=True):\n    result = SMCRequest(\n        params={'filter': name,\n                'filter_context': filter_context,\n                'exact_match': exact_match}).read()\n    if not result.json:\n        result.json = []\n    return result",
    "docstring": "Find the element based on name and optional filters. By default, the\n    name provided uses the standard filter query. Additional filters can\n    be used based on supported collections in the SMC API.\n\n    :method: GET\n    :param str name: element name, can use * as wildcard\n    :param str filter_context: further filter request, i.e. 'host', 'group',\n        'single_fw', 'network_elements', 'services',\n        'services_and_applications'\n    :param bool exact_match: Do an exact match by name, note this still can\n        return multiple entries\n    :rtype: SMCResult"
  },
  {
    "code": "def asynchronous(self, fun, low, user='UNKNOWN', pub=None):\n        async_pub = pub if pub is not None else self._gen_async_pub()\n        proc = salt.utils.process.SignalHandlingMultiprocessingProcess(\n                target=self._proc_function,\n                args=(fun, low, user, async_pub['tag'], async_pub['jid']))\n        with salt.utils.process.default_signals(signal.SIGINT, signal.SIGTERM):\n            proc.start()\n        proc.join()\n        return async_pub",
    "docstring": "Execute the function in a multiprocess and return the event tag to use\n        to watch for the return"
  },
  {
    "code": "def reject(self, delivery_tag, requeue=False):\n        args = Writer()\n        args.write_longlong(delivery_tag).\\\n            write_bit(requeue)\n        self.send_frame(MethodFrame(self.channel_id, 60, 90, args))",
    "docstring": "Reject a message."
  },
  {
    "code": "def uninstall(\n    ctx,\n    state,\n    all_dev=False,\n    all=False,\n    **kwargs\n):\n    from ..core import do_uninstall\n    retcode = do_uninstall(\n        packages=state.installstate.packages,\n        editable_packages=state.installstate.editables,\n        three=state.three,\n        python=state.python,\n        system=state.system,\n        lock=not state.installstate.skip_lock,\n        all_dev=all_dev,\n        all=all,\n        keep_outdated=state.installstate.keep_outdated,\n        pypi_mirror=state.pypi_mirror,\n        ctx=ctx\n    )\n    if retcode:\n        sys.exit(retcode)",
    "docstring": "Un-installs a provided package and removes it from Pipfile."
  },
  {
    "code": "def new(filename: str, *, file_attrs: Optional[Dict[str, str]] = None) -> LoomConnection:\n\tif filename.startswith(\"~/\"):\n\t\tfilename = os.path.expanduser(filename)\n\tif file_attrs is None:\n\t\tfile_attrs = {}\n\tf = h5py.File(name=filename, mode='w')\n\tf.create_group('/layers')\n\tf.create_group('/row_attrs')\n\tf.create_group('/col_attrs')\n\tf.create_group('/row_graphs')\n\tf.create_group('/col_graphs')\n\tf.flush()\n\tf.close()\n\tds = connect(filename, validate=False)\n\tfor vals in file_attrs:\n\t\tds.attrs[vals] = file_attrs[vals]\n\tcurrentTime = time.localtime(time.time())\n\tds.attrs['CreationDate'] = timestamp()\n\tds.attrs[\"LOOM_SPEC_VERSION\"] = loompy.loom_spec_version\n\treturn ds",
    "docstring": "Create an empty Loom file, and return it as a context manager."
  },
  {
    "code": "def copy_layer_keywords(layer_keywords):\n    copy_keywords = {}\n    for key, value in list(layer_keywords.items()):\n        if isinstance(value, QUrl):\n            copy_keywords[key] = value.toString()\n        elif isinstance(value, datetime):\n            copy_keywords[key] = value.date().isoformat()\n        elif isinstance(value, QDate):\n            copy_keywords[key] = value.toString(Qt.ISODate)\n        elif isinstance(value, QDateTime):\n            copy_keywords[key] = value.toString(Qt.ISODate)\n        elif isinstance(value, date):\n            copy_keywords[key] = value.isoformat()\n        else:\n            copy_keywords[key] = deepcopy(value)\n    return copy_keywords",
    "docstring": "Helper to make a deep copy of a layer keywords.\n\n    :param layer_keywords: A dictionary of layer's keywords.\n    :type layer_keywords: dict\n\n    :returns: A deep copy of layer keywords.\n    :rtype: dict"
  },
  {
    "code": "def get_analyses(self):\n        analyses = self.context.getAnalyses(full_objects=True)\n        return filter(self.is_analysis_attachment_allowed, analyses)",
    "docstring": "Returns a list of analyses from the AR"
  },
  {
    "code": "def decrypt_block(self, cipherText):\n    if not self.initialized:\n      raise TypeError(\"CamCrypt object has not been initialized\")\n    if len(cipherText) != BLOCK_SIZE:\n      raise ValueError(\"cipherText must be %d bytes long (received %d bytes)\" %\n                       (BLOCK_SIZE, len(cipherText)))\n    plain = ctypes.create_string_buffer(BLOCK_SIZE)\n    self.decblock(self.bitlen, cipherText, self.keytable, plain)\n    return plain.raw",
    "docstring": "Decrypt a 16-byte block of data.\n\n    NOTE: This function was formerly called `decrypt`, but was changed when\n    support for decrypting arbitrary-length strings was added.\n\n    Args:\n        cipherText (str): 16-byte data.\n\n    Returns:\n        16-byte str.\n\n    Raises:\n        TypeError if CamCrypt object has not been initialized.\n        ValueError if `cipherText` is not BLOCK_SIZE (i.e. 16) bytes."
  },
  {
    "code": "def enable_repositories(self, repositories):\n        for r in repositories:\n            if r['type'] != 'rhsm_channel':\n                continue\n            if r['name'] not in self.rhsm_channels:\n                self.rhsm_channels.append(r['name'])\n        if self.rhsm_active:\n            subscription_cmd = \"subscription-manager repos '--disable=*' --enable=\" + ' --enable='.join(\n                self.rhsm_channels)\n            self.run(subscription_cmd)\n        repo_files = [r for r in repositories if r['type'] == 'yum_repo']\n        for repo_file in repo_files:\n            self.create_file(repo_file['dest'], repo_file['content'])\n        packages = [r['name'] for r in repositories if r['type'] == 'package']\n        if packages:\n            self.yum_install(packages)",
    "docstring": "Enable a list of RHSM repositories.\n\n        :param repositories: a dict in this format:\n            [{'type': 'rhsm_channel', 'name': 'rhel-7-server-rpms'}]"
  },
  {
    "code": "def _handle_dumps(self, handler, **kwargs):\n    return handler.dumps(self.__class__, to_dict(self), **kwargs)",
    "docstring": "Dumps caller, used by partial method for dynamic handler assignments.\n\n    :param object handler: The dump handler\n    :return: The dumped string\n    :rtype: str"
  },
  {
    "code": "def until(self, method, message=''):\n        screen = None\n        stacktrace = None\n        end_time = time.time() + self._timeout\n        while True:\n            try:\n                value = method(self._driver)\n                if value:\n                    return value\n            except self._ignored_exceptions as exc:\n                screen = getattr(exc, 'screen', None)\n                stacktrace = getattr(exc, 'stacktrace', None)\n            time.sleep(self._poll)\n            if time.time() > end_time:\n                break\n        raise TimeoutException(message, screen, stacktrace)",
    "docstring": "Calls the method provided with the driver as an argument until the \\\n        return value does not evaluate to ``False``.\n\n        :param method: callable(WebDriver)\n        :param message: optional message for :exc:`TimeoutException`\n        :returns: the result of the last call to `method`\n        :raises: :exc:`selenium.common.exceptions.TimeoutException` if timeout occurs"
  },
  {
    "code": "def read_local_manifest(self):\n        manifest = file_or_default(self.get_full_file_path(self.manifest_file), {\n            'format_version' : 2,\n            'root'           : '/',\n            'have_revision'  : 'root',\n            'files'          : {}}, json.loads)\n        if 'format_version' not in manifest or manifest['format_version'] < 2:\n            raise SystemExit('Please update the client manifest format')\n        return manifest",
    "docstring": "Read the file manifest, or create a new one if there isn't one already"
  },
  {
    "code": "def platform_path(path):\n    r\n    try:\n        if path == '':\n            raise ValueError('path cannot be the empty string')\n        path1 = truepath_relative(path)\n        if sys.platform.startswith('win32'):\n            path2 = expand_win32_shortname(path1)\n        else:\n            path2 = path1\n    except Exception as ex:\n        util_dbg.printex(ex, keys=['path', 'path1', 'path2'])\n        raise\n    return path2",
    "docstring": "r\"\"\"\n    Returns platform specific path for pyinstaller usage\n\n    Args:\n        path (str):\n\n    Returns:\n        str: path2\n\n    CommandLine:\n        python -m utool.util_path --test-platform_path\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> # FIXME: find examples of the wird paths this fixes (mostly on win32 i think)\n        >>> from utool.util_path import *  # NOQA\n        >>> import utool as ut\n        >>> path = 'some/odd/../weird/path'\n        >>> path2 = platform_path(path)\n        >>> result = str(path2)\n        >>> if ut.WIN32:\n        ...     ut.assert_eq(path2, r'some\\weird\\path')\n        ... else:\n        ...     ut.assert_eq(path2, r'some/weird/path')\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_path import *  # NOQA\n        >>> import utool as ut    # NOQA\n        >>> if ut.WIN32:\n        ...     path = 'C:/PROGRA~2'\n        ...     path2 = platform_path(path)\n        ...     assert path2 == u'..\\\\..\\\\..\\\\..\\\\Program Files (x86)'"
  },
  {
    "code": "def setPrefix(self, p, u=None):\n        self.prefix = p\n        if p is not None and u is not None:\n            self.addPrefix(p, u)\n        return self",
    "docstring": "Set the element namespace prefix.\n        @param p: A new prefix for the element.\n        @type p: basestring\n        @param u: A namespace URI to be mapped to the prefix.\n        @type u: basestring\n        @return: self\n        @rtype: L{Element}"
  },
  {
    "code": "def dir2(obj):\n    attrs = set()\n    if not hasattr(obj, '__bases__'):\n        if not hasattr(obj, '__class__'):\n            return sorted(get_attrs(obj))\n        klass = obj.__class__\n        attrs.update(get_attrs(klass))\n    else:\n        klass = obj\n    for cls in klass.__bases__:\n        attrs.update(get_attrs(cls))\n        attrs.update(dir2(cls))\n    attrs.update(get_attrs(obj))\n    return list(attrs)",
    "docstring": "Default dir implementation.\n\n    Inspired by gist: katyukha/dirmixin.py\n    https://gist.github.com/katyukha/c6e5e2b829e247c9b009"
  },
  {
    "code": "def list_templates():\n    templates = [f for f in glob.glob(os.path.join(template_path, '*.yaml'))]\n    return templates",
    "docstring": "Returns a list of all templates."
  },
  {
    "code": "def replace(self, year=None, week=None):\n        return self.__class__(self.year if year is None else year,\n                              self.week if week is None else week)",
    "docstring": "Return a Week with either the year or week attribute value replaced"
  },
  {
    "code": "def get_version_manifest(name, data=None, required=False):\n    manifest_dir = _get_manifest_dir(data, name)\n    manifest_vs = _get_versions_manifest(manifest_dir) or []\n    for x in manifest_vs:\n        if x[\"program\"] == name:\n            v = x.get(\"version\", \"\")\n            if v:\n                return v\n    if required:\n        raise ValueError(\"Did not find %s in install manifest. Could not check version.\" % name)\n    return \"\"",
    "docstring": "Retrieve a version from the currently installed manifest."
  },
  {
    "code": "def get_convert_dist(\n    dist_units_in: str, dist_units_out: str\n) -> Callable[[float], float]:\n    di, do = dist_units_in, dist_units_out\n    DU = cs.DIST_UNITS\n    if not (di in DU and do in DU):\n        raise ValueError(f\"Distance units must lie in {DU}\")\n    d = {\n        \"ft\": {\"ft\": 1, \"m\": 0.3048, \"mi\": 1 / 5280, \"km\": 0.0003048},\n        \"m\": {\"ft\": 1 / 0.3048, \"m\": 1, \"mi\": 1 / 1609.344, \"km\": 1 / 1000},\n        \"mi\": {\"ft\": 5280, \"m\": 1609.344, \"mi\": 1, \"km\": 1.609344},\n        \"km\": {\"ft\": 1 / 0.0003048, \"m\": 1000, \"mi\": 1 / 1.609344, \"km\": 1},\n    }\n    return lambda x: d[di][do] * x",
    "docstring": "Return a function of the form\n\n      distance in the units ``dist_units_in`` ->\n      distance in the units ``dist_units_out``\n\n    Only supports distance units in :const:`constants.DIST_UNITS`."
  },
  {
    "code": "def assemble_points(graph, assemblies, multicolor, verbose=False, verbose_destination=None):\n    if verbose:\n        print(\">>Assembling for multicolor\", [e.name for e in multicolor.multicolors.elements()],\n              file=verbose_destination)\n    for assembly in assemblies:\n        v1, v2, (before, after, ex_data) = assembly\n        iv1 = get_irregular_vertex(get_irregular_edge_by_vertex(graph, vertex=v1))\n        iv2 = get_irregular_vertex(get_irregular_edge_by_vertex(graph, vertex=v2))\n        kbreak = KBreak(start_edges=[(v1, iv1), (v2, iv2)],\n                        result_edges=[(v1, v2), (iv1, iv2)],\n                        multicolor=multicolor)\n        if verbose:\n            print(\"(\", v1.name, \",\", iv1.name, \")x(\", v2.name, \",\", iv2.name, \")\", \" score=\", before - after, sep=\"\",\n                  file=verbose_destination)\n        graph.apply_kbreak(kbreak=kbreak, merge=True)",
    "docstring": "This function actually does assembling being provided\n        a graph, to play with\n        a list of assembly points\n        and a multicolor, which to assemble"
  },
  {
    "code": "def _parse_methods(cls, list_string):\n        if list_string is None:\n            return APIServer.DEFAULT_METHODS\n        json_list = list_string.replace(\"'\", '\"')\n        return json.loads(json_list)",
    "docstring": "Return HTTP method list. Use json for security reasons."
  },
  {
    "code": "def breslauer_corrections(seq, pars_error):\n    deltas_corr = [0, 0]\n    contains_gc = 'G' in str(seq) or 'C' in str(seq)\n    only_at = str(seq).count('A') + str(seq).count('T') == len(seq)\n    symmetric = seq == seq.reverse_complement()\n    terminal_t = str(seq)[0] == 'T' + str(seq)[-1] == 'T'\n    for i, delta in enumerate(['delta_h', 'delta_s']):\n        if contains_gc:\n            deltas_corr[i] += pars_error[delta]['anyGC']\n        if only_at:\n            deltas_corr[i] += pars_error[delta]['onlyAT']\n        if symmetric:\n            deltas_corr[i] += pars_error[delta]['symmetry']\n        if terminal_t and delta == 'delta_h':\n            deltas_corr[i] += pars_error[delta]['terminalT'] * terminal_t\n    return deltas_corr",
    "docstring": "Sum corrections for Breslauer '84 method.\n\n    :param seq: sequence for which to calculate corrections.\n    :type seq: str\n    :param pars_error: dictionary of error corrections\n    :type pars_error: dict\n    :returns: Corrected delta_H and delta_S parameters\n    :rtype: list of floats"
  },
  {
    "code": "def get_title(self, entry):\n        title = _('%(title)s (%(word_count)i words)') % \\\n            {'title': entry.title, 'word_count': entry.word_count}\n        reaction_count = int(entry.comment_count +\n                             entry.pingback_count +\n                             entry.trackback_count)\n        if reaction_count:\n            return ungettext_lazy(\n                '%(title)s (%(reactions)i reaction)',\n                '%(title)s (%(reactions)i reactions)', reaction_count) % \\\n                {'title': title,\n                 'reactions': reaction_count}\n        return title",
    "docstring": "Return the title with word count and number of comments."
  },
  {
    "code": "def safe_shake(self, x, fun, fmax):\n        self.lock[:] = False\n        def extra_equation(xx):\n            f, g = fun(xx, do_gradient=True)\n            return (f-fmax)/abs(fmax), g/abs(fmax)\n        self.equations.append((-1,extra_equation))\n        x, shake_counter, constraint_couter = self.free_shake(x)\n        del self.equations[-1]\n        return x, shake_counter, constraint_couter",
    "docstring": "Brings unknowns to the constraints, without increasing fun above fmax.\n\n           Arguments:\n            | ``x`` -- The unknowns.\n            | ``fun`` -- The function being minimized.\n            | ``fmax`` -- The highest allowed value of the function being\n                          minimized.\n\n           The function ``fun`` takes a mandatory argument ``x`` and an optional\n           argument ``do_gradient``:\n            | ``x``  --  the arguments of the function to be tested\n            | ``do_gradient``  --  when False, only the function value is\n                                   returned. when True, a 2-tuple with the\n                                   function value and the gradient are returned\n                                   [default=False]"
  },
  {
    "code": "def _hasViewChangeQuorum(self):\n        num_of_ready_nodes = len(self._view_change_done)\n        diff = self.quorum - num_of_ready_nodes\n        if diff > 0:\n            logger.info('{} needs {} ViewChangeDone messages'.format(self, diff))\n            return False\n        logger.info(\"{} got view change quorum ({} >= {})\".\n                    format(self.name, num_of_ready_nodes, self.quorum))\n        return True",
    "docstring": "Checks whether n-f nodes completed view change and whether one\n        of them is the next primary"
  },
  {
    "code": "def multiple_packaged_versions(package_name):\n    dist_files = os.listdir('dist')\n    versions = set()\n    for filename in dist_files:\n        version = funcy.re_find(r'{}-(.+).tar.gz'.format(package_name), filename)\n        if version:\n            versions.add(version)\n    return len(versions) > 1",
    "docstring": "Look through built package directory and see if there are multiple versions there"
  },
  {
    "code": "def get_vault_query_session(self, proxy):\n        if not self.supports_vault_query():\n            raise errors.Unimplemented()\n        return sessions.VaultQuerySession(proxy=proxy, runtime=self._runtime)",
    "docstring": "Gets the OsidSession associated with the vault query service.\n\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.authorization.VaultQuerySession) - a\n                ``VaultQuerySession``\n        raise:  NullArgument - ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_vault_query() is false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_vault_query()`` is true.*"
  },
  {
    "code": "def url_unquote_plus(s, charset='utf-8', errors='replace'):\n    if isinstance(s, unicode):\n        s = s.encode(charset)\n    return _decode_unicode(_unquote_plus(s), charset, errors)",
    "docstring": "URL decode a single string with the given decoding and decode\n    a \"+\" to whitespace.\n\n    Per default encoding errors are ignored.  If you want a different behavior\n    you can set `errors` to ``'replace'`` or ``'strict'``.  In strict mode a\n    `HTTPUnicodeError` is raised.\n\n    :param s: the string to unquote.\n    :param charset: the charset to be used.\n    :param errors: the error handling for the charset decoding."
  },
  {
    "code": "def set_language(self, editor, language):\n        LOGGER.debug(\"> Setting '{0}' language to '{1}' editor.\".format(language.name, editor))\n        return editor.set_language(language)",
    "docstring": "Sets given language to given Model editor.\n\n        :param editor: Editor to set language to.\n        :type editor: Editor\n        :param language: Language to set.\n        :type language: Language\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def new_logger(name):\n    log = get_task_logger(name)\n    handler = logstash.LogstashHandler(\n        config.logstash.host, config.logstash.port)\n    log.addHandler(handler)\n    create_logdir(config.logdir)\n    handler = TimedRotatingFileHandler(\n        '%s.json' % join(config.logdir, name),\n        when='midnight',\n        utc=True,\n    )\n    handler.setFormatter(JSONFormatter())\n    log.addHandler(handler)\n    return TaskCtxAdapter(log, {})",
    "docstring": "Return new logger which will log both to logstash and to file in JSON\n    format.\n\n    Log files are stored in <logdir>/name.json"
  },
  {
    "code": "def print_prompt_values(values, message=None, sub_attr=None):\n    if message:\n        prompt_message(message)\n    for index, entry in enumerate(values):\n        if sub_attr:\n            line = '{:2d}: {}'.format(index, getattr(utf8(entry), sub_attr))\n        else:\n            line = '{:2d}: {}'.format(index, utf8(entry))\n        with indent(3):\n            print_message(line)",
    "docstring": "Prints prompt title and choices with a bit of formatting."
  },
  {
    "code": "def get_temp_filename (content):\n    fd, filename = fileutil.get_temp_file(mode='wb', suffix='.doc',\n        prefix='lc_')\n    try:\n        fd.write(content)\n    finally:\n        fd.close()\n    return filename",
    "docstring": "Get temporary filename for content to parse."
  },
  {
    "code": "def queryTypesDescriptions(self, types):\n        types = list(types)\n        if types:\n            types_descs = self.describeSObjects(types)\n        else:\n            types_descs = []\n        return dict(map(lambda t, d: (t, d), types, types_descs))",
    "docstring": "Given a list of types, construct a dictionary such that\n        each key is a type, and each value is the corresponding sObject\n        for that type."
  },
  {
    "code": "async def sort(self, request, reverse=False):\n        return sorted(\n            self.collection, key=lambda o: getattr(o, self.columns_sort, 0), reverse=reverse)",
    "docstring": "Sort collection."
  },
  {
    "code": "def is_email(potential_email_address):\n    context, mail = parseaddr(potential_email_address)\n    first_condition = len(context) == 0 and len(mail) != 0\n    dot_after_at = ('@' in potential_email_address and\n                    '.' in potential_email_address.split('@')[1])\n    return first_condition and dot_after_at",
    "docstring": "Check if potential_email_address is a valid e-mail address.\n\n    Please note that this function has no false-negatives but many\n    false-positives. So if it returns that the input is not a valid\n    e-mail adress, it certainly isn't. If it returns True, it might still be\n    invalid. For example, the domain could not be registered.\n\n    Parameters\n    ----------\n    potential_email_address : str\n\n    Returns\n    -------\n    is_email : bool\n\n    Examples\n    --------\n    >>> is_email('')\n    False\n    >>> is_email('info@martin-thoma.de')\n    True\n    >>> is_email('info@math.martin-thoma.de')\n    True\n    >>> is_email('Martin Thoma <info@martin-thoma.de>')\n    False\n    >>> is_email('info@martin-thoma')\n    False"
  },
  {
    "code": "def connection(self, commit=False):\n        if commit:\n            self._need_commit = True\n        if self._db:\n            yield self._db\n        else:\n            try:\n                with self._get_db() as db:\n                    self._db = db\n                    db.create_function(\"REGEXP\", 2, sql_regexp_func)\n                    db.create_function(\"PROGRAM_NAME\", 1,\n                                       sql_program_name_func)\n                    db.create_function(\"PATHDIST\", 2, sql_pathdist_func)\n                    yield self._db\n                    if self._need_commit:\n                        db.commit()\n            finally:\n                self._db = None\n                self._need_commit = False",
    "docstring": "Context manager to keep around DB connection.\n\n        :rtype: sqlite3.Connection\n\n        SOMEDAY: Get rid of this function.  Keeping connection around as\n        an argument to the method using this context manager is\n        probably better as it is more explicit.\n        Also, holding \"global state\" as instance attribute is bad for\n        supporting threaded search, which is required for more fluent\n        percol integration."
  },
  {
    "code": "def _ts_parse(ts):\n    dt = datetime.strptime(ts[:19],\"%Y-%m-%dT%H:%M:%S\")\n    if ts[19] == '+':\n        dt -= timedelta(hours=int(ts[20:22]),minutes=int(ts[23:]))\n    elif ts[19] == '-':\n        dt += timedelta(hours=int(ts[20:22]),minutes=int(ts[23:]))\n    return dt.replace(tzinfo=pytz.UTC)",
    "docstring": "Parse alert timestamp, return UTC datetime object to maintain Python 2 compatibility."
  },
  {
    "code": "def server(port):\n    args = ['python', 'manage.py', 'runserver']\n    if port:\n        args.append(port)\n    run.main(args)",
    "docstring": "Start the Django dev server."
  },
  {
    "code": "def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None):\n    if not conn:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    if conn:\n        vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id})\n        for vpc_route_table in vpc_route_tables:\n            for rt_association in vpc_route_table.associations:\n                if rt_association.subnet_id == subnet_id and not rt_association.main:\n                    return rt_association.id\n    return None",
    "docstring": "helper function to find subnet explicit route table associations\n\n    .. versionadded:: 2016.11.0"
  },
  {
    "code": "def endswith(self, search_str):\n        for entry in reversed(list(open(self._jrnl_file, 'r'))[-5:]):\n            if search_str in entry:\n                return True\n        return False",
    "docstring": "Check whether the provided string exists in Journal file.\n\n        Only checks the last 5 lines of the journal file. This method is\n        usually used when tracking a journal from an active Revit session.\n\n        Args:\n            search_str (str): string to search for\n\n        Returns:\n            bool: if True the search string is found"
  },
  {
    "code": "def load_recipe(self, recipe):\n    self.recipe = recipe\n    for module_description in recipe['modules']:\n      module_name = module_description['name']\n      module = self.config.get_module(module_name)(self)\n      self._module_pool[module_name] = module",
    "docstring": "Populates the internal module pool with modules declared in a recipe.\n\n    Args:\n      recipe: Dict, recipe declaring modules to load."
  },
  {
    "code": "def load_config(self, config_file_name):\n        with open(config_file_name) as f:\n            commands = f.read().splitlines()\n        for command in commands:\n            if not command.startswith(';'):\n                try:\n                    self.send_command(command)\n                except XenaCommandException as e:\n                    self.logger.warning(str(e))",
    "docstring": "Load configuration file from xpc file.\n\n        :param config_file_name: full path to the configuration file."
  },
  {
    "code": "def register_array(self, name, shape, dtype, **kwargs):\n        if name in self._arrays:\n            raise ValueError(('Array %s is already registered '\n                'on this cube object.') % name)\n        A = self._arrays[name] = AttrDict(name=name,\n            dtype=dtype, shape=shape,\n            **kwargs)\n        return A",
    "docstring": "Register an array with this cube.\n\n        .. code-block:: python\n\n            cube.register_array(\"model_vis\", (\"ntime\", \"nbl\", \"nchan\", 4), np.complex128)\n\n        Parameters\n        ----------\n        name : str\n            Array name\n        shape : A tuple containing either Dimension names or ints\n            Array shape schema\n        dtype :\n            Array data type"
  },
  {
    "code": "def business_days(start, stop):\n    dates=rrule.rruleset()\n    dates.rrule(rrule.rrule(rrule.DAILY, dtstart=start, until=stop))\n    dates.exrule(rrule.rrule(rrule.DAILY, byweekday=(rrule.SA, rrule.SU), dtstart=start)) \n    return dates.count()",
    "docstring": "Return business days between two inclusive dates - ignoring public holidays.\n    \n    Note that start must be less than stop or else 0 is returned.\n    \n    @param start: Start date\n    @param stop: Stop date\n    @return int"
  },
  {
    "code": "def get_pipeline(node: Node) -> RenderingPipeline:\n    pipeline = _get_registered_pipeline(node)\n    if pipeline is None:\n        msg = _get_pipeline_registration_error_message(node)\n        raise RenderingError(msg)\n    return pipeline",
    "docstring": "Gets rendering pipeline for passed node"
  },
  {
    "code": "def _checker_mixer(slice1,\n                   slice2,\n                   checker_size=None):\n    checkers = _get_checkers(slice1.shape, checker_size)\n    if slice1.shape != slice2.shape or slice2.shape != checkers.shape:\n        raise ValueError('size mismatch between cropped slices and checkers!!!')\n    mixed = slice1.copy()\n    mixed[checkers > 0] = slice2[checkers > 0]\n    return mixed",
    "docstring": "Mixes the two slices in alternating areas specified by checkers"
  },
  {
    "code": "def url_encode(url):\n    if isinstance(url, text_type):\n        url = url.encode('utf8')\n    return quote(url, ':/%?&=')",
    "docstring": "Convert special characters using %xx escape.\n\n    :param url: str\n    :return: str - encoded url"
  },
  {
    "code": "def to_text(self):\n        if self.text == '':\n            return '::%s' % self.uri\n        return '::%s [%s]' % (self.text, self.uri)",
    "docstring": "Render as plain text."
  },
  {
    "code": "def format(self):\n        if hasattr(self.image, '_getexif'):\n            self.rotate_exif()\n        crop_box = self.crop_to_ratio()\n        self.resize()\n        return self.image, crop_box",
    "docstring": "Crop and resize the supplied image. Return the image and the crop_box used.\n        If the input format is JPEG and in EXIF there is information about rotation, use it and rotate resulting image."
  },
  {
    "code": "def combine_kwargs(**kwargs):\n    combined_kwargs = []\n    for kw, arg in kwargs.items():\n        if isinstance(arg, dict):\n            for k, v in arg.items():\n                for tup in flatten_kwarg(k, v):\n                    combined_kwargs.append(('{}{}'.format(kw, tup[0]), tup[1]))\n        elif is_multivalued(arg):\n            for i in arg:\n                for tup in flatten_kwarg('', i):\n                    combined_kwargs.append(('{}{}'.format(kw, tup[0]), tup[1]))\n        else:\n            combined_kwargs.append((text_type(kw), arg))\n    return combined_kwargs",
    "docstring": "Flatten a series of keyword arguments from complex combinations of\n    dictionaries and lists into a list of tuples representing\n    properly-formatted parameters to pass to the Requester object.\n\n    :param kwargs: A dictionary containing keyword arguments to be\n        flattened into properly-formatted parameters.\n    :type kwargs: dict\n\n    :returns: A list of tuples that represent flattened kwargs. The\n        first element is a string representing the key. The second\n        element is the value.\n    :rtype: `list` of `tuple`"
  },
  {
    "code": "def _get_subject_public_key(cert):\n        public_key = cert.get_pubkey()\n        cryptographic_key = public_key.to_cryptography_key()\n        subject_public_key = cryptographic_key.public_bytes(Encoding.DER,\n                                                            PublicFormat.PKCS1)\n        return subject_public_key",
    "docstring": "Returns the SubjectPublicKey asn.1 field of the SubjectPublicKeyInfo\n        field of the server's certificate. This is used in the server\n        verification steps to thwart MitM attacks.\n\n        :param cert: X509 certificate from pyOpenSSL .get_peer_certificate()\n        :return: byte string of the asn.1 DER encoded SubjectPublicKey field"
  },
  {
    "code": "def limit(self, value):\n        self._query = self._query.limit(value)\n        return self",
    "docstring": "Allows for limiting number of results returned for query. Useful\n        for pagination."
  },
  {
    "code": "def list_private_repos(profile='github'):\n    repos = []\n    for repo in _get_repos(profile):\n        if repo.private is True:\n            repos.append(repo.name)\n    return repos",
    "docstring": "List private repositories within the organization. Dependent upon the access\n    rights of the profile token.\n\n    .. versionadded:: 2016.11.0\n\n    profile\n        The name of the profile configuration to use. Defaults to ``github``.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion github.list_private_repos\n        salt myminion github.list_private_repos profile='my-github-profile'"
  },
  {
    "code": "def map(self, f, preservesPartitioning=False):\n        return (\n            self\n            .mapPartitions(lambda p: (f(e) for e in p), preservesPartitioning)\n            .transform(lambda rdd:\n                       rdd.setName('{}:{}'.format(rdd.prev.name(), f)))\n        )",
    "docstring": "Apply function f\n\n        :param f: mapping function\n        :rtype: DStream\n\n\n        Example:\n\n        >>> import pysparkling\n        >>> sc = pysparkling.Context()\n        >>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)\n        >>> (\n        ...     ssc\n        ...     .queueStream([[4], [2], [7]])\n        ...     .map(lambda e: e + 1)\n        ...     .foreachRDD(lambda rdd: print(rdd.collect()))\n        ... )\n        >>> ssc.start()\n        >>> ssc.awaitTermination(0.35)\n        [5]\n        [3]\n        [8]"
  },
  {
    "code": "def with_name(cls, name, id_user=0, **extra_data):\n        return cls(name=name, id_user=0, **extra_data)",
    "docstring": "Instantiate a WorkflowEngine given a name or UUID.\n\n        :param name: name of workflow to run.\n        :type name: str\n\n        :param id_user: id of user to associate with workflow\n        :type id_user: int\n\n        :param module_name: label used to query groups of workflows.\n        :type module_name: str"
  },
  {
    "code": "def cv_error(self, cv=True, skip_endpoints=True):\n        resids = self.cv_residuals(cv)\n        if skip_endpoints:\n            resids = resids[1:-1]\n        return np.mean(abs(resids))",
    "docstring": "Return the sum of cross-validation residuals for the input data"
  },
  {
    "code": "def decodes(self, s: str) -> BioCCollection:\n        tree = etree.parse(io.BytesIO(bytes(s, encoding='UTF-8')))\n        collection = self.__parse_collection(tree.getroot())\n        collection.encoding = tree.docinfo.encoding\n        collection.standalone = tree.docinfo.standalone\n        collection.version = tree.docinfo.xml_version\n        return collection",
    "docstring": "Deserialize ``s`` to a BioC collection object.\n\n        Args:\n            s: a \"str\" instance containing a BioC collection\n\n        Returns:\n            an object of BioCollection"
  },
  {
    "code": "def create_guest_screen_info(self, display, status, primary, change_origin, origin_x, origin_y, width, height, bits_per_pixel):\n        if not isinstance(display, baseinteger):\n            raise TypeError(\"display can only be an instance of type baseinteger\")\n        if not isinstance(status, GuestMonitorStatus):\n            raise TypeError(\"status can only be an instance of type GuestMonitorStatus\")\n        if not isinstance(primary, bool):\n            raise TypeError(\"primary can only be an instance of type bool\")\n        if not isinstance(change_origin, bool):\n            raise TypeError(\"change_origin can only be an instance of type bool\")\n        if not isinstance(origin_x, baseinteger):\n            raise TypeError(\"origin_x can only be an instance of type baseinteger\")\n        if not isinstance(origin_y, baseinteger):\n            raise TypeError(\"origin_y can only be an instance of type baseinteger\")\n        if not isinstance(width, baseinteger):\n            raise TypeError(\"width can only be an instance of type baseinteger\")\n        if not isinstance(height, baseinteger):\n            raise TypeError(\"height can only be an instance of type baseinteger\")\n        if not isinstance(bits_per_pixel, baseinteger):\n            raise TypeError(\"bits_per_pixel can only be an instance of type baseinteger\")\n        guest_screen_info = self._call(\"createGuestScreenInfo\",\n                     in_p=[display, status, primary, change_origin, origin_x, origin_y, width, height, bits_per_pixel])\n        guest_screen_info = IGuestScreenInfo(guest_screen_info)\n        return guest_screen_info",
    "docstring": "Make a IGuestScreenInfo object with the provided parameters.\n\n        in display of type int\n            The number of the guest display.\n\n        in status of type :class:`GuestMonitorStatus`\n            @c True, if this guest screen is enabled,\n            @c False otherwise.\n\n        in primary of type bool\n            Whether this guest monitor must be primary.\n\n        in change_origin of type bool\n            @c True, if the origin of the guest screen should be changed,\n            @c False otherwise.\n\n        in origin_x of type int\n            The X origin of the guest screen.\n\n        in origin_y of type int\n            The Y origin of the guest screen.\n\n        in width of type int\n            The width of the guest screen.\n\n        in height of type int\n            The height of the guest screen.\n\n        in bits_per_pixel of type int\n            The number of bits per pixel of the guest screen.\n\n        return guest_screen_info of type :class:`IGuestScreenInfo`\n            The created object."
  },
  {
    "code": "def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None,\n                            region=None, key=None, keyid=None, profile=None):\n    return resource_exists('customer_gateway', name=customer_gateway_name,\n                           resource_id=customer_gateway_id,\n                           region=region, key=key, keyid=keyid, profile=profile)",
    "docstring": "Given a customer gateway ID, check if the customer gateway ID exists.\n\n    Returns True if the customer gateway ID exists; Returns False otherwise.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df\n        salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw"
  },
  {
    "code": "def subdomain(self, hostname):\n        hostname = hostname.split(\":\")[0]\n        for domain in getDomainNames(self.siteStore):\n            if hostname.endswith(\".\" + domain):\n                username = hostname[:-len(domain) - 1]\n                if username != \"www\":\n                    return username, domain\n        return None",
    "docstring": "Determine of which known domain the given hostname is a subdomain.\n\n        @return: A two-tuple giving the subdomain part and the domain part or\n            C{None} if the domain is not a subdomain of any known domain."
  },
  {
    "code": "def intervention(self, commit, conf):\n        if not conf.harpoon.interactive or conf.harpoon.no_intervention:\n            yield\n            return\n        hp.write_to(conf.harpoon.stdout, \"!!!!\\n\")\n        hp.write_to(conf.harpoon.stdout, \"It would appear building the image failed\\n\")\n        hp.write_to(conf.harpoon.stdout, \"Do you want to run {0} where the build to help debug why it failed?\\n\".format(conf.resolved_shell))\n        conf.harpoon.stdout.flush()\n        answer = input(\"[y]: \")\n        if answer and not answer.lower().startswith(\"y\"):\n            yield\n            return\n        with self.commit_and_run(commit, conf, command=conf.resolved_shell):\n            yield",
    "docstring": "Ask the user if they want to commit this container and run sh in it"
  },
  {
    "code": "async def _put_chunk(\n            cls, session: aiohttp.ClientSession,\n            upload_uri: str, buf: bytes):\n        headers = {\n            'Content-Type': 'application/octet-stream',\n            'Content-Length': '%s' % len(buf),\n        }\n        credentials = cls._handler.session.credentials\n        if credentials is not None:\n            utils.sign(upload_uri, headers, credentials)\n        async with await session.put(\n                upload_uri, data=buf, headers=headers) as response:\n            if response.status != 200:\n                content = await response.read()\n                request = {\n                    \"body\": buf,\n                    \"headers\": headers,\n                    \"method\": \"PUT\",\n                    \"uri\": upload_uri,\n                }\n                raise CallError(request, response, content, None)",
    "docstring": "Upload one chunk to `upload_uri`."
  },
  {
    "code": "def _ensure_tuple_or_list(arg_name, tuple_or_list):\n    if not isinstance(tuple_or_list, (tuple, list)):\n        raise TypeError(\n            \"Expected %s to be a tuple or list. \"\n            \"Received %r\" % (arg_name, tuple_or_list)\n        )\n    return list(tuple_or_list)",
    "docstring": "Ensures an input is a tuple or list.\n\n    This effectively reduces the iterable types allowed to a very short\n    whitelist: list and tuple.\n\n    :type arg_name: str\n    :param arg_name: Name of argument to use in error message.\n\n    :type tuple_or_list: sequence of str\n    :param tuple_or_list: Sequence to be verified.\n\n    :rtype: list of str\n    :returns: The ``tuple_or_list`` passed in cast to a ``list``.\n    :raises TypeError: if the ``tuple_or_list`` is not a tuple or list."
  },
  {
    "code": "def multi_rpush(self, queue, values, bulk_size=0, transaction=False):\r\n        if hasattr(values, '__iter__'):\r\n            pipe = self.pipeline(transaction=transaction)\r\n            pipe.multi()\r\n            self._multi_rpush_pipeline(pipe, queue, values, bulk_size)\r\n            pipe.execute()\r\n        else:\r\n            raise ValueError('Expected an iterable')",
    "docstring": "Pushes multiple elements to a list\r\n            If bulk_size is set it will execute the pipeline every bulk_size elements\r\n            This operation will be atomic if transaction=True is passed"
  },
  {
    "code": "def scale_subplots(subplots=None, xlim='auto', ylim='auto'):\n    auto_axis = ''\n    if xlim == 'auto':\n        auto_axis += 'x'\n    if ylim == 'auto':\n        auto_axis += 'y'\n    autoscale_subplots(subplots, auto_axis)\n    for loc, ax in numpy.ndenumerate(subplots):\n        if 'x' not in auto_axis:\n            ax.set_xlim(xlim)\n        if 'y' not in auto_axis:\n            ax.set_ylim(ylim)",
    "docstring": "Set the x and y axis limits for a collection of subplots.\n\n    Parameters\n    -----------\n    subplots : ndarray or list of matplotlib.axes.Axes\n\n    xlim : None | 'auto' | (xmin, xmax)\n        'auto' : sets the limits according to the most\n        extreme values of data encountered.\n    ylim : None | 'auto' | (ymin, ymax)"
  },
  {
    "code": "def add(self, src):\n        if not audio.get_type(src):\n            raise TypeError('The type of this file is not supported.')\n        return super().add(src)",
    "docstring": "store an audio file to storage dir\n\n        :param src: audio file path\n        :return: checksum value"
  },
  {
    "code": "def newline(self, *args, **kwargs):\n        levelOverride = kwargs.get('level') or self._lastlevel\n        self._log(levelOverride, '', 'newline', args, kwargs)",
    "docstring": "Prints an empty line to the log. Uses the level of the last message\n        printed unless specified otherwise with the level= kwarg."
  },
  {
    "code": "def get_by_hostname(self, hostname):\n        resources = self._client.get_all()\n        resources_filtered = [x for x in resources if x['hostname'] == hostname]\n        if resources_filtered:\n            return resources_filtered[0]\n        else:\n            return None",
    "docstring": "Retrieve a storage system by its hostname.\n\n        Works only in API500 onwards.\n\n        Args:\n            hostname: Storage system hostname.\n\n        Returns:\n            dict"
  },
  {
    "code": "def weld_arrays_to_vec_of_struct(arrays, weld_types):\n    weld_obj = create_empty_weld_object()\n    obj_ids = [get_weld_obj_id(weld_obj, array) for array in arrays]\n    arrays = 'zip({})'.format(', '.join(obj_ids)) if len(obj_ids) > 1 else '{}'.format(obj_ids[0])\n    input_types = struct_of('{e}', weld_types) if len(obj_ids) > 1 else '{}'.format(weld_types[0])\n    res_types = struct_of('{e}', weld_types)\n    to_merge = 'e' if len(obj_ids) > 1 else '{e}'\n    weld_template =\n    weld_obj.weld_code = weld_template.format(arrays=arrays,\n                                              input_types=input_types,\n                                              res_types=res_types,\n                                              to_merge=to_merge)\n    return weld_obj",
    "docstring": "Create a vector of structs from multiple vectors.\n\n    Parameters\n    ----------\n    arrays : list of (numpy.ndarray or WeldObject)\n        Arrays to put in a struct.\n    weld_types : list of WeldType\n        The Weld types of the arrays in the same order.\n\n    Returns\n    -------\n    WeldObject\n        Representation of this computation."
  },
  {
    "code": "def _split_stock_code(self, code):\n        stock_str = str(code)\n        split_loc = stock_str.find(\".\")\n        if 0 <= split_loc < len(\n                stock_str) - 1 and stock_str[0:split_loc] in MKT_MAP:\n            market_str = stock_str[0:split_loc]\n            partial_stock_str = stock_str[split_loc + 1:]\n            return RET_OK, (market_str, partial_stock_str)\n        else:\n            error_str = ERROR_STR_PREFIX + \"format of %s is wrong. (US.AAPL, HK.00700, SZ.000001)\" % stock_str\n            return RET_ERROR, error_str",
    "docstring": "do not use the built-in split function in python.\n        The built-in function cannot handle some stock strings correctly.\n        for instance, US..DJI, where the dot . itself is a part of original code"
  },
  {
    "code": "def getPolicyValue(self):\n        self._cur.execute(\"SELECT action FROM policy\")\n        r = self._cur.fetchall()\n        policy = [x[0] for x in r]\n        self._cur.execute(\"SELECT value FROM V\")\n        r = self._cur.fetchall()\n        value = [x[0] for x in r]\n        return policy, value",
    "docstring": "Get the policy and value vectors."
  },
  {
    "code": "def columnSimilarities(self, threshold=0.0):\n        java_sims_mat = self._java_matrix_wrapper.call(\"columnSimilarities\", float(threshold))\n        return CoordinateMatrix(java_sims_mat)",
    "docstring": "Compute similarities between columns of this matrix.\n\n        The threshold parameter is a trade-off knob between estimate\n        quality and computational cost.\n\n        The default threshold setting of 0 guarantees deterministically\n        correct results, but uses the brute-force approach of computing\n        normalized dot products.\n\n        Setting the threshold to positive values uses a sampling\n        approach and incurs strictly less computational cost than the\n        brute-force approach. However the similarities computed will\n        be estimates.\n\n        The sampling guarantees relative-error correctness for those\n        pairs of columns that have similarity greater than the given\n        similarity threshold.\n\n        To describe the guarantee, we set some notation:\n            * Let A be the smallest in magnitude non-zero element of\n              this matrix.\n            * Let B be the largest in magnitude non-zero element of\n              this matrix.\n            * Let L be the maximum number of non-zeros per row.\n\n        For example, for {0,1} matrices: A=B=1.\n        Another example, for the Netflix matrix: A=1, B=5\n\n        For those column pairs that are above the threshold, the\n        computed similarity is correct to within 20% relative error\n        with probability at least 1 - (0.981)^10/B^\n\n        The shuffle size is bounded by the *smaller* of the following\n        two expressions:\n\n            * O(n log(n) L / (threshold * A))\n            * O(m L^2^)\n\n        The latter is the cost of the brute-force approach, so for\n        non-zero thresholds, the cost is always cheaper than the\n        brute-force approach.\n\n        :param: threshold: Set to 0 for deterministic guaranteed\n                           correctness. Similarities above this\n                           threshold are estimated with the cost vs\n                           estimate quality trade-off described above.\n        :return: An n x n sparse upper-triangular CoordinateMatrix of\n                 cosine similarities between columns of this matrix.\n\n        >>> rows = sc.parallelize([[1, 2], [1, 5]])\n        >>> mat = RowMatrix(rows)\n\n        >>> sims = mat.columnSimilarities()\n        >>> sims.entries.first().value\n        0.91914503..."
  },
  {
    "code": "def validate_metadata(self, handler):\n        if self.meta == 'category':\n            new_metadata = self.metadata\n            cur_metadata = handler.read_metadata(self.cname)\n            if (new_metadata is not None and cur_metadata is not None and\n                    not array_equivalent(new_metadata, cur_metadata)):\n                raise ValueError(\"cannot append a categorical with \"\n                                 \"different categories to the existing\")",
    "docstring": "validate that kind=category does not change the categories"
  },
  {
    "code": "def _types_match(type1, type2):\n        if isinstance(type1, six.string_types) and \\\n                isinstance(type2, six.string_types):\n            type1 = type1.rstrip('?')\n            type2 = type2.rstrip('?')\n            if type1 != type2:\n                return False\n        return True",
    "docstring": "Returns False only if it can show that no value of type1\n        can possibly match type2.\n\n        Supports only a limited selection of types."
  },
  {
    "code": "def append(self, data, segment=0):\n        if not hasattr(data, '__iter__'):\n            data = [data]\n        self._builder.append(data, segment)",
    "docstring": "Append a single row to an SFrame.\n\n        Throws a RuntimeError if one or more column's type is incompatible with\n        a type appended.\n\n        Parameters\n        ----------\n        data  : iterable\n            An iterable representation of a single row.\n\n        segment : int\n            The segment to write this row. Each segment is numbered\n            sequentially, starting with 0. Any value in segment 1 will be after\n            any value in segment 0, and the order of rows in each segment is\n            preserved as they are added."
  },
  {
    "code": "def largest_connected_set(C, directed=True):\n    r\n    if isdense(C):\n        return sparse.connectivity.largest_connected_set(csr_matrix(C), directed=directed)\n    else:\n        return sparse.connectivity.largest_connected_set(C, directed=directed)",
    "docstring": "r\"\"\"Largest connected component for a directed graph with edge-weights\n    given by the count matrix.\n\n    Parameters\n    ----------\n    C : scipy.sparse matrix\n        Count matrix specifying edge weights.\n    directed : bool, optional\n       Whether to compute connected components for a directed  or\n       undirected graph. Default is True.\n\n    Returns\n    -------\n    lcc : array of integers\n        The largest connected component of the directed graph.\n\n    See also\n    --------\n    connected_sets\n\n    Notes\n    -----\n    Viewing the count matrix as the adjacency matrix of a (directed)\n    graph the largest connected set is the largest connected set of\n    nodes of the corresponding graph. The largest connected set of a graph\n    can be efficiently computed using Tarjan's algorithm.\n\n    References\n    ----------\n    .. [1] Tarjan, R E. 1972. Depth-first search and linear graph\n        algorithms. SIAM Journal on Computing 1 (2): 146-160.\n\n    Examples\n    --------\n\n    >>> import numpy as np\n    >>> from msmtools.estimation import largest_connected_set\n\n    >>> C =  np.array([[10, 1, 0], [2, 0, 3], [0, 0, 4]])\n    >>> lcc_directed = largest_connected_set(C)\n    >>> lcc_directed\n    array([0, 1])\n\n    >>> lcc_undirected = largest_connected_set(C, directed=False)\n    >>> lcc_undirected\n    array([0, 1, 2])"
  },
  {
    "code": "def open_in_composer(self):\n        impact_layer = self.impact_function.analysis_impacted\n        report_path = dirname(impact_layer.source())\n        impact_report = self.impact_function.impact_report\n        custom_map_report_metadata = impact_report.metadata\n        custom_map_report_product = (\n            custom_map_report_metadata.component_by_tags(\n                [final_product_tag, pdf_product_tag]))\n        for template_path in self.retrieve_paths(\n                custom_map_report_product,\n                report_path=report_path,\n                suffix='.qpt'):\n            layout = QgsPrintLayout(QgsProject.instance())\n            with open(template_path) as template_file:\n                template_content = template_file.read()\n            document = QtXml.QDomDocument()\n            document.setContent(template_content)\n            rwcontext = QgsReadWriteContext()\n            load_status = layout.loadFromTemplate(document, rwcontext)\n            if not load_status:\n                QtWidgets.QMessageBox.warning(\n                    self,\n                    tr('InaSAFE'),\n                    tr('Error loading template: %s') % template_path)\n                return\n            QgsProject.instance().layoutManager().addLayout(layout)\n            self.iface.openLayoutDesigner(layout)",
    "docstring": "Open in layout designer a given MapReport instance.\n\n        .. versionadded: 4.3.0"
  },
  {
    "code": "def _validation_error(prop, prop_type, prop_value, expected):\n    if prop_type is None:\n        attrib = 'value'\n        assigned = prop_value\n    else:\n        attrib = 'type'\n        assigned = prop_type\n    raise ValidationError(\n        'Invalid property {attrib} for {prop}:\\n\\t{attrib}: {assigned}\\n\\texpected: {expected}',\n        attrib=attrib, prop=prop, assigned=assigned, expected=expected,\n        invalid={prop: prop_value} if attrib == 'value' else {}\n    )",
    "docstring": "Default validation for updated properties"
  },
  {
    "code": "def func(\n    coroutine: Union[str, Function, Callable],\n    *,\n    name: Optional[str] = None,\n    keep_result: Optional[SecondsTimedelta] = None,\n    timeout: Optional[SecondsTimedelta] = None,\n    max_tries: Optional[int] = None,\n) -> Function:\n    if isinstance(coroutine, Function):\n        return coroutine\n    if isinstance(coroutine, str):\n        name = name or coroutine\n        coroutine = import_string(coroutine)\n    assert asyncio.iscoroutinefunction(coroutine), f'{coroutine} is not a coroutine function'\n    timeout = to_seconds(timeout)\n    keep_result = to_seconds(keep_result)\n    return Function(name or coroutine.__qualname__, coroutine, timeout, keep_result, max_tries)",
    "docstring": "Wrapper for a job function which lets you configure more settings.\n\n    :param coroutine: coroutine function to call, can be a string to import\n    :param name: name for function, if None, ``coroutine.__qualname__`` is used\n    :param keep_result: duration to keep the result for, if 0 the result is not kept\n    :param timeout: maximum time the job should take\n    :param max_tries: maximum number of tries allowed for the function, use 1 to prevent retrying"
  },
  {
    "code": "def get_ga_client_id(self):\n        request = self.get_ga_request()\n        if not request or not hasattr(request, 'session'):\n            return super(GARequestErrorReportingMixin, self).get_ga_client_id()\n        if 'ga_client_id' not in request.session:\n            client_id = self.ga_cookie_re.match(request.COOKIES.get('_ga', ''))\n            client_id = client_id and client_id.group('cid') or str(uuid.uuid4())\n            request.session['ga_client_id'] = client_id\n        return request.session['ga_client_id']",
    "docstring": "Retrieve the client ID from the Google Analytics cookie, if available,\n        and save in the current session"
  },
  {
    "code": "def _read_para_seq_data(self, code, cbit, clen, *, desc, length, version):\n        if clen != 4:\n            raise ProtocolError(f'HIPv{version}: [Parano {code}] invalid format')\n        _seqn = self._read_unpack(4)\n        seq_data = dict(\n            type=desc,\n            critical=cbit,\n            length=clen,\n            seq=_seqn,\n        )\n        return seq_data",
    "docstring": "Read HIP SEQ_DATA parameter.\n\n        Structure of HIP SEQ_DATA parameter [RFC 6078]:\n             0                   1                   2                   3\n             0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |             Type              |             Length            |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |                        Sequence number                        |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n            Octets      Bits        Name                            Description\n              0           0     seq_data.type                   Parameter Type\n              1          15     seq_data.critical               Critical Bit\n              2          16     seq_data.length                 Length of Contents\n              4          32     seq_data.seq                    Sequence number"
  },
  {
    "code": "def cmd_karma_bulk(infile, jsonout, badonly, verbose):\n    if verbose:\n        logging.basicConfig(level=logging.INFO, format='%(message)s')\n    data = infile.read()\n    result = {}\n    for ip in data.split('\\n'):\n        if ip:\n            logging.info('Checking ' + ip)\n            response = karma(ip)\n            if response:\n                result[ip] = response\n            elif not badonly:\n                result[ip] = ['CLEAN']\n    if jsonout:\n        print(json.dumps(result, indent=4))\n    else:\n        for k,v in result.items():\n            print(k, '\\t', ','.join(v))",
    "docstring": "Show which IP addresses are inside blacklists using the Karma online service.\n\n    Example:\n\n    \\b\n    $ cat /var/log/auth.log | habu.extract.ipv4 | habu.karma.bulk\n    172.217.162.4   spamhaus_drop,alienvault_spamming\n    23.52.213.96    CLEAN\n    190.210.43.70   alienvault_malicious"
  },
  {
    "code": "def get_space_id(deployment_name,\n                 space_name,\n                 token_manager=None,\n                 app_url=defaults.APP_URL):\n    spaces = get_spaces(deployment_name,\n                        token_manager=token_manager,\n                        app_url=app_url)\n    for space in spaces:\n        if space['name'] == space_name:\n            return space['id']\n    raise JutException('Unable to find space \"%s\" within deployment \"%s\"' %\n                    (space_name, deployment_name))",
    "docstring": "get the space id that relates to the space name provided"
  },
  {
    "code": "def oauth_access(\n        self, *, client_id: str, client_secret: str, code: str, **kwargs\n    ) -> SlackResponse:\n        kwargs.update(\n            {\"client_id\": client_id, \"client_secret\": client_secret, \"code\": code}\n        )\n        return self.api_call(\"oauth.access\", data=kwargs)",
    "docstring": "Exchanges a temporary OAuth verifier code for an access token.\n\n        Args:\n            client_id (str): Issued when you created your application. e.g. '4b39e9-752c4'\n            client_secret (str): Issued when you created your application. e.g. '33fea0113f5b1'\n            code (str): The code param returned via the OAuth callback. e.g. 'ccdaa72ad'"
  },
  {
    "code": "def delete(self, indexes):\n        indexes = [indexes] if not isinstance(indexes, (list, blist)) else indexes\n        if all([isinstance(i, bool) for i in indexes]):\n            if len(indexes) != len(self._index):\n                raise ValueError('boolean indexes list must be same size of existing indexes')\n            indexes = [i for i, x in enumerate(indexes) if x]\n        else:\n            indexes = [sorted_index(self._index, x) for x in indexes] if self._sort \\\n                else [self._index.index(x) for x in indexes]\n        indexes = sorted(indexes, reverse=True)\n        for i in indexes:\n            del self._data[i]\n        for i in indexes:\n            del self._index[i]",
    "docstring": "Delete rows from the DataFrame\n\n        :param indexes: either a list of values or list of booleans for the rows to delete\n        :return: nothing"
  },
  {
    "code": "def linear_deform(template, displacement, out=None):\n    image_pts = template.space.points()\n    for i, vi in enumerate(displacement):\n        image_pts[:, i] += vi.asarray().ravel()\n    values = template.interpolation(image_pts.T, out=out, bounds_check=False)\n    return values.reshape(template.space.shape)",
    "docstring": "Linearized deformation of a template with a displacement field.\n\n    The function maps a given template ``I`` and a given displacement\n    field ``v`` to the new function ``x --> I(x + v(x))``.\n\n    Parameters\n    ----------\n    template : `DiscreteLpElement`\n        Template to be deformed by a displacement field.\n    displacement : element of power space of ``template.space``\n        Vector field (displacement field) used to deform the\n        template.\n    out : `numpy.ndarray`, optional\n        Array to which the function values of the deformed template\n        are written. It must have the same shape as ``template`` and\n        a data type compatible with ``template.dtype``.\n\n    Returns\n    -------\n    deformed_template : `numpy.ndarray`\n        Function values of the deformed template. If ``out`` was given,\n        the returned object is a reference to it.\n\n    Examples\n    --------\n    Create a simple 1D template to initialize the operator and\n    apply it to a displacement field. Where the displacement is zero,\n    the output value is the same as the input value.\n    In the 4-th point, the value is taken from 0.2 (one cell) to the\n    left, i.e. 1.0.\n\n    >>> space = odl.uniform_discr(0, 1, 5)\n    >>> disp_field_space = space.tangent_bundle\n    >>> template = space.element([0, 0, 1, 0, 0])\n    >>> displacement_field = disp_field_space.element([[0, 0, 0, -0.2, 0]])\n    >>> linear_deform(template, displacement_field)\n    array([ 0.,  0.,  1.,  1.,  0.])\n\n    The result depends on the chosen interpolation. With 'linear'\n    interpolation and an offset equal to half the distance between two\n    points, 0.1, one gets the mean of the values.\n\n    >>> space = odl.uniform_discr(0, 1, 5, interp='linear')\n    >>> disp_field_space = space.tangent_bundle\n    >>> template = space.element([0, 0, 1, 0, 0])\n    >>> displacement_field = disp_field_space.element([[0, 0, 0, -0.1, 0]])\n    >>> linear_deform(template, displacement_field)\n    array([ 0. ,  0. ,  1. ,  0.5,  0. ])"
  },
  {
    "code": "def set_lacp_timeout(self, name, value=None):\n        commands = ['interface %s' % name]\n        string = 'port-channel lacp fallback timeout'\n        commands.append(self.command_builder(string, value=value))\n        return self.configure(commands)",
    "docstring": "Configures the Port-Channel LACP fallback timeout\n           The fallback timeout configures the period an interface in\n           fallback mode remains in LACP mode without receiving a PDU.\n\n        Args:\n            name(str): The Port-Channel interface name\n\n            value(int): port-channel lacp fallback timeout in seconds\n\n        Returns:\n            True if the operation succeeds otherwise False is returned"
  },
  {
    "code": "def random_gate(qubits: Union[int, Qubits]) -> Gate:\n    r\n    N, qubits = qubits_count_tuple(qubits)\n    unitary = scipy.stats.unitary_group.rvs(2**N)\n    return Gate(unitary, qubits=qubits, name='RAND{}'.format(N))",
    "docstring": "r\"\"\"Returns a random unitary gate on K qubits.\n\n    Ref:\n        \"How to generate random matrices from the classical compact groups\"\n        Francesco Mezzadri, math-ph/0609050"
  },
  {
    "code": "def from_handle(fh, stream_default='fasta'):\n    if fh in (sys.stdin, sys.stdout, sys.stderr):\n        return stream_default\n    return from_filename(fh.name)",
    "docstring": "Look up the BioPython file type corresponding to a file-like object.\n\n    For stdin, stdout, and stderr, ``stream_default`` is used."
  },
  {
    "code": "def _rshift_arithmetic(self, shift_amount):\n        if self.is_empty:\n            return self\n        nsplit = self._nsplit()\n        if len(nsplit) == 1:\n            highest_bit_set = self.lower_bound > StridedInterval.signed_max_int(nsplit[0].bits)\n            l = self.lower_bound >> shift_amount\n            u = self.upper_bound >> shift_amount\n            stride = max(self.stride >> shift_amount, 1)\n            mask = ((2 ** shift_amount - 1) << (self.bits - shift_amount))\n            if highest_bit_set:\n                l = l | mask\n                u = u | mask\n            if l == u:\n                stride = 0\n            return StridedInterval(bits=self.bits,\n                                   lower_bound=l,\n                                   upper_bound=u,\n                                   stride=stride,\n                                   uninitialized=self.uninitialized\n                                   )\n        else:\n            a = nsplit[0]._rshift_arithmetic(shift_amount)\n            b = nsplit[1]._rshift_arithmetic(shift_amount)\n            return a.union(b)",
    "docstring": "Arithmetic shift right with a concrete shift amount\n\n        :param int shift_amount: Number of bits to shift right.\n        :return: The new StridedInterval after right shifting\n        :rtype: StridedInterval"
  },
  {
    "code": "def _apply(self, func, name, window=None, center=None,\n               check_minp=None, **kwargs):\n        def f(x, name=name, *args):\n            x = self._shallow_copy(x)\n            if isinstance(name, str):\n                return getattr(x, name)(*args, **kwargs)\n            return x.apply(name, *args, **kwargs)\n        return self._groupby.apply(f)",
    "docstring": "Dispatch to apply; we are stripping all of the _apply kwargs and\n        performing the original function call on the grouped object."
  },
  {
    "code": "def highlight_min(self, subset=None, color='yellow', axis=0):\n        return self._highlight_handler(subset=subset, color=color, axis=axis,\n                                       max_=False)",
    "docstring": "Highlight the minimum by shading the background.\n\n        Parameters\n        ----------\n        subset : IndexSlice, default None\n            a valid slice for ``data`` to limit the style application to.\n        color : str, default 'yellow'\n        axis : {0 or 'index', 1 or 'columns', None}, default 0\n            apply to each column (``axis=0`` or ``'index'``), to each row\n            (``axis=1`` or ``'columns'``), or to the entire DataFrame at once\n            with ``axis=None``.\n\n        Returns\n        -------\n        self : Styler"
  },
  {
    "code": "def find_worktree_git_dir(dotgit):\n    try:\n        statbuf = os.stat(dotgit)\n    except OSError:\n        return None\n    if not stat.S_ISREG(statbuf.st_mode):\n        return None\n    try:\n        lines = open(dotgit, 'r').readlines()\n        for key, value in [line.strip().split(': ') for line in lines]:\n            if key == 'gitdir':\n                return value\n    except ValueError:\n        pass\n    return None",
    "docstring": "Search for a gitdir for this worktree."
  },
  {
    "code": "def process_byte(self, tag):\n        tag.set_address(self.normal_register.current_address)\n        self.normal_register.move_to_next_address(1)",
    "docstring": "Process byte type tags"
  },
  {
    "code": "def _global_step(hparams):\n  step = tf.to_float(tf.train.get_or_create_global_step())\n  multiplier = hparams.optimizer_multistep_accumulate_steps\n  if not multiplier:\n    return step\n  tf.logging.info(\"Dividing global step by %d for multi-step optimizer.\"\n                  % multiplier)\n  return step / tf.to_float(multiplier)",
    "docstring": "Adjust global step if a multi-step optimizer is used."
  },
  {
    "code": "def get_flattened_bsp_keys_from_schema(schema):\n    keys = []\n    for key in schema.declared_fields.keys():\n        field = schema.declared_fields[key]\n        if isinstance(field, mm.fields.Nested) and \\\n                isinstance(field.schema, BoundSpatialPoint):\n            keys.append(\"{}.{}\".format(key, \"position\"))\n    return keys",
    "docstring": "Returns the flattened keys of BoundSpatialPoints in a schema\n\n    :param schema: schema\n    :return: list"
  },
  {
    "code": "def shear(cls, x_angle=0, y_angle=0):\n        sx = math.tan(math.radians(x_angle))\n        sy = math.tan(math.radians(y_angle))\n        return tuple.__new__(cls, (1.0, sy, 0.0, sx, 1.0, 0.0, 0.0, 0.0, 1.0))",
    "docstring": "Create a shear transform along one or both axes.\n\n        :param x_angle: Angle in degrees to shear along the x-axis.\n        :type x_angle: float\n        :param y_angle: Angle in degrees to shear along the y-axis.\n        :type y_angle: float\n        :rtype: Affine"
  },
  {
    "code": "def _complete_multipart_upload(self, bucket_name, object_name,\n                                   upload_id, uploaded_parts):\n        is_valid_bucket_name(bucket_name)\n        is_non_empty_string(object_name)\n        is_non_empty_string(upload_id)\n        ordered_parts = []\n        for part in sorted(uploaded_parts.keys()):\n            ordered_parts.append(uploaded_parts[part])\n        data = xml_marshal_complete_multipart_upload(ordered_parts)\n        sha256_hex = get_sha256_hexdigest(data)\n        md5_base64 = get_md5_base64digest(data)\n        headers = {\n            'Content-Length': len(data),\n            'Content-Type': 'application/xml',\n            'Content-Md5': md5_base64,\n        }\n        response = self._url_open('POST', bucket_name=bucket_name,\n                                  object_name=object_name,\n                                  query={'uploadId': upload_id},\n                                  headers=headers, body=data,\n                                  content_sha256=sha256_hex)\n        return parse_multipart_upload_result(response.data)",
    "docstring": "Complete an active multipart upload request.\n\n        :param bucket_name: Bucket name of the multipart request.\n        :param object_name: Object name of the multipart request.\n        :param upload_id: Upload id of the active multipart request.\n        :param uploaded_parts: Key, Value dictionary of uploaded parts."
  },
  {
    "code": "def metis(hdf5_file_name, N_clusters_max):\n    file_name = wgraph(hdf5_file_name)\n    labels = sgraph(N_clusters_max, file_name)\n    subprocess.call(['rm', file_name])\n    return labels",
    "docstring": "METIS algorithm by Karypis and Kumar. Partitions the induced similarity graph \n        passed by CSPA.\n\n    Parameters\n    ----------\n    hdf5_file_name : string or file handle\n    \n    N_clusters_max : int\n    \n    Returns\n    -------\n    labels : array of shape (n_samples,)\n        A vector of labels denoting the cluster to which each sample has been assigned\n        as a result of the CSPA heuristics for consensus clustering.\n    \n    Reference\n    ---------\n    G. Karypis and V. Kumar, \"A Fast and High Quality Multilevel Scheme for\n    Partitioning Irregular Graphs\"\n    In: SIAM Journal on Scientific Computing, Vol. 20, No. 1, pp. 359-392, 1999."
  },
  {
    "code": "def camelize(word):\n    return ''.join(w[0].upper() + w[1:]\n                   for w in re.sub('[^A-Z^a-z^0-9^:]+', ' ', word).split(' '))",
    "docstring": "Convert a word from lower_with_underscores to CamelCase.\n\n    Args:\n        word: The string to convert.\n    Returns:\n        The modified string."
  },
  {
    "code": "def channelize(gen, channels):\n\tdef pick(g, channel):\n\t\tfor samples in g:\n\t\t\tyield samples[channel]\n\treturn [pick(gen_copy, channel) for channel, gen_copy in enumerate(itertools.tee(gen, channels))]",
    "docstring": "Break multi-channel generator into one sub-generator per channel\n\n\tTakes a generator producing n-tuples of samples and returns n generators,\n\teach producing samples for a single channel.\n\n\tSince multi-channel generators are the only reasonable way to synchronize samples\n\tacross channels, and the sampler functions only take tuples of generators,\n\tyou must use this function to process synchronized streams for output."
  },
  {
    "code": "def fbank(wav_path, flat=True):\n    (rate, sig) = wav.read(wav_path)\n    if len(sig) == 0:\n        logger.warning(\"Empty wav: {}\".format(wav_path))\n    fbank_feat = python_speech_features.logfbank(sig, rate, nfilt=40)\n    energy = extract_energy(rate, sig)\n    feat = np.hstack([energy, fbank_feat])\n    delta_feat = python_speech_features.delta(feat, 2)\n    delta_delta_feat = python_speech_features.delta(delta_feat, 2)\n    all_feats = [feat, delta_feat, delta_delta_feat]\n    if not flat:\n        all_feats = np.array(all_feats)\n        all_feats = np.swapaxes(all_feats, 0, 1)\n        all_feats = np.swapaxes(all_feats, 1, 2)\n    else:\n        all_feats = np.concatenate(all_feats, axis=1)\n    feat_fn = wav_path[:-3] + \"fbank.npy\"\n    np.save(feat_fn, all_feats)",
    "docstring": "Currently grabs log Mel filterbank, deltas and double deltas."
  },
  {
    "code": "def section_term_branch_orders(neurites, neurite_type=NeuriteType.all):\n    return map_sections(sectionfunc.branch_order, neurites, neurite_type=neurite_type,\n                        iterator_type=Tree.ileaf)",
    "docstring": "Termination section branch orders in a collection of neurites"
  },
  {
    "code": "def _netstat_route_netbsd():\n    ret = []\n    cmd = 'netstat -f inet -rn | tail -n+5'\n    out = __salt__['cmd.run'](cmd, python_shell=True)\n    for line in out.splitlines():\n        comps = line.split()\n        ret.append({\n            'addr_family': 'inet',\n            'destination': comps[0],\n            'gateway': comps[1],\n            'netmask': '',\n            'flags': comps[3],\n            'interface': comps[6]})\n    cmd = 'netstat -f inet6 -rn | tail -n+5'\n    out = __salt__['cmd.run'](cmd, python_shell=True)\n    for line in out.splitlines():\n        comps = line.split()\n        ret.append({\n            'addr_family': 'inet6',\n            'destination': comps[0],\n            'gateway': comps[1],\n            'netmask': '',\n            'flags': comps[3],\n            'interface': comps[6]})\n    return ret",
    "docstring": "Return netstat routing information for NetBSD"
  },
  {
    "code": "async def create_lease_store_if_not_exists_async(self):\n        try:\n            await self.host.loop.run_in_executor(\n                self.executor,\n                functools.partial(\n                    self.storage_client.create_container,\n                    self.lease_container_name))\n        except Exception as err:\n            _logger.error(\"%r\", err)\n            raise err\n        return True",
    "docstring": "Create the lease store if it does not exist, do nothing if it does exist.\n\n        :return: `True` if the lease store already exists or was created successfully, `False` if not.\n        :rtype: bool"
  },
  {
    "code": "def validate_subnet(s):\n    if isinstance(s, basestring):\n        if '/' in s:\n            start, mask = s.split('/', 2)\n            return validate_ip(start) and validate_netmask(mask)\n        else:\n            return False\n    raise TypeError(\"expected string or unicode\")",
    "docstring": "Validate a dotted-quad ip address including a netmask.\n\n    The string is considered a valid dotted-quad address with netmask if it\n    consists of one to four octets (0-255) seperated by periods (.) followed\n    by a forward slash (/) and a subnet bitmask which is expressed in\n    dotted-quad format.\n\n\n    >>> validate_subnet('127.0.0.1/255.255.255.255')\n    True\n    >>> validate_subnet('127.0/255.0.0.0')\n    True\n    >>> validate_subnet('127.0/255')\n    True\n    >>> validate_subnet('127.0.0.256/255.255.255.255')\n    False\n    >>> validate_subnet('127.0.0.1/255.255.255.256')\n    False\n    >>> validate_subnet('127.0.0.0')\n    False\n    >>> validate_subnet(None)\n    Traceback (most recent call last):\n        ...\n    TypeError: expected string or unicode\n\n\n    :param s: String to validate as a dotted-quad ip address with netmask.\n    :type s: str\n    :returns: ``True`` if a valid dotted-quad ip address with netmask,\n        ``False`` otherwise.\n    :raises: TypeError"
  },
  {
    "code": "def expand(doc, doc_url=\"param://\", params=None):\n    if doc_url.find(\"://\") == -1:\n        Log.error(\"{{url}} must have a prototcol (eg http://) declared\", url=doc_url)\n    url = URL(doc_url)\n    url.query = set_default(url.query, params)\n    phase1 = _replace_ref(doc, url)\n    phase2 = _replace_locals(phase1, [phase1])\n    return wrap(phase2)",
    "docstring": "ASSUMING YOU ALREADY PULED THE doc FROM doc_url, YOU CAN STILL USE THE\n    EXPANDING FEATURE\n\n    USE mo_json_config.expand({}) TO ASSUME CURRENT WORKING DIRECTORY\n\n    :param doc: THE DATA STRUCTURE FROM JSON SOURCE\n    :param doc_url: THE URL THIS doc CAME FROM (DEFAULT USES params AS A DOCUMENT SOURCE)\n    :param params: EXTRA PARAMETERS NOT FOUND IN THE doc_url PARAMETERS (WILL SUPERSEDE PARAMETERS FROM doc_url)\n    :return: EXPANDED JSON-SERIALIZABLE STRUCTURE"
  },
  {
    "code": "def addRectAnnot(self, rect):\n        CheckParent(self)\n        val = _fitz.Page_addRectAnnot(self, rect)\n        if not val: return\n        val.thisown = True\n        val.parent = weakref.proxy(self)\n        self._annot_refs[id(val)] = val\n        return val",
    "docstring": "Add a 'Rectangle' annotation."
  },
  {
    "code": "def start_router(router_class, router_name):\n    handle = router_class.remote(router_name)\n    ray.experimental.register_actor(router_name, handle)\n    handle.start.remote()\n    return handle",
    "docstring": "Wrapper for starting a router and register it.\n\n    Args:\n        router_class: The router class to instantiate.\n        router_name: The name to give to the router.\n\n    Returns:\n        A handle to newly started router actor."
  },
  {
    "code": "def _to_event_data(obj):\n    if obj is None:\n        return None\n    if isinstance(obj, bool):\n        return obj\n    if isinstance(obj, int):\n        return obj\n    if isinstance(obj, float):\n        return obj\n    if isinstance(obj, str):\n        return obj\n    if isinstance(obj, bytes):\n        return obj\n    if isinstance(obj, dict):\n        return obj\n    if isinstance(obj, NodeDriver):\n        return obj.name\n    if isinstance(obj, list):\n        return [_to_event_data(item) for item in obj]\n    event_data = {}\n    for attribute_name in dir(obj):\n        if attribute_name.startswith('_'):\n            continue\n        attribute_value = getattr(obj, attribute_name)\n        if callable(attribute_value):\n            continue\n        event_data[attribute_name] = _to_event_data(attribute_value)\n    return event_data",
    "docstring": "Convert the specified object into a form that can be serialised by msgpack as event data.\n\n    :param obj: The object to convert."
  },
  {
    "code": "def load_stock_quantity(self):\n        info = StocksInfo(self.config)\n        for stock in self.model.stocks:\n            stock.quantity = info.load_stock_quantity(stock.symbol)\n        info.gc_book.close()",
    "docstring": "Loads quantities for all stocks"
  },
  {
    "code": "def mri_knee_data_8_channel():\n    url = 'https://zenodo.org/record/800529/files/3_rawdata_knee_8ch.mat'\n    dct = get_data('3_rawdata_knee_8ch.mat', subset=DATA_SUBSET, url=url)\n    data = flip(np.swapaxes(dct['rawdata'], 0, -1) * 9e3, 2)\n    return data",
    "docstring": "Raw data for 8 channel MRI of a knee.\n\n    This is an SE measurement of the knee of a healthy volunteer.\n\n    The data has been rescaled so that the reconstruction fits approximately in\n    [0, 1].\n\n    See the data source with DOI `10.5281/zenodo.800529`_ or the\n    `project webpage`_ for further information.\n\n    See Also\n    --------\n    mri_knee_inverse_8_channel\n\n    References\n    ----------\n    .. _10.5281/zenodo.800529: https://zenodo.org/record/800529\n    .. _project webpage: http://imsc.uni-graz.at/mobis/internal/\\\nplatform_aktuell.html"
  },
  {
    "code": "def insert(self, part):\n        params = {k: str(v) for k,v in part.params.items()}\n        res=c.create_assembly_instance(self.uri.as_dict(), part.uri.as_dict(), params)\n        return res",
    "docstring": "Insert a part into this assembly.\n\n        Args:\n            - part (onshapepy.part.Part) A Part instance that will be inserted.\n\n        Returns:\n            - requests.Response: Onshape response data"
  },
  {
    "code": "def get_days_in_month(year: int, month: int) -> int:\n    month_range = calendar.monthrange(year, month)\n    return month_range[1]",
    "docstring": "Returns number of days in the given month.\n    1-based numbers as arguments. i.e. November = 11"
  },
  {
    "code": "def _control_longitude(self):\n        if self.lonm < 0.0:\n            self.lonm = 360.0 + self.lonm\n        if self.lonM < 0.0:\n            self.lonM = 360.0 + self.lonM\n        if self.lonm > 360.0:\n            self.lonm = self.lonm - 360.0\n        if self.lonM > 360.0:\n            self.lonM = self.lonM - 360.0",
    "docstring": "Control on longitude values"
  },
  {
    "code": "def _handle_aleph_keyword_view(dataset):\n        adder = ViewController.aleph_kw_handler.add_keyword\n        for keyword in dataset.get(\"keyword_tags\", []):\n            adder(keyword[\"val\"])\n        if \"keyword_tags\" in dataset:\n            del dataset[\"keyword_tags\"]",
    "docstring": "Translate the Aleph keywords to locally used data."
  },
  {
    "code": "def _remove_white_background(image):\n    from PIL import ImageMath, Image\n    if image.mode == \"RGBA\":\n        bands = image.split()\n        a = bands[3]\n        rgb = [\n            ImageMath.eval(\n                'convert('\n                'float(x + a - 255) * 255.0 / float(max(a, 1)) * '\n                'float(min(a, 1)) + float(x) * float(1 - min(a, 1))'\n                ', \"L\")',\n                x=x, a=a\n            )\n            for x in bands[:3]\n        ]\n        return Image.merge(bands=rgb + [a], mode=\"RGBA\")\n    return image",
    "docstring": "Remove white background in the preview image."
  },
  {
    "code": "def global_request(self, kind, data=None, wait=True):\n        if wait:\n            self.completion_event = threading.Event()\n        m = Message()\n        m.add_byte(cMSG_GLOBAL_REQUEST)\n        m.add_string(kind)\n        m.add_boolean(wait)\n        if data is not None:\n            m.add(*data)\n        self._log(DEBUG, 'Sending global request \"%s\"' % kind)\n        self._send_user_message(m)\n        if not wait:\n            return None\n        while True:\n            self.completion_event.wait(0.1)\n            if not self.active:\n                return None\n            if self.completion_event.isSet():\n                break\n        return self.global_response",
    "docstring": "Make a global request to the remote host.  These are normally\n        extensions to the SSH2 protocol.\n\n        :param str kind: name of the request.\n        :param tuple data:\n            an optional tuple containing additional data to attach to the\n            request.\n        :param bool wait:\n            ``True`` if this method should not return until a response is\n            received; ``False`` otherwise.\n        :return:\n            a `.Message` containing possible additional data if the request was\n            successful (or an empty `.Message` if ``wait`` was ``False``);\n            ``None`` if the request was denied."
  },
  {
    "code": "def init_app(self, app, config_prefix=None):\n        self.kill_session = self.original_kill_session\n        config_prefix = (config_prefix or 'JIRA').rstrip('_').upper()\n        if not hasattr(app, 'extensions'):\n            app.extensions = dict()\n        if config_prefix.lower() in app.extensions:\n            raise ValueError('Already registered config prefix {0!r}.'.format(config_prefix))\n        app.extensions[config_prefix.lower()] = _JIRAState(self, app)\n        args = read_config(app.config, config_prefix)\n        try:\n            super(JIRA, self).__init__(**args)\n        except ConnectionError:\n            if not app.config.get('{0}_IGNORE_INITIAL_CONNECTION_FAILURE'.format(config_prefix)):\n                raise\n            LOG.exception('Ignoring ConnectionError.')",
    "docstring": "Actual method to read JIRA settings from app configuration and initialize the JIRA instance.\n\n        Positional arguments:\n        app -- Flask application instance.\n\n        Keyword arguments:\n        config_prefix -- Prefix used in config key names in the Flask app's configuration. Useful for applications which\n            maintain two authenticated sessions with a JIRA server. Default is 'JIRA'. Will be converted to upper case.\n            Examples:\n                JIRA_SYSTEM_SERVER = 'http://jira.mycompany.com'\n                JIRA_SYSTEM_USER = 'system_account'\n                JIRA_SERVER = 'http://jira.mycompany.com'\n                JIRA_TOKEN = '<token for oauthing users>'"
  },
  {
    "code": "def beam(problem, beam_size=100, iterations_limit=0, viewer=None):\n    return _local_search(problem,\n                         _all_expander,\n                         iterations_limit=iterations_limit,\n                         fringe_size=beam_size,\n                         random_initial_states=True,\n                         stop_when_no_better=iterations_limit==0,\n                         viewer=viewer)",
    "docstring": "Beam search.\n\n    beam_size is the size of the beam.\n    If iterations_limit is specified, the algorithm will end after that\n    number of iterations. Else, it will continue until it can't find a\n    better node than the current one.\n    Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value,\n    and SearchProblem.generate_random_state."
  },
  {
    "code": "def open(self, section_index=0):\n        uri = self._sections[section_index][1]\n        if len(uri.split()) == 1:\n            self._open_url(uri)\n        else:\n            if self._verbose:\n                print \"running command: %s\" % uri\n            p = popen(uri, shell=True)\n            p.wait()",
    "docstring": "Launch a help section."
  },
  {
    "code": "def on_chord_part_return(self, task, state, result, propagate=False):\n        u\n        with transaction.atomic():\n            chord_data = ChordData.objects.select_for_update().get(\n                callback_result__task_id=task.request.chord[u'options'][u'task_id']\n            )\n            _ = TaskMeta.objects.update_or_create(\n                task_id=task.request.id,\n                defaults={\n                    u'status': state,\n                    u'result': result\n                }\n            )\n            if chord_data.is_ready():\n                self.get_suitable_app(current_app).tasks[u'celery.backend_cleanup'].apply_async()\n                chord_data.execute_callback()",
    "docstring": "u\"\"\"\n        Update the linking ChordData object and execute callback if needed.\n\n        Parameters\n        ----------\n            subtask: The subtask that just finished executing. Most useful values\n                are stored on subtask.request.\n            state: the status of the just-finished subtask.\n            result: the resulting value of subtask execution.\n            propagate: unused here, we check CELERY_CHORD_PROPAGATES and the\n                chord's options in chord_data.execute_callback()"
  },
  {
    "code": "def set_switch_state(self, state):\n        self.set_service_value(\n            self.switch_service,\n            'Target',\n            'newTargetValue',\n            state)\n        self.set_cache_value('Status', state)",
    "docstring": "Set the switch state, also update local state."
  },
  {
    "code": "def norm_squared(x, Mx=None, inner_product=ip_euclid):\n    assert(len(x.shape) == 2)\n    if Mx is None:\n        rho = inner_product(x, x)\n    else:\n        assert(len(Mx.shape) == 2)\n        rho = inner_product(x, Mx)\n    if rho.shape == (1, 1):\n        if abs(rho[0, 0].imag) > abs(rho[0, 0])*1e-10 or rho[0, 0].real < 0.0:\n            raise InnerProductError(('<x,Mx> = %g. Is the inner product '\n                                     'indefinite?') % rho[0, 0])\n    return numpy.linalg.norm(rho, 2)",
    "docstring": "Compute the norm^2 w.r.t. to a given scalar product."
  },
  {
    "code": "def clone_repo(pkg, dest, repo, repo_dest, branch):\n    git(['clone', '--recursive', '-b', branch, repo, repo_dest])",
    "docstring": "Clone the Playdoh repo into a custom path."
  },
  {
    "code": "def apply_adaptation(self, target_illuminant, adaptation='bradford'):\n        logger.debug(\"  \\- Original illuminant: %s\", self.illuminant)\n        logger.debug(\"  \\- Target illuminant: %s\", target_illuminant)\n        if self.illuminant != target_illuminant:\n            logger.debug(\"  \\* Applying transformation from %s to %s \",\n                         self.illuminant, target_illuminant)\n            apply_chromatic_adaptation_on_color(\n                color=self,\n                targ_illum=target_illuminant,\n                adaptation=adaptation)",
    "docstring": "This applies an adaptation matrix to change the XYZ color's illuminant.\n        You'll most likely only need this during RGB conversions."
  },
  {
    "code": "def combination(n, r):\n    if n == r or r == 0:\n        return 1\n    else:\n        return combination(n-1, r-1) + combination(n-1, r)",
    "docstring": "This function calculates nCr."
  },
  {
    "code": "def get(self):\n        LOG.info('Returning all ansible runs')\n        response = []\n        for run in self.backend_store.list_runs():\n            response.append(run_model.format_response(run))\n        return response",
    "docstring": "Get run list"
  },
  {
    "code": "def indexables(self):\n        if self._indexables is None:\n            d = self.description\n            self._indexables = [GenericIndexCol(name='index', axis=0)]\n            for i, n in enumerate(d._v_names):\n                dc = GenericDataIndexableCol(\n                    name=n, pos=i, values=[n], version=self.version)\n                self._indexables.append(dc)\n        return self._indexables",
    "docstring": "create the indexables from the table description"
  },
  {
    "code": "def copystat(self, target):\n        shutil.copystat(self.path, self._to_backend(target))",
    "docstring": "Copies the permissions, times and flags from this to the `target`.\n\n        The owner is not copied."
  },
  {
    "code": "def connect(*cmds, **kwargs):\n    stdin = kwargs.get(\"stdin\")\n    env = kwargs.get(\"env\", os.environ)\n    timeout = kwargs.get(\"timeout\")\n    end = len(cmds) - 1\n    @contextmanager\n    def inner(idx, inp):\n        with stream(cmds[idx], stdin=inp, env=env, timeout=timeout) as s:\n            if idx == end:\n                yield s\n            else:\n                with inner(idx + 1, s) as c:\n                    yield c\n    with inner(0, stdin) as s:\n        yield s",
    "docstring": "Connects multiple command streams together and yields the final stream.\n\n    Args:\n        cmds (list): list of commands to pipe together. Each command will be an\n            input to ``stream``.\n        stdin (file like object): stream to use as the first command's\n            standard input.\n        env (dict): The environment in which to execute the commands. PATH\n            should be defined.\n        timeout (int): Amount of time in seconds to give the pipeline to complete.\n            The ``timeout`` utility must be installed to use this feature.\n\n    Yields:\n        The output stream for the final command in the pipeline. It should\n        typically be wrapped in a ``reader``."
  },
  {
    "code": "def find_group_consistencies(groups1, groups2):\n    r\n    group1_list = {tuple(sorted(_group)) for _group in groups1}\n    group2_list = {tuple(sorted(_group)) for _group in groups2}\n    common_groups = list(group1_list.intersection(group2_list))\n    return common_groups",
    "docstring": "r\"\"\"\n    Returns a measure of group consistency\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_alg import *  # NOQA\n        >>> groups1 = [[1, 2, 3], [4], [5, 6]]\n        >>> groups2 = [[1, 2], [4], [5, 6]]\n        >>> common_groups = find_group_consistencies(groups1, groups2)\n        >>> result = ('common_groups = %r' % (common_groups,))\n        >>> print(result)\n        common_groups = [(5, 6), (4,)]"
  },
  {
    "code": "def multiply(self, number):\n        return self.from_list([x * number for x in self.to_list()])",
    "docstring": "Return a Vector as the product of the vector and a real number."
  },
  {
    "code": "def calc_log_size(request, calc_id):\n    try:\n        response_data = logs.dbcmd('get_log_size', calc_id)\n    except dbapi.NotFound:\n        return HttpResponseNotFound()\n    return HttpResponse(content=json.dumps(response_data), content_type=JSON)",
    "docstring": "Get the current number of lines in the log"
  },
  {
    "code": "def check_output(self, cmd, timeout=None, keep_rc=False, env=None):\n        return subproc.call(cmd, timeout=timeout or self.timeout,\n                keep_rc=keep_rc, env=env)",
    "docstring": "Subclasses can override to provide special\n            environment setup, command prefixes, etc."
  },
  {
    "code": "def output_file(self, _container):\n        p = local.path(_container)\n        if p.exists():\n            if not ui.ask(\"Path '{0}' already exists.\"\n                          \" Overwrite?\".format(p)):\n                sys.exit(0)\n        CFG[\"container\"][\"output\"] = str(p)",
    "docstring": "Find and writes the output path of a chroot container."
  },
  {
    "code": "def clear_and_configure(config=None, bind_in_runtime=True):\n    with _INJECTOR_LOCK:\n        clear()\n        return configure(config, bind_in_runtime=bind_in_runtime)",
    "docstring": "Clear an existing injector and create another one with a callable config."
  },
  {
    "code": "def validate_value(self, value):\n        field = self.instance.preference.setup_field()\n        value = field.to_python(value)\n        field.validate(value)\n        field.run_validators(value)\n        return value",
    "docstring": "We call validation from the underlying form field"
  },
  {
    "code": "def mod_issquare(a, p):\n    if not a:\n        return True\n    p1 = p // 2\n    p2 = pow(a, p1, p)\n    return p2 == 1",
    "docstring": "Returns whether `a' is a square modulo p"
  },
  {
    "code": "def apply(self, doc):\n        if not isinstance(doc, Document):\n            raise TypeError(\n                \"Input Contexts to MentionSentences.apply() must be of type Document\"\n            )\n        for sentence in doc.sentences:\n            yield TemporarySpanMention(\n                char_start=0, char_end=len(sentence.text) - 1, sentence=sentence\n            )",
    "docstring": "Generate MentionSentences from a Document by parsing all of its Sentences.\n\n        :param doc: The ``Document`` to parse.\n        :type doc: ``Document``\n        :raises TypeError: If the input doc is not of type ``Document``."
  },
  {
    "code": "def msg_intro(self):\n        delim = self.style.attr_minor(self.style.delimiter)\n        txt = self.intro_msg_fmt.format(delim=delim).rstrip()\n        return self.term.center(txt)",
    "docstring": "Introductory message disabled above heading."
  },
  {
    "code": "def copy_script(self, filename, id_=-1):\n        for repo in self._children:\n            repo.copy_script(filename, id_)",
    "docstring": "Copy a script to all repositories.\n\n        Takes into account whether a JSS has been migrated. See the\n        individual DistributionPoint types for more information.\n\n        Args:\n            filename: String path to the local file to copy.\n            id_: Integer ID you wish to associate script with for a JDS\n                or CDP only. Default is -1, which is used for creating\n                a new script object in the database."
  },
  {
    "code": "def simple_moving_matrix(x, n=10):\n    if x.ndim > 1 and len(x[0]) > 1:\n        x = np.average(x, axis=1)\n    h = n / 2\n    o = 0 if h * 2 == n else 1\n    xx = []\n    for i in range(h, len(x) - h):\n        xx.append(x[i-h:i+h+o])\n    return np.array(xx)",
    "docstring": "Create simple moving matrix.\n\n    Parameters\n    ----------\n    x : ndarray\n        A numpy array\n    n : integer\n        The number of sample points used to make average\n\n    Returns\n    -------\n    ndarray\n        A n x n numpy array which will be useful for calculating confidentail\n        interval of simple moving average"
  },
  {
    "code": "def state_range_type(self) -> Sequence[str]:\n        fluents = self.domain.state_fluents\n        ordering = self.domain.state_fluent_ordering\n        return self._fluent_range_type(fluents, ordering)",
    "docstring": "The range type of each state fluent in canonical order.\n\n        Returns:\n            Sequence[str]: A tuple of range types representing\n            the range of each fluent."
  },
  {
    "code": "def initialize_model(self, root_node):\n        LOGGER.debug(\"> Initializing model with '{0}' root node.\".format(root_node))\n        self.beginResetModel()\n        self.root_node = root_node\n        self.enable_model_triggers(True)\n        self.endResetModel()\n        return True",
    "docstring": "Initializes the Model using given root node.\n\n        :param root_node: Graph root node.\n        :type root_node: DefaultNode\n        :return: Method success\n        :rtype: bool"
  },
  {
    "code": "def mysql_batch_and_fetch(mysql_config, *sql_queries):\n    import MySQLdb as mydb\n    import sys\n    import gc\n    if len(sql_queries) == 1:\n        if isinstance(sql_queries[0], str):\n            sql_queries = sql_queries[0].split(\";\")\n        if isinstance(sql_queries[0], (list, tuple)):\n            sql_queries = sql_queries[0]\n    try:\n        conn = mydb.connect(**mysql_config)\n        curs = conn.cursor()\n        for sql_query in sql_queries:\n            if len(sql_query) > 0:\n                curs.execute(sql_query)\n        result_table = curs.fetchall()\n    except mydb.Error as err:\n        print(err)\n        gc.collect()\n        sys.exit(1)\n    else:\n        if conn:\n            conn.close()\n        gc.collect()\n        return result_table",
    "docstring": "Excute a series of SQL statements before the final Select query\n\n    Parameters\n    ----------\n    mysql_config : dict\n        The user credentials as defined in MySQLdb.connect, e.g.\n        mysql_conig = {'user': 'myname', 'passwd': 'supersecret',\n        'host': '<ip adress or domain>', 'db': '<myschema>'}\n\n    sql_queries : list or tuple\n        A list or tuple of SQL queries wheras the last SQL command\n        have to be final Select query.\n        (If a string is provided the semicolon \";\" is used to split\n         the string into a list of strings)\n\n    Returns\n    -------\n    result_table : tuple\n        The result table as tuple of tuples.\n\n    Sources\n    -------\n    * http://mysqlclient.readthedocs.io/user_guide.html"
  },
  {
    "code": "def _get_group_difference(self, sp_groups):\n        db_groups = set(Group.objects.all().values_list('name', flat=True))\n        missing_from_db = set(sp_groups).difference(db_groups)\n        missing_from_sp = db_groups.difference(sp_groups)\n        return (missing_from_db, missing_from_sp)",
    "docstring": "Helper method for gettings the groups that\n        are present in the local db but not on stormpath\n        and the other way around."
  },
  {
    "code": "def _unquote_or_none(s: Optional[str]) -> Optional[bytes]:\n    if s is None:\n        return s\n    return url_unescape(s, encoding=None, plus=False)",
    "docstring": "None-safe wrapper around url_unescape to handle unmatched optional\n    groups correctly.\n\n    Note that args are passed as bytes so the handler can decide what\n    encoding to use."
  },
  {
    "code": "def filter_by_func(self, func:Callable)->'ItemList':\n        \"Only keep elements for which `func` returns `True`.\"\n        self.items = array([o for o in self.items if func(o)])\n        return self",
    "docstring": "Only keep elements for which `func` returns `True`."
  },
  {
    "code": "def buffered_generator(source_gen, buffer_size=2, use_multiprocessing=False):\n    r\n    if buffer_size < 2:\n        raise RuntimeError(\"Minimal buffer_ size is 2!\")\n    if use_multiprocessing:\n        print('WARNING seems to freeze if passed in a generator')\n        if False:\n            pool = multiprocessing.Pool(processes=get_default_numprocs(),\n                                        initializer=init_worker,\n                                        maxtasksperchild=None)\n            Process = pool.Process\n        else:\n            Process = multiprocessing.Process\n        _Queue = multiprocessing.Queue\n        target = _buffered_generation_process\n    else:\n        _Queue = queue.Queue\n        Process = KillableThread\n        target = _buffered_generation_thread\n    buffer_ = _Queue(maxsize=buffer_size - 1)\n    sentinal = StopIteration\n    process = Process(\n        target=target,\n        args=(iter(source_gen), buffer_, sentinal)\n    )\n    process.daemon = True\n    process.start()\n    while True:\n        output = buffer_.get()\n        if output is sentinal:\n            raise StopIteration\n        yield output",
    "docstring": "r\"\"\"\n    Generator that runs a slow source generator in a separate process.\n\n    My generate function still seems faster on test cases.\n    However, this function is more flexible in its compatability.\n\n    Args:\n        source_gen (iterable): slow generator\n        buffer_size (int): the maximal number of items to pre-generate\n            (length of the buffer) (default = 2)\n        use_multiprocessing (bool): if False uses GIL-hindered threading\n            instead of multiprocessing (defualt = False).\n\n    Note:\n        use_multiprocessing = True seems to freeze if passed in a generator\n        built by six.moves.map.\n\n    References:\n        Taken from Sander Dieleman's data augmentation pipeline\n        https://github.com/benanne/kaggle-ndsb/blob/11a66cdbddee16c69514b9530a727df0ac6e136f/buffering.py\n\n    CommandLine:\n        python -m utool.util_parallel --test-buffered_generator:0\n        python -m utool.util_parallel --test-buffered_generator:1\n\n    Ignore:\n        >>> #functime = timeit.timeit(\n        >>> # 'ut.is_prime(' + str(prime) + ')', setup='import utool as ut',\n        >>> # number=500) / 1000.0\n\n    Example:\n        >>> # DISABLE_DOCTEST\n        >>> # UNSTABLE_DOCTEST\n        >>> from utool.util_parallel import *  # NOQA\n        >>> import utool as ut\n        >>> num = 2 ** 14\n        >>> func = ut.is_prime\n        >>> data = [38873] * num\n        >>> data = list(range(num))\n        >>> with ut.Timer('serial') as t1:\n        ...     result1 = list(map(func, data))\n        >>> with ut.Timer('ut.generate2') as t3:\n        ...     result3 = list(ut.generate2(func, zip(data), chunksize=2, quiet=1, verbose=0))\n        >>> with ut.Timer('ut.buffered_generator') as t2:\n        ...     result2 = list(ut.buffered_generator(map(func, data)))\n        >>> assert len(result1) == num and len(result2) == num and len(result3) == num\n        >>> assert result3 == result2, 'inconsistent results'\n        >>> assert result1 == result2, 'inconsistent results'\n\n    Example1:\n        >>> # DISABLE_DOCTEST\n        >>> # VERYSLLOOWWW_DOCTEST\n        >>> from utool.util_parallel import _test_buffered_generator\n        >>> _test_buffered_generator2()"
  },
  {
    "code": "def _find_vm(name, data, quiet=False):\n    for hv_ in data:\n        if not isinstance(data[hv_], dict):\n            continue\n        if name in data[hv_].get('vm_info', {}):\n            ret = {hv_: {name: data[hv_]['vm_info'][name]}}\n            if not quiet:\n                __jid_event__.fire_event({'data': ret, 'outputter': 'nested'}, 'progress')\n            return ret\n    return {}",
    "docstring": "Scan the query data for the named VM"
  },
  {
    "code": "def get_title(self):\n        def _title(context_model):\n            context = context_model.context()\n            if context is None:\n                return \"new context*\"\n            title = os.path.basename(context.load_path) if context.load_path \\\n                else \"new context\"\n            if context_model.is_modified():\n                title += '*'\n            return title\n        if self.diff_mode:\n            diff_title = _title(self.diff_context_model)\n            if self.diff_from_source:\n                diff_title += \"'\"\n            return \"%s  %s  %s\" % (_title(self.context_model),\n                                   self.short_double_arrow, diff_title)\n        else:\n            return _title(self.context_model)",
    "docstring": "Returns a string suitable for titling a window containing this table."
  },
  {
    "code": "def find_path(self, basename, install_dir=None):\n        for dir in self.find_path_dirs:\n            path = os.path.join(dir, basename)\n            if os.path.exists(path):\n                return path\n        return os.path.join(install_dir or self.preferred_install_dir, basename)",
    "docstring": "Look in a few places for a file with the given name.  If a custom\n        version of the file is found in the directory being managed by\n        this workspace, return it.  Otherwise look in the custom and default \n        input directories in the root directory, and then finally in the root \n        directory itself.\n\n        This function makes it easy to provide custom parameters to any stage\n        to the design pipeline.  Just place the file with the custom parameters\n        in a directory associated with that stage."
  },
  {
    "code": "def Subclasses(cls, sort_by=None, reverse=False):\n        l = list()\n        for attr, value in get_all_attributes(cls):\n            try:\n                if issubclass(value, Constant):\n                    l.append((attr, value))\n            except:\n                pass\n        if sort_by is None:\n            sort_by = \"__creation_index__\"\n        l = list(\n            sorted(l, key=lambda x: getattr(x[1], sort_by), reverse=reverse))\n        return l",
    "docstring": "Get all nested Constant class and it's name pair.\n\n        :param sort_by: the attribute name used for sorting.\n        :param reverse: if True, return in descend order.\n        :returns: [(attr, value),...] pairs.\n\n        ::\n\n        >>> class MyClass(Constant):\n        ...     a = 1 # non-class attributre\n        ...     b = 2 # non-class attributre\n        ...\n        ...     class C(Constant):\n        ...         pass\n        ...\n        ...     class D(Constant):\n        ...         pass\n\n        >>> MyClass.Subclasses()\n        [(\"C\", MyClass.C), (\"D\", MyClass.D)]\n\n        .. versionadded:: 0.0.3"
  },
  {
    "code": "def _check_input_names(symbol, names, typename, throw):\n    args = symbol.list_arguments()\n    for name in names:\n        if name in args:\n            continue\n        candidates = [arg for arg in args if\n                      not arg.endswith('_weight') and\n                      not arg.endswith('_bias') and\n                      not arg.endswith('_gamma') and\n                      not arg.endswith('_beta')]\n        msg = \"\\033[91mYou created Module with Module(..., %s_names=%s) but \" \\\n              \"input with name '%s' is not found in symbol.list_arguments(). \" \\\n              \"Did you mean one of:\\n\\t%s\\033[0m\"%(\n                  typename, str(names), name, '\\n\\t'.join(candidates))\n        if throw:\n            raise ValueError(msg)\n        else:\n            warnings.warn(msg)",
    "docstring": "Check that all input names are in symbol's arguments."
  },
  {
    "code": "def getRankMaps(self):\n        rankMaps = []\n        for preference in self.preferences:\n            rankMaps.append(preference.getRankMap())\n        return rankMaps",
    "docstring": "Returns a list of dictionaries, one for each preference, that associates the integer \n        representation of each candidate with its position in the ranking, starting from 1 and\n        returns a list of the number of times each preference is given."
  },
  {
    "code": "def is_expired(self):\n        if time.time() - self.last_ping > HB_PING_TIME:\n            self.ping()\n        return (time.time() - self.last_pong) > HB_PING_TIME + HB_PONG_TIME",
    "docstring": "Indicates if connection has expired."
  },
  {
    "code": "def cast_pars_dict(pars_dict):\n    o = {}\n    for pname, pdict in pars_dict.items():\n        o[pname] = {}\n        for k, v in pdict.items():\n            if k == 'free':\n                o[pname][k] = bool(int(v))\n            elif k == 'name':\n                o[pname][k] = v\n            else:\n                o[pname][k] = float(v)\n    return o",
    "docstring": "Cast the bool and float elements of a parameters dict to\n    the appropriate python types."
  },
  {
    "code": "def filter_record(self, record):\n        if len(record) >= self.max_length:\n            return record[:self.max_length]\n        else:\n            return record",
    "docstring": "Filter record, truncating any over some maximum length"
  },
  {
    "code": "def mutateSequence(seq, distance):\n    subProb=distance\n    inProb=0.05*distance\n    deProb=0.05*distance\n    contProb=0.9\n    l = []\n    bases = [ 'A', 'C', 'T', 'G' ]\n    i=0\n    while i < len(seq):\n        if random.random() < subProb:\n            l.append(random.choice(bases))\n        else:\n            l.append(seq[i])\n        if random.random() < inProb:\n            l += getRandomSequence(_expLength(0, contProb))[1]\n        if random.random() < deProb:\n            i += int(_expLength(0, contProb))\n        i += 1\n    return \"\".join(l)",
    "docstring": "Mutates the DNA sequence for use in testing."
  },
  {
    "code": "def read_stdout(self):\n        output = \"\"\n        if self._stdout_file:\n            try:\n                with open(self._stdout_file, \"rb\") as file:\n                    output = file.read().decode(\"utf-8\", errors=\"replace\")\n            except OSError as e:\n                log.warning(\"Could not read {}: {}\".format(self._stdout_file, e))\n        return output",
    "docstring": "Reads the standard output of the QEMU process.\n        Only use when the process has been stopped or has crashed."
  },
  {
    "code": "def searchInAleph(base, phrase, considerSimilar, field):\n    downer = Downloader()\n    if field.lower() not in VALID_ALEPH_FIELDS:\n        raise InvalidAlephFieldException(\"Unknown field '\" + field + \"'!\")\n    param_url = Template(SEARCH_URL_TEMPLATE).substitute(\n        PHRASE=quote_plus(phrase),\n        BASE=base,\n        FIELD=field,\n        SIMILAR=\"Y\" if considerSimilar else \"N\"\n    )\n    result = downer.download(ALEPH_URL + param_url)\n    dom = dhtmlparser.parseString(result)\n    find = dom.find(\"find\")\n    if len(find) <= 0:\n        raise AlephException(\"Aleph didn't returned any information.\")\n    find = find[0]\n    result = _alephResultToDict(find)\n    result[\"base\"] = base\n    if \"error\" not in result:\n        return result\n    if result[\"error\"] == \"empty set\":\n        result[\"no_entries\"] = 0\n        return result\n    else:\n        raise AlephException(result[\"error\"])",
    "docstring": "Send request to the aleph search engine.\n\n    Request itself is pretty useless, but it can be later used as parameter\n    for :func:`getDocumentIDs`, which can fetch records from Aleph.\n\n    Args:\n        base (str): which database you want to use\n        phrase (str): what do you want to search\n        considerSimilar (bool): fuzzy search, which is not working at all, so\n                               don't use it\n        field (str): where you want to look (see: :attr:`VALID_ALEPH_FIELDS`)\n\n    Returns:\n        dictionary: consisting from following fields:\n\n            | error (optional): present if there was some form of error\n            | no_entries (int): number of entries that can be fetch from aleph\n            | no_records (int): no idea what is this, but it is always >= than\n                                `no_entries`\n            | set_number (int): important - something like ID of your request\n            | session-id (str): used to count users for licensing purposes\n\n    Example:\n      Returned dict::\n\n        {\n         'session-id': 'YLI54HBQJESUTS678YYUNKEU4BNAUJDKA914GMF39J6K89VSCB',\n         'set_number': 36520,\n         'no_records': 1,\n         'no_entries': 1\n        }\n\n    Raises:\n        AlephException: if Aleph doesn't return any information\n        InvalidAlephFieldException: if specified field is not valid"
  },
  {
    "code": "def respond_client(self, answer, socket):\n        response = pickle.dumps(answer, -1)\n        socket.sendall(response)\n        self.read_list.remove(socket)\n        socket.close()",
    "docstring": "Send an answer to the client."
  },
  {
    "code": "def _read_message(self):\n        payload_info = self._read_bytes_from_socket(4)\n        read_len = unpack(\">I\", payload_info)[0]\n        payload = self._read_bytes_from_socket(read_len)\n        message = cast_channel_pb2.CastMessage()\n        message.ParseFromString(payload)\n        return message",
    "docstring": "Reads a message from the socket and converts it to a message."
  },
  {
    "code": "def split_css_classes(css_classes):\n    classes_list = text_value(css_classes).split(\" \")\n    return [c for c in classes_list if c]",
    "docstring": "Turn string into a list of CSS classes"
  },
  {
    "code": "def set_property_filter(filter_proto, name, op, value):\n  filter_proto.Clear()\n  pf = filter_proto.property_filter\n  pf.property.name = name\n  pf.op = op\n  set_value(pf.value, value)\n  return filter_proto",
    "docstring": "Set property filter contraint in the given datastore.Filter proto message.\n\n  Args:\n    filter_proto: datastore.Filter proto message\n    name: property name\n    op: datastore.PropertyFilter.Operation\n    value: property value\n\n  Returns:\n    the same datastore.Filter.\n\n  Usage:\n    >>> set_property_filter(filter_proto, 'foo',\n    ...   datastore.PropertyFilter.EQUAL, 'a')  # WHERE 'foo' = 'a'"
  },
  {
    "code": "def _get_object_pydoc_page_name(obj):\n    page_name = fullqualname.fullqualname(obj)\n    if page_name is not None:\n       page_name = _remove_builtin_prefix(page_name)\n    return page_name",
    "docstring": "Returns fully qualified name, including module name, except for the\n    built-in module."
  },
  {
    "code": "def filter_by_transcript_expression(\n            self,\n            transcript_expression_dict,\n            min_expression_value=0.0):\n        return self.filter_any_above_threshold(\n            multi_key_fn=lambda variant: variant.transcript_ids,\n            value_dict=transcript_expression_dict,\n            threshold=min_expression_value)",
    "docstring": "Filters variants down to those which have overlap a transcript whose\n        expression value in the transcript_expression_dict argument is greater\n        than min_expression_value.\n\n        Parameters\n        ----------\n        transcript_expression_dict : dict\n            Dictionary mapping Ensembl transcript IDs to expression estimates\n            (either FPKM or TPM)\n\n        min_expression_value : float\n            Threshold above which we'll keep an effect in the result collection"
  },
  {
    "code": "def options(self, **options):\n        for k in options:\n            self._jwrite = self._jwrite.option(k, to_str(options[k]))\n        return self",
    "docstring": "Adds output options for the underlying data source.\n\n        You can set the following option(s) for writing files:\n            * ``timeZone``: sets the string that indicates a timezone to be used to format\n                timestamps in the JSON/CSV datasources or partition values.\n                If it isn't set, it uses the default value, session local timezone."
  },
  {
    "code": "def install_egg(self, egg_name):\n        if not os.path.exists(self.egg_directory):\n            os.makedirs(self.egg_directory)\n        self.requirement_set.add_requirement(\n            InstallRequirement.from_line(egg_name, None))\n        try:\n            self.requirement_set.prepare_files(self.finder)\n            self.requirement_set.install(['--prefix=' + self.egg_directory], [])\n        except DistributionNotFound:\n            self.requirement_set.requirements._keys.remove(egg_name)\n            raise PipException()",
    "docstring": "Install an egg into the egg directory"
  },
  {
    "code": "def set_children(self, child_ids):\n        if not isinstance(child_ids, list):\n            raise errors.InvalidArgument()\n        if self.get_children_metadata().is_read_only():\n            raise errors.NoAccess()\n        idstr_list = []\n        for object_id in child_ids:\n            if not self._is_valid_id(object_id):\n                raise errors.InvalidArgument()\n            if str(object_id) not in idstr_list:\n                idstr_list.append(str(object_id))\n        self._my_map['childIds'] = idstr_list",
    "docstring": "Sets the children.\n\n        arg:    child_ids (osid.id.Id[]): the children``Ids``\n        raise:  InvalidArgument - ``child_ids`` is invalid\n        raise:  NoAccess - ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def list_compatible_canvas_layers(self):\n        italic_font = QFont()\n        italic_font.setItalic(True)\n        list_widget = self.lstCanvasHazLayers\n        list_widget.clear()\n        for layer in self.parent.get_compatible_canvas_layers('hazard'):\n            item = QListWidgetItem(layer['name'], list_widget)\n            item.setData(Qt.UserRole, layer['id'])\n            if not layer['keywords']:\n                item.setFont(italic_font)\n            list_widget.addItem(item)",
    "docstring": "Fill the list widget with compatible layers.\n\n        :returns: Metadata of found layers.\n        :rtype: list of dicts"
  },
  {
    "code": "def release_lock(dax, key, lock_mode=LockMode.wait):\n  lock_fxn = _lock_fxn(\"unlock\", lock_mode, False)\n  return dax.get_scalar(\n    dax.callproc(lock_fxn, key if isinstance(key, (list, tuple)) else [key])[0])",
    "docstring": "Manually release a pg advisory lock.\n\n  :dax: a DataAccess instance\n  :key: either a big int or a 2-tuple of integers\n  :lock_mode: a member of the LockMode enum"
  },
  {
    "code": "def auth_token(cls, token):\n        store = goldman.sess.store\n        login = store.find(cls.RTYPE, 'token', token)\n        if not login:\n            msg = 'No login found with that token. It may have been revoked.'\n            raise AuthRejected(**{'detail': msg})\n        elif login.locked:\n            msg = 'The login account is currently locked out.'\n            raise AuthRejected(**{'detail': msg})\n        else:\n            login.post_authenticate()",
    "docstring": "Callback method for OAuth 2.0 bearer token middleware"
  },
  {
    "code": "def set_exception(self, exception):\n        assert isinstance(exception, Exception), \\\n            \"%r should be an Exception\" % exception\n        self._exception = exception\n        self._state = self.FINISHED",
    "docstring": "Sets the result of the future as being the given exception.\n\n        Should only be used by Task and unit tests."
  },
  {
    "code": "def kth_to_last_dict(head, k):\n    if not (head and k > -1):\n        return False\n    d = dict()\n    count = 0\n    while head:\n        d[count] = head\n        head = head.next\n        count += 1\n    return len(d)-k in d and d[len(d)-k]",
    "docstring": "This is a brute force method where we keep a dict the size of the list\n    Then we check it for the value we need. If the key is not in the dict,\n    our and statement will short circuit and return False"
  },
  {
    "code": "def _load_data():\n    lines = dragonmapper.data.load_data_file('transcriptions.csv')\n    pinyin_map, zhuyin_map, ipa_map = {}, {}, {}\n    for line in lines:\n        p, z, i = line.split(',')\n        pinyin_map[p] = {'Zhuyin': z, 'IPA': i}\n        zhuyin_map[z] = {'Pinyin': p, 'IPA': i}\n        ipa_map[i] = {'Pinyin': p, 'Zhuyin': z}\n    return pinyin_map, zhuyin_map, ipa_map",
    "docstring": "Load the transcription mapping data into a dictionary."
  },
  {
    "code": "def _recursively_lookup_complex(self, complex_id):\n        assert complex_id in self.complex_map\n        expanded_agent_strings = []\n        expand_these_next = [complex_id]\n        while len(expand_these_next) > 0:\n            c = expand_these_next[0]\n            expand_these_next = expand_these_next[1:]\n            assert c in self.complex_map\n            for s in self.complex_map[c]:\n                if s in self.complex_map:\n                    expand_these_next.append(s)\n                else:\n                    expanded_agent_strings.append(s)\n        return expanded_agent_strings",
    "docstring": "Looks up the constitutents of a complex. If any constituent is\n        itself a complex, recursively expands until all constituents are\n        not complexes."
  },
  {
    "code": "def _escapify(label):\n    text = ''\n    for c in label:\n        if c in _escaped:\n            text += '\\\\' + c\n        elif ord(c) > 0x20 and ord(c) < 0x7F:\n            text += c\n        else:\n            text += '\\\\%03d' % ord(c)\n    return text",
    "docstring": "Escape the characters in label which need it.\n    @returns: the escaped string\n    @rtype: string"
  },
  {
    "code": "def snap(self, *args):\n        length = len(args)\n        if not 2 <= length <= 6:\n            msg = 'snap takes 2 to 6 arguments, {0} given.'.format(length)\n            raise TypeError(msg)\n        param = Enum(\n            'x', 'y', 'r', 'theta', 'aux1', 'aux2', 'aux3', 'aux4',\n            'frequency', 'trace1', 'trace2', 'trace3', 'trace4'\n        )\n        cmd = 'SNAP?', (Float,) * length, (param, ) * length\n        return self._ask(cmd, *args)",
    "docstring": "Records multiple values at once.\n\n        It takes two to six arguments specifying which values should be\n        recorded together. Valid arguments are 'x', 'y', 'r', 'theta',\n        'aux1', 'aux2', 'aux3', 'aux4', 'frequency', 'trace1', 'trace2',\n        'trace3' and 'trace4'.\n\n        snap is faster since it avoids communication overhead. 'x' and 'y'\n        are recorded together, as well as 'r' and 'theta'. Between these\n        pairs, there is a delay of approximately 10 us. 'aux1', 'aux2', 'aux3'\n        and 'aux4' have am uncertainty of up to 32 us. It takes at least 40 ms\n        or a period to calculate the frequency.\n\n        E.g.::\n\n            lockin.snap('x', 'theta', 'trace3')"
  },
  {
    "code": "def _input_as_multiline_string(self, data):\n        self._input_filename = self.getTmpFilename(\n            self.WorkingDir, suffix='.fasta')\n        with open(self._input_filename, 'w') as f:\n            f.write(data)\n        return self._input_filename",
    "docstring": "Write multiline string to temp file, return filename\n\n        data: a multiline string to be written to a file."
  },
  {
    "code": "def _unquote(self, val):\n        if (len(val) >= 2) and (val[0] in (\"'\", '\"')) and (val[0] == val[-1]):\n            val = val[1:-1]\n        return val",
    "docstring": "Unquote a value if necessary."
  },
  {
    "code": "def get_pushes(self, project, **params):\n        return self._get_json_list(self.PUSH_ENDPOINT, project, **params)",
    "docstring": "Gets pushes from project, filtered by parameters\n\n        By default this method will just return the latest 10 pushes (if they exist)\n\n        :param project: project (repository name) to query data for\n        :param params: keyword arguments to filter results"
  },
  {
    "code": "async def delete(self, iden):\n        appt = self.appts.get(iden)\n        if appt is None:\n            raise s_exc.NoSuchIden()\n        try:\n            heappos = self.apptheap.index(appt)\n        except ValueError:\n            pass\n        else:\n            if heappos == len(self.apptheap) - 1:\n                del self.apptheap[heappos]\n            else:\n                self.apptheap[heappos] = self.apptheap.pop()\n                heapq.heapify(self.apptheap)\n        del self.appts[iden]\n        await self._hivedict.pop(iden)",
    "docstring": "Delete an appointment"
  },
  {
    "code": "def list(gandi, domain, limit):\n    options = {'items_per_page': limit}\n    result = gandi.forward.list(domain, options)\n    for forward in result:\n        output_forward(gandi, domain, forward)\n    return result",
    "docstring": "List mail forwards for a domain."
  },
  {
    "code": "def _get_pooling_layers(self, start_node_id, end_node_id):\n        layer_list = []\n        node_list = [start_node_id]\n        assert self._depth_first_search(end_node_id, layer_list, node_list)\n        ret = []\n        for layer_id in layer_list:\n            layer = self.layer_list[layer_id]\n            if is_layer(layer, \"Pooling\"):\n                ret.append(layer)\n            elif is_layer(layer, \"Conv\") and layer.stride != 1:\n                ret.append(layer)\n        return ret",
    "docstring": "Given two node IDs, return all the pooling layers between them."
  },
  {
    "code": "def votes(self):\n        votes = []\n        for option in self.options.all():\n            votes += option.votes.all()\n        return votes",
    "docstring": "Returns all the votes related to this topic poll."
  },
  {
    "code": "def has_annotation(self, annotation: str) -> bool:\n        return (\n            self.has_enumerated_annotation(annotation) or\n            self.has_regex_annotation(annotation) or\n            self.has_local_annotation(annotation)\n        )",
    "docstring": "Check if this annotation is defined."
  },
  {
    "code": "def triad(note, key):\n    return [note, intervals.third(note, key), intervals.fifth(note, key)]",
    "docstring": "Return the triad on note in key as a list.\n\n    Examples:\n    >>> triad('E', 'C')\n    ['E', 'G', 'B']\n    >>> triad('E', 'B')\n    ['E', 'G#', 'B']"
  },
  {
    "code": "def date_from_string(string, format_string=None):\n    if isinstance(format_string, str):\n        return datetime.datetime.strptime(string, format_string).date()\n    elif format_string is None:\n        format_string = [\n            \"%Y-%m-%d\",\n            \"%m-%d-%Y\",\n            \"%m/%d/%Y\",\n            \"%d/%m/%Y\",\n        ]\n    for format in format_string:\n        try:\n            return datetime.datetime.strptime(string, format).date()\n        except ValueError:\n            continue\n    raise ValueError(\"Could not produce date from string: {}\".format(string))",
    "docstring": "Runs through a few common string formats for datetimes,\n    and attempts to coerce them into a datetime. Alternatively,\n    format_string can provide either a single string to attempt\n    or an iterable of strings to attempt."
  },
  {
    "code": "def __init_defaults(self, config):\n        provider = self.__provider\n        if provider == 'sqlite':\n            config.setdefault('dbname', ':memory:')\n            config.setdefault('create_db',  True)\n        elif provider == 'mysql':\n            config.setdefault('port', 3306)\n            config.setdefault('charset', 'utf8')\n        elif provider == 'postgres':\n            config.setdefault('port', 5432)\n        elif provider == 'oracle':\n            config.setdefault('port', 1521)\n        else:\n            raise ValueError('Unsupported provider \"{}\"'.format(provider))\n        if provider != 'sqlite':\n            config.setdefault('host', 'localhost')\n            config.setdefault('user', None)\n            config.setdefault('password', None)\n            config.setdefault('dbname', None)",
    "docstring": "Initializes the default connection settings."
  },
  {
    "code": "def _add_opt_argument(self, opt_args, arg_parser):\n        option_args = opt_args.copy()\n        groups = option_args.pop('groups', None)\n        if groups:\n            self._add_group(\n                parser=arg_parser,\n                groups=groups,\n                option_args=option_args\n            )\n        exclusive_args = option_args.pop('mutually_exclusive', None)\n        if exclusive_args:\n            self._add_mutually_exclusive_group(\n                parser=arg_parser,\n                groups=exclusive_args,\n                option_args=option_args\n            )\n        for k, v in option_args.items():\n            self._add_arg(parser=arg_parser, value_dict=v)",
    "docstring": "Add an argument to an instantiated parser.\n\n        :param opt_args: ``dict``\n        :param arg_parser: ``object``"
  },
  {
    "code": "def prettylist(list_):\n    if not list_:\n        return ''\n    values = set()\n    uniqueList = []\n    for entry in list_:\n        if not entry in values:\n            values.add(entry)\n            uniqueList.append(entry)\n    return uniqueList[0] if len(uniqueList) == 1 \\\n        else '[' + '; '.join(uniqueList) + ']'",
    "docstring": "Filter out duplicate values while keeping order."
  },
  {
    "code": "def ecef2enuv(u: float, v: float, w: float,\n              lat0: float, lon0: float, deg: bool = True) -> Tuple[float, float, float]:\n    if deg:\n        lat0 = radians(lat0)\n        lon0 = radians(lon0)\n    t = cos(lon0) * u + sin(lon0) * v\n    uEast = -sin(lon0) * u + cos(lon0) * v\n    wUp = cos(lat0) * t + sin(lat0) * w\n    vNorth = -sin(lat0) * t + cos(lat0) * w\n    return uEast, vNorth, wUp",
    "docstring": "VECTOR from observer to target  ECEF => ENU\n\n    Parameters\n    ----------\n    u : float or numpy.ndarray of float\n        target x ECEF coordinate (meters)\n    v : float or numpy.ndarray of float\n        target y ECEF coordinate (meters)\n    w : float or numpy.ndarray of float\n        target z ECEF coordinate (meters)\n    lat0 : float\n           Observer geodetic latitude\n    lon0 : float\n           Observer geodetic longitude\n    h0 : float\n         observer altitude above geodetic ellipsoid (meters)\n    deg : bool, optional\n          degrees input/output  (False: radians in/out)\n\n    Returns\n    -------\n    uEast : float or numpy.ndarray of float\n        target east ENU coordinate (meters)\n    vNorth : float or numpy.ndarray of float\n        target north ENU coordinate (meters)\n    wUp : float or numpy.ndarray of float\n        target up ENU coordinate (meters)"
  },
  {
    "code": "def get_unique_figname(dirname, root, ext):\n    i = 1\n    figname = root + '_%d' % i + ext\n    while True:\n        if osp.exists(osp.join(dirname, figname)):\n            i += 1\n            figname = root + '_%d' % i + ext\n        else:\n            return osp.join(dirname, figname)",
    "docstring": "Append a number to \"root\" to form a filename that does not already exist\n    in \"dirname\"."
  },
  {
    "code": "def log_power_spectrum(frames, fft_points=512, normalize=True):\n    power_spec = power_spectrum(frames, fft_points)\n    power_spec[power_spec <= 1e-20] = 1e-20\n    log_power_spec = 10 * np.log10(power_spec)\n    if normalize:\n        return log_power_spec - np.max(log_power_spec)\n    else:\n        return log_power_spec",
    "docstring": "Log power spectrum of each frame in frames.\n\n    Args:\n        frames (array): The frame array in which each row is a frame.\n        fft_points (int): The length of FFT. If fft_length is greater than\n            frame_len, the frames will be zero-padded.\n        normalize (bool): If normalize=True, the log power spectrum\n            will be normalized.\n\n    Returns:\n           array: The power spectrum - If frames is an\n           num_frames x sample_per_frame matrix, output will be\n           num_frames x fft_length."
  },
  {
    "code": "def _receive_all(self):\n        (data, part) = ('', '')\n        if is_py3:\n            crlf_bytes = bytes(self.__CRLF, encoding=self.__encoding)\n        else:\n            crlf_bytes = self.__CRLF\n        while self._running and part[-2:] != crlf_bytes:\n            try:\n                part = self._socket.recv(self.buffer_size)\n            except (socket.timeout, socket.error) as e:\n                if self._running:\n                    self.stop()\n                    raise SocketError('[Connect: %s]: Socket %s' % (self._unique_id, e))\n                else:\n                    return\n            if len(part) == 0:\n                self.stop()\n                raise SocketError('Connection closed by server')\n            data += part.decode(self.__encoding)\n        return data",
    "docstring": "Whilst socket is running receives data from socket,\n        till CRLF is detected."
  },
  {
    "code": "def gen_tensor_data():\n    X, y = toy_interaction(return_X_y=True, n=10000)\n    gam = LinearGAM(te(0, 1,lam=0.1)).fit(X, y)\n    XX = gam.generate_X_grid(term=0, meshgrid=True)\n    Z = gam.partial_dependence(term=0, meshgrid=True)\n    fig = plt.figure(figsize=(9,6))\n    ax = plt.axes(projection='3d')\n    ax.dist = 7.5\n    ax.plot_surface(XX[0], XX[1], Z, cmap='viridis')\n    ax.set_axis_off()\n    fig.tight_layout()\n    plt.savefig('imgs/pygam_tensor.png', transparent=True, dpi=300)",
    "docstring": "toy interaction data"
  },
  {
    "code": "def encode(self, tags, encoding, values_to_sub):\n        for tag in tags:\n            if tags[tag].get(encoding) != \"None\":\n                if tags[tag].get(encoding) == \"url\":\n                    values_to_sub[tag] = self.url_encode(values_to_sub[tag])\n                if tags[tag].get(encoding) == \"base64\":\n                    values_to_sub[tag] = self.base64_utf_encode(values_to_sub[tag])\n        return values_to_sub",
    "docstring": "reads the encoding type from the event-mapping.json\n        and determines whether a value needs encoding\n\n        Parameters\n        ----------\n        tags: dict\n            the values of a particular event that can be substituted\n            within the event json\n        encoding: string\n            string that helps navigate to the encoding field of the json\n        values_to_sub: dict\n            key/value pairs that will be substituted into the json\n        Returns\n        -------\n        values_to_sub: dict\n            the encoded (if need be) values to substitute into the json."
  },
  {
    "code": "def load(self, local='localsettings.py', default='settings.py'):\n        self._load_defaults(default)\n        self._load_custom(local)\n        return self.settings()",
    "docstring": "Load the settings dict\n\n        @param local: The local settings filename to use\n        @param default: The default settings module to read\n        @return: A dict of the loaded settings"
  },
  {
    "code": "def _print_breakdown(cls, savedir, fname, data):\n        if not os.path.exists(savedir):\n            os.makedirs(savedir)\n        with open(os.path.join(savedir, fname), 'w') as fout:\n            fout.write(data)",
    "docstring": "Function to print model fixtures into generated file"
  },
  {
    "code": "def get_data_source(self):\n        product_type = self.product_id.split('_')[1]\n        if product_type.endswith('L1C') or product_type == 'OPER':\n            return DataSource.SENTINEL2_L1C\n        if product_type.endswith('L2A') or product_type == 'USER':\n            return DataSource.SENTINEL2_L2A\n        raise ValueError('Unknown data source of product {}'.format(self.product_id))",
    "docstring": "The method determines data source from product ID.\n\n        :return: Data source of the product\n        :rtype: DataSource\n        :raises: ValueError"
  },
  {
    "code": "def load_buildfile(self, target):\n        log.info('Loading: %s', target)\n        filepath = os.path.join(target.path, app.get_options().buildfile_name)\n        try:\n            repo = self.repo_state.GetRepo(target.repo)\n            return repo.get_file(filepath)\n        except gitrepo.GitError as err:\n            log.error('Failed loading %s: %s', target, err)\n            raise error.BrokenGraph('Sadface.')",
    "docstring": "Pull a build file from git."
  },
  {
    "code": "def get_node(service_name, host_name):\n    return common_pb2.Node(\n        identifier=common_pb2.ProcessIdentifier(\n            host_name=socket.gethostname() if host_name is None\n            else host_name,\n            pid=os.getpid(),\n            start_timestamp=proto_ts_from_datetime(\n                datetime.datetime.utcnow())),\n        library_info=common_pb2.LibraryInfo(\n            language=common_pb2.LibraryInfo.Language.Value('PYTHON'),\n            exporter_version=EXPORTER_VERSION,\n            core_library_version=opencensus_version),\n        service_info=common_pb2.ServiceInfo(name=service_name))",
    "docstring": "Generates Node message from params and system information."
  },
  {
    "code": "def schema_class(self, object_schema, model_name, classes=False):\n        cls_bldr = ClassBuilder(self.resolver)\n        model_cls = cls_bldr.construct(model_name, object_schema)\n        model_cls.proptype = SchemaObjectFactory.proptype\n        return [model_cls, cls_bldr.resolved][classes]",
    "docstring": "Create a object-class based on the object_schema.  Use\n        this class to create specific instances, and validate the\n        data values.  See the \"python-jsonschema-objects\" package\n        for details on further usage.\n\n        Parameters\n        ----------\n        object_schema : dict\n            The JSON-schema that defines the object\n\n        model_name : str\n            if provided, the name given to the new class.  if not\n            provided, then the name will be determined by\n            one of the following schema values, in this order:\n            ['x-model', 'title', 'id']\n\n        classes : bool\n            When `True`, this method will return the complete\n            dictionary of all resolved object-classes built\n            from the object_schema.  This can be helpful\n            when a deeply nested object_schema is provided; but\n            generally not necessary.  You can then create\n            a :class:`Namespace` instance using this dict.  See\n            the 'python-jschonschema-objects.utls' package\n            for further details.\n\n            When `False` (default), return only the object-class\n\n        Returns\n        -------\n            - new class for given object_schema (default)\n            - dict of all classes when :param:`classes` is True"
  },
  {
    "code": "def prepare_value(self, value):\n        if value is None and self.required:\n            choices =list(self.choices)\n            if len(choices) == 1:\n                value = choices[0][0]\n        return super(TemplateChoiceField, self).prepare_value(value)",
    "docstring": "To avoid evaluating the lazysorted callable more than necessary to\n        establish a potential initial value for the field, we do it here.\n\n        If there's\n        - only one template choice, and\n        - the field is required, and\n        - there's no prior initial set (either by being bound or by being set\n          higher up the stack\n        then forcibly select the only \"good\" value as the default."
  },
  {
    "code": "def genome_alignment_iterator(fn, reference_species, index_friendly=False,\n                              verbose=False):\n  kw_args = {\"reference_species\": reference_species}\n  for e in maf.maf_iterator(fn, index_friendly=index_friendly,\n                            yield_class=GenomeAlignmentBlock,\n                            yield_kw_args=kw_args,\n                            verbose=verbose):\n    yield e",
    "docstring": "build an iterator for an MAF file of genome alignment blocks.\n\n  :param fn:                 filename or stream-like object to iterate over.\n  :param reference_species:  which species in the alignment should be treated\n                             as the reference?\n  :param index_friendly:     if True, buffering is disabled to support using\n                             the iterator to build an index.\n\n  :return an iterator that yields GenomeAlignment objects"
  },
  {
    "code": "def match(self, method, path):\n        segments = path.split('/')\n        while len(segments):\n            index = '/'.join(segments)\n            if index in self.__idx__:\n                handler, params = self.match_rule(method, path,\n                                                  self.__idx__[index])\n                if handler:\n                    return handler, params\n            segments.pop()\n        return None, None",
    "docstring": "find handler from registered rules\n\n        Example:\n\n            handler, params = match('GET', '/path')"
  },
  {
    "code": "def date_to_json(pydate, manager):\n    if pydate is None:\n        return None\n    else:\n        return dict(\n            year=pydate.year,\n            month=pydate.month - 1,\n            date=pydate.day\n        )",
    "docstring": "Serialize a Python date object.\n\n    Attributes of this dictionary are to be passed to the JavaScript Date\n    constructor."
  },
  {
    "code": "def _get_by_id(collection, id):\n    matches = [item for item in collection if item.id == id]\n    if not matches:\n        raise ValueError('Could not find a matching item')\n    elif len(matches) > 1:\n        raise ValueError('The id matched {0} items, not 1'.format(len(matches)))\n    return matches[0]",
    "docstring": "Get item from a list by the id field"
  },
  {
    "code": "def get_service_details(self, service_id):\n        service_query = \\\n            self._soap_client.service['LDBServiceSoap']['GetServiceDetails']\n        try:\n            soap_response = service_query(serviceID=service_id)\n        except WebFault:\n            raise WebServiceError\n        return ServiceDetails(soap_response)",
    "docstring": "Get the details of an individual service and return a ServiceDetails\n        instance.\n\n        Positional arguments:\n        service_id: A Darwin LDB service id"
  },
  {
    "code": "def update( self, jump ):\n        atom = jump.initial_site.atom\n        dr = jump.dr( self.cell_lengths )\n        jump.final_site.occupation = atom.number\n        jump.final_site.atom = atom\n        jump.final_site.is_occupied = True\n        jump.initial_site.occupation = 0\n        jump.initial_site.atom = None\n        jump.initial_site.is_occupied = False\n        atom.site = jump.final_site\n        atom.number_of_hops += 1\n        atom.dr += dr\n        atom.summed_dr2 += np.dot( dr, dr )",
    "docstring": "Update the lattice state by accepting a specific jump\n\n        Args:\n            jump (Jump): The jump that has been accepted.\n\n        Returns:\n            None."
  },
  {
    "code": "def read_sha1(\n    file_path,\n    buf_size = None,\n    start_byte = 0,\n    read_size = None,\n    extra_hashers = [],\n):\n    read_size = read_size or os.stat(file_path).st_size\n    buf_size = buf_size or DEFAULT_BUFFER_SIZE\n    data_read = 0\n    total_sha1 = hashlib.sha1()\n    while data_read < read_size:\n        with open( file_path, 'rb', buffering = 0 ) as f:\n            f.seek( start_byte )\n            data = f.read( min(buf_size, read_size - data_read) )\n            assert( len(data) > 0 )\n            total_sha1.update( data )\n            for hasher in extra_hashers:\n                hasher.update( data )\n            data_read += len(data)\n            start_byte += len(data)\n    assert( data_read == read_size )\n    return total_sha1",
    "docstring": "Determines the sha1 hash of a file in chunks, to prevent loading the entire file at once into memory"
  },
  {
    "code": "def get_user_id(self, user):\n        user_field = getattr(settings, 'SAML_IDP_DJANGO_USERNAME_FIELD', None) or \\\n                     getattr(user, 'USERNAME_FIELD', 'username')\n        return str(getattr(user, user_field))",
    "docstring": "Get identifier for a user. Take the one defined in settings.SAML_IDP_DJANGO_USERNAME_FIELD first, if not set\n            use the USERNAME_FIELD property which is set on the user Model. This defaults to the user.username field."
  },
  {
    "code": "def render_impl(self, template, context, **options):\n        ropts = dict((k, v) for k, v in options.items() if k != \"safe\")\n        tmpl = anytemplate.engines.base.fallback_render(template, {}, **ropts)\n        return self.renders_impl(tmpl, context, **options)",
    "docstring": "Inherited class must implement this!\n\n        :param template: Template file path\n        :param context: A dict or dict-like object to instantiate given\n            template file\n        :param options: Same options as :meth:`renders_impl`\n\n            - at_paths: Template search paths (common option)\n            - at_encoding: Template encoding (common option)\n            - safe: Safely substitute parameters in templates, that is,\n              original template content will be returned if some of template\n              parameters are not found in given context\n\n        :return: To be rendered string in inherited classes"
  },
  {
    "code": "def get_chunks(self,chunk_type):\n        for nonter,this_type in self.label_for_nonter.items():\n            if this_type == chunk_type:\n                subsumed = self.terms_subsumed_by_nonter.get(nonter)\n                if subsumed is not None:\n                    yield sorted(list(subsumed))",
    "docstring": "Returns the chunks for a certain type\n        @type chunk_type: string\n        @param chunk_type: type of the chunk\n        @rtype: list\n        @return: the chunks for that type"
  },
  {
    "code": "def namespace_map(self, target):\n    self._check_target(target)\n    return target.namespace_map or self._default_namespace_map",
    "docstring": "Returns the namespace_map used for Thrift generation.\n\n    :param target: The target to extract the namespace_map from.\n    :type target: :class:`pants.backend.codegen.targets.java_thrift_library.JavaThriftLibrary`\n    :returns: The namespaces to remap (old to new).\n    :rtype: dictionary"
  },
  {
    "code": "def fix_header(filepath):\n    with open(filepath, \"r+\") as f:\n        current = f.read()\n        fixed = \"\\n\".join(line.strip() for line in current.split(\"\\n\"))\n        if current == fixed:\n            return\n        f.seek(0)\n        f.truncate()\n        f.write(fixed)",
    "docstring": "Removes leading whitespace from a MacOS header file.\n\n    This whitespace is causing issues with directives on some platforms."
  },
  {
    "code": "def get_fact_cache(self, host):\n        if self.config.fact_cache_type != 'jsonfile':\n            raise Exception('Unsupported fact cache type.  Only \"jsonfile\" is supported for reading and writing facts from ansible-runner')\n        fact_cache = os.path.join(self.config.fact_cache, host)\n        if os.path.exists(fact_cache):\n            with open(fact_cache) as f:\n                return json.loads(f.read())\n        return {}",
    "docstring": "Get the entire fact cache only if the fact_cache_type is 'jsonfile'"
  },
  {
    "code": "def max_pool(x_input, pool_size):\n    return tf.nn.max_pool(x_input, ksize=[1, pool_size, pool_size, 1],\n                          strides=[1, pool_size, pool_size, 1], padding='SAME')",
    "docstring": "max_pool downsamples a feature map by 2X."
  },
  {
    "code": "def accept_moderator_invite(self, subreddit):\n        data = {'r': six.text_type(subreddit)}\n        self.user._mod_subs = None\n        self.evict(self.config['my_mod_subreddits'])\n        return self.request_json(self.config['accept_mod_invite'], data=data)",
    "docstring": "Accept a moderator invite to the given subreddit.\n\n        Callable upon an instance of Subreddit with no arguments.\n\n        :returns: The json response from the server."
  },
  {
    "code": "def extender(path=None, cache=None):\n    old_path = sys.path[:]\n    extend(path, cache=None)\n    try:\n        yield\n    finally:\n        sys.path = old_path",
    "docstring": "A context that temporarily extends sys.path and reverts it after the\n       context is complete."
  },
  {
    "code": "def pretty_print_config_to_json(self, configs):\n    descriptor = self.get_directory_list_doc(configs)\n    return json.dumps(descriptor, sort_keys=True, indent=2,\n                      separators=(',', ': '))",
    "docstring": "JSON string description of a protorpc.remote.Service in a discovery doc.\n\n    Args:\n      configs: Either a single dict or a list of dicts containing the service\n        configurations to list.\n\n    Returns:\n      string, The directory list document as a JSON string."
  },
  {
    "code": "def urlread(url, encoding='utf8'):\n    try:\n        from urllib.request import urlopen\n    except ImportError:\n        from urllib2 import urlopen\n    response = urlopen(url)\n    content = response.read()\n    content = content.decode(encoding)\n    return content",
    "docstring": "Read the content of an URL.\n\n    Parameters\n    ----------\n    url : str\n\n    Returns\n    -------\n    content : str"
  },
  {
    "code": "def get_cb_plot(cb, plot=None):\n    plot = plot or cb.plot\n    if isinstance(plot, GeoOverlayPlot):\n        plots = [get_cb_plot(cb, p) for p in plot.subplots.values()]\n        plots = [p for p in plots if any(s in cb.streams and getattr(s, '_triggering', False)\n                                         for s in p.streams)]\n        if plots:\n            plot = plots[0]\n    return plot",
    "docstring": "Finds the subplot with the corresponding stream."
  },
  {
    "code": "def cmd(self,\n            tgt,\n            fun,\n            arg=(),\n            timeout=None,\n            tgt_type='glob',\n            ret='',\n            jid='',\n            full_return=False,\n            kwarg=None,\n            **kwargs):\n        was_listening = self.event.cpub\n        try:\n            pub_data = self.run_job(tgt,\n                                    fun,\n                                    arg,\n                                    tgt_type,\n                                    ret,\n                                    timeout,\n                                    jid,\n                                    kwarg=kwarg,\n                                    listen=True,\n                                    **kwargs)\n            if not pub_data:\n                return pub_data\n            ret = {}\n            for fn_ret in self.get_cli_event_returns(\n                    pub_data['jid'],\n                    pub_data['minions'],\n                    self._get_timeout(timeout),\n                    tgt,\n                    tgt_type,\n                    **kwargs):\n                if fn_ret:\n                    for mid, data in six.iteritems(fn_ret):\n                        ret[mid] = (data if full_return\n                                else data.get('ret', {}))\n            for failed in list(set(pub_data['minions']) - set(ret)):\n                ret[failed] = False\n            return ret\n        finally:\n            if not was_listening:\n                self.event.close_pub()",
    "docstring": "Synchronously execute a command on targeted minions\n\n        The cmd method will execute and wait for the timeout period for all\n        minions to reply, then it will return all minion data at once.\n\n        .. code-block:: python\n\n            >>> import salt.client\n            >>> local = salt.client.LocalClient()\n            >>> local.cmd('*', 'cmd.run', ['whoami'])\n            {'jerry': 'root'}\n\n        With extra keyword arguments for the command function to be run:\n\n        .. code-block:: python\n\n            local.cmd('*', 'test.arg', ['arg1', 'arg2'], kwarg={'foo': 'bar'})\n\n        Compound commands can be used for multiple executions in a single\n        publish. Function names and function arguments are provided in separate\n        lists but the index values must correlate and an empty list must be\n        used if no arguments are required.\n\n        .. code-block:: python\n\n            >>> local.cmd('*', [\n                    'grains.items',\n                    'sys.doc',\n                    'cmd.run',\n                ],\n                [\n                    [],\n                    [],\n                    ['uptime'],\n                ])\n\n        :param tgt: Which minions to target for the execution. Default is shell\n            glob. Modified by the ``tgt_type`` option.\n        :type tgt: string or list\n\n        :param fun: The module and function to call on the specified minions of\n            the form ``module.function``. For example ``test.ping`` or\n            ``grains.items``.\n\n            Compound commands\n                Multiple functions may be called in a single publish by\n                passing a list of commands. This can dramatically lower\n                overhead and speed up the application communicating with Salt.\n\n                This requires that the ``arg`` param is a list of lists. The\n                ``fun`` list and the ``arg`` list must correlate by index\n                meaning a function that does not take arguments must still have\n                a corresponding empty list at the expected index.\n        :type fun: string or list of strings\n\n        :param arg: A list of arguments to pass to the remote function. If the\n            function takes no arguments ``arg`` may be omitted except when\n            executing a compound command.\n        :type arg: list or list-of-lists\n\n        :param timeout: Seconds to wait after the last minion returns but\n            before all minions return.\n\n        :param tgt_type: The type of ``tgt``. Allowed values:\n\n            * ``glob`` - Bash glob completion - Default\n            * ``pcre`` - Perl style regular expression\n            * ``list`` - Python list of hosts\n            * ``grain`` - Match based on a grain comparison\n            * ``grain_pcre`` - Grain comparison with a regex\n            * ``pillar`` - Pillar data comparison\n            * ``pillar_pcre`` - Pillar data comparison with a regex\n            * ``nodegroup`` - Match on nodegroup\n            * ``range`` - Use a Range server for matching\n            * ``compound`` - Pass a compound match string\n            * ``ipcidr`` - Match based on Subnet (CIDR notation) or IPv4 address.\n\n            .. versionchanged:: 2017.7.0\n                Renamed from ``expr_form`` to ``tgt_type``\n\n        :param ret: The returner to use. The value passed can be single\n            returner, or a comma delimited list of returners to call in order\n            on the minions\n\n        :param kwarg: A dictionary with keyword arguments for the function.\n\n        :param full_return: Output the job return only (default) or the full\n            return including exit code and other job metadata.\n\n        :param kwargs: Optional keyword arguments.\n            Authentication credentials may be passed when using\n            :conf_master:`external_auth`.\n\n            For example: ``local.cmd('*', 'test.ping', username='saltdev',\n            password='saltdev', eauth='pam')``.\n            Or: ``local.cmd('*', 'test.ping',\n            token='5871821ea51754fdcea8153c1c745433')``\n\n        :returns: A dictionary with the result of the execution, keyed by\n            minion ID. A compound command will return a sub-dictionary keyed by\n            function name."
  },
  {
    "code": "def google_nest_count(self, style):\n        nest_count = 0\n        if 'margin-left' in style:\n            nest_count = int(style['margin-left'][:-2]) / self.google_list_indent\n        return nest_count",
    "docstring": "calculate the nesting count of google doc lists"
  },
  {
    "code": "def removeRouterPrefix(self, prefixEntry):\n        print '%s call removeRouterPrefix' % self.port\n        print prefixEntry\n        prefix = self.__convertIp6PrefixStringToIp6Address(str(prefixEntry))\n        try:\n            prefixLen = 64\n            cmd = 'prefix remove %s/%d' % (prefix, prefixLen)\n            print cmd\n            if self.__sendCommand(cmd)[0] == 'Done':\n                return self.__sendCommand('netdataregister')[0] == 'Done'\n            else:\n                return False\n        except Exception, e:\n            ModuleHelper.WriteIntoDebugLogger(\"removeRouterPrefix() Error: \" + str(e))",
    "docstring": "remove the configured prefix on a border router\n\n        Args:\n            prefixEntry: a on-mesh prefix entry\n\n        Returns:\n            True: successful to remove the prefix entry from border router\n            False: fail to remove the prefix entry from border router"
  },
  {
    "code": "def is_suburi(self, base, test):\n        if base == test:\n            return True\n        if base[0] != test[0]:\n            return False\n        common = posixpath.commonprefix((base[1], test[1]))\n        if len(common) == len(base[1]):\n            return True\n        return False",
    "docstring": "Check if test is below base in a URI tree\n\n        Both args must be URIs in reduced form."
  },
  {
    "code": "def clipPolygons(self, polygons):\n        if not self.plane: \n            return polygons[:]\n        front = []\n        back = []\n        for poly in polygons:\n            self.plane.splitPolygon(poly, front, back, front, back)\n        if self.front: \n            front = self.front.clipPolygons(front)\n        if self.back: \n            back = self.back.clipPolygons(back)\n        else:\n            back = []\n        front.extend(back)\n        return front",
    "docstring": "Recursively remove all polygons in `polygons` that are inside this BSP\n        tree."
  },
  {
    "code": "def streaming_command(self, service, command='', timeout_ms=None):\n    timeout = timeouts.PolledTimeout.from_millis(timeout_ms)\n    stream = self.open_stream('%s:%s' % (service, command), timeout)\n    if not stream:\n      raise usb_exceptions.AdbStreamUnavailableError(\n          '%s does not support service: %s', self, service)\n    for data in stream.read_until_close(timeout):\n      yield data",
    "docstring": "One complete set of packets for a single command.\n\n    Helper function to call open_stream and yield the output.  Sends\n    service:command in a new connection, reading the data for the response. All\n    the data is held in memory, large responses will be slow and can fill up\n    memory.\n\n    Args:\n      service: The service on the device to talk to.\n      command: The command to send to the service.\n      timeout_ms: Timeout for the entire command, in milliseconds (or as a\n        PolledTimeout object).\n\n    Yields:\n      The data contained in the responses from the service."
  },
  {
    "code": "def get_code_language(self):\n        js_source = self.get_js_source()\n        if self.options.get(\"include_html\", False):\n            resources = get_sphinx_resources(include_bokehjs_api=True)\n            html_source = BJS_HTML.render(\n                css_files=resources.css_files,\n                js_files=resources.js_files,\n                bjs_script=js_source)\n            return [html_source, \"html\"]\n        else:\n            return [js_source, \"javascript\"]",
    "docstring": "This is largely copied from bokeh.sphinxext.bokeh_plot.run"
  },
  {
    "code": "def _forward(self):\n        try:\n            self.current_token = next(self.tokens)\n        except StopIteration:\n            raise MissingTokensError(\"Unexpected end of token stream at %d.\" %\n                self.current_pos)\n        self.current_pos += 1",
    "docstring": "Advance to the next token.\n\n        Internal methods, updates:\n        - self.current_token\n        - self.current_pos\n\n        Raises:\n            MissingTokensError: when trying to advance beyond the end of the\n                token flow."
  },
  {
    "code": "def get_args_and_values(parser, an_action):\n    args = inspect.getargspec(an_action.__class__.__init__).args\n    kwargs = dict(\n        (an_attr, getattr(an_action, an_attr))\n        for an_attr in args\n        if (\n            an_attr not in ('self', 'required')\n            and getattr(an_action, an_attr) is not None\n        )\n    )\n    action_name = find_action_name_by_value(\n        parser._optionals._registries,\n        an_action\n    )\n    if 'required' in kwargs:\n        del kwargs['required']\n    kwargs['action'] = action_name\n    if 'option_strings' in kwargs:\n        args = tuple(kwargs['option_strings'])\n        del kwargs['option_strings']\n    else:\n        args = ()\n    return args, kwargs",
    "docstring": "this rountine attempts to reconstruct the kwargs that were used in the\n    creation of an action object"
  },
  {
    "code": "def get_aggregate (config):\n    _urlqueue = urlqueue.UrlQueue(max_allowed_urls=config[\"maxnumurls\"])\n    _robots_txt = robots_txt.RobotsTxt(config[\"useragent\"])\n    plugin_manager = plugins.PluginManager(config)\n    result_cache = results.ResultCache()\n    return aggregator.Aggregate(config, _urlqueue, _robots_txt, plugin_manager,\n        result_cache)",
    "docstring": "Get an aggregator instance with given configuration."
  },
  {
    "code": "def get_current_main_assistant(self):\n        current_page = self.notebook.get_nth_page(self.notebook.get_current_page())\n        return current_page.main_assistant",
    "docstring": "Function return current assistant"
  },
  {
    "code": "def unstructure_attrs_asdict(self, obj):\n        attrs = obj.__class__.__attrs_attrs__\n        dispatch = self._unstructure_func.dispatch\n        rv = self._dict_factory()\n        for a in attrs:\n            name = a.name\n            v = getattr(obj, name)\n            rv[name] = dispatch(v.__class__)(v)\n        return rv",
    "docstring": "Our version of `attrs.asdict`, so we can call back to us."
  },
  {
    "code": "def is_edge(obj, shape):\n    if obj[0].start == 0: return True\n    if obj[1].start == 0: return True\n    if obj[0].stop == shape[0]: return True\n    if obj[1].stop == shape[1]: return True\n    return False",
    "docstring": "Check if a 2d object is on the edge of the array.\n\n    Parameters\n    ----------\n    obj : tuple(slice, slice)\n        Pair of slices (e.g. from scipy.ndimage.measurements.find_objects)\n    shape : tuple(int, int)\n        Array shape.\n\n    Returns\n    -------\n    b : boolean\n        True if the object touches any edge of the array, else False."
  },
  {
    "code": "def rekey_multi(self, keys, nonce=None, recovery_key=False):\n        result = None\n        for key in keys:\n            result = self.rekey(\n                key=key,\n                nonce=nonce,\n                recovery_key=recovery_key,\n            )\n            if result.get('complete'):\n                break\n        return result",
    "docstring": "Enter multiple recovery key shares to progress the rekey of the Vault.\n\n        If the threshold number of recovery key shares is reached, Vault will complete the rekey.\n\n        :param keys: Specifies multiple recovery share keys.\n        :type keys: list\n        :param nonce: Specifies the nonce of the rekey operation.\n        :type nonce: str | unicode\n        :param recovery_key: If true, send requests to \"rekey-recovery-key\" instead of \"rekey\" api path.\n        :type recovery_key: bool\n        :return: The last response of the rekey request.\n        :rtype: response.Request"
  },
  {
    "code": "def change_password(self):\n        form = self._get_form('SECURITY_CHANGE_PASSWORD_FORM')\n        if form.validate_on_submit():\n            self.security_service.change_password(\n                current_user._get_current_object(),\n                form.new_password.data)\n            self.after_this_request(self._commit)\n            self.flash(_('flask_unchained.bundles.security:flash.password_change'),\n                       category='success')\n            if request.is_json:\n                return self.jsonify({'token': current_user.get_auth_token()})\n            return self.redirect('SECURITY_POST_CHANGE_REDIRECT_ENDPOINT',\n                                 'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT')\n        elif form.errors and request.is_json:\n            return self.errors(form.errors)\n        return self.render('change_password',\n                           change_password_form=form,\n                           **self.security.run_ctx_processor('change_password'))",
    "docstring": "View function for a user to change their password.\n        Supports html and json requests."
  },
  {
    "code": "def return_port(port):\n    if port in _random_ports:\n        _random_ports.remove(port)\n    elif port in _owned_ports:\n        _owned_ports.remove(port)\n        _free_ports.add(port)\n    elif port in _free_ports:\n        logging.info(\"Returning a port that was already returned: %s\", port)\n    else:\n        logging.info(\"Returning a port that wasn't given by portpicker: %s\",\n                     port)",
    "docstring": "Return a port that is no longer being used so it can be reused."
  },
  {
    "code": "async def handle_client_new_job(self, client_addr, message: ClientNewJob):\n        self._logger.info(\"Adding a new job %s %s to the queue\", client_addr, message.job_id)\n        self._waiting_jobs[(client_addr, message.job_id)] = message\n        await self.update_queue()",
    "docstring": "Handle an ClientNewJob message. Add a job to the queue and triggers an update"
  },
  {
    "code": "def int2str(self, num):\n        if int(num) != num:\n            raise TypeError('number must be an integer')\n        if num < 0:\n            raise ValueError('number must be positive')\n        radix, alphabet = self.radix, self.alphabet\n        if radix in (8, 10, 16) and \\\n                alphabet[:radix].lower() == BASE85[:radix].lower():\n            return ({8: '%o', 10: '%d', 16: '%x'}[radix] % num).upper()\n        ret = ''\n        while True:\n            ret = alphabet[num % radix] + ret\n            if num < radix:\n                break\n            num //= radix\n        return ret",
    "docstring": "Converts an integer into a string.\n\n        :param num: A numeric value to be converted to another base as a\n                    string.\n\n        :rtype: string\n\n        :raise TypeError: when *num* isn't an integer\n        :raise ValueError: when *num* isn't positive"
  },
  {
    "code": "def mcast_sender(mcgroup=MC_GROUP):\n    sock = socket(AF_INET, SOCK_DGRAM)\n    sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n    if _is_broadcast_group(mcgroup):\n        group = '<broadcast>'\n        sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)\n    elif((int(mcgroup.split(\".\")[0]) > 239) or\n         (int(mcgroup.split(\".\")[0]) < 224)):\n        raise IOError(\"Invalid multicast address.\")\n    else:\n        group = mcgroup\n        ttl = struct.pack('b', TTL_LOCALNET)\n        sock.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl)\n    return sock, group",
    "docstring": "Non-object interface for sending multicast messages."
  },
  {
    "code": "def to_raster(self, vector):\n        return transform(vector.get_shape(vector.crs), vector.crs, self.crs, dst_affine=~self.affine)",
    "docstring": "Return the vector in pixel coordinates, as shapely.Geometry."
  },
  {
    "code": "def list_replications(self):\n        docs = self.database.all_docs(include_docs=True)['rows']\n        documents = []\n        for doc in docs:\n            if doc['id'].startswith('_design/'):\n                continue\n            document = Document(self.database, doc['id'])\n            document.update(doc['doc'])\n            documents.append(document)\n        return documents",
    "docstring": "Retrieves all replication documents from the replication database.\n\n        :returns: List containing replication Document objects"
  },
  {
    "code": "def sort(self, *columns, **options):\n        sorts = self.meta.setdefault('sort', [])\n        for column in columns:\n            if isinstance(column, Column):\n                identifier = column.id\n            elif isinstance(column, utils.basestring):\n                descending = column.startswith('-') or options.get('descending', False)\n                identifier = self.api.columns[column.lstrip('-')].id\n            else:\n                raise ValueError(\"Can only sort on columns or column strings. Received: {}\".format(column))\n            if descending:\n                sign = '-'\n            else:\n                sign = ''\n            sorts.append(sign + identifier)\n        self.raw['sort'] = \",\".join(sorts)\n        return self",
    "docstring": "Return a new query which will produce results sorted by\n        one or more metrics or dimensions. You may use plain\n        strings for the columns, or actual `Column`, `Metric`\n        and `Dimension` objects.\n\n        Add a minus in front of the metric (either the string or\n        the object) to sort in descending order.\n\n        ```python\n        # sort using strings\n        query.sort('pageviews', '-device type')\n        # alternatively, ask for a descending sort in a keyword argument\n        query.sort('pageviews', descending=True)\n\n        # sort using metric, dimension or column objects\n        pageviews = profile.core.metrics['pageviews']\n        query.sort(-pageviews)\n        ```"
  },
  {
    "code": "def _update_frames(self, written):\n        if self.seekable():\n            curr = self.tell()\n            self._info.frames = self.seek(0, SEEK_END)\n            self.seek(curr, SEEK_SET)\n        else:\n            self._info.frames += written",
    "docstring": "Update self.frames after writing."
  },
  {
    "code": "def _write(self, session, openFile, replaceParamFile):\n        hmetRecords = self.hmetRecords\n        for record in hmetRecords:\n            openFile.write('%s\\t%s\\t%s\\t%s\\t%.3f\\t%s\\t%s\\t%s\\t%s\\t%.2f\\t%.2f\\n' % (\n                record.hmetDateTime.year,\n                record.hmetDateTime.month,\n                record.hmetDateTime.day,\n                record.hmetDateTime.hour,\n                record.barometricPress,\n                record.relHumidity,\n                record.totalSkyCover,\n                record.windSpeed,\n                record.dryBulbTemp,\n                record.directRad,\n                record.globalRad))",
    "docstring": "Write HMET WES to File Method"
  },
  {
    "code": "def remove_context(self, name):\n        self._context(name)\n        del self.contexts[name]\n        self._flush_tools()",
    "docstring": "Remove a context from the suite.\n\n        Args:\n            name (str): Name of the context to remove."
  },
  {
    "code": "def do_python_eval(self):\n        annopath = os.path.join(self.data_path, 'Annotations', '{:s}.xml')\n        imageset_file = os.path.join(self.data_path, 'ImageSets', 'Main', self.image_set + '.txt')\n        cache_dir = os.path.join(self.cache_path, self.name)\n        aps = []\n        use_07_metric = True if int(self.year) < 2010 else False\n        print('VOC07 metric? ' + ('Y' if use_07_metric else 'No'))\n        for cls_ind, cls in enumerate(self.classes):\n            filename = self.get_result_file_template().format(cls)\n            rec, prec, ap = voc_eval(filename, annopath, imageset_file, cls, cache_dir,\n                                     ovthresh=0.5, use_07_metric=use_07_metric)\n            aps += [ap]\n            print('AP for {} = {:.4f}'.format(cls, ap))\n        print('Mean AP = {:.4f}'.format(np.mean(aps)))",
    "docstring": "python evaluation wrapper\n\n        Returns:\n        ----------\n        None"
  },
  {
    "code": "def DbDeleteClassAttributeProperty(self, argin):\n        self._log.debug(\"In DbDeleteClassAttributeProperty()\")\n        if len(argin) < 3:\n            self.warn_stream(\"DataBase::db_delete_class_attribute_property(): insufficient number of arguments \")\n            th_exc(DB_IncorrectArguments,\n                   \"insufficient number of arguments to delete class attribute property\",\n                   \"DataBase::DeleteClassAttributeProperty()\")\n        klass_name, attr_name = argin[:2]\n        for prop_name in argin[2:]:\n            self.db.delete_class_attribute_property(klass_name, attr_name, prop_name)",
    "docstring": "delete class attribute properties from database\n\n        :param argin: Str[0] = Tango class name\n        Str[1] = Attribute name\n        Str[2] = Property name\n        Str[n] = Property name\n        :type: tango.DevVarStringArray\n        :return:\n        :rtype: tango.DevVoid"
  },
  {
    "code": "def _extract_sel_info(sel):\n    from cssselect2.parser import (CombinedSelector, CompoundSelector,\n                                   PseudoClassSelector,\n                                   FunctionalPseudoClassSelector)\n    steps = []\n    extras = []\n    if isinstance(sel, CombinedSelector):\n        lstep, lextras = _extract_sel_info(sel.left)\n        rstep, rextras = _extract_sel_info(sel.right)\n        steps = lstep + rstep\n        extras = lextras + rextras\n    elif isinstance(sel, CompoundSelector):\n        for ssel in sel.simple_selectors:\n            s, e = _extract_sel_info(ssel)\n            steps.extend(s)\n            extras.extend(e)\n    elif isinstance(sel, FunctionalPseudoClassSelector):\n        if sel.name == 'pass':\n            steps.append(serialize(sel.arguments).strip('\"\\''))\n    elif isinstance(sel, PseudoClassSelector):\n        if sel.name == 'deferred':\n            extras.append('deferred')\n    return (steps, extras)",
    "docstring": "Recurse down parsed tree, return pseudo class info"
  },
  {
    "code": "def atlasdb_get_zonefiles_missing_count_by_name(name, max_index=None, indexes_exclude=[], con=None, path=None):\n    with AtlasDBOpen(con=con, path=path) as dbcon:\n        sql = 'SELECT COUNT(*) FROM zonefiles WHERE name = ? AND present = 0 {} {};'.format(\n                'AND inv_index <= ?' if max_index is not None else '',\n                'AND inv_index NOT IN ({})'.format(','.join([str(int(i)) for i in indexes_exclude])) if len(indexes_exclude) > 0 else ''\n                )\n        args = (name,)\n        if max_index is not None:\n            args += (max_index,)\n        cur = dbcon.cursor()\n        res = atlasdb_query_execute(cur, sql, args)\n        for row in res:\n            return row['COUNT(*)']",
    "docstring": "Get the number of missing zone files for a particular name, optionally up to a maximum\n    zonefile index and optionally omitting particular zone files in the count.\n    Returns an integer"
  },
  {
    "code": "def _process_value(self, value, type):\n        if not isinstance(value, six.string_types + (list,)):\n            value = json.dumps(value)\n        return value",
    "docstring": "Process a value that will be sent to backend\n\n        :param value: the value to return\n\n        :param type: hint for what sort of value this is\n        :type type: str"
  },
  {
    "code": "def addComponentToPathway(self, component_id, pathway_id):\n        self.graph.addTriple(component_id, self.globaltt['involved in'], pathway_id)\n        return",
    "docstring": "This can be used directly when the component is directly involved in\n        the pathway.  If a transforming event is performed on the component\n        first, then the addGeneToPathway should be used instead.\n\n        :param pathway_id:\n        :param component_id:\n        :return:"
  },
  {
    "code": "def addLoginMethod(self, localpart, domain, protocol=ANY_PROTOCOL, verified=False, internal=False):\n        if self.store.parent is None:\n            otherStore = self.avatars.open()\n            peer = otherStore.findUnique(LoginAccount)\n        else:\n            otherStore = self.store.parent\n            subStoreItem = self.store.parent.getItemByID(self.store.idInParent)\n            peer = otherStore.findUnique(LoginAccount,\n                                         LoginAccount.avatars == subStoreItem)\n        for store, account in [(otherStore, peer), (self.store, self)]:\n            store.findOrCreate(LoginMethod,\n                               account=account,\n                               localpart=localpart,\n                               domain=domain,\n                               protocol=protocol,\n                               verified=verified,\n                               internal=internal)",
    "docstring": "Add a login method to this account, propogating up or down as necessary\n        to site store or user store to maintain consistency."
  },
  {
    "code": "def get_threads(self, querystring, sort='newest_first', exclude_tags=None):\n        assert sort in self._sort_orders\n        q = self.query(querystring)\n        q.set_sort(self._sort_orders[sort])\n        if exclude_tags:\n            for tag in exclude_tags:\n                q.exclude_tag(tag)\n        return self.async_(q.search_threads, (lambda a: a.get_thread_id()))",
    "docstring": "asynchronously look up thread ids matching `querystring`.\n\n        :param querystring: The query string to use for the lookup\n        :type querystring: str.\n        :param sort: Sort order. one of ['oldest_first', 'newest_first',\n                     'message_id', 'unsorted']\n        :type query: str\n        :param exclude_tags: Tags to exclude by default unless included in the\n                             search\n        :type exclude_tags: list of str\n        :returns: a pipe together with the process that asynchronously\n                  writes to it.\n        :rtype: (:class:`multiprocessing.Pipe`,\n                :class:`multiprocessing.Process`)"
  },
  {
    "code": "def particles_by_name(self, name):\n        for particle in self.particles():\n            if particle.name == name:\n                yield particle",
    "docstring": "Return all Particles of the Compound with a specific name\n\n        Parameters\n        ----------\n        name : str\n            Only particles with this name are returned\n\n        Yields\n        ------\n        mb.Compound\n            The next Particle in the Compound with the user-specified name"
  },
  {
    "code": "def timeit(func):\n    @wraps(func)\n    def timer_wrapper(*args, **kwargs):\n        with Timer() as timer:\n            result = func(*args, **kwargs)\n        return result, timer\n    return timer_wrapper",
    "docstring": "Returns the number of seconds that a function took along with the result"
  },
  {
    "code": "def _generate(self):\n        needs_close = False\n        if sys.hexversion >= 0x03000000:\n            if self._opts.output == '-':\n                from io import TextIOWrapper\n                pyfile = TextIOWrapper(sys.stdout.buffer, encoding='utf8')\n            else:\n                pyfile = open(self._opts.output, 'wt', encoding='utf8')\n                needs_close = True\n        else:\n            if self._opts.output == '-':\n                pyfile = sys.stdout\n            else:\n                pyfile = open(self._opts.output, 'wt')\n                needs_close = True\n        import_from = self._opts.import_from\n        if import_from:\n            from_imports = True\n        elif self._opts.from_imports:\n            from_imports = True\n            import_from = '.'\n        else:\n            from_imports = False\n        compileUi(self._ui_file, pyfile, self._opts.execute, self._opts.indent,\n                from_imports, self._opts.resource_suffix, import_from)\n        if needs_close:\n            pyfile.close()",
    "docstring": "Generate the Python code."
  },
  {
    "code": "def _extract_image_urls(self):\n        resultsPage = self._chromeDriver.page_source\n        resultsPageSoup = BeautifulSoup(resultsPage, 'html.parser')\n        images = resultsPageSoup.find_all('div', class_='rg_meta')\n        images = [json.loads(image.contents[0]) for image in images]\n        [self._imageURLs.append(image['ou']) for image in images]\n        self._imageURLsExtractedCount += len(images)",
    "docstring": "Retrieves image URLs from the current page"
  },
  {
    "code": "def groupReadOnlyViews(self, person):\n        grouped = {}\n        for contactType in self.getContactTypes():\n            for contactItem in contactType.getContactItems(person):\n                contactGroup = contactType.getContactGroup(contactItem)\n                if contactGroup is not None:\n                    contactGroup = contactGroup.groupName\n                if contactGroup not in grouped:\n                    grouped[contactGroup] = []\n                grouped[contactGroup].append(\n                    contactType.getReadOnlyView(contactItem))\n        return grouped",
    "docstring": "Collect all contact items from the available contact types for the\n        given person, organize them by contact group, and turn them into\n        read-only views.\n\n        @type person: L{Person}\n        @param person: The person whose contact items we're interested in.\n\n        @return: A mapping of of L{ContactGroup} names to the read-only views\n        of their member contact items, with C{None} being the key for\n        groupless contact items.\n        @rtype: C{dict} of C{str}"
  },
  {
    "code": "def GetParsersInformation(cls):\n    parsers_information = []\n    for _, parser_class in cls.GetParsers():\n      description = getattr(parser_class, 'DESCRIPTION', '')\n      parsers_information.append((parser_class.NAME, description))\n    return parsers_information",
    "docstring": "Retrieves the parsers information.\n\n    Returns:\n      list[tuple[str, str]]: parser names and descriptions."
  },
  {
    "code": "def load(cls, path):\n        assert os.path.exists(path), \"No such file: %r\" % path\n        (folder, filename) = os.path.split(path)\n        (name, extension) = os.path.splitext(filename)\n        wave = Waveform(None)\n        wave._path = path\n        return wave",
    "docstring": "Load Waveform from file."
  },
  {
    "code": "def in_same_dir(as_file, target_file):\n    return os.path.abspath(os.path.join(os.path.dirname(as_file), target_file))",
    "docstring": "Return an absolute path to a target file that is located in the same directory as as_file\n\n    Args:\n        as_file: File name (including __file__)\n            Use the directory path of this file\n        target_file: Name of the target file"
  },
  {
    "code": "def send_scp(self, *args, **kwargs):\n        x = kwargs.pop(\"x\")\n        y = kwargs.pop(\"y\")\n        p = kwargs.pop(\"p\")\n        return self._send_scp(x, y, p, *args, **kwargs)",
    "docstring": "Transmit an SCP Packet and return the response.\n\n        This function is a thin wrapper around\n        :py:meth:`rig.machine_control.scp_connection.SCPConnection.send_scp`.\n\n        This function will attempt to use the SCP connection nearest the\n        destination of the SCP command if multiple connections have been\n        discovered using :py:meth:`.discover_connections`.\n\n        Parameters\n        ----------\n        x : int\n        y : int\n        p : int\n        *args\n        **kwargs"
  },
  {
    "code": "def make_local_dirs(dl_dir, dl_inputs, keep_subdirs):\n    if not os.path.isdir(dl_dir):\n        os.makedirs(dl_dir)\n        print('Created local base download directory: %s' % dl_dir)\n    if keep_subdirs:\n        dl_dirs = set([os.path.join(dl_dir, d[1]) for d in dl_inputs])\n        for d in dl_dirs:\n            if not os.path.isdir(d):\n                os.makedirs(d)\n    return",
    "docstring": "Make any required local directories to prepare for downloading"
  },
  {
    "code": "def publish(self, distribution, storage=\"\"):\n        try:\n            return self._publishes[distribution]\n        except KeyError:\n            self._publishes[distribution] = Publish(self.client, distribution, timestamp=self.timestamp, storage=(storage or self.storage))\n            return self._publishes[distribution]",
    "docstring": "Get or create publish"
  },
  {
    "code": "def object(self, infotype, key):\n        \"Return the encoding, idletime, or refcount about the key\"\n        return self.execute_command('OBJECT', infotype, key, infotype=infotype)",
    "docstring": "Return the encoding, idletime, or refcount about the key"
  },
  {
    "code": "def get_emitter(self, name: str) -> Callable[[Event], Event]:\n        return self._event_manager.get_emitter(name)",
    "docstring": "Gets and emitter for a named event.\n\n        Parameters\n        ----------\n        name :\n            The name of the event he requested emitter will emit.\n            Users may provide their own named events by requesting an emitter with this function,\n            but should do so with caution as it makes time much more difficult to think about.\n\n        Returns\n        -------\n            An emitter for the named event. The emitter should be called by the requesting component\n            at the appropriate point in the simulation lifecycle."
  },
  {
    "code": "def redirect_output(fileobj):\n    old = sys.stdout\n    sys.stdout = fileobj\n    try:\n        yield fileobj\n    finally:\n        sys.stdout = old",
    "docstring": "Redirect standard out to file."
  },
  {
    "code": "def read_kioslaverc (kde_config_dir):\n    data = {}\n    filename = os.path.join(kde_config_dir, \"kioslaverc\")\n    with open(filename) as fd:\n        for line in  fd:\n            line = line.rstrip()\n            if line.startswith('['):\n                in_proxy_settings = line.startswith(\"[Proxy Settings]\")\n            elif in_proxy_settings:\n                if '=' not in line:\n                    continue\n                key, value = line.split('=', 1)\n                key = key.strip()\n                value = value.strip()\n                if not key:\n                    continue\n                key = loc_ro.sub(\"\", key).strip()\n                if not key:\n                    continue\n                add_kde_setting(key, value, data)\n    resolve_kde_settings(data)\n    return data",
    "docstring": "Read kioslaverc into data dictionary."
  },
  {
    "code": "def f2tc(f,base=25):\n    try:\n        f = int(f)\n    except:\n        return \"--:--:--:--\"\n    hh = int((f / base) / 3600)\n    mm = int(((f / base) / 60) - (hh*60))\n    ss = int((f/base) - (hh*3600) - (mm*60))\n    ff = int(f - (hh*3600*base) - (mm*60*base) - (ss*base))\n    return \"{:02d}:{:02d}:{:02d}:{:02d}\".format(hh, mm, ss, ff)",
    "docstring": "Converts frames to timecode"
  },
  {
    "code": "def undecorate(cls, function):\n        if cls.is_function_validated(function):\n            return cls.get_function_validator(function).function\n        return function",
    "docstring": "Remove validator decoration from a function.\n\n        The `function` argument is the function to be cleaned from\n        the validator decorator."
  },
  {
    "code": "def remove_event(self, func_name: str, event: str) -> None:\n        event_funcs_copy = self._events[event].copy()\n        for func in self._event_funcs(event):\n            if func.__name__ == func_name:\n                event_funcs_copy.remove(func)\n        if self._events[event] == event_funcs_copy:\n            err_msg = \"function doesn't exist inside event {} \".format(event)\n            raise EventDoesntExist(err_msg)\n        else:\n            self._events[event] = event_funcs_copy",
    "docstring": "Removes a subscribed function from a specific event.\n\n        :param func_name: The name of the function to be removed.\n        :type func_name: str\n\n        :param event: The name of the event.\n        :type event: str\n\n        :raise EventDoesntExist if there func_name doesn't exist in event."
  },
  {
    "code": "def archs(self, _args):\n        print('{Style.BRIGHT}Available target architectures are:'\n              '{Style.RESET_ALL}'.format(Style=Out_Style))\n        for arch in self.ctx.archs:\n            print('    {}'.format(arch.arch))",
    "docstring": "List the target architectures available to be built for."
  },
  {
    "code": "def mean_values(self):\n        if not self.istransformed:\n            return self.pst.parameter_data.parval1.copy()\n        else:\n            vals = self.pst.parameter_data.parval1.copy()\n            vals[self.log_indexer] = np.log10(vals[self.log_indexer])\n            return vals",
    "docstring": "the mean value vector while respecting log transform\n\n        Returns\n        -------\n        mean_values : pandas.Series"
  },
  {
    "code": "def getThirdPartyLibCmakeFlags(self, libs):\n\t\tfmt = PrintingFormat.singleLine()\n\t\tif libs[0] == '--multiline':\n\t\t\tfmt = PrintingFormat.multiLine()\n\t\t\tlibs = libs[1:]\n\t\tplatformDefaults = True\n\t\tif libs[0] == '--nodefaults':\n\t\t\tplatformDefaults = False\n\t\t\tlibs = libs[1:]\n\t\tdetails = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults)\n\t\tCMakeCustomFlags.processLibraryDetails(details)\n\t\treturn details.getCMakeFlags(self.getEngineRoot(), fmt)",
    "docstring": "Retrieves the CMake invocation flags for building against the Unreal-bundled versions of the specified third-party libraries"
  },
  {
    "code": "def serialize(self, attr, obj, accessor=None, **kwargs):\n        if self._CHECK_ATTRIBUTE:\n            value = self.get_value(obj, attr, accessor=accessor)\n            if value is missing_ and hasattr(self, 'default'):\n                default = self.default\n                value = default() if callable(default) else default\n            if value is missing_:\n                return value\n        else:\n            value = None\n        return self._serialize(value, attr, obj, **kwargs)",
    "docstring": "Pulls the value for the given key from the object, applies the\n        field's formatting and returns the result.\n\n        :param str attr: The attribute or key to get from the object.\n        :param str obj: The object to pull the key from.\n        :param callable accessor: Function used to pull values from ``obj``.\n        :param dict kwargs': Field-specific keyword arguments.\n        :raise ValidationError: In case of formatting problem"
  },
  {
    "code": "def open(fn, expand_includes=True, include_comments=False, include_position=False, **kwargs):\n    p = Parser(expand_includes=expand_includes,\n               include_comments=include_comments, **kwargs)\n    ast = p.parse_file(fn)\n    m = MapfileToDict(include_position=include_position,\n                      include_comments=include_comments, **kwargs)\n    d = m.transform(ast)\n    return d",
    "docstring": "Load a Mapfile from the supplied filename into a Python dictionary.\n\n    Parameters\n    ----------\n\n    fn: string\n        The path to the Mapfile, or partial Mapfile\n    expand_includes: boolean\n        Load any ``INCLUDE`` files in the MapFile\n    include_comments: boolean\n         Include or discard comment strings from the Mapfile - *experimental*\n    include_position: boolean\n         Include the position of the Mapfile tokens in the output\n\n    Returns\n    -------\n\n    dict\n        A Python dictionary representing the Mapfile in the mappyfile format\n\n    Example\n    -------\n\n    To open a Mapfile from a filename and return it as a dictionary object::\n\n        d = mappyfile.open('mymap.map')\n\n    Notes\n    -----\n\n    Partial Mapfiles can also be opened, for example a file containing a ``LAYER`` object."
  },
  {
    "code": "def get_connectable_volume_templates(self, start=0, count=-1, filter='', query='', sort=''):\n        uri = self.URI + \"/connectable-volume-templates\"\n        get_uri = self._client.build_query_uri(start=start, count=count, filter=filter,\n                                               query=query, sort=sort, uri=uri)\n        return self._client.get(get_uri)",
    "docstring": "Gets the storage volume templates that are available on the specified networks based on the storage system\n        port's expected network connectivity. If there are no storage volume templates that meet the specified\n        connectivity criteria, an empty collection will be returned.\n\n        Returns:\n            list: Storage volume templates."
  },
  {
    "code": "def parse_groups(self, group, params):\n        if group['GroupName'] in self.groups:\n            return\n        api_client = params['api_client']\n        group['id'] = group.pop('GroupId')\n        group['name'] = group.pop('GroupName')\n        group['arn'] = group.pop('Arn')\n        group['users'] = self.__fetch_group_users(api_client, group['name']);\n        policies = self.__get_inline_policies(api_client, 'group', group['id'], group['name'])\n        if len(policies):\n            group['inline_policies'] = policies\n        group['inline_policies_count'] = len(policies)\n        self.groups[group['id']] = group",
    "docstring": "Parse a single IAM group and fetch additional information"
  },
  {
    "code": "def transaction_fail(self, name):\n        if not name:\n            raise ValueError(\"Transaction name cannot be empty\")\n        if self.transaction_count > 0:\n            logger.debug(\"{}. Failing transaction {}\".format(self.transaction_count, name))\n            if self.transaction_count == 1:\n                self._transaction_fail()\n            else:\n                self._transaction_failing(name)\n            self.transaction_count -= 1",
    "docstring": "rollback a transaction if currently in one\n\n        e -- Exception() -- if passed in, bubble up the exception by re-raising it"
  },
  {
    "code": "def sample(self, hash, limit=None, offset=None):\n        uri = self._uris['sample'].format(hash)\n        params = {'limit': limit, 'offset': offset}\n        return self.get_parse(uri, params)",
    "docstring": "Return an object representing the sample identified by the input hash, or an empty object if that sample is not found"
  },
  {
    "code": "def strict_deps_for_target(self, target, predicate=None):\n    if self._native_build_settings.get_strict_deps_value_for_target(target):\n      strict_deps = target.strict_dependencies(DependencyContext())\n      if predicate:\n        filtered_deps = list(filter(predicate, strict_deps))\n      else:\n        filtered_deps = strict_deps\n      deps = [target] + filtered_deps\n    else:\n      deps = self.context.build_graph.transitive_subgraph_of_addresses(\n        [target.address], predicate=predicate)\n    deps = filter(predicate, deps)\n    return deps",
    "docstring": "Get the dependencies of `target` filtered by `predicate`, accounting for 'strict_deps'.\n\n    If 'strict_deps' is on, instead of using the transitive closure of dependencies, targets will\n    only be able to see their immediate dependencies declared in the BUILD file. The 'strict_deps'\n    setting is obtained from the result of `get_compile_settings()`.\n\n    NB: This includes the current target in the result."
  },
  {
    "code": "def rdf_source(self, aformat=\"turtle\"):\n\t\tif aformat and aformat not in self.SUPPORTED_FORMATS:\n\t\t\treturn \"Sorry. Allowed formats are %s\" % str(self.SUPPORTED_FORMATS)\n\t\tif aformat == \"dot\":\n\t\t\treturn self.__serializedDot()\n\t\telse:\n\t\t\treturn self.rdflib_graph.serialize(format=aformat)",
    "docstring": "Serialize graph using the format required"
  },
  {
    "code": "def create_primary_zone_by_upload(self, account_name, zone_name, bind_file):\n        zone_properties = {\"name\": zone_name, \"accountName\": account_name, \"type\": \"PRIMARY\"}\n        primary_zone_info = {\"forceImport\": True, \"createType\": \"UPLOAD\"}\n        zone_data = {\"properties\": zone_properties, \"primaryCreateInfo\": primary_zone_info}\n        files = {'zone': ('', json.dumps(zone_data), 'application/json'),\n                 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')}\n        return self.rest_api_connection.post_multi_part(\"/v1/zones\", files)",
    "docstring": "Creates a new primary zone by uploading a bind file\n\n        Arguments:\n        account_name -- The name of the account that will contain this zone.\n        zone_name -- The name of the zone.  It must be unique.\n        bind_file -- The file to upload."
  },
  {
    "code": "def _md5_compare(self, file_path, checksum, block_size=2 ** 13):\n        with closing(self._tqdm(desc=\"MD5 checksumming\", total=getsize(file_path), unit=\"B\",\n                                unit_scale=True)) as progress:\n            md5 = hashlib.md5()\n            with open(file_path, \"rb\") as f:\n                while True:\n                    block_data = f.read(block_size)\n                    if not block_data:\n                        break\n                    md5.update(block_data)\n                    progress.update(len(block_data))\n            return md5.hexdigest().lower() == checksum.lower()",
    "docstring": "Compare a given MD5 checksum with one calculated from a file."
  },
  {
    "code": "def unmarshal_event(self, data: str, response_type):\n        js = json.loads(data)\n        js['raw_object'] = js['object']\n        if js['type'].lower() == 'error':\n            return js\n        if response_type is not None:\n            js['object'] = self._api_client.deserialize(\n                response=SimpleNamespace(data=json.dumps(js['raw_object'])),\n                response_type=response_type\n            )\n            if hasattr(js['object'], 'metadata'):\n                self.resource_version = js['object'].metadata.resource_version\n            elif (isinstance(js['object'], dict) and\n                  'metadata' in js['object'] and\n                  'resourceVersion' in js['object']['metadata']):\n                self.resource_version = js['object']['metadata']['resourceVersion']\n        return js",
    "docstring": "Return the K8s response `data` in JSON format."
  },
  {
    "code": "def find_filter_class(filtername):\n    if filtername in FILTERS:\n        return FILTERS[filtername]\n    for name, cls in find_plugin_filters():\n        if name == filtername:\n            return cls\n    return None",
    "docstring": "Lookup a filter by name. Return None if not found."
  },
  {
    "code": "def verify_database(trusted_consensus_hash, consensus_block_height, untrusted_working_dir, trusted_working_dir, start_block=None, expected_snapshots={}):\n    db = BlockstackDB.get_readwrite_instance(trusted_working_dir)\n    consensus_impl = virtualchain_hooks\n    return virtualchain.state_engine_verify(trusted_consensus_hash, consensus_block_height, consensus_impl, untrusted_working_dir, db, start_block=start_block, expected_snapshots=expected_snapshots)",
    "docstring": "Verify that a database is consistent with a\n    known-good consensus hash.\n    Return True if valid.\n    Return False if not"
  },
  {
    "code": "async def get_default(cls):\n        data = await cls._handler.read(id=cls._default_fabric_id)\n        return cls(data)",
    "docstring": "Get the 'default' Fabric for the MAAS."
  },
  {
    "code": "def normalize_shape(shape):\n    if shape is None:\n        raise TypeError('shape is None')\n    if isinstance(shape, numbers.Integral):\n        shape = (int(shape),)\n    shape = tuple(int(s) for s in shape)\n    return shape",
    "docstring": "Convenience function to normalize the `shape` argument."
  },
  {
    "code": "def create_files(filedef, cleanup=True):\n    cwd = os.getcwd()\n    tmpdir = tempfile.mkdtemp()\n    try:\n        Filemaker(tmpdir, filedef)\n        if not cleanup:\n            pass\n        os.chdir(tmpdir)\n        yield tmpdir\n    finally:\n        os.chdir(cwd)\n        if cleanup:\n            shutil.rmtree(tmpdir, ignore_errors=True)",
    "docstring": "Contextmanager that creates a directory structure from a yaml\n       descripttion."
  },
  {
    "code": "def get_appended_name(name, columns):\n    loop = 0\n    while name in columns:\n        loop += 1\n        if loop > 10:\n            logger_misc.warn(\"get_appended_name: Too many loops: Tried to get appended name but something looks wrong\")\n            break\n        tmp = name + \"-\" + str(loop)\n        if tmp not in columns:\n            return tmp\n    return name + \"-99\"",
    "docstring": "Append numbers to a name until it no longer conflicts with the other names in a column.\n    Necessary to avoid overwriting columns and losing data. Loop a preset amount of times to avoid an infinite loop.\n    There shouldn't ever be more than two or three identical variable names in a table.\n\n    :param str name: Variable name in question\n    :param dict columns: Columns listed by variable name\n    :return str: Appended variable name"
  },
  {
    "code": "def tracking_save(sender, instance, raw, using, update_fields, **kwargs):\n    if _has_changed(instance):\n        if instance._original_fields['pk'] is None:\n            _create_create_tracking_event(instance)\n        else:\n            _create_update_tracking_event(instance)\n    if _has_changed_related(instance):\n        _create_update_tracking_related_event(instance)\n    if _has_changed(instance) or _has_changed_related(instance):\n        _set_original_fields(instance)",
    "docstring": "Post save, detect creation or changes and log them.\n    We need post_save to have the object for a create."
  },
  {
    "code": "def clear_state(self):\n        self.state = {}\n        self.state['steps'] = []\n        self.state['current_step'] = None\n        self.state['scope'] = []\n        self.state['counters'] = {}\n        self.state['strings'] = {}\n        for step in self.matchers:\n            self.state[step] = {}\n            self.state[step]['pending'] = {}\n            self.state[step]['actions'] = []\n            self.state[step]['counters'] = {}\n            self.state[step]['strings'] = {}\n            self.state[step]['recipe'] = False",
    "docstring": "Clear the recipe state."
  },
  {
    "code": "def get_prev_block_hash(block_representation, coin_symbol='btc', api_key=None):\n    return get_block_overview(block_representation=block_representation,\n            coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['prev_block']",
    "docstring": "Takes a block_representation and returns the previous block hash"
  },
  {
    "code": "def DbAddServer(self, argin):\n        self._log.debug(\"In DbAddServer()\")\n        if len(argin) < 3 or not len(argin) % 2:\n            self.warn_stream(\"DataBase::AddServer(): incorrect number of input arguments \")\n            th_exc(DB_IncorrectArguments,\n                   \"incorrect no. of input arguments, needs at least 3 (server,device,class)\",\n                   \"DataBase::AddServer()\")\n        server_name = argin[0]\n        for i in range((len(argin) - 1) / 2):\n            d_name, klass_name = argin[i * 2 + 1], argin[i * 2 + 2]\n            ret, dev_name, dfm = check_device_name(d_name)\n            if not ret:\n                th_exc(DB_IncorrectDeviceName,\n                      \"device name (\" + d_name + \") syntax error (should be [tango:][//instance/]domain/family/member)\",\n                      \"DataBase::AddServer()\")\n            self.db.add_device(server_name, (dev_name, dfm) , klass_name)",
    "docstring": "Create a device server process entry in database\n\n        :param argin: Str[0] = Full device server name\n        Str[1] = Device(s) name\n        Str[2] = Tango class name\n        Str[n] = Device name\n        Str[n + 1] = Tango class name\n        :type: tango.DevVarStringArray\n        :return:\n        :rtype: tango.DevVoid"
  },
  {
    "code": "def transfer(self, transfer_payload=None, *, from_user, to_user):\n        if self.persist_id is None:\n            raise EntityNotYetPersistedError(('Entities cannot be transferred '\n                                              'until they have been '\n                                              'persisted'))\n        return self.plugin.transfer(self.persist_id, transfer_payload,\n                                    from_user=from_user, to_user=to_user)",
    "docstring": "Transfer this entity to another owner on the backing\n        persistence layer\n\n        Args:\n            transfer_payload (dict): Payload for the transfer\n            from_user (any): A user based on the model specified by the\n                persistence layer\n            to_user (any): A user based on the model specified by the\n                persistence layer\n\n        Returns:\n            str: Id of the resulting transfer action on the persistence\n            layer\n\n        Raises:\n            :exc:`~.EntityNotYetPersistedError`: If the entity being\n                transferred is not associated with an id on the\n                persistence layer (:attr:`~Entity.persist_id`) yet\n            :exc:`~.EntityNotFoundError`: If the entity could not be\n                found on the persistence layer\n            :exc:`~.EntityTransferError`: If the entity fails to be\n                transferred on the persistence layer\n            :exc:`~.PersistenceError`: If any other unhandled error\n                in the plugin occurred"
  },
  {
    "code": "def cluster_path(cls, project, instance, cluster):\n        return google.api_core.path_template.expand(\n            \"projects/{project}/instances/{instance}/clusters/{cluster}\",\n            project=project,\n            instance=instance,\n            cluster=cluster,\n        )",
    "docstring": "Return a fully-qualified cluster string."
  },
  {
    "code": "def symmetrized(self):\n        perms = list(itertools.permutations(range(self.rank)))\n        return sum([np.transpose(self, ind) for ind in perms]) / len(perms)",
    "docstring": "Returns a generally symmetrized tensor, calculated by taking\n        the sum of the tensor and its transpose with respect to all\n        possible permutations of indices"
  },
  {
    "code": "def count(self):\n        if hasattr(self, '_response'):\n            return self._response.hits.total\n        es = connections.get_connection(self._using)\n        d = self.to_dict(count=True)\n        return es.count(\n            index=self._index,\n            body=d,\n            **self._params\n        )['count']",
    "docstring": "Return the number of hits matching the query and filters. Note that\n        only the actual number is returned."
  },
  {
    "code": "def update_room(room):\n    if room.custom_server:\n        return\n    def _update_room(xmpp):\n        muc = xmpp.plugin['xep_0045']\n        muc.joinMUC(room.jid, xmpp.requested_jid.user)\n        muc.configureRoom(room.jid, _set_form_values(xmpp, room, muc.getRoomConfig(room.jid)))\n    current_plugin.logger.info('Updating room %s', room.jid)\n    _execute_xmpp(_update_room)",
    "docstring": "Updates a MUC room on the XMPP server."
  },
  {
    "code": "def typecounter(table, field):\n    counter = Counter()\n    for v in values(table, field):\n        try:\n            counter[v.__class__.__name__] += 1\n        except IndexError:\n            pass\n    return counter",
    "docstring": "Count the number of values found for each Python type.\n\n        >>> import petl as etl\n        >>> table = [['foo', 'bar', 'baz'],\n        ...          ['A', 1, 2],\n        ...          ['B', u'2', '3.4'],\n        ...          [u'B', u'3', u'7.8', True],\n        ...          ['D', u'xyz', 9.0],\n        ...          ['E', 42]]\n        >>> etl.typecounter(table, 'foo')\n        Counter({'str': 5})\n        >>> etl.typecounter(table, 'bar')\n        Counter({'str': 3, 'int': 2})\n        >>> etl.typecounter(table, 'baz')\n        Counter({'str': 2, 'int': 1, 'float': 1, 'NoneType': 1})\n\n    The `field` argument can be a field name or index (starting from zero)."
  },
  {
    "code": "def absolute_uri(self, location=None, scheme=None, **query):\n        if not is_absolute_uri(location):\n            if location or location is None:\n                location = self.full_path(location, **query)\n            if not scheme:\n                scheme = self.is_secure and 'https' or 'http'\n            base = '%s://%s' % (scheme, self.get_host())\n            return '%s%s' % (base, location)\n        elif not scheme:\n            return iri_to_uri(location)\n        else:\n            raise ValueError('Absolute location with scheme not valid')",
    "docstring": "Builds an absolute URI from ``location`` and variables\n        available in this request.\n\n        If no ``location`` is specified, the relative URI is built from\n        :meth:`full_path`."
  },
  {
    "code": "def min(self):\n        if self.is_quantized or self.base_dtype in (\n            bool,\n            string,\n            complex64,\n            complex128,\n        ):\n            raise TypeError(\"Cannot find minimum value of %s.\" % self)\n        try:\n            return np.finfo(self.as_numpy_dtype()).min\n        except:\n            try:\n                return np.iinfo(self.as_numpy_dtype()).min\n            except:\n                if self.base_dtype == bfloat16:\n                    return _np_bfloat16(float.fromhex(\"-0x1.FEp127\"))\n                raise TypeError(\"Cannot find minimum value of %s.\" % self)",
    "docstring": "Returns the minimum representable value in this data type.\n\n        Raises:\n          TypeError: if this is a non-numeric, unordered, or quantized type."
  },
  {
    "code": "def flat_list(input_list):\n    r\n    x = input_list\n    if isinstance(x, list):\n        return [a for i in x for a in flat_list(i)]\n    else:\n        return [x]",
    "docstring": "r\"\"\"\n    Given a list of nested lists of arbitrary depth, returns a single level or\n    'flat' list."
  },
  {
    "code": "def putParamset(self, paramset, data={}):\n        try:\n            if paramset in self._PARAMSETS and data:\n                self._proxy.putParamset(self._ADDRESS, paramset, data)\n                self.updateParamsets()\n                return True\n            else:\n                return False\n        except Exception as err:\n            LOG.error(\"HMGeneric.putParamset: Exception: \" + str(err))\n            return False",
    "docstring": "Some devices act upon changes to paramsets.\n        A \"putted\" paramset must not contain all keys available in the specified paramset,\n        just the ones which are writable and should be changed."
  },
  {
    "code": "def gateways_info():\n    data = netifaces.gateways()\n    results = {'default': {}}\n    with suppress(KeyError):\n        results['ipv4'] = data[netifaces.AF_INET]\n        results['default']['ipv4'] = data['default'][netifaces.AF_INET]\n    with suppress(KeyError):\n        results['ipv6'] = data[netifaces.AF_INET6]\n        results['default']['ipv6'] = data['default'][netifaces.AF_INET6]\n    return results",
    "docstring": "Returns gateways data."
  },
  {
    "code": "def library_hierarchy_depth(self):\n        current_library_hierarchy_depth = 1\n        library_root_state = self.get_next_upper_library_root_state()\n        while library_root_state is not None:\n            current_library_hierarchy_depth += 1\n            library_root_state = library_root_state.parent.get_next_upper_library_root_state()\n        return current_library_hierarchy_depth",
    "docstring": "Calculates the library hierarchy depth\n\n        Counting starts at the current library state. So if the there is no upper library state the depth is one.\n        \n        :return: library hierarchy depth\n        :rtype: int"
  },
  {
    "code": "def token_cache_pkgs(source=None, release=None):\n    packages = []\n    if enable_memcache(source=source, release=release):\n        packages.extend(['memcached', 'python-memcache'])\n    return packages",
    "docstring": "Determine additional packages needed for token caching\n\n    @param source: source string for charm\n    @param release: release of OpenStack currently deployed\n    @returns List of package to enable token caching"
  },
  {
    "code": "def verify_connectivity(config):\n    logger.debug(\"Verifying Connectivity\")\n    ic = InsightsConnection(config)\n    try:\n        branch_info = ic.get_branch_info()\n    except requests.ConnectionError as e:\n        logger.debug(e)\n        logger.debug(\"Failed to connect to satellite\")\n        return False\n    except LookupError as e:\n        logger.debug(e)\n        logger.debug(\"Failed to parse response from satellite\")\n        return False\n    try:\n        remote_leaf = branch_info['remote_leaf']\n        return remote_leaf\n    except LookupError as e:\n        logger.debug(e)\n        logger.debug(\"Failed to find accurate branch_info\")\n        return False",
    "docstring": "Verify connectivity to satellite server"
  },
  {
    "code": "def _inject_patched_examples(self, existing_item, patched_item):\n        for key, _ in patched_item.examples.items():\n            patched_example = patched_item.examples[key]\n            existing_examples = existing_item.examples\n            if key in existing_examples:\n                existing_examples[key].fields.update(patched_example.fields)\n            else:\n                error_msg = 'Example defined in patch {} must correspond to a pre-existing example.'\n                raise InvalidSpec(error_msg.format(\n                    quote(patched_item.name)), patched_example.lineno, patched_example.path)",
    "docstring": "Injects patched examples into original examples."
  },
  {
    "code": "def validate_argmin_with_skipna(skipna, args, kwargs):\n    skipna, args = process_skipna(skipna, args)\n    validate_argmin(args, kwargs)\n    return skipna",
    "docstring": "If 'Series.argmin' is called via the 'numpy' library,\n    the third parameter in its signature is 'out', which\n    takes either an ndarray or 'None', so check if the\n    'skipna' parameter is either an instance of ndarray or\n    is None, since 'skipna' itself should be a boolean"
  },
  {
    "code": "def next(self):\n        if self._selfiter is None:\n            warnings.warn(\n                \"Calling 'next' directly on a query is deprecated. \"\n                \"Perhaps you want to use iter(query).next(), or something \"\n                \"more expressive like store.findFirst or store.findOrCreate?\",\n                DeprecationWarning, stacklevel=2)\n            self._selfiter = self.__iter__()\n        return self._selfiter.next()",
    "docstring": "This method is deprecated, a holdover from when queries were iterators,\n        rather than iterables.\n\n        @return: one element of massaged data."
  },
  {
    "code": "def rollback(self, release):\n        r = self._h._http_resource(\n            method='POST',\n            resource=('apps', self.name, 'releases'),\n            data={'rollback': release}\n        )\n        return self.releases[-1]",
    "docstring": "Rolls back the release to the given version."
  },
  {
    "code": "def most_recent_submission(project, group):\n        return (Submission.query_by(project=project, group=group)\n                .order_by(Submission.created_at.desc()).first())",
    "docstring": "Return the most recent submission for the user and project id."
  },
  {
    "code": "def params_for(prefix, kwargs):\n    if not prefix.endswith('__'):\n        prefix += '__'\n    return {key[len(prefix):]: val for key, val in kwargs.items()\n            if key.startswith(prefix)}",
    "docstring": "Extract parameters that belong to a given sklearn module prefix from\n    ``kwargs``. This is useful to obtain parameters that belong to a\n    submodule.\n\n    Examples\n    --------\n    >>> kwargs = {'encoder__a': 3, 'encoder__b': 4, 'decoder__a': 5}\n    >>> params_for('encoder', kwargs)\n    {'a': 3, 'b': 4}"
  },
  {
    "code": "def joint_entropy_calc(classes, table, POP):\n    try:\n        result = 0\n        for i in classes:\n            for index, j in enumerate(classes):\n                p_prime = table[i][j] / POP[i]\n                if p_prime != 0:\n                    result += p_prime * math.log(p_prime, 2)\n        return -result\n    except Exception:\n        return \"None\"",
    "docstring": "Calculate joint entropy.\n\n    :param classes: confusion matrix classes\n    :type classes : list\n    :param table: confusion matrix table\n    :type table : dict\n    :param POP: population\n    :type POP : dict\n    :return: joint entropy as float"
  },
  {
    "code": "def create_placement_group(self, name, strategy='cluster'):\n        params = {'GroupName':name, 'Strategy':strategy}\n        group = self.get_status('CreatePlacementGroup', params, verb='POST')\n        return group",
    "docstring": "Create a new placement group for your account.\n        This will create the placement group within the region you\n        are currently connected to.\n\n        :type name: string\n        :param name: The name of the new placement group\n\n        :type strategy: string\n        :param strategy: The placement strategy of the new placement group.\n                         Currently, the only acceptable value is \"cluster\".\n\n        :rtype: bool\n        :return: True if successful"
  },
  {
    "code": "def _Enum(docstring, *names):\n  enums = dict(zip(names, range(len(names))))\n  reverse = dict((value, key) for key, value in enums.iteritems())\n  enums['reverse_mapping'] = reverse\n  enums['__doc__'] = docstring\n  return type('Enum', (object,), enums)",
    "docstring": "Utility to generate enum classes used by annotations.\n\n  Args:\n    docstring: Docstring for the generated enum class.\n    *names: Enum names.\n\n  Returns:\n    A class that contains enum names as attributes."
  },
  {
    "code": "def setdatastrs(self, label, unit, format, coord_sys):\n        status = _C.SDsetdatastrs(self._id, label, unit, format, coord_sys)\n        _checkErr('setdatastrs', status, 'cannot execute')",
    "docstring": "Set the dataset standard string type attributes.\n\n        Args::\n\n          label         dataset label (attribute 'long_name')\n          unit          dataset unit (attribute 'units')\n          format        dataset format (attribute 'format')\n          coord_sys     dataset coordinate system (attribute 'coordsys')\n\n        Returns::\n\n          None\n\n        Those strings are part of the so-called standard\n        SDS attributes. Calling 'setdatastrs' is equivalent to setting\n        the following attributes, which correspond to the method\n        parameters, in order::\n\n          long_name, units, format, coordsys\n\n        C library equivalent: SDsetdatastrs"
  },
  {
    "code": "def get_local_ip_address(target):\n    ip_adr = ''\n    try:\n        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n        s.connect((target, 8000))\n        ip_adr = s.getsockname()[0]\n        s.close()\n    except:\n        pass\n    return ip_adr",
    "docstring": "Get the local ip address to access one specific target."
  },
  {
    "code": "def hideEvent(self, event):\n        super(CallTipWidget, self).hideEvent(event)\n        self._text_edit.cursorPositionChanged.disconnect(\n            self._cursor_position_changed)\n        self._text_edit.removeEventFilter(self)",
    "docstring": "Reimplemented to disconnect signal handlers and event filter."
  },
  {
    "code": "def importpath(path, error_text=None):\n    result = None\n    attrs = []\n    parts = path.split('.')\n    exception = None\n    while parts:\n        try:\n            result = __import__('.'.join(parts), {}, {}, [''])\n        except ImportError as e:\n            if exception is None:\n                exception = e\n            attrs = parts[-1:] + attrs\n            parts = parts[:-1]\n        else:\n            break\n    for attr in attrs:\n        try:\n            result = getattr(result, attr)\n        except (AttributeError, ValueError) as e:\n            if error_text is not None:\n                raise ImproperlyConfigured('Error: %s can import \"%s\"' % (\n                    error_text, path))\n            else:\n                raise exception\n    return result",
    "docstring": "Import value by specified ``path``.\n    Value can represent module, class, object, attribute or method.\n    If ``error_text`` is not None and import will\n    raise ImproperlyConfigured with user friendly text."
  },
  {
    "code": "def list_principals():\n    ret = {}\n    cmd = __execute_kadmin('list_principals')\n    if cmd['retcode'] != 0 or cmd['stderr']:\n        ret['comment'] = cmd['stderr'].splitlines()[-1]\n        ret['result'] = False\n        return ret\n    ret = {'principals': []}\n    for i in cmd['stdout'].splitlines()[1:]:\n        ret['principals'].append(i)\n    return ret",
    "docstring": "Get all principals\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'kde.example.com' kerberos.list_principals"
  },
  {
    "code": "def parse(self, **global_args):\n        if self.build_file not in ParseContext._parsed:\n            butcher_context = {}\n            for str_to_exec in self._strs_to_exec:\n                ast = compile(str_to_exec, '<string>', 'exec')\n                exec_function(ast, butcher_context)\n            with ParseContext.activate(self):\n                startdir = os.path.abspath(os.curdir)\n                try:\n                    os.chdir(self.build_file.path_on_disk)\n                    if self.build_file not in ParseContext._parsed:\n                        ParseContext._parsed.add(self.build_file)\n                        eval_globals = copy.copy(butcher_context)\n                        eval_globals.update(\n                            {'ROOT_DIR': self.build_file.path_on_disk,\n                             '__file__': 'bogus please fix this'})\n                        eval_globals.update(global_args)\n                        exec_function(self.build_file.code, eval_globals)\n                finally:\n                    os.chdir(startdir)",
    "docstring": "Entry point to parsing a BUILD file.\n\n        Args:\n          **global_args: Variables to include in the parsing environment."
  },
  {
    "code": "def set_type(self,type):\n    self.add_var_opt('type',str(type))\n    self.__type = str(type)\n    self.__set_output()",
    "docstring": "sets the frame type that we are querying"
  },
  {
    "code": "def logger(self):\n        if self._logger:\n            return self._logger\n        else:\n            log_builder = p_logging.ProsperLogger(\n                self.PROGNAME,\n                self.config.get_option('LOGGING', 'log_path'),\n                config_obj=self.config\n            )\n            if self.verbose:\n                log_builder.configure_debug_logger()\n            else:\n                id_string = '({platform}--{version})'.format(\n                    platform=platform.node(),\n                    version=self.VERSION\n                )\n                if self.config.get_option('LOGGING', 'discord_webhook'):\n                    log_builder.configure_discord_logger(\n                        custom_args=id_string\n                    )\n                if self.config.get_option('LOGGING', 'slack_webhook'):\n                    log_builder.configure_slack_logger(\n                        custom_args=id_string\n                    )\n                if self.config.get_option('LOGGING', 'hipchat_webhook'):\n                    log_builder.configure_hipchat_logger(\n                        custom_args=id_string\n                    )\n            self._logger = log_builder.get_logger()\n            return self._logger",
    "docstring": "uses \"global logger\" for logging"
  },
  {
    "code": "def dispatch(self, *args, **kwargs):\n        if not self.registration_allowed():\n            return HttpResponseRedirect(force_text(self.disallowed_url))\n        return super(RegistrationView, self).dispatch(*args, **kwargs)",
    "docstring": "Check that user signup is allowed before even bothering to\n        dispatch or do other processing."
  },
  {
    "code": "def _get_path_from_parent(self, parent):\n    if hasattr(self, 'get_path_from_parent'):\n        return self.get_path_from_parent(parent)\n    if self.model is parent:\n        return []\n    model = self.concrete_model\n    chain = model._meta.get_base_chain(parent) or []\n    chain.reverse()\n    chain.append(model)\n    path = []\n    for i, ancestor in enumerate(chain[:-1]):\n        child = chain[i + 1]\n        link = child._meta.get_ancestor_link(ancestor)\n        path.extend(link.get_reverse_path_info())\n    return path",
    "docstring": "Return a list of PathInfos containing the path from the parent\n    model to the current model, or an empty list if parent is not a\n    parent of the current model."
  },
  {
    "code": "def Prod(a, axis, keep_dims):\n    return np.prod(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),\n                   keepdims=keep_dims),",
    "docstring": "Prod reduction op."
  },
  {
    "code": "def normalizeGlyphTopMargin(value):\n    if not isinstance(value, (int, float)) and value is not None:\n        raise TypeError(\"Glyph top margin must be an :ref:`type-int-float`, \"\n                        \"not %s.\" % type(value).__name__)\n    return value",
    "docstring": "Normalizes glyph top margin.\n\n    * **value** must be a :ref:`type-int-float` or `None`.\n    * Returned value is the same type as the input value."
  },
  {
    "code": "def parse_remote(cls, filename):\n        blob_file = cls._URL_FORMAT.search(filename)\n        return cls._REMOTE_FILE(\"blob\",\n                                storage=blob_file.group(\"storage\"),\n                                container=blob_file.group(\"container\"),\n                                blob=blob_file.group(\"blob\"))",
    "docstring": "Parses a remote filename into blob information."
  },
  {
    "code": "def relocate(source, destination, move=False):\n    venv = api.VirtualEnvironment(source)\n    if not move:\n        venv.relocate(destination)\n        return None\n    venv.move(destination)\n    return None",
    "docstring": "Adjust the virtual environment settings and optional move it.\n\n    Args:\n        source (str): Path to the existing virtual environment.\n        destination (str): Desired path of the virtual environment.\n        move (bool): Whether or not to actually move the files. Default False."
  },
  {
    "code": "def add_to_sources(self, action, doc_source):\n        mapping = self.sources.setdefault(action[\"_index\"], {}).setdefault(\n            action[\"_type\"], {}\n        )\n        mapping[action[\"_id\"]] = doc_source",
    "docstring": "Store sources locally"
  },
  {
    "code": "def override_build_kwarg(workflow, k, v, platform=None):\n    key = OrchestrateBuildPlugin.key\n    workspace = workflow.plugin_workspace.setdefault(key, {})\n    override_kwargs = workspace.setdefault(WORKSPACE_KEY_OVERRIDE_KWARGS, {})\n    override_kwargs.setdefault(platform, {})\n    override_kwargs[platform][k] = v",
    "docstring": "Override a build-kwarg for all worker builds"
  },
  {
    "code": "def fave(self, deviationid, folderid=\"\"):\n        if self.standard_grant_type is not \"authorization_code\":\n            raise DeviantartError(\"Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.\")\n        post_data = {}\n        post_data['deviationid'] = deviationid\n        if folderid:\n            post_data['folderid'] = folderid\n        response = self._req('/collections/fave', post_data = post_data)\n        return response",
    "docstring": "Add deviation to favourites\n\n        :param deviationid: Id of the Deviation to favourite\n        :param folderid: Optional UUID of the Collection folder to add the favourite into"
  },
  {
    "code": "def save_metadata(self, metadata):\n        if metadata in (None, {}):\n            return None\n        if SYSTEM_METADATA in metadata:\n            raise StoreException(\"Not allowed to store %r in metadata\" % SYSTEM_METADATA)\n        path = self.temporary_object_path(str(uuid.uuid4()))\n        with open(path, 'w') as fd:\n            try:\n                json.dump(metadata, fd, sort_keys=True, separators=(',', ':'))\n            except (TypeError, ValueError):\n                raise StoreException(\"Metadata is not serializable\")\n        metahash = digest_file(path)\n        self._move_to_store(path, metahash)\n        return metahash",
    "docstring": "Save metadata to the store."
  },
  {
    "code": "def values_for_column(self, column_name, limit=10000):\n        cols = {col.column_name: col for col in self.columns}\n        target_col = cols[column_name]\n        tp = self.get_template_processor()\n        qry = (\n            select([target_col.get_sqla_col()])\n            .select_from(self.get_from_clause(tp))\n            .distinct()\n        )\n        if limit:\n            qry = qry.limit(limit)\n        if self.fetch_values_predicate:\n            tp = self.get_template_processor()\n            qry = qry.where(tp.process_template(self.fetch_values_predicate))\n        engine = self.database.get_sqla_engine()\n        sql = '{}'.format(\n            qry.compile(engine, compile_kwargs={'literal_binds': True}),\n        )\n        sql = self.mutate_query_from_config(sql)\n        df = pd.read_sql_query(sql=sql, con=engine)\n        return [row[0] for row in df.to_records(index=False)]",
    "docstring": "Runs query against sqla to retrieve some\n        sample values for the given column."
  },
  {
    "code": "def setsockopt(self, *sockopts):\n        if type(sockopts[0]) in (list, tuple):\n            for sock_opt in sockopts[0]:\n                level, option, value = sock_opt\n                self.connection.sockopts.add((level, option, value))\n        else:\n            level, option, value = sockopts\n            self.connection.sockopts.add((level, option, value))",
    "docstring": "Add socket options to set"
  },
  {
    "code": "def replace_pattern(tokens, new_pattern):\n    for state in tokens.values():\n        for index, pattern in enumerate(state):\n            if isinstance(pattern, tuple) and pattern[1] == new_pattern[1]:\n                state[index] = new_pattern",
    "docstring": "Given a RegexLexer token dictionary 'tokens', replace all patterns that\n        match the token specified in 'new_pattern' with 'new_pattern'."
  },
  {
    "code": "def drawPolyline(self, points):\n        for i, p in enumerate(points):\n            if i == 0:\n                if not (self.lastPoint == Point(p)):\n                    self.draw_cont += \"%g %g m\\n\" % JM_TUPLE(Point(p) * self.ipctm)\n                    self.lastPoint = Point(p)\n            else:\n                self.draw_cont += \"%g %g l\\n\" % JM_TUPLE(Point(p) * self.ipctm)\n            self.updateRect(p)\n        self.lastPoint = Point(points[-1])\n        return self.lastPoint",
    "docstring": "Draw several connected line segments."
  },
  {
    "code": "def links(self, base_link, current_page) -> dict:\r\n        max_pages = self.max_pages - 1 if \\\r\n            self.max_pages > 0 else self.max_pages\r\n        base_link = '/%s' % (base_link.strip(\"/\"))\r\n        self_page = current_page\r\n        prev = current_page - 1 if current_page is not 0 else None\r\n        prev_link = '%s/page/%s/%s' % (base_link, prev, self.limit) if \\\r\n            prev is not None else None\r\n        next = current_page + 1 if current_page < max_pages else None\r\n        next_link = '%s/page/%s/%s' % (base_link, next, self.limit) if \\\r\n            next is not None else None\r\n        first = 0\r\n        last = max_pages\r\n        return {\r\n            'self': '%s/page/%s/%s' % (base_link, self_page, self.limit),\r\n            'prev': prev_link,\r\n            'next': next_link,\r\n            'first': '%s/page/%s/%s' % (base_link, first, self.limit),\r\n            'last': '%s/page/%s/%s' % (base_link, last, self.limit),\r\n        }",
    "docstring": "Return JSON paginate links"
  },
  {
    "code": "def close(self):\n        log.debug(\"Closing socket connection for %s:%d\" % (self.host, self.port))\n        if self._sock:\n            try:\n                self._sock.shutdown(socket.SHUT_RDWR)\n            except socket.error:\n                pass\n            self._sock.close()\n            self._sock = None\n        else:\n            log.debug(\"No socket found to close!\")",
    "docstring": "Shutdown and close the connection socket"
  },
  {
    "code": "def format_national_number_with_carrier_code(numobj, carrier_code):\n    country_code = numobj.country_code\n    nsn = national_significant_number(numobj)\n    if not _has_valid_country_calling_code(country_code):\n        return nsn\n    region_code = region_code_for_country_code(country_code)\n    metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code)\n    formatted_number = _format_nsn(nsn,\n                                   metadata,\n                                   PhoneNumberFormat.NATIONAL,\n                                   carrier_code)\n    formatted_number = _maybe_append_formatted_extension(numobj,\n                                                         metadata,\n                                                         PhoneNumberFormat.NATIONAL,\n                                                         formatted_number)\n    formatted_number = _prefix_number_with_country_calling_code(country_code,\n                                                                PhoneNumberFormat.NATIONAL,\n                                                                formatted_number)\n    return formatted_number",
    "docstring": "Format a number in national format for dialing using the specified carrier.\n\n    The carrier-code will always be used regardless of whether the phone\n    number already has a preferred domestic carrier code stored. If\n    carrier_code contains an empty string, returns the number in national\n    format without any carrier code.\n\n    Arguments:\n    numobj -- The phone number to be formatted\n    carrier_code -- The carrier selection code to be used\n\n    Returns the formatted phone number in national format for dialing using\n    the carrier as specified in the carrier_code."
  },
  {
    "code": "def add_key_path(key_proto, *path_elements):\n  for i in range(0, len(path_elements), 2):\n    pair = path_elements[i:i+2]\n    elem = key_proto.path.add()\n    elem.kind = pair[0]\n    if len(pair) == 1:\n      return\n    id_or_name = pair[1]\n    if isinstance(id_or_name, (int, long)):\n      elem.id = id_or_name\n    elif isinstance(id_or_name, basestring):\n      elem.name = id_or_name\n    else:\n      raise TypeError(\n          'Expected an integer id or string name as argument %d; '\n          'received %r (a %s).' % (i + 2, id_or_name, type(id_or_name)))\n  return key_proto",
    "docstring": "Add path elements to the given datastore.Key proto message.\n\n  Args:\n    key_proto: datastore.Key proto message.\n    *path_elements: list of ancestors to add to the key.\n        (kind1, id1/name1, ..., kindN, idN/nameN), the last 2 elements\n        represent the entity key, if no terminating id/name: they key\n        will be an incomplete key.\n\n  Raises:\n    TypeError: the given id or name has the wrong type.\n\n  Returns:\n    the same datastore.Key.\n\n  Usage:\n    >>> add_key_path(key_proto, 'Kind', 'name')  # no parent, with name\n    datastore.Key(...)\n    >>> add_key_path(key_proto, 'Kind2', 1)  # no parent, with id\n    datastore.Key(...)\n    >>> add_key_path(key_proto, 'Kind', 'name', 'Kind2', 1)  # parent, complete\n    datastore.Key(...)\n    >>> add_key_path(key_proto, 'Kind', 'name', 'Kind2')  # parent, incomplete\n    datastore.Key(...)"
  },
  {
    "code": "def publish(self):\n        \" Publish last changes.\"\n        response = self.put('/REST/Zone/%s' % (\n            self.zone, ), data={'publish': True})\n        return response.content['data']['serial']",
    "docstring": "Publish last changes."
  },
  {
    "code": "def addHost(self, name=None):\n        if name is None:\n            while True:\n                name = 'h' + str(self.__hnum)\n                self.__hnum += 1\n                if name not in self.__nxgraph:\n                    break\n        self.__addNode(name, Host)\n        return name",
    "docstring": "Add a new host node to the topology."
  },
  {
    "code": "def parse_instancepath(self, tup_tree):\n        self.check_node(tup_tree, 'INSTANCEPATH')\n        k = kids(tup_tree)\n        if len(k) != 2:\n            raise CIMXMLParseError(\n                _format(\"Element {0!A} has invalid number of child elements \"\n                        \"{1!A} (expecting two child elements \"\n                        \"(NAMESPACEPATH, INSTANCENAME))\", name(tup_tree), k),\n                conn_id=self.conn_id)\n        host, namespace = self.parse_namespacepath(k[0])\n        inst_path = self.parse_instancename(k[1])\n        inst_path.host = host\n        inst_path.namespace = namespace\n        return inst_path",
    "docstring": "Parse an INSTANCEPATH element and return the instance path it\n        represents as a CIMInstanceName object.\n\n          ::\n\n            <!ELEMENT INSTANCEPATH (NAMESPACEPATH, INSTANCENAME)>"
  },
  {
    "code": "def download(self, path, file):\n        resp = self._sendRequest(\"GET\", path)\n        if resp.status_code == 200:\n            with open(file, \"wb\") as f:\n                f.write(resp.content)\n        else:\n            raise YaDiskException(resp.status_code, resp.content)",
    "docstring": "Download remote file to disk."
  },
  {
    "code": "def bind(self, study, **kwargs):\n        if self.default is None:\n            raise ArcanaError(\n                \"Attempted to bind '{}' to {} but only acquired specs with \"\n                \"a default value should be bound to studies{})\".format(\n                    self.name, study))\n        if self._study is not None:\n            bound = self\n        else:\n            bound = copy(self)\n            bound._study = study\n            bound._default = bound.default.bind(study)\n        return bound",
    "docstring": "Returns a copy of the AcquiredSpec bound to the given study\n\n        Parameters\n        ----------\n        study : Study\n            A study to bind the fileset spec to (should happen in the\n            study __init__)"
  },
  {
    "code": "def parse_xml_file(self, fileobj, id_generator=None):\n        root = etree.parse(fileobj).getroot()\n        usage_id = self._usage_id_from_node(root, None, id_generator)\n        return usage_id",
    "docstring": "Parse an open XML file, returning a usage id."
  },
  {
    "code": "def from_api(cls, **kwargs):\n        vals = cls.get_non_empty_vals({\n            cls._to_snake_case(k): v for k, v in kwargs.items()\n        })\n        remove = []\n        for attr, val in vals.items():\n            try:\n                vals[attr] = cls._parse_property(attr, val)\n            except HelpScoutValidationException:\n                remove.append(attr)\n                logger.info(\n                    'Unexpected property received in API response',\n                    exc_info=True,\n                )\n        for attr in remove:\n            del vals[attr]\n        return cls(**cls.get_non_empty_vals(vals))",
    "docstring": "Create a new instance from API arguments.\n\n        This will switch camelCase keys into snake_case for instantiation.\n\n        It will also identify any ``Instance`` or ``List`` properties, and\n        instantiate the proper objects using the values. The end result being\n        a fully Objectified and Pythonified API response.\n\n        Returns:\n            BaseModel: Instantiated model using the API values."
  },
  {
    "code": "def discover_settings(conf_base=None):\n    settings = {\n        'zmq_prefix': '',\n        'libzmq_extension': False,\n        'no_libzmq_extension': False,\n        'skip_check_zmq': False,\n        'build_ext': {},\n        'bdist_egg': {},\n    }\n    if sys.platform.startswith('win'):\n        settings['have_sys_un_h'] = False\n    if conf_base:\n        merge(settings, load_config('config', conf_base))\n    merge(settings, get_cfg_args())\n    merge(settings, get_eargs())\n    return settings",
    "docstring": "Discover custom settings for ZMQ path"
  },
  {
    "code": "def detect_regions(bam_in, bed_file, out_dir, prefix):\n    bed_file = _reorder_columns(bed_file)\n    counts_reads_cmd = (\"coverageBed -s -counts -b {bam_in} \"\n                        \"-a {bed_file} | sort -k4,4 \"\n                        \"> {out_dir}/loci.cov\")\n    with utils.chdir(out_dir):\n        run(counts_reads_cmd.format(min_trimmed_read_len=min_trimmed_read_len, max_trimmed_read_len=max_trimmed_read_len, **locals()), \"Run counts_reads\")\n        loci_file = _fix_score_column(op.join(out_dir, \"loci.cov\"))\n        return loci_file",
    "docstring": "Detect regions using first CoRaL module"
  },
  {
    "code": "def assert_valid_input(cls, tag):\n        if not cls.is_tag(tag):\n            raise TypeError(\"Expected a BeautifulSoup 'Tag', but instead recieved type {}\".format(type(tag)))",
    "docstring": "Check if valid input tag or document."
  },
  {
    "code": "def _cast_to_type(self, value):\n        if not isinstance(value, dict):\n            self.fail('invalid', value=value)\n        return value",
    "docstring": "Raise error if the value is not a dict"
  },
  {
    "code": "def cleanup(output_root):\n    if os.path.exists(output_root):\n        if os.path.isdir(output_root):\n            rmtree(output_root)\n        else:\n            os.remove(output_root)",
    "docstring": "Remove any reST files which were generated by this extension"
  },
  {
    "code": "def _push_frontier(self,\n                       early_frontier: Dict[ops.Qid, int],\n                       late_frontier: Dict[ops.Qid, int],\n                       update_qubits: Iterable[ops.Qid] = None\n                       ) -> Tuple[int, int]:\n        if update_qubits is None:\n            update_qubits = set(early_frontier).difference(late_frontier)\n        n_new_moments = (max(early_frontier.get(q, 0) - late_frontier[q]\n                             for q in late_frontier)\n                         if late_frontier else 0)\n        if n_new_moments > 0:\n            insert_index = min(late_frontier.values())\n            self._moments[insert_index:insert_index] = (\n                [ops.Moment()] * n_new_moments)\n            for q in update_qubits:\n                if early_frontier.get(q, 0) > insert_index:\n                    early_frontier[q] += n_new_moments\n            return insert_index, n_new_moments\n        return (0, 0)",
    "docstring": "Inserts moments to separate two frontiers.\n\n        After insertion n_new moments, the following holds:\n           for q in late_frontier:\n               early_frontier[q] <= late_frontier[q] + n_new\n           for q in update_qubits:\n               early_frontier[q] the identifies the same moment as before\n                   (but whose index may have changed if this moment is after\n                   those inserted).\n\n        Args:\n            early_frontier: The earlier frontier. For qubits not in the later\n                frontier, this is updated to account for the newly inserted\n                moments.\n            late_frontier: The later frontier. This is not modified.\n            update_qubits: The qubits for which to update early_frontier to\n                account for the newly inserted moments.\n\n        Returns:\n            (index at which new moments were inserted, how many new moments\n            were inserted) if new moments were indeed inserted. (0, 0)\n            otherwise."
  },
  {
    "code": "def field_exists(self, well_x, well_y, field_x, field_y):\n        \"Check if field exists ScanFieldArray.\"\n        return self.field(well_x, well_y, field_x, field_y) != None",
    "docstring": "Check if field exists ScanFieldArray."
  },
  {
    "code": "def _get_candidates(self):\n        candidates = np.where(self.dpp_vector == 0)\n        return None if len(candidates[0]) == 0 else candidates[0]",
    "docstring": "Finds the pipelines that are not yet tried.\n\n        Returns:\n            np.array: Indices corresponding to columns in ``dpp_matrix`` that haven't been tried on\n                ``X``. ``None`` if all pipelines have been tried on X."
  },
  {
    "code": "async def send_frame(self, frame):\n        if not self.connection.connected:\n            await self.connect()\n            await self.update_version()\n            await set_utc(pyvlx=self)\n            await house_status_monitor_enable(pyvlx=self)\n        self.connection.write(frame)",
    "docstring": "Send frame to API via connection."
  },
  {
    "code": "def get_enrollment(self, id):\n        url = self._url('enrollments/{}'.format(id))\n        return self.client.get(url)",
    "docstring": "Retrieves an enrollment.\n        Useful to check its type and related metadata.\n\n        Args:\n           id (str): The id of the device account to update\n\n\n        See: https://auth0.com/docs/api/management/v2#!/Guardian/get_enrollments_by_id"
  },
  {
    "code": "def validate_request_certificate(headers, data):\n    if 'SignatureCertChainUrl' not in headers or \\\n       'Signature' not in headers:\n        log.error('invalid request headers')\n        return False\n    cert_url = headers['SignatureCertChainUrl']\n    sig = base64.b64decode(headers['Signature'])\n    cert = _get_certificate(cert_url)\n    if not cert:\n        return False\n    try:\n        crypto.verify(cert, sig, data, 'sha1')\n        return True\n    except:\n        log.error('invalid request signature')\n        return False",
    "docstring": "Ensure that the certificate and signature specified in the\n    request headers are truely from Amazon and correctly verify.\n\n    Returns True if certificate verification succeeds, False otherwise.\n\n    :param headers: Dictionary (or sufficiently dictionary-like) map of request\n        headers.\n    :param data: Raw POST data attached to this request."
  },
  {
    "code": "def handle_exception(self, exception):\n        can_redirect = getattr(exception, \"can_redirect\", True)\n        redirect_uri = getattr(self, \"redirect_uri\", None)\n        if can_redirect and redirect_uri:\n            return self.redirect_exception(exception)\n        else:\n            return self.render_exception(exception)",
    "docstring": "Handle a unspecified exception and return the correct method that should be used\n        for handling it.\n\n        If the exception has the `can_redirect` property set to False, it is\n        rendered to the browser.  Otherwise, it will be redirected to the location\n        provided in the `RedirectUri` object that is associated with the request."
  },
  {
    "code": "def __clean_and_tokenize(self, doc_list):\n        doc_list = filter(\n            lambda x: x is not None and len(x) <= GitSuggest.MAX_DESC_LEN,\n            doc_list,\n        )\n        cleaned_doc_list = list()\n        tokenizer = RegexpTokenizer(r\"[a-zA-Z]+\")\n        stopwords = self.__get_words_to_ignore()\n        dict_words = self.__get_words_to_consider()\n        for doc in doc_list:\n            lower = doc.lower()\n            tokens = tokenizer.tokenize(lower)\n            tokens = [tok for tok in tokens if tok in dict_words]\n            tokens = [tok for tok in tokens if tok not in stopwords]\n            tokens = [tok for tok in tokens if tok is not None]\n            cleaned_doc_list.append(tokens)\n        return cleaned_doc_list",
    "docstring": "Method to clean and tokenize the document list.\n\n        :param doc_list: Document list to clean and tokenize.\n        :return: Cleaned and tokenized document list."
  },
  {
    "code": "def cacheback(lifetime=None, fetch_on_miss=None, cache_alias=None,\n              job_class=None, task_options=None, **job_class_kwargs):\n    if job_class is None:\n        job_class = FunctionJob\n    job = job_class(lifetime=lifetime, fetch_on_miss=fetch_on_miss,\n                    cache_alias=cache_alias, task_options=task_options,\n                    **job_class_kwargs)\n    def _wrapper(fn):\n        @wraps(fn, assigned=available_attrs(fn))\n        def __wrapper(*args, **kwargs):\n            return job.get(fn, *args, **kwargs)\n        __wrapper.fn = fn\n        __wrapper.job = job\n        return __wrapper\n    return _wrapper",
    "docstring": "Decorate function to cache its return value.\n\n    :lifetime: How long to cache items for\n    :fetch_on_miss: Whether to perform a synchronous fetch when no cached\n                    result is found\n    :cache_alias: The Django cache alias to store the result into.\n    :job_class: The class to use for running the cache refresh job.  Defaults\n                using the FunctionJob.\n    :job_class_kwargs: Any extra kwargs to pass to job_class constructor.\n                       Useful with custom job_class implementations."
  },
  {
    "code": "def from_str(cls, s):\n        r\n        if '\\x1b[' in s:\n            try:\n                tokens_and_strings = parse(s)\n            except ValueError:\n                return FmtStr(Chunk(remove_ansi(s)))\n            else:\n                chunks = []\n                cur_fmt = {}\n                for x in tokens_and_strings:\n                    if isinstance(x, dict):\n                        cur_fmt.update(x)\n                    elif isinstance(x, (bytes, unicode)):\n                        atts = parse_args('', dict((k, v)\n                                          for k, v in cur_fmt.items()\n                                          if v is not None))\n                        chunks.append(Chunk(x, atts=atts))\n                    else:\n                        raise Exception(\"logic error\")\n                return FmtStr(*chunks)\n        else:\n            return FmtStr(Chunk(s))",
    "docstring": "r\"\"\"\n        Return a FmtStr representing input.\n\n        The str() of a FmtStr is guaranteed to produced the same FmtStr.\n        Other input with escape sequences may not be preserved.\n\n        >>> fmtstr(\"|\"+fmtstr(\"hey\", fg='red', bg='blue')+\"|\")\n        '|'+on_blue(red('hey'))+'|'\n        >>> fmtstr('|\\x1b[31m\\x1b[44mhey\\x1b[49m\\x1b[39m|')\n        '|'+on_blue(red('hey'))+'|'"
  },
  {
    "code": "def run(path, code=None, params=None, ignore=None, select=None, **meta):\n        complexity = params.get('complexity', 10)\n        no_assert = params.get('no_assert', False)\n        show_closures = params.get('show_closures', False)\n        visitor = ComplexityVisitor.from_code(code, no_assert=no_assert)\n        blocks = visitor.blocks\n        if show_closures:\n            blocks = add_inner_blocks(blocks)\n        return [\n            {'lnum': block.lineno, 'col': block.col_offset, 'type': 'R', 'number': 'R709',\n             'text': 'R701: %s is too complex %d' % (block.name, block.complexity)}\n            for block in visitor.blocks if block.complexity > complexity\n        ]",
    "docstring": "Check code with Radon.\n\n        :return list: List of errors."
  },
  {
    "code": "def _Pluralize(value, unused_context, args):\n    if len(args) == 0:\n        s, p = '', 's'\n    elif len(args) == 1:\n        s, p = '', args[0]\n    elif len(args) == 2:\n        s, p = args\n    else:\n        raise AssertionError\n    if value > 1:\n        return p\n    else:\n        return s",
    "docstring": "Formatter to pluralize words."
  },
  {
    "code": "def items(self):\n        result = [(key, self._mapping[key]) for key in list(self._queue)]\n        result.reverse()\n        return result",
    "docstring": "Return a list of items."
  },
  {
    "code": "def _domain_event_metadata_change_cb(conn, domain, mtype, nsuri, opaque):\n    _salt_send_domain_event(opaque, conn, domain, opaque['event'], {\n        'type': _get_libvirt_enum_string('VIR_DOMAIN_METADATA_', mtype),\n        'nsuri': nsuri\n    })",
    "docstring": "Domain metadata change events handler"
  },
  {
    "code": "def _create_cache_filename(self, source_file):\n        res = self._create_cache_key(source_file) + \".cache\"\n        return os.path.join(self.__dir, res)",
    "docstring": "return the cache file name for a header file.\n\n        :param source_file: Header file name\n        :type source_file: str\n        :rtype: str"
  },
  {
    "code": "def get_list_subtask_positions_objs(client, list_id):\n    params = {\n            'list_id' : int(list_id)\n            }\n    response = client.authenticated_request(client.api.Endpoints.SUBTASK_POSITIONS, params=params)\n    return response.json()",
    "docstring": "Gets all subtask positions objects for the tasks within a given list. This is a convenience method so you don't have to get all the list's tasks before getting subtasks, though I can't fathom how mass subtask reordering is useful.\n\n    Returns:\n    List of SubtaskPositionsObj-mapped objects representing the order of subtasks for the tasks within the given list"
  },
  {
    "code": "def build(cls: Type[T], data: Generic) -> T:\n        fields = fields_dict(cls)\n        kwargs: Dict[str, Any] = {}\n        for key, value in data.items():\n            if key in fields:\n                if isinstance(value, Mapping):\n                    t = fields[key].type\n                    if issubclass(t, Auto):\n                        value = t.build(value)\n                    else:\n                        value = Auto.generate(value, name=key.title())\n                kwargs[key] = value\n            else:\n                log.debug(f\"got unknown attribute {key} for {cls.__name__}\")\n        return cls(**kwargs)",
    "docstring": "Build objects from dictionaries, recursively."
  },
  {
    "code": "def castable(source, target):\n    op = source.op()\n    value = getattr(op, 'value', None)\n    return dt.castable(source.type(), target.type(), value=value)",
    "docstring": "Return whether source ir type is implicitly castable to target\n\n    Based on the underlying datatypes and the value in case of Literals"
  },
  {
    "code": "def standard_program_header(self, title, length, line=32768):\n        self.save_header(self.HEADER_TYPE_BASIC, title, length, param1=line, param2=length)",
    "docstring": "Generates a standard header block of PROGRAM type"
  },
  {
    "code": "def stopService(self):\n        super(_SiteScheduler, self).stopService()\n        if self.timer is not None:\n            self.timer.cancel()\n            self.timer = None",
    "docstring": "Stop calling persistent timed events."
  },
  {
    "code": "def get_addresses_on_both_chains(wallet_obj, used=None, zero_balance=None):\n    mpub = wallet_obj.serialize_b58(private=False)\n    wallet_name = get_blockcypher_walletname_from_mpub(\n            mpub=mpub,\n            subchain_indices=[0, 1],\n            )\n    wallet_addresses = get_wallet_addresses(\n            wallet_name=wallet_name,\n            api_key=BLOCKCYPHER_API_KEY,\n            is_hd_wallet=True,\n            used=used,\n            zero_balance=zero_balance,\n            coin_symbol=coin_symbol_from_mkey(mpub),\n            )\n    verbose_print('wallet_addresses:')\n    verbose_print(wallet_addresses)\n    if wallet_obj.private_key:\n        master_key = wallet_obj.serialize_b58(private=True)\n    else:\n        master_key = mpub\n    chains_address_paths_cleaned = []\n    for chain in wallet_addresses['chains']:\n        if chain['chain_addresses']:\n            chain_address_paths = verify_and_fill_address_paths_from_bip32key(\n                    address_paths=chain['chain_addresses'],\n                    master_key=master_key,\n                    network=guess_network_from_mkey(mpub),\n                    )\n            chain_address_paths_cleaned = {\n                    'index': chain['index'],\n                    'chain_addresses': chain_address_paths,\n                    }\n            chains_address_paths_cleaned.append(chain_address_paths_cleaned)\n    return chains_address_paths_cleaned",
    "docstring": "Get addresses across both subchains based on the filter criteria passed in\n\n    Returns a list of dicts of the following form:\n        [\n            {'address': '1abc123...', 'path': 'm/0/9', 'pubkeyhex': '0123456...'},\n            ...,\n        ]\n\n    Dicts may also contain WIF and privkeyhex if wallet_obj has private key"
  },
  {
    "code": "def folder_size(pth, ignore=None):\n    if not os.path.isdir(pth):\n        raise exc.FolderNotFound\n    ignore = coerce_to_list(ignore)\n    total = 0\n    for root, _, names in os.walk(pth):\n        paths = [os.path.realpath(os.path.join(root, nm)) for nm in names]\n        for pth in paths[::-1]:\n            if not os.path.exists(pth):\n                paths.remove(pth)\n            elif match_pattern(pth, ignore):\n                paths.remove(pth)\n        total += sum(os.stat(pth).st_size for pth in paths)\n    return total",
    "docstring": "Returns the total bytes for the specified path, optionally ignoring\n    any files which match the 'ignore' parameter. 'ignore' can either be\n    a single string pattern, or a list of such patterns."
  },
  {
    "code": "def save(self, obj, run_id):\n        id_code = self.generate_save_identifier(obj, run_id)\n        self.store.save(obj, id_code)",
    "docstring": "Save a workflow\n        obj - instance of a workflow to save\n        run_id - unique id to give the run"
  },
  {
    "code": "def _parse_mode(self, mode, allowed=None, single=False):\n        r\n        if type(mode) is str:\n            mode = [mode]\n        for item in mode:\n            if (allowed is not None) and (item not in allowed):\n                raise Exception('\\'mode\\' must be one of the following: ' +\n                                allowed.__str__())\n        [mode.remove(L) for L in mode if mode.count(L) > 1]\n        if single:\n            if len(mode) > 1:\n                raise Exception('Multiple modes received when only one mode ' +\n                                'allowed')\n            else:\n                mode = mode[0]\n        return mode",
    "docstring": "r\"\"\"\n        This private method is for checking the \\'mode\\' used in the calling\n        method.\n\n        Parameters\n        ----------\n        mode : string or list of strings\n            The mode(s) to be parsed\n\n        allowed : list of strings\n            A list containing the allowed modes.  This list is defined by the\n            calling method.  If any of the received modes are not in the\n            allowed list an exception is raised.\n\n        single : boolean (default is False)\n            Indicates if only a single mode is allowed.  If this argument is\n            True than a string is returned rather than a list of strings, which\n            makes it easier to work with in the caller method.\n\n        Returns\n        -------\n        A list containing the received modes as strings, checked to ensure they\n        are all within the allowed set (if provoided).  Also, if the ``single``\n        argument was True, then a string is returned."
  },
  {
    "code": "def merge_rects(rect1, rect2):\n    r = pygame.Rect(rect1)\n    t = pygame.Rect(rect2)\n    right = max(r.right, t.right)\n    bot = max(r.bottom, t.bottom)\n    x = min(t.x, r.x)\n    y = min(t.y, r.y)\n    return pygame.Rect(x, y, right - x, bot - y)",
    "docstring": "Return the smallest rect containning two rects"
  },
  {
    "code": "def get_containers(self, include_only=[]):\n        locations = self.get_locations() \n        if len(locations) == 0:\n            raise ValueError(\"No locations for containers exist in Cheminventory\")\n        final_locations = []\n        if include_only:\n            for location in locations:\n                check = location in include_only or location.group in include_only\n                if check:\n                    final_locations.append(location)\n            if len(final_locations)==0: raise ValueError(f\"Location(s) or group(s) {include_only} is/are not in the database.\")\n        else:\n            final_locations = locations\n        containers = []\n        for location in final_locations:\n            containers += self._get_location_containers(location.inventory_id)\n        return containers",
    "docstring": "Download all the containers owned by a group\n\n        Arguments\n        ---------\n        include_only: List containg `Group` or `Location` objects\n            Search only over a list of groups or locations"
  },
  {
    "code": "def _expand_logical_shortcuts(cls, schema):\n        def is_of_rule(x):\n            return isinstance(x, _str_type) and \\\n                x.startswith(('allof_', 'anyof_', 'noneof_', 'oneof_'))\n        for field in schema:\n            for of_rule in (x for x in schema[field] if is_of_rule(x)):\n                operator, rule = of_rule.split('_')\n                schema[field].update({operator: []})\n                for value in schema[field][of_rule]:\n                    schema[field][operator].append({rule: value})\n                del schema[field][of_rule]\n        return schema",
    "docstring": "Expand agglutinated rules in a definition-schema.\n\n        :param schema: The schema-definition to expand.\n        :return: The expanded schema-definition."
  },
  {
    "code": "def new_config_event(self):\n        try:\n            self.on_set_config()\n        except Exception as ex:\n            self.logger.exception(ex)\n            raise StopIteration()",
    "docstring": "Called by the event loop when new config is available."
  },
  {
    "code": "def get_occupied_slots(instance):\n    return [slot for slot in get_all_slots(type(instance))\n            if hasattr(instance,slot)]",
    "docstring": "Return a list of slots for which values have been set.\n\n    (While a slot might be defined, if a value for that slot hasn't\n    been set, then it's an AttributeError to request the slot's\n    value.)"
  },
  {
    "code": "def group_add(self, name, restrict, repos, lces=[], assets=[], queries=[],\n                  policies=[], dashboards=[], credentials=[], description=''):\n        return self.raw_query('group', 'add', data={\n            'lces': [{'id': i} for i in lces],\n            'assets': [{'id': i} for i in assets],\n            'queries': [{'id': i} for i in queries],\n            'policies': [{'id': i} for i in policies],\n            'dashboardTabs': [{'id': i} for i in dashboards],\n            'credentials': [{'id': i} for i in credentials],\n            'repositories': [{'id': i} for i in repos],\n            'definingAssets': [{'id': i} for i in restrict],\n            'name': name,\n            'description': description,\n            'users': [],\n            'context': ''\n        })",
    "docstring": "group_add name, restrict, repos"
  },
  {
    "code": "def inlink_file(self, filepath):\n        if not os.path.exists(filepath):\n            logger.debug(\"Creating symbolic link to not existent file %s\" % filepath)\n        root, abiext = abi_splitext(filepath)\n        infile = \"in_\" + abiext\n        infile = self.indir.path_in(infile)\n        self.history.info(\"Linking path %s --> %s\" % (filepath, infile))\n        if not os.path.exists(infile):\n            os.symlink(filepath, infile)\n        else:\n            if os.path.realpath(infile) != filepath:\n                raise self.Error(\"infile %s does not point to filepath %s\" % (infile, filepath))",
    "docstring": "Create a symbolic link to the specified file in the\n        directory containing the input files of the task."
  },
  {
    "code": "def filter(cls, filters, iterable):\n    if isinstance(filters, Filter):\n      filters = [filters]\n    for filter in filters:\n      iterable = filter.generator(iterable)\n    return iterable",
    "docstring": "Returns the elements in `iterable` that pass given `filters`"
  },
  {
    "code": "def moveaxis(tensor, source, destination):\n    try:\n        source = np.core.numeric.normalize_axis_tuple(source, tensor.ndim)\n    except IndexError:\n        raise ValueError('Source should verify 0 <= source < tensor.ndim'\n                         'Got %d' % source)\n    try:\n        destination = np.core.numeric.normalize_axis_tuple(destination, tensor.ndim)\n    except IndexError:\n        raise ValueError('Destination should verify 0 <= destination < tensor.ndim (%d).'\n                         % tensor.ndim, 'Got %d' % destination)\n    if len(source) != len(destination):\n        raise ValueError('`source` and `destination` arguments must have '\n                         'the same number of elements')\n    order = [n for n in range(tensor.ndim) if n not in source]\n    for dest, src in sorted(zip(destination, source)):\n        order.insert(dest, src)\n    return op.transpose(tensor, order)",
    "docstring": "Moves the `source` axis into the `destination` position\n    while leaving the other axes in their original order\n\n    Parameters\n    ----------\n    tensor : mx.nd.array\n        The array which axes should be reordered\n    source : int or sequence of int\n        Original position of the axes to move. Can be negative but must be unique.\n    destination : int or sequence of int\n        Destination position for each of the original axes. Can be negative but must be unique.\n\n    Returns\n    -------\n    result : mx.nd.array\n        Array with moved axes.\n\n    Examples\n    --------\n    >>> X = mx.nd.array([[1, 2, 3], [4, 5, 6]])\n    >>> mx.nd.moveaxis(X, 0, 1).shape\n    (3L, 2L)\n\n    >>> X = mx.nd.zeros((3, 4, 5))\n    >>> mx.nd.moveaxis(X, [0, 1], [-1, -2]).shape\n    (5, 4, 3)"
  },
  {
    "code": "def primary_transcript(entrystream, parenttype='gene', logstream=stderr):\n    for entry in entrystream:\n        if not isinstance(entry, tag.Feature):\n            yield entry\n            continue\n        for parent in tag.select.features(entry, parenttype, traverse=True):\n            if parent.num_children == 0:\n                continue\n            transcripts = defaultdict(list)\n            for child in parent.children:\n                if child.type in type_terms:\n                    transcripts[child.type].append(child)\n            if len(transcripts) == 0:\n                continue\n            ttypes = list(transcripts.keys())\n            ttype = _get_primary_type(ttypes, parent)\n            transcript_list = transcripts[ttype]\n            if ttype == 'mRNA':\n                _emplace_pmrna(transcript_list, parent, strict=True)\n            else:\n                _emplace_transcript(transcript_list, parent)\n        yield entry",
    "docstring": "Select a single transcript as a representative for each gene.\n\n    This function is a generalization of the `primary_mrna` function that\n    attempts, under certain conditions, to select a single transcript as a\n    representative for each gene. If a gene encodes multiple transcript types,\n    one of those types must be **mRNA** or the function will complain loudly\n    and fail.\n\n    For mRNAs, the primary transcript is selected according to translated\n    length. For all other transcript types, the length of the transcript\n    feature itself is used. I'd be eager to hear suggestions for alternative\n    selection criteria.\n\n    Like the `primary_mrna` function, this function **does not** return only\n    transcript features. It **does** modify gene features to ensure that each\n    has at most one transcript feature.\n\n    >>> reader = tag.GFF3Reader(tag.pkgdata('psyllid-mixed-gene.gff3.gz'))\n    >>> gene_filter = tag.select.features(reader, type='gene')\n    >>> trans_filter = tag.transcript.primary_transcript(gene_filter)\n    >>> for gene in trans_filter:\n    ...     assert gene.num_children == 1\n\n    In cases where the direct children of a gene feature have heterogenous\n    types, the `primary_mrna` function will only discard mRNA features. This\n    function, however, will discard all direct children of the gene that are\n    not the primary transcript, including non-transcript children. This is a\n    retty subtle distinction, and anecdotal experience suggests that cases in\n    which the distinction actually matters are extremely rare."
  },
  {
    "code": "def make_geojson(contents):\n    if isinstance(contents, six.string_types):\n        return contents\n    if hasattr(contents, '__geo_interface__'):\n        features = [_geo_to_feature(contents)]\n    else:\n        try:\n            feature_iter = iter(contents)\n        except TypeError:\n            raise ValueError('Unknown type for input')\n        features = []\n        for i, f in enumerate(feature_iter):\n            if not hasattr(f, '__geo_interface__'):\n                raise ValueError('Unknown type at index {0}'.format(i))\n            features.append(_geo_to_feature(f))\n    data = {'type': 'FeatureCollection', 'features': features}\n    return json.dumps(data)",
    "docstring": "Return a GeoJSON string from a variety of inputs.\n    See the documentation for make_url for the possible contents\n    input.\n\n    Returns\n    -------\n    GeoJSON string"
  },
  {
    "code": "async def send(self, message_type, message_content, timeout=None):\n        return await self._sender.send(\n            message_type, message_content, timeout=timeout)",
    "docstring": "Sends a message and returns a future for the response."
  },
  {
    "code": "def missing_datetimes(self, finite_datetimes):\n        return [d for d in finite_datetimes if not self._instantiate_task_cls(self.datetime_to_parameter(d)).complete()]",
    "docstring": "Override in subclasses to do bulk checks.\n\n        Returns a sorted list.\n\n        This is a conservative base implementation that brutally checks completeness, instance by instance.\n\n        Inadvisable as it may be slow."
  },
  {
    "code": "def add_view_no_menu(self, baseview, endpoint=None, static_folder=None):\n        baseview = self._check_and_init(baseview)\n        log.info(LOGMSG_INF_FAB_ADD_VIEW.format(baseview.__class__.__name__, \"\"))\n        if not self._view_exists(baseview):\n            baseview.appbuilder = self\n            self.baseviews.append(baseview)\n            self._process_inner_views()\n            if self.app:\n                self.register_blueprint(\n                    baseview, endpoint=endpoint, static_folder=static_folder\n                )\n                self._add_permission(baseview)\n        else:\n            log.warning(LOGMSG_WAR_FAB_VIEW_EXISTS.format(baseview.__class__.__name__))\n        return baseview",
    "docstring": "Add your views without creating a menu.\n\n        :param baseview:\n            A BaseView type class instantiated."
  },
  {
    "code": "def winrm_cmd(session, command, flags, **kwargs):\n    log.debug('Executing WinRM command: %s %s', command, flags)\n    session.protocol.transport.build_session()\n    r = session.run_cmd(command, flags)\n    return r.status_code",
    "docstring": "Wrapper for commands to be run against Windows boxes using WinRM."
  },
  {
    "code": "def view_running_services(self, package: str='') -> str:\n        output, _ = self._execute(\n            '-s', self.device_sn, 'shell', 'dumpsys', 'activity', 'services', package)\n        return output",
    "docstring": "View running services."
  },
  {
    "code": "def one(self, filetype, **kwargs):\n        expanded_files = self.expand(filetype, **kwargs)\n        isany = self.any(filetype, **kwargs)\n        return choice(expanded_files) if isany else None",
    "docstring": "Returns random one of the given type of file\n\n        Parameters\n        ----------\n        filetype : str\n            File type parameter.\n\n        as_url: bool\n            Boolean to return SAS urls\n\n        refine: str\n            Regular expression string to filter the list of files by\n            before random selection\n\n        Returns\n        -------\n        one : str\n            Random file selected from the expanded list of full paths on disk."
  },
  {
    "code": "def results(self):\n        self.out('cif', self.ctx.cif)\n        if 'group_cif' in self.inputs:\n            self.inputs.group_cif.add_nodes([self.ctx.cif])\n        if 'group_structure' in self.inputs:\n            try:\n                structure = self.ctx.structure\n            except AttributeError:\n                return self.ctx.exit_code\n            else:\n                self.inputs.group_structure.add_nodes([structure])\n                self.out('structure', structure)\n        self.report('workchain finished successfully')",
    "docstring": "If successfully created, add the cleaned `CifData` and `StructureData` as output nodes to the workchain.\n\n        The filter and select calculations were successful, so we return the cleaned CifData node. If the `group_cif`\n        was defined in the inputs, the node is added to it. If the structure should have been parsed, verify that it\n        is was put in the context by the `parse_cif_structure` step and add it to the group and outputs, otherwise\n        return the finish status that should correspond to the exit code of the `primitive_structure_from_cif` function."
  },
  {
    "code": "def convert_geojson_to_shapefile(geojson_path):\n    layer = QgsVectorLayer(geojson_path, 'vector layer', 'ogr')\n    if not layer.isValid():\n        return False\n    shapefile_path = os.path.splitext(geojson_path)[0] + '.shp'\n    QgsVectorFileWriter.writeAsVectorFormat(\n        layer,\n        shapefile_path,\n        'utf-8',\n        layer.crs(),\n        'ESRI Shapefile')\n    if os.path.exists(shapefile_path):\n        return True\n    return False",
    "docstring": "Convert geojson file to shapefile.\n\n    It will create a necessary file next to the geojson file. It will not\n    affect another files (e.g. .xml, .qml, etc).\n\n    :param geojson_path: The path to geojson file.\n    :type geojson_path: basestring\n\n    :returns: True if shapefile layer created, False otherwise.\n    :rtype: bool"
  },
  {
    "code": "def add_tab(self, tab, title='', icon=None):\n        if icon:\n            tab._icon = icon\n        if not hasattr(tab, 'clones'):\n            tab.clones = []\n        if not hasattr(tab, 'original'):\n            tab.original = None\n        if icon:\n            self.main_tab_widget.addTab(tab, icon, title)\n        else:\n            self.main_tab_widget.addTab(tab, title)\n        self.main_tab_widget.setCurrentIndex(\n            self.main_tab_widget.indexOf(tab))\n        self.main_tab_widget.show()\n        tab._uuid = self._uuid\n        try:\n            scroll_bar = tab.horizontalScrollBar()\n        except AttributeError:\n            pass\n        else:\n            scroll_bar.setValue(0)\n        tab.setFocus()\n        tab._original_tab_widget = self\n        self._tabs.append(tab)\n        self._on_focus_changed(None, tab)",
    "docstring": "Adds a tab to main tab widget.\n\n        :param tab: Widget to add as a new tab of the main tab widget.\n        :param title: Tab title\n        :param icon: Tab icon"
  },
  {
    "code": "def parse_source(info):\n    if \"extractor_key\" in info:\n        source = info[\"extractor_key\"]\n        lower_source = source.lower()\n        for key in SOURCE_TO_NAME:\n            lower_key = key.lower()\n            if lower_source == lower_key:\n                source = SOURCE_TO_NAME[lower_key]\n        if source != \"Generic\":\n            return source\n    if \"url\" in info and info[\"url\"] is not None:\n        p = urlparse(info[\"url\"])\n        if p and p.netloc:\n            return p.netloc\n    return \"Unknown\"",
    "docstring": "Parses the source info from an info dict generated by youtube-dl\n\n    Args:\n        info (dict): The info dict to parse\n\n    Returns:\n        source (str): The source of this song"
  },
  {
    "code": "def historical_pandas_yahoo(symbol, source='yahoo', start=None, end=None):\n    return DataReader(symbol, source, start=start, end=end)",
    "docstring": "Fetch from yahoo! finance historical quotes"
  },
  {
    "code": "def _build_web_client(cls, session: AppSession):\n        cookie_jar = cls._build_cookie_jar(session)\n        http_client = cls._build_http_client(session)\n        redirect_factory = functools.partial(\n            session.factory.class_map['RedirectTracker'],\n            max_redirects=session.args.max_redirect\n        )\n        return session.factory.new(\n            'WebClient',\n            http_client,\n            redirect_tracker_factory=redirect_factory,\n            cookie_jar=cookie_jar,\n            request_factory=cls._build_request_factory(session),\n        )",
    "docstring": "Build Web Client."
  },
  {
    "code": "def expect_equal(first, second, msg=None, extras=None):\n    try:\n        asserts.assert_equal(first, second, msg, extras)\n    except signals.TestSignal as e:\n        logging.exception('Expected %s equals to %s, but they are not.', first,\n                          second)\n        recorder.add_error(e)",
    "docstring": "Expects the equality of objects, otherwise fail the test.\n\n    If the expectation is not met, the test is marked as fail after its\n    execution finishes.\n\n    Error message is \"first != second\" by default. Additional explanation can\n    be supplied in the message.\n\n    Args:\n        first: The first object to compare.\n        second: The second object to compare.\n        msg: A string that adds additional info about the failure.\n        extras: An optional field for extra information to be included in test\n            result."
  },
  {
    "code": "def find_field(browser, field, value):\n    return find_field_by_id(browser, field, value) + \\\n        find_field_by_name(browser, field, value) + \\\n        find_field_by_label(browser, field, value)",
    "docstring": "Locate an input field of a given value\n\n    This first looks for the value as the id of the element, then\n    the name of the element, then a label for the element."
  },
  {
    "code": "def scipy_psd(x, f_sample=1.0, nr_segments=4):\n    f_axis, psd_of_x = scipy.signal.welch(x, f_sample, nperseg=len(x)/nr_segments)\n    return f_axis, psd_of_x",
    "docstring": "PSD routine from scipy\n        we can compare our own numpy result against this one"
  },
  {
    "code": "def glob_config(pattern, *search_dirs):\n    patterns = config_search_paths(pattern, *search_dirs, check_exists=False)\n    for pattern in patterns:\n        for path in glob.iglob(pattern):\n            yield path",
    "docstring": "Return glob results for all possible configuration locations.\n\n    Note: This method does not check the configuration \"base\" directory if the pattern includes a subdirectory.\n          This is done for performance since this is usually used to find *all* configs for a certain component."
  },
  {
    "code": "def show(self, msg, indent=0, style=\"\", **kwargs):\n        if self.enable_verbose:\n            new_msg = self.MessageTemplate.with_style.format(\n                indent=self.tab * indent,\n                style=style,\n                msg=msg,\n            )\n            print(new_msg, **kwargs)",
    "docstring": "Print message to console, indent format may apply."
  },
  {
    "code": "def call(self, task, decorators=None):\n        if decorators is None:\n            decorators = []\n        task = self.apply_task_decorators(task, decorators)\n        data = task.get_data()\n        name = task.get_name()\n        result = self._inner_call(name, data)\n        task_result = RawTaskResult(task, result)\n        return self.apply_task_result_decorators(task_result, decorators)",
    "docstring": "Call given task on service layer.\n\n        :param task: task to be called. task will be decorated with\n            TaskDecorator's contained in 'decorators' list\n        :type task: instance of Task class\n        :param decorators: list of TaskDecorator's / TaskResultDecorator's\n            inherited classes\n        :type decorators: list\n\n        :return task_result: result of task call decorated with TaskResultDecorator's\n            contained in 'decorators' list\n        :rtype TaskResult instance"
  },
  {
    "code": "def warning(message, css_path=CSS_PATH):\n    env = Environment()\n    env.loader = FileSystemLoader(osp.join(CONFDIR_PATH, 'templates'))\n    warning = env.get_template(\"warning.html\")\n    return warning.render(css_path=css_path, text=message)",
    "docstring": "Print a warning message on the rich text view"
  },
  {
    "code": "def save(self, force=False):\n        if (not self._success) and (not force):\n            raise ConfigError((\n                'The config file appears to be corrupted:\\n\\n'\n                '    {fname}\\n\\n'\n                'Before attempting to save the configuration, please either '\n                'fix the config file manually, or overwrite it with a blank '\n                'configuration as follows:\\n\\n'\n                '    from dustmaps.config import config\\n'\n                '    config.reset()\\n\\n'\n                ).format(fname=self.fname))\n        with open(self.fname, 'w') as f:\n            json.dump(self._options, f, indent=2)",
    "docstring": "Saves the configuration to a JSON, in the standard config location.\n\n        Args:\n            force (Optional[:obj:`bool`]): Continue writing, even if the original\n                config file was not loaded properly. This is dangerous, because\n                it could cause the previous configuration options to be lost.\n                Defaults to :obj:`False`.\n\n        Raises:\n            :obj:`ConfigError`: if the configuration file was not successfully\n                                loaded on initialization of the class, and\n                                :obj:`force` is :obj:`False`."
  },
  {
    "code": "def set_categories(self):\n        self.categories = []\n        temp_categories = self.soup.findAll('category')\n        for category in temp_categories:\n            category_text = category.string\n            self.categories.append(category_text)",
    "docstring": "Parses and set feed categories"
  },
  {
    "code": "def list_parameter_ranges(self, parameter, start=None, stop=None,\n                              min_gap=None, max_gap=None,\n                              parameter_cache='realtime'):\n        path = '/archive/{}/parameters{}/ranges'.format(\n            self._instance, parameter)\n        params = {}\n        if start is not None:\n            params['start'] = to_isostring(start)\n        if stop is not None:\n            params['stop'] = to_isostring(stop)\n        if min_gap is not None:\n            params['minGap'] = int(min_gap * 1000)\n        if max_gap is not None:\n            params['maxGap'] = int(max_gap * 1000)\n        if parameter_cache:\n            params['processor'] = parameter_cache\n        else:\n            params['norealtime'] = True\n        response = self._client.get_proto(path=path, params=params)\n        message = pvalue_pb2.Ranges()\n        message.ParseFromString(response.content)\n        ranges = getattr(message, 'range')\n        return [ParameterRange(r) for r in ranges]",
    "docstring": "Returns parameter ranges between the specified start and stop time.\n\n        Each range indicates an interval during which this parameter's\n        value was uninterrupted and unchanged.\n\n        Ranges are a good fit for retrieving the value of a parameter\n        that does not change frequently. For example an on/off indicator\n        or some operational status. Querying ranges will then induce\n        much less overhead than manually processing the output of\n        :meth:`list_parameter_values` would.\n\n        The maximum number of returned ranges is limited to 500.\n\n        :param str parameter: Either a fully-qualified XTCE name or an alias in the\n                              format ``NAMESPACE/NAME``.\n        :param ~datetime.datetime start: Minimum generation time of the considered\n                                         values (inclusive)\n        :param ~datetime.datetime stop: Maximum generation time of the considered\n                                        values (exclusive)\n        :param float min_gap: Time in seconds. Any gap (detected based on parameter\n                              expiration) smaller than this will be ignored.\n                              However if the parameter changes value, the ranges\n                              will still be split.\n        :param float max_gap: Time in seconds. If the distance between two\n                              subsequent parameter values is bigger than\n                              this value (but smaller than the parameter\n                              expiration), then an artificial gap is\n                              created. This also applies if there is no\n                              expiration defined for the parameter.\n        :param str parameter_cache: Specify the name of the processor who's\n                                    parameter cache is merged with already\n                                    archived values. To disable results from\n                                    the parameter cache, set this to ``None``.\n        :rtype: .ParameterRange[]"
  },
  {
    "code": "def could_collide_hor(self, vpos, adsb_pkt):\n        margin = self.asterix_settings.filter_dist_xy\n        timeout = self.asterix_settings.filter_time\n        alat = adsb_pkt.lat * 1.0e-7\n        alon = adsb_pkt.lon * 1.0e-7\n        avel = adsb_pkt.hor_velocity * 0.01\n        vvel = sqrt(vpos.vx**2 + vpos.vy**2)\n        dist = mp_util.gps_distance(vpos.lat, vpos.lon, alat, alon)\n        dist -= avel * timeout\n        dist -= vvel * timeout\n        if dist <= margin:\n            return True\n        return False",
    "docstring": "return true if vehicle could come within filter_dist_xy meters of adsb vehicle in timeout seconds"
  },
  {
    "code": "def sort(self,\n             key,\n             by=None,\n             external=None,\n             offset=0,\n             limit=None,\n             order=None,\n             alpha=False,\n             store_as=None):\n        if order and order not in [b'ASC', b'DESC', 'ASC', 'DESC']:\n            raise ValueError('invalid sort order \"{}\"'.format(order))\n        command = [b'SORT', key]\n        if by:\n            command += [b'BY', by]\n        if external and isinstance(external, list):\n            for entry in external:\n                command += [b'GET', entry]\n        elif external:\n            command += [b'GET', external]\n        if limit:\n            command += [\n                b'LIMIT',\n                ascii(offset).encode('utf-8'),\n                ascii(limit).encode('utf-8')\n            ]\n        if order:\n            command.append(order)\n        if alpha is True:\n            command.append(b'ALPHA')\n        if store_as:\n            command += [b'STORE', store_as]\n        return self._execute(command)",
    "docstring": "Returns or stores the elements contained in the list, set or sorted\n        set at key. By default, sorting is numeric and elements are compared by\n        their value interpreted as double precision floating point number.\n\n        The ``external`` parameter is used to specify the\n        `GET <http://redis.io/commands/sort#retrieving-external-keys>_`\n        parameter for retrieving external keys. It can be a single string\n        or a list of strings.\n\n        .. note::\n\n           **Time complexity**: ``O(N+M*log(M))`` where ``N`` is the number of\n           elements in the list or set to sort, and ``M`` the number of\n           returned elements. When the elements are not sorted, complexity is\n           currently ``O(N)`` as there is a copy step that will be avoided in\n           next releases.\n\n        :param key: The key to get the refcount for\n        :type key: :class:`str`, :class:`bytes`\n\n        :param by: The optional pattern for external sorting keys\n        :type by: :class:`str`, :class:`bytes`\n        :param external: Pattern or list of patterns to return external keys\n        :type external: :class:`str`, :class:`bytes`, list\n        :param int offset: The starting offset when using limit\n        :param int limit: The number of elements to return\n        :param order: The sort order - one of ``ASC`` or ``DESC``\n        :type order: :class:`str`, :class:`bytes`\n        :param bool alpha: Sort the results lexicographically\n        :param store_as: When specified, the key to store the results as\n        :type store_as: :class:`str`, :class:`bytes`, None\n        :rtype: list|int\n        :raises: :exc:`~tredis.exceptions.RedisError`\n        :raises: :exc:`ValueError`"
  },
  {
    "code": "def _expect_extra(expected, present, exc_unexpected, exc_missing, exc_args):\n    if present:\n        if not expected:\n            raise exc_unexpected(*exc_args)\n    elif expected and expected is not Argument.ignore:\n        raise exc_missing(*exc_args)",
    "docstring": "Checks for the presence of an extra to the argument list. Raises expections\n    if this is unexpected or if it is missing and expected."
  },
  {
    "code": "def is_selected(self, model):\n        if model is None:\n            return len(self._selected) == 0\n        return model in self._selected",
    "docstring": "Checks whether the given model is selected\n\n        :param model:\n        :return: True if the model is within the selection, False else\n        :rtype: bool"
  },
  {
    "code": "def _locate_point(nodes, point):\n    r\n    candidates = [(0.0, 1.0, nodes)]\n    for _ in six.moves.xrange(_MAX_LOCATE_SUBDIVISIONS + 1):\n        next_candidates = []\n        for start, end, candidate in candidates:\n            if _helpers.contains_nd(candidate, point.ravel(order=\"F\")):\n                midpoint = 0.5 * (start + end)\n                left, right = subdivide_nodes(candidate)\n                next_candidates.extend(\n                    ((start, midpoint, left), (midpoint, end, right))\n                )\n        candidates = next_candidates\n    if not candidates:\n        return None\n    params = [(start, end) for start, end, _ in candidates]\n    if np.std(params) > _LOCATE_STD_CAP:\n        raise ValueError(\"Parameters not close enough to one another\", params)\n    s_approx = np.mean(params)\n    s_approx = newton_refine(nodes, point, s_approx)\n    if s_approx < 0.0:\n        return 0.0\n    elif s_approx > 1.0:\n        return 1.0\n    else:\n        return s_approx",
    "docstring": "r\"\"\"Locate a point on a curve.\n\n    Does so by recursively subdividing the curve and rejecting\n    sub-curves with bounding boxes that don't contain the point.\n    After the sub-curves are sufficiently small, uses Newton's\n    method to zoom in on the parameter value.\n\n    .. note::\n\n       This assumes, but does not check, that ``point`` is ``D x 1``,\n       where ``D`` is the dimension that ``curve`` is in.\n\n    .. note::\n\n       There is also a Fortran implementation of this function, which\n       will be used if it can be built.\n\n    Args:\n        nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve.\n        point (numpy.ndarray): The point to locate.\n\n    Returns:\n        Optional[float]: The parameter value (:math:`s`) corresponding\n        to ``point`` or :data:`None` if the point is not on the ``curve``.\n\n    Raises:\n        ValueError: If the standard deviation of the remaining start / end\n            parameters among the subdivided intervals exceeds a given\n            threshold (e.g. :math:`2^{-20}`)."
  },
  {
    "code": "def _calc_order(self, order):\n        if order is not None and order != '':\n            self.order = order.upper()\n        else:\n            shape = self.shape\n            if len(shape) <= 2:\n                self.order = 'M'\n            else:\n                depth = shape[-1]\n                if depth == 1:\n                    self.order = 'M'\n                elif depth == 2:\n                    self.order = 'AM'\n                elif depth == 3:\n                    self.order = 'RGB'\n                elif depth == 4:\n                    self.order = 'RGBA'",
    "docstring": "Called to set the order of a multi-channel image.\n        The order should be determined by the loader, but this will\n        make a best guess if passed `order` is `None`."
  },
  {
    "code": "def encode(self, boundary):\n        if self.value is None:\n            value = self.fileobj.read()\n        else:\n            value = self.value\n        if re.search(\"^--%s$\" % re.escape(boundary), value, re.M):\n            raise ValueError(\"boundary found in encoded string\")\n        return \"%s%s\\r\\n\" % (self.encode_hdr(boundary), value)",
    "docstring": "Returns the string encoding of this parameter"
  },
  {
    "code": "def _writeCloseFrame(self, reason=DISCONNECT.GO_AWAY):\n        self.transport.writeClose(reason)\n        self.transport.loseConnection()\n        self.transport = None",
    "docstring": "Write a close frame with the given reason and schedule this\n        connection close."
  },
  {
    "code": "def check_paths(self, paths, update=None):\n        exclude = [] if not self.exclude else self.exclude \\\n            if isinstance(self.exclude, list) else [self.exclude]\n        for pathname, path in paths.items():\n            if update and pathname.upper() not in exclude:\n                os.environ[pathname.upper()] = os.path.normpath(path)\n            elif pathname.upper() not in os.environ:\n                os.environ[pathname.upper()] = os.path.normpath(path)",
    "docstring": "Check if the path is in the os environ, and if not add it\n\n        Paramters:\n            paths (OrderedDict):\n                An ordered dict containing all of the paths from the\n                a given section, as key:val = name:path\n            update (bool):\n                If True, overwrites existing tree environment variables in your\n                local environment.  Default is False."
  },
  {
    "code": "def benchmark(store, n=10000):\n    x = UpdatableItem(store=store, count=0)\n    for _ in xrange(n):\n        x.count += 1",
    "docstring": "Increments an integer count n times."
  },
  {
    "code": "def fullData(master):\n    builders = []\n    for b in master.config.builders:\n        steps = []\n        for step in b.factory.steps:\n            steps.append(getName(step))\n        builders.append(steps)\n    return {'builders': builders}",
    "docstring": "Send the actual configuration of the builders, how the steps are agenced.\n        Note that full data will never send actual detail of what command is run, name of servers, etc."
  },
  {
    "code": "def read(cls, *criteria, **kwargs):\n        if not kwargs.get('removed', False):\n            return cls.query.filter(cls.time_removed == 0, *criteria)\n        return cls.query.filter(*criteria)",
    "docstring": "filter query helper that handles soft delete logic. If your query conditions do not require expressions,\n        consider using read_by.\n\n        :param criteria: where clause conditions\n        :param kwargs: set removed=True if you want soft-deleted rows\n        :return: row object generator"
  },
  {
    "code": "def function_call_action(self, text, loc, fun):\r\n        exshared.setpos(loc, text)\r\n        if DEBUG > 0:\r\n            print(\"FUN_CALL:\",fun)\r\n            if DEBUG == 2: self.symtab.display()\r\n            if DEBUG > 2: return\r\n        if len(self.function_arguments) != self.symtab.get_attribute(self.function_call_index):\r\n            raise SemanticException(\"Wrong number of arguments for function '%s'\" % fun.name)\r\n        self.function_arguments.reverse()\r\n        self.codegen.function_call(self.function_call_index, self.function_arguments)\r\n        self.codegen.restore_used_registers()\r\n        return_type = self.symtab.get_type(self.function_call_index)\r\n        self.function_call_index = self.function_call_stack.pop()\r\n        self.function_arguments = self.function_arguments_stack.pop()\r\n        register = self.codegen.take_register(return_type)\r\n        self.codegen.move(self.codegen.take_function_register(return_type), register)\r\n        return register",
    "docstring": "Code executed after recognising the whole function call"
  },
  {
    "code": "def get_response(self, results):\n        if results is None:\n            return None\n        for result in itertools.chain.from_iterable(results):\n            if isinstance(result, BaseResponse):\n                return result",
    "docstring": "Get response object from results.\n\n        :param results: list\n        :return:"
  },
  {
    "code": "def close(self, terminate=True, kill=False):\n        if not self.closed:\n            if self.child_fd is not None:\n                os.close(self.child_fd)\n                self.child_fd = None\n            if self.child_fde is not None:\n                os.close(self.child_fde)\n                self.child_fde = None\n            time.sleep(0.1)\n            if terminate:\n                if not self.terminate(kill):\n                    raise TerminalException('Failed to terminate child process.')\n            self.closed = True",
    "docstring": "Close the communication with the terminal's child.\n        If ``terminate`` is ``True`` then additionally try to terminate the\n        terminal, and if ``kill`` is also ``True``, kill the terminal if\n        terminating it was not enough."
  },
  {
    "code": "def load_data_file(\n    file_path,\n    file_path_is_relative=False,\n    comment_string=DATA_FILE_COMMENT,\n    field_separator=DATA_FILE_FIELD_SEPARATOR,\n    line_format=None\n):\n    raw_tuples = []\n    if file_path_is_relative:\n        file_path = os.path.join(os.path.dirname(__file__), file_path)\n    with io.open(file_path, \"r\", encoding=\"utf-8\") as f:\n        for line in f:\n            line = line.strip()\n            if (len(line) > 0) and (not line.startswith(comment_string)):\n                raw_list = line.split(field_separator)\n                if len(raw_list) != len(line_format):\n                    raise ValueError(\"Data file '%s' contains a bad line: '%s'\" % (file_path, line))\n                raw_tuples.append(tuple(raw_list))\n    if (line_format is None) or (len(line_format) < 1):\n        return raw_tuples\n    return [convert_raw_tuple(t, line_format) for t in raw_tuples]",
    "docstring": "Load a data file, with one record per line and\n    fields separated by ``field_separator``,\n    returning a list of tuples.\n\n    It ignores lines starting with ``comment_string`` or empty lines.\n\n    If ``values_per_line`` is not ``None``,\n    check that each line (tuple)\n    has the prescribed number of values.\n\n    :param str file_path: path of the data file to load\n    :param bool file_path_is_relative: if ``True``, ``file_path`` is relative to this source code file\n    :param str comment_string: ignore lines starting with this string\n    :param str field_separator: fields are separated by this string\n    :param str line_format: if not ``None``, parses each line according to the given format\n                            (``s`` = string, ``S`` = split string using spaces,\n                            ``i`` = int, ``x`` = ignore, ``U`` = Unicode, ``A`` = ASCII)\n    :rtype: list of tuples"
  },
  {
    "code": "def _get_info(self, host, port, unix_socket, auth):\n        client = self._client(host, port, unix_socket, auth)\n        if client is None:\n            return None\n        info = client.info()\n        del client\n        return info",
    "docstring": "Return info dict from specified Redis instance\n\n:param str host: redis host\n:param int port: redis port\n:rtype: dict"
  },
  {
    "code": "def _rule_as_string(self, rule):\n        if isinstance(rule, RuleSet):\n            return '%s{%s}' % (\n                self._selector_as_string(rule.selector),\n                self._declarations_as_string(rule.declarations))\n        elif isinstance(rule, ImportRule):\n            return \"@import url('%s') %s;\" % (\n                rule.uri, ','.join(rule.media))\n        elif isinstance(rule, FontFaceRule):\n            return \"@font-face{%s}\" % self._declarations_as_string(rule.declarations)\n        elif isinstance(rule, MediaRule):\n            return \"@media %s{%s}\" % (\n                ','.join(rule.media),\n                ''.join(self._rule_as_string(r) for r in rule.rules))\n        elif isinstance(rule, PageRule):\n            selector, pseudo = rule.selector\n            return \"@page%s%s{%s}\" % (\n                ' %s' % selector if selector else '',\n                ' :%s' % pseudo if pseudo else '',\n                self._declarations_as_string(rule.declarations))\n        return ''",
    "docstring": "Converts a tinycss rule to a formatted CSS string\n\n        :param rule: The rule to format\n        :type rule: tinycss Rule object\n        :returns: The Rule as a CSS string\n        :rtype: str"
  },
  {
    "code": "def do_batch_status(args):\n    rest_client = RestClient(args.url, args.user)\n    batch_ids = args.batch_ids.split(',')\n    if args.wait and args.wait > 0:\n        statuses = rest_client.get_statuses(batch_ids, args.wait)\n    else:\n        statuses = rest_client.get_statuses(batch_ids)\n    if args.format == 'yaml':\n        fmt.print_yaml(statuses)\n    elif args.format == 'json':\n        fmt.print_json(statuses)\n    else:\n        raise AssertionError('Missing handler: {}'.format(args.format))",
    "docstring": "Runs the batch-status command, printing output to the console\n\n        Args:\n            args: The parsed arguments sent to the command at runtime"
  },
  {
    "code": "def process_openxml_file(filename: str,\n                         print_good: bool,\n                         delete_if_bad: bool) -> None:\n    print_bad = not print_good\n    try:\n        file_good = is_openxml_good(filename)\n        file_bad = not file_good\n        if (print_good and file_good) or (print_bad and file_bad):\n            print(filename)\n        if delete_if_bad and file_bad:\n            log.warning(\"Deleting: {}\", filename)\n            os.remove(filename)\n    except Exception as e:\n        log.critical(\"Uncaught error in subprocess: {!r}\\n{}\", e,\n                     traceback.format_exc())\n        raise",
    "docstring": "Prints the filename of, or deletes, an OpenXML file depending on whether\n    it is corrupt or not.\n\n    Args:\n        filename: filename to check\n        print_good: if ``True``, then prints the filename if the file\n            appears good.\n        delete_if_bad: if ``True``, then deletes the file if the file\n            appears corrupt."
  },
  {
    "code": "def zpopmin(self, key, count=None, *, encoding=_NOTSET):\n        if count is not None and not isinstance(count, int):\n            raise TypeError(\"count argument must be int\")\n        args = []\n        if count is not None:\n            args.extend([count])\n        fut = self.execute(b'ZPOPMIN', key, *args, encoding=encoding)\n        return fut",
    "docstring": "Removes and returns up to count members with the lowest scores\n        in the sorted set stored at key.\n\n        :raises TypeError: if count is not int"
  },
  {
    "code": "def _get_http_args(self, params):\n        headers = self.http_args.get('headers', {})\n        if self.auth is not None:\n            auth_headers = self.auth.get_headers()\n            headers.update(auth_headers)\n        http_args = self.http_args.copy()\n        if self._source_id is not None:\n            headers['source_id'] = self._source_id\n        http_args['headers'] = headers\n        merged_params = http_args.get('params', {})\n        merged_params.update(params)\n        http_args['params'] = merged_params\n        return http_args",
    "docstring": "Return a copy of the http_args\n\n        Adds auth headers and 'source_id', merges in params."
  },
  {
    "code": "def delete_mirror(name, config_path=_DEFAULT_CONFIG_PATH, force=False):\n    _validate_config(config_path)\n    force = six.text_type(bool(force)).lower()\n    current_mirror = __salt__['aptly.get_mirror'](name=name, config_path=config_path)\n    if not current_mirror:\n        log.debug('Mirror already absent: %s', name)\n        return True\n    cmd = ['mirror', 'drop', '-config={}'.format(config_path),\n           '-force={}'.format(force), name]\n    _cmd_run(cmd)\n    mirror = __salt__['aptly.get_mirror'](name=name, config_path=config_path)\n    if mirror:\n        log.error('Unable to remove mirror: %s', name)\n        return False\n    log.debug('Removed mirror: %s', name)\n    return True",
    "docstring": "Remove a mirrored remote repository. By default, Package data is not removed.\n\n    :param str name: The name of the remote repository mirror.\n    :param str config_path: The path to the configuration file for the aptly instance.\n    :param bool force: Whether to remove the mirror even if it is used as the source\n        of an existing snapshot.\n\n    :return: A boolean representing whether all changes succeeded.\n    :rtype: bool\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' aptly.delete_mirror name=\"test-mirror\""
  },
  {
    "code": "def to_carrier(self, span_context, carrier):\n        carrier[_TRACE_ID_KEY] = str(span_context.trace_id)\n        if span_context.span_id is not None:\n            carrier[_SPAN_ID_KEY] = str(span_context.span_id)\n        carrier[_TRACE_OPTIONS_KEY] = str(\n            span_context.trace_options.trace_options_byte)\n        return carrier",
    "docstring": "Inject the SpanContext fields to carrier dict.\n\n        :type span_context:\n            :class:`~opencensus.trace.span_context.SpanContext`\n        :param span_context: SpanContext object.\n\n        :type carrier: dict\n        :param carrier: The carrier which holds the trace_id, span_id, options\n                        information from a SpanContext.\n\n        :rtype: dict\n        :returns: The carrier which holds the span context information."
  },
  {
    "code": "def get_default_classes(self):\n        default_classes = super(TabGroup, self).get_default_classes()\n        default_classes.extend(CSS_TAB_GROUP_CLASSES)\n        return default_classes",
    "docstring": "Returns a list of the default classes for the tab group.\n\n        Defaults to ``[\"nav\", \"nav-tabs\", \"ajax-tabs\"]``."
  },
  {
    "code": "def getcoords(ddtt):\n    n_vertices_index = ddtt.objls.index('Number_of_Vertices')\n    first_x = n_vertices_index + 1\n    pts = ddtt.obj[first_x:]\n    return list(grouper(3, pts))",
    "docstring": "return the coordinates of the surface"
  },
  {
    "code": "def _set_last_aid(func):\n    @functools.wraps(func)\n    def new_func(self, *args, **kwargs):\n        aid = func(self, *args, **kwargs)\n        self.last_aid = aid\n        return aid\n    return new_func",
    "docstring": "Decorator for setting last_aid."
  },
  {
    "code": "def list(self):\n        if self.is_fake:\n            return\n        for item in self.collection.list():\n            yield item.uid + self.content_suffix",
    "docstring": "List collection items."
  },
  {
    "code": "def FormatDescriptorToPython(i):\n    i = i.replace(\"/\", \"_\")\n    i = i.replace(\";\", \"\")\n    i = i.replace(\"[\", \"\")\n    i = i.replace(\"(\", \"\")\n    i = i.replace(\")\", \"\")\n    i = i.replace(\" \", \"\")\n    i = i.replace(\"$\", \"\")\n    return i",
    "docstring": "Format a descriptor into a form which can be used as a python attribute\n\n    example::\n\n        >>> FormatDescriptorToPython('(Ljava/lang/Long; Ljava/lang/Long; Z Z)V')\n        'Ljava_lang_LongLjava_lang_LongZZV\n\n    :param i: name to transform\n    :rtype: str"
  },
  {
    "code": "def get_person_by_regid(self, regid):\n        if not self.valid_uwregid(regid):\n            raise InvalidRegID(regid)\n        url = \"{}/{}/full.json\".format(PERSON_PREFIX, regid.upper())\n        response = DAO.getURL(url, {\"Accept\": \"application/json\"})\n        if response.status != 200:\n            raise DataFailureException(url, response.status, response.data)\n        return self._person_from_json(response.data)",
    "docstring": "Returns a restclients.Person object for the given regid.  If the\n        regid isn't found, or if there is an error communicating with the PWS,\n        a DataFailureException will be thrown."
  },
  {
    "code": "def tracefunc_xml(func):\n    funcname = meta_util_six.get_funcname(func)\n    def wrp_tracefunc2(*args, **kwargs):\n        verbose = kwargs.get('verbose', True)\n        if verbose:\n            print('<%s>' % (funcname,))\n        with util_print.Indenter('    '):\n            ret = func(*args, **kwargs)\n        if verbose:\n            print('</%s>' % (funcname,))\n        return ret\n    wrp_tracefunc2_ = ignores_exc_tb(wrp_tracefunc2)\n    wrp_tracefunc2_ = preserve_sig(wrp_tracefunc2_, func)\n    return wrp_tracefunc2_",
    "docstring": "Causes output of function to be printed in an XML style block"
  },
  {
    "code": "def pageLeft(self):\n        targetIdx = self.leftVisibleColIndex\n        firstNonKeyVisibleColIndex = self.visibleCols.index(self.nonKeyVisibleCols[0])\n        while self.rightVisibleColIndex != targetIdx and self.leftVisibleColIndex > firstNonKeyVisibleColIndex:\n            self.cursorVisibleColIndex -= 1\n            self.leftVisibleColIndex -= 1\n            self.calcColLayout()\n        if self.rightVisibleColIndex == self.nVisibleCols-1:\n            while self.leftVisibleColIndex > 0:\n                rightcol = self.visibleCols[self.rightVisibleColIndex]\n                if rightcol.width > self.visibleColLayout[self.rightVisibleColIndex][1]:\n                    self.cursorVisibleColIndex += 1\n                    self.leftVisibleColIndex += 1\n                    break\n                else:\n                    self.cursorVisibleColIndex -= 1\n                    self.leftVisibleColIndex -= 1\n                    self.calcColLayout()",
    "docstring": "Redraw page one screen to the left.\n\n        Note: keep the column cursor in the same general relative position:\n\n         - if it is on the furthest right column, then it should stay on the\n           furthest right column if possible\n\n         - likewise on the left or in the middle\n\n        So really both the `leftIndex` and the `cursorIndex` should move in\n        tandem until things are correct."
  },
  {
    "code": "def new(name):\n        vi = vips_lib.vips_interpolate_new(_to_bytes(name))\n        if vi == ffi.NULL:\n            raise Error('no such interpolator {0}'.format(name))\n        return Interpolate(vi)",
    "docstring": "Make a new interpolator by name.\n\n        Make a new interpolator from the libvips class nickname. For example::\n\n            inter = pyvips.Interpolator.new('bicubic')\n\n        You can get a list of all supported interpolators from the command-line\n        with::\n\n            $ vips -l interpolate\n\n        See for example :meth:`.affine`."
  },
  {
    "code": "def milestone(self, column=None, value=None, **kwargs):\n        return self._resolve_call('GIC_MILESTONE', column, value, **kwargs)",
    "docstring": "Status codes and related dates of certain grants,\n\n        >>> GICS().milestone('milestone_date', '16-MAR-01')"
  },
  {
    "code": "def hexists(self, hashkey, attribute):\n        redis_hash = self._get_hash(hashkey, 'HEXISTS')\n        return self._encode(attribute) in redis_hash",
    "docstring": "Emulate hexists."
  },
  {
    "code": "def to_json(self):\n        return {\n            'st_month': self.st_month,\n            'st_day': self.st_day,\n            'st_hour': self.st_hour,\n            'end_month': self.end_month,\n            'end_day': self.end_day,\n            'end_hour': self.end_hour,\n            'timestep': self.timestep,\n            'is_leap_year': self.is_leap_year\n        }",
    "docstring": "Convert the analysis period to a dictionary."
  },
  {
    "code": "def _def_check(self):\n        if self._def != dict():\n            for key, val in iteritems_(self._def):\n                if key not in list(TEXT_INDEX_ARGS.keys()):\n                    raise CloudantArgumentError(127, key)\n                if not isinstance(val, TEXT_INDEX_ARGS[key]):\n                    raise CloudantArgumentError(128, key, TEXT_INDEX_ARGS[key])",
    "docstring": "Checks that the definition provided contains only valid arguments for a\n        text index."
  },
  {
    "code": "def read_csv(filename):\n    field_names = ('latitude', 'longitude', 'name')\n    data = utils.prepare_csv_read(filename, field_names, skipinitialspace=True)\n    locations = {}\n    args = []\n    for index, row in enumerate(data, 1):\n        name = '%02i:%s' % (index, row['name'])\n        locations[name] = (row['latitude'], row['longitude'])\n        args.append(name)\n    return locations, args",
    "docstring": "Pull locations from a user's CSV file.\n\n    Read gpsbabel_'s CSV output format\n\n    .. _gpsbabel: http://www.gpsbabel.org/\n\n    Args:\n        filename (str): CSV file to parse\n\n    Returns:\n        tuple of dict and list: List of locations as ``str`` objects"
  },
  {
    "code": "def _remove_tree(self, tree, parent=None):\n        for sub_tree in tree.sub_trees:\n            self._remove_tree(sub_tree, parent=tree)\n        for index in tree.indexes:\n            if not getattr(tree, index):\n                continue\n            self._remove_from(\n                getattr(self, index + \"_db\"),\n                getattr(tree, index),\n                tree,\n            )\n        if parent:\n            self._remove_from(self.parent_db, tree.path, parent)\n        self.zeo.pack()",
    "docstring": "Really remove the tree identified by `tree` instance from all indexes\n        from database.\n\n        Args:\n            tree (obj): :class:`.Tree` instance.\n            parent (obj, default None): Reference to parent."
  },
  {
    "code": "def Definition(self):\n    result = self._FormatDescriptionComment()\n    result += \"  enum %s {\\n\" % self.enum_name\n    for k, v in sorted(iteritems(self.reverse_enum)):\n      result += \"    %s = %s;\\n\" % (v, k)\n    result += \"  }\\n\"\n    result += self._FormatField()\n    return result",
    "docstring": "Return a string with the definition of this field."
  },
  {
    "code": "def execute_request(self, url, http_method, query_params, post_data):\n        response = requests.request(http_method, url, params=query_params,\n                                    auth=self._auth, json=post_data,\n                                    headers={'User-Agent': USER_AGENT})\n        if isinstance(self._output_generator, str) and self._output_generator.lower() == \"json\":\n            return response.json()\n        elif self._output_generator is not None:\n            return self._output_generator.process_response(response)\n        else:\n            return response",
    "docstring": "Makes a request to the specified url endpoint with the\n        specified http method, params and post data.\n\n        Args:\n            url (string): The url to the API without query params.\n                          Example: \"https://api.housecanary.com/v2/property/value\"\n            http_method (string): The http method to use for the request.\n            query_params (dict): Dictionary of query params to add to the request.\n            post_data: Json post data to send in the body of the request.\n\n        Returns:\n            The result of calling this instance's OutputGenerator process_response method\n            on the requests.Response object.\n            If no OutputGenerator is specified for this instance, returns the requests.Response."
  },
  {
    "code": "def parse(self, data):\n        ASNlist = []\n        for line in data.splitlines()[1:]:\n            line = plain_str(line)\n            if \"|\" not in line:\n                continue\n            asn, ip, desc = [elt.strip() for elt in line.split('|')]\n            if asn == \"NA\":\n                continue\n            asn = \"AS%s\" % asn\n            ASNlist.append((ip, asn, desc))\n        return ASNlist",
    "docstring": "Parse bulk cymru data"
  },
  {
    "code": "def list_commands(self, ctx):\n        rv = []\n        files = [_ for _ in next(os.walk(self.folder))[2] if not _.startswith(\"_\") and _.endswith(\".py\")]\n        for filename in files:\n            rv.append(filename[:-3])\n        rv.sort()\n        return rv",
    "docstring": "List commands from folder."
  },
  {
    "code": "def create_event_subscription(self, url):\n        params = {'callbackUrl': url}\n        response = self._do_request('POST', '/v2/eventSubscriptions', params)\n        return response.json()",
    "docstring": "Register a callback URL as an event subscriber.\n\n        :param str url: callback URL\n\n        :returns: the created event subscription\n        :rtype: dict"
  },
  {
    "code": "def assign_vertex_attrib_location(self, vbo, location):\n        with vbo:\n            if self.n_verts:\n                assert vbo.data.shape[0] == self.n_verts\n            else:\n                self.n_verts = vbo.data.shape[0]\n            gl.glVertexAttribPointer(location, vbo.data.shape[1], gl.GL_FLOAT, gl.GL_FALSE, 0, 0)\n            gl.glEnableVertexAttribArray(location)",
    "docstring": "Load data into a vbo"
  },
  {
    "code": "def team_robots(self, team):\n        return [Robot(raw) for raw in self._get('team/%s/robots' % self.team_key(team))]",
    "docstring": "Get data about a team's robots.\n\n        :param team: Key for team whose robots you want data on.\n        :return: List of Robot objects"
  },
  {
    "code": "def send(self, msg, timeout=None):\n        arb_id = msg.arbitration_id\n        if msg.is_extended_id:\n            arb_id |= NC_FL_CAN_ARBID_XTD\n        raw_msg = TxMessageStruct(arb_id,\n                                  bool(msg.is_remote_frame),\n                                  msg.dlc,\n                                  CanData(*msg.data))\n        nican.ncWrite(\n            self.handle, ctypes.sizeof(raw_msg), ctypes.byref(raw_msg))",
    "docstring": "Send a message to NI-CAN.\n\n        :param can.Message msg:\n            Message to send\n\n        :raises can.interfaces.nican.NicanError:\n            If writing to transmit buffer fails.\n            It does not wait for message to be ACKed currently."
  },
  {
    "code": "def ensure_specification_cols_are_in_dataframe(specification, dataframe):\n    try:\n        assert isinstance(specification, OrderedDict)\n    except AssertionError:\n        raise TypeError(\"`specification` must be an OrderedDict.\")\n    assert isinstance(dataframe, pd.DataFrame)\n    problem_cols = []\n    dataframe_cols = dataframe.columns\n    for key in specification:\n        if key not in dataframe_cols:\n            problem_cols.append(key)\n    if problem_cols != []:\n        msg = \"The following keys in the specification are not in 'data':\\n{}\"\n        raise ValueError(msg.format(problem_cols))\n    return None",
    "docstring": "Checks whether each column in `specification` is in `dataframe`. Raises\n    ValueError if any of the columns are not in the dataframe.\n\n    Parameters\n    ----------\n    specification : OrderedDict.\n        Keys are a proper subset of the columns in `data`. Values are either a\n        list or a single string, \"all_diff\" or \"all_same\". If a list, the\n        elements should be:\n            - single objects that are in the alternative ID column of `data`\n            - lists of objects that are within the alternative ID column of\n              `data`. For each single object in the list, a unique column will\n              be created (i.e. there will be a unique coefficient for that\n              variable in the corresponding utility equation of the\n              corresponding alternative). For lists within the\n              `specification` values, a single column will be created for all\n              the alternatives within the iterable (i.e. there will be one\n              common coefficient for the variables in the iterable).\n    dataframe : pandas DataFrame.\n        Dataframe containing the data for the choice model to be estimated.\n\n    Returns\n    -------\n    None."
  },
  {
    "code": "def weight_statistics(self):\n        all_weights = [d.get('weight', None) for u, v, d\n                       in self.graph.edges(data=True)]\n        stats = describe(all_weights, nan_policy='omit')\n        return {\n            'all_weights': all_weights,\n            'min': stats.minmax[0],\n            'max': stats.minmax[1],\n            'mean': stats.mean,\n            'variance': stats.variance\n        }",
    "docstring": "Extract a statistical summary of edge weights present in\n        the graph.\n\n        :return: A dict with an 'all_weights' list, 'minimum',\n        'maximum', 'median', 'mean', 'std_dev'"
  },
  {
    "code": "def add_f90_to_env(env):\n    try:\n        F90Suffixes = env['F90FILESUFFIXES']\n    except KeyError:\n        F90Suffixes = ['.f90']\n    try:\n        F90PPSuffixes = env['F90PPFILESUFFIXES']\n    except KeyError:\n        F90PPSuffixes = []\n    DialectAddToEnv(env, \"F90\", F90Suffixes, F90PPSuffixes,\n                    support_module = 1)",
    "docstring": "Add Builders and construction variables for f90 to an Environment."
  },
  {
    "code": "def loads(schema_str):\n    try:\n        if sys.version_info[0] < 3:\n            return schema.parse(schema_str)\n        else:\n            return schema.Parse(schema_str)\n    except schema.SchemaParseException as e:\n        raise ClientError(\"Schema parse failed: %s\" % (str(e)))",
    "docstring": "Parse a schema given a schema string"
  },
  {
    "code": "def bootstraps(self, _args):\n        for bs in Bootstrap.list_bootstraps():\n            bs = Bootstrap.get_bootstrap(bs, self.ctx)\n            print('{Fore.BLUE}{Style.BRIGHT}{bs.name}{Style.RESET_ALL}'\n                  .format(bs=bs, Fore=Out_Fore, Style=Out_Style))\n            print('    {Fore.GREEN}depends: {bs.recipe_depends}{Fore.RESET}'\n                  .format(bs=bs, Fore=Out_Fore))",
    "docstring": "List all the bootstraps available to build with."
  },
  {
    "code": "def create_textview(self, wrap_mode=Gtk.WrapMode.WORD_CHAR, justify=Gtk.Justification.LEFT, visible=True, editable=True):\n        text_view = Gtk.TextView()\n        text_view.set_wrap_mode(wrap_mode)\n        text_view.set_editable(editable)\n        if not editable:\n            text_view.set_cursor_visible(False)\n        else:\n            text_view.set_cursor_visible(visible)\n        text_view.set_justification(justify)\n        return text_view",
    "docstring": "Function creates a text view with wrap_mode\n        and justification"
  },
  {
    "code": "def disable(self):\n        self.post(\"disable\")\n        if self.service.restart_required:\n            self.service.restart(120)\n        return self",
    "docstring": "Disables the entity at this endpoint."
  },
  {
    "code": "def PrintFeed(feed):\n  import gdata\n  for i, entry in enumerate(feed.entry):\n    if isinstance(feed, gdata.spreadsheet.SpreadsheetsCellsFeed):\n      print '%s %s\\n' % (entry.title.text, entry.content.text)\n    elif isinstance(feed, gdata.spreadsheet.SpreadsheetsListFeed):\n      print '%s %s %s' % (i, entry.title.text, entry.content.text)\n      print 'Contents:'\n      for key in entry.custom:\n        print '  %s: %s' % (key, entry.custom[key].text)\n      print '\\n',\n    else:\n      print '%s %s\\n' % (i, entry.title.text)",
    "docstring": "Example function from Google to print a feed"
  },
  {
    "code": "def _score(cluster):\n    x, y = zip(*cluster)[:2]\n    return min(len(set(x)), len(set(y)))",
    "docstring": "score of the cluster, in this case, is the number of non-repetitive matches"
  },
  {
    "code": "def sadd(self, name, values, *args):\n        with self.pipe as pipe:\n            values = [self.valueparse.encode(v) for v in\n                      self._parse_values(values, args)]\n            return pipe.sadd(self.redis_key(name), *values)",
    "docstring": "Add the specified members to the Set.\n\n        :param name: str     the name of the redis key\n        :param values: a list of values or a simple value.\n        :return: Future()"
  },
  {
    "code": "def encode_signature(sig_r, sig_s):\n    if sig_s * 2 >= SECP256k1_order:\n        log.debug(\"High-S to low-S\")\n        sig_s = SECP256k1_order - sig_s\n    sig_bin = '{:064x}{:064x}'.format(sig_r, sig_s).decode('hex')\n    assert len(sig_bin) == 64\n    sig_b64 = base64.b64encode(sig_bin)\n    return sig_b64",
    "docstring": "Encode an ECDSA signature, with low-s"
  },
  {
    "code": "def _ScanEncryptedVolumeNode(self, scan_context, scan_node):\n    if scan_node.type_indicator == definitions.TYPE_INDICATOR_APFS_CONTAINER:\n      container_file_entry = resolver.Resolver.OpenFileEntry(\n          scan_node.path_spec, resolver_context=self._resolver_context)\n      fsapfs_volume = container_file_entry.GetAPFSVolume()\n      try:\n        is_locked = not apfs_helper.APFSUnlockVolume(\n            fsapfs_volume, scan_node.path_spec, resolver.Resolver.key_chain)\n      except IOError as exception:\n        raise errors.BackEndError(\n            'Unable to unlock APFS volume with error: {0!s}'.format(exception))\n    else:\n      file_object = resolver.Resolver.OpenFileObject(\n          scan_node.path_spec, resolver_context=self._resolver_context)\n      is_locked = not file_object or file_object.is_locked\n      file_object.close()\n    if is_locked:\n      scan_context.LockScanNode(scan_node.path_spec)\n      if scan_node.type_indicator == definitions.TYPE_INDICATOR_BDE:\n        path_spec = self.ScanForFileSystem(scan_node.path_spec.parent)\n        if path_spec:\n          scan_context.AddScanNode(path_spec, scan_node.parent_node)",
    "docstring": "Scans an encrypted volume node for supported formats.\n\n    Args:\n      scan_context (SourceScannerContext): source scanner context.\n      scan_node (SourceScanNode): source scan node.\n\n    Raises:\n      BackEndError: if the scan node cannot be unlocked.\n      ValueError: if the scan context or scan node is invalid."
  },
  {
    "code": "def assert_not_in(first, second, msg_fmt=\"{msg}\"):\n    if first in second:\n        msg = \"{!r} is in {!r}\".format(first, second)\n        fail(msg_fmt.format(msg=msg, first=first, second=second))",
    "docstring": "Fail if first is in a collection second.\n\n    >>> assert_not_in(\"bar\", [4, \"foo\", {}])\n    >>> assert_not_in(\"foo\", [4, \"foo\", {}])\n    Traceback (most recent call last):\n        ...\n    AssertionError: 'foo' is in [4, 'foo', {}]\n\n    The following msg_fmt arguments are supported:\n    * msg - the default error message\n    * first - the element looked for\n    * second - the container looked in"
  },
  {
    "code": "def find_newline(source):\n    assert not isinstance(source, unicode)\n    counter = collections.defaultdict(int)\n    for line in source:\n        if line.endswith(CRLF):\n            counter[CRLF] += 1\n        elif line.endswith(CR):\n            counter[CR] += 1\n        elif line.endswith(LF):\n            counter[LF] += 1\n    return (sorted(counter, key=counter.get, reverse=True) or [LF])[0]",
    "docstring": "Return type of newline used in source.\n\n    Input is a list of lines."
  },
  {
    "code": "def _apply_sort(cursor, sort_by, sort_direction):\n        if sort_direction is not None and sort_direction.lower() == \"desc\":\n            sort = pymongo.DESCENDING\n        else:\n            sort = pymongo.ASCENDING\n        return cursor.sort(sort_by, sort)",
    "docstring": "Apply sort to a cursor.\n\n        :param cursor: The cursor to apply sort on.\n        :param sort_by: The field name to sort by.\n        :param sort_direction: The direction to sort, \"asc\" or \"desc\".\n        :return:"
  },
  {
    "code": "def _encode_payload(data, headers=None):\n    \"Wrap data in an SCGI request.\"\n    prolog = \"CONTENT_LENGTH\\0%d\\0SCGI\\x001\\0\" % len(data)\n    if headers:\n        prolog += _encode_headers(headers)\n    return _encode_netstring(prolog) + data",
    "docstring": "Wrap data in an SCGI request."
  },
  {
    "code": "def moist_static_energy(heights, temperature, specific_humidity):\n    r\n    return (dry_static_energy(heights, temperature)\n            + mpconsts.Lv * specific_humidity.to('dimensionless')).to('kJ/kg')",
    "docstring": "r\"\"\"Calculate the moist static energy of parcels.\n\n    This function will calculate the moist static energy following\n    equation 3.72 in [Hobbs2006]_.\n    Notes\n    -----\n    .. math::\\text{moist static energy} = c_{pd} * T + gz + L_v q\n\n    * :math:`T` is temperature\n    * :math:`z` is height\n    * :math:`q` is specific humidity\n\n    Parameters\n    ----------\n    heights : array-like\n        Atmospheric height\n    temperature : array-like\n        Atmospheric temperature\n    specific_humidity : array-like\n        Atmospheric specific humidity\n\n    Returns\n    -------\n    `pint.Quantity`\n        The moist static energy"
  },
  {
    "code": "def add(self, command):\n        self.add_command(command.config)\n        command.set_application(self)\n        return self",
    "docstring": "Adds a command object."
  },
  {
    "code": "def satellite(isochrone, kernel, stellar_mass, distance_modulus,**kwargs):\n    mag_1, mag_2 = isochrone.simulate(stellar_mass, distance_modulus)\n    lon, lat     = kernel.simulate(len(mag_1))\n    return mag_1, mag_2, lon, lat",
    "docstring": "Wrapping the isochrone and kernel simulate functions."
  },
  {
    "code": "def get_translated_items(fapi, file_uri, use_cache, cache_dir=None):\n    items = None\n    cache_file = os.path.join(cache_dir, sha1(file_uri)) if use_cache else None\n    if use_cache and os.path.exists(cache_file):\n        print(\"Using cache file %s for translated items for: %s\" % (cache_file, file_uri))\n        items = json.loads(read_from_file(cache_file))\n    if not items:\n        print(\"Downloading %s from smartling\" % file_uri)\n        (response, code) = fapi.last_modified(file_uri)\n        items = response.data.items\n        if cache_file:\n            print(\"Caching %s to %s\" % (file_uri, cache_file))\n            write_to_file(cache_file, json.dumps(items))\n    return items",
    "docstring": "Returns the last modified from smarterling"
  },
  {
    "code": "def reset_coords(self, names=None, drop=False, inplace=None):\n        inplace = _check_inplace(inplace)\n        if inplace and not drop:\n            raise ValueError('cannot reset coordinates in-place on a '\n                             'DataArray without ``drop == True``')\n        if names is None:\n            names = set(self.coords) - set(self.dims)\n        dataset = self.coords.to_dataset().reset_coords(names, drop)\n        if drop:\n            if inplace:\n                self._coords = dataset._variables\n            else:\n                return self._replace(coords=dataset._variables)\n        else:\n            if self.name is None:\n                raise ValueError('cannot reset_coords with drop=False '\n                                 'on an unnamed DataArrray')\n            dataset[self.name] = self.variable\n            return dataset",
    "docstring": "Given names of coordinates, reset them to become variables.\n\n        Parameters\n        ----------\n        names : str or list of str, optional\n            Name(s) of non-index coordinates in this dataset to reset into\n            variables. By default, all non-index coordinates are reset.\n        drop : bool, optional\n            If True, remove coordinates instead of converting them into\n            variables.\n        inplace : bool, optional\n            If True, modify this dataset inplace. Otherwise, create a new\n            object.\n\n        Returns\n        -------\n        Dataset, or DataArray if ``drop == True``"
  },
  {
    "code": "def getMaxWidth(self, rows):\n        'Return the maximum length of any cell in column or its header.'\n        w = 0\n        if len(rows) > 0:\n            w = max(max(len(self.getDisplayValue(r)) for r in rows), len(self.name))+2\n        return max(w, len(self.name))",
    "docstring": "Return the maximum length of any cell in column or its header."
  },
  {
    "code": "def _load_prefix_binding(self):\n        pymux = self.pymux\n        if self._prefix_binding:\n            self.custom_key_bindings.remove_binding(self._prefix_binding)\n        @self.custom_key_bindings.add(*self._prefix, filter=\n            ~(HasPrefix(pymux) | has_focus(COMMAND) | has_focus(PROMPT) |\n              WaitsForConfirmation(pymux)))\n        def enter_prefix_handler(event):\n            \" Enter prefix mode. \"\n            pymux.get_client_state().has_prefix = True\n        self._prefix_binding = enter_prefix_handler",
    "docstring": "Load the prefix key binding."
  },
  {
    "code": "def session(self, auth=None):\n        url = '{server}{auth_url}'.format(**self._options)\n        if isinstance(self._session.auth, tuple) or auth:\n            if not auth:\n                auth = self._session.auth\n            username, password = auth\n            authentication_data = {'username': username, 'password': password}\n            r = self._session.post(url, data=json.dumps(authentication_data))\n        else:\n            r = self._session.get(url)\n        user = User(self._options, self._session, json_loads(r))\n        return user",
    "docstring": "Get a dict of the current authenticated user's session information.\n\n        :param auth: Tuple of username and password.\n        :type auth: Optional[Tuple[str,str]]\n\n        :rtype: User"
  },
  {
    "code": "def find_models(self, constructor, constraints=None, *, columns=None, order_by=None,\n                  limiting=None, table_name=None):\n    return self._find_models(\n      constructor, table_name or constructor.table_name, constraints, columns=columns,\n      order_by=order_by, limiting=limiting)",
    "docstring": "Specialization of DataAccess.find_all that returns models instead of cursor objects."
  },
  {
    "code": "def bandpass_filter_matrix( matrix,\n    tr=1, lowf=0.01, highf=0.1, order = 3):\n    from scipy.signal import butter, filtfilt\n    def butter_bandpass(lowcut, highcut, fs, order ):\n        nyq = 0.5 * fs\n        low = lowcut / nyq\n        high = highcut / nyq\n        b, a = butter(order, [low, high], btype='band')\n        return b, a\n    def butter_bandpass_filter(data, lowcut, highcut, fs, order ):\n        b, a = butter_bandpass(lowcut, highcut, fs, order=order)\n        y = filtfilt(b, a, data)\n        return y\n    fs = 1/tr\n    nsamples = matrix.shape[0]\n    ncolumns = matrix.shape[1]\n    matrixOut = matrix.copy()\n    for k in range( ncolumns ):\n        matrixOut[:,k] = butter_bandpass_filter(\n            matrix[:,k], lowf, highf, fs, order=order )\n    return matrixOut",
    "docstring": "Bandpass filter the input time series image\n\n    ANTsR function: `frequencyFilterfMRI`\n\n    Arguments\n    ---------\n\n    image: input time series image\n\n    tr:    sampling time interval (inverse of sampling rate)\n\n    lowf:  low frequency cutoff\n\n    highf: high frequency cutoff\n\n    order: order of the butterworth filter run using `filtfilt`\n\n    Returns\n    -------\n    filtered matrix\n\n    Example\n    -------\n\n    >>> import numpy as np\n    >>> import ants\n    >>> import matplotlib.pyplot as plt\n    >>> brainSignal = np.random.randn( 400, 1000 )\n    >>> tr = 1\n    >>> filtered = ants.bandpass_filter_matrix( brainSignal, tr = tr )\n    >>> nsamples = brainSignal.shape[0]\n    >>> t = np.linspace(0, tr*nsamples, nsamples, endpoint=False)\n    >>> k = 20\n    >>> plt.plot(t, brainSignal[:,k], label='Noisy signal')\n    >>> plt.plot(t, filtered[:,k], label='Filtered signal')\n    >>> plt.xlabel('time (seconds)')\n    >>> plt.grid(True)\n    >>> plt.axis('tight')\n    >>> plt.legend(loc='upper left')\n    >>> plt.show()"
  },
  {
    "code": "def build_swagger12_handler(schema):\n    if schema:\n        return SwaggerHandler(\n            op_for_request=schema.validators_for_request,\n            handle_request=handle_request,\n            handle_response=validate_response,\n        )",
    "docstring": "Builds a swagger12 handler or returns None if no schema is present.\n\n    :type schema: :class:`pyramid_swagger.model.SwaggerSchema`\n    :rtype: :class:`SwaggerHandler` or None"
  },
  {
    "code": "def param_help_download(self):\n        files = []\n        for vehicle in ['APMrover2', 'ArduCopter', 'ArduPlane', 'ArduSub', 'AntennaTracker']:\n            url = 'http://autotest.ardupilot.org/Parameters/%s/apm.pdef.xml' % vehicle\n            path = mp_util.dot_mavproxy(\"%s.xml\" % vehicle)\n            files.append((url, path))\n            url = 'http://autotest.ardupilot.org/%s-defaults.parm' % vehicle\n            if vehicle != 'AntennaTracker':\n                path = mp_util.dot_mavproxy(\"%s-defaults.parm\" % vehicle)\n                files.append((url, path))\n        try:\n            child = multiproc.Process(target=mp_util.download_files, args=(files,))\n            child.start()\n        except Exception as e:\n            print(e)",
    "docstring": "download XML files for parameters"
  },
  {
    "code": "def total_misses(self, filename=None):\n        if filename is not None:\n            return len(self.missed_statements(filename))\n        total = 0\n        for filename in self.files():\n            total += len(self.missed_statements(filename))\n        return total",
    "docstring": "Return the total number of uncovered statements for the file\n        `filename`. If `filename` is not given, return the total\n        number of uncovered statements for all files."
  },
  {
    "code": "def _filter(self, text):\n        self.markdown.reset()\n        return self.markdown.convert(text)",
    "docstring": "Filter markdown."
  },
  {
    "code": "def load_global_catalog():\n    cat_dir = global_data_dir()\n    if not os.path.isdir(cat_dir):\n        return Catalog()\n    else:\n        return YAMLFilesCatalog(cat_dir)",
    "docstring": "Return a catalog for the environment-specific Intake directory"
  },
  {
    "code": "def format_kwargs(attrs, params):\n    attrs_mapping = {'cell_methods': {'YS': 'years', 'MS': 'months'},\n                     'long_name': {'YS': 'Annual', 'MS': 'Monthly'}}\n    for key, val in attrs.items():\n        mba = {}\n        for k, v in params.items():\n            if isinstance(v, six.string_types) and v in attrs_mapping.get(key, {}).keys():\n                mba[k] = '{' + v + '}'\n            else:\n                mba[k] = v\n        attrs[key] = val.format(**mba).format(**attrs_mapping.get(key, {}))",
    "docstring": "Modify attribute with argument values.\n\n    Parameters\n    ----------\n    attrs : dict\n      Attributes to be assigned to function output. The values of the attributes in braces will be replaced the\n      the corresponding args values.\n    params : dict\n      A BoundArguments.arguments dictionary storing a function's arguments."
  },
  {
    "code": "def main():\n    if '-h' in sys.argv:\n        print(main.__doc__)\n        sys.exit()\n    if '-f' in sys.argv:\n        dat=[]\n        ind=sys.argv.index('-f')\n        file=sys.argv[ind+1]\n    else:\n        file = sys.stdin\n    ofile=\"\"\n    if '-F' in sys.argv:\n        ind = sys.argv.index('-F')\n        ofile= sys.argv[ind+1]\n        out = open(ofile, 'w + a')\n    DIIs=numpy.loadtxt(file,dtype=numpy.float)\n    vpars,R=pmag.vector_mean(DIIs)\n    outstring='%7.1f %7.1f   %10.3e %i'%(vpars[0],vpars[1],R,len(DIIs))\n    if ofile == \"\":\n        print(outstring)\n    else:\n        out.write(outstring + \"\\n\")",
    "docstring": "NAME\n       vector_mean.py\n\n    DESCRIPTION\n       calculates vector mean of vector data\n\n    INPUT FORMAT\n       takes dec, inc, int from an input file\n\n    SYNTAX\n       vector_mean.py [command line options]  [< filename]\n\n    OPTIONS\n        -h prints help message and quits\n        -f FILE, specify input file\n        -F FILE, specify output file\n        < filename for reading from standard input\n   \n    OUTPUT\n       mean dec, mean inc, R, N"
  },
  {
    "code": "def request_middleware(api=None):\n    def decorator(middleware_method):\n        apply_to_api = hug.API(api) if api else hug.api.from_object(middleware_method)\n        class MiddlewareRouter(object):\n            __slots__ = ()\n            def process_request(self, request, response):\n                return middleware_method(request, response)\n        apply_to_api.http.add_middleware(MiddlewareRouter())\n        return middleware_method\n    return decorator",
    "docstring": "Registers a middleware function that will be called on every request"
  },
  {
    "code": "def consolidate_args(args):\n        if not hasattr(args, 'hex_limit'):\n            return\n        active_plugins = {}\n        is_using_default_value = {}\n        for plugin in PluginOptions.all_plugins:\n            arg_name = PluginOptions._convert_flag_text_to_argument_name(\n                plugin.disable_flag_text,\n            )\n            is_disabled = getattr(args, arg_name, False)\n            delattr(args, arg_name)\n            if is_disabled:\n                continue\n            related_args = {}\n            for related_arg_tuple in plugin.related_args:\n                try:\n                    flag_name, default_value = related_arg_tuple\n                except ValueError:\n                    flag_name = related_arg_tuple\n                    default_value = None\n                arg_name = PluginOptions._convert_flag_text_to_argument_name(\n                    flag_name,\n                )\n                related_args[arg_name] = getattr(args, arg_name)\n                delattr(args, arg_name)\n                if default_value and related_args[arg_name] is None:\n                    related_args[arg_name] = default_value\n                    is_using_default_value[arg_name] = True\n            active_plugins.update({\n                plugin.classname: related_args,\n            })\n        args.plugins = active_plugins\n        args.is_using_default_value = is_using_default_value",
    "docstring": "There are many argument fields related to configuring plugins.\n        This function consolidates all of them, and saves the consolidated\n        information in args.plugins.\n\n        Note that we're deferring initialization of those plugins, because\n        plugins may have various initialization values, referenced in\n        different places.\n\n        :param args: output of `argparse.ArgumentParser.parse_args`"
  },
  {
    "code": "def get_sqlite_core(connection_string, *, cursor_factory=None, edit_connection=None):\n  import sqlite3 as sqlite\n  def opener():\n    cn = sqlite.connect(connection_string)\n    if cursor_factory:\n      cn.row_factory = cursor_factory\n    if edit_connection:\n      edit_connection(cn)\n    return cn\n  return InjectedDataAccessCore(\n    opener,\n    default_connection_closer, (\":{0}\", \"?\", SQL_CAST),\n    empty_params=[],\n    supports_timezones=True,\n    supports_returning_syntax=False,\n    get_autocommit=get_sqlite_autocommit,\n    set_autocommit=set_sqlite_autocommit)",
    "docstring": "Creates a simple SQLite3 core."
  },
  {
    "code": "def generate_data_for_create_page(self):\n        if not self.can_create:\n            return {}\n        if self.create_form:\n            return self.create_form.to_dict()\n        return self.generate_simple_data_page()",
    "docstring": "Generate a custom representation of table's fields in dictionary type\n        if exist create form else use default representation.\n\n        :return: dict"
  },
  {
    "code": "def read_data(filename, data_format=None):\n    if not os.path.exists(filename):\n        raise ValueError('Filename {} does not exist'.format(filename))\n    if not isinstance(data_format, MimeType):\n        data_format = get_data_format(filename)\n    if data_format.is_tiff_format():\n        return read_tiff_image(filename)\n    if data_format is MimeType.JP2:\n        return read_jp2_image(filename)\n    if data_format.is_image_format():\n        return read_image(filename)\n    try:\n        return {\n            MimeType.TXT: read_text,\n            MimeType.CSV: read_csv,\n            MimeType.JSON: read_json,\n            MimeType.XML: read_xml,\n            MimeType.GML: read_xml,\n            MimeType.SAFE: read_xml\n        }[data_format](filename)\n    except KeyError:\n        raise ValueError('Reading data format .{} is not supported'.format(data_format.value))",
    "docstring": "Read image data from file\n\n    This function reads input data from file. The format of the file\n    can be specified in ``data_format``. If not specified, the format is\n    guessed from the extension of the filename.\n\n    :param filename: filename to read data from\n    :type filename: str\n    :param data_format: format of filename. Default is ``None``\n    :type data_format: MimeType\n    :return: data read from filename\n    :raises: exception if filename does not exist"
  },
  {
    "code": "def absolutify(url):\n    site_url = getattr(settings, 'SITE_URL', False)\n    if not site_url:\n        protocol = settings.PROTOCOL\n        hostname = settings.DOMAIN\n        port = settings.PORT\n        if (protocol, port) in (('https://', 443), ('http://', 80)):\n            site_url = ''.join(map(str, (protocol, hostname)))\n        else:\n            site_url = ''.join(map(str, (protocol, hostname, ':', port)))\n    return site_url + url",
    "docstring": "Takes a URL and prepends the SITE_URL"
  },
  {
    "code": "def detectBlackBerry(self):\n        return UAgentInfo.deviceBB in self.__userAgent \\\n            or UAgentInfo.vndRIM in self.__httpAccept",
    "docstring": "Return detection of Blackberry\n\n        Detects if the current browser is any BlackBerry.\n        Includes the PlayBook."
  },
  {
    "code": "def get_config(self):\n        config = {\n            'location': self.location,\n            'language': self.language,\n            'topic': self.topic,\n        }\n        return config",
    "docstring": "function to get current configuration"
  },
  {
    "code": "def get_raw_token(self, header):\n        parts = header.split()\n        if len(parts) == 0:\n            return None\n        if parts[0] not in AUTH_HEADER_TYPE_BYTES:\n            return None\n        if len(parts) != 2:\n            raise AuthenticationFailed(\n                _('Authorization header must contain two space-delimited values'),\n                code='bad_authorization_header',\n            )\n        return parts[1]",
    "docstring": "Extracts an unvalidated JSON web token from the given \"Authorization\"\n        header value."
  },
  {
    "code": "def tensor(self, field_name, tensor_ind):\n        if tensor_ind == self._tensor_cache_file_num[field_name]:\n            return self._tensors[field_name]\n        filename = self.generate_tensor_filename(field_name, tensor_ind, compressed=True)\n        Tensor.load(filename, compressed=True,\n                    prealloc=self._tensors[field_name])\n        self._tensor_cache_file_num[field_name] = tensor_ind\n        return self._tensors[field_name]",
    "docstring": "Returns the tensor for a given field and tensor index.\n\n        Parameters\n        ----------\n        field_name : str\n            the name of the field to load\n        tensor_index : int\n            the index of the tensor\n\n        Returns\n        -------\n        :obj:`Tensor`\n            the desired tensor"
  },
  {
    "code": "def _detect_gamepads(self):\n        state = XinputState()\n        for device_number in range(4):\n            res = self.xinput.XInputGetState(\n                device_number, ctypes.byref(state))\n            if res == XINPUT_ERROR_SUCCESS:\n                device_path = (\n                    \"/dev/input/by_id/\" +\n                    \"usb-Microsoft_Corporation_Controller_%s-event-joystick\"\n                    % device_number)\n                self.gamepads.append(GamePad(self, device_path))\n                continue\n            if res != XINPUT_ERROR_DEVICE_NOT_CONNECTED:\n                raise RuntimeError(\n                    \"Unknown error %d attempting to get state of device %d\"\n                    % (res, device_number))",
    "docstring": "Find gamepads."
  },
  {
    "code": "def render_check_and_set_platforms(self):\n        phase = 'prebuild_plugins'\n        plugin = 'check_and_set_platforms'\n        if not self.pt.has_plugin_conf(phase, plugin):\n            return\n        if self.user_params.koji_target.value:\n            self.pt.set_plugin_arg(phase, plugin, \"koji_target\",\n                                   self.user_params.koji_target.value)",
    "docstring": "If the check_and_set_platforms plugin is present, configure it"
  },
  {
    "code": "def manage_mep(self, mep_json):\n        responses = representative_pre_import.send(sender=self,\n                representative_data=mep_json)\n        for receiver, response in responses:\n            if response is False:\n                logger.debug(\n                    'Skipping MEP %s', mep_json['Name']['full'])\n                return\n        changed = False\n        slug = slugify('%s-%s' % (\n            mep_json[\"Name\"][\"full\"] if 'full' in mep_json[\"Name\"]\n            else mep_json[\"Name\"][\"sur\"] + \" \" + mep_json[\"Name\"][\"family\"],\n            _parse_date(mep_json[\"Birth\"][\"date\"])\n        ))\n        try:\n            representative = Representative.objects.get(slug=slug)\n        except Representative.DoesNotExist:\n            representative = Representative(slug=slug)\n            changed = True\n        self.import_representative_details(representative, mep_json, changed)\n        self.add_mandates(representative, mep_json)\n        self.add_contacts(representative, mep_json)\n        logger.debug('Imported MEP %s', unicode(representative))\n        return representative",
    "docstring": "Import a mep as a representative from the json dict fetched from\n        parltrack"
  },
  {
    "code": "def long_form_multiple_formats(jupytext_formats, metadata=None):\n    if not jupytext_formats:\n        return []\n    if not isinstance(jupytext_formats, list):\n        jupytext_formats = [fmt for fmt in jupytext_formats.split(',') if fmt]\n    jupytext_formats = [long_form_one_format(fmt, metadata) for fmt in jupytext_formats]\n    return jupytext_formats",
    "docstring": "Convert a concise encoding of jupytext.formats to a list of formats, encoded as dictionaries"
  },
  {
    "code": "def _generate_initial_model(self):\n        initial_parameters = [p.current_value for p in self.current_parameters]\n        try:\n            initial_model = self.specification(*initial_parameters)\n        except TypeError:\n            raise TypeError(\n                'Failed to build initial model. Make sure that the input '\n                'parameters match the number and order of arguements '\n                'expected by the input specification.')\n        initial_model.pack_new_sequences(self.sequences)\n        self.current_energy = self.eval_function(initial_model)\n        self.best_energy = copy.deepcopy(self.current_energy)\n        self.best_parameters = copy.deepcopy(self.current_parameters)\n        self.best_model = initial_model\n        return",
    "docstring": "Creates the initial model for the optimistation.\n\n        Raises\n        ------\n        TypeError\n            Raised if the model failed to build. This could be due to\n            parameters being passed to the specification in the wrong\n            format."
  },
  {
    "code": "def GetNetworks(alias=None,location=None):\n\t\tif alias is None:  alias = clc.v1.Account.GetAlias()\n\t\tif location is None:  location = clc.v1.Account.GetLocation()\n\t\tr = clc.v1.API.Call('post','Network/GetAccountNetworks', { 'AccountAlias': alias, 'Location': location })\n\t\tif int(r['StatusCode']) == 0:  return(r['Networks'])",
    "docstring": "Gets the list of Networks mapped to the account in the specified datacenter.\n\n\t\thttps://t3n.zendesk.com/entries/21024721-Get-Networks\n\n\t\t:param alias: short code for a particular account.  If none will use account's default alias\n\t\t:param location: datacenter where group resides.  If none will use account's primary datacenter"
  },
  {
    "code": "def construct_s3_location_object(location_uri, logical_id, property_name):\n    if isinstance(location_uri, dict):\n        if not location_uri.get(\"Bucket\") or not location_uri.get(\"Key\"):\n            raise InvalidResourceException(logical_id,\n                                           \"'{}' requires Bucket and Key properties to be \"\n                                           \"specified\".format(property_name))\n        s3_pointer = location_uri\n    else:\n        s3_pointer = parse_s3_uri(location_uri)\n        if s3_pointer is None:\n            raise InvalidResourceException(logical_id,\n                                           '\\'{}\\' is not a valid S3 Uri of the form '\n                                           '\"s3://bucket/key\" with optional versionId query '\n                                           'parameter.'.format(property_name))\n    code = {\n        'S3Bucket': s3_pointer['Bucket'],\n        'S3Key': s3_pointer['Key']\n    }\n    if 'Version' in s3_pointer:\n        code['S3ObjectVersion'] = s3_pointer['Version']\n    return code",
    "docstring": "Constructs a Lambda `Code` or `Content` property, from the SAM `CodeUri` or `ContentUri` property.\n    This follows the current scheme for Lambda Functions and LayerVersions.\n\n    :param dict or string location_uri: s3 location dict or string\n    :param string logical_id: logical_id of the resource calling this function\n    :param string property_name: name of the property which is used as an input to this function.\n    :returns: a Code dict, containing the S3 Bucket, Key, and Version of the Lambda layer code\n    :rtype: dict"
  },
  {
    "code": "def _pys_assert_version(self, line):\n        if float(line.strip()) > 1.0:\n            msg = _(\"File version {version} unsupported (>1.0).\").format(\n                version=line.strip())\n            raise ValueError(msg)",
    "docstring": "Asserts pys file version"
  },
  {
    "code": "def split_result_of_axis_func_pandas(axis, num_splits, result, length_list=None):\n    if num_splits == 1:\n        return result\n    if length_list is not None:\n        length_list.insert(0, 0)\n        sums = np.cumsum(length_list)\n        if axis == 0:\n            return [result.iloc[sums[i] : sums[i + 1]] for i in range(len(sums) - 1)]\n        else:\n            return [result.iloc[:, sums[i] : sums[i + 1]] for i in range(len(sums) - 1)]\n    chunksize = compute_chunksize(result, num_splits, axis=axis)\n    if axis == 0:\n        return [\n            result.iloc[chunksize * i : chunksize * (i + 1)] for i in range(num_splits)\n        ]\n    else:\n        return [\n            result.iloc[:, chunksize * i : chunksize * (i + 1)]\n            for i in range(num_splits)\n        ]",
    "docstring": "Split the Pandas result evenly based on the provided number of splits.\n\n    Args:\n        axis: The axis to split across.\n        num_splits: The number of even splits to create.\n        result: The result of the computation. This should be a Pandas\n            DataFrame.\n        length_list: The list of lengths to split this DataFrame into. This is used to\n            return the DataFrame to its original partitioning schema.\n\n    Returns:\n        A list of Pandas DataFrames."
  },
  {
    "code": "def load_from_file(self, path):\n        with open(path) as inf:\n            data = inf.read()\n            if data:\n                items = json.loads(data)\n            else:\n                items = {}\n        for item in items:\n            extra = dict((x, y) for x, y in item.items()\n                         if x not in ['name', 'value', 'domain'])\n            self.set(item['name'], item['value'], item['domain'], **extra)",
    "docstring": "Load cookies from the file.\n\n        Content of file should be a JSON-serialized list of dicts."
  },
  {
    "code": "def pdf(self, resource_id):\n        self.resource_id(str(resource_id))\n        self._request_uri = '{}/pdf'.format(self._request_uri)",
    "docstring": "Update the request URI to get the pdf for this resource.\n\n        Args:\n            resource_id (integer): The group id."
  },
  {
    "code": "def removeAllChildrenAtIndex(self, parentIndex):\n        if not parentIndex.isValid():\n            logger.debug(\"No valid item selected for deletion (ignored).\")\n            return\n        parentItem = self.getItem(parentIndex, None)\n        logger.debug(\"Removing children of {!r}\".format(parentItem))\n        assert parentItem, \"parentItem not found\"\n        self.beginRemoveRows(parentIndex, 0, parentItem.nChildren()-1)\n        try:\n            parentItem.removeAllChildren()\n        finally:\n            self.endRemoveRows()\n        logger.debug(\"removeAllChildrenAtIndex completed\")",
    "docstring": "Removes all children of the item at the parentIndex.\n            The children's finalize method is called before removing them to give them a\n            chance to close their resources"
  },
  {
    "code": "def _init_ws(n_items, comparisons, prior_inv, tau, nu):\n    prec = np.zeros((n_items, n_items))\n    xs = np.zeros(n_items)\n    for i, (a, b) in enumerate(comparisons):\n        prec[(a, a, b, b), (a, b, a, b)] += tau[i] * MAT_ONE_FLAT \n        xs[a] += nu[i]\n        xs[b] -= nu[i]\n    cov = inv_posdef(prior_inv + prec)\n    mean = cov.dot(xs)\n    return mean, cov, xs , prec",
    "docstring": "Initialize parameters in the weight space."
  },
  {
    "code": "def sign(self, h):\n        if not self.is_private():\n            raise RuntimeError(\"Key must be private to be able to sign\")\n        val = from_bytes_32(h)\n        r, s = self._generator.sign(self.secret_exponent(), val)\n        return sigencode_der(r, s)",
    "docstring": "Return a der-encoded signature for a hash h.\n        Will throw a RuntimeError if this key is not a private key"
  },
  {
    "code": "def store_checksums(dataset_name, sizes_checksums):\n  path = _get_path(dataset_name)\n  original_data = _get_sizes_checksums(path)\n  new_data = original_data.copy()\n  new_data.update(sizes_checksums)\n  if original_data == new_data:\n    return\n  with tf.io.gfile.GFile(path, 'w') as f:\n    for url, (size, checksum) in sorted(new_data.items()):\n      f.write('%s %s %s\\n' % (url, size, checksum))",
    "docstring": "Store given checksums and sizes for specific dataset.\n\n  Content of file is never disgarded, only updated. This is to ensure that if\n  process is killed right after first download finishes, checksums registered\n  during previous runs aren't lost.\n\n  It is the responsibility of the caller not to call function multiple times in\n  parallel for a given dataset.\n\n  Only original file content is updated. This means the entire set of new sizes\n  and checksums must be given at every call.\n\n  Args:\n    dataset_name: string.\n    sizes_checksums: dict, {url: (size_in_bytes, checksum)}."
  },
  {
    "code": "def prepare_release(ver=None):\n    write_changelog(True)\n    if ver is None:\n        ver = next_release()\n    print('saving updates to ChangeLog')\n    run('git commit ChangeLog -m \"[RELEASE] Update to version v{}\"'.format(ver), hide=True)\n    sha = run('git log -1 --pretty=format:\"%h\"', hide=True).stdout\n    run('git tag -a \"{ver}\" -m \"version {ver}\" {sha}'.format(ver=ver, sha=sha), hide=True)\n    package()\n    write_changelog()\n    run('git tag -d {}'.format(ver), hide=True)\n    run('git commit --all --amend --no-edit', hide=True)",
    "docstring": "Prepare release artifacts"
  },
  {
    "code": "def pop_key(self, arg, key, *args, **kwargs):\n        return self.unfinished_arguments[arg].pop(key, *args, **kwargs)",
    "docstring": "Delete a previously defined key for the `add_argument`"
  },
  {
    "code": "def dump(self, output, close_after_write=True):\n        try:\n            output.write\n            self.stream = output\n        except AttributeError:\n            self.stream = io.open(output, \"w\", encoding=\"utf-8\")\n        try:\n            self.write_table()\n        finally:\n            if close_after_write:\n                self.stream.close()\n                self.stream = sys.stdout",
    "docstring": "Write data to the output with tabular format.\n\n        Args:\n            output (file descriptor or str):\n                file descriptor or path to the output file.\n            close_after_write (bool, optional):\n                Close the output after write.\n                Defaults to |True|."
  },
  {
    "code": "def _create_batches(self, instances: Iterable[Instance], shuffle: bool) -> Iterable[Batch]:\n        raise NotImplementedError",
    "docstring": "This method should return one epoch worth of batches."
  },
  {
    "code": "def reload(self, index):\r\n        finfo = self.data[index]\r\n        txt, finfo.encoding = encoding.read(finfo.filename)\r\n        finfo.lastmodified = QFileInfo(finfo.filename).lastModified()\r\n        position = finfo.editor.get_position('cursor')\r\n        finfo.editor.set_text(txt)\r\n        finfo.editor.document().setModified(False)\r\n        finfo.editor.document().changed_since_autosave = False\r\n        finfo.editor.set_cursor_position(position)\r\n        finfo.editor.rehighlight()\r\n        self._refresh_outlineexplorer(index)",
    "docstring": "Reload file from disk"
  },
  {
    "code": "def is_client_ip_address_blacklisted(request: AxesHttpRequest) -> bool:\n    if is_ip_address_in_blacklist(request.axes_ip_address):\n        return True\n    if settings.AXES_ONLY_WHITELIST and not is_ip_address_in_whitelist(request.axes_ip_address):\n        return True\n    return False",
    "docstring": "Check if the given request refers to a blacklisted IP."
  },
  {
    "code": "def bind(self, **config):\n        while self.unbound_types:\n            typedef = self.unbound_types.pop()\n            try:\n                load, dump = typedef.bind(self, **config)\n                self.bound_types[typedef] = {\n                    \"load\": load, \"dump\": dump\n                }\n            except Exception:\n                self.unbound_types.add(typedef)\n                raise",
    "docstring": "Bind all unbound types to the engine.\n\n        Bind each unbound typedef to the engine, passing in the engine and\n        :attr:`config`.  The resulting ``load`` and ``dump`` functions can\n        be found under ``self.bound_types[typedef][\"load\"]`` and\n        ``self.bound_types[typedef][\"dump\"], respectively.\n\n        Parameters\n        ----------\n        config : dict, optional\n            Engine-binding configuration to pass to each typedef that will be\n            bound.  Examples include floating-point precision values, maximum\n            lengths for strings, or any other translation constraints/settings\n            that a typedef needs to construct a load/dump function pair."
  },
  {
    "code": "def ping(self):\n        if not self.conn:\n            self.connect()\n        self.conn.send('PING', time.time())\n        cmd, payload = self.conn.recv()\n        recv_ts = time.time()\n        if cmd != 'PONG':\n            raise Exception(\"Invalid response from server\")\n        return recv_ts - payload[0]",
    "docstring": "Ping the server.  Returns the time interval, in seconds,\n        required for the server to respond to the PING message."
  },
  {
    "code": "def load_from_json(db_file, language=DEFAULT_LANG):\n        raw = json.loads(file(db_file).read())\n        data = {\n            '_id': raw['id'],\n            'title': raw['title'],\n            'description': DBVuln.handle_ref(raw['description'], language=language),\n            'severity': raw['severity'],\n            'wasc': raw.get('wasc', []),\n            'tags': raw.get('tags', []),\n            'cwe': raw.get('cwe', []),\n            'owasp_top_10': raw.get('owasp_top_10', {}),\n            'fix_effort': raw['fix']['effort'],\n            'fix_guidance': DBVuln.handle_ref(raw['fix']['guidance'], language=language),\n            'references': DBVuln.handle_references(raw.get('references', [])),\n            'db_file': db_file,\n        }\n        return data",
    "docstring": "Parses the JSON data and returns it\n\n        :param db_file: File and path pointing to the JSON file to parse\n        :param language: The user's language (en, es, etc.)\n        :raises: All kind of exceptions if the file doesn't exist or JSON is\n                 invalid.\n        :return: None"
  },
  {
    "code": "def out(self):\n        out = \"\"\n        if self.use_sentinel:\n            out += sentinel_var + \" = _coconut.object()\\n\"\n        closes = 0\n        for checks, defs in self.checkdefs:\n            if checks:\n                out += \"if \" + paren_join(checks, \"and\") + \":\\n\" + openindent\n                closes += 1\n            if defs:\n                out += \"\\n\".join(defs) + \"\\n\"\n        return out + (\n            self.check_var + \" = True\\n\"\n            + closeindent * closes\n            + \"\".join(other.out() for other in self.others)\n            + (\n                \"if \" + self.check_var + \" and not (\"\n                + paren_join(self.guards, \"and\")\n                + \"):\\n\" + openindent\n                + self.check_var + \" = False\\n\" + closeindent\n                if self.guards else \"\"\n            )\n        )",
    "docstring": "Return pattern-matching code."
  },
  {
    "code": "def _configure_logger_handler(cls, log_dest, log_filename):\n        if log_dest is None:\n            return None\n        msg_format = '%(asctime)s-%(name)s-%(message)s'\n        if log_dest == 'stderr':\n            handler = logging.StreamHandler()\n            handler.setFormatter(logging.Formatter(msg_format))\n        elif log_dest == 'file':\n            if not log_filename:\n                raise ValueError(\"Log filename is required if log destination \"\n                                 \"is 'file'\")\n            handler = logging.FileHandler(log_filename, encoding=\"UTF-8\")\n            handler.setFormatter(logging.Formatter(msg_format))\n        else:\n            raise ValueError(\n                _format(\"Invalid log destination: {0!A}; Must be one of: \"\n                        \"{1!A}\", log_dest, LOG_DESTINATIONS))\n        return handler",
    "docstring": "Return a logging handler for the specified `log_dest`, or `None` if\n        `log_dest` is `None`."
  },
  {
    "code": "def log(self, level, msg, *args, **kwargs):\n    if level >= logging.FATAL:\n      extra = kwargs.setdefault('extra', {})\n      extra[_ABSL_LOG_FATAL] = True\n    super(ABSLLogger, self).log(level, msg, *args, **kwargs)",
    "docstring": "Logs a message at a cetain level substituting in the supplied arguments.\n\n    This method behaves differently in python and c++ modes.\n\n    Args:\n      level: int, the standard logging level at which to log the message.\n      msg: str, the text of the message to log.\n      *args: The arguments to substitute in the message.\n      **kwargs: The keyword arguments to substitute in the message."
  },
  {
    "code": "def find_vm_by_name(self, si, path, name):\n        return self.find_obj_by_path(si, path, name, self.VM)",
    "docstring": "Finds vm in the vCenter or returns \"None\"\n\n        :param si:         pyvmomi 'ServiceInstance'\n        :param path:       the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')\n        :param name:       the vm name to return"
  },
  {
    "code": "def add_net(self, net):\n        self.sanity_check_net(net)\n        self.logic.add(net)",
    "docstring": "Add a net to the logic of the block.\n\n        The passed net, which must be of type LogicNet, is checked and then\n        added to the block.  No wires are added by this member, they must be\n        added seperately with add_wirevector."
  },
  {
    "code": "def _media(self):\n        css = ['markymark/css/markdown-editor.css']\n        iconlibrary_css = getattr(\n            settings,\n            'MARKYMARK_FONTAWESOME_CSS',\n            'markymark/fontawesome/fontawesome.min.css'\n        )\n        if iconlibrary_css:\n            css.append(iconlibrary_css)\n        media = forms.Media(\n            css={'all': css},\n            js=('markymark/js/markdown-editor.js',)\n        )\n        renderer = initialize_renderer()\n        for extension in renderer.registeredExtensions:\n            if hasattr(extension, 'media'):\n                media += extension.media\n        return media",
    "docstring": "Returns a forms.Media instance with the basic editor media and media\n        from all registered extensions."
  },
  {
    "code": "def initrepo(repopath, bare, shared):\n    ag = activegit.ActiveGit(repopath, bare=bare, shared=shared)",
    "docstring": "Initialize an activegit repo. \n    Default makes base shared repo that should be cloned for users"
  },
  {
    "code": "def sysmeta_add_preferred(sysmeta_pyxb, node_urn):\n    if not has_replication_policy(sysmeta_pyxb):\n        sysmeta_set_default_rp(sysmeta_pyxb)\n    rp_pyxb = sysmeta_pyxb.replicationPolicy\n    _add_node(rp_pyxb, 'pref', node_urn)\n    _remove_node(rp_pyxb, 'block', node_urn)",
    "docstring": "Add a remote Member Node to the list of preferred replication targets to this\n    System Metadata object.\n\n    Also remove the target MN from the list of blocked Member Nodes if present.\n\n    If the target MN is already in the preferred list and not in the blocked list, this\n    function is a no-op.\n\n    Args:\n      sysmeta_pyxb : SystemMetadata PyXB object.\n        System Metadata in which to add the preferred replication target.\n\n        If the System Metadata does not already have a Replication Policy, a default\n        replication policy which enables replication is added and populated with the\n        preferred replication target.\n\n      node_urn : str\n        Node URN of the remote MN that will be added. On the form\n       ``urn:node:MyMemberNode``."
  },
  {
    "code": "def output_json(gandi, format, value):\n    if format == 'json':\n        gandi.echo(json.dumps(value, default=date_handler, sort_keys=True))\n    elif format == 'pretty-json':\n        gandi.echo(json.dumps(value, default=date_handler, sort_keys=True,\n                              indent=2, separators=(',', ': ')))",
    "docstring": "Helper to show json output"
  },
  {
    "code": "def convert_field_to_html(cr, table, field_name, html_field_name):\n    if version_info[0] < 7:\n        logger.error(\"You cannot use this method in an OpenUpgrade version \"\n                     \"prior to 7.0.\")\n        return\n    cr.execute(\n        \"SELECT id, %(field)s FROM %(table)s WHERE %(field)s IS NOT NULL\" % {\n            'field': field_name,\n            'table': table,\n        }\n    )\n    for row in cr.fetchall():\n        logged_query(\n            cr, \"UPDATE %(table)s SET %(field)s = %%s WHERE id = %%s\" % {\n                'field': html_field_name,\n                'table': table,\n            }, (plaintext2html(row[1]), row[0])\n        )",
    "docstring": "Convert field value to HTML value.\n\n    .. versionadded:: 7.0"
  },
  {
    "code": "def check_tweet(tweet, validation_checking=False):\n    if \"id\" not in tweet:\n        raise NotATweetError(\"This text has no 'id' key\")\n    original_format = is_original_format(tweet)\n    if original_format:\n        _check_original_format_tweet(tweet, validation_checking=validation_checking)\n    else:\n        _check_activity_streams_tweet(tweet, validation_checking=validation_checking)\n    return original_format",
    "docstring": "Ensures a tweet is valid and determines the type of format for the tweet.\n\n    Args:\n        tweet (dict/Tweet): the tweet payload\n        validation_checking (bool): check for valid key structure in a tweet."
  },
  {
    "code": "def adopt(self):\n        valid_relationships = set(Relationship._instances.keys())\n        relationships = [\n            (parent, relation.complement(), term.id)\n                for term in six.itervalues(self.terms)\n                    for relation in term.relations\n                        for parent in term.relations[relation]\n                            if relation.complementary\n                                and relation.complementary in valid_relationships\n        ]\n        relationships.sort(key=operator.itemgetter(2))\n        for parent, rel, child in relationships:\n            if rel is None:\n                break\n            try:\n                parent = parent.id\n            except AttributeError:\n                pass\n            if parent in self.terms:\n                try:\n                    if child not in self.terms[parent].relations[rel]:\n                        self.terms[parent].relations[rel].append(child)\n                except KeyError:\n                    self[parent].relations[rel] = [child]\n        del relationships",
    "docstring": "Make terms aware of their children.\n\n        This is done automatically when using the `~Ontology.merge` and\n        `~Ontology.include` methods as well as the `~Ontology.__init__`\n        method, but it should be called in case of manual editing of the\n        parents or children of a `Term`."
  },
  {
    "code": "def ring_coding(array):\n    n = len(array)\n    codes = np.ones(n, dtype=Path.code_type) * Path.LINETO\n    codes[0] = Path.MOVETO\n    codes[-1] = Path.CLOSEPOLY\n    return codes",
    "docstring": "Produces matplotlib Path codes for exterior and interior rings\n    of a polygon geometry."
  },
  {
    "code": "def next(self):\n        if not self.cursor:\n            self.cursor = self.coll_handle.find().sort([(\"ts\", ASCENDING)])\n        doc = self.cursor.next()\n        doc['thread'] = self.name\n        le = LogEvent(doc)\n        return le",
    "docstring": "Make iterators."
  },
  {
    "code": "def _ConvertBool(value, require_str):\n  if require_str:\n    if value == 'true':\n      return True\n    elif value == 'false':\n      return False\n    else:\n      raise ParseError('Expected \"true\" or \"false\", not {0}.'.format(value))\n  if not isinstance(value, bool):\n    raise ParseError('Expected true or false without quotes.')\n  return value",
    "docstring": "Convert a boolean value.\n\n  Args:\n    value: A scalar value to convert.\n    require_str: If True, value must be a str.\n\n  Returns:\n    The bool parsed.\n\n  Raises:\n    ParseError: If a boolean value couldn't be consumed."
  },
  {
    "code": "def stop_app(self, callback_function_param=False):\n        self.logger.info(\"Receiver:Stopping current app '%s'\", self.app_id)\n        return self.send_message(\n            {MESSAGE_TYPE: 'STOP'},\n            inc_session_id=True, callback_function=callback_function_param)",
    "docstring": "Stops the current running app on the Chromecast."
  },
  {
    "code": "def getBehavior(name, id=None):\n    name = name.upper()\n    if name in __behaviorRegistry:\n        if id:\n            for n, behavior in __behaviorRegistry[name]:\n                if n == id:\n                    return behavior\n        return __behaviorRegistry[name][0][1]\n    return None",
    "docstring": "Return a matching behavior if it exists, or None.\n\n    If id is None, return the default for name."
  },
  {
    "code": "def check_predefined_conditions():\n    try:\n        node_info = current_k8s_corev1_api_client.list_node()\n        for node in node_info.items:\n            for condition in node.status.conditions:\n                if not condition.status:\n                    return False\n    except ApiException as e:\n        log.error('Something went wrong while getting node information.')\n        log.error(e)\n        return False\n    return True",
    "docstring": "Check k8s predefined conditions for the nodes."
  },
  {
    "code": "def check():\n    dist_path = Path(DIST_PATH)\n    if not dist_path.exists() or not list(dist_path.glob('*')):\n        print(\"No distribution files found. Please run 'build' command first\")\n        return\n    subprocess.check_call(['twine', 'check', 'dist/*'])",
    "docstring": "Checks the long description."
  },
  {
    "code": "def get_previous_character(self):\n        cursor = self.textCursor()\n        cursor.movePosition(QTextCursor.PreviousCharacter, QTextCursor.KeepAnchor)\n        return cursor.selectedText()",
    "docstring": "Returns the character before the cursor.\n\n        :return: Previous cursor character.\n        :rtype: QString"
  },
  {
    "code": "def dispatch(argdict):\n    cmd = argdict['command']\n    ftc = getattr(THIS_MODULE, 'do_'+cmd)\n    ftc(argdict)",
    "docstring": "Call the command-specific function, depending on the command."
  },
  {
    "code": "def _reset_errors(self, msg=None):\n        if msg is not None and msg in self._errors:\n            del self._errors[msg]\n        else:\n            self._errors = {}",
    "docstring": "Resets the logging throttle cache, so the next error is emitted\n        regardless of the value in `self.server_error_interval`\n\n        :param msg: if present, only this key is reset. Otherwise, the whole\n            cache is cleaned."
  },
  {
    "code": "def _cli_main(args=None):\n    arguments = _parse_arguments(args)\n    _remove_none_values(arguments)\n    verbosity = min(arguments.pop('verbose'), 4)\n    levels = [logging.ERROR,\n              logging.WARNING,\n              logging.INFO,\n              logging.DEBUG,\n              TRACE_LEVEL]\n    arguments.setdefault('debug_level', levels[verbosity])\n    with open_tunnel(**arguments) as tunnel:\n        if tunnel.is_alive:\n            input_(\n)",
    "docstring": "Pass input arguments to open_tunnel\n\n        Mandatory: ssh_address, -R (remote bind address list)\n\n        Optional:\n        -U (username) we may gather it from SSH_CONFIG_FILE or current username\n        -p (server_port), defaults to 22\n        -P (password)\n        -L (local_bind_address), default to 0.0.0.0:22\n        -k (ssh_host_key)\n        -K (private_key_file), may be gathered from SSH_CONFIG_FILE\n        -S (private_key_password)\n        -t (threaded), allow concurrent connections over tunnels\n        -v (verbose), up to 3 (-vvv) to raise loglevel from ERROR to DEBUG\n        -V (version)\n        -x (proxy), ProxyCommand's IP:PORT, may be gathered from config file\n        -c (ssh_config), ssh configuration file (defaults to SSH_CONFIG_FILE)\n        -z (compress)\n        -n (noagent), disable looking for keys from an Agent\n        -d (host_pkey_directories), look for keys on these folders"
  },
  {
    "code": "def straight_line_show(title, length=100, linestyle=\"=\", pad=0):\n        print(StrTemplate.straight_line(\n            title=title, length=length, linestyle=linestyle, pad=pad))",
    "docstring": "Print a formatted straight line."
  },
  {
    "code": "def __set_rate_type(self, value):\n        if value not in [RATE_TYPE_FIXED, RATE_TYPE_PERCENTAGE]:\n            raise ValueError(\"Invalid rate type.\")\n        self.__rate_type = value",
    "docstring": "Sets the rate type.\n        @param value:str"
  },
  {
    "code": "async def run_action(self, action_name, **params):\n        action_facade = client.ActionFacade.from_connection(self.connection)\n        log.debug('Starting action `%s` on %s', action_name, self.name)\n        res = await action_facade.Enqueue([client.Action(\n            name=action_name,\n            parameters=params,\n            receiver=self.tag,\n        )])\n        action = res.results[0].action\n        error = res.results[0].error\n        if error and error.code == 'not found':\n            raise ValueError('Action `%s` not found on %s' % (action_name,\n                                                              self.name))\n        elif error:\n            raise Exception('Unknown action error: %s' % error.serialize())\n        action_id = action.tag[len('action-'):]\n        log.debug('Action started as %s', action_id)\n        return await self.model._wait_for_new('action', action_id)",
    "docstring": "Run an action on this unit.\n\n        :param str action_name: Name of action to run\n        :param **params: Action parameters\n        :returns: A :class:`juju.action.Action` instance.\n\n        Note that this only enqueues the action.  You will need to call\n        ``action.wait()`` on the resulting `Action` instance if you wish\n        to block until the action is complete."
  },
  {
    "code": "def update(self):\n        ring = self._fetch()\n        n_replicas = len(ring)\n        replica_set = set([r[1] for r in self.replicas])\n        self.ranges = []\n        for n, (start, replica) in enumerate(ring):\n            if replica in replica_set:\n                end = ring[(n+1) % n_replicas][0] % RING_SIZE\n                if start < end:\n                    self.ranges.append((start, end))\n                elif end < start:\n                    self.ranges.append((start, RING_SIZE))\n                    self.ranges.append((0, end))\n                else:\n                    self.ranges.append((0, RING_SIZE))",
    "docstring": "Fetches the updated ring from Redis and updates the current ranges."
  },
  {
    "code": "def validate(self, graph):\n        if not nx.is_directed_acyclic_graph(graph):\n            raise DirectedAcyclicGraphInvalid(graph_name=self._name)",
    "docstring": "Validate the graph by checking whether it is a directed acyclic graph.\n\n        Args:\n            graph (DiGraph): Reference to a DiGraph object from NetworkX.\n\n        Raises:\n            DirectedAcyclicGraphInvalid: If the graph is not a valid dag."
  },
  {
    "code": "def validate_request(self,\n                         data: Any,\n                         *additional: AnyMapping,\n                         merged_class: Type[dict] = dict) -> Any:\n        r\n        request_schema = getattr(self.module, 'request', None)\n        if request_schema is None:\n            logger.error(\n                'Request schema should be defined',\n                extra={'schema_module': self.module,\n                       'schema_module_attrs': dir(self.module)})\n            raise self.make_error('Request schema should be defined')\n        if isinstance(data, dict) and additional:\n            data = merged_class(self._merge_data(data, *additional))\n        try:\n            self._validate(data, request_schema)\n        finally:\n            self._valid_request = False\n        self._valid_request = True\n        processor = getattr(self.module, 'request_processor', None)\n        return processor(data) if processor else data",
    "docstring": "r\"\"\"Validate request data against request schema from module.\n\n        :param data: Request data.\n        :param \\*additional:\n            Additional data dicts to be merged with base request data.\n        :param merged_class:\n            When additional data dicts supplied method by default will return\n            merged **dict** with all data, but you can customize things to\n            use read-only dict or any other additional class or callable."
  },
  {
    "code": "def glyph_metrics_stats(ttFont):\n  glyph_metrics = ttFont['hmtx'].metrics\n  ascii_glyph_names = [ttFont.getBestCmap()[c] for c in range(32, 128)\n                       if c in ttFont.getBestCmap()]\n  ascii_widths = [adv for name, (adv, lsb) in glyph_metrics.items()\n                  if name in ascii_glyph_names]\n  ascii_width_count = Counter(ascii_widths)\n  ascii_most_common_width = ascii_width_count.most_common(1)[0][1]\n  seems_monospaced = ascii_most_common_width >= len(ascii_widths) * 0.8\n  width_max = max([adv for k, (adv, lsb) in glyph_metrics.items()])\n  most_common_width = Counter(glyph_metrics.values()).most_common(1)[0][0][0]\n  return {\n      \"seems_monospaced\": seems_monospaced,\n      \"width_max\": width_max,\n      \"most_common_width\": most_common_width,\n  }",
    "docstring": "Returns a dict containing whether the font seems_monospaced,\n  what's the maximum glyph width and what's the most common width.\n\n  For a font to be considered monospaced, at least 80% of\n  the ascii glyphs must have the same width."
  },
  {
    "code": "def print_version(self):\n        if not self._version:\n            return self\n        if not self._title:\n            print('  %s %s' % (self._name, self._version))\n            return self\n        print('  %s (%s %s)' % (self._title, self._name, self._version))\n        return self",
    "docstring": "Print the program version."
  },
  {
    "code": "def find_tag_by_name(repo, tag_name, safe=True):\n    tagfmt = 'tags/{ref}'.format(ref=tag_name)\n    try:\n        ref = repo.get_git_ref(tagfmt)\n        if ref and ref.ref:\n            return ref\n    except github.UnknownObjectException:\n        if not safe:\n            raise\n    return None",
    "docstring": "Find tag by name in a github Repository\n\n    Parameters\n    ----------\n    repo: :class:`github.Repository` instance\n\n    tag_name: str\n        Short name of tag (not a fully qualified ref).\n\n    safe: bool, optional\n        Defaults to `True`. When `True`, `None` is returned on failure. When\n        `False`, an exception will be raised upon failure.\n\n    Returns\n    -------\n    gh : :class:`github.GitRef` instance or `None`\n\n    Raises\n    ------\n    github.UnknownObjectException\n        If git tag name does not exist in repo."
  },
  {
    "code": "def init_attachment_cache(self):\n        if self.request.method == 'GET':\n            attachments_cache.delete(self.get_attachments_cache_key(self.request))\n            return\n        attachments_cache_key = self.get_attachments_cache_key(self.request)\n        restored_attachments_dict = attachments_cache.get(attachments_cache_key)\n        if restored_attachments_dict:\n            restored_attachments_dict.update(self.request.FILES)\n            self.request._files = restored_attachments_dict\n        if self.request.FILES:\n            attachments_cache.set(attachments_cache_key, self.request.FILES)",
    "docstring": "Initializes the attachment cache for the current view."
  },
  {
    "code": "def recycle():\n    for service in cache.iter_keys('th_*'):\n        try:\n            service_value = cache.get(service, version=2)\n            cache.set(service, service_value)\n            cache.delete_pattern(service, version=2)\n        except ValueError:\n            pass\n    logger.info('recycle of cache done!')",
    "docstring": "the purpose of this tasks is to recycle the data from the cache\n        with version=2 in the main cache"
  },
  {
    "code": "def cmd(self, argv):\n        assert isinstance(argv, (list, tuple)), \\\n                \"'argv' is not a sequence: %r\" % argv\n        retval = None\n        try:\n            argv = self.precmd(argv)\n            retval = self.onecmd(argv)\n            self.postcmd(argv)\n        except:\n            if not self.cmdexc(argv):\n                raise\n            retval = 1\n        return retval",
    "docstring": "Run one command and exit.\n\n            \"argv\" is the arglist for the command to run. argv[0] is the\n                command to run. If argv is an empty list then the\n                'emptyline' handler is run.\n\n        Returns the return value from the command handler."
  },
  {
    "code": "def add_nodes(self, nodes, attr_dict=None, **attr):\n        attr_dict = self._combine_attribute_arguments(attr_dict, attr)\n        for node in nodes:\n            if type(node) is tuple:\n                new_node, node_attr_dict = node\n                new_dict = attr_dict.copy()\n                new_dict.update(node_attr_dict)\n                self.add_node(new_node, new_dict)\n            else:\n                self.add_node(node, attr_dict.copy())",
    "docstring": "Adds multiple nodes to the graph, along with any related attributes\n            of the nodes.\n\n        :param nodes: iterable container to either references of the nodes\n                    OR tuples of (node reference, attribute dictionary);\n                    if an attribute dictionary is provided in the tuple,\n                    its values will override both attr_dict's and attr's\n                    values.\n        :param attr_dict: dictionary of attributes shared by all the nodes.\n        :param attr: keyword arguments of attributes of the node;\n                    attr's values will override attr_dict's values\n                    if both are provided.\n\n        See also:\n        add_node\n\n        Examples:\n        ::\n\n            >>> H = DirectedHypergraph()\n            >>> attributes = {label: \"positive\"}\n            >>> node_list = [\"A\",\n                             (\"B\", {label=\"negative\"}),\n                             (\"C\", {root=True})]\n            >>> H.add_nodes(node_list, attributes)"
  },
  {
    "code": "def _printable_id_code(self):\n        code = super(ISWCCode, self)._printable_id_code()\n        code1 = code[:3]\n        code2 = code[3:6]\n        code3 = code[-3:]\n        return '%s.%s.%s' % (code1, code2, code3)",
    "docstring": "Returns the code in a printable form, separating it into groups of\n        three characters using a point between them.\n\n        :return: the ID code in a printable form"
  },
  {
    "code": "def can_add_new_content(self, block, file_info):\n        return ((self._max_files_per_container == 0 or self._max_files_per_container > len(block.content_file_infos))\n                and (self.does_content_fit(file_info, block)\n                     or\n                     (block.content_size < self._max_container_content_size_in_bytes\n                      and (self._should_split_small_files or not self._is_small_file(file_info)))))",
    "docstring": "new content from file_info can be added into block iff\n        - file count limit hasn't been reached for the block\n        - there is enough space to completely fit the info into the block\n        - OR the info can be split and some info can fit into the block"
  },
  {
    "code": "def as_dict(self, use_preliminary=False):\n        config = dict()\n        for key in self.config.keys:\n            if use_preliminary and key in self.preliminary_config:\n                value = self.preliminary_config[key]\n            else:\n                value = self.config.get_config_value(key)\n            config[key] = value\n        return config",
    "docstring": "Create a copy of the config in form of a dict\n\n        :param bool use_preliminary: Whether to include the preliminary config\n        :return: A dict with the copy of the config\n        :rtype: dict"
  },
  {
    "code": "def info(verbose):\n    if _get_mongopatcher().manifest.is_initialized():\n        print('Datamodel version: %s' % _get_mongopatcher().manifest.version)\n        if verbose:\n            print('\\nUpdate history:')\n            for update in reversed(_get_mongopatcher().manifest.history):\n                reason = update.get('reason')\n                reason = '(%s)' % reason if reason else ''\n                print(' - %s: %s %s' % (update['timestamp'], update['version'],\n                                        reason))\n    else:\n        print('Datamodel is not initialized')",
    "docstring": "Show version of the datamodel"
  },
  {
    "code": "def get_es(self, default_builder=get_es):\n        return super(S, self).get_es(default_builder=default_builder)",
    "docstring": "Returns the elasticsearch Elasticsearch object to use.\n\n        This uses the django get_es builder by default which takes\n        into account settings in ``settings.py``."
  },
  {
    "code": "def groups_replies(self, *, channel: str, thread_ts: str, **kwargs) -> SlackResponse:\n        self._validate_xoxp_token()\n        kwargs.update({\"channel\": channel, \"thread_ts\": thread_ts})\n        return self.api_call(\"groups.replies\", http_verb=\"GET\", params=kwargs)",
    "docstring": "Retrieve a thread of messages posted to a private channel\n\n        Args:\n            channel (str): The channel id. e.g. 'C1234567890'\n            thread_ts (str): The timestamp of an existing message with 0 or more replies.\n                e.g. '1234567890.123456'"
  },
  {
    "code": "def on(self, event_name, *args, **kwargs):\n        def decorator(f):\n            self.add_event_handler(event_name, f, *args, **kwargs)\n            return f\n        return decorator",
    "docstring": "Decorator shortcut for add_event_handler.\n\n        Args:\n            event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events` or\n                any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.\n            *args: optional args to be passed to `handler`.\n            **kwargs: optional keyword args to be passed to `handler`."
  },
  {
    "code": "def write_chunk(outfile, tag, data=b''):\n    data = bytes(data)\n    outfile.write(struct.pack(\"!I\", len(data)))\n    outfile.write(tag)\n    outfile.write(data)\n    checksum = zlib.crc32(tag)\n    checksum = zlib.crc32(data, checksum)\n    checksum &= 2 ** 32 - 1\n    outfile.write(struct.pack(\"!I\", checksum))",
    "docstring": "Write a PNG chunk to the output file, including length and\n    checksum."
  },
  {
    "code": "def copy_openapi_specs(output_path, component):\n    if component == 'reana-server':\n        file = 'reana_server.json'\n    elif component == 'reana-workflow-controller':\n        file = 'reana_workflow_controller.json'\n    elif component == 'reana-job-controller':\n        file = 'reana_job_controller.json'\n    if os.environ.get('REANA_SRCDIR'):\n        reana_srcdir = os.environ.get('REANA_SRCDIR')\n    else:\n        reana_srcdir = os.path.join('..')\n    try:\n        reana_commons_specs_path = os.path.join(\n            reana_srcdir,\n            'reana-commons',\n            'reana_commons',\n            'openapi_specifications')\n        if os.path.exists(reana_commons_specs_path):\n            if os.path.isfile(output_path):\n                shutil.copy(output_path,\n                            os.path.join(reana_commons_specs_path,\n                                         file))\n                shutil.copy(output_path,\n                            os.path.join('docs', 'openapi.json'))\n    except Exception as e:\n        click.echo('Something went wrong, could not copy openapi '\n                   'specifications to reana-commons \\n{0}'.format(e))",
    "docstring": "Copy generated and validated openapi specs to reana-commons module."
  },
  {
    "code": "def get_src_address_from_data(self, decoded=True):\n        src_address_label = next((lbl for lbl in self.message_type if lbl.field_type\n                                  and lbl.field_type.function == FieldType.Function.SRC_ADDRESS), None)\n        if src_address_label:\n            start, end = self.get_label_range(src_address_label, view=1, decode=decoded)\n            if decoded:\n                src_address = self.decoded_hex_str[start:end]\n            else:\n                src_address = self.plain_hex_str[start:end]\n        else:\n            src_address = None\n        return src_address",
    "docstring": "Return the SRC address of a message if SRC_ADDRESS label is present in message type of the message\n        Return None otherwise\n\n        :param decoded:\n        :return:"
  },
  {
    "code": "def difference(self, other, sort=None):\n        self._validate_sort_keyword(sort)\n        self._assert_can_do_setop(other)\n        if self.equals(other):\n            return self._shallow_copy(self._data[:0])\n        other, result_name = self._convert_can_do_setop(other)\n        this = self._get_unique_index()\n        indexer = this.get_indexer(other)\n        indexer = indexer.take((indexer != -1).nonzero()[0])\n        label_diff = np.setdiff1d(np.arange(this.size), indexer,\n                                  assume_unique=True)\n        the_diff = this.values.take(label_diff)\n        if sort is None:\n            try:\n                the_diff = sorting.safe_sort(the_diff)\n            except TypeError:\n                pass\n        return this._shallow_copy(the_diff, name=result_name, freq=None)",
    "docstring": "Return a new Index with elements from the index that are not in\n        `other`.\n\n        This is the set difference of two Index objects.\n\n        Parameters\n        ----------\n        other : Index or array-like\n        sort : False or None, default None\n            Whether to sort the resulting index. By default, the\n            values are attempted to be sorted, but any TypeError from\n            incomparable elements is caught by pandas.\n\n            * None : Attempt to sort the result, but catch any TypeErrors\n              from comparing incomparable elements.\n            * False : Do not sort the result.\n\n            .. versionadded:: 0.24.0\n\n            .. versionchanged:: 0.24.1\n\n               Changed the default value from ``True`` to ``None``\n               (without change in behaviour).\n\n        Returns\n        -------\n        difference : Index\n\n        Examples\n        --------\n\n        >>> idx1 = pd.Index([2, 1, 3, 4])\n        >>> idx2 = pd.Index([3, 4, 5, 6])\n        >>> idx1.difference(idx2)\n        Int64Index([1, 2], dtype='int64')\n        >>> idx1.difference(idx2, sort=False)\n        Int64Index([2, 1], dtype='int64')"
  },
  {
    "code": "def create(self):\n        out = helm(\n            \"repo\",\n            \"add\",\n            \"jupyterhub\",\n            self.helm_repo\n        )\n        out = helm(\"repo\", \"update\")\n        secret_yaml = self.get_security_yaml()\n        out = helm(\n            \"upgrade\",\n            \"--install\",\n            self.release,\n            \"jupyterhub/jupyterhub\",\n            namespace=self.namespace,\n            version=self.version,\n            input=secret_yaml\n        )\n        if out.returncode != 0:\n            print(out.stderr)\n        else:\n            print(out.stdout)",
    "docstring": "Create a single instance of notebook."
  },
  {
    "code": "def filename(self):\r\n        self._filename = getattr(self, '_filename', None)\r\n        self._root_path = getattr(self, '_root_path', None)\r\n        if self._filename is None and self._root_path is None:\r\n            return self._filename_global()\r\n        else:\r\n            return self._filename_projects()",
    "docstring": "Defines the name of the configuration file to use."
  },
  {
    "code": "def distance_to_contact(D, alpha=1):\n    if callable(alpha):\n        distance_function = alpha\n    else:\n        try:\n            a = np.float64(alpha)\n            def distance_function(x):\n                return 1 / (x ** (1 / a))\n        except TypeError:\n            print(\"Alpha parameter must be callable or an array-like\")\n            raise\n        except ZeroDivisionError:\n            raise ValueError(\"Alpha parameter must be non-zero\")\n    m = np.max(distance_function(D[D != 0]))\n    M = np.zeros(D.shape)\n    M[D != 0] = distance_function(D[D != 0])\n    M[D == 0] = m\n    return M",
    "docstring": "Compute contact matrix from input distance matrix. Distance values of\n    zeroes are given the largest contact count otherwise inferred non-zero\n    distance values."
  },
  {
    "code": "def remove_file(profile, branch, file_path, commit_message=None):\n    branch_sha = get_branch_sha(profile, branch)\n    tree = get_files_in_branch(profile, branch_sha)\n    new_tree = remove_file_from_tree(tree, file_path)\n    data = trees.create_tree(profile, new_tree)\n    sha = data.get(\"sha\")\n    if not commit_message:\n        commit_message = \"Deleted \" + file_path + \".\"\n    parents = [branch_sha]\n    commit_data = commits.create_commit(profile, commit_message, sha, parents)\n    commit_sha = commit_data.get(\"sha\")\n    ref_data = refs.update_ref(profile, \"heads/\" + branch, commit_sha)\n    return ref_data",
    "docstring": "Remove a file from a branch.\n\n    Args:\n\n        profile\n            A profile generated from ``simplygithub.authentication.profile``.\n            Such profiles tell this module (i) the ``repo`` to connect to,\n            and (ii) the ``token`` to connect with.\n\n        branch\n            The name of a branch.\n\n        file_path\n            The path of the file to delete.\n\n        commit_message\n            A commit message to give to the commit.\n\n    Returns:\n        A dict with data about the branch's new ref (it includes the new SHA\n        the branch's HEAD points to, after committing the new file)."
  },
  {
    "code": "def infer_shape(self, node, input_shapes):\n        if isinstance(self.operator, Functional):\n            return [()]\n        else:\n            return [tuple(native(si) for si in self.operator.range.shape)]",
    "docstring": "Return a list of output shapes based on ``input_shapes``.\n\n        This method is optional. It allows to compute the shape of the\n        output without having to evaluate.\n\n        Parameters\n        ----------\n        node : `theano.gof.graph.Apply`\n            The node of this Op in the computation graph.\n        input_shapes : 1-element list of `theano.compile.ops.Shape`\n            Symbolic shape of the input.\n\n        Returns\n        -------\n        output_shapes : 1-element list of tuples\n            Fixed shape of the output determined by `odl_op`."
  },
  {
    "code": "def component(self, **kwargs):\n        kwargs_copy = self.base_dict.copy()\n        kwargs_copy.update(**kwargs)\n        self._replace_none(kwargs_copy)        \n        try:\n            return NameFactory.component_format.format(**kwargs_copy)\n        except KeyError:\n            return None",
    "docstring": "Return a key that specifies data the sub-selection"
  },
  {
    "code": "def delete(self):\n        redis = type(self).get_redis()\n        for fieldname, field in self.proxy:\n            field.delete(redis)\n        redis.delete(self.key())\n        redis.srem(type(self).members_key(), self.id)\n        if isinstance(self, PermissionHolder):\n            redis.delete(self.allow_key())\n        if self.notify:\n            data = json.dumps({\n                'event': 'delete',\n                'data': self.to_json(),\n            })\n            redis.publish(type(self).cls_key(), data)\n            redis.publish(self.key(), data)\n        return self",
    "docstring": "Deletes this model from the database, calling delete in each field\n        to properly delete special cases"
  },
  {
    "code": "def loadJSON(self, jdata):\n        super(ReferenceColumn, self).loadJSON(jdata)\n        self.__reference = jdata.get('reference') or self.__reference\n        self.__removeAction = jdata.get('removeAction') or self.__removeAction",
    "docstring": "Loads the given JSON information for this column.\n\n        :param jdata: <dict>"
  },
  {
    "code": "def skip_signatures_and_duplicates_concat_well_known_metadata(cls, default_dup_action=None,\n                                                                additional_rules=None):\n    default_dup_action = Duplicate.validate_action(default_dup_action or Duplicate.SKIP)\n    additional_rules = assert_list(additional_rules,\n                                   expected_type=(Duplicate, Skip))\n    rules = [Skip(r'^META-INF/[^/]+\\.SF$'),\n             Skip(r'^META-INF/[^/]+\\.DSA$'),\n             Skip(r'^META-INF/[^/]+\\.RSA$'),\n             Skip(r'^META-INF/INDEX.LIST$'),\n             Duplicate(r'^META-INF/services/', Duplicate.CONCAT_TEXT)]\n    return JarRules(rules=rules + additional_rules, default_dup_action=default_dup_action)",
    "docstring": "Produces a rule set useful in many deploy jar creation contexts.\n\n    The rule set skips duplicate entries by default, retaining the 1st encountered.  In addition it\n    has the following special handling:\n\n    - jar signature metadata is dropped\n    - jar indexing files INDEX.LIST are dropped\n    - ``java.util.ServiceLoader`` provider-configuration files are concatenated in the order\n      encountered\n\n    :param default_dup_action: An optional default action to take for duplicates.  Defaults to\n      `Duplicate.SKIP` if not specified.\n    :param additional_rules: Optionally one or more jar rules to add to those described above.\n    :returns: JarRules"
  },
  {
    "code": "def stop(self):\n        if not self._started:\n            raise NotRunningError(\"This AutobahnSync instance is not started\")\n        self._callbacks_runner.stop()\n        self._started = False",
    "docstring": "Terminate the WAMP session\n\n        .. note::\n            If the :meth:`AutobahnSync.run` has been run with ``blocking=True``,\n            it will returns then."
  },
  {
    "code": "def upsert_module_file(module_ident, fileid, filename):\n    with db_connect() as db_conn:\n        with db_conn.cursor() as cursor:\n            cursor.execute(\"SELECT true FROM module_files \"\n                           \"WHERE module_ident = %s \"\n                           \"AND filename = %s\",\n                           (module_ident, filename,))\n            try:\n                cursor.fetchone()[0]\n            except (IndexError, TypeError):\n                cursor.execute(\"INSERT INTO module_files \"\n                               \"(module_ident, fileid, filename) \"\n                               \"VALUES (%s, %s, %s)\",\n                               (module_ident, fileid, filename,))\n            else:\n                cursor.execute(\"UPDATE module_files \"\n                               \"SET (fileid) = (%s) \"\n                               \"WHERE module_ident = %s AND filename = %s\",\n                               (fileid, module_ident, filename,))",
    "docstring": "Upsert a file associated with ``fileid`` with ``filename``\n    as a module_files entry associated with content at ``module_ident``."
  },
  {
    "code": "def similarity(w1, w2, threshold=0.5):\n    ratio = SM(None, str(w1).lower(), str(w2).lower()).ratio()\n    return ratio if ratio > threshold else 0",
    "docstring": "compare two strings 'words', and\n    return ratio of smiliarity, be it larger than the threshold,\n    or 0 otherwise.\n\n    NOTE: if the result more like junk, increase the threshold value."
  },
  {
    "code": "def http_request(self,\n\t\t\tverb,\n\t\t\turi,\n\t\t\tdata=None,\n\t\t\theaders=None,\n\t\t\tfiles=None,\n\t\t\tresponse_format=None,\n\t\t\tis_rdf = True,\n\t\t\tstream = False\n\t\t):\n\t\tif is_rdf:\n\t\t\tif verb == 'GET':\n\t\t\t\tif not response_format:\n\t\t\t\t\tresponse_format = self.repo.default_serialization\n\t\t\t\tif headers and 'Accept' not in headers.keys():\n\t\t\t\t\theaders['Accept'] = response_format\n\t\t\t\telse:\n\t\t\t\t\theaders = {'Accept':response_format}\n\t\tif type(uri) == rdflib.term.URIRef:\n\t\t\turi = uri.toPython()\n\t\tlogger.debug(\"%s request for %s, format %s, headers %s\" %\n\t\t\t(verb, uri, response_format, headers))\n\t\tsession = requests.Session()\n\t\trequest = requests.Request(verb, uri, auth=(self.repo.username, self.repo.password), data=data, headers=headers, files=files)\n\t\tprepped_request = session.prepare_request(request)\n\t\tresponse = session.send(prepped_request,\n\t\t\tstream=stream,\n\t\t)\n\t\treturn response",
    "docstring": "Primary route for all HTTP requests to repository.  Ability to set most parameters for requests library,\n\t\twith some additional convenience parameters as well.\n\n\t\tArgs:\n\t\t\tverb (str): HTTP verb to use for request, e.g. PUT, POST, GET, HEAD, PATCH, etc.\n\t\t\turi (rdflib.term.URIRef,str): input URI\n\t\t\tdata (str,file): payload of data to send for request, may be overridden in preperation of request\n\t\t\theaders (dict): optional dictionary of headers passed directly to requests.request\n\t\t\tfiles (dict): optional dictionary of files passed directly to requests.request\n\t\t\tresponse_format (str): desired response format for resource's payload, e.g. 'application/rdf+xml', 'text/turtle', etc.\n\t\t\tis_rdf (bool): if True, set Accept header based on combination of response_format and headers\n\t\t\tstream (bool): passed directly to requests.request for stream parameter\n\n\t\tReturns:\n\t\t\trequests.models.Response"
  },
  {
    "code": "def touch(self):\n        key = self.get_related().get_key_name()\n        columns = self.get_related_fresh_update()\n        ids = self.get_related_ids()\n        if len(ids) > 0:\n            self.get_related().new_query().where_in(key, ids).update(columns)",
    "docstring": "Touch all of the related models of the relationship."
  },
  {
    "code": "def predict(self,Xstar):\n        KV = self._update_cache()\n        self.covar.setXstar(Xstar)\n        Kstar = self.covar.Kcross()\n        Ystar = SP.dot(Kstar,KV['alpha'])\n        return Ystar",
    "docstring": "predict on Xstar"
  },
  {
    "code": "def _calculate_unique_id(self, xblock):\n        key = scope_key(self, xblock)\n        return hashlib.sha1(key.encode('utf-8')).hexdigest()",
    "docstring": "Provide a default value for fields with `default=UNIQUE_ID`.\n\n        Returned string is a SHA1 hex digest that is deterministically calculated\n        for the field in its given scope."
  },
  {
    "code": "def extract_datetime_hour(cls, datetime_str):\n        if not datetime_str:\n            raise DateTimeFormatterException('datetime_str must a valid string')\n        try:\n            return cls._extract_timestamp(datetime_str, cls.DATETIME_HOUR_FORMAT)\n        except (TypeError, ValueError):\n            raise DateTimeFormatterException('Invalid datetime string {}.'.format(datetime_str))",
    "docstring": "Tries to extract a `datetime` object from the given string, including only hours.\n\n        Raises `DateTimeFormatterException` if the extraction fails."
  },
  {
    "code": "def _term(self, term):\n        term = str(term)\n        if term:\n            self.__query[\"q\"] += term\n        return self",
    "docstring": "Add a term to the query.\n\n        Arguments:\n            term (str): The term to add.\n\n        Returns:\n            SearchHelper: Self"
  },
  {
    "code": "def c_module_relocs(self):\n        if self.opts.no_structs or self.opts.windll:\n            return '', ''\n        x86 = reloc_var(\n            self.name, self._c_struct_names()[1],\n            self.opts.reloc_delta,\n            self._c_uses_pointer()\n        )\n        x64 = '{0} *{1} = &_{1};\\n'.format(\n            self._c_struct_names()[1], self.name\n        ) if self._c_uses_pointer() else ''\n        return x86, x64",
    "docstring": "Build relocation for the module variable."
  },
  {
    "code": "def parent_workspace(context):\n    if IWorkspaceFolder.providedBy(context):\n        return context\n    for parent in aq_chain(context):\n        if IWorkspaceFolder.providedBy(parent):\n            return parent",
    "docstring": "Return containing workspace\n        Returns None if not found."
  },
  {
    "code": "def add_field(self, field):\n        self.remove_field(field.name)\n        self._fields[field.name] = field\n        if field.default is not None:\n            if six.callable(field.default):\n                self._default_callables[field.key] = field.default\n            else:\n                self._defaults[field.key] = field.default",
    "docstring": "Add the received field to the model."
  },
  {
    "code": "def apply_async(self, args=None, kwargs=None, **options):\n        key = self._get_cache_key(args, kwargs)\n        counter, penalty = cache.get(key, (0, 0))\n        if not counter:\n            return super(PenalizedBackgroundTask, self).apply_async(args=args, kwargs=kwargs, **options)\n        cache.set(key, (counter - 1, penalty), self.CACHE_LIFETIME)\n        logger.info('The task %s will not be executed due to the penalty.' % self.name)\n        return self.AsyncResult(options.get('task_id') or str(uuid4()))",
    "docstring": "Checks whether task must be skipped and decreases the counter in that case."
  },
  {
    "code": "def generate_blocks(self, assume_complete_blocks=None):\n        _track_assume_blocks = self.assume_complete_blocks\n        try:\n            if assume_complete_blocks != None:\n                self.assume_complete_blocks = assume_complete_blocks\n            if self.processed_tables == None:\n                self.preprocess()\n            self.processed_blocks = []\n            for worksheet in range(len(self.processed_tables)):\n                ptable = self.processed_tables[worksheet]\n                flags = self.flags_by_table[worksheet]\n                units = self.units_by_table[worksheet]\n                if not self.assume_complete_blocks:\n                    self.fill_in_table(ptable, worksheet, flags)\n                self.processed_blocks.extend(self._find_blocks(ptable, worksheet, flags, units,\n                        { 'worksheet': worksheet }))\n            return self.processed_blocks\n        finally:\n            self.assume_complete_blocks = _track_assume_blocks",
    "docstring": "Identifies and extracts all blocks from the input tables. These blocks are logical\n        identifiers for where related information resides in the original table. Any block can be\n        converted into a row-titled table which can then be stitched together with other tables from\n        other blocks to form a fully converted data set.\n\n        Args:\n            assume_complete_blocks: Optimizes block loopups by not allowing titles to be extended.\n                Blocks should be perfectly dense to be found when active. Optional, defaults to\n                constructor value."
  },
  {
    "code": "def get_subdomain(url):\n        if url not in URLHelper.__cache:\n            URLHelper.__cache[url] = urlparse(url)\n        return \".\".join(URLHelper.__cache[url].netloc.split(\".\")[:-2])",
    "docstring": "Get the subdomain of the given URL.\n\n        Args:\n            url (str): The URL to get the subdomain from.\n\n        Returns:\n            str: The subdomain(s)"
  },
  {
    "code": "def connect(url):\n    url = urlparse(url)\n    if url.scheme == 'tcp':\n        sock = socket()\n        netloc = tuple(url.netloc.rsplit(':', 1))\n        hostname = socket.gethostname()\n    elif url.scheme == 'ipc':\n        sock = socket(AF_UNIX)\n        netloc = url.path\n        hostname = 'localhost'\n    else:\n        raise ValueError('unknown socket type: %s' % url.scheme)\n    sock.connect(netloc)\n    return sock, hostname",
    "docstring": "Connect to UNIX or TCP socket.\n\n        url can be either tcp://<host>:port or ipc://<path>"
  },
  {
    "code": "def get_attribute(self, attrkey, as_string=False, as_list=False):\n        assert not as_string or not as_list\n        if attrkey not in self._attrs:\n            return None\n        if attrkey == 'ID':\n            return self._attrs[attrkey]\n        attrvalues = list(self._attrs[attrkey])\n        attrvalues.sort()\n        if len(attrvalues) == 1 and not as_list:\n            return attrvalues[0]\n        elif as_string:\n            return ','.join(attrvalues)\n        return attrvalues",
    "docstring": "Get the value of an attribute.\n\n        By default, returns a string for ID and attributes with a single value,\n        and a list of strings for attributes with multiple values. The\n        `as_string` and `as_list` options can be used to force the function to\n        return values as a string (comma-separated in case of multiple values)\n        or a list."
  },
  {
    "code": "def matches_pattern(self, other):\n        ismatch = False\n        if isinstance(other, Userdata):\n            for key in self._userdata:\n                if self._userdata[key] is None or other[key] is None:\n                    ismatch = True\n                elif self._userdata[key] == other[key]:\n                    ismatch = True\n                else:\n                    ismatch = False\n                    break\n        return ismatch",
    "docstring": "Test if the current instance matches a template instance."
  },
  {
    "code": "def WriteBlobs(self, blob_id_data_map, cursor=None):\n    chunks = []\n    for blob_id, blob in iteritems(blob_id_data_map):\n      chunks.extend(_BlobToChunks(blob_id.AsBytes(), blob))\n    for values in _PartitionChunks(chunks):\n      _Insert(cursor, \"blobs\", values)",
    "docstring": "Writes given blobs."
  },
  {
    "code": "def client_end(request, socket, context):\n    for channel in socket.channels:\n        events.on_unsubscribe.send(request, socket, context, channel)\n    events.on_finish.send(request, socket, context)\n    for channel in socket.channels[:]:\n        socket.unsubscribe(channel)\n    del CLIENTS[socket.session.session_id]",
    "docstring": "Handles cleanup when a session ends for the given client triple.\n    Sends unsubscribe and finish events, actually unsubscribes from\n    any channels subscribed to, and removes the client triple from\n    CLIENTS."
  },
  {
    "code": "def count(self, with_limit_and_skip=False):\n        validate_boolean(\"with_limit_and_skip\", with_limit_and_skip)\n        cmd = SON([(\"count\", self.__collection.name),\n                   (\"query\", self.__spec)])\n        if self.__max_time_ms is not None:\n            cmd[\"maxTimeMS\"] = self.__max_time_ms\n        if self.__comment:\n            cmd[\"$comment\"] = self.__comment\n        if self.__hint is not None:\n            cmd[\"hint\"] = self.__hint\n        if with_limit_and_skip:\n            if self.__limit:\n                cmd[\"limit\"] = self.__limit\n            if self.__skip:\n                cmd[\"skip\"] = self.__skip\n        return self.__collection._count(cmd, self.__collation)",
    "docstring": "Get the size of the results set for this query.\n\n        Returns the number of documents in the results set for this query. Does\n        not take :meth:`limit` and :meth:`skip` into account by default - set\n        `with_limit_and_skip` to ``True`` if that is the desired behavior.\n        Raises :class:`~pymongo.errors.OperationFailure` on a database error.\n\n        When used with MongoDB >= 2.6, :meth:`~count` uses any :meth:`~hint`\n        applied to the query. In the following example the hint is passed to\n        the count command:\n\n          collection.find({'field': 'value'}).hint('field_1').count()\n\n        The :meth:`count` method obeys the\n        :attr:`~pymongo.collection.Collection.read_preference` of the\n        :class:`~pymongo.collection.Collection` instance on which\n        :meth:`~pymongo.collection.Collection.find` was called.\n\n        :Parameters:\n          - `with_limit_and_skip` (optional): take any :meth:`limit` or\n            :meth:`skip` that has been applied to this cursor into account when\n            getting the count\n\n        .. note:: The `with_limit_and_skip` parameter requires server\n           version **>= 1.1.4-**\n\n        .. versionchanged:: 2.8\n           The :meth:`~count` method now supports :meth:`~hint`."
  },
  {
    "code": "def set_connection_logging(self, loadbalancer, val):\n        uri = \"/loadbalancers/%s/connectionlogging\" % utils.get_id(loadbalancer)\n        val = str(val).lower()\n        req_body = {\"connectionLogging\": {\n                \"enabled\": val,\n                }}\n        resp, body = self.api.method_put(uri, body=req_body)\n        return body",
    "docstring": "Sets the connection logging for the given load balancer."
  },
  {
    "code": "def create_window(self, pane, name=None, set_active=True):\n        assert isinstance(pane, Pane)\n        assert name is None or isinstance(name, six.text_type)\n        taken_indexes = [w.index for w in self.windows]\n        index = self.base_index\n        while index in taken_indexes:\n            index += 1\n        w = Window(index)\n        w.add_pane(pane)\n        self.windows.append(w)\n        self.windows = sorted(self.windows, key=lambda w: w.index)\n        app = get_app(return_none=True)\n        if app is not None and set_active:\n            self.set_active_window(w)\n        if name is not None:\n            w.chosen_name = name\n        assert w.active_pane == pane\n        assert w._get_parent(pane)",
    "docstring": "Create a new window that contains just this pane.\n\n        :param pane: The :class:`.Pane` instance to put in the new window.\n        :param name: If given, name for the new window.\n        :param set_active: When True, focus the new window."
  },
  {
    "code": "def openid_authorization_validator(self, request):\n        request_info = super(HybridGrant, self).openid_authorization_validator(request)\n        if not request_info:\n            return request_info\n        if request.response_type in [\"code id_token\", \"code id_token token\"]:\n            if not request.nonce:\n                raise InvalidRequestError(\n                    request=request,\n                    description='Request is missing mandatory nonce parameter.'\n                )\n        return request_info",
    "docstring": "Additional validation when following the Authorization Code flow."
  },
  {
    "code": "def param_upload(field, path):\n    if not path:\n        return None\n    param = {}\n    param['field'] = field\n    param['path'] = path\n    return param",
    "docstring": "Pack upload metadata."
  },
  {
    "code": "def xAxisIsMinor(self):\n        return min(self.radius.x, self.radius.y) == self.radius.x",
    "docstring": "Returns True if the minor axis is parallel to the X axis, boolean."
  },
  {
    "code": "def non_parallel(self, vector):\n        if (self.is_parallel(vector) is not True and\n                self.is_perpendicular(vector) is not True):\n            return True\n        return False",
    "docstring": "Return True if vectors are non-parallel.\n\n        Non-parallel vectors are vectors which are neither parallel\n        nor perpendicular to each other."
  },
  {
    "code": "def __set_date(self, value):\n        if not issubclass(value.__class__, date):\n            raise ValueError('Invalid date value')\n        self.__date = value",
    "docstring": "Sets the date of the payment.\n        @param value:datetime"
  },
  {
    "code": "def _find_column(input_, token):\n    i = token.lexpos\n    while i > 0:\n        if input_[i] == '\\n':\n            break\n        i -= 1\n    column = token.lexpos - i - 1\n    return column",
    "docstring": "Find the column in file where error occured. This is taken from\n        token.lexpos converted to the position on the current line by\n        finding the previous EOL."
  },
  {
    "code": "def widen(self):\n        t, h = self.time, self.half_duration\n        h *= self.scaling_coeff_x\n        self.set_interval((t - h, t + h))",
    "docstring": "Increase the interval size."
  },
  {
    "code": "def write_PIA0_B_control(self, cpu_cycles, op_address, address, value):\n        log.critical(\n            \"%04x| write $%02x (%s) to $%04x -> PIA 0 B side Control reg.\\t|%s\",\n            op_address, value, byte2bit_string(value),\n            address, self.cfg.mem_info.get_shortest(op_address)\n        )\n        if is_bit_set(value, bit=0):\n            log.critical(\n                \"%04x| write $%02x (%s) to $%04x -> VSYNC IRQ: enable\\t|%s\",\n                op_address, value, byte2bit_string(value),\n                address, self.cfg.mem_info.get_shortest(op_address)\n            )\n            self.cpu.irq_enabled = True\n            value = set_bit(value, bit=7)\n        else:\n            log.critical(\n                \"%04x| write $%02x (%s) to $%04x -> VSYNC IRQ: disable\\t|%s\",\n                op_address, value, byte2bit_string(value),\n                address, self.cfg.mem_info.get_shortest(op_address)\n            )\n            self.cpu.irq_enabled = False\n        if not is_bit_set(value, bit=2):\n            self.pia_0_B_control.select_pdr()\n        else:\n            self.pia_0_B_control.deselect_pdr()\n        self.pia_0_B_control.set(value)",
    "docstring": "write to 0xff03 -> PIA 0 B side Control reg.\n\n        TODO: Handle IRQ\n\n        bit 7 | IRQ 1 (VSYNC) flag\n        bit 6 | IRQ 2 flag(not used)\n        bit 5 | Control line 2 (CB2) is an output = 1\n        bit 4 | Control line 2 (CB2) set by bit 3 = 1\n        bit 3 | select line MSB of analog multiplexor (MUX): 0 = control line 2 LO / 1 = control line 2 HI\n        bit 2 | set data direction: 0 = $FF02 is DDR / 1 = $FF02 is normal data lines\n        bit 1 | control line 1 (CB1): IRQ polarity 0 = IRQ on HI to LO / 1 = IRQ on LO to HI\n        bit 0 | VSYNC IRQ: 0 = disable IRQ / 1 = enable IRQ"
  },
  {
    "code": "def make_inst2():\n    I,d = multidict({1:45, 2:20, 3:30 , 4:30})\n    J,M = multidict({1:35, 2:50, 3:40})\n    c = {(1,1):8,    (1,2):9,    (1,3):14  ,\n         (2,1):6,    (2,2):12,   (2,3):9   ,\n         (3,1):10,   (3,2):13,   (3,3):16  ,\n         (4,1):9,    (4,2):7,    (4,3):5   ,\n         }\n    return I,J,c,d,M",
    "docstring": "creates example data set 2"
  },
  {
    "code": "def XanyKXany(self):\n        result = np.empty((self.P,self.F_any.shape[1],self.F_any.shape[1]), order='C')\n        for p in range(self.P):\n            X1D = self.Fstar_any * self.D[:,p:p+1]\n            X1X2 = X1D.T.dot(self.Fstar_any)\n            result[p] = X1X2\n        return result",
    "docstring": "compute self covariance for any"
  },
  {
    "code": "def _parse_identifier(self, identifier, zone=None):\n        rdtype, name, content = None, None, None\n        if len(identifier) > 7:\n            parts = identifier.split('/')\n            rdtype, name, content = parts[0], parts[1], '/'.join(parts[2:])\n        else:\n            records = self._list_records_in_zone(zone)\n            for record in records:\n                if record['id'] == identifier:\n                    rdtype, name, content = record['type'], record['name'] + '.', record['content']\n        return rdtype, name, content",
    "docstring": "Parses the record identifier and returns type, name & content of the associated record\n        as tuple. The tuple is empty if no associated record found."
  },
  {
    "code": "def _calculate_degree_days(temperature_equivalent, base_temperature, cooling=False):\n    if cooling:\n        ret = temperature_equivalent - base_temperature\n    else:\n        ret = base_temperature - temperature_equivalent\n    ret[ret < 0] = 0\n    prefix = 'CDD' if cooling else 'HDD'\n    ret.name = '{}_{}'.format(prefix, base_temperature)\n    return ret",
    "docstring": "Calculates degree days, starting with a series of temperature equivalent values\n\n    Parameters\n    ----------\n    temperature_equivalent : Pandas Series\n    base_temperature : float\n    cooling : bool\n        Set True if you want cooling degree days instead of heating degree days\n\n    Returns\n    -------\n    Pandas Series called HDD_base_temperature for heating degree days or\n    CDD_base_temperature for cooling degree days."
  },
  {
    "code": "def content_break(self, el):\n        should_break = False\n        if self.type == 'odp':\n            if el.name == 'page' and el.namespace and el.namespace == self.namespaces['draw']:\n                should_break = True\n        return should_break",
    "docstring": "Break on specified boundaries."
  },
  {
    "code": "def stop(self):\n        if self._started is False:\n            raise ArgumentError(\"EmulationLoop.stop() called without calling start()\")\n        self.verify_calling_thread(False, \"Cannot call EmulationLoop.stop() from inside the event loop\")\n        if self._thread.is_alive():\n            self._loop.call_soon_threadsafe(self._loop.create_task, self._clean_shutdown())\n            self._thread.join()",
    "docstring": "Stop the background emulation loop."
  },
  {
    "code": "def address(self, street, city=None, state=None, zipcode=None, **kwargs):\n        fields = {\n            'street': street,\n            'city': city,\n            'state': state,\n            'zip': zipcode,\n        }\n        return self._fetch('address', fields, **kwargs)",
    "docstring": "Geocode an address."
  },
  {
    "code": "def _type_check_pointers(utype):\n    result = []\n    for mname, member in utype.members.items():\n        if (\"pointer\" in member.modifiers and member.D > 0 and\n            (member.default is None or \"null\" not in member.default)):\n            result.append(member)\n    return result",
    "docstring": "Checks the user-derived type for non-nullified pointer array declarations\n    in its base definition.\n\n    Returns (list of offending members)."
  },
  {
    "code": "def _loop_no_cache(self, helper_function, num, fragment):\n        self.log([u\"Examining fragment %d (no cache)...\", num])\n        voice_code = self._language_to_voice_code(fragment.language)\n        self.log(u\"Calling helper function\")\n        succeeded, data = helper_function(\n            text=fragment.filtered_text,\n            voice_code=voice_code,\n            output_file_path=None,\n            return_audio_data=True\n        )\n        if not succeeded:\n            self.log_crit(u\"An unexpected error occurred in helper_function\")\n            return (False, None)\n        self.log([u\"Examining fragment %d (no cache)... done\", num])\n        return (True, data)",
    "docstring": "Synthesize all fragments without using the cache"
  },
  {
    "code": "def to_array(self):\n        array = super(MaskPosition, self).to_array()\n        array['point'] = u(self.point)\n        array['x_shift'] = float(self.x_shift)\n        array['y_shift'] = float(self.y_shift)\n        array['scale'] = float(self.scale)\n        return array",
    "docstring": "Serializes this MaskPosition to a dictionary.\n\n        :return: dictionary representation of this object.\n        :rtype: dict"
  },
  {
    "code": "def generate_host_meta(template=None, *args, **kwargs):\n    if template == \"diaspora\":\n        hostmeta = DiasporaHostMeta(*args, **kwargs)\n    else:\n        hostmeta = BaseHostMeta(*args, **kwargs)\n    return hostmeta.render()",
    "docstring": "Generate a host-meta XRD document.\n\n    Template specific key-value pairs need to be passed as ``kwargs``, see classes.\n\n    :arg template: Ready template to fill with args, for example \"diaspora\" (optional)\n    :returns: Rendered XRD document (str)"
  },
  {
    "code": "def averageAbove(requestContext, seriesList, n):\n    results = []\n    for series in seriesList:\n        val = safeAvg(series)\n        if val is not None and val >= n:\n            results.append(series)\n    return results",
    "docstring": "Takes one metric or a wildcard seriesList followed by an integer N.\n    Out of all metrics passed, draws only the metrics with an average value\n    above N for the time period specified.\n\n    Example::\n\n        &target=averageAbove(server*.instance*.threads.busy,25)\n\n    Draws the servers with average values above 25."
  },
  {
    "code": "def WriteSignedBinaryBlobs(binary_urn,\n                           blobs,\n                           token = None):\n  if _ShouldUseLegacyDatastore():\n    aff4.FACTORY.Delete(binary_urn, token=token)\n    with data_store.DB.GetMutationPool() as mutation_pool:\n      with aff4.FACTORY.Create(\n          binary_urn,\n          collects.GRRSignedBlob,\n          mode=\"w\",\n          mutation_pool=mutation_pool,\n          token=token) as fd:\n        for blob in blobs:\n          fd.Add(blob, mutation_pool=mutation_pool)\n  if data_store.RelationalDBEnabled():\n    blob_references = rdf_objects.BlobReferences()\n    current_offset = 0\n    for blob in blobs:\n      blob_id = data_store.BLOBS.WriteBlobWithUnknownHash(\n          blob.SerializeToString())\n      blob_references.items.Append(\n          rdf_objects.BlobReference(\n              offset=current_offset, size=len(blob.data), blob_id=blob_id))\n      current_offset += len(blob.data)\n    data_store.REL_DB.WriteSignedBinaryReferences(\n        _SignedBinaryIDFromURN(binary_urn), blob_references)",
    "docstring": "Saves signed blobs to the datastore.\n\n  If a signed binary with the given URN already exists, its contents will get\n  overwritten.\n\n  Args:\n    binary_urn: RDFURN that should serve as a unique identifier for the binary.\n    blobs: An Iterable of signed blobs to write to the datastore.\n    token: ACL token to use with the legacy (non-relational) datastore."
  },
  {
    "code": "def new_item(self, hash_key, range_key=None, attrs=None):\n        return Item(self, hash_key, range_key, attrs)",
    "docstring": "Return an new, unsaved Item which can later be PUT to\n        Amazon DynamoDB."
  },
  {
    "code": "def _process_params(self):\n        self._sort_to_str()\n        if 'rows' not in self._solr_params:\n            self._solr_params['rows'] = self._cfg['row_size']\n        for key, val in self._solr_params.items():\n            if isinstance(val, str) and six.PY2:\n                self._solr_params[key] = val.encode(encoding='UTF-8')\n        return self._solr_params",
    "docstring": "Adds default row size if it's not given in the query.\n        Converts param values into unicode strings.\n\n        Returns:\n            Processed self._solr_params dict."
  },
  {
    "code": "def _find_current_phase(self, global_step):\n    epoch_size = sum(phase.steps for phase in self._phases)\n    epoch = int(global_step // epoch_size)\n    steps_in = global_step % epoch_size\n    for phase in self._phases:\n      if steps_in < phase.steps:\n        return phase, epoch, steps_in\n      steps_in -= phase.steps",
    "docstring": "Determine the current phase based on the global step.\n\n    This ensures continuing the correct phase after restoring checkoints.\n\n    Args:\n      global_step: The global number of steps performed across all phases.\n\n    Returns:\n      Tuple of phase object, epoch number, and phase steps within the epoch."
  },
  {
    "code": "def show_one(request, post_process_fun, object_class, id, template='common_json.html'):\n    obj = get_object_or_404(object_class, pk=id)\n    json = post_process_fun(request, obj)\n    return render_json(request, json, template=template, help_text=show_one.__doc__)",
    "docstring": "Return object of the given type with the specified identifier.\n\n    GET parameters:\n      user:\n        identifier of the current user\n      stats:\n        turn on the enrichment of the objects by some statistics\n      html\n        turn on the HTML version of the API"
  },
  {
    "code": "def _ssweek_num_weeks(ssweek_year):\n    \"Get the number of Sundaystarting-weeks in this year\"\n    year_start = _ssweek_year_start(ssweek_year)\n    next_year_start = _ssweek_year_start(ssweek_year+1)\n    year_num_weeks = ((next_year_start - year_start).days) // 7\n    return year_num_weeks",
    "docstring": "Get the number of Sundaystarting-weeks in this year"
  },
  {
    "code": "def settle(self, reserveTransactionId, transactionAmount=None):\n        params = {}\n        params['ReserveTransactionId'] = reserveTransactionId\n        if(transactionAmount != None):\n            params['TransactionAmount'] = transactionAmount\n        response = self.make_request(\"Settle\", params)\n        body = response.read()\n        if(response.status == 200):\n            rs = ResultSet()\n            h = handler.XmlHandler(rs, self)\n            xml.sax.parseString(body, h)\n            return rs\n        else:\n            raise FPSResponseError(response.status, response.reason, body)",
    "docstring": "Charges for a reserved payment."
  },
  {
    "code": "def user_addmedia(userids, active, mediatypeid, period, sendto, severity, **kwargs):\n    conn_args = _login(**kwargs)\n    ret = {}\n    try:\n        if conn_args:\n            method = 'user.addmedia'\n            params = {\"users\": []}\n            if not isinstance(userids, list):\n                userids = [userids]\n            for user in userids:\n                params['users'].append({\"userid\": user})\n            params['medias'] = [{\"active\": active, \"mediatypeid\": mediatypeid, \"period\": period,\n                                 \"sendto\": sendto, \"severity\": severity}, ]\n            ret = _query(method, params, conn_args['url'], conn_args['auth'])\n            return ret['result']['mediaids']\n        else:\n            raise KeyError\n    except KeyError:\n        return ret",
    "docstring": "Add new media to multiple users.\n\n    .. versionadded:: 2016.3.0\n\n    :param userids: ID of the user that uses the media\n    :param active: Whether the media is enabled (0 enabled, 1 disabled)\n    :param mediatypeid: ID of the media type used by the media\n    :param period: Time when the notifications can be sent as a time period\n    :param sendto: Address, user name or other identifier of the recipient\n    :param severity: Trigger severities to send notifications about\n    :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n    :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n    :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n    :return: IDs of the created media.\n\n    CLI Example:\n    .. code-block:: bash\n\n        salt '*' zabbix.user_addmedia 4 active=0 mediatypeid=1 period='1-7,00:00-24:00' sendto='support2@example.com'\n        severity=63"
  },
  {
    "code": "def _auditpol_cmd(cmd):\n    ret = salt.modules.cmdmod.run_all(cmd='auditpol {0}'.format(cmd),\n                                      python_shell=True)\n    if ret['retcode'] == 0:\n        return ret['stdout'].splitlines()\n    msg = 'Error executing auditpol command: {0}\\n'.format(cmd)\n    msg += '\\n'.join(ret['stdout'])\n    raise CommandExecutionError(msg)",
    "docstring": "Helper function for running the auditpol command\n\n    Args:\n        cmd (str): the auditpol command to run\n\n    Returns:\n        list: A list containing each line of the return (splitlines)\n\n    Raises:\n        CommandExecutionError: If the command encounters an error"
  },
  {
    "code": "def input_list_parser(infile_list):\n    final_list_of_files = []\n    for x in infile_list:\n        if op.isdir(x):\n            os.chdir(x)\n            final_list_of_files.extend(glob.glob('*'))\n        if op.isfile(x):\n            final_list_of_files.append(x)\n    return final_list_of_files",
    "docstring": "Always return a list of files with varying input.\n\n    >>> input_list_parser(['/path/to/folder/'])\n    ['/path/to/folder/file1.txt', '/path/to/folder/file2.txt', '/path/to/folder/file3.txt']\n\n    >>> input_list_parser(['/path/to/file.txt'])\n    ['/path/to/file.txt']\n\n    >>> input_list_parser(['file1.txt'])\n    ['file1.txt']\n\n    Args:\n        infile_list: List of arguments\n\n    Returns:\n        list: Standardized list of files"
  },
  {
    "code": "def dumps(self):\n        return {table_name: getattr(self, table_name).dumps() for table_name in self.TABLES}",
    "docstring": "Return a dictionnary of current tables"
  },
  {
    "code": "def show_mode_indicator(viewer, tf, corner='ur'):\n    tag = '_$mode_indicator'\n    canvas = viewer.get_private_canvas()\n    try:\n        indic = canvas.get_object_by_tag(tag)\n        if not tf:\n            canvas.delete_object_by_tag(tag)\n        else:\n            indic.corner = corner\n    except KeyError:\n        if tf:\n            bm = viewer.get_bindmap()\n            bm.add_callback('mode-set',\n                            lambda *args: viewer.redraw(whence=3))\n            Indicator = canvas.get_draw_class('modeindicator')\n            canvas.add(Indicator(corner=corner),\n                       tag=tag, redraw=False)\n    canvas.update_canvas(whence=3)",
    "docstring": "Show a keyboard mode indicator in one of the corners.\n\n    Parameters\n    ----------\n    viewer : an ImageView subclass instance\n        If True, show the color bar; else remove it if present.\n\n    tf : bool\n        If True, show the mark; else remove it if present.\n\n    corner : str\n        One of 'll', 'lr', 'ul' or 'ur' selecting a corner.\n        The default is 'ur'."
  },
  {
    "code": "def _init_modules_stub(self, **_):\n        from google.appengine.api import request_info\n        all_versions = {}\n        def_versions = {}\n        m2h = {}\n        for module in self.configuration.modules:\n            module_name = module._module_name or 'default'\n            module_version = module._version or '1'\n            all_versions[module_name] = [module_version]\n            def_versions[module_name] = module_version\n            m2h[module_name] = {module_version: 'localhost:8080'}\n        request_info._local_dispatcher = request_info._LocalFakeDispatcher(\n            module_names=list(all_versions),\n            module_name_to_versions=all_versions,\n            module_name_to_default_versions=def_versions,\n            module_name_to_version_to_hostname=m2h)\n        self.testbed.init_modules_stub()",
    "docstring": "Initializes the modules stub based off of your current yaml files\n\n        Implements solution from\n        http://stackoverflow.com/questions/28166558/invalidmoduleerror-when-using-testbed-to-unit-test-google-app-engine"
  },
  {
    "code": "def push_activations(activations, from_layer, to_layer):\n    inverse_covariance_matrix = layer_inverse_covariance(from_layer)\n    activations_decorrelated = np.dot(inverse_covariance_matrix, activations.T).T\n    covariance_matrix = layer_covariance(from_layer, to_layer)\n    activation_recorrelated = np.dot(activations_decorrelated, covariance_matrix)\n    return activation_recorrelated",
    "docstring": "Push activations from one model to another using prerecorded correlations"
  },
  {
    "code": "def _finalize_metadata(self, node):\n        final = {}\n        for key, val in iter(node.metadata.items()):\n            final[key] = list(val)\n        node.metadata = final\n        return node",
    "docstring": "Convert node metadata back into a standard dictionary and list."
  },
  {
    "code": "def eval(self):\n        max_size = _get_max_size(self.parts)\n        parts_list = _grow([[]], max_size-1)\n        counter = Ticker(max_size)\n        parts = self.parts[:]\n        while len(parts) > 0:\n            parts_list, counter = _get_parts_list(parts,\n                parts_list, counter)\n        commands = []\n        for i, parts in enumerate(parts_list):\n            alias = self._get_alias(i+1)\n            new_parts = copy.deepcopy(parts)\n            commands.append(Command(alias=alias, parts=new_parts))\n        return commands",
    "docstring": "Returns a list of Command objects that can be evaluated as their\n        string values. Each command will track it's preliminary dependencies,\n        but these values should not be depended on for running commands."
  },
  {
    "code": "def move_mouse(self, x, y, screen=0):\n        x = ctypes.c_int(x)\n        y = ctypes.c_int(y)\n        screen = ctypes.c_int(screen)\n        _libxdo.xdo_move_mouse(self._xdo, x, y, screen)",
    "docstring": "Move the mouse to a specific location.\n\n        :param x: the target X coordinate on the screen in pixels.\n        :param y: the target Y coordinate on the screen in pixels.\n        :param screen: the screen (number) you want to move on."
  },
  {
    "code": "def _get_names(self):\n        for line in self.content:\n            line = line.strip()\n            if line and re.search(\"^[a-zA-Z0-9]\", line):\n                yield line",
    "docstring": "Get the names of the objects to include in the table.\n\n        :returns: The names of the objects to include.\n        :rtype: generator(str)"
  },
  {
    "code": "def key_from_file(filename, passphrase):\n    hexdigest = sha256_file(filename)\n    if passphrase is None:\n        passphrase = DEFAULT_HMAC_PASSPHRASE\n    return keyed_hash(hexdigest, passphrase)",
    "docstring": "Calculate convergent encryption key.\n\n    This takes a filename and an optional passphrase.\n    If no passphrase is given, a default is used.\n    Using the default passphrase means you will be\n    vulnerable to confirmation attacks and\n    learn-partial-information attacks.\n\n    :param filename: The filename you want to create a key for.\n    :type filename: str\n    :param passphrase: The passphrase you want to use to encrypt the file.\n    :type passphrase: str or None\n    :returns: A convergent encryption key.\n    :rtype: str"
  },
  {
    "code": "def compose_all(tups):\n  from . import ast\n  return functools.reduce(lambda x, y: x.compose(y), map(ast.make_tuple, tups), ast.make_tuple({}))",
    "docstring": "Compose all given tuples together."
  },
  {
    "code": "def _get_decimal128(data, position, dummy0, dummy1, dummy2):\n    end = position + 16\n    return Decimal128.from_bid(data[position:end]), end",
    "docstring": "Decode a BSON decimal128 to bson.decimal128.Decimal128."
  },
  {
    "code": "def treynor_ratio(self, benchmark, rf=0.02):\n        benchmark = _try_to_squeeze(benchmark)\n        if benchmark.ndim > 1:\n            raise ValueError(\"Treynor ratio requires a single benchmark\")\n        rf = self._validate_rf(rf)\n        beta = self.beta(benchmark)\n        return (self.anlzd_ret() - rf) / beta",
    "docstring": "Return over `rf` per unit of systematic risk.\n\n        A measure of risk-adjusted performance that relates a\n        portfolio's excess returns to the portfolio's beta.\n        [Source: CFA Institute]\n\n        Parameters\n        ----------\n        benchmark : {pd.Series, TSeries, 1d np.ndarray}\n            The benchmark security to which `self` is compared.\n        rf : {float, TSeries, pd.Series}, default 0.02\n            If float, this represents an *compounded annualized*\n            risk-free rate; 2.0% is the default.\n            If a TSeries or pd.Series, this represents a time series\n            of periodic returns to a risk-free security.\n\n            To download a risk-free rate return series using\n            3-month US T-bill yields, see:`pyfinance.datasets.load_rf`.\n\n        Returns\n        -------\n        float"
  },
  {
    "code": "def get_pval_field(self):\n        pval_fld = self.args.pval_field\n        if pval_fld is not None:\n            if pval_fld[:2] != 'p_':\n                pval_fld = 'p_' + pval_fld\n        elif len(self.methods) == 1:\n            pval_fld = 'p_' + self.methods[0]\n        else:\n            pval_fld = 'p_uncorrected'\n        if self.results_all:\n            assert hasattr(next(iter(self.results_all)), pval_fld), \\\n                'NO PVAL({P}). EXPECTED ONE OF: {E}'.format(\n                    P=self.args.pval_field,\n                    E=\" \".join([k for k in dir(next(iter(self.results_all))) if k[:2] == 'p_']))\n        return pval_fld",
    "docstring": "Get 'p_uncorrected' or the user-specified field for determining significant results."
  },
  {
    "code": "def count_items(self, unique=True):\n        if unique:\n            return len(self.items)\n        return sum([item.quantity for item in self.items.values()])",
    "docstring": "Count items in the cart.\n\n        Parameters\n        ----------\n        unique : bool-convertible, optional\n\n        Returns\n        -------\n        int\n            If `unique` is truthy, then the result is the number of\n            items in the cart. Otherwise, it's the sum of all item\n            quantities."
  },
  {
    "code": "def _save_file(self, data):\n        if platform.system() == 'Windows':\n            with open(self.file, \"w\") as outfile:\n                json.dump(data, outfile)\n        else:\n            newpath = self.file + '.new'\n            with open(newpath, \"w\") as outfile:\n                json.dump(data, outfile)\n            os.rename(\n                os.path.realpath(newpath),\n                os.path.realpath(self.file)\n            )",
    "docstring": "Attempt to atomically save file by saving and then moving into position\n\n        The goal is to make it difficult for a crash to corrupt our data file since\n        the move operation can be made atomic if needed on mission critical filesystems."
  },
  {
    "code": "def resource_listing(cls, request) -> [(200, 'Ok', ResourceListingModel)]:\n        apis = [api.get_swagger_fragment() for api in Api if not api.private]\n        Respond(200, {\n            'apiVersion': cls.api.version,\n            'swaggerVersion': cls.api.swagger_version,\n            'apis': apis\n        })",
    "docstring": "Return the list of all available resources on the system.\n\n        Resources are filtered according to the permission system, so querying\n        this resource as different users may bare different results."
  },
  {
    "code": "def load(filepath, update=True):\n    if filepath == 'automatic' or filepath == 'example':\n        fpath = os.path.dirname(os.path.abspath(__file__)) + '/data/automatic.egg'\n        return load_egg(fpath)\n    elif filepath == 'manual':\n        fpath = os.path.dirname(os.path.abspath(__file__)) + '/data/manual.egg'\n        return load_egg(fpath, update=False)\n    elif filepath == 'naturalistic':\n        fpath = os.path.dirname(os.path.abspath(__file__)) + '/data/naturalistic.egg'\n    elif filepath.split('.')[-1]=='egg':\n        return load_egg(filepath, update=update)\n    elif filepath.split('.')[-1]=='fegg':\n        return load_fegg(filepath, update=False)\n    else:\n        raise ValueError('Could not load file.')",
    "docstring": "Loads eggs, fried eggs ands example data\n\n    Parameters\n    ----------\n    filepath : str\n        Location of file\n\n    update : bool\n        If true, updates egg to latest format\n\n    Returns\n    ----------\n    data : quail.Egg or quail.FriedEgg\n        Data loaded from disk"
  },
  {
    "code": "def longitude(self, value=0.0):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError('value {} need to be of type float '\n                                 'for field `longitude`'.format(value))\n            if value < -180.0:\n                raise ValueError('value need to be greater or equal -180.0 '\n                                 'for field `longitude`')\n            if value > 180.0:\n                raise ValueError('value need to be smaller 180.0 '\n                                 'for field `longitude`')\n        self._longitude = value",
    "docstring": "Corresponds to IDD Field `longitude`\n\n        - is West, + is East, degree minutes represented in decimal (i.e. 30 minutes is .5)\n\n        Args:\n            value (float): value for IDD Field `longitude`\n                Unit: deg\n                Default value: 0.0\n                value >= -180.0\n                value <= 180.0\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def _http_req_apply_default_headers(self, request_headers,\n                                        content_type, body):\n        if not request_headers:\n            request_headers = {}\n        request_headers.setdefault(\n            'Accept', ', '.join([str(ct) for ct in AVAILABLE_CONTENT_TYPES]))\n        if body:\n            request_headers.setdefault(\n                'Content-Type', str(content_type) or str(CONTENT_TYPE_MSGPACK))\n        if hasattr(self, 'correlation_id'):\n            request_headers.setdefault(\n                'Correlation-Id', self.correlation_id)\n        elif hasattr(self, 'request') and \\\n                self.request.headers.get('Correlation-Id'):\n            request_headers.setdefault(\n                'Correlation-Id', self.request.headers['Correlation-Id'])\n        return request_headers",
    "docstring": "Set default values for common HTTP request headers\n\n        :param dict request_headers: The HTTP request headers\n        :param content_type: The mime-type used in the request/response\n        :type content_type: :py:class:`ietfparse.datastructures.ContentType`\n            or str\n        :param mixed body: The request body\n        :rtype: dict"
  },
  {
    "code": "def json_encoder_default(obj):\n    if np is not None and hasattr(obj, 'size') and hasattr(obj, 'dtype'):\n        if obj.size == 1:\n            if np.issubdtype(obj.dtype, np.integer):\n                return int(obj)\n            elif np.issubdtype(obj.dtype, np.floating):\n                return float(obj)\n    if isinstance(obj, set):\n        return list(obj)\n    elif hasattr(obj, 'to_native'):\n        return obj.to_native()\n    elif hasattr(obj, 'tolist') and hasattr(obj, '__iter__'):\n        return obj.tolist()\n    return obj",
    "docstring": "Handle more data types than the default JSON encoder.\n\n    Specifically, it treats a `set` and a `numpy.array` like a `list`.\n\n    Example usage: ``json.dumps(obj, default=json_encoder_default)``"
  },
  {
    "code": "def set_prior_probs(self, statements):\n        self.scorer.check_prior_probs(statements)\n        for st in statements:\n            st.belief = self.scorer.score_statement(st)",
    "docstring": "Sets the prior belief probabilities for a list of INDRA Statements.\n\n        The Statements are assumed to be de-duplicated. In other words,\n        each Statement in the list passed to this function is assumed to have\n        a list of Evidence objects that support it. The prior probability of\n        each Statement is calculated based on the number of Evidences it has\n        and their sources.\n\n        Parameters\n        ----------\n        statements : list[indra.statements.Statement]\n            A list of INDRA Statements whose belief scores are to\n            be calculated. Each Statement object's belief attribute is updated\n            by this function."
  },
  {
    "code": "def values(self, predicate=None):\n        if predicate:\n            predicate_data = self._to_data(predicate)\n            return self._encode_invoke(map_values_with_predicate_codec, predicate=predicate_data)\n        else:\n            return self._encode_invoke(map_values_codec)",
    "docstring": "Returns a list clone of the values contained in this map or values of the entries which are filtered with\n        the predicate if provided.\n\n        **Warning:\n        The list is NOT backed by the map, so changes to the map are NOT reflected in the list, and\n        vice-versa.**\n\n        :param predicate: (Predicate), predicate to filter the entries (optional).\n        :return: (Sequence), a list of clone of the values contained in this map.\n\n        .. seealso:: :class:`~hazelcast.serialization.predicate.Predicate` for more info about predicates."
  },
  {
    "code": "def _retryable_write(self, retryable, func, session):\n        with self._tmp_session(session) as s:\n            return self._retry_with_session(retryable, func, s, None)",
    "docstring": "Internal retryable write helper."
  },
  {
    "code": "def connection(self):\n        if self._connection:\n            return self._connection\n        self.log.debug('Initializing connection to %s' % (self.bosh_service.\n                                                          netloc))\n        if self.bosh_service.scheme == 'http':\n            Connection = httplib.HTTPConnection\n        elif self.bosh_service.scheme == 'https':\n            Connection = httplib.HTTPSConnection\n        else:\n            raise Exception('Invalid URL scheme %s' % self.bosh_service.scheme)\n        self._connection = Connection(self.bosh_service.netloc, timeout=10)\n        self.log.debug('Connection initialized')\n        return self._connection",
    "docstring": "Returns an stablished connection"
  },
  {
    "code": "def make_simple_gt_aware_merged_vcf_with_no_combinations(self, ref_seq):\n        if len(self) <= 1:\n            return\n        merged_vcf_record = self.vcf_records[0]\n        for i in range(1, len(self.vcf_records), 1):\n            if self.vcf_records[i].intersects(merged_vcf_record):\n                return\n            else:\n                merged_vcf_record = merged_vcf_record.gt_aware_merge(self.vcf_records[i], ref_seq)\n        self.vcf_records = [merged_vcf_record]",
    "docstring": "Does a simple merging of all variants in this cluster.\n        Assumes one ALT in each variant. Uses the called allele for each\n        variant, making one new vcf_record that has all the variants\n        put together"
  },
  {
    "code": "def _translate_config_path(location):\n    package_name, filename = resolve_asset_spec(location.strip())\n    if not package_name:\n        path = filename\n    else:\n        package = __import__(package_name)\n        path = os.path.join(package_path(package), filename)\n    return path",
    "docstring": "Translate location into fullpath according asset specification.\n\n    Might be package:path for package related paths, or simply path\n\n    :param str location: resource location\n    :returns: fullpath\n\n    :rtype: str"
  },
  {
    "code": "def get_last_month_range():\n    today = date.today()\n    end_of_last_month = snap_to_beginning_of_month(today) - timedelta(days=1)\n    start_of_last_month = snap_to_beginning_of_month(end_of_last_month)\n    return (start_of_last_month, end_of_last_month)",
    "docstring": "Gets the date for the first and the last day of the previous complete month.\n\n    :returns: A tuple containing two date objects, for the first and the last day of the month\n              respectively."
  },
  {
    "code": "def filter(self, qs, value):\n        _id = None\n        if value is not None:\n            _, _id = from_global_id(value)\n        return super(GlobalIDFilter, self).filter(qs, _id)",
    "docstring": "Convert the filter value to a primary key before filtering"
  },
  {
    "code": "def extract_lambda_package(self, package_name, path):\n        lambda_package = lambda_packages[package_name][self.runtime]\n        shutil.rmtree(os.path.join(path, package_name), ignore_errors=True)\n        tar = tarfile.open(lambda_package['path'], mode=\"r:gz\")\n        for member in tar.getmembers():\n            tar.extract(member, path)",
    "docstring": "Extracts the lambda package into a given path. Assumes the package exists in lambda packages."
  },
  {
    "code": "def has_type(type, names):\n    if type.arg in names:\n        return type\n    for t in type.search('type'):\n        r = has_type(t, names)\n        if r is not None:\n            return r\n    if not hasattr(type, 'i_typedef'):\n        return None\n    if (type.i_typedef is not None and\n        hasattr(type.i_typedef, 'i_is_circular') and\n        type.i_typedef.i_is_circular == False):\n        t = type.i_typedef.search_one('type')\n        if t is not None:\n            return has_type(t, names)\n    return None",
    "docstring": "Return type with name if `type` has name as one of its base types,\n    and name is in the `names` list.  otherwise, return None."
  },
  {
    "code": "def wait(self, progress=None):\n    if not len(self._threads):\n      return self\n    desc = None\n    if type(progress) is str:\n      desc = progress\n    last = self._inserted\n    with tqdm(total=self._inserted, disable=(not progress), desc=desc) as pbar:\n      while not self._queue.empty():\n        size = self._queue.qsize()\n        delta = last - size\n        if delta != 0:\n          pbar.update(delta)\n        last = size\n        self._check_errors()\n        time.sleep(0.1)\n      self._queue.join() \n      self._check_errors()\n      final = self._inserted - last\n      if final:\n        pbar.update(final)\n    if self._queue.empty():\n      self._inserted = 0\n    return self",
    "docstring": "Allow background threads to process until the\n    task queue is empty. If there are no threads,\n    in theory the queue should always be empty\n    as processing happens immediately on the main thread.\n\n    Optional:\n      progress: (bool or str) show a tqdm progress bar optionally\n        with a description if a string is provided\n    \n    Returns: self (for chaining)\n\n    Raises: The first exception recieved from threads"
  },
  {
    "code": "def find_rotation_scale(im0, im1, isccs=False):\n    im0 = np.asarray(im0, dtype=np.float32)\n    im1 = np.asarray(im1, dtype=np.float32)\n    truesize = None\n    if isccs:\n        truesize = im0.shape\n        im0 = centered_mag_sq_ccs(im0)\n        im1 = centered_mag_sq_ccs(im1)\n    lp1, log_base = polar_fft(im1, logpolar=True, isshiftdft=isccs,\n                              logoutput=True, truesize=truesize)\n    lp0, log_base = polar_fft(im0, logpolar=True, isshiftdft=isccs,\n                              logoutput=True, truesize=truesize,\n                              nangle=lp1.shape[0], radiimax=lp1.shape[1])\n    angle, scale = find_shift_dft(lp0, lp1)\n    angle *= np.pi / lp1.shape[0]\n    scale = log_base ** (scale)\n    return angle, scale",
    "docstring": "Compares the images and return the best guess for the rotation angle,\n    and scale difference.\n\n    Parameters\n    ----------\n    im0: 2d array\n        First image\n    im1: 2d array\n        Second image\n    isccs: boolean, default False\n        Set to True if the images are alredy DFT and in CCS representation\n\n    Returns\n    -------\n    angle: number\n        The angle difference\n    scale: number\n        The scale difference\n\n    Notes\n    -----\n    Uses find_shift_dft"
  },
  {
    "code": "def summary(doc):\n    lines = []\n    if \"Summary\" in doc and len(doc[\"Summary\"]) > 0:\n        lines.append(fix_footnotes(\" \".join(doc[\"Summary\"])))\n        lines.append(\"\\n\")\n    if \"Extended Summary\" in doc and len(doc[\"Extended Summary\"]) > 0:\n        lines.append(fix_footnotes(\" \".join(doc[\"Extended Summary\"])))\n        lines.append(\"\\n\")\n    return lines",
    "docstring": "Generate markdown for summary section.\n\n    Parameters\n    ----------\n    doc : dict\n        Output from numpydoc\n\n    Returns\n    -------\n    list of str\n        Markdown strings"
  },
  {
    "code": "def split_sentences_regex(text):\n    parts = regex.split(r'([a-zA-Z0-9][.?!])[\\s$]', text)\n    sentences = [''.join(s) for s in zip(parts[0::2], parts[1::2])]\n    return sentences + [parts[-1]] if len(parts) % 2 else sentences",
    "docstring": "Use dead-simple regex to split text into sentences. Very poor accuracy.\n\n    >>> split_sentences_regex(\"Hello World. I'm I.B.M.'s Watson. --Watson\")\n    ['Hello World.', \"I'm I.B.M.'s Watson.\", '--Watson']"
  },
  {
    "code": "def remove_option(self, mask):\n        if not isinstance(mask, int):\n            raise TypeError(\"mask must be an int\")\n        self.__check_okay_to_chain()\n        if mask & _QUERY_OPTIONS[\"exhaust\"]:\n            self.__exhaust = False\n        self.__query_flags &= ~mask\n        return self",
    "docstring": "Unset arbitrary query flags using a bitmask.\n\n        To unset the tailable flag:\n        cursor.remove_option(2)"
  },
  {
    "code": "def check_tool(command):\n    assert is_iterable_typed(command, basestring)\n    if check_tool_aux(command[0]) or check_tool_aux(command[-1]):\n        return command",
    "docstring": "Checks that a tool can be invoked by 'command'.\n        If command is not an absolute path, checks if it can be found in 'path'.\n        If comand is absolute path, check that it exists. Returns 'command'\n        if ok and empty string otherwise."
  },
  {
    "code": "def driverDebugRequest(self, unDeviceIndex, pchRequest, pchResponseBuffer, unResponseBufferSize):\n        fn = self.function_table.driverDebugRequest\n        result = fn(unDeviceIndex, pchRequest, pchResponseBuffer, unResponseBufferSize)\n        return result",
    "docstring": "Sends a request to the driver for the specified device and returns the response. The maximum response size is 32k,\n        but this method can be called with a smaller buffer. If the response exceeds the size of the buffer, it is truncated. \n        The size of the response including its terminating null is returned."
  },
  {
    "code": "def copy(self):\n        return Quaternion(self.w, self.x, self.y, self.z, False)",
    "docstring": "Create an exact copy of this quaternion."
  },
  {
    "code": "def classes(self):\n        defclass = lib.EnvGetNextDefclass(self._env, ffi.NULL)\n        while defclass != ffi.NULL:\n            yield Class(self._env, defclass)\n            defclass = lib.EnvGetNextDefclass(self._env, defclass)",
    "docstring": "Iterate over the defined Classes."
  },
  {
    "code": "def _max_weight_state(states: Iterable[TensorProductState]) -> Union[None, TensorProductState]:\n    mapping = dict()\n    for state in states:\n        for oneq_state in state.states:\n            if oneq_state.qubit in mapping:\n                if mapping[oneq_state.qubit] != oneq_state:\n                    return None\n            else:\n                mapping[oneq_state.qubit] = oneq_state\n    return TensorProductState(list(mapping.values()))",
    "docstring": "Construct a TensorProductState by taking the single-qubit state at each\n    qubit position.\n\n    This function will return ``None`` if the input states are not compatible\n\n    For example, the max_weight_state of [\"(+X, q0)\", \"(-Z, q1)\"] is \"(+X, q0; -Z q1)\". Asking for\n    the max weight state of something like [\"(+X, q0)\", \"(+Z, q0)\"] will return None."
  },
  {
    "code": "def list_path_traversal(path):\n    out = [path]\n    (head, tail) = os.path.split(path)\n    if tail == '':\n        out = [head]\n        (head, tail) = os.path.split(head)\n    while head != out[0]:\n        out.insert(0, head)\n        (head, tail) = os.path.split(head)\n    return out",
    "docstring": "Returns a full list of directories leading up to, and including, a path.\n\n    So list_path_traversal('/path/to/salt') would return:\n        ['/', '/path', '/path/to', '/path/to/salt']\n    in that order.\n\n    This routine has been tested on Windows systems as well.\n    list_path_traversal('c:\\\\path\\\\to\\\\salt') on Windows would return:\n        ['c:\\\\', 'c:\\\\path', 'c:\\\\path\\\\to', 'c:\\\\path\\\\to\\\\salt']"
  },
  {
    "code": "def voltage(self):\n        raw = self.value\n        volts = raw * (_ADS1X15_PGA_RANGE[self._ads.gain] / (2**(self._ads.bits-1) - 1))\n        return volts",
    "docstring": "Returns the voltage from the ADC pin as a floating point value."
  },
  {
    "code": "def namfrm(frname):\n    frname = stypes.stringToCharP(frname)\n    frcode = ctypes.c_int()\n    libspice.namfrm_c(frname, ctypes.byref(frcode))\n    return frcode.value",
    "docstring": "Look up the frame ID code associated with a string.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/namfrm_c.html\n\n    :param frname: The name of some reference frame.\n    :type frname: str\n    :return: The SPICE ID code of the frame.\n    :rtype: int"
  },
  {
    "code": "def clamp(self, clampVal):\n        if self.x > clampVal:\n            self.x = clampVal\n        if self.y > clampVal:\n            self.y = clampVal\n        if self.z > clampVal:\n            self.z = clampVal\n        if self.w > clampVal:\n            self.w = clampVal",
    "docstring": "Clamps all the components in the vector to the specified clampVal."
  },
  {
    "code": "def append_code(original, codefile):\n    with open(codefile) as code, open(original, \"a\") as o:\n        o.write(\"\\n\")\n        o.writelines(code)",
    "docstring": "Append the contents of one file to another.\n\n    :param original: name of file that will be appended to\n    :type original: str\n    :param codefile: name of file that will be appende\n    :type codefile: str\n\n    This function is particularly useful when one wants to replace a function\n    in student code with their own implementation of one. If two functions are\n    defined with the same name in Python, the latter definition is taken so overwriting\n    a function is as simple as writing it to a file and then appending it to the\n    student's code.\n\n    Example usage::\n\n        # Include a file containing our own implementation of a lookup function.\n        check50.include(\"lookup.py\")\n\n        # Overwrite the lookup function in helpers.py with our own implementation.\n        check50.py.append_code(\"helpers.py\", \"lookup.py\")"
  },
  {
    "code": "def copy_update(pb_message, **kwds):\n    result = pb_message.__class__()\n    result.CopyFrom(pb_message)\n    for k, v in kwds.items():\n        setattr(result, k, v)\n    return result",
    "docstring": "Returns a copy of the PB object, with some fields updated.\n\n    Args:\n        pb_message:\n        **kwds:\n\n    Returns:"
  },
  {
    "code": "def query_tags(order=None, orderby=None, limit=None):\n    from taggit.models import Tag, TaggedItem\n    EntryModel = get_entry_model()\n    ct = ContentType.objects.get_for_model(EntryModel)\n    entry_filter = {\n        'status': EntryModel.PUBLISHED\n    }\n    if appsettings.FLUENT_BLOGS_FILTER_SITE_ID:\n        entry_filter['parent_site'] = settings.SITE_ID\n    entry_qs = EntryModel.objects.filter(**entry_filter).values_list('pk')\n    queryset = Tag.objects.filter(\n        taggit_taggeditem_items__content_type=ct,\n        taggit_taggeditem_items__object_id__in=entry_qs\n    ).annotate(\n        count=Count('taggit_taggeditem_items')\n    )\n    if orderby:\n        queryset = queryset.order_by(*_get_order_by(order, orderby, TAG_ORDER_BY_FIELDS))\n    else:\n        queryset = queryset.order_by('-count')\n    if limit:\n        queryset = queryset[:limit]\n    return queryset",
    "docstring": "Query the tags, with usage count included.\n    This interface is mainly used by the ``get_tags`` template tag."
  },
  {
    "code": "def get_day_end(config):\n    day_start_datetime = datetime.datetime.combine(datetime.date.today(), config['day_start'])\n    day_end_datetime = day_start_datetime - datetime.timedelta(seconds=1)\n    return day_end_datetime.time()",
    "docstring": "Get the day end time given the day start. This assumes full 24h day.\n\n    Args:\n        config (dict): Configdict. Needed to extract ``day_start``.\n\n    Note:\n        This is merely a convinience funtion so we do not have to deduct this from ``day_start``\n        by hand all the time."
  },
  {
    "code": "def get_token_network_identifiers(\n        chain_state: ChainState,\n        payment_network_id: PaymentNetworkID,\n) -> List[TokenNetworkID]:\n    payment_network = chain_state.identifiers_to_paymentnetworks.get(payment_network_id)\n    if payment_network is not None:\n        return [\n            token_network.address\n            for token_network in payment_network.tokenidentifiers_to_tokennetworks.values()\n        ]\n    return list()",
    "docstring": "Return the list of token networks registered with the given payment network."
  },
  {
    "code": "def get_file_handler(file_path=\"out.log\", level=logging.INFO,\n                     log_format=log_formats.easy_read,\n                     handler=logging.FileHandler,\n                     **handler_kwargs):\n    fh = handler(file_path, **handler_kwargs)\n    fh.setLevel(level)\n    fh.setFormatter(logging.Formatter(log_format))\n    return fh",
    "docstring": "Set up a file handler to add to a logger.\n\n    :param file_path: file to write the log to, defaults to out.log\n    :param level: logging level to set handler at\n    :param log_format: formatter to use\n    :param handler: logging handler to use, defaults to FileHandler\n    :param handler_kwargs: options to pass to the handler\n    :return: handler"
  },
  {
    "code": "def norm_package_version(version):\n    if version:\n        version = ','.join(v.strip() for v in version.split(',')).strip()\n        if version.startswith('(') and version.endswith(')'):\n            version = version[1:-1]\n        version = ''.join(v for v in version if v.strip())\n    else:\n        version = ''\n    return version",
    "docstring": "Normalize a version by removing extra spaces and parentheses."
  },
  {
    "code": "def verify_checksum(self):\n        res = self._FITS.verify_checksum(self._ext+1)\n        if res['dataok'] != 1:\n            raise ValueError(\"data checksum failed\")\n        if res['hduok'] != 1:\n            raise ValueError(\"hdu checksum failed\")",
    "docstring": "Verify the checksum in the header for this HDU."
  },
  {
    "code": "def stream(self, status=values.unset, phone_number=values.unset,\n               incoming_phone_number_sid=values.unset, friendly_name=values.unset,\n               unique_name=values.unset, limit=None, page_size=None):\n        limits = self._version.read_limits(limit, page_size)\n        page = self.page(\n            status=status,\n            phone_number=phone_number,\n            incoming_phone_number_sid=incoming_phone_number_sid,\n            friendly_name=friendly_name,\n            unique_name=unique_name,\n            page_size=limits['page_size'],\n        )\n        return self._version.stream(page, limits['limit'], limits['page_limit'])",
    "docstring": "Streams DependentHostedNumberOrderInstance records from the API as a generator stream.\n        This operation lazily loads records as efficiently as possible until the limit\n        is reached.\n        The results are returned as a generator, so this operation is memory efficient.\n\n        :param DependentHostedNumberOrderInstance.Status status: The Status of this HostedNumberOrder.\n        :param unicode phone_number: An E164 formatted phone number.\n        :param unicode incoming_phone_number_sid: IncomingPhoneNumber sid.\n        :param unicode friendly_name: A human readable description of this resource.\n        :param unicode unique_name: A unique, developer assigned name of this HostedNumberOrder.\n        :param int limit: Upper limit for the number of records to return. stream()\n                          guarantees to never return more than limit.  Default is no limit\n        :param int page_size: Number of records to fetch per request, when not set will use\n                              the default value of 50 records.  If no page_size is defined\n                              but a limit is defined, stream() will attempt to read the\n                              limit with the most efficient page size, i.e. min(limit, 1000)\n\n        :returns: Generator that will yield up to limit results\n        :rtype: list[twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance]"
  },
  {
    "code": "def calcOffset(self, x, y):\n        return x + self.size * (self.size - y - 1)",
    "docstring": "Calculate offset into data array. Only uses to test correctness\n            of the formula."
  },
  {
    "code": "def search(self, keyword):\n        params = {\n            \"source\": \"map\",\n            \"description\": keyword\n        }\n        data = self._request(ENDPOINTS['SEARCH'], params)\n        data['result_data'] = [res for res in data['result_data'] if isinstance(res, dict)]\n        return data",
    "docstring": "Return all buildings related to the provided query.\n\n        :param keyword:\n            The keyword for your map search\n\n        >>> results = n.search('Harrison')"
  },
  {
    "code": "def get_model_url_base():\n    url_base = get_model_url_base_from_env()\n    if url_base is not None:\n        logger.info('NNBLA_MODELS_URL_BASE is set as {}.'.format(url_base))\n    else:\n        url_base = 'https://nnabla.org/pretrained-models/nnp_models/'\n    return url_base",
    "docstring": "Returns a root folder for models."
  },
  {
    "code": "def parse_column_names(text):\n    return tuple(\n        re.sub(r\"^`(.*)`$\", r\"\\1\", column_data.strip())\n        for column_data in text.split(\",\")\n    )",
    "docstring": "Extracts column names from a string containing quoted and comma separated\n    column names of a table.\n\n    :param text: Line extracted from MySQL's `INSERT INTO` statement containing\n                 quoted and comma separated column names.\n    :type text: str\n\n    :return: Tuple containing just the column names.\n    :rtype: tuple[str]"
  },
  {
    "code": "def _queue_models(self, models, context):\n        model_queue = []\n        number_remaining_models = len(models)\n        MAX_CYCLES = number_remaining_models\n        allowed_cycles = MAX_CYCLES\n        while number_remaining_models > 0:\n            previous_number_remaining_models = number_remaining_models\n            model = models.pop(0)\n            if check_dependencies(model, model_queue, context[\"__avaliable_models\"]):\n                model_class = ModelCode(model=model, context=context, stdout=self.stdout, stderr=self.stderr, options=self.options)\n                model_queue.append(model_class)\n            else:\n                models.append(model)\n            number_remaining_models = len(models)\n            if number_remaining_models == previous_number_remaining_models:\n                allowed_cycles -= 1\n                if allowed_cycles <= 0:\n                    missing_models = [ModelCode(model=m, context=context, stdout=self.stdout, stderr=self.stderr, options=self.options) for m in models]\n                    model_queue += missing_models\n                    models[:] = missing_models\n                    break\n            else:\n                allowed_cycles = MAX_CYCLES\n        return model_queue",
    "docstring": "Work an an appropriate ordering for the models.\n        This isn't essential, but makes the script look nicer because\n        more instances can be defined on their first try."
  },
  {
    "code": "def admin_password(self, environment, target_name, password):\n        try:\n            remote_server_command(\n                [\"ssh\", environment.deploy_target,\n                    \"admin_password\", target_name, password],\n                environment, self,\n                clean_up=True\n                )\n            return True\n        except WebCommandError:\n            return False",
    "docstring": "Return True if password was set successfully"
  },
  {
    "code": "def getBufferedFiles(self, block_id):\n        try:\n            conn = self.dbi.connection()\n            result = self.buflist.execute(conn, block_id)\n            return result\n        finally:\n            if conn:\n                conn.close()",
    "docstring": "Get some files from the insert buffer"
  },
  {
    "code": "def _read_file(self, filename):\n        if self.__compression:\n            f = gzip.GzipFile(filename, \"rb\")\n        else:\n            f = open(filename, \"rb\")\n        res = pickle.load(f)\n        f.close()\n        return res",
    "docstring": "read a Python object from a cache file.\n\n        Reads a pickled object from disk and returns it.\n\n        :param filename: Name of the file that should be read.\n        :type filename: str\n        :rtype: object"
  },
  {
    "code": "def _load(self, files_in, files_out, urlpath, meta=True):\n        import dask\n        out = []\n        outnames = []\n        for file_in, file_out in zip(files_in, files_out):\n            cache_path = file_out.path\n            outnames.append(cache_path)\n            if cache_path == urlpath:\n                continue\n            if not os.path.isfile(cache_path):\n                logger.debug(\"Caching file: {}\".format(file_in.path))\n                logger.debug(\"Original path: {}\".format(urlpath))\n                logger.debug(\"Cached at: {}\".format(cache_path))\n                if meta:\n                    self._log_metadata(urlpath, file_in.path, cache_path)\n                ddown = dask.delayed(_download)\n                out.append(ddown(file_in, file_out, self.blocksize,\n                                 self.output))\n        dask.compute(*out)\n        return outnames",
    "docstring": "Download a set of files"
  },
  {
    "code": "def connected_component_labels(edges, node_count=None):\n    matrix = edges_to_coo(edges, node_count)\n    body_count, labels = csgraph.connected_components(\n        matrix, directed=False)\n    assert len(labels) == node_count\n    return labels",
    "docstring": "Label graph nodes from an edge list, using scipy.sparse.csgraph\n\n    Parameters\n    ----------\n    edges : (n, 2) int\n       Edges of a graph\n    node_count : int, or None\n        The largest node in the graph.\n\n    Returns\n    ---------\n    labels : (node_count,) int\n        Component labels for each node"
  },
  {
    "code": "def update_authorization(self, authorization_form):\n        collection = JSONClientValidated('authorization',\n                                         collection='Authorization',\n                                         runtime=self._runtime)\n        if not isinstance(authorization_form, ABCAuthorizationForm):\n            raise errors.InvalidArgument('argument type is not an AuthorizationForm')\n        if not authorization_form.is_for_update():\n            raise errors.InvalidArgument('the AuthorizationForm is for update only, not create')\n        try:\n            if self._forms[authorization_form.get_id().get_identifier()] == UPDATED:\n                raise errors.IllegalState('authorization_form already used in an update transaction')\n        except KeyError:\n            raise errors.Unsupported('authorization_form did not originate from this session')\n        if not authorization_form.is_valid():\n            raise errors.InvalidArgument('one or more of the form elements is invalid')\n        collection.save(authorization_form._my_map)\n        self._forms[authorization_form.get_id().get_identifier()] = UPDATED\n        return objects.Authorization(\n            osid_object_map=authorization_form._my_map,\n            runtime=self._runtime,\n            proxy=self._proxy)",
    "docstring": "Updates an existing authorization.\n\n        arg:    authorization_form\n                (osid.authorization.AuthorizationForm): the\n                authorization ``Id``\n        raise:  IllegalState - ``authorization_form`` already used in an\n                update transaction\n        raise:  InvalidArgument - one or more of the form elements is\n                invalid\n        raise:  NullArgument - ``authorization_form`` is ``null``\n        raise:  OperationFailed - ``unable to complete request``\n        raise:  PermissionDenied - authorization failure\n        raise:  Unsupported - ``authorization_form`` did not originate\n                from ``get_authorization_form_for_update()``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def fire_master(self, data, tag, preload=None):\n        load = {}\n        if preload:\n            load.update(preload)\n        load.update({\n            'id': self.opts['id'],\n            'tag': tag,\n            'data': data,\n            'cmd': '_minion_event',\n            'tok': self.auth.gen_token(b'salt'),\n        })\n        channel = salt.transport.client.ReqChannel.factory(self.opts)\n        try:\n            channel.send(load)\n        except Exception:\n            pass\n        finally:\n            channel.close()\n        return True",
    "docstring": "Fire an event off on the master server\n\n        CLI Example:\n\n        .. code-block:: bash\n\n            salt '*' event.fire_master 'stuff to be in the event' 'tag'"
  },
  {
    "code": "def flatten(l, unique=True):\n    l = reduce(lambda x, y: x + y, l)\n    if not unique:\n        return list(l)\n    return list(set(l))",
    "docstring": "flatten a list of lists\n\n    Parameters\n    ----------\n    l          : list\n                 of lists\n    unique     : boolean\n                 whether or not only unique items are wanted (default=True)\n\n    Returns\n    -------\n    list\n        of single items\n\n    Examples\n    --------\n\n    Creating a sample list whose elements are lists of integers\n\n    >>> l = [[1, 2], [3, 4, ], [5, 6]]\n\n    Applying flatten function\n\n    >>> flatten(l)\n    [1, 2, 3, 4, 5, 6]"
  },
  {
    "code": "def call_workflow_event(instance, event, after=True):\n    if not event.transition:\n        return False\n    portal_type = instance.portal_type\n    wf_module = _load_wf_module('{}.events'.format(portal_type.lower()))\n    if not wf_module:\n        return False\n    prefix = after and \"after\" or \"before\"\n    func_name = \"{}_{}\".format(prefix, event.transition.id)\n    func = getattr(wf_module, func_name, False)\n    if not func:\n        return False\n    logger.info('WF event: {0}.events.{1}'\n                .format(portal_type.lower(), func_name))\n    func(instance)\n    return True",
    "docstring": "Calls the instance's workflow event"
  },
  {
    "code": "def results_to_csv(query_name, **kwargs):\n    query = get_result_set(query_name, **kwargs)\n    result = query.result\n    columns = list(result[0].keys())\n    data = [tuple(row.values()) for row in result]\n    frame = tablib.Dataset()\n    frame.headers = columns\n    for row in data:\n        frame.append(row)\n    csvs = frame.export('csv')\n    return csvs",
    "docstring": "Generate CSV from result data"
  },
  {
    "code": "def fetch(self,\n              minion_id,\n              pillar,\n              *args,\n              **kwargs):\n        db_name = self._db_name()\n        log.info('Querying %s for information for %s', db_name, minion_id)\n        qbuffer = self.extract_queries(args, kwargs)\n        with self._get_cursor() as cursor:\n            for root, details in qbuffer:\n                cursor.execute(details['query'], (minion_id,))\n                self.process_fields([row[0] for row in cursor.description], details['depth'])\n                self.enter_root(root)\n                self.as_list = details['as_list']\n                if details['with_lists']:\n                    self.with_lists = details['with_lists']\n                else:\n                    self.with_lists = []\n                self.ignore_null = details['ignore_null']\n                self.process_results(cursor.fetchall())\n                log.debug('ext_pillar %s: Return data: %s', db_name, self)\n        return self.result",
    "docstring": "Execute queries, merge and return as a dict."
  },
  {
    "code": "def installedOn(self):\n    try:\n        return self.store.findUnique(_DependencyConnector,\n                                     _DependencyConnector.installee == self\n                                     ).target\n    except ItemNotFound:\n        return None",
    "docstring": "If this item is installed on another item, return the install\n    target. Otherwise return None."
  },
  {
    "code": "def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None,\n              keyid=None, profile=None):\n    if not _exactly_one((vpc_name, vpc_id)):\n        raise SaltInvocationError('One (but not both) of vpc_id or vpc_name '\n                                  'must be provided.')\n    if vpc_name:\n        vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid,\n                         profile=profile)\n    elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid,\n                        profile=profile):\n        log.info('VPC %s does not exist.', vpc_id)\n        return None\n    return vpc_id",
    "docstring": "Check whether a VPC with the given name or id exists.\n    Returns the vpc_id or None. Raises SaltInvocationError if\n    both vpc_id and vpc_name are None. Optionally raise a\n    CommandExecutionError if the VPC does not exist.\n\n    .. versionadded:: 2016.3.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile"
  },
  {
    "code": "def optimizer(name):\n  warn_msg = (\"Please update `registry.optimizer` callsite \"\n              \"(likely due to a `HParams.optimizer` value)\")\n  if name == \"SGD\":\n    name = \"sgd\"\n    tf.logging.warning(\"'SGD' optimizer now keyed by 'sgd'. %s\" % warn_msg)\n  elif name == \"RMSProp\":\n    name = \"rms_prop\"\n    tf.logging.warning(\n        \"'RMSProp' optimizer now keyed by 'rms_prop'. %s\" % warn_msg)\n  else:\n    snake_name = misc_utils.camelcase_to_snakecase(name)\n    if name != snake_name:\n      tf.logging.warning(\n          \"optimizer names now keyed by snake_case names. %s\" % warn_msg)\n      name = snake_name\n  return Registries.optimizers[name]",
    "docstring": "Get pre-registered optimizer keyed by name.\n\n  `name` should be snake case, though SGD -> sgd, RMSProp -> rms_prop and\n  UpperCamelCase -> snake_case conversions included for legacy support.\n\n  Args:\n    name: name of optimizer used in registration. This should be a snake case\n      identifier, though others supported for legacy reasons.\n\n  Returns:\n    optimizer"
  },
  {
    "code": "def split_scene(geometry):\n    if util.is_instance_named(geometry, 'Scene'):\n        return geometry\n    if util.is_sequence(geometry):\n        metadata = {}\n        for g in geometry:\n            try:\n                metadata.update(g.metadata)\n            except BaseException:\n                continue\n        return Scene(geometry,\n                     metadata=metadata)\n    split = collections.deque()\n    metadata = {}\n    for g in util.make_sequence(geometry):\n        split.extend(g.split())\n        metadata.update(g.metadata)\n    if len(split) == 1 and 'file_name' in metadata:\n        split = {metadata['file_name']: split[0]}\n    scene = Scene(split, metadata=metadata)\n    return scene",
    "docstring": "Given a geometry, list of geometries, or a Scene\n    return them as a single Scene object.\n\n    Parameters\n    ----------\n    geometry : splittable\n\n    Returns\n    ---------\n    scene: trimesh.Scene"
  },
  {
    "code": "def CloseCHM(self):\n        if self.filename is not None:\n            chmlib.chm_close(self.file)\n            self.file = None\n            self.filename = ''\n            self.title = \"\"\n            self.home = \"/\"\n            self.index = None\n            self.topics = None\n            self.encoding = None",
    "docstring": "Closes the CHM archive.\n        This function will close the CHM file, if it is open. All variables\n        are also reset."
  },
  {
    "code": "def _updateRepo(self, func, *args, **kwargs):\n        self._repo.open(datarepo.MODE_WRITE)\n        try:\n            func(*args, **kwargs)\n            self._repo.commit()\n        finally:\n            self._repo.close()",
    "docstring": "Runs the specified function that updates the repo with the specified\n        arguments. This method ensures that all updates are transactional,\n        so that if any part of the update fails no changes are made to the\n        repo."
  },
  {
    "code": "def token(self):\n        return self._portalTokenHandler.servertoken(serverURL=self._serverUrl,\n                                                    referer=self._referer)",
    "docstring": "gets the AGS server token"
  },
  {
    "code": "def get_operator_cloud(auth=None):\n    if auth is None:\n        auth = __salt__['config.option']('keystone', {})\n    if 'shade_opcloud' in __context__:\n        if __context__['shade_opcloud'].auth == auth:\n            return __context__['shade_opcloud']\n    __context__['shade_opcloud'] = shade.operator_cloud(**auth)\n    return __context__['shade_opcloud']",
    "docstring": "Return an operator_cloud"
  },
  {
    "code": "def start_container(self):\n        self.__container_lengths.append(self.current_container_length)\n        self.current_container_length = 0\n        new_container_node = _Node()\n        self.__container_node.add_child(new_container_node)\n        self.__container_nodes.append(self.__container_node)\n        self.__container_node = new_container_node",
    "docstring": "Add a node to the tree that represents the start of a container.\n\n        Until end_container is called, any nodes added through add_scalar_value\n        or start_container will be children of this new node."
  },
  {
    "code": "def create(self, name, incident_preference):\n        data = {\n            \"policy\": {\n                \"name\": name,\n                \"incident_preference\": incident_preference\n            }\n        }\n        return self._post(\n            url='{0}alerts_policies.json'.format(self.URL),\n            headers=self.headers,\n            data=data\n        )",
    "docstring": "This API endpoint allows you to create an alert policy\n\n        :type name: str\n        :param name: The name of the policy\n\n        :type incident_preference: str\n        :param incident_preference: Can be PER_POLICY, PER_CONDITION or\n            PER_CONDITION_AND_TARGET\n\n        :rtype: dict\n        :return: The JSON response of the API\n\n        ::\n\n            {\n                \"policy\": {\n                    \"created_at\": \"time\",\n                    \"id\": \"integer\",\n                    \"incident_preference\": \"string\",\n                    \"name\": \"string\",\n                    \"updated_at\": \"time\"\n                }\n            }"
  },
  {
    "code": "def from_non_aligned_residue_IDs(Chain, StartResidueID, EndResidueID, Sequence = None):\n        return PDBSection(Chain, PDB.ResidueID2String(StartResidueID), PDB.ResidueID2String(EndResidueID), Sequence = Sequence)",
    "docstring": "A more forgiving method that does not care about the padding of the residue IDs."
  },
  {
    "code": "def skull_strip(dset,suffix='_ns',prefix=None,unifize=True):\n    return available_method('skull_strip')(dset,suffix,prefix,unifize)",
    "docstring": "attempts to cleanly remove skull from ``dset``"
  },
  {
    "code": "def reset_parameter_group(self, name, reset_all_params=False,\n                              parameters=None):\n        params = {'DBParameterGroupName':name}\n        if reset_all_params:\n            params['ResetAllParameters'] = 'true'\n        else:\n            params['ResetAllParameters'] = 'false'\n            for i in range(0, len(parameters)):\n                parameter = parameters[i]\n                parameter.merge(params, i+1)\n        return self.get_status('ResetDBParameterGroup', params)",
    "docstring": "Resets some or all of the parameters of a ParameterGroup to the\n        default value\n\n        :type key_name: string\n        :param key_name: The name of the ParameterGroup to reset\n\n        :type parameters: list of :class:`boto.rds.parametergroup.Parameter`\n        :param parameters: The parameters to reset.  If not supplied,\n                           all parameters will be reset."
  },
  {
    "code": "def next_frame_ae_tiny():\n  hparams = next_frame_tiny()\n  hparams.bottom[\"inputs\"] = modalities.video_bitwise_bottom\n  hparams.top[\"inputs\"] = modalities.video_top\n  hparams.batch_size = 8\n  hparams.dropout = 0.4\n  return hparams",
    "docstring": "Conv autoencoder, tiny set for testing."
  },
  {
    "code": "def kml(self):\n        url = self._url + \"/kml\"\n        return _kml.KML(url=url,\n                        securityHandler=self._securityHandler,\n                        proxy_url=self._proxy_url,\n                        proxy_port=self._proxy_port,\n                        initialize=True)",
    "docstring": "returns the kml functions for server"
  },
  {
    "code": "def last_message(self, timeout=5):\n        if self._thread is not None:\n            self._thread.join(timeout=timeout)\n        return self._task.last_message",
    "docstring": "Wait a specified amount of time and return\n        the last message from the task\n\n        :rtype: str"
  },
  {
    "code": "def _make_one_char_uppercase(string: str) -> str:\n        if not isinstance(string, str):\n            raise TypeError('string must be a string')\n        if Aux.lowercase_count(string) > 0:\n            while True:\n                cindex = randbelow(len(string))\n                if string[cindex].islower():\n                    aux = list(string)\n                    aux[cindex] = aux[cindex].upper()\n                    string = ''.join(aux)\n                    break\n        return string",
    "docstring": "Make a single char from the string uppercase."
  },
  {
    "code": "def parse_bool(val):\n    true_vals = ('t', 'true', 'yes', 'y', '1', 'on')\n    false_vals = ('f', 'false', 'no', 'n', '0', 'off')\n    val = val.lower()\n    if val in true_vals:\n        return True\n    if val in false_vals:\n        return False\n    raise ValueError('\"%s\" is not a valid bool value' % val)",
    "docstring": "Parse a bool value.\n\n    Handles a series of values, but you should probably standardize on\n    \"true\" and \"false\".\n\n    >>> parse_bool('y')\n    True\n    >>> parse_bool('FALSE')\n    False"
  },
  {
    "code": "def api(f):\n    def wraps(self, *args, **kwargs):\n        try:\n            return f(self, *args, **kwargs)\n        except Exception as e:\n            logging.exception(e)\n            return json_error_response(get_error_msg())\n    return functools.update_wrapper(wraps, f)",
    "docstring": "A decorator to label an endpoint as an API. Catches uncaught exceptions and\n    return the response in the JSON format"
  },
  {
    "code": "def verify(self, signature, msg):\n        if not self.key:\n            return False\n        try:\n            self.key.verify(signature + msg)\n        except ValueError:\n            return False\n        return True",
    "docstring": "Verify the message"
  },
  {
    "code": "def all_stop_places_quays(self) -> list:\n        all_places = self.stops.copy()\n        for quay in self.quays:\n            all_places.append(quay)\n        return all_places",
    "docstring": "Get all stop places and quays"
  },
  {
    "code": "def get_table(table_name):\n    table = get_raw_table(table_name)\n    if isinstance(table, TableFuncWrapper):\n        table = table()\n    return table",
    "docstring": "Get a registered table.\n\n    Decorated functions will be converted to `DataFrameWrapper`.\n\n    Parameters\n    ----------\n    table_name : str\n\n    Returns\n    -------\n    table : `DataFrameWrapper`"
  },
  {
    "code": "def get_lab_managers_formatted_emails(self):\n        users = api.get_users_by_roles(\"LabManager\")\n        users = map(lambda user: (user.getProperty(\"fullname\"),\n                                  user.getProperty(\"email\")), users)\n        return map(self.get_formatted_email, users)",
    "docstring": "Returns a list with lab managers formatted emails"
  },
  {
    "code": "async def serviceViewChanger(self, limit) -> int:\n        if not self.isReady():\n            return 0\n        o = self.serviceViewChangerOutBox(limit)\n        i = await self.serviceViewChangerInbox(limit)\n        return o + i",
    "docstring": "Service the view_changer's inBox, outBox and action queues.\n\n        :return: the number of messages successfully serviced"
  },
  {
    "code": "def read(self, config_dir=None, clear=False, config_file=None):\n        if config_file:\n            data_file = os.path.basename(config_file)\n            data_path = os.path.dirname(config_file)\n            if clear:\n                self.clear()\n            config = munge.load_datafile(data_file, data_path, default=None)\n            if not config:\n                raise IOError(\"Config file not found: %s\" % config_file)\n            munge.util.recursive_update(self.data, config)\n            self._meta_config_dir = data_path\n            return\n        else:\n            return super(Config, self).read(config_dir=config_dir, clear=clear)",
    "docstring": "The munge Config's read function only allows to read from\n        a config directory, but we also want to be able to read\n        straight from a config file as well"
  },
  {
    "code": "def __generate_string(length):\n        return ''.join(\n            SystemRandom().choice(string.ascii_letters + string.digits)\n            for x in range(length)).encode()",
    "docstring": "Generate a string for password creation."
  },
  {
    "code": "def addcomment(self, comment, private=False):\n        vals = self.bugzilla.build_update(comment=comment,\n                                          comment_private=private)\n        log.debug(\"addcomment: update=%s\", vals)\n        return self.bugzilla.update_bugs(self.bug_id, vals)",
    "docstring": "Add the given comment to this bug. Set private to True to mark this\n        comment as private."
  },
  {
    "code": "def build_args(cmd, src, dst):\n    cmd = cmd % (quote(src), quote(dst))\n    args = shlex.split(cmd)\n    return [arg for arg in args if arg]",
    "docstring": "Build arguments list for passing to subprocess.call_check\n\n        :param cmd str: Command string to interpolate src and dst filepaths into.\n            Typically the output of `config.Config.uic_command` or `config.Config.rcc_command`.\n        :param src str: Source filepath.\n        :param dst str: Destination filepath."
  },
  {
    "code": "def _process_params(self, params):\r\n        new_params = OrderedDict()\r\n        for param_name, param_value in sorted(params.items()):\r\n            param_value = params[param_name]\r\n            ParamClass = AirtableParams._get(param_name)\r\n            new_params.update(ParamClass(param_value).to_param_dict())\r\n        return new_params",
    "docstring": "Process params names or values as needed using filters"
  },
  {
    "code": "def parse_escape_sequences(string):\n    string = safe_unicode(string)\n    characters = []\n    i = 0\n    string_len = len(string)\n    while i < string_len:\n        character = string[i]\n        if character == '\\\\':\n            if string[(i + 1):(i + 2)] == 'u':\n                offset = 6\n            else:\n                offset = 2\n            try:\n                json_string = '\"' + string[i:(i + offset)] + '\"'\n                character = scanstring(json_string, 1)[0]\n                characters.append(character)\n                i += offset\n            except ValueError:\n                raise_from(ValueError(string), None)\n        else:\n            characters.append(character)\n            i += 1\n    return ''.join(characters)",
    "docstring": "Parse a string for possible escape sequences.\n\n    Sample usage:\n    >>> parse_escape_sequences('foo\\\\nbar')\n    'foo\\nbar'\n    >>> parse_escape_sequences('foo\\\\\\\\u0256')\n    'foo\\\\u0256'\n\n    :param string:\n        Any string.\n    :type string:\n        `basestring`\n    :raises:\n        :class:`ValueError` if a backslash character is found, but it doesn't\n        form a proper escape sequence with the character(s) that follow.\n    :return:\n        The parsed string. Will parse the standard escape sequences, and also\n        basic \\\\uxxxx escape sequences.\n        \\\\uxxxxxxxxxx escape sequences are not currently supported.\n    :rtype:\n        `unicode`"
  },
  {
    "code": "def dateJDN(year, month, day, calendar):\n    a = (14 - month) // 12\n    y = year + 4800 - a\n    m = month + 12*a - 3\n    if calendar == GREGORIAN:\n        return day + (153*m + 2)//5 + 365*y + y//4 - y//100 + y//400 - 32045\n    else:\n        return day + (153*m + 2)//5 + 365*y + y//4 - 32083",
    "docstring": "Converts date to Julian Day Number."
  },
  {
    "code": "def _piped_input_cl(data, region, tmp_dir, out_base_file, prep_params):\n    return data[\"work_bam\"], _gatk_extract_reads_cl(data, region, prep_params, tmp_dir)",
    "docstring": "Retrieve the commandline for streaming input into preparation step."
  },
  {
    "code": "def run(self):\n        inside = 0\n        for draws in range(1, self.data['samples']):\n            r1, r2 = (random(), random())\n            if r1 ** 2 + r2 ** 2 < 1.0:\n                inside += 1\n            if draws % 1000 != 0:\n                continue\n            yield self.emit('log', {'draws': draws, 'inside': inside})\n            p = inside / draws\n            pi = {\n                'estimate': 4.0 * inside / draws,\n                'uncertainty': 4.0 * math.sqrt(draws * p * (1.0 - p)) / draws,\n            }\n            yield self.set_state(pi=pi)\n        yield self.emit('log', {'action': 'done'})",
    "docstring": "Run when button is pressed."
  },
  {
    "code": "def force_list(data):\n    if data is None:\n        return []\n    elif not isinstance(data, (list, tuple, set)):\n        return [data]\n    elif isinstance(data, (tuple, set)):\n        return list(data)\n    return data",
    "docstring": "Force ``data`` to become a list.\n\n    You should use this method whenever you don't want to deal with the\n    fact that ``NoneType`` can't be iterated over. For example, instead\n    of writing::\n\n        bar = foo.get('bar')\n        if bar is not None:\n            for el in bar:\n                ...\n\n    you can write::\n\n        for el in force_list(foo.get('bar')):\n            ...\n\n    Args:\n        data: any Python object.\n\n    Returns:\n        list: a list representation of ``data``.\n\n    Examples:\n        >>> force_list(None)\n        []\n        >>> force_list('foo')\n        ['foo']\n        >>> force_list(('foo', 'bar'))\n        ['foo', 'bar']\n        >>> force_list(['foo', 'bar', 'baz'])\n        ['foo', 'bar', 'baz']"
  },
  {
    "code": "def make_codon_list(protein_seq, template_dna=None, include_stop=True):\n    codon_list = []\n    if template_dna is None:\n        template_dna = []\n    for i, res in enumerate(protein_seq.upper()):\n        try: template_codon = template_dna[3*i:3*i+3]\n        except IndexError: template_codon = '---'\n        possible_codons = dna.ecoli_reverse_translate[res]\n        possible_codons.sort(\n                key=lambda x: dna.num_mutations(x, template_codon))\n        codon_list.append(possible_codons[0])\n    last_codon = codon_list[-1]\n    stop_codons = dna.ecoli_reverse_translate['.']\n    if include_stop and last_codon not in stop_codons:\n        codon_list.append(stop_codons[0])\n    return codon_list",
    "docstring": "Return a list of codons that would be translated to the given protein \n    sequence.  Codons are picked first to minimize the mutations relative to a \n    template DNA sequence and second to prefer \"optimal\" codons."
  },
  {
    "code": "def args_from_config(func):\n    func_args = signature(func).parameters\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        config = get_config()\n        for i, argname in enumerate(func_args):\n            if len(args) > i or argname in kwargs:\n                continue\n            elif argname in config:\n                kwargs[argname] = config[argname]\n        try:\n            getcallargs(func, *args, **kwargs)\n        except TypeError as exc:\n            msg = \"{}\\n{}\".format(exc.args[0], PALLADIUM_CONFIG_ERROR)\n            exc.args = (msg,)\n            raise exc\n        return func(*args, **kwargs)\n    wrapper.__wrapped__ = func\n    return wrapper",
    "docstring": "Decorator that injects parameters from the configuration."
  },
  {
    "code": "def get_unread_topics(context, topics, user):\n    request = context.get('request', None)\n    return TrackingHandler(request=request).get_unread_topics(topics, user)",
    "docstring": "This will return a list of unread topics for the given user from a given set of topics.\n\n    Usage::\n\n        {% get_unread_topics topics request.user as unread_topics %}"
  },
  {
    "code": "def _parse_order_by(model, order_by):\n    out = []\n    for key in order_by:\n        key = key.strip()\n        if key.startswith(\"+\"):\n            out.append(getattr(model, key[1:]))\n        elif key.startswith(\"-\"):\n            out.append(getattr(model, key[1:]).desc())\n        else:\n            out.append(getattr(model, key))\n    return out",
    "docstring": "This function figures out the list of orderings for the given model and\n        argument.\n\n        Args:\n            model (nautilus.BaseModel): The model to compute ordering against\n            order_by (list of str): the list of fields to order_by. If the field\n                starts with a `+` then the order is acending, if `-` descending,\n                if no character proceeds the field, the ordering is assumed to be\n                ascending.\n\n        Returns:\n            (list of filters): the model filters to apply to the query"
  },
  {
    "code": "def backup_location(src, loc=None):\n    from photon.util.system import get_timestamp\n    src = _path.realpath(src)\n    if not loc or not loc.startswith(_sep):\n        loc = _path.dirname(src)\n    pth = _path.join(_path.basename(src), _path.realpath(loc))\n    out = '%s_backup_%s' % (_path.basename(src), get_timestamp())\n    change_location(src, search_location(out, create_in=pth))",
    "docstring": "Writes Backups of locations\n\n    :param src:\n        The source file/folder to backup\n    :param loc:\n        The target folder to backup into\n\n        The backup will be called `src` + :func:`util.system.get_timestamp`.\n        * If `loc` left to none, the backup gets written in the same \\\n        folder like `src` resides in\n\n        * Otherwise the specified path will be used."
  },
  {
    "code": "def _find_intervals(bundles, duration, step):\n    segments = []\n    for bund in bundles:\n        beg, end = bund['times'][0][0], bund['times'][-1][1]\n        if end - beg >= duration:\n            new_begs = arange(beg, end - duration, step)\n            for t in new_begs:\n                seg = bund.copy()\n                seg['times'] = [(t, t + duration)]\n                segments.append(seg)\n    return segments",
    "docstring": "Divide bundles into segments of a certain duration and a certain step,\n    discarding any remainder."
  },
  {
    "code": "def _maybe_warn_for_unseparable_batches(self, output_key: str):\n        if  output_key not in self._warn_for_unseparable_batches:\n            logger.warning(f\"Encountered the {output_key} key in the model's return dictionary which \"\n                           \"couldn't be split by the batch size. Key will be ignored.\")\n            self._warn_for_unseparable_batches.add(output_key)",
    "docstring": "This method warns once if a user implements a model which returns a dictionary with\n        values which we are unable to split back up into elements of the batch. This is controlled\n        by a class attribute ``_warn_for_unseperable_batches`` because it would be extremely verbose\n        otherwise."
  },
  {
    "code": "def copy(self):\n        new = self.__class__()\n        for dict_attr in (\"symbol2number\", \"number2symbol\", \"dfas\", \"keywords\",\n                          \"tokens\", \"symbol2label\"):\n            setattr(new, dict_attr, getattr(self, dict_attr).copy())\n        new.labels = self.labels[:]\n        new.states = self.states[:]\n        new.start = self.start\n        return new",
    "docstring": "Copy the grammar."
  },
  {
    "code": "def remove_trailing_white_spaces(self):\n        cursor = self.textCursor()\n        block = self.document().findBlockByLineNumber(0)\n        while block.isValid():\n            cursor.setPosition(block.position())\n            if re.search(r\"\\s+$\", block.text()):\n                cursor.movePosition(QTextCursor.EndOfBlock)\n                cursor.movePosition(QTextCursor.StartOfBlock, QTextCursor.KeepAnchor)\n                cursor.insertText(foundations.strings.to_string(block.text()).rstrip())\n            block = block.next()\n        cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)\n        if not cursor.block().text().isEmpty():\n            cursor.insertText(\"\\n\")\n        return True",
    "docstring": "Removes document trailing white spaces.\n\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def get_subsections(self, section_name):\n        subsections = [sec[len(section_name)+1:] for sec in self.sections()\\\n                       if sec.startswith(section_name + '-')]\n        for sec in subsections:\n            sp = sec.split('-')\n            if (len(sp) > 1) and not self.has_section('%s-%s' % (section_name,\n                                                                 sp[0])):\n                raise ValueError( \"Workflow uses the '-' as a delimiter so \"\n                    \"this is interpreted as section-subsection-tag. \"\n                    \"While checking section %s, no section with \"\n                    \"name %s-%s was found. \"\n                    \"If you did not intend to use tags in an \"\n                    \"'advanced user' manner, or do not understand what \"\n                    \"this means, don't use dashes in section \"\n                    \"names. So [injection-nsbhinj] is good. \"\n                    \"[injection-nsbh-inj] is not.\" % (sec, sp[0], sp[1]))\n        if len(subsections) > 0:\n            return [sec.split('-')[0] for sec in subsections]\n        elif self.has_section(section_name):\n            return ['']\n        else:\n            return []",
    "docstring": "Return a list of subsections for the given section name"
  },
  {
    "code": "def create_profiles(self, prefix, weeks, ip_user=False):\n        record_counter = {}\n        for year, week in weeks:\n            file = self.storage.get(prefix, year, week)\n            self.count_records(record_counter, file)\n        print(\"Records read all: {}\".format(self.stat))\n        records_valid = self.filter_counter(record_counter)\n        profiles = defaultdict(list)\n        for year, week in weeks:\n            file = self.storage.get(prefix, year, week)\n            self._create_user_profiles(profiles, file, records_valid, ip_user,\n                                       year, week)\n        return profiles",
    "docstring": "Create the user profiles for the given weeks."
  },
  {
    "code": "def _check_response_for_request_errors(self):\n        if self.response.HighestSeverity == \"ERROR\":\n            for notification in self.response.Notifications:\n                if notification.Severity == \"ERROR\":\n                    raise FedexError(notification.Code,\n                                     notification.Message)",
    "docstring": "Override this in each service module to check for errors that are\n        specific to that module. For example, invalid tracking numbers in\n        a Tracking request."
  },
  {
    "code": "def interlink_translated_content(generator):\n    inspector = GeneratorInspector(generator)\n    for content in inspector.all_contents():\n        interlink_translations(content)",
    "docstring": "Make translations link to the native locations\n\n    for generators that may contain translated content"
  },
  {
    "code": "def _updateTargetFromNode(self):\n        self.plotItem.showGrid(x=self.xGridCti.configValue, y=self.yGridCti.configValue,\n                               alpha=self.alphaCti.configValue)\n        self.plotItem.updateGrid()",
    "docstring": "Applies the configuration to the grid of the plot item."
  },
  {
    "code": "def stop(self):\n        self.camera._get_config()['actions']['movie'].set(False)\n        self.videofile = self.camera._wait_for_event(\n            event_type=lib.GP_EVENT_FILE_ADDED)\n        if self._old_captarget != \"Memory card\":\n            self.camera.config['settings']['capturetarget'].set(\n                self._old_captarget)",
    "docstring": "Stop the capture."
  },
  {
    "code": "def arduino_default_path():\n    if sys.platform == 'darwin':\n        s = path('/Applications/Arduino.app/Contents/Resources/Java')\n    elif sys.platform == 'win32':\n        s = None\n    else:\n        s = path('/usr/share/arduino/')\n    return s",
    "docstring": "platform specific default root path."
  },
  {
    "code": "def load_builtin_slots():\n    builtin_slots = {}\n    for index, line in enumerate(open(BUILTIN_SLOTS_LOCATION)):\n        o =  line.strip().split('\\t')\n        builtin_slots[index] = {'name' : o[0],\n                                'description' : o[1] } \n    return builtin_slots",
    "docstring": "Helper function to load builtin slots from the data location"
  },
  {
    "code": "def communicate(sock, command, settings=[]):\r\n    try:\r\n        COMMUNICATE_LOCK.acquire()\r\n        write_packet(sock, command)\r\n        for option in settings:\r\n            write_packet(sock, option)\r\n        return read_packet(sock)\r\n    finally:\r\n        COMMUNICATE_LOCK.release()",
    "docstring": "Communicate with monitor"
  },
  {
    "code": "def _load_values(self):\n        path = self._config_path()\n        if path is not None and os.path.isfile(path):\n            self._load_file(path)",
    "docstring": "Load config.yaml from the run directory if available."
  },
  {
    "code": "def get_new_document(self, cursor_pos=None):\n        lines = []\n        if self.original_document.text_before_cursor:\n            lines.append(self.original_document.text_before_cursor)\n        for line_no in sorted(self.selected_lines):\n            lines.append(self.history_lines[line_no])\n        if self.original_document.text_after_cursor:\n            lines.append(self.original_document.text_after_cursor)\n        text = '\\n'.join(lines)\n        if cursor_pos is not None and cursor_pos > len(text):\n            cursor_pos = len(text)\n        return Document(text, cursor_pos)",
    "docstring": "Create a `Document` instance that contains the resulting text."
  },
  {
    "code": "def to_dict(self, properties=None):\n        if not properties:\n            skip = {'deposited_compound', 'standardized_compound', 'cids', 'aids'}\n            properties = [p for p in dir(Substance) if isinstance(getattr(Substance, p), property) and p not in skip]\n        return {p: getattr(self, p) for p in properties}",
    "docstring": "Return a dictionary containing Substance data.\n\n        If the properties parameter is not specified, everything except cids and aids is included. This is because the\n        aids and cids properties each require an extra request to retrieve.\n\n        :param properties: (optional) A list of the desired properties."
  },
  {
    "code": "def _prt_edge(dag_edge, attr):\n        print(\"Edge {ATTR}: {VAL}\".format(ATTR=attr, VAL=dag_edge.obj_dict[attr]))",
    "docstring": "Print edge attribute"
  },
  {
    "code": "def DbDeleteDeviceAlias(self, argin):\n        self._log.debug(\"In DbDeleteDeviceAlias()\")\n        self.db.delete_device_alias(argin)",
    "docstring": "Delete a device alias.\n\n        :param argin: device alias name\n        :type: tango.DevString\n        :return:\n        :rtype: tango.DevVoid"
  },
  {
    "code": "def copy_submission_to_destination(self, src_filename, dst_subdir,\n                                     submission_id):\n    extension = [e for e in ALLOWED_EXTENSIONS if src_filename.endswith(e)]\n    if len(extension) != 1:\n      logging.error('Invalid submission extension: %s', src_filename)\n      return\n    dst_filename = os.path.join(self.target_dir, dst_subdir,\n                                submission_id + extension[0])\n    cmd = ['gsutil', 'cp', src_filename, dst_filename]\n    if subprocess.call(cmd) != 0:\n      logging.error('Can\\'t copy submission to destination')\n    else:\n      logging.info('Submission copied to: %s', dst_filename)",
    "docstring": "Copies submission to target directory.\n\n    Args:\n      src_filename: source filename of the submission\n      dst_subdir: subdirectory of the target directory where submission should\n        be copied to\n      submission_id: ID of the submission, will be used as a new\n        submission filename (before extension)"
  },
  {
    "code": "def get_asset_temporal_assignment_session(self):\n        if not self.supports_asset_temporal_assignment():\n            raise Unimplemented()\n        try:\n            from . import sessions\n        except ImportError:\n            raise\n        try:\n            session = sessions.AssetTemporalAssignmentSession(proxy=self._proxy,\n                                                              runtime=self._runtime)\n        except AttributeError:\n            raise\n        return session",
    "docstring": "Gets the session for assigning temporal coverage to an asset.\n\n        return: (osid.repository.AssetTemporalAssignmentSession) - an\n                AssetTemporalAssignmentSession\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - supports_asset_temporal_assignment() is\n                false\n        compliance: optional - This method must be implemented if\n                    supports_asset_temporal_assignment() is true."
  },
  {
    "code": "def build_complex_fault_geometry(fault_source):\n    num_edges = len(fault_source.edges)\n    edge_nodes = []\n    for iloc, edge in enumerate(fault_source.edges):\n        if iloc == 0:\n            node_name = \"faultTopEdge\"\n        elif iloc == (num_edges - 1):\n            node_name = \"faultBottomEdge\"\n        else:\n            node_name = \"intermediateEdge\"\n        edge_nodes.append(\n            Node(node_name,\n                 nodes=[build_linestring_node(edge, with_depth=True)]))\n    return Node(\"complexFaultGeometry\", nodes=edge_nodes)",
    "docstring": "Returns the complex fault source geometry as a Node\n\n    :param fault_source:\n        Complex fault source model as an instance of the :class:\n        `openquake.hazardlib.source.complex_fault.ComplexFaultSource`\n    :returns:\n        Instance of :class:`openquake.baselib.node.Node`"
  },
  {
    "code": "def _get_component(self, string, initial_pos):\n    add_code = string[initial_pos:initial_pos + self.ADDR_CODE_LENGTH]\n    if add_code == 'REM':\n      raise ish_reportException(\"This is a remarks record\")\n    if add_code == 'EQD':\n      raise ish_reportException(\"This is EQD record\")\n    initial_pos += self.ADDR_CODE_LENGTH \n    try:\n      useable_map = self.MAP[add_code]\n    except:\n      raise BaseException(\"Cannot find code %s in string %s (%d).\" % (add_code, string, initial_pos))\n    if useable_map[1] is False:\n      chars_to_read = string[initial_pos + self.ADDR_CODE_LENGTH:initial_pos + \\\n                      (self.ADDR_CODE_LENGTH * 2)]\n      chars_to_read = int(chars_to_read)\n      initial_pos += (self.ADDR_CODE_LENGTH * 2)\n    else:\n      chars_to_read = useable_map[1]\n    new_position = initial_pos + chars_to_read\n    string_value = string[initial_pos:new_position]\n    try:\n      object_value = useable_map[2]()\n      object_value.loads(string_value)\n    except IndexError as err:\n      object_value = string_value\n    return (new_position, [add_code, object_value])",
    "docstring": "given a string and a position, return both an updated position and\n    either a Component Object or a String back to the caller"
  },
  {
    "code": "def is_reserved_ip(self, ip):\n        theip = ipaddress(ip)\n        for res in self._reserved_netmasks:\n            if theip in ipnetwork(res):\n                return True\n        return False",
    "docstring": "Check if the given ip address is in a reserved ipv4 address space.\n\n        :param ip: ip address\n        :return: boolean"
  },
  {
    "code": "def create_reader_of_type(type_name):\n    readers = available_readers()\n    if type_name not in readers.keys():\n        raise UnknownReaderException('Unknown reader: %s' % (type_name,))\n    return readers[type_name]()",
    "docstring": "Create an instance of the reader with the given name.\n\n        Args:\n            type_name: The name of a reader.\n\n        Returns:\n            An instance of the reader with the given type."
  },
  {
    "code": "def setPhysicalMinimum(self, edfsignal, physical_minimum):\n        if (edfsignal < 0 or edfsignal > self.n_channels):\n            raise ChannelDoesNotExist(edfsignal)\n        self.channels[edfsignal]['physical_min'] = physical_minimum\n        self.update_header()",
    "docstring": "Sets the physical_minimum of signal edfsignal.\n\n        Parameters\n        ----------\n        edfsignal: int\n            signal number\n        physical_minimum: float\n            Sets the physical minimum\n\n        Notes\n        -----\n        This function is required for every signal and can be called only after opening a file in writemode and before the first sample write action."
  },
  {
    "code": "def scan(self):\n        self.logger.info('{0} registered scan functions, starting {0} threads '\n                         'to scan candidate proxy lists...'\n                         .format(len(self.scan_funcs)))\n        for i in range(len(self.scan_funcs)):\n            t = threading.Thread(\n                name=self.scan_funcs[i].__name__,\n                target=self.scan_funcs[i],\n                kwargs=self.scan_kwargs[i])\n            t.daemon = True\n            self.scan_threads.append(t)\n            t.start()",
    "docstring": "Start a thread for each registered scan function to scan proxy lists"
  },
  {
    "code": "def _remove_trailing_new_line(l):\n    for n in sorted(new_lines_bytes, key=lambda x: len(x), reverse=True):\n        if l.endswith(n):\n            remove_new_line = slice(None, -len(n))\n            return l[remove_new_line]\n    return l",
    "docstring": "Remove a single instance of new line at the end of l if it exists.\n\n    Returns:\n        bytestring"
  },
  {
    "code": "def get_keyid(keyname):\n    if not keyname:\n        return None\n    keypairs = list_keypairs(call='function')\n    keyid = keypairs[keyname]['id']\n    if keyid:\n        return keyid\n    raise SaltCloudNotFound('The specified ssh key could not be found.')",
    "docstring": "Return the ID of the keyname"
  },
  {
    "code": "def get_app_state(app_id):\n    try:\n        conn = get_conn()\n        c = conn.cursor()\n        c.execute(\"SELECT state FROM app WHERE id='{0}' \".format(app_id))\n        result = c.fetchone()\n        conn.close()\n        if result:\n            state = result[0]\n            return state\n        else:\n            return None\n    except Exception,e:\n        raise RuntimeError('get app state failed! %s' % e)",
    "docstring": "get app state"
  },
  {
    "code": "def path(self, args, kw):\n        params = self._pop_params(args, kw)\n        if args or kw:\n            raise InvalidArgumentError(\"Extra parameters (%s, %s) when building path for %s\" % (args, kw, self.template))\n        return self.build_url(**params)",
    "docstring": "Builds the URL path fragment for this route."
  },
  {
    "code": "def remove(self, fieldspec):\n        pattern = r'(?P<field>[^.]+)(.(?P<subfield>[^.]+))?'\n        match = re.match(pattern, fieldspec)\n        if not match:\n            return None\n        grp = match.groupdict()\n        for field in self.get_fields(grp['field']):\n            if grp['subfield']:\n                updated = []\n                for code, value in pairwise(field.subfields):\n                    if not code == grp['subfield']:\n                        updated += [code, value]\n                if not updated:\n                    self.remove_field(field)\n                else:\n                    field.subfields = updated\n            else:\n                self.remove_field(field)",
    "docstring": "Removes fields or subfields according to `fieldspec`.\n\n        If a non-control field subfield removal leaves no other subfields,\n        delete the field entirely."
  },
  {
    "code": "def create(self, **kwargs):\n        url_str = self.base_url\n        if 'tenant_id' in kwargs:\n            url_str = url_str + '?tenant_id=%s' % kwargs['tenant_id']\n            del kwargs['tenant_id']\n        data = kwargs['jsonbody'] if 'jsonbody' in kwargs else kwargs\n        body = self.client.create(url=url_str, json=data)\n        return body",
    "docstring": "Create a metric."
  },
  {
    "code": "def get_clean_interp_index(arr, dim, use_coordinate=True, **kwargs):\n    if use_coordinate:\n        if use_coordinate is True:\n            index = arr.get_index(dim)\n        else:\n            index = arr.coords[use_coordinate]\n            if index.ndim != 1:\n                raise ValueError(\n                    'Coordinates used for interpolation must be 1D, '\n                    '%s is %dD.' % (use_coordinate, index.ndim))\n        try:\n            index = index.values.astype(np.float64)\n        except (TypeError, ValueError):\n            raise TypeError('Index must be castable to float64 to support'\n                            'interpolation, got: %s' % type(index))\n        if not (np.diff(index) > 0).all():\n            raise ValueError(\"Index must be monotonicly increasing\")\n    else:\n        axis = arr.get_axis_num(dim)\n        index = np.arange(arr.shape[axis], dtype=np.float64)\n    return index",
    "docstring": "get index to use for x values in interpolation.\n\n    If use_coordinate is True, the coordinate that shares the name of the\n    dimension along which interpolation is being performed will be used as the\n    x values.\n\n    If use_coordinate is False, the x values are set as an equally spaced\n    sequence."
  },
  {
    "code": "def gets(self):\n        ret = self.stdin.readline()\n        if ret == '':\n            raise EOFError\n        return ret.rstrip('\\n')",
    "docstring": "Read line from stdin.\n\n        The trailing newline will be omitted.\n        :return: string:"
  },
  {
    "code": "def follow(the_file):\n    with open(the_file) as f:\n        f.seek(0, 2)\n        while True:\n            line = f.readline()\n            if not line:\n                time.sleep(0.1)\n                continue\n            yield line",
    "docstring": "Follow a given file and yield new lines when they are available, like `tail -f`."
  },
  {
    "code": "def Reset(self):\n    self.state = \"INITIAL\"\n    self.state_stack = []\n    self.buffer = \"\"\n    self.error = 0\n    self.verbose = 0\n    self.processed = 0\n    self.processed_buffer = \"\"",
    "docstring": "Reset the lexer to process a new data feed."
  },
  {
    "code": "def read_tsv(cls, file_path: str, gene_table: ExpGeneTable = None,\n                 encoding: str = 'UTF-8', sep: str = '\\t'):\n        matrix = cls(pd.read_csv(file_path, sep=sep, index_col=0, header=0,\n                                 encoding=encoding))\n        ind = pd.read_csv(file_path, sep=sep, usecols=[0, ], header=None,\n                          skiprows=1, encoding=encoding, na_filter=False)\n        matrix.index = ind.iloc[:, 0]\n        matrix.index.name = 'Genes'\n        if gene_table is not None:\n            matrix = matrix.filter_genes(gene_table.gene_names)\n        return matrix",
    "docstring": "Read expression matrix from a tab-delimited text file.\n\n        Parameters\n        ----------\n        file_path: str\n            The path of the text file.\n        gene_table: `ExpGeneTable` object, optional\n            The set of valid genes. If given, the genes in the text file will\n            be filtered against this set of genes. (None)\n        encoding: str, optional\n            The file encoding. (\"UTF-8\")\n        sep: str, optional\n            The separator. (\"\\t\")\n\n        Returns\n        -------\n        `ExpMatrix`\n            The expression matrix."
  },
  {
    "code": "def profile_delete(self):\n        self.validate_profile_exists()\n        profile_data = self.profiles.get(self.args.profile_name)\n        fqfn = profile_data.get('fqfn')\n        with open(fqfn, 'r+') as fh:\n            data = json.load(fh)\n            for profile in data:\n                if profile.get('profile_name') == self.args.profile_name:\n                    data.remove(profile)\n            fh.seek(0)\n            fh.write(json.dumps(data, indent=2, sort_keys=True))\n            fh.truncate()\n        if not data:\n            os.remove(fqfn)",
    "docstring": "Delete an existing profile."
  },
  {
    "code": "def hash_function(self):\n        assert hasattr(self, 'f1') and hasattr(self, 'f2')\n        f1, f2, g = self.f1, self.f2, self.g\n        def czech_hash(word):\n            v1 = f1(word)\n            v2 = f2(word)\n            return g[v1] + g[v2]\n        return czech_hash",
    "docstring": "Returns the hash function proper. Ensures that `self` is not bound to\n        the returned closure."
  },
  {
    "code": "def unescape(self):\n        for i, k in enumerate(self._html_escape_table):\n            v = self._html_escape_table[k]\n            self.obj = self.obj.replace(v, k)\n        return self._wrap(self.obj)",
    "docstring": "Within an interpolation, evaluation, or escaping, remove HTML escaping\n        that had been previously added."
  },
  {
    "code": "def call(self, method_path, **kwargs):\n        interface, method = method_path.split('.', 1)\n        return getattr(getattr(self, interface), method)(**kwargs)",
    "docstring": "Make an API call for specific method\n\n        :param method_path: format ``Interface.Method`` (e.g. ``ISteamWebAPIUtil.GetServerInfo``)\n        :type method_path: :class:`str`\n        :param kwargs: keyword arguments for the specific method\n        :return: response\n        :rtype: :class:`dict`, :class:`lxml.etree.Element` or :class:`str`"
  },
  {
    "code": "def parse_from_dict(json_dict):\n    history_columns = json_dict['columns']\n    history_list = MarketHistoryList(\n        upload_keys=json_dict['uploadKeys'],\n        history_generator=json_dict['generator'],\n    )\n    for rowset in json_dict['rowsets']:\n        generated_at = parse_datetime(rowset['generatedAt'])\n        region_id = rowset['regionID']\n        type_id = rowset['typeID']\n        history_list.set_empty_region(region_id, type_id, generated_at)\n        for row in rowset['rows']:\n            history_kwargs = _columns_to_kwargs(\n                SPEC_TO_KWARG_CONVERSION, history_columns, row)\n            historical_date = parse_datetime(history_kwargs['historical_date'])\n            history_kwargs.update({\n                'type_id': type_id,\n                'region_id': region_id,\n                'historical_date': historical_date,\n                'generated_at': generated_at,\n            })\n            history_list.add_entry(MarketHistoryEntry(**history_kwargs))\n    return history_list",
    "docstring": "Given a Unified Uploader message, parse the contents and return a\n    MarketHistoryList instance.\n\n    :param dict json_dict: A Unified Uploader message as a dict.\n    :rtype: MarketOrderList\n    :returns: An instance of MarketOrderList, containing the orders\n        within."
  },
  {
    "code": "def _init_go2res(**kws):\n        if 'goea_results' in kws:\n            return {res.GO:res for res in kws['goea_results']}\n        if 'go2nt' in kws:\n            return kws['go2nt']",
    "docstring": "Initialize GOEA results."
  },
  {
    "code": "def parse(file_path):\n    _, ext = path.splitext(file_path)\n    if ext in ('.yaml', '.yml'):\n        func = yaml.load\n    elif ext == '.json':\n        func = json.load\n    else:\n        raise ValueError(\"Unrecognized config file type %s\" % ext)\n    with open(file_path, 'r') as f:\n        return func(f)",
    "docstring": "Parse a YAML or JSON file."
  },
  {
    "code": "def _normalize_file_paths(self, *args):\n        paths = []\n        for arg in args:\n            if arg is None:\n                continue\n            elif self._is_valid_file(arg):\n                paths.append(arg)\n            elif isinstance(arg, list) and all(self._is_valid_file(_) for _ in arg):\n                paths = paths + arg\n            elif not self.ignore_errors:\n                raise TypeError('Config file paths must be string path or list of paths!')\n        return paths",
    "docstring": "Returns all given configuration file paths as one list."
  },
  {
    "code": "def get_shell_folder (name):\n    try:\n        import _winreg as winreg\n    except ImportError:\n        import winreg\n    lm = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)\n    try:\n        key = winreg.OpenKey(lm, r\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\")\n        try:\n            return winreg.QueryValueEx(key, name)[0]\n        finally:\n            key.Close()\n    finally:\n        lm.Close()",
    "docstring": "Get Windows Shell Folder locations from the registry."
  },
  {
    "code": "def run(self, cmd):\n        cmd = dict(cmd)\n        client = 'minion'\n        mode = cmd.get('mode', 'async')\n        funparts = cmd.get('fun', '').split('.')\n        if len(funparts) > 2 and funparts[0] in ['wheel', 'runner']:\n            client = funparts[0]\n            cmd['fun'] = '.'.join(funparts[1:])\n        if not ('token' in cmd or\n                ('eauth' in cmd and 'password' in cmd and 'username' in cmd)):\n            raise EauthAuthenticationError('No authentication credentials given')\n        executor = getattr(self, '{0}_{1}'.format(client, mode))\n        result = executor(**cmd)\n        return result",
    "docstring": "Execute the salt command given by cmd dict.\n\n        cmd is a dictionary of the following form:\n\n        {\n            'mode': 'modestring',\n            'fun' : 'modulefunctionstring',\n            'kwarg': functionkeywordargdictionary,\n            'tgt' : 'targetpatternstring',\n            'tgt_type' : 'targetpatterntype',\n            'ret' : 'returner namestring',\n            'timeout': 'functiontimeout',\n            'arg' : 'functionpositionalarg sequence',\n            'token': 'salttokenstring',\n            'username': 'usernamestring',\n            'password': 'passwordstring',\n            'eauth': 'eauthtypestring',\n        }\n\n        Implied by the fun is which client is used to run the command, that is, either\n        the master local minion client, the master runner client, or the master wheel client.\n\n        The cmd dict items are as follows:\n\n        mode: either 'sync' or 'asynchronous'. Defaults to 'asynchronous' if missing\n        fun: required. If the function is to be run on the master using either\n            a wheel or runner client then the fun: includes either\n            'wheel.' or 'runner.' as a prefix and has three parts separated by '.'.\n            Otherwise the fun: specifies a module to be run on a minion via the local\n            minion client.\n            Example:\n                fun of 'wheel.config.values' run with master wheel client\n                fun of 'runner.manage.status' run with master runner client\n                fun of 'test.ping' run with local minion client\n                fun of 'wheel.foobar' run with with local minion client not wheel\n        kwarg: A dictionary of keyword function parameters to be passed to the eventual\n               salt function specified by fun:\n        tgt: Pattern string specifying the targeted minions when the implied client is local\n        tgt_type: Optional target pattern type string when client is local minion.\n            Defaults to 'glob' if missing\n        ret: Optional name string of returner when local minion client.\n        arg: Optional positional argument string when local minion client\n        token: the salt token. Either token: is required or the set of username:,\n            password: , and eauth:\n        username: the salt username. Required if token is missing.\n        password: the user's password. Required if token is missing.\n        eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing"
  },
  {
    "code": "def get_resources(connection):\n    resp = connection.describe(verbose=False).split('\\r\\n')\n    resources = [x.replace('a=control:','') for x in resp if (x.find('control:') != -1 and x[-1] != '*' )]\n    return resources",
    "docstring": "Do an RTSP-DESCRIBE request, then parse out available resources from the response"
  },
  {
    "code": "def bash_rule(bash, hostnames):\n    if isinstance(bash, dict):\n        return make_fail('bash_rule',\n                         error_message=\"Run this rule with a cluster archive\")\n    return make_pass('bash_rule', bash=bash, hostname=hostnames)",
    "docstring": "Cluster rule to process bash and hostname info\n\n    ``bash`` and ``hostnames`` are Pandas DataFrames for the facts collected\n    for each host in the cluster.  See\n    https://pandas.pydata.org/pandas-docs/stable/api.html#dataframe\n    for information on available attributes and methods.\n\n    Arguments:\n        bash (pandas.DataFrame): Includes facts from ``bash_version``\n            fact with columns \"name\" and \"version\" and one row per\n            host in the cluster.\n        hostnames (pandas.DataFrame): Includes facts from ``get_hostname``\n            fact with column \"hostname\" and one row per\n            host in the cluster."
  },
  {
    "code": "def run_example(example_name, environ):\n    mod = EXAMPLE_MODULES[example_name]\n    register_calendar(\"YAHOO\", get_calendar(\"NYSE\"), force=True)\n    return run_algorithm(\n        initialize=getattr(mod, 'initialize', None),\n        handle_data=getattr(mod, 'handle_data', None),\n        before_trading_start=getattr(mod, 'before_trading_start', None),\n        analyze=getattr(mod, 'analyze', None),\n        bundle='test',\n        environ=environ,\n        **merge({'capital_base': 1e7}, mod._test_args())\n    )",
    "docstring": "Run an example module from zipline.examples."
  },
  {
    "code": "def dafopw(fname):\n    fname = stypes.stringToCharP(fname)\n    handle = ctypes.c_int()\n    libspice.dafopw_c(fname, ctypes.byref(handle))\n    return handle.value",
    "docstring": "Open a DAF for subsequent write requests.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafopw_c.html\n\n    :param fname: Name of DAF to be opened.\n    :type fname: str\n    :return: Handle assigned to DAF.\n    :rtype: int"
  },
  {
    "code": "def set_tags(self, md5, tags):\n        if isinstance(tags, str):\n            tags = [tags]\n        tag_set = set(tags)\n        self.data_store.store_work_results({'tags': list(tag_set)}, 'tags', md5)",
    "docstring": "Set the tags for this sample"
  },
  {
    "code": "def get_mentions(self, docs=None, sort=False):\n        result = []\n        if docs:\n            docs = docs if isinstance(docs, (list, tuple)) else [docs]\n            for mention_class in self.mention_classes:\n                mentions = (\n                    self.session.query(mention_class)\n                    .filter(mention_class.document_id.in_([doc.id for doc in docs]))\n                    .order_by(mention_class.id)\n                    .all()\n                )\n                if sort:\n                    mentions = sorted(mentions, key=lambda x: x[0].get_stable_id())\n                result.append(mentions)\n        else:\n            for mention_class in self.mention_classes:\n                mentions = (\n                    self.session.query(mention_class).order_by(mention_class.id).all()\n                )\n                if sort:\n                    mentions = sorted(mentions, key=lambda x: x[0].get_stable_id())\n                result.append(mentions)\n        return result",
    "docstring": "Return a list of lists of the mentions associated with this extractor.\n\n        Each list of the return will contain the Mentions for one of the\n        mention classes associated with the MentionExtractor.\n\n        :param docs: If provided, return Mentions from these documents. Else,\n            return all Mentions.\n        :param sort: If sort is True, then return all Mentions sorted by stable_id.\n        :type sort: bool\n        :return: Mentions for each mention_class.\n        :rtype: List of lists."
  },
  {
    "code": "def items(self, *args, **kwargs):\n        return self.get_stream()(self.get_object(*args, **kwargs))",
    "docstring": "Returns a queryset of Actions to use based on the stream method and object."
  },
  {
    "code": "def load_template(path_or_buffer):\n    from itertools import groupby\n    from operator import itemgetter\n    path_or_buffer = _stringify_path(path_or_buffer)\n    if is_file_like(path_or_buffer):\n        templates = json.load(path_or_buffer)\n    else:\n        with open(path_or_buffer, 'r') as f:\n            templates = json.load(f)\n    options = []\n    grouper = itemgetter('page', 'extraction_method')\n    for key, grp in groupby(sorted(templates, key=grouper), grouper):\n        tmp_options = [_convert_template_option(e) for e in grp]\n        if len(tmp_options) == 1:\n            options.append(tmp_options[0])\n            continue\n        option = tmp_options[0]\n        areas = [e.get('area') for e in tmp_options]\n        option['area'] = areas\n        option['multiple_tables'] = True\n        options.append(option)\n    return options",
    "docstring": "Build tabula-py option from template file\n\n    Args:\n        file_like_obj: File like object of Tabula app template\n\n    Returns:\n        `obj`:dict: tabula-py options"
  },
  {
    "code": "def create_datapoint(value, timestamp=None, **tags):\n    if timestamp is None:\n        timestamp = time_millis()\n    if type(timestamp) is datetime:\n        timestamp = datetime_to_time_millis(timestamp)\n    item = { 'timestamp': timestamp,\n             'value': value }\n    if tags is not None:\n        item['tags'] = tags\n    return item",
    "docstring": "Creates a single datapoint dict with a value, timestamp and tags.\n\n    :param value: Value of the datapoint. Type depends on the id's MetricType\n    :param timestamp: Optional timestamp of the datapoint. Uses client current time if not set. Millisecond accuracy. Can be datetime instance also.\n    :param tags: Optional datapoint tags. Not to be confused with metric definition tags"
  },
  {
    "code": "def on_button_release(self, event):\n        self.queue_draw(self.view)\n        x0, y0, x1, y1 = self.x0, self.y0, self.x1, self.y1\n        rectangle = (min(x0, x1), min(y0, y1), abs(x1 - x0), abs(y1 - y0))\n        selected_items = self.view.get_items_in_rectangle(rectangle, intersect=False)\n        self.view.handle_new_selection(selected_items)\n        return True",
    "docstring": "Select or deselect rubber banded groups of items\n\n         The selection of elements is prior and never items are selected or deselected at the same time."
  },
  {
    "code": "def minus(repo_list_a, repo_list_b):\n        included = defaultdict(lambda: False)\n        for repo in repo_list_b:\n            included[repo.full_name] = True\n        a_minus_b = list()\n        for repo in repo_list_a:\n            if not included[repo.full_name]:\n                included[repo.full_name] = True\n                a_minus_b.append(repo)\n        return a_minus_b",
    "docstring": "Method to create a list of repositories such that the repository\n        belongs to repo list a but not repo list b.\n\n        In an ideal scenario we should be able to do this by set(a) - set(b)\n        but as GithubRepositories have shown that set() on them is not reliable\n        resort to this until it is all sorted out.\n\n        :param repo_list_a: List of repositories.\n        :param repo_list_b: List of repositories."
  },
  {
    "code": "def combine_and_save(add_path_list, out_path):\n    add_path_list = list(add_path_list)\n    first_ds_path = add_path_list[0]\n    print('Starting with {}'.format(first_ds_path))\n    combined = MLDataset(first_ds_path)\n    for ds_path in add_path_list[1:]:\n        try:\n            combined = combined + MLDataset(ds_path)\n        except:\n            print('      Failed to add {}'.format(ds_path))\n            traceback.print_exc()\n        else:\n            print('Successfully added {}'.format(ds_path))\n    combined.save(out_path)\n    return",
    "docstring": "Combines whatever datasets that can be combined,\n    and save the bigger dataset to a given location."
  },
  {
    "code": "def _add_logical_operator(self, operator):\n        if not self.c_oper:\n            raise QueryExpressionError(\"Logical operators must be preceded by an expression\")\n        self.current_field = None\n        self.c_oper = None\n        self.l_oper = inspect.currentframe().f_back.f_code.co_name\n        self._query.append(operator)\n        return self",
    "docstring": "Adds a logical operator in query\n\n        :param operator: logical operator (str)\n        :raise:\n            - QueryExpressionError: if a expression hasn't been set"
  },
  {
    "code": "def power_status_update(self, POWER_STATUS):\n        now = time.time()\n        Vservo = POWER_STATUS.Vservo * 0.001\n        Vcc = POWER_STATUS.Vcc * 0.001\n        self.high_servo_voltage = max(self.high_servo_voltage, Vservo)\n        if self.high_servo_voltage > 1 and Vservo < self.settings.servowarn:\n            if now - self.last_servo_warn_time > 30:\n                self.last_servo_warn_time = now\n                self.say(\"Servo volt %.1f\" % Vservo)\n                if Vservo < 1:\n                    self.high_servo_voltage = Vservo\n        if Vcc > 0 and Vcc < self.settings.vccwarn:\n            if now - self.last_vcc_warn_time > 30:\n                self.last_vcc_warn_time = now\n                self.say(\"Vcc %.1f\" % Vcc)",
    "docstring": "update POWER_STATUS warnings level"
  },
  {
    "code": "def combinePlinkBinaryFiles(prefixes, outPrefix):\n    outputFile = None\n    try:\n        outputFile = open(outPrefix + \".files_to_merge\", \"w\")\n    except IOError:\n        msg = \"%(outPrefix)s.filesToMerge: can't write file\" % locals()\n        raise ProgramError(msg)\n    for prefix in prefixes[1:]:\n        print >>outputFile, \" \".join([\n            prefix + i for i in [\".bed\", \".bim\", \".fam\"]\n        ])\n    outputFile.close()\n    plinkCommand = [\"plink\", \"--noweb\", \"--bfile\", prefixes[0],\n                    \"--merge-list\", outPrefix + \".files_to_merge\",\n                    \"--make-bed\", \"--out\", outPrefix]\n    runCommand(plinkCommand)",
    "docstring": "Combine Plink binary files.\n\n    :param prefixes: a list of the prefix of the files that need to be\n                     combined.\n    :param outPrefix: the prefix of the output file (the combined file).\n\n    :type prefixes: list\n    :type outPrefix: str\n\n    It uses Plink to merge a list of binary files (which is a list of prefixes\n    (strings)), and create the final data set which as ``outPrefix`` as the\n    prefix."
  },
  {
    "code": "def add_header(self, name, value):\n        if self.headers is None:\n            self.headers = []\n        self.headers.append(dict(Name=name, Value=value))",
    "docstring": "Attach an email header to send with the message.\n\n        :param name: The name of the header value.\n        :param value: The header value."
  },
  {
    "code": "def raise_db_exception(self):\n        if not self.messages:\n            raise tds_base.Error(\"Request failed, server didn't send error message\")\n        msg = None\n        while True:\n            msg = self.messages[-1]\n            if msg['msgno'] == 3621:\n                self.messages = self.messages[:-1]\n            else:\n                break\n        error_msg = ' '.join(m['message'] for m in self.messages)\n        ex = _create_exception_by_message(msg, error_msg)\n        raise ex",
    "docstring": "Raises exception from last server message\n\n        This function will skip messages: The statement has been terminated"
  },
  {
    "code": "def check_key(self, key: str) -> bool:\n        keys = self.get_keys()\n        return key in keys",
    "docstring": "Checks if key exists in datastore. True if yes, False if no.\n\n        :param: SHA512 hash key\n\n        :return: whether or key not exists in datastore"
  },
  {
    "code": "def tokenize(self, s):\n        javabridge.call(self.jobject, \"tokenize\", \"(Ljava/lang/String;)V\", s)\n        return TokenIterator(self)",
    "docstring": "Tokenizes the string.\n\n        :param s: the string to tokenize\n        :type s: str\n        :return: the iterator\n        :rtype: TokenIterator"
  },
  {
    "code": "def expired(self):\n        self._data[\"_killed\"] = True\n        self.save()\n        raise SessionExpired(self._config.expired_message)",
    "docstring": "Called when an expired session is atime"
  },
  {
    "code": "def stream_messages(self):\n        if self._stream_messages is None:\n            self._stream_messages = StreamMessageList(\n                self._version,\n                service_sid=self._solution['service_sid'],\n                stream_sid=self._solution['sid'],\n            )\n        return self._stream_messages",
    "docstring": "Access the stream_messages\n\n        :returns: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageList\n        :rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageList"
  },
  {
    "code": "async def download_file_by_id(self, file_id: base.String, destination=None,\n                                  timeout: base.Integer = 30, chunk_size: base.Integer = 65536,\n                                  seek: base.Boolean = True):\n        file = await self.get_file(file_id)\n        return await self.download_file(file_path=file.file_path, destination=destination,\n                                        timeout=timeout, chunk_size=chunk_size, seek=seek)",
    "docstring": "Download file by file_id to destination\n\n        if You want to automatically create destination (:class:`io.BytesIO`) use default\n        value of destination and handle result of this method.\n\n        :param file_id: str\n        :param destination: filename or instance of :class:`io.IOBase`. For e. g. :class:`io.BytesIO`\n        :param timeout: int\n        :param chunk_size: int\n        :param seek: bool - go to start of file when downloading is finished\n        :return: destination"
  },
  {
    "code": "def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):\n    ax.xaxis.set_ticks_position('bottom')\n    ax.yaxis.set_ticks_position(yticks_position)\n    ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,\n                             pad=tick_padding, length=2, width=0.5)\n    ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,\n                             pad=tick_padding, length=2, width=0.5)\n    ax.xaxis.labelpad = label_padding\n    ax.yaxis.labelpad = label_padding\n    ax.xaxis.label.set_size(fontsize)\n    ax.yaxis.label.set_size(fontsize)",
    "docstring": "Set standardized axis formatting for figure."
  },
  {
    "code": "def generate_semantic_data_key(used_semantic_keys):\n    semantic_data_id_counter = -1\n    while True:\n        semantic_data_id_counter += 1\n        if \"semantic data key \" + str(semantic_data_id_counter) not in used_semantic_keys:\n            break\n    return \"semantic data key \" + str(semantic_data_id_counter)",
    "docstring": "Create a new and unique semantic data key\n\n    :param list used_semantic_keys: Handed list of keys already in use\n    :rtype: str\n    :return: semantic_data_id"
  },
  {
    "code": "def send_message(self, message):\n        if self.connected:\n            self.send(\n                json.dumps(message.request))",
    "docstring": "Send a message down the socket. The message is expected\n        to have a `request` attribute that holds the message to\n        be serialized and sent."
  },
  {
    "code": "def _parse_title(line_iter, cur_line, conf):\n    title = []\n    conf['title'].append(title)\n    title.append(('title_name', cur_line.split('title', 1)[1].strip()))\n    while (True):\n        line = next(line_iter)\n        if line.startswith(\"title \"):\n            return line\n        cmd, opt = _parse_cmd(line)\n        title.append((cmd, opt))",
    "docstring": "Parse \"title\" in grub v1 config"
  },
  {
    "code": "def explicit_counts_map(self, pixels=None):\n        if self.hpx._ipix is None:\n            if self.data.ndim == 2:\n                summed = self.counts.sum(0)\n                if pixels is None:\n                    nz = summed.nonzero()[0]\n                else:\n                    nz = pixels\n                data_out = np.vstack(self.data[i].flat[nz]\n                                     for i in range(self.data.shape[0]))\n            else:\n                if pixels is None:\n                    nz = self.data.nonzero()[0]\n                else:\n                    nz = pixels\n                data_out = self.data[nz]\n            return (nz, data_out)\n        else:\n            if pixels is None:\n                return (self.hpx._ipix, self.data)\n        raise RuntimeError(\n            'HPX.explicit_counts_map called with pixels for a map that already has pixels')",
    "docstring": "return a counts map with explicit index scheme\n\n        Parameters\n        ----------\n        pixels : `np.ndarray` or None\n            If set, grab only those pixels.  \n            If none, grab only non-zero pixels"
  },
  {
    "code": "def set_codes(self, codes):\n        codemap = ''\n        for cc in codes:\n            cc = cc.upper()\n            if cc in self.__ccodes:\n                codemap += cc\n            else:\n                raise UnknownCountryCodeException(cc)\n        self.codes = codemap",
    "docstring": "Set the country code map for the data.\n        Codes given in a list.\n\n        i.e. DE - Germany\n             AT - Austria\n             US - United States"
  },
  {
    "code": "def prepend_path_variable_command(variable, paths):\n    assert isinstance(variable, basestring)\n    assert is_iterable_typed(paths, basestring)\n    return path_variable_setting_command(\n        variable, paths + [expand_variable(variable)])",
    "docstring": "Returns a command that prepends the given paths to the named path variable on\n        the current platform."
  },
  {
    "code": "def write_relationships(self, file_name, flat=True):\n        with open(file_name, 'w') as writer:\n            if flat:\n                self._write_relationships_flat(writer)\n            else:\n                self._write_relationships_non_flat(writer)",
    "docstring": "This module will output the eDNA tags which are used inside each\n        calculation.\n\n        If flat=True, data will be written flat, like:\n            ADE1CA01, ADE1PI01, ADE1PI02\n\n        If flat=False, data will be written in the non-flat way, like:\n            ADE1CA01, ADE1PI01\n            ADE1CA01, ADE1PI02\n\n        :param file_name: the output filename to write the relationships,\n                          which should include the '.csv' extension\n        :param flat: True or False"
  },
  {
    "code": "def namer(cls, imageUrl, pageUrl):\n        imgname = imageUrl.split('/')[-1]\n        imgbase = imgname.rsplit('-', 1)[0]\n        imgext = imgname.rsplit('.', 1)[1]\n        return '%s.%s' % (imgbase, imgext)",
    "docstring": "Remove random junk from image names."
  },
  {
    "code": "def isValid(folder, epoch=0):\n    return os.path.exists(os.path.join(folder, str(epoch), \"train\", \"silence.pkl\"))",
    "docstring": "Check if the given folder is a valid preprocessed dataset"
  },
  {
    "code": "def _simplify_non_context_field_binary_composition(expression):\n    if any((isinstance(expression.left, ContextField),\n            isinstance(expression.right, ContextField))):\n        raise AssertionError(u'Received a BinaryComposition {} with a ContextField '\n                             u'operand. This should never happen.'.format(expression))\n    if expression.operator == u'||':\n        if expression.left == TrueLiteral or expression.right == TrueLiteral:\n            return TrueLiteral\n        else:\n            return expression\n    elif expression.operator == u'&&':\n        if expression.left == TrueLiteral:\n            return expression.right\n        if expression.right == TrueLiteral:\n            return expression.left\n        else:\n            return expression\n    else:\n        return expression",
    "docstring": "Return a simplified BinaryComposition if either operand is a TrueLiteral.\n\n    Args:\n        expression: BinaryComposition without any ContextField operand(s)\n\n    Returns:\n        simplified expression if the given expression is a disjunction/conjunction\n        and one of it's operands is a TrueLiteral,\n        and the original expression otherwise"
  },
  {
    "code": "def who_has(self, subid):\n        answer = []\n        for name in self.__map:\n            if subid in self.__map[name] and not name in answer:\n                answer.append(name)\n        return answer",
    "docstring": "Return a list of names who own subid in their id range set."
  },
  {
    "code": "def formation_energy(self, chemical_potentials=None, fermi_level=0):\n        chemical_potentials = chemical_potentials if chemical_potentials else {}\n        chempot_correction = sum([\n            chem_pot * (self.bulk_structure.composition[el] - self.defect.defect_composition[el])\n            for el, chem_pot in chemical_potentials.items()\n        ])\n        formation_energy = self.energy + chempot_correction\n        if \"vbm\" in self.parameters:\n            formation_energy += self.charge * (self.parameters[\"vbm\"] + fermi_level)\n        else:\n            formation_energy += self.charge * fermi_level\n        return formation_energy",
    "docstring": "Computes the formation energy for a defect taking into account a given chemical potential and fermi_level"
  },
  {
    "code": "def run(options, http_req_handler = HttpReqHandler):\n    global _HTTP_SERVER\n    for x in ('server_version', 'sys_version'):\n        if _OPTIONS.get(x) is not None:\n            setattr(http_req_handler, x, _OPTIONS[x])\n    _HTTP_SERVER = threading_tcp_server.KillableThreadingHTTPServer(\n                       _OPTIONS,\n                       (_OPTIONS['listen_addr'], _OPTIONS['listen_port']),\n                       http_req_handler,\n                       name = \"httpdis\")\n    for name, cmd in _COMMANDS.iteritems():\n        if cmd.at_start:\n            LOG.info(\"at_start: %r\", name)\n            cmd.at_start(options)\n    LOG.info(\"will now serve\")\n    while not _KILLED:\n        try:\n            _HTTP_SERVER.serve_until_killed()\n        except (socket.error, select.error), why:\n            if errno.EINTR == why[0]:\n                LOG.debug(\"interrupted system call\")\n            elif errno.EBADF == why[0] and _KILLED:\n                LOG.debug(\"server close\")\n            else:\n                raise\n    LOG.info(\"exiting\")",
    "docstring": "Start and execute the server"
  },
  {
    "code": "def include(self, pattern):\n        found = [f for f in glob(pattern) if not os.path.isdir(f)]\n        self.extend(found)\n        return bool(found)",
    "docstring": "Include files that match 'pattern'."
  },
  {
    "code": "def run(self, **kwargs):\n        self.saveas('in.idf')\n        idd = kwargs.pop('idd', self.iddname)\n        epw = kwargs.pop('weather', self.epw)\n        try:\n            run(self, weather=epw, idd=idd, **kwargs)\n        finally:\n            os.remove('in.idf')",
    "docstring": "Run an IDF file with a given EnergyPlus weather file. This is a\n        wrapper for the EnergyPlus command line interface.\n\n        Parameters\n        ----------\n        **kwargs\n            See eppy.runner.functions.run()"
  },
  {
    "code": "def list_domains_by_service(self, service_id):\n\t\tcontent = self._fetch(\"/service/%s/domain\" % service_id, method=\"GET\")\n\t\treturn map(lambda x: FastlyDomain(self, x), content)",
    "docstring": "List the domains within a service."
  },
  {
    "code": "def summary(self):\n        if self.features is not None:\n            feature_count = len(self.features)\n        else:\n            feature_count = 0\n        feature_hash = 'feathash:' + str(hash(tuple(self.features)))\n        return (str(self.estimator), feature_count, feature_hash, self.target)",
    "docstring": "Summary of model definition for labeling. Intended to be somewhat\n        readable but unique to a given model definition."
  },
  {
    "code": "def draw(self, **kwargs):\n        labels = (\"Training Score\", \"Cross Validation Score\")\n        curves = (\n            (self.train_scores_mean_, self.train_scores_std_),\n            (self.test_scores_mean_, self.test_scores_std_),\n        )\n        colors = resolve_colors(n_colors=2)\n        for idx, (mean, std) in enumerate(curves):\n            self.ax.fill_between(\n                self.train_sizes_, mean - std, mean+std, alpha=0.25,\n                color=colors[idx],\n            )\n        for idx, (mean, _) in enumerate(curves):\n            self.ax.plot(\n                self.train_sizes_, mean, 'o-', color=colors[idx],\n                label=labels[idx],\n            )\n        return self.ax",
    "docstring": "Renders the training and test learning curves."
  },
  {
    "code": "def get_delay(self, planned, estimated):\n        delay = 0\n        if estimated >= planned:\n            delay = round((estimated - planned).seconds / 60)\n        else:\n            delay = round((planned - estimated).seconds / 60) * -1\n        return delay",
    "docstring": "Min of delay on planned departure."
  },
  {
    "code": "def first(script, value=None, default=None, vars={}, url=None, opener=default_opener, library_paths=[]):\n    return compile(script, vars, library_paths).first(_get_value(value, url, opener), default)",
    "docstring": "Transform object by jq script, returning the first result.\n    Return default if result is empty."
  },
  {
    "code": "def staticmap(ctx, mapid, output, features, lat, lon, zoom, size):\n    access_token = (ctx.obj and ctx.obj.get('access_token')) or None\n    if features:\n        features = list(\n            cligj.normalize_feature_inputs(None, 'features', [features]))\n    service = mapbox.Static(access_token=access_token)\n    try:\n        res = service.image(\n            mapid,\n            lon=lon, lat=lat, z=zoom,\n            width=size[0], height=size[1],\n            features=features, sort_keys=True)\n    except mapbox.errors.ValidationError as exc:\n        raise click.BadParameter(str(exc))\n    if res.status_code == 200:\n        output.write(res.content)\n    else:\n        raise MapboxCLIException(res.text.strip())",
    "docstring": "Generate static map images from existing Mapbox map ids.\n    Optionally overlay with geojson features.\n\n      $ mapbox staticmap --features features.geojson mapbox.satellite out.png\n      $ mapbox staticmap --lon -61.7 --lat 12.1 --zoom 12 mapbox.satellite out2.png\n\n    An access token is required, see `mapbox --help`."
  },
  {
    "code": "def remove_rows_matching(df, column, match):\n    df = df.copy()\n    mask = df[column].values != match\n    return df.iloc[mask, :]",
    "docstring": "Return a ``DataFrame`` with rows where `column` values match `match` are removed.\n\n    The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared\n    to `match`, and those rows that match are removed from the DataFrame.\n\n    :param df: Pandas ``DataFrame``\n    :param column: Column indexer\n    :param match: ``str`` match target\n    :return: Pandas ``DataFrame`` filtered"
  },
  {
    "code": "def Flush(self):\n    if self.locked and self.CheckLease() == 0:\n      self._RaiseLockError(\"Flush\")\n    self._WriteAttributes()\n    self._SyncAttributes()\n    if self.parent:\n      self.parent.Flush()",
    "docstring": "Syncs this object with the data store, maintaining object validity."
  },
  {
    "code": "def on_add_rows(self, event):\n        num_rows = self.rows_spin_ctrl.GetValue()\n        for row in range(num_rows):\n            self.grid.add_row()\n        self.main_sizer.Fit(self)",
    "docstring": "add rows to grid"
  },
  {
    "code": "def get_entity(self, entity, default=None):\n        self._ensure_loaded()\n        return self.entities.get(str(entity), default)",
    "docstring": "Gets an entity object from the ACL.\n\n        :type entity: :class:`_ACLEntity` or string\n        :param entity: The entity to get lookup in the ACL.\n\n        :type default: anything\n        :param default: This value will be returned if the entity\n                        doesn't exist.\n\n        :rtype: :class:`_ACLEntity`\n        :returns: The corresponding entity or the value provided\n                  to ``default``."
  },
  {
    "code": "def on_enter_specimen(self, event):\n        new_specimen = self.specimens_box.GetValue()\n        if new_specimen not in self.specimens:\n            self.user_warning(\n                \"%s is not a valid specimen with measurement data, aborting\" % (new_specimen))\n            self.specimens_box.SetValue(self.s)\n            return\n        self.select_specimen(new_specimen)\n        if self.ie_open:\n            self.ie.change_selected(self.current_fit)\n        self.update_selection()",
    "docstring": "upon enter on the specimen box it makes that specimen the current\n        specimen"
  },
  {
    "code": "def default_resolve_fn(source, info, **args):\n    name = info.field_name\n    if isinstance(source, dict):\n        property = source.get(name)\n    else:\n        property = getattr(source, name, None)\n    if callable(property):\n        return property()\n    return property",
    "docstring": "If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object\n    of the same name as the field and returns it as the result, or if it's a function, returns the result of calling that function."
  },
  {
    "code": "def handle_feedback(self, pkt):\n        self.logger.debug(\"handle feedback\")\n        self.frame = self.decode_frameno(pkt.z & 0o7777) - 1\n        self.server.controller.init_frame(self.frame)\n        self.server.controller.set_frame(self.frame)",
    "docstring": "This part of the protocol is used by IRAF to erase a frame in\n        the framebuffers."
  },
  {
    "code": "def create_initialized_contract_account(self, contract_code, storage) -> None:\n        new_account = Account(\n            self._generate_new_address(), code=contract_code, balance=0\n        )\n        new_account.storage = storage\n        self._put_account(new_account)",
    "docstring": "Creates a new contract account, based on the contract code and\n        storage provided The contract code only includes the runtime contract\n        bytecode.\n\n        :param contract_code: Runtime bytecode for the contract\n        :param storage: Initial storage for the contract\n        :return: The new account"
  },
  {
    "code": "def update_in_hdx(self, **kwargs):\n        self._check_load_existing_object('resource', 'id')\n        if self.file_to_upload and 'url' in self.data:\n            del self.data['url']\n        self._merge_hdx_update('resource', 'id', self.file_to_upload, **kwargs)",
    "docstring": "Check if resource exists in HDX and if so, update it\n\n        Args:\n            **kwargs: See below\n            operation (string): Operation to perform eg. patch. Defaults to update.\n\n        Returns:\n            None"
  },
  {
    "code": "def _strip_marker_elem(elem_name, elements):\n    extra_indexes = []\n    preceding_operators = [\"and\"] if elem_name == \"extra\" else [\"and\", \"or\"]\n    for i, element in enumerate(elements):\n        if isinstance(element, list):\n            cancelled = _strip_marker_elem(elem_name, element)\n            if cancelled:\n                extra_indexes.append(i)\n        elif isinstance(element, tuple) and element[0].value == elem_name:\n            extra_indexes.append(i)\n    for i in reversed(extra_indexes):\n        del elements[i]\n        if i > 0 and elements[i - 1] in preceding_operators:\n            del elements[i - 1]\n        elif elements:\n            del elements[0]\n    return not elements",
    "docstring": "Remove the supplied element from the marker.\n\n    This is not a comprehensive implementation, but relies on an important\n    characteristic of metadata generation: The element's operand is always\n    associated with an \"and\" operator. This means that we can simply remove the\n    operand and the \"and\" operator associated with it."
  },
  {
    "code": "def _high_dim_sim(self, v, w, normalize=False, X=None, idx=0):\n        sim = np.exp((-np.linalg.norm(v - w) ** 2) / (2*self._sigma[idx] ** 2))\n        if normalize:\n            return sim / sum(map(lambda x: x[1], self._knn(idx, X, high_dim=True)))\n        else:\n            return sim",
    "docstring": "Similarity measurement based on Gaussian Distribution"
  },
  {
    "code": "def getMessage(self):\n        if isinstance(self.msg, numpy.ndarray):\n            msg = self.array2string(self.msg)\n        else:\n            msg = str(self.msg)\n        if self.args:\n            a2s = self.array2string\n            if isinstance(self.args, Dict):\n                args = {k: (a2s(v) if isinstance(v, numpy.ndarray) else v)\n                        for (k, v) in self.args.items()}\n            elif isinstance(self.args, Sequence):\n                args = tuple((a2s(a) if isinstance(a, numpy.ndarray) else a)\n                             for a in self.args)\n            else:\n                raise TypeError(\"Unexpected input '%s' with type '%s'\" % (self.args,\n                                                                          type(self.args)))\n            msg = msg % args\n        return msg",
    "docstring": "Return the message for this LogRecord.\n\n        Return the message for this LogRecord after merging any user-supplied \\\n        arguments with the message."
  },
  {
    "code": "def get_resource_search_session(self, proxy):\n        if not self.supports_resource_search():\n            raise errors.Unimplemented()\n        return sessions.ResourceSearchSession(proxy=proxy, runtime=self._runtime)",
    "docstring": "Gets a resource search session.\n\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.resource.ResourceSearchSession) - ``a\n                ResourceSearchSession``\n        raise:  NullArgument - ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented - ``supports_resource_search()`` is\n                ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_resource_search()`` is ``true``.*"
  },
  {
    "code": "def hist_axis_func(axis_type: enum.Enum) -> Callable[[Hist], Axis]:\n    def axis_func(hist: Hist) -> Axis:\n        try:\n            hist_axis_type = axis_type.value\n        except AttributeError:\n            hist_axis_type = axis_type\n        if hasattr(hist, \"ProjectionND\") and hasattr(hist, \"Projection\"):\n            return hist.GetAxis(hist_axis_type)\n        else:\n            axis_function_map = {\n                TH1AxisType.x_axis.value: hist.GetXaxis,\n                TH1AxisType.y_axis.value: hist.GetYaxis,\n                TH1AxisType.z_axis.value: hist.GetZaxis\n            }\n            return_func = axis_function_map[hist_axis_type]\n            return return_func()\n    return axis_func",
    "docstring": "Wrapper to retrieve the axis of a given histogram.\n\n    This can be convenient outside of just projections, so it's made available in the API.\n\n    Args:\n        axis_type: The type of axis to retrieve.\n    Returns:\n        Callable to retrieve the specified axis when given a hist."
  },
  {
    "code": "def to_yaml(obj, stream=None, dumper_cls=yaml.Dumper, default_flow_style=False,\n            **kwargs):\n    class OrderedDumper(dumper_cls):\n        pass\n    def dict_representer(dumper, data):\n        return dumper.represent_mapping(\n            yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,\n            data.items())\n    OrderedDumper.add_representer(OrderedDict, dict_representer)\n    obj_dict = to_dict(obj, **kwargs)\n    return yaml.dump(obj_dict, stream, OrderedDumper,\n                     default_flow_style=default_flow_style)",
    "docstring": "Serialize a Python object into a YAML stream with OrderedDict and\n    default_flow_style defaulted to False.\n\n    If stream is None, return the produced string instead.\n\n    OrderedDict reference: http://stackoverflow.com/a/21912744\n    default_flow_style reference: http://stackoverflow.com/a/18210750\n\n    :param data: python object to be serialized\n    :param stream: to be serialized to\n    :param Dumper: base Dumper class to extend.\n    :param kwargs: arguments to pass to to_dict\n    :return: stream if provided, string if stream is None"
  },
  {
    "code": "def pop_arguments(instr, stack):\n    needed = instr.stack_effect\n    if needed >= 0:\n        raise DecompilationError(\n            \"%s is does not have a negative stack effect\" % instr\n        )\n    for popcount, to_pop in enumerate(reversed(stack), start=1):\n        needed += to_pop.stack_effect\n        if not needed:\n            break\n    else:\n        raise DecompilationError(\n            \"Reached end of stack without finding inputs to %s\" % instr,\n        )\n    popped = stack[-popcount:]\n    stack[:] = stack[:-popcount]\n    return popped",
    "docstring": "Pop instructions off `stack` until we pop all instructions that will\n    produce values popped by `instr`."
  },
  {
    "code": "def removeIndividual(self, individual):\n        q = models.Individual.delete().where(\n            models.Individual.id == individual.getId())\n        q.execute()",
    "docstring": "Removes the specified individual from this repository."
  },
  {
    "code": "def on_action_run(self, task_vars, delegate_to_hostname, loader_basedir):\n        self.inventory_hostname = task_vars['inventory_hostname']\n        self._task_vars = task_vars\n        self.host_vars = task_vars['hostvars']\n        self.delegate_to_hostname = delegate_to_hostname\n        self.loader_basedir = loader_basedir\n        self._mitogen_reset(mode='put')",
    "docstring": "Invoked by ActionModuleMixin to indicate a new task is about to start\n        executing. We use the opportunity to grab relevant bits from the\n        task-specific data.\n\n        :param dict task_vars:\n            Task variable dictionary.\n        :param str delegate_to_hostname:\n            :data:`None`, or the template-expanded inventory hostname this task\n            is being delegated to. A similar variable exists on PlayContext\n            when ``delegate_to:`` is active, however it is unexpanded.\n        :param str loader_basedir:\n            Loader base directory; see :attr:`loader_basedir`."
  },
  {
    "code": "def get_future(self):\n        now = dt.now()\n        four_days = now + timedelta(hours=96)\n        now = now.timestamp()\n        four_days = four_days.timestamp()\n        url = build_url(self.api_key, self.spot_id, self.fields,\n                        self.unit, now, four_days)\n        return get_msw(url)",
    "docstring": "Get current and future forecasts."
  },
  {
    "code": "def group_select(selects, length=None, depth=None):\n    if length == None and depth == None:\n        length = depth = len(selects[0])\n    getter = operator.itemgetter(depth-length)\n    if length > 1:\n        selects = sorted(selects, key=getter)\n        grouped_selects = defaultdict(dict)\n        for k, v in itertools.groupby(selects, getter):\n            grouped_selects[k] = group_select(list(v), length-1, depth)\n        return grouped_selects\n    else:\n        return list(selects)",
    "docstring": "Given a list of key tuples to select, groups them into sensible\n    chunks to avoid duplicating indexing operations."
  },
  {
    "code": "def show_distribution_section(config, title, section_name):\n    payload = requests.get(config.apps_url).json()\n    distributions = sorted(payload.keys(), reverse=True)\n    latest_distribution = payload[distributions[0]]\n    click.echo(\"{} {}\".format(\"Release\".rjust(7), title))\n    click.echo(\"------- ---------------\")\n    section = latest_distribution[section_name]\n    names = sorted(section.keys())\n    for name in names:\n        click.echo(\"{} {}\".format(section[name].rjust(7), name))",
    "docstring": "Obtain distribution data and display latest distribution section,\n    i.e. \"demos\" or \"apps\" or \"themes\"."
  },
  {
    "code": "def from_remote_hive(cls, url, *args, **kwargs):\n        version = kwargs.pop('version', None)\n        require = kwargs.pop('require_https', False)\n        return cls(Hive.from_url(url, version, require), *args, **kwargs)",
    "docstring": "Download a JSON hive file from a URL, and initialize from it,\n        paying attention to the version keyword argument."
  },
  {
    "code": "def download_page(url, data=None):\n    conn = urllib2.urlopen(url, data)\n    resp = conn.read()\n    conn.close()\n    return resp",
    "docstring": "Returns the response for the given url. The optional data argument is\n    passed directly to urlopen."
  },
  {
    "code": "def shell(environment, opts):\n    environment.require_data()\n    environment.start_supporting_containers()\n    return environment.interactive_shell(\n        opts['COMMAND'],\n        detach=opts['--detach']\n    )",
    "docstring": "Run a command or interactive shell within this environment\n\nUsage:\n  datacats [-d] [-s NAME] shell [ENVIRONMENT [COMMAND...]]\n\nOptions:\n  -d --detach       Run the resulting container in the background\n  -s --site=NAME   Specify a site to run the shell on [default: primary]\n\nENVIRONMENT may be an environment name or a path to an environment directory.\nDefault: '.'"
  },
  {
    "code": "def independentlinear60(display=False):\n    old_seed = np.random.seed()\n    np.random.seed(0)\n    N = 1000\n    M = 60\n    beta = np.zeros(M)\n    beta[0:30:3] = 1\n    f = lambda X: np.matmul(X, beta)\n    X_start = np.random.randn(N, M)\n    X = X_start - X_start.mean(0)\n    y = f(X) + np.random.randn(N) * 1e-2\n    np.random.seed(old_seed)\n    return pd.DataFrame(X), y",
    "docstring": "A simulated dataset with tight correlations among distinct groups of features."
  },
  {
    "code": "def _set_default_serializer(self, name):\n        try:\n            (self._default_content_type, self._default_content_encoding,\n             self._default_encode) = self._encoders[name]\n        except KeyError:\n            raise SerializerNotInstalled(\n                \"No encoder installed for %s\" % name)",
    "docstring": "Set the default serialization method used by this library.\n\n        :param name: The name of the registered serialization method.\n            For example, ``json`` (default), ``pickle``, ``yaml``,\n            or any custom methods registered using :meth:`register`.\n\n        :raises SerializerNotInstalled: If the serialization method\n            requested is not available."
  },
  {
    "code": "def page_view(url):\n    def decorator(func):\n        @wraps(func)\n        async def wrapper(self: BaseState, *args, **kwargs):\n            user_id = self.request.user.id\n            try:\n                user_lang = await self.request.user.get_locale()\n            except NotImplementedError:\n                user_lang = ''\n            title = self.__class__.__name__\n            async for p in providers():\n                await p.page_view(url, title, user_id, user_lang)\n            return await func(self, *args, **kwargs)\n        return wrapper\n    return decorator",
    "docstring": "Page view decorator.\n\n    Put that around a state handler function in order to log a page view each\n    time the handler gets called.\n\n    :param url: simili-URL that you want to give to the state"
  },
  {
    "code": "def __symlink_dir(self, dir_name, name, path):\n        target_dir = os.path.join(self.root_dir, dir_name)\n        if not os.path.exists(target_dir):\n            os.makedirs(target_dir)\n        target_path = os.path.join(self.root_dir, dir_name, name)\n        logger.debug(\"Attempting to symlink %s to %s...\" % (path, target_path))\n        if os.path.exists(target_path):\n            if os.path.islink(target_path):\n                os.remove(target_path)\n            else:\n                logger.warn(\"%s is not a symlink! please remove it manually.\" % target_path)\n                return\n        os.symlink(path, target_path)",
    "docstring": "Symlink an object at path to name in the dir_name folder. remove it if it already exists."
  },
  {
    "code": "def do_help(self, arg):\n        if not arg or arg not in self.argparse_names():\n            cmd.Cmd.do_help(self, arg)\n        else:\n            try:\n                self.argparser.parse_args([arg, '--help'])\n            except Exception:\n                pass",
    "docstring": "Patched to show help for arparse commands"
  },
  {
    "code": "def is_integer(obj):\n    if PYTHON3:\n        return isinstance(obj, int)\n    return isinstance(obj, (int, long))",
    "docstring": "Is this an integer.\n\n    :param object obj:\n    :return:"
  },
  {
    "code": "def __get_connection_SNS():\n    region = get_global_option('region')\n    try:\n        if (get_global_option('aws_access_key_id') and\n                get_global_option('aws_secret_access_key')):\n            logger.debug(\n                'Authenticating to SNS using '\n                'credentials in configuration file')\n            connection = sns.connect_to_region(\n                region,\n                aws_access_key_id=get_global_option(\n                    'aws_access_key_id'),\n                aws_secret_access_key=get_global_option(\n                    'aws_secret_access_key'))\n        else:\n            logger.debug(\n                'Authenticating using boto\\'s authentication handler')\n            connection = sns.connect_to_region(region)\n    except Exception as err:\n        logger.error('Failed connecting to SNS: {0}'.format(err))\n        logger.error(\n            'Please report an issue at: '\n            'https://github.com/sebdah/dynamic-dynamodb/issues')\n        raise\n    logger.debug('Connected to SNS in {0}'.format(region))\n    return connection",
    "docstring": "Ensure connection to SNS"
  },
  {
    "code": "def ami_lookup(region='us-east-1', name='tomcat8'):\n    if AMI_JSON_URL:\n        ami_dict = _get_ami_dict(AMI_JSON_URL)\n        ami_id = ami_dict[region][name]\n    elif GITLAB_TOKEN:\n        warn_user('Use AMI_JSON_URL feature instead.')\n        ami_contents = _get_ami_file(region=region)\n        ami_dict = json.loads(ami_contents)\n        ami_id = ami_dict[name]\n    else:\n        ami_id = name\n    LOG.info('Using AMI: %s', ami_id)\n    return ami_id",
    "docstring": "Look up AMI ID.\n\n    Use _name_ to find AMI ID. If no ami_base_url or gitlab_token is provided,\n    _name_ is returned as the ami id.\n\n    Args:\n        region (str): AWS Region to find AMI ID.\n        name (str): Simple AMI base name to lookup.\n\n    Returns:\n        str: AMI ID for _name_ in _region_."
  },
  {
    "code": "def width(self):\n        if self._width is not None:\n            return self._width\n        self._width = sum(fs.width for fs in self.chunks)\n        return self._width",
    "docstring": "The number of columns it would take to display this string"
  },
  {
    "code": "def add_children_to_node(self, node):\n        if self.has_children:\n            for child_id in self.children:\n                child = self.runtime.get_block(child_id)\n                self.runtime.add_block_as_child_node(child, node)",
    "docstring": "Add children to etree.Element `node`."
  },
  {
    "code": "def add_release(self, login, package_name, version, requirements, announce, release_attrs):\n        url = '%s/release/%s/%s/%s' % (self.domain, login, package_name, version)\n        if not release_attrs:\n            release_attrs = {}\n        payload = {\n            'requirements': requirements,\n            'announce': announce,\n            'description': None,\n        }\n        payload.update(release_attrs)\n        data, headers = jencode(payload)\n        res = self.session.post(url, data=data, headers=headers)\n        self._check_response(res)\n        return res.json()",
    "docstring": "Add a new release to a package.\n\n        :param login: the login of the package owner\n        :param package_name: the name of the package\n        :param version: the version string of the release\n        :param requirements: A dict of requirements TODO: describe\n        :param announce: An announcement that will be posted to all package watchers"
  },
  {
    "code": "def timestamp_from_datetime(date_time):\n    if date_time.tzinfo is None:\n      return time.mktime((date_time.year, date_time.month, date_time.day, date_time.hour,\n                          date_time.minute, date_time.second,\n                          -1, -1, -1)) + date_time.microsecond / 1e6\n    return (date_time - _EPOCH).total_seconds()",
    "docstring": "Returns POSIX timestamp as float"
  },
  {
    "code": "def restore_schema(task, **kwargs):\n    from .compat import get_public_schema_name\n    schema_name = get_public_schema_name()\n    include_public = True\n    if hasattr(task, '_old_schema'):\n        schema_name, include_public = task._old_schema\n    if connection.schema_name == schema_name:\n        return\n    connection.set_schema(schema_name, include_public=include_public)",
    "docstring": "Switches the schema back to the one from before running the task."
  },
  {
    "code": "def sync_next_id(self):\n\t\tif self.next_id is not None:\n\t\t\tif len(self):\n\t\t\t\tn = max(self.getColumnByName(self.next_id.column_name)) + 1\n\t\t\telse:\n\t\t\t\tn = type(self.next_id)(0)\n\t\t\tif n > self.next_id:\n\t\t\t\tself.set_next_id(n)\n\t\treturn self.next_id",
    "docstring": "Determines the highest-numbered ID in this table, and sets\n\t\tthe table's .next_id attribute to the next highest ID in\n\t\tsequence.  If the .next_id attribute is already set to a\n\t\tvalue greater than the highest value found, then it is left\n\t\tunmodified.  The return value is the ID identified by this\n\t\tmethod.  If the table's .next_id attribute is None, then\n\t\tthis function is a no-op.\n\n\t\tNote that tables of the same name typically share a common\n\t\t.next_id attribute (it is a class attribute, not an\n\t\tattribute of each instance) so that IDs can be generated\n\t\tthat are unique across all tables in the document.  Running\n\t\tsync_next_id() on all the tables in a document that are of\n\t\tthe same type will have the effect of setting the ID to the\n\t\tnext ID higher than any ID in any of those tables.\n\n\t\tExample:\n\n\t\t>>> import lsctables\n\t\t>>> tbl = lsctables.New(lsctables.ProcessTable)\n\t\t>>> print tbl.sync_next_id()\n\t\tprocess:process_id:0"
  },
  {
    "code": "def lazy_property(function):\n    cached_val = []\n    def _wrapper(*args):\n        try:\n            return cached_val[0]\n        except IndexError:\n            ret_val = function(*args)\n            cached_val.append(ret_val)\n            return ret_val\n    return _wrapper",
    "docstring": "Cache the first return value of a function for all subsequent calls.\n\n    This decorator is usefull for argument-less functions that behave more\n    like a global or static property that should be calculated once, but\n    lazily (i.e. only if requested)."
  },
  {
    "code": "def encode_streaming(self, data):\n        buffer = 0\n        size = 0\n        for s in data:\n            b, v = self._table[s]\n            buffer = (buffer << b) + v\n            size += b\n            while size >= 8:\n                byte = buffer >> (size - 8)\n                yield to_byte(byte)\n                buffer = buffer - (byte << (size - 8))\n                size -= 8\n        if size > 0:\n            b, v = self._table[_EOF]\n            buffer = (buffer << b) + v\n            size += b\n            if size >= 8:\n                byte = buffer >> (size - 8)\n            else:\n                byte = buffer << (8 - size)\n            yield to_byte(byte)",
    "docstring": "Encode given data in streaming fashion.\n\n        :param data: sequence of symbols (e.g. byte string, unicode string, list, iterator)\n        :return: generator of bytes (single character strings in Python2, ints in Python 3)"
  },
  {
    "code": "def hydrate_point(srid, *coordinates):\n    try:\n        point_class, dim = __srid_table[srid]\n    except KeyError:\n        point = Point(coordinates)\n        point.srid = srid\n        return point\n    else:\n        if len(coordinates) != dim:\n            raise ValueError(\"SRID %d requires %d coordinates (%d provided)\" % (srid, dim, len(coordinates)))\n        return point_class(coordinates)",
    "docstring": "Create a new instance of a Point subclass from a raw\n    set of fields. The subclass chosen is determined by the\n    given SRID; a ValueError will be raised if no such\n    subclass can be found."
  },
  {
    "code": "def get_module_verbosity_flags(*labels):\n    verbose_prefix_list = ['--verbose-', '--verb', '--verb-']\n    veryverbose_prefix_list = ['--veryverbose-', '--veryverb', '--veryverb-']\n    verbose_flags = tuple(\n        [prefix + lbl for prefix, lbl in\n         itertools.product(verbose_prefix_list, labels)])\n    veryverbose_flags = tuple(\n        [prefix + lbl for prefix, lbl in\n         itertools.product(veryverbose_prefix_list, labels)])\n    veryverbose_module = get_argflag(veryverbose_flags) or VERYVERBOSE\n    verbose_module = (get_argflag(verbose_flags) or veryverbose_module or VERBOSE)\n    if veryverbose_module:\n        verbose_module = 2\n    return verbose_module, veryverbose_module",
    "docstring": "checks for standard flags for enableing module specific verbosity"
  },
  {
    "code": "def setRti(self, rti):\n        check_class(rti, BaseRti)\n        self._rti = rti\n        self._updateWidgets()\n        self._updateRtiInfo()",
    "docstring": "Updates the current VisItem from the contents of the repo tree item.\n\n            Is a slot but the signal is usually connected to the Collector, which then calls\n            this function directly."
  },
  {
    "code": "def sorted_conkeys(self, prefix=None):\n        conkeys = []\n        for cond in _COND_PREFIXES:\n            conkeys += sorted([key for key in self.conditions\n                               if key.startswith(cond)], key=self.cond_int)\n        if not prefix:\n            return conkeys\n        return [key for key in conkeys if key.startswith(prefix)]",
    "docstring": "Return all condition keys in self.conditions as a list sorted\n        suitable for print or write to a file. If prefix is given return\n        only the ones prefixed with prefix."
  },
  {
    "code": "def _encode_time(mtime: float):\n    dt = arrow.get(mtime)\n    dt = dt.to(\"local\")\n    date_val = ((dt.year - 1980) << 9) | (dt.month << 5) | dt.day\n    secs = dt.second + dt.microsecond / 10**6\n    time_val = (dt.hour << 11) | (dt.minute << 5) | math.floor(secs / 2)\n    return (date_val << 16) | time_val",
    "docstring": "Encode a mtime float as a 32-bit FAT time"
  },
  {
    "code": "def get_image_label(name, default=\"not_found.png\"):\r\n    label = QLabel()\r\n    label.setPixmap(QPixmap(get_image_path(name, default)))\r\n    return label",
    "docstring": "Return image inside a QLabel object"
  },
  {
    "code": "def flush(self):\n        for name in self.item_names:\n            item = self[name]\n            item.flush()\n        self.file.flush()",
    "docstring": "Ensure contents are written to file."
  },
  {
    "code": "def get_conn(self, *args, **kwargs):\n        connections = self.__connections_for('get_conn', args=args, kwargs=kwargs)\n        if len(connections) is 1:\n            return connections[0]\n        else:\n            return connections",
    "docstring": "Returns a connection object from the router given ``args``.\n\n        Useful in cases where a connection cannot be automatically determined\n        during all steps of the process. An example of this would be\n        Redis pipelines."
  },
  {
    "code": "def load_rv_data(filename, indep, dep, indweight=None, dir='./'):\n    if '/' in filename:\n        path, filename = os.path.split(filename)\n    else:\n        path = dir\n    load_file = os.path.join(path, filename)\n    rvdata = np.loadtxt(load_file)\n    d ={}\n    d['phoebe_rv_time'] = rvdata[:,0]\n    d['phoebe_rv_vel'] = rvdata[:,1]\n    ncol = len(rvdata[0])\n    if indweight==\"Standard deviation\":\n        if ncol >= 3:\n            d['phoebe_rv_sigmarv'] = rvdata[:,2]\n        else:\n            logger.warning('A sigma column is mentioned in the .phoebe file but is not present in the rv data file')\n    elif indweight ==\"Standard weight\":\n                if ncol >= 3:\n                    sigma = np.sqrt(1/rvdata[:,2])\n                    d['phoebe_rv_sigmarv'] = sigma\n                    logger.warning('Standard weight has been converted to Standard deviation.')\n    else:\n        logger.warning('Phoebe 2 currently only supports standard deviaton')\n    return d",
    "docstring": "load dictionary with rv data."
  },
  {
    "code": "def qstd(x,quant=0.05,top=False,bottom=False):\n    s = np.sort(x)\n    n = np.size(x)\n    lo = s[int(n*quant)]\n    hi = s[int(n*(1-quant))]\n    if top:\n        w = np.where(x>=lo)\n    elif bottom:\n        w = np.where(x<=hi)\n    else:\n        w = np.where((x>=lo)&(x<=hi))\n    return np.std(x[w])",
    "docstring": "returns std, ignoring outer 'quant' pctiles"
  },
  {
    "code": "def on_touch(self, view, event):\n        d = self.declaration\n        r = {'event': event, 'result': False}\n        d.touch_event(r)\n        return r['result']",
    "docstring": "Trigger the touch event\n\n        Parameters\n        ----------\n        view: int\n            The ID of the view that sent this event\n        data: bytes\n            The msgpack encoded key event"
  },
  {
    "code": "def process_exception(self, request, exception):\n        if isinstance(exception, (exceptions.NotAuthorized,\n                                  exceptions.NotAuthenticated)):\n            auth_url = settings.LOGIN_URL\n            next_url = iri_to_uri(request.get_full_path())\n            if next_url != auth_url:\n                field_name = REDIRECT_FIELD_NAME\n            else:\n                field_name = None\n            login_url = request.build_absolute_uri(auth_url)\n            response = redirect_to_login(next_url, login_url=login_url,\n                                         redirect_field_name=field_name)\n            if isinstance(exception, exceptions.NotAuthorized):\n                response.delete_cookie('messages')\n                return shortcuts.render(request, 'not_authorized.html',\n                                        status=403)\n            if request.is_ajax():\n                response_401 = http.HttpResponse(status=401)\n                response_401['X-Horizon-Location'] = response['location']\n                return response_401\n            return response\n        if isinstance(exception, exceptions.NotFound):\n            raise http.Http404(exception)\n        if isinstance(exception, exceptions.Http302):\n            return shortcuts.redirect(exception.location)",
    "docstring": "Catches internal Horizon exception classes.\n\n        Exception classes such as NotAuthorized, NotFound and Http302\n        are caught and handles them gracefully."
  },
  {
    "code": "def apply(self, docs, split=0, clear=True, parallelism=None, progress_bar=True):\n        super(CandidateExtractor, self).apply(\n            docs,\n            split=split,\n            clear=clear,\n            parallelism=parallelism,\n            progress_bar=progress_bar,\n        )",
    "docstring": "Run the CandidateExtractor.\n\n        :Example: To extract candidates from a set of training documents using\n            4 cores::\n\n                candidate_extractor.apply(train_docs, split=0, parallelism=4)\n\n        :param docs: Set of documents to extract from.\n        :param split: Which split to assign the extracted Candidates to.\n        :type split: int\n        :param clear: Whether or not to clear the existing Candidates\n            beforehand.\n        :type clear: bool\n        :param parallelism: How many threads to use for extraction. This will\n            override the parallelism value used to initialize the\n            CandidateExtractor if it is provided.\n        :type parallelism: int\n        :param progress_bar: Whether or not to display a progress bar. The\n            progress bar is measured per document.\n        :type progress_bar: bool"
  },
  {
    "code": "def trans(self, id, parameters=None, domain=None, locale=None):\n        if parameters is None:\n            parameters = {}\n        if locale is None:\n            locale = self.locale\n        else:\n            self._assert_valid_locale(locale)\n        if domain is None:\n            domain = 'messages'\n        catalogue = self.get_catalogue(locale)\n        if not catalogue.has(id, domain):\n            raise RuntimeError(\n                \"There is no translation for {0} in domain {1}\".format(\n                    id,\n                    domain\n                )\n            )\n        msg = self.get_catalogue(locale).get(id, domain)\n        return self.format(msg, parameters)",
    "docstring": "Throws RuntimeError whenever a message is missing"
  },
  {
    "code": "def visit_root(self, _, children):\n        resource = children[1]\n        resource.is_root = True\n        return resource",
    "docstring": "The main node holding all the query.\n\n        Arguments\n        ---------\n        _ (node) : parsimonious.nodes.Node.\n        children : list\n            - 0: for ``WS`` (whitespace): ``None``.\n            - 1: for ``NAMED_RESOURCE``: an instance of a subclass of ``.resources.Resource``.\n            - 2: for ``WS`` (whitespace): ``None``.\n\n        Returns\n        -------\n        .resources.Resource\n            An instance of a subclass of ``.resources.Resource``, with ``is_root`` set to ``True``.\n\n        Example\n        -------\n\n        >>> data = DataQLParser(r'''\n        ... foo\n        ... ''', default_rule='ROOT').data\n        >>> data\n        <Field[foo] />\n        >>> data.is_root\n        True\n        >>> data = DataQLParser(r'''\n        ... bar[name]\n        ... ''', default_rule='ROOT').data\n        >>> data\n        <List[bar]>\n          <Field[name] />\n        </List[bar]>\n        >>> data.is_root\n        True\n        >>> data = DataQLParser(r'''\n        ... baz{name}\n        ... ''', default_rule='ROOT').data\n        >>> data\n        <Object[baz]>\n          <Field[name] />\n        </Object[baz]>\n        >>> data.is_root\n        True"
  },
  {
    "code": "def send_scheduled_messages(priority=None, ignore_unknown_messengers=False, ignore_unknown_message_types=False):\n    dispatches_by_messengers = Dispatch.group_by_messengers(Dispatch.get_unsent(priority=priority))\n    for messenger_id, messages in dispatches_by_messengers.items():\n        try:\n            messenger_obj = get_registered_messenger_object(messenger_id)\n            messenger_obj._process_messages(messages, ignore_unknown_message_types=ignore_unknown_message_types)\n        except UnknownMessengerError:\n            if ignore_unknown_messengers:\n                continue\n            raise",
    "docstring": "Sends scheduled messages.\n\n    :param int, None priority: number to limit sending message by this priority.\n    :param bool ignore_unknown_messengers: to silence UnknownMessengerError\n    :param bool ignore_unknown_message_types: to silence UnknownMessageTypeError\n    :raises UnknownMessengerError:\n    :raises UnknownMessageTypeError:"
  },
  {
    "code": "def handle(self, event):\n        def dec(func):\n            self.add_handler(event, func)\n            return func\n        return dec",
    "docstring": "Decorator for adding a handler function for a particular event.\n\n        Usage:\n\n            my_client = Client()\n\n            @my_client.handle(\"WELCOME\")\n            def welcome_handler(client, *params):\n                # Do something with the event.\n                pass"
  },
  {
    "code": "def _unescape_math(xml):\n    xpath_math_script = etree.XPath(\n            '//x:script[@type=\"math/mml\"]',\n            namespaces={'x': 'http://www.w3.org/1999/xhtml'})\n    math_script_list = xpath_math_script(xml)\n    for mathscript in math_script_list:\n        math = mathscript.text\n        math = unescape(unescape(math))\n        mathscript.clear()\n        mathscript.set('type', 'math/mml')\n        new_math = etree.fromstring(math)\n        mathscript.append(new_math)\n    return xml",
    "docstring": "Unescapes Math from Mathjax to MathML."
  },
  {
    "code": "async def starttls(self, context=None):\n        if not self.use_aioopenssl:\n            raise BadImplementationError(\"This connection does not use aioopenssl\")\n        import aioopenssl\n        import OpenSSL\n        await self.ehlo_or_helo_if_needed()\n        if \"starttls\" not in self.esmtp_extensions:\n            raise SMTPCommandNotSupportedError(\"STARTTLS\")\n        code, message = await self.do_cmd(\"STARTTLS\", success=(220,))\n        if context is None:\n            context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD)\n        await self.transport.starttls(ssl_context=context)\n        self.last_ehlo_response = (None, None)\n        self.last_helo_response = (None, None)\n        self.supports_esmtp = False\n        self.esmtp_extensions = {}\n        self.auth_mechanisms = []\n        return (code, message)",
    "docstring": "Upgrades the connection to the SMTP server into TLS mode.\n\n        If there has been no previous EHLO or HELO command this session, this\n        method tries ESMTP EHLO first.\n\n        If the server supports SSL/TLS, this will encrypt the rest of the SMTP\n        session.\n\n        Raises:\n            SMTPCommandNotSupportedError: If the server does not support STARTTLS.\n            SMTPCommandFailedError: If the STARTTLS command fails\n            BadImplementationError: If the connection does not use aioopenssl.\n\n        Args:\n            context (:obj:`OpenSSL.SSL.Context`): SSL context\n\n        Returns:\n            (int, message): A (code, message) 2-tuple containing the server\n                response."
  },
  {
    "code": "def config(\n    state, host, key, value,\n    repo=None,\n):\n    existing_config = host.fact.git_config(repo)\n    if key not in existing_config or existing_config[key] != value:\n        if repo is None:\n            yield 'git config --global {0} \"{1}\"'.format(key, value)\n        else:\n            yield 'cd {0} && git config --local {1} \"{2}\"'.format(repo, key, value)",
    "docstring": "Manage git config for a repository or globally.\n\n    + key: the key of the config to ensure\n    + value: the value this key should have\n    + repo: specify the git repo path to edit local config (defaults to global)"
  },
  {
    "code": "def rest_action(self, func, url, **kwargs):\n        try:\n            response = func(url, timeout=self.TIMEOUT, **kwargs)\n        except requests.RequestException, err:\n            log.exception(\n                \"[PyLmod] Error - connection error in \"\n                \"rest_action, err=%s\", err\n            )\n            raise err\n        try:\n            return response.json()\n        except ValueError, err:\n            log.exception('Unable to decode %s', response.content)\n            raise err",
    "docstring": "Routine to do low-level REST operation, with retry.\n\n        Args:\n            func (callable): API function to call\n            url (str): service URL endpoint\n            kwargs (dict): addition parameters\n\n        Raises:\n            requests.RequestException: Exception connection error\n            ValueError: Unable to decode response content\n\n        Returns:\n            list: the json-encoded content of the response"
  },
  {
    "code": "def screenshot(self, filename, scale=1.0, quality=100):\n        result = self.server.screenshot(filename, scale, quality)\n        if result:\n            return result\n        device_file = self.server.jsonrpc.takeScreenshot(\"screenshot.png\",\n                                                         scale, quality)\n        if not device_file:\n            return None\n        p = self.server.adb.cmd(\"pull\", device_file, filename)\n        p.wait()\n        self.server.adb.cmd(\"shell\", \"rm\", device_file).wait()\n        return filename if p.returncode is 0 else None",
    "docstring": "take screenshot."
  },
  {
    "code": "def _timestamp():\n    moment = time.time()\n    moment_us = repr(moment).split('.')[1]\n    return time.strftime(\"%Y-%m-%d-%H-%M-%S-{}\".format(moment_us), time.gmtime(moment))",
    "docstring": "Return a timestamp with microsecond precision."
  },
  {
    "code": "def name_with_version(self):\n        if self.version == 1:\n            return self.name\n        else:\n            return '{}:{}'.format(self.name, self.version)",
    "docstring": "Get user-friendly representation of the route.\n\n        :return: Route name with version suffix. The version suffix is omitted for version 1."
  },
  {
    "code": "def _clean(value):\n    if isinstance(value, np.ndarray):\n        if value.dtype.kind == 'S':\n            return np.char.decode(value).tolist()\n        else:\n            return value.tolist()\n    elif type(value).__module__ == np.__name__:\n        conversion = np.asscalar(value)\n        if sys.version_info.major == 3 and isinstance(conversion, bytes):\n            conversion = conversion.decode()\n        return conversion\n    elif sys.version_info.major == 3 and isinstance(value, bytes):\n        return value.decode()\n    else:\n        return value",
    "docstring": "Convert numpy numeric types to their python equivalents."
  },
  {
    "code": "def list_features_0(self, locus, term, **kwargs):\n        kwargs['_return_http_data_only'] = True\n        if kwargs.get('callback'):\n            return self.list_features_0_with_http_info(locus, term, **kwargs)\n        else:\n            (data) = self.list_features_0_with_http_info(locus, term, **kwargs)\n            return data",
    "docstring": "List the enumerated sequence features matching a term at a locus\n        \n\n        This method makes a synchronous HTTP request by default. To make an\n        asynchronous HTTP request, please define a `callback` function\n        to be invoked when receiving the response.\n        >>> def callback_function(response):\n        >>>     pprint(response)\n        >>>\n        >>> thread = api.list_features_0(locus, term, callback=callback_function)\n\n        :param callback function: The callback function\n            for asynchronous request. (optional)\n        :param str locus: locus name or URI (required)\n        :param str term: Sequence Ontology (SO) term name, accession, or URI (required)\n        :return: list[Feature]\n                 If the method is called asynchronously,\n                 returns the request thread."
  },
  {
    "code": "def render_table(output_dir, packages, jenv=JENV):\n  destination_filename = output_dir + \"/com/swiftnav/sbp/client/MessageTable.java\"\n  with open(destination_filename, 'w+') as f:\n      print(destination_filename)\n      f.write(jenv.get_template(TEMPLATE_TABLE_NAME).render(packages=packages))",
    "docstring": "Render and output dispatch table"
  },
  {
    "code": "def _check_team_exists(team):\n    if team is None:\n        return\n    hostname = urlparse(get_registry_url(team)).hostname\n    try:\n        socket.gethostbyname(hostname)\n    except IOError:\n        try:\n            socket.gethostbyname('quiltdata.com')\n        except IOError:\n            message = \"Can't find quiltdata.com. Check your internet connection.\"\n        else:\n            message = \"Unable to connect to registry. Is the team name %r correct?\" % team\n        raise CommandException(message)",
    "docstring": "Check that the team registry actually exists."
  },
  {
    "code": "async def close_authenticator_async(self):\n        _logger.info(\"Shutting down CBS session on connection: %r.\", self._connection.container_id)\n        try:\n            self._cbs_auth.destroy()\n            _logger.info(\"Auth closed, destroying session on connection: %r.\", self._connection.container_id)\n            await self._session.destroy_async()\n        finally:\n            _logger.info(\"Finished shutting down CBS session on connection: %r.\", self._connection.container_id)",
    "docstring": "Close the CBS auth channel and session asynchronously."
  },
  {
    "code": "def load_json(filename, **kwargs):\n    with open(filename, 'r', encoding='utf-8') as f:\n        return json.load(f, **kwargs)",
    "docstring": "Load a JSON object from the specified file.\n\n    Args:\n        filename: Path to the input JSON file.\n        **kwargs: Additional arguments to `json.load`.\n\n    Returns:\n        The object deserialized from JSON."
  },
  {
    "code": "async def do_api_call(self):\n        self.pyvlx.connection.register_frame_received_cb(\n            self.response_rec_callback)\n        await self.send_frame()\n        await self.start_timeout()\n        await self.response_received_or_timeout.wait()\n        await self.stop_timeout()\n        self.pyvlx.connection.unregister_frame_received_cb(self.response_rec_callback)",
    "docstring": "Start. Sending and waiting for answer."
  },
  {
    "code": "def is_https(request_data):\n        is_https = 'https' in request_data and request_data['https'] != 'off'\n        is_https = is_https or ('server_port' in request_data and str(request_data['server_port']) == '443')\n        return is_https",
    "docstring": "Checks if https or http.\n\n        :param request_data: The request as a dict\n        :type: dict\n\n        :return: False if https is not active\n        :rtype: boolean"
  },
  {
    "code": "def crud_mutation_name(action, model):\n    model_string = get_model_string(model)\n    model_string = model_string[0].upper() + model_string[1:]\n    return \"{}{}\".format(action, model_string)",
    "docstring": "This function returns the name of a mutation that performs the specified\n        crud action on the given model service"
  },
  {
    "code": "def right_click_event_statusicon(self, icon, button, time):\n        def pos(menu, aicon):\n            return Gtk.StatusIcon.position_menu(menu, aicon)\n        self.menu.popup(None, None, pos, icon, button, time)",
    "docstring": "It's just way how popup menu works in GTK. Don't ask me how it works."
  },
  {
    "code": "def backward_transfer_pair(\n        backward_channel: NettingChannelState,\n        payer_transfer: LockedTransferSignedState,\n        pseudo_random_generator: random.Random,\n        block_number: BlockNumber,\n) -> Tuple[Optional[MediationPairState], List[Event]]:\n    transfer_pair = None\n    events: List[Event] = list()\n    lock = payer_transfer.lock\n    lock_timeout = BlockTimeout(lock.expiration - block_number)\n    if is_channel_usable(backward_channel, lock.amount, lock_timeout):\n        message_identifier = message_identifier_from_prng(pseudo_random_generator)\n        refund_transfer = channel.send_refundtransfer(\n            channel_state=backward_channel,\n            initiator=payer_transfer.initiator,\n            target=payer_transfer.target,\n            amount=get_lock_amount_after_fees(lock, backward_channel),\n            message_identifier=message_identifier,\n            payment_identifier=payer_transfer.payment_identifier,\n            expiration=lock.expiration,\n            secrethash=lock.secrethash,\n        )\n        transfer_pair = MediationPairState(\n            payer_transfer,\n            backward_channel.partner_state.address,\n            refund_transfer.transfer,\n        )\n        events.append(refund_transfer)\n    return (transfer_pair, events)",
    "docstring": "Sends a transfer backwards, allowing the previous hop to try a new\n    route.\n\n    When all the routes available for this node failed, send a transfer\n    backwards with the same amount and secrethash, allowing the previous hop to\n    do a retry.\n\n    Args:\n        backward_channel: The original channel which sent the mediated transfer\n            to this node.\n        payer_transfer: The *latest* payer transfer which is backing the\n            mediation.\n        block_number: The current block number.\n\n    Returns:\n        The mediator pair and the correspoding refund event."
  },
  {
    "code": "def _getmember(self, name, tarinfo=None, normalize=False):\n        members = self.getmembers()\n        if tarinfo is not None:\n            members = members[:members.index(tarinfo)]\n        if normalize:\n            name = os.path.normpath(name)\n        for member in reversed(members):\n            if normalize:\n                member_name = os.path.normpath(member.name)\n            else:\n                member_name = member.name\n            if name == member_name:\n                return member",
    "docstring": "Find an archive member by name from bottom to top.\n           If tarinfo is given, it is used as the starting point."
  },
  {
    "code": "def registers(self, unroll=False, skip_not_present=True):\n        for child in self.children(unroll, skip_not_present):\n            if isinstance(child, RegNode):\n                yield child",
    "docstring": "Returns an iterator that provides nodes for all immediate registers of\n        this component.\n\n        Parameters\n        ----------\n        unroll : bool\n            If True, any children that are arrays are unrolled.\n\n        skip_not_present : bool\n            If True, skips children whose 'ispresent' property is set to False\n\n        Yields\n        ------\n        :class:`~RegNode`\n            All registers in this component"
  },
  {
    "code": "def _MergeOptional(self, a, b):\n    if a and b:\n      if a != b:\n        raise MergeError(\"values must be identical if both specified \"\n                         \"('%s' vs '%s')\" % (transitfeed.EncodeUnicode(a),\n                                             transitfeed.EncodeUnicode(b)))\n    return a or b",
    "docstring": "Tries to merge two values which may be None.\n\n    If both values are not None, they are required to be the same and the\n    merge is trivial. If one of the values is None and the other is not None,\n    the merge results in the one which is not None. If both are None, the merge\n    results in None.\n\n    Args:\n      a: The first value.\n      b: The second value.\n\n    Returns:\n      The merged value.\n\n    Raises:\n      MergeError: If both values are not None and are not the same."
  },
  {
    "code": "def expectation(self, prep_prog, operator_programs=None):\n        if isinstance(operator_programs, Program):\n            warnings.warn(\n                \"You have provided a Program rather than a list of Programs. The results from expectation \"\n                \"will be line-wise expectation values of the operator_programs.\", SyntaxWarning)\n        payload = self._expectation_payload(prep_prog, operator_programs)\n        response = post_json(self.session, self.sync_endpoint + \"/qvm\", payload)\n        return response.json()",
    "docstring": "Calculate the expectation value of operators given a state prepared by\n        prep_program.\n\n        :note: If the execution of ``quil_program`` is **non-deterministic**, i.e., if it includes\n            measurements and/or noisy quantum gates, then the final wavefunction from which the\n            expectation values are computed itself only represents a stochastically generated\n            sample. The expectations returned from *different* ``expectation`` calls *will then\n            generally be different*.\n\n        To measure the expectation of a PauliSum, you probably want to\n        do something like this::\n\n                progs, coefs = hamiltonian.get_programs()\n                expect_coeffs = np.array(cxn.expectation(prep_program, operator_programs=progs))\n                return np.real_if_close(np.dot(coefs, expect_coeffs))\n\n        :param Program prep_prog: Quil program for state preparation.\n        :param list operator_programs: A list of Programs, each specifying an operator whose expectation to compute.\n            Default is a list containing only the empty Program.\n        :return: Expectation values of the operators.\n        :rtype: List[float]"
  },
  {
    "code": "def cudaDriverGetVersion():\n    version = ctypes.c_int()\n    status = _libcudart.cudaDriverGetVersion(ctypes.byref(version))\n    cudaCheckStatus(status)\n    return version.value",
    "docstring": "Get installed CUDA driver version.\n\n    Return the version of the installed CUDA driver as an integer. If\n    no driver is detected, 0 is returned.\n\n    Returns\n    -------\n    version : int\n        Driver version."
  },
  {
    "code": "def get_rule_option(self, rule_name_or_id, option_name):\n        option = self._get_option(rule_name_or_id, option_name)\n        return option.value",
    "docstring": "Returns the value of a given option for a given rule. LintConfigErrors will be raised if the\n        rule or option don't exist."
  },
  {
    "code": "def has_error(self):\n        self.get_info()\n        if 'status' not in self.info:\n            return False\n        if 'hasError' not in self.info['status']:\n            return False\n        return self.info['status']['hasError']",
    "docstring": "Queries the server to check if the job has an error.\n        Returns True or False."
  },
  {
    "code": "def add_records(self, domain, records):\n        url = self.API_TEMPLATE + self.RECORDS.format(domain=domain)\n        self._patch(url, json=records)\n        self.logger.debug('Added records @ {}'.format(records))\n        return True",
    "docstring": "Adds the specified DNS records to a domain.\n\n        :param domain: the domain to add the records to\n        :param records: the records to add"
  },
  {
    "code": "def parse_FreqDist_interChr(self, f):\n        parsed_data = dict()\n        firstline = True\n        for l in f['f']:\n            if firstline:\n                firstline = False\n                interChr = float(re.sub(\"\\)\", \"\", l.split(\":\")[1]))\n            else:\n                break\n        parsed_data['interChr'] = interChr\n        return parsed_data",
    "docstring": "Parse HOMER tagdirectory petag.FreqDistribution_1000 file to get inter-chromosomal interactions."
  },
  {
    "code": "def constantLine(requestContext, value):\n    name = \"constantLine(%s)\" % str(value)\n    start = int(epoch(requestContext['startTime']))\n    end = int(epoch(requestContext['endTime']))\n    step = int((end - start) / 2.0)\n    series = TimeSeries(str(value), start, end, step, [value, value, value])\n    series.pathExpression = name\n    return [series]",
    "docstring": "Takes a float F.\n\n    Draws a horizontal line at value F across the graph.\n\n    Example::\n\n        &target=constantLine(123.456)"
  },
  {
    "code": "def master(self, name):\n        fut = self.execute(b'MASTER', name, encoding='utf-8')\n        return wait_convert(fut, parse_sentinel_master)",
    "docstring": "Returns a dictionary containing the specified masters state."
  },
  {
    "code": "def get_model_name(self):\n        if self.model_name is None:\n            raise ImproperlyConfigured(\n                \"%s requires either a definition of \"\n                \"'model_name' or an implementation of 'get_model_name()'\" %\n                self.__class__.__name__)\n        return self.model_name",
    "docstring": "Return the model name for templates."
  },
  {
    "code": "def Clear(self):\n    try:\n      with io.open(self.logfile, \"wb\") as fd:\n        fd.write(b\"\")\n    except (IOError, OSError):\n      pass",
    "docstring": "Wipes the transaction log."
  },
  {
    "code": "def _enter_plotting(self, fontsize=9):\n        self.original_fontsize = pyplot.rcParams['font.size']\n        pyplot.rcParams['font.size'] = fontsize\n        pyplot.hold(False)\n        pyplot.ioff()",
    "docstring": "assumes that a figure is open"
  },
  {
    "code": "def should_generate_summaries():\n  name_scope = tf.contrib.framework.get_name_scope()\n  if name_scope and \"while/\" in name_scope:\n    return False\n  if tf.get_variable_scope().reuse:\n    return False\n  return True",
    "docstring": "Is this an appropriate context to generate summaries.\n\n  Returns:\n    a boolean"
  },
  {
    "code": "def fill_edge_matrix(nsrcs, match_dict):\n    e_matrix = np.zeros((nsrcs, nsrcs))\n    for k, v in match_dict.items():\n        e_matrix[k[0], k[1]] = v\n    return e_matrix",
    "docstring": "Create and fill a matrix with the graph 'edges' between sources.\n\n    Parameters\n    ----------\n    nsrcs  : int \n        number of sources (used to allocate the size of the matrix)\n\n    match_dict :  dict((int,int):float)    \n        Each entry gives a pair of source indices, and the\n        corresponding measure (either distance or sigma)\n\n    Returns\n    -------\n    e_matrix : `~numpy.ndarray`    \n        numpy.ndarray((nsrcs,nsrcs)) filled with zeros except for the\n        matches, which are filled with the edge measures (either\n        distances or sigmas)"
  },
  {
    "code": "def elcm_session_terminate(irmc_info, session_id):\n    resp = elcm_request(irmc_info,\n                        method='DELETE',\n                        path='/sessionInformation/%s/terminate' % session_id)\n    if resp.status_code == 200:\n        return\n    elif resp.status_code == 404:\n        raise ELCMSessionNotFound('Session \"%s\" does not exist' % session_id)\n    else:\n        raise scci.SCCIClientError(('Failed to terminate session '\n                                    '\"%(session)s\" with error code %(error)s' %\n                                    {'session': session_id,\n                                     'error': resp.status_code}))",
    "docstring": "send an eLCM request to terminate a session\n\n    :param irmc_info: node info\n    :param session_id: session id\n    :raises: ELCMSessionNotFound if the session does not exist\n    :raises: SCCIClientError if SCCI failed"
  },
  {
    "code": "def _B(self, x, a, b):\n        return special.betainc(a, b, x) * special.beta(a, b)",
    "docstring": "incomplete Beta function as described in Mamon&Lokas A13\n\n        :param x:\n        :param a:\n        :param b:\n        :return:"
  },
  {
    "code": "def compute_vest_stat(vest_dict, ref_aa, somatic_aa, codon_pos,\n                      stat_func=np.mean,\n                      default_val=0.0):\n    if vest_dict is None:\n        return default_val\n    myscores = fetch_vest_scores(vest_dict, ref_aa, somatic_aa, codon_pos)\n    if myscores:\n        score_stat = stat_func(myscores)\n    else:\n        score_stat = default_val\n    return score_stat",
    "docstring": "Compute missense VEST score statistic.\n\n    Note: non-missense mutations are intentially not filtered out and will take\n    a default value of zero.\n\n    Parameters\n    ----------\n    vest_dict : dict\n        dictionary containing vest scores across the gene of interest\n    ref_aa: list of str\n        list of reference amino acids\n    somatic_aa: list of str\n        somatic mutation aa\n    codon_pos : list of int\n        position of codon in protein sequence\n    stat_func : function, default=np.mean\n        function that calculates a statistic\n    default_val : float\n        default value to return if there are no mutations\n\n    Returns\n    -------\n    score_stat : float\n        vest score statistic for provided mutation list"
  },
  {
    "code": "def node_detail(node_name):\n    token = session.get('token')\n    node = nago.core.get_node(token)\n    if not node.get('access') == 'master':\n        return jsonify(status='error', error=\"You need master access to view this page\")\n    node = nago.core.get_node(node_name)\n    return render_template('node_detail.html', node=node)",
    "docstring": "View one specific node"
  },
  {
    "code": "def set_references(references, components):\n        if components == None:\n            return\n        for component in components:\n            Referencer.set_references_for_one(references, component)",
    "docstring": "Sets references to multiple components.\n\n        To set references components must implement [[IReferenceable]] interface.\n        If they don't the call to this method has no effect.\n\n        :param references: the references to be set.\n\n        :param components: a list of components to set the references to."
  },
  {
    "code": "def set_tax_benefit_systems(self, tax_benefit_system = None, baseline_tax_benefit_system = None):\n        assert tax_benefit_system is not None\n        self.tax_benefit_system = tax_benefit_system\n        if self.cache_blacklist is not None:\n            self.tax_benefit_system.cache_blacklist = self.cache_blacklist\n        if baseline_tax_benefit_system is not None:\n            self.baseline_tax_benefit_system = baseline_tax_benefit_system\n            if self.cache_blacklist is not None:\n                self.baseline_tax_benefit_system.cache_blacklist = self.cache_blacklist",
    "docstring": "Set the tax and benefit system and eventually the baseline tax and benefit system"
  },
  {
    "code": "def raise_for_old_graph(graph):\n    graph_version = tokenize_version(graph.pybel_version)\n    if graph_version < PYBEL_MINIMUM_IMPORT_VERSION:\n        raise ImportVersionWarning(graph_version, PYBEL_MINIMUM_IMPORT_VERSION)",
    "docstring": "Raise an ImportVersionWarning if the BEL graph was produced by a legacy version of PyBEL.\n\n    :raises ImportVersionWarning: If the BEL graph was produced by a legacy version of PyBEL"
  },
  {
    "code": "def _run_varnishadm(cmd, params=(), **kwargs):\n    cmd = ['varnishadm', cmd]\n    cmd.extend([param for param in params if param is not None])\n    log.debug('Executing: %s', ' '.join(cmd))\n    return __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs)",
    "docstring": "Execute varnishadm command\n    return the output of the command\n\n    cmd\n        The command to run in varnishadm\n\n    params\n        Any additional args to add to the command line\n\n    kwargs\n        Additional options to pass to the salt cmd.run_all function"
  },
  {
    "code": "def find_raw_devices(vendor=None, product=None, serial_number=None,\n                     custom_match=None, **kwargs):\n    def is_usbraw(dev):\n        if custom_match and not custom_match(dev):\n            return False\n        return bool(find_interfaces(dev, bInterfaceClass=0xFF,\n                                    bInterfaceSubClass=0xFF))\n    return find_devices(vendor, product, serial_number, is_usbraw, **kwargs)",
    "docstring": "Find connected USB RAW devices. See usbutil.find_devices for more info."
  },
  {
    "code": "def addDepartment(self, dep):\n        if api.is_uid(dep):\n            dep = api.get_object_by_uid(dep)\n        deps = self.getDepartments()\n        if dep not in deps:\n            return False\n        deps.append(dep)\n        self.setDepartments(deps)\n        return True",
    "docstring": "Adds a department\n\n        :param dep: UID or department object\n        :returns: True when the department was added"
  },
  {
    "code": "def find_existing_items(\n\tsrc, dst, *, fields=None, field_map=None,\n\tnormalize_values=False, normalize_func=normalize_value):\n\tif field_map is None:\n\t\tfield_map = FIELD_MAP\n\tdst_keys = {\n\t\t_gather_field_values(\n\t\t\tdst_item, fields=fields, field_map=field_map,\n\t\t\tnormalize_values=normalize_values, normalize_func=normalize_func\n\t\t) for dst_item in dst\n\t}\n\tfor src_item in src:\n\t\tif _gather_field_values(\n\t\t\tsrc_item, fields=fields, field_map=field_map,\n\t\t\tnormalize_values=normalize_values, normalize_func=normalize_func\n\t\t) in dst_keys:\n\t\t\tyield src_item",
    "docstring": "Find items from an item collection that are in another item collection.\n\n\tParameters:\n\t\tsrc (list): A list of item dicts or filepaths.\n\t\tdst (list): A list of item dicts or filepaths.\n\t\tfields (list): A list of fields used to compare item dicts.\n\t\tfield_map (~collections.abc.Mapping): A mapping field name aliases.\n\t\t\tDefault: :data:`~google_music_utils.constants.FIELD_MAP`\n\t\tnormalize_values (bool): Normalize metadata values to remove common differences between sources.\n\t\t\tDefault: ``False``\n\t\tnormalize_func (function): Function to apply to metadata values if\n\t\t\t``normalize_values`` is ``True``.\n\t\t\tDefault: :func:`~google_music_utils.utils.normalize_value`\n\n\tYields:\n\t\tdict: The next item from ``src`` collection in ``dst`` collection."
  },
  {
    "code": "def disconnect_sync(self, connection_handle):\n        self.bable.disconnect(connection_handle=connection_handle, sync=True)",
    "docstring": "Synchronously disconnect from whoever has connected to us\n\n        Args:\n            connection_handle (int): The handle of the connection we wish to disconnect."
  },
  {
    "code": "def delete(self, request, key):\n        request.DELETE = http.QueryDict(request.body)\n        email_addr = request.DELETE.get('email')\n        user_id = request.DELETE.get('user')\n        if not email_addr:\n            return http.HttpResponseBadRequest()\n        try:\n            email = EmailAddressValidation.objects.get(address=email_addr,\n                                                       user_id=user_id)\n        except EmailAddressValidation.DoesNotExist:\n            pass\n        else:\n            email.delete()\n            return http.HttpResponse(status=204)\n        try:\n            email = EmailAddress.objects.get(address=email_addr,\n                                             user_id=user_id)\n        except EmailAddress.DoesNotExist:\n            raise http.Http404\n        email.user = None\n        email.save()\n        return http.HttpResponse(status=204)",
    "docstring": "Remove an email address, validated or not."
  },
  {
    "code": "def validate_matches(other):\n    def matches_validator(field, data):\n        if field.value is None:\n            return\n        if not (field.value == data.get(other)):\n            raise ValidationError('matches', other=other)\n    return matches_validator",
    "docstring": "Validate the field value is equal to another field in the data.\n    Should work with anything that supports '==' operator.\n\n    :param value: Field key to compare.\n    :raises: ``ValidationError('matches')``"
  },
  {
    "code": "def find_regions(self, word):\n        length = len(word)\n        for index, match in enumerate(re.finditer(\"[aeiouy][^aeiouy]\", word)):\n            if index == 0:\n                if match.end() < length:\n                    self.r1 = match.end()\n            if index == 1:\n                if match.end() < length:\n                    self.r2 = match.end()\n                break",
    "docstring": "Find regions R1 and R2."
  },
  {
    "code": "def reload(self):\n        config = self._default_configuration()\n        if self._file_path:\n            config.update(self._load_config_file())\n        if config != self._values:\n            self._values = config\n            return True\n        return False",
    "docstring": "Reload the configuration from disk returning True if the\n        configuration has changed from the previous values."
  },
  {
    "code": "def resolve_object_property(obj, path: str):\n    value = obj\n    for path_part in path.split('.'):\n        value = getattr(value, path_part)\n    return value",
    "docstring": "Resolves the value of a property on an object.\n\n    Is able to resolve nested properties. For example,\n    a path can be specified:\n\n        'other.beer.name'\n\n    Raises:\n        AttributeError:\n            In case the property could not be resolved.\n\n    Returns:\n        The value of the specified property."
  },
  {
    "code": "def get_downsampled_scatter(self, xax=\"area_um\", yax=\"deform\",\n                                downsample=0, xscale=\"linear\",\n                                yscale=\"linear\"):\n        if downsample < 0:\n            raise ValueError(\"`downsample` must be zero or positive!\")\n        downsample = int(downsample)\n        xax = xax.lower()\n        yax = yax.lower()\n        x = self[xax][self.filter.all]\n        y = self[yax][self.filter.all]\n        xs = self._apply_scale(x, xscale, xax)\n        ys = self._apply_scale(y, yscale, yax)\n        _, _, idx = downsampling.downsample_grid(xs, ys,\n                                                 samples=downsample,\n                                                 ret_idx=True)\n        self._plot_filter = idx\n        return x[idx], y[idx]",
    "docstring": "Downsampling by removing points at dense locations\n\n        Parameters\n        ----------\n        xax: str\n            Identifier for x axis (e.g. \"area_um\", \"aspect\", \"deform\")\n        yax: str\n            Identifier for y axis\n        downsample: int\n            Number of points to draw in the down-sampled plot.\n            This number is either\n\n            - >=1: exactly downsample to this number by randomly adding\n                   or removing points\n            - 0  : do not perform downsampling\n        xscale: str\n            If set to \"log\", take the logarithm of the x-values before\n            performing downsampling. This is useful when data are are\n            displayed on a log-scale. Defaults to \"linear\".\n        yscale: str\n            See `xscale`.\n\n        Returns\n        -------\n        xnew, xnew: filtered x and y"
  },
  {
    "code": "def detect_mode(term_hint=\"xterm-256color\"):\n    if \"ANSICON\" in os.environ:\n        return 16\n    elif os.environ.get(\"ConEmuANSI\", \"OFF\") == \"ON\":\n        return 256\n    else:\n        term = os.environ.get(\"TERM\", term_hint)\n        if term.endswith(\"-256color\") or term in (\"xterm\", \"screen\"):\n            return 256\n        elif term.endswith(\"-color\") or term in (\"rxvt\",):\n            return 16\n        else:\n            return 256",
    "docstring": "Poor-mans color mode detection."
  },
  {
    "code": "def post(self, url, obj, content_type=JSON_CONTENT_TYPE, **kwargs):\n        def retry_bad_nonce(f):\n            f.trap(ServerError)\n            if f.value.message.typ.split(':')[-1] == 'badNonce':\n                self._nonces.clear()\n                self._add_nonce(f.value.response)\n                return self._post(url, obj, content_type, **kwargs)\n            return f\n        return (\n            self._post(url, obj, content_type, **kwargs)\n            .addErrback(retry_bad_nonce))",
    "docstring": "POST an object and check the response. Retry once if a badNonce error\n        is received.\n\n        :param str url: The URL to request.\n        :param ~josepy.interfaces.JSONDeSerializable obj: The serializable\n            payload of the request.\n        :param bytes content_type: The expected content type of the response.\n            By default, JSON.\n\n        :raises txacme.client.ServerError: If server response body carries HTTP\n            Problem (draft-ietf-appsawg-http-problem-00).\n        :raises acme.errors.ClientError: In case of other protocol errors."
  },
  {
    "code": "def clean_text(text):\n    new_text = re.sub(ur'\\p{P}+', ' ', text)\n    new_text = [stem(i) for i in new_text.lower().split() if not\n                re.findall(r'[0-9]', i)]\n    new_text = ' '.join(new_text)\n    return new_text",
    "docstring": "Clean text for TFIDF."
  },
  {
    "code": "def get_host_port_names(self, host_name):\r\n        port_names = list()\r\n        host = self.get_hosts_by_name(host_name)\r\n        fc_ports = host.fc_ports\r\n        iscsi_ports = host.iscsi_ports\r\n        port_names.extend(fc_ports.split(',') if fc_ports != '' else [])\r\n        port_names.extend(iscsi_ports.split(',') if iscsi_ports != '' else [])\r\n        return port_names",
    "docstring": "return a list of the port names of XIV host"
  },
  {
    "code": "def afw_json_importer(input_file: str) -> dict:\n    file = open(input_file)\n    json_file = json.load(file)\n    transitions = {}\n    for p in json_file['transitions']:\n        transitions[p[0], p[1]] = p[2]\n    afw = {\n        'alphabet': set(json_file['alphabet']),\n        'states': set(json_file['states']),\n        'initial_state': json_file['initial_state'],\n        'accepting_states': set(json_file['accepting_states']),\n        'transitions': transitions\n    }\n    return afw",
    "docstring": "Imports a AFW from a JSON file.\n\n    :param str input_file: path+filename to input JSON file;\n    :return: *(dict)* representing a AFW."
  },
  {
    "code": "def is_valid_variable_name(string_to_check):\n    try:\n        parse('{} = None'.format(string_to_check))\n        return True\n    except (SyntaxError, ValueError, TypeError):\n        return False",
    "docstring": "Returns whether the provided name is a valid variable name in Python\n\n    :param string_to_check: the string to be checked\n    :return: True or False"
  },
  {
    "code": "def Timestamp():\n    timestamp = ''\n    try:\n        timestamp = str(datetime.datetime.now())+' UTC'\n    except Exception as e:\n        logger.error('Could not get current time ' + str(e))\n    return timestamp",
    "docstring": "Get the current datetime in UTC"
  },
  {
    "code": "def request_add_sensor(self, sock, msg):\n        self.add_sensor(Sensor(int, 'int_sensor%d' % len(self._sensors),\n                               'descr', 'unit', params=[-10, 10]))\n        return Message.reply('add-sensor', 'ok')",
    "docstring": "add a sensor"
  },
  {
    "code": "def remove_tmp_prefix_from_file_path(file_path):\n    path, filename = os.path.split(file_path)\n    return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\\\', '/')",
    "docstring": "Remove tmp prefix from file path or url."
  },
  {
    "code": "def _value_format(self, value, serie, index):\n        sum_ = serie.points[index][1]\n        if serie in self.series and (\n                self.stack_from_top\n                and self.series.index(serie) == self._order - 1\n                or not self.stack_from_top and self.series.index(serie) == 0):\n            return super(StackedLine, self)._value_format(value)\n        return '%s (+%s)' % (self._y_format(sum_), self._y_format(value))",
    "docstring": "Display value and cumulation"
  },
  {
    "code": "def makeMissingRequiredGlyphs(font, glyphSet):\n        if \".notdef\" in glyphSet:\n            return\n        unitsPerEm = otRound(getAttrWithFallback(font.info, \"unitsPerEm\"))\n        ascender = otRound(getAttrWithFallback(font.info, \"ascender\"))\n        descender = otRound(getAttrWithFallback(font.info, \"descender\"))\n        defaultWidth = otRound(unitsPerEm * 0.5)\n        glyphSet[\".notdef\"] = StubGlyph(name=\".notdef\",\n                                        width=defaultWidth,\n                                        unitsPerEm=unitsPerEm,\n                                        ascender=ascender,\n                                        descender=descender)",
    "docstring": "Add .notdef to the glyph set if it is not present.\n\n        **This should not be called externally.** Subclasses\n        may override this method to handle the glyph creation\n        in a different way if desired."
  },
  {
    "code": "def ubridge_path(self):\n        path = self._manager.config.get_section_config(\"Server\").get(\"ubridge_path\", \"ubridge\")\n        path = shutil.which(path)\n        return path",
    "docstring": "Returns the uBridge executable path.\n\n        :returns: path to uBridge"
  },
  {
    "code": "def add(cls, model, commit=True):\n        if not isinstance(model, cls):\n            raise ValueError('%s is not of type %s' % (model, cls))\n        cls.session.add(model)\n        try:\n            if commit:\n                cls.session.commit()\n            return model\n        except:\n            cls.session.rollback()\n            raise",
    "docstring": "Adds a model instance to session and commits the\n        transaction.\n\n        Args:\n\n            model: The instance to add.\n\n        Examples:\n\n            >>> customer = Customer.new(name=\"hari\", email=\"hari@gmail.com\")\n\n            >>> Customer.add(customer)\n            hari@gmail.com"
  },
  {
    "code": "def renew_access_token(self):\n        auth_params = {'REFRESH_TOKEN': self.refresh_token}\n        self._add_secret_hash(auth_params, 'SECRET_HASH')\n        refresh_response = self.client.initiate_auth(\n            ClientId=self.client_id,\n            AuthFlow='REFRESH_TOKEN',\n            AuthParameters=auth_params,\n        )\n        self._set_attributes(\n            refresh_response,\n            {\n                'access_token': refresh_response['AuthenticationResult']['AccessToken'],\n                'id_token': refresh_response['AuthenticationResult']['IdToken'],\n                'token_type': refresh_response['AuthenticationResult']['TokenType']\n            }\n        )",
    "docstring": "Sets a new access token on the User using the refresh token."
  },
  {
    "code": "def get_user_cmd(node_dict):\n    key_lu = {\"q\": [\"quit\", True], \"r\": [\"run\", True],\n              \"s\": [\"stop\", True], \"u\": [\"update\", True],\n              \"c\": [\"connect\", True], \"d\": [\"details\", True]}\n    ui_cmd_bar()\n    cmd_valid = False\n    input_flush()\n    with term.cbreak():\n        while not cmd_valid:\n            val = input_by_key()\n            cmd_name, cmd_valid = key_lu.get(val.lower(), [\"invalid\", False])\n            if not cmd_valid:\n                ui_print(\" - {0}Invalid Entry{1}\".format(C_ERR, C_NORM))\n                sleep(0.5)\n                ui_cmd_bar()\n    return cmd_name",
    "docstring": "Get main command selection."
  },
  {
    "code": "def text(self, force_get=False):\n        def text_element():\n            return self.element.text\n        def force_text_element():\n            return self.driver_wrapper.js_executor.execute_template_and_return_result(\n                'getElementText.js', {}, self.element\n            )\n        if force_get:\n            return self.execute_and_handle_webelement_exceptions(force_text_element, 'get text by javascript')\n        else:\n            return self.execute_and_handle_webelement_exceptions(text_element, 'get text')",
    "docstring": "Get the text of the element\n\n        @rtype:     str\n        @return:    Text of the element"
  },
  {
    "code": "def get_code(self):\n        buff = self.get_attribute(\"Code\")\n        if buff is None:\n            return None\n        with unpack(buff) as up:\n            code = JavaCodeInfo(self.cpool)\n            code.unpack(up)\n        return code",
    "docstring": "the JavaCodeInfo of this member if it is a non-abstract method,\n        None otherwise\n\n        reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.3"
  },
  {
    "code": "def get_message_from_call(self, *args, **kwargs):\n        if len(args) == 1 and isinstance(args[0], dict):\n            self.logger.debug('called with arg dictionary')\n            result = args[0]\n        elif len(args) == 0 and kwargs != {}:\n            self.logger.debug('called with kwargs')\n            result = kwargs\n        else:\n            self.logger.error(\n                'get_message_from_call could not handle \"%r\", \"%r\"',\n                args, kwargs\n            )\n            raise TypeError('Pass either keyword arguments or a dictionary argument')\n        return self.message_class(result)",
    "docstring": "\\\n        Get message object from a call.\n\n        :raises: :py:exc:`TypeError` (if the format is not what we expect)\n\n        This is where arguments to nodes are turned into Messages. Arguments\n        are parsed in the following order:\n\n         - A single positional argument (a :py:class:`dict`)\n         - No positional arguments and a number of keyword arguments"
  },
  {
    "code": "def depth_november_average_ground_temperature(self, value=None):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError(\n                    'value {} need to be of type float '\n                    'for field `depth_november_average_ground_temperature`'.format(value))\n        self._depth_november_average_ground_temperature = value",
    "docstring": "Corresponds to IDD Field `depth_november_average_ground_temperature`\n\n        Args:\n            value (float): value for IDD Field `depth_november_average_ground_temperature`\n                Unit: C\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def ones(shape, ctx=None, dtype=None, **kwargs):\n    if ctx is None:\n        ctx = current_context()\n    dtype = mx_real_t if dtype is None else dtype\n    return _internal._ones(shape=shape, ctx=ctx, dtype=dtype, **kwargs)",
    "docstring": "Returns a new array filled with all ones, with the given shape and type.\n\n    Parameters\n    ----------\n    shape : int or tuple of int or list of int\n        The shape of the empty array.\n    ctx : Context, optional\n        An optional device context.\n        Defaults to the current default context (``mxnet.context.current_context()``).\n    dtype : str or numpy.dtype, optional\n        An optional value type (default is `float32`).\n    out : NDArray, optional\n        The output NDArray (default is `None`).\n\n    Returns\n    -------\n    NDArray\n        A new array of the specified shape filled with all ones.\n\n    Examples\n    --------\n    >>> mx.nd.ones(1).asnumpy()\n    array([ 1.], dtype=float32)\n    >>> mx.nd.ones((1,2), mx.gpu(0))\n    <NDArray 1x2 @gpu(0)>\n    >>> mx.nd.ones((1,2), dtype='float16').asnumpy()\n    array([[ 1.,  1.]], dtype=float16)"
  },
  {
    "code": "def _load_result(response, ret):\n    if response['code'] is None:\n        ret['comment'] = response['content']\n    elif response['code'] == 401:\n        ret['comment'] = '401 Forbidden: Authentication required!'\n    elif response['code'] == 404:\n        ret['comment'] = response['content']['message']\n    elif response['code'] == 200:\n        ret['result'] = True\n        ret['comment'] = 'Listing Current Configuration Only.  ' \\\n                         'Not action or changes occurred during the execution of this state.'\n        ret['changes'] = response['content']\n    else:\n        ret['comment'] = response['content']['message']\n    return ret",
    "docstring": "format the results of listing functions"
  },
  {
    "code": "def set_footer(self, *, text=EmptyEmbed, icon_url=EmptyEmbed):\n        self._footer = {}\n        if text is not EmptyEmbed:\n            self._footer['text'] = str(text)\n        if icon_url is not EmptyEmbed:\n            self._footer['icon_url'] = str(icon_url)\n        return self",
    "docstring": "Sets the footer for the embed content.\n\n        This function returns the class instance to allow for fluent-style\n        chaining.\n\n        Parameters\n        -----------\n        text: :class:`str`\n            The footer text.\n        icon_url: :class:`str`\n            The URL of the footer icon. Only HTTP(S) is supported."
  },
  {
    "code": "def repl():\n    try:\n        import IPython\n    except:\n        print(\"ERROR: IPython is not installed. Please install it to use the repl.\", file=sys.stderr)\n        raise\n    IPython.embed(user_ns=dict(\n        settings=oz.settings,\n        actions=oz._actions,\n        uimodules=oz._uimodules,\n        routes=oz._routes,\n    ))",
    "docstring": "Runs an IPython repl with some context"
  },
  {
    "code": "def ssh_file(opts, dest_path, contents=None, kwargs=None, local_file=None):\n    if opts.get('file_transport', 'sftp') == 'sftp':\n        return sftp_file(dest_path, contents, kwargs, local_file)\n    return scp_file(dest_path, contents, kwargs, local_file)",
    "docstring": "Copies a file to the remote SSH target using either sftp or scp, as\n    configured."
  },
  {
    "code": "def add_user(\n        self,\n        username,\n        first_name,\n        last_name,\n        email,\n        role,\n        password=\"\",\n        hashed_password=\"\",\n    ):\n        try:\n            user = self.user_model()\n            user.first_name = first_name\n            user.last_name = last_name\n            user.username = username\n            user.email = email\n            user.active = True\n            user.roles.append(role)\n            if hashed_password:\n                user.password = hashed_password\n            else:\n                user.password = generate_password_hash(password)\n            self.get_session.add(user)\n            self.get_session.commit()\n            log.info(c.LOGMSG_INF_SEC_ADD_USER.format(username))\n            return user\n        except Exception as e:\n            log.error(c.LOGMSG_ERR_SEC_ADD_USER.format(str(e)))\n            self.get_session.rollback()\n            return False",
    "docstring": "Generic function to create user"
  },
  {
    "code": "def get_template_vars(self, slides):\n        try:\n            head_title = slides[0]['title']\n        except (IndexError, TypeError):\n            head_title = \"Untitled Presentation\"\n        for slide_index, slide_vars in enumerate(slides):\n            if not slide_vars:\n                continue\n            self.num_slides += 1\n            slide_number = slide_vars['number'] = self.num_slides\n            if slide_vars['level'] and slide_vars['level'] <= TOC_MAX_LEVEL:\n                self.add_toc_entry(slide_vars['title'], slide_vars['level'],\n                                   slide_number)\n            else:\n                self.add_toc_entry(u\"-\", 1, slide_number)\n        return {'head_title': head_title, 'num_slides': str(self.num_slides),\n                'slides': slides, 'toc': self.toc, 'embed': self.embed,\n                'css': self.get_css(), 'js': self.get_js(),\n                'user_css': self.user_css, 'user_js': self.user_js,\n                'math_output': self.math_output}",
    "docstring": "Computes template vars from slides html source code."
  },
  {
    "code": "def delete_lbaas_port(self, lb_id):\n        lb_id = lb_id.replace('-', '')\n        req = dict(instance_id=lb_id)\n        instances = self.get_vms_for_this_req(**req)\n        for vm in instances:\n            LOG.info(\"deleting lbaas vm %s \" % vm.name)\n            self.delete_vm_function(vm.port_id, vm)",
    "docstring": "send vm down event and delete db.\n\n        :param lb_id: vip id for v1 and lbaas_id for v2"
  },
  {
    "code": "def send_registered_email(self, user, user_email, request_email_confirmation):\n        if not self.user_manager.USER_ENABLE_EMAIL: return\n        if not self.user_manager.USER_SEND_REGISTERED_EMAIL: return\n        email = user_email.email if user_email else user.email\n        if request_email_confirmation:\n            token = self.user_manager.generate_token(user_email.id if user_email else user.id)\n            confirm_email_link = url_for('user.confirm_email', token=token, _external=True)\n        else:\n            confirm_email_link = None\n        self._render_and_send_email(\n            email,\n            user,\n            self.user_manager.USER_REGISTERED_EMAIL_TEMPLATE,\n            confirm_email_link=confirm_email_link,\n        )",
    "docstring": "Send the 'user has registered' notification email."
  },
  {
    "code": "def _prep_cnv_file(in_file, work_dir, somatic_info):\n    out_file = os.path.join(work_dir, \"%s-prep%s\" % utils.splitext_plus(os.path.basename(in_file)))\n    if not utils.file_uptodate(out_file, in_file):\n        with file_transaction(somatic_info.tumor_data, out_file) as tx_out_file:\n            with open(in_file) as in_handle:\n                with open(tx_out_file, \"w\") as out_handle:\n                    out_handle.write(in_handle.readline())\n                    for line in in_handle:\n                        parts = line.split(\"\\t\")\n                        parts[1] = _phylowgs_compatible_chroms(parts[1])\n                        out_handle.write(\"\\t\".join(parts))\n    return out_file",
    "docstring": "Prepare Battenberg CNV file for ingest by PhyloWGS.\n\n    The PhyloWGS preparation script does not handle 'chr' prefixed chromosomes (hg19 style)\n    correctly. This converts them over to GRCh37 (no 'chr') style to match preparation\n    work in _prep_vrn_file."
  },
  {
    "code": "def get_sorted_attachments(self):\n        inf = float(\"inf\")\n        order = self.get_attachments_order()\n        attachments = self.get_attachments()\n        def att_cmp(att1, att2):\n            _n1 = att1.get('UID')\n            _n2 = att2.get('UID')\n            _i1 = _n1 in order and order.index(_n1) + 1 or inf\n            _i2 = _n2 in order and order.index(_n2) + 1 or inf\n            return cmp(_i1, _i2)\n        sorted_attachments = sorted(attachments, cmp=att_cmp)\n        return sorted_attachments",
    "docstring": "Returns a sorted list of analysis info dictionaries"
  },
  {
    "code": "def is_native_xmon_op(op: ops.Operation) -> bool:\n    return (isinstance(op, ops.GateOperation) and\n            is_native_xmon_gate(op.gate))",
    "docstring": "Check if the gate corresponding to an operation is a native xmon gate.\n\n    Args:\n        op: Input operation.\n\n    Returns:\n        True if the operation is native to the xmon, false otherwise."
  },
  {
    "code": "def convert_unicode_2_utf8(input):\n    if isinstance(input, dict):\n        try:\n            return dict((convert_unicode_2_utf8(key), convert_unicode_2_utf8(value))\n                        for key, value\n                        in input.iteritems())\n        except AttributeError:\n            return eval(\n)\n    elif isinstance(input, list):\n        return [convert_unicode_2_utf8(element) for element in input]\n    elif isinstance(input, str):\n        return input\n    else:\n        try:\n            if eval():\n                return input.encode('utf-8')\n        except NameError:\n            pass\n        return input",
    "docstring": "Return a copy of `input` with every str component encoded from unicode to\n    utf-8."
  },
  {
    "code": "def RaiseIfLastError(result, func = None, arguments = ()):\n    code = GetLastError()\n    if code != ERROR_SUCCESS:\n        raise ctypes.WinError(code)\n    return result",
    "docstring": "Error checking for Win32 API calls with no error-specific return value.\n\n    Regardless of the return value, the function calls GetLastError(). If the\n    code is not C{ERROR_SUCCESS} then a C{WindowsError} exception is raised.\n\n    For this to work, the user MUST call SetLastError(ERROR_SUCCESS) prior to\n    calling the API. Otherwise an exception may be raised even on success,\n    since most API calls don't clear the error status code."
  },
  {
    "code": "def install():\n    tmp_weboob_dir = '/tmp/weboob'\n    while (os.path.exists(tmp_weboob_dir)):\n        tmp_weboob_dir += '1'\n    print 'Fetching sources in temporary dir {}'.format(tmp_weboob_dir)\n    result = cmd_exec('git clone {} {}'.format(WEBOOB_REPO, tmp_weboob_dir))\n    if (result['error']):\n        print result['stderr']\n        print 'Weboob installation failed: could not clone repository'\n        exit()\n    print 'Sources fetched, will now process to installation'\n    result = cmd_exec('cd {} && ./setup.py install'.format(tmp_weboob_dir))\n    shutil.rmtree(tmp_weboob_dir)\n    if (result['error']):\n        print result['stderr']\n        print 'Weboob installation failed: setup failed'\n        exit()\n    print result['stdout']\n    weboob_version = get_weboob_version()\n    if (not weboob_version):\n        print 'Weboob installation failed: version not detected'\n        exit()\n    print 'Weboob (version: {}) installation succeeded'.format(weboob_version)\n    update()",
    "docstring": "Install weboob system-wide"
  },
  {
    "code": "def to_dict(self):\n        return {\n            \"gates\": [km.to_dict() for km in self.gates],\n            \"assignment_probs\": {str(qid): a.tolist() for qid, a in self.assignment_probs.items()},\n        }",
    "docstring": "Create a JSON serializable representation of the noise model.\n\n        For example::\n\n            {\n                \"gates\": [\n                    # list of embedded dictionary representations of KrausModels here [...]\n                ]\n                \"assignment_probs\": {\n                    \"0\": [[.8, .1],\n                          [.2, .9]],\n                    \"1\": [[.9, .4],\n                          [.1, .6]],\n                }\n            }\n\n        :return: A dictionary representation of self.\n        :rtype: Dict[str,Any]"
  },
  {
    "code": "def get(s, delimiter='', format=\"diacritical\"):\n    return delimiter.join(_pinyin_generator(u(s), format=format))",
    "docstring": "Return pinyin of string, the string must be unicode"
  },
  {
    "code": "def withNamedValues(cls, **values):\n        enums = set(cls.namedValues.items())\n        enums.update(values.items())\n        class X(cls):\n            namedValues = namedval.NamedValues(*enums)\n            subtypeSpec = cls.subtypeSpec + constraint.SingleValueConstraint(\n                *values.values())\n        X.__name__ = cls.__name__\n        return X",
    "docstring": "Create a subclass with discreet named values constraint.\n\n        Reduce fully duplicate enumerations along the way."
  },
  {
    "code": "def receive_data_chunk(self, raw_data, start):\n        self.file.write(raw_data)\n        eventlet.sleep(0)",
    "docstring": "Over-ridden method to circumvent the worker timeouts on large uploads."
  },
  {
    "code": "def get_app_settings_from_arguments(args):\n    config_filepath = os.path.abspath(args.config_uri)\n    return get_appsettings(config_filepath, name=args.config_name)",
    "docstring": "Parse ``argparse`` style arguments into app settings.\n\n    Given an ``argparse`` set of arguments as ``args``\n    parse the arguments to return the application settings.\n    This assumes the parser was created using ``create_parser``."
  },
  {
    "code": "def get_context_from_gdoc(self):\n        try:\n            start = int(time.time())\n            if not self.data or start > self.expires:\n                self.data = self._get_context_from_gdoc(self.project.SPREADSHEET_KEY)\n                end = int(time.time())\n                ttl = getattr(self.project, 'SPREADSHEET_CACHE_TTL',\n                              SPREADSHEET_CACHE_TTL)\n                self.expires = end + ttl\n            return self.data\n        except AttributeError:\n            return {}",
    "docstring": "Wrap getting context from Google sheets in a simple caching mechanism."
  },
  {
    "code": "def addFollowOnFn(self, fn, *args, **kwargs):\n        if PromisedRequirement.convertPromises(kwargs):\n            return self.addFollowOn(PromisedRequirementFunctionWrappingJob.create(fn, *args, **kwargs))\n        else:\n            return self.addFollowOn(FunctionWrappingJob(fn, *args, **kwargs))",
    "docstring": "Adds a function as a follow-on job.\n\n        :param fn: Function to be run as a follow-on job with ``*args`` and ``**kwargs`` as \\\n        arguments to this function. See toil.job.FunctionWrappingJob for reserved \\\n        keyword arguments used to specify resource requirements.\n        :return: The new follow-on job that wraps fn.\n        :rtype: toil.job.FunctionWrappingJob"
  },
  {
    "code": "def set_prob_type(cls, problem_type, classification_type, eval_type):\n        assert problem_type in problem_type_list, 'Need to set Problem Type'\n        if problem_type == 'classification':\n            assert classification_type in classification_type_list,\\\n                                            'Need to set Classification Type'\n        assert eval_type in eval_type_list, 'Need to set Evaluation Type'\n        cls.problem_type = problem_type\n        cls.classification_type = classification_type\n        cls.eval_type = eval_type\n        if cls.problem_type == 'classification':\n            print 'Setting Problem:{}, Type:{}, Eval:{}'.format(cls.problem_type,\n                                                                cls.classification_type,\n                                                                cls.eval_type)\n        elif cls.problem_type == 'regression':\n            print 'Setting Problem:{}, Eval:{}'.format(cls.problem_type,\n                                                        cls.eval_type)\n        return",
    "docstring": "Set problem type"
  },
  {
    "code": "def _simplify_block(self, ail_block, stack_pointer_tracker=None):\n        simp = self.project.analyses.AILBlockSimplifier(ail_block, stack_pointer_tracker=stack_pointer_tracker)\n        return simp.result_block",
    "docstring": "Simplify a single AIL block.\n\n        :param ailment.Block ail_block: The AIL block to simplify.\n        :param stack_pointer_tracker:   The RegisterDeltaTracker analysis instance.\n        :return:                        A simplified AIL block."
  },
  {
    "code": "def get_unicode_str(obj):\n    if isinstance(obj, six.text_type):\n        return obj\n    if isinstance(obj, six.binary_type):\n        return obj.decode(\"utf-8\", errors=\"ignore\")\n    return six.text_type(obj)",
    "docstring": "Makes sure obj is a unicode string."
  },
  {
    "code": "def _setweights(self):\n        for name_w in self.weights:\n            raw_w = getattr(self.module, name_w + '_raw')\n            w = torch.nn.functional.dropout(raw_w, p=self.dropout, training=self.training)\n            if hasattr(self.module, name_w):\n                delattr(self.module, name_w)\n            setattr(self.module, name_w, w)",
    "docstring": "Uses pytorch's built-in dropout function to apply dropout to the parameters of\n        the wrapped module.\n\n        Args:\n            None\n        Returns:\n            None"
  },
  {
    "code": "def run(self):\n        cmd = list(self.vasp_cmd)\n        if self.auto_gamma:\n            vi = VaspInput.from_directory(\".\")\n            kpts = vi[\"KPOINTS\"]\n            if kpts.style == Kpoints.supported_modes.Gamma \\\n                    and tuple(kpts.kpts[0]) == (1, 1, 1):\n                if self.gamma_vasp_cmd is not None and which(\n                        self.gamma_vasp_cmd[-1]):\n                    cmd = self.gamma_vasp_cmd\n                elif which(cmd[-1] + \".gamma\"):\n                    cmd[-1] += \".gamma\"\n        logger.info(\"Running {}\".format(\" \".join(cmd)))\n        with open(self.output_file, 'w') as f_std, \\\n                open(self.stderr_file, \"w\", buffering=1) as f_err:\n            p = subprocess.Popen(cmd, stdout=f_std, stderr=f_err)\n        return p",
    "docstring": "Perform the actual VASP run.\n\n        Returns:\n            (subprocess.Popen) Used for monitoring."
  },
  {
    "code": "def total_items(self, request):\r\n        n_total = 0\r\n        for item in self.get_queryset(request):\r\n            n_total += item.quantity\r\n        return Response(data={\"quantity\": n_total}, status=status.HTTP_200_OK)",
    "docstring": "Get total number of items in the basket"
  },
  {
    "code": "def get_finder(sources=None, pip_command=None, pip_options=None):\n    if not pip_command:\n        pip_command = get_pip_command()\n    if not sources:\n        sources = [\n            {\"url\": \"https://pypi.org/simple\", \"name\": \"pypi\", \"verify_ssl\": True}\n        ]\n    if not pip_options:\n        pip_options = get_pip_options(sources=sources, pip_command=pip_command)\n    session = pip_command._build_session(pip_options)\n    atexit.register(session.close)\n    finder = pip_shims.shims.PackageFinder(\n        find_links=[],\n        index_urls=[s.get(\"url\") for s in sources],\n        trusted_hosts=[],\n        allow_all_prereleases=pip_options.pre,\n        session=session,\n    )\n    return finder",
    "docstring": "Get a package finder for looking up candidates to install\n\n    :param sources: A list of pipfile-formatted sources, defaults to None\n    :param sources: list[dict], optional\n    :param pip_command: A pip command instance, defaults to None\n    :type pip_command: :class:`~pip._internal.cli.base_command.Command`\n    :param pip_options: A pip options, defaults to None\n    :type pip_options: :class:`~pip._internal.cli.cmdoptions`\n    :return: A package finder\n    :rtype: :class:`~pip._internal.index.PackageFinder`"
  },
  {
    "code": "def ActionEnum(ctx):\n    return Enum(\n        ctx,\n        interact=0,\n        stop=1,\n        ai_interact=2,\n        move=3,\n        add_attribute=5,\n        give_attribute=6,\n        ai_move=10,\n        resign=11,\n        spec=15,\n        waypoint=16,\n        stance=18,\n        guard=19,\n        follow=20,\n        patrol=21,\n        formation=23,\n        save=27,\n        ai_waypoint=31,\n        chapter=32,\n        ai_command=53,\n        ai_queue=100,\n        research=101,\n        build=102,\n        game=103,\n        wall=105,\n        delete=106,\n        attackground=107,\n        tribute=108,\n        repair=110,\n        release=111,\n        multiqueue=112,\n        togglegate=114,\n        flare=115,\n        order=117,\n        queue=119,\n        gatherpoint=120,\n        sell=122,\n        buy=123,\n        droprelic=126,\n        townbell=127,\n        backtowork=128,\n        postgame=255,\n        default=Pass\n    )",
    "docstring": "Action Enumeration."
  },
  {
    "code": "def allow_unconfirmed_email(view_function):\n    @wraps(view_function)\n    def decorator(*args, **kwargs):\n        g._flask_user_allow_unconfirmed_email = True\n        try:\n            user_manager = current_app.user_manager\n            allowed = _is_logged_in_with_confirmed_email(user_manager)\n            if not allowed:\n                return user_manager.unauthenticated_view()\n            return view_function(*args, **kwargs)\n        finally:\n            g._flask_user_allow_unconfirmed_email = False\n    return decorator",
    "docstring": "This decorator ensures that the user is logged in,\n    but allows users with or without a confirmed email addresses\n    to access this particular view.\n\n    It works in tandem with the ``USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL=True`` setting.\n\n    .. caution::\n\n        | Use ``USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL=True`` and\n            ``@allow_unconfirmed_email`` with caution,\n            as they relax security requirements.\n        | Make sure that decorated views **never call other views directly**.\n            Allways use ``redirect()`` to ensure proper view protection.\n\n\n    Example::\n\n        @route('/show_promotion')\n        @allow_unconfirmed_emails\n        def show_promotion():   # Logged in, with or without\n            ...                 # confirmed email address\n\n    It can also precede the ``@roles_required`` and ``@roles_accepted`` view decorators::\n\n        @route('/show_promotion')\n        @allow_unconfirmed_emails\n        @roles_required('Visitor')\n        def show_promotion():   # Logged in, with or without\n            ...                 # confirmed email address\n\n    | Calls unauthorized_view() when the user is not logged in.\n    | Calls the decorated view otherwise."
  },
  {
    "code": "def update_dataset(self, dataset, fields, retry=DEFAULT_RETRY):\n        partial = dataset._build_resource(fields)\n        if dataset.etag is not None:\n            headers = {\"If-Match\": dataset.etag}\n        else:\n            headers = None\n        api_response = self._call_api(\n            retry, method=\"PATCH\", path=dataset.path, data=partial, headers=headers\n        )\n        return Dataset.from_api_repr(api_response)",
    "docstring": "Change some fields of a dataset.\n\n        Use ``fields`` to specify which fields to update. At least one field\n        must be provided. If a field is listed in ``fields`` and is ``None`` in\n        ``dataset``, it will be deleted.\n\n        If ``dataset.etag`` is not ``None``, the update will only\n        succeed if the dataset on the server has the same ETag. Thus\n        reading a dataset with ``get_dataset``, changing its fields,\n        and then passing it to ``update_dataset`` will ensure that the changes\n        will only be saved if no modifications to the dataset occurred\n        since the read.\n\n        Args:\n            dataset (google.cloud.bigquery.dataset.Dataset):\n                The dataset to update.\n            fields (Sequence[str]):\n                The properties of ``dataset`` to change (e.g. \"friendly_name\").\n            retry (google.api_core.retry.Retry, optional):\n                How to retry the RPC.\n\n        Returns:\n            google.cloud.bigquery.dataset.Dataset:\n                The modified ``Dataset`` instance."
  },
  {
    "code": "def get_predicate_indices(tags: List[str]) -> List[int]:\n    return [ind for ind, tag in enumerate(tags) if 'V' in tag]",
    "docstring": "Return the word indices of a predicate in BIO tags."
  },
  {
    "code": "def remove(self, key, cas=0, quiet=None, persist_to=0, replicate_to=0):\n        return _Base.remove(self, key, cas=cas, quiet=quiet,\n                            persist_to=persist_to, replicate_to=replicate_to)",
    "docstring": "Remove the key-value entry for a given key in Couchbase.\n\n        :param key: A string which is the key to remove. The format and\n            type of the key follows the same conventions as in\n            :meth:`upsert`\n        :type key: string, dict, or tuple/list\n\n        :param int cas: The CAS to use for the removal operation.\n            If specified, the key will only be removed from the server\n            if it has the same CAS as specified. This is useful to\n            remove a key only if its value has not been changed from the\n            version currently visible to the client. If the CAS on the\n            server does not match the one specified, an exception is\n            thrown.\n        :param boolean quiet:\n            Follows the same semantics as `quiet` in :meth:`get`\n        :param int persist_to: If set, wait for the item to be removed\n            from the storage of at least these many nodes\n        :param int replicate_to: If set, wait for the item to be removed\n            from the cache of at least these many nodes\n            (excluding the master)\n        :raise: :exc:`.NotFoundError` if the key does not exist.\n        :raise: :exc:`.KeyExistsError` if a CAS was specified, but\n            the CAS on the server had changed\n        :return: A :class:`~.Result` object.\n\n        Simple remove::\n\n            ok = cb.remove(\"key\").success\n\n        Don't complain if key does not exist::\n\n            ok = cb.remove(\"key\", quiet=True)\n\n        Only remove if CAS matches our version::\n\n            rv = cb.get(\"key\")\n            cb.remove(\"key\", cas=rv.cas)\n\n        Remove multiple keys::\n\n            oks = cb.remove_multi([\"key1\", \"key2\", \"key3\"])\n\n        Remove multiple keys with CAS::\n\n            oks = cb.remove({\n                \"key1\" : cas1,\n                \"key2\" : cas2,\n                \"key3\" : cas3\n            })\n\n        .. seealso:: :meth:`remove_multi`, :meth:`endure`\n            for more information on the ``persist_to`` and\n            ``replicate_to`` options."
  },
  {
    "code": "def GMailer(recipients, username, password, subject='Log message from lggr.py'):\n    import smtplib\n    srvr = smtplib.SMTP('smtp.gmail.com', 587)\n    srvr.ehlo()\n    srvr.starttls()\n    srvr.ehlo()\n    srvr.login(username, password)\n    if not (isinstance(recipients, list) or isinstance(recipients, tuple)):\n        recipients = [recipients]\n    gmail_sender = '{0}@gmail.com'.format(username)\n    msg = 'To: {0}\\nFrom: '+gmail_sender+'\\nSubject: '+subject+'\\n'\n    msg = msg + '\\n{1}\\n\\n'\n    try:\n        while True:\n            logstr = (yield)\n            for rcp in recipients:\n                message = msg.format(rcp, logstr)\n                srvr.sendmail(gmail_sender, rcp, message)\n    except GeneratorExit:\n        srvr.quit()",
    "docstring": "Sends messages as emails to the given list\n        of recipients, from a GMail account."
  },
  {
    "code": "def disable_napp(mgr):\n        if mgr.is_enabled():\n            LOG.info('  Disabling...')\n            mgr.disable()\n            LOG.info('  Disabled.')\n        else:\n            LOG.error(\"  NApp isn't enabled.\")",
    "docstring": "Disable a NApp."
  },
  {
    "code": "def service_running(service_name, **kwargs):\n    if init_is_systemd():\n        return service('is-active', service_name)\n    else:\n        if os.path.exists(_UPSTART_CONF.format(service_name)):\n            try:\n                cmd = ['status', service_name]\n                for key, value in six.iteritems(kwargs):\n                    parameter = '%s=%s' % (key, value)\n                    cmd.append(parameter)\n                output = subprocess.check_output(\n                    cmd, stderr=subprocess.STDOUT).decode('UTF-8')\n            except subprocess.CalledProcessError:\n                return False\n            else:\n                if (\"start/running\" in output or\n                        \"is running\" in output or\n                        \"up and running\" in output):\n                    return True\n        elif os.path.exists(_INIT_D_CONF.format(service_name)):\n            return service('status', service_name)\n        return False",
    "docstring": "Determine whether a system service is running.\n\n    :param service_name: the name of the service\n    :param **kwargs: additional args to pass to the service command. This is\n                     used to pass additional key=value arguments to the\n                     service command line for managing specific instance\n                     units (e.g. service ceph-osd status id=2). The kwargs\n                     are ignored in systemd services."
  },
  {
    "code": "def find_ignored_languages(source):\n    for (index, line) in enumerate(source.splitlines()):\n        match = RSTCHECK_COMMENT_RE.match(line)\n        if match:\n            key_and_value = line[match.end():].strip().split('=')\n            if len(key_and_value) != 2:\n                raise Error('Expected \"key=value\" syntax',\n                            line_number=index + 1)\n            if key_and_value[0] == 'ignore-language':\n                for language in key_and_value[1].split(','):\n                    yield language.strip()",
    "docstring": "Yield ignored languages.\n\n    Languages are ignored via comment.\n\n    For example, to ignore C++, JSON, and Python:\n\n    >>> list(find_ignored_languages('''\n    ... Example\n    ... =======\n    ...\n    ... .. rstcheck: ignore-language=cpp,json\n    ...\n    ... .. rstcheck: ignore-language=python\n    ... '''))\n    ['cpp', 'json', 'python']"
  },
  {
    "code": "def to_web_include(\n        project: 'projects.Project',\n        file_path: str\n) -> WEB_INCLUDE:\n    if not file_path.endswith('.css') and not file_path.endswith('.js'):\n        return None\n    slug = file_path[len(project.source_directory):]\n    url = '/{}' \\\n        .format(slug) \\\n        .replace('\\\\', '/') \\\n        .replace('//', '/')\n    return WEB_INCLUDE(name=':project:{}'.format(url), src=url)",
    "docstring": "Converts the given file_path into a WEB_INCLUDE instance that represents\n    the deployed version of this file to be loaded into the results project\n    page\n\n    :param project:\n        Project in which the file_path resides\n    :param file_path:\n        Absolute path to the source file for which the WEB_INCLUDE instance\n        will be created\n    :return:\n        The WEB_INCLUDE instance that represents the given source file"
  },
  {
    "code": "def register_on_snapshot_deleted(self, callback):\n        event_type = library.VBoxEventType.on_snapshot_deleted\n        return self.event_source.register_callback(callback, event_type)",
    "docstring": "Set the callback function to consume on snapshot deleted events.\n\n        Callback receives a ISnapshotDeletedEvent object.\n\n        Returns the callback_id"
  },
  {
    "code": "def to_binary(value, encoding='utf-8'):\n    if not value:\n        return b''\n    if isinstance(value, six.binary_type):\n        return value\n    if isinstance(value, six.text_type):\n        return value.encode(encoding)\n    return to_text(value).encode(encoding)",
    "docstring": "Convert value to binary string, default encoding is utf-8\n\n    :param value: Value to be converted\n    :param encoding: Desired encoding"
  },
  {
    "code": "def check_aggregate(df, variable, components=None, exclude_on_fail=False,\n                    multiplier=1, **kwargs):\n    fdf = df.filter(**kwargs)\n    if len(fdf.data) > 0:\n        vdf = fdf.check_aggregate(variable=variable, components=components,\n                                  exclude_on_fail=exclude_on_fail,\n                                  multiplier=multiplier)\n        df.meta['exclude'] |= fdf.meta['exclude']\n        return vdf",
    "docstring": "Check whether the timeseries values match the aggregation\n    of sub-categories\n\n    Parameters\n    ----------\n    df: IamDataFrame instance\n    args: see IamDataFrame.check_aggregate() for details\n    kwargs: passed to `df.filter()`"
  },
  {
    "code": "def spin_sz(self):\n        return conversions.secondary_spin(self.mass1, self.mass2, self.spin1z,\n                                        self.spin2z)",
    "docstring": "Returns the z-component of the spin of the secondary mass."
  },
  {
    "code": "def validate(method):\n    @wraps(method)\n    def mod_run(self, rinput):\n        self.validate_input(rinput)\n        result = method(self, rinput)\n        self.validate_result(result)\n        return result\n    return mod_run",
    "docstring": "Decorate run method, inputs and outputs are validated"
  },
  {
    "code": "def process_commission(self, commission):\n        asset = commission['asset']\n        cost = commission['cost']\n        self.position_tracker.handle_commission(asset, cost)\n        self._cash_flow(-cost)",
    "docstring": "Process the commission.\n\n        Parameters\n        ----------\n        commission : zp.Event\n            The commission being paid."
  },
  {
    "code": "def error(self, msgid, error):\n        self.requests[msgid].errback(error)\n        del self.requests[msgid]",
    "docstring": "Handle a error message."
  },
  {
    "code": "def fuse_wheels(to_wheel, from_wheel, out_wheel):\n    to_wheel, from_wheel, out_wheel = [\n        abspath(w) for w in (to_wheel, from_wheel, out_wheel)]\n    with InTemporaryDirectory():\n        zip2dir(to_wheel, 'to_wheel')\n        zip2dir(from_wheel, 'from_wheel')\n        fuse_trees('to_wheel', 'from_wheel')\n        rewrite_record('to_wheel')\n        dir2zip('to_wheel', out_wheel)",
    "docstring": "Fuse `from_wheel` into `to_wheel`, write to `out_wheel`\n\n    Parameters\n    ---------\n    to_wheel : str\n        filename of wheel to fuse into\n    from_wheel : str\n        filename of wheel to fuse from\n    out_wheel : str\n        filename of new wheel from fusion of `to_wheel` and `from_wheel`"
  },
  {
    "code": "def get_server_url(self):\n        server_host = self.driver_wrapper.config.get('Server', 'host')\n        server_port = self.driver_wrapper.config.get('Server', 'port')\n        server_username = self.driver_wrapper.config.get_optional('Server', 'username')\n        server_password = self.driver_wrapper.config.get_optional('Server', 'password')\n        server_auth = '{}:{}@'.format(server_username, server_password) if server_username and server_password else ''\n        server_url = 'http://{}{}:{}'.format(server_auth, server_host, server_port)\n        return server_url",
    "docstring": "Return the configured server url\n\n        :returns: server url"
  },
  {
    "code": "def duplicates(inlist):\n    dups = []\n    for i in range(len(inlist)):\n        if inlist[i] in inlist[i+1:]:\n            dups.append(inlist[i])\n    return dups",
    "docstring": "Returns duplicate items in the FIRST dimension of the passed list.\n\nUsage:   duplicates (inlist)"
  },
  {
    "code": "def loads(string):\n    d = _loads(string)\n    for k, v in d.items():\n        FILTERS[dr.get_component(k) or k] = set(v)",
    "docstring": "Loads the filters dictionary given a string."
  },
  {
    "code": "def _export_module_attachments(meta_graph):\n  added_attachments = tf_v1.get_collection(_ATTACHMENT_COLLECTION_INTERNAL)\n  if not added_attachments: return\n  unique_attachments = collections.OrderedDict(\n      (attachment.key, attachment)\n      for attachment in added_attachments)\n  meta_graph.collection_def[ATTACHMENT_COLLECTION_SAVED].bytes_list.value[:] = [\n      attachment.SerializeToString()\n      for attachment in unique_attachments.values()]",
    "docstring": "Exports ModuleAttachments from the current tf.Graph into `meta_graph`."
  },
  {
    "code": "def js_adaptor(buffer):\n    buffer = re.sub('true', 'True', buffer)\n    buffer = re.sub('false', 'False', buffer)\n    buffer = re.sub('none', 'None', buffer)\n    buffer = re.sub('NaN', '\"NaN\"', buffer)\n    return buffer",
    "docstring": "convert javascript objects like true, none, NaN etc. to\n    quoted word.\n\n    Arguments:\n        buffer: string to be converted\n\n    Returns:\n        string after conversion"
  },
  {
    "code": "def is_article(self, response, url):\n        site = self.__sites_object[url]\n        heuristics = self.__get_enabled_heuristics(url)\n        self.log.info(\"Checking site: %s\", response.url)\n        statement = self.__get_condition(url)\n        self.log.debug(\"Condition (original): %s\", statement)\n        for heuristic, condition in heuristics.items():\n            heuristic_func = getattr(self, heuristic)\n            result = heuristic_func(response, site)\n            check = self.__evaluate_result(result, condition)\n            statement = re.sub(r\"\\b%s\\b\" % heuristic, str(check), statement)\n            self.log.debug(\"Checking heuristic (%s)\"\n                           \" result (%s) on condition (%s): %s\",\n                           heuristic, result, condition, check)\n        self.log.debug(\"Condition (evaluated): %s\", statement)\n        is_article = eval(statement)\n        self.log.debug(\"Article accepted: %s\", is_article)\n        return is_article",
    "docstring": "Tests if the given response is an article by calling and checking\n        the heuristics set in config.cfg and sitelist.json\n\n        :param obj response: The response of the site.\n        :param str url: The base_url (needed to get the site-specific config\n                        from the JSON-file)\n        :return bool: true if the heuristics match the site as an article"
  },
  {
    "code": "def select(*signals: Signal, **kwargs) -> List[Signal]:\n    class CleanUp(Interrupt):\n        pass\n    timeout = kwargs.get(\"timeout\", None)\n    if not isinstance(timeout, (float, int, type(None))):\n        raise ValueError(\"The timeout keyword parameter can be either None or a number.\")\n    def wait_one(signal: Signal, common: Signal) -> None:\n        try:\n            signal.wait()\n            common.turn_on()\n        except CleanUp:\n            pass\n    common = Signal(name=local.name + \"-selector\").turn_off()\n    if _logger is not None:\n        _log(INFO, \"select\", \"select\", \"select\", signals=[sig.name for sig in signals])\n    procs = []\n    for signal in signals:\n        procs.append(add(wait_one, signal, common))\n    try:\n        common.wait(timeout)\n    finally:\n        for proc in procs:\n            proc.interrupt(CleanUp())\n    return [signal for signal in signals if signal.is_on]",
    "docstring": "Allows the current process to wait for multiple concurrent signals. Waits until one of the signals turns on, at\n    which point this signal is returned.\n\n    :param timeout:\n        If this parameter is not ``None``, it is taken as a delay at the end of which the process times out, and\n        stops waiting on the set of :py:class:`Signal`s. In such a situation, a :py:class:`Timeout` exception is raised\n        on the process."
  },
  {
    "code": "def _update(self, dataFile, handle):\n        self._cache.remove((dataFile, handle))\n        self._add(dataFile, handle)",
    "docstring": "Update the priority of the file handle. The element is first\n        removed and then added to the left of the deque."
  },
  {
    "code": "def create_divisao_dc(self):\n        return DivisaoDc(\n            self.networkapi_url,\n            self.user,\n            self.password,\n            self.user_ldap)",
    "docstring": "Get an instance of divisao_dc services facade."
  },
  {
    "code": "def global_state_code(self):\n        self._generate_func_code()\n        if not self._compile_regexps:\n            return '\\n'.join(\n                [\n                    'from fastjsonschema import JsonSchemaException',\n                    '',\n                    '',\n                ]\n            )\n        regexs = ['\"{}\": re.compile(r\"{}\")'.format(key, value.pattern) for key, value in self._compile_regexps.items()]\n        return '\\n'.join(\n            [\n                'import re',\n                'from fastjsonschema import JsonSchemaException',\n                '',\n                '',\n                'REGEX_PATTERNS = {',\n                '    ' + ',\\n    '.join(regexs),\n                '}',\n                '',\n            ]\n        )",
    "docstring": "Returns global variables for generating function from ``func_code`` as code.\n        Includes compiled regular expressions and imports."
  },
  {
    "code": "def first(self, values, axis=0):\n        values = np.asarray(values)\n        return self.unique, np.take(values, self.index.sorter[self.index.start], axis)",
    "docstring": "return values at first occurance of its associated key\n\n        Parameters\n        ----------\n        values : array_like, [keys, ...]\n            values to pick the first value of per group\n        axis : int, optional\n            alternative reduction axis for values\n\n        Returns\n        -------\n        unique: ndarray, [groups]\n            unique keys\n        reduced : ndarray, [groups, ...]\n            value array, reduced over groups"
  },
  {
    "code": "def sunset_utc(self, date, latitude, longitude, observer_elevation=0):\n        try:\n            return self._calc_time(90 + 0.833, SUN_SETTING, date, latitude, longitude, observer_elevation)\n        except ValueError as exc:\n            if exc.args[0] == \"math domain error\":\n                raise AstralError(\n                    (\"Sun never reaches the horizon on this day, \" \"at this location.\")\n                )\n            else:\n                raise",
    "docstring": "Calculate sunset time in the UTC timezone.\n\n        :param date:       Date to calculate for.\n        :type date:        :class:`datetime.date`\n        :param latitude:   Latitude - Northern latitudes should be positive\n        :type latitude:    float\n        :param longitude:  Longitude - Eastern longitudes should be positive\n        :type longitude:   float\n        :param observer_elevation:  Elevation in metres to calculate sunset for\n        :type observer_elevation:   int\n\n        :return: The UTC date and time at which sunset occurs.\n        :rtype: :class:`~datetime.datetime`"
  },
  {
    "code": "def restart(self, force=False, wait_for_available=True,\n                operation_timeout=None):\n        body = {'force': force}\n        self.manager.session.post(self.uri + '/operations/restart', body=body)\n        if wait_for_available:\n            time.sleep(10)\n            self.manager.client.wait_for_available(\n                operation_timeout=operation_timeout)",
    "docstring": "Restart the HMC represented by this Console object.\n\n        Once the HMC is online again, this Console object, as well as any other\n        resource objects accessed through this HMC, can continue to be used.\n        An automatic re-logon will be performed under the covers, because the\n        HMC restart invalidates the currently used HMC session.\n\n        Authorization requirements:\n\n        * Task permission for the \"Shutdown/Restart\" task.\n        * \"Remote Restart\" must be enabled on the HMC.\n\n        Parameters:\n\n          force (bool):\n            Boolean controlling whether the restart operation is processed when\n            users are connected (`True`) or not (`False`). Users in this sense\n            are local or remote GUI users. HMC WS API clients do not count as\n            users for this purpose.\n\n          wait_for_available (bool):\n            Boolean controlling whether this method should wait for the HMC to\n            become available again after the restart, as follows:\n\n            * If `True`, this method will wait until the HMC has restarted and\n              is available again. The\n              :meth:`~zhmcclient.Client.query_api_version` method will be used\n              to check for availability of the HMC.\n\n            * If `False`, this method will return immediately once the HMC\n              has accepted the request to be restarted.\n\n          operation_timeout (:term:`number`):\n            Timeout in seconds, for waiting for HMC availability after the\n            restart. The special value 0 means that no timeout is set. `None`\n            means that the default async operation timeout of the session is\n            used. If the timeout expires when `wait_for_available=True`, a\n            :exc:`~zhmcclient.OperationTimeout` is raised.\n\n        Raises:\n\n          :exc:`~zhmcclient.HTTPError`\n          :exc:`~zhmcclient.ParseError`\n          :exc:`~zhmcclient.AuthError`\n          :exc:`~zhmcclient.ConnectionError`\n          :exc:`~zhmcclient.OperationTimeout`: The timeout expired while\n            waiting for the HMC to become available again after the restart."
  },
  {
    "code": "def show_agent(self, agent, **_params):\n        return self.get(self.agent_path % (agent), params=_params)",
    "docstring": "Fetches information of a certain agent."
  },
  {
    "code": "def __iterate_value(self, value):\r\n        if hasattr(value, '__dict__') or isinstance(value, dict):\r\n            return self.__find_object_children(value)\n        elif isinstance(value, (list, tuple, set)):\r\n            return self.__construct_list(value)\n        return self.safe_values(value)",
    "docstring": "Return value for JSON serialization"
  },
  {
    "code": "def add_corpus(self,\n                   customization_id,\n                   corpus_name,\n                   corpus_file,\n                   allow_overwrite=None,\n                   **kwargs):\n        if customization_id is None:\n            raise ValueError('customization_id must be provided')\n        if corpus_name is None:\n            raise ValueError('corpus_name must be provided')\n        if corpus_file is None:\n            raise ValueError('corpus_file must be provided')\n        headers = {}\n        if 'headers' in kwargs:\n            headers.update(kwargs.get('headers'))\n        sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'add_corpus')\n        headers.update(sdk_headers)\n        params = {'allow_overwrite': allow_overwrite}\n        form_data = {}\n        form_data['corpus_file'] = (None, corpus_file, 'text/plain')\n        url = '/v1/customizations/{0}/corpora/{1}'.format(\n            *self._encode_path_vars(customization_id, corpus_name))\n        response = self.request(\n            method='POST',\n            url=url,\n            headers=headers,\n            params=params,\n            files=form_data,\n            accept_json=True)\n        return response",
    "docstring": "Add a corpus.\n\n        Adds a single corpus text file of new training data to a custom language model.\n        Use multiple requests to submit multiple corpus text files. You must use\n        credentials for the instance of the service that owns a model to add a corpus to\n        it. Adding a corpus does not affect the custom language model until you train the\n        model for the new data by using the **Train a custom language model** method.\n        Submit a plain text file that contains sample sentences from the domain of\n        interest to enable the service to extract words in context. The more sentences you\n        add that represent the context in which speakers use words from the domain, the\n        better the service's recognition accuracy.\n        The call returns an HTTP 201 response code if the corpus is valid. The service\n        then asynchronously processes the contents of the corpus and automatically\n        extracts new words that it finds. This can take on the order of a minute or two to\n        complete depending on the total number of words and the number of new words in the\n        corpus, as well as the current load on the service. You cannot submit requests to\n        add additional resources to the custom model or to train the model until the\n        service's analysis of the corpus for the current request completes. Use the **List\n        a corpus** method to check the status of the analysis.\n        The service auto-populates the model's words resource with words from the corpus\n        that are not found in its base vocabulary. These are referred to as\n        out-of-vocabulary (OOV) words. You can use the **List custom words** method to\n        examine the words resource. You can use other words method to eliminate typos and\n        modify how words are pronounced as needed.\n        To add a corpus file that has the same name as an existing corpus, set the\n        `allow_overwrite` parameter to `true`; otherwise, the request fails. Overwriting\n        an existing corpus causes the service to process the corpus text file and extract\n        OOV words anew. Before doing so, it removes any OOV words associated with the\n        existing corpus from the model's words resource unless they were also added by\n        another corpus or grammar, or they have been modified in some way with the **Add\n        custom words** or **Add a custom word** method.\n        The service limits the overall amount of data that you can add to a custom model\n        to a maximum of 10 million total words from all sources combined. Also, you can\n        add no more than 30 thousand custom (OOV) words to a model. This includes words\n        that the service extracts from corpora and grammars, and words that you add\n        directly.\n        **See also:**\n        * [Working with\n        corpora](https://cloud.ibm.com/docs/services/speech-to-text/language-resource.html#workingCorpora)\n        * [Add corpora to the custom language\n        model](https://cloud.ibm.com/docs/services/speech-to-text/language-create.html#addCorpora).\n\n        :param str customization_id: The customization ID (GUID) of the custom language\n        model that is to be used for the request. You must make the request with\n        credentials for the instance of the service that owns the custom model.\n        :param str corpus_name: The name of the new corpus for the custom language model.\n        Use a localized name that matches the language of the custom model and reflects\n        the contents of the corpus.\n        * Include a maximum of 128 characters in the name.\n        * Do not include spaces, slashes, or backslashes in the name.\n        * Do not use the name of an existing corpus or grammar that is already defined for\n        the custom model.\n        * Do not use the name `user`, which is reserved by the service to denote custom\n        words that are added or modified by the user.\n        :param file corpus_file: A plain text file that contains the training data for the\n        corpus. Encode the file in UTF-8 if it contains non-ASCII characters; the service\n        assumes UTF-8 encoding if it encounters non-ASCII characters.\n        Make sure that you know the character encoding of the file. You must use that\n        encoding when working with the words in the custom language model. For more\n        information, see [Character\n        encoding](https://cloud.ibm.com/docs/services/speech-to-text/language-resource.html#charEncoding).\n        With the `curl` command, use the `--data-binary` option to upload the file for the\n        request.\n        :param bool allow_overwrite: If `true`, the specified corpus overwrites an\n        existing corpus with the same name. If `false`, the request fails if a corpus with\n        the same name already exists. The parameter has no effect if a corpus with the\n        same name does not already exist.\n        :param dict headers: A `dict` containing the request headers\n        :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n        :rtype: DetailedResponse"
  },
  {
    "code": "def get_cache_buster(src_path, method='importtime'):\n    try:\n        fn = _BUST_METHODS[method]\n    except KeyError:\n        raise KeyError('Unsupported busting method value: %s' % method)\n    return fn(src_path)",
    "docstring": "Return a string that can be used as a parameter for cache-busting URLs\n    for this asset.\n\n    :param src_path:\n        Filesystem path to the file we're generating a cache-busting value for.\n\n    :param method:\n        Method for cache-busting. Supported values: importtime, mtime, md5\n        The default is 'importtime', because it requires the least processing.\n\n    Note that the mtime and md5 cache busting methods' results are cached on\n    the src_path.\n\n    Example::\n\n        >>> SRC_PATH = os.path.join(os.path.dirname(__file__), 'html.py')\n        >>> get_cache_buster(SRC_PATH) is _IMPORT_TIME\n        True\n        >>> get_cache_buster(SRC_PATH, method='mtime') == _cache_key_by_mtime(SRC_PATH)\n        True\n        >>> get_cache_buster(SRC_PATH, method='md5') == _cache_key_by_md5(SRC_PATH)\n        True"
  },
  {
    "code": "def validate(self,value):\n        if self.validator is not None:\n            try:\n                valid = self.validator(value)\n            except Exception as e:\n                import pdb; pdb.set_trace()\n            if isinstance(valid, tuple) and len(valid) == 2:\n                valid, errormsg = valid\n            elif isinstance(valid, bool):\n                errormsg = \"Invalid value\"\n            else:\n                raise TypeError(\"Custom validator must return a boolean or a (bool, errormsg) tuple.\")\n            if valid:\n                self.error = None\n            else:\n                self.error = errormsg\n            return valid\n        else:\n            self.error = None\n            return True",
    "docstring": "Validate the parameter"
  },
  {
    "code": "def event_exists(self, client, check):\n        return self.api_request(\n            'get',\n            'events/{}/{}'.format(client, check)\n            ).status_code == 200",
    "docstring": "Query Sensu API for event."
  },
  {
    "code": "def bwrite(stream, obj):\n    handle = None\n    if not hasattr(stream, \"write\"):\n        stream = handle = open(stream, \"wb\")\n    try:\n        stream.write(bencode(obj))\n    finally:\n        if handle:\n            handle.close()",
    "docstring": "Encode a given object to a file or stream."
  },
  {
    "code": "def create(self, to, from_, parameters=values.unset):\n        data = values.of({'To': to, 'From': from_, 'Parameters': serialize.object(parameters), })\n        payload = self._version.create(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return ExecutionInstance(self._version, payload, flow_sid=self._solution['flow_sid'], )",
    "docstring": "Create a new ExecutionInstance\n\n        :param unicode to: The Contact phone number to start a Studio Flow Execution.\n        :param unicode from_: The Twilio phone number to send messages or initiate calls from during the Flow Execution.\n        :param dict parameters: JSON data that will be added to your flow's context and can accessed as variables inside your flow.\n\n        :returns: Newly created ExecutionInstance\n        :rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance"
  },
  {
    "code": "def predictions_iter(self):\n        for fname in self.forecast_names:\n            yield self.predictions.get(col_names=fname)",
    "docstring": "property decorated prediction iterator\n\n        Returns\n        -------\n        iterator : iterator\n            iterator on prediction sensitivity vectors (matrix)"
  },
  {
    "code": "def determine_version(self, request, api_version=None):\n        if api_version is False:\n            api_version = None\n            for version in self.versions:\n                if version and \"v{0}\".format(version) in request.path:\n                    api_version = version\n                    break\n        request_version = set()\n        if api_version is not None:\n            request_version.add(api_version)\n        version_header = request.get_header(\"X-API-VERSION\")\n        if version_header:\n            request_version.add(version_header)\n        version_param = request.get_param('api_version')\n        if version_param is not None:\n            request_version.add(version_param)\n        if len(request_version) > 1:\n            raise ValueError('You are requesting conflicting versions')\n        return next(iter(request_version or (None, )))",
    "docstring": "Determines the appropriate version given the set api_version, the request header, and URL query params"
  },
  {
    "code": "def enable(self, trigger_ids=[]):\n        trigger_ids = ','.join(trigger_ids)\n        url = self._service_url(['triggers', 'enabled'], params={'triggerIds': trigger_ids, 'enabled': 'true'})\n        self._put(url, data=None, parse_json=False)",
    "docstring": "Enable triggers.\n\n        :param trigger_ids: List of trigger definition ids to enable"
  },
  {
    "code": "def register_vcs_handler(vcs, method):\n    def decorate(f):\n        if vcs not in HANDLERS:\n            HANDLERS[vcs] = {}\n        HANDLERS[vcs][method] = f\n        return f\n    return decorate",
    "docstring": "Decorator to mark a method as the handler for a particular VCS."
  },
  {
    "code": "def calc_checksum(sentence):\n    if sentence.startswith('$'):\n        sentence = sentence[1:]\n    sentence = sentence.split('*')[0]\n    return reduce(xor, map(ord, sentence))",
    "docstring": "Calculate a NMEA 0183 checksum for the given sentence.\n\n    NMEA checksums are a simple XOR of all the characters in the sentence\n    between the leading \"$\" symbol, and the \"*\" checksum separator.\n\n    Args:\n        sentence (str): NMEA 0183 formatted sentence"
  },
  {
    "code": "def convert(source, ext=COMPLETE, fmt=HTML, dname=None):\n    if dname and not ext & COMPATIBILITY:\n        if os.path.isfile(dname):\n            dname = os.path.abspath(os.path.dirname(dname))\n        source, _ = _expand_source(source, dname, fmt)\n    _MMD_LIB.markdown_to_string.argtypes = [ctypes.c_char_p, ctypes.c_ulong, ctypes.c_int]\n    _MMD_LIB.markdown_to_string.restype = ctypes.c_char_p\n    src = source.encode('utf-8')\n    return _MMD_LIB.markdown_to_string(src, ext, fmt).decode('utf-8')",
    "docstring": "Converts a string of MultiMarkdown text to the requested format.\n    Transclusion is performed if the COMPATIBILITY extension is not set, and dname is set to a\n    valid directory\n\n    Keyword arguments:\n    source -- string containing MultiMarkdown text\n    ext -- extension bitfield to pass to conversion process\n    fmt -- flag indicating output format to use\n    dname -- Path to use for transclusion - if None, transclusion functionality is bypassed"
  },
  {
    "code": "def load(self, name):\n        name = ctypes.util.find_library(name)\n        return ctypes.cdll.LoadLibrary(name)",
    "docstring": "Loads and returns foreign library."
  },
  {
    "code": "def _check_load_parameters(self, **kwargs):\n        rset = self._meta_data['required_load_parameters']\n        check = _missing_required_parameters(rset, **kwargs)\n        if check:\n            check.sort()\n            error_message = 'Missing required params: %s' % check\n            raise MissingRequiredReadParameter(error_message)",
    "docstring": "Params given to load should at least satisfy required params.\n\n        :params: kwargs\n        :raises: MissingRequiredReadParameter"
  },
  {
    "code": "def region_by_identifier(self, identifier):\n        if identifier < 0:\n            raise(ValueError(\"Identifier must be a positive integer.\"))\n        if not np.equal(np.mod(identifier, 1), 0):\n            raise(ValueError(\"Identifier must be a positive integer.\"))\n        if identifier == 0:\n            raise(ValueError(\"0 represents the background.\"))\n        return Region.select_from_array(self, identifier)",
    "docstring": "Return region of interest corresponding to the supplied identifier.\n\n        :param identifier: integer corresponding to the segment of interest\n        :returns: `jicbioimage.core.region.Region`"
  },
  {
    "code": "def open(self):\n        if not self.handle:\n            try:\n                path = self.system_dir\n            except AttributeError:\n                path = ''\n            self.__handle = lvm_init(path)\n            if not bool(self.__handle):\n                raise HandleError(\"Failed to initialize LVM handle.\")",
    "docstring": "Obtains the lvm handle. Usually you would never need to use this method unless\n        you are trying to do operations using the ctypes function wrappers in conversion.py\n\n        *Raises:*\n\n        *       HandleError"
  },
  {
    "code": "def filter_by_analysis_period(self, analysis_period):\n        self._check_analysis_period(analysis_period)\n        _filtered_data = self.filter_by_moys(analysis_period.moys)\n        _filtered_data.header._analysis_period = analysis_period\n        return _filtered_data",
    "docstring": "Filter a Data Collection based on an analysis period.\n\n        Args:\n           analysis period: A Ladybug analysis period\n\n        Return:\n            A new Data Collection with filtered data"
  },
  {
    "code": "def page_should_not_contain_text(self, text, loglevel='INFO'):\r\n        if self._is_text_present(text):\r\n            self.log_source(loglevel)\r\n            raise AssertionError(\"Page should not have contained text '%s'\" % text)\r\n        self._info(\"Current page does not contains text '%s'.\" % text)",
    "docstring": "Verifies that current page not contains `text`.\r\n\r\n        If this keyword fails, it automatically logs the page source\r\n        using the log level specified with the optional `loglevel` argument.\r\n        Giving `NONE` as level disables logging."
  },
  {
    "code": "def upsample(self, factor):\n        self.checkforpilimage()\n        if type(factor) != type(0):\n            raise RuntimeError, \"Upsample factor must be an integer !\"\n        if self.verbose:\n            print \"Upsampling by a factor of %i\" % factor\n        self.pilimage = self.pilimage.resize((self.pilimage.size[0] * factor, self.pilimage.size[1] * factor))\n        self.upsamplefactor = factor\n        self.draw = None",
    "docstring": "The inverse operation of rebin, applied on the PIL image.\n        Do this before writing text or drawing on the image !\n        The coordinates will be automatically converted for you"
  },
  {
    "code": "def set_proto_message_event(\n        pb_message_event,\n        span_data_message_event):\n    pb_message_event.type = span_data_message_event.type\n    pb_message_event.id = span_data_message_event.id\n    pb_message_event.uncompressed_size = \\\n        span_data_message_event.uncompressed_size_bytes\n    pb_message_event.compressed_size = \\\n        span_data_message_event.compressed_size_bytes",
    "docstring": "Sets properties on the protobuf message event.\n\n    :type pb_message_event:\n        :class: `~opencensus.proto.trace.Span.TimeEvent.MessageEvent`\n    :param pb_message_event: protobuf message event\n\n    :type span_data_message_event:\n        :class: `~opencensus.trace.time_event.MessageEvent`\n    :param span_data_message_event: opencensus message event"
  },
  {
    "code": "def to_dqflags(self, bits=None, minlen=1, dtype=float, round=False):\n        from ..segments import DataQualityDict\n        out = DataQualityDict()\n        bitseries = self.get_bit_series(bits=bits)\n        for bit, sts in bitseries.items():\n            out[bit] = sts.to_dqflag(name=bit, minlen=minlen, round=round,\n                                     dtype=dtype,\n                                     description=self.bits.description[bit])\n        return out",
    "docstring": "Convert this `StateVector` into a `~gwpy.segments.DataQualityDict`\n\n        The `StateTimeSeries` for each bit is converted into a\n        `~gwpy.segments.DataQualityFlag` with the bits combined into a dict.\n\n        Parameters\n        ----------\n        minlen : `int`, optional, default: 1\n           minimum number of consecutive `True` values to identify as a\n           `Segment`. This is useful to ignore single bit flips,\n           for example.\n\n        bits : `list`, optional\n            a list of bit indices or bit names to select, defaults to\n            `~StateVector.bits`\n\n        Returns\n        -------\n        DataQualityFlag list : `list`\n            a list of `~gwpy.segments.flag.DataQualityFlag`\n            reprensentations for each bit in this `StateVector`\n\n        See Also\n        --------\n        :meth:`StateTimeSeries.to_dqflag`\n            for details on the segment representation method for\n            `StateVector` bits"
  },
  {
    "code": "def get_categorical_feature_names(example):\n  features = get_example_features(example)\n  return sorted([\n      feature_name for feature_name in features\n      if features[feature_name].WhichOneof('kind') == 'bytes_list'\n  ])",
    "docstring": "Returns a list of feature names for byte type features.\n\n  Args:\n    example: An example.\n\n  Returns:\n    A list of categorical feature names (e.g. ['education', 'marital_status'] )"
  },
  {
    "code": "def _check_and_handle_includes(self, from_file):\n        logger.debug(\"Check/handle includes from %s\", from_file)\n        try:\n            paths = self._parser.get(\"INCLUDE\", \"paths\")\n        except (config_parser.NoSectionError,\n                config_parser.NoOptionError) as exc:\n            logger.debug(\"_check_and_handle_includes: EXCEPTION: %s\", exc)\n            return\n        paths_lines = [p.strip() for p in paths.split(\"\\n\")]\n        logger.debug(\"paths = %s (wanted just once; CLEARING)\", paths_lines)\n        self._parser.remove_option(\"INCLUDE\", \"paths\")\n        for f in paths_lines:\n            abspath = (f if os.path.isabs(f) else\n                       os.path.abspath(\n                           os.path.join(os.path.dirname(from_file), f)))\n            use_path = os.path.normpath(abspath)\n            if use_path in self._parsed_files:\n                raise RecursionInConfigFile(\"In %s: %s already read\",\n                                            from_file, use_path)\n            self._parsed_files.append(use_path)\n            self._handle_rc_file(use_path)",
    "docstring": "Look for an optional INCLUDE section in the given file path.  If\n        the parser set `paths`, it is cleared so that they do not keep\n        showing up when additional files are parsed."
  },
  {
    "code": "def _print_results(file, status):\n        file_color = c.Fore.GREEN\n        status_color = c.Fore.RED\n        if status == 'Success':\n            status_color = c.Fore.GREEN\n        elif status == 'Skipped':\n            status_color = c.Fore.YELLOW\n        print(\n            '{}{!s:<13}{}{!s:<35}{}{!s:<8}{}{}'.format(\n                c.Fore.CYAN,\n                'Downloading:',\n                file_color,\n                file,\n                c.Fore.CYAN,\n                'Status:',\n                status_color,\n                status,\n            )\n        )",
    "docstring": "Print the download results.\n\n        Args:\n            file (str): The filename.\n            status (str): The file download status."
  },
  {
    "code": "def rebalance_replicas(\n            self,\n            max_movement_count=None,\n            max_movement_size=None,\n    ):\n        movement_count = 0\n        movement_size = 0\n        for partition in six.itervalues(self.cluster_topology.partitions):\n            count, size = self._rebalance_partition_replicas(\n                partition,\n                None if not max_movement_count\n                else max_movement_count - movement_count,\n                None if not max_movement_size\n                else max_movement_size - movement_size,\n            )\n            movement_count += count\n            movement_size += size\n        return movement_count, movement_size",
    "docstring": "Balance replicas across replication-groups.\n\n        :param max_movement_count: The maximum number of partitions to move.\n        :param max_movement_size: The maximum total size of the partitions to move.\n\n        :returns: A 2-tuple whose first element is the number of partitions moved\n            and whose second element is the total size of the partitions moved."
  },
  {
    "code": "def _send_script(self, device_info, control_info, script, progress_callback):\n        for i in range(0, len(script), 20):\n            chunk = script[i:i+20]\n            self._send_rpc(device_info, control_info, 8, 0x2101, chunk, 0.001, 1.0)\n            if progress_callback is not None:\n                progress_callback(i + len(chunk), len(script))",
    "docstring": "Send a script by repeatedly sending it as a bunch of RPCs.\n\n        This function doesn't do anything special, it just sends a bunch of RPCs\n        with each chunk of the script until it's finished."
  },
  {
    "code": "def filter_dependencies(self):\n        dependencies = self.event['check'].get('dependencies', None)\n        if dependencies is None or not isinstance(dependencies, list):\n            return\n        for dependency in self.event['check']['dependencies']:\n            if not str(dependency):\n                continue\n            dependency_split = tuple(dependency.split('/'))\n            if len(dependency_split) == 2:\n                client, check = dependency_split\n            else:\n                client = self.event['client']['name']\n                check = dependency_split[0]\n            if self.event_exists(client, check):\n                self.bail('check dependency event exists')",
    "docstring": "Determine whether a check has dependencies."
  },
  {
    "code": "def get_parameters(self, params, graph=None):\n        g = graph if graph is not None else self.tf_graph\n        with g.as_default():\n            with tf.Session() as self.tf_session:\n                self.tf_saver.restore(self.tf_session, self.model_path)\n                out = {}\n                for par in params:\n                    if type(params[par]) == list:\n                        for i, p in enumerate(params[par]):\n                            out[par + '-' + str(i+1)] = p.eval()\n                    else:\n                        out[par] = params[par].eval()\n                return out",
    "docstring": "Get the parameters of the model.\n\n        :param params: dictionary of keys (str names) and values (tensors).\n        :return: evaluated tensors in params"
  },
  {
    "code": "def txn_getAssociation(self, server_url, handle=None):\n        if handle is not None:\n            self.db_get_assoc(server_url, handle)\n        else:\n            self.db_get_assocs(server_url)\n        rows = self.cur.fetchall()\n        if len(rows) == 0:\n            return None\n        else:\n            associations = []\n            for values in rows:\n                values = list(values)\n                values[1] = self.blobDecode(values[1])\n                assoc = Association(*values)\n                if assoc.expiresIn == 0:\n                    self.txn_removeAssociation(server_url, assoc.handle)\n                else:\n                    associations.append((assoc.issued, assoc))\n            if associations:\n                associations.sort()\n                return associations[-1][1]\n            else:\n                return None",
    "docstring": "Get the most recent association that has been set for this\n        server URL and handle.\n\n        str -> NoneType or Association"
  },
  {
    "code": "def pysal_Moran(self, **kwargs):\n        if self.weights is None:\n            self.raster_weights(**kwargs)\n        rasterf = self.raster.flatten()\n        rasterf = rasterf[rasterf.mask==False]\n        self.Moran = pysal.Moran(rasterf, self.weights, **kwargs)",
    "docstring": "Compute Moran's I measure of global spatial autocorrelation for GeoRaster\n\n        Usage:\n        geo.pysal_Moran(permutations = 1000, rook=True)\n\n        arguments passed to raster_weights() and pysal.Moran\n        See help(gr.raster_weights), help(pysal.Moran) for options"
  },
  {
    "code": "async def _connect_sentinel(self, address, timeout, pools):\n        try:\n            with async_timeout(timeout, loop=self._loop):\n                pool = await create_pool(\n                    address, minsize=1, maxsize=2,\n                    parser=self._parser_class,\n                    loop=self._loop)\n            pools.append(pool)\n            return pool\n        except asyncio.TimeoutError as err:\n            sentinel_logger.debug(\n                \"Failed to connect to Sentinel(%r) within %ss timeout\",\n                address, timeout)\n            return err\n        except Exception as err:\n            sentinel_logger.debug(\n                \"Error connecting to Sentinel(%r): %r\", address, err)\n            return err",
    "docstring": "Try to connect to specified Sentinel returning either\n        connections pool or exception."
  },
  {
    "code": "def calculate_size(self, modules_per_line, number_of_lines, dpi=300):\n        width = 2 * self.quiet_zone + modules_per_line * self.module_width\n        height = 2.0 + self.module_height * number_of_lines\n        if self.font_size and self.text:\n            height += pt2mm(self.font_size) / 2 + self.text_distance\n        return int(mm2px(width, dpi)), int(mm2px(height, dpi))",
    "docstring": "Calculates the size of the barcode in pixel.\n\n        :parameters:\n            modules_per_line : Integer\n                Number of modules in one line.\n            number_of_lines : Integer\n                Number of lines of the barcode.\n            dpi : Integer\n                DPI to calculate.\n\n        :returns: Width and height of the barcode in pixel.\n        :rtype: Tuple"
  },
  {
    "code": "def menu_text(self, request=None):\n        source_field_name = settings.PAGE_FIELD_FOR_MENU_ITEM_TEXT\n        if(\n            source_field_name != 'menu_text' and\n            hasattr(self, source_field_name)\n        ):\n            return getattr(self, source_field_name)\n        return self.title",
    "docstring": "Return a string to use as link text when this page appears in\n        menus."
  },
  {
    "code": "def discover(package, cls_match_func):\n    matched_classes = set()\n    for _, module_name, _ in pkgutil.walk_packages(\n            package.__path__,\n            prefix=package.__name__ + '.',\n    ):\n        module = __import__(module_name, fromlist=[str('__trash')], level=0)\n        for _, imported_class in inspect.getmembers(module, inspect.isclass):\n            if imported_class.__module__ != module.__name__:\n                continue\n            if cls_match_func(imported_class):\n                matched_classes.add(imported_class)\n    return matched_classes",
    "docstring": "Returns a set of classes in the directory matched by cls_match_func\n\n    Args:\n        path - A Python package\n        cls_match_func - Function taking a class and returning true if the\n            class is to be included in the output."
  },
  {
    "code": "def addif(self, iname):\n        _runshell([brctlexe, 'addif', self.name, iname],\n            \"Could not add interface %s to %s.\" % (iname, self.name))",
    "docstring": "Add an interface to the bridge"
  },
  {
    "code": "def repeats(seq, size):\n    seq = str(seq)\n    n_mers = [seq[i:i + size] for i in range(len(seq) - size + 1)]\n    counted = Counter(n_mers)\n    found_repeats = [(key, value) for key, value in counted.iteritems() if\n                     value > 1]\n    return found_repeats",
    "docstring": "Count times that a sequence of a certain size is repeated.\n\n    :param seq: Input sequence.\n    :type seq: coral.DNA or coral.RNA\n    :param size: Size of the repeat to count.\n    :type size: int\n    :returns: Occurrences of repeats and how many\n    :rtype: tuple of the matched sequence and how many times it occurs"
  },
  {
    "code": "def make(target=\"all\", dir=\".\", **kwargs):\n    if not fs.isfile(fs.path(dir, \"Makefile\")):\n        raise NoMakefileError(\"No makefile in '{}'\".format(fs.abspath(dir)))\n    fs.cd(dir)\n    if \"timeout\" not in kwargs: kwargs[\"timeout\"] = 300\n    ret, out, err = system.run([\"make\", target], **kwargs)\n    fs.cdpop()\n    if ret > 0:\n        if re.search(_BAD_TARGET_RE, err):\n            raise NoTargetError(\"No rule for target '{}'\"\n                                .format(target))\n        else:\n            raise MakeError(\"Target '{}' failed\".format(target))\n        raise MakeError(\"Failed\")\n    return ret, out, err",
    "docstring": "Run make.\n\n    Arguments:\n\n        target (str, optional): Name of the target to build. Defaults\n          to \"all\".\n        dir (str, optional): Path to directory containing Makefile.\n        **kwargs (optional): Any additional arguments to be passed to\n          system.run().\n\n    Returns:\n\n        (int, str, str): The first element is the return code of the\n          make command. The second and third elements are the stdout\n          and stderr of the process.\n\n    Raises:\n\n        NoMakefileError: In case a Makefile is not found in the target\n          directory.\n        NoTargetError: In case the Makefile does not support the\n          requested target.\n        MakeError: In case the target rule fails."
  },
  {
    "code": "def certify_bool(value, required=True):\n    if certify_required(\n        value=value,\n        required=required,\n    ):\n        return\n    if not isinstance(value, bool):\n        raise CertifierTypeError(\n            message=\"expected bool, but value is of type {cls!r}\".format(\n                cls=value.__class__.__name__),\n            value=value,\n            required=required,\n        )",
    "docstring": "Certifier for boolean values.\n\n    :param value:\n        The value to be certified.\n    :param bool required:\n        Whether the value can be `None`.  Defaults to True.\n    :raises CertifierTypeError:\n        The type is invalid"
  },
  {
    "code": "def batch_iter(iterator, batch_size, return_func=None, padding=None):\n    for batch in zip_longest(*[iter(iterator)]*batch_size, fillvalue=padding):\n        gen = (thing for thing in batch if thing is not padding)\n        if return_func is None:\n            yield gen\n        else:\n            yield return_func(gen)",
    "docstring": "Break an iterable into batches of size batch_size\n\n    Note that `padding` should be set to something (anything) which is NOT a\n    valid member of the iterator. For example, None works for [0,1,2,...10], but\n    not for ['a', None, 'c', 'd'].\n\n    Parameters\n    ----------\n    iterator : iterable\n        A python object which is iterable.\n    batch_size : int\n        The size of batches you wish to produce from the iterator.\n    return_func : executable or None\n        Pass a function that takes a generator and returns an iterable (e.g.\n        `list` or `set`). If None, a generator will be returned.\n    padding : anything\n        This is used internally to ensure that the remainder of the list is\n        included. This MUST NOT be a valid element of the iterator.\n\n    Returns\n    -------\n    An iterator over lists or generators, depending on `return_lists`."
  },
  {
    "code": "def parse_peddy_sexcheck(handle: TextIO):\n    data = {}\n    samples = csv.DictReader(handle)\n    for sample in samples:\n        data[sample['sample_id']] = {\n            'predicted_sex': sample['predicted_sex'],\n            'het_ratio': float(sample['het_ratio']),\n            'error': True if sample['error'] == 'True' else False,\n        }\n    return data",
    "docstring": "Parse Peddy sexcheck output."
  },
  {
    "code": "def get_string_camel_patterns(cls, name, min_length=0):\n        patterns = []\n        abbreviations = list(set(cls._get_abbreviations(name, output_length=min_length)))\n        abbreviations.sort(key=len, reverse=True)\n        for abbr in abbreviations:\n            casing_permutations = list(set(cls._get_casing_permutations(abbr)))\n            casing_permutations.sort(key=lambda v: (v.upper(), v[0].islower(), len(v)))\n            permutations = [permutation for permutation in casing_permutations if\n                            cls.is_valid_camel(permutation) or len(permutation) <= 2]\n            if permutations:\n                patterns.append(permutations)\n        return patterns",
    "docstring": "Finds all permutations of possible camel casing of the given name\n\n        :param name: str, the name we need to get all possible permutations and abbreviations for\n        :param min_length: int, minimum length we want for abbreviations\n        :return: list(list(str)), list casing permutations of list of abbreviations"
  },
  {
    "code": "def ensure_dim(core, dim, dim_):\n    if dim is None:\n        dim = dim_\n    if not dim:\n        return core, 1\n    if dim_ == dim:\n        return core, int(dim)\n    if dim > dim_:\n        key_convert = lambda vari: vari[:dim_]\n    else:\n        key_convert = lambda vari: vari + (0,)*(dim-dim_)\n    new_core = {}\n    for key, val in core.items():\n        key_ = key_convert(key)\n        if key_ in new_core:\n            new_core[key_] += val\n        else:\n            new_core[key_] = val\n    return new_core, int(dim)",
    "docstring": "Ensure that dim is correct."
  },
  {
    "code": "def extern_call(self, context_handle, func, args_ptr, args_len):\n    c = self._ffi.from_handle(context_handle)\n    runnable = c.from_value(func[0])\n    args = tuple(c.from_value(arg[0]) for arg in self._ffi.unpack(args_ptr, args_len))\n    return self.call(c, runnable, args)",
    "docstring": "Given a callable, call it."
  },
  {
    "code": "def excluded(filename):\n    basename = os.path.basename(filename)\n    for pattern in options.exclude:\n        if fnmatch(basename, pattern):\n            return True",
    "docstring": "Check if options.exclude contains a pattern that matches filename."
  },
  {
    "code": "def free_vpcid_for_switch(vpc_id, nexus_ip):\n    LOG.debug(\"free_vpcid_for_switch() called\")\n    if vpc_id != 0:\n        update_vpc_entry([nexus_ip], vpc_id, False, False)",
    "docstring": "Free a vpc id for the given switch_ip."
  },
  {
    "code": "def wrap_as_node(self, func):\n        'wrap a function as a node'\n        name = self.get_name(func)\n        @wraps(func)\n        def wrapped(*args, **kwargs):\n            'wrapped version of func'\n            message = self.get_message_from_call(*args, **kwargs)\n            self.logger.info('calling \"%s\" with %r', name, message)\n            result = func(message)\n            if isinstance(result, GeneratorType):\n                results = [\n                    self.wrap_result(name, item)\n                    for item in result\n                    if item is not NoResult\n                ]\n                self.logger.debug(\n                    '%s returned generator yielding %d items', func, len(results)\n                )\n                [self.route(name, item) for item in results]\n                return tuple(results)\n            else:\n                if result is NoResult:\n                    return result\n                result = self.wrap_result(name, result)\n                self.logger.debug(\n                    '%s returned single value %s', func, result\n                )\n                self.route(name, result)\n                return result\n        return wrapped",
    "docstring": "wrap a function as a node"
  },
  {
    "code": "def read(database, table, key):\n    with database.snapshot() as snapshot:\n        result = snapshot.execute_sql('SELECT u.* FROM %s u WHERE u.id=\"%s\"' %\n                                      (table, key))\n        for row in result:\n            key = row[0]\n        for i in range(NUM_FIELD):\n            field = row[i + 1]",
    "docstring": "Does a single read operation."
  },
  {
    "code": "def humanize_timedelta(seconds):\n    hours, remainder = divmod(seconds, 3600)\n    days, hours = divmod(hours, 24)\n    minutes, seconds = divmod(remainder, 60)\n    if days:\n        result = '{}d'.format(days)\n        if hours:\n            result += ' {}h'.format(hours)\n        if minutes:\n            result += ' {}m'.format(minutes)\n        return result\n    if hours:\n        result = '{}h'.format(hours)\n        if minutes:\n            result += ' {}m'.format(minutes)\n        return result\n    if minutes:\n        result = '{}m'.format(minutes)\n        if seconds:\n            result += ' {}s'.format(seconds)\n        return result\n    return '{}s'.format(seconds)",
    "docstring": "Creates a string representation of timedelta."
  },
  {
    "code": "def drop_nodes(self) -> None:\n        t = time.time()\n        self.session.query(Node).delete()\n        self.session.commit()\n        log.info('dropped all nodes in %.2f seconds', time.time() - t)",
    "docstring": "Drop all nodes in the database."
  },
  {
    "code": "def pack(self):\n        try:\n            structs_ = get_structs_for_fields([self.fields[0]])\n        except (TypeError):\n            raise PackError(self)\n        if structs_ == []:\n            try:\n                structs_ = get_structs_for_fields([self.fields[0], self.fields[1]])\n            except (IndexError, TypeError):\n                raise PackError(self)\n        for struct_ in structs_:\n            try:\n                return struct_.pack(*self.fields)\n            except struct.error:\n                pass\n        raise PackError(self)",
    "docstring": "Return binary format of packet.\n\n           The returned string is the binary format of the packet with\n           stuffing and framing applied. It is ready to be sent to\n           the GPS."
  },
  {
    "code": "def pfadd(self, key, *elements):\n        return self._execute([b'PFADD', key] + list(elements), 1)",
    "docstring": "Adds all the element arguments to the HyperLogLog data structure\n        stored at the variable name specified as first argument.\n\n        As a side effect of this command the HyperLogLog internals may be\n        updated to reflect a different estimation of the number of unique items\n        added so far (the cardinality of the set).\n\n        If the approximated cardinality estimated by the HyperLogLog changed\n        after executing the command, :meth:`~tredis.RedisClient.pfadd` returns\n        ``1``, otherwise ``0`` is returned. The command automatically creates\n        an empty HyperLogLog structure (that is, a Redis String of a specified\n        length and with a given encoding) if the specified key does not exist.\n\n        To call the command without elements but just the variable name is\n        valid, this will result into no operation performed if the variable\n        already exists, or just the creation of the data structure if the key\n        does not exist (in the latter case ``1`` is returned).\n\n        For an introduction to HyperLogLog data structure check\n        :meth:`~tredis.RedisClient.pfcount`.\n\n        .. versionadded:: 0.2.0\n\n        .. note:: **Time complexity**: ``O(1)`` to add every element.\n\n        :param key: The key to add the elements to\n        :type key: :class:`str`, :class:`bytes`\n        :param elements: One or more elements to add\n        :type elements: :class:`str`, :class:`bytes`\n        :rtype: bool\n        :raises: :exc:`~tredis.exceptions.RedisError`"
  },
  {
    "code": "def labels():\n    datapath = path.join(path.dirname(path.realpath(__file__)), path.pardir)\n    datapath = path.join(datapath, '../gzoo_data', 'train_solution.csv')\n    return path.normpath(datapath)",
    "docstring": "Path to labels file"
  },
  {
    "code": "def get_child(parent, tag_name, root_or_cache, namespace):\n    if parent is None:\n        return None\n    ret = parent.find('.//' + namespace + tag_name)\n    if ret is None:\n        reference = parent.find('.//' + namespace + tag_name + '-REF')\n        if reference is not None:\n            if isinstance(root_or_cache, ArTree):\n                ret = get_cached_element_by_path(root_or_cache, reference.text)\n            else:\n                ret = get_element_by_path(root_or_cache, reference.text, namespace)\n    return ret",
    "docstring": "Get first sub-child or referenced sub-child with given name."
  },
  {
    "code": "def font(self):\n        defRPr = (\n            self._chartSpace\n                .get_or_add_txPr()\n                .p_lst[0]\n                .get_or_add_pPr()\n                .get_or_add_defRPr()\n        )\n        return Font(defRPr)",
    "docstring": "Font object controlling text format defaults for this chart."
  },
  {
    "code": "def _visit_body(self, node):\n        if (node.body and isinstance(node.body[0], ast.Expr) and\n                self.is_base_string(node.body[0].value)):\n            node.body[0].value.is_docstring = True\n            self.visit(node.body[0].value)\n        for sub_node in node.body:\n            self.visit(sub_node)",
    "docstring": "Traverse the body of the node manually.\n\n        If the first node is an expression which contains a string or bytes it\n        marks that as a docstring."
  },
  {
    "code": "def decipher_block (self, state):\n        if len(state) != 16:\n            Log.error(u\"Expecting block of 16\")\n        self._add_round_key(state, self._Nr)\n        for i in range(self._Nr - 1, 0, -1):\n            self._i_shift_rows(state)\n            self._i_sub_bytes(state)\n            self._add_round_key(state, i)\n            self._mix_columns(state, True)\n        self._i_shift_rows(state)\n        self._i_sub_bytes(state)\n        self._add_round_key(state, 0)\n        return state",
    "docstring": "Perform AES block decipher on input"
  },
  {
    "code": "def setup_shot_page(self, ):\n        self.shot_asset_treev.header().setResizeMode(QtGui.QHeaderView.ResizeToContents)\n        self.shot_task_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)",
    "docstring": "Create and set the model on the shot page\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def valuemap(f):\n    @wraps(f)\n    def wrapper(*args, **kwargs):\n        if 'value' in kwargs:\n            val = kwargs['value']\n            del kwargs['value']\n            _f = f(*args, **kwargs)\n            def valued_f(*args, **kwargs):\n                result = _f(*args, **kwargs)\n                s, obj, span = result\n                if callable(val):\n                    return PegreResult(s, val(obj), span)\n                else:\n                    return PegreResult(s, val, span)\n            return valued_f\n        else:\n            return f(*args, **kwargs)\n    return wrapper",
    "docstring": "Decorator to help PEG functions handle value conversions."
  },
  {
    "code": "def generichash_blake2b_update(state, data):\n    ensure(isinstance(state, Blake2State),\n           'State must be a Blake2State object',\n           raising=exc.TypeError)\n    ensure(isinstance(data, bytes),\n           'Input data must be a bytes sequence',\n           raising=exc.TypeError)\n    rc = lib.crypto_generichash_blake2b_update(state._statebuf,\n                                               data, len(data))\n    ensure(rc == 0, 'Unexpected failure',\n           raising=exc.RuntimeError)",
    "docstring": "Update the blake2b hash state\n\n    :param state: a initialized Blake2bState object as returned from\n                     :py:func:`.crypto_generichash_blake2b_init`\n    :type state: :py:class:`.Blake2State`\n    :param data:\n    :type data: bytes"
  },
  {
    "code": "def set_signal(self, signal, name):\n        r\n        signal = self._check_signal(signal)\n        self.signals[name] = signal",
    "docstring": "r\"\"\"Attach a signal to the graph.\n\n        Attached signals can be accessed (and modified or deleted) through the\n        :attr:`signals` dictionary.\n\n        Parameters\n        ----------\n        signal : array_like\n            A sequence that assigns a value to each vertex.\n            The value of the signal at vertex `i` is ``signal[i]``.\n        name : String\n            Name of the signal used as a key in the :attr:`signals` dictionary.\n\n        Examples\n        --------\n        >>> graph = graphs.Sensor(10)\n        >>> signal = np.arange(graph.n_vertices)\n        >>> graph.set_signal(signal, 'mysignal')\n        >>> graph.signals\n        {'mysignal': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])}"
  },
  {
    "code": "def update(self, params, ignore_set=False, overwrite=False):\n        log = logging.getLogger(__name__)\n        valid = {i[0] for i in self}\n        for key, value in params.items():\n            if not hasattr(self, key):\n                raise AttributeError(\"'{}' object has no attribute '{}'\".format(self.__class__.__name__, key))\n            if key not in valid:\n                message = \"'{}' object does not support item assignment on '{}'\"\n                raise AttributeError(message.format(self.__class__.__name__, key))\n            if key in self._already_set:\n                if ignore_set:\n                    log.debug('%s already set in config, skipping.', key)\n                    continue\n                if not overwrite:\n                    message = \"'{}' object does not support item re-assignment on '{}'\"\n                    raise AttributeError(message.format(self.__class__.__name__, key))\n            setattr(self, key, value)\n            self._already_set.add(key)",
    "docstring": "Set instance values from dictionary.\n\n        :param dict params: Click context params.\n        :param bool ignore_set: Skip already-set values instead of raising AttributeError.\n        :param bool overwrite: Allow overwriting already-set values."
  },
  {
    "code": "def submit(self, q, context=None, task_name=\"casjobs\", estimate=30):\n        if not context:\n            context = self.context\n        params = {\"qry\": q, \"context\": context, \"taskname\": task_name,\n                  \"estimate\": estimate}\n        r = self._send_request(\"SubmitJob\", params=params)\n        job_id = int(self._parse_single(r.text, \"long\"))\n        return job_id",
    "docstring": "Submit a job to CasJobs.\n\n        ## Arguments\n\n        * `q` (str): The SQL query.\n\n        ## Keyword Arguments\n\n        * `context` (str): Casjobs context used for this query.\n        * `task_name` (str): The task name.\n        * `estimate` (int): Estimate of the time this job will take (in minutes).\n\n        ## Returns\n\n        * `job_id` (int): The submission ID."
  },
  {
    "code": "def getMechanismName(self):\n        if self._server_side:\n            mech = self._authenticator.current_mech\n            return mech.getMechanismName() if mech else None\n        else:\n            return getattr(self._authenticator, 'authMech', None)",
    "docstring": "Return the authentication mechanism name."
  },
  {
    "code": "def tag_add(package, tag, pkghash):\n    team, owner, pkg = parse_package(package)\n    session = _get_session(team)\n    session.put(\n        \"{url}/api/tag/{owner}/{pkg}/{tag}\".format(\n            url=get_registry_url(team),\n            owner=owner,\n            pkg=pkg,\n            tag=tag\n        ),\n        data=json.dumps(dict(\n            hash=_match_hash(package, pkghash)\n        ))\n    )",
    "docstring": "Add a new tag for a given package hash.\n\n    Unlike versions, tags can have an arbitrary format, and can be modified\n    and deleted.\n\n    When a package is pushed, it gets the \"latest\" tag."
  },
  {
    "code": "def check_ssl():\n    try:\n        import ssl\n    except:\n        log.warning('Error importing SSL module', stack_info=True)\n        print(SSL_ERROR_MESSAGE)\n        sys.exit(1)\n    else:\n        log.info('SSL module is available')\n        return ssl",
    "docstring": "Attempts to import SSL or raises an exception."
  },
  {
    "code": "def _jobStoreClasses(self):\n        jobStoreClassNames = (\n            \"toil.jobStores.azureJobStore.AzureJobStore\",\n            \"toil.jobStores.fileJobStore.FileJobStore\",\n            \"toil.jobStores.googleJobStore.GoogleJobStore\",\n            \"toil.jobStores.aws.jobStore.AWSJobStore\",\n            \"toil.jobStores.abstractJobStore.JobStoreSupport\")\n        jobStoreClasses = []\n        for className in jobStoreClassNames:\n            moduleName, className = className.rsplit('.', 1)\n            from importlib import import_module\n            try:\n                module = import_module(moduleName)\n            except ImportError:\n                logger.debug(\"Unable to import '%s' as is expected if the corresponding extra was \"\n                             \"omitted at installation time.\", moduleName)\n            else:\n                jobStoreClass = getattr(module, className)\n                jobStoreClasses.append(jobStoreClass)\n        return jobStoreClasses",
    "docstring": "A list of concrete AbstractJobStore implementations whose dependencies are installed.\n\n        :rtype: list[AbstractJobStore]"
  },
  {
    "code": "def gen_all_voltages_for_injections(self, injections_raw):\n        injections = injections_raw.astype(int)\n        N = self.nr_electrodes\n        all_quadpoles = []\n        for idipole in injections:\n            Icurrent = np.sort(idipole) - 1\n            velecs = list(range(1, N + 1))\n            del(velecs[Icurrent[1]])\n            del(velecs[Icurrent[0]])\n            voltages = itertools.permutations(velecs, 2)\n            for voltage in voltages:\n                all_quadpoles.append(\n                    (idipole[0], idipole[1], voltage[0], voltage[1])\n                )\n        configs_unsorted = np.array(all_quadpoles)\n        configs_sorted = np.hstack((\n            np.sort(configs_unsorted[:, 0:2], axis=1),\n            np.sort(configs_unsorted[:, 2:4], axis=1),\n        ))\n        configs = self.remove_duplicates(configs_sorted)\n        self.add_to_configs(configs)\n        self.remove_duplicates()\n        return configs",
    "docstring": "For a given set of current injections AB, generate all possible\n        unique potential measurements.\n\n        After Noel and Xu, 1991, for N electrodes, the number of possible\n        voltage dipoles for a given current dipole is :math:`(N - 2)(N - 3) /\n        2`. This includes normal and reciprocal measurements.\n\n        If current dipoles are generated with\n        ConfigManager.gen_all_current_dipoles(), then :math:`N \\cdot (N - 1) /\n        2` current dipoles are generated. Thus, this function will produce\n        :math:`(N - 1)(N - 2)(N - 3) / 4` four-point configurations ABMN, half\n        of which are reciprocals (Noel and Xu, 1991).\n\n        All generated measurements are added to the instance.\n\n        Use ConfigManager.split_into_normal_and_reciprocal() to split the\n        configurations into normal and reciprocal measurements.\n\n        Parameters\n        ----------\n        injections: numpy.ndarray\n            Kx2 array holding K current injection dipoles A-B\n\n        Returns\n        -------\n        configs: numpy.ndarray\n            Nax4 array holding all possible measurement configurations"
  },
  {
    "code": "def prepare_inventory(self):\n        if self.inventory is None:\n            self.inventory  = os.path.join(self.private_data_dir, \"inventory\")",
    "docstring": "Prepares the inventory default under ``private_data_dir`` if it's not overridden by the constructor."
  },
  {
    "code": "def write(self, value):\n        if self.capacity > 0 and self.strategy == 0:\n            len_value = len(value)\n            if len_value >= self.capacity:\n                needs_new_strategy = True\n            else:\n                self.seek(0, 2)\n                needs_new_strategy = \\\n                    (self.tell() + len_value) >= self.capacity\n            if needs_new_strategy:\n                self.makeTempFile()\n        if not isinstance(value, six.binary_type):\n            value = value.encode('utf-8')\n        self._delegate.write(value)",
    "docstring": "If capacity != -1 and length of file > capacity it is time to switch"
  },
  {
    "code": "def add(self, value):\n\t\tindex = len(self.__history)\n\t\tself.__history.append(value)\n\t\treturn index",
    "docstring": "Add new record to history. Record will be added to the end\n\n\t\t:param value: new record\n\t\t:return: int record position in history"
  },
  {
    "code": "def argument_request_user(obj, func_name):\n    func = getattr(obj, func_name)\n    request = threadlocals.request()\n    if request:\n        return func(request.user)",
    "docstring": "Pass request.user as an argument to the given function call."
  },
  {
    "code": "async def get_update_info(self, from_network=True) -> SoftwareUpdateInfo:\n        if from_network:\n            from_network = \"true\"\n        else:\n            from_network = \"false\"\n        info = await self.services[\"system\"][\"getSWUpdateInfo\"](network=from_network)\n        return SoftwareUpdateInfo.make(**info)",
    "docstring": "Get information about updates."
  },
  {
    "code": "def display_information_message_bar(\n        title=None,\n        message=None,\n        more_details=None,\n        button_text=tr('Show details ...'),\n        duration=8,\n        iface_object=iface):\n    iface_object.messageBar().clearWidgets()\n    widget = iface_object.messageBar().createMessage(title, message)\n    if more_details:\n        button = QPushButton(widget)\n        button.setText(button_text)\n        button.pressed.connect(\n            lambda: display_information_message_box(\n                title=title, message=more_details))\n        widget.layout().addWidget(button)\n    iface_object.messageBar().pushWidget(widget, Qgis.Info, duration)",
    "docstring": "Display an information message bar.\n\n    :param iface_object: The QGIS IFace instance. Note that we cannot\n        use qgis.utils.iface since it is not available in our\n        test environment.\n    :type iface_object: QgisInterface\n\n    :param title: The title of the message bar.\n    :type title: basestring\n\n    :param message: The message inside the message bar.\n    :type message: basestring\n\n    :param more_details: The message inside the 'Show details' button.\n    :type more_details: basestring\n\n    :param button_text: The text of the button if 'more_details' is not empty.\n    :type button_text: basestring\n\n    :param duration: The duration for the display, default is 8 seconds.\n    :type duration: int"
  },
  {
    "code": "def close(self):\n        if self._server is None:\n            raise RuntimeError('Server is not started')\n        self._server.close()\n        for handler in self._handlers:\n            handler.close()",
    "docstring": "Stops accepting new connections, cancels all currently running\n        requests. Request handlers are able to handle `CancelledError` and\n        exit properly."
  },
  {
    "code": "def formvalue (form, key):\n    field = form.get(key)\n    if isinstance(field, list):\n        field = field[0]\n    return field",
    "docstring": "Get value with given key from WSGI form."
  },
  {
    "code": "def newest(cls, session):\n    media_type = cls.__name__.lower()\n    p = session.session.get(u'http://myanimelist.net/' + media_type + '.php?o=9&c[]=a&c[]=d&cv=2&w=1').text\n    soup = utilities.get_clean_dom(p)\n    latest_entry = soup.find(u\"div\", {u\"class\": u\"hoverinfo\"})\n    if not latest_entry:\n      raise MalformedMediaPageError(0, p, u\"No media entries found on recently-added page\")\n    latest_id = int(latest_entry[u'rel'][1:])\n    return getattr(session, media_type)(latest_id)",
    "docstring": "Fetches the latest media added to MAL.\n\n    :type session: :class:`myanimelist.session.Session`\n    :param session: A valid MAL session\n\n    :rtype: :class:`.Media`\n    :return: the newest media on MAL\n\n    :raises: :class:`.MalformedMediaPageError`"
  },
  {
    "code": "def unsubscribe(self, message, handler):\n        with self._lock:\n            self._subscribers[message].remove(WeakCallable(handler))",
    "docstring": "Removes handler from message listeners.\n\n        :param str message:\n            Name of message to unsubscribe handler from.\n\n        :param callable handler:\n            Callable that should be removed as handler for `message`."
  },
  {
    "code": "def shutdown(url=None):\n    if url is None:\n        for host in util.hosts.values():\n            host.shutdown()\n        global core_type\n        core_type = None\n    else:\n        host = util.hosts[url]\n        host.shutdown()",
    "docstring": "Stops the Host passed by parameter or all of them if none is\n    specified, stopping at the same time all its actors.\n    Should be called at the end of its usage, to finish correctly\n    all the connections and threads."
  },
  {
    "code": "def get_schema(self, schema_id):\n        res = requests.get(self._url('/schemas/ids/{}', schema_id))\n        raise_if_failed(res)\n        return json.loads(res.json()['schema'])",
    "docstring": "Retrieves the schema with the given schema_id from the registry\n        and returns it as a `dict`."
  },
  {
    "code": "def html_parts(input_string, source_path=None, destination_path=None,\n               input_encoding='unicode', doctitle=1, initial_header_level=1):\n    overrides = {\n        'input_encoding': input_encoding,\n        'doctitle_xform': doctitle,\n        'initial_header_level': initial_header_level,\n        'report_level': 5\n    }\n    parts = core.publish_parts(\n        source=input_string, source_path=source_path,\n        destination_path=destination_path,\n        writer_name='html', settings_overrides=overrides)\n    return parts",
    "docstring": "Given an input string, returns a dictionary of HTML document parts.\n\n    Dictionary keys are the names of parts, and values are Unicode strings;\n    encoding is up to the client.\n\n    Parameters:\n\n    - `input_string`: A multi-line text string; required.\n    - `source_path`: Path to the source file or object.  Optional, but useful\n      for diagnostic output (system messages).\n    - `destination_path`: Path to the file or object which will receive the\n      output; optional.  Used for determining relative paths (stylesheets,\n      source links, etc.).\n    - `input_encoding`: The encoding of `input_string`.  If it is an encoded\n      8-bit string, provide the correct encoding.  If it is a Unicode string,\n      use \"unicode\", the default.\n    - `doctitle`: Disable the promotion of a lone top-level section title to\n      document title (and subsequent section title to document subtitle\n      promotion); enabled by default.\n    - `initial_header_level`: The initial level for header elements (e.g. 1\n      for \"<h1>\")."
  },
  {
    "code": "def create_serving_logger() -> Logger:\n    logger = getLogger('quart.serving')\n    if logger.level == NOTSET:\n        logger.setLevel(INFO)\n    logger.addHandler(serving_handler)\n    return logger",
    "docstring": "Create a logger for serving.\n\n    This creates a logger named quart.serving."
  },
  {
    "code": "def iterate_with_exp_backoff(base_iter,\n                             max_num_tries=6,\n                             max_backoff=300.0,\n                             start_backoff=4.0,\n                             backoff_multiplier=2.0,\n                             frac_random_backoff=0.25):\n  try_number = 0\n  if hasattr(base_iter, '__iter__'):\n    base_iter = iter(base_iter)\n  while True:\n    try:\n      yield next(base_iter)\n      try_number = 0\n    except StopIteration:\n      break\n    except TooManyRequests as e:\n      logging.warning('TooManyRequests error: %s', tb.format_exc())\n      if try_number >= max_num_tries:\n        logging.error('Number of tries exceeded, too many requests: %s', e)\n        raise\n      sleep_time = start_backoff * math.pow(backoff_multiplier, try_number)\n      sleep_time *= (1.0 + frac_random_backoff * random.random())\n      sleep_time = min(sleep_time, max_backoff)\n      logging.warning('Too many requests error, '\n                      'retrying with exponential backoff %.3f', sleep_time)\n      time.sleep(sleep_time)\n      try_number += 1",
    "docstring": "Iterate with exponential backoff on failures.\n\n  Useful to wrap results of datastore Query.fetch to avoid 429 error.\n\n  Args:\n    base_iter: basic iterator of generator object\n    max_num_tries: maximum number of tries for each request\n    max_backoff: maximum backoff, in seconds\n    start_backoff: initial value of backoff\n    backoff_multiplier: backoff multiplier\n    frac_random_backoff: fraction of the value of random part of the backoff\n\n  Yields:\n    values of yielded by base iterator"
  },
  {
    "code": "def setitem(self, key, value):\n        with self.lock:\n            self.tbl[key] = value",
    "docstring": "Maps dictionary keys to values for assignment.  Called for\n        dictionary style access with assignment."
  },
  {
    "code": "def _is_word_type(token_type):\n    return token_type in [TokenType.Word,\n                          TokenType.QuotedLiteral,\n                          TokenType.UnquotedLiteral,\n                          TokenType.Number,\n                          TokenType.Deref]",
    "docstring": "Return true if this is a word-type token."
  },
  {
    "code": "def load_patt(filename):\n    with open(filename) as f: \n        lines = f.readlines()\n        lst = lines[0].split(',')\n        patt = np.zeros([int(lst[0]), int(lst[1])],\n                        dtype=np.complex128)\n        lines.pop(0)\n        for line in lines:\n            lst = line.split(',')\n            n = int(lst[0])\n            m = int(lst[1])\n            re = float(lst[2])\n            im = float(lst[3])\n            patt[n, m] = re + 1j * im\n    return sp.ScalarPatternUniform(patt, doublesphere=False)",
    "docstring": "Loads a file that was saved with the save_patt routine."
  },
  {
    "code": "def consume_value(self, ctx, opts):\n        value = click.Option.consume_value(self, ctx, opts)\n        if not value:\n            gandi = ctx.obj\n            value = gandi.get(self.name)\n            if value is not None:\n                self.display_value(ctx, value)\n            else:\n                if self.default is None and self.required:\n                    metavar = ''\n                    if self.type.name not in ['integer', 'text']:\n                        metavar = self.make_metavar()\n                    prompt = '%s %s' % (self.help, metavar)\n                    gandi.echo(prompt)\n        return value",
    "docstring": "Retrieve default value and display it when prompt is disabled."
  },
  {
    "code": "def start_capture(self):\n        previous_map_tool = self.canvas.mapTool()\n        if previous_map_tool != self.tool:\n            self.previous_map_tool = previous_map_tool\n        self.canvas.setMapTool(self.tool)\n        self.hide()",
    "docstring": "Start capturing the rectangle."
  },
  {
    "code": "def to_spans(self):\n        \"Convert the tree to a set of nonterms and spans.\"\n        s = set()\n        self._convert_to_spans(self.tree, 1, s)\n        return s",
    "docstring": "Convert the tree to a set of nonterms and spans."
  },
  {
    "code": "def _get_erred_shared_settings_module(self):\n        result_module = modules.LinkList(title=_('Shared provider settings in erred state'))\n        result_module.template = 'admin/dashboard/erred_link_list.html'\n        erred_state = structure_models.SharedServiceSettings.States.ERRED\n        queryset = structure_models.SharedServiceSettings.objects\n        settings_in_erred_state = queryset.filter(state=erred_state).count()\n        if settings_in_erred_state:\n            result_module.title = '%s (%s)' % (result_module.title, settings_in_erred_state)\n            for service_settings in queryset.filter(state=erred_state).iterator():\n                module_child = self._get_link_to_instance(service_settings)\n                module_child['error'] = service_settings.error_message\n                result_module.children.append(module_child)\n        else:\n            result_module.pre_content = _('Nothing found.')\n        return result_module",
    "docstring": "Returns a LinkList based module which contains link to shared service setting instances in ERRED state."
  },
  {
    "code": "def grant(self, auth, resource, permissions, ttl=None, defer=False):\n        args = [resource, permissions]\n        if ttl is not None:\n            args.append({\"ttl\": ttl})\n        return self._call('grant', auth, args, defer)",
    "docstring": "Grant resources with specific permissions and return a token.\n\n        Args:\n            auth: <cik>\n            resource: Alias or ID of resource.\n            permissions: permissions of resources.\n            ttl: Time To Live."
  },
  {
    "code": "def wait(self, timeout=None):\n    if not self.__running:\n      raise RuntimeError(\"ThreadPool ain't running\")\n    self.__queue.wait(timeout)",
    "docstring": "Block until all jobs in the ThreadPool are finished. Beware that this can\n    make the program run into a deadlock if another thread adds new jobs to the\n    pool!\n\n    # Raises\n    Timeout: If the timeout is exceeded."
  },
  {
    "code": "def route(self, origin, message):\n        self.resolve_node_modules()\n        if not self.routing_enabled:\n            return\n        subs = self.routes.get(origin, set())\n        for destination in subs:\n            self.logger.debug('routing \"%s\" -> \"%s\"', origin, destination)\n            self.dispatch(origin, destination, message)",
    "docstring": "\\\n        Using the routing dictionary, dispatch a message to all subscribers\n\n        :param origin: name of the origin node\n        :type origin: :py:class:`str`\n        :param message: message to dispatch\n        :type message: :py:class:`emit.message.Message` or subclass"
  },
  {
    "code": "def make_vertical_bar(percentage, width=1):\n    bar = ' _▁▂▃▄▅▆▇█'\n    percentage //= 10\n    percentage = int(percentage)\n    if percentage < 0:\n        output = bar[0]\n    elif percentage >= len(bar):\n        output = bar[-1]\n    else:\n        output = bar[percentage]\n    return output * width",
    "docstring": "Draws a vertical bar made of unicode characters.\n\n    :param value: A value between 0 and 100\n    :param width: How many characters wide the bar should be.\n    :returns: Bar as a String"
  },
  {
    "code": "def getfile(self, section, option, raw=False, vars=None, fallback=\"\", validate=False):\n        v = self.get(section, option, raw=raw, vars=vars, fallback=fallback)\n        v = self._convert_to_path(v)\n        return v if not validate or os.path.isfile(v) else fallback",
    "docstring": "A convenience method which coerces the option in the specified section to a file."
  },
  {
    "code": "def css(request):\n    if 'grappelli' in settings.INSTALLED_APPS:\n        margin_left = 0\n    elif VERSION[:2] <= (1, 8):\n        margin_left = 110\n    else:\n        margin_left = 170\n    responsive_admin = VERSION[:2] >= (2, 0)\n    return HttpResponse(render_to_string('tinymce/tinymce4.css',\n                                         context={\n                                             'margin_left': margin_left,\n                                             'responsive_admin': responsive_admin\n                                         },\n                                         request=request),\n                        content_type='text/css; charset=utf-8')",
    "docstring": "Custom CSS for TinyMCE 4 widget\n\n    By default it fixes widget's position in Django Admin\n\n    :param request: Django http request\n    :type request: django.http.request.HttpRequest\n    :return: Django http response with CSS file for TinyMCE 4\n    :rtype: django.http.HttpResponse"
  },
  {
    "code": "def _get_generator(self, name):\n        for ep in pkg_resources.iter_entry_points(self.group, name=None):\n            if ep.name == name:\n                generator = ep.load()\n                return generator",
    "docstring": "Load the generator plugin and execute its lifecycle.\n\n        :param dist: distribution"
  },
  {
    "code": "def generate_random_string(template_dict, key='start'):\n    data = template_dict.get(key)\n    result = random.choice(data)\n    for match in token_regex.findall(result):\n        word = generate_random_string(template_dict, match) or match\n        result = result.replace('{{{0}}}'.format(match), word)\n    return result",
    "docstring": "Generates a random excuse from a simple template dict.\n\n    Based off of drow's generator.js (public domain).\n    Grok it here: http://donjon.bin.sh/code/random/generator.js\n\n    Args:\n        template_dict: Dict with template strings.\n        key: String with the starting index for the dict. (Default: 'start')\n\n    Returns:\n        Generated string."
  },
  {
    "code": "def SetConfiguredUsers(self, users):\n    prefix = self.logger.name + '-'\n    with tempfile.NamedTemporaryFile(\n        mode='w', prefix=prefix, delete=True) as updated_users:\n      updated_users_file = updated_users.name\n      for user in users:\n        updated_users.write(user + '\\n')\n      updated_users.flush()\n      if not os.path.exists(self.google_users_dir):\n        os.makedirs(self.google_users_dir)\n      shutil.copy(updated_users_file, self.google_users_file)\n    file_utils.SetPermissions(self.google_users_file, mode=0o600, uid=0, gid=0)",
    "docstring": "Set the list of configured Google user accounts.\n\n    Args:\n      users: list, the username strings of the Linux accounts."
  },
  {
    "code": "def copy(self) -> \"Feed\":\n        other = Feed(dist_units=self.dist_units)\n        for key in set(cs.FEED_ATTRS) - set([\"dist_units\"]):\n            value = getattr(self, key)\n            if isinstance(value, pd.DataFrame):\n                value = value.copy()\n            elif isinstance(value, pd.core.groupby.DataFrameGroupBy):\n                value = deepcopy(value)\n            setattr(other, key, value)\n        return other",
    "docstring": "Return a copy of this feed, that is, a feed with all the same\n        attributes."
  },
  {
    "code": "def drop(self, async_=False, if_exists=False, **kw):\n        async_ = kw.get('async', async_)\n        return self.parent.delete(self, async_=async_, if_exists=if_exists)",
    "docstring": "Drop this table.\n\n        :param async_: run asynchronously if True\n        :return: None"
  },
  {
    "code": "def wait_until_not_present(self, locator, timeout=None):\n        timeout = timeout if timeout is not None else self.timeout\n        this = self\n        def wait():\n            return WebDriverWait(self.driver, timeout).until(lambda d: not this.is_present(locator))\n        return self.execute_and_handle_webdriver_exceptions(\n            wait, timeout, locator, 'Timeout waiting for element not to be present')",
    "docstring": "Waits for an element to no longer be present\n\n        @type locator:  webdriverwrapper.support.locator.Locator\n        @param locator: the locator or css string to search for the element\n        @type timeout:  int\n        @param timeout:  the maximum number of seconds the driver will wait before timing out\n\n        @rtype:                 webdriverwrapper.WebElementWrapper\n        @return:                Returns the element found"
  },
  {
    "code": "def parse(cls, string):\n        match = re.match(r'^(?P<name>[A-Za-z0-9\\.\\-_]+)\\s+' +\n                         '(?P<value>[0-9\\.]+)\\s+' +\n                         '(?P<timestamp>[0-9\\.]+)(\\n?)$',\n                         string)\n        try:\n            groups = match.groupdict()\n            return Metric(groups['name'],\n                          groups['value'],\n                          float(groups['timestamp']))\n        except:\n            raise DiamondException(\n                \"Metric could not be parsed from string: %s.\" % string)",
    "docstring": "Parse a string and create a metric"
  },
  {
    "code": "def match(fullname1, fullname2, strictness='default', options=None):\n    if options is not None:\n        settings = deepcopy(SETTINGS[strictness])\n        deep_update_dict(settings, options)\n    else:\n        settings = SETTINGS[strictness]\n    name1 = Name(fullname1)\n    name2 = Name(fullname2)\n    return name1.deep_compare(name2, settings)",
    "docstring": "Takes two names and returns true if they describe the same person.\n\n    :param string fullname1: first human name\n    :param string fullname2: second human name\n    :param string strictness: strictness settings to use\n    :param dict options: custom strictness settings updates\n    :return bool: the names match"
  },
  {
    "code": "def _lookup_nexus_bindings(query_type, session=None, **bfilter):\n    if session is None:\n        session = bc.get_reader_session()\n    query_method = getattr(session.query(\n        nexus_models_v2.NexusPortBinding).filter_by(**bfilter), query_type)\n    try:\n        bindings = query_method()\n        if bindings:\n            return bindings\n    except sa_exc.NoResultFound:\n        pass\n    raise c_exc.NexusPortBindingNotFound(**bfilter)",
    "docstring": "Look up 'query_type' Nexus bindings matching the filter.\n\n    :param query_type: 'all', 'one' or 'first'\n    :param session: db session\n    :param bfilter: filter for bindings query\n    :returns: bindings if query gave a result, else\n             raise NexusPortBindingNotFound."
  },
  {
    "code": "def _write_string(self, string, pos_x, pos_y, height, color, bold=False, align_right=False, depth=0.):\n        stroke_width = height / 8.\n        if bold:\n            stroke_width = height / 5.\n        color.set()\n        self._set_closest_stroke_width(stroke_width)\n        glMatrixMode(GL_MODELVIEW)\n        glPushMatrix()\n        pos_y -= height\n        if not align_right:\n            glTranslatef(pos_x, pos_y, depth)\n        else:\n            width = self._string_width(string, height)\n            glTranslatef(pos_x - width, pos_y, depth)\n        font_height = 119.5\n        scale_factor = height / font_height\n        glScalef(scale_factor, scale_factor, scale_factor)\n        for c in string:\n            glutStrokeCharacter(GLUT_STROKE_ROMAN, ord(c))\n        glPopMatrix()",
    "docstring": "Write a string\n\n        Writes a string with a simple OpenGL method in the given size at the given position.\n\n        :param string: The string to draw\n        :param pos_x: x starting position\n        :param pos_y: y starting position\n        :param height: desired height\n        :param bold: flag whether to use a bold font\n        :param depth: the Z layer"
  },
  {
    "code": "def basename(path):\n    base_path = path.strip(SEP)\n    sep_ind = base_path.rfind(SEP)\n    if sep_ind < 0:\n        return path\n    return base_path[sep_ind + 1:]",
    "docstring": "Rightmost part of path after separator."
  },
  {
    "code": "def findOverlap(x_mins, y_mins, min_distance):\n    n = len(x_mins)\n    idex = []\n    for i in range(n):\n        if i == 0:\n            pass\n        else:\n            for j in range(0, i):\n                if (abs(x_mins[i] - x_mins[j]) < min_distance and abs(y_mins[i] - y_mins[j]) < min_distance):\n                    idex.append(i)\n                    break\n    x_mins = np.delete(x_mins, idex, axis=0)\n    y_mins = np.delete(y_mins, idex, axis=0)\n    return x_mins, y_mins",
    "docstring": "finds overlapping solutions, deletes multiples and deletes non-solutions and if it is not a solution, deleted as well"
  },
  {
    "code": "def details_dict(obj, existing, ignore_missing, opt):\n    existing = dict_unicodeize(existing)\n    obj = dict_unicodeize(obj)\n    for ex_k, ex_v in iteritems(existing):\n        new_value = normalize_val(obj.get(ex_k))\n        og_value = normalize_val(ex_v)\n        if ex_k in obj and og_value != new_value:\n            print(maybe_colored(\"-- %s: %s\" % (ex_k, og_value),\n                                'red', opt))\n            print(maybe_colored(\"++ %s: %s\" % (ex_k, new_value),\n                                'green', opt))\n        if (not ignore_missing) and (ex_k not in obj):\n            print(maybe_colored(\"-- %s: %s\" % (ex_k, og_value),\n                                'red', opt))\n    for ob_k, ob_v in iteritems(obj):\n        val = normalize_val(ob_v)\n        if ob_k not in existing:\n            print(maybe_colored(\"++ %s: %s\" % (ob_k, val),\n                                'green', opt))\n    return",
    "docstring": "Output the changes, if any, for a dict"
  },
  {
    "code": "def get_corrected_commands(self, command):\n        new_commands = self.get_new_command(command)\n        if not isinstance(new_commands, list):\n            new_commands = (new_commands,)\n        for n, new_command in enumerate(new_commands):\n            yield CorrectedCommand(script=new_command,\n                                   side_effect=self.side_effect,\n                                   priority=(n + 1) * self.priority)",
    "docstring": "Returns generator with corrected commands.\n\n        :type command: Command\n        :rtype: Iterable[CorrectedCommand]"
  },
  {
    "code": "def resolve(self, function):\n        filename = self.get_filename()\n        if not filename:\n            return None\n        try:\n            hlib    = win32.GetModuleHandle(filename)\n            address = win32.GetProcAddress(hlib, function)\n        except WindowsError:\n            try:\n                hlib = win32.LoadLibraryEx(filename,\n                                           win32.DONT_RESOLVE_DLL_REFERENCES)\n                try:\n                    address = win32.GetProcAddress(hlib, function)\n                finally:\n                    win32.FreeLibrary(hlib)\n            except WindowsError:\n                return None\n        if address in (None, 0):\n            return None\n        return address - hlib + self.lpBaseOfDll",
    "docstring": "Resolves a function exported by this module.\n\n        @type  function: str or int\n        @param function:\n            str: Name of the function.\n            int: Ordinal of the function.\n\n        @rtype:  int\n        @return: Memory address of the exported function in the process.\n            Returns None on error."
  },
  {
    "code": "def run_validation(options):\n    if options.files == sys.stdin:\n        results = validate(options.files, options)\n        return [FileValidationResults(is_valid=results.is_valid,\n                                      filepath='stdin',\n                                      object_results=results)]\n    files = get_json_files(options.files, options.recursive)\n    results = [validate_file(fn, options) for fn in files]\n    return results",
    "docstring": "Validate files based on command line options.\n\n    Args:\n        options: An instance of ``ValidationOptions`` containing options for\n            this validation run."
  },
  {
    "code": "def request_quotes(tickers_list, selected_columns=['*']):\n    __validate_list(tickers_list)\n    __validate_list(selected_columns)\n    query = 'select {cols} from yahoo.finance.quotes where symbol in ({vals})'\n    query = query.format(\n        cols=', '.join(selected_columns),\n        vals=', '.join('\"{0}\"'.format(s) for s in tickers_list)\n    )\n    response = __yahoo_request(query)\n    if not response:\n        raise RequestError('Unable to process the request. Check if the ' +\n                           'columns selected are valid.')\n    if not type(response['quote']) is list:\n        return [response['quote']]\n    return response['quote']",
    "docstring": "Request Yahoo Finance recent quotes.\n\n    Returns quotes information from YQL. The columns to be requested are\n    listed at selected_columns. Check `here <http://goo.gl/8AROUD>`_ for more\n    information on YQL.\n\n    >>> request_quotes(['AAPL'], ['Name', 'PreviousClose'])\n    {\n        'PreviousClose': '95.60',\n        'Name': 'Apple Inc.'\n    }\n\n    :param table: Table name.\n    :type table: string\n    :param tickers_list: List of tickers that will be returned.\n    :type tickers_list: list of strings\n    :param selected_columns: List of columns to be returned, defaults to ['*']\n    :type selected_columns: list of strings, optional\n    :returns: Requested quotes.\n    :rtype: json\n    :raises: TypeError, TypeError"
  },
  {
    "code": "def minimize(self, tolerance=None, max_iterations=None):\n        if tolerance is None:\n            tolerance = self.minimization_tolerance\n        if max_iterations is None:\n            max_iterations = self.minimization_max_iterations\n        self.simulation.minimizeEnergy(tolerance * u.kilojoules_per_mole, max_iterations)",
    "docstring": "Minimize energy of the system until meeting `tolerance` or\n        performing `max_iterations`."
  },
  {
    "code": "def login_required(http_method_handler):\n    @wraps(http_method_handler)\n    def secure_http_method_handler(self, *args, **kwargs):\n        if not self.__provider_config__.authentication:\n            _message = \"Service available to authenticated users only, no auth context provider set in handler\"\n            authentication_error = prestans.exception.AuthenticationError(_message)\n            authentication_error.request = self.request\n            raise authentication_error\n        if not self.__provider_config__.authentication.is_authenticated_user():\n            authentication_error = prestans.exception.AuthenticationError()\n            authentication_error.request = self.request\n            raise authentication_error\n        http_method_handler(self, *args, **kwargs)\n    return secure_http_method_handler",
    "docstring": "provides a decorator for RESTRequestHandler methods to check for authenticated users\n\n    RESTRequestHandler subclass must have a auth_context instance, refer to prestans.auth\n    for the parent class definition.\n\n    If decorator is used and no auth_context is provided the client will be denied access.\n\n    Handler will return a 401 Unauthorized if the user is not logged in, the service does\n    not redirect to login handler page, this is the client's responsibility.\n\n    auth_context_handler instance provides a message called get_current_user, use this\n    to obtain a reference to an authenticated user profile.\n\n    If all goes well, the original handler definition is executed."
  },
  {
    "code": "def close(self):\n        if self.mdr is None:\n            return\n        exc = (None, None, None)\n        try:\n            self.cursor.close()\n        except:\n            exc = sys.exc_info()\n        try:\n            if self.mdr.__exit__(*exc):\n                exc = (None, None, None)\n        except:\n            exc = sys.exc_info()\n        self.mdr = None\n        self.cursor = None\n        if exc != (None, None, None):\n            six.reraise(*exc)",
    "docstring": "Release all resources associated with this factory."
  },
  {
    "code": "def activities(self):\n        if self._activities is None:\n            self._activities = ActivityList(self._version, workspace_sid=self._solution['sid'], )\n        return self._activities",
    "docstring": "Access the activities\n\n        :returns: twilio.rest.taskrouter.v1.workspace.activity.ActivityList\n        :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityList"
  },
  {
    "code": "def id(self, id):\n        if id is None:\n            raise ValueError(\"Invalid value for `id`, must not be `None`\")\n        if id is not None and not re.search('^[A-Za-z0-9]{32}', id):\n            raise ValueError(\"Invalid value for `id`, must be a follow pattern or equal to `/^[A-Za-z0-9]{32}/`\")\n        self._id = id",
    "docstring": "Sets the id of this BulkResponse.\n        Bulk ID\n\n        :param id: The id of this BulkResponse.\n        :type: str"
  },
  {
    "code": "def registerLoggers(info, error, debug):\n    global log_info\n    global log_error\n    global log_debug\n    log_info = info\n    log_error = error\n    log_debug = debug",
    "docstring": "Add logging functions to this module.\n\n    Functions will be called on various severities (log, error, or debug\n    respectively).\n\n    Each function must have the signature:\n        fn(message, **kwargs)\n\n    If Python str.format()-style placeholders are in message, kwargs will be\n    interpolated."
  },
  {
    "code": "def AsCGI(nsdict={}, typesmodule=None, rpc=False, modules=None):\n    if os.environ.get('REQUEST_METHOD') != 'POST':\n        _CGISendFault(Fault(Fault.Client, 'Must use POST'))\n        return\n    ct = os.environ['CONTENT_TYPE']\n    try:\n        if ct.startswith('multipart/'):\n            cid = resolvers.MIMEResolver(ct, sys.stdin)\n            xml = cid.GetSOAPPart()\n            ps = ParsedSoap(xml, resolver=cid.Resolve)\n        else:\n            length = int(os.environ['CONTENT_LENGTH'])\n            ps = ParsedSoap(sys.stdin.read(length))\n    except ParseException, e:\n        _CGISendFault(FaultFromZSIException(e))\n        return\n    _Dispatch(ps, modules, _CGISendXML, _CGISendFault, nsdict=nsdict,\n              typesmodule=typesmodule, rpc=rpc)",
    "docstring": "Dispatch within a CGI script."
  },
  {
    "code": "def _init_weights(self,\n                      X):\n        X = np.asarray(X, dtype=np.float64)\n        if self.scaler is not None:\n            X = self.scaler.fit_transform(X)\n        if self.initializer is not None:\n            self.weights = self.initializer(X, self.num_neurons)\n        for v in self.params.values():\n            v['value'] = v['orig']\n        return X",
    "docstring": "Set the weights and normalize data before starting training."
  },
  {
    "code": "def get_linked_version(doi):\n    try:\n        request = requests.head(to_url(doi))\n        return request.headers.get(\"location\")\n    except RequestException:\n        return None",
    "docstring": "Get the original link behind the DOI.\n\n    :param doi: A canonical DOI.\n    :returns: The canonical URL behind the DOI, or ``None``.\n\n    >>> get_linked_version('10.1209/0295-5075/111/40005')\n    'http://stacks.iop.org/0295-5075/111/i=4/a=40005?key=crossref.9ad851948a976ecdf216d4929b0b6f01'"
  },
  {
    "code": "def find_rings(self, including=None):\n        undirected = self.graph.to_undirected()\n        directed = undirected.to_directed()\n        cycles_nodes = []\n        cycles_edges = []\n        all_cycles = [c for c in nx.simple_cycles(directed) if len(c) > 2]\n        unique_sorted = []\n        unique_cycles = []\n        for cycle in all_cycles:\n            if sorted(cycle) not in unique_sorted:\n                unique_sorted.append(sorted(cycle))\n                unique_cycles.append(cycle)\n        if including is None:\n            cycles_nodes = unique_cycles\n        else:\n            for i in including:\n                for cycle in unique_cycles:\n                    if i in cycle and cycle not in cycles_nodes:\n                        cycles_nodes.append(cycle)\n        for cycle in cycles_nodes:\n            edges = []\n            for i, e in enumerate(cycle):\n                edges.append((cycle[i-1], e))\n            cycles_edges.append(edges)\n        return cycles_edges",
    "docstring": "Find ring structures in the MoleculeGraph.\n\n        :param including: list of site indices. If\n        including is not None, then find_rings will\n        only return those rings including the specified\n        sites. By default, this parameter is None, and\n        all rings will be returned.\n        :return: dict {index:cycle}. Each\n        entry will be a ring (cycle, in graph theory terms) including the index\n        found in the Molecule. If there is no cycle including an index, the\n        value will be an empty list."
  },
  {
    "code": "def _get_line_no_from_comments(py_line):\n    matched = LINECOL_COMMENT_RE.match(py_line)\n    if matched:\n        return int(matched.group(1))\n    else:\n        return 0",
    "docstring": "Return the line number parsed from the comment or 0."
  },
  {
    "code": "def start_server(self):\n        if self._server is None:\n            self._server = SimpleServer()\n            self._server.createPV(prefix=self._options.prefix,\n                                  pvdb={k: v.config for k, v in self.interface.bound_pvs.items()})\n            self._driver = PropertyExposingDriver(interface=self.interface,\n                                                  device_lock=self.device_lock)\n            self._driver.process_pv_updates(force=True)\n            self.log.info('Started serving PVs: %s',\n                          ', '.join((self._options.prefix + pv for pv in\n                                     self.interface.bound_pvs.keys())))",
    "docstring": "Creates a pcaspy-server.\n\n        .. note::\n\n            The server does not process requests unless :meth:`handle` is called regularly."
  },
  {
    "code": "def has_port_by_name(self, port_name):\n        with self._mutex:\n            if self.get_port_by_name(port_name):\n                return True\n            return False",
    "docstring": "Check if this component has a port by the given name."
  },
  {
    "code": "def _build_cached_instances(self):\n        connection = self._connect()\n        reservations = connection.get_all_reservations()\n        cached_instances = {}\n        for rs in reservations:\n            for vm in rs.instances:\n                cached_instances[vm.id] = vm\n        return cached_instances",
    "docstring": "Build lookup table of VM instances known to the cloud provider.\n\n        The returned dictionary links VM id with the actual VM object."
  },
  {
    "code": "def file(cls, path, encoding=None, parser=None):\n        cls.__hierarchy.append(file.File(path, encoding, parser))",
    "docstring": "Set a file as a source.\n\n        File are parsed as literal python dicts by default, this behaviour\n        can be configured.\n\n        Args:\n            path: The path to the file to be parsed\n            encoding: The encoding of the file.\n                Defaults to 'raw'. Available built-in values: 'ini', 'json', 'yaml'.\n                Custom value can be used in conjunction with parser.\n            parser: A parser function for a custom encoder.\n                It is expected to return a dict containing the parsed values\n                when called with the contents of the file as an argument."
  },
  {
    "code": "def authenticate(self):\n        unique_id = self.new_unique_id()\n        message = {\n            'op': 'authentication',\n            'id': unique_id,\n            'appKey': self.app_key,\n            'session': self.session_token,\n        }\n        self._send(message)\n        return unique_id",
    "docstring": "Authentication request."
  },
  {
    "code": "def subject(self) -> Optional[UnstructuredHeader]:\n        try:\n            return cast(UnstructuredHeader, self[b'subject'][0])\n        except (KeyError, IndexError):\n            return None",
    "docstring": "The ``Subject`` header."
  },
  {
    "code": "def setup_method_options(method, tuning_options):\n    kwargs = {}\n    maxiter = numpy.prod([len(v) for v in tuning_options.tune_params.values()])\n    kwargs['maxiter'] = maxiter\n    if method in [\"Nelder-Mead\", \"Powell\"]:\n        kwargs['maxfev'] = maxiter\n    elif method == \"L-BFGS-B\":\n        kwargs['maxfun'] = maxiter\n    if method in [\"CG\", \"BFGS\", \"L-BFGS-B\", \"TNC\", \"SLSQP\"]:\n        kwargs['eps'] = tuning_options.eps\n    elif method == \"COBYLA\":\n        kwargs['rhobeg'] = tuning_options.eps\n    return kwargs",
    "docstring": "prepare method specific options"
  },
  {
    "code": "def _receive_with_timeout(self, socket, timeout_s, use_multipart=False):\n        if timeout_s is config.FOREVER:\n            timeout_ms = config.FOREVER\n        else:\n            timeout_ms = int(1000 * timeout_s)\n        poller = zmq.Poller()\n        poller.register(socket, zmq.POLLIN)\n        ms_so_far = 0\n        try:\n            for interval_ms in self.intervals_ms(timeout_ms):\n                sockets = dict(poller.poll(interval_ms))\n                ms_so_far += interval_ms\n                if socket in sockets:\n                    if use_multipart:\n                        return socket.recv_multipart()\n                    else:\n                        return socket.recv()\n            else:\n                raise core.SocketTimedOutError(timeout_s)\n        except KeyboardInterrupt:\n            raise core.SocketInterruptedError(ms_so_far / 1000.0)",
    "docstring": "Check for socket activity and either return what's\n        received on the socket or time out if timeout_s expires\n        without anything on the socket.\n        \n        This is implemented in loops of self.try_length_ms milliseconds \n        to allow Ctrl-C handling to take place."
  },
  {
    "code": "def compile(self, model):\n        log = SensorLog(InMemoryStorageEngine(model), model)\n        self.sensor_graph = SensorGraph(log, model)\n        allocator = StreamAllocator(self.sensor_graph, model)\n        self._scope_stack = []\n        root = RootScope(self.sensor_graph, allocator)\n        self._scope_stack.append(root)\n        for statement in self.statements:\n            statement.execute(self.sensor_graph, self._scope_stack)\n        self.sensor_graph.initialize_remaining_constants()\n        self.sensor_graph.sort_nodes()",
    "docstring": "Compile this file into a SensorGraph.\n\n        You must have preivously called parse_file to parse a\n        sensor graph file into statements that are then executed\n        by this command to build a sensor graph.\n\n        The results are stored in self.sensor_graph and can be\n        inspected before running optimization passes.\n\n        Args:\n            model (DeviceModel): The device model that we should compile\n                this sensor graph for."
  },
  {
    "code": "def get_essential_properties(self):\n        data = self.get_host_health_data()\n        properties = {\n            'memory_mb': self._parse_memory_embedded_health(data)\n        }\n        cpus, cpu_arch = self._parse_processor_embedded_health(data)\n        properties['cpus'] = cpus\n        properties['cpu_arch'] = cpu_arch\n        properties['local_gb'] = self._parse_storage_embedded_health(data)\n        macs = self._parse_nics_embedded_health(data)\n        return_value = {'properties': properties, 'macs': macs}\n        return return_value",
    "docstring": "Gets essential scheduling properties as required by ironic\n\n        :returns: a dictionary of server properties like memory size,\n                  disk size, number of cpus, cpu arch, port numbers\n                  and mac addresses.\n        :raises:IloError if iLO returns an error in command execution."
  },
  {
    "code": "def organize_commands(corrected_commands):\n    try:\n        first_command = next(corrected_commands)\n        yield first_command\n    except StopIteration:\n        return\n    without_duplicates = {\n        command for command in sorted(\n            corrected_commands, key=lambda command: command.priority)\n        if command != first_command}\n    sorted_commands = sorted(\n        without_duplicates,\n        key=lambda corrected_command: corrected_command.priority)\n    logs.debug('Corrected commands: '.format(\n        ', '.join(u'{}'.format(cmd) for cmd in [first_command] + sorted_commands)))\n    for command in sorted_commands:\n        yield command",
    "docstring": "Yields sorted commands without duplicates.\n\n    :type corrected_commands: Iterable[thefuck.types.CorrectedCommand]\n    :rtype: Iterable[thefuck.types.CorrectedCommand]"
  },
  {
    "code": "def autolink(self, raw_url, is_email):\n        if self.check_url(raw_url):\n            url = self.rewrite_url(('mailto:' if is_email else '') + raw_url)\n            url = escape_html(url)\n            return '<a href=\"%s\">%s</a>' % (url, escape_html(raw_url))\n        else:\n            return escape_html('<%s>' % raw_url)",
    "docstring": "Filters links generated by the ``autolink`` extension."
  },
  {
    "code": "def unregister(self, thread):\n        if thread not in self.threads.keys():\n            self.log.warning(\"Can not unregister thread %s\" % thread)\n        else:\n            del (self.threads[thread])\n            self.__log.debug(\"Thread %s got unregistered\" % thread)",
    "docstring": "Unregisters an existing thread, so that this thread is no longer available.\n\n        This function is mainly used during plugin deactivation.\n\n        :param thread: Name of the thread"
  },
  {
    "code": "def append_tier(self, coro, **kwargs):\n        source = self.tiers[-1] if self.tiers else None\n        return self.add_tier(coro, source=source, **kwargs)",
    "docstring": "Implicitly source from the tail tier like a pipe."
  },
  {
    "code": "def get_network_name(self):\n        start = self.network.find('network')\n        end = self.network.find('}\\n', start)\n        network_attribute = Suppress('network') + Word(alphanums + '_' + '-') + '{'\n        network_name = network_attribute.searchString(self.network[start:end])[0][0]\n        return network_name",
    "docstring": "Retruns the name of the network\n\n        Example\n        ---------------\n        >>> from pgmpy.readwrite import BIFReader\n        >>> reader = BIF.BifReader(\"bif_test.bif\")\n        >>> reader.network_name()\n        'Dog-Problem'"
  },
  {
    "code": "def job_callback(self, job):\n\t\tself.logger.debug('job_callback for %s started'%str(job.id))\n\t\twith self.thread_cond:\n\t\t\tself.logger.debug('job_callback for %s got condition'%str(job.id))\n\t\t\tself.num_running_jobs -= 1\n\t\t\tif not self.result_logger is None:\n\t\t\t\tself.result_logger(job)\n\t\t\tself.iterations[job.id[0]].register_result(job)\n\t\t\tself.config_generator.new_result(job)\n\t\t\tif self.num_running_jobs <= self.job_queue_sizes[0]:\n\t\t\t\tself.logger.debug(\"HBMASTER: Trying to run another job!\")\n\t\t\t\tself.thread_cond.notify()\n\t\tself.logger.debug('job_callback for %s finished'%str(job.id))",
    "docstring": "method to be called when a job has finished\n\n\t\tthis will do some book keeping and call the user defined\n\t\tnew_result_callback if one was specified"
  },
  {
    "code": "def get_neighbor_attribute_map(neigh_ip_address, route_dist=None,\n                               route_family=VRF_RF_IPV4):\n    core = CORE_MANAGER.get_core_service()\n    peer = core.peer_manager.get_by_addr(neigh_ip_address)\n    at_maps_key = const.ATTR_MAPS_LABEL_DEFAULT\n    if route_dist is not None:\n        at_maps_key = ':'.join([route_dist, route_family])\n    at_maps = peer.attribute_maps.get(at_maps_key)\n    if at_maps:\n        return at_maps.get(const.ATTR_MAPS_ORG_KEY)\n    else:\n        return []",
    "docstring": "Returns a neighbor attribute_map for given ip address if exists."
  },
  {
    "code": "def expand_abbreviations(txt, fields):\n    def _expand(matchobj):\n        s = matchobj.group(\"var\")\n        if s not in fields:\n            matches = [x for x in fields if x.startswith(s)]\n            if len(matches) == 1:\n                s = matches[0]\n        return \"{%s}\" % s\n    return re.sub(FORMAT_VAR_REGEX, _expand, txt)",
    "docstring": "Expand abbreviations in a format string.\n\n    If an abbreviation does not match a field, or matches multiple fields, it\n    is left unchanged.\n\n    Example:\n\n        >>> fields = (\"hey\", \"there\", \"dude\")\n        >>> expand_abbreviations(\"hello {d}\", fields)\n        'hello dude'\n\n    Args:\n        txt (str): Format string.\n        fields (list of str): Fields to expand to.\n\n    Returns:\n        Expanded string."
  },
  {
    "code": "def sed(match, replacement, path, modifiers=\"\"):\n    cmd = \"sed -r -i 's/%s/%s/%s' %s\" % (match, replacement, modifiers, path)\n    process = Subprocess(cmd, shell=True)\n    ret, out, err = process.run(timeout=60)\n    if ret:\n        raise SubprocessError(\"Sed command failed!\")",
    "docstring": "Perform sed text substitution."
  },
  {
    "code": "def get_version(path, default=\"master\"):\n    version = default\n    if os.path.exists(path):\n        version_contents = file_to_string(path)\n        if version_contents:\n            version = version_contents.strip()\n    return version",
    "docstring": "Return the version from a VERSION file"
  },
  {
    "code": "def resources_gc_prefix(options, policy_config, policy_collection):\n    policy_regions = {}\n    for p in policy_collection:\n        if p.execution_mode == 'poll':\n            continue\n        policy_regions.setdefault(p.options.region, []).append(p)\n    regions = get_gc_regions(options.regions)\n    for r in regions:\n        region_gc(options, r, policy_config, policy_regions.get(r, []))",
    "docstring": "Garbage collect old custodian policies based on prefix.\n\n    We attempt to introspect to find the event sources for a policy\n    but without the old configuration this is implicit."
  },
  {
    "code": "def sample_grid(self, count=None, step=None):\n        if (count is not None and\n                step is not None):\n            raise ValueError('only step OR count can be specified!')\n        bounds = np.array([-self.primitive.extents,\n                           self.primitive.extents]) * .5\n        if step is not None:\n            grid = util.grid_arange(bounds, step=step)\n        elif count is not None:\n            grid = util.grid_linspace(bounds, count=count)\n        else:\n            raise ValueError('either count or step must be specified!')\n        transformed = transformations.transform_points(\n            grid, matrix=self.primitive.transform)\n        return transformed",
    "docstring": "Return a 3D grid which is contained by the box.\n        Samples are either 'step' distance apart, or there are\n        'count' samples per box side.\n\n        Parameters\n        -----------\n        count : int or (3,) int\n          If specified samples are spaced with np.linspace\n        step : float or (3,) float\n          If specified samples are spaced with np.arange\n\n        Returns\n        -----------\n        grid : (n, 3) float\n          Points inside the box"
  },
  {
    "code": "def setup(self, interval):\n        self.trace_counter = 0\n        self._halt = False\n        self.interval = interval",
    "docstring": "Prepares the tests for execution, interval in ms"
  },
  {
    "code": "def format_energy_results(energy):\n    if not energy:\n        return {}\n    result = {}\n    cpuenergy = Decimal(0)\n    for pkg, domains in energy.items():\n        for domain, value in domains.items():\n            if domain == DOMAIN_PACKAGE:\n                cpuenergy += value\n                result['cpuenergy-pkg{}'.format(pkg)] = value\n            else:\n                result['cpuenergy-pkg{}-{}'.format(pkg, domain)] = value\n    result['cpuenergy'] = cpuenergy\n    result = collections.OrderedDict(sorted(result.items()))\n    return result",
    "docstring": "Take the result of an energy measurement and return a flat dictionary that contains all values."
  },
  {
    "code": "def get_user_info(self):\n        resp = self.requester.get(\n            urljoin(\n                self.base_url,\n                '/api/mobile/v0.5/my_user_info'\n            )\n        )\n        resp.raise_for_status()\n        return Info(resp.json())",
    "docstring": "Returns a UserInfo object for the logged in user.\n\n        Returns:\n            UserInfo: object representing the student current grades"
  },
  {
    "code": "def matches_querytime(instance, querytime):\n        if not querytime.active:\n            return True\n        if not querytime.time:\n            return instance.version_end_date is None\n        return (instance.version_start_date <= querytime.time and\n                (instance.version_end_date is None or\n                 instance.version_end_date > querytime.time))",
    "docstring": "Checks whether the given instance satisfies the given QueryTime object.\n\n        :param instance: an instance of Versionable\n        :param querytime: QueryTime value to check against"
  },
  {
    "code": "def resource(resource_id):\n    resource_obj = app.db.resource(resource_id)\n    if 'raw' in request.args:\n        return send_from_directory(os.path.dirname(resource_obj.path),\n                                   os.path.basename(resource_obj.path))\n    return render_template('resource.html', resource=resource_obj)",
    "docstring": "Show a resource."
  },
  {
    "code": "def query(\n        self,\n        query,\n        job_config=None,\n        job_id=None,\n        job_id_prefix=None,\n        location=None,\n        project=None,\n        retry=DEFAULT_RETRY,\n    ):\n        job_id = _make_job_id(job_id, job_id_prefix)\n        if project is None:\n            project = self.project\n        if location is None:\n            location = self.location\n        if self._default_query_job_config:\n            if job_config:\n                job_config = job_config._fill_from_default(\n                    self._default_query_job_config\n                )\n            else:\n                job_config = self._default_query_job_config\n        job_ref = job._JobReference(job_id, project=project, location=location)\n        query_job = job.QueryJob(job_ref, query, client=self, job_config=job_config)\n        query_job._begin(retry=retry)\n        return query_job",
    "docstring": "Run a SQL query.\n\n        See\n        https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query\n\n        Arguments:\n            query (str):\n                SQL query to be executed. Defaults to the standard SQL\n                dialect. Use the ``job_config`` parameter to change dialects.\n\n        Keyword Arguments:\n            job_config (google.cloud.bigquery.job.QueryJobConfig):\n                (Optional) Extra configuration options for the job.\n                To override any options that were previously set in\n                the ``default_query_job_config`` given to the\n                ``Client`` constructor, manually set those options to ``None``,\n                or whatever value is preferred.\n            job_id (str): (Optional) ID to use for the query job.\n            job_id_prefix (str):\n                (Optional) The prefix to use for a randomly generated job ID.\n                This parameter will be ignored if a ``job_id`` is also given.\n            location (str):\n                Location where to run the job. Must match the location of the\n                any table used in the query as well as the destination table.\n            project (str):\n                Project ID of the project of where to run the job. Defaults\n                to the client's project.\n            retry (google.api_core.retry.Retry):\n                (Optional) How to retry the RPC.\n\n        Returns:\n            google.cloud.bigquery.job.QueryJob: A new query job instance."
  },
  {
    "code": "def check_input_sample(input_sample, num_params, num_samples):\n        assert type(input_sample) == np.ndarray, \\\n            \"Input sample is not an numpy array\"\n        assert input_sample.shape[0] == (num_params + 1) * num_samples, \\\n            \"Input sample does not match number of parameters or groups\"\n        assert np.any((input_sample >= 0) | (input_sample <= 1)), \\\n            \"Input sample must be scaled between 0 and 1\"",
    "docstring": "Check the `input_sample` is valid\n\n        Checks input sample is:\n            - the correct size\n            - values between 0 and 1\n\n        Arguments\n        ---------\n        input_sample : numpy.ndarray\n        num_params : int\n        num_samples : int"
  },
  {
    "code": "async def do_upload(context, files):\n    status = 0\n    try:\n        await upload_artifacts(context, files)\n    except ScriptWorkerException as e:\n        status = worst_level(status, e.exit_code)\n        log.error(\"Hit ScriptWorkerException: {}\".format(e))\n    except aiohttp.ClientError as e:\n        status = worst_level(status, STATUSES['intermittent-task'])\n        log.error(\"Hit aiohttp error: {}\".format(e))\n    except Exception as e:\n        log.exception(\"SCRIPTWORKER_UNEXPECTED_EXCEPTION upload {}\".format(e))\n        raise\n    return status",
    "docstring": "Upload artifacts and return status.\n\n    Returns the integer status of the upload.\n\n    args:\n        context (scriptworker.context.Context): the scriptworker context.\n        files (list of str): list of files to be uploaded as artifacts\n\n    Raises:\n        Exception: on unexpected exception.\n\n    Returns:\n        int: exit status"
  },
  {
    "code": "def edit(args):\n        tap = DbTap.find(args.id)\n        options = {}\n        if not args.name is None:\n            options[\"db_name\"]=args.name\n        if args.host is not None:\n            options[\"db_host\"]=args.host\n        if args.user is not None:\n            options[\"db_user\"]=args.user\n        if args.password is not None:\n            options[\"db_passwd\"] = args.password\n        if args.type is not None:\n            options[\"db_type\"] = args.type\n        if args.location is not None:\n            options[\"db_location\"] = args.location\n        if args.port is not None:\n            options[\"port\"] = args.port\n        tap = tap.edit(**options)\n        return json.dumps(tap.attributes, sort_keys=True, indent=4)",
    "docstring": "Carefully setup a dict"
  },
  {
    "code": "def simple_profile(self, sex=None):\n        SEX = [\"F\", \"M\"]\n        if sex not in SEX:\n            sex = self.random_element(SEX)\n        if sex == 'F':\n            name = self.generator.name_female()\n        elif sex == 'M':\n            name = self.generator.name_male()\n        return {\n            \"username\": self.generator.user_name(),\n            \"name\": name,\n            \"sex\": sex,\n            \"address\": self.generator.address(),\n            \"mail\": self.generator.free_email(),\n            \"birthdate\": self.generator.date_of_birth(),\n        }",
    "docstring": "Generates a basic profile with personal informations"
  },
  {
    "code": "def search(self):\n        s = super(TopicSearchMixin, self).search()\n        s = s.filter('bool', should=[\n            Q('term', tags=tag) for tag in self.topic.tags\n        ])\n        return s",
    "docstring": "Override search to match on topic tags"
  },
  {
    "code": "def is_color_supported():\n    \"Find out if your terminal environment supports color.\"\n    if not hasattr(sys.stdout, 'isatty'):\n        return False\n    if not sys.stdout.isatty() and 'TERMINAL-COLOR' not in os.environ:\n        return False\n    if sys.platform == 'win32':\n        try:\n            import colorama\n            colorama.init()\n            return True\n        except ImportError:\n            return False\n    if 'COLORTERM' in os.environ:\n        return True\n    term = os.environ.get('TERM', 'dumb').lower()\n    return term in ('xterm', 'linux') or 'color' in term",
    "docstring": "Find out if your terminal environment supports color."
  },
  {
    "code": "def _call(self, method, url, params, uploads):\n        try:\n            data = self._request(method, url, params, uploads)\n        except Exception, e:\n            self._failed_cb(e)\n        else:\n            self._completed_cb(data)",
    "docstring": "Initiate resquest to server and handle outcomes."
  },
  {
    "code": "def _build_query_params(self, headers_only=False, page_size=None):\n        params = {\"name\": self._project_path, \"filter_\": self.filter}\n        params[\"interval\"] = types.TimeInterval()\n        params[\"interval\"].end_time.FromDatetime(self._end_time)\n        if self._start_time:\n            params[\"interval\"].start_time.FromDatetime(self._start_time)\n        if (\n            self._per_series_aligner\n            or self._alignment_period_seconds\n            or self._cross_series_reducer\n            or self._group_by_fields\n        ):\n            params[\"aggregation\"] = types.Aggregation(\n                per_series_aligner=self._per_series_aligner,\n                cross_series_reducer=self._cross_series_reducer,\n                group_by_fields=self._group_by_fields,\n                alignment_period={\"seconds\": self._alignment_period_seconds},\n            )\n        if headers_only:\n            params[\"view\"] = enums.ListTimeSeriesRequest.TimeSeriesView.HEADERS\n        else:\n            params[\"view\"] = enums.ListTimeSeriesRequest.TimeSeriesView.FULL\n        if page_size is not None:\n            params[\"page_size\"] = page_size\n        return params",
    "docstring": "Return key-value pairs for the list_time_series API call.\n\n        :type headers_only: bool\n        :param headers_only:\n             Whether to omit the point data from the\n             :class:`~google.cloud.monitoring_v3.types.TimeSeries` objects.\n\n        :type page_size: int\n        :param page_size:\n            (Optional) The maximum number of points in each page of results\n            from this request. Non-positive values are ignored. Defaults\n            to a sensible value set by the API."
  },
  {
    "code": "def login_server(self):\n        local('ssh -i {0} {1}@{2}'.format(\n            env.key_filename, env.user, env.host_string\n        ))",
    "docstring": "Login to server"
  },
  {
    "code": "def update_object(self, form, obj):\n        field_name = form.cleaned_data['name']\n        value = form.cleaned_data['value']\n        setattr(obj, field_name, value)\n        save_kwargs = {}\n        if CAN_UPDATE_FIELDS:\n            save_kwargs['update_fields'] = [field_name]\n        obj.save(**save_kwargs)\n        data = json.dumps({\n            'status': 'success',\n        })\n        return HttpResponse(data, content_type=\"application/json\")",
    "docstring": "Saves the new value to the target object."
  },
  {
    "code": "def _find_solo_consonant(self, letters: List[str]) -> List[int]:\n        solos = []\n        for idx, letter in enumerate(letters):\n            if len(letter) == 1 and self._contains_consonants(letter):\n                solos.append(idx)\n        return solos",
    "docstring": "Find the positions of any solo consonants that are not yet paired with a vowel."
  },
  {
    "code": "def settings_view_decorator(function):\n    dec = settings.CLOUD_BROWSER_VIEW_DECORATOR\n    if isinstance(dec, str):\n        mod_str, _, dec_str = dec.rpartition('.')\n        if not (mod_str and dec_str):\n            raise ImportError(\"Unable to import module: %s\" % mod_str)\n        mod = import_module(mod_str)\n        if not hasattr(mod, dec_str):\n            raise ImportError(\"Unable to import decorator: %s\" % dec)\n        dec = getattr(mod, dec_str)\n    if dec and callable(dec):\n        return dec(function)\n    return function",
    "docstring": "Insert decorator from settings, if any.\n\n    .. note:: Decorator in ``CLOUD_BROWSER_VIEW_DECORATOR`` can be either a\n        callable or a fully-qualified string path (the latter, which we'll\n        lazy import)."
  },
  {
    "code": "def write_ensemble(ensemble, options):\n    size = len(ensemble)\n    filename = '%s_%s_queries.csv' % (options.outname, size)\n    file = os.path.join(os.getcwd(), filename)\n    f = open(file, 'w')\n    out = ', '.join(ensemble)\n    f.write(out)\n    f.close()",
    "docstring": "Prints out the ensemble composition at each size"
  },
  {
    "code": "def disassociate_public_ip(self, public_ip_id):\n        floating_ip = self.client.floating_ips.get(public_ip_id)\n        floating_ip = floating_ip.to_dict()\n        instance_id = floating_ip.get('instance_id')\n        address = floating_ip.get('ip')\n        self.client.servers.remove_floating_ip(instance_id, address)\n        return True",
    "docstring": "Disassociate a external IP"
  },
  {
    "code": "def split_into_batches(input_list, batch_size, batch_storage_dir, checkpoint=False):\n    if checkpoint and not os.path.exists(batch_storage_dir):\n        os.mkdir(batch_storage_dir)\n    batches = [\n        {\n            'index': batch_index,\n            'data': input_list[start_index:start_index + batch_size],\n            'input_filename': os.path.join(batch_storage_dir, 'batch-{:05d}-input.pickle'.format(batch_index)),\n            'result_filename': os.path.join(batch_storage_dir, 'batch-{:05d}-output.pickle'.format(batch_index)),\n        }\n        for batch_index, start_index in enumerate(range(0, len(input_list), batch_size))\n    ]\n    if checkpoint:\n        for batch in batches:\n            save(batch['data'], batch['input_filename'])\n    return batches",
    "docstring": "Break the input data into smaller batches, optionally saving each one to disk.\n\n    Args:\n        input_list: An input object that has a list-like interface (indexing and slicing).\n        batch_size: The maximum number of input items in each batch.\n        batch_storage_dir: The directory to save the checkpoints to.\n        checkpoint: Whether to save each batch to a file.\n\n    Returns:\n        A list of batch objects with the following structure:\n        {'index', 'data', 'input_filename', 'result_filename'}"
  },
  {
    "code": "def decode_wireformat_uuid(rawguid):\n    if isinstance(rawguid, list):\n        rawguid = bytearray(rawguid)\n    lebytes = struct.unpack_from('<IHH', buffer(rawguid[:8]))\n    bebytes = struct.unpack_from('>HHI', buffer(rawguid[8:]))\n    return '{0:08X}-{1:04X}-{2:04X}-{3:04X}-{4:04X}{5:08X}'.format(\n        lebytes[0], lebytes[1], lebytes[2], bebytes[0], bebytes[1], bebytes[2])",
    "docstring": "Decode a wire format UUID\n\n    It handles the rather particular scheme where half is little endian\n    and half is big endian.  It returns a string like dmidecode would output."
  },
  {
    "code": "def as_list(self):\n        return [self.name, self.value, [x.as_list for x in self.children]]",
    "docstring": "Return all child objects in nested lists of strings."
  },
  {
    "code": "def add_camera_make_model(self, make, model):\n        self._ef['0th'][piexif.ImageIFD.Make] = make\n        self._ef['0th'][piexif.ImageIFD.Model] = model",
    "docstring": "Add camera make and model."
  },
  {
    "code": "def todo(self):\n        if not os.path.exists(self.migrate_dir):\n            self.logger.warn('Migration directory: %s does not exist.', self.migrate_dir)\n            os.makedirs(self.migrate_dir)\n        return sorted(f[:-3] for f in os.listdir(self.migrate_dir) if self.filemask.match(f))",
    "docstring": "Scan migrations in file system."
  },
  {
    "code": "def searchAccount(searchTerm, book):\n    print(\"Search results:\\n\")\n    found = False\n    for account in book.accounts:\n        if searchTerm.lower() in account.fullname.lower():\n            print(account.fullname)\n            found = True\n    if not found:\n        print(\"Search term not found in account names.\")",
    "docstring": "Searches through account names"
  },
  {
    "code": "def handle_sketch_name(msg):\n    if not msg.gateway.is_sensor(msg.node_id):\n        return None\n    msg.gateway.sensors[msg.node_id].sketch_name = msg.payload\n    msg.gateway.alert(msg)\n    return None",
    "docstring": "Process an internal sketch name message."
  },
  {
    "code": "def do_GET(self):\n        if self.path.startswith(self.serve_url):\n            from_key = self.path[len(self.serve_url):]\n            val_res = self.decrypt_yubikey_otp(from_key)\n            self.send_response(200)\n            self.send_header('Content-type', 'text/html')\n            self.end_headers()\n            self.wfile.write(val_res)\n            self.wfile.write(\"\\n\")\n        elif self.stats_url and self.path == self.stats_url:\n            self.send_response(200)\n            self.send_header('Content-type', 'text/html')\n            self.end_headers()\n            for key in stats:\n                self.wfile.write(\"%s %d\\n\" % (key, stats[key]))\n        else:\n            self.log_error(\"Bad URL '%s' - I'm serving '%s' (responding 403)\" % (self.path, self.serve_url))\n            self.send_response(403, 'Forbidden')\n            self.end_headers()",
    "docstring": "Handle a HTTP GET request."
  },
  {
    "code": "def _assert_all_loadable_terms_specialized_to(self, domain):\n        for term in self.graph.node:\n            if isinstance(term, LoadableTerm):\n                assert term.domain is domain",
    "docstring": "Make sure that we've specialized all loadable terms in the graph."
  },
  {
    "code": "def api_call(self, opts, args=None, body=None, **kwargs):\n        if args:\n            path = opts['name'] % args\n        else:\n            path = opts['name']\n        path = '/api/v1%s' % path\n        return self._request(\n            opts['method'], path=path, payload=body, **kwargs)",
    "docstring": "Setup the request"
  },
  {
    "code": "def issuperset(self, other):\n        if len(self) < len(other):\n            return False\n        return all(item in self for item in other)",
    "docstring": "Report whether this set contains another set.\n\n        Example:\n            >>> OrderedSet([1, 2]).issuperset([1, 2, 3])\n            False\n            >>> OrderedSet([1, 2, 3, 4]).issuperset({1, 2, 3})\n            True\n            >>> OrderedSet([1, 4, 3, 5]).issuperset({1, 2, 3})\n            False"
  },
  {
    "code": "def _format_issue_url(self):\n        query = urlencode({\n            'title': self._format_issue_title(),\n            'body': self._format_issue_body(),\n        })\n        return self.REPO_URL + self.ISSUE_SUFFIX + '?' + query",
    "docstring": "Format full issue URL."
  },
  {
    "code": "def convert_units(values, source_measure_or_unit_abbreviation, target_measure_or_unit_abbreviation,**kwargs):\n    if numpy.isscalar(values):\n        values = [values]\n    float_values = [float(value) for value in values]\n    values_to_return = convert(float_values, source_measure_or_unit_abbreviation, target_measure_or_unit_abbreviation)\n    return values_to_return",
    "docstring": "Convert a value from one unit to another one.\n\n        Example::\n\n            >>> cli = PluginLib.connect()\n            >>> cli.service.convert_units(20.0, 'm', 'km')\n            0.02\n        Parameters:\n            values: single measure or an array of measures\n            source_measure_or_unit_abbreviation: A measure in the source unit, or just the abbreviation of the source unit, from which convert the provided measure value/values\n            target_measure_or_unit_abbreviation: A measure in the target unit, or just the abbreviation of the target unit, into which convert the provided measure value/values\n\n        Returns:\n            Always a list"
  },
  {
    "code": "def recompute(self, quiet=False, **kwargs):\n        if not self.computed:\n            if not (hasattr(self, \"_x\") and hasattr(self, \"_yerr2\")):\n                raise RuntimeError(\"You need to compute the model first\")\n            try:\n                self.compute(self._x, np.sqrt(self._yerr2), **kwargs)\n            except (ValueError, LinAlgError):\n                if quiet:\n                    return False\n                raise\n        return True",
    "docstring": "Re-compute a previously computed model. You might want to do this if\n        the kernel parameters change and the kernel is labeled as ``dirty``.\n\n        :param quiet: (optional)\n            If ``True``, return false when the computation fails. Otherwise,\n            throw an error if something goes wrong. (default: ``False``)"
  },
  {
    "code": "def redirect(location=None, internal=False, code=None, headers={},\n             add_slash=False, request=None):\n    request = request or state.request\n    if add_slash:\n        if location is None:\n            split_url = list(urlparse.urlsplit(request.url))\n            new_proto = request.environ.get(\n                'HTTP_X_FORWARDED_PROTO', split_url[0]\n            )\n            split_url[0] = new_proto\n        else:\n            split_url = urlparse.urlsplit(location)\n        split_url[2] = split_url[2].rstrip('/') + '/'\n        location = urlparse.urlunsplit(split_url)\n    if not headers:\n        headers = {}\n    if internal:\n        if code is not None:\n            raise ValueError('Cannot specify a code for internal redirects')\n        request.environ['pecan.recursive.context'] = request.context\n        raise ForwardRequestException(location)\n    if code is None:\n        code = 302\n    raise exc.status_map[code](location=location, headers=headers)",
    "docstring": "Perform a redirect, either internal or external. An internal redirect\n    performs the redirect server-side, while the external redirect utilizes\n    an HTTP 302 status code.\n\n    :param location: The HTTP location to redirect to.\n    :param internal: A boolean indicating whether the redirect should be\n                     internal.\n    :param code: The HTTP status code to use for the redirect. Defaults to 302.\n    :param headers: Any HTTP headers to send with the response, as a\n                    dictionary.\n    :param request: The :class:`pecan.Request` instance to use."
  },
  {
    "code": "def notifications(self):\n        params = {\"f\": \"json\"}\n        url = \"%s/notifications\" % self.root\n        return Notifications(url=url,\n                             securityHandler=self._securityHandler,\n                             proxy_url=self._proxy_url,\n                             proxy_port=self._proxy_port)",
    "docstring": "The notifications that are available for the given user.\n        Notifications are events that need the user's attention-application\n        for joining a group administered by the user, acceptance of a group\n        membership application, and so on. A notification is initially\n        marked as new. The user can mark it as read or delete the notification."
  },
  {
    "code": "def insert_bytes(fobj, size, offset, BUFFER_SIZE=2 ** 16):\n    if size < 0 or offset < 0:\n        raise ValueError\n    fobj.seek(0, 2)\n    filesize = fobj.tell()\n    movesize = filesize - offset\n    if movesize < 0:\n        raise ValueError\n    resize_file(fobj, size, BUFFER_SIZE)\n    if mmap is not None:\n        try:\n            mmap_move(fobj, offset + size, offset, movesize)\n        except mmap.error:\n            fallback_move(fobj, offset + size, offset, movesize, BUFFER_SIZE)\n    else:\n        fallback_move(fobj, offset + size, offset, movesize, BUFFER_SIZE)",
    "docstring": "Insert size bytes of empty space starting at offset.\n\n    fobj must be an open file object, open rb+ or\n    equivalent. Mutagen tries to use mmap to resize the file, but\n    falls back to a significantly slower method if mmap fails.\n\n    Args:\n        fobj (fileobj)\n        size (int): The amount of space to insert\n        offset (int): The offset at which to insert the space\n    Raises:\n        IOError"
  },
  {
    "code": "def _setFlags(self):\n\t\tself.atEnd = not self.gametree.variations and (self.index + 1 == len(self.gametree))\n\t\tself.atStart = not self.stack and (self.index == 0)",
    "docstring": "Sets up the flags 'self.atEnd' and 'self.atStart'."
  },
  {
    "code": "def add_tree(self, tree, parent=None):\n        if tree.path in self.path_db:\n            self.remove_tree_by_path(tree.path)\n        for index in tree.indexes:\n            if not getattr(tree, index):\n                continue\n            self._add_to(\n                getattr(self, index + \"_db\"),\n                getattr(tree, index),\n                tree,\n            )\n        if parent:\n            self._add_to(self.parent_db, tree.path, parent)\n        for sub_tree in tree.sub_trees:\n            assert sub_tree.path.startswith(tree.path)\n        for sub_tree in tree.sub_trees:\n            self.add_tree(sub_tree, parent=tree)",
    "docstring": "Add `tree` into database.\n\n        Args:\n            tree (obj): :class:`.Tree` instance.\n            parent (ref, default None): Reference to parent tree. This is used\n                for all sub-trees in recursive call."
  },
  {
    "code": "def update(self, num):\n        num = float(num)\n        self.count += 1\n        self.low = min(self.low, num)\n        self.high = max(self.high, num)\n        delta = num - self.mean\n        self.mean = self.mean + delta / self.count\n        delta2 = num - self.mean\n        self._rolling_variance = self._rolling_variance + delta * delta2\n        if self.count > 1:\n            self.deviation = math.sqrt(self._rolling_variance / (self.count - 1))\n        else:\n            self.deviation = 0.0",
    "docstring": "Update metrics with the new number."
  },
  {
    "code": "def _get_deps(self, tree, include_punct, representation, universal):\n        if universal:\n            converter = self.universal_converter\n            if self.universal_converter == self.converter:\n                import warnings\n                warnings.warn(\"This jar doesn't support universal \"\n                              \"dependencies, falling back to Stanford \"\n                              \"Dependencies. To suppress this message, \"\n                              \"call with universal=False\")\n        else:\n            converter = self.converter\n        if include_punct:\n            egs = converter(tree, self.acceptFilter)\n        else:\n            egs = converter(tree)\n        if representation == 'basic':\n            deps = egs.typedDependencies()\n        elif representation == 'collapsed':\n            deps = egs.typedDependenciesCollapsed(True)\n        elif representation == 'CCprocessed':\n            deps = egs.typedDependenciesCCprocessed(True)\n        else:\n            assert representation == 'collapsedTree'\n            deps = egs.typedDependenciesCollapsedTree()\n        return self._listify(deps)",
    "docstring": "Get a list of dependencies from a Stanford Tree for a specific\n        Stanford Dependencies representation."
  },
  {
    "code": "def _on_closed(self):\n        LOGGER.error('Redis connection closed')\n        self.connected = False\n        self._on_close()\n        self._stream = None",
    "docstring": "Invoked when the connection is closed"
  },
  {
    "code": "def reset(self):\n        self.update_widgets()\n        for column in self._columns:\n            for widget in column:\n                widget.reset()\n                widget.blur()\n        self._live_widget = -1\n        self._find_next_widget(1)",
    "docstring": "Reset this Layout and the Widgets it contains."
  },
  {
    "code": "def on_nick(self, connection, event):\n        old_nickname = self.get_nickname(event)\n        old_color = self.nicknames.pop(old_nickname)\n        new_nickname = event.target()\n        message = \"is now known as %s\" % new_nickname\n        self.namespace.emit(\"message\", old_nickname, message, old_color)\n        new_color = color(new_nickname)\n        self.nicknames[new_nickname] = new_color\n        self.emit_nicknames()\n        if self.nickname == old_nickname:\n            self.nickname = new_nickname",
    "docstring": "Someone changed their nickname - send the nicknames list to the\n        WebSocket."
  },
  {
    "code": "def iters(cls, batch_size=32, device=0, root='.data', vectors=None, **kwargs):\n        TEXT = data.Field()\n        LABEL = data.Field(sequential=False)\n        train, val, test = cls.splits(TEXT, LABEL, root=root, **kwargs)\n        TEXT.build_vocab(train, vectors=vectors)\n        LABEL.build_vocab(train)\n        return data.BucketIterator.splits(\n            (train, val, test), batch_size=batch_size, device=device)",
    "docstring": "Create iterator objects for splits of the SST dataset.\n\n        Arguments:\n            batch_size: Batch_size\n            device: Device to create batches on. Use - 1 for CPU and None for\n                the currently active GPU device.\n            root: The root directory that the dataset's zip archive will be\n                expanded into; therefore the directory in whose trees\n                subdirectory the data files will be stored.\n            vectors: one of the available pretrained vectors or a list with each\n                element one of the available pretrained vectors (see Vocab.load_vectors)\n            Remaining keyword arguments: Passed to the splits method."
  },
  {
    "code": "def a2bits_list(chars: str, encoding: str = \"UTF-8\") -> List[str]:\n    return [bin(ord(x))[2:].rjust(ENCODINGS[encoding], \"0\") for x in chars]",
    "docstring": "Convert a string to its bits representation as a list of 0's and 1's.\n\n    >>>  a2bits_list(\"Hello World!\")\n    ['01001000',\n    '01100101',\n    '01101100',\n    '01101100',\n    '01101111',\n    '00100000',\n    '01010111',\n    '01101111',\n    '01110010',\n    '01101100',\n    '01100100',\n    '00100001']\n    >>> \"\".join(a2bits_list(\"Hello World!\"))\n    '010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001'"
  },
  {
    "code": "def tar_extract(cls, tar_comp_file_path):\n        try:\n            with contextlib.closing(tarfile.open(tar_comp_file_path)) as tar:\n                tar.extractall()\n        except tarfile.ReadError as e:\n            message_format = (\n                'Extract failed: '\n                'tar_comp_file_path: {0}, reason: {1}'\n            )\n            raise InstallError(message_format.format(tar_comp_file_path, e))",
    "docstring": "Extract tar.gz or tar bz2 file.\n\n        It behaves like\n          - tar xzf tar_gz_file_path\n          - tar xjf tar_bz2_file_path\n        It raises tarfile.ReadError if the file is broken."
  },
  {
    "code": "def name(self, name):\n        success = idaapi.set_enum_member_name(self.cid, name)\n        if not success:\n            raise exceptions.CantRenameEnumMember(\n                \"Failed renaming {!r} to {!r}. Does the name exist somewhere else?\".format(self.name, name))",
    "docstring": "Set the member name.\n\n        Note that a member name cannot appear in other enums, or generally\n        anywhere else in the IDB."
  },
  {
    "code": "def profile_cancel(self, query_id, timeout=10):\n        result = Result(*self.perform_request(**{\n            'method': 'GET',\n            'url': '/profiles/cancel/{0}'.format(query_id),\n            'params': {\n                'request_timeout': timeout\n            }\n        }))\n        return result",
    "docstring": "Cancel the query that has the given queryid.\n\n        :param query_id: The UUID of the query in standard UUID format that Drill assigns to each query.\n        :param timeout: int\n        :return: pydrill.client.Result"
  },
  {
    "code": "def statuses(self):\n        r_json = self._get_json('status')\n        statuses = [Status(self._options, self._session, raw_stat_json)\n                    for raw_stat_json in r_json]\n        return statuses",
    "docstring": "Get a list of status Resources from the server.\n\n        :rtype: List[Status]"
  },
  {
    "code": "def _factory(slice_, axis, weighted):\n        if slice_.dim_types[0] == DT.MR_SUBVAR:\n            return _MrXCatPairwiseSignificance(slice_, axis, weighted)\n        return _CatXCatPairwiseSignificance(slice_, axis, weighted)",
    "docstring": "return subclass for PairwiseSignificance, based on slice dimension types."
  },
  {
    "code": "def load_from_file(cls, filename_prefix):\n    filename = cls._filename(filename_prefix)\n    lines, _ = cls._read_lines_from_file(filename)\n    vocab_list = [line[1:-1] for line in lines]\n    return cls(vocab_list=vocab_list)",
    "docstring": "Extracts list of subwords from file."
  },
  {
    "code": "def extract_bzip2 (archive, compression, cmd, verbosity, interactive, outdir):\n    targetname = util.get_single_outfile(outdir, archive)\n    try:\n        with bz2.BZ2File(archive) as bz2file:\n            with open(targetname, 'wb') as targetfile:\n                data = bz2file.read(READ_SIZE_BYTES)\n                while data:\n                    targetfile.write(data)\n                    data = bz2file.read(READ_SIZE_BYTES)\n    except Exception as err:\n        msg = \"error extracting %s to %s: %s\" % (archive, targetname, err)\n        raise util.PatoolError(msg)\n    return None",
    "docstring": "Extract a BZIP2 archive with the bz2 Python module."
  },
  {
    "code": "def info(self, name, description, labelnames=None, labelvalues=None, **labels):\n        if labels and labelnames:\n            raise ValueError(\n                'Cannot have labels defined as `dict` '\n                'and collections of names and values'\n            )\n        if labelnames is None and labels:\n            labelnames = labels.keys()\n        elif labelnames and labelvalues:\n            for idx, label_name in enumerate(labelnames):\n                labels[label_name] = labelvalues[idx]\n        gauge = Gauge(\n            name, description, labelnames or tuple(),\n            registry=self.registry\n        )\n        if labels:\n            gauge = gauge.labels(**labels)\n        gauge.set(1)\n        return gauge",
    "docstring": "Report any information as a Prometheus metric.\n        This will create a `Gauge` with the initial value of 1.\n\n        The easiest way to use it is:\n\n            metrics = PrometheusMetrics(app)\n            metrics.info(\n                'app_info', 'Application info',\n                version='1.0', major=1, minor=0\n            )\n\n        If the order of the labels matters:\n\n            metrics = PrometheusMetrics(app)\n            metrics.info(\n                'app_info', 'Application info',\n                ('version', 'major', 'minor'),\n                ('1.0', 1, 0)\n            )\n\n        :param name: the name of the metric\n        :param description: the description of the metric\n        :param labelnames: the names of the labels\n        :param labelvalues: the values of the labels\n        :param labels: the names and values of the labels\n        :return: the newly created `Gauge` metric"
  },
  {
    "code": "def create_system(self, **system_options):\n        if self.master is None:\n            raise ValueError('Handler {} is not able to create systems.'.format(self))\n        if isinstance(self.master, ForceField):\n            system = self.master.createSystem(self.topology, **system_options)\n        elif isinstance(self.master, (AmberPrmtopFile, GromacsTopFile, DesmondDMSFile)):\n            system = self.master.createSystem(**system_options)\n        elif isinstance(self.master, CharmmPsfFile):\n            if not hasattr(self.master, 'parmset'):\n                raise ValueError('PSF topology files require Charmm parameters.')\n            system = self.master.createSystem(self.master.parmset, **system_options)\n        else:\n            raise NotImplementedError('Handler {} is not able to create systems.'.format(self))\n        if self.has_box:\n            system.setDefaultPeriodicBoxVectors(*self.box)\n        return system",
    "docstring": "Create an OpenMM system for every supported topology file with given system options"
  },
  {
    "code": "def delete_events(\n        self,\n        project_name,\n        retry=google.api_core.gapic_v1.method.DEFAULT,\n        timeout=google.api_core.gapic_v1.method.DEFAULT,\n        metadata=None,\n    ):\n        if \"delete_events\" not in self._inner_api_calls:\n            self._inner_api_calls[\n                \"delete_events\"\n            ] = google.api_core.gapic_v1.method.wrap_method(\n                self.transport.delete_events,\n                default_retry=self._method_configs[\"DeleteEvents\"].retry,\n                default_timeout=self._method_configs[\"DeleteEvents\"].timeout,\n                client_info=self._client_info,\n            )\n        request = error_stats_service_pb2.DeleteEventsRequest(project_name=project_name)\n        if metadata is None:\n            metadata = []\n        metadata = list(metadata)\n        try:\n            routing_header = [(\"project_name\", project_name)]\n        except AttributeError:\n            pass\n        else:\n            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(\n                routing_header\n            )\n            metadata.append(routing_metadata)\n        return self._inner_api_calls[\"delete_events\"](\n            request, retry=retry, timeout=timeout, metadata=metadata\n        )",
    "docstring": "Deletes all error events of a given project.\n\n        Example:\n            >>> from google.cloud import errorreporting_v1beta1\n            >>>\n            >>> client = errorreporting_v1beta1.ErrorStatsServiceClient()\n            >>>\n            >>> project_name = client.project_path('[PROJECT]')\n            >>>\n            >>> response = client.delete_events(project_name)\n\n        Args:\n            project_name (str): [Required] The resource name of the Google Cloud Platform project.\n                Written as ``projects/`` plus the `Google Cloud Platform project\n                ID <https://support.google.com/cloud/answer/6158840>`__. Example:\n                ``projects/my-project-123``.\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.errorreporting_v1beta1.types.DeleteEventsResponse` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def restrict_to_dtype(dtype, message_template):\n    def processor(term_method, _, term_instance):\n        term_dtype = term_instance.dtype\n        if term_dtype != dtype:\n            raise TypeError(\n                message_template.format(\n                    method_name=term_method.__name__,\n                    expected_dtype=dtype.name,\n                    received_dtype=term_dtype,\n                )\n            )\n        return term_instance\n    return preprocess(self=processor)",
    "docstring": "A factory for decorators that restrict Term methods to only be callable on\n    Terms with a specific dtype.\n\n    This is conceptually similar to\n    zipline.utils.input_validation.expect_dtypes, but provides more flexibility\n    for providing error messages that are specifically targeting Term methods.\n\n    Parameters\n    ----------\n    dtype : numpy.dtype\n        The dtype on which the decorated method may be called.\n    message_template : str\n        A template for the error message to be raised.\n        `message_template.format` will be called with keyword arguments\n        `method_name`, `expected_dtype`, and `received_dtype`.\n\n    Examples\n    --------\n    @restrict_to_dtype(\n        dtype=float64_dtype,\n        message_template=(\n            \"{method_name}() was called on a factor of dtype {received_dtype}.\"\n            \"{method_name}() requires factors of dtype{expected_dtype}.\"\n\n        ),\n    )\n    def some_factor_method(self, ...):\n        self.stuff_that_requires_being_float64(...)"
  },
  {
    "code": "def getRequest(self):\n        ars = self.getLinkedRequests()\n        if len(ars) > 1:\n            ar_ids = \", \".join(map(api.get_id, ars))\n            logger.info(\"Attachment assigned to more than one AR: [{}]. \"\n                        \"The first AR will be returned\".format(ar_ids))\n        if len(ars) >= 1:\n            return ars[0]\n        analysis = self.getAnalysis()\n        if IRequestAnalysis.providedBy(analysis):\n            return analysis.getRequest()\n        return None",
    "docstring": "Return the primary AR this attachment is linked"
  },
  {
    "code": "def get_by_id(self, id_networkv6):\n        uri = 'api/networkv4/%s/' % id_networkv6\n        return super(ApiNetworkIPv6, self).get(uri)",
    "docstring": "Get IPv6 network\n\n        :param id_networkv4: ID for NetworkIPv6\n\n        :return: IPv6 Network"
  },
  {
    "code": "def keep_tc_pos(func):\n    @functools.wraps(func)\n    def wrapper(editor, *args, **kwds):\n        sb = editor.verticalScrollBar()\n        spos = sb.sliderPosition()\n        pos = editor.textCursor().position()\n        retval = func(editor, *args, **kwds)\n        text_cursor = editor.textCursor()\n        text_cursor.setPosition(pos)\n        editor.setTextCursor(text_cursor)\n        sb.setSliderPosition(spos)\n        return retval\n    return wrapper",
    "docstring": "Cache text cursor position and restore it when the wrapped\n    function exits.\n\n    This decorator can only be used on modes or panels.\n\n    :param func: wrapped function"
  },
  {
    "code": "def optimize(exp_rets, covs):\n    _cov_inv = np.linalg.inv(covs)        \n    _u = np.ones((len(exp_rets)))\n    _u_cov_inv = _u.dot(_cov_inv)\n    _rets_cov_inv = exp_rets.dot(_cov_inv)\n    _m = np.empty((2, 2))\n    _m[0, 0] = _rets_cov_inv.dot(exp_rets)\n    _m[0, 1] = _u_cov_inv.dot(exp_rets)\n    _m[1, 0] = _rets_cov_inv.dot(_u)\n    _m[1, 1] = _u_cov_inv.dot(_u)\n    _m_inv = np.linalg.inv(_m)\n    a = _m_inv[0, 0] * _rets_cov_inv + _m_inv[1, 0] * _u_cov_inv\n    b = _m_inv[0, 1] * _rets_cov_inv + _m_inv[1, 1] * _u_cov_inv\n    least_risk_ret = _m[0, 1] / _m[1, 1]\n    return a, b, least_risk_ret",
    "docstring": "Return parameters for portfolio optimization.\n\n    Parameters\n    ----------\n    exp_rets : ndarray\n        Vector of expected returns for each investment..\n    covs : ndarray\n        Covariance matrix for the given investments.\n\n    Returns\n    ---------\n    a : ndarray\n        The first vector (to be combined with target return as scalar)\n        in the linear equation for optimal weights.\n    b : ndarray\n        The second (constant) vector in the linear equation for\n        optimal weights.\n    least_risk_ret : int\n        The return achieved on the portfolio that combines the given\n        equities so as to achieve the lowest possible risk.\n\n    Notes\n    ---------\n    *   The length of `exp_rets` must match the number of rows\n        and columns in the `covs` matrix.\n    *   The weights for an optimal portfolio with expected return\n        `ret` is given by the formula `w = ret * a + b` where `a`\n        and `b` are the vectors returned here. The weights `w` for\n        the portfolio with lowest risk are given by `w = least_risk_ret * a + b`.\n    *   An exception will be raised if the covariance matrix\n        is singular or if each prospective investment has the\n        same expected return."
  },
  {
    "code": "def _serialize(self, uri, node):\n        meta = self._decode_meta(node['meta'], is_published=bool(node['is_published']))\n        return {\n            'uri': uri.clone(ext=node['plugin'], version=node['version']),\n            'content': node['content'],\n            'meta': meta\n        }",
    "docstring": "Serialize node result as dict"
  },
  {
    "code": "def cache_key(self, request, method=None):\n        if method is None:\n            method = request.method\n        return \"bettercache_page:%s:%s\" %(request.build_absolute_uri(), method)",
    "docstring": "the cache key is the absolute uri and the request method"
  },
  {
    "code": "def image_server_response(self, api_version=None):\n        headers = dict(self.headers)\n        if (api_version < '1.1'):\n            headers['Content-Type'] = 'text/xml'\n            response = self.as_xml()\n        else:\n            headers['Content-Type'] = 'text/plain'\n            response = self.as_txt()\n        return(response, self.code, headers)",
    "docstring": "Response, code and headers for image server error response.\n\n        api_version selects the format (XML of 1.0). The return value is\n        a tuple of\n          response - body of HTTP response\n          status - the HTTP status code\n          headers - a dict of HTTP headers which will include the Content-Type\n\n        As a side effect the routine sets self.content_type\n        to the correct media type for the response."
  },
  {
    "code": "def get_plugins(modules, classobj):\n    for module in modules:\n        for plugin in get_module_plugins(module, classobj):\n            yield plugin",
    "docstring": "Find all class objects in all modules.\n    @param modules: the modules to search\n    @ptype modules: iterator of modules\n    @return: found classes\n    @rytpe: iterator of class objects"
  },
  {
    "code": "def _get_partial(name, partials_dict, partials_path, partials_ext):\n    try:\n        return partials_dict[name]\n    except KeyError:\n        try:\n            path_ext = ('.' + partials_ext if partials_ext else '')\n            path = partials_path + '/' + name + path_ext\n            with io.open(path, 'r', encoding='utf-8') as partial:\n                return partial.read()\n        except IOError:\n            return ''",
    "docstring": "Load a partial"
  },
  {
    "code": "def start(vm_name, call=None):\n    if call != 'action':\n        raise SaltCloudSystemExit(\n            'The start action must be called with -a or --action.'\n        )\n    conn = get_conn()\n    __utils__['cloud.fire_event'](\n        'event',\n        'start instance',\n        'salt/cloud/{0}/starting'.format(vm_name),\n        args={'name': vm_name},\n        sock_dir=__opts__['sock_dir'],\n        transport=__opts__['transport']\n    )\n    result = conn.ex_start_node(\n        conn.ex_get_node(vm_name)\n    )\n    __utils__['cloud.fire_event'](\n        'event',\n        'start instance',\n        'salt/cloud/{0}/started'.format(vm_name),\n        args={'name': vm_name},\n        sock_dir=__opts__['sock_dir'],\n        transport=__opts__['transport']\n    )\n    return result",
    "docstring": "Call GCE 'start on the instance.\n\n    .. versionadded:: 2017.7.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -a start myinstance"
  },
  {
    "code": "def to_arrow_schema(schema):\n    import pyarrow as pa\n    fields = [pa.field(field.name, to_arrow_type(field.dataType), nullable=field.nullable)\n              for field in schema]\n    return pa.schema(fields)",
    "docstring": "Convert a schema from Spark to Arrow"
  },
  {
    "code": "def detect_django_settings():\n    matches = []\n    for root, dirnames, filenames in os.walk(os.getcwd()):\n        for filename in fnmatch.filter(filenames, '*settings.py'):\n            full = os.path.join(root, filename)\n            if 'site-packages' in full:\n                continue\n            full = os.path.join(root, filename)\n            package_path = full.replace(os.getcwd(), '')\n            package_module = package_path.replace(os.sep, '.').split('.', 1)[1].replace('.py', '')\n            matches.append(package_module)\n    return matches",
    "docstring": "Automatically try to discover Django settings files,\n    return them as relative module paths."
  },
  {
    "code": "def passive_aggressive_train(self):\n\t\tself._clf = PassiveAggressiveClassifier(n_iter=50, C=0.2, n_jobs=-1, random_state=0)\n\t\tself._clf.fit(self._term_doc_matrix._X, self._term_doc_matrix._y)\n\t\ty_dist = self._clf.decision_function(self._term_doc_matrix._X)\n\t\tpos_ecdf = ECDF(y_dist[y_dist >= 0])\n\t\tneg_ecdf = ECDF(y_dist[y_dist <= 0])\n\t\tdef proba_function(distance_from_hyperplane):\n\t\t\tif distance_from_hyperplane > 0:\n\t\t\t\treturn pos_ecdf(distance_from_hyperplane) / 2. + 0.5\n\t\t\telif distance_from_hyperplane < 0:\n\t\t\t\treturn pos_ecdf(distance_from_hyperplane) / 2.\n\t\t\treturn 0.5\n\t\tself._proba = proba_function\n\t\treturn self",
    "docstring": "Trains passive aggressive classifier"
  },
  {
    "code": "def compile_less(input_file, output_file):\n    from .modules import less\n    if not isinstance(input_file, str):\n        raise RuntimeError('LESS compiler takes only a single input file.')\n    return {\n        'dependencies_fn': less.less_dependencies,\n        'compiler_fn': less.less_compile,\n        'input': input_file,\n        'output': output_file,\n        'kwargs': {},\n    }",
    "docstring": "Compile a LESS source file. Minifies the output in release mode."
  },
  {
    "code": "def CMN(self, params):\n        Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params)\n        self.check_arguments(low_registers=(Ra, Rb))\n        def CMN_func():\n            self.set_NZCV_flags(self.register[Ra], self.register[Rb],\n                                self.register[Ra] + self.register[Rb], 'add')\n        return CMN_func",
    "docstring": "CMN Ra, Rb\n\n        Add the two registers and set the NZCV flags\n        The result is discarded\n        Ra and Rb must be low registers"
  },
  {
    "code": "def create_book(self, name):\n        name = name.strip()\n        if not len(name):\n            self.error(\"Cannot have a blank book name\")\n        if name.find(\",\") >= 0:\n            self.error(\"Cannot have a ',' in a book name\")\n        existing = self.list_books()\n        nexisting = len(existing)\n        if name in existing:\n            self.error(\"Already have a book named '%s'\" % name)\n        try:\n            self.cur.execute(\"INSERT INTO book (number, name) VALUES(?, ?);\", (nexisting, name))\n            self.con.commit()\n        except:\n            self.fyi(\"Error adding a book named '%s'\" % name)",
    "docstring": "Create a new book"
  },
  {
    "code": "def Decorate(cls, class_name, member, parent_member):\n    if isinstance(member, property):\n      fget = cls.DecorateMethod(class_name, member.fget, parent_member)\n      fset = None\n      if member.fset:\n        fset = cls.DecorateMethod(class_name, member.fset, parent_member)\n      fdel = None\n      if member.fdel:\n        fdel = cls.DecorateMethod(class_name, member.fdel, parent_member)\n      return property(fget, fset, fdel, member.__doc__)\n    else:\n      return cls.DecorateMethod(class_name, member, parent_member)",
    "docstring": "Decorates a member with @typecheck. Inherit checks from parent member."
  },
  {
    "code": "def get_score_system_id(self):\n        if not bool(self._my_map['scoreSystemId']):\n            raise errors.IllegalState('this AssessmentOffered has no score_system')\n        else:\n            return Id(self._my_map['scoreSystemId'])",
    "docstring": "Gets the grade system ``Id`` for the score.\n\n        return: (osid.id.Id) - the grade system ``Id``\n        raise:  IllegalState - ``is_scored()`` is ``false``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def read_only_s3_bucket_policy_statements(buckets, folder=\"*\"):\n    list_buckets = [s3_arn(b) for b in buckets]\n    object_buckets = [s3_objects_arn(b, folder) for b in buckets]\n    bucket_resources = list_buckets + object_buckets\n    return [\n        Statement(\n            Effect=Allow,\n            Resource=[s3_arn(\"*\")],\n            Action=[s3.ListAllMyBuckets]\n        ),\n        Statement(\n            Effect=Allow,\n            Resource=bucket_resources,\n            Action=[Action('s3', 'Get*'), Action('s3', 'List*')]\n        )\n    ]",
    "docstring": "Read only policy an s3 bucket."
  },
  {
    "code": "def run_callbacks(obj, log=None):\n    def run_callback(callback, args):\n        return callback(*args)\n    return walk_callbacks(obj, run_callback, log)",
    "docstring": "Run callbacks."
  },
  {
    "code": "def bulk(self, actions, stats_only=False, **kwargs):\n        success, failed = es_helpers.bulk(self.client, actions, stats_only, **kwargs)\n        logger.info('Bulk is done success %s failed %s actions: \\n %s' % (success, failed, actions))",
    "docstring": "Executes bulk api by elasticsearch.helpers.bulk.\n\n        :param actions: iterator containing the actions\n        :param stats_only:if `True` only report number of successful/failed\n        operations instead of just number of successful and a list of error responses\n        Any additional keyword arguments will be passed to\n        :func:`~elasticsearch.helpers.streaming_bulk` which is used to execute\n        the operation, see :func:`~elasticsearch.helpers.streaming_bulk` for more\n        accepted parameters."
  },
  {
    "code": "def iter_following(username, number=-1, etag=None):\n    return gh.iter_following(username, number, etag) if username else []",
    "docstring": "List the people ``username`` follows.\n\n    :param str username: (required), login of the user\n    :param int number: (optional), number of users being followed by username\n        to return. Default: -1, return all of them\n    :param str etag: (optional), ETag from a previous request to the same\n        endpoint\n    :returns: generator of :class:`User <github3.users.User>`"
  },
  {
    "code": "def get_records(self, ids):\n        return self.query(Ids(values=[str(id_) for id_ in ids]))",
    "docstring": "Return records by their identifiers.\n\n        :param ids: A list of record identifier.\n        :returns: A list of records."
  },
  {
    "code": "def convert_to_cgs(self, equivalence=None, **kwargs):\n        self.convert_to_units(\n            self.units.get_cgs_equivalent(), equivalence=equivalence, **kwargs\n        )",
    "docstring": "Convert the array and in-place to the equivalent cgs units.\n\n        Optionally, an equivalence can be specified to convert to an\n        equivalent quantity which is not in the same dimensions.\n\n        Parameters\n        ----------\n        equivalence : string, optional\n            The equivalence you wish to use. To see which equivalencies\n            are supported for this object, try the ``list_equivalencies``\n            method. Default: None\n        kwargs: optional\n            Any additional keyword arguments are supplied to the equivalence\n\n        Raises\n        ------\n        If the provided unit does not have the same dimensions as the array\n        this will raise a UnitConversionError\n\n        Examples\n        --------\n        >>> from unyt import Newton\n        >>> data = [1., 2., 3.]*Newton\n        >>> data.convert_to_cgs()\n        >>> data\n        unyt_array([100000., 200000., 300000.], 'dyn')"
  },
  {
    "code": "def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,\n            password=None):\n    if master_host and not master_port:\n        master_port = 6379\n    server = _connect(host, port, db, password)\n    return server.slaveof(master_host, master_port)",
    "docstring": "Make the server a slave of another instance, or promote it as master\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        # Become slave of redis-n01.example.com:6379\n        salt '*' redis.slaveof redis-n01.example.com 6379\n        salt '*' redis.slaveof redis-n01.example.com\n        # Become master\n        salt '*' redis.slaveof"
  },
  {
    "code": "def subdomains_init(blockstack_opts, working_dir, atlas_state):\n    if not is_subdomains_enabled(blockstack_opts):\n        return None\n    subdomain_state = SubdomainIndex(blockstack_opts['subdomaindb_path'], blockstack_opts=blockstack_opts)\n    atlas_node_add_callback(atlas_state, 'store_zonefile', subdomain_state.enqueue_zonefile)\n    return subdomain_state",
    "docstring": "Set up subdomain state\n    Returns a SubdomainIndex object that has been successfully connected to Atlas"
  },
  {
    "code": "def createHorizonPolygons(self):\n        vertsTop = [[-1,0],[-1,1],[1,1],[1,0],[-1,0]]\n        self.topPolygon = Polygon(vertsTop,facecolor='dodgerblue',edgecolor='none')\n        self.axes.add_patch(self.topPolygon)\n        vertsBot = [[-1,0],[-1,-1],[1,-1],[1,0],[-1,0]]\n        self.botPolygon = Polygon(vertsBot,facecolor='brown',edgecolor='none')\n        self.axes.add_patch(self.botPolygon)",
    "docstring": "Creates the two polygons to show the sky and ground."
  },
  {
    "code": "def prox_yline(y, step):\n    if not np.isscalar(y):\n        y= y[0]\n    if y > -0.75:\n        return np.array([-0.75])\n    else:\n        return np.array([y])",
    "docstring": "Projection onto line in y"
  },
  {
    "code": "def get_user_permissions(self, user_id):\n        permissions = self.user_service.getPermissions(id=user_id)\n        return sorted(permissions, key=itemgetter('keyName'))",
    "docstring": "Returns a sorted list of a users permissions"
  },
  {
    "code": "def execute(self):\n        if self.direct:\n            if self.file_type == 'pdf':\n                raise IOError(u\"Direct output mode is not available for PDF \"\n                               \"export\")\n            else:\n                print(self.render().encode(self.encoding))\n        else:\n            self.write_and_log()\n            if self.watch:\n                from landslide.watcher import watch\n                self.log(u\"Watching %s\\n\" % self.watch_dir)\n                watch(self.watch_dir, self.write_and_log)",
    "docstring": "Execute this generator regarding its current configuration."
  },
  {
    "code": "def is_cidr_in_cidr(small_cidr, big_cidr):\n    if small_cidr == \"0.0.0.0/0\":\n        return big_cidr == \"0.0.0.0/0\"\n    else:\n        if big_cidr == \"0.0.0.0/0\":\n            return False\n    s = ipaddress.IPv4Network(unicode(small_cidr))\n    b = ipaddress.IPv4Network(unicode(big_cidr))\n    return s.subnet_of(b)",
    "docstring": "Return True if the small CIDR is contained in the big CIDR."
  },
  {
    "code": "def fit_lsq(self, df):\n        tdf = df.set_index('div')\n        return tdf.ix['1,1']['n_spp'], tdf.ix['1,1']['n_individs']",
    "docstring": "Parameterize generic SAR curve from empirical data set\n\n        Parameters\n        ----------\n        df : DataFrame\n            Result data frame from empirical SAR analysis\n\n        Notes\n        -----\n        Simply returns S0 and N0 from empirical SAR output, which are two fixed\n        parameters of METE SAR and EAR. This simply returns n_spp and\n        n_individs from the 1,1 division in\n        the dataframe. An error will be thrown if this division is not present\n        The ``fit_lsq`` is retained for consistency with other curves."
  },
  {
    "code": "def get_peer_id(peer, add_mark=True):\n    if isinstance(peer, int):\n        return peer if add_mark else resolve_id(peer)[0]\n    if isinstance(peer, types.InputPeerSelf):\n        _raise_cast_fail(peer, 'int (you might want to use client.get_peer_id)')\n    try:\n        peer = get_peer(peer)\n    except TypeError:\n        _raise_cast_fail(peer, 'int')\n    if isinstance(peer, types.PeerUser):\n        return peer.user_id\n    elif isinstance(peer, types.PeerChat):\n        if not (0 < peer.chat_id <= 0x7fffffff):\n            peer.chat_id = resolve_id(peer.chat_id)[0]\n        return -peer.chat_id if add_mark else peer.chat_id\n    else:\n        if not (0 < peer.channel_id <= 0x7fffffff):\n            peer.channel_id = resolve_id(peer.channel_id)[0]\n        if not add_mark:\n            return peer.channel_id\n        return -(peer.channel_id + pow(\n            10, math.floor(math.log10(peer.channel_id) + 3)))",
    "docstring": "Finds the ID of the given peer, and converts it to the \"bot api\" format\n    so it the peer can be identified back. User ID is left unmodified,\n    chat ID is negated, and channel ID is prefixed with -100.\n\n    The original ID and the peer type class can be returned with\n    a call to :meth:`resolve_id(marked_id)`."
  },
  {
    "code": "def _eval_model(self):\n        arguments = self._x_grid.copy()\n        arguments.update({param: param.value for param in self.model.params})\n        return self.model(**key2str(arguments))",
    "docstring": "Convenience method for evaluating the model with the current parameters\n\n        :return: named tuple with results"
  },
  {
    "code": "def clean_time(self, time):\n        if isinstance(time, int):\n            time = datetime.utcfromtimestamp(time)\n        elif isinstance(time, str):\n            time = parser.parse(time)\n        return time",
    "docstring": "Transform time field to datetime object if there is any."
  },
  {
    "code": "def _ToString(x):\n    if x is None:\n        return 'null'\n    if isinstance(x, six.string_types):\n        return x\n    return pprint.pformat(x)",
    "docstring": "The default default formatter!."
  },
  {
    "code": "def gather_commands(self, ingredient):\n        for command_name, command in ingredient.commands.items():\n            yield join_paths(ingredient.path, command_name), command",
    "docstring": "Collect all commands from this ingredient and its sub-ingredients.\n\n        Yields\n        ------\n        cmd_name: str\n            The full (dotted) name of the command.\n        cmd: function\n            The corresponding captured function."
  },
  {
    "code": "def run_snr(self):\n        if self.ecc:\n            required_kwargs = {'dist_type': self.dist_type,\n                               'initial_cond_type': self.initial_cond_type,\n                               'ecc': True}\n            input_args = [self.m1, self.m2, self.z_or_dist, self.initial_point,\n                          self.eccentricity, self.observation_time]\n        else:\n            required_kwargs = {'dist_type': self.dist_type}\n            input_args = [self.m1, self.m2, self.spin_1, self.spin_2,\n                          self.z_or_dist, self.start_time, self.end_time]\n        input_kwargs = {**required_kwargs,\n                        **self.general,\n                        **self.sensitivity_input,\n                        **self.snr_input,\n                        **self.parallel_input}\n        self.final_dict = snr(*input_args, **input_kwargs)\n        return",
    "docstring": "Run the snr calculation.\n\n        Takes results from ``self.set_parameters`` and other inputs and inputs these\n        into the snr calculator."
  },
  {
    "code": "def rebalance_brokers(self):\n        for rg in six.itervalues(self.cluster_topology.rgs):\n            rg.rebalance_brokers()",
    "docstring": "Rebalance partition-count across brokers within each replication-group."
  },
  {
    "code": "def log_setup(debug_bool):\n    level = logging.DEBUG if debug_bool else logging.INFO\n    logging.config.dictConfig(\n        {\n            \"version\": 1,\n            \"disable_existing_loggers\": False,\n            \"formatters\": {\n                \"verbose\": {\n                    \"format\": \"%(asctime)s %(levelname)-8s %(name)s %(module)s \"\n                    \"%(process)d %(thread)d %(message)s\",\n                    \"datefmt\": \"%Y-%m-%d %H:%M:%S\",\n                }\n            },\n            \"handlers\": {\n                \"console\": {\n                    \"class\": \"logging.StreamHandler\",\n                    \"formatter\": \"verbose\",\n                    \"level\": level,\n                    \"stream\": \"ext://sys.stdout\",\n                }\n            },\n            \"loggers\": {\n                \"\": {\n                    \"handlers\": [\"console\"],\n                    \"level\": level,\n                    \"class\": \"logging.StreamHandler\",\n                }\n            },\n        }\n    )",
    "docstring": "Set up logging.\n\n    We output only to stdout. Instead of also writing to a log file, redirect stdout to\n    a log file when the script is executed from cron."
  },
  {
    "code": "def login(self, username, password, limit=10, sync=True, device_id=None):\n        response = self.api.login(\n            \"m.login.password\", user=username, password=password, device_id=device_id\n        )\n        self.user_id = response[\"user_id\"]\n        self.token = response[\"access_token\"]\n        self.hs = response[\"home_server\"]\n        self.api.token = self.token\n        self.device_id = response[\"device_id\"]\n        if self._encryption:\n            self.olm_device = OlmDevice(\n                self.api, self.user_id, self.device_id, **self.encryption_conf)\n            self.olm_device.upload_identity_keys()\n            self.olm_device.upload_one_time_keys()\n        if sync:\n            self.sync_filter = '{ \"room\": { \"timeline\" : { \"limit\" : %i } } }' % limit\n            self._sync()\n        return self.token",
    "docstring": "Login to the homeserver.\n\n        Args:\n            username (str): Account username\n            password (str): Account password\n            limit (int): Deprecated. How many messages to return when syncing.\n                This will be replaced by a filter API in a later release.\n            sync (bool): Optional. Whether to initiate a /sync request after logging in.\n            device_id (str): Optional. ID of the client device. The server will\n                auto-generate a device_id if this is not specified.\n\n        Returns:\n            str: Access token\n\n        Raises:\n            MatrixRequestError"
  },
  {
    "code": "def serialized_task(self, task: Task) -> Tuple[str, str]:\n        return f\"{task.hash}.json\", task.json",
    "docstring": "Returns the name of the task definition file and its contents."
  },
  {
    "code": "def map_aliases_to_device_objects(self):\n        all_devices = self.get_all_devices_in_portal()\n        for dev_o in all_devices:\n            dev_o['portals_aliases'] = self.get_portal_by_name(\n                                                        self.portal_name()\n                                                )[2][1]['info']['aliases'][ dev_o['rid'] ]\n        return all_devices",
    "docstring": "A device object knows its rid, but not its alias.\n            A portal object knows its device rids and aliases.\n\n            This function adds an 'portals_aliases' key to all of the \n            device objects so they can be sorted by alias."
  },
  {
    "code": "def remove_subkey(self, subkey):\n        if len(self.subkeys) > 0:\n            key = subkey if isinstance(subkey, str) else subkey.key\n            for i in range(len(self.subkeys)):\n                if self.subkeys[i].key == key:\n                    self.subkeys.pop(i)\n                    break",
    "docstring": "Remove the given subkey, if existed, from this AdfKey.\n\n        Parameters\n        ----------\n        subkey : str or AdfKey\n            The subkey to remove."
  },
  {
    "code": "async def mutation_resolver(self, mutation_name, args, fields):\n        try:\n            mutation_summary = [mutation for mutation in \\\n                                            self._external_service_data['mutations'] \\\n                                            if mutation['name'] == mutation_name][0]\n        except KeyError as e:\n            raise ValueError(\"Could not execute mutation named: \" + mutation_name)\n        event_function = self.event_broker.ask\n        value =  await event_function(\n            action_type=mutation_summary['event'],\n            payload=args\n        )\n        try:\n            return json.loads(value)\n        except json.decoder.JSONDecodeError:\n            raise RuntimeError(value)",
    "docstring": "the default behavior for mutations is to look up the event,\n            publish the correct event type with the args as the body,\n            and return the fields contained in the result"
  },
  {
    "code": "def post_process(self, indices):\n        array = javabridge.call(self.jobject, \"postProcess\", \"([I)[I\", indices)\n        if array is None:\n            return None\n        else:\n            return javabridge.get_env().get_int_array_elements(array)",
    "docstring": "Post-processes the evaluator with the selected attribute indices.\n\n        :param indices: the attribute indices list to use\n        :type indices: ndarray\n        :return: the processed indices\n        :rtype: ndarray"
  },
  {
    "code": "def from_traverse(cls, traverse_block):\n        if isinstance(traverse_block, Traverse):\n            return cls(traverse_block.direction, traverse_block.edge_name)\n        else:\n            raise AssertionError(u'Tried to initialize an instance of GremlinFoldedTraverse '\n                                 u'with block of type {}'.format(type(traverse_block)))",
    "docstring": "Create a GremlinFoldedTraverse block as a copy of the given Traverse block."
  },
  {
    "code": "def set_eng_float_format(accuracy=3, use_eng_prefix=False):\n    set_option(\"display.float_format\", EngFormatter(accuracy, use_eng_prefix))\n    set_option(\"display.column_space\", max(12, accuracy + 9))",
    "docstring": "Alter default behavior on how float is formatted in DataFrame.\n    Format float in engineering format. By accuracy, we mean the number of\n    decimal digits after the floating point.\n\n    See also EngFormatter."
  },
  {
    "code": "def is_valid(self):\n        if not isinstance(self._expiration, datetime.datetime):\n            raise InvalidArgumentError('Expiration datetime must be specified.')\n        if 'key' not in self.form_data:\n            raise InvalidArgumentError('object key must be specified.')\n        if 'bucket' not in self.form_data:\n            raise InvalidArgumentError('bucket name must be specified.')",
    "docstring": "Validate for required parameters."
  },
  {
    "code": "def stream_bytes(data, chunk_size=default_chunk_size):\n    stream = BytesStream(data, chunk_size=chunk_size)\n    return stream.body(), stream.headers",
    "docstring": "Gets a buffered generator for streaming binary data.\n\n    Returns a buffered generator which encodes binary data as\n    :mimetype:`multipart/form-data` with the corresponding headers.\n\n    Parameters\n    ----------\n    data : bytes\n        The data bytes to stream\n    chunk_size : int\n        The maximum size of each stream chunk\n\n    Returns\n    -------\n        (generator, dict)"
  },
  {
    "code": "def _raise_error_if_column_exists(dataset, column_name = 'dataset',\n                            dataset_variable_name = 'dataset',\n                            column_name_error_message_name = 'column_name'):\n    err_msg = 'The SFrame {0} must contain the column {1}.'.format(\n                                                dataset_variable_name,\n                                             column_name_error_message_name)\n    if column_name not in dataset.column_names():\n      raise ToolkitError(str(err_msg))",
    "docstring": "Check if a column exists in an SFrame with error message."
  },
  {
    "code": "def add_gemini_query(self, name, query):\n        logger.info(\"Adding query {0} with text {1}\".format(name, query))\n        new_query = GeminiQuery(name=name, query=query)\n        self.session.add(new_query)\n        self.save()\n        return new_query",
    "docstring": "Add a user defined gemini query\n\n        Args:\n            name (str)\n            query (str)"
  },
  {
    "code": "def plot(self, dimension):\n        import matplotlib.pyplot as plt\n        life_lines = self.get_life_lines(dimension)\n        x, y = zip(*life_lines)\n        plt.scatter(x, y)\n        plt.xlabel(\"Birth\")\n        plt.ylabel(\"Death\")\n        if self.max_life is not None:\n            plt.xlim([0, self.max_life])\n        plt.title(\"Persistence Homology Dimension {}\".format(dimension))\n        plt.show()",
    "docstring": "Plot barcode using matplotlib."
  },
  {
    "code": "def send_frame(self, frame):\n        if self.closed:\n            if self.close_info and len(self.close_info['reply_text']) > 0:\n                raise ChannelClosed(\n                    \"channel %d is closed: %s : %s\",\n                    self.channel_id,\n                    self.close_info['reply_code'],\n                    self.close_info['reply_text'])\n            raise ChannelClosed()\n        if not len(self._pending_events):\n            if not self._active and \\\n                    isinstance(frame, (ContentFrame, HeaderFrame)):\n                raise Channel.Inactive(\n                    \"Channel %d flow control activated\", self.channel_id)\n            self._connection.send_frame(frame)\n        else:\n            self._pending_events.append(frame)",
    "docstring": "Queue a frame for sending.  Will send immediately if there are no\n        pending synchronous transactions on this connection."
  },
  {
    "code": "def add_vhost(vhost, runas=None):\n    if runas is None and not salt.utils.platform.is_windows():\n        runas = salt.utils.user.get_user()\n    res = __salt__['cmd.run_all'](\n        [RABBITMQCTL, 'add_vhost', vhost],\n        reset_system_locale=False,\n        runas=runas,\n        python_shell=False)\n    msg = 'Added'\n    return _format_response(res, msg)",
    "docstring": "Adds a vhost via rabbitmqctl add_vhost.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' rabbitmq add_vhost '<vhost_name>'"
  },
  {
    "code": "def load_wav(path, mono=True):\n    fs, audio_data = scipy.io.wavfile.read(path)\n    if audio_data.dtype == 'int8':\n        audio_data = audio_data/float(2**8)\n    elif audio_data.dtype == 'int16':\n        audio_data = audio_data/float(2**16)\n    elif audio_data.dtype == 'int32':\n        audio_data = audio_data/float(2**24)\n    else:\n        raise ValueError('Got unexpected .wav data type '\n                         '{}'.format(audio_data.dtype))\n    if mono and audio_data.ndim != 1:\n        audio_data = audio_data.mean(axis=1)\n    return audio_data, fs",
    "docstring": "Loads a .wav file as a numpy array using ``scipy.io.wavfile``.\n\n    Parameters\n    ----------\n    path : str\n        Path to a .wav file\n    mono : bool\n        If the provided .wav has more than one channel, it will be\n        converted to mono if ``mono=True``. (Default value = True)\n\n    Returns\n    -------\n    audio_data : np.ndarray\n        Array of audio samples, normalized to the range [-1., 1.]\n    fs : int\n        Sampling rate of the audio data"
  },
  {
    "code": "def get_monotone_constraints(self):\n        if self.monotone_constraints is None:\n            self.monotone_constraints = self.get_field('monotone_constraints')\n        return self.monotone_constraints",
    "docstring": "Get the monotone constraints of the Dataset.\n\n        Returns\n        -------\n        monotone_constraints : numpy array or None\n            Monotone constraints: -1, 0 or 1, for each feature in the Dataset."
  },
  {
    "code": "def create_bmi_config_file(self, filename: str = \"bmi_config.txt\") -> None:\n        s0 = self.construct_default_initial_state()\n        s0.to_csv(filename, index_label=\"variable\")",
    "docstring": "Create a BMI config file to initialize the model.\n\n        Args:\n            filename: The filename with which the config file should be saved."
  },
  {
    "code": "def check_metric(self, metric):\n        if metric not in self.VALID_METRICS:\n            raise ValueError(\n                f\"`{self.__class__.__name__}` does not support the `{metric}` \"\n                f\"metric. Please choose one of the supported metrics: \"\n                f\"{', '.join(self.VALID_METRICS)}.\"\n            )",
    "docstring": "Check that the metric is supported by the KNNIndex instance."
  },
  {
    "code": "def encode(self, data, size):\n        return return_fresh_string(lib.zarmour_encode(self._as_parameter_, data, size))",
    "docstring": "Encode a stream of bytes into an armoured string. Returns the armoured\nstring, or NULL if there was insufficient memory available to allocate\na new string."
  },
  {
    "code": "def ElectronIC(pars, data):\n    ECPL = ExponentialCutoffPowerLaw(\n        pars[0] / u.eV, 10.0 * u.TeV, pars[1], 10 ** pars[2] * u.TeV\n    )\n    IC = InverseCompton(ECPL, seed_photon_fields=[\"CMB\"])\n    return IC.flux(data, distance=1.0 * u.kpc)",
    "docstring": "Define particle distribution model, radiative model, and return model flux\n    at data energy values"
  },
  {
    "code": "def GetDateRange(self):\n    start = self.start_date\n    end = self.end_date\n    for date, (exception_type, _) in self.date_exceptions.items():\n      if exception_type == self._EXCEPTION_TYPE_REMOVE:\n        continue\n      if not start or (date < start):\n        start = date\n      if not end or (date > end):\n        end = date\n    if start is None:\n      start = end\n    elif end is None:\n      end = start\n    return (start, end)",
    "docstring": "Return the range over which this ServicePeriod is valid.\n\n    The range includes exception dates that add service outside of\n    (start_date, end_date), but doesn't shrink the range if exception\n    dates take away service at the edges of the range.\n\n    Returns:\n      A tuple of \"YYYYMMDD\" strings, (start date, end date) or (None, None) if\n      no dates have been given."
  },
  {
    "code": "def read(*components, **kwargs):\n    rstrip = kwargs.get(\"rstrip\", True)\n    comment_char = kwargs.get(\"comment_char\", None)\n    ignore_comments = comment_char is not None\n    file = open(path(*components))\n    lines = file.readlines()\n    file.close()\n    if ignore_comments:\n        comment_line_re = re.compile(\"^\\s*{char}\".format(char=comment_char))\n        not_comment_re = re.compile(\"[^{char}]+\".format(char=comment_char))\n        if rstrip:\n            return [re.match(not_comment_re, line).group(0).rstrip()\n                    for line in lines\n                    if not re.match(comment_line_re, line)]\n        else:\n            return [re.match(not_comment_re, line).group(0)\n                    for line in lines\n                    if not re.match(comment_line_re, line)]\n    elif rstrip:\n        return [line.rstrip() for line in lines]\n    else:\n        return lines",
    "docstring": "Read file and return a list of lines. If comment_char is set, ignore the\n    contents of lines following the comment_char.\n\n    Raises:\n\n        IOError: if reading path fails"
  },
  {
    "code": "def register_plugin(host, plugin):\n    class OriginalMethods(object):\n        def __getattr__(self, name):\n            return lambda *args, **kwargs: getattr(host, name).original(host, *args, **kwargs)\n    if not hasattr(host, \"_plugins\"):\n        host._plugins = [OriginalMethods()]\n    plugin.parent = host._plugins[-1]\n    plugin.host = host\n    host._plugins.append(plugin)",
    "docstring": "Register a plugin with a host object. Some @pluggable methods in the host\n    will have their behaviour altered by the plugin."
  },
  {
    "code": "def setup_logger(log_level, log_file=None):\n    level = getattr(logging, log_level.upper(), None)\n    if not level:\n        color_print(\"Invalid log level: %s\" % log_level, \"RED\")\n        sys.exit(1)\n    if level >= logging.INFO:\n        sys.tracebacklimit = 0\n    formatter = ColoredFormatter(\n        u\"%(log_color)s%(bg_white)s%(levelname)-8s%(reset)s %(message)s\",\n        datefmt=None,\n        reset=True,\n        log_colors=log_colors_config\n    )\n    if log_file:\n        handler = logging.FileHandler(log_file, encoding=\"utf-8\")\n    else:\n        handler = logging.StreamHandler()\n    handler.setFormatter(formatter)\n    logger.addHandler(handler)\n    logger.setLevel(level)",
    "docstring": "setup root logger with ColoredFormatter."
  },
  {
    "code": "def list_keyvaults(access_token, subscription_id, rgname):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/resourcegroups/', rgname,\n                        '/providers/Microsoft.KeyVault/vaults',\n                        '?api-version=', KEYVAULT_API])\n    return do_get_next(endpoint, access_token)",
    "docstring": "Lists key vaults in the named resource group.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n        rgname (str): Azure resource group name.\n\n    Returns:\n        HTTP response. 200 OK."
  },
  {
    "code": "def get_true_capacity(self):\n        c = self.capacity\n        if c is not None:\n            return c\n        else:\n            if self.rooms.count() == 0 and self.activity.default_capacity:\n                return self.activity.default_capacity\n            rooms = self.get_true_rooms()\n            return EighthRoom.total_capacity_of_rooms(rooms)",
    "docstring": "Get the capacity for the scheduled activity, taking into account activity defaults and\n        overrides."
  },
  {
    "code": "def get_group_details(group):\n    result = []\n    for datastore in _get_datastores():\n        value = datastore.get_group_details(group)\n        value['datastore'] = datastore.config['DESCRIPTION']\n        result.append(value)\n    return result",
    "docstring": "Get group details."
  },
  {
    "code": "def _ReadPresetsFromFileObject(self, file_object):\n    yaml_generator = yaml.safe_load_all(file_object)\n    last_preset_definition = None\n    for yaml_definition in yaml_generator:\n      try:\n        preset_definition = self._ReadParserPresetValues(yaml_definition)\n      except errors.MalformedPresetError as exception:\n        error_location = 'At start'\n        if last_preset_definition:\n          error_location = 'After: {0:s}'.format(last_preset_definition.name)\n        raise errors.MalformedPresetError(\n            '{0:s} {1!s}'.format(error_location, exception))\n      yield preset_definition\n      last_preset_definition = preset_definition",
    "docstring": "Reads parser and parser plugin presets from a file-like object.\n\n    Args:\n      file_object (file): file-like object containing the parser and parser\n          plugin presets definitions.\n\n    Yields:\n      ParserPreset: a parser preset.\n\n    Raises:\n      MalformedPresetError: if one or more plugin preset definitions are\n          malformed."
  },
  {
    "code": "def _replace_with_new_dims(\n        self: T,\n        variables: 'OrderedDict[Any, Variable]' = None,\n        coord_names: set = None,\n        attrs: 'Optional[OrderedDict]' = __default,\n        indexes: 'Optional[OrderedDict[Any, pd.Index]]' = __default,\n        inplace: bool = False,\n    ) -> T:\n        dims = dict(calculate_dimensions(variables))\n        return self._replace(\n            variables, coord_names, dims, attrs, indexes, inplace=inplace)",
    "docstring": "Replace variables with recalculated dimensions."
  },
  {
    "code": "def street_address(self, address):\n        address = self.street_addresses([address])\n        if not len(address):\n            return None\n        return Address(address[0])",
    "docstring": "Geocode one and only address, get a single Address object back\n\n        >>> client.street_address(\"100 Main St, Anywhere, USA\")\n        >>> client.street_address({\"street\": \"100 Main St, anywhere USA\"})\n\n        :param address: string or dictionary with street address information\n        :return: an Address object or None for no match"
  },
  {
    "code": "def _check_error(response):\n        if 'error' in response:\n            raise InfluxDBError(response['error'])\n        elif 'results' in response:\n            for statement in response['results']:\n                if 'error' in statement:\n                    msg = '{d[error]} (statement {d[statement_id]})'\n                    raise InfluxDBError(msg.format(d=statement))",
    "docstring": "Checks for JSON error messages and raises Python exception"
  },
  {
    "code": "def _displaystr2num(st):\n    num = None\n    for s, n in [('DFP-', 16), ('TV-', 8), ('CRT-', 0)]:\n        if st.startswith(s):\n            try:\n                curnum = int(st[len(s):])\n                if 0 <= curnum <= 7:\n                    num = n + curnum\n                    break\n            except Exception:\n                pass\n    if num is not None:\n        return num\n    else:\n        raise ValueError('Unrecognised display name: ' + st)",
    "docstring": "Return a display number from a string"
  },
  {
    "code": "def call_state(self, addr, *args, **kwargs):\n        return self.project.simos.state_call(addr, *args, **kwargs)",
    "docstring": "Returns a state object initialized to the start of a given function, as if it were called with given parameters.\n\n        :param addr:            The address the state should start at instead of the entry point.\n        :param args:            Any additional positional arguments will be used as arguments to the function call.\n\n        The following parametrs are optional.\n\n        :param base_state:      Use this SimState as the base for the new state instead of a blank state.\n        :param cc:              Optionally provide a SimCC object to use a specific calling convention.\n        :param ret_addr:        Use this address as the function's return target.\n        :param stack_base:      An optional pointer to use as the top of the stack, circa the function entry point\n        :param alloc_base:      An optional pointer to use as the place to put excess argument data\n        :param grow_like_stack: When allocating data at alloc_base, whether to allocate at decreasing addresses\n        :param toc:             The address of the table of contents for ppc64\n        :param initial_prefix:  If this is provided, all symbolic registers will hold symbolic values with names\n                                prefixed by this string.\n        :param fs:              A dictionary of file names with associated preset SimFile objects.\n        :param concrete_fs:     bool describing whether the host filesystem should be consulted when opening files.\n        :param chroot:          A path to use as a fake root directory, Behaves similarly to a real chroot. Used only\n                                when concrete_fs is set to True.\n        :param kwargs:          Any additional keyword args will be passed to the SimState constructor.\n        :return:                The state at the beginning of the function.\n        :rtype:                 SimState\n\n        The idea here is that you can provide almost any kind of python type in `args` and it'll be translated to a\n        binary format to be placed into simulated memory. Lists (representing arrays) must be entirely elements of the\n        same type and size, while tuples (representing structs) can be elements of any type and size.\n        If you'd like there to be a pointer to a given value, wrap the value in a `SimCC.PointerWrapper`. Any value\n        that can't fit in a register will be automatically put in a\n        PointerWrapper.\n\n        If stack_base is not provided, the current stack pointer will be used, and it will be updated.\n        If alloc_base is not provided, the current stack pointer will be used, and it will be updated.\n        You might not like the results if you provide stack_base but not alloc_base.\n\n        grow_like_stack controls the behavior of allocating data at alloc_base. When data from args needs to be wrapped\n        in a pointer, the pointer needs to point somewhere, so that data is dumped into memory at alloc_base. If you\n        set alloc_base to point to somewhere other than the stack, set grow_like_stack to False so that sequencial\n        allocations happen at increasing addresses."
  },
  {
    "code": "def build_uri(secret, name, initial_count=None, issuer_name=None):\n    is_initial_count_present = (initial_count is not None)\n    otp_type = 'hotp' if is_initial_count_present else 'totp'\n    base = 'otpauth://%s/' % otp_type\n    if issuer_name:\n        issuer_name = quote(issuer_name)\n        base += '%s:' % issuer_name\n    uri = '%(base)s%(name)s?secret=%(secret)s' % {\n        'name': quote(name, safe='@'),\n        'secret': secret,\n        'base': base,\n    }\n    if is_initial_count_present:\n        uri += '&counter=%s' % initial_count\n    if issuer_name:\n        uri += '&issuer=%s' % issuer_name\n    return uri",
    "docstring": "Returns the provisioning URI for the OTP; works for either TOTP or HOTP.\n\n    This can then be encoded in a QR Code and used to provision the Google\n    Authenticator app.\n\n    For module-internal use.\n\n    See also:\n        http://code.google.com/p/google-authenticator/wiki/KeyUriFormat\n\n    @param [String] the hotp/totp secret used to generate the URI\n    @param [String] name of the account\n    @param [Integer] initial_count starting counter value, defaults to None.\n        If none, the OTP type will be assumed as TOTP.\n    @param [String] the name of the OTP issuer; this will be the\n        organization title of the OTP entry in Authenticator\n    @return [String] provisioning uri"
  },
  {
    "code": "def on_show(request, page_name):\n    revision_id = request.args.get(\"rev\", type=int)\n    query = RevisionedPage.query.filter_by(name=page_name)\n    if revision_id:\n        query = query.filter_by(revision_id=revision_id)\n        revision_requested = True\n    else:\n        query = query.order_by(RevisionedPage.revision_id.desc())\n        revision_requested = False\n    page = query.first()\n    if page is None:\n        return page_missing(request, page_name, revision_requested)\n    return Response(generate_template(\"action_show.html\", page=page))",
    "docstring": "Displays the page the user requests."
  },
  {
    "code": "def state(self, new_state: bool):\n    self._lutron.send(Lutron.OP_EXECUTE, Keypad._CMD_TYPE, self._keypad.id,\n                      self.component_number, Led._ACTION_LED_STATE,\n                      int(new_state))\n    self._state = new_state",
    "docstring": "Sets the new led state.\n\n    new_state: bool"
  },
  {
    "code": "def start_worker(which_worker, config={}):\n    if which_worker == 'multi_worker':\n        cls = MultiWorker\n    elif which_worker == 'fork_worker':\n        cls = ForkWorker\n    else:\n        cls = ForkWorker\n    return run_worker(cls, config)",
    "docstring": "Start some worker class.\n\n    :param str which_worker: name of the worker\n    :param dict config: ``rejester`` config block"
  },
  {
    "code": "def deployment_groups(self):\n        if not self.__deployment_groups:\n            self.__deployment_groups = DeploymentGroups(self.__connection)\n        return self.__deployment_groups",
    "docstring": "Gets the Deployment Groups API client.\n\n        Returns:\n            DeploymentGroups:"
  },
  {
    "code": "def loss(self, x_data, y_true):\n        y_pred = self(x_data)\n        return y_pred, self.loss_value(x_data, y_true, y_pred)",
    "docstring": "Forward propagate network and return a value of loss function"
  },
  {
    "code": "def is_multicast(text):\n    try:\n        first = ord(dns.ipv4.inet_aton(text)[0])\n        return (first >= 224 and first <= 239)\n    except Exception:\n        try:\n            first = ord(dns.ipv6.inet_aton(text)[0])\n            return (first == 255)\n        except Exception:\n            raise ValueError",
    "docstring": "Is the textual-form network address a multicast address?\n\n    @param text: the textual address\n    @raises ValueError: the address family cannot be determined from the input.\n    @rtype: bool"
  },
  {
    "code": "def get_logfile_name(tags):\n  if not os.path.exists(sd.LOG_DIR):\n    os.mkdir(sd.LOG_DIR)\n  filename = \"log\"\n  for tag in tags:\n    filename += \"_{}\".format(tag)\n  filename += \".txt\"\n  filename = os.path.join(sd.LOG_DIR,filename)\n  return filename",
    "docstring": "Formulates a log file name that incorporates the provided tags.\n\n  The log file will be located in ``scgpm_seqresults_dnanexus.LOG_DIR``.\n  \n  Args:\n      tags: `list` of tags to append to the log file name. Each tag will be '_' delimited. Each tag\n          will be added in the same order as provided."
  },
  {
    "code": "def no_duplicates_constructor(loader, node, deep=False):\n    mapping = {}\n    for key_node, value_node in node.value:\n        key = loader.construct_object(key_node, deep=deep)\n        value = loader.construct_object(value_node, deep=deep)\n        if key in mapping:\n            from intake.catalog.exceptions import DuplicateKeyError\n            raise DuplicateKeyError(\"while constructing a mapping\",\n                                    node.start_mark,\n                                    \"found duplicate key (%s)\" % key,\n                                    key_node.start_mark)\n        mapping[key] = value\n    return loader.construct_mapping(node, deep)",
    "docstring": "Check for duplicate keys while loading YAML\n\n    https://gist.github.com/pypt/94d747fe5180851196eb"
  },
  {
    "code": "def wifi_status(self):\n        return self._info_json.get(CONST.STATUS, {}).get(CONST.WIFI_LINK)",
    "docstring": "Get the wifi status."
  },
  {
    "code": "def add_object(self, obj, properties=()):\n        self._objects.add(obj)\n        self._properties |= properties\n        self._pairs.update((obj, p) for p in properties)",
    "docstring": "Add an object to the definition and add ``properties`` as related."
  },
  {
    "code": "def create_group(self, trigger):\n        data = self._serialize_object(trigger)\n        return Trigger(self._post(self._service_url(['triggers', 'groups']), data))",
    "docstring": "Create a new group trigger.\n\n        :param trigger: Group member trigger to be created\n        :return: The created group Trigger"
  },
  {
    "code": "def squeeze(self, array):\n        if not self._squeeze:\n            return array\n        array = array.copy()\n        array = array.squeeze()\n        if array.ndim == 0:\n            array = array[()]\n        return array",
    "docstring": "Simplify the given array as much as possible - squeeze out all singleton\n        dimensions and also convert a zero dimensional array into array scalar"
  },
  {
    "code": "def get_device_topology(self, id_or_uri):\n        uri = self._client.build_uri(id_or_uri) + \"/deviceTopology\"\n        return self._client.get(uri)",
    "docstring": "Retrieves the topology information for the rack resource specified by ID or URI.\n\n        Args:\n            id_or_uri: Can be either the resource ID or the resource URI.\n\n        Return:\n            dict: Device topology."
  },
  {
    "code": "def get_external_commands_from_arbiters(self):\n        for arbiter_link_uuid in self.arbiters:\n            link = self.arbiters[arbiter_link_uuid]\n            if not link.active:\n                logger.debug(\"The arbiter '%s' is not active, it is not possible to get \"\n                             \"its external commands!\", link.name)\n                continue\n            try:\n                logger.debug(\"Getting external commands from: %s\", link.name)\n                external_commands = link.get_external_commands()\n                if external_commands:\n                    logger.debug(\"Got %d commands from: %s\", len(external_commands), link.name)\n                else:\n                    external_commands = []\n                for external_command in external_commands:\n                    self.add(external_command)\n            except LinkError:\n                logger.warning(\"Arbiter connection failed, I could not get external commands!\")\n            except Exception as exp:\n                logger.error(\"Arbiter connection failed, I could not get external commands!\")\n                logger.exception(\"Exception: %s\", exp)",
    "docstring": "Get external commands from our arbiters\n\n        As of now, only the arbiter are requested to provide their external commands that\n        the receiver will push to all the known schedulers to make them being executed.\n\n        :return: None"
  },
  {
    "code": "def handle_address_save(self, sender, instance, **kwargs):\n    objects = self.find_associated_with_address(instance)\n    for obj in objects:\n      self.handle_save(obj.__class__, obj)",
    "docstring": "Custom handler for address save"
  },
  {
    "code": "def move_out_16(library, session, space, offset, length, data, extended=False):\n    converted_buffer = (ViUInt16 * length)(*tuple(data))\n    if extended:\n        return library.viMoveOut16Ex(session, space, offset, length, converted_buffer)\n    else:\n        return library.viMoveOut16(session, space, offset, length, converted_buffer)",
    "docstring": "Moves an 16-bit block of data from local memory to the specified address space and offset.\n\n    Corresponds to viMoveOut16* functions of the VISA library.\n\n    :param library: the visa library wrapped by ctypes.\n    :param session: Unique logical identifier to a session.\n    :param space: Specifies the address space. (Constants.*SPACE*)\n    :param offset: Offset (in bytes) of the address or register from which to read.\n    :param length: Number of elements to transfer, where the data width of the elements to transfer\n                   is identical to the source data width.\n    :param data: Data to write to bus.\n    :param extended: Use 64 bits offset independent of the platform.\n    :return: return value of the library call.\n    :rtype: :class:`pyvisa.constants.StatusCode`"
  },
  {
    "code": "def _set_input(el, value):\n        if isinstance(value, dict):\n            el.value = value[\"val\"]\n        elif type(value) in [list, tuple]:\n            el.value = \", \".join(item[\"val\"] for item in value)\n        else:\n            el.value = value",
    "docstring": "Set content of given `el` to `value`.\n\n        Args:\n            el (obj): El reference to input you wish to set.\n            value (obj/list): Value to which the `el` will be set."
  },
  {
    "code": "def wp_is_loiter(self, i):\n        loiter_cmds = [mavutil.mavlink.MAV_CMD_NAV_LOITER_UNLIM,\n                mavutil.mavlink.MAV_CMD_NAV_LOITER_TURNS,\n                mavutil.mavlink.MAV_CMD_NAV_LOITER_TIME,\n                mavutil.mavlink.MAV_CMD_NAV_LOITER_TO_ALT]\n        if (self.wpoints[i].command in loiter_cmds):\n            return True    \n        return False",
    "docstring": "return true if waypoint is a loiter waypoint"
  },
  {
    "code": "def backlinks(\n            self,\n            page: 'WikipediaPage',\n            **kwargs\n    ) -> PagesDict:\n        params = {\n            'action': 'query',\n            'list': 'backlinks',\n            'bltitle': page.title,\n            'bllimit': 500,\n        }\n        used_params = kwargs\n        used_params.update(params)\n        raw = self._query(\n            page,\n            used_params\n        )\n        self._common_attributes(raw['query'], page)\n        v = raw['query']\n        while 'continue' in raw:\n            params['blcontinue'] = raw['continue']['blcontinue']\n            raw = self._query(\n                page,\n                params\n            )\n            v['backlinks'] += raw['query']['backlinks']\n        return self._build_backlinks(v, page)",
    "docstring": "Returns backlinks from other pages with respect to parameters\n\n        API Calls for parameters:\n\n        - https://www.mediawiki.org/w/api.php?action=help&modules=query%2Bbacklinks\n        - https://www.mediawiki.org/wiki/API:Backlinks\n\n        :param page: :class:`WikipediaPage`\n        :param kwargs: parameters used in API call\n        :return: backlinks from other pages"
  },
  {
    "code": "def get_states(self, devices):\n        header = BASE_HEADERS.copy()\n        header['Cookie'] = self.__cookie\n        json_data = self._create_get_state_request(devices)\n        request = requests.post(\n            BASE_URL + 'getStates',\n            headers=header,\n            data=json_data,\n            timeout=10)\n        if request.status_code != 200:\n            self.__logged_in = False\n            self.login()\n            self.get_states(devices)\n            return\n        try:\n            result = request.json()\n        except ValueError as error:\n            raise Exception(\n                \"Not a valid result for\" +\n                \"getStates, protocol error:\" + error)\n        self._get_states(result)",
    "docstring": "Get States of Devices."
  },
  {
    "code": "def _subtoken_ids_to_tokens(self, subtokens):\n    concatenated = \"\".join(\n        [self._subtoken_id_to_subtoken_string(s) for s in subtokens])\n    split = concatenated.split(\"_\")\n    ret = []\n    for t in split:\n      if t:\n        unescaped = _unescape_token(t + \"_\")\n        if unescaped:\n          ret.append(unescaped)\n    return ret",
    "docstring": "Converts a list of subtoken ids to a list of tokens.\n\n    Args:\n      subtokens: a list of integers in the range [0, vocab_size)\n    Returns:\n      a list of strings."
  },
  {
    "code": "def _try_parse_basic_number(self, data):\n        try:\n            return int(data)\n        except ValueError:\n            pass\n        try:\n            return float(data)\n        except ValueError:\n            pass\n        return data",
    "docstring": "Try to convert the data into ``int`` or ``float``.\n\n        :returns: ``Decimal`` or ``data`` if conversion fails."
  },
  {
    "code": "def _ParseEventData(self, variable_length_section):\n    event_data = WinJobEventData()\n    event_data.application = (\n        variable_length_section.application_name.rstrip('\\x00'))\n    event_data.comment = variable_length_section.comment.rstrip('\\x00')\n    event_data.parameters = (\n        variable_length_section.parameters.rstrip('\\x00'))\n    event_data.username = variable_length_section.author.rstrip('\\x00')\n    event_data.working_directory = (\n        variable_length_section.working_directory.rstrip('\\x00'))\n    return event_data",
    "docstring": "Parses the event data form a variable-length data section.\n\n    Args:\n      variable_length_section (job_variable_length_data_section): a\n          Windows Scheduled Task job variable-length data section.\n\n    Returns:\n      WinJobEventData: event data of the job file."
  },
  {
    "code": "def init(args=None):\n    if args is None:\n        args = []\n    arr = (ctypes.c_char_p * len(args))()\n    arr[:] = args\n    _LIB.RabitInit(len(arr), arr)",
    "docstring": "Initialize the rabit library with arguments"
  },
  {
    "code": "def create_chunked_list(in_dir, size, out_dir, out_name):\n    create_dirs(out_dir)\n    in_files = get_files(in_dir)\n    chunks = chunk(in_files, size)\n    division = {}\n    for i, files in enumerate(chunks):\n        division[i] = [os.path.basename(f) for f in files]\n    out_file = os.path.join(out_dir, out_name)\n    with codecs.open(out_file, 'wb', encoding='utf-8') as f:\n        json.dump(division, f, indent=4)",
    "docstring": "Create a division of the input files in chunks.\n\n    The result is stored to a JSON file."
  },
  {
    "code": "def _nose_tools_functions():\n    module = _BUILDER.string_build(\n        textwrap.dedent(\n        )\n    )\n    try:\n        case = next(module[\"a\"].infer())\n    except astroid.InferenceError:\n        return\n    for method in case.methods():\n        if method.name.startswith(\"assert\") and \"_\" not in method.name:\n            pep8_name = _pep8(method.name)\n            yield pep8_name, astroid.BoundMethod(method, case)\n        if method.name == \"assertEqual\":\n            yield \"assert_equals\", astroid.BoundMethod(method, case)",
    "docstring": "Get an iterator of names and bound methods."
  },
  {
    "code": "def child_link_extent(self):\n        if not self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not yet initialized')\n        if self.dr_entries.cl_record is not None:\n            return self.dr_entries.cl_record.child_log_block_num\n        if self.ce_entries.cl_record is not None:\n            return self.ce_entries.cl_record.child_log_block_num\n        raise pycdlibexception.PyCdlibInternalError('Asked for child extent for non-existent parent record')",
    "docstring": "Get the extent of the child of this entry if it has one.\n\n        Parameters:\n         None.\n        Returns:\n         The logical block number of the child if it exists."
  },
  {
    "code": "def _allows_url (self, url_data, roboturl):\n        with cache_lock:\n            if roboturl in self.cache:\n                self.hits += 1\n                rp = self.cache[roboturl]\n                return rp.can_fetch(self.useragent, url_data.url)\n            self.misses += 1\n        kwargs = dict(auth=url_data.auth, session=url_data.session)\n        if hasattr(url_data, \"proxy\") and hasattr(url_data, \"proxy_type\"):\n            kwargs[\"proxies\"] = {url_data.proxytype: url_data.proxy}\n        rp = robotparser2.RobotFileParser(**kwargs)\n        rp.set_url(roboturl)\n        rp.read()\n        with cache_lock:\n            self.cache[roboturl] = rp\n        self.add_sitemap_urls(rp, url_data, roboturl)\n        return rp.can_fetch(self.useragent, url_data.url)",
    "docstring": "Ask robots.txt allowance. Assumes only single thread per robots.txt\n        URL calls this function."
  },
  {
    "code": "def attach(self, num_name, write=0):\n        if isinstance(num_name, bytes):\n            num = self.find(num_name)\n        else:\n            num = num_name\n        vg_id = _C.Vattach(self._hdf_inst._id, num,\n                           write and 'w' or 'r')\n        _checkErr('vattach', vg_id, \"cannot attach Vgroup\")\n        return VG(self, vg_id)",
    "docstring": "Open an existing vgroup given its name or its reference\n        number, or create a new vgroup, returning a VG instance for\n        that vgroup.\n\n        Args::\n\n          num_name      reference number or name of the vgroup to open,\n                        or -1 to create a new vgroup; vcreate() can also\n                        be called to create and name a new vgroup\n          write         set to non-zero to open the vgroup in write mode\n                        and to 0 to open it in readonly mode (default)\n\n        Returns::\n\n          VG instance for the vgroup\n\n        An exception is raised if an attempt is made to open\n        a non-existent vgroup.\n\n        C library equivalent : Vattach"
  },
  {
    "code": "def _postback(self):\n        return requests.post(self.get_endpoint(),\n                             data=dict(cmd=\"_notify-synch\", at=IDENTITY_TOKEN, tx=self.tx)).content",
    "docstring": "Perform PayPal PDT Postback validation.\n        Sends the transaction ID and business token to PayPal which responses with\n        SUCCESS or FAILED."
  },
  {
    "code": "def list_files(dirname, extension=None):\n    f = []\n    for (dirpath, dirnames, filenames) in os.walk(dirname):\n        f.extend(filenames)\n        break\n    if extension is not None:\n        filtered = []\n        for filename in f:\n            fn, ext = os.path.splitext(filename)\n            if ext.lower() == '.' + extension.lower():\n                filtered.append(filename)\n        f = filtered\n    return f",
    "docstring": "List all files in directory `dirname`, option to filter on file extension"
  },
  {
    "code": "def get_log_metric(\n        self,\n        metric_name,\n        retry=google.api_core.gapic_v1.method.DEFAULT,\n        timeout=google.api_core.gapic_v1.method.DEFAULT,\n        metadata=None,\n    ):\n        if \"get_log_metric\" not in self._inner_api_calls:\n            self._inner_api_calls[\n                \"get_log_metric\"\n            ] = google.api_core.gapic_v1.method.wrap_method(\n                self.transport.get_log_metric,\n                default_retry=self._method_configs[\"GetLogMetric\"].retry,\n                default_timeout=self._method_configs[\"GetLogMetric\"].timeout,\n                client_info=self._client_info,\n            )\n        request = logging_metrics_pb2.GetLogMetricRequest(metric_name=metric_name)\n        if metadata is None:\n            metadata = []\n        metadata = list(metadata)\n        try:\n            routing_header = [(\"metric_name\", metric_name)]\n        except AttributeError:\n            pass\n        else:\n            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(\n                routing_header\n            )\n            metadata.append(routing_metadata)\n        return self._inner_api_calls[\"get_log_metric\"](\n            request, retry=retry, timeout=timeout, metadata=metadata\n        )",
    "docstring": "Gets a logs-based metric.\n\n        Example:\n            >>> from google.cloud import logging_v2\n            >>>\n            >>> client = logging_v2.MetricsServiceV2Client()\n            >>>\n            >>> metric_name = client.metric_path('[PROJECT]', '[METRIC]')\n            >>>\n            >>> response = client.get_log_metric(metric_name)\n\n        Args:\n            metric_name (str): The resource name of the desired metric:\n\n                ::\n\n                     \"projects/[PROJECT_ID]/metrics/[METRIC_ID]\"\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.logging_v2.types.LogMetric` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def size_on_disk(self, start_pos=0):\n        size = 1\n        fmts = opcode_table[self.opcode]['operands']\n        if self.wide:\n            size += 2\n            if self.opcode == 0x84:\n                size += 2\n        elif fmts:\n            for fmt, _ in fmts:\n                size += fmt.value.size\n        elif self.opcode == 0xAB:\n            padding = 4 - (start_pos + 1) % 4\n            padding = padding if padding != 4 else 0\n            size += padding\n            size += 8\n            size += len(self.operands[0]) * 8\n        elif self.opcode == 0xAA:\n            raise NotImplementedError()\n        return size",
    "docstring": "Returns the size of this instruction and its operands when\n        packed. `start_pos` is required for the `tableswitch` and\n        `lookupswitch` instruction as the padding depends on alignment."
  },
  {
    "code": "def setup_sanitize_files(self):\n        for fname in self.get_sanitize_files():\n            with open(fname, 'r') as f:\n                self.sanitize_patterns.update(get_sanitize_patterns(f.read()))",
    "docstring": "For each of the sanitize files that were specified as command line options\n        load the contents of the file into the sanitise patterns dictionary."
  },
  {
    "code": "def delete(self, request, **resources):\n        resource = resources.get(self._meta.name)\n        if not resource:\n            raise HttpError(\"Bad request\", status=status.HTTP_404_NOT_FOUND)\n        for o in as_tuple(resource):\n            o.delete()\n        return HttpResponse(\"\")",
    "docstring": "Default DELETE method. Allow bulk delete.\n\n        :return django.http.response: empty response"
  },
  {
    "code": "def init_db():\n    db.drop_all()\n    db.create_all()\n    title = \"de Finibus Bonorum et Malorum - Part I\"\n    text = \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor \\\n                incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud \\\n                exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure \\\n                dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \\\n                Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt \\\n                mollit anim id est laborum.\"\n    post = Post(title=title, text=text)\n    db.session.add(post)\n    db.session.commit()",
    "docstring": "Populate a small db with some example entries."
  },
  {
    "code": "def print_email(message, app):\n    invenio_mail = app.extensions['invenio-mail']\n    with invenio_mail._lock:\n        invenio_mail.stream.write(\n            '{0}\\n{1}\\n'.format(message.as_string(), '-' * 79))\n        invenio_mail.stream.flush()",
    "docstring": "Print mail to stream.\n\n    Signal handler for email_dispatched signal. Prints by default the output\n    to the stream specified in the constructor of InvenioMail.\n\n    :param message: Message object.\n    :param app: Flask application object."
  },
  {
    "code": "def license_fallback(vendor_dir, sdist_name):\n    libname = libname_from_dir(sdist_name)\n    if libname not in HARDCODED_LICENSE_URLS:\n        raise ValueError('No hardcoded URL for {} license'.format(libname))\n    url = HARDCODED_LICENSE_URLS[libname]\n    _, _, name = url.rpartition('/')\n    dest = license_destination(vendor_dir, libname, name)\n    r = requests.get(url, allow_redirects=True)\n    log('Downloading {}'.format(url))\n    r.raise_for_status()\n    dest.write_bytes(r.content)",
    "docstring": "Hardcoded license URLs. Check when updating if those are still needed"
  },
  {
    "code": "def get_time_period(value):\n        for time_period in TimePeriod:\n            if time_period.period == value:\n                return time_period\n        raise ValueError('{} is not a valid TimePeriod'.format(value))",
    "docstring": "Get the corresponding TimePeriod from the value.\n\n        Example values: 'all', 'hour', 'day', 'week', or 'month'."
  },
  {
    "code": "def _groupby_new_state(index, outputs, decisions):\n    output_map = {o: i for i, o in enumerate(outputs)}\n    groups = pd.Series(index).groupby([output_map[d] for d in decisions])\n    results = [(outputs[i], pd.Index(sub_group.values)) for i, sub_group in groups]\n    selected_outputs = [o for o, _ in results]\n    for output in outputs:\n        if output not in selected_outputs:\n            results.append((output, pd.Index([])))\n    return results",
    "docstring": "Groups the simulants in the index by their new output state.\n\n    Parameters\n    ----------\n    index : iterable of ints\n        An iterable of integer labels for the simulants.\n    outputs : iterable\n        A list of possible output states.\n    decisions : `pandas.Series`\n        A series containing the name of the next state for each simulant in the index.\n\n    Returns\n    -------\n    iterable of 2-tuples\n        The first item in each tuple is the name of an output state and the second item\n        is a `pandas.Index` representing the simulants to transition into that state."
  },
  {
    "code": "def qs_add(self, *args, **kwargs):\n        query = self.query.copy()\n        if args:\n            mdict = MultiDict(args[0])\n            for k, v in mdict.items():\n                query.add(k, v)\n        for k, v in kwargs.items():\n            query.add(k, v)\n        return self._copy(query=query)",
    "docstring": "Add value to QuerySet MultiDict"
  },
  {
    "code": "def _is_valid_index(self, index):\n        if isinstance(index, int):\n            return (index >= 0) and (index < len(self))\n        if isinstance(index, list):\n            valid = True\n            for i in index:\n                valid = valid or self._is_valid_index(i)\n            return valid\n        return False",
    "docstring": "Return ``True`` if and only if the given ``index``\n        is valid."
  },
  {
    "code": "def render(self, obj, name, context):\n        if self.value_lambda is not None:\n            val = self.value_lambda(obj)\n        else:\n            attr_name = name\n            if self.property_name is not None:\n                attr_name = self.property_name\n            if isinstance(obj, dict):\n                val = obj.get(attr_name, None)\n            else:\n                val = getattr(obj, attr_name, None)\n        if callable(val):\n            try:\n                val = val()\n            except:\n                logging.exception(\"Attempted to call `%s` on obj of type %s.\",\n                    attr_name, type(obj))\n                raise\n        return val",
    "docstring": "The default field renderer.\n\n        This basic renderer assumes that the object has an attribute with\n        the same name as the field, unless a different field is specified\n        as a `property_name`.\n\n        The renderer is also passed the context so that it can be\n        propagated to the `_render_serializable` method of nested\n        resources (or, for example, if you decide to implement attribute\n        hiding at the field level instead of at the object level).\n\n        Callable attributes of `obj` will be called to fetch value.\n        This is useful for fields computed from lambda functions\n        or instance methods."
  },
  {
    "code": "def _validate_prepare_time(self, t, pos_c):\n        if hasattr(t, 'unit'):\n            t = t.decompose(self.units).value\n        if not isiterable(t):\n            t = np.atleast_1d(t)\n        t = np.ascontiguousarray(t.ravel())\n        if len(t) > 1:\n            if len(t) != pos_c.shape[0]:\n                raise ValueError(\"If passing in an array of times, it must have a shape \"\n                                 \"compatible with the input position(s).\")\n        return t",
    "docstring": "Make sure that t is a 1D array and compatible with the C position array."
  },
  {
    "code": "def _get_mapping_for_table(self, table):\n        for mapping in self.mappings.values():\n            if mapping[\"table\"] == table:\n                return mapping",
    "docstring": "Returns the first mapping for a table name"
  },
  {
    "code": "def _parse_statements(lines):\n    lines = (l.strip() for l in lines if l)\n    lines = (l for l in lines if l and not l.startswith('--'))\n    parts = []\n    for line in lines:\n        parts.append(line.rstrip(';'))\n        if line.endswith(';'):\n            yield '\\n'.join(parts)\n            parts[:] = []\n    if parts:\n        yield '\\n'.join(parts)",
    "docstring": "Return a generator of statements\n\n    Args: A list of strings that can contain one or more statements.\n          Statements are separated using ';' at the end of a line\n          Everything after the last ';' will be treated as the last statement.\n\n    >>> list(_parse_statements(['select * from ', 't1;', 'select name']))\n    ['select * from\\\\nt1', 'select name']\n\n    >>> list(_parse_statements(['select * from t1;', '  ']))\n    ['select * from t1']"
  },
  {
    "code": "def vector_args(self, args):\n        for i in reversed(range(self._vector_count)):\n            pieces = []\n            for vec in args:\n                pieces.append(vec[(i+1) * self._vector_size - 1 : i * self._vector_size])\n            yield pieces",
    "docstring": "Yields each of the individual lane pairs from the arguments, in\n         order from most significan to least significant"
  },
  {
    "code": "def str_args(args):\n    res = []\n    for x in args:\n        if isinstance(x, tuple) and len(x) == 2:\n            key, value = x\n            if value and str_arg(value):\n                res += [\"%s=%s\" % (key, str_arg(value))]\n        else:\n            res += [str_arg(x)]\n    return ', '.join(res)",
    "docstring": "formats a list of function arguments prettily not as code\n\n    (kwargs are tuples (argname, argvalue)"
  },
  {
    "code": "def ratio_to_ave(window, eqdata, **kwargs):\n    _selection = kwargs.get('selection', 'Volume')\n    _skipstartrows = kwargs.get('skipstartrows', 0)\n    _skipendrows = kwargs.get('skipendrows', 0)\n    _outputcol = kwargs.get('outputcol', 'Ratio to Ave')\n    _size = len(eqdata.index)\n    _eqdata = eqdata.loc[:, _selection]\n    _sma = _eqdata.iloc[:-1 - _skipendrows].rolling(window=window, center=False).mean().values\n    _outdata = _eqdata.values[window + _skipstartrows:_size - _skipendrows] /\\\n            _sma[window + _skipstartrows - 1:]\n    _index = eqdata.index[window + _skipstartrows:_size - _skipendrows]\n    return pd.DataFrame(_outdata, index=_index, columns=[_outputcol], dtype=np.float64)",
    "docstring": "Return values expressed as ratios to the average over some number\n    of prior sessions.\n\n    Parameters\n    ----------\n    eqdata : DataFrame\n        Must contain a column with name matching `selection`, or, if\n        `selection` is not specified, a column named 'Volume'\n    window : int\n        Interval over which to calculate the average. Normally 252 (1 year)\n    selection : str, optional\n        Column to select for calculating ratio. Defaults to 'Volume'\n    skipstartrows : int, optional\n        Rows to skip at beginning in addition to the `window` rows\n        that must be skipped to get the baseline volume. Defaults to 0.\n    skipendrows : int, optional\n        Rows to skip at end. Defaults to 0.\n    outputcol : str, optional\n        Name of column in output dataframe. Defaults to 'Ratio to Ave'\n\n    Returns\n    ---------\n    out : DataFrame"
  },
  {
    "code": "def create_pgm_dict(\n    lambdaFile: str,\n    asts: List,\n    file_name: str,\n    mode_mapper_dict: dict,\n    save_file=False,\n) -> Dict:\n    lambdaStrings = [\"import math\\n\\n\"]\n    state = PGMState(lambdaStrings)\n    generator = GrFNGenerator()\n    generator.mode_mapper = mode_mapper_dict\n    pgm = generator.genPgm(asts, state, {}, \"\")[0]\n    if pgm.get(\"start\"):\n        pgm[\"start\"] = pgm[\"start\"][0]\n    else:\n        pgm[\"start\"] = generator.function_defs[-1]\n    pgm[\"source\"] = [[get_path(file_name, \"source\")]]\n    pgm[\"dateCreated\"] = f\"{datetime.today().strftime('%Y%m%d')}\"\n    with open(lambdaFile, \"w\") as f:\n        f.write(\"\".join(lambdaStrings))\n    if save_file:\n        json.dump(pgm, open(file_name[:file_name.rfind(\".\")] + \".json\", \"w\"))\n    return pgm",
    "docstring": "Create a Python dict representing the PGM, with additional metadata for\n    JSON output."
  },
  {
    "code": "def db_validate_yubikey_otp(self, public_id, otp):\n        return pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP( \\\n            self.stick, public_id, otp).execute()",
    "docstring": "Request the YubiHSM to validate an OTP for a YubiKey stored\n        in the internal database.\n\n        @param public_id: The six bytes public id of the YubiKey\n        @param otp: The OTP from a YubiKey in binary form (16 bytes)\n        @type public_id: string\n        @type otp: string\n\n        @returns: validation response\n        @rtype: L{YHSM_ValidationResult}\n\n        @see: L{pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP}"
  },
  {
    "code": "def size(self):\n        old = self.__file.tell()\n        self.__file.seek(0, 2)\n        n_bytes = self.__file.tell()\n        self.__file.seek(old)\n        return n_bytes",
    "docstring": "Calculate and return the file size in bytes."
  },
  {
    "code": "def _get_token(self, oauth_request, token_type='access'):\n        token_field = oauth_request.get_parameter('oauth_token')\n        token = self.data_store.lookup_token(token_type, token_field)\n        if not token:\n            raise OAuthError('Invalid %s token: %s' % (token_type, token_field))\n        return token",
    "docstring": "Try to find the token for the provided request token key."
  },
  {
    "code": "def consume_keys_asynchronous_processes(self):\n        print(\"\\nLooking up \" + self.input_queue.qsize().__str__() + \" keys from \" + self.source_name + \"\\n\")\n        jobs = multiprocessing.cpu_count()*4 if (multiprocessing.cpu_count()*4 < self.input_queue.qsize()) \\\n            else self.input_queue.qsize()\n        pool = multiprocessing.Pool(processes=jobs,  maxtasksperchild=10)\n        for x in range(jobs):\n            pool.apply(self.data_worker, [], self.worker_args)\n        pool.close()\n        pool.join()",
    "docstring": "Work through the keys to look up asynchronously using multiple processes"
  },
  {
    "code": "def bulk_copy(self, ids):\n        schema = UserSchema()\n        return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)",
    "docstring": "Bulk copy a set of users.\n\n        :param ids: Int list of user IDs.\n        :return: :class:`users.User <users.User>` list"
  },
  {
    "code": "def _get_I(self, a, b, size, plus_transpose=True):\n        r_sum = np.zeros((3, 3), dtype='double', order='C')\n        for r in self._rotations_cartesian:\n            for i in range(3):\n                for j in range(3):\n                    r_sum[i, j] += r[a, i] * r[b, j]\n        if plus_transpose:\n            r_sum += r_sum.T\n        if (np.abs(r_sum) < 1e-10).all():\n            return None\n        I_mat = np.zeros((3 * size, 3 * size), dtype='double', order='C')\n        for i in range(size):\n            I_mat[(i * 3):((i + 1) * 3), (i * 3):((i + 1) * 3)] = r_sum\n        return I_mat",
    "docstring": "Return I matrix in Chaput's PRL paper.\n\n        None is returned if I is zero matrix."
  },
  {
    "code": "def get_link_map(self, nslave):\n        tree_map, parent_map = self.get_tree(nslave)\n        ring_map = self.get_ring(tree_map, parent_map)\n        rmap = {0 : 0}\n        k = 0\n        for i in range(nslave - 1):\n            k = ring_map[k][1]\n            rmap[k] = i + 1\n        ring_map_ = {}\n        tree_map_ = {}\n        parent_map_ ={}\n        for k, v in ring_map.items():\n            ring_map_[rmap[k]] = (rmap[v[0]], rmap[v[1]])\n        for k, v in tree_map.items():\n            tree_map_[rmap[k]] = [rmap[x] for x in v]\n        for k, v in parent_map.items():\n            if k != 0:\n                parent_map_[rmap[k]] = rmap[v]\n            else:\n                parent_map_[rmap[k]] = -1\n        return tree_map_, parent_map_, ring_map_",
    "docstring": "get the link map, this is a bit hacky, call for better algorithm\n        to place similar nodes together"
  },
  {
    "code": "def detach_disk(name=None, kwargs=None, call=None):\n    if call != 'action':\n        raise SaltCloudSystemExit(\n            'The detach_Disk action must be called with -a or --action.'\n        )\n    if not name:\n        log.error(\n            'Must specify an instance name.'\n        )\n        return False\n    if not kwargs or 'disk_name' not in kwargs:\n        log.error(\n            'Must specify a disk_name to detach.'\n        )\n        return False\n    node_name = name\n    disk_name = kwargs['disk_name']\n    conn = get_conn()\n    node = conn.ex_get_node(node_name)\n    disk = conn.ex_get_volume(disk_name)\n    __utils__['cloud.fire_event'](\n        'event',\n        'detach disk',\n        'salt/cloud/disk/detaching',\n        args={\n            'name': node_name,\n            'disk_name': disk_name,\n        },\n        sock_dir=__opts__['sock_dir'],\n        transport=__opts__['transport']\n    )\n    result = conn.detach_volume(disk, node)\n    __utils__['cloud.fire_event'](\n        'event',\n        'detached disk',\n        'salt/cloud/disk/detached',\n        args={\n            'name': node_name,\n            'disk_name': disk_name,\n        },\n        sock_dir=__opts__['sock_dir'],\n        transport=__opts__['transport']\n    )\n    return result",
    "docstring": "Detach a disk from an instance.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -a detach_disk myinstance disk_name=mydisk"
  },
  {
    "code": "def set_random_state(state):\n    randgen.state_set = True\n    randgen.setstate(state)\n    faker.generator.random.setstate(state)",
    "docstring": "Force-set the state of factory.fuzzy's random generator."
  },
  {
    "code": "def package_releases(request, package_name, show_hidden=False):\n    session = DBSession()\n    package = Package.by_name(session, package_name)\n    return [rel.version for rel in package.sorted_releases]",
    "docstring": "Retrieve a list of the releases registered for the given package_name.\n    Returns a list with all version strings if show_hidden is True or\n    only the non-hidden ones otherwise."
  },
  {
    "code": "def right(self):\n        if self._has_real():\n            return self._data.real_right\n        return self._data.right",
    "docstring": "Right coordinate."
  },
  {
    "code": "def compare_wfns(cls, source, target):\n        for att in CPEComponent.CPE_COMP_KEYS_EXTENDED:\n            value_src = source.get_attribute_values(att)[0]\n            if value_src.find('\"') > -1:\n                value_src = value_src[1:-1]\n            value_tar = target.get_attribute_values(att)[0]\n            if value_tar.find('\"') > -1:\n                value_tar = value_tar[1:-1]\n            yield (att, CPESet2_3._compare(value_src, value_tar))",
    "docstring": "Compares two WFNs and returns a generator of pairwise attribute-value\n        comparison results. It provides full access to the individual\n        comparison results to enable use-case specific implementations\n        of novel name-comparison algorithms.\n\n        Compare each attribute of the Source WFN to the Target WFN:\n\n        :param CPE2_3_WFN source: first WFN CPE Name\n        :param CPE2_3_WFN target: seconds WFN CPE Name\n        :returns: generator of pairwise attribute comparison results\n        :rtype: generator"
  },
  {
    "code": "def _platform(self) -> Optional[str]:\n        try:\n            return str(self.journey.MainStop.BasicStop.Dep.Platform.text)\n        except AttributeError:\n            return None",
    "docstring": "Extract platform."
  },
  {
    "code": "def bschoc(value, ndim, lenvals, array, order):\n    value = stypes.stringToCharP(value)\n    ndim = ctypes.c_int(ndim)\n    lenvals = ctypes.c_int(lenvals)\n    array = stypes.listToCharArrayPtr(array, xLen=lenvals, yLen=ndim)\n    order = stypes.toIntVector(order)\n    return libspice.bschoc_c(value, ndim, lenvals, array, order)",
    "docstring": "Do a binary search for a given value within a character string array,\n    accompanied by an order vector.  Return the index of the matching array\n    entry, or -1 if the key value is not found.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bschoc_c.html\n\n    :param value: Key value to be found in array.\n    :type value: str\n    :param ndim: Dimension of array.\n    :type ndim: int\n    :param lenvals: String length.\n    :type lenvals: int\n    :param array: Character string array to search.\n    :type array: list of strings\n    :param order: Order vector.\n    :type order: Array of ints\n    :return: index\n    :rtype: int"
  },
  {
    "code": "def by_ip(self, ip):\n        try:\n            number = inet_aton(ip)\n        except Exception:\n            raise IpRange.DoesNotExist\n        try:\n            return self.filter(start_ip__lte=number, end_ip__gte=number)\\\n                       .order_by('end_ip', '-start_ip')[0]\n        except IndexError:\n            raise IpRange.DoesNotExist",
    "docstring": "Find the smallest range containing the given IP."
  },
  {
    "code": "def set_contourf_properties(stroke_width, fcolor, fill_opacity, contour_levels, contourf_idx, unit):\n    return {\n        \"stroke\": fcolor,\n        \"stroke-width\": stroke_width,\n        \"stroke-opacity\": 1,\n        \"fill\": fcolor,\n        \"fill-opacity\": fill_opacity,\n        \"title\": \"%.2f\" % contour_levels[contourf_idx] + ' ' + unit\n    }",
    "docstring": "Set property values for Polygon."
  },
  {
    "code": "def char_code(columns, name=None):\n    if name is None:\n        name = 'Char Code Field (' + str(columns) + ' columns)'\n    if columns <= 0:\n        raise BaseException()\n    char_sets = None\n    for char_set in _tables.get_data('character_set'):\n        regex = '[ ]{' + str(15 - len(char_set)) + '}' + char_set\n        if char_sets is None:\n            char_sets = regex\n        else:\n            char_sets += '|' + regex\n    _character_sets = pp.Regex(char_sets)\n    _unicode_1_16b = pp.Regex('U\\+0[0-8,A-F]{3}[ ]{' + str(columns - 6) + '}')\n    _unicode_2_21b = pp.Regex('U\\+0[0-8,A-F]{4}[ ]{' + str(columns - 7) + '}')\n    char_code_field = (_character_sets | _unicode_1_16b | _unicode_2_21b)\n    char_code_field = char_code_field.setParseAction(lambda s: s[0].strip())\n    char_code_field.setName(name)\n    return char_code_field",
    "docstring": "Character set code field.\n\n    :param name: name for the field\n    :return: an instance of the Character set code field rules"
  },
  {
    "code": "def _altaz_rotation(self, t):\n        R_lon = rot_z(- self.longitude.radians - t.gast * tau / 24.0)\n        return einsum('ij...,jk...,kl...->il...', self.R_lat, R_lon, t.M)",
    "docstring": "Compute the rotation from the ICRF into the alt-az system."
  },
  {
    "code": "def makeicons(source):\n    im = Image.open(source)\n    for name, (_, w, h, func) in icon_sizes.iteritems():\n        print('Making icon %s...' % name)\n        tn = func(im, (w, h))\n        bg = Image.new('RGBA', (w, h), (255, 255, 255))\n        x = (w / 2) - (tn.size[0] / 2)\n        y = (h / 2) - (tn.size[1] / 2)\n        bg.paste(tn, (x, y))\n        bg.save(path.join(env.dir, name))",
    "docstring": "Create all the neccessary icons from source image"
  },
  {
    "code": "def _format_dates(self, start, end):\n        start = self._split_date(start)\n        end = self._split_date(end)\n        return start, end",
    "docstring": "Format start and end dates."
  },
  {
    "code": "def get_command_class(name, exclude_packages=None, exclude_command_class=None):\n    from django.conf import settings\n    return get_command_class_from_apps(\n        name, \n        settings.INSTALLED_APPS \\\n            if \"django.core\" in settings.INSTALLED_APPS \\\n            else (\"django.core\",) + tuple(settings.INSTALLED_APPS),\n        exclude_packages=exclude_packages,\n        exclude_command_class=exclude_command_class)",
    "docstring": "Searches \"django.core\" and the apps in settings.INSTALLED_APPS to find the\n    named command class, optionally skipping packages or a particular\n    command class."
  },
  {
    "code": "def size(self):\n        (halfw, halfh) = self._halfdim\n        if self.orientation in [\"top\", \"bottom\"]:\n            return (halfw * 2., halfh * 2.)\n        else:\n            return (halfh * 2., halfw * 2.)",
    "docstring": "The size of the ColorBar\n\n        Returns\n        -------\n        size: (major_axis_length, minor_axis_length)\n            major and minor axis are defined by the\n            orientation of the ColorBar"
  },
  {
    "code": "def merge_config(self, user_config):\n        temp_data_config = copy.deepcopy(self.data_config).update(user_config)\n        temp_model_config = copy.deepcopy(self.model_config).update(user_config)\n        temp_conversation_config = copy.deepcopy(self.conversation_config).update(user_config)\n        if validate_data_config(temp_data_config):\n            self.data_config = temp_data_config\n        if validate_model_config(temp_model_config):\n            self.model_config = temp_model_config\n        if validate_conversation_config(temp_conversation_config):\n            self.conversation_config = temp_conversation_config",
    "docstring": "Take a dictionary of user preferences and use them to update the default\n        data, model, and conversation configurations."
  },
  {
    "code": "def get_tri_area(pts):\n    a, b, c = pts[0], pts[1], pts[2]\n    v1 = np.array(b) - np.array(a)\n    v2 = np.array(c) - np.array(a)\n    area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) / 2)\n    return area_tri",
    "docstring": "Given a list of coords for 3 points,\n    Compute the area of this triangle.\n\n    Args:\n        pts: [a, b, c] three points"
  },
  {
    "code": "def humanize_hours(total_hours, frmt='{hours:02d}:{minutes:02d}:{seconds:02d}',\n                   negative_frmt=None):\n    seconds = int(float(total_hours) * 3600)\n    return humanize_seconds(seconds, frmt, negative_frmt)",
    "docstring": "Given time in hours, return a string representing the time."
  },
  {
    "code": "def _unichr(i):\n    if not isinstance(i, int):\n        raise TypeError\n    try:\n        return six.unichr(i)\n    except ValueError:\n        return struct.pack(\"i\", i).decode(\"utf-32\")",
    "docstring": "Helper function for taking a Unicode scalar value and returning a Unicode character.\n\n    :param s: Unicode scalar value to convert.\n    :return: Unicode character"
  },
  {
    "code": "def create_tag_and_push(version):\n    \"Create a git tag for `version` and push it to origin.\"\n    assert version not in tags()\n    git('config', 'user.name', 'Travis CI on behalf of Austin Bingham')\n    git('config', 'user.email', 'austin@sixty-north.com')\n    git('config', 'core.sshCommand', 'ssh -i deploy_key')\n    git(\n        'remote', 'add', 'ssh-origin',\n        'git@github.com:sixty-north/cosmic-ray.git'\n    )\n    git('tag', version)\n    subprocess.check_call([\n        'ssh-agent', 'sh', '-c',\n        'chmod 0600 deploy_key && ' +\n        'ssh-add deploy_key && ' +\n        'git push ssh-origin --tags'\n    ])",
    "docstring": "Create a git tag for `version` and push it to origin."
  },
  {
    "code": "def lookup_mac(self, ip):\n\t\tres = self.lookup_by_lease(ip=ip)\n\t\ttry:\n\t\t\treturn res[\"hardware-address\"]\n\t\texcept KeyError:\n\t\t\traise OmapiErrorAttributeNotFound()",
    "docstring": "Look up a lease object with given ip address and return the\n\t\tassociated mac address.\n\n\t\t@type ip: str\n\t\t@rtype: str or None\n\t\t@raises ValueError:\n\t\t@raises OmapiError:\n\t\t@raises OmapiErrorNotFound: if no lease object with the given ip could be found\n\t\t@raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks a mac\n\t\t@raises socket.error:"
  },
  {
    "code": "def initialize(self):\n    if self._modules is None:\n      self._modules = []\n      for i in xrange(self.moduleCount):\n        self._modules.append(ThresholdedGaussian2DLocationModule(\n          cellsPerAxis=self.cellsPerAxis,\n          scale=self.scale[i],\n          orientation=self.orientation[i],\n          anchorInputSize=self.anchorInputSize,\n          activeFiringRate=self.activeFiringRate,\n          bumpSigma=self.bumpSigma,\n          activationThreshold=self.activationThreshold,\n          initialPermanence=self.initialPermanence,\n          connectedPermanence=self.connectedPermanence,\n          learningThreshold=self.learningThreshold,\n          sampleSize=self.sampleSize,\n          permanenceIncrement=self.permanenceIncrement,\n          permanenceDecrement=self.permanenceDecrement,\n          maxSynapsesPerSegment=self.maxSynapsesPerSegment,\n          bumpOverlapMethod=self.bumpOverlapMethod,\n          seed=self.seed))\n      if self.dimensions > 2:\n        self._projection = [\n          self.createProjectionMatrix(dimensions=self.dimensions)\n            for _ in xrange(self.moduleCount)]",
    "docstring": "Initialize grid cell modules"
  },
  {
    "code": "def save_map(dsp, path):\n    import dill\n    with open(path, 'wb') as f:\n        dill.dump(dsp.dmap, f)",
    "docstring": "Write Dispatcher graph object in Python pickle format.\n\n    Pickles are a serialized byte stream of a Python object.\n    This format will preserve Python objects used as nodes or edges.\n\n    :param dsp:\n        A dispatcher that identifies the model adopted.\n    :type dsp: schedula.Dispatcher\n\n    :param path:\n        File or filename to write.\n        File names ending in .gz or .bz2 will be compressed.\n    :type path: str, file\n\n    .. testsetup::\n        >>> from tempfile import mkstemp\n        >>> file_name = mkstemp()[1]\n\n    Example::\n\n        >>> from schedula import Dispatcher\n        >>> dsp = Dispatcher()\n        >>> dsp.add_function(function=max, inputs=['a', 'b'], outputs=['c'])\n        'max'\n        >>> save_map(dsp, file_name)"
  },
  {
    "code": "def access_array(self, id_, lineno, scope=None, default_type=None):\n        if not self.check_is_declared(id_, lineno, 'array', scope):\n            return None\n        if not self.check_class(id_, CLASS.array, lineno, scope):\n            return None\n        return self.access_id(id_, lineno, scope=scope, default_type=default_type)",
    "docstring": "Called whenever an accessed variable is expected to be an array.\n        ZX BASIC requires arrays to be declared before usage, so they're\n        checked.\n\n        Also checks for class array."
  },
  {
    "code": "def set_keywords_creation_mode(self, layer=None, keywords=None):\n        self.layer = layer or self.iface.mapCanvas().currentLayer()\n        if keywords is not None:\n            self.existing_keywords = keywords\n        else:\n            try:\n                self.existing_keywords = self.keyword_io.read_keywords(\n                    self.layer)\n            except (HashNotFoundError,\n                    OperationalError,\n                    NoKeywordsFoundError,\n                    KeywordNotFoundError,\n                    InvalidParameterError,\n                    UnsupportedProviderError,\n                    MetadataReadError):\n                self.existing_keywords = {}\n        self.set_mode_label_to_keywords_creation()\n        step = self.step_kw_purpose\n        step.set_widgets()\n        self.go_to_step(step)",
    "docstring": "Set the Wizard to the Keywords Creation mode.\n\n        :param layer: Layer to set the keywords for\n        :type layer: QgsMapLayer\n\n        :param keywords: Keywords for the layer.\n        :type keywords: dict, None"
  },
  {
    "code": "def validate_arc_links_same_outline(sender, instance, *args, **kwargs):\n    if instance.story_element_node:\n        if instance.story_element_node.outline != instance.parent_outline:\n            raise IntegrityError(_('An arc cannot be associated with an story element from another outline.'))",
    "docstring": "Evaluates attempts to link an arc to a story node from another outline."
  },
  {
    "code": "def setM0Coast(self, device=DEFAULT_DEVICE_ID):\n        cmd = self._COMMAND.get('m0-coast')\n        self._writeData(cmd, device)",
    "docstring": "Set motor 0 to coast.\n\n        :Keywords:\n          device : `int`\n            The device is the integer number of the hardware devices ID and\n            is only used with the Pololu Protocol. Defaults to the hardware's\n            default value.\n\n        :Exceptions:\n          * `SerialTimeoutException`\n            If the low level serial package times out.\n          * `SerialException`\n            IO error when the port is not open."
  },
  {
    "code": "def create_order(self, order_deets):\n        request = self._post('transactions/orders', order_deets)\n        return self.responder(request)",
    "docstring": "Creates a new order transaction."
  },
  {
    "code": "def get_characters(self, *args, **kwargs):\n        from .character import Character, CharacterDataWrapper\n        return self.get_related_resource(Character, CharacterDataWrapper, args, kwargs)",
    "docstring": "Returns a full CharacterDataWrapper object for this story.\n\n        /stories/{storyId}/characters\n\n        :returns:  CharacterDataWrapper -- A new request to API. Contains full results set."
  },
  {
    "code": "def update_qos_aggregated_configuration(self, qos_configuration, timeout=-1):\n        uri = \"{}{}\".format(self.data[\"uri\"], self.QOS_AGGREGATED_CONFIGURATION)\n        return self._helper.update(qos_configuration, uri=uri, timeout=timeout)",
    "docstring": "Updates the QoS aggregated configuration for the logical interconnect.\n\n        Args:\n            qos_configuration:\n                QOS configuration.\n            timeout:\n                Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in\n                OneView, just stops waiting for its completion.\n\n        Returns:\n            dict: Logical Interconnect."
  },
  {
    "code": "def write_libxc_docs_json(xcfuncs, jpath):\n    from copy import deepcopy\n    xcfuncs = deepcopy(xcfuncs)\n    for d in xcfuncs.values():\n        d[\"Family\"] = d[\"Family\"].replace(\"XC_FAMILY_\", \"\", 1)\n        d[\"Kind\"] = d[\"Kind\"].replace(\"XC_\", \"\", 1)\n    for num, d in xcfuncs.items():\n        xcfuncs[num] = {k: d[k] for k in (\"Family\", \"Kind\", \"References\")}\n        for opt in (\"Description 1\", \"Description 2\"):\n            desc = d.get(opt)\n            if desc is not None: xcfuncs[num][opt] = desc\n    with open(jpath, \"wt\") as fh:\n        json.dump(xcfuncs, fh)\n    return xcfuncs",
    "docstring": "Write json file with libxc metadata to path jpath."
  },
  {
    "code": "def set_include_rts(self, rts):\n        if not isinstance(rts, bool):\n            raise TwitterSearchException(1008)\n        self.arguments.update({'include_rts': 'true' if rts else 'false'})",
    "docstring": "Sets 'include_rts' parameter. When set to False, \\\n        the timeline will strip any native retweets from the returned timeline\n\n        :param rts: Boolean triggering the usage of the parameter\n        :raises: TwitterSearchException"
  },
  {
    "code": "def get_file(path,\n             dest,\n             saltenv='base',\n             makedirs=False,\n             template=None,\n             gzip=None):\n    if gzip is not None:\n        log.warning('The gzip argument to cp.get_file in salt-ssh is '\n                    'unsupported')\n    if template is not None:\n        (path, dest) = _render_filenames(path, dest, saltenv, template)\n    src = __context__['fileclient'].cache_file(\n        path,\n        saltenv,\n        cachedir=os.path.join('salt-ssh', __salt__.kwargs['id_']))\n    single = salt.client.ssh.Single(\n            __opts__,\n            '',\n            **__salt__.kwargs)\n    ret = single.shell.send(src, dest, makedirs)\n    return not ret[2]",
    "docstring": "Send a file from the master to the location in specified\n\n    .. note::\n\n        gzip compression is not supported in the salt-ssh version of\n        cp.get_file. The argument is only accepted for interface compatibility."
  },
  {
    "code": "def monitor(i):\n    count = 0\n    for x in i:\n        count+=1\n        if count % 10000 == 0:\n            logger.info(\"%d records so far, current record is %s\",\n                count, x[\"idx\"])\n        yield x",
    "docstring": "Given an iterator, yields data from it\n    but prints progress every 10,000 records"
  },
  {
    "code": "def execute(self, args):\n    all_args = list(args)\n    try:\n      return self._cmd(all_args)\n    except OSError as e:\n      if errno.E2BIG == e.errno:\n        args1, args2 = self._split_args(all_args)\n        result = self.execute(args1)\n        if result != 0:\n          return result\n        return self.execute(args2)\n      else:\n        raise e",
    "docstring": "Executes the configured cmd passing args in one or more rounds xargs style.\n\n    :param list args: Extra arguments to pass to cmd."
  },
  {
    "code": "def i3():\n    install_package('i3')\n    install_file_legacy(path='~/.i3/config', username=env.user, repos_dir='repos')\n    install_packages(['make', 'pkg-config', 'gcc', 'libc6-dev', 'libx11-dev'])\n    checkup_git_repo_legacy(url='https://github.com/aktau/hhpc.git')\n    run('cd ~/repos/hhpc  &&  make')",
    "docstring": "Install and customize the tiling window manager i3."
  },
  {
    "code": "def delete(self, response_choice=1, async=False, callback=None):\n        return self._manage_child_object(nurest_object=self, method=HTTP_METHOD_DELETE, async=async, callback=callback, response_choice=response_choice)",
    "docstring": "Delete object and call given callback in case of call.\n\n            Args:\n                response_choice (int): Automatically send a response choice when confirmation is needed\n                async (bool): Boolean to make an asynchronous call. Default is False\n                callback (function): Callback method that will be triggered in case of asynchronous call\n\n            Example:\n                >>> entity.delete() # will delete the enterprise from the server"
  },
  {
    "code": "def add_node_to_network(self, node, network):\n        network.add_node(node)\n        node.receive()\n        environment = network.nodes(type=Environment)[0]\n        environment.connect(whom=node)\n        gene = node.infos(type=LearningGene)[0].contents\n        if (gene == \"social\"):\n            prev_agents = RogersAgent.query\\\n                .filter(and_(RogersAgent.failed == False,\n                             RogersAgent.network_id == network.id,\n                             RogersAgent.generation == node.generation - 1))\\\n                .all()\n            parent = random.choice(prev_agents)\n            parent.connect(whom=node)\n            parent.transmit(what=Meme, to_whom=node)\n        elif (gene == \"asocial\"):\n            environment.transmit(to_whom=node)\n        else:\n            raise ValueError(\"{} has invalid learning gene value of {}\"\n                             .format(node, gene))\n        node.receive()",
    "docstring": "Add participant's node to a network."
  },
  {
    "code": "def OnMacroToolbarToggle(self, event):\n        self.main_window.macro_toolbar.SetGripperVisible(True)\n        macro_toolbar_info = self.main_window._mgr.GetPane(\"macro_toolbar\")\n        self._toggle_pane(macro_toolbar_info)\n        event.Skip()",
    "docstring": "Macro toolbar toggle event handler"
  },
  {
    "code": "def from_string(address):\n\t\tif len(address) == 0:\n\t\t\treturn WFQDN()\n\t\tif address[-1] == '.':\n\t\t\taddress = address[:-1]\n\t\tif len(address) > WFQDN.maximum_fqdn_length:\n\t\t\traise ValueError('Invalid address')\n\t\tresult = WFQDN()\n\t\tfor label in address.split('.'):\n\t\t\tif isinstance(label, str) and WFQDN.re_label.match(label):\n\t\t\t\tresult._labels.append(label)\n\t\t\telse:\n\t\t\t\traise ValueError('Invalid address')\n\t\treturn result",
    "docstring": "Convert doted-written FQDN address to WFQDN object\n\n\t\t:param address: address to convert\n\t\t:return: WFQDN"
  },
  {
    "code": "def replace(self, replacements):\n        for old_var, new_var in replacements.items():\n            old_var_id = id(old_var)\n            if old_var_id in self._object_mapping:\n                old_so = self._object_mapping[old_var_id]\n                self._store(old_so.start, new_var, old_so.size, overwrite=True)\n        return self",
    "docstring": "Replace variables with other variables.\n\n        :param dict replacements:   A dict of variable replacements.\n        :return:                    self"
  },
  {
    "code": "def schema_map(schema):\n    mapper = {}\n    for name in getFieldNames(schema):\n        mapper[name] = name\n    return mapper",
    "docstring": "Return a valid ICachedItemMapper.map for schema"
  },
  {
    "code": "def format_datetime(self, format='medium', locale='en_US'):\n        return format_datetime(self._dt, format=format, locale=locale)",
    "docstring": "Return a date string formatted to the given pattern.\n\n        .. testsetup::\n\n            from delorean import Delorean\n\n        .. doctest::\n\n            >>> d = Delorean(datetime(2015, 1, 1, 12, 30), timezone='US/Pacific')\n            >>> d.format_datetime(locale='en_US')\n            u'Jan 1, 2015, 12:30:00 PM'\n\n            >>> d.format_datetime(format='long', locale='de_DE')\n            u'1. Januar 2015 12:30:00 -0800'\n\n        :param format: one of \"full\", \"long\", \"medium\", \"short\", or a custom datetime pattern\n        :param locale: a locale identifier"
  },
  {
    "code": "def transfer_funds(self, to, amount, denom, msg):\n        try:\n            self.steem_instance().commit.transfer(to, \n                float(amount), denom, msg, self.mainaccount)\n        except Exception as e:\n            self.msg.error_message(e)\n            return False\n        else:\n            return True",
    "docstring": "Transfer SBD or STEEM to the given account"
  },
  {
    "code": "def _get_resize_target(img, crop_target, do_crop=False)->TensorImageSize:\n    \"Calc size of `img` to fit in `crop_target` - adjust based on `do_crop`.\"\n    if crop_target is None: return None\n    ch,r,c = img.shape\n    target_r,target_c = crop_target\n    ratio = (min if do_crop else max)(r/target_r, c/target_c)\n    return ch,int(round(r/ratio)),int(round(c/ratio))",
    "docstring": "Calc size of `img` to fit in `crop_target` - adjust based on `do_crop`."
  },
  {
    "code": "def sort(iterable):\n    ips = sorted(normalize_ip(ip) for ip in iterable)\n    return [clean_ip(ip) for ip in ips]",
    "docstring": "Given an IP address list, this function sorts the list.\n\n    :type  iterable: Iterator\n    :param iterable: An IP address list.\n    :rtype:  list\n    :return: The sorted IP address list."
  },
  {
    "code": "def get_route_name(resource_uri):\n    resource_uri = resource_uri.strip('/')\n    resource_uri = re.sub('\\W', '', resource_uri)\n    return resource_uri",
    "docstring": "Get route name from RAML resource URI.\n\n    :param resource_uri: String representing RAML resource URI.\n    :returns string: String with route name, which is :resource_uri:\n        stripped of non-word characters."
  },
  {
    "code": "def kernel_type(self, kernel_type):\n        if kernel_type is None:\n            raise ValueError(\"Invalid value for `kernel_type`, must not be `None`\")\n        allowed_values = [\"script\", \"notebook\"]\n        if kernel_type not in allowed_values:\n            raise ValueError(\n                \"Invalid value for `kernel_type` ({0}), must be one of {1}\"\n                .format(kernel_type, allowed_values)\n            )\n        self._kernel_type = kernel_type",
    "docstring": "Sets the kernel_type of this KernelPushRequest.\n\n        The type of kernel. Cannot be changed once the kernel has been created  # noqa: E501\n\n        :param kernel_type: The kernel_type of this KernelPushRequest.  # noqa: E501\n        :type: str"
  },
  {
    "code": "def read(self, *args, **kwargs):\n        with self.open('r') as f:\n            return f.read(*args, **kwargs)",
    "docstring": "Reads the node as a file"
  },
  {
    "code": "def dpt_timeseries(adata, color_map=None, show=None, save=None, as_heatmap=True):\n    if adata.n_vars > 100:\n        logg.warn('Plotting more than 100 genes might take some while,'\n                  'consider selecting only highly variable genes, for example.')\n    if as_heatmap:\n        timeseries_as_heatmap(adata.X[adata.obs['dpt_order_indices'].values],\n                              var_names=adata.var_names,\n                              highlightsX=adata.uns['dpt_changepoints'],\n                              color_map=color_map)\n    else:\n        timeseries(adata.X[adata.obs['dpt_order_indices'].values],\n                   var_names=adata.var_names,\n                   highlightsX=adata.uns['dpt_changepoints'],\n                   xlim=[0, 1.3*adata.X.shape[0]])\n    pl.xlabel('dpt order')\n    utils.savefig_or_show('dpt_timeseries', save=save, show=show)",
    "docstring": "Heatmap of pseudotime series.\n\n    Parameters\n    ----------\n    as_heatmap : bool (default: False)\n        Plot the timeseries as heatmap."
  },
  {
    "code": "def run_py(self, cmd, cwd=os.curdir):\n        c = None\n        if isinstance(cmd, six.string_types):\n            script = vistir.cmdparse.Script.parse(\"{0} -c {1}\".format(self.python, cmd))\n        else:\n            script = vistir.cmdparse.Script.parse([self.python, \"-c\"] + list(cmd))\n        with self.activated():\n            c = vistir.misc.run(script._parts, return_object=True, nospin=True, cwd=cwd, write_to_stdout=False)\n        return c",
    "docstring": "Run a python command in the enviornment context.\n\n        :param cmd: A command to run in the environment - runs with `python -c`\n        :type cmd: str or list\n        :param str cwd: The working directory in which to execute the command, defaults to :data:`os.curdir`\n        :return: A finished command object\n        :rtype: :class:`~subprocess.Popen`"
  },
  {
    "code": "def format(self, record):\n    super(CliFormatter, self).format(record)\n    localized_time = datetime.datetime.fromtimestamp(record.created)\n    terse_time = localized_time.strftime(u'%H:%M:%S')\n    terse_level = record.levelname[0]\n    terse_name = record.name.split('.')[-1]\n    match = RECORD_LOGGER_RE.match(record.name)\n    if match:\n      subsys_match = SUBSYSTEM_LOGGER_RE.match(record.name)\n      if subsys_match:\n        terse_name = '<{subsys}: {id}>'.format(\n            subsys=subsys_match.group('subsys'),\n            id=subsys_match.group('id'))\n      else:\n        terse_name = '<test %s>' % match.group('test_uid')[-5:]\n    return '{lvl} {time} {logger} - {msg}'.format(lvl=terse_level,\n                                                  time=terse_time,\n                                                  logger=terse_name,\n                                                  msg=record.message)",
    "docstring": "Format the record as tersely as possible but preserve info."
  },
  {
    "code": "def revisit(self, node, include_self=True):\n        successors = self.successors(node)\n        if include_self:\n            self._sorted_nodes.add(node)\n        for succ in successors:\n            self._sorted_nodes.add(succ)\n        self._sorted_nodes = OrderedSet(sorted(self._sorted_nodes, key=lambda n: self._node_to_index[n]))",
    "docstring": "Revisit a node in the future. As a result, the successors to this node will be revisited as well.\n\n        :param node: The node to revisit in the future.\n        :return:     None"
  },
  {
    "code": "def _validate_nested_list_type(self, name, obj, nested_level, *args):\n        if nested_level <= 1:\n            self._validate_list_type(name, obj, *args)\n        else:\n            if obj is None:\n                return\n            if not isinstance(obj, list):\n                raise TypeError(self.__class__.__name__ + '.' + name + ' contains value of type ' +\n                                type(obj).__name__ + ' where a list is expected')\n            for sub_obj in obj:\n                self._validate_nested_list_type(name, sub_obj, nested_level - 1, *args)",
    "docstring": "Helper function that checks the input object as a list then recursively until nested_level is 1.\n\n        :param name: Name of the object.\n        :param obj: Object to check the type of.\n        :param nested_level: Integer with the current nested level.\n        :param args: List of classes.\n        :raises TypeError: if the input object is not of any of the allowed types."
  },
  {
    "code": "def from_string(cls, model_id, default_project=None):\n        proj, dset, model = _helpers._parse_3_part_id(\n            model_id, default_project=default_project, property_name=\"model_id\"\n        )\n        return cls.from_api_repr(\n            {\"projectId\": proj, \"datasetId\": dset, \"modelId\": model}\n        )",
    "docstring": "Construct a model reference from model ID string.\n\n        Args:\n            model_id (str):\n                A model ID in standard SQL format. If ``default_project``\n                is not specified, this must included a project ID, dataset\n                ID, and model ID, each separated by ``.``.\n            default_project (str):\n                Optional. The project ID to use when ``model_id`` does not\n                include a project ID.\n\n        Returns:\n            google.cloud.bigquery.model.ModelReference:\n                Model reference parsed from ``model_id``.\n\n        Raises:\n            ValueError:\n                If ``model_id`` is not a fully-qualified table ID in\n                standard SQL format."
  },
  {
    "code": "def _run_workflow(items, paired, workflow_file, work_dir):\n    utils.remove_safe(os.path.join(work_dir, \"workspace\"))\n    data = paired.tumor_data if paired else items[0]\n    cmd = [utils.get_program_python(\"configManta.py\"), workflow_file, \"-m\", \"local\", \"-j\", dd.get_num_cores(data)]\n    do.run(cmd, \"Run manta SV analysis\")\n    utils.remove_safe(os.path.join(work_dir, \"workspace\"))",
    "docstring": "Run manta analysis inside prepared workflow directory."
  },
  {
    "code": "def diet_adam_optimizer_params():\n  return hparam.HParams(\n      quantize=True,\n      quantization_scale=10.0 / tf.int16.max,\n      optimizer=\"DietAdam\",\n      learning_rate=1.0,\n      learning_rate_warmup_steps=2000,\n      learning_rate_decay_scheme=\"noam\",\n      epsilon=1e-10,\n      beta1=0.0,\n      beta2=0.98,\n      factored_second_moment_accumulator=True,\n  )",
    "docstring": "Default hyperparameters for a DietAdamOptimizer.\n\n  Returns:\n    a hyperparameters object."
  },
  {
    "code": "def build_vars(path=None):\n        init_vars = {\n            \"__name__\": \"__main__\",\n            \"__package__\": None,\n            \"reload\": reload,\n        }\n        if path is not None:\n            init_vars[\"__file__\"] = fixpath(path)\n        for var in reserved_vars:\n            init_vars[var] = None\n        return init_vars",
    "docstring": "Build initial vars."
  },
  {
    "code": "def SetBackingStore(cls, backing):\n        if backing not in ['json', 'sqlite', 'memory']:\n            raise ArgumentError(\"Unknown backing store type that is not json or sqlite\", backing=backing)\n        if backing == 'json':\n            cls.BackingType = JSONKVStore\n            cls.BackingFileName = 'component_registry.json'\n        elif backing == 'memory':\n            cls.BackingType = InMemoryKVStore\n            cls.BackingFileName = None\n        else:\n            cls.BackingType = SQLiteKVStore\n            cls.BackingFileName = 'component_registry.db'",
    "docstring": "Set the global backing type used by the ComponentRegistry from this point forward\n\n        This function must be called before any operations that use the registry are initiated\n        otherwise they will work from different registries that will likely contain different data"
  },
  {
    "code": "def _init():\n    connection.connect()\n    ready_data = utils.encode_data('host:track-devices')\n    connection.adb_socket.send(ready_data)\n    status = connection.adb_socket.recv(4)\n    if status != b'OKAY':\n        raise RuntimeError('adb server return \"{}\", not OKAY'.format(str(status)))",
    "docstring": "build connection and init it"
  },
  {
    "code": "def build_archive(cls, **kwargs):\n        if cls._archive is None:\n            cls._archive = cls(**kwargs)\n        return cls._archive",
    "docstring": "Return the singleton `JobArchive` instance, building it if needed"
  },
  {
    "code": "def line_math(fx=None, fy=None, axes='gca'):\n    if axes=='gca': axes = _pylab.gca()\n    lines = axes.get_lines()\n    for line in lines:\n        if isinstance(line, _mpl.lines.Line2D):\n            xdata, ydata = line.get_data()\n            if not fx==None: xdata = fx(xdata)\n            if not fy==None: ydata = fy(ydata)\n            line.set_data(xdata,ydata)\n    _pylab.draw()",
    "docstring": "applies function fx to all xdata and fy to all ydata."
  },
  {
    "code": "def smart_import(mpath):\n    try:\n        rest = __import__(mpath)\n    except ImportError:\n        split = mpath.split('.')\n        rest = smart_import('.'.join(split[:-1]))\n        rest = getattr(rest, split[-1])\n    return rest",
    "docstring": "Given a path smart_import will import the module and return the attr reffered to."
  },
  {
    "code": "def on_valid(valid_content_type, on_invalid=json):\n    invalid_kwargs = introspect.generate_accepted_kwargs(on_invalid, 'request', 'response')\n    invalid_takes_response = introspect.takes_all_arguments(on_invalid, 'response')\n    def wrapper(function):\n        valid_kwargs = introspect.generate_accepted_kwargs(function, 'request', 'response')\n        valid_takes_response = introspect.takes_all_arguments(function, 'response')\n        @content_type(valid_content_type)\n        @wraps(function)\n        def output_content(content, response, **kwargs):\n            if type(content) == dict and 'errors' in content:\n                response.content_type = on_invalid.content_type\n                if invalid_takes_response:\n                    kwargs['response'] = response\n                return on_invalid(content, **invalid_kwargs(kwargs))\n            if valid_takes_response:\n                kwargs['response'] = response\n            return function(content, **valid_kwargs(kwargs))\n        return output_content\n    return wrapper",
    "docstring": "Renders as the specified content type only if no errors are found in the provided data object"
  },
  {
    "code": "def typed_range(type_func, minimum, maximum):\n    @functools.wraps(type_func)\n    def inner(string):\n        result = type_func(string)\n        if not result >= minimum and result <= maximum:\n            raise argparse.ArgumentTypeError(\n                    \"Please provide a value between {0} and {1}\".format(\n                        minimum, maximum))\n        return result\n    return inner",
    "docstring": "Require variables to be of the specified type, between minimum and maximum"
  },
  {
    "code": "def delete_dagobah(self, dagobah_id):\n        rec = self.dagobah_coll.find_one({'_id': dagobah_id})\n        for job in rec.get('jobs', []):\n            if 'job_id' in job:\n                self.delete_job(job['job_id'])\n        self.log_coll.remove({'parent_id': dagobah_id})\n        self.dagobah_coll.remove({'_id': dagobah_id})",
    "docstring": "Deletes the Dagobah and all child Jobs from the database.\n\n        Related run logs are deleted as well."
  },
  {
    "code": "def default_rotations(*qubits):\n    for gates in cartesian_product(TOMOGRAPHY_GATES.keys(), repeat=len(qubits)):\n        tomography_program = Program()\n        for qubit, gate in izip(qubits, gates):\n            tomography_program.inst(gate(qubit))\n        yield tomography_program",
    "docstring": "Generates the Quil programs for the tomographic pre- and post-rotations of any number of qubits.\n\n    :param list qubits: A list of qubits to perform tomography on."
  },
  {
    "code": "def make_github_markdown_collector(opts):\n    assert hasattr(opts, 'wrapper_regex')\n    atx = MarkdownATXCollectorStrategy(opts)\n    setext = MarkdownSetextCollectorStrategy(opts)\n    code_block_switch = ghswitches.code_block_switch\n    strategies = [atx, setext]\n    switches = [code_block_switch]\n    return Collector(converter.create_anchor_from_header, strategies,\n                     switches=switches)",
    "docstring": "Creates a Collector object used for parsing Markdown files with a GitHub\n    style anchor transformation\n\n    :param opts: Namespace object of options for the AnchorHub program.\n    Usually created from command-line arguments. It must contain a\n    'wrapper_regex' attribute\n    :return: a Collector object designed for collecting tag/anchor pairs from\n    Markdown files using GitHub style anchors"
  },
  {
    "code": "def binary_size(self):\n        return (\n            1 +\n            2 +\n            1 + len(self.name.encode('utf-8')) +\n            1 +\n            1 + len(self.dimensions) +\n            self.total_bytes +\n            1 + len(self.desc.encode('utf-8'))\n            )",
    "docstring": "Return the number of bytes needed to store this parameter."
  },
  {
    "code": "def _match_value_filter(self, p, value):\n        return self._VALUE_FILTER_MAP[p[0]](value[p[1]], p[2])",
    "docstring": "Returns True of False if value in the pattern p matches the filter."
  },
  {
    "code": "def compare(dicts):\n    common_members = {}\n    common_keys = reduce(lambda x, y: x & y, map(dict.keys, dicts))\n    for k in common_keys:\n        common_members[k] = list(\n            reduce(lambda x, y: x & y, [set(d[k]) for d in dicts]))\n    return common_members",
    "docstring": "Compare by iteration"
  },
  {
    "code": "def sleep(self, seconds):\n        start = self.time()\n        while (self.time() - start < seconds and\n               not self.need_to_stop.is_set()):\n            self.need_to_stop.wait(self.sim_time)",
    "docstring": "Sleep in simulated time."
  },
  {
    "code": "def match(self, url):\n        try:\n            urlSchemes = self._urlSchemes.itervalues()\n        except AttributeError:\n            urlSchemes = self._urlSchemes.values()\n        for urlScheme in urlSchemes:\n            if urlScheme.match(url):\n                return True\n        return False",
    "docstring": "Try to find if url matches against any of the schemes within this\n        endpoint.\n\n        Args:\n            url: The url to match against each scheme\n\n        Returns:\n            True if a matching scheme was found for the url, False otherwise"
  },
  {
    "code": "def get_user(self, request):\n        try:\n            return User.objects.get(username=request.data.get('username'),\n                                    is_active=True)\n        except User.DoesNotExist:\n            return None",
    "docstring": "return active user or ``None``"
  },
  {
    "code": "def is_legacy_server():\n    with Session() as session:\n        ret = session.Kernel.hello()\n    bai_version = ret['version']\n    legacy = True if bai_version <= 'v4.20181215' else False\n    return legacy",
    "docstring": "Determine execution mode.\n\n    Legacy mode: <= v4.20181215"
  },
  {
    "code": "def probability_density(self, X):\n        self.check_fit()\n        return norm.pdf(X, loc=self.mean, scale=self.std)",
    "docstring": "Compute probability density.\n\n        Arguments:\n            X: `np.ndarray` of shape (n, 1).\n\n        Returns:\n            np.ndarray"
  },
  {
    "code": "def prefix(self, keys):\n        assert isinstance(keys, tuple)\n        self._prefix = keys\n        self._load_prefix_binding()",
    "docstring": "Set a new prefix key."
  },
  {
    "code": "def _get_correlated_reports_page_generator(self, indicators, enclave_ids=None, is_enclave=True,\n                                               start_page=0, page_size=None):\n        get_page = functools.partial(self.get_correlated_reports_page, indicators, enclave_ids, is_enclave)\n        return Page.get_page_generator(get_page, start_page, page_size)",
    "docstring": "Creates a generator from the |get_correlated_reports_page| method that returns each\n        successive page.\n\n        :param indicators: A list of indicator values to retrieve correlated reports for.\n        :param enclave_ids:\n        :param is_enclave:\n        :return: The generator."
  },
  {
    "code": "def _sign_response(self, response):\n        if 'Authorization' not in request.headers:\n            return response\n        try:\n            mohawk_receiver = mohawk.Receiver(\n                credentials_map=self._client_key_loader_func,\n                request_header=request.headers['Authorization'],\n                url=request.url,\n                method=request.method,\n                content=request.get_data(),\n                content_type=request.mimetype,\n                accept_untrusted_content=current_app.config['HAWK_ACCEPT_UNTRUSTED_CONTENT'],\n                localtime_offset_in_seconds=current_app.config['HAWK_LOCALTIME_OFFSET_IN_SECONDS'],\n                timestamp_skew_in_seconds=current_app.config['HAWK_TIMESTAMP_SKEW_IN_SECONDS']\n            )\n        except mohawk.exc.HawkFail:\n            return response\n        response.headers['Server-Authorization'] = mohawk_receiver.respond(\n            content=response.data,\n            content_type=response.mimetype\n        )\n        return response",
    "docstring": "Signs a response if it's possible."
  },
  {
    "code": "def add_layer_to_canvas(layer, name):\n    if qgis_version() >= 21800:\n        layer.setName(name)\n    else:\n        layer.setLayerName(name)\n    QgsProject.instance().addMapLayer(layer, False)",
    "docstring": "Helper method to add layer to QGIS.\n\n    :param layer: The layer.\n    :type layer: QgsMapLayer\n\n    :param name: Layer name.\n    :type name: str"
  },
  {
    "code": "def write_file(self, filename):\n        with open(filename, \"w\") as f:\n            f.write(self.__str__())",
    "docstring": "Write the PWSCF input file.\n\n        Args:\n            filename (str): The string filename to output to."
  },
  {
    "code": "def get_magnitude_scaling_term(self, C, rup):\n        if rup.mag <= self.CONSTANTS[\"m_c\"]:\n            return C[\"ccr\"] * rup.mag\n        else:\n            return (C[\"ccr\"] * self.CONSTANTS[\"m_c\"]) +\\\n                (C[\"dcr\"] * (rup.mag - self.CONSTANTS[\"m_c\"]))",
    "docstring": "Returns the magnitude scaling term in equations 1 and 2"
  },
  {
    "code": "def flush(self):\n        self.notify(tuple(self._queue))\n        self._queue.clear()",
    "docstring": "Emits the current queue and clears the queue"
  },
  {
    "code": "def getDigitalActionData(self, action, unActionDataSize, ulRestrictToDevice):\n        fn = self.function_table.getDigitalActionData\n        pActionData = InputDigitalActionData_t()\n        result = fn(action, byref(pActionData), unActionDataSize, ulRestrictToDevice)\n        return result, pActionData",
    "docstring": "Reads the state of a digital action given its handle. This will return VRInputError_WrongType if the type of\n        action is something other than digital"
  },
  {
    "code": "def get_info(self, info):\r\n        if info['docstring']:\r\n            if info['filename']:\r\n                filename = os.path.basename(info['filename'])\r\n                filename = os.path.splitext(filename)[0]\r\n            else:\r\n                filename = '<module>'\r\n            resp = dict(docstring=info['docstring'],\r\n                        name=filename,\r\n                        note='',\r\n                        argspec='',\r\n                        calltip=None)\r\n            return resp\r\n        else:\r\n            return default_info_response()",
    "docstring": "Get a formatted calltip and docstring from Fallback"
  },
  {
    "code": "def get_default_prefix(self, instance=None):\n        if instance is None and hasattr(self, 'instance'):\n            instance = self.instance\n        if instance and instance.id is not None:\n            instance_prefix = self.default_instance_prefix\n            if instance_prefix is None:\n                instance_prefix = self.__class__.__name__.lower() + 'i-'\n            return '{0}{1}'.format(instance_prefix,\n                                   instance.id)\n        if self.default_new_prefix is not None:\n            return self.default_new_prefix\n        return self.__class__.__name__.lower() + 'new-'",
    "docstring": "Gets the prefix for this form.\n\n        :param instance: the form model instance.  When calling this method\n            directly this should almost always stay None so it looks for\n            self.instance."
  },
  {
    "code": "def save(self, file_name, model_name='default', overwrite=False, save_streaming_chain=False):\n        r\n        from pyemma._base.serialization.h5file import H5File\n        try:\n            with H5File(file_name=file_name, mode='a') as f:\n                f.add_serializable(model_name, obj=self, overwrite=overwrite, save_streaming_chain=save_streaming_chain)\n        except Exception as e:\n            msg = ('During saving the object {obj}\") '\n                   'the following error occurred: {error}'.format(obj=self, error=e))\n            if isinstance(self, Loggable):\n                self.logger.exception(msg)\n            else:\n                logger.exception(msg)\n            raise",
    "docstring": "r\"\"\" saves the current state of this object to given file and name.\n\n        Parameters\n        -----------\n        file_name: str\n            path to desired output file\n        model_name: str, default='default'\n            creates a group named 'model_name' in the given file, which will contain all of the data.\n            If the name already exists, and overwrite is False (default) will raise a RuntimeError.\n        overwrite: bool, default=False\n            Should overwrite existing model names?\n        save_streaming_chain : boolean, default=False\n            if True, the data_producer(s) of this object will also be saved in the given file.\n\n        Examples\n        --------\n        >>> import pyemma, numpy as np\n        >>> from pyemma.util.contexts import named_temporary_file\n        >>> m = pyemma.msm.MSM(P=np.array([[0.1, 0.9], [0.9, 0.1]]))\n\n        >>> with named_temporary_file() as file: # doctest: +SKIP\n        ...    m.save(file, 'simple') # doctest: +SKIP\n        ...    inst_restored = pyemma.load(file, 'simple') # doctest: +SKIP\n        >>> np.testing.assert_equal(m.P, inst_restored.P) # doctest: +SKIP"
  },
  {
    "code": "def invalidate(self):\n        for row in self.rows:\n            for key in row.keys:\n                key.state = 0",
    "docstring": "Rests all keys states."
  },
  {
    "code": "def open(self, writeAccess=False):\n        host = self.database().writeHost() if writeAccess else self.database().host()\n        pool = self.__pool[host]\n        if self.__poolSize[host] >= self.__maxSize or pool.qsize():\n            if pool.qsize() == 0:\n                log.warning('Waiting for connection to database!!!')\n            return pool.get()\n        else:\n            db = self.database()\n            event = orb.events.ConnectionEvent()\n            db.onPreConnect(event)\n            self.__poolSize[host] += 1\n            try:\n                conn = self._open(self.database(), writeAccess=writeAccess)\n            except Exception:\n                self.__poolSize[host] -= 1\n                raise\n            else:\n                event = orb.events.ConnectionEvent(success=conn is not None, native=conn)\n                db.onPostConnect(event)\n                return conn",
    "docstring": "Returns the sqlite database for the current thread.\n\n        :return     <variant> || None"
  },
  {
    "code": "def cli_form(self, *args):\n        if args[0] == '*':\n            for schema in schemastore:\n                self.log(schema, ':', schemastore[schema]['form'], pretty=True)\n        else:\n            self.log(schemastore[args[0]]['form'], pretty=True)",
    "docstring": "Display a schemata's form definition"
  },
  {
    "code": "def get_partition_vrfProf(self, org_name, part_name=None, part_info=None):\n        vrf_profile = None\n        if part_info is None:\n            part_info = self._get_partition(org_name, part_name)\n            LOG.info(\"query result from dcnm for partition info is %s\",\n                     part_info)\n        if (\"vrfProfileName\" in part_info):\n            vrf_profile = part_info.get(\"vrfProfileName\")\n        return vrf_profile",
    "docstring": "get VRF Profile for the partition from the DCNM.\n\n        :param org_name: name of organization\n        :param part_name: name of partition"
  },
  {
    "code": "def with_exit_condition(self, exit_condition: Optional[bool]=True) -> 'MonitorTask':\n        self._exit_condition = exit_condition\n        return self",
    "docstring": "Sets the flag indicating that the task should also run after the optimisation is ended."
  },
  {
    "code": "def _assemble_translocation(stmt):\n    agent_str = _assemble_agent_str(stmt.agent)\n    stmt_str = agent_str + ' translocates'\n    if stmt.from_location is not None:\n        stmt_str += ' from the ' + stmt.from_location\n    if stmt.to_location is not None:\n        stmt_str += ' to the ' + stmt.to_location\n    return _make_sentence(stmt_str)",
    "docstring": "Assemble Translocation statements into text."
  },
  {
    "code": "def Popen(self, cmd, **kwargs):\n        prefixed_cmd = self._prepare_cmd(cmd)\n        return subprocess.Popen(prefixed_cmd, **kwargs)",
    "docstring": "Remote Popen."
  },
  {
    "code": "def yaml_dquote(text):\n    with io.StringIO() as ostream:\n        yemitter = yaml.emitter.Emitter(ostream, width=six.MAXSIZE)\n        yemitter.write_double_quoted(six.text_type(text))\n        return ostream.getvalue()",
    "docstring": "Make text into a double-quoted YAML string with correct escaping\n    for special characters.  Includes the opening and closing double\n    quote characters."
  },
  {
    "code": "def set_author(self):\n        try:\n            self.author = self.soup.find('author').string\n        except AttributeError:\n            self.author = None",
    "docstring": "Parses author and set value."
  },
  {
    "code": "def sorted_maybe_numeric(x):\n    all_numeric = all(map(str.isdigit, x))\n    if all_numeric:\n        return sorted(x, key=int)\n    else:\n        return sorted(x)",
    "docstring": "Sorts x with numeric semantics if all keys are nonnegative integers.\n    Otherwise uses standard string sorting."
  },
  {
    "code": "def clean(self):\n        if not self.urlhash or 'url' in self._get_changed_fields():\n            self.urlhash = hash_url(self.url)\n        super(Reuse, self).clean()",
    "docstring": "Auto populate urlhash from url"
  },
  {
    "code": "def model_post_save(sender, instance, created=False, **kwargs):\n    if sender._meta.app_label == 'rest_framework_reactive':\n        return\n    def notify():\n        table = sender._meta.db_table\n        if created:\n            notify_observers(table, ORM_NOTIFY_KIND_CREATE, instance.pk)\n        else:\n            notify_observers(table, ORM_NOTIFY_KIND_UPDATE, instance.pk)\n    transaction.on_commit(notify)",
    "docstring": "Signal emitted after any model is saved via Django ORM.\n\n    :param sender: Model class that was saved\n    :param instance: The actual instance that was saved\n    :param created: True if a new row was created"
  },
  {
    "code": "def add_ticks_to_x(ax, newticks, newnames):\n    ticks = list(ax.get_xticks())\n    ticks.extend(newticks)\n    ax.set_xticks(ticks)\n    names = list(ax.get_xticklabels())\n    names.extend(newnames)\n    ax.set_xticklabels(names)",
    "docstring": "Add new ticks to an axis.\n\n    I use this for the right-hand plotting of resonance names in my plots."
  },
  {
    "code": "def valid_config_exists(config_path=CONFIG_PATH):\n    if os.path.isfile(config_path):\n        try:\n            config = read_config(config_path)\n            check_config(config)\n        except (ConfigurationError, IOError):\n            return False\n    else:\n        return False\n    return True",
    "docstring": "Verify that a valid config file exists.\n\n    Args:\n        config_path (str): Path to the config file.\n\n    Returns:\n        boolean: True if there is a valid config file, false if not."
  },
  {
    "code": "def update_channels(cls, installation_id, channels_to_add=set(),\n                        channels_to_remove=set(), **kw):\n        installation_url = cls._get_installation_url(installation_id)\n        current_config = cls.GET(installation_url)\n        new_channels = list(set(current_config['channels']).union(channels_to_add).difference(channels_to_remove))\n        cls.PUT(installation_url, channels=new_channels)",
    "docstring": "Allow an application to manually subscribe or unsubscribe an\n        installation to a certain push channel in a unified operation.\n\n        this is based on:\n        https://www.parse.com/docs/rest#installations-updating\n\n        installation_id: the installation id you'd like to add a channel to\n        channels_to_add: the name of the channel you'd like to subscribe the user to\n        channels_to_remove: the name of the channel you'd like to unsubscribe the user from"
  },
  {
    "code": "def _clean_data(self, str_value, file_data, obj_value):\n        str_value = str_value or None\n        obj_value = obj_value or None\n        return (str_value, None, obj_value)",
    "docstring": "This overwrite is neccesary for work with multivalues"
  },
  {
    "code": "def to_glyphs_master_user_data(self, ufo, master):\n    target_user_data = master.userData\n    for key, value in ufo.lib.items():\n        if _user_data_has_no_special_meaning(key):\n            target_user_data[key] = value\n    if ufo.data.fileNames:\n        from glyphsLib.types import BinaryData\n        ufo_data = {}\n        for os_filename in ufo.data.fileNames:\n            filename = posixpath.join(*os_filename.split(os.path.sep))\n            ufo_data[filename] = BinaryData(ufo.data[os_filename])\n        master.userData[UFO_DATA_KEY] = ufo_data",
    "docstring": "Set the GSFontMaster userData from the UFO master-specific lib data."
  },
  {
    "code": "def get_git_isolation():\n    ctx = click.get_current_context(silent=True)\n    if ctx and GIT_ISOLATION in ctx.meta:\n        return ctx.meta[GIT_ISOLATION]",
    "docstring": "Get Git isolation from the current context."
  },
  {
    "code": "def arp_packet(opcode, src_mac, src_ip, dst_mac, dst_ip):\n        pkt = packet.Packet()\n        eth_pkt = ethernet.ethernet(dst_mac, src_mac, ETH_TYPE_ARP)\n        pkt.add_protocol(eth_pkt)\n        arp_pkt = arp.arp_ip(opcode, src_mac, src_ip, dst_mac, dst_ip)\n        pkt.add_protocol(arp_pkt)\n        pkt.serialize()\n        return pkt.data",
    "docstring": "Generate ARP packet with ethernet encapsulated."
  },
  {
    "code": "def _translate_space(self, space):\n        self.space = []\n        self.dimensionality = 0\n        self.has_types = d = {t: False for t in self.supported_types}\n        for i, d in enumerate(space):\n            descriptor = deepcopy(d)\n            descriptor['name'] = descriptor.get('name', 'var_' + str(i))\n            descriptor['type'] = descriptor.get('type', 'continuous')\n            if 'domain' not in descriptor:\n                raise InvalidConfigError('Domain attribute is missing for variable ' + descriptor['name'])\n            variable = create_variable(descriptor)\n            self.space.append(variable)\n            self.dimensionality += variable.dimensionality\n            self.has_types[variable.type] = True\n        if any(v.is_bandit() for v in self.space) and any(not v.is_bandit() for v in self.space):\n            raise InvalidConfigError('Invalid mixed domain configuration. Bandit variables cannot be mixed with other types.')",
    "docstring": "Translates a list of dictionaries into internal list of variables"
  },
  {
    "code": "def undo(self, change=None, drop=False,\n             task_handle=taskhandle.NullTaskHandle()):\n        if not self._undo_list:\n            raise exceptions.HistoryError('Undo list is empty')\n        if change is None:\n            change = self.undo_list[-1]\n        dependencies = self._find_dependencies(self.undo_list, change)\n        self._move_front(self.undo_list, dependencies)\n        self._perform_undos(len(dependencies), task_handle)\n        result = self.redo_list[-len(dependencies):]\n        if drop:\n            del self.redo_list[-len(dependencies):]\n        return result",
    "docstring": "Redo done changes from the history\n\n        When `change` is `None`, the last done change will be undone.\n        If change is not `None` it should be an item from\n        `self.undo_list`; this change and all changes that depend on\n        it will be undone.  In both cases the list of undone changes\n        will be returned.\n\n        If `drop` is `True`, the undone change will not be appended to\n        the redo list."
  },
  {
    "code": "def unmount(self):\n        self.unmount_bindmounts()\n        self.unmount_mounts()\n        self.unmount_volume_groups()\n        self.unmount_loopbacks()\n        self.unmount_base_images()\n        self.clean_dirs()",
    "docstring": "Calls all unmount methods in the correct order."
  },
  {
    "code": "def interactive(outdir):\n    print(\"Building your Blended files into a website!\")\n    global outdir_type\n    outdir_type = outdir\n    reload(sys)\n    sys.setdefaultencoding('utf8')\n    build_files(outdir)\n    print(\"Watching the content and templates directories for changes, press CTRL+C to stop...\\n\")\n    w = Watcher()\n    w.run()",
    "docstring": "Blends the generated files and outputs a HTML website on file change"
  },
  {
    "code": "def _compile_and_collapse(self):\n        self._real_regex = self._real_re_compile(*self._regex_args,\n                                                 **self._regex_kwargs)\n        for attr in self._regex_attributes_to_copy:\n            setattr(self, attr, getattr(self._real_regex, attr))",
    "docstring": "Actually compile the requested regex"
  },
  {
    "code": "def silent_execute(self, code):\n        try:\n            self.kernel_client.execute(to_text_string(code), silent=True)\n        except AttributeError:\n            pass",
    "docstring": "Execute code in the kernel without increasing the prompt"
  },
  {
    "code": "def stop(self):\n        distributed_logger.info('Stopping metrics aggregator')\n        self.process.terminate()\n        self.process.join()\n        distributed_logger.info('Stopped metrics aggregator')",
    "docstring": "Terminates the forked process.\n\n        Only valid if started as a fork, because... well you wouldn't get here otherwise.\n        :return:"
  },
  {
    "code": "def impute_knn(df, k=3):\n        imputed_matrix = KNN(k=k).complete(df.values)\n        imputed_df = pd.DataFrame(imputed_matrix, df.index, df.columns)\n        return imputed_df",
    "docstring": "Nearest neighbour imputations which weights samples using the mean squared difference on features for which two rows both have observed data.\n\n        :param df: The input dataframe that contains missing values\n        :param k: The number of neighbours\n        :return: the imputed dataframe"
  },
  {
    "code": "def vectorize(fn):\n    @functools.wraps(fn)\n    def vectorized_function(values, *vargs, **kwargs):\n        return [fn(value, *vargs, **kwargs) for value in values]\n    return vectorized_function",
    "docstring": "Allows a method to accept a list argument, but internally deal only\n    with a single item of that list."
  },
  {
    "code": "def list_nodes(**kwargs):\n    ret = {}\n    nodes = list_nodes_full()\n    for node in nodes:\n        ret[node] = {}\n        for prop in 'id', 'image', 'size', 'state', 'private_ips', 'public_ips':\n            ret[node][prop] = nodes[node][prop]\n    return ret",
    "docstring": "Return basic data on nodes"
  },
  {
    "code": "def registration_function_for_optionable(self, optionable_class):\n    self._assert_not_frozen()\n    def register(*args, **kwargs):\n      kwargs['registering_class'] = optionable_class\n      self.register(optionable_class.options_scope, *args, **kwargs)\n    register.bootstrap = self.bootstrap_option_values()\n    register.scope = optionable_class.options_scope\n    return register",
    "docstring": "Returns a function for registering options on the given scope."
  },
  {
    "code": "def clear_cache_delete_selected(modeladmin, request, queryset):\n    result = delete_selected(modeladmin, request, queryset)\n    if not result and hasattr(modeladmin, 'invalidate_cache'):\n        modeladmin.invalidate_cache(queryset=queryset)\n    return result",
    "docstring": "A delete action that will invalidate cache after being called."
  },
  {
    "code": "def _validate_all_tags_are_used(metadata):\n    tag_names = set([tag_name for tag_name, _ in metadata.tags])\n    filter_arg_names = set()\n    for location, _ in metadata.registered_locations:\n        for filter_info in metadata.get_filter_infos(location):\n            for filter_arg in filter_info.args:\n                if is_tag_argument(filter_arg):\n                    filter_arg_names.add(get_directive_argument_name(filter_arg))\n    unused_tags = tag_names - filter_arg_names\n    if unused_tags:\n        raise GraphQLCompilationError(u'This GraphQL query contains @tag directives whose values '\n                                      u'are not used: {}. This is not allowed. Please either use '\n                                      u'them in a filter or remove them entirely.'\n                                      .format(unused_tags))",
    "docstring": "Ensure all tags are used in some filter."
  },
  {
    "code": "def sample(self, data, interval):\n        data_slice = dict()\n        for key in data:\n            if '_valid' in key:\n                continue\n            index = [slice(None)] * data[key].ndim\n            index[0] = self.rng.randint(0, data[key].shape[0])\n            index[0] = slice(index[0], index[0] + 1)\n            for tdim in self._time[key]:\n                index[tdim] = interval\n            data_slice[key] = data[key][tuple(index)]\n        return data_slice",
    "docstring": "Sample a patch from the data object\n\n        Parameters\n        ----------\n        data : dict\n            A data dict as produced by pumpp.Pump.transform\n\n        interval : slice\n            The time interval to sample\n\n        Returns\n        -------\n        data_slice : dict\n            `data` restricted to `interval`."
  },
  {
    "code": "def ilsr_pairwise_dense(\n        comp_mat, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8):\n    fun = functools.partial(\n            lsr_pairwise_dense, comp_mat=comp_mat, alpha=alpha)\n    return _ilsr(fun, initial_params, max_iter, tol)",
    "docstring": "Compute the ML estimate of model parameters given dense data.\n\n    This function computes the maximum-likelihood (ML) estimate of model\n    parameters given dense pairwise-comparison data.\n\n    The data is described by a pairwise-comparison matrix ``comp_mat`` such\n    that ``comp_mat[i,j]`` contains the number of times that item ``i`` wins\n    against item ``j``.\n\n    In comparison to :func:`~choix.ilsr_pairwise`, this function is\n    particularly efficient for dense pairwise-comparison datasets (i.e.,\n    containing many comparisons for a large fraction of item pairs).\n\n    The transition rates of the LSR Markov chain are initialized with\n    ``alpha``. When ``alpha > 0``, this corresponds to a form of regularization\n    (see :ref:`regularization` for details).\n\n    Parameters\n    ----------\n    comp_mat : np.array\n        2D square matrix describing the pairwise-comparison outcomes.\n    alpha : float, optional\n        Regularization parameter.\n    initial_params : array_like, optional\n        Parameters used to initialize the iterative procedure.\n    max_iter : int, optional\n        Maximum number of iterations allowed.\n    tol : float, optional\n        Maximum L1-norm of the difference between successive iterates to\n        declare convergence.\n\n    Returns\n    -------\n    params : numpy.ndarray\n        The ML estimate of model parameters."
  },
  {
    "code": "def sam_readline(sock, partial = None):\n    response = b''\n    exception = None\n    while True:\n        try:\n            c = sock.recv(1)\n            if not c:\n                raise EOFError('SAM connection died. Partial response %r %r' % (partial, response))\n            elif c == b'\\n':\n                break\n            else:\n                response += c\n        except (BlockingIOError, pysocket.timeout) as e:\n            if partial is None:\n                raise e\n            else:\n                exception = e\n                break\n    if partial is None:\n        return response.decode('ascii')\n    else:\n        return (partial + response.decode('ascii'), exception)",
    "docstring": "read a line from a sam control socket"
  },
  {
    "code": "def _get_token_from_headers(self, request, refresh_token):\n        header = request.headers.get(self.config.authorization_header(), None)\n        if header is None:\n            return None\n        else:\n            header_prefix_key = \"authorization_header_prefix\"\n            header_prefix = getattr(self.config, header_prefix_key)\n            if header_prefix():\n                try:\n                    prefix, token = header.split(\" \")\n                    if prefix != header_prefix():\n                        raise Exception\n                except Exception:\n                    raise exceptions.InvalidAuthorizationHeader()\n            else:\n                token = header\n            if refresh_token:\n                token = request.json.get(self.config.refresh_token_name())\n            return token",
    "docstring": "Extract the token if present inside the headers of a request."
  },
  {
    "code": "def content_types(self):\n        return EnvironmentContentTypesProxy(self._client, self.space.id, self.id)",
    "docstring": "Provides access to content type management methods for content types of an environment.\n\n        API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/content-types\n\n        :return: :class:`EnvironmentContentTypesProxy <contentful_management.space_content_types_proxy.EnvironmentContentTypesProxy>` object.\n        :rtype: contentful.space_content_types_proxy.EnvironmentContentTypesProxy\n\n        Usage:\n\n            >>> space_content_types_proxy = environment.content_types()\n            <EnvironmentContentTypesProxy space_id=\"cfexampleapi\" environment_id=\"master\">"
  },
  {
    "code": "def tag(self, text):\n        matches = self._match(text.text)\n        matches = self._resolve_conflicts(matches)\n        if self.return_layer:\n            return matches\n        else:\n            text[self.layer_name] = matches",
    "docstring": "Retrieves list of regex_matches in text.\n\n        Parameters\n        ----------\n        text: Text\n            The estnltk text object to search for events.\n\n        Returns\n        -------\n        list of matches"
  },
  {
    "code": "def register_error(self, code=1, errmsg=None):\n        if errmsg is not None:\n            if self.errmsg is None:\n                self.errmsg = errmsg\n            elif errmsg not in self.errmsg:\n                self.errmsg += \", \" + errmsg\n        if code is not None:\n            self.exit_code = max(self.exit_code, code)",
    "docstring": "Update the exit code."
  },
  {
    "code": "def update_default_iou_values(self):\n        try:\n            output = yield from gns3server.utils.asyncio.subprocess_check_output(self._path, \"-h\", cwd=self.working_dir, stderr=True)\n            match = re.search(\"-n <n>\\s+Size of nvram in Kb \\(default ([0-9]+)KB\\)\", output)\n            if match:\n                self.nvram = int(match.group(1))\n            match = re.search(\"-m <n>\\s+Megabytes of router memory \\(default ([0-9]+)MB\\)\", output)\n            if match:\n                self.ram = int(match.group(1))\n        except (ValueError, OSError, subprocess.SubprocessError) as e:\n            log.warning(\"could not find default RAM and NVRAM values for {}: {}\".format(os.path.basename(self._path), e))",
    "docstring": "Finds the default RAM and NVRAM values for the IOU image."
  },
  {
    "code": "def reflect_well(value, bounds):\n    while value not in bounds:\n        value = bounds._max.reflect_left(value)\n        value = bounds._min.reflect_right(value)\n    return value",
    "docstring": "Given some boundaries, reflects the value until it falls within both\n    boundaries. This is done iteratively, reflecting left off of the\n    `boundaries.max`, then right off of the `boundaries.min`, etc.\n\n    Parameters\n    ----------\n    value : float\n        The value to apply the reflected boundaries to.\n    bounds : Bounds instance\n        Boundaries to reflect between. Both `bounds.min` and `bounds.max` must\n        be instances of `ReflectedBound`, otherwise an AttributeError is\n        raised.\n\n    Returns\n    -------\n    float\n        The value after being reflected between the two bounds."
  },
  {
    "code": "def get_queryset(self):\n        queryset    = super(IndexView, self).get_queryset()\n        search_form = self.get_search_form()\n        if search_form.is_valid():\n            query_str   = search_form.cleaned_data.get('q', '').strip()\n            queryset    = self.model.objects.search(query_str)\n        return queryset",
    "docstring": "Returns queryset instance.\n\n        :rtype: django.db.models.query.QuerySet."
  },
  {
    "code": "def get_tag_context(name, state):\n    new_contexts = 0\n    ctm = None\n    while True:\n        try:\n            ctx_key, name = name.split('.', 1)\n            ctm = state.context.get(ctx_key)\n        except ValueError:\n            break\n        if not ctm:\n            break\n        else:\n            state.context.push(ctm)\n            new_contexts += 1\n    ctm = state.context.get(name)\n    return new_contexts, ctm",
    "docstring": "Given a tag name, return its associated value as defined in the current\n    context stack."
  },
  {
    "code": "def sendACK(self, blocknumber=None):\n        log.debug(\"In sendACK, passed blocknumber is %s\", blocknumber)\n        if blocknumber is None:\n            blocknumber = self.context.next_block\n        log.info(\"Sending ack to block %d\" % blocknumber)\n        ackpkt = TftpPacketACK()\n        ackpkt.blocknumber = blocknumber\n        self.context.sock.sendto(ackpkt.encode().buffer,\n                                 (self.context.host,\n                                  self.context.tidport))\n        self.context.last_pkt = ackpkt",
    "docstring": "This method sends an ack packet to the block number specified. If\n        none is specified, it defaults to the next_block property in the\n        parent context."
  },
  {
    "code": "def apply(self, im):\n        from scipy.ndimage.interpolation import shift\n        im = rollaxis(im, self.axis)\n        im.setflags(write=True)\n        for ind in range(0, im.shape[0]):\n            im[ind] = shift(im[ind],  map(lambda x: -x, self.delta[ind]), mode='nearest')\n        im = rollaxis(im, 0, self.axis+1)\n        return im",
    "docstring": "Apply axis-localized displacements.\n\n        Parameters\n        ----------\n        im : ndarray\n            The image or volume to shift"
  },
  {
    "code": "def render_css(self, fn=None, text=None, margin='', indent='\\t'):\n        fn = fn or os.path.splitext(self.fn)[0]+'.css'\n        if not os.path.exists(os.path.dirname(fn)):\n            os.makedirs(os.path.dirname(fn))\n        curdir = os.path.abspath(os.curdir)\n        os.chdir(os.path.dirname(fn))\n        text = text or self.render_styles()\n        if text != '': text = sass.compile(string=text)\n        os.chdir(curdir)\n        return CSS(fn=fn, text=text)",
    "docstring": "output css using the Sass processor"
  },
  {
    "code": "def load_spectrum(filename):\n    import f311\n    f = load_with_classes(filename, f311.classes_sp())\n    if f:\n        return f.spectrum\n    return None",
    "docstring": "Attempts to load spectrum as one of the supported types.\n\n    Returns:\n        a Spectrum, or None"
  },
  {
    "code": "def extract_bus_routine(page):\n    if not isinstance(page, pq):\n        page = pq(page)\n    stations = extract_stations(page)\n    return {\n        'name': extract_routine_name(page),\n        'stations': stations,\n        'current': extract_current_routine(page, stations)\n    }",
    "docstring": "Extract bus routine information from page.\n\n    :param page: crawled page."
  },
  {
    "code": "def load(name, **kwargs):\n    ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}\n    ret['changes'] = __salt__['junos.load'](name, **kwargs)\n    return ret",
    "docstring": "Loads the configuration provided onto the junos device.\n\n    .. code-block:: yaml\n\n            Install the mentioned config:\n              junos:\n                - load\n                - path: salt//configs/interface.set\n\n    .. code-block:: yaml\n\n            Install the mentioned config:\n              junos:\n                - load\n                - template_path: salt//configs/interface.set\n                - template_vars:\n                    interface_name: lo0\n                    description: Creating interface via SaltStack.\n\n\n    name\n        Path where the configuration/template file is present. If the file has\n        a ``*.conf`` extension, the content is treated as text format. If the\n        file has a ``*.xml`` extension, the content is treated as XML format. If\n        the file has a ``*.set`` extension, the content is treated as Junos OS\n        ``set`` commands.\n\n    overwrite : False\n        Set to ``True`` if you want this file is to completely replace the\n        configuration file.\n\n    replace : False\n        Specify whether the configuration file uses \"replace:\" statements.\n        Only those statements under the 'replace' tag will be changed.\n\n    format:\n      Determines the format of the contents.\n\n    update : False\n        Compare a complete loaded configuration against the candidate\n        configuration. For each hierarchy level or configuration object that is\n        different in the two configurations, the version in the loaded\n        configuration replaces the version in the candidate configuration. When\n        the configuration is later committed, only system processes that are\n        affected by the changed configuration elements parse the new\n        configuration. This action is supported from PyEZ 2.1 (default = False)\n\n    template_vars\n      Variables to be passed into the template processing engine in addition\n      to those present in __pillar__, __opts__, __grains__, etc.\n      You may reference these variables in your template like so:\n      {{ template_vars[\"var_name\"] }}"
  },
  {
    "code": "def validate(self, val):\n        if val in self.values:\n            return True, None\n        else:\n            return False, \"'%s' is not in enum: %s\" % (val, str(self.values))",
    "docstring": "Validates that the val is in the list of values for this Enum.\n\n        Returns two element tuple: (bool, string)\n\n        - `bool` - True if valid, False if not\n        - `string` - Description of validation error, or None if valid\n\n        :Parameters:\n          val\n            Value to validate.  Should be a string."
  },
  {
    "code": "def fermi_dist(energy, beta):\n    exponent = np.asarray(beta*energy).clip(-600, 600)\n    return 1./(np.exp(exponent) + 1)",
    "docstring": "Fermi Dirac distribution"
  },
  {
    "code": "def __parse_drac(output):\n    drac = {}\n    section = ''\n    for i in output.splitlines():\n        if i.strip().endswith(':') and '=' not in i:\n            section = i[0:-1]\n            drac[section] = {}\n        if i.rstrip() and '=' in i:\n            if section in drac:\n                drac[section].update(dict(\n                    [[prop.strip() for prop in i.split('=')]]\n                ))\n            else:\n                section = i.strip()\n                if section not in drac and section:\n                    drac[section] = {}\n    return drac",
    "docstring": "Parse Dell DRAC output"
  },
  {
    "code": "def transform(self, context, handler, result):\n\t\thandler = handler.__func__ if hasattr(handler, '__func__') else handler\n\t\tannotation = getattr(handler, '__annotations__', {}).get('return', None)\n\t\tif annotation:\n\t\t\treturn (annotation, result)\n\t\treturn result",
    "docstring": "Transform the value returned by the controller endpoint.\n\t\t\n\t\tThis extension transforms returned values if the endpoint has a return type annotation."
  },
  {
    "code": "def to_node(value):\n    if isinstance(value, Node):\n        return value\n    elif isinstance(value, str):\n        return Node('string', value=value, pseudo_type='String')\n    elif isinstance(value, int):\n        return Node('int', value=value, pseudo_type='Int')\n    elif isinstance(value, bool):\n        return Node('boolean', value=str(value).lower(), pseudo_type='Boolean')\n    elif isinstance(value, float):\n        return Node('float', value=value, pseudo_type='Float')\n    elif value is None:\n        return Node('null', pseudo_type='Void')\n    else:\n        1/0",
    "docstring": "Expand to a literal node if a basic type otherwise just returns the node"
  },
  {
    "code": "def extract_fieldnames(config):\n    fields = []\n    for x in get_fields(config):\n        if x in fields:\n            fields.append(x + '_' + str(fields.count(x) + 1))\n        else:\n            fields.append(x)\n    return fields",
    "docstring": "Function to return a list of unique field names from the config file\n\n    :param config: The configuration file that contains the specification of the extractor\n    :return: A list of field names from the config file"
  },
  {
    "code": "def write_config(self):\n        json.dump(\n            self.config,\n            open(CONFIG_FILE, 'w'),\n            indent=4,\n            separators=(',', ': ')\n        )\n        return True",
    "docstring": "Write the configuration to a local file.\n\n        :return: Boolean if successful"
  },
  {
    "code": "def list_records(self, file_const=None):\n        for r in self._dataset.files:\n            if file_const and r.minor_type != file_const:\n                continue\n            yield self.instance_from_name(r.path)",
    "docstring": "Iterate through the file records"
  },
  {
    "code": "def _validate_install(self):\r\n        self.printer('Checking heroku installation ... ', flush=True)\r\n        from os import devnull\r\n        from subprocess import call, check_output\r\n        sys_command = 'heroku --version'\r\n        try:\r\n            call(sys_command, shell=True, stdout=open(devnull, 'wb'))\r\n        except Exception as err:\r\n            self.printer('ERROR')\r\n            raise Exception('\"heroku cli\" not installed. GoTo: https://devcenter.heroku.com/articles/heroku-cli')\r\n        self.printer('done.')\r\n        return True",
    "docstring": "a method to validate heroku is installed"
  },
  {
    "code": "def set_status(self, enabled):\n        self.__manual_update_time = time.time()\n        if enabled:\n            data = self._controller.command(self._id,\n                                            'auto_conditioning_start',\n                                            wake_if_asleep=True)\n            if data['response']['result']:\n                self.__is_auto_conditioning_on = True\n                self.__is_climate_on = True\n        else:\n            data = self._controller.command(self._id,\n                                            'auto_conditioning_stop',\n                                            wake_if_asleep=True)\n            if data['response']['result']:\n                self.__is_auto_conditioning_on = False\n                self.__is_climate_on = False\n        self.update()",
    "docstring": "Enable or disable the HVAC."
  },
  {
    "code": "def load(self, config):\n        password_dict = {}\n        if config is None:\n            logger.warning(\"No configuration file available. Cannot load password list.\")\n        elif not config.has_section(self._section):\n            logger.warning(\"No [%s] section in the configuration file. Cannot load password list.\" % self._section)\n        else:\n            logger.info(\"Start reading the [%s] section in the configuration file\" % self._section)\n            password_dict = dict(config.items(self._section))\n            logger.info(\"%s password(s) loaded from the configuration file\" % len(password_dict))\n            logger.debug(\"Password dictionary: %s\" % password_dict)\n        return password_dict",
    "docstring": "Load the password from the configuration file."
  },
  {
    "code": "def kernels_push_cli(self, folder):\n        folder = folder or os.getcwd()\n        result = self.kernels_push(folder)\n        if result is None:\n            print('Kernel push error: see previous output')\n        elif not result.error:\n            if result.invalidTags:\n                print(\n                    'The following are not valid tags and could not be added '\n                    'to the kernel: ' + str(result.invalidTags))\n            if result.invalidDatasetSources:\n                print(\n                    'The following are not valid dataset sources and could not '\n                    'be added to the kernel: ' +\n                    str(result.invalidDatasetSources))\n            if result.invalidCompetitionSources:\n                print(\n                    'The following are not valid competition sources and could '\n                    'not be added to the kernel: ' +\n                    str(result.invalidCompetitionSources))\n            if result.invalidKernelSources:\n                print(\n                    'The following are not valid kernel sources and could not '\n                    'be added to the kernel: ' +\n                    str(result.invalidKernelSources))\n            if result.versionNumber:\n                print('Kernel version %s successfully pushed.  Please check '\n                      'progress at %s' % (result.versionNumber, result.url))\n            else:\n                print('Kernel version successfully pushed.  Please check '\n                      'progress at %s' % result.url)\n        else:\n            print('Kernel push error: ' + result.error)",
    "docstring": "client wrapper for kernels_push, with same arguments."
  },
  {
    "code": "def startAll(self):\n\t\tself.logger.info(\"Starting all workers...\")\n\t\tfor worker in self.getWorkers():\n\t\t\tprocess = self.getWorker(worker)\n\t\t\tself.logger.debug(\"Starting {0}\".format(process.name))\n\t\t\tprocess.start()\n\t\tself.logger.info(\"Started all workers\")",
    "docstring": "Start all registered Workers."
  },
  {
    "code": "def _read_channel(channel, stream, start, duration):\n    channel_type = lalframe.FrStreamGetTimeSeriesType(channel, stream)\n    read_func = _fr_type_map[channel_type][0]\n    d_type = _fr_type_map[channel_type][1]\n    data = read_func(stream, channel, start, duration, 0)\n    return TimeSeries(data.data.data, delta_t=data.deltaT, epoch=start,\n                      dtype=d_type)",
    "docstring": "Get channel using lalframe"
  },
  {
    "code": "def any_validator(obj, validators, **kwargs):\n    if not len(validators) > 1:\n        raise ValueError(\n            \"any_validator requires at least 2 validator.  Only got \"\n            \"{0}\".format(len(validators))\n        )\n    errors = ErrorDict()\n    for key, validator in validators.items():\n        try:\n            validator(obj, **kwargs)\n        except ValidationError as err:\n            errors[key] = err.detail\n        else:\n            break\n    else:\n        if len(errors) == 1:\n            error = errors.values()[0]\n            raise ValidationError(error)\n        else:\n            errors.raise_()",
    "docstring": "Attempt multiple validators on an object.\n\n    - If any pass, then all validation passes.\n    - Otherwise, raise all of the errors."
  },
  {
    "code": "def rotate(self):\n        self._index -= 1\n        if self._index >= 0:\n            return self._ring[self._index]\n        return None",
    "docstring": "Rotate the kill ring, then yank back the new top.\n\n        Returns\n        -------\n        A text string or None."
  },
  {
    "code": "def export_gpx_file(self):\n        gpx = create_elem('gpx', GPX_ELEM_ATTRIB)\n        if not self.metadata.bounds:\n            self.metadata.bounds = [j for i in self for j in i]\n        gpx.append(self.metadata.togpx())\n        track = create_elem('trk')\n        gpx.append(track)\n        for segment in self:\n            chunk = create_elem('trkseg')\n            track.append(chunk)\n            for place in segment:\n                chunk.append(place.togpx())\n        return etree.ElementTree(gpx)",
    "docstring": "Generate GPX element tree from ``Trackpoints``.\n\n        Returns:\n            etree.ElementTree: GPX element tree depicting ``Trackpoints``\n                objects"
  },
  {
    "code": "def privacy_options_view(request):\n    if \"user\" in request.GET:\n        user = User.objects.user_with_ion_id(request.GET.get(\"user\"))\n    elif \"student_id\" in request.GET:\n        user = User.objects.user_with_student_id(request.GET.get(\"student_id\"))\n    else:\n        user = request.user\n    if not user:\n        messages.error(request, \"Invalid user.\")\n        user = request.user\n    if user.is_eighthoffice:\n        user = None\n    if user:\n        if request.method == \"POST\":\n            privacy_options_form = save_privacy_options(request, user)\n        else:\n            privacy_options = get_privacy_options(user)\n            privacy_options_form = PrivacyOptionsForm(user, initial=privacy_options)\n        context = {\"privacy_options_form\": privacy_options_form, \"profile_user\": user}\n    else:\n        context = {\"profile_user\": user}\n    return render(request, \"preferences/privacy_options.html\", context)",
    "docstring": "View and edit privacy options for a user."
  },
  {
    "code": "def protect_pip_from_modification_on_windows(modifying_pip):\n    pip_names = [\n        \"pip.exe\",\n        \"pip{}.exe\".format(sys.version_info[0]),\n        \"pip{}.{}.exe\".format(*sys.version_info[:2])\n    ]\n    should_show_use_python_msg = (\n        modifying_pip and\n        WINDOWS and\n        os.path.basename(sys.argv[0]) in pip_names\n    )\n    if should_show_use_python_msg:\n        new_command = [\n            sys.executable, \"-m\", \"pip\"\n        ] + sys.argv[1:]\n        raise CommandError(\n            'To modify pip, please run the following command:\\n{}'\n            .format(\" \".join(new_command))\n        )",
    "docstring": "Protection of pip.exe from modification on Windows\n\n    On Windows, any operation modifying pip should be run as:\n        python -m pip ..."
  },
  {
    "code": "def close(self):\n        if self._connection:\n            self._connection_file.close()\n            self._connection_file = None\n            self._connection.close()\n            self._connection = None",
    "docstring": "Closes connection with the q service."
  },
  {
    "code": "def knapsack_iterative(items, maxweight):\n    weights = [t[1] for t in items]\n    max_exp = max([number_of_decimals(w_) for w_ in weights])\n    coeff = 10 ** max_exp\n    int_maxweight = int(maxweight * coeff)\n    int_items = [(v, int(w * coeff), idx) for v, w, idx in items]\n    return knapsack_iterative_int(int_items, int_maxweight)",
    "docstring": "items = int_items\n    maxweight = int_maxweight"
  },
  {
    "code": "def get_stream_formats(self, media_item):\n        scraper = ScraperApi(self._ajax_api._connector)\n        formats = scraper.get_media_formats(media_item.media_id)\n        return formats",
    "docstring": "Get the available media formats for a given media item\n\n        @param crunchyroll.models.Media\n        @return dict"
  },
  {
    "code": "def run(self):\n        qry = os.path.abspath(self.qry)\n        ref = os.path.abspath(self.ref)\n        outfile = os.path.abspath(self.outfile)\n        tmpdir = tempfile.mkdtemp(prefix='tmp.run_nucmer.', dir=os.getcwd())\n        original_dir = os.getcwd()\n        os.chdir(tmpdir)\n        script = 'run_nucmer.sh'\n        self._write_script(script, ref, qry, outfile)\n        syscall.run('bash ' + script, verbose=self.verbose)\n        os.chdir(original_dir)\n        shutil.rmtree(tmpdir)",
    "docstring": "Change to a temp directory\n        Run bash script containing commands\n        Place results in specified output file\n        Clean up temp directory"
  },
  {
    "code": "def create_intent(self,\n                      parent,\n                      intent,\n                      language_code=None,\n                      intent_view=None,\n                      retry=google.api_core.gapic_v1.method.DEFAULT,\n                      timeout=google.api_core.gapic_v1.method.DEFAULT,\n                      metadata=None):\n        if 'create_intent' not in self._inner_api_calls:\n            self._inner_api_calls[\n                'create_intent'] = google.api_core.gapic_v1.method.wrap_method(\n                    self.transport.create_intent,\n                    default_retry=self._method_configs['CreateIntent'].retry,\n                    default_timeout=self._method_configs['CreateIntent']\n                    .timeout,\n                    client_info=self._client_info,\n                )\n        request = intent_pb2.CreateIntentRequest(\n            parent=parent,\n            intent=intent,\n            language_code=language_code,\n            intent_view=intent_view,\n        )\n        return self._inner_api_calls['create_intent'](\n            request, retry=retry, timeout=timeout, metadata=metadata)",
    "docstring": "Creates an intent in the specified agent.\n\n        Example:\n            >>> import dialogflow_v2\n            >>>\n            >>> client = dialogflow_v2.IntentsClient()\n            >>>\n            >>> parent = client.project_agent_path('[PROJECT]')\n            >>>\n            >>> # TODO: Initialize ``intent``:\n            >>> intent = {}\n            >>>\n            >>> response = client.create_intent(parent, intent)\n\n        Args:\n            parent (str): Required. The agent to create a intent for.\n                Format: ``projects/<Project ID>/agent``.\n            intent (Union[dict, ~google.cloud.dialogflow_v2.types.Intent]): Required. The intent to create.\n                If a dict is provided, it must be of the same form as the protobuf\n                message :class:`~google.cloud.dialogflow_v2.types.Intent`\n            language_code (str): Optional. The language of training phrases, parameters and rich messages\n                defined in ``intent``. If not specified, the agent's default language is\n                used. [More than a dozen\n                languages](https://dialogflow.com/docs/reference/language) are supported.\n                Note: languages must be enabled in the agent, before they can be used.\n            intent_view (~google.cloud.dialogflow_v2.types.IntentView): Optional. The resource view to apply to the returned intent.\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.dialogflow_v2.types.Intent` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def preprocess_cell(\n        self, cell: \"NotebookNode\", resources: dict, index: int\n    ) -> Tuple[\"NotebookNode\", dict]:\n        if cell.cell_type == \"markdown\":\n            variables = cell[\"metadata\"].get(\"variables\", {})\n            if len(variables) > 0:\n                cell.source = self.replace_variables(cell.source, variables)\n                if resources.get(\"delete_pymarkdown\", False):\n                    del cell.metadata[\"variables\"]\n        return cell, resources",
    "docstring": "Preprocess cell.\n\n        Parameters\n        ----------\n        cell : NotebookNode cell\n            Notebook cell being processed\n        resources : dictionary\n            Additional resources used in the conversion process. Allows\n            preprocessors to pass variables into the Jinja engine.\n        cell_index : int\n            Index of the cell being processed (see base.py)"
  },
  {
    "code": "def _main(self):\n        self.set_proctitle(self.name)\n        self.set_signal_handler()\n        logger.info(\"process for module %s is now running (pid=%d)\", self.name, os.getpid())\n        try:\n            self.main()\n        except (IOError, EOFError):\n            pass\n        except Exception as exp:\n            logger.exception('main function exception: %s', exp)\n        self.do_stop()\n        logger.info(\"process for module %s is now exiting (pid=%d)\", self.name, os.getpid())\n        exit()",
    "docstring": "module \"main\" method. Only used by external modules.\n\n        :return: None"
  },
  {
    "code": "def import_mapping(connection_id, mapping):\n    url = os.path.join(settings.HEROKU_CONNECT_API_ENDPOINT,\n                       'connections', connection_id, 'actions', 'import')\n    response = requests.post(\n        url=url,\n        json=mapping,\n        headers=_get_authorization_headers()\n    )\n    response.raise_for_status()",
    "docstring": "Import Heroku Connection mapping for given connection.\n\n    Args:\n        connection_id (str): Heroku Connection connection ID.\n        mapping (dict): Heroku Connect mapping.\n\n    Raises:\n        requests.HTTPError: If an error occurs uploading the mapping.\n        ValueError: If the mapping is not JSON serializable."
  },
  {
    "code": "def parse(\n        files,\n        config=None,\n        compilation_mode=COMPILATION_MODE.FILE_BY_FILE,\n        cache=None):\n    if not config:\n        config = xml_generator_configuration_t()\n    parser = project_reader_t(config=config, cache=cache)\n    declarations = parser.read_files(files, compilation_mode)\n    config.xml_generator_from_xml_file = parser.xml_generator_from_xml_file\n    return declarations",
    "docstring": "Parse header files.\n\n    :param files: The header files that should be parsed\n    :type files: list of str\n    :param config: Configuration object or None\n    :type config: :class:`parser.xml_generator_configuration_t`\n    :param compilation_mode: Determines whether the files are parsed\n                             individually or as one single chunk\n    :type compilation_mode: :class:`parser.COMPILATION_MODE`\n    :param cache: Declaration cache (None=no cache)\n    :type cache: :class:`parser.cache_base_t` or str\n    :rtype: list of :class:`declarations.declaration_t`"
  },
  {
    "code": "def create_organization(self, name):\n        log.warning('Creating organization...')\n        url = 'rest/servicedeskapi/organization'\n        data = {'name': name}\n        return self.post(url, headers=self.experimental_headers, data=data)",
    "docstring": "To create an organization Jira administrator global permission or agent permission is required\n        depending on the settings\n\n        :param name: str\n        :return: Organization data"
  },
  {
    "code": "def show_settings(self):\n        self.notes.config.put_values()\n        self.overview.config.put_values()\n        self.settings.config.put_values()\n        self.spectrum.config.put_values()\n        self.traces.config.put_values()\n        self.video.config.put_values()\n        self.settings.show()",
    "docstring": "Open the Setting windows, after updating the values in GUI."
  },
  {
    "code": "def decode(vol, filename, content):\n  bbox = Bbox.from_filename(filename)\n  content_len = len(content) if content is not None else 0\n  if not content:\n    if vol.fill_missing:\n      content = ''\n    else:\n      raise EmptyVolumeException(filename)\n  shape = list(bbox.size3()) + [ vol.num_channels ]\n  try:\n    return chunks.decode(\n      content, \n      encoding=vol.encoding, \n      shape=shape, \n      dtype=vol.dtype, \n      block_size=vol.compressed_segmentation_block_size,\n    )\n  except Exception as error:\n    print(red('File Read Error: {} bytes, {}, {}, errors: {}'.format(\n        content_len, bbox, filename, error)))\n    raise",
    "docstring": "Decode content according to settings in a cloudvolume instance."
  },
  {
    "code": "def select_fields(self, *fields):\n        if fields:\n            if not isinstance(fields[0], basestring): \n                fields = list(fields[0]) + list(fields)[1:]\n        for field_name in fields:\n            field_name = self._normalize_field_name(field_name)\n            self.select_field(field_name)\n        return self",
    "docstring": "set multiple fields to be selected"
  },
  {
    "code": "def clean_value(self):\n        result = []\n        for mdl in self:\n            result.append(super(ListNode, mdl).clean_value())\n        return result",
    "docstring": "Populates json serialization ready data.\n        This is the method used to serialize and store the object data in to DB\n\n        Returns:\n            List of dicts."
  },
  {
    "code": "def matches(self, *specs):\n        for spec in specs:\n            if ':' in spec:\n                app_name, endpoint_name = spec.split(':')\n            else:\n                app_name, endpoint_name = spec, None\n            for endpoint in self.endpoints:\n                if app_name == endpoint.application.name and \\\n                   endpoint_name in (endpoint.name, None):\n                    break\n            else:\n                return False\n        return True",
    "docstring": "Check if this relation matches relationship specs.\n\n        Relation specs are strings that would be given to Juju to establish a\n        relation, and should be in the form ``<application>[:<endpoint_name>]``\n        where the ``:<endpoint_name>`` suffix is optional.  If the suffix is\n        omitted, this relation will match on any endpoint as long as the given\n        application is involved.\n\n        In other words, this relation will match a spec if that spec could have\n        created this relation.\n\n        :return: True if all specs match."
  },
  {
    "code": "def encode_numeric(self):\n        with io.StringIO() as buf:\n            for triplet in self.grouper(3, self.data):\n                number = ''\n                for digit in triplet:\n                    if isinstance(digit, int):\n                        digit = chr(digit)\n                    if digit:\n                        number = ''.join([number, digit])\n                    else:\n                        break\n                if len(number) == 1:\n                    bin = self.binary_string(number, 4)\n                elif len(number) == 2:\n                    bin = self.binary_string(number, 7)\n                else:\n                    bin = self.binary_string(number, 10)\n                buf.write(bin)\n            return buf.getvalue()",
    "docstring": "This method encodes the QR code's data if its mode is\n        numeric. It returns the data encoded as a binary string."
  },
  {
    "code": "def get_chunk(self, chunk_id):\n        if chunk_id in self.idx:\n            return Cchunk(self.idx[chunk_id], self.type)\n        else:\n            return None",
    "docstring": "Returns the chunk object for the supplied identifier\n        @type chunk_id: string\n        @param chunk_id: chunk identifier"
  },
  {
    "code": "def delete_table(self, table_name):\n        data = {'TableName': table_name}\n        json_input = json.dumps(data)\n        return self.make_request('DeleteTable', json_input)",
    "docstring": "Deletes the table and all of it's data.  After this request\n        the table will be in the DELETING state until DynamoDB\n        completes the delete operation.\n\n        :type table_name: str\n        :param table_name: The name of the table to delete."
  },
  {
    "code": "def colored(text, color=None, on_color=None, attrs=None, ansi_code=None):\n    if os.getenv('ANSI_COLORS_DISABLED') is None:\n        if ansi_code is not None:\n            return \"\\033[38;5;{}m{}\\033[0m\".format(ansi_code, text)\n        fmt_str = '\\033[%dm%s'\n        if color is not None:\n            text = re.sub(COLORS_RE + '(.*?)' + RESET_RE, r'\\1', text)\n            text = fmt_str % (COLORS[color], text)\n        if on_color is not None:\n            text = re.sub(HIGHLIGHTS_RE + '(.*?)' + RESET_RE, r'\\1', text)\n            text = fmt_str % (HIGHLIGHTS[on_color], text)\n        if attrs is not None:\n            text = re.sub(ATTRIBUTES_RE + '(.*?)' + RESET_RE, r'\\1', text)\n            for attr in attrs:\n                text = fmt_str % (ATTRIBUTES[attr], text)\n        return text + RESET\n    else:\n        return text",
    "docstring": "Colorize text, while stripping nested ANSI color sequences.\n\n    Author:  Konstantin Lepa <konstantin.lepa@gmail.com> / termcolor\n\n    Available text colors:\n        red, green, yellow, blue, magenta, cyan, white.\n    Available text highlights:\n        on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.\n    Available attributes:\n        bold, dark, underline, blink, reverse, concealed.\n    Example:\n        colored('Hello, World!', 'red', 'on_grey', ['blue', 'blink'])\n        colored('Hello, World!', 'green')"
  },
  {
    "code": "def list_passwords(kwargs=None, call=None):\n    response = _query('support', 'password/list')\n    ret = {}\n    for item in response['list']:\n        if 'server' in item:\n            server = item['server']['name']\n            if server not in ret:\n                ret[server] = []\n            ret[server].append(item)\n    return ret",
    "docstring": "List all password on the account\n\n    .. versionadded:: 2015.8.0"
  },
  {
    "code": "def init_extension(self, app):\n        app.config.setdefault('CACHE_VERSION', '0')\n        app.config.setdefault('CACHE_PREFIX', 'r')\n        app.config.setdefault('CACHE_BACKEND', 'rio.exts.flask_cache.NullBackend')\n        app.config.setdefault('CACHE_BACKEND_OPTIONS', {})",
    "docstring": "Initialize cache instance."
  },
  {
    "code": "def randomEarlyShared(store, role):\n    for r in role.allRoles():\n        share = store.findFirst(Share, Share.sharedTo == r,\n                                sort=Share.storeID.ascending)\n        if share is not None:\n            return share.sharedItem\n    raise NoSuchShare(\"Why, that user hasn't shared anything at all!\")",
    "docstring": "If there are no explicitly-published public index pages to display, find a\n    shared item to present to the user as first."
  },
  {
    "code": "def TokenClient(\n    domain,\n    token,\n    user_agent=None,\n    request_encoder=default_request_encoder,\n    response_decoder=default_response_decoder,\n):\n    return AuthorizingClient(\n        domain,\n        transport.TokenAuthorization(token),\n        request_encoder,\n        response_decoder,\n        user_agent=user_agent\n    )",
    "docstring": "Creates a Freshbooks client for a freshbooks domain, using\n    token-based auth.\n    \n    The optional request_encoder and response_decoder parameters can be\n    passed the logging_request_encoder and logging_response_decoder objects\n    from this module, or custom encoders, to aid debugging or change the\n    behaviour of refreshbooks' request-to-XML-to-response mapping.\n    \n    The optional user_agent keyword parameter can be used to specify the\n    user agent string passed to FreshBooks. If unset, a default user agent\n    string is used."
  },
  {
    "code": "def _removeTags(tags, objects):\n    for t in tags:\n        for o in objects:\n            o.tags.remove(t)\n    return True",
    "docstring": "Removes tags from objects"
  },
  {
    "code": "def open_inbox_page(self, content_type):\n        from .inbox_page import InboxPage\n        with self.term.loader('Loading inbox'):\n            page = InboxPage(self.reddit, self.term, self.config, self.oauth,\n                             content_type=content_type)\n        if not self.term.loader.exception:\n            return page",
    "docstring": "Open an instance of the inbox page for the logged in user."
  },
  {
    "code": "def aggregate(self, search):\n        for f, facet in iteritems(self.facets):\n            agg = facet.get_aggregation()\n            agg_filter = MatchAll()\n            for field, filter in iteritems(self._filters):\n                if f == field:\n                    continue\n                agg_filter &= filter\n            search.aggs.bucket(\n                '_filter_' + f,\n                'filter',\n                filter=agg_filter\n            ).bucket(f, agg)",
    "docstring": "Add aggregations representing the facets selected, including potential\n        filters."
  },
  {
    "code": "def is_address_guard(self, address):\n        try:\n            mbi = self.mquery(address)\n        except WindowsError:\n            e = sys.exc_info()[1]\n            if e.winerror == win32.ERROR_INVALID_PARAMETER:\n                return False\n            raise\n        return mbi.is_guard()",
    "docstring": "Determines if an address belongs to a guard page.\n\n        @note: Returns always C{False} for kernel mode addresses.\n\n        @type  address: int\n        @param address: Memory address to query.\n\n        @rtype:  bool\n        @return: C{True} if the address belongs to a guard page.\n\n        @raise WindowsError: An exception is raised on error."
  },
  {
    "code": "def spheres_intersect(ar, aR, br, bR):\n    return vector.vector_mag_sq(ar - br) < (aR + bR) ** 2",
    "docstring": "Return whether or not two spheres intersect each other.\n\n    Parameters\n    ----------\n    ar, br: array-like, shape (n,) in n dimensions\n        Coordinates of the centres of the spheres `a` and `b`.\n    aR, bR: float\n        Radiuses of the spheres `a` and `b`.\n\n    Returns\n    -------\n    intersecting: boolean\n        True if the spheres intersect."
  },
  {
    "code": "def check_internet_on(secrets_file_path):\n    while True:\n        if internet_on() is True and not os.path.exists(secrets_file_path):\n            break\n        else:\n            print(\"Turn on your internet and unplug your USB to continue...\")\n            time.sleep(10)\n    return True",
    "docstring": "If internet on and USB unplugged, returns true. Else, continues to wait..."
  },
  {
    "code": "def load_modules(self, modules, config):\n        for pluginclass in get_plugin_classes(modules):\n            name = pluginclass.__name__\n            if name in config[\"enabledplugins\"]:\n                if issubclass(pluginclass, _ConnectionPlugin):\n                    log.debug(LOG_PLUGIN, \"Enable connection plugin %s\", name)\n                    self.connection_plugins.append(pluginclass(config[name]))\n                elif issubclass(pluginclass, _ContentPlugin):\n                    log.debug(LOG_PLUGIN, \"Enable content plugin %s\", name)\n                    self.content_plugins.append(pluginclass(config[name]))\n                elif issubclass(pluginclass, _ParserPlugin):\n                    log.debug(LOG_PLUGIN, \"Enable parser plugin %s\", name)\n                    self.parser_plugins.append(pluginclass(config[name]))\n                else:\n                    raise ValueError(\"Invalid plugin class %s\" % pluginclass)",
    "docstring": "Load plugin modules."
  },
  {
    "code": "def get_pkg_version():\n    try:\n        with open(\"PKG-INFO\", \"r\") as fp:\n            rgx = re.compile(r\"Version: (\\d+)\")\n            for line in fp.readlines():\n                match = rgx.match(line)\n                if match:\n                    return match.group(1)\n    except IOError:\n        return None",
    "docstring": "Get version string by parsing PKG-INFO."
  },
  {
    "code": "def ip_to_int(ip):\n    ret = 0\n    for octet in ip.split('.'):\n        ret = ret * 256 + int(octet)\n    return ret",
    "docstring": "Converts an IP address to an integer"
  },
  {
    "code": "def run_query_series(queries, conn):\n    results = []\n    for item in queries:\n        qry = item\n        kwargs = {}\n        if isinstance(item, tuple):\n            qry = item[0]\n            kwargs = item[1]\n        result = conn.update_query(qry, **kwargs)\n        results.append(result)\n    return results",
    "docstring": "Iterates through a list of queries and runs them through the connection\n\n    Args:\n    -----\n        queries: list of strings or tuples containing (query_string, kwargs)\n        conn: the triplestore connection to use"
  },
  {
    "code": "def changes_found(self):\n        if self.dest is None:\n            warnings.warn(\"dest directory not found!\")\n        if self.src is None:\n            warnings.warn(\"src directory not found!\")\n        if self.src is None or self.dest is None:\n            return False\n        dest_mtime = -1\n        src_mtime = os.path.getmtime(self.src)\n        if os.path.exists(self.dest):\n            dest_mtime = os.path.getmtime(self.dest)\n        if src_mtime >= dest_mtime:\n            return True\n        for folder, _, files in os.walk(self.src):\n            for filename in fnmatch.filter(files, '*.scss'):\n                src_path = os.path.join(folder, filename)\n                if os.path.getmtime(src_path) >= dest_mtime:\n                    return True \n        return False",
    "docstring": "Returns True if the target folder is older than the source folder."
  },
  {
    "code": "def _merge_colormaps(kwargs):\n    from trollimage.colormap import Colormap\n    full_cmap = None\n    palette = kwargs['palettes']\n    if isinstance(palette, Colormap):\n        full_cmap = palette\n    else:\n        for itm in palette:\n            cmap = create_colormap(itm)\n            cmap.set_range(itm[\"min_value\"], itm[\"max_value\"])\n            if full_cmap is None:\n                full_cmap = cmap\n            else:\n                full_cmap = full_cmap + cmap\n    return full_cmap",
    "docstring": "Merge colormaps listed in kwargs."
  },
  {
    "code": "def visit_const(self, node, parent):\n        return nodes.Const(\n            node.value,\n            getattr(node, \"lineno\", None),\n            getattr(node, \"col_offset\", None),\n            parent,\n        )",
    "docstring": "visit a Const node by returning a fresh instance of it"
  },
  {
    "code": "def _process_article_phene_row(self, row):\n        phenotype_id = self.id_hash['phene'].get(row['phene_id'])\n        article_id = self.id_hash['article'].get(row['article_id'])\n        omia_id = self._get_omia_id_from_phene_id(phenotype_id)\n        if self.test_mode or omia_id not in self.test_ids['disease'] \\\n                or phenotype_id is None or article_id is None:\n            return\n        self.graph.addTriple(\n            article_id,\n            self.globaltt['is_about'], phenotype_id)\n        return",
    "docstring": "Linking articles to species-specific phenes.\n\n        :param row:\n        :return:"
  },
  {
    "code": "def _extract_tls_session_ticket(ssl_session: nassl._nassl.SSL_SESSION) -> str:\n        session_string = ((ssl_session.as_text()).split('TLS session ticket:'))[1]\n        session_tls_ticket = (session_string.split('Compression:'))[0]\n        return session_tls_ticket",
    "docstring": "Extract the TLS session ticket from a SSL session object or raises IndexError if the ticket was not set."
  },
  {
    "code": "def crop_resize_image(image: np.ndarray, size) -> np.ndarray:\n    width, height = image.size\n    if width > height:\n        left = (width - height) / 2\n        right = width - left\n        top = 0\n        bottom = height\n    else:\n        top = (height - width) / 2\n        bottom = height - top\n        left = 0\n        right = width\n    image = image.crop((left, top, right, bottom))\n    image = image.resize(size, Image.ANTIALIAS)\n    return image",
    "docstring": "Resize the input image.\n\n    :param image: Original image which is a  PIL object.\n    :param size: Tuple of height and width to resize the image to.\n    :return: Resized image which is a PIL object"
  },
  {
    "code": "def attach_remote_media(self, url, username=None, password=None):\n        self.oem_init()\n        return self._oem.attach_remote_media(url, username, password)",
    "docstring": "Attach remote media by url\n\n        Given a url, attach remote media (cd/usb image) to the target system.\n\n        :param url:  URL to indicate where to find image (protocol support\n                     varies by BMC)\n        :param username: Username for endpoint to use when accessing the URL.\n                         If applicable, 'domain' would be indicated by '@' or\n                         '\\' syntax.\n        :param password: Password for endpoint to use when accessing the URL."
  },
  {
    "code": "def _cost_method(self, *args, **kwargs):\n        cost_val = self.thresh * nuclear_norm(cube2matrix(args[0]))\n        if 'verbose' in kwargs and kwargs['verbose']:\n            print(' - NUCLEAR NORM (X):', cost_val)\n        return cost_val",
    "docstring": "Calculate low-rank component of the cost\n\n        This method returns the nuclear norm error of the deconvolved data in\n        matrix form\n\n        Returns\n        -------\n        float low-rank cost component"
  },
  {
    "code": "def timex_starts(self):\n        if not self.is_tagged(TIMEXES):\n            self.tag_timexes()\n        return self.starts(TIMEXES)",
    "docstring": "The list of start positions of ``timexes`` layer elements."
  },
  {
    "code": "def invert_projection(self, X, identities):\n        distances = self.transform(X)\n        if len(distances) != len(identities):\n            raise ValueError(\"X and identities are not the same length: \"\n                             \"{0} and {1}\".format(len(X), len(identities)))\n        node_match = []\n        for d in distances.__getattribute__(self.argfunc)(0):\n            node_match.append(identities[d])\n        return np.array(node_match)",
    "docstring": "Calculate the inverted projection.\n\n        The inverted projectio of a SOM is created by association each weight\n        with the input which matches it the most, thus giving a good\n        approximation of the \"influence\" of each input item.\n\n        Works best for symbolic (instead of continuous) input data.\n\n        Parameters\n        ----------\n        X : numpy array\n            Input data\n        identities : list\n            A list of names for each of the input data. Must be the same\n            length as X.\n\n        Returns\n        -------\n        m : numpy array\n            An array with the same shape as the map"
  },
  {
    "code": "def visit_augassign(self, node, parent):\n        newnode = nodes.AugAssign(\n            self._bin_op_classes[type(node.op)] + \"=\",\n            node.lineno,\n            node.col_offset,\n            parent,\n        )\n        newnode.postinit(\n            self.visit(node.target, newnode), self.visit(node.value, newnode)\n        )\n        return newnode",
    "docstring": "visit a AugAssign node by returning a fresh instance of it"
  },
  {
    "code": "def get_dict_for_mongodb_queries(self):\n        d = {}\n        return d\n        all_structures = [task.input.structure for task in self.iflat_tasks()]\n        all_pseudos = [task.input.pseudos for task in self.iflat_tasks()]",
    "docstring": "This function returns a dictionary with the attributes that will be\n        put in the mongodb document to facilitate the query.\n        Subclasses may want to replace or extend the default behaviour."
  },
  {
    "code": "def _validate_planar_fault_geometry(self, node, _float_re):\n        valid_spacing = node[\"spacing\"]\n        for key in [\"topLeft\", \"topRight\", \"bottomLeft\", \"bottomRight\"]:\n            lon = getattr(node, key)[\"lon\"]\n            lat = getattr(node, key)[\"lat\"]\n            depth = getattr(node, key)[\"depth\"]\n            valid_lon = (lon >= -180.0) and (lon <= 180.0)\n            valid_lat = (lat >= -90.0) and (lat <= 90.0)\n            valid_depth = (depth >= 0.0)\n            is_valid = valid_lon and valid_lat and valid_depth\n            if not is_valid or not valid_spacing:\n                raise LogicTreeError(\n                    node, self.filename,\n                    \"'planarFaultGeometry' node is not valid\")",
    "docstring": "Validares a node representation of a planar fault geometry"
  },
  {
    "code": "def backward_delete_char(event):\n    \" Delete the character behind the cursor. \"\n    if event.arg < 0:\n        deleted = event.current_buffer.delete(count=-event.arg)\n    else:\n        deleted = event.current_buffer.delete_before_cursor(count=event.arg)\n    if not deleted:\n        event.cli.output.bell()",
    "docstring": "Delete the character behind the cursor."
  },
  {
    "code": "def setduration(self, **duration):\n        if len(duration) == 1:\n            arg = [x[0] for x in duration.items()]\n            if not arg[0] in self.units:\n                raise Exception('must be: %s' % str(self.units))\n            self.duration = arg\n        return self",
    "docstring": "Set the caching duration which defines how long the\n        file will be cached.\n        @param duration: The cached file duration which defines how\n            long the file will be cached.  A duration=0 means forever.\n            The duration may be: (months|weeks|days|hours|minutes|seconds).\n        @type duration: {unit:value}"
  },
  {
    "code": "def structure(cls):\n        downstream = cls.cutter.elucidate()\n        upstream = str(Seq(downstream).reverse_complement())\n        return \"\".join(\n            [\n                upstream.replace(\"^\", \")(\").replace(\"_\", \"(\"),\n                \"N*\",\n                downstream.replace(\"^\", \")(\").replace(\"_\", \")\"),\n            ]\n        )",
    "docstring": "Get the vector structure, as a DNA regex pattern.\n\n        Warning:\n            If overloading this method, the returned pattern must include 3\n            capture groups to capture the following features:\n\n            1. The downstream (3') overhang sequence\n            2. The vector placeholder sequence\n            3. The upstream (5') overhang sequence"
  },
  {
    "code": "def wait_for_save(filename, timeout=5):\n    modification_time = os.path.getmtime(filename)\n    start_time = time.time()\n    while time.time() < start_time + timeout:\n        if (os.path.getmtime(filename) > modification_time and\n            os.path.getsize(filename) > 0):\n            return True\n        time.sleep(0.2)\n    return False",
    "docstring": "Waits for FILENAME to update, waiting up to TIMEOUT seconds.\n    Returns True if a save was detected, and False otherwise."
  },
  {
    "code": "def geolocate(client, home_mobile_country_code=None,\n              home_mobile_network_code=None, radio_type=None, carrier=None,\n              consider_ip=None, cell_towers=None, wifi_access_points=None):\n    params = {}\n    if home_mobile_country_code is not None:\n        params[\"homeMobileCountryCode\"] = home_mobile_country_code\n    if home_mobile_network_code is not None:\n        params[\"homeMobileNetworkCode\"] = home_mobile_network_code\n    if radio_type is not None:\n        params[\"radioType\"] = radio_type\n    if carrier is not None:\n        params[\"carrier\"] = carrier\n    if consider_ip is not None:\n        params[\"considerIp\"] = consider_ip\n    if cell_towers is not None:\n        params[\"cellTowers\"] = cell_towers\n    if wifi_access_points is not None:\n        params[\"wifiAccessPoints\"] = wifi_access_points\n    return client._request(\"/geolocation/v1/geolocate\", {},\n                           base_url=_GEOLOCATION_BASE_URL,\n                           extract_body=_geolocation_extract,\n                           post_json=params)",
    "docstring": "The Google Maps Geolocation API returns a location and accuracy\n    radius based on information about cell towers and WiFi nodes given.\n\n    See https://developers.google.com/maps/documentation/geolocation/intro\n    for more info, including more detail for each parameter below.\n\n    :param home_mobile_country_code: The mobile country code (MCC) for\n        the device's home network.\n    :type home_mobile_country_code: string\n\n    :param home_mobile_network_code: The mobile network code (MCC) for\n        the device's home network.\n    :type home_mobile_network_code: string\n\n    :param radio_type: The mobile radio type. Supported values are\n        lte, gsm, cdma, and wcdma. While this field is optional, it\n        should be included if a value is available, for more accurate\n        results.\n    :type radio_type: string\n\n    :param carrier: The carrier name.\n    :type carrier: string\n\n    :param consider_ip: Specifies whether to fall back to IP geolocation\n        if wifi and cell tower signals are not available. Note that the\n        IP address in the request header may not be the IP of the device.\n    :type consider_ip: bool\n\n    :param cell_towers: A list of cell tower dicts. See\n        https://developers.google.com/maps/documentation/geolocation/intro#cell_tower_object\n        for more detail.\n    :type cell_towers: list of dicts\n\n    :param wifi_access_points: A list of WiFi access point dicts. See\n        https://developers.google.com/maps/documentation/geolocation/intro#wifi_access_point_object\n        for more detail.\n    :type wifi_access_points: list of dicts"
  },
  {
    "code": "def bitswap_unwant(self, key, **kwargs):\n        args = (key,)\n        return self._client.request('/bitswap/unwant', args, **kwargs)",
    "docstring": "Remove a given block from wantlist.\n\n        Parameters\n        ----------\n        key : str\n            Key to remove from wantlist."
  },
  {
    "code": "def accepts_kwarg(func, kwarg):\n    signature = inspect.signature(func)\n    try:\n        signature.bind_partial(**{kwarg: None})\n        return True\n    except TypeError:\n        return False",
    "docstring": "Determine whether the callable `func` has a signature that accepts the\n    keyword argument `kwarg`"
  },
  {
    "code": "def delete(stack_ref: List[str],\n           region: str, dry_run: bool, force: bool, remote: str):\n    lizzy = setup_lizzy_client(remote)\n    stack_refs = get_stack_refs(stack_ref)\n    all_with_version = all(stack.version is not None\n                           for stack in stack_refs)\n    if (not all_with_version and not dry_run and not force):\n        fatal_error(\n            'Error: {} matching stacks found. '.format(len(stack_refs)) +\n            'Please use the \"--force\" flag if you really want to delete multiple stacks.')\n    output = ''\n    for stack in stack_refs:\n        if stack.version is not None:\n            stack_id = '{stack.name}-{stack.version}'.format(stack=stack)\n        else:\n            stack_id = stack.name\n        with Action(\"Requesting stack '{stack_id}' deletion..\",\n                    stack_id=stack_id):\n            output = lizzy.delete(stack_id, region=region, dry_run=dry_run)\n    print(output)",
    "docstring": "Delete Cloud Formation stacks"
  },
  {
    "code": "def rectify_pgroups(self):\n        pdata_groups = list(self.parameter_data.loc[:,\"pargp\"].\\\n            value_counts().keys())\n        need_groups = []\n        existing_groups = list(self.parameter_groups.pargpnme)\n        for pg in pdata_groups:\n            if pg not in existing_groups:\n                need_groups.append(pg)\n        if len(need_groups) > 0:\n            defaults = copy.copy(pst_utils.pst_config[\"pargp_defaults\"])\n            for grp in need_groups:\n                defaults[\"pargpnme\"] = grp\n                self.parameter_groups = \\\n                    self.parameter_groups.append(defaults,ignore_index=True)\n        for gp in self.parameter_groups.loc[:,\"pargpnme\"]:\n            if gp in pdata_groups and gp not in need_groups:\n                need_groups.append(gp)\n        self.parameter_groups.index = self.parameter_groups.pargpnme\n        self.parameter_groups = self.parameter_groups.loc[need_groups,:]",
    "docstring": "private method to synchronize parameter groups section with\n        the parameter data section"
  },
  {
    "code": "def pathFromHere_explore(self, astr_startPath = '/'):\n            self.l_lwd  = []\n            self.treeExplore(startPath = astr_startPath, f=self.lwd)\n            return self.l_lwd",
    "docstring": "Return a list of paths from \"here\" in the stree, using the\n            child explore access.\n\n            :param astr_startPath: path from which to start\n            :return: a list of paths from \"here\""
  },
  {
    "code": "def installSite(self):\n        for iface, priority in self.__getPowerupInterfaces__([]):\n            self.store.powerUp(self, iface, priority)",
    "docstring": "Not using the dependency system for this class because it's only\n        installed via the command line, and multiple instances can be\n        installed."
  },
  {
    "code": "def Load(cls, file_input, client=None):\n    if client is None:\n      client = AdWordsClient.LoadFromStorage()\n    try:\n      data = yaml.safe_load(file_input)\n    except yaml.YAMLError as e:\n      raise googleads.errors.GoogleAdsError(\n          'Error loading IncrementalUploadHelper from file: %s' % str(e))\n    try:\n      request_builder = BatchJobHelper.GetRequestBuilder(\n          client, version=data['version'], server=data['server']\n      )\n      return cls(request_builder, data['upload_url'],\n                 current_content_length=data['current_content_length'],\n                 is_last=data['is_last'])\n    except KeyError as e:\n      raise googleads.errors.GoogleAdsValueError(\n          'Can\\'t parse IncrementalUploadHelper from file. Required field '\n          '\"%s\" is missing.' % e.message)",
    "docstring": "Loads an IncrementalUploadHelper from the given file-like object.\n\n    Args:\n      file_input: a file-like object containing a serialized\n        IncrementalUploadHelper.\n      client: an AdWordsClient instance. If not specified, an AdWordsClient will\n        be instantiated using the default configuration file.\n\n    Returns:\n      An IncrementalUploadHelper instance initialized using the contents of the\n      serialized input file.\n\n    Raises:\n      GoogleAdsError: If there is an error reading the input file containing the\n        serialized IncrementalUploadHelper.\n      GoogleAdsValueError: If the contents of the input file can't be parsed to\n        produce an IncrementalUploadHelper."
  },
  {
    "code": "def prune_by_work_count(self, minimum=None, maximum=None, label=None):\n        self._logger.info('Pruning results by work count')\n        count_fieldname = 'tmp_count'\n        matches = self._matches\n        if label is not None:\n            matches = matches[matches[constants.LABEL_FIELDNAME] == label]\n        filtered = matches[matches[constants.COUNT_FIELDNAME] > 0]\n        grouped = filtered.groupby(constants.NGRAM_FIELDNAME, sort=False)\n        counts = pd.DataFrame(grouped[constants.WORK_FIELDNAME].nunique())\n        counts.rename(columns={constants.WORK_FIELDNAME: count_fieldname},\n                      inplace=True)\n        if minimum:\n            counts = counts[counts[count_fieldname] >= minimum]\n        if maximum:\n            counts = counts[counts[count_fieldname] <= maximum]\n        self._matches = pd.merge(self._matches, counts,\n                                 left_on=constants.NGRAM_FIELDNAME,\n                                 right_index=True)\n        del self._matches[count_fieldname]",
    "docstring": "Removes results rows for n-grams that are not attested in a\n        number of works in the range specified by `minimum` and\n        `maximum`.\n\n        Work here encompasses all witnesses, so that the same n-gram\n        appearing in multiple witnesses of the same work are counted\n        as a single work.\n\n        If `label` is specified, the works counted are restricted to\n        those associated with `label`.\n\n        :param minimum: minimum number of works\n        :type minimum: `int`\n        :param maximum: maximum number of works\n        :type maximum: `int`\n        :param label: optional label to restrict requirement to\n        :type label: `str`"
  },
  {
    "code": "def fetch(self, from_time, until_time=None):\n        until_time = until_time or datetime.now()\n        time_info, values = whisper.fetch(self.path,\n                                          from_time.strftime('%s'),\n                                          until_time.strftime('%s'))\n        start_time, end_time, step = time_info\n        current = start_time\n        times = []\n        while current <= end_time:\n            times.append(current)\n            current += step\n        return zip(times, values)",
    "docstring": "This method fetch data from the database according to the period\n        given\n\n        fetch(path, fromTime, untilTime=None)\n\n        fromTime is an datetime\n        untilTime is also an datetime, but defaults to now.\n\n        Returns a tuple of (timeInfo, valueList)\n        where timeInfo is itself a tuple of (fromTime, untilTime, step)\n\n        Returns None if no data can be returned"
  },
  {
    "code": "def _preprocess_input(self, input):\n        if not re.search(preprocess_chars, input):\n            return input\n        input = self._add_punctuation_spacing(input)\n        return input",
    "docstring": "Preprocesses the input before it's split into a list."
  },
  {
    "code": "def peek(self, lpBaseAddress, nSize):\n        data = ''\n        if nSize > 0:\n            try:\n                hProcess = self.get_handle( win32.PROCESS_VM_READ |\n                                            win32.PROCESS_QUERY_INFORMATION )\n                for mbi in self.get_memory_map(lpBaseAddress,\n                                               lpBaseAddress + nSize):\n                    if not mbi.is_readable():\n                        nSize = mbi.BaseAddress - lpBaseAddress\n                        break\n                if nSize > 0:\n                    data = win32.ReadProcessMemory(\n                                    hProcess, lpBaseAddress, nSize)\n            except WindowsError:\n                e = sys.exc_info()[1]\n                msg = \"Error reading process %d address %s: %s\"\n                msg %= (self.get_pid(),\n                        HexDump.address(lpBaseAddress),\n                        e.strerror)\n                warnings.warn(msg)\n        return data",
    "docstring": "Reads the memory of the process.\n\n        @see: L{read}\n\n        @type  lpBaseAddress: int\n        @param lpBaseAddress: Memory address to begin reading.\n\n        @type  nSize: int\n        @param nSize: Number of bytes to read.\n\n        @rtype:  str\n        @return: Bytes read from the process memory.\n            Returns an empty string on error."
  },
  {
    "code": "def from_netcdf(filename):\n        groups = {}\n        with nc.Dataset(filename, mode=\"r\") as data:\n            data_groups = list(data.groups)\n        for group in data_groups:\n            with xr.open_dataset(filename, group=group) as data:\n                groups[group] = data\n        return InferenceData(**groups)",
    "docstring": "Initialize object from a netcdf file.\n\n        Expects that the file will have groups, each of which can be loaded by xarray.\n\n        Parameters\n        ----------\n        filename : str\n            location of netcdf file\n\n        Returns\n        -------\n        InferenceData object"
  },
  {
    "code": "def _recursive_overwrite(self, src, dest):\n        if os.path.isdir(src):\n            if not os.path.isdir(dest):\n                os.makedirs(dest)\n            files = os.listdir(src)\n            for f in files:\n                self._recursive_overwrite(os.path.join(src, f),\n                                          os.path.join(dest, f))\n        else:\n            shutil.copyfile(src, dest, follow_symlinks=False)",
    "docstring": "Copy src to dest, recursively and with file overwrite."
  },
  {
    "code": "def vault_relation_complete(backend=None):\n    vault_kv = VaultKVContext(secret_backend=backend or VAULTLOCKER_BACKEND)\n    vault_kv()\n    return vault_kv.complete",
    "docstring": "Determine whether vault relation is complete\n\n    :param backend: Name of secrets backend requested\n    :ptype backend: string\n    :returns: whether the relation to vault is complete\n    :rtype: bool"
  },
  {
    "code": "def help(self, command=None):\n    from spython.utils import check_install\n    check_install()\n    cmd = ['singularity','--help']\n    if command != None:\n        cmd.append(command)\n    help = self._run_command(cmd)\n    return help",
    "docstring": "help prints the general function help, or help for a specific command\n\n        Parameters\n        ==========   \n        command: the command to get help for, if none, prints general help"
  },
  {
    "code": "def _unbind(cls, boundname):\n        try:\n            fs = CPE2_3_FS(boundname)\n        except:\n            try:\n                uri = CPE2_3_URI(boundname)\n            except:\n                return CPE2_3_WFN(boundname)\n            else:\n                return CPE2_3_WFN(uri.as_wfn())\n        else:\n            return CPE2_3_WFN(fs.as_wfn())",
    "docstring": "Unbinds a bound form to a WFN.\n\n        :param string boundname: CPE name\n        :returns: WFN object associated with boundname.\n        :rtype: CPE2_3_WFN"
  },
  {
    "code": "def get_command(self, name):\n        def command(options):\n            client = ZookeeperClient(\n                \"%s:%d\" % (options.pop('host'), options.pop('port')),\n                session_timeout=1000\n                )\n            path = options.pop('path_prefix')\n            force = options.pop('force')\n            extra = options.pop('extra')\n            options.update(extra)\n            controller = Command(client, path, self.services, force)\n            method = getattr(controller, \"cmd_%s\" % name)\n            return method(**options)\n        return command",
    "docstring": "Wrap command class in constructor."
  },
  {
    "code": "def copy_non_reserved(props, target):\n    target.update(\n        {\n            key: value\n            for key, value in props.items()\n            if not is_reserved_property(key)\n        }\n    )\n    return target",
    "docstring": "Copies all properties with non-reserved names from ``props`` to ``target``\n\n    :param props: A dictionary of properties\n    :param target: Another dictionary\n    :return: The target dictionary"
  },
  {
    "code": "def _wrap_client(self, region_name, method, *args, **kwargs):\n        try:\n            return method(*args, **kwargs)\n        except botocore.exceptions.BotoCoreError:\n            self._regional_clients.pop(region_name)\n            _LOGGER.error(\n                'Removing regional client \"%s\" from cache due to BotoCoreError on %s call', region_name, method.__name__\n            )\n            raise",
    "docstring": "Proxies all calls to a kms clients methods and removes misbehaving clients\n\n        :param str region_name: AWS Region ID (ex: us-east-1)\n        :param callable method: a method on the KMS client to proxy\n        :param tuple args: list of arguments to pass to the provided ``method``\n        :param dict kwargs: dictonary of keyword arguments to pass to the provided ``method``"
  },
  {
    "code": "def get_available_types_for_scene(self, element):\n        available = []\n        for typ, inter in self.types.items():\n            if inter(self).is_available_for_scene(element):\n                available.append(typ)\n        return available",
    "docstring": "Return a list of types that can be used in combination with the given element\n        to add new reftracks to the scene.\n\n        This allows for example the user, to add new reftracks (aliens) to the scene.\n        So e.g. for a shader, it wouldn't make sense to make it available to be added to the scene, because\n        one would use them only as children of let's say an asset or cache.\n        Some types might only be available for shots or assets etc.\n\n        :param element: the element that could be used in conjuction with the returned types to create new reftracks.\n        :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot`\n        :returns: a list of types\n        :rtype: :class:`list`\n        :raises: None"
  },
  {
    "code": "def cublasCher2k(handle, uplo, trans, n, k, alpha, A, lda, B, ldb, beta, C, ldc):\n    status = _libcublas.cublasCher2k_v2(handle, \n                                        _CUBLAS_FILL_MODE[uplo], \n                                        _CUBLAS_OP[trans], \n                                        n, k, ctypes.byref(cuda.cuFloatComplex(alpha.real,                 \n                                                                               alpha.imag)),\n                                        int(A), lda, int(B), ldb, \n                                        ctypes.byref(cuda.cuFloatComplex(beta.real,\n                                                                         beta.imag)),\n                                        int(C), ldc)\n    cublasCheckStatus(status)",
    "docstring": "Rank-2k operation on Hermitian matrix."
  },
  {
    "code": "def _getArrays(items, attr, defaultValue):\n    arrays = dict([(key, []) for key in attr])\n    for item in items:\n        for key in attr:\n            arrays[key].append(getattr(item, key, defaultValue))\n    for key in [_ for _ in viewkeys(arrays)]:\n        arrays[key] = numpy.array(arrays[key])\n    return arrays",
    "docstring": "Return arrays with equal size of item attributes from a list of sorted\n    \"items\" for fast and convenient data processing.\n\n    :param attr: list of item attributes that should be added to the returned\n        array.\n    :param defaultValue: if an item is missing an attribute, the \"defaultValue\"\n        is added to the array instead.\n\n    :returns: {'attribute1': numpy.array([attributeValue1, ...]), ...}"
  },
  {
    "code": "def list_vms(access_token, subscription_id, resource_group):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/resourceGroups/', resource_group,\n                        '/providers/Microsoft.Compute/virtualMachines',\n                        '?api-version=', COMP_API])\n    return do_get(endpoint, access_token)",
    "docstring": "List VMs in a resource group.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n        resource_group (str): Azure resource group name.\n\n    Returns:\n        HTTP response. JSON body of a list of VM model views."
  },
  {
    "code": "def _login(self):\n        self.logger.debug(\"Logging into \" + \"{}/{}\".format(self._im_api_url, \"j_spring_security_check\"))\n        self._im_session.headers.update({'Content-Type':'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36'})\n        self.j_username = self._username\n        self.j_password = self._password\n        requests.packages.urllib3.disable_warnings()\n        payload = {'j_username': self.j_username, 'j_password': self.j_password, 'submit':'Login'}\n        r = self._im_session.post(\n            \"{}/{}\".format(self._im_api_url,\"j_spring_security_check\"),\n            verify=self._im_verify_ssl,\n            data=payload)\n        self.logger.debug(\"Login POST response: \" + \"{}\".format(r.text))\n        self._im_logged_in = True",
    "docstring": "LOGIN CAN ONLY BE DONE BY POSTING TO A HTTP FORM.\n        A COOKIE IS THEN USED FOR INTERACTING WITH THE API"
  },
  {
    "code": "def _to_string(self, fmt, locale=None):\n        if fmt not in self._FORMATS:\n            raise ValueError(\"Format [{}] is not supported\".format(fmt))\n        fmt = self._FORMATS[fmt]\n        if callable(fmt):\n            return fmt(self)\n        return self.format(fmt, locale=locale)",
    "docstring": "Format the instance to a common string format.\n\n        :param fmt: The name of the string format\n        :type fmt: string\n\n        :param locale: The locale to use\n        :type locale: str or None\n\n        :rtype: str"
  },
  {
    "code": "def linkify_s_by_hst(self, hosts):\n        for serv in self:\n            if not hasattr(serv, 'host_name'):\n                serv.host = None\n                continue\n            try:\n                hst_name = serv.host_name\n                hst = hosts.find_by_name(hst_name)\n                if hst is not None:\n                    serv.host = hst.uuid\n                    hst.add_service_link(serv.uuid)\n                else:\n                    err = \"Warning: the service '%s' got an invalid host_name '%s'\" % \\\n                          (serv.get_name(), hst_name)\n                    serv.configuration_warnings.append(err)\n                    continue\n            except AttributeError:\n                pass",
    "docstring": "Link services with their parent host\n\n        :param hosts: Hosts to look for simple host\n        :type hosts: alignak.objects.host.Hosts\n        :return: None"
  },
  {
    "code": "def sendMessage(self,chat_id,text,parse_mode=None,disable_web=None,reply_msg_id=None,markup=None):\n\t\tpayload={'chat_id' : chat_id, 'text' : text, 'parse_mode': parse_mode , 'disable_web_page_preview' : disable_web , 'reply_to_message_id' : reply_msg_id}\n\t\tif(markup):\n\t\t\tpayload['reply_markup']=json.dumps(markup)\n\t\tresponse_str = self._command('sendMessage',payload,method='post')\n\t\treturn _validate_response_msg(response_str)",
    "docstring": "On failure returns False\n\t\tOn success returns Message Object"
  },
  {
    "code": "def process_cpp(self, path, suffix):\n        _cpplint_state.ResetErrorCounts()\n        cpplint.ProcessFile(str(path), _cpplint_state.verbose_level)\n        _cpplint_state.PrintErrorCounts()\n        errors = _cpplint_state.errors_by_category.copy()\n        if suffix == 'h':\n            self.cpp_header_map[str(path)] = errors\n        else:\n            self.cpp_src_map[str(path)] = errors",
    "docstring": "Process a cpp file."
  },
  {
    "code": "def delayed_unpacking(self, container, fun, *args, **kwargs):\n        try:\n            self._delayed += 1\n            blob = self._begin()\n            try:\n                fun(*args, **kwargs)\n                self._commit(blob)\n                return container\n            except DelayPacking:\n                self._rollback(blob)\n                continuation = (fun, args, kwargs)\n                self._pending.append(continuation)\n                return container\n        finally:\n            self._delayed -= 1",
    "docstring": "Should be used when unpacking mutable values.\n        This allows circular references resolution by pausing serialization."
  },
  {
    "code": "def get_way(self, way_id, resolve_missing=False):\n        ways = self.get_ways(way_id=way_id)\n        if len(ways) == 0:\n            if resolve_missing is False:\n                raise exception.DataIncomplete(\"Resolve missing way is disabled\")\n            query = (\"\\n\"\n                     \"[out:json];\\n\"\n                     \"way({way_id});\\n\"\n                     \"out body;\\n\"\n                     )\n            query = query.format(\n                way_id=way_id\n            )\n            tmp_result = self.api.query(query)\n            self.expand(tmp_result)\n            ways = self.get_ways(way_id=way_id)\n        if len(ways) == 0:\n            raise exception.DataIncomplete(\"Unable to resolve requested way\")\n        return ways[0]",
    "docstring": "Get a way by its ID.\n\n        :param way_id: The way ID\n        :type way_id: Integer\n        :param resolve_missing: Query the Overpass API if the way is missing in the result set.\n        :return: The way\n        :rtype: overpy.Way\n        :raises overpy.exception.DataIncomplete: The requested way is not available in the result cache.\n        :raises overpy.exception.DataIncomplete: If resolve_missing is True and the way can't be resolved."
  },
  {
    "code": "def _check_types(self) -> None:\n        all_instance_fields_and_types: List[Dict[str, str]] = [{k: v.__class__.__name__\n                                                                for k, v in x.fields.items()}\n                                                               for x in self.instances]\n        if not all([all_instance_fields_and_types[0] == x for x in all_instance_fields_and_types]):\n            raise ConfigurationError(\"You cannot construct a Batch with non-homogeneous Instances.\")",
    "docstring": "Check that all the instances have the same types."
  },
  {
    "code": "def usergroup_exists(name=None, node=None, nodeids=None, **kwargs):\n    conn_args = _login(**kwargs)\n    zabbix_version = apiinfo_version(**kwargs)\n    ret = {}\n    try:\n        if conn_args:\n            if _LooseVersion(zabbix_version) > _LooseVersion(\"2.5\"):\n                if not name:\n                    name = ''\n                ret = usergroup_get(name, None, **kwargs)\n                return bool(ret)\n            else:\n                method = 'usergroup.exists'\n                params = {}\n                if not name and not node and not nodeids:\n                    return {'result': False, 'comment': 'Please submit name, node or nodeids parameter to check if '\n                                                        'at least one user group exists.'}\n                if name:\n                    params['name'] = name\n                if _LooseVersion(zabbix_version) < _LooseVersion(\"2.4\"):\n                    if node:\n                        params['node'] = node\n                    if nodeids:\n                        params['nodeids'] = nodeids\n                ret = _query(method, params, conn_args['url'], conn_args['auth'])\n                return ret['result']\n        else:\n            raise KeyError\n    except KeyError:\n        return ret",
    "docstring": "Checks if at least one user group that matches the given filter criteria exists\n\n    .. versionadded:: 2016.3.0\n\n    :param name: names of the user groups\n    :param node: name of the node the user groups must belong to (This will override the nodeids parameter.)\n    :param nodeids: IDs of the nodes the user groups must belong to\n\n    :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n    :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n    :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n    :return: True if at least one user group that matches the given filter criteria exists, else False.\n\n    CLI Example:\n    .. code-block:: bash\n\n        salt '*' zabbix.usergroup_exists Guests"
  },
  {
    "code": "def dump(\n        self, stream, progress=None, lower=None, upper=None,\n        incremental=False, deltas=False\n    ):\n        cmd = [SVNADMIN, 'dump', '.']\n        if progress is None:\n            cmd.append('-q')\n        if lower is not None:\n            cmd.append('-r')\n            if upper is None:\n                cmd.append(str(int(lower)))\n            else:\n                cmd.append('%d:%d' % (int(lower), int(upper)))\n        if incremental:\n            cmd.append('--incremental')\n        if deltas:\n            cmd.append('--deltas')\n        p = subprocess.Popen(cmd, cwd=self.path, stdout=stream, stderr=progress)\n        p.wait()\n        if p.returncode != 0:\n            raise subprocess.CalledProcessError(p.returncode, cmd)",
    "docstring": "Dump the repository to a dumpfile stream.\n\n        :param stream: A file stream to which the dumpfile is written\n        :param progress: A file stream to which progress is written\n        :param lower: Must be a numeric version number\n        :param upper: Must be a numeric version number\n\n        See ``svnadmin help dump`` for details on the other arguments."
  },
  {
    "code": "def lower_unsupported_metafield_expressions(ir_blocks):\n    def visitor_fn(expression):\n        if not isinstance(expression, expressions.LocalField):\n            return expression\n        if expression.field_name not in constants.UNSUPPORTED_META_FIELDS:\n            return expression\n        raise NotImplementedError(\n            u'Encountered unsupported metafield {} in LocalField {} during construction of '\n            u'SQL query tree for IR blocks {}.'.format(\n                constants.UNSUPPORTED_META_FIELDS[expression.field_name], expression, ir_blocks))\n    new_ir_blocks = [\n        block.visit_and_update_expressions(visitor_fn)\n        for block in ir_blocks\n    ]\n    return new_ir_blocks",
    "docstring": "Raise exception if an unsupported metafield is encountered in any LocalField expression."
  },
  {
    "code": "def aggregate(self, index):\n        if isinstance(index, string_types):\n            col_df_grouped = self.col_df.groupby(self.df[index])\n        else:\n            self.col_df.index = pd.MultiIndex.from_arrays([self.df[i] for i in index])\n            col_df_grouped = self.col_df.groupby(level=index)\n            self.col_df.index = self.df.index\n        self.reduced_df = pd.DataFrame({\n            colred: col_df_grouped[colred.column].agg(colred.agg_func)\n            for colred in self.column_reductions\n            })\n        reduced_dfs = []\n        for cf in self.column_functions:\n            reduced_dfs.append(cf.apply_and_name(self))\n        return pd.concat(reduced_dfs, axis=1)",
    "docstring": "Performs a groupby of the unique Columns by index, as constructed from self.df.\n\n        Args:\n            index (str, or pd.Index): Index or column name of self.df.\n\n        Returns:\n            pd.DataFrame: A dataframe, aggregated by index, that contains the result\n                of the various ColumnFunctions, and named accordingly."
  },
  {
    "code": "def define_objective_with_I(I, *args):\n    objective = I[0][0]\n    if len(args) > 2 or len(args) == 0:\n        raise Exception(\"Wrong number of arguments!\")\n    elif len(args) == 1:\n        A = args[0].parties[0]\n        B = args[0].parties[1]\n    else:\n        A = args[0]\n        B = args[1]\n    i, j = 0, 1\n    for m_Bj in B:\n        for Bj in m_Bj:\n            objective += I[i][j] * Bj\n            j += 1\n    i += 1\n    for m_Ai in A:\n        for Ai in m_Ai:\n            objective += I[i][0] * Ai\n            j = 1\n            for m_Bj in B:\n                for Bj in m_Bj:\n                    objective += I[i][j] * Ai * Bj\n                    j += 1\n            i += 1\n    return -objective",
    "docstring": "Define a polynomial using measurements and an I matrix describing a Bell\n    inequality.\n\n    :param I: The I matrix of a Bell inequality in the Collins-Gisin notation.\n    :type I: list of list of int.\n    :param args: Either the measurements of Alice and Bob or a `Probability`\n                 class describing their measurement operators.\n    :type A: tuple of list of list of\n             :class:`sympy.physics.quantum.operator.HermitianOperator` or\n             :class:`ncpol2sdpa.Probability`\n\n    :returns: :class:`sympy.core.expr.Expr` -- the objective function to be\n              solved as a minimization problem to find the maximum quantum\n              violation. Note that the sign is flipped compared to the Bell\n              inequality."
  },
  {
    "code": "def get_assessments_offered_by_banks(self, bank_ids):\n        assessment_offered_list = []\n        for bank_id in bank_ids:\n            assessment_offered_list += list(\n                self.get_assessments_offered_by_bank(bank_id))\n        return objects.AssessmentOfferedList(assessment_offered_list)",
    "docstring": "Gets the list of ``AssessmentOffered`` objects corresponding to a list of ``Banks``.\n\n        arg:    bank_ids (osid.id.IdList): list of bank ``Ids``\n        return: (osid.assessment.AssessmentOfferedList) - list of\n                assessments offered\n        raise:  NullArgument - ``bank_ids`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _add_genotypes(self, variant_obj, gemini_variant, case_id,\n                       individual_objs):\n        for ind in individual_objs:\n            index = ind.ind_index\n            variant_obj.add_individual(Genotype(\n                sample_id=ind.ind_id,\n                genotype=gemini_variant['gts'][index],\n                case_id=case_id,\n                phenotype=ind.phenotype,\n                ref_depth=gemini_variant['gt_ref_depths'][index],\n                alt_depth=gemini_variant['gt_alt_depths'][index],\n                depth=gemini_variant['gt_depths'][index],\n                genotype_quality=gemini_variant['gt_quals'][index]\n            ))",
    "docstring": "Add the genotypes for a variant for all individuals\n\n                Args:\n                    variant_obj (puzzle.models.Variant)\n                    gemini_variant (GeminiQueryRow): The gemini variant\n                    case_id (str): related case id\n                    individual_objs (list(dict)): A list of Individuals"
  },
  {
    "code": "def at_css(self, css, timeout = DEFAULT_AT_TIMEOUT, **kw):\n    return self.wait_for_safe(lambda: super(WaitMixin, self).at_css(css),\n                              timeout = timeout,\n                              **kw)",
    "docstring": "Returns the first node matching the given CSSv3 expression or ``None``\n    if a timeout occurs."
  },
  {
    "code": "def extract_relations(dgtree, relations=None):\n    if hasattr(dgtree, 'reltypes'):\n        return dgtree.reltypes\n    if relations is None:\n        relations = {}\n    if is_leaf(dgtree):\n        return relations\n    root_label = dgtree.label()\n    if root_label == '':\n        assert dgtree == DGParentedTree('', []), \\\n            \"The tree has no root label, but isn't empty: {}\".format(dgtree)\n        return relations\n    elif root_label in NUCLEARITY_LABELS:\n        for child in dgtree:\n            relations.update(extract_relations(child, relations))\n    else:\n        child_labels = [child.label() for child in dgtree]\n        assert all(label in NUCLEARITY_LABELS for label in child_labels)\n        if 'S' in child_labels:\n            relations[root_label] = 'rst'\n        else:\n            relations[root_label] = 'multinuc'\n        for child in dgtree:\n            relations.update(extract_relations(child, relations))\n    return relations",
    "docstring": "Extracts relations from a DGParentedTree.\n\n    Given a DGParentedTree, returns a (relation name, relation type) dict\n    of all the RST relations occurring in that tree."
  },
  {
    "code": "def deserialize(serialized_material_description):\n    try:\n        _raw_material_description = serialized_material_description[Tag.BINARY.dynamodb_tag]\n        material_description_bytes = io.BytesIO(_raw_material_description)\n        total_bytes = len(_raw_material_description)\n    except (TypeError, KeyError):\n        message = \"Invalid material description\"\n        _LOGGER.exception(message)\n        raise InvalidMaterialDescriptionError(message)\n    _read_version(material_description_bytes)\n    material_description = {}\n    try:\n        while material_description_bytes.tell() < total_bytes:\n            name = to_str(decode_value(material_description_bytes))\n            value = to_str(decode_value(material_description_bytes))\n            material_description[name] = value\n    except struct.error:\n        message = \"Invalid material description\"\n        _LOGGER.exception(message)\n        raise InvalidMaterialDescriptionError(message)\n    return material_description",
    "docstring": "Deserialize a serialized material description attribute into a material description dictionary.\n\n    :param dict serialized_material_description: DynamoDB attribute value containing serialized material description.\n    :returns: Material description dictionary\n    :rtype: dict\n    :raises InvalidMaterialDescriptionError: if malformed version\n    :raises InvalidMaterialDescriptionVersionError: if unknown version is found"
  },
  {
    "code": "def generate_ctrlptsw2d_file(file_in='', file_out='ctrlptsw.txt'):\n    ctrlpts2d, size_u, size_v = _read_ctrltps2d_file(file_in)\n    new_ctrlpts2d = generate_ctrlptsw2d(ctrlpts2d)\n    _save_ctrlpts2d_file(new_ctrlpts2d, size_u, size_v, file_out)",
    "docstring": "Generates weighted control points from unweighted ones in 2-D.\n\n    This function\n\n    #. Takes in a 2-D control points file whose coordinates are organized in (x, y, z, w) format\n    #. Converts into (x*w, y*w, z*w, w) format\n    #. Saves the result to a file\n\n    Therefore, the resultant file could be a direct input of the NURBS.Surface class.\n\n    :param file_in: name of the input file (to be read)\n    :type file_in: str\n    :param file_out: name of the output file (to be saved)\n    :type file_out: str\n    :raises IOError: an error occurred reading or writing the file"
  },
  {
    "code": "def alpha_blend(self, other):\n    fa = self.__a + other.__a - (self.__a * other.__a)\n    if fa==0: sa = 0\n    else: sa = min(1.0, self.__a/other.__a)\n    da = 1.0 - sa\n    sr, sg, sb = [v * sa for v in self.__rgb]\n    dr, dg, db = [v * da for v in other.__rgb]\n    return Color((sr+dr, sg+dg, sb+db), 'rgb', fa, self.__wref)",
    "docstring": "Alpha-blend this color on the other one.\n\n    Args:\n      :other:\n        The grapefruit.Color to alpha-blend with this one.\n\n    Returns:\n      A grapefruit.Color instance which is the result of alpha-blending\n      this color on the other one.\n\n    >>> c1 = Color.from_rgb(1, 0.5, 0, 0.2)\n    >>> c2 = Color.from_rgb(1, 1, 1, 0.8)\n    >>> c3 = c1.alpha_blend(c2)\n    >>> c3\n    Color(1.0, 0.875, 0.75, 0.84)"
  },
  {
    "code": "def vinet_v_single(p, v0, k0, k0p, min_strain=0.01):\n    if p <= 1.e-5:\n        return v0\n    def f_diff(v, v0, k0, k0p, p):\n        return vinet_p(v, v0, k0, k0p) - p\n    v = brenth(f_diff, v0, v0 * min_strain, args=(v0, k0, k0p, p))\n    return v",
    "docstring": "find volume at given pressure using brenth in scipy.optimize\n    this is for single p value, not vectorized\n\n    :param p: pressure in GPa\n    :param v0: unit-cell volume in A^3 at 1 bar\n    :param k0: bulk modulus at reference conditions\n    :param k0p: pressure derivative of bulk modulus at reference conditions\n    :param min_strain: defining minimum v/v0 value to search volume for\n    :return: unit cell volume at high pressure in A^3"
  },
  {
    "code": "def authenticate(self):\n        if self.__token:\n            try:\n                resp = self._refresh_token()\n            except exceptions.TVDBRequestException as err:\n                if getattr(err.response, 'status_code', 0) == 401:\n                    resp = self._login()\n                else:\n                    raise\n        else:\n            resp = self._login()\n        self.__token = resp.get('token')\n        self._token_timer = timeutil.utcnow()",
    "docstring": "Aquire authorization token for using thetvdb apis."
  },
  {
    "code": "def _disambiguate_star_fusion_junctions(star_junction_file, contamination_bam, disambig_out_file, data):\n    out_file = disambig_out_file\n    fusiondict = {}\n    with open(star_junction_file, \"r\") as in_handle:\n        for my_line in in_handle:\n            my_line_split = my_line.strip().split(\"\\t\")\n            if len(my_line_split) < 10:\n                continue\n            fusiondict[my_line_split[9]] = my_line.strip(\"\\n\")\n    with pysam.Samfile(contamination_bam, \"rb\") as samfile:\n        for my_read in samfile:\n            if my_read.is_unmapped or my_read.is_secondary:\n                continue\n            if my_read.qname in fusiondict:\n                fusiondict.pop(my_read.qname)\n    with file_transaction(data, out_file) as tx_out_file:\n        with open(tx_out_file, 'w') as myhandle:\n            for my_key in fusiondict:\n                print(fusiondict[my_key], file=myhandle)\n    return out_file",
    "docstring": "Disambiguate detected fusions based on alignments to another species."
  },
  {
    "code": "def service(\n    state, host,\n    *args, **kwargs\n):\n    if host.fact.which('systemctl'):\n        yield systemd(state, host, *args, **kwargs)\n        return\n    if host.fact.which('initctl'):\n        yield upstart(state, host, *args, **kwargs)\n        return\n    if host.fact.directory('/etc/init.d'):\n        yield d(state, host, *args, **kwargs)\n        return\n    if host.fact.directory('/etc/rc.d'):\n        yield rc(state, host, *args, **kwargs)\n        return\n    raise OperationError((\n        'No init system found '\n        '(no systemctl, initctl, /etc/init.d or /etc/rc.d found)'\n    ))",
    "docstring": "Manage the state of services. This command checks for the presence of all the\n    init systems pyinfra can handle and executes the relevant operation. See init\n    system sepcific operation for arguments."
  },
  {
    "code": "def _set_alternates(self, alts):\n        alternates_path = osp.join(self.common_dir, 'objects', 'info', 'alternates')\n        if not alts:\n            if osp.isfile(alternates_path):\n                os.remove(alternates_path)\n        else:\n            with open(alternates_path, 'wb') as f:\n                f.write(\"\\n\".join(alts).encode(defenc))",
    "docstring": "Sets the alternates\n\n        :param alts:\n            is the array of string paths representing the alternates at which\n            git should look for objects, i.e. /home/user/repo/.git/objects\n\n        :raise NoSuchPathError:\n        :note:\n            The method does not check for the existence of the paths in alts\n            as the caller is responsible."
  },
  {
    "code": "def ned_to_use(tensor):\n    return np.array(ROT_NED_USE * np.matrix(tensor) * ROT_NED_USE.T)",
    "docstring": "Converts a tensor in NED coordinate sytem to USE"
  },
  {
    "code": "def map_package(shutit_pexpect_session, package, install_type):\n\tif package in PACKAGE_MAP.keys():\n\t\tfor itype in PACKAGE_MAP[package].keys():\n\t\t\tif itype == install_type:\n\t\t\t\tret = PACKAGE_MAP[package][install_type]\n\t\t\t\tif isinstance(ret,str):\n\t\t\t\t\treturn ret\n\t\t\t\tif callable(ret):\n\t\t\t\t\tret(shutit_pexpect_session)\n\t\t\t\t\treturn ''\n\treturn package",
    "docstring": "If package mapping exists, then return it, else return package."
  },
  {
    "code": "def compile_query(query):\n    if isinstance(query, dict):\n        expressions = []\n        for key, value in query.items():\n            if key.startswith('$'):\n                if key not in query_funcs:\n                    raise AttributeError('Invalid operator: {}'.format(key))\n                expressions.append(query_funcs[key](value))\n            else:\n                expressions.append(filter_query(key, value))\n        if len(expressions) > 1:\n            return boolean_operator_query(operator.and_)(expressions)\n        else:\n            return (\n                expressions[0]\n                if len(expressions)\n                else lambda query_function: query_function(None, None)\n            )\n    else:\n        return query",
    "docstring": "Compile each expression in query recursively."
  },
  {
    "code": "def purge_obsolete_samples(self, config, now):\n        expire_age = config.samples * config.time_window_ms\n        for sample in self._samples:\n            if now - sample.last_window_ms >= expire_age:\n                sample.reset(now)",
    "docstring": "Timeout any windows that have expired in the absence of any events"
  },
  {
    "code": "def size(self, value):\n        self._size   = value\n        self._thumb  = self._link_to_img()",
    "docstring": "Set the size parameter and regenerate the thumbnail link."
  },
  {
    "code": "def getmetadata(self, key=None):\n        if self.metadata:\n            d =  self.doc.submetadata[self.metadata]\n        elif self.parent:\n            d =  self.parent.getmetadata()\n        elif self.doc:\n            d =  self.doc.metadata\n        else:\n            return None\n        if key:\n            return d[key]\n        else:\n            return d",
    "docstring": "Get the metadata that applies to this element, automatically inherited from parent elements"
  },
  {
    "code": "def read(self, input_file):\n        key, value = None, None\n        import sys\n        for line in input_file:\n            if line == '\\n':\n                break\n            if line[-1:] == '\\n':\n                line = line[:-1]\n            item = line.split(':', 1)\n            if len(item) == 2:\n                self._update(key, value)\n                key, value = item[0], urllib.unquote(item[1])\n            elif key is not None:\n                value = '\\n'.join([value, urllib.unquote(line)])\n        self._update(key, value)\n        return",
    "docstring": "Reads an InputHeader from `input_file`.\n\n        The input header is read as a sequence of *<key>***:***<value>* pairs\n        separated by a newline. The end of the input header is signalled by an\n        empty line or an end-of-file.\n\n        :param input_file: File-like object that supports iteration over lines"
  },
  {
    "code": "def read(self, pin, is_differential=False):\n        pin = pin if is_differential else pin + 0x04\n        return self._read(pin)",
    "docstring": "I2C Interface for ADS1x15-based ADCs reads.\n\n        params:\n            :param pin: individual or differential pin.\n            :param bool is_differential: single-ended or differential read."
  },
  {
    "code": "def clean(self):\r\n        super(SlotCreationForm,self).clean()\r\n        startDate = self.cleaned_data.get('startDate')\r\n        endDate = self.cleaned_data.get('endDate')\r\n        startTime = self.cleaned_data.get('startTime')\r\n        endTime = self.cleaned_data.get('endTime')\r\n        instructor = self.cleaned_data.get('instructorId')\r\n        existingSlots = InstructorAvailabilitySlot.objects.filter(\r\n            instructor=instructor,\r\n            startTime__gt=(\r\n                ensure_localtime(datetime.combine(startDate,startTime)) -\r\n                timedelta(minutes=getConstant('privateLessons__lessonLengthInterval'))\r\n            ),\r\n            startTime__lt=ensure_localtime(datetime.combine(endDate,endTime)),\r\n        )\r\n        if existingSlots.exists():\r\n            raise ValidationError(_('Newly created slots cannot overlap existing slots for this instructor.'),code='invalid')",
    "docstring": "Only allow submission if there are not already slots in the submitted window,\r\n        and only allow rooms associated with the chosen location."
  },
  {
    "code": "def getOverlayTextureSize(self, ulOverlayHandle):\n        fn = self.function_table.getOverlayTextureSize\n        pWidth = c_uint32()\n        pHeight = c_uint32()\n        result = fn(ulOverlayHandle, byref(pWidth), byref(pHeight))\n        return result, pWidth.value, pHeight.value",
    "docstring": "Get the size of the overlay texture"
  },
  {
    "code": "def set_data(self, frames):\n        data_frames = []\n        for frame in frames:\n            frame = frame.swapaxes(0, 1)\n            if len(frame.shape) < 3:\n                frame = np.array([frame]).swapaxes(0, 2).swapaxes(0, 1)\n            data_frames.append(frame)\n        frames_n = len(data_frames)\n        data_frames = np.array(data_frames)\n        data_frames = np.rollaxis(data_frames, 3)\n        data_frames = data_frames.swapaxes(2, 3)\n        self.data = data_frames\n        self.length = frames_n",
    "docstring": "Prepare the input of model"
  },
  {
    "code": "def return_feature_list_base(dbpath, set_object):\n    engine = create_engine('sqlite:////' + dbpath)\n    session_cl = sessionmaker(bind=engine)\n    session = session_cl()\n    return_list = []\n    tmp_object = session.query(set_object).get(1)\n    for feature in tmp_object.features:\n        return_list.append(feature)\n    session.close()\n    return return_list",
    "docstring": "Generic function which returns a list of the names of all available features\n\n    Parameters\n    ----------\n    dbpath : string, path to SQLite database file\n    set_object : object (either TestSet or TrainSet) which is stored in the database\n\n    Returns\n    -------\n    return_list : list of strings corresponding to all available features"
  },
  {
    "code": "def get_deliveryserver(self, domainid, serverid):\n        return self.api_call(\n            ENDPOINTS['deliveryservers']['get'],\n            dict(domainid=domainid, serverid=serverid))",
    "docstring": "Get a delivery server"
  },
  {
    "code": "def add_scm_info(self):\n    scm = get_scm()\n    if scm:\n      revision = scm.commit_id\n      branch = scm.branch_name or revision\n    else:\n      revision, branch = 'none', 'none'\n    self.add_infos(('revision', revision), ('branch', branch))",
    "docstring": "Adds SCM-related info."
  },
  {
    "code": "def get_k8s_metadata():\n    k8s_metadata = {}\n    gcp_cluster = (gcp_metadata_config.GcpMetadataConfig\n                   .get_attribute(gcp_metadata_config.CLUSTER_NAME_KEY))\n    if gcp_cluster is not None:\n        k8s_metadata[CLUSTER_NAME_KEY] = gcp_cluster\n    for attribute_key, attribute_env in _K8S_ENV_ATTRIBUTES.items():\n        attribute_value = os.environ.get(attribute_env)\n        if attribute_value is not None:\n            k8s_metadata[attribute_key] = attribute_value\n    return k8s_metadata",
    "docstring": "Get kubernetes container metadata, as on GCP GKE."
  },
  {
    "code": "def mate_top(self):\n        \" top of the stator\"\n        return Mate(self, CoordSystem(\n            origin=(0, 0, self.length/2),\n            xDir=(0, 1, 0),\n            normal=(0, 0, 1)\n            ))",
    "docstring": "top of the stator"
  },
  {
    "code": "def long2str(l):\n    if type(l) not in (types.IntType, types.LongType):\n        raise ValueError('the input must be an integer')\n    if l < 0:\n        raise ValueError('the input must be greater than 0')\n    s = ''\n    while l:\n        s = s + chr(l & 255)\n        l >>= 8\n    return s",
    "docstring": "Convert an integer to a string."
  },
  {
    "code": "def get_firmware_version(self, cached=True):\n        if cached and self.firmware_version != 'unknown':\n            return self.firmware_version\n        firmware_version = self.get_characteristic_handle_from_uuid(UUID_FIRMWARE_REVISION)\n        if firmware_version is None:\n            logger.warn('Failed to find handle for firmware version')\n            return None\n        self.firmware_version = self.dongle._read_attribute(self.conn_handle, firmware_version)\n        return self.firmware_version",
    "docstring": "Returns the SK8 device firmware version.\n\n        Args:\n            cached (bool): if True, returns the locally cached copy of the firmware version.\n                If this is set to False, or the version is not cached, it will read from\n                the device instead. \n\n        Returns:\n            str. The current firmware version string. May be `None` if an error occurs."
  },
  {
    "code": "def bind_client(self, new):\n        top = self._stack[-1]\n        self._stack[-1] = (new, top[1])",
    "docstring": "Binds a new client to the hub."
  },
  {
    "code": "def linsys(x0, rho, P, q):\n    return np.linalg.solve(rho * np.eye(q.shape[0]) + P, rho * x0.copy() + q)",
    "docstring": "Proximal operator for the linear approximation Ax = b\n\n    Minimizes the function:\n\n    .. math:: f(x) = (1/2)||Ax-b||_2^2 = (1/2)x^TA^TAx - (b^TA)x + b^Tb\n\n    Parameters\n    ----------\n    x0 : array_like\n        The starting or initial point used in the proximal update step\n\n    rho : float\n        Momentum parameter for the proximal step (larger value -> stays closer to x0)\n\n    P : array_like\n        The symmetric matrix A^TA, where we are trying to approximate Ax=b\n\n    q : array_like\n        The vector A^Tb, where we are trying to approximate Ax=b\n\n    Returns\n    -------\n    theta : array_like\n        The parameter vector found after running the proximal update step"
  },
  {
    "code": "def compile(self):\n        if self.buffer is None:\n            self.buffer = self._compile_value(self.data, 0)\n        return self.buffer.strip()",
    "docstring": "Return Hip string if already compiled else compile it."
  },
  {
    "code": "def coerce_str_to_bool(val: t.Union[str, int, bool, None], strict: bool = False) -> bool:\n    if isinstance(val, str):\n        val = val.lower()\n    flag = ENV_STR_BOOL_COERCE_MAP.get(val, None)\n    if flag is not None:\n        return flag\n    if strict:\n        raise ValueError('Unsupported value for boolean flag: `%s`' % val)\n    return bool(val)",
    "docstring": "Converts a given string ``val`` into a boolean.\n\n    :param val: any string representation of boolean\n    :param strict: raise ``ValueError`` if ``val`` does not look like a boolean-like object\n    :return: ``True`` if ``val`` is thruthy, ``False`` otherwise.\n\n    :raises ValueError: if ``strict`` specified and ``val`` got anything except\n     ``['', 0, 1, true, false, on, off, True, False]``"
  },
  {
    "code": "def _request(self, func, url, version=1, *args, **kwargs):\n        return_json = kwargs.pop('return_json', False)\n        url = self.api_url[version] + url\n        response = func(url, *args, **kwargs)\n        if 'proxies' not in kwargs:\n            kwargs['proxies'] = self.proxydict\n        response.raise_for_status()\n        try:\n            json_response = response.json()\n        except ValueError:\n            json_response = None\n        if isinstance(json_response, dict):\n            error = json_response.get('error')\n            if error:\n                raise BitstampError(error)\n            elif json_response.get('status') == \"error\":\n                raise BitstampError(json_response.get('reason'))\n        if return_json:\n            if json_response is None:\n                raise BitstampError(\n                    \"Could not decode json for: \" + response.text)\n            return json_response\n        return response",
    "docstring": "Make a generic request, adding in any proxy defined by the instance.\n\n        Raises a ``requests.HTTPError`` if the response status isn't 200, and\n        raises a :class:`BitstampError` if the response contains a json encoded\n        error message."
  },
  {
    "code": "def uri_path(self, path):\n        path = path.strip(\"/\")\n        tmp = path.split(\"?\")\n        path = tmp[0]\n        paths = path.split(\"/\")\n        for p in paths:\n            option = Option()\n            option.number = defines.OptionRegistry.URI_PATH.number\n            option.value = p\n            self.add_option(option)\n        if len(tmp) > 1:\n            query = tmp[1]\n            self.uri_query = query",
    "docstring": "Set the Uri-Path of a request.\n\n        :param path: the Uri-Path"
  },
  {
    "code": "def show_log(self):\n        self.action_show_report.setEnabled(True)\n        self.action_show_log.setEnabled(False)\n        self.load_html_file(self.log_path)",
    "docstring": "Show log."
  },
  {
    "code": "def most_confused(self, min_val:int=1, slice_size:int=1)->Collection[Tuple[str,str,int]]:\n        \"Sorted descending list of largest non-diagonal entries of confusion matrix, presented as actual, predicted, number of occurrences.\"\n        cm = self.confusion_matrix(slice_size=slice_size)\n        np.fill_diagonal(cm, 0)\n        res = [(self.data.classes[i],self.data.classes[j],cm[i,j])\n                for i,j in zip(*np.where(cm>=min_val))]\n        return sorted(res, key=itemgetter(2), reverse=True)",
    "docstring": "Sorted descending list of largest non-diagonal entries of confusion matrix, presented as actual, predicted, number of occurrences."
  },
  {
    "code": "def validate_packet(self, data):\n        expected_length = data[0] + 1\n        if len(data) != expected_length:\n            raise InvalidPacketLength(\n                \"Expected packet length to be %s bytes but it was %s bytes\"\n                % (expected_length, len(data))\n            )\n        if expected_length < 4:\n            raise MalformedPacket(\n                    \"Expected packet length to be larger than 4 bytes but \\\n                    it was %s bytes\"\n                    % (len(data))\n            )\n        packet_type = data[1]\n        if self.PACKET_TYPES and packet_type not in self.PACKET_TYPES:\n            types = \",\".join(\"0x{:02x}\".format(pt) for pt in self.PACKET_TYPES)\n            raise UnknownPacketType(\n                \"Expected packet type to be one of [%s] but recieved %s\"\n                % (types, packet_type)\n            )\n        sub_type = data[2]\n        if self.PACKET_SUBTYPES and sub_type not in self.PACKET_SUBTYPES:\n            types = \\\n                \",\".join(\"0x{:02x}\".format(pt) for pt in self.PACKET_SUBTYPES)\n            raise UnknownPacketSubtype(\n                \"Expected packet type to be one of [%s] but recieved %s\"\n                % (types, sub_type))\n        return True",
    "docstring": "Validate a packet against this packet handler and determine if it\n        meets the requirements. This is done by checking the following\n        conditions are true.\n\n        - The length of the packet is equal to the first byte.\n        - The second byte is in the set of defined PACKET_TYPES for this class.\n        - The third byte is in the set of this class defined PACKET_SUBTYPES.\n\n        If one or more of these conditions isn't met then we have a packet that\n        isn't valid or at least isn't understood by this handler.\n\n        :param data: bytearray to be verified\n        :type data: bytearray\n\n\n        :raises: :py:class:`rfxcom.exceptions.InvalidPacketLength`: If the\n            number of bytes in the packet doesn't match the expected length.\n\n        :raises: :py:class:`rfxcom.exceptions.UnknownPacketType`: If the packet\n            type is unknown to this packet handler\n\n        :raises: :py:class:`rfxcom.exceptions.UnknownPacketSubtype`: If the\n            packet sub type is unknown to this packet handler\n\n        :return: true is returned if validation passes.\n        :rtype: boolean"
  },
  {
    "code": "def save_session(zap_helper, file_path):\n    console.debug('Saving the session to \"{0}\"'.format(file_path))\n    zap_helper.zap.core.save_session(file_path, overwrite='true')",
    "docstring": "Save the session."
  },
  {
    "code": "def getter_(self, fget) -> 'BaseProperty':\n        self.fget = fget\n        self.set_doc(fget.__doc__)\n        return self",
    "docstring": "Add the given getter function and its docstring to the\n         property and return it."
  },
  {
    "code": "def to_swagger(self):\n        return dict_filter(\n            operationId=self.operation_id,\n            description=(self.callback.__doc__ or '').strip() or None,\n            summary=self.summary or None,\n            tags=list(self.tags) or None,\n            deprecated=self.deprecated or None,\n            consumes=list(self.consumes) or None,\n            parameters=[param.to_swagger(self.resource) for param in self.parameters] or None,\n            produces=list(self.produces) or None,\n            responses=dict(resp.to_swagger(self.resource) for resp in self.responses) or None,\n            security=self.security.to_swagger() if self.security else None,\n        )",
    "docstring": "Generate a dictionary for documentation generation."
  },
  {
    "code": "def npix_to_nside(npix):\n    npix = np.asanyarray(npix, dtype=np.int64)\n    if not np.all(npix % 12 == 0):\n        raise ValueError('Number of pixels must be divisible by 12')\n    square_root = np.sqrt(npix / 12)\n    if not np.all(square_root ** 2 == npix / 12):\n        raise ValueError('Number of pixels is not of the form 12 * nside ** 2')\n    return np.round(square_root).astype(int)",
    "docstring": "Find the number of pixels on the side of one of the 12 'top-level' HEALPix\n    tiles given a total number of pixels.\n\n    Parameters\n    ----------\n    npix : int\n        The number of pixels in the HEALPix map.\n\n    Returns\n    -------\n    nside : int\n        The number of pixels on the side of one of the 12 'top-level' HEALPix tiles."
  },
  {
    "code": "def getmoduleinfo(path):\n    filename = os.path.basename(path)\n    suffixes = map(lambda (suffix, mode, mtype):\n                   (-len(suffix), suffix, mode, mtype), imp.get_suffixes())\n    suffixes.sort()\n    for neglen, suffix, mode, mtype in suffixes:\n        if filename[neglen:] == suffix:\n            return filename[:neglen], suffix, mode, mtype",
    "docstring": "Get the module name, suffix, mode, and module type for a given file."
  },
  {
    "code": "def get_generation_code(self):\n        if len(self.gates) < 1:\n            code = ''\n        else:\n            import_list = set([gate._gencode_gate_class for gate in self.gates])\n            import_list = 'from FlowCytometryTools import ' + ', '.join(import_list)\n            code_list = [gate.get_generation_code() for gate in self.gates]\n            code_list.sort()\n            code_list = '\\n'.join(code_list)\n            code = import_list + 2 * '\\n' + code_list\n        self.callback(Event('generated_code',\n                            {'code': code}))\n        return code",
    "docstring": "Return python code that generates all drawn gates."
  },
  {
    "code": "def reset(self, source):\n        self.tokens = []\n        self.source = source\n        self.pos = 0",
    "docstring": "Reset scanner's state.\n\n        :param source: Source for parsing"
  },
  {
    "code": "def get_unique_groups(input_list):\n    out_list = []\n    for item in input_list:\n        if item not in out_list:\n            out_list.append(item)\n    return out_list",
    "docstring": "Function to get a unique list of groups."
  },
  {
    "code": "def __parse_main(self, args):\n        if six.PY2:\n            self._subparsers_action.add_parser(\"__dummy\")\n            return super(FuncArgParser, self).parse_known_args(\n                list(args) + ['__dummy'])\n        return super(FuncArgParser, self).parse_known_args(args)",
    "docstring": "Parse the main arguments only. This is a work around for python 2.7\n        because argparse does not allow to parse arguments without subparsers"
  },
  {
    "code": "def _isinstance(expr, classname):\n        for cls in type(expr).__mro__:\n            if cls.__name__ == classname:\n                return True\n        return False",
    "docstring": "Check whether `expr` is an instance of the class with name\n        `classname`\n\n        This is like the builtin `isinstance`, but it take the `classname` a\n        string, instead of the class directly. Useful for when we don't want to\n        import the class for which we want to check (also, remember that\n        printer choose rendering method based on the class name, so this is\n        totally ok)"
  },
  {
    "code": "def wncond(left, right, window):\n    assert isinstance(window, stypes.SpiceCell)\n    assert window.dtype == 1\n    left = ctypes.c_double(left)\n    right = ctypes.c_double(right)\n    libspice.wncond_c(left, right, ctypes.byref(window))\n    return window",
    "docstring": "Contract each of the intervals of a double precision window.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wncond_c.html\n\n    :param left: Amount added to each left endpoint. \n    :type left: float\n    :param right: Amount subtracted from each right endpoint. \n    :type right: float\n    :param window: Window to be contracted \n    :type window: spiceypy.utils.support_types.SpiceCell\n    :return: Contracted Window.\n    :rtype: spiceypy.utils.support_types.SpiceCell"
  },
  {
    "code": "async def jsk_vc_stop(self, ctx: commands.Context):\n        voice = ctx.guild.voice_client\n        voice.stop()\n        await ctx.send(f\"Stopped playing audio in {voice.channel.name}.\")",
    "docstring": "Stops running an audio source, if there is one."
  },
  {
    "code": "def _represent_match_traversal(match_traversal):\n    output = []\n    output.append(_first_step_to_match(match_traversal[0]))\n    for step in match_traversal[1:]:\n        output.append(_subsequent_step_to_match(step))\n    return u''.join(output)",
    "docstring": "Emit MATCH query code for an entire MATCH traversal sequence."
  },
  {
    "code": "def update_plot_limits(ax, white_space):\n    if hasattr(ax, 'zz_dataLim'):\n        bounds = ax.xy_dataLim.bounds\n        ax.set_xlim(bounds[0] - white_space, bounds[0] + bounds[2] + white_space)\n        ax.set_ylim(bounds[1] - white_space, bounds[1] + bounds[3] + white_space)\n        bounds = ax.zz_dataLim.bounds\n        ax.set_zlim(bounds[0] - white_space, bounds[0] + bounds[2] + white_space)\n    else:\n        bounds = ax.dataLim.bounds\n        assert not any(map(np.isinf, bounds)), 'Cannot set bounds if dataLim has infinite elements'\n        ax.set_xlim(bounds[0] - white_space, bounds[0] + bounds[2] + white_space)\n        ax.set_ylim(bounds[1] - white_space, bounds[1] + bounds[3] + white_space)",
    "docstring": "Sets the limit options of a matplotlib plot.\n\n    Args:\n        ax: matplotlib axes\n        white_space(float): whitespace added to surround the tight limit of the data\n\n    Note: This relies on ax.dataLim (in 2d) and ax.[xy, zz]_dataLim being set in 3d"
  },
  {
    "code": "def SaveGDAL(filename, rda):\n  if type(rda) is not rdarray:\n    raise Exception(\"A richdem.rdarray or numpy.ndarray is required!\")\n  if not GDAL_AVAILABLE:\n    raise Exception(\"richdem.SaveGDAL() requires GDAL.\")\n  driver    = gdal.GetDriverByName('GTiff')\n  data_type = gdal.GDT_Float32\n  data_set  = driver.Create(filename, xsize=rda.shape[1], ysize=rda.shape[0], bands=1, eType=data_type)\n  data_set.SetGeoTransform(rda.geotransform)\n  data_set.SetProjection(rda.projection)\n  band = data_set.GetRasterBand(1)\n  band.SetNoDataValue(rda.no_data)\n  band.WriteArray(np.array(rda))\n  for k,v in rda.metadata.items():\n    data_set.SetMetadataItem(str(k),str(v))",
    "docstring": "Save a GDAL file.\n\n     Saves a RichDEM array to a data file in GeoTIFF format.\n\n     If you need to do something more complicated, look at the source of this\n     function.\n\n     Args:\n         filename (str):     Name of the raster file to be created\n         rda      (rdarray): Data to save.\n\n     Returns:\n         No Return"
  },
  {
    "code": "def handle_data(self, data):\n        if data:\n            inTag = self._inTag\n            if len(inTag) > 0:\n                if inTag[-1].tagName not in PRESERVE_CONTENTS_TAGS:\n                    data = data.replace('\\t', ' ').strip('\\r\\n')\n                    if data.startswith(' '):\n                        data = ' ' + data.lstrip()\n                    if data.endswith(' '):\n                        data = data.rstrip() + ' '\n                inTag[-1].appendText(data)\n            elif data.strip():\n                raise MultipleRootNodeException()",
    "docstring": "handle_data - Internal for parsing"
  },
  {
    "code": "def _kill_process(self, pid, cgroups=None, sig=signal.SIGKILL):\n        if self._user is not None:\n            if not cgroups:\n                cgroups = find_cgroups_of_process(pid)\n            pids = cgroups.get_all_tasks(FREEZER)\n            try:\n                if pid == next(pids):\n                    pid = next(pids)\n            except StopIteration:\n                pass\n            finally:\n                pids.close()\n        self._kill_process0(pid, sig)",
    "docstring": "Try to send signal to given process, either directly of with sudo.\n        Because we cannot send signals to the sudo process itself,\n        this method checks whether the target is the sudo process\n        and redirects the signal to sudo's child in this case."
  },
  {
    "code": "def precheck():\n    binaries = ['make']\n    for bin in binaries:\n        if not which(bin):\n            msg = 'Dependency fail -- Unable to locate rquired binary: '\n            stdout_message('%s: %s' % (msg, ACCENT + bin + RESET))\n            return False\n        elif not root():\n            return False\n    return True",
    "docstring": "Pre-run dependency check"
  },
  {
    "code": "def invert_map(map):\n\tres = dict((v, k) for k, v in map.items())\n\tif not len(res) == len(map):\n\t\traise ValueError('Key conflict in inverted mapping')\n\treturn res",
    "docstring": "Given a dictionary, return another dictionary with keys and values\n\tswitched. If any of the values resolve to the same key, raises\n\ta ValueError.\n\n\t>>> numbers = dict(a=1, b=2, c=3)\n\t>>> letters = invert_map(numbers)\n\t>>> letters[1]\n\t'a'\n\t>>> numbers['d'] = 3\n\t>>> invert_map(numbers)\n\tTraceback (most recent call last):\n\t...\n\tValueError: Key conflict in inverted mapping"
  },
  {
    "code": "def _push_broks(self):\n        data = cherrypy.request.json\n        with self.app.arbiter_broks_lock:\n            logger.debug(\"Pushing %d broks\", len(data['broks']))\n            self.app.arbiter_broks.extend([unserialize(elem, True) for elem in data['broks']])",
    "docstring": "Push the provided broks objects to the broker daemon\n\n        Only used on a Broker daemon by the Arbiter\n\n        :param: broks\n        :type: list\n        :return: None"
  },
  {
    "code": "def get_user(user, driver):\n    response = ApitaxResponse()\n    driver: Driver = LoadedDrivers.getDriver(driver)\n    user: User = driver.getApitaxUser(User(username=user))\n    response.body.add({'user': {'username': user.username, 'role': user.role}})\n    return Response(status=200, body=response.getResponseBody())",
    "docstring": "Retrieve a user\n\n    Retrieve a user # noqa: E501\n\n    :param user: Get user with this name\n    :type user: str\n    :param driver: The driver to use for the request. ie. github\n    :type driver: str\n\n    :rtype: Response"
  },
  {
    "code": "def shiftAccent(self, shiftAmount):\n        if shiftAmount == 0:\n            return\n        self.pointList = [(time + shiftAmount, pitch)\n                          for time, pitch in self.pointList]\n        if shiftAmount < 0:\n            self.netLeftShift += shiftAmount\n        elif shiftAmount >= 0:\n            self.netRightShift += shiftAmount",
    "docstring": "Move the whole accent earlier or later"
  },
  {
    "code": "def require_root(fn):\n    @wraps(fn)\n    def xex(*args, **kwargs):\n        assert os.geteuid() == 0, \\\n            \"You have to be root to run function '%s'.\" % fn.__name__\n        return fn(*args, **kwargs)\n    return xex",
    "docstring": "Decorator to make sure, that user is root."
  },
  {
    "code": "def idfn(fixture_params: Iterable[Any]) -> str:\n    return \":\".join((str(item) for item in fixture_params))",
    "docstring": "Function for pytest to produce uniform names for fixtures."
  },
  {
    "code": "def execute_until_in_scope(\n    expr, scope, aggcontext=None, clients=None, post_execute_=None, **kwargs\n):\n    assert aggcontext is not None, 'aggcontext is None'\n    assert clients is not None, 'clients is None'\n    assert post_execute_ is not None, 'post_execute_ is None'\n    op = expr.op()\n    if op in scope:\n        return scope[op]\n    new_scope = execute_bottom_up(\n        expr,\n        scope,\n        aggcontext=aggcontext,\n        post_execute_=post_execute_,\n        clients=clients,\n        **kwargs,\n    )\n    new_scope = toolz.merge(\n        new_scope, pre_execute(op, *clients, scope=scope, **kwargs)\n    )\n    return execute_until_in_scope(\n        expr,\n        new_scope,\n        aggcontext=aggcontext,\n        clients=clients,\n        post_execute_=post_execute_,\n        **kwargs,\n    )",
    "docstring": "Execute until our op is in `scope`.\n\n    Parameters\n    ----------\n    expr : ibis.expr.types.Expr\n    scope : Mapping\n    aggcontext : Optional[AggregationContext]\n    clients : List[ibis.client.Client]\n    kwargs : Mapping"
  },
  {
    "code": "def close(self, silent=False):\n        if not silent:\n            saveme = get_input(\"Save database contents to '{}/'? (y, [n]) \\n\"\n                               \"To save elsewhere, run db.save() before closing. \".format(self.directory))\n            if saveme.lower() == 'y':\n                self.save()\n            delete = get_input(\"Do you want to delete {0}? (y,[n]) \\n\"\n                               \"Don't worry, a new one will be generated if you run astrodb.Database('{1}') \"\n                               .format(self.dbpath, self.sqlpath))\n            if delete.lower() == 'y':\n                print(\"Deleting {}\".format(self.dbpath))\n                os.system(\"rm {}\".format(self.dbpath))\n        print('Closing connection')\n        self.conn.close()",
    "docstring": "Close the database and ask to save and delete the file\n\n        Parameters\n        ----------\n        silent: bool\n            Close quietly without saving or deleting (Default: False)."
  },
  {
    "code": "def serialize_artifact_json_blobs(artifacts):\n    for artifact in artifacts:\n        blob = artifact['blob']\n        if (artifact['type'].lower() == 'json' and\n                not isinstance(blob, str)):\n            artifact['blob'] = json.dumps(blob)\n    return artifacts",
    "docstring": "Ensure that JSON artifact blobs passed as dicts are converted to JSON"
  },
  {
    "code": "def save(self, force_insert=False, force_update=False, using=None,\n             update_fields=None):\n        self.pk = None\n        super(ConfigurationModel, self).save(\n            force_insert,\n            force_update,\n            using,\n            update_fields\n        )\n        cache.delete(self.cache_key_name(*[getattr(self, key) for key in self.KEY_FIELDS]))\n        if self.KEY_FIELDS:\n            cache.delete(self.key_values_cache_key_name())",
    "docstring": "Clear the cached value when saving a new configuration entry"
  },
  {
    "code": "def get_sym_eq_kpoints(self, kpoint, cartesian=False, tol=1e-2):\n        if not self.structure:\n            return None\n        sg = SpacegroupAnalyzer(self.structure)\n        symmops = sg.get_point_group_operations(cartesian=cartesian)\n        points = np.dot(kpoint, [m.rotation_matrix for m in symmops])\n        rm_list = []\n        for i in range(len(points) - 1):\n            for j in range(i + 1, len(points)):\n                if np.allclose(pbc_diff(points[i], points[j]), [0, 0, 0], tol):\n                    rm_list.append(i)\n                    break\n        return np.delete(points, rm_list, axis=0)",
    "docstring": "Returns a list of unique symmetrically equivalent k-points.\n\n        Args:\n            kpoint (1x3 array): coordinate of the k-point\n            cartesian (bool): kpoint is in cartesian or fractional coordinates\n            tol (float): tolerance below which coordinates are considered equal\n\n        Returns:\n            ([1x3 array] or None): if structure is not available returns None"
  },
  {
    "code": "def CreateBlockDeviceMap(self, image_id, instance_type):\n      image = self.ec2.get_image(image_id)\n      block_device_map = image.block_device_mapping\n      assert(block_device_map)\n      ephemeral_device_names = ['/dev/sdb', '/dev/sdc', '/dev/sdd', '/dev/sde']\n      for i, device_name in enumerate(ephemeral_device_names):\n        name = 'ephemeral%d' % (i)\n        bdt = blockdevicemapping.BlockDeviceType(ephemeral_name = name)\n        block_device_map[device_name] = bdt\n      return block_device_map",
    "docstring": "If you launch without specifying a manual device block mapping, you may \n      not get all the ephemeral devices available to the given instance type.\n      This will build one that ensures all available ephemeral devices are\n      mapped."
  },
  {
    "code": "def _configure_ebs_volume(self, vol_type, name, size, delete_on_termination):\n        root_dev = boto.ec2.blockdevicemapping.BlockDeviceType()\n        root_dev.delete_on_termination = delete_on_termination\n        root_dev.volume_type = vol_type\n        if size != 'default':\n            root_dev.size = size\n        bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()\n        bdm[name] = root_dev\n        return bdm",
    "docstring": "Sets the desired root EBS size, otherwise the default EC2 value is used.\n\n        :param vol_type: Type of EBS storage - gp2 (SSD), io1 or standard (magnetic)\n        :type vol_type: str\n        :param size: Desired root EBS size.\n        :type size: int\n        :param delete_on_termination: Toggle this flag to delete EBS volume on termination.\n        :type delete_on_termination: bool\n        :return: A BlockDeviceMapping object.\n        :rtype: object"
  },
  {
    "code": "def to_dict(self):\n        session = self._get_session()\n        snapshot = self._get_snapshot()\n        return {\n            \"session_id\": session._session_id,\n            \"transaction_id\": snapshot._transaction_id,\n        }",
    "docstring": "Return state as a dictionary.\n\n        Result can be used to serialize the instance and reconstitute\n        it later using :meth:`from_dict`.\n\n        :rtype: dict"
  },
  {
    "code": "def getopt(self, p, default=None):\n        for k, v in self.pairs:\n            if k == p:\n                return v\n        return default",
    "docstring": "Returns the first option value stored that matches p or default."
  },
  {
    "code": "def _fetch_dataframe(self):\n        def reshape(training_summary):\n            out = {}\n            for k, v in training_summary['TunedHyperParameters'].items():\n                try:\n                    v = float(v)\n                except (TypeError, ValueError):\n                    pass\n                out[k] = v\n            out['TrainingJobName'] = training_summary['TrainingJobName']\n            out['TrainingJobStatus'] = training_summary['TrainingJobStatus']\n            out['FinalObjectiveValue'] = training_summary.get('FinalHyperParameterTuningJobObjectiveMetric',\n                                                              {}).get('Value')\n            start_time = training_summary.get('TrainingStartTime', None)\n            end_time = training_summary.get('TrainingEndTime', None)\n            out['TrainingStartTime'] = start_time\n            out['TrainingEndTime'] = end_time\n            if start_time and end_time:\n                out['TrainingElapsedTimeSeconds'] = (end_time - start_time).total_seconds()\n            return out\n        df = pd.DataFrame([reshape(tjs) for tjs in self.training_job_summaries()])\n        return df",
    "docstring": "Return a pandas dataframe with all the training jobs, along with their\n        hyperparameters, results, and metadata. This also includes a column to indicate\n        if a training job was the best seen so far."
  },
  {
    "code": "def export_modifications(self):\n        if self.__modified_data__ is not None:\n            return self.export_data()\n        result = {}\n        for key, value in enumerate(self.__original_data__):\n            try:\n                if not value.is_modified():\n                    continue\n                modifications = value.export_modifications()\n            except AttributeError:\n                continue\n            try:\n                result.update({'{}.{}'.format(key, f): v for f, v in modifications.items()})\n            except AttributeError:\n                result[key] = modifications\n        return result",
    "docstring": "Returns list modifications."
  },
  {
    "code": "def pop_fw_local(self, tenant_id, net_id, direc, node_ip):\n        net = self.get_network(net_id)\n        serv_obj = self.get_service_obj(tenant_id)\n        serv_obj.update_fw_local_cache(net_id, direc, node_ip)\n        if net is not None:\n            net_dict = self.fill_dcnm_net_info(tenant_id, direc, net.vlan,\n                                               net.segmentation_id)\n            serv_obj.store_dcnm_net_dict(net_dict, direc)\n        if direc == \"in\":\n            subnet = self.service_in_ip.get_subnet_by_netid(net_id)\n        else:\n            subnet = self.service_out_ip.get_subnet_by_netid(net_id)\n        if subnet is not None:\n            subnet_dict = self.fill_dcnm_subnet_info(\n                tenant_id, subnet,\n                self.get_start_ip(subnet), self.get_end_ip(subnet),\n                self.get_gateway(subnet), self.get_secondary_gateway(subnet),\n                direc)\n            serv_obj.store_dcnm_subnet_dict(subnet_dict, direc)",
    "docstring": "Populate the local cache.\n\n        Read the Network DB and populate the local cache.\n        Read the subnet from the Subnet DB, given the net_id and populate the\n        cache."
  },
  {
    "code": "def set_pragmas(self, pragmas):\n        self.pragmas = pragmas\n        c = self.conn.cursor()\n        c.executescript(\n            ';\\n'.join(\n                ['PRAGMA %s=%s' % i for i in self.pragmas.items()]\n            )\n        )\n        self.conn.commit()",
    "docstring": "Set pragmas for the current database connection.\n\n        Parameters\n        ----------\n        pragmas : dict\n            Dictionary of pragmas; see constants.default_pragmas for a template\n            and http://www.sqlite.org/pragma.html for a full list."
  },
  {
    "code": "def _admin_metadata_from_uri(uri, config_path):\n    uri = dtoolcore.utils.sanitise_uri(uri)\n    storage_broker = _get_storage_broker(uri, config_path)\n    admin_metadata = storage_broker.get_admin_metadata()\n    return admin_metadata",
    "docstring": "Helper function for getting admin metadata."
  },
  {
    "code": "def declare_local_operator(self, type, raw_model=None):\n        onnx_name = self.get_unique_operator_name(str(type))\n        operator = Operator(onnx_name, self.name, type, raw_model, self.target_opset)\n        self.operators[onnx_name] = operator\n        return operator",
    "docstring": "This function is used to declare new local operator."
  },
  {
    "code": "def sort(self, columnId, order=Qt.AscendingOrder):\n        self.layoutAboutToBeChanged.emit()\n        self.sortingAboutToStart.emit()\n        column = self._dataFrame.columns[columnId]\n        self._dataFrame.sort_values(column, ascending=not bool(order), inplace=True)\n        self.layoutChanged.emit()\n        self.sortingFinished.emit()",
    "docstring": "Sorts the model column\n\n        After sorting the data in ascending or descending order, a signal\n        `layoutChanged` is emitted.\n\n        :param: columnId (int)\n            the index of the column to sort on.\n        :param: order (Qt::SortOrder, optional)\n            descending(1) or ascending(0). defaults to Qt.AscendingOrder"
  },
  {
    "code": "def metadata(dataset, node, entityids, extended=False, api_key=None):\n    api_key = _get_api_key(api_key)\n    url = '{}/metadata'.format(USGS_API)\n    payload = {\n        \"jsonRequest\": payloads.metadata(dataset, node, entityids, api_key=api_key)\n    }\n    r = requests.post(url, payload)\n    response = r.json()\n    _check_for_usgs_error(response)\n    if extended:\n        metadata_urls = map(_get_metadata_url, response['data'])\n        results = _async_requests(metadata_urls)\n        data = map(lambda idx: _get_extended(response['data'][idx], results[idx]), range(len(response['data'])))\n    return response",
    "docstring": "Request metadata for a given scene in a USGS dataset.\n\n    :param dataset:\n    :param node:\n    :param entityids:\n    :param extended:\n        Send a second request to the metadata url to get extended metadata on the scene.\n    :param api_key:"
  },
  {
    "code": "def get_project(username, project, machine_name=None):\n    try:\n        account = Account.objects.get(\n            username=username,\n            date_deleted__isnull=True)\n    except Account.DoesNotExist:\n        return \"Account '%s' not found\" % username\n    if project is None:\n        project = account.default_project\n    else:\n        try:\n            project = Project.objects.get(pid=project)\n        except Project.DoesNotExist:\n            project = account.default_project\n    if project is None:\n        return \"None\"\n    if account.person not in project.group.members.all():\n        project = account.default_project\n    if project is None:\n        return \"None\"\n    if account.person not in project.group.members.all():\n        return \"None\"\n    return project.pid",
    "docstring": "Used in the submit filter to make sure user is in project"
  },
  {
    "code": "def _update_indexes_for_deleted_object(collection, obj):\n    for index in _db[collection].indexes.values():\n        _remove_from_index(index, obj)",
    "docstring": "If an object is deleted, it should no longer be\n    indexed so this removes the object from all indexes\n    on the given collection."
  },
  {
    "code": "def get_random_node(graph,\n                    node_blacklist: Set[BaseEntity],\n                    invert_degrees: Optional[bool] = None,\n                    ) -> Optional[BaseEntity]:\n    try:\n        nodes, degrees = zip(*(\n            (node, degree)\n            for node, degree in sorted(graph.degree(), key=itemgetter(1))\n            if node not in node_blacklist\n        ))\n    except ValueError:\n        return\n    if invert_degrees is None or invert_degrees:\n        degrees = [1 / degree for degree in degrees]\n    wrg = WeightedRandomGenerator(nodes, degrees)\n    return wrg.next()",
    "docstring": "Choose a node from the graph with probabilities based on their degrees.\n\n    :type graph: networkx.Graph\n    :param node_blacklist: Nodes to filter out\n    :param invert_degrees: Should the degrees be inverted? Defaults to true."
  },
  {
    "code": "def body_as_str(self, encoding='UTF-8'):\n        data = self.body\n        try:\n            return \"\".join(b.decode(encoding) for b in data)\n        except TypeError:\n            return six.text_type(data)\n        except:\n            pass\n        try:\n            return data.decode(encoding)\n        except Exception as e:\n            raise TypeError(\"Message data is not compatible with string type: {}\".format(e))",
    "docstring": "The body of the event data as a string if the data is of a\n        compatible type.\n\n        :param encoding: The encoding to use for decoding message data.\n         Default is 'UTF-8'\n        :rtype: str or unicode"
  },
  {
    "code": "def _restore_volume(self, fade):\n        self.device.mute = self.mute\n        if self.volume == 100:\n            fixed_vol = self.device.renderingControl.GetOutputFixed(\n                [('InstanceID', 0)])['CurrentFixed']\n        else:\n            fixed_vol = False\n        if not fixed_vol:\n            self.device.bass = self.bass\n            self.device.treble = self.treble\n            self.device.loudness = self.loudness\n            if fade:\n                self.device.volume = 0\n                self.device.ramp_to_volume(self.volume)\n            else:\n                self.device.volume = self.volume",
    "docstring": "Reinstate volume.\n\n        Args:\n            fade (bool): Whether volume should be faded up on restore."
  },
  {
    "code": "def _ensure_extra_rows(self, term, N):\n        attrs = self.graph.node[term]\n        attrs['extra_rows'] = max(N, attrs.get('extra_rows', 0))",
    "docstring": "Ensure that we're going to compute at least N extra rows of `term`."
  },
  {
    "code": "def ingest(self, **kwargs):\n        __name__ = '%s.ingest' % self.__class__.__name__\n        schema_dict = self.schema\n        path_to_root = '.'\n        valid_data = self._ingest_dict(kwargs, schema_dict, path_to_root)\n        return valid_data",
    "docstring": "a core method to ingest and validate arbitrary keyword data\n\n            **NOTE: data is always returned with this method**\n\n            for each key in the model, a value is returned according\n             to the following priority:\n\n                1. value in kwargs if field passes validation test\n                2. default value declared for the key in the model\n                3. empty value appropriate to datatype of key in the model\n\n            **NOTE: as long as a default value is provided for each key-\n             value, returned data will be model valid\n\n            **NOTE: if 'extra_fields' is True for a dictionary, the key-\n             value pair of all fields in kwargs which are not declared in\n             the model will also be added to the corresponding dictionary\n             data\n\n            **NOTE: if 'max_size' is declared for a list, method will\n             stop adding input to the list once it reaches max size\n\n        :param kwargs: key, value pairs\n        :return: dictionary with keys and value"
  },
  {
    "code": "def copy_neg(self):\n        result = mpfr.Mpfr_t.__new__(BigFloat)\n        mpfr.mpfr_init2(result, self.precision)\n        new_sign = not self._sign()\n        mpfr.mpfr_setsign(result, self, new_sign, ROUND_TIES_TO_EVEN)\n        return result",
    "docstring": "Return a copy of self with the opposite sign bit.\n\n        Unlike -self, this does not make use of the context:  the result\n        has the same precision as the original."
  },
  {
    "code": "def get_property_value_for_brok(self, prop, tab):\n        entry = tab[prop]\n        value = getattr(self, prop, entry.default)\n        pre_op = entry.brok_transformation\n        if pre_op is not None:\n            value = pre_op(self, value)\n        return value",
    "docstring": "Get the property of an object and brok_transformation if needed and return the value\n\n        :param prop: property name\n        :type prop: str\n        :param tab: object with all properties of an object\n        :type tab: object\n        :return: value of the property original or brok converted\n        :rtype: str"
  },
  {
    "code": "def _init_dict(self, data, index=None, dtype=None):\n        if data:\n            keys, values = zip(*data.items())\n            values = list(values)\n        elif index is not None:\n            values = na_value_for_dtype(dtype)\n            keys = index\n        else:\n            keys, values = [], []\n        s = Series(values, index=keys, dtype=dtype)\n        if data and index is not None:\n            s = s.reindex(index, copy=False)\n        elif not PY36 and not isinstance(data, OrderedDict) and data:\n            try:\n                s = s.sort_index()\n            except TypeError:\n                pass\n        return s._data, s.index",
    "docstring": "Derive the \"_data\" and \"index\" attributes of a new Series from a\n        dictionary input.\n\n        Parameters\n        ----------\n        data : dict or dict-like\n            Data used to populate the new Series\n        index : Index or index-like, default None\n            index for the new Series: if None, use dict keys\n        dtype : dtype, default None\n            dtype for the new Series: if None, infer from data\n\n        Returns\n        -------\n        _data : BlockManager for the new Series\n        index : index for the new Series"
  },
  {
    "code": "def recall_score(y_true, y_pred, average='micro', suffix=False):\n    true_entities = set(get_entities(y_true, suffix))\n    pred_entities = set(get_entities(y_pred, suffix))\n    nb_correct = len(true_entities & pred_entities)\n    nb_true = len(true_entities)\n    score = nb_correct / nb_true if nb_true > 0 else 0\n    return score",
    "docstring": "Compute the recall.\n\n    The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of\n    true positives and ``fn`` the number of false negatives. The recall is\n    intuitively the ability of the classifier to find all the positive samples.\n\n    The best value is 1 and the worst value is 0.\n\n    Args:\n        y_true : 2d array. Ground truth (correct) target values.\n        y_pred : 2d array. Estimated targets as returned by a tagger.\n\n    Returns:\n        score : float.\n\n    Example:\n        >>> from seqeval.metrics import recall_score\n        >>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]\n        >>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]\n        >>> recall_score(y_true, y_pred)\n        0.50"
  },
  {
    "code": "def _get_record(self, record_type):\n        if not self.has_record_type(record_type):\n            raise errors.Unsupported()\n        if str(record_type) not in self._records:\n            raise errors.Unimplemented()\n        return self._records[str(record_type)]",
    "docstring": "Get the record string type value given the record_type."
  },
  {
    "code": "def _is_string(thing):\n    if _util._py3k: return isinstance(thing, str)\n    else: return isinstance(thing, basestring)",
    "docstring": "Python character arrays are a mess.\n\n    If Python2, check if **thing** is an :obj:`unicode` or a :obj:`str`.\n    If Python3, check if **thing** is a :obj:`str`.\n\n    :param thing: The thing to check.\n    :returns: ``True`` if **thing** is a string according to whichever version\n              of Python we're running in."
  },
  {
    "code": "def read_index(self):\n        if not isinstance(self.tree, dict):\n            self.tree = dict()\n        self.tree.clear()\n        for path, metadata in self.read_index_iter():\n            self.tree[path] = metadata",
    "docstring": "Reads the index and populates the directory tree"
  },
  {
    "code": "def depth_february_average_ground_temperature(self, value=None):\n        if value is not None:\n            try:\n                value = float(value)\n            except ValueError:\n                raise ValueError(\n                    'value {} need to be of type float '\n                    'for field `depth_february_average_ground_temperature`'.format(value))\n        self._depth_february_average_ground_temperature = value",
    "docstring": "Corresponds to IDD Field `depth_february_average_ground_temperature`\n\n        Args:\n            value (float): value for IDD Field `depth_february_average_ground_temperature`\n                Unit: C\n                if `value` is None it will not be checked against the\n                specification and is assumed to be a missing value\n\n        Raises:\n            ValueError: if `value` is not a valid value"
  },
  {
    "code": "def _repair_row(self):\n        check_for_title = True\n        for row_index in range(self.start[0], self.end[0]):\n            table_row = self.table[row_index]\n            row_start = table_row[self.start[1]]\n            if check_for_title and is_empty_cell(row_start):\n                self._stringify_row(row_index)\n            elif (isinstance(row_start, basestring) and\n                  re.search(allregex.year_regex, row_start)):\n                self._check_stringify_year_row(row_index)\n            else:\n                check_for_title = False",
    "docstring": "Searches for missing titles that can be inferred from the surrounding data and automatically\n        repairs those titles."
  },
  {
    "code": "def _log_msg(self, msg, ok):\n        if self._config['color']:\n            CGREEN, CRED, CEND = '\\033[92m', '\\033[91m', '\\033[0m'\n        else:\n            CGREEN = CRED = CEND = ''\n        LOG_LEVELS = {False: logging.ERROR, True: logging.INFO}\n        L.log(LOG_LEVELS[ok],\n              '%35s %s' + CEND, msg, CGREEN + 'PASS' if ok else CRED + 'FAIL')",
    "docstring": "Helper to log message to the right level"
  },
  {
    "code": "def update_url(self, url=None):\n        if not url:\n            raise ValueError(\"Neither a url or regex was provided to update_url.\")\n        post_url = \"%s%s\" % (self.BASE_URL, url)\n        r = self.session.post(post_url)\n        return int(r.status_code) < 500",
    "docstring": "Accepts a fully-qualified url.\n        Returns True if successful, False if not successful."
  },
  {
    "code": "def get_gpu_memory_usage(ctx: List[mx.context.Context]) -> Dict[int, Tuple[int, int]]:\n    if isinstance(ctx, mx.context.Context):\n        ctx = [ctx]\n    ctx = [c for c in ctx if c.device_type == 'gpu']\n    if not ctx:\n        return {}\n    if shutil.which(\"nvidia-smi\") is None:\n        logger.warning(\"Couldn't find nvidia-smi, therefore we assume no GPUs are available.\")\n        return {}\n    device_ids = [c.device_id for c in ctx]\n    mp_context = mp_utils.get_context()\n    result_queue = mp_context.Queue()\n    nvidia_smi_process = mp_context.Process(target=query_nvidia_smi, args=(device_ids, result_queue,))\n    nvidia_smi_process.start()\n    nvidia_smi_process.join()\n    memory_data = result_queue.get()\n    log_gpu_memory_usage(memory_data)\n    return memory_data",
    "docstring": "Returns used and total memory for GPUs identified by the given context list.\n\n    :param ctx: List of MXNet context devices.\n    :return: Dictionary of device id mapping to a tuple of (memory used, memory total)."
  },
  {
    "code": "def save(self, filename):\n        filename = pathlib.Path(filename)\n        out = []\n        keys = sorted(list(self.keys()))\n        for key in keys:\n            out.append(\"[{}]\".format(key))\n            section = self[key]\n            ikeys = list(section.keys())\n            ikeys.sort()\n            for ikey in ikeys:\n                var, val = keyval_typ2str(ikey, section[ikey])\n                out.append(\"{} = {}\".format(var, val))\n            out.append(\"\")\n        with filename.open(\"w\") as f:\n            for i in range(len(out)):\n                out[i] = out[i]+\"\\n\"\n            f.writelines(out)",
    "docstring": "Save the configuration to a file"
  },
  {
    "code": "def zcr(data):\n    data = np.mean(data, axis=1)\n    count = len(data)\n    countZ = np.sum(np.abs(np.diff(np.sign(data)))) / 2\n    return (np.float64(countZ) / np.float64(count - 1.0))",
    "docstring": "Computes zero crossing rate of segment"
  },
  {
    "code": "def adjust_attributes_on_object(self, collection, name, things, values, how):\n        url = self._build_url(\"%s/%s\" % (collection, name))\n        response = self._get(url)\n        logger.debug(\"before modification: %s\", response.content)\n        build_json = response.json()\n        how(build_json['metadata'], things, values)\n        response = self._put(url, data=json.dumps(build_json), use_json=True)\n        check_response(response)\n        return response",
    "docstring": "adjust labels or annotations on object\n\n        labels have to match RE: (([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])? and\n        have at most 63 chars\n\n        :param collection: str, object collection e.g. 'builds'\n        :param name: str, name of object\n        :param things: str, 'labels' or 'annotations'\n        :param values: dict, values to set\n        :param how: callable, how to adjust the values e.g.\n                    self._replace_metadata_things\n        :return:"
  },
  {
    "code": "def get_pixel_thresholds_from_calibration_array(gdacs, calibration_gdacs, threshold_calibration_array, bounds_error=True):\n    if len(calibration_gdacs) != threshold_calibration_array.shape[2]:\n        raise ValueError('Length of the provided pixel GDACs does not match the third dimension of the calibration array')\n    interpolation = interp1d(x=calibration_gdacs, y=threshold_calibration_array, kind='slinear', bounds_error=bounds_error)\n    return interpolation(gdacs)",
    "docstring": "Calculates the threshold for all pixels in threshold_calibration_array at the given GDAC settings via linear interpolation. The GDAC settings used during calibration have to be given.\n\n    Parameters\n    ----------\n    gdacs : array like\n        The GDAC settings where the threshold should be determined from the calibration\n    calibration_gdacs : array like\n        GDAC settings used during calibration, needed to translate the index of the calibration array to a value.\n    threshold_calibration_array : numpy.array, shape=(80,336,# of GDACs during calibration)\n        The calibration array\n\n    Returns\n    -------\n    numpy.array, shape=(80,336,# gdacs given)\n        The threshold values for each pixel at gdacs."
  },
  {
    "code": "def store(self, addr, length=1, non_temporal=False):\n        if non_temporal:\n            raise ValueError(\"non_temporal stores are not yet supported\")\n        if addr is None:\n            return\n        elif not isinstance(addr, Iterable):\n            self.first_level.store(addr, length=length)\n        else:\n            self.first_level.iterstore(addr, length=length)",
    "docstring": "Store one or more adresses.\n\n        :param addr: byte address of store location\n        :param length: All address from addr until addr+length (exclusive) are\n                       stored (default: 1)\n        :param non_temporal: if True, no write-allocate will be issued, but cacheline will be zeroed"
  },
  {
    "code": "def singleton(cls):\n    import inspect\n    instances = {}\n    if cls.__init__ is not object.__init__:\n        argspec = inspect.getfullargspec(cls.__init__)\n        if len(argspec.args) != 1 or argspec.varargs or argspec.varkw:\n            raise TypeError(\"Singleton classes cannot accept arguments to the constructor.\")\n    def get_instance():\n        if cls not in instances:\n            instances[cls] = cls()\n        return instances[cls]\n    return get_instance",
    "docstring": "Decorator function that turns a class into a singleton."
  },
  {
    "code": "def _plan_on_valid_line(self, at_line, final_line_count):\n        if at_line == 1 or at_line == final_line_count:\n            return True\n        after_version = (\n            self._lines_seen[\"version\"]\n            and self._lines_seen[\"version\"][0] == 1\n            and at_line == 2\n        )\n        if after_version:\n            return True\n        return False",
    "docstring": "Check if a plan is on a valid line."
  },
  {
    "code": "def all(self, customer_id, data={}, **kwargs):\n        url = \"{}/{}/tokens\".format(self.base_url, customer_id)\n        return self.get_url(url, data, **kwargs)",
    "docstring": "Get all tokens for given customer Id\n\n        Args:\n            customer_id : Customer Id for which tokens have to be fetched\n\n        Returns:\n            Token dicts for given cutomer Id"
  },
  {
    "code": "def fit(self, p, x, y):\n        self.regression_model.fit(p, y)\n        ml_pred = self.regression_model.predict(p)\n        print('Finished learning regression model')\n        self.krige.fit(x=x, y=y - ml_pred)\n        print('Finished kriging residuals')",
    "docstring": "fit the regression method and also Krige the residual\n\n        Parameters\n        ----------\n        p: ndarray\n            (Ns, d) array of predictor variables (Ns samples, d dimensions)\n            for regression\n        x: ndarray\n            ndarray of (x, y) points. Needs to be a (Ns, 2) array\n            corresponding to the lon/lat, for example 2d regression kriging.\n            array of Points, (x, y, z) pairs of shape (N, 3) for 3d kriging\n        y: ndarray\n            array of targets (Ns, )"
  },
  {
    "code": "def proxy_model(self):\n        if self.category != Category.MODEL:\n            raise IllegalArgumentError(\"Part {} is not a model, therefore it cannot have a proxy model\".format(self))\n        if 'proxy' in self._json_data and self._json_data.get('proxy'):\n            catalog_model_id = self._json_data['proxy'].get('id')\n            return self._client.model(pk=catalog_model_id)\n        else:\n            raise NotFoundError(\"Part {} is not a proxy\".format(self.name))",
    "docstring": "Retrieve the proxy model of this proxied `Part` as a `Part`.\n\n        Allows you to retrieve the model of a proxy. But trying to get the catalog model of a part that\n        has no proxy, will raise an :exc:`NotFoundError`. Only models can have a proxy.\n\n        :return: :class:`Part` with category `MODEL` and from which the current part is proxied\n        :raises NotFoundError: When no proxy model is found\n\n        Example\n        -------\n\n        >>> proxy_part = project.model('Proxy based on catalog model')\n        >>> catalog_model_of_proxy_part = proxy_part.proxy_model()\n\n        >>> proxied_material_of_the_bolt_model = project.model('Bolt Material')\n        >>> proxy_basis_for_the_material_model = proxied_material_of_the_bolt_model.proxy_model()"
  },
  {
    "code": "def kalman_filter(points, noise):\n    kalman = ikalman.filter(noise)\n    for point in points:\n        kalman.update_velocity2d(point.lat, point.lon, point.dt)\n        (lat, lon) = kalman.get_lat_long()\n        point.lat = lat\n        point.lon = lon\n    return points",
    "docstring": "Smooths points with kalman filter\n\n    See https://github.com/open-city/ikalman\n\n    Args:\n        points (:obj:`list` of :obj:`Point`): points to smooth\n        noise (float): expected noise"
  },
  {
    "code": "def sample_stats_prior_to_xarray(self):\n        data = self.sample_stats_prior\n        if not isinstance(data, dict):\n            raise TypeError(\"DictConverter.sample_stats_prior is not a dictionary\")\n        return dict_to_dataset(data, library=None, coords=self.coords, dims=self.dims)",
    "docstring": "Convert sample_stats_prior samples to xarray."
  },
  {
    "code": "def expand_short_options(self, argv):\n        new_argv = []\n        for arg in argv:\n            result = self.parse_multi_short_option(arg)\n            new_argv.extend(result)\n        return new_argv",
    "docstring": "Convert grouped short options like `-abc` to `-a, -b, -c`.\n\n        This is necessary because we set ``allow_abbrev=False`` on the\n        ``ArgumentParser`` in :prop:`self.arg_parser`. The argparse docs\n        say ``allow_abbrev`` applies only to long options, but it also\n        affects whether short options grouped behind a single dash will\n        be parsed into multiple short options."
  },
  {
    "code": "def add_commands(self):\n        self.parser.add_argument(\n            '-d',\n            action=\"count\",\n            **self.config.default.debug.get_arg_parse_arguments())",
    "docstring": "You can override this method in order to add your command line\n        arguments to the argparse parser. The configuration file  was\n        reloaded at this time."
  },
  {
    "code": "def set_state_options(self, left_add_options=None, left_remove_options=None, right_add_options=None, right_remove_options=None):\n        s_right = self.project.factory.full_init_state(\n            add_options=right_add_options, remove_options=right_remove_options,\n            args=[],\n        )\n        s_left = self.project.factory.full_init_state(\n            add_options=left_add_options, remove_options=left_remove_options,\n            args=[],\n        )\n        return self.set_states(s_left, s_right)",
    "docstring": "Checks that the specified state options result in the same states over the next `depth` states."
  },
  {
    "code": "def key(self, frame):\n        \"Return the sort key for the given frame.\"\n        def keytuple(primary):\n            if frame.frameno is None:\n                return (primary, 1)\n            return (primary, 0, frame.frameno)\n        if type(frame) in self.frame_keys:\n            return keytuple(self.frame_keys[type(frame)])\n        if frame._in_version(2) and type(frame).__bases__[0] in self.frame_keys:\n            return keytuple(self.frame_keys[type(frame).__bases__[0]])\n        for (pattern, key) in self.re_keys:\n            if re.match(pattern, frame.frameid):\n                return keytuple(key)\n        return keytuple(self.unknown_key)",
    "docstring": "Return the sort key for the given frame."
  },
  {
    "code": "def _validate_flushed(self) -> None:\n        journal_diff = self._journal_storage.diff()\n        if len(journal_diff) > 0:\n            raise ValidationError(\n                \"StorageDB had a dirty journal when it needed to be clean: %r\" % journal_diff\n            )",
    "docstring": "Will raise an exception if there are some changes made since the last persist."
  },
  {
    "code": "def get_covariance_table(self, chain=0, parameters=None, caption=\"Parameter Covariance\",\n                              label=\"tab:parameter_covariance\"):\n        parameters, cov = self.get_covariance(chain=chain, parameters=parameters)\n        return self._get_2d_latex_table(parameters, cov, caption, label)",
    "docstring": "Gets a LaTeX table of parameter covariance.\n\n        Parameters\n        ----------\n        chain : int|str, optional\n            The chain index or name. Defaults to first chain.\n        parameters : list[str], optional\n            The list of parameters to compute correlations. Defaults to all parameters\n            for the given chain.\n        caption : str, optional\n            The LaTeX table caption.\n        label : str, optional\n            The LaTeX table label.\n\n        Returns\n        -------\n            str\n                The LaTeX table ready to go!"
  },
  {
    "code": "def combine(self, other, name=None):\n    return PhaseGroup(\n        setup=self.setup + other.setup,\n        main=self.main + other.main,\n        teardown=self.teardown + other.teardown,\n        name=name)",
    "docstring": "Combine with another PhaseGroup and return the result."
  },
  {
    "code": "def reboot(self):\n        token = self.get_token()\n        self.bbox_auth.set_access(BboxConstant.AUTHENTICATION_LEVEL_PRIVATE, BboxConstant.AUTHENTICATION_LEVEL_PRIVATE)\n        url_suffix = \"reboot?btoken={}\".format(token)\n        self.bbox_url.set_api_name(BboxConstant.API_DEVICE, url_suffix)\n        api = BboxApiCall(self.bbox_url, BboxConstant.HTTP_METHOD_POST, None,\n                          self.bbox_auth)\n        api.execute_api_request()",
    "docstring": "Reboot the device\n        Useful when trying to get xDSL sync"
  },
  {
    "code": "def get_temp_export_dir(timestamped_export_dir):\n  (dirname, basename) = os.path.split(timestamped_export_dir)\n  temp_export_dir = os.path.join(\n      tf.compat.as_bytes(dirname),\n      tf.compat.as_bytes(\"temp-{}\".format(basename)))\n  return temp_export_dir",
    "docstring": "Builds a directory name based on the argument but starting with 'temp-'.\n\n  This relies on the fact that TensorFlow Serving ignores subdirectories of\n  the base directory that can't be parsed as integers.\n\n  Args:\n    timestamped_export_dir: the name of the eventual export directory, e.g.\n      /foo/bar/<timestamp>\n\n  Returns:\n    A sister directory prefixed with 'temp-', e.g. /foo/bar/temp-<timestamp>."
  },
  {
    "code": "def setup(app):\n    app.add_config_value('sphinxmark_enable', False, 'html')\n    app.add_config_value('sphinxmark_div', 'default', 'html')\n    app.add_config_value('sphinxmark_border', None, 'html')\n    app.add_config_value('sphinxmark_repeat', True, 'html')\n    app.add_config_value('sphinxmark_fixed', False, 'html')\n    app.add_config_value('sphinxmark_image', 'default', 'html')\n    app.add_config_value('sphinxmark_text', 'default', 'html')\n    app.add_config_value('sphinxmark_text_color', (255, 0, 0), 'html')\n    app.add_config_value('sphinxmark_text_size', 100, 'html')\n    app.add_config_value('sphinxmark_text_width', 1000, 'html')\n    app.add_config_value('sphinxmark_text_opacity', 20, 'html')\n    app.add_config_value('sphinxmark_text_spacing', 400, 'html')\n    app.add_config_value('sphinxmark_text_rotation', 0, 'html')\n    app.connect('env-updated', watermark)\n    return {\n        'version': '0.1.18',\n        'parallel_read_safe': True,\n        'parallel_write_safe': True,\n    }",
    "docstring": "Configure setup for Sphinx extension.\n\n    :param app: Sphinx application context."
  },
  {
    "code": "def _table_union(left, right, distinct=False):\n    op = ops.Union(left, right, distinct=distinct)\n    return op.to_expr()",
    "docstring": "Form the table set union of two table expressions having identical\n    schemas.\n\n    Parameters\n    ----------\n    right : TableExpr\n    distinct : boolean, default False\n        Only union distinct rows not occurring in the calling table (this\n        can be very expensive, be careful)\n\n    Returns\n    -------\n    union : TableExpr"
  },
  {
    "code": "def publish_message(self, message, expire=None):\n        if expire is None:\n            expire = self._expire\n        if not isinstance(message, RedisMessage):\n            raise ValueError('message object is not of type RedisMessage')\n        for channel in self._publishers:\n            self._connection.publish(channel, message)\n            if expire > 0:\n                self._connection.setex(channel, expire, message)",
    "docstring": "Publish a ``message`` on the subscribed channel on the Redis datastore.\n        ``expire`` sets the time in seconds, on how long the message shall additionally of being\n        published, also be persisted in the Redis datastore. If unset, it defaults to the\n        configuration settings ``WS4REDIS_EXPIRE``."
  },
  {
    "code": "def fetch(opts):\n    resources = _load(opts.resources, opts.output_dir)\n    if opts.all:\n        opts.resource_names = ALL\n    reporthook = None if opts.quiet else lambda name: print('Fetching {}...'.format(name))\n    if opts.verbose:\n        backend.VERBOSE = True\n    _fetch(resources, opts.resource_names, opts.mirror_url, opts.force, reporthook)\n    return verify(opts)",
    "docstring": "Create a local mirror of one or more resources."
  },
  {
    "code": "def can_claim_fifty_moves(self) -> bool:\n        if self.halfmove_clock >= 100:\n            if any(self.generate_legal_moves()):\n                return True\n        return False",
    "docstring": "Draw by the fifty-move rule can be claimed once the clock of halfmoves\n        since the last capture or pawn move becomes equal or greater to 100\n        and the side to move still has a legal move they can make."
  },
  {
    "code": "def String(length=None, **kwargs):\n    return Property(\n        length=length,\n        types=stringy_types,\n        convert=to_string,\n        **kwargs\n    )",
    "docstring": "A string valued property with max. `length`."
  },
  {
    "code": "def key(state, host, key=None, keyserver=None, keyid=None):\n    if key:\n        if urlparse(key).scheme:\n            yield 'wget -O- {0} | apt-key add -'.format(key)\n        else:\n            yield 'apt-key add {0}'.format(key)\n    if keyserver and keyid:\n        yield 'apt-key adv --keyserver {0} --recv-keys {1}'.format(keyserver, keyid)",
    "docstring": "Add apt gpg keys with ``apt-key``.\n\n    + key: filename or URL\n    + keyserver: URL of keyserver to fetch key from\n    + keyid: key identifier when using keyserver\n\n    Note:\n        Always returns an add command, not state checking.\n\n    keyserver/id:\n        These must be provided together."
  },
  {
    "code": "def _call_variants(example_dir, region_bed, data, out_file):\n    tf_out_file = \"%s-tfrecord.gz\" % utils.splitext_plus(out_file)[0]\n    if not utils.file_exists(tf_out_file):\n        with file_transaction(data, tf_out_file) as tx_out_file:\n            model = \"wes\" if strelka2.coverage_interval_from_bed(region_bed) == \"targeted\" else \"wgs\"\n            cmd = [\"dv_call_variants.py\", \"--cores\", dd.get_num_cores(data),\n                   \"--outfile\", tx_out_file, \"--examples\", example_dir,\n                   \"--sample\", dd.get_sample_name(data), \"--model\", model]\n            do.run(cmd, \"DeepVariant call_variants %s\" % dd.get_sample_name(data))\n    return tf_out_file",
    "docstring": "Call variants from prepared pileup examples, creating tensorflow record file."
  },
  {
    "code": "def peak_generation(self, mode):\n        if mode == 'MV':\n            return sum([_.capacity for _ in self.grid.generators()])\n        elif mode == 'MVLV':\n            cum_mv_peak_generation = sum([_.capacity for _ in self.grid.generators()])\n            cum_lv_peak_generation = 0\n            for load_area in self.grid.grid_district.lv_load_areas():\n                cum_lv_peak_generation += load_area.peak_generation\n            return cum_mv_peak_generation + cum_lv_peak_generation\n        else:\n            raise ValueError('parameter \\'mode\\' is invalid!')",
    "docstring": "Calculates cumulative peak generation of generators connected to underlying grids\n        \n        This is done instantaneously using bottom-up approach.\n\n        Parameters\n        ----------\n        mode: str\n            determines which generators are included::\n\n            'MV':   Only generation capacities of MV level are considered.\n            \n            'MVLV': Generation capacities of MV and LV are considered\n                    (= cumulative generation capacities in entire MVGD).\n\n        Returns\n        -------\n        float\n            Cumulative peak generation"
  },
  {
    "code": "def _untrack_tendril(self, tendril):\n        try:\n            del self.tendrils[tendril._tendril_key]\n        except KeyError:\n            pass\n        try:\n            del self._tendrils[tendril.proto][tendril._tendril_key]\n        except KeyError:\n            pass",
    "docstring": "Removes the tendril from the set of tracked tendrils."
  },
  {
    "code": "def _get_predicton_csv_lines(data, headers, images):\n  if images:\n    data = copy.deepcopy(data)\n    for img_col in images:\n      for d, im in zip(data, images[img_col]):\n        if im == '':\n          continue\n        im = im.copy()\n        im.thumbnail((299, 299), Image.ANTIALIAS)\n        buf = BytesIO()\n        im.save(buf, \"JPEG\")\n        content = base64.urlsafe_b64encode(buf.getvalue()).decode('ascii')\n        d[img_col] = content\n  csv_lines = []\n  for d in data:\n    buf = six.StringIO()\n    writer = csv.DictWriter(buf, fieldnames=headers, lineterminator='')\n    writer.writerow(d)\n    csv_lines.append(buf.getvalue())\n  return csv_lines",
    "docstring": "Create CSV lines from list-of-dict data."
  },
  {
    "code": "def decide(self, package):\n        if self._backtracking:\n            self._attempted_solutions += 1\n        self._backtracking = False\n        self._decisions[package.name] = package\n        self._assign(\n            Assignment.decision(package, self.decision_level, len(self._assignments))\n        )",
    "docstring": "Adds an assignment of package as a decision\n        and increments the decision level."
  },
  {
    "code": "def _set_schedules(self):\n        self.schedules = ['ReturnHeader990x', ]\n        self.otherforms = []\n        for sked in self.raw_irs_dict['Return']['ReturnData'].keys():\n            if not sked.startswith(\"@\"):\n                if sked in KNOWN_SCHEDULES:\n                    self.schedules.append(sked)\n                else:\n                    self.otherforms.append(sked)",
    "docstring": "Attach the known and unknown schedules"
  },
  {
    "code": "def chi_squareds(self, p=None):\n        if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None\n        if p is None: p = self.results[0]\n        rs = self.studentized_residuals(p)\n        if rs == None: return None\n        cs = []\n        for r in rs: cs.append(sum(r**2))\n        return cs",
    "docstring": "Returns a list of chi squared for each data set. Also uses ydata_massaged.\n\n        p=None means use the fit results"
  },
  {
    "code": "def AddXrefFrom(self, ref_kind, classobj, methodobj, offset):\n        self.xreffrom[classobj].add((ref_kind, methodobj, offset))",
    "docstring": "Creates a crossreference from this class.\n        XrefFrom means, that the current class is called by another class.\n\n        :param REF_TYPE ref_kind: type of call\n        :param classobj: :class:`ClassAnalysis` object to link\n        :param methodobj:\n        :param offset: Offset in the methods bytecode, where the call happens\n        :return:"
  },
  {
    "code": "def streaming_command(self, command, raw=False, timeout_ms=None):\n    if raw:\n      command = self._to_raw_command(command)\n    return self.adb_connection.streaming_command('shell', command, timeout_ms)",
    "docstring": "Run the given command and yield the output as we receive it."
  },
  {
    "code": "def g_step(self, gen_frames, fake_logits_stop):\n    hparam_to_gen_loss = {\n        \"least_squares\": gan_losses.least_squares_generator_loss,\n        \"cross_entropy\": gan_losses.modified_generator_loss,\n        \"wasserstein\": gan_losses.wasserstein_generator_loss\n    }\n    fake_logits = self.discriminator(gen_frames)\n    mean_fake_logits = tf.reduce_mean(fake_logits)\n    tf.summary.scalar(\"mean_fake_logits\", mean_fake_logits)\n    generator_loss_func = hparam_to_gen_loss[self.hparams.gan_loss]\n    gan_g_loss_pos_d = generator_loss_func(\n        discriminator_gen_outputs=fake_logits, add_summaries=True)\n    gan_g_loss_neg_d = -generator_loss_func(\n        discriminator_gen_outputs=fake_logits_stop, add_summaries=True)\n    return gan_g_loss_pos_d, gan_g_loss_neg_d",
    "docstring": "Performs the generator step in computing the GAN loss.\n\n    Args:\n      gen_frames: Generated frames\n      fake_logits_stop: Logits corresponding to the generated frames as per\n                        the discriminator. Assumed to have a stop-gradient term.\n    Returns:\n      gan_g_loss_pos_d: Loss.\n      gan_g_loss_neg_d: -gan_g_loss_pos_d but with a stop gradient on generator."
  },
  {
    "code": "def instagram_config(self, id, secret, scope=None, **_):\n        scope = scope if scope else 'basic'\n        token_params = dict(scope=scope)\n        config = dict(\n            access_token_url='/oauth/access_token/',\n            authorize_url='/oauth/authorize/',\n            base_url='https://api.instagram.com/',\n            consumer_key=id,\n            consumer_secret=secret,\n            request_token_params=token_params\n        )\n        return config",
    "docstring": "Get config dictionary for instagram oauth"
  },
  {
    "code": "def run_algorithm(start,\n                  end,\n                  initialize,\n                  capital_base,\n                  handle_data=None,\n                  before_trading_start=None,\n                  analyze=None,\n                  data_frequency='daily',\n                  bundle='quantopian-quandl',\n                  bundle_timestamp=None,\n                  trading_calendar=None,\n                  metrics_set='default',\n                  benchmark_returns=None,\n                  default_extension=True,\n                  extensions=(),\n                  strict_extensions=True,\n                  environ=os.environ,\n                  blotter='default'):\n    load_extensions(default_extension, extensions, strict_extensions, environ)\n    return _run(\n        handle_data=handle_data,\n        initialize=initialize,\n        before_trading_start=before_trading_start,\n        analyze=analyze,\n        algofile=None,\n        algotext=None,\n        defines=(),\n        data_frequency=data_frequency,\n        capital_base=capital_base,\n        bundle=bundle,\n        bundle_timestamp=bundle_timestamp,\n        start=start,\n        end=end,\n        output=os.devnull,\n        trading_calendar=trading_calendar,\n        print_algo=False,\n        metrics_set=metrics_set,\n        local_namespace=False,\n        environ=environ,\n        blotter=blotter,\n        benchmark_returns=benchmark_returns,\n    )",
    "docstring": "Run a trading algorithm.\n\n    Parameters\n    ----------\n    start : datetime\n        The start date of the backtest.\n    end : datetime\n        The end date of the backtest..\n    initialize : callable[context -> None]\n        The initialize function to use for the algorithm. This is called once\n        at the very begining of the backtest and should be used to set up\n        any state needed by the algorithm.\n    capital_base : float\n        The starting capital for the backtest.\n    handle_data : callable[(context, BarData) -> None], optional\n        The handle_data function to use for the algorithm. This is called\n        every minute when ``data_frequency == 'minute'`` or every day\n        when ``data_frequency == 'daily'``.\n    before_trading_start : callable[(context, BarData) -> None], optional\n        The before_trading_start function for the algorithm. This is called\n        once before each trading day (after initialize on the first day).\n    analyze : callable[(context, pd.DataFrame) -> None], optional\n        The analyze function to use for the algorithm. This function is called\n        once at the end of the backtest and is passed the context and the\n        performance data.\n    data_frequency : {'daily', 'minute'}, optional\n        The data frequency to run the algorithm at.\n    bundle : str, optional\n        The name of the data bundle to use to load the data to run the backtest\n        with. This defaults to 'quantopian-quandl'.\n    bundle_timestamp : datetime, optional\n        The datetime to lookup the bundle data for. This defaults to the\n        current time.\n    trading_calendar : TradingCalendar, optional\n        The trading calendar to use for your backtest.\n    metrics_set : iterable[Metric] or str, optional\n        The set of metrics to compute in the simulation. If a string is passed,\n        resolve the set with :func:`zipline.finance.metrics.load`.\n    default_extension : bool, optional\n        Should the default zipline extension be loaded. This is found at\n        ``$ZIPLINE_ROOT/extension.py``\n    extensions : iterable[str], optional\n        The names of any other extensions to load. Each element may either be\n        a dotted module path like ``a.b.c`` or a path to a python file ending\n        in ``.py`` like ``a/b/c.py``.\n    strict_extensions : bool, optional\n        Should the run fail if any extensions fail to load. If this is false,\n        a warning will be raised instead.\n    environ : mapping[str -> str], optional\n        The os environment to use. Many extensions use this to get parameters.\n        This defaults to ``os.environ``.\n    blotter : str or zipline.finance.blotter.Blotter, optional\n        Blotter to use with this algorithm. If passed as a string, we look for\n        a blotter construction function registered with\n        ``zipline.extensions.register`` and call it with no parameters.\n        Default is a :class:`zipline.finance.blotter.SimulationBlotter` that\n        never cancels orders.\n\n    Returns\n    -------\n    perf : pd.DataFrame\n        The daily performance of the algorithm.\n\n    See Also\n    --------\n    zipline.data.bundles.bundles : The available data bundles."
  },
  {
    "code": "def change_type(self, cls):\n        target_type = cls._type\n        target = self._embedded.createInstance(target_type)\n        self._embedded.setDiagram(target)\n        return cls(target)",
    "docstring": "Change type of diagram in this chart.\n\n        Accepts one of classes which extend Diagram."
  },
  {
    "code": "def join_channel(self, channel, key=None, tags=None):\n        params = [channel]\n        if key:\n            params.append(key)\n        self.send('JOIN', params=params, tags=tags)",
    "docstring": "Join the given channel."
  },
  {
    "code": "def send(self, load, tries=None, timeout=None, raw=False):\n        if 'cmd' not in load:\n            log.error('Malformed request, no cmd: %s', load)\n            return {}\n        cmd = load['cmd'].lstrip('_')\n        if cmd in self.cmd_stub:\n            return self.cmd_stub[cmd]\n        if not hasattr(self.fs, cmd):\n            log.error('Malformed request, invalid cmd: %s', load)\n            return {}\n        return getattr(self.fs, cmd)(load)",
    "docstring": "Emulate the channel send method, the tries and timeout are not used"
  },
  {
    "code": "def construct_func_expr(n):\n    op = n[0]\n    if op.startswith('_') and op.endswith('_'):\n        op = op.strip('_')\n        if op == 'var':\n            return Var(str(n[1]))\n        elif op == 'literal':\n            if isinstance(n[1], basestring):\n                raise \"not implemented\"\n            return Constant(n[1])\n        elif op == 'cast':\n            raise \"not implemented\"\n    elif op in '+-/*':\n        return ArithErrFunc(op, *map(construct_func_expr,n[1:]))\n    else:\n        klass = __agg2f__.get(op, None)\n        if klass:\n            return klass(map(construct_func_expr, n[1:]))\n        raise \"no klass\"",
    "docstring": "construct the function expression"
  },
  {
    "code": "def wait(self, timeout=None):\n        us = -1 if timeout is None else int(timeout * 1000000)\n        return super(Reader, self).wait(us)",
    "docstring": "Wait for a change in the journal.\n\n        `timeout` is the maximum time in seconds to wait, or None which\n        means to wait forever.\n\n        Returns one of NOP (no change), APPEND (new entries have been added to\n        the end of the journal), or INVALIDATE (journal files have been added or\n        removed)."
  },
  {
    "code": "def _get_symmetry(self):\n        d = spglib.get_symmetry(self._cell, symprec=self._symprec,\n                                angle_tolerance=self._angle_tol)\n        trans = []\n        for t in d[\"translations\"]:\n            trans.append([float(Fraction.from_float(c).limit_denominator(1000))\n                          for c in t])\n        trans = np.array(trans)\n        trans[np.abs(trans) == 1] = 0\n        return d[\"rotations\"], trans",
    "docstring": "Get the symmetry operations associated with the structure.\n\n        Returns:\n            Symmetry operations as a tuple of two equal length sequences.\n            (rotations, translations). \"rotations\" is the numpy integer array\n            of the rotation matrices for scaled positions\n            \"translations\" gives the numpy float64 array of the translation\n            vectors in scaled positions."
  },
  {
    "code": "def blit_2x(\n        self,\n        console: tcod.console.Console,\n        dest_x: int,\n        dest_y: int,\n        img_x: int = 0,\n        img_y: int = 0,\n        img_width: int = -1,\n        img_height: int = -1,\n    ) -> None:\n        lib.TCOD_image_blit_2x(\n            self.image_c,\n            _console(console),\n            dest_x,\n            dest_y,\n            img_x,\n            img_y,\n            img_width,\n            img_height,\n        )",
    "docstring": "Blit onto a Console with double resolution.\n\n        Args:\n            console (Console): Blit destination Console.\n            dest_x (int): Console tile X position starting from the left at 0.\n            dest_y (int): Console tile Y position starting from the top at 0.\n            img_x (int): Left corner pixel of the Image to blit\n            img_y (int): Top corner pixel of the Image to blit\n            img_width (int): Width of the Image to blit.\n                             Use -1 for the full Image width.\n            img_height (int): Height of the Image to blit.\n                              Use -1 for the full Image height."
  },
  {
    "code": "def lookup(self, key):\n        values = self.filter(lambda kv: kv[0] == key).values()\n        if self.partitioner is not None:\n            return self.ctx.runJob(values, lambda x: x, [self.partitioner(key)])\n        return values.collect()",
    "docstring": "Return the list of values in the RDD for key `key`. This operation\n        is done efficiently if the RDD has a known partitioner by only\n        searching the partition that the key maps to.\n\n        >>> l = range(1000)\n        >>> rdd = sc.parallelize(zip(l, l), 10)\n        >>> rdd.lookup(42)  # slow\n        [42]\n        >>> sorted = rdd.sortByKey()\n        >>> sorted.lookup(42)  # fast\n        [42]\n        >>> sorted.lookup(1024)\n        []\n        >>> rdd2 = sc.parallelize([(('a', 'b'), 'c')]).groupByKey()\n        >>> list(rdd2.lookup(('a', 'b'))[0])\n        ['c']"
  },
  {
    "code": "def anchor(self):\n        anchor = self._subtotal_dict[\"anchor\"]\n        try:\n            anchor = int(anchor)\n            if anchor not in self.valid_elements.element_ids:\n                return \"bottom\"\n            return anchor\n        except (TypeError, ValueError):\n            return anchor.lower()",
    "docstring": "int or str indicating element under which to insert this subtotal.\n\n        An int anchor is the id of the dimension element (category or\n        subvariable) under which to place this subtotal. The return value can\n        also be one of 'top' or 'bottom'.\n\n        The return value defaults to 'bottom' for an anchor referring to an\n        element that is no longer present in the dimension or an element that\n        represents missing data."
  },
  {
    "code": "def as_coeff_unit(self):\n        coeff, mul = self.expr.as_coeff_Mul()\n        coeff = float(coeff)\n        ret = Unit(\n            mul,\n            self.base_value / coeff,\n            self.base_offset,\n            self.dimensions,\n            self.registry,\n        )\n        return coeff, ret",
    "docstring": "Factor the coefficient multiplying a unit\n\n        For units that are multiplied by a constant dimensionless\n        coefficient, returns a tuple containing the coefficient and\n        a new unit object for the unmultiplied unit.\n\n        Example\n        -------\n\n        >>> import unyt as u\n        >>> unit = (u.m**2/u.cm).simplify()\n        >>> unit\n        100*m\n        >>> unit.as_coeff_unit()\n        (100.0, m)"
  },
  {
    "code": "def push(self, filename, data):\n        self._queue.put(Chunk(filename, data))",
    "docstring": "Push a chunk of a file to the streaming endpoint.\n\n        Args:\n            filename: Name of file that this is a chunk of.\n            chunk_id: TODO: change to 'offset'\n            chunk: File data."
  },
  {
    "code": "def set_terminal_width(self, command=\"\", delay_factor=1):\n        if not command:\n            return \"\"\n        delay_factor = self.select_delay_factor(delay_factor)\n        command = self.normalize_cmd(command)\n        self.write_channel(command)\n        output = self.read_until_prompt()\n        if self.ansi_escape_codes:\n            output = self.strip_ansi_escape_codes(output)\n        return output",
    "docstring": "CLI terminals try to automatically adjust the line based on the width of the terminal.\n        This causes the output to get distorted when accessed programmatically.\n\n        Set terminal width to 511 which works on a broad set of devices.\n\n        :param command: Command string to send to the device\n        :type command: str\n\n        :param delay_factor: See __init__: global_delay_factor\n        :type delay_factor: int"
  },
  {
    "code": "def generate_string(self, initial_logits, initial_state, sequence_length):\n    current_logits = initial_logits\n    current_state = initial_state\n    generated_letters = []\n    for _ in range(sequence_length):\n      char_index = tf.squeeze(tf.multinomial(current_logits, 1))\n      char_one_hot = tf.one_hot(char_index, self._output_size, 1.0, 0.0)\n      generated_letters.append(char_one_hot)\n      gen_out_seq, current_state = self._core(\n          tf.nn.relu(self._embed_module(char_one_hot)),\n          current_state)\n      current_logits = self._output_module(gen_out_seq)\n    generated_string = tf.stack(generated_letters)\n    return generated_string",
    "docstring": "Builds sub-graph to generate a string, sampled from the model.\n\n    Args:\n      initial_logits: Starting logits to sample from.\n      initial_state: Starting state for the RNN core.\n      sequence_length: Number of characters to sample.\n\n    Returns:\n      A Tensor of characters, with dimensions `[sequence_length, batch_size,\n      output_size]`."
  },
  {
    "code": "def threeprime_plot(self):\n        data = dict()\n        dict_to_add = dict()\n        for key in self.threepGtoAfreq_data:\n            pos = list(range(1,len(self.threepGtoAfreq_data.get(key))))\n            tmp = [i * 100.0 for i in self.threepGtoAfreq_data.get(key)]\n            tuples = list(zip(pos,tmp))\n            data = dict((x, y) for x, y in tuples)\n            dict_to_add[key] = data\n        config = {\n            'id': 'threeprime_misinc_plot',\n            'title': 'DamageProfiler: 3P G>A misincorporation plot',\n            'ylab': '% G to A substituted',\n            'xlab': 'Nucleotide position from 3\\'',\n            'tt_label': '{point.y:.2f} % G>A misincorporations at nucleotide position {point.x}',\n            'ymin': 0,\n            'xmin': 1\n        }\n        return linegraph.plot(dict_to_add,config)",
    "docstring": "Generate a 3' G>A linegraph plot"
  },
  {
    "code": "def set_constants(self, *constants, verbose=True):\n        new = []\n        current = {c.expression: c for c in self._constants}\n        for expression in constants:\n            constant = current.get(expression, Constant(self, expression))\n            new.append(constant)\n        self._constants = new\n        for c in self._constants:\n            if c.units is None:\n                c.convert(c.variables[0].units)\n        self.flush()\n        self._on_constants_updated()",
    "docstring": "Set the constants associated with the data.\n\n        Parameters\n        ----------\n        constants : str\n            Expressions for the new set of constants.\n        verbose : boolean (optional)\n            Toggle talkback. Default is True\n\n        See Also\n        --------\n        transform\n            Similar method except for axes.\n        create_constant\n            Add an individual constant.\n        remove_constant\n            Remove an individual constant."
  },
  {
    "code": "def _execute(self, worker):\n        self._assert_status_is(TaskStatus.RUNNING)\n        operation = worker.look_up(self.operation)\n        operation.invoke(self, [], worker=worker)",
    "docstring": "This method is ASSIGNED during the evaluation to control how to resume it once it has been paused"
  },
  {
    "code": "def _load_maps_by_type(map_type):\n    seq_maps = COLOR_MAPS[map_type]\n    loaded_maps = {}\n    for map_name in seq_maps:\n        loaded_maps[map_name] = {}\n        for num in seq_maps[map_name]:\n            inum = int(num)\n            colors = seq_maps[map_name][num]['Colors']\n            bmap = BrewerMap(map_name, map_type, colors)\n            loaded_maps[map_name][inum] = bmap\n        max_num = int(max(seq_maps[map_name].keys(), key=int))\n        loaded_maps[map_name]['max'] = loaded_maps[map_name][max_num]\n    return loaded_maps",
    "docstring": "Load all maps of a given type into a dictionary.\n\n    Color maps are loaded as BrewerMap objects. Dictionary is\n    keyed by map name and then integer numbers of defined\n    colors. There is an additional 'max' key that points to the\n    color map with the largest number of defined colors.\n\n    Parameters\n    ----------\n    map_type : {'Sequential', 'Diverging', 'Qualitative'}\n\n    Returns\n    -------\n    maps : dict of BrewerMap"
  },
  {
    "code": "def apply_args(self, **kwargs):\n        def apply_format(node):\n            if isinstance(node, PathParam):\n                return PathParam(node.name.format(**kwargs), node.type, node.type_args)\n            else:\n                return node\n        return UrlPath(*(apply_format(n) for n in self._nodes))",
    "docstring": "Apply formatting to each path node.\n\n        This is used to apply a name to nodes (used to apply key names) eg:\n\n        >>> a = UrlPath(\"foo\", PathParam('{key_field}'), \"bar\")\n        >>> b = a.apply_args(id=\"item_id\")\n        >>> b.format()\n        'foo/{item_id}/bar'"
  },
  {
    "code": "def update_refobj(self, old, new, reftrack):\n        if old:\n            del self._parentsearchdict[old]\n        if new:\n            self._parentsearchdict[new] = reftrack",
    "docstring": "Update the parent search dict so that the reftrack can be found\n        with the new refobj and delete the entry for the old refobj.\n\n        Old or new can also be None.\n\n        :param old: the old refobj of reftrack\n        :param new: the new refobj of reftrack\n        :param reftrack: The reftrack, which refobj was updated\n        :type reftrack: :class:`Reftrack`\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def list_(name, add, match, stamp=False, prune=0):\n    ret = {'name': name,\n           'changes': {},\n           'comment': '',\n           'result': True}\n    if not isinstance(add, list):\n        add = add.split(',')\n    if name not in __reg__:\n        __reg__[name] = {}\n        __reg__[name]['val'] = []\n    for event in __events__:\n        try:\n            event_data = event['data']['data']\n        except KeyError:\n            event_data = event['data']\n        if salt.utils.stringutils.expr_match(event['tag'], match):\n            item = {}\n            for key in add:\n                if key in event_data:\n                    item[key] = event_data[key]\n                    if stamp is True:\n                        item['time'] = event['data']['_stamp']\n            __reg__[name]['val'].append(item)\n    if prune > 0:\n        __reg__[name]['val'] = __reg__[name]['val'][:prune]\n    return ret",
    "docstring": "Add the specified values to the named list\n\n    If ``stamp`` is True, then the timestamp from the event will also be added\n    if ``prune`` is set to an integer higher than ``0``, then only the last\n    ``prune`` values will be kept in the list.\n\n    USAGE:\n\n    .. code-block:: yaml\n\n        foo:\n          reg.list:\n            - add: bar\n            - match: my/custom/event\n            - stamp: True"
  },
  {
    "code": "def replacePassword(self, currentPassword, newPassword):\n        if unicode(currentPassword) != self.password:\n            return fail(BadCredentials())\n        return self.setPassword(newPassword)",
    "docstring": "Set this account's password if the current password matches.\n\n        @param currentPassword: The password to match against the current one.\n        @param newPassword: The new password.\n\n        @return: A deferred firing when the password has been changed.\n        @raise BadCredentials: If the current password did not match."
  },
  {
    "code": "def splits(cls, exts, fields, root='.data',\n               train='train', validation='val', test='test2016', **kwargs):\n        if 'path' not in kwargs:\n            expected_folder = os.path.join(root, cls.name)\n            path = expected_folder if os.path.exists(expected_folder) else None\n        else:\n            path = kwargs['path']\n            del kwargs['path']\n        return super(Multi30k, cls).splits(\n            exts, fields, path, root, train, validation, test, **kwargs)",
    "docstring": "Create dataset objects for splits of the Multi30k dataset.\n\n        Arguments:\n            exts: A tuple containing the extension to path for each language.\n            fields: A tuple containing the fields that will be used for data\n                in each language.\n            root: Root dataset storage directory. Default is '.data'.\n            train: The prefix of the train data. Default: 'train'.\n            validation: The prefix of the validation data. Default: 'val'.\n            test: The prefix of the test data. Default: 'test'.\n            Remaining keyword arguments: Passed to the splits method of\n                Dataset."
  },
  {
    "code": "def cmd_signing_key(self, args):\n        if len(args) == 0:\n            print(\"usage: signing setup passphrase\")\n            return\n        if not self.master.mavlink20():\n            print(\"You must be using MAVLink2 for signing\")\n            return\n        passphrase = args[0]\n        key = self.passphrase_to_key(passphrase)\n        self.master.setup_signing(key, sign_outgoing=True, allow_unsigned_callback=self.allow_unsigned)\n        print(\"Setup signing key\")",
    "docstring": "set signing key on connection"
  },
  {
    "code": "def extract_header_comment_key_value_tuples_from_file(file_descriptor):\n    file_data = file_descriptor.read()\n    findall_result = re.findall(HEADER_COMMENT_KEY_VALUE_TUPLES_REGEX, file_data, re.MULTILINE | re.DOTALL)\n    returned_list = []\n    for header_comment, _ignored, raw_comments, key, value in findall_result:\n        comments = re.findall(\"/\\* (.*?) \\*/\", raw_comments)\n        if len(comments) == 0:\n            comments = [u\"\"]\n        returned_list.append((header_comment, comments, key, value))\n    return returned_list",
    "docstring": "Extracts tuples representing comments and localization entries from strings file.\n\n    Args:\n        file_descriptor (file): The file to read the tuples from\n\n    Returns:\n        list : List of tuples representing the headers and localization entries."
  },
  {
    "code": "def export_batch(self):\n        batch = self.batch_cls(\n            model=self.model, history_model=self.history_model, using=self.using\n        )\n        if batch.items:\n            try:\n                json_file = self.json_file_cls(batch=batch, path=self.path)\n                json_file.write()\n            except JSONDumpFileError as e:\n                raise TransactionExporterError(e)\n            batch.close()\n            return batch\n        return None",
    "docstring": "Returns a batch instance after exporting a batch of txs."
  },
  {
    "code": "def nhapDaiHan(self, cucSo, gioiTinh):\n        for cung in self.thapNhiCung:\n            khoangCach = khoangCachCung(cung.cungSo, self.cungMenh, gioiTinh)\n            cung.daiHan(cucSo + khoangCach * 10)\n        return self",
    "docstring": "Nhap dai han\n\n        Args:\n            cucSo (TYPE): Description\n            gioiTinh (TYPE): Description\n\n        Returns:\n            TYPE: Description"
  },
  {
    "code": "def read(self) -> None:\n        try:\n            with netcdf4.Dataset(self.filepath, \"r\") as ncfile:\n                timegrid = query_timegrid(ncfile)\n                for variable in self.variables.values():\n                    variable.read(ncfile, timegrid)\n        except BaseException:\n            objecttools.augment_excmessage(\n                f'While trying to read data from NetCDF file `{self.filepath}`')",
    "docstring": "Open an existing NetCDF file temporarily and call method\n        |NetCDFVariableDeep.read| of all handled |NetCDFVariableBase|\n        objects."
  },
  {
    "code": "def _create_socket(self):\n        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        s = ssl.wrap_socket(s)\n        s.connect((self.host, self.__port))\n        s.settimeout(self.timeout)\n        return s",
    "docstring": "Creates ssl socket, connects to stream api and\n        sets timeout."
  },
  {
    "code": "def handle_status(self):\n        status = self.get_status()\n        if status:\n            self.zones['main'].update_status(status)",
    "docstring": "Handle status from device"
  },
  {
    "code": "def absorption_coefficient( dielectric ):\n    energies_in_eV = np.array( dielectric[0] )\n    real_dielectric = parse_dielectric_data( dielectric[1] )\n    imag_dielectric = parse_dielectric_data( dielectric[2] )\n    epsilon_1 = np.mean( real_dielectric, axis=1 )\n    epsilon_2 = np.mean( imag_dielectric, axis=1 )\n    return ( 2.0 * np.sqrt(2.0)*pi*eV_to_recip_cm*energies_in_eV\n                 * np.sqrt( -epsilon_1 + np.sqrt( epsilon_1**2 + epsilon_2**2 ) ) )",
    "docstring": "Calculate the optical absorption coefficient from an input set of\n    pymatgen vasprun dielectric constant data.\n\n    Args:\n        dielectric (list): A list containing the dielectric response function\n                           in the pymatgen vasprun format.\n\n                           | element 0: list of energies\n                           | element 1: real dielectric tensors, in ``[xx, yy, zz, xy, xz, yz]`` format.\n                           | element 2: imaginary dielectric tensors, in ``[xx, yy, zz, xy, xz, yz]`` format.\n    \n    Returns:\n        (np.array): absorption coefficient using eV as frequency units (cm^-1).\n\n    Notes:\n        The absorption coefficient is calculated as\n\n        .. math:: \\\\alpha = \\\\frac{2\\sqrt{2} \\pi}{\\lambda} \\sqrt{-\\epsilon_1+\\sqrt{\\epsilon_1^2+\\epsilon_2^2}}"
  },
  {
    "code": "def menu(self, prompt, choices):\n        menu = [prompt] + [\n            \"{0}. {1}\".format(*choice) for choice in enumerate(choices, start=1)\n        ]\n        command = 'inputlist({})'.format(repr(menu))\n        choice = int(self._vim.eval(command))\n        if not 0 < choice < len(menu):\n            return\n        return choices[choice - 1]",
    "docstring": "Presents a selection menu and returns the user's choice.\n\n        Args:\n            prompt (str): Text to ask the user what to select.\n            choices (Sequence[str]): Values for the user to select from.\n\n        Returns:\n            The value selected by the user, or ``None``.\n\n        Todo:\n            Nice opportunity to provide a hook for Unite.vim, etc. here."
  },
  {
    "code": "def format_call(self, api_version, api_call):\n        api_call = api_call.lstrip('/')\n        api_call = api_call.rstrip('?')\n        logger.debug('api_call post strip =\\n%s' % api_call)\n        if (api_version == 2 and api_call[-1] != '/'):\n            logger.debug('Adding \"/\" to api_call.')\n            api_call += '/'\n        if api_call in self.api_methods_with_trailing_slash[api_version]:\n            logger.debug('Adding \"/\" to api_call.')\n            api_call += '/'\n        return api_call",
    "docstring": "Return properly formatted QualysGuard API call according to api_version etiquette."
  },
  {
    "code": "def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):\n    return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,\n                profile=profile))",
    "docstring": "Check to see if an ElastiCache security group exists.\n\n    Example:\n\n    .. code-block:: bash\n\n        salt myminion boto3_elasticache.cache_security_group_exists mysecuritygroup"
  },
  {
    "code": "def set_stepdown_window(self, start, end, enabled=True, scheduled=True, weekly=True):\n        if not start < end:\n            raise TypeError('Parameter \"start\" must occur earlier in time than \"end\".')\n        week_delta = datetime.timedelta(days=7)\n        if not ((end - start) <= week_delta):\n            raise TypeError('Stepdown windows can not be longer than 1 week in length.')\n        url = self._service_url + 'stepdown/'\n        data = {\n            'start': int(start.strftime('%s')),\n            'end': int(end.strftime('%s')),\n            'enabled': enabled,\n            'scheduled': scheduled,\n            'weekly': weekly,\n        }\n        response = requests.post(\n            url,\n            data=json.dumps(data),\n            **self._instances._default_request_kwargs\n        )\n        return response.json()",
    "docstring": "Set the stepdown window for this instance.\n\n        Date times are assumed to be UTC, so use UTC date times.\n\n        :param datetime.datetime start: The datetime which the stepdown window is to open.\n        :param datetime.datetime end: The datetime which the stepdown window is to close.\n        :param bool enabled: A boolean indicating whether or not stepdown is to be enabled.\n        :param bool scheduled: A boolean indicating whether or not to schedule stepdown.\n        :param bool weekly: A boolean indicating whether or not to schedule compaction weekly."
  },
  {
    "code": "def can_proceed(self):\n        now = datetime.datetime.now()\n        delta = datetime.timedelta(days=self.update_interval)\n        return now >= self.last_update + delta",
    "docstring": "Checks whether app can proceed\n\n        :return: True iff app is not locked and times since last update < app\n            update interval"
  },
  {
    "code": "def nb_per_chunk(item_size, item_dim, chunk_size):\n    size = chunk_size * 10.**6\n    ratio = int(round(size / (item_size*item_dim)))\n    return max(10, ratio)",
    "docstring": "Return the number of items that can be stored in one chunk.\n\n    :param int item_size: Size of an item's scalar componant in\n        Bytes (e.g. for np.float64 this is 8)\n\n    :param int item_dim: Items dimension (length of the second axis)\n\n    :param float chunk_size: The size of a chunk given in MBytes."
  },
  {
    "code": "def get_mapping(self, index, doc_type=None):\n        mapping = self.es.indices.get_mapping(index=index, doc_type=doc_type)\n        return next(iter(mapping.values()))",
    "docstring": "Get mapping for index.\n\n        :param index: index name"
  },
  {
    "code": "def session_end_pb(status, end_time_secs=None):\n  if end_time_secs is None:\n    end_time_secs = time.time()\n  session_end_info = plugin_data_pb2.SessionEndInfo(status=status,\n                                                    end_time_secs=end_time_secs)\n  return _summary(metadata.SESSION_END_INFO_TAG,\n                  plugin_data_pb2.HParamsPluginData(\n                      session_end_info=session_end_info))",
    "docstring": "Constructs a SessionEndInfo protobuffer.\n\n  Creates a summary that contains status information for a completed\n  training session. Should be exported after the training session is completed.\n  One such summary per training session should be created. Each should have\n  a different run.\n\n  Args:\n    status: A tensorboard.hparams.Status enumeration value denoting the\n        status of the session.\n    end_time_secs: float. The time to use as the session end time. Represented\n        as seconds since the unix epoch. If None uses the current time.\n\n  Returns:\n    The summary protobuffer mentioned above."
  },
  {
    "code": "def _mesh_to_material(mesh, metallic=0.0, rough=0.0):\n    try:\n        color = mesh.visual.main_color\n    except BaseException:\n        color = np.array([100, 100, 100, 255], dtype=np.uint8)\n    color = color.astype(float32) / np.iinfo(color.dtype).max\n    material = {\n        \"pbrMetallicRoughness\": {\n            \"baseColorFactor\": color.tolist(),\n            \"metallicFactor\": metallic,\n            \"roughnessFactor\": rough}\n    }\n    return material",
    "docstring": "Create a simple GLTF material for a mesh using the most\n    commonly occurring color in that mesh.\n\n    Parameters\n    ------------\n    mesh: trimesh.Trimesh\n      Mesh to create a material from\n\n    Returns\n    ------------\n    material: dict\n      In GLTF material format"
  },
  {
    "code": "def CheckInputArgs(*interfaces):\n    l = len(interfaces)\n    def wrapper(func):\n        def check_args(self, *args, **kw):\n            for i in range(len(args)):\n                if (l > i and interfaces[i].providedBy(args[i])) or interfaces[-1].providedBy(args[i]):\n                    continue\n                if l > i: raise TypeError, 'arg %s does not implement %s' %(args[i], interfaces[i])\n                raise TypeError, 'arg %s does not implement %s' %(args[i], interfaces[-1])\n            func(self, *args, **kw)\n        return check_args\n    return wrapper",
    "docstring": "Must provide at least one interface, the last one may be repeated."
  },
  {
    "code": "def daily(self):\n        if self._daily is None:\n            self._daily = DailyList(self._version, account_sid=self._solution['account_sid'], )\n        return self._daily",
    "docstring": "Access the daily\n\n        :returns: twilio.rest.api.v2010.account.usage.record.daily.DailyList\n        :rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyList"
  },
  {
    "code": "def get_data_with_timestamps(self):\n        result = []\n        for t, d in zip(self.timestamps, self.data_points):\n            result.append(t, round(d, self.lr))\n        return result",
    "docstring": "Returns the data points with timestamps.\n\n        Returns:\n            A list of tuples in the format of (timestamp, data)"
  },
  {
    "code": "def validate_data_columns(self, data_columns, min_itemsize):\n        if not len(self.non_index_axes):\n            return []\n        axis, axis_labels = self.non_index_axes[0]\n        info = self.info.get(axis, dict())\n        if info.get('type') == 'MultiIndex' and data_columns:\n            raise ValueError(\"cannot use a multi-index on axis [{0}] with \"\n                             \"data_columns {1}\".format(axis, data_columns))\n        if data_columns is True:\n            data_columns = list(axis_labels)\n        elif data_columns is None:\n            data_columns = []\n        if isinstance(min_itemsize, dict):\n            existing_data_columns = set(data_columns)\n            data_columns.extend([\n                k for k in min_itemsize.keys()\n                if k != 'values' and k not in existing_data_columns\n            ])\n        return [c for c in data_columns if c in axis_labels]",
    "docstring": "take the input data_columns and min_itemize and create a data\n        columns spec"
  },
  {
    "code": "def get_channel_property(self, channel_id, property_name):\n        if isinstance(channel_id, (int, np.integer)):\n            if channel_id in self.get_channel_ids():\n                if channel_id not in self._channel_properties:\n                    self._channel_properties[channel_id] = {}\n                if isinstance(property_name, str):\n                    if property_name in list(self._channel_properties[channel_id].keys()):\n                        return self._channel_properties[channel_id][property_name]\n                    else:\n                        raise ValueError(str(property_name) + \" has not been added to channel \" + str(channel_id))\n                else:\n                    raise ValueError(str(property_name) + \" must be a string\")\n            else:\n                raise ValueError(str(channel_id) + \" is not a valid channel_id\")\n        else:\n            raise ValueError(str(channel_id) + \" must be an int\")",
    "docstring": "This function returns the data stored under the property name from\n        the given channel.\n\n        Parameters\n        ----------\n        channel_id: int\n            The channel id for which the property will be returned\n        property_name: str\n            A property stored by the RecordingExtractor (location, etc.)\n\n        Returns\n        ----------\n        property_data\n            The data associated with the given property name. Could be many\n            formats as specified by the user."
  },
  {
    "code": "def x_y_by_col_lbl(df, y_col_lbl):\n    x_cols = [col for col in df.columns if col != y_col_lbl]\n    return df[x_cols], df[y_col_lbl]",
    "docstring": "Returns an X dataframe and a y series by the given column name.\n\n    Parameters\n    ----------\n    df : pandas.DataFrame\n        The dataframe to split.\n    y_col_lbl : object\n        The label of the y column.\n\n    Returns\n    -------\n    X, y : pandas.DataFrame, pandas.Series\n        A dataframe made up of all columns but the column with the given name\n        and a series made up of the same column, respectively.\n\n    Example\n    -------\n    >>> import pandas as pd\n    >>> data = [[23, 'Jo', 4], [19, 'Mi', 3]]\n    >>> df = pd.DataFrame(data, [1, 2] , ['Age', 'Name', 'D'])\n    >>> X, y = x_y_by_col_lbl(df, 'D')\n    >>> X\n       Age Name\n    1   23   Jo\n    2   19   Mi\n    >>> y\n    1    4\n    2    3\n    Name: D, dtype: int64"
  },
  {
    "code": "def remove_unsafe_chars(text):\n    if isinstance(text, six.string_types):\n        text = UNSAFE_RE.sub('', text)\n    return text",
    "docstring": "Remove unsafe unicode characters from a piece of text."
  },
  {
    "code": "def vi_score(self, x, index):\n        if index == 0:\n            return self.vi_loc_score(x)\n        elif index == 1:\n            return self.vi_scale_score(x)",
    "docstring": "Wrapper function for selecting appropriate score\n\n        Parameters\n        ----------\n        x : float\n            A random variable\n\n        index : int\n            0 or 1 depending on which latent variable\n\n        Returns\n        ----------\n        The gradient of the scale latent variable at x"
  },
  {
    "code": "def merge(self, other):\n        if not getattr(other, '_catalog', None):\n            return\n        if self._catalog is None:\n            self.plural = other.plural\n            self._info = other._info.copy()\n            self._catalog = other._catalog.copy()\n        else:\n            self._catalog.update(other._catalog)",
    "docstring": "Merge another translation into this catalog."
  },
  {
    "code": "def add_weight(cls):\n  @functools.wraps(cls.add_weight)\n  def _add_weight(self,\n                  name=None,\n                  shape=None,\n                  dtype=None,\n                  initializer=None,\n                  regularizer=None,\n                  **kwargs):\n    if isinstance(initializer, tf.keras.layers.Layer):\n      weight = initializer(shape, dtype)\n      self._trainable_weights.extend(initializer.trainable_weights)\n      self._non_trainable_weights.extend(initializer.non_trainable_weights)\n      if regularizer is not None:\n        def loss_fn():\n          with tf.name_scope(name + '/Regularizer'):\n            return regularizer(initializer(shape, dtype))\n        self.add_loss(loss_fn)\n      return weight\n    return super(cls, self).add_weight(name=name,\n                                       shape=shape,\n                                       dtype=dtype,\n                                       initializer=initializer,\n                                       regularizer=regularizer,\n                                       **kwargs)\n  cls.add_weight = _add_weight\n  return cls",
    "docstring": "Decorator for Layers, overriding add_weight for trainable initializers."
  },
  {
    "code": "def allowed_entries(self, capability):\n        index = re.match(r'(.+)index$', capability)\n        archive = re.match(r'(.+)\\-archive$', capability)\n        if (capability == 'capabilitylistindex'):\n            return([])\n        elif (index):\n            return([index.group(1)])\n        elif (archive):\n            return([archive.group(1)])\n        elif (capability == 'description'):\n            return(['capabilitylist'])\n        elif (capability == 'capabilitylist'):\n            return(['resourcelist', 'resourcedump',\n                    'changelist', 'changedump',\n                    'resourcelist-archive', 'resourcedump-archive',\n                    'changelist-archive', 'changedump-archive'])\n        return([])",
    "docstring": "Return list of allowed entries for given capability document.\n\n        Includes handling of capability = *index where the only acceptable\n        entries are *."
  },
  {
    "code": "def lex(args):\n    if len(args) == 0 or args[0] == SHOW:\n        return [(SHOW, None)]\n    elif args[0] == LOG:\n        return [(LOG, None)]\n    elif args[0] == ECHO:\n        return [(ECHO, None)]\n    elif args[0] == SET and args[1] == RATE:\n        return tokenizeSetRate(args[2:])\n    elif args[0] == SET and args[1] == DAYS:\n        return tokenizeSetDays(args[2:])\n    elif args[0] == TAKE:\n        return tokenizeTake(args[1:])\n    elif args[0] == CANCEL:\n        return tokenizeCancel(args[1:])\n    elif isMonth(args[0]):\n        return tokenizeTake(args)\n    else:\n        print('Unknown commands: {}'.format(' '.join(args)))\n        return []",
    "docstring": "Lex input and return a list of actions to perform."
  },
  {
    "code": "def _download(self):\n        min_x, max_x, min_y, max_y = self.gssha_grid.bounds(as_geographic=True)\n        if self.era_download_data == 'era5':\n            log.info(\"Downloading ERA5 data ...\")\n            download_era5_for_gssha(self.lsm_input_folder_path,\n                                    self.download_start_datetime,\n                                    self.download_end_datetime,\n                                    leftlon=min_x-0.5,\n                                    rightlon=max_x+0.5,\n                                    toplat=max_y+0.5,\n                                    bottomlat=min_y-0.5)\n        else:\n            log.info(\"Downloading ERA Interim data ...\")\n            download_interim_for_gssha(self.lsm_input_folder_path,\n                                       self.download_start_datetime,\n                                       self.download_end_datetime,\n                                       leftlon=min_x-1,\n                                       rightlon=max_x+1,\n                                       toplat=max_y+1,\n                                       bottomlat=min_y-1)",
    "docstring": "download ERA5 data for GSSHA domain"
  },
  {
    "code": "def _save_vocab_file(vocab_file, subtoken_list):\n  with tf.gfile.Open(vocab_file, mode=\"w\") as f:\n    for subtoken in subtoken_list:\n      f.write(\"'%s'\\n\" % _unicode_to_native(subtoken))",
    "docstring": "Save subtokens to file."
  },
  {
    "code": "def _is_env_per_bucket():\n    buckets = _get_buckets()\n    if isinstance(buckets, dict):\n        return True\n    elif isinstance(buckets, list):\n        return False\n    else:\n        raise ValueError('Incorrect s3.buckets type given in config')",
    "docstring": "Return the configuration mode, either buckets per environment or a list of\n    buckets that have environment dirs in their root"
  },
  {
    "code": "def read_csv_from_file(filename):\n    logger_csvs.info(\"enter read_csv_from_file\")\n    d = {}\n    l = []\n    try:\n        logger_csvs.info(\"open file: {}\".format(filename))\n        with open(filename, 'r') as f:\n            r = csv.reader(f, delimiter=',')\n            for idx, col in enumerate(next(r)):\n                d[idx] = []\n                d = cast_values_csvs(d, idx, col)\n            for row in r:\n                for idx, col in enumerate(row):\n                    d = cast_values_csvs(d, idx, col)\n        for idx, col in d.items():\n            l.append(col)\n    except FileNotFoundError as e:\n        print('CSV FileNotFound: ' + filename)\n        logger_csvs.warn(\"read_csv_to_columns: FileNotFound: {}, {}\".format(filename, e))\n    logger_csvs.info(\"exit read_csv_from_file\")\n    return l",
    "docstring": "Opens the target CSV file and creates a dictionary with one list for each CSV column.\n\n    :param str filename:\n    :return list of lists: column values"
  },
  {
    "code": "def get_api_service(self, name=None):\n        try:\n            svc = self.services_by_name.get(name, None)\n            if svc is None:\n                raise ValueError(f\"Couldn't find the API service configuration\")\n            return svc\n        except:\n            raise Exception(f\"Failed to retrieve the API service configuration\")",
    "docstring": "Returns the specific service config definition"
  },
  {
    "code": "def list_services(self, limit=None, marker=None):\n        return self._services_manager.list(limit=limit, marker=marker)",
    "docstring": "List CDN services."
  },
  {
    "code": "def _update_dict(self, to_dict, from_dict):\n        for key, value in from_dict.items():\n            if key in to_dict and isinstance(to_dict[key], dict) and \\\n                    isinstance(from_dict[key], dict):\n                self._update_dict(to_dict[key], from_dict[key])\n            else:\n                to_dict[key] = from_dict[key]",
    "docstring": "Recursively merges the fields for two dictionaries.\n\n        Args:\n            to_dict (dict): The dictionary onto which the merge is executed.\n            from_dict (dict): The dictionary merged into to_dict"
  },
  {
    "code": "def get(self):\n        if (self.obj is None) or (time.time() >= self.expires):\n            with self.lock:\n                self.expires, self.obj = self.factory()\n                if isinstance(self.obj, BaseException):\n                    self.exception = self.obj\n                else:\n                    self.exception = None\n        if self.exception:\n            raise self.exception\n        else:\n            return self.obj",
    "docstring": "Get the wrapped object."
  },
  {
    "code": "def get_processor_name():\n    if platform.system() == \"Linux\":\n        with open(\"/proc/cpuinfo\", \"rb\") as cpuinfo:\n            all_info = cpuinfo.readlines()\n            for line in all_info:\n                if b'model name' in line:\n                    return re.sub(b'.*model name.*:', b'', line, 1)\n    return platform.processor()",
    "docstring": "Returns the processor name in the system"
  },
  {
    "code": "def responses_callback(request):\n    method = request.method\n    headers = CaseInsensitiveDict()\n    request_headers = CaseInsensitiveDict()\n    request_headers.update(request.headers)\n    request.headers = request_headers\n    uri = request.url\n    return StackInABox.call_into(method,\n                                 request,\n                                 uri,\n                                 headers)",
    "docstring": "Responses Request Handler.\n\n    Converts a call intercepted by Responses to\n    the Stack-In-A-Box infrastructure\n\n    :param request: request object\n\n    :returns: tuple - (int, dict, string) containing:\n                      int - the HTTP response status code\n                      dict - the headers for the HTTP response\n                      string - HTTP string response"
  },
  {
    "code": "def _prepare_colors(color, values, limits_c, colormap, alpha, chan=None):\n    if values is not None:\n        if limits_c is None:\n            limits_c = array([-1, 1]) * nanmax(abs(values))\n        norm_values = normalize(values, *limits_c)\n        cm = get_colormap(colormap)\n        colors = cm[norm_values]\n    elif color is not None:\n        colors = ColorArray(color)\n    else:\n        cm = get_colormap('hsl')\n        group_idx = _chan_groups_to_index(chan)\n        colors = cm[group_idx]\n    if alpha is not None:\n        colors.alpha = alpha\n    return colors, limits_c",
    "docstring": "Return colors for all the channels based on various inputs.\n\n    Parameters\n    ----------\n    color : tuple\n        3-, 4-element tuple, representing RGB and alpha, between 0 and 1\n    values : ndarray\n        array with values for each channel\n    limits_c : tuple of 2 floats, optional\n        min and max values to normalize the color\n    colormap : str\n        one of the colormaps in vispy\n    alpha : float\n        transparency (0 = transparent, 1 = opaque)\n    chan : instance of Channels\n        use labels to create channel groups\n\n    Returns\n    -------\n    1d / 2d array\n        colors for all the channels or for each channel individually\n    tuple of two float or None\n        limits for the values"
  },
  {
    "code": "def validate_value(self, value):\n        if value not in (None, self._unset):\n            super(ReferenceField, self).validate_value(value)\n            if value.app != self.target_app:\n                raise ValidationError(\n                    self.record,\n                    \"Reference field '{}' has target app '{}', cannot reference record '{}' from app '{}'\".format(\n                        self.name,\n                        self.target_app,\n                        value,\n                        value.app\n                    )\n                )",
    "docstring": "Validate provided record is a part of the appropriate target app for the field"
  },
  {
    "code": "def wheelEvent(self, event):\n        initial_state = event.isAccepted()\n        event.ignore()\n        self.mouse_wheel_activated.emit(event)\n        if not event.isAccepted():\n            event.setAccepted(initial_state)\n            super(CodeEdit, self).wheelEvent(event)",
    "docstring": "Emits the mouse_wheel_activated signal.\n\n        :param event: QMouseEvent"
  },
  {
    "code": "def generate(self):\n    header = ' '.join('=' * self.width[i] for i in range(self.w))\n    lines = [\n        ' '.join(row[i].ljust(self.width[i]) for i in range(self.w))\n        for row in self.rows]\n    return [header] + lines + [header]",
    "docstring": "Generate a list of strings representing the table in RST format."
  },
  {
    "code": "def transaction_error_code(self):\n        error = self.response_doc.find('transaction_error')\n        if error is not None:\n            code = error.find('error_code')\n            if code is not None:\n                return code.text",
    "docstring": "The machine-readable error code for a transaction error."
  },
  {
    "code": "def image_get(auth=None, **kwargs):\n    cloud = get_operator_cloud(auth)\n    kwargs = _clean_kwargs(**kwargs)\n    return cloud.get_image(**kwargs)",
    "docstring": "Get a single image\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' glanceng.image_get name=image1\n        salt '*' glanceng.image_get name=0e4febc2a5ab4f2c8f374b054162506d"
  },
  {
    "code": "def installedUniqueRequirements(self, target):\n    myDepends = dependentsOf(self.__class__)\n    for dc in self.store.query(_DependencyConnector,\n                               _DependencyConnector.target==target):\n        if dc.installee is self:\n            continue\n        depends = dependentsOf(dc.installee.__class__)\n        if self.__class__ in depends:\n            raise DependencyError(\n                \"%r cannot be uninstalled from %r, \"\n                \"%r still depends on it\" % (self, target, dc.installee))\n        for cls in myDepends[:]:\n            if cls in depends:\n                myDepends.remove(cls)\n    for dc in self.store.query(_DependencyConnector,\n                               _DependencyConnector.target==target):\n        if (dc.installee.__class__ in myDepends\n            and not dc.explicitlyInstalled):\n            yield dc.installee",
    "docstring": "Return an iterable of things installed on the target that this item\n    requires and are not required by anything else."
  },
  {
    "code": "def next_chunks(self):\n        with self.chunk_available:\n            while True:\n                playing_sounds = [s for s in self.sounds if s.playing]\n                chunks = []\n                for s in playing_sounds:\n                    try:\n                        chunks.append(next(s.chunks))\n                    except StopIteration:\n                        s.playing = False\n                        self.sounds.remove(s)\n                        self.is_done.set()\n                if chunks:\n                    break\n                self.chunk_available.wait()\n            return numpy.mean(chunks, axis=0)",
    "docstring": "Gets a new chunk from all played sound and mix them together."
  },
  {
    "code": "def try_enqueue(conn, queue_name, msg):\n    logger.debug('Getting Queue URL for queue %s', queue_name)\n    qurl = conn.get_queue_url(QueueName=queue_name)['QueueUrl']\n    logger.debug('Sending message to queue at: %s', qurl)\n    resp = conn.send_message(\n        QueueUrl=qurl,\n        MessageBody=msg,\n        DelaySeconds=0\n    )\n    logger.debug('Enqueued message in %s with ID %s', queue_name,\n                 resp['MessageId'])\n    return resp['MessageId']",
    "docstring": "Try to enqueue a message. If it succeeds, return the message ID.\n\n    :param conn: SQS API connection\n    :type conn: :py:class:`botocore:SQS.Client`\n    :param queue_name: name of queue to put message in\n    :type queue_name: str\n    :param msg: JSON-serialized message body\n    :type msg: str\n    :return: message ID\n    :rtype: str"
  },
  {
    "code": "def _get_auth_token(self):\n        url = '/%s/oauth2/token' % getattr(\n            settings, 'RESTCLIENTS_O365_TENANT', 'test')\n        headers = {'Accept': 'application/json'}\n        data = {\n            \"grant_type\": \"client_credentials\",\n            \"client_id\": getattr(settings,\n                                 'RESTCLIENTS_O365_CLIENT_ID',\n                                 None),\n            \"client_secret\": getattr(settings,\n                                     'RESTCLIENTS_O365_CLIENT_SECRET',\n                                     None),\n            \"resource\": self._api_host\n        }\n        body = urlencode(data)\n        auth_pool = self._get_pool(self._auth_host)\n        response = get_live_url(auth_pool, 'POST', self._auth_host,\n                                url, headers=headers, body=body,\n                                service_name='o365')\n        try:\n            json_data = json.loads(response.data)\n            if response.status == 200:\n                return \"%s %s\" % (\n                    json_data['token_type'], json_data['access_token'])\n            else:\n                raise DataFailureException(\n                    url, response.status,\n                    'Auth token failure: %s - %s' % (\n                        json_data.get('error', 'unknown'),\n                        json_data.get('error_description', 'no description')))\n        except ValueError:\n            raise DataFailureException(\n                url, response.status,\n                'Auth token failure: %s' % (response.data))",
    "docstring": "Given the office356 tenant and client id, and client secret\n        acquire a new authorization token"
  },
  {
    "code": "def remove_from_queue(self, index):\n        updid = '0'\n        objid = 'Q:0/' + str(index + 1)\n        self.avTransport.RemoveTrackFromQueue([\n            ('InstanceID', 0),\n            ('ObjectID', objid),\n            ('UpdateID', updid),\n        ])",
    "docstring": "Remove a track from the queue by index. The index number is\n        required as an argument, where the first index is 0.\n\n        Args:\n            index (int): The (0-based) index of the track to remove"
  },
  {
    "code": "def _convert_to_clusters(c):\n    new_dict = {}\n    n_cluster = 0\n    logger.debug(\"_convert_to_cluster: loci %s\" % c.loci2seq.keys())\n    for idl in c.loci2seq:\n        n_cluster += 1\n        new_c = cluster(n_cluster)\n        new_c.loci2seq[idl] = c.loci2seq[idl]\n        new_dict[n_cluster] = new_c\n    logger.debug(\"_convert_to_cluster: new ids %s\" % new_dict.keys())\n    return new_dict",
    "docstring": "Return 1 cluster per loci"
  },
  {
    "code": "def read(self):\n        if not self.ready_to_read():\n            return None\n        data = self._read()\n        if data is None:\n            return None\n        return self._parse_message(data)",
    "docstring": "If there is data available to be read from the transport, reads the data and tries to parse it as a protobuf message.  If the parsing succeeds, return a protobuf object.\n        Otherwise, returns None."
  },
  {
    "code": "def loc(self):\n        try:\n            return '{}:{}'.format(*ParseError.loc_info(self.text, self.index))\n        except ValueError:\n            return '<out of bounds index {!r}>'.format(self.index)",
    "docstring": "Locate the error position in the source code text."
  },
  {
    "code": "def send_status(self, payload):\n        answer = {}\n        data = []\n        if self.paused:\n            answer['status'] = 'paused'\n        else:\n            answer['status'] = 'running'\n        if len(self.queue) > 0:\n            data = deepcopy(self.queue.queue)\n            for key, item in data.items():\n                if 'stderr' in item:\n                    del item['stderr']\n                if 'stdout' in item:\n                    del item['stdout']\n        else:\n            data = 'Queue is empty'\n        answer['data'] = data\n        return answer",
    "docstring": "Send the daemon status and the current queue for displaying."
  },
  {
    "code": "def _tracebacks(score_matrix, traceback_matrix, idx):\n    score = score_matrix[idx]\n    if score == 0:\n        yield ()\n        return\n    directions = traceback_matrix[idx]\n    assert directions != Direction.NONE, 'Tracebacks with direction NONE should have value 0!'\n    row, col = idx\n    if directions & Direction.UP.value:\n        for tb in _tracebacks(score_matrix, traceback_matrix, (row - 1, col)):\n            yield itertools.chain(tb, ((idx, Direction.UP),))\n    if directions & Direction.LEFT.value:\n        for tb in _tracebacks(score_matrix, traceback_matrix, (row, col - 1)):\n            yield itertools.chain(tb, ((idx, Direction.LEFT),))\n    if directions & Direction.DIAG.value:\n        for tb in _tracebacks(score_matrix, traceback_matrix, (row - 1, col - 1)):\n            yield itertools.chain(tb, ((idx, Direction.DIAG),))",
    "docstring": "Implementation of traceeback.\n\n    This version can produce empty tracebacks, which we generally don't want\n    users seeing. So the higher level `tracebacks` filters those out."
  },
  {
    "code": "def _parse_content_type(content_type: Optional[str]) -> Tuple[Optional[str], str]:\n    if not content_type:\n        return None, \"utf-8\"\n    else:\n        type_, parameters = cgi.parse_header(content_type)\n        encoding = parameters.get(\"charset\", \"utf-8\")\n        return type_, encoding",
    "docstring": "Tease out the content-type and character encoding.\n\n    A default character encoding of UTF-8 is used, so the content-type\n    must be used to determine if any decoding is necessary to begin\n    with."
  },
  {
    "code": "def get_similar(self, limit=None):\n        params = self._get_params()\n        if limit:\n            params[\"limit\"] = limit\n        doc = self._request(self.ws_prefix + \".getSimilar\", True, params)\n        names = _extract_all(doc, \"name\")\n        matches = _extract_all(doc, \"match\")\n        artists = []\n        for i in range(0, len(names)):\n            artists.append(\n                SimilarItem(Artist(names[i], self.network), _number(matches[i]))\n            )\n        return artists",
    "docstring": "Returns the similar artists on the network."
  },
  {
    "code": "def resolve(self, working_set=None):\n    working_set = working_set or global_working_set\n    if self._plugin_requirements:\n      for plugin_location in self._resolve_plugin_locations():\n        if self._is_wheel(plugin_location):\n          plugin_location = self._activate_wheel(plugin_location)\n        working_set.add_entry(plugin_location)\n    return working_set",
    "docstring": "Resolves any configured plugins and adds them to the global working set.\n\n    :param working_set: The working set to add the resolved plugins to instead of the global\n                        working set (for testing).\n    :type: :class:`pkg_resources.WorkingSet`"
  },
  {
    "code": "def OnDestroy(self, event):\n        if hasattr(self, 'cardmonitor'):\n            self.cardmonitor.deleteObserver(self.cardtreecardobserver)\n        if hasattr(self, 'readermonitor'):\n            self.readermonitor.deleteObserver(self.readertreereaderobserver)\n            self.cardmonitor.deleteObserver(self.readertreecardobserver)\n        event.Skip()",
    "docstring": "Called on panel destruction."
  },
  {
    "code": "def get_effective_target_sdk_version(self):\n        target_sdk_version = self.get_target_sdk_version()\n        if not target_sdk_version:\n            target_sdk_version = self.get_min_sdk_version()\n        try:\n            return int(target_sdk_version)\n        except (ValueError, TypeError):\n            return 1",
    "docstring": "Return the effective targetSdkVersion, always returns int > 0.\n\n            If the targetSdkVersion is not set, it defaults to 1.  This is\n            set based on defaults as defined in:\n            https://developer.android.com/guide/topics/manifest/uses-sdk-element.html\n\n            :rtype: int"
  },
  {
    "code": "def GET_savedtimegrid(self) -> None:\n        try:\n            self._write_timegrid(state.timegrids[self._id])\n        except KeyError:\n            self._write_timegrid(hydpy.pub.timegrids.init)",
    "docstring": "Get the previously saved simulation period."
  },
  {
    "code": "def append(self, value):\n        if not self.need_free:\n            raise ValueError(\"Stack is read-only\")\n        if not isinstance(value, X509):\n            raise TypeError('StackOfX509 can contain only X509 objects')\n        sk_push(self.ptr, libcrypto.X509_dup(value.cert))",
    "docstring": "Adds certificate to stack"
  },
  {
    "code": "def rank_dated_files(pattern, dir, descending=True):\n    files = glob.glob(op.join(dir, pattern))\n    return sorted(files, reverse=descending)",
    "docstring": "Search a directory for files that match a pattern. Return an ordered list of these files by filename.\n\n    Args:\n        pattern: The glob pattern to search for.\n        dir: Path to directory where the files will be searched for.\n        descending: Default True, will sort alphabetically by descending order.\n\n    Returns:\n        list: Rank-ordered list by filename."
  },
  {
    "code": "def _no_primary(max_staleness, selection):\n    smax = selection.secondary_with_max_last_write_date()\n    if not smax:\n        return selection.with_server_descriptions([])\n    sds = []\n    for s in selection.server_descriptions:\n        if s.server_type == SERVER_TYPE.RSSecondary:\n            staleness = (smax.last_write_date -\n                         s.last_write_date +\n                         selection.heartbeat_frequency)\n            if staleness <= max_staleness:\n                sds.append(s)\n        else:\n            sds.append(s)\n    return selection.with_server_descriptions(sds)",
    "docstring": "Apply max_staleness, in seconds, to a Selection with no known primary."
  },
  {
    "code": "def has_permission(self, request, view):\n        if not self.global_permissions:\n            return True\n        serializer_class = view.get_serializer_class()\n        assert serializer_class.Meta.model is not None, (\n            \"global_permissions set to true without a model \"\n            \"set on the serializer for '%s'\" % view.__class__.__name__\n        )\n        model_class = serializer_class.Meta.model\n        action_method_name = None\n        if hasattr(view, 'action'):\n            action = self._get_action(view.action)\n            action_method_name = \"has_{action}_permission\".format(action=action)\n            if hasattr(model_class, action_method_name):\n                return getattr(model_class, action_method_name)(request)\n        if request.method in permissions.SAFE_METHODS:\n            assert hasattr(model_class, 'has_read_permission'), \\\n                self._get_error_message(model_class, 'has_read_permission', action_method_name)\n            return model_class.has_read_permission(request)\n        else:\n            assert hasattr(model_class, 'has_write_permission'), \\\n                self._get_error_message(model_class, 'has_write_permission', action_method_name)\n            return model_class.has_write_permission(request)",
    "docstring": "Overrides the standard function and figures out methods to call for global permissions."
  },
  {
    "code": "def targetpop(upper_density, coul, target_cf, slsp, n_tot):\n    if upper_density < 0.503: return 0.\n    trypops=population_distri(upper_density, n_tot)\n    slsp.set_filling(trypops)\n    slsp.selfconsistency(coul,0)\n    efm_free = dos_bethe_find_crystalfield(trypops, slsp.param['hopping'])\n    orb_ener = slsp.param['lambda']+ slsp.quasiparticle_weight()*efm_free\n    obtained_cf = orb_ener[5] - orb_ener[0]\n    return target_cf - obtained_cf",
    "docstring": "restriction on finding the right populations that leave the crystal\n    field same"
  },
  {
    "code": "def rav2xf(rot, av):\n    rot = stypes.toDoubleMatrix(rot)\n    av = stypes.toDoubleVector(av)\n    xform = stypes.emptyDoubleMatrix(x=6, y=6)\n    libspice.rav2xf_c(rot, av, xform)\n    return stypes.cMatrixToNumpy(xform)",
    "docstring": "This routine determines a state transformation matrix\n    from a rotation matrix and the angular velocity of the\n    rotation.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rav2xf_c.html\n\n    :param rot: Rotation matrix.\n    :type rot: 3x3-Element Array of floats\n    :param av: Angular velocity vector.\n    :type av: 3-Element Array of floats\n    :return: State transformation associated with rot and av.\n    :rtype: 6x6-Element Array of floats"
  },
  {
    "code": "def no_coroutine(f):\n    @functools.wraps(f)\n    def _no_coroutine(*args, **kwargs):\n        generator = f(*args, **kwargs)\n        if not isinstance(generator, types.GeneratorType):\n            return generator\n        previous = None\n        first    = True\n        while True:\n            element = None\n            try:\n                if first:\n                    element = next(generator)\n                else:\n                    element = generator.send(previous)\n            except StopIteration as e:\n                return getattr(e, \"value\", None)\n            except ReturnValueException as e:\n                return e.value\n            else:\n                previous = element\n                first    = False\n    return _no_coroutine",
    "docstring": "This is not a coroutine ;)\n\n    Use as a decorator:\n    @no_coroutine\n    def foo():\n        five = yield 5\n        print(yield \"hello\")\n\n    The function passed should be a generator yielding whatever you feel like.\n    The yielded values instantly get passed back into the generator.\n    It's basically the same as if you didn't use yield at all.\n    The example above is equivalent to:\n    def foo():\n        five = 5\n        print(\"hello\")\n\n    Why?\n    This is the counterpart to coroutine used by maybe_coroutine below."
  },
  {
    "code": "def get_cache_time(\n        self, path: str, modified: Optional[datetime.datetime], mime_type: str\n    ) -> int:\n        return self.CACHE_MAX_AGE if \"v\" in self.request.arguments else 0",
    "docstring": "Override to customize cache control behavior.\n\n        Return a positive number of seconds to make the result\n        cacheable for that amount of time or 0 to mark resource as\n        cacheable for an unspecified amount of time (subject to\n        browser heuristics).\n\n        By default returns cache expiry of 10 years for resources requested\n        with ``v`` argument."
  },
  {
    "code": "def find_cached_dm(self):\n        pmag_dir = find_pmag_dir.get_pmag_dir()\n        if pmag_dir is None:\n            pmag_dir = '.'\n        model_file = os.path.join(pmag_dir, 'pmagpy',\n                                  'data_model', 'data_model.json')\n        if not os.path.isfile(model_file):\n            model_file = os.path.join(pmag_dir, 'data_model',\n                                      'data_model.json')\n        if not os.path.isfile(model_file):\n            model_file = os.path.join(os.path.split(os.path.dirname(__file__))[0],'pmagpy', 'data_model','data_model.json')\n        if not os.path.isfile(model_file):\n            model_file = os.path.join(os.path.split(os.path.dirname(__file__))[0], 'data_model','data_model.json')\n        return model_file",
    "docstring": "Find filename where cached data model json is stored.\n\n        Returns\n        ---------\n        model_file : str\n            data model json file location"
  },
  {
    "code": "def _in_tag(self, tagname, attributes=None):\n        node = self.cur_node\n        while not node is None:\n            if node.tag == tagname:\n                if attributes and node.attrib == attributes:\n                    return True\n                elif attributes:\n                    return False\n                return True\n            node = node.getparent()\n        return False",
    "docstring": "Determine if we are already in a certain tag.\n        If we give attributes, make sure they match."
  },
  {
    "code": "def datapath(self):\n        path = self._fields['path']\n        if not path:\n            path = self.fetch('directory')\n            if path and not self._fields['is_multi_file']:\n                path = os.path.join(path, self._fields['name'])\n        return os.path.expanduser(fmt.to_unicode(path))",
    "docstring": "Get an item's data path."
  },
  {
    "code": "def get_gallery_favorites(self):\n        url = (self._imgur._base_url + \"/3/account/{0}/gallery_favorites\".format(\n               self.name))\n        resp = self._imgur._send_request(url)\n        return [Image(img, self._imgur) for img in resp]",
    "docstring": "Get a list of the images in the gallery this user has favorited."
  },
  {
    "code": "def participant_policy(self, value):\n        old_policy = self.participant_policy\n        new_policy = value\n        self._participant_policy = new_policy\n        notify(ParticipationPolicyChangedEvent(self, old_policy, new_policy))",
    "docstring": "Changing participation policy fires a\n        \"ParticipationPolicyChanged\" event"
  },
  {
    "code": "def sell(self, product_id, order_type, **kwargs):\n        return self.place_order(product_id, 'sell', order_type, **kwargs)",
    "docstring": "Place a sell order.\n\n        This is included to maintain backwards compatibility with older versions\n        of cbpro-Python. For maximum support from docstrings and function\n        signatures see the order type-specific functions place_limit_order,\n        place_market_order, and place_stop_order.\n\n        Args:\n            product_id (str): Product to order (eg. 'BTC-USD')\n            order_type (str): Order type ('limit', 'market', or 'stop')\n            **kwargs: Additional arguments can be specified for different order\n                types.\n\n        Returns:\n            dict: Order details. See `place_order` for example."
  },
  {
    "code": "def job_delayed(self, job, queue):\n        delayed_until = job.delayed_until.hget()\n        if delayed_until:\n            try:\n                delayed_until = compute_delayed_until(delayed_until=parse(delayed_until))\n            except (ValueError, TypeError):\n                delayed_until = None\n        if not delayed_until:\n            delayed_until = compute_delayed_until(delayed_for=60)\n        job.enqueue_or_delay(\n            queue_name=queue._cached_name,\n            delayed_until=delayed_until,\n            queue_model=queue.__class__,\n        )\n        self.log(self.job_delayed_message(job, queue), level='warning')\n        if hasattr(job, 'on_delayed'):\n            job.on_delayed(queue)",
    "docstring": "Called if a job, before trying to run it, has the \"delayed\" status, or,\n        after run, if its status was set to \"delayed\"\n        If delayed_until was not set, or is invalid, set it to 60sec in the future"
  },
  {
    "code": "def _resolve_deps(self, depmap):\n    deps = defaultdict(lambda: OrderedSet())\n    for category, depspecs in depmap.items():\n      dependencies = deps[category]\n      for depspec in depspecs:\n        dep_address = Address.parse(depspec)\n        try:\n          self.context.build_graph.maybe_inject_address_closure(dep_address)\n          dependencies.add(self.context.build_graph.get_target(dep_address))\n        except AddressLookupError as e:\n          raise AddressLookupError('{}\\n  referenced from {} scope'.format(e, self.options_scope))\n    return deps",
    "docstring": "Given a map of gen-key=>target specs, resolves the target specs into references."
  },
  {
    "code": "def infer(self, ob):\n    self._add_to_stack(ob)\n    logits, vf = self.infer_from_frame_stack(self._frame_stack)\n    return logits, vf",
    "docstring": "Add new observation to frame stack and infer policy.\n\n    Args:\n      ob: array of shape (height, width, channels)\n\n    Returns:\n      logits and vf."
  },
  {
    "code": "def remove_entity(self, entity, second=False):\n        if entity in self._entities:\n            if second:\n                for group in self._groups.keys():\n                    if entity in self._groups[group]:\n                        self.deregister_entity_from_group(entity, group)\n                self._entities.remove(entity)\n            else:\n                entity.kill()\n        else:\n            raise UnmanagedEntityError(entity)",
    "docstring": "Removes entity from world and kills entity"
  },
  {
    "code": "def E_Advective_Dispersion(t, Pe):\n    if isinstance(t, list):\n        t[t == 0] = 10**(-10)\n    return (Pe/(4*np.pi*t))**(0.5)*np.exp((-Pe*((1-t)**2))/(4*t))",
    "docstring": "Calculate a dimensionless measure of the output tracer concentration from\n    a spike input to reactor with advection and dispersion.\n\n    :param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR.\n    :type t: float or numpy.array\n    :param Pe: The ratio of advection to dispersion ((mean fluid velocity)/(Dispersion*flow path length))\n    :type Pe: float\n\n    :return: dimensionless measure of the output tracer concentration (concentration * volume of reactor) / (mass of tracer)\n    :rtype: float\n\n    :Examples:\n\n    >>> from aguaclara.research.environmental_processes_analysis import E_Advective_Dispersion\n    >>> round(E_Advective_Dispersion(0.5, 5), 7)\n    0.4774864"
  },
  {
    "code": "def dump_tree(self, statement=None, indent_level=0):\n        out = u\"\"\n        indent = u\" \"*indent_level\n        if statement is None:\n            for root_statement in self.statements:\n                out += self.dump_tree(root_statement, indent_level)\n        else:\n            out += indent + str(statement) + u'\\n'\n            if len(statement.children) > 0:\n                for child in statement.children:\n                    out += self.dump_tree(child, indent_level=indent_level+4)\n        return out",
    "docstring": "Dump the AST for this parsed file.\n\n        Args:\n            statement (SensorGraphStatement): the statement to print\n                if this function is called recursively.\n            indent_level (int): The number of spaces to indent this\n                statement.  Used for recursively printing blocks of\n                statements.\n        Returns:\n            str: The AST for this parsed sg file as a nested\n                tree with one node per line and blocks indented."
  },
  {
    "code": "def maybe_reduce(nodes):\n    r\n    _, num_nodes = nodes.shape\n    if num_nodes < 2:\n        return False, nodes\n    elif num_nodes == 2:\n        projection = _PROJECTION0\n        denom = _PROJ_DENOM0\n    elif num_nodes == 3:\n        projection = _PROJECTION1\n        denom = _PROJ_DENOM1\n    elif num_nodes == 4:\n        projection = _PROJECTION2\n        denom = _PROJ_DENOM2\n    elif num_nodes == 5:\n        projection = _PROJECTION3\n        denom = _PROJ_DENOM3\n    else:\n        raise _helpers.UnsupportedDegree(\n            num_nodes - 1, supported=(0, 1, 2, 3, 4)\n        )\n    projected = _helpers.matrix_product(nodes, projection) / denom\n    relative_err = projection_error(nodes, projected)\n    if relative_err < _REDUCE_THRESHOLD:\n        return True, reduce_pseudo_inverse(nodes)\n    else:\n        return False, nodes",
    "docstring": "r\"\"\"Reduce nodes in a curve if they are degree-elevated.\n\n    .. note::\n\n        This is a helper for :func:`_full_reduce`. Hence there is no\n        corresponding Fortran speedup.\n\n    We check if the nodes are degree-elevated by projecting onto the\n    space of degree-elevated curves of the same degree, then comparing\n    to the projection. We form the projection by taking the corresponding\n    (right) elevation matrix :math:`E` (from one degree lower) and forming\n    :math:`E^T \\left(E E^T\\right)^{-1} E`.\n\n    Args:\n        nodes (numpy.ndarray): The nodes in the curve.\n\n    Returns:\n        Tuple[bool, numpy.ndarray]: Pair of values. The first indicates\n        if the ``nodes`` were reduced. The second is the resulting nodes,\n        either the reduced ones or the original passed in.\n\n    Raises:\n        .UnsupportedDegree: If the curve is degree 5 or higher."
  },
  {
    "code": "def thresholdBlocks(self, blocks, recall_weight=1.5):\n        candidate_records = itertools.chain.from_iterable(self._blockedPairs(blocks))\n        probability = core.scoreDuplicates(candidate_records,\n                                           self.data_model,\n                                           self.classifier,\n                                           self.num_cores)['score']\n        probability = probability.copy()\n        probability.sort()\n        probability = probability[::-1]\n        expected_dupes = numpy.cumsum(probability)\n        recall = expected_dupes / expected_dupes[-1]\n        precision = expected_dupes / numpy.arange(1, len(expected_dupes) + 1)\n        score = recall * precision / (recall + recall_weight ** 2 * precision)\n        i = numpy.argmax(score)\n        logger.info('Maximum expected recall and precision')\n        logger.info('recall: %2.3f', recall[i])\n        logger.info('precision: %2.3f', precision[i])\n        logger.info('With threshold: %2.3f', probability[i])\n        return probability[i]",
    "docstring": "Returns the threshold that maximizes the expected F score, a\n        weighted average of precision and recall for a sample of\n        blocked data.\n\n        Arguments:\n\n        blocks -- Sequence of tuples of records, where each tuple is a\n                  set of records covered by a blocking predicate\n\n        recall_weight -- Sets the tradeoff between precision and\n                         recall. I.e. if you care twice as much about\n                         recall as you do precision, set recall_weight\n                         to 2."
  },
  {
    "code": "def resize(self, size, disk=None):\n        if isinstance(size, Size):\n            size = size.slug\n        opts = {\"disk\": disk} if disk is not None else {}\n        return self.act(type='resize', size=size, **opts)",
    "docstring": "Resize the droplet\n\n        :param size: a size slug or a `Size` object representing the size to\n            resize to\n        :type size: string or `Size`\n        :param bool disk: Set to `True` for a permanent resize, including\n            disk changes\n        :return: an `Action` representing the in-progress operation on the\n            droplet\n        :rtype: Action\n        :raises DOAPIError: if the API endpoint replies with an error"
  },
  {
    "code": "def image_create(cmptparms, cspace):\n    lst = [ctypes.c_int, ctypes.POINTER(ImageComptParmType), ctypes.c_int]\n    OPENJPEG.opj_image_create.argtypes = lst\n    OPENJPEG.opj_image_create.restype = ctypes.POINTER(ImageType)\n    image = OPENJPEG.opj_image_create(len(cmptparms), cmptparms, cspace)\n    return(image)",
    "docstring": "Wrapper for openjpeg library function opj_image_create."
  },
  {
    "code": "def boolean(self):\n        try:\n            return self._boolean\n        except AttributeError:\n            nbits = len(self.bits)\n            boolean = numpy.zeros((self.size, nbits), dtype=bool)\n            for i, sample in enumerate(self.value):\n                boolean[i, :] = [int(sample) >> j & 1 for j in range(nbits)]\n            self._boolean = Array2D(boolean, name=self.name,\n                                    x0=self.x0, dx=self.dx, y0=0, dy=1)\n            return self.boolean",
    "docstring": "A mapping of this `StateVector` to a 2-D array containing all\n        binary bits as booleans, for each time point."
  },
  {
    "code": "def _is_cow(path):\n    dirname = os.path.dirname(path)\n    return 'C' not in __salt__['file.lsattr'](dirname)[path]",
    "docstring": "Check if the subvolume is copy on write"
  },
  {
    "code": "def check_query(query):\n    q = query.lower()\n    if \"select \" not in q:\n        raise InvalidQuery(\"SELECT word not found in the query: {0}\".format(query))\n    if \" from \" not in q:\n        raise InvalidQuery(\"FROM word not found in the query: {0}\".format(query))",
    "docstring": "Check query sanity\n\n    Args:\n        query: query string\n\n    Returns:\n        None"
  },
  {
    "code": "def rbac_policy_create(request, **kwargs):\n    body = {'rbac_policy': kwargs}\n    rbac_policy = neutronclient(request).create_rbac_policy(\n        body=body).get('rbac_policy')\n    return RBACPolicy(rbac_policy)",
    "docstring": "Create a RBAC Policy.\n\n    :param request: request context\n    :param target_tenant: target tenant of the policy\n    :param tenant_id: owner tenant of the policy(Not recommended)\n    :param object_type: network or qos_policy\n    :param object_id: object id of policy\n    :param action: access_as_shared or access_as_external\n    :return: RBACPolicy object"
  },
  {
    "code": "def on_data(self, raw_data):\n        try:\n            data = json.loads(raw_data)\n        except ValueError:\n            logger.error('value error: %s' % raw_data)\n            return\n        unique_id = data.get('id')\n        if self._error_handler(data, unique_id):\n            return False\n        operation = data['op']\n        if operation == 'connection':\n            self._on_connection(data, unique_id)\n        elif operation == 'status':\n            self._on_status(data, unique_id)\n        elif operation in ['mcm', 'ocm']:\n            if self.stream_unique_id not in [unique_id, 'HISTORICAL']:\n                logger.warning('Unwanted data received from uniqueId: %s, expecting: %s' %\n                               (unique_id, self.stream_unique_id))\n                return\n            self._on_change_message(data, unique_id)",
    "docstring": "Called when raw data is received from connection.\n        Override this method if you wish to manually handle\n        the stream data\n\n        :param raw_data: Received raw data\n        :return: Return False to stop stream and close connection"
  },
  {
    "code": "def __calculate_boltzmann_factor(self, state_key, next_action_list):\n        sigmoid = self.__calculate_sigmoid()\n        q_df = self.q_df[self.q_df.state_key == state_key]\n        q_df = q_df[q_df.isin(next_action_list)]\n        q_df[\"boltzmann_factor\"] = q_df[\"q_value\"] / sigmoid\n        q_df[\"boltzmann_factor\"] = q_df[\"boltzmann_factor\"].apply(np.exp)\n        q_df[\"boltzmann_factor\"] = q_df[\"boltzmann_factor\"] / q_df[\"boltzmann_factor\"].sum()\n        return q_df",
    "docstring": "Calculate boltzmann factor.\n\n        Args:\n            state_key:              The key of state.\n            next_action_list:       The possible action in `self.t+1`.\n                                    If the length of this list is 0, all action should be possible.\n\n        Returns:\n            [(`The key of action`, `boltzmann probability`)]"
  },
  {
    "code": "def _authenticate(self):\n        try:\n            hosted_zones = self.r53_client.list_hosted_zones_by_name()[\n                'HostedZones'\n            ]\n            hosted_zone = next(\n                hz for hz in hosted_zones\n                if self.filter_zone(hz)\n            )\n            self.domain_id = hosted_zone['Id']\n        except StopIteration:\n            raise Exception('No domain found')",
    "docstring": "Determine the hosted zone id for the domain."
  },
  {
    "code": "def handle_message(self, msg):\n        if msg.msg_id not in self.msg_types:\n            self.report_message_type(msg)\n            self.msg_types.add(msg.msg_id)\n        self.tc.message('inspection', typeId=msg.msg_id, message=msg.msg,\n                        file=os.path.relpath(msg.abspath).replace('\\\\', '/'),\n                        line=str(msg.line),\n                        SEVERITY=TC_SEVERITY.get(msg.category))",
    "docstring": "Issues an `inspection` service message based on a PyLint message.\n        Registers each message type upon first encounter.\n\n        :param utils.Message msg: a PyLint message"
  },
  {
    "code": "def get_posix(self, i):\n        index = i.index\n        value = ['[']\n        try:\n            c = next(i)\n            if c != ':':\n                raise ValueError('Not a valid property!')\n            else:\n                value.append(c)\n                c = next(i)\n                if c == '^':\n                    value.append(c)\n                    c = next(i)\n                while c != ':':\n                    if c not in _PROPERTY:\n                        raise ValueError('Not a valid property!')\n                    if c not in _PROPERTY_STRIP:\n                        value.append(c)\n                    c = next(i)\n                value.append(c)\n                c = next(i)\n                if c != ']' or not value:\n                    raise ValueError('Unmatched ]')\n                value.append(c)\n        except Exception:\n            i.rewind(i.index - index)\n            value = []\n        return ''.join(value) if value else None",
    "docstring": "Get POSIX."
  },
  {
    "code": "def many_nodes(\n    lexer: Lexer,\n    open_kind: TokenKind,\n    parse_fn: Callable[[Lexer], Node],\n    close_kind: TokenKind,\n) -> List[Node]:\n    expect_token(lexer, open_kind)\n    nodes = [parse_fn(lexer)]\n    append = nodes.append\n    while not expect_optional_token(lexer, close_kind):\n        append(parse_fn(lexer))\n    return nodes",
    "docstring": "Fetch matching nodes, at least one.\n\n    Returns a non-empty list of parse nodes, determined by the `parse_fn`.\n    This list begins with a lex token of `open_kind` and ends with a lex token of\n    `close_kind`. Advances the parser to the next lex token after the closing token."
  },
  {
    "code": "def save_statement(self, statement):\n        if not isinstance(statement, Statement):\n            statement = Statement(statement)\n        request = HTTPRequest(\n            method=\"POST\",\n            resource=\"statements\"\n        )\n        if statement.id is not None:\n            request.method = \"PUT\"\n            request.query_params[\"statementId\"] = statement.id\n        request.headers[\"Content-Type\"] = \"application/json\"\n        request.content = statement.to_json(self.version)\n        lrs_response = self._send_request(request)\n        if lrs_response.success:\n            if statement.id is None:\n                statement.id = json.loads(lrs_response.data)[0]\n            lrs_response.content = statement\n        return lrs_response",
    "docstring": "Save statement to LRS and update statement id if necessary\n\n        :param statement: Statement object to be saved\n        :type statement: :class:`tincan.statement.Statement`\n        :return: LRS Response object with the saved statement as content\n        :rtype: :class:`tincan.lrs_response.LRSResponse`"
  },
  {
    "code": "def _start_reader(self):\n        while True:\n            message = yield From(self.pipe.read_message())\n            self._process(message)",
    "docstring": "Read messages from the Win32 pipe server and handle them."
  },
  {
    "code": "def format_norm(kwargs, current=None):\n    norm = kwargs.pop('norm', current) or 'linear'\n    vmin = kwargs.pop('vmin', None)\n    vmax = kwargs.pop('vmax', None)\n    clim = kwargs.pop('clim', (vmin, vmax)) or (None, None)\n    clip = kwargs.pop('clip', None)\n    if norm == 'linear':\n        norm = colors.Normalize()\n    elif norm == 'log':\n        norm = colors.LogNorm()\n    elif not isinstance(norm, colors.Normalize):\n        raise ValueError(\"unrecognised value for norm {!r}\".format(norm))\n    for attr, value in (('vmin', clim[0]), ('vmax', clim[1]), ('clip', clip)):\n        if value is not None:\n            setattr(norm, attr, value)\n    return norm, kwargs",
    "docstring": "Format a `~matplotlib.colors.Normalize` from a set of kwargs\n\n    Returns\n    -------\n    norm, kwargs\n        the formatted `Normalize` instance, and the remaining keywords"
  },
  {
    "code": "def OnDrawBackground(self, dc, rect, item, flags):\n        if (item & 1 == 0 or flags & (wx.combo.ODCB_PAINTING_CONTROL |\n                                      wx.combo.ODCB_PAINTING_SELECTED)):\n            try:\n                wx.combo.OwnerDrawnComboBox.OnDrawBackground(self, dc,\n                                                             rect, item, flags)\n            finally:\n                return\n        bg_color = get_color(config[\"label_color\"])\n        dc.SetBrush(wx.Brush(bg_color))\n        dc.SetPen(wx.Pen(bg_color))\n        dc.DrawRectangleRect(rect)",
    "docstring": "Called for drawing the background area of each item\n\n        Overridden from OwnerDrawnComboBox"
  },
  {
    "code": "def sign_off(self):\n        try:\n            logger.info(\"Bot player signing off.\")\n            feedback = WebDriverWait(self.driver, 20).until(\n                EC.presence_of_element_located((By.ID, \"submit-questionnaire\"))\n            )\n            self.complete_questionnaire()\n            feedback.click()\n            logger.info(\"Clicked submit questionnaire button.\")\n            self.driver.switch_to_window(self.driver.window_handles[0])\n            self.driver.set_window_size(1024, 768)\n            logger.info(\"Switched back to initial window.\")\n            return True\n        except TimeoutException:\n            logger.error(\"Error during experiment sign off.\")\n            return False",
    "docstring": "Submit questionnaire and finish.\n\n        This uses Selenium to click the submit button on the questionnaire\n        and return to the original window."
  },
  {
    "code": "def to_yaml(value) -> str:\n    stream = yaml.io.StringIO()\n    dumper = ConfigDumper(stream, default_flow_style=True, width=sys.maxsize)\n    val = None\n    try:\n        dumper.open()\n        dumper.represent(value)\n        val = stream.getvalue().strip()\n        dumper.close()\n    finally:\n        dumper.dispose()\n    return val",
    "docstring": "Convert a given value to a YAML string."
  },
  {
    "code": "def _make_version(major, minor, micro, releaselevel, serial):\n    assert releaselevel in ['alpha', 'beta', 'candidate', 'final']\n    version = \"%d.%d\" % (major, minor)\n    if micro:\n        version += \".%d\" % (micro,)\n    if releaselevel != 'final':\n        short = {'alpha': 'a', 'beta': 'b', 'candidate': 'rc'}[releaselevel]\n        version += \"%s%d\" % (short, serial)\n    return version",
    "docstring": "Create a readable version string from version_info tuple components."
  },
  {
    "code": "def _build_auth_request(self, verify=False, **kwargs):\n        json = {\n            'domain': self.domain\n        }\n        credential = self.credential\n        params = {}\n        if credential.provider_name.startswith('lms'):\n            params = dict(\n                login=credential._login,\n                pwd=credential._pwd)\n        else:\n            json.update(authenticationkey=credential._api_key)\n        if kwargs:\n            json.update(**kwargs)\n            self._extra_args.update(**kwargs)\n        request = dict(\n            url=self.credential.get_provider_entry_point(self.url, self.api_version),\n            json=json,\n            params=params,\n            headers={'content-type': 'application/json'},\n            verify=verify)\n        return request",
    "docstring": "Build the authentication request to SMC"
  },
  {
    "code": "def finalize(self, result):\n        runtime = int(time.time() * 1000) - self.execution_start_time\n        self.testcase_manager.update_execution_data(self.execution_guid,\n                                                    runtime)",
    "docstring": "At the end of the run, we want to\n        update the DB row with the execution time."
  },
  {
    "code": "def ListAssets(logdir, plugin_name):\n  plugin_dir = PluginDirectory(logdir, plugin_name)\n  try:\n    return [x.rstrip('/') for x in tf.io.gfile.listdir(plugin_dir)]\n  except tf.errors.NotFoundError:\n    return []",
    "docstring": "List all the assets that are available for given plugin in a logdir.\n\n  Args:\n    logdir: A directory that was created by a TensorFlow summary.FileWriter.\n    plugin_name: A string name of a plugin to list assets for.\n\n  Returns:\n    A string list of available plugin assets. If the plugin subdirectory does\n    not exist (either because the logdir doesn't exist, or because the plugin\n    didn't register) an empty list is returned."
  },
  {
    "code": "def _register_allocator(self, plugin_name, plugin_instance):\n        for allocator in plugin_instance.get_allocators().keys():\n            if allocator in self._allocators:\n                raise PluginException(\"Allocator with name {} already exists! unable to add \"\n                                      \"allocators from plugin {}\".format(allocator, plugin_name))\n            self._allocators[allocator] = plugin_instance.get_allocators().get(allocator)",
    "docstring": "Register an allocator.\n\n        :param plugin_name: Allocator name\n        :param plugin_instance: RunPluginBase\n        :return:"
  },
  {
    "code": "def evaluate_accuracy(data_iterator, net):\n    acc = mx.metric.Accuracy()\n    for data, label in data_iterator:\n        output = net(data)\n        predictions = nd.argmax(output, axis=1)\n        predictions = predictions.reshape((-1, 1))\n        acc.update(preds=predictions, labels=label)\n    return acc.get()[1]",
    "docstring": "Function to evaluate accuracy of any data iterator passed to it as an argument"
  },
  {
    "code": "def update(self, _attributes=None, **attributes):\n        if _attributes is not None:\n            attributes.update(_attributes)\n        instance = self.get_results()\n        return instance.fill(attributes).save()",
    "docstring": "Update the parent model on the relationship.\n\n        :param attributes: The update attributes\n        :type attributes: dict\n\n        :rtype: mixed"
  },
  {
    "code": "def delete(self, container_id=None, sudo=None):\n    sudo = self._get_sudo(sudo)\n    container_id = self.get_container_id(container_id)\n    cmd = self._init_command('delete')\n    cmd.append(container_id)\n    return self._run_and_return(cmd, sudo=sudo)",
    "docstring": "delete an instance based on container_id.\n\n       Parameters\n       ==========\n       container_id: the container_id to delete\n       sudo: whether to issue the command with sudo (or not)\n             a container started with sudo will belong to the root user\n             If started by a user, the user needs to control deleting it\n             if the user doesn't set to True/False, we use client self.sudo\n\n       Returns\n       =======\n       return_code: the return code from the delete command. 0 indicates a\n                    successful delete, 255 indicates not."
  },
  {
    "code": "def add_multiple(self, flags):\n        if not isinstance(flags, list):\n            raise TypeError(\"Expected list of flags, got object of type{}\".format(type(flags)))\n        for flag in flags:\n            if isinstance(flag, Flag):\n                self.add_item(flag)\n            elif isinstance(flag, tuple):\n                try:\n                    item = Flag(*flag)\n                    self.add_item(item)\n                except TypeError as e:\n                    raise TypeError(\"Invalid arguments to initialize a flag definition, expect ({0} [, {1}]) but got {3}\"\n                        .format(\", \".join(Flag.REQUIRED_FIELDS),\n                        \", \".join(Flag.OPTIONAL_FIELDS), flag))",
    "docstring": "Add multiple command line flags\n\n        Arguments:\n            flags (:obj:`list` of :obj:`tuple`): List of flags\n                in tuples (name, flag_type, description, (optional) default)\n\n        Raises:\n            TypeError: Provided wrong arguments or arguments of wrong types, method will raise TypeError"
  },
  {
    "code": "def load_dwg(file_obj, **kwargs):\n    data = file_obj.read()\n    converted = _teigha_convert(data)\n    result = load_dxf(util.wrap_as_stream(converted))\n    return result",
    "docstring": "Load DWG files by converting them to DXF files using\n    TeighaFileConverter.\n\n    Parameters\n    -------------\n    file_obj : file- like object\n\n    Returns\n    -------------\n    loaded : dict\n        kwargs for a Path2D constructor"
  },
  {
    "code": "def list_qos_rule_types(self, retrieve_all=True, **_params):\n        return self.list('rule_types', self.qos_rule_types_path,\n                         retrieve_all, **_params)",
    "docstring": "List available qos rule types."
  },
  {
    "code": "def _set_textarea(el, value):\n        if isinstance(value, dict):\n            el.text = value[\"val\"]\n        elif type(value) in [list, tuple]:\n            el.text = \"\\n\\n\".join(\n                \"-- %s --\\n%s\" % (item[\"source\"], item[\"val\"])\n                for item in value\n            )\n        else:\n            el.text = value",
    "docstring": "Set content of given textarea element `el` to `value`.\n\n        Args:\n            el (obj): Reference to textarea element you wish to set.\n            value (obj/list): Value to which the `el` will be set."
  },
  {
    "code": "def disconnect_socket(self):\n        self.running = False\n        if self.socket is not None:\n            if self.__need_ssl():\n                try:\n                    self.socket = self.socket.unwrap()\n                except Exception:\n                    _, e, _ = sys.exc_info()\n                    log.warning(e)\n            elif hasattr(socket, 'SHUT_RDWR'):\n                try:\n                    self.socket.shutdown(socket.SHUT_RDWR)\n                except socket.error:\n                    _, e, _ = sys.exc_info()\n                    if get_errno(e) != errno.ENOTCONN:\n                        log.warning(\"Unable to issue SHUT_RDWR on socket because of error '%s'\", e)\n        if self.socket is not None:\n            try:\n                self.socket.close()\n            except socket.error:\n                _, e, _ = sys.exc_info()\n                log.warning(\"Unable to close socket because of error '%s'\", e)\n        self.current_host_and_port = None\n        self.socket = None\n        self.notify('disconnected')",
    "docstring": "Disconnect the underlying socket connection"
  },
  {
    "code": "def find_geom(geom, geoms):\n    for i, g in enumerate(geoms):\n        if g is geom:\n            return i",
    "docstring": "Returns the index of a geometry in a list of geometries avoiding\n    expensive equality checks of `in` operator."
  },
  {
    "code": "def get_item_dicts(self, buckets=None, results=15, start=0,item_ids=None):\n        kwargs = {}\n        kwargs['bucket'] = buckets or []\n        kwargs['item_id'] = item_ids or []\n        response = self.get_attribute(\"read\", results=results, start=start, **kwargs)\n        rval = ResultList(response['catalog']['items'])\n        if item_ids:\n            rval.start=0;\n            rval.total=len(response['catalog']['items'])\n        else:\n            rval.start = response['catalog']['start']\n            rval.total = response['catalog']['total']\n        return rval",
    "docstring": "Returns data from the catalog; also expanded for the requested buckets\n\n        Args:\n\n        Kwargs:\n            buckets (list): A list of strings specifying which buckets to retrieve\n\n            results (int): An integer number of results to return\n\n            start (int): An integer starting value for the result set\n\n        Returns:\n            A list of dicts representing objects in the catalog; list has additional attributes 'start' and 'total'\n\n        Example:\n\n        >>> c\n        <catalog - my_songs>\n        >>> c.read_items(results=1)\n        [\n                {\n                    \"artist_id\": \"AR78KRI1187B98E6F2\",\n                    \"artist_name\": \"Art of Noise\",\n                    \"date_added\": \"2012-04-02T16:50:02\",\n                    \"foreign_id\": \"CAHLYLR13674D1CF83:song:1000\",\n                    \"request\": {\n                        \"artist_name\": \"The Art Of Noise\",\n                        \"item_id\": \"1000\",\n                        \"song_name\": \"Love\"\n                    },\n                    \"song_id\": \"SOSBCTO1311AFE7AE0\",\n                    \"song_name\": \"Love\"\n                }\n        ]"
  },
  {
    "code": "def generate_response_property(name=None, value=None):\n    name = name or \"dump2polarion\"\n    value = value or \"\".join(random.sample(string.ascii_lowercase, 12))\n    return (name, value)",
    "docstring": "Generates response property."
  },
  {
    "code": "def stringify(metrics_headers=()):\n    metrics_headers = collections.OrderedDict(metrics_headers)\n    return ' '.join(['%s/%s' % (k, v) for k, v in metrics_headers.items()])",
    "docstring": "Convert the provided metrics headers to a string.\n\n    Iterate over the metrics headers (a dictionary, usually ordered) and\n    return a properly-formatted space-separated string\n    (e.g. foo/1.2.3 bar/3.14.159)."
  },
  {
    "code": "def wrap_socket(self, sock, server_side=False,\n                    do_handshake_on_connect=True,\n                    suppress_ragged_eofs=True, dummy=None):\n        return ssl.wrap_socket(sock, keyfile=self._keyfile,\n                               certfile=self._certfile,\n                               server_side=server_side,\n                               cert_reqs=self._verify_mode,\n                               ssl_version=self._protocol,\n                               ca_certs=self._cafile,\n                               do_handshake_on_connect=do_handshake_on_connect,\n                               suppress_ragged_eofs=suppress_ragged_eofs)",
    "docstring": "Wrap an existing Python socket sock and return an ssl.SSLSocket\n        object."
  },
  {
    "code": "def version(self):\n        try:\n            f = self.func.__call__.__code__\n        except AttributeError:\n            f = self.func.__code__\n        h = md5()\n        h.update(f.co_code)\n        h.update(str(f.co_names).encode())\n        try:\n            closure = self.func.__closure__\n        except AttributeError:\n            return h.hexdigest()\n        if closure is None or self.closure_fingerprint is None:\n            return h.hexdigest()\n        d = dict(\n            (name, cell.cell_contents)\n            for name, cell in zip(f.co_freevars, closure))\n        h.update(self.closure_fingerprint(d).encode())\n        return h.hexdigest()",
    "docstring": "Compute the version identifier for this functional node using the\n        func code and local names.  Optionally, also allow closed-over variable\n        values to affect the version number when closure_fingerprint is\n        specified"
  },
  {
    "code": "def configure(paths, relative_to):\n    if not paths:\n        return\n    for path in [normalize_path(p, relative_to) for p in paths]:\n        logger.debug('configuration path {0}'.format(path))\n        pubkeys_path = join(path, PUBKEYSDIR)\n        if os.path.exists(pubkeys_path):\n            load_pubkeys(pubkeys_path, PUBKEYS)\n        init_module(path)",
    "docstring": "Iterate on each configuration path, collecting all public keys\n    destined for the new node's root account's authorized keys.\n    Additionally attempt to import path as python module."
  },
  {
    "code": "def address(self):\n        if self.isDirect():\n            base36 = self._iban[4:]\n            asInt = int(base36, 36)\n            return to_checksum_address(pad_left_hex(baseN(asInt, 16), 20))\n        return \"\"",
    "docstring": "Should be called to get client direct address\n\n        @method address\n        @returns {String} client direct address"
  },
  {
    "code": "def reverse_index_mapping(self):\n        if self._reverse_index_mapping is None:\n            if self.is_indexed:\n                r = np.zeros(self.base_length, dtype=np.int32) - 1\n                r[self.order] = np.arange(len(self.order), dtype=np.int32)\n            elif self.data.base is None:\n                r = np.arange(self.data_length, dtype=np.int32)\n            else:\n                r = np.zeros(self.base_length, dtype=np.int32) - 1\n                r[self.data_start - self.base_start:self.data_end - self.base_start] = np.arange(self.data_length, dtype=np.int32)\n            self._reverse_index_mapping = r\n        return self._reverse_index_mapping",
    "docstring": "Get mapping from this segment's indexes to the indexes of\n        the base array.\n\n        If the index is < 0, the index is out of range, meaning that it doesn't\n        exist in this segment and is not mapped to the base array"
  },
  {
    "code": "def _venv_match(self, installed, requirements):\n        if not requirements:\n            return None if installed else []\n        satisfying_deps = []\n        for repo, req_deps in requirements.items():\n            useful_inst = set()\n            if repo not in installed:\n                return None\n            if repo == REPO_VCS:\n                inst_deps = {VCSDependency(url) for url in installed[repo].keys()}\n            else:\n                inst_deps = {Distribution(project_name=dep, version=ver)\n                             for (dep, ver) in installed[repo].items()}\n            for req in req_deps:\n                for inst in inst_deps:\n                    if inst in req:\n                        useful_inst.add(inst)\n                        break\n                else:\n                    return None\n            if useful_inst == inst_deps:\n                satisfying_deps.extend(inst_deps)\n            else:\n                return None\n        return satisfying_deps",
    "docstring": "Return True if what is installed satisfies the requirements.\n\n        This method has multiple exit-points, but only for False (because\n        if *anything* is not satisified, the venv is no good). Only after\n        all was checked, and it didn't exit, the venv is ok so return True."
  },
  {
    "code": "def handle_market_close(self, dt, data_portal):\n        completed_session = self._current_session\n        if self.emission_rate == 'daily':\n            self.sync_last_sale_prices(dt, data_portal)\n        session_ix = self._session_count\n        self._session_count += 1\n        packet = {\n            'period_start': self._first_session,\n            'period_end': self._last_session,\n            'capital_base': self._capital_base,\n            'daily_perf': {\n                'period_open': self._market_open,\n                'period_close': dt,\n            },\n            'cumulative_perf': {\n                'period_open': self._first_session,\n                'period_close': self._last_session,\n            },\n            'progress': self._progress(self),\n            'cumulative_risk_metrics': {},\n        }\n        ledger = self._ledger\n        ledger.end_of_session(session_ix)\n        self.end_of_session(\n            packet,\n            ledger,\n            completed_session,\n            session_ix,\n            data_portal,\n        )\n        return packet",
    "docstring": "Handles the close of the given day.\n\n        Parameters\n        ----------\n        dt : Timestamp\n            The most recently completed simulation datetime.\n        data_portal : DataPortal\n            The current data portal.\n\n        Returns\n        -------\n        A daily perf packet."
  },
  {
    "code": "def get_section_by_offset(self, offset):\n        sections = [s for s in self.sections if s.contains_offset(offset)]\n        if sections:\n            return sections[0]\n        return None",
    "docstring": "Get the section containing the given file offset."
  },
  {
    "code": "def clean_translated_locales(configuration, langs=None):\n    if not langs:\n        langs = configuration.translated_locales\n    for locale in langs:\n        clean_locale(configuration, locale)",
    "docstring": "Strips out the warning from all translated po files\n    about being an English source file."
  },
  {
    "code": "def set_transaction_isolation(self, level):\n        self.ensure_connected()\n        self._transaction_isolation_level = level\n        self._platform.set_transaction_isolation(level)",
    "docstring": "Sets the transaction isolation level.\n\n        :param level: the level to set"
  },
  {
    "code": "def _safe_output(line):\n    return not any([\n        line.startswith('Listing') and line.endswith('...'),\n        line.startswith('Listing') and '\\t' not in line,\n        '...done' in line,\n        line.startswith('WARNING:')\n    ])",
    "docstring": "Looks for rabbitmqctl warning, or general formatting, strings that aren't\n    intended to be parsed as output.\n    Returns a boolean whether the line can be parsed as rabbitmqctl output."
  },
  {
    "code": "def out_16(library, session, space, offset, data, extended=False):\n    if extended:\n        return library.viOut16Ex(session, space, offset, data, extended=False)\n    else:\n        return library.viOut16(session, space, offset, data, extended=False)",
    "docstring": "Write in an 16-bit value from the specified memory space and offset.\n\n    Corresponds to viOut16* functions of the VISA library.\n\n    :param library: the visa library wrapped by ctypes.\n    :param session: Unique logical identifier to a session.\n    :param space: Specifies the address space. (Constants.*SPACE*)\n    :param offset: Offset (in bytes) of the address or register from which to read.\n    :param data: Data to write to bus.\n    :param extended: Use 64 bits offset independent of the platform.\n    :return: return value of the library call.\n    :rtype: :class:`pyvisa.constants.StatusCode`"
  },
  {
    "code": "def get_parameter(self, parameter):\n        \"Return a dict for given parameter\"\n        parameter = self._get_parameter_name(parameter)\n        return self._parameters[parameter]",
    "docstring": "Return a dict for given parameter"
  },
  {
    "code": "def exclude_data_files(self, package, src_dir, files):\n        files = list(files)\n        patterns = self._get_platform_patterns(\n            self.exclude_package_data,\n            package,\n            src_dir,\n        )\n        match_groups = (\n            fnmatch.filter(files, pattern)\n            for pattern in patterns\n        )\n        matches = itertools.chain.from_iterable(match_groups)\n        bad = set(matches)\n        keepers = (\n            fn\n            for fn in files\n            if fn not in bad\n        )\n        return list(_unique_everseen(keepers))",
    "docstring": "Filter filenames for package's data files in 'src_dir"
  },
  {
    "code": "def set_speed(self,speed):\n\tself.speed=speed\n\tself.send_cmd(\"SPEED\"+str(speed))",
    "docstring": "Set the display speed.  The parameters is the number of milliseconds\n\tbetween each column scrolling off the display"
  },
  {
    "code": "def _resolve_transformations(transformations):\n    registry = _ModulesRegistry()\n    transformations = transformations or []\n    for t in transformations:\n        try:\n            mod, attr = t.split(\":\", 1)\n            yield getattr(registry.require(mod), attr)\n        except ValueError:\n            yield getattr(bonobo, t)",
    "docstring": "Resolve a collection of strings into the matching python objects, defaulting to bonobo namespace if no package is provided.\n\n    Syntax for each string is path.to.package:attribute\n\n    :param transformations: tuple(str)\n    :return: tuple(object)"
  },
  {
    "code": "def get(self, sid):\n        return QueryContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, )",
    "docstring": "Constructs a QueryContext\n\n        :param sid: The unique string that identifies the resource\n\n        :returns: twilio.rest.autopilot.v1.assistant.query.QueryContext\n        :rtype: twilio.rest.autopilot.v1.assistant.query.QueryContext"
  },
  {
    "code": "def node_container(self, container_id):\n        path = '/ws/v1/node/containers/{containerid}'.format(\n            containerid=container_id)\n        return self.request(path)",
    "docstring": "A container resource contains information about a particular container\n        that is running on this NodeManager.\n\n        :param str container_id: The container id\n        :returns: API response object with JSON data\n        :rtype: :py:class:`yarn_api_client.base.Response`"
  },
  {
    "code": "def display(fig=None, closefig=True, **kwargs):\n    from IPython.display import HTML\n    if fig is None:\n        fig = plt.gcf()\n    if closefig:\n        plt.close(fig)\n    html = fig_to_html(fig, **kwargs)\n    iframe_html = '<iframe src=\"data:text/html;base64,{html}\" width=\"{width}\" height=\"{height}\"></iframe>'\\\n    .format(html = base64.b64encode(html.encode('utf8')).decode('utf8'),\n            width = '100%',\n            height= int(60.*fig.get_figheight()),\n           )\n    return HTML(iframe_html)",
    "docstring": "Convert a Matplotlib Figure to a Leaflet map. Embed in IPython notebook.\n\n    Parameters\n    ----------\n    fig : figure, default gcf()\n        Figure used to convert to map\n    closefig : boolean, default True\n        Close the current Figure"
  },
  {
    "code": "def mkdir_command(endpoint_plus_path):\n    endpoint_id, path = endpoint_plus_path\n    client = get_client()\n    autoactivate(client, endpoint_id, if_expires_in=60)\n    res = client.operation_mkdir(endpoint_id, path=path)\n    formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key=\"message\")",
    "docstring": "Executor for `globus mkdir`"
  },
  {
    "code": "def find(cls, paths):\n    pythons = []\n    for path in paths:\n      for fn in cls.expand_path(path):\n        basefile = os.path.basename(fn)\n        if cls._matches_binary_name(basefile):\n          try:\n            pythons.append(cls.from_binary(fn))\n          except Exception as e:\n            TRACER.log('Could not identify %s: %s' % (fn, e))\n            continue\n    return pythons",
    "docstring": "Given a list of files or directories, try to detect python interpreters amongst them.\n      Returns a list of PythonInterpreter objects."
  },
  {
    "code": "def _get_seqprop_to_seqprop_alignment(self, seqprop1, seqprop2):\n        if isinstance(seqprop1, str):\n            seqprop1_id = seqprop1\n        else:\n            seqprop1_id = seqprop1.id\n        if isinstance(seqprop2, str):\n            seqprop2_id = seqprop2\n        else:\n            seqprop2_id = seqprop2.id\n        aln_id = '{}_{}'.format(seqprop1_id, seqprop2_id)\n        if self.sequence_alignments.has_id(aln_id):\n            alignment = self.sequence_alignments.get_by_id(aln_id)\n            return alignment\n        else:\n            raise ValueError('{}: sequence alignment not found, please run the alignment first'.format(aln_id))",
    "docstring": "Return the alignment stored in self.sequence_alignments given a seqprop + another seqprop"
  },
  {
    "code": "def is_battery_level(value):\n    try:\n        value = percent_int(value)\n        return value\n    except vol.Invalid:\n        _LOGGER.warning(\n            '%s is not a valid battery level, falling back to battery level 0',\n            value)\n        return 0",
    "docstring": "Validate that value is a valid battery level integer."
  },
  {
    "code": "def is_installed(self, bug: Bug) -> bool:\n        r = self.__api.get('bugs/{}/installed'.format(bug.name))\n        if r.status_code == 200:\n            answer = r.json()\n            assert isinstance(answer, bool)\n            return answer\n        if r.status_code == 404:\n            raise KeyError(\"no bug found with given name: {}\".format(bug.name))\n        self.__api.handle_erroneous_response(r)",
    "docstring": "Determines whether the Docker image for a given bug has been installed\n        on the server."
  },
  {
    "code": "def name(self):\n        parts = self._parts\n        if len(parts) == (1 if (self._drv or self._root) else 0):\n            return ''\n        return parts[-1]",
    "docstring": "The final path component, if any."
  },
  {
    "code": "def logToFile(path, level=logging.INFO):\n    logger = logging.getLogger()\n    logger.setLevel(level)\n    formatter = logging.Formatter(\n        '%(asctime)s %(name)s %(levelname)s %(message)s')\n    handler = logging.FileHandler(path)\n    handler.setFormatter(formatter)\n    logger.addHandler(handler)",
    "docstring": "Create a log handler that logs to the given file."
  },
  {
    "code": "def validate_file(fn, options=None):\n    file_results = FileValidationResults(filepath=fn)\n    output.info(\"Performing JSON schema validation on %s\" % fn)\n    if not options:\n        options = ValidationOptions(files=fn)\n    try:\n        with open(fn) as instance_file:\n            file_results.object_results = validate(instance_file, options)\n    except Exception as ex:\n        if 'Expecting value' in str(ex):\n            line_no = str(ex).split()[3]\n            file_results.fatal = ValidationErrorResults(\n                'Invalid JSON input on line %s' % line_no\n            )\n        else:\n            file_results.fatal = ValidationErrorResults(ex)\n        msg = (\"Unexpected error occurred with file '{fn}'. No further \"\n               \"validation will be performed: {error}\")\n        output.info(msg.format(fn=fn, error=str(ex)))\n    file_results.is_valid = (all(object_result.is_valid\n                                 for object_result in file_results.object_results)\n                             and not file_results.fatal)\n    return file_results",
    "docstring": "Validate the input document `fn` according to the options passed in.\n\n    If any exceptions are raised during validation, no further validation\n    will take place.\n\n    Args:\n        fn: The filename of the JSON file to be validated.\n        options: An instance of ``ValidationOptions``.\n\n    Returns:\n        An instance of FileValidationResults."
  },
  {
    "code": "def initiate_handshake(self, headers, timeout=None):\n        io_loop = IOLoop.current()\n        timeout = timeout or DEFAULT_INIT_TIMEOUT_SECS\n        self.writer.put(messages.InitRequestMessage(\n            version=PROTOCOL_VERSION,\n            headers=headers\n        ))\n        init_res_future = self.reader.get()\n        timeout_handle = io_loop.call_later(timeout, (\n            lambda: init_res_future.set_exception(errors.TimeoutError(\n                'Handshake with %s:%d timed out. Did not receive an INIT_RES '\n                'after %s seconds' % (\n                    self.remote_host, self.remote_host_port, str(timeout)\n                )\n            ))\n        ))\n        io_loop.add_future(\n            init_res_future,\n            (lambda _: io_loop.remove_timeout(timeout_handle)),\n        )\n        init_res = yield init_res_future\n        if init_res.message_type != Types.INIT_RES:\n            raise errors.UnexpectedError(\n                \"Expected handshake response, got %s\" % repr(init_res)\n            )\n        self._extract_handshake_headers(init_res)\n        self._handshake_performed = True\n        self._loop()\n        raise tornado.gen.Return(init_res)",
    "docstring": "Initiate a handshake with the remote host.\n\n        :param headers:\n            A dictionary of headers to send.\n        :returns:\n            A future that resolves (with a value of None) when the handshake\n            is complete."
  },
  {
    "code": "def new_task(func):\n    @wraps(func)\n    async def wrapper(self, *args, **kwargs):\n        loop = get_event_loop()\n        loop.create_task(func(self, *args, **kwargs))\n    return wrapper",
    "docstring": "Runs the decorated function in a new task"
  },
  {
    "code": "def create_from(cls, another, **kwargs):\n        reused_fields = {}\n        for field, value in another.get_fields():\n            if field in cls.FIELDS:\n                reused_fields[field] = value\n        reused_fields.update(kwargs)\n        return cls(**reused_fields)",
    "docstring": "Create from another object of different type.\n\n        Another object must be from a derived class of SimpleObject (which\n        contains FIELDS)"
  },
  {
    "code": "def _check_version(self, request):\n        version = self._get_version(request)\n        if version and version != self.version:\n            raise Error('OAuth version %s not supported.' % str(version))",
    "docstring": "Verify the correct version of the request for this server."
  },
  {
    "code": "def is_cloudflare_challenge(response):\n        return (\n            response.status == 503\n            and response.headers.get('Server', '').startswith(b'cloudflare')\n            and 'jschl_vc' in response.text\n            and 'jschl_answer' in response.text\n        )",
    "docstring": "Test if the given response contains the cloudflare's anti-bot protection"
  },
  {
    "code": "def verifyWriteMode(files):\n    if not isinstance(files, list):\n        files = [files]\n    not_writable = []\n    writable = True\n    for fname in files:\n        try:\n            f = open(fname,'a')\n            f.close()\n            del f\n        except:\n            not_writable.append(fname)\n            writable = False\n    if not writable:\n        print('The following file(s) do not have write permission!')\n        for fname in not_writable:\n            print('    ', fname)\n    return writable",
    "docstring": "Checks whether files are writable. It is up to the calling routine to raise\n    an Exception, if desired.\n\n    This function returns True, if all files are writable and False, if any are\n    not writable.  In addition, for all files found to not be writable, it will\n    print out the list of names of affected files."
  },
  {
    "code": "def message(self, bot, comm):\n        super(KarmaAdv, self).message(bot, comm)\n        if not comm['directed'] and not comm['pm']:\n            msg = comm['message'].strip().lower()\n            words = self.regstr.findall(msg)\n            karmas = self.modify_karma(words)\n            if comm['user'] in karmas.keys():\n                if karmas[comm['user']] <= 0:\n                    bot.reply(comm, \"Don't be so hard on yourself.\")\n                else:\n                    bot.reply(comm, \"Tisk, tisk, no up'ing your own karma.\")\n            self.update_db(comm[\"user\"], karmas)",
    "docstring": "Check for strings ending with 2 or more '-' or '+'"
  },
  {
    "code": "def install_lib(url, replace_existing=False, fix_wprogram=True):\n    d = tmpdir(tmpdir())\n    f = download(url)\n    Archive(f).extractall(d)\n    clean_dir(d)\n    d, src_dlib = find_lib_dir(d)\n    move_examples(d, src_dlib)\n    fix_examples_dir(src_dlib)\n    if fix_wprogram:\n        fix_wprogram_in_files(src_dlib)\n    targ_dlib = libraries_dir() / src_dlib.name\n    if targ_dlib.exists():\n        log.debug('library already exists: %s', targ_dlib)\n        if replace_existing:\n            log.debug('remove %s', targ_dlib)\n            targ_dlib.rmtree()\n        else:\n            raise ConfduinoError('library already exists:' + targ_dlib)\n    log.debug('move %s -> %s', src_dlib, targ_dlib)\n    src_dlib.move(targ_dlib)\n    libraries_dir().copymode(targ_dlib)\n    for x in targ_dlib.walk():\n        libraries_dir().copymode(x)\n    return targ_dlib.name",
    "docstring": "install library from web or local files system.\n\n    :param url: web address or file path\n    :param replace_existing: bool\n    :rtype: None"
  },
  {
    "code": "def GetListCollection(self):\n        soap_request = soap('GetListCollection')\n        self.last_request = str(soap_request)\n        response = self._session.post(url=self._url('SiteData'),\n                                      headers=self._headers('GetListCollection'),\n                                      data=str(soap_request),\n                                      verify=self._verify_ssl,\n                                      timeout=self.timeout)\n        if response.status_code == 200:\n            envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))\n            result = envelope[0][0][0].text\n            lists = envelope[0][0][1]\n            data = []\n            for _list in lists:\n                _list_data = {}\n                for item in _list:\n                    key = item.tag.replace('{http://schemas.microsoft.com/sharepoint/soap/}', '')\n                    value = item.text\n                    _list_data[key] = value\n                data.append(_list_data)\n            return data\n        else:\n            return response",
    "docstring": "Returns List information for current Site"
  },
  {
    "code": "def _list_files(path, suffix=\"\"):\n  if os.path.isdir(path):\n    incomplete = os.listdir(path)\n    complete = [os.path.join(path, entry) for entry in incomplete]\n    lists = [_list_files(subpath, suffix) for subpath in complete]\n    flattened = []\n    for one_list in lists:\n      for elem in one_list:\n        flattened.append(elem)\n    return flattened\n  else:\n    assert os.path.exists(path), \"couldn't find file '%s'\" % path\n    if path.endswith(suffix):\n      return [path]\n    return []",
    "docstring": "Returns a list of all files ending in `suffix` contained within `path`.\n\n  Parameters\n  ----------\n  path : str\n      a filepath\n  suffix : str\n\n  Returns\n  -------\n  l : list\n      A list of all files ending in `suffix` contained within `path`.\n      (If `path` is a file rather than a directory, it is considered\n      to \"contain\" itself)"
  },
  {
    "code": "def is_new_preorder( self, preorder_hash, lastblock=None ):\n        if lastblock is None:\n            lastblock = self.lastblock \n        preorder = namedb_get_name_preorder( self.db, preorder_hash, lastblock )\n        if preorder is not None:\n            return False\n        else:\n            return True",
    "docstring": "Given a preorder hash of a name, determine whether or not it is unseen before."
  },
  {
    "code": "def pre_execute(self, execution, context):\n        path = self._fspath\n        if path:\n            path = path.format(\n                benchmark=context.benchmark,\n                api=execution['category'],\n                **execution.get('metas', {})\n            )\n            if self.clean_path:\n                shutil.rmtree(path, ignore_errors=True)\n            if execution['metas']['file_mode'] == 'onefile':\n                path = osp.dirname(path)\n            if not osp.exists(path):\n                os.makedirs(path)",
    "docstring": "Make sure the named directory is created if possible"
  },
  {
    "code": "def info(self, user_id):\n        resp = self._rtm_client.get('v1/user.info?user_id={}'.format(user_id))\n        if resp.is_fail():\n            raise RTMServiceError('Failed to get user information', resp)\n        return resp.data['result']",
    "docstring": "Gets user information by user id\n\n        Args:\n            user_id(int): the id of user\n\n        Returns:\n            User\n\n        Throws:\n            RTMServiceError when request failed"
  },
  {
    "code": "def restore_backup(\n            self, bootstrap=False, constraints=None, archive=None,\n            backup_id=None, upload_tools=False):\n        raise NotImplementedError()",
    "docstring": "Restore a backup archive to a new controller.\n\n        :param bool bootstrap: Bootstrap a new state machine\n        :param constraints: Model constraints\n        :type constraints: :class:`juju.Constraints`\n        :param str archive: Path to backup archive to restore\n        :param str backup_id: Id of backup to restore\n        :param bool upload_tools: Upload tools if bootstrapping a new machine"
  },
  {
    "code": "def nack(messageid, subscriptionid, transactionid=None):\n    header = 'subscription:%s\\nmessage-id:%s' % (subscriptionid, messageid)\n    if transactionid:\n        header += '\\ntransaction:%s' % transactionid\n    return \"NACK\\n%s\\n\\n\\x00\\n\" % header",
    "docstring": "STOMP negative acknowledge command.\n\n    NACK is the opposite of ACK. It is used to tell the server that the client\n    did not consume the message. The server can then either send the message to\n    a different client, discard it, or put it in a dead letter queue. The exact\n    behavior is server specific.\n\n    messageid:\n        This is the id of the message we are acknowledging,\n        what else could it be? ;)\n\n    subscriptionid:\n        This is the id of the subscription that applies to the message.\n\n    transactionid:\n        This is the id that all actions in this transaction\n        will have. If this is not given then a random UUID\n        will be generated for this."
  },
  {
    "code": "def settings(self) -> typing.Union[None, SharedCache]:\n        return self._project.settings if self._project else None",
    "docstring": "The settings associated with this project."
  },
  {
    "code": "def erase_disk_partitions(disk_id=None, scsi_address=None,\n                          service_instance=None):\n    if not disk_id and not scsi_address:\n        raise ArgumentValueError('Either \\'disk_id\\' or \\'scsi_address\\' '\n                                 'needs to be specified')\n    host_ref = _get_proxy_target(service_instance)\n    hostname = __proxy__['esxi.get_details']()['esxi_host']\n    if not disk_id:\n        scsi_address_to_lun = \\\n                salt.utils.vmware.get_scsi_address_to_lun_map(host_ref)\n        if scsi_address not in scsi_address_to_lun:\n            raise VMwareObjectRetrievalError(\n                'Scsi lun with address \\'{0}\\' was not found on host \\'{1}\\''\n                ''.format(scsi_address, hostname))\n        disk_id = scsi_address_to_lun[scsi_address].canonicalName\n        log.trace('[%s] Got disk id \\'%s\\' for scsi address \\'%s\\'',\n                  hostname, disk_id, scsi_address)\n    log.trace('Erasing disk partitions on disk \\'%s\\' in host \\'%s\\'',\n              disk_id, hostname)\n    salt.utils.vmware.erase_disk_partitions(service_instance,\n                                            host_ref, disk_id,\n                                            hostname=hostname)\n    log.info('Erased disk partitions on disk \\'%s\\' on host \\'%s\\'',\n             disk_id, hostname)\n    return True",
    "docstring": "Erases the partitions on a disk.\n    The disk can be specified either by the canonical name, or by the\n    scsi_address.\n\n    disk_id\n        Canonical name of the disk.\n        Either ``disk_id`` or ``scsi_address`` needs to be specified\n        (``disk_id`` supersedes ``scsi_address``.\n\n    scsi_address\n        Scsi address of the disk.\n        ``disk_id`` or ``scsi_address`` needs to be specified\n        (``disk_id`` supersedes ``scsi_address``.\n\n    service_instance\n        Service instance (vim.ServiceInstance) of the vCenter/ESXi host.\n        Default is None.\n\n    .. code-block:: bash\n\n        salt '*' vsphere.erase_disk_partitions scsi_address='vmhaba0:C0:T0:L0'\n\n        salt '*' vsphere.erase_disk_partitions disk_id='naa.000000000000001'"
  },
  {
    "code": "def _on_status_message(self, sequence, topic, message):\n        self._logger.debug(\"Received message on (topic=%s): %s\" % (topic, message))\n        try:\n            conn_key = self._find_connection(topic)\n        except ArgumentError:\n            self._logger.warn(\"Dropping message that does not correspond with a known connection, message=%s\", message)\n            return\n        if messages.ConnectionResponse.matches(message):\n            if self.name != message['client']:\n                self._logger.debug(\"Connection response received for a different client, client=%s, name=%s\", message['client'], self.name)\n                return\n            self.conns.finish_connection(conn_key, message['success'], message.get('failure_reason', None))\n        else:\n            self._logger.warn(\"Dropping message that did not correspond with a known schema, message=%s\", message)",
    "docstring": "Process a status message received\n\n        Args:\n            sequence (int): The sequence number of the packet received\n            topic (string): The topic this message was received on\n            message (dict): The message itself"
  },
  {
    "code": "def new_consumer(self, config, consumer_name):\n        return Consumer(0,\n                        dict(),\n                        config.get('qty', self.DEFAULT_CONSUMER_QTY),\n                        config.get('queue', consumer_name))",
    "docstring": "Return a consumer dict for the given name and configuration.\n\n        :param dict config: The consumer configuration\n        :param str consumer_name: The consumer name\n        :rtype: dict"
  },
  {
    "code": "def notGroup (states, *stateIndexPairs):\n    start, dead = group(states, *stateIndexPairs)\n    finish = len(states)\n    states.append([])\n    states[start].append((DEFAULT, finish))\n    return start, finish",
    "docstring": "Like group, but will add a DEFAULT transition to a new end state,\n    causing anything in the group to not match by going to a dead state.\n    XXX I think this is right..."
  },
  {
    "code": "def add_field_value(self, field, value):\n        super(Issue, self).update(fields={\"update\": {field: [{\"add\": value}]}})",
    "docstring": "Add a value to a field that supports multiple values, without resetting the existing values.\n\n        This should work with: labels, multiple checkbox lists, multiple select\n\n        :param field: The field name\n        :param value: The field's value\n\n        :type field: str"
  },
  {
    "code": "def sync(self):\n        self._elk.add_handler('VN', self._vn_handler)\n        self._elk.add_handler('XK', self._xk_handler)\n        self._elk.add_handler('RP', self._rp_handler)\n        self._elk.add_handler('IE', self._elk.call_sync_handlers)\n        self._elk.add_handler('SS', self._ss_handler)\n        self._elk.send(vn_encode())\n        self._elk.send(lw_encode())\n        self._elk.send(ss_encode())",
    "docstring": "Retrieve panel information from ElkM1"
  },
  {
    "code": "def startswith(self, pat):\n        check_type(pat, str)\n        return _series_bool_result(self, weld_str_startswith, pat=pat)",
    "docstring": "Test if elements start with pat.\n\n        Parameters\n        ----------\n        pat : str\n\n        Returns\n        -------\n        Series"
  },
  {
    "code": "def _getgroup(string, depth):\n    out, comma = [], False\n    while string:\n        items, string = _getitem(string, depth)\n        if not string:\n            break\n        out += items\n        if string[0] == '}':\n            if comma:\n                return out, string[1:]\n            return ['{' + a + '}' for a in out], string[1:]\n        if string[0] == ',':\n            comma, string = True, string[1:]\n    return None",
    "docstring": "Get a group from the string, where group is a list of all the comma\n    separated substrings up to the next '}' char or the brace enclosed substring\n    if there is no comma"
  },
  {
    "code": "def do_child_watch(self, params):\n        get_child_watcher(self._zk, print_func=self.show_output).update(\n            params.path, params.verbose)",
    "docstring": "\\x1b[1mNAME\\x1b[0m\n        child_watch - Watch a path for child changes\n\n\\x1b[1mSYNOPSIS\\x1b[0m\n        child_watch <path> [verbose]\n\n\\x1b[1mOPTIONS\\x1b[0m\n        * verbose: prints list of znodes (default: false)\n\n\\x1b[1mEXAMPLES\\x1b[0m\n        # only prints the current number of children\n        > child_watch /\n\n        # prints num of children along with znodes listing\n        > child_watch / true"
  },
  {
    "code": "def load_file_or_hdu(filename):\n    if isinstance(filename, fits.HDUList):\n        hdulist = filename\n    else:\n        hdulist = fits.open(filename, ignore_missing_end=True)\n    return hdulist",
    "docstring": "Load a file from disk and return an HDUList\n    If filename is already an HDUList return that instead\n\n    Parameters\n    ----------\n    filename : str or HDUList\n        File or HDU to be loaded\n\n    Returns\n    -------\n    hdulist : HDUList"
  },
  {
    "code": "def insert_node_node(**kw):\n    with current_app.app_context():\n        insert_query(name='select_link_node_from_node.sql', node_id=kw.get('node_id'))\n        db.execute(text(fetch_query_string('insert_node_node.sql')), **kw)",
    "docstring": "Link a node to another node. node_id -> target_node_id.  Where `node_id` is\n    the parent and `target_node_id` is the child."
  },
  {
    "code": "def getSbus(self, buses=None):\n        bs = self.buses if buses is None else buses\n        s = array([self.s_surplus(v) / self.base_mva for v in bs])\n        return s",
    "docstring": "Returns the net complex bus power injection vector in p.u."
  },
  {
    "code": "def create_db_user(username, password=None, flags=None):\n    flags = flags or u'-D -A -R'\n    sudo(u'createuser %s %s' % (flags, username), user=u'postgres')\n    if password:\n        change_db_user_password(username, password)",
    "docstring": "Create a databse user."
  },
  {
    "code": "def schedule_ping_frequency(self):\n        \"Send a ping message to slack every 20 seconds\"\n        ping = crontab('* * * * * */20', func=self.send_ping, start=False)\n        ping.start()",
    "docstring": "Send a ping message to slack every 20 seconds"
  },
  {
    "code": "def get_float(self, input_string):\n        if input_string == '--training_fraction':\n            try:\n                index = self.args.index(input_string) + 1\n            except ValueError:\n                return None\n            try:\n                if self.args[index] in self.flags:\n                    print(\"\\n {flag} was set but a value was not specified\".format(flag=input_string))\n                    print_short_help()\n                    sys.exit(1)\n            except IndexError:\n                print(\"\\n {flag} was set but a value was not specified\".format(flag=input_string))\n                print_short_help()\n                sys.exit(1)\n            try:\n                value = float(self.args[index])\n            except ValueError:\n                print(\"\\n {flag} must be a float less than or equal to 1, e.g. 0.4\".format(flag=input_string))\n                print_short_help()\n                sys.exit(1)\n            if value > 1.0 or value < 0:\n                print(\"\\n {flag} must be a float less than or equal to 1, e.g. 0.4\".format(flag=input_string))\n                print_short_help()\n                sys.exit(1)\n            return value",
    "docstring": "Return float type user input"
  },
  {
    "code": "def advanced_search(self, terms, relation=None, index=0, limit=25, **kwargs):\n        assert isinstance(terms, dict), \"terms must be a dict\"\n        query = \" \".join(sorted(['{}:\"{}\"'.format(k, v) for (k, v) in terms.items()]))\n        return self.get_object(\n            \"search\", relation=relation, q=query, index=index, limit=limit, **kwargs\n        )",
    "docstring": "Advanced search of track, album or artist.\n\n        See `Search section of Deezer API\n        <https://developers.deezer.com/api/search>`_ for search terms.\n\n        :returns: a list of :class:`~deezer.resources.Resource` objects.\n\n        >>> client.advanced_search({\"artist\": \"Daft Punk\", \"album\": \"Homework\"})\n        >>> client.advanced_search({\"artist\": \"Daft Punk\", \"album\": \"Homework\"},\n        ...                        relation=\"track\")"
  },
  {
    "code": "def delete_user(self, user):\n        user_id = utils.get_id(user)\n        uri = \"users/%s\" % user_id\n        resp, resp_body = self.method_delete(uri)\n        if resp.status_code == 404:\n            raise exc.UserNotFound(\"User '%s' does not exist.\" % user)\n        elif resp.status_code in (401, 403):\n            raise exc.AuthorizationFailure(\"You are not authorized to delete \"\n                    \"users.\")",
    "docstring": "ADMIN ONLY. Removes the user from the system. There is no 'undo'\n        available, so you should be certain that the user specified is the user\n        you wish to delete."
  },
  {
    "code": "def stop(self):\n        try:\n            self.aitask.stop()\n            self.aotask.stop()\n            pass\n        except:     \n            print u\"No task running\"\n        self.aitask = None\n        self.aotask = None",
    "docstring": "Halts the acquisition, this must be called before resetting acquisition"
  },
  {
    "code": "def save(self):\n        content = self.dumps()\n        fileutils.save_text_to_file(content, self.file_path)",
    "docstring": "Saves the settings contents"
  },
  {
    "code": "def syllabify(self, hierarchy):\n        if len(self.long_lines) == 0:\n            logger.error(\"No text was imported\")\n            self.syllabified_text = []\n        else:\n            syllabifier = Syllabifier(language=\"old_norse\", break_geminants=True)\n            syllabifier.set_hierarchy(hierarchy)\n            syllabified_text = []\n            for i, long_line in enumerate(self.long_lines):\n                syllabified_text.append([])\n                for short_line in long_line:\n                    assert isinstance(short_line, ShortLine) or isinstance(short_line, LongLine)\n                    short_line.syllabify(syllabifier)\n                    syllabified_text[i].append(short_line.syllabified)\n            self.syllabified_text = syllabified_text",
    "docstring": "Syllables may play a role in verse classification."
  },
  {
    "code": "def comment_lines(lines, prefix):\n    if not prefix:\n        return lines\n    return [prefix + ' ' + line if line else prefix for line in lines]",
    "docstring": "Return commented lines"
  },
  {
    "code": "def _build_object_table(self):\n        types = self.domain.types\n        objects = dict(self.non_fluents.objects)\n        self.object_table = dict()\n        for name, value in self.domain.types:\n            if value == 'object':\n                objs = objects[name]\n                idx = { obj: i for i, obj in enumerate(objs) }\n                self.object_table[name] = {\n                    'size': len(objs),\n                    'idx': idx,\n                    'objects': objs\n                }",
    "docstring": "Builds the object table for each RDDL type."
  },
  {
    "code": "def list_poll_choices_in_poll(self, poll_id):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"poll_id\"] = poll_id\r\n        self.logger.debug(\"GET /api/v1/polls/{poll_id}/poll_choices with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"GET\", \"/api/v1/polls/{poll_id}/poll_choices\".format(**path), data=data, params=params, no_data=True)",
    "docstring": "List poll choices in a poll.\r\n\r\n        Returns the list of PollChoices in this poll."
  },
  {
    "code": "def get_async(self, **ctx_options):\n    from . import model, tasklets\n    ctx = tasklets.get_context()\n    cls = model.Model._kind_map.get(self.kind())\n    if cls:\n      cls._pre_get_hook(self)\n    fut = ctx.get(self, **ctx_options)\n    if cls:\n      post_hook = cls._post_get_hook\n      if not cls._is_default_hook(model.Model._default_post_get_hook,\n                                  post_hook):\n        fut.add_immediate_callback(post_hook, self, fut)\n    return fut",
    "docstring": "Return a Future whose result is the entity for this Key.\n\n    If no such entity exists, a Future is still returned, and the\n    Future's eventual return result be None."
  },
  {
    "code": "def render_inner(self, token):\n        rendered = [self.render(child) for child in token.children]\n        return ''.join(rendered)",
    "docstring": "Recursively renders child tokens. Joins the rendered\n        strings with no space in between.\n\n        If newlines / spaces are needed between tokens, add them\n        in their respective templates, or override this function\n        in the renderer subclass, so that whitespace won't seem to\n        appear magically for anyone reading your program.\n\n        Arguments:\n            token: a branch node who has children attribute."
  },
  {
    "code": "def rpy(self):\n    x, y, z, w = self.x, self.y, self.z, self.w\n    roll = math.atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z)\n    pitch = math.atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z)\n    yaw = math.asin(2*x*y + 2*z*w)\n    return (roll, pitch, yaw)",
    "docstring": "Calculates the Roll, Pitch and Yaw of the Quaternion."
  },
  {
    "code": "def plot_residuals(self, plot=None):\n        if plot is None:\n            import matplotlib.pyplot as plot\n        x = numpy.arange(1, len(self.residuals) + 1)\n        y = _gvar.mean(self.residuals)\n        yerr = _gvar.sdev(self.residuals)\n        plot.errorbar(x=x, y=y, yerr=yerr, fmt='o', color='b')\n        plot.ylabel('normalized residuals')\n        xr = [x[0], x[-1]]\n        plot.plot([x[0], x[-1]], [0, 0], 'r-')\n        plot.fill_between(\n            x=xr, y1=[-1,-1], y2=[1,1], color='r', alpha=0.075\n            )\n        return plot",
    "docstring": "Plot normalized fit residuals.\n\n        The sum of the squares of the residuals equals ``self.chi2``.\n        Individual residuals should be distributed about one, in\n        a Gaussian distribution.\n\n        Args:\n            plot: :mod:`matplotlib` plotter. If ``None``, uses\n                ``matplotlib.pyplot`.\n\n        Returns:\n            Plotter ``plot``."
  },
  {
    "code": "def get_penalty_model(specification):\n    feasible_configurations = specification.feasible_configurations\n    if specification.vartype is dimod.BINARY:\n        feasible_configurations = {tuple(2 * v - 1 for v in config): en\n                                   for config, en in iteritems(feasible_configurations)}\n    ising_quadratic_ranges = specification.ising_quadratic_ranges\n    quadratic_ranges = {(u, v): ising_quadratic_ranges[u][v] for u, v in specification.graph.edges}\n    try:\n        bqm, gap = generate_bqm(specification.graph, feasible_configurations,\n                                specification.decision_variables,\n                                linear_energy_ranges=specification.ising_linear_ranges,\n                                quadratic_energy_ranges=quadratic_ranges,\n                                min_classical_gap=specification.min_classical_gap)\n    except ValueError:\n        raise pm.exceptions.FactoryException(\"Specification is for too large of a model\")\n    return pm.PenaltyModel.from_specification(specification, bqm, gap, 0.0)",
    "docstring": "Factory function for penaltymodel-lp.\n\n    Args:\n        specification (penaltymodel.Specification): The specification\n            for the desired penalty model.\n\n    Returns:\n        :class:`penaltymodel.PenaltyModel`: Penalty model with the given specification.\n\n    Raises:\n        :class:`penaltymodel.ImpossiblePenaltyModel`: If the penalty cannot be built.\n\n    Parameters:\n        priority (int): -100"
  },
  {
    "code": "def http_method(self, method):\n        self.build_url()\n        try:\n            response = self.get_http_method(method)\n            is_success = response.ok\n            try:\n                response_message = response.json()\n            except ValueError:\n                response_message = response.text\n        except requests.exceptions.RequestException as exc:\n            is_success = False\n            response_message = exc.args\n        return is_success, response_message",
    "docstring": "Execute the given HTTP method and returns if it's success or not\n        and the response as a string if not success and as python object after\n        unjson if it's success."
  },
  {
    "code": "def _vertex_one_color_qubo(x_vars):\n    Q = {}\n    for v in x_vars:\n        for color in x_vars[v]:\n            idx = x_vars[v][color]\n            Q[(idx, idx)] = -1\n        for color0, color1 in itertools.combinations(x_vars[v], 2):\n            idx0 = x_vars[v][color0]\n            idx1 = x_vars[v][color1]\n            Q[(idx0, idx1)] = 2\n    return Q",
    "docstring": "For each vertex, it should have exactly one color. Generates\n    the QUBO to enforce this constraint.\n\n    Notes\n    -----\n    Does not enforce neighboring vertices having different colors.\n\n    Ground energy is -1 * |G|, infeasible gap is 1."
  },
  {
    "code": "def date_0utc(date):\n    return ee.Date.fromYMD(date.get('year'), date.get('month'),\n                           date.get('day'))",
    "docstring": "Get the 0 UTC date for a date\n\n    Parameters\n    ----------\n    date : ee.Date\n\n    Returns\n    -------\n    ee.Date"
  },
  {
    "code": "def container_device_add(name, device_name, device_type='disk',\n                         remote_addr=None,\n                         cert=None, key=None, verify_cert=True,\n                         **kwargs):\n    container = container_get(\n        name, remote_addr, cert, key, verify_cert, _raw=True\n    )\n    kwargs['type'] = device_type\n    return _set_property_dict_item(\n        container, 'devices', device_name, kwargs\n    )",
    "docstring": "Add a container device\n\n    name :\n        Name of the container\n\n    device_name :\n        The device name to add\n\n    device_type :\n        Type of the device\n\n    ** kwargs :\n        Additional device args\n\n    remote_addr :\n        An URL to a remote Server, you also have to give cert and key if\n        you provide remote_addr and its a TCP Address!\n\n        Examples:\n            https://myserver.lan:8443\n            /var/lib/mysocket.sock\n\n    cert :\n        PEM Formatted SSL Certificate.\n\n        Examples:\n            ~/.config/lxc/client.crt\n\n    key :\n        PEM Formatted SSL Key.\n\n        Examples:\n            ~/.config/lxc/client.key\n\n    verify_cert : True\n        Wherever to verify the cert, this is by default True\n        but in the most cases you want to set it off as LXD\n        normaly uses self-signed certificates."
  },
  {
    "code": "def _preprocessContaminantOutFilePath(outPath):\n        if '/' in outPath:\n            splitPath = outPath.split('/')\n        elif '\\\\' in outPath:\n            splitPath = outPath.split('\\\\')\n        else:\n            splitPath = [outPath, ]\n        if splitPath[-1] == '':\n            outputFilename = splitPath[-2]\n        else:\n            outputFilename = splitPath[-1]\n        if '.' in outputFilename:\n            outputFilename = outputFilename.split('.')[0]\n        return outputFilename",
    "docstring": "Preprocess the contaminant output file path to a relative path."
  },
  {
    "code": "def is_topk(self, topk=10, reverse=False):\n        with cython_context():\n            return SArray(_proxy = self.__proxy__.topk_index(topk, reverse))",
    "docstring": "Create an SArray indicating which elements are in the top k.\n\n        Entries are '1' if the corresponding element in the current SArray is a\n        part of the top k elements, and '0' if that corresponding element is\n        not. Order is descending by default.\n\n        Parameters\n        ----------\n        topk : int\n            The number of elements to determine if 'top'\n\n        reverse : bool\n            If True, return the topk elements in ascending order\n\n        Returns\n        -------\n        out : SArray (of type int)\n\n        Notes\n        -----\n        This is used internally by SFrame's topk function."
  },
  {
    "code": "def model_saved(sender, instance,\n                        created,\n                        raw,\n                        using,\n                        **kwargs):\n    opts = get_opts(instance)\n    model = '.'.join([opts.app_label, opts.object_name])\n    action = 'created' if created else 'updated'\n    distill_model_event(instance, model, action)",
    "docstring": "Automatically triggers \"created\" and \"updated\" actions."
  },
  {
    "code": "def iter_links_element_text(cls, element):\n        if element.text:\n            link_type = identify_link_type(element.text)\n            yield LinkInfo(\n                element=element, tag=element.tag, attrib=None,\n                link=element.text,\n                inline=False, linked=True,\n                base_link=None,\n                value_type='plain',\n                link_type=link_type\n            )",
    "docstring": "Get the element text as a link."
  },
  {
    "code": "def create_classifier(self, metadata, training_data, **kwargs):\n        if metadata is None:\n            raise ValueError('metadata must be provided')\n        if training_data is None:\n            raise ValueError('training_data must be provided')\n        headers = {}\n        if 'headers' in kwargs:\n            headers.update(kwargs.get('headers'))\n        sdk_headers = get_sdk_headers('natural_language_classifier', 'V1',\n                                      'create_classifier')\n        headers.update(sdk_headers)\n        form_data = {}\n        form_data['training_metadata'] = (None, metadata, 'application/json')\n        form_data['training_data'] = (None, training_data, 'text/csv')\n        url = '/v1/classifiers'\n        response = self.request(\n            method='POST',\n            url=url,\n            headers=headers,\n            files=form_data,\n            accept_json=True)\n        return response",
    "docstring": "Create classifier.\n\n        Sends data to create and train a classifier and returns information about the new\n        classifier.\n\n        :param file metadata: Metadata in JSON format. The metadata identifies the\n        language of the data, and an optional name to identify the classifier. Specify the\n        language with the 2-letter primary language code as assigned in ISO standard 639.\n        Supported languages are English (`en`), Arabic (`ar`), French (`fr`), German,\n        (`de`), Italian (`it`), Japanese (`ja`), Korean (`ko`), Brazilian Portuguese\n        (`pt`), and Spanish (`es`).\n        :param file training_data: Training data in CSV format. Each text value must have\n        at least one class. The data can include up to 3,000 classes and 20,000 records.\n        For details, see [Data\n        preparation](https://cloud.ibm.com/docs/services/natural-language-classifier/using-your-data.html).\n        :param dict headers: A `dict` containing the request headers\n        :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n        :rtype: DetailedResponse"
  },
  {
    "code": "def import_pf_config(self):\n        scenario = cfg_ding0.get(\"powerflow\", \"test_grid_stability_scenario\")\n        start_hour = int(cfg_ding0.get(\"powerflow\", \"start_hour\"))\n        end_hour = int(cfg_ding0.get(\"powerflow\", \"end_hour\"))\n        start_time = datetime(1970, 1, 1, 00, 00, 0)\n        resolution = cfg_ding0.get(\"powerflow\", \"resolution\")\n        srid = str(int(cfg_ding0.get('geo', 'srid')))\n        return PFConfigDing0(scenarios=[scenario],\n                             timestep_start=start_time,\n                             timesteps_count=end_hour-start_hour,\n                             srid=srid,\n                             resolution=resolution)",
    "docstring": "Creates power flow config class and imports config from file\n\n        Returns\n        -------\n        PFConfigDing0\n            PFConfigDing0 object"
  },
  {
    "code": "def get_group_id(self, uuid=None):\n        group_data = self.get_group(uuid)\n        try:\n            return group_data['response']['docs'][0]['id']\n        except (KeyError, IndexError):\n            failure_message = ('Error in get_group response data - '\n                               'got {0}'.format(group_data))\n            log.exception(failure_message)\n            raise PyLmodUnexpectedData(failure_message)",
    "docstring": "Get group id based on uuid.\n\n        Args:\n            uuid (str): optional uuid. defaults to self.cuuid\n\n        Raises:\n            PyLmodUnexpectedData: No group data was returned.\n            requests.RequestException: Exception connection error\n\n        Returns:\n            int: numeric group id"
  },
  {
    "code": "def rshift_arithmetic(self, shift_amount):\n        lower, upper = self._pre_shift(shift_amount)\n        ret = None\n        for amount in xrange(lower, upper + 1):\n            si_ = self._rshift_arithmetic(amount)\n            ret = si_ if ret is None else ret.union(si_)\n        ret.normalize()\n        ret.uninitialized = self.uninitialized\n        return ret",
    "docstring": "Arithmetic shift right.\n\n        :param StridedInterval shift_amount: The amount of shifting\n        :return: The shifted StridedInterval\n        :rtype: StridedInterval"
  },
  {
    "code": "def put(path, obj):\n    try:\n        import cPickle as pickle\n    except:\n        import pickle\n    with open(path, 'wb') as file:\n        return pickle.dump(obj, file)",
    "docstring": "Write an object to file"
  },
  {
    "code": "def update_bgp_speaker(self, bgp_speaker_id, body=None):\n        return self.put(self.bgp_speaker_path % bgp_speaker_id, body=body)",
    "docstring": "Update a BGP speaker."
  },
  {
    "code": "def has_too_few_calls(self):\n        if self.has_exact and self._call_count < self._exact:\n            return True\n        if self.has_minimum and self._call_count < self._minimum:\n            return True\n        return False",
    "docstring": "Test if there have not been enough calls\n\n        :rtype boolean"
  },
  {
    "code": "def __is_surrogate_escaped(self, text):\n        try:\n            text.encode('utf-8')\n        except UnicodeEncodeError as e:\n            if e.reason == 'surrogates not allowed':\n                return True\n        return False",
    "docstring": "Checks if surrogate is escaped"
  },
  {
    "code": "def repr_tree(self):\n        import utool as ut\n        import networkx as nx\n        repr_tree = nx.DiGraph()\n        for u, v in ut.itertwo(self.values()):\n            if not repr_tree.has_edge(v, u):\n                repr_tree.add_edge(u, v)\n        return repr_tree",
    "docstring": "reconstruct represented tree as a DiGraph to\n        preserve the current rootedness"
  },
  {
    "code": "def clear_adb_log(self):\n        try:\n            self._ad.adb.logcat('-c')\n        except adb.AdbError as e:\n            if b'failed to clear' in e.stderr:\n                self._ad.log.warning(\n                    'Encountered known Android error to clear logcat.')\n            else:\n                raise",
    "docstring": "Clears cached adb content."
  },
  {
    "code": "def bsrchd(value, ndim, array):\n    value = ctypes.c_double(value)\n    ndim = ctypes.c_int(ndim)\n    array = stypes.toDoubleVector(array)\n    return libspice.bsrchd_c(value, ndim, array)",
    "docstring": "Do a binary search for a key value within a double precision array,\n    assumed to be in increasing order. Return the index of the matching\n    array entry, or -1 if the key value is not found.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchd_c.html\n\n    :param value: Value to find in array.\n    :type value: float\n    :param ndim: Dimension of array.\n    :type ndim: int\n    :param array: Array to be searched.\n    :type array: Array of floats\n    :return: index\n    :rtype: int"
  },
  {
    "code": "def remote_urls(self):\n        cmd = 'git config -l | grep \"url\"'\n        return self.sh(cmd,\n                       shell=True,\n                       ignore_error=True).strip()",
    "docstring": "Get all configured remote urls for this Repository\n\n        Returns:\n            str: primary remote url for this Repository\n                (``git config -l | grep \"url\"``)"
  },
  {
    "code": "def make_elements(tokens, text, start=0, end=None, fallback=None):\n    result = []\n    end = end or len(text)\n    prev_end = start\n    for token in tokens:\n        if prev_end < token.start:\n            result.append(fallback(text[prev_end:token.start]))\n        result.append(token.as_element())\n        prev_end = token.end\n    if prev_end < end:\n        result.append(fallback(text[prev_end:end]))\n    return result",
    "docstring": "Make elements from a list of parsed tokens.\n    It will turn all unmatched holes into fallback elements.\n\n    :param tokens: a list of parsed tokens.\n    :param text: the original tet.\n    :param start: the offset of where parsing starts. Defaults to the start of text.\n    :param end: the offset of where parsing ends. Defauls to the end of text.\n    :param fallback: fallback element type.\n    :returns: a list of inline elements."
  },
  {
    "code": "def chput(local_path=None, remote_path=None, user=None, group=None,\n          mode=None, use_sudo=True, mirror_local_mode=False, check=True):\n    result = None\n    if env.get('full') or not check or diff(local_path, remote_path):\n        result = put(local_path, remote_path, use_sudo,\n                     mirror_local_mode, mode)\n    with hide('commands'):\n        chown(remote_path, user, group)\n    return result",
    "docstring": "Put file and set user and group ownership.  Default to use sudo."
  },
  {
    "code": "def _normalize_bbox(self, bbox, size):\n        bbox_ratio = float(bbox.width) / float(bbox.height)\n        size_ratio = float(size[0]) / float(size[1])\n        if round(size_ratio, 4) == round(bbox_ratio, 4):\n            return bbox\n        else:\n            if bbox.height * size_ratio >= bbox.width:\n                diff = bbox.height*size_ratio - bbox.width\n                return BBox((bbox.xmin - diff/2, bbox.ymin, bbox.xmax + diff/2, bbox.ymax), bbox.projection)\n            else:\n                diff = abs(bbox.width/size_ratio - bbox.height)\n                return BBox((bbox.xmin, bbox.ymin - diff/2, bbox.xmax, bbox.ymax + diff/2), bbox.projection)",
    "docstring": "Returns this bbox normalized to match the ratio of the given size."
  },
  {
    "code": "def update(self):\n        self.kSS = 1.0\n        self.MSS = 1.0\n        self.KtoLnow_init = self.kSS\n        self.Rfunc = ConstantFunction(self.Rfree)\n        self.wFunc = ConstantFunction(self.wRte)\n        self.RfreeNow_init = self.Rfunc(self.kSS)\n        self.wRteNow_init = self.wFunc(self.kSS)\n        self.MaggNow_init = self.kSS\n        self.AaggNow_init = self.kSS\n        self.PermShkAggNow_init = 1.0\n        self.TranShkAggNow_init = 1.0\n        self.makeAggShkDstn()\n        self.AFunc = ConstantFunction(1.0)",
    "docstring": "Use primitive parameters to set basic objects.  This is an extremely stripped-down version\n        of update for CobbDouglasEconomy.\n\n        Parameters\n        ----------\n        none\n\n        Returns\n        -------\n        none"
  },
  {
    "code": "def api_headers(self, value):\n        value = validators.validate_api_headers(\"api_headers\", value)\n        self._set_option(\"api_headers\", value)",
    "docstring": "Set value for API headers."
  },
  {
    "code": "def Error(filename, linenum, category, confidence, message):\n  if _ShouldPrintError(category, confidence, linenum):\n    _cpplint_state.IncrementErrorCount(category)\n    if _cpplint_state.output_format == 'vs7':\n      sys.stderr.write('%s(%s):  %s  [%s] [%d]\\n' % (\n          filename, linenum, message, category, confidence))\n    elif _cpplint_state.output_format == 'eclipse':\n      sys.stderr.write('%s:%s: warning: %s  [%s] [%d]\\n' % (\n          filename, linenum, message, category, confidence))\n    else:\n      sys.stderr.write('%s:%s:  %s  [%s] [%d]\\n' % (\n          filename, linenum, message, category, confidence))",
    "docstring": "Logs the fact we've found a lint error.\n\n  We log where the error was found, and also our confidence in the error,\n  that is, how certain we are this is a legitimate style regression, and\n  not a misidentification or a use that's sometimes justified.\n\n  False positives can be suppressed by the use of\n  \"cpplint(category)\"  comments on the offending line.  These are\n  parsed into _error_suppressions.\n\n  Args:\n    filename: The name of the file containing the error.\n    linenum: The number of the line containing the error.\n    category: A string used to describe the \"category\" this bug\n      falls under: \"whitespace\", say, or \"runtime\".  Categories\n      may have a hierarchy separated by slashes: \"whitespace/indent\".\n    confidence: A number from 1-5 representing a confidence score for\n      the error, with 5 meaning that we are certain of the problem,\n      and 1 meaning that it could be a legitimate construct.\n    message: The error message."
  },
  {
    "code": "def execute_request(server_url, creds, namespace, classname):\n    print('Requesting url=%s, ns=%s, class=%s' % \\\n        (server_url, namespace, classname))\n    try:\n        CONN = WBEMConnection(server_url, creds,\n                              default_namespace=namespace,\n                              no_verification=True)\n        INSTANCES = CONN.EnumerateInstances(classname)\n        print('instances type=%s len=%s' % (type(INSTANCES),\n                                            len(INSTANCES)))\n        for inst in INSTANCES:\n            print('path=%s\\n' % inst.path)\n            print(inst.tomof())\n    except Error as err:\n        if isinstance(err, CIMError):\n            print('Operation Failed: CIMError: code=%s, Description=%s' % \\\n                  (err.status_code_name, err.status_description))\n        else:\n            print (\"Operation failed: %s\" % err)\n        sys.exit(1)",
    "docstring": "Open a connection with the server_url and creds, and\n        enumerate instances defined by the functions namespace and\n        classname arguments.\n        Displays either the error return or the mof for instances\n        returned."
  },
  {
    "code": "def image_to_string(image, lang=None, boxes=False):\n    input_file_name = '%s.bmp' % tempnam()\n    output_file_name_base = tempnam()\n    if not boxes:\n        output_file_name = '%s.txt' % output_file_name_base\n    else:\n        output_file_name = '%s.box' % output_file_name_base\n    try:\n        image.save(input_file_name)\n        status, error_string = run_tesseract(input_file_name,\n                                             output_file_name_base,\n                                             lang=lang,\n                                             boxes=boxes)\n        if status:\n            errors = get_errors(error_string)\n            raise TesseractError(status, errors)\n        f = file(output_file_name)\n        try:\n            return f.read().strip()\n        finally:\n            f.close()\n    finally:\n        cleanup(input_file_name)\n        cleanup(output_file_name)",
    "docstring": "Runs tesseract on the specified image. First, the image is written to disk,\n    and then the tesseract command is run on the image. Resseract's result is\n    read, and the temporary files are erased."
  },
  {
    "code": "def get_objective_form(self, *args, **kwargs):\n        if isinstance(args[-1], list) or 'objective_record_types' in kwargs:\n            return self.get_objective_form_for_create(*args, **kwargs)\n        else:\n            return self.get_objective_form_for_update(*args, **kwargs)",
    "docstring": "Pass through to provider ObjectiveAdminSession.get_objective_form_for_update"
  },
  {
    "code": "def random_name_gen(size=6):\n    return ''.join(\n        [random.choice(string.ascii_uppercase)] +\n        [random.choice(string.ascii_uppercase + string.digits) for i in range(size - 1)]\n    ) if size > 0 else ''",
    "docstring": "Generate a random python attribute name."
  },
  {
    "code": "def get_consumption(self):\n        self.get_status()\n        try:\n            self.consumption = self.data['power']\n        except TypeError:\n            self.consumption = 0\n        return self.consumption",
    "docstring": "Get current power consumption in mWh."
  },
  {
    "code": "def _read_country_names(self, countries_file=None):\n        if not countries_file:\n            countries_file = os.path.join(os.path.dirname(__file__), self.COUNTRY_FILE_DEFAULT)\n        with open(countries_file) as f:\n            countries_json = f.read()\n        return json.loads(countries_json)",
    "docstring": "Read list of countries from specified country file or default file."
  },
  {
    "code": "def maybe_cythonize(extensions, *args, **kwargs):\n    if len(sys.argv) > 1 and 'clean' in sys.argv:\n        return extensions\n    if not cython:\n        return extensions\n    numpy_incl = pkg_resources.resource_filename('numpy', 'core/include')\n    for ext in extensions:\n        if (hasattr(ext, 'include_dirs') and\n                numpy_incl not in ext.include_dirs):\n            ext.include_dirs.append(numpy_incl)\n    build_ext.render_templates(_pxifiles)\n    return cythonize(extensions, *args, **kwargs)",
    "docstring": "Render tempita templates before calling cythonize"
  },
  {
    "code": "def try_int(o:Any)->Any:\n    \"Try to convert `o` to int, default to `o` if not possible.\"\n    if isinstance(o, (np.ndarray,Tensor)): return o if o.ndim else int(o)\n    if isinstance(o, collections.Sized) or getattr(o,'__array_interface__',False): return o\n    try: return int(o)\n    except: return o",
    "docstring": "Try to convert `o` to int, default to `o` if not possible."
  },
  {
    "code": "def _check_list_props(self, inst: \"InstanceNode\") -> None:\n        if self.keys:\n            self._check_keys(inst)\n        for u in self.unique:\n            self._check_unique(u, inst)",
    "docstring": "Check uniqueness of keys and \"unique\" properties, if applicable."
  },
  {
    "code": "def find_free(cls, vrf, args):\n        xmlrpc = XMLRPCConnection()\n        q = {\n            'args': args,\n            'auth': AuthOptions().options\n        }\n        if isinstance(vrf, VRF):\n            q['vrf'] = { 'id': vrf.id }\n        elif vrf is None:\n            q['vrf'] = None\n        else:\n            raise NipapValueError('vrf parameter must be instance of VRF class')\n        try:\n            find_res = xmlrpc.connection.find_free_prefix(q)\n        except xmlrpclib.Fault as xml_fault:\n            raise _fault_to_exception(xml_fault)\n        pass\n        return find_res",
    "docstring": "Finds a free prefix.\n\n            Maps to the function\n            :py:func:`nipap.backend.Nipap.find_free_prefix` in the backend.\n            Please see the documentation for the backend function for\n            information regarding input arguments and return values."
  },
  {
    "code": "def discount_rewards(r):\n    discounted_r = np.zeros_like(r)\n    running_add = 0\n    for t in reversed(range(0, r.size)):\n        if r[t] != 0:\n            running_add = 0\n        running_add = running_add * gamma + r[t]\n        discounted_r[t] = running_add\n    return discounted_r",
    "docstring": "take 1D float array of rewards and compute discounted reward"
  },
  {
    "code": "def crs(self, crs):\n        if isinstance(crs, QgsCoordinateReferenceSystem):\n            self._crs = crs\n            self._is_ready = False\n        else:\n            raise InvalidExtentError('%s is not a valid CRS object.' % crs)",
    "docstring": "Setter for extent_crs property.\n\n        :param crs: The coordinate reference system for the analysis boundary.\n        :type crs: QgsCoordinateReferenceSystem"
  },
  {
    "code": "def reload_wsgi():\n    \"Gets the PID for the wsgi process and sends a HUP signal.\"\n    pid = run('supervisorctl pid varify-{host}'.format(host=env.host))\n    try:\n        int(pid)\n        sudo('kill -HUP {0}'.format(pid))\n    except (TypeError, ValueError):\n        pass",
    "docstring": "Gets the PID for the wsgi process and sends a HUP signal."
  },
  {
    "code": "def _on_items_changed(self, change):\n        if change['type'] != 'container':\n            return\n        op = change['operation']\n        if op == 'append':\n            i = len(change['value'])-1\n            self.adapter.notifyItemInserted(i)\n        elif op == 'insert':\n            self.adapter.notifyItemInserted(change['index'])\n        elif op in ('pop', '__delitem__'):\n            self.adapter.notifyItemRemoved(change['index'])\n        elif op == '__setitem__':\n            self.adapter.notifyItemChanged(change['index'])\n        elif op == 'extend':\n            n = len(change['items'])\n            i = len(change['value'])-n\n            self.adapter.notifyItemRangeInserted(i, n)\n        elif op in ('remove', 'reverse', 'sort'):\n            self.adapter.notifyDataSetChanged()",
    "docstring": "Observe container events on the items list and update the\n        adapter appropriately."
  },
  {
    "code": "def spawn(self, context=None):\n        if context is None:\n            context = self.default_context\n        if isinstance(context, collections.Callable):\n            context = context()\n        if not isinstance(context, collections.Mapping):\n            raise PatchboardError('Cannot determine a valid context')\n        return Client(self, context, self.api, self.endpoint_classes)",
    "docstring": "context may be a callable or a dict."
  },
  {
    "code": "def date_to_um_date(date):\n    assert date.hour == 0 and date.minute == 0 and date.second == 0\n    return [date.year, date.month, date.day, 0, 0, 0]",
    "docstring": "Convert a date object to 'year, month, day, hour, minute, second.'"
  },
  {
    "code": "def list(region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        buckets = conn.list_buckets()\n        if not bool(buckets.get('Buckets')):\n            log.warning('No buckets found')\n        if 'ResponseMetadata' in buckets:\n            del buckets['ResponseMetadata']\n        return buckets\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "List all buckets owned by the authenticated sender of the request.\n\n    Returns list of buckets\n\n    CLI Example:\n\n    .. code-block:: yaml\n\n        Owner: {...}\n        Buckets:\n          - {...}\n          - {...}"
  },
  {
    "code": "def list_message_files (package, suffix=\".mo\"):\n    for fname in glob.glob(\"po/*\" + suffix):\n        localename = os.path.splitext(os.path.basename(fname))[0]\n        domainname = \"%s.mo\" % package.lower()\n        yield (fname, os.path.join(\n            \"share\", \"locale\", localename, \"LC_MESSAGES\", domainname))",
    "docstring": "Return list of all found message files and their installation paths."
  },
  {
    "code": "def enqueue_jobs(self):\n        self.log.debug('Checking for scheduled jobs')\n        jobs = self.get_jobs_to_queue()\n        for job in jobs:\n            self.enqueue_job(job)\n        self.connection.expire(self.scheduler_key, int(self._interval) + 10)\n        return jobs",
    "docstring": "Move scheduled jobs into queues."
  },
  {
    "code": "def weld_str_strip(array):\n    obj_id, weld_obj = create_weld_object(array)\n    weld_template =\n    weld_obj.weld_code = weld_template.format(array=obj_id)\n    return weld_obj",
    "docstring": "Strip whitespace from start and end of elements.\n\n    Note it currently only looks for whitespace (Ascii 32), not tabs or EOL.\n\n    Parameters\n    ----------\n    array : numpy.ndarray or WeldObject\n        Input data.\n\n    Returns\n    -------\n    WeldObject\n        Representation of this computation."
  },
  {
    "code": "def get(self, *args, **kwargs):\n        self.model = self.get_model(kwargs.get('id'))\n        result = yield self.model.fetch()\n        if not result:\n            LOGGER.debug('Not found')\n            self.not_found()\n            return\n        if not self.has_read_permission():\n            LOGGER.debug('Permission denied')\n            self.permission_denied()\n            return\n        self.add_headers()\n        self.finish(self.model_json())",
    "docstring": "Handle reading of the model\n\n        :param args:\n        :param kwargs:"
  },
  {
    "code": "def add(event, reactors, saltenv='base', test=None):\n    if isinstance(reactors, string_types):\n        reactors = [reactors]\n    sevent = salt.utils.event.get_event(\n            'master',\n            __opts__['sock_dir'],\n            __opts__['transport'],\n            opts=__opts__,\n            listen=True)\n    master_key = salt.utils.master.get_master_key('root', __opts__)\n    __jid_event__.fire_event({'event': event,\n                              'reactors': reactors,\n                              'key': master_key},\n                             'salt/reactors/manage/add')\n    res = sevent.get_event(wait=30, tag='salt/reactors/manage/add-complete')\n    return res['result']",
    "docstring": "Add a new reactor\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-run reactor.add 'salt/cloud/*/destroyed' reactors='/srv/reactor/destroy/*.sls'"
  },
  {
    "code": "def _call_connection_lost_and_clean_up(self, exc):\n        self._state = _State.CLOSED\n        try:\n            self._protocol.connection_lost(exc)\n        finally:\n            self._rawsock.close()\n            if self._tls_conn is not None:\n                self._tls_conn.set_app_data(None)\n                self._tls_conn = None\n            self._rawsock = None\n            self._protocol = None\n            self._loop = None",
    "docstring": "Clean up all resources and call the protocols connection lost method."
  },
  {
    "code": "def reset_parameter(**kwargs):\n    def _callback(env):\n        new_parameters = {}\n        for key, value in kwargs.items():\n            if key in ['num_class', 'num_classes',\n                       'boosting', 'boost', 'boosting_type',\n                       'metric', 'metrics', 'metric_types']:\n                raise RuntimeError(\"cannot reset {} during training\".format(repr(key)))\n            if isinstance(value, list):\n                if len(value) != env.end_iteration - env.begin_iteration:\n                    raise ValueError(\"Length of list {} has to equal to 'num_boost_round'.\"\n                                     .format(repr(key)))\n                new_param = value[env.iteration - env.begin_iteration]\n            else:\n                new_param = value(env.iteration - env.begin_iteration)\n            if new_param != env.params.get(key, None):\n                new_parameters[key] = new_param\n        if new_parameters:\n            env.model.reset_parameter(new_parameters)\n            env.params.update(new_parameters)\n    _callback.before_iteration = True\n    _callback.order = 10\n    return _callback",
    "docstring": "Create a callback that resets the parameter after the first iteration.\n\n    Note\n    ----\n    The initial parameter will still take in-effect on first iteration.\n\n    Parameters\n    ----------\n    **kwargs : value should be list or function\n        List of parameters for each boosting round\n        or a customized function that calculates the parameter in terms of\n        current number of round (e.g. yields learning rate decay).\n        If list lst, parameter = lst[current_round].\n        If function func, parameter = func(current_round).\n\n    Returns\n    -------\n    callback : function\n        The callback that resets the parameter after the first iteration."
  },
  {
    "code": "def x_select_cb(self, w, index):\n        try:\n            self.x_col = self.cols[index]\n        except IndexError as e:\n            self.logger.error(str(e))\n        else:\n            self.plot_two_columns(reset_xlimits=True)",
    "docstring": "Callback to set X-axis column."
  },
  {
    "code": "def _get_user_info(self, access_token, id_token):\n        try:\n            unverified_header = jwt.get_unverified_header(id_token)\n        except jwt.JWTError:\n            raise AuthError('Unable to decode the Id token header')\n        if 'kid' not in unverified_header:\n            raise AuthError('Id token header missing RSA key ID')\n        rsa_key = None\n        for key in jwks[\"keys\"]:\n            if key[\"kid\"] == unverified_header[\"kid\"]:\n                rsa_key = {\n                    \"kty\": key[\"kty\"],\n                    \"kid\": key[\"kid\"],\n                    \"use\": key[\"use\"],\n                    \"n\": key[\"n\"],\n                    \"e\": key[\"e\"]\n                }\n                break\n        if not rsa_key:\n            raise AuthError('Id token using unrecognised RSA key ID')\n        try:\n            user_info = jwt.decode(\n                id_token,\n                rsa_key,\n                algorithms=['RS256'],\n                audience=AUTH0_CLIENTID,\n                access_token=access_token,\n                issuer=\"https://\"+AUTH0_DOMAIN+\"/\"\n            )\n            return user_info\n        except jwt.ExpiredSignatureError:\n            raise AuthError('Id token is expired')\n        except jwt.JWTClaimsError:\n            raise AuthError(\"Incorrect claims: please check the audience and issuer\")\n        except jwt.JWTError:\n            raise AuthError(\"Invalid header: Unable to parse authentication\")",
    "docstring": "Extracts the user info payload from the Id Token.\n\n        Example return value:\n\n        {\n            \"at_hash\": \"<HASH>\",\n            \"aud\": \"<HASH>\",\n            \"email_verified\": true,\n            \"email\": \"fsurname@mozilla.com\",\n            \"exp\": 1551259495,\n            \"family_name\": \"Surname\",\n            \"given_name\": \"Firstname\",\n            \"https://sso.mozilla.com/claim/groups\": [\n                \"all_scm_level_1\",\n                \"all_scm_level_2\",\n                \"all_scm_level_3\",\n                # ...\n            ],\n            \"iat\": 1550654695,\n            \"iss\": \"https://auth.mozilla.auth0.com/\",\n            \"name\": \"Firstname Surname\",\n            \"nickname\": \"Firstname Surname\",\n            \"nonce\": \"<HASH>\",\n            \"picture\": \"<GRAVATAR_URL>\",\n            \"sub\": \"ad|Mozilla-LDAP|fsurname\",\n            \"updated_at\": \"2019-02-20T09:24:55.449Z\",\n        }"
  },
  {
    "code": "def deserialize_duration(attr):\n        if isinstance(attr, ET.Element):\n            attr = attr.text\n        try:\n            duration = isodate.parse_duration(attr)\n        except(ValueError, OverflowError, AttributeError) as err:\n            msg = \"Cannot deserialize duration object.\"\n            raise_with_traceback(DeserializationError, msg, err)\n        else:\n            return duration",
    "docstring": "Deserialize ISO-8601 formatted string into TimeDelta object.\n\n        :param str attr: response string to be deserialized.\n        :rtype: TimeDelta\n        :raises: DeserializationError if string format invalid."
  },
  {
    "code": "def init(self, acct: Account, payer_acct: Account, gas_limit: int, gas_price: int) -> str:\n        func = InvokeFunction('init')\n        tx_hash = self.__sdk.get_network().send_neo_vm_transaction(self.__hex_contract_address, acct, payer_acct,\n                                                                   gas_limit, gas_price, func)\n        return tx_hash",
    "docstring": "This interface is used to call the TotalSupply method in ope4\n        that initialize smart contract parameter.\n\n        :param acct: an Account class that used to sign the transaction.\n        :param payer_acct: an Account class that used to pay for the transaction.\n        :param gas_limit: an int value that indicate the gas limit.\n        :param gas_price: an int value that indicate the gas price.\n        :return: the hexadecimal transaction hash value."
  },
  {
    "code": "def _handle_prompt_command(self, buffer):\n        \" When a command-prompt command is accepted. \"\n        text = buffer.text\n        prompt_command = self.prompt_command\n        self.pymux.leave_command_mode(append_to_history=True)\n        self.pymux.handle_command(prompt_command.replace('%%', text))",
    "docstring": "When a command-prompt command is accepted."
  },
  {
    "code": "def get_color(self,callb=None):\n        response = self.req_with_resp(LightGet, LightState, callb=callb)\n        return self.color",
    "docstring": "Convenience method to request the colour status from the device\n\n        This method will check whether the value has already been retrieved from the device,\n        if so, it will simply return it. If no, it will request the information from the device\n        and request that callb be executed when a response is received. The default callback\n        will simply cache the value.\n\n        :param callb: Callable to be used when the response is received. If not set,\n                      self.resp_set_label will be used.\n        :type callb: callable\n        :returns: The cached value\n        :rtype: int"
  },
  {
    "code": "def load_average(self):\n        with io.open(self.load_average_file, 'r') as f:\n            file_columns = f.readline().strip().split()\n            return float(file_columns[self._load_average_file_column])",
    "docstring": "Returns the current load average."
  },
  {
    "code": "def get_change(self, change_id):\n        uri = '/%s/change/%s' % (self.Version, change_id)\n        response = self.make_request('GET', uri)\n        body = response.read()\n        boto.log.debug(body)\n        if response.status >= 300:\n            raise exception.DNSServerError(response.status,\n                                           response.reason,\n                                           body)\n        e = boto.jsonresponse.Element()\n        h = boto.jsonresponse.XmlHandler(e, None)\n        h.parse(body)\n        return e",
    "docstring": "Get information about a proposed set of changes, as submitted\n        by the change_rrsets method.\n        Returns a Python data structure with status information about the\n        changes.\n\n        :type change_id: str\n        :param change_id: The unique identifier for the set of changes.\n            This ID is returned in the response to the change_rrsets method."
  },
  {
    "code": "def list_domains(self, service_id, version_number):\n\t\tcontent = self._fetch(\"/service/%s/version/%d/domain\" % (service_id, version_number))\n\t\treturn map(lambda x: FastlyDomain(self, x), content)",
    "docstring": "List the domains for a particular service and version."
  },
  {
    "code": "def remove_item(self, item):\n        for idx, _item in enumerate(self.items):\n            if item == _item:\n                del self.items[idx]\n                return True\n        return False",
    "docstring": "Remove the specified item from the menu.\n\n        Args:\n            item (MenuItem): the item to be removed.\n\n        Returns:\n            bool: True if the item was removed; False otherwise."
  },
  {
    "code": "def display_cached_string(self, bi):\n        if not isinstance(bi, SConfBuildInfo):\n            SCons.Warnings.warn(SConfWarning,\n              \"The stored build information has an unexpected class: %s\" % bi.__class__)\n        else:\n            self.display(\"The original builder output was:\\n\" +\n                         (\"  |\" + str(bi.string)).replace(\"\\n\", \"\\n  |\"))",
    "docstring": "Logs the original builder messages, given the SConfBuildInfo instance\n        bi."
  },
  {
    "code": "def persistant_info(request, message, extra_tags='', fail_silently=False, *args, **kwargs):\n    add_message(request, INFO_PERSISTENT, message, extra_tags=extra_tags,\n                fail_silently=fail_silently, *args, **kwargs)",
    "docstring": "Adds a persistant message with the ``INFO`` level."
  },
  {
    "code": "def computeAccuracyEnding(predictions, truths, iterations,\n                    resets=None, randoms=None, num=None,\n                    sequenceCounter=None):\n  accuracy = []\n  numIteration = []\n  numSequences = []\n  for i in xrange(len(predictions) - 1):\n    if num is not None and i > num:\n      continue\n    if truths[i] is None:\n      continue\n    if resets is not None or randoms is not None:\n      if not (resets[i+1] or randoms[i+1]):\n        continue\n    correct = truths[i] is None or truths[i] in predictions[i]\n    accuracy.append(correct)\n    numSequences.append(sequenceCounter[i])\n    numIteration.append(iterations[i])\n  return (accuracy, numIteration, numSequences)",
    "docstring": "Compute accuracy on the sequence ending"
  },
  {
    "code": "def getNewestCompleteTime(self):\n        bldrid = yield self.getBuilderId()\n        completed = yield self.master.data.get(\n            ('builders', bldrid, 'buildrequests'),\n            [resultspec.Filter('complete', 'eq', [False])],\n            order=['-complete_at'], limit=1)\n        if completed:\n            return completed[0]['complete_at']\n        else:\n            return None",
    "docstring": "Returns the complete_at of the latest completed build request for\n        this builder, or None if there are no such build requests.\n\n        @returns: datetime instance or None, via Deferred"
  },
  {
    "code": "def _get_response_body_from_gzipped_content(self, url, response):\n        try:\n            gzipper = gzip.GzipFile(fileobj=six.BytesIO(response.text))\n            LOG.debug(self._(\"Received compressed response for \"\n                             \"url %(url)s.\"), {'url': url})\n            uncompressed_string = (gzipper.read().decode('UTF-8'))\n            response_body = json.loads(uncompressed_string)\n        except Exception as e:\n            LOG.debug(\n                self._(\"Error occurred while decompressing body. \"\n                       \"Got invalid response '%(response)s' for \"\n                       \"url %(url)s: %(error)s\"),\n                {'url': url, 'response': response.text, 'error': e})\n            raise exception.IloError(e)\n        return response_body",
    "docstring": "Get the response body from gzipped content\n\n        Try to decode as gzip (we should check the headers for\n        Content-Encoding=gzip)\n\n          if response.headers['content-encoding'] == \"gzip\":\n            ...\n\n        :param url: the url for which response was sent\n        :type url: str\n        :param response: response content object, probably gzipped\n        :type response: object\n        :returns: returns response body\n        :raises IloError: if the content is **not** gzipped"
  },
  {
    "code": "def parent_resources(cls):\n        parent = cls.parent_resource\n        parents = [parent]\n        try:\n            while True:\n                parent = parent.parent_resource\n                parents.append(parent)\n        except AttributeError:\n            pass\n        parents.reverse()\n        return parents",
    "docstring": "Get a list of parent resources, starting from the Document"
  },
  {
    "code": "def _update_staticmethod(self, oldsm, newsm):\n        self._update(None, None, oldsm.__get__(0), newsm.__get__(0))",
    "docstring": "Update a staticmethod update."
  },
  {
    "code": "def _prepare(self, serialized_obj):\n        nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE)\n        encrypted = self.__safe.encrypt(serialized_obj, nonce)\n        signed = self.__signing_key.sign(encrypted)\n        return signed",
    "docstring": "Prepare the object to be sent over the untrusted channel."
  },
  {
    "code": "def _id(self):\n        return (self.__class__, self.number_of_needles, self.needle_positions,\n                self.left_end_needle)",
    "docstring": "What this object is equal to."
  },
  {
    "code": "def sync_readmes():\n    print(\"syncing README\")\n    with open(\"README.md\", 'r') as reader:\n        file_text = reader.read()\n    with open(\"README\", 'w') as writer:\n        writer.write(file_text)",
    "docstring": "just copies README.md into README for pypi documentation"
  },
  {
    "code": "def andrew(S):\n    S.sort()\n    top = []\n    bot = []\n    for p in S:\n        while len(top) >= 2 and not left_turn(p, top[-1], top[-2]):\n            top.pop()\n        top.append(p)\n        while len(bot) >= 2 and not left_turn(bot[-2], bot[-1], p):\n            bot.pop()\n        bot.append(p)\n    return bot[:-1] + top[:0:-1]",
    "docstring": "Convex hull by Andrew\n\n    :param S: list of points as coordinate pairs\n    :requires: S has at least 2 points\n    :returns: list of points of the convex hull\n    :complexity: `O(n log n)`"
  },
  {
    "code": "def last_modified():\n    files = model.FileFingerprint.select().order_by(\n        orm.desc(model.FileFingerprint.file_mtime))\n    for file in files:\n        return file.file_mtime, file.file_path\n    return None, None",
    "docstring": "information about the most recently modified file"
  },
  {
    "code": "def extended_arg_patterns(self):\n        for arg in self._arg_iterator(self.args):\n            if isinstance(arg, Pattern):\n                if arg.mode > self.single:\n                    while True:\n                        yield arg\n                else:\n                    yield arg\n            else:\n                yield arg",
    "docstring": "Iterator over patterns for positional arguments to be matched\n\n        This yields the elements of :attr:`args`, extended by their `mode`\n        value"
  },
  {
    "code": "def generators_from_logdir(logdir):\n  subdirs = io_wrapper.GetLogdirSubdirectories(logdir)\n  generators = [\n      itertools.chain(*[\n          generator_from_event_file(os.path.join(subdir, f))\n          for f in tf.io.gfile.listdir(subdir)\n          if io_wrapper.IsTensorFlowEventsFile(os.path.join(subdir, f))\n      ]) for subdir in subdirs\n  ]\n  return generators",
    "docstring": "Returns a list of event generators for subdirectories with event files.\n\n  The number of generators returned should equal the number of directories\n  within logdir that contain event files. If only logdir contains event files,\n  returns a list of length one.\n\n  Args:\n    logdir: A log directory that contains event files.\n\n  Returns:\n    List of event generators for each subdirectory with event files."
  },
  {
    "code": "def get_all_articles(self, params=None):\n        if not params:\n            params = {}\n        return self._iterate_through_pages(self.get_articles_per_page, resource=ARTICLES, **{'params': params})",
    "docstring": "Get all articles\n        This will iterate over all pages until it gets all elements.\n        So if the rate limit exceeded it will throw an Exception and you will get nothing\n\n        :param params: search params\n        :return: list"
  },
  {
    "code": "async def run_jog(data):\n    axis = data.get('axis')\n    direction = data.get('direction')\n    step = data.get('step')\n    if axis not in ('x', 'y', 'z'):\n        message = '\"axis\" must be \"x\", \"y\", or \"z\"'\n        status = 400\n    elif direction not in (-1, 1):\n        message = '\"direction\" must be -1 or 1'\n        status = 400\n    elif step is None:\n        message = '\"step\" must be specified'\n        status = 400\n    else:\n        position = jog(\n            axis,\n            direction,\n            step,\n            session.adapter,\n            session.current_mount,\n            session.cp)\n        message = 'Jogged to {}'.format(position)\n        status = 200\n    return web.json_response({'message': message}, status=status)",
    "docstring": "Allow the user to jog the selected pipette around the deck map\n\n    :param data: Information obtained from a POST request.\n    The content type is application/json\n    The correct packet form should be as follows:\n    {\n      'token': UUID token from current session start\n      'command': 'jog'\n      'axis': The current axis you wish to move\n      'direction': The direction you wish to move (+ or -)\n      'step': The increment you wish to move\n    }\n    :return: The position you are moving to based on axis, direction, step\n    given by the user."
  },
  {
    "code": "def resid_dev(self, endog, mu, scale=1.):\n        return (endog - mu) / np.sqrt(self.variance(mu)) / scale",
    "docstring": "Gaussian deviance residuals\n\n        Parameters\n        -----------\n        endog : array-like\n            Endogenous response variable\n        mu : array-like\n            Fitted mean response variable\n        scale : float, optional\n            An optional argument to divide the residuals by scale. The default\n            is 1.\n\n        Returns\n        -------\n        resid_dev : array\n            Deviance residuals as defined below"
  },
  {
    "code": "def create_conda_env(sandbox_dir, env_name, dependencies, options=()):\n    env_dir = os.path.join(sandbox_dir, env_name)\n    cmdline = [\"conda\", \"create\", \"--yes\", \"--copy\", \"--quiet\", \"-p\", env_dir] + list(options) + dependencies\n    log.info(\"Creating conda environment: \")\n    log.info(\"  command line: %s\", cmdline)\n    subprocess.check_call(cmdline, stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n    log.debug(\"Environment created\")\n    return env_dir, env_name",
    "docstring": "Create a conda environment inside the current sandbox for the given list of dependencies and options.\n\n    Parameters\n    ----------\n    sandbox_dir : str\n    env_name : str\n    dependencies : list\n        List of conda specs\n    options\n        List of additional options to pass to conda.  Things like [\"-c\", \"conda-forge\"]\n\n    Returns\n    -------\n    (env_dir, env_name)"
  },
  {
    "code": "def get_substituted_contents(contents, substitutions):\n    result = contents\n    for sub in substitutions:\n        result = sub.apply_and_get_result(result)\n    return result",
    "docstring": "Perform a list of substitutions and return the result.\n\n    contents: the starting string on which to beging substitutions\n    substitutions: list of Substitution objects to call, in order, with the\n        result of the previous substitution."
  },
  {
    "code": "def tvdb_series_id(token, id_tvdb, lang=\"en\", cache=True):\n    if lang not in TVDB_LANGUAGE_CODES:\n        raise MapiProviderException(\n            \"'lang' must be one of %s\" % \",\".join(TVDB_LANGUAGE_CODES)\n        )\n    try:\n        url = \"https://api.thetvdb.com/series/%d\" % int(id_tvdb)\n    except ValueError:\n        raise MapiProviderException(\"id_tvdb must be numeric\")\n    headers = {\"Accept-Language\": lang, \"Authorization\": \"Bearer %s\" % token}\n    status, content = _request_json(url, headers=headers, cache=cache)\n    if status == 401:\n        raise MapiProviderException(\"invalid token\")\n    elif status == 404:\n        raise MapiNotFoundException\n    elif status != 200 or not content.get(\"data\"):\n        raise MapiNetworkException(\"TVDb down or unavailable?\")\n    return content",
    "docstring": "Returns a series records that contains all information known about a\n    particular series id\n\n    Online docs: api.thetvdb.com/swagger#!/Series/get_series_id="
  },
  {
    "code": "def from_dynacRepr(cls, pynacRepr):\n        L = float(pynacRepr[1][0][0])\n        B = float(pynacRepr[1][0][1])\n        aperRadius = float(pynacRepr[1][0][2])\n        return cls(L, B, aperRadius)",
    "docstring": "Construct a ``Quad`` instance from the Pynac lattice element"
  },
  {
    "code": "def subscriberSocket(self, host, port, filt=b'', conflate=False):\n        socket = self._context.socket(zmq.SUB)\n        if conflate:\n            socket.setsockopt(zmq.CONFLATE, 1)\n        socket.connect(self.tcpAddress(host, port))\n        socket.setsockopt(zmq.SUBSCRIBE, filt)\n        return socket",
    "docstring": "Create a SUB-style socket for data receivers"
  },
  {
    "code": "def items(*args, **kwargs):\n    if args:\n        return item(*args)\n    pillarenv = kwargs.get('pillarenv')\n    if pillarenv is None:\n        if __opts__.get('pillarenv_from_saltenv', False):\n            pillarenv = kwargs.get('saltenv') or __opts__['saltenv']\n        else:\n            pillarenv = __opts__['pillarenv']\n    pillar_override = kwargs.get('pillar')\n    pillar_enc = kwargs.get('pillar_enc')\n    if pillar_override and pillar_enc:\n        try:\n            pillar_override = salt.utils.crypt.decrypt(\n                pillar_override,\n                pillar_enc,\n                translate_newlines=True,\n                opts=__opts__,\n                valid_rend=__opts__['decrypt_pillar_renderers'])\n        except Exception as exc:\n            raise CommandExecutionError(\n                'Failed to decrypt pillar override: {0}'.format(exc)\n            )\n    pillar = salt.pillar.get_pillar(\n        __opts__,\n        __grains__,\n        __opts__['id'],\n        pillar_override=pillar_override,\n        pillarenv=pillarenv)\n    return pillar.compile_pillar()",
    "docstring": "Calls the master for a fresh pillar and generates the pillar data on the\n    fly\n\n    Contrast with :py:func:`raw` which returns the pillar data that is\n    currently loaded into the minion.\n\n    pillar\n        If specified, allows for a dictionary of pillar data to be made\n        available to pillar and ext_pillar rendering. these pillar variables\n        will also override any variables of the same name in pillar or\n        ext_pillar.\n\n        .. versionadded:: 2015.5.0\n\n    pillar_enc\n        If specified, the data passed in the ``pillar`` argument will be passed\n        through this renderer to decrypt it.\n\n        .. note::\n            This will decrypt on the minion side, so the specified renderer\n            must be set up on the minion for this to work. Alternatively,\n            pillar data can be decrypted master-side. For more information, see\n            the :ref:`Pillar Encryption <pillar-encryption>` documentation.\n            Pillar data that is decrypted master-side, is not decrypted until\n            the end of pillar compilation though, so minion-side decryption\n            will be necessary if the encrypted pillar data must be made\n            available in an decrypted state pillar/ext_pillar rendering.\n\n        .. versionadded:: 2017.7.0\n\n    pillarenv\n        Pass a specific pillar environment from which to compile pillar data.\n        If not specified, then the minion's :conf_minion:`pillarenv` option is\n        not used, and if that also is not specified then all configured pillar\n        environments will be merged into a single pillar dictionary and\n        returned.\n\n        .. versionadded:: 2016.11.2\n\n    saltenv\n        Included only for compatibility with\n        :conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' pillar.items"
  },
  {
    "code": "def from_cap(cls, theta, lwin, clat=None, clon=None, nwin=None,\n                 theta_degrees=True, coord_degrees=True, dj_matrix=None,\n                 weights=None):\n        if theta_degrees:\n            tapers, eigenvalues, taper_order = _shtools.SHReturnTapers(\n                _np.radians(theta), lwin)\n        else:\n            tapers, eigenvalues, taper_order = _shtools.SHReturnTapers(\n                theta, lwin)\n        return SHWindowCap(theta, tapers, eigenvalues, taper_order,\n                           clat, clon, nwin, theta_degrees, coord_degrees,\n                           dj_matrix, weights, copy=False)",
    "docstring": "Construct spherical cap localization windows.\n\n        Usage\n        -----\n        x = SHWindow.from_cap(theta, lwin, [clat, clon, nwin, theta_degrees,\n                                            coord_degrees, dj_matrix, weights])\n\n        Returns\n        -------\n        x : SHWindow class instance\n\n        Parameters\n        ----------\n        theta : float\n            Angular radius of the spherical cap localization domain (default\n            in degrees).\n        lwin : int\n            Spherical harmonic bandwidth of the localization windows.\n        clat, clon : float, optional, default = None\n            Latitude and longitude of the center of the rotated spherical cap\n            localization windows (default in degrees).\n        nwin : int, optional, default (lwin+1)**2\n            Number of localization windows.\n        theta_degrees : bool, optional, default = True\n            True if theta is in degrees.\n        coord_degrees : bool, optional, default = True\n            True if clat and clon are in degrees.\n        dj_matrix : ndarray, optional, default = None\n            The djpi2 rotation matrix computed by a call to djpi2.\n        weights : ndarray, optional, default = None\n            Taper weights used with the multitaper spectral analyses."
  },
  {
    "code": "def createFile(dataArray=None, outfile=None, header=None):\n    assert(dataArray is not None), \"Please supply a data array for createFiles\"\n    try:\n        fitsobj = fits.HDUList()\n        if header is not None:\n            try:\n                del(header['NAXIS1'])\n                del(header['NAXIS2'])\n                if 'XTENSION' in header:\n                    del(header['XTENSION'])\n                if 'EXTNAME' in header:\n                    del(header['EXTNAME'])\n                if 'EXTVER' in header:\n                    del(header['EXTVER'])\n            except KeyError:\n                pass\n            if 'NEXTEND' in header:\n                header['NEXTEND'] = 0\n            hdu = fits.PrimaryHDU(data=dataArray, header=header)\n            try:\n                del hdu.header['PCOUNT']\n                del hdu.header['GCOUNT']\n            except KeyError:\n                pass\n        else:\n            hdu = fits.PrimaryHDU(data=dataArray)\n        fitsobj.append(hdu)\n        if outfile is not None:\n            fitsobj.writeto(outfile)\n    finally:\n        fitsobj.close()\n        if outfile is not None:\n            del fitsobj\n            fitsobj = None\n    return fitsobj",
    "docstring": "Create a simple fits file for the given data array and header.\n    Returns either the FITS object in-membory when outfile==None or\n    None when the FITS file was written out to a file."
  },
  {
    "code": "def _indicator_table():\n    from xclim import temperature, precip\n    import inspect\n    inds = _get_indicators([temperature, precip])\n    table = []\n    for ind in inds:\n        args = {name: p.default for (name, p) in ind._sig.parameters.items() if p.default != inspect._empty}\n        table.append(ind.json(args))\n    return table",
    "docstring": "Return a sequence of dicts storing metadata about all available indices."
  },
  {
    "code": "def removeDataFrameRows(self, rows):\n        if not self.editable:\n            return False\n        if rows:\n            position = min(rows)\n            count = len(rows)\n            self.beginRemoveRows(QtCore.QModelIndex(), position, position + count - 1)\n            removedAny = False\n            for idx, line in self._dataFrame.iterrows():\n                if idx in rows:\n                    removedAny = True\n                    self._dataFrame.drop(idx, inplace=True)\n            if not removedAny:\n                return False\n            self._dataFrame.reset_index(inplace=True, drop=True)\n            self.endRemoveRows()\n            return True\n        return False",
    "docstring": "Removes rows from the dataframe.\n\n        :param rows: (list)\n            of row indexes to removes.\n        :return: (bool)\n            True on success, False on failure."
  },
  {
    "code": "def is_quota_exceeded(self) -> bool:\n        if self.quota and self._url_table is not None:\n            return self.size >= self.quota and \\\n                   self._url_table.get_root_url_todo_count() == 0",
    "docstring": "Return whether the quota is exceeded."
  },
  {
    "code": "def mine_items(self, identifiers, params=None, callback=None):\n        params = {'dontcache': 1} if not params else {}\n        requests = metadata_requests(identifiers, params, callback, self)\n        yield from self.mine(requests)",
    "docstring": "Mine metadata from Archive.org items.\n\n        :param identifiers: Archive.org identifiers to be mined.\n        :type identifiers: iterable\n\n        :param params: URL parameters to send with each metadata\n                       request.\n        :type params: dict\n\n        :param callback: A callback function to be called on each\n                         :py:class:`aiohttp.client.ClientResponse`.\n        :type callback: func"
  },
  {
    "code": "def sha1_digest(instr):\n    if six.PY3:\n        b = salt.utils.stringutils.to_bytes(instr)\n        return hashlib.sha1(b).hexdigest()\n    return hashlib.sha1(instr).hexdigest()",
    "docstring": "Generate an sha1 hash of a given string."
  },
  {
    "code": "def summary(self) -> str:\n        if not self.translations:\n            self.update()\n        return summary.metar(self.translations)",
    "docstring": "Condensed report summary created from translations"
  },
  {
    "code": "def put_summary(self, summary):\n        if isinstance(summary, six.binary_type):\n            summary = tf.Summary.FromString(summary)\n        assert isinstance(summary, tf.Summary), type(summary)\n        for val in summary.value:\n            if val.WhichOneof('value') == 'simple_value':\n                val.tag = re.sub('tower[0-9]+/', '', val.tag)\n                suffix = '-summary'\n                if val.tag.endswith(suffix):\n                    val.tag = val.tag[:-len(suffix)]\n                self._dispatch(lambda m: m.process_scalar(val.tag, val.simple_value))\n        self._dispatch(lambda m: m.process_summary(summary))",
    "docstring": "Put a `tf.Summary`."
  },
  {
    "code": "def wait_for_healthy(\n        raiden: 'RaidenService',\n        node_address: Address,\n        retry_timeout: float,\n) -> None:\n    network_statuses = views.get_networkstatuses(\n        views.state_from_raiden(raiden),\n    )\n    while network_statuses.get(node_address) != NODE_NETWORK_REACHABLE:\n        gevent.sleep(retry_timeout)\n        network_statuses = views.get_networkstatuses(\n            views.state_from_raiden(raiden),\n        )",
    "docstring": "Wait until `node_address` becomes healthy.\n\n    Note:\n        This does not time out, use gevent.Timeout."
  },
  {
    "code": "def create_url(url_protocol, host, api, url_params):\n    is_batch = url_params.pop(\"batch\", None)\n    apis = url_params.pop(\"apis\", None)\n    version = url_params.pop(\"version\", None) or url_params.pop(\"v\", None)\n    method = url_params.pop('method', None)\n    host_url_seg = url_protocol + \"://%s\" % host\n    api_url_seg = \"/%s\" % api\n    batch_url_seg = \"/batch\" if is_batch else \"\"\n    method_url_seg = \"/%s\" % method if method else \"\"\n    params = {}\n    if apis:\n        params[\"apis\"] = \",\".join(apis)\n    if version:\n        params[\"version\"] = version\n    url = host_url_seg + api_url_seg + batch_url_seg + method_url_seg\n    if params:\n        url += \"?\" + urlencode(params)\n    return url",
    "docstring": "Generate the proper url for sending off data for analysis"
  },
  {
    "code": "def get_creator_by_name(name):\n    return {'docker(container)': Container.creator,\n            'shell': Bash.creator, 'docker(image)': Image.creator,\n            'python': Script.creator, 'packer': Packer.creator,\n            'ansible(simple)': Ansible.creator}[name]",
    "docstring": "Get creator function by name.\n\n    Args:\n        name (str): name of the creator function.\n\n    Returns:\n        function: creater function."
  },
  {
    "code": "def get_utc_date(entry):\n    if entry['numeric_date_stamp'] == '0':\n        entry['numeric_date_stamp_utc'] = '0'\n        return entry\n    else:\n        if '.' in entry['numeric_date_stamp']:\n            t = datetime.strptime(entry['numeric_date_stamp'],\n                    '%Y%m%d%H%M%S.%f')\n        else:\n            t = datetime.strptime(entry['numeric_date_stamp'],\n                    '%Y%m%d%H%M%S')\n        tdelta = timedelta(hours = int(entry['tzone'][1:3]),\n                minutes = int(entry['tzone'][3:5]))\n        if entry['tzone'][0] == '-':\n            ut = t + tdelta\n        else:\n            ut = t - tdelta\n        entry['numeric_date_stamp_utc'] = ut.strftime('%Y%m%d%H%M%S.%f')\n        return entry",
    "docstring": "Return datestamp converted to UTC"
  },
  {
    "code": "def _retrieve_indices(cols):\n        if isinstance(cols, int):\n            return [cols]\n        elif isinstance(cols, slice):\n            start = cols.start if cols.start else 0\n            stop = cols.stop\n            step = cols.step if cols.step else 1\n            return list(range(start, stop, step))\n        elif isinstance(cols, list) and cols:\n            if isinstance(cols[0], bool):\n                return np.flatnonzero(np.asarray(cols))\n            elif isinstance(cols[0], int):\n                return cols\n        else:\n            raise TypeError('No valid column specifier. Only a scalar, list or slice of all'\n                            'integers or a boolean mask are allowed.')",
    "docstring": "Retrieve a list of indices corresponding to the provided column specification."
  },
  {
    "code": "def save_form(self, form):\n        force = self.get_force_instance_values()\n        if force:\n            for k, v in force.items():\n                setattr(form.instance, k, v)\n        should_add = False\n        if self.parent_object:\n            m2ms = [f.name for f in form.instance._meta.many_to_many]\n            m2ms.extend(\n                [f.field.rel.related_name for f in\n                    [\n                        f for f in form.instance._meta.get_fields(include_hidden=True)\n                        if f.many_to_many and f.auto_created\n                    ]\n                ]\n            )\n            if self.parent_field in m2ms:\n                should_add = True\n            else:\n                try:\n                    form.instance._meta.get_field(self.parent_field)\n                    setattr(form.instance, self.parent_field,\n                            self.parent_object)\n                except FieldDoesNotExist:\n                    pass\n        obj = form.save()\n        if should_add:\n            getattr(obj, self.parent_field).add(self.parent_object)\n        return obj",
    "docstring": "Save a valid form. If there is a parent attribute,\n        this will make sure that the parent object is added\n        to the saved object. Either as a relationship before\n        saving or in the case of many to many relations after\n        saving. Any forced instance values are set as well.\n\n        Returns the saved object."
  },
  {
    "code": "def get_db(db, ip='localhost', port=27017, user=None, password=None):\n    if platform.system().lower() == 'darwin':\n        connect = False\n    else:\n        connect = True\n    if user and password:\n        import urllib\n        pwd = urllib.quote_plus(password)\n        uri = 'mongodb://{}:{}@{}:{}'.format(user, pwd, ip, port)\n        conn = MongoClient(uri, connect=connect)\n    else:\n        conn = MongoClient(ip, port, connect=connect)\n    return conn[db]",
    "docstring": "Returns a pymongo Database object.\n\n    .. note:\n\n        Both ``user`` and ``password`` are required when connecting to a MongoDB\n        database that has authentication enabled.\n\n    Arguments:\n\n        db (str): Name of the MongoDB database. Required.\n\n        ip (str): IP address of the MongoDB server. Default is ``localhost``.\n\n        port (int): Port of the MongoDB server. Default is ``27017``.\n\n        user (str): Username, if authentication is enabled on the MongoDB database.\n            Default is ``None``, which results in requesting the connection\n            without authentication.\n\n        password (str): Password, if authentication is enabled on the MongoDB database.\n            Default is ``None``, which results in requesting the connection\n            without authentication."
  },
  {
    "code": "def remove(self, *labelvalues):\n        if not self._labelnames:\n            raise ValueError('No label names were set when constructing %s' % self)\n        if len(labelvalues) != len(self._labelnames):\n            raise ValueError('Incorrect label count (expected %d, got %s)' % (len(self._labelnames), labelvalues))\n        labelvalues = tuple(unicode(l) for l in labelvalues)\n        with self._lock:\n            del self._metrics[labelvalues]",
    "docstring": "Remove the given labelset from the metric."
  },
  {
    "code": "def add_action(self, action, add_to_toolbar=True, add_to_legend=False):\n        self.actions.append(action)\n        self.iface.addPluginToMenu(self.tr('InaSAFE'), action)\n        if add_to_toolbar:\n            self.toolbar.addAction(action)\n        if add_to_legend:\n            self.iface.addCustomActionForLayerType(\n                action,\n                self.tr('InaSAFE'),\n                QgsMapLayer.VectorLayer,\n                True)\n            self.iface.addCustomActionForLayerType(\n                action,\n                self.tr('InaSAFE'),\n                QgsMapLayer.RasterLayer,\n                True)",
    "docstring": "Add a toolbar icon to the InaSAFE toolbar.\n\n        :param action: The action that should be added to the toolbar.\n        :type action: QAction\n\n        :param add_to_toolbar: Flag indicating whether the action should also\n            be added to the InaSAFE toolbar. Defaults to True.\n        :type add_to_toolbar: bool\n\n        :param add_to_legend: Flag indicating whether the action should also\n            be added to the layer legend menu. Default to False.\n        :type add_to_legend: bool"
  },
  {
    "code": "def RegisterKey(cls, key,\n                    getter=None, setter=None, deleter=None, lister=None):\n        key = key.lower()\n        if getter is not None:\n            cls.Get[key] = getter\n        if setter is not None:\n            cls.Set[key] = setter\n        if deleter is not None:\n            cls.Delete[key] = deleter\n        if lister is not None:\n            cls.List[key] = lister",
    "docstring": "Register a new key mapping.\n\n        A key mapping is four functions, a getter, setter, deleter,\n        and lister. The key may be either a string or a glob pattern.\n\n        The getter, deleted, and lister receive an MP4Tags instance\n        and the requested key name. The setter also receives the\n        desired value, which will be a list of strings.\n\n        The getter, setter, and deleter are used to implement __getitem__,\n        __setitem__, and __delitem__.\n\n        The lister is used to implement keys(). It should return a\n        list of keys that are actually in the MP4 instance, provided\n        by its associated getter."
  },
  {
    "code": "def disarm(self, wait=True, timeout=None):\n        self.armed = False\n        if wait:\n            self.wait_for(lambda: not self.armed, timeout=timeout,\n                          errmsg='failed to disarm vehicle')",
    "docstring": "Disarm the vehicle.\n\n        If wait is True, wait for disarm operation to complete before\n        returning.  If timeout is nonzero, raise a TimeouTerror if the\n        vehicle has not disarmed after timeout seconds."
  },
  {
    "code": "def get_projects(osa_repo_dir, commit):\n    repo = Repo(osa_repo_dir)\n    checkout(repo, commit)\n    yaml_files = glob.glob(\n        '{0}/playbooks/defaults/repo_packages/*.yml'.format(osa_repo_dir)\n    )\n    yaml_parsed = []\n    for yaml_file in yaml_files:\n        with open(yaml_file, 'r') as f:\n            yaml_parsed.append(yaml.load(f))\n    merged_dicts = {k: v for d in yaml_parsed for k, v in d.items()}\n    return normalize_yaml(merged_dicts)",
    "docstring": "Get all projects from multiple YAML files."
  },
  {
    "code": "def __is_function_action(self, action_function):\n        is_function_action = True\n        if not hasattr(action_function, '__call__'):\n            return False\n        try:\n            for end_string, context in action_function():\n                if not isinstance(end_string, basestring):\n                    self.log_error(\"Action function must return end of filename as a string as first argument\")\n                if not isinstance(context, dict):\n                    self.log_error(\"Action function must return context as a dict as second argument\")\n                break\n        except Exception:\n            is_function_action = False\n        return is_function_action",
    "docstring": "Detect if given function is really an action function.\n\n        Args:\n            action_function: Function to test.\n\n        Note:\n            We don't care if the variable refer to a function but rather if it is callable or not."
  },
  {
    "code": "def links(self):\n        if not self._responses:\n            return None\n        if 'Link' in self._responses[-1].headers:\n            links = []\n            for l in headers.parse_link(self._responses[-1].headers['Link']):\n                link = {'target': l.target}\n                link.update({k: v for (k, v) in l.parameters})\n                links.append(link)\n            return links",
    "docstring": "Return the parsed link header if it was set, returning a list of\n        the links as a dict.\n\n        :rtype: list(dict()) or None"
  },
  {
    "code": "def kscale(matrix, k=7, dists=None):\n    dists = (kdists(matrix, k=k) if dists is None else dists)\n    scale = dists.dot(dists.T)\n    return scale",
    "docstring": "Returns the local scale based on the k-th nearest neighbour"
  },
  {
    "code": "def get_iex_dividends(start=None, **kwargs):\r\n    import warnings\r\n    warnings.warn(WNG_MSG % (\"get_iex_dividends\", \"refdata.get_iex_dividends\"))\r\n    return Dividends(start=start, **kwargs).fetch()",
    "docstring": "MOVED to iexfinance.refdata.get_iex_dividends"
  },
  {
    "code": "def set_verbosity(cls, verbosity):\n        if verbosity > 0:\n            logger = KittyObject.get_logger()\n            levels = [logging.DEBUG]\n            verbosity = min(verbosity, len(levels)) - 1\n            logger.setLevel(levels[verbosity])",
    "docstring": "Set verbosity of logger\n\n        :param verbosity: verbosity level. currently, we only support 1 (logging.DEBUG)"
  },
  {
    "code": "def _mark_received(self, tsn):\n        if uint32_gte(self._last_received_tsn, tsn) or tsn in self._sack_misordered:\n            self._sack_duplicates.append(tsn)\n            return True\n        self._sack_misordered.add(tsn)\n        for tsn in sorted(self._sack_misordered):\n            if tsn == tsn_plus_one(self._last_received_tsn):\n                self._last_received_tsn = tsn\n            else:\n                break\n        def is_obsolete(x):\n            return uint32_gt(x, self._last_received_tsn)\n        self._sack_duplicates = list(filter(is_obsolete, self._sack_duplicates))\n        self._sack_misordered = set(filter(is_obsolete, self._sack_misordered))",
    "docstring": "Mark an incoming data TSN as received."
  },
  {
    "code": "def GetRpcServer(options):\n\trpc_server_class = HttpRpcServer\n\tdef GetUserCredentials():\n\t\tglobal global_status\n\t\tst = global_status\n\t\tglobal_status = None\n\t\temail = options.email\n\t\tif email is None:\n\t\t\temail = GetEmail(\"Email (login for uploading to %s)\" % options.server)\n\t\tpassword = getpass.getpass(\"Password for %s: \" % email)\n\t\tglobal_status = st\n\t\treturn (email, password)\n\thost = (options.host or options.server).lower()\n\tif host == \"localhost\" or host.startswith(\"localhost:\"):\n\t\temail = options.email\n\t\tif email is None:\n\t\t\temail = \"test@example.com\"\n\t\t\tlogging.info(\"Using debug user %s.  Override with --email\" % email)\n\t\tserver = rpc_server_class(\n\t\t\t\toptions.server,\n\t\t\t\tlambda: (email, \"password\"),\n\t\t\t\thost_override=options.host,\n\t\t\t\textra_headers={\"Cookie\": 'dev_appserver_login=\"%s:False\"' % email},\n\t\t\t\tsave_cookies=options.save_cookies)\n\t\tserver.authenticated = True\n\t\treturn server\n\treturn rpc_server_class(options.server, GetUserCredentials,\n\t\thost_override=options.host, save_cookies=options.save_cookies)",
    "docstring": "Returns an instance of an AbstractRpcServer.\n\n\tReturns:\n\t\tA new AbstractRpcServer, on which RPC calls can be made."
  },
  {
    "code": "def get_playcount(self):\n        return _number(\n            _extract(\n                self._request(self.ws_prefix + \".getInfo\", cacheable=True), \"playcount\"\n            )\n        )",
    "docstring": "Returns the number of plays on the network"
  },
  {
    "code": "def get_default_value(self):\n        default = self.default_value\n        if isinstance(default, collections.Callable):\n            default = default()\n        return default",
    "docstring": "return default value"
  },
  {
    "code": "def list(cls, name, parent=None, interleave=None):\n        node = cls.leaf_list(name, parent, interleave=interleave)\n        node.keys = []\n        node.keymap = {}\n        return node",
    "docstring": "Create _list_ node for a list."
  },
  {
    "code": "def setSignalHeader(self, edfsignal, channel_info):\n        if edfsignal < 0 or edfsignal > self.n_channels:\n            raise ChannelDoesNotExist(edfsignal)\n        self.channels[edfsignal] = channel_info\n        self.update_header()",
    "docstring": "Sets the parameter for signal edfsignal.\n\n        channel_info should be a dict with\n        these values:\n\n            'label' : channel label (string, <= 16 characters, must be unique)\n            'dimension' : physical dimension (e.g., mV) (string, <= 8 characters)\n            'sample_rate' : sample frequency in hertz (int)\n            'physical_max' : maximum physical value (float)\n            'physical_min' : minimum physical value (float)\n            'digital_max' : maximum digital value (int, -2**15 <= x < 2**15)\n            'digital_min' : minimum digital value (int, -2**15 <= x < 2**15)"
  },
  {
    "code": "def remove_element_attributes(elem_to_parse, *args):\n    element = get_element(elem_to_parse)\n    if element is None:\n        return element\n    if len(args):\n        attribs = element.attrib\n        return {key: attribs.pop(key) for key in args if key in attribs}\n    return {}",
    "docstring": "Removes the specified keys from the element's attributes, and\n    returns a dict containing the attributes that have been removed."
  },
  {
    "code": "def _get_call_names_helper(node):\n    if isinstance(node, ast.Name):\n        if node.id not in BLACK_LISTED_CALL_NAMES:\n            yield node.id\n    elif isinstance(node, ast.Subscript):\n        yield from _get_call_names_helper(node.value)\n    elif isinstance(node, ast.Str):\n        yield node.s\n    elif isinstance(node, ast.Attribute):\n        yield node.attr\n        yield from _get_call_names_helper(node.value)",
    "docstring": "Recursively finds all function names."
  },
  {
    "code": "def v1_stream_id_associations(tags, stream_id):\n    stream_id = stream_id.decode('utf-8').strip()\n    return {'associations': tags.assocs_by_stream_id(stream_id)}",
    "docstring": "Retrieve associations for a given stream_id.\n\n    The associations returned have the exact same structure as defined\n    in the ``v1_tag_associate`` route with one addition: a ``tag``\n    field contains the full tag name for the association."
  },
  {
    "code": "def indexableText(self, tree):\n        rval = set()\n        root = tree.getroot()\n        for txp in self.text_elts_xpaths:\n            elts = txp(root)\n            texts = []\n            for elt in elts:\n                text = self.text_extract_xpath(elt)\n                if len(text) > 0:\n                    texts.append(text[0])\n            texts = self.separator.join(texts)\n            texts = [toUnicode(x) for x in self.wordssearch_rx.findall(texts)\n                     if len(x) > 0]\n            rval |= set(texts)\n        return rval",
    "docstring": "Provides the indexable - search engine oriented - raw text\n        @param tree: an ElementTree\n        @return: set([\"foo\", \"bar\", ...])"
  },
  {
    "code": "def check_domain_request(self, domains):\n        request = E.checkDomainRequest(\n            E.domains(\n                E.array(\n                    *[E.item(\n                        E.name(domain.split(\".\")[0]),\n                        E.extension(domain.split(\".\")[1])\n                    ) for domain in domains]\n                )\n            )\n        )\n        response = self.request(request)\n        return [Model(item) for item in response.data.array.item]",
    "docstring": "Return the availability of one or more domain names.\n\n        The availability is a model containing a domain and a status. It can also have a premium\n        attribute in case the domain has non-default costs."
  },
  {
    "code": "def ghz_circuit(qubits: Qubits) -> Circuit:\n    circ = Circuit()\n    circ += H(qubits[0])\n    for q0 in range(0, len(qubits)-1):\n        circ += CNOT(qubits[q0], qubits[q0+1])\n    return circ",
    "docstring": "Returns a circuit that prepares a multi-qubit Bell state from the zero\n    state."
  },
  {
    "code": "def describe_api_deployments(restApiId, region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        deployments = []\n        _deployments = conn.get_deployments(restApiId=restApiId)\n        while True:\n            if _deployments:\n                deployments = deployments + _deployments['items']\n                if 'position' not in _deployments:\n                    break\n                _deployments = conn.get_deployments(restApiId=restApiId, position=_deployments['position'])\n        return {'deployments': [_convert_datetime_str(deployment) for deployment in deployments]}\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Gets information about the defined API Deployments.  Return list of api deployments.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_apigateway.describe_api_deployments restApiId"
  },
  {
    "code": "def _pure_data(self, data: Any) -> Any:\n        if not isinstance(data, dict) and not isinstance(data, list):\n            try:\n                return dict(data)\n            except TypeError:\n                ...\n        return data",
    "docstring": "If data is dict-like object, convert it to pure dict instance, so it\n        will be possible to pass to default ``jsonschema.validate`` func.\n\n        :param data: Request or response data."
  },
  {
    "code": "def now_time(str=False):\n    if str:\n        return datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n    return datetime.datetime.now()",
    "docstring": "Get the current time."
  },
  {
    "code": "def add_const(features):\n    content = np.empty((features.shape[0], features.shape[1] + 1), dtype='float64')\n    content[:, 0] = 1.\n    if isinstance(features, np.ndarray):\n        content[:, 1:] = features\n        return content\n    content[:, 1:] = features.iloc[:, :].values\n    cols = ['Constant'] + features.columns.tolist()\n    return pd.DataFrame(data=content, index=features.index, columns=cols, dtype='float64')",
    "docstring": "Prepend the constant feature 1 as first feature and return the modified\n    feature set.\n\n    Parameters\n    ----------\n    features : ndarray or DataFrame"
  },
  {
    "code": "def nvrtcCreateProgram(self, src, name, headers, include_names):\n        res = c_void_p()\n        headers_array = (c_char_p * len(headers))()\n        headers_array[:] = encode_str_list(headers)\n        include_names_array = (c_char_p * len(include_names))()\n        include_names_array[:] = encode_str_list(include_names)\n        code = self._lib.nvrtcCreateProgram(byref(res),\n                                            c_char_p(encode_str(src)), c_char_p(encode_str(name)),\n                                            len(headers),\n                                            headers_array, include_names_array)\n        self._throw_on_error(code)\n        return res",
    "docstring": "Creates and returns a new NVRTC program object."
  },
  {
    "code": "def publish(self):\n        if self.published is False:\n            self.published = True\n        else:\n            raise Warning(self.title + ' is already published.')",
    "docstring": "Mark an episode as published."
  },
  {
    "code": "def patched(f):\n    def wrapped(*args, **kwargs):\n        kwargs['return_response'] = False\n        kwargs['prefetch'] = True\n        return f(*args, **kwargs)\n    return wrapped",
    "docstring": "Patches a given API function to not send."
  },
  {
    "code": "def _diffSchema(diskSchema, memorySchema):\n    diskSchema = set(diskSchema)\n    memorySchema = set(memorySchema)\n    diskOnly = diskSchema - memorySchema\n    memoryOnly = memorySchema - diskSchema\n    diff = []\n    if diskOnly:\n        diff.append('Only on disk:')\n        diff.extend(map(repr, diskOnly))\n    if memoryOnly:\n        diff.append('Only in memory:')\n        diff.extend(map(repr, memoryOnly))\n    return '\\n'.join(diff)",
    "docstring": "Format a schema mismatch for human consumption.\n\n    @param diskSchema: The on-disk schema.\n\n    @param memorySchema: The in-memory schema.\n\n    @rtype: L{bytes}\n    @return: A description of the schema differences."
  },
  {
    "code": "def get_object(self):\n        from ..util import AttrDict\n        c = self.record.unpacked_contents\n        if not c:\n            c = yaml.safe_load(self.default)\n        return AttrDict(c)",
    "docstring": "Return contents in object form, an AttrDict"
  },
  {
    "code": "def select_chain(self, chain_urls: Dict[str, List[str]]) -> Tuple[str, List[str]]:\n        chain_name = self.scenario.chain_name\n        if chain_name in ('any', 'Any', 'ANY'):\n            chain_name = random.choice(list(chain_urls.keys()))\n        log.info('Using chain', chain=chain_name)\n        try:\n            return chain_name, chain_urls[chain_name]\n        except KeyError:\n            raise ScenarioError(\n                f'The scenario requested chain \"{chain_name}\" for which no RPC-URL is known.',\n            )",
    "docstring": "Select a chain and return its name and RPC URL.\n\n        If the currently loaded scenario's designated chain is set to 'any',\n        we randomly select a chain from the given `chain_urls`.\n        Otherwise, we will return `ScenarioRunner.scenario.chain_name` and whatever value\n        may be associated with this key in `chain_urls`.\n\n        :raises ScenarioError:\n            if ScenarioRunner.scenario.chain_name is not one of `('any', 'Any', 'ANY')`\n            and it is not a key in `chain_urls`."
  },
  {
    "code": "def generate_unique_name(name_prefix, reservation_id=None):\n    if reservation_id and isinstance(reservation_id, str) and len(reservation_id) >= 4:\n        unique_id = str(uuid.uuid4())[:4] + \"-\" + reservation_id[-4:]\n    else:\n        unique_id = str(uuid.uuid4())[:8]\n    return name_prefix + \"_\" + unique_id",
    "docstring": "Generate a unique name.\n    Method generate a guid and adds the first 8 characteres of the new guid to 'name_prefix'.\n    If reservation id is provided than the first 4 chars of the generated guid are taken and the last 4\n    of the reservation id"
  },
  {
    "code": "def inject(self, solutions):\n        if not hasattr(self, 'pop_injection_directions'):\n            self.pop_injection_directions = []\n        for solution in solutions:\n            if len(solution) != self.N:\n                raise ValueError('method `inject` needs a list or array'\n                    + (' each el with dimension (`len`) %d' % self.N))\n            self.pop_injection_directions.append(\n                array(solution, copy=False, dtype=float) - self.mean)",
    "docstring": "inject a genotypic solution. The solution is used as direction\n        relative to the distribution mean to compute a new candidate\n        solution returned in method `ask_geno` which in turn is used in\n        method `ask`.\n\n        >>> import cma\n        >>> es = cma.CMAEvolutionStrategy(4 * [1], 2)\n        >>> while not es.stop():\n        ...     es.inject([4 * [0.0]])\n        ...     X = es.ask()\n        ...     break\n        >>> assert X[0][0] == X[0][1]"
  },
  {
    "code": "def _set_closest_stroke_width(self, width):\n        width *= self.pixel_to_size_ratio() / 6.\n        stroke_width_range = glGetFloatv(GL_LINE_WIDTH_RANGE)\n        stroke_width_granularity = glGetFloatv(GL_LINE_WIDTH_GRANULARITY)\n        if width < stroke_width_range[0]:\n            glLineWidth(stroke_width_range[0])\n            return\n        if width > stroke_width_range[1]:\n            glLineWidth(stroke_width_range[1])\n            return\n        glLineWidth(round(width / stroke_width_granularity) * stroke_width_granularity)",
    "docstring": "Sets the line width to the closest supported one\n\n        Not all line widths are supported. This function queries both minimum and maximum as well as the step size of\n        the line width and calculates the width, which is closest to the given one. This width is then set.\n\n        :param width: The desired line width"
  },
  {
    "code": "def get(ctx, uri):\n    http_client = get_wva(ctx).get_http_client()\n    cli_pprint(http_client.get(uri))",
    "docstring": "Perform an HTTP GET of the provided URI\n\nThe URI provided is relative to the /ws base to allow for easy navigation of\nthe resources exposed by the WVA.  Example Usage::\n\n\\b\n    $ wva get /\n    {'ws': ['vehicle',\n             'hw',\n             'config',\n             'state',\n             'files',\n             'alarms',\n             'subscriptions',\n             'password']}\n    $ wva get /vehicle\n    {'vehicle': ['vehicle/ecus', 'vehicle/data', 'vehicle/dtc']}\n    $ wva get /vehicle/ecus\n    {'ecus': ['vehicle/ecus/can0ecu0', 'vehicle/ecus/can0ecu251']}\n    $ wva get /vehicle/ecus/can0ecu0\n    {'can0ecu0': ['vehicle/ecus/can0ecu0/name',\n           'vehicle/ecus/can0ecu0/address',\n           'vehicle/ecus/can0ecu0/function',\n           'vehicle/ecus/can0ecu0/bus',\n           'vehicle/ecus/can0ecu0/channel',\n           'vehicle/ecus/can0ecu0/make',\n           'vehicle/ecus/can0ecu0/model',\n           'vehicle/ecus/can0ecu0/serial_number',\n           'vehicle/ecus/can0ecu0/unit_number',\n           'vehicle/ecus/can0ecu0/VIN']}\n    $ wva get /vehicle/ecus/can0ecu0/bus\n    {'bus': 'J1939'}"
  },
  {
    "code": "def add(self, *destinations):\n        buffered_messages = None\n        if not self._any_added:\n            self._any_added = True\n            buffered_messages = self._destinations[0].messages\n            self._destinations = []\n        self._destinations.extend(destinations)\n        if buffered_messages:\n            for message in buffered_messages:\n                self.send(message)",
    "docstring": "Adds new destinations.\n\n        A destination should never ever throw an exception. Seriously.\n        A destination should not mutate the dictionary it is given.\n\n        @param destinations: A list of callables that takes message\n            dictionaries."
  },
  {
    "code": "def fit_transform(self, X, y=None):\n        X_original, missing_mask = self.prepare_input_data(X)\n        observed_mask = ~missing_mask\n        X = X_original.copy()\n        if self.normalizer is not None:\n            X = self.normalizer.fit_transform(X)\n        X_filled = self.fill(X, missing_mask, inplace=True)\n        if not isinstance(X_filled, np.ndarray):\n            raise TypeError(\n                \"Expected %s.fill() to return NumPy array but got %s\" % (\n                    self.__class__.__name__,\n                    type(X_filled)))\n        X_result = self.solve(X_filled, missing_mask)\n        if not isinstance(X_result, np.ndarray):\n            raise TypeError(\n                \"Expected %s.solve() to return NumPy array but got %s\" % (\n                    self.__class__.__name__,\n                    type(X_result)))\n        X_result = self.project_result(X=X_result)\n        X_result[observed_mask] = X_original[observed_mask]\n        return X_result",
    "docstring": "Fit the imputer and then transform input `X`\n\n        Note: all imputations should have a `fit_transform` method,\n        but only some (like IterativeImputer) also support inductive mode\n        using `fit` or `fit_transform` on `X_train` and then `transform`\n        on new `X_test`."
  },
  {
    "code": "def get_index_from_alias(alias_name, index_client=None):\n    index_client = index_client or indices_client()\n    if not index_client.exists_alias(name=alias_name):\n        return None\n    return list(index_client.get_alias(name=alias_name).keys())[0]",
    "docstring": "Retrieve the base index name from an alias\n\n    Args:\n        alias_name (str) Name of the alias\n        index_client (Elasticsearch.IndicesClient) an Elasticsearch index\n            client. Optional, will create one if not given\n\n    Returns: (str) Name of index"
  },
  {
    "code": "def get_syslog(self, service_id, version_number, name):\n\t\tcontent = self._fetch(\"/service/%s/version/%d/syslog/%s\" % (service_id, version_number, name))\n\t\treturn FastlySyslog(self, content)",
    "docstring": "Get the Syslog for a particular service and version."
  },
  {
    "code": "def get_subscription_by_channel_id_and_endpoint_id(\n            self, channel_id, endpoint_id):\n        subscriptions = self.search_subscriptions(\n            channel_id=channel_id, endpoint_id=endpoint_id)\n        try:\n            return subscriptions[0]\n        except IndexError:\n            raise DataFailureException(url, 404, \"No subscription found\")",
    "docstring": "Search for subscription by a given channel and endpoint"
  },
  {
    "code": "def request(self, action, data={}, headers={}, method='GET'):\n        data = self.merge(data, {'user': self.username, 'password': self.password, 'api_id': self.apiId})\n        return Transport.request(self, action, data, headers, method)",
    "docstring": "Append the user authentication details to every incoming request"
  },
  {
    "code": "def cmd_whois_domain(domain):\n    warnings.filterwarnings(\"ignore\")\n    data = whois.whois(domain)\n    data = remove_duplicates(data)\n    print(json.dumps(data, indent=4, default=str))",
    "docstring": "Simple whois client to check domain names.\n\n    Example:\n\n    \\b\n    $ habu.whois.domain portantier.com\n    {\n        \"domain_name\": \"portantier.com\",\n        \"registrar\": \"Amazon Registrar, Inc.\",\n        \"whois_server\": \"whois.registrar.amazon.com\",\n        ..."
  },
  {
    "code": "def start(config, args):\n    global mode\n    if core.is_standalone():\n        from glances.standalone import GlancesStandalone as GlancesMode\n    elif core.is_client():\n        if core.is_client_browser():\n            from glances.client_browser import GlancesClientBrowser as GlancesMode\n        else:\n            from glances.client import GlancesClient as GlancesMode\n    elif core.is_server():\n        from glances.server import GlancesServer as GlancesMode\n    elif core.is_webserver():\n        from glances.webserver import GlancesWebServer as GlancesMode\n    logger.info(\"Start {} mode\".format(GlancesMode.__name__))\n    mode = GlancesMode(config=config, args=args)\n    mode.serve_forever()\n    mode.end()",
    "docstring": "Start Glances."
  },
  {
    "code": "def serialize_close(code: int, reason: str) -> bytes:\n    check_close(code)\n    return struct.pack(\"!H\", code) + reason.encode(\"utf-8\")",
    "docstring": "Serialize the data for a close frame.\n\n    This is the reverse of :func:`parse_close`."
  },
  {
    "code": "def register_incoming_conn(self, conn):\n        assert conn, \"conn is required\"\n        conn.set_outbound_pending_change_callback(self._on_conn_change)\n        self.connections.appendleft(conn)\n        self._set_on_close_cb(conn)\n        self._on_conn_change()",
    "docstring": "Add incoming connection into the heap."
  },
  {
    "code": "def get_key(self, command, args):\n        spec = COMMANDS.get(command.upper())\n        if spec is None:\n            raise UnroutableCommand('The command \"%r\" is unknown to the '\n                                    'router and cannot be handled as a '\n                                    'result.' % command)\n        if 'movablekeys' in spec['flags']:\n            raise UnroutableCommand('The keys for \"%r\" are movable and '\n                                    'as such cannot be routed to a single '\n                                    'host.')\n        keys = extract_keys(args, spec['key_spec'])\n        if len(keys) == 1:\n            return keys[0]\n        elif not keys:\n            raise UnroutableCommand(\n                'The command \"%r\" does not operate on a key which means '\n                'that no suitable host could be determined.  Consider '\n                'using a fanout instead.')\n        raise UnroutableCommand(\n            'The command \"%r\" operates on multiple keys (%d passed) which is '\n            'something that is not supported.' % (command, len(keys)))",
    "docstring": "Returns the key a command operates on."
  },
  {
    "code": "def while_not_sync_standby(self, func):\n        if not self.is_synchronous_mode() or self.patroni.nosync:\n            return func()\n        with self._member_state_lock:\n            self._disable_sync += 1\n        try:\n            if self.touch_member():\n                for _ in polling_loop(timeout=self.dcs.loop_wait*2, interval=2):\n                    try:\n                        if not self.is_sync_standby(self.dcs.get_cluster()):\n                            break\n                    except DCSError:\n                        logger.warning(\"Could not get cluster state, skipping synchronous standby disable\")\n                        break\n                    logger.info(\"Waiting for master to release us from synchronous standby\")\n            else:\n                logger.warning(\"Updating member state failed, skipping synchronous standby disable\")\n            return func()\n        finally:\n            with self._member_state_lock:\n                self._disable_sync -= 1",
    "docstring": "Runs specified action while trying to make sure that the node is not assigned synchronous standby status.\n\n        Tags us as not allowed to be a sync standby as we are going to go away, if we currently are wait for\n        leader to notice and pick an alternative one or if the leader changes or goes away we are also free.\n\n        If the connection to DCS fails we run the action anyway, as this is only a hint.\n\n        There is a small race window where this function runs between a master picking us the sync standby and\n        publishing it to the DCS. As the window is rather tiny consequences are holding up commits for one cycle\n        period we don't worry about it here."
  },
  {
    "code": "def get_client(self, request=None):\n        if not isinstance(request, oauth.Request):\n            request = self.get_oauth_request()\n        client_key = request.get_parameter('oauth_consumer_key')\n        if not client_key:\n            raise Exception('Missing \"oauth_consumer_key\" parameter in ' \\\n                'OAuth \"Authorization\" header')\n        client = models.Client.get_by_key_name(client_key)\n        if not client:\n            raise Exception('Client \"%s\" not found.' % client_key)\n        return client",
    "docstring": "Return the client from the OAuth parameters."
  },
  {
    "code": "def get_permissions(self, grp_name, resource):\n        self.project_service.set_auth(self._token_project)\n        return self.project_service.get_permissions(grp_name, resource)",
    "docstring": "Get permissions associated the group has with the given resource.\n\n        Args:\n            grp_name (string): Name of group.\n            resource (intern.resource.boss.Resource): Identifies which data\n                model object to operate on.\n\n        Returns:\n            (list): List of permissions.\n\n        Raises:\n            requests.HTTPError on failure."
  },
  {
    "code": "def refresh(self):\n        if self.exists:\n            self.delete()\n        self.populate()\n        self.open()",
    "docstring": "Refresh the cache by deleting the old one and creating a new one."
  },
  {
    "code": "def group_dict(self, group: str) -> Dict[str, Any]:\n        return dict(\n            (opt.name, opt.value())\n            for name, opt in self._options.items()\n            if not group or group == opt.group_name\n        )",
    "docstring": "The names and values of options in a group.\n\n        Useful for copying options into Application settings::\n\n            from tornado.options import define, parse_command_line, options\n\n            define('template_path', group='application')\n            define('static_path', group='application')\n\n            parse_command_line()\n\n            application = Application(\n                handlers, **options.group_dict('application'))\n\n        .. versionadded:: 3.1"
  },
  {
    "code": "def get_mod(cls):\n    if isinstance(cls, (type, types.FunctionType)):\n        ret = cls.__module__\n    else:\n        ret = cls.__class__.__module__\n    return ret",
    "docstring": "Returns the string identifying the module that cls is defined in."
  },
  {
    "code": "def get_bug_log(nr):\n    reply = _soap_client_call('get_bug_log', nr)\n    items_el = reply('soapenc:Array')\n    buglogs = []\n    for buglog_el in items_el.children():\n        buglog = {}\n        buglog[\"header\"] = _parse_string_el(buglog_el(\"header\"))\n        buglog[\"body\"] = _parse_string_el(buglog_el(\"body\"))\n        buglog[\"msg_num\"] = int(buglog_el(\"msg_num\"))\n        buglog[\"attachments\"] = []\n        mail_parser = email.feedparser.FeedParser()\n        mail_parser.feed(buglog[\"header\"])\n        mail_parser.feed(\"\\n\\n\")\n        mail_parser.feed(buglog[\"body\"])\n        buglog[\"message\"] = mail_parser.close()\n        buglogs.append(buglog)\n    return buglogs",
    "docstring": "Get Buglogs.\n\n    A buglog is a dictionary with the following mappings:\n        * \"header\" => string\n        * \"body\" => string\n        * \"attachments\" => list\n        * \"msg_num\" => int\n        * \"message\" => email.message.Message\n\n    Parameters\n    ----------\n    nr : int\n        the bugnumber\n\n    Returns\n    -------\n    buglogs : list of dicts"
  },
  {
    "code": "def Add(self, artifact=None, target=None, callback=None):\n    if target is None:\n      target = Target()\n    os_name = target.Get(\"os\") or [None]\n    cpe = target.Get(\"cpe\") or [None]\n    label = target.Get(\"label\") or [None]\n    attributes = itertools.product(os_name, cpe, label)\n    new_conditions = [Condition(artifact, *attr) for attr in attributes]\n    self.conditions.update(new_conditions)\n    self._Register(new_conditions, callback)",
    "docstring": "Add criteria for a check.\n\n    Args:\n      artifact: An artifact name.\n      target: A tuple of artifact necessary to process the data.\n      callback: Entities that should be called if the condition matches."
  },
  {
    "code": "def generate_fetch_ivy(cls, jars, ivyxml, confs, resolve_hash_name):\n    org = IvyUtils.INTERNAL_ORG_NAME\n    name = resolve_hash_name\n    extra_configurations = [conf for conf in confs if conf and conf != 'default']\n    jars_by_key = OrderedDict()\n    for jar in jars:\n      jars_by_key.setdefault((jar.org, jar.name, jar.rev), []).append(jar)\n    dependencies = [cls._generate_fetch_jar_template(_jars) for _jars in jars_by_key.values()]\n    template_data = TemplateData(org=org,\n                                 module=name,\n                                 extra_configurations=extra_configurations,\n                                 dependencies=dependencies)\n    template_relpath = os.path.join('templates', 'ivy_utils', 'ivy_fetch.xml.mustache')\n    cls._write_ivy_xml_file(ivyxml, template_data, template_relpath)",
    "docstring": "Generates an ivy xml with all jars marked as intransitive using the all conflict manager."
  },
  {
    "code": "def invalidate_m2m_cache(sender, instance, model, **kwargs):\n    logger.debug('Received m2m_changed signals from sender {0}'.format(sender))\n    update_model_cache(instance._meta.db_table)\n    update_model_cache(model._meta.db_table)",
    "docstring": "Signal receiver for models to invalidate model cache for many-to-many relationship.\n\n    Parameters\n    ~~~~~~~~~~\n    sender\n        The model class\n    instance\n        The instance whose many-to-many relation is updated.\n    model\n        The class of the objects that are added to, removed from or cleared from the relation."
  },
  {
    "code": "def load(self, rel_path=None):\n        for k, v in self.layer.iteritems():\n            self.add(k, v['module'], v.get('package'))\n            filename = v.get('filename')\n            path = v.get('path')\n            if filename:\n                if not path:\n                    path = rel_path\n                else:\n                    path = os.path.join(rel_path, path)\n                if isinstance(filename, basestring):\n                    filename = os.path.join(path, filename)\n                else:\n                    file_list = [os.path.join(path, f) for f in filename]\n                    filename = os.path.pathsep.join(file_list)\n                self.open(k, filename)",
    "docstring": "Add data_sources to layer and open files with data for the data_source."
  },
  {
    "code": "def get_form_success_data(self, form):\n        data = {\n            \"html\": render_to_string(\n                \"pinax/teams/_invite_form.html\",\n                {\n                    \"invite_form\": self.get_unbound_form(),\n                    \"team\": self.team\n                },\n                request=self.request\n            )\n        }\n        membership = self.membership\n        if membership is not None:\n            if membership.state == Membership.STATE_APPLIED:\n                fragment_class = \".applicants\"\n            elif membership.state == Membership.STATE_INVITED:\n                fragment_class = \".invitees\"\n            elif membership.state in (Membership.STATE_AUTO_JOINED, Membership.STATE_ACCEPTED):\n                fragment_class = {\n                    Membership.ROLE_OWNER: \".owners\",\n                    Membership.ROLE_MANAGER: \".managers\",\n                    Membership.ROLE_MEMBER: \".members\"\n                }[membership.role]\n            data.update({\n                \"append-fragments\": {\n                    fragment_class: render_to_string(\n                        \"pinax/teams/_membership.html\",\n                        {\n                            \"membership\": membership,\n                            \"team\": self.team\n                        },\n                        request=self.request\n                    )\n                }\n            })\n        return data",
    "docstring": "Allows customization of the JSON data returned when a valid form submission occurs."
  },
  {
    "code": "def apparent_dip_correction(axes):\n    a1 = axes[0].copy()\n    a1[-1] = 0\n    cosa = angle(axes[0],a1,cos=True)\n    _ = 1-cosa**2\n    if _ > 1e-12:\n        sina = N.sqrt(_)\n        if cosa < 0:\n            sina *= -1\n        R= N.array([[cosa,sina],[-sina,cosa]])\n    else:\n        R = N.identity(2)\n    return R",
    "docstring": "Produces a two-dimensional rotation matrix that\n    rotates a projected dataset to correct for apparent dip"
  },
  {
    "code": "def _rollout_metadata(batch_env):\n  batch_env_shape = batch_env.observ.get_shape().as_list()\n  batch_size = [batch_env_shape[0]]\n  shapes_types_names = [\n      (batch_size + batch_env_shape[1:], batch_env.observ_dtype, \"observation\"),\n      (batch_size, tf.float32, \"reward\"),\n      (batch_size, tf.bool, \"done\"),\n      (batch_size + list(batch_env.action_shape), batch_env.action_dtype,\n       \"action\"),\n      (batch_size, tf.float32, \"pdf\"),\n      (batch_size, tf.float32, \"value_function\"),\n  ]\n  return shapes_types_names",
    "docstring": "Metadata for rollouts."
  },
  {
    "code": "def _lookup_first(dictionary, key):\n    value = dictionary[key]\n    if type(value) == list:\n        return value[0]\n    else:\n        return value",
    "docstring": "Lookup the first value given a key. Returns the first value if the key\n    refers to a list or the value itself.\n\n    :param dict dictionary: The dictionary to search\n\n    :param str key: The key to get\n\n    :return: Returns the first value available for the key\n    :rtype: str"
  },
  {
    "code": "def save(self, update_site=False, *args, **kwargs):\n        if update_site or (self.id is None and self.site_id is None):\n            self.site_id = current_site_id()\n        super(SiteRelated, self).save(*args, **kwargs)",
    "docstring": "Set the site to the current site when the record is first\n        created, or the ``update_site`` argument is explicitly set\n        to ``True``."
  },
  {
    "code": "def set_bar(self, bar, value):\n        if bar < 0 or bar > 23:\n            return\n        c = (bar if bar < 12 else bar - 12) // 4\n        a = bar % 4\n        if bar >= 12:\n            a += 4\n        self.set_led(c*16+a+8, 1 if value & GREEN > 0 else 0)\n        self.set_led(c*16+a, 1 if value & RED > 0 else 0)",
    "docstring": "Set bar to desired color.  Bar should be a value of 0 to 23, and value\n        should be OFF, GREEN, RED, or YELLOW."
  },
  {
    "code": "def histogram(values, bins=10, vrange=None, title=\"\", c=\"g\", corner=1, lines=True):\n    fs, edges = np.histogram(values, bins=bins, range=vrange)\n    pts = []\n    for i in range(len(fs)):\n        pts.append([(edges[i] + edges[i + 1]) / 2, fs[i]])\n    return xyplot(pts, title, c, corner, lines)",
    "docstring": "Build a 2D histogram from a list of values in n bins.\n\n    Use *vrange* to restrict the range of the histogram.\n\n    Use *corner* to assign its position:\n        - 1, topleft,\n        - 2, topright,\n        - 3, bottomleft,\n        - 4, bottomright.\n\n    .. hint:: Example: |fitplanes.py|_"
  },
  {
    "code": "def fir_from_transfer(transfer, ntaps, window='hanning', ncorner=None):\n    transfer = truncate_transfer(transfer, ncorner=ncorner)\n    impulse = npfft.irfft(transfer)\n    impulse = truncate_impulse(impulse, ntaps=ntaps, window=window)\n    out = numpy.roll(impulse, int(ntaps/2 - 1))[0:ntaps]\n    return out",
    "docstring": "Design a Type II FIR filter given an arbitrary transfer function\n\n    Parameters\n    ----------\n    transfer : `numpy.ndarray`\n        transfer function to start from, must have at least ten samples\n\n    ntaps : `int`\n        number of taps in the final filter, must be an even number\n\n    window : `str`, `numpy.ndarray`, optional\n        window function to truncate with, default: ``'hanning'``\n        see :func:`scipy.signal.get_window` for details on acceptable formats\n\n    ncorner : `int`, optional\n        number of extra samples to zero off at low frequency, default: `None`\n\n    Returns\n    -------\n    out : `numpy.ndarray`\n        A time domain FIR filter of length `ntaps`\n\n    Notes\n    -----\n    The final FIR filter will use `~numpy.fft.rfft` FFT normalisation.\n\n    If `ncorner` is not `None`, then `ncorner` extra samples will be zeroed\n    on the left as a hard highpass filter.\n\n    See Also\n    --------\n    scipy.signal.remez\n        an alternative FIR filter design using the Remez exchange algorithm"
  },
  {
    "code": "def address_target_pairs_from_address_families(self, address_families):\n    single_af = assert_single_element(address_families)\n    addr_tgt_pairs = [\n      (addr, tgt) for addr, tgt in single_af.addressables.items()\n      if addr.target_name == self.name\n    ]\n    if len(addr_tgt_pairs) == 0:\n      raise self._SingleAddressResolutionError(single_af, self.name)\n    assert(len(addr_tgt_pairs) == 1)\n    return addr_tgt_pairs",
    "docstring": "Return the pair for the single target matching the single AddressFamily, or error.\n\n    :raises: :class:`SingleAddress._SingleAddressResolutionError` if no targets could be found for a\n             :class:`SingleAddress` instance.\n    :return: list of (Address, Target) pairs with exactly one element."
  },
  {
    "code": "def _create_function(name, doc=\"\"):\n    def _(col):\n        spark_ctx = SparkContext._active_spark_context\n        java_ctx = (getattr(spark_ctx._jvm.com.sparklingpandas.functions,\n                            name)\n                    (col._java_ctx if isinstance(col, Column) else col))\n        return Column(java_ctx)\n    _.__name__ = name\n    _.__doc__ = doc\n    return _",
    "docstring": "Create a function for aggregator by name"
  },
  {
    "code": "def _ReadSupportedOS(self, definition_values, definition_object, name):\n    supported_os = definition_values.get('supported_os', [])\n    if not isinstance(supported_os, list):\n      raise errors.FormatError(\n          'Invalid supported_os type: {0!s}'.format(type(supported_os)))\n    undefined_supported_os = set(supported_os).difference(self.supported_os)\n    if undefined_supported_os:\n      error_string = (\n          'Artifact definition: {0:s} undefined supported operating system: '\n          '{1:s}.').format(name, ', '.join(undefined_supported_os))\n      raise errors.FormatError(error_string)\n    definition_object.supported_os = supported_os",
    "docstring": "Reads the optional artifact or source type supported OS.\n\n    Args:\n      definition_values (dict[str, object]): artifact definition values.\n      definition_object (ArtifactDefinition|SourceType): the definition object.\n      name (str): name of the artifact definition.\n\n    Raises:\n      FormatError: if there are undefined supported operating systems."
  },
  {
    "code": "def _build_receipt_table(result, billing=\"hourly\", test=False):\n    title = \"OrderId: %s\" % (result.get('orderId', 'No order placed'))\n    table = formatting.Table(['Cost', 'Description'], title=title)\n    table.align['Cost'] = 'r'\n    table.align['Description'] = 'l'\n    total = 0.000\n    if test:\n        prices = result['prices']\n    else:\n        prices = result['orderDetails']['prices']\n    for item in prices:\n        rate = 0.000\n        if billing == \"hourly\":\n            rate += float(item.get('hourlyRecurringFee', 0.000))\n        else:\n            rate += float(item.get('recurringFee', 0.000))\n        total += rate\n        table.add_row([rate, item['item']['description']])\n    table.add_row([\"%.3f\" % total, \"Total %s cost\" % billing])\n    return table",
    "docstring": "Retrieve the total recurring fee of the items prices"
  },
  {
    "code": "def get_dependency_metadata():\n    link = os.path.join(_api_url(), 'meta.txt')\n    return _process_req_txt(requests.get(link)).split('\\n')",
    "docstring": "Returns list of strings with dependency metadata from Dapi"
  },
  {
    "code": "def remove_child_repositories(self, repository_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.remove_child_catalogs(catalog_id=repository_id)\n        return self._hierarchy_session.remove_children(id_=repository_id)",
    "docstring": "Removes all children from a repository.\n\n        arg:    repository_id (osid.id.Id): the ``Id`` of a repository\n        raise:  NotFound - ``repository_id`` not in hierarchy\n        raise:  NullArgument - ``repository_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def agent_path(cls, project, agent):\n        return google.api_core.path_template.expand(\n            'projects/{project}/agents/{agent}',\n            project=project,\n            agent=agent,\n        )",
    "docstring": "Return a fully-qualified agent string."
  },
  {
    "code": "def generate_distance_matrix(source, target, weights=None):\n    if weights is None:\n        weights = ones((source.shape[1], 1))\n    sLen = source.shape[0]\n    tLen = target.shape[0]\n    distMat = zeros((sLen, tLen))\n    for i in range(sLen):\n        for j in range(tLen):\n            distMat[i, j] = euclidean(source[i, :], target[j, :])\n    return distMat",
    "docstring": "Generates a local distance matrix for use in dynamic time warping.\n\n    Parameters\n    ----------\n    source : 2D array\n        Source matrix with features in the second dimension.\n    target : 2D array\n        Target matrix with features in the second dimension.\n\n    Returns\n    -------\n    2D array\n        Local distance matrix."
  },
  {
    "code": "def removeAssociation(self, server_url, handle):\n        assoc = self.getAssociation(server_url, handle)\n        if assoc is None:\n            return 0\n        else:\n            filename = self.getAssociationFilename(server_url, handle)\n            return _removeIfPresent(filename)",
    "docstring": "Remove an association if it exists. Do nothing if it does not.\n\n        (str, str) -> bool"
  },
  {
    "code": "def mobile(self):\n        if self._mobile is None:\n            self._mobile = MobileList(self._version, account_sid=self._solution['account_sid'], )\n        return self._mobile",
    "docstring": "Access the mobile\n\n        :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList\n        :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileList"
  },
  {
    "code": "def prepare_normal_vectors(atomselection):\n    ring_atomselection = [atomselection.coordinates()[a] for a in [0,2,4]]\n    vect1 = self.vector(ring_atomselection[0],ring_atomselection[1])\n    vect2 = self.vector(ring_atomselection[2],ring_atomselection[0])\n    return self.normalize_vector(np.cross(vect1,vect2))",
    "docstring": "Create and normalize a vector across ring plane."
  },
  {
    "code": "def set_deadline(self, end):\n        if self.get_deadline_metadata().is_read_only():\n            raise errors.NoAccess()\n        if not self._is_valid_timestamp(\n                end,\n                self.get_deadline_metadata()):\n            raise errors.InvalidArgument()\n        self._my_map['deadline'] = end",
    "docstring": "Sets the assessment end time.\n\n        arg:    end (timestamp): assessment end time\n        raise:  InvalidArgument - ``end`` is invalid\n        raise:  NoAccess - ``Metadata.isReadOnly()`` is ``true``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def to_representation(self, instance):\n        if not isinstance(instance, dict):\n            data = super(\n                DynamicEphemeralSerializer,\n                self\n            ).to_representation(instance)\n        else:\n            data = instance\n            instance = EphemeralObject(data)\n        if self.id_only():\n            return data\n        else:\n            return tag_dict(data, serializer=self, instance=instance)",
    "docstring": "Provides post processing. Sub-classes should implement their own\n        to_representation method, but pass the resulting dict through\n        this function to get tagging and field selection.\n\n        Arguments:\n            instance: Serialized dict, or object. If object,\n                it will be serialized by the super class's\n                to_representation() method."
  },
  {
    "code": "def get_catalog(self, locale):\n        with translation.override(locale):\n            translation_engine = DjangoTranslation(locale, domain=self.domain, localedirs=self.paths)\n            trans_cat = translation_engine._catalog\n            trans_fallback_cat = translation_engine._fallback._catalog if translation_engine._fallback else {}\n            return trans_cat, trans_fallback_cat",
    "docstring": "Create Django translation catalogue for `locale`."
  },
  {
    "code": "def checkAndCreate(self, key, payload, domainId):\n        if key not in self:\n            self[key] = payload\n        oid = self[key]['id']\n        if not oid:\n            return False\n        subnetDomainIds = []\n        for domain in self[key]['domains']:\n            subnetDomainIds.append(domain['id'])\n        if domainId not in subnetDomainIds:\n            subnetDomainIds.append(domainId)\n            self[key][\"domain_ids\"] = subnetDomainIds\n            if len(self[key][\"domains\"]) is not len(subnetDomainIds):\n                return False\n        return oid",
    "docstring": "Function checkAndCreate\n        Check if a subnet exists and create it if not\n\n        @param key: The targeted subnet\n        @param payload: The targeted subnet description\n        @param domainId: The domainId to be attached wiuth the subnet\n        @return RETURN: The id of the subnet"
  },
  {
    "code": "def poly_energies(samples_like, poly):\n    msg = (\"poly_energies is deprecated and will be removed in dimod 0.9.0.\"\n           \"In the future, use BinaryPolynomial.energies\")\n    warnings.warn(msg, DeprecationWarning)\n    return BinaryPolynomial(poly, 'SPIN').energies(samples_like)",
    "docstring": "Calculates energy of samples from a higher order polynomial.\n\n    Args:\n        sample (samples_like):\n            A collection of raw samples. `samples_like` is an extension of\n            NumPy's array_like structure. See :func:`.as_samples`.\n\n        poly (dict):\n            Polynomial as a dict of form {term: bias, ...}, where `term` is a\n            tuple of variables and `bias` the associated bias. Variable\n            labeling/indexing of terms in poly dict must match that of the\n            sample(s).\n\n    Returns:\n        list/:obj:`numpy.ndarray`: The energy of the sample(s)."
  },
  {
    "code": "def _hardware_count(self):\n        return self._counts.get(\"hardware\") + self._counts.get(\"serial\") + self._counts.get(\"mbed\")",
    "docstring": "Amount of hardware resources.\n\n        :return: integer"
  },
  {
    "code": "def get_log_entries_by_ids(self, log_entry_ids):\n        collection = JSONClientValidated('logging',\n                                         collection='LogEntry',\n                                         runtime=self._runtime)\n        object_id_list = []\n        for i in log_entry_ids:\n            object_id_list.append(ObjectId(self._get_id(i, 'logging').get_identifier()))\n        result = collection.find(\n            dict({'_id': {'$in': object_id_list}},\n                 **self._view_filter()))\n        result = list(result)\n        sorted_result = []\n        for object_id in object_id_list:\n            for object_map in result:\n                if object_map['_id'] == object_id:\n                    sorted_result.append(object_map)\n                    break\n        return objects.LogEntryList(sorted_result, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets a ``LogEntryList`` corresponding to the given ``IdList``.\n\n        In plenary mode, the returned list contains all of the entries\n        specified in the ``Id`` list, in the order of the list,\n        including duplicates, or an error results if an ``Id`` in the\n        supplied list is not found or inaccessible. Otherwise,\n        inaccessible logentries may be omitted from the list and may\n        present the elements in any order including returning a unique\n        set.\n\n        arg:    log_entry_ids (osid.id.IdList): the list of ``Ids`` to\n                retrieve\n        return: (osid.logging.LogEntryList) - the returned ``LogEntry\n                list``\n        raise:  NotFound - an ``Id was`` not found\n        raise:  NullArgument - ``log_entry_ids`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _get_snmpv3(self, oid):\n        snmp_target = (self.hostname, self.snmp_port)\n        cmd_gen = cmdgen.CommandGenerator()\n        (error_detected, error_status, error_index, snmp_data) = cmd_gen.getCmd(\n            cmdgen.UsmUserData(\n                self.user,\n                self.auth_key,\n                self.encrypt_key,\n                authProtocol=self.auth_proto,\n                privProtocol=self.encryp_proto,\n            ),\n            cmdgen.UdpTransportTarget(snmp_target, timeout=1.5, retries=2),\n            oid,\n            lookupNames=True,\n            lookupValues=True,\n        )\n        if not error_detected and snmp_data[0][1]:\n            return text_type(snmp_data[0][1])\n        return \"\"",
    "docstring": "Try to send an SNMP GET operation using SNMPv3 for the specified OID.\n\n        Parameters\n        ----------\n        oid : str\n            The SNMP OID that you want to get.\n\n        Returns\n        -------\n        string : str\n            The string as part of the value from the OID you are trying to retrieve."
  },
  {
    "code": "def _check_valid_data(self, data):\n        if len(data.shape) == 2 and data.shape[1] != 1:\n            raise ValueError('Can only initialize Direction from a single Nx1 array') \n        if np.abs(np.linalg.norm(data) - 1.0) > 1e-4:\n            raise ValueError('Direction data must have norm=1.0')",
    "docstring": "Checks that the incoming data is a Nx1 ndarray.\n\n        Parameters\n        ----------\n        data : :obj:`numpy.ndarray`\n            The data to verify.\n\n        Raises\n        ------\n        ValueError\n            If the data is not of the correct shape or if the vector is not\n            normed."
  },
  {
    "code": "def countbit(self, name, start=None, size=None):\n        if start is not None and size is not None:\n            start = get_integer('start', start)\n            size = get_integer('size', size)\n            return self.execute_command('countbit', name, start, size)\n        elif start is not None:\n            start = get_integer('start', start)            \n            return self.execute_command('countbit', name, start)\n        return self.execute_command('countbit', name)",
    "docstring": "Returns the count of set bits in the value of ``key``.  Optional\n        ``start`` and ``size`` paramaters indicate which bytes to consider.\n\n        Similiar with **Redis.BITCOUNT**\n\n        :param string name: the key name\n        :param int start: Optional, if start is negative, count from start'th\n         character from the end of string.\n        :param int size: Optional, if size is negative, then that many\n         characters will be omitted from the end of string.\n        :return: the count of the bit 1\n        :rtype: int\n        \n        >>> ssdb.set('bit_test', 1)\n        True\n        >>> ssdb.countbit('bit_test')\n        3\n        >>> ssdb.set('bit_test','1234567890')\n        True\n        >>> ssdb.countbit('bit_test', 0, 1)\n        3\n        >>> ssdb.countbit('bit_test', 3, -3)\n        16"
  },
  {
    "code": "def _build_one_legacy(self, req, tempd, python_tag=None):\n        base_args = self._base_setup_args(req)\n        spin_message = 'Building wheel for %s (setup.py)' % (req.name,)\n        with open_spinner(spin_message) as spinner:\n            logger.debug('Destination directory: %s', tempd)\n            wheel_args = base_args + ['bdist_wheel', '-d', tempd] \\\n                + self.build_options\n            if python_tag is not None:\n                wheel_args += [\"--python-tag\", python_tag]\n            try:\n                output = call_subprocess(wheel_args, cwd=req.setup_py_dir,\n                                         show_stdout=False, spinner=spinner)\n            except Exception:\n                spinner.finish(\"error\")\n                logger.error('Failed building wheel for %s', req.name)\n                return None\n            names = os.listdir(tempd)\n            wheel_path = get_legacy_build_wheel_path(\n                names=names,\n                temp_dir=tempd,\n                req=req,\n                command_args=wheel_args,\n                command_output=output,\n            )\n            return wheel_path",
    "docstring": "Build one InstallRequirement using the \"legacy\" build process.\n\n        Returns path to wheel if successfully built. Otherwise, returns None."
  },
  {
    "code": "def warp_by_scalar(dataset, scalars=None, scale_factor=1.0, normal=None,\n                       inplace=False):\n        if scalars is None:\n            field, scalars = dataset.active_scalar_info\n        arr, field = get_scalar(dataset, scalars, preference='point', info=True)\n        if field != vtki.POINT_DATA_FIELD:\n            raise AssertionError('Dataset can only by warped by a point data array.')\n        alg = vtk.vtkWarpScalar()\n        alg.SetInputDataObject(dataset)\n        alg.SetInputArrayToProcess(0, 0, 0, field, scalars)\n        alg.SetScaleFactor(scale_factor)\n        if normal is not None:\n            alg.SetNormal(normal)\n            alg.SetUseNormal(True)\n        alg.Update()\n        output = _get_output(alg)\n        if inplace:\n            dataset.points = output.points\n            return\n        return output",
    "docstring": "Warp the dataset's points by a point data scalar array's values.\n        This modifies point coordinates by moving points along point normals by\n        the scalar amount times the scale factor.\n\n        Parameters\n        ----------\n        scalars : str, optional\n            Name of scalars to warb by. Defaults to currently active scalars.\n\n        scale_factor : float, optional\n            A scalaing factor to increase the scaling effect\n\n        normal : np.array, list, tuple of length 3\n            User specified normal. If given, data normals will be ignored and\n            the given normal will be used to project the warp.\n\n        inplace : bool\n            If True, the points of the give dataset will be updated."
  },
  {
    "code": "def _get_computer_object():\n    with salt.utils.winapi.Com():\n        nt = win32com.client.Dispatch('AdsNameSpaces')\n    return nt.GetObject('', 'WinNT://.,computer')",
    "docstring": "A helper function to get the object for the local machine\n\n    Returns:\n        object: Returns the computer object for the local machine"
  },
  {
    "code": "def tee_lookahead(t, i):\n    for value in islice(t.__copy__(), i, None):\n        return value\n    raise IndexError(i)",
    "docstring": "Inspect the i-th upcomping value from a tee object\n       while leaving the tee object at its current position.\n\n       Raise an IndexError if the underlying iterator doesn't\n       have enough values."
  },
  {
    "code": "def _sample_rows(self, X, Y, sample_shape, seed):\n        if sample_shape[0] is None or X.shape[0] <= sample_shape[0]:\n            X_sample, Y_sample = X, Y\n        elif Y is None:\n            np.random.seed(seed)\n            row_indices = np.random.choice(\n                X.shape[0], size=sample_shape[0], replace=False\n            )\n            X_sample, Y_sample = X.iloc[row_indices], Y\n        else:\n            drop_size = X.shape[0] - sample_shape[0]\n            sample_size = sample_shape[0]\n            sss = StratifiedShuffleSplit(\n                n_splits=2, test_size=drop_size, train_size=sample_size, random_state=seed\n            )\n            row_indices, _ = next(sss.split(X, Y))\n            X_sample, Y_sample = X.iloc[row_indices], Y.iloc[row_indices]\n        return (X_sample, Y_sample)",
    "docstring": "Stratified uniform sampling of rows, according to the classes in Y.\n        Ensures there are enough samples from each class in Y for cross\n        validation."
  },
  {
    "code": "def popitem (self):\n        if self._keys:\n            k = self._keys[0]\n            v = self[k]\n            del self[k]\n            return (k, v)\n        raise KeyError(\"popitem() on empty dictionary\")",
    "docstring": "Remove oldest key from dict and return item."
  },
  {
    "code": "def _decode_length(self, offset, sizeof_char):\n        sizeof_2chars = sizeof_char << 1\n        fmt = \"<2{}\".format('B' if sizeof_char == 1 else 'H')\n        highbit = 0x80 << (8 * (sizeof_char - 1))\n        length1, length2 = unpack(fmt, self.m_charbuff[offset:(offset + sizeof_2chars)])\n        if (length1 & highbit) != 0:\n            length = ((length1 & ~highbit) << (8 * sizeof_char)) | length2\n            size = sizeof_2chars\n        else:\n            length = length1\n            size = sizeof_char\n        if sizeof_char == 1:\n            assert length <= 0x7FFF, \"length of UTF-8 string is too large! At offset={}\".format(offset)\n        else:\n            assert length <= 0x7FFFFFFF, \"length of UTF-16 string is too large!  At offset={}\".format(offset)\n        return length, size",
    "docstring": "Generic Length Decoding at offset of string\n\n        The method works for both 8 and 16 bit Strings.\n        Length checks are enforced:\n        * 8 bit strings: maximum of 0x7FFF bytes (See\n        http://androidxref.com/9.0.0_r3/xref/frameworks/base/libs/androidfw/ResourceTypes.cpp#692)\n        * 16 bit strings: maximum of 0x7FFFFFF bytes (See\n        http://androidxref.com/9.0.0_r3/xref/frameworks/base/libs/androidfw/ResourceTypes.cpp#670)\n\n        :param offset: offset into the string data section of the beginning of\n        the string\n        :param sizeof_char: number of bytes per char (1 = 8bit, 2 = 16bit)\n        :returns: tuple of (length, read bytes)"
  },
  {
    "code": "def get_partition_dciId(self, org_name, part_name, part_info=None):\n        if part_info is None:\n            part_info = self._get_partition(org_name, part_name)\n            LOG.info(\"query result from dcnm for partition info is %s\",\n                     part_info)\n        if part_info is not None and \"dciId\" in part_info:\n            return part_info.get(\"dciId\")",
    "docstring": "get DCI ID for the partition.\n\n        :param org_name: name of organization\n        :param part_name: name of partition"
  },
  {
    "code": "def get_open_fds():\n    pid = os.getpid()\n    procs = subprocess.check_output([\"lsof\", '-w', '-Ff', \"-p\", str(pid)])\n    procs = procs.decode(\"utf-8\")\n    return len([s for s in procs.split('\\n')\n                if s and s[0] == 'f' and s[1:].isdigit()])",
    "docstring": "Return the number of open file descriptors for current process\n\n    .. warning: will only work on UNIX-like OS-es."
  },
  {
    "code": "def get_dimension_by_unit_measure_or_abbreviation(measure_or_unit_abbreviation,**kwargs):\n    unit_abbreviation, factor = _parse_unit(measure_or_unit_abbreviation)\n    units = db.DBSession.query(Unit).filter(Unit.abbreviation==unit_abbreviation).all()\n    if len(units) == 0:\n        raise HydraError('Unit %s not found.'%(unit_abbreviation))\n    elif len(units) > 1:\n        raise HydraError('Unit %s has multiple dimensions not found.'%(unit_abbreviation))\n    else:\n        dimension = db.DBSession.query(Dimension).filter(Dimension.id==units[0].dimension_id).one()\n        return str(dimension.name)",
    "docstring": "Return the physical dimension a given unit abbreviation of a measure, or the measure itself, refers to.\n        The search key is the abbreviation or the full measure"
  },
  {
    "code": "def _makeTimingRelative(absoluteDataList):\n    timingSeq = [row[0] for row in absoluteDataList]\n    valueSeq = [list(row[1:]) for row in absoluteDataList]\n    relTimingSeq, startTime, endTime = makeSequenceRelative(timingSeq)\n    relDataList = [tuple([time, ] + row) for time, row\n                   in zip(relTimingSeq, valueSeq)]\n    return relDataList, startTime, endTime",
    "docstring": "Given normal pitch tier data, puts the times on a scale from 0 to 1\n\n    Input is a list of tuples of the form\n    ([(time1, pitch1), (time2, pitch2),...]\n\n    Also returns the start and end time so that the process can be reversed"
  },
  {
    "code": "def create_response(self, data=None):\n        frame = deepcopy(self)\n        if data is not None:\n            frame.data = data\n        frame.length = 2 + len(frame.data)\n        return frame",
    "docstring": "Create a response frame based on this frame.\n\n        :param data: Data section of response as bytearray. If None, request data section is kept.\n        :return: ModbusTCPFrame instance that represents a response"
  },
  {
    "code": "def size(self):\n        return (0 if self.shape == () else\n                int(np.prod(self.shape, dtype='int64')))",
    "docstring": "Total number of grid points."
  },
  {
    "code": "def read_egginfo_json(pkg_name, filename=DEFAULT_JSON, working_set=None):\n    working_set = working_set or default_working_set\n    dist = find_pkg_dist(pkg_name, working_set=working_set)\n    return read_dist_egginfo_json(dist, filename)",
    "docstring": "Read json from egginfo of a package identified by `pkg_name` that's\n    already installed within the current Python environment."
  },
  {
    "code": "def begin_abort(self, root_pipeline_key, abort_message):\n    def txn():\n      pipeline_record = db.get(root_pipeline_key)\n      if pipeline_record is None:\n        logging.warning(\n            'Tried to abort root pipeline ID \"%s\" but it does not exist.',\n            root_pipeline_key.name())\n        raise db.Rollback()\n      if pipeline_record.status == _PipelineRecord.ABORTED:\n        logging.warning(\n            'Tried to abort root pipeline ID \"%s\"; already in state: %s',\n            root_pipeline_key.name(), pipeline_record.status)\n        raise db.Rollback()\n      if pipeline_record.abort_requested:\n        logging.warning(\n            'Tried to abort root pipeline ID \"%s\"; abort signal already sent.',\n            root_pipeline_key.name())\n        raise db.Rollback()\n      pipeline_record.abort_requested = True\n      pipeline_record.abort_message = abort_message\n      pipeline_record.put()\n      task = taskqueue.Task(\n          url=self.fanout_abort_handler_path,\n          params=dict(root_pipeline_key=root_pipeline_key))\n      task.add(queue_name=self.queue_name, transactional=True)\n      return True\n    return db.run_in_transaction(txn)",
    "docstring": "Kicks off the abort process for a root pipeline and all its children.\n\n    Args:\n      root_pipeline_key: db.Key of the root pipeline to abort.\n      abort_message: Message explaining why the abort happened, only saved\n          into the root pipeline.\n\n    Returns:\n      True if the abort signal was sent successfully; False otherwise."
  },
  {
    "code": "def info_count(i: int, n: int, *rest: Token, **kwargs: Any) -> None:\n    num_digits = len(str(n))\n    counter_format = \"(%{}d/%d)\".format(num_digits)\n    counter_str = counter_format % (i + 1, n)\n    info(green, \"*\", reset, counter_str, reset, *rest, **kwargs)",
    "docstring": "Display a counter before the rest of the message.\n\n    ``rest`` and ``kwargs`` are passed to :func:`info`\n\n    Current index should start at 0 and end at ``n-1``, like in ``enumerate()``\n\n    :param i: current index\n    :param n: total number of items"
  },
  {
    "code": "def GetMemUsedMB(self):\n        counter = c_uint()\n        ret = vmGuestLib.VMGuestLib_GetMemUsedMB(self.handle.value, byref(counter))\n        if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)\n        return counter.value",
    "docstring": "Retrieves the estimated amount of physical host memory currently\n           consumed for this virtual machine's physical memory."
  },
  {
    "code": "def png(self):\n        use_plugin('freeimage')\n        with TemporaryFilePath(suffix='.png') as tmp:\n            safe_range_im = 255 * normalise(self)\n            imsave(tmp.fpath, safe_range_im.astype(np.uint8))\n            with open(tmp.fpath, 'rb') as fh:\n                return fh.read()",
    "docstring": "Return png string of image."
  },
  {
    "code": "def _parse_canonical_int32(doc):\n    i_str = doc['$numberInt']\n    if len(doc) != 1:\n        raise TypeError('Bad $numberInt, extra field(s): %s' % (doc,))\n    if not isinstance(i_str, string_type):\n        raise TypeError('$numberInt must be string: %s' % (doc,))\n    return int(i_str)",
    "docstring": "Decode a JSON int32 to python int."
  },
  {
    "code": "def loadedfields(self):\n        if self._loadedfields is None:\n            for field in self._meta.scalarfields:\n                yield field\n        else:\n            fields = self._meta.dfields\n            processed = set()\n            for name in self._loadedfields:\n                if name in processed:\n                    continue\n                if name in fields:\n                    processed.add(name)\n                    yield fields[name]\n                else:\n                    name = name.split(JSPLITTER)[0]\n                    if name in fields and name not in processed:\n                        field = fields[name]\n                        if field.type == 'json object':\n                            processed.add(name)\n                            yield field",
    "docstring": "Generator of fields loaded from database"
  },
  {
    "code": "def is_inside_any(dir_list, fname):\n    for dirname in dir_list:\n        if is_inside(dirname, fname):\n            return True\n    return False",
    "docstring": "True if fname is inside any of given dirs."
  },
  {
    "code": "def shutdown(self, vm_names=None, reboot=False):\n        self.virt_env.shutdown(vm_names, reboot)",
    "docstring": "Shutdown this prefix\n\n        Args:\n            vm_names(list of str): List of the vms to shutdown\n            reboot(bool): If true, reboot the requested vms\n\n        Returns:\n            None"
  },
  {
    "code": "def altshuler_debyetemp(v, v0, gamma0, gamma_inf, beta, theta0):\n    x = v / v0\n    if isuncertainties([v, v0, gamma0, gamma_inf, beta, theta0]):\n        theta = theta0 * np.power(x, -1. * gamma_inf) *\\\n            unp.exp((gamma0 - gamma_inf) / beta * (1. - np.power(x, beta)))\n    else:\n        theta = theta0 * np.power(x, -1. * gamma_inf) *\\\n            np.exp((gamma0 - gamma_inf) / beta * (1. - np.power(x, beta)))\n    return theta",
    "docstring": "calculate Debye temperature for Altshuler equation\n\n    :param v: unit-cell volume in A^3\n    :param v0: unit-cell volume in A^3 at 1 bar\n    :param gamma0: Gruneisen parameter at 1 bar\n    :param gamma_inf: Gruneisen parameter at infinite pressure\n    :param beta: volume dependence of Gruneisen parameter\n    :param theta0: Debye temperature at 1 bar in K\n    :return: Debye temperature in K"
  },
  {
    "code": "def utterances_from_eaf(eaf_path: Path, tier_prefixes: Tuple[str, ...]) -> List[Utterance]:\n    if not eaf_path.is_file():\n        raise FileNotFoundError(\"Cannot find {}\".format(eaf_path))\n    eaf = Eaf(eaf_path)\n    utterances = []\n    for tier_name in sorted(list(eaf.tiers)):\n        for tier_prefix in tier_prefixes:\n            if tier_name.startswith(tier_prefix):\n                utterances.extend(utterances_from_tier(eaf, tier_name))\n                break\n    return utterances",
    "docstring": "Extracts utterances in tiers that start with tier_prefixes found in the ELAN .eaf XML file\n    at eaf_path.\n\n    For example, if xv@Mark is a tier in the eaf file, and\n    tier_prefixes = [\"xv\"], then utterances from that tier will be gathered."
  },
  {
    "code": "def parse_connection_option(\n    header: str, pos: int, header_name: str\n) -> Tuple[ConnectionOption, int]:\n    item, pos = parse_token(header, pos, header_name)\n    return cast(ConnectionOption, item), pos",
    "docstring": "Parse a Connection option from ``header`` at the given position.\n\n    Return the protocol value and the new position.\n\n    Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs."
  },
  {
    "code": "def multi_substitution(*substitutions):\n\tsubstitutions = itertools.starmap(substitution, substitutions)\n\tsubstitutions = reversed(tuple(substitutions))\n\treturn compose(*substitutions)",
    "docstring": "Take a sequence of pairs specifying substitutions, and create\n\ta function that performs those substitutions.\n\n\t>>> multi_substitution(('foo', 'bar'), ('bar', 'baz'))('foo')\n\t'baz'"
  },
  {
    "code": "def _get_run_info_dict(self, run_id):\n    run_info_path = os.path.join(self._settings.info_dir, run_id, 'info')\n    if os.path.exists(run_info_path):\n      return RunInfo(run_info_path).get_as_dict()\n    else:\n      return None",
    "docstring": "Get the RunInfo for a run, as a dict."
  },
  {
    "code": "def data_ma(self):\n        mask = (self._segment_img[self.slices] != self.label)\n        return np.ma.masked_array(self._segment_img[self.slices], mask=mask)",
    "docstring": "A 2D `~numpy.ma.MaskedArray` cutout image of the segment using\n        the minimal bounding box.\n\n        The mask is `True` for pixels outside of the source segment\n        (i.e. neighboring segments within the rectangular cutout image\n        are masked)."
  },
  {
    "code": "def srp1(*args, **kargs):\n    ans, _ = srp(*args, **kargs)\n    if len(ans) > 0:\n        return ans[0][1]\n    else:\n        return None",
    "docstring": "Send and receive packets at layer 2 and return only the first answer"
  },
  {
    "code": "def indirectStarter(url, latestSearch):\n    @classmethod\n    def _starter(cls):\n        data = cls.getPage(url)\n        return cls.fetchUrl(url, data, latestSearch)\n    return _starter",
    "docstring": "Get start URL by indirection."
  },
  {
    "code": "def save(self):\n        if self.path.is_collection:\n            self.session.post_json(self.href,\n                                   {self.type: dict(self.data)},\n                                   cls=ResourceEncoder)\n        else:\n            self.session.put_json(self.href,\n                                  {self.type: dict(self.data)},\n                                  cls=ResourceEncoder)\n        return self.fetch(exclude_children=True, exclude_back_refs=True)",
    "docstring": "Save the resource to the API server\n\n        If the resource doesn't have a uuid the resource will be created.\n        If uuid is present the resource is updated.\n\n        :rtype: Resource"
  },
  {
    "code": "def api_retrieve(self, api_key=None):\n\t\tapi_key = api_key or self.default_api_key\n\t\treturn self.stripe_class.retrieve(\n\t\t\tid=self.id, api_key=api_key, expand=self.expand_fields\n\t\t)",
    "docstring": "Call the stripe API's retrieve operation for this model.\n\n\t\t:param api_key: The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.\n\t\t:type api_key: string"
  },
  {
    "code": "def next(self):\n        if self.idx >= len(self.page_list):\n            raise StopIteration()\n        page = self.page_list[self.idx]\n        self.idx += 1\n        return page",
    "docstring": "Provide the next element of the list."
  },
  {
    "code": "def debugging():\n    print(\"In debugging\")\n    json_file = r\"C:\\Scripting\\Processing\\Cell\" \\\n                r\"data\\outdata\\SiBEC\\cellpy_batch_bec_exp02.json\"\n    b = init(default_log_level=\"DEBUG\")\n    b.load_info_df(json_file)\n    print(b.info_df.head())\n    b.export_raw = False\n    b.export_cycles = False\n    b.export_ica = False\n    b.save_cellpy_file = True\n    b.force_raw_file = False\n    b.force_cellpy_file = True\n    b.load_and_save_raw(parent_level=\"cellpydata\")",
    "docstring": "This one I use for debugging..."
  },
  {
    "code": "def get_member_class(resource):\n    reg = get_current_registry()\n    if IInterface in provided_by(resource):\n        member_class = reg.getUtility(resource, name='member-class')\n    else:\n        member_class = reg.getAdapter(resource, IMemberResource,\n                                      name='member-class')\n    return member_class",
    "docstring": "Returns the registered member class for the given resource.\n\n    :param resource: registered resource\n    :type resource: class implementing or instance providing or subclass of\n        a registered resource interface."
  },
  {
    "code": "def username_or(user, attr):\n    if not settings.ACCOUNTS_NO_USERNAME:\n        attr = \"username\"\n    value = getattr(user, attr)\n    if callable(value):\n        value = value()\n    return value",
    "docstring": "Returns the user's username for display, or an alternate attribute\n    if ``ACCOUNTS_NO_USERNAME`` is set to ``True``."
  },
  {
    "code": "def image_from_simplestreams(server,\n                             alias,\n                             remote_addr=None,\n                             cert=None,\n                             key=None,\n                             verify_cert=True,\n                             aliases=None,\n                             public=False,\n                             auto_update=False,\n                             _raw=False):\n    if aliases is None:\n        aliases = []\n    client = pylxd_client_get(remote_addr, cert, key, verify_cert)\n    try:\n        image = client.images.create_from_simplestreams(\n            server, alias, public=public, auto_update=auto_update\n        )\n    except pylxd.exceptions.LXDAPIException as e:\n        raise CommandExecutionError(six.text_type(e))\n    for alias in aliases:\n        image_alias_add(image, alias)\n    if _raw:\n        return image\n    return _pylxd_model_to_dict(image)",
    "docstring": "Create an image from simplestreams\n\n        server :\n            Simplestreams server URI\n\n        alias :\n            The alias of the image to retrieve\n\n        remote_addr :\n            An URL to a remote Server, you also have to give cert and key if\n            you provide remote_addr and its a TCP Address!\n\n            Examples:\n                https://myserver.lan:8443\n                /var/lib/mysocket.sock\n\n        cert :\n            PEM Formatted SSL Certificate.\n\n            Examples:\n                ~/.config/lxc/client.crt\n\n        key :\n            PEM Formatted SSL Key.\n\n            Examples:\n                ~/.config/lxc/client.key\n\n        verify_cert : True\n            Wherever to verify the cert, this is by default True\n            but in the most cases you want to set it off as LXD\n            normaly uses self-signed certificates.\n\n        aliases : []\n            List of aliases to append to the copied image\n\n        public : False\n            Make this image public available\n\n        auto_update : False\n            Should LXD auto update that image?\n\n        _raw : False\n            Return the raw pylxd object or a dict of the image?\n\n        CLI Examples:\n\n        ..code-block:: bash\n\n            $ salt '*' lxd.image_from_simplestreams \"https://cloud-images.ubuntu.com/releases\" \"trusty/amd64\" aliases='[\"t\", \"trusty/amd64\"]' auto_update=True"
  },
  {
    "code": "def _has_perm(self, user, permission):\n        if user.is_superuser:\n            return True\n        if user.is_active:\n            perms = [perm.split('.')[1] for perm in user.get_all_permissions()]\n            return permission in perms\n        return False",
    "docstring": "Check whether the user has the given permission\n\n        @return True if user is granted with access, False if not."
  },
  {
    "code": "def nla_parse(tb, maxtype, head, len_, policy):\n    rem = c_int()\n    for nla in nla_for_each_attr(head, len_, rem):\n        type_ = nla_type(nla)\n        if type_ > maxtype:\n            continue\n        if policy:\n            err = validate_nla(nla, maxtype, policy)\n            if err < 0:\n                return err\n        if type_ in tb and tb[type_]:\n            _LOGGER.debug('Attribute of type %d found multiple times in message, previous attribute is being ignored.',\n                          type_)\n        tb[type_] = nla\n    if rem.value > 0:\n        _LOGGER.debug('netlink: %d bytes leftover after parsing attributes.', rem.value)\n    return 0",
    "docstring": "Create attribute index based on a stream of attributes.\n\n    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L242\n\n    Iterates over the stream of attributes and stores a pointer to each attribute in the index array using the attribute\n    type as index to the array. Attribute with a type greater than the maximum type specified will be silently ignored\n    in order to maintain backwards compatibility. If `policy` is not None, the attribute will be validated using the\n    specified policy.\n\n    Positional arguments:\n    tb -- dictionary to be filled (maxtype+1 elements).\n    maxtype -- maximum attribute type expected and accepted (integer).\n    head -- first nlattr with more in its bytearray payload (nlattr class instance).\n    len_ -- length of attribute stream (integer).\n    policy -- dictionary of nla_policy class instances as values, with nla types as keys.\n\n    Returns:\n    0 on success or a negative error code."
  },
  {
    "code": "def append_string(self, field, header=False):\n        bits = field.split('=', 1)\n        if len(bits) != 2:\n            raise ValueError(\"Field missing '=' separator.\")\n        try:\n            tag_int = int(bits[0])\n        except ValueError:\n            raise ValueError(\"Tag value must be an integer\")\n        self.append_pair(tag_int, bits[1], header=header)\n        return",
    "docstring": "Append a tag=value pair in string format.\n\n        :param field: String \"tag=value\" to be appended to this message.\n        :param header: Append to header if True; default to body.\n\n        The string is split at the first '=' character, and the resulting\n        tag and value strings are appended to the message."
  },
  {
    "code": "def send_message(\n            self,\n            title=None,\n            body=None,\n            icon=None,\n            data=None,\n            sound=None,\n            badge=None,\n            api_key=None,\n            **kwargs):\n        if self:\n            from .fcm import fcm_send_bulk_message\n            registration_ids = list(self.filter(active=True).values_list(\n                'registration_id',\n                flat=True\n            ))\n            if len(registration_ids) == 0:\n                return [{'failure': len(self), 'success': 0}]\n            result = fcm_send_bulk_message(\n                registration_ids=registration_ids,\n                title=title,\n                body=body,\n                icon=icon,\n                data=data,\n                sound=sound,\n                badge=badge,\n                api_key=api_key,\n                **kwargs\n            )\n            self._deactivate_devices_with_error_results(\n                registration_ids,\n                result['results']\n            )\n            return result",
    "docstring": "Send notification for all active devices in queryset and deactivate if\n        DELETE_INACTIVE_DEVICES setting is set to True."
  },
  {
    "code": "def calculate_median(given_list):\n        median = None\n        if not given_list:\n            return median\n        given_list = sorted(given_list)\n        list_length = len(given_list)\n        if list_length % 2:\n            median = given_list[int(list_length / 2)]\n        else:\n            median = (given_list[int(list_length / 2)] + given_list[int(list_length / 2) - 1]) / 2.0\n        return median",
    "docstring": "Returns the median of values in the given list."
  },
  {
    "code": "def get_cli_argument(self, command, name):\n        parts = command.split()\n        result = CLIArgumentType()\n        for index in range(0, len(parts) + 1):\n            probe = ' '.join(parts[0:index])\n            override = self.arguments.get(probe, {}).get(name, None)\n            if override:\n                result.update(override)\n        return result",
    "docstring": "Get the argument for the command after applying the scope hierarchy\n\n        :param command: The command that we want the argument for\n        :type command: str\n        :param name: The name of the argument\n        :type name: str\n        :return: The CLI command after all overrides in the scope hierarchy have been applied\n        :rtype: knack.arguments.CLIArgumentType"
  },
  {
    "code": "def run(configobj=None):\n    acssum(configobj['input'],\n           configobj['output'],\n           exec_path=configobj['exec_path'],\n           time_stamps=configobj['time_stamps'],\n           verbose=configobj['verbose'],\n           quiet=configobj['quiet']\n           )",
    "docstring": "TEAL interface for the `acssum` function."
  },
  {
    "code": "def report_score_vs_rmsd_funnels(designs, path):\n    from matplotlib.backends.backend_pdf import PdfPages\n    import matplotlib.pyplot as plt\n    print \"Reporting score vs RMSD funnels...\"\n    pdf = PdfPages(path)\n    designs = sorted(designs, key=lambda x: x.fancy_path)\n    for index, design in enumerate(designs):\n        plt.figure(figsize=(8.5, 11))\n        plt.suptitle(design.fancy_path)\n        axes = plt.subplot(2, 1, 1)\n        plot_score_vs_dist(axes, design, metric=\"Max COOH Distance\")\n        axes = plt.subplot(2, 1, 2)\n        plot_score_vs_dist(axes, design, metric=\"Loop RMSD\")\n        pdf.savefig(orientation='portrait')\n        plt.close()\n    pdf.close()",
    "docstring": "Create a PDF showing the score vs. RMSD funnels for all the reasonable\n    designs.  This method was copied from an old version of this script, and\n    does not currently work."
  },
  {
    "code": "def partition(molList, options):\n    status_field = options.status_field\n    active_label = options.active_label\n    decoy_label = options.decoy_label\n    activeList = []\n    decoyList = []\n    for mol in molList:\n        if mol.GetProp(status_field) == active_label:\n            activeList.append(mol)\n        elif mol.GetProp(status_field) == decoy_label:\n            decoyList.append(mol)\n    return activeList, decoyList",
    "docstring": "Partition molList into activeList and decoyList"
  },
  {
    "code": "def aligner_from_header(in_bam):\n    from bcbio.pipeline.alignment import TOOLS\n    with pysam.Samfile(in_bam, \"rb\") as bamfile:\n        for pg in bamfile.header.get(\"PG\", []):\n            for ka in TOOLS.keys():\n                if pg.get(\"PN\", \"\").lower().find(ka) >= 0:\n                    return ka",
    "docstring": "Identify aligner from the BAM header; handling pre-aligned inputs."
  },
  {
    "code": "def trace_start(self):\n        cmd = enums.JLinkTraceCommand.START\n        res = self._dll.JLINKARM_TRACE_Control(cmd, 0)\n        if (res == 1):\n            raise errors.JLinkException('Failed to start trace.')\n        return None",
    "docstring": "Starts collecting trace data.\n\n        Args:\n          self (JLink): the ``JLink`` instance.\n\n        Returns:\n          ``None``"
  },
  {
    "code": "def attach_files(self, files: Sequence[AttachedFile]):\n        assert not self._content, 'content must be empty to attach files.'\n        self.content_type = 'multipart/form-data'\n        self._attached_files = files",
    "docstring": "Attach a list of files represented as AttachedFile."
  },
  {
    "code": "def validate_categories(categories):\n        if not set(categories) <= Source.categories:\n            invalid = list(set(categories) - Source.categories)\n            raise ValueError('Invalid categories: %s' % invalid)",
    "docstring": "Take an iterable of source categories and raise ValueError if some \n        of them are invalid."
  },
  {
    "code": "def crps(self):\n        return np.sum(self.errors[\"F_2\"].values - self.errors[\"F_O\"].values * 2.0 + self.errors[\"O_2\"].values) / \\\n            (self.thresholds.size * self.num_forecasts)",
    "docstring": "Calculates the continuous ranked probability score."
  },
  {
    "code": "def if_not_exists(self):\n        if self.model._has_counter:\n            raise IfNotExistsWithCounterColumn('if_not_exists cannot be used with tables containing counter columns')\n        clone = copy.deepcopy(self)\n        clone._if_not_exists = True\n        return clone",
    "docstring": "Check the existence of an object before insertion.\n\n        If the insertion isn't applied, a LWTException is raised."
  },
  {
    "code": "def blend_palette(colors, n_colors=6, as_cmap=False):\n    name = \"-\".join(map(str, colors))\n    pal = mpl.colors.LinearSegmentedColormap.from_list(name, colors)\n    if not as_cmap:\n        pal = pal(np.linspace(0, 1, n_colors))\n    return pal",
    "docstring": "Make a palette that blends between a list of colors.\n\n    Parameters\n    ----------\n    colors : sequence of matplotlib colors\n        hex, rgb-tuple, or html color name\n    n_colors : int, optional\n        number of colors in the palette\n    as_cmap : bool, optional\n        if True, return as a matplotlib colormap instead of list\n\n    Returns\n    -------\n    palette : list or colormap"
  },
  {
    "code": "def refresh_metrics(self):\n        metrics = self.get_metrics()\n        dbmetrics = (\n            db.session.query(DruidMetric)\n            .filter(DruidMetric.datasource_id == self.datasource_id)\n            .filter(DruidMetric.metric_name.in_(metrics.keys()))\n        )\n        dbmetrics = {metric.metric_name: metric for metric in dbmetrics}\n        for metric in metrics.values():\n            dbmetric = dbmetrics.get(metric.metric_name)\n            if dbmetric:\n                for attr in ['json', 'metric_type']:\n                    setattr(dbmetric, attr, getattr(metric, attr))\n            else:\n                with db.session.no_autoflush:\n                    metric.datasource_id = self.datasource_id\n                    db.session.add(metric)",
    "docstring": "Refresh metrics based on the column metadata"
  },
  {
    "code": "def set_monitoring(module):\n    def monitoring(is_monitoring,\n                   track_data=None,\n                   track_grad=None,\n                   track_update=None,\n                   track_update_ratio=None):\n        module.is_monitoring = is_monitoring\n        module.track_data = track_data if track_data is not None else module.track_data\n        module.track_grad = track_grad if track_grad is not None else module.track_grad\n        module.track_update = track_update if track_update is not None else module.track_update\n        module.track_update_ratio = track_update_ratio if track_update_ratio is not None else module.track_update_ratio\n    module.monitoring = monitoring",
    "docstring": "Defines the monitoring method on the module."
  },
  {
    "code": "def load_cufflinks(self, filter_ok=True):\n        return \\\n            pd.concat(\n                [self._load_single_patient_cufflinks(patient, filter_ok) for patient in self],\n                copy=False\n        )",
    "docstring": "Load a Cufflinks gene expression data for a cohort\n\n        Parameters\n        ----------\n        filter_ok : bool, optional\n            If true, filter Cufflinks data to row with FPKM_status == \"OK\"\n\n        Returns\n        -------\n        cufflinks_data : Pandas dataframe\n            Pandas dataframe with Cufflinks data for all patients\n            columns include patient_id, gene_id, gene_short_name, FPKM, FPKM_conf_lo, FPKM_conf_hi"
  },
  {
    "code": "def token_urlsafe(nbytes=32):\n    tok = os.urandom(nbytes)\n    return base64.urlsafe_b64encode(tok).rstrip(b'=').decode('ascii')",
    "docstring": "Return a random URL-safe text string, in Base64 encoding.\n\n    This is taken and slightly modified from the Python 3.6 stdlib.\n\n    The string has *nbytes* random bytes.  If *nbytes* is ``None``\n    or not supplied, a reasonable default is used.\n\n    >>> token_urlsafe(16)  #doctest:+SKIP\n    'Drmhze6EPcv0fN_81Bj-nA'"
  },
  {
    "code": "def save(self, filename, format=None, **kwargs):\n        if format is None:\n            format = format_from_extension(filename)\n        with file(filename, 'wb') as fp:\n            self.save_to_file_object(fp, format, **kwargs)",
    "docstring": "Save the object to file given by filename."
  },
  {
    "code": "def load_ipython_extension(ip):\n    ip.register_magics(CustomMagics)\n    patch = (\"IPython.config.cell_magic_highlight['clrmagic'] = \"\n             \"{'reg':[/^%%CS/]};\")\n    js = display.Javascript(data=patch,\n                            lib=[\"https://github.com/codemirror/CodeMirror/blob/master/mode/clike/clike.js\"])",
    "docstring": "register magics function, can be called from a notebook"
  },
  {
    "code": "def exam_reliability_by_datetime(\n        datetime_axis, datetime_new_axis, reliable_distance):\n    numeric_datetime_axis = [\n        totimestamp(a_datetime) for a_datetime in datetime_axis\n    ]\n    numeric_datetime_new_axis = [\n        totimestamp(a_datetime) for a_datetime in datetime_new_axis\n    ]\n    return exam_reliability(numeric_datetime_axis, numeric_datetime_new_axis,\n                            reliable_distance, precision=0)",
    "docstring": "A datetime-version that takes datetime object list as x_axis\n    reliable_distance equals to the time difference in seconds."
  },
  {
    "code": "def is_lagging(self, wal_position):\n        lag = (self.cluster.last_leader_operation or 0) - wal_position\n        return lag > self.patroni.config.get('maximum_lag_on_failover', 0)",
    "docstring": "Returns if instance with an wal should consider itself unhealthy to be promoted due to replication lag.\n\n        :param wal_position: Current wal position.\n        :returns True when node is lagging"
  },
  {
    "code": "def _contains_yieldpoint(children):\n    if isinstance(children, dict):\n        return any(isinstance(i, YieldPoint) for i in children.values())\n    if isinstance(children, list):\n        return any(isinstance(i, YieldPoint) for i in children)\n    return False",
    "docstring": "Returns True if ``children`` contains any YieldPoints.\n\n    ``children`` may be a dict or a list, as used by `MultiYieldPoint`\n    and `multi_future`."
  },
  {
    "code": "def clear_session(self, response):\n        session.clear()\n        if 'flask_login' in sys.modules:\n            remember_cookie = current_app.config.get('REMEMBER_COOKIE',\n                                                     'remember_token')\n            response.set_cookie(remember_cookie, '', expires=0, max_age=0)",
    "docstring": "Clear the session.\n\n        This method is invoked when the session is found to be invalid.\n        Subclasses can override this method to implement a custom session\n        reset."
  },
  {
    "code": "async def handle_agent_job_started(self, agent_addr, message: AgentJobStarted):\n        self._logger.debug(\"Job %s %s started on agent %s\", message.job_id[0], message.job_id[1], agent_addr)\n        await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobStarted(message.job_id[1]))",
    "docstring": "Handle an AgentJobStarted message. Send the data back to the client"
  },
  {
    "code": "def get(self, key, failobj=None, exact=0):\n        if not exact:\n            try:\n                key = self.getfullkey(key)\n            except KeyError:\n                return failobj\n        return self.data.get(key,failobj)",
    "docstring": "Returns failobj if key is not found or is ambiguous"
  },
  {
    "code": "def load_tiff(filename, crs=None, apply_transform=False, nan_nodata=False, **kwargs):\n    try:\n        import xarray as xr\n    except:\n        raise ImportError('Loading tiffs requires xarray to be installed')\n    with warnings.catch_warnings():\n        warnings.filterwarnings('ignore')\n        da = xr.open_rasterio(filename)\n    return from_xarray(da, crs, apply_transform, nan_nodata, **kwargs)",
    "docstring": "Returns an RGB or Image element loaded from a geotiff file.\n\n    The data is loaded using xarray and rasterio. If a crs attribute\n    is present on the loaded data it will attempt to decode it into\n    a cartopy projection otherwise it will default to a non-geographic\n    HoloViews element.\n\n    Parameters\n    ----------\n    filename: string\n      Filename pointing to geotiff file to load\n    crs: Cartopy CRS or EPSG string (optional)\n      Overrides CRS inferred from the data\n    apply_transform: boolean\n      Whether to apply affine transform if defined on the data\n    nan_nodata: boolean\n      If data contains nodata values convert them to NaNs\n    **kwargs:\n      Keyword arguments passed to the HoloViews/GeoViews element\n\n    Returns\n    -------\n    element: Image/RGB/QuadMesh element"
  },
  {
    "code": "def trainModel(model, loader, optimizer, device, criterion=F.nll_loss,\n               batches_in_epoch=sys.maxsize, batch_callback=None,\n               progress_bar=None):\n  model.train()\n  if progress_bar is not None:\n    loader = tqdm(loader, **progress_bar)\n    if batches_in_epoch < len(loader):\n      loader.total = batches_in_epoch\n  for batch_idx, (data, target) in enumerate(loader):\n    data, target = data.to(device), target.to(device)\n    optimizer.zero_grad()\n    output = model(data)\n    loss = criterion(output, target)\n    loss.backward()\n    optimizer.step()\n    if batch_callback is not None:\n      batch_callback(model=model, batch_idx=batch_idx)\n    if batch_idx >= batches_in_epoch:\n      break\n  if progress_bar is not None:\n    loader.n = loader.total\n    loader.close()",
    "docstring": "Train the given model by iterating through mini batches. An epoch\n  ends after one pass through the training set, or if the number of mini\n  batches exceeds the parameter \"batches_in_epoch\".\n\n  :param model: pytorch model to be trained\n  :type model: torch.nn.Module\n  :param loader: train dataset loader\n  :type loader: :class:`torch.utils.data.DataLoader`\n  :param optimizer: Optimizer object used to train the model.\n         This function will train the model on every batch using this optimizer\n         and the :func:`torch.nn.functional.nll_loss` function\n  :param batches_in_epoch: Max number of mini batches to train.\n  :param device: device to use ('cpu' or 'cuda')\n  :type device: :class:`torch.device\n  :param criterion: loss function to use\n  :type criterion: function\n  :param batch_callback: Callback function to be called on every batch with the\n                         following parameters: model, batch_idx\n  :type batch_callback: function\n  :param progress_bar: Optional :class:`tqdm` progress bar args.\n                       None for no progress bar\n  :type progress_bar: dict or None"
  },
  {
    "code": "def _get_resource_list(self, rsrc_dict):\n        if 'collections' in rsrc_dict:\n            return rsrc_dict['collections']\n        if 'experiments' in rsrc_dict:\n            return rsrc_dict['experiments']\n        if 'channels' in rsrc_dict:\n            return rsrc_dict['channels']\n        if 'coords' in rsrc_dict:\n            return rsrc_dict['coords']\n        raise RuntimeError('Invalid list response received from Boss.  No known resource type returned.')",
    "docstring": "Extracts list of resources from the HTTP response.\n\n        Args:\n            rsrc_dict (dict): HTTP response encoded in a dictionary.\n\n        Returns:\n            (list[string]): List of a type of resource (collections, experiments, etc).\n\n        Raises:\n            (RuntimeError): If rsrc_dict does not contain any known resources."
  },
  {
    "code": "def dedent(string, indent_str='   ', max_levels=None):\n    if len(indent_str) == 0:\n        return string\n    lines = string.splitlines()\n    def num_indents(line):\n        max_num = int(np.ceil(len(line) / len(indent_str)))\n        for i in range(max_num):\n            if line.startswith(indent_str):\n                line = line[len(indent_str):]\n            else:\n                break\n        return i\n    num_levels = num_indents(min(lines, key=num_indents))\n    if max_levels is not None:\n        num_levels = min(num_levels, max_levels)\n    dedent_len = num_levels * len(indent_str)\n    return '\\n'.join(line[dedent_len:] for line in lines)",
    "docstring": "Revert the effect of indentation.\n\n    Examples\n    --------\n    Remove a simple one-level indentation:\n\n    >>> text = '''<->This is line 1.\n    ... <->Next line.\n    ... <->And another one.'''\n    >>> print(text)\n    <->This is line 1.\n    <->Next line.\n    <->And another one.\n    >>> print(dedent(text, '<->'))\n    This is line 1.\n    Next line.\n    And another one.\n\n    Multiple levels of indentation:\n\n    >>> text = '''<->Level 1.\n    ... <-><->Level 2.\n    ... <-><-><->Level 3.'''\n    >>> print(text)\n    <->Level 1.\n    <-><->Level 2.\n    <-><-><->Level 3.\n    >>> print(dedent(text, '<->'))\n    Level 1.\n    <->Level 2.\n    <-><->Level 3.\n\n    >>> text = '''<-><->Level 2.\n    ... <-><-><->Level 3.'''\n    >>> print(text)\n    <-><->Level 2.\n    <-><-><->Level 3.\n    >>> print(dedent(text, '<->'))\n    Level 2.\n    <->Level 3.\n    >>> print(dedent(text, '<->', max_levels=1))\n    <->Level 2.\n    <-><->Level 3."
  },
  {
    "code": "def get_request_token(self,\n                          method='GET',\n                          decoder=parse_utf8_qsl,\n                          key_token='oauth_token',\n                          key_token_secret='oauth_token_secret',\n                          **kwargs):\n        r = self.get_raw_request_token(method=method, **kwargs)\n        request_token, request_token_secret = \\\n            process_token_request(r, decoder, key_token, key_token_secret)\n        return request_token, request_token_secret",
    "docstring": "Return a request token pair.\n\n        :param method: A string representation of the HTTP method to be used,\n            defaults to `GET`.\n        :type method: str\n        :param decoder: A function used to parse the Response content. Should\n            return a dictionary.\n        :type decoder: func\n        :param key_token: The key the access token will be decoded by, defaults\n            to 'oauth_token'.\n        :type string:\n        :param key_token_secret: The key the access token will be decoded by,\n            defaults to 'oauth_token_secret'.\n        :type string:\n        :param \\*\\*kwargs: Optional arguments. Same as Requests.\n        :type \\*\\*kwargs: dict"
  },
  {
    "code": "def create(self, resource):\n        schema = self.CREATE_SCHEMA\n        json = self.service.encode(schema, resource)\n        schema = self.GET_SCHEMA\n        resp = self.service.create(self.base, json)\n        return self.service.decode(schema, resp)",
    "docstring": "Create a new config.\n\n        :param resource: :class:`configs.Config <configs.Config>` object\n        :return: :class:`configs.Config <configs.Config>` object\n        :rtype: configs.Config"
  },
  {
    "code": "def delete_grade(self, grade_id):\n        from dlkit.abstract_osid.id.primitives import Id as ABCId\n        from .objects import Grade\n        collection = JSONClientValidated('grading',\n                                         collection='GradeSystem',\n                                         runtime=self._runtime)\n        if not isinstance(grade_id, ABCId):\n            raise errors.InvalidArgument('the argument is not a valid OSID Id')\n        grade_system = collection.find_one({'grades._id': ObjectId(grade_id.get_identifier())})\n        index = 0\n        found = False\n        for i in grade_system['grades']:\n            if i['_id'] == ObjectId(grade_id.get_identifier()):\n                grade_map = grade_system['grades'].pop(index)\n            index += 1\n            found = True\n        if not found:\n            raise errors.OperationFailed()\n        Grade(\n            osid_object_map=grade_map,\n            runtime=self._runtime,\n            proxy=self._proxy)._delete()\n        collection.save(grade_system)",
    "docstring": "Deletes a ``Grade``.\n\n        arg:    grade_id (osid.id.Id): the ``Id`` of the ``Grade`` to\n                remove\n        raise:  NotFound - ``grade_id`` not found\n        raise:  NullArgument - ``grade_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def io_surface(timestep, time, fid, fld):\n    fid.write(\"{} {}\".format(timestep, time))\n    fid.writelines([\"%10.2e\" % item for item in fld[:]])\n    fid.writelines([\"\\n\"])",
    "docstring": "Output for surface files"
  },
  {
    "code": "async def explain(self, *args, analyze=False):\n        query = 'EXPLAIN (FORMAT JSON, VERBOSE'\n        if analyze:\n            query += ', ANALYZE) '\n        else:\n            query += ') '\n        query += self._state.query\n        if analyze:\n            tr = self._connection.transaction()\n            await tr.start()\n            try:\n                data = await self._connection.fetchval(query, *args)\n            finally:\n                await tr.rollback()\n        else:\n            data = await self._connection.fetchval(query, *args)\n        return json.loads(data)",
    "docstring": "Return the execution plan of the statement.\n\n        :param args: Query arguments.\n        :param analyze: If ``True``, the statement will be executed and\n                        the run time statitics added to the return value.\n\n        :return: An object representing the execution plan.  This value\n                 is actually a deserialized JSON output of the SQL\n                 ``EXPLAIN`` command."
  },
  {
    "code": "def put_readme(self, content):\n        logger.debug(\"Putting readme\")\n        key = self.get_readme_key()\n        self.put_text(key, content)",
    "docstring": "Store the readme descriptive metadata."
  },
  {
    "code": "def request_sid_cookie(self, username, password):\n        log.debug(\"Requesting SID cookie\")\n        target_url = self._login_url + '?usr={0}&pwd={1}&persist=y'.format(\n            username, password\n        )\n        cookie = urlopen(target_url).read()\n        return cookie",
    "docstring": "Request cookie for permanent session token."
  },
  {
    "code": "def _retrieve_value(self, entity, default=None):\n    return entity._values.get(self._name, default)",
    "docstring": "Internal helper to retrieve the value for this Property from an entity.\n\n    This returns None if no value is set, or the default argument if\n    given.  For a repeated Property this returns a list if a value is\n    set, otherwise None.  No additional transformations are applied."
  },
  {
    "code": "def transform_rest_response(self, response_body):\n    body_json = json.loads(response_body)\n    return json.dumps(body_json, indent=1, sort_keys=True)",
    "docstring": "Translates an apiserving REST response so it's ready to return.\n\n    Currently, the only thing that needs to be fixed here is indentation,\n    so it's consistent with what the live app will return.\n\n    Args:\n      response_body: A string containing the backend response.\n\n    Returns:\n      A reformatted version of the response JSON."
  },
  {
    "code": "def override(self, key, value):\n        keys = key.split('.')\n        if len(keys) > 1:\n            if keys[0] != \"plugins\":\n                raise AttributeError(\"no such setting: %r\" % key)\n            self.plugins.override(keys[1:], value)\n        else:\n            self.overrides[key] = value\n            self._uncache(key)",
    "docstring": "Set a setting to the given value.\n\n        Note that `key` can be in dotted form, eg\n        'plugins.release_hook.emailer.sender'."
  },
  {
    "code": "def _serialize_attributes(attributes):\n    result = ''\n    for name, value in attributes.items():\n        if not value:\n            continue\n        result += ' ' + _unmangle_attribute_name(name)\n        result += '=\"' + escape(value, True) + '\"'\n    return result",
    "docstring": "Serializes HTML element attributes in a name=\"value\" pair form."
  },
  {
    "code": "def get_series_as_of_date(self, series_id, as_of_date):\n        as_of_date = pd.to_datetime(as_of_date)\n        df = self.get_series_all_releases(series_id)\n        data = df[df['realtime_start'] <= as_of_date]\n        return data",
    "docstring": "Get latest data for a Fred series id as known on a particular date. This includes any revision to the data series\n        before or on as_of_date, but ignores any revision on dates after as_of_date.\n\n        Parameters\n        ----------\n        series_id : str\n            Fred series id such as 'GDP'\n        as_of_date : datetime, or datetime-like str such as '10/25/2014'\n            Include data revisions on or before this date, and ignore revisions afterwards\n\n        Returns\n        -------\n        data : Series\n            a Series where each index is the observation date and the value is the data for the Fred series"
  },
  {
    "code": "def set_prompt(self, prompt):\n        if prompt and self.settings.vehicle_name:\n            prompt = self.settings.vehicle_name + ':' + prompt\n        self.mpstate.rl.set_prompt(prompt)",
    "docstring": "set prompt for command line"
  },
  {
    "code": "def _spawn(self, distribution, executor=None, *args, **kwargs):\n    actual_executor = executor or SubprocessExecutor(distribution)\n    return distribution.execute_java_async(*args,\n                                           executor=actual_executor,\n                                           **kwargs)",
    "docstring": "Returns a processhandler to a process executing java.\n\n    :param Executor executor: the java subprocess executor to use. If not specified, construct\n      using the distribution.\n    :param Distribution distribution: The JDK or JRE installed.\n    :rtype: ProcessHandler"
  },
  {
    "code": "def get_authorization_ids_by_vault(self, vault_id):\n        id_list = []\n        for authorization in self.get_authorizations_by_vault(vault_id):\n            id_list.append(authorization.get_id())\n        return IdList(id_list)",
    "docstring": "Gets the list of ``Authorization``  ``Ids`` associated with a ``Vault``.\n\n        arg:    vault_id (osid.id.Id): ``Id`` of a ``Vault``\n        return: (osid.id.IdList) - list of related authorization ``Ids``\n        raise:  NotFound - ``vault_id`` is not found\n        raise:  NullArgument - ``vault_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _populate_route_attributes(self):\n        route_schema = self._validate_stone_cfg()\n        self.api.add_route_schema(route_schema)\n        for namespace in self.api.namespaces.values():\n            env = self._get_or_create_env(namespace.name)\n            for route in namespace.routes:\n                self._populate_route_attributes_helper(env, route, route_schema)",
    "docstring": "Converts all routes from forward references to complete definitions."
  },
  {
    "code": "def remove_server(self, name):\n        for i in self._server_list:\n            if i['key'] == name:\n                try:\n                    self._server_list.remove(i)\n                    logger.debug(\"Remove server %s from the list\" % name)\n                    logger.debug(\"Updated servers list (%s servers): %s\" % (\n                        len(self._server_list), self._server_list))\n                except ValueError:\n                    logger.error(\n                        \"Cannot remove server %s from the list\" % name)",
    "docstring": "Remove a server from the dict."
  },
  {
    "code": "def pad_decr(ids):\n  if len(ids) < 1:\n    return list(ids)\n  if not any(ids):\n    return []\n  idx = -1\n  while not ids[idx]:\n    idx -= 1\n  if idx == -1:\n    ids = ids\n  else:\n    ids = ids[:idx + 1]\n  return [i - 1 for i in ids]",
    "docstring": "Strip ID 0 and decrement ids by 1."
  },
  {
    "code": "def cublasZtrsm(handle, side, uplo, transa, diag, m, n, alpha, A, lda, B, ldb):\n    status = _libcublas.cublasZtrsm_v2(handle, \n                                       _CUBLAS_SIDE_MODE[side], \n                                       _CUBLAS_FILL_MODE[uplo], \n                                       _CUBLAS_OP[trans], \n                                       _CUBLAS_DIAG[diag], \n                                       m, n, ctypes.byref(cuda.cuDoubleComplex(alpha.real,                    \n                                                                               alpha.imag)),\n                                       int(A), lda, int(B), ldb)\n    cublasCheckStatus(status)",
    "docstring": "Solve complex triangular system with multiple right-hand sides."
  },
  {
    "code": "def transfer_state_data(cls, source_entity, target_entity):\n        state_data = cls.get_state_data(source_entity)\n        cls.set_state_data(target_entity, state_data)",
    "docstring": "Transfers instance state data from the given source entity to the\n        given target entity."
  },
  {
    "code": "async def helo(\n        self, hostname: str = None, timeout: DefaultNumType = _default\n    ) -> SMTPResponse:\n        if hostname is None:\n            hostname = self.source_address\n        async with self._command_lock:\n            response = await self.execute_command(\n                b\"HELO\", hostname.encode(\"ascii\"), timeout=timeout\n            )\n        self.last_helo_response = response\n        if response.code != SMTPStatus.completed:\n            raise SMTPHeloError(response.code, response.message)\n        return response",
    "docstring": "Send the SMTP HELO command.\n        Hostname to send for this command defaults to the FQDN of the local\n        host.\n\n        :raises SMTPHeloError: on unexpected server response code"
  },
  {
    "code": "def get_modified_time(self) -> Optional[datetime.datetime]:\n        stat_result = self._stat()\n        modified = datetime.datetime.utcfromtimestamp(int(stat_result.st_mtime))\n        return modified",
    "docstring": "Returns the time that ``self.absolute_path`` was last modified.\n\n        May be overridden in subclasses.  Should return a `~datetime.datetime`\n        object or None.\n\n        .. versionadded:: 3.1"
  },
  {
    "code": "def print_dependencies(_run):\n    print('Dependencies:')\n    for dep in _run.experiment_info['dependencies']:\n        pack, _, version = dep.partition('==')\n        print('  {:<20} == {}'.format(pack, version))\n    print('\\nSources:')\n    for source, digest in _run.experiment_info['sources']:\n        print('  {:<43}  {}'.format(source, digest))\n    if _run.experiment_info['repositories']:\n        repos = _run.experiment_info['repositories']\n        print('\\nVersion Control:')\n        for repo in repos:\n            mod = COLOR_DIRTY + 'M' if repo['dirty'] else ' '\n            print('{} {:<43}  {}'.format(mod, repo['url'], repo['commit']) +\n                  ENDC)\n    print('')",
    "docstring": "Print the detected source-files and dependencies."
  },
  {
    "code": "def file_or_stdin() -> Callable:\n    def parse(path):\n        if path is None or path == \"-\":\n            return sys.stdin\n        else:\n            return data_io.smart_open(path)\n    return parse",
    "docstring": "Returns a file descriptor from stdin or opening a file from a given path."
  },
  {
    "code": "async def eap_options(request: web.Request) -> web.Response:\n    return web.json_response(EAP_CONFIG_SHAPE, status=200)",
    "docstring": "Get request returns the available configuration options for WPA-EAP.\n\n    Because the options for connecting to WPA-EAP secured networks are quite\n    complex, to avoid duplicating logic this endpoint returns a json object\n    describing the structure of arguments and options for the eap_config arg to\n    /wifi/configure.\n\n    The object is shaped like this:\n    {\n        options: [ // Supported EAP methods and their options. One of these\n                   // method names must be passed in the eapConfig dict\n            {\n                name: str // i.e. TTLS-EAPMSCHAPv2. Should be in the eapType\n                          // key of eapConfig when sent to /configure.\n                options: [\n                    {\n                     name: str // i.e. \"username\"\n                     displayName: str // i.e. \"Username\"\n                     required: bool,\n                     type: str\n                   }\n                ]\n            }\n        ]\n    }\n\n\n    The ``type`` keys denote the semantic kind of the argument. Valid types\n    are:\n\n    password: This is some kind of password. It may be a psk for the network,\n              an Active Directory password, or the passphrase for a private key\n    string:   A generic string; perhaps a username, or a subject-matches\n              domain name for server validation\n    file:     A file that the user must provide. This should be the id of a\n              file previously uploaded via POST /wifi/keys.\n\n\n    Although the arguments are described hierarchically, they should be\n    specified in eap_config as a flat dict. For instance, a /configure\n    invocation for TTLS/EAP-TLS might look like\n\n    ```\n    POST\n    {\n        ssid: \"my-ssid\",\n        securityType: \"wpa-eap\",\n        hidden: false,\n        eapConfig : {\n            eapType: \"TTLS/EAP-TLS\",  // One of the method options\n            identity: \"alice@example.com\", // And then its arguments\n            anonymousIdentity: \"anonymous@example.com\",\n            password: \"testing123\",\n            caCert: \"12d1f180f081b\",\n            phase2CaCert: \"12d1f180f081b\",\n            phase2ClientCert: \"009909fd9fa\",\n            phase2PrivateKey: \"081009fbcbc\"\n            phase2PrivateKeyPassword: \"testing321\"\n        }\n    }\n    ```"
  },
  {
    "code": "def make_c_args(arg_pairs):\n    logging.debug(arg_pairs)\n    c_args = [\n        '{} {}'.format(arg_type, arg_name) if arg_name else arg_type\n        for dummy_number, arg_type, arg_name in sorted(arg_pairs)\n    ]\n    return ', '.join(c_args)",
    "docstring": "Build a C argument list from return type and arguments pairs."
  },
  {
    "code": "def getcal(self):\n        status, cal, cal_error, offset, offset_err, data_type = \\\n                         _C.SDgetcal(self._id)\n        _checkErr('getcal', status, 'no calibration record')\n        return cal, cal_error, offset, offset_err, data_type",
    "docstring": "Retrieve the SDS calibration coefficients.\n\n        Args::\n\n          no argument\n\n        Returns::\n\n          5-element tuple holding:\n\n          - cal: calibration factor (attribute 'scale_factor')\n          - cal_error : calibration factor error\n                        (attribute 'scale_factor_err')\n          - offset: calibration offset (attribute 'add_offset')\n          - offset_err : offset error (attribute 'add_offset_err')\n          - data_type : type of the data resulting from applying\n                        the calibration formula to the dataset values\n                        (attribute 'calibrated_nt')\n\n        An exception is raised if no calibration data are defined.\n\n        Original dataset values 'orival' are converted to calibrated\n        values 'calval' through the formula::\n\n           calval = cal * (orival - offset)\n\n        The calibration coefficients are part of the so-called\n        \"standard\" SDS attributes. The values inside the tuple returned\n        by 'getcal' are those of the following attributes, in order::\n\n          scale_factor, scale_factor_err, add_offset, add_offset_err,\n          calibrated_nt\n\n        C library equivalent: SDgetcal()"
  },
  {
    "code": "def build_rdn(self):\n        bits = []\n        for field in self._meta.fields:\n            if field.db_column and field.primary_key:\n                bits.append(\"%s=%s\" % (field.db_column,\n                                       getattr(self, field.name)))\n        if not len(bits):\n            raise Exception(\"Could not build Distinguished Name\")\n        return '+'.join(bits)",
    "docstring": "Build the Relative Distinguished Name for this entry."
  },
  {
    "code": "def send_message(self, message, sign=True):\n\t\tif sign:\n\t\t\tmessage.sign(self.authenticators[self.defauth])\n\t\tlogger.debug(\"sending %s\", LazyStr(message.dump_oneline))\n\t\tself.transport.write(message.as_string())",
    "docstring": "Send the given message to the connection.\n\n\t\t@type message: OmapiMessage\n\t\t@param sign: whether the message needs to be signed\n\t\t@raises OmapiError:\n\t\t@raises socket.error:"
  },
  {
    "code": "def count(self) -> int:\n        counter = 0\n        for pool in self._host_pools.values():\n            counter += pool.count()\n        return counter",
    "docstring": "Return number of connections."
  },
  {
    "code": "def set_size(self, data_size):\n        if len(str(data_size)) > self.first:\n            raise ValueError(\n              'Send size is too large for message size-field width!')\n        self.data_size = data_size",
    "docstring": "Set the data slice size."
  },
  {
    "code": "def deserialize(self, value, **kwargs):\n        for validator in self.validators:\n            validator.validate(value, **kwargs)\n        return value",
    "docstring": "Deserialization of value.\n\n        :return: Deserialized value.\n        :raises: :class:`halogen.exception.ValidationError` exception if value is not valid."
  },
  {
    "code": "def libvlc_media_player_has_vout(p_mi):\n    f = _Cfunctions.get('libvlc_media_player_has_vout', None) or \\\n        _Cfunction('libvlc_media_player_has_vout', ((1,),), None,\n                    ctypes.c_uint, MediaPlayer)\n    return f(p_mi)",
    "docstring": "How many video outputs does this media player have?\n    @param p_mi: the media player.\n    @return: the number of video outputs."
  },
  {
    "code": "def _FormatDescription(self, event):\n    date_time_string = timelib.Timestamp.CopyToIsoFormat(\n        event.timestamp, timezone=self._output_mediator.timezone)\n    timestamp_description = event.timestamp_desc or 'UNKNOWN'\n    message, _ = self._output_mediator.GetFormattedMessages(event)\n    if message is None:\n      data_type = getattr(event, 'data_type', 'UNKNOWN')\n      raise errors.NoFormatterFound(\n          'Unable to find event formatter for: {0:s}.'.format(data_type))\n    description = '{0:s}; {1:s}; {2:s}'.format(\n        date_time_string, timestamp_description,\n        message.replace(self._DESCRIPTION_FIELD_DELIMITER, ' '))\n    return self._SanitizeField(description)",
    "docstring": "Formats the description.\n\n    Args:\n      event (EventObject): event.\n\n    Returns:\n      str: formatted description field."
  },
  {
    "code": "async def discover_nupnp(websession):\n    async with websession.get(URL_NUPNP) as res:\n        return [Bridge(item['internalipaddress'], websession=websession)\n                for item in (await res.json())]",
    "docstring": "Discover bridges via NUPNP."
  },
  {
    "code": "def get_file_hash(storage, path):\n    contents = storage.open(path).read()\n    file_hash = hashlib.md5(contents).hexdigest()\n    content_type = mimetypes.guess_type(path)[0] or 'application/octet-stream'\n    if settings.is_gzipped and content_type in settings.gzip_content_types:\n        cache_key = get_cache_key('gzip_hash_%s' % file_hash)\n        file_hash = cache.get(cache_key, False)\n        if file_hash is False:\n            buffer = BytesIO()\n            zf = gzip.GzipFile(\n                mode='wb', compresslevel=6, fileobj=buffer, mtime=0.0)\n            zf.write(force_bytes(contents))\n            zf.close()\n            file_hash = hashlib.md5(buffer.getvalue()).hexdigest()\n            cache.set(cache_key, file_hash)\n    return '\"%s\"' % file_hash",
    "docstring": "Create md5 hash from file contents."
  },
  {
    "code": "def define_code_breakpoint(self, dwProcessId, address,   condition = True,\n                                                                action = None):\n        process = self.system.get_process(dwProcessId)\n        bp = CodeBreakpoint(address, condition, action)\n        key = (dwProcessId, bp.get_address())\n        if key in self.__codeBP:\n            msg = \"Already exists (PID %d) : %r\"\n            raise KeyError(msg % (dwProcessId, self.__codeBP[key]))\n        self.__codeBP[key] = bp\n        return bp",
    "docstring": "Creates a disabled code breakpoint at the given address.\n\n        @see:\n            L{has_code_breakpoint},\n            L{get_code_breakpoint},\n            L{enable_code_breakpoint},\n            L{enable_one_shot_code_breakpoint},\n            L{disable_code_breakpoint},\n            L{erase_code_breakpoint}\n\n        @type  dwProcessId: int\n        @param dwProcessId: Process global ID.\n\n        @type  address: int\n        @param address: Memory address of the code instruction to break at.\n\n        @type  condition: function\n        @param condition: (Optional) Condition callback function.\n\n            The callback signature is::\n\n                def condition_callback(event):\n                    return True     # returns True or False\n\n            Where B{event} is an L{Event} object,\n            and the return value is a boolean\n            (C{True} to dispatch the event, C{False} otherwise).\n\n        @type  action: function\n        @param action: (Optional) Action callback function.\n            If specified, the event is handled by this callback instead of\n            being dispatched normally.\n\n            The callback signature is::\n\n                def action_callback(event):\n                    pass        # no return value\n\n            Where B{event} is an L{Event} object,\n            and the return value is a boolean\n            (C{True} to dispatch the event, C{False} otherwise).\n\n        @rtype:  L{CodeBreakpoint}\n        @return: The code breakpoint object."
  },
  {
    "code": "def main(cls, args=None):\n        if args is None:\n            args = sys.argv[1:]\n        try:\n            o = cls()\n            o.parseOptions(args)\n        except usage.UsageError as e:\n            print(o.getSynopsis())\n            print(o.getUsage())\n            print(str(e))\n            return 1\n        except CLIError as ce:\n            print(str(ce))\n            return ce.returnCode\n        return 0",
    "docstring": "Fill in command-line arguments from argv"
  },
  {
    "code": "def write_bit(self, b, pack=Struct('B').pack):\n        self._output_buffer.append(pack(True if b else False))\n        return self",
    "docstring": "Write a single bit. Convenience method for single bit args."
  },
  {
    "code": "def cumulative_sum(self):\n        from .. import extensions\n        agg_op = \"__builtin__cum_sum__\"\n        return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))",
    "docstring": "Return the cumulative sum of the elements in the SArray.\n\n        Returns an SArray where each element in the output corresponds to the\n        sum of all the elements preceding and including it. The SArray is\n        expected to be of numeric type (int, float), or a numeric vector type.\n\n        Returns\n        -------\n        out : sarray[int, float, array.array]\n\n        Notes\n        -----\n         - Missing values are ignored while performing the cumulative\n           aggregate operation.\n         - For SArray's of type array.array, all entries are expected to\n           be of the same size.\n\n        Examples\n        --------\n        >>> sa = SArray([1, 2, 3, 4, 5])\n        >>> sa.cumulative_sum()\n        dtype: int\n        rows: 3\n        [1, 3, 6, 10, 15]"
  },
  {
    "code": "def is_uniform(self):\n        pages = self.pages\n        page = pages[0]\n        if page.is_scanimage or page.is_nih:\n            return True\n        try:\n            useframes = pages.useframes\n            pages.useframes = False\n            h = page.hash\n            for i in (1, 7, -1):\n                if pages[i].aspage().hash != h:\n                    return False\n        except IndexError:\n            return False\n        finally:\n            pages.useframes = useframes\n        return True",
    "docstring": "Return if file contains a uniform series of pages."
  },
  {
    "code": "def crypto_pwhash_scryptsalsa208sha256_ll(passwd, salt, n, r, p, dklen=64,\n                                          maxmem=SCRYPT_MAX_MEM):\n    ensure(isinstance(n, integer_types),\n           raising=TypeError)\n    ensure(isinstance(r, integer_types),\n           raising=TypeError)\n    ensure(isinstance(p, integer_types),\n           raising=TypeError)\n    ensure(isinstance(passwd, bytes),\n           raising=TypeError)\n    ensure(isinstance(salt, bytes),\n           raising=TypeError)\n    _check_memory_occupation(n, r, p, maxmem)\n    buf = ffi.new(\"uint8_t[]\", dklen)\n    ret = lib.crypto_pwhash_scryptsalsa208sha256_ll(passwd, len(passwd),\n                                                    salt, len(salt),\n                                                    n, r, p,\n                                                    buf, dklen)\n    ensure(ret == 0, 'Unexpected failure in key derivation',\n           raising=exc.RuntimeError)\n    return ffi.buffer(ffi.cast(\"char *\", buf), dklen)[:]",
    "docstring": "Derive a cryptographic key using the ``passwd`` and ``salt``\n    given as input.\n\n    The work factor can be tuned by by picking different\n    values for the parameters\n\n    :param bytes passwd:\n    :param bytes salt:\n    :param bytes salt: *must* be *exactly* :py:const:`.SALTBYTES` long\n    :param int dklen:\n    :param int opslimit:\n    :param int n:\n    :param int r: block size,\n    :param int p: the parallelism factor\n    :param int maxmem: the maximum available memory available for scrypt's\n                       operations\n    :rtype: bytes"
  },
  {
    "code": "def _maybe_extract(compressed_filename, directory, extension=None):\n    logger.info('Extracting {}'.format(compressed_filename))\n    if extension is None:\n        basename = os.path.basename(compressed_filename)\n        extension = basename.split('.', 1)[1]\n    if 'zip' in extension:\n        with zipfile.ZipFile(compressed_filename, \"r\") as zip_:\n            zip_.extractall(directory)\n    elif 'tar' in extension or 'tgz' in extension:\n        with tarfile.open(compressed_filename, mode='r') as tar:\n            tar.extractall(path=directory)\n    logger.info('Extracted {}'.format(compressed_filename))",
    "docstring": "Extract a compressed file to ``directory``.\n\n    Args:\n        compressed_filename (str): Compressed file.\n        directory (str): Extract to directory.\n        extension (str, optional): Extension of the file; Otherwise, attempts to extract extension\n            from the filename."
  },
  {
    "code": "def fetch(self):\n        params = values.of({})\n        payload = self._version.fetch(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return InstalledAddOnExtensionInstance(\n            self._version,\n            payload,\n            installed_add_on_sid=self._solution['installed_add_on_sid'],\n            sid=self._solution['sid'],\n        )",
    "docstring": "Fetch a InstalledAddOnExtensionInstance\n\n        :returns: Fetched InstalledAddOnExtensionInstance\n        :rtype: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionInstance"
  },
  {
    "code": "def promote(self, name):\n        return PartitionName(**dict(list(name.dict.items()) + list(self.dict.items())))",
    "docstring": "Promote to a PartitionName by combining with a bundle Name."
  },
  {
    "code": "def blockgen(blocks, shape):\n    iterables = [blockgen1d(l, s) for (l, s) in zip(blocks, shape)]\n    return product(*iterables)",
    "docstring": "Generate a list of slice tuples to be used by combine.\n\n    The tuples represent regions in an N-dimensional image.\n\n    :param blocks: a tuple of block sizes\n    :param shape: the shape of the n-dimensional array\n    :return: an iterator to the list of tuples of slices\n\n    Example:\n\n        >>> blocks = (500, 512)\n        >>> shape = (1040, 1024)\n        >>> for i in blockgen(blocks, shape):\n        ...     print i\n        (slice(0, 260, None), slice(0, 512, None))\n        (slice(0, 260, None), slice(512, 1024, None))\n        (slice(260, 520, None), slice(0, 512, None))\n        (slice(260, 520, None), slice(512, 1024, None))\n        (slice(520, 780, None), slice(0, 512, None))\n        (slice(520, 780, None), slice(512, 1024, None))\n        (slice(780, 1040, None), slice(0, 512, None))\n        (slice(780, 1040, None), slice(512, 1024, None))"
  },
  {
    "code": "def insert_query_m(data, table, conn, columns=None, db_type='mysql'):\n    if len(data) > 10000:\n        _chunk_query(data, 10000, columns, conn, table, db_type)\n    else:\n        if db_type == 'sqlite':\n            type_sign = '?'\n        else:\n            type_sign = '%s'\n        type_com = type_sign + \", \"\n        type = type_com * (len(data[0]) - 1)\n        type = type + type_sign\n        if columns:\n            stmt = \"INSERT INTO \" + table + \"( \" + columns + \") VALUES (\" + type + \")\"\n        else:\n            stmt = \"INSERT INTO \" + table + \" VALUES (\" + type + \")\"\n        cursor = conn.cursor()\n        cursor.executemany(stmt, data)\n        conn.commit()",
    "docstring": "Insert python list of tuples into SQL table\n\n    Args:\n        data (list): List of tuples\n        table (str): Name of database table\n        conn (connection object): database connection object\n        columns (str): String of column names to use if not assigned then all columns are presumed to be used [Optional]\n        db_type (str): If \"sqlite\" or \"mysql\""
  },
  {
    "code": "async def exchange_declare(self):\n        await self.channel.exchange_declare(\n            self.exchange,\n            self.exchange_type,\n            durable=self.durable,\n            auto_delete=self.auto_delete,\n            no_wait=self.no_wait,\n        )",
    "docstring": "Override this method to change how a exchange is declared"
  },
  {
    "code": "def _closure_createlink(self):\n        linkparents = self._closure_model.objects.filter(\n            child__pk=self._closure_parent_pk\n        ).values(\"parent\", \"depth\")\n        linkchildren = self._closure_model.objects.filter(\n            parent__pk=self.pk\n        ).values(\"child\", \"depth\")\n        newlinks = [self._closure_model(\n            parent_id=p['parent'],\n            child_id=c['child'],\n            depth=p['depth']+c['depth']+1\n        ) for p in linkparents for c in linkchildren]\n        self._closure_model.objects.bulk_create(newlinks)",
    "docstring": "Create a link in the closure tree."
  },
  {
    "code": "def get_path_list(args, nni_config, trial_content, temp_nni_path):\n    path_list, host_list = parse_log_path(args, trial_content)\n    platform = nni_config.get_config('experimentConfig').get('trainingServicePlatform')\n    if platform == 'local':\n        print_normal('Log path: %s' % ' '.join(path_list))\n        return path_list\n    elif platform == 'remote':\n        path_list = copy_data_from_remote(args, nni_config, trial_content, path_list, host_list, temp_nni_path)\n        print_normal('Log path: %s' % ' '.join(path_list))\n        return path_list\n    else:\n        print_error('Not supported platform!')\n        exit(1)",
    "docstring": "get path list according to different platform"
  },
  {
    "code": "def or_where_pivot(self, column, operator=None, value=None):\n        return self.where_pivot(column, operator, value, \"or\")",
    "docstring": "Set an or where clause for a pivot table column.\n\n        :param column: The column of the where clause, can also be a QueryBuilder instance for sub where\n        :type column: str|Builder\n\n        :param operator: The operator of the where clause\n        :type operator: str\n\n        :param value: The value of the where clause\n        :type value: mixed\n\n        :return: self\n        :rtype: BelongsToMany"
  },
  {
    "code": "def getbr(self, name):\n        for br in self.showall():\n            if br.name == name:\n                return br\n        raise BridgeException(\"Bridge does not exist.\")",
    "docstring": "Return a bridge object."
  },
  {
    "code": "def delete_series(self, database=None, measurement=None, tags=None):\n        database = database or self._database\n        query_str = 'DROP SERIES'\n        if measurement:\n            query_str += ' FROM {0}'.format(quote_ident(measurement))\n        if tags:\n            tag_eq_list = [\"{0}={1}\".format(quote_ident(k), quote_literal(v))\n                           for k, v in tags.items()]\n            query_str += ' WHERE ' + ' AND '.join(tag_eq_list)\n        self.query(query_str, database=database, method=\"POST\")",
    "docstring": "Delete series from a database.\n\n        Series must be filtered by either measurement and tags.\n        This method cannot be used to delete all series, use\n        `drop_database` instead.\n\n        :param database: the database from which the series should be\n            deleted, defaults to client's current database\n        :type database: str\n        :param measurement: Delete all series from a measurement\n        :type measurement: str\n        :param tags: Delete all series that match given tags\n        :type tags: dict"
  },
  {
    "code": "def get_exception_message(instance):\n    args = getattr(instance, 'args', None)\n    if args:\n        return str(instance)\n    try:\n        return type(instance).__name__\n    except AttributeError:\n        return str(instance)",
    "docstring": "Try to get the exception message or the class name."
  },
  {
    "code": "def create_section(\n        aggregation_summary, analysis_layer, postprocessor_fields,\n        section_header,\n        use_aggregation=True,\n        units_label=None,\n        use_rounding=True,\n        extra_component_args=None):\n    if use_aggregation:\n        return create_section_with_aggregation(\n            aggregation_summary, analysis_layer, postprocessor_fields,\n            section_header,\n            units_label=units_label,\n            use_rounding=use_rounding,\n            extra_component_args=extra_component_args)\n    else:\n        return create_section_without_aggregation(\n            aggregation_summary, analysis_layer, postprocessor_fields,\n            section_header,\n            units_label=units_label,\n            use_rounding=use_rounding,\n            extra_component_args=extra_component_args)",
    "docstring": "Create demographic section context.\n\n    :param aggregation_summary: Aggregation summary\n    :type aggregation_summary: qgis.core.QgsVectorlayer\n\n    :param analysis_layer: Analysis layer\n    :type analysis_layer: qgis.core.QgsVectorLayer\n\n    :param postprocessor_fields: Postprocessor fields to extract\n    :type postprocessor_fields: list[dict]\n\n    :param section_header: Section header text\n    :type section_header: qgis.core.QgsVectorLayer\n\n    :param use_aggregation: Flag, if using aggregation layer\n    :type use_aggregation: bool\n\n    :param units_label: Unit label for each column\n    :type units_label: list[str]\n\n    :param use_rounding: flag for rounding, affect number representations\n    :type use_rounding: bool\n\n    :param extra_component_args: extra_args passed from report component\n        metadata\n    :type extra_component_args: dict\n\n    :return: context for gender section\n    :rtype: dict\n\n    .. versionadded:: 4.0"
  },
  {
    "code": "def _check_image(self, image_nD):\n        self.input_image = load_image_from_disk(image_nD)\n        if len(self.input_image.shape) < 3:\n            raise ValueError('Input image must be atleast 3D')\n        if np.count_nonzero(self.input_image) == 0:\n            raise ValueError('Input image is completely filled with zeros! '\n                             'Must be non-empty')",
    "docstring": "Sanity checks on the image data"
  },
  {
    "code": "def setPoint(self, targetTemp):\n        self.targetTemp = targetTemp\n        self.Integrator = 0\n        self.Derivator = 0",
    "docstring": "Initilize the setpoint of PID."
  },
  {
    "code": "def make_retry_state(previous_attempt_number, delay_since_first_attempt,\n                     last_result=None):\n    required_parameter_unset = (previous_attempt_number is _unset or\n                                delay_since_first_attempt is _unset)\n    if required_parameter_unset:\n        raise _make_unset_exception(\n            'wait/stop',\n            previous_attempt_number=previous_attempt_number,\n            delay_since_first_attempt=delay_since_first_attempt)\n    from tenacity import RetryCallState\n    retry_state = RetryCallState(None, None, (), {})\n    retry_state.attempt_number = previous_attempt_number\n    if last_result is not None:\n        retry_state.outcome = last_result\n    else:\n        retry_state.set_result(None)\n    _set_delay_since_start(retry_state, delay_since_first_attempt)\n    return retry_state",
    "docstring": "Construct RetryCallState for given attempt number & delay.\n\n    Only used in testing and thus is extra careful about timestamp arithmetics."
  },
  {
    "code": "def metarate(self, func, name='values'):\n        setattr(func, name, self.values)\n        return func",
    "docstring": "Set the values object to the function object's namespace"
  },
  {
    "code": "def tree2array(tree,\n               branches=None,\n               selection=None,\n               object_selection=None,\n               start=None,\n               stop=None,\n               step=None,\n               include_weight=False,\n               weight_name='weight',\n               cache_size=-1):\n    import ROOT\n    if not isinstance(tree, ROOT.TTree):\n        raise TypeError(\"tree must be a ROOT.TTree\")\n    cobj = ROOT.AsCObject(tree)\n    if isinstance(branches, string_types):\n        flatten = branches\n        branches = [branches]\n    elif isinstance(branches, tuple):\n        if len(branches) not in (2, 3):\n            raise ValueError(\n                \"invalid branch tuple: {0}. \"\n                \"A branch tuple must contain two elements \"\n                \"(branch_name, fill_value) or three elements \"\n                \"(branch_name, fill_value, length) \"\n                \"to yield a single value or truncate, respectively\".format(branches))\n        flatten = branches[0]\n        branches = [branches]\n    else:\n        flatten = False\n    arr = _librootnumpy.root2array_fromtree(\n        cobj, branches, selection, object_selection,\n        start, stop, step,\n        include_weight,\n        weight_name,\n        cache_size)\n    if flatten:\n        return arr[flatten]\n    return arr",
    "docstring": "Convert a tree into a numpy structured array.\n\n    Convert branches of strings and basic types such as bool, int, float,\n    double, etc. as well as variable-length and fixed-length multidimensional\n    arrays and 1D or 2D vectors of basic types and strings. ``tree2array`` can\n    also create columns in the output array that are expressions involving the\n    TTree branches (i.e. ``'vect.Pt() / 1000'``) similar to ``TTree::Draw()``.\n    See the notes below for important details.\n\n    Parameters\n    ----------\n    tree : ROOT TTree instance\n        The ROOT TTree to convert into an array.\n    branches : list of strings and tuples or a string or tuple, optional (default=None)\n        List of branches and expressions to include as columns of the array or\n        a single branch or expression in which case a nonstructured array is\n        returned. If None then include all branches that can be converted.\n        Branches or expressions that result in variable-length subarrays can be\n        truncated at a fixed length by using the tuple ``(branch_or_expression,\n        fill_value, length)`` or converted into a single value with\n        ``(branch_or_expression, fill_value)`` where ``length==1`` is implied.\n        ``fill_value`` is used when the original array is shorter than\n        ``length``. This truncation is after any object selection performed\n        with the ``object_selection`` argument.\n    selection : str, optional (default=None)\n        Only include entries fulfilling this condition. If the condition\n        evaluates to multiple values per tree entry (e.g. conditions on array\n        branches) then an entry will be included if the condition evaluates to\n        true for at least one array element.\n    object_selection : dict, optional (default=None)\n        A dictionary mapping selection strings to branch names or lists of\n        branch names. Only array elements passing the selection strings will be\n        included in the output array per entry in the tree. The branches\n        specified must be variable-length array-type branches and the length of\n        the selection and branches it acts on must match for each tree entry.\n        For example ``object_selection={'a > 0': ['a', 'b']}`` will include all\n        elements of 'a' and corresponding elements of 'b' where 'a > 0' for\n        each tree entry. 'a' and 'b' must have the same length in every tree\n        entry.\n    start, stop, step: int, optional (default=None)\n        The meaning of the ``start``, ``stop`` and ``step`` parameters is the\n        same as for Python slices. If a range is supplied (by setting some of\n        the ``start``, ``stop`` or ``step`` parameters), only the entries in\n        that range and fulfilling the ``selection`` condition (if defined) are\n        used.\n    include_weight : bool, optional (default=False)\n        Include a column containing the tree weight ``TTree::GetWeight()``.\n        Note that this will be the same value for all entries unless the tree\n        is actually a TChain containing multiple trees with different weights.\n    weight_name : str, optional (default='weight')\n        The field name for the weight column if ``include_weight=True``.\n    cache_size : int, optional (default=-1)\n        Set the size (in bytes) of the TTreeCache used while reading a TTree. A\n        value of -1 uses ROOT's default cache size. A value of 0 disables the\n        cache.\n\n    Notes\n    -----\n    Types are converted according to the following table:\n\n    .. _conversion_table:\n\n    ========================  ===============================\n    ROOT                      NumPy\n    ========================  ===============================\n    ``Bool_t``                ``np.bool``\n    ``Char_t``                ``np.int8``\n    ``UChar_t``               ``np.uint8``\n    ``Short_t``               ``np.int16``\n    ``UShort_t``              ``np.uint16``\n    ``Int_t``                 ``np.int32``\n    ``UInt_t``                ``np.uint32``\n    ``Float_t``               ``np.float32``\n    ``Double_t``              ``np.float64``\n    ``Long64_t``              ``np.int64``\n    ``ULong64_t``             ``np.uint64``\n    ``<type>[2][3]...``       ``(<nptype>, (2, 3, ...))``\n    ``<type>[nx][2]...``      ``np.object``\n    ``string``                ``np.object``\n    ``vector<t>``             ``np.object``\n    ``vector<vector<t> >``    ``np.object``\n    ========================  ===============================\n\n    * Variable-length arrays (such as ``x[nx][2]``) and vectors (such as\n      ``vector<int>``) are converted to NumPy arrays of the corresponding\n      types.\n\n    * Fixed-length arrays are converted to fixed-length NumPy array fields.\n\n    **Branches with different lengths:**\n\n    Note that when converting trees that have branches of different lengths\n    into numpy arrays, the shorter branches will be extended to match the\n    length of the longest branch by repeating their last values. If all\n    requested branches are shorter than the longest branch in the tree, this\n    will result in a \"read failure\" since beyond the end of the longest\n    requested branch no additional bytes will be read from the file and\n    root_numpy is unable to distinguish this from other ROOT errors that result\n    in no bytes being read. In this case, explicitly set the ``stop`` argument\n    to the length of the longest requested branch.\n\n\n    See Also\n    --------\n    root2array\n    array2root\n    array2tree"
  },
  {
    "code": "def load_report(identifier=None):\n    path = os.path.join(\n        report_dir(),\n        identifier + '.pyireport'\n    )\n    return ProfilerSession.load(path)",
    "docstring": "Returns the session referred to by identifier"
  },
  {
    "code": "def getLibraryFiles(self, engineRoot, delimiter=' '):\n\t\treturn delimiter.join(self.resolveRoot(self.libs, engineRoot))",
    "docstring": "Returns the list of library files for this library, joined using the specified delimiter"
  },
  {
    "code": "def worker_stopped(name, workers=None, profile='default'):\n    if workers is None:\n        workers = []\n    return _bulk_state(\n        'modjk.bulk_stop', name, workers, profile\n    )",
    "docstring": "Stop all the workers in the modjk load balancer\n\n    Example:\n\n    .. code-block:: yaml\n\n        loadbalancer:\n          modjk.worker_stopped:\n            - workers:\n              - app1\n              - app2"
  },
  {
    "code": "def get_dbcollection_with_es(self, **kwargs):\n        es_objects = self.get_collection_es()\n        db_objects = self.Model.filter_objects(es_objects)\n        return db_objects",
    "docstring": "Get DB objects collection by first querying ES."
  },
  {
    "code": "def retrieve(url):\n    try:\n        pem_data = urlopen(url).read()\n    except (ValueError, HTTPError):\n        warnings.warn('Certificate URL is invalid.')\n        return False\n    if sys.version >= '3':\n        try:\n            pem_data = pem_data.decode()\n        except(UnicodeDecodeError):\n            warnings.warn('Certificate encoding is not utf-8.')\n            return False\n    return _parse_pem_data(pem_data)",
    "docstring": "Retrieve and parse PEM-encoded X.509 certificate chain.\n\n    See `validate.request` for additional info.\n\n    Args:\n        url: str. SignatureCertChainUrl header value sent by request.\n\n    Returns:\n        list or bool: If url is valid, returns the certificate chain as a list\n            of cryptography.hazmat.backends.openssl.x509._Certificate\n            certificates where certs[0] is the first certificate in the file; if\n            url is invalid, returns False."
  },
  {
    "code": "def get_player_summaries(players, **kwargs):\n    if (isinstance(players, list)):\n        params = {'steamids': ','.join(str(p) for p in players)}\n    elif (isinstance(players, int)):\n        params = {'steamids': players}\n    else:\n        raise ValueError(\"The players input needs to be a list or int\")\n    return make_request(\"GetPlayerSummaries\", params, version=\"v0002\",\n        base=\"http://api.steampowered.com/ISteamUser/\", **kwargs)",
    "docstring": "Get players steam profile from their steam ids"
  },
  {
    "code": "def compare_config(self):\n        diff = self.device.cu.diff()\n        if diff is None:\n            return ''\n        else:\n            return diff.strip()",
    "docstring": "Compare candidate config with running."
  },
  {
    "code": "def clean_videos(self):\n        if self.videos:\n            self.videos = [int(v) for v in self.videos if v is not None and is_valid_digit(v)]",
    "docstring": "Validates that all values in the video list are integer ids and removes all None values."
  },
  {
    "code": "def has_permission(self, request, view):\n        user_filter = self._get_user_filter(request)\n        if not user_filter:\n            return True\n        username_param = get_username_param(request)\n        allowed = user_filter == username_param\n        if not allowed:\n            log.warning(\n                u\"Permission JwtHasUserFilterForRequestedUser: user_filter %s doesn't match username %s.\",\n                user_filter,\n                username_param,\n            )\n        return allowed",
    "docstring": "If the JWT has a user filter, verify that the filtered\n        user value matches the user in the URL."
  },
  {
    "code": "def models_max_input_output_length(models: List[InferenceModel],\n                                   num_stds: int,\n                                   forced_max_input_len: Optional[int] = None,\n                                   forced_max_output_len: Optional[int] = None) -> Tuple[int, Callable]:\n    max_mean = max(model.length_ratio_mean for model in models)\n    max_std = max(model.length_ratio_std for model in models)\n    supported_max_seq_len_source = min((model.max_supported_seq_len_source for model in models\n                                        if model.max_supported_seq_len_source is not None),\n                                       default=None)\n    supported_max_seq_len_target = min((model.max_supported_seq_len_target for model in models\n                                        if model.max_supported_seq_len_target is not None),\n                                       default=None)\n    training_max_seq_len_source = min(model.training_max_seq_len_source for model in models)\n    return get_max_input_output_length(supported_max_seq_len_source,\n                                       supported_max_seq_len_target,\n                                       training_max_seq_len_source,\n                                       length_ratio_mean=max_mean,\n                                       length_ratio_std=max_std,\n                                       num_stds=num_stds,\n                                       forced_max_input_len=forced_max_input_len,\n                                       forced_max_output_len=forced_max_output_len)",
    "docstring": "Returns a function to compute maximum output length given a fixed number of standard deviations as a\n    safety margin, and the current input length.\n    Mean and std are taken from the model with the largest values to allow proper ensembling of models\n    trained on different data sets.\n\n    :param models: List of models.\n    :param num_stds: Number of standard deviations to add as a safety margin. If -1, returned maximum output lengths\n                     will always be 2 * input_length.\n    :param forced_max_input_len: An optional overwrite of the maximum input length.\n    :param forced_max_output_len: An optional overwrite of the maximum output length.\n    :return: The maximum input length and a function to get the output length given the input length."
  },
  {
    "code": "def load_manifest_file(client, bucket, schema, versioned, ifilters, key_info):\n    yield None\n    with tempfile.NamedTemporaryFile() as fh:\n        client.download_fileobj(Bucket=bucket, Key=key_info['key'], Fileobj=fh)\n        fh.seek(0)\n        reader = csv.reader(gzip.GzipFile(fileobj=fh, mode='r'))\n        for key_set in chunks(reader, 1000):\n            keys = []\n            for kr in key_set:\n                k = kr[1]\n                if inventory_filter(ifilters, schema, kr):\n                    continue\n                k = unquote_plus(k)\n                if versioned:\n                    if kr[3] == 'true':\n                        keys.append((k, kr[2], True))\n                    else:\n                        keys.append((k, kr[2]))\n                else:\n                    keys.append(k)\n            yield keys",
    "docstring": "Given an inventory csv file, return an iterator over keys"
  },
  {
    "code": "def load_private_key(pem_path, passphrase_bytes=None):\n    with open(pem_path, \"rb\") as f:\n        return cryptography.hazmat.primitives.serialization.load_pem_private_key(\n            data=f.read(),\n            password=passphrase_bytes,\n            backend=cryptography.hazmat.backends.default_backend(),\n        )",
    "docstring": "Load private key from PEM encoded file"
  },
  {
    "code": "def outputtemplate(self, template_id):\n        for profile in self.profiles:\n            for outputtemplate in profile.outputtemplates():\n                if outputtemplate.id == template_id:\n                    return outputtemplate\n        return KeyError(\"Outputtemplate \" + template_id + \" not found\")",
    "docstring": "Get an output template by ID"
  },
  {
    "code": "def point_stokes(self, context):\n        (ls, us), (lt, ut), (l, u) = context.array_extents(context.name)\n        data = np.empty(context.shape, context.dtype)\n        data[ls:us,:,l:u] = np.asarray(lm_stokes)[ls:us,None,:]\n        return data",
    "docstring": "Supply point source stokes parameters to montblanc"
  },
  {
    "code": "def is_binary(self):\n        with open(self.path, 'rb') as fin:\n            CHUNKSIZE = 1024\n            while 1:\n                chunk = fin.read(CHUNKSIZE)\n                if b'\\0' in chunk:\n                    return True\n                if len(chunk) < CHUNKSIZE:\n                    break\n        return False",
    "docstring": "Return true if this is a binary file."
  },
  {
    "code": "def steepest_descent(f, x, line_search=1.0, maxiter=1000, tol=1e-16,\n                     projection=None, callback=None):\n    r\n    grad = f.gradient\n    if x not in grad.domain:\n        raise TypeError('`x` {!r} is not in the domain of `grad` {!r}'\n                        ''.format(x, grad.domain))\n    if not callable(line_search):\n        line_search = ConstantLineSearch(line_search)\n    grad_x = grad.range.element()\n    for _ in range(maxiter):\n        grad(x, out=grad_x)\n        dir_derivative = -grad_x.norm() ** 2\n        if np.abs(dir_derivative) < tol:\n            return\n        step = line_search(x, -grad_x, dir_derivative)\n        x.lincomb(1, x, -step, grad_x)\n        if projection is not None:\n            projection(x)\n        if callback is not None:\n            callback(x)",
    "docstring": "r\"\"\"Steepest descent method to minimize an objective function.\n\n    General implementation of steepest decent (also known as gradient\n    decent) for solving\n\n    .. math::\n        \\min f(x)\n\n    The algorithm is intended for unconstrained problems. It needs line\n    search in order guarantee convergence. With appropriate line search,\n    it can also be used for constrained problems where one wants to\n    minimize over some given set :math:`C`. This can be done by defining\n    :math:`f(x) = \\infty` for :math:`x\\\\not\\\\in C`, or by providing a\n    ``projection`` function that projects the iterates on :math:`C`.\n\n    The algorithm is described in [BV2004], section 9.3--9.4\n    (`book available online\n    <http://stanford.edu/~boyd/cvxbook/bv_cvxbook.pdf>`_),\n    [GNS2009], Section 12.2, and wikipedia\n    `Gradient_descent\n    <https://en.wikipedia.org/wiki/Gradient_descent>`_.\n\n    Parameters\n    ----------\n    f : `Functional`\n        Goal functional. Needs to have ``f.gradient``.\n    x : ``f.domain`` element\n        Starting point of the iteration\n    line_search : float or `LineSearch`, optional\n        Strategy to choose the step length. If a float is given, uses it as a\n        fixed step length.\n    maxiter : int, optional\n        Maximum number of iterations.\n    tol : float, optional\n        Tolerance that should be used for terminating the iteration.\n    projection : callable, optional\n        Function that can be used to modify the iterates in each iteration,\n        for example enforcing positivity. The function should take one\n        argument and modify it in-place.\n    callback : callable, optional\n        Object executing code per iteration, e.g. plotting each iterate\n\n    See Also\n    --------\n    odl.solvers.iterative.iterative.landweber :\n        Optimized solver for the case ``f(x) = ||Ax - b||_2^2``\n    odl.solvers.iterative.iterative.conjugate_gradient :\n        Optimized solver for the case ``f(x) = x^T Ax - 2 x^T b``\n\n    References\n    ----------\n    [BV2004] Boyd, S, and Vandenberghe, L. *Convex optimization*.\n    Cambridge university press, 2004.\n\n    [GNS2009] Griva, I, Nash, S G, and Sofer, A. *Linear and nonlinear\n    optimization*. Siam, 2009."
  },
  {
    "code": "def modify(self, *, sort=None, purge=False, done=None):\n        return self._modifyInternal(sort=sort, purge=purge, done=done)",
    "docstring": "Calls Model._modifyInternal after loading the database."
  },
  {
    "code": "def ParseUserEngagedRow(\n      self, parser_mediator, query, row, **unused_kwargs):\n    query_hash = hash(query)\n    event_data = WindowsTimelineUserEngagedEventData()\n    event_data.package_identifier = self._GetRowValue(\n        query_hash, row, 'PackageName')\n    payload_json_bytes = bytes(self._GetRowValue(query_hash, row, 'Payload'))\n    payload_json_string = payload_json_bytes.decode('utf-8')\n    payload = json.loads(payload_json_string)\n    if 'reportingApp' in payload:\n      event_data.reporting_app = payload['reportingApp']\n    if 'activeDurationSeconds' in payload:\n      event_data.active_duration_seconds = int(payload['activeDurationSeconds'])\n    timestamp = self._GetRowValue(query_hash, row, 'StartTime')\n    date_time = dfdatetime_posix_time.PosixTime(timestamp=timestamp)\n    event = time_events.DateTimeValuesEvent(\n        date_time, definitions.TIME_DESCRIPTION_START)\n    parser_mediator.ProduceEventWithEventData(event, event_data)",
    "docstring": "Parses a timeline row that describes a user interacting with an app.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      query (str): query that created the row.\n      row (sqlite3.Row): row."
  },
  {
    "code": "def find_executable(executable_name):\n    if six.PY3:\n        executable_abs = shutil.which(executable_name)\n    else:\n        import distutils.spawn\n        executable_abs = distutils.spawn.find_executable(executable_name)\n    return executable_abs",
    "docstring": "Tries to find executable in PATH environment\n\n    It uses ``shutil.which`` method in Python3 and\n    ``distutils.spawn.find_executable`` method in Python2.7 to find the\n    absolute path to the 'name' executable.\n    :param executable_name: name of the executable\n    :returns: Returns the absolute path to the executable or None if not found."
  },
  {
    "code": "def creating_schema_and_index(self, models, func):\n        waiting_models = []\n        self.base_thread.do_with_submit(func, models, waiting_models, threads=self.threads)\n        if waiting_models:\n            print(\"WAITING MODELS ARE CHECKING...\")\n            self.creating_schema_and_index(waiting_models, func)",
    "docstring": "Executes given functions with given models.\n\n        Args:\n            models: models to execute\n            func: function name to execute\n\n        Returns:"
  },
  {
    "code": "def put_scancode(self, scancode):\n        if not isinstance(scancode, baseinteger):\n            raise TypeError(\"scancode can only be an instance of type baseinteger\")\n        self._call(\"putScancode\",\n                     in_p=[scancode])",
    "docstring": "Sends a scancode to the keyboard.\n\n        in scancode of type int\n\n        raises :class:`VBoxErrorIprtError`\n            Could not send scan code to virtual keyboard."
  },
  {
    "code": "def to_string(self, verbose=0, title=None, **kwargs):\n        from pprint import pformat\n        s = pformat(self, **kwargs)\n        if title is not None:\n            return \"\\n\".join([marquee(title, mark=\"=\"), s])\n        return s",
    "docstring": "String representation. kwargs are passed to `pprint.pformat`.\n\n        Args:\n            verbose: Verbosity level\n            title: Title string."
  },
  {
    "code": "def apply(\n        self, doc_loader, pdf_path=None, clear=True, parallelism=None, progress_bar=True\n    ):\n        super(Parser, self).apply(\n            doc_loader,\n            pdf_path=pdf_path,\n            clear=clear,\n            parallelism=parallelism,\n            progress_bar=progress_bar,\n        )",
    "docstring": "Run the Parser.\n\n        :param doc_loader: An iteratable of ``Documents`` to parse. Typically,\n            one of Fonduer's document preprocessors.\n        :param pdf_path: The path to the PDF documents, if any. This path will\n            override the one used in initialization, if provided.\n        :param clear: Whether or not to clear the labels table before applying\n            these LFs.\n        :type clear: bool\n        :param parallelism: How many threads to use for extraction. This will\n            override the parallelism value used to initialize the Labeler if\n            it is provided.\n        :type parallelism: int\n        :param progress_bar: Whether or not to display a progress bar. The\n            progress bar is measured per document.\n        :type progress_bar: bool"
  },
  {
    "code": "def check_rates(self, rates, base):\n        if \"rates\" not in rates:\n            raise RuntimeError(\"%s: 'rates' not found in results\" % self.name)\n        if \"base\" not in rates or rates[\"base\"] != base or base not in rates[\"rates\"]:\n            self.log(logging.WARNING, \"%s: 'base' not found in results\", self.name)\n        self.rates = rates",
    "docstring": "Local helper function for validating rates response"
  },
  {
    "code": "def clear_breakpoint(self, filename, lineno):\r\n        clear_breakpoint(filename, lineno)\r\n        self.breakpoints_saved.emit()\r\n        editorstack = self.get_current_editorstack()\r\n        if editorstack is not None:\r\n            index = self.is_file_opened(filename)\r\n            if index is not None:\r\n                editorstack.data[index].editor.debugger.toogle_breakpoint(\r\n                        lineno)",
    "docstring": "Remove a single breakpoint"
  },
  {
    "code": "def get_items_by_banks(self, bank_ids):\n        item_list = []\n        for bank_id in bank_ids:\n            item_list += list(\n                self.get_items_by_bank(bank_id))\n        return objects.ItemList(item_list)",
    "docstring": "Gets the list of ``Items`` corresponding to a list of ``Banks``.\n\n        arg:    bank_ids (osid.id.IdList): list of bank ``Ids``\n        return: (osid.assessment.ItemList) - list of items\n        raise:  NullArgument - ``bank_ids`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - assessment failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def pyxb_to_dict(rp_pyxb):\n    return {\n        'allowed': bool(_get_attr_or_list(rp_pyxb, 'allowed')),\n        'num': _get_as_int(rp_pyxb),\n        'block': _get_as_set(rp_pyxb, 'block'),\n        'pref': _get_as_set(rp_pyxb, 'pref'),\n    }",
    "docstring": "Convert ReplicationPolicy PyXB object to a normalized dict.\n\n    Args:\n      rp_pyxb: ReplicationPolicy to convert.\n\n    Returns:\n        dict : Replication Policy as normalized dict.\n\n    Example::\n\n      {\n        'allowed': True,\n        'num': 3,\n        'blockedMemberNode': {'urn:node:NODE1', 'urn:node:NODE2', 'urn:node:NODE3'},\n        'preferredMemberNode': {'urn:node:NODE4', 'urn:node:NODE5'},\n      }"
  },
  {
    "code": "def get_encoder_from_vocab(vocab_filepath):\n  if not tf.gfile.Exists(vocab_filepath):\n    raise ValueError(\"Vocab file does not exist: {}.\".format(vocab_filepath))\n  tf.logging.info(\"Found vocab file: %s\", vocab_filepath)\n  encoder = text_encoder.SubwordTextEncoder(vocab_filepath)\n  return encoder",
    "docstring": "Get encoder from vocab file.\n\n  If vocab is not found in output dir, it will be copied there by\n  copy_vocab_to_output_dir to clarify the vocab used to generate the data.\n\n  Args:\n    vocab_filepath: path to vocab, either local or cns\n\n  Returns:\n    A SubwordTextEncoder vocabulary object. None if the output_parallel_text\n    is set."
  },
  {
    "code": "def set_entry_points(self, names):\n        names = util.return_set(names)\n        self.entry_point_names = names",
    "docstring": "sets the internal collection of entry points to be\n        equal to `names`\n\n        `names` can be a single object or an iterable but\n        must be a string or iterable of strings."
  },
  {
    "code": "def freq_from_final_mass_spin(final_mass, final_spin, l=2, m=2, nmodes=1):\n    return get_lm_f0tau(final_mass, final_spin, l, m, nmodes)[0]",
    "docstring": "Returns QNM frequency for the given mass and spin and mode.\n\n    Parameters\n    ----------\n    final_mass : float or array\n        Mass of the black hole (in solar masses).\n    final_spin : float or array\n        Dimensionless spin of the final black hole.\n    l : int or array, optional\n        l-index of the harmonic. Default is 2.\n    m : int or array, optional\n        m-index of the harmonic. Default is 2.\n    nmodes : int, optional\n        The number of overtones to generate. Default is 1.\n\n    Returns\n    -------\n    float or array\n        The frequency of the QNM(s), in Hz. If only a single mode is requested\n        (and mass, spin, l, and m are not arrays), this will be a float. If\n        multiple modes requested, will be an array with shape\n        ``[input shape x] nmodes``, where ``input shape`` is the broadcasted\n        shape of the inputs."
  },
  {
    "code": "def _parse_default(self, target):\n        if not isinstance(target, (list, tuple)):\n            k, v, t = target, None, lambda x: x\n        elif len(target) == 1:\n            k, v, t = target[0], None, lambda x: x\n        elif len(target) == 2:\n            k, v, t = target[0], target[1], lambda x: x\n        elif len(target) > 2:\n            k, v, t = target[0], target[1], target[2]\n        else:\n            k = None\n        if not isinstance(k, string_types):\n            msg = \"{} is not a valid target, (name, default) expected.\".format(target)\n            raise ValueError(msg)\n        return k, v, t",
    "docstring": "Helper function to parse default values."
  },
  {
    "code": "def _BuildKeyHierarchy(self, subkeys, values):\n    if subkeys:\n      for registry_key in subkeys:\n        name = registry_key.name.upper()\n        if name in self._subkeys:\n          continue\n        self._subkeys[name] = registry_key\n        registry_key._key_path = key_paths.JoinKeyPath([\n            self._key_path, registry_key.name])\n    if values:\n      for registry_value in values:\n        name = registry_value.name.upper()\n        if name in self._values:\n          continue\n        self._values[name] = registry_value",
    "docstring": "Builds the Windows Registry key hierarchy.\n\n    Args:\n      subkeys (list[FakeWinRegistryKey]): list of subkeys.\n      values (list[FakeWinRegistryValue]): list of values."
  },
  {
    "code": "def truncate(self, path, length, fh=None):\n        \"Download existing path, truncate and reupload\"\n        try:\n            f = self._getpath(path)\n        except JFS.JFSError:\n            raise OSError(errno.ENOENT, '')\n        if isinstance(f, (JFS.JFSFile, JFS.JFSFolder)) and f.is_deleted():\n            raise OSError(errno.ENOENT)\n        data = StringIO(f.read())\n        data.truncate(length)\n        try:\n            self.client.up(path, data)\n            self._dirty(path)\n            return ESUCCESS\n        except:\n            raise OSError(errno.ENOENT, '')",
    "docstring": "Download existing path, truncate and reupload"
  },
  {
    "code": "def get_all_delivery_notes(self, params=None):\n        if not params:\n            params = {}\n        return self._iterate_through_pages(\n            self.get_delivery_notes_per_page,\n            resource=DELIVERY_NOTES,\n            **{'params': params}\n        )",
    "docstring": "Get all delivery notes\n        This will iterate over all pages until it gets all elements.\n        So if the rate limit exceeded it will throw an Exception and you will get nothing\n\n        :param params: search params\n        :return: list"
  },
  {
    "code": "def todo_results_changed(self):\r\n        editorstack = self.get_current_editorstack()\r\n        results = editorstack.get_todo_results()\r\n        index = editorstack.get_stack_index()\r\n        if index != -1:\r\n            filename = editorstack.data[index].filename\r\n            for other_editorstack in self.editorstacks:\r\n                if other_editorstack is not editorstack:\r\n                    other_editorstack.set_todo_results(filename, results)\r\n        self.update_todo_actions()",
    "docstring": "Synchronize todo results between editorstacks\r\n        Refresh todo list navigation buttons"
  },
  {
    "code": "def send_response(self, msgid, error=None, result=None):\n        msg = self._encoder.create_response(msgid, error, result)\n        self._send_message(msg)",
    "docstring": "Send a response"
  },
  {
    "code": "def get_next_file_path(self, service, operation):\n        base_name = '{0}.{1}'.format(service, operation)\n        if self.prefix:\n            base_name = '{0}.{1}'.format(self.prefix, base_name)\n        LOG.debug('get_next_file_path: %s', base_name)\n        next_file = None\n        serializer_format = None\n        index = self._index.setdefault(base_name, 1)\n        while not next_file:\n            file_name = os.path.join(\n                self._data_path, base_name + '_{0}'.format(index))\n            next_file, serializer_format = self.find_file_format(file_name)\n            if next_file:\n                self._index[base_name] += 1\n            elif index != 1:\n                index = 1\n                self._index[base_name] = 1\n            else:\n                raise IOError('response file ({0}.[{1}]) not found'.format(\n                    file_name, \"|\".join(Format.ALLOWED)))\n        return next_file, serializer_format",
    "docstring": "Returns a tuple with the next file to read and the serializer\n        format used"
  },
  {
    "code": "def build_absolute_uri(self, uri):\n        request = self.context.get('request', None)\n        return (\n            request.build_absolute_uri(uri) if request is not None else uri\n        )",
    "docstring": "Return a fully qualified absolute url for the given uri."
  },
  {
    "code": "def list_subnets(conn=None, call=None, kwargs=None):\n    if call == 'action':\n        raise SaltCloudSystemExit(\n            'The list_subnets function must be called with '\n            '-f or --function.'\n        )\n    if conn is None:\n        conn = get_conn()\n    if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):\n        raise SaltCloudSystemExit(\n            'A `network` must be specified'\n        )\n    return conn.list_subnets(filters={'network': kwargs['network']})",
    "docstring": "List subnets in a virtual network\n\n    network\n        network to list subnets of\n\n    .. code-block:: bash\n\n        salt-cloud -f list_subnets myopenstack network=salt-net"
  },
  {
    "code": "def validate_examples(example_file):\n    def test_example(raw):\n        example = tf.train.Example()\n        example.ParseFromString(raw)\n        pi = np.frombuffer(example.features.feature['pi'].bytes_list.value[0], np.float32)\n        value = example.features.feature['outcome'].float_list.value[0]\n        assert abs(pi.sum() - 1) < 1e-4, pi.sum()\n        assert value in (-1, 1), value\n    opts = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.ZLIB)\n    for record in tqdm(tf.python_io.tf_record_iterator(example_file, opts)):\n        test_example(record)",
    "docstring": "Validate that examples are well formed.\n\n    Pi should sum to 1.0\n    value should be {-1,1}\n\n    Usage:\n        validate_examples(\"../data/300.tfrecord.zz\")"
  },
  {
    "code": "def states(self, states):\n        if not isinstance(states, dict):\n            raise TypeError(\"states must be of type dict\")\n        if [state_id for state_id, state in states.items() if not isinstance(state, State)]:\n            raise TypeError(\"element of container_state.states must be of type State\")\n        if [state_id for state_id, state in states.items() if not state_id == state.state_id]:\n            raise AttributeError(\"The key of the state dictionary and the id of the state do not match\")\n        old_states = self._states\n        self._states = states\n        for state_id, state in states.items():\n            try:\n                state.parent = self\n            except ValueError:\n                self._states = old_states\n                raise\n        for old_state in old_states.values():\n            if old_state not in self._states.values() and old_state.parent is self:\n                old_state.parent = None",
    "docstring": "Setter for _states field\n\n        See property\n\n        :param states: Dictionary of States\n        :raises exceptions.TypeError: if the states parameter is of wrong type\n        :raises exceptions.AttributeError: if the keys of the dictionary and the state_ids in the dictionary do not match"
  },
  {
    "code": "def parse_error(output_dir):\n    sys.stderr.seek(0)\n    std_err = sys.stderr.read().decode('utf-8')\n    err_file = os.path.join(output_dir, \"eplusout.err\")\n    if os.path.isfile(err_file):\n        with open(err_file, \"r\") as f:\n            ep_err = f.read()\n    else:\n        ep_err = \"<File not found>\"\n    message = \"\\r\\n{std_err}\\r\\nContents of EnergyPlus error file at {err_file}\\r\\n{ep_err}\".format(**locals())\n    return message",
    "docstring": "Add contents of stderr and eplusout.err and put it in the exception message.\n\n    :param output_dir: str\n    :return: str"
  },
  {
    "code": "def from_string(cls, s):\n        for num, text in cls._STATUS2STR.items():\n            if text == s:\n                return cls(num)\n        else:\n            raise ValueError(\"Wrong string %s\" % s)",
    "docstring": "Return a `Status` instance from its string representation."
  },
  {
    "code": "def handle_event(self, message):\n        needs_update = 0\n        for zone in self.zones:\n            if zone in message:\n                _LOGGER.debug(\"Received message for zone: %s\", zone)\n                self.zones[zone].update_status(message[zone])\n        if 'netusb' in message:\n            needs_update += self.handle_netusb(message['netusb'])\n        if needs_update > 0:\n            _LOGGER.debug(\"needs_update: %d\", needs_update)\n            self.update_hass()",
    "docstring": "Dispatch all event messages"
  },
  {
    "code": "def safe_cd(path):\n    starting_directory = os.getcwd()\n    try:\n        os.chdir(path)\n        yield\n    finally:\n        os.chdir(starting_directory)",
    "docstring": "Changes to a directory, yields, and changes back.\n    Additionally any error will also change the directory back.\n\n    Usage:\n    >>> with safe_cd('some/repo'):\n    ...     call('git status')"
  },
  {
    "code": "def read_serialized_rsa_pub_key(serialized):\n        n = None\n        e = None\n        rsa = from_hex(serialized)\n        pos = 0\n        ln = len(rsa)\n        while pos < ln:\n            tag = bytes_to_byte(rsa, pos)\n            pos += 1\n            length = bytes_to_short(rsa, pos)\n            pos += 2\n            if tag == 0x81:\n                e = bytes_to_long(rsa[pos:pos+length])\n            elif tag == 0x82:\n                n = bytes_to_long(rsa[pos:pos+length])\n            pos += length\n        if e is None or n is None:\n            logger.warning(\"Could not process import key\")\n            raise ValueError('Public key deserialization failed')\n        return n, e",
    "docstring": "Reads serialized RSA pub key\n        TAG|len-2B|value. 81 = exponent, 82 = modulus\n\n        :param serialized:\n        :return: n, e"
  },
  {
    "code": "def AppendContent(self, src_fd):\n    while 1:\n      blob = src_fd.read(self.chunksize)\n      if not blob:\n        break\n      blob_id = data_store.BLOBS.WriteBlobWithUnknownHash(blob)\n      self.AddBlob(blob_id, len(blob))\n    self.Flush()",
    "docstring": "Create new blob hashes and append to BlobImage.\n\n    We don't support writing at arbitrary file offsets, but this method provides\n    a convenient way to add blobs for a new file, or append content to an\n    existing one.\n\n    Args:\n      src_fd: source file handle open for read\n\n    Raises:\n      IOError: if blob has already been finalized."
  },
  {
    "code": "def _autocomplete(client, url_part, input_text, session_token=None,\n                  offset=None, location=None, radius=None, language=None,\n                  types=None, components=None, strict_bounds=False):\n    params = {\"input\": input_text}\n    if session_token:\n        params[\"sessiontoken\"] = session_token\n    if offset:\n        params[\"offset\"] = offset\n    if location:\n        params[\"location\"] = convert.latlng(location)\n    if radius:\n        params[\"radius\"] = radius\n    if language:\n        params[\"language\"] = language\n    if types:\n        params[\"types\"] = types\n    if components:\n        if len(components) != 1 or list(components.keys())[0] != \"country\":\n            raise ValueError(\"Only country components are supported\")\n        params[\"components\"] = convert.components(components)\n    if strict_bounds:\n        params[\"strictbounds\"] = \"true\"\n    url = \"/maps/api/place/%sautocomplete/json\" % url_part\n    return client._request(url, params).get(\"predictions\", [])",
    "docstring": "Internal handler for ``autocomplete`` and ``autocomplete_query``.\n    See each method's docs for arg details."
  },
  {
    "code": "def copydb(self, sourcedb, destslab, destdbname=None, progresscb=None):\n        destdb = destslab.initdb(destdbname, sourcedb.dupsort)\n        statdict = destslab.stat(db=destdb)\n        if statdict['entries'] > 0:\n            raise s_exc.DataAlreadyExists()\n        rowcount = 0\n        for chunk in s_common.chunks(self.scanByFull(db=sourcedb), COPY_CHUNKSIZE):\n            ccount, acount = destslab.putmulti(chunk, dupdata=True, append=True, db=destdb)\n            if ccount != len(chunk) or acount != len(chunk):\n                raise s_exc.BadCoreStore(mesg='Unexpected number of values written')\n            rowcount += len(chunk)\n            if progresscb is not None and 0 == (rowcount % PROGRESS_PERIOD):\n                progresscb(rowcount)\n        return rowcount",
    "docstring": "Copy an entire database in this slab to a new database in potentially another slab.\n\n        Args:\n            sourcedb (LmdbDatabase): which database in this slab to copy rows from\n            destslab (LmdbSlab): which slab to copy rows to\n            destdbname (str): the name of the database to copy rows to in destslab\n            progresscb (Callable[int]):  if not None, this function will be periodically called with the number of rows\n                                         completed\n\n        Returns:\n            (int): the number of rows copied\n\n        Note:\n            If any rows already exist in the target database, this method returns an error.  This means that one cannot\n            use destdbname=None unless there are no explicit databases in the destination slab."
  },
  {
    "code": "def files(self):\n        tag_name = self.release['tag_name']\n        repo_name = self.repository['full_name']\n        zipball_url = self.release['zipball_url']\n        filename = u'{name}-{tag}.zip'.format(name=repo_name, tag=tag_name)\n        response = self.gh.api.session.head(zipball_url)\n        assert response.status_code == 302, \\\n            u'Could not retrieve archive from GitHub: {0}'.format(zipball_url)\n        yield filename, zipball_url",
    "docstring": "Extract files to download from GitHub payload."
  },
  {
    "code": "def _get_hangul_syllable_type(hangul_syllable):\n    if not _is_hangul_syllable(hangul_syllable):\n        raise ValueError(\"Value 0x%0.4x does not represent a Hangul syllable!\" % hangul_syllable)\n    if not _hangul_syllable_types:\n        _load_hangul_syllable_types()\n    return _hangul_syllable_types[hangul_syllable]",
    "docstring": "Function for taking a Unicode scalar value representing a Hangul syllable and determining the correct value for its\n    Hangul_Syllable_Type property.  For more information on the Hangul_Syllable_Type property see the Unicode Standard,\n    ch. 03, section 3.12, Conjoining Jamo Behavior.\n\n    https://www.unicode.org/versions/latest/ch03.pdf\n\n    :param hangul_syllable: Unicode scalar value representing a Hangul syllable\n    :return: Returns a string representing its Hangul_Syllable_Type property (\"L\", \"V\", \"T\", \"LV\" or \"LVT\")"
  },
  {
    "code": "def load_http_response(cls, http_response):\n        if not http_response.ok:\n            raise APIResponseError(http_response.text)\n        c = cls(http_response)\n        c.response = http_response\n        RateLimits.getRateLimits(cls.__name__).set(c.response.headers)\n        return c",
    "docstring": "This method should return an instantiated class and set its response\n        to the requests.Response object."
  },
  {
    "code": "def param_defs(self, method):\n        pts = self.bodypart_types(method)\n        if not method.soap.input.body.wrapped:\n            return pts\n        pt = pts[0][1].resolve()\n        return [(c.name, c, a) for c, a in pt if not c.isattr()]",
    "docstring": "Get parameter definitions for document literal."
  },
  {
    "code": "def metadata():\n    with open(os.path.join(charm_dir(), 'metadata.yaml')) as md:\n        return yaml.safe_load(md)",
    "docstring": "Get the current charm metadata.yaml contents as a python object"
  },
  {
    "code": "def usearch61_chimera_check_ref(abundance_fp,\n                                uchime_ref_fp,\n                                reference_seqs_fp,\n                                minlen=64,\n                                output_dir=\".\",\n                                remove_usearch_logs=False,\n                                uchime_ref_log_fp=\"uchime_ref.log\",\n                                usearch61_minh=0.28,\n                                usearch61_xn=8.0,\n                                usearch61_dn=1.4,\n                                usearch61_mindiffs=3,\n                                usearch61_mindiv=0.8,\n                                threads=1.0,\n                                HALT_EXEC=False):\n    params = {'--minseqlength': minlen,\n              '--uchime_ref': abundance_fp,\n              '--uchimeout': uchime_ref_fp,\n              '--db': reference_seqs_fp,\n              '--minh': usearch61_minh,\n              '--xn': usearch61_xn,\n              '--dn': usearch61_dn,\n              '--mindiffs': usearch61_mindiffs,\n              '--mindiv': usearch61_mindiv,\n              '--strand': 'plus',\n              '--threads': threads\n              }\n    if not remove_usearch_logs:\n        params['--log'] = uchime_ref_log_fp\n    app = Usearch61(params, WorkingDir=output_dir, HALT_EXEC=HALT_EXEC)\n    app_result = app()\n    return uchime_ref_fp, app_result",
    "docstring": "Does reference based chimera checking with usearch61\n\n    abundance_fp: input consensus fasta file with abundance information for\n     each cluster.\n    uchime_ref_fp: output uchime filepath for reference results\n    reference_seqs_fp: reference fasta database for chimera checking.\n    minlen: minimum sequence length for usearch input fasta seqs.\n    output_dir: output directory\n    removed_usearch_logs: suppresses creation of log file.\n    uchime_denovo_log_fp: output filepath for log file.\n    usearch61_minh: Minimum score (h) to be classified as chimera.\n     Increasing this value tends to the number of false positives (and also\n     sensitivity).\n    usearch61_xn:  Weight of \"no\" vote.  Increasing this value tends to the\n     number of false positives (and also sensitivity).\n    usearch61_dn:  Pseudo-count prior for \"no\" votes. (n). Increasing this\n     value tends to the number of false positives (and also sensitivity).\n    usearch61_mindiffs:  Minimum number of diffs in a segment. Increasing this\n     value tends to reduce the number of false positives while reducing\n     sensitivity to very low-divergence chimeras.\n    usearch61_mindiv:  Minimum divergence, i.e. 100% - identity between the\n     query and closest reference database sequence. Expressed as a percentage,\n     so the default is 0.8%, which allows chimeras that are up to 99.2% similar\n     to a reference sequence.\n    threads: Specify number of threads used per core per CPU\n    HALTEXEC: halt execution and returns command used for app controller."
  },
  {
    "code": "def set_trace(*args, **kwargs):\n    out = sys.stdout.stream if hasattr(sys.stdout, 'stream') else None\n    kwargs['stdout'] = out\n    debugger = pdb.Pdb(*args, **kwargs)\n    debugger.use_rawinput = True\n    debugger.set_trace(sys._getframe().f_back)",
    "docstring": "Call pdb.set_trace, making sure it receives the unwrapped stdout.\n\n    This is so we don't keep drawing progress bars over debugger output."
  },
  {
    "code": "def to_text(self, relative=False, indent_level=0, clean_empty_block=False):\n        if relative:\n            fwd = self.rel_path_fwd\n            bwd = self.rel_path_bwd\n        else:\n            fwd = self.full_path_fwd\n            bwd = self.full_path_bwd\n        indent = 4*indent_level*' '\n        pre = '%s%s' % (indent, fwd)\n        post = '%s%s' % (indent, bwd)\n        text = ''\n        for param, value in self.iterparams():\n            text += '  %sset %s %s\\n' % (indent, param, value)\n        for key, block in self.iterblocks():\n            text += block.to_text(True, indent_level+1)\n        if len(text) > 0 or not clean_empty_block:\n            text = '%s%s%s' % (pre, text, post)\n        return text",
    "docstring": "This method returns the object model in text format. You should be able to copy&paste this text into any\n        device running a supported version of FortiOS.\n\n        Args:\n            - **relative** (bool):\n                * If ``True``  the text returned will assume that you are one block away\n                * If ``False`` the text returned will contain instructions to reach the block from the root.\n            - **indent_level** (int): This value is for aesthetics only. It will help format the text in blocks to\\\n                increase readability.\n            - **clean_empty_block** (bool):\n                * If ``True`` a block without parameters or with sub_blocks without parameters will return an empty\\\n                    string\n                * If ``False`` a block without parameters will still return how to create it."
  },
  {
    "code": "def _findSingleMemberGroups(classDictionaries):\n    toRemove = {}\n    for classDictionaryGroup in classDictionaries:\n        for classDictionary in classDictionaryGroup:\n            for name, members in list(classDictionary.items()):\n                if len(members) == 1:\n                    toRemove[name] = list(members)[0]\n                    del classDictionary[name]\n    return toRemove",
    "docstring": "Find all classes that have only one member."
  },
  {
    "code": "def checksum_creation_action(target, source, env):\n    import crcmod\n    crc32_func = crcmod.mkCrcFun(0x104C11DB7, initCrc=0xFFFFFFFF, rev=False, xorOut=0)\n    with open(str(source[0]), 'rb') as f:\n        data = f.read()\n        data = data[:-4]\n        magicbin = data[-4:]\n        magic, = struct.unpack('<L', magicbin)\n        if magic != 0xBAADDAAD:\n            raise BuildError(\"Attempting to patch a file that is not a CDB binary or has the wrong size\", reason=\"invalid magic number found\", actual_magic=magic, desired_magic=0xBAADDAAD)\n        checksum = crc32_func(data) & 0xFFFFFFFF\n    with open(str(target[0]), 'w') as f:\n        checkhex = hex(checksum)\n        if checkhex[-1] == 'L':\n            checkhex = checkhex[:-1]\n        f.write(\"--defsym=__image_checksum=%s\\n\" % checkhex)",
    "docstring": "Create a linker command file for patching an application checksum into a firmware image"
  },
  {
    "code": "def full(self):\n        if not self.size: return False\n        return len(self.pq) == (self.size + self.removed_count)",
    "docstring": "Return True if the queue is full"
  },
  {
    "code": "def calc_padding(fmt, align):\n    remain = struct.calcsize(fmt) % align\n    if remain == 0:\n        return \"\"\n    return 'x' * (align - remain)",
    "docstring": "Calculate how many padding bytes needed for ``fmt`` to be aligned to\n    ``align``.\n\n    Args:\n        fmt (str): :mod:`struct` format.\n        align (int): alignment (2, 4, 8, etc.)\n\n    Returns:\n        str: padding format (e.g., various number of 'x').\n\n    >>> calc_padding('b', 2)\n    'x'\n\n    >>> calc_padding('b', 3)\n    'xx'"
  },
  {
    "code": "def _ensure_tuple(item):\n    if isinstance(item, tuple):\n        return item\n    elif isinstance(item, list):\n        return tuple(item)\n    elif isinstance(item, np.ndarray):\n        return tuple(item.tolist())\n    else:\n        raise NotImplementedError",
    "docstring": "Simply ensure that the passed item is a tuple.  If it is not, then\n    convert it if possible, or raise a NotImplementedError\n\n    Args:\n        item: the item that needs to become a tuple\n\n    Returns:\n        the item casted as a tuple\n\n    Raises:\n        NotImplementedError: if converting the given item to a tuple\n            is not implemented."
  },
  {
    "code": "def process_tags(self, tag=None):\n        if self.downloaded is False:\n            raise serror(\"Track not downloaded, can't process tags..\")\n        filetype = magic.from_file(self.filepath, mime=True)\n        if filetype != \"audio/mpeg\":\n            raise serror(\"Cannot process tags for file type %s.\" % filetype)\n        print(\"Processing tags for %s..\" % self.filepath)\n        if tag is None:\n            tag = stag()\n        tag.load_id3(self)\n        tag.write_id3(self.filepath)",
    "docstring": "Process ID3 Tags for mp3 files."
  },
  {
    "code": "def _repair_column(self):\n        check_for_title = True\n        for column_index in range(self.start[1], self.end[1]):\n            table_column = TableTranspose(self.table)[column_index]\n            column_start = table_column[self.start[0]]\n            if check_for_title and is_empty_cell(column_start):\n                self._stringify_column(column_index)\n            elif (isinstance(column_start, basestring) and\n                  re.search(allregex.year_regex, column_start)):\n                self._check_stringify_year_column(column_index)\n            else:\n                check_for_title = False",
    "docstring": "Same as _repair_row but for columns."
  },
  {
    "code": "def mark_backward(output_tensor, used_node_names):\n  op = output_tensor.op\n  if op.name in used_node_names:\n    return\n  used_node_names.add(op.name)\n  for input_tensor in op.inputs:\n    mark_backward(input_tensor, used_node_names)\n  for control_input_op in op.control_inputs:\n    used_node_names.add(control_input_op.name)\n    for input_tensor in control_input_op.inputs:\n      mark_backward(input_tensor, used_node_names)",
    "docstring": "Function to propagate backwards in the graph and mark nodes as used.\n\n  Traverses recursively through the graph from the end tensor, through the op\n  that generates the tensor, and then to the input tensors that feed the op.\n  Nodes encountered are stored in used_node_names.\n\n  Args:\n    output_tensor: A Tensor which we start the propagation.\n    used_node_names: A list of strings, stores the name of nodes we've marked as\n      visited."
  },
  {
    "code": "def _compute_distance_term(self, C, mag, rrup):\n        term1 = C['b'] * rrup\n        term2 = - np.log(rrup + C['c'] * np.exp(C['d'] * mag))\n        return term1 + term2",
    "docstring": "Compute second and third terms in equation 1, p. 901."
  },
  {
    "code": "def prepare_args(self, args, transform=True):\n        updated_args = list(args)\n        if transform:\n            updated_args[-1] = self.transform_value(updated_args[-1])\n        if self.key:\n            updated_args.insert(-1, self.key)\n        return updated_args",
    "docstring": "Prepare args to be used by a sub-index\n\n        Parameters\n        ----------\n        args: list\n            The while list of arguments passed to add, check_uniqueness, get_filtered_keys...\n        transform: bool\n            If ``True``, the last entry in `args`, ie the value, will be transformed.\n            Else it will be kept as is."
  },
  {
    "code": "def patched_packing_env(env):\n  old_env = pkg_resources.packaging.markers.default_environment\n  new_env = lambda: env\n  pkg_resources._vendor.packaging.markers.default_environment = new_env\n  try:\n    yield\n  finally:\n    pkg_resources._vendor.packaging.markers.default_environment = old_env",
    "docstring": "Monkey patch packaging.markers.default_environment"
  },
  {
    "code": "def convert_complex_output(out_in):\n    out = {}\n    for key, val in out_in.iteritems():\n        if val.data.dtype in  complex_types:\n            rval = copy(val)\n            rval.data = val.data.real\n            out['real(%s)' % key] = rval\n            ival = copy(val)\n            ival.data = val.data.imag\n            out['imag(%s)' % key] = ival\n        else:\n            out[key] = val\n    return out",
    "docstring": "Convert complex values in the output dictionary `out_in` to pairs of\n    real and imaginary parts."
  },
  {
    "code": "def _read_bks_key(cls, data, pos, store_type):\n        key_type = b1.unpack_from(data, pos)[0]; pos += 1\n        key_format, pos = BksKeyStore._read_utf(data, pos, kind=\"key format\")\n        key_algorithm, pos = BksKeyStore._read_utf(data, pos, kind=\"key algorithm\")\n        key_enc, pos = BksKeyStore._read_data(data, pos)\n        entry = BksKeyEntry(key_type, key_format, key_algorithm, key_enc, store_type=store_type)\n        return entry, pos",
    "docstring": "Given a data stream, attempt to parse a stored BKS key entry at the given position, and return it as a BksKeyEntry."
  },
  {
    "code": "def load_nicknames(self, file):\n        with open(os.path.join(main_dir, file + '.dat'), 'r') as f:\n            self.nicknames = json.load(f)",
    "docstring": "Load dict from file for random nicknames.\n\n        :param str file: filename"
  },
  {
    "code": "def cluster_seqs(seqs,\n                 neighbor_join=False,\n                 params={},\n                 add_seq_names=True,\n                 WorkingDir=tempfile.gettempdir(),\n                 SuppressStderr=None,\n                 SuppressStdout=None,\n                 max_chars=1000000,\n                 max_hours=1.0,\n                 constructor=PhyloNode,\n                 clean_up=True\n                 ):\n    num_seqs = len(seqs)\n    if num_seqs < 2:\n        raise ValueError, \"Muscle requres 2 or more sequences to cluster.\"\n    num_chars = sum(map(len, seqs))\n    if num_chars > max_chars:\n        params[\"-maxiters\"] = 2\n        params[\"-diags1\"] = True\n        params[\"-sv\"] = True\n        print \"lots of chars, using fast align\", num_chars\n    params[\"-maxhours\"] = max_hours\n    params[\"-clusteronly\"] = True\n    params[\"-tree1\"] = get_tmp_filename(WorkingDir)\n    muscle_res = muscle_seqs(seqs,\n                 params=params,\n                 add_seq_names=add_seq_names,\n                 WorkingDir=WorkingDir,\n                 SuppressStderr=SuppressStderr,\n                 SuppressStdout=SuppressStdout)\n    tree = DndParser(muscle_res[\"Tree1Out\"], constructor=constructor)\n    if clean_up:\n        muscle_res.cleanUp()\n    return tree",
    "docstring": "Muscle cluster list of sequences.\n\n    seqs: either file name or list of sequence objects or list of strings or\n        single multiline string containing sequences.\n\n    Addl docs coming soon"
  },
  {
    "code": "def chi_p_from_xi1_xi2(xi1, xi2):\n    xi1, xi2, input_is_array = ensurearray(xi1, xi2)\n    chi_p = copy.copy(xi1)\n    mask = xi1 < xi2\n    chi_p[mask] = xi2[mask]\n    return formatreturn(chi_p, input_is_array)",
    "docstring": "Returns effective precession spin from xi1 and xi2."
  },
  {
    "code": "def remove_from_postmortem_exclusion_list(cls, pathname, bits = None):\n        if bits is None:\n            bits = cls.bits\n        elif bits not in (32, 64):\n            raise NotImplementedError(\"Unknown architecture (%r bits)\" % bits)\n        if bits == 32 and cls.bits == 64:\n            keyname = 'HKLM\\\\SOFTWARE\\\\Wow6432Node\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\AeDebug\\\\AutoExclusionList'\n        else:\n            keyname = 'HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\AeDebug\\\\AutoExclusionList'\n        try:\n            key = cls.registry[keyname]\n        except KeyError:\n            return\n        try:\n            del key[pathname]\n        except KeyError:\n            return",
    "docstring": "Removes the given filename to the exclusion list for postmortem\n        debugging from the Registry.\n\n        @warning: This method requires administrative rights.\n\n        @warning: Don't ever delete entries you haven't created yourself!\n            Some entries are set by default for your version of Windows.\n            Deleting them might deadlock your system under some circumstances.\n\n            For more details see:\n            U{http://msdn.microsoft.com/en-us/library/bb204634(v=vs.85).aspx}\n\n        @see: L{get_postmortem_exclusion_list}\n\n        @type  pathname: str\n        @param pathname: Application pathname to remove from the postmortem\n            debugging exclusion list.\n\n        @type  bits: int\n        @param bits: Set to C{32} for the 32 bits debugger, or C{64} for the\n            64 bits debugger. Set to {None} for the default (L{System.bits}).\n\n        @raise WindowsError:\n            Raises an exception on error."
  },
  {
    "code": "def get_field_values(self, fldnames, rpt_fmt=True, itemid2name=None):\n        row = []\n        for fld in fldnames:\n            val = getattr(self, fld, None)\n            if val is not None:\n                if rpt_fmt:\n                    val = self._get_rpt_fmt(fld, val, itemid2name)\n                row.append(val)\n            else:\n                val = getattr(self.goterm, fld, None)\n                if rpt_fmt:\n                    val = self._get_rpt_fmt(fld, val, itemid2name)\n                if val is not None:\n                    row.append(val)\n                else:\n                    self._err_fld(fld, fldnames)\n            if rpt_fmt:\n                assert not isinstance(val, list), \\\n                   \"UNEXPECTED LIST: FIELD({F}) VALUE({V}) FMT({P})\".format(\n                       P=rpt_fmt, F=fld, V=val)\n        return row",
    "docstring": "Get flat namedtuple fields for one GOEnrichmentRecord."
  },
  {
    "code": "def put_replication(Bucket, Role, Rules,\n           region=None, key=None, keyid=None, profile=None):\n    try:\n        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n        Role = _get_role_arn(name=Role,\n                             region=region, key=key, keyid=keyid, profile=profile)\n        if Rules is None:\n            Rules = []\n        elif isinstance(Rules, six.string_types):\n            Rules = salt.utils.json.loads(Rules)\n        conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={\n                'Role': Role,\n                'Rules': Rules\n        })\n        return {'updated': True, 'name': Bucket}\n    except ClientError as e:\n        return {'updated': False, 'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Given a valid config, update the replication configuration for a bucket.\n\n    Returns {updated: true} if replication configuration was updated and returns\n    {updated: False} if replication configuration was not updated.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]"
  },
  {
    "code": "def update_data(self):\n        url = ('https://www.openhumans.org/api/direct-sharing/project/'\n               'members/?access_token={}'.format(self.master_access_token))\n        results = get_all_results(url)\n        self.project_data = dict()\n        for result in results:\n            self.project_data[result['project_member_id']] = result\n            if len(result['data']) < result['file_count']:\n                member_data = get_page(result['exchange_member'])\n                final_data = member_data['data']\n                while member_data['next']:\n                    member_data = get_page(member_data['next'])\n                    final_data = final_data + member_data['data']\n                self.project_data[\n                    result['project_member_id']]['data'] = final_data\n        return self.project_data",
    "docstring": "Returns data for all users including shared data files."
  },
  {
    "code": "def _exec_command(self, command: str):\n        stdin, stdout, stderr = self._ssh.exec_command(command)\n        stdout.read()\n        stderr.read()\n        stdin.close()",
    "docstring": "Executes the command and closes the handles\n        afterwards."
  },
  {
    "code": "def add_configuration_file(self, file_name):\n        logger.info('adding %s to configuration files', file_name)\n        if file_name not in self.configuration_files and self._inotify:\n            self._watch_manager.add_watch(file_name, pyinotify.IN_MODIFY)\n        if os.access(file_name, os.R_OK):\n            self.configuration_files[file_name] = SafeConfigParser()\n            self.configuration_files[file_name].read(file_name)\n        else:\n            logger.warn('could not read %s', file_name)\n            warnings.warn('could not read {}'.format(file_name), ResourceWarning)",
    "docstring": "Register a file path from which to read parameter values.\n\n        This method can be called multiple times to register multiple files for\n        querying.  Files are expected to be ``ini`` formatted.\n\n        No assumptions should be made about the order that the registered files\n        are read and values defined in multiple files may have unpredictable\n        results.\n\n        **Arguments**\n\n        :``file_name``: Name of the file to add to the parameter search."
  },
  {
    "code": "def decrypt_stream(mode, in_stream, out_stream, block_size = BLOCK_SIZE, padding = PADDING_DEFAULT):\n    'Decrypts a stream of bytes from in_stream to out_stream using mode.'\n    decrypter = Decrypter(mode, padding = padding)\n    _feed_stream(decrypter, in_stream, out_stream, block_size)",
    "docstring": "Decrypts a stream of bytes from in_stream to out_stream using mode."
  },
  {
    "code": "def _parse_line_entry(self, line, type):\n        name = None\n        key_values = {}\n        if type == 'vars':\n            key_values = self._parse_line_vars(line)\n        else:\n            tokens = shlex.split(line.strip())\n            name = tokens.pop(0)\n            try:\n                key_values = self._parse_vars(tokens)\n            except ValueError:\n                self.log.warning(\"Unsupported vars syntax. Skipping line: {0}\".format(line))\n                return (name, {})\n        return (name, key_values)",
    "docstring": "Parse a section entry line into its components. In case of a 'vars'\n        section, the first field will be None. Otherwise, the first field will\n        be the unexpanded host or group name the variables apply to.\n\n        For example:\n            [production:children]\n            frontend  purpose=\"web\"    # The line we process\n        Returns:\n            ('frontend', {'purpose': 'web'})\n\n        For example:\n            [production:vars]\n            purpose=\"web\"              # The line we process\n        Returns:\n            (None, {'purpose': 'web'})\n\n        Undocumented feature:\n            [prod:vars]\n            json_like_vars=[{'name': 'htpasswd_auth'}]\n        Returns:\n            (None, {'name': 'htpasswd_auth'})"
  },
  {
    "code": "def create_package_level_rst_index_file(\n        package_name, max_depth, modules, inner_packages=None):\n    if inner_packages is None:\n        inner_packages = []\n    return_text = 'Package::' + package_name\n    dash = '=' * len(return_text)\n    return_text += '\\n' + dash + '\\n\\n'\n    return_text += '.. toctree::' + '\\n'\n    return_text += '   :maxdepth: ' + str(max_depth) + '\\n\\n'\n    upper_package = package_name.split('.')[-1]\n    for module in modules:\n        if module in EXCLUDED_PACKAGES:\n            continue\n        return_text += '   ' + upper_package + os.sep + module[:-3] + '\\n'\n    for inner_package in inner_packages:\n        if inner_package in EXCLUDED_PACKAGES:\n            continue\n        return_text += '   ' + upper_package + os.sep + inner_package + '\\n'\n    return return_text",
    "docstring": "Function for creating text for index for a package.\n\n    :param package_name: name of the package\n    :type package_name: str\n\n    :param max_depth: Value for max_depth in the index file.\n    :type max_depth: int\n\n    :param modules: list of module in the package.\n    :type modules: list\n\n    :return: A text for the content of the index file.\n    :rtype: str"
  },
  {
    "code": "def _wva(values, weights):\n        assert len(values) == len(weights) and len(weights) > 0\n        return sum([mul(*x) for x in zip(values, weights)]) / sum(weights)",
    "docstring": "Calculates a weighted average"
  },
  {
    "code": "def _get_more(collection_name, num_to_return, cursor_id):\n    return b\"\".join([\n        _ZERO_32,\n        _make_c_string(collection_name),\n        _pack_int(num_to_return),\n        _pack_long_long(cursor_id)])",
    "docstring": "Get an OP_GET_MORE message."
  },
  {
    "code": "def redo(self):\n        if self._undoing or self._redoing:\n            raise RuntimeError\n        if not self._redo:\n            return\n        group = self._redo.pop()\n        self._redoing = True\n        self.begin_grouping()\n        group.perform()\n        self.set_action_name(group.name)\n        self.end_grouping()\n        self._redoing = False\n        self.notify()",
    "docstring": "Performs the top group on the redo stack, if present. Creates an undo\n        group with the same name. Raises RuntimeError if called while undoing."
  },
  {
    "code": "def findBinomialNsWithExpectedSampleMinimum(desiredValuesSorted, p, numSamples, nMax):\n  actualValues = [\n    getExpectedValue(\n      SampleMinimumDistribution(numSamples,\n                                BinomialDistribution(n, p, cache=True)))\n    for n in xrange(nMax + 1)]\n  results = []\n  n = 0\n  for desiredValue in desiredValuesSorted:\n    while n + 1 <= nMax and actualValues[n + 1] < desiredValue:\n      n += 1\n    if n + 1 > nMax:\n      break\n    interpolated = n + ((desiredValue - actualValues[n]) /\n                        (actualValues[n+1] - actualValues[n]))\n    result = (interpolated, actualValues[n], actualValues[n + 1])\n    results.append(result)\n  return results",
    "docstring": "For each desired value, find an approximate n for which the sample minimum\n  has a expected value equal to this value.\n\n  For each value, find an adjacent pair of n values whose expected sample minima\n  are below and above the desired value, respectively, and return a\n  linearly-interpolated n between these two values.\n\n  @param p (float)\n  The p if the binomial distribution.\n\n  @param numSamples (int)\n  The number of samples in the sample minimum distribution.\n\n  @return\n  A list of results. Each result contains\n    (interpolated_n, lower_value, upper_value).\n  where each lower_value and upper_value are the expected sample minimum for\n  floor(interpolated_n) and ceil(interpolated_n)"
  },
  {
    "code": "def _get_bank_redis_key(bank):\n    opts = _get_redis_keys_opts()\n    return '{prefix}{separator}{bank}'.format(\n        prefix=opts['bank_prefix'],\n        separator=opts['separator'],\n        bank=bank\n    )",
    "docstring": "Return the Redis key for the bank given the name."
  },
  {
    "code": "def fetch_friend_ids(self, user):\n        friends = self.fetch_friends(user)\n        friend_ids = []\n        for friend in friends:\n            friend_ids.append(friend.id)\n        return friend_ids",
    "docstring": "fethces friend id's from twitter\n\n        Return:\n            collection of friend ids"
  },
  {
    "code": "def get_package_info(self, name):\n        if self._disable_cache:\n            return self._get_package_info(name)\n        return self._cache.store(\"packages\").remember_forever(\n            name, lambda: self._get_package_info(name)\n        )",
    "docstring": "Return the package information given its name.\n\n        The information is returned from the cache if it exists\n        or retrieved from the remote server."
  },
  {
    "code": "def verify_and_extract_time(self, log_file, division, result_name):\n    expected_level = constants.DIVISION_COMPLIANCE_CHECK_LEVEL.get(\n        division, None)\n    print(result_name)\n    if expected_level is None:\n      raise Exception('Unknown division: {}'.format(division))\n    start_time, level, dt, _, success = self.get_compliance(log_file)\n    print(float(start_time))\n    if int(level) != expected_level:\n      raise Exception('Error Level {} does not match needed level {}:{}'.format(\n          level, expected_level, log_file))\n    if success and dt:\n      return dt, start_time\n    else:\n      print('Result was not a success set to INFINITE_TIME({})'.format(\n          INFINITE_TIME))\n      return INFINITE_TIME, start_time",
    "docstring": "Verifies and result and returns timing.\n\n    Uses submodule mlp_compliance (https://github.com/bitfort/mlp_compliance)\n\n    Args:\n      log_file: Absolute path to result file.\n      division: open, closed\n      result_name: name of the benchmark, ncf, ssd, etc\n\n    Returns:\n      Time for the result or `INFINITE_TIME` if not a success\n\n    Raises:\n      Exception: If expected compliance level is not hit or cannot figure\n      out expected compliance level."
  },
  {
    "code": "def ledger_effects(self, ledger_id, cursor=None, order='asc', limit=10):\n        endpoint = '/ledgers/{ledger_id}/effects'.format(ledger_id=ledger_id)\n        params = self.__query_params(cursor=cursor, order=order, limit=limit)\n        return self.query(endpoint, params)",
    "docstring": "This endpoint represents all effects that occurred in the given\n        ledger.\n\n        `GET /ledgers/{id}/effects{?cursor,limit,order}\n        <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-ledger.html>`_\n\n        :param int ledger_id: The id of the ledger to look up.\n        :param int cursor: A paging token, specifying where to start returning records from.\n        :param str order: The order in which to return rows, \"asc\" or \"desc\".\n        :param int limit: Maximum number of records to return.\n        :return: The effects for a single ledger.\n        :rtype: dict"
  },
  {
    "code": "def __render(self, context, **kwargs):\n        kwargs[\"namespaces\"] = [context, ] + kwargs.get(\"namespaces\", []) \\\n                                           + kwargs.get(\"searchList\", [])\n        kwargs[\"searchList\"] = None\n        kwargs = self.filter_options(kwargs, self.engine_valid_options())\n        self.engine_options.update(kwargs)\n        return render_impl(**self.engine_options)",
    "docstring": "Render template.\n\n        :param context: A dict or dict-like object to instantiate given\n            template file\n        :param kwargs: Keyword arguments passed to the template engine to\n            render templates with specific features enabled.\n\n        :return: Rendered string"
  },
  {
    "code": "def update(self, ipv6s):\n        data = {'ips': ipv6s}\n        ipv6s_ids = [str(ipv6.get('id')) for ipv6 in ipv6s]\n        return super(ApiIPv6, self).put('api/v3/ipv6/%s/' %\n                                        ';'.join(ipv6s_ids), data)",
    "docstring": "Method to update ipv6's\n\n        :param ipv6s: List containing ipv6's desired to updated\n        :return: None"
  },
  {
    "code": "def get_help_usage(command):\n    if not command:\n        doc = get_primary_command_usage()\n    elif command in ('-a', '--all'):\n        subcommands = [k for k in settings.subcommands if k is not None]\n        available_commands = subcommands + ['help']\n        command_doc = '\\nAvailable commands:\\n{}\\n'.format(\n            '\\n'.join('  {}'.format(c) for c in sorted(available_commands)))\n        doc = get_primary_command_usage(command_doc)\n    elif command.startswith('-'):\n        raise ValueError(\"Unrecognized option '{}'.\".format(command))\n    elif command in settings.subcommands:\n        subcommand = settings.subcommands[command]\n        doc = format_usage(subcommand.__doc__)\n    docopt.docopt(doc, argv=('--help',))",
    "docstring": "Print out a help message and exit the program.\n\n    Args:\n        command: If a command value is supplied then print the help message for\n            the command module if available. If the command is '-a' or '--all',\n            then print the standard help message but with a full list of\n            available commands.\n\n    Raises:\n        ValueError: Raised if the help message is requested for an invalid\n            command or an unrecognized option is passed to help."
  },
  {
    "code": "def avroize_type(field_type, name_prefix=\"\"):\n    if isinstance(field_type, MutableSequence):\n        for field in field_type:\n            avroize_type(field, name_prefix)\n    elif isinstance(field_type, MutableMapping):\n        if field_type[\"type\"] in (\"enum\", \"record\"):\n            if \"name\" not in field_type:\n                field_type[\"name\"] = name_prefix + Text(uuid.uuid4())\n        if field_type[\"type\"] == \"record\":\n            avroize_type(field_type[\"fields\"], name_prefix)\n        if field_type[\"type\"] == \"array\":\n            avroize_type(field_type[\"items\"], name_prefix)\n        if isinstance(field_type[\"type\"], MutableSequence):\n            for ctype in field_type[\"type\"]:\n                avroize_type(ctype, name_prefix)\n    return field_type",
    "docstring": "adds missing information to a type so that CWL types are valid in schema_salad."
  },
  {
    "code": "def load_from_dict(dct=None, **kwargs):\n    dct = dct or dict()\n    dct.update(kwargs)\n    def _load_from_dict(metadata):\n        return dict(dct)\n    return _load_from_dict",
    "docstring": "Load configuration from a dictionary."
  },
  {
    "code": "def _setTaskParsObj(self, theTask):\n        self._taskParsObj = cfgpars.getObjectFromTaskArg(theTask,\n                                    self._strict, False)\n        self._taskParsObj.setDebugLogger(self)\n        self._lastSavedState = self._taskParsObj.dict()",
    "docstring": "Overridden version for ConfigObj. theTask can be either\n            a .cfg file name or a ConfigObjPars object."
  },
  {
    "code": "def set_source_filter(self, source):\n        if isinstance(source, str if py3k else basestring) and len(source) >= 2:\n            self.source_filter = source\n        else:\n            raise TwitterSearchException(1009)",
    "docstring": "Only search for tweets entered via given source\n\n        :param source: String. Name of the source to search for. An example \\\n        would be ``source=twitterfeed`` for tweets submitted via TwitterFeed\n        :raises: TwitterSearchException"
  },
  {
    "code": "def hash_file(path, digest=None):\n  digest = digest or hashlib.sha1()\n  with open(path, 'rb') as fd:\n    s = fd.read(8192)\n    while s:\n      digest.update(s)\n      s = fd.read(8192)\n  return digest.hexdigest() if PY3 else digest.hexdigest().decode('utf-8')",
    "docstring": "Hashes the contents of the file at the given path and returns the hash digest in hex form.\n\n  If a hashlib message digest is not supplied a new sha1 message digest is used."
  },
  {
    "code": "def get_branch_container_tag(self):\n        if self.__prefix:\n            return \"{0}-{1}\".format(\n                self.__prefix,\n                self.__branch)\n        else:\n            return \"{0}\".format(self.__branch)",
    "docstring": "Returns the branch container tag"
  },
  {
    "code": "async def query_handler(service, action_type, payload, props, **kwds):\n    if action_type == query_action_type():\n        print('encountered query event {!r} '.format(payload))\n        result = await parse_string(payload,\n            service.object_resolver,\n            service.connection_resolver,\n            service.mutation_resolver,\n            obey_auth=False\n        )\n        reply_props = {'correlation_id': props['correlation_id']} if 'correlation_id' in props else {}\n        await service.event_broker.send(\n            payload=result,\n            action_type=change_action_status(action_type, success_status()),\n            **reply_props\n        )",
    "docstring": "This action handler interprets the payload as a query to be executed\n        by the api gateway service."
  },
  {
    "code": "def error_response(response):\n    if response.status_code >= 500:\n        raise exceptions.GeocodioServerError\n    elif response.status_code == 403:\n        raise exceptions.GeocodioAuthError\n    elif response.status_code == 422:\n        raise exceptions.GeocodioDataError(response.json()[\"error\"])\n    else:\n        raise exceptions.GeocodioError(\n            \"Unknown service error (HTTP {0})\".format(response.status_code)\n        )",
    "docstring": "Raises errors matching the response code"
  },
  {
    "code": "def load (self, jamfile_location):\n        assert isinstance(jamfile_location, basestring)\n        absolute = os.path.join(os.getcwd(), jamfile_location)\n        absolute = os.path.normpath(absolute)\n        jamfile_location = b2.util.path.relpath(os.getcwd(), absolute)\n        mname = self.module_name(jamfile_location)\n        if not mname in self.jamfile_modules:\n            if \"--debug-loading\" in self.manager.argv():\n                print \"Loading Jamfile at '%s'\" % jamfile_location\n            self.load_jamfile(jamfile_location, mname)\n            self.load_used_projects(mname)\n        return mname",
    "docstring": "Loads jamfile at the given location. After loading, project global\n        file and jamfile needed by the loaded one will be loaded recursively.\n        If the jamfile at that location is loaded already, does nothing.\n        Returns the project module for the Jamfile."
  },
  {
    "code": "def _create_save_scenario_action(self):\n        icon = resources_path('img', 'icons', 'save-as-scenario.svg')\n        self.action_save_scenario = QAction(\n            QIcon(icon),\n            self.tr('Save Current Scenario'), self.iface.mainWindow())\n        message = self.tr('Save current scenario to text file')\n        self.action_save_scenario.setStatusTip(message)\n        self.action_save_scenario.setWhatsThis(message)\n        self.action_save_scenario.triggered.connect(self.save_scenario)\n        self.add_action(\n            self.action_save_scenario, add_to_toolbar=self.full_toolbar)",
    "docstring": "Create action for save scenario dialog."
  },
  {
    "code": "def makePalette(color1, color2, N, hsv=True):\n    if hsv:\n        color1 = rgb2hsv(color1)\n        color2 = rgb2hsv(color2)\n    c1 = np.array(getColor(color1))\n    c2 = np.array(getColor(color2))\n    cols = []\n    for f in np.linspace(0, 1, N - 1, endpoint=True):\n        c = c1 * (1 - f) + c2 * f\n        if hsv:\n            c = np.array(hsv2rgb(c))\n        cols.append(c)\n    return cols",
    "docstring": "Generate N colors starting from `color1` to `color2`\n    by linear interpolation HSV in or RGB spaces.\n\n    :param int N: number of output colors.\n    :param color1: first rgb color.\n    :param color2: second rgb color.\n    :param bool hsv: if `False`, interpolation is calculated in RGB space.\n\n    .. hint:: Example: |colorpalette.py|_"
  },
  {
    "code": "def split_data(X, y, ratio=(0.8, 0.1, 0.1)):\n    assert(sum(ratio) == 1 and len(ratio) == 3)\n    X_train, X_rest, y_train, y_rest = train_test_split(\n        X, y, train_size=ratio[0])\n    X_val, X_test, y_val, y_test = train_test_split(\n        X_rest, y_rest, train_size=ratio[1])\n    return X_train, X_val, X_test, y_train, y_val, y_test",
    "docstring": "Splits data into a training, validation, and test set.\n\n        Args:\n            X: text data\n            y: data labels\n            ratio: the ratio for splitting. Default: (0.8, 0.1, 0.1)\n\n        Returns:\n            split data: X_train, X_val, X_test, y_train, y_val, y_test"
  },
  {
    "code": "def _HasOOOWrite(self, path):\n    size = tf.io.gfile.stat(path).length\n    old_size = self._finalized_sizes.get(path, None)\n    if size != old_size:\n      if old_size is None:\n        logger.error('File %s created after file %s even though it\\'s '\n                         'lexicographically earlier', path, self._path)\n      else:\n        logger.error('File %s updated even though the current file is %s',\n                         path, self._path)\n      return True\n    else:\n      return False",
    "docstring": "Returns whether the path has had an out-of-order write."
  },
  {
    "code": "def add_title_translation(self, title, language, source=None):\n        title_translation = self._sourced_dict(\n            source,\n            title=title,\n            language=language,\n        )\n        self._append_to('title_translations', title_translation)",
    "docstring": "Add title translation.\n\n        :param title: translated title\n        :type title: string\n\n        :param language: language for the original title\n        :type language: string (2 characters ISO639-1)\n\n        :param source: source for the given title\n        :type source: string"
  },
  {
    "code": "def getClassInPackageFromName(className, pkg):\n    n = getAvClassNamesInPackage(pkg)\n    i = n.index(className)\n    c = getAvailableClassesInPackage(pkg)\n    return c[i]",
    "docstring": "get a class from name within a package"
  },
  {
    "code": "def init_app(self, app, add_context_processor=True):\n        if not hasattr(app, 'login_manager'):\n            self.login_manager.init_app(\n                app,\n                add_context_processor=add_context_processor)\n        self.login_manager.login_message = None\n        self.login_manager.needs_refresh_message = None\n        self.login_manager.unauthorized_handler(self.unauthorized_callback)",
    "docstring": "Initialize with app configuration"
  },
  {
    "code": "def available_perm_status(user):\n    roles = get_user_roles(user)\n    permission_hash = {}\n    for role in roles:\n        permission_names = role.permission_names_list()\n        for permission_name in permission_names:\n            permission_hash[permission_name] = get_permission(\n                permission_name) in user.user_permissions.all()\n    return permission_hash",
    "docstring": "Get a boolean map of the permissions available to a user\n    based on that user's roles."
  },
  {
    "code": "async def register_storage_library(storage_type: str, c_library: str, entry_point: str) -> None:\n        LOGGER.debug(\n            'WalletManager.register_storage_library >>> storage_type %s, c_library %s, entry_point %s',\n            storage_type,\n            c_library,\n            entry_point)\n        try:\n            stg_lib = CDLL(c_library)\n            result = stg_lib[entry_point]()\n            if result:\n                LOGGER.debug(\n                    'WalletManager.register_storage_library <!< indy error code %s on storage library entry at %s',\n                    result,\n                    entry_point)\n                raise IndyError(result)\n            LOGGER.info('Loaded storage library type %s (%s)', storage_type, c_library)\n        except IndyError as x_indy:\n            LOGGER.debug(\n                'WalletManager.register_storage_library <!< indy error code %s on load of storage library %s %s',\n                x_indy.error_code,\n                storage_type,\n                c_library)\n            raise\n        LOGGER.debug('WalletManager.register_storage_library <<<')",
    "docstring": "Load a wallet storage plug-in.\n\n        An indy-sdk wallet storage plug-in is a shared library; relying parties must explicitly\n        load it before creating or opening a wallet with the plug-in.\n\n        The implementation loads a dynamic library and calls an entry point; internally,\n        the plug-in calls the indy-sdk wallet\n        async def register_wallet_storage_library(storage_type: str, c_library: str, fn_pfx: str).\n\n        :param storage_type: wallet storage type\n        :param c_library: plug-in library\n        :param entry_point: function to initialize the library"
  },
  {
    "code": "def verify(self):\n        if self._is_verified:\n            return\n        for proxy in self._proxies.values():\n            proxy.verify()\n        self._is_verified = True",
    "docstring": "Verifies expectations on all doubled objects.\n\n        :raise: ``MockExpectationError`` on the first expectation that is not satisfied, if any."
  },
  {
    "code": "def name(self):\n        if self._name:\n            return self._name\n        return [\n            line.strip() for line in self.__doc__.split(\"\\n\")\n            if line.strip()][0]",
    "docstring": "Use the first line of docs string unless name set."
  },
  {
    "code": "async def async_put_state(self, field: str, data: dict) -> dict:\n        session = self.session.put\n        url = self.api_url + field\n        jsondata = json.dumps(data)\n        response_dict = await async_request(session, url, data=jsondata)\n        return response_dict",
    "docstring": "Set state of object in deCONZ.\n\n        Field is a string representing a specific device in deCONZ\n        e.g. field='/lights/1/state'.\n        Data is a json object with what data you want to alter\n        e.g. data={'on': True}.\n        See Dresden Elektroniks REST API documentation for details:\n        http://dresden-elektronik.github.io/deconz-rest-doc/rest/"
  },
  {
    "code": "def save_translations(self, instance, translated_data):\n        for meta in self.Meta.model._parler_meta:\n            translations = translated_data.get(meta.rel_name, {})\n            for lang_code, model_fields in translations.items():\n                translation = instance._get_translated_model(lang_code, auto_create=True, meta=meta)\n                for field, value in model_fields.items():\n                    setattr(translation, field, value)\n        instance.save_translations()",
    "docstring": "Save translation data into translation objects."
  },
  {
    "code": "def list(self, wg_uuid, parent=None, flat=False, node_types=None):\n        url = \"%(base)s/%(wg_uuid)s/nodes\" % {\n            'base': self.local_base_url,\n            'wg_uuid': wg_uuid\n        }\n        param = []\n        if parent:\n            if isinstance(parent, (list,)):\n                if len(parent) >= 1:\n                    parent = parent[-1]\n            param.append((\"parent\", parent))\n        if flat:\n            param.append((\"flat\", True))\n        if node_types:\n            for node_type in node_types:\n                param.append((\"type\", node_type))\n        encode = urllib.urlencode(param)\n        if encode:\n            url += \"?\"\n            url += encode\n        return self.core.list(url)",
    "docstring": "Get a list of workgroup nodes."
  },
  {
    "code": "def pluck(self, column):\n        result = self.first([column])\n        if result:\n            return result[column]",
    "docstring": "Pluck a single column from the database.\n\n        :param column: THe column to pluck\n        :type column: str\n\n        :return: The column value\n        :rtype: mixed"
  },
  {
    "code": "def register_value_producer(self, value_name: str, source: Callable[..., pd.DataFrame]=None,\n                                preferred_combiner: Callable=replace_combiner,\n                                preferred_post_processor: Callable[..., pd.DataFrame]=None) -> Pipeline:\n        return self._value_manager.register_value_producer(value_name, source,\n                                                           preferred_combiner,\n                                                           preferred_post_processor)",
    "docstring": "Marks a ``Callable`` as the producer of a named value.\n\n        Parameters\n        ----------\n        value_name :\n            The name of the new dynamic value pipeline.\n        source :\n            A callable source for the dynamic value pipeline.\n        preferred_combiner :\n            A strategy for combining the source and the results of any calls to mutators in the pipeline.\n            ``vivarium`` provides the strategies ``replace_combiner`` (the default), ``list_combiner``,\n            and ``set_combiner`` which are importable from ``vivarium.framework.values``.  Client code\n            may define additional strategies as necessary.\n        preferred_post_processor :\n            A strategy for processing the final output of the pipeline. ``vivarium`` provides the strategies\n            ``rescale_post_processor`` and ``joint_value_post_processor`` which are importable from\n            ``vivarium.framework.values``.  Client code may define additional strategies as necessary.\n\n        Returns\n        -------\n        Callable\n            A callable reference to the named dynamic value pipeline."
  },
  {
    "code": "def initbinset(self,binset=None):\n        if binset is None:\n            msg=\"(%s) does not have a defined binset in the wavecat table. The waveset of the spectrum will be used instead.\"%str(self.bandpass)\n            try:\n                self.binwave = self.bandpass.binset\n            except (KeyError, AttributeError):\n                self.binwave = self.spectrum.wave\n                print(msg)\n            if self.binwave is None:\n                self.binwave = self.spectrum.wave\n                print(msg)\n        else:\n            self.binwave=binset",
    "docstring": "Set ``self.binwave``.\n\n        By default, wavelength values for binning are inherited\n        from bandpass. If the bandpass has no binning information,\n        then source spectrum wavelengths are used. However, if\n        user provides values, then those are used without question.\n\n        Parameters\n        ----------\n        binset : array_like or `None`\n            Wavelength values to be used for binning when converting to counts."
  },
  {
    "code": "async def _auth_plain(self, username, password):\n        mechanism = \"PLAIN\"\n        credentials = \"\\0{}\\0{}\".format(username, password)\n        encoded_credentials = SMTP.b64enc(credentials)\n        try:\n            code, message = await self.do_cmd(\n                \"AUTH\", mechanism, encoded_credentials, success=(235, 503)\n            )\n        except SMTPCommandFailedError as e:\n            raise SMTPAuthenticationError(e.code, e.message, mechanism)\n        return code, message",
    "docstring": "Performs an authentication attempt using the PLAIN mechanism.\n\n        Protocol:\n\n            1. Format the username and password in a suitable way ;\n            2. The formatted string is base64-encoded ;\n            3. The string 'AUTH PLAIN' and a space character are prepended to\n               the base64-encoded username and password and sent to the\n               server ;\n            4. If the server replies with a 235 return code, user is\n               authenticated.\n\n        Args:\n            username (str): Identifier of the user trying to authenticate.\n            password (str): Password for the user.\n\n        Raises:\n            ConnectionResetError: If the connection with the server is\n                unexpectedely lost.\n            SMTPAuthenticationError: If the authentication attempt fails.\n\n        Returns:\n            (int, str): A (code, message) 2-tuple containing the server\n                response."
  },
  {
    "code": "def find(self, node, path):\n        return node.find(path, namespaces=self.namespaces)",
    "docstring": "Wrapper for lxml`s find."
  },
  {
    "code": "def querydict_to_multidict(query_dict, wrap=None):\n    wrap = wrap or (lambda val: val)\n    return MultiDict(chain.from_iterable(\n        six.moves.zip(repeat(key), (wrap(v) for v in vals))\n        for key, vals in six.iterlists(query_dict)\n    ))",
    "docstring": "Returns a new `webob.MultiDict` from a `django.http.QueryDict`.\n\n    If `wrap` is provided, it's used to wrap the values."
  },
  {
    "code": "def reverse_complement_sequences(records):\n    logging.info('Applying _reverse_complement_sequences generator: '\n                 'transforming sequences into reverse complements.')\n    for record in records:\n        rev_record = SeqRecord(record.seq.reverse_complement(),\n                               id=record.id, name=record.name,\n                               description=record.description)\n        _reverse_annotations(record, rev_record)\n        yield rev_record",
    "docstring": "Transform sequences into reverse complements."
  },
  {
    "code": "def table_from_cwb(source, *args, **kwargs):\n    return EventTable.read(source, 'waveburst', *args, format='root', **kwargs)",
    "docstring": "Read an `EventTable` from a Coherent WaveBurst ROOT file\n\n    This function just redirects to the format='root' reader with appropriate\n    defaults."
  },
  {
    "code": "def command_exists(command):\n    for category, commands in iteritems(command_categories):\n        for existing_command in commands:\n            if existing_command.match(command):\n                return True\n    return False",
    "docstring": "Check if the given command was registered. In another words if it\n    exists."
  },
  {
    "code": "async def process_updates(self, updates, fast: typing.Optional[bool] = True):\n        if fast:\n            tasks = []\n            for update in updates:\n                tasks.append(self.updates_handler.notify(update))\n            return await asyncio.gather(*tasks)\n        results = []\n        for update in updates:\n            results.append(await self.updates_handler.notify(update))\n        return results",
    "docstring": "Process list of updates\n\n        :param updates:\n        :param fast:\n        :return:"
  },
  {
    "code": "def color_for_level(level):\n    if not color_available:\n        return None\n    return {\n        logging.DEBUG: colorama.Fore.WHITE,\n        logging.INFO: colorama.Fore.BLUE,\n        logging.WARNING: colorama.Fore.YELLOW,\n        logging.ERROR: colorama.Fore.RED,\n        logging.CRITICAL: colorama.Fore.MAGENTA\n    }.get(level, colorama.Fore.WHITE)",
    "docstring": "Returns the colorama Fore color for a given log level.\n\n    If color is not available, returns None."
  },
  {
    "code": "def absent(name,\n           vhost='/',\n           runas=None):\n    ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n    policy_exists = __salt__['rabbitmq.policy_exists'](\n        vhost, name, runas=runas)\n    if not policy_exists:\n        ret['comment'] = 'Policy \\'{0} {1}\\' is not present.'.format(vhost, name)\n        return ret\n    if not __opts__['test']:\n        result = __salt__['rabbitmq.delete_policy'](vhost, name, runas=runas)\n        if 'Error' in result:\n            ret['result'] = False\n            ret['comment'] = result['Error']\n            return ret\n        elif 'Deleted' in result:\n            ret['comment'] = 'Deleted'\n    ret['changes'] = {'new': '', 'old': name}\n    if __opts__['test']:\n        ret['result'] = None\n        ret['comment'] = 'Policy \\'{0} {1}\\' will be removed.'.format(vhost, name)\n    return ret",
    "docstring": "Ensure the named policy is absent\n\n    Reference: http://www.rabbitmq.com/ha.html\n\n    name\n        The name of the policy to remove\n    runas\n        Name of the user to run the command as"
  },
  {
    "code": "def remove_sonos_playlist(self, sonos_playlist):\n        object_id = getattr(sonos_playlist, 'item_id', sonos_playlist)\n        return self.contentDirectory.DestroyObject([('ObjectID', object_id)])",
    "docstring": "Remove a Sonos playlist.\n\n        Args:\n            sonos_playlist (DidlPlaylistContainer): Sonos playlist to remove\n                or the item_id (str).\n\n        Returns:\n            bool: True if succesful, False otherwise\n\n        Raises:\n            SoCoUPnPException: If sonos_playlist does not point to a valid\n                object."
  },
  {
    "code": "def OnActivateReader(self, reader):\n        SimpleSCardAppEventObserver.OnActivateReader(self, reader)\n        self.feedbacktext.SetLabel('Activated reader: ' + repr(reader))",
    "docstring": "Called when a reader is activated by double-clicking on the\n        reader tree control or toolbar."
  },
  {
    "code": "def close(self):\n        self.stopped.set()\n        for event in self.to_be_stopped:\n            event.set()\n        if self._receiver_thread is not None:\n            self._receiver_thread.join()\n        self._socket.close()",
    "docstring": "Stop the client."
  },
  {
    "code": "def with_respect_to(self):\n        try:\n            name = self.order_with_respect_to\n            value = getattr(self, name)\n        except AttributeError:\n            return {}\n        field = getattr(self.__class__, name)\n        if isinstance(field, GenericForeignKey):\n            names = (field.ct_field, field.fk_field)\n            return dict([(n, getattr(self, n)) for n in names])\n        return {name: value}",
    "docstring": "Returns a dict to use as a filter for ordering operations\n        containing the original ``Meta.order_with_respect_to`` value\n        if provided. If the field is a Generic Relation, the dict\n        returned contains names and values for looking up the\n        relation's ``ct_field`` and ``fk_field`` attributes."
  },
  {
    "code": "def get_unit_property(self, unit_id, property_name):\n        if isinstance(unit_id, (int, np.integer)):\n            if unit_id in self.get_unit_ids():\n                if unit_id not in self._unit_properties:\n                    self._unit_properties[unit_id] = {}\n                if isinstance(property_name, str):\n                    if property_name in list(self._unit_properties[unit_id].keys()):\n                        return self._unit_properties[unit_id][property_name]\n                    else:\n                        raise ValueError(str(property_name) + \" has not been added to unit \" + str(unit_id))\n                else:\n                    raise ValueError(str(property_name) + \" must be a string\")\n            else:\n                raise ValueError(str(unit_id) + \" is not a valid unit_id\")\n        else:\n            raise ValueError(str(unit_id) + \" must be an int\")",
    "docstring": "This function rerturns the data stored under the property name given\n        from the given unit.\n\n        Parameters\n        ----------\n        unit_id: int\n            The unit id for which the property will be returned\n        property_name: str\n            The name of the property\n        Returns\n        ----------\n        value\n            The data associated with the given property name. Could be many\n            formats as specified by the user."
  },
  {
    "code": "def clear(self, key=None):\n        if not self.options.enabled:\n            return CACHE_DISABLED\n        logger.debug('clear(key={})'.format(repr(key)))\n        if key is not None and key in self._dict.keys():\n            del self._dict[key]\n            logger.info('cache cleared for key: ' + repr(key))\n        elif not key:\n            for cached_key in [k for k in self._dict.keys()]:\n                del self._dict[cached_key]\n            logger.info('cache cleared for ALL keys')\n        return True",
    "docstring": "Clear a cache entry, or the entire cache if no key is given\n\n        Returns CACHE_DISABLED if the cache is disabled\n        Returns True on successful operation\n\n        :param key: optional key to limit the clear operation to (defaults to None)"
  },
  {
    "code": "def _get_response(self, connection):\n        response_header = self._receive(connection, 13)\n        logger.debug('Response header: %s', response_header)\n        if (not response_header.startswith(b'ZBXD\\x01') or\n                len(response_header) != 13):\n            logger.debug('Zabbix return not valid response.')\n            result = False\n        else:\n            response_len = struct.unpack('<Q', response_header[5:])[0]\n            response_body = connection.recv(response_len)\n            result = json.loads(response_body.decode(\"utf-8\"))\n            logger.debug('Data received: %s', result)\n        try:\n            connection.close()\n        except Exception as err:\n            pass\n        return result",
    "docstring": "Get response from zabbix server, reads from self.socket.\n\n        :type connection: :class:`socket._socketobject`\n        :param connection: Socket to read.\n\n        :rtype: dict\n        :return: Response from zabbix server or False in case of error."
  },
  {
    "code": "def byte_adaptor(fbuffer):\n    if six.PY3:\n        strings = fbuffer.read().decode('latin-1')\n        fbuffer = six.StringIO(strings)\n        return fbuffer\n    else:\n        return fbuffer",
    "docstring": "provides py3 compatibility by converting byte based\n    file stream to string based file stream\n\n    Arguments:\n        fbuffer: file like objects containing bytes\n\n    Returns:\n        string buffer"
  },
  {
    "code": "def find_one(self, filter=None, fields=None, skip=0, sort=None):\n        result = self.find(filter=filter, fields=fields, skip=skip, limit=1, sort=sort)\n        if len(result) > 0:\n            return result[0]\n        else:\n            return None",
    "docstring": "Similar to find. This method will only retrieve one row.\n        If no row matches, returns None"
  },
  {
    "code": "def image(cam):\n    yield marv.set_header(title=cam.topic)\n    msg = yield marv.pull(cam)\n    if msg is None:\n        return\n    pytype = get_message_type(cam)\n    rosmsg = pytype()\n    rosmsg.deserialize(msg.data)\n    name = '{}.jpg'.format(cam.topic.replace('/', ':')[1:])\n    imgfile = yield marv.make_file(name)\n    img = imgmsg_to_cv2(rosmsg, \"rgb8\")\n    cv2.imwrite(imgfile.path, img, (cv2.IMWRITE_JPEG_QUALITY, 60))\n    yield marv.push(imgfile)",
    "docstring": "Extract first image of input stream to jpg file.\n\n    Args:\n        cam: Input stream of raw rosbag messages.\n\n    Returns:\n        File instance for first image of input stream."
  },
  {
    "code": "def file_content_list(self, project):\n        project_list = False\n        self.load_project_flag_list_file(il.get('project_exceptions'), project)\n        try:\n            flag_list = (fl['file_audits']['file_contents'])\n        except KeyError:\n            logger.error('Key Error processing file_contents list values')\n        try:\n            ignore_list = il['file_audits']['file_contents']\n        except KeyError:\n            logger.error('Key Error processing file_contents list values')\n        try:\n            project_list = fl['file_audits'][project]['file_contents']\n            logger.info('Loaded %s specific file_contents entries', project)\n        except KeyError:\n            logger.info('No project specific file_contents section for project %s', project)\n        if project_list:\n            ignore_list_merge = project_list + ignore_list\n            ignore_list_re = re.compile(\"|\".join(ignore_list_merge), flags=re.IGNORECASE)\n            return flag_list, ignore_list_re\n        else:\n            ignore_list_re = re.compile(\"|\".join(ignore_list),\n                                        flags=re.IGNORECASE)\n            return flag_list, ignore_list_re",
    "docstring": "gathers content strings"
  },
  {
    "code": "def rytov_sc(radius=5e-6, sphere_index=1.339, medium_index=1.333,\n             wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80),\n             center=(39.5, 39.5), radius_sampling=42):\n    r\n    r_ryt, n_ryt = correct_rytov_sc_input(radius_sc=radius,\n                                          sphere_index_sc=sphere_index,\n                                          medium_index=medium_index,\n                                          radius_sampling=radius_sampling)\n    qpi = mod_rytov.rytov(radius=r_ryt,\n                          sphere_index=n_ryt,\n                          medium_index=medium_index,\n                          wavelength=wavelength,\n                          pixel_size=pixel_size,\n                          grid_size=grid_size,\n                          center=center,\n                          radius_sampling=radius_sampling)\n    qpi[\"sim radius\"] = radius\n    qpi[\"sim index\"] = sphere_index\n    qpi[\"sim model\"] = \"rytov-sc\"\n    return qpi",
    "docstring": "r\"\"\"Field behind a dielectric sphere, systematically corrected Rytov\n\n    This method implements a correction of\n    :func:`qpsphere.models.rytov`, where the\n    `radius` :math:`r_\\text{Ryt}` and the `sphere_index`\n    :math:`n_\\text{Ryt}` are corrected using\n    the approach described in :cite:`Mueller2018` (eqns. 3,4, and 5).\n\n    .. math::\n\n        n_\\text{Ryt-SC} &= n_\\text{Ryt} + n_\\text{med} \\cdot\n                           \\left( a_n x^2 + b_n x + c_n \\right)\n\n        r_\\text{Ryt-SC} &= r_\\text{Ryt} \\cdot\n                           \\left( a_r x^2 +b_r x + c_r \\right)\n\n        &\\text{with} x = \\frac{n_\\text{Ryt}}{n_\\text{med}} - 1\n\n    The correction factors are given in\n    :data:`qpsphere.models.mod_rytov_sc.RSC_PARAMS`.\n\n    Parameters\n    ----------\n    radius: float\n        Radius of the sphere [m]\n    sphere_index: float\n        Refractive index of the sphere\n    medium_index: float\n        Refractive index of the surrounding medium\n    wavelength: float\n        Vacuum wavelength of the imaging light [m]\n    pixel_size: float\n        Pixel size [m]\n    grid_size: tuple of floats\n        Resulting image size in x and y [px]\n    center: tuple of floats\n        Center position in image coordinates [px]\n    radius_sampling: int\n        Number of pixels used to sample the sphere radius when\n        computing the Rytov field. The default value of 42\n        pixels is a reasonable number for single-cell analysis.\n\n    Returns\n    -------\n    qpi: qpimage.QPImage\n        Quantitative phase data set"
  },
  {
    "code": "def validate_word(self, word):\n        while word:\n            match = self.seg_regex.match(word)\n            if match:\n                word = word[len(match.group(0)):]\n            else:\n                return False\n        return True",
    "docstring": "Returns True if `word` consists exhaustively of valid IPA segments\n\n        Args:\n            word (unicode): input word as Unicode IPA string\n\n        Returns:\n            bool: True if `word` can be divided exhaustively into IPA segments\n                  that exist in the database"
  },
  {
    "code": "def did_you_mean(unknown_command, entry_points):\n    from difflib import SequenceMatcher\n    similarity = lambda x: SequenceMatcher(None, x, unknown_command).ratio()\n    did_you_mean = sorted(entry_points, key=similarity, reverse=True)\n    return did_you_mean[0]",
    "docstring": "Return the command with the name most similar to what the user typed.  This \n    is used to suggest a correct command when the user types an illegal \n    command."
  },
  {
    "code": "def block_specification_to_number(block: BlockSpecification, web3: Web3) -> BlockNumber:\n    if isinstance(block, str):\n        msg = f\"string block specification can't contain {block}\"\n        assert block in ('latest', 'pending'), msg\n        number = web3.eth.getBlock(block)['number']\n    elif isinstance(block, T_BlockHash):\n        number = web3.eth.getBlock(block)['number']\n    elif isinstance(block, T_BlockNumber):\n        number = block\n    else:\n        if __debug__:\n            raise AssertionError(f'Unknown type {type(block)} given for block specification')\n    return BlockNumber(number)",
    "docstring": "Converts a block specification to an actual block number"
  },
  {
    "code": "def from_requirement(cls, provider, requirement, parent):\n        candidates = provider.find_matches(requirement)\n        if not candidates:\n            raise NoVersionsAvailable(requirement, parent)\n        return cls(\n            candidates=candidates,\n            information=[RequirementInformation(requirement, parent)],\n        )",
    "docstring": "Build an instance from a requirement."
  },
  {
    "code": "def job(name, **kwargs):\n    return task(name=name, schedulable=True, base=JobTask,\n                bind=True, **kwargs)",
    "docstring": "A shortcut decorator for declaring jobs"
  },
  {
    "code": "def get_modpath_from_modname(modname, prefer_pkg=False, prefer_main=False):\n    from os.path import dirname, basename, join, exists\n    initname = '__init__.py'\n    mainname = '__main__.py'\n    if modname in sys.modules:\n        modpath = sys.modules[modname].__file__.replace('.pyc', '.py')\n    else:\n        import pkgutil\n        loader = pkgutil.find_loader(modname)\n        modpath = loader.filename.replace('.pyc', '.py')\n        if '.' not in basename(modpath):\n            modpath = join(modpath, initname)\n    if prefer_pkg:\n        if modpath.endswith(initname) or modpath.endswith(mainname):\n            modpath = dirname(modpath)\n    if prefer_main:\n        if modpath.endswith(initname):\n            main_modpath = modpath[:-len(initname)] + mainname\n            if exists(main_modpath):\n                modpath = main_modpath\n    return modpath",
    "docstring": "Same as get_modpath but doesnt import directly\n\n    SeeAlso:\n        get_modpath"
  },
  {
    "code": "def _close_app(app, mongo_client, client):\n    app.stop()\n    client.close()\n    mongo_client.close()",
    "docstring": "Ensures that the app is properly closed"
  },
  {
    "code": "def htmresearchCorePrereleaseInstalled():\n  try:\n    coreDistribution = pkg_resources.get_distribution(\"htmresearch-core\")\n    if pkg_resources.parse_version(coreDistribution.version).is_prerelease:\n      return True\n  except pkg_resources.DistributionNotFound:\n    pass\n  return False",
    "docstring": "Make an attempt to determine if a pre-release version of htmresearch-core is\n  installed already.\n\n  @return: boolean"
  },
  {
    "code": "def cursor_after(self):\n    if isinstance(self._cursor_after, BaseException):\n      raise self._cursor_after\n    return self._cursor_after",
    "docstring": "Return the cursor after the current item.\n\n    You must pass a QueryOptions object with produce_cursors=True\n    for this to work.\n\n    If there is no cursor or no current item, raise BadArgumentError.\n    Before next() has returned there is no cursor.    Once the loop is\n    exhausted, this returns the cursor after the last item."
  },
  {
    "code": "def unregister_listener(self, address, func):\n        listeners = self.address_listeners[address]\n        if listeners is None:\n            return False\n        if func in listeners:\n            listeners.remove(func)\n            return True\n        return False",
    "docstring": "Removes a listener function for a given address\n\n        Remove the listener for the given address. Returns true if the listener\n        was found and removed, false otherwise"
  },
  {
    "code": "def _format_generic(lines, element, printed, spacer=\"\"):\n    for doc in element.docstring:\n        if doc.doctype.lower() not in printed:\n            lines.append(spacer + doc.__str__())",
    "docstring": "Generically formats all remaining docstrings and custom XML\n    tags that don't appear in the list of already printed documentation.\n\n    :arg printed: a list of XML tags for the element that have already\n      been handled by a higher method."
  },
  {
    "code": "def wash_html_id(dirty):\n    import re\n    if not dirty[0].isalpha():\n        dirty = 'i' + dirty\n    non_word = re.compile(r'[^\\w]+')\n    return non_word.sub('', dirty)",
    "docstring": "Strip non-alphabetic or newline characters from a given string.\n\n    It can be used as a HTML element ID (also with jQuery and in all browsers).\n\n    :param dirty: the string to wash\n    :returns: the HTML ID ready string"
  },
  {
    "code": "def _build_sentence(word):\n    return (\n        \"(?:{word}|[{non_stops}]|(?<![{stops} ]) )+\"\n        \"[{stops}]['\\\"\\]\\}}\\)]*\"\n    ).format(word=word, non_stops=non_stops.replace('-', '\\-'),\n             stops=stops)",
    "docstring": "Builds a Pinyin sentence re pattern from a Pinyin word re pattern.\n\n    A sentence is defined as a series of valid Pinyin words, punctuation\n    (non-stops), and spaces followed by a single stop and zero or more\n    container-closing punctuation marks (e.g. apostrophe and brackets)."
  },
  {
    "code": "def get_available_options(self, service_name):\n        options = {}\n        for data_dir in self.data_dirs:\n            service_glob = \"{0}-*.json\".format(service_name)\n            path = os.path.join(data_dir, service_glob)\n            found = glob.glob(path)\n            for match in found:\n                base = os.path.basename(match)\n                bits = os.path.splitext(base)[0].split('-', 1)\n                if len(bits) < 2:\n                    continue\n                api_version = bits[1]\n                options.setdefault(api_version, [])\n                options[api_version].append(match)\n        return options",
    "docstring": "Fetches a collection of all JSON files for a given service.\n\n        This checks user-created files (if present) as well as including the\n        default service files.\n\n        Example::\n\n            >>> loader.get_available_options('s3')\n            {\n                '2013-11-27': [\n                    '~/.boto-overrides/s3-2013-11-27.json',\n                    '/path/to/kotocore/data/aws/resources/s3-2013-11-27.json',\n                ],\n                '2010-10-06': [\n                    '/path/to/kotocore/data/aws/resources/s3-2010-10-06.json',\n                ],\n                '2007-09-15': [\n                    '~/.boto-overrides/s3-2007-09-15.json',\n                ],\n            }\n\n        :param service_name: The name of the desired service\n        :type service_name: string\n\n        :returns: A dictionary of api_version keys, with a list of filepaths\n            for that version (in preferential order).\n        :rtype: dict"
  },
  {
    "code": "def service_desks(self):\n        url = self._options['server'] + '/rest/servicedeskapi/servicedesk'\n        headers = {'X-ExperimentalApi': 'opt-in'}\n        r_json = json_loads(self._session.get(url, headers=headers))\n        projects = [ServiceDesk(self._options, self._session, raw_project_json)\n                    for raw_project_json in r_json['values']]\n        return projects",
    "docstring": "Get a list of ServiceDesk Resources from the server visible to the current authenticated user.\n\n        :rtype: List[ServiceDesk]"
  },
  {
    "code": "def sign(self, private_keys):\n        if private_keys is None or not isinstance(private_keys, list):\n            raise TypeError('`private_keys` must be a list instance')\n        def gen_public_key(private_key):\n            public_key = private_key.get_verifying_key().encode()\n            return public_key.decode()\n        key_pairs = {gen_public_key(PrivateKey(private_key)):\n                     PrivateKey(private_key) for private_key in private_keys}\n        tx_dict = self.to_dict()\n        tx_dict = Transaction._remove_signatures(tx_dict)\n        tx_serialized = Transaction._to_str(tx_dict)\n        for i, input_ in enumerate(self.inputs):\n            self.inputs[i] = self._sign_input(input_, tx_serialized, key_pairs)\n        self._hash()\n        return self",
    "docstring": "Fulfills a previous Transaction's Output by signing Inputs.\n\n            Note:\n                This method works only for the following Cryptoconditions\n                currently:\n                    - Ed25519Fulfillment\n                    - ThresholdSha256\n                Furthermore, note that all keys required to fully sign the\n                Transaction have to be passed to this method. A subset of all\n                will cause this method to fail.\n\n            Args:\n                private_keys (:obj:`list` of :obj:`str`): A complete list of\n                    all private keys needed to sign all Fulfillments of this\n                    Transaction.\n\n            Returns:\n                :class:`~bigchaindb.common.transaction.Transaction`"
  },
  {
    "code": "def close(self):\n        self._check_device_status()\n        hidapi.hid_close(self._device)\n        self._device = None",
    "docstring": "Close connection to HID device.\n\n        Automatically run when a Device object is garbage-collected, though\n        manual invocation is recommended."
  },
  {
    "code": "def dt2ts(dt):\r\n    assert isinstance(dt, (datetime.datetime, datetime.date))\r\n    ret = time.mktime(dt.timetuple())\r\n    if isinstance(dt, datetime.datetime):\r\n        ret += 1e-6 * dt.microsecond\r\n    return ret",
    "docstring": "Converts to float representing number of seconds since 1970-01-01 GMT."
  },
  {
    "code": "def _check_permission(self, name, obj=None):\n        def redirect_or_exception(ex):\n            if not self.request.user or not self.request.user.is_authenticated:\n                if self.auto_login_redirect:\n                    redirect_to_login(self.request.get_full_path())\n                else:\n                    raise HTTPUnauthorizedResponseException\n            else:\n                raise ex\n        try:\n            if not self._has_permission(name, obj):\n                redirect_or_exception(HTTPForbiddenResponseException)\n        except Http404 as ex:\n            redirect_or_exception(ex)",
    "docstring": "If customer is not authorized he should not get information that object is exists.\n        Therefore 403 is returned if object was not found or is redirected to the login page.\n        If custmer is authorized and object was not found is returned 404.\n        If object was found and user is not authorized is returned 403 or redirect to login page.\n        If object was found and user is authorized is returned 403 or 200 according of result of _has_permission method."
  },
  {
    "code": "def fetch(self, **kwargs) -> 'FetchContextManager':\n        assert self.method in self._allowed_methods, \\\n               'Disallowed HTTP method: {}'.format(self.method)\n        self.date = datetime.now(tzutc())\n        self.headers['Date'] = self.date.isoformat()\n        if self.content_type is not None:\n            self.headers['Content-Type'] = self.content_type\n        full_url = self._build_url()\n        self._sign(full_url.relative())\n        rqst_ctx = self.session.aiohttp_session.request(\n            self.method,\n            str(full_url),\n            data=self._pack_content(),\n            timeout=_default_request_timeout,\n            headers=self.headers)\n        return FetchContextManager(self.session, rqst_ctx, **kwargs)",
    "docstring": "Sends the request to the server and reads the response.\n\n        You may use this method either with plain synchronous Session or\n        AsyncSession.  Both the followings patterns are valid:\n\n        .. code-block:: python3\n\n          from ai.backend.client.request import Request\n          from ai.backend.client.session import Session\n\n          with Session() as sess:\n            rqst = Request(sess, 'GET', ...)\n            with rqst.fetch() as resp:\n              print(resp.text())\n\n        .. code-block:: python3\n\n          from ai.backend.client.request import Request\n          from ai.backend.client.session import AsyncSession\n\n          async with AsyncSession() as sess:\n            rqst = Request(sess, 'GET', ...)\n            async with rqst.fetch() as resp:\n              print(await resp.text())"
  },
  {
    "code": "def retrieve_data(self):\n        df = self.manager.get_historic_data(self.start.date(), self.end.date())\n        df.replace(0, np.nan, inplace=True)\n        return df",
    "docstring": "Retrives data as a DataFrame."
  },
  {
    "code": "def find_nearest(x, x0) -> Tuple[int, Any]:\n    x = np.asanyarray(x)\n    x0 = np.atleast_1d(x0)\n    if x.size == 0 or x0.size == 0:\n        raise ValueError('empty input(s)')\n    if x0.ndim not in (0, 1):\n        raise ValueError('2-D x0 not handled yet')\n    ind = np.empty_like(x0, dtype=int)\n    for i, xi in enumerate(x0):\n        if xi is not None and (isinstance(xi, (datetime.datetime, datetime.date, np.datetime64)) or np.isfinite(xi)):\n            ind[i] = np.nanargmin(abs(x-xi))\n        else:\n            raise ValueError('x0 must NOT be None or NaN to avoid surprising None return value')\n    return ind.squeeze()[()], x[ind].squeeze()[()]",
    "docstring": "This find_nearest function does NOT assume sorted input\n\n    inputs:\n    x: array (float, int, datetime, h5py.Dataset) within which to search for x0\n    x0: singleton or array of values to search for in x\n\n    outputs:\n    idx: index of flattened x nearest to x0  (i.e. works with higher than 1-D arrays also)\n    xidx: x[idx]\n\n    Observe how bisect.bisect() gives the incorrect result!\n\n    idea based on:\n    http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array"
  },
  {
    "code": "def submit(self, port_id, tuple_):\n        port_index = self._splpy_output_ports[port_id]\n        ec._submit(self, port_index, tuple_)",
    "docstring": "Submit a tuple to the output port.\n\n        The value to be submitted (``tuple_``) can be a ``None`` (nothing will be submitted),\n        ``tuple``, ``dict` or ``list`` of those types. For details\n        on how the ``tuple_`` is mapped to an SPL tuple see :ref:`submit-from-python`.\n\n        Args:\n             port_id: Identifier of the port specified in the\n                  ``output_ports`` parameter of the ``@spl.primitive_operator``\n                  decorator.\n             tuple_: Tuple (or tuples) to be submitted to the output port."
  },
  {
    "code": "def build_request_relationship(type, ids):\n    if ids is None:\n        return {\n            'data': None\n        }\n    elif isinstance(ids, str):\n        return {\n            'data': {'id': ids, 'type': type}\n        }\n    else:\n        return {\n            \"data\": [{\"id\": id, \"type\": type} for id in ids]\n        }",
    "docstring": "Build a relationship list.\n\n    A relationship list is used to update relationships between two\n    resources. Setting sensors on a label, for example, uses this\n    function to construct the list of sensor ids to pass to the Helium\n    API.\n\n    Args:\n\n        type(string): The resource type for the ids in the relationship\n        ids([uuid] or uuid): Just one or a list of resource uuids to use\n            in the relationship\n\n    Returns:\n\n        A ready to use relationship JSON object."
  },
  {
    "code": "def init_search(self):\n        if self.verbose:\n            logger.info(\"Initializing search.\")\n        for generator in self.generators:\n            graph = generator(self.n_classes, self.input_shape).generate(\n                self.default_model_len, self.default_model_width\n            )\n            model_id = self.model_count\n            self.model_count += 1\n            self.training_queue.append((graph, -1, model_id))\n            self.descriptors.append(graph.extract_descriptor())\n        if self.verbose:\n            logger.info(\"Initialization finished.\")",
    "docstring": "Call the generators to generate the initial architectures for the search."
  },
  {
    "code": "def get_publisher(self):\n        doi_prefix = self.doi.split('/')[0]\n        try:\n            publisher_mod = openaccess_epub.publisher.import_by_doi(doi_prefix)\n        except ImportError as e:\n            log.exception(e)\n            return None\n        return publisher_mod.pub_class(self)",
    "docstring": "This method defines how the Article tries to determine the publisher of\n        the article.\n\n        This method relies on the success of the get_DOI method to fetch the\n        appropriate full DOI for the article. It then takes the DOI prefix\n        which corresponds to the publisher and then uses that to attempt to load\n        the correct publisher-specific code. This may fail; if the DOI is not\n        mapped to a code file, if the DOI is mapped but the code file could not\n        be located, or if the mapped code file is malformed then this method\n        will issue/log an informative error message and return None. This method\n        will not try to infer the publisher based on any metadata other than the\n        DOI of the article.\n\n        Returns\n        -------\n        publisher : Publisher instance or None"
  },
  {
    "code": "def file_copy(name, dest=None, **kwargs):\n    ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}\n    ret['changes'] = __salt__['junos.file_copy'](name, dest, **kwargs)\n    return ret",
    "docstring": "Copies the file from the local device to the junos device.\n\n    .. code-block:: yaml\n\n            /home/m2/info.txt:\n              junos:\n                - file_copy\n                - dest: info_copy.txt\n\n    Parameters:\n      Required\n        * src:\n          The sorce path where the file is kept.\n        * dest:\n          The destination path where the file will be copied."
  },
  {
    "code": "def hook_drag(self):\n        widget = self.widget\n        widget.mousePressEvent = self.mousePressEvent\n        widget.mouseMoveEvent = self.mouseMoveEvent\n        widget.mouseReleaseEvent = self.mouseReleaseEvent",
    "docstring": "Install the hooks for drag operations."
  },
  {
    "code": "def removeSubscribers(self, emails_list):\n        if not hasattr(emails_list, \"__iter__\"):\n            error_msg = \"Input parameter 'emails_list' is not iterable\"\n            self.log.error(error_msg)\n            raise exception.BadValue(error_msg)\n        missing_flags = True\n        headers, raw_data = self._perform_subscribe()\n        for email in emails_list:\n            missing_flag, raw_data = self._remove_subscriber(email, raw_data)\n            missing_flags = missing_flags and missing_flag\n        if missing_flags:\n            return\n        self._update_subscribe(headers, raw_data)\n        self.log.info(\"Successfully remove subscribers: %s for <Workitem %s>\",\n                      emails_list, self)",
    "docstring": "Remove subscribers from this workitem\n\n        If the subscribers have not been added, no more actions will be\n        performed.\n\n        :param emails_list: a :class:`list`/:class:`tuple`/:class:`set`\n            contains the the subscribers' emails"
  },
  {
    "code": "def ellipsis(text, length, symbol=\"...\"):\n    if len(text) > length:\n        pos = text.rfind(\" \", 0, length)\n        if pos < 0:\n            return text[:length].rstrip(\".\") + symbol\n        else:\n            return text[:pos].rstrip(\".\") + symbol\n    else:\n        return text",
    "docstring": "Present a block of text of given length.\n    \n    If the length of available text exceeds the requested length, truncate and\n    intelligently append an ellipsis."
  },
  {
    "code": "def load_data(self, data_np):\n        image = AstroImage.AstroImage(logger=self.logger)\n        image.set_data(data_np)\n        self.set_image(image)",
    "docstring": "Load raw numpy data into the viewer."
  },
  {
    "code": "def update(self, **kwargs):\n        update_compute = False\n        old_json = self.__json__()\n        compute_properties = None\n        for prop in kwargs:\n            if getattr(self, prop) != kwargs[prop]:\n                if prop not in self.CONTROLLER_ONLY_PROPERTIES:\n                    update_compute = True\n                if prop == \"properties\":\n                    compute_properties = kwargs[prop]\n                else:\n                    setattr(self, prop, kwargs[prop])\n        self._list_ports()\n        if old_json != self.__json__():\n            self.project.controller.notification.emit(\"node.updated\", self.__json__())\n        if update_compute:\n            data = self._node_data(properties=compute_properties)\n            response = yield from self.put(None, data=data)\n            yield from self.parse_node_response(response.json)\n        self.project.dump()",
    "docstring": "Update the node on the compute server\n\n        :param kwargs: Node properties"
  },
  {
    "code": "def to_geojson(self, filename):\n        with open(filename, 'w') as fd:\n            json.dump(self.to_record(WGS84_CRS), fd)",
    "docstring": "Save vector as geojson."
  },
  {
    "code": "def _make_concept(self, entity):\n        name = self._sanitize(entity['canonicalName'])\n        db_refs = _get_grounding(entity)\n        concept = Concept(name, db_refs=db_refs)\n        metadata = {arg['type']: arg['value']['@id']\n                    for arg in entity['arguments']}\n        return concept, metadata",
    "docstring": "Return Concept from a Hume entity."
  },
  {
    "code": "def tip_fdr(a, alpha=0.05):\n    zscores = tip_zscores(a)\n    pvals = stats.norm.pdf(zscores)\n    rejected, fdrs = fdrcorrection(pvals)\n    return fdrs",
    "docstring": "Returns adjusted TIP p-values for a particular `alpha`.\n\n    (see :func:`tip_zscores` for more info)\n\n    :param a: NumPy array, where each row is the signal for a feature\n    :param alpha: False discovery rate"
  },
  {
    "code": "def run(self):\n        from zengine.lib.cache import WFSpecNames\n        if self.manager.args.clear:\n            self._clear_models()\n            return\n        if self.manager.args.wf_path:\n            paths = self.get_wf_from_path(self.manager.args.wf_path)\n        else:\n            paths = self.get_workflows()\n        self.count = 0\n        self.do_with_submit(self.load_diagram, paths, threads=self.manager.args.threads)\n        WFSpecNames().refresh()\n        print(\"%s BPMN file loaded\" % self.count)",
    "docstring": "read workflows, checks if it's updated,\n        tries to update if there aren't any running instances of that wf"
  },
  {
    "code": "def make_and_return_path_from_path_and_folder_names(path, folder_names):\n    for folder_name in folder_names:\n        path += folder_name + '/'\n        try:\n            os.makedirs(path)\n        except FileExistsError:\n            pass\n    return path",
    "docstring": "For a given path, create a directory structure composed of a set of folders and return the path to the \\\n    inner-most folder.\n\n    For example, if path='/path/to/folders', and folder_names=['folder1', 'folder2'], the directory created will be\n    '/path/to/folders/folder1/folder2/' and the returned path will be '/path/to/folders/folder1/folder2/'.\n\n    If the folders already exist, routine continues as normal.\n\n    Parameters\n    ----------\n    path : str\n        The path where the directories are created.\n    folder_names : [str]\n        The names of the folders which are created in the path directory.\n\n    Returns\n    -------\n    path\n        A string specifying the path to the inner-most folder created.\n\n    Examples\n    --------\n    path = '/path/to/folders'\n    path = make_and_return_path(path=path, folder_names=['folder1', 'folder2']."
  },
  {
    "code": "def get_buffer(self):\n        if self.doc_to_update:\n            self.update_sources()\n        ES_buffer = self.action_buffer\n        self.clean_up()\n        return ES_buffer",
    "docstring": "Get buffer which needs to be bulked to elasticsearch"
  },
  {
    "code": "def traverse_inorder(self, leaves=True, internal=True):\n        for node in self.root.traverse_inorder(leaves=leaves, internal=internal):\n            yield node",
    "docstring": "Perform an inorder traversal of the ``Node`` objects in this ``Tree``\n\n        Args:\n            ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``\n\n            ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``"
  },
  {
    "code": "def cmd_watch(args):\n    if len(args) == 0:\n        mpstate.status.watch = None\n        return\n    mpstate.status.watch = args\n    print(\"Watching %s\" % mpstate.status.watch)",
    "docstring": "watch a mavlink packet pattern"
  },
  {
    "code": "def serialize_on_post_delete(sender, instance, using, **kwargs):\n    try:\n        wrapped_instance = site_offline_models.get_wrapped_instance(instance)\n    except ModelNotRegistered:\n        pass\n    else:\n        wrapped_instance.to_outgoing_transaction(using, created=False, deleted=True)",
    "docstring": "Creates a serialized OutgoingTransaction when\n    a model instance is deleted.\n\n    Skip those not registered."
  },
  {
    "code": "def predict(self, X, nsamples=200, likelihood_args=()):\n        Ey, _ = self.predict_moments(X, nsamples, likelihood_args)\n        return Ey",
    "docstring": "Predict target values from Bayesian generalized linear regression.\n\n        Parameters\n        ----------\n        X : ndarray\n            (N*,d) array query input dataset (N* samples, d dimensions).\n        nsamples : int, optional\n            Number of samples for sampling the expected target values from the\n            predictive distribution.\n        likelihood_args : sequence, optional\n            sequence of arguments to pass to the likelihood function. These are\n            non-learnable parameters. They can be scalars or arrays of length\n            N.\n\n        Returns\n        -------\n        Ey : ndarray\n            The expected value of y* for the query inputs, X* of shape (N*,)."
  },
  {
    "code": "def _load(self):\n        if os.path.exists(self.path):\n            root = ET.parse(self.path).getroot()\n            if (root.tag == \"fortpy\" and \"mode\" in root.attrib and\n                root.attrib[\"mode\"] == \"template\" and \"direction\" in root.attrib and\n                root.attrib[\"direction\"] == self.direction):\n                for v in _get_xml_version(root):\n                    self.versions[v] = TemplateContents()\n                self._load_entries(root)\n                if \"autoname\" in root.attrib:\n                    self.name = root.attrib[\"autoname\"]\n            else:\n                msg.err(\"the specified template {} \".format(self.path) + \n                        \"is missing the mode and direction attributes.\")\n                exit(1)\n        else:\n            msg.err(\"could not find the template {}.\".format(self.path))\n            exit(1)",
    "docstring": "Extracts the XML template data from the file."
  },
  {
    "code": "def get_extra(cls, name=None):\n    if not name:\n      return cls._extra_config\n    return cls._extra_config.get(name, None)",
    "docstring": "Gets extra configuration parameters.\n\n    These parameters should be loaded through load_extra or load_extra_data.\n\n    Args:\n      name: str, the name of the configuration data to load.\n\n    Returns:\n      A dictionary containing the requested configuration data. None if\n      data was never loaded under that name."
  },
  {
    "code": "def take(self, num_instances: int = 1, timeout: Optional[float] = None) -> None:\n        if num_instances < 1:\n            raise ValueError(f\"Process must request at least 1 instance; here requested {num_instances}.\")\n        if num_instances > self.num_instances_total:\n            raise ValueError(\n                f\"Process must request at most {self.num_instances_total} instances; here requested {num_instances}.\"\n            )\n        if _logger is not None:\n            self._log(INFO, \"take\", num_instances=num_instances, free=self.num_instances_free)\n        proc = Process.current()\n        if self._num_instances_free < num_instances:\n            proc.local.__num_instances_required = num_instances\n            try:\n                self._waiting.join(timeout)\n            finally:\n                del proc.local.__num_instances_required\n        self._num_instances_free -= num_instances\n        if _logger is not None and proc in self._usage:\n            self._log(WARNING, \"take-again\", already=self._usage[proc], more=num_instances)\n        self._usage.setdefault(proc, 0)\n        self._usage[proc] += num_instances",
    "docstring": "The current process reserves a certain number of instances. If there are not enough instances available, the\n        process is made to join a queue. When this method returns, the process holds the instances it has requested to\n        take.\n\n        :param num_instances:\n            Number of resource instances to take.\n        :param timeout:\n            If this parameter is not ``None``, it is taken as a delay at the end of which the process times out, and\n            leaves the queue forcibly. In such a situation, a :py:class:`Timeout` exception is raised on the process."
  },
  {
    "code": "def _get_billing_cycle_number(self, billing_cycle):\n        begins_before_initial_date = billing_cycle.date_range.lower < self.initial_billing_cycle.date_range.lower\n        if begins_before_initial_date:\n            raise ProvidedBillingCycleBeginsBeforeInitialBillingCycle(\n                '{} precedes initial cycle {}'.format(billing_cycle, self.initial_billing_cycle)\n            )\n        billing_cycle_number = BillingCycle.objects.filter(\n            date_range__contained_by=DateRange(\n                self.initial_billing_cycle.date_range.lower,\n                billing_cycle.date_range.upper,\n                bounds='[]',\n            ),\n        ).count()\n        return billing_cycle_number",
    "docstring": "Gets the 1-indexed number of the billing cycle relative to the provided billing cycle"
  },
  {
    "code": "def unzip_file(source_file, dest_dir=None, mkdir=False):\n    if dest_dir is None:\n        dest_dir, fname = os.path.split(source_file)\n    elif not os.path.isdir(dest_dir):\n        if mkdir:\n            preparedir(dest_dir)\n        else:\n            created = preparedir(dest_dir, False)\n            if not created:\n                raise ValueError(\"Failed to find %s.\" % dest_dir)\n    with zipfile.ZipFile(source_file) as zf:\n        for member in zf.infolist():\n            words = member.filename.split('\\\\')\n            for word in words[:-1]:\n                drive, word = os.path.splitdrive(word)\n                head, word = os.path.split(word)\n                if word in (os.curdir, os.pardir, ''):\n                    continue\n                dest_dir = os.path.join(dest_dir, word)\n            zf.extract(member, dest_dir)",
    "docstring": "Unzip a compressed file.\n\n    Args:\n        source_file: Full path to a valid compressed file (e.g. c:/ladybug/testPts.zip)\n        dest_dir: Target folder to extract to (e.g. c:/ladybug).\n            Default is set to the same directory as the source file.\n        mkdir: Set to True to create the directory if doesn't exist (Default: False)"
  },
  {
    "code": "def _get_retention_policy_value(self):\n        if self.RetentionPolicy is None or self.RetentionPolicy.lower() == self.RETAIN.lower():\n            return self.RETAIN\n        elif self.RetentionPolicy.lower() == self.DELETE.lower():\n            return self.DELETE\n        elif self.RetentionPolicy.lower() not in self.retention_policy_options:\n            raise InvalidResourceException(self.logical_id,\n                                           \"'{}' must be one of the following options: {}.\"\n                                           .format('RetentionPolicy', [self.RETAIN, self.DELETE]))",
    "docstring": "Sets the deletion policy on this resource. The default is 'Retain'.\n\n        :return: value for the DeletionPolicy attribute."
  },
  {
    "code": "def fen(self, *, shredder: bool = False, en_passant: str = \"legal\", promoted: Optional[bool] = None) -> str:\n        return \" \".join([\n            self.epd(shredder=shredder, en_passant=en_passant, promoted=promoted),\n            str(self.halfmove_clock),\n            str(self.fullmove_number)\n        ])",
    "docstring": "Gets a FEN representation of the position.\n\n        A FEN string (e.g.,\n        ``rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1``) consists\n        of the position part :func:`~chess.Board.board_fen()`, the\n        :data:`~chess.Board.turn`, the castling part\n        (:data:`~chess.Board.castling_rights`),\n        the en passant square (:data:`~chess.Board.ep_square`),\n        the :data:`~chess.Board.halfmove_clock`\n        and the :data:`~chess.Board.fullmove_number`.\n\n        :param shredder: Use :func:`~chess.Board.castling_shredder_fen()`\n            and encode castling rights by the file of the rook\n            (like ``HAha``) instead of the default\n            :func:`~chess.Board.castling_xfen()` (like ``KQkq``).\n        :param en_passant: By default, only fully legal en passant squares\n            are included (:func:`~chess.Board.has_legal_en_passant()`).\n            Pass ``fen`` to strictly follow the FEN specification\n            (always include the en passant square after a two-step pawn move)\n            or ``xfen`` to follow the X-FEN specification\n            (:func:`~chess.Board.has_pseudo_legal_en_passant()`).\n        :param promoted: Mark promoted pieces like ``Q~``. By default, this is\n            only enabled in chess variants where this is relevant."
  },
  {
    "code": "def _exec_info(self):\n        if self._info is None:\n            self._info = self.client.exec_inspect(self.exec_id)\n        return self._info",
    "docstring": "Caching wrapper around client.exec_inspect"
  },
  {
    "code": "def get_field_setup_query(query, model, column_name):\n    if not hasattr(model, column_name):\n        rel_model = getattr(model, column_name.split(\".\")[0]).mapper.class_\n        query = query.join(rel_model)\n        return query, getattr(rel_model, column_name.split(\".\")[1])\n    else:\n        return query, getattr(model, column_name)",
    "docstring": "Help function for SQLA filters, checks for dot notation on column names.\n        If it exists, will join the query with the model\n        from the first part of the field name.\n\n        example:\n            Contact.created_by: if created_by is a User model,\n            it will be joined to the query."
  },
  {
    "code": "def _completion_checker(async_id, context_id):\n    if not context_id:\n        logging.debug(\"Context for async %s does not exist\", async_id)\n        return\n    context = FuriousContext.from_id(context_id)\n    marker = FuriousCompletionMarker.get_by_id(context_id)\n    if marker and marker.complete:\n        logging.info(\"Context %s already complete\" % context_id)\n        return True\n    task_ids = context.task_ids\n    if async_id in task_ids:\n        task_ids.remove(async_id)\n    logging.debug(\"Loaded context.\")\n    logging.debug(task_ids)\n    done, has_errors = _check_markers(task_ids)\n    if not done:\n        return False\n    _mark_context_complete(marker, context, has_errors)\n    return True",
    "docstring": "Check if all Async jobs within a Context have been run."
  },
  {
    "code": "def _transliterate (self, text, outFormat):\n        result = []\n        text = self._preprocess(text)\n        i = 0\n        while i < len(text):\n            if text[i].isspace(): \n                result.append(text[i])\n                i = i+1\n            else: \n                chr = self._getNextChar(text, i)\n                try:\n                    result.append(self[chr].unichr)\n                except KeyError:\n                    result.append(_unrecognised(chr))\n                i = i + len(chr)\n        return result",
    "docstring": "Transliterate the text to Unicode."
  },
  {
    "code": "def close(self):\n        log.debug(\"%r: close\", self)\n        self._closing = True\n        brokerclients, self.clients = self.clients, None\n        self._close_brokerclients(brokerclients.values())\n        self.reset_all_metadata()\n        return self.close_dlist or defer.succeed(None)",
    "docstring": "Permanently dispose of the client\n\n        - Immediately mark the client as closed, causing current operations to\n          fail with :exc:`~afkak.common.CancelledError` and future operations to\n          fail with :exc:`~afkak.common.ClientError`.\n        - Clear cached metadata.\n        - Close any connections to Kafka brokers.\n\n        :returns:\n            deferred that fires when all resources have been released"
  },
  {
    "code": "def serialize_upload(name, storage, url):\n    if isinstance(storage, LazyObject):\n        storage._setup()\n        cls = storage._wrapped.__class__\n    else:\n        cls = storage.__class__\n    return signing.dumps({\n        'name': name,\n        'storage': '%s.%s' % (cls.__module__, cls.__name__)\n    }, salt=url)",
    "docstring": "Serialize uploaded file by name and storage. Namespaced by the upload url."
  },
  {
    "code": "def diffsp(self, col: str, serie: \"iterable\", name: str=\"Diff\"):\n        try:\n            d = []\n            for i, row in self.df.iterrows():\n                v = (row[col]*100) / serie[i]\n                d.append(v)\n            self.df[name] = d\n        except Exception as e:\n            self.err(e, self._append, \"Can not diff column from serie\")",
    "docstring": "Add a diff column in percentage from a serie. The serie is \n        an iterable of the same length than the dataframe\n\n        :param col: column to diff\n        :type col: str\n        :param serie: serie to diff from\n        :type serie: iterable\n        :param name: name of the diff col, defaults to \"Diff\"\n        :param name: str, optional\n\n        :example: ``ds.diffp(\"Col 1\", [1, 1, 4], \"New col\")``"
  },
  {
    "code": "def cancel_orders(self, order_ids: List[str]) -> List[str]:\n        orders_to_cancel = order_ids\n        self.log.debug(f'Canceling orders on {self.name}: ids={orders_to_cancel}')\n        cancelled_orders = []\n        if self.dry_run:\n            self.log.warning(f'DRY RUN: Orders cancelled on {self.name}: {orders_to_cancel}')\n            return orders_to_cancel\n        try:\n            if self.has_batch_cancel:\n                self._cancel_orders(orders_to_cancel)\n                cancelled_orders.append(orders_to_cancel)\n                orders_to_cancel.clear()\n            else:\n                for i, order_id in enumerate(orders_to_cancel):\n                    self._cancel_order(order_id)\n                    cancelled_orders.append(order_id)\n                    orders_to_cancel.pop(i)\n        except Exception as e:\n            msg = f'Failed to cancel {len(orders_to_cancel)} orders on {self.name}: ids={orders_to_cancel}'\n            raise self.exception(OrderNotFound, msg, e) from e\n        self.log.info(f'Orders cancelled on {self.name}: ids={cancelled_orders}')\n        return cancelled_orders",
    "docstring": "Cancel multiple orders by a list of IDs."
  },
  {
    "code": "def _copy_selection(self, *event):\n        if react_to_event(self.view, self.view.editor, event):\n            logger.debug(\"copy selection\")\n            global_clipboard.copy(self.model.selection)\n            return True",
    "docstring": "Copies the current selection to the clipboard."
  },
  {
    "code": "def folder(self) -> typing.Union[str, None]:\n        if 'folder' in self.data:\n            return self.data.get('folder')\n        elif self.project_folder:\n            if callable(self.project_folder):\n                return self.project_folder()\n            else:\n                return self.project_folder\n        return None",
    "docstring": "The folder, relative to the project source_directory, where the file\n        resides\n\n        :return:"
  },
  {
    "code": "def get_repository_configuration(id):\n    response = utils.checked_api_call(pnc_api.repositories, 'get_specific', id=id)\n    if response:\n        return response.content",
    "docstring": "Retrieve a specific RepositoryConfiguration"
  },
  {
    "code": "def del_graph(self, graph):\n        g = self.pack(graph)\n        self.sql('del_edge_val_graph', g)\n        self.sql('del_node_val_graph', g)\n        self.sql('del_edge_val_graph', g)\n        self.sql('del_edges_graph', g)\n        self.sql('del_nodes_graph', g)\n        self.sql('del_graph', g)",
    "docstring": "Delete all records to do with the graph"
  },
  {
    "code": "def send_publish(self, mid, topic, payload, qos, retain, dup):\n        self.logger.debug(\"Send PUBLISH\")\n        if self.sock == NC.INVALID_SOCKET:\n            return NC.ERR_NO_CONN\n        return self._do_send_publish(mid, utf8encode(topic), utf8encode(payload), qos, retain, dup)",
    "docstring": "Send PUBLISH."
  },
  {
    "code": "def encode(self, delimiter=';'):\n        try:\n            return delimiter.join([str(f) for f in [\n                self.node_id,\n                self.child_id,\n                int(self.type),\n                self.ack,\n                int(self.sub_type),\n                self.payload,\n            ]]) + '\\n'\n        except ValueError:\n            _LOGGER.error('Error encoding message to gateway')",
    "docstring": "Encode a command string from message."
  },
  {
    "code": "def filter_records(root, head, update, filters=()):\n    root, head, update = freeze(root), freeze(head), freeze(update)\n    for filter_ in filters:\n        root, head, update = filter_(root, head, update)\n    return thaw(root), thaw(head), thaw(update)",
    "docstring": "Apply the filters to the records."
  },
  {
    "code": "def run_spyder(app, options, args):\r\n    main = MainWindow(options)\r\n    try:\r\n        main.setup()\r\n    except BaseException:\r\n        if main.console is not None:\r\n            try:\r\n                main.console.shell.exit_interpreter()\r\n            except BaseException:\r\n                pass\r\n        raise\r\n    main.show()\r\n    main.post_visible_setup()\r\n    if main.console:\r\n        main.console.shell.interpreter.namespace['spy'] = \\\r\n                                                    Spy(app=app, window=main)\r\n    if args:\r\n        for a in args:\r\n            main.open_external_file(a)\r\n    if sys.platform == 'darwin':\r\n        QCoreApplication.setAttribute(Qt.AA_DontShowIconsInMenus, True)\r\n    if running_in_mac_app():\r\n        app.sig_open_external_file.connect(main.open_external_file)\r\n    app.focusChanged.connect(main.change_last_focused_widget)\r\n    if not running_under_pytest():\r\n        app.exec_()\r\n    return main",
    "docstring": "Create and show Spyder's main window\r\n    Start QApplication event loop"
  },
  {
    "code": "def list_datasets(name=None):\n    reg = registry.get_registry(Dataset)\n    if name is not None:\n        class_ = reg[name.lower()]\n        return _REGSITRY_NAME_KWARGS[class_]\n    else:\n        return {\n            dataset_name: _REGSITRY_NAME_KWARGS[class_]\n            for dataset_name, class_ in registry.get_registry(Dataset).items()\n        }",
    "docstring": "Get valid datasets and registered parameters.\n\n    Parameters\n    ----------\n    name : str or None, default None\n        Return names and registered parameters of registered datasets. If name\n        is specified, only registered parameters of the respective dataset are\n        returned.\n\n    Returns\n    -------\n    dict:\n        A dict of all the valid keyword parameters names for the specified\n        dataset. If name is set to None, returns a dict mapping each valid name\n        to its respective keyword parameter dict. The valid names can be\n        plugged in `gluonnlp.model.word_evaluation_model.create(name)`."
  },
  {
    "code": "def sctiks(sc, clkstr):\n    sc = ctypes.c_int(sc)\n    clkstr = stypes.stringToCharP(clkstr)\n    ticks = ctypes.c_double()\n    libspice.sctiks_c(sc, clkstr, ctypes.byref(ticks))\n    return ticks.value",
    "docstring": "Convert a spacecraft clock format string to number of \"ticks\".\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sctiks_c.html\n\n    :param sc: NAIF spacecraft identification code.\n    :type sc: int\n    :param clkstr: Character representation of a spacecraft clock.\n    :type clkstr: str\n    :return: Number of ticks represented by the clock string.\n    :rtype: float"
  },
  {
    "code": "def reference(self, ):\n        tfi = self.get_taskfileinfo_selection()\n        if tfi:\n            self.reftrack.reference(tfi)",
    "docstring": "Reference a file\n\n        :returns: None\n        :rtype: None\n        :raises: None"
  },
  {
    "code": "def get_lists(client):\n    response = client.authenticated_request(client.api.Endpoints.LISTS)\n    return response.json()",
    "docstring": "Gets all the client's lists"
  },
  {
    "code": "def as_dict(self):\n        if not self._is_valid:\n            self.validate()\n        from .converters import to_dict\n        return to_dict(self)",
    "docstring": "Returns the model as a dict"
  },
  {
    "code": "def init_tape(self, string):\n        for char in string:\n            if char not in self.alphabet and not char.isspace() and char != self.EMPTY_SYMBOL:\n                raise RuntimeError('Invalid symbol: \"' + char + '\"')\n        self.check()\n        self.state = self.START_STATE\n        self.head = 0\n        self.tape = {}\n        for i in range(len(string)):\n            symbol = string[i] if not string[i].isspace() else self.EMPTY_SYMBOL\n            self.tape[i] = symbol",
    "docstring": "Init system values."
  },
  {
    "code": "def sha1(s):\n    h = hashlib.new('sha1')\n    h.update(s)\n    return h.hexdigest()",
    "docstring": "Returns a sha1 of the given string"
  },
  {
    "code": "def parse_age(value=None):\n    if not value:\n        return None\n    try:\n        seconds = int(value)\n    except ValueError:\n        return None\n    if seconds < 0:\n        return None\n    try:\n        return timedelta(seconds=seconds)\n    except OverflowError:\n        return None",
    "docstring": "Parses a base-10 integer count of seconds into a timedelta.\n\n    If parsing fails, the return value is `None`.\n\n    :param value: a string consisting of an integer represented in base-10\n    :return: a :class:`datetime.timedelta` object or `None`."
  },
  {
    "code": "def get_arguments():\n    parser = argparse.ArgumentParser(\n        description='Handles bumping of the artifact version')\n    parser.add_argument('--log-config',\n                        '-l',\n                        action='store',\n                        dest='logger_config',\n                        help='The location of the logging config json file',\n                        default='')\n    parser.add_argument('--log-level',\n                        '-L',\n                        help='Provide the log level. Defaults to INFO.',\n                        dest='log_level',\n                        action='store',\n                        default='INFO',\n                        choices=['DEBUG',\n                                 'INFO',\n                                 'WARNING',\n                                 'ERROR',\n                                 'CRITICAL'])\n    parser.add_argument('--major',\n                        help='Bump the major version',\n                        dest='bump_major',\n                        action='store_true',\n                        default=False)\n    parser.add_argument('--minor',\n                        help='Bump the minor version',\n                        dest='bump_minor',\n                        action='store_true',\n                        default=False)\n    parser.add_argument('--patch',\n                        help='Bump the patch version',\n                        dest='bump_patch',\n                        action='store_true',\n                        default=False)\n    parser.add_argument('--version',\n                        help='Set the version',\n                        dest='version',\n                        action='store',\n                        default=False)\n    args = parser.parse_args()\n    return args",
    "docstring": "This get us the cli arguments.\n\n    Returns the args as parsed from the argsparser."
  },
  {
    "code": "def _check_timezone_max_length_attribute(self):\n        possible_max_length = max(map(len, pytz.all_timezones))\n        if self.max_length < possible_max_length:\n            return [\n                checks.Error(\n                    msg=(\n                        \"'max_length' is too short to support all possible \"\n                        \"pytz time zones.\"\n                    ),\n                    hint=(\n                        \"pytz {version}'s longest time zone string has a \"\n                        \"length of {value}, although it is recommended that \"\n                        \"you leave room for longer time zone strings to be \"\n                        \"added in the future.\".format(\n                            version=pytz.VERSION,\n                            value=possible_max_length\n                        )\n                    ),\n                    obj=self,\n                )\n            ]\n        return []",
    "docstring": "Checks that the `max_length` attribute covers all possible pytz\n        timezone lengths."
  },
  {
    "code": "def connect(self, funct):\n        def get_directory():\n            rec = QFileDialog.getExistingDirectory(self,\n                                                   'Path to Recording'\n                                                   ' Directory')\n            if rec == '':\n                return\n            self.setText(rec)\n            funct()\n        self.clicked.connect(get_directory)",
    "docstring": "Call funct when the text was changed.\n\n        Parameters\n        ----------\n        funct : function\n            function that broadcasts a change.\n\n        Notes\n        -----\n        There is something wrong here. When you run this function, it calls\n        for opening a directory three or four times. This is obviously wrong\n        but I don't understand why this happens three times. Traceback did not\n        help."
  },
  {
    "code": "def list_container_services(access_token, subscription_id, resource_group):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/resourcegroups/', resource_group,\n                        '/providers/Microsoft.ContainerService/ContainerServices',\n                        '?api-version=', ACS_API])\n    return do_get(endpoint, access_token)",
    "docstring": "List the container services in a resource group.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n        resource_group (str): Azure resource group name.\n\n    Returns:\n        HTTP response. JSON model."
  },
  {
    "code": "def set_variations(self, variations):\n        if variations is None:\n            variations = ffi.NULL\n        else:\n            variations = _encode_string(variations)\n        cairo.cairo_font_options_set_variations(self._pointer, variations)\n        self._check_status()",
    "docstring": "Sets the OpenType font variations for the font options object.\n\n        Font variations are specified as a string with a format that is similar\n        to the CSS font-variation-settings. The string contains a\n        comma-separated list of axis assignments, which each assignment\n        consists of a 4-character axis name and a value, separated by\n        whitespace and optional equals sign.\n\n        :param variations: the new font variations, or ``None``.\n\n        *New in cairo 1.16.*\n\n        *New in cairocffi 0.9.*"
  },
  {
    "code": "def pca(U, centre=False):\n    if centre:\n        C = np.mean(U, axis=1, keepdims=True)\n        U = U - C\n    else:\n        C = None\n    B, S, _ = np.linalg.svd(U, full_matrices=False, compute_uv=True)\n    return B, S**2, C",
    "docstring": "Compute the PCA basis for columns of input array `U`.\n\n    Parameters\n    ----------\n    U : array_like\n      2D data array with rows corresponding to different variables and\n      columns corresponding to different observations\n    center : bool, optional (default False)\n      Flag indicating whether to centre data\n\n    Returns\n    -------\n    B : ndarray\n      A 2D array representing the PCA basis; each column is a PCA\n      component.\n      B.T is the analysis transform into the PCA representation, and B\n      is the corresponding synthesis transform\n    S : ndarray\n      The eigenvalues of the PCA components\n    C : ndarray or None\n      None if centering is disabled, otherwise the mean of the data\n      matrix subtracted in performing the centering"
  },
  {
    "code": "def add_bonus(worker_dict):\n        \" Adds DB-logged worker bonus to worker list data \"\n        try:\n            unique_id = '{}:{}'.format(worker_dict['workerId'], worker_dict['assignmentId'])\n            worker = Participant.query.filter(\n                Participant.uniqueid == unique_id).one()\n            worker_dict['bonus'] = worker.bonus\n        except sa.exc.InvalidRequestError:\n            worker_dict['bonus'] = 'N/A'\n        return worker_dict",
    "docstring": "Adds DB-logged worker bonus to worker list data"
  },
  {
    "code": "def _pop(self, block=True, timeout=None, left=False):\n        item  = None\n        timer = None\n        deque = self._deque\n        empty = IndexError('pop from an empty deque')\n        if block is False:\n            if len(self._deque) > 0:\n                item = deque.popleft() if left else deque.pop()\n            else:\n                raise empty\n        else:\n            try:\n                if timeout is not None:\n                    timer = gevent.Timeout(timeout, empty)\n                    timer.start()\n                while True:\n                    self.notEmpty.wait()\n                    if len(deque) > 0:\n                        item = deque.popleft() if left else deque.pop()\n                        break\n            finally:\n                if timer is not None:\n                    timer.cancel()\n        if len(deque) == 0:\n            self.notEmpty.clear()\n        return item",
    "docstring": "Removes and returns the an item from this GeventDeque.\n\n        This is an internal method, called by the public methods\n        pop() and popleft()."
  },
  {
    "code": "def get_stream(self, stream):\n        path = '/archive/{}/streams/{}'.format(self._instance, stream)\n        response = self._client.get_proto(path=path)\n        message = archive_pb2.StreamInfo()\n        message.ParseFromString(response.content)\n        return Stream(message)",
    "docstring": "Gets a single stream.\n\n        :param str stream: The name of the stream.\n        :rtype: .Stream"
  },
  {
    "code": "def strtobytes(input, encoding):\n    py_version = sys.version_info[0]\n    if py_version >= 3:\n        return _strtobytes_py3(input, encoding)\n    return _strtobytes_py2(input, encoding)",
    "docstring": "Take a str and transform it into a byte array."
  },
  {
    "code": "def newDocFragment(self):\n        ret = libxml2mod.xmlNewDocFragment(self._o)\n        if ret is None:raise treeError('xmlNewDocFragment() failed')\n        __tmp = xmlNode(_obj=ret)\n        return __tmp",
    "docstring": "Creation of a new Fragment node."
  },
  {
    "code": "def find_outliers(group, delta):\n    with_pos = sorted([pair for pair in enumerate(group)], key=lambda p: p[1])\n    outliers_start = outliers_end = -1\n    for i in range(0, len(with_pos) - 1):\n        cur = with_pos[i][1]\n        nex = with_pos[i + 1][1]\n        if nex - cur > delta:\n            if i < (len(with_pos) - i):\n                outliers_start, outliers_end = 0, i + 1\n            else:\n                outliers_start, outliers_end = i + 1, len(with_pos)\n            break\n    if outliers_start != -1:\n        return [with_pos[i][0] for i in range(outliers_start, outliers_end)]\n    else:\n        return []",
    "docstring": "given a list of values, find those that are apart from the rest by\n    `delta`. the indexes for the outliers is returned, if any.\n\n    examples:\n\n    values = [100, 6, 7, 8, 9, 10, 150]\n    find_outliers(values, 5) -> [0, 6]\n\n    values = [5, 6, 5, 4, 5]\n    find_outliers(values, 3) -> []"
  },
  {
    "code": "def stack1d(*points):\n    result = np.empty((2, len(points)), order=\"F\")\n    for index, point in enumerate(points):\n        result[:, index] = point\n    return result",
    "docstring": "Fill out the columns of matrix with a series of points.\n\n    This is because ``np.hstack()`` will just make another 1D vector\n    out of them and ``np.vstack()`` will put them in the rows.\n\n    Args:\n        points (Tuple[numpy.ndarray, ...]): Tuple of 1D points (i.e.\n            arrays with shape ``(2,)``.\n\n    Returns:\n        numpy.ndarray: The array with each point in ``points`` as its\n        columns."
  },
  {
    "code": "def append(self, other):\n        if not isinstance(other,StarPopulation):\n            raise TypeError('Only StarPopulation objects can be appended to a StarPopulation.')\n        if not np.all(self.stars.columns == other.stars.columns):\n            raise ValueError('Two populations must have same columns to combine them.')\n        if len(self.constraints) > 0:\n            logging.warning('All constraints are cleared when appending another population.')\n        self.stars = pd.concat((self.stars, other.stars))\n        if self.orbpop is not None and other.orbpop is not None:\n            self.orbpop = self.orbpop + other.orbpop",
    "docstring": "Appends stars from another StarPopulations, in place.\n\n        :param other:\n            Another :class:`StarPopulation`; must have same columns as ``self``."
  },
  {
    "code": "def _add_property(self, name, default_value):\n        name = str(name)\n        self._properties[name] = default_value",
    "docstring": "Add a device property with a given default value.\n\n        Args:\n            name (str): The name of the property to add\n            default_value (int, bool): The value of the property"
  },
  {
    "code": "def dst(self, dt):\n        tt = _localtime(_mktime((dt.year, dt.month, dt.day,\n                 dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))\n        if tt.tm_isdst > 0: return _dstdiff\n        return _zero",
    "docstring": "datetime -> DST offset in minutes east of UTC."
  },
  {
    "code": "def is_invalid_operation(self, callsign, timestamp=datetime.utcnow().replace(tzinfo=UTC)):\n        callsign = callsign.strip().upper()\n        if self._lookuptype == \"clublogxml\":\n            return self._check_inv_operation_for_date(callsign, timestamp, self._invalid_operations, self._invalid_operations_index)\n        elif self._lookuptype == \"redis\":\n            data_dict, index = self._get_dicts_from_redis(\"_inv_op_\", \"_inv_op_index_\", self._redis_prefix, callsign)\n            return self._check_inv_operation_for_date(callsign, timestamp, data_dict, index)\n        raise KeyError",
    "docstring": "Returns True if an operations is known as invalid\n\n        Args:\n            callsign (string): Amateur Radio callsign\n            timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)\n\n        Returns:\n            bool: True if a record exists for this callsign (at the given time)\n\n        Raises:\n            KeyError: No matching callsign found\n            APIKeyMissingError: API Key for Clublog missing or incorrect\n\n        Example:\n           The following code checks the Clublog XML database if the operation is valid for two dates.\n\n           >>> from pyhamtools import LookupLib\n           >>> from datetime import datetime\n           >>> import pytz\n           >>> my_lookuplib = LookupLib(lookuptype=\"clublogxml\", apikey=\"myapikey\")\n           >>> print my_lookuplib.is_invalid_operation(\"5W1CFN\")\n           True\n           >>> try:\n           >>>   timestamp = datetime(year=2012, month=1, day=31).replace(tzinfo=pytz.UTC)\n           >>>   my_lookuplib.is_invalid_operation(\"5W1CFN\", timestamp)\n           >>> except KeyError:\n           >>>   print \"Seems to be invalid operation before 31.1.2012\"\n           Seems to be an invalid operation before 31.1.2012\n\n        Note:\n            This method is available for\n\n            - clublogxml\n            - redis"
  },
  {
    "code": "def get_custom_values(self, key):\n        self._handled.add(key)\n        return self._lookup[key]",
    "docstring": "Return a set of values for the given customParameter name."
  },
  {
    "code": "def query(self, query, media=None, year=None, fields=None, extended=None, **kwargs):\n        if not media:\n            warnings.warn(\n                \"\\\"media\\\" parameter is now required on the Trakt['search'].query() method\",\n                DeprecationWarning, stacklevel=2\n            )\n        if fields and not media:\n            raise ValueError('\"fields\" can only be used when the \"media\" parameter is defined')\n        query = {\n            'query': query\n        }\n        if year:\n            query['year'] = year\n        if fields:\n            query['fields'] = fields\n        if extended:\n            query['extended'] = extended\n        if isinstance(media, list):\n            media = ','.join(media)\n        response = self.http.get(\n            params=[media],\n            query=query\n        )\n        items = self.get_data(response, **kwargs)\n        if isinstance(items, requests.Response):\n            return items\n        if items is not None:\n            return SearchMapper.process_many(self.client, items)\n        return None",
    "docstring": "Search by titles, descriptions, translated titles, aliases, and people.\n\n        **Note:** Results are ordered by the most relevant score.\n\n        :param query: Search title or description\n        :type query: :class:`~python:str`\n\n        :param media: Desired media type (or :code:`None` to return all matching items)\n\n            **Possible values:**\n             - :code:`movie`\n             - :code:`show`\n             - :code:`episode`\n             - :code:`person`\n             - :code:`list`\n\n        :type media: :class:`~python:str` or :class:`~python:list` of :class:`~python:str`\n\n        :param year: Desired media year (or :code:`None` to return all matching items)\n        :type year: :class:`~python:str` or :class:`~python:int`\n\n        :param fields: Fields to search for :code:`query` (or :code:`None` to search all fields)\n        :type fields: :class:`~python:str` or :class:`~python:list`\n\n        :param extended: Level of information to include in response\n\n            **Possible values:**\n             - :code:`None`: Minimal (e.g. title, year, ids) **(default)**\n             - :code:`full`: Complete\n\n        :type extended: :class:`~python:str`\n\n        :param kwargs: Extra request options\n        :type kwargs: :class:`~python:dict`\n\n        :return: Results\n        :rtype: :class:`~python:list` of :class:`trakt.objects.media.Media`"
  },
  {
    "code": "def make_gym_env(name,\n                 rl_env_max_episode_steps=-1,\n                 maxskip_env=False,\n                 rendered_env=False,\n                 rendered_env_resize_to=None,\n                 sticky_actions=False):\n  env = gym.make(name)\n  return gym_env_wrapper(env, rl_env_max_episode_steps, maxskip_env,\n                         rendered_env, rendered_env_resize_to, sticky_actions)",
    "docstring": "Create a gym env optionally with a time limit and maxskip wrapper.\n\n  NOTE: The returned env may already be wrapped with TimeLimit!\n\n  Args:\n    name: `str` - base name of the gym env to make.\n    rl_env_max_episode_steps: `int` or None - Using any value < 0 returns the\n      env as-in, otherwise we impose the requested timelimit. Setting this to\n      None returns a wrapped env that doesn't have a step limit.\n    maxskip_env: whether to also use MaxAndSkip wrapper before time limit.\n    rendered_env: whether to force render for observations. Use this for\n      environments that are not natively rendering the scene for observations.\n    rendered_env_resize_to: a list of [height, width] to change the original\n      resolution of the native environment render.\n    sticky_actions: whether to use sticky_actions before MaxAndSkip wrapper.\n\n  Returns:\n    An instance of `gym.Env` or `gym.Wrapper`."
  },
  {
    "code": "def migrate(self, migrations_package_name, up_to=9999):\n        from .migrations import MigrationHistory\n        logger = logging.getLogger('migrations')\n        applied_migrations = self._get_applied_migrations(migrations_package_name)\n        modules = import_submodules(migrations_package_name)\n        unapplied_migrations = set(modules.keys()) - applied_migrations\n        for name in sorted(unapplied_migrations):\n            logger.info('Applying migration %s...', name)\n            for operation in modules[name].operations:\n                operation.apply(self)\n            self.insert([MigrationHistory(package_name=migrations_package_name, module_name=name, applied=datetime.date.today())])\n            if int(name[:4]) >= up_to:\n                break",
    "docstring": "Executes schema migrations.\n\n        - `migrations_package_name` - fully qualified name of the Python package\n          containing the migrations.\n        - `up_to` - number of the last migration to apply."
  },
  {
    "code": "def limitsSql(startIndex=0, maxResults=0):\n    if startIndex and maxResults:\n        return \" LIMIT {}, {}\".format(startIndex, maxResults)\n    elif startIndex:\n        raise Exception(\"startIndex was provided, but maxResults was not\")\n    elif maxResults:\n        return \" LIMIT {}\".format(maxResults)\n    else:\n        return \"\"",
    "docstring": "Construct a SQL LIMIT clause"
  },
  {
    "code": "def _get_network_vswitch_map_by_port_id(self, port_id):\n        for network_id, vswitch in six.iteritems(self._network_vswitch_map):\n            if port_id in vswitch['ports']:\n                return (network_id, vswitch)\n        return (None, None)",
    "docstring": "Get the vswitch name for the received port id."
  },
  {
    "code": "def native(self, writeAccess=False, isolation_level=None):\n        host = self.database().writeHost() if writeAccess else self.database().host()\n        conn = self.open(writeAccess=writeAccess)\n        try:\n            if isolation_level is not None:\n                if conn.isolation_level == isolation_level:\n                    isolation_level = None\n                else:\n                    conn.set_isolation_level(isolation_level)\n            yield conn\n        except Exception:\n            if self._closed(conn):\n                conn = None\n                self.close()\n            else:\n                conn = self._rollback(conn)\n            raise\n        else:\n            if not self._closed(conn):\n                self._commit(conn)\n        finally:\n            if conn is not None and not self._closed(conn):\n                if isolation_level is not None:\n                    conn.set_isolation_level(isolation_level)\n                self.__pool[host].put(conn)",
    "docstring": "Opens a new database connection to the database defined\n        by the inputted database.\n\n        :return     <varaint> native connection"
  },
  {
    "code": "def template(args):\n    \" Add or remove templates from site. \"\n    site = Site(args.PATH)\n    if args.ACTION == \"add\":\n        return site.add_template(args.TEMPLATE)\n    return site.remove_template(args.TEMPLATE)",
    "docstring": "Add or remove templates from site."
  },
  {
    "code": "def remove(self, point, node=None):\n        if not self:\n            return\n        if self.should_remove(point, node):\n            return self._remove(point)\n        if self.left and self.left.should_remove(point, node):\n            self.left = self.left._remove(point)\n        elif self.right and self.right.should_remove(point, node):\n            self.right = self.right._remove(point)\n        if point[self.axis] <= self.data[self.axis]:\n            if self.left:\n                self.left = self.left.remove(point, node)\n        if point[self.axis] >= self.data[self.axis]:\n            if self.right:\n                self.right = self.right.remove(point, node)\n        return self",
    "docstring": "Removes the node with the given point from the tree\n\n        Returns the new root node of the (sub)tree.\n\n        If there are multiple points matching \"point\", only one is removed. The\n        optional \"node\" parameter is used for checking the identity, once the\n        removeal candidate is decided."
  },
  {
    "code": "def setnode(delta, graph, node, exists):\n    delta.setdefault(graph, {}).setdefault('nodes', {})[node] = bool(exists)",
    "docstring": "Change a delta to say that a node was created or deleted"
  },
  {
    "code": "def layer_norm(x,\n               filters=None,\n               epsilon=1e-6,\n               name=None,\n               reuse=None,\n               layer_collection=None):\n  if filters is None:\n    filters = shape_list(x)[-1]\n  with tf.variable_scope(\n      name, default_name=\"layer_norm\", values=[x], reuse=reuse):\n    scale, bias = layer_norm_vars(filters)\n    return layer_norm_compute(x, epsilon, scale, bias,\n                              layer_collection=layer_collection)",
    "docstring": "Layer normalize the tensor x, averaging over the last dimension."
  },
  {
    "code": "def enable(\n        self, cmd=\"enable\", pattern=r\"(ssword|User Name)\", re_flags=re.IGNORECASE\n    ):\n        output = \"\"\n        if not self.check_enable_mode():\n            count = 4\n            i = 1\n            while i < count:\n                self.write_channel(self.normalize_cmd(cmd))\n                new_data = self.read_until_prompt_or_pattern(\n                    pattern=pattern, re_flags=re_flags\n                )\n                output += new_data\n                if \"User Name\" in new_data:\n                    self.write_channel(self.normalize_cmd(self.username))\n                    new_data = self.read_until_prompt_or_pattern(\n                        pattern=pattern, re_flags=re_flags\n                    )\n                    output += new_data\n                if \"ssword\" in new_data:\n                    self.write_channel(self.normalize_cmd(self.secret))\n                    output += self.read_until_prompt()\n                    return output\n                time.sleep(1)\n                i += 1\n        if not self.check_enable_mode():\n            msg = (\n                \"Failed to enter enable mode. Please ensure you pass \"\n                \"the 'secret' argument to ConnectHandler.\"\n            )\n            raise ValueError(msg)",
    "docstring": "Enter enable mode.\n        With RADIUS can prompt for User Name\n        SSH@Lab-ICX7250>en\n        User Name:service_netmiko\n        Password:\n        SSH@Lab-ICX7250#"
  },
  {
    "code": "def delete(self):\n        res = requests.delete(url=self.record_url, headers=HEADERS, verify=False)\n        if res.status_code == 204:\n            return {}\n        return res.json()",
    "docstring": "Deletes the record."
  },
  {
    "code": "def get_special_folder(self, name):\n        name = name if \\\n            isinstance(name, OneDriveWellKnowFolderNames) \\\n            else OneDriveWellKnowFolderNames(name.lower())\n        name = name.value\n        if self.object_id:\n            url = self.build_url(\n                self._endpoints.get('get_special').format(id=self.object_id,\n                                                          name=name))\n        else:\n            url = self.build_url(\n                self._endpoints.get('get_special_default').format(name=name))\n        response = self.con.get(url)\n        if not response:\n            return None\n        data = response.json()\n        return self._classifier(data)(parent=self,\n                                      **{self._cloud_data_key: data})",
    "docstring": "Returns the specified Special Folder\n\n        :return: a special Folder\n        :rtype: drive.Folder"
  },
  {
    "code": "def add_passwords(self, identifiers, passwords):\n        if not isinstance(identifiers, list):\n            raise TypeError(\"identifiers can only be an instance of type list\")\n        for a in identifiers[:10]:\n            if not isinstance(a, basestring):\n                raise TypeError(\n                        \"array can only contain objects of type basestring\")\n        if not isinstance(passwords, list):\n            raise TypeError(\"passwords can only be an instance of type list\")\n        for a in passwords[:10]:\n            if not isinstance(a, basestring):\n                raise TypeError(\n                        \"array can only contain objects of type basestring\")\n        self._call(\"addPasswords\",\n                     in_p=[identifiers, passwords])",
    "docstring": "Adds a list of passwords required to import or export encrypted virtual\n        machines.\n\n        in identifiers of type str\n            List of identifiers.\n\n        in passwords of type str\n            List of matching passwords."
  },
  {
    "code": "def mutate(self, node, index):\n        assert index < len(OFFSETS), 'received count with no associated offset'\n        assert isinstance(node, parso.python.tree.Number)\n        val = eval(node.value) + OFFSETS[index]\n        return parso.python.tree.Number(' ' + str(val), node.start_pos)",
    "docstring": "Modify the numeric value on `node`."
  },
  {
    "code": "def delete_user_role(self, user, role):\n        self.project_service.set_auth(self._token_project)\n        self.project_service.delete_user_role(user, role)",
    "docstring": "Remove role from given user.\n\n        Args:\n            user (string): User name.\n            role (string): Role to remove.\n\n        Raises:\n            requests.HTTPError on failure."
  },
  {
    "code": "def rt(nu, size=None):\n    return rnormal(0, 1, size) / np.sqrt(rchi2(nu, size) / nu)",
    "docstring": "Student's t random variates."
  },
  {
    "code": "def _get_packet(self, socket):\n        data, (ip, port) = socket.recvfrom(self._buffer_size)\n        packet, remainder = self._unpack(data)\n        self.inbox.put((ip, port, packet))\n        self.new_packet.set()\n        self.debug(u\"RX: {}\".format(packet))\n        if packet.header.sequence_number is not None:\n            self._send_ack(ip, port, packet)\n        ack_seq = packet.header.ack_sequence_number\n        if ack_seq is not None:\n            with self._seq_ack_lock:\n                if ack_seq in self._seq_ack:\n                    self.debug(u\"Seq {} got acked\".format(ack_seq))\n                    self._seq_ack.remove(ack_seq)\n        return packet",
    "docstring": "Read packet and put it into inbox\n\n        :param socket: Socket to read from\n        :type socket: socket.socket\n        :return: Read packet\n        :rtype: APPMessage"
  },
  {
    "code": "def find_by_name(self, term: str, include_placeholders: bool = False) -> List[Account]:\n        query = (\n            self.query\n            .filter(Account.name.like('%' + term + '%'))\n            .order_by(Account.name)\n        )\n        if not include_placeholders:\n            query = query.filter(Account.placeholder == 0)\n        return query.all()",
    "docstring": "Search for account by part of the name"
  },
  {
    "code": "def _prerun(self):\n        self.check_required_params()\n        self._set_status(\"RUNNING\")\n        logger.debug(\n            \"{}.PreRun: {}[{}]: running...\".format(\n                self.__class__.__name__, self.__class__.path, self.uuid\n            ),\n            extra=dict(\n                kmsg=Message(\n                    self.uuid, entrypoint=self.__class__.path,\n                    params=self.params\n                ).dump()\n            )\n        )\n        return self.prerun()",
    "docstring": "To execute before running message"
  },
  {
    "code": "def set_substitution(self, what, rep):\n        if rep is None:\n            if what in self._subs:\n                del self._subs[what]\n        self._subs[what] = rep",
    "docstring": "Set a substitution.\n\n        Equivalent to ``! sub`` in RiveScript code.\n\n        :param str what: The original text to replace.\n        :param str rep: The text to replace it with.\n            Set this to ``None`` to delete the substitution."
  },
  {
    "code": "def entrez_sets_of_results(url, retstart=False, retmax=False, count=False) -> Optional[List[requests.Response]]:\n    if not retstart:\n        retstart = 0\n    if not retmax:\n        retmax = 500\n    if not count:\n        count = retmax\n    retmax = 500\n    while retstart < count:\n        diff = count - retstart\n        if diff < 500:\n            retmax = diff\n        _url = url + f'&retstart={retstart}&retmax={retmax}'\n        resp = entrez_try_get_multiple_times(_url)\n        if resp is None:\n            return\n        retstart += retmax\n        yield resp",
    "docstring": "Gets sets of results back from Entrez.\n\n    Entrez can only return 500 results at a time. This creates a generator that gets results by incrementing\n    retstart and retmax.\n\n    Parameters\n    ----------\n    url : str\n        The Entrez API url to use.\n    retstart : int\n        Return values starting at this index.\n    retmax : int\n        Return at most this number of values.\n    count : int\n        The number of results returned by EQuery.\n\n    Yields\n    ------\n    requests.Response"
  },
  {
    "code": "def _set_lim_and_transforms(self):\n        LambertAxes._set_lim_and_transforms(self)\n        yaxis_stretch = Affine2D().scale(4 * self.horizon, 1.0)\n        yaxis_stretch = yaxis_stretch.translate(-self.horizon, 0.0)\n        yaxis_space = Affine2D().scale(1.0, 1.1)\n        self._yaxis_transform = \\\n            yaxis_stretch + \\\n            self.transData\n        yaxis_text_base = \\\n            yaxis_stretch + \\\n            self.transProjection + \\\n            (yaxis_space + \\\n             self.transAffine + \\\n             self.transAxes)\n        self._yaxis_text1_transform = \\\n            yaxis_text_base + \\\n            Affine2D().translate(-8.0, 0.0)\n        self._yaxis_text2_transform = \\\n            yaxis_text_base + \\\n            Affine2D().translate(8.0, 0.0)",
    "docstring": "Setup the key transforms for the axes."
  },
  {
    "code": "def children_as_pi(self, squash=False):\n        probs = self.child_N\n        if squash:\n            probs = probs ** .98\n        sum_probs = np.sum(probs)\n        if sum_probs == 0:\n            return probs\n        return probs / np.sum(probs)",
    "docstring": "Returns the child visit counts as a probability distribution, pi\n        If squash is true, exponentiate the probabilities by a temperature\n        slightly larger than unity to encourage diversity in early play and\n        hopefully to move away from 3-3s"
  },
  {
    "code": "def emit(self, record):\n        try:\n            QgsMessageLog.logMessage(record.getMessage(), 'InaSAFE', 0)\n        except MemoryError:\n            message = tr(\n                'Due to memory limitations on this machine, InaSAFE can not '\n                'handle the full log')\n            print(message)\n            QgsMessageLog.logMessage(message, 'InaSAFE', 0)",
    "docstring": "Try to log the message to QGIS if available, otherwise do nothing.\n\n        :param record: logging record containing whatever info needs to be\n                logged."
  },
  {
    "code": "def _pdb_frame(self):\n        if self._pdb_obj is not None and self._pdb_obj.curframe is not None:\n            return self._pdb_obj.curframe",
    "docstring": "Return current Pdb frame if there is any"
  },
  {
    "code": "def say_tmp_filepath(\n    text               = None,\n    preference_program = \"festival\"\n    ):\n    filepath = shijian.tmp_filepath() + \".wav\"\n    say(\n        text               = text,\n        preference_program = preference_program,\n        filepath           = filepath\n    )\n    return filepath",
    "docstring": "Say specified text to a temporary file and return the filepath."
  },
  {
    "code": "def gdal_rasterize(src, dst, options):\n    out = gdal.Rasterize(dst, src, options=gdal.RasterizeOptions(**options))\n    out = None",
    "docstring": "a simple wrapper for gdal.Rasterize\n\n    Parameters\n    ----------\n    src: str or :osgeo:class:`ogr.DataSource`\n        the input data set\n    dst: str\n        the output data set\n    options: dict\n        additional parameters passed to gdal.Rasterize; see :osgeo:func:`gdal.RasterizeOptions`\n\n    Returns\n    -------"
  },
  {
    "code": "def layout_asides(self, block, context, frag, view_name, aside_frag_fns):\n        result = Fragment(frag.content)\n        result.add_fragment_resources(frag)\n        for aside, aside_fn in aside_frag_fns:\n            aside_frag = self.wrap_aside(block, aside, view_name, aside_fn(block, context), context)\n            aside.save()\n            result.add_content(aside_frag.content)\n            result.add_fragment_resources(aside_frag)\n        return result",
    "docstring": "Execute and layout the aside_frags wrt the block's frag. Runtimes should feel free to override this\n        method to control execution, place, and style the asides appropriately for their application\n\n        This default method appends the aside_frags after frag. If you override this, you must\n        call wrap_aside around each aside as per this function.\n\n        Args:\n            block (XBlock): the block being rendered\n            frag (html): The result from rendering the block\n            aside_frag_fns list((aside, aside_fn)): The asides and closures for rendering to call"
  },
  {
    "code": "def __get_factory_with_context(self, factory_name):\n        factory = self.__factories.get(factory_name)\n        if factory is None:\n            raise TypeError(\"Unknown factory '{0}'\".format(factory_name))\n        factory_context = getattr(\n            factory, constants.IPOPO_FACTORY_CONTEXT, None\n        )\n        if factory_context is None:\n            raise TypeError(\n                \"Factory context missing in '{0}'\".format(factory_name)\n            )\n        return factory, factory_context",
    "docstring": "Retrieves the factory registered with the given and its factory context\n\n        :param factory_name: The name of the factory\n        :return: A (factory, context) tuple\n        :raise TypeError: Unknown factory, or factory not manipulated"
  },
  {
    "code": "def _load_settings(self):\n        if self._autosettings_path == None: return\n        gui_settings_dir = _os.path.join(_cwd, 'egg_settings')\n        path = _os.path.join(gui_settings_dir, self._autosettings_path)\n        if not _os.path.exists(path): return\n        settings = _g.QtCore.QSettings(path, _g.QtCore.QSettings.IniFormat)\n        if settings.contains('State') and hasattr_safe(self._window, \"restoreState\"):    \n            x = settings.value('State')\n            if hasattr(x, \"toByteArray\"): x = x.toByteArray()            \n            self._window.restoreState(x)\n        if settings.contains('Geometry'): \n            x = settings.value('Geometry')\n            if hasattr(x, \"toByteArray\"): x = x.toByteArray()\n            self._window.restoreGeometry(x)",
    "docstring": "Loads all the parameters from a databox text file. If path=None,\n        loads from self._autosettings_path."
  },
  {
    "code": "def show_ipsecpolicy(self, ipsecpolicy, **_params):\n        return self.get(self.ipsecpolicy_path % (ipsecpolicy), params=_params)",
    "docstring": "Fetches information of a specific IPsecPolicy."
  },
  {
    "code": "def reset(self, force):\n        client = self.create_client()\n        bucket = client.lookup_bucket(self.bucket_name)\n        if bucket is not None:\n            if not force:\n                self._log.error(\"Bucket already exists, aborting.\")\n                raise ExistingBackendError\n            self._log.info(\"Bucket already exists, deleting all content.\")\n            for blob in bucket.list_blobs():\n                self._log.info(\"Deleting %s ...\" % blob.name)\n                bucket.delete_blob(blob.name)\n        else:\n            client.create_bucket(self.bucket_name)",
    "docstring": "Connect to the assigned bucket or create if needed. Clear all the blobs inside."
  },
  {
    "code": "def change_ref(self, r0=None, lmax=None):\n        if lmax is None:\n            lmax = self.lmax\n        clm = self.pad(lmax)\n        if r0 is not None and r0 != self.r0:\n            for l in _np.arange(lmax+1):\n                clm.coeffs[:, l, :l+1] *= (self.r0 / r0)**(l+2)\n                if self.errors is not None:\n                    clm.errors[:, l, :l+1] *= (self.r0 / r0)**(l+2)\n            clm.r0 = r0\n        return clm",
    "docstring": "Return a new SHMagCoeffs class instance with a different reference r0.\n\n        Usage\n        -----\n        clm = x.change_ref([r0, lmax])\n\n        Returns\n        -------\n        clm : SHMagCoeffs class instance.\n\n        Parameters\n        ----------\n        r0 : float, optional, default = self.r0\n            The reference radius of the spherical harmonic coefficients.\n        lmax : int, optional, default = self.lmax\n            Maximum spherical harmonic degree to output.\n\n        Description\n        -----------\n        This method returns a new class instance of the magnetic potential,\n        but using a difference reference r0. When changing the reference\n        radius r0, the spherical harmonic coefficients will be upward or\n        downward continued under the assumption that the reference radius is\n        exterior to the body."
  },
  {
    "code": "def str_to_list(\n    input_str,\n    item_converter=lambda x: x,\n    item_separator=',',\n    list_to_collection_converter=None,\n):\n    if not isinstance(input_str, six.string_types):\n        raise ValueError(input_str)\n    input_str = str_quote_stripper(input_str)\n    result = [\n        item_converter(x.strip())\n        for x in input_str.split(item_separator) if x.strip()\n    ]\n    if list_to_collection_converter is not None:\n        return list_to_collection_converter(result)\n    return result",
    "docstring": "a conversion function for list"
  },
  {
    "code": "def fit(self, y, **kwargs):\n        if y.ndim > 1:\n            raise YellowbrickValueError(\"y needs to be an array or Series with one dimension\") \n        if self.target is None:\n            self.target = 'Frequency'\n        self.draw(y)\n        return self",
    "docstring": "Sets up y for the histogram and checks to\n        ensure that ``y`` is of the correct data type.\n        Fit calls draw.\n\n        Parameters\n        ----------\n        y : an array of one dimension or a pandas Series\n\n        kwargs : dict\n            keyword arguments passed to scikit-learn API."
  },
  {
    "code": "def tospark(self, engine=None):\n        from thunder.series.readers import fromarray\n        if self.mode == 'spark':\n            logging.getLogger('thunder').warn('images already in local mode')\n            pass\n        if engine is None:\n            raise ValueError('Must provide SparkContext')\n        return fromarray(self.toarray(), index=self.index, labels=self.labels, engine=engine)",
    "docstring": "Convert to spark mode."
  },
  {
    "code": "def get_throttled_by_consumed_read_percent(\n        table_name, lookback_window_start=15, lookback_period=5):\n    try:\n        metrics1 = __get_aws_metric(\n            table_name,\n            lookback_window_start,\n            lookback_period,\n            'ConsumedReadCapacityUnits')\n        metrics2 = __get_aws_metric(\n            table_name,\n            lookback_window_start,\n            lookback_period,\n            'ReadThrottleEvents')\n    except BotoServerError:\n        raise\n    if metrics1 and metrics2:\n        lookback_seconds = lookback_period * 60\n        throttled_by_consumed_read_percent = (\n            (\n                (float(metrics2[0]['Sum']) / float(lookback_seconds)) /\n                (float(metrics1[0]['Sum']) / float(lookback_seconds))\n            ) * 100)\n    else:\n        throttled_by_consumed_read_percent = 0\n    logger.info('{0} - Throttled read percent by consumption: {1:.2f}%'.format(\n        table_name, throttled_by_consumed_read_percent))\n    return throttled_by_consumed_read_percent",
    "docstring": "Returns the number of throttled read events in percent of consumption\n\n    :type table_name: str\n    :param table_name: Name of the DynamoDB table\n    :type lookback_window_start: int\n    :param lookback_window_start: Relative start time for the CloudWatch metric\n    :type lookback_period: int\n    :param lookback_period: Number of minutes to look at\n    :returns: float -- Percent of throttled read events by consumption"
  },
  {
    "code": "def _output_file_data(self, outfp, blocksize, ino):\n        log_block_size = self.pvd.logical_block_size()\n        outfp.seek(ino.extent_location() * log_block_size)\n        tmp_start = outfp.tell()\n        with inode.InodeOpenData(ino, log_block_size) as (data_fp, data_len):\n            utils.copy_data(data_len, blocksize, data_fp, outfp)\n            utils.zero_pad(outfp, data_len, log_block_size)\n        if self._track_writes:\n            end = outfp.tell()\n            bisect.insort_left(self._write_check_list, self._WriteRange(tmp_start, end - 1))\n        if ino.boot_info_table is not None:\n            old = outfp.tell()\n            outfp.seek(tmp_start + 8)\n            self._outfp_write_with_check(outfp, ino.boot_info_table.record(),\n                                         enable_overwrite_check=False)\n            outfp.seek(old)\n        return outfp.tell() - tmp_start",
    "docstring": "Internal method to write a directory record entry out.\n\n        Parameters:\n         outfp - The file object to write the data to.\n         blocksize - The blocksize to use when writing the data out.\n         ino - The Inode to write.\n        Returns:\n         The total number of bytes written out."
  },
  {
    "code": "def hline(self, x, y, width, color):\n        self.rect(x, y, width, 1, color, fill=True)",
    "docstring": "Draw a horizontal line up to a given length."
  },
  {
    "code": "def _load_config(self, path):\n        p = os.path.abspath(os.path.expanduser(path))\n        logger.debug('Loading configuration from: %s', p)\n        return read_json_file(p)",
    "docstring": "Load configuration from JSON\n\n        :param path: path to the JSON config file\n        :type path: str\n        :return: config dictionary\n        :rtype: dict"
  },
  {
    "code": "def resample(\n        self,\n        rule: Union[str, int] = \"1s\",\n        max_workers: int = 4,\n    ) -> \"Traffic\":\n        with ProcessPoolExecutor(max_workers=max_workers) as executor:\n            cumul = []\n            tasks = {\n                executor.submit(flight.resample, rule): flight\n                for flight in self\n            }\n            for future in tqdm(as_completed(tasks), total=len(tasks)):\n                cumul.append(future.result())\n        return self.__class__.from_flights(cumul)",
    "docstring": "Resamples all trajectories, flight by flight.\n\n        `rule` defines the desired sample rate (default: 1s)"
  },
  {
    "code": "def check_empty_response(self, orig_request, method_config, start_response):\n    response_config = method_config.get('response', {}).get('body')\n    if response_config == 'empty':\n      cors_handler = self._create_cors_handler(orig_request)\n      return util.send_wsgi_no_content_response(start_response, cors_handler)",
    "docstring": "If the response from the backend is empty, return a HTTP 204 No Content.\n\n    Args:\n      orig_request: An ApiRequest, the original request from the user.\n      method_config: A dict, the API config of the method to be called.\n      start_response: A function with semantics defined in PEP-333.\n\n    Returns:\n      If the backend response was empty, this returns a string containing the\n      response body that should be returned to the user.  If the backend\n      response wasn't empty, this returns None, indicating that we should not\n      exit early with a 204."
  },
  {
    "code": "def item_details(item_id, lang=\"en\"):\n    params = {\"item_id\": item_id, \"lang\": lang}\n    cache_name = \"item_details.%(item_id)s.%(lang)s.json\" % params\n    return get_cached(\"item_details.json\", cache_name, params=params)",
    "docstring": "This resource returns a details about a single item.\n\n    :param item_id: The item to query for.\n    :param lang: The language to display the texts in.\n\n    The response is an object with at least the following properties. Note that\n    the availability of some properties depends on the type of the item.\n\n    item_id (number):\n        The item id.\n\n    name (string):\n        The name of the item.\n\n    description (string):\n        The item description.\n\n    type (string):\n        The item type.\n\n    level (integer):\n        The required level.\n\n    rarity (string):\n        The rarity. On of ``Junk``, ``Basic``, ``Fine``, ``Masterwork``,\n        ``Rare``, ``Exotic``, ``Ascended`` or ``Legendary``.\n\n    vendor_value (integer):\n        The value in coins when selling to a vendor.\n\n    icon_file_id (string):\n        The icon file id to be used with the render service.\n\n    icon_file_signature (string):\n        The icon file signature to be used with the render service.\n\n    game_types (list):\n        The game types where the item is usable.\n        Currently known game types are: ``Activity``, ``Dungeon``, ``Pve``,\n        ``Pvp``, ``PvpLobby`` and ``WvW``\n\n    flags (list):\n        Additional item flags.\n        Currently known item flags are: ``AccountBound``, ``HideSuffix``,\n        ``NoMysticForge``, ``NoSalvage``, ``NoSell``, ``NotUpgradeable``,\n        ``NoUnderwater``, ``SoulbindOnAcquire``, ``SoulBindOnUse`` and\n        ``Unique``\n\n    restrictions (list):\n        Race restrictions: ``Asura``, ``Charr``, ``Human``, ``Norn`` and\n        ``Sylvari``.\n\n    Each item type has an `additional key`_ with information specific to that\n    item type.\n\n    .. _additional key: item-properties.html"
  },
  {
    "code": "def collapse_indents(indentation):\n    change_in_level = ind_change(indentation)\n    if change_in_level == 0:\n        indents = \"\"\n    elif change_in_level < 0:\n        indents = closeindent * (-change_in_level)\n    else:\n        indents = openindent * change_in_level\n    return indentation.replace(openindent, \"\").replace(closeindent, \"\") + indents",
    "docstring": "Removes all openindent-closeindent pairs."
  },
  {
    "code": "def fuzzy(self, key, limit=5):\n        instances = [i[2] for i in self.container if i[2]]\n        if not instances:\n            return\n        instances = sum(instances, [])\n        from fuzzywuzzy import process\n        maybe = process.extract(key, instances, limit=limit)\n        return maybe",
    "docstring": "Give suggestion from all instances."
  },
  {
    "code": "def visit_Break(self, _):\n        if self.break_handlers and self.break_handlers[-1]:\n            return Statement(\"goto {0}\".format(self.break_handlers[-1]))\n        else:\n            return Statement(\"break\")",
    "docstring": "Generate break statement in most case and goto for orelse clause.\n\n        See Also : cxx_loop"
  },
  {
    "code": "def _preprocess_add_items(self, items):\n        paths = []\n        entries = []\n        for item in items:\n            if isinstance(item, string_types):\n                paths.append(self._to_relative_path(item))\n            elif isinstance(item, (Blob, Submodule)):\n                entries.append(BaseIndexEntry.from_blob(item))\n            elif isinstance(item, BaseIndexEntry):\n                entries.append(item)\n            else:\n                raise TypeError(\"Invalid Type: %r\" % item)\n        return (paths, entries)",
    "docstring": "Split the items into two lists of path strings and BaseEntries."
  },
  {
    "code": "def FlushShortIdRecords(site_service):\n    szService = c_char_p(site_service.encode('utf-8'))\n    szMessage = create_string_buffer(b\"                    \")\n    nMessage = c_ushort(20)\n    nRet = dnaserv_dll.DnaFlushShortIdRecords(szService, byref(szMessage),\n                                              nMessage)\n    return str(nRet) + szMessage.value.decode('utf-8')",
    "docstring": "Flush all the queued records.\n\n    :param site_service: The site.service where data was pushed\n    :return: message whether function was successful"
  },
  {
    "code": "def delete_minion_cachedir(minion_id, provider, opts, base=None):\n    if isinstance(opts, dict):\n        __opts__.update(opts)\n    if __opts__.get('update_cachedir', False) is False:\n        return\n    if base is None:\n        base = __opts__['cachedir']\n    driver = next(six.iterkeys(__opts__['providers'][provider]))\n    fname = '{0}.p'.format(minion_id)\n    for cachedir in 'requested', 'active':\n        path = os.path.join(base, cachedir, driver, provider, fname)\n        log.debug('path: %s', path)\n        if os.path.exists(path):\n            os.remove(path)",
    "docstring": "Deletes a minion's entry from the cloud cachedir. It will search through\n    all cachedirs to find the minion's cache file.\n    Needs `update_cachedir` set to True."
  },
  {
    "code": "def handle_invocation(self, message):\n        req_id = message.request_id\n        reg_id = message.registration_id\n        if reg_id in self._registered_calls:\n            handler = self._registered_calls[reg_id][REGISTERED_CALL_CALLBACK]\n            invoke = WampInvokeWrapper(self,handler,message)\n            invoke.start()\n        else:\n            error_uri = self.get_full_uri('error.unknown.uri')\n            self.send_message(ERROR(\n                request_code = WAMP_INVOCATION,\n                request_id = req_id,\n                details = {},\n                error =error_uri\n            ))",
    "docstring": "Passes the invocation request to the appropriate\n            callback."
  },
  {
    "code": "def get_full_url(self, parsed_url):\n        full_path = parsed_url.path\n        if parsed_url.query:\n            full_path = '%s?%s' % (full_path, parsed_url.query)\n        return full_path",
    "docstring": "Returns url path with querystring"
  },
  {
    "code": "def printArchive(fileName):\n    archive = CombineArchive()\n    if archive.initializeFromArchive(fileName) is None:\n        print(\"Invalid Combine Archive\")\n        return None\n    print('*'*80)\n    print('Print archive:', fileName)\n    print('*' * 80)\n    printMetaDataFor(archive, \".\")\n    print(\"Num Entries: {0}\".format(archive.getNumEntries()))\n    for i in range(archive.getNumEntries()):\n        entry = archive.getEntry(i)\n        print(\" {0}: location: {1} format: {2}\".format(i, entry.getLocation(), entry.getFormat()))\n        printMetaDataFor(archive, entry.getLocation())\n        for j in range(entry.getNumCrossRefs()):\n            print(\"  {0}: crossRef location {1}\".format(j, entry.getCrossRef(j).getLocation()))\n    archive.cleanUp()",
    "docstring": "Prints content of combine archive\n\n    :param fileName: path of archive\n    :return: None"
  },
  {
    "code": "def _get_module(target):\n    filepath, sep, namespace = target.rpartition('|')\n    if sep and not filepath:\n        raise BadDirectory(\"Path to file not supplied.\")\n    module, sep, class_or_function = namespace.rpartition(':')\n    if (sep and not module) or (filepath and not module):\n        raise MissingModule(\"Need a module path for %s (%s)\" %\n                            (namespace, target))\n    if filepath and filepath not in sys.path:\n        if not os.path.isdir(filepath):\n            raise BadDirectory(\"No such directory: '%s'\" % filepath)\n        sys.path.append(filepath)\n    if not class_or_function:\n        raise MissingMethodOrFunction(\n            \"No Method or Function specified in '%s'\" % target)\n    if module:\n        try:\n            __import__(module)\n        except ImportError as e:\n            raise ImportFailed(\"Failed to import '%s'. \"\n                               \"Error: %s\" % (module, e))\n    klass, sep, function = class_or_function.rpartition('.')\n    return module, klass, function",
    "docstring": "Import a named class, module, method or function.\n\n    Accepts these formats:\n        \".../file/path|module_name:Class.method\"\n        \".../file/path|module_name:Class\"\n        \".../file/path|module_name:function\"\n        \"module_name:Class\"\n        \"module_name:function\"\n        \"module_name:Class.function\"\n\n    If a fully qualified directory is specified, it implies the\n    directory is not already on the Python Path, in which case\n    it will be added.\n\n    For example, if I import /home/foo (and\n    /home/foo is not in the python path) as\n    \"/home/foo|mycode:MyClass.mymethod\"\n    then /home/foo will be added to the python path and\n    the module loaded as normal."
  },
  {
    "code": "def numval(token):\n    if token.type == 'INTEGER':\n        return int(token.value)\n    elif token.type == 'FLOAT':\n        return float(token.value)\n    else:\n        return token.value",
    "docstring": "Return the numerical value of token.value if it is a number"
  },
  {
    "code": "def resource(self, uri, methods=frozenset({'GET'}), **kwargs):\n        def decorator(f):\n            if kwargs.get('stream'):\n                f.is_stream = kwargs['stream']\n            self.add_resource(f, uri=uri, methods=methods, **kwargs)\n        return decorator",
    "docstring": "Decorates a function to be registered as a resource route.\n\n        :param uri: path of the URL\n        :param methods: list or tuple of methods allowed\n        :param host:\n        :param strict_slashes:\n        :param stream:\n        :param version:\n        :param name: user defined route name for url_for\n        :param filters: List of callable that will filter request and\n                        response data\n        :param validators: List of callable added to the filter list.\n\n        :return: A decorated function"
  },
  {
    "code": "def read_stdin(self):\n        text = sys.stdin.read()\n        if sys.version_info[0] < 3 and text is not None:\n            text = text.decode(sys.stdin.encoding or 'utf-8')\n        return text",
    "docstring": "Reads STDIN until the end of input and returns a unicode string."
  },
  {
    "code": "def default( self, o ):\n        if isinstance(o, datetime):\n            return o.isoformat()\n        else:\n            if isinstance(o, Exception):\n                return str(o)\n            else:\n                if isinstance(o, numpy.integer):\n                    return int(o)\n                else:\n                    return super(MetadataEncoder, self).default(o)",
    "docstring": "If o is a datetime object, convert it to an ISO string. If it is an\n        exception, convert it to a string. If it is a numpy int, coerce it to\n        a Python int.\n\n        :param o: the field to serialise\n        :returns: a string encoding of the field"
  },
  {
    "code": "def set_app_args(self, *args):\n        if args:\n            self._set('pyargv', ' '.join(args))\n        return self._section",
    "docstring": "Sets ``sys.argv`` for python apps.\n\n        Examples:\n            * pyargv=\"one two three\" will set ``sys.argv`` to ``('one', 'two', 'three')``.\n\n        :param args:"
  },
  {
    "code": "def _class(self):\n        try:\n            self._project_name()\n        except ValueError:\n            return MalformedReq\n        if self._is_satisfied():\n            return SatisfiedReq\n        if not self._expected_hashes():\n            return MissingReq\n        if self._actual_hash() not in self._expected_hashes():\n            return MismatchedReq\n        return InstallableReq",
    "docstring": "Return the class I should be, spanning a continuum of goodness."
  },
  {
    "code": "def reply(self, text):\n        data = {'text': text, 'vchannel_id': self['vchannel_id']}\n        if self.is_p2p():\n            data['type'] = RTMMessageType.P2PMessage\n            data['to_uid'] = self['uid']\n        else:\n            data['type'] = RTMMessageType.ChannelMessage\n            data['channel_id'] = self['channel_id']\n        return RTMMessage(data)",
    "docstring": "Replys a text message\n\n        Args:\n            text(str): message content\n\n        Returns:\n            RTMMessage"
  },
  {
    "code": "def from_pandas_dataframe(cls, bqm_df, offset=0.0, interactions=None):\n        if interactions is None:\n            interactions = []\n        bqm = cls({}, {}, offset, Vartype.BINARY)\n        for u, row in bqm_df.iterrows():\n            for v, bias in row.iteritems():\n                if u == v:\n                    bqm.add_variable(u, bias)\n                elif bias:\n                    bqm.add_interaction(u, v, bias)\n        for u, v in interactions:\n            bqm.add_interaction(u, v, 0.0)\n        return bqm",
    "docstring": "Create a binary quadratic model from a QUBO model formatted as a pandas DataFrame.\n\n        Args:\n            bqm_df (:class:`pandas.DataFrame`):\n                Quadratic unconstrained binary optimization (QUBO) model formatted\n                as a pandas DataFrame. Row and column indices label the QUBO variables;\n                values are QUBO coefficients.\n\n            offset (optional, default=0.0):\n                Constant offset for the binary quadratic model.\n\n            interactions (iterable, optional, default=[]):\n                Any additional 0.0-bias interactions to be added to the binary quadratic model.\n\n        Returns:\n            :class:`.BinaryQuadraticModel`: Binary quadratic model with vartype set to\n            :class:`vartype.BINARY`.\n\n        Examples:\n            This example creates a binary quadratic model from a QUBO in pandas DataFrame format\n            while adding an interaction and setting a constant offset.\n\n            >>> import dimod\n            >>> import pandas as pd\n            >>> pd_qubo = pd.DataFrame(data={0: [-1, 0], 1: [2, -1]})\n            >>> pd_qubo\n               0  1\n            0 -1  2\n            1  0 -1\n            >>> model = dimod.BinaryQuadraticModel.from_pandas_dataframe(pd_qubo,\n            ...         offset = 2.5,\n            ...         interactions = {(0,2), (1,2)})\n            >>> model.linear        # doctest: +SKIP\n            {0: -1, 1: -1.0, 2: 0.0}\n            >>> model.quadratic     # doctest: +SKIP\n            {(0, 1): 2, (0, 2): 0.0, (1, 2): 0.0}\n            >>> model.offset\n            2.5\n            >>> model.vartype\n            <Vartype.BINARY: frozenset({0, 1})>"
  },
  {
    "code": "def async_update(self, event, reason={}):\n        reason['attr'] = []\n        for data in ['state', 'config']:\n            changed_attr = self.update_attr(event.get(data, {}))\n            reason[data] = data in event\n            reason['attr'] += changed_attr\n        super().async_update(event, reason)",
    "docstring": "New event for sensor.\n\n        Check if state or config is part of event.\n        Signal that sensor has updated attributes.\n        Inform what attributes got changed values."
  },
  {
    "code": "def from_binary(cls,pst,filename):\n        m = Matrix.from_binary(filename)\n        return ObservationEnsemble(data=m.x,pst=pst, index=m.row_names)",
    "docstring": "instantiate an observation obsemble from a jco-type file\n\n        Parameters\n        ----------\n        pst : pyemu.Pst\n            a Pst instance\n        filename : str\n            the binary file name\n\n        Returns\n        -------\n        oe : ObservationEnsemble"
  },
  {
    "code": "def _stream(self, char):\n        num = ord(char)\n        if num in self.basic:\n            self.dispatch(self.basic[num])\n        elif num == ctrl.ESC:\n            self.state = \"escape\"\n        elif num == 0x00:\n            pass\n        else: \n            self.dispatch(\"print\", char)",
    "docstring": "Process a character when in the\n        default 'stream' state."
  },
  {
    "code": "def _FormatDateTime(self, event):\n    try:\n      datetime_object = datetime.datetime(\n          1970, 1, 1, 0, 0, 0, 0, tzinfo=pytz.UTC)\n      datetime_object += datetime.timedelta(microseconds=event.timestamp)\n      datetime_object.astimezone(self._output_mediator.timezone)\n      return datetime_object.replace(tzinfo=None)\n    except (OverflowError, ValueError) as exception:\n      self._ReportEventError(event, (\n          'unable to copy timestamp: {0!s} to a human readable date and time '\n          'with error: {1!s}. Defaulting to: \"ERROR\"').format(\n              event.timestamp, exception))\n      return 'ERROR'",
    "docstring": "Formats the date to a datetime object without timezone information.\n\n    Note: timezone information must be removed due to lack of support\n    by xlsxwriter and Excel.\n\n    Args:\n      event (EventObject): event.\n\n    Returns:\n      datetime.datetime|str: date and time value or a string containing\n          \"ERROR\" on OverflowError."
  },
  {
    "code": "def list_media_services(access_token, subscription_id):\n    endpoint = ''.join([get_rm_endpoint(),\n                        '/subscriptions/', subscription_id,\n                        '/providers/microsoft.media/mediaservices?api-version=', MEDIA_API])\n    return do_get(endpoint, access_token)",
    "docstring": "List the media services in a subscription.\n\n    Args:\n        access_token (str): A valid Azure authentication token.\n        subscription_id (str): Azure subscription id.\n\n    Returns:\n        HTTP response. JSON body."
  },
  {
    "code": "async def delete(self):\n        if self.id == self._origin.Fabric._default_fabric_id:\n            raise CannotDelete(\"Default fabric cannot be deleted.\")\n        await self._handler.delete(id=self.id)",
    "docstring": "Delete this Fabric."
  },
  {
    "code": "def class_balancing_sampler(y, indices):\n        weights = WeightedSampler.class_balancing_sample_weights(y[indices])\n        return WeightedSubsetSampler(weights, indices=indices)",
    "docstring": "Construct a `WeightedSubsetSampler` that compensates for class\n        imbalance.\n\n        Parameters\n        ----------\n        y: NumPy array, 1D dtype=int\n            sample classes, values must be 0 or positive\n        indices: NumPy array, 1D dtype=int\n            An array of indices that identify the subset of samples drawn\n            from data that are to be used\n\n        Returns\n        -------\n        WeightedSubsetSampler instance\n            Sampler"
  },
  {
    "code": "def GetLoadedModuleBySuffix(path):\n  root = os.path.splitext(path)[0]\n  for module in sys.modules.values():\n    mod_root = os.path.splitext(getattr(module, '__file__', None) or '')[0]\n    if not mod_root:\n      continue\n    if not os.path.isabs(mod_root):\n      mod_root = os.path.join(os.getcwd(), mod_root)\n    if IsPathSuffix(mod_root, root):\n      return module\n  return None",
    "docstring": "Searches sys.modules to find a module with the given file path.\n\n  Args:\n    path: Path to the source file. It can be relative or absolute, as suffix\n          match can handle both. If absolute, it must have already been\n          sanitized.\n\n  Algorithm:\n    The given path must be a full suffix of a loaded module to be a valid match.\n    File extensions are ignored when performing suffix match.\n\n  Example:\n    path: 'a/b/c.py'\n    modules: {'a': 'a.py', 'a.b': 'a/b.py', 'a.b.c': 'a/b/c.pyc']\n    returns: module('a.b.c')\n\n  Returns:\n    The module that corresponds to path, or None if such module was not\n    found."
  },
  {
    "code": "def getAddr (self, ifname):\n        if sys.platform == 'darwin':\n            return ifconfig_inet(ifname).get('address')\n        return self._getaddr(ifname, self.SIOCGIFADDR)",
    "docstring": "Get the inet addr for an interface.\n        @param ifname: interface name\n        @type ifname: string"
  },
  {
    "code": "def additive_coupling(name, x, mid_channels=512, reverse=False,\n                      activation=\"relu\", dropout=0.0):\n  with tf.variable_scope(name, reuse=tf.AUTO_REUSE):\n    output_channels = common_layers.shape_list(x)[-1] // 2\n    x1, x2 = tf.split(x, num_or_size_splits=2, axis=-1)\n    z1 = x1\n    shift = conv_stack(\"nn\", x1, mid_channels, output_channels=output_channels,\n                       activation=activation, dropout=dropout)\n    if not reverse:\n      z2 = x2 + shift\n    else:\n      z2 = x2 - shift\n    return tf.concat([z1, z2], axis=3), 0.0",
    "docstring": "Reversible additive coupling layer.\n\n  Args:\n    name: variable scope.\n    x: 4-D Tensor, shape=(NHWC).\n    mid_channels: number of channels in the coupling layer.\n    reverse: Forward or reverse operation.\n    activation: \"relu\" or \"gatu\"\n    dropout: default, 0.0\n  Returns:\n    output: 4-D Tensor, shape=(NHWC)\n    objective: 0.0"
  },
  {
    "code": "def peak_templates(self):\n        peak_templates = []\n        for peak_descr in self:\n            expanded_dims = [dim_group.dimensions for dim_group in peak_descr]\n            templates = product(*expanded_dims)\n            for template in templates:\n                peak_templates.append(PeakTemplate(template))\n        return peak_templates",
    "docstring": "Create a list of concrete peak templates from a list of general peak descriptions.\n\n        :return: List of peak templates.\n        :rtype: :py:class:`list`"
  },
  {
    "code": "def _clean(self):\n        found_ids = {}\n        nodes = [self._nodes[_node.Root.ID]]\n        while nodes:\n            node = nodes.pop()\n            found_ids[node.id] = None\n            nodes = nodes + node.children\n        for node_id in self._nodes:\n            if node_id in found_ids:\n                continue\n            logger.error('Dangling node: %s', node_id)\n        for node_id in found_ids:\n            if node_id in self._nodes:\n                continue\n            logger.error('Unregistered node: %s', node_id)",
    "docstring": "Recursively check that all nodes are reachable."
  },
  {
    "code": "def _cell_scalar(self, name=None):\n        if name is None:\n            field, name = self.active_scalar_info\n            if field != CELL_DATA_FIELD:\n                raise RuntimeError('Must specify an array to fetch.')\n        vtkarr = self.GetCellData().GetArray(name)\n        if vtkarr is None:\n            raise AssertionError('({}) is not a cell scalar'.format(name))\n        if isinstance(vtkarr, vtk.vtkBitArray):\n            vtkarr = vtk_bit_array_to_char(vtkarr)\n            if name not in self._cell_bool_array_names:\n                self._cell_bool_array_names.append(name)\n        array = vtk_to_numpy(vtkarr)\n        if array.dtype == np.uint8 and name in self._cell_bool_array_names:\n            array = array.view(np.bool)\n        return array",
    "docstring": "Returns the cell scalars of a vtk object\n\n        Parameters\n        ----------\n        name : str\n            Name of cell scalars to retrive.\n\n        Returns\n        -------\n        scalars : np.ndarray\n            Numpy array of scalars"
  },
  {
    "code": "def set_boot_arch(arch='default'):\n    if arch not in ['i386', 'x86_64', 'default']:\n        msg = 'Invalid value passed for arch.\\n' \\\n              'Must be i386, x86_64, or default.\\n' \\\n              'Passed: {0}'.format(arch)\n        raise SaltInvocationError(msg)\n    cmd = 'systemsetup -setkernelbootarchitecture {0}'.format(arch)\n    __utils__['mac_utils.execute_return_success'](cmd)\n    return __utils__['mac_utils.confirm_updated'](\n        arch,\n        get_boot_arch,\n    )",
    "docstring": "Set the kernel to boot in 32 or 64 bit mode on next boot.\n\n    .. note::\n        When this function fails with the error ``changes to kernel\n        architecture failed to save!``, then the boot arch is not updated.\n        This is either an Apple bug, not available on the test system, or a\n        result of system files being locked down in macOS (SIP Protection).\n\n    :param str arch: A string representing the desired architecture. If no\n        value is passed, default is assumed. Valid values include:\n\n        - i386\n        - x86_64\n        - default\n\n    :return: True if successful, False if not\n    :rtype: bool\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' system.set_boot_arch i386"
  },
  {
    "code": "def inv_matrix(self) -> np.ndarray:\n        if self._inv_matrix is None:\n            self._inv_matrix = inv(self._matrix)\n            self._inv_matrix.setflags(write=False)\n        return self._inv_matrix",
    "docstring": "Inverse of lattice matrix."
  },
  {
    "code": "def _getImageSize(filename):\n    result = None\n    file = open(filename, 'rb')\n    if file.read(8) == b'\\x89PNG\\r\\n\\x1a\\n':\n        while 1:\n            length, = _struct.unpack('>i', file.read(4))\n            chunkID = file.read(4)\n            if chunkID == '':\n                break\n            if chunkID == b'IHDR':\n                result = _struct.unpack('>ii', file.read(8))\n                break\n            file.seek(4 + length, 1)\n        file.close()\n        return result\n    file.seek(0)\n    if file.read(8) == b'BM':\n        file.seek(18, 0)\n        result = _struct.unpack('<ii', file.read(8))\n    file.close()\n    return result",
    "docstring": "Try to get the width and height of a bmp of png image file"
  },
  {
    "code": "def setup_file_logger(filename, formatting, log_level):\n    logger = logging.getLogger()\n    if logger.handlers:\n        logger.removeHandler(logger.handlers[0])\n    handler = logging.FileHandler(filename)\n    logger.addHandler(handler)\n    formatter = logging.Formatter(*formatting)\n    handler.setFormatter(formatter)\n    logger.setLevel(log_level)\n    handler.setLevel(log_level)\n    return logger",
    "docstring": "A helper function for creating a file logger.\n    Accepts arguments, as it is used in Status and LoggingWriter."
  },
  {
    "code": "def djrepo_path(self):\n        root, ext = os.path.splitext(self.filepath)\n        path = root + \".djrepo\"\n        return path",
    "docstring": "The path of the djrepo file. None if file does not exist."
  },
  {
    "code": "def _setup(self):\n        default_settings.reload()\n        environment_variable = self._kwargs.get(\n            \"ENVVAR_FOR_DYNACONF\", default_settings.ENVVAR_FOR_DYNACONF\n        )\n        settings_module = os.environ.get(environment_variable)\n        self._wrapped = Settings(\n            settings_module=settings_module, **self._kwargs\n        )\n        self.logger.debug(\"Lazy Settings _setup ...\")",
    "docstring": "Initial setup, run once."
  },
  {
    "code": "def _compile(pattern, flags):\n    return re.compile(WcParse(pattern, flags & FLAG_MASK).parse())",
    "docstring": "Compile the pattern to regex."
  },
  {
    "code": "def badnick(self, me=None, nick=None, **kw):\n        if me == '*':\n            self.bot.set_nick(self.bot.nick + '_')\n        self.bot.log.debug('Trying to regain nickname in 30s...')\n        self.nick_handle = self.bot.loop.call_later(\n            30, self.bot.set_nick, self.bot.original_nick)",
    "docstring": "Use alt nick on nick error"
  },
  {
    "code": "def get_assessment_section_mdata():\n    return {\n        'assessment_taken': {\n            'element_label': {\n                'text': 'assessment taken',\n                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),\n                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),\n                'formatTypeId': str(DEFAULT_FORMAT_TYPE),\n            },\n            'instructions': {\n                'text': 'accepts an osid.id.Id object',\n                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),\n                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),\n                'formatTypeId': str(DEFAULT_FORMAT_TYPE),\n            },\n            'required': False,\n            'read_only': False,\n            'linked': False,\n            'array': False,\n            'default_id_values': [''],\n            'syntax': 'ID',\n            'id_set': [],\n        },\n    }",
    "docstring": "Return default mdata map for AssessmentSection"
  },
  {
    "code": "def _process_unresolved_indirect_jumps(self):\n        l.info(\"%d indirect jumps to resolve.\", len(self._indirect_jumps_to_resolve))\n        all_targets = set()\n        for idx, jump in enumerate(self._indirect_jumps_to_resolve):\n            if self._low_priority:\n                self._release_gil(idx, 20, 0.0001)\n            all_targets |= self._process_one_indirect_jump(jump)\n        self._indirect_jumps_to_resolve.clear()\n        return all_targets",
    "docstring": "Resolve all unresolved indirect jumps found in previous scanning.\n\n        Currently we support resolving the following types of indirect jumps:\n        - Ijk_Call: indirect calls where the function address is passed in from a proceeding basic block\n        - Ijk_Boring: jump tables\n        - For an up-to-date list, see analyses/cfg/indirect_jump_resolvers\n\n        :return:    A set of concrete indirect jump targets (ints).\n        :rtype:     set"
  },
  {
    "code": "def list_previous_page(self):\n        uri = self._paging.get(\"domain\", {}).get(\"prev_uri\")\n        if uri is None:\n            raise exc.NoMoreResults(\"There are no previous pages of domains \"\n                    \"to list.\")\n        return self._list(uri)",
    "docstring": "When paging through results, this will return the previous page, using\n        the same limit. If there are no more results, a NoMoreResults exception\n        will be raised."
  },
  {
    "code": "def flatten_all_paths(self, group_filter=lambda x: True,\n                          path_filter=lambda x: True,\n                          path_conversions=CONVERSIONS):\n        return flatten_all_paths(self.tree.getroot(), group_filter,\n                                 path_filter, path_conversions)",
    "docstring": "Forward the tree of this document into the more general\n        flatten_all_paths function and return the result."
  },
  {
    "code": "def __get_package_manager(self):\n        package_manager = \"\"\n        args = \"\"\n        sudo_required = True\n        if system.is_osx():\n            package_manager = \"brew\"\n            sudo_required = False\n            args = \" install\"\n        elif system.is_debian():\n            package_manager = \"apt-get\"\n            args = \" -y install\"\n        elif system.is_fedora():\n            package_manager = \"yum\"\n            args = \" install\"\n        elif system.is_arch():\n            package_manager = \"pacman\"\n            args = \" --noconfirm -S\"\n        if lib.which(package_manager) is None:\n            self.logger.warn(\"Package manager %s not installed! Packages will not be installed.\"\n                             % package_manager)\n            self.package_manager = None\n        self.package_manager = package_manager\n        self.sudo_required = sudo_required\n        self.args = args",
    "docstring": "Installs and verifies package manager"
  },
  {
    "code": "def get_column_for_modelfield(model_field):\n    while model_field.related_model:\n        model_field = model_field.related_model._meta.pk\n    for ColumnClass, modelfield_classes in COLUMN_CLASSES:\n        if isinstance(model_field, tuple(modelfield_classes)):\n            return ColumnClass",
    "docstring": "Return the built-in Column class for a model field class."
  },
  {
    "code": "def get_hash_as_int(*args, group: cmod.PairingGroup = None):\n    group = group if group else cmod.PairingGroup(PAIRING_GROUP)\n    h_challenge = sha256()\n    serialedArgs = [group.serialize(arg) if isGroupElement(arg)\n                    else cmod.Conversion.IP2OS(arg)\n                    for arg in args]\n    for arg in sorted(serialedArgs):\n        h_challenge.update(arg)\n    return bytes_to_int(h_challenge.digest())",
    "docstring": "Enumerate over the input tuple and generate a hash using the tuple values\n\n    :param args: sequence of either group or integer elements\n    :param group: pairing group if an element is a group element\n    :return:"
  },
  {
    "code": "def _set(self, **kwargs):\n        for param, value in kwargs.items():\n            p = getattr(self, param)\n            if value is not None:\n                try:\n                    value = p.typeConverter(value)\n                except TypeError as e:\n                    raise TypeError('Invalid param value given for param \"%s\". %s' % (p.name, e))\n            self._paramMap[p] = value\n        return self",
    "docstring": "Sets user-supplied params."
  },
  {
    "code": "def find_best_candidate(self):\n        self.fill_percent_done()\n        i_b = np.argmax(self.percent_done.ravel())\n        if self.percent_done.ravel()[i_b] <= 0:\n            return None\n        I = self.percent_done.ravel() == self.percent_done.ravel()[i_b]\n        if I.sum() == 1:\n            return i_b\n        else:\n            I2 = np.argmax(self.max_elev.ravel()[I])\n            return I.nonzero()[0][I2]",
    "docstring": "Determine which tile, when processed, would complete the largest\n        percentage of unresolved edge pixels. This is a heuristic function\n        and does not give the optimal tile."
  },
  {
    "code": "def get(self):\n        opts = current_app.config['RECORDS_REST_SORT_OPTIONS'].get(\n            self.search_index)\n        sort_fields = []\n        if opts:\n            for key, item in sorted(opts.items(), key=lambda x: x[1]['order']):\n                sort_fields.append(\n                    {key: dict(\n                        title=item['title'],\n                        default_order=item.get('default_order', 'asc'))}\n                )\n        return jsonify(dict(\n            sort_fields=sort_fields,\n            max_result_window=self.max_result_window,\n            default_media_type=self.default_media_type,\n            search_media_types=sorted(self.search_media_types),\n            item_media_types=sorted(self.item_media_types),\n        ))",
    "docstring": "Get options."
  },
  {
    "code": "def _ExtractGMailSearchQuery(self, url):\n    if 'search/' not in url:\n      return None\n    _, _, line = url.partition('search/')\n    line, _, _ = line.partition('/')\n    line, _, _ = line.partition('?')\n    return line.replace('+', ' ')",
    "docstring": "Extracts a search query from a GMail search URL.\n\n    GMail: https://mail.google.com/mail/u/0/#search/query[/?]\n\n    Args:\n      url (str): URL.\n\n    Returns:\n      str: search query or None if no query was found."
  },
  {
    "code": "def Range(start, limit, delta):\n    return np.arange(start, limit, delta, dtype=np.int32),",
    "docstring": "Range op."
  },
  {
    "code": "def _generate_key_map(entity_list, key, entity_class):\n    key_map = {}\n    for obj in entity_list:\n      key_map[obj[key]] = entity_class(**obj)\n    return key_map",
    "docstring": "Helper method to generate map from key to entity object for given list of dicts.\n\n    Args:\n      entity_list: List consisting of dict.\n      key: Key in each dict which will be key in the map.\n      entity_class: Class representing the entity.\n\n    Returns:\n      Map mapping key to entity object."
  },
  {
    "code": "def escape_latex_str_if_str(value):\n    if not isinstance(value, str):\n        return value\n    for regex, replace_text in REGEX_ESCAPE_CHARS:\n        value = re.sub(regex, replace_text, value)\n    value = re.sub(REGEX_BACKSLASH, r'\\\\\\\\', value)\n    return value",
    "docstring": "Escape a latex string"
  },
  {
    "code": "def lookup_host(self, name):\n\t\tres = self.lookup_by_host(name=name)\n\t\ttry:\n\t\t\treturn dict(ip=res[\"ip-address\"], mac=res[\"hardware-address\"], hostname=res[\"name\"].decode('utf-8'))\n\t\texcept KeyError:\n\t\t\traise OmapiErrorAttributeNotFound()",
    "docstring": "Look for a host object with given name and return the\n\t\tname, mac, and ip address\n\n\t\t@type name: str\n\t\t@rtype: dict or None\n\t\t@raises ValueError:\n\t\t@raises OmapiError:\n\t\t@raises OmapiErrorNotFound: if no host object with the given name could be found\n\t\t@raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks ip, mac or name\n\t\t@raises socket.error:"
  },
  {
    "code": "def clear(self):\n        node = self._first\n        while node is not None:\n            next_node = node._next\n            node._list = node._prev = node._next = None\n            node = next_node\n        self._size = 0",
    "docstring": "Remove all nodes from the list."
  },
  {
    "code": "def populate_user(self,\n                      request,\n                      sociallogin,\n                      data):\n        username = data.get('username')\n        first_name = data.get('first_name')\n        last_name = data.get('last_name')\n        email = data.get('email')\n        name = data.get('name')\n        user = sociallogin.user\n        user_username(user, username or '')\n        user_email(user, valid_email_or_none(email) or '')\n        name_parts = (name or '').partition(' ')\n        user_field(user, 'first_name', first_name or name_parts[0])\n        user_field(user, 'last_name', last_name or name_parts[2])\n        return user",
    "docstring": "Hook that can be used to further populate the user instance.\n\n        For convenience, we populate several common fields.\n\n        Note that the user instance being populated represents a\n        suggested User instance that represents the social user that is\n        in the process of being logged in.\n\n        The User instance need not be completely valid and conflict\n        free. For example, verifying whether or not the username\n        already exists, is not a responsibility."
  },
  {
    "code": "def key_press_event(self, event):\n        if event.key() == QtCore.Qt.Key_Return:\n            cursor = self.edit.textCursor()\n            cursor.movePosition(cursor.EndOfBlock)\n            self.edit.setTextCursor(cursor)\n        code = _qkey_to_ascii(event)\n        if code:\n            self.process.writeData(code)\n            return False\n        return True",
    "docstring": "Directly writes the ascii code of the key to the process' stdin.\n\n        :retuns: False to prevent the event from being propagated to the parent widget."
  },
  {
    "code": "def delete(self, block, name):\n        self._kvs.delete(self._key(block, name))",
    "docstring": "Reset the value of the field named `name` to the default"
  },
  {
    "code": "def open(self):\r\n        self.h_info = SetupDiGetClassDevs(byref(self.guid), None, None,\r\n                (DIGCF.PRESENT | DIGCF.DEVICEINTERFACE) )\r\n        return self.h_info",
    "docstring": "Calls SetupDiGetClassDevs to obtain a handle to an opaque device\r\n        information set that describes the device interfaces supported by all\r\n        the USB collections currently installed in the system. The\r\n        application should specify DIGCF.PRESENT and DIGCF.INTERFACEDEVICE\r\n        in the Flags parameter passed to SetupDiGetClassDevs."
  },
  {
    "code": "def string_to_integer(value, strict=False):\n    if is_undefined(value):\n        if strict:\n            raise ValueError('The value cannot be null')\n        return None\n    try:\n        return int(value)\n    except ValueError:\n        raise ValueError('The specified string \"%s\" does not represent an integer' % value)",
    "docstring": "Return an integer corresponding to the string representation of a\n    number.\n\n    @param value: a string representation of an integer number.\n\n    @param strict:  indicate whether the specified string MUST be of a\n        valid integer number representation.\n\n    @return: the integer value represented by the string.\n\n    @raise ValueError: if the string doesn't represent a valid integer,\n        while the argument ``strict`` equals ``True``."
  },
  {
    "code": "def df(self, version=None, tags=None, ext=None, **kwargs):\n        ext = self._find_extension(version=version, tags=tags)\n        if ext is None:\n            attribs = \"{}{}\".format(\n                \"version={} and \".format(version) if version else \"\",\n                \"tags={}\".format(tags) if tags else \"\",\n            )\n            raise MissingDatasetError(\n                \"No dataset with {} in local store!\".format(attribs))\n        fpath = self.fpath(version=version, tags=tags, ext=ext)\n        fmt = SerializationFormat.by_name(ext)\n        return fmt.deserialize(fpath, **kwargs)",
    "docstring": "Loads an instance of this dataset into a dataframe.\n\n        Parameters\n        ----------\n        version: str, optional\n            The version of the instance of this dataset.\n        tags : list of str, optional\n            The tags associated with the desired instance of this dataset.\n        ext : str, optional\n            The file extension to use. If not given, the default extension is\n            used.\n        **kwargs : extra keyword arguments, optional\n            Extra keyword arguments are forwarded to the deserialization method\n            of the SerializationFormat object corresponding to the extension\n            used.\n\n        Returns\n        -------\n        pandas.DataFrame\n            A dataframe containing the desired instance of this dataset."
  },
  {
    "code": "def connect(port=8813, numRetries=10, host=\"localhost\", proc=None):\n    for wait in range(1, numRetries + 2):\n        try:\n            return Connection(host, port, proc)\n        except socket.error as e:\n            print(\"Could not connect to TraCI server at %s:%s\" %\n                  (host, port), e)\n            if wait < numRetries + 1:\n                print(\" Retrying in %s seconds\" % wait)\n                time.sleep(wait)\n    raise FatalTraCIError(str(e))",
    "docstring": "Establish a connection to a TraCI-Server and return the\n    connection object. The connection is not saved in the pool and not\n    accessible via traci.switch. It should be safe to use different\n    connections established by this method in different threads."
  },
  {
    "code": "async def ltrim(self, name, start, end):\n        return await self.execute_command('LTRIM', name, start, end)",
    "docstring": "Trim the list ``name``, removing all values not within the slice\n        between ``start`` and ``end``\n\n        ``start`` and ``end`` can be negative numbers just like\n        Python slicing notation"
  },
  {
    "code": "def generate(env):\n    java_file = SCons.Tool.CreateJavaFileBuilder(env)\n    java_class = SCons.Tool.CreateJavaClassFileBuilder(env)\n    java_class_dir = SCons.Tool.CreateJavaClassDirBuilder(env)\n    java_class.add_emitter(None, emit_java_classes)\n    java_class.add_emitter(env.subst('$JAVASUFFIX'), emit_java_classes)\n    java_class_dir.emitter = emit_java_classes\n    env.AddMethod(Java)\n    env['JAVAC']                    = 'javac'\n    env['JAVACFLAGS']               = SCons.Util.CLVar('')\n    env['JAVABOOTCLASSPATH']        = []\n    env['JAVACLASSPATH']            = []\n    env['JAVASOURCEPATH']           = []\n    env['_javapathopt']             = pathopt\n    env['_JAVABOOTCLASSPATH']       = '${_javapathopt(\"-bootclasspath\", \"JAVABOOTCLASSPATH\")} '\n    env['_JAVACLASSPATH']           = '${_javapathopt(\"-classpath\", \"JAVACLASSPATH\")} '\n    env['_JAVASOURCEPATH']          = '${_javapathopt(\"-sourcepath\", \"JAVASOURCEPATH\", \"_JAVASOURCEPATHDEFAULT\")} '\n    env['_JAVASOURCEPATHDEFAULT']   = '${TARGET.attributes.java_sourcedir}'\n    env['_JAVACCOM']                = '$JAVAC $JAVACFLAGS $_JAVABOOTCLASSPATH $_JAVACLASSPATH -d ${TARGET.attributes.java_classdir} $_JAVASOURCEPATH $SOURCES'\n    env['JAVACCOM']                 = \"${TEMPFILE('$_JAVACCOM','$JAVACCOMSTR')}\"\n    env['JAVACLASSSUFFIX']          = '.class'\n    env['JAVASUFFIX']               = '.java'",
    "docstring": "Add Builders and construction variables for javac to an Environment."
  },
  {
    "code": "def get_post_fields(request):\n    fields = dict()\n    for field,value in request.form.items():\n        fields[field] = value\n    return fields",
    "docstring": "parse through a request, and return fields from post in a dictionary"
  },
  {
    "code": "def nan_circmean(samples, high=2.0*np.pi, low=0.0, axis=None):\n    samples = np.asarray(samples)\n    samples = samples[~np.isnan(samples)]\n    if samples.size == 0:\n        return np.nan\n    ang = (samples - low) * 2.0 * np.pi / (high - low)\n    ssum = np.sin(ang).sum(axis=axis)\n    csum = np.cos(ang).sum(axis=axis)\n    res = np.arctan2(ssum, csum)\n    mask = res < 0.0\n    if mask.ndim > 0:\n        res[mask] += 2.0 * np.pi\n    elif mask:\n        res += 2.0 * np.pi\n    circmean = res * (high - low) / (2.0 * np.pi) + low\n    return circmean",
    "docstring": "NaN insensitive version of scipy's circular mean routine\n\n    Parameters\n    -----------\n    samples : array_like\n        Input array\n    low : float or int\n        Lower boundary for circular standard deviation range (default=0)\n    high: float or int\n        Upper boundary for circular standard deviation range (default=2 pi)\n    axis : int or NoneType\n        Axis along which standard deviations are computed.  The default is to\n        compute the standard deviation of the flattened array\n\n    Returns\n    --------\n    circmean : float\n        Circular mean"
  },
  {
    "code": "def node_add_label(node_name, label_name, label_value, **kwargs):\n    cfg = _setup_conn(**kwargs)\n    try:\n        api_instance = kubernetes.client.CoreV1Api()\n        body = {\n            'metadata': {\n                'labels': {\n                    label_name: label_value}\n                }\n        }\n        api_response = api_instance.patch_node(node_name, body)\n        return api_response\n    except (ApiException, HTTPError) as exc:\n        if isinstance(exc, ApiException) and exc.status == 404:\n            return None\n        else:\n            log.exception('Exception when calling CoreV1Api->patch_node')\n            raise CommandExecutionError(exc)\n    finally:\n        _cleanup(**cfg)\n    return None",
    "docstring": "Set the value of the label identified by `label_name` to `label_value` on\n    the node identified by the name `node_name`.\n    Creates the lable if not present.\n\n    CLI Examples::\n\n        salt '*' kubernetes.node_add_label node_name=\"minikube\" \\\n            label_name=\"foo\" label_value=\"bar\""
  },
  {
    "code": "def _set_default_resource_names(self):\n        self.ip_config_name = ''.join([\n            self.running_instance_id, '-ip-config'\n        ])\n        self.nic_name = ''.join([self.running_instance_id, '-nic'])\n        self.public_ip_name = ''.join([self.running_instance_id, '-public-ip'])",
    "docstring": "Generate names for resources based on the running_instance_id."
  },
  {
    "code": "def _set_digraph_b(self, char):\n        self.has_digraph_b = True\n        self.active_vowel_ro = di_b_lt[char][0]\n        self.active_dgr_b_info = di_b_lt[char]",
    "docstring": "Sets the second part of a digraph."
  },
  {
    "code": "def build_connection(url):\n    username = os.environ.get('ELASTICSEARCH_USERNAME')\n    password = os.environ.get('ELASTICSEARCH_PASSWORD')\n    if username and password:\n        return Elasticsearch(url, http_auth=(username, password))\n    return Elasticsearch(url)",
    "docstring": "Build an Elasticsearch connection with the given url\n\n    Elastic.co's Heroku addon doesn't create credientials with access to the\n    cluster by default so they aren't exposed in the URL they provide either.\n    This function works around the situation by grabbing our credentials from\n    the environment via Django settings and building a connection with them."
  },
  {
    "code": "def _head_length(self, port):\n        if not port:\n            return 0.\n        parent_state_v = self.get_parent_state_v()\n        if parent_state_v is port.parent:\n            return port.port_size[1]\n        return max(port.port_size[1] * 1.5, self._calc_line_width() / 1.3)",
    "docstring": "Distance from the center of the port to the perpendicular waypoint"
  },
  {
    "code": "def _evalAndDer(self,x):\n        m = len(x)\n        fx = np.zeros((m,self.funcCount))\n        for j in range(self.funcCount):\n            fx[:,j] = self.functions[j](x)\n        fx[np.isnan(fx)] = np.inf\n        i = np.argmin(fx,axis=1)\n        y = fx[np.arange(m),i]\n        dydx = np.zeros_like(y)\n        for j in range(self.funcCount):\n            c = i == j\n            dydx[c] = self.functions[j].derivative(x[c])\n        return y,dydx",
    "docstring": "Returns the level and first derivative of the function at each value in\n        x.  Only called internally by HARKinterpolator1D.eval_and_der."
  },
  {
    "code": "def _validate_timeout(cls, value, name):\n        if value is _Default:\n            return cls.DEFAULT_TIMEOUT\n        if value is None or value is cls.DEFAULT_TIMEOUT:\n            return value\n        if isinstance(value, bool):\n            raise ValueError(\"Timeout cannot be a boolean value. It must \"\n                             \"be an int, float or None.\")\n        try:\n            float(value)\n        except (TypeError, ValueError):\n            raise ValueError(\"Timeout value %s was %s, but it must be an \"\n                             \"int, float or None.\" % (name, value))\n        try:\n            if value <= 0:\n                raise ValueError(\"Attempted to set %s timeout to %s, but the \"\n                                 \"timeout cannot be set to a value less \"\n                                 \"than or equal to 0.\" % (name, value))\n        except TypeError:\n            raise ValueError(\"Timeout value %s was %s, but it must be an \"\n                             \"int, float or None.\" % (name, value))\n        return value",
    "docstring": "Check that a timeout attribute is valid.\n\n        :param value: The timeout value to validate\n        :param name: The name of the timeout attribute to validate. This is\n            used to specify in error messages.\n        :return: The validated and casted version of the given value.\n        :raises ValueError: If it is a numeric value less than or equal to\n            zero, or the type is not an integer, float, or None."
  },
  {
    "code": "def unit(self, unit):\n        allowed_values = [\"cm\", \"inch\", \"foot\"]\n        if unit is not None and unit not in allowed_values:\n            raise ValueError(\n                \"Invalid value for `unit` ({0}), must be one of {1}\"\n                .format(unit, allowed_values)\n            )\n        self._unit = unit",
    "docstring": "Sets the unit of this Dimensions.\n\n\n        :param unit: The unit of this Dimensions.\n        :type: str"
  },
  {
    "code": "def _call(self, method, *args, **kwargs):\n        assert self.session\n        if not kwargs.get('verify'):\n            kwargs['verify'] = self.SSL_VERIFY\n        response = self.session.request(method, *args, **kwargs)\n        response_json = response.text and response.json() or {}\n        if response.status_code < 200 or response.status_code >= 300:\n            message = response_json.get('error', response_json.get('message'))\n            raise HelpScoutRemoteException(response.status_code, message)\n        self.page_current = response_json.get(self.PAGE_CURRENT, 1)\n        self.page_total = response_json.get(self.PAGE_TOTAL, 1)\n        try:\n            return response_json[self.PAGE_DATA_MULTI]\n        except KeyError:\n            pass\n        try:\n            return [response_json[self.PAGE_DATA_SINGLE]]\n        except KeyError:\n            pass\n        return None",
    "docstring": "Call the remote service and return the response data."
  },
  {
    "code": "def setup_logging(args):\n    handler = logging.StreamHandler()\n    handler.setLevel(args.log_level)\n    formatter = logging.Formatter(('%(asctime)s - '\n                                   '%(name)s - '\n                                   '%(levelname)s - '\n                                   '%(message)s'))\n    handler.setFormatter(formatter)\n    LOGGER.addHandler(handler)",
    "docstring": "This sets up the logging.\n\n    Needs the args to get the log level supplied\n    :param args: The command line arguments"
  },
  {
    "code": "def parser(input_file_path='config.json'):\n    try:\n        with open(input_file_path, 'r') as config_file:\n            config_new = json.load(config_file)\n            config_file.close()\n    except:\n        raise Exception('Config file \"'+input_file_path+'\" not loaded properly. Please check it an try again.')\n    import copy\n    options = update_config(config_new, copy.deepcopy(default_config))\n    return options",
    "docstring": "Parser for the .json file containing the configuration of the method."
  },
  {
    "code": "def get_config_files():\n        apps_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),\n                                APPS_DIR)\n        custom_apps_dir = os.path.join(os.environ['HOME'], CUSTOM_APPS_DIR)\n        config_files = set()\n        custom_files = set()\n        if os.path.isdir(custom_apps_dir):\n            for filename in os.listdir(custom_apps_dir):\n                if filename.endswith('.cfg'):\n                    config_files.add(os.path.join(custom_apps_dir,\n                                                  filename))\n                    custom_files.add(filename)\n        for filename in os.listdir(apps_dir):\n            if filename.endswith('.cfg') and filename not in custom_files:\n                config_files.add(os.path.join(apps_dir, filename))\n        return config_files",
    "docstring": "Return the application configuration files.\n\n        Return a list of configuration files describing the apps supported by\n        Mackup. The files return are absolute full path to those files.\n        e.g. /usr/lib/mackup/applications/bash.cfg\n\n        Only one config file per application should be returned, custom config\n        having a priority over stock config.\n\n        Returns:\n            set of strings."
  },
  {
    "code": "def usage(path):\n    out = __salt__['cmd.run_all'](\"btrfs filesystem usage {0}\".format(path))\n    salt.utils.fsutils._verify_run(out)\n    ret = {}\n    for section in out['stdout'].split(\"\\n\\n\"):\n        if section.startswith(\"Overall:\\n\"):\n            ret['overall'] = _usage_overall(section)\n        elif section.startswith(\"Unallocated:\\n\"):\n            ret['unallocated'] = _usage_unallocated(section)\n        else:\n            ret.update(_usage_specific(section))\n    return ret",
    "docstring": "Show in which disk the chunks are allocated.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' btrfs.usage /your/mountpoint"
  },
  {
    "code": "def multiple_domains(self):\n        domains = []\n        for cookie in iter(self):\n            if cookie.domain is not None and cookie.domain in domains:\n                return True\n            domains.append(cookie.domain)\n        return False",
    "docstring": "Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool"
  },
  {
    "code": "def _renderBlockDevice(self, block_device, build):\n        rendered_block_device = yield build.render(block_device)\n        if rendered_block_device['volume_size'] is None:\n            source_type = rendered_block_device['source_type']\n            source_uuid = rendered_block_device['uuid']\n            volume_size = self._determineVolumeSize(source_type, source_uuid)\n            rendered_block_device['volume_size'] = volume_size\n        return rendered_block_device",
    "docstring": "Render all of the block device's values."
  },
  {
    "code": "def get_isolated_cpus():\n    path = sysfs_path('devices/system/cpu/isolated')\n    isolated = read_first_line(path)\n    if isolated:\n        return parse_cpu_list(isolated)\n    cmdline = read_first_line(proc_path('cmdline'))\n    if cmdline:\n        match = re.search(r'\\bisolcpus=([^ ]+)', cmdline)\n        if match:\n            isolated = match.group(1)\n            return parse_cpu_list(isolated)\n    return None",
    "docstring": "Get the list of isolated CPUs.\n\n    Return a sorted list of CPU identifiers, or return None if no CPU is\n    isolated."
  },
  {
    "code": "def subscribe(self, topic, callback, qos):\n        if topic in self.topics:\n            return\n        def _message_callback(mqttc, userdata, msg):\n            callback(msg.topic, msg.payload.decode('utf-8'), msg.qos)\n        self._mqttc.subscribe(topic, qos)\n        self._mqttc.message_callback_add(topic, _message_callback)\n        self.topics[topic] = callback",
    "docstring": "Subscribe to an MQTT topic."
  },
  {
    "code": "def make_flatten(decl_or_decls):\n    def proceed_single(decl):\n        answer = [decl]\n        if not isinstance(decl, scopedef_t):\n            return answer\n        for elem in decl.declarations:\n            if isinstance(elem, scopedef_t):\n                answer.extend(proceed_single(elem))\n            else:\n                answer.append(elem)\n        return answer\n    decls = []\n    if isinstance(decl_or_decls, list):\n        decls.extend(decl_or_decls)\n    else:\n        decls.append(decl_or_decls)\n    answer = []\n    for decl in decls:\n        answer.extend(proceed_single(decl))\n    return answer",
    "docstring": "Converts tree representation of declarations to flatten one.\n\n    :param decl_or_decls: reference to list of declaration's or single\n        declaration\n    :type decl_or_decls: :class:`declaration_t` or [ :class:`declaration_t` ]\n    :rtype: [ all internal declarations ]"
  },
  {
    "code": "def setup_paths(self, environ, coll, record=False):\n        if not coll or not self.warcserver.root_dir:\n            return\n        if coll != '$root':\n            pop_path_info(environ)\n            if record:\n                pop_path_info(environ)\n        paths = [self.warcserver.root_dir]\n        if coll != '$root':\n            paths.append(coll)\n        paths.append(self.templates_dir)\n        environ['pywb.templates_dir'] = '/'.join(paths)",
    "docstring": "Populates the WSGI environment dictionary with the path information necessary to perform a response for\n        content or record.\n\n        :param dict environ: The WSGI environment dictionary for the request\n        :param str coll: The name of the collection the record is to be served from\n        :param bool record: Should the content being served by recorded (save to a warc). Only valid in record mode"
  },
  {
    "code": "def get_wrapper_class(backend_name):\n    try:\n        return _WRAPPERS[backend_name]\n    except KeyError:\n        if backend_name == 'ni':\n            from .ctwrapper import NIVisaLibrary\n            _WRAPPERS['ni'] = NIVisaLibrary\n            return NIVisaLibrary\n    try:\n        pkg = __import__('pyvisa-' + backend_name)\n        _WRAPPERS[backend_name] = cls = pkg.WRAPPER_CLASS\n        return cls\n    except ImportError:\n        raise ValueError('Wrapper not found: No package named pyvisa-%s' % backend_name)",
    "docstring": "Return the WRAPPER_CLASS for a given backend.\n\n    :rtype: pyvisa.highlevel.VisaLibraryBase"
  },
  {
    "code": "def tokenize_words(self):\n        if not self.is_tagged(SENTENCES):\n            self.tokenize_sentences()\n        tok = self.__word_tokenizer\n        text = self.text\n        dicts = []\n        for sentence in self[SENTENCES]:\n            sent_start, sent_end = sentence[START], sentence[END]\n            sent_text = text[sent_start:sent_end]\n            spans = tok.span_tokenize(sent_text)\n            for start, end in spans:\n                dicts.append({START: start+sent_start, END: end+sent_start, TEXT: sent_text[start:end]})\n        self[WORDS] = dicts\n        return self",
    "docstring": "Apply word tokenization and create ``words`` layer.\n\n        Automatically creates ``paragraphs`` and ``sentences`` layers."
  },
  {
    "code": "def checkout(self, revision, options):\n        rev = revision.key\n        self.repo.git.checkout(rev)",
    "docstring": "Checkout a specific revision.\n\n        :param revision: The revision identifier.\n        :type  revision: :class:`Revision`\n\n        :param options: Any additional options.\n        :type  options: ``dict``"
  },
  {
    "code": "def _sort(self, session_groups):\n    session_groups.sort(key=operator.attrgetter('name'))\n    for col_param, extractor in reversed(list(zip(self._request.col_params,\n                                                  self._extractors))):\n      if col_param.order == api_pb2.ORDER_UNSPECIFIED:\n        continue\n      if col_param.order == api_pb2.ORDER_ASC:\n        session_groups.sort(\n            key=_create_key_func(\n                extractor,\n                none_is_largest=not col_param.missing_values_first))\n      elif col_param.order == api_pb2.ORDER_DESC:\n        session_groups.sort(\n            key=_create_key_func(\n                extractor,\n                none_is_largest=col_param.missing_values_first),\n            reverse=True)\n      else:\n        raise error.HParamsError('Unknown col_param.order given: %s' %\n                                 col_param)",
    "docstring": "Sorts 'session_groups' in place according to _request.col_params."
  },
  {
    "code": "def get_next(self, skip=1):\n        r\n        if super(Reader, self)._next(skip):\n            entry = super(Reader, self)._get_all()\n            if entry:\n                entry['__REALTIME_TIMESTAMP'] = self._get_realtime()\n                entry['__MONOTONIC_TIMESTAMP'] = self._get_monotonic()\n                entry['__CURSOR'] = self._get_cursor()\n                return self._convert_entry(entry)\n        return dict()",
    "docstring": "r\"\"\"Return the next log entry as a dictionary.\n\n        Entries will be processed with converters specified during Reader\n        creation.\n\n        Optional `skip` value will return the `skip`-th log entry.\n\n        Currently a standard dictionary of fields is returned, but in the\n        future this might be changed to a different mapping type, so the\n        calling code should not make assumptions about a specific type."
  },
  {
    "code": "def process_request_thread(self, request, client_address):\n        try:\n            self.finish_request(request, client_address)\n            self.shutdown_request(request)\n        except Exception as e:\n            self.logger.error(e)\n            self.handle_error(request, client_address)\n            self.shutdown_request(request)",
    "docstring": "Process the request."
  },
  {
    "code": "def current_memory_usage():\n    import psutil\n    proc = psutil.Process(os.getpid())\n    meminfo = proc.memory_info()\n    rss = meminfo[0]\n    vms = meminfo[1]\n    return rss",
    "docstring": "Returns this programs current memory usage in bytes"
  },
  {
    "code": "def match_date(self, value, strict=False):\n        value = stringify(value)\n        try:\n            parse(value)\n        except Exception:\n            self.shout('Value %r is not a valid date', strict, value)",
    "docstring": "if value is a date"
  },
  {
    "code": "def add_data(self, request, pk=None):\n        resp = super().add_data(request, pk)\n        entity = self.get_object()\n        for collection in entity.collections.all():\n            collection.data.add(*request.data['ids'])\n        return resp",
    "docstring": "Add data to Entity and it's collection."
  },
  {
    "code": "def word_ends(self):\n        if not self.is_tagged(WORDS):\n            self.tokenize_words()\n        return self.ends(WORDS)",
    "docstring": "The list of end positions representing ``words`` layer elements."
  },
  {
    "code": "def _login(self, user, password, restrict_login=None):\n        payload = {'login': user, 'password': password}\n        if restrict_login:\n            payload['restrict_login'] = True\n        return self._proxy.User.login(payload)",
    "docstring": "Backend login method for Bugzilla3"
  },
  {
    "code": "def network_lpf(network, snapshots=None, skip_pre=False):\n    _network_prepare_and_run_pf(network, snapshots, skip_pre, linear=True)",
    "docstring": "Linear power flow for generic network.\n\n    Parameters\n    ----------\n    snapshots : list-like|single snapshot\n        A subset or an elements of network.snapshots on which to run\n        the power flow, defaults to network.snapshots\n    skip_pre: bool, default False\n        Skip the preliminary steps of computing topology, calculating\n        dependent values and finding bus controls.\n\n    Returns\n    -------\n    None"
  },
  {
    "code": "def not_modified(cls, errors=None):\n        if cls.expose_status:\n            cls.response.content_type = 'application/json'\n            cls.response._status_line = '304 Not Modified'\n        return cls(304, None, errors).to_json",
    "docstring": "Shortcut API for HTTP 304 `Not Modified` response.\n\n        Args:\n            errors (list): Response key/value data.\n\n        Returns:\n            WSResponse Instance."
  },
  {
    "code": "def get_indic_syllabic_category_property(value, is_bytes=False):\n    obj = unidata.ascii_indic_syllabic_category if is_bytes else unidata.unicode_indic_syllabic_category\n    if value.startswith('^'):\n        negated = value[1:]\n        value = '^' + unidata.unicode_alias['indicsyllabiccategory'].get(negated, negated)\n    else:\n        value = unidata.unicode_alias['indicsyllabiccategory'].get(value, value)\n    return obj[value]",
    "docstring": "Get `INDIC SYLLABIC CATEGORY` property."
  },
  {
    "code": "def to_meta(self, md5=None, file=None):\n        if not md5:\n            if not file:\n                raise ValueError('Must specify either file or md5')\n            md5 = md5_for_file(file)\n            size = os.stat(file).st_size\n        else:\n            size = None\n        return {\n            'id': self.id_,\n            'identity': json.dumps(self.dict),\n            'name': self.sname,\n            'fqname': self.fqname,\n            'md5': md5,\n            'size': size\n        }",
    "docstring": "Return a dictionary of metadata, for use in the Remote api."
  },
  {
    "code": "def set_working_directory(working_directory):\n    logger.debug(\"starting\")\n    logger.debug(f\"adding {working_directory} to sys.paths\")\n    sys.path.append(working_directory)\n    logger.debug(\"done\")",
    "docstring": "Add working_directory to sys.paths.\n\n    This allows dynamic loading of arbitrary python modules in cwd.\n\n    Args:\n        working_directory: string. path to add to sys.paths"
  },
  {
    "code": "def read(fobj, **kwargs):\n    fsamp, arr = wavfile.read(fobj, **kwargs)\n    return TimeSeries(arr, sample_rate=fsamp)",
    "docstring": "Read a WAV file into a `TimeSeries`\n\n    Parameters\n    ----------\n    fobj : `file`, `str`\n        open file-like object or filename to read from\n\n    **kwargs\n        all keyword arguments are passed onto :func:`scipy.io.wavfile.read`\n\n    See also\n    --------\n    scipy.io.wavfile.read\n        for details on how the WAV file is actually read\n\n    Examples\n    --------\n    >>> from gwpy.timeseries import TimeSeries\n    >>> t = TimeSeries.read('test.wav')"
  },
  {
    "code": "def linkify_hostgroups_hosts(self, hosts):\n        for hostgroup in self:\n            members = hostgroup.get_hosts()\n            new_members = []\n            for member in members:\n                member = member.strip()\n                if not member:\n                    continue\n                if member == '*':\n                    new_members.extend(list(hosts.items.keys()))\n                else:\n                    host = hosts.find_by_name(member)\n                    if host is not None:\n                        new_members.append(host.uuid)\n                        if hostgroup.uuid not in host.hostgroups:\n                            host.hostgroups.append(hostgroup.uuid)\n                    else:\n                        hostgroup.add_unknown_members(member)\n            new_members = list(set(new_members))\n            hostgroup.replace_members(new_members)",
    "docstring": "We just search for each hostgroup the id of the hosts\n        and replace the names by the found identifiers\n\n        :param hosts: object Hosts\n        :type hosts: alignak.objects.host.Hosts\n        :return: None"
  },
  {
    "code": "def encode_int(n):\n    global ENCODED_INT_CACHE\n    try:\n        return ENCODED_INT_CACHE[n]\n    except KeyError:\n        pass\n    if n < MIN_29B_INT or n > MAX_29B_INT:\n        raise OverflowError(\"Out of range\")\n    if n < 0:\n        n += 0x20000000\n    bytes = ''\n    real_value = None\n    if n > 0x1fffff:\n        real_value = n\n        n >>= 1\n        bytes += chr(0x80 | ((n >> 21) & 0xff))\n    if n > 0x3fff:\n        bytes += chr(0x80 | ((n >> 14) & 0xff))\n    if n > 0x7f:\n        bytes += chr(0x80 | ((n >> 7) & 0xff))\n    if real_value is not None:\n        n = real_value\n    if n > 0x1fffff:\n        bytes += chr(n & 0xff)\n    else:\n        bytes += chr(n & 0x7f)\n    ENCODED_INT_CACHE[n] = bytes\n    return bytes",
    "docstring": "Encodes an int as a variable length signed 29-bit integer as defined by\n    the spec.\n\n    @param n: The integer to be encoded\n    @return: The encoded string\n    @rtype: C{str}\n    @raise OverflowError: Out of range."
  },
  {
    "code": "def enable_shuffle(self, value=None):\n        if value is None:\n            value = not self.shuffled\n        spotifyconnect.Error.maybe_raise(lib.SpPlaybackEnableShuffle(value))",
    "docstring": "Enable shuffle mode"
  },
  {
    "code": "def entry_snapshots(self, space_id, environment_id, entry_id):\n        return SnapshotsProxy(self, space_id, environment_id, entry_id, 'entries')",
    "docstring": "Provides access to entry snapshot management methods.\n\n        API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots\n\n        :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object.\n        :rtype: contentful.snapshots_proxy.SnapshotsProxy\n\n        Usage:\n\n            >>> entry_snapshots_proxy = client.entry_snapshots('cfexampleapi', 'master', 'nyancat')\n            <SnapshotsProxy[entries] space_id=\"cfexampleapi\" environment_id=\"master\" parent_resource_id=\"nyancat\">"
  },
  {
    "code": "def job_file(self):\n        job_file_name = '%s.job' % (self.name)\n        job_file_path = os.path.join(self.initial_dir, job_file_name)\n        self._job_file = job_file_path\n        return self._job_file",
    "docstring": "The path to the submit description file representing this job."
  },
  {
    "code": "def transcribe_to_modern(self, text) :\r\n\t\tphoneme_words = self.transcribe(text, as_phonemes = True)\r\n\t\twords = [''.join([self.to_modern[0][phoneme.ipa] for phoneme in word]) for word in phoneme_words]\r\n\t\tmodern_text =  ' '.join(words)\r\n\t\tfor regexp, replacement in self.to_modern[1]:\r\n\t\t\tmodern_text = re.sub(regexp, replacement, modern_text)\r\n\t\treturn modern_text",
    "docstring": "A very first attempt at trancribing from IPA to some modern orthography.\r\n\t\tThe method is intended to provide the student with clues to the pronounciation of old orthographies."
  },
  {
    "code": "def _treat_devices_removed(self):\n        for device in self._removed_ports.copy():\n            eventlet.spawn_n(self._process_removed_port, device)",
    "docstring": "Process the removed devices."
  },
  {
    "code": "def _dump(f, mesh):\n    dae = mesh_to_collada(mesh)\n    dae.write(f.name)",
    "docstring": "Writes a mesh to collada file format."
  },
  {
    "code": "def list_rules(region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    try:\n        ret = []\n        NextToken = ''\n        while NextToken is not None:\n            args = {'NextToken': NextToken} if NextToken else {}\n            r = conn.list_rules(**args)\n            ret += r.get('Rules', [])\n            NextToken = r.get('NextToken')\n        return ret\n    except ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "List, with details, all Cloudwatch Event rules visible in the current scope.\n\n    CLI example::\n\n        salt myminion boto_cloudwatch_event.list_rules region=us-east-1"
  },
  {
    "code": "def build_indentation_list(parser: str = 'github'):\n    r\n    indentation_list = list()\n    if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'\n            or parser == 'commonmarker' or parser == 'redcarpet'):\n        for i in range(0, md_parser[parser]['header']['max_levels']):\n            indentation_list.append(False)\n    return indentation_list",
    "docstring": "r\"\"\"Create a data structure that holds the state of indentations.\n\n    :parameter parser: decides the length of the list.\n         Defaults to ``github``.\n    :type parser: str\n    :returns: indentation_list, a list that contains the state of\n         indentations given a header type.\n    :rtype: list\n    :raises: a built-in exception."
  },
  {
    "code": "def map(self, func):\n\t\treturn dict((key, func(value)) for key, value in self.iteritems())",
    "docstring": "Return a dictionary of the results of func applied to each\n\t\tof the segmentlist objects in self.\n\n\t\tExample:\n\n\t\t>>> x = segmentlistdict()\n\t\t>>> x[\"H1\"] = segmentlist([segment(0, 10)])\n\t\t>>> x[\"H2\"] = segmentlist([segment(5, 15)])\n\t\t>>> x.map(lambda l: 12 in l)\n\t\t{'H2': True, 'H1': False}"
  },
  {
    "code": "def local_manager_is_default(self, adm_gid, gid):\n        config = self.root['settings']['ugm_localmanager'].attrs\n        rule = config[adm_gid]\n        if gid not in rule['target']:\n            raise Exception(u\"group '%s' not managed by '%s'\" % (gid, adm_gid))\n        return gid in rule['default']",
    "docstring": "Check whether gid is default group for local manager group."
  },
  {
    "code": "def terminal_sexy_to_wal(data):\n    data[\"colors\"] = {}\n    data[\"special\"] = {\n        \"foreground\": data[\"foreground\"],\n        \"background\": data[\"background\"],\n        \"cursor\": data[\"color\"][9]\n    }\n    for i, color in enumerate(data[\"color\"]):\n        data[\"colors\"][\"color%s\" % i] = color\n    return data",
    "docstring": "Convert terminal.sexy json schema to wal."
  },
  {
    "code": "def initalize(self, physics_dta):\n        self.rotation = random.randint(self.rotation_range[0], self.rotation_range[1])\n        self.current_time = 0.0\n        self.color = self.start_color\n        self.scale = self.start_scale\n        self.physics = physics_dta",
    "docstring": "Prepare our particle for use.\n        physics_dta describes the velocity, coordinates, and acceleration of the particle."
  },
  {
    "code": "def draw_lines(self, *points):\n        point_array = ffi.new('SDL_Point[]', len(points))\n        for i, p in enumerate(points):\n            point_array[i] = p._ptr[0]\n        check_int_err(lib.SDL_RenderDrawLines(self._ptr, point_array, len(points)))",
    "docstring": "Draw a series of connected lines on the current rendering target.\n\n        Args:\n            *points (Point): The points along the lines.\n\n        Raises:\n            SDLError: If an error is encountered."
  },
  {
    "code": "def my_on_connect(client):\n    client.send('You connected from %s\\n' % client.addrport())\n    if CLIENTS:\n        client.send('Also connected are:\\n')\n        for neighbor in CLIENTS:\n            client.send('%s\\n' % neighbor.addrport())\n    else:\n        client.send('Sadly, you are alone.\\n')\n    CLIENTS.append(client)",
    "docstring": "Example on_connect handler."
  },
  {
    "code": "def bods2c(name):\n    name = stypes.stringToCharP(name)\n    code = ctypes.c_int(0)\n    found = ctypes.c_int(0)\n    libspice.bods2c_c(name, ctypes.byref(code), ctypes.byref(found))\n    return code.value, bool(found.value)",
    "docstring": "Translate a string containing a body name or ID code to an integer code.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bods2c_c.html\n\n    :param name: String to be translated to an ID code.\n    :type name: str\n    :return: Integer ID code corresponding to name.\n    :rtype: int"
  },
  {
    "code": "def add_constant(self, stream, value):\n        if stream in self.constant_database:\n            raise ArgumentError(\"Attempted to set the same constant twice\", stream=stream, old_value=self.constant_database[stream], new_value=value)\n        self.constant_database[stream] = value",
    "docstring": "Store a constant value for use in this sensor graph.\n\n        Constant assignments occur after all sensor graph nodes have been\n        allocated since they must be propogated to all appropriate virtual\n        stream walkers.\n\n        Args:\n            stream (DataStream): The constant stream to assign the value to\n            value (int): The value to assign."
  },
  {
    "code": "def transpose(self, trans, scale=\"C\"):\n        if not isinstance(trans, int):\n            raise TypeError(\"Expected integers, not {}\".format(type(trans)))\n        self._root = transpose_note(self._root, trans, scale)\n        if self._on:\n            self._on = transpose_note(self._on, trans, scale)\n        self._reconfigure_chord()",
    "docstring": "Transpose the chord\n\n        :param int trans: Transpose key\n        :param str scale: key scale\n        :return:"
  },
  {
    "code": "def create(self, ticket, payload=None, expires=None):\n        if not payload:\n            payload = True\n        self._client.set(str(ticket), payload, expires)",
    "docstring": "Create a session identifier in memcache associated with ``ticket``."
  },
  {
    "code": "def _eval_meta_as_summary(meta):\n    if meta == '':\n        return False\n    if len(meta)>500:\n        return False\n    if 'login' in meta.lower():\n        return False\n    return True",
    "docstring": "some crude heuristics for now\n    most are implemented on bot-side\n    with domain whitelists"
  },
  {
    "code": "def children(self, unroll=False, skip_not_present=True):\n        for child_inst in self.inst.children:\n            if skip_not_present:\n                if not child_inst.properties.get('ispresent', True):\n                    continue\n            if unroll and isinstance(child_inst, comp.AddressableComponent) and child_inst.is_array:\n                range_list = [range(n) for n in child_inst.array_dimensions]\n                for idxs in itertools.product(*range_list):\n                    N = Node._factory(child_inst, self.env, self)\n                    N.current_idx = idxs\n                    yield N\n            else:\n                yield Node._factory(child_inst, self.env, self)",
    "docstring": "Returns an iterator that provides nodes for all immediate children of\n        this component.\n\n        Parameters\n        ----------\n        unroll : bool\n            If True, any children that are arrays are unrolled.\n\n        skip_not_present : bool\n            If True, skips children whose 'ispresent' property is set to False\n\n        Yields\n        ------\n        :class:`~Node`\n            All immediate children"
  },
  {
    "code": "def doLayout(self, width):\n        self.width = width\n        font_sizes = [0] + [frag.get(\"fontSize\", 0) for frag in self]\n        self.fontSize = max(font_sizes)\n        self.height = self.lineHeight = max(frag * self.LINEHEIGHT for frag in font_sizes)\n        y = (self.lineHeight - self.fontSize)\n        for frag in self:\n            frag[\"y\"] = y\n        return self.height",
    "docstring": "Align words in previous line."
  },
  {
    "code": "def _create_adapter_type(network_adapter, adapter_type,\n                         network_adapter_label=''):\n    log.trace('Configuring virtual machine network '\n              'adapter adapter_type=%s', adapter_type)\n    if adapter_type in ['vmxnet', 'vmxnet2', 'vmxnet3', 'e1000', 'e1000e']:\n        edited_network_adapter = salt.utils.vmware.get_network_adapter_type(\n            adapter_type)\n        if isinstance(network_adapter, type(edited_network_adapter)):\n            edited_network_adapter = network_adapter\n        else:\n            if network_adapter:\n                log.trace('Changing type of \\'%s\\' from \\'%s\\' to \\'%s\\'',\n                          network_adapter.deviceInfo.label,\n                          type(network_adapter).__name__.rsplit(\".\", 1)[1][7:].lower(),\n                          adapter_type)\n    else:\n        if network_adapter:\n            if adapter_type:\n                log.error(\n                    'Cannot change type of \\'%s\\' to \\'%s\\'. Not changing type',\n                    network_adapter.deviceInfo.label, adapter_type\n                )\n            edited_network_adapter = network_adapter\n        else:\n            if not adapter_type:\n                log.trace('The type of \\'%s\\' has not been specified. '\n                          'Creating of default type \\'vmxnet3\\'',\n                          network_adapter_label)\n            edited_network_adapter = vim.vm.device.VirtualVmxnet3()\n    return edited_network_adapter",
    "docstring": "Returns a vim.vm.device.VirtualEthernetCard object specifying a virtual\n    ethernet card information\n\n    network_adapter\n        None or VirtualEthernet object\n\n    adapter_type\n        String, type of adapter\n\n    network_adapter_label\n        string, network adapter name"
  },
  {
    "code": "def _get_groups(self, data):\n        groups = []\n        for attribute in SOURCE_KEYS:\n            for k, v in data[attribute].items():\n                if k == None:\n                    k = 'Sources'\n                if k not in groups:\n                    groups.append(k)\n        for k, v in data['include_files'].items():\n            if k == None:\n                k = 'Includes'\n            if k not in groups:\n                groups.append(k)\n        return groups",
    "docstring": "Get all groups defined"
  },
  {
    "code": "def set_data_type(self, data_type):\n        validate_type(data_type, type(None), *six.string_types)\n        if isinstance(data_type, *six.string_types):\n            data_type = str(data_type).upper()\n        if not data_type in ({None} | set(DSTREAM_TYPE_MAP.keys())):\n            raise ValueError(\"Provided data type not in available set of types\")\n        self._data_type = data_type",
    "docstring": "Set the data type for ths data point\n\n        The data type is actually associated with the stream itself and should\n        not (generally) vary on a point-per-point basis.  That being said, if\n        creating a new stream by writing a datapoint, it may be beneficial to\n        include this information.\n\n        The data type provided should be in the set of available data types of\n        { INTEGER, LONG, FLOAT, DOUBLE, STRING, BINARY, UNKNOWN }."
  },
  {
    "code": "def laplacian_eigenmaps(self, num_dims=None, normed=True, val_thresh=1e-8):\n    L = self.laplacian(normed=normed)\n    return _null_space(L, num_dims, val_thresh, overwrite=True)",
    "docstring": "Laplacian Eigenmaps embedding.\n\n    num_dims : dimension of embedded coordinates, defaults to input dimension\n    normed : used for .laplacian() calculation\n    val_thresh : threshold for omitting vectors with near-zero eigenvalues"
  },
  {
    "code": "def get_addr_of_native_method(self, soot_method):\n        for name, symbol in self.native_symbols.items():\n            if soot_method.matches_with_native_name(native_method=name):\n                l.debug(\"Found native symbol '%s' @ %x matching Soot method '%s'\",\n                        name, symbol.rebased_addr, soot_method)\n                return symbol.rebased_addr\n        native_symbols = \"\\n\".join(self.native_symbols.keys())\n        l.warning(\"No native method found that matches the Soot method '%s'. \"\n                  \"Skipping statement.\", soot_method.name)\n        l.debug(\"Available symbols (prefix + encoded class path + encoded method \"\n                \"name):\\n%s\", native_symbols)\n        return None",
    "docstring": "Get address of the implementation from a native declared Java function.\n\n        :param soot_method: Method descriptor of a native declared function.\n        :return: CLE address of the given method."
  },
  {
    "code": "def generate_http_manifest(self):\n        base_path = os.path.dirname(self.translate_path(self.path))\n        self.dataset = dtoolcore.DataSet.from_uri(base_path)\n        admin_metadata_fpath = os.path.join(base_path, \".dtool\", \"dtool\")\n        with open(admin_metadata_fpath) as fh:\n            admin_metadata = json.load(fh)\n        http_manifest = {\n            \"admin_metadata\": admin_metadata,\n            \"manifest_url\": self.generate_url(\".dtool/manifest.json\"),\n            \"readme_url\": self.generate_url(\"README.yml\"),\n            \"overlays\": self.generate_overlay_urls(),\n            \"item_urls\": self.generate_item_urls()\n        }\n        return bytes(json.dumps(http_manifest), \"utf-8\")",
    "docstring": "Return http manifest.\n\n        The http manifest is the resource that defines a dataset as HTTP\n        enabled (published)."
  },
  {
    "code": "def predict(model, x):\n    if not hasattr(x, \"chunks\") and hasattr(x, \"to_dask_array\"):\n        x = x.to_dask_array()\n    assert x.ndim == 2\n    if len(x.chunks[1]) > 1:\n        x = x.rechunk(chunks=(x.chunks[0], sum(x.chunks[1])))\n    func = partial(_predict, model)\n    xx = np.zeros((1, x.shape[1]), dtype=x.dtype)\n    dt = model.predict(xx).dtype\n    return x.map_blocks(func, chunks=(x.chunks[0], (1,)), dtype=dt).squeeze()",
    "docstring": "Predict with a scikit learn model\n\n    Parameters\n    ----------\n    model : scikit learn classifier\n    x : dask Array\n\n    See docstring for ``da.learn.fit``"
  },
  {
    "code": "def build(self, n, vec):\n    for i in range(-self.maxDisplacement, self.maxDisplacement+1):\n      next = vec + [i]\n      if n == 1:\n        print '{:>5}\\t'.format(next), \" = \",\n        printSequence(self.encodeMotorInput(next))\n      else:\n        self.build(n-1, next)",
    "docstring": "Recursive function to help print motor coding scheme."
  },
  {
    "code": "def update_gradebook(self, gradebook_form):\n        if self._catalog_session is not None:\n            return self._catalog_session.update_catalog(catalog_form=gradebook_form)\n        collection = JSONClientValidated('grading',\n                                         collection='Gradebook',\n                                         runtime=self._runtime)\n        if not isinstance(gradebook_form, ABCGradebookForm):\n            raise errors.InvalidArgument('argument type is not an GradebookForm')\n        if not gradebook_form.is_for_update():\n            raise errors.InvalidArgument('the GradebookForm is for update only, not create')\n        try:\n            if self._forms[gradebook_form.get_id().get_identifier()] == UPDATED:\n                raise errors.IllegalState('gradebook_form already used in an update transaction')\n        except KeyError:\n            raise errors.Unsupported('gradebook_form did not originate from this session')\n        if not gradebook_form.is_valid():\n            raise errors.InvalidArgument('one or more of the form elements is invalid')\n        collection.save(gradebook_form._my_map)\n        self._forms[gradebook_form.get_id().get_identifier()] = UPDATED\n        return objects.Gradebook(osid_object_map=gradebook_form._my_map, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Updates an existing gradebook.\n\n        arg:    gradebook_form (osid.grading.GradebookForm): the form\n                containing the elements to be updated\n        raise:  IllegalState - ``gradebook_form`` already used in an\n                update transaction\n        raise:  InvalidArgument - the form contains an invalid value\n        raise:  NullArgument - ``gradebook_form`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        raise:  Unsupported - ``gradebook_form did not originate from\n                get_gradebook_form_for_update()``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def stop(self, timeout_s=None):\n    self.stopped.set()\n    if self.thread:\n      self.thread.join(timeout_s)\n      return not self.thread.isAlive()\n    else:\n      return True",
    "docstring": "Stops the interval.\n\n    If a timeout is provided and stop returns False then the thread is\n    effectively abandoned in whatever state it was in (presumably dead-locked).\n\n    Args:\n      timeout_s: The time in seconds to wait on the thread to finish.  By\n          default it's forever.\n    Returns:\n      False if a timeout was provided and we timed out."
  },
  {
    "code": "def create(self, weight, priority, enabled, friendly_name, sip_url):\n        data = values.of({\n            'Weight': weight,\n            'Priority': priority,\n            'Enabled': enabled,\n            'FriendlyName': friendly_name,\n            'SipUrl': sip_url,\n        })\n        payload = self._version.create(\n            'POST',\n            self._uri,\n            data=data,\n        )\n        return OriginationUrlInstance(self._version, payload, trunk_sid=self._solution['trunk_sid'], )",
    "docstring": "Create a new OriginationUrlInstance\n\n        :param unicode weight: The value that determines the relative load the URI should receive compared to others with the same priority\n        :param unicode priority: The relative importance of the URI\n        :param bool enabled: Whether the URL is enabled\n        :param unicode friendly_name: A string to describe the resource\n        :param unicode sip_url: The SIP address you want Twilio to route your Origination calls to\n\n        :returns: Newly created OriginationUrlInstance\n        :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance"
  },
  {
    "code": "def _signal(self, sig, pid=None):\n        log = self._params.get('log', self._discard)\n        if pid is None:\n            pids = self.get_pids()\n        else:\n            pids = [pid]\n        for pid in pids:\n            try:\n                os.kill(pid, sig)\n                log.debug(\"Signalled '%s' pid %d with %s\", self._name, pid, utils.signame(sig))\n            except Exception as e:\n                log.warning(\"Failed to signal '%s' pid %d with %s -- %s\", self._name, pid, utils.signame(sig), e)",
    "docstring": "Send a signal to one or all pids associated with this task.  Never fails, but logs\n        signalling faults as warnings."
  },
  {
    "code": "def locked(self):\n        conn = self._get_connection()\n        try:\n            self._lock(conn)\n            yield conn\n        finally:\n            self._unlock(conn)",
    "docstring": "Context generator for `with` statement, yields thread-safe connection.\n\n        :return: thread-safe connection\n        :rtype: pydbal.connection.Connection"
  },
  {
    "code": "def get_stetson_k(self, mag, avg, err):\n        residual = (mag - avg) / err\n        stetson_k = np.sum(np.fabs(residual)) \\\n                    / np.sqrt(np.sum(residual * residual)) / np.sqrt(len(mag))\n        return stetson_k",
    "docstring": "Return Stetson K feature.\n\n        Parameters\n        ----------\n        mag : array_like\n            An array of magnitude.\n        avg : float\n            An average value of magnitudes.\n        err : array_like\n            An array of magnitude errors.\n\n        Returns\n        -------\n        stetson_k : float\n            Stetson K value."
  },
  {
    "code": "def get_unassigned_ports(self):\n        uri = \"{}/unassignedPortsForPortMonitor\".format(self.data[\"uri\"])\n        response = self._helper.do_get(uri)\n        return self._helper.get_members(response)",
    "docstring": "Gets the collection ports from the member interconnects\n        which are eligible for assignment to an anlyzer port\n\n        Returns:\n            dict: Collection of ports"
  },
  {
    "code": "def get_permissions_for_role(role, brain_or_object):\n    obj = api.get_object(brain_or_object)\n    valid_roles = get_valid_roles_for(obj)\n    if role not in valid_roles:\n        raise ValueError(\"The Role '{}' is invalid.\".format(role))\n    out = []\n    for item in obj.ac_inherited_permissions(1):\n        name, value = item[:2]\n        permission = Permission(name, value, obj)\n        if role in permission.getRoles():\n            out.append(name)\n    return out",
    "docstring": "Return the permissions of the role which are granted on the object\n\n    Code extracted from `IRoleManager.permissionsOfRole`\n\n    :param role: The role to check the permission\n    :param brain_or_object: Catalog brain or object\n    :returns: List of permissions of the role"
  },
  {
    "code": "def aggregate(self, dataset_ids=None, boundary='exact', side='left', func='mean', **dim_kwargs):\n        new_scn = self.copy(datasets=dataset_ids)\n        for src_area, ds_ids in new_scn.iter_by_area():\n            if src_area is None:\n                for ds_id in ds_ids:\n                    new_scn.datasets[ds_id] = self[ds_id]\n                continue\n            if boundary != 'exact':\n                raise NotImplementedError(\"boundary modes appart from 'exact' are not implemented yet.\")\n            target_area = src_area.aggregate(**dim_kwargs)\n            resolution = max(target_area.pixel_size_x, target_area.pixel_size_y)\n            for ds_id in ds_ids:\n                res = self[ds_id].coarsen(boundary=boundary, side=side, func=func, **dim_kwargs)\n                new_scn.datasets[ds_id] = getattr(res, func)()\n                new_scn.datasets[ds_id].attrs['area'] = target_area\n                new_scn.datasets[ds_id].attrs['resolution'] = resolution\n        return new_scn",
    "docstring": "Create an aggregated version of the Scene.\n\n        Args:\n            dataset_ids (iterable): DatasetIDs to include in the returned\n                                    `Scene`. Defaults to all datasets.\n            func (string): Function to apply on each aggregation window. One of\n                           'mean', 'sum', 'min', 'max', 'median', 'argmin',\n                           'argmax', 'prod', 'std', 'var'.\n                           'mean' is the default.\n            boundary: Not implemented.\n            side: Not implemented.\n            dim_kwargs: the size of the windows to aggregate.\n\n        Returns:\n            A new aggregated scene\n\n        See also:\n            xarray.DataArray.coarsen\n\n        Example:\n            `scn.aggregate(func='min', x=2, y=2)` will aggregate 2x2 pixels by\n            applying the `min` function."
  },
  {
    "code": "def _prepare(self, data, groupname):\n        if groupname in self.h5file:\n            del self.h5file[groupname]\n        group = self.h5file.create_group(groupname)\n        group.attrs['version'] = self.version\n        data.init_group(\n            group, self.chunk_size, self.compression, self.compression_opts)\n        return group",
    "docstring": "Clear the group if existing and initialize empty datasets."
  },
  {
    "code": "def assertHeader(self, name, value=None, *args, **kwargs):\n        return name in self.raw_headers and (\n            True if value is None else self.raw_headers[name] == value)",
    "docstring": "Returns `True` if ``name`` was in the headers and, if ``value`` is\n        True, whether or not the values match, or `False` otherwise."
  },
  {
    "code": "def name2unicode(name):\n    if name in glyphname2unicode:\n        return glyphname2unicode[name]\n    m = STRIP_NAME.search(name)\n    if not m:\n        raise KeyError(name)\n    return unichr(int(m.group(0)))",
    "docstring": "Converts Adobe glyph names to Unicode numbers."
  },
  {
    "code": "def fromseconds(cls, seconds):\n        try:\n            seconds = int(seconds)\n        except TypeError:\n            seconds = int(seconds.flatten()[0])\n        return cls(datetime.timedelta(0, int(seconds)))",
    "docstring": "Return a |Period| instance based on a given number of seconds."
  },
  {
    "code": "def request(self, request_method, api_method, *args, **kwargs):\n        url = self._build_url(api_method)\n        resp = requests.request(request_method, url, *args, **kwargs)\n        try:\n            rv = resp.json()\n        except ValueError:\n            raise RequestFailedError(resp, 'not a json body')\n        if not resp.ok:\n            raise RequestFailedError(resp, rv.get('error'))\n        return rv",
    "docstring": "Perform a request.\n\n        Args:\n            request_method: HTTP method for this request.\n            api_method: API method name for this request.\n            *args: Extra arguments to pass to the request.\n            **kwargs: Extra keyword arguments to pass to the request.\n\n        Returns:\n            A dict contains the request response data.\n\n        Raises:\n            RequestFailedError: Raises when BearyChat's OpenAPI responses\n                with status code != 2xx"
  },
  {
    "code": "def make_vbox_dirs(max_vbox_id, output_dir, topology_name):\n    if max_vbox_id is not None:\n        for i in range(1, max_vbox_id + 1):\n            vbox_dir = os.path.join(output_dir, topology_name + '-files',\n                                    'vbox', 'vm-%s' % i)\n            os.makedirs(vbox_dir)",
    "docstring": "Create VirtualBox working directories if required\n\n    :param int max_vbox_id: Number of directories to create\n    :param str output_dir: Output directory\n    :param str topology_name: Topology name"
  },
  {
    "code": "def csvtolist(inputstr):\n    reader = csv.reader([inputstr], skipinitialspace=True)\n    output = []\n    for r in reader:\n        output += r\n    return output",
    "docstring": "converts a csv string into a list"
  },
  {
    "code": "def translatePath(path):\n    valid_dirs = ['xbmc', 'home', 'temp', 'masterprofile', 'profile',\n        'subtitles', 'userdata', 'database', 'thumbnails', 'recordings',\n        'screenshots', 'musicplaylists', 'videoplaylists', 'cdrips', 'skin',\n    ]\n    assert path.startswith('special://'), 'Not a valid special:// path.'\n    parts = path.split('/')[2:]\n    assert len(parts) > 1, 'Need at least a single root directory'\n    assert parts[0] in valid_dirs, '%s is not a valid root dir.' % parts[0]\n    _create_dir(os.path.join(TEMP_DIR, parts[0]))\n    return os.path.join(TEMP_DIR, *parts)",
    "docstring": "Creates folders in the OS's temp directory. Doesn't touch any\n    possible XBMC installation on the machine. Attempting to do as\n    little work as possible to enable this function to work seamlessly."
  },
  {
    "code": "def tempoAdjust1(self, tempoFactor):\n    if self.apicalIntersect.any():\n      tempoFactor = tempoFactor * 0.5\n    else:\n      tempoFactor = tempoFactor * 2\n    return tempoFactor",
    "docstring": "Adjust tempo based on recent active apical input only\n\n    :param tempoFactor: scaling signal to MC clock from last sequence item\n    :return: adjusted scaling signal"
  },
  {
    "code": "def add_namespace(self, namespace):\n        if namespace is None:\n            raise ValueError(\"Namespace argument must not be None\")\n        namespace = namespace.strip('/')\n        if namespace in self.namespaces:\n            raise CIMError(\n                CIM_ERR_ALREADY_EXISTS,\n                _format(\"Namespace {0!A} already exists in the mock \"\n                        \"repository\", namespace))\n        self.namespaces[namespace] = True",
    "docstring": "Add a CIM namespace to the mock repository.\n\n        The namespace must not yet exist in the mock repository.\n\n        Note that the default connection namespace is automatically added to\n        the mock repository upon creation of this object.\n\n        Parameters:\n\n          namespace (:term:`string`):\n            The name of the CIM namespace in the mock repository. Must not be\n            `None`. Any leading and trailing slash characters are split off\n            from the provided string.\n\n        Raises:\n\n          ValueError: Namespace argument must not be None\n          CIMError: CIM_ERR_ALREADY_EXISTS if the namespace already exists in\n            the mock repository."
  },
  {
    "code": "def setOutBoundLinkQuality(self, LinkQuality):\n        print '%s call setOutBoundLinkQuality' % self.port\n        print LinkQuality\n        try:\n            cmd = 'macfilter rss add-lqi * %s' % str(LinkQuality)\n            print cmd\n            return self.__sendCommand(cmd)[0] == 'Done'\n        except Exception, e:\n            ModuleHelper.WriteIntoDebugLogger(\"setOutBoundLinkQuality() Error: \" + str(e))",
    "docstring": "set custom LinkQualityIn for all receiving messages from the any address\n\n        Args:\n            LinkQuality: a given custom link quality\n                         link quality/link margin mapping table\n                         3: 21 - 255 (dB)\n                         2: 11 - 20 (dB)\n                         1: 3 - 9 (dB)\n                         0: 0 - 2 (dB)\n\n        Returns:\n            True: successful to set the link quality\n            False: fail to set the link quality"
  },
  {
    "code": "def ltrim(self, key, start, stop):\n        redis_list = self._get_list(key, 'LTRIM')\n        if redis_list:\n            start, stop = self._translate_range(len(redis_list), start, stop)\n            self.redis[self._encode(key)] = redis_list[start:stop + 1]\n        return True",
    "docstring": "Emulate ltrim."
  },
  {
    "code": "def functionFactory(in_code, name, defaults, globals_, imports):\n    def generatedFunction():\n        pass\n    generatedFunction.__code__ = marshal.loads(in_code)\n    generatedFunction.__name__ = name\n    generatedFunction.__defaults = defaults\n    generatedFunction.__globals__.update(pickle.loads(globals_))\n    for key, value in imports.items():\n        imported_module = __import__(value)\n        scoop.logger.debug(\"Dynamically loaded module {0}\".format(value))\n        generatedFunction.__globals__.update({key: imported_module})\n    return generatedFunction",
    "docstring": "Creates a function at runtime using binary compiled inCode"
  },
  {
    "code": "def remove(self, elem):\n        try:\n            return PDeque(self._left_list.remove(elem), self._right_list, self._length - 1)\n        except ValueError:\n            try:\n                return PDeque(self._left_list,\n                               self._right_list.reverse().remove(elem).reverse(), self._length - 1)\n            except ValueError:\n                raise ValueError('{0} not found in PDeque'.format(elem))",
    "docstring": "Return new deque with first element from left equal to elem removed. If no such element is found\n        a ValueError is raised.\n\n        >>> pdeque([2, 1, 2]).remove(2)\n        pdeque([1, 2])"
  },
  {
    "code": "def unique(values):\n    ret = None\n    if isinstance(values, collections.Hashable):\n        ret = set(values)\n    else:\n        ret = []\n        for value in values:\n            if value not in ret:\n                ret.append(value)\n    return ret",
    "docstring": "Removes duplicates from a list.\n\n    .. code-block:: jinja\n\n        {% set my_list = ['a', 'b', 'c', 'a', 'b'] -%}\n        {{ my_list | unique }}\n\n    will be rendered as:\n\n    .. code-block:: text\n\n        ['a', 'b', 'c']"
  },
  {
    "code": "def handle_legacy_tloc(line: str, position: int, tokens: ParseResults) -> ParseResults:\n    log.log(5, 'legacy translocation statement: %s [%d]', line, position)\n    return tokens",
    "docstring": "Handle translocations that lack the ``fromLoc`` and ``toLoc`` entries."
  },
  {
    "code": "def bookmarks(self):\n        cmd = [HG, 'bookmarks']\n        output = self._command(cmd).decode(self.encoding, 'replace')\n        if output.startswith('no bookmarks set'):\n            return []\n        results = []\n        for line in output.splitlines():\n            m = bookmarks_rx.match(line)\n            assert m, 'unexpected output: ' + line\n            results.append(m.group('name'))\n        return results",
    "docstring": "Get list of bookmarks"
  },
  {
    "code": "def del_feature(self, pr_name):\n        if hasattr(self, pr_name):\n            delattr(self, pr_name)\n            self.features.remove(pr_name)",
    "docstring": "Permanently deletes a node's feature."
  },
  {
    "code": "def getMaskIndices(mask):\n  return [\n    list(mask).index(True), len(mask) - 1 - list(mask)[::-1].index(True)\n  ]",
    "docstring": "get lower and upper index of mask"
  },
  {
    "code": "def index_raw_bulk(self, header, document):\n        self.bulker.add(\"%s%s\" % (header, document))\n        return self.flush_bulk()",
    "docstring": "Function helper for fast inserting\n\n        :param header: a string with the bulk header must be ended with a newline\n        :param document: a json document string must be ended with a newline"
  },
  {
    "code": "def preprocess_value(self, value, default=tuple()):\n        if not value:\n            return default\n        if isinstance(value, (list, tuple)):\n            if len(value) == 1 and not value[0]:\n                return default\n        if not isinstance(value, (list, tuple)):\n            value = value,\n        return value",
    "docstring": "Preprocess the value for set"
  },
  {
    "code": "def validate_identifier(self, field):\n        if field.data:\n            field.data = field.data.lower()\n            if Community.get(field.data, with_deleted=True):\n                raise validators.ValidationError(\n                    _('The identifier already exists. '\n                      'Please choose a different one.'))",
    "docstring": "Validate field identifier."
  },
  {
    "code": "def set_position(self, point, reset=False):\n        if isinstance(point, np.ndarray):\n            if point.ndim != 1:\n                point = point.ravel()\n        self.camera.SetPosition(point)\n        if reset:\n            self.reset_camera()\n        self.camera_set = True\n        self._render()",
    "docstring": "sets camera position to a point"
  },
  {
    "code": "def add_user(self, user, is_admin=False):\n        users_count = self.users.all().count()\n        if users_count == 0:\n            is_admin = True\n        org_user = self._org_user_model.objects.create(\n            user=user, organization=self, is_admin=is_admin\n        )\n        if users_count == 0:\n            self._org_owner_model.objects.create(\n                organization=self, organization_user=org_user\n            )\n        user_added.send(sender=self, user=user)\n        return org_user",
    "docstring": "Adds a new user and if the first user makes the user an admin and\n        the owner."
  },
  {
    "code": "def rpc_get_names(self, filename, source, offset):\n        source = get_source(source)\n        if hasattr(self.backend, \"rpc_get_names\"):\n            return self.backend.rpc_get_names(filename, source, offset)\n        else:\n            raise Fault(\"get_names not implemented by current backend\",\n                        code=400)",
    "docstring": "Get all possible names"
  },
  {
    "code": "def add_petabencana_layer(self):\n        from safe.gui.tools.peta_bencana_dialog import PetaBencanaDialog\n        dialog = PetaBencanaDialog(self.iface.mainWindow(), self.iface)\n        dialog.show()",
    "docstring": "Add petabencana layer to the map.\n\n        This uses the PetaBencana API to fetch the latest floods in JK. See\n        https://data.petabencana.id/floods"
  },
  {
    "code": "async def update_version(self):\n        get_version = GetVersion(pyvlx=self)\n        await get_version.do_api_call()\n        if not get_version.success:\n            raise PyVLXException(\"Unable to retrieve version\")\n        self.version = get_version.version\n        get_protocol_version = GetProtocolVersion(pyvlx=self)\n        await get_protocol_version.do_api_call()\n        if not get_protocol_version.success:\n            raise PyVLXException(\"Unable to retrieve protocol version\")\n        self.protocol_version = get_protocol_version.version\n        PYVLXLOG.warning(\n            \"Connected to: %s, protocol version: %s\",\n            self.version, self.protocol_version)",
    "docstring": "Retrieve version and protocol version from API."
  },
  {
    "code": "def _build_request(self, verb, verb_arguments):\n        method = getattr(self._component, verb)\n        method_args = {str(k): v for k, v in verb_arguments.items()}\n        return method(**method_args)",
    "docstring": "Builds HttpRequest object.\n\n        Args:\n            verb (str): Request verb (ex. insert, update, delete).\n            verb_arguments (dict): Arguments to be passed with the request.\n\n        Returns:\n            httplib2.HttpRequest: HttpRequest to be sent to the API."
  },
  {
    "code": "def _list_records(self, rtype=None, name=None, content=None):\n        if name:\n            name = self._relative_name(name)\n        if not rtype:\n            rtype = \"ANY\"\n        filter_query = {\"rdtype\": rtype, \"name\": name, \"content\": content}\n        with localzone.manage(self.filename, self.origin, autosave=True) as zone:\n            records = zone.find_record(**filter_query)\n        result = []\n        for record in records:\n            rdict = {\n                \"type\": record.rdtype,\n                \"name\": self._full_name(record.name),\n                \"ttl\": record.ttl,\n                \"content\": record.content,\n                \"id\": record.hashid,\n            }\n            if rdict[\"type\"] == \"TXT\":\n                rdict[\"content\"] = rdict[\"content\"].replace('\"', \"\")\n            result.append(rdict)\n        LOGGER.debug(\"list_records: %s\", result)\n        return result",
    "docstring": "Return a list of records matching the supplied params. If no params are\n        provided, then return all zone records. If no records are found, return\n        an empty list."
  },
  {
    "code": "def pack(args):\n    \" Parse file or dir, import css, js code and save with prefix \"\n    assert op.exists(args.source), \"Does not exists: %s\" % args.source\n    zeta_pack(args)",
    "docstring": "Parse file or dir, import css, js code and save with prefix"
  },
  {
    "code": "def only_self(self):\n        others, self.others = self.others, []\n        try:\n            yield\n        finally:\n            self.others = others + self.others",
    "docstring": "Only match in self not others."
  },
  {
    "code": "def regs(self):\n        regs = set()\n        for operand in self.operands:\n            if not operand.type.has_reg:\n                continue\n            regs.update(operand.regs)\n        return regs",
    "docstring": "Names of all registers used by the instruction."
  },
  {
    "code": "def _bsecurate_cli_component_file_refs(args):\n    data = curate.component_file_refs(args.files)\n    s = ''\n    for cfile, cdata in data.items():\n        s += cfile + '\\n'\n        rows = []\n        for el, refs in cdata:\n            rows.append(('    ' + el, ' '.join(refs)))\n        s += '\\n'.join(format_columns(rows)) + '\\n\\n'\n    return s",
    "docstring": "Handles the component-file-refs subcommand"
  },
  {
    "code": "def delete_lines(self):\n        cursor = self.textCursor()\n        self.__select_text_under_cursor_blocks(cursor)\n        cursor.removeSelectedText()\n        cursor.deleteChar()\n        return True",
    "docstring": "Deletes the document lines under cursor.\n\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def response(self, in_thread: Optional[bool] = None) -> \"Message\":\n        data = {\"channel\": self[\"channel\"]}\n        if in_thread:\n            if \"message\" in self:\n                data[\"thread_ts\"] = (\n                    self[\"message\"].get(\"thread_ts\") or self[\"message\"][\"ts\"]\n                )\n            else:\n                data[\"thread_ts\"] = self.get(\"thread_ts\") or self[\"ts\"]\n        elif in_thread is None:\n            if \"message\" in self and \"thread_ts\" in self[\"message\"]:\n                data[\"thread_ts\"] = self[\"message\"][\"thread_ts\"]\n            elif \"thread_ts\" in self:\n                data[\"thread_ts\"] = self[\"thread_ts\"]\n        return Message(data)",
    "docstring": "Create a response message.\n\n        Depending on the incoming message the response can be in a thread. By default the response follow where the\n        incoming message was posted.\n\n        Args:\n            in_thread (boolean): Overwrite the `threading` behaviour\n\n        Returns:\n             a new :class:`slack.event.Message`"
  },
  {
    "code": "def setup(service_manager, conf, reload_method=\"reload\"):\n    conf.register_opts(service_opts)\n    _load_service_manager_options(service_manager, conf)\n    def _service_manager_reload():\n        _configfile_reload(conf, reload_method)\n        _load_service_manager_options(service_manager, conf)\n    if os.name != \"posix\":\n        return\n    service_manager.register_hooks(\n        on_new_worker=functools.partial(\n            _new_worker_hook, conf, reload_method),\n        on_reload=_service_manager_reload)",
    "docstring": "Load services configuration from oslo config object.\n\n    It reads ServiceManager and Service configuration options from an\n    oslo_config.ConfigOpts() object. Also It registers a ServiceManager hook to\n    reload the configuration file on reload in the master process and in all\n    children. And then when each child start or reload, the configuration\n    options are logged if the oslo config option 'log_options' is True.\n\n    On children, the configuration file is reloaded before the running the\n    application reload method.\n\n    Options currently supported on ServiceManager and Service:\n    * graceful_shutdown_timeout\n\n    :param service_manager: ServiceManager instance\n    :type service_manager: cotyledon.ServiceManager\n    :param conf: Oslo Config object\n    :type conf: oslo_config.ConfigOpts()\n    :param reload_method: reload or mutate the config files\n    :type reload_method: str \"reload/mutate\""
  },
  {
    "code": "def add_actions_to_context_menu(self, menu):\r\n        inspect_action = create_action(self, _(\"Inspect current object\"),\r\n                                    QKeySequence(get_shortcut('console',\r\n                                                    'inspect current object')),\r\n                                    icon=ima.icon('MessageBoxInformation'),\r\n                                    triggered=self.inspect_object)\r\n        clear_line_action = create_action(self, _(\"Clear line or block\"),\r\n                                          QKeySequence(get_shortcut(\r\n                                                  'console',\r\n                                                  'clear line')),\r\n                                          triggered=self.clear_line)\r\n        reset_namespace_action = create_action(self, _(\"Remove all variables\"),\r\n                                               QKeySequence(get_shortcut(\r\n                                                       'ipython_console',\r\n                                                       'reset namespace')),\r\n                                               icon=ima.icon('editdelete'),\r\n                                               triggered=self.reset_namespace)\r\n        clear_console_action = create_action(self, _(\"Clear console\"),\r\n                                             QKeySequence(get_shortcut('console',\r\n                                                               'clear shell')),\r\n                                             triggered=self.clear_console)\r\n        quit_action = create_action(self, _(\"&Quit\"), icon=ima.icon('exit'),\r\n                                    triggered=self.exit_callback)\r\n        add_actions(menu, (None, inspect_action, clear_line_action,\r\n                           clear_console_action, reset_namespace_action,\r\n                           None, quit_action))\r\n        return menu",
    "docstring": "Add actions to IPython widget context menu"
  },
  {
    "code": "def update(self, quality_score, issue=values.unset):\n        return self._proxy.update(quality_score, issue=issue, )",
    "docstring": "Update the FeedbackInstance\n\n        :param unicode quality_score: The call quality expressed as an integer from 1 to 5\n        :param FeedbackInstance.Issues issue: Issues experienced during the call\n\n        :returns: Updated FeedbackInstance\n        :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstance"
  },
  {
    "code": "def raise_for_redefined_annotation(self, line: str, position: int, annotation: str) -> None:\n        if self.disallow_redefinition and self.has_annotation(annotation):\n            raise RedefinedAnnotationError(self.get_line_number(), line, position, annotation)",
    "docstring": "Raise an exception if the given annotation is already defined.\n\n        :raises: RedefinedAnnotationError"
  },
  {
    "code": "def _initSymbols(ptc):\n    ptc.am = ['', '']\n    ptc.pm = ['', '']\n    for idx, xm in enumerate(ptc.locale.meridian[:2]):\n        target = ['am', 'pm'][idx]\n        setattr(ptc, target, [xm])\n        target = getattr(ptc, target)\n        if xm:\n            lxm = xm.lower()\n            target.extend((xm[0], '{0}.{1}.'.format(*xm),\n                           lxm, lxm[0], '{0}.{1}.'.format(*lxm)))",
    "docstring": "Initialize symbols and single character constants."
  },
  {
    "code": "def watch_context(keys, result, reqid, container, module = 'objectdb'):\n    try:\n        keys = [k for k,r in zip(keys, result) if r is not None]\n        yield result\n    finally:\n        if keys:\n            async def clearup():\n                try:\n                    await send_api(container, module, 'munwatch', {'keys': keys, 'requestid': reqid})\n                except QuitException:\n                    pass\n            container.subroutine(clearup(), False)",
    "docstring": "DEPRECATED - use request_context for most use cases"
  },
  {
    "code": "def create_transform(ctx, transform):\n    from canari.commands.create_transform import create_transform\n    create_transform(ctx.project, transform)",
    "docstring": "Creates a new transform in the specified directory and auto-updates dependencies."
  },
  {
    "code": "def add(self, metric_name, stat, config=None):\n        with self._lock:\n            metric = KafkaMetric(metric_name, stat, config or self._config)\n            self._registry.register_metric(metric)\n            self._metrics.append(metric)\n            self._stats.append(stat)",
    "docstring": "Register a metric with this sensor\n\n        Arguments:\n            metric_name (MetricName): The name of the metric\n            stat (AbstractMeasurableStat): The statistic to keep\n            config (MetricConfig): A special configuration for this metric.\n                If None use the sensor default configuration."
  },
  {
    "code": "def add_to_configs(self, configs):\n        if len(configs) == 0:\n            return None\n        if self.configs is None:\n            self.configs = np.atleast_2d(configs)\n        else:\n            configs = np.atleast_2d(configs)\n            self.configs = np.vstack((self.configs, configs))\n        return self.configs",
    "docstring": "Add one or more measurement configurations to the stored\n        configurations\n\n        Parameters\n        ----------\n        configs: list or numpy.ndarray\n            list or array of configurations\n\n        Returns\n        -------\n        configs: Kx4 numpy.ndarray\n            array holding all configurations of this instance"
  },
  {
    "code": "def validate(self, value):\n        if value in self.empty_values and self.required:\n            raise ValidationError(self.error_messages['required'])",
    "docstring": "This was overridden to have our own ``empty_values``."
  },
  {
    "code": "def get_addon_name(addonxml):\n    xml = parse(addonxml)\n    addon_node = xml.getElementsByTagName('addon')[0]\n    return addon_node.getAttribute('name')",
    "docstring": "Parses an addon name from the given addon.xml filename."
  },
  {
    "code": "def has_namespace(self, namespace: str) -> bool:\n        return self.has_enumerated_namespace(namespace) or self.has_regex_namespace(namespace)",
    "docstring": "Check that the namespace has either been defined by an enumeration or a regular expression."
  },
  {
    "code": "def verify(self, windowSize=None):\n        if self.samplerate() is None:\n            return \"Multiple recording files with conflicting samplerates\"\n        msg = self._autoParams.verify()\n        if msg:\n            return msg\n        if self.traceCount() == 0:\n            return \"Test is empty\"\n        if windowSize is not None:\n            durations = self.expandFunction(self.duration)\n            if durations[0] > windowSize or durations[-1] > windowSize:\n                return \"Stimulus duration exceeds window duration\"\n        msg = self.verifyExpanded(self.samplerate())\n        if msg:\n            return msg\n        if self.caldb is None or self.calv is None:\n            return \"Test reference voltage not set\"\n        if None in self.voltage_limits:\n            return \"Device voltage limits not set\"\n        return 0",
    "docstring": "Checks the stimulus, including expanded parameters for invalidating conditions\n\n        :param windowSize: acquistion (recording) window size (seconds)\n        :type windowSize: float\n        :returns: str -- error message, if any, 0 otherwise"
  },
  {
    "code": "def play_actions(self, target):\n        for method_name, args, kwargs in self.actions:\n            method = getattr(target, method_name)\n            method(*args, **kwargs)",
    "docstring": "Play record actions on the target object.\n\n        :param target: the target which recive all record actions, is a brown\n                       ant app instance normally.\n        :type target: :class:`~brownant.app.Brownant`"
  },
  {
    "code": "def redirect_response(self, url, permanent=False):\n        if permanent:\n            self.send_response(301)\n        else:\n            self.send_response(302)\n        self.send_header(\"Location\", url)\n        self.end_headers()",
    "docstring": "Generate redirect response"
  },
  {
    "code": "def set_ylabels(self, label=None, **kwargs):\n        if label is None:\n            label = label_from_attrs(self.data[self._y_var])\n        for ax in self._left_axes:\n            ax.set_ylabel(label, **kwargs)\n        return self",
    "docstring": "Label the y axis on the left column of the grid."
  },
  {
    "code": "def _get_struct_encodedu32(self):\n        useful = []\n        while True:\n            byte = ord(self._src.read(1))\n            useful.append(byte)\n            if byte < 127:\n                break\n        useful = ['00000000' + bin(b)[2:] for b in useful[::-1]]\n        return int(''.join([b[-7:] for b in useful]), 2)",
    "docstring": "Get a EncodedU32 number."
  },
  {
    "code": "def end_state(self):\n        if self.str_begin != len(self.format):\n            if len(self.state) > 1 or self.state[-1] != 'string':\n                self.fmt.append_text(\n                    \"(Bad format string; ended in state %r)\" % self.state[-1])\n            else:\n                self.fmt.append_text(self.format[self.str_begin:])\n        return self.fmt",
    "docstring": "Wrap things up and add any final string content."
  },
  {
    "code": "def _update_params(self, constants):\n        constants = np.max(np.min(constants, 1))\n        self.params['r']['value'] = max([self.params['r']['value'],\n                                         constants])\n        epsilon = constants / self.params['r']['value']\n        influence = self._calculate_influence(epsilon)\n        return influence * epsilon",
    "docstring": "Update the params."
  },
  {
    "code": "def output_json(data, code, headers=None):\n    settings = current_app.config.get('RESTFUL_JSON', {})\n    if current_app.debug:\n        settings.setdefault('indent', 4)\n        settings.setdefault('sort_keys', not PY3)\n    dumped = dumps(data, **settings) + \"\\n\"\n    resp = make_response(dumped, code)\n    resp.headers.extend(headers or {})\n    return resp",
    "docstring": "Makes a Flask response with a JSON encoded body"
  },
  {
    "code": "def get_cached_placeholder_output(parent_object, placeholder_name):\n    if not PlaceholderRenderingPipe.may_cache_placeholders():\n        return None\n    language_code = get_parent_language_code(parent_object)\n    cache_key = get_placeholder_cache_key_for_parent(parent_object, placeholder_name, language_code)\n    return cache.get(cache_key)",
    "docstring": "Return cached output for a placeholder, if available.\n    This avoids fetching the Placeholder object."
  },
  {
    "code": "def get_residuals(ds, m):\n    model_spectra = get_model_spectra(ds, m)\n    resid = ds.test_flux - model_spectra\n    return resid",
    "docstring": "Using the dataset and model object, calculate the residuals and return\n\n    Parameters\n    ----------\n    ds: dataset object\n    m: model object\n    Return\n    ------\n    residuals: array of residuals, spec minus model spec"
  },
  {
    "code": "def sortByNamespacePrefix(urisList, nsList):\n    exit = []\n    urisList = sort_uri_list_by_name(urisList)\n    for ns in nsList:\n        innerexit = []\n        for uri in urisList:\n            if str(uri).startswith(str(ns)):\n                innerexit += [uri]\n        exit += innerexit\n    for uri in urisList:\n        if uri not in exit:\n            exit += [uri]\n    return exit",
    "docstring": "Given an ordered list of namespaces prefixes, order a list of uris based on that.\n        Eg\n\n        In [7]: ll\n        Out[7]:\n        [rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),\n         rdflib.term.URIRef(u'printGenericTreeorg/2000/01/rdf-schema#comment'),\n         rdflib.term.URIRef(u'http://www.w3.org/2000/01/rdf-schema#label'),\n         rdflib.term.URIRef(u'http://www.w3.org/2002/07/owl#equivalentClass')]\n\n        In [8]: sortByNamespacePrefix(ll, [OWL.OWLNS, RDFS])\n        Out[8]:\n        [rdflib.term.URIRef(u'http://www.w3.org/2002/07/owl#equivalentClass'),\n         rdflib.term.URIRef(u'http://www.w3.org/2000/01/rdf-schema#comment'),\n         rdflib.term.URIRef(u'http://www.w3.org/2000/01/rdf-schema#label'),\n         rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type')]"
  },
  {
    "code": "def get_client_secret(self):\n        self._client_secret = predix.config.get_env_value(predix.app.Manifest, 'client_secret')\n        return self._client_secret",
    "docstring": "Return the client secret that should correspond with\n        the client id."
  },
  {
    "code": "def is_root(self):\n        sub_prefix = self.reddit_session.config.by_object[Submission]\n        return self.parent_id.startswith(sub_prefix)",
    "docstring": "Return True when the comment is a top level comment."
  },
  {
    "code": "def modify_area(self, pid, xmin, xmax, zmin, zmax, value):\n        area_polygon = shapgeo.Polygon(\n            ((xmin, zmax), (xmax, zmax), (xmax, zmin), (xmin, zmin))\n        )\n        self.modify_polygon(pid, area_polygon, value)",
    "docstring": "Modify the given dataset in the rectangular area given by the\n        parameters and assign all parameters inside this area the given value.\n\n        Partially contained elements are treated as INSIDE the area, i.e., they\n        are assigned new values.\n\n        Parameters\n        ----------\n        pid: int\n            id of the parameter set to modify\n        xmin: float\n            smallest x value of the area to modify\n        xmax: float\n            largest x value of the area to modify\n        zmin: float\n            smallest z value of the area to modify\n        zmin: float\n            largest z value of the area to modify\n        value: float\n            this value is assigned to all parameters of the area\n\n        Examples\n        --------\n\n        >>> import crtomo.tdManager as CRtdm\n            tdman = CRtdm.tdMan(\n                    elem_file='GRID/elem.dat',\n                    elec_file='GRID/elec.dat',\n            )\n            pid = tdman.parman.add_empty_dataset(value=1)\n            tdman.parman.modify_area(\n                    pid,\n                    xmin=0,\n                    xmax=2,\n                    zmin=-2,\n                    zmin=-0.5,\n                    value=2,\n            )\n            fig, ax = tdman.plot.plot_elements_to_ax(pid)\n            fig.savefig('out.png')"
  },
  {
    "code": "def assure_check(fnc):\n    @wraps(fnc)\n    def _wrapped(self, check, *args, **kwargs):\n        if not isinstance(check, CloudMonitorCheck):\n            check = self._check_manager.get(check)\n        return fnc(self, check, *args, **kwargs)\n    return _wrapped",
    "docstring": "Converts an checkID passed as the check to a CloudMonitorCheck object."
  },
  {
    "code": "def send_batch(messages, api_key=None, secure=None, test=None, **request_args):\n    return _default_pyst_batch_sender.send(messages=messages, api_key=api_key,\n                                           secure=secure, test=test,\n                                           **request_args)",
    "docstring": "Send a batch of messages.\n\n    :param messages: Messages to send.\n    :type message: A list of `dict` or :class:`Message`\n    :param api_key: Your Postmark API key. Required, if `test` is not `True`.\n    :param secure: Use the https scheme for the Postmark API.\n        Defaults to `True`\n    :param test: Use the Postmark Test API. Defaults to `False`.\n    :param \\*\\*request_args: Keyword arguments to pass to\n        :func:`requests.request`.\n    :rtype: :class:`BatchSendResponse`"
  },
  {
    "code": "def most_frequent(lst):\n    lst = lst[:]\n    highest_freq = 0\n    most_freq = None\n    for val in unique(lst):\n        if lst.count(val) > highest_freq:\n            most_freq = val\n            highest_freq = lst.count(val)\n    return most_freq",
    "docstring": "Returns the item that appears most frequently in the given list."
  },
  {
    "code": "def load(self, arguments):\n        \"Load the values from the a ServerConnection arguments\"\n        features = arguments[1:-1]\n        list(map(self.load_feature, features))",
    "docstring": "Load the values from the a ServerConnection arguments"
  },
  {
    "code": "def center_line(space, line):\n    line = line.strip()\n    left_length = math.floor((space - len(line)) / 2)\n    right_length = math.ceil((space - len(line)) / 2)\n    left_space = \" \" * int(left_length)\n    right_space = \" \" * int(right_length)\n    line = ''.join([left_space, line, right_space])\n    return line",
    "docstring": "Add leading & trailing space to text to center it within an allowed\n    width\n\n    Parameters\n    ----------\n    space : int\n        The maximum character width allowed for the text. If the length\n        of text is more than this value, no space will be added.\\\n    line : str\n        The text that will be centered.\n\n    Returns\n    -------\n    line : str\n        The text with the leading space added to it"
  },
  {
    "code": "def concatenate_1d(arrays):\n    if len(arrays) == 0:\n        return np.array([])\n    if len(arrays) == 1:\n        return np.asanyarray(arrays[0])\n    if any(map(np.ma.is_masked, arrays)):\n        return np.ma.concatenate(arrays)\n    return np.concatenate(arrays)",
    "docstring": "Concatenate 1D numpy arrays.\n    Similar to np.concatenate but work with empty input and masked arrays."
  },
  {
    "code": "def random_pairs_without_replacement_large_frames(\n        n, shape, random_state=None):\n    n_max = max_pairs(shape)\n    sample = np.array([])\n    while len(sample) < n:\n        n_sample_size = (n - len(sample)) * 2\n        sample = random_state.randint(n_max, size=n_sample_size)\n        pairs_non_unique = np.append(sample, sample)\n        sample = _unique_rows_numpy(pairs_non_unique)\n    if len(shape) == 1:\n        return _map_tril_1d_on_2d(sample[0:n], shape[0])\n    else:\n        return np.unravel_index(sample[0:n], shape)",
    "docstring": "Make a sample of random pairs with replacement"
  },
  {
    "code": "def device_add_rule(self, direction, action, src, dst, target=None):\n        value = [direction, src, dst, action]\n        if target:\n            value.append(target)\n        self._set_aliased('device-rule', ' '.join(value), multi=True)\n        return self",
    "docstring": "Adds a tuntap device rule.\n\n        To be used in a vassal.\n\n        :param str|unicode direction: Direction:\n\n            * in\n            * out.\n\n        :param str|unicode action: Action:\n\n            * allow\n            * deny\n            * route\n            * gateway.\n\n        :param str|unicode src: Source/mask.\n\n        :param str|unicode dst: Destination/mask.\n\n        :param str|unicode target: Depends on action.\n\n            * Route / Gateway: Accept addr:port"
  },
  {
    "code": "def do_copy(self,args):\n        parser = CommandArgumentParser(\"copy\")\n        parser.add_argument('-a','--asg',dest='asg',nargs='+',required=False,default=[],help='Copy specified ASG info.')\n        parser.add_argument('-o','--output',dest='output',nargs='+',required=False,default=[],help='Copy specified output info.')        \n        args = vars(parser.parse_args(args))\n        values = []\n        if args['output']:\n            values.extend(self.getOutputs(args['output']))\n        if args['asg']:\n            for asg in args['asg']:\n                try:\n                    index = int(asg)\n                    asgSummary = self.wrappedStack['resourcesByTypeIndex']['AWS::AutoScaling::AutoScalingGroup'][index]\n                except:\n                    asgSummary = self.wrappedStack['resourcesByTypeName']['AWS::AutoScaling::AutoScalingGroup'][asg]\n                values.append(asgSummary.physical_resource_id)\n        print(\"values:{}\".format(values))\n        pyperclip.copy(\"\\n\".join(values))",
    "docstring": "Copy specified id to stack. copy -h for detailed help."
  },
  {
    "code": "def make_account_admin(self, user_id, account_id, role=None, role_id=None, send_confirmation=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"account_id\"] = account_id\r\n        data[\"user_id\"] = user_id\r\n        if role is not None:\r\n            data[\"role\"] = role\r\n        if role_id is not None:\r\n            data[\"role_id\"] = role_id\r\n        if send_confirmation is not None:\r\n            data[\"send_confirmation\"] = send_confirmation\r\n        self.logger.debug(\"POST /api/v1/accounts/{account_id}/admins with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"POST\", \"/api/v1/accounts/{account_id}/admins\".format(**path), data=data, params=params, single_item=True)",
    "docstring": "Make an account admin.\r\n\r\n        Flag an existing user as an admin within the account."
  },
  {
    "code": "def from_json(cls, data):\n        optional_keys = {'wind_direction': 0, 'rain': False, 'snow_on_ground': False}\n        assert 'wind_speed' in data, 'Required key \"wind_speed\" is missing!'\n        for key, val in optional_keys.items():\n            if key not in data:\n                data[key] = val\n        return cls(data['wind_speed'], data['wind_direction'], data['rain'],\n                   data['snow_on_ground'])",
    "docstring": "Create a Wind Condition from a dictionary.\n\n        Args:\n            data = {\n            \"wind_speed\": float,\n            \"wind_direction\": float,\n            \"rain\": bool,\n            \"snow_on_ground\": bool}"
  },
  {
    "code": "def view_attr(attr_name):\n    def view_attr(_value, context, **_params):\n        value = getattr(context[\"view\"], attr_name)\n        return _attr(value)\n    return view_attr",
    "docstring": "Creates a getter that will drop the current value\n    and retrieve the view's attribute with specified name.\n    @param attr_name: the name of an attribute belonging to the view.\n    @type attr_name: str"
  },
  {
    "code": "def _build_default_options(self):\n        return [\n            OptionDefault('model', None, inherit=True),\n            OptionDefault('abstract', False, inherit=False),\n            OptionDefault('strategy', enums.CREATE_STRATEGY, inherit=True),\n            OptionDefault('inline_args', (), inherit=True),\n            OptionDefault('exclude', (), inherit=True),\n            OptionDefault('rename', {}, inherit=True),\n        ]",
    "docstring": "Provide the default value for all allowed fields.\n\n        Custom FactoryOptions classes should override this method\n        to update() its return value."
  },
  {
    "code": "def format(self, info_dict, delimiter='/'):\n        def dfs(father, path, acc):\n            if isinstance(father, list):\n                for child in father:\n                    dfs(child, path, acc)\n            elif isinstance(father, collections.Mapping):\n                for child in sorted(father.items(), key=itemgetter(0)), :\n                    dfs(child, path, acc)\n            elif isinstance(father, tuple):\n                path = copy.copy(path)\n                path.append(father[0])\n                dfs(father[1], path, acc)\n            else:\n                path[-1] = '{}: {}'.format(path[-1], str(father))\n                acc.append(delimiter.join(path))\n        result = []\n        dfs(info_dict.get('Prefix') or info_dict, [], result)\n        return '\\n'.join(result)",
    "docstring": "This formatter will take a data structure that\n        represent a tree and will print all the paths\n        from the root to the leaves\n\n        in our case it will print each value and the keys\n        that needed to get to it, for example:\n\n        vm0:\n            net: lago\n            memory: 1024\n\n        will be output as:\n\n        vm0/net/lago\n        vm0/memory/1024\n\n            Args:\n                info_dict (dict): information to reformat\n                delimiter (str): a delimiter for the path components\n            Returns:\n                str: String representing the formatted info"
  },
  {
    "code": "def is_pid_healthy(pid):\n    if HAS_PSUTIL:\n        try:\n            proc = psutil.Process(pid)\n        except psutil.NoSuchProcess:\n            log.warning(\"PID %s is no longer running.\", pid)\n            return False\n        return any(['salt' in cmd for cmd in proc.cmdline()])\n    if salt.utils.platform.is_aix() or salt.utils.platform.is_windows():\n        return True\n    if not salt.utils.process.os_is_running(pid):\n        log.warning(\"PID %s is no longer running.\", pid)\n        return False\n    cmdline_file = os.path.join('proc', str(pid), 'cmdline')\n    try:\n        with salt.utils.files.fopen(cmdline_file, 'rb') as fp_:\n            return b'salt' in fp_.read()\n    except (OSError, IOError) as err:\n        log.error(\"There was a problem reading proc file: %s\", err)\n        return False",
    "docstring": "This is a health check that will confirm the PID is running\n    and executed by salt.\n\n    If pusutil is available:\n        * all architectures are checked\n\n    if psutil is not available:\n        * Linux/Solaris/etc: archs with `/proc/cmdline` available are checked\n        * AIX/Windows: assume PID is healhty and return True"
  },
  {
    "code": "def _add_flaky_report(self, stream):\n        value = self._stream.getvalue()\n        if not self._flaky_success_report and not value:\n            return\n        stream.write('===Flaky Test Report===\\n\\n')\n        try:\n            stream.write(value)\n        except UnicodeEncodeError:\n            stream.write(value.encode('utf-8', 'replace'))\n        stream.write('\\n===End Flaky Test Report===\\n')",
    "docstring": "Baseclass override. Write details about flaky tests to the test report.\n\n        :param stream:\n            The test stream to which the report can be written.\n        :type stream:\n            `file`"
  },
  {
    "code": "def _delete_iapp(self, iapp_name, deploying_device):\n        iapp = deploying_device.tm.sys.application\n        iapp_serv = iapp.services.service.load(\n            name=iapp_name, partition=self.partition\n        )\n        iapp_serv.delete()\n        iapp_tmpl = iapp.templates.template.load(\n            name=iapp_name, partition=self.partition\n        )\n        iapp_tmpl.delete()",
    "docstring": "Delete an iapp service and template on the root device.\n\n        :param iapp_name: str -- name of iapp\n        :param deploying_device: ManagementRoot object -- device where the\n                                 iapp will be deleted"
  },
  {
    "code": "def date_range(field_name, **kwargs):\n    for k, v in kwargs.items():\n        dt = v\n        if not hasattr(v, 'isoformat'):\n            dt = strp_lenient(str(v))\n            if dt is None:\n                raise ValueError(\"unable to use provided time: \" + str(v))\n        kwargs[k] = dt.isoformat() + 'Z'\n    return _filter('DateRangeFilter', config=kwargs, field_name=field_name)",
    "docstring": "Build a DateRangeFilter.\n\n    Predicate arguments accept a value str that in ISO-8601 format or a value\n    that has a `isoformat` callable that returns an ISO-8601 str.\n\n    :raises: ValueError if predicate value does not parse\n\n    >>> date_range('acquired', gt='2017') == \\\n    {'config': {'gt': '2017-01-01T00:00:00Z'}, \\\n    'field_name': 'acquired', 'type': 'DateRangeFilter'}\n    True"
  },
  {
    "code": "def write_wave(path, audio, sample_rate):\n    with contextlib.closing(wave.open(path, 'wb')) as wf:\n        wf.setnchannels(1)\n        wf.setsampwidth(2)\n        wf.setframerate(sample_rate)\n        wf.writeframes(audio)",
    "docstring": "Writes a .wav file.\n\n    Takes path, PCM audio data, and sample rate."
  },
  {
    "code": "def initialize_env_specs(hparams, env_problem_name):\n  if env_problem_name:\n    env = registry.env_problem(env_problem_name, batch_size=hparams.batch_size)\n  else:\n    env = rl_utils.setup_env(hparams, hparams.batch_size,\n                             hparams.eval_max_num_noops,\n                             hparams.rl_env_max_episode_steps,\n                             env_name=hparams.rl_env_name)\n    env.start_new_epoch(0)\n  return rl.make_real_env_fn(env)",
    "docstring": "Initializes env_specs using the appropriate env."
  },
  {
    "code": "def fix_partial_utf8_punct_in_1252(text):\n    def latin1_to_w1252(match):\n        \"The function to apply when this regex matches.\"\n        return match.group(0).encode('latin-1').decode('sloppy-windows-1252')\n    def w1252_to_utf8(match):\n        \"The function to apply when this regex matches.\"\n        return match.group(0).encode('sloppy-windows-1252').decode('utf-8')\n    text = C1_CONTROL_RE.sub(latin1_to_w1252, text)\n    return PARTIAL_UTF8_PUNCT_RE.sub(w1252_to_utf8, text)",
    "docstring": "Fix particular characters that seem to be found in the wild encoded in\n    UTF-8 and decoded in Latin-1 or Windows-1252, even when this fix can't be\n    consistently applied.\n\n    One form of inconsistency we need to deal with is that some character might\n    be from the Latin-1 C1 control character set, while others are from the\n    set of characters that take their place in Windows-1252. So we first replace\n    those characters, then apply a fix that only works on Windows-1252 characters.\n\n    This is used as a transcoder within `fix_encoding`."
  },
  {
    "code": "def read_varint64(self):\n        i = self.read_var_uint64()\n        if i > wire_format.INT64_MAX:\n            i -= (1 << 64)\n        return i",
    "docstring": "Reads a varint from the stream, interprets this varint\n        as a signed, 64-bit integer, and returns the integer."
  },
  {
    "code": "def save_fits(self, data, name):\n        data = data.reshape(1, 1, data.shape[0], data.shape[0])\n        new_file = pyfits.PrimaryHDU(data,self.img_hdu_list[0].header)\n        new_file.writeto(\"{}\".format(name), overwrite=True)",
    "docstring": "This method simply saves the model components and the residual.\n\n        INPUTS:\n        data    (no default)    Data which is to be saved.\n        name    (no default)    File name for new .fits file. Will overwrite."
  },
  {
    "code": "def data(self, data):\n        self._data = {det: d.copy() for (det, d) in data.items()}",
    "docstring": "Store a copy of the data."
  },
  {
    "code": "def get_specification(self):\n        resp = self._call('getApplicationSpec', proto.Empty())\n        return ApplicationSpec.from_protobuf(resp)",
    "docstring": "Get the specification for the running application.\n\n        Returns\n        -------\n        spec : ApplicationSpec"
  },
  {
    "code": "def _DeserializeAttributeContainer(self, container_type, serialized_data):\n    if not serialized_data:\n      return None\n    if self._serializers_profiler:\n      self._serializers_profiler.StartTiming(container_type)\n    try:\n      serialized_string = serialized_data.decode('utf-8')\n    except UnicodeDecodeError as exception:\n      raise IOError('Unable to decode serialized data: {0!s}'.format(\n          exception))\n    attribute_container = self._serializer.ReadSerialized(serialized_string)\n    if self._serializers_profiler:\n      self._serializers_profiler.StopTiming(container_type)\n    return attribute_container",
    "docstring": "Deserializes an attribute container.\n\n    Args:\n      container_type (str): attribute container type.\n      serialized_data (bytes): serialized attribute container data.\n\n    Returns:\n      AttributeContainer: attribute container or None.\n\n    Raises:\n      IOError: if the serialized data cannot be decoded.\n      OSError: if the serialized data cannot be decoded."
  },
  {
    "code": "def format_currency_field(__, prec, number, locale):\n    locale = Locale.parse(locale)\n    currency = get_territory_currencies(locale.territory)[0]\n    if prec is None:\n        pattern, currency_digits = None, True\n    else:\n        prec = int(prec)\n        pattern = locale.currency_formats['standard']\n        pattern = modify_number_pattern(pattern, frac_prec=(prec, prec))\n        currency_digits = False\n    return format_currency(number, currency, pattern, locale=locale,\n                           currency_digits=currency_digits)",
    "docstring": "Formats a currency field."
  },
  {
    "code": "def check_for_end_game(self):\n\t\tgameover = False\n\t\tfor player in self.players:\n\t\t\tif player.playstate in (PlayState.CONCEDED, PlayState.DISCONNECTED):\n\t\t\t\tplayer.playstate = PlayState.LOSING\n\t\t\tif player.playstate == PlayState.LOSING:\n\t\t\t\tgameover = True\n\t\tif gameover:\n\t\t\tif self.players[0].playstate == self.players[1].playstate:\n\t\t\t\tfor player in self.players:\n\t\t\t\t\tplayer.playstate = PlayState.TIED\n\t\t\telse:\n\t\t\t\tfor player in self.players:\n\t\t\t\t\tif player.playstate == PlayState.LOSING:\n\t\t\t\t\t\tplayer.playstate = PlayState.LOST\n\t\t\t\t\telse:\n\t\t\t\t\t\tplayer.playstate = PlayState.WON\n\t\t\tself.state = State.COMPLETE\n\t\t\tself.manager.step(self.next_step, Step.FINAL_WRAPUP)\n\t\t\tself.manager.step(self.next_step, Step.FINAL_GAMEOVER)\n\t\t\tself.manager.step(self.next_step)",
    "docstring": "Check if one or more player is currently losing.\n\t\tEnd the game if they are."
  },
  {
    "code": "def to_dict(self):\n        def _json_safe(v):\n            if isinstance(v, np.ndarray):\n                return v.tolist()\n            elif is_unit(v)[0]:\n                return v.to_string()\n            else:\n                return v\n        d = {k:_json_safe(v) for k,v in self._descriptors.items()}\n        d['nparray'] = self.__class__.__name__.lower()\n        return d",
    "docstring": "dump a representation of the nparray object to a dictionary.  The\n        nparray object should then be able to be fully restored via\n        nparray.from_dict"
  },
  {
    "code": "def render(self, url, template=None, expiration=0):\n        template = template or self.default_template\n        return render_to_string(template, self.get_context(url, expiration))",
    "docstring": "Render feed template"
  },
  {
    "code": "def getVersionList(self, full_path, startnum = 0, pagingrow = 50, dummy = 54213):\n        data = {'orgresource': full_path,\n                'startnum': startnum,\n                'pagingrow': pagingrow,\n                'userid': self.user_id,\n                'useridx': self.useridx,\n                'dummy': dummy,\n                }\n        s, metadata = self.POST('getVersionList', data)\n        if s is True:\n            return metadata\n        else:\n            print \"Error getVersionList: Cannot get version list\"\n            return False",
    "docstring": "Get a version list of a file or dierectory.\n\n        :param full_path: The full path to get the file or directory property. Path should start with '/'\n        :param startnum: Start version index.\n        :param pagingrow: Max # of version list in one page.\n\n        :returns: ``metadata`` if succcess or ``False`` (failed to get history or there is no history)\n\n        :metadata:\n              - createuser\n              - filesize\n              - getlastmodified\n              - href\n              - versioninfo\n              - versionkey"
  },
  {
    "code": "def dim_axis_label(dimensions, separator=', '):\n    if not isinstance(dimensions, list): dimensions = [dimensions]\n    return separator.join([d.pprint_label for d in dimensions])",
    "docstring": "Returns an axis label for one or more dimensions."
  },
  {
    "code": "def reorder_view(self, request):\n        model = self.model\n        if not self.has_change_permission(request):\n            raise PermissionDenied\n        if request.method == \"POST\":\n            object_pks = request.POST.getlist('neworder[]')\n            model.objects.set_orders(object_pks)\n        return HttpResponse(\"OK\")",
    "docstring": "The 'reorder' admin view for this model."
  },
  {
    "code": "def find_network_by_name(self, si, path, name):\n        return self.find_obj_by_path(si, path, name, self.Network)",
    "docstring": "Finds network in the vCenter or returns \"None\"\n\n        :param si:         pyvmomi 'ServiceInstance'\n        :param path:       the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')\n        :param name:       the datastore name to return"
  },
  {
    "code": "def remove_reserved_keys(self, op):\n        sanitized = {}\n        reserved = {}\n        for k in op.keys():\n            if str(k) not in RESERVED_KEYS:\n                sanitized[str(k)] = copy.deepcopy(op[k])\n            else:\n                reserved[str(k)] = copy.deepcopy(op[k])\n        return sanitized, reserved",
    "docstring": "Remove reserved keywords from an op dict,\n        which can then safely be passed into the db.\n        \n        Returns a new op dict, and the reserved fields"
  },
  {
    "code": "def do_alarm_history_list(mc, args):\n    fields = {}\n    if args.dimensions:\n        fields['dimensions'] = utils.format_parameters(args.dimensions)\n    if args.starttime:\n        _translate_starttime(args)\n        fields['start_time'] = args.starttime\n    if args.endtime:\n        fields['end_time'] = args.endtime\n    if args.limit:\n        fields['limit'] = args.limit\n    if args.offset:\n        fields['offset'] = args.offset\n    try:\n        alarm = mc.alarms.history_list(**fields)\n    except (osc_exc.ClientException, k_exc.HttpError) as he:\n        raise osc_exc.CommandError('%s\\n%s' % (he.message, he.details))\n    else:\n        output_alarm_history(args, alarm)",
    "docstring": "List alarms state history."
  },
  {
    "code": "def project_community(index, start, end):\n    results = {\n        \"author_metrics\": [Authors(index, start, end)],\n        \"people_top_metrics\": [Authors(index, start, end)],\n        \"orgs_top_metrics\": [Organizations(index, start, end)],\n    }\n    return results",
    "docstring": "Compute the metrics for the project community section of the enriched\n    git index.\n\n    Returns a dictionary containing \"author_metrics\", \"people_top_metrics\"\n    and \"orgs_top_metrics\" as the keys and the related Metrics as the values.\n\n    :param index: index object\n    :param start: start date to get the data from\n    :param end: end date to get the data upto\n    :return: dictionary with the value of the metrics"
  },
  {
    "code": "def load(self, require=True, *args, **kwargs):\n        if not require or args or kwargs:\n            warnings.warn(\n                \"Parameters to load are deprecated.  Call .resolve and \"\n                \".require separately.\",\n                PkgResourcesDeprecationWarning,\n                stacklevel=2,\n            )\n        if require:\n            self.require(*args, **kwargs)\n        return self.resolve()",
    "docstring": "Require packages for this EntryPoint, then resolve it."
  },
  {
    "code": "def disassemble(self, start=None, end=None, arch_mode=None):\n        if arch_mode is None:\n            arch_mode = self.binary.architecture_mode\n        curr_addr = start if start else self.binary.ea_start\n        end_addr = end if end else self.binary.ea_end\n        while curr_addr < end_addr:\n            encoding = self.__fetch_instr(curr_addr)\n            asm_instr = self.disassembler.disassemble(encoding, curr_addr, architecture_mode=arch_mode)\n            if not asm_instr:\n                return\n            yield curr_addr, asm_instr, asm_instr.size\n            curr_addr += asm_instr.size",
    "docstring": "Disassemble native instructions.\n\n        Args:\n            start (int): Start address.\n            end (int): End address.\n            arch_mode (int): Architecture mode.\n\n        Returns:\n            (int, Instruction, int): A tuple of the form (address, assembler instruction, instruction size)."
  },
  {
    "code": "def data(self, value):\n        if not value:\n            value = b''\n        if len(value) > self.SIZE:\n            raise ValueError(\"The maximum tag size is {0}\".format(self.SIZE))\n        self._data = value\n        while len(self._data) < self.SIZE:\n            self._data += b'\\x00'",
    "docstring": "Set the byte data and fill up the bytes to fit the size."
  },
  {
    "code": "def _first_owner(self, name):\n        owner = None\n        unowned = []\n        pieces = normalize_name(name).split('.')\n        while pieces and is_none_or_zero_address(owner):\n            name = '.'.join(pieces)\n            owner = self.owner(name)\n            if is_none_or_zero_address(owner):\n                unowned.append(pieces.pop(0))\n        return (owner, unowned, name)",
    "docstring": "Takes a name, and returns the owner of the deepest subdomain that has an owner\n\n        :returns: (owner or None, list(unowned_subdomain_labels), first_owned_domain)"
  },
  {
    "code": "def nice_true_ces(tc):\n    cause_list = []\n    next_list = []\n    cause = '<--'\n    effect = '-->'\n    for event in tc:\n        if event.direction == Direction.CAUSE:\n            cause_list.append([\"{0:.4f}\".format(round(event.alpha, 4)),\n                               event.mechanism, cause, event.purview])\n        elif event.direction == Direction.EFFECT:\n            next_list.append([\"{0:.4f}\".format(round(event.alpha, 4)),\n                              event.mechanism, effect, event.purview])\n        else:\n            validate.direction(event.direction)\n    true_list = [(cause_list[event], next_list[event])\n                 for event in range(len(cause_list))]\n    return true_list",
    "docstring": "Format a true |CauseEffectStructure|."
  },
  {
    "code": "def configure_app(app, config=None, config_obj=None):\n    app.config.from_object(config_obj or BaseConfig)\n    if config is not None:\n        app.config.from_pyfile(config)",
    "docstring": "Configure application instance.\n\n    Args:\n        app (Flask): initialized Flask app instance\n        config (Optional[path]): path to a Python module config file\n        config_obj (Optional[class]): Python config object"
  },
  {
    "code": "def _prepare_sort_by_score(self, values, sort_options):\n        base_tmp_key, tmp_keys = self._zset_to_keys(\n                                    key=self._sort_by_sortedset['by'],\n                                    values=values,\n                                    )\n        sort_options['by'] = '%s:*' % base_tmp_key\n        for key in ('desc', 'alpha', 'get', 'store'):\n            if key in self._sort_by_sortedset:\n                sort_options[key] = self._sort_by_sortedset[key]\n        if sort_options.get('get'):\n            try:\n                pos = sort_options['get'].index(SORTED_SCORE)\n            except:\n                pass\n            else:\n                sort_options['get'][pos] = '%s:*' % base_tmp_key\n        return base_tmp_key, tmp_keys",
    "docstring": "Create the key to sort on the sorted set references in\n        self._sort_by_sortedset and adapte sort options"
  },
  {
    "code": "def parts():\n    parts = {\n        'Canon': [ _ for _  in range(1, 5) ],\n        'Apostle': [ 5 ],\n        'Paul': [ _ for _ in range(6, 19) ],\n        'General': [ _ for _ in range(19, 26) ],\n        'Apocalypse': [ 27 ]\n    }\n    return parts",
    "docstring": "Returns the dictionary with the part as key and the contained book as indices."
  },
  {
    "code": "def _samples_dicts_to_array(samples_dicts, labels):\n    itersamples = iter(samples_dicts)\n    first_sample = next(itersamples)\n    if labels is None:\n        labels = list(first_sample)\n    num_variables = len(labels)\n    def _iter_samples():\n        yield np.fromiter((first_sample[v] for v in labels),\n                          count=num_variables, dtype=np.int8)\n        try:\n            for sample in itersamples:\n                yield np.fromiter((sample[v] for v in labels),\n                                  count=num_variables, dtype=np.int8)\n        except KeyError:\n            msg = (\"Each dict in 'samples' must have the same keys.\")\n            raise ValueError(msg)\n    return np.stack(list(_iter_samples())), labels",
    "docstring": "Convert an iterable of samples where each sample is a dict to a numpy 2d array. Also\n    determines the labels is they are None."
  },
  {
    "code": "def focusPrev(self, event):\n        try:\n            event.widget.tk_focusPrev().focus_set()\n        except TypeError:\n            name = event.widget.tk.call('tk_focusPrev', event.widget._w)\n            event.widget._nametowidget(str(name)).focus_set()",
    "docstring": "Set focus to previous item in sequence"
  },
  {
    "code": "def switch_to_json_payload_encoding(call_fn, response_class):\n    def json_serializer(*args, **kwargs):\n        return bytes(json_format.MessageToJson(args[0], True, preserving_proto_field_name=True), \"utf-8\")\n    def json_deserializer(*args, **kwargs):\n        resp = response_class()\n        json_format.Parse(args[0], resp, True)\n        return resp\n    call_fn._request_serializer    = json_serializer\n    call_fn._response_deserializer = json_deserializer",
    "docstring": "Switch payload encoding to JSON for GRPC call"
  },
  {
    "code": "def write(self, address, size, value):\n        for i in range(0, size):\n            self.__write_byte(address + i, (value >> (i * 8)) & 0xff)",
    "docstring": "Write arbitrary size content to memory."
  },
  {
    "code": "def _cookies_for_request(self, request):\n        cookies = []\n        for domain in self._cookies.keys():\n            cookies.extend(self._cookies_for_domain(domain, request))\n        return cookies",
    "docstring": "Return a list of cookies to be returned to server."
  },
  {
    "code": "def put_feature(ctx, dataset, fid, feature, input):\n    if feature is None:\n        stdin = click.open_file(input, 'r')\n        feature = stdin.read()\n    feature = json.loads(feature)\n    service = ctx.obj.get('service')\n    res = service.update_feature(dataset, fid, feature)\n    if res.status_code == 200:\n        click.echo(res.text)\n    else:\n        raise MapboxCLIException(res.text.strip())",
    "docstring": "Create or update a dataset feature.\n\n    The semantics of HTTP PUT apply: if the dataset has no feature\n    with the given `fid` a new feature will be created. Returns a\n    GeoJSON representation of the new or updated feature.\n\n        $ mapbox datasets put-feature dataset-id feature-id 'geojson-feature'\n\n    All endpoints require authentication. An access token with\n    `datasets:write` scope is required, see `mapbox --help`."
  },
  {
    "code": "def _verifyHostKey(self, hostKey, fingerprint):\n        if fingerprint in self.knownHosts:\n            return defer.succeed(True)\n        return defer.fail(UnknownHostKey(hostKey, fingerprint))",
    "docstring": "Called when ssh transport requests us to verify a given host key.\n        Return a deferred that callback if we accept the key or errback if we\n        decide to reject it."
  },
  {
    "code": "def errors(request, *args, **kwargs):\n    search_term = request.GET.get('q', None)\n    if '400' in search_term:\n        return HttpResponseBadRequest(MESSAGE_400)\n    elif '403' in search_term:\n        return HttpResponseForbidden(MESSAGE_403)\n    elif '404' in search_term:\n        return HttpResponseNotFound(MESSAGE_404)\n    elif '405' in search_term:\n        return HttpResponseNotAllowed(['PATCH'], MESSAGE_405)\n    return HttpResponseServerError(MESSAGE_500)",
    "docstring": "A dummy view that will throw errors.\n\n    It'll throw any HTTP error that is contained in the search query."
  },
  {
    "code": "def add_basemap(ax, zoom=12):\n    url = ctx.sources.ST_TONER_LITE\n    xmin, xmax, ymin, ymax = ax.axis()\n    basemap, extent = ctx.bounds2img(xmin, ymin, xmax, ymax,\n                                            zoom=zoom, url=url)\n    ax.imshow(basemap, extent=extent, interpolation='bilinear')\n    ax.axis((xmin, xmax, ymin, ymax))",
    "docstring": "Adds map to a plot."
  },
  {
    "code": "def _validate_codeblock_size(self, cparams):\n        if cparams.cblockw_init != 0 and cparams.cblockh_init != 0:\n            width = cparams.cblockw_init\n            height = cparams.cblockh_init\n            if height * width > 4096 or height < 4 or width < 4:\n                msg = (\"The code block area is specified as \"\n                       \"{height} x {width} = {area} square pixels.  \"\n                       \"Code block area cannot exceed 4096 square pixels.  \"\n                       \"Code block height and width dimensions must be larger \"\n                       \"than 4 pixels.\")\n                msg = msg.format(height=height, width=width,\n                                 area=height * width)\n                raise IOError(msg)\n            if ((math.log(height, 2) != math.floor(math.log(height, 2)) or\n                 math.log(width, 2) != math.floor(math.log(width, 2)))):\n                msg = (\"Bad code block size ({height} x {width}).  \"\n                       \"The dimensions must be powers of 2.\")\n                msg = msg.format(height=height, width=width)\n                raise IOError(msg)",
    "docstring": "Code block dimensions must satisfy certain restrictions.\n\n        They must both be a power of 2 and the total area defined by the width\n        and height cannot be either too great or too small for the codec."
  },
  {
    "code": "def elapsed(t0=0.0):\n    now = time()\n    dt = now - t0\n    dt_sec = Decimal(str(dt)).quantize(Decimal('.0001'), rounding=ROUND_DOWN)\n    if dt_sec <= 1:\n        dt_str = str(dt_sec) + ' second'\n    else:\n        dt_str = str(dt_sec) + ' seconds'\n    return now, dt_str",
    "docstring": "get elapsed time from the give time\n\n    Returns:\n        now: the absolute time now\n        dt_str: elapsed time in string"
  },
  {
    "code": "def create_empty(self, name=None, renderers=None, RootNetworkList=None, verbose=False):\n        PARAMS=set_param([\"name\",\"renderers\",\"RootNetworkList\"],[name,renderers,RootNetworkList])\n        response=api(url=self.__url+\"/create empty\", PARAMS=PARAMS, method=\"POST\", verbose=verbose)\n        return response",
    "docstring": "Create a new, empty network. The new network may be created as part of\n        an existing network collection or a new network collection.\n\n        :param name (string, optional): Enter the name of the new network.\n        :param renderers (string, optional): Select the renderer to use for the\n            new network view. By default, the standard Cytoscape 2D renderer (Ding)\n            will be used = [''],\n        :param RootNetworkList (string, optional): Choose the network collection\n            the new network should be part of. If no network collection is selected,\n            a new network collection is created. = [' -- Create new network collection --',\n            'cy:command_documentation_generation']\n        :param verbose: print more"
  },
  {
    "code": "def deserialize(klass, data):\n    handler = DESERIALIZE_REGISTRY.get(klass)\n    if handler:\n        return handler(data)\n    raise TypeError(\"There is no deserializer registered to handle \"\n                    \"instances of '{}'\".format(klass.__name__))",
    "docstring": "Helper function to access a method that creates objects of a\n    given `klass` with the received `data`."
  },
  {
    "code": "def cmd_async(self, low):\n        fun = low.pop('fun')\n        return self.asynchronous(fun, low)",
    "docstring": "Execute a function asynchronously; eauth is respected\n\n        This function requires that :conf_master:`external_auth` is configured\n        and the user is authorized\n\n        .. code-block:: python\n\n            >>> wheel.cmd_async({\n                'fun': 'key.finger',\n                'match': 'jerry',\n                'eauth': 'auto',\n                'username': 'saltdev',\n                'password': 'saltdev',\n            })\n            {'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'}"
  },
  {
    "code": "def runjava(self, classpath, main, jvm_options=None, args=None, workunit_name=None,\n              workunit_labels=None, workunit_log_config=None, dist=None):\n    executor = self.create_java_executor(dist=dist)\n    create_synthetic_jar = self.execution_strategy != self.NAILGUN\n    try:\n      return util.execute_java(classpath=classpath,\n                               main=main,\n                               jvm_options=jvm_options,\n                               args=args,\n                               executor=executor,\n                               workunit_factory=self.context.new_workunit,\n                               workunit_name=workunit_name,\n                               workunit_labels=workunit_labels,\n                               workunit_log_config=workunit_log_config,\n                               create_synthetic_jar=create_synthetic_jar,\n                               synthetic_jar_dir=self._executor_workdir)\n    except executor.Error as e:\n      raise TaskError(e)",
    "docstring": "Runs the java main using the given classpath and args.\n\n    If --execution-strategy=subprocess is specified then the java main is run in a freshly spawned\n    subprocess, otherwise a persistent nailgun server dedicated to this Task subclass is used to\n    speed up amortized run times.\n\n    :API: public"
  },
  {
    "code": "def format_exc(*exc_info):\n    typ, exc, tb = exc_info or sys.exc_info()\n    error = traceback.format_exception(typ, exc, tb)\n    return \"\".join(error)",
    "docstring": "Show exception with traceback."
  },
  {
    "code": "def get_requests_for_local_unit(relation_name=None):\n    local_name = local_unit().replace('/', '_')\n    raw_certs_key = '{}.processed_requests'.format(local_name)\n    relation_name = relation_name or 'certificates'\n    bundles = []\n    for rid in relation_ids(relation_name):\n        for unit in related_units(rid):\n            data = relation_get(rid=rid, unit=unit)\n            if data.get(raw_certs_key):\n                bundles.append({\n                    'ca': data['ca'],\n                    'chain': data.get('chain'),\n                    'certs': json.loads(data[raw_certs_key])})\n    return bundles",
    "docstring": "Extract any certificates data targeted at this unit down relation_name.\n\n    :param relation_name: str Name of relation to check for data.\n    :returns: List of bundles of certificates.\n    :rtype: List of dicts"
  },
  {
    "code": "def disconnect(self, client):\n        self.clients.remove(client)\n        del self.connect_args[client]\n        client.disconnect()",
    "docstring": "Remove client from pool."
  },
  {
    "code": "def dict_to_path(as_dict):\n    result = as_dict.copy()\n    loaders = {'Arc': Arc, 'Line': Line}\n    entities = [None] * len(as_dict['entities'])\n    for entity_index, entity in enumerate(as_dict['entities']):\n        entities[entity_index] = loaders[entity['type']](\n            points=entity['points'], closed=entity['closed'])\n    result['entities'] = entities\n    return result",
    "docstring": "Turn a pure dict into a dict containing entity objects that\n    can be sent directly to a Path constructor.\n\n    Parameters\n    -----------\n    as_dict : dict\n      Has keys: 'vertices', 'entities'\n\n    Returns\n    ------------\n    kwargs : dict\n      Has keys: 'vertices', 'entities'"
  },
  {
    "code": "def _depr(fn, usage, stacklevel=3):\n    warn('{0} is deprecated. Use {1} instead'.format(fn, usage),\n         stacklevel=stacklevel, category=DeprecationWarning)",
    "docstring": "Internal convenience function for deprecation warnings"
  },
  {
    "code": "def get_errors_for_state_name(self, name):\n        return_value = None\n        for state_id, name_outcome_tuple in self.child_errors.items():\n            if name_outcome_tuple[0] == name:\n                return_value = name_outcome_tuple[1]\n                break\n        return return_value",
    "docstring": "Returns the error message of the child state specified by name.\n\n        Note: This is utility function that is used by the programmer to make a decision based on the final outcome\n        of its child states. A state is not uniquely specified by the name, but as the programmer normally does not want\n        to use state-ids in his code this utility function was defined.\n\n        :param name: The name of the state to get the error message for\n        :return:"
  },
  {
    "code": "def add_class(self, className):\n        if className not in self._dom_classes:\n            self._dom_classes = list(self._dom_classes) + [className]\n        return self",
    "docstring": "Adds a class to the top level element of the widget.\n\n        Doesn't add the class if it already exists."
  },
  {
    "code": "async def on_raw_join(self, message):\n        nick, metadata = self._parse_user(message.source)\n        self._sync_user(nick, metadata)\n        channels = message.params[0].split(',')\n        if self.is_same_nick(self.nickname, nick):\n            for channel in channels:\n                if not self.in_channel(channel):\n                    self._create_channel(channel)\n                await self.rawmsg('MODE', channel)\n        else:\n            for channel in channels:\n                if self.in_channel(channel):\n                    self.channels[channel]['users'].add(nick)\n        for channel in channels:\n            await self.on_join(channel, nick)",
    "docstring": "JOIN command."
  },
  {
    "code": "def cublasStrmm(handle, side, uplo, trans, diag, m, n, alpha, A, lda, B, ldb, C, ldc):\n    status = _libcublas.cublasStrmm_v2(handle,\n                                       _CUBLAS_SIDE_MODE[side], \n                                       _CUBLAS_FILL_MODE[uplo], \n                                       _CUBLAS_OP[trans], \n                                       _CUBLAS_DIAG[diag], \n                                       m, n, ctypes.byref(ctypes.c_float(alpha)),\n                                       int(A), lda, int(B), ldb, int(C), ldc)\n    cublasCheckStatus(status)",
    "docstring": "Matrix-matrix product for real triangular matrix."
  },
  {
    "code": "def file_client(self):\n        if not self._file_client:\n            self._file_client = salt.fileclient.get_file_client(\n                self.opts, self.pillar_rend)\n        return self._file_client",
    "docstring": "Return a file client. Instantiates on first call."
  },
  {
    "code": "def set_image(self, image, add_to_canvas=True):\n        if not isinstance(image, BaseImage.BaseImage):\n            raise ValueError(\"Wrong type of object to load: %s\" % (\n                str(type(image))))\n        canvas_img = self.get_canvas_image()\n        old_image = canvas_img.get_image()\n        self.make_callback('image-unset', old_image)\n        with self.suppress_redraw:\n            canvas_img.set_image(image)\n            if add_to_canvas:\n                try:\n                    self.canvas.get_object_by_tag(self._canvas_img_tag)\n                except KeyError:\n                    self.canvas.add(canvas_img, tag=self._canvas_img_tag)\n                self.canvas.lower_object(canvas_img)",
    "docstring": "Set an image to be displayed.\n\n        If there is no error, the ``'image-unset'`` and ``'image-set'``\n        callbacks will be invoked.\n\n        Parameters\n        ----------\n        image : `~ginga.AstroImage.AstroImage` or `~ginga.RGBImage.RGBImage`\n            Image object.\n\n        add_to_canvas : bool\n            Add image to canvas."
  },
  {
    "code": "def serie(self, serie):\n        return dict(\n            plot=self.node(\n                self.graph.nodes['plot'],\n                class_='series serie-%d color-%d' % (serie.index, serie.index)\n            ),\n            overlay=self.node(\n                self.graph.nodes['overlay'],\n                class_='series serie-%d color-%d' % (serie.index, serie.index)\n            ),\n            text_overlay=self.node(\n                self.graph.nodes['text_overlay'],\n                class_='series serie-%d color-%d' % (serie.index, serie.index)\n            )\n        )",
    "docstring": "Make serie node"
  },
  {
    "code": "def get_values(self):\n        attrs = vars(self).copy()\n        attrs.pop('_server_config')\n        attrs.pop('_fields')\n        attrs.pop('_meta')\n        if '_path_fields' in attrs:\n            attrs.pop('_path_fields')\n        return attrs",
    "docstring": "Return a copy of field values on the current object.\n\n        This method is almost identical to ``vars(self).copy()``. However,\n        only instance attributes that correspond to a field are included in\n        the returned dict.\n\n        :return: A dict mapping field names to user-provided values."
  },
  {
    "code": "def getAnalysisServicesVocabulary(self):\n        bsc = getToolByName(self, 'bika_setup_catalog')\n        brains = bsc(portal_type='AnalysisService',\n                     is_active=True)\n        items = [(b.UID, b.Title) for b in brains]\n        items.insert(0, (\"\", \"\"))\n        items.sort(lambda x, y: cmp(x[1], y[1]))\n        return DisplayList(list(items))",
    "docstring": "Get all active Analysis Services from Bika Setup and return them as Display List."
  },
  {
    "code": "def correct_rates(rates, opt_qes, combs):\n    corrected_rates = np.array([\n        rate / opt_qes[comb[0]] / opt_qes[comb[1]]\n        for rate, comb in zip(rates, combs)\n    ])\n    return corrected_rates",
    "docstring": "Applies optimal qes to rates.\n\n    Should be closer to fitted_rates afterwards.\n\n    Parameters\n    ----------\n    rates: numpy array of rates of all PMT combinations\n    opt_qes: numpy array of optimal qe values for all PMTs\n    combs: pmt combinations used to correct\n\n    Returns\n    -------\n    corrected_rates: numpy array of corrected rates for all PMT combinations"
  },
  {
    "code": "def plot(values, mode_names, title, (xlabel, ylabel), out_file):\n    matplotlib.pyplot.clf()\n    for mode, mode_name in mode_names.iteritems():\n        vals = values[mode]\n        matplotlib.pyplot.plot(\n            [x for x, _ in vals],\n            [y for _, y in vals],\n            label=mode_name\n        )\n    matplotlib.pyplot.title(title)\n    matplotlib.pyplot.xlabel(xlabel)\n    matplotlib.pyplot.ylabel(ylabel)\n    if len(mode_names) > 1:\n        matplotlib.pyplot.legend()\n    matplotlib.pyplot.savefig(out_file)",
    "docstring": "Plot a diagram"
  },
  {
    "code": "def _get_seo_content_types(seo_models):\n    try:\n        return [ContentType.objects.get_for_model(m).id for m in seo_models]\n    except Exception:\n        return []",
    "docstring": "Returns a list of content types from the models defined in settings."
  },
  {
    "code": "def awaitTermination(self, timeout=None):\n        if timeout is not None:\n            IOLoop.current().call_later(timeout, self.stop)\n        IOLoop.current().start()\n        IOLoop.clear_current()",
    "docstring": "Wait for context to stop.\n\n        :param float timeout: in seconds"
  },
  {
    "code": "def starts(self, layer):\n        starts = []\n        for data in self[layer]:\n            starts.append(data[START])\n        return starts",
    "docstring": "Retrieve start positions of elements if given layer."
  },
  {
    "code": "def get_header_as_text(file_content, reference_id):\n    res = _CONTENT_PATTERN.findall(file_content)\n    if len(res) == 2:\n        content = res[0]\n    elif len(res) == 1:\n        return ''\n    else:\n        raise ValueError('Unexpected <code><pre> sections: \"%r\"' % res)\n    return _clean_html(content)",
    "docstring": "\\\n    Returns the cable's header as text.\n    \n    `file_content`\n        The HTML file content, c.f. `get_file_content`."
  },
  {
    "code": "def decrease_posts_count_after_post_deletion(sender, instance, **kwargs):\n    if not instance.approved:\n        return\n    try:\n        assert instance.poster_id is not None\n        poster = User.objects.get(pk=instance.poster_id)\n    except AssertionError:\n        return\n    except ObjectDoesNotExist:\n        return\n    profile, dummy = ForumProfile.objects.get_or_create(user=poster)\n    if profile.posts_count:\n        profile.posts_count = F('posts_count') - 1\n        profile.save()",
    "docstring": "Decreases the member's post count after a post deletion.\n\n    This receiver handles the deletion of a forum post: the posts count related to the post's\n    author is decreased."
  },
  {
    "code": "def _get_peer_connection(self, blacklist=None):\n        blacklist = blacklist or set()\n        peer = None\n        connection = None\n        while connection is None:\n            peer = self._choose(blacklist)\n            if not peer:\n                raise NoAvailablePeerError(\n                    \"Can't find an available peer for '%s'\" % self.service\n                )\n            try:\n                connection = yield peer.connect()\n            except NetworkError as e:\n                log.info(\n                    'Failed to connect to %s. Trying a different host.',\n                    peer.hostport,\n                    exc_info=e,\n                )\n                connection = None\n                blacklist.add(peer.hostport)\n        raise gen.Return((peer, connection))",
    "docstring": "Find a peer and connect to it.\n\n        Returns a ``(peer, connection)`` tuple.\n\n        Raises ``NoAvailablePeerError`` if no healthy peers are found.\n\n        :param blacklist:\n            If given, a set of hostports for peers that we must not try."
  },
  {
    "code": "def set(self, path, item, replace):\n        if len(path) == 0:\n            if self._item is None or replace:\n                self._item = item\n            return self._item\n        else:\n            head, tail = path[0], path[1:]\n            if head.startswith(':'):\n                default = (head[1:], self.__class__())\n                _, rtree = self._subtrees.setdefault(self._WILDCARD, default)\n                return rtree.set(tail, item, replace)\n            else:\n                rtree = self._subtrees.setdefault(head, self.__class__())\n                return rtree.set(tail, item, replace)",
    "docstring": "Sets item for `path` and returns the item.\n        Replaces existing item with `item` when `replace` is true\n\n        :param path: Path for item\n        :param item: New item\n        :param replace: Updating mode\n        :type path: list\n        :type item: object\n        :type replace: bool"
  },
  {
    "code": "def execute(self):\n        if self._decode_output:\n            with Popen(self.command, shell=True, stdout=PIPE) as process:\n                self._output = [i.decode(\"utf-8\").strip() for i in process.stdout]\n                self._success = True\n        else:\n            os.system(self.command)\n            self._success = True\n        return self",
    "docstring": "Execute a system command."
  },
  {
    "code": "def shell(state, host, commands, chdir=None):\n    if isinstance(commands, six.string_types):\n        commands = [commands]\n    for command in commands:\n        if chdir:\n            yield 'cd {0} && ({1})'.format(chdir, command)\n        else:\n            yield command",
    "docstring": "Run raw shell code.\n\n    + commands: command or list of commands to execute on the remote server\n    + chdir: directory to cd into before executing commands"
  },
  {
    "code": "def gtpswd(prompt, confirmPassword):\n    try:\n        return util.getPassword(prompt=prompt,\n                                confirmPrompt=confirmPassword,\n                                confirm=True)\n    except TypeError:\n        return util.getPassword(prompt=prompt,\n                                confirm=True)",
    "docstring": "Temporary wrapper for Twisted's getPassword until a version that supports\n    customizing the 'confirm' prompt is released."
  },
  {
    "code": "def trace_module(module, tracer=tracer, pattern=r\".*\", flags=0):\n    if is_traced(module):\n        return False\n    global REGISTERED_MODULES\n    for name, function in inspect.getmembers(module, inspect.isfunction):\n        if name not in module.__all__ or not re.search(pattern, name, flags=flags):\n            continue\n        trace_function(module, function, tracer)\n    for name, cls in inspect.getmembers(module, inspect.isclass):\n        if name not in module.__all__ or not re.search(pattern, name, flags=flags):\n            continue\n        trace_class(cls, tracer, pattern, flags)\n    REGISTERED_MODULES.add(module)\n    set_traced(module)\n    return True",
    "docstring": "Traces given module members using given tracer.\n\n    :param module: Module to trace.\n    :type module: ModuleType\n    :param tracer: Tracer.\n    :type tracer: object\n    :param pattern: Matching pattern.\n    :type pattern: unicode\n    :param flags: Matching regex flags.\n    :type flags: int\n    :return: Definition success.\n    :rtype: bool\n\n    :note: Only members exported by **__all__** attribute will be traced."
  },
  {
    "code": "def get_value(cls, object_version, key):\n        obj = cls.get(object_version, key)\n        return obj.value if obj else None",
    "docstring": "Get the tag value."
  },
  {
    "code": "def matrix_to_images(data_matrix, mask):\n    if data_matrix.ndim > 2:\n        data_matrix = data_matrix.reshape(data_matrix.shape[0], -1)\n    numimages = len(data_matrix)\n    numVoxelsInMatrix = data_matrix.shape[1]\n    numVoxelsInMask = (mask >= 0.5).sum()\n    if numVoxelsInMask != numVoxelsInMatrix:\n        raise ValueError('Num masked voxels %i must match data matrix %i' % (numVoxelsInMask, numVoxelsInMatrix))\n    imagelist = []\n    for i in range(numimages):\n        img = mask.clone()\n        img[mask >= 0.5] = data_matrix[i,:]\n        imagelist.append(img)\n    return imagelist",
    "docstring": "Unmasks rows of a matrix and writes as images\n\n    ANTsR function: `matrixToImages`\n\n    Arguments\n    ---------\n    data_matrix : numpy.ndarray\n        each row corresponds to an image\n        array should have number of columns equal to non-zero voxels in the mask\n\n    mask : ANTsImage\n        image containing a binary mask. Rows of the matrix are\n        unmasked and written as images. The mask defines the output image space\n\n    Returns\n    -------\n    list of ANTsImage types"
  },
  {
    "code": "def extract_symbol_app(parser, _, args):\n    parser.add_argument('file', help='ELF file to extract a symbol from')\n    parser.add_argument('symbol', help='the symbol to extract')\n    args = parser.parse_args(args)\n    return ELF(args.file).get_symbol(args.symbol).content",
    "docstring": "Extract a symbol from an ELF file."
  },
  {
    "code": "def error_state(self):\n        self.buildstate.state.lasttime = time()\n        self.buildstate.commit()\n        return self.buildstate.state.error",
    "docstring": "Set the error condition"
  },
  {
    "code": "def copy(self):\n        parser_copy = self.__class__(self.argument_class, self.namespace_class)\n        parser_copy.args = deepcopy(self.args)\n        parser_copy.trim = self.trim\n        parser_copy.bundle_errors = self.bundle_errors\n        return parser_copy",
    "docstring": "Creates a copy of this RequestParser with the same set of arguments"
  },
  {
    "code": "def fastaReadHeaders(fasta):\n    headers = []\n    fileHandle = open(fasta, 'r')\n    line = fileHandle.readline()\n    while line != '':\n        assert line[-1] == '\\n'\n        if line[0] == '>':\n            headers.append(line[1:-1])\n        line = fileHandle.readline()\n    fileHandle.close()\n    return headers",
    "docstring": "Returns a list of fasta header lines, excluding"
  },
  {
    "code": "def community_neighbors(c_j, reverse_index_rows, unavailable_communities, unavailable_communities_counter):\n    indices = list()\n    extend = indices.extend\n    for node in c_j:\n        extend(reverse_index_rows[node])\n    indices = np.array(indices)\n    indices = np.setdiff1d(indices, unavailable_communities[:unavailable_communities_counter+1])\n    return indices",
    "docstring": "Finds communities with shared nodes to a seed community. Called by mroc.\n\n    Inputs:  - c_j: The seed community for which we want to find which communities overlap.\n             - reverse_index_rows: A node to community indicator matrix.\n             - unavailable_communities: A set of communities that have already either been merged or failed to merge.\n             - unavailable_communities_counter: The number of such communities.\n\n    Outputs: - indices: An array containing the communities that exhibit overlap with the seed community."
  },
  {
    "code": "def tmatrix_cov(C, row=None):\n    r\n    if row is None:\n        alpha = C + 1.0\n        alpha0 = alpha.sum(axis=1)\n        norm = alpha0 ** 2 * (alpha0 + 1.0)\n        Z = -alpha[:, :, np.newaxis] * alpha[:, np.newaxis, :]\n        ind = np.diag_indices(C.shape[0])\n        Z[:, ind[0], ind[1]] += alpha0[:, np.newaxis] * alpha\n        cov = Z / norm[:, np.newaxis, np.newaxis]\n        return cov\n    else:\n        alpha = C[row, :] + 1.0\n        return dirichlet_covariance(alpha)",
    "docstring": "r\"\"\"Covariance tensor for the non-reversible transition matrix ensemble\n\n    Normally the covariance tensor cov(p_ij, p_kl) would carry four indices\n    (i,j,k,l). In the non-reversible case rows are independent so that\n    cov(p_ij, p_kl)=0 for i not equal to k. Therefore the function will only\n    return cov(p_ij, p_ik).\n\n    Parameters\n    ----------\n    C : (M, M) ndarray\n        Count matrix\n    row : int (optional)\n        If row is given return covariance matrix for specified row only\n\n    Returns\n    -------\n    cov : (M, M, M) ndarray\n        Covariance tensor"
  },
  {
    "code": "def find_ruuvitags(bt_device=''):\n        log.info('Finding RuuviTags. Stop with Ctrl+C.')\n        datas = dict()\n        for new_data in RuuviTagSensor._get_ruuvitag_datas(bt_device=bt_device):\n            if new_data[0] in datas:\n                continue\n            datas[new_data[0]] = new_data[1]\n            log.info(new_data[0])\n            log.info(new_data[1])\n        return datas",
    "docstring": "Find all RuuviTags. Function will print the mac and the state of the sensors when found.\n        Function will execute as long as it is stopped. Stop ecexution with Crtl+C.\n\n        Returns:\n            dict: MAC and state of found sensors"
  },
  {
    "code": "def nodes(**kwargs):\n    cfg = _setup_conn(**kwargs)\n    try:\n        api_instance = kubernetes.client.CoreV1Api()\n        api_response = api_instance.list_node()\n        return [k8s_node['metadata']['name'] for k8s_node in api_response.to_dict().get('items')]\n    except (ApiException, HTTPError) as exc:\n        if isinstance(exc, ApiException) and exc.status == 404:\n            return None\n        else:\n            log.exception('Exception when calling CoreV1Api->list_node')\n            raise CommandExecutionError(exc)\n    finally:\n        _cleanup(**cfg)",
    "docstring": "Return the names of the nodes composing the kubernetes cluster\n\n    CLI Examples::\n\n        salt '*' kubernetes.nodes\n        salt '*' kubernetes.nodes kubeconfig=/etc/salt/k8s/kubeconfig context=minikube"
  },
  {
    "code": "def _range_from_slice(myslice, start=None, stop=None, step=None, length=None):\n    assert isinstance(myslice, slice)\n    step = myslice.step if myslice.step is not None else step\n    if step is None:\n        step = 1\n    start = myslice.start if myslice.start is not None else start\n    if start is None:\n        start = 0\n    stop = myslice.stop if myslice.stop is not None else stop\n    if length is not None:\n        stop_inferred = floor(start + step * length)\n        if stop is not None and stop < stop_inferred:\n            raise ValueError(\"'stop' ({stop}) and \".format(stop=stop) +\n                             \"'length' ({length}) \".format(length=length) +\n                             \"are not compatible.\")\n        stop = stop_inferred\n    if stop is None and length is None:\n        raise ValueError(\"'stop' and 'length' cannot be both unspecified.\")\n    myrange = np.arange(start, stop, step)\n    if length is not None:\n        assert len(myrange) == length\n    return myrange",
    "docstring": "Convert a slice to an array of integers."
  },
  {
    "code": "def cliques(self, xg):\n        g = nx.DiGraph()\n        for (x,y) in self.merged_ontology.get_graph().edges():\n            g.add_edge(x,y)\n        for (x,y) in xg.edges():\n            g.add_edge(x,y)\n            g.add_edge(y,x)\n        return list(strongly_connected_components(g))",
    "docstring": "Return all equivalence set cliques, assuming each edge in the xref graph is treated as equivalent,\n        and all edges in ontology are subClassOf\n\n        Arguments\n        ---------\n        xg : Graph\n            an xref graph\n\n        Returns\n        -------\n        list of sets"
  },
  {
    "code": "def _add_resources(data, runtime):\n    if \"config\" not in data:\n        data[\"config\"] = {}\n    resources = data.get(\"resources\", {}) or {}\n    if isinstance(resources, six.string_types) and resources.startswith((\"{\", \"[\")):\n        resources = json.loads(resources)\n        data[\"resources\"] = resources\n    assert isinstance(resources, dict), (resources, data)\n    data[\"config\"][\"resources\"] = resources\n    memory = int(float(runtime[\"ram\"]) / float(runtime[\"cores\"]))\n    data[\"config\"][\"resources\"].update({\"default\": {\"cores\": int(runtime[\"cores\"]),\n                                                    \"memory\": \"%sM\" % memory,\n                                                    \"jvm_opts\": [\"-Xms%sm\" % min(1000, memory // 2),\n                                                                    \"-Xmx%sm\" % memory]}})\n    data[\"config\"][\"algorithm\"][\"num_cores\"] = int(runtime[\"cores\"])\n    return data",
    "docstring": "Merge input resources with current CWL runtime parameters."
  },
  {
    "code": "def demote(self, amount_, *queries, **kw):\n        q = Q()\n        for query in queries:\n            q += query\n        q += Q(**kw)\n        return self._clone(next_step=('demote', (amount_, q)))",
    "docstring": "Returns a new S instance with boosting query and demotion.\n\n        You can demote documents that match query criteria::\n\n            q = (S().query(title='trucks')\n                    .demote(0.5, description__match='gross'))\n\n            q = (S().query(title='trucks')\n                    .demote(0.5, Q(description__match='gross')))\n\n        This is implemented using the boosting query in\n        Elasticsearch. Anything you specify with ``.query()`` goes\n        into the positive section. The negative query and negative\n        boost portions are specified as the first and second arguments\n        to ``.demote()``.\n\n        .. Note::\n\n           Calling this again will overwrite previous ``.demote()``\n           calls."
  },
  {
    "code": "def get_shell(self):\r\n        if (not hasattr(self.shell, 'get_doc') or\r\n                (hasattr(self.shell, 'is_running') and\r\n                 not self.shell.is_running())):\r\n            self.shell = None\r\n            if self.main.ipyconsole is not None:\r\n                shell = self.main.ipyconsole.get_current_shellwidget()\r\n                if shell is not None and shell.kernel_client is not None:\r\n                    self.shell = shell\r\n            if self.shell is None:\r\n                self.shell = self.internal_shell\r\n        return self.shell",
    "docstring": "Return shell which is currently bound to Help,\r\n        or another running shell if it has been terminated"
  },
  {
    "code": "def encode_message(self):\n        if not self._message:\n            raise ValueError(\"No message data to encode.\")\n        cloned_data = self._message.clone()\n        self._populate_message_attributes(cloned_data)\n        encoded_data = []\n        c_uamqp.get_encoded_message_size(cloned_data, encoded_data)\n        return b\"\".join(encoded_data)",
    "docstring": "Encode message to AMQP wire-encoded bytearray.\n\n        :rtype: bytearray"
  },
  {
    "code": "def to_json(self):\n        json_data = dict()\n        for field_name, field_obj in self._fields.items():\n            if isinstance(field_obj, NestedDocumentField):\n                nested_document = field_obj.__get__(self, self.__class__)\n                value = None if nested_document is None else nested_document.to_json()\n            elif isinstance(field_obj, BaseField):\n                value = field_obj.__get__(self, self.__class__)\n                value = field_obj.to_json(value)\n            else:\n                continue\n            if value is None:\n                continue\n            json_data[field_name] = value\n        return json_data",
    "docstring": "Converts given document to JSON dict."
  },
  {
    "code": "def _copy(self):\n        ins = copy.copy(self)\n        ins._fire_page_number(self.page_number + 1)\n        return ins",
    "docstring": "needs to update page numbers"
  },
  {
    "code": "def raw_name(self):\n        parts = self.raw_parts\n        if self.is_absolute():\n            parts = parts[1:]\n            if not parts:\n                return \"\"\n            else:\n                return parts[-1]\n        else:\n            return parts[-1]",
    "docstring": "The last part of raw_parts."
  },
  {
    "code": "async def georadiusbymember(self, name, member, radius, unit=None,\n                                withdist=False, withcoord=False, withhash=False,\n                                count=None, sort=None, store=None, store_dist=None):\n        return await self._georadiusgeneric('GEORADIUSBYMEMBER',\n                                            name, member, radius, unit=unit,\n                                            withdist=withdist, withcoord=withcoord,\n                                            withhash=withhash, count=count,\n                                            sort=sort, store=store,\n                                            store_dist=store_dist)",
    "docstring": "This command is exactly like ``georadius`` with the sole difference\n        that instead of taking, as the center of the area to query, a longitude\n        and latitude value, it takes the name of a member already existing\n        inside the geospatial index represented by the sorted set."
  },
  {
    "code": "def _req_lixian_task_lists(self, page=1):\n        url = 'http://115.com/lixian/'\n        params = {'ct': 'lixian', 'ac': 'task_lists'}\n        self._load_signatures()\n        data = {\n            'page': page,\n            'uid': self.user_id,\n            'sign': self._signatures['offline_space'],\n            'time': self._lixian_timestamp,\n        }\n        req = Request(method='POST', url=url, params=params, data=data)\n        res = self.http.send(req)\n        if res.state:\n            self._task_count = res.content['count']\n            self._task_quota = res.content['quota']\n            return res.content['tasks']\n        else:\n            msg = 'Failed to get tasks.'\n            raise RequestFailure(msg)",
    "docstring": "This request will cause the system to create a default downloads\n        directory if it does not exist"
  },
  {
    "code": "def fetch(self, endpoint, data = None):\n        payload = {\n            \"lastServerChangeId\": \"-1\",\n            \"csrf\": self.__csrf,\n            \"apiClient\": \"WEB\"\n        }\n        if data is not None:\n            payload.update(data)\n        return self.post(endpoint, payload)",
    "docstring": "for getting data after logged in"
  },
  {
    "code": "def execute(self, cmd, cwd):\n        self.output = \"\"\n        env = os.environ.copy()\n        env.update(self.env)\n        if six.PY2:\n            if self._stdout == self.DEVNULL:\n                self._stdout = open(os.devnull, 'w+b')\n            if self._stderr == self.DEVNULL:\n                self._stderr = open(os.devnull, 'w+b')\n        proc = subprocess.Popen(\n            cmd, stdout=self._stdout, stderr=self._stderr,\n            bufsize=0, universal_newlines=True,\n            cwd=cwd, env=env,\n            close_fds=ON_POSIX\n        )\n        for line in self._unbuffered(proc):\n            self.line_handler(line)\n        return_code = proc.poll()\n        if return_code:\n            logger.error(self.output)\n            raise subprocess.CalledProcessError(\n                return_code, cmd, output=str(self.output)\n            )\n        return self.output",
    "docstring": "Execute commands and output this\n\n        :param cmd: -- list of cmd command and arguments\n        :type cmd: list\n        :param cwd: -- workdir for executions\n        :type cwd: str,unicode\n        :return: -- string with full output\n        :rtype: str"
  },
  {
    "code": "def delete_attribute_group(group_id, **kwargs):\n    user_id = kwargs['user_id']\n    try:\n        group_i = db.DBSession.query(AttrGroup).filter(AttrGroup.id==group_id).one()\n        group_i.project.check_write_permission(user_id)\n        db.DBSession.delete(group_i)\n        db.DBSession.flush()\n        log.info(\"Group %s in project %s deleted\", group_i.id, group_i.project_id)\n    except NoResultFound:\n        raise HydraError('No Attribute Group %s was found', group_id)\n    return 'OK'",
    "docstring": "Delete an attribute group."
  },
  {
    "code": "def _parse_dtype(self, space):\n    if isinstance(space, gym.spaces.Discrete):\n      return tf.int32\n    if isinstance(space, gym.spaces.Box):\n      return tf.float32\n    raise NotImplementedError()",
    "docstring": "Get a tensor dtype from a OpenAI Gym space.\n\n    Args:\n      space: Gym space.\n\n    Raises:\n      NotImplementedError: For spaces other than Box and Discrete.\n\n    Returns:\n      TensorFlow data type."
  },
  {
    "code": "def create(self, name, kind, **kwargs):\n        kindpath = self.kindpath(kind)\n        self.post(kindpath, name=name, **kwargs)\n        name = UrlEncoded(name, encode_slash=True)\n        path = _path(\n            self.path + kindpath,\n            '%s:%s' % (kwargs['restrictToHost'], name) \\\n                if 'restrictToHost' in kwargs else name\n                )\n        return Input(self.service, path, kind)",
    "docstring": "Creates an input of a specific kind in this collection, with any\n        arguments you specify.\n\n        :param `name`: The input name.\n        :type name: ``string``\n        :param `kind`: The kind of input:\n\n            - \"ad\": Active Directory\n\n            - \"monitor\": Files and directories\n\n            - \"registry\": Windows Registry\n\n            - \"script\": Scripts\n\n            - \"splunktcp\": TCP, processed\n\n            - \"tcp\": TCP, unprocessed\n\n            - \"udp\": UDP\n\n            - \"win-event-log-collections\": Windows event log\n\n            - \"win-perfmon\": Performance monitoring\n\n            - \"win-wmi-collections\": WMI\n\n        :type kind: ``string``\n        :param `kwargs`: Additional arguments (optional). For more about the\n            available parameters, see `Input parameters <http://dev.splunk.com/view/SP-CAAAEE6#inputparams>`_ on Splunk Developer Portal.\n\n        :type kwargs: ``dict``\n\n        :return: The new :class:`Input`."
  },
  {
    "code": "def _maybe_repeat(self, x):\n    if isinstance(x, list):\n      assert len(x) == self.n\n      return x\n    else:\n      return [x] * self.n",
    "docstring": "Utility function for processing arguments that are singletons or lists.\n\n    Args:\n      x: either a list of self.n elements, or not a list.\n\n    Returns:\n      a list of self.n elements."
  },
  {
    "code": "def get_v_total_stress_at_depth(self, z):\n        if not hasattr(z, \"__len__\"):\n            return self.one_vertical_total_stress(z)\n        else:\n            sigma_v_effs = []\n            for value in z:\n                sigma_v_effs.append(self.one_vertical_total_stress(value))\n            return np.array(sigma_v_effs)",
    "docstring": "Determine the vertical total stress at depth z, where z can be a number or an array of numbers."
  },
  {
    "code": "def parse_changes():\n    with open('CHANGES') as changes:\n        for match in re.finditer(RE_CHANGES, changes.read(1024), re.M):\n            if len(match.group(1)) != len(match.group(3)):\n                error('incorrect underline in CHANGES')\n            date = datetime.datetime.strptime(match.group(4),\n                                              '%Y-%m-%d').date()\n            if date != datetime.date.today():\n                error('release date is not today')\n            return match.group(2)\n    error('invalid release entry in CHANGES')",
    "docstring": "grab version from CHANGES and validate entry"
  },
  {
    "code": "def add_node(self, agent_type=None, state=None, name='network_process', **state_params):\n        agent_id = int(len(self.global_topology.nodes()))\n        agent = agent_type(self.env, agent_id=agent_id, state=state, name=name, **state_params)\n        self.global_topology.add_node(agent_id, {'agent': agent})\n        return agent_id",
    "docstring": "Add a new node to the current network\n\n        Parameters\n        ----------\n        agent_type : NetworkAgent subclass\n            Agent in the new node will be instantiated using this agent class\n        state : object\n            State of the Agent, this may be an integer or string or any other\n        name : str, optional\n            Descriptive name of the agent\n        state_params : keyword arguments, optional\n            Key-value pairs of other state parameters for the agent\n\n        Return\n        ------\n        int\n            Agent ID of the new node"
  },
  {
    "code": "def hash_str(data, hasher=None):\n    hasher = hasher or hashlib.sha1()\n    hasher.update(data)\n    return hasher",
    "docstring": "Checksum hash a string."
  },
  {
    "code": "def add_parent(self,node):\n    if not isinstance(node, (CondorDAGNode,CondorDAGManNode) ):\n      raise CondorDAGNodeError, \"Parent must be a CondorDAGNode or a CondorDAGManNode\"\n    self.__parents.append( node )",
    "docstring": "Add a parent to this node. This node will not be executed until the\n    parent node has run sucessfully.\n    @param node: CondorDAGNode to add as a parent."
  },
  {
    "code": "def get_next_application_id(nodes):\n    used = set([n.application_id for n in nodes])\n    pool = set(range(1, 512))\n    try:\n        return (pool - used).pop()\n    except KeyError:\n        raise IOUError(\"Cannot create a new IOU VM (limit of 512 VMs on one host reached)\")",
    "docstring": "Calculates free application_id from given nodes\n\n    :param nodes:\n    :raises IOUError when exceeds number\n    :return: integer first free id"
  },
  {
    "code": "def user(self, username=None, pk=None, **kwargs):\n        _users = self.users(username=username, pk=pk, **kwargs)\n        if len(_users) == 0:\n            raise NotFoundError(\"No user criteria matches\")\n        if len(_users) != 1:\n            raise MultipleFoundError(\"Multiple users fit criteria\")\n        return _users[0]",
    "docstring": "User of KE-chain.\n\n        Provides single user of :class:`User` of KE-chain. You can filter on username or id or an advanced filter.\n\n        :param username: (optional) username to filter\n        :type username: basestring or None\n        :param pk: (optional) id of the user to filter\n        :type pk: basestring or None\n        :param kwargs: Additional filtering keyword=value arguments\n        :type kwargs: dict or None\n        :return: List of :class:`User`\n        :raises NotFoundError: when a user could not be found\n        :raises MultipleFoundError: when more than a single user can be found"
  },
  {
    "code": "def project_layout(proposal, user=None, repo=None, log=None):\n    proposal = proposal.lower()\n    try:\n        os.mkdir(proposal)\n    except FileExistsError:\n        log.info('Skip directory structure, as project seem to already exists')\n    with open('.gitignore', 'w') as f:\n        f.write(\n)\n    with open( '/'.join([proposal, '__init__.py']), 'w') as f: \n        f.write(\n)\n    travis_yml()\n    log.info('Workig in %s', os.getcwd())\n    os.listdir('.')\n    subprocess.call(['git','add','.'], )\n    subprocess.call(['git','commit',\"-am'initial commit of %s'\" % proposal])\n    subprocess.call(['git', \"push\", \"origin\", \"master:master\"])",
    "docstring": "generate the project template\n\n    proposal is the name of the project, \n    user is an object containing some information about the user. \n        - full name, \n        - github username\n        - email"
  },
  {
    "code": "def get_agent(self,\n                  parent,\n                  retry=google.api_core.gapic_v1.method.DEFAULT,\n                  timeout=google.api_core.gapic_v1.method.DEFAULT,\n                  metadata=None):\n        if 'get_agent' not in self._inner_api_calls:\n            self._inner_api_calls[\n                'get_agent'] = google.api_core.gapic_v1.method.wrap_method(\n                    self.transport.get_agent,\n                    default_retry=self._method_configs['GetAgent'].retry,\n                    default_timeout=self._method_configs['GetAgent'].timeout,\n                    client_info=self._client_info,\n                )\n        request = agent_pb2.GetAgentRequest(parent=parent, )\n        return self._inner_api_calls['get_agent'](\n            request, retry=retry, timeout=timeout, metadata=metadata)",
    "docstring": "Retrieves the specified agent.\n\n        Example:\n            >>> import dialogflow_v2\n            >>>\n            >>> client = dialogflow_v2.AgentsClient()\n            >>>\n            >>> parent = client.project_path('[PROJECT]')\n            >>>\n            >>> response = client.get_agent(parent)\n\n        Args:\n            parent (str): Required. The project that the agent to fetch is associated with.\n                Format: ``projects/<Project ID>``.\n            retry (Optional[google.api_core.retry.Retry]):  A retry object used\n                to retry requests. If ``None`` is specified, requests will not\n                be retried.\n            timeout (Optional[float]): The amount of time, in seconds, to wait\n                for the request to complete. Note that if ``retry`` is\n                specified, the timeout applies to each individual attempt.\n            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n                that is provided to the method.\n\n        Returns:\n            A :class:`~google.cloud.dialogflow_v2.types.Agent` instance.\n\n        Raises:\n            google.api_core.exceptions.GoogleAPICallError: If the request\n                    failed for any reason.\n            google.api_core.exceptions.RetryError: If the request failed due\n                    to a retryable error and retry attempts failed.\n            ValueError: If the parameters are invalid."
  },
  {
    "code": "def _next_datetime_with_utc_hour(table_name, utc_hour):\n    today = datetime.date.today()\n    start_date_time = datetime.datetime(\n        year=today.year,\n        month=today.month,\n        day=today.day,\n        hour=utc_hour,\n        minute=_get_deterministic_value_for_table_name(table_name, 60),\n        second=_get_deterministic_value_for_table_name(table_name, 60)\n    )\n    if start_date_time < datetime.datetime.utcnow():\n        one_day = datetime.timedelta(days=1)\n        start_date_time += one_day\n    return start_date_time",
    "docstring": "Datapipeline API is throttling us, as all the pipelines are started at the same time.\n    We would like to uniformly distribute the startTime over a 60 minute window.\n\n    Return the next future utc datetime where\n        hour == utc_hour\n        minute = A value between 0-59 (depending on table name)\n        second = A value between 0-59 (depending on table name)"
  },
  {
    "code": "def set_rest_notification(self, hit_type, url, event_types=None):\n        return self._set_notification(hit_type, 'REST', url, event_types)",
    "docstring": "Performs a SetHITTypeNotification operation to set REST notification\n        for a specified HIT type"
  },
  {
    "code": "def fetcher_with_object(cls, parent_object, relationship=\"child\"):\n        fetcher = cls()\n        fetcher.parent_object = parent_object\n        fetcher.relationship = relationship\n        rest_name = cls.managed_object_rest_name()\n        parent_object.register_fetcher(fetcher, rest_name)\n        return fetcher",
    "docstring": "Register the fetcher for a served object.\n\n            This method will fill the fetcher with `managed_class` instances\n\n            Args:\n                parent_object: the instance of the parent object to serve\n\n            Returns:\n                It returns the fetcher instance."
  },
  {
    "code": "def pad_to(data, alignment, pad_character=b'\\xFF'):\n    pad_mod = len(data) % alignment\n    if pad_mod != 0:\n        data += pad_character * (alignment - pad_mod)\n    return data",
    "docstring": "Pad to the next alignment boundary"
  },
  {
    "code": "def is_moderated(self, curr_time, pipe):\n        value = pipe.get(self.moderate_key)\n        if value is None:\n            value = 0.0\n        else:\n            value = float(value)\n        if (curr_time - value) < self.moderation:\n            return True\n        return False",
    "docstring": "Tests to see if the moderation limit is not exceeded\n\n        @return: True if the moderation limit is exceeded"
  },
  {
    "code": "def _find_combo_text(widget, value):\n    i = widget.findText(value)\n    if i == -1:\n        raise ValueError(\"%s not found in combo box\" % value)\n    else:\n        return i",
    "docstring": "Returns the index in a combo box where text == value\n\n    Raises a ValueError if data is not found"
  },
  {
    "code": "def make_compound_word(self, start_index, how_many):\n        if not self.quiet:\n            compound_word = \"\"\n            for word in self.unit_list[start_index:start_index + how_many]:\n                compound_word += \" \" + word.text\n            print compound_word.strip(), \"-->\",\"_\".join(compound_word.split())\n        for other_unit in range(1, how_many):\n            self.unit_list[start_index].original_text.append(self.unit_list[start_index + other_unit].text)\n            self.unit_list[start_index].text += \"_\" + self.unit_list[start_index + other_unit].text\n        self.unit_list[start_index].end_time = self.unit_list[start_index + how_many - 1].end_time\n        self.unit_list = self.unit_list[:start_index + 1] + self.unit_list[start_index + how_many:]",
    "docstring": "Combines two Units in self.unit_list to make a compound word token.\n\n        :param int start_index: Index of first Unit in self.unit_list to be combined\n        :param int how_many: Index of how many Units in self.unit_list to be combined.\n\n        Modifies:\n                - self.unit_list: Modifies the Unit corresponding to the first word\n                    in the compound word. Changes the .text property to include .text\n                    properties from subsequent Units, separted by underscores. Modifies\n                    the .original_text property to record each componentword separately.\n                    Modifies the .end_time property to be the .end_time of the final unit\n                    in the compound word.  Finally, after extracting the text and timing\n                    information, it removes all units in the compound word except for the\n                    first.\n\n        .. note: This method is only used with semantic processing, so we don't need to worry\n            about the phonetic representation of Units."
  },
  {
    "code": "def iterate_with_name(cls):\n        for attr_name, field in cls.iterate_over_fields():\n            structure_name = field.structue_name(attr_name)\n            yield attr_name, structure_name, field",
    "docstring": "Iterate over fields, but also give `structure_name`.\n\n        Format is `(attribute_name, structue_name, field_instance)`.\n        Structure name is name under which value is seen in structure and\n        schema (in primitives) and only there."
  },
  {
    "code": "def rpush(self, key, *args):\n        redis_list = self._get_list(key, 'RPUSH', create=True)\n        redis_list.extend(map(self._encode, args))\n        return len(redis_list)",
    "docstring": "Emulate rpush."
  },
  {
    "code": "def _validate_certificate_url(self, cert_url):\n        parsed_url = urlparse(cert_url)\n        protocol = parsed_url.scheme\n        if protocol.lower() != CERT_CHAIN_URL_PROTOCOL.lower():\n            raise VerificationException(\n                \"Signature Certificate URL has invalid protocol: {}. \"\n                \"Expecting {}\".format(protocol, CERT_CHAIN_URL_PROTOCOL))\n        hostname = parsed_url.hostname\n        if (hostname is None or\n                hostname.lower() != CERT_CHAIN_URL_HOSTNAME.lower()):\n            raise VerificationException(\n                \"Signature Certificate URL has invalid hostname: {}. \"\n                \"Expecting {}\".format(hostname, CERT_CHAIN_URL_HOSTNAME))\n        normalized_path = os.path.normpath(parsed_url.path)\n        if not normalized_path.startswith(CERT_CHAIN_URL_STARTPATH):\n            raise VerificationException(\n                \"Signature Certificate URL has invalid path: {}. \"\n                \"Expecting the path to start with {}\".format(\n                    normalized_path, CERT_CHAIN_URL_STARTPATH))\n        port = parsed_url.port\n        if port is not None and port != CERT_CHAIN_URL_PORT:\n            raise VerificationException(\n                \"Signature Certificate URL has invalid port: {}. \"\n                \"Expecting {}\".format(str(port), str(CERT_CHAIN_URL_PORT)))",
    "docstring": "Validate the URL containing the certificate chain.\n\n        This method validates if the URL provided adheres to the format\n        mentioned here :\n        https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-web-service.html#cert-verify-signature-certificate-url\n\n        :param cert_url: URL for retrieving certificate chain\n        :type cert_url: str\n        :raises: :py:class:`VerificationException` if the URL is invalid"
  },
  {
    "code": "def shell(self):\n        click.echo(click.style(\"NOTICE!\", fg=\"yellow\", bold=True) + \" This is a \" + click.style(\"local\", fg=\"green\", bold=True) + \" shell, inside a \" + click.style(\"Zappa\", bold=True) + \" object!\")\n        self.zappa.shell()\n        return",
    "docstring": "Spawn a debug shell."
  },
  {
    "code": "def atomic_open_for_write(target, binary=False, newline=None, encoding=None):\n    mode = \"w+b\" if binary else \"w\"\n    f = NamedTemporaryFile(\n        dir=os.path.dirname(target),\n        prefix=\".__atomic-write\",\n        mode=mode,\n        encoding=encoding,\n        newline=newline,\n        delete=False,\n    )\n    os.chmod(f.name, stat.S_IWUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)\n    try:\n        yield f\n    except BaseException:\n        f.close()\n        try:\n            os.remove(f.name)\n        except OSError:\n            pass\n        raise\n    else:\n        f.close()\n        try:\n            os.remove(target)\n        except OSError:\n            pass\n        os.rename(f.name, target)",
    "docstring": "Atomically open `target` for writing.\n\n    This is based on Lektor's `atomic_open()` utility, but simplified a lot\n    to handle only writing, and skip many multi-process/thread edge cases\n    handled by Werkzeug.\n\n    :param str target: Target filename to write\n    :param bool binary: Whether to open in binary mode, default False\n    :param str newline: The newline character to use when writing, determined from system if not supplied\n    :param str encoding: The encoding to use when writing, defaults to system encoding\n\n    How this works:\n\n    * Create a temp file (in the same directory of the actual target), and\n      yield for surrounding code to write to it.\n    * If some thing goes wrong, try to remove the temp file. The actual target\n      is not touched whatsoever.\n    * If everything goes well, close the temp file, and replace the actual\n      target with this new file.\n\n    .. code:: python\n\n        >>> fn = \"test_file.txt\"\n        >>> def read_test_file(filename=fn):\n                with open(filename, 'r') as fh:\n                    print(fh.read().strip())\n\n        >>> with open(fn, \"w\") as fh:\n                fh.write(\"this is some test text\")\n        >>> read_test_file()\n        this is some test text\n\n        >>> def raise_exception_while_writing(filename):\n                with open(filename, \"w\") as fh:\n                    fh.write(\"writing some new text\")\n                    raise RuntimeError(\"Uh oh, hope your file didn't get overwritten\")\n\n        >>> raise_exception_while_writing(fn)\n        Traceback (most recent call last):\n            ...\n        RuntimeError: Uh oh, hope your file didn't get overwritten\n        >>> read_test_file()\n        writing some new text\n\n        # Now try with vistir\n        >>> def raise_exception_while_writing(filename):\n                with vistir.contextmanagers.atomic_open_for_write(filename) as fh:\n                    fh.write(\"Overwriting all the text from before with even newer text\")\n                    raise RuntimeError(\"But did it get overwritten now?\")\n\n        >>> raise_exception_while_writing(fn)\n            Traceback (most recent call last):\n                ...\n            RuntimeError: But did it get overwritten now?\n\n        >>> read_test_file()\n            writing some new text"
  },
  {
    "code": "def compute_symm_block_tridiag_covariances(H_diag, H_upper_diag):\n    T, D, _ = H_diag.shape\n    assert H_diag.ndim == 3 and H_diag.shape[2] == D\n    assert H_upper_diag.shape == (T - 1, D, D)\n    J_init = J_11 = J_22 = np.zeros((D, D))\n    h_init = h_1 = h_2 = np.zeros((D,))\n    J_21 = np.swapaxes(H_upper_diag, -1, -2)\n    J_node = H_diag\n    h_node = np.zeros((T, D))\n    _, _, sigmas, E_xt_xtp1 = \\\n        info_E_step(J_init, h_init, 0,\n                    J_11, J_21, J_22, h_1, h_2, np.zeros((T-1)),\n                    J_node, h_node, np.zeros(T))\n    return sigmas, E_xt_xtp1",
    "docstring": "use the info smoother to solve a symmetric block tridiagonal system"
  },
  {
    "code": "def daily_returns(ts, **kwargs):\n    relative = kwargs.get('relative', 0)\n    return returns(ts, delta=BDay(), relative=relative)",
    "docstring": "re-compute ts on a daily basis"
  },
  {
    "code": "def _rand_sparse(m, n, density, format='csr'):\n    nnz = max(min(int(m*n*density), m*n), 0)\n    row = np.random.randint(low=0, high=m-1, size=nnz)\n    col = np.random.randint(low=0, high=n-1, size=nnz)\n    data = np.ones(nnz, dtype=float)\n    return sp.sparse.csr_matrix((data, (row, col)), shape=(m, n))",
    "docstring": "Construct base function for sprand, sprandn."
  },
  {
    "code": "def _try_to_squeeze(obj, raise_=False):\n    if isinstance(obj, pd.Series):\n        return obj\n    elif isinstance(obj, pd.DataFrame) and obj.shape[-1] == 1:\n        return obj.squeeze()\n    else:\n        if raise_:\n            raise ValueError(\"Input cannot be squeezed.\")\n        return obj",
    "docstring": "Attempt to squeeze to 1d Series.\n\n    Parameters\n    ----------\n    obj : {pd.Series, pd.DataFrame}\n    raise_ : bool, default False"
  },
  {
    "code": "def submit_and_render():\n    data = request.files.file\n    template = env.get_template(\"results.html\")\n    if not data:\n        pass\n    results = analyse_pcap(data.file, data.filename)\n    results.update(base)\n    return template.render(results)",
    "docstring": "Blocking POST handler for file submission.\n    Runs snort on supplied file and returns results as rendered html."
  },
  {
    "code": "def saveAsTextFiles(self, prefix, suffix=None):\n        def saveAsTextFile(t, rdd):\n            path = rddToFileName(prefix, suffix, t)\n            try:\n                rdd.saveAsTextFile(path)\n            except Py4JJavaError as e:\n                if 'FileAlreadyExistsException' not in str(e):\n                    raise\n        return self.foreachRDD(saveAsTextFile)",
    "docstring": "Save each RDD in this DStream as at text file, using string\n        representation of elements."
  },
  {
    "code": "async def forget_ticket(self, request):\n        session = await get_session(request)\n        session.pop(self.cookie_name, '')",
    "docstring": "Called to forget the ticket data a request\n\n        Args:\n            request: aiohttp Request object."
  },
  {
    "code": "def flush_to_index(self):\n        assert self._smref is not None\n        assert not isinstance(self._file_or_files, BytesIO)\n        sm = self._smref()\n        if sm is not None:\n            index = self._index\n            if index is None:\n                index = sm.repo.index\n            index.add([sm.k_modules_file], write=self._auto_write)\n            sm._clear_cache()",
    "docstring": "Flush changes in our configuration file to the index"
  },
  {
    "code": "def database_caller_creator(self, host, port, name=None):\n        name = name or 0\n        client = redis.StrictRedis(host=host, port=port, db=name)\n        pipe = client.pipeline(transaction=False)\n        return client, pipe",
    "docstring": "creates a redis connection object\n        which will be later used to modify the db"
  },
  {
    "code": "def shell(ctx, package, working_dir, sudo):\n    ctx.mode = CanariMode.LocalShellDebug\n    from canari.commands.shell import shell\n    shell(package, working_dir, sudo)",
    "docstring": "Runs a Canari interactive python shell"
  },
  {
    "code": "def coerce_types(**kwargs):\n    def _coerce(types):\n        return coerce(*types)\n    return preprocess(**valmap(_coerce, kwargs))",
    "docstring": "Preprocessing decorator that applies type coercions.\n\n    Parameters\n    ----------\n    **kwargs : dict[str -> (type, callable)]\n         Keyword arguments mapping function parameter names to pairs of\n         (from_type, to_type).\n\n    Examples\n    --------\n    >>> @coerce_types(x=(float, int), y=(int, str))\n    ... def func(x, y):\n    ...     return (x, y)\n    ...\n    >>> func(1.0, 3)\n    (1, '3')"
  },
  {
    "code": "def _get_digest(self, info):\n        result = None\n        for algo in ('sha256', 'md5'):\n            key = '%s_digest' % algo\n            if key in info:\n                result = (algo, info[key])\n                break\n        return result",
    "docstring": "Get a digest from a dictionary by looking at keys of the form\n        'algo_digest'.\n\n        Returns a 2-tuple (algo, digest) if found, else None. Currently\n        looks only for SHA256, then MD5."
  },
  {
    "code": "def close(self):\n        self.logger.info(\"Closing Rest Service\")\n        self.closed = True\n        self._close_thread(self._redis_thread, \"Redis setup\")\n        self._close_thread(self._heartbeat_thread, \"Heartbeat\")\n        self._close_thread(self._kafka_thread, \"Kafka setup\")\n        self._close_thread(self._consumer_thread, \"Consumer\")\n        if self.consumer is not None:\n            self.logger.debug(\"Closing kafka consumer\")\n            self.consumer.close()\n        if self.producer is not None:\n            self.logger.debug(\"Closing kafka producer\")\n            self.producer.close(timeout=10)",
    "docstring": "Cleans up anything from the process"
  },
  {
    "code": "def hmetis(hdf5_file_name, N_clusters_max, w = None):\n    if w is None:\n        file_name = wgraph(hdf5_file_name, None, 2)\n    else:\n        file_name = wgraph(hdf5_file_name, w, 3)\n    labels = sgraph(N_clusters_max, file_name)\n    labels = one_to_max(labels)\n    subprocess.call(['rm', file_name])\n    return labels",
    "docstring": "Gives cluster labels ranging from 1 to N_clusters_max for \n        hypergraph partitioning required for HGPA.\n\n    Parameters\n    ----------\n    hdf5_file_name : file handle or string\n    \n    N_clusters_max : int\n    \n    w : array, optional (default = None)\n    \n    Returns\n    -------\n    labels : array of shape (n_samples,)\n        A vector of labels denoting the cluster to which each sample has been assigned\n        as a result of the HGPA approximation algorithm for consensus clustering.\n    \n    Reference\n    ---------\n    G. Karypis, R. Aggarwal, V. Kumar and S. Shekhar, \"Multilevel hypergraph\n    partitioning: applications in VLSI domain\" \n    In: IEEE Transactions on Very Large Scale Integration (VLSI) Systems, \n    Vol. 7, No. 1, pp. 69-79, 1999."
  },
  {
    "code": "def exec_action(module, action, module_parameter=None, action_parameter=None, state_only=False):\n    out = __salt__['cmd.run'](\n        'eselect --brief --colour=no {0} {1} {2} {3}'.format(\n            module, module_parameter or '', action, action_parameter or ''),\n        python_shell=False\n    )\n    out = out.strip().split('\\n')\n    if out[0].startswith('!!! Error'):\n        return False\n    if state_only:\n        return True\n    if not out:\n        return False\n    if len(out) == 1 and not out[0].strip():\n        return False\n    return out",
    "docstring": "Execute an arbitrary action on a module.\n\n    module\n        name of the module to be executed\n\n    action\n        name of the module's action to be run\n\n    module_parameter\n        additional params passed to the defined module\n\n    action_parameter\n        additional params passed to the defined action\n\n    state_only\n        don't return any output but only the success/failure of the operation\n\n    CLI Example (updating the ``php`` implementation used for ``apache2``):\n\n    .. code-block:: bash\n\n        salt '*' eselect.exec_action php update action_parameter='apache2'"
  },
  {
    "code": "def nextSunset(jd, lat, lon):\n    return swe.sweNextTransit(const.SUN, jd, lat, lon, 'SET')",
    "docstring": "Returns the JD of the next sunset."
  },
  {
    "code": "def _wrap_universe(self, func):\n        @wraps(func)\n        def wrapper(graph, *args, **kwargs):\n            if self.universe is None:\n                raise MissingUniverseError(\n                    'Can not run universe function [{}] - No universe is set'.format(func.__name__))\n            return func(self.universe, graph, *args, **kwargs)\n        return wrapper",
    "docstring": "Take a function that needs a universe graph as the first argument and returns a wrapped one."
  },
  {
    "code": "def cache_key(model, pk):\n    \"Generates a cache key for a model instance.\"\n    app = model._meta.app_label\n    name = model._meta.module_name\n    return 'api:{0}:{1}:{2}'.format(app, name, pk)",
    "docstring": "Generates a cache key for a model instance."
  },
  {
    "code": "def isempty(self, tables=None):\n        tables = tables or self.tables\n        for table in tables:\n            if self.num_rows(table) > 0:\n                return False\n        return True",
    "docstring": "Return whether a table or the entire database is empty.\n\n        A database is empty is if it has no tables. A table is empty\n        if it has no rows.\n\n        Arguments:\n\n            tables (sequence of str, optional): If provided, check\n              that the named tables are empty. If not provided, check\n              that all tables are empty.\n\n        Returns:\n\n            bool: True if tables are empty, else false.\n\n        Raises:\n\n            sql.OperationalError: If one or more of the tables do not\n              exist."
  },
  {
    "code": "def put(f, s3_path, multipart_chunk_size_mb=500, logger=None):\n    if not logger:\n        logger = log.get_logger('s3')\n    fname = os.path.basename(f)\n    target = os.path.join(s3_path, fname)\n    s3cmd_cline = 's3cmd put {} {} --multipart-chunk-size-mb {}'.format(f,\n                                                                        target,\n                                                                        multipart_chunk_size_mb)\n    print_put_info(fname, target, logger)\n    s3cmd = sp.Popen(s3cmd_cline,\n                     stdout=sp.PIPE,\n                     stderr=sp.PIPE,\n                     shell=True)\n    stdout, stderr = s3cmd.communicate()",
    "docstring": "Uploads a single file to S3, using s3cmd.\n\n    Args:\n\n        f (str): Path to a single file.\n\n        s3_path (str): The S3 path, with the filename omitted. The S3 filename\n            will be the basename of the ``f``. For example::\n\n                put(f='/path/to/myfile.tar.gz', s3_path='s3://my_bucket/path/to/')\n\n            will result in an uploaded S3 path of ``s3://my_bucket/path/to/myfile.tar.gz``"
  },
  {
    "code": "def opt_to_ri(f, res, nm):\n    r\n    ri = nm + f / (2 * np.pi) * res\n    return ri",
    "docstring": "r\"\"\"Convert the OPT object function to refractive index\n\n    In :abbr:`OPT (Optical Projection Tomography)`, the object function\n    is computed from the raw phase data. This method converts phase data\n    to refractive index data.\n\n    .. math::\n\n        n(\\mathbf{r})  = n_\\mathrm{m} +\n            \\frac{f(\\mathbf{r}) \\cdot \\lambda}{2 \\pi}\n\n    Parameters\n    ----------\n    f: n-dimensional ndarray\n        The reconstructed object function :math:`f(\\mathbf{r})`.\n    res: float\n        The size of the vacuum wave length :math:`\\lambda` in pixels.\n    nm: float\n        The refractive index of the medium :math:`n_\\mathrm{m}` that\n        surrounds the object in :math:`f(\\mathbf{r})`.\n\n    Returns\n    -------\n    ri: n-dimensional ndarray\n        The complex refractive index :math:`n(\\mathbf{r})`.\n\n    Notes\n    -----\n    This function is not meant to be used with diffraction tomography\n    data. For ODT, use :py:func:`odt_to_ri` instead."
  },
  {
    "code": "def update(self, data=None, priority=None, ttl=None, comment=None):\n        return self.manager.update_record(self.domain_id, self, data=data,\n            priority=priority, ttl=ttl, comment=comment)",
    "docstring": "Modifies this record."
  },
  {
    "code": "def multiplicative_jitter(x, epsilon=1e-2):\n  if epsilon == 0:\n    return x\n  return x * mtf.random_uniform(\n      x.mesh, x.shape, minval=1.0 - epsilon, maxval=1.0+epsilon, dtype=x.dtype)",
    "docstring": "Multiply values by a random number between 1-epsilon and 1+epsilon.\n\n  Makes models more resilient to rounding errors introduced by bfloat16.\n  This seems particularly important for logits.\n\n  Args:\n    x: a mtf.Tensor\n    epsilon: a floating point value\n\n  Returns:\n    a mtf.Tensor with the same type and shape as x."
  },
  {
    "code": "def update_values(self):\n        Q, R, A, B, N, C = self.Q, self.R, self.A, self.B, self.N, self.C\n        P, d = self.P, self.d\n        S1 = Q + self.beta * dot(B.T, dot(P, B))\n        S2 = self.beta * dot(B.T, dot(P, A)) + N\n        S3 = self.beta * dot(A.T, dot(P, A))\n        self.F = solve(S1, S2)\n        new_P = R - dot(S2.T, self.F) + S3\n        new_d = self.beta * (d + np.trace(dot(P, dot(C, C.T))))\n        self.P, self.d = new_P, new_d",
    "docstring": "This method is for updating in the finite horizon case.  It\n        shifts the current value function\n\n        .. math::\n\n             V_t(x) = x' P_t x + d_t\n\n        and the optimal policy :math:`F_t` one step *back* in time,\n        replacing the pair :math:`P_t` and :math:`d_t` with\n        :math:`P_{t-1}` and :math:`d_{t-1}`, and :math:`F_t` with\n        :math:`F_{t-1}`"
  },
  {
    "code": "def coderelpath(coderoot, relpath):\n    from os import chdir, getcwd, path\n    cd = getcwd()\n    chdir(coderoot)\n    result = path.abspath(relpath)\n    chdir(cd)\n    return result",
    "docstring": "Returns the absolute path of the 'relpath' relative to the specified code directory."
  },
  {
    "code": "def product(self, factorset, inplace=True):\n        r\n        factor_set = self if inplace else self.copy()\n        factor_set1 = factorset.copy()\n        factor_set.add_factors(*factor_set1.factors)\n        if not inplace:\n            return factor_set",
    "docstring": "r\"\"\"\n        Return the factor sets product with the given factor sets\n\n        Suppose :math:`\\vec\\phi_1` and :math:`\\vec\\phi_2` are two factor sets then their product is a another factors\n        set :math:`\\vec\\phi_3 = \\vec\\phi_1 \\cup \\vec\\phi_2`.\n\n        Parameters\n        ----------\n        factorsets: FactorSet1, FactorSet2, ..., FactorSetn\n            FactorSets to be multiplied\n\n        inplace: A boolean (Default value True)\n            If inplace = True , then it will modify the FactorSet object, if False, it will\n            return a new FactorSet object.\n\n        Returns\n        --------\n        If inpalce = False, will return a new FactorSet object, which is product of two factors\n\n        Examples\n        --------\n        >>> from pgmpy.factors import FactorSet\n        >>> from pgmpy.factors.discrete import DiscreteFactor\n        >>> phi1 = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 2], range(12))\n        >>> phi2 = DiscreteFactor(['x3', 'x4', 'x1'], [2, 2, 2], range(8))\n        >>> factor_set1 = FactorSet(phi1, phi2)\n        >>> phi3 = DiscreteFactor(['x5', 'x6', 'x7'], [2, 2, 2], range(8))\n        >>> phi4 = DiscreteFactor(['x5', 'x7', 'x8'], [2, 2, 2], range(8))\n        >>> factor_set2 = FactorSet(phi3, phi4)\n        >>> print(factor_set2)\n        set([<DiscreteFactor representing phi(x5:2, x6:2, x7:2) at 0x7f8e32b5b050>,\n             <DiscreteFactor representing phi(x5:2, x7:2, x8:2) at 0x7f8e32b5b690>])\n        >>> factor_set2.product(factor_set1)\n        >>> print(factor_set2)\n        set([<DiscreteFactor representing phi(x1:2, x2:3, x3:2) at 0x7f8e32b4c910>,\n             <DiscreteFactor representing phi(x3:2, x4:2, x1:2) at 0x7f8e32b4cc50>,\n             <DiscreteFactor representing phi(x5:2, x6:2, x7:2) at 0x7f8e32b5b050>,\n             <DiscreteFactor representing phi(x5:2, x7:2, x8:2) at 0x7f8e32b5b690>])\n        >>> factor_set2 = FactorSet(phi3, phi4)\n        >>> factor_set3 = factor_set2.product(factor_set1, inplace=False)\n        >>> print(factor_set2)\n        set([<DiscreteFactor representing phi(x5:2, x6:2, x7:2) at 0x7f8e32b5b060>,\n             <DiscreteFactor representing phi(x5:2, x7:2, x8:2) at 0x7f8e32b5b790>])"
  },
  {
    "code": "def to_css(self):\n        if self.a == 1.0:\n            return \"rgb(%d, %d, %d)\" % (self.r, self.g, self.b)\n        else:\n            return \"rgba(%d, %d, %d, %s)\" % (self.r, self.g, self.b, self.a)",
    "docstring": "Generate the CSS representation of this RGB color.\n\n        Returns:\n            str, ``\"rgb(...)\"`` or ``\"rgba(...)\"``"
  },
  {
    "code": "def get_connection(self, name):\n        return self._api_get('/api/connections/{0}'.format(\n            urllib.parse.quote_plus(name)\n        ))",
    "docstring": "An individual connection.\n\n        :param name: The connection name\n        :type name: str"
  },
  {
    "code": "def init(self, value):\n        value = self.value_or_default(value)\n        if value is None: return None\n        if is_hashed(value):\n            return value\n        return make_password(value)",
    "docstring": "hash passwords given in the constructor"
  },
  {
    "code": "def add_particles_ascii(self, s):\n        for l in s.split(\"\\n\"):\n            r = l.split()\n            if len(r):\n                try:\n                    r = [float(x) for x in r]\n                    p = Particle(simulation=self, m=r[0], r=r[1], x=r[2], y=r[3], z=r[4], vx=r[5], vy=r[6], vz=r[7])\n                    self.add(p)\n                except:\n                    raise AttributeError(\"Each line requires 8 floats corresponding to mass, radius, position (x,y,z) and velocity (x,y,z).\")",
    "docstring": "Adds particles from an ASCII string. \n\n        Parameters\n        ----------\n        s : string\n            One particle per line. Each line should include particle's mass, radius, position and velocity."
  },
  {
    "code": "def from_json(cls, json_moc):\n        intervals = np.array([])\n        for order, pix_l in json_moc.items():\n            if len(pix_l) == 0:\n                continue\n            pix = np.array(pix_l)\n            p1 = pix\n            p2 = pix + 1\n            shift = 2 * (AbstractMOC.HPY_MAX_NORDER - int(order))\n            itv = np.vstack((p1 << shift, p2 << shift)).T\n            if intervals.size == 0:\n                intervals = itv\n            else:\n                intervals = np.vstack((intervals, itv))\n        return cls(IntervalSet(intervals))",
    "docstring": "Creates a MOC from a dictionary of HEALPix cell arrays indexed by their depth.\n\n        Parameters\n        ----------\n        json_moc : dict(str : [int]\n            A dictionary of HEALPix cell arrays indexed by their depth.\n\n        Returns\n        -------\n        moc : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC`\n            the MOC."
  },
  {
    "code": "def is_file(value, **kwargs):\n    try:\n        value = validators.file_exists(value, **kwargs)\n    except SyntaxError as error:\n        raise error\n    except Exception:\n        return False\n    return True",
    "docstring": "Indicate whether ``value`` is a file that exists on the local filesystem.\n\n    :param value: The value to evaluate.\n\n    :returns: ``True`` if ``value`` is valid, ``False`` if it is not.\n    :rtype: :class:`bool <python:bool>`\n\n    :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates\n      keyword parameters passed to the underlying validator"
  },
  {
    "code": "def requires_target(self):\n\t\tif self.has_combo and PlayReq.REQ_TARGET_FOR_COMBO in self.requirements:\n\t\t\tif self.controller.combo:\n\t\t\t\treturn True\n\t\tif PlayReq.REQ_TARGET_IF_AVAILABLE in self.requirements:\n\t\t\treturn bool(self.play_targets)\n\t\tif PlayReq.REQ_TARGET_IF_AVAILABLE_AND_DRAGON_IN_HAND in self.requirements:\n\t\t\tif self.controller.hand.filter(race=Race.DRAGON):\n\t\t\t\treturn bool(self.play_targets)\n\t\treq = self.requirements.get(PlayReq.REQ_TARGET_IF_AVAILABLE_AND_MINIMUM_FRIENDLY_MINIONS)\n\t\tif req is not None:\n\t\t\tif len(self.controller.field) >= req:\n\t\t\t\treturn bool(self.play_targets)\n\t\treq = self.requirements.get(PlayReq.REQ_TARGET_IF_AVAILABLE_AND_MINIMUM_FRIENDLY_SECRETS)\n\t\tif req is not None:\n\t\t\tif len(self.controller.secrets) >= req:\n\t\t\t\treturn bool(self.play_targets)\n\t\treturn PlayReq.REQ_TARGET_TO_PLAY in self.requirements",
    "docstring": "True if the card currently requires a target"
  },
  {
    "code": "def DEBUG_ON_RESPONSE(self, statusCode, responseHeader, data):\n        if self.DEBUG_FLAG:\n            self._frameBuffer[self._frameCount][1:4] = [statusCode, responseHeader, data]\n            responseHeader[self.DEBUG_HEADER_KEY] = self._frameCount",
    "docstring": "Update current frame with response\n        Current frame index will be attached to responseHeader"
  },
  {
    "code": "def live_migrate_move(self, userid, destination, parms):\n        rd = ('migratevm %(uid)s move --destination %(dest)s ' %\n              {'uid': userid, 'dest': destination})\n        if 'maxtotal' in parms:\n            rd += ('--maxtotal ' + str(parms['maxTotal']))\n        if 'maxquiesce' in parms:\n            rd += ('--maxquiesce ' + str(parms['maxquiesce']))\n        if 'immediate' in parms:\n            rd += \" --immediate\"\n        if 'forcearch' in parms:\n            rd += \" --forcearch\"\n        if 'forcedomain' in parms:\n            rd += \" --forcedomain\"\n        if 'forcestorage' in parms:\n            rd += \" --forcestorage\"\n        action = \"move userid '%s' to SSI '%s'\" % (userid, destination)\n        try:\n            self._request(rd)\n        except exception.SDKSMTRequestFailed as err:\n            msg = ''\n            if action is not None:\n                msg = \"Failed to %s. \" % action\n            msg += \"SMT error: %s\" % err.format_message()\n            LOG.error(msg)\n            raise exception.SDKSMTRequestFailed(err.results, msg)",
    "docstring": "moves the specified virtual machine, while it continues to run,\n         to the specified system within the SSI cluster."
  },
  {
    "code": "def get_file_descriptor(self):\n        return self._subscription.connection and self._subscription.connection._sock.fileno()",
    "docstring": "Returns the file descriptor used for passing to the select call when listening\n        on the message queue."
  },
  {
    "code": "def fetch_json_by_name(name):\n    result = fetch_meta_by_name(name)\n    if result.href:\n        result = fetch_json_by_href(result.href)\n    return result",
    "docstring": "Fetch json based on the element name\n    First gets the href based on a search by name, then makes a\n    second query to obtain the element json\n\n    :method: GET\n    :param str name: element name\n    :return: :py:class:`smc.api.web.SMCResult`"
  },
  {
    "code": "def clone_from(cls, url, to_path, progress=None, env=None, **kwargs):\n        git = Git(os.getcwd())\n        if env is not None:\n            git.update_environment(**env)\n        return cls._clone(git, url, to_path, GitCmdObjectDB, progress, **kwargs)",
    "docstring": "Create a clone from the given URL\n\n        :param url: valid git url, see http://www.kernel.org/pub/software/scm/git/docs/git-clone.html#URLS\n        :param to_path: Path to which the repository should be cloned to\n        :param progress: See 'git.remote.Remote.push'.\n        :param env: Optional dictionary containing the desired environment variables.\n        :param kwargs: see the ``clone`` method\n        :return: Repo instance pointing to the cloned directory"
  },
  {
    "code": "def abort(self, err):\n        if _debug: IOGroup._debug(\"abort %r\", err)\n        self.ioState = ABORTED\n        self.ioError = err\n        for iocb in self.ioMembers:\n            iocb.abort(err)\n        self.trigger()",
    "docstring": "Called by a client to abort all of the member transactions.\n        When the last pending member is aborted the group callback\n        function will be called."
  },
  {
    "code": "def _retrieve(self, map):\n        self._conn.request('GET', \"cache_object://%s/%s\" % (self._host, map), \n                           None, self._httpHeaders)\n        rp = self._conn.getresponse()\n        if rp.status == 200:\n            data = rp.read()\n            return data\n        else:\n            raise Exception(\"Retrieval of stats from Squid Proxy Server\"\n                            \"on host %s and port %s failed.\\n\"\n                            \"HTTP - Status: %s    Reason: %s\" \n                            % (self._host, self._port, rp.status, rp.reason))",
    "docstring": "Query Squid Proxy Server Manager Interface for stats.\n        \n        @param map: Statistics map name.\n        @return:    Dictionary of query results."
  },
  {
    "code": "def write_output_file(self,\n                          path: str,\n                          per_identity_data: 'RDD',\n                          spark_session: Optional['SparkSession'] = None) -> None:\n        _spark_session_ = get_spark_session(spark_session)\n        if not self._window_bts:\n            per_identity_data.flatMap(\n                lambda x: [json.dumps(data, cls=BlurrJSONEncoder) for data in x[1][0].items()]\n            ).saveAsTextFile(path)\n        else:\n            _spark_session_.createDataFrame(per_identity_data.flatMap(lambda x: x[1][1])).write.csv(\n                path, header=True)",
    "docstring": "Basic helper function to persist data to disk.\n\n        If window BTS was provided then the window BTS output to written in csv format, otherwise,\n        the streaming BTS output is written in JSON format to the `path` provided\n\n        :param path: Path where the output should be written.\n        :param per_identity_data: Output of the `execute()` call.\n        :param spark_session: `SparkSession` to use for execution. If None is provided then a basic\n            `SparkSession` is created.\n        :return:"
  },
  {
    "code": "def month_interval(year, month, milliseconds=False, return_string=False):\n    if milliseconds:\n        delta = timedelta(milliseconds=1)\n    else:\n        delta = timedelta(seconds=1)\n    if month == 12:\n        start = datetime(year, month, 1)\n        end = datetime(year + 1, 1, 1) - delta\n    else:\n        start = datetime(year, month, 1)\n        end = datetime(year, month + 1, 1) - delta\n    if not return_string:\n        return start, end\n    else:\n        return str(start), str(end)",
    "docstring": "Return a start datetime and end datetime of a month.\n\n    :param milliseconds: Minimum time resolution.\n    :param return_string: If you want string instead of datetime, set True\n\n    Usage Example::\n\n        >>> start, end = rolex.month_interval(2000, 2)\n        >>> start\n        datetime(2000, 2, 1, 0, 0, 0)\n\n        >>> end\n        datetime(2000, 2, 29, 23, 59, 59)"
  },
  {
    "code": "def _encode_dbref(name, value, check_keys, opts):\n    buf = bytearray(b\"\\x03\" + name + b\"\\x00\\x00\\x00\\x00\")\n    begin = len(buf) - 4\n    buf += _name_value_to_bson(b\"$ref\\x00\",\n                               value.collection, check_keys, opts)\n    buf += _name_value_to_bson(b\"$id\\x00\",\n                               value.id, check_keys, opts)\n    if value.database is not None:\n        buf += _name_value_to_bson(\n            b\"$db\\x00\", value.database, check_keys, opts)\n    for key, val in iteritems(value._DBRef__kwargs):\n        buf += _element_to_bson(key, val, check_keys, opts)\n    buf += b\"\\x00\"\n    buf[begin:begin + 4] = _PACK_INT(len(buf) - begin)\n    return bytes(buf)",
    "docstring": "Encode bson.dbref.DBRef."
  },
  {
    "code": "def normalized(vector):\n    length = numpy.sum(vector * vector, axis=-1)\n    length = numpy.sqrt(length.reshape(length.shape + (1, )))\n    return vector / length",
    "docstring": "Get unit vector for a given one.\n\n    :param vector:\n        Numpy vector as coordinates in Cartesian space, or an array of such.\n    :returns:\n        Numpy array of the same shape and structure where all vectors are\n        normalized. That is, each coordinate component is divided by its\n        vector's length."
  },
  {
    "code": "def remove_config_lock(name):\n    ret = _default_ret(name)\n    ret.update({\n        'changes': __salt__['panos.remove_config_lock'](),\n        'result': True\n    })\n    return ret",
    "docstring": "Release config lock previously held.\n\n    name: The name of the module function to execute.\n\n    SLS Example:\n\n    .. code-block:: yaml\n\n        panos/takelock:\n            panos.remove_config_lock"
  },
  {
    "code": "def OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY(self):\n        if not self._unauthenticated_session_management_key:\n            self._unauthenticated_session_management_key = ''.join(\n                random.choice(string.ascii_uppercase + string.digits) for _ in range(100))\n        return self._unauthenticated_session_management_key",
    "docstring": "OPTIONAL. Supply a fixed string to use as browser-state key for unauthenticated clients."
  },
  {
    "code": "def copy(self):\n        o = Option(\n            name=self.name,\n            default=self.default,\n            doc=self.doc,\n            from_string_converter=self.from_string_converter,\n            to_string_converter=self.to_string_converter,\n            value=self.value,\n            short_form=self.short_form,\n            exclude_from_print_conf=self.exclude_from_print_conf,\n            exclude_from_dump_conf=self.exclude_from_dump_conf,\n            is_argument=self.is_argument,\n            likely_to_be_changed=self.likely_to_be_changed,\n            not_for_definition=self.not_for_definition,\n            reference_value_from=self.reference_value_from,\n            secret=self.secret,\n            has_changed=self.has_changed,\n            foreign_data=self.foreign_data,\n        )\n        return o",
    "docstring": "return a copy"
  },
  {
    "code": "def init_not_msvc(self):\n        paths = os.environ.get('LD_LIBRARY_PATH', '').split(':')\n        for gomp in ('libgomp.so', 'libgomp.dylib'):\n            if cxx is None:\n                continue\n            cmd = [cxx, '-print-file-name=' + gomp]\n            try:\n                path = os.path.dirname(check_output(cmd).strip())\n                if path:\n                    paths.append(path)\n            except OSError:\n                pass\n        libgomp_path = find_library(\"gomp\")\n        for path in paths:\n            if libgomp_path:\n                break\n            path = path.strip()\n            if os.path.isdir(path):\n                libgomp_path = find_library(os.path.join(str(path), \"libgomp\"))\n        if not libgomp_path:\n            raise ImportError(\"I can't find a shared library for libgomp,\"\n                              \" you may need to install it or adjust the \"\n                              \"LD_LIBRARY_PATH environment variable.\")\n        else:\n            self.libomp = ctypes.CDLL(libgomp_path)\n            self.version = 45",
    "docstring": "Find OpenMP library and try to load if using ctype interface."
  },
  {
    "code": "def _logoutclient(self, useruuid, clientuuid):\n        self.log(\"Cleaning up client of logged in user.\", lvl=debug)\n        try:\n            self._users[useruuid].clients.remove(clientuuid)\n            if len(self._users[useruuid].clients) == 0:\n                self.log(\"Last client of user disconnected.\", lvl=verbose)\n                self.fireEvent(userlogout(useruuid, clientuuid))\n                del self._users[useruuid]\n            self._clients[clientuuid].useruuid = None\n        except Exception as e:\n            self.log(\"Error during client logout: \", e, type(e),\n                     clientuuid, useruuid, lvl=error,\n                     exc=True)",
    "docstring": "Log out a client and possibly associated user"
  },
  {
    "code": "def download(self, file_to_be_downloaded, perform_download=True, download_to_path=None):\n        response = self.get(\n            '/path/data/', file_to_be_downloaded, raw=False)\n        if not perform_download:\n            return response\n        if not download_to_path:\n            download_to_path = file_to_be_downloaded.split(\"/\")[-1]\n        o = open(download_to_path, 'wb')\n        return shutil.copyfileobj(response.raw, o)",
    "docstring": "file_to_be_downloaded is a file-like object that has already\n        been uploaded, you cannot download folders"
  },
  {
    "code": "async def _wait(self, entity_type, entity_id, action, predicate=None):\n        q = asyncio.Queue(loop=self._connector.loop)\n        async def callback(delta, old, new, model):\n            await q.put(delta.get_id())\n        self.add_observer(callback, entity_type, action, entity_id, predicate)\n        entity_id = await q.get()\n        return self.state._live_entity_map(entity_type).get(entity_id)",
    "docstring": "Block the calling routine until a given action has happened to the\n        given entity\n\n        :param entity_type: The entity's type.\n        :param entity_id: The entity's id.\n        :param action: the type of action (e.g., 'add', 'change', or 'remove')\n        :param predicate: optional callable that must take as an\n            argument a delta, and must return a boolean, indicating\n            whether the delta contains the specific action we're looking\n            for. For example, you might check to see whether a 'change'\n            has a 'completed' status. See the _Observer class for details."
  },
  {
    "code": "def send_status_message(self, object_id, status):\n        try:\n            body = json.dumps({\n                'id': object_id,\n                'status': status\n            })\n            self.status_queue.send_message(\n                MessageBody=body,\n                MessageGroupId='job_status',\n                MessageDeduplicationId=get_hash((object_id, status))\n            )\n            return True\n        except Exception as ex:\n            print(ex)\n            return False",
    "docstring": "Send a message to the `status_queue` to update a job's status.\n\n        Returns `True` if the message was sent, else `False`\n\n        Args:\n            object_id (`str`): ID of the job that was executed\n            status (:obj:`SchedulerStatus`): Status of the job\n\n        Returns:\n            `bool`"
  },
  {
    "code": "def plotprofMulti(self, ini, end, delta, what_specie, xlim1, xlim2,\n                      ylim1, ylim2, symbol=None):\n        plotType=self._classTest()\n        if plotType=='se':\n            for i in range(ini,end+1,delta):\n                step = int(i)\n                if symbol==None:\n                    symbol_dummy = '-'\n                    for j in range(len(what_specie)):\n                        self.plot_prof_1(step,what_specie[j],xlim1,xlim2,ylim1,ylim2,symbol_dummy)\n                else:\n                    for j in range(len(what_specie)):\n                        symbol_dummy = symbol[j]\n                        self.plot_prof_1(step,what_specie[j],xlim1,xlim2,ylim1,ylim2,symbol_dummy)\n                filename = str('%03d' % step)+'_test.png'\n                pl.savefig(filename, dpi=400)\n                print('wrote file ', filename)\n                pl.clf()\n        else:\n            print('This method is not supported for '+str(self.__class__))\n            return",
    "docstring": "create a movie with mass fractions vs mass coordinate between\n        xlim1 and xlim2, ylim1 and ylim2. Only works with instances of\n        se.\n\n        Parameters\n        ----------\n        ini : integer\n            Initial model i.e. cycle.\n        end : integer\n            Final model i.e. cycle.\n        delta : integer\n            Sparsity factor of the frames.\n        what_specie : list\n            Array with species in the plot.\n        xlim1, xlim2 : integer or float\n            Mass coordinate range.\n        ylim1, ylim2 : integer or float\n            Mass fraction coordinate range.\n        symbol : list, optional\n            Array indicating which symbol you want to use. Must be of\n            the same len of what_specie array.  The default is None."
  },
  {
    "code": "def nb_fit(data, P_init=None, R_init=None, epsilon=1e-8, max_iters=100):\n    means = data.mean(1)\n    variances = data.var(1)\n    if (means > variances).any():\n        raise ValueError(\"For NB fit, means must be less than variances\")\n    genes, cells = data.shape\n    P = 1.0 - means/variances\n    R = means*(1-P)/P\n    for i in range(genes):\n        result = minimize(nb_ll_row, [P[i], R[i]], args=(data[i,:],),\n                bounds = [(0, 1), (eps, None)])\n        params = result.x\n        P[i] = params[0]\n        R[i] = params[1]\n    return P,R",
    "docstring": "Fits the NB distribution to data using method of moments.\n\n    Args:\n        data (array): genes x cells\n        P_init (array, optional): NB success prob param - genes x 1\n        R_init (array, optional): NB stopping param - genes x 1\n\n    Returns:\n        P, R - fit to data"
  },
  {
    "code": "def all_fields(self):\n        return [field \n                for container in FieldsContainer.class_container.values()\n                for field in getattr(self, container)]",
    "docstring": "A list with all the fields contained in this object."
  },
  {
    "code": "def _multiplyThroughputs(self):\n        index = 0\n        for component in self.components:\n            if component.throughput != None:\n                break\n            index += 1\n        return BaseObservationMode._multiplyThroughputs(self, index)",
    "docstring": "Overrides base class in order to deal with opaque components."
  },
  {
    "code": "def _validate_response(self, response, message, exclude_code=None):\n        if 'code' in response and response['code'] >= 2000:\n            if exclude_code is not None and response['code'] == exclude_code:\n                return\n            raise Exception(\"{0}: {1} ({2})\".format(\n                message, response['msg'], response['code']))",
    "docstring": "validate an api server response\n\n        :param dict response: server response to check\n        :param str message: error message to raise\n        :param int exclude_code: error codes to exclude from errorhandling\n        :return:\n        \":raises Exception: on error"
  },
  {
    "code": "def get_all_suppliers(self, params=None):\n        if not params:\n            params = {}\n        return self._iterate_through_pages(\n            get_function=self.get_suppliers_per_page,\n            resource=SUPPLIERS,\n            **{'params': params}\n        )",
    "docstring": "Get all suppliers\n        This will iterate over all pages until it gets all elements.\n        So if the rate limit exceeded it will throw an Exception and you will get nothing\n\n        :param params: search params\n        :return: list"
  },
  {
    "code": "def receiver(self):\n        try:\n            return current_webhooks.receivers[self.receiver_id]\n        except KeyError:\n            raise ReceiverDoesNotExist(self.receiver_id)",
    "docstring": "Return registered receiver."
  },
  {
    "code": "def paranoidclass(cls):\n    for methname in dir(cls):\n        meth = getattr(cls, methname)\n        if U.has_fun_prop(meth, \"argtypes\"):\n            argtypes = U.get_fun_prop(meth, \"argtypes\")\n            if \"self\" in argtypes and isinstance(argtypes[\"self\"], T.Self):\n                argtypes[\"self\"] = T.Generic(cls)\n                U.set_fun_prop(meth, \"argtypes\", argtypes)\n        if U.has_fun_prop(meth, \"returntype\"):\n            if isinstance(U.get_fun_prop(meth, \"returntype\"), T.Self):\n                U.set_fun_prop(meth, \"returntype\", T.Generic(cls))\n    return cls",
    "docstring": "A class decorator to specify that class methods contain paranoid decorators.\n\n    Example usage:\n\n      | @paranoidclass\n      | class Point:\n      |     def __init__(self, x, y):\n      |         ...\n      |     @returns(Number)\n      |     def distance_from_zero():\n      |         ..."
  },
  {
    "code": "def bivrandom (x0, y0, sx, sy, cxy, size=None):\n    from numpy.random import multivariate_normal as mvn\n    p0 = np.asarray ([x0, y0])\n    cov = np.asarray ([[sx**2, cxy],\n                       [cxy, sy**2]])\n    return mvn (p0, cov, size)",
    "docstring": "Compute random values distributed according to the specified bivariate\n    distribution.\n\n    Inputs:\n\n    * x0: the center of the x distribution (i.e. its intended mean)\n    * y0: the center of the y distribution\n    * sx: standard deviation (not variance) of x var\n    * sy: standard deviation (not variance) of y var\n    * cxy: covariance (not correlation coefficient) of x and y\n    * size (optional): the number of values to compute\n\n    Returns: array of shape (size, 2); or just (2, ), if size was not\n      specified.\n\n    The bivariate parameters of the generated data are approximately\n    recoverable by calling 'databiv(retval)'."
  },
  {
    "code": "def add_key(self, ref, mode=\"shared\"):\n        if ref not in self.keys:\n            response = self.request(\"client_add_key %s -%s\" % (ref, mode))\n            if \"success\" not in response:\n                return None\n            self.keys.append(ref)\n            return ref",
    "docstring": "Add a key.\n\n        (ref)\n        Return key name or None on error"
  },
  {
    "code": "def reg_to_lex(conditions, wildcards):\n    aliases = defaultdict(set)\n    n_conds = []\n    for i, _ in enumerate(conditions):\n        n_cond = []\n        for char in conditions[i]:\n            if char in wildcards:\n                alias = '%s_%s' % (char, len(aliases[char]))\n                aliases[char].add(alias)\n                n_cond.append(make_token(alias, reg=wildcards[char]))\n            else:\n                n_cond.append(~Literal(char))\n        n_cond.append(Eos())\n        n_conds.append(reduce(operator.and_, n_cond) > make_dict)\n    return tuple(n_conds), aliases",
    "docstring": "Transform a regular expression into a LEPL object.\n\n    Replace the wildcards in the conditions by LEPL elements,\n    like xM will be replaced by Any() & 'M'.\n    In case of multiple same wildcards (like xMx), aliases\n    are created to allow the regexp to compile, like\n    Any() > 'x_0' & 'M' & Any() > 'x_1', and we chech that the matched values\n    for all aliases like x_0, x_1 are the same."
  },
  {
    "code": "def commands(cls):\n        cmds = [cmd[4:] for cmd in dir(cls) if cmd.startswith('cmd_')]\n        return cmds",
    "docstring": "Returns a list of all methods that start with ``cmd_``."
  },
  {
    "code": "def make_value(self, value):\n        value = self.unicode_escape_sequence_fix(value)\n        if value and value[0] in ['\"', \"'\"]:\n            return self.remove_quotes(value)\n        try:\n            return int(value)\n        except ValueError:\n            pass\n        try:\n            return float(value)\n        except ValueError:\n            pass\n        if value.lower() == \"true\":\n            return True\n        if value.lower() == \"false\":\n            return False\n        if value.lower() == \"none\":\n            return None\n        return value",
    "docstring": "Converts to actual value, or remains as string."
  },
  {
    "code": "def get_focus_widget(self):\n        current_widget = QApplication.focusWidget()\n        if current_widget is None:\n            return False\n        if current_widget.objectName() == \"Script_Editor_Output_plainTextEdit\" or \\\n                isinstance(current_widget, Editor):\n            return current_widget",
    "docstring": "Returns the Widget with focus.\n\n        :return: Widget with focus.\n        :rtype: QWidget"
  },
  {
    "code": "def stdchannel_redirected(stdchannel):\n    try:\n        s = io.StringIO()\n        old = getattr(sys, stdchannel)\n        setattr(sys, stdchannel, s)\n        yield s\n    finally:\n        setattr(sys, stdchannel, old)",
    "docstring": "Redirects stdout or stderr to a StringIO object. As of python 3.4, there is a\n    standard library contextmanager for this, but backwards compatibility!"
  },
  {
    "code": "def split_locale(loc):\n    def split(st, char):\n        split_st = st.split(char, 1)\n        if len(split_st) == 1:\n            split_st.append('')\n        return split_st\n    comps = {}\n    work_st, comps['charmap'] = split(loc, ' ')\n    work_st, comps['modifier'] = split(work_st, '@')\n    work_st, comps['codeset'] = split(work_st, '.')\n    comps['language'], comps['territory'] = split(work_st, '_')\n    return comps",
    "docstring": "Split a locale specifier.  The general format is\n\n    language[_territory][.codeset][@modifier] [charmap]\n\n    For example:\n\n    ca_ES.UTF-8@valencia UTF-8"
  },
  {
    "code": "def __GetElementTree(protocol, server, port, path, sslContext):\n   if protocol == \"https\":\n      kwargs = {\"context\": sslContext} if sslContext else {}\n      conn = http_client.HTTPSConnection(server, port=port, **kwargs)\n   elif protocol == \"http\":\n      conn = http_client.HTTPConnection(server, port=port)\n   else:\n      raise Exception(\"Protocol \" + protocol + \" not supported.\")\n   conn.request(\"GET\", path)\n   response = conn.getresponse()\n   if response.status == 200:\n      try:\n         tree = ElementTree.fromstring(response.read())\n         return tree\n      except ExpatError:\n         pass\n   return None",
    "docstring": "Private method that returns a root from ElementTree for a remote XML document.\n\n   @param protocol: What protocol to use for the connection (e.g. https or http).\n   @type  protocol: string\n   @param server: Which server to connect to.\n   @type  server: string\n   @param port: Port\n   @type  port: int\n   @param path: Path\n   @type  path: string\n   @param sslContext: SSL Context describing the various SSL options. It is only\n                      supported in Python 2.7.9 or higher.\n   @type  sslContext: SSL.Context"
  },
  {
    "code": "def _repr_html_(self, **kwargs):\n        from jinja2 import Template\n        from markdown import markdown as convert_markdown\n        extensions = [\n            'markdown.extensions.extra',\n            'markdown.extensions.admonition'\n        ]\n        return convert_markdown(self.markdown, extensions)",
    "docstring": "Produce HTML for Jupyter Notebook"
  },
  {
    "code": "def get_hosting_device_configuration(self, context, id):\n        admin_context = context.is_admin and context or context.elevated()\n        agents = self._dmplugin.get_cfg_agents_for_hosting_devices(\n            admin_context, [id], admin_state_up=True, schedule=True)\n        if agents:\n            cctxt = self.client.prepare(server=agents[0].host)\n            return cctxt.call(context, 'get_hosting_device_configuration',\n                              payload={'hosting_device_id': id})",
    "docstring": "Fetch configuration of hosting device with id.\n\n        The configuration agent should respond with the running config of\n        the hosting device."
  },
  {
    "code": "def _read_pug_fixed_grid(projection, distance_multiplier=1.0):\n        a = projection.semi_major_axis\n        h = projection.perspective_point_height\n        b = projection.semi_minor_axis\n        lon_0 = projection.longitude_of_projection_origin\n        sweep_axis = projection.sweep_angle_axis[0]\n        proj_dict = {'a': float(a) * distance_multiplier,\n                     'b': float(b) * distance_multiplier,\n                     'lon_0': float(lon_0),\n                     'h': float(h) * distance_multiplier,\n                     'proj': 'geos',\n                     'units': 'm',\n                     'sweep': sweep_axis}\n        return proj_dict",
    "docstring": "Read from recent PUG format, where axes are in meters"
  },
  {
    "code": "def make_module_class(name):\n    source = sys.modules[name]\n    members = vars(source)\n    is_descriptor = lambda x: not isinstance(x, type) and hasattr(x, '__get__')\n    descriptors = {k: v for (k, v) in members.items() if is_descriptor(v)}\n    members = {k: v for (k, v) in members.items() if k not in descriptors}\n    descriptors['__source'] = source\n    target = type(name, (types.ModuleType,), descriptors)(name)\n    target.__dict__.update(members)\n    sys.modules[name] = target",
    "docstring": "Takes the module referenced by name and make it a full class."
  },
  {
    "code": "def rollback(name, database=None, directory=None, verbose=None):\n    router = get_router(directory, database, verbose)\n    router.rollback(name)",
    "docstring": "Rollback a migration with given name."
  },
  {
    "code": "def new(self, boot_system_id):\n        if self._initialized:\n            raise Exception('Boot Record already initialized')\n        self.boot_system_identifier = boot_system_id.ljust(32, b'\\x00')\n        self.boot_identifier = b'\\x00' * 32\n        self.boot_system_use = b'\\x00' * 197\n        self._initialized = True",
    "docstring": "A method to create a new Boot Record.\n\n        Parameters:\n         boot_system_id - The system identifier to associate with this Boot\n                          Record.\n        Returns:\n         Nothing."
  },
  {
    "code": "def upload_sequence_fileobj(file_obj, file_name, fields, retry_fields, session, samples_resource):\n    try:\n        _direct_upload(file_obj, file_name, fields, session, samples_resource)\n        sample_id = fields[\"sample_id\"]\n    except RetryableUploadException:\n        logging.error(\"{}: Connectivity issue, trying direct upload...\".format(file_name))\n        file_obj.seek(0)\n        try:\n            retry_fields = samples_resource.init_multipart_upload(retry_fields)\n        except requests.exceptions.HTTPError as e:\n            raise_api_error(e.response, state=\"init\")\n        except requests.exceptions.ConnectionError:\n            raise_connectivity_error(file_name)\n        s3_upload = _s3_intermediate_upload(\n            file_obj,\n            file_name,\n            retry_fields,\n            session,\n            samples_resource._client._root_url + retry_fields[\"callback_url\"],\n        )\n        sample_id = s3_upload.get(\"sample_id\", \"<UUID not yet assigned>\")\n    logging.info(\"{}: finished as sample {}\".format(file_name, sample_id))\n    return sample_id",
    "docstring": "Uploads a single file-like object to the One Codex server via either fastx-proxy or directly\n    to S3.\n\n    Parameters\n    ----------\n    file_obj : `FASTXInterleave`, `FilePassthru`, or a file-like object\n        A wrapper around a pair of fastx files (`FASTXInterleave`) or a single fastx file. In the\n        case of paired files, they will be interleaved and uploaded uncompressed. In the case of a\n        single file, it will simply be passed through (`FilePassthru`) to One Codex, compressed\n        or otherwise. If a file-like object is given, its mime-type will be sent as 'text/plain'.\n    file_name : `string`\n        The file_name you wish to associate this fastx file with at One Codex.\n    fields : `dict`\n        Additional data fields to include as JSON in the POST. Must include 'sample_id' and\n        'upload_url' at a minimum.\n    retry_fields : `dict`\n        Metadata sent to `init_multipart_upload` in the case that the upload via fastx-proxy fails.\n    session : `requests.Session`\n        Connection to One Codex API.\n    samples_resource : `onecodex.models.Samples`\n        Wrapped potion-client object exposing `init_upload` and `confirm_upload` routes to mainline.\n\n    Raises\n    ------\n    UploadException\n        In the case of a fatal exception during an upload.\n\n    Returns\n    -------\n    `string` containing sample ID of newly uploaded file."
  },
  {
    "code": "def is_empty(self):\n        while self.pq:\n            if self.pq[0][1] != self.INVALID:\n                return False\n            else:\n                _, _, element = heapq.heappop(self.pq)\n                if element in self.element_finder:\n                    del self.element_finder[element]\n        return True",
    "docstring": "Determines if the priority queue has any elements.\n        Performs removal of any elements that were \"marked-as-invalid\".\n\n        :returns: true iff the priority queue has no elements."
  },
  {
    "code": "def help_version(self):\n        if (len(self.args) == 1 and self.args[0] in [\"-h\", \"--help\"] and\n                self.args[1:] == []):\n            options()\n        elif (len(self.args) == 1 and self.args[0] in [\"-v\", \"--version\"] and\n                self.args[1:] == []):\n            prog_version()\n        else:\n            usage(\"\")",
    "docstring": "Help and version info"
  },
  {
    "code": "def todate(val):\n    if not val:\n        raise ValueError(\"Value not provided\")\n    if isinstance(val, datetime):\n        return val.date()\n    elif isinstance(val, date):\n        return val\n    else:\n        try:\n            ival = int(val)\n            sval = str(ival)\n            if len(sval) == 8:\n                return yyyymmdd2date(val)\n            elif len(sval) == 5:\n                return juldate2date(val)\n            else:\n                raise ValueError\n        except Exception:\n            try:\n                return date_from_string(val).date()\n            except Exception:\n                raise ValueError(\"Could not convert %s to date\" % val)",
    "docstring": "Convert val to a datetime.date instance by trying several\n    conversion algorithm.\n    If it fails it raise a ValueError exception."
  },
  {
    "code": "def log(self, *lines):\n        if getattr(self, \"debug\", False):\n            print(dt.datetime.now().time(), end=' ')\n            for line in lines:\n                print(line, end=' ')\n            print()",
    "docstring": "will print out the lines in console if debug is enabled for the\n           specific sprite"
  },
  {
    "code": "def search_get_class_names(cls):\n        if hasattr(cls, '_class_key'):\n            class_names = []\n            for n in cls._class_key():\n                class_names.append(n)\n            return class_names\n        else:\n            return [cls.__name__]",
    "docstring": "Returns class names for use in document indexing."
  },
  {
    "code": "def check_platform_variables(self, ds):\n        platform_names = getattr(ds, 'platform', '').split(' ')\n        val = all(platform_name in ds.variables for platform_name in platform_names)\n        msgs = []\n        if not val:\n            msgs = [('The value of \"platform\" global attribute should be set to another variable '\n                     'which contains the details of the platform. If multiple platforms are '\n                     'involved, a variable should be defined for each platform and referenced '\n                     'from the geophysical variable in a space separated string.')]\n        return [Result(BaseCheck.HIGH, val, 'platform variables', msgs)]",
    "docstring": "The value of platform attribute should be set to another variable which\n        contains the details of the platform. There can be multiple platforms\n        involved depending on if all the instances of the featureType in the\n        collection share the same platform or not. If multiple platforms are\n        involved, a variable should be defined for each platform and referenced\n        from the geophysical variable in a space separated string.\n\n        :param netCDF4.Dataset ds: An open netCDF dataset"
  },
  {
    "code": "def _check_bios_resource(self, properties=[]):\n        system = self._get_host_details()\n        if ('links' in system['Oem']['Hp'] and\n                'BIOS' in system['Oem']['Hp']['links']):\n            bios_uri = system['Oem']['Hp']['links']['BIOS']['href']\n            status, headers, bios_settings = self._rest_get(bios_uri)\n            if status >= 300:\n                msg = self._get_extended_error(bios_settings)\n                raise exception.IloError(msg)\n            for property in properties:\n                if property not in bios_settings:\n                    msg = ('BIOS Property \"' + property + '\" is not'\n                           ' supported on this system.')\n                    raise exception.IloCommandNotSupportedError(msg)\n            return headers, bios_uri, bios_settings\n        else:\n            msg = ('\"links/BIOS\" section in ComputerSystem/Oem/Hp'\n                   ' does not exist')\n            raise exception.IloCommandNotSupportedError(msg)",
    "docstring": "Check if the bios resource exists."
  },
  {
    "code": "def _add_arg_datasets(datasets, args):\n    for dataset in args:\n        if not isinstance(dataset, (tuple, GentyArgs)):\n            dataset = (dataset,)\n        if isinstance(dataset, GentyArgs):\n            dataset_strings = dataset\n        else:\n            dataset_strings = [format_arg(data) for data in dataset]\n        test_method_suffix = \", \".join(dataset_strings)\n        datasets[test_method_suffix] = dataset",
    "docstring": "Add data sets of the given args.\n\n    :param datasets:\n        The dict where to accumulate data sets.\n    :type datasets:\n        `dict`\n    :param args:\n        Tuple of unnamed data sets.\n    :type args:\n        `tuple` of varies"
  },
  {
    "code": "def validate_config_has_one_of(config, one_of_keys):\n  intersection = set(config).intersection(one_of_keys)\n  if len(intersection) > 1:\n    raise Exception('Only one of the values in \"%s\" is needed' % ', '.join(intersection))\n  if len(intersection) == 0:\n    raise Exception('One of the values in \"%s\" is needed' % ', '.join(one_of_keys))",
    "docstring": "Validate a config dictionary to make sure it has one and only one\n      key in one_of_keys.\n\n  Args:\n    config: the config to validate.\n    one_of_keys: the list of possible keys that config can have one and only one.\n\n  Raises:\n    Exception if the config does not have any of them, or multiple of them."
  },
  {
    "code": "def Proxy(f):\n  def Wrapped(self, *args):\n    return getattr(self, f)(*args)\n  return Wrapped",
    "docstring": "A helper to create a proxy method in a class."
  },
  {
    "code": "def _combine(self, other, conn='and'):\n        f = F()\n        self_filters = copy.deepcopy(self.filters)\n        other_filters = copy.deepcopy(other.filters)\n        if not self.filters:\n            f.filters = other_filters\n        elif not other.filters:\n            f.filters = self_filters\n        elif conn in self.filters[0]:\n            f.filters = self_filters\n            f.filters[0][conn].extend(other_filters)\n        elif conn in other.filters[0]:\n            f.filters = other_filters\n            f.filters[0][conn].extend(self_filters)\n        else:\n            f.filters = [{conn: self_filters + other_filters}]\n        return f",
    "docstring": "OR and AND will create a new F, with the filters from both F\n        objects combined with the connector `conn`."
  },
  {
    "code": "def clean_weight_files(cls):\n        deleted = []\n        for f in cls._files:\n            try:\n                os.remove(f)\n                deleted.append(f)\n            except FileNotFoundError:\n                pass\n        print('Deleted %d weight files' % len(deleted))\n        cls._files = []",
    "docstring": "Cleans existing weight files."
  },
  {
    "code": "def _sanitise(self):\n        for k in self.__dict__:\n            if isinstance(self.__dict__[k], np.float32):\n                self.__dict__[k] = np.float64(self.__dict__[k])",
    "docstring": "Convert attributes of type npumpy.float32 to numpy.float64 so that they will print properly."
  },
  {
    "code": "def format(tokens, formatter, outfile=None):\n    try:\n        if not outfile:\n            realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO()\n            formatter.format(tokens, realoutfile)\n            return realoutfile.getvalue()\n        else:\n            formatter.format(tokens, outfile)\n    except TypeError as err:\n        if (isinstance(err.args[0], str) and\n            ('unbound method format' in err.args[0] or\n             'missing 1 required positional argument' in err.args[0])):\n            raise TypeError('format() argument must be a formatter instance, '\n                            'not a class')\n        raise",
    "docstring": "Format a tokenlist ``tokens`` with the formatter ``formatter``.\n\n    If ``outfile`` is given and a valid file object (an object\n    with a ``write`` method), the result will be written to it, otherwise\n    it is returned as a string."
  },
  {
    "code": "def watch_project(self, path):\n    try:\n      return self.client.query('watch-project', os.path.realpath(path))\n    finally:\n      self._attempt_set_timeout(self._timeout)",
    "docstring": "Issues the watch-project command to watchman to begin watching the buildroot.\n\n    :param string path: the path to the watchman project root/pants build root."
  },
  {
    "code": "def _set_fields(self, json_dict):\n        for key, value in json_dict.items():\n            if not key.startswith(\"_\"):\n                setattr(self, key, value)",
    "docstring": "Set this object's attributes specified in json_dict"
  },
  {
    "code": "def header_expand(headers):\n    collector = []\n    if isinstance(headers, dict):\n        headers = headers.items()\n    elif isinstance(headers, basestring):\n        return headers\n    for i, (value, params) in enumerate(headers):\n        _params = []\n        for (p_k, p_v) in params.items():\n            _params.append('%s=%s' % (p_k, p_v))\n        collector.append(value)\n        collector.append('; ')\n        if len(params):\n            collector.append('; '.join(_params))\n            if not len(headers) == i+1:\n                collector.append(', ')\n    if collector[-1] in (', ', '; '):\n        del collector[-1]\n    return ''.join(collector)",
    "docstring": "Returns an HTTP Header value string from a dictionary.\n\n    Example expansion::\n\n        {'text/x-dvi': {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}, 'text/x-c': {}}\n        # Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c\n\n        (('text/x-dvi', {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}), ('text/x-c', {}))\n        # Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c"
  },
  {
    "code": "def is_time_variable(varname, var):\n    satisfied = varname.lower() == 'time'\n    satisfied |= getattr(var, 'standard_name', '') == 'time'\n    satisfied |= getattr(var, 'axis', '') == 'T'\n    satisfied |= units_convertible('seconds since 1900-01-01', getattr(var, 'units', ''))\n    return satisfied",
    "docstring": "Identifies if a variable is represents time"
  },
  {
    "code": "def lookup(self, profile, setting):\n        for path in profiles():\n            cfg = SafeConfigParser()\n            cfg.read(path)\n            if profile not in cfg.sections():\n                continue\n            if not cfg.has_option(profile, setting):\n                continue\n            return cfg.get(profile, setting)",
    "docstring": "Check koji.conf.d files for this profile's setting.\n\n        :param setting: ``str`` like \"server\" (for kojihub) or \"weburl\"\n        :returns: ``str``, value for this setting"
  },
  {
    "code": "def patch(self, spin, header, *args):\n        spawn(spin, 'DCC %s' % args[0], header, *args[1:])",
    "docstring": "It spawns DCC TYPE as event."
  },
  {
    "code": "def _GetGdbThreadMapping(self, position):\n    if len(gdb.selected_inferior().threads()) == 1:\n      return {position[1]: 1}\n    thread_line_regexp = r'\\s*\\**\\s*([0-9]+)\\s+[a-zA-Z]+\\s+([x0-9a-fA-F]+)\\s.*'\n    output = gdb.execute('info threads', to_string=True)\n    matches = [re.match(thread_line_regexp, line) for line\n               in output.split('\\n')[1:]]\n    return {int(match.group(2), 16): int(match.group(1))\n            for match in matches if match}",
    "docstring": "Gets a mapping from python tid to gdb thread num.\n\n    There's no way to get the thread ident from a gdb thread.  We only get the\n    \"ID of the thread, as assigned by GDB\", which is completely useless for\n    everything except talking to gdb.  So in order to translate between these\n    two, we have to execute 'info threads' and parse its output. Note that this\n    may only work on linux, and only when python was compiled to use pthreads.\n    It may work elsewhere, but we won't guarantee it.\n\n    Args:\n      position: array of pid, tid, framedepth specifying the requested position.\n    Returns:\n      A dictionary of the form {python_tid: gdb_threadnum}."
  },
  {
    "code": "def open(self, options):\n        if self.opened:\n            return\n        self.opened = True\n        log.debug('%s, including location=\"%s\"', self.id, self.location)\n        result = self.download(options)\n        log.debug('included:\\n%s', result)\n        return result",
    "docstring": "Open and include the refrenced schema.\n        @param options: An options dictionary.\n        @type options: L{options.Options}\n        @return: The referenced schema.\n        @rtype: L{Schema}"
  },
  {
    "code": "def parse_negation_operation(operation: str) -> Tuple[bool, str]:\n    _operation = operation.strip()\n    if not _operation:\n        raise QueryParserException('Operation is not valid: {}'.format(operation))\n    negation = False\n    if _operation[0] == '~':\n        negation = True\n        _operation = _operation[1:]\n    return negation, _operation.strip()",
    "docstring": "Parse the negation modifier in an operation."
  },
  {
    "code": "def make_job(job_name, **kwargs):\n    def wraps(func):\n        kwargs['process'] = func\n        job = type(job_name, (Job,), kwargs)\n        globals()[job_name] = job\n        return job\n    return wraps",
    "docstring": "Decorator to create a Job from a function.\n    Give a job name and add extra fields to the job.\n\n        @make_job(\"ExecuteDecJob\",\n                  command=mongoengine.StringField(required=True),\n                  output=mongoengine.StringField(default=None))\n        def execute(job: Job):\n            job.log_info('ExecuteJob %s - Executing command...' % job.uuid)\n            result = subprocess.run(job.command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n            job.output = result.stdout.decode('utf-8') + \" \" + result.stderr.decode('utf-8')"
  },
  {
    "code": "def _property_set(self, msg):\n        prop = self._sent_property.get('prop')\n        if prop and hasattr(self, prop):\n            setattr(self, prop, self._sent_property.get('val'))\n        self._sent_property = {}",
    "docstring": "Set command received and acknowledged."
  },
  {
    "code": "def label_clusters(image, min_cluster_size=50, min_thresh=1e-6, max_thresh=1, fully_connected=False):\n    dim = image.dimension\n    clust = threshold_image(image, min_thresh, max_thresh)\n    temp = int(fully_connected)\n    args = [dim, clust, clust, min_cluster_size, temp]\n    processed_args = _int_antsProcessArguments(args)\n    libfn = utils.get_lib_fn('LabelClustersUniquely')\n    libfn(processed_args)\n    return clust",
    "docstring": "This will give a unique ID to each connected \n    component 1 through N of size > min_cluster_size\n\n    ANTsR function: `labelClusters`\n\n    Arguments\n    ---------\n    image : ANTsImage \n        input image e.g. a statistical map\n    \n    min_cluster_size : integer  \n        throw away clusters smaller than this value\n    \n    min_thresh : scalar\n        threshold to a statistical map\n    \n    max_thresh : scalar\n        threshold to a statistical map\n    \n    fully_connected : boolean\n        boolean sets neighborhood connectivity pattern\n    \n    Returns\n    -------\n    ANTsImage\n\n    Example\n    -------\n    >>> import ants\n    >>> image = ants.image_read( ants.get_ants_data('r16') )\n    >>> timageFully = ants.label_clusters( image, 10, 128, 150, True )\n    >>> timageFace = ants.label_clusters( image, 10, 128, 150, False )"
  },
  {
    "code": "def split_by_fname_file(self, fname:PathOrStr, path:PathOrStr=None)->'ItemLists':\n        \"Split the data by using the names in `fname` for the validation set. `path` will override `self.path`.\"\n        path = Path(ifnone(path, self.path))\n        valid_names = loadtxt_str(path/fname)\n        return self.split_by_files(valid_names)",
    "docstring": "Split the data by using the names in `fname` for the validation set. `path` will override `self.path`."
  },
  {
    "code": "def update_status(self, status):\n        assert (status in (HightonConstants.WON, HightonConstants.PENDING, HightonConstants.LOST))\n        from highton.models import Status\n        status_obj = Status(name=status)\n        return self._put_request(\n            data=status_obj.element_to_string(status_obj.encode()),\n            endpoint=self.ENDPOINT + '/' + str(self.id) + '/status',\n        )",
    "docstring": "Updates the status of the deal\n\n        :param status: status have to be ('won', 'pending', 'lost')\n        :return: successfull response or raise Exception\n        :rtype:"
  },
  {
    "code": "def process_resource(self, req, resp, resource, uri_kwargs=None):\n        if 'user' in req.context:\n            return\n        identifier = self.identify(req, resp, resource, uri_kwargs)\n        user = self.try_storage(identifier, req, resp, resource, uri_kwargs)\n        if user is not None:\n            req.context['user'] = user\n        elif self.challenge is not None:\n            req.context.setdefault(\n                'challenges', list()\n            ).append(self.challenge)",
    "docstring": "Process resource after routing to it.\n\n        This is basic falcon middleware handler.\n\n        Args:\n            req (falcon.Request): request object\n            resp (falcon.Response): response object\n            resource (object): resource object matched by falcon router\n            uri_kwargs (dict): additional keyword argument from uri template.\n                For ``falcon<1.0.0`` this is always ``None``"
  },
  {
    "code": "def doit(self, classes=None, recursive=True, **kwargs):\n        return super().doit(classes, recursive, **kwargs)",
    "docstring": "Write out commutator\n\n        Write out the commutator according to its definition\n        $[\\Op{A}, \\Op{B}] = \\Op{A}\\Op{B} - \\Op{A}\\Op{B}$.\n\n        See :meth:`.Expression.doit`."
  },
  {
    "code": "def _my_pdf_formatter(data, format, ordered_alphabets) :\n    eps = _my_eps_formatter(data, format, ordered_alphabets).decode()\n    gs = weblogolib.GhostscriptAPI()    \n    return gs.convert('pdf', eps, format.logo_width, format.logo_height)",
    "docstring": "Generate a logo in PDF format.\n    \n    Modified from weblogo version 3.4 source code."
  },
  {
    "code": "def pop(self, name, default=SENTINEL):\n\t\tif default is SENTINEL:\n\t\t\treturn self.__data__.pop(name)\n\t\treturn self.__data__.pop(name, default)",
    "docstring": "Retrieve and remove a value from the backing store, optionally with a default."
  },
  {
    "code": "def spawn_isolated_child(econtext):\n    mitogen.parent.upgrade_router(econtext)\n    if FORK_SUPPORTED:\n        context = econtext.router.fork()\n    else:\n        context = econtext.router.local()\n    LOG.debug('create_fork_child() -> %r', context)\n    return context",
    "docstring": "For helper functions executed in the fork parent context, arrange for\n    the context's router to be upgraded as necessary and for a new child to be\n    prepared.\n\n    The actual fork occurs from the 'virginal fork parent', which does not have\n    any Ansible modules loaded prior to fork, to avoid conflicts resulting from\n    custom module_utils paths."
  },
  {
    "code": "def tic(self):\n        if self.step % self.interval == 0:\n            for exe in self.exes:\n                for array in exe.arg_arrays:\n                    array.wait_to_read()\n                for array in exe.aux_arrays:\n                    array.wait_to_read()\n            self.queue = []\n            self.activated = True\n        self.step += 1",
    "docstring": "Start collecting stats for current batch.\n        Call before calling forward."
  },
  {
    "code": "def _stripe_object_field_to_foreign_key(\n\t\tcls, field, manipulated_data, current_ids=None, pending_relations=None\n\t):\n\t\tfield_data = None\n\t\tfield_name = field.name\n\t\traw_field_data = manipulated_data.get(field_name)\n\t\trefetch = False\n\t\tskip = False\n\t\tif issubclass(field.related_model, StripeModel):\n\t\t\tid_ = cls._id_from_data(raw_field_data)\n\t\t\tif not raw_field_data:\n\t\t\t\tskip = True\n\t\t\telif id_ == raw_field_data:\n\t\t\t\trefetch = True\n\t\t\telse:\n\t\t\t\tpass\n\t\t\tif id_ in current_ids:\n\t\t\t\tif pending_relations is not None:\n\t\t\t\t\tobject_id = manipulated_data[\"id\"]\n\t\t\t\t\tpending_relations.append((object_id, field, id_))\n\t\t\t\tskip = True\n\t\t\tif not skip:\n\t\t\t\tfield_data, _ = field.related_model._get_or_create_from_stripe_object(\n\t\t\t\t\tmanipulated_data,\n\t\t\t\t\tfield_name,\n\t\t\t\t\trefetch=refetch,\n\t\t\t\t\tcurrent_ids=current_ids,\n\t\t\t\t\tpending_relations=pending_relations,\n\t\t\t\t)\n\t\telse:\n\t\t\tskip = True\n\t\treturn field_data, skip",
    "docstring": "This converts a stripe API field to the dj stripe object it references,\n\t\tso that foreign keys can be connected up automatically.\n\n\t\t:param field:\n\t\t:type field: models.ForeignKey\n\t\t:param manipulated_data:\n\t\t:type manipulated_data: dict\n\t\t:param current_ids: stripe ids of objects that are currently being processed\n\t\t:type current_ids: set\n\t\t:param pending_relations: list of tuples of relations to be attached post-save\n\t\t:type pending_relations: list\n\t\t:return:"
  },
  {
    "code": "def pandas_dtype(dtype):\n    if isinstance(dtype, np.ndarray):\n        return dtype.dtype\n    elif isinstance(dtype, (np.dtype, PandasExtensionDtype, ExtensionDtype)):\n        return dtype\n    result = registry.find(dtype)\n    if result is not None:\n        return result\n    try:\n        npdtype = np.dtype(dtype)\n    except Exception:\n        if not isinstance(dtype, str):\n            raise TypeError(\"data type not understood\")\n        raise TypeError(\"data type '{}' not understood\".format(\n            dtype))\n    if is_hashable(dtype) and dtype in [object, np.object_, 'object', 'O']:\n        return npdtype\n    elif npdtype.kind == 'O':\n        raise TypeError(\"dtype '{}' not understood\".format(dtype))\n    return npdtype",
    "docstring": "Convert input into a pandas only dtype object or a numpy dtype object.\n\n    Parameters\n    ----------\n    dtype : object to be converted\n\n    Returns\n    -------\n    np.dtype or a pandas dtype\n\n    Raises\n    ------\n    TypeError if not a dtype"
  },
  {
    "code": "def echo_via_pager(*args, **kwargs):\n    try:\n        restore = 'LESS' not in os.environ\n        os.environ.setdefault('LESS', '-iXFR')\n        click.echo_via_pager(*args, **kwargs)\n    finally:\n        if restore:\n            os.environ.pop('LESS', None)",
    "docstring": "Display pager only if it does not fit in one terminal screen.\n\n    NOTE: The feature is available only on ``less``-based pager."
  },
  {
    "code": "def _find_feed_language(self):\n        self.feed_language = (\n            read_first_available_value(\n                os.path.join(self.src_dir, 'feed_info.txt'), 'feed_lang') or\n            read_first_available_value(\n                os.path.join(self.src_dir, 'agency.txt'), 'agency_lang'))\n        if not self.feed_language:\n            raise Exception(\n                'Cannot find feed language in feed_info.txt and agency.txt')\n        print('\\tfeed language: %s' % self.feed_language)",
    "docstring": "Find feed language based specified feed_info.txt or agency.txt."
  },
  {
    "code": "def _merge_csv_section(sections, pc, csvs):\n    logger_csvs.info(\"enter merge_csv_section\")\n    try:\n        for _name, _section in sections.items():\n            if \"measurementTable\" in _section:\n                sections[_name][\"measurementTable\"] = _merge_csv_table(_section[\"measurementTable\"], pc, csvs)\n            if \"model\" in _section:\n                sections[_name][\"model\"] = _merge_csv_model(_section[\"model\"], pc, csvs)\n    except Exception as e:\n        print(\"Error: There was an error merging CSV data into the metadata \")\n        logger_csvs.error(\"merge_csv_section: {}\".format(e))\n    logger_csvs.info(\"exit merge_csv_section\")\n    return sections",
    "docstring": "Add csv data to all paleo data tables\n\n    :param dict sections: Metadata\n    :return dict sections: Metadata"
  },
  {
    "code": "def stop_loop(self):\n        hub.kill(self._querier_thread)\n        self._querier_thread = None\n        self._datapath = None\n        self.logger.info(\"stopped a querier.\")",
    "docstring": "stop QUERY thread."
  },
  {
    "code": "def make(cls, **kwargs):\n    cls_attrs = {f.name: f for f in attr.fields(cls)}\n    unknown = {k: v for k, v in kwargs.items() if k not in cls_attrs}\n    if len(unknown) > 0:\n        _LOGGER.warning(\n            \"Got unknowns for %s: %s - please create an issue!\", cls.__name__, unknown\n        )\n    missing = [k for k in cls_attrs if k not in kwargs]\n    data = {k: v for k, v in kwargs.items() if k in cls_attrs}\n    for m in missing:\n        default = cls_attrs[m].default\n        if isinstance(default, attr.Factory):\n            if not default.takes_self:\n                data[m] = default.factory()\n            else:\n                raise NotImplementedError\n        else:\n            _LOGGER.debug(\"Missing key %s with no default for %s\", m, cls.__name__)\n            data[m] = None\n    inst = cls(**data)\n    setattr(inst, \"raw\", kwargs)\n    return inst",
    "docstring": "Create a container.\n\n    Reports extra keys as well as missing ones.\n    Thanks to habnabit for the idea!"
  },
  {
    "code": "def overlaps(self, other):\n        if self > other:\n            smaller, larger = other, self\n        else:\n            smaller, larger = self, other\n        if larger.empty():\n            return False\n        if smaller._upper_value == larger._lower_value:\n            return smaller._upper == smaller.CLOSED and larger._lower == smaller.CLOSED\n        return larger._lower_value < smaller._upper_value",
    "docstring": "If self and other have any overlapping values returns True, otherwise returns False"
  },
  {
    "code": "def resolveSharedConnections(root: LNode):\n    for ch in root.children:\n        resolveSharedConnections(ch)\n    for ch in root.children:\n        for p in ch.iterPorts():\n            portTryReduce(root, p)",
    "docstring": "Walk all ports on all nodes and group subinterface connections\n    to only parent interface connection if it is possible"
  },
  {
    "code": "def _set_body(self, body):\n        assert isinstance(body, CodeStatement)\n        if isinstance(body, CodeBlock):\n            self.body = body\n        else:\n            self.body._add(body)",
    "docstring": "Set the main body for this control flow structure."
  },
  {
    "code": "def show(dataset_uri, overlay_name):\n    dataset = dtoolcore.DataSet.from_uri(dataset_uri)\n    try:\n        overlay = dataset.get_overlay(overlay_name)\n    except:\n        click.secho(\n            \"No such overlay: {}\".format(overlay_name),\n            fg=\"red\",\n            err=True\n        )\n        sys.exit(11)\n    formatted_json = json.dumps(overlay, indent=2)\n    colorful_json = pygments.highlight(\n        formatted_json,\n        pygments.lexers.JsonLexer(),\n        pygments.formatters.TerminalFormatter())\n    click.secho(colorful_json, nl=False)",
    "docstring": "Show the content of a specific overlay."
  },
  {
    "code": "def query(self, transport, protocol, *data):\n        if not self._query:\n            raise AttributeError('Command is not queryable')\n        if self.protocol:\n            protocol = self.protocol\n        if self._query.data_type:\n            data = _dump(self._query.data_type, data)\n        else:\n            data = ()\n        if isinstance(transport, SimulatedTransport):\n            response = self.simulate_query(data)\n        else:\n            response = protocol.query(transport, self._query.header, *data)\n        response = _load(self._query.response_type, response)\n        return response[0] if len(response) == 1 else response",
    "docstring": "Generates and sends a query message unit.\n\n        :param transport: An object implementing the `.Transport` interface.\n            It is used by the protocol to send the message and receive the\n            response.\n        :param protocol: An object implementing the `.Protocol` interface.\n        :param data: The program data.\n\n        :raises AttributeError: if the command is not queryable."
  },
  {
    "code": "def _find_stages(self):\n        stages = []\n        end = last_user_found = None\n        for part in reversed(self.dfp.structure):\n            if end is None:\n                end = part\n            if part['instruction'] == 'USER' and not last_user_found:\n                last_user_found = part['content']\n            if part['instruction'] == 'FROM':\n                stages.insert(0, {'from_structure': part,\n                                  'end_structure': end,\n                                  'stage_user': last_user_found})\n                end = last_user_found = None\n        return stages",
    "docstring": "Find limits of each Dockerfile stage"
  },
  {
    "code": "def giant_text_sqltype(dialect: Dialect) -> str:\n    if dialect.name == SqlaDialectName.SQLSERVER:\n        return 'NVARCHAR(MAX)'\n    elif dialect.name == SqlaDialectName.MYSQL:\n        return 'LONGTEXT'\n    else:\n        raise ValueError(\"Unknown dialect: {}\".format(dialect.name))",
    "docstring": "Returns the SQL column type used to make very large text columns for a\n    given dialect.\n\n    Args:\n        dialect: a SQLAlchemy :class:`Dialect`\n    Returns:\n        the SQL data type of \"giant text\", typically 'LONGTEXT' for MySQL\n        and 'NVARCHAR(MAX)' for SQL Server."
  },
  {
    "code": "def write_rst(self,\n                  prefix: str = \"\",\n                  suffix: str = \"\",\n                  heading_underline_char: str = \"=\",\n                  method: AutodocMethod = None,\n                  overwrite: bool = False,\n                  mock: bool = False) -> None:\n        content = self.rst_content(\n            prefix=prefix,\n            suffix=suffix,\n            heading_underline_char=heading_underline_char,\n            method=method\n        )\n        write_if_allowed(self.target_rst_filename, content,\n                         overwrite=overwrite, mock=mock)",
    "docstring": "Writes the RST file to our destination RST filename, making any\n        necessary directories.\n\n        Args:\n            prefix: as for :func:`rst_content`\n            suffix: as for :func:`rst_content`\n            heading_underline_char: as for :func:`rst_content`\n            method: as for :func:`rst_content`\n            overwrite: overwrite the file if it exists already?\n            mock: pretend to write, but don't"
  },
  {
    "code": "def callback_result(self):\n        if self._state in [PENDING, RUNNING]:\n            self.x\n        if self._user_callbacks:\n            return self._callback_result\n        else:\n            return self.x",
    "docstring": "Block the main thead until future finish, return the future.callback_result."
  },
  {
    "code": "def validate_no_duplicate_paths(self, resources):\n        paths = set()\n        for item in resources:\n            file_name = item.get('path')\n            if file_name in paths:\n                raise ValueError(\n                    '%s path was specified more than once in the metadata' %\n                    file_name)\n            paths.add(file_name)",
    "docstring": "ensure that the user has not provided duplicate paths in\n            a list of resources.\n\n            Parameters\n            ==========\n            resources: one or more resources to validate not duplicated"
  },
  {
    "code": "def getRoom(self, _id):\n        if SockJSRoomHandler._room.has_key(self._gcls() + _id):\n            return SockJSRoomHandler._room[self._gcls() + _id]\n        return None",
    "docstring": "Retrieve a room from it's id"
  },
  {
    "code": "def transpose(self):\n        graph = self.graph\n        transposed = DAG()\n        for node, edges in graph.items():\n            transposed.add_node(node)\n        for node, edges in graph.items():\n            for edge in edges:\n                transposed.add_edge(edge, node)\n        return transposed",
    "docstring": "Builds a new graph with the edges reversed.\n\n        Returns:\n            :class:`stacker.dag.DAG`: The transposed graph."
  },
  {
    "code": "def cv(params, dtrain, num_boost_round=10, nfold=3, metrics=(),\n       obj=None, feval=None, fpreproc=None, as_pandas=True,\n       show_progress=None, show_stdv=True, seed=0):\n    results = []\n    cvfolds = mknfold(dtrain, nfold, params, seed, metrics, fpreproc)\n    for i in range(num_boost_round):\n        for fold in cvfolds:\n            fold.update(i, obj)\n        res = aggcv([f.eval(i, feval) for f in cvfolds],\n                    show_stdv=show_stdv, show_progress=show_progress,\n                    as_pandas=as_pandas)\n        results.append(res)\n    if as_pandas:\n        try:\n            import pandas as pd\n            results = pd.DataFrame(results)\n        except ImportError:\n            results = np.array(results)\n    else:\n        results = np.array(results)\n    return results",
    "docstring": "Cross-validation with given paramaters.\n\n    Parameters\n    ----------\n    params : dict\n        Booster params.\n    dtrain : DMatrix\n        Data to be trained.\n    num_boost_round : int\n        Number of boosting iterations.\n    nfold : int\n        Number of folds in CV.\n    metrics : list of strings\n        Evaluation metrics to be watched in CV.\n    obj : function\n        Custom objective function.\n    feval : function\n        Custom evaluation function.\n    fpreproc : function\n        Preprocessing function that takes (dtrain, dtest, param) and returns\n        transformed versions of those.\n    as_pandas : bool, default True\n        Return pd.DataFrame when pandas is installed.\n        If False or pandas is not installed, return np.ndarray\n    show_progress : bool or None, default None\n        Whether to display the progress. If None, progress will be displayed\n        when np.ndarray is returned.\n    show_stdv : bool, default True\n        Whether to display the standard deviation in progress.\n        Results are not affected, and always contains std.\n    seed : int\n        Seed used to generate the folds (passed to numpy.random.seed).\n\n    Returns\n    -------\n    evaluation history : list(string)"
  },
  {
    "code": "def iter_options(self):\n        for section in self.sections:\n            name = str(section)\n            for key, value in section._get_options():\n                yield name, key, value",
    "docstring": "Iterates configuration sections groups options."
  },
  {
    "code": "def run_preassembly_duplicate(preassembler, beliefengine, **kwargs):\n    logger.info('Combining duplicates on %d statements...' %\n                len(preassembler.stmts))\n    dump_pkl = kwargs.get('save')\n    stmts_out = preassembler.combine_duplicates()\n    beliefengine.set_prior_probs(stmts_out)\n    logger.info('%d unique statements' % len(stmts_out))\n    if dump_pkl:\n        dump_statements(stmts_out, dump_pkl)\n    return stmts_out",
    "docstring": "Run deduplication stage of preassembly on a list of statements.\n\n    Parameters\n    ----------\n    preassembler : indra.preassembler.Preassembler\n        A Preassembler instance\n    beliefengine : indra.belief.BeliefEngine\n        A BeliefEngine instance.\n    save : Optional[str]\n        The name of a pickle file to save the results (stmts_out) into.\n\n    Returns\n    -------\n    stmts_out : list[indra.statements.Statement]\n        A list of unique statements."
  },
  {
    "code": "def order_derived_parameters(component):\n    if len(component.derived_parameters) == 0:\n        return []\n    ordering = []\n    dps = []\n    for dp in component.derived_parameters:\n        dps.append(dp.name)\n    maxcount = 5\n    count = maxcount\n    while count > 0 and dps != []:\n        count = count - 1\n        for dp1 in dps:\n            value = component.derived_parameters[dp1].value\n            found = False\n            for dp2 in dps:\n                if dp1 != dp2 and dp2 in value:\n                    found = True\n            if not found:\n                ordering.append(dp1)\n                del dps[dps.index(dp1)]\n                count = maxcount\n                break\n    if count == 0:\n        raise SimBuildError((\"Unable to find ordering for derived \"\n                             \"parameter in component '{0}'\").format(component))\n    return ordering",
    "docstring": "Finds ordering of derived_parameters.\n\n    @param component: Component containing derived parameters.\n    @type component: lems.model.component.Component\n\n    @return: Returns ordered list of derived parameters.\n    @rtype: list(string)\n\n    @raise SimBuildError: Raised when a proper ordering of derived\n    parameters could not be found."
  },
  {
    "code": "def main():\n    tar_file = TMPDIR + '/' + BINARY_URL.split('/')[-1]\n    chksum = TMPDIR + '/' + MD5_URL.split('/')[-1]\n    if precheck() and os_packages(distro.linux_distribution()):\n        stdout_message('begin download')\n        download()\n        stdout_message('begin valid_checksum')\n        valid_checksum(tar_file, chksum)\n        return compile_binary(tar_file)\n    logger.warning('%s: Pre-run dependency check fail - Exit' % inspect.stack()[0][3])\n    return False",
    "docstring": "Check Dependencies, download files, integrity check"
  },
  {
    "code": "def codingthreads(self):\n        printtime('Extracting CDS features', self.start)\n        for i in range(self.cpus):\n            threads = Thread(target=self.codingsequences, args=())\n            threads.setDaemon(True)\n            threads.start()\n        for sample in self.runmetadata.samples:\n            self.codingqueue.put(sample)\n        self.codingqueue.join()\n        self.corethreads()",
    "docstring": "Find CDS features in .gff files to filter out non-coding sequences from the analysis"
  },
  {
    "code": "def document(self):\n        doc = {'mode': self.__mongos_mode}\n        if self.__tag_sets not in (None, [{}]):\n            doc['tags'] = self.__tag_sets\n        if self.__max_staleness != -1:\n            doc['maxStalenessSeconds'] = self.__max_staleness\n        return doc",
    "docstring": "Read preference as a document."
  },
  {
    "code": "def _prepare_data_dir(self, data):\n        logger.debug(__(\"Preparing data directory for Data with id {}.\", data.id))\n        with transaction.atomic():\n            temporary_location_string = uuid.uuid4().hex[:10]\n            data_location = DataLocation.objects.create(subpath=temporary_location_string)\n            data_location.subpath = str(data_location.id)\n            data_location.save()\n            data_location.data.add(data)\n        output_path = self._get_per_data_dir('DATA_DIR', data_location.subpath)\n        dir_mode = self.settings_actual.get('FLOW_EXECUTOR', {}).get('DATA_DIR_MODE', 0o755)\n        os.mkdir(output_path, mode=dir_mode)\n        os.chmod(output_path, dir_mode)\n        return output_path",
    "docstring": "Prepare destination directory where the data will live.\n\n        :param data: The :class:`~resolwe.flow.models.Data` object for\n            which to prepare the private execution directory.\n        :return: The prepared data directory path.\n        :rtype: str"
  },
  {
    "code": "def orbit(self, x1_px, y1_px, x2_px, y2_px):\n        px_per_deg = self.vport_radius_px / float(self.orbit_speed)\n        radians_per_px = 1.0 / px_per_deg * np.pi / 180.0\n        t2p = self.position - self.target\n        M = Matrix4x4.rotation_around_origin((x1_px - x2_px) * radians_per_px,\n                                             self.ground)\n        t2p = M * t2p\n        self.up = M * self.up\n        right = (self.up ^ t2p).normalized()\n        M = Matrix4x4.rotation_around_origin((y1_px - y2_px) * radians_per_px,\n                                             right)\n        t2p = M * t2p\n        self.up = M * self.up\n        self.position = self.target + t2p",
    "docstring": "Causes the camera to \"orbit\" around the target point.\n        This is also called \"tumbling\" in some software packages."
  },
  {
    "code": "def toggle(self):\n        for device in self:\n            if isinstance(device, (OutputDevice, CompositeOutputDevice)):\n                device.toggle()",
    "docstring": "Toggle all the output devices. For each device, if it's on, turn it\n        off; if it's off, turn it on."
  },
  {
    "code": "def set_data(self, pos=None, color=None, width=None, connect=None):\n        if pos is not None:\n            self._bounds = None\n            self._pos = pos\n            self._changed['pos'] = True\n        if color is not None:\n            self._color = color\n            self._changed['color'] = True\n        if width is not None:\n            self._width = width\n            self._changed['width'] = True\n        if connect is not None:\n            self._connect = connect\n            self._changed['connect'] = True\n        self.update()",
    "docstring": "Set the data used to draw this visual.\n\n        Parameters\n        ----------\n        pos : array\n            Array of shape (..., 2) or (..., 3) specifying vertex coordinates.\n        color : Color, tuple, or array\n            The color to use when drawing the line. If an array is given, it\n            must be of shape (..., 4) and provide one rgba color per vertex.\n        width:\n            The width of the line in px. Line widths < 1 px will be rounded up\n            to 1 px when using the 'gl' method.\n        connect : str or array\n            Determines which vertices are connected by lines.\n            * \"strip\" causes the line to be drawn with each vertex\n              connected to the next.\n            * \"segments\" causes each pair of vertices to draw an\n              independent line segment\n            * int numpy arrays specify the exact set of segment pairs to\n              connect.\n            * bool numpy arrays specify which _adjacent_ pairs to connect."
  },
  {
    "code": "def c2r(self):\n        return matrix(a=self.tt.__complex_op('M'), n=_np.concatenate(\n            (self.n, [2])), m=_np.concatenate((self.m, [2])))",
    "docstring": "Get real matrix from complex one suitable for solving complex linear system with real solver.\n\n        For matrix :math:`M(i_1,j_1,\\\\ldots,i_d,j_d) = \\\\Re M + i\\\\Im M` returns (d+1)-dimensional matrix\n        :math:`\\\\tilde{M}(i_1,j_1,\\\\ldots,i_d,j_d,i_{d+1},j_{d+1})` of form\n        :math:`\\\\begin{bmatrix}\\\\Re M & -\\\\Im M \\\\\\\\ \\\\Im M &  \\\\Re M  \\\\end{bmatrix}`. This function\n        is useful for solving complex linear system :math:`\\\\mathcal{A}X = B` with real solver by\n        transforming it into\n\n        .. math::\n           \\\\begin{bmatrix}\\\\Re\\\\mathcal{A} & -\\\\Im\\\\mathcal{A} \\\\\\\\\n                           \\\\Im\\\\mathcal{A} &  \\\\Re\\\\mathcal{A}  \\\\end{bmatrix}\n           \\\\begin{bmatrix}\\\\Re X \\\\\\\\ \\\\Im X\\\\end{bmatrix} =\n           \\\\begin{bmatrix}\\\\Re B \\\\\\\\ \\\\Im B\\\\end{bmatrix}."
  },
  {
    "code": "def contains_duplicates(values: Iterable[Any]) -> bool:\n    for v in Counter(values).values():\n        if v > 1:\n            return True\n    return False",
    "docstring": "Does the iterable contain any duplicate values?"
  },
  {
    "code": "def flatten_check(out:Tensor, targ:Tensor) -> Tensor:\n    \"Check that `out` and `targ` have the same number of elements and flatten them.\"\n    out,targ = out.contiguous().view(-1),targ.contiguous().view(-1)\n    assert len(out) == len(targ), f\"Expected output and target to have the same number of elements but got {len(out)} and {len(targ)}.\"\n    return out,targ",
    "docstring": "Check that `out` and `targ` have the same number of elements and flatten them."
  },
  {
    "code": "def secgroup_info(call=None, kwargs=None):\n    if call != 'function':\n        raise SaltCloudSystemExit(\n            'The secgroup_info function must be called with -f or --function.'\n        )\n    if kwargs is None:\n        kwargs = {}\n    name = kwargs.get('name', None)\n    secgroup_id = kwargs.get('secgroup_id', None)\n    if secgroup_id:\n        if name:\n            log.warning(\n                'Both the \\'secgroup_id\\' and \\'name\\' arguments were provided. '\n                '\\'secgroup_id\\' will take precedence.'\n            )\n    elif name:\n        secgroup_id = get_secgroup_id(kwargs={'name': name})\n    else:\n        raise SaltCloudSystemExit(\n            'The secgroup_info function requires either a name or a secgroup_id '\n            'to be provided.'\n        )\n    server, user, password = _get_xml_rpc()\n    auth = ':'.join([user, password])\n    info = {}\n    response = server.one.secgroup.info(auth, int(secgroup_id))[1]\n    tree = _get_xml(response)\n    info[tree.find('NAME').text] = _xml_to_dict(tree)\n    return info",
    "docstring": "Retrieves information for the given security group. Either a name or a\n    secgroup_id must be supplied.\n\n    .. versionadded:: 2016.3.0\n\n    name\n        The name of the security group for which to gather information. Can be\n        used instead of ``secgroup_id``.\n\n    secgroup_id\n        The ID of the security group for which to gather information. Can be\n        used instead of ``name``.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -f secgroup_info opennebula name=my-secgroup\n        salt-cloud --function secgroup_info opennebula secgroup_id=5"
  },
  {
    "code": "def resize(att_mat, max_length=None):\n  for i, att in enumerate(att_mat):\n    if att.ndim == 3:\n      att = np.expand_dims(att, axis=0)\n    if max_length is not None:\n      att = att[:, :, :max_length, :max_length]\n      row_sums = np.sum(att, axis=2)\n      att /= row_sums[:, :, np.newaxis]\n    att_mat[i] = att\n  return att_mat",
    "docstring": "Normalize attention matrices and reshape as necessary."
  },
  {
    "code": "def clean(self, elements):\n\t\tcleanelements = []\n\t\tfor i in xrange(len(elements)):\n\t\t\tif isempty(elements[i]):\n\t\t\t\treturn []\n\t\t\tnext = elements[i]\n\t\t\tif isinstance(elements[i], (list, tuple)):\n\t\t\t\tnext = self.clean(elements[i])\n\t\t\tif next:\n\t\t\t\tcleanelements.append(elements[i])\n\t\treturn cleanelements",
    "docstring": "Removes empty or incomplete answers."
  },
  {
    "code": "def ENUM(self, _cursor_type):\n        _decl = _cursor_type.get_declaration()\n        name = self.get_unique_name(_decl)\n        if self.is_registered(name):\n            obj = self.get_registered(name)\n        else:\n            log.warning('Was in ENUM but had to parse record declaration ')\n            obj = self.parse_cursor(_decl)\n        return obj",
    "docstring": "Handles ENUM typedef."
  },
  {
    "code": "def query_by_assignment(self, assignment_id, end_time=None, start_time=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"assignment_id\"] = assignment_id\r\n        if start_time is not None:\r\n            params[\"start_time\"] = start_time\r\n        if end_time is not None:\r\n            params[\"end_time\"] = end_time\r\n        self.logger.debug(\"GET /api/v1/audit/grade_change/assignments/{assignment_id} with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"GET\", \"/api/v1/audit/grade_change/assignments/{assignment_id}\".format(**path), data=data, params=params, all_pages=True)",
    "docstring": "Query by assignment.\r\n\r\n        List grade change events for a given assignment."
  },
  {
    "code": "def construct_sls_str(self, node):\n        obj = self.construct_scalar(node)\n        if six.PY2:\n            obj = obj.encode('utf-8')\n        return SLSString(obj)",
    "docstring": "Build the SLSString."
  },
  {
    "code": "def ignore_nan_inf(kde_method):\n    def new_kde_method(events_x, events_y, xout=None, yout=None,\n                       *args, **kwargs):\n        bad_in = get_bad_vals(events_x, events_y)\n        if xout is None:\n            density = np.zeros_like(events_x, dtype=float)\n            bad_out = bad_in\n            xo = yo = None\n        else:\n            density = np.zeros_like(xout, dtype=float)\n            bad_out = get_bad_vals(xout, yout)\n            xo = xout[~bad_out]\n            yo = yout[~bad_out]\n        ev_x = events_x[~bad_in]\n        ev_y = events_y[~bad_in]\n        density[~bad_out] = kde_method(ev_x, ev_y,\n                                       xo, yo,\n                                       *args, **kwargs)\n        density[bad_out] = np.nan\n        return density\n    doc_add = \"\\n    Notes\\n\" +\\\n              \"    -----\\n\" +\\\n              \"    This is a wrapped version that ignores nan and inf values.\"\n    new_kde_method.__doc__ = kde_method.__doc__ + doc_add\n    return new_kde_method",
    "docstring": "Ignores nans and infs from the input data\n\n    Invalid positions in the resulting density are set to nan."
  },
  {
    "code": "def emit(self, record):\n        if self.triggerLevelNo is not None and record.levelno>=self.triggerLevelNo:\n            self.triggered = True\n        logging.handlers.BufferingHandler.emit(self,record)",
    "docstring": "Emit record after checking if message triggers later sending of e-mail."
  },
  {
    "code": "def export_to_json(self):\n        return {\n            hostname: sorted(self._encode_key(key) for key in pins)\n            for hostname, pins in self._storage.items()\n        }",
    "docstring": "Return a JSON dictionary which contains all the pins stored in this\n        store."
  },
  {
    "code": "def cd(path_to):\n    if path_to == '-':\n        if not cd.previous:\n            raise PathError('No previous directory to return to')\n        return cd(cd.previous)\n    if not hasattr(path_to, 'cd'):\n        path_to = makepath(path_to)\n    try:\n        previous = os.getcwd()\n    except OSError as e:\n        if 'No such file or directory' in str(e):\n            return False\n        raise\n    if path_to.isdir():\n        os.chdir(path_to)\n    elif path_to.isfile():\n        os.chdir(path_to.parent)\n    elif not os.path.exists(path_to):\n        return False\n    else:\n        raise PathError('Cannot cd to %s' % path_to)\n    cd.previous = previous\n    return True",
    "docstring": "cd to the given path\n\n    If the path is a file, then cd to its parent directory\n\n    Remember current directory before the cd\n        so that we can cd back there with cd('-')"
  },
  {
    "code": "def get_inline_expression(self, text):\n        text = text.strip()\n        if not text.startswith(self.inline_tags[0]) or not text.endswith(self.inline_tags[1]):\n            return\n        return text[2:-2]",
    "docstring": "Extract an inline expression from the given text."
  },
  {
    "code": "def clean_zeros(a, b, M):\n    M2 = M[a > 0, :][:, b > 0].copy()\n    a2 = a[a > 0]\n    b2 = b[b > 0]\n    return a2, b2, M2",
    "docstring": "Remove all components with zeros weights in a and b"
  },
  {
    "code": "def findLeftBrace(self, block, column):\n        block, column = self.findBracketBackward(block, column, '{')\n        try:\n            block, column = self.tryParenthesisBeforeBrace(block, column)\n        except ValueError:\n            pass\n        return self._blockIndent(block)",
    "docstring": "Search for a corresponding '{' and return its indentation\n        If not found return None"
  },
  {
    "code": "def peek_string(self, lpBaseAddress, fUnicode = False, dwMaxSize = 0x1000):\n        if not lpBaseAddress or dwMaxSize == 0:\n            if fUnicode:\n                return u''\n            return ''\n        if not dwMaxSize:\n            dwMaxSize = 0x1000\n        szString = self.peek(lpBaseAddress, dwMaxSize)\n        if fUnicode:\n            szString = compat.unicode(szString, 'U16', 'replace')\n            szString = szString[ : szString.find(u'\\0') ]\n        else:\n            szString = szString[ : szString.find('\\0') ]\n        return szString",
    "docstring": "Tries to read an ASCII or Unicode string\n        from the address space of the process.\n\n        @see: L{read_string}\n\n        @type  lpBaseAddress: int\n        @param lpBaseAddress: Memory address to begin reading.\n\n        @type  fUnicode: bool\n        @param fUnicode: C{True} is the string is expected to be Unicode,\n            C{False} if it's expected to be ANSI.\n\n        @type  dwMaxSize: int\n        @param dwMaxSize: Maximum allowed string length to read, in bytes.\n\n        @rtype:  str, compat.unicode\n        @return: String read from the process memory space.\n            It B{doesn't} include the terminating null character.\n            Returns an empty string on failure."
  },
  {
    "code": "def get_library_name():\n    from os.path import split, abspath\n    __lib_name = split(split(abspath(sys.modules[__name__].__file__))[0])[1]\n    assert __lib_name in [\"sframe\", \"turicreate\"]\n    return __lib_name",
    "docstring": "Returns either sframe or turicreate depending on which library\n    this file is bundled with."
  },
  {
    "code": "def save(self, obj, id_code):\n        filestream = open('{0}/{1}'.format(self.data_path, id_code), 'w+')\n        pickle.dump(obj, filestream)\n        filestream.close()",
    "docstring": "Save an object, and use id_code in the filename\n        obj - any object\n        id_code - unique identifier"
  },
  {
    "code": "def _get_body(self):\n        \" Return the Container object for the current CLI. \"\n        new_hash = self.pymux.arrangement.invalidation_hash()\n        app = get_app()\n        if app in self._bodies_for_app:\n            existing_hash, container = self._bodies_for_app[app]\n            if existing_hash == new_hash:\n                return container\n        new_layout = self._build_layout()\n        self._bodies_for_app[app] = (new_hash, new_layout)\n        return new_layout",
    "docstring": "Return the Container object for the current CLI."
  },
  {
    "code": "def _apply_task(task: Task, args: Tuple, kwargs: Dict[str, Any]) -> Any:\n        if args is None:\n            args = ()\n        if kwargs is None:\n            kwargs = {}\n        start = monotonic()\n        try:\n            return task.apply(*args, **kwargs)\n        finally:\n            delta = monotonic() - start\n            logger.info(\"%s finished in %i seconds.\" % (task.name, delta))",
    "docstring": "Logs the time spent while running the task."
  },
  {
    "code": "def GetDefault(self, fd=None, default=None):\n    if callable(self.default):\n      return self.default(fd)\n    if self.default is not None:\n      if isinstance(self.default, rdfvalue.RDFValue):\n        default = self.default.Copy()\n        default.attribute_instance = self\n        return self(default)\n      else:\n        return self(self.default)\n    if isinstance(default, rdfvalue.RDFValue):\n      default = default.Copy()\n      default.attribute_instance = self\n    return default",
    "docstring": "Returns a default attribute if it is not set."
  },
  {
    "code": "def _exception_free_callback(self, callback, *args, **kwargs):\n        try:\n            return callback(*args, **kwargs)\n        except Exception:\n            self._logger.exception(\"An exception occurred while calling a hook! \",exc_info=True)\n            return None",
    "docstring": "A wrapper that remove all exceptions raised from hooks"
  },
  {
    "code": "def to_dict(self, xml):\n        children = list(xml)\n        if not children:\n            return xml.text\n        else:\n            out = {}\n            for node in list(xml):\n                if node.tag in out:\n                    if not isinstance(out[node.tag], list):\n                        out[node.tag] = [out[node.tag]]\n                    out[node.tag].append(self.to_dict(node))\n                else:\n                    out[node.tag] = self.to_dict(node)\n            return out",
    "docstring": "Convert XML structure to dict recursively, repeated keys\n        entries are returned as in list containers."
  },
  {
    "code": "def copy_shell(self):\n        cls = self.__class__\n        new_i = cls()\n        new_i.uuid = self.uuid\n        for prop in cls.properties:\n            if hasattr(self, prop):\n                if prop in ['members', 'unknown_members']:\n                    setattr(new_i, prop, [])\n                else:\n                    setattr(new_i, prop, getattr(self, prop))\n        return new_i",
    "docstring": "Copy the group properties EXCEPT the members.\n        Members need to be filled after manually\n\n        :return: Itemgroup object\n        :rtype: alignak.objects.itemgroup.Itemgroup\n        :return: None"
  },
  {
    "code": "def timed_call(self, ms, callback, *args, **kwargs):\n        return self.loop.timed_call(ms, callback, *args, **kwargs)",
    "docstring": "Invoke a callable on the main event loop thread at a\n        specified time in the future.\n\n        Parameters\n        ----------\n        ms : int\n            The time to delay, in milliseconds, before executing the\n            callable.\n\n        callback : callable\n            The callable object to execute at some point in the future.\n\n        *args, **kwargs\n            Any additional positional and keyword arguments to pass to\n            the callback."
  },
  {
    "code": "def doUpdate(self, timeout=1):\n        namespace = Fritz.getServiceType(\"doUpdate\")\n        uri = self.getControlURL(namespace)\n        results = self.execute(uri, namespace, \"X_AVM-DE_DoUpdate\", timeout=timeout)\n        return results[\"NewUpgradeAvailable\"], results[\"NewX_AVM-DE_UpdateState\"]",
    "docstring": "Do a software update of the Fritz Box if available.\n\n        :param float timeout: the timeout to wait for the action to be executed\n        :return: a list of if an update was available and the update state (bool, str)\n        :rtype: tuple(bool, str)"
  },
  {
    "code": "def get_version(path=\"src/devpy/__init__.py\"):\n    init_content = open(path, \"rt\").read()\n    pattern = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"\n    return re.search(pattern, init_content, re.M).group(1)",
    "docstring": "Return the version of by with regex intead of importing it"
  },
  {
    "code": "def qd2apex(self, qlat, qlon, height):\n        alat, alon = self._qd2apex(qlat, qlon, height)\n        return np.float64(alat), np.float64(alon)",
    "docstring": "Converts quasi-dipole to modified apex coordinates.\n\n        Parameters\n        ==========\n        qlat : array_like\n            Quasi-dipole latitude\n        qlon : array_like\n            Quasi-dipole longitude\n        height : array_like\n            Altitude in km\n\n        Returns\n        =======\n        alat : ndarray or float\n            Modified apex latitude\n        alon : ndarray or float\n            Modified apex longitude\n\n        Raises\n        ======\n        ApexHeightError\n            if apex height < reference height"
  },
  {
    "code": "def db_for_read(self, model, **hints):\n        if model._meta.app_label in self._apps:\n            return getattr(model, '_db_alias', model._meta.app_label)\n        return None",
    "docstring": "If the app has its own database, use it for reads"
  },
  {
    "code": "def _fill_vao(self):\n        with self.vao:\n            self.vbos = []\n            for loc, verts in enumerate(self.arrays):\n                vbo = VBO(verts)\n                self.vbos.append(vbo)\n                self.vao.assign_vertex_attrib_location(vbo, loc)",
    "docstring": "Put array location in VAO for shader in same order as arrays given to Mesh."
  },
  {
    "code": "def configure_urls(apps, index_view=None, prefixes=None):\n    prefixes = prefixes or {}\n    urlpatterns = patterns('')\n    if index_view:\n        from django.views.generic.base import RedirectView\n        urlpatterns += patterns('',\n            url(r'^$', RedirectView.as_view(pattern_name=index_view, permanent=False)),\n        )\n    for app_name in apps:\n        app_module = importlib.import_module(app_name)\n        if module_has_submodule(app_module, 'urls'):\n            module = importlib.import_module(\"%s.urls\" % app_name)\n            if not hasattr(module, 'urlpatterns'):\n                continue\n            app_prefix = prefixes.get(app_name, app_name.replace(\"_\",\"-\"))\n            urlpatterns += patterns(\n                '',\n                url(\n                    r'^%s/' % app_prefix if app_prefix else '',\n                    include(\"%s.urls\" % app_name),\n                ),\n            )\n    return urlpatterns",
    "docstring": "Configure urls from a list of apps."
  },
  {
    "code": "def get_proficiency_search_session(self, proxy):\n        if not self.supports_proficiency_search():\n            raise Unimplemented()\n        try:\n            from . import sessions\n        except ImportError:\n            raise OperationFailed()\n        proxy = self._convert_proxy(proxy)\n        try:\n            session = sessions.ProficiencySearchSession(proxy=proxy, runtime=self._runtime)\n        except AttributeError:\n            raise OperationFailed()\n        return session",
    "docstring": "Gets the ``OsidSession`` associated with the proficiency search service.\n\n        :param proxy: a proxy\n        :type proxy: ``osid.proxy.Proxy``\n        :return: a ``ProficiencySearchSession``\n        :rtype: ``osid.learning.ProficiencySearchSession``\n        :raise: ``NullArgument`` -- ``proxy`` is ``null``\n        :raise: ``OperationFailed`` -- unable to complete request\n        :raise: ``Unimplemented`` -- ``supports_proficiency_search()`` is ``false``\n\n        *compliance: optional -- This method must be implemented if ``supports_proficiency_search()`` is ``true``.*"
  },
  {
    "code": "def popenCLIExecutable(command, **kwargs):\n    cliExecutable = command[0]\n    ma = re_slicerSubPath.search(cliExecutable)\n    if ma:\n        wrapper = os.path.join(cliExecutable[:ma.start()], 'Slicer')\n        if sys.platform.startswith('win'):\n            wrapper += '.exe'\n        if os.path.exists(wrapper):\n            command = [wrapper, '--launcher-no-splash', '--launch'] + command\n    return subprocess.Popen(command, **kwargs)",
    "docstring": "Wrapper around subprocess.Popen constructor that tries to\n    detect Slicer CLI modules and launches them through the Slicer\n    launcher in order to prevent potential DLL dependency issues.\n\n    Any kwargs are passed on to subprocess.Popen().\n\n    If you ever try to use this function to run a CLI, you might want to\n    take a look at\n    https://github.com/hmeine/MeVisLab-CLI/blob/master/Modules/Macros/CTK_CLI/CLIModuleBackend.py\n    (in particular, the CLIExecution class.)\n    Ideally, more of that code would be extracted and moved here, but\n    I have not gotten around to doing that yet."
  },
  {
    "code": "def _integer_to_interval(arg, unit='s'):\n    op = ops.IntervalFromInteger(arg, unit)\n    return op.to_expr()",
    "docstring": "Convert integer interval with the same inner type\n\n    Parameters\n    ----------\n    unit : {'Y', 'M', 'W', 'D', 'h', 'm', s', 'ms', 'us', 'ns'}\n\n    Returns\n    -------\n    interval : interval value expression"
  },
  {
    "code": "def _plot(self):\n        for serie in self.series[::-1 if self.stack_from_top else 1]:\n            self.bar(serie)\n        for serie in self.secondary_series[::-1 if self.stack_from_top else 1]:\n            self.bar(serie, True)",
    "docstring": "Draw bars for series and secondary series"
  },
  {
    "code": "def stopDtmfAcknowledge():\n    a = TpPd(pd=0x3)\n    b = MessageType(mesType=0x32)\n    packet = a / b\n    return packet",
    "docstring": "STOP DTMF ACKNOWLEDGE Section 9.3.30"
  },
  {
    "code": "def create_model(schema, collection, class_name=None):\n    if not class_name:\n        class_name = camelize(str(collection.name))\n    model_class = type(class_name,\n                       (Model,),\n                       dict(schema=schema, _collection_factory=staticmethod(lambda: collection)))\n    model_class.__module__ = _module_name_from_previous_frame(1)\n    return model_class",
    "docstring": "Main entry point to creating a new mongothon model. Both\n    schema and Pymongo collection objects must be provided.\n\n    Returns a new class which can be used as a model class.\n\n    The class name of the model class by default is inferred\n    from the provided collection (converted to camel case).\n    Optionally, a class_name argument can be provided to\n    override this."
  },
  {
    "code": "def is_applicable_python_file(rel_path: str) -> bool:\n    return (rel_path.endswith('.py') and\n            not any(re.search(pat, rel_path) for pat in IGNORED_FILE_PATTERNS))",
    "docstring": "Determines if a file should be included in incremental coverage analysis.\n\n    Args:\n        rel_path: The repo-relative file path being considered.\n    Returns:\n        Whether to include the file."
  },
  {
    "code": "def add_general_optgroup(parser):\n    g = parser.add_argument_group(\"General Options\")\n    g.add_argument(\"-q\", \"--quiet\", dest=\"silent\",\n                   action=\"store_true\", default=False)\n    g.add_argument(\"-v\", \"--verbose\", nargs=0, action=_opt_cb_verbose)\n    g.add_argument(\"-o\", \"--output\", dest=\"output\", default=None)\n    g.add_argument(\"-j\", \"--json\", dest=\"json\",\n                   action=\"store_true\", default=False)\n    g.add_argument(\"--show-ignored\", action=\"store_true\", default=False)\n    g.add_argument(\"--show-unchanged\", action=\"store_true\", default=False)\n    g.add_argument(\"--ignore\", action=_opt_cb_ignore,\n                   help=\"comma-separated list of ignores\")",
    "docstring": "option group for general-use features of all javatool CLIs"
  },
  {
    "code": "def RegisterMountPoint(cls, mount_point, path_spec):\n    if mount_point in cls._mount_points:\n      raise KeyError('Mount point: {0:s} already set.'.format(mount_point))\n    cls._mount_points[mount_point] = path_spec",
    "docstring": "Registers a path specification mount point.\n\n    Args:\n      mount_point (str): mount point identifier.\n      path_spec (PathSpec): path specification of the mount point.\n\n    Raises:\n      KeyError: if the corresponding mount point is already set."
  },
  {
    "code": "def objref(obj):\n    ref = _objrefs.get(obj)\n    if ref is None:\n        clsname = obj.__class__.__name__.split('.')[-1]\n        seqno = _lastids.setdefault(clsname, 1)\n        ref = '{}-{}'.format(clsname, seqno)\n        _objrefs[obj] = ref\n        _lastids[clsname] += 1\n    return ref",
    "docstring": "Return a string that uniquely and compactly identifies an object."
  },
  {
    "code": "def _get_norms_of_rows(data_frame, method):\n    if method == 'vector':\n        norm_vector = np.linalg.norm(data_frame.values, axis=1)\n    elif method == 'last':\n        norm_vector = data_frame.iloc[:, -1].values\n    elif method == 'mean':\n        norm_vector = np.mean(data_frame.values, axis=1)\n    elif method == 'first':\n        norm_vector = data_frame.iloc[:, 0].values\n    else:\n        raise ValueError(\"no normalization method '{0}'\".format(method))\n    return norm_vector",
    "docstring": "return a column vector containing the norm of each row"
  },
  {
    "code": "def date_sorted_sources(*sources):\n    sorted_stream = heapq.merge(*(_decorate_source(s) for s in sources))\n    for _, message in sorted_stream:\n        yield message",
    "docstring": "Takes an iterable of sources, generating namestrings and\n    piping their output into date_sort."
  },
  {
    "code": "def edit(self,\n             billing_email=None,\n             company=None,\n             email=None,\n             location=None,\n             name=None):\n        json = None\n        data = {'billing_email': billing_email, 'company': company,\n                'email': email, 'location': location, 'name': name}\n        self._remove_none(data)\n        if data:\n            json = self._json(self._patch(self._api, data=dumps(data)), 200)\n        if json:\n            self._update_(json)\n            return True\n        return False",
    "docstring": "Edit this organization.\n\n        :param str billing_email: (optional) Billing email address (private)\n        :param str company: (optional)\n        :param str email: (optional) Public email address\n        :param str location: (optional)\n        :param str name: (optional)\n        :returns: bool"
  },
  {
    "code": "def compression_details(self):\n        event_type = self.findtext(\"event_type\")\n        if event_type != \"compression\":\n            raise AttributeError(\n                'PREMIS events of type \"{}\" have no compression'\n                \" details\".format(event_type)\n            )\n        parsed_compression_event_detail = self.parsed_event_detail\n        compression_program = _get_event_detail_attr(\n            \"program\", parsed_compression_event_detail\n        )\n        compression_algorithm = _get_event_detail_attr(\n            \"algorithm\", parsed_compression_event_detail\n        )\n        compression_program_version = _get_event_detail_attr(\n            \"version\", parsed_compression_event_detail\n        )\n        archive_tool = {\"7z\": \"7-Zip\"}.get(compression_program, compression_program)\n        return compression_algorithm, compression_program_version, archive_tool",
    "docstring": "Return as a 3-tuple, this PREMIS compression event's program,\n        version, and algorithm used to perform the compression."
  },
  {
    "code": "def remove_redis_keyword(self, keyword):\n        redisvr.srem(CMS_CFG['redis_kw'] + self.userinfo.user_name, keyword)\n        return json.dump({}, self)",
    "docstring": "Remove the keyword for redis."
  },
  {
    "code": "def open(self, target_uri, **kwargs):\n        target = urlsplit(target_uri, scheme=self.default_opener)\n        opener = self.get_opener(target.scheme)\n        query = opener.conform_query(target.query)\n        target = opener.get_target(\n            target.scheme,\n            target.path,\n            target.fragment,\n            target.username,\n            target.password,\n            target.hostname,\n            target.port,\n            query,\n            **kwargs\n        )\n        target.opener_path = target_uri\n        return target",
    "docstring": "Open target uri.\n\n        :param target_uri: Uri to open\n        :type target_uri: string\n\n        :returns: Target object"
  },
  {
    "code": "def set_comment(self, comment = None):\n        if comment is None or type(comment) is not str:\n            raise KPError(\"Need a new image number\")\n        else:\n            self.comment = comment\n            self.last_mod = datetime.now().replace(microsecond=0)\n            return True",
    "docstring": "This method is used to the the comment.\n\n        comment must be a string."
  },
  {
    "code": "def GetClassesByArtifact(cls, artifact_name):\n    return [\n        cls.classes[c]\n        for c in cls.classes\n        if artifact_name in cls.classes[c].supported_artifacts\n    ]",
    "docstring": "Get the classes that support parsing a given artifact."
  },
  {
    "code": "def _wrap_jinja_filter(self, function):\n        def wrapper(*args, **kwargs):\n            try:\n                return function(*args, **kwargs)\n            except Exception:\n                return NestedUndefined()\n        for attribute in dir(function):\n            if attribute.endswith('filter'):\n                setattr(wrapper, attribute, getattr(function, attribute))\n        return wrapper",
    "docstring": "Propagate exceptions as undefined values filter."
  },
  {
    "code": "def subsample(time_series, downsample_factor):\n    Ns = np.int(np.floor(np.size(time_series)/downsample_factor))\n    g = gaussian_kernel(0.5*downsample_factor)\n    ts_blur = np.convolve(time_series,g,'same')\n    ts_out = np.zeros((Ns,1), dtype='float64')\n    for k in range(0,Ns):\n        cpos  = (k+.5)*downsample_factor-.5\n        cfrac = cpos-np.floor(cpos)\n        cind  = np.floor(cpos)\n        if cfrac>0:\n            ts_out[k]=ts_blur[cind]*(1-cfrac)+ts_blur[cind+1]*cfrac\n        else:\n            ts_out[k]=ts_blur[cind]\n    return ts_out",
    "docstring": "Subsample with Gaussian prefilter\n\n    The prefilter will have the filter size $\\sigma_g=.5*ssfactor$\n\n    Parameters\n    --------------\n    time_series : ndarray\n            Input signal\n    downsample_factor : float\n            Downsampling factor\n       \n    Returns\n    --------------\n       ts_out : ndarray\n            The downsampled signal"
  },
  {
    "code": "def insert(self, node, before=None):\n        node._list = self\n        if self._first is None:\n            self._first = self._last = node\n            self._size += 1\n            return node\n        if before is None:\n            self._last._next = node\n            node._prev = self._last\n            self._last = node\n        else:\n            node._next = before\n            node._prev = before._prev\n            if node._prev:\n                node._prev._next = node\n            else:\n                self._first = node\n            node._next._prev = node\n        self._size += 1\n        return node",
    "docstring": "Insert a new node in the list.\n\n        If *before* is specified, the new node is inserted before this node.\n        Otherwise, the node is inserted at the end of the list."
  },
  {
    "code": "def _get_document_path(client, path):\n    parts = (client._database_string, \"documents\") + path\n    return _helpers.DOCUMENT_PATH_DELIMITER.join(parts)",
    "docstring": "Convert a path tuple into a full path string.\n\n    Of the form:\n\n        ``projects/{project_id}/databases/{database_id}/...\n              documents/{document_path}``\n\n    Args:\n        client (~.firestore_v1beta1.client.Client): The client that holds\n            configuration details and a GAPIC client object.\n        path (Tuple[str, ...]): The components in a document path.\n\n    Returns:\n        str: The fully-qualified document path."
  },
  {
    "code": "def getIPString():\n        if not(NetInfo.systemip):\n            NetInfo.systemip = \",\".join(NetInfo.getSystemIps())\n        return NetInfo.systemip",
    "docstring": "return comma delimited string of all the system IPs"
  },
  {
    "code": "def _query(self, url=None, params=\"\"):\n        if url is None:\n            raise NoUrlError(\"No URL was provided.\")\n        headers = {'location': None, 'title': None}\n        headerdata = urllib.urlencode(params)\n        try:\n            request = urllib2.Request(url, headerdata)\n            response = urllib2.urlopen(request)\n            if 'jsonp' in params:\n                status = response.read()\n            else:\n                status = response.getcode()\n            info = response.info()\n            try:\n                headers['location'] = info['Content-Location']\n            except KeyError:\n                pass\n            try:\n                headers['title'] = info['X-Instapaper-Title']\n            except KeyError:\n                pass\n            return (status, headers)\n        except urllib2.HTTPError as exception:\n            if 'jsonp' in params:\n                return ('%s({\"status\":%d})' % (params['jsonp'], exception.code), headers)\n            else:\n                return (exception.code, headers)\n        except IOError as exception:\n            return (exception.code, headers)",
    "docstring": "method to query a URL with the given parameters\n\n            Parameters:\n                url -> URL to query\n                params -> dictionary with parameter values\n\n            Returns: HTTP response code, headers\n                     If an exception occurred, headers fields are None"
  },
  {
    "code": "def meminfo_send(self, brkval, freemem, force_mavlink1=False):\n                return self.send(self.meminfo_encode(brkval, freemem), force_mavlink1=force_mavlink1)",
    "docstring": "state of APM memory\n\n                brkval                    : heap top (uint16_t)\n                freemem                   : free memory (uint16_t)"
  },
  {
    "code": "def get_context(pid_file, daemon=False):\n    port_file = get_context_file_name(pid_file)\n    if not os.path.exists(port_file):\n        return None\n    with open(port_file, \"rt\") as f:\n        json_data = f.read()\n        try:\n            data = json.loads(json_data)\n        except ValueError as e:\n            logger.error(\"Damaged context json data %s\", json_data)\n            return None\n        if not daemon:\n            pid = data.get(\"pid\")\n            if pid and not check_pid(int(pid)):\n                return None\n        return data",
    "docstring": "Get context of running notebook.\n\n    A context file is created when notebook starts.\n\n    :param daemon: Are we trying to fetch the context inside the daemon. Otherwise do the death check.\n\n    :return: dict or None if the process is dead/not launcherd"
  },
  {
    "code": "def get_events_with_n_cluster(event_number, condition='n_cluster==1'):\n    logging.debug(\"Calculate events with clusters where \" + condition)\n    n_cluster_in_events = analysis_utils.get_n_cluster_in_events(event_number)\n    n_cluster = n_cluster_in_events[:, 1]\n    return n_cluster_in_events[ne.evaluate(condition), 0]",
    "docstring": "Selects the events with a certain number of cluster.\n\n    Parameters\n    ----------\n    event_number : numpy.array\n\n    Returns\n    -------\n    numpy.array"
  },
  {
    "code": "def trace_next_query(self, ):\n    self._seqid += 1\n    d = self._reqs[self._seqid] = defer.Deferred()\n    self.send_trace_next_query()\n    return d",
    "docstring": "Enables tracing for the next query in this connection and returns the UUID for that trace session\n    The next query will be traced idependently of trace probability and the returned UUID can be used to query the trace keyspace"
  },
  {
    "code": "def _lookup_global(self, symbol):\n        assert symbol.parts\n        namespace = self.namespaces\n        if len(symbol.parts) == 1:\n            namespace = self.namespaces[None]\n        try:\n            return self._lookup_namespace(symbol, namespace)\n        except Error as orig_exc:\n            try:\n                namespace = self.namespaces[None]\n                return self._lookup_namespace(symbol, namespace)\n            except Error:\n                raise orig_exc",
    "docstring": "Helper for lookup_symbol that only looks up global variables.\n\n        Args:\n          symbol: Symbol"
  },
  {
    "code": "def latex(self):\n        if not self:\n            return \"\"\n        s = str(self)\n        s = s.replace(\"==\", \" = \")\n        s = s.replace(\"<=\", \" \\leq \")\n        s = s.replace(\">=\", \" \\geq \")\n        s = s.replace(\"&&\", r\" \\text{ and } \")\n        s = s.replace(\"||\", r\" \\text{ or } \")\n        return s",
    "docstring": "Returns a string representation for use in LaTeX"
  },
  {
    "code": "def _iso_week_of_month(date_value):\n    \"0-starting index which ISO-week in the month this date is\"\n    weekday_of_first = date_value.replace(day=1).weekday()\n    return (date_value.day + weekday_of_first - 1) // 7",
    "docstring": "0-starting index which ISO-week in the month this date is"
  },
  {
    "code": "def pearsonr(self, target, correlation_length, mask=NotSpecified):\n        from .statistical import RollingPearson\n        return RollingPearson(\n            base_factor=self,\n            target=target,\n            correlation_length=correlation_length,\n            mask=mask,\n        )",
    "docstring": "Construct a new Factor that computes rolling pearson correlation\n        coefficients between `target` and the columns of `self`.\n\n        This method can only be called on factors which are deemed safe for use\n        as inputs to other factors. This includes `Returns` and any factors\n        created from `Factor.rank` or `Factor.zscore`.\n\n        Parameters\n        ----------\n        target : zipline.pipeline.Term with a numeric dtype\n            The term used to compute correlations against each column of data\n            produced by `self`. This may be a Factor, a BoundColumn or a Slice.\n            If `target` is two-dimensional, correlations are computed\n            asset-wise.\n        correlation_length : int\n            Length of the lookback window over which to compute each\n            correlation coefficient.\n        mask : zipline.pipeline.Filter, optional\n            A Filter describing which assets should have their correlation with\n            the target slice computed each day.\n\n        Returns\n        -------\n        correlations : zipline.pipeline.factors.RollingPearson\n            A new Factor that will compute correlations between `target` and\n            the columns of `self`.\n\n        Examples\n        --------\n        Suppose we want to create a factor that computes the correlation\n        between AAPL's 10-day returns and the 10-day returns of all other\n        assets, computing each correlation over 30 days. This can be achieved\n        by doing the following::\n\n            returns = Returns(window_length=10)\n            returns_slice = returns[sid(24)]\n            aapl_correlations = returns.pearsonr(\n                target=returns_slice, correlation_length=30,\n            )\n\n        This is equivalent to doing::\n\n            aapl_correlations = RollingPearsonOfReturns(\n                target=sid(24), returns_length=10, correlation_length=30,\n            )\n\n        See Also\n        --------\n        :func:`scipy.stats.pearsonr`\n        :class:`zipline.pipeline.factors.RollingPearsonOfReturns`\n        :meth:`Factor.spearmanr`"
  },
  {
    "code": "def binary_hash(self, project, patch_file):\n        global il\n        exception_file = None\n        try:\n            project_exceptions = il.get('project_exceptions')\n        except KeyError:\n            logger.info('project_exceptions missing in %s for %s', ignore_list, project)\n        for project_files in project_exceptions:\n            if project in project_files:\n                exception_file = project_files.get(project)\n                with open(exception_file, 'r') as f:\n                    bl = yaml.safe_load(f)\n                for key, value in bl.items():\n                    if key == 'binaries':\n                        if patch_file in value:\n                            hashvalue = value[patch_file]\n                            return hashvalue\n                        else:\n                            for key, value in il.items():\n                                if key == 'binaries':\n                                    if patch_file in value:\n                                        hashvalue = value[patch_file]\n                                        return hashvalue\n                                    else:\n                                        hashvalue = \"\"\n                                        return hashvalue\n            else:\n                logger.info('%s not found in %s', project, ignore_list)\n                logger.info('No project specific exceptions will be applied')\n                hashvalue = \"\"\n                return hashvalue",
    "docstring": "Gathers sha256 hashes from binary lists"
  },
  {
    "code": "def stage_import_from_url(self, url, token=None, username=None, password=None, insecure=False):\n        schema = ImportSchema()\n        resp = self.service.post(self.base,\n                                 params={'url': url, 'token': token, 'username': username, 'password': password, 'insecure': insecure})\n        return self.service.decode(schema, resp)",
    "docstring": "Stage an import from a URL to another CDRouter system.\n\n        :param url: URL to import as string.\n        :param token: (optional) API token to use as string (may be required if importing from a CDRouter 10+ system).\n        :param username: (optional) API username to use as string (may be required if importing from a CDRouter 10+ system).\n        :param password: (optional) API password to use as string (may be required if importing from a CDRouter 10+ system).\n        :param insecure: (optional) Allow insecure HTTPS connections if bool `True`.\n        :return: :class:`imports.Import <imports.Import>` object"
  },
  {
    "code": "def tabulate(collection, headers, datetime_fmt='%Y-%m-%d %H:%M:%S', **kwargs):\n    if isinstance(headers, dict):\n        attrs = headers.keys()\n        names = [\n            key if value is None else value for key, value in headers.items()\n        ]\n    else:\n        attrs = names = headers\n    table = [(\n        format_cell(cell, datetime_fmt=datetime_fmt)\n        for cell in attrgetter(*attrs)(c)\n    ) for c in collection]\n    return tblte(table, headers=[h.upper() for h in names], **kwargs)",
    "docstring": "Pretty-print a collection."
  },
  {
    "code": "def get_settings(self, using=None, **kwargs):\n        return self._get_connection(using).indices.get_settings(index=self._name, **kwargs)",
    "docstring": "Retrieve settings for the index.\n\n        Any additional keyword arguments will be passed to\n        ``Elasticsearch.indices.get_settings`` unchanged."
  },
  {
    "code": "def read_stack_data(self, size = 128, offset = 0):\n        aProcess = self.get_process()\n        return aProcess.read(self.get_sp() + offset, size)",
    "docstring": "Reads the contents of the top of the stack.\n\n        @type  size: int\n        @param size: Number of bytes to read.\n\n        @type  offset: int\n        @param offset: Offset from the stack pointer to begin reading.\n\n        @rtype:  str\n        @return: Stack data.\n\n        @raise WindowsError: Could not read the requested data."
  },
  {
    "code": "def start(self):\n        if self.num_workers:\n            self.queue = Queue(maxsize=self.num_workers)\n            self.workers = [_Worker(self) for _ in range(self.num_workers)]\n            for worker in self.workers:\n                worker.start()\n        self.running = True",
    "docstring": "Start the workers."
  },
  {
    "code": "def find_version(file_path):\n    with open(file_path, 'r') as f:\n        file_contents = f.read()\n    version_match = re.search(r\"^__version__\\s*=\\s*['\\\"]([^'\\\"]*)['\\\"]\",\n                              file_contents, re.M)\n    if version_match:\n        return version_match.group(1)\n    else:\n        raise RuntimeError(\"unable to find version string\")",
    "docstring": "Scrape version information from specified file path."
  },
  {
    "code": "def clean_for_doc(nb):\n    new_cells = []\n    for cell in nb.worksheets[0].cells:\n        if \"input\" in cell and cell[\"input\"].strip() == \"%pylab inline\":\n            continue\n        if \"outputs\" in cell:\n            outputs = [_i for _i in cell[\"outputs\"] if \"text\" not in _i or\n                       not _i[\"text\"].startswith(\"<obspy.core\")]\n            cell[\"outputs\"] = outputs\n        new_cells.append(cell)\n    nb.worksheets[0].cells = new_cells\n    return nb",
    "docstring": "Cleans the notebook to be suitable for inclusion in the docs."
  },
  {
    "code": "def from_callback(cls, cb, transf_cbs, nx, nparams=0, pre_adj=None,\n                      **kwargs):\n        be = Backend(kwargs.pop('backend', None))\n        x = be.real_symarray('x', nx)\n        p = be.real_symarray('p', nparams)\n        try:\n            transf = [(transf_cbs[idx][0](xi),\n                       transf_cbs[idx][1](xi))\n                      for idx, xi in enumerate(x)]\n        except TypeError:\n            transf = zip(_map2(transf_cbs[0], x), _map2(transf_cbs[1], x))\n        try:\n            exprs = cb(x, p, be)\n        except TypeError:\n            exprs = _ensure_3args(cb)(x, p, be)\n        return cls(x, _map2l(pre_adj, exprs), transf, p, backend=be, **kwargs)",
    "docstring": "Generate a TransformedSys instance from a callback\n\n        Parameters\n        ----------\n        cb : callable\n            Should have the signature ``cb(x, p, backend) -> list of exprs``.\n            The callback ``cb`` should return *untransformed* expressions.\n        transf_cbs : pair or iterable of pairs of callables\n            Callables for forward- and backward-transformations. Each\n            callable should take a single parameter (expression) and\n            return a single expression.\n        nx : int\n            Number of unkowns.\n        nparams : int\n            Number of parameters.\n        pre_adj : callable, optional\n            To tweak expression prior to transformation. Takes a\n            sinlge argument (expression) and return a single argument\n            rewritten expression.\n        \\\\*\\\\*kwargs :\n            Keyword arguments passed on to :class:`TransformedSys`. See also\n            :class:`SymbolicSys` and :class:`pyneqsys.NeqSys`.\n\n        Examples\n        --------\n        >>> import sympy as sp\n        >>> transformed = TransformedSys.from_callback(lambda x, p, be: [\n        ...     x[0]*x[1] - p[0],\n        ...     be.exp(-x[0]) + be.exp(-x[1]) - p[0]**-2\n        ... ], (sp.log, sp.exp), 2, 1)\n        ..."
  },
  {
    "code": "def remote_call(request, cls, method, args, kw):\n    actor = request.actor\n    name = 'remote_%s' % cls.__name__\n    if not hasattr(actor, name):\n        object = cls(actor)\n        setattr(actor, name, object)\n    else:\n        object = getattr(actor, name)\n    method_name = '%s%s' % (PREFIX, method)\n    return getattr(object, method_name)(request, *args, **kw)",
    "docstring": "Command for executing remote calls on a remote object"
  },
  {
    "code": "def _set_transmaps(self):\n        if self._std == 'ascii':\n            self._lower_chars = string.ascii_lowercase\n            self._upper_chars = string.ascii_uppercase\n        elif self._std == 'rfc1459':\n            self._lower_chars = (string.ascii_lowercase +\n                                 ''.join(chr(i) for i in range(123, 127)))\n            self._upper_chars = (string.ascii_uppercase +\n                                 ''.join(chr(i) for i in range(91, 95)))\n        elif self._std == 'rfc1459-strict':\n            self._lower_chars = (string.ascii_lowercase +\n                                 ''.join(chr(i) for i in range(123, 126)))\n            self._upper_chars = (string.ascii_uppercase +\n                                 ''.join(chr(i) for i in range(91, 94)))",
    "docstring": "Set translation maps for our standard."
  },
  {
    "code": "def ask_float(msg=\"Enter a float\", dft=None, vld=None, hlp=None):\n    vld = vld or [float]\n    return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp)",
    "docstring": "Prompts the user for a float."
  },
  {
    "code": "def get_roles(self, groups):\n        roles = set([])\n        parentroles = set([])\n        notroles = set([])\n        tmp = set([])\n        usedgroups = {}\n        unusedgroups = {}\n        ret = {}\n        for role in self.roles:\n            if self._check_member(\n                    role, groups, notroles,\n                    tmp, parentroles, usedgroups):\n                roles.add(role)\n        for b in groups:\n            for g in groups[b]:\n                if b not in usedgroups or g not in usedgroups[b]:\n                    if b not in unusedgroups:\n                        unusedgroups[b] = set([])\n                    unusedgroups[b].add(g)\n        ret['roles'] = roles\n        ret['unusedgroups'] = unusedgroups\n        return ret",
    "docstring": "get list of roles and list of standalone groups"
  },
  {
    "code": "def has_field(cls, field_name):\n        if super(ModelWithDynamicFieldMixin, cls).has_field(field_name):\n            return True\n        try:\n            cls._get_dynamic_field_for(field_name)\n        except ValueError:\n            return False\n        else:\n            return True",
    "docstring": "Check if the current class has a field with the name \"field_name\"\n        Add management of dynamic fields, to return True if the name matches an\n        existing dynamic field without existing copy for this name."
  },
  {
    "code": "def update_probs(self):\n        syst_error = 0.05\n        prior_probs = {'syst': {}, 'rand': {}}\n        for source, (p, n) in self.prior_counts.items():\n            if n + p == 0:\n                continue\n            prior_probs['syst'][source] = syst_error\n            prior_probs['rand'][source] = \\\n                1 - min((float(p) / (n + p), 1-syst_error)) - syst_error\n        subtype_probs = {}\n        for source, entry in self.subtype_counts.items():\n            for rule, (p, n) in entry.items():\n                if n + p == 0:\n                    continue\n                if source not in subtype_probs:\n                    subtype_probs[source] = {}\n                subtype_probs[source][rule] = \\\n                    1 - min((float(p) / (n + p), 1-syst_error)) - syst_error\n        super(BayesianScorer, self).update_probs(prior_probs, subtype_probs)",
    "docstring": "Update the internal probability values given the counts."
  },
  {
    "code": "def calculate_up_moves(high_data):\n    up_moves = [high_data[idx] - high_data[idx-1] for idx in range(1, len(high_data))]\n    return [np.nan] + up_moves",
    "docstring": "Up Move.\n\n    Formula:\n    UPMOVE = Ht - Ht-1"
  },
  {
    "code": "def remove_root_gradebook(self, gradebook_id):\n        if self._catalog_session is not None:\n            return self._catalog_session.remove_root_catalog(catalog_id=gradebook_id)\n        return self._hierarchy_session.remove_root(id_=gradebook_id)",
    "docstring": "Removes a root gradebook.\n\n        arg:    gradebook_id (osid.id.Id): the ``Id`` of a gradebook\n        raise:  NotFound - ``gradebook_id`` is not a root\n        raise:  NullArgument - ``gradebook_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _clear_strobes(self):\n        self['SEQ']['GLOBAL_SHIFT_EN'].setall(False)\n        self['SEQ']['GLOBAL_CTR_LD'].setall(False)\n        self['SEQ']['GLOBAL_DAC_LD'].setall(False)\n        self['SEQ']['PIXEL_SHIFT_EN'].setall(False)\n        self['SEQ']['INJECTION'].setall(False)",
    "docstring": "Resets the \"enable\" and \"load\" output streams to all 0."
  },
  {
    "code": "def undeployed(name,\n               url='http://localhost:8080/manager',\n               timeout=180):\n    ret = {'name': name,\n           'result': True,\n           'changes': {},\n           'comment': ''}\n    if not __salt__['tomcat.status'](url, timeout):\n        ret['comment'] = 'Tomcat Manager does not respond'\n        ret['result'] = False\n        return ret\n    try:\n        version = __salt__['tomcat.ls'](url, timeout)[name]['version']\n        ret['changes'] = {'undeploy': version}\n    except KeyError:\n        return ret\n    if __opts__['test']:\n        ret['result'] = None\n        return ret\n    undeploy = __salt__['tomcat.undeploy'](name, url, timeout=timeout)\n    if undeploy.startswith('FAIL'):\n        ret['result'] = False\n        ret['comment'] = undeploy\n        return ret\n    return ret",
    "docstring": "Enforce that the WAR will be undeployed from the server\n\n    name\n        The context path to undeploy.\n    url : http://localhost:8080/manager\n        The URL of the server with the Tomcat Manager webapp.\n    timeout : 180\n        Timeout for HTTP request to the Tomcat Manager.\n\n    Example:\n\n    .. code-block:: yaml\n\n        jenkins:\n          tomcat.undeployed:\n            - name: /ran\n            - require:\n              - service: application-service"
  },
  {
    "code": "def _build_indices(self):\n        result = {key: OrderedDict() for key in LINES_WITH_ID}\n        for line in self.lines:\n            if line.key in LINES_WITH_ID:\n                result.setdefault(line.key, OrderedDict())\n                if line.mapping[\"ID\"] in result[line.key]:\n                    warnings.warn(\n                        (\"Seen {} header more than once: {}, using first\" \"occurence\").format(\n                            line.key, line.mapping[\"ID\"]\n                        ),\n                        DuplicateHeaderLineWarning,\n                    )\n                else:\n                    result[line.key][line.mapping[\"ID\"]] = line\n            else:\n                result.setdefault(line.key, [])\n                result[line.key].append(line)\n        return result",
    "docstring": "Build indices for the different field types"
  },
  {
    "code": "def _prep_binary_content(self):\n\t\tif not self.data and not self.location and 'Content-Location' not in self.resource.headers.keys():\n\t\t\traise Exception('creating/updating NonRDFSource requires content from self.binary.data, self.binary.location, or the Content-Location header')\n\t\telif 'Content-Location' in self.resource.headers.keys():\n\t\t\tlogger.debug('Content-Location header found, using')\n\t\t\tself.delivery = 'header'\n\t\telif 'Content-Location' not in self.resource.headers.keys():\n\t\t\tif self.location:\n\t\t\t\tself.resource.headers['Content-Location'] = self.location\n\t\t\t\tself.delivery = 'header'\n\t\t\telif self.data:\n\t\t\t\tif isinstance(self.data, io.BufferedIOBase):\n\t\t\t\t\tlogger.debug('detected file-like object')\n\t\t\t\t\tself.delivery = 'payload'\n\t\t\t\telse:\n\t\t\t\t\tlogger.debug('detected bytes')\n\t\t\t\t\tself.delivery = 'payload'",
    "docstring": "Sets delivery method of either payload or header\n\t\tFavors Content-Location header if set\n\n\t\tArgs:\n\t\t\tNone\n\n\t\tReturns:\n\t\t\tNone: sets attributes in self.binary and headers"
  },
  {
    "code": "def _clear_ignore(endpoint_props):\n    return dict(\n        (prop_name, prop_val)\n        for prop_name, prop_val in six.iteritems(endpoint_props)\n        if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None\n    )",
    "docstring": "Both _clear_dict and _ignore_keys in a single iteration."
  },
  {
    "code": "def uuid(self):\n        self.open()\n        uuid = lvm_vg_get_uuid(self.handle)\n        self.close()\n        return uuid",
    "docstring": "Returns the volume group uuid."
  },
  {
    "code": "def run_muse(job, tumor_bam, normal_bam, univ_options, muse_options):\n    if muse_options['chromosomes']:\n        chromosomes = muse_options['chromosomes']\n    else:\n        chromosomes = sample_chromosomes(job, muse_options['genome_fai'])\n    perchrom_muse = defaultdict()\n    for chrom in chromosomes:\n        call = job.addChildJobFn(run_muse_perchrom, tumor_bam, normal_bam, univ_options,\n                                 muse_options, chrom, disk=PromisedRequirement(\n                                     muse_disk,\n                                     tumor_bam['tumor_dna_fix_pg_sorted.bam'],\n                                     normal_bam['normal_dna_fix_pg_sorted.bam'],\n                                     muse_options['genome_fasta']),\n                                 memory='6G')\n        sump = call.addChildJobFn(run_muse_sump_perchrom, call.rv(), univ_options, muse_options,\n                                  chrom,\n                                  disk=PromisedRequirement(muse_sump_disk,\n                                                           muse_options['dbsnp_vcf']),\n                                  memory='6G')\n        perchrom_muse[chrom] = sump.rv()\n    return perchrom_muse",
    "docstring": "Spawn a MuSE job for each chromosome on the DNA bams.\n\n    :param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq\n    :param dict normal_bam: Dict of bam and bai for normal DNA-Seq\n    :param dict univ_options: Dict of universal options used by almost all tools\n    :param dict muse_options: Options specific to MuSE\n    :return: Dict of results from running MuSE on every chromosome\n             perchrom_muse:\n                 |- 'chr1': fsID\n                 |- 'chr2' fsID\n                 |\n                 |-...\n                 |\n                 +- 'chrM': fsID\n    :rtype: dict"
  },
  {
    "code": "def eventFilter(self, obj, event):\r\n        if obj == self.dataTable and event.type() == QEvent.Resize:\r\n            self._resizeVisibleColumnsToContents()\r\n        return False",
    "docstring": "Override eventFilter to catch resize event."
  },
  {
    "code": "def get_candidate_votes(self, candidate):\n        candidate_election = CandidateElection.objects.get(\n            candidate=candidate, election=self\n        )\n        return candidate_election.votes.all()",
    "docstring": "Get all votes attached to a CandidateElection for a Candidate in\n        this election."
  },
  {
    "code": "def optlist_to_dict(optlist, opt_sep=',', kv_sep='=', strip_quotes=False):\n    def make_kv(opt):\n        if kv_sep is not None and kv_sep in opt:\n            k, v = opt.split(kv_sep, 1)\n            k = k.strip()\n            if strip_quotes and v[0] in ('\"', \"'\") and v[-1] == v[0]:\n                return k, v[1:-1]\n            else:\n                return k, v\n        else:\n            return opt, True\n    return dict(make_kv(opt) for opt in optlist.split(opt_sep))",
    "docstring": "Parse an option list into a dictionary.\n\n    Takes a list of options separated by ``opt_sep`` and places them into\n    a dictionary with the default value of ``True``.  If ``kv_sep`` option\n    is specified then key/value options ``key=value`` are parsed.  Useful\n    for parsing options such as mount options in the format\n    ``rw,ro,rsize=32168,xyz``.\n\n    Parameters:\n        optlist (str): String of options to parse.\n        opt_sep (str): Separater used to split options.\n        kv_sep (str): If not `None` then `optlist` includes key=value pairs\n            to be split, and this str is used to split them.\n        strip_quotes (bool): If set, will remove matching '\"' and '\"'\n            characters from start and end of line.  No quotes are removed\n            from inside the string and mismatched quotes are not removed.\n\n    Returns:\n        dict: Returns a dictionary of names present in the list.  If `kv_sep`\n        is not `None` then the values will be the str on the right-hand side\n        of `kv_sep`.  If `kv_sep` is `None` then each key will have a default\n        value of `True`.\n\n    Examples:\n        >>> optlist = 'rw,ro,rsize=32168,xyz'\n        >>> optlist_to_dict(optlist)\n        {'rw': True, 'ro': True, 'rsize': '32168', 'xyz': True}"
  },
  {
    "code": "def set(self, uuid, content, encoding=\"utf-8\"):\n        dest = self.abs_path(uuid)\n        if not dest.parent.exists():\n            dest.parent.mkdir(0o775, parents=True)\n        if hasattr(content, \"read\"):\n            content = content.read()\n        mode = \"tw\"\n        if not isinstance(content, str):\n            mode = \"bw\"\n            encoding = None\n        with dest.open(mode, encoding=encoding) as f:\n            f.write(content)",
    "docstring": "Store binary content with uuid as key.\n\n        :param:uuid: :class:`UUID` instance\n        :param:content: string, bytes, or any object with a `read()` method\n        :param:encoding: encoding to use when content is Unicode"
  },
  {
    "code": "def get_url(field):\n    hydrated_path = _get_hydrated_path(field)\n    base_url = getattr(settings, 'RESOLWE_HOST_URL', 'localhost')\n    return \"{}/data/{}/{}\".format(base_url, hydrated_path.data_id, hydrated_path.file_name)",
    "docstring": "Return file's url based on base url set in settings."
  },
  {
    "code": "def available(self):\n        if not self._schema:\n            return set()\n        avail = set(self._schema.__vers_downgraders__.keys())\n        avail.add(self._schema.__version__)\n        return avail",
    "docstring": "Returns a set of the available versions.\n\n        :returns: A set of integers giving the available versions."
  },
  {
    "code": "def load_subclasses(klass, modules=None):\n    if modules:\n        if isinstance(modules, six.string_types):\n            modules = [modules]\n        loader = Loader()\n        loader.load(*modules)\n    return klass.__subclasses__()",
    "docstring": "Load recursively all all subclasses from a module.\n\n    Args:\n        klass (str or list of str): Class whose subclasses we want to load.\n        modules: List of additional modules or module names that should be\n            recursively imported in order to find all the subclasses of the\n            desired class. Default: None\n\n    FIXME: This function is kept only for backward compatibility reasons, it\n        should not be used. Deprecation warning should be raised and it should\n        be replaces by the ``Loader`` class."
  },
  {
    "code": "def _handle_job_without_successors(self, job, irsb, insn_addrs):\n        ins_addr = job.addr\n        for stmt_idx, stmt in enumerate(irsb.statements):\n            if type(stmt) is pyvex.IRStmt.IMark:\n                ins_addr = stmt.addr + stmt.delta\n            elif type(stmt) is pyvex.IRStmt.Exit:\n                successor_jumpkind = stmt.jk\n                self._update_function_transition_graph(\n                    job.block_id, None,\n                    jumpkind = successor_jumpkind,\n                    ins_addr=ins_addr,\n                    stmt_idx=stmt_idx,\n                )\n        successor_jumpkind = irsb.jumpkind\n        successor_last_ins_addr = insn_addrs[-1]\n        self._update_function_transition_graph(job.block_id, None,\n                                               jumpkind=successor_jumpkind,\n                                               ins_addr=successor_last_ins_addr,\n                                               stmt_idx=DEFAULT_STATEMENT,\n                                               )",
    "docstring": "A block without successors should still be handled so it can be added to the function graph correctly.\n\n        :param CFGJob job:  The current job that do not have any successor.\n        :param IRSB irsb:   The related IRSB.\n        :param insn_addrs:  A list of instruction addresses of this IRSB.\n        :return: None"
  },
  {
    "code": "def equals(self, data):\n        if isinstance(data, six.string_types):\n            return self._add_condition('=', data, types=[int, str])\n        elif isinstance(data, list):\n            return self._add_condition('IN', \",\".join(map(str, data)), types=[str])\n        raise QueryTypeError('Expected value of type `str` or `list`, not %s' % type(data))",
    "docstring": "Adds new `IN` or `=` condition depending on if a list or string was provided\n\n        :param data: string or list of values\n        :raise:\n            - QueryTypeError: if `data` is of an unexpected type"
  },
  {
    "code": "def column_list(tables, columns):\n    columns = set(columns)\n    foundcols = tz.reduce(lambda x, y: x.union(y), (set(t.columns) for t in tables))\n    return list(columns.intersection(foundcols))",
    "docstring": "Take a list of tables and a list of column names and return the columns\n    that are present in the tables.\n\n    Parameters\n    ----------\n    tables : sequence of _DataFrameWrapper or _TableFuncWrapper\n        Could also be sequence of modified pandas.DataFrames, the important\n        thing is that they have ``.name`` and ``.columns`` attributes.\n    columns : sequence of str\n        The column names of interest.\n\n    Returns\n    -------\n    cols : list\n        Lists of column names available in the tables."
  },
  {
    "code": "def _get_host_libc_from_host_compiler(self):\n    compiler_exe = self.get_options().host_compiler\n    library_dirs = self._parse_search_dirs.get_compiler_library_dirs(compiler_exe)\n    libc_crti_object_file = None\n    for libc_dir_candidate in library_dirs:\n      maybe_libc_crti = os.path.join(libc_dir_candidate, self._LIBC_INIT_OBJECT_FILE)\n      if os.path.isfile(maybe_libc_crti):\n        libc_crti_object_file = maybe_libc_crti\n        break\n    if not libc_crti_object_file:\n      raise self.HostLibcDevResolutionError(\n        \"Could not locate {fname} in library search dirs {dirs} from compiler: {compiler!r}. \"\n        \"You may need to install a libc dev package for the current system. \"\n        \"For many operating systems, this package is named 'libc-dev' or 'libc6-dev'.\"\n        .format(fname=self._LIBC_INIT_OBJECT_FILE, dirs=library_dirs, compiler=compiler_exe))\n    return HostLibcDev(crti_object=libc_crti_object_file,\n                       fingerprint=hash_file(libc_crti_object_file))",
    "docstring": "Locate the host's libc-dev installation using a specified host compiler's search dirs."
  },
  {
    "code": "def _parse_blkio_metrics(self, stats):\n        metrics = {\n            'io_read': 0,\n            'io_write': 0,\n        }\n        for line in stats:\n            if 'Read' in line:\n                metrics['io_read'] += int(line.split()[2])\n            if 'Write' in line:\n                metrics['io_write'] += int(line.split()[2])\n        return metrics",
    "docstring": "Parse the blkio metrics."
  },
  {
    "code": "def _input_as_paths(self, data):\n        return self._command_delimiter.join(\n            map(str, map(self._input_as_path, data)))",
    "docstring": "Return data as a space delimited string with each path quoted\n\n            data: paths or filenames, most likely as a list of\n             strings"
  },
  {
    "code": "def ang_veltoaxisangledot(angle, axis, Omega):\n    angle_dot = axis.dot(Omega)\n    axis_dot = 1/2*(hat_map(axis) - 1/np.tan(angle/2) * hat_map(axis).dot(hat_map(axis))).dot(Omega)\n    return angle_dot, axis_dot",
    "docstring": "Compute kinematics for axis angle representation"
  },
  {
    "code": "def finish(self, chunk=None):\n        self._log_disconnect()\n        super(BaseHandler, self).finish(chunk)",
    "docstring": "Tornado `finish` handler"
  },
  {
    "code": "def child_cardinality(self, child):\n        for prop, klassdef in self.c_children.values():\n            if child == prop:\n                if isinstance(klassdef, list):\n                    try:\n                        _min = self.c_cardinality[\"min\"]\n                    except KeyError:\n                        _min = 1\n                    try:\n                        _max = self.c_cardinality[\"max\"]\n                    except KeyError:\n                        _max = \"unbounded\"\n                    return _min, _max\n                else:\n                    return 1, 1\n        return None",
    "docstring": "Return the cardinality of a child element\n\n        :param child: The name of the child element\n        :return: The cardinality as a 2-tuple (min, max).\n            The max value is either a number or the string \"unbounded\".\n            The min value is always a number."
  },
  {
    "code": "def dev():\r\n    env.roledefs = {\r\n        'web': ['192.168.1.2'],\r\n        'lb': ['192.168.1.2'],\r\n    }\r\n    env.user = 'vagrant'\r\n    env.backends = env.roledefs['web']\r\n    env.server_name = 'django_search_model-dev.net'\r\n    env.short_server_name = 'django_search_model-dev'\r\n    env.static_folder = '/site_media/'\r\n    env.server_ip = '192.168.1.2'\r\n    env.no_shared_sessions = False\r\n    env.server_ssl_on = False\r\n    env.goal = 'dev'\r\n    env.socket_port = '8001'\r\n    env.map_settings = {}\r\n    execute(build_env)",
    "docstring": "Define dev stage"
  },
  {
    "code": "def merged_with(self, provider, requirement, parent):\n        infos = list(self.information)\n        infos.append(RequirementInformation(requirement, parent))\n        candidates = [\n            c for c in self.candidates\n            if provider.is_satisfied_by(requirement, c)\n        ]\n        if not candidates:\n            raise RequirementsConflicted(self)\n        return type(self)(candidates, infos)",
    "docstring": "Build a new instance from this and a new requirement."
  },
  {
    "code": "def _evaluate(dataset, predictions):\n    f1_result = exact_match = total = 0\n    count = 0\n    for article in dataset:\n        for paragraph in article['paragraphs']:\n            for qa_pair in paragraph['qas']:\n                total += 1\n                if qa_pair['id'] not in predictions:\n                    count += 1\n                    continue\n                ground_truths = list(map(lambda x: x['text'], qa_pair['answers']))\n                prediction = predictions[qa_pair['id']]\n                exact_match += metric_max_over_ground_truths(\n                    exact_match_score, prediction, ground_truths)\n                f1_result += metric_max_over_ground_truths(\n                    f1_score, prediction, ground_truths)\n    print('total', total, 'exact_match', exact_match, 'unanswer_question ', count)\n    exact_match = 100.0 * exact_match / total\n    f1_result = 100.0 * f1_result / total\n    return {'exact_match': exact_match, 'f1': f1_result}",
    "docstring": "Evaluate function."
  },
  {
    "code": "def submitter(self, f):\n        f = self._wrap_coro_function_with_sem(f)\n        @wraps(f)\n        def wrapped(*args, **kwargs):\n            return self.submit(f(*args, **kwargs))\n        return wrapped",
    "docstring": "Decorator to submit a coro-function as NewTask to self.loop with sem control.\n        Use default_callback frequency of loop."
  },
  {
    "code": "def qpop_back(self, name, size=1):\n        size = get_positive_integer(\"size\", size)\n        return self.execute_command('qpop_back', name, size)",
    "docstring": "Remove and return the last ``size`` item of the list ``name``\n\n        Like **Redis.RPOP**\n\n        :param string name: the queue name\n        :param int size: the length of result\n        :return: the list of pop elements\n        :rtype: list"
  },
  {
    "code": "def _extract_query(self, redirect_url):\n        qs = urlparse(redirect_url)\n        qs = qs.fragment if isinstance(self, ImplicitGrant) else qs.query\n        query_params = parse_qs(qs)\n        query_params = {qp: query_params[qp][0] for qp in query_params}\n        return query_params",
    "docstring": "Extract query parameters from a url.\n\n        Parameters\n            redirect_url (str)\n                The full URL that the Uber server redirected to after\n                the user authorized your app.\n\n        Returns\n            (dict)\n                A dictionary of query parameters."
  },
  {
    "code": "def prune(self):\n        LOG.info('Pruning extra files from scenario ephemeral directory')\n        safe_files = [\n            self.config.provisioner.config_file,\n            self.config.provisioner.inventory_file,\n            self.config.state.state_file,\n        ] + self.config.driver.safe_files\n        files = util.os_walk(self.ephemeral_directory, '*')\n        for f in files:\n            if not any(sf for sf in safe_files if fnmatch.fnmatch(f, sf)):\n                os.remove(f)\n        for dirpath, dirs, files in os.walk(\n                self.ephemeral_directory, topdown=False):\n            if not dirs and not files:\n                os.removedirs(dirpath)",
    "docstring": "Prune the scenario ephemeral directory files and returns None.\n\n        \"safe files\" will not be pruned, including the ansible configuration\n        and inventory used by this scenario, the scenario state file, and\n        files declared as \"safe_files\" in the ``driver`` configuration\n        declared in ``molecule.yml``.\n\n        :return: None"
  },
  {
    "code": "def mock_lockfile_update(path):\n    updated_lockfile_contents = {\n        'package1': '1.2.0'\n    }\n    with open(path, 'w+') as f:\n        f.write(json.dumps(updated_lockfile_contents, indent=4))\n    return updated_lockfile_contents",
    "docstring": "This is a mock update. In place of this, you might simply shell out\n    to a command like `yarn upgrade`."
  },
  {
    "code": "def list_folders(kwargs=None, call=None):\n    if call != 'function':\n        raise SaltCloudSystemExit(\n            'The list_folders function must be called with '\n            '-f or --function.'\n        )\n    return {'Folders': salt.utils.vmware.list_folders(_get_si())}",
    "docstring": "List all the folders for this VMware environment\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -f list_folders my-vmware-config"
  },
  {
    "code": "def requires_app_credentials(func):\n    @wraps(func)\n    def auth_wrapper(self, *args, **kwargs):\n        client_id, client_secret = self._session.retrieve_client_credentials()\n        if client_id and client_secret:\n            return func(self, *args, **kwargs)\n        else:\n            from .models import GitHubError\n            r = generate_fake_error_response(\n                '{\"message\": \"Requires username/password authentication\"}'\n            )\n            raise GitHubError(r)\n    return auth_wrapper",
    "docstring": "Require client_id and client_secret to be associated.\n\n    This is used to note and enforce which methods require a client_id and\n    client_secret to be used."
  },
  {
    "code": "def _do_download(version, download_base, to_dir, download_delay):\n    py_desig = 'py{sys.version_info[0]}.{sys.version_info[1]}'.format(sys=sys)\n    tp = 'setuptools-{version}-{py_desig}.egg'\n    egg = os.path.join(to_dir, tp.format(**locals()))\n    if not os.path.exists(egg):\n        archive = download_setuptools(version, download_base,\n            to_dir, download_delay)\n        _build_egg(egg, archive, to_dir)\n    sys.path.insert(0, egg)\n    if 'pkg_resources' in sys.modules:\n        _unload_pkg_resources()\n    import setuptools\n    setuptools.bootstrap_install_from = egg",
    "docstring": "Download Setuptools."
  },
  {
    "code": "def stop(self):\n        log.debug(\"Stopping periodic task\")\n        stopframe = build_bcm_tx_delete_header(self.can_id_with_flags, self.flags)\n        send_bcm(self.bcm_socket, stopframe)",
    "docstring": "Send a TX_DELETE message to cancel this task.\n\n        This will delete the entry for the transmission of the CAN-message\n        with the specified can_id CAN identifier. The message length for the command\n        TX_DELETE is {[bcm_msg_head]} (only the header)."
  },
  {
    "code": "def layer(command=None, *args):\n    'hints the start of a new layer'\n    if not command:\n        return eval([['hint', 'layer']])\n    else:\n        lst = [['layer']]\n        for arg in args:\n            lst.append([command, arg])\n            lst.append(['layer'])\n        return eval(lst)",
    "docstring": "hints the start of a new layer"
  },
  {
    "code": "def __build_cmd_maps(cls):\n        cmd_map_all = {}\n        cmd_map_visible = {}\n        cmd_map_internal = {}\n        for name in dir(cls):\n            obj = getattr(cls, name)\n            if iscommand(obj):\n                for cmd in getcommands(obj):\n                    if cmd in cmd_map_all.keys():\n                        raise PyShellError(\"The command '{}' already has cmd\"\n                                           \" method '{}', cannot register a\"\n                                           \" second method '{}'.\".format( \\\n                                                    cmd, cmd_map_all[cmd], obj.__name__))\n                    cmd_map_all[cmd] = obj.__name__\n                    if isvisiblecommand(obj):\n                        cmd_map_visible[cmd] = obj.__name__\n                    if isinternalcommand(obj):\n                        cmd_map_internal[cmd] = obj.__name__\n        return cmd_map_all, cmd_map_visible, cmd_map_internal",
    "docstring": "Build the mapping from command names to method names.\n\n        One command name maps to at most one method.\n        Multiple command names can map to the same method.\n\n        Only used by __init__() to initialize self._cmd_map. MUST NOT be used\n        elsewhere.\n\n        Returns:\n            A tuple (cmd_map, hidden_cmd_map, internal_cmd_map)."
  },
  {
    "code": "def serve(content):\n    temp_folder = tempfile.gettempdir()\n    temp_file_name = tempfile.gettempprefix() + str(uuid.uuid4()) + \".html\"\n    temp_file_path = os.path.join(temp_folder, temp_file_name)\n    save(temp_file_path, content)\n    webbrowser.open(\"file://{}\".format(temp_file_path))\n    try:\n        while True:\n            time.sleep(1)\n    except KeyboardInterrupt:\n        os.remove(temp_file_path)",
    "docstring": "Write content to a temp file and serve it in browser"
  },
  {
    "code": "def convert_timespan(timespan):\n    start, end = timespan.split('-->')\n    start = convert_timestamp(start)\n    end = convert_timestamp(end)\n    return start, end",
    "docstring": "Convert an srt timespan into a start and end timestamp."
  },
  {
    "code": "def getPixels(self):\n        array = self.toArray()\n        (width, height, depth) = array.size\n        for x in range(width):\n            for y in range(height):\n                yield Pixel(array, x, y)",
    "docstring": "Return a stream of pixels from current Canvas."
  },
  {
    "code": "def validate(self, ymldata=None, messages=None):\n        schema_val = self.schema_val(messages)\n        if len(messages) == 0:\n            content_val = self.content_val(ymldata, messages)\n        return schema_val and content_val",
    "docstring": "Validates the Telemetry Dictionary definitions"
  },
  {
    "code": "def facts_refresh():\n    conn = __proxy__['junos.conn']()\n    ret = {}\n    ret['out'] = True\n    try:\n        conn.facts_refresh()\n    except Exception as exception:\n        ret['message'] = 'Execution failed due to \"{0}\"'.format(exception)\n        ret['out'] = False\n        return ret\n    ret['facts'] = __proxy__['junos.get_serialized_facts']()\n    try:\n        __salt__['saltutil.sync_grains']()\n    except Exception as exception:\n        log.error('Grains could not be updated due to \"%s\"', exception)\n    return ret",
    "docstring": "Reload the facts dictionary from the device. Usually only needed if,\n    the device configuration is changed by some other actor.\n    This function will also refresh the facts stored in the salt grains.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'device_name' junos.facts_refresh"
  },
  {
    "code": "def _periodic_callback(self):\n        try:\n            self.notify(self._state)\n        except Exception:\n            self._error_callback(*sys.exc_info())\n        if self._subscriptions:\n            self._call_later_handle = \\\n                self._loop.call_later(self._interval, self._periodic_callback)\n        else:\n            self._state = NONE\n            self._call_later_handle = None",
    "docstring": "Will be started on first emit"
  },
  {
    "code": "def send_and_wait(self, path, message, timeout=0, responder=None):\n        message.on(\"response\", lambda x,event_origin,source:None, once=True)\n        if timeout > 0:\n            ts = time.time()\n        else:\n            ts = 0\n        sent = False\n        while not message.response_received:\n            if not sent:\n                self.send(path, message)\n                sent = True\n            if ts:\n                if time.time() - ts > timeout:\n                    raise exceptions.TimeoutError(\"send_and_wait(%s)\"%path, timeout)\n        return message.response_message",
    "docstring": "Send a message and block until a response is received. Return response message"
  },
  {
    "code": "def as_sparse_array(self, kind=None, fill_value=None, copy=False):\n        if fill_value is None:\n            fill_value = self.fill_value\n        if kind is None:\n            kind = self.kind\n        return SparseArray(self.values, sparse_index=self.sp_index,\n                           fill_value=fill_value, kind=kind, copy=copy)",
    "docstring": "return my self as a sparse array, do not copy by default"
  },
  {
    "code": "def alignment_a(self):\n        from molmod.transformations import Rotation\n        new_x = self.matrix[:, 0].copy()\n        new_x /= np.linalg.norm(new_x)\n        new_z = np.cross(new_x, self.matrix[:, 1])\n        new_z /= np.linalg.norm(new_z)\n        new_y = np.cross(new_z, new_x)\n        new_y /= np.linalg.norm(new_y)\n        return Rotation(np.array([new_x, new_y, new_z]))",
    "docstring": "Computes the rotation matrix that aligns the unit cell with the\n           Cartesian axes, starting with cell vector a.\n\n           * a parallel to x\n           * b in xy-plane with b_y positive\n           * c with c_z positive"
  },
  {
    "code": "def on_controller_change(self, name, value):\n        if self.__controller != name:\n            return\n        self.__controller_on = value\n        if value:\n            self._register_service()\n        else:\n            self._unregister_service()",
    "docstring": "Called by the instance manager when a controller value has been\n        modified\n\n        :param name: The name of the controller\n        :param value: The new value of the controller"
  },
  {
    "code": "def activate(specifier):\n    try:\n        for distro in require(specifier):\n            distro.activate()\n    except (VersionConflict, DistributionNotFound):\n        raise RuntimeError('The installed version of pip is too old; peep '\n                           'requires ' + specifier)",
    "docstring": "Make a compatible version of pip importable. Raise a RuntimeError if we\n    couldn't."
  },
  {
    "code": "def _sum(ctx, *number):\n    if len(number) == 0:\n        raise ValueError(\"Wrong number of arguments\")\n    result = Decimal(0)\n    for arg in number:\n        result += conversions.to_decimal(arg, ctx)\n    return result",
    "docstring": "Returns the sum of all arguments"
  },
  {
    "code": "def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout,\n                        sep=',', ignored_columns=None, significance=None):\n    from_records = list(records.load(from_csv, sep=sep))\n    to_records = records.load(to_csv, sep=sep)\n    diff = patch.create(from_records, to_records, index_columns, ignored_columns)\n    if significance is not None:\n        diff = patch.filter_significance(diff, significance)\n    _summarize_diff(diff, len(from_records), stream=stream)\n    exit_code = (EXIT_SAME\n                 if patch.is_empty(diff)\n                 else EXIT_DIFFERENT)\n    sys.exit(exit_code)",
    "docstring": "Print a summary of the difference between the two files."
  },
  {
    "code": "def sum(vari, axis=None):\n    if isinstance(vari, Poly):\n        core = vari.A.copy()\n        for key in vari.keys:\n            core[key] = sum(core[key], axis)\n        return Poly(core, vari.dim, None, vari.dtype)\n    return np.sum(vari, axis)",
    "docstring": "Sum the components of a shapeable quantity along a given axis.\n\n    Args:\n        vari (chaospy.poly.base.Poly, numpy.ndarray):\n            Input data.\n        axis (int):\n            Axis over which the sum is taken. By default ``axis`` is None, and\n            all elements are summed.\n\n    Returns:\n        (chaospy.poly.base.Poly, numpy.ndarray):\n            Polynomial array with same shape as ``vari``, with the specified\n            axis removed. If ``vari`` is an 0-d array, or ``axis`` is None,\n            a (non-iterable) component is returned.\n\n    Examples:\n        >>> vari = cp.prange(3)\n        >>> print(vari)\n        [1, q0, q0^2]\n        >>> print(cp.sum(vari))\n        q0^2+q0+1"
  },
  {
    "code": "def _build_request(request):\n    msg = bytes([request['cmd']])\n    if 'dest' in request:\n        msg += bytes([request['dest']])\n    else:\n        msg += b'\\0'\n    if 'sha' in request:\n        msg += request['sha']\n    else:\n        for dummy in range(64):\n            msg += b'0'\n    logging.debug(\"Request (%d): %s\", len(msg), msg)\n    return msg",
    "docstring": "Build message to transfer over the socket from a request."
  },
  {
    "code": "def maybe_parse_user_type(t):\n    is_type = isinstance(t, type)\n    is_preserved = isinstance(t, type) and issubclass(t, _preserved_iterable_types)\n    is_string = isinstance(t, string_types)\n    is_iterable = isinstance(t, Iterable)\n    if is_preserved:\n        return [t]\n    elif is_string:\n        return [t]\n    elif is_type and not is_iterable:\n        return [t]\n    elif is_iterable:\n        ts = t\n        return tuple(e for t in ts for e in maybe_parse_user_type(t))\n    else:\n        raise TypeError(\n            'Type specifications must be types or strings. Input: {}'.format(t)\n        )",
    "docstring": "Try to coerce a user-supplied type directive into a list of types.\n\n    This function should be used in all places where a user specifies a type,\n    for consistency.\n\n    The policy for what defines valid user input should be clear from the implementation."
  },
  {
    "code": "def linear_trend_timewise(x, param):\n    ix = x.index\n    times_seconds = (ix - ix[0]).total_seconds()\n    times_hours = np.asarray(times_seconds / float(3600))\n    linReg = linregress(times_hours, x.values)\n    return [(\"attr_\\\"{}\\\"\".format(config[\"attr\"]), getattr(linReg, config[\"attr\"]))\n            for config in param]",
    "docstring": "Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to\n    length of the time series minus one.\n    This feature uses the index of the time series to fit the model, which must be of a datetime\n    dtype.\n    The parameters control which of the characteristics are returned.\n\n    Possible extracted attributes are \"pvalue\", \"rvalue\", \"intercept\", \"slope\", \"stderr\", see the documentation of\n    linregress for more information.\n\n    :param x: the time series to calculate the feature of. The index must be datetime.\n    :type x: pandas.Series\n    :param param: contains dictionaries {\"attr\": x} with x an string, the attribute name of the regression model\n    :type param: list\n    :return: the different feature values\n    :return type: list"
  },
  {
    "code": "def parameterSpace( self ):\n        ps = self.parameters()\n        if len(ps) == 0:\n            return []\n        else:\n            return self._crossProduct(ps)",
    "docstring": "Return the parameter space of the experiment as a list of dicts,\n        with each dict mapping each parameter name to a value.\n\n        :returns: the parameter space as a list of dicts"
  },
  {
    "code": "def confirm_lock(lockfile):\n    pidfile = open(lockfile, \"r\")\n    pidfile_pid = pidfile.readline().strip()\n    pidfile.close()\n    if int(pidfile_pid) != os.getpid():\n        raise RuntimeError, (\"pidfile %s contains pid %s; expected pid %s!\" %\n                             (lockfile, os.getpid(), pidfile_pid))\n    return True",
    "docstring": "Confirm that the given lockfile contains our pid.\n    Should be entirely unecessary, but paranoia always served me well."
  },
  {
    "code": "def _filters_pb(self):\n        num_filters = len(self._field_filters)\n        if num_filters == 0:\n            return None\n        elif num_filters == 1:\n            return _filter_pb(self._field_filters[0])\n        else:\n            composite_filter = query_pb2.StructuredQuery.CompositeFilter(\n                op=enums.StructuredQuery.CompositeFilter.Operator.AND,\n                filters=[_filter_pb(filter_) for filter_ in self._field_filters],\n            )\n            return query_pb2.StructuredQuery.Filter(composite_filter=composite_filter)",
    "docstring": "Convert all the filters into a single generic Filter protobuf.\n\n        This may be a lone field filter or unary filter, may be a composite\n        filter or may be :data:`None`.\n\n        Returns:\n            google.cloud.firestore_v1beta1.types.\\\n            StructuredQuery.Filter: A \"generic\" filter representing the\n            current query's filters."
  },
  {
    "code": "def _check_valid_version():\n    bower_version = _LooseVersion(\n        __salt__['cmd.run']('bower --version'))\n    valid_version = _LooseVersion('1.3')\n    if bower_version < valid_version:\n        raise CommandExecutionError(\n            '\\'bower\\' is not recent enough({0} < {1}). '\n            'Please Upgrade.'.format(\n                bower_version, valid_version\n            )\n        )",
    "docstring": "Check the version of Bower to ensure this module will work. Currently\n    bower must be at least version 1.3."
  },
  {
    "code": "def _fulfills_version_spec(version, version_spec):\n    for oper, spec in version_spec:\n        if oper is None:\n            continue\n        if not salt.utils.versions.compare(ver1=version, oper=oper, ver2=spec, cmp_func=_pep440_version_cmp):\n            return False\n    return True",
    "docstring": "Check version number against version specification info and return a\n    boolean value based on whether or not the version number meets the\n    specified version."
  },
  {
    "code": "def list_documents(self, page_size=None):\n        parent, _ = self._parent_info()\n        iterator = self._client._firestore_api.list_documents(\n            parent,\n            self.id,\n            page_size=page_size,\n            show_missing=True,\n            metadata=self._client._rpc_metadata,\n        )\n        iterator.collection = self\n        iterator.item_to_value = _item_to_document_ref\n        return iterator",
    "docstring": "List all subdocuments of the current collection.\n\n        Args:\n            page_size (Optional[int]]): The maximum number of documents\n            in each page of results from this request. Non-positive values\n            are ignored. Defaults to a sensible value set by the API.\n\n        Returns:\n            Sequence[~.firestore_v1beta1.collection.DocumentReference]:\n                iterator of subdocuments of the current collection. If the\n                collection does not exist at the time of `snapshot`, the\n                iterator will be empty"
  },
  {
    "code": "def varchar(self, field=None):\n        assert field is not None, \"The field parameter must be passed to the 'varchar' method.\"\n        max_length = field.max_length\n        def source():\n            length = random.choice(range(1, max_length + 1))\n            return \"\".join(random.choice(general_chars) for i in xrange(length))\n        return self.get_allowed_value(source, field)",
    "docstring": "Returns a chunk of text, of maximum length 'max_length'"
  },
  {
    "code": "def getMargin(self, name):\n        for margin in self._margins:\n            if margin.getName() == name:\n                return margin\n        return None",
    "docstring": "Provides the requested margin.\n           Returns a reference to the margin if found and None otherwise"
  },
  {
    "code": "def print_global_config(global_config):\n    if global_config.has_section('shell'):\n        print(\"\\nShell configurations:\")\n        for shell_type, set_value in global_config.items('shell'):\n            print(\"{0}: {1}\".format(shell_type, set_value))\n    if global_config.has_option('global', 'env_source_rc'):\n        print(\"\\nHave sprinter env source rc: {0}\".format(\n            global_config.get('global', 'env_source_rc')))",
    "docstring": "print the global configuration"
  },
  {
    "code": "def load(cli, yaml_filename):\n        with open(yaml_filename, 'rb') as filehandle:\n            for waybill in yaml.load(filehandle.read()):\n                cli.create(waybill.name,\n                           waybill.docker_id)",
    "docstring": "Creates waybill shims from a given yaml file definiations"
  },
  {
    "code": "def _writeFile(cls, filePath, content, encoding = None):\n        filePath = os.path.realpath(filePath)\n        log.debug(_(\"Real file path to write: %s\" % filePath))\n        if encoding is None:\n            encoding = File.DEFAULT_ENCODING\n        try:\n            encodedContent = ''.join(content).encode(encoding)\n        except LookupError as msg:\n            raise SubFileError(_(\"Unknown encoding name: '%s'.\") % encoding)\n        except UnicodeEncodeError:\n            raise SubFileError(\n                _(\"There are some characters in '%(file)s' that cannot be encoded to '%(enc)s'.\")\n                % {\"file\": filePath, \"enc\": encoding})\n        tmpFilePath = \"%s.tmp\" % filePath\n        bakFilePath = \"%s.bak\" % filePath\n        with open(tmpFilePath, 'wb') as f:\n            f.write(encodedContent)\n            f.flush()\n        try:\n            os.rename(filePath, bakFilePath)\n        except FileNotFoundError:\n            pass\n        os.rename(tmpFilePath, filePath)\n        try:\n            os.unlink(bakFilePath)\n        except FileNotFoundError:\n            pass",
    "docstring": "Safe file writing. Most common mistakes are checked against and reported before write\n        operation. After that, if anything unexpected happens, user won't be left without data or\n        with corrupted one as this method writes to a temporary file and then simply renames it\n        (which should be atomic operation according to POSIX but who knows how Ext4 really works.\n        @see: http://lwn.net/Articles/322823/)."
  },
  {
    "code": "def sa_indices(num_states, num_actions):\n    L = num_states * num_actions\n    dtype = np.int_\n    s_indices = np.empty(L, dtype=dtype)\n    a_indices = np.empty(L, dtype=dtype)\n    i = 0\n    for s in range(num_states):\n        for a in range(num_actions):\n            s_indices[i] = s\n            a_indices[i] = a\n            i += 1\n    return s_indices, a_indices",
    "docstring": "Generate `s_indices` and `a_indices` for `DiscreteDP`, for the case\n    where all the actions are feasible at every state.\n\n    Parameters\n    ----------\n    num_states : scalar(int)\n        Number of states.\n\n    num_actions : scalar(int)\n        Number of actions.\n\n    Returns\n    -------\n    s_indices : ndarray(int, ndim=1)\n        Array containing the state indices.\n\n    a_indices : ndarray(int, ndim=1)\n        Array containing the action indices.\n\n    Examples\n    --------\n    >>> s_indices, a_indices = qe.markov.sa_indices(4, 3)\n    >>> s_indices\n    array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3])\n    >>> a_indices\n    array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2])"
  },
  {
    "code": "def raster_binarization(given_value, rasterfilename):\n        origin_raster = RasterUtilClass.read_raster(rasterfilename)\n        binary_raster = numpy.where(origin_raster.data == given_value, 1, 0)\n        return binary_raster",
    "docstring": "Make the raster into binarization.\n\n        The opening and closing are based on binary image. Therefore we need to\n        make the raster into binarization.\n\n        Args:\n            given_value: The given value's pixels will be value in 1,\n            other pixels will be value in 0.\n            rasterfilename: The initial rasterfilena,e.\n\n        Returns:\n            binary_raster: Raster after binarization."
  },
  {
    "code": "def download_api(branch=None) -> str:\n    habitica_github_api = 'https://api.github.com/repos/HabitRPG/habitica'\n    if not branch:\n        branch = requests.get(habitica_github_api + '/releases/latest').json()['tag_name']\n    curl = local['curl']['-sL', habitica_github_api + '/tarball/{}'.format(branch)]\n    tar = local['tar'][\n        'axzf', '-', '--wildcards', '*/website/server/controllers/api-v3/*', '--to-stdout']\n    grep = local['grep']['@api']\n    sed = local['sed']['-e', 's/^[ */]*//g', '-e', 's/  / /g', '-']\n    return (curl | tar | grep | sed)()",
    "docstring": "download API documentation from _branch_ of Habitica\\'s repo on Github"
  },
  {
    "code": "def all_host_infos():\n    output = []\n    output.append([\"Operating system\", os()])\n    output.append([\"CPUID information\", cpu()])\n    output.append([\"CC information\", compiler()])\n    output.append([\"JDK information\", from_cmd(\"java -version\")])\n    output.append([\"MPI information\", from_cmd(\"mpirun -version\")])\n    output.append([\"Scala information\", from_cmd(\"scala -version\")])\n    output.append([\"OpenCL headers\", from_cmd(\n        \"find /usr/include|grep opencl.h\")])\n    output.append([\"OpenCL libraries\", from_cmd(\n        \"find /usr/lib/ -iname '*opencl*'\")])\n    output.append([\"NVidia SMI\", from_cmd(\"nvidia-smi -q\")])\n    output.append([\"OpenCL Details\", opencl()])\n    return output",
    "docstring": "Summarize all host information."
  },
  {
    "code": "def get_values(self, *args, **kwargs):\n        if isinstance(args[0], list):\n            raise ValueError(\"Can only get_values() for a single tag.\")\n        response = self.get_datapoints(*args, **kwargs)\n        for value in response['tags'][0]['results'][0]['values']:\n            yield [datetime.datetime.utcfromtimestamp(value[0]/1000),\n                   value[1],\n                   value[2]]",
    "docstring": "Convenience method that for simple single tag queries will\n        return just the values to be iterated on."
  },
  {
    "code": "def check_dipole(inp, name, verb):\n    r\n    _check_shape(np.squeeze(inp), name, (3,))\n    inp[0] = _check_var(inp[0], float, 1, name+'-x')\n    inp[1] = _check_var(inp[1], float, 1, name+'-y', inp[0].shape)\n    inp[2] = _check_var(inp[2], float, 1, name+'-z', (1,))\n    if verb > 2:\n        if name == 'src':\n            longname = '   Source(s)       : '\n        else:\n            longname = '   Receiver(s)     : '\n        print(longname, str(inp[0].size), 'dipole(s)')\n        tname = ['x  ', 'y  ', 'z  ']\n        for i in range(3):\n            text = \"     > \" + tname[i] + \"     [m] : \"\n            _prnt_min_max_val(inp[i], text, verb)\n    return inp, inp[0].size",
    "docstring": "r\"\"\"Check dipole parameters.\n\n    This check-function is called from one of the modelling routines in\n    :mod:`model`.  Consult these modelling routines for a detailed description\n    of the input parameters.\n\n    Parameters\n    ----------\n    inp : list of floats or arrays\n        Pole coordinates (m): [pole-x, pole-y, pole-z].\n\n    name : str, {'src', 'rec'}\n        Pole-type.\n\n    verb : {0, 1, 2, 3, 4}\n        Level of verbosity.\n\n    Returns\n    -------\n    inp : list\n        List of pole coordinates [x, y, z].\n\n    ninp : int\n        Number of inp-elements"
  },
  {
    "code": "def has_extensions(self, *exts):\n        file_ext = splitext(self.filename)[1]\n        file_ext = file_ext.lower()\n        for e in exts:\n            if file_ext == e:\n                return True\n        return False",
    "docstring": "Check if file has one of the extensions."
  },
  {
    "code": "def search_people_by_bio(query, limit_results=DEFAULT_LIMIT,\n                         index=['onename_people_index']):\n    from pyes import QueryStringQuery, ES\n    conn = ES()\n    q = QueryStringQuery(query,\n                         search_fields=['username', 'profile_bio'],\n                         default_operator='and')\n    results = conn.search(query=q, size=20, indices=index)\n    count = conn.count(query=q)\n    count = count.count\n    if(count == 0):\n        q = QueryStringQuery(query,\n                             search_fields=['username', 'profile_bio'],\n                             default_operator='or')\n        results = conn.search(query=q, size=20, indices=index)\n    results_list = []\n    counter = 0\n    for profile in results:\n        username = profile['username']\n        results_list.append(username)\n        counter += 1\n        if(counter == limit_results):\n            break\n    return results_list",
    "docstring": "queries lucene index to find a nearest match, output is profile username"
  },
  {
    "code": "def set_pattern_step_setpoint(self, patternnumber, stepnumber, setpointvalue):\n        _checkPatternNumber(patternnumber)\n        _checkStepNumber(stepnumber)\n        _checkSetpointValue(setpointvalue, self.setpoint_max)\n        address = _calculateRegisterAddress('setpoint', patternnumber, stepnumber)\n        self.write_register(address, setpointvalue, 1)",
    "docstring": "Set the setpoint value for a step.\n\n        Args:\n            * patternnumber (integer): 0-7\n            * stepnumber (integer): 0-7\n            * setpointvalue (float): Setpoint value"
  },
  {
    "code": "def connection_class(self, adapter):\n        if self.adapters.get(adapter):\n            return self.adapters[adapter]\n        try:\n            class_prefix = getattr(\n                __import__('db.' + adapter, globals(), locals(),\n                           ['__class_prefix__']), '__class_prefix__')\n            driver = self._import_class('db.' + adapter + '.connection.' +\n                                        class_prefix + 'Connection')\n        except ImportError:\n            raise DBError(\"Must install adapter `%s` or doesn't support\" %\n                          (adapter))\n        self.adapters[adapter] = driver\n        return driver",
    "docstring": "Get connection class by adapter"
  },
  {
    "code": "def _have_pyspark():\n    if _have_pyspark.flag is None:\n        try:\n            if PackageStore.get_parquet_lib() is ParquetLib.SPARK:\n                import pyspark\n                _have_pyspark.flag = True\n            else:\n                _have_pyspark.flag = False\n        except ImportError:\n            _have_pyspark.flag = False\n    return _have_pyspark.flag",
    "docstring": "Check if we're running Pyspark"
  },
  {
    "code": "def _filter_nonextensions(cls, obj):\n        if hasattr(obj, '__dict__') and obj.__dict__.get('__NO_EXTENSION__', False) is True:\n            return False\n        return True",
    "docstring": "Remove all classes marked as not extensions.\n\n        This allows us to have a deeper hierarchy of classes than just\n        one base class that is filtered by _filter_subclasses.  Any\n        class can define a class propery named:\n\n        __NO_EXTENSION__ = True\n\n        That class will never be returned as an extension.  This is useful\n        for masking out base classes for extensions that are declared in\n        CoreTools and would be present in module imports but should not\n        create a second entry point."
  },
  {
    "code": "def _get_node_groups(self):\n        node_dict = {node['data']['id']: {'sources': [], 'targets': []}\n                     for node in self._nodes}\n        for edge in self._edges:\n            edge_data = (edge['data']['i'], edge['data']['polarity'],\n                         edge['data']['source'])\n            node_dict[edge['data']['target']]['sources'].append(edge_data)\n            edge_data = (edge['data']['i'], edge['data']['polarity'],\n                         edge['data']['target'])\n            node_dict[edge['data']['source']]['targets'].append(edge_data)\n        node_key_dict = collections.defaultdict(lambda: [])\n        for node_id, node_d in node_dict.items():\n            key = self._get_node_key(node_d)\n            node_key_dict[key].append(node_id)\n        node_groups = [g for g in node_key_dict.values() if (len(g) > 1)]\n        return node_groups",
    "docstring": "Return a list of node id lists that are topologically identical.\n\n        First construct a node_dict which is keyed to the node id and\n        has a value which is a dict with keys 'sources' and 'targets'.\n        The 'sources' and 'targets' each contain a list of tuples\n        (i, polarity, source) edge of the node. node_dict is then processed\n        by _get_node_key() which returns a tuple of (s,t) where s,t are\n        sorted tuples of the ids for the source and target nodes. (s,t) is\n        then used as a key in node_key_dict where the values are the node\n        ids. node_groups is restricted to groups greater than 1 node."
  },
  {
    "code": "def _check_local_option(self, option):\n        if not self.telnet_opt_dict.has_key(option):\n            self.telnet_opt_dict[option] = TelnetOption()\n        return self.telnet_opt_dict[option].local_option",
    "docstring": "Test the status of local negotiated Telnet options."
  },
  {
    "code": "def raw(self, query: Any, data: Any = None):\n        assert isinstance(query, str)\n        input_db = self.conn['data'][self.schema_name]\n        result = None\n        try:\n            query = query.replace(\"'\", \"\\\"\")\n            criteria = json.loads(query)\n            for key, value in criteria.items():\n                input_db = self.provider._evaluate_lookup(key, value, False, input_db)\n            items = list(input_db.values())\n            result = ResultSet(\n                offset=1,\n                limit=len(items),\n                total=len(items),\n                items=items)\n        except json.JSONDecodeError:\n            raise Exception(\"Query Malformed\")\n        return result",
    "docstring": "Run raw query on Repository.\n\n        For this stand-in repository, the query string is a json string that contains kwargs\n        criteria with straigh-forward equality checks. Individual criteria are always ANDed\n        and the result is always a subset of the full repository.\n\n        We will ignore the `data` parameter for this kind of repository."
  },
  {
    "code": "def ffn_expert_fn(input_size,\n                  hidden_sizes,\n                  output_size,\n                  hidden_activation=tf.nn.relu):\n  def my_fn(x):\n    layer_sizes = [input_size] + hidden_sizes + [output_size]\n    for i in range(1 + len(hidden_sizes)):\n      w = tf.get_variable(\"w_%d\" % i, layer_sizes[i:i+2], tf.float32)\n      x = tf.matmul(x, w)\n      if i < len(hidden_sizes):\n        x = hidden_activation(x)\n      if layer_sizes[i] != input_size:\n        x *= (layer_sizes[i] / float(input_size))**-0.5\n    return x\n  return my_fn",
    "docstring": "Returns a function that creates a feed-forward network.\n\n  Use this function to create the expert_fn argument to distributed_moe.\n\n  Args:\n    input_size: an integer\n    hidden_sizes: a list of integers\n    output_size: an integer\n    hidden_activation: a unary function.\n\n  Returns:\n    a unary function"
  },
  {
    "code": "def _sidConversion(cls, val, **kwargs):\n        if isinstance(val, six.string_types):\n            val = val.split(',')\n        usernames = []\n        for _sid in val:\n            try:\n                userSid = win32security.LookupAccountSid('', _sid)\n                if userSid[1]:\n                    userSid = '{1}\\\\{0}'.format(userSid[0], userSid[1])\n                else:\n                    userSid = '{0}'.format(userSid[0])\n            except Exception:\n                userSid = win32security.ConvertSidToStringSid(_sid)\n                log.warning('Unable to convert SID \"%s\" to a friendly name.  The SID will be disaplayed instead of a user/group name.', userSid)\n            usernames.append(userSid)\n        return usernames",
    "docstring": "converts a list of pysid objects to string representations"
  },
  {
    "code": "def rmtree(path):\n    def handle_remove_readonly(func, path, exc):\n        excvalue = exc[1]\n        if (\n                func in (os.rmdir, os.remove, os.unlink) and\n                excvalue.errno == errno.EACCES\n        ):\n            os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)\n            func(path)\n        else:\n            raise\n    shutil.rmtree(path, ignore_errors=False, onerror=handle_remove_readonly)",
    "docstring": "On windows, rmtree fails for readonly dirs."
  },
  {
    "code": "def geo_length(arg, use_spheroid=None):\n    op = ops.GeoLength(arg, use_spheroid)\n    return op.to_expr()",
    "docstring": "Compute length of a geo spatial data\n\n    Parameters\n    ----------\n    arg : geometry or geography\n    use_spheroid : default None\n\n    Returns\n    -------\n    length : double scalar"
  },
  {
    "code": "def _handle_resps(self, root):\n        resps, bearers = self.get_resps(root)\n        if not resps:\n            return root\n        file_desc = root.xpath(\n            '/tei:teiCorpus/tei:teiHeader/tei:fileDesc',\n            namespaces=constants.NAMESPACES)[0]\n        edition_stmt = etree.Element(TEI + 'editionStmt')\n        file_desc.insert(1, edition_stmt)\n        for index, (resp_resp, resp_name) in enumerate(resps):\n            resp_stmt = etree.SubElement(edition_stmt, TEI + 'respStmt')\n            xml_id = 'resp{}'.format(index+1)\n            resp_stmt.set(constants.XML + 'id', xml_id)\n            resp = etree.SubElement(resp_stmt, TEI + 'resp')\n            resp.text = resp_resp\n            name = etree.SubElement(resp_stmt, TEI + 'name')\n            name.text = resp_name\n            resp_data = '{{{}|{}}}'.format(resp_resp, resp_name)\n            self._update_refs(root, bearers, 'resp', resp_data, xml_id)\n        return root",
    "docstring": "Returns `root` with a resp list added to the TEI header and @resp\n        values changed to references."
  },
  {
    "code": "def total(self):\n        if self._result_cache:\n            return self._result_cache.total\n        return self.all().total",
    "docstring": "Return the total number of records"
  },
  {
    "code": "def get(self, secret_id):\n        return self.prepare_model(self.client.api.inspect_secret(secret_id))",
    "docstring": "Get a secret.\n\n        Args:\n            secret_id (str): Secret ID.\n\n        Returns:\n            (:py:class:`Secret`): The secret.\n\n        Raises:\n            :py:class:`docker.errors.NotFound`\n                If the secret does not exist.\n            :py:class:`docker.errors.APIError`\n                If the server returns an error."
  },
  {
    "code": "def forward_remote(\n        self,\n        remote_port,\n        local_port=None,\n        remote_host=\"127.0.0.1\",\n        local_host=\"localhost\",\n    ):\n        if not local_port:\n            local_port = remote_port\n        tunnels = []\n        def callback(channel, src_addr_tup, dst_addr_tup):\n            sock = socket.socket()\n            sock.connect((local_host, local_port))\n            tunnel = Tunnel(channel=channel, sock=sock, finished=Event())\n            tunnel.start()\n            tunnels.append(tunnel)\n        try:\n            self.transport.request_port_forward(\n                address=remote_host, port=remote_port, handler=callback\n            )\n            yield\n        finally:\n            for tunnel in tunnels:\n                tunnel.finished.set()\n                tunnel.join()\n            self.transport.cancel_port_forward(\n                address=remote_host, port=remote_port\n            )",
    "docstring": "Open a tunnel connecting ``remote_port`` to the local environment.\n\n        For example, say you're running a daemon in development mode on your\n        workstation at port 8080, and want to funnel traffic to it from a\n        production or staging environment.\n\n        In most situations this isn't possible as your office/home network\n        probably blocks inbound traffic. But you have SSH access to this\n        server, so you can temporarily make port 8080 on that server act like\n        port 8080 on your workstation::\n\n            from fabric import Connection\n\n            c = Connection('my-remote-server')\n            with c.forward_remote(8080):\n                c.run(\"remote-data-writer --port 8080\")\n                # Assuming remote-data-writer runs until interrupted, this will\n                # stay open until you Ctrl-C...\n\n        This method is analogous to using the ``-R`` option of OpenSSH's\n        ``ssh`` program.\n\n        :param int remote_port: The remote port number on which to listen.\n\n        :param int local_port:\n            The local port number. Defaults to the same value as\n            ``remote_port``.\n\n        :param str local_host:\n            The local hostname/interface the forwarded connection talks to.\n            Default: ``localhost``.\n\n        :param str remote_host:\n            The remote interface address to listen on when forwarding\n            connections. Default: ``127.0.0.1`` (i.e. only listen on the remote\n            localhost).\n\n        :returns:\n            Nothing; this method is only useful as a context manager affecting\n            local operating system state.\n\n        .. versionadded:: 2.0"
  },
  {
    "code": "def parse_rune_links(html: str) -> dict:\n    soup = BeautifulSoup(html, 'lxml')\n    single_page_raw = soup.find_all('li', class_='champion')\n    single_page = {re.split('\\W+', x.a.div.div['style'])[-3].lower():\n                       [x.a['href']] for x in single_page_raw if x.a is not None}\n    double_page_raw = soup.find_all('div', class_='champion-modal-open')\n    double_page_decode = [json.loads(x['data-loadouts']) for x in double_page_raw]\n    double_page = {re.sub('[^A-Za-z0-9]+', '', x[0]['champion'].lower()):\n                       [x[0]['link'], x[1]['link']] for x in double_page_decode}\n    champs_combined = {**single_page, **double_page}\n    return champs_combined",
    "docstring": "A function which parses the main Runeforge website into dict format.\n\n    Parameters\n    ----------\n    html : str\n        The string representation of the html obtained via a GET request.\n\n    Returns\n    -------\n    dict\n        The nested rune_links champ rune pages from runeforge."
  },
  {
    "code": "def __expire_files(self):\n        self.__files = OrderedDict(\n            item for item in self.__files.items() if not item[1].expired\n        )",
    "docstring": "Because files are always unclean"
  },
  {
    "code": "def find_by_tooltip(browser, tooltip):\n    return ElementSelector(\n        world.browser,\n        str('//*[@title=%(tooltip)s or @data-original-title=%(tooltip)s]' %\n            dict(tooltip=string_literal(tooltip))),\n        filter_displayed=True,\n    )",
    "docstring": "Find elements with the given tooltip.\n\n    :param browser: ``world.browser``\n    :param tooltip: Tooltip to search for\n\n    Returns: an :class:`ElementSelector`"
  },
  {
    "code": "def plot_dop(bands, int_max, dop, hund_cu, name):\n    data = ssplt.calc_z(bands, dop, np.arange(0, int_max, 0.1), hund_cu, name)\n    ssplt.plot_curves_z(data, name)",
    "docstring": "Plot of Quasiparticle weight for N degenerate bands\n       under selected doping shows transition only at half-fill\n       the rest are metallic states"
  },
  {
    "code": "def reset(self, keep_state=False):\n        if not keep_state:\n            self.state = state.ManagerState(state.MANAGER_STATE_PREFIX)\n            self.state.reset()\n        async_to_sync(consumer.run_consumer)(timeout=1)\n        async_to_sync(self.sync_counter.reset)()",
    "docstring": "Reset the shared state and drain Django Channels.\n\n        :param keep_state: If ``True``, do not reset the shared manager\n            state (useful in tests, where the settings overrides need to\n            be kept). Defaults to ``False``."
  },
  {
    "code": "def match(self, **kwargs):\n        if kwargs:\n            if self.definition.get('model') is None:\n                raise ValueError(\"match() with filter only available on relationships with a model\")\n            output = process_filter_args(self.definition['model'], kwargs)\n            if output:\n                self.filters.append(output)\n        return self",
    "docstring": "Traverse relationships with properties matching the given parameters.\n\n            e.g: `.match(price__lt=10)`\n\n        :param kwargs: see `NodeSet.filter()` for syntax\n        :return: self"
  },
  {
    "code": "def for_window(cls, window):\n        utcnow = datetime.datetime.utcnow()\n        return cls(utcnow - window, 0)",
    "docstring": "Given a timedelta window, return a timestamp representing\n        that time."
  },
  {
    "code": "def color_split_position(self):\n        return self.get_text_width(' ') + self.label_width + \\\n            int(float(self.font_width) * float(self.num_padding_chars))",
    "docstring": "The SVG x position where the color split should occur."
  },
  {
    "code": "def kick(self, channel, nick, message=None):\n        self.send(\"KICK\", channel, nick, \":%s\" % (message or self.user.nick))",
    "docstring": "Attempt to kick a user from a channel.\n\n        If a message is not provided, defaults to own nick."
  },
  {
    "code": "def itervalues(self, key_type=None):\r\n        if(key_type is not None):\r\n            intermediate_key = str(key_type)\r\n            if intermediate_key in self.__dict__:\r\n                for direct_key in self.__dict__[intermediate_key].values():\r\n                    yield self.items_dict[direct_key]\r\n        else:\r\n            for value in self.items_dict.values():\r\n                yield value",
    "docstring": "Returns an iterator over the dictionary's values.\r\n            @param key_type if specified, iterator will be returning only values pointed by keys of this type.\r\n                   Otherwise (if not specified) all values in this dictinary will be generated."
  },
  {
    "code": "def extract_mean_or_value(cls, obs_or_pred, key=None):\n        result = None\n        if not isinstance(obs_or_pred, dict):\n            result = obs_or_pred\n        else:\n            keys = ([key] if key is not None else []) + ['mean', 'value']\n            for k in keys:\n                if k in obs_or_pred:\n                    result = obs_or_pred[k]\n                    break\n            if result is None:\n                raise KeyError((\"%s has neither a mean nor a single \"\n                                \"value\" % obs_or_pred))\n        return result",
    "docstring": "Extracts the mean, value, or user-provided key from an observation\n        or prediction dictionary."
  },
  {
    "code": "def subprocess_manager(self, exec_args):\n        try:\n            sp = gevent.subprocess.Popen(exec_args, stdout=gevent.subprocess.PIPE, stderr=gevent.subprocess.PIPE)\n        except OSError:\n            raise RuntimeError('Could not run bro executable (either not installed or not in path): %s' % (exec_args))\n        out, err = sp.communicate()\n        if out:\n            print 'standard output of subprocess: %s' % out\n        if err:\n            raise RuntimeError('%s\\npcap_bro had output on stderr: %s' % (exec_args, err))\n        if sp.returncode:\n            raise RuntimeError('%s\\npcap_bro had returncode: %d' % (exec_args, sp.returncode))",
    "docstring": "Bro subprocess manager"
  },
  {
    "code": "def _whatsnd(data):\n    hdr = data[:512]\n    fakefile = BytesIO(hdr)\n    for testfn in sndhdr.tests:\n        res = testfn(hdr, fakefile)\n        if res is not None:\n            return _sndhdr_MIMEmap.get(res[0])\n    return None",
    "docstring": "Try to identify a sound file type.\n\n    sndhdr.what() has a pretty cruddy interface, unfortunately.  This is why\n    we re-do it here.  It would be easier to reverse engineer the Unix 'file'\n    command and use the standard 'magic' file, as shipped with a modern Unix."
  },
  {
    "code": "def __set_default_ui_state(self, *args):\n        LOGGER.debug(\"> Setting default View state!\")\n        if not self.model():\n            return\n        self.expandAll()\n        for column in range(len(self.model().horizontal_headers)):\n            self.resizeColumnToContents(column)",
    "docstring": "Sets the Widget default ui state.\n\n        :param \\*args: Arguments.\n        :type \\*args: \\*"
  },
  {
    "code": "def describe(self):\n        desc = {\n            'name': self.name,\n            'description': self.description,\n            'type': self.type or 'unknown',\n        }\n        for attr in ['min', 'max', 'allowed', 'default']:\n            v = getattr(self, attr)\n            if v is not None:\n                desc[attr] = v\n        return desc",
    "docstring": "Information about this parameter"
  },
  {
    "code": "def get(self, name, default=None):\n        session = self.__get_session_from_db()\n        return session.get(name, default)",
    "docstring": "Gets the object for \"name\", or None if there's no such object. If\n        \"default\" is provided, return it if no object is found."
  },
  {
    "code": "def get_instance(page_to_crawl):\n    global _instances\n    if isinstance(page_to_crawl, basestring):\n        uri = page_to_crawl\n        page_to_crawl = crawlpage.get_instance(uri)\n    elif isinstance(page_to_crawl, crawlpage.CrawlPage):\n        uri = page_to_crawl.uri\n    else:\n        raise TypeError(\n            \"get_instance() expects a parker.CrawlPage \"\n            \"or basestring derivative.\"\n        )\n    try:\n        instance = _instances[uri]\n    except KeyError:\n        instance = CrawlModel(page_to_crawl)\n        _instances[uri] = instance\n    return instance",
    "docstring": "Return an instance of CrawlModel."
  },
  {
    "code": "def clean(self, value):\n        if (\n            self.base_type is not None and\n            value is not None and\n            not isinstance(value, self.base_type)\n        ):\n            if isinstance(self.base_type, tuple):\n                allowed_types = [typ.__name__ for typ in self.base_type]\n                allowed_types_text = ' or '.join(allowed_types)\n            else:\n                allowed_types_text = self.base_type.__name__\n            err_msg = 'Value must be of %s type.' % allowed_types_text\n            raise ValidationError(err_msg)\n        if not self.has_value(value):\n            if self.default is not None:\n                raise StopValidation(self.default)\n            if self.required:\n                raise ValidationError('This field is required.')\n            else:\n                raise StopValidation(self.blank_value)\n        return value",
    "docstring": "Take a dirty value and clean it."
  },
  {
    "code": "def CaptureVariablesList(self, items, depth, empty_message, limits):\n    v = []\n    for name, value in items:\n      if (self._total_size >= self.max_size) or (\n          len(v) >= limits.max_list_items):\n        v.append({\n            'status': {\n                'refersTo': 'VARIABLE_VALUE',\n                'description': {\n                    'format':\n                        ('Only first $0 items were captured. Use in an '\n                         'expression to see all items.'),\n                    'parameters': [str(len(v))]}}})\n        break\n      v.append(self.CaptureNamedVariable(name, value, depth, limits))\n    if not v:\n      return [{'status': {\n          'refersTo': 'VARIABLE_NAME',\n          'description': {'format': empty_message}}}]\n    return v",
    "docstring": "Captures list of named items.\n\n    Args:\n      items: iterable of (name, value) tuples.\n      depth: nested depth of dictionaries and vectors for items.\n      empty_message: info status message to set if items is empty.\n      limits: Per-object limits for capturing variable data.\n\n    Returns:\n      List of formatted variable objects."
  },
  {
    "code": "def parse_config(args):\n    config_path = path.expanduser(args.config_file)\n    if not path.exists(config_path):\n        if args.config_file != DEFAULT_JOURNAL_RC:\n            print(\"journal: error: config file '\" + args.config_file + \"' not found\")\n            sys.exit()\n        else:\n            return DEFAULT_JOURNAL\n    config = ConfigParser.SafeConfigParser({\n        'journal':{'default':'__journal'},\n        '__journal':{'location':DEFAULT_JOURNAL}\n    })\n    config.read(config_path)\n    journal_location = config.get(config.get('journal', 'default'), 'location');\n    if args.journal:\n        journal_location = config.get(args.journal, 'location');\n    return journal_location",
    "docstring": "Try to load config, to load other journal locations\n    Otherwise, return default location\n\n    Returns journal location"
  },
  {
    "code": "def _prune_hit(hit, model):\n    hit_id = hit[\"_id\"]\n    hit_index = hit[\"_index\"]\n    if model.objects.in_search_queryset(hit_id, index=hit_index):\n        logger.debug(\n            \"%s with id=%s exists in the '%s' index queryset.\", model, hit_id, hit_index\n        )\n        return None\n    else:\n        logger.debug(\n            \"%s with id=%s does not exist in the '%s' index queryset and will be pruned.\",\n            model,\n            hit_id,\n            hit_index,\n        )\n        return model(pk=hit_id)",
    "docstring": "Check whether a document should be pruned.\n\n    This method uses the SearchDocumentManagerMixin.in_search_queryset method\n    to determine whether a 'hit' (search document) should be pruned from an index,\n    and if so it returns the hit as a Django object(id=hit_id).\n\n    Args:\n        hit: dict object the represents a document as returned from the scan_index\n            function. (Contains object id and index.)\n        model: the Django model (not object) from which the document was derived.\n            Used to get the correct model manager and bulk action.\n\n    Returns:\n        an object of type model, with id=hit_id. NB this is not the object\n        itself, which by definition may not exist in the underlying database,\n        but a temporary object with the document id - which is enough to create\n        a 'delete' action."
  },
  {
    "code": "def delete_group(self, group_id, keep_non_orphans=False, keep_orphans=False):\n        params = {'keepNonOrphans': str(keep_non_orphans).lower(), 'keepOrphans': str(keep_orphans).lower()}\n        self._delete(self._service_url(['triggers', 'groups', group_id], params=params))",
    "docstring": "Delete a group trigger\n\n        :param group_id: ID of the group trigger to delete\n        :param keep_non_orphans: if True converts the non-orphan member triggers to standard triggers\n        :param keep_orphans: if True converts the orphan member triggers to standard triggers"
  },
  {
    "code": "def predicates_overlap(tags1: List[str], tags2: List[str]) -> bool:\n    pred_ind1 = get_predicate_indices(tags1)\n    pred_ind2 = get_predicate_indices(tags2)\n    return any(set.intersection(set(pred_ind1), set(pred_ind2)))",
    "docstring": "Tests whether the predicate in BIO tags1 overlap\n    with those of tags2."
  },
  {
    "code": "def calibrate(self):\n        if self._driver and self._driver.is_connected():\n            self._driver.probe_plate()\n            self._engaged = False",
    "docstring": "Calibration involves probing for top plate to get the plate height"
  },
  {
    "code": "def match_level(self, overlay):\n        slice_width = len(self._pattern_spec)\n        if slice_width > len(overlay): return None\n        best_lvl, match_slice = (0, None)\n        for i in range(len(overlay)-slice_width+1):\n            overlay_slice = overlay.values()[i:i+slice_width]\n            lvl = self._slice_match_level(overlay_slice)\n            if lvl is None: continue\n            if lvl > best_lvl:\n                best_lvl = lvl\n                match_slice = (i, i+slice_width)\n        return (best_lvl, match_slice) if best_lvl != 0 else None",
    "docstring": "Given an overlay, return the match level and applicable slice\n        of the overall overlay. The level an integer if there is a\n        match or None if there is no match.\n\n        The level integer is the number of matching components. Higher\n        values indicate a stronger match."
  },
  {
    "code": "def drop_nan(self, col: str=None, method: str=\"all\", **kwargs):\n        try:\n            if col is None:\n                self.df = self.df.dropna(how=method, **kwargs)\n            else:\n                self.df = self.df[self.df[col].notnull()]\n        except Exception as e:\n            self.err(e, \"Error dropping nan values\")",
    "docstring": "Drop rows with NaN values from the main dataframe\n\n        :param col: name of the column, defaults to None. Drops in \n                                                                                                                                                                                                        all columns if no value is provided\n        :type col: str, optional\n        :param method: ``how`` param for ``df.dropna``, defaults to \"all\"\n        :type method: str, optional\n        :param \\*\\*kwargs: params for ``df.dropna``\n        :type \\*\\*kwargs: optional\n\n        :example: ``ds.drop_nan(\"mycol\")``"
  },
  {
    "code": "def load(self, mdl_file):\n        import dill as pickle\n        mdl_file_e = op.expanduser(mdl_file)\n        sv = pickle.load(open(mdl_file_e, \"rb\"))\n        self.mdl = sv[\"mdl\"]\n        self.modelparams.update(sv[\"modelparams\"])\n        logger.debug(\"loaded model from path: \" + mdl_file_e)",
    "docstring": "load model from file. fv_type is not set with this function. It is expected to set it before."
  },
  {
    "code": "def home_wins(self):\n        try:\n            wins, losses = re.findall(r'\\d+', self._home_record)\n            return wins\n        except ValueError:\n            return 0",
    "docstring": "Returns an ``int`` of the number of games the home team won after the\n        conclusion of the game."
  },
  {
    "code": "def cli_opts():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--homeassistant-config\",\n        type=str,\n        required=False,\n        dest=\"config\",\n        help=\"Create configuration section for home assistant\",)\n    parser.add_argument(\n        \"-f\",\n        \"--filter\",\n        type=str,\n        required=False,\n        dest=\"filter\",\n        help=\"Ignore events related with these devices\",)\n    parser.add_argument(\n        \"-o\",\n        \"--output\",\n        type=str,\n        required=False,\n        dest=\"output\",\n        help=\"Send output to file\",)\n    parser.add_argument(\n        \"-v\", \"--verbose\",\n        action=\"store_true\",\n        dest=\"verbose\",\n        help=\"Verbose output\",)\n    parser.add_argument('device')\n    return parser.parse_args()",
    "docstring": "Handle the command line options"
  },
  {
    "code": "def handle_triple(self, lhs, relation, rhs):\n        relation = relation.replace(':', '', 1)\n        if self.is_relation_inverted(relation):\n            source, target, inverted = rhs, lhs, True\n            relation = self.invert_relation(relation)\n        else:\n            source, target, inverted = lhs, rhs, False\n        source = _default_cast(source)\n        target = _default_cast(target)\n        if relation == '':\n            relation = None\n        return Triple(source, relation, target, inverted)",
    "docstring": "Process triples before they are added to the graph.\n\n        Note that *lhs* and *rhs* are as they originally appeared, and\n        may be inverted. Inversions are detected by\n        is_relation_inverted() and de-inverted by invert_relation().\n\n        By default, this function:\n         * removes initial colons on relations\n         * de-inverts all inverted relations\n         * sets empty relations to `None`\n         * casts numeric string sources and targets to their numeric\n           types (e.g. float, int)\n\n        Args:\n            lhs: the left hand side of an observed triple\n            relation: the triple relation (possibly inverted)\n            rhs: the right hand side of an observed triple\n        Returns:\n            The processed (source, relation, target) triple. By default,\n            it is returned as a Triple object."
  },
  {
    "code": "def list_vrf(self, auth, spec=None):\n        if spec is None:\n            spec = {}\n        self._logger.debug(\"list_vrf called; spec: %s\" % unicode(spec))\n        sql = \"SELECT * FROM ip_net_vrf\"\n        params = list()\n        if spec is not None and not {}:\n            where, params = self._expand_vrf_spec(spec)\n        if len(params) > 0:\n            sql += \" WHERE \" + where\n        sql += \" ORDER BY vrf_rt_order(rt) NULLS FIRST\"\n        self._execute(sql, params)\n        res = list()\n        for row in self._curs_pg:\n            res.append(dict(row))\n        return res",
    "docstring": "Return a list of VRFs matching `spec`.\n\n            * `auth` [BaseAuth]\n                AAA options.\n            * `spec` [vrf_spec]\n                A VRF specification. If omitted, all VRFs are returned.\n\n            Returns a list of dicts.\n\n            This is the documentation of the internal backend function. It's\n            exposed over XML-RPC, please also see the XML-RPC documentation for\n            :py:func:`nipap.xmlrpc.NipapXMLRPC.list_vrf` for full\n            understanding."
  },
  {
    "code": "def _get_internal_field_by_name(self, name):\n        field = self._all_fields.get(name, self._all_fields.get('%s.%s' % (self._full_name, name)))\n        if field is not None:\n            return field\n        for field_name in self._all_fields:\n            if field_name.endswith('.%s' % name):\n                return self._all_fields[field_name]",
    "docstring": "Gets the field by name, or None if not found."
  },
  {
    "code": "def _ProcessArtifactFilesSource(self, source):\n    if source.path_type != rdf_paths.PathSpec.PathType.OS:\n      raise ValueError(\"Only supported path type is OS.\")\n    paths = []\n    pathspec_attribute = source.base_source.attributes.get(\"pathspec_attribute\")\n    for source_result_list in self._ProcessSources(\n        source.artifact_sources, parser_factory=None):\n      for response in source_result_list:\n        path = _ExtractPath(response, pathspec_attribute)\n        if path is not None:\n          paths.append(path)\n    file_finder_action = rdf_file_finder.FileFinderAction.Download()\n    request = rdf_file_finder.FileFinderArgs(\n        paths=paths, pathtype=source.path_type, action=file_finder_action)\n    action = file_finder.FileFinderOSFromClient\n    yield action, request",
    "docstring": "Get artifact responses, extract paths and send corresponding files."
  },
  {
    "code": "def _read_depth_images(self, num_images):\n        depth_images = self._ros_read_images(self._depth_image_buffer, num_images, self.staleness_limit)\n        for i in range(0, num_images):\n            depth_images[i] = depth_images[i] * MM_TO_METERS\n            if self._flip_images:\n                depth_images[i] = np.flipud(depth_images[i])\n                depth_images[i] = np.fliplr(depth_images[i])\n            depth_images[i] = DepthImage(depth_images[i], frame=self._frame) \n        return depth_images",
    "docstring": "Reads depth images from the device"
  },
  {
    "code": "def get(self, id_):\n        if self.api.queue_exists(id_):\n            return Queue(self, {\"queue\": {\"name\": id_, \"id_\": id_}}, key=\"queue\")\n        raise exc.NotFound(\"The queue '%s' does not exist.\" % id_)",
    "docstring": "Need to customize, since Queues are not returned with normal response\n        bodies."
  },
  {
    "code": "def get_text(self, text):\n        if sys.maxunicode == 0xffff:\n            return text[self.offset:self.offset + self.length]\n        if not isinstance(text, bytes):\n            entity_text = text.encode('utf-16-le')\n        else:\n            entity_text = text\n        entity_text = entity_text[self.offset * 2:(self.offset + self.length) * 2]\n        return entity_text.decode('utf-16-le')",
    "docstring": "Get value of entity\n\n        :param text: full text\n        :return: part of text"
  },
  {
    "code": "def graph_from_edges(edge_list, node_prefix='', directed=False):\n    if edge_list is None:\n        edge_list = []\n    graph_type = \"digraph\" if directed else \"graph\"\n    with_prefix = functools.partial(\"{0}{1}\".format, node_prefix)\n    graph = Dot(graph_type=graph_type)\n    for src, dst in edge_list:\n        src = with_prefix(src)\n        dst = with_prefix(dst)\n        graph.add_edge(Edge(src, dst))\n    return graph",
    "docstring": "Creates a basic graph out of an edge list.\n\n    The edge list has to be a list of tuples representing\n    the nodes connected by the edge.\n    The values can be anything: bool, int, float, str.\n\n    If the graph is undirected by default, it is only\n    calculated from one of the symmetric halves of the matrix."
  },
  {
    "code": "def setServer(self, server):\r\n        if server == 'live':\r\n            self.__server__ = server\r\n            self.__server_url__ = 'api.sense-os.nl'\r\n            self.setUseHTTPS()\r\n            return True\r\n        elif server == 'dev':\r\n            self.__server__ = server\r\n            self.__server_url__ = 'api.dev.sense-os.nl'\r\n            self.setUseHTTPS(False)\r\n            return True\r\n        elif server == 'rc':\r\n            self.__server__ = server\r\n            self.__server_url__ = 'api.rc.dev.sense-os.nl'\r\n            self.setUseHTTPS(False)\r\n        else:\r\n            return False",
    "docstring": "Set server to interact with.\r\n            \r\n            @param server (string) - 'live' for live server, 'dev' for test server, 'rc' for release candidate\r\n            \r\n            @return (boolean) - Boolean indicating whether setServer succeeded"
  },
  {
    "code": "def _GetNextPath(self):\n    paths = sorted(path\n                   for path in io_wrapper.ListDirectoryAbsolute(self._directory)\n                   if self._path_filter(path))\n    if not paths:\n      return None\n    if self._path is None:\n      return paths[0]\n    if not io_wrapper.IsCloudPath(paths[0]) and not self._ooo_writes_detected:\n      current_path_index = bisect.bisect_left(paths, self._path)\n      ooo_check_start = max(0, current_path_index - self._OOO_WRITE_CHECK_COUNT)\n      for path in paths[ooo_check_start:current_path_index]:\n        if self._HasOOOWrite(path):\n          self._ooo_writes_detected = True\n          break\n    next_paths = list(path\n                      for path in paths\n                      if self._path is None or path > self._path)\n    if next_paths:\n      return min(next_paths)\n    else:\n      return None",
    "docstring": "Gets the next path to load from.\n\n    This function also does the checking for out-of-order writes as it iterates\n    through the paths.\n\n    Returns:\n      The next path to load events from, or None if there are no more paths."
  },
  {
    "code": "def get_content(self, key):\n        LOGGER.debug(\"> Retrieving '{0}' content from the cache.\".format(self.__class__.__name__, key))\n        return self.get(key)",
    "docstring": "Gets given content from the cache.\n\n        Usage::\n\n            >>> cache = Cache()\n            >>> cache.add_content(John=\"Doe\", Luke=\"Skywalker\")\n            True\n            >>> cache.get_content(\"Luke\")\n            'Skywalker'\n\n        :param key: Content to retrieve.\n        :type key: object\n        :return: Content.\n        :rtype: object"
  },
  {
    "code": "def construct_makeblastdb_cmd(\n    filename, outdir, blastdb_exe=pyani_config.MAKEBLASTDB_DEFAULT\n):\n    title = os.path.splitext(os.path.split(filename)[-1])[0]\n    outfilename = os.path.join(outdir, os.path.split(filename)[-1])\n    return (\n        \"{0} -dbtype nucl -in {1} -title {2} -out {3}\".format(\n            blastdb_exe, filename, title, outfilename\n        ),\n        outfilename,\n    )",
    "docstring": "Returns a single makeblastdb command.\n\n    - filename - input filename\n    - blastdb_exe - path to the makeblastdb executable"
  },
  {
    "code": "def initialize_from_sql_cursor(self, sqlcursor):\n        tuples = 0\n        data = sqlcursor.fetchmany()\n        while 0 < len(data):\n            for entry in data:\n                self.add_entry(str(entry[0]), entry[1])\n            data = sqlcursor.fetchmany()\n        self._normalized = self._check_normalization\n        return tuples",
    "docstring": "Initializes the TimeSeries's data from the given SQL cursor.\n\n        You need to set the time stamp format using :py:meth:`TimeSeries.set_timeformat`.\n\n        :param SQLCursor sqlcursor:    Cursor that was holds the SQL result for any given\n            \"SELECT timestamp, value, ... FROM ...\" SQL query.\n            Only the first two attributes of the SQL result will be used.\n\n        :return:    Returns the number of entries added to the TimeSeries.\n        :rtype:     integer"
  },
  {
    "code": "def create_treeitem(self, ):\n        p = self.get_parent()\n        root = self.get_root()\n        if p:\n            pitem = p.get_treeitem()\n        else:\n            pitem = root.get_rootitem()\n        idata = root.create_itemdata(self)\n        item = TreeItem(idata, parent=pitem)\n        return item",
    "docstring": "Create a new treeitem for this reftrack instance.\n\n        .. Note:: Parent should be set, Parent should already have a treeitem.\n                  If there is no parent, the root tree item is used as parent for the treeitem.\n\n        :returns: a new treeitem that contains a itemdata with the reftrack instanec.\n        :rtype: :class:`TreeItem`\n        :raises: None"
  },
  {
    "code": "def _ior(self, other):\n\t\tif not isinstance(other, _basebag):\n\t\t\tother = self._from_iterable(other)\n\t\tfor elem, other_count in other.counts():\n\t\t\told_count = self.count(elem)\n\t\t\tnew_count = max(other_count, old_count)\n\t\t\tself._set_count(elem, new_count)\n\t\treturn self",
    "docstring": "Set multiplicity of each element to the maximum of the two collections.\n\n\t\tif isinstance(other, _basebag):\n\t\t\tThis runs in O(other.num_unique_elements())\n\t\telse:\n\t\t\tThis runs in O(len(other))"
  },
  {
    "code": "def histogram_voltage(self, timestep=None, title=True, **kwargs):\n        data = self.network.results.v_res()\n        if title is True:\n            if timestep is not None:\n                title = \"Voltage histogram for time step {}\".format(timestep)\n            else:\n                title = \"Voltage histogram \\nfor time steps {} to {}\".format(\n                    data.index[0], data.index[-1])\n        elif title is False:\n            title = None\n        plots.histogram(data=data, title=title, timeindex=timestep, **kwargs)",
    "docstring": "Plots histogram of voltages.\n\n        For more information see :func:`edisgo.tools.plots.histogram`.\n\n        Parameters\n        ----------\n        timestep : :pandas:`pandas.Timestamp<timestamp>` or None, optional\n            Specifies time step histogram is plotted for. If timestep is None\n            all time steps voltages are calculated for are used. Default: None.\n        title : :obj:`str` or :obj:`bool`, optional\n            Title for plot. If True title is auto generated. If False plot has\n            no title. If :obj:`str`, the provided title is used. Default: True."
  },
  {
    "code": "def next_sibling(self):\n        if self.parent is None:\n            return None\n        for i, child in enumerate(self.parent.children):\n            if child is self:\n                try:\n                    return self.parent.children[i+1]\n                except IndexError:\n                    return None",
    "docstring": "The node immediately following the invocant in their parent's children\n        list. If the invocant does not have a next sibling, it is None"
  },
  {
    "code": "def create_move(project, resource, offset=None):\n    if offset is None:\n        return MoveModule(project, resource)\n    this_pymodule = project.get_pymodule(resource)\n    pyname = evaluate.eval_location(this_pymodule, offset)\n    if pyname is not None:\n        pyobject = pyname.get_object()\n        if isinstance(pyobject, pyobjects.PyModule) or \\\n           isinstance(pyobject, pyobjects.PyPackage):\n            return MoveModule(project, pyobject.get_resource())\n        if isinstance(pyobject, pyobjects.PyFunction) and \\\n           isinstance(pyobject.parent, pyobjects.PyClass):\n            return MoveMethod(project, resource, offset)\n        if isinstance(pyobject, pyobjects.PyDefinedObject) and \\\n           isinstance(pyobject.parent, pyobjects.PyModule) or \\\n           isinstance(pyname, pynames.AssignedName):\n            return MoveGlobal(project, resource, offset)\n    raise exceptions.RefactoringError(\n        'Move only works on global classes/functions/variables, modules and '\n        'methods.')",
    "docstring": "A factory for creating Move objects\n\n    Based on `resource` and `offset`, return one of `MoveModule`,\n    `MoveGlobal` or `MoveMethod` for performing move refactoring."
  },
  {
    "code": "def _createJobStateFile(self):\n        jobStateFile = os.path.join(self.localTempDir, '.jobState')\n        jobState = {'jobPID': os.getpid(),\n                    'jobName': self.jobName,\n                    'jobDir': self.localTempDir,\n                    'deferredFunctions': []}\n        with open(jobStateFile + '.tmp', 'wb') as fH:\n            dill.dump(jobState, fH)\n        os.rename(jobStateFile + '.tmp', jobStateFile)\n        return jobStateFile",
    "docstring": "Create the job state file for the current job and fill in the required\n        values.\n\n        :return: Path to the job state file\n        :rtype: str"
  },
  {
    "code": "def calc_et0_v1(self):\n    con = self.parameters.control.fastaccess\n    inp = self.sequences.inputs.fastaccess\n    flu = self.sequences.fluxes.fastaccess\n    for k in range(con.nhru):\n        flu.et0[k] = (con.ke[k]*(((8.64*inp.glob+93.*con.kf[k]) *\n                                  (flu.tkor[k]+22.)) /\n                                 (165.*(flu.tkor[k]+123.) *\n                                  (1.+0.00019*min(con.hnn[k], 600.)))))",
    "docstring": "Calculate reference evapotranspiration after Turc-Wendling.\n\n    Required control parameters:\n      |NHRU|\n      |KE|\n      |KF|\n      |HNN|\n\n    Required input sequence:\n      |Glob|\n\n    Required flux sequence:\n      |TKor|\n\n    Calculated flux sequence:\n      |ET0|\n\n    Basic equation:\n      :math:`ET0 = KE \\\\cdot\n      \\\\frac{(8.64 \\\\cdot Glob+93 \\\\cdot KF) \\\\cdot (TKor+22)}\n      {165 \\\\cdot (TKor+123) \\\\cdot (1 + 0.00019 \\\\cdot min(HNN, 600))}`\n\n    Example:\n\n        >>> from hydpy.models.lland import *\n        >>> parameterstep('1d')\n        >>> simulationstep('12h')\n        >>> nhru(3)\n        >>> ke(1.1)\n        >>> kf(0.6)\n        >>> hnn(200.0, 600.0, 1000.0)\n        >>> inputs.glob = 200.0\n        >>> fluxes.tkor = 15.0\n        >>> model.calc_et0_v1()\n        >>> fluxes.et0\n        et0(3.07171, 2.86215, 2.86215)"
  },
  {
    "code": "def update_input(filelist, ivmlist=None, removed_files=None):\n    newfilelist = []\n    if removed_files == []:\n        return filelist, ivmlist\n    else:\n        sci_ivm = list(zip(filelist, ivmlist))\n        for f in removed_files:\n            result=[sci_ivm.remove(t) for t in sci_ivm if t[0] == f ]\n        ivmlist = [el[1] for el in sci_ivm]\n        newfilelist = [el[0] for el in sci_ivm]\n        return newfilelist, ivmlist",
    "docstring": "Removes files flagged to be removed from the input filelist.\n    Removes the corresponding ivm files if present."
  },
  {
    "code": "def seq_md5(seq, normalize=True):\n    seq = normalize_sequence(seq) if normalize else seq\n    bseq = seq.encode(\"ascii\")\n    return hashlib.md5(bseq).hexdigest()",
    "docstring": "returns unicode md5 as hex digest for sequence `seq`.\n\n    >>> seq_md5('')\n    'd41d8cd98f00b204e9800998ecf8427e'\n\n    >>> seq_md5('ACGT')\n    'f1f8f4bf413b16ad135722aa4591043e'\n\n    >>> seq_md5('ACGT*')\n    'f1f8f4bf413b16ad135722aa4591043e'\n\n    >>> seq_md5(' A C G T ')\n    'f1f8f4bf413b16ad135722aa4591043e'\n\n    >>> seq_md5('acgt')\n    'f1f8f4bf413b16ad135722aa4591043e'\n\n    >>> seq_md5('acgt', normalize=False)\n    'db516c3913e179338b162b2476d1c23f'"
  },
  {
    "code": "def set_path(self, file_path):\n        if not file_path:\n            self.read_data = self.memory_read\n            self.write_data = self.memory_write\n        elif not is_valid(file_path):\n            self.write_data(file_path, {})\n        self.path = file_path",
    "docstring": "Set the path of the database.\n        Create the file if it does not exist."
  },
  {
    "code": "def close(self):\n        self._serial.write(b\"@c\")\n        self._serial.read()\n        self._serial.close()",
    "docstring": "Closes the connection to the serial port and ensure no pending\n        operatoin are left"
  },
  {
    "code": "def get_hoisted(dct, child_name):\n  child = dct[child_name]\n  del dct[child_name]\n  dct.update(child)\n  return dct",
    "docstring": "Pulls all of a child's keys up to the parent, with the names unchanged."
  },
  {
    "code": "def exec_func(code, glob_vars, loc_vars=None):\n    if loc_vars is None:\n        exec(code, glob_vars)\n    else:\n        exec(code, glob_vars, loc_vars)",
    "docstring": "Wrapper around exec."
  },
  {
    "code": "def validate_root_vertex_directives(root_ast):\n    directives_present_at_root = set()\n    for directive_obj in root_ast.directives:\n        directive_name = directive_obj.name.value\n        if is_filter_with_outer_scope_vertex_field_operator(directive_obj):\n            raise GraphQLCompilationError(u'Found a filter directive with an operator that is not'\n                                          u'allowed on the root vertex: {}'.format(directive_obj))\n        directives_present_at_root.add(directive_name)\n    disallowed_directives = directives_present_at_root & VERTEX_DIRECTIVES_PROHIBITED_ON_ROOT\n    if disallowed_directives:\n        raise GraphQLCompilationError(u'Found prohibited directives on root vertex: '\n                                      u'{}'.format(disallowed_directives))",
    "docstring": "Validate the directives that appear at the root vertex field."
  },
  {
    "code": "def _pretty_time_delta(td):\n    seconds = td.total_seconds()\n    sign_string = '-' if seconds < 0 else ''\n    seconds = abs(int(seconds))\n    days, seconds = divmod(seconds, 86400)\n    hours, seconds = divmod(seconds, 3600)\n    minutes, seconds = divmod(seconds, 60)\n    d = dict(sign=sign_string, days=days, hours=hours, minutes=minutes, seconds=seconds)\n    if days > 0:\n        return '{sign}{days}d{hours:02d}h{minutes:02d}m:{seconds:02d}s'.format(**d)\n    elif hours > 0:\n        return '{sign}{hours:02d}h{minutes:02d}m:{seconds:02d}s'.format(**d)\n    elif minutes > 0:\n        return '{sign}{minutes:02d}m:{seconds:02d}s'.format(**d)\n    else:\n        return '{sign}{seconds:02d}s'.format(**d)",
    "docstring": "Creates a string representation of a time delta.\n\n    Parameters\n    ----------\n    td : :class:`datetime.timedelta`\n\n    Returns\n    -------\n    pretty_formatted_datetime : str"
  },
  {
    "code": "def _FlushInput(self):\n        self.ser.flush()\n        flushed = 0\n        while True:\n            ready_r, ready_w, ready_x = select.select([self.ser], [],\n                                                      [self.ser], 0)\n            if len(ready_x) > 0:\n                logging.error(\"Exception from serial port.\")\n                return None\n            elif len(ready_r) > 0:\n                flushed += 1\n                self.ser.read(1)\n                self.ser.flush()\n            else:\n                break",
    "docstring": "Flush all read data until no more available."
  },
  {
    "code": "def get_from_layer(self, name, layer=None):\n        if name not in self._children:\n            if self._frozen:\n                raise KeyError(name)\n            self._children[name] = ConfigTree(layers=self._layers)\n        child = self._children[name]\n        if isinstance(child, ConfigNode):\n            return child.get_value(layer)\n        else:\n            return child",
    "docstring": "Get a configuration value from the named layer.\n\n        Parameters\n        ----------\n        name : str\n            The name of the value to retrieve\n        layer: str\n            The name of the layer to retrieve the value from. If it is not supplied\n            then the outermost layer in which the key is defined will be used."
  },
  {
    "code": "def stats_add_duration(self, key, duration):\n        if not self._measurement:\n            if not self.IGNORE_OOB_STATS:\n                self.logger.warning(\n                    'stats_add_timing invoked outside execution')\n            return\n        self._measurement.add_duration(key, duration)",
    "docstring": "Add a duration to the per-message measurements\n\n        .. versionadded:: 3.19.0\n\n        .. note:: If this method is called when there is not a message being\n            processed, a message will be logged at the ``warning`` level to\n            indicate the value is being dropped. To suppress these warnings,\n            set the :attr:`~rejected.consumer.Consumer.IGNORE_OOB_STATS`\n            attribute to :data:`True`.\n\n        :param key: The key to add the timing to\n        :type key: :class:`str`\n        :param duration: The timing value in seconds\n        :type duration: :class:`int` or :class:`float`"
  },
  {
    "code": "def humanize_bytes(bytesize, precision=2):\n    abbrevs = (\n        (1 << 50, 'PB'),\n        (1 << 40, 'TB'),\n        (1 << 30, 'GB'),\n        (1 << 20, 'MB'),\n        (1 << 10, 'kB'),\n        (1, 'bytes')\n    )\n    if bytesize == 1:\n        return '1 byte'\n    for factor, suffix in abbrevs:\n        if bytesize >= factor:\n            break\n    if factor == 1:\n        precision = 0\n    return '%.*f %s' % (precision, bytesize / float(factor), suffix)",
    "docstring": "Humanize byte size figures\n\n    https://gist.github.com/moird/3684595"
  },
  {
    "code": "def photos_search(user_id='', auth=False,  tags='', tag_mode='', text='',\\\n                  min_upload_date='', max_upload_date='',\\\n                  min_taken_date='', max_taken_date='', \\\n                  license='', per_page='', page='', sort=''):\n    method = 'flickr.photos.search'\n    data = _doget(method, auth=auth, user_id=user_id, tags=tags, text=text,\\\n                  min_upload_date=min_upload_date,\\\n                  max_upload_date=max_upload_date, \\\n                  min_taken_date=min_taken_date, \\\n                  max_taken_date=max_taken_date, \\\n                  license=license, per_page=per_page,\\\n                  page=page, sort=sort)\n    photos = []\n    if isinstance(data.rsp.photos.photo, list):\n        for photo in data.rsp.photos.photo:\n            photos.append(_parse_photo(photo))\n    else:\n        photos = [_parse_photo(data.rsp.photos.photo)]\n    return photos",
    "docstring": "Returns a list of Photo objects.\n\n    If auth=True then will auth the user.  Can see private etc"
  },
  {
    "code": "def get_name(node):\n  if isinstance(node, gast.Name):\n    return node.id\n  elif isinstance(node, (gast.Subscript, gast.Attribute)):\n    return get_name(node.value)\n  else:\n    raise TypeError",
    "docstring": "Get the name of a variable.\n\n  Args:\n    node: A `Name`, `Subscript` or `Attribute` node.\n\n  Returns:\n    The name of the variable e.g. `'x'` for `x`, `x.i` and `x[i]`."
  },
  {
    "code": "def download_artifact_bundle(self, id_or_uri, file_path):\n        uri = self.DOWNLOAD_PATH + '/' + extract_id_from_uri(id_or_uri)\n        return self._client.download(uri, file_path)",
    "docstring": "Download the Artifact Bundle.\n\n        Args:\n            id_or_uri: ID or URI of the Artifact Bundle.\n            file_path(str): Destination file path.\n\n        Returns:\n            bool: Successfully downloaded."
  },
  {
    "code": "def update(self, data):\n        self.name = data[\"name\"]\n        self.description = data['description']\n        self.win_index = data['win_index']\n        if conf.use_winpcapy:\n            self._update_pcapdata()\n        try:\n            self.ip = socket.inet_ntoa(get_if_raw_addr(data['guid']))\n        except (KeyError, AttributeError, NameError):\n            pass\n        try:\n            self.mac = data['mac']\n        except KeyError:\n            pass",
    "docstring": "Update info about network interface according to given dnet dictionary"
  },
  {
    "code": "def live_scores(self, live_scores):\n        headers = ['League', 'Home Team Name', 'Home Team Goals',\n                   'Away Team Goals', 'Away Team Name']\n        result = [headers]\n        result.extend([game['league'], game['homeTeamName'],\n                       game['goalsHomeTeam'], game['goalsAwayTeam'],\n                       game['awayTeamName']] for game in live_scores['games'])\n        self.generate_output(result)",
    "docstring": "Store output of live scores to a CSV file"
  },
  {
    "code": "def allpathsX(args):\n    p = OptionParser(allpathsX.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 2:\n        sys.exit(not p.print_help())\n    folder, tag = args\n    tag = tag.split(\",\")\n    for p, pf in iter_project(folder):\n        assemble_pairs(p, pf, tag)",
    "docstring": "%prog allpathsX folder tag\n\n    Run assembly on a folder of paired reads and apply tag (PE-200, PE-500).\n    Allow multiple tags separated by comma, e.g. PE-350,TT-1050"
  },
  {
    "code": "def stop_gradient(input_layer):\n  if input_layer.is_sequence():\n    result = [tf.stop_gradient(t) for t in input_layer.sequence]\n    return input_layer.with_sequence(result)\n  else:\n    return tf.stop_gradient(input_layer)",
    "docstring": "Cuts off the gradient at this point.\n\n  This works on both sequence and regular Pretty Tensors.\n\n  Args:\n    input_layer: The input.\n  Returns:\n    A new Pretty Tensor of the same type with stop_gradient applied."
  },
  {
    "code": "def gff(args):\n    p = OptionParser(gff.__doc__)\n    opts, args = p.parse_args(args)\n    if len(args) != 1:\n        sys.exit(not p.print_help())\n    gbkfile, = args\n    MultiGenBank(gbkfile)",
    "docstring": "%prog gff seq.gbk\n\n    Convert Genbank file to GFF and FASTA file.\n    The Genbank file can contain multiple records."
  },
  {
    "code": "def validate_output(schema):\n    location = get_callsite_location()\n    def decorator(fn):\n        validate_schema(schema)\n        wrapper = wrap_response(fn, schema)\n        record_schemas(\n            fn, wrapper, location, response_schema=sort_schema(schema))\n        return wrapper\n    return decorator",
    "docstring": "Validate the body of a response from a flask view.\n\n    Like `validate_body`, this function compares a json document to a\n    jsonschema specification. However, this function applies the schema to the\n    view response.\n\n    Instead of the view returning a flask response object, it should instead\n    return a Python list or dictionary. For example::\n\n        from snapstore_schemas import validate_output\n\n        @validate_output({\n            'type': 'object',\n            'properties': {\n                'ok': {'type': 'boolean'},\n            },\n            'required': ['ok'],\n            'additionalProperties': False\n        }\n        def my_flask_view():\n            # view code here\n            return {'ok': True}\n\n    Every view response will be evaluated against the schema. Any that do not\n    comply with the schema will cause DataValidationError to be raised."
  },
  {
    "code": "def _should_fuzz_node(self, fuzz_node, stage):\n        if stage == ClientFuzzer.STAGE_ANY:\n            return True\n        if fuzz_node.name.lower() == stage.lower():\n            if self._index_in_path == len(self._fuzz_path) - 1:\n                return True\n        else:\n            return False",
    "docstring": "The matching stage is either the name of the last node, or ClientFuzzer.STAGE_ANY.\n\n        :return: True if we are in the correct model node"
  },
  {
    "code": "def set_stop_chars(self, stop_chars):\n        warnings.warn(\"Method set_stop_chars is deprecated, \"\n                      \"use `set_stop_chars_left` or \"\n                      \"`set_stop_chars_right` instead\", DeprecationWarning)\n        self._stop_chars = set(stop_chars)\n        self._stop_chars_left = self._stop_chars\n        self._stop_chars_right = self._stop_chars",
    "docstring": "Set stop characters used when determining end of URL.\n\n        .. deprecated:: 0.7\n            Use :func:`set_stop_chars_left` or :func:`set_stop_chars_right`\n            instead.\n\n        :param list stop_chars: list of characters"
  },
  {
    "code": "def show(self, frame):\n        if len(frame.shape) != 3:\n            raise ValueError('frame should have shape with only 3 dimensions')\n        if not self.is_open:\n            self.open()\n        self._window.clear()\n        self._window.switch_to()\n        self._window.dispatch_events()\n        image = ImageData(\n            frame.shape[1],\n            frame.shape[0],\n            'RGB',\n            frame.tobytes(),\n            pitch=frame.shape[1]*-3\n        )\n        image.blit(0, 0, width=self._window.width, height=self._window.height)\n        self._window.flip()",
    "docstring": "Show an array of pixels on the window.\n\n        Args:\n            frame (numpy.ndarray): the frame to show on the window\n\n        Returns:\n            None"
  },
  {
    "code": "def update(self, **kwargs):\n        if self.condition is not None:\n            self.result = self.do_(self.model.table.update().where(self.condition).values(**kwargs))\n        else:\n            self.result = self.do_(self.model.table.update().values(**kwargs))\n        return self.result",
    "docstring": "Execute update table set field = field+1 like statement"
  },
  {
    "code": "def mkdir(dir_path):\n        if not os.path.isdir(dir_path) or not os.path.exists(dir_path):\n            os.makedirs(dir_path)",
    "docstring": "Make directory if not existed"
  },
  {
    "code": "def _remove_last(votes, fpl, cl, ranking):\n    for v in votes:\n        for r in v:\n            if r == fpl[-1]:\n                v.remove(r)\n    for c in cl:\n        if c == fpl[-1]:\n            if c not in ranking:\n                ranking.append((c, len(ranking) + 1))",
    "docstring": "Remove last candidate in IRV voting."
  },
  {
    "code": "def calldata(vcf_fn, region=None, samples=None, ploidy=2, fields=None,\n             exclude_fields=None, dtypes=None, arities=None, fills=None,\n             vcf_types=None, count=None, progress=0, logstream=None,\n             condition=None, slice_args=None, verbose=True, cache=False,\n             cachedir=None, skip_cached=False, compress_cache=False,\n             truncate=True):\n    loader = _CalldataLoader(vcf_fn, region=region, samples=samples,\n                             ploidy=ploidy, fields=fields,\n                             exclude_fields=exclude_fields, dtypes=dtypes,\n                             arities=arities, fills=fills, vcf_types=vcf_types,\n                             count=count, progress=progress,\n                             logstream=logstream, condition=condition,\n                             slice_args=slice_args, verbose=verbose,\n                             cache=cache, cachedir=cachedir,\n                             skip_cached=skip_cached,\n                             compress_cache=compress_cache,\n                             truncate=truncate)\n    arr = loader.load()\n    return arr",
    "docstring": "Load a numpy 1-dimensional structured array with data from the sample\n    columns of a VCF file.\n\n    Parameters\n    ----------\n\n    vcf_fn: string or list\n        Name of the VCF file or list of file names.\n    region: string\n        Region to extract, e.g., 'chr1' or 'chr1:0-100000'.\n    fields: list or array-like\n        List of fields to extract from the VCF.\n    exclude_fields: list or array-like\n        Fields to exclude from extraction.\n    dtypes: dict or dict-like\n        Dictionary cotaining dtypes to use instead of the default inferred ones\n    arities: dict or dict-like\n        Override the amount of values to expect.\n    fills: dict or dict-like\n        Dictionary containing field:fillvalue mappings used to override the\n        default fill in values in VCF fields.\n    vcf_types: dict or dict-like\n        Dictionary containing field:string mappings used to override any\n        bogus type declarations in the VCF header.\n    count: int\n        Attempt to extract a specific number of records.\n    progress: int\n        If greater than 0, log parsing progress.\n    logstream: file or file-like object\n        Stream to use for logging progress.\n    condition: array\n        Boolean array defining which rows to load.\n    slice_args: tuple or list\n        Slice of the underlying iterator, e.g., (0, 1000, 10) takes every\n        10th row from the first 1000.\n    verbose: bool\n        Log more messages.\n    cache: bool\n        If True, save the resulting numpy array to disk, and load from the\n        cache if present rather than rebuilding from the VCF.\n    cachedir: string\n        Manually specify the directory to use to store cache files.\n    skip_cached: bool\n        If True and cache file is fresh, do not load and return None.\n    compress_cache: bool, optional\n        If True, compress the cache file.\n    truncate: bool, optional\n        If True (default) only include variants whose start position is within\n        the given region. If False, use default tabix behaviour.\n\n    Examples\n    --------\n\n    >>> from vcfnp import calldata, view2d\n    >>> c = calldata('fixture/sample.vcf')\n    >>> c\n    array([ ((True, True, [0, 0], 0, 0, b'0|0', [10, 10]), (True, True, [0, 0], 0, 0, b'0|0', [10, 10]), (True, False, [0, 1], 0, 0, b'0/1', [3, 3])),\n           ((True, True, [0, 0], 0, 0, b'0|0', [10, 10]), (True, True, [0, 0], 0, 0, b'0|0', [10, 10]), (True, False, [0, 1], 0, 0, b'0/1', [3, 3])),\n           ((True, True, [0, 0], 1, 48, b'0|0', [51, 51]), (True, True, [1, 0], 8, 48, b'1|0', [51, 51]), (True, False, [1, 1], 5, 43, b'1/1', [0, 0])),\n           ((True, True, [0, 0], 3, 49, b'0|0', [58, 50]), (True, True, [0, 1], 5, 3, b'0|1', [65, 3]), (True, False, [0, 0], 3, 41, b'0/0', [0, 0])),\n           ((True, True, [1, 2], 6, 21, b'1|2', [23, 27]), (True, True, [2, 1], 0, 2, b'2|1', [18, 2]), (True, False, [2, 2], 4, 35, b'2/2', [0, 0])),\n           ((True, True, [0, 0], 0, 54, b'0|0', [56, 60]), (True, True, [0, 0], 4, 48, b'0|0', [51, 51]), (True, False, [0, 0], 2, 61, b'0/0', [0, 0])),\n           ((True, False, [0, 1], 4, 0, b'0/1', [0, 0]), (True, False, [0, 2], 2, 17, b'0/2', [0, 0]), (False, False, [-1, -1], 3, 40, b'./.', [0, 0])),\n           ((True, False, [0, 0], 0, 0, b'0/0', [0, 0]), (True, True, [0, 0], 0, 0, b'0|0', [0, 0]), (False, False, [-1, -1], 0, 0, b'./.', [0, 0])),\n           ((True, False, [0, -1], 0, 0, b'0', [0, 0]), (True, False, [0, 1], 0, 0, b'0/1', [0, 0]), (True, True, [0, 2], 0, 0, b'0|2', [0, 0]))],\n          dtype=[('NA00001', [('is_called', '?'), ('is_phased', '?'), ('genotype', 'i1', (2,)), ('DP', '<u2'), ('GQ', 'u1'), ('GT', 'S3'), ('HQ', '<i4', (2,))]), ('NA00002', [('is_called', '?'), ('is_phased', '?'), ('genotype', 'i1', (2,)), ('DP', '<u2'), ('GQ', 'u1'), ('GT', 'S3'), ('HQ', '<i4', (2,))]), ('NA00003', [('is_called', '?'), ('is_phased', '?'), ('genotype', 'i1', (2,)), ('DP', '<u2'), ('GQ', 'u1'), ('GT', 'S3'), ('HQ', '<i4', (2,))])])\n    >>> c['NA00001']\n    array([(True, True, [0, 0], 0, 0, b'0|0', [10, 10]),\n           (True, True, [0, 0], 0, 0, b'0|0', [10, 10]),\n           (True, True, [0, 0], 1, 48, b'0|0', [51, 51]),\n           (True, True, [0, 0], 3, 49, b'0|0', [58, 50]),\n           (True, True, [1, 2], 6, 21, b'1|2', [23, 27]),\n           (True, True, [0, 0], 0, 54, b'0|0', [56, 60]),\n           (True, False, [0, 1], 4, 0, b'0/1', [0, 0]),\n           (True, False, [0, 0], 0, 0, b'0/0', [0, 0]),\n           (True, False, [0, -1], 0, 0, b'0', [0, 0])],\n          dtype=[('is_called', '?'), ('is_phased', '?'), ('genotype', 'i1', (2,)), ('DP', '<u2'), ('GQ', 'u1'), ('GT', 'S3'), ('HQ', '<i4', (2,))])\n    >>> c2d = view2d(c)\n    >>> c2d\n    array([[(True, True, [0, 0], 0, 0, b'0|0', [10, 10]),\n            (True, True, [0, 0], 0, 0, b'0|0', [10, 10]),\n            (True, False, [0, 1], 0, 0, b'0/1', [3, 3])],\n           [(True, True, [0, 0], 0, 0, b'0|0', [10, 10]),\n            (True, True, [0, 0], 0, 0, b'0|0', [10, 10]),\n            (True, False, [0, 1], 0, 0, b'0/1', [3, 3])],\n           [(True, True, [0, 0], 1, 48, b'0|0', [51, 51]),\n            (True, True, [1, 0], 8, 48, b'1|0', [51, 51]),\n            (True, False, [1, 1], 5, 43, b'1/1', [0, 0])],\n           [(True, True, [0, 0], 3, 49, b'0|0', [58, 50]),\n            (True, True, [0, 1], 5, 3, b'0|1', [65, 3]),\n            (True, False, [0, 0], 3, 41, b'0/0', [0, 0])],\n           [(True, True, [1, 2], 6, 21, b'1|2', [23, 27]),\n            (True, True, [2, 1], 0, 2, b'2|1', [18, 2]),\n            (True, False, [2, 2], 4, 35, b'2/2', [0, 0])],\n           [(True, True, [0, 0], 0, 54, b'0|0', [56, 60]),\n            (True, True, [0, 0], 4, 48, b'0|0', [51, 51]),\n            (True, False, [0, 0], 2, 61, b'0/0', [0, 0])],\n           [(True, False, [0, 1], 4, 0, b'0/1', [0, 0]),\n            (True, False, [0, 2], 2, 17, b'0/2', [0, 0]),\n            (False, False, [-1, -1], 3, 40, b'./.', [0, 0])],\n           [(True, False, [0, 0], 0, 0, b'0/0', [0, 0]),\n            (True, True, [0, 0], 0, 0, b'0|0', [0, 0]),\n            (False, False, [-1, -1], 0, 0, b'./.', [0, 0])],\n           [(True, False, [0, -1], 0, 0, b'0', [0, 0]),\n            (True, False, [0, 1], 0, 0, b'0/1', [0, 0]),\n            (True, True, [0, 2], 0, 0, b'0|2', [0, 0])]],\n          dtype=[('is_called', '?'), ('is_phased', '?'), ('genotype', 'i1', (2,)), ('DP', '<u2'), ('GQ', 'u1'), ('GT', 'S3'), ('HQ', '<i4', (2,))])\n    >>> c2d['genotype']\n    array([[[ 0,  0],\n            [ 0,  0],\n            [ 0,  1]],\n           [[ 0,  0],\n            [ 0,  0],\n            [ 0,  1]],\n           [[ 0,  0],\n            [ 1,  0],\n            [ 1,  1]],\n           [[ 0,  0],\n            [ 0,  1],\n            [ 0,  0]],\n           [[ 1,  2],\n            [ 2,  1],\n            [ 2,  2]],\n           [[ 0,  0],\n            [ 0,  0],\n            [ 0,  0]],\n           [[ 0,  1],\n            [ 0,  2],\n            [-1, -1]],\n           [[ 0,  0],\n            [ 0,  0],\n            [-1, -1]],\n           [[ 0, -1],\n            [ 0,  1],\n            [ 0,  2]]], dtype=int8)\n    >>> c2d['genotype'][3, :]\n    array([[0, 0],\n           [0, 1],\n           [0, 0]], dtype=int8)"
  },
  {
    "code": "def flags(self, index):\n        activeFlags = (Qt.ItemIsEnabled | Qt.ItemIsSelectable |\n                       Qt.ItemIsUserCheckable)\n        item = self.item(index)\n        column = index.column()\n        if column > 0 and not item.childCount():\n            activeFlags = activeFlags | Qt.ItemIsEditable\n        return activeFlags",
    "docstring": "Return the active flags for the given index. Add editable\n        flag to items other than the first column."
  },
  {
    "code": "def _check_minions_directories(pki_dir):\n    minions_accepted = os.path.join(pki_dir, salt.key.Key.ACC)\n    minions_pre = os.path.join(pki_dir, salt.key.Key.PEND)\n    minions_rejected = os.path.join(pki_dir, salt.key.Key.REJ)\n    minions_denied = os.path.join(pki_dir, salt.key.Key.DEN)\n    return minions_accepted, minions_pre, minions_rejected, minions_denied",
    "docstring": "Return the minion keys directory paths.\n\n    This function is a copy of salt.key.Key._check_minions_directories."
  },
  {
    "code": "def create_window(self):\n        self.undocked_window = window = PluginWindow(self)\n        window.setAttribute(Qt.WA_DeleteOnClose)\n        icon = self.get_plugin_icon()\n        if is_text_string(icon):\n            icon = self.get_icon(icon)\n        window.setWindowIcon(icon)\n        window.setWindowTitle(self.get_plugin_title())\n        window.setCentralWidget(self)\n        window.resize(self.size())\n        self.refresh_plugin()\n        self.dockwidget.setFloating(False)\n        self.dockwidget.setVisible(False)\n        window.show()",
    "docstring": "Create a QMainWindow instance containing this plugin."
  },
  {
    "code": "def clear_conditions(self, *conkeys, **noclear):\n        offenders = set(conkeys) - set(self.conconf.conditions.keys())\n        if offenders:\n            raise KeyError(', '.join([off for off in offenders]))\n        offenders = set(noclear) - set({'noclear'})\n        if offenders:\n            raise KeyError(', '.join([off for off in offenders]))\n        noclear = noclear.get('noclear', False)\n        for ck in self.conconf.conditions:\n            if not conkeys:\n                self.conconf.reset()\n                break\n            elif not noclear and ck in conkeys:\n                self.conconf.set_condition(ck, None)\n            elif noclear and ck not in conkeys:\n                self.conconf.set_condition(ck, None)\n        if not self.no_auto:\n            self.make_mask()",
    "docstring": "Clear conditions.\n\n        Clear only the conditions conkeys if specified. Clear only the\n        conditions not specified by conkeys if noclear is True (False\n        default).\n\n        .. note::\n           Updates the mask if not no_auto."
  },
  {
    "code": "def _calculate_day_cost(self, plan, period):\n        plan_pricings = plan.planpricing_set.order_by('-pricing__period').select_related('pricing')\n        selected_pricing = None\n        for plan_pricing in plan_pricings:\n            selected_pricing = plan_pricing\n            if plan_pricing.pricing.period <= period:\n                break\n        if selected_pricing:\n            return (selected_pricing.price / selected_pricing.pricing.period).quantize(Decimal('1.00'))\n        raise ValueError('Plan %s has no pricings.' % plan)",
    "docstring": "Finds most fitted plan pricing for a given period, and calculate day cost"
  },
  {
    "code": "def encode_offset_commit_request(cls, group, payloads):\n        return kafka.protocol.commit.OffsetCommitRequest[0](\n            consumer_group=group,\n            topics=[(\n                topic,\n                [(\n                    partition,\n                    payload.offset,\n                    payload.metadata)\n                for partition, payload in six.iteritems(topic_payloads)])\n            for topic, topic_payloads in six.iteritems(group_by_topic_and_partition(payloads))])",
    "docstring": "Encode an OffsetCommitRequest struct\n\n        Arguments:\n            group: string, the consumer group you are committing offsets for\n            payloads: list of OffsetCommitRequestPayload"
  },
  {
    "code": "def face_adjacency(self):\n        adjacency, edges = graph.face_adjacency(mesh=self,\n                                                return_edges=True)\n        self._cache['face_adjacency_edges'] = edges\n        return adjacency",
    "docstring": "Find faces that share an edge, which we call here 'adjacent'.\n\n        Returns\n        ----------\n        adjacency : (n,2) int\n          Pairs of faces which share an edge\n\n        Examples\n        ---------\n\n        In [1]: mesh = trimesh.load('models/featuretype.STL')\n\n        In [2]: mesh.face_adjacency\n        Out[2]:\n        array([[   0,    1],\n               [   2,    3],\n               [   0,    3],\n               ...,\n               [1112,  949],\n               [3467, 3475],\n               [1113, 3475]])\n\n        In [3]: mesh.faces[mesh.face_adjacency[0]]\n        Out[3]:\n        TrackedArray([[   1,    0,  408],\n                      [1239,    0,    1]], dtype=int64)\n\n        In [4]: import networkx as nx\n\n        In [5]: graph = nx.from_edgelist(mesh.face_adjacency)\n\n        In [6]: groups = nx.connected_components(graph)"
  },
  {
    "code": "def aggregate_repeated_calls(frame, options):\n    if frame is None:\n        return None\n    children_by_identifier = {}\n    for child in frame.children:\n        if child.identifier in children_by_identifier:\n            aggregate_frame = children_by_identifier[child.identifier]\n            aggregate_frame.self_time += child.self_time\n            if child.children:\n                aggregate_frame.add_children(child.children)\n            child.remove_from_parent()\n        else:\n            children_by_identifier[child.identifier] = child\n    for child in frame.children:\n        aggregate_repeated_calls(child, options=options)\n    frame._children.sort(key=methodcaller('time'), reverse=True)\n    return frame",
    "docstring": "Converts a timeline into a time-aggregate summary.\n\n    Adds together calls along the same call stack, so that repeated calls appear as the same\n    frame. Removes time-linearity - frames are sorted according to total time spent.\n\n    Useful for outputs that display a summary of execution (e.g. text and html outputs)"
  },
  {
    "code": "def connected_objects(self, from_obj):\n        return self.to_content_type.get_all_objects_for_this_type(pk__in=self.connected_object_ids(from_obj))",
    "docstring": "Returns a query set matching all connected objects with the given\n        object as a source."
  },
  {
    "code": "def get_fullsize(self, kwargs):\n        fullsize_args = {}\n        if 'absolute' in kwargs:\n            fullsize_args['absolute'] = kwargs['absolute']\n        for key in ('width', 'height', 'quality', 'format', 'background', 'crop'):\n            fsk = 'fullsize_' + key\n            if fsk in kwargs:\n                fullsize_args[key] = kwargs[fsk]\n        img_fullsize, _ = self.get_rendition(1, **fullsize_args)\n        return img_fullsize",
    "docstring": "Get the fullsize rendition URL"
  },
  {
    "code": "def get_instance(self, payload):\n        return InviteInstance(\n            self._version,\n            payload,\n            service_sid=self._solution['service_sid'],\n            channel_sid=self._solution['channel_sid'],\n        )",
    "docstring": "Build an instance of InviteInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.chat.v2.service.channel.invite.InviteInstance\n        :rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance"
  },
  {
    "code": "def subscribe_list(self, list_id):\n        return List(tweepy_list_to_json(self._client.subscribe_list(list_id=list_id)))",
    "docstring": "Subscribe to a list\n\n        :param list_id: list ID number\n        :return: :class:`~responsebot.models.List` object"
  },
  {
    "code": "def abbreviate_tab_names_changed(self, settings, key, user_data):\n        abbreviate_tab_names = settings.get_boolean('abbreviate-tab-names')\n        self.guake.abbreviate = abbreviate_tab_names\n        self.guake.recompute_tabs_titles()",
    "docstring": "If the gconf var abbreviate_tab_names be changed, this method will\n        be called and will update tab names."
  },
  {
    "code": "def get_sdb_keys(self, path):\n        list_resp = get_with_retry(\n            self.cerberus_url + '/v1/secret/' + path + '/?list=true',\n            headers=self.HEADERS\n        )\n        throw_if_bad_response(list_resp)\n        return list_resp.json()['data']['keys']",
    "docstring": "Return the keys for a SDB, which are need for the full secure data path"
  },
  {
    "code": "def set_features(self):\n        allpsms_str = readers.generate_psms_multiple_fractions_strings(\n            self.mergefiles, self.ns)\n        allpeps = preparation.merge_peptides(self.mergefiles, self.ns)\n        self.features = {'psm': allpsms_str, 'peptide': allpeps}",
    "docstring": "Merge all psms and peptides"
  },
  {
    "code": "def update_rejection_permissions(portal):\n    updated = update_rejection_permissions_for(portal, \"bika_ar_workflow\",\n                                               \"Reject Analysis Request\")\n    if updated:\n        brains = api.search(dict(portal_type=\"AnalysisRequest\"),\n                            CATALOG_ANALYSIS_REQUEST_LISTING)\n        update_rolemappings_for(brains, \"bika_ar_workflow\")\n    updated = update_rejection_permissions_for(portal, \"bika_sample_workflow\",\n                                               \"Reject Sample\")\n    if updated:\n        brains = api.search(dict(portal_type=\"Sample\"), \"bika_catalog\")\n        update_rolemappings_for(brains, \"bika_sample_workflow\")",
    "docstring": "Adds the permission 'Reject Analysis Request' and update the permission\n     mappings accordingly"
  },
  {
    "code": "def _annotate_query(query, generate_dict):\n    annotate_key_list = []\n    for field_name, annotate_dict in generate_dict.items():\n        for annotate_name, annotate_func in annotate_dict[\"annotate_dict\"].items():\n            query = annotate_func(query)\n            annotate_key_list.append(annotate_name)\n    return query, annotate_key_list",
    "docstring": "Add annotations to the query to retrieve values required by field value generate\n    functions."
  },
  {
    "code": "def removeSingleCachedFile(self, fileStoreID):\n        with self._CacheState.open(self) as cacheInfo:\n            cachedFile = self.encodedFileID(fileStoreID)\n            cachedFileStats = os.stat(cachedFile)\n            assert cachedFileStats.st_nlink <= self.nlinkThreshold, \\\n                   'Attempting to delete a global file that is in use by another job.'\n            assert cachedFileStats.st_nlink >= self.nlinkThreshold, \\\n                   'A global file has too FEW links at deletion time. Our link threshold is incorrect!'\n            os.remove(cachedFile)\n            if self.nlinkThreshold != 2:\n                cacheInfo.cached -= cachedFileStats.st_size\n            if not cacheInfo.isBalanced():\n                self.logToMaster('CACHE: The cache was not balanced on removing single file',\n                                 logging.WARN)\n            self.logToMaster('CACHE: Successfully removed file with ID \\'%s\\'.' % fileStoreID)\n        return None",
    "docstring": "Removes a single file described by the fileStoreID from the cache forcibly."
  },
  {
    "code": "def expand(self, msgpos):\n        MT = self._tree[msgpos]\n        MT.expand(MT.root)",
    "docstring": "expand message at given position"
  },
  {
    "code": "def _build_url(self, shorten=True):\n        self.url = URL_FORMAT.format(*self._get_url_params(shorten=shorten))",
    "docstring": "Build the url for a cable ratings page"
  },
  {
    "code": "def status(self):\n        hw_type, name, major, minor, patch, status = self.rpc(0x00, 0x04, result_format=\"H6sBBBB\")\n        status = {\n            'hw_type': hw_type,\n            'name': name.decode('utf-8'),\n            'version': (major, minor, patch),\n            'status': status\n        }\n        return status",
    "docstring": "Query the status of an IOTile including its name and version"
  },
  {
    "code": "async def find_backwards(self, stream_name, predicate, predicate_label='predicate'):\n        logger = self._logger.getChild(predicate_label)\n        logger.info('Fetching first matching event')\n        uri = self._head_uri\n        try:\n            page = await self._fetcher.fetch(uri)\n        except HttpNotFoundError as e:\n            raise StreamNotFoundError() from e\n        while True:\n            evt = next(page.iter_events_matching(predicate), None)\n            if evt is not None:\n                return evt\n            uri = page.get_link(\"next\")\n            if uri is None:\n                logger.warning(\"No matching event found\")\n                return None\n            page = await self._fetcher.fetch(uri)",
    "docstring": "Return first event matching predicate, or None if none exists.\n\n        Note: 'backwards', both here and in Event Store, means 'towards the\n        event emitted furthest in the past'."
  },
  {
    "code": "def disconnect(self, callback):\n        try:\n            self._callbacks.remove(callback)\n        except ValueError:\n            self._callbacks.remove(ref(callback))",
    "docstring": "Disconnects a callback from this signal.\n\n        :param callback: The callback to disconnect.\n        :param weak: A flag that must have the same value than the one\n            specified during the call to `connect`.\n\n        .. warning::\n            If the callback is not connected at the time of call, a\n            :class:`ValueError` exception is thrown.\n\n        .. note::\n            You may call `disconnect` from a connected callback."
  },
  {
    "code": "def financial_float(s, scale_factor=1, typ=float,\n                    ignore=FINANCIAL_WHITESPACE,\n                    percent_str=PERCENT_SYMBOLS,\n                    replace=FINANCIAL_MAPPING,\n                    normalize_case=str.lower):\n    percent_scale_factor = 1\n    if isinstance(s, basestring):\n        s = normalize_case(s).strip()\n        for i in ignore:\n            s = s.replace(normalize_case(i), '')\n        s = s.strip()\n        for old, new in replace:\n            s = s.replace(old, new)\n        for p in percent_str:\n            if s.endswith(p):\n                percent_scale_factor *= 0.01\n                s = s[:-len(p)]\n    try:\n        return (scale_factor if scale_factor < 1 else percent_scale_factor) * typ(float(s))\n    except (ValueError, TypeError):\n        return s",
    "docstring": "Strip dollar signs and commas from financial numerical string\n\n    Also, convert percentages to fractions/factors (generally between 0 and 1.0)\n\n    >>> [financial_float(x) for x in (\"12k Flat\", \"12,000 flat\", \"20%\", \"$10,000 Flat\", \"15K flat\", \"null\", \"None\", \"\", None)]\n    [12000.0, 12000.0, 0.2, 10000.0, 15000.0, 'null', 'none', '', None]"
  },
  {
    "code": "def traverse_until_fixpoint(predicate, tree):\n    old_tree = None\n    tree = simplify(tree)\n    while tree and old_tree != tree:\n        old_tree = tree\n        tree = tree.traverse(predicate)\n        if not tree:\n            return None\n        tree = simplify(tree)\n    return tree",
    "docstring": "Traverses the tree again and again until it is not modified."
  },
  {
    "code": "def fill_transaction_defaults(web3, transaction):\n    defaults = {}\n    for key, default_getter in TRANSACTION_DEFAULTS.items():\n        if key not in transaction:\n            if callable(default_getter):\n                if web3 is not None:\n                    default_val = default_getter(web3, transaction)\n                else:\n                    raise ValueError(\"You must specify %s in the transaction\" % key)\n            else:\n                default_val = default_getter\n            defaults[key] = default_val\n    return merge(defaults, transaction)",
    "docstring": "if web3 is None, fill as much as possible while offline"
  },
  {
    "code": "def upoint2bddpoint(upoint):\n    point = dict()\n    for uniqid in upoint[0]:\n        point[_VARS[uniqid]] = 0\n    for uniqid in upoint[1]:\n        point[_VARS[uniqid]] = 1\n    return point",
    "docstring": "Convert an untyped point into a BDD point.\n\n    .. seealso::\n       For definitions of points and untyped points,\n       see the :mod:`pyeda.boolalg.boolfunc` module."
  },
  {
    "code": "def _six_fail_hook(modname):\n    attribute_of = modname != \"six.moves\" and modname.startswith(\"six.moves\")\n    if modname != \"six.moves\" and not attribute_of:\n        raise AstroidBuildingError(modname=modname)\n    module = AstroidBuilder(MANAGER).string_build(_IMPORTS)\n    module.name = \"six.moves\"\n    if attribute_of:\n        start_index = len(module.name)\n        attribute = modname[start_index:].lstrip(\".\").replace(\".\", \"_\")\n        try:\n            import_attr = module.getattr(attribute)[0]\n        except AttributeInferenceError:\n            raise AstroidBuildingError(modname=modname)\n        if isinstance(import_attr, nodes.Import):\n            submodule = MANAGER.ast_from_module_name(import_attr.names[0][0])\n            return submodule\n    return module",
    "docstring": "Fix six.moves imports due to the dynamic nature of this\n    class.\n\n    Construct a pseudo-module which contains all the necessary imports\n    for six\n\n    :param modname: Name of failed module\n    :type modname: str\n\n    :return: An astroid module\n    :rtype: nodes.Module"
  },
  {
    "code": "def get_orgs(self):\n        orgs = []\n        for resource in self._get_orgs()['resources']:\n            orgs.append(resource['entity']['name'])\n        return orgs",
    "docstring": "Returns a flat list of the names for the organizations\n        user belongs."
  },
  {
    "code": "def validate_pro():\n    cmd = ['python3', 'validate.py', FLAGS.pro_dataset,\n           '--use_tpu',\n           '--tpu_name={}'.format(TPU_NAME),\n           '--work_dir={}'.format(fsdb.working_dir()),\n           '--flagfile=rl_loop/distributed_flags',\n           '--validate_name=pro']\n    mask_flags.run(cmd)",
    "docstring": "Validate on professional data."
  },
  {
    "code": "def _check_for_duplicates(durations, events):\n        df = pd.DataFrame({\"t\": durations, \"e\": events})\n        dup_times = df.loc[df[\"e\"] != 0, \"t\"].duplicated(keep=False)\n        dup_events = df.loc[df[\"e\"] != 0, [\"t\", \"e\"]].duplicated(keep=False)\n        return (dup_times & (~dup_events)).any()",
    "docstring": "Checks for duplicated event times in the data set. This is narrowed to detecting duplicated event times\n        where the events are of different types"
  },
  {
    "code": "def __copy_extracted(self, path, destination):\n        unpacked_dir = self.filename + '.unpacked'\n        if not os.path.isdir(unpacked_dir):\n            LOGGER.warn(\n                'Failed to copy extracted file %s, no extracted dir',\n                path\n            )\n            return\n        source_path = os.path.join(unpacked_dir, path)\n        if not os.path.exists(source_path):\n            LOGGER.warn(\n                'Failed to copy extracted file %s, does not exist',\n                path\n            )\n            return\n        destination_path = os.path.join(destination, path)\n        shutil.copyfile(source_path, destination_path)",
    "docstring": "Copies a file that was already extracted to the destination directory.\n\n        Args:\n            path (str):\n                Relative (to the root of the archive) of the file to copy.\n\n            destination (str):\n                Directory to extract the archive to."
  },
  {
    "code": "def best_assemblyfile(self):\n        for sample in self.metadata:\n            try:\n                filtered_outputfile = os.path.join(self.path, 'raw_assemblies', '{}.fasta'.format(sample.name))\n                if os.path.isfile(sample.general.assemblyfile):\n                    size = os.path.getsize(sample.general.assemblyfile)\n                    if size == 0:\n                        sample.general.bestassemblyfile = 'NA'\n                    else:\n                        sample.general.bestassemblyfile = sample.general.assemblyfile\n                        shutil.copyfile(sample.general.bestassemblyfile, filtered_outputfile)\n                else:\n                    sample.general.bestassemblyfile = 'NA'\n                sample.general.filteredfile = filtered_outputfile\n            except AttributeError:\n                sample.general.assemblyfile = 'NA'\n                sample.general.bestassemblyfile = 'NA'",
    "docstring": "Determine whether the contigs.fasta output file from the assembler is present. If not, set the .bestassembly\n        attribute to 'NA'"
  },
  {
    "code": "def qgis_version_detailed():\n    version = str(Qgis.QGIS_VERSION_INT)\n    return [int(version[0]), int(version[1:3]), int(version[3:])]",
    "docstring": "Get the detailed version of QGIS.\n\n    :returns: List containing major, minor and patch.\n    :rtype: list"
  },
  {
    "code": "def stopThread(self):\n        if self._thread is not None:\n            self.performSelector_onThread_withObject_waitUntilDone_('stopPowerNotificationsThread', self._thread, None, objc.YES)\n            self._thread = None",
    "docstring": "Stops spawned NSThread."
  },
  {
    "code": "def inspect_streamer(self, index):\n        if index >= len(self.graph.streamers):\n            return [_pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED), b'\\0'*14]\n        return [Error.NO_ERROR, streamer_descriptor.create_binary_descriptor(self.graph.streamers[index])]",
    "docstring": "Inspect the streamer at the given index."
  },
  {
    "code": "def augment_excmessage(prefix=None, suffix=None) -> NoReturn:\n    exc_old = sys.exc_info()[1]\n    message = str(exc_old)\n    if prefix is not None:\n        message = f'{prefix}, the following error occurred: {message}'\n    if suffix is not None:\n        message = f'{message} {suffix}'\n    try:\n        exc_new = type(exc_old)(message)\n    except BaseException:\n        exc_name = str(type(exc_old)).split(\"'\")[1]\n        exc_type = type(exc_name, (BaseException,), {})\n        exc_type.__module = exc_old.__module__\n        raise exc_type(message) from exc_old\n    raise exc_new from exc_old",
    "docstring": "Augment an exception message with additional information while keeping\n    the original traceback.\n\n    You can prefix and/or suffix text.  If you prefix something (which happens\n    much more often in the HydPy framework), the sub-clause ', the following\n    error occurred:' is automatically included:\n\n    >>> from hydpy.core import objecttools\n    >>> import textwrap\n    >>> try:\n    ...     1 + '1'\n    ... except BaseException:\n    ...     prefix = 'While showing how prefixing works'\n    ...     suffix = '(This is a final remark.)'\n    ...     objecttools.augment_excmessage(prefix, suffix)\n    Traceback (most recent call last):\n    ...\n    TypeError: While showing how prefixing works, the following error \\\noccurred: unsupported operand type(s) for +: 'int' and 'str' \\\n(This is a final remark.)\n\n    Some exceptions derived by site-packages do not support exception\n    chaining due to requiring multiple initialisation arguments.\n    In such cases, |augment_excmessage| generates an exception with the\n    same name on the fly and raises it afterwards, which is pointed out\n    by the exception name mentioning to the \"objecttools\" module:\n\n    >>> class WrongError(BaseException):\n    ...     def __init__(self, arg1, arg2):\n    ...         pass\n    >>> try:\n    ...     raise WrongError('info 1', 'info 2')\n    ... except BaseException:\n    ...     objecttools.augment_excmessage(\n    ...         'While showing how prefixing works')\n    Traceback (most recent call last):\n    ...\n    hydpy.core.objecttools.hydpy.core.objecttools.WrongError: While showing \\\nhow prefixing works, the following error occurred: ('info 1', 'info 2')"
  },
  {
    "code": "def _sha1_for_file(filename):\n    with open(filename, \"rb\") as fileobj:\n        contents = fileobj.read()\n        return hashlib.sha1(contents).hexdigest()",
    "docstring": "Return sha1 for contents of filename."
  },
  {
    "code": "def single_device_data_message(self,\n                                   registration_id=None,\n                                   condition=None,\n                                   collapse_key=None,\n                                   delay_while_idle=False,\n                                   time_to_live=None,\n                                   restricted_package_name=None,\n                                   low_priority=False,\n                                   dry_run=False,\n                                   data_message=None,\n                                   content_available=None,\n                                   android_channel_id=None,\n                                   timeout=5,\n                                   extra_notification_kwargs=None,\n                                   extra_kwargs={}):\n        if registration_id is None:\n            raise InvalidDataError('Invalid registration ID')\n        payload = self.parse_payload(\n            registration_ids=[registration_id],\n            condition=condition,\n            collapse_key=collapse_key,\n            delay_while_idle=delay_while_idle,\n            time_to_live=time_to_live,\n            restricted_package_name=restricted_package_name,\n            low_priority=low_priority,\n            dry_run=dry_run,\n            data_message=data_message,\n            content_available=content_available,\n            remove_notification=True,\n            android_channel_id=android_channel_id,\n            extra_notification_kwargs=extra_notification_kwargs,\n            **extra_kwargs\n        )\n        self.send_request([payload], timeout)\n        return self.parse_responses()",
    "docstring": "Send push message to a single device\n\n        Args:\n            registration_id (list, optional): FCM device registration ID\n            condition (str, optiona): Topic condition to deliver messages to\n            collapse_key (str, optional): Identifier for a group of messages\n                that can be collapsed so that only the last message gets sent\n                when delivery can be resumed. Defaults to `None`.\n            delay_while_idle (bool, optional): deprecated\n            time_to_live (int, optional): How long (in seconds) the message\n                should be kept in FCM storage if the device is offline. The\n                maximum time to live supported is 4 weeks. Defaults to `None`\n                which uses the FCM default of 4 weeks.\n            restricted_package_name (str, optional): Name of package\n            low_priority (bool, optional): Whether to send notification with\n                the low priority flag. Defaults to `False`.\n            dry_run (bool, optional): If `True` no message will be sent but request will be tested.\n            data_message (dict, optional): Custom key-value pairs\n            content_available (bool, optional): Inactive client app is awoken\n            android_channel_id (str, optional): Starting in Android 8.0 (API level 26),\n                all notifications must be assigned to a channel. For each channel, you can set the\n                visual and auditory behavior that is applied to all notifications in that channel.\n                Then, users can change these settings and decide which notification channels from\n                your app should be intrusive or visible at all.\n            timeout (int, optional): set time limit for the request\n            extra_notification_kwargs (dict, optional): More notification keyword arguments\n            extra_kwargs (dict, optional): More keyword arguments\n\n        Returns:\n            dict: Response from FCM server (`multicast_id`, `success`, `failure`, `canonical_ids`, `results`)\n\n        Raises:\n            AuthenticationError: If :attr:`api_key` is not set or provided\n                or there is an error authenticating the sender.\n            FCMServerError: Internal server error or timeout error on Firebase cloud messaging server\n            InvalidDataError: Invalid data provided\n            InternalPackageError: Mostly from changes in the response of FCM,\n                contact the project owner to resolve the issue"
  },
  {
    "code": "def submit(self, command=\"\", blocksize=1, job_name=\"parsl.auto\"):\n        instance, name = self.create_instance(command=command)\n        self.provisioned_blocks += 1\n        self.resources[name] = {\"job_id\": name, \"status\": translate_table[instance['status']]}\n        return name",
    "docstring": "The submit method takes the command string to be executed upon\n        instantiation of a resource most often to start a pilot.\n\n        Args :\n             - command (str) : The bash command string to be executed.\n             - blocksize (int) : Blocksize to be requested\n\n        KWargs:\n             - job_name (str) : Human friendly name to be assigned to the job request\n\n        Returns:\n             - A job identifier, this could be an integer, string etc\n\n        Raises:\n             - ExecutionProviderException or its subclasses"
  },
  {
    "code": "def fillna(series_or_arr, missing_value=0.0):\n    if pandas.notnull(missing_value):\n        if isinstance(series_or_arr, (numpy.ndarray)):\n            series_or_arr[numpy.isnan(series_or_arr)] = missing_value\n        else:\n            series_or_arr.fillna(missing_value, inplace=True)\n    return series_or_arr",
    "docstring": "Fill missing values in pandas objects and numpy arrays.\n\n    Arguments\n    ---------\n    series_or_arr : pandas.Series, numpy.ndarray\n        The numpy array or pandas series for which the missing values\n        need to be replaced.\n    missing_value : float, int, str\n        The value to replace the missing value with. Default 0.0.\n\n    Returns\n    -------\n    pandas.Series, numpy.ndarray\n        The numpy array or pandas series with the missing values\n        filled."
  },
  {
    "code": "def _effective_view_filter(self):\n        if self._effective_view == EFFECTIVE:\n            now = datetime.datetime.utcnow()\n            return {'startDate': {'$$lte': now}, 'endDate': {'$$gte': now}}\n        return {}",
    "docstring": "Returns the mongodb relationship filter for effective views"
  },
  {
    "code": "def save(self):\n        if not self.is_valid():\n            return self._errors\n        _new = self.is_new()\n        if _new:\n            self._initialize_id()\n        with Mutex(self):\n            self._write(_new)\n        return True",
    "docstring": "Saves the instance to the datastore."
  },
  {
    "code": "def ustr(obj):\n    if sys.version_info[0] == 2:\n        if type(obj) in [str, basestring]:\n            return unicode(obj, DEFAULT_ENCODING)\n        else:\n            return unicode(obj)\n    else:\n        if type(obj) in [bytes]:\n            return obj.decode(DEFAULT_ENCODING)\n        else:\n            return str(obj)",
    "docstring": "Python 2 and 3 utility method that converts an obj to unicode in python 2 and to a str object in python 3"
  },
  {
    "code": "def delete_resourcegroupitems(scenario_id, item_ids, **kwargs):\n    user_id = int(kwargs.get('user_id'))\n    _get_scenario(scenario_id, user_id)\n    for item_id in item_ids:\n        rgi = db.DBSession.query(ResourceGroupItem).\\\n                filter(ResourceGroupItem.id==item_id).one()\n        db.DBSession.delete(rgi)\n    db.DBSession.flush()",
    "docstring": "Delete specified items in a group, in a scenario."
  },
  {
    "code": "def write_tree_newick(self, filename, hide_rooted_prefix=False):\n        if not isinstance(filename, str):\n            raise TypeError(\"filename must be a str\")\n        treestr = self.newick()\n        if hide_rooted_prefix:\n            if treestr.startswith('[&R]'):\n                treestr = treestr[4:].strip()\n            else:\n                warn(\"Specified hide_rooted_prefix, but tree was not rooted\")\n        if filename.lower().endswith('.gz'):\n            f = gopen(expanduser(filename),'wb',9); f.write(treestr.encode()); f.close()\n        else:\n            f = open(expanduser(filename),'w'); f.write(treestr); f.close()",
    "docstring": "Write this ``Tree`` to a Newick file\n\n        Args:\n            ``filename`` (``str``): Path to desired output file (plain-text or gzipped)"
  },
  {
    "code": "def get_schema_dir(db_version=1):\n    v = str(db_version)\n    return os.path.join(_top_dir, '..', 'schemata', 'versions', v)",
    "docstring": "Get path to directory with schemata.\n\n    :param db_version: Version of the database\n    :type db_version: int\n    :return: Path\n    :rtype: str"
  },
  {
    "code": "def copy_graph(subject, existing_graph):\n    new_graph = rdflib.Graph()\n    for predicate, object_ in existing_graph.predicate_objects():\n        new_graph.add((subject, predicate, object_))\n    return new_graph",
    "docstring": "Function takes a subject and an existing graph, returns a new graph with\n    all predicate and objects of the existing graph copied to the new_graph with\n    subject as the new subject\n\n    Args:\n        subject(rdflib.URIRef): A URIRef subject\n        existing_graph(rdflib.Graph): A rdflib.Graph\n\n    Returns:\n        rdflib.Graph"
  },
  {
    "code": "def temporal_segmentation(segments, min_time):\n    final_segments = []\n    for segment in segments:\n        final_segments.append([])\n        for point in segment:\n            if point.dt > min_time:\n                final_segments.append([])\n            final_segments[-1].append(point)\n    return final_segments",
    "docstring": "Segments based on time distant points\n\n    Args:\n        segments (:obj:`list` of :obj:`list` of :obj:`Point`): segment points\n        min_time (int): minimum required time for segmentation"
  },
  {
    "code": "def xml_entity_escape(data):\n    data = data.replace(\"&\", \"&amp;\")\n    data = data.replace(\">\", \"&gt;\")\n    data = data.replace(\"<\", \"&lt;\")\n    return data",
    "docstring": "replace special characters with their XML entity versions"
  },
  {
    "code": "def _apply_mapping(self, mapping):\n        self._POST[\"P0100LDR__\"] = mapping[0]\n        self._POST[\"P0200FMT__\"] = mapping[1]\n        self._POST[\"P0300BAS__a\"] = mapping[2]\n        self._POST[\"P07022001_b\"] = mapping[3]\n        self._POST[\"P1501IST1_a\"] = mapping[4]",
    "docstring": "Map some case specific data to the fields in internal dictionary."
  },
  {
    "code": "def mount(dev, mountpoint, flags='', log=None):\n    ensureDirectory(mountpoint)\n    systemCall('mount %s %s %s' % (flags, dev, mountpoint),\n               log=log)",
    "docstring": "Mount the given dev to the given mountpoint by using the given flags"
  },
  {
    "code": "def unpause(self):\n        self._pause_level -= 1\n        if not self._pause_level:\n            self._offset = self._paused_time - self._clock()",
    "docstring": "Unpause the animation."
  },
  {
    "code": "async def read(self) -> bytes:\n        if self._read_bytes is None:\n            body = bytearray()\n            while True:\n                chunk = await self._payload.readany()\n                body.extend(chunk)\n                if self._client_max_size:\n                    body_size = len(body)\n                    if body_size >= self._client_max_size:\n                        raise HTTPRequestEntityTooLarge(\n                            max_size=self._client_max_size,\n                            actual_size=body_size\n                        )\n                if not chunk:\n                    break\n            self._read_bytes = bytes(body)\n        return self._read_bytes",
    "docstring": "Read request body if present.\n\n        Returns bytes object with full request content."
  },
  {
    "code": "def to_pandas(self):\n        if not self.is_raw():\n            raise ValueError('Cannot convert to pandas Index if not evaluated.')\n        from pandas import Index as PandasIndex\n        return PandasIndex(self.values,\n                           self.dtype,\n                           name=self.name)",
    "docstring": "Convert to pandas Index.\n\n        Returns\n        -------\n        pandas.base.Index"
  },
  {
    "code": "def is_builtin(text):\r\n    from spyder.py3compat import builtins\r\n    return text in [str(name) for name in dir(builtins)\r\n                    if not name.startswith('_')]",
    "docstring": "Test if passed string is the name of a Python builtin object"
  },
  {
    "code": "def read_creds_from_environment_variables():\n    creds = init_creds()\n    if 'AWS_ACCESS_KEY_ID' in os.environ and 'AWS_SECRET_ACCESS_KEY' in os.environ:\n        creds['AccessKeyId'] = os.environ['AWS_ACCESS_KEY_ID']\n        creds['SecretAccessKey'] = os.environ['AWS_SECRET_ACCESS_KEY']\n        if 'AWS_SESSION_TOKEN' in os.environ:\n            creds['SessionToken'] = os.environ['AWS_SESSION_TOKEN']\n    return creds",
    "docstring": "Read credentials from environment variables\n\n    :return:"
  },
  {
    "code": "def set_transform_interface_params(spec, input_features, output_features, are_optional = False):\n    input_features = _fm.process_or_validate_features(input_features)\n    output_features = _fm.process_or_validate_features(output_features)\n    for (fname, ftype) in input_features:\n        input_ = spec.description.input.add()\n        input_.name = fname\n        datatypes._set_datatype(input_.type, ftype)\n        if are_optional:\n            input_.type.isOptional = are_optional\n    for (fname, ftype) in output_features:\n        output_ = spec.description.output.add()\n        output_.name = fname\n        datatypes._set_datatype(output_.type, ftype)\n    return spec",
    "docstring": "Common utilities to set transform interface params."
  },
  {
    "code": "def get_specific_nodes(self, node, names):\n        nodes = [(x.tagName, x) for x in node.childNodes\n                 if x.nodeType == x.ELEMENT_NODE and\n                 x.tagName in names]\n        return dict(nodes)",
    "docstring": "Given a node and a sequence of strings in `names`, return a\n        dictionary containing the names as keys and child\n        `ELEMENT_NODEs`, that have a `tagName` equal to the name."
  },
  {
    "code": "def generate_manifest(self, progressbar=None):\n        items = dict()\n        if progressbar:\n            progressbar.label = \"Generating manifest\"\n        for handle in self._storage_broker.iter_item_handles():\n            key = dtoolcore.utils.generate_identifier(handle)\n            value = self._storage_broker.item_properties(handle)\n            items[key] = value\n            if progressbar:\n                progressbar.item_show_func = lambda x: handle\n                progressbar.update(1)\n        manifest = {\n            \"items\": items,\n            \"dtoolcore_version\": __version__,\n            \"hash_function\": self._storage_broker.hasher.name\n        }\n        return manifest",
    "docstring": "Return manifest generated from knowledge about contents."
  },
  {
    "code": "def _get_params(self):\n        params = {'accountNumber': self._service.accountNumber}\n        for key, val in self.__dict__.iteritems():\n            if key in self.field_order:\n                if isinstance(val, str,):\n                    val = val.decode('utf8')\n                params[key] = val\n        for key in self.field_order:\n            if key not in params:\n                params[key] = u''\n        def order_keys(k):\n            if k[0] in self.field_order:\n                return self.field_order.index(k[0])\n            return len(self.field_order) + 1\n        params = OrderedDict(sorted(params.items(), key=order_keys))\n        if hasattr(self, 'hash') and self.hash is not None:\n            params['hash'] = self.hash\n        return params",
    "docstring": "Generate SOAP parameters."
  },
  {
    "code": "def _verify_cert(self, sock: ssl.SSLSocket):\n        verify_mode = self._ssl_context.verify_mode\n        assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED,\n                               ssl.CERT_OPTIONAL), \\\n            'Unknown verify mode {}'.format(verify_mode)\n        if verify_mode == ssl.CERT_NONE:\n            return\n        cert = sock.getpeercert()\n        if not cert and verify_mode == ssl.CERT_OPTIONAL:\n            return\n        if not cert:\n            raise SSLVerificationError('No SSL certificate given')\n        try:\n            ssl.match_hostname(cert, self._hostname)\n        except ssl.CertificateError as error:\n            raise SSLVerificationError('Invalid SSL certificate') from error",
    "docstring": "Check if certificate matches hostname."
  },
  {
    "code": "def fetch(self):\n        self.retrieveVals()\n        for parent_name in self._graphNames:\n            graph = self._graphDict[parent_name]\n            if self.isMultigraph:\n                print \"multigraph %s\" % self._getMultigraphID(parent_name)\n            print self._formatVals(graph.getVals())\n            print\n        if (self.isMultigraph and self._nestedGraphs \n            and self._subgraphDict and self._subgraphNames):\n            for (parent_name, subgraph_names) in self._subgraphNames.iteritems():\n                for graph_name in subgraph_names:\n                    graph = self._subgraphDict[parent_name][graph_name]\n                    print \"multigraph %s\" % self.getMultigraphID(parent_name, \n                                                                 graph_name)\n                    print self._formatVals(graph.getVals())\n                    print\n        return True",
    "docstring": "Implements Munin Plugin Fetch Option.\n\n        Prints out measured values."
  },
  {
    "code": "def combine_first(self, other):\n        new_index = self.index.union(other.index)\n        this = self.reindex(new_index, copy=False)\n        other = other.reindex(new_index, copy=False)\n        if is_datetimelike(this) and not is_datetimelike(other):\n            other = to_datetime(other)\n        return this.where(notna(this), other)",
    "docstring": "Combine Series values, choosing the calling Series's values first.\n\n        Parameters\n        ----------\n        other : Series\n            The value(s) to be combined with the `Series`.\n\n        Returns\n        -------\n        Series\n            The result of combining the Series with the other object.\n\n        See Also\n        --------\n        Series.combine : Perform elementwise operation on two Series\n            using a given function.\n\n        Notes\n        -----\n        Result index will be the union of the two indexes.\n\n        Examples\n        --------\n        >>> s1 = pd.Series([1, np.nan])\n        >>> s2 = pd.Series([3, 4])\n        >>> s1.combine_first(s2)\n        0    1.0\n        1    4.0\n        dtype: float64"
  },
  {
    "code": "def batch(self, timelimit=None):\n        from .launcher import BatchLauncher\n        prev_dir = os.path.join(*self.workdir.split(os.path.sep)[:-1])\n        prev_dir = os.path.join(os.path.sep, prev_dir)\n        workdir = os.path.join(prev_dir, os.path.basename(self.workdir) + \"_batch\")\n        return BatchLauncher(workdir=workdir, flows=self).submit(timelimit=timelimit)",
    "docstring": "Run the flow in batch mode, return exit status of the job script.\n        Requires a manager.yml file and a batch_adapter adapter.\n\n        Args:\n            timelimit: Time limit (int with seconds or string with time given with the slurm convention:\n            \"days-hours:minutes:seconds\"). If timelimit is None, the default value specified in the\n            `batch_adapter` entry of `manager.yml` is used."
  },
  {
    "code": "def get_monitor_pos(monitor):\n    xpos_value = ctypes.c_int(0)\n    xpos = ctypes.pointer(xpos_value)\n    ypos_value = ctypes.c_int(0)\n    ypos = ctypes.pointer(ypos_value)\n    _glfw.glfwGetMonitorPos(monitor, xpos, ypos)\n    return xpos_value.value, ypos_value.value",
    "docstring": "Returns the position of the monitor's viewport on the virtual screen.\n\n    Wrapper for:\n        void glfwGetMonitorPos(GLFWmonitor* monitor, int* xpos, int* ypos);"
  },
  {
    "code": "def _interface_to_service(iface):\n    for _service in _get_services():\n        service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service))\n        if service_info.get_property('Ethernet')['Interface'] == iface:\n            return _service\n    return None",
    "docstring": "returns the coresponding service to given interface if exists, otherwise return None"
  },
  {
    "code": "def send_mails(cls):\n        if settings.CAS_NEW_VERSION_EMAIL_WARNING and settings.ADMINS:\n            try:\n                obj = cls.objects.get()\n            except cls.DoesNotExist:\n                obj = NewVersionWarning.objects.create(version=VERSION)\n            LAST_VERSION = utils.last_version()\n            if LAST_VERSION is not None and LAST_VERSION != obj.version:\n                if utils.decode_version(VERSION) < utils.decode_version(LAST_VERSION):\n                    try:\n                        send_mail(\n                            (\n                                '%sA new version of django-cas-server is available'\n                            ) % settings.EMAIL_SUBJECT_PREFIX,\n                            u\n.strip() % (VERSION, LAST_VERSION),\n                            settings.SERVER_EMAIL,\n                            [\"%s <%s>\" % admin for admin in settings.ADMINS],\n                            fail_silently=False,\n                        )\n                        obj.version = LAST_VERSION\n                        obj.save()\n                    except smtplib.SMTPException as error:\n                        logger.error(\"Unable to send new version mail: %s\" % error)",
    "docstring": "For each new django-cas-server version, if the current instance is not up to date\n            send one mail to ``settings.ADMINS``."
  },
  {
    "code": "def get_logs(self, login=None, **kwargs):\n        _login = kwargs.get(\n            'login',\n            login\n        )\n        log_events_url = GSA_LOGS_URL.format(login=_login)\n        return self._request_api(url=log_events_url).json()",
    "docstring": "Get a user's logs.\n\n        :param str login: User's login (Default: self._login)\n        :return: JSON"
  },
  {
    "code": "def inet_ntop(af, addr):\n    addr = bytes_encode(addr)\n    try:\n        return socket.inet_ntop(af, addr)\n    except AttributeError:\n        try:\n            return _INET_NTOP[af](addr)\n        except KeyError:\n            raise ValueError(\"unknown address family %d\" % af)",
    "docstring": "Convert an IP address from binary form into text representation."
  },
  {
    "code": "def tsv_import(self, xsv_source, encoding=\"UTF-8\", transforms=None, row_class=DataObject, **kwargs):\n        return self._xsv_import(xsv_source, encoding, transforms=transforms, delimiter=\"\\t\", row_class=row_class, **kwargs)",
    "docstring": "Imports the contents of a tab-separated data file into this table.\n           @param xsv_source: tab-separated data file - if a string is given, the file with that name will be\n               opened, read, and closed; if a file object is given, then that object\n               will be read as-is, and left for the caller to be closed.\n           @type xsv_source: string or file\n           @param transforms: dict of functions by attribute name; if given, each\n               attribute will be transformed using the corresponding transform; if there is no\n               matching transform, the attribute will be read as a string (default); the\n               transform function can also be defined as a (function, default-value) tuple; if\n               there is an Exception raised by the transform function, then the attribute will\n               be set to the given default value\n           @type transforms: dict (optional)"
  },
  {
    "code": "def show(self):\n        with_matplotlib = True\n        try:\n            import matplotlib.pyplot as plt\n        except RuntimeError:\n            import skimage.io as io\n            with_matplotlib = False\n        if with_matplotlib:\n            equalised_img = self.equalise()\n            _, ax = plt.subplots()\n            ax.imshow(equalised_img, cmap='gray')\n            import random\n            for contour_set in self.as_contours.itervalues():\n                r, g, b = random.random(), random.random(), random.random()\n                [ax.plot(contour[:,1], contour[:,0], linewidth=2, color=(r,g,b,1)) for contour in contour_set]\n            ax.axis('image')\n            ax.set_xticks([])\n            ax.set_yticks([])\n            plt.show()\n        else:\n            io.imshow(self.equalise())\n            io.show()",
    "docstring": "Display the image"
  },
  {
    "code": "def find_outer_region(im, r=0):\n    r\n    if r == 0:\n        dt = spim.distance_transform_edt(input=im)\n        r = int(sp.amax(dt)) * 2\n    im_padded = sp.pad(array=im, pad_width=r, mode='constant',\n                       constant_values=True)\n    dt = spim.distance_transform_edt(input=im_padded)\n    seeds = (dt >= r) + get_border(shape=im_padded.shape)\n    labels = spim.label(seeds)[0]\n    mask = labels == 1\n    dt = spim.distance_transform_edt(~mask)\n    outer_region = dt < r\n    outer_region = extract_subsection(im=outer_region, shape=im.shape)\n    return outer_region",
    "docstring": "r\"\"\"\n    Finds regions of the image that are outside of the solid matrix.\n\n    This function uses the rolling ball method to define where the outer region\n    ends and the void space begins.\n\n    This function is particularly useful for samples that do not fill the\n    entire rectangular image, such as cylindrical cores or samples with non-\n    parallel faces.\n\n    Parameters\n    ----------\n    im : ND-array\n        Image of the porous material with 1's for void and 0's for solid\n\n    r : scalar\n        The radius of the rolling ball to use.  If not specified then a value\n        is calculated as twice maximum of the distance transform.  The image\n        size is padded by this amount in all directions, so the image can\n        become quite large and unwieldy if too large a value is given.\n\n    Returns\n    -------\n    image : ND-array\n        A boolean mask the same shape as ``im``, containing True in all voxels\n        identified as *outside* the sample."
  },
  {
    "code": "def to_valid_state_vector(state_rep: Union[int, np.ndarray],\n                          num_qubits: int,\n                          dtype: Type[np.number] = np.complex64) -> np.ndarray:\n    if isinstance(state_rep, np.ndarray):\n        if len(state_rep) != 2 ** num_qubits:\n            raise ValueError(\n                'initial state was of size {} '\n                'but expected state for {} qubits'.format(\n                    len(state_rep), num_qubits))\n        state = state_rep\n    elif isinstance(state_rep, int):\n        if state_rep < 0:\n            raise ValueError('initial_state must be positive')\n        elif state_rep >= 2 ** num_qubits:\n            raise ValueError(\n                'initial state was {} but expected state for {} qubits'.format(\n                    state_rep, num_qubits))\n        else:\n            state = np.zeros(2 ** num_qubits, dtype=dtype)\n            state[state_rep] = 1.0\n    else:\n        raise TypeError('initial_state was not of type int or ndarray')\n    validate_normalized_state(state, num_qubits, dtype)\n    return state",
    "docstring": "Verifies the state_rep is valid and converts it to ndarray form.\n\n    This method is used to support passing in an integer representing a\n    computational basis state or a full wave function as a representation of\n    a state.\n\n    Args:\n        state_rep: If an int, the state returned is the state corresponding to\n            a computational basis state. If an numpy array this is the full\n            wave function. Both of these are validated for the given number\n            of qubits, and the state must be properly normalized and of the\n            appropriate dtype.\n        num_qubits: The number of qubits for the state. The state_rep must be\n            valid for this number of qubits.\n        dtype: The numpy dtype of the state, will be used when creating the\n            state for a computational basis state, or validated against if\n            state_rep is a numpy array.\n\n    Returns:\n        A numpy ndarray corresponding to the state on the given number of\n        qubits.\n\n    Raises:\n        ValueError if the state is not valid."
  },
  {
    "code": "def Update(self, attribute=None):\n    currently_running = self.Get(self.Schema.CONTENT_LOCK)\n    if currently_running:\n      flow_obj = aff4.FACTORY.Open(currently_running, token=self.token)\n      if flow_obj and flow_obj.GetRunner().IsRunning():\n        return\n    client_id = self.urn.Path().split(\"/\", 2)[1]\n    pathspec = self.Get(self.Schema.STAT).pathspec\n    flow_urn = flow.StartAFF4Flow(\n        client_id=client_id,\n        flow_name=\"MultiGetFile\",\n        token=self.token,\n        pathspecs=[pathspec])\n    self.Set(self.Schema.CONTENT_LOCK(flow_urn))\n    self.Close()\n    return flow_urn",
    "docstring": "Update an attribute from the client."
  },
  {
    "code": "def alter_object(self, obj):\n        for attname, field, replacer in self.replacers:\n            currentval = getattr(obj, attname)\n            replacement = replacer(self, obj, field, currentval)\n            setattr(obj, attname, replacement)",
    "docstring": "Alters all the attributes in an individual object.\n\n        If it returns False, the object will not be saved"
  },
  {
    "code": "def get_page_square_dpi(pageinfo, options):\n    \"Get the DPI when we require xres == yres, scaled to physical units\"\n    xres = pageinfo.xres or 0\n    yres = pageinfo.yres or 0\n    userunit = pageinfo.userunit or 1\n    return float(\n        max(\n            (xres * userunit) or VECTOR_PAGE_DPI,\n            (yres * userunit) or VECTOR_PAGE_DPI,\n            VECTOR_PAGE_DPI if pageinfo.has_vector else 0,\n            options.oversample or 0,\n        )\n    )",
    "docstring": "Get the DPI when we require xres == yres, scaled to physical units"
  },
  {
    "code": "def render(file):\n    with file.open() as fp:\n        encoding = detect_encoding(fp, default='utf-8')\n        result = mistune.markdown(fp.read().decode(encoding))\n        return result",
    "docstring": "Render HTML from Markdown file content."
  },
  {
    "code": "def one_hot_encoding(labels, num_classes, scope=None):\n  with tf.name_scope(scope, 'OneHotEncoding', [labels]):\n    batch_size = labels.get_shape()[0]\n    indices = tf.expand_dims(tf.range(0, batch_size), 1)\n    labels = tf.cast(tf.expand_dims(labels, 1), indices.dtype)\n    concated = tf.concat(axis=1, values=[indices, labels])\n    onehot_labels = tf.sparse_to_dense(\n        concated, tf.stack([batch_size, num_classes]), 1.0, 0.0)\n    onehot_labels.set_shape([batch_size, num_classes])\n    return onehot_labels",
    "docstring": "Transform numeric labels into onehot_labels.\n\n  Args:\n    labels: [batch_size] target labels.\n    num_classes: total number of classes.\n    scope: Optional scope for name_scope.\n  Returns:\n    one hot encoding of the labels."
  },
  {
    "code": "def _unpad(self, a, axis, out):\n        assert a.shape[axis] == self.N\n        Npad = self.N - self.Nin\n        if out:\n            _Npad, Npad_ = Npad - Npad//2, Npad//2\n        else:\n            _Npad, Npad_ = Npad//2, Npad - Npad//2\n        return np.take(a, range(_Npad, self.N - Npad_), axis=axis)",
    "docstring": "Undo padding in an array.\n\n        Parameters\n        ----------\n        a : (..., N, ...) ndarray\n            array to be trimmed to size `Nin`\n        axis : int\n            axis along which to unpad\n        out : bool\n            trim the output if True, otherwise the input; the two cases have\n            their left and right pad sizes reversed"
  },
  {
    "code": "def invalidate(self, assoc_handle, dumb):\n        if dumb:\n            key = self._dumb_key\n        else:\n            key = self._normal_key\n        self.store.removeAssociation(key, assoc_handle)",
    "docstring": "Invalidates the association with the given handle.\n\n        @type assoc_handle: str\n\n        @param dumb: Is this association used with dumb mode?\n        @type dumb: bool"
  },
  {
    "code": "def getOldestRequestTime(self):\n        bldrid = yield self.getBuilderId()\n        unclaimed = yield self.master.data.get(\n            ('builders', bldrid, 'buildrequests'),\n            [resultspec.Filter('claimed', 'eq', [False])],\n            order=['submitted_at'], limit=1)\n        if unclaimed:\n            return unclaimed[0]['submitted_at']",
    "docstring": "Returns the submitted_at of the oldest unclaimed build request for\n        this builder, or None if there are no build requests.\n\n        @returns: datetime instance or None, via Deferred"
  },
  {
    "code": "def parse_json_feed_file(filename: str) -> JSONFeed:\n    with open(filename) as f:\n        try:\n            root = json.load(f)\n        except json.decoder.JSONDecodeError:\n            raise FeedJSONError('Not a valid JSON document')\n    return parse_json_feed(root)",
    "docstring": "Parse a JSON feed from a local json file."
  },
  {
    "code": "def autodiscover():\n    url_conf = getattr(settings, 'ROOT_URLCONF', ())\n    resolver = urlresolvers.get_resolver(url_conf)\n    urlpatterns = resolver.url_patterns\n    permissions = generate_permissions(urlpatterns)\n    refresh_permissions(permissions)",
    "docstring": "Autodiscover for urls.py"
  },
  {
    "code": "def evaluate_emb(emb, labels):\n    d_mat = get_distance_matrix(emb)\n    d_mat = d_mat.asnumpy()\n    labels = labels.asnumpy()\n    names = []\n    accs = []\n    for k in [1, 2, 4, 8, 16]:\n        names.append('Recall@%d' % k)\n        correct, cnt = 0.0, 0.0\n        for i in range(emb.shape[0]):\n            d_mat[i, i] = 1e10\n            nns = argpartition(d_mat[i], k)[:k]\n            if any(labels[i] == labels[nn] for nn in nns):\n                correct += 1\n            cnt += 1\n        accs.append(correct/cnt)\n    return names, accs",
    "docstring": "Evaluate embeddings based on Recall@k."
  },
  {
    "code": "def set_project_dir(self, directory):\r\n        if directory is not None:\r\n            self.treewidget.set_root_path(osp.dirname(directory))\r\n            self.treewidget.set_folder_names([osp.basename(directory)])\r\n        self.treewidget.setup_project_view()\r\n        try:\r\n            self.treewidget.setExpanded(self.treewidget.get_index(directory),\r\n                                        True)\r\n        except TypeError:\r\n            pass",
    "docstring": "Set the project directory"
  },
  {
    "code": "def configure_environ(dsn_env_name='PROM_DSN', connection_class=DsnConnection):\n    inters = []\n    cs = dsnparse.parse_environs(dsn_env_name, parse_class=connection_class)\n    for c in cs:\n        inter = c.interface\n        set_interface(inter, c.name)\n        inters.append(inter)\n    return inters",
    "docstring": "configure interfaces based on environment variables\n\n    by default, when prom is imported, it will look for PROM_DSN, and PROM_DSN_N (where\n    N is 1 through infinity) in the environment, if it finds them, it will assume they\n    are dsn urls that prom understands and will configure db connections with them. If you\n    don't want this behavior (ie, you want to configure prom manually) then just make sure\n    you don't have any environment variables with matching names\n\n    The num checks (eg PROM_DSN_1, PROM_DSN_2) go in order, so you can't do PROM_DSN_1, PROM_DSN_3,\n    because it will fail on _2 and move on, so make sure your num dsns are in order (eg, 1, 2, 3, ...)\n\n    example --\n        export PROM_DSN_1=some.Interface://host:port/dbname#i1\n        export PROM_DSN_2=some.Interface://host2:port/dbname2#i2\n        $ python\n        >>> import prom\n        >>> print prom.interfaces # prints a dict with interfaces i1 and i2 keys\n\n    :param dsn_env_name: string, the name of the environment variables"
  },
  {
    "code": "def _get_full_path(self, path, environ):\n        if path.startswith('/'):\n            path = environ.get('SCRIPT_NAME', '') + path\n        return path",
    "docstring": "Return the full path to ``path`` by prepending the SCRIPT_NAME.\n        \n        If ``path`` is a URL, do nothing."
  },
  {
    "code": "def GetFeeds(client):\n  feed_service = client.GetService('FeedService', 'v201809')\n  feeds = []\n  more_pages = True\n  selector = {\n      'fields': ['Id', 'Name', 'Attributes'],\n      'predicates': [\n          {\n              'field': 'Origin',\n              'operator': 'EQUALS',\n              'values': ['USER']\n          },\n          {\n              'field': 'FeedStatus',\n              'operator': 'EQUALS',\n              'values': ['ENABLED']\n          }\n      ],\n      'paging': {\n          'startIndex': 0,\n          'numberResults': PAGE_SIZE\n      }\n  }\n  while more_pages:\n    page = feed_service.get(selector)\n    if 'entries' in page:\n      feeds.extend(page['entries'])\n    selector['paging']['startIndex'] += PAGE_SIZE\n    more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries'])\n  return feeds",
    "docstring": "Returns a list of all enabled Feeds.\n\n  Args:\n    client: an AdWordsClient instance.\n\n  Returns:\n    A list containing all enabled Feeds."
  },
  {
    "code": "def update_volume(self, data):\n        self._client['config']['volume'] = data['volume']\n        _LOGGER.info('updated volume on %s', self.friendly_name)\n        self._server.group(self.group.identifier).callback()\n        self.callback()",
    "docstring": "Update volume."
  },
  {
    "code": "def getResponse(self, http_request, request):\n        response = remoting.Envelope(request.amfVersion)\n        for name, message in request:\n            http_request.amf_request = message\n            processor = self.getProcessor(message)\n            response[name] = processor(message, http_request=http_request)\n        return response",
    "docstring": "Processes the AMF request, returning an AMF response.\n\n        @param http_request: The underlying HTTP Request.\n        @type http_request: U{HTTPRequest<http://docs.djangoproject.com\n            /en/dev/ref/request-response/#httprequest-objects>}\n        @param request: The AMF Request.\n        @type request: L{Envelope<pyamf.remoting.Envelope>}\n        @rtype: L{Envelope<pyamf.remoting.Envelope>}"
  },
  {
    "code": "def sayHello(self, name=\"Not given\", message=\"nothing\"):\n        print(\n            \"Python.sayHello called by: {0} \"\n            \"with message: '{1}'\".format(name, message)\n        )\n        return (\n            \"PythonSync says: Howdy {0} \"\n            \"that's a nice runtime you got there\".format(name)\n        )",
    "docstring": "Synchronous implementation of IHello.sayHello synchronous method.\n        The remote calling thread will be blocked until this is executed and\n        responds."
  },
  {
    "code": "def _consolidate(blocks):\n    gkey = lambda x: x._consolidate_key\n    grouper = itertools.groupby(sorted(blocks, key=gkey), gkey)\n    new_blocks = []\n    for (_can_consolidate, dtype), group_blocks in grouper:\n        merged_blocks = _merge_blocks(list(group_blocks), dtype=dtype,\n                                      _can_consolidate=_can_consolidate)\n        new_blocks = _extend_blocks(merged_blocks, new_blocks)\n    return new_blocks",
    "docstring": "Merge blocks having same dtype, exclude non-consolidating blocks"
  },
  {
    "code": "def add_state_machine(widget, event=None):\n    logger.debug(\"Creating new state-machine...\")\n    root_state = HierarchyState(\"new root state\")\n    state_machine = StateMachine(root_state)\n    rafcon.core.singleton.state_machine_manager.add_state_machine(state_machine)",
    "docstring": "Create a new state-machine when the user clicks on the '+' next to the tabs"
  },
  {
    "code": "def _get_ipv6addrs(self):\n        addrs = self._get_addrs()\n        ipv6addrs = addrs.get(netifaces.AF_INET6)\n        if not ipv6addrs:\n            return {}\n        return ipv6addrs[0]",
    "docstring": "Returns the IPv6 addresses associated with this NIC. If no IPv6\n        addresses are used, empty dict is returned."
  },
  {
    "code": "def peek_pointers_in_registers(self, peekSize = 16, context = None):\n        peekable_registers = (\n            'Eax', 'Ebx', 'Ecx', 'Edx', 'Esi', 'Edi', 'Ebp'\n        )\n        if not context:\n            context = self.get_context(win32.CONTEXT_CONTROL | \\\n                                       win32.CONTEXT_INTEGER)\n        aProcess    = self.get_process()\n        data        = dict()\n        for (reg_name, reg_value) in compat.iteritems(context):\n            if reg_name not in peekable_registers:\n                continue\n            reg_data = aProcess.peek(reg_value, peekSize)\n            if reg_data:\n                data[reg_name] = reg_data\n        return data",
    "docstring": "Tries to guess which values in the registers are valid pointers,\n        and reads some data from them.\n\n        @type  peekSize: int\n        @param peekSize: Number of bytes to read from each pointer found.\n\n        @type  context: dict( str S{->} int )\n        @param context: (Optional)\n            Dictionary mapping register names to their values.\n            If not given, the current thread context will be used.\n\n        @rtype:  dict( str S{->} str )\n        @return: Dictionary mapping register names to the data they point to."
  },
  {
    "code": "def get_form_kwargs(self, **kwargs):\n        kwargs = super(ClassRegistrationView, self).get_form_kwargs(**kwargs)\n        kwargs['user'] = self.request.user if hasattr(self.request,'user') else None\n        listing = self.get_listing()\n        kwargs.update({\n            'openEvents': listing['openEvents'],\n            'closedEvents': listing['closedEvents'],\n        })\n        return kwargs",
    "docstring": "Tell the form which fields to render"
  },
  {
    "code": "def add_node(self, id, label=None, type='CLASS', meta=None):\n        g = self.get_graph()\n        if meta is None:\n            meta={}\n        g.add_node(id, label=label, type=type, meta=meta)",
    "docstring": "Add a new node to the ontology"
  },
  {
    "code": "def _serialize(self, value, attr, obj):\n        if isinstance(value, arrow.arrow.Arrow):\n            value = value.datetime\n        return super(ArrowField, self)._serialize(value, attr, obj)",
    "docstring": "Convert the Arrow object into a string."
  },
  {
    "code": "def GET_account_record(self, path_info, account_addr, token_type):\n        if not check_account_address(account_addr):\n            return self._reply_json({'error': 'Invalid address'}, status_code=400)\n        if not check_token_type(token_type):\n            return self._reply_json({'error': 'Invalid token type'}, status_code=400)\n        blockstackd_url = get_blockstackd_url()\n        res = blockstackd_client.get_account_record(account_addr, token_type, hostport=blockstackd_url)\n        if json_is_error(res):\n            log.error(\"Failed to get account state for {} {}: {}\".format(account_addr, token_type, res['error']))\n            return self._reply_json({'error': 'Failed to get account record for {} {}: {}'.format(token_type, account_addr, res['error'])}, status_code=res.get('http_status', 500))\n        self._reply_json(res)\n        return",
    "docstring": "Get the state of a particular token account\n        Returns the account"
  },
  {
    "code": "def run(files, temp_folder):\n    \"Check flake8 errors in the code base.\"\n    try:\n        import flake8\n    except ImportError:\n        return NO_FLAKE_MSG\n    try:\n        from flake8.engine import get_style_guide\n    except ImportError:\n        from flake8.api.legacy import get_style_guide\n    py_files = filter_python_files(files)\n    if not py_files:\n        return\n    DEFAULT_CONFIG = join(temp_folder, get_config_file())\n    with change_folder(temp_folder):\n        flake8_style = get_style_guide(config_file=DEFAULT_CONFIG)\n        out, err = StringIO(), StringIO()\n        with redirected(out, err):\n            flake8_style.check_files(py_files)\n    return out.getvalue().strip() + err.getvalue().strip()",
    "docstring": "Check flake8 errors in the code base."
  },
  {
    "code": "def write_bit(self, registeraddress, value, functioncode=5):\n        _checkFunctioncode(functioncode, [5, 15])\n        _checkInt(value, minvalue=0, maxvalue=1, description='input value')\n        self._genericCommand(functioncode, registeraddress, value)",
    "docstring": "Write one bit to the slave.\n\n        Args:\n            * registeraddress (int): The slave register address (use decimal numbers, not hex).\n            * value (int): 0 or 1\n            * functioncode (int): Modbus function code. Can be 5 or 15.\n\n        Returns:\n            None\n\n        Raises:\n            ValueError, TypeError, IOError"
  },
  {
    "code": "def request(self, method, path, params=None, headers=None, body=None):\n        if not headers:\n            headers = {}\n        if not params:\n            params = {}\n        headers[\"Accept\"] = \"application/json\"\n        headers[\"Accept-Version\"] = \"^1.15.0\"\n        if self.auth_token:\n            headers[\"Authorization\"] = \"Bearer {0}\".format(self.auth_token)\n        path = self.url + path\n        params = self.flatten_params(params)\n        response = requests.request(method, path, params=params, headers=headers, json=body)\n        result = response.text\n        try:\n            result = response.json()\n        except Exception:\n            pass\n        if response.status_code >= 400:\n            raise LosantError(response.status_code, result)\n        return result",
    "docstring": "Base method for making a Losant API request"
  },
  {
    "code": "def uord(c):\n    if len(c) == 2:\n        high, low = [ord(p) for p in c]\n        ordinal = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000\n    else:\n        ordinal = ord(c)\n    return ordinal",
    "docstring": "Get Unicode ordinal."
  },
  {
    "code": "def __handle_request(self, request, *args, **kw):\n        self._authenticate(request)\n        self._check_permission(request)\n        method = self._get_method(request)\n        data = self._get_input_data(request)\n        data = self._clean_input_data(data, request)\n        response = self._exec_method(method, request, data, *args, **kw)\n        return self._process_response(response, request)",
    "docstring": "Intercept the request and response.\n\n        This function lets `HttpStatusCodeError`s fall through. They\n        are caught and transformed into HTTP responses by the caller.\n\n        :return: ``HttpResponse``"
  },
  {
    "code": "def find(key):\n    docs = list(collection.find({KEY_FIELD: key}))\n    if not docs:\n        return None\n    pickled_value = docs[0][VALUE_FIELD]\n    return pickle.loads(pickled_value)",
    "docstring": "Return the value associated with a key.\n\n    If there is no value with the given key, returns ``None``."
  },
  {
    "code": "def add_to_path(p):\n    old_path = sys.path\n    if p not in sys.path:\n        sys.path = sys.path[:]\n        sys.path.insert(0, p)\n    try:\n        yield\n    finally:\n        sys.path = old_path",
    "docstring": "Adds a path to python paths and removes it after the 'with' block ends"
  },
  {
    "code": "async def sleep(self, sleep_time):\n        try:\n            await asyncio.sleep(sleep_time)\n        except RuntimeError:\n            if self.log_output:\n                logging.info('sleep exception')\n            else:\n                print('sleep exception')\n            await self.shutdown()",
    "docstring": "This method is a proxy method for asyncio.sleep\n\n        :param sleep_time: Sleep interval in seconds\n\n        :returns: No return value."
  },
  {
    "code": "def get_subclass_from_module(module, parent_class):\n    try:\n        r = __recursive_import(module)\n        member_dict = dict(inspect.getmembers(r))\n        sprinter_class = parent_class\n        for v in member_dict.values():\n            if inspect.isclass(v) and issubclass(v, parent_class) and v != parent_class:\n                if sprinter_class is parent_class:\n                    sprinter_class = v\n        if sprinter_class is None:\n            raise SprinterException(\"No subclass %s that extends %s exists in classpath!\" % (module, str(parent_class)))\n        return sprinter_class\n    except ImportError:\n        e = sys.exc_info()[1]\n        raise e",
    "docstring": "Get a subclass of parent_class from the module at module\n\n    get_subclass_from_module performs reflection to find the first class that\n    extends the parent_class in the module path, and returns it."
  },
  {
    "code": "def _check_load_existing_object(self, object_type, id_field_name, operation='update'):\n        self._check_existing_object(object_type, id_field_name)\n        if not self._load_from_hdx(object_type, self.data[id_field_name]):\n            raise HDXError('No existing %s to %s!' % (object_type, operation))",
    "docstring": "Check metadata exists and contains HDX object identifier, and if so load HDX object\n\n        Args:\n            object_type (str): Description of HDX object type (for messages)\n            id_field_name (str): Name of field containing HDX object identifier\n            operation (str): Operation to report if error. Defaults to update.\n\n        Returns:\n            None"
  },
  {
    "code": "def _release(self, lease):\n        if lease.exist:\n            os.unlink(lease.path)\n            LOGGER.debug('Removed subnet lease {}'.format(lease.path))",
    "docstring": "Free the given lease\n\n        Args:\n            lease (lago.subnet_lease.Lease): The lease to free"
  },
  {
    "code": "def coarsen(self, dim: Optional[Mapping[Hashable, int]] = None,\n                boundary: str = 'exact',\n                side: Union[str, Mapping[Hashable, str]] = 'left',\n                coord_func: str = 'mean',\n                **dim_kwargs: int):\n        dim = either_dict_or_kwargs(dim, dim_kwargs, 'coarsen')\n        return self._coarsen_cls(\n            self, dim, boundary=boundary, side=side,\n            coord_func=coord_func)",
    "docstring": "Coarsen object.\n\n        Parameters\n        ----------\n        dim: dict, optional\n            Mapping from the dimension name to the window size.\n            dim : str\n                Name of the dimension to create the rolling iterator\n                along (e.g., `time`).\n            window : int\n                Size of the moving window.\n        boundary : 'exact' | 'trim' | 'pad'\n            If 'exact', a ValueError will be raised if dimension size is not a\n            multiple of the window size. If 'trim', the excess entries are\n            dropped. If 'pad', NA will be padded.\n        side : 'left' or 'right' or mapping from dimension to 'left' or 'right'\n        coord_func: function (name) that is applied to the coordintes,\n            or a mapping from coordinate name to function (name).\n\n        Returns\n        -------\n        Coarsen object (core.rolling.DataArrayCoarsen for DataArray,\n        core.rolling.DatasetCoarsen for Dataset.)\n\n        Examples\n        --------\n        Coarsen the long time series by averaging over every four days.\n\n        >>> da = xr.DataArray(np.linspace(0, 364, num=364),\n        ...                   dims='time',\n        ...                   coords={'time': pd.date_range(\n        ...                       '15/12/1999', periods=364)})\n        >>> da\n        <xarray.DataArray (time: 364)>\n        array([  0.      ,   1.002755,   2.00551 , ..., 361.99449 , 362.997245,\n               364.      ])\n        Coordinates:\n          * time     (time) datetime64[ns] 1999-12-15 1999-12-16 ... 2000-12-12\n        >>>\n        >>> da.coarsen(time=3, boundary='trim').mean()\n        <xarray.DataArray (time: 121)>\n        array([  1.002755,   4.011019,   7.019284,  ...,  358.986226,\n               361.99449 ])\n        Coordinates:\n          * time     (time) datetime64[ns] 1999-12-16 1999-12-19 ... 2000-12-10\n        >>>\n\n        See Also\n        --------\n        core.rolling.DataArrayCoarsen\n        core.rolling.DatasetCoarsen"
  },
  {
    "code": "def add_version(self, project, version, egg):\n        url = self._build_url(constants.ADD_VERSION_ENDPOINT)\n        data = {\n            'project': project,\n            'version': version\n        }\n        files = {\n            'egg': egg\n        }\n        json = self.client.post(url, data=data, files=files,\n                                timeout=self.timeout)\n        return json['spiders']",
    "docstring": "Adds a new project egg to the Scrapyd service. First class, maps to\n        Scrapyd's add version endpoint."
  },
  {
    "code": "def to_xml(self, root):\n        if not len(self.__custom_elements):\n            return\n        for uri, tags in self.__custom_elements.items():\n            prefix, url = uri.split(\":\", 1)\n            for name, value in tags.items():\n                self.__createElementNS(root, url, prefix + \":\" + name, value)\n        return root",
    "docstring": "Returns a DOM element contaning the XML representation of the\n        ExtensibleXMLiElement\n        @param root:Element Root XML element.\n        @return: Element"
  },
  {
    "code": "def get_par_css_dataframe(self):\n        assert self.jco is not None\n        assert self.pst is not None\n        jco = self.jco.to_dataframe()\n        weights = self.pst.observation_data.loc[jco.index,\"weight\"].copy().values\n        jco = (jco.T * weights).T\n        dss_sum = jco.apply(np.linalg.norm)\n        css = (dss_sum / float(self.pst.nnz_obs)).to_frame()\n        css.columns = [\"pest_css\"]\n        self.pst.add_transform_columns()\n        parval1 = self.pst.parameter_data.loc[dss_sum.index,\"parval1_trans\"].values\n        css.loc[:,\"hill_css\"] = (dss_sum * parval1) / (float(self.pst.nnz_obs)**2)\n        return css",
    "docstring": "get a dataframe of composite scaled sensitivities.  Includes both\n        PEST-style and Hill-style.\n\n        Returns\n        -------\n        css : pandas.DataFrame"
  },
  {
    "code": "def removeSinglePixels(img):\r\n    gx = img.shape[0]\r\n    gy = img.shape[1]\r\n    for i in range(gx):\r\n        for j in range(gy):\r\n            if img[i, j]:\r\n                found_neighbour = False\r\n                for ii in range(max(0, i - 1), min(gx, i + 2)):\r\n                    for jj in range(max(0, j - 1), min(gy, j + 2)):\r\n                        if ii == i and jj == j:\r\n                            continue\r\n                        if img[ii, jj]:\r\n                            found_neighbour = True\r\n                            break\r\n                    if found_neighbour:\r\n                        break\r\n                if not found_neighbour:\r\n                    img[i, j] = 0",
    "docstring": "img - boolean array\r\n    remove all pixels that have no neighbour"
  },
  {
    "code": "def get_annotationdefault(self):\n        buff = self.get_attribute(\"AnnotationDefault\")\n        if buff is None:\n            return None\n        with unpack(buff) as up:\n            (ti, ) = up.unpack_struct(_H)\n        return ti",
    "docstring": "The AnnotationDefault attribute, only present upon fields in an\n        annotaion.\n\n        reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.20"
  },
  {
    "code": "def watch_for_events():\n    fd = inotify.init()\n    try:\n        wd = inotify.add_watch(fd, '/tmp', inotify.IN_CLOSE_WRITE)\n        while True:\n            for event in inotify.get_events(fd):\n                print(\"event:\", event.name, event.get_mask_description())\n    finally:\n        os.close(fd)",
    "docstring": "Wait for events and print them to stdout."
  },
  {
    "code": "def get_screen_info(self):\n    return GetScreenInfo(\n        display=self.display,\n        opcode=self.display.get_extension_major(extname),\n        window=self,\n        )",
    "docstring": "Retrieve information about the current and available configurations for\n    the screen associated with this window."
  },
  {
    "code": "def fromstring(cls, string):\n        parser = etree.XMLParser(remove_blank_text=True)\n        root = etree.fromstring(string, parser)\n        tree = root.getroottree()\n        return cls.fromtree(tree)",
    "docstring": "Create a METS by parsing a string.\n\n        :param str string: String containing a METS document."
  },
  {
    "code": "def get_public_trades(self, time_frame='hour'):\n        self._log('get public trades')\n        return self._rest_client.get(\n            endpoint='/transactions',\n            params={'book': self.name, 'time': time_frame}\n        )",
    "docstring": "Return public trades that were completed recently.\n\n        :param time_frame: Time frame. Allowed values are \"minute\" for trades\n            in the last minute, or \"hour\" for trades in the last hour (default:\n            \"hour\").\n        :type time_frame: str | unicode\n        :return: Public trades completed recently.\n        :rtype: [dict]"
  },
  {
    "code": "def delete(self, qname):\n        try:\n            q = self.exists(qname)\n            if not q:\n                return False\n            queue = self.show(qname)\n            if queue:\n                queue.delete()\n        except pyrax.exceptions as err_msg:\n            log.error('RackSpace API got some problems during deletion: %s',\n                      err_msg)\n            return False\n        return True",
    "docstring": "Delete an existings RackSpace Queue."
  },
  {
    "code": "def _swap(self):\n        self.ref_start, self.qry_start = self.qry_start, self.ref_start\n        self.ref_end, self.qry_end = self.qry_end, self.ref_end\n        self.hit_length_ref, self.hit_length_qry = self.hit_length_qry, self.hit_length_ref\n        self.ref_length, self.qry_length = self.qry_length, self.ref_length\n        self.ref_name, self.qry_name = self.qry_name, self.ref_name",
    "docstring": "Swaps the alignment so that the reference becomes the query and vice-versa. Swaps their names, coordinates etc. The frame is not changed"
  },
  {
    "code": "def CreateCustomizerFeed(client, feed_name):\n  ad_customizer_feed_service = client.GetService('AdCustomizerFeedService',\n                                                 'v201809')\n  customizer_feed = {\n      'feedName': feed_name,\n      'feedAttributes': [\n          {'type': 'STRING', 'name': 'Name'},\n          {'type': 'STRING', 'name': 'Price'},\n          {'type': 'DATE_TIME', 'name': 'Date'}\n      ]\n  }\n  feed_service_operation = {\n      'operator': 'ADD',\n      'operand': customizer_feed\n  }\n  response = ad_customizer_feed_service.mutate([feed_service_operation])\n  if response and 'value' in response:\n    feed = response['value'][0]\n    feed_data = {\n        'feedId': feed['feedId'],\n        'nameId': feed['feedAttributes'][0]['id'],\n        'priceId': feed['feedAttributes'][1]['id'],\n        'dateId': feed['feedAttributes'][2]['id']\n    }\n    print ('Feed with name \"%s\" and ID %s was added with:\\n'\n           '\\tName attribute ID %s and price attribute ID %s and date attribute'\n           'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'],\n                       feed_data['priceId'], feed_data['dateId'])\n    return feed\n  else:\n    raise errors.GoogleAdsError('No feeds were added')",
    "docstring": "Creates a new AdCustomizerFeed.\n\n  Args:\n    client: an AdWordsClient instance.\n    feed_name: the name for the new AdCustomizerFeed.\n\n  Returns:\n    The new AdCustomizerFeed."
  },
  {
    "code": "def _cint(col, _map={base26(i): i - 1 for i in range(1, 257)}):\n        try:\n            return _map[col.upper()]\n        except KeyError:\n            raise ValueError(col)",
    "docstring": "Return zero-based column index from bijective base26 string.\n\n        >>> Coordinates._cint('Ab')\n        27\n\n        >>> Coordinates._cint('spam')\n        Traceback (most recent call last):\n            ...\n        ValueError: spam"
  },
  {
    "code": "def parse_plugin_metadata(content):\n  if not isinstance(content, bytes):\n    raise TypeError('Content type must be bytes')\n  result = plugin_data_pb2.PrCurvePluginData.FromString(content)\n  if result.version == 0:\n    return result\n  else:\n    logger.warn(\n        'Unknown metadata version: %s. The latest version known to '\n        'this build of TensorBoard is %s; perhaps a newer build is '\n        'available?', result.version, PROTO_VERSION)\n    return result",
    "docstring": "Parse summary metadata to a Python object.\n\n  Arguments:\n    content: The `content` field of a `SummaryMetadata` proto\n      corresponding to the pr_curves plugin.\n\n  Returns:\n    A `PrCurvesPlugin` protobuf object."
  },
  {
    "code": "def actual_query_range(self):\n    a = self.alignment_ranges\n    if self.get_strand() == '+':\n      return GenomicRange(a[0][1].chr,a[0][1].start,a[-1][1].end,self.get_strand())\n    return GenomicRange(a[0][1].chr,self.query_sequence_length-a[-1][1].end+1,self.query_sequence_length-a[0][1].start+1,dir=self.strand)",
    "docstring": "This is the actual query range for the positive strand\n\n    :returns: Range of query positive strand covered\n    :rtype: GenomicRange"
  },
  {
    "code": "def intersect_range_array(bed1,beds2,payload=None,is_sorted=False):\n  if not is_sorted: beds2 = sort_ranges(beds2)\n  output = []\n  for bed2 in beds2:\n    cval = bed2.cmp(bed1)\n    if cval == -1: continue\n    elif cval == 0:\n      output.append(bed1.intersect(bed2))\n      if payload==1:\n        output[-1].set_payload(bed1.payload)\n      if payload==2:\n        output[-1].set_payload(bed2.payload)\n    elif cval == 1: break\n  if payload: return sort_ranges(output)\n  return merge_ranges(output)",
    "docstring": "Does not do a merge if the payload has been set\n\n  :param bed1:\n  :param bed2:\n  :param payload: payload=1 return the payload of bed1 on each of the intersect set, payload=2 return the payload of bed2 on each of the union set, payload=3 return the payload of bed1 and bed2 on each of the union set\n  :param is_sorted:\n  :type bed1: GenomicRange\n  :type bed2: GenomicRange\n  :type payload: int\n  :type is_sorted: bool"
  },
  {
    "code": "def get_waittime(self):\n        now = time.time()\n        self.sentmessages.appendleft(now)\n        if len(self.sentmessages) == self.sentmessages.maxlen:\n            oldest = self.sentmessages[-1]\n            waittime = self.limitinterval - (now - oldest)\n            if waittime > 0:\n                return waittime + 1\n        return 0",
    "docstring": "Return the appropriate time to wait, if we sent too many messages\n\n        :returns: the time to wait in seconds\n        :rtype: :class:`float`\n        :raises: None"
  },
  {
    "code": "def _start_action_for_section(self, section):\n        if section == \"configuration\":\n            return\n        Global.LOGGER.debug(\"starting actions for section \" + section)\n        action_configuration = Global.CONFIG_MANAGER.sections[\n            section]\n        if len(action_configuration) == 0:\n            Global.LOGGER.warn(f\"section {section} has no configuration, skipping\")\n            return\n        action_type = None\n        new_managed_input = []\n        if \"type\" in action_configuration:\n            action_type = action_configuration[\"type\"]\n        if \"input\" in action_configuration:\n            action_input = action_configuration[\"input\"]\n            new_managed_input = (item.strip()\n                                    for item in action_input.split(\",\"))\n        my_action = Action.create_action_for_code(action_type,\n                                                    section,\n                                                    action_configuration,\n                                                    list(new_managed_input))\n        if not my_action:\n            Global.LOGGER.warn(f\"can't find a type for action {section}, the action will be skipped\")\n            return\n        self.actions.append(my_action)\n        Global.LOGGER.debug(\"updating the subscriptions table\")\n        for my_input in my_action.monitored_input:\n            self.subscriptions.setdefault(\n                my_input, []).append(my_action)",
    "docstring": "Start all the actions for a particular section"
  },
  {
    "code": "def annotate_from_changeset(self, changeset):\n        if self.annotate_from_changeset_func:\n            return self.annotate_from_changeset_func(changeset)\n        else:\n            return ''.join((changeset.id, '\\n'))",
    "docstring": "Returns full html line for single changeset per annotated line."
  },
  {
    "code": "def search(self, text, includes=None, doc_type=None, limit=None,\n               autocomplete=False, promulgated_only=False, tags=None,\n               sort=None, owner=None, series=None):\n        queries = self._common_query_parameters(doc_type, includes, owner,\n                                                promulgated_only, series, sort)\n        if len(text):\n            queries.append(('text', text))\n        if limit is not None:\n            queries.append(('limit', limit))\n        if autocomplete:\n            queries.append(('autocomplete', 1))\n        if tags is not None:\n            if type(tags) is list:\n                tags = ','.join(tags)\n            queries.append(('tags', tags))\n        if len(queries):\n            url = '{}/search?{}'.format(self.url, urlencode(queries))\n        else:\n            url = '{}/search'.format(self.url)\n        data = self._get(url)\n        return data.json()['Results']",
    "docstring": "Search for entities in the charmstore.\n\n        @param text The text to search for.\n        @param includes What metadata to return in results (e.g. charm-config).\n        @param doc_type Filter to this type: bundle or charm.\n        @param limit Maximum number of results to return.\n        @param autocomplete Whether to prefix/suffix match search terms.\n        @param promulgated_only Whether to filter to only promulgated charms.\n        @param tags The tags to filter; can be a list of tags or a single tag.\n        @param sort Sorting the result based on the sort string provided\n            which can be name, author, series and - in front for descending.\n        @param owner Optional owner. If provided, search results will only\n            include entities that owner can view.\n        @param series The series to filter; can be a list of series or a\n            single series."
  },
  {
    "code": "def propagate_defaults(config_doc):\n    for group_name, group_doc in config_doc.items():\n        if isinstance(group_doc, dict):\n            defaults = group_doc.get('defaults', {})\n            for item_name, item_doc in group_doc.items():\n                if item_name == 'defaults':\n                    continue\n                if isinstance(item_doc, dict):\n                    group_doc[item_name] = \\\n                        dict_merge_pair(copy.deepcopy(defaults), item_doc)\n    return config_doc",
    "docstring": "Propagate default values to sections of the doc."
  },
  {
    "code": "def start(self, use_atexit=True):\n        assert not self._process\n        _logger.debug('Starting process %s', self._proc_args)\n        process_future = asyncio.create_subprocess_exec(\n            stdin=subprocess.PIPE,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n            *self._proc_args\n        )\n        self._process = yield from process_future\n        self._stderr_reader = asyncio.async(self._read_stderr())\n        self._stdout_reader = asyncio.async(self._read_stdout())\n        if use_atexit:\n            atexit.register(self.close)",
    "docstring": "Start the executable.\n\n        Args:\n            use_atexit (bool): If True, the process will automatically be\n                terminated at exit."
  },
  {
    "code": "def info(self):\n        return super(QgisComposerComponentsMetadata, self).info.update({\n            'orientation': self.orientation,\n            'page_dpi': self.page_dpi,\n            'page_width': self.page_width,\n            'page_height': self.page_height\n        })",
    "docstring": "Short info of the metadata.\n\n        :return: Returned dictionary of information about the component.\n        :rtype: dict"
  },
  {
    "code": "def ignore(self, *ignore_lst: str):\n        def stream():\n            for each in ignore_lst:\n                each = ConstStrPool.cast_to_const(each)\n                yield id(each), each\n        self.ignore_lst.update(stream())",
    "docstring": "ignore a set of tokens with specific names"
  },
  {
    "code": "def current_version():\n    import setuptools\n    version = [None]\n    def monkey_setup(**settings):\n        version[0] = settings['version']\n    old_setup = setuptools.setup\n    setuptools.setup = monkey_setup\n    import setup\n    reload(setup)\n    setuptools.setup = old_setup\n    return version[0]",
    "docstring": "Get the current version number from setup.py"
  },
  {
    "code": "def inform_student(submission, request, state):\n    details_url = request.build_absolute_uri(reverse('details', args=(submission.pk,)))\n    if state == submission.TEST_VALIDITY_FAILED:\n        subject = STUDENT_FAILED_SUB\n        message = STUDENT_FAILED_MSG\n        message = message % (submission.assignment,\n                             submission.assignment.course,\n                             details_url)\n    elif state == submission.CLOSED:\n        if submission.assignment.is_graded():\n            subject = STUDENT_GRADED_SUB\n            message = STUDENT_GRADED_MSG\n        else:\n            subject = STUDENT_PASSED_SUB\n            message = STUDENT_PASSED_MSG\n        message = message % (submission.assignment,\n                             submission.assignment.course,\n                             details_url)\n    else:\n        return\n    subject = \"[%s] %s\" % (submission.assignment.course, subject)\n    from_email = submission.assignment.course.owner.email\n    recipients = submission.authors.values_list(\n        'email', flat=True).distinct().order_by('email')\n    email = EmailMessage(subject, message, from_email, recipients)\n    email.send(fail_silently=True)",
    "docstring": "Create an email message for the student,\n    based on the given submission state.\n\n    Sending eMails on validation completion does\n    not work, since this may have been triggered\n    by the admin."
  },
  {
    "code": "def nondegenerate(triangles, areas=None, height=None):\n    triangles = np.asanyarray(triangles, dtype=np.float64)\n    if not util.is_shape(triangles, (-1, 3, 3)):\n        raise ValueError('Triangles must be (n,3,3)!')\n    if height is None:\n        height = tol.merge\n    ok = (extents(triangles=triangles,\n                  areas=areas) > height).all(axis=1)\n    return ok",
    "docstring": "Find all triangles which have an oriented bounding box\n    where both of the two sides is larger than a specified height.\n\n    Degenerate triangles can be when:\n    1) Two of the three vertices are colocated\n    2) All three vertices are unique but colinear\n\n\n    Parameters\n    ----------\n    triangles : (n, 3, 3) float\n      Triangles in space\n    height : float\n      Minimum edge length of a triangle to keep\n\n    Returns\n    ----------\n    nondegenerate : (n,) bool\n      True if a triangle meets required minimum height"
  },
  {
    "code": "def detached_signature_for(plaintext_str, keys):\n    ctx = gpg.core.Context(armor=True)\n    ctx.signers = keys\n    (sigblob, sign_result) = ctx.sign(plaintext_str,\n                                      mode=gpg.constants.SIG_MODE_DETACH)\n    return sign_result.signatures, sigblob",
    "docstring": "Signs the given plaintext string and returns the detached signature.\n\n    A detached signature in GPG speak is a separate blob of data containing\n    a signature for the specified plaintext.\n\n    :param bytes plaintext_str: bytestring to sign\n    :param keys: list of one or more key to sign with.\n    :type keys: list[gpg.gpgme._gpgme_key]\n    :returns: A list of signature and the signed blob of data\n    :rtype: tuple[list[gpg.results.NewSignature], str]"
  },
  {
    "code": "def find_vcs_root(cls, path):\n        if cls.search_parents_for_root():\n            valid_dirs = walk_up_dirs(path)\n        else:\n            valid_dirs = [path]\n        for i, current_path in enumerate(valid_dirs):\n            if cls.is_valid_root(current_path):\n                return current_path, i\n        return None",
    "docstring": "Try to find a version control root directory of this type for the\n        given path.\n\n        If successful, returns (vcs_root, levels_up), where vcs_root is the\n        path to the version control root directory it found, and levels_up is an\n        integer indicating how many parent directories it had to search through\n        to find it, where 0 means it was found in the indicated path, 1 means it\n        was found in that path's parent, etc. If not sucessful, returns None"
  },
  {
    "code": "def read_config_file(self, file_name):\n        with open(os.path.join(self.__path(), os.path.basename(file_name)),\n                  'rt') as file_config:\n            return self._parser.parseString(file_config.read())",
    "docstring": "Reads a CWR grammar config file.\n\n        :param file_name: name of the text file\n        :return: the file's contents"
  },
  {
    "code": "def emit_only(self, event: str, func_names: Union[str, List[str]], *args,\n                  **kwargs) -> None:\n        if isinstance(func_names, str):\n            func_names = [func_names]\n        for func in self._event_funcs(event):\n            if func.__name__ in func_names:\n                func(*args, **kwargs)",
    "docstring": "Specifically only emits certain subscribed events.\n\n        :param event: Name of the event.\n        :type event: str\n\n        :param func_names: Function(s) to emit.\n        :type func_names: Union[ str | List[str] ]"
  },
  {
    "code": "def add_env(self, name, val):\n        if name in self.env_vars:\n            raise KeyError(name)\n        self.env_vars[name] = val",
    "docstring": "Add an environment variable to the docker run invocation"
  },
  {
    "code": "def iscm_md_append_array(self, arraypath, member):\n        array_path = string.split(arraypath, \".\")\n        array_key = array_path.pop()\n        current = self.metadata\n        for k in array_path:\n            if not current.has_key(k):\n                current[k] = {}\n            current = current[k]\n        if not current.has_key(array_key):\n            current[array_key] = []\n        if not type(current[array_key]) == list:\n            raise KeyError(\"%s doesn't point to an array\" % arraypath)\n        current[array_key].append(member)",
    "docstring": "Append a member to a metadata array entry"
  },
  {
    "code": "def get_vocabulary(preprocess_output_dir, name):\n  vocab_file = os.path.join(preprocess_output_dir, CATEGORICAL_ANALYSIS % name)\n  if not file_io.file_exists(vocab_file):\n    raise ValueError('File %s not found in %s' %\n                     (CATEGORICAL_ANALYSIS % name, preprocess_output_dir))\n  labels = python_portable_string(\n      file_io.read_file_to_string(vocab_file)).split('\\n')\n  label_values = [x for x in labels if x]\n  return label_values",
    "docstring": "Loads the vocabulary file as a list of strings.\n\n  Args:\n    preprocess_output_dir: Should contain the file CATEGORICAL_ANALYSIS % name.\n    name: name of the csv column.\n\n  Returns:\n    List of strings.\n\n  Raises:\n    ValueError: if file is missing."
  },
  {
    "code": "def remove_video_for_course(course_id, edx_video_id):\n    course_video = CourseVideo.objects.get(course_id=course_id, video__edx_video_id=edx_video_id)\n    course_video.is_hidden = True\n    course_video.save()",
    "docstring": "Soft deletes video for particular course.\n\n    Arguments:\n        course_id (str): id of the course\n        edx_video_id (str): id of the video to be hidden"
  },
  {
    "code": "def rerender_options(options):\n    args = []\n    for name,value in options.iteritems():\n        name = name.replace(\"_\",\"-\")\n        if value is None:\n            pass\n        elif isinstance(value,bool):\n            if value:\n                args.append(\"--%s\" % (name,))\n        elif isinstance(value,list):\n            for item in value:\n                args.append(\"--%s=%s\" % (name,item))\n        else:\n            args.append(\"--%s=%s\" % (name,value))\n    return \" \".join(args)",
    "docstring": "Helper function to re-render command-line options.\n\n    This assumes that command-line options use the same name as their\n    key in the options dictionary."
  },
  {
    "code": "def _get_interpreter_info(interpreter=None):\n    if interpreter is None:\n        major, minor = sys.version_info[:2]\n        executable = sys.executable\n    else:\n        args = [interpreter, '-c', SHOW_VERSION_CMD]\n        try:\n            requested_interpreter_info = logged_exec(args)\n        except Exception as error:\n            logger.error(\"Error getting requested interpreter version: %s\", error)\n            raise FadesError(\"Could not get interpreter version\")\n        requested_interpreter_info = json.loads(requested_interpreter_info[0])\n        executable = requested_interpreter_info['path']\n        major = requested_interpreter_info['major']\n        minor = requested_interpreter_info['minor']\n    if executable[-1].isdigit():\n        executable = executable.split(\".\")[0][:-1]\n    interpreter = \"{}{}.{}\".format(executable, major, minor)\n    return interpreter",
    "docstring": "Return the interpreter's full path using pythonX.Y format."
  },
  {
    "code": "def check_directory_path(self, path):\n        if os.path.isdir(path) is not True:\n            msg = \"Directory Does Not Exist {}\".format(path)\n            raise OSError(msg)",
    "docstring": "Ensure directory exists at the provided path\n\n        :type path: string\n        :param path: path to directory to check"
  },
  {
    "code": "def cursor_position(self, value):\n        assert isinstance(value, int)\n        assert value <= len(self.text)\n        changed = self._set_cursor_position(value)\n        if changed:\n            self._cursor_position_changed()",
    "docstring": "Setting cursor position."
  },
  {
    "code": "def get_parameters_as_dictionary(self, query_string):\n        pairs = (x.split('=', 1) for x in query_string.split('&'))\n        return dict((k, unquote(v)) for k, v in pairs)",
    "docstring": "Returns query string parameters as a dictionary."
  },
  {
    "code": "def _parse_mut(subs):\n    if subs!=\"0\":\n        subs = [[subs.replace(subs[-2:], \"\"),subs[-2], subs[-1]]]\n    return subs",
    "docstring": "Parse mutation tag from miraligner output"
  },
  {
    "code": "def snap_remove(packages, *flags):\n    if type(packages) is not list:\n        packages = [packages]\n    flags = list(flags)\n    message = 'Removing snap(s) \"%s\"' % ', '.join(packages)\n    if flags:\n        message += ' with options \"%s\"' % ', '.join(flags)\n    log(message, level='INFO')\n    return _snap_exec(['remove'] + flags + packages)",
    "docstring": "Remove a snap package.\n\n    :param packages: String or List String package name\n    :param flags: List String flags to pass to remove command\n    :return: Integer return code from snap"
  },
  {
    "code": "def get_older_backup(self, encrypted=None, compressed=None,\n                         content_type=None, database=None, servername=None):\n        files = self.list_backups(encrypted=encrypted, compressed=compressed,\n                                  content_type=content_type, database=database,\n                                  servername=servername)\n        if not files:\n            raise FileNotFound(\"There's no backup file available.\")\n        return min(files, key=utils.filename_to_date)",
    "docstring": "Return the older backup's file name.\n\n        :param encrypted: Filter by encrypted or not\n        :type encrypted: ``bool`` or ``None``\n\n        :param compressed: Filter by compressed or not\n        :type compressed: ``bool`` or ``None``\n\n        :param content_type: Filter by media or database backup, must be\n                             ``'db'`` or ``'media'``\n\n        :type content_type: ``str`` or ``None``\n\n        :param database: Filter by source database's name\n        :type: ``str`` or ``None``\n\n        :param servername: Filter by source server's name\n        :type: ``str`` or ``None``\n\n        :returns: Older file\n        :rtype: ``str``\n\n        :raises: FileNotFound: If no backup file is found"
  },
  {
    "code": "def _InitializeURL(self, upload_url, current_content_length):\n    if current_content_length != 0:\n      return upload_url\n    headers = {\n        'Content-Type': 'application/xml',\n        'Content-Length': 0,\n        'x-goog-resumable': 'start'\n    }\n    req = urllib2.Request(upload_url, data={}, headers=headers)\n    resp = self._url_opener.open(req)\n    return resp.headers['location']",
    "docstring": "Ensures that the URL used to upload operations is properly initialized.\n\n    Args:\n      upload_url: a string url.\n      current_content_length: an integer identifying the current content length\n        of data uploaded to the Batch Job.\n\n    Returns:\n      An initialized string URL, or the provided string URL if the URL has\n      already been initialized."
  },
  {
    "code": "def mols_to_file(mols, path):\n    with open(path, 'w') as f:\n        f.write(mols_to_text(mols))",
    "docstring": "Save molecules to the SDFile format file\n\n    Args:\n        mols: list of molecule objects\n        path: file path to save"
  },
  {
    "code": "def snake(s):\n    if len(s) < 2:\n        return s.lower()\n    out = s[0].lower()\n    for c in s[1:]:\n        if c.isupper():\n            out += \"_\"\n            c = c.lower()\n        out += c\n    return out",
    "docstring": "Convert from title or camelCase to snake_case."
  },
  {
    "code": "def get_standard(self):\n        try:\n            res = urlopen(PARSELY_PAGE_SCHEMA)\n        except:\n            return []\n        text = res.read()\n        if isinstance(text, bytes):\n            text = text.decode('utf-8')\n        tree = etree.parse(StringIO(text))\n        stdref = tree.xpath(\"//div/@about\")\n        return [a.split(':')[1] for a in stdref]",
    "docstring": "get list of allowed parameters"
  },
  {
    "code": "def clone(self) -> \"Event\":\n        return self.__class__(copy.deepcopy(self.event), copy.deepcopy(self.metadata))",
    "docstring": "Clone the event\n\n        Returns:\n            :class:`slack.events.Event`"
  },
  {
    "code": "def add_localedir_translations(self, localedir):\n        global _localedirs\n        if localedir in self.localedirs:\n            return\n        self.localedirs.append(localedir)\n        full_localedir = os.path.join(localedir, 'locale')\n        if os.path.exists(full_localedir):\n            translation = self._new_gnu_trans(full_localedir)\n            self.merge(translation)",
    "docstring": "Merge translations from localedir."
  },
  {
    "code": "def tostring(node, indent=4, nsmap=None):\n    out = io.BytesIO()\n    writer = StreamingXMLWriter(out, indent, nsmap=nsmap)\n    writer.serialize(node)\n    return out.getvalue()",
    "docstring": "Convert a node into an XML string by using the StreamingXMLWriter.\n    This is useful for testing purposes.\n\n    :param node: a node object (typically an ElementTree object)\n    :param indent: the indentation to use in the XML (default 4 spaces)"
  },
  {
    "code": "def add_clients(session, verbose):\n  for ctype in ['Genuine', 'Impostor']:\n    for cdid in userid_clients:\n      cid = ctype + '_%d' % cdid\n      if verbose>1: print(\"  Adding user '%s' of type '%s'...\" % (cid, ctype))\n      session.add(Client(cid, ctype, cdid))",
    "docstring": "Add clients to the ATVS Keystroke database."
  },
  {
    "code": "def QueryValueEx(key, value_name):\n  regqueryvalueex = advapi32[\"RegQueryValueExW\"]\n  regqueryvalueex.restype = ctypes.c_long\n  regqueryvalueex.argtypes = [\n      ctypes.c_void_p, ctypes.c_wchar_p, LPDWORD, LPDWORD, LPBYTE, LPDWORD\n  ]\n  size = 256\n  data_type = ctypes.wintypes.DWORD()\n  while True:\n    tmp_size = ctypes.wintypes.DWORD(size)\n    buf = ctypes.create_string_buffer(size)\n    rc = regqueryvalueex(key.handle, value_name, LPDWORD(),\n                         ctypes.byref(data_type), ctypes.cast(buf, LPBYTE),\n                         ctypes.byref(tmp_size))\n    if rc != ERROR_MORE_DATA:\n      break\n    if size > 10 * 1024 * 1024:\n      raise OSError(\"Value too big to be read by GRR.\")\n    size *= 2\n  if rc != ERROR_SUCCESS:\n    raise ctypes.WinError(2)\n  return _Reg2Py(buf, tmp_size.value, data_type.value), data_type.value",
    "docstring": "This calls the Windows QueryValueEx function in a Unicode safe way."
  },
  {
    "code": "def _get_conditions_list(table, conds, archive=True):\n    if conds is None:\n        conds = []\n    all_conditions = []\n    for cond in conds:\n        if len(cond) != len(table.version_columns):\n            raise ValueError('Conditions must specify all unique constraints.')\n        conditions = []\n        t = table.ArchiveTable if archive else table\n        for col_name, value in cond.iteritems():\n            if col_name not in table.version_columns:\n                raise ValueError('{} is not one of the unique columns <{}>'.format(\n                    col_name, ','.join(table.version_columns)\n                ))\n            conditions.append(getattr(t, col_name) == value)\n        all_conditions.append(conditions)\n    return all_conditions",
    "docstring": "This function returns a list of list of == conditions on sqlalchemy columns given conds.\n    This should be treated as an or of ands.\n\n    :param table: the user table model class which inherits from\n        savage.models.SavageModelMixin\n    :param conds: a list of dictionaries of key value pairs where keys are column names and\n        values are conditions to be placed on the column.\n    :param archive: If true, the condition is with columns from the archive table. Else its from\n        the user table."
  },
  {
    "code": "def _parse_param(key, val):\n    regex = re.compile(r'fields\\[([A-Za-z]+)\\]')\n    match = regex.match(key)\n    if match:\n        if not isinstance(val, list):\n            val = val.split(',')\n        fields = [field.lower() for field in val]\n        rtype = match.groups()[0].lower()\n        return rtype, fields",
    "docstring": "Parse the query param looking for sparse fields params\n\n    Ensure the `val` or what will become the sparse fields\n    is always an array. If the query param is not a sparse\n    fields query param then return None.\n\n    :param key:\n        the query parameter key in the request (left of =)\n    :param val:\n        the query parameter val in the request (right of =)\n    :return:\n        tuple of resource type to implement the sparse\n        fields on & a array of the fields."
  },
  {
    "code": "def split_markers_from_line(line):\n    if not any(line.startswith(uri_prefix) for uri_prefix in SCHEME_LIST):\n        marker_sep = \";\"\n    else:\n        marker_sep = \"; \"\n    markers = None\n    if marker_sep in line:\n        line, markers = line.split(marker_sep, 1)\n        markers = markers.strip() if markers else None\n    return line, markers",
    "docstring": "Split markers from a dependency"
  },
  {
    "code": "def transfer_list(request, detailed=True, search_opts=None):\n    c_client = cinderclient(request)\n    try:\n        return [VolumeTransfer(v) for v in c_client.transfers.list(\n            detailed=detailed, search_opts=search_opts)]\n    except cinder_exception.Forbidden as error:\n        LOG.error(error)\n        return []",
    "docstring": "List volume transfers.\n\n    To see all volumes transfers as an admin pass in a special\n    search option: {'all_tenants': 1}"
  },
  {
    "code": "def dict2kvlist(o):\n    return chain.from_iterable((k, v) for k, v in o.items())",
    "docstring": "Serializes a dict-like object into a generator of the flatten list of\n    repeating key-value pairs.  It is useful when using HMSET method in Redis.\n\n    Example:\n    >>> list(dict2kvlist({'a': 1, 'b': 2}))\n    ['a', 1, 'b', 2]"
  },
  {
    "code": "def next_version(self, object, relations_as_of='end'):\n        if object.version_end_date is None:\n            next = object\n        else:\n            next = self.filter(\n                Q(identity=object.identity),\n                Q(version_start_date__gte=object.version_end_date)\n            ).order_by('version_start_date').first()\n            if not next:\n                raise ObjectDoesNotExist(\n                    \"next_version couldn't find a next version of object \" +\n                    str(object.identity))\n        return self.adjust_version_as_of(next, relations_as_of)",
    "docstring": "Return the next version of the given object.\n\n        In case there is no next object existing, meaning the given\n        object is the current version, the function returns this version.\n\n        Note that if object's version_end_date is None, this does not check\n        the database to see if there is a newer version (perhaps created by\n        some other code), it simply returns the passed object.\n\n        ``relations_as_of`` is used to fix the point in time for the version;\n        this affects which related objects are returned when querying for\n        object relations. See ``VersionManager.version_as_of`` for details\n        on valid ``relations_as_of`` values.\n\n        :param Versionable object: object whose next version will be returned.\n        :param mixed relations_as_of: determines point in time used to access\n            relations. 'start'|'end'|datetime|None\n        :return: Versionable"
  },
  {
    "code": "def mark_as_read(self):\n        if self.object_id is None or self.__is_draft:\n            raise RuntimeError('Attempting to mark as read an unsaved Message')\n        data = {self._cc('isRead'): True}\n        url = self.build_url(\n            self._endpoints.get('get_message').format(id=self.object_id))\n        response = self.con.patch(url, data=data)\n        if not response:\n            return False\n        self.__is_read = True\n        return True",
    "docstring": "Marks this message as read in the cloud\n\n        :return: Success / Failure\n        :rtype: bool"
  },
  {
    "code": "def push(self, undoObj):\n        if not isinstance(undoObj, QtmacsUndoCommand):\n            raise QtmacsArgumentError('undoObj', 'QtmacsUndoCommand',\n                                      inspect.stack()[0][3])\n        self._wasUndo = False\n        self._push(undoObj)",
    "docstring": "Add ``undoObj`` command to stack and run its ``commit`` method.\n\n        |Args|\n\n        * ``undoObj`` (**QtmacsUndoCommand**): the new command object.\n\n        |Returns|\n\n        * **None**\n\n        |Raises|\n\n        * **QtmacsArgumentError** if at least one argument has an invalid type."
  },
  {
    "code": "def make_directory(directory):\n    if not os.path.isdir(directory):\n        os.mkdir(directory)\n        logger.info('Path {} not found, I will create it.'\n                    .format(directory))",
    "docstring": "Makes directory if it does not exist.\n\n    Parameters\n    -----------\n    directory : :obj:`str`\n        Directory path"
  },
  {
    "code": "def get_item_children(item):\r\n    children = [item.child(index) for index in range(item.childCount())]\r\n    for child in children[:]:\r\n        others = get_item_children(child)\r\n        if others is not None:\r\n            children += others\r\n    return sorted(children, key=lambda child: child.line)",
    "docstring": "Return a sorted list of all the children items of 'item'."
  },
  {
    "code": "def read_file(*relative_path_elements):\n    file_path = path.join(path.dirname(__file__), *relative_path_elements)\n    return io.open(file_path, encoding='utf8').read().strip()",
    "docstring": "Return content of a file relative to this ``setup.py``."
  },
  {
    "code": "def _acquire_media_transport(self, path, access_type):\n        transport = BTMediaTransport(path=path)\n        (fd, read_mtu, write_mtu) = transport.acquire(access_type)\n        self.fd = fd.take()\n        self.write_mtu = write_mtu\n        self.read_mtu = read_mtu\n        self.access_type = access_type\n        self.path = path\n        self._install_transport_ready()",
    "docstring": "Should be called by subclass when it is ready\n        to acquire the media transport file descriptor"
  },
  {
    "code": "def convert(self, json=\"\", table_attributes='border=\"1\"', clubbing=True, encode=False, escape=True):\n        self.table_init_markup = \"<table %s>\" % table_attributes\n        self.clubbing = clubbing\n        self.escape = escape\n        json_input = None\n        if not json:\n            json_input = {}\n        elif type(json) in text_types:\n            try:\n                json_input = json_parser.loads(json, object_pairs_hook=OrderedDict)\n            except ValueError as e:\n                if u\"Expecting property name\" in text(e):\n                    raise e\n                json_input = json\n        else:\n            json_input = json\n        converted = self.convert_json_node(json_input)\n        if encode:\n            return converted.encode('ascii', 'xmlcharrefreplace')\n        return converted",
    "docstring": "Convert JSON to HTML Table format"
  },
  {
    "code": "def _expr2code(self, arg_list, expr):\n        code = lambdastr(arg_list, expr)\n        function_code = code.split(':')[1].strip()\n        return function_code",
    "docstring": "Convert the given symbolic expression into code."
  },
  {
    "code": "def _load_json(self, filename):\n        with open(filename, 'r') as file_handle:\n            self._sensors.update(json.load(\n                file_handle, cls=MySensorsJSONDecoder))",
    "docstring": "Load sensors from json file."
  },
  {
    "code": "def _read_miraligner(fn):\n    reads = defaultdict(realign)\n    with open(fn) as in_handle:\n        in_handle.next()\n        for line in in_handle:\n            cols = line.strip().split(\"\\t\")\n            iso = isomir()\n            query_name, seq = cols[1], cols[0]\n            chrom, reference_start = cols[-2], cols[3]\n            iso.mirna = cols[3]\n            subs, add, iso.t5, iso.t3 = cols[6:10]\n            if query_name not in reads:\n                reads[query_name].sequence = seq\n            iso.align = line\n            iso.start = reference_start\n            iso.subs, iso.add = _parse_mut(subs), add\n            logger.debug(\"%s %s %s %s %s\" % (query_name, reference_start, chrom, iso.subs, iso.add))\n            reads[query_name].set_precursor(chrom, iso)\n    return reads",
    "docstring": "Read ouput of miraligner and create compatible output."
  },
  {
    "code": "def parse_singular_string(t, tag_name):\n    pos = t.getElementsByTagName(tag_name)\n    assert(len(pos) == 1)\n    pos = pos[0]\n    assert(len(pos.childNodes) == 1)\n    return pos.childNodes[0].data",
    "docstring": "Parses the sole string value with name tag_name in tag t. Heavy-handed with the asserts."
  },
  {
    "code": "def unique(objects, key=None):\n    dupl = []\n    for obj, group in itertools.groupby(sorted(objects), key):\n        if sum(1 for _ in group) > 1:\n            dupl.append(obj)\n    if dupl:\n        raise ValueError('Found duplicates %s' % dupl)\n    return objects",
    "docstring": "Raise a ValueError if there is a duplicated object, otherwise\n    returns the objects as they are."
  },
  {
    "code": "def _realValue_to_float(value_str):\n    if REAL_VALUE.match(value_str):\n        value = float(value_str)\n    else:\n        value = None\n    return value",
    "docstring": "Convert a value string that conforms to DSP0004 `realValue`, into\n    the corresponding float and return it.\n\n    The special values 'INF', '-INF', and 'NAN' are supported.\n\n    Note that the Python `float()` function supports a superset of input\n    formats compared to the `realValue` definition in DSP0004. For example,\n    \"1.\" is allowed for `float()` but not for `realValue`. In addition, it\n    has the same support for Unicode decimal digits as `int()`.\n    Therefore, the match patterns explicitly check for US-ASCII digits, and\n    the `float()` function should never raise `ValueError`.\n\n    Returns None if the value string does not conform to `realValue`."
  },
  {
    "code": "def load(cls, path):\n        assert os.path.exists(path), \"No such file: %r\" % path\n        (folder, filename) = os.path.split(path)\n        (name, extension) = os.path.splitext(filename)\n        image = Image(None)\n        image._path = path\n        image._format = Image.image_format(extension)\n        return image",
    "docstring": "Load image from file."
  },
  {
    "code": "def controlprompt_cmd(self, cmd):\n        data = tags.string_tag('cmbe', cmd) + tags.uint8_tag('cmcc', 0)\n        return self.daap.post(_CTRL_PROMPT_CMD, data=data)",
    "docstring": "Perform a \"controlpromptentry\" command."
  },
  {
    "code": "def toints(self):\n        def grouper(iterable, n, fillvalue=None):\n            \"Collect data into fixed-length chunks or blocks\"\n            return zip_longest(*[iter(iterable)] * n, fillvalue=fillvalue)\n        return [int(''.join(map(str, group)), 2) for group in grouper(self._data, 8, 0)]",
    "docstring": "\\\n        Returns an iterable of integers interpreting the content of `seq`\n        as sequence of binary numbers of length 8."
  },
  {
    "code": "def from_path(cls, conn, path):\n        path = path.strip(SEP)\n        full_path = os.path.join(conn.abs_root, path)\n        return cls(conn, path, 0, os.path.getsize(full_path))",
    "docstring": "Create container from path."
  },
  {
    "code": "def convert_elementwise_mul_scalar(net, node, module, builder):\n    import numpy\n    input_name, output_name = _get_input_output_name(net, node)\n    name = node['name']\n    param = _get_attr(node)\n    mult = literal_eval(param['scalar'])\n    builder.add_scale(name=name,\n                      W=numpy.array([mult]),\n                      b=0,\n                      has_bias=False,\n                      input_name=input_name,\n                      output_name=output_name)",
    "docstring": "Convert a scalar multiplication from mxnet to coreml.\n\n    Parameters\n    ----------\n    net: network\n        A mxnet network object.\n\n    node: layer\n        Node to convert.\n\n    module: module\n        An module for MXNet\n\n    builder: NeuralNetworkBuilder\n        A neural network builder object."
  },
  {
    "code": "def crc16_ccitt(data, crc=0):\n    tab = CRC16_CCITT_TAB\n    for byte in six.iterbytes(data):\n        crc = (((crc << 8) & 0xff00) ^ tab[((crc >> 8) & 0xff) ^ byte])\n    return crc & 0xffff",
    "docstring": "Calculate the crc16 ccitt checksum of some data\n\n    A starting crc value may be specified if desired.  The input data\n    is expected to be a sequence of bytes (string) and the output\n    is an integer in the range (0, 0xFFFF).  No packing is done to the\n    resultant crc value.  To check the value a checksum, just pass in\n    the data byes and checksum value.  If the data matches the checksum,\n    then the resultant checksum from this function should be 0."
  },
  {
    "code": "def first(dmap_data, *path):\n    if not (path and isinstance(dmap_data, list)):\n        return dmap_data\n    for key in dmap_data:\n        if path[0] in key:\n            return first(key[path[0]], *path[1:])\n    return None",
    "docstring": "Look up a value given a path in some parsed DMAP data."
  },
  {
    "code": "def _continue_params(self):\n        if not self.data.get('continue'):\n            return\n        params = []\n        for item in self.data['continue']:\n            params.append(\"&%s=%s\" % (item, self.data['continue'][item]))\n        return ''.join(params)",
    "docstring": "Returns query string fragment continue parameters"
  },
  {
    "code": "def get_state_all(self):\n        state_dict = {}\n        for device in self.get_device_names().keys():\n            state_dict[device] = self.get_state(device)\n        return state_dict",
    "docstring": "Returns all device states"
  },
  {
    "code": "def block(bdaddr):\n    if not salt.utils.validate.net.mac(bdaddr):\n        raise CommandExecutionError(\n            'Invalid BD address passed to bluetooth.block'\n        )\n    cmd = 'hciconfig {0} block'.format(bdaddr)\n    __salt__['cmd.run'](cmd).splitlines()",
    "docstring": "Block a specific bluetooth device by BD Address\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' bluetooth.block DE:AD:BE:EF:CA:FE"
  },
  {
    "code": "def is_connected(self, attempts=3):\n        if self.gce is None:\n            while attempts > 0:\n                self.logger.info(\"Attempting to connect ...\")\n                try:\n                    self.connect()\n                except ComputeEngineManagerException:\n                    attempts -= 1\n                    continue\n                self.logger.info(\"Connection established.\")\n                return True\n            self.logger.error(\"Unable to connect to Google Compute Engine.\")\n            return False\n        return True",
    "docstring": "Try to reconnect if neccessary.\n\n        :param   attempts: The amount of tries to reconnect if neccessary.\n        :type    attempts: ``int``"
  },
  {
    "code": "def pixels_from_softmax(frame_logits, pure_sampling=False,\n                        temperature=1.0, gumbel_noise_factor=0.2):\n  if pure_sampling or temperature == 0.0:\n    return common_layers.sample_with_temperature(frame_logits, temperature)\n  pixel_range = tf.to_float(tf.range(256))\n  for _ in range(len(frame_logits.get_shape().as_list()) - 1):\n    pixel_range = tf.expand_dims(pixel_range, axis=0)\n  frame_logits = tf.nn.log_softmax(frame_logits)\n  gumbel_samples = discretization.gumbel_sample(\n      common_layers.shape_list(frame_logits)) * gumbel_noise_factor\n  frame = tf.nn.softmax((frame_logits + gumbel_samples) / temperature, axis=-1)\n  result = tf.reduce_sum(frame * pixel_range, axis=-1)\n  return result + tf.stop_gradient(tf.round(result) - result)",
    "docstring": "Given frame_logits from a per-pixel softmax, generate colors."
  },
  {
    "code": "def add_vertex(self, x, y, z, name):\n        self.vertices[name] = Vertex(x, y, z, name)\n        return self.vertices[name]",
    "docstring": "add vertex by coordinate and uniq name\n        x y z is coordinates of vertex\n        name is uniq name to refer the vertex\n        returns Vertex object whici is added."
  },
  {
    "code": "def _is_pingable(ip):\n    ping_cmd = ['ping',\n                '-c', '5',\n                '-W', '1',\n                '-i', '0.2',\n                ip]\n    try:\n        linux_utils.execute(ping_cmd, check_exit_code=True)\n        return True\n    except RuntimeError:\n        LOG.warning(\"Cannot ping ip address: %s\", ip)\n        return False",
    "docstring": "Checks whether an IP address is reachable by pinging.\n\n    Use linux utils to execute the ping (ICMP ECHO) command.\n    Sends 5 packets with an interval of 0.2 seconds and timeout of 1\n    seconds. Runtime error implies unreachability else IP is pingable.\n    :param ip: IP to check\n    :return: bool - True or False depending on pingability."
  },
  {
    "code": "def get_video_transcript_storage():\n    if hasattr(settings, 'VIDEO_TRANSCRIPTS_SETTINGS'):\n        return get_storage_class(\n            settings.VIDEO_TRANSCRIPTS_SETTINGS.get('STORAGE_CLASS'),\n        )(**settings.VIDEO_TRANSCRIPTS_SETTINGS.get('STORAGE_KWARGS', {}))\n    else:\n        return get_storage_class()()",
    "docstring": "Return the configured django storage backend for video transcripts."
  },
  {
    "code": "def from_json(cls, filename):\n        with open(filename) as fp:\n            raw = json.load(fp)\n        return cls(raw['stimuli'], raw['inhibitors'], raw['readouts'])",
    "docstring": "Creates an experimental setup from a JSON file\n\n        Parameters\n        ----------\n        filename : str\n            Absolute path to JSON file\n\n        Returns\n        -------\n        caspo.core.setup.Setup\n            Created object instance"
  },
  {
    "code": "def isOverlayVisible(self, ulOverlayHandle):\n        fn = self.function_table.isOverlayVisible\n        result = fn(ulOverlayHandle)\n        return result",
    "docstring": "Returns true if the overlay is visible."
  },
  {
    "code": "def cfloat64_array_to_numpy(cptr, length):\n    if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):\n        return np.fromiter(cptr, dtype=np.float64, count=length)\n    else:\n        raise RuntimeError('Expected double pointer')",
    "docstring": "Convert a ctypes double pointer array to a numpy array."
  },
  {
    "code": "def get_k8s_model(model_type, model_dict):\n    model_dict = copy.deepcopy(model_dict)\n    if isinstance(model_dict, model_type):\n        return model_dict\n    elif isinstance(model_dict, dict):\n        model_dict = _map_dict_keys_to_model_attributes(model_type, model_dict)\n        return model_type(**model_dict)\n    else:\n        raise AttributeError(\"Expected object of type 'dict' (or '{}') but got '{}'.\".format(model_type.__name__, type(model_dict).__name__))",
    "docstring": "Returns an instance of type specified model_type from an model instance or\n    represantative dictionary."
  },
  {
    "code": "def ltake(n: int, xs: Iterable[T]) -> List[T]:\n    return list(take(n, xs))",
    "docstring": "A non-lazy version of take."
  },
  {
    "code": "def guess_currency_from_address(address):\n    if is_py2:\n        fixer = lambda x: int(x.encode('hex'), 16)\n    else:\n        fixer = lambda x: x\n    first_byte = fixer(b58decode_check(address)[0])\n    double_first_byte = fixer(b58decode_check(address)[:2])\n    hits = []\n    for currency, data in crypto_data.items():\n        if hasattr(data, 'get'):\n            version = data.get('address_version_byte', None)\n            if version is not None and version in [double_first_byte, first_byte]:\n                hits.append([currency, data['name']])\n    if hits:\n        return hits\n    raise ValueError(\"Unknown Currency with first byte: %s\" % first_byte)",
    "docstring": "Given a crypto address, find which currency it likely belongs to.\n    Raises an exception if it can't find a match. Raises exception if address\n    is invalid."
  },
  {
    "code": "def get_sections(self):\n        try:\n            obj_list = self.__dict__['sections']\n            return [Section(i) for i in obj_list]\n        except KeyError:\n            self._lazy_load()\n            obj_list = self.__dict__['sections']\n            return [Section(i) for i in obj_list]",
    "docstring": "Fetch the sections field if it does not exist."
  },
  {
    "code": "def rstyle(self, name):\n\t\ttry:\n\t\t\tdel self.chart_style[name]\n\t\texcept KeyError:\n\t\t\tself.warning(\"Style \" + name + \" is not set\")\n\t\texcept:\n\t\t\tself.err(\"Can not remove style \" + name)",
    "docstring": "Remove one style"
  },
  {
    "code": "def get_base_url(html: str) -> str:\n    forms = BeautifulSoup(html, 'html.parser').find_all('form')\n    if not forms:\n        raise VVKBaseUrlException('Form for login not found')\n    elif len(forms) > 1:\n        raise VVKBaseUrlException('More than one login form found')\n    login_url = forms[0].get('action')\n    if not login_url:\n        raise VVKBaseUrlException('No action tag in form')\n    return login_url",
    "docstring": "Search for login url from VK login page"
  },
  {
    "code": "def from_path(cls, path):\n        urlparts = urlparse.urlsplit(path)\n        site = 'nonlocal'\n        if (urlparts.scheme == '' or urlparts.scheme == 'file'):\n            if os.path.isfile(urlparts.path):\n                path = os.path.abspath(urlparts.path)\n                path = urlparse.urljoin('file:',\n                                        urllib.pathname2url(path)) \n                site = 'local'\n        fil = File(os.path.basename(path))\n        fil.PFN(path, site)\n        return fil",
    "docstring": "Takes a path and returns a File object with the path as the PFN."
  },
  {
    "code": "def get_rlz(self, rlzstr):\n        r\n        mo = re.match(r'rlz-(\\d+)', rlzstr)\n        if not mo:\n            return\n        return self.realizations[int(mo.group(1))]",
    "docstring": "r\"\"\"\n        Get a Realization instance for a string of the form 'rlz-\\d+'"
  },
  {
    "code": "def plot_roc_curve(self, on, bootstrap_samples=100, ax=None, **kwargs):\n        plot_col, df = self.as_dataframe(on, return_cols=True, **kwargs)\n        df = filter_not_null(df, \"benefit\")\n        df = filter_not_null(df, plot_col)\n        df.benefit = df.benefit.astype(bool)\n        return roc_curve_plot(df, plot_col, \"benefit\", bootstrap_samples, ax=ax)",
    "docstring": "Plot an ROC curve for benefit and a given variable\n\n        Parameters\n        ----------\n        on : str or function or list or dict\n            See `cohort.load.as_dataframe`\n        bootstrap_samples : int, optional\n            Number of boostrap samples to use to compute the AUC\n        ax : Axes, default None\n            Axes to plot on\n\n        Returns\n        -------\n        (mean_auc_score, plot): (float, matplotlib plot)\n            Returns the average AUC for the given predictor over `bootstrap_samples`\n            and the associated ROC curve"
  },
  {
    "code": "def delete(self, *keys):\n        key_counter = 0\n        for key in map(self._encode, keys):\n            if key in self.redis:\n                del self.redis[key]\n                key_counter += 1\n            if key in self.timeouts:\n                del self.timeouts[key]\n        return key_counter",
    "docstring": "Emulate delete."
  },
  {
    "code": "def write(self, request):\n    if FLAGS.sc2_verbose_protocol:\n      self._log(\" Writing request \".center(60, \"-\") + \"\\n\")\n      self._log_packet(request)\n    self._write(request)",
    "docstring": "Write a Request."
  },
  {
    "code": "def add(self, lineitem):\n        if lineitem['ProductName']:\n            self._lineitems.append(lineitem)\n            if lineitem['BlendedCost']:\n                self._blended_cost += lineitem['BlendedCost']\n            if lineitem['UnBlendedCost']:\n                self._unblended_cost += lineitem['UnBlendedCost']",
    "docstring": "Add a line item record to this Costs object."
  },
  {
    "code": "def map_query(self, variables=None, evidence=None, elimination_order=None):\n        final_distribution = self._variable_elimination(variables, 'marginalize',\n                                                        evidence=evidence,\n                                                        elimination_order=elimination_order)\n        argmax = np.argmax(final_distribution.values)\n        assignment = final_distribution.assignment([argmax])[0]\n        map_query_results = {}\n        for var_assignment in assignment:\n            var, value = var_assignment\n            map_query_results[var] = value\n        if not variables:\n            return map_query_results\n        else:\n            return_dict = {}\n            for var in variables:\n                return_dict[var] = map_query_results[var]\n            return return_dict",
    "docstring": "Computes the MAP Query over the variables given the evidence.\n\n        Note: When multiple variables are passed, it returns the map_query for each\n        of them individually.\n\n        Parameters\n        ----------\n        variables: list\n            list of variables over which we want to compute the max-marginal.\n        evidence: dict\n            a dict key, value pair as {var: state_of_var_observed}\n            None if no evidence\n        elimination_order: list\n            order of variable eliminations (if nothing is provided) order is\n            computed automatically\n\n        Examples\n        --------\n        >>> from pgmpy.inference import VariableElimination\n        >>> from pgmpy.models import BayesianModel\n        >>> import numpy as np\n        >>> import pandas as pd\n        >>> values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 5)),\n        ...                       columns=['A', 'B', 'C', 'D', 'E'])\n        >>> model = BayesianModel([('A', 'B'), ('C', 'B'), ('C', 'D'), ('B', 'E')])\n        >>> model.fit(values)\n        >>> inference = VariableElimination(model)\n        >>> phi_query = inference.map_query(['A', 'B'])"
  },
  {
    "code": "def _get_permission_description(permission_name):\n    parts = permission_name.split('_')\n    parts.pop(0)\n    method = parts.pop()\n    resource = ('_'.join(parts)).lower()\n    return 'Can %s %s' % (method.upper(), resource)",
    "docstring": "Generate a descriptive string based on the permission name.\n\n    For example: 'resource_Order_get'  ->  'Can GET order'\n\n    todo: add support for the resource name to have underscores"
  },
  {
    "code": "def is_mainline(self) -> bool:\n        node = self\n        while node.parent:\n            parent = node.parent\n            if not parent.variations or parent.variations[0] != node:\n                return False\n            node = parent\n        return True",
    "docstring": "Checks if the node is in the mainline of the game."
  },
  {
    "code": "def build_on_start(self, runnable, regime, on_start):\n        on_start_code = []\n        for action in on_start.actions:\n            code = self.build_action(runnable, regime, action)\n            for line in code:\n                on_start_code += [line]\n        return on_start_code",
    "docstring": "Build OnStart start handler code.\n\n        @param on_start: OnStart start handler object\n        @type on_start: lems.model.dynamics.OnStart\n\n        @return: Generated OnStart code\n        @rtype: list(string)"
  },
  {
    "code": "def mark_dead(self, proxy, _time=None):\n        if proxy not in self.proxies:\n            logger.warn(\"Proxy <%s> was not found in proxies list\" % proxy)\n            return\n        if proxy in self.good:\n            logger.debug(\"GOOD proxy became DEAD: <%s>\" % proxy)\n        else:\n            logger.debug(\"Proxy <%s> is DEAD\" % proxy)\n        self.unchecked.discard(proxy)\n        self.good.discard(proxy)\n        self.dead.add(proxy)\n        now = _time or time.time()\n        state = self.proxies[proxy]\n        state.backoff_time = self.backoff(state.failed_attempts)\n        state.next_check = now + state.backoff_time\n        state.failed_attempts += 1",
    "docstring": "Mark a proxy as dead"
  },
  {
    "code": "def calcLorenzDistance(self):\n        LorenzSim = np.mean(np.array(self.Lorenz_hist)[self.ignore_periods:,:],axis=0)\n        dist = np.sqrt(np.sum((100*(LorenzSim - self.LorenzTarget))**2))\n        self.LorenzDistance = dist\n        return dist",
    "docstring": "Returns the sum of squared differences between simulated and target Lorenz points.\n\n        Parameters\n        ----------\n        None\n\n        Returns\n        -------\n        dist : float\n            Sum of squared distances between simulated and target Lorenz points (sqrt)"
  },
  {
    "code": "def update_release(id, **kwargs):\n    data = update_release_raw(id, **kwargs)\n    if data:\n        return utils.format_json(data)",
    "docstring": "Update an existing ProductRelease with new information"
  },
  {
    "code": "def loop_input(self, on_quit=None):\n        self._run_script(\n            self.__session, self._context.get_property(PROP_INIT_FILE)\n        )\n        script_file = self._context.get_property(PROP_RUN_FILE)\n        if script_file:\n            self._run_script(self.__session, script_file)\n        else:\n            self._run_loop(self.__session)\n        self._stop_event.set()\n        sys.stdout.write(\"Bye !\\n\")\n        sys.stdout.flush()\n        if on_quit is not None:\n            on_quit()",
    "docstring": "Reads the standard input until the shell session is stopped\n\n        :param on_quit: A call back method, called without argument when the\n                        shell session has ended"
  },
  {
    "code": "def _init_metadata(self):\n        self._mdata.update(default_mdata.get_osid_form_mdata())\n        update_display_text_defaults(self._mdata['journal_comment'], self._locale_map)\n        for element_name in self._mdata:\n            self._mdata[element_name].update(\n                {'element_id': Id(self._authority,\n                                  self._namespace,\n                                  element_name)})\n        self._journal_comment_default = self._mdata['journal_comment']['default_string_values'][0]\n        self._validation_messages = {}",
    "docstring": "Initialize OsidObjectForm metadata."
  },
  {
    "code": "def highlight_source_at_location(source: \"Source\", location: \"SourceLocation\") -> str:\n    first_line_column_offset = source.location_offset.column - 1\n    body = \" \" * first_line_column_offset + source.body\n    line_index = location.line - 1\n    line_offset = source.location_offset.line - 1\n    line_num = location.line + line_offset\n    column_offset = first_line_column_offset if location.line == 1 else 0\n    column_num = location.column + column_offset\n    lines = _re_newline.split(body)\n    len_lines = len(lines)\n    def get_line(index: int) -> Optional[str]:\n        return lines[index] if 0 <= index < len_lines else None\n    return f\"{source.name} ({line_num}:{column_num})\\n\" + print_prefixed_lines(\n        [\n            (f\"{line_num - 1}: \", get_line(line_index - 1)),\n            (f\"{line_num}: \", get_line(line_index)),\n            (\"\", \" \" * (column_num - 1) + \"^\"),\n            (f\"{line_num + 1}: \", get_line(line_index + 1)),\n        ]\n    )",
    "docstring": "Highlight source at given location.\n\n    This renders a helpful description of the location of the error in the GraphQL\n    Source document."
  },
  {
    "code": "def _ServerActions(action,alias,servers):\n\t\tif alias is None:  alias = clc.v1.Account.GetAlias()\n\t\tresults = []\n\t\tfor server in servers:\n\t\t\tr = clc.v1.API.Call('post','Server/%sServer' % (action), {'AccountAlias': alias, 'Name': server })\n\t\t\tif int(r['StatusCode']) == 0:  results.append(r)\n\t\treturn(results)",
    "docstring": "Archives the specified servers.\n\n\t\t:param action: the server action url to exec against\n\t\t:param alias: short code for a particular account.  If none will use account's default alias\n\t\t:param servers: list of server names"
  },
  {
    "code": "def query_most(num=8, kind='1'):\n        return TabPost.select().where(\n            (TabPost.kind == kind) &\n            (TabPost.valid == 1)\n        ).order_by(\n            TabPost.view_count.desc()\n        ).limit(num)",
    "docstring": "Query most viewed."
  },
  {
    "code": "def create_osd_keyring(conn, cluster, key):\n    logger = conn.logger\n    path = '/var/lib/ceph/bootstrap-osd/{cluster}.keyring'.format(\n        cluster=cluster,\n    )\n    if not conn.remote_module.path_exists(path):\n        logger.warning('osd keyring does not exist yet, creating one')\n        conn.remote_module.write_keyring(path, key)",
    "docstring": "Run on osd node, writes the bootstrap key if not there yet."
  },
  {
    "code": "def remove_file(config_map, file_key):\n    if file_key[0] == '/':\n        file_key = file_key[1::]\n    client = boto3.client(\n        's3',\n        aws_access_key_id=config_map['put_public_key'],\n        aws_secret_access_key=config_map['put_private_key']\n    )\n    client.delete_object(\n        Bucket=config_map['s3_bucket'],\n        Key=file_key\n    )",
    "docstring": "Convenience function for removing objects from AWS S3\n\n    Added by cjshaw@mit.edu, Apr 28, 2015\n    May 25, 2017: Switch to boto3"
  },
  {
    "code": "def new_floating_ip(self, **kwargs):\n        droplet_id = kwargs.get('droplet_id')\n        region = kwargs.get('region')\n        if self.api_version == 2:\n            if droplet_id is not None and region is not None:\n                raise DoError('Only one of droplet_id and region is required to create a Floating IP. ' \\\n                    'Set one of the variables and try again.')\n            elif droplet_id is None and region is None:\n                raise DoError('droplet_id or region is required to create a Floating IP. ' \\\n                    'Set one of the variables and try again.')\n            else:\n                if droplet_id is not None:\n                    params = {'droplet_id': droplet_id}\n                else:\n                    params = {'region': region}\n                json = self.request('/floating_ips', params=params, method='POST')\n                return json['floating_ip']\n        else:\n            raise DoError(v2_api_required_str)",
    "docstring": "Creates a Floating IP and assigns it to a Droplet or reserves it to a region."
  },
  {
    "code": "def email(self, value):\n        email = self.wait.until(expected.visibility_of_element_located(\n            self._email_input_locator))\n        email.clear()\n        email.send_keys(value)",
    "docstring": "Set the value of the email field."
  },
  {
    "code": "def _indent(stream, indent, *msgs):\n    for x in range(0, indent):\n        stream.write(\"  \")\n    for x in msgs:\n        stream.write(x.encode(\"ascii\", \"backslashreplace\").decode(\"ascii\"))\n    stream.write(\"\\n\")",
    "docstring": "write a message to a text stream, with indentation. Also ensures that\n    the output encoding of the messages is safe for writing."
  },
  {
    "code": "def clean(self, *args, **kwargs):\n        if self.status != LINK_STATUS.get('planned'):\n            if self.interface_a is None or self.interface_b is None:\n                raise ValidationError(_('fields \"from interface\" and \"to interface\" are mandatory in this case'))\n            if (self.interface_a_id == self.interface_b_id) or (self.interface_a == self.interface_b):\n                msg = _('link cannot have same \"from interface\" and \"to interface: %s\"') % self.interface_a\n                raise ValidationError(msg)\n        if self.status == LINK_STATUS.get('planned') and (self.node_a is None or self.node_b is None):\n            raise ValidationError(_('fields \"from node\" and \"to node\" are mandatory for planned links'))\n        if self.type != LINK_TYPES.get('radio') and (self.dbm is not None or self.noise is not None):\n            raise ValidationError(_('Only links of type \"radio\" can contain \"dbm\" and \"noise\" information'))",
    "docstring": "Custom validation\n            1. interface_a and interface_b mandatory except for planned links\n            2. planned links should have at least node_a and node_b filled in\n            3. dbm and noise fields can be filled only for radio links\n            4. interface_a and interface_b must differ\n            5. interface a and b type must match"
  },
  {
    "code": "def image_data(verbose=False):\n  global _IMAGE_DATA\n  if _IMAGE_DATA is None:\n    if verbose:\n      logger.info(\"--- Downloading image.\")\n    with contextlib.closing(urllib.request.urlopen(IMAGE_URL)) as infile:\n      _IMAGE_DATA = infile.read()\n  return _IMAGE_DATA",
    "docstring": "Get the raw encoded image data, downloading it if necessary."
  },
  {
    "code": "def create_client_for_kernel(self):\r\n        connect_output = KernelConnectionDialog.get_connection_parameters(self)\r\n        (connection_file, hostname, sshkey, password, ok) = connect_output\r\n        if not ok:\r\n            return\r\n        else:\r\n            self._create_client_for_kernel(connection_file, hostname, sshkey,\r\n                                           password)",
    "docstring": "Create a client connected to an existing kernel"
  },
  {
    "code": "def save(self, *args, **kwargs):\n        if self.descriptor_schema:\n            try:\n                validate_schema(self.descriptor, self.descriptor_schema.schema)\n                self.descriptor_dirty = False\n            except DirtyError:\n                self.descriptor_dirty = True\n        elif self.descriptor and self.descriptor != {}:\n            raise ValueError(\"`descriptor_schema` must be defined if `descriptor` is given\")\n        super().save()",
    "docstring": "Perform descriptor validation and save object."
  },
  {
    "code": "def generate_new_address(coin_symbol='btc', api_key=None):\n    assert api_key, 'api_key required'\n    assert is_valid_coin_symbol(coin_symbol)\n    if coin_symbol not in ('btc-testnet', 'bcy'):\n        WARNING_MSG = [\n                'Generating private key details server-side.',\n                'You really should do this client-side.',\n                'See https://github.com/sbuss/bitmerchant for an example.',\n                ]\n        print(' '.join(WARNING_MSG))\n    url = make_url(coin_symbol, 'addrs')\n    params = {'token': api_key}\n    r = requests.post(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)\n    return get_valid_json(r)",
    "docstring": "Takes a coin_symbol and returns a new address with it's public and private keys.\n\n    This method will create the address server side, which is inherently insecure and should only be used for testing.\n\n    If you want to create a secure address client-side using python, please check out bitmerchant:\n\n        from bitmerchant.wallet import Wallet\n        Wallet.new_random_wallet()\n\n    https://github.com/sbuss/bitmerchant"
  },
  {
    "code": "def H11(self):\n        \"Difference entropy.\"\n        return -(self.p_xminusy * np.log(self.p_xminusy + self.eps)).sum(1)",
    "docstring": "Difference entropy."
  },
  {
    "code": "def commit(message, add=False, quiet=False):\n    if add:\n        run('add .')\n    try:\n        stdout = run('commit -m %r' % str(message), quiet=quiet)\n    except GitError as e:\n        s = str(e)\n        if 'nothing to commit' in s or 'no changes added to commit' in s:\n            raise EmptyCommit(*e.inits())\n        raise\n    return re.split('[ \\]]', stdout.splitlines()[0])[1]",
    "docstring": "Commit with that message and return the SHA1 of the commit\n\n    If add is truish then \"$ git add .\" first"
  },
  {
    "code": "def __set_frame_shift_status(self):\n        if 'fs' in self.hgvs_original:\n            self.is_frame_shift = True\n            self.is_non_silent = True\n        elif re.search('[A-Z]\\d+[A-Z]+\\*', self.hgvs_original):\n            self.is_frame_shift = True\n            self.is_non_silent = True\n        else:\n            self.is_frame_shift = False",
    "docstring": "Check for frame shift and set the self.is_frame_shift flag."
  },
  {
    "code": "def parse(self, text):\n        if isinstance(text, bytes):\n            text = text.decode(\"ascii\")\n        text = re.sub(\"\\s+\", \" \", unidecode(text))\n        return self.communicate(text + \"\\n\")",
    "docstring": "Call the server and return the raw results."
  },
  {
    "code": "def brighten(color, brightness):\n    h, s, v = rgb_to_hsv(*map(down_scale, color))\n    return tuple(map(up_scale, hsv_to_rgb(h, s, v + down_scale(brightness))))",
    "docstring": "Adds or subtracts value to a color."
  },
  {
    "code": "def _CamelCaseToSnakeCase(path_name):\n  result = []\n  for c in path_name:\n    if c == '_':\n      raise ParseError('Fail to parse FieldMask: Path name '\n                       '{0} must not contain \"_\"s.'.format(path_name))\n    if c.isupper():\n      result += '_'\n      result += c.lower()\n    else:\n      result += c\n  return ''.join(result)",
    "docstring": "Converts a field name from camelCase to snake_case."
  },
  {
    "code": "def add_ref(self, ref, attr=None):\n        self.session.add_ref(self, ref, attr)\n        return self.fetch()",
    "docstring": "Add reference to resource\n\n        :param ref: reference to add\n        :type ref: Resource\n\n        :rtype: Resource"
  },
  {
    "code": "def _setup(self):\n        if isinstance(self.module, torch.nn.RNNBase): self.module.flatten_parameters = noop\n        for name_w in self.weights:\n            w = getattr(self.module, name_w)\n            del self.module._parameters[name_w]\n            self.module.register_parameter(name_w + '_raw', nn.Parameter(w.data))",
    "docstring": "for each string defined in self.weights, the corresponding\n        attribute in the wrapped module is referenced, then deleted, and subsequently\n        registered as a new parameter with a slightly modified name.\n\n        Args:\n            None\n\n         Returns:\n             None"
  },
  {
    "code": "def _parse_datetime_string(val):\n    dt = None\n    lenval = len(val)\n    fmt = {19: \"%Y-%m-%d %H:%M:%S\", 10: \"%Y-%m-%d\"}.get(lenval)\n    if fmt is None:\n        raise exc.InvalidDateTimeString(\"The supplied value '%s' does not \"\n              \"match either of the formats 'YYYY-MM-DD HH:MM:SS' or \"\n              \"'YYYY-MM-DD'.\" % val)\n    return datetime.datetime.strptime(val, fmt)",
    "docstring": "Attempts to parse a string representation of a date or datetime value, and\n    returns a datetime if successful. If not, a InvalidDateTimeString exception\n    will be raised."
  },
  {
    "code": "def createWidgets(self):\r\n        from gooey.gui.components import widgets\r\n        return [getattr(widgets, item['type'])(self, item)\r\n                for item in getin(self.widgetInfo, ['data', 'widgets'], [])]",
    "docstring": "Instantiate the Gooey Widgets that are used within the RadioGroup"
  },
  {
    "code": "def GetHandlers(self):\n    handlers = []\n    if self.ssl_context:\n      handlers.append(urllib2.HTTPSHandler(context=self.ssl_context))\n    if self.proxies:\n      handlers.append(urllib2.ProxyHandler(self.proxies))\n    return handlers",
    "docstring": "Retrieve the appropriate urllib2 handlers for the given configuration.\n\n    Returns:\n      A list of urllib2.BaseHandler subclasses to be used when making calls\n      with proxy."
  },
  {
    "code": "def find_stacks(node, strict=False):\n  fso = FindStackOps()\n  fso.visit(node)\n  AnnotateStacks(fso.push_pop_pairs, strict).visit(node)\n  return node",
    "docstring": "Find pushes and pops to the stack and annotate them as such.\n\n  Args:\n    node: An AST node that might contain stack pushes and pops.\n    strict: A boolean indicating whether to stringently test whether each\n        push and pop are matched. This is not always possible when taking\n        higher-order derivatives of code generated in split-motion.\n\n  Returns:\n    node: The node passed in, but with pushes and pops annotated in AST nodes."
  },
  {
    "code": "def requires(self):\n        value = self._schema.get(\"requires\", {})\n        if not isinstance(value, (basestring, dict)):\n            raise SchemaError(\n                \"requires value {0!r} is neither a string nor an\"\n                \" object\".format(value))\n        return value",
    "docstring": "Additional object or objects required by this object."
  },
  {
    "code": "def pre_request(self, response, exc=None):\n        if response.request.method == 'CONNECT':\n            self.start_response(\n                '200 Connection established',\n                [('content-length', '0')]\n            )\n            self.future.set_result([b''])\n            upstream = response.connection\n            dostream = self.connection\n            dostream.upgrade(partial(StreamTunnel.create, upstream))\n            upstream.upgrade(partial(StreamTunnel.create, dostream))\n            response.fire_event('post_request')\n            raise AbortEvent\n        else:\n            response.event('data_processed').bind(self.data_processed)\n            response.event('post_request').bind(self.post_request)",
    "docstring": "Start the tunnel.\n\n        This is a callback fired once a connection with upstream server is\n        established."
  },
  {
    "code": "def get_config(path):\n    if configparser is None:\n        return None\n    if os.path.exists(os.path.join(ROOT, 'config', NAME, path)):\n        path = os.path.join(ROOT, 'config', NAME, path)\n    else:\n        path = os.path.join(ROOT, 'config', path)\n    if not os.path.isfile(path):\n        return None\n    conf = open(path, 'rt').read()\n    conf = os.path.expandvars(conf)\n    config = configparser.SafeConfigParser()\n    if sys.version_info[0] == 2:\n        from io import StringIO\n        config.readfp(StringIO(unicode(conf)))\n    else:\n        config.read_string(conf)\n    return config",
    "docstring": "Load a config from disk\n\n    :param path: target config\n    :type path: unicode\n    :return:\n    :rtype: configparser.Config"
  },
  {
    "code": "def insert_all(db, schema_name, table_name, columns, items):\n    table = '{0}.{1}'.format(schema_name, table_name) if schema_name else table_name\n    columns_list = ', '.join(columns)\n    values_list = ', '.join(['?'] * len(columns))\n    query = 'INSERT INTO {table} ({columns}) VALUES ({values})'.format(\n        table=table, columns=columns_list, values=values_list)\n    for item in items:\n        values = [getattr(item, col) for col in columns]\n        db.execute(query, values)",
    "docstring": "Insert all item in given items list into the specified table, schema_name.table_name."
  },
  {
    "code": "def is_participle_clause_fragment(sentence):\n    if not _begins_with_one_of(sentence, ['VBG', 'VBN', 'JJ']):\n        return 0.0\n    if _begins_with_one_of(sentence, ['JJ']):\n        doc = nlp(sentence)\n        fw = [w for w in doc][0]\n        if fw.dep_ == 'amod':\n            return 0.0\n    if _begins_with_one_of(sentence, ['VBG']):\n        doc = nlp(sentence)\n        fw = [w for w in doc][0]\n        if fw.dep_.endswith('subj'):\n            return 0.0\n        fc = [c for c in doc.noun_chunks]\n        if str(fw) in str(fc):\n            return 0.0\n    positive_prob = models['participle'].predict([_text_to_vector(sentence,\n        trigram2idx['participle'], trigram_count['participle'])])[0][1]\n    return float(positive_prob)",
    "docstring": "Supply a sentence or fragment and recieve a confidence interval"
  },
  {
    "code": "def sprand(m, n, density, format='csr'):\n    m, n = int(m), int(n)\n    A = _rand_sparse(m, n, density, format='csr')\n    A.data = sp.rand(A.nnz)\n    return A.asformat(format)",
    "docstring": "Return a random sparse matrix.\n\n    Parameters\n    ----------\n    m, n : int\n        shape of the result\n    density : float\n        target a matrix with nnz(A) = m*n*density, 0<=density<=1\n    format : string\n        sparse matrix format to return, e.g. 'csr', 'coo', etc.\n\n    Return\n    ------\n    A : sparse matrix\n        m x n sparse matrix\n\n    Examples\n    --------\n    >>> from pyamg.gallery import sprand\n    >>> A = sprand(5,5,3/5.0)"
  },
  {
    "code": "def get_app_config(app_id):\n    try:\n        req = requests.get(\n            (\"https://clients3.google.com/\"\n             \"cast/chromecast/device/app?a={}\").format(app_id))\n        return json.loads(req.text[4:]) if req.status_code == 200 else {}\n    except ValueError:\n        return {}",
    "docstring": "Get specific configuration for 'app_id'."
  },
  {
    "code": "def get_cgi_parameter_float(form: cgi.FieldStorage,\n                            key: str) -> Optional[float]:\n    return get_float_or_none(get_cgi_parameter_str(form, key))",
    "docstring": "Extracts a float parameter from a CGI form, or None if the key is\n    absent or the string value is not convertible to ``float``."
  },
  {
    "code": "def read_float(self):\n        self.bitcount = self.bits = 0\n        return unpack('>d', self.input.read(8))[0]",
    "docstring": "Read float value."
  },
  {
    "code": "def is_valid_boundaries(self, boundaries):\n        if boundaries is not None:\n            min_ = boundaries[0]\n            for value in boundaries:\n                if value < min_:\n                    return False\n                else:\n                    min_ = value\n            return True\n        return False",
    "docstring": "checks if the boundaries are in ascending order"
  },
  {
    "code": "def deserialize_header_auth(stream, algorithm, verifier=None):\n    _LOGGER.debug(\"Starting header auth deserialization\")\n    format_string = \">{iv_len}s{tag_len}s\".format(iv_len=algorithm.iv_len, tag_len=algorithm.tag_len)\n    return MessageHeaderAuthentication(*unpack_values(format_string, stream, verifier))",
    "docstring": "Deserializes a MessageHeaderAuthentication object from a source stream.\n\n    :param stream: Source data stream\n    :type stream: io.BytesIO\n    :param algorithm: The AlgorithmSuite object type contained in the header\n    :type algorith: aws_encryption_sdk.identifiers.AlgorithmSuite\n    :param verifier: Signature verifier object (optional)\n    :type verifier: aws_encryption_sdk.internal.crypto.Verifier\n    :returns: Deserialized MessageHeaderAuthentication object\n    :rtype: aws_encryption_sdk.internal.structures.MessageHeaderAuthentication"
  },
  {
    "code": "def query(self, *args):\n        if not args or len(args) > 2:\n            raise TypeError('query() takes 2 or 3 arguments (a query or a key '\n                            'and a query) (%d given)' % (len(args) + 1))\n        elif len(args) == 1:\n            query, = args\n            return self.get('text').query(text_type(query))\n        else:\n            key, query = args\n            index_key = self.get(key)\n            if isinstance(query, string_types):\n                return index_key.query(query)\n            else:\n                if query.fielded:\n                    raise ValueError('Queries with an included key should '\n                                     'not include a field.')\n                return index_key.query(text_type(query))",
    "docstring": "Query a fulltext index by key and query or just a plain Lucene query,\n\n        i1 = gdb.nodes.indexes.get('people',type='fulltext', provider='lucene')\n        i1.query('name','do*')\n        i1.query('name:do*')\n\n        In this example, the last two line are equivalent."
  },
  {
    "code": "def validate_work_spec(cls, work_spec):\n        if 'name' not in work_spec:\n            raise ProgrammerError('work_spec lacks \"name\"')\n        if 'min_gb' not in work_spec or \\\n                not isinstance(work_spec['min_gb'], (float, int, long)):\n            raise ProgrammerError('work_spec[\"min_gb\"] must be a number')",
    "docstring": "Check that `work_spec` is valid.\n\n        It must at the very minimum contain a ``name`` and ``min_gb``.\n\n        :raise rejester.exceptions.ProgrammerError: if it isn't valid"
  },
  {
    "code": "def after_third_friday(day=None):\n    day = day if day is not None else datetime.datetime.now()\n    now = day.replace(day=1, hour=16, minute=0, second=0, microsecond=0)\n    now += relativedelta.relativedelta(weeks=2, weekday=relativedelta.FR)\n    return day > now",
    "docstring": "check if day is after month's 3rd friday"
  },
  {
    "code": "def listen_now_items(self):\n\t\tresponse = self._call(\n\t\t\tmc_calls.ListenNowGetListenNowItems\n\t\t)\n\t\tlisten_now_item_list = response.body.get('listennow_items', [])\n\t\tlisten_now_items = defaultdict(list)\n\t\tfor item in listen_now_item_list:\n\t\t\ttype_ = f\"{ListenNowItemType(item['type']).name}s\"\n\t\t\tlisten_now_items[type_].append(item)\n\t\treturn dict(listen_now_items)",
    "docstring": "Get a listing of Listen Now items.\n\n\t\tNote:\n\t\t\tThis does not include situations;\n\t\t\tuse the :meth:`situations` method instead.\n\n\t\tReturns:\n\t\t\tdict: With ``albums`` and ``stations`` keys of listen now items."
  },
  {
    "code": "def _create_sync_map(self, sync_root):\n        sync_map = SyncMap(tree=sync_root, rconf=self.rconf, logger=self.logger)\n        if self.rconf.safety_checks:\n            self.log(u\"Running sanity check on computed sync map...\")\n            if not sync_map.leaves_are_consistent:\n                self._step_failure(ValueError(u\"The computed sync map contains inconsistent fragments\"))\n            self.log(u\"Running sanity check on computed sync map... passed\")\n        else:\n            self.log(u\"Not running sanity check on computed sync map\")\n        self.task.sync_map = sync_map",
    "docstring": "If requested, check that the computed sync map is consistent.\n        Then, add it to the Task."
  },
  {
    "code": "def update_ticket(self, ticket_id=None, body=None):\n        return self.ticket.addUpdate({'entry': body}, id=ticket_id)",
    "docstring": "Update a ticket.\n\n        :param integer ticket_id: the id of the ticket to update\n        :param string body: entry to update in the ticket"
  },
  {
    "code": "def hasReaders(self, ulBuffer):\n        fn = self.function_table.hasReaders\n        result = fn(ulBuffer)\n        return result",
    "docstring": "inexpensively checks for readers to allow writers to fast-fail potentially expensive copies and writes."
  },
  {
    "code": "def get_instance(cls, encoded_key):\n        login_str = base64.b64decode(encoded_key).decode('utf-8')\n        usertoken, password = login_str.strip().split(':', 1)\n        instance = cls(usertoken, password)\n        return instance",
    "docstring": "Return an ApiAuth instance from an encoded key"
  },
  {
    "code": "def stop(self, nowait=False):\n        self._stop.set()\n        if nowait:\n            self._stop_nowait.set()\n        self.queue.put_nowait(self._sentinel_item)\n        if (self._thread.isAlive() and\n                self._thread is not threading.currentThread()):\n            self._thread.join()\n        self._thread = None",
    "docstring": "Stop the listener.\n\n        This asks the thread to terminate, and then waits for it to do so.\n        Note that if you don't call this before your application exits, there\n        may be some records still left on the queue, which won't be processed.\n        If nowait is False then thread will handle remaining items in queue and\n        stop.\n        If nowait is True then thread will be stopped even if the queue still\n        contains items."
  },
  {
    "code": "def populate_audit_fields(self, event):\n        event.updated = self._data\n        event.original = self.get_original()._data",
    "docstring": "Populates the the audit JSON fields with raw data from the model, so\n        all changes can be tracked and diffed.\n\n        Args:\n            event (Event): The Event instance to attach the data to\n            instance (fleaker.db.Model): The newly created/updated model"
  },
  {
    "code": "def schemaValidCtxtGetParserCtxt(self):\n        ret = libxml2mod.xmlSchemaValidCtxtGetParserCtxt(self._o)\n        if ret is None:raise parserError('xmlSchemaValidCtxtGetParserCtxt() failed')\n        __tmp = parserCtxt(_obj=ret)\n        return __tmp",
    "docstring": "allow access to the parser context of the schema validation\n           context"
  },
  {
    "code": "def iterate_similarity_datasets(args):\n    for dataset_name in args.similarity_datasets:\n        parameters = nlp.data.list_datasets(dataset_name)\n        for key_values in itertools.product(*parameters.values()):\n            kwargs = dict(zip(parameters.keys(), key_values))\n            yield dataset_name, kwargs, nlp.data.create(dataset_name, **kwargs)",
    "docstring": "Generator over all similarity evaluation datasets.\n\n    Iterates over dataset names, keyword arguments for their creation and the\n    created dataset."
  },
  {
    "code": "def bind(cls, origin, handler, *, name=None):\n        name = cls.__name__ if name is None else name\n        attrs = {\n            \"_origin\": origin, \"_handler\": handler,\n            \"__module__\": \"origin\",\n        }\n        return type(name, (cls,), attrs)",
    "docstring": "Bind this object to the given origin and handler.\n\n        :param origin: An instance of `Origin`.\n        :param handler: An instance of `bones.HandlerAPI`.\n        :return: A subclass of this class."
  },
  {
    "code": "def get_time_position(self, time):\n        if time < self._start or time > self._finish:\n            raise ValueError(\"time argument out of bounds\")\n        return (time - self._start) / (self._resolution / self._zoom_factor)",
    "docstring": "Get x-coordinate for given time\n\n        :param time: Time to determine x-coordinate on Canvas for\n        :type time: float\n        :return: X-coordinate for the given time\n        :rtype: int\n        :raises: ValueError"
  },
  {
    "code": "def open(self, mode):\n        if mode == 'w':\n            return self.format.pipe_writer(AtomicFtpFile(self._fs, self.path))\n        elif mode == 'r':\n            temp_dir = os.path.join(tempfile.gettempdir(), 'luigi-contrib-ftp')\n            self.__tmp_path = temp_dir + '/' + self.path.lstrip('/') + '-luigi-tmp-%09d' % random.randrange(0, 1e10)\n            self._fs.get(self.path, self.__tmp_path)\n            return self.format.pipe_reader(\n                FileWrapper(io.BufferedReader(io.FileIO(self.__tmp_path, 'r')))\n            )\n        else:\n            raise Exception(\"mode must be 'r' or 'w' (got: %s)\" % mode)",
    "docstring": "Open the FileSystem target.\n\n        This method returns a file-like object which can either be read from or written to depending\n        on the specified mode.\n\n        :param mode: the mode `r` opens the FileSystemTarget in read-only mode, whereas `w` will\n                     open the FileSystemTarget in write mode. Subclasses can implement\n                     additional options.\n        :type mode: str"
  },
  {
    "code": "def eol_distance_last(self, offset=0):\n        distance = 0\n        for char in reversed(self.string[:self.pos + offset]):\n            if char == '\\n':\n                break\n            else:\n                distance += 1\n        return distance",
    "docstring": "Return the ammount of characters until the last newline."
  },
  {
    "code": "def order_target_percent(self, asset, target,\n                             limit_price=None, stop_price=None, style=None):\n        if not self._can_order_asset(asset):\n            return None\n        amount = self._calculate_order_target_percent_amount(asset, target)\n        return self.order(asset, amount,\n                          limit_price=limit_price,\n                          stop_price=stop_price,\n                          style=style)",
    "docstring": "Place an order to adjust a position to a target percent of the\n        current portfolio value. If the position doesn't already exist, this is\n        equivalent to placing a new order. If the position does exist, this is\n        equivalent to placing an order for the difference between the target\n        percent and the current percent.\n\n        Parameters\n        ----------\n        asset : Asset\n            The asset that this order is for.\n        target : float\n            The desired percentage of the portfolio value to allocate to\n            ``asset``. This is specified as a decimal, for example:\n            0.50 means 50%.\n        limit_price : float, optional\n            The limit price for the order.\n        stop_price : float, optional\n            The stop price for the order.\n        style : ExecutionStyle\n            The execution style for the order.\n\n        Returns\n        -------\n        order_id : str\n            The unique identifier for this order.\n\n        Notes\n        -----\n        ``order_target_value`` does not take into account any open orders. For\n        example:\n\n        .. code-block:: python\n\n           order_target_percent(sid(0), 10)\n           order_target_percent(sid(0), 10)\n\n        This code will result in 20% of the portfolio being allocated to sid(0)\n        because the first call to ``order_target_percent`` will not have been\n        filled when the second ``order_target_percent`` call is made.\n\n        See :func:`zipline.api.order` for more information about\n        ``limit_price``, ``stop_price``, and ``style``\n\n        See Also\n        --------\n        :class:`zipline.finance.execution.ExecutionStyle`\n        :func:`zipline.api.order`\n        :func:`zipline.api.order_target`\n        :func:`zipline.api.order_target_value`"
  },
  {
    "code": "def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None,\n                     cql_user=None, cql_pass=None):\n    permission_cql = \"grant {0}\".format(permission) if permission else \"grant all permissions\"\n    resource_cql = \"on {0} {1}\".format(resource_type, resource) if resource else \"on all keyspaces\"\n    query = \"{0} {1} to {2}\".format(permission_cql, resource_cql, username)\n    log.debug(\"Attempting to grant permissions with query '%s'\", query)\n    try:\n        cql_query(query, contact_points, port, cql_user, cql_pass)\n    except CommandExecutionError:\n        log.critical('Could not grant permissions.')\n        raise\n    except BaseException as e:\n        log.critical('Unexpected error while granting permissions: %s', e)\n        raise\n    return True",
    "docstring": "Grant permissions to a user.\n\n    :param username:       The name of the user to grant permissions to.\n    :type  username:       str\n    :param resource:       The resource (keyspace or table), if None, permissions for all resources are granted.\n    :type  resource:       str\n    :param resource_type:  The resource_type (keyspace or table), defaults to 'keyspace'.\n    :type  resource_type:  str\n    :param permission:     A permission name (e.g. select), if None, all permissions are granted.\n    :type  permission:     str\n    :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.\n    :type  contact_points: str | list[str]\n    :param cql_user:       The Cassandra user if authentication is turned on.\n    :type  cql_user:       str\n    :param cql_pass:       The Cassandra user password if authentication is turned on.\n    :type  cql_pass:       str\n    :param port:           The Cassandra cluster port, defaults to None.\n    :type  port:           int\n    :return:\n    :rtype:\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt 'minion1' cassandra_cql.grant_permission\n\n        salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select\n\n        salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \\\n        permission=select contact_points=minion1"
  },
  {
    "code": "def count(a, axis=None):\n    axes = _normalise_axis(axis, a)\n    if axes is None or len(axes) != 1:\n        msg = \"This operation is currently limited to a single axis\"\n        raise AxisSupportError(msg)\n    return _Aggregation(a, axes[0],\n                        _CountStreamsHandler, _CountMaskedStreamsHandler,\n                        np.dtype('i'), {})",
    "docstring": "Count the non-masked elements of the array along the given axis.\n\n    .. note:: Currently limited to operating on a single axis.\n\n    :param axis: Axis or axes along which the operation is performed.\n                 The default (axis=None) is to perform the operation\n                 over all the dimensions of the input array.\n                 The axis may be negative, in which case it counts from\n                 the last to the first axis.\n                 If axis is a tuple of ints, the operation is performed\n                 over multiple axes.\n    :type axis: None, or int, or iterable of ints.\n    :return: The Array representing the requested mean.\n    :rtype: Array"
  },
  {
    "code": "def lines(self):\n        if self._lines is None:\n            with io.open(self.path, 'r', encoding='utf-8') as fh:\n                self._lines = fh.read().split('\\n')\n        return self._lines",
    "docstring": "List of file lines."
  },
  {
    "code": "def get_version():\n    if not INSTALLED:\n        try:\n            with open('version.txt', 'r') as v_fh:\n                return v_fh.read()\n        except Exception:\n            warnings.warn(\n                'Unable to resolve package version until installed',\n                UserWarning\n            )\n            return '0.0.0'\n    return p_version.get_version(HERE)",
    "docstring": "find current version information\n\n    Returns:\n        (str): version information"
  },
  {
    "code": "def stringify(data):\n    def serialize(k, v):\n        if k == \"candidates\":\n            return int(v)\n        if isinstance(v, numbers.Number):\n            if k == \"zipcode\":\n                return str(v).zfill(5)\n            return str(v)\n        return v\n    return [{k: serialize(k, v) for k, v in json_dict.items()} for json_dict in data]",
    "docstring": "Ensure all values in the dictionary are strings, except for the value for `candidate` which\n    should just be an integer.\n\n    :param data: a list of addresses in dictionary format\n    :return: the same list with all values except for `candidate` count as a string"
  },
  {
    "code": "def rm(venv_name):\n    inenv = InenvManager()\n    venv = inenv.get_venv(venv_name)\n    click.confirm(\"Delete dir {}\".format(venv.path))\n    shutil.rmtree(venv.path)",
    "docstring": "Removes the venv by name"
  },
  {
    "code": "def build_table(self, table, force=False):\n        sources = self._resolve_sources(None, [table])\n        for source in sources:\n            self.build_source(None, source, force=force)\n        self.unify_partitions()",
    "docstring": "Build all of the sources for a table"
  },
  {
    "code": "def format_sms_payload(self, message, to, sender='elkme', options=[]):\n        self.validate_number(to)\n        if not isinstance(message, str):\n            message = \" \".join(message)\n        message = message.rstrip()\n        sms = {\n            'from': sender,\n            'to': to,\n            'message': message\n        }\n        for option in options:\n          if option not in ['dontlog', 'dryrun', 'flashsms']:\n            raise ElksException('Option %s not supported' % option)\n          sms[option] = 'yes'\n        return sms",
    "docstring": "Helper function to create a SMS payload with little effort"
  },
  {
    "code": "def create_server(loop, host, port=CONTROL_PORT, reconnect=False):\n    server = Snapserver(loop, host, port, reconnect)\n    yield from server.start()\n    return server",
    "docstring": "Server factory."
  },
  {
    "code": "def check_production_parameters_exist(self):\n        for k, v in self.modelInstance.parameter_sets.items():\n            for p_id in self.modelInstance.production_params.keys():\n                if v.get(p_id):\n                    pass\n                else:\n                    v[p_id] = 1.0\n            for p_id in self.modelInstance.allocation_params.keys():\n                if v.get(p_id):\n                    pass\n                else:\n                    v[p_id] = 1.0",
    "docstring": "old versions of models won't have produciton parameters, leading to ZeroDivision errors and breaking things"
  },
  {
    "code": "def close_db(self, exception):\n        if self.is_connected:\n            if exception is None and not transaction.isDoomed():\n                transaction.commit()\n            else:\n                transaction.abort()\n            self.connection.close()",
    "docstring": "Added as a `~flask.Flask.teardown_request` to applications to\n        commit the transaction and disconnect ZODB if it was used during\n        the request."
  },
  {
    "code": "def show(self, uuid=None, term=None):\n        try:\n            if uuid:\n                uidentities = api.unique_identities(self.db, uuid)\n            elif term:\n                uidentities = api.search_unique_identities(self.db, term)\n            else:\n                uidentities = api.unique_identities(self.db)\n            for uid in uidentities:\n                enrollments = api.enrollments(self.db, uid.uuid)\n                uid.roles = enrollments\n            self.display('show.tmpl', uidentities=uidentities)\n        except NotFoundError as e:\n            self.error(str(e))\n            return e.code\n        return CMD_SUCCESS",
    "docstring": "Show the information related to unique identities.\n\n        This method prints information related to unique identities such as\n        identities or enrollments.\n\n        When <uuid> is given, it will only show information about the unique\n        identity related to <uuid>.\n\n        When <term> is set, it will only show information about those unique\n        identities that have any attribute (name, email, username, source)\n        which match with the given term. This parameter does not have any\n        effect when <uuid> is set.\n\n        :param uuid: unique identifier\n        :param term: term to match with unique identities data"
  },
  {
    "code": "def get_similar_commands(name):\n    from difflib import get_close_matches\n    name = name.lower()\n    close_commands = get_close_matches(name, commands_dict.keys())\n    if close_commands:\n        return close_commands[0]\n    else:\n        return False",
    "docstring": "Command name auto-correct."
  },
  {
    "code": "def readString(self):\n        length, is_reference = self._readLength()\n        if is_reference:\n            result = self.context.getString(length)\n            return self.context.getStringForBytes(result)\n        if length == 0:\n            return ''\n        result = self.stream.read(length)\n        self.context.addString(result)\n        return self.context.getStringForBytes(result)",
    "docstring": "Reads and returns a string from the stream."
  },
  {
    "code": "def _dataframe_to_edge_list(df):\n    cols = df.columns\n    if len(cols):\n        assert _SRC_VID_COLUMN in cols, \"Vertex DataFrame must contain column %s\" % _SRC_VID_COLUMN\n        assert _DST_VID_COLUMN in cols, \"Vertex DataFrame must contain column %s\" % _DST_VID_COLUMN\n        df = df[cols].T\n        ret = [Edge(None, None, _series=df[col]) for col in df]\n        return ret\n    else:\n        return []",
    "docstring": "Convert dataframe into list of edges, assuming that source and target ids are stored in _SRC_VID_COLUMN, and _DST_VID_COLUMN respectively."
  },
  {
    "code": "def after(f, chain=False):\n    def decorator(g):\n        @wraps(g)\n        def h(*args, **kargs):\n            if chain:\n                return f(g(*args, **kargs))\n            else:\n                r = g(*args, **kargs)\n                f(*args, **kargs)\n                return r\n        return h\n    return decorator",
    "docstring": "Runs f with the result of the decorated function."
  },
  {
    "code": "def _from_dict(cls, _dict):\n        args = {}\n        if 'input' in _dict:\n            args['input'] = MessageInput._from_dict(_dict.get('input'))\n        if 'intents' in _dict:\n            args['intents'] = [\n                RuntimeIntent._from_dict(x) for x in (_dict.get('intents'))\n            ]\n        if 'entities' in _dict:\n            args['entities'] = [\n                RuntimeEntity._from_dict(x) for x in (_dict.get('entities'))\n            ]\n        return cls(**args)",
    "docstring": "Initialize a DialogSuggestionValue object from a json dictionary."
  },
  {
    "code": "def getExtensionArgs(self):\n        aliases = NamespaceMap()\n        required = []\n        if_available = []\n        ax_args = self._newArgs()\n        for type_uri, attribute in self.requested_attributes.items():\n            if attribute.alias is None:\n                alias = aliases.add(type_uri)\n            else:\n                alias = aliases.addAlias(type_uri, attribute.alias)\n            if attribute.required:\n                required.append(alias)\n            else:\n                if_available.append(alias)\n            if attribute.count != 1:\n                ax_args['count.' + alias] = str(attribute.count)\n            ax_args['type.' + alias] = type_uri\n        if required:\n            ax_args['required'] = ','.join(required)\n        if if_available:\n            ax_args['if_available'] = ','.join(if_available)\n        return ax_args",
    "docstring": "Get the serialized form of this attribute fetch request.\n\n        @returns: The fetch request message parameters\n        @rtype: {unicode:unicode}"
  },
  {
    "code": "def determine_end_point(http_request, url):\n    if url.endswith('aggregates') or url.endswith('aggregates/'):\n        return 'aggregates'\n    else:\n        return 'detail' if is_detail_url(http_request, url) else 'list'",
    "docstring": "returns detail, list or aggregates"
  },
  {
    "code": "def types(self):\n        out = []\n        if self._transform_bytes:\n            out.append(bytes)\n        if self._transform_str:\n            out.append(str)\n        return tuple(out)",
    "docstring": "Tuple containing types transformed by this transformer."
  },
  {
    "code": "def entity_types(args):\n    r = fapi.list_entity_types(args.project, args.workspace)\n    fapi._check_response_code(r, 200)\n    return r.json().keys()",
    "docstring": "List entity types in a workspace"
  },
  {
    "code": "def shutdown(self):\n        self._must_shutdown = True\n        self._is_shutdown.wait()\n        self._meta_runner.stop()",
    "docstring": "Shutdown the accept loop and stop running payloads"
  },
  {
    "code": "def insert(self, space, t, *, replace=False, timeout=-1) -> _MethodRet:\n        return self._db.insert(space, t,\n                               replace=replace,\n                               timeout=timeout)",
    "docstring": "Insert request coroutine.\n\n            Examples:\n\n            .. code-block:: pycon\n\n                # Basic usage\n                >>> await conn.insert('tester', [0, 'hello'])\n                <Response sync=3 rowcount=1 data=[\n                    <TarantoolTuple id=0 name='hello'>\n                ]>\n\n                # Using dict as an argument tuple\n                >>> await conn.insert('tester', {\n                ...                     'id': 0\n                ...                     'text': 'hell0'\n                ...                   })\n                <Response sync=3 rowcount=1 data=[\n                    <TarantoolTuple id=0 name='hello'>\n                ]>\n\n            :param space: space id or space name.\n            :param t: tuple to insert (list object)\n            :param replace: performs replace request instead of insert\n            :param timeout: Request timeout\n\n            :returns: :class:`asynctnt.Response` instance"
  },
  {
    "code": "def serialize_to_string(self, name, datas):\n        value = datas.get('value', None)\n        if value is None:\n            msg = (\"String reference '{}' lacks of required 'value' variable \"\n                   \"or is empty\")\n            raise SerializerError(msg.format(name))\n        return value",
    "docstring": "Serialize given datas to a string.\n\n        Simply return the value from required variable``value``.\n\n        Arguments:\n            name (string): Name only used inside possible exception message.\n            datas (dict): Datas to serialize.\n\n        Returns:\n            string: Value."
  },
  {
    "code": "def SensorShare(self, sensor_id, parameters):\r\n        if not parameters['user']['id']:\r\n            parameters['user'].pop('id')\r\n        if not parameters['user']['username']:\r\n            parameters['user'].pop('username')\r\n        if self.__SenseApiCall__(\"/sensors/{0}/users\".format(sensor_id), \"POST\", parameters = parameters):\r\n            return True\r\n        else:\r\n            self.__error__ = \"api call unsuccessful\"\r\n            return False",
    "docstring": "Share a sensor with a user\r\n\r\n            @param sensor_id (int) - Id of sensor to be shared\r\n            @param parameters (dictionary) - Additional parameters for the call\r\n\r\n            @return (bool) - Boolean indicating whether the ShareSensor call was successful"
  },
  {
    "code": "def get_queryset(self, request):\n        if request.GET.get(ShowHistoryFilter.parameter_name) == '1':\n            queryset = self.model.objects.with_active_flag()\n        else:\n            queryset = self.model.objects.current_set()\n        ordering = self.get_ordering(request)\n        if ordering:\n            return queryset.order_by(*ordering)\n        return queryset",
    "docstring": "Annote the queryset with an 'is_active' property that's true iff that row is the most\n        recently added row for that particular set of KEY_FIELDS values.\n        Filter the queryset to show only is_active rows by default."
  },
  {
    "code": "def salt_syndic():\n    import salt.utils.process\n    salt.utils.process.notify_systemd()\n    import salt.cli.daemons\n    pid = os.getpid()\n    try:\n        syndic = salt.cli.daemons.Syndic()\n        syndic.start()\n    except KeyboardInterrupt:\n        os.kill(pid, 15)",
    "docstring": "Start the salt syndic."
  },
  {
    "code": "def add_results(self, *rvs, **kwargs):\n        if not rvs:\n            raise MissingTokenError.pyexc(message='No results passed')\n        for rv in rvs:\n            mi = rv._mutinfo\n            if not mi:\n                if kwargs.get('quiet'):\n                    return False\n                raise MissingTokenError.pyexc(\n                    message='Result does not contain token')\n            self._add_scanvec(mi)\n        return True",
    "docstring": "Changes the state to reflect the mutation which yielded the given\n        result.\n\n        In order to use the result, the `fetch_mutation_tokens` option must\n        have been specified in the connection string, _and_ the result\n        must have been successful.\n\n        :param rvs: One or more :class:`~.OperationResult` which have been\n            returned from mutations\n        :param quiet: Suppress errors if one of the results does not\n            contain a convertible state.\n        :return: `True` if the result was valid and added, `False` if not\n            added (and `quiet` was specified\n        :raise: :exc:`~.MissingTokenError` if `result` does not contain\n            a valid token"
  },
  {
    "code": "def assure_relation(cls, cms_page):\n        try:\n            cms_page.cascadepage\n        except cls.DoesNotExist:\n            cls.objects.create(extended_object=cms_page)",
    "docstring": "Assure that we have a foreign key relation, pointing from CascadePage onto CMSPage."
  },
  {
    "code": "def airspeed_energy_error(NAV_CONTROLLER_OUTPUT, VFR_HUD):\n    aspeed_cm = VFR_HUD.airspeed*100\n    target_airspeed = NAV_CONTROLLER_OUTPUT.aspd_error + aspeed_cm\n    airspeed_energy_error = ((target_airspeed*target_airspeed) - (aspeed_cm*aspeed_cm))*0.00005\n    return airspeed_energy_error",
    "docstring": "return airspeed energy error matching APM internals\n    This is positive when we are going too slow"
  },
  {
    "code": "def full_clean(self, *args, **kwargs):\n        name = getattr(self, 'name', self.slugName.title())\n        self.title = \"{} for {}\".format(name, dateFormat(self.except_date))\n        self.slug = \"{}-{}\".format(self.except_date, self.slugName)\n        super().full_clean(*args, **kwargs)",
    "docstring": "Apply fixups that need to happen before per-field validation occurs.\n        Sets the page's title."
  },
  {
    "code": "def save(self, *args, **kwargs):\n        self._create_slug()\n        self._create_date_slug()\n        self._render_content()\n        send_published_signal = False\n        if self.published and self.published_on is None:\n            send_published_signal = self._set_published()\n        super(Entry, self).save(*args, **kwargs)\n        if send_published_signal:\n            entry_published.send(sender=self, entry=self)",
    "docstring": "Auto-generate a slug from the name."
  },
  {
    "code": "def less_than_pi_constraints(self):\n        pi = self.prior_information\n        lt_pi = pi.loc[pi.apply(lambda x: self._is_less_const(x.obgnme) \\\n                                             and x.weight != 0.0, axis=1), \"pilbl\"]\n        return lt_pi",
    "docstring": "get the names of the prior information eqs that\n        are listed as less than inequality constraints.  Zero-\n        weighted pi are skipped\n\n        Returns\n        -------\n        pandas.Series : pilbl of prior information that are non-zero weighted\n                        less than constraints"
  },
  {
    "code": "def elapsed_time(seconds: float) -> str:\n    environ.abort_thread()\n    parts = (\n        '{}'.format(timedelta(seconds=seconds))\n        .rsplit('.', 1)\n    )\n    hours, minutes, seconds = parts[0].split(':')\n    return templating.render_template(\n        'elapsed_time.html',\n        hours=hours.zfill(2),\n        minutes=minutes.zfill(2),\n        seconds=seconds.zfill(2),\n        microseconds=parts[-1] if len(parts) > 1 else ''\n    )",
    "docstring": "Displays the elapsed time since the current step started running."
  },
  {
    "code": "def _cron_id(cron):\n    cid = None\n    if cron['identifier']:\n        cid = cron['identifier']\n    else:\n        cid = SALT_CRON_NO_IDENTIFIER\n    if cid:\n        return _ensure_string(cid)",
    "docstring": "SAFETYBELT, Only set if we really have an identifier"
  },
  {
    "code": "def client(self):\n        if not hasattr(self, \"_client\"):\n            self._client = connections.get_connection(\"default\")\n        return self._client",
    "docstring": "Get an elasticsearch client"
  },
  {
    "code": "def get_highest_build_tool(sdk_version=None):\n  if sdk_version is None:\n    sdk_version = config.sdk_version\n  android_home = os.environ.get('AG_MOBILE_SDK', os.environ.get('ANDROID_HOME'))\n  build_tool_folder = '%s/build-tools' % android_home\n  folder_list = os.listdir(build_tool_folder)\n  versions = [folder for folder in folder_list if folder.startswith('%s.' % sdk_version)]\n  if len(versions) == 0:\n    return config.build_tool_version\n  return versions[::-1][0]",
    "docstring": "Gets the highest build tool version based on major version sdk version.\n\n  :param sdk_version(int) - sdk version to be used as the marjor build tool version context.\n\n  Returns:\n    A string containg the build tool version (default is 23.0.2 if none is found)"
  },
  {
    "code": "def build_vcf_deletion(x, genome_2bit):\n    base1 = genome_2bit[x.chrom1].get(x.start1, x.start1 + 1).upper()\n    id1 = \"hydra{0}\".format(x.name)\n    return VcfLine(x.chrom1, x.start1, id1, base1, \"<DEL>\",\n                   _vcf_single_end_info(x, \"DEL\", True))",
    "docstring": "Provide representation of deletion from BedPE breakpoints."
  },
  {
    "code": "def create_from_mesh_and_lines(cls, mesh, lines):\n        mesh_with_lines = mesh.copy()\n        mesh_with_lines.add_lines(lines)\n        return mesh_with_lines",
    "docstring": "Return a copy of mesh with line vertices and edges added.\n\n        mesh: A Mesh\n        lines: A list of Polyline or Lines objects."
  },
  {
    "code": "def selinux_fs_path():\n    try:\n        for directory in ('/sys/fs/selinux', '/selinux'):\n            if os.path.isdir(directory):\n                if os.path.isfile(os.path.join(directory, 'enforce')):\n                    return directory\n        return None\n    except AttributeError:\n        return None",
    "docstring": "Return the location of the SELinux VFS directory\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' selinux.selinux_fs_path"
  },
  {
    "code": "def _del_controller(self, uid):\n        try:\n            self.controllers.pop(uid)\n            e = Event(uid, E_DISCONNECT)\n            self.queue.put_nowait(e)\n        except KeyError:\n            pass",
    "docstring": "Remove controller from internal list and tell the game.\n\n        :param uid: Unique id of the controller\n        :type uid: str"
  },
  {
    "code": "def exists_orm(session: Session,\n               ormclass: DeclarativeMeta,\n               *criteria: Any) -> bool:\n    q = session.query(ormclass)\n    for criterion in criteria:\n        q = q.filter(criterion)\n    exists_clause = q.exists()\n    return bool_from_exists_clause(session=session,\n                                   exists_clause=exists_clause)",
    "docstring": "Detects whether a database record exists for the specified ``ormclass``\n    and ``criteria``.\n\n    Example usage:\n\n    .. code-block:: python\n\n        bool_exists = exists_orm(session, MyClass, MyClass.myfield == value)"
  },
  {
    "code": "def saveScreenCapture(self, path=None, name=None):\n        bitmap = self.getBitmap()\n        target_file = None\n        if path is None and name is None:\n            _, target_file = tempfile.mkstemp(\".png\")\n        elif name is None:\n            _, tpath = tempfile.mkstemp(\".png\")\n            target_file = os.path.join(path, tfile)\n        else:\n            target_file = os.path.join(path, name+\".png\")\n        cv2.imwrite(target_file, bitmap)\n        return target_file",
    "docstring": "Saves the region's bitmap"
  },
  {
    "code": "def default_if_empty(self, default):\n        if self.closed():\n            raise ValueError(\"Attempt to call default_if_empty() on a \"\n                             \"closed Queryable.\")\n        return self._create(self._generate_default_if_empty_result(default))",
    "docstring": "If the source sequence is empty return a single element sequence\n        containing the supplied default value, otherwise return the source\n        sequence unchanged.\n\n        Note: This method uses deferred execution.\n\n        Args:\n            default: The element to be returned if the source sequence is empty.\n\n        Returns:\n            The source sequence, or if the source sequence is empty an sequence\n            containing a single element with the supplied default value.\n\n        Raises:\n            ValueError: If the Queryable has been closed."
  },
  {
    "code": "def handle_response(self, content, target=None, single_result=True, raw=False):\n        response = content['response']\n        self.check_errors(response)\n        data = response.get('data')\n        if is_empty(data):\n            return data\n        elif is_paginated(data):\n            if 'count' in data and not data['count']:\n                return data['data']\n            data = data['data']\n        if raw:\n            return data\n        return self.init_all_objects(data, target=target, single_result=single_result)",
    "docstring": "Parses response, checks it."
  },
  {
    "code": "def lmpool(cvals):\n    lenvals = ctypes.c_int(len(max(cvals, key=len)) + 1)\n    n = ctypes.c_int(len(cvals))\n    cvals = stypes.listToCharArrayPtr(cvals, xLen=lenvals, yLen=n)\n    libspice.lmpool_c(cvals, lenvals, n)",
    "docstring": "Load the variables contained in an internal buffer into the\n    kernel pool.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lmpool_c.html\n\n    :param cvals: list of strings.\n    :type cvals: list of str"
  },
  {
    "code": "def startup_gce_instance(instance_name, project, zone, username, machine_type,\n                         image, public_key, disk_name=None):\n    log_green(\"Started...\")\n    log_yellow(\"...Creating GCE Jenkins Slave Instance...\")\n    instance_config = get_gce_instance_config(\n        instance_name, project, zone, machine_type, image,\n        username, public_key, disk_name\n    )\n    operation = _get_gce_compute().instances().insert(\n        project=project,\n        zone=zone,\n        body=instance_config\n    ).execute()\n    result = gce_wait_until_done(operation)\n    if not result:\n        raise RuntimeError(\"Creation of VM timed out or returned no result\")\n    log_green(\"Instance has booted\")",
    "docstring": "For now, jclouds is broken for GCE and we will have static slaves\n    in Jenkins.  Use this to boot them."
  },
  {
    "code": "def _add_word(completer):\n    def inner(word: str):\n        completer.words.add(word)\n    return inner",
    "docstring": "Used to add words to the completors"
  },
  {
    "code": "def replace_headers(source_pdb_content, target_pdb_content):\n        s = PDB(source_pdb_content)\n        t = PDB(target_pdb_content)\n        source_headers = []\n        for l in s.lines:\n            if l[:6].strip() in non_header_records:\n                break\n            else:\n                source_headers.append(l)\n        target_body = []\n        in_header = True\n        for l in t.lines:\n            if l[:6].strip() in non_header_records:\n                in_header = False\n            if not in_header:\n                target_body.append(l)\n        return '\\n'.join(source_headers + target_body)",
    "docstring": "Takes the headers from source_pdb_content and adds them to target_pdb_content, removing any headers that\n           target_pdb_content had.\n           Only the content up to the first structural line are taken from source_pdb_content and only the content from\n           the first structural line in target_pdb_content are taken."
  },
  {
    "code": "def add_to(self, email):\n        if email.substitutions:\n            if isinstance(email.substitutions, list):\n                for substitution in email.substitutions:\n                    self.add_substitution(substitution)\n            else:\n                self.add_substitution(email.substitutions)\n        if email.subject:\n            if isinstance(email.subject, str):\n                self.subject = email.subject\n            else:\n                self.subject = email.subject.get()\n        self._tos.append(email.get())",
    "docstring": "Add a single recipient to this Personalization.\n\n        :type email: Email"
  },
  {
    "code": "def away_save_percentage(self):\n        try:\n            save_pct = float(self.away_saves) / float(self.home_shots_on_goal)\n            return round(save_pct, 3)\n        except ZeroDivisionError:\n            return 0.0",
    "docstring": "Returns a ``float`` of the percentage of shots the away team saved.\n        Percentage ranges from 0-1."
  },
  {
    "code": "def add_significance_indicator(plot, col_a=0, col_b=1, significant=False):\n    plot_bottom, plot_top = plot.get_ylim()\n    line_height = vertical_percent(plot, 0.1)\n    plot_top = plot_top + line_height\n    plot.set_ylim(top=plot_top + line_height * 2)\n    color = \"black\"\n    line_top = plot_top + line_height\n    plot.plot([col_a, col_a, col_b, col_b], [plot_top, line_top, line_top, plot_top], lw=1.5, color=color)\n    indicator = \"*\" if significant else \"ns\"\n    plot.text((col_a + col_b) * 0.5, line_top, indicator, ha=\"center\", va=\"bottom\", color=color)",
    "docstring": "Add a p-value significance indicator."
  },
  {
    "code": "def start(self):\n        old_start_count = self.__start_count\n        self.__start_count += 1\n        if old_start_count == 0:\n            self.data_channel_start_event.fire()",
    "docstring": "Called from hardware source when data starts streaming."
  },
  {
    "code": "def dump(self):\n        return {\n            'target': str(self.target),\n            'data': base64.b64encode(self.data).decode('utf-8'),\n            'var_id': self.var_id,\n            'valid': self.valid\n        }",
    "docstring": "Serialize this object."
  },
  {
    "code": "def humanize_bytes(size):\n    if size == 0: return \"0\"\n    if size is None: return \"\"\n    assert size >= 0, \"`size` cannot be negative, got %d\" % size\n    suffixes = \"TGMK\"\n    maxl = len(suffixes)\n    for i in range(maxl + 1):\n        shift = (maxl - i) * 10\n        if size >> shift == 0: continue\n        ndigits = 0\n        for nd in [3, 2, 1]:\n            if size >> (shift + 12 - nd * 3) == 0:\n                ndigits = nd\n                break\n        if ndigits == 0 or size == (size >> shift) << shift:\n            rounded_val = str(size >> shift)\n        else:\n            rounded_val = \"%.*f\" % (ndigits, size / (1 << shift))\n        return \"%s%sB\" % (rounded_val, suffixes[i] if i < maxl else \"\")",
    "docstring": "Convert given number of bytes into a human readable representation, i.e. add\n    prefix such as KB, MB, GB, etc. The `size` argument must be a non-negative\n    integer.\n\n    :param size: integer representing byte size of something\n    :return: string representation of the size, in human-readable form"
  },
  {
    "code": "def generate_GitHub_token(*, note=\"Doctr token for pushing to gh-pages from Travis\", scopes=None, **login_kwargs):\n    if scopes is None:\n        scopes = ['public_repo']\n    AUTH_URL = \"https://api.github.com/authorizations\"\n    data = {\n        \"scopes\": scopes,\n        \"note\": note,\n        \"note_url\": \"https://github.com/drdoctr/doctr\",\n        \"fingerprint\": str(uuid.uuid4()),\n    }\n    return GitHub_post(data, AUTH_URL, **login_kwargs)",
    "docstring": "Generate a GitHub token for pushing from Travis\n\n    The scope requested is public_repo.\n\n    If no password or OTP are provided, they will be requested from the\n    command line.\n\n    The token created here can be revoked at\n    https://github.com/settings/tokens."
  },
  {
    "code": "def copy_with(self, geometry=None, properties=None, assets=None):\n        def copy_assets_object(asset):\n            obj = asset.get(\"__object\")\n            if hasattr(\"copy\", obj):\n                new_obj = obj.copy()\n            if obj:\n                asset[\"__object\"] = new_obj\n        geometry = geometry or self.geometry.copy()\n        new_properties = copy.deepcopy(self.properties)\n        if properties:\n            new_properties.update(properties)\n        if not assets:\n            assets = copy.deepcopy(self.assets)\n            map(copy_assets_object, assets.values())\n        else:\n            assets = {}\n        return self.__class__(geometry, new_properties, assets)",
    "docstring": "Generate a new GeoFeature with different geometry or preperties."
  },
  {
    "code": "def calcSMA(self):\n        try:\n            return eq.KeplersThirdLaw(None, self.star.M, self.P).a\n        except HierarchyError:\n            return np.nan",
    "docstring": "Calculates the semi-major axis from Keplers Third Law"
  },
  {
    "code": "def trusted_permission(f):\n    @functools.wraps(f)\n    def wrapper(request, *args, **kwargs):\n        trusted(request)\n        return f(request, *args, **kwargs)\n    return wrapper",
    "docstring": "Access only by D1 infrastructure."
  },
  {
    "code": "def cumsum(x, axis=0, exclusive=False):\n  if not is_xla_compiled():\n    return tf.cumsum(x, axis=axis, exclusive=exclusive)\n  x_shape = shape_list(x)\n  rank = len(x_shape)\n  length = x_shape[axis]\n  my_range = tf.range(length)\n  comparator = tf.less if exclusive else tf.less_equal\n  mask = tf.cast(\n      comparator(tf.expand_dims(my_range, 1), tf.expand_dims(my_range, 0)),\n      x.dtype)\n  ret = tf.tensordot(x, mask, axes=[[axis], [0]])\n  if axis != rank - 1:\n    ret = tf.transpose(\n        ret,\n        list(range(axis)) + [rank - 1] + list(range(axis, rank - 1)))\n  return ret",
    "docstring": "TPU hack for tf.cumsum.\n\n  This is equivalent to tf.cumsum and is faster on TPU as of 04/2018 unless\n  the axis dimension is very large.\n\n  Args:\n    x: a Tensor\n    axis: an integer\n    exclusive: a boolean\n\n  Returns:\n    Tensor of the same shape as x."
  },
  {
    "code": "def get(self, instance, acl):\n        base_url = self._url.format(instance=instance)\n        url = '{base}{aclid}/'.format(base=base_url, aclid=acl)\n        response = requests.get(url, **self._default_request_kwargs)\n        data = self._get_response_data(response)\n        return self._concrete_acl(data)",
    "docstring": "Get an ACL by ID belonging to the instance specified by name.\n\n        :param str instance: The name of the instance from which to fetch the ACL.\n        :param str acl: The ID of the ACL to fetch.\n        :returns: An :py:class:`Acl` object, or None if ACL does not exist.\n        :rtype: :py:class:`Acl`"
  },
  {
    "code": "def _make_pmap_field_type(key_type, value_type):\n    type_ = _pmap_field_types.get((key_type, value_type))\n    if type_ is not None:\n        return type_\n    class TheMap(CheckedPMap):\n        __key_type__ = key_type\n        __value_type__ = value_type\n        def __reduce__(self):\n            return (_restore_pmap_field_pickle,\n                    (self.__key_type__, self.__value_type__, dict(self)))\n    TheMap.__name__ = \"{0}To{1}PMap\".format(\n        _types_to_names(TheMap._checked_key_types),\n        _types_to_names(TheMap._checked_value_types))\n    _pmap_field_types[key_type, value_type] = TheMap\n    return TheMap",
    "docstring": "Create a subclass of CheckedPMap with the given key and value types."
  },
  {
    "code": "def get_ipv4(hostname):\n    addrinfo = socket.getaddrinfo(hostname, None, socket.AF_INET,\n                                  socket.SOCK_STREAM)\n    return [addrinfo[x][4][0] for x in range(len(addrinfo))]",
    "docstring": "Get list of ipv4 addresses for hostname"
  },
  {
    "code": "def succ(cmd, check_stderr=True, stdout=None, stderr=None):\n    code, out, err = run(cmd)\n    if stdout is not None:\n        stdout[:] = out\n    if stderr is not None:\n        stderr[:] = err\n    if code != 0:\n        for l in out:\n            print(l)\n    assert code == 0, 'Return: {} {}\\nStderr: {}'.format(code, cmd, err)\n    if check_stderr:\n        assert err == [], 'Error: {} {}'.format(err, code)\n    return code, out, err",
    "docstring": "Alias to run with check return code and stderr"
  },
  {
    "code": "def get_all_incomings(chebi_ids):\n    all_incomings = [get_incomings(chebi_id) for chebi_id in chebi_ids]\n    return [x for sublist in all_incomings for x in sublist]",
    "docstring": "Returns all incomings"
  },
  {
    "code": "def command_getkeys(self, command, *args, encoding='utf-8'):\n        return self.execute(b'COMMAND', b'GETKEYS', command, *args,\n                            encoding=encoding)",
    "docstring": "Extract keys given a full Redis command."
  },
  {
    "code": "def __json_strnum_to_bignum(json_object):\n        for key in ('id', 'week', 'in_reply_to_id', 'in_reply_to_account_id', 'logins', 'registrations', 'statuses'):\n            if (key in json_object and isinstance(json_object[key], six.text_type)):\n                try:\n                    json_object[key] = int(json_object[key])\n                except ValueError:\n                    pass\n        return json_object",
    "docstring": "Converts json string numerals to native python bignums."
  },
  {
    "code": "def ConsultarCTGActivosPorPatente(self, patente=\"ZZZ999\"):\n        \"Consulta de CTGs activos por patente\"\n        ret = self.client.consultarCTGActivosPorPatente(request=dict(\n                        auth={\n                            'token': self.Token, 'sign': self.Sign,\n                            'cuitRepresentado': self.Cuit, },\n                        patente=patente,\n                            ))['response']\n        self.__analizar_errores(ret)\n        datos = ret.get('arrayConsultarCTGActivosPorPatenteResponse')\n        if datos:\n            self.DatosCTG = datos\n            self.LeerDatosCTG(pop=False)\n            return True\n        else:\n            self.DatosCTG = []\n        return False",
    "docstring": "Consulta de CTGs activos por patente"
  },
  {
    "code": "def get_all_instances(sql, class_type, *args, **kwargs):\n        records = CoyoteDb.get_all_records(sql, *args, **kwargs)\n        instances = [CoyoteDb.get_object_from_dictionary_representation(\n            dictionary=record, class_type=class_type) for record in records]\n        for instance in instances:\n            instance._query = sql\n        return instances",
    "docstring": "Returns a list of instances of class_type populated with attributes from the DB record\n\n        @param sql: Sql statement to execute\n        @param class_type: The type of class to instantiate and populate with DB record\n        @return: Return a list of instances with attributes set to values from DB"
  },
  {
    "code": "def parse(cls, addr):\n        if addr.endswith('/'):\n            raise ValueError(\"Uris must not end in '/'\")\n        parts = addr.split('/')\n        if ':' in parts[0]:\n            node, parts[0] = parts[0], ''\n        else:\n            node = None\n        ret = None\n        for step in parts:\n            ret = Uri(name=step, parent=ret, node=node)\n            node = None\n        return ret",
    "docstring": "Parses a new `Uri` instance from a string representation of a URI.\n\n        >>> u1 = Uri.parse('/foo/bar')\n        >>> u1.node, u1.steps, u1.path, u1.name\n        (None, ['', 'foo', 'bar'], '/foo/bar', 'bar')\n        >>> u2 = Uri.parse('somenode:123/foo/bar')\n        >>> u2.node, u1.steps, u2.path, ur2.name\n        ('somenode:123', ['', 'foo', 'bar'], '/foo/bar', 'bar')\n        >>> u1 = Uri.parse('foo/bar')\n        >>> u1.node, u1.steps, u1.path, u1.name\n        (None, ['foo', 'bar'], 'foo/bar', 'bar')"
  },
  {
    "code": "def do_quit(self, _):\n        if (self.server.is_server_running() == 'yes' or\n                self.server.is_server_running() == 'maybe'):\n            user_input = raw_input(\"Quitting shell will shut down experiment \"\n                                    \"server. Really quit? y or n: \")\n            if user_input == 'y':\n                self.server_off()\n            else:\n                return False\n        return True",
    "docstring": "Override do_quit for network clean up."
  },
  {
    "code": "def add_translation(sender):\n\tsignals.post_save.connect(_save_translations, sender=sender)\n\tsender.add_to_class(\"get_fieldtranslations\", _get_fieldtranslations)\n\tsender.add_to_class(\"load_translations\", _load_translations)\n\tsender.add_to_class(\"set_translation_fields\", _set_dict_translations)\n\tsender.add_to_class(\"_\", _get_translated_field)\n\tsender.add_to_class(\"get_trans_attr\", _get_translated_field)\n\tsender.add_to_class(\"_t\", _get_translated_field)",
    "docstring": "Adds the actions to a class."
  },
  {
    "code": "def selectnotnone(table, field, complement=False):\n    return select(table, field, lambda v: v is not None,\n                  complement=complement)",
    "docstring": "Select rows where the given field is not `None`."
  },
  {
    "code": "def iterweekdays(self, d1, d2):\n        for dt in self.iterdays(d1, d2):\n            if not self.isweekend(dt):\n                yield dt",
    "docstring": "Date iterator returning dates in d1 <= x < d2, excluding weekends"
  },
  {
    "code": "def script_deployment(path, script, submap=None):\n    if submap is None:\n        submap = {}\n    script = substitute(script, submap)\n    return libcloud.compute.deployment.ScriptDeployment(script, path)",
    "docstring": "Return a ScriptDeployment from script with possible template\n    substitutions."
  },
  {
    "code": "def crashlog_clean(name, timestamp, size, **kwargs):\n    ctx = Context(**kwargs)\n    ctx.execute_action('crashlog:clean', **{\n        'storage': ctx.repo.create_secure_service('storage'),\n        'name': name,\n        'size': size,\n        'timestamp': timestamp,\n    })",
    "docstring": "For application NAME leave SIZE crashlogs or remove all crashlogs with timestamp > TIMESTAMP."
  },
  {
    "code": "def right_model_factory(*, validator=validators.is_right_model,\n                        ld_type='Right', **kwargs):\n    return _model_factory(validator=validator, ld_type=ld_type, **kwargs)",
    "docstring": "Generate a Right model.\n\n    Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and\n    ``ld_context`` as keyword arguments."
  },
  {
    "code": "def rebin(a, newshape):\n    slices = [slice(0, old, float(old)/new)\n              for old, new in zip(a.shape, newshape)]\n    coordinates = numpy.mgrid[slices]\n    indices = coordinates.astype('i')\n    return a[tuple(indices)]",
    "docstring": "Rebin an array to a new shape."
  },
  {
    "code": "def render(self, text, add_header=False):\n        html = mark_text(text, self.aesthetics, self.rules)\n        html = html.replace('\\n', '<br/>')\n        if add_header:\n            html = '\\n'.join([HEADER, self.css, MIDDLE, html, FOOTER])\n        return html",
    "docstring": "Render the HTML.\n\n        Parameters\n        ----------\n        add_header: boolean (default: False)\n            If True, add HTML5 header and footer.\n\n        Returns\n        -------\n        str\n            The rendered HTML."
  },
  {
    "code": "def get_schema_spec(self, key):\n    member_node = self._ast_node.member.get(key, None)\n    if not member_node:\n      return schema.AnySchema()\n    s = framework.eval(member_node.member_schema, self.env(self))\n    if not isinstance(s, schema.Schema):\n      raise ValueError('Node %r with schema node %r should evaluate to Schema, got %r' % (member_node, member_node.member_schema, s))\n    return s",
    "docstring": "Return the evaluated schema expression from a subkey."
  },
  {
    "code": "def items(self):\n        return [(section, dict(self.conf.items(section, raw=True))) for \\\n            section in [section for section in self.conf.sections()]]",
    "docstring": "Settings as key-value pair."
  },
  {
    "code": "def unlink_intermediate(self, sourceId, targetId):\n        source = self.database['items'][(self.database.get('name'), sourceId)]\n        target = self.database['items'][(self.database.get('name'), targetId)]\n        production_exchange = [x['input'] for x in source['exchanges'] if x['type'] == 'production'][0]\n        new_exchanges = [x for x in target['exchanges'] if x['input'] != production_exchange]\n        target['exchanges'] = new_exchanges\n        self.parameter_scan()\n        return True",
    "docstring": "Remove a link between two processes"
  },
  {
    "code": "def get_es_requirements(es_version):\n    es_version = es_version.replace('x', '0')\n    es_version = map(int, es_version.split('.'))\n    if es_version >= [6]:\n        return \">=6.0.0, <7.0.0\"\n    elif es_version >= [5]:\n        return \">=5.0.0, <6.0.0\"\n    elif es_version >= [2]:\n        return \">=2.0.0, <3.0.0\"\n    elif es_version >= [1]:\n        return \">=1.0.0, <2.0.0\"\n    else:\n        return \"<1.0.0\"",
    "docstring": "Get the requirements string for elasticsearch-py library\n\n    Returns a suitable requirements string for the elsaticsearch-py library\n    according to the elasticsearch version to be supported (es_version)"
  },
  {
    "code": "def mainswitch_state(frames):\n        reader = MessageReader(frames)\n        res = reader.string(\"command\").bool(\"state\").assert_end().get()\n        if res.command != \"mainswitch.state\":\n            raise MessageParserError(\"Command is not 'mainswitch.state'\")\n        return (res.state,)",
    "docstring": "parse a mainswitch.state message"
  },
  {
    "code": "def parse_channel_name(cls, name, strict=True):\n        match = cls.MATCH.search(name)\n        if match is None or (strict and (\n                match.start() != 0 or match.end() != len(name))):\n            raise ValueError(\"Cannot parse channel name according to LIGO \"\n                             \"channel-naming convention T990033\")\n        return match.groupdict()",
    "docstring": "Decompose a channel name string into its components\n\n        Parameters\n        ----------\n        name : `str`\n            name to parse\n        strict : `bool`, optional\n            require exact matching of format, with no surrounding text,\n            default `True`\n\n        Returns\n        -------\n        match : `dict`\n            `dict` of channel name components with the following keys:\n\n            - `'ifo'`: the letter-number interferometer prefix\n            - `'system'`: the top-level system name\n            - `'subsystem'`: the second-level sub-system name\n            - `'signal'`: the remaining underscore-delimited signal name\n            - `'trend'`: the trend type\n            - `'ndstype'`: the NDS2 channel suffix\n\n            Any optional keys that aren't found will return a value of `None`\n\n        Raises\n        ------\n        ValueError\n            if the name cannot be parsed with at least an IFO and SYSTEM\n\n        Examples\n        --------\n        >>> Channel.parse_channel_name('L1:LSC-DARM_IN1_DQ')\n        {'ifo': 'L1',\n         'ndstype': None,\n         'signal': 'IN1_DQ',\n         'subsystem': 'DARM',\n         'system': 'LSC',\n         'trend': None}\n\n        >>> Channel.parse_channel_name(\n            'H1:ISI-BS_ST1_SENSCOR_GND_STS_X_BLRMS_100M_300M.rms,m-trend')\n        {'ifo': 'H1',\n         'ndstype': 'm-trend',\n         'signal': 'ST1_SENSCOR_GND_STS_X_BLRMS_100M_300M',\n         'subsystem': 'BS',\n         'system': 'ISI',\n         'trend': 'rms'}"
  },
  {
    "code": "def ssh_cmd(self, name, ssh_command):\n        if not self.container_exists(name=name):\n            exit(\"Unknown container {0}\".format(name))\n        if not self.container_running(name=name):\n            exit(\"Container {0} is not running\".format(name))\n        ip = self.get_container_ip(name)\n        if not ip:\n            exit(\"Failed to get network address for \"\n                 \"container {0}\".format(name))\n        if ssh_command:\n            ssh.do_cmd('root', ip, 'password', \" \".join(ssh_command))\n        else:\n            ssh.launch_shell('root', ip, 'password')",
    "docstring": "SSH into given container and executre command if given"
  },
  {
    "code": "def floor(x, context=None):\n    return _apply_function_in_current_context(\n        BigFloat,\n        mpfr.mpfr_rint_floor,\n        (BigFloat._implicit_convert(x),),\n        context,\n    )",
    "docstring": "Return the next lower or equal integer to x.\n\n    If the result is not exactly representable, it will be rounded according to\n    the current context.\n\n    Note that it's possible for the result to be larger than ``x``.  See the\n    documentation of the :func:`ceil` function for more information.\n\n    .. note::\n\n       This function corresponds to the MPFR function ``mpfr_rint_floor``,\n       not to ``mpfr_floor``."
  },
  {
    "code": "def set_input(self):\r\n\t\tname = self.attrs.get(\"_override\", self.widget.__class__.__name__)\r\n\t\tself.values[\"field\"] = str(FIELDS.get(name, FIELDS.get(None))(self.field, self.attrs))",
    "docstring": "Returns form input field of Field."
  },
  {
    "code": "def get_color_scheme(name):\r\n    name = name.lower()\r\n    scheme = {}\r\n    for key in COLOR_SCHEME_KEYS:\r\n        try:\r\n            scheme[key] = CONF.get('appearance', name+'/'+key)\r\n        except:\r\n            scheme[key] = CONF.get('appearance', 'spyder/'+key)\r\n    return scheme",
    "docstring": "Get a color scheme from config using its name"
  },
  {
    "code": "def _pfp__set_watch(self, watch_fields, update_func, *func_call_info):\n        self._pfp__watch_fields = watch_fields\n        for watch_field in watch_fields:\n            watch_field._pfp__watch(self)\n        self._pfp__update_func = update_func\n        self._pfp__update_func_call_info = func_call_info",
    "docstring": "Subscribe to update events on each field in ``watch_fields``, using\n        ``update_func`` to update self's value when ``watch_field``\n        changes"
  },
  {
    "code": "def BuildLegacySubject(subject_id, approval_type):\n  at = rdf_objects.ApprovalRequest.ApprovalType\n  if approval_type == at.APPROVAL_TYPE_CLIENT:\n    return \"aff4:/%s\" % subject_id\n  elif approval_type == at.APPROVAL_TYPE_HUNT:\n    return \"aff4:/hunts/%s\" % subject_id\n  elif approval_type == at.APPROVAL_TYPE_CRON_JOB:\n    return \"aff4:/cron/%s\" % subject_id\n  raise ValueError(\"Invalid approval type.\")",
    "docstring": "Builds a legacy AFF4 urn string for a given subject and approval type."
  },
  {
    "code": "def paste(self):\r\n        text = to_text_string(QApplication.clipboard().text())\r\n        if len(text.splitlines()) > 1:\r\n            if self.new_input_line:\r\n                self.on_new_line()\r\n            self.remove_selected_text()\n            end = self.get_current_line_from_cursor()\r\n            lines = self.get_current_line_to_cursor() + text + end\r\n            self.clear_line()\r\n            self.execute_lines(lines)\r\n            self.move_cursor(-len(end))\r\n        else:\r\n            ShellBaseWidget.paste(self)",
    "docstring": "Reimplemented slot to handle multiline paste action"
  },
  {
    "code": "def connectExec(connection, protocol, commandLine):\n    deferred = connectSession(connection, protocol)\n    @deferred.addCallback\n    def requestSubsystem(session):\n        return session.requestExec(commandLine)\n    return deferred",
    "docstring": "Connect a Protocol to a ssh exec session"
  },
  {
    "code": "def run_config(self, project, run=None, entity=None):\n        query = gql(\n)\n        response = self.gql(query, variable_values={\n            'name': project, 'run': run, 'entity': entity\n        })\n        if response['model'] == None:\n            raise ValueError(\"Run {}/{}/{} not found\".format(entity, project, run) )\n        run = response['model']['bucket']\n        commit = run['commit']\n        patch = run['patch']\n        config = json.loads(run['config'] or '{}')\n        if len(run['files']['edges']) > 0:\n            url = run['files']['edges'][0]['node']['url']\n            res = requests.get(url)\n            res.raise_for_status()\n            metadata = res.json()\n        else:\n            metadata = {}\n        return (commit, config, patch, metadata)",
    "docstring": "Get the relevant configs for a run\n\n        Args:\n            project (str): The project to download, (can include bucket)\n            run (str, optional): The run to download\n            entity (str, optional): The entity to scope this project to."
  },
  {
    "code": "def update_beliefs(self, corpus_id):\n        corpus = self.get_corpus(corpus_id)\n        be = BeliefEngine(self.scorer)\n        stmts = list(corpus.statements.values())\n        be.set_prior_probs(stmts)\n        for uuid, correct in corpus.curations.items():\n            stmt = corpus.statements.get(uuid)\n            if stmt is None:\n                logger.warning('%s is not in the corpus.' % uuid)\n                continue\n            stmt.belief = correct\n        belief_dict = {st.uuid: st.belief for st in stmts}\n        return belief_dict",
    "docstring": "Return updated belief scores for a given corpus.\n\n        Parameters\n        ----------\n        corpus_id : str\n            The ID of the corpus for which beliefs are to be updated.\n\n        Returns\n        -------\n        dict\n            A dictionary of belief scores with keys corresponding to Statement\n            UUIDs and values to new belief scores."
  },
  {
    "code": "def wordrelationships(relationshiplist):\n    relationships = etree.fromstring(\n        '<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006'\n        '/relationships\"></Relationships>')\n    count = 0\n    for relationship in relationshiplist:\n        rel_elm = makeelement('Relationship', nsprefix=None,\n                              attributes={'Id':     'rId'+str(count+1),\n                                          'Type':   relationship[0],\n                                          'Target': relationship[1]}\n                              )\n        relationships.append(rel_elm)\n        count += 1\n    return relationships",
    "docstring": "Generate a Word relationships file"
  },
  {
    "code": "def get(self, buffer_type, offset):\n        if buffer_type == u'streaming':\n            chosen_buffer = self.streaming_data\n        else:\n            chosen_buffer = self.storage_data\n        if offset >= len(chosen_buffer):\n            raise StreamEmptyError(\"Invalid index given in get command\", requested=offset, stored=len(chosen_buffer), buffer=buffer_type)\n        return chosen_buffer[offset]",
    "docstring": "Get a reading from the buffer at offset.\n\n        Offset is specified relative to the start of the data buffer.\n        This means that if the buffer rolls over, the offset for a given\n        item will appear to change.  Anyone holding an offset outside of this\n        engine object will need to be notified when rollovers happen (i.e.\n        popn is called so that they can update their offset indices)\n\n        Args:\n            buffer_type (str): The buffer to pop from (either u\"storage\" or u\"streaming\")\n            offset (int): The offset of the reading to get"
  },
  {
    "code": "def _load_config_section(self, section_name):\n        if self._config.has_section(section_name):\n            section = dict(self._config.items(section_name))\n        elif self._config.has_section(\"Default\"):\n            section = dict(self._config.items(\"Default\"))\n        else:\n            raise KeyError((\n                \"'{}' was not found in the configuration file and no default \" +\n                \"configuration was provided.\"\n            ).format(section_name))\n        if \"protocol\" in section and \"host\" in section and \"token\" in section:\n            return section\n        else:\n            raise KeyError(\n                \"Missing values in configuration data. \" +\n                \"Must contain: protocol, host, token\"\n            )",
    "docstring": "Method to load the specific Service section from the config file if it\n        exists, or fall back to the default\n\n        Args:\n            section_name (str): The desired service section name\n\n        Returns:\n            (dict): the section parameters"
  },
  {
    "code": "def _has_fulltext(cls, uri):\n\t\tcoll = cls._get_collection(uri)\n\t\twith ExceptionTrap(storage.pymongo.errors.OperationFailure) as trap:\n\t\t\tcoll.create_index([('message', 'text')], background=True)\n\t\treturn not trap",
    "docstring": "Enable full text search on the messages if possible and return True.\n\t\tIf the full text search cannot be enabled, then return False."
  },
  {
    "code": "def _is_device_active(device):\n        cmd = ['dmsetup', 'info', device]\n        dmsetup_info = util.subp(cmd)\n        for dm_line in dmsetup_info.stdout.split(\"\\n\"):\n            line = dm_line.split(':')\n            if ('State' in line[0].strip()) and ('ACTIVE' in line[1].strip()):\n                return True\n        return False",
    "docstring": "Checks dmsetup to see if a device is already active"
  },
  {
    "code": "def get_gaf_format(self):\n        sep = '\\t'\n        return sep.join(\n            [self.gene, self.db_ref, self.term.id, self.evidence,\n             '|'.join(self.db_ref), '|'.join(self.with_)])",
    "docstring": "Return a GAF 2.0-compatible string representation of the annotation.\n\n        Parameters\n        ----------\n\n        Returns\n        -------\n        str\n            The formatted string."
  },
  {
    "code": "def patch_script_directory(graph):\n    temporary_dir = mkdtemp()\n    from_config_original = getattr(ScriptDirectory, \"from_config\")\n    run_env_original = getattr(ScriptDirectory, \"run_env\")\n    with open(join(temporary_dir, \"script.py.mako\"), \"w\") as file_:\n        file_.write(make_script_py_mako())\n        file_.flush()\n    setattr(ScriptDirectory, \"from_config\", classmethod(make_script_directory))\n    setattr(ScriptDirectory, \"run_env\", run_online_migration)\n    setattr(ScriptDirectory, \"graph\", graph)\n    try:\n        yield temporary_dir\n    finally:\n        delattr(ScriptDirectory, \"graph\")\n        setattr(ScriptDirectory, \"run_env\", run_env_original)\n        setattr(ScriptDirectory, \"from_config\", from_config_original)\n        rmtree(temporary_dir)",
    "docstring": "Monkey patch the `ScriptDirectory` class, working around configuration assumptions.\n\n    Changes include:\n      - Using a generated, temporary directory (with a generated, temporary `script.py.mako`)\n        instead of the assumed script directory.\n      - Using our `make_script_directory` function instead of the default `ScriptDirectory.from_config`.\n      - Using our `run_online_migration` function instead of the default `ScriptDirectory.run_env`.\n      - Injecting the current object graph."
  },
  {
    "code": "def _weight_init(self, m, n, name):\n        x = np.sqrt(6.0/(m+n))\n        with tf.name_scope(name) as scope:\n            return tf.Variable(\n                tf.random_uniform(\n                    [m, n], minval=-x, maxval=x), name=name)",
    "docstring": "Uses the Xavier Glorot method for initializing weights. This is\n        built in to TensorFlow as `tf.contrib.layers.xavier_initializer`,\n        but it's nice to see all the details."
  },
  {
    "code": "def _consume_blanklines(self):\n        empty_size = 0\n        first_line = True\n        while True:\n            line = self.reader.readline()\n            if len(line) == 0:\n                return None, empty_size\n            stripped = line.rstrip()\n            if len(stripped) == 0 or first_line:\n                empty_size += len(line)\n                if len(stripped) != 0:\n                    err_offset = self.fh.tell() - self.reader.rem_length() - empty_size\n                    sys.stderr.write(self.INC_RECORD.format(err_offset, line))\n                    self.err_count += 1\n                first_line = False\n                continue\n            return line, empty_size",
    "docstring": "Consume blank lines that are between records\n        - For warcs, there are usually 2\n        - For arcs, may be 1 or 0\n        - For block gzipped files, these are at end of each gzip envelope\n          and are included in record length which is the full gzip envelope\n        - For uncompressed, they are between records and so are NOT part of\n          the record length\n\n          count empty_size so that it can be substracted from\n          the record length for uncompressed\n\n          if first line read is not blank, likely error in WARC/ARC,\n          display a warning"
  },
  {
    "code": "def as_qubit_order(val: 'qubit_order_or_list.QubitOrderOrList'\n                       ) -> 'QubitOrder':\n        if isinstance(val, collections.Iterable):\n            return QubitOrder.explicit(val)\n        if isinstance(val, QubitOrder):\n            return val\n        raise ValueError(\n            \"Don't know how to interpret <{}> as a Basis.\".format(val))",
    "docstring": "Converts a value into a basis.\n\n        Args:\n            val: An iterable or a basis.\n\n        Returns:\n            The basis implied by the value."
  },
  {
    "code": "def get_intercepted(target):\n    function = _get_function(target)\n    intercepted = getattr(function, _INTERCEPTED, None)\n    ctx = getattr(function, _INTERCEPTED_CTX, None)\n    return intercepted, ctx",
    "docstring": "Get intercepted function and ctx from input target.\n\n    :param target: target from where getting the intercepted function and ctx.\n\n    :return: target intercepted function and ctx.\n        (None, None) if no intercepted function exist.\n        (fn, None) if not ctx exists.\n    :rtype: tuple"
  },
  {
    "code": "def send_request(self, request):\n        self.aggregate.wait_for_host(self.urlparts[1])\n        kwargs = self.get_request_kwargs()\n        kwargs[\"allow_redirects\"] = False\n        self._send_request(request, **kwargs)",
    "docstring": "Send request and store response in self.url_connection."
  },
  {
    "code": "def get_page_dpi(pageinfo, options):\n    \"Get the DPI when nonsquare DPI is tolerable\"\n    xres = max(\n        pageinfo.xres or VECTOR_PAGE_DPI,\n        options.oversample or 0,\n        VECTOR_PAGE_DPI if pageinfo.has_vector else 0,\n    )\n    yres = max(\n        pageinfo.yres or VECTOR_PAGE_DPI,\n        options.oversample or 0,\n        VECTOR_PAGE_DPI if pageinfo.has_vector else 0,\n    )\n    return (float(xres), float(yres))",
    "docstring": "Get the DPI when nonsquare DPI is tolerable"
  },
  {
    "code": "def get_annotated_list(cls, parent=None, max_depth=None):\n        result, info = [], {}\n        start_depth, prev_depth = (None, None)\n        qs = cls.get_tree(parent)\n        if max_depth:\n            qs = qs.filter(depth__lte=max_depth)\n        return cls.get_annotated_list_qs(qs)",
    "docstring": "Gets an annotated list from a tree branch.\n\n        :param parent:\n\n            The node whose descendants will be annotated. The node itself\n            will be included in the list. If not given, the entire tree\n            will be annotated.\n\n        :param max_depth:\n\n            Optionally limit to specified depth"
  },
  {
    "code": "def _raise_or_append_exception(self):\n        message = (\n            'Connection dead, no heartbeat or data received in >= '\n            '%ds' % (\n                self._interval * 2\n            )\n        )\n        why = AMQPConnectionError(message)\n        if self._exceptions is None:\n            raise why\n        self._exceptions.append(why)",
    "docstring": "The connection is presumably dead and we need to raise or\n        append an exception.\n\n            If we have a list for exceptions, append the exception and let\n            the connection handle it, if not raise the exception here.\n\n        :return:"
  },
  {
    "code": "def inspect(logdir='', event_file='', tag=''):\n  print(PRINT_SEPARATOR +\n        'Processing event files... (this can take a few minutes)\\n' +\n        PRINT_SEPARATOR)\n  inspection_units = get_inspection_units(logdir, event_file, tag)\n  for unit in inspection_units:\n    if tag:\n      print('Event statistics for tag {} in {}:'.format(tag, unit.name))\n    else:\n      print('These tags are in {}:'.format(unit.name))\n      print_dict(get_unique_tags(unit.field_to_obs))\n      print(PRINT_SEPARATOR)\n      print('Event statistics for {}:'.format(unit.name))\n    print_dict(get_dict_to_print(unit.field_to_obs), show_missing=(not tag))\n    print(PRINT_SEPARATOR)",
    "docstring": "Main function for inspector that prints out a digest of event files.\n\n  Args:\n    logdir: A log directory that contains event files.\n    event_file: Or, a particular event file path.\n    tag: An optional tag name to query for.\n\n  Raises:\n    ValueError: If neither logdir and event_file are given, or both are given."
  },
  {
    "code": "def add_view(self, request, **kwargs):\n        if self.model is Page:\n            return HttpResponseRedirect(self.get_content_models()[0].add_url)\n        return super(PageAdmin, self).add_view(request, **kwargs)",
    "docstring": "For the ``Page`` model, redirect to the add view for the\n        first page model, based on the ``ADD_PAGE_ORDER`` setting."
  },
  {
    "code": "def mean(self, *args, **kwargs):\n        nv.validate_window_func('mean', args, kwargs)\n        return self._apply('ewma', **kwargs)",
    "docstring": "Exponential weighted moving average.\n\n        Parameters\n        ----------\n        *args, **kwargs\n            Arguments and keyword arguments to be passed into func."
  },
  {
    "code": "def reduce_opacity(img, opacity):\n    assert opacity >= 0 and opacity <= 1\n    if img.mode != 'RGBA':\n        img = img.convert('RGBA')\n    else:\n        img = img.copy()\n    alpha = img.split()[3]\n    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)\n    img.putalpha(alpha)\n    return img",
    "docstring": "Returns an image with reduced opacity."
  },
  {
    "code": "def voice(self):\n        if self._voice is None:\n            from twilio.rest.voice import Voice\n            self._voice = Voice(self)\n        return self._voice",
    "docstring": "Access the Voice Twilio Domain\n\n        :returns: Voice Twilio Domain\n        :rtype: twilio.rest.voice.Voice"
  },
  {
    "code": "def setup(app):\n    sphinx_compatibility._app = app\n    app.add_config_value('sphinx_gallery_conf', DEFAULT_GALLERY_CONF, 'html')\n    for key in ['plot_gallery', 'abort_on_example_error']:\n        app.add_config_value(key, get_default_config_value(key), 'html')\n    try:\n        app.add_css_file('gallery.css')\n    except AttributeError:\n        app.add_stylesheet('gallery.css')\n    extensions_attr = '_extensions' if hasattr(\n        app, '_extensions') else 'extensions'\n    if 'sphinx.ext.autodoc' in getattr(app, extensions_attr):\n        app.connect('autodoc-process-docstring', touch_empty_backreferences)\n    app.connect('builder-inited', generate_gallery_rst)\n    app.connect('build-finished', copy_binder_files)\n    app.connect('build-finished', summarize_failing_examples)\n    app.connect('build-finished', embed_code_links)\n    metadata = {'parallel_read_safe': True,\n                'parallel_write_safe': False,\n                'version': _sg_version}\n    return metadata",
    "docstring": "Setup sphinx-gallery sphinx extension"
  },
  {
    "code": "def _on_mouse_released(self, event):\n        if event.button() == 1 and self._deco:\n            cursor = TextHelper(self.editor).word_under_mouse_cursor()\n            if cursor and cursor.selectedText():\n                self._timer.request_job(\n                    self.word_clicked.emit, cursor)",
    "docstring": "mouse pressed callback"
  },
  {
    "code": "def register_arguments(self, parser):\n        parser.add_argument('x', type=int, help='the first value')\n        parser.add_argument('y', type=int, help='the second value')",
    "docstring": "Guacamole method used by the argparse ingredient.\n\n        :param parser:\n            Argument parser (from :mod:`argparse`) specific to this command."
  },
  {
    "code": "def add_output_list_opt(self, opt, outputs):\n        self.add_opt(opt)\n        for out in outputs:\n            self.add_opt(out)\n            self._add_output(out)",
    "docstring": "Add an option that determines a list of outputs"
  },
  {
    "code": "def is_valid_article_slug(article, language, slug):\n    from ..models import Title\n    qs = Title.objects.filter(slug=slug, language=language)\n    if article.pk:\n        qs = qs.exclude(Q(language=language) & Q(article=article))\n        qs = qs.exclude(article__publisher_public=article)\n    if qs.count():\n        return False\n    return True",
    "docstring": "Validates given slug depending on settings."
  },
  {
    "code": "def add_row(self):\n        tbl = self._tbl\n        tr = tbl.add_tr()\n        for gridCol in tbl.tblGrid.gridCol_lst:\n            tc = tr.add_tc()\n            tc.width = gridCol.w\n        return _Row(tr, self)",
    "docstring": "Return a |_Row| instance, newly added bottom-most to the table."
  },
  {
    "code": "def run(self):\n        config = self.state.document.settings.env.config\n        processes = get_processes(config.autoprocess_process_dir, config.autoprocess_source_base_url)\n        process_nodes = []\n        for process in sorted(processes, key=itemgetter('name')):\n            process_nodes.extend(self.make_process_node(process))\n        return process_nodes",
    "docstring": "Create a list of process definitions."
  },
  {
    "code": "def create_subscriptions(config, profile_name):\n    if 'kinesis' in config.subscription.keys():\n        data = config.subscription['kinesis']\n        function_name = config.name\n        stream_name = data['stream']\n        batch_size = data['batch_size']\n        starting_position = data['starting_position']\n        starting_position_ts = None\n        if starting_position == 'AT_TIMESTAMP':\n            ts = data.get('starting_position_timestamp')\n            starting_position_ts = datetime.strptime(ts, '%Y-%m-%dT%H:%M:%SZ')\n        s = KinesisSubscriber(config, profile_name,\n                              function_name, stream_name, batch_size,\n                              starting_position,\n                              starting_position_ts=starting_position_ts)\n        s.subscribe()",
    "docstring": "Adds supported subscriptions"
  },
  {
    "code": "def convert_frame(frame, body_encoding=None):\n    lines = []\n    body = None\n    if frame.body:\n        if body_encoding:\n            body = encode(frame.body, body_encoding)\n        else:\n            body = encode(frame.body)\n        if HDR_CONTENT_LENGTH in frame.headers:\n            frame.headers[HDR_CONTENT_LENGTH] = len(body)\n    if frame.cmd:\n        lines.append(encode(frame.cmd))\n        lines.append(ENC_NEWLINE)\n    for key, vals in sorted(frame.headers.items()):\n        if vals is None:\n            continue\n        if type(vals) != tuple:\n            vals = (vals,)\n        for val in vals:\n            lines.append(encode(\"%s:%s\\n\" % (key, val)))\n    lines.append(ENC_NEWLINE)\n    if body:\n        lines.append(body)\n    if frame.cmd:\n        lines.append(ENC_NULL)\n    return lines",
    "docstring": "Convert a frame to a list of lines separated by newlines.\n\n    :param Frame frame: the Frame object to convert\n\n    :rtype: list(str)"
  },
  {
    "code": "def reset(self):\n        self.stepid = 0\n        for task, agent in zip(self.tasks, self.agents):\n            task.reset()\n            agent.module.reset()\n            agent.history.reset()",
    "docstring": "Sets initial conditions for the experiment."
  },
  {
    "code": "def _parse_device_path(self, device_path, char_path_override=None):\n        try:\n            device_type = device_path.rsplit('-', 1)[1]\n        except IndexError:\n            warn(\"The following device path was skipped as it could \"\n                 \"not be parsed: %s\" % device_path, RuntimeWarning)\n            return\n        realpath = os.path.realpath(device_path)\n        if realpath in self._raw:\n            return\n        self._raw.append(realpath)\n        if device_type == 'kbd':\n            self.keyboards.append(Keyboard(self, device_path,\n                                           char_path_override))\n        elif device_type == 'mouse':\n            self.mice.append(Mouse(self, device_path,\n                                   char_path_override))\n        elif device_type == 'joystick':\n            self.gamepads.append(GamePad(self,\n                                         device_path,\n                                         char_path_override))\n        else:\n            self.other_devices.append(OtherDevice(self,\n                                                  device_path,\n                                                  char_path_override))",
    "docstring": "Parse each device and add to the approriate list."
  },
  {
    "code": "def _initialize(self, show_bounds, reset_camera, outline):\n        self.plotter.subplot(*self.loc)\n        if outline is None:\n            self.plotter.add_mesh(self.input_dataset.outline_corners(),\n                    reset_camera=False, color=vtki.rcParams['outline_color'],\n                    loc=self.loc)\n        elif outline:\n            self.plotter.add_mesh(self.input_dataset.outline(),\n                    reset_camera=False, color=vtki.rcParams['outline_color'],\n                    loc=self.loc)\n        if show_bounds:\n            self.plotter.show_bounds(reset_camera=False, loc=loc)\n        if reset_camera:\n            cpos = self.plotter.get_default_cam_pos()\n            self.plotter.camera_position = cpos\n            self.plotter.reset_camera()\n            self.plotter.camera_set = False",
    "docstring": "Outlines the input dataset and sets up the scene"
  },
  {
    "code": "def delete_s3_bucket(client, resource):\n    if dbconfig.get('enable_delete_s3_buckets', NS_AUDITOR_REQUIRED_TAGS, False):\n        client.delete_bucket(Bucket=resource.id)\n    return ActionStatus.SUCCEED, resource.metrics()",
    "docstring": "Delete an S3 bucket\n\n    This function will try to delete an S3 bucket\n\n    Args:\n        client (:obj:`boto3.session.Session.client`): A boto3 client object\n        resource (:obj:`Resource`): The resource object to terminate\n\n    Returns:\n        `ActionStatus`"
  },
  {
    "code": "def get_time_server():\n    ret = salt.utils.mac_utils.execute_return_result(\n        'systemsetup -getnetworktimeserver')\n    return salt.utils.mac_utils.parse_return(ret)",
    "docstring": "Display the currently set network time server.\n\n    :return: the network time server\n    :rtype: str\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' timezone.get_time_server"
  },
  {
    "code": "def to_json(value, **kwargs):\n        if isinstance(value, HasProperties):\n            return value.serialize(**kwargs)\n        try:\n            return json.loads(json.dumps(value))\n        except TypeError:\n            raise TypeError(\n                \"Cannot convert type {} to JSON without calling 'serialize' \"\n                \"on an instance of Instance Property and registering a custom \"\n                \"serializer\".format(value.__class__.__name__)\n            )",
    "docstring": "Convert instance to JSON"
  },
  {
    "code": "def _CheckIsFile(self, file_entry):\n    if definitions.FILE_ENTRY_TYPE_FILE not in self._file_entry_types:\n      return False\n    return file_entry.IsFile()",
    "docstring": "Checks the is_file find specification.\n\n    Args:\n      file_entry (FileEntry): file entry.\n\n    Returns:\n      bool: True if the file entry matches the find specification, False if not."
  },
  {
    "code": "def stop_periodic_snapshots(self):\n        if self._periodic_thread and self._periodic_thread.isAlive():\n            self._periodic_thread.stop = True\n            self._periodic_thread.join()\n            self._periodic_thread = None",
    "docstring": "Post a stop signal to the thread that takes the periodic snapshots. The\n        function waits for the thread to terminate which can take some time\n        depending on the configured interval."
  },
  {
    "code": "def _expected_condition_find_element(self, element):\n        from toolium.pageelements.page_element import PageElement\n        web_element = False\n        try:\n            if isinstance(element, PageElement):\n                element._web_element = None\n                element._find_web_element()\n                web_element = element._web_element\n            elif isinstance(element, tuple):\n                web_element = self.driver_wrapper.driver.find_element(*element)\n        except NoSuchElementException:\n            pass\n        return web_element",
    "docstring": "Tries to find the element, but does not thrown an exception if the element is not found\n\n        :param element: PageElement or element locator as a tuple (locator_type, locator_value) to be found\n        :returns: the web element if it has been found or False\n        :rtype: selenium.webdriver.remote.webelement.WebElement or appium.webdriver.webelement.WebElement"
  },
  {
    "code": "def get_project(self, name):\n        uri = '{base}/{project}'.format(base=self.BASE_URI, project=name)\n        resp = self._client.get(uri, model=models.Project)\n        return resp",
    "docstring": "Retrives project information by name\n\n        :param name: The formal project name in string form."
  },
  {
    "code": "def hook_up(self, router: UrlDispatcher):\n        router.add_get(self.webhook_path, self.check_hook)\n        router.add_post(self.webhook_path, self.receive_events)",
    "docstring": "Dynamically hooks the right webhook paths"
  },
  {
    "code": "def new_status(self, new_status):\n        allowed_values = [\"NEW\", \"DONE\", \"REJECTED\"]\n        if new_status not in allowed_values:\n            raise ValueError(\n                \"Invalid value for `new_status` ({0}), must be one of {1}\"\n                .format(new_status, allowed_values)\n            )\n        self._new_status = new_status",
    "docstring": "Sets the new_status of this BuildSetStatusChangedEvent.\n\n        :param new_status: The new_status of this BuildSetStatusChangedEvent.\n        :type: str"
  },
  {
    "code": "def statusEnquiry():\n    a = TpPd(pd=0x3)\n    b = MessageType(mesType=0x34)\n    packet = a / b\n    return packet",
    "docstring": "STATUS ENQUIRY Section 9.3.28"
  },
  {
    "code": "def swap_columns(self, column_name_1, column_name_2, inplace=False):\n        if inplace:\n            self.__is_dirty__ = True\n            with cython_context():\n                if self._is_vertex_frame():\n                    graph_proxy = self.__graph__.__proxy__.swap_vertex_fields(column_name_1, column_name_2)\n                    self.__graph__.__proxy__ = graph_proxy\n                elif self._is_edge_frame():\n                    graph_proxy = self.__graph__.__proxy__.swap_edge_fields(column_name_1, column_name_2)\n                    self.__graph__.__proxy__ = graph_proxy\n            return self\n        else:\n            return super(GFrame, self).swap_columns(column_name_1, column_name_2, inplace=inplace)",
    "docstring": "Swaps the columns with the given names.\n\n        If inplace == False (default) this operation does not modify the\n        current SFrame, returning a new SFrame.\n\n        If inplace == True, this operation modifies the current\n        SFrame, returning self.\n\n        Parameters\n        ----------\n        column_name_1 : string\n            Name of column to swap\n\n        column_name_2 : string\n            Name of other column to swap\n\n        inplace : bool, optional. Defaults to False.\n            Whether the SFrame is modified in place."
  },
  {
    "code": "def convert(self, destination_units, *, convert_variables=False):\n        if self.units is None and (destination_units is None or destination_units == \"None\"):\n            return\n        if not wt_units.is_valid_conversion(self.units, destination_units):\n            valid = wt_units.get_valid_conversions(self.units)\n            raise wt_exceptions.UnitsError(valid, destination_units)\n        if convert_variables:\n            for v in self.variables:\n                v.convert(destination_units)\n        self.units = destination_units",
    "docstring": "Convert axis to destination_units.\n\n        Parameters\n        ----------\n        destination_units : string\n            Destination units.\n        convert_variables : boolean (optional)\n            Toggle conversion of stored arrays. Default is False."
  },
  {
    "code": "def example_lab_to_rgb():\n    print(\"=== RGB Example: Lab->RGB ===\")\n    lab = LabColor(0.903, 16.296, -2.217)\n    print(lab)\n    rgb = convert_color(lab, sRGBColor)\n    print(rgb)\n    print(\"=== End Example ===\\n\")",
    "docstring": "Conversions to RGB are a little more complex mathematically. There are also\n    several kinds of RGB color spaces. When converting from a device-independent\n    color space to RGB, sRGB is assumed unless otherwise specified with the\n    target_rgb keyword arg."
  },
  {
    "code": "def check_ups_alarms_present(the_session, the_helper, the_snmp_value):\n    if the_snmp_value != '0':\n        the_helper.add_status(pynag.Plugins.critical)\n    else:\n        the_helper.add_status(pynag.Plugins.ok)\n    the_helper.set_summary(\"{} active alarms \".format(the_snmp_value))",
    "docstring": "OID .1.3.6.1.2.1.33.1.6.1.0\n    MIB excerpt\n    The present number of active alarm conditions."
  },
  {
    "code": "def publish(branch, full_force=False):\n    checkout(branch)\n    try:\n        push('--force --set-upstream origin', branch)\n    except ExistingReference:\n        if full_force:\n            push('origin --delete', branch)\n            push('--force --set-upstream origin', branch)",
    "docstring": "Publish that branch, i.e. push it to origin"
  },
  {
    "code": "def _load(self):\n        if self.dbfile is not None:\n            with open(self.dbfile, 'r') as f:\n                self._db = json.loads(f.read())\n        else:\n            self._db = {}",
    "docstring": "Load the database from its ``dbfile`` if it has one"
  },
  {
    "code": "def keyword_hookup(self, noteId, keywords):\n        try:\n            self.cur.execute(\"DELETE FROM notekeyword WHERE noteid=?\", [noteId])\n        except:\n            self.error(\"ERROR: cannot unhook previous keywords\")\n        for keyword in keywords:\n            keyword = keyword.decode('utf-8')\n            self.fyi(\" inserting keyword:\", keyword)\n            keywordId = self.con.execute(\"SELECT keywordId FROM keyword WHERE keyword = ?;\", [keyword]).fetchone()\n            try:\n                if keywordId:\n                    self.fyi(\"  (existing keyword with id: %s)\" % keywordId)\n                    keywordId = keywordId[0]\n                else:\n                    self.fyi(\"  (new keyword)\")\n                    self.cur.execute(\"INSERT INTO keyword(keyword) VALUES (?);\", [keyword])\n                    keywordId = self.cur.lastrowid\n                self.con.execute(\"INSERT INTO notekeyword(noteId, keywordID) VALUES(?, ?)\", [noteId, keywordId])\n            except:\n                self.error(\"error hooking up keyword '%s'\" % keyword)\n        self.con.commit()",
    "docstring": "Unhook existing cross-linking entries."
  },
  {
    "code": "def _get_wcs_request(self, bbox, time_interval, size_x, size_y, maxcc, time_difference, custom_url_params):\n        return WcsRequest(layer=self.data_feature,\n                          bbox=bbox,\n                          time=time_interval,\n                          resx=size_x, resy=size_y,\n                          maxcc=maxcc,\n                          custom_url_params=custom_url_params,\n                          time_difference=time_difference,\n                          image_format=self.image_format,\n                          data_source=self.data_source,\n                          instance_id=self.instance_id)",
    "docstring": "Returns WCS request."
  },
  {
    "code": "def get_username(identifier):\n    pattern = re.compile('.+@\\w+\\..+')\n    if pattern.match(identifier):\n        try:\n            user = User.objects.get(email=identifier)\n        except:\n            raise Http404\n        else:\n            return user.username\n    else:\n        return identifier",
    "docstring": "Checks if a string is a email adress or not."
  },
  {
    "code": "def do_set_log_level(self, arg):\n        if arg in ['i', 'v']:\n            _LOGGING.info('Setting log level to %s', arg)\n            if arg == 'i':\n                _LOGGING.setLevel(logging.INFO)\n                _INSTEONPLM_LOGGING.setLevel(logging.INFO)\n            else:\n                _LOGGING.setLevel(logging.DEBUG)\n                _INSTEONPLM_LOGGING.setLevel(logging.DEBUG)\n        else:\n            _LOGGING.error('Log level value error.')\n            self.do_help('set_log_level')",
    "docstring": "Set the log level.\n\n        Usage:\n            set_log_level i|v\n        Parameters:\n            log_level: i - info | v - verbose"
  },
  {
    "code": "def build_endpoint_name(cls, name, endpoint_prefix=None):\n        if endpoint_prefix is None:\n            endpoint_prefix = 'api_{}'.format(\n                cls.__name__.replace('Resource', '').lower()\n            )\n        endpoint_prefix = endpoint_prefix.rstrip('_')\n        return '_'.join([endpoint_prefix, name])",
    "docstring": "Given a ``name`` & an optional ``endpoint_prefix``, this generates a name\n        for a URL.\n\n        :param name: The name for the URL (ex. 'detail')\n        :type name: string\n\n        :param endpoint_prefix: (Optional) A prefix for the URL's name (for\n            resolving). The default is ``None``, which will autocreate a prefix\n            based on the class name. Ex: ``BlogPostResource`` ->\n            ``api_blogpost_list``\n        :type endpoint_prefix: string\n\n        :returns: The final name\n        :rtype: string"
  },
  {
    "code": "def addToPrePrepares(self, pp: PrePrepare) -> None:\n        key = (pp.viewNo, pp.ppSeqNo)\n        self.prePrepares[key] = pp\n        self.lastPrePrepareSeqNo = pp.ppSeqNo\n        self.last_accepted_pre_prepare_time = pp.ppTime\n        self.dequeue_prepares(*key)\n        self.dequeue_commits(*key)\n        self.stats.inc(TPCStat.PrePrepareRcvd)\n        self.tryPrepare(pp)",
    "docstring": "Add the specified PRE-PREPARE to this replica's list of received\n        PRE-PREPAREs and try sending PREPARE\n\n        :param pp: the PRE-PREPARE to add to the list"
  },
  {
    "code": "def rnormal(mu, tau, size=None):\n    return np.random.normal(mu, 1. / np.sqrt(tau), size)",
    "docstring": "Random normal variates."
  },
  {
    "code": "def xyz(self):\n        if not self.children:\n            pos = np.expand_dims(self._pos, axis=0)\n        else:\n            arr = np.fromiter(itertools.chain.from_iterable(\n                particle.pos for particle in self.particles()), dtype=float)\n            pos = arr.reshape((-1, 3))\n        return pos",
    "docstring": "Return all particle coordinates in this compound.\n\n        Returns\n        -------\n        pos : np.ndarray, shape=(n, 3), dtype=float\n            Array with the positions of all particles."
  },
  {
    "code": "def ping(host, timeout=False, return_boolean=False):\n    if timeout:\n        timeout = int(timeout) * 1000 // 4\n        cmd = ['ping', '-n', '4', '-w', six.text_type(timeout), salt.utils.network.sanitize_host(host)]\n    else:\n        cmd = ['ping', '-n', '4', salt.utils.network.sanitize_host(host)]\n    if return_boolean:\n        ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n        if ret['retcode'] != 0:\n            return False\n        else:\n            return True\n    else:\n        return __salt__['cmd.run'](cmd, python_shell=False)",
    "docstring": "Performs a ping to a host\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' network.ping archlinux.org\n\n    .. versionadded:: 2016.11.0\n\n    Return a True or False instead of ping output.\n\n    .. code-block:: bash\n\n        salt '*' network.ping archlinux.org return_boolean=True\n\n    Set the time to wait for a response in seconds.\n\n    .. code-block:: bash\n\n        salt '*' network.ping archlinux.org timeout=3"
  },
  {
    "code": "def home_abbreviation(self):\n        abbr = re.sub(r'.*/teams/', '', str(self._home_name))\n        abbr = re.sub(r'/.*', '', abbr)\n        return abbr",
    "docstring": "Returns a ``string`` of the home team's abbreviation, such as 'KAN'."
  },
  {
    "code": "def members(self):\n        with self._mutex:\n            if not self._members:\n                self._members = {}\n                for o in self.organisations:\n                    self._members[o.org_id] = o.obj.get_members()\n        return self._members",
    "docstring": "Member components if this component is composite."
  },
  {
    "code": "def get_term_freq(self, go_id):\n        num_ns = float(self.get_total_count(self.go2obj[go_id].namespace))\n        return float(self.get_count(go_id))/num_ns if num_ns != 0 else 0",
    "docstring": "Returns the frequency at which a particular GO term has\n            been observed in the annotations."
  },
  {
    "code": "def show_profiles(self):\n        for i, (id, profiler, showed) in enumerate(self.profilers):\n            if not showed and profiler:\n                profiler.show(id)\n                self.profilers[i][2] = True",
    "docstring": "Print the profile stats to stdout"
  },
  {
    "code": "def setup_files(class_dir, seed):\n    random.seed(seed)\n    files = list_files(class_dir)\n    files.sort()\n    random.shuffle(files)\n    return files",
    "docstring": "Returns shuffled files"
  },
  {
    "code": "def get_html(self):\r\n        if self.__htmltree is not None:\r\n            return self.__htmltree\r\n        else:\r\n            self.__make_tree()\r\n            return self.__htmltree",
    "docstring": "Generates if need be and returns a simpler html document with text"
  },
  {
    "code": "async def start_component(workload: CoroutineFunction[T], *args: Any, **kwargs: Any) -> Component[T]:\n    commands_a, commands_b = pipe()\n    events_a, events_b = pipe()\n    task = asyncio.create_task(workload(*args, commands=commands_b, events=events_b, **kwargs))\n    component = Component[T](commands_a, events_a, task)\n    await component.wait_for_start()\n    return component",
    "docstring": "\\\n    Starts the passed `workload` with additional `commands` and `events` pipes.\n    The workload will be executed as a task.\n\n    A simple example. Note that here, the component is exclusively reacting to commands,\n    and the owner waits for acknowledgements to its commands, making the order of outputs predictable.\n\n    >>> @component_workload\n    ... async def component(msg, *, commands, events):\n    ...     # do any startup tasks here\n    ...     print(\"> component starting up...\")\n    ...     await events.send(Component.EVENT_START)\n    ...\n    ...     count = 0\n    ...     while True:\n    ...         command = await commands.recv()\n    ...         if command == Component.COMMAND_STOP:\n    ...             # honor stop commands\n    ...             break\n    ...         elif command == 'ECHO':\n    ...             print(f\"> {msg}\")\n    ...             count += 1\n    ...             # acknowledge the command was serviced completely\n    ...             await commands.send(None)\n    ...         else:\n    ...             # unknown command; terminate\n    ...             # by closing the commands pipe,\n    ...             # the caller (if waiting for a reply) will receive an EOFError\n    ...             await commands.send(eof=True)\n    ...             raise ValueError\n    ...\n    ...     # do any cleanup tasks here, probably in a finally block\n    ...     print(\"> component cleaning up...\")\n    ...     return count\n    ...\n    >>> async def example():\n    ...     print(\"call start\")\n    ...     comp = await start_component(component, \"Hello World\")\n    ...     print(\"done\")\n    ...\n    ...     print(\"send command\")\n    ...     await comp.request('ECHO')\n    ...     print(\"done\")\n    ...\n    ...     print(\"call stop\")\n    ...     count = await comp.stop()\n    ...     print(\"done\")\n    ...\n    ...     print(count)\n    ...\n    >>> asyncio.run(example())\n    call start\n    > component starting up...\n    done\n    send command\n    > Hello World\n    done\n    call stop\n    > component cleaning up...\n    done\n    1"
  },
  {
    "code": "def svg2str(display_object, dpi=300):\n    from io import StringIO\n    image_buf = StringIO()\n    display_object.frame_axes.figure.savefig(\n        image_buf, dpi=dpi, format='svg',\n        facecolor='k', edgecolor='k')\n    return image_buf.getvalue()",
    "docstring": "Serializes a nilearn display object as a string"
  },
  {
    "code": "def check_elasticsearch(record, *args, **kwargs):\n    def can(self):\n        search = request._methodview.search_class()\n        search = search.get_record(str(record.id))\n        return search.count() == 1\n    return type('CheckES', (), {'can': can})()",
    "docstring": "Return permission that check if the record exists in ES index.\n\n    :params record: A record object.\n    :returns: A object instance with a ``can()`` method."
  },
  {
    "code": "def add_configuration(self, configuration, collect_another_source, done, result, src):\n        if \"includes\" in result:\n            for include in result[\"includes\"]:\n                collect_another_source(include)\n        configuration.update(result, source=src)",
    "docstring": "Used to add a file to the configuration, result here is the yaml.load of the src"
  },
  {
    "code": "def load_parent_implems(self, parent_implems):\n        for trname, attr, implem in parent_implems.get_custom_implementations():\n            self.implementations[trname] = implem.copy()\n            self.transitions_at[trname] = attr\n            self.custom_implems.add(trname)",
    "docstring": "Import previously defined implementations.\n\n        Args:\n            parent_implems (ImplementationList): List of implementations defined\n                in a parent class."
  },
  {
    "code": "def removeAllEntitlements(self, appId):\n        params = {\n            \"f\" : \"json\",\n            \"appId\" : appId\n        }\n        url = self._url + \"/licenses/removeAllEntitlements\"\n        return self._post(url=url,\n                          param_dict=params,\n                          proxy_url=self._proxy_url,\n                          proxy_port=self._proxy_port)",
    "docstring": "This operation removes all entitlements from the portal for ArcGIS\n        Pro or additional products such as Navigator for ArcGIS and revokes\n        all entitlements assigned to users for the specified product. The\n        portal is no longer a licensing portal for that product.\n        License assignments are retained on disk. Therefore, if you decide\n        to configure this portal as a licensing portal for the product\n        again in the future, all licensing assignments will be available in\n        the website.\n\n        Parameters:\n           appId - The identifier for the application for which the\n            entitlements are being removed."
  },
  {
    "code": "def make_butterworth_bandpass_b_a(CenterFreq, bandwidth, SampleFreq, order=5, btype='band'):\n    lowcut = CenterFreq-bandwidth/2\n    highcut = CenterFreq+bandwidth/2\n    b, a = make_butterworth_b_a(lowcut, highcut, SampleFreq, order, btype)\n    return b, a",
    "docstring": "Generates the b and a coefficients for a butterworth bandpass IIR filter.\n\n    Parameters\n    ----------\n    CenterFreq : float\n        central frequency of bandpass\n    bandwidth : float\n        width of the bandpass from centre to edge\n    SampleFreq : float\n        Sample frequency of filter\n    order : int, optional\n        order of IIR filter. Is 5 by default\n    btype : string, optional\n        type of filter to make e.g. (band, low, high)\n\n    Returns\n    -------\n    b : ndarray\n        coefficients multiplying the current and past inputs (feedforward coefficients)\n    a : ndarray\n        coefficients multiplying the past outputs (feedback coefficients)"
  },
  {
    "code": "def delete(self, using=None):\n        from organizations.exceptions import OwnershipRequired\n        try:\n            if self.organization.owner.organization_user.pk == self.pk:\n                raise OwnershipRequired(\n                    _(\n                        \"Cannot delete organization owner \"\n                        \"before organization or transferring ownership.\"\n                    )\n                )\n        except self._org_owner_model.DoesNotExist:\n            pass\n        super(AbstractBaseOrganizationUser, self).delete(using=using)",
    "docstring": "If the organization user is also the owner, this should not be deleted\n        unless it's part of a cascade from the Organization.\n\n        If there is no owner then the deletion should proceed."
  },
  {
    "code": "def storage_class(self, value):\n        if value not in self._STORAGE_CLASSES:\n            raise ValueError(\"Invalid storage class: %s\" % (value,))\n        self._patch_property(\"storageClass\", value)",
    "docstring": "Set the storage class for the bucket.\n\n        See https://cloud.google.com/storage/docs/storage-classes\n\n        :type value: str\n        :param value: one of \"MULTI_REGIONAL\", \"REGIONAL\", \"NEARLINE\",\n                      \"COLDLINE\", \"STANDARD\", or \"DURABLE_REDUCED_AVAILABILITY\""
  },
  {
    "code": "def run(self, order=None):\n    for event in self.runner.run(order=order):\n      self.receive(event)",
    "docstring": "self.runner must be present"
  },
  {
    "code": "def normalise_key(self, key):\n        key = key.replace('-', '_')\n        if key.startswith(\"noy_\"):\n            key = key[4:]\n        return key",
    "docstring": "Make sure key is a valid python attribute"
  },
  {
    "code": "def endswith_strip(s, endswith='.txt', ignorecase=True):\n    if ignorecase:\n        if s.lower().endswith(endswith.lower()):\n            return s[:-len(endswith)]\n    else:\n        if s.endswith(endswith):\n            return s[:-len(endswith)]\n    return s",
    "docstring": "Strip a suffix from the end of a string\n\n    >>> endswith_strip('http://TotalGood.com', '.COM')\n    'http://TotalGood'\n    >>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False)\n    'http://TotalGood.com'"
  },
  {
    "code": "def _compile_files(self):\n        for f in glob.glob(os.path.join(self.dir_path, '*.py')):\n            if not os.path.isfile(os.path.join(self.dir_path, f + 'c')):\n                compileall.compile_dir(self.dir_path, quiet=True)\n                logging.debug('Compiled plugins as a new plugin has been added.')\n                return\n            elif os.path.getmtime(os.path.join(self.dir_path, f)) > os.path.getmtime(\n                    os.path.join(self.dir_path, f + 'c')):\n                compileall.compile_dir(self.dir_path, quiet=True)\n                logging.debug('Compiled plugins as a plugin has been changed.')\n                return",
    "docstring": "Compiles python plugin files in order to be processed by the loader.\n        It compiles the plugins if they have been updated or haven't yet been\n        compiled."
  },
  {
    "code": "def rename(name, new_name, **kwargs):\n    flags = []\n    target = []\n    if __utils__['zfs.is_snapshot'](name):\n        if kwargs.get('create_parent', False):\n            log.warning('zfs.rename - create_parent=True cannot be used with snapshots.')\n        if kwargs.get('force', False):\n            log.warning('zfs.rename - force=True cannot be used with snapshots.')\n        if kwargs.get('recursive', False):\n            flags.append('-r')\n    else:\n        if kwargs.get('create_parent', False):\n            flags.append('-p')\n        if kwargs.get('force', False):\n            flags.append('-f')\n        if kwargs.get('recursive', False):\n            log.warning('zfs.rename - recursive=True can only be used with snapshots.')\n    target.append(name)\n    target.append(new_name)\n    res = __salt__['cmd.run_all'](\n        __utils__['zfs.zfs_command'](\n            command='rename',\n            flags=flags,\n            target=target,\n        ),\n        python_shell=False,\n    )\n    return __utils__['zfs.parse_command_result'](res, 'renamed')",
    "docstring": "Rename or Relocate a ZFS File System.\n\n    name : string\n        name of dataset, volume, or snapshot\n    new_name : string\n        new name of dataset, volume, or snapshot\n    force : boolean\n        force unmount any filesystems that need to be unmounted in the process.\n    create_parent : boolean\n        creates all the nonexistent parent datasets. Datasets created in\n        this manner are automatically mounted according to the mountpoint\n        property inherited from their parent.\n    recursive : boolean\n        recursively rename the snapshots of all descendent datasets.\n        snapshots are the only dataset that can be renamed recursively.\n\n    .. versionadded:: 2015.5.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' zfs.rename myzpool/mydataset myzpool/renameddataset"
  },
  {
    "code": "def _mark_dirty(self, xblock, value):\n        if self not in xblock._dirty_fields:\n            xblock._dirty_fields[self] = copy.deepcopy(value)",
    "docstring": "Set this field to dirty on the xblock."
  },
  {
    "code": "def get_all_vpcs(self, vpc_ids=None, filters=None):\n        params = {}\n        if vpc_ids:\n            self.build_list_params(params, vpc_ids, 'VpcId')\n        if filters:\n            i = 1\n            for filter in filters:\n                params[('Filter.%d.Name' % i)] = filter[0]\n                params[('Filter.%d.Value.1' % i)] = filter[1]\n                i += 1\n        return self.get_list('DescribeVpcs', params, [('item', VPC)])",
    "docstring": "Retrieve information about your VPCs.  You can filter results to\n        return information only about those VPCs that match your search\n        parameters.  Otherwise, all VPCs associated with your account\n        are returned.\n\n        :type vpc_ids: list\n        :param vpc_ids: A list of strings with the desired VPC ID's\n\n        :type filters: list of tuples\n        :param filters: A list of tuples containing filters.  Each tuple\n                        consists of a filter key and a filter value.\n                        Possible filter keys are:\n\n                        - *state*, the state of the VPC (pending or available)\n                        - *cidrBlock*, CIDR block of the VPC\n                        - *dhcpOptionsId*, the ID of a set of DHCP options\n\n        :rtype: list\n        :return: A list of :class:`boto.vpc.vpc.VPC`"
  },
  {
    "code": "def get_lattice_type(cryst):\n    lattice_types = [\n            [3,   \"Triclinic\"],\n            [16,  \"Monoclinic\"],\n            [75,  \"Orthorombic\"],\n            [143, \"Tetragonal\"],\n            [168, \"Trigonal\"],\n            [195, \"Hexagonal\"],\n            [231, \"Cubic\"]\n        ]\n    sg = spg.get_spacegroup(cryst)\n    m = re.match(r'([A-Z].*\\b)\\s*\\(([0-9]*)\\)', sg)\n    sg_name = m.group(1)\n    sg_nr = int(m.group(2))\n    for n, l in enumerate(lattice_types):\n        if sg_nr < l[0]:\n            bravais = l[1]\n            lattype = n+1\n            break\n    return lattype, bravais, sg_name, sg_nr",
    "docstring": "Find the symmetry of the crystal using spglib symmetry finder.\n\n    Derive name of the space group and its number extracted from the result.\n    Based on the group number identify also the lattice type and the Bravais\n    lattice of the crystal. The lattice type numbers are\n    (the numbering starts from 1):\n\n    Triclinic (1), Monoclinic (2), Orthorombic (3),\n    Tetragonal (4), Trigonal (5), Hexagonal (6), Cubic (7)\n\n    :param cryst: ASE Atoms object\n\n    :returns: tuple (lattice type number (1-7), lattice name, space group\n                     name, space group number)"
  },
  {
    "code": "def nx_all_nodes_between(graph, source, target, data=False):\n    import utool as ut\n    if source is None:\n        sources = list(ut.nx_source_nodes(graph))\n        assert len(sources) == 1, (\n            'specify source if there is not only one')\n        source = sources[0]\n    if target is None:\n        sinks = list(ut.nx_sink_nodes(graph))\n        assert len(sinks) == 1, (\n            'specify sink if there is not only one')\n        target = sinks[0]\n    all_simple_paths = list(nx.all_simple_paths(graph, source, target))\n    nodes = sorted(set.union(*map(set, all_simple_paths)))\n    return nodes",
    "docstring": "Find all nodes with on paths between source and target."
  },
  {
    "code": "def UTCFromGps(gpsWeek, SOW, leapSecs=14):\n    secFract = SOW % 1\n    epochTuple = gpsEpoch + (-1, -1, 0) \n    t0 = time.mktime(epochTuple) - time.timezone\n    tdiff = (gpsWeek * secsInWeek) + SOW - leapSecs\n    t = t0 + tdiff\n    (year, month, day, hh, mm, ss, dayOfWeek, julianDay, daylightsaving) = time.gmtime(t)\n    return (year, month, day, hh, mm, ss + secFract)",
    "docstring": "converts gps week and seconds to UTC\n\n    see comments of inverse function!\n\n    SOW = seconds of week\n    gpsWeek is the full number (not modulo 1024)"
  },
  {
    "code": "def on_widget_created(self, ref):\n        d = self.declaration\n        self.widget = Snackbar(__id__=ref)\n        self.init_widget()",
    "docstring": "Using Snackbar.make returns async so we have to \n        initialize it later."
  },
  {
    "code": "def to_array(self):\n        array = super(Animation, self).to_array()\n        array['file_id'] = u(self.file_id)\n        array['width'] = int(self.width)\n        array['height'] = int(self.height)\n        array['duration'] = int(self.duration)\n        if self.thumb is not None:\n            array['thumb'] = self.thumb.to_array()\n        if self.file_name is not None:\n            array['file_name'] = u(self.file_name)\n        if self.mime_type is not None:\n            array['mime_type'] = u(self.mime_type)\n        if self.file_size is not None:\n            array['file_size'] = int(self.file_size)\n        return array",
    "docstring": "Serializes this Animation to a dictionary.\n\n        :return: dictionary representation of this object.\n        :rtype: dict"
  },
  {
    "code": "def _execCommand(Argv, collect_missing):\r\n  r\n  if not Argv:\r\n    raise HandledException('Please specify a command!')\r\n  RouteParts = Argv[0].split('/')\r\n  Args, KwArgs = getDigestableArgs(Argv[1:])\r\n  ResolvedMember = getDescendant(BaseGroup, RouteParts[:])\r\n  if isinstance(ResolvedMember, Group):\r\n    raise HandledException('Please specify a task.', Member=ResolvedMember)\r\n  if not isinstance(ResolvedMember, Task):\r\n    raise HandledException('No such task.', Member=BaseGroup)\r\n  return ResolvedMember.__collect_n_call__(*Args, **KwArgs) if collect_missing else ResolvedMember(*Args, **KwArgs)",
    "docstring": "r\"\"\"Worker of execCommand."
  },
  {
    "code": "def delete_api_method_response(restApiId, resourcePath, httpMethod, statusCode,\n                               region=None, key=None, keyid=None, profile=None):\n    try:\n        resource = describe_api_resource(restApiId, resourcePath, region=region,\n                                         key=key, keyid=keyid, profile=profile).get('resource')\n        if resource:\n            conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n            conn.delete_method_response(restApiId=restApiId, resourceId=resource['id'],\n                                        httpMethod=httpMethod, statusCode=str(statusCode))\n            return {'deleted': True}\n        return {'deleted': False, 'error': 'no such resource'}\n    except ClientError as e:\n        return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Delete API method response for a resource in the given API\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_apigateway.delete_api_method_response restApiId resourcePath httpMethod statusCode"
  },
  {
    "code": "def apply_effect(layer, image):\n    for effect in layer.effects:\n        if effect.__class__.__name__ == 'PatternOverlay':\n            draw_pattern_fill(image, layer._psd, effect.value)\n    for effect in layer.effects:\n        if effect.__class__.__name__ == 'GradientOverlay':\n            draw_gradient_fill(image, effect.value)\n    for effect in layer.effects:\n        if effect.__class__.__name__ == 'ColorOverlay':\n            draw_solid_color_fill(image, effect.value)",
    "docstring": "Apply effect to the image.\n\n    ..note: Correct effect order is the following. All the effects are first\n        applied to the original image then blended together.\n\n        * dropshadow\n        * outerglow\n        * (original)\n        * patternoverlay\n        * gradientoverlay\n        * coloroverlay\n        * innershadow\n        * innerglow\n        * bevelemboss\n        * satin\n        * stroke"
  },
  {
    "code": "def is_model_factory(node):\n    try:\n        parent_classes = node.expr.inferred()\n    except:\n        return False\n    parents = ('factory.declarations.LazyFunction',\n               'factory.declarations.SubFactory',\n               'factory.django.DjangoModelFactory')\n    for parent_class in parent_classes:\n        try:\n            if parent_class.qname() in parents:\n                return True\n            if node_is_subclass(parent_class, *parents):\n                return True\n        except AttributeError:\n            continue\n    return False",
    "docstring": "Checks that node is derivative of DjangoModelFactory or SubFactory class."
  },
  {
    "code": "def load_styles(path_or_doc):\n    if isinstance(path_or_doc, string_types):\n        doc = load(path_or_doc)\n    else:\n        if isinstance(path_or_doc, ODFDocument):\n            doc = path_or_doc._doc\n        else:\n            doc = path_or_doc\n        assert isinstance(doc, OpenDocument), doc\n    styles = {_style_name(style): style for style in doc.styles.childNodes}\n    return styles",
    "docstring": "Return a dictionary of all styles contained in an ODF document."
  },
  {
    "code": "def get_major_minor(ilo_ver_str):\n    if not ilo_ver_str:\n        return None\n    try:\n        pattern = re.search(ILO_VER_STR_PATTERN, ilo_ver_str)\n        if pattern:\n            matched = pattern.group(0)\n            if matched:\n                return matched\n            return None\n    except Exception:\n        return None",
    "docstring": "Extract the major and minor number from the passed string\n\n    :param ilo_ver_str: the string that contains the version information\n    :returns: String of the form \"<major>.<minor>\" or None"
  },
  {
    "code": "def runtime_values_changed(self, model, prop_name, info):\n        if (\"_input_runtime_value\" in info.method_name or\n                info.method_name in ['use_runtime_value_input_data_ports',\n                                     'input_data_port_runtime_values']) and \\\n                self.model is model:\n            self._data_ports_changed(model)",
    "docstring": "Handle cases for the library runtime values"
  },
  {
    "code": "def StatsToCSV(campaign, model='nPLD'):\n    statsfile = os.path.join(EVEREST_SRC, 'missions', 'k2',\n                             'tables', 'c%02d_%s.cdpp' % (campaign, model))\n    csvfile = os.path.join(os.path.dirname(EVEREST_SRC), 'docs',\n                           'c%02d.csv' % campaign)\n    epic, kp, cdpp6r, cdpp6, _, _, _, _, saturated = \\\n        np.loadtxt(statsfile, unpack=True, skiprows=2)\n    with open(csvfile, 'w') as f:\n        print('c%02d' % campaign, file=f)\n        for i in range(len(epic)):\n            print('%09d,%.3f,%.3f,%.3f,%d' % (epic[i], kp[i],\n                                              cdpp6r[i], cdpp6[i],\n                                              int(saturated[i])),\n                                              file=f)",
    "docstring": "Generate the CSV file used in the search database for the documentation."
  },
  {
    "code": "def localize_shapefile(shp_href, dirs):\n    mapnik_requires_absolute_paths = (MAPNIK_VERSION < 601)\n    shp_href = urljoin(dirs.source.rstrip('/')+'/', shp_href)\n    scheme, host, path, p, q, f = urlparse(shp_href)\n    if scheme in ('http','https'):\n        msg('%s | %s' % (shp_href, dirs.cache))\n        scheme, path = '', locally_cache_remote_file(shp_href, dirs.cache)\n    else:\n        host = None\n    to_posix(systempath.realpath(path))\n    if scheme not in ('file', ''):\n        raise Exception(\"Shapefile needs to be local, not %s\" % shp_href)\n    if mapnik_requires_absolute_paths:\n        path = posixpath.realpath(path)\n        original = path\n    path = dirs.output_path(path)\n    if path.endswith('.zip'):\n        path = posixpath.join(dirs.output, path)\n        path = unzip_shapefile_into(path, dirs.cache, host)\n    return dirs.output_path(path)",
    "docstring": "Given a shapefile href and a set of directories, modify the shapefile\n        name so it's correct with respect to the output and cache directories."
  },
  {
    "code": "def reference(self):\n        total_enabled = \", \".join(self.selected)\n        if len(total_enabled) < 1:\n            total_enabled = (\"{0}Are you crazy? This is a package \"\n                             \"manager for packages :p{1}\".format(\n                                 self.meta.color[\"RED\"],\n                                 self.meta.color[\"ENDC\"]))\n        self.msg.template(78)\n        print(\"| Enabled repositories:\")\n        self.msg.template(78)\n        print(\"| {0}\".format(total_enabled))\n        self.msg.template(78)\n        print(\"{0}Total {1}/{2} repositories enabled.{3}\\n\".format(\n            self.meta.color[\"GREY\"], len(self.selected),\n            len(self.enabled + self.disabled), self.meta.color[\"ENDC\"]))",
    "docstring": "Reference enable repositories"
  },
  {
    "code": "def avglosses_data_transfer(token, dstore):\n    oq = dstore['oqparam']\n    N = len(dstore['assetcol'])\n    R = dstore['csm_info'].get_num_rlzs()\n    L = len(dstore.get_attr('risk_model', 'loss_types'))\n    ct = oq.concurrent_tasks\n    size_bytes = N * R * L * 8 * ct\n    return (\n        '%d asset(s) x %d realization(s) x %d loss type(s) losses x '\n        '8 bytes x %d tasks = %s' % (N, R, L, ct, humansize(size_bytes)))",
    "docstring": "Determine the amount of average losses transferred from the workers to the\n    controller node in a risk calculation."
  },
  {
    "code": "def fromStructTime(klass, structTime, tzinfo=None):\n        dtime = datetime.datetime(tzinfo=tzinfo, *structTime[:6])\n        self = klass.fromDatetime(dtime)\n        self.resolution = datetime.timedelta(seconds=1)\n        return self",
    "docstring": "Return a new Time instance from a time.struct_time.\n\n        If tzinfo is None, structTime is in UTC. Otherwise, tzinfo is a\n        datetime.tzinfo instance coresponding to the timezone in which\n        structTime is.\n\n        Many of the functions in the standard time module return these things.\n        This will also work with a plain 9-tuple, for parity with the time\n        module. The last three elements, or tm_wday, tm_yday, and tm_isdst are\n        ignored."
  },
  {
    "code": "def is_tomodir(subdirectories):\n    required = (\n        'exe',\n        'config',\n        'rho',\n        'mod',\n        'inv'\n    )\n    is_tomodir = True\n    for subdir in required:\n        if subdir not in subdirectories:\n            is_tomodir = False\n    return is_tomodir",
    "docstring": "provided with the subdirectories of a given directory, check if this is\n    a tomodir"
  },
  {
    "code": "def group_comments_by_round(comments, ranking=0):\n    comment_rounds = {}\n    ordered_comment_round_names = []\n    for comment in comments:\n        comment_round_name = ranking and comment[11] or comment[7]\n        if comment_round_name not in comment_rounds:\n            comment_rounds[comment_round_name] = []\n            ordered_comment_round_names.append(comment_round_name)\n        comment_rounds[comment_round_name].append(comment)\n    return [(comment_round_name, comment_rounds[comment_round_name])\n            for comment_round_name in ordered_comment_round_names]",
    "docstring": "Group comments by the round to which they belong"
  },
  {
    "code": "def get_cv_accuracy(res):\n    ac_list = [(accuracy[\"train_acc_final\"],\n                accuracy[\"test_acc_final\"]\n                )\n               for accuracy, weights in res]\n    ac = np.array(ac_list)\n    perf = {\n        \"mean_train_acc\": np.mean(ac[:, 0]),\n        \"std_train_acc\": np.std(ac[:, 0]),\n        \"mean_test_acc\": np.mean(ac[:, 1]),\n        \"std_test_acc\": np.std(ac[:, 1]),\n    }\n    return perf",
    "docstring": "Extract the cv accuracy from the model"
  },
  {
    "code": "def from_buffer(buffer, mime=False):\n    m = _get_magic_type(mime)\n    return m.from_buffer(buffer)",
    "docstring": "Accepts a binary string and returns the detected filetype.  Return\n    value is the mimetype if mime=True, otherwise a human readable\n    name.\n\n    >>> magic.from_buffer(open(\"testdata/test.pdf\").read(1024))\n    'PDF document, version 1.2'"
  },
  {
    "code": "def info(self):\n        if self.descriptions is None:\n            choice_list = ['\"{}\"'.format(choice) for choice in self.choices]\n        else:\n            choice_list = [\n                '\"{}\" ({})'.format(choice, self.descriptions[choice])\n                for choice in self.choices\n            ]\n        if len(self.choices) == 2:\n            return 'either {} or {}'.format(choice_list[0], choice_list[1])\n        return 'any of {}'.format(', '.join(choice_list))",
    "docstring": "Formatted string to display the available choices"
  },
  {
    "code": "def acknowledge_alarm(self, alarm, comment=None):\n        url = '/processors/{}/{}/parameters{}/alarms/{}'.format(\n            self._instance, self._processor, alarm.name, alarm.sequence_number)\n        req = rest_pb2.EditAlarmRequest()\n        req.state = 'acknowledged'\n        if comment is not None:\n            req.comment = comment\n        self._client.put_proto(url, data=req.SerializeToString())",
    "docstring": "Acknowledges a specific alarm associated with a parameter.\n\n        :param alarm: Alarm instance\n        :type alarm: :class:`.Alarm`\n        :param str comment: Optional comment to associate with the state\n                            change."
  },
  {
    "code": "def set_ddns_config(self, isenable, hostname, ddnsserver,\n                                        user, password, callback=None):\n        params = {'isEnable': isenable,\n                  'hostName': hostname,\n                  'ddnsServer': ddnsserver,\n                  'user': user,\n                  'password': password,\n                 }\n        return self.execute_command('setDDNSConfig', params, callback=callback)",
    "docstring": "Set DDNS config."
  },
  {
    "code": "def save(self):\n        with open(self._user_config_file, 'w', encoding='utf-8') as f:\n            self.write(f)",
    "docstring": "Write data to user config file."
  },
  {
    "code": "def mark_offer_as_win(self, offer_id):\n        return self._create_put_request(\n            resource=OFFERS,\n            billomat_id=offer_id,\n            command=WIN,\n        )",
    "docstring": "Mark offer as win\n\n        :param offer_id: the offer id\n        :return Response"
  },
  {
    "code": "def stop(self, timeout=15):\n        pp = self.pid\n        if pp:\n            try:\n                kill_process_nicely(pp, timeout=timeout)\n            except psutil.NoSuchProcess:\n                pass",
    "docstring": "Stop the subprocess.\n\n        Keyword Arguments\n\n        **timeout**\n          Time in seconds to wait for a process and its\n          children to exit."
  },
  {
    "code": "def output(self, args):\n        print(\"SensuPlugin: {}\".format(' '.join(str(a) for a in args)))",
    "docstring": "Print the output message."
  },
  {
    "code": "def create_repository(self):\n        repo = repository.Repository(\n            self.repository_config['repository'],\n            self.username,\n            self.password,\n            self.disable_progress_bar\n        )\n        repo.set_certificate_authority(self.cacert)\n        repo.set_client_certificate(self.client_cert)\n        return repo",
    "docstring": "Create a new repository for uploading."
  },
  {
    "code": "def _fetch_xml(self, url):\n        with contextlib.closing(urlopen(url)) as f:\n            return xml.etree.ElementTree.parse(f).getroot()",
    "docstring": "Fetch a url and parse the document's XML."
  },
  {
    "code": "def _build_function(self, function_name, codeuri, runtime):\n        code_dir = str(pathlib.Path(self._base_dir, codeuri).resolve())\n        config = get_workflow_config(runtime, code_dir, self._base_dir)\n        artifacts_dir = str(pathlib.Path(self._build_dir, function_name))\n        with osutils.mkdir_temp() as scratch_dir:\n            manifest_path = self._manifest_path_override or os.path.join(code_dir, config.manifest_name)\n            build_method = self._build_function_in_process\n            if self._container_manager:\n                build_method = self._build_function_on_container\n            return build_method(config,\n                                code_dir,\n                                artifacts_dir,\n                                scratch_dir,\n                                manifest_path,\n                                runtime)",
    "docstring": "Given the function information, this method will build the Lambda function. Depending on the configuration\n        it will either build the function in process or by spinning up a Docker container.\n\n        Parameters\n        ----------\n        function_name : str\n            Name or LogicalId of the function\n\n        codeuri : str\n            Path to where the code lives\n\n        runtime : str\n            AWS Lambda function runtime\n\n        Returns\n        -------\n        str\n            Path to the location where built artifacts are available"
  },
  {
    "code": "def uses_na_format(station: str) -> bool:\n    if station[0] in NA_REGIONS:\n        return True\n    if station[0] in IN_REGIONS:\n        return False\n    if station[:2] in M_NA_REGIONS:\n        return True\n    if station[:2] in M_IN_REGIONS:\n        return False\n    raise BadStation(\"Station doesn't start with a recognized character set\")",
    "docstring": "Returns True if the station uses the North American format,\n    False if the International format"
  },
  {
    "code": "def schedule(self):\n        assert self.collection_is_completed\n        if self.collection is not None:\n            for node in self.nodes:\n                self.check_schedule(node)\n            return\n        if not self._check_nodes_have_same_collection():\n            self.log(\"**Different tests collected, aborting run**\")\n            return\n        self.collection = list(self.node2collection.values())[0]\n        self.pending[:] = range(len(self.collection))\n        if not self.collection:\n            return\n        initial_batch = max(len(self.pending) // 4, 2 * len(self.nodes))\n        nodes = cycle(self.nodes)\n        for i in range(initial_batch):\n            self._send_tests(next(nodes), 1)\n        if not self.pending:\n            for node in self.nodes:\n                node.shutdown()",
    "docstring": "Initiate distribution of the test collection\n\n        Initiate scheduling of the items across the nodes.  If this\n        gets called again later it behaves the same as calling\n        ``.check_schedule()`` on all nodes so that newly added nodes\n        will start to be used.\n\n        This is called by the ``DSession.worker_collectionfinish`` hook\n        if ``.collection_is_completed`` is True."
  },
  {
    "code": "def ekacei(handle, segno, recno, column, nvals, ivals, isnull):\n    handle = ctypes.c_int(handle)\n    segno = ctypes.c_int(segno)\n    recno = ctypes.c_int(recno)\n    column = stypes.stringToCharP(column)\n    nvals = ctypes.c_int(nvals)\n    ivals = stypes.toIntVector(ivals)\n    isnull = ctypes.c_int(isnull)\n    libspice.ekacei_c(handle, segno, recno, column, nvals, ivals, isnull)",
    "docstring": "Add data to an integer column in a specified EK record.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacei_c.html\n\n    :param handle: EK file handle.\n    :type handle: int\n    :param segno: Index of segment containing record.\n    :type segno: int\n    :param recno: Record to which data is to be added.\n    :type recno: int\n    :param column: Column name.\n    :type column: str\n    :param nvals: Number of values to add to column.\n    :type nvals: int\n    :param ivals: Integer values to add to column.\n    :type ivals: Array of ints\n    :param isnull: Flag indicating whether column entry is null.\n    :type isnull: bool"
  },
  {
    "code": "def Mux(fs, sel, simplify=True):\n    if isinstance(sel, Expression):\n        sel = [sel]\n    if len(sel) < clog2(len(fs)):\n        fstr = \"expected at least {} select bits, got {}\"\n        raise ValueError(fstr.format(clog2(len(fs)), len(sel)))\n    it = boolfunc.iter_terms(sel)\n    y = exprnode.or_(*[exprnode.and_(f.node, *[lit.node for lit in next(it)])\n                       for f in fs])\n    if simplify:\n        y = y.simplify()\n    return _expr(y)",
    "docstring": "Return an expression that multiplexes a sequence of input functions over a\n    sequence of select functions."
  },
  {
    "code": "def get_object_url(self):\n        return self.bundle.get_view_url('edit',\n                                        self.request.user, {}, self.kwargs)",
    "docstring": "Returns the url to link to the object\n        The get_view_url will be called on the current bundle using\n        'edit` as the view name."
  },
  {
    "code": "def remove(cls, target, exclude=None, ctx=None, select=lambda *p: True):\n        exclude = () if exclude is None else exclude\n        try:\n            local_annotations = get_local_property(\n                target, Annotation.__ANNOTATIONS_KEY__\n            )\n        except TypeError:\n            raise TypeError('target {0} must be hashable'.format(target))\n        if local_annotations is not None:\n            annotations_to_remove = [\n                annotation for annotation in local_annotations\n                if (\n                    isinstance(annotation, cls)\n                    and not isinstance(annotation, exclude)\n                    and select(target, ctx, annotation)\n                )\n            ]\n            for annotation_to_remove in annotations_to_remove:\n                annotation_to_remove.remove_from(target)",
    "docstring": "Remove from target annotations which inherit from cls.\n\n        :param target: target from where remove annotations which inherits from\n            cls.\n        :param tuple/type exclude: annotation types to exclude from selection.\n        :param ctx: target ctx.\n        :param select: annotation selection function which takes in parameters\n            a target, a ctx and an annotation and return True if the annotation\n            has to be removed."
  },
  {
    "code": "def softmax(input_,\n            labels=None,\n            name=PROVIDED,\n            loss_weight=None,\n            per_example_weights=None):\n  if labels is not None:\n    full = input_.as_layer()\n    return SoftmaxResult(input_.softmax_activation(),\n                         full.cross_entropy(\n                             labels,\n                             name=name,\n                             loss_weight=loss_weight,\n                             per_example_weights=per_example_weights))\n  else:\n    return SoftmaxResult(input_.softmax_activation(), None)",
    "docstring": "Applies softmax and if labels is not None, then it also adds a loss.\n\n  Args:\n    input_: A rank 2 Tensor or a Pretty Tensor holding the logits.\n    labels: The target labels to learn as a float tensor.  Use None to not\n      include a training loss.\n    name: The optional name.\n    loss_weight: A scalar multiplier for the loss.\n    per_example_weights: A Tensor with a weight per example.\n  Returns:\n    A tuple of the a handle to softmax and a handle to the loss tensor.\n  Raises:\n    ValueError: If the datatype is wrong."
  },
  {
    "code": "def listAttachments(self, oid):\n        url = self._url + \"/%s/attachments\" % oid\n        params = {\n            \"f\":\"json\"\n        }\n        return self._get(url, params,\n                            securityHandler=self._securityHandler,\n                            proxy_port=self._proxy_port,\n                            proxy_url=self._proxy_url)",
    "docstring": "list attachements for a given OBJECT ID"
  },
  {
    "code": "def distance_correlation_af_inv_sqr(x, y):\n    x = _af_inv_scaled(x)\n    y = _af_inv_scaled(y)\n    correlation = distance_correlation_sqr(x, y)\n    return 0 if np.isnan(correlation) else correlation",
    "docstring": "Square of the affinely invariant distance correlation.\n\n    Computes the estimator for the square of the affinely invariant distance\n    correlation between two random vectors.\n\n    .. warning:: The return value of this function is undefined when the\n                 covariance matrix of :math:`x` or :math:`y` is singular.\n\n    Parameters\n    ----------\n    x: array_like\n        First random vector. The columns correspond with the individual random\n        variables while the rows are individual instances of the random vector.\n    y: array_like\n        Second random vector. The columns correspond with the individual random\n        variables while the rows are individual instances of the random vector.\n\n    Returns\n    -------\n    numpy scalar\n        Value of the estimator of the squared affinely invariant\n        distance correlation.\n\n    See Also\n    --------\n    distance_correlation\n    u_distance_correlation\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> import dcor\n    >>> a = np.array([[1, 3, 2, 5],\n    ...               [5, 7, 6, 8],\n    ...               [9, 10, 11, 12],\n    ...               [13, 15, 15, 16]])\n    >>> b = np.array([[1], [0], [0], [1]])\n    >>> dcor.distance_correlation_af_inv_sqr(a, a)\n    1.0\n    >>> dcor.distance_correlation_af_inv_sqr(a, b) # doctest: +ELLIPSIS\n    0.5773502...\n    >>> dcor.distance_correlation_af_inv_sqr(b, b)\n    1.0"
  },
  {
    "code": "def repo_tools(self, branch):\n        tools = []\n        m_helper = Tools()\n        repo = self.parentApp.repo_value['repo']\n        version = self.parentApp.repo_value['versions'][branch]\n        status = m_helper.repo_tools(repo, branch, version)\n        if status[0]:\n            r_tools = status[1]\n            for tool in r_tools:\n                tools.append(tool[0])\n        return tools",
    "docstring": "Set the appropriate repo dir and get the tools available of it"
  },
  {
    "code": "def set_context(pid_file, context_info):\n    assert type(context_info) == dict\n    port_file = get_context_file_name(pid_file)\n    with open(port_file, \"wt\") as f:\n        f.write(json.dumps(context_info))",
    "docstring": "Set context of running notebook.\n\n    :param context_info: dict of extra context parameters, see comm.py comments"
  },
  {
    "code": "def message(self, data):\n        logging.info('Driver sends framework message {}'.format(data))\n        return self.driver.sendFrameworkMessage(data)",
    "docstring": "Sends a message to the framework scheduler.\n\n        These messages are best effort; do not expect a framework message to be\n        retransmitted in any reliable fashion."
  },
  {
    "code": "def get_token_from_header(request):\n    token = None\n    if 'Authorization' in request.headers:\n        split_header = request.headers.get('Authorization').split()\n        if len(split_header) == 2 and split_header[0] == 'Bearer':\n            token = split_header[1]\n    else:\n        token = request.access_token\n    return token",
    "docstring": "Helper function to extract a token from the request header.\n\n    :param request: OAuthlib request.\n    :type request: oauthlib.common.Request\n    :return: Return the token or None if the Authorization header is malformed."
  },
  {
    "code": "def templatesCollector(text, open, close):\n    others = []\n    spans = [i for i in findBalanced(text, open, close)]\n    spanscopy = copy(spans)\n    for i in range(len(spans)):\n        start, end = spans[i]\n        o = text[start:end]\n        ol = o.lower()\n        if 'vaata|' in ol or 'wikitable' in ol:\n            spanscopy.remove(spans[i])\n            continue\n        others.append(o)\n    text = dropSpans(spanscopy, text)\n    return text, others",
    "docstring": "leaves related articles and wikitables in place"
  },
  {
    "code": "def hazard_notes(self):\n        notes = []\n        hazard = definition(self.hazard.keywords.get('hazard'))\n        if 'notes' in hazard:\n            notes += hazard['notes']\n        if self.hazard.keywords['layer_mode'] == 'classified':\n            if 'classified_notes' in hazard:\n                notes += hazard['classified_notes']\n        if self.hazard.keywords['layer_mode'] == 'continuous':\n            if 'continuous_notes' in hazard:\n                notes += hazard['continuous_notes']\n        if self.hazard.keywords['hazard_category'] == 'single_event':\n            if 'single_event_notes' in hazard:\n                notes += hazard['single_event_notes']\n        if self.hazard.keywords['hazard_category'] == 'multiple_event':\n            if 'multi_event_notes' in hazard:\n                notes += hazard['multi_event_notes']\n        return notes",
    "docstring": "Get the hazard specific notes defined in definitions.\n\n        This method will do a lookup in definitions and return the\n        hazard definition specific notes dictionary.\n\n        This is a helper function to make it\n        easy to get hazard specific notes from the definitions metadata.\n\n        .. versionadded:: 3.5\n\n        :returns: A list like e.g. safe.definitions.hazard_land_cover[\n            'notes']\n        :rtype: list, None"
  },
  {
    "code": "def get_service_name(wrapped, instance, args, kwargs):\n    if 'serviceAbbreviation' not in instance._service_model.metadata:\n        return instance._service_model.metadata['endpointPrefix']\n    return instance._service_model.metadata['serviceAbbreviation']",
    "docstring": "Return the AWS service name the client is communicating with."
  },
  {
    "code": "def _write_related_m2m_relations(self, obj, many_to_many_relationships):\n        for fieldname, related_objs in many_to_many_relationships.items():\n            setattr(obj, fieldname, related_objs)",
    "docstring": "For the given `many_to_many_relationships` dict mapping field names to\n        a list of object instances, apply the instance listing to the `obj`s\n        named many-to-many relationship field."
  },
  {
    "code": "def _rewrite_col(self, col):\n        if isinstance(col, Col):\n            new_name = rewrite_lookup_key(self.model, col.target.name)\n            if col.target.name != new_name:\n                new_field = self.model._meta.get_field(new_name)\n                if col.target is col.source:\n                    col.source = new_field\n                col.target = new_field\n        elif hasattr(col, 'col'):\n            self._rewrite_col(col.col)\n        elif hasattr(col, 'lhs'):\n            self._rewrite_col(col.lhs)",
    "docstring": "Django >= 1.7 column name rewriting"
  },
  {
    "code": "def phi_components_normalized(self):\n        phi_components_normalized = {i: self.phi_components[i]/self.phi for i in self.phi_components}\n        return phi_components_normalized",
    "docstring": "get the individual components of the total objective function\n            normalized to the total PHI being 1.0\n\n        Returns\n        -------\n        dict : dict\n            dictionary of observation group, normalized contribution to total phi\n\n        Raises\n        ------\n        Assertion error if self.observation_data groups don't match\n        self.res groups"
  },
  {
    "code": "def renumber(self):\n        num = 0\n        for cell in self.cells:\n            cell_split = cell.splitlines()\n            if len(cell_split) >= 2:\n                num += 1\n                cell_split[0] = str(num)\n                yield '\\n'.join(cell_split)",
    "docstring": "Re-number cells."
  },
  {
    "code": "def _rest_patch(self, suburi, request_headers, request_body):\n        return self._rest_op('PATCH', suburi, request_headers, request_body)",
    "docstring": "REST PATCH operation.\n\n        HTTP response codes could be 500, 404, 202 etc."
  },
  {
    "code": "def get_sdb_secret_version_paths(self, sdb_id):\n        sdb_resp = get_with_retry(str.join('', [self.cerberus_url, '/v1/sdb-secret-version-paths/', sdb_id]),\n                                headers=self.HEADERS)\n        throw_if_bad_response(sdb_resp)\n        return sdb_resp.json()",
    "docstring": "Get SDB secret version paths.  This function takes the sdb_id"
  },
  {
    "code": "def _zero_mantissa(dval):\n    bb = _double_as_bytes(dval)\n    return ((bb[1] & 0x0f) | reduce(operator.or_, bb[2:])) == 0",
    "docstring": "Determine whether the mantissa bits of the given double are all\n    zero."
  },
  {
    "code": "def cube2matrix(data_cube):\n    r\n    return data_cube.reshape([data_cube.shape[0]] +\n                             [np.prod(data_cube.shape[1:])]).T",
    "docstring": "r\"\"\"Cube to Matrix\n\n    This method transforms a 3D cube to a 2D matrix\n\n    Parameters\n    ----------\n    data_cube : np.ndarray\n        Input data cube, 3D array\n\n    Returns\n    -------\n    np.ndarray 2D matrix\n\n    Examples\n    --------\n    >>> from modopt.base.transform import cube2matrix\n    >>> a = np.arange(16).reshape((4, 2, 2))\n    >>> cube2matrix(a)\n    array([[ 0,  4,  8, 12],\n           [ 1,  5,  9, 13],\n           [ 2,  6, 10, 14],\n           [ 3,  7, 11, 15]])"
  },
  {
    "code": "def inspect_node(node):\n    node_information = {}\n    ssh = node.connect()\n    if not ssh:\n        log.error(\"Unable to connect to node %s\", node.name)\n        return\n    (_in, _out, _err) = ssh.exec_command(\"(type >& /dev/null -a srun && echo slurm) \\\n                      || (type >& /dev/null -a qconf && echo sge) \\\n                      || (type >& /dev/null -a pbsnodes && echo pbs) \\\n                      || echo UNKNOWN\")\n    node_information['type'] = _out.read().strip()\n    (_in, _out, _err) = ssh.exec_command(\"arch\")\n    node_information['architecture'] = _out.read().strip()\n    if node_information['type'] == 'slurm':\n        inspect_slurm_cluster(ssh, node_information)\n    elif node_information['type'] == 'sge':\n        inspect_sge_cluster(ssh, node_information)\n    ssh.close()\n    return node_information",
    "docstring": "This function accept a `elasticluster.cluster.Node` class,\n    connects to a node and tries to discover the kind of batch system\n    installed, and some other information."
  },
  {
    "code": "def iptag_get(self, iptag, x, y):\n        ack = self._send_scp(x, y, 0, SCPCommands.iptag,\n                             int(consts.IPTagCommands.get) << 16 | iptag, 1,\n                             expected_args=0)\n        return IPTag.from_bytestring(ack.data)",
    "docstring": "Get the value of an IPTag.\n\n        Parameters\n        ----------\n        iptag : int\n            Index of the IPTag to get\n\n        Returns\n        -------\n        :py:class:`.IPTag`\n            The IPTag returned from SpiNNaker."
  },
  {
    "code": "def bh_fdr(pval):\n    pval_array = np.array(pval)\n    sorted_order = np.argsort(pval_array)\n    original_order = np.argsort(sorted_order)\n    pval_array = pval_array[sorted_order]\n    n = float(len(pval))\n    pval_adj = np.zeros(int(n))\n    i = np.arange(1, int(n)+1, dtype=float)[::-1]\n    pval_adj = np.minimum(1, cummin(n/i * pval_array[::-1]))[::-1]\n    return pval_adj[original_order]",
    "docstring": "A python implementation of the Benjamani-Hochberg FDR method.\n\n    This code should always give precisely the same answer as using\n    p.adjust(pval, method=\"BH\") in R.\n\n    Parameters\n    ----------\n    pval : list or array\n        list/array of p-values\n\n    Returns\n    -------\n    pval_adj : np.array\n        adjusted p-values according the benjamani-hochberg method"
  },
  {
    "code": "def run_jobs(delete_completed=False, ignore_errors=False, now=None):\n    if ScheduledJob.objects.filter(status='running'):\n        raise ValueError('jobs in progress found; aborting')\n    if now is None:\n        now = datetime.datetime.now()\n    expire_jobs(now)\n    schedule_sticky_jobs()\n    start_scheduled_jobs(now, delete_completed, ignore_errors)",
    "docstring": "Run scheduled jobs.\n\n    You may specify a date to be treated as the current time."
  },
  {
    "code": "def _get_results_from_api(identifiers, endpoints, api_key, api_secret):\n    if api_key is not None and api_secret is not None:\n        client = housecanary.ApiClient(api_key, api_secret)\n    else:\n        client = housecanary.ApiClient()\n    wrapper = getattr(client, endpoints[0].split('/')[0])\n    if len(endpoints) > 1:\n        return wrapper.component_mget(identifiers, endpoints)\n    else:\n        return wrapper.fetch_identifier_component(endpoints[0], identifiers)",
    "docstring": "Use the HouseCanary API Python Client to access the API"
  },
  {
    "code": "def is_atlas_enabled(blockstack_opts):\n    if not blockstack_opts['atlas']:\n        log.debug(\"Atlas is disabled\")\n        return False\n    if 'zonefiles' not in blockstack_opts:\n        log.debug(\"Atlas is disabled: no 'zonefiles' path set\")\n        return False\n    if 'atlasdb_path' not in blockstack_opts:\n        log.debug(\"Atlas is disabled: no 'atlasdb_path' path set\")\n        return False\n    return True",
    "docstring": "Can we do atlas operations?"
  },
  {
    "code": "async def spawn_slaves(self, spawn_cmd, ports=None, **ssh_kwargs):\n        pool = multiprocessing.Pool(len(self.nodes))\n        rets = []\n        for i, node in enumerate(self.nodes):\n            server, server_port = node\n            port = ports[node] if ports is not None else self.port\n            mgr_addr = \"tcp://{}:{}/0\".format(server, port)\n            self._manager_addrs.append(mgr_addr)\n            if type(spawn_cmd) in [list, tuple]:\n                cmd = spawn_cmd[i]\n            else:\n                cmd = spawn_cmd\n            args = [server, cmd]\n            ssh_kwargs_cp = ssh_kwargs.copy()\n            ssh_kwargs_cp['port'] = server_port\n            ret = pool.apply_async(ssh_exec_in_new_loop,\n                                   args=args,\n                                   kwds=ssh_kwargs_cp,\n                                   error_callback=logger.warning)\n            rets.append(ret)\n        self._pool = pool\n        self._r = rets",
    "docstring": "Spawn multi-environments on the nodes through SSH-connections.\n\n        :param spawn_cmd:\n            str or list, command(s) used to spawn the environment on each node.\n            If *list*, it must contain one command for each node in\n            :attr:`nodes`. If *str*, the same command is used for each node.\n\n        :param ports:\n            Optional. If not ``None``, must be a mapping from nodes\n            (``(server, port)``-tuples) to ports which are used for the spawned\n            multi-environments' master manager environments. If ``None``, then\n            the same port is used to derive the master manager addresses as was\n            used to initialize this distributed environment's managing\n            environment (port in :attr:`addr`).\n\n        :param ssh_kwargs:\n            Any additional SSH-connection arguments, as specified by\n            :meth:`asyncssh.connect`. See `asyncssh documentation\n            <http://asyncssh.readthedocs.io/en/latest/api.html#connect>`_ for\n            details.\n\n        Nodes are spawned by creating a multiprocessing pool where each node\n        has its own subprocess. These subprocesses then use SSH-connections\n        to spawn the multi-environments on the nodes. The SSH-connections in\n        the pool are kept alive until the nodes are stopped, i.e. this\n        distributed environment is destroyed."
  },
  {
    "code": "def set_uppercase(self, uppercase):\n        for row in self.rows:\n            for key in row.keys:\n                if type(key) == VKey:\n                    if uppercase:\n                        key.value = key.value.upper()\n                    else:\n                        key.value = key.value.lower()",
    "docstring": "Sets layout uppercase state.\n\n        :param uppercase: True if uppercase, False otherwise."
  },
  {
    "code": "def dns_resolution(self):\n        if not self.can_update():\n            self._tcex.handle_error(910, [self.type])\n        return self.tc_requests.dns_resolution(\n            self.api_type, self.api_sub_type, self.unique_id, owner=self.owner\n        )",
    "docstring": "Updates the Host DNS resolution\n\n        Returns:"
  },
  {
    "code": "def find_all(self, **names):\n        values = names.items()\n        if len(values) != 1:\n            raise ValueError('Only one query is allowed at a time')\n        name, value = values[0]\n        for item in self:\n            if item.get(name) == value:\n                yield item",
    "docstring": "Find all items with matching extra values.\n\n        :param \\*\\*names: Extra values to match.\n        :rtype: ``Iterable[`EnumItem`]``"
  },
  {
    "code": "def append_executable(self, executable):\n        if isinstance(executable, str) and not isinstance(executable, unicode):\n            executable = unicode(executable)\n        if not isinstance(executable, unicode):\n            raise TypeError(\"expected executable name as str, not {}\".\n                            format(executable.__class__.__name__))\n        self._executables.append(executable)",
    "docstring": "Append san executable os command to the list to be called.\n\n        Argument:\n          executable (str): os callable executable."
  },
  {
    "code": "def fetch_credentials(auth_id, auth_token):\n    if not (auth_id and auth_token):\n        try:\n            auth_id = os.environ['PLIVO_AUTH_ID']\n            auth_token = os.environ['PLIVO_AUTH_TOKEN']\n        except KeyError:\n            raise AuthenticationError('The Plivo Python SDK '\n                                      'could not find your auth credentials.')\n    if not (is_valid_mainaccount(auth_id) or is_valid_subaccount(auth_id)):\n        raise AuthenticationError('Invalid auth_id supplied: %s' % auth_id)\n    return AuthenticationCredentials(auth_id=auth_id, auth_token=auth_token)",
    "docstring": "Fetches the right credentials either from params or from environment"
  },
  {
    "code": "def _on_model_save(sender, **kwargs):\n    instance = kwargs.pop(\"instance\")\n    update_fields = kwargs.pop(\"update_fields\")\n    for index in instance.search_indexes:\n        try:\n            _update_search_index(\n                instance=instance, index=index, update_fields=update_fields\n            )\n        except Exception:\n            logger.exception(\"Error handling 'on_save' signal for %s\", instance)",
    "docstring": "Update document in search index post_save."
  },
  {
    "code": "def compile_path(self, path, write=True, package=None, *args, **kwargs):\n        path = fixpath(path)\n        if not isinstance(write, bool):\n            write = fixpath(write)\n        if os.path.isfile(path):\n            if package is None:\n                package = False\n            destpath = self.compile_file(path, write, package, *args, **kwargs)\n            return [destpath] if destpath is not None else []\n        elif os.path.isdir(path):\n            if package is None:\n                package = True\n            return self.compile_folder(path, write, package, *args, **kwargs)\n        else:\n            raise CoconutException(\"could not find source path\", path)",
    "docstring": "Compile a path and returns paths to compiled files."
  },
  {
    "code": "def template_subst(template, subs, delims=('<', '>')):\n    subst_text = template\n    for (k,v) in subs.items():\n        subst_text = subst_text.replace(\n                delims[0] + k + delims[1], v)\n    return subst_text",
    "docstring": "Perform substitution of content into tagged string.\n\n    For substitutions into template input files for external computational\n    packages, no checks for valid syntax are performed.\n\n    Each key in `subs` corresponds to a delimited\n    substitution tag to be replaced in `template` by the entire text of the\n    value of that key. For example, the dict ``{\"ABC\": \"text\"}`` would\n    convert ``The <ABC> is working`` to  ``The text is working``, using the\n    default delimiters of '<' and '>'. Substitutions are performed in\n    iteration order from `subs`; recursive substitution\n    as the tag parsing proceeds is thus\n    feasible if an :class:`~collections.OrderedDict` is used and substitution\n    key/value pairs are added in the proper order.\n\n    Start and end delimiters for the tags are modified by `delims`. For\n    example, to substitute a tag of the form **{\\|TAG\\|}**, the tuple\n    ``(\"{|\",\"|}\")`` should be passed to `subs_delims`.  Any elements in\n    `delims` past the second are ignored. No checking is\n    performed for whether the delimiters are \"sensible\" or not.\n\n    Parameters\n    ----------\n    template\n        |str| --\n        Template containing tags delimited by `subs_delims`,\n        with tag names and substitution contents provided in `subs`\n\n    subs\n        |dict| of |str| --\n        Each item's key and value are the tag name and corresponding content to\n        be substituted into the provided template.\n\n    delims\n        iterable of |str| --\n        Iterable containing the 'open' and 'close' strings used to mark tags\n        in the template, which are drawn from elements zero and one,\n        respectively. Any elements beyond these are ignored.\n\n    Returns\n    -------\n    subst_text\n        |str| --\n        String generated from the parsed template, with all tag\n        substitutions performed."
  },
  {
    "code": "def __could_edit(self, slug):\n        page_rec = MWiki.get_by_uid(slug)\n        if not page_rec:\n            return False\n        if self.check_post_role()['EDIT']:\n            return True\n        elif page_rec.user_name == self.userinfo.user_name:\n            return True\n        else:\n            return False",
    "docstring": "Test if the user could edit the page."
  },
  {
    "code": "def add_to_grid(self, agent):\n        for i in range(len(self.grid)):\n            for j in range(len(self.grid[0])):\n                if self.grid[i][j] is None:\n                    x = self.origin[0] + i\n                    y = self.origin[1] + j\n                    self.grid[i][j] = agent\n                    return (x, y)\n        raise ValueError(\"Trying to add an agent to a full grid.\"\n                         .format(len(self._grid[0]), len(self._grid[1])))",
    "docstring": "Add agent to the next available spot in the grid.\n\n        :returns:\n            (x,y) of the agent in the grid. This is the agent's overall\n            coordinate in the grand grid (i.e. the actual coordinate of the\n            agent w.t.r **origin**).\n\n        :raises: `ValueError` if the grid is full."
  },
  {
    "code": "def slackbuild(self, name, sbo_file):\n        return URL(self.sbo_url + name + sbo_file).reading()",
    "docstring": "Read SlackBuild file"
  },
  {
    "code": "def check_trajectory_id(self, dataset):\n        results = []\n        exists_ctx = TestCtx(BaseCheck.MEDIUM, 'Variable defining \"trajectory_id\" exists')\n        trajectory_ids = dataset.get_variables_by_attributes(cf_role='trajectory_id')\n        exists_ctx.assert_true(trajectory_ids, 'variable defining cf_role=\"trajectory_id\" exists')\n        if not trajectory_ids:\n            return exists_ctx.to_result()\n        results.append(exists_ctx.to_result())\n        test_ctx = TestCtx(BaseCheck.MEDIUM, 'Recommended attributes for the {} variable'.format(trajectory_ids[0].name))\n        test_ctx.assert_true(\n            getattr(trajectory_ids[0], 'long_name', '') != \"\",\n            \"long_name attribute should exist and not be empty\"\n        )\n        results.append(test_ctx.to_result())\n        return results",
    "docstring": "Checks that if a variable exists for the trajectory id it has the appropriate attributes\n\n        :param netCDF4.Dataset dataset: An open netCDF dataset"
  },
  {
    "code": "def readGyroRange( self ):\n        raw_data = self._readByte( self.REG_GYRO_CONFIG )\n        raw_data = (raw_data | 0xE7) ^ 0xE7\n        return raw_data",
    "docstring": "!\n        Read range of gyroscope.\n\n        @return an int value. It should be one of the following values (GYRO_RANGE_250DEG)\n\n        @see GYRO_RANGE_250DEG\n        @see GYRO_RANGE_500DEG\n        @see GYRO_RANGE_1KDEG\n        @see GYRO_RANGE_2KDEG"
  },
  {
    "code": "def _calculate_checksum(value):\n        polynomial = 0x131\n        crc = 0xFF\n        for byteCtr in [ord(x) for x in struct.pack(\">H\", value)]:\n            crc ^= byteCtr\n            for bit in range(8, 0, -1):\n                if crc & 0x80:\n                    crc = (crc << 1) ^ polynomial\n                else:\n                    crc = (crc << 1)\n        return crc",
    "docstring": "4.12 Checksum Calculation from an unsigned short input"
  },
  {
    "code": "def countByValue(self):\n        return self.map(lambda x: (x, 1)).reduceByKey(lambda x, y: x+y)",
    "docstring": "Return a new DStream in which each RDD contains the counts of each\n        distinct value in each RDD of this DStream."
  },
  {
    "code": "def find_data_files(source, target, patterns):\n    if glob.has_magic(source) or glob.has_magic(target):\n        raise ValueError(\"Magic not allowed in src, target\")\n    ret = {}\n    for pattern in patterns:\n        pattern = os.path.join(source, pattern)\n        for filename in glob.glob(pattern):\n            if os.path.isfile(filename):\n                targetpath = os.path.join(\n                    target, os.path.relpath(filename, source)\n                )\n                path = os.path.dirname(targetpath)\n                ret.setdefault(path, []).append(filename)\n    return sorted(ret.items())",
    "docstring": "Locates the specified data-files and returns the matches\n    in a data_files compatible format.\n\n    source is the root of the source data tree.\n        Use '' or '.' for current directory.\n    target is the root of the target data tree.\n        Use '' or '.' for the distribution directory.\n    patterns is a sequence of glob-patterns for the\n        files you want to copy."
  },
  {
    "code": "def home_two_point_field_goal_percentage(self):\n        result = float(self.home_two_point_field_goals) / \\\n            float(self.home_two_point_field_goal_attempts)\n        return round(float(result), 3)",
    "docstring": "Returns a ``float`` of the number of two point field goals made divided\n        by the number of two point field goal attempts by the home team.\n        Percentage ranges from 0-1."
  },
  {
    "code": "def get_widget(self, index=None, path=None, tabs=None):\n        if (index and tabs) or (path and tabs):\n            return tabs.widget(index)\n        elif self.plugin:\n            return self.get_plugin_tabwidget(self.plugin).currentWidget()\n        else:\n            return self.plugins_tabs[0][0].currentWidget()",
    "docstring": "Get widget by index.\n\n        If no tabs and index specified the current active widget is returned."
  },
  {
    "code": "def prt_gos_flat(self, prt):\n        prtfmt = self.datobj.kws['fmtgo']\n        _go2nt = self.sortobj.grprobj.go2nt\n        go2nt = {go:_go2nt[go] for go in self.go2nt}\n        prt.write(\"\\n{N} GO IDs:\\n\".format(N=len(go2nt)))\n        _sortby = self._get_sortgo()\n        for ntgo in sorted(go2nt.values(), key=_sortby):\n            prt.write(prtfmt.format(**ntgo._asdict()))",
    "docstring": "Print flat GO list."
  },
  {
    "code": "def _function_handler(function, args, kwargs, pipe):\n    signal.signal(signal.SIGINT, signal.SIG_IGN)\n    result = process_execute(function, *args, **kwargs)\n    send_result(pipe, result)",
    "docstring": "Runs the actual function in separate process and returns its result."
  },
  {
    "code": "def score_braycurtis(self, term1, term2, **kwargs):\n        t1_kde = self.kde(term1, **kwargs)\n        t2_kde = self.kde(term2, **kwargs)\n        return 1-distance.braycurtis(t1_kde, t2_kde)",
    "docstring": "Compute a weighting score based on the \"City Block\" distance between\n        the kernel density estimates of two terms.\n\n        Args:\n            term1 (str)\n            term2 (str)\n\n        Returns: float"
  },
  {
    "code": "def rarlognormal(a, sigma, rho, size=1):\n    R\n    f = utils.ar1\n    if np.isscalar(a):\n        r = f(rho, 0, sigma, size)\n    else:\n        n = len(a)\n        r = [f(rho, 0, sigma, n) for i in range(size)]\n        if size == 1:\n            r = r[0]\n    return a * np.exp(r)",
    "docstring": "R\"\"\"\n    Autoregressive normal random variates.\n\n    If a is a scalar, generates one series of length size.\n    If a is a sequence, generates size series of the same length\n    as a."
  },
  {
    "code": "def block(self, to_block):\n        to_block = list(map(lambda obj: self.idpool.id(obj), to_block))\n        new_obj = list(filter(lambda vid: vid not in self.oracle.vmap.e2i, to_block))\n        self.oracle.add_clause([-vid for vid in to_block])\n        for vid in new_obj:\n            self.oracle.add_clause([-vid], 1)",
    "docstring": "The method serves for imposing a constraint forbidding the hitting\n            set solver to compute a given hitting set. Each set to block is\n            encoded as a hard clause in the MaxSAT problem formulation, which\n            is then added to the underlying oracle.\n\n            :param to_block: a set to block\n            :type to_block: iterable(obj)"
  },
  {
    "code": "def focus_parent(self):\n        mid = self.get_selected_mid()\n        newpos = self._tree.parent_position(mid)\n        if newpos is not None:\n            newpos = self._sanitize_position((newpos,))\n            self.body.set_focus(newpos)",
    "docstring": "move focus to parent of currently focussed message"
  },
  {
    "code": "def get_next_asset(self):\n        try:\n            next_object = next(self)\n        except StopIteration:\n            raise IllegalState('no more elements available in this list')\n        except Exception:\n            raise OperationFailed()\n        else:\n            return next_object",
    "docstring": "Gets the next Asset in this list.\n\n        return: (osid.repository.Asset) - the next Asset in this list.\n                The has_next() method should be used to test that a next\n                Asset is available before calling this method.\n        raise:  IllegalState - no more elements available in this list\n        raise:  OperationFailed - unable to complete request\n        compliance: mandatory - This method must be implemented."
  },
  {
    "code": "def tobinary(images, path, prefix=\"image\", overwrite=False, credentials=None):\n    from thunder.writers import get_parallel_writer\n    def tobuffer(kv):\n        key, img = kv\n        fname = prefix + \"-\" + \"%05d.bin\" % int(key)\n        return fname, img.copy()\n    writer = get_parallel_writer(path)(path, overwrite=overwrite, credentials=credentials)\n    images.foreach(lambda x: writer.write(tobuffer(x)))\n    config(path, list(images.value_shape), images.dtype, overwrite=overwrite)",
    "docstring": "Write out images as binary files.\n\n    See also\n    --------\n    thunder.data.images.tobinary"
  },
  {
    "code": "def _pfp__restore_snapshot(self, recurse=True):\n        super(Struct, self)._pfp__restore_snapshot(recurse=recurse)\n        if recurse:\n            for child in self._pfp__children:\n                child._pfp__restore_snapshot(recurse=recurse)",
    "docstring": "Restore the snapshotted value without triggering any events"
  },
  {
    "code": "def array_bytes(shape, dtype):\n    return np.product(shape)*np.dtype(dtype).itemsize",
    "docstring": "Estimates the memory in bytes required for an array of the supplied shape and dtype"
  },
  {
    "code": "def compute_master_secret(self, pre_master_secret,\n                              client_random, server_random):\n        seed = client_random + server_random\n        if self.tls_version < 0x0300:\n            return None\n        elif self.tls_version == 0x0300:\n            return self.prf(pre_master_secret, seed, 48)\n        else:\n            return self.prf(pre_master_secret, b\"master secret\", seed, 48)",
    "docstring": "Return the 48-byte master_secret, computed from pre_master_secret,\n        client_random and server_random. See RFC 5246, section 6.3."
  },
  {
    "code": "def find_first_in_list(txt: str, str_list: [str]) -> int:\n    start = len(txt) + 1\n    for item in str_list:\n        if start > txt.find(item) > -1:\n            start = txt.find(item)\n    return start if len(txt) + 1 > start > -1 else -1",
    "docstring": "Returns the index of the earliest occurence of an item from a list in a string\n\n    Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3"
  },
  {
    "code": "def get_tasks():\n    from paver.tasks import environment\n    for tsk in environment.get_tasks():\n        print(tsk.shortname)",
    "docstring": "Get all paver-defined tasks."
  },
  {
    "code": "def handle(self, *args, **options):\n        logger.info(\"Build started\")\n        self.set_options(*args, **options)\n        if not options.get(\"keep_build_dir\"):\n            self.init_build_dir()\n        if not options.get(\"skip_static\"):\n            self.build_static()\n        if not options.get(\"skip_media\"):\n            self.build_media()\n        self.build_views()\n        logger.info(\"Build finished\")",
    "docstring": "Making it happen."
  },
  {
    "code": "def action(args):\n    log.info('loading reference package')\n    r = refpkg.Refpkg(args.refpkg, create=False)\n    q = r.contents\n    for i in range(args.n):\n        if q['rollback'] is None:\n            log.error('Cannot rollback {} changes; '\n                      'refpkg only records {} changes.'.format(args.n, i))\n            return 1\n        else:\n            q = q['rollback']\n    for i in range(args.n):\n        r.rollback()\n    return 0",
    "docstring": "Roll back commands on a refpkg.\n\n    *args* should be an argparse object with fields refpkg (giving the\n    path to the refpkg to operate on) and n (giving the number of\n    operations to roll back)."
  },
  {
    "code": "def add_request(self, request):\n        queue_item = QueueItem(request, Response(request.url))\n        self.add(queue_item)\n        return queue_item",
    "docstring": "Add a request to the queue.\n\n        Args:\n            request (:class:`nyawc.http.Request`): The request to add.\n\n        Returns:\n            :class:`nyawc.QueueItem`: The created queue item."
  },
  {
    "code": "def name(self, value):\n        if isinstance(value, string_types):\n            match = Parameter._PARAM_NAME_COMPILER_MATCHER(value)\n            if match is None or match.group() != value:\n                value = re_compile(value)\n        self._name = value",
    "docstring": "Set parameter name.\n\n        :param str value: name value."
  },
  {
    "code": "def get_note(self, note_id):\n        index = 0\n        while True:\n            notes = self.my_notes(start_index=index, sort_by='noteId')\n            if notes['result'] != 'success':\n                break\n            if notes['loans'][0]['noteId'] > note_id:\n                break\n            if notes['loans'][-1]['noteId'] >= note_id:\n                for note in notes['loans']:\n                    if note['noteId'] == note_id:\n                        return note\n            index += 100\n        return False",
    "docstring": "Get a loan note that you've invested in by ID\n\n        Parameters\n        ----------\n        note_id : int\n            The note ID\n\n        Returns\n        -------\n        dict\n            A dictionary representing the matching note or False\n\n        Examples\n        --------\n            >>> from lendingclub import LendingClub\n            >>> lc = LendingClub(email='test@test.com', password='secret123')\n            >>> lc.authenticate()\n            True\n            >>> notes = lc.my_notes()                  # Get the first 100 loan notes\n            >>> len(notes['loans'])\n            100\n            >>> notes['total']                          # See the total number of loan notes you have\n            630\n            >>> notes = lc.my_notes(start_index=100)   # Get the next 100 loan notes\n            >>> len(notes['loans'])\n            100\n            >>> notes = lc.my_notes(get_all=True)       # Get all notes in one request (may be slow)\n            >>> len(notes['loans'])\n            630"
  },
  {
    "code": "def get_parameters(self):\n        d = {}\n        for k in ['label', 'verbose_name', 'required', 'hint', 'placeholder', 'choices',\n            'default', 'validators', 'max_length']:\n            d[k] = getattr(self, k)\n        return d",
    "docstring": "Get common attributes and it'll used for Model.relationship clone process"
  },
  {
    "code": "def CreateWeightTableLDAS(in_ldas_nc,\n                          in_nc_lon_var,\n                          in_nc_lat_var,\n                          in_catchment_shapefile,\n                          river_id,\n                          in_connectivity_file,\n                          out_weight_table,\n                          area_id=None,\n                          file_geodatabase=None):\n    data_ldas_nc = Dataset(in_ldas_nc)\n    variables_list = data_ldas_nc.variables.keys()\n    if in_nc_lon_var not in variables_list:\n        raise Exception(\"Invalid longitude variable. Choose from: {0}\"\n                        .format(variables_list))\n    if in_nc_lat_var not in variables_list:\n        raise Exception(\"Invalid latitude variable. Choose from: {0}\"\n                        .format(variables_list))\n    ldas_lon = data_ldas_nc.variables[in_nc_lon_var][:]\n    ldas_lat = data_ldas_nc.variables[in_nc_lat_var][:]\n    data_ldas_nc.close()\n    rtree_create_weight_table(ldas_lat, ldas_lon,\n                              in_catchment_shapefile, river_id,\n                              in_connectivity_file, out_weight_table,\n                              file_geodatabase, area_id)",
    "docstring": "Create Weight Table for NLDAS, GLDAS grids as well as for 2D Joules,\n    or LIS Grids\n\n    Parameters\n    ----------\n    in_ldas_nc: str\n        Path to the land surface model NetCDF grid.\n    in_nc_lon_var: str\n        The variable name in the NetCDF file for the longitude.\n    in_nc_lat_var: str\n        The variable name in the NetCDF file for the latitude.\n    in_catchment_shapefile: str\n        Path to the Catchment shapefile.\n    river_id: str\n        The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO').\n    in_connectivity_file: str\n        The path to the RAPID connectivity file.\n    out_weight_table: str\n        The path to the output weight table file.\n    area_id: str, optional\n        The name of the field with the area of each catchment stored in meters\n        squared. Default is it calculate the area.\n    file_geodatabase: str, optional\n        Path to the file geodatabase. If you use this option, in_drainage_line\n        is the name of the stream network feature class.\n        (WARNING: Not always stable with GDAL.)\n\n\n    Example:\n\n    .. code:: python\n\n        from RAPIDpy.gis.weight import CreateWeightTableLDAS\n\n        CreateWeightTableLDAS(\n            in_ldas_nc='/path/to/runoff_grid.nc',\n            in_nc_lon_var=\"lon_110\",\n            in_nc_lat_var=\"lat_110\",\n            in_catchment_shapefile='/path/to/catchment.shp',\n            river_id='LINKNO',\n            in_connectivity_file='/path/to/rapid_connect.csv',\n            out_weight_table='/path/to/ldas_weight.csv',\n        )"
  },
  {
    "code": "def after(self, i, sibling, name=None):\n        self.parent._insert(sibling, idx=self._own_index + 1 + i, name=name)\n        return self",
    "docstring": "Adds siblings after the current tag."
  },
  {
    "code": "def get_named_parent(decl):\n    if not decl:\n        return None\n    parent = decl.parent\n    while parent and (not parent.name or parent.name == '::'):\n        parent = parent.parent\n    return parent",
    "docstring": "Returns a reference to a named parent declaration.\n\n    Args:\n        decl (declaration_t): the child declaration\n\n    Returns:\n        declaration_t: the declaration or None if not found."
  },
  {
    "code": "def exec_background(controller, cmd, *args):\n    controller.logger.info(\"Executing in the background: {0} {1}\",\n                           cmd, \" \".join(args))\n    try:\n        subprocess.Popen([cmd] + list(args),\n                         stdout=open(os.devnull, \"wb\"),\n                         stderr=open(os.devnull, \"wb\"))\n    except OSError as err:\n        controller.logger.error(\"Failed to execute process: {0}\", err)",
    "docstring": "Executes a subprocess in the background."
  },
  {
    "code": "def quantiles(data, nbins_or_partition_bounds):\n    return apply_along_axis(\n        qcut,\n        1,\n        data,\n        q=nbins_or_partition_bounds, labels=False,\n    )",
    "docstring": "Compute rowwise array quantiles on an input."
  },
  {
    "code": "def get_config(config_spec):\n        config_file = None\n        if config_spec.startswith(\"http\"):\n            config_file = urllib.urlopen(config_spec)\n        else:\n            config_file = open(config_spec)\n        config = json.load(config_file)\n        try:\n            config_file.close()\n        except:\n            pass\n        return config",
    "docstring": "Like get_json_config but does not parse result as JSON"
  },
  {
    "code": "def func_str(func, args=[], kwargs={}, type_aliases=[], packed=False,\n             packkw=None, truncate=False):\n    import utool as ut\n    truncatekw = {}\n    argrepr_list = ([] if args is None else\n                    ut.get_itemstr_list(args, nl=False, truncate=truncate,\n                                        truncatekw=truncatekw))\n    kwrepr_list = ([] if kwargs is None else\n                   ut.dict_itemstr_list(kwargs, explicit=True, nl=False,\n                                        truncate=truncate,\n                                        truncatekw=truncatekw))\n    repr_list = argrepr_list + kwrepr_list\n    argskwargs_str = ', '.join(repr_list)\n    _str = '%s(%s)' % (meta_util_six.get_funcname(func), argskwargs_str)\n    if packed:\n        packkw_ = dict(textwidth=80, nlprefix='    ', break_words=False)\n        if packkw is not None:\n            packkw_.update(packkw_)\n        _str = packstr(_str, **packkw_)\n    return _str",
    "docstring": "string representation of function definition\n\n    Returns:\n        str: a representation of func with args, kwargs, and type_aliases\n\n    Args:\n        func (function):\n        args (list): argument values (default = [])\n        kwargs (dict): kwargs values (default = {})\n        type_aliases (list): (default = [])\n        packed (bool): (default = False)\n        packkw (None): (default = None)\n\n    Returns:\n        str: func_str\n\n    CommandLine:\n        python -m utool.util_str --exec-func_str\n\n    Example:\n        >>> # ENABLE_DOCTEST\n        >>> from utool.util_str import *  # NOQA\n        >>> func = byte_str\n        >>> args = [1024, 'MB']\n        >>> kwargs = dict(precision=2)\n        >>> type_aliases = []\n        >>> packed = False\n        >>> packkw = None\n        >>> _str = func_str(func, args, kwargs, type_aliases, packed, packkw)\n        >>> result = _str\n        >>> print(result)\n        byte_str(1024, 'MB', precision=2)"
  },
  {
    "code": "def run(self):\n        self.timer = t.Thread(target=self.report_spans)\n        self.timer.daemon = True\n        self.timer.name = \"Instana Span Reporting\"\n        self.timer.start()",
    "docstring": "Span a background thread to periodically report queued spans"
  },
  {
    "code": "def speckleRange(self, value):\n        if value >= 0:\n            self._speckle_range = value\n        else:\n            raise InvalidSpeckleRangeError(\"Speckle range cannot be negative.\")\n        self._replace_bm()",
    "docstring": "Set private ``_speckle_range`` and reset ``_block_matcher``."
  },
  {
    "code": "def direct(ctx, path):\n    try:\n        url = make_url(ctx.obj['RWS'].base_url, path)\n        resp = requests.get(url, auth=HTTPBasicAuth(ctx.obj['USERNAME'], ctx.obj['PASSWORD']))\n        click.echo(resp.text)\n    except RWSException as e:\n        click.echo(e.message)\n    except requests.exceptions.HTTPError as e:\n        click.echo(e.message)",
    "docstring": "Make direct call to RWS, bypassing rwslib"
  },
  {
    "code": "def register_func_list(self, func_and_handler):\n        for func, handler in func_and_handler:\n            self._function_dispatch.register(func, handler)\n        self.dispatch.cache_clear()",
    "docstring": "register a function to determine if the handle\n            should be used for the type"
  },
  {
    "code": "def remove_from_gallery(self):\n        url = self._imgur._base_url + \"/3/gallery/{0}\".format(self.id)\n        self._imgur._send_request(url, needs_auth=True, method='DELETE')\n        if isinstance(self, Image):\n            item = self._imgur.get_image(self.id)\n        else:\n            item = self._imgur.get_album(self.id)\n        _change_object(self, item)\n        return self",
    "docstring": "Remove this image from the gallery."
  },
  {
    "code": "def add_crs(op, element, **kwargs):\n    return element.map(lambda x: convert_to_geotype(x, kwargs.get('crs')), Element)",
    "docstring": "Converts any elements in the input to their equivalent geotypes\n    if given a coordinate reference system."
  },
  {
    "code": "def is_multifile_object_without_children(self, location: str) -> bool:\n        if isdir(location):\n            return len(self.find_multifile_object_children(location)) == 0\n        else:\n            if exists(location):\n                return True\n            else:\n                return False",
    "docstring": "Returns True if an item with this location is present as a multifile object without children.\n        For this implementation, this means that there is a file with the appropriate name but without extension\n\n        :param location:\n        :return:"
  },
  {
    "code": "def update(self, new_email_address, name, access_level, password=None):\n        params = {\"email\": self.email_address}\n        body = {\n            \"EmailAddress\": new_email_address,\n            \"Name\": name,\n            \"AccessLevel\": access_level,\n            \"Password\": password}\n        response = self._put(\"/clients/%s/people.json\" % self.client_id,\n                             body=json.dumps(body), params=params)\n        self.email_address = new_email_address",
    "docstring": "Updates the details for a person. Password is optional and is only updated if supplied."
  },
  {
    "code": "def get_balance(self):\n        self.br.open(self.MOBILE_WEB_URL % {'accountno': self.account})\n        try:\n            self.br.find_link(text='Register')\n            raise InvalidAccountException\n        except mechanize.LinkNotFoundError:\n            pass\n        self.br.follow_link(text='My sarafu')\n        self.br.follow_link(text='Balance Inquiry')\n        self.br.select_form(nr=0)\n        self.br['pin'] = self.pin\n        r = self.br.submit().read()\n        if re.search(r'Invalid PIN', r):\n            raise AuthDeniedException\n        if re.search(r'Error occured', r):\n            raise RequestErrorException\n        if re.search(r'Your balance is TSH (?P<balance>[\\d\\.]+)', r):\n            match = re.search(r'Your balance is TSH (?P<balance>[\\d\\.]+)', r)\n            return match.group('balance')",
    "docstring": "Retrieves the balance for the configured account"
  },
  {
    "code": "def spark_string(ints):\n    ticks = u'▁▂▃▅▆▇'\n    ints = [i for i in ints if type(i) == int]\n    if len(ints) == 0:\n        return \"\"\n    step = (max(ints) / float(len(ticks) - 1)) or 1\n    return u''.join(\n        ticks[int(round(i / step))] if type(i) == int else u'.' for i in ints)",
    "docstring": "Returns a spark string from given iterable of ints."
  },
  {
    "code": "def _fix_lsm_bitspersample(self, parent):\n        if self.code != 258 or self.count != 2:\n            return\n        log.warning('TiffTag %i: correcting LSM bitspersample tag', self.code)\n        value = struct.pack('<HH', *self.value)\n        self.valueoffset = struct.unpack('<I', value)[0]\n        parent.filehandle.seek(self.valueoffset)\n        self.value = struct.unpack('<HH', parent.filehandle.read(4))",
    "docstring": "Correct LSM bitspersample tag.\n\n        Old LSM writers may use a separate region for two 16-bit values,\n        although they fit into the tag value element of the tag."
  },
  {
    "code": "def _add_flags(flags, new_flags):\n    flags = _get_flags(flags)\n    new_flags = _get_flags(new_flags)\n    return flags | new_flags",
    "docstring": "Combine ``flags`` and ``new_flags``"
  },
  {
    "code": "def add_intf_router(self, rout_id, tenant_id, subnet_lst):\n        try:\n            for subnet_id in subnet_lst:\n                body = {'subnet_id': subnet_id}\n                intf = self.neutronclient.add_interface_router(rout_id,\n                                                               body=body)\n                intf.get('port_id')\n        except Exception as exc:\n            LOG.error(\"Failed to create router intf ID %(id)s,\"\n                      \" Exc %(exc)s\", {'id': rout_id, 'exc': str(exc)})\n            return False\n        return True",
    "docstring": "Add the interfaces to a router."
  },
  {
    "code": "def open(self):\n        self._geometry.lid_status = self._module.open()\n        self._ctx.deck.recalculate_high_z()\n        return self._geometry.lid_status",
    "docstring": "Opens the lid"
  },
  {
    "code": "def absolute(parser, token):\n    node = url(parser, token)\n    return AbsoluteUrlNode(\n        view_name=node.view_name,\n        args=node.args,\n        kwargs=node.kwargs,\n        asvar=node.asvar\n    )",
    "docstring": "Returns a full absolute URL based on the request host.\n\n    This template tag takes exactly the same paramters as url template tag."
  },
  {
    "code": "def read(tex):\n    if isinstance(tex, str):\n        tex = tex\n    else:\n        tex = ''.join(itertools.chain(*tex))\n    buf, children = Buffer(tokenize(tex)), []\n    while buf.hasNext():\n        content = read_tex(buf)\n        if content is not None:\n            children.append(content)\n    return TexEnv('[tex]', children), tex",
    "docstring": "Read and parse all LaTeX source\n\n    :param Union[str,iterable] tex: LaTeX source\n    :return TexEnv: the global environment"
  },
  {
    "code": "def splunk(cmd, user='admin', passwd='changeme'):\n    return sudo('/opt/splunkforwarder/bin/splunk {c} -auth {u}:{p}'\n                .format(c=cmd, u=user, p=passwd))",
    "docstring": "Authenticated call to splunk"
  },
  {
    "code": "def _sample_actions(self,\n            state: Sequence[tf.Tensor]) -> Tuple[Sequence[tf.Tensor], tf.Tensor, tf.Tensor]:\n        default = self.compiler.compile_default_action(self.batch_size)\n        bound_constraints = self.compiler.compile_action_bound_constraints(state)\n        action = self._sample_action(bound_constraints, default)\n        n, action, checking = self._check_preconditions(state, action, bound_constraints, default)\n        return action, n, checking",
    "docstring": "Returns sampled action fluents and tensors related to the sampling.\n\n        Args:\n            state (Sequence[tf.Tensor]): A list of state fluents.\n\n        Returns:\n            Tuple[Sequence[tf.Tensor], tf.Tensor, tf.Tensor]: A tuple with\n            action fluents, an integer tensor for the number of samples, and\n            a boolean tensor for checking all action preconditions."
  },
  {
    "code": "def parse_partlist(str):\n    lines = str.strip().splitlines()\n    lines = filter(len, lines)\n    hind = header_index(lines)\n    if hind is None:\n        log.debug('empty partlist found')\n        return ([], [])\n    header_line = lines[hind]\n    header = header_line.split('  ')\n    header = filter(len, header)\n    positions = [header_line.index(x) for x in header]\n    header = [x.strip().split()[0].lower() for x in header]\n    data_lines = lines[hind + 1:]\n    def parse_data_line(line):\n        y = [(h, line[pos1:pos2].strip()) for h, pos1, pos2 in zip(\n            header, positions, positions[1:] + [1000])]\n        return dict(y)\n    data = [parse_data_line(x) for x in data_lines]\n    return (header, data)",
    "docstring": "parse partlist text delivered by eagle.\n\n    header is converted to lowercase\n\n    :param str: input string\n    :rtype: tuple of header list and dict list: (['part','value',..], [{'part':'C1', 'value':'1n'}, ..])"
  },
  {
    "code": "def _parse_features(cls, feat_response):\n        features = {}\n        if feat_response.split(\"-\")[0] == \"211\":\n            for line in feat_response.splitlines():\n                if line.startswith(\" \"):\n                    key, _, value = line[1:].partition(\" \")\n                    features[key] = value\n        return features",
    "docstring": "Parse a dict of features from FTP feat response."
  },
  {
    "code": "def _on_hid_pnp(self, w_param, l_param):\r\n        \"Process WM_DEVICECHANGE system messages\"\r\n        new_status = \"unknown\"\r\n        if w_param == DBT_DEVICEARRIVAL:\r\n            notify_obj = None\r\n            if int(l_param):\r\n                notify_obj = DevBroadcastDevInterface.from_address(l_param)\r\n            if notify_obj and \\\r\n                    notify_obj.dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE:\r\n                new_status = \"connected\"\r\n        elif w_param == DBT_DEVICEREMOVECOMPLETE:\r\n            notify_obj = None\r\n            if int(l_param):\r\n                notify_obj = DevBroadcastDevInterface.from_address(l_param)\r\n            if notify_obj and \\\r\n                    notify_obj.dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE:\r\n                new_status = \"disconnected\"\r\n        if new_status != \"unknown\" and new_status != self.current_status:\r\n            self.current_status = new_status\r\n            self.on_hid_pnp(self.current_status)\r\n        return True",
    "docstring": "Process WM_DEVICECHANGE system messages"
  },
  {
    "code": "def check_token_auth(self, token):\n        serializer = self.get_signature()\n        try:\n            data = serializer.loads(token)\n        except BadSignature:\n            log.warning('Received bad token signature')\n            return False, None\n        if data['username'] not in self.users.users():\n            log.warning(\n                'Token auth signed message, but invalid user %s',\n                data['username']\n            )\n            return False, None\n        if data['hashhash'] != self.get_hashhash(data['username']):\n            log.warning(\n                'Token and password do not match, %s '\n                'needs to regenerate token',\n                data['username']\n            )\n            return False, None\n        return True, data['username']",
    "docstring": "Check to see who this is and if their token gets\n        them into the system."
  },
  {
    "code": "def reduce_alias_table(alias_table):\n    for alias in alias_table.sections():\n        if alias_table.has_option(alias, 'command'):\n            yield (alias, alias_table.get(alias, 'command'))",
    "docstring": "Reduce the alias table to a tuple that contains the alias and the command that the alias points to.\n\n    Args:\n        The alias table to be reduced.\n\n    Yields\n        A tuple that contains the alias and the command that the alias points to."
  },
  {
    "code": "def get_activities(self, count=10, since=None, style='summary',\n                       limit=None):\n        params = {}\n        if since:\n            params.update(fromDate=to_timestamp(since))\n        parts = ['my', 'activities', 'search']\n        if style != 'summary':\n            parts.append(style)\n        url = self._build_url(*parts)\n        return islice(self._iter(url, count, **params), limit)",
    "docstring": "Iterate over all activities, from newest to oldest.\n\n        :param count: The number of results to retrieve per page. If set to\n                      ``None``, pagination is disabled.\n\n        :param since: Return only activities since this date. Can be either\n                      a timestamp or a datetime object.\n\n        :param style: The type of records to return. May be one of\n                      'summary', 'briefs', 'ids', or 'extended'.\n\n        :param limit: The maximum number of activities to return for the given\n                      query."
  },
  {
    "code": "def _get_minutes(self, duration):\n        if isinstance(duration, datetime.datetime):\n            from_now = (duration - datetime.datetime.now()).total_seconds()\n            from_now = math.ceil(from_now / 60)\n            if from_now > 0:\n                return from_now\n            return\n        return duration",
    "docstring": "Calculate the number of minutes with the given duration.\n\n        :param duration: The duration\n        :type duration: int or datetime\n\n        :rtype: int or None"
  },
  {
    "code": "def is_union(declaration):\n    if not is_class(declaration):\n        return False\n    decl = class_traits.get_declaration(declaration)\n    return decl.class_type == class_declaration.CLASS_TYPES.UNION",
    "docstring": "Returns True if declaration represents a C++ union\n\n    Args:\n        declaration (declaration_t): the declaration to be checked.\n\n    Returns:\n        bool: True if declaration represents a C++ union"
  },
  {
    "code": "def parse_object(self, data):\n        for key, value in data.items():\n            if isinstance(value, (str, type(u''))) and \\\n               self.strict_iso_match.match(value):\n                data[key] = dateutil.parser.parse(value)\n        return data",
    "docstring": "Look for datetime looking strings."
  },
  {
    "code": "def is_suitable(self, request):\n        if self.key_type:\n            validation = KEY_TYPE_VALIDATIONS.get( self.get_type() )\n            return validation( request ) if validation else None\n        return True",
    "docstring": "Checks if key is suitable for given request according to key type and request's user agent."
  },
  {
    "code": "def from_mmap(cls, fname):\n        memmaped = joblib.load(fname, mmap_mode=\"r+\")\n        return cls(vocab=memmaped.vocab, vectors=memmaped.vectors)",
    "docstring": "Create a WordVectors class from a memory map\n\n        Parameters\n        ----------\n        fname : path to file\n\n        Returns\n        -------\n        WordVectors instance"
  },
  {
    "code": "def _get_business_hours_by_sec(self):\n        if self._get_daytime_flag:\n            dtstart = datetime(2014, 4, 1, self.start.hour, self.start.minute)\n            until = datetime(2014, 4, 1, self.end.hour, self.end.minute)\n            return (until - dtstart).total_seconds()\n        else:\n            dtstart = datetime(2014, 4, 1, self.start.hour, self.start.minute)\n            until = datetime(2014, 4, 2, self.end.hour, self.end.minute)\n            return (until - dtstart).total_seconds()",
    "docstring": "Return business hours in a day by seconds."
  },
  {
    "code": "def _keys_to_lower(self):\n        for k in list(self.keys()):\n            val = super(CaseInsensitiveDict, self).__getitem__(k)\n            super(CaseInsensitiveDict, self).__delitem__(k)\n            self.__setitem__(CaseInsensitiveStr(k), val)",
    "docstring": "Convert key set to lowercase."
  },
  {
    "code": "def _build_resource(self):\n        resource = {\"name\": self.name}\n        if self.dns_name is not None:\n            resource[\"dnsName\"] = self.dns_name\n        if self.description is not None:\n            resource[\"description\"] = self.description\n        if self.name_server_set is not None:\n            resource[\"nameServerSet\"] = self.name_server_set\n        return resource",
    "docstring": "Generate a resource for ``create`` or ``update``."
  },
  {
    "code": "def toSparse(self):\n        if self.isTransposed:\n            values = np.ravel(self.toArray(), order='F')\n        else:\n            values = self.values\n        indices = np.nonzero(values)[0]\n        colCounts = np.bincount(indices // self.numRows)\n        colPtrs = np.cumsum(np.hstack(\n            (0, colCounts, np.zeros(self.numCols - colCounts.size))))\n        values = values[indices]\n        rowIndices = indices % self.numRows\n        return SparseMatrix(self.numRows, self.numCols, colPtrs, rowIndices, values)",
    "docstring": "Convert to SparseMatrix"
  },
  {
    "code": "def _get_clean_parameters(kwargs):\n        return dict((k, v) for k, v in kwargs.items() if v is not None)",
    "docstring": "Clean the parameters by filtering out any parameters that have a None value."
  },
  {
    "code": "def get(self):\n        if not self.thread_local_data:\n            self.thread_local_data = threading.local()\n        if not hasattr(self.thread_local_data, 'context'):\n            self.thread_local_data.context = OrderedDict()\n        return self.thread_local_data.context",
    "docstring": "Return a reference to a thread-specific context"
  },
  {
    "code": "def initinfo(self) -> Tuple[Union[float, int, bool], bool]:\n        init = self.INIT\n        if (init is not None) and hydpy.pub.options.usedefaultvalues:\n            with Parameter.parameterstep('1d'):\n                return self.apply_timefactor(init), True\n        return variabletools.TYPE2MISSINGVALUE[self.TYPE], False",
    "docstring": "The actual initial value of the given parameter.\n\n        Some |Parameter| subclasses define another value for class\n        attribute `INIT` than |None| to provide a default value.\n\n        Let's define a parameter test class and prepare a function for\n        initialising it and connecting the resulting instance to a\n        |SubParameters| object:\n\n        >>> from hydpy.core.parametertools import Parameter, SubParameters\n        >>> class Test(Parameter):\n        ...     NDIM = 0\n        ...     TYPE = float\n        ...     TIME = None\n        ...     INIT = 2.0\n        >>> class SubGroup(SubParameters):\n        ...     CLASSES = (Test,)\n        >>> def prepare():\n        ...     subpars = SubGroup(None)\n        ...     test = Test(subpars)\n        ...     test.__hydpy__connect_variable2subgroup__()\n        ...     return test\n\n        By default, making use of the `INIT` attribute is disabled:\n\n        >>> test = prepare()\n        >>> test\n        test(?)\n\n        Enable it through setting |Options.usedefaultvalues| to |True|:\n\n        >>> from hydpy import pub\n        >>> pub.options.usedefaultvalues = True\n        >>> test = prepare()\n        >>> test\n        test(2.0)\n\n        When no `INIT` attribute is defined, enabling\n        |Options.usedefaultvalues| has no effect, of course:\n\n        >>> del Test.INIT\n        >>> test = prepare()\n        >>> test\n        test(?)\n\n        For time-dependent parameter values, the `INIT` attribute is assumed\n        to be related to a |Parameterstep| of one day:\n\n        >>> test.parameterstep = '2d'\n        >>> test.simulationstep = '12h'\n        >>> Test.INIT = 2.0\n        >>> Test.TIME = True\n        >>> test = prepare()\n        >>> test\n        test(4.0)\n        >>> test.value\n        1.0"
  },
  {
    "code": "def wns_send_bulk_message(\n\turi_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs\n):\n\tres = []\n\tif uri_list:\n\t\tfor uri in uri_list:\n\t\t\tr = wns_send_message(\n\t\t\t\turi=uri, message=message, xml_data=xml_data,\n\t\t\t\traw_data=raw_data, application_id=application_id, **kwargs\n\t\t\t)\n\t\t\tres.append(r)\n\treturn res",
    "docstring": "WNS doesn't support bulk notification, so we loop through each uri.\n\n\t:param uri_list: list: A list of uris the notification will be sent to.\n\t:param message: str: The notification data to be sent.\n\t:param xml_data: dict: A dictionary containing data to be converted to an xml tree.\n\t:param raw_data: str: Data to be sent via a `raw` notification."
  },
  {
    "code": "def server_reboot(host=None,\n                  admin_username=None,\n                  admin_password=None,\n                  module=None):\n    return __execute_cmd('serveraction powercycle',\n                         host=host, admin_username=admin_username,\n                         admin_password=admin_password, module=module)",
    "docstring": "Issues a power-cycle operation on the managed server. This action is\n    similar to pressing the power button on the system's front panel to\n    power down and then power up the system.\n\n    host\n        The chassis host.\n\n    admin_username\n        The username used to access the chassis.\n\n    admin_password\n        The password used to access the chassis.\n\n    module\n        The element to reboot on the chassis such as a blade. If not provided,\n        the chassis will be rebooted.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt dell dracr.server_reboot\n        salt dell dracr.server_reboot module=server-1"
  },
  {
    "code": "def to_dataframe(self):\n        keys = self.data[0].keys()\n        column_list =[]\n        for k in keys:\n            key_list = []\n            for i in xrange(0,len(self.data)):\n                key_list.append(self.data[i][k])\n            column_list.append(key_list)\n        df = DataFrame(np.asarray(column_list).transpose(), columns=keys)\n        for i in xrange(0,df.shape[1]):\n            if is_number(df.iloc[:,i]):\n                df.iloc[:,i] = df.iloc[:,i].astype(float)\n        return df",
    "docstring": "Reads the common format self.data and writes out to a dataframe."
  },
  {
    "code": "def get_job_logs_from_workflow(workflow_id):\n    query_result = (\n        db.session.query(\n            models.CrawlerJob.logs,\n        )\n        .join(\n            models.CrawlerWorkflowObject,\n            models.CrawlerJob.job_id == models.CrawlerWorkflowObject.job_id,\n        )\n        .filter(models.CrawlerWorkflowObject.object_id == workflow_id)\n        .one_or_none()\n    )\n    if query_result is None:\n        click.secho(\n            (\n                \"Workflow %s was not found, maybe it's not a crawl workflow?\" %\n                workflow_id\n            ),\n            fg='yellow',\n        )\n        sys.exit(1)\n    _show_file(\n        file_path=query_result[0],\n        header_name='Log',\n    )",
    "docstring": "Retrieve the crawl logs from the workflow id."
  },
  {
    "code": "def aggregate_detail(slug_list, with_data_table=False):\n    r = get_r()\n    metrics_data = []\n    granularities = r._granularities()\n    keys = ['seconds', 'minutes', 'hours', 'day', 'week', 'month', 'year']\n    key_mapping = {gran: key for gran, key in zip(GRANULARITIES, keys)}\n    keys = [key_mapping[gran] for gran in granularities]\n    for slug, data in r.get_metrics(slug_list):\n        values = [data[t] for t in keys]\n        metrics_data.append((slug, values))\n    return {\n        'chart_id': \"metric-aggregate-{0}\".format(\"-\".join(slug_list)),\n        'slugs': slug_list,\n        'metrics': metrics_data,\n        'with_data_table': with_data_table,\n        'granularities': [g.title() for g in keys],\n    }",
    "docstring": "Template Tag to display multiple metrics.\n\n    * ``slug_list`` -- A list of slugs to display\n    * ``with_data_table`` -- if True, prints the raw data in a table."
  },
  {
    "code": "def _coerce_consumer_group(consumer_group):\n    if not isinstance(consumer_group, string_types):\n        raise TypeError('consumer_group={!r} must be text'.format(consumer_group))\n    if not isinstance(consumer_group, text_type):\n        consumer_group = consumer_group.decode('utf-8')\n    return consumer_group",
    "docstring": "Ensure that the consumer group is a text string.\n\n    :param consumer_group: :class:`bytes` or :class:`str` instance\n    :raises TypeError: when `consumer_group` is not :class:`bytes`\n        or :class:`str`"
  },
  {
    "code": "def get_option_labels(self, typ, element):\n        inter = self.get_typ_interface(typ)\n        return inter.get_option_labels(element)",
    "docstring": "Return labels for each level of the option model.\n\n        The options returned by :meth:`RefobjInterface.fetch_options` is a treemodel\n        with ``n`` levels. Each level should get a label to describe what is displays.\n\n        E.g. if you organize your options, so that the first level shows the tasks, the second\n        level shows the descriptors and the third one shows the versions, then\n        your labels should be: ``[\"Task\", \"Descriptor\", \"Version\"]``.\n\n        :param typ: the typ of options. E.g. Asset, Alembic, Camera etc\n        :type typ: str\n        :param element: The element for which the options should be fetched.\n        :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot`\n        :returns: label strings for all levels\n        :rtype: list\n        :raises: None"
  },
  {
    "code": "def _align_method_SERIES(left, right, align_asobject=False):\n    if isinstance(right, ABCSeries):\n        if not left.index.equals(right.index):\n            if align_asobject:\n                left = left.astype(object)\n                right = right.astype(object)\n            left, right = left.align(right, copy=False)\n    return left, right",
    "docstring": "align lhs and rhs Series"
  },
  {
    "code": "def add_token_without_limits(\n            self,\n            token_address: TokenAddress,\n    ) -> Address:\n        return self._add_token(\n            token_address=token_address,\n            additional_arguments=dict(),\n        )",
    "docstring": "Register token of `token_address` with the token network.\n        This applies for versions prior to 0.13.0 of raiden-contracts,\n        since limits were hardcoded into the TokenNetwork contract."
  },
  {
    "code": "def add_to_class(self, cls, name):\n        self.model_class = cls\n        setattr(cls, name, PhoneNumberDescriptor(self))\n        self._bound = True",
    "docstring": "Overrides the base class to add a PhoheNumberDescriptor rather than the standard FieldDescriptor"
  },
  {
    "code": "def join(self, timeout=None):\n    return super(_StoppableDaemonThread, self).join(timeout or self.JOIN_TIMEOUT)",
    "docstring": "Joins with a default timeout exposed on the class."
  },
  {
    "code": "def unset_sentry_context(self, tag):\n        if self.sentry_client:\n            self.sentry_client.tags.pop(tag, None)",
    "docstring": "Remove a context tag from sentry\n\n        :param tag: The context tag to remove\n        :type tag: :class:`str`"
  },
  {
    "code": "def _query_helper(self, by=None):\n        if by is None:\n            primary_keys = self.table.primary_key.columns.keys()\n            if len(primary_keys) > 1:\n                warnings.warn(\"WARNING: MORE THAN 1 PRIMARY KEY FOR TABLE %s. \"\n                              \"USING THE FIRST KEY %s.\" %\n                              (self.table.name, primary_keys[0]))\n            if not primary_keys:\n                raise NoPrimaryKeyException(\"Table %s needs a primary key for\"\n                                            \"the .last() method to work properly. \"\n                                            \"Alternatively, specify an ORDER BY \"\n                                            \"column with the by= argument. \" %\n                                            self.table.name)\n            id_col = primary_keys[0]\n        else:\n            id_col = by\n        if self.column is None:\n            col = \"*\"\n        else:\n            col = self.column.name\n        return col, id_col",
    "docstring": "Internal helper for preparing queries."
  },
  {
    "code": "def add(self, logical_id, deployment_preference_dict):\n        if logical_id in self._resource_preferences:\n            raise ValueError(\"logical_id {logical_id} previously added to this deployment_preference_collection\".format(\n                logical_id=logical_id))\n        self._resource_preferences[logical_id] = DeploymentPreference.from_dict(logical_id, deployment_preference_dict)",
    "docstring": "Add this deployment preference to the collection\n\n        :raise ValueError if an existing logical id already exists in the _resource_preferences\n        :param logical_id: logical id of the resource where this deployment preference applies\n        :param deployment_preference_dict: the input SAM template deployment preference mapping"
  },
  {
    "code": "def _merge_many_to_one_field_from_fkey(self, main_infos, prop, result):\n        if prop.columns[0].foreign_keys and prop.key.endswith('_id'):\n            rel_name = prop.key[0:-3]\n            for val in result:\n                if val[\"name\"] == rel_name:\n                    val[\"label\"] = main_infos['label']\n                    main_infos = None\n                    break\n        return main_infos",
    "docstring": "Find the relationship associated with this fkey and set the title\n\n        :param dict main_infos: The already collected datas about this column\n        :param obj prop: The property mapper of the relationship\n        :param list result: The actual collected headers\n        :returns: a main_infos dict or None"
  },
  {
    "code": "def get_ldict_keys(ldict, flatten_keys=False, **kwargs):\n    result = []\n    for ddict in ldict:\n        if isinstance(ddict, dict):\n            if flatten_keys:\n                ddict = flatten(ddict, **kwargs)\n            result.extend(ddict.keys())\n    return list(set(result))",
    "docstring": "Get first level keys from a list of dicts"
  },
  {
    "code": "def qnwgamma(n, a=1.0, b=1.0, tol=3e-14):\n    return _make_multidim_func(_qnwgamma1, n, a, b, tol)",
    "docstring": "Computes nodes and weights for gamma distribution\n\n    Parameters\n    ----------\n    n : int or array_like(float)\n        A length-d iterable of the number of nodes in each dimension\n\n    a : scalar or array_like(float) : optional(default=ones(d))\n        Shape parameter of the gamma distribution parameter. Must be positive\n\n    b : scalar or array_like(float) : optional(default=ones(d))\n        Scale parameter of the gamma distribution parameter. Must be positive\n\n    tol : scalar or array_like(float) : optional(default=ones(d) * 3e-14)\n        Tolerance parameter for newton iterations for each node\n\n    Returns\n    -------\n    nodes : np.ndarray(dtype=float)\n        Quadrature nodes\n\n    weights : np.ndarray(dtype=float)\n        Weights for quadrature nodes\n\n    Notes\n    -----\n    Based of original function ``qnwgamma`` in CompEcon toolbox by\n    Miranda and Fackler\n\n    References\n    ----------\n    Miranda, Mario J, and Paul L Fackler. Applied Computational\n    Economics and Finance, MIT Press, 2002."
  },
  {
    "code": "def permission_denied(request, template_name=None, extra_context=None):\n    if template_name is None:\n        template_name = ('403.html', 'authority/403.html')\n    context = {\n        'request_path': request.path,\n    }\n    if extra_context:\n        context.update(extra_context)\n    return HttpResponseForbidden(loader.render_to_string(\n        template_name=template_name,\n        context=context,\n        request=request,\n    ))",
    "docstring": "Default 403 handler.\n\n    Templates: `403.html`\n    Context:\n        request_path\n            The path of the requested URL (e.g., '/app/pages/bad_page/')"
  },
  {
    "code": "def reset(self):\n        if self._call_later_handler is not None:\n            self._call_later_handler.cancel()\n            self._call_later_handler = None\n            self._wait_done_cb()",
    "docstring": "Reseting duration for throttling"
  },
  {
    "code": "def object_build_function(node, member, localname):\n    args, varargs, varkw, defaults = inspect.getargspec(member)\n    if varargs is not None:\n        args.append(varargs)\n    if varkw is not None:\n        args.append(varkw)\n    func = build_function(\n        getattr(member, \"__name__\", None) or localname, args, defaults, member.__doc__\n    )\n    node.add_local_node(func, localname)",
    "docstring": "create astroid for a living function object"
  },
  {
    "code": "def send_frame(self, cmd, headers=None, body=''):\n        frame = utils.Frame(cmd, headers, body)\n        self.transport.transmit(frame)",
    "docstring": "Encode and send a stomp frame\n        through the underlying transport.\n\n        :param str cmd: the protocol command\n        :param dict headers: a map of headers to include in the frame\n        :param body: the content of the message"
  },
  {
    "code": "def consolidate_metadata(store, metadata_key='.zmetadata'):\n    store = normalize_store_arg(store)\n    def is_zarr_key(key):\n        return (key.endswith('.zarray') or key.endswith('.zgroup') or\n                key.endswith('.zattrs'))\n    out = {\n        'zarr_consolidated_format': 1,\n        'metadata': {\n            key: json_loads(store[key])\n            for key in store if is_zarr_key(key)\n        }\n    }\n    store[metadata_key] = json_dumps(out)\n    return open_consolidated(store, metadata_key=metadata_key)",
    "docstring": "Consolidate all metadata for groups and arrays within the given store\n    into a single resource and put it under the given key.\n\n    This produces a single object in the backend store, containing all the\n    metadata read from all the zarr-related keys that can be found. After\n    metadata have been consolidated, use :func:`open_consolidated` to open\n    the root group in optimised, read-only mode, using the consolidated\n    metadata to reduce the number of read operations on the backend store.\n\n    Note, that if the metadata in the store is changed after this\n    consolidation, then the metadata read by :func:`open_consolidated`\n    would be incorrect unless this function is called again.\n\n    .. note:: This is an experimental feature.\n\n    Parameters\n    ----------\n    store : MutableMapping or string\n        Store or path to directory in file system or name of zip file.\n    metadata_key : str\n        Key to put the consolidated metadata under.\n\n    Returns\n    -------\n    g : :class:`zarr.hierarchy.Group`\n        Group instance, opened with the new consolidated metadata.\n\n    See Also\n    --------\n    open_consolidated"
  },
  {
    "code": "def run(self, cmd):\n        import __main__\n        main_dict = __main__.__dict__\n        return self.runctx(cmd, main_dict, main_dict)",
    "docstring": "Profile a single executable statement in the main namespace."
  },
  {
    "code": "def _getOverlay(self, readDataInstance, sectionHdrsInstance):\n        if readDataInstance is not None and sectionHdrsInstance is not None:            \n            try:\n                offset = sectionHdrsInstance[-1].pointerToRawData.value + sectionHdrsInstance[-1].sizeOfRawData.value\n                readDataInstance.setOffset(offset)\n            except excep.WrongOffsetValueException:\n                if self._verbose:\n                    print \"It seems that the file has no overlay data.\"\n        else:\n            raise excep.InstanceErrorException(\"ReadData instance or SectionHeaders instance not specified.\")\n        return readDataInstance.data[readDataInstance.offset:]",
    "docstring": "Returns the overlay data from the PE file.\n        \n        @type readDataInstance: L{ReadData}\n        @param readDataInstance: A L{ReadData} instance containing the PE file data.\n        \n        @type sectionHdrsInstance: L{SectionHeaders}\n        @param sectionHdrsInstance: A L{SectionHeaders} instance containing the information about the sections present in the PE file.\n        \n        @rtype: str\n        @return: A string with the overlay data from the PE file.\n        \n        @raise InstanceErrorException: If the C{readDataInstance} or the C{sectionHdrsInstance} were not specified."
  },
  {
    "code": "def strip_empty_values(obj):\n    if isinstance(obj, dict):\n        new_obj = {}\n        for key, val in obj.items():\n            new_val = strip_empty_values(val)\n            if new_val is not None:\n                new_obj[key] = new_val\n        return new_obj or None\n    elif isinstance(obj, (list, tuple, set)):\n        new_obj = []\n        for val in obj:\n            new_val = strip_empty_values(val)\n            if new_val is not None:\n                new_obj.append(new_val)\n        return type(obj)(new_obj) or None\n    elif obj or obj is False or obj == 0:\n        return obj\n    else:\n        return None",
    "docstring": "Recursively strips empty values."
  },
  {
    "code": "def update_from(self, res_list):\n        for res in res_list:\n            name = res.properties.get(self._manager._name_prop, None)\n            uri = res.properties.get(self._manager._uri_prop, None)\n            self.update(name, uri)",
    "docstring": "Update the Name-URI cache from the provided resource list.\n\n        This is done by going through the resource list and updating any cache\n        entries for non-empty resource names in that list. Other cache entries\n        remain unchanged."
  },
  {
    "code": "def OnDoubleClick(self, event):\n        node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())\n        if node:\n            wx.PostEvent( self, SquareActivationEvent( node=node, point=event.GetPosition(), map=self ) )",
    "docstring": "Double click on a given square in the map"
  },
  {
    "code": "def batch_run(self, *commands):\n        original_retries = self.repeat_commands\n        self.repeat_commands = 1\n        for _ in range(original_retries):\n            for command in commands:\n                cmd = command[0]\n                args = command[1:]\n                cmd(*args)\n        self.repeat_commands = original_retries",
    "docstring": "Run batch of commands in sequence.\n\n            Input is positional arguments with (function pointer, *args) tuples.\n\n            This method is useful for executing commands to multiple groups with retries,\n            without having too long delays. For example,\n\n            - Set group 1 to red and brightness to 10%\n            - Set group 2 to red and brightness to 10%\n            - Set group 3 to white and brightness to 100%\n            - Turn off group 4\n\n            With three repeats, running these consecutively takes approximately 100ms * 13 commands * 3 times = 3.9 seconds.\n\n            With batch_run, execution takes same time, but first loop - each command is sent once to every group -\n            is finished within 1.3 seconds. After that, each command is repeated two times. Most of the time, this ensures\n            slightly faster changes for each group.\n\n            Usage:\n\n            led.batch_run((led.set_color, \"red\", 1), (led.set_brightness, 10, 1), (led.set_color, \"white\", 3), ...)"
  },
  {
    "code": "def delete_network(self, network):\n        n_res = MechResource(network['id'], a_const.NETWORK_RESOURCE,\n                             a_const.DELETE)\n        self.provision_queue.put(n_res)",
    "docstring": "Enqueue network delete"
  },
  {
    "code": "def _rearrange_output_for_package(self, target_workdir, java_package):\n    package_dir_rel = java_package.replace('.', os.path.sep)\n    package_dir = os.path.join(target_workdir, package_dir_rel)\n    safe_mkdir(package_dir)\n    for root, dirs, files in safe_walk(target_workdir):\n      if root == package_dir_rel:\n        continue\n      for f in files:\n        os.rename(\n          os.path.join(root, f),\n          os.path.join(package_dir, f)\n        )\n    for root, dirs, files in safe_walk(target_workdir, topdown = False):\n      for d in dirs:\n        full_dir = os.path.join(root, d)\n        if not os.listdir(full_dir):\n          os.rmdir(full_dir)",
    "docstring": "Rearrange the output files to match a standard Java structure.\n\n    Antlr emits a directory structure based on the relative path provided\n    for the grammar file. If the source root of the file is different from\n    the Pants build root, then the Java files end up with undesired parent\n    directories."
  },
  {
    "code": "def date_string_to_date(p_date):\n    result = None\n    if p_date:\n        parsed_date = re.match(r'(\\d{4})-(\\d{2})-(\\d{2})', p_date)\n        if parsed_date:\n            result = date(\n                int(parsed_date.group(1)),\n                int(parsed_date.group(2)),\n                int(parsed_date.group(3))\n            )\n        else:\n            raise ValueError\n    return result",
    "docstring": "Given a date in YYYY-MM-DD, returns a Python date object. Throws a\n    ValueError if the date is invalid."
  },
  {
    "code": "def RemoveWifiConnection(self, dev_path, connection_path):\n    dev_obj = dbusmock.get_object(dev_path)\n    settings_obj = dbusmock.get_object(SETTINGS_OBJ)\n    connections = dev_obj.Get(DEVICE_IFACE, 'AvailableConnections')\n    main_connections = settings_obj.ListConnections()\n    if connection_path not in connections and connection_path not in main_connections:\n        return\n    connections.remove(dbus.ObjectPath(connection_path))\n    dev_obj.Set(DEVICE_IFACE, 'AvailableConnections', connections)\n    main_connections.remove(connection_path)\n    settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections)\n    settings_obj.EmitSignal(SETTINGS_IFACE, 'ConnectionRemoved', 'o', [connection_path])\n    connection_obj = dbusmock.get_object(connection_path)\n    connection_obj.EmitSignal(CSETTINGS_IFACE, 'Removed', '', [])\n    self.object_manager_emit_removed(connection_path)\n    self.RemoveObject(connection_path)",
    "docstring": "Remove the specified WiFi connection.\n\n    You have to specify the device to remove the connection from, and the\n    path of the Connection.\n\n    Please note that this does not set any global properties."
  },
  {
    "code": "def lookup(ctx, path):\n    regions = parse_intervals(path, as_context=ctx.obj['semantic'])\n    _report_from_regions(regions, ctx.obj)",
    "docstring": "Determine which tests intersect a source interval."
  },
  {
    "code": "def _GetPathSegmentSeparator(self, path):\n    if path.startswith('\\\\') or path[1:].startswith(':\\\\'):\n      return '\\\\'\n    if path.startswith('/'):\n      return '/'\n    if '/' and '\\\\' in path:\n      forward_count = len(path.split('/'))\n      backward_count = len(path.split('\\\\'))\n      if forward_count > backward_count:\n        return '/'\n      return '\\\\'\n    if '/' in path:\n      return '/'\n    return '\\\\'",
    "docstring": "Given a path give back the path separator as a best guess.\n\n    Args:\n      path (str): path.\n\n    Returns:\n      str: path segment separator."
  },
  {
    "code": "def round_sf(number, digits):\n    units = None\n    try:\n        num = number.magnitude\n        units = number.units\n    except AttributeError:\n        num = number\n    try:\n        if (units != None):\n            rounded_num = round(num, digits - int(floor(log10(abs(num)))) - 1) * units\n        else:\n            rounded_num = round(num, digits - int(floor(log10(abs(num)))) - 1)\n        return rounded_num\n    except ValueError:\n        if (units != None):\n            return 0 * units\n        else:\n            return 0",
    "docstring": "Returns inputted value rounded to number of significant figures desired.\n\n    :param number: Value to be rounded\n    :type number: float\n    :param digits: number of significant digits to be rounded to.\n    :type digits: int"
  },
  {
    "code": "def _pseudodepths_wenner(configs, spacing=1, grid=None):\n    if grid is None:\n        xpositions = (configs - 1) * spacing\n    else:\n        xpositions = grid.get_electrode_positions()[configs - 1, 0]\n    z = np.abs(np.max(xpositions, axis=1) - np.min(xpositions, axis=1)) * -0.11\n    x = np.mean(xpositions, axis=1)\n    return x, z",
    "docstring": "Given distances between electrodes, compute Wenner pseudo\n    depths for the provided configuration\n\n    The pseudodepth is computed after Roy & Apparao, 1971, as 0.11 times\n    the distance between the two outermost electrodes. It's not really\n    clear why the Wenner depths are different from the Dipole-Dipole\n    depths, given the fact that Wenner configurations are a complete subset\n    of the Dipole-Dipole configurations."
  },
  {
    "code": "def user_object(\n        element_name,\n        cls,\n        child_processors,\n        required=True,\n        alias=None,\n        hooks=None\n):\n    converter = _user_object_converter(cls)\n    processor = _Aggregate(element_name, converter, child_processors, required, alias)\n    return _processor_wrap_if_hooks(processor, hooks)",
    "docstring": "Create a processor for user objects.\n\n    :param cls: Class object with a no-argument constructor or other callable no-argument object.\n\n    See also :func:`declxml.dictionary`"
  },
  {
    "code": "def _get_client():\n    client = salt.cloud.CloudClient(\n        os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),\n        pillars=copy.deepcopy(__pillar__.get('cloud', {}))\n    )\n    return client",
    "docstring": "Return a cloud client"
  },
  {
    "code": "def toc_directive(self, maxdepth=1):\n        articles_directive_content = TC.toc.render(\n            maxdepth=maxdepth,\n            article_list=self.sub_article_folders,\n        )\n        return articles_directive_content",
    "docstring": "Generate toctree directive text.\n\n        :param table_of_content_header:\n        :param header_bar_char:\n        :param header_line_length:\n        :param maxdepth:\n        :return:"
  },
  {
    "code": "def rethreshold(self, new_threshold, new_threshold_type='MAD'):\n        for family in self.families:\n            rethresh_detections = []\n            for d in family.detections:\n                if new_threshold_type == 'MAD' and d.threshold_type == 'MAD':\n                    new_thresh = (d.threshold /\n                                  d.threshold_input) * new_threshold\n                elif new_threshold_type == 'MAD' and d.threshold_type != 'MAD':\n                    raise MatchFilterError(\n                        'Cannot recalculate MAD level, '\n                        'use another threshold type')\n                elif new_threshold_type == 'absolute':\n                    new_thresh = new_threshold\n                elif new_threshold_type == 'av_chan_corr':\n                    new_thresh = new_threshold * d.no_chans\n                else:\n                    raise MatchFilterError(\n                        'new_threshold_type %s is not recognised' %\n                        str(new_threshold_type))\n                if d.detect_val >= new_thresh:\n                    d.threshold = new_thresh\n                    d.threshold_input = new_threshold\n                    d.threshold_type = new_threshold_type\n                    rethresh_detections.append(d)\n            family.detections = rethresh_detections\n        return self",
    "docstring": "Remove detections from the Party that are below a new threshold.\n\n        .. Note:: threshold can only be set higher.\n\n        .. Warning::\n            Works in place on Party.\n\n        :type new_threshold: float\n        :param new_threshold: New threshold level\n        :type new_threshold_type: str\n        :param new_threshold_type: Either 'MAD', 'absolute' or 'av_chan_corr'\n\n        .. rubric:: Examples\n\n        Using the MAD threshold on detections made using the MAD threshold:\n\n        >>> party = Party().read()\n        >>> len(party)\n        4\n        >>> party = party.rethreshold(10.0)\n        >>> len(party)\n        4\n        >>> # Note that all detections are self detections\n\n\n        Using the absolute thresholding method on the same Party:\n\n        >>> party = Party().read().rethreshold(6.0, 'absolute')\n        >>> len(party)\n        1\n\n\n        Using the av_chan_corr method on the same Party:\n\n        >>> party = Party().read().rethreshold(0.9, 'av_chan_corr')\n        >>> len(party)\n        4"
  },
  {
    "code": "def _match_setters(self, query):\n        q = query.decode('utf-8')\n        for name, parser, response, error_response in self._setters:\n            try:\n                parsed = parser(q)\n                logger.debug('Found response in setter of %s' % name)\n            except ValueError:\n                continue\n            try:\n                if isinstance(parsed, dict) and 'ch_id' in parsed:\n                    self._selected = parsed['ch_id']\n                    self._properties[name].set_value(parsed['0'])\n                else:\n                    self._properties[name].set_value(parsed)\n                return response\n            except ValueError:\n                if isinstance(error_response, bytes):\n                    return error_response\n                return self._device.error_response('command_error')\n        return None",
    "docstring": "Try to find a match"
  },
  {
    "code": "def get_all_items_of_delivery_note(self, delivery_note_id):\n        return self._iterate_through_pages(\n            get_function=self.get_items_of_delivery_note_per_page,\n            resource=DELIVERY_NOTE_ITEMS,\n            **{'delivery_note_id': delivery_note_id}\n        )",
    "docstring": "Get all items of delivery note\n        This will iterate over all pages until it gets all elements.\n        So if the rate limit exceeded it will throw an Exception and you will get nothing\n\n        :param delivery_note_id: the delivery note id\n        :return: list"
  },
  {
    "code": "def one_to_many(df, unitcol, manycol):\n    subset = df[[manycol, unitcol]].drop_duplicates()\n    for many in subset[manycol].unique():\n        if subset[subset[manycol] == many].shape[0] > 1:\n            msg = \"{} in {} has multiple values for {}\".format(many, manycol, unitcol)\n            raise AssertionError(msg)\n    return df",
    "docstring": "Assert that a many-to-one relationship is preserved between two\n    columns. For example, a retail store will have have distinct\n    departments, each with several employees. If each employee may\n    only work in a single department, then the relationship of the\n    department to the employees is one to many.\n\n    Parameters\n    ==========\n    df : DataFrame\n    unitcol : str\n        The column that encapulates the groups in ``manycol``.\n    manycol : str\n        The column that must remain unique in the distict pairs\n        between ``manycol`` and ``unitcol``\n\n    Returns\n    =======\n    df : DataFrame"
  },
  {
    "code": "def render_generator(self, context, result):\n\t\tcontext.response.encoding = 'utf8'\n\t\tcontext.response.app_iter = (\n\t\t\t\t(i.encode('utf8') if isinstance(i, unicode) else i)\n\t\t\t\tfor i in result if i is not None\n\t\t\t)\n\t\treturn True",
    "docstring": "Attempt to serve generator responses through stream encoding.\n\t\t\n\t\tThis allows for direct use of cinje template functions, which are generators, as returned views."
  },
  {
    "code": "def debug(self):\n        try:\n            __import__('ipdb').post_mortem(self.traceback)\n        except ImportError:\n            __import__('pdb').post_mortem(self.traceback)",
    "docstring": "Launch a postmortem debug shell at the site of the error."
  },
  {
    "code": "def get_sla_template_path(service_type=ServiceTypes.ASSET_ACCESS):\n    if service_type == ServiceTypes.ASSET_ACCESS:\n        name = 'access_sla_template.json'\n    elif service_type == ServiceTypes.CLOUD_COMPUTE:\n        name = 'compute_sla_template.json'\n    elif service_type == ServiceTypes.FITCHAIN_COMPUTE:\n        name = 'fitchain_sla_template.json'\n    else:\n        raise ValueError(f'Invalid/unsupported service agreement type {service_type}')\n    return os.path.join(os.path.sep, *os.path.realpath(__file__).split(os.path.sep)[1:-1], name)",
    "docstring": "Get the template for a ServiceType.\n\n    :param service_type: ServiceTypes\n    :return: Path of the template, str"
  },
  {
    "code": "def convert(name):\n    s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n    return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()",
    "docstring": "Convert CamelCase to underscore\n\n    Parameters\n    ----------\n    name : str\n        Camelcase string\n\n    Returns\n    -------\n    name : str\n        Converted name"
  },
  {
    "code": "def get_task(self, id, client=None):\n        client = self._require_client(client)\n        task = Task(taskqueue=self, id=id)\n        try:\n            response = client.connection.api_request(method='GET', path=task.path, _target_object=task)\n            task._set_properties(response)\n            return task\n        except NotFound:\n            return None",
    "docstring": "Gets a named task from taskqueue\n\n        If the task isn't found (backend 404), raises a\n        :class:`gcloud.exceptions.NotFound`.\n        :type id: string\n        :param id: A task name to get\n\n        :type client: :class:`gcloud.taskqueue.client.Client` or ``NoneType``\n        :param client: Optional. The client to use.  If not passed, falls back\n                       to the ``client`` stored on the current taskqueue.\n\n        :rtype: :class:`_Task`.\n        :returns: a task\n        :raises: :class:`gcloud.exceptions.NotFound`"
  },
  {
    "code": "def _parse_hparams(hparams):\n  prefixes = [\"agent_\", \"optimizer_\", \"runner_\", \"replay_buffer_\"]\n  ret = []\n  for prefix in prefixes:\n    ret_dict = {}\n    for key in hparams.values():\n      if prefix in key:\n        par_name = key[len(prefix):]\n        ret_dict[par_name] = hparams.get(key)\n    ret.append(ret_dict)\n  return ret",
    "docstring": "Split hparams, based on key prefixes.\n\n  Args:\n    hparams: hyperparameters\n\n  Returns:\n    Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer."
  },
  {
    "code": "def opt_strip(prefix, opts):\n    ret = {}\n    for opt_name, opt_value in opts.items():\n        if opt_name.startswith(prefix):\n            opt_name = opt_name[len(prefix):]\n        ret[opt_name] = opt_value\n    return ret",
    "docstring": "Given a dict of opts that start with prefix,\n    remove the prefix from each of them."
  },
  {
    "code": "def get_settings(self, link):\n        return reverse(\n            'servicesettings-detail', kwargs={'uuid': link.service.settings.uuid}, request=self.context['request'])",
    "docstring": "URL of service settings"
  },
  {
    "code": "def get_pubmed_record(pmid):\n        handle = Entrez.esummary(db=\"pubmed\", id=pmid)\n        record = Entrez.read(handle)\n        return record",
    "docstring": "Get PubMed record from PubMed ID."
  },
  {
    "code": "def prep(config=None, path=None):\n    if config is None:\n        config = parse()\n    if path is None:\n        path = os.getcwd()\n    root = config.get('root', 'path')\n    root = os.path.join(path, root)\n    root = os.path.realpath(root)\n    os.environ['SCIDASH_HOME'] = root\n    if sys.path[0] != root:\n        sys.path.insert(0, root)",
    "docstring": "Prepare to read the configuration information."
  },
  {
    "code": "def link_property(prop, cls_object):\n    register = False\n    cls_name = cls_object.__name__\n    if cls_name and cls_name != 'RdfBaseClass':\n        new_name = \"%s_%s\" % (prop._prop_name, cls_name)\n    else:\n        new_name = prop._prop_name\n    new_prop = types.new_class(new_name,\n                               (prop,),\n                               {'metaclass': RdfLinkedPropertyMeta,\n                                'cls_name': cls_name,\n                                'prop_name': prop._prop_name,\n                                'linked_cls': cls_object})\n    return new_prop",
    "docstring": "Generates a property class linked to the rdfclass\n\n    args:\n        prop: unlinked property class\n        cls_name: the name of the rdf_class with which the property is\n                  associated\n        cls_object: the rdf_class"
  },
  {
    "code": "def __hammingDistance(s1, s2):\n        l1 = len(s1)\n        l2 = len(s2)\n        if l1 != l2:\n            raise ValueError(\"Hamming distance requires strings of same size.\")\n        return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))",
    "docstring": "Finds the Hamming distance between two strings.\n\n        @param s1: string\n        @param s2: string\n        @return: the distance\n        @raise ValueError: if the lenght of the strings differ"
  },
  {
    "code": "def records(self):\n        compounds = ModelList()\n        seen_labels = set()\n        tagged_tokens = [(CONTROL_RE.sub('', token), tag) for token, tag in self.tagged_tokens]\n        for parser in self.parsers:\n            for record in parser.parse(tagged_tokens):\n                p = record.serialize()\n                if not p:\n                    continue\n                if record in compounds:\n                    continue\n                if all(k in {'labels', 'roles'} for k in p.keys()) and set(record.labels).issubset(seen_labels):\n                    continue\n                seen_labels.update(record.labels)\n                compounds.append(record)\n        return compounds",
    "docstring": "Return a list of records for this sentence."
  },
  {
    "code": "def dim(self, dim):\n        contrast = 0\n        if not dim:\n            if self._vccstate == SSD1306_EXTERNALVCC:\n                contrast = 0x9F\n            else:\n                contrast = 0xCF",
    "docstring": "Adjusts contrast to dim the display if dim is True, otherwise sets the\n        contrast to normal brightness if dim is False."
  },
  {
    "code": "def components(self):\n        with self._mutex:\n            if not self._components:\n                self._components = [c for c in self.children if c.is_component]\n        return self._components",
    "docstring": "The list of components in this manager, if any.\n\n        This information can also be found by listing the children of this node\n        that are of type @ref Component. That method is more useful as it returns\n        the tree entries for the components."
  },
  {
    "code": "def extend_request_args(self, args, item_cls, item_type, key,\n                            parameters, orig=False):\n        try:\n            item = self.get_item(item_cls, item_type, key)\n        except KeyError:\n            pass\n        else:\n            for parameter in parameters:\n                if orig:\n                    try:\n                        args[parameter] = item[parameter]\n                    except KeyError:\n                        pass\n                else:\n                    try:\n                        args[parameter] = item[verified_claim_name(parameter)]\n                    except KeyError:\n                        try:\n                            args[parameter] = item[parameter]\n                        except KeyError:\n                            pass\n        return args",
    "docstring": "Add a set of parameters and their value to a set of request arguments.\n\n        :param args: A dictionary\n        :param item_cls: The :py:class:`oidcmsg.message.Message` subclass\n            that describes the item\n        :param item_type: The type of item, this is one of the parameter\n            names in the :py:class:`oidcservice.state_interface.State` class.\n        :param key: The key to the information in the database\n        :param parameters: A list of parameters who's values this method\n            will return.\n        :param orig: Where the value of a claim is a signed JWT return\n            that.\n        :return: A dictionary with keys from the list of parameters and\n            values being the values of those parameters in the item.\n            If the parameter does not a appear in the item it will not appear\n            in the returned dictionary."
  },
  {
    "code": "def ip2long(ip):\n    if not validate_ip(ip):\n        return None\n    quads = ip.split('.')\n    if len(quads) == 1:\n        quads = quads + [0, 0, 0]\n    elif len(quads) < 4:\n        host = quads[-1:]\n        quads = quads[:-1] + [0, ] * (4 - len(quads)) + host\n    lngip = 0\n    for q in quads:\n        lngip = (lngip << 8) | int(q)\n    return lngip",
    "docstring": "Convert a dotted-quad ip address to a network byte order 32-bit\n    integer.\n\n\n    >>> ip2long('127.0.0.1')\n    2130706433\n    >>> ip2long('127.1')\n    2130706433\n    >>> ip2long('127')\n    2130706432\n    >>> ip2long('127.0.0.256') is None\n    True\n\n\n    :param ip: Dotted-quad ip address (eg. '127.0.0.1').\n    :type ip: str\n    :returns: Network byte order 32-bit integer or ``None`` if ip is invalid."
  },
  {
    "code": "def build_index(self, idx_name, _type='default'):\n        \"Build the index related to the `name`.\"\n        indexes = {}\n        has_non_string_values = False\n        for key, item in self.data.items():\n            if idx_name in item:\n                value = item[idx_name]\n                if not isinstance(value, six.string_types):\n                    has_non_string_values = True\n                if value not in indexes:\n                    indexes[value] = set([])\n                indexes[value].add(key)\n        self.indexes[idx_name] = indexes\n        if self._meta.lazy_indexes or has_non_string_values:\n            _type = 'lazy'\n        self.index_defs[idx_name] = {'type': _type}",
    "docstring": "Build the index related to the `name`."
  },
  {
    "code": "def __continue_session(self):\n        now = time.time()\n        diff = abs(now - self.last_request_time)\n        timeout_sec = self.session_timeout * 60\n        if diff >= timeout_sec:\n            self.__log('Session timed out, attempting to authenticate')\n            self.authenticate()",
    "docstring": "Check if the time since the last HTTP request is under the\n        session timeout limit. If it's been too long since the last request\n        attempt to authenticate again."
  },
  {
    "code": "def update(self, sequence):\n        item_index = None\n        try:\n            for item in sequence:\n                item_index = self.add(item)\n        except TypeError:\n            raise ValueError(\n                \"Argument needs to be an iterable, got %s\" % type(sequence)\n            )\n        return item_index",
    "docstring": "Update the set with the given iterable sequence, then return the index\n        of the last element inserted.\n\n        Example:\n            >>> oset = OrderedSet([1, 2, 3])\n            >>> oset.update([3, 1, 5, 1, 4])\n            4\n            >>> print(oset)\n            OrderedSet([1, 2, 3, 5, 4])"
  },
  {
    "code": "def verify_calling_thread(self, should_be_emulation, message=None):\n        if should_be_emulation == self._on_emulation_thread():\n            return\n        if message is None:\n            message = \"Operation performed on invalid thread\"\n        raise InternalError(message)",
    "docstring": "Verify if the calling thread is or is not the emulation thread.\n\n        This method can be called to make sure that an action is being taken\n        in the appropriate context such as not blocking the event loop thread\n        or modifying an emulate state outside of the event loop thread.\n\n        If the verification fails an InternalError exception is raised,\n        allowing this method to be used to protect other methods from being\n        called in a context that could deadlock or cause race conditions.\n\n        Args:\n            should_be_emulation (bool): True if this call should be taking place\n                on the emulation, thread, False if it must not take place on\n                the emulation thread.\n            message (str): Optional message to include when raising the exception.\n                Otherwise a generic message is used.\n\n        Raises:\n            InternalError: When called from the wrong thread."
  },
  {
    "code": "def _add_months(self, date, months):\n        year = date.year + (date.month + months - 1) // 12\n        month = (date.month + months - 1) % 12 + 1\n        return datetime.date(year=year, month=month, day=1)",
    "docstring": "Add ``months`` months to ``date``.\n\n        Unfortunately we can't use timedeltas to add months because timedelta counts in days\n        and there's no foolproof way to add N months in days without counting the number of\n        days per month."
  },
  {
    "code": "def _build_raw_headers(self, headers: Dict) -> Tuple:\n        raw_headers = []\n        for k, v in headers.items():\n            raw_headers.append((k.encode('utf8'), v.encode('utf8')))\n        return tuple(raw_headers)",
    "docstring": "Convert a dict of headers to a tuple of tuples\n\n        Mimics the format of ClientResponse."
  },
  {
    "code": "def register(self, obj):\n        for method in dir(obj):\n            if not method.startswith('_'):\n                fct = getattr(obj, method)\n                try:\n                    getattr(fct, '__call__')\n                except AttributeError:\n                    pass\n                else:\n                    logging.debug('JSONRPC: Found Method: \"%s\"' % method)\n                    self._methods[method] = {\n                        'argspec': inspect.getargspec(fct),\n                        'fct': fct\n                    }",
    "docstring": "register all methods for of an object as json rpc methods\n\n        obj - object with methods"
  },
  {
    "code": "def service_reload(service_name, restart_on_failure=False, **kwargs):\n    service_result = service('reload', service_name, **kwargs)\n    if not service_result and restart_on_failure:\n        service_result = service('restart', service_name, **kwargs)\n    return service_result",
    "docstring": "Reload a system service, optionally falling back to restart if\n    reload fails.\n\n    The specified service name is managed via the system level init system.\n    Some init systems (e.g. upstart) require that additional arguments be\n    provided in order to directly control service instances whereas other init\n    systems allow for addressing instances of a service directly by name (e.g.\n    systemd).\n\n    The kwargs allow for the additional parameters to be passed to underlying\n    init systems for those systems which require/allow for them. For example,\n    the ceph-osd upstart script requires the id parameter to be passed along\n    in order to identify which running daemon should be reloaded. The follow-\n    ing example restarts the ceph-osd service for instance id=4:\n\n    service_reload('ceph-osd', id=4)\n\n    :param service_name: the name of the service to reload\n    :param restart_on_failure: boolean indicating whether to fallback to a\n                               restart if the reload fails.\n    :param **kwargs: additional parameters to pass to the init system when\n                     managing services. These will be passed as key=value\n                     parameters to the  init system's commandline. kwargs\n                     are ignored for init systems not allowing additional\n                     parameters via the commandline (systemd)."
  },
  {
    "code": "def get_min_sec_from_morning(self):\n        mins = []\n        for timerange in self.timeranges:\n            mins.append(timerange.get_sec_from_morning())\n        return min(mins)",
    "docstring": "Get the first second from midnight where a timerange is effective\n\n        :return: smallest amount of second from midnight of all timerange\n        :rtype: int"
  },
  {
    "code": "def pwm_max_score(self):\n        if self.max_score is None:\n            score = 0\n            for row in self.pwm:\n                score += log(max(row) / 0.25 + 0.01)\n            self.max_score = score\n        return self.max_score",
    "docstring": "Return the maximum PWM score.\n\n        Returns\n        -------\n        score : float\n            Maximum PWM score."
  },
  {
    "code": "def get_area_def(self, dsid):\n        msg = self._get_message(self._msg_datasets[dsid])\n        try:\n            return self._area_def_from_msg(msg)\n        except (RuntimeError, KeyError):\n            raise RuntimeError(\"Unknown GRIB projection information\")",
    "docstring": "Get area definition for message.\n\n        If latlong grid then convert to valid eqc grid."
  },
  {
    "code": "def Overlay(child, parent):\n  for arg in child, parent:\n    if not isinstance(arg, collections.Mapping):\n      raise DefinitionError(\"Trying to merge badly defined hints. Child: %s, \"\n                            \"Parent: %s\" % (type(child), type(parent)))\n  for attr in [\"fix\", \"format\", \"problem\", \"summary\"]:\n    if not child.get(attr):\n      child[attr] = parent.get(attr, \"\").strip()\n  return child",
    "docstring": "Adds hint attributes to a child hint if they are not defined."
  },
  {
    "code": "def sort_by(self, fieldName, reverse=False):\n        return self.__class__(\n            sorted(self, key = lambda item : self._get_item_value(item, fieldName), reverse=reverse)\n        )",
    "docstring": "sort_by - Return a copy of this collection, sorted by the given fieldName.\n\n              The fieldName is accessed the same way as other filtering, so it supports custom properties, etc.\n\n              @param fieldName <str> - The name of the field on which to sort by\n\n              @param reverse <bool> Default False - If True, list will be in reverse order.\n\n              @return <QueryableList> - A QueryableList of the same type with the elements sorted based on arguments."
  },
  {
    "code": "def _build_calmar_data(self):\n        assert self.initial_weight_name is not None\n        data = pd.DataFrame()\n        data[self.initial_weight_name] = self.initial_weight * self.filter_by\n        for variable in self.margins_by_variable:\n            if variable == 'total_population':\n                continue\n            assert variable in self.survey_scenario.tax_benefit_system.variables\n            period = self.period\n            data[variable] = self.survey_scenario.calculate_variable(variable = variable, period = period)\n        return data",
    "docstring": "Builds the data dictionnary used as calmar input argument"
  },
  {
    "code": "def write(self, data):\n        data_off = 0\n        while data_off < len(data):\n            left = len(self._buf) - self._pos\n            if left <= 0:\n                self._write_packet(final=False)\n            else:\n                to_write = min(left, len(data) - data_off)\n                self._buf[self._pos:self._pos + to_write] = data[data_off:data_off + to_write]\n                self._pos += to_write\n                data_off += to_write",
    "docstring": "Writes given bytes buffer into the stream\n\n        Function returns only when entire buffer is written"
  },
  {
    "code": "def validate_protocol(protocol):\n    if not re.match(PROTOCOL_REGEX, protocol):\n        raise ValueError(f'invalid protocol: {protocol}')\n    return protocol.lower()",
    "docstring": "Validate a protocol, a string, and return it."
  },
  {
    "code": "def export_node(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix=\"\", condition=\"\", who=\"\",\n                    add_join=False):\n        node_type = node[1][consts.Consts.type]\n        if node_type == consts.Consts.start_event:\n            return BpmnDiagramGraphCsvExport.export_start_event(bpmn_graph, export_elements, node, nodes_classification,\n                                                                order=order, prefix=prefix, condition=condition,\n                                                                who=who)\n        elif node_type == consts.Consts.end_event:\n            return BpmnDiagramGraphCsvExport.export_end_event(export_elements, node, order=order, prefix=prefix,\n                                                              condition=condition, who=who)\n        else:\n            return BpmnDiagramGraphCsvExport.export_element(bpmn_graph, export_elements, node, nodes_classification,\n                                                            order=order, prefix=prefix, condition=condition, who=who,\n                                                            add_join=add_join)",
    "docstring": "General method for node exporting\n\n        :param bpmn_graph: an instance of BpmnDiagramGraph class,\n        :param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that\n               will be used in exported CSV document,\n        :param node: networkx.Node object,\n        :param nodes_classification: dictionary of classification labels. Key - node id. Value - a list of labels,\n        :param order: the order param of exported node,\n        :param prefix: the prefix of exported node - if the task appears after some gateway, the prefix will identify\n               the branch\n        :param condition: the condition param of exported node,\n        :param who: the condition param of exported node,\n        :param add_join: boolean flag. Used to indicate if \"Join\" element should be added to CSV.\n        :return: None or the next node object if the exported node was a gateway join."
  },
  {
    "code": "def _trim_buffer_garbage(rawmessage, debug=True):\n    while rawmessage and rawmessage[0] != MESSAGE_START_CODE_0X02:\n        if debug:\n            _LOGGER.debug('Buffer content: %s', binascii.hexlify(rawmessage))\n            _LOGGER.debug('Trimming leading buffer garbage')\n        rawmessage = rawmessage[1:]\n    return rawmessage",
    "docstring": "Remove leading bytes from a byte stream.\n\n    A proper message byte stream begins with 0x02."
  },
  {
    "code": "def state(self, state):\n        logger.debug('client changing to state=%s', ClientState.Names[state])\n        self._state = state",
    "docstring": "Change the state of the client. This is one of the values\n        defined in ClientStates."
  },
  {
    "code": "def _record_first_run():\n    info = {'pid': _get_shell_pid(),\n            'time': time.time()}\n    mode = 'wb' if six.PY2 else 'w'\n    with _get_not_configured_usage_tracker_path().open(mode) as tracker:\n        json.dump(info, tracker)",
    "docstring": "Records shell pid to tracker file."
  },
  {
    "code": "def strain_in_plane(self, **kwargs):\n        if self._strain_out_of_plane is not None:\n            return ((self._strain_out_of_plane / -2.) *\n                    (self.unstrained.c11(**kwargs) /\n                     self.unstrained.c12(**kwargs)  )  )\n        else:\n            return 1 - self.unstrained.a(**kwargs) / self.substrate.a(**kwargs)",
    "docstring": "Returns the in-plane strain assuming no lattice relaxation, which\n        is positive for tensile strain and negative for compressive strain."
  },
  {
    "code": "def packet_in_handler(self, evt):\n        msg = evt.msg\n        dpid = msg.datapath.id\n        req_pkt = packet.Packet(msg.data)\n        req_igmp = req_pkt.get_protocol(igmp.igmp)\n        if req_igmp:\n            if self._querier.dpid == dpid:\n                self._querier.packet_in_handler(req_igmp, msg)\n            else:\n                self._snooper.packet_in_handler(req_pkt, req_igmp, msg)\n        else:\n            self.send_event_to_observers(EventPacketIn(msg))",
    "docstring": "PacketIn event handler. when the received packet was IGMP,\n        proceed it. otherwise, send a event."
  },
  {
    "code": "def xack(self, stream, group_name, id, *ids):\n        return self.execute(b'XACK', stream, group_name, id, *ids)",
    "docstring": "Acknowledge a message for a given consumer group"
  },
  {
    "code": "def asset_asset_swap(\n            self, asset1_id, asset1_transfer_spec, asset2_id, asset2_transfer_spec, fees):\n        btc_transfer_spec = TransferParameters(\n            asset1_transfer_spec.unspent_outputs, asset1_transfer_spec.to_script, asset1_transfer_spec.change_script, 0)\n        return self.transfer(\n            [(asset1_id, asset1_transfer_spec), (asset2_id, asset2_transfer_spec)], btc_transfer_spec, fees)",
    "docstring": "Creates a transaction for swapping an asset for another asset.\n\n        :param bytes asset1_id: The ID of the first asset.\n        :param TransferParameters asset1_transfer_spec: The parameters of the first asset being transferred.\n            It is also used for paying fees and/or receiving change if any.\n        :param bytes asset2_id: The ID of the second asset.\n        :param TransferDetails asset2_transfer_spec: The parameters of the second asset being transferred.\n        :param int fees: The fees to include in the transaction.\n        :return: The resulting unsigned transaction.\n        :rtype: CTransaction"
  },
  {
    "code": "def resolve(self, space_id=None, environment_id=None):\n        proxy_method = getattr(\n            self._client,\n            base_path_for(self.link_type)\n        )\n        if self.link_type == 'Space':\n            return proxy_method().find(self.id)\n        elif environment_id is not None:\n            return proxy_method(space_id, environment_id).find(self.id)\n        else:\n            return proxy_method(space_id).find(self.id)",
    "docstring": "Resolves link to a specific resource."
  },
  {
    "code": "def start(st_reg_number):\n    weights = [9, 8, 7, 6, 5, 4, 3, 2]\n    digit_state_registration = st_reg_number[-1]\n    if len(st_reg_number) != 9:\n        return False\n    sum_total = 0\n    for i in range(0, 8):\n        sum_total = sum_total + weights[i] * int(st_reg_number[i])\n    if sum_total % 11 == 0:\n        return digit_state_registration[-1] == '0'\n    digit_check = 11 - sum_total % 11\n    return str(digit_check) == digit_state_registration",
    "docstring": "Checks the number valiaty for the Paraiba state"
  },
  {
    "code": "def mul_table(self, other):\n        other = coerceBigInt(other)\n        if not other:\n            return NotImplemented\n        other %= orderG2()\n        if not self._table:\n            self._table = lwnafTable()\n            librelic.ep2_mul_pre_lwnaf(byref(self._table), byref(self))\n        result = G2Element()\n        librelic.ep2_mul_fix_lwnaf(byref(result), byref(self._table), \n            byref(other))\n        return result",
    "docstring": "Fast multiplication using a the LWNAF precomputation table."
  },
  {
    "code": "def __get_node_by_name(self, name):\n        try:\n            for entry in filter(lambda x: x.name == name, self.nodes()):\n                return entry\n        except StopIteration:\n            raise ValueError(\"Attempted to retrieve a non-existing tree node with name: {name}\"\n                             \"\".format(name=name))",
    "docstring": "Returns a first TreeNode object, which name matches the specified argument\n\n        :raises: ValueError (if no node with specified name is present in the tree)"
  },
  {
    "code": "def quote_edge(identifier):\n    node, _, rest = identifier.partition(':')\n    parts = [quote(node)]\n    if rest:\n        port, _, compass = rest.partition(':')\n        parts.append(quote(port))\n        if compass:\n            parts.append(compass)\n    return ':'.join(parts)",
    "docstring": "Return DOT edge statement node_id from string, quote if needed.\n\n    >>> quote_edge('spam')\n    'spam'\n\n    >>> quote_edge('spam spam:eggs eggs')\n    '\"spam spam\":\"eggs eggs\"'\n\n    >>> quote_edge('spam:eggs:s')\n    'spam:eggs:s'"
  },
  {
    "code": "def text_search(self, search, *, limit=0, table='assets'):\n        return backend.query.text_search(self.connection, search, limit=limit,\n                                         table=table)",
    "docstring": "Return an iterator of assets that match the text search\n\n        Args:\n            search (str): Text search string to query the text index\n            limit (int, optional): Limit the number of returned documents.\n\n        Returns:\n            iter: An iterator of assets that match the text search."
  },
  {
    "code": "def _bind_length_handlers(tids, user_handler, lns):\n    for tid in tids:\n        for ln in lns:\n            type_octet = _gen_type_octet(tid, ln)\n            ion_type = _TID_VALUE_TYPE_TABLE[tid]\n            if ln == 1 and ion_type is IonType.STRUCT:\n                handler = partial(_ordered_struct_start_handler, partial(user_handler, ion_type))\n            elif ln < _LENGTH_FIELD_FOLLOWS:\n                handler = partial(user_handler, ion_type, ln)\n            else:\n                handler = partial(_var_uint_field_handler, partial(user_handler, ion_type))\n            _HANDLER_DISPATCH_TABLE[type_octet] = handler",
    "docstring": "Binds a set of handlers with the given factory.\n\n    Args:\n        tids (Sequence[int]): The Type IDs to bind to.\n        user_handler (Callable): A function that takes as its parameters\n            :class:`IonType`, ``length``, and the ``ctx`` context\n            returning a co-routine.\n        lns (Sequence[int]): The low-nibble lengths to bind to."
  },
  {
    "code": "def main():\n    parser = argparse.ArgumentParser(\n        description='Relocate a virtual environment.'\n    )\n    parser.add_argument(\n        '--source',\n        help='The existing virtual environment.',\n        required=True,\n    )\n    parser.add_argument(\n        '--destination',\n        help='The location for which to configure the virtual environment.',\n        required=True,\n    )\n    parser.add_argument(\n        '--move',\n        help='Move the virtual environment to the destination.',\n        default=False,\n        action='store_true',\n    )\n    args = parser.parse_args()\n    relocate(args.source, args.destination, args.move)",
    "docstring": "Relocate a virtual environment."
  },
  {
    "code": "def resized(self, dl, targ, new_path, resume = True, fn=None):\n        return dl.dataset.resize_imgs(targ, new_path, resume=resume, fn=fn) if dl else None",
    "docstring": "Return a copy of this dataset resized"
  },
  {
    "code": "def run_config_diagnostics(config_path=CONFIG_PATH):\n    config = read_config(config_path)\n    missing_sections = set()\n    malformed_entries = defaultdict(set)\n    for section, expected_section_keys in SECTION_KEYS.items():\n        section_content = config.get(section)\n        if not section_content:\n            missing_sections.add(section)\n        else:\n            for option in expected_section_keys:\n                option_value = section_content.get(option)\n                if not option_value:\n                    malformed_entries[section].add(option)\n    return config_path, missing_sections, malformed_entries",
    "docstring": "Run diagnostics on the configuration file.\n\n    Args:\n        config_path (str): Path to the configuration file.\n    Returns:\n        str, Set[str], dict(str, Set[str]): The path to the configuration file, a set of missing\n        sections and a dict that maps each section to the entries that have either missing or empty\n        options."
  },
  {
    "code": "def _HasExpectedLineLength(self, file_object):\n    original_file_position = file_object.tell()\n    line_reader = self._CreateLineReader(file_object)\n    for _ in range(0, 20):\n      sample_line = line_reader.readline(self._maximum_line_length + 1)\n      if len(sample_line) > self._maximum_line_length:\n        file_object.seek(original_file_position)\n        return False\n    file_object.seek(original_file_position)\n    return True",
    "docstring": "Determines if a file begins with lines of the expected length.\n\n    As we know the maximum length of valid lines in the DSV file, the presence\n    of lines longer than this indicates that the file will not be parsed\n    successfully, without reading excessive data from a large file.\n\n    Args:\n      file_object (dfvfs.FileIO): file-like object.\n\n    Returns:\n      bool: True if the file has lines of the expected length."
  },
  {
    "code": "def load(stream=None):\n    if stream:\n        loads(stream.read())\n    else:\n        data = pkgutil.get_data(insights.__name__, _filename)\n        return loads(data) if data else None",
    "docstring": "Loads filters from a stream, normally an open file. If one is\n    not passed, filters are loaded from a default location within\n    the project."
  },
  {
    "code": "def open_in_browser(file_location):\n    if not os.path.isfile(file_location):\n        file_location = os.path.join(os.getcwd(), file_location)\n    if not os.path.isfile(file_location):\n        raise IOError(\"\\n\\nFile not found.\")\n    if sys.platform == \"darwin\":\n        file_location = \"file:///\"+file_location\n    new = 2\n    webbrowser.get().open(file_location, new=new)",
    "docstring": "Attempt to open file located at file_location in the default web\n    browser."
  },
  {
    "code": "def make_auth_headers(self, content_type):\n        headers = self.make_headers(content_type)\n        headers['Authorization'] = 'Basic {}'.format(self.get_auth_string())\n        return headers",
    "docstring": "Add authorization header."
  },
  {
    "code": "def _syllabifyPhones(phoneList, syllableList):\n    numPhoneList = [len(syllable) for syllable in syllableList]\n    start = 0\n    syllabifiedList = []\n    for end in numPhoneList:\n        syllable = phoneList[start:start + end]\n        syllabifiedList.append(syllable)\n        start += end\n    return syllabifiedList",
    "docstring": "Given a phone list and a syllable list, syllabify the phones\n    \n    Typically used by findBestSyllabification which first aligns the phoneList\n    with a dictionary phoneList and then uses the dictionary syllabification\n    to syllabify the input phoneList."
  },
  {
    "code": "def get_sortobj(self, goea_results, **kws):\n        nts_goea = MgrNtGOEAs(goea_results).get_goea_nts_prt(**kws)\n        goids = set(nt.GO for nt in nts_goea)\n        go2nt = {nt.GO:nt for nt in nts_goea}\n        grprobj = Grouper(\"GOEA\", goids, self.hdrobj, self.grprdflt.gosubdag, go2nt=go2nt)\n        grprobj.prt_summary(sys.stdout)\n        sortobj = Sorter(grprobj, section_sortby=lambda nt: getattr(nt, self.pval_fld))\n        return sortobj",
    "docstring": "Return a Grouper object, given a list of GOEnrichmentRecord."
  },
  {
    "code": "def config_(name: str, local: bool, package: str, section: str,\n            key: Optional[str]):\n    cfg = config.read_configs(package, name, local=local)\n    if key:\n        with suppress(NoOptionError, NoSectionError):\n            echo(cfg.get(section, key))\n    else:\n        with suppress(NoSectionError):\n            for opt in cfg.options(section):\n                colourise.pinfo(opt)\n                echo('    {}'.format(cfg.get(section, opt)))",
    "docstring": "Extract or list values from config."
  },
  {
    "code": "def migrate_config_file(\n        self,\n        config_file_path,\n        always_update=False,\n        current_file_type=None,\n        output_file_name=None,\n        output_file_type=None,\n        create=True,\n        update_defaults=True,\n        dump_kwargs=None,\n        include_bootstrap=True,\n    ):\n        current_file_type = current_file_type or self._file_type\n        output_file_type = output_file_type or self._file_type\n        output_file_name = output_file_name or config_file_path\n        current_config = self._get_config_if_exists(config_file_path,\n                                                    create,\n                                                    current_file_type)\n        migrated_config = {}\n        if include_bootstrap:\n            items = self._yapconf_items.values()\n        else:\n            items = [\n                item for item in self._yapconf_items.values()\n                if not item.bootstrap\n            ]\n        for item in items:\n            item.migrate_config(current_config, migrated_config,\n                                always_update, update_defaults)\n        if create:\n            yapconf.dump_data(migrated_config,\n                              filename=output_file_name,\n                              file_type=output_file_type,\n                              klazz=YapconfLoadError,\n                              dump_kwargs=dump_kwargs)\n        return Box(migrated_config)",
    "docstring": "Migrates a configuration file.\n\n        This is used to help you update your configurations throughout the\n        lifetime of your application. It is probably best explained through\n        example.\n\n        Examples:\n            Assume we have a JSON config file ('/path/to/config.json')\n            like the following:\n            ``{\"db_name\": \"test_db_name\", \"db_host\": \"1.2.3.4\"}``\n\n            >>> spec = YapconfSpec({\n            ...    'db_name': {\n            ...        'type': 'str',\n            ...        'default': 'new_default',\n            ...        'previous_defaults': ['test_db_name']\n            ...    },\n            ...    'db_host': {\n            ...        'type': 'str',\n            ...        'previous_defaults': ['localhost']\n            ...    }\n            ... })\n\n            We can migrate that file quite easily with the spec object:\n\n            >>> spec.migrate_config_file('/path/to/config.json')\n\n            Will result in /path/to/config.json being overwritten:\n            ``{\"db_name\": \"new_default\", \"db_host\": \"1.2.3.4\"}``\n\n        Args:\n            config_file_path (str): The path to your current config\n            always_update (bool): Always update values (even to None)\n            current_file_type (str): Defaults to self._file_type\n            output_file_name (str): Defaults to the current_file_path\n            output_file_type (str): Defaults to self._file_type\n            create (bool): Create the file if it doesn't exist (otherwise\n                error if the file does not exist).\n            update_defaults (bool): Update values that have a value set to\n                something listed in the previous_defaults\n            dump_kwargs (dict): A key-value pair that will be passed to dump\n            include_bootstrap (bool): Include bootstrap items in the output\n\n        Returns:\n            box.Box: The newly migrated configuration."
  },
  {
    "code": "def _gerrit_user_to_author(props, username=\"unknown\"):\n    username = props.get(\"username\", username)\n    username = props.get(\"name\", username)\n    if \"email\" in props:\n        username += \" <%(email)s>\" % props\n    return username",
    "docstring": "Convert Gerrit account properties to Buildbot format\n\n    Take into account missing values"
  },
  {
    "code": "def update(self, title, key):\n        json = None\n        if title and key:\n            data = {'title': title, 'key': key}\n            json = self._json(self._patch(self._api, data=dumps(data)), 200)\n        if json:\n            self._update_(json)\n            return True\n        return False",
    "docstring": "Update this key.\n\n        :param str title: (required), title of the key\n        :param str key: (required), text of the key file\n        :returns: bool"
  },
  {
    "code": "def remove_path(path):\n    if path is None or not os.path.exists(path):\n        return\n    if platform.system() == 'Windows':\n        os.chmod(path, stat.S_IWRITE)\n    try:\n        if os.path.isdir(path):\n            shutil.rmtree(path)\n        elif os.path.isfile(path):\n            shutil.os.remove(path)\n    except OSError:\n        logger.exception(\"Could not remove path: %s\" % path)",
    "docstring": "remove path from file system\n    If path is None - do nothing"
  },
  {
    "code": "def get_all_available_leaves(self, language=None, forbidden_item_ids=None):\n        return self.get_all_leaves(language=language, forbidden_item_ids=forbidden_item_ids)",
    "docstring": "Get all available leaves."
  },
  {
    "code": "def _sanitize_usecols(usecols):\n    if usecols is None:\n        return None\n    try:\n        pats = usecols.split(',')\n        pats = [p.strip() for p in pats if p]\n    except AttributeError:\n        usecols = [int(c) for c in usecols]\n        usecols.sort()\n        return tuple(usecols)\n    cols = []\n    for pat in pats:\n        if ':' in pat:\n            c1, c2 = pat.split(':')\n            n1 = letter2num(c1, zbase=True)\n            n2 = letter2num(c2, zbase=False)\n            cols += range(n1, n2)\n        else:\n            cols += [letter2num(pat, zbase=True)]\n    cols = list(set(cols))\n    cols.sort()\n    return tuple(cols)",
    "docstring": "Make a tuple of sorted integers and return it. Return None if\n    usecols is None"
  },
  {
    "code": "def and_evaluator(conditions, leaf_evaluator):\n  saw_null_result = False\n  for condition in conditions:\n    result = evaluate(condition, leaf_evaluator)\n    if result is False:\n      return False\n    if result is None:\n      saw_null_result = True\n  return None if saw_null_result else True",
    "docstring": "Evaluates a list of conditions as if the evaluator had been applied\n  to each entry and the results AND-ed together.\n\n  Args:\n    conditions: List of conditions ex: [operand_1, operand_2].\n    leaf_evaluator: Function which will be called to evaluate leaf condition values.\n\n  Returns:\n    Boolean:\n      - True if all operands evaluate to True.\n      - False if a single operand evaluates to False.\n    None: if conditions couldn't be evaluated."
  },
  {
    "code": "def update_machine_state(state_path):\n    charmhelpers.contrib.templating.contexts.juju_state_to_yaml(\n        salt_grains_path)\n    subprocess.check_call([\n        'salt-call',\n        '--local',\n        'state.template',\n        state_path,\n    ])",
    "docstring": "Update the machine state using the provided state declaration."
  },
  {
    "code": "def create_new_account(data_dir, password, **geth_kwargs):\n    if os.path.exists(password):\n        geth_kwargs['password'] = password\n    command, proc = spawn_geth(dict(\n        data_dir=data_dir,\n        suffix_args=['account', 'new'],\n        **geth_kwargs\n    ))\n    if os.path.exists(password):\n        stdoutdata, stderrdata = proc.communicate()\n    else:\n        stdoutdata, stderrdata = proc.communicate(b\"\\n\".join((password, password)))\n    if proc.returncode:\n        raise ValueError(format_error_message(\n            \"Error trying to create a new account\",\n            command,\n            proc.returncode,\n            stdoutdata,\n            stderrdata,\n        ))\n    match = account_regex.search(stdoutdata)\n    if not match:\n        raise ValueError(format_error_message(\n            \"Did not find an address in process output\",\n            command,\n            proc.returncode,\n            stdoutdata,\n            stderrdata,\n        ))\n    return b'0x' + match.groups()[0]",
    "docstring": "Creates a new Ethereum account on geth.\n\n    This is useful for testing when you want to stress\n    interaction (transfers) between Ethereum accounts.\n\n    This command communicates with ``geth`` command over\n    terminal interaction. It creates keystore folder and new\n    account there.\n\n    This function only works against offline geth processes,\n    because geth builds an account cache when starting up.\n    If geth process is already running you can create new\n    accounts using\n    `web3.personal.newAccount()\n    <https://github.com/ethereum/go-ethereum/wiki/JavaScript-Console#personalnewaccount>_`\n    RPC API.\n\n\n    Example py.test fixture for tests:\n\n    .. code-block:: python\n\n        import os\n\n        from geth.wrapper import DEFAULT_PASSWORD_PATH\n        from geth.accounts import create_new_account\n\n\n        @pytest.fixture\n        def target_account() -> str:\n            '''Create a new Ethereum account on a running Geth node.\n\n            The account can be used as a withdrawal target for tests.\n\n            :return: 0x address of the account\n            '''\n\n            # We store keystore files in the current working directory\n            # of the test run\n            data_dir = os.getcwd()\n\n            # Use the default password \"this-is-not-a-secure-password\"\n            # as supplied in geth/default_blockchain_password file.\n            # The supplied password must be bytes, not string,\n            # as we only want ASCII characters and do not want to\n            # deal encoding problems with passwords\n            account = create_new_account(data_dir, DEFAULT_PASSWORD_PATH)\n            return account\n\n    :param data_dir: Geth data fir path - where to keep \"keystore\" folder\n    :param password: Path to a file containing the password\n        for newly created account\n    :param geth_kwargs: Extra command line arguments passwrord to geth\n    :return: Account as 0x prefixed hex string"
  },
  {
    "code": "def _choose_rest_version(self):\n        versions = self._list_available_rest_versions()\n        versions = [LooseVersion(x) for x in versions if x in self.supported_rest_versions]\n        if versions:\n            return max(versions)\n        else:\n            raise PureError(\n                \"Library is incompatible with all REST API versions supported\"\n                \"by the target array.\")",
    "docstring": "Return the newest REST API version supported by target array."
  },
  {
    "code": "def read_partition(self, i):\n        self._load_metadata()\n        if i < 0 or i >= self.npartitions:\n            raise IndexError('%d is out of range' % i)\n        return self._get_partition(i)",
    "docstring": "Return a part of the data corresponding to i-th partition.\n\n        By default, assumes i should be an integer between zero and npartitions;\n        override for more complex indexing schemes."
  },
  {
    "code": "def backward(self, speed=1):\n        self.left_motor.backward(speed)\n        self.right_motor.backward(speed)",
    "docstring": "Drive the robot backward by running both motors backward.\n\n        :param float speed:\n            Speed at which to drive the motors, as a value between 0 (stopped)\n            and 1 (full speed). The default is 1."
  },
  {
    "code": "def stop(self, *args, **kwargs):\n        if self.status in (Status.stopping, Status.stopped):\n            logger.debug(\"{} is already {}\".format(self, self.status.name))\n        else:\n            self.status = Status.stopping\n            self.onStopping(*args, **kwargs)\n            self.status = Status.stopped",
    "docstring": "Set the status to Status.stopping and also call `onStopping`\n        with the provided args and kwargs."
  },
  {
    "code": "def url(self):\n        if self.is_public:\n            return '{0}/{1}/{2}'.format(\n                self.bucket._boto_s3.meta.client.meta.endpoint_url,\n                self.bucket.name,\n                self.name\n            )\n        else:\n            raise ValueError('{0!r} does not have the public-read ACL set. '\n                             'Use the make_public() method to allow for '\n                             'public URL sharing.'.format(self.name))",
    "docstring": "Returns the public URL for the given key."
  },
  {
    "code": "def _full_like_variable(other, fill_value,\n                        dtype: Union[str, np.dtype, None] = None):\n    from .variable import Variable\n    if isinstance(other.data, dask_array_type):\n        import dask.array\n        if dtype is None:\n            dtype = other.dtype\n        data = dask.array.full(other.shape, fill_value, dtype=dtype,\n                               chunks=other.data.chunks)\n    else:\n        data = np.full_like(other, fill_value, dtype=dtype)\n    return Variable(dims=other.dims, data=data, attrs=other.attrs)",
    "docstring": "Inner function of full_like, where other must be a variable"
  },
  {
    "code": "def loadBatch(self, records):\r\n        try:\r\n            curr_batch = records[:self.batchSize()]\r\n            next_batch = records[self.batchSize():]\r\n            curr_records = list(curr_batch)\r\n            if self._preloadColumns:\r\n                for record in curr_records:\r\n                    record.recordValues(self._preloadColumns)\r\n            if len(curr_records) == self.batchSize():\r\n                self.loadedRecords[object, object].emit(curr_records,\r\n                                                        next_batch)\r\n            else:\r\n                self.loadedRecords[object].emit(curr_records)\r\n        except ConnectionLostError:\r\n            self.connectionLost.emit()\r\n        except Interruption:\r\n            pass",
    "docstring": "Loads the records for this instance in a batched mode."
  },
  {
    "code": "def get_graph_data(self, graph, benchmark):\n        if benchmark.get('params'):\n            param_iter = enumerate(zip(itertools.product(*benchmark['params']),\n                                           graph.get_steps()))\n        else:\n            param_iter = [(None, (None, graph.get_steps()))]\n        for j, (param, steps) in param_iter:\n            if param is None:\n                entry_name = benchmark['name']\n            else:\n                entry_name = benchmark['name'] + '({0})'.format(', '.join(param))\n            start_revision = self._get_start_revision(graph, benchmark, entry_name)\n            threshold = self._get_threshold(graph, benchmark, entry_name)\n            if start_revision is None:\n                continue\n            steps = [step for step in steps if step[1] >= start_revision]\n            yield j, entry_name, steps, threshold",
    "docstring": "Iterator over graph data sets\n\n        Yields\n        ------\n        param_idx\n            Flat index to parameter permutations for parameterized benchmarks.\n            None if benchmark is not parameterized.\n        entry_name\n            Name for the data set. If benchmark is non-parameterized, this is the\n            benchmark name.\n        steps\n            Steps to consider in regression detection.\n        threshold\n            User-specified threshold for regression detection."
  },
  {
    "code": "def registration_id_chunks(self, registration_ids):\n        try:\n            xrange\n        except NameError:\n            xrange = range\n        for i in xrange(0, len(registration_ids), self.FCM_MAX_RECIPIENTS):\n            yield registration_ids[i:i + self.FCM_MAX_RECIPIENTS]",
    "docstring": "Splits registration ids in several lists of max 1000 registration ids per list\n\n        Args:\n            registration_ids (list): FCM device registration ID\n\n        Yields:\n            generator: list including lists with registration ids"
  },
  {
    "code": "def to_dict(obj, **kwargs):\n    if is_model(obj.__class__):\n        return related_obj_to_dict(obj, **kwargs)\n    else:\n        return obj",
    "docstring": "Convert an object into dictionary. Uses singledispatch to allow for\n    clean extensions for custom class types.\n\n    Reference: https://pypi.python.org/pypi/singledispatch\n\n    :param obj: object instance\n    :param kwargs: keyword arguments such as suppress_private_attr,\n                   suppress_empty_values, dict_factory\n    :return: converted dictionary."
  },
  {
    "code": "def merge_asof(left, right, on=None,\n               left_on=None, right_on=None,\n               left_index=False, right_index=False,\n               by=None, left_by=None, right_by=None,\n               suffixes=('_x', '_y'),\n               tolerance=None,\n               allow_exact_matches=True,\n               direction='backward'):\n    op = _AsOfMerge(left, right,\n                    on=on, left_on=left_on, right_on=right_on,\n                    left_index=left_index, right_index=right_index,\n                    by=by, left_by=left_by, right_by=right_by,\n                    suffixes=suffixes,\n                    how='asof', tolerance=tolerance,\n                    allow_exact_matches=allow_exact_matches,\n                    direction=direction)\n    return op.get_result()",
    "docstring": "Perform an asof merge. This is similar to a left-join except that we\n    match on nearest key rather than equal keys.\n\n    Both DataFrames must be sorted by the key.\n\n    For each row in the left DataFrame:\n\n      - A \"backward\" search selects the last row in the right DataFrame whose\n        'on' key is less than or equal to the left's key.\n\n      - A \"forward\" search selects the first row in the right DataFrame whose\n        'on' key is greater than or equal to the left's key.\n\n      - A \"nearest\" search selects the row in the right DataFrame whose 'on'\n        key is closest in absolute distance to the left's key.\n\n    The default is \"backward\" and is compatible in versions below 0.20.0.\n    The direction parameter was added in version 0.20.0 and introduces\n    \"forward\" and \"nearest\".\n\n    Optionally match on equivalent keys with 'by' before searching with 'on'.\n\n    .. versionadded:: 0.19.0\n\n    Parameters\n    ----------\n    left : DataFrame\n    right : DataFrame\n    on : label\n        Field name to join on. Must be found in both DataFrames.\n        The data MUST be ordered. Furthermore this must be a numeric column,\n        such as datetimelike, integer, or float. On or left_on/right_on\n        must be given.\n    left_on : label\n        Field name to join on in left DataFrame.\n    right_on : label\n        Field name to join on in right DataFrame.\n    left_index : boolean\n        Use the index of the left DataFrame as the join key.\n\n        .. versionadded:: 0.19.2\n\n    right_index : boolean\n        Use the index of the right DataFrame as the join key.\n\n        .. versionadded:: 0.19.2\n\n    by : column name or list of column names\n        Match on these columns before performing merge operation.\n    left_by : column name\n        Field names to match on in the left DataFrame.\n\n        .. versionadded:: 0.19.2\n\n    right_by : column name\n        Field names to match on in the right DataFrame.\n\n        .. versionadded:: 0.19.2\n\n    suffixes : 2-length sequence (tuple, list, ...)\n        Suffix to apply to overlapping column names in the left and right\n        side, respectively.\n    tolerance : integer or Timedelta, optional, default None\n        Select asof tolerance within this range; must be compatible\n        with the merge index.\n    allow_exact_matches : boolean, default True\n\n        - If True, allow matching with the same 'on' value\n          (i.e. less-than-or-equal-to / greater-than-or-equal-to)\n        - If False, don't match the same 'on' value\n          (i.e., strictly less-than / strictly greater-than)\n\n    direction : 'backward' (default), 'forward', or 'nearest'\n        Whether to search for prior, subsequent, or closest matches.\n\n        .. versionadded:: 0.20.0\n\n    Returns\n    -------\n    merged : DataFrame\n\n    See Also\n    --------\n    merge\n    merge_ordered\n\n    Examples\n    --------\n    >>> left = pd.DataFrame({'a': [1, 5, 10], 'left_val': ['a', 'b', 'c']})\n    >>> left\n        a left_val\n    0   1        a\n    1   5        b\n    2  10        c\n\n    >>> right = pd.DataFrame({'a': [1, 2, 3, 6, 7],\n    ...                       'right_val': [1, 2, 3, 6, 7]})\n    >>> right\n       a  right_val\n    0  1          1\n    1  2          2\n    2  3          3\n    3  6          6\n    4  7          7\n\n    >>> pd.merge_asof(left, right, on='a')\n        a left_val  right_val\n    0   1        a          1\n    1   5        b          3\n    2  10        c          7\n\n    >>> pd.merge_asof(left, right, on='a', allow_exact_matches=False)\n        a left_val  right_val\n    0   1        a        NaN\n    1   5        b        3.0\n    2  10        c        7.0\n\n    >>> pd.merge_asof(left, right, on='a', direction='forward')\n        a left_val  right_val\n    0   1        a        1.0\n    1   5        b        6.0\n    2  10        c        NaN\n\n    >>> pd.merge_asof(left, right, on='a', direction='nearest')\n        a left_val  right_val\n    0   1        a          1\n    1   5        b          6\n    2  10        c          7\n\n    We can use indexed DataFrames as well.\n\n    >>> left = pd.DataFrame({'left_val': ['a', 'b', 'c']}, index=[1, 5, 10])\n    >>> left\n       left_val\n    1         a\n    5         b\n    10        c\n\n    >>> right = pd.DataFrame({'right_val': [1, 2, 3, 6, 7]},\n    ...                      index=[1, 2, 3, 6, 7])\n    >>> right\n       right_val\n    1          1\n    2          2\n    3          3\n    6          6\n    7          7\n\n    >>> pd.merge_asof(left, right, left_index=True, right_index=True)\n       left_val  right_val\n    1         a          1\n    5         b          3\n    10        c          7\n\n    Here is a real-world times-series example\n\n    >>> quotes\n                         time ticker     bid     ask\n    0 2016-05-25 13:30:00.023   GOOG  720.50  720.93\n    1 2016-05-25 13:30:00.023   MSFT   51.95   51.96\n    2 2016-05-25 13:30:00.030   MSFT   51.97   51.98\n    3 2016-05-25 13:30:00.041   MSFT   51.99   52.00\n    4 2016-05-25 13:30:00.048   GOOG  720.50  720.93\n    5 2016-05-25 13:30:00.049   AAPL   97.99   98.01\n    6 2016-05-25 13:30:00.072   GOOG  720.50  720.88\n    7 2016-05-25 13:30:00.075   MSFT   52.01   52.03\n\n    >>> trades\n                         time ticker   price  quantity\n    0 2016-05-25 13:30:00.023   MSFT   51.95        75\n    1 2016-05-25 13:30:00.038   MSFT   51.95       155\n    2 2016-05-25 13:30:00.048   GOOG  720.77       100\n    3 2016-05-25 13:30:00.048   GOOG  720.92       100\n    4 2016-05-25 13:30:00.048   AAPL   98.00       100\n\n    By default we are taking the asof of the quotes\n\n    >>> pd.merge_asof(trades, quotes,\n    ...                       on='time',\n    ...                       by='ticker')\n                         time ticker   price  quantity     bid     ask\n    0 2016-05-25 13:30:00.023   MSFT   51.95        75   51.95   51.96\n    1 2016-05-25 13:30:00.038   MSFT   51.95       155   51.97   51.98\n    2 2016-05-25 13:30:00.048   GOOG  720.77       100  720.50  720.93\n    3 2016-05-25 13:30:00.048   GOOG  720.92       100  720.50  720.93\n    4 2016-05-25 13:30:00.048   AAPL   98.00       100     NaN     NaN\n\n    We only asof within 2ms between the quote time and the trade time\n\n    >>> pd.merge_asof(trades, quotes,\n    ...                       on='time',\n    ...                       by='ticker',\n    ...                       tolerance=pd.Timedelta('2ms'))\n                         time ticker   price  quantity     bid     ask\n    0 2016-05-25 13:30:00.023   MSFT   51.95        75   51.95   51.96\n    1 2016-05-25 13:30:00.038   MSFT   51.95       155     NaN     NaN\n    2 2016-05-25 13:30:00.048   GOOG  720.77       100  720.50  720.93\n    3 2016-05-25 13:30:00.048   GOOG  720.92       100  720.50  720.93\n    4 2016-05-25 13:30:00.048   AAPL   98.00       100     NaN     NaN\n\n    We only asof within 10ms between the quote time and the trade time\n    and we exclude exact matches on time. However *prior* data will\n    propagate forward\n\n    >>> pd.merge_asof(trades, quotes,\n    ...                       on='time',\n    ...                       by='ticker',\n    ...                       tolerance=pd.Timedelta('10ms'),\n    ...                       allow_exact_matches=False)\n                         time ticker   price  quantity     bid     ask\n    0 2016-05-25 13:30:00.023   MSFT   51.95        75     NaN     NaN\n    1 2016-05-25 13:30:00.038   MSFT   51.95       155   51.97   51.98\n    2 2016-05-25 13:30:00.048   GOOG  720.77       100     NaN     NaN\n    3 2016-05-25 13:30:00.048   GOOG  720.92       100     NaN     NaN\n    4 2016-05-25 13:30:00.048   AAPL   98.00       100     NaN     NaN"
  },
  {
    "code": "def python_sidebar_navigation(python_input):\n    def get_text_fragments():\n        tokens = []\n        tokens.extend([\n            ('class:sidebar', '    '),\n            ('class:sidebar.key', '[Arrows]'),\n            ('class:sidebar', ' '),\n            ('class:sidebar.description', 'Navigate'),\n            ('class:sidebar', ' '),\n            ('class:sidebar.key', '[Enter]'),\n            ('class:sidebar', ' '),\n            ('class:sidebar.description', 'Hide menu'),\n        ])\n        return tokens\n    return Window(\n        FormattedTextControl(get_text_fragments),\n        style='class:sidebar',\n        width=Dimension.exact(43),\n        height=Dimension.exact(1))",
    "docstring": "Create the `Layout` showing the navigation information for the sidebar."
  },
  {
    "code": "def anchor_stream(self, stream_id, converter=\"rtc\"):\n        if isinstance(converter, str):\n            converter = self._known_converters.get(converter)\n            if converter is None:\n                raise ArgumentError(\"Unknown anchor converter string: %s\" % converter,\n                                    known_converters=list(self._known_converters))\n        self._anchor_streams[stream_id] = converter",
    "docstring": "Mark a stream as containing anchor points."
  },
  {
    "code": "def to_embedded(pool_id=None, is_thin_enabled=None,\n                    is_deduplication_enabled=None, is_compression_enabled=None,\n                    is_backup_only=None, size=None, tiering_policy=None,\n                    request_id=None, src_id=None, name=None, default_sp=None,\n                    replication_resource_type=None):\n        return {'poolId': pool_id, 'isThinEnabled': is_thin_enabled,\n                'isDeduplicationEnabled': is_deduplication_enabled,\n                'isCompressionEnabled': is_compression_enabled,\n                'isBackupOnly': is_backup_only, 'size': size,\n                'tieringPolicy': tiering_policy, 'requestId': request_id,\n                'srcId': src_id, 'name': name, 'defaultSP': default_sp,\n                'replicationResourceType': replication_resource_type}",
    "docstring": "Constructs an embeded object of `UnityResourceConfig`.\n\n        :param pool_id: storage pool of the resource.\n        :param is_thin_enabled: is thin type or not.\n        :param is_deduplication_enabled: is deduplication enabled or not.\n        :param is_compression_enabled: is in-line compression (ILC) enabled or\n            not.\n        :param is_backup_only: is backup only or not.\n        :param size: size of the resource.\n        :param tiering_policy: `TieringPolicyEnum` value. Tiering policy\n            for the resource.\n        :param request_id: unique request ID for the configuration.\n        :param src_id: storage resource if it already exists.\n        :param name: name of the storage resource.\n        :param default_sp: `NodeEnum` value. Default storage processor for\n            the resource.\n        :param replication_resource_type: `ReplicationEndpointResourceTypeEnum`\n            value. Replication resource type.\n        :return:"
  },
  {
    "code": "def initialise_loggers(names, log_level=_builtin_logging.WARNING, handler_class=SplitStreamHandler):\n    frmttr = get_formatter()\n    for name in names:\n        logr = _builtin_logging.getLogger(name)\n        handler = handler_class()\n        handler.setFormatter(frmttr)\n        logr.addHandler(handler)\n        logr.setLevel(log_level)",
    "docstring": "Initialises specified loggers to generate output at the\n    specified logging level. If the specified named loggers do not exist,\n    they are created.\n\n    :type names: :obj:`list` of :obj:`str`\n    :param names: List of logger names.\n    :type log_level: :obj:`int`\n    :param log_level: Log level for messages, typically\n       one of :obj:`logging.DEBUG`, :obj:`logging.INFO`, :obj:`logging.WARN`, :obj:`logging.ERROR`\n       or :obj:`logging.CRITICAL`.\n       See :ref:`levels`.\n    :type handler_class: One of the :obj:`logging.handlers` classes.\n    :param handler_class: The handler class for output of log messages,\n       for example :obj:`SplitStreamHandler` or :obj:`logging.StreamHandler`.\n\n    Example::\n\n       >>> from array_split import logging\n       >>> logging.initialise_loggers([\"my_logger\",], log_level=logging.INFO)\n       >>> logger = logging.getLogger(\"my_logger\")\n       >>> logger.info(\"This is info logging.\")\n       16:35:09|ARRSPLT| This is info logging.\n       >>> logger.debug(\"Not logged at logging.INFO level.\")\n       >>>"
  },
  {
    "code": "def _get_callback_context(env):\n    if env.model is not None and env.cvfolds is None:\n        context = 'train'\n    elif env.model is None and env.cvfolds is not None:\n        context = 'cv'\n    return context",
    "docstring": "return whether the current callback context is cv or train"
  },
  {
    "code": "def date_range(self):\n        try:\n            days = int(self.days)\n        except ValueError:\n            exit_after_echo(QUERY_DAYS_INVALID)\n        if days < 1:\n            exit_after_echo(QUERY_DAYS_INVALID)\n        start = datetime.today()\n        end = start + timedelta(days=days)\n        return (\n            datetime.strftime(start, '%Y-%m-%d'),\n            datetime.strftime(end, '%Y-%m-%d')\n        )",
    "docstring": "Generate date range according to the `days` user input."
  },
  {
    "code": "def stop_workflow(config, *, names=None):\n    jobs = list_jobs(config, filter_by_type=JobType.Workflow)\n    if names is not None:\n        filtered_jobs = []\n        for job in jobs:\n            if (job.id in names) or (job.name in names) or (job.workflow_id in names):\n                filtered_jobs.append(job)\n    else:\n        filtered_jobs = jobs\n    success = []\n    failed = []\n    for job in filtered_jobs:\n        client = Client(SignalConnection(**config.signal, auto_connect=True),\n                        request_key=job.workflow_id)\n        if client.send(Request(action='stop_workflow')).success:\n            success.append(job)\n        else:\n            failed.append(job)\n    return success, failed",
    "docstring": "Stop one or more workflows.\n\n    Args:\n        config (Config): Reference to the configuration object from which the\n            settings for the workflow are retrieved.\n        names (list): List of workflow names, workflow ids or workflow job ids for the\n            workflows that should be stopped. If all workflows should be\n            stopped, set it to None.\n\n    Returns:\n        tuple: A tuple of the workflow jobs that were successfully stopped and the ones\n            that could not be stopped."
  },
  {
    "code": "def get(key, profile=None):\n    conn = salt.utils.memcached.get_conn(profile)\n    return salt.utils.memcached.get(conn, key)",
    "docstring": "Get a value from memcached"
  },
  {
    "code": "def classify_coincident(st_vals, coincident):\n    r\n    if not coincident:\n        return None\n    if st_vals[0, 0] >= st_vals[0, 1] or st_vals[1, 0] >= st_vals[1, 1]:\n        return UNUSED_T\n    else:\n        return CLASSIFICATION_T.COINCIDENT",
    "docstring": "r\"\"\"Determine if coincident parameters are \"unused\".\n\n    .. note::\n\n       This is a helper for :func:`surface_intersections`.\n\n    In the case that ``coincident`` is :data:`True`, then we'll have two\n    sets of parameters :math:`(s_1, t_1)` and :math:`(s_2, t_2)`.\n\n    If one of :math:`s1 < s2` or :math:`t1 < t2` is not satisfied, the\n    coincident segments will be moving in opposite directions, hence don't\n    define an interior of an intersection.\n\n    .. warning::\n\n       In the \"coincident\" case, this assumes, but doesn't check, that\n       ``st_vals`` is ``2 x 2``.\n\n    Args:\n        st_vals (numpy.ndarray): ``2 X N`` array of intersection parameters.\n        coincident (bool): Flag indicating if the intersections are the\n            endpoints of coincident segments of two curves.\n\n    Returns:\n        Optional[.IntersectionClassification]: The classification of the\n        intersections."
  },
  {
    "code": "def reset(self):\n        if self.resync_period > 0 and (self.resets + 1) % self.resync_period == 0:\n            self._exit_resync()\n        while not self.done:\n            self.done = self._quit_episode()\n            if not self.done:\n                time.sleep(0.1)\n        return self._start_up()",
    "docstring": "gym api reset"
  },
  {
    "code": "def write(name, keyword, domain, citation, author, description, species, version, contact, licenses, values,\n          functions, output, value_prefix):\n    write_namespace(\n        name, keyword, domain, author, citation, values,\n        namespace_description=description,\n        namespace_species=species,\n        namespace_version=version,\n        author_contact=contact,\n        author_copyright=licenses,\n        functions=functions,\n        file=output,\n        value_prefix=value_prefix\n    )",
    "docstring": "Build a namespace from items."
  },
  {
    "code": "def get_logfile_path(working_dir):\n   logfile_filename = virtualchain_hooks.get_virtual_chain_name() + \".log\"\n   return os.path.join( working_dir, logfile_filename )",
    "docstring": "Get the logfile path for our service endpoint."
  },
  {
    "code": "def is_monotonic(full_list):\n    prev_elements = set({full_list[0]})\n    prev_item = full_list[0]\n    for item in full_list:\n        if item != prev_item:\n            if item in prev_elements:\n                return False\n            prev_item = item\n            prev_elements.add(item)\n    return True",
    "docstring": "Determine whether elements in a list are monotonic. ie. unique\n    elements are clustered together.\n\n    ie. [5,5,3,4] is, [5,3,5] is not."
  },
  {
    "code": "def reload(self):\n        other = type(self).get(self.name, service=self.service)\n        self.request_count = other.request_count",
    "docstring": "reload self from self.service"
  },
  {
    "code": "def get_current_shutit_pexpect_session(self, note=None):\n\t\tself.handle_note(note)\n\t\tres = self.current_shutit_pexpect_session\n\t\tself.handle_note_after(note)\n\t\treturn res",
    "docstring": "Returns the currently-set default pexpect child.\n\n\t\t@return: default shutit pexpect child object"
  },
  {
    "code": "def get_genus_type_metadata(self):\n        metadata = dict(self._mdata['genus_type'])\n        metadata.update({'existing_string_values': self._my_map['genusTypeId']})\n        return Metadata(**metadata)",
    "docstring": "Gets the metadata for a genus type.\n\n        return: (osid.Metadata) - metadata for the genus\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def delete_user_template(self, uid=0, temp_id=0, user_id=''):\n        if self.tcp and user_id:\n            command = 134\n            command_string = pack('<24sB', str(user_id), temp_id)\n            cmd_response = self.__send_command(command, command_string)\n            if cmd_response.get('status'):\n                return True\n            else:\n                return False\n        if not uid:\n            users = self.get_users()\n            users = list(filter(lambda x: x.user_id==str(user_id), users))\n            if not users:\n                return False\n            uid = users[0].uid\n        command = const.CMD_DELETE_USERTEMP\n        command_string = pack('hb', uid, temp_id)\n        cmd_response = self.__send_command(command, command_string)\n        if cmd_response.get('status'):\n            return True\n        else:\n            return False",
    "docstring": "Delete specific template\n\n        :param uid: user ID that are generated from device\n        :param user_id: your own user ID\n        :return: bool"
  },
  {
    "code": "def convert_response(allocate_quota_response, project_id):\n    if not allocate_quota_response or not allocate_quota_response.allocateErrors:\n        return _IS_OK\n    theError = allocate_quota_response.allocateErrors[0]\n    error_tuple = _QUOTA_ERROR_CONVERSION.get(theError.code, _IS_UNKNOWN)\n    if error_tuple[1].find(u'{') == -1:\n        return error_tuple\n    updated_msg = error_tuple[1].format(project_id=project_id, detail=theError.description or u'')\n    return error_tuple[0], updated_msg",
    "docstring": "Computes a http status code and message `AllocateQuotaResponse`\n\n    The return value a tuple (code, message) where\n\n    code: is the http status code\n    message: is the message to return\n\n    Args:\n       allocate_quota_response (:class:`endpoints_management.gen.servicecontrol_v1_messages.AllocateQuotaResponse`):\n         the response from calling an api\n\n    Returns:\n       tuple(code, message)"
  },
  {
    "code": "def config_changed(inherit_napalm_device=None, **kwargs):\n    is_config_changed = False\n    reason = ''\n    try_compare = compare_config(inherit_napalm_device=napalm_device)\n    if try_compare.get('result'):\n        if try_compare.get('out'):\n            is_config_changed = True\n        else:\n            reason = 'Configuration was not changed on the device.'\n    else:\n        reason = try_compare.get('comment')\n    return is_config_changed, reason",
    "docstring": "Will prompt if the configuration has been changed.\n\n    :return: A tuple with a boolean that specifies if the config was changed on the device.\\\n    And a string that provides more details of the reason why the configuration was not changed.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' net.config_changed"
  },
  {
    "code": "def get_archive_type(path):\n    if not is_directory_archive(path):\n        raise TypeError('Unable to determine the type of archive at path: %s' % path)\n    try:\n        ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini'])\n        parser = _ConfigParser.SafeConfigParser()\n        parser.read(ini_path)\n        contents = parser.get('metadata', 'contents')\n        return contents\n    except Exception as e:\n        raise TypeError('Unable to determine type of archive for path: %s' % path, e)",
    "docstring": "Returns the contents type for the provided archive path.\n\n    Parameters\n    ----------\n    path : string\n        Directory to evaluate.\n\n    Returns\n    -------\n    Returns a string of: sframe, sgraph, raises TypeError for anything else"
  },
  {
    "code": "def quantile_turnover(quantile_factor, quantile, period=1):\n    quant_names = quantile_factor[quantile_factor == quantile]\n    quant_name_sets = quant_names.groupby(level=['date']).apply(\n        lambda x: set(x.index.get_level_values('asset')))\n    if isinstance(period, int):\n        name_shifted = quant_name_sets.shift(period)\n    else:\n        shifted_idx = utils.add_custom_calendar_timedelta(\n                quant_name_sets.index, -pd.Timedelta(period),\n                quantile_factor.index.levels[0].freq)\n        name_shifted = quant_name_sets.reindex(shifted_idx)\n        name_shifted.index = quant_name_sets.index\n    new_names = (quant_name_sets - name_shifted).dropna()\n    quant_turnover = new_names.apply(\n        lambda x: len(x)) / quant_name_sets.apply(lambda x: len(x))\n    quant_turnover.name = quantile\n    return quant_turnover",
    "docstring": "Computes the proportion of names in a factor quantile that were\n    not in that quantile in the previous period.\n\n    Parameters\n    ----------\n    quantile_factor : pd.Series\n        DataFrame with date, asset and factor quantile.\n    quantile : int\n        Quantile on which to perform turnover analysis.\n    period: string or int, optional\n        Period over which to calculate the turnover. If it is a string it must\n        follow pandas.Timedelta constructor format (e.g. '1 days', '1D', '30m',\n        '3h', '1D1h', etc).\n    Returns\n    -------\n    quant_turnover : pd.Series\n        Period by period turnover for that quantile."
  },
  {
    "code": "def HasStorage(self):\n        from neo.Core.State.ContractState import ContractPropertyState\n        return self.ContractProperties & ContractPropertyState.HasStorage > 0",
    "docstring": "Flag indicating if storage is available.\n\n        Returns:\n            bool: True if available. False otherwise."
  },
  {
    "code": "def _set_rock_ridge(self, rr):\n        if not self.rock_ridge:\n            self.rock_ridge = rr\n        else:\n            for ver in ['1.09', '1.10', '1.12']:\n                if self.rock_ridge == ver:\n                    if rr and rr != ver:\n                        raise pycdlibexception.PyCdlibInvalidISO('Inconsistent Rock Ridge versions on the ISO!')",
    "docstring": "An internal method to set the Rock Ridge version of the ISO given the\n        Rock Ridge version of the previous entry.\n\n        Parameters:\n         rr - The version of rr from the last directory record.\n        Returns:\n         Nothing."
  },
  {
    "code": "def read_file(path):\n    if os.path.isabs(path):\n        with wrap_file_exceptions():\n            with open(path, 'rb') as stream:\n                return stream.read()\n    with wrap_file_exceptions():\n        stream = ca_storage.open(path)\n    try:\n        return stream.read()\n    finally:\n        stream.close()",
    "docstring": "Read the file from the given path.\n\n    If ``path`` is an absolute path, reads a file from the local filesystem. For relative paths, read the file\n    using the storage backend configured using :ref:`CA_FILE_STORAGE <settings-ca-file-storage>`."
  },
  {
    "code": "def getAWSAccountID():\n  link = \"http://169.254.169.254/latest/dynamic/instance-identity/document\"\n  try:\n    conn = urllib2.urlopen(url=link, timeout=5)\n  except urllib2.URLError:\n    return '0'\n  jsonData = json.loads(conn.read())\n  return jsonData['accountId']",
    "docstring": "Print an instance's AWS account number or 0 when not in EC2"
  },
  {
    "code": "def __clear_covers(self):\n        for i in range(self.n):\n            self.row_covered[i] = False\n            self.col_covered[i] = False",
    "docstring": "Clear all covered matrix cells"
  },
  {
    "code": "def ngettext(self, singular, plural, num, domain=None, **variables):\n        variables.setdefault('num', num)\n        t = self.get_translations(domain)\n        return t.ungettext(singular, plural, num) % variables",
    "docstring": "Translate a string wity the current locale.\n\n        The `num` parameter is used to dispatch between singular and various plural forms of the\n        message."
  },
  {
    "code": "def headloss_rect(FlowRate, Width, DistCenter, Length,\n                  KMinor, Nu, PipeRough, openchannel):\n    return (headloss_exp_rect(FlowRate, Width, DistCenter, KMinor).magnitude\n              + headloss_fric_rect(FlowRate, Width, DistCenter, Length,\n                                   Nu, PipeRough, openchannel).magnitude)",
    "docstring": "Return the total head loss in a rectangular channel.\n\n    Total head loss is a combination of the major and minor losses.\n    This equation applies to both laminar and turbulent flows."
  },
  {
    "code": "def _parse_error_message(self, message):\n        msg = message['error']['message']\n        code = message['error']['code']\n        err = None\n        out = None\n        if 'data' in message['error']:\n            err = ' '.join(message['error']['data'][-1]['errors'])\n            out = message['error']['data']\n        return code, msg, err, out",
    "docstring": "Parses the eAPI failure response message\n\n        This method accepts an eAPI failure message and parses the necesary\n        parts in order to generate a CommandError.\n\n        Args:\n            message (str): The error message to parse\n\n        Returns:\n            tuple: A tuple that consists of the following:\n                * code: The error code specified in the failure message\n                * message: The error text specified in the failure message\n                * error: The error text from the command that generated the\n                    error (the last command that ran)\n                * output: A list of all output from all commands"
  },
  {
    "code": "def on_api_error(self, error_status=None, message=None, event_origin=None):\n        if message.meta[\"error\"].find(\"Widget instance not found on server\") > -1:\n            error_status[\"retry\"] = True\n            self.comm.attach_remote(\n                self.id,\n                self.remote_name,\n                remote_name=self.name,\n                **self.init_kwargs\n            )",
    "docstring": "API error handling"
  },
  {
    "code": "def requires_refcount(cls, func):\n        @functools.wraps(func)\n        def requires_active_handle(*args, **kwargs):\n            if cls.refcount() == 0:\n                raise NoHandleException()\n            return func(*args, **kwargs)\n        return requires_active_handle",
    "docstring": "The ``requires_refcount`` decorator adds a check prior to call ``func`` to verify\n        that there is an active handle. if there is no such handle, a ``NoHandleException`` exception is thrown."
  },
  {
    "code": "def process_params(mod_id, params, type_params):\n    res = {}\n    for param_name, param_info in type_params.items():\n        val = params.get(param_name, param_info.get(\"default\", None))\n        if val is not None:\n            param_res = dict(param_info)\n            param_res[\"value\"] = val\n            res[param_name] = param_res\n        elif type_params.get(\"required\", False):\n            raise ValueError(\n                'Required parameter \"{}\" is not defined for module '\n                '\"{}\"'.format(param_name, mod_id)\n            )\n    return res",
    "docstring": "Takes as input a dictionary of parameters defined on a module and the\n    information about the required parameters defined on the corresponding\n    module type. Validatates that are required parameters were supplied and\n    fills any missing parameters with their default values from the module\n    type. Returns a nested dictionary of the same format as the `type_params`\n    but with an additional key `value` on each inner dictionary that gives the\n    value of that parameter for this specific module"
  },
  {
    "code": "def knx_to_time(knxdata):\n    if len(knxdata) != 3:\n        raise KNXException(\"Can only convert a 3 Byte object to time\")\n    dow = knxdata[0] >> 5\n    res = time(knxdata[0] & 0x1f, knxdata[1], knxdata[2])\n    return [res, dow]",
    "docstring": "Converts a KNX time to a tuple of a time object and the day of week"
  },
  {
    "code": "def construct_rest_of_worlds_mapping(self, excluded, fp=None):\n        metadata = {\n            'filename': 'faces.gpkg',\n            'field': 'id',\n            'sha256': sha256(self.faces_fp)\n        }\n        data = []\n        for key, locations in excluded.items():\n            for location in locations:\n                assert location in self.locations, \"Can't find location {}\".format(location)\n            included = self.all_faces.difference(\n                {face for loc in locations for face in self.data[loc]}\n            )\n            data.append((key, sorted(included)))\n        obj = {'data': data, 'metadata': metadata}\n        if fp:\n            with open(fp, \"w\") as f:\n                json.dump(obj, f, indent=2)\n        else:\n            return obj",
    "docstring": "Construct topo mapping file for ``excluded``.\n\n        ``excluded`` must be a **dictionary** of {\"rest-of-world label\": [\"names\", \"of\", \"excluded\", \"locations\"]}``.\n\n        Topo mapping has the data format:\n\n        .. code-block:: python\n\n            {\n                'data': [\n                    ['location label', ['topo face integer ids']],\n                ],\n                'metadata': {\n                    'filename': 'name of face definitions file',\n                    'field': 'field with uniquely identifies the fields in ``filename``',\n                    'sha256': 'SHA 256 hash of ``filename``'\n                }\n            }"
  },
  {
    "code": "def load(fp, encode_nominal=False, return_type=DENSE):\n    decoder = ArffDecoder()\n    return decoder.decode(fp, encode_nominal=encode_nominal,\n                          return_type=return_type)",
    "docstring": "Load a file-like object containing the ARFF document and convert it into\n    a Python object.\n\n    :param fp: a file-like object.\n    :param encode_nominal: boolean, if True perform a label encoding\n        while reading the .arff file.\n    :param return_type: determines the data structure used to store the\n        dataset. Can be one of `arff.DENSE`, `arff.COO`, `arff.LOD`,\n        `arff.DENSE_GEN` or `arff.LOD_GEN`.\n        Consult the sections on `working with sparse data`_ and `loading\n        progressively`_.\n    :return: a dictionary."
  },
  {
    "code": "def normalize(self, text, cleaned=False, **kwargs):\n        if not cleaned:\n            text = self.clean(text, **kwargs)\n        return ensure_list(text)",
    "docstring": "Create a represenation ideal for comparisons, but not to be\n        shown to the user."
  },
  {
    "code": "def translate(root_list, use_bag_semantics=False):\n    translator = (Translator() if use_bag_semantics else SetTranslator())\n    return [translator.translate(root).to_sql() for root in root_list]",
    "docstring": "Translate a list of relational algebra trees into SQL statements.\n\n    :param root_list: a list of tree roots\n    :param use_bag_semantics: flag for using relational algebra bag semantics\n    :return: a list of SQL statements"
  },
  {
    "code": "def toString(self):\n        slist = self.toList()\n        string = angle.slistStr(slist)\n        return string if slist[0] == '-' else string[1:]",
    "docstring": "Returns time as string."
  },
  {
    "code": "def login(self, username='0000', userid=0, password=None):\n\t\tif password and len(password) > 20:\n\t\t\tself.logger.error('password longer than 20 characters received')\n\t\t\traise Exception('password longer than 20 characters, login failed')\n\t\tself.send(C1218LogonRequest(username, userid))\n\t\tdata = self.recv()\n\t\tif data != b'\\x00':\n\t\t\tself.logger.warning('login failed, username and user id rejected')\n\t\t\treturn False\n\t\tif password is not None:\n\t\t\tself.send(C1218SecurityRequest(password))\n\t\t\tdata = self.recv()\n\t\t\tif data != b'\\x00':\n\t\t\t\tself.logger.warning('login failed, password rejected')\n\t\t\t\treturn False\n\t\tself.logged_in = True\n\t\treturn True",
    "docstring": "Log into the connected device.\n\n\t\t:param str username: the username to log in with (len(username) <= 10)\n\t\t:param int userid: the userid to log in with (0x0000 <= userid <= 0xffff)\n\t\t:param str password: password to log in with (len(password) <= 20)\n\t\t:rtype: bool"
  },
  {
    "code": "def update_from_dict(self, dct):\n        if not dct:\n            return\n        all_props = self.__class__.CONFIG_PROPERTIES\n        for key, value in six.iteritems(dct):\n            attr_config = all_props.get(key)\n            if attr_config:\n                setattr(self, key, value)\n            else:\n                self.update_default_from_dict(key, value)",
    "docstring": "Updates this configuration object from a dictionary.\n\n        See :meth:`ConfigurationObject.update` for details.\n\n        :param dct: Values to update the ConfigurationObject with.\n        :type dct: dict"
  },
  {
    "code": "def node_transmissions(node_id):\n    exp = Experiment(session)\n    direction = request_parameter(parameter=\"direction\", default=\"incoming\")\n    status = request_parameter(parameter=\"status\", default=\"all\")\n    for x in [direction, status]:\n        if type(x) == Response:\n            return x\n    node = models.Node.query.get(node_id)\n    if node is None:\n        return error_response(error_type=\"/node/transmissions, node does not exist\")\n    transmissions = node.transmissions(direction=direction, status=status)\n    try:\n        if direction in [\"incoming\", \"all\"] and status in [\"pending\", \"all\"]:\n            node.receive()\n            session.commit()\n        exp.transmission_get_request(node=node, transmissions=transmissions)\n        session.commit()\n    except Exception:\n        return error_response(\n            error_type=\"/node/transmissions GET server error\",\n            status=403,\n            participant=node.participant,\n        )\n    return success_response(transmissions=[t.__json__() for t in transmissions])",
    "docstring": "Get all the transmissions of a node.\n\n    The node id must be specified in the url.\n    You can also pass direction (to/from/all) or status (all/pending/received)\n    as arguments."
  },
  {
    "code": "def _parse_common_paths_file(project_path):\n        common_paths_file = os.path.join(project_path, 'common_paths.xml')\n        tree = etree.parse(common_paths_file)\n        paths = {}\n        path_vars = ['basedata', 'scheme', 'style', 'style', 'customization',\n                     'markable']\n        for path_var in path_vars:\n            specific_path = tree.find('//{}_path'.format(path_var)).text\n            paths[path_var] = specific_path if specific_path else project_path\n        paths['project_path'] = project_path\n        annotations = {}\n        for level in tree.iterfind('//level'):\n            annotations[level.attrib['name']] = {\n                'schemefile': level.attrib['schemefile'],\n                'customization_file': level.attrib['customization_file'],\n                'file_extension': level.text[1:]}\n        stylesheet = tree.find('//stylesheet').text\n        return paths, annotations, stylesheet",
    "docstring": "Parses a common_paths.xml file and returns a dictionary of paths,\n        a dictionary of annotation level descriptions and the filename\n        of the style file.\n\n        Parameters\n        ----------\n        project_path : str\n            path to the root directory of the MMAX project\n\n        Returns\n        -------\n        paths : dict\n            maps from MMAX file types (str, e.g. 'basedata' or 'markable')\n            to the relative path (str) containing files of this type\n        annotations : dict\n            maps from MMAX annotation level names (str, e.g. 'sentence',\n            'primmark') to a dict of features.\n            The features are: 'schemefile' (maps to a file),\n            'customization_file' (ditto) and 'file_extension' (maps to the\n            file name ending used for all annotations files of this level)\n        stylefile : str\n            name of the (default) style file used in this MMAX project"
  },
  {
    "code": "def acquire_auth_token_ticket(self, headers=None):\n        logging.debug('[CAS] Acquiring Auth token ticket')\n        url = self._get_auth_token_tickets_url()\n        text = self._perform_post(url, headers=headers)\n        auth_token_ticket = json.loads(text)['ticket']\n        logging.debug('[CAS] Acquire Auth token ticket: {}'.format(\n            auth_token_ticket))\n        return auth_token_ticket",
    "docstring": "Acquire an auth token from the CAS server."
  },
  {
    "code": "def start_centroid_distance(item_a, item_b, max_value):\n    start_a = item_a.center_of_mass(item_a.times[0])\n    start_b = item_b.center_of_mass(item_b.times[0])\n    start_distance = np.sqrt((start_a[0] - start_b[0]) ** 2 + (start_a[1] - start_b[1]) ** 2)\n    return np.minimum(start_distance, max_value) / float(max_value)",
    "docstring": "Distance between the centroids of the first step in each object.\n\n    Args:\n        item_a: STObject from the first set in TrackMatcher\n        item_b: STObject from the second set in TrackMatcher\n        max_value: Maximum distance value used as scaling value and upper constraint.\n\n    Returns:\n        Distance value between 0 and 1."
  },
  {
    "code": "def invocation():\n    cmdargs = [sys.executable] + sys.argv[:]\n    invocation = \" \".join(shlex.quote(s) for s in cmdargs)\n    return invocation",
    "docstring": "reconstructs the invocation for this python program"
  },
  {
    "code": "def get_logs(self):\n        folder = os.path.dirname(self.pcfg['log_file'])\n        for path, dir, files in os.walk(folder):\n            for file in files:\n                if os.path.splitext(file)[-1] == '.log':\n                    yield os.path.join(path, file)",
    "docstring": "returns logs from disk, requires .log extenstion"
  },
  {
    "code": "def __query_options(self):\n        options = 0\n        if self.__tailable:\n            options |= _QUERY_OPTIONS[\"tailable_cursor\"]\n        if self.__slave_okay or self.__pool._slave_okay:\n            options |= _QUERY_OPTIONS[\"slave_okay\"]\n        if not self.__timeout:\n            options |= _QUERY_OPTIONS[\"no_timeout\"]\n        return options",
    "docstring": "Get the query options string to use for this query."
  },
  {
    "code": "def project_with_metadata(self, term_doc_mat, x_dim=0, y_dim=1):\n        return self._project_category_corpus(self._get_category_metadata_corpus_and_replace_terms(term_doc_mat),\n                                             x_dim, y_dim)",
    "docstring": "Returns a projection of the\n\n        :param term_doc_mat: a TermDocMatrix\n        :return: CategoryProjection"
  },
  {
    "code": "def run_subprocess(command, return_code=False, **kwargs):\n    use_kwargs = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n    use_kwargs.update(kwargs)\n    p = subprocess.Popen(command, **use_kwargs)\n    output = p.communicate()\n    output = ['' if s is None else s for s in output]\n    output = [s.decode('utf-8') if isinstance(s, bytes) else s for s in output]\n    output = tuple(output)\n    if not return_code and p.returncode:\n        print(output[0])\n        print(output[1])\n        err_fun = subprocess.CalledProcessError.__init__\n        if 'output' in inspect.getargspec(err_fun).args:\n            raise subprocess.CalledProcessError(p.returncode, command, output)\n        else:\n            raise subprocess.CalledProcessError(p.returncode, command)\n    if return_code:\n        output = output + (p.returncode,)\n    return output",
    "docstring": "Run command using subprocess.Popen\n\n    Run command and wait for command to complete. If the return code was zero\n    then return, otherwise raise CalledProcessError.\n    By default, this will also add stdout= and stderr=subproces.PIPE\n    to the call to Popen to suppress printing to the terminal.\n\n    Parameters\n    ----------\n    command : list of str\n        Command to run as subprocess (see subprocess.Popen documentation).\n    return_code : bool\n        If True, the returncode will be returned, and no error checking\n        will be performed (so this function should always return without\n        error).\n    **kwargs : dict\n        Additional kwargs to pass to ``subprocess.Popen``.\n\n    Returns\n    -------\n    stdout : str\n        Stdout returned by the process.\n    stderr : str\n        Stderr returned by the process.\n    code : int\n        The command exit code. Only returned if ``return_code`` is True."
  },
  {
    "code": "def init_db():\n    import reana_db.models\n    if not database_exists(engine.url):\n        create_database(engine.url)\n    Base.metadata.create_all(bind=engine)",
    "docstring": "Initialize the DB."
  },
  {
    "code": "def _reset(cls):\n        if os.getpid() != cls._cls_pid:\n            cls._cls_pid = os.getpid()\n            cls._cls_instances_by_target.clear()\n            cls._cls_thread_by_target.clear()",
    "docstring": "If we have forked since the watch dictionaries were initialized, all\n        that has is garbage, so clear it."
  },
  {
    "code": "def update_cache(from_currency, to_currency):\n\tif check_update(from_currency, to_currency) is True:\n\t\tccache[from_currency][to_currency]['value'] = convert_using_api(from_currency, to_currency)\n\t\tccache[from_currency][to_currency]['last_update'] = time.time()\n\t\tcache.write(ccache)",
    "docstring": "update from_currency to_currency pair in cache if\n\tlast update for that pair is over 30 minutes ago by request API info"
  },
  {
    "code": "def createPopulationFile(inputFiles, labels, outputFileName):\n    outputFile = None\n    try:\n        outputFile = open(outputFileName, 'w')\n    except IOError:\n        msg = \"%(outputFileName)s: can't write file\"\n        raise ProgramError(msg)\n    for i in xrange(len(inputFiles)):\n        fileName = inputFiles[i]\n        label = labels[i]\n        try:\n            with open(fileName, 'r') as inputFile:\n                for line in inputFile:\n                    row = line.rstrip(\"\\r\\n\").split(\" \")\n                    famID = row[0]\n                    indID = row[1]\n                    print >>outputFile, \"\\t\".join([famID, indID, label])\n        except IOError:\n            msg = \"%(fileName)s: no such file\" % locals()\n            raise ProgramError(msg)\n    outputFile.close()",
    "docstring": "Creates a population file.\n\n    :param inputFiles: the list of input files.\n    :param labels: the list of labels (corresponding to the input files).\n    :param outputFileName: the name of the output file.\n\n    :type inputFiles: list\n    :type labels: list\n    :type outputFileName: str\n\n    The ``inputFiles`` is in reality a list of ``tfam`` files composed of\n    samples. For each of those ``tfam`` files, there is a label associated with\n    it (representing the name of the population).\n\n    The output file consists of one row per sample, with the following three\n    columns: the family ID, the individual ID and the population of each\n    sample."
  },
  {
    "code": "def run_timed(self, **kwargs):\n        for key in kwargs:\n            setattr(self, key, kwargs[key])\n        self.command = self.COMMAND_RUN_TIMED",
    "docstring": "Run the motor for the amount of time specified in `time_sp`\n        and then stop the motor using the action specified by `stop_action`."
  },
  {
    "code": "def check_ellipsis(text):\n    err = \"typography.symbols.ellipsis\"\n    msg = u\"'...' is an approximation, use the ellipsis symbol '…'.\"\n    regex = \"\\.\\.\\.\"\n    return existence_check(text, [regex], err, msg, max_errors=3,\n                           require_padding=False, offset=0)",
    "docstring": "Use an ellipsis instead of three dots."
  },
  {
    "code": "def cli(out_fmt, input, output):\n    _input = StringIO()\n    for l in input:\n        try:\n            _input.write(str(l))\n        except TypeError:\n            _input.write(bytes(l, 'utf-8'))\n    _input = seria.load(_input)\n    _out = (_input.dump(out_fmt))\n    output.write(_out)",
    "docstring": "Converts text."
  },
  {
    "code": "def _node_name(self, concept):\n        if (\n            self.grounding_threshold is not None\n            and concept.db_refs[self.grounding_ontology]\n            and (concept.db_refs[self.grounding_ontology][0][1] >\n                 self.grounding_threshold)):\n                entry = concept.db_refs[self.grounding_ontology][0][0]\n                return entry.split('/')[-1].replace('_', ' ').capitalize()\n        else:\n            return concept.name.capitalize()",
    "docstring": "Return a standardized name for a node given a Concept."
  },
  {
    "code": "def extract_archive(filepath):\n    if os.path.isdir(filepath):\n        path = os.path.abspath(filepath)\n        print(\"Archive already extracted. Viewing from {}...\".format(path))\n        return path\n    elif not zipfile.is_zipfile(filepath):\n        raise TypeError(\"{} is not a zipfile\".format(filepath))\n    archive_sha = SHA1_file(\n        filepath=filepath,\n        extra=to_bytes(slackviewer.__version__)\n    )\n    extracted_path = os.path.join(SLACKVIEWER_TEMP_PATH, archive_sha)\n    if os.path.exists(extracted_path):\n        print(\"{} already exists\".format(extracted_path))\n    else:\n        with zipfile.ZipFile(filepath) as zip:\n            print(\"{} extracting to {}...\".format(filepath, extracted_path))\n            zip.extractall(path=extracted_path)\n        print(\"{} extracted to {}\".format(filepath, extracted_path))\n        create_archive_info(filepath, extracted_path, archive_sha)\n    return extracted_path",
    "docstring": "Returns the path of the archive\n\n    :param str filepath: Path to file to extract or read\n\n    :return: path of the archive\n\n    :rtype: str"
  },
  {
    "code": "def description(self):\n        for e in self:\n            if isinstance(e, Description):\n                return e.value\n        raise NoSuchAnnotation",
    "docstring": "Obtain the description associated with the element.\n\n        Raises:\n            :class:`NoSuchAnnotation` if there is no associated description."
  },
  {
    "code": "def send_audio_packet(self, data, *, encode=True):\n        self.checked_add('sequence', 1, 65535)\n        if encode:\n            encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME)\n        else:\n            encoded_data = data\n        packet = self._get_voice_packet(encoded_data)\n        try:\n            self.socket.sendto(packet, (self.endpoint_ip, self.voice_port))\n        except BlockingIOError:\n            log.warning('A packet has been dropped (seq: %s, timestamp: %s)', self.sequence, self.timestamp)\n        self.checked_add('timestamp', self.encoder.SAMPLES_PER_FRAME, 4294967295)",
    "docstring": "Sends an audio packet composed of the data.\n\n        You must be connected to play audio.\n\n        Parameters\n        ----------\n        data: bytes\n            The :term:`py:bytes-like object` denoting PCM or Opus voice data.\n        encode: bool\n            Indicates if ``data`` should be encoded into Opus.\n\n        Raises\n        -------\n        ClientException\n            You are not connected.\n        OpusError\n            Encoding the data failed."
  },
  {
    "code": "def infer_location(\n            self,\n            location_query,\n            max_distance,\n            google_key,\n            foursquare_client_id,\n            foursquare_client_secret,\n            limit\n        ):\n        self.location_from = infer_location(\n            self.points[0],\n            location_query,\n            max_distance,\n            google_key,\n            foursquare_client_id,\n            foursquare_client_secret,\n            limit\n        )\n        self.location_to = infer_location(\n            self.points[-1],\n            location_query,\n            max_distance,\n            google_key,\n            foursquare_client_id,\n            foursquare_client_secret,\n            limit\n        )\n        return self",
    "docstring": "In-place location inferring\n\n        See infer_location function\n\n        Args:\n        Returns:\n            :obj:`Segment`: self"
  },
  {
    "code": "def drop_primary_key(self, table):\n        if self.get_primary_key(table):\n            self.execute('ALTER TABLE {0} DROP PRIMARY KEY'.format(wrap(table)))",
    "docstring": "Drop a Primary Key constraint for a specific table."
  },
  {
    "code": "def exit_if_missing_graphviz(self):\n        (out, err) = utils.capture_shell(\"which dot\")\n        if \"dot\" not in out:\n            ui.error(c.MESSAGES[\"dot_missing\"])",
    "docstring": "Detect the presence of the dot utility to make a png graph."
  },
  {
    "code": "def execute_command(self, args, parent_environ=None, **subprocess_kwargs):\n        if parent_environ in (None, os.environ):\n            target_environ = {}\n        else:\n            target_environ = parent_environ.copy()\n        interpreter = Python(target_environ=target_environ)\n        executor = self._create_executor(interpreter, parent_environ)\n        self._execute(executor)\n        return interpreter.subprocess(args, **subprocess_kwargs)",
    "docstring": "Run a command within a resolved context.\n\n        This applies the context to a python environ dict, then runs a\n        subprocess in that namespace. This is not a fully configured subshell -\n        shell-specific commands such as aliases will not be applied. To execute\n        a command within a subshell instead, use execute_shell().\n\n        Warning:\n            This runs a command in a configured environ dict only, not in a true\n            shell. To do that, call `execute_shell` using the `command` keyword\n            argument.\n\n        Args:\n            args: Command arguments, can be a string.\n            parent_environ: Environment to interpret the context within,\n                defaults to os.environ if None.\n            subprocess_kwargs: Args to pass to subprocess.Popen.\n\n        Returns:\n            A subprocess.Popen object.\n\n        Note:\n            This does not alter the current python session."
  },
  {
    "code": "def listen(self, port: int, address: str = \"\") -> None:\n        sockets = bind_sockets(port, address=address)\n        self.add_sockets(sockets)",
    "docstring": "Starts accepting connections on the given port.\n\n        This method may be called more than once to listen on multiple ports.\n        `listen` takes effect immediately; it is not necessary to call\n        `TCPServer.start` afterwards.  It is, however, necessary to start\n        the `.IOLoop`."
  },
  {
    "code": "def Containers(vent=True, running=True, exclude_labels=None):\n    containers = []\n    try:\n        d_client = docker.from_env()\n        if vent:\n            c = d_client.containers.list(all=not running,\n                                         filters={'label': 'vent'})\n        else:\n            c = d_client.containers.list(all=not running)\n        for container in c:\n            include = True\n            if exclude_labels:\n                for label in exclude_labels:\n                    if 'vent.groups' in container.labels and label in container.labels['vent.groups']:\n                        include = False\n            if include:\n                containers.append((container.name, container.status))\n    except Exception as e:\n        logger.error('Docker problem ' + str(e))\n    return containers",
    "docstring": "Get containers that are created, by default limit to vent containers that\n    are running"
  },
  {
    "code": "def _read_proto_resolve(self, length, ptype):\n        if ptype == '0800':\n            return ipaddress.ip_address(self._read_fileng(4))\n        elif ptype == '86dd':\n            return ipaddress.ip_address(self._read_fileng(16))\n        else:\n            return self._read_fileng(length)",
    "docstring": "Resolve IP address according to protocol.\n\n        Positional arguments:\n            * length -- int, protocol address length\n            * ptype -- int, protocol type\n\n        Returns:\n            * str -- IP address"
  },
  {
    "code": "def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,\n                        to_dir=os.curdir, delay=15):\n    to_dir = os.path.abspath(to_dir)\n    try:\n        from urllib.request import urlopen\n    except ImportError:\n        from urllib2 import urlopen\n    tgz_name = \"distribute-%s.tar.gz\" % version\n    url = download_base + tgz_name\n    saveto = os.path.join(to_dir, tgz_name)\n    src = dst = None\n    if not os.path.exists(saveto):\n        try:\n            log.warn(\"Downloading %s\", url)\n            src = urlopen(url)\n            data = src.read()\n            dst = open(saveto, \"wb\")\n            dst.write(data)\n        finally:\n            if src:\n                src.close()\n            if dst:\n                dst.close()\n    return os.path.realpath(saveto)",
    "docstring": "Download distribute from a specified location and return its filename\n\n    `version` should be a valid distribute version number that is available\n    as an egg for download under the `download_base` URL (which should end\n    with a '/'). `to_dir` is the directory where the egg will be downloaded.\n    `delay` is the number of seconds to pause before an actual download\n    attempt."
  },
  {
    "code": "def get(self, key):\n    if key not in self._keystore:\n      return None\n    rec = self._keystore[key]\n    if rec.is_expired:\n      self.delete(key)\n      return None\n    return rec.value",
    "docstring": "Retrieves previously stored key from the storage\n\n    :return value, stored in the storage"
  },
  {
    "code": "def _create_alignment_button(self):\n        iconnames = [\"AlignTop\", \"AlignCenter\", \"AlignBottom\"]\n        bmplist = [icons[iconname] for iconname in iconnames]\n        self.alignment_tb = _widgets.BitmapToggleButton(self, bmplist)\n        self.alignment_tb.SetToolTipString(_(u\"Alignment\"))\n        self.Bind(wx.EVT_BUTTON, self.OnAlignment, self.alignment_tb)\n        self.AddControl(self.alignment_tb)",
    "docstring": "Creates vertical alignment button"
  },
  {
    "code": "def delete(self, domain, type_name, search_command):\n        return self._request(domain, type_name, search_command, 'DELETE', None)",
    "docstring": "Delete entry in ThreatConnect Data Store\n\n        Args:\n            domain (string): One of 'local', 'organization', or 'system'.\n            type_name (string): This is a free form index type name. The ThreatConnect API will use\n                this resource verbatim.\n            search_command (string): Search command to pass to ES."
  },
  {
    "code": "def create_repo(url, vcs, **kwargs):\n    r\n    if vcs == 'git':\n        return GitRepo(url, **kwargs)\n    elif vcs == 'hg':\n        return MercurialRepo(url, **kwargs)\n    elif vcs == 'svn':\n        return SubversionRepo(url, **kwargs)\n    else:\n        raise InvalidVCS('VCS %s is not a valid VCS' % vcs)",
    "docstring": "r\"\"\"Return a object representation of a VCS repository.\n\n    :returns: instance of a repository object\n    :rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or\n        :class:`libvcs.hg.MercurialRepo`.\n\n    Usage Example::\n\n        >>> from libvcs.shortcuts import create_repo\n\n        >>> r = create_repo(\n        ...         url='https://www.github.com/you/myrepo',\n        ...         vcs='git',\n        ...         repo_dir='/tmp/myrepo')\n\n        >>> r.update_repo()\n        |myrepo| (git)  Repo directory for myrepo (git) does not exist @ \\\n            /tmp/myrepo\n        |myrepo| (git)  Cloning.\n        |myrepo| (git)  git clone https://www.github.com/tony/myrepo \\\n            /tmp/myrepo\n        Cloning into '/tmp/myrepo'...\n        Checking connectivity... done.\n        |myrepo| (git)  git fetch\n        |myrepo| (git)  git pull\n        Already up-to-date."
  },
  {
    "code": "def getIndex(reference):\n    if reference:\n        reffas = reference\n    else:\n        parent_directory = path.dirname(path.abspath(path.dirname(__file__)))\n        reffas = path.join(parent_directory, \"reference/DNA_CS.fasta\")\n    if not path.isfile(reffas):\n        logging.error(\"Could not find reference fasta for lambda genome.\")\n        sys.exit(\"Could not find reference fasta for lambda genome.\")\n    aligner = mp.Aligner(reffas, preset=\"map-ont\")\n    if not aligner:\n        logging.error(\"Failed to load/build index\")\n        raise Exception(\"ERROR: failed to load/build index\")\n    return aligner",
    "docstring": "Find the reference folder using the location of the script file\n    Create the index, test if successful"
  },
  {
    "code": "def convert_notebook(self, name):\n        exporter = nbconvert.exporters.python.PythonExporter()\n        relative_path = self.convert_path(name)\n        file_path = self.get_path(\"%s.ipynb\"%relative_path)\n        code = exporter.from_filename(file_path)[0]\n        self.write_code(name, code)\n        self.clean_code(name, [])",
    "docstring": "Converts a notebook into a python file."
  },
  {
    "code": "def handle_input(self, event):\n        self.update_timeval()\n        self.events = []\n        code = self._get_event_key_code(event)\n        if code in self.codes:\n            new_code = self.codes[code]\n        else:\n            new_code = 0\n        event_type = self._get_event_type(event)\n        value = self._get_key_value(event, event_type)\n        scan_event, key_event = self.emulate_press(\n            new_code, code, value, self.timeval)\n        self.events.append(scan_event)\n        self.events.append(key_event)\n        self.events.append(self.sync_marker(self.timeval))\n        self.write_to_pipe(self.events)",
    "docstring": "Process they keyboard input."
  },
  {
    "code": "def to_html(self, show_mean=None, sortable=None, colorize=True, *args,\n                **kwargs):\n        if show_mean is None:\n            show_mean = self.show_mean\n        if sortable is None:\n            sortable = self.sortable\n        df = self.copy()\n        if show_mean:\n            df.insert(0, 'Mean', None)\n            df.loc[:, 'Mean'] = ['%.3f' % self[m].mean() for m in self.models]\n        html = df.to_html(*args, **kwargs)\n        html, table_id = self.annotate(df, html, show_mean, colorize)\n        if sortable:\n            self.dynamify(table_id)\n        return html",
    "docstring": "Extend Pandas built in `to_html` method for rendering a DataFrame\n        and use it to render a ScoreMatrix."
  },
  {
    "code": "def three_digit(number):\n    number = str(number)\n    if len(number) == 1:\n        return u'00%s' % number\n    elif len(number) == 2:\n        return u'0%s' % number\n    else:\n        return number",
    "docstring": "Add 0s to inputs that their length is less than 3.\n\n    :param number:\n        The number to convert\n    :type number:\n        int\n\n    :returns:\n        String\n\n    :example:\n        >>> three_digit(1)\n        '001'"
  },
  {
    "code": "def disconnect(self):\n        all_conns = chain(\n            self._available_connections.values(),\n            self._in_use_connections.values(),\n        )\n        for node_connections in all_conns:\n            for connection in node_connections:\n                connection.disconnect()",
    "docstring": "Nothing that requires any overwrite."
  },
  {
    "code": "def nonKeyVisibleCols(self):\n        'All columns which are not keysList of unhidden non-key columns.'\n        return [c for c in self.columns if not c.hidden and c not in self.keyCols]",
    "docstring": "All columns which are not keysList of unhidden non-key columns."
  },
  {
    "code": "def calculate_start_time(df):\n    if \"time\" in df:\n        df[\"time_arr\"] = pd.Series(df[\"time\"], dtype='datetime64[s]')\n    elif \"timestamp\" in df:\n        df[\"time_arr\"] = pd.Series(df[\"timestamp\"], dtype=\"datetime64[ns]\")\n    else:\n        return df\n    if \"dataset\" in df:\n        for dset in df[\"dataset\"].unique():\n            time_zero = df.loc[df[\"dataset\"] == dset, \"time_arr\"].min()\n            df.loc[df[\"dataset\"] == dset, \"start_time\"] = \\\n                df.loc[df[\"dataset\"] == dset, \"time_arr\"] - time_zero\n    else:\n        df[\"start_time\"] = df[\"time_arr\"] - df[\"time_arr\"].min()\n    return df.drop([\"time\", \"timestamp\", \"time_arr\"], axis=1, errors=\"ignore\")",
    "docstring": "Calculate the star_time per read.\n\n    Time data is either\n    a \"time\" (in seconds, derived from summary files) or\n    a \"timestamp\" (in UTC, derived from fastq_rich format)\n    and has to be converted appropriately in a datetime format time_arr\n\n    For both the time_zero is the minimal value of the time_arr,\n    which is then used to subtract from all other times\n\n    In the case of method=track (and dataset is a column in the df) then this\n    subtraction is done per dataset"
  },
  {
    "code": "def rename_variables(expression: Expression, renaming: Dict[str, str]) -> Expression:\n    if isinstance(expression, Operation):\n        if hasattr(expression, 'variable_name'):\n            variable_name = renaming.get(expression.variable_name, expression.variable_name)\n            return create_operation_expression(\n                expression, [rename_variables(o, renaming) for o in op_iter(expression)], variable_name=variable_name\n            )\n        operands = [rename_variables(o, renaming) for o in op_iter(expression)]\n        return create_operation_expression(expression, operands)\n    elif isinstance(expression, Expression):\n        expression = expression.__copy__()\n        expression.variable_name = renaming.get(expression.variable_name, expression.variable_name)\n    return expression",
    "docstring": "Rename the variables in the expression according to the given dictionary.\n\n    Args:\n        expression:\n            The expression in which the variables are renamed.\n        renaming:\n            The renaming dictionary. Maps old variable names to new ones.\n            Variable names not occuring in the dictionary are left unchanged.\n\n    Returns:\n        The expression with renamed variables."
  },
  {
    "code": "def merge(args):\n    p = OptionParser(merge.__doc__)\n    p.set_outdir(outdir=\"outdir\")\n    opts, args = p.parse_args(args)\n    if len(args) < 1:\n        sys.exit(not p.print_help())\n    folders = args\n    outdir = opts.outdir\n    mkdir(outdir)\n    files = flatten(glob(\"{0}/*.*.fastq\".format(x)) for x in folders)\n    files = list(files)\n    key = lambda x: op.basename(x).split(\".\")[0]\n    files.sort(key=key)\n    for id, fns in groupby(files, key=key):\n        fns = list(fns)\n        outfile = op.join(outdir, \"{0}.fastq\".format(id))\n        FileMerger(fns, outfile=outfile).merge(checkexists=True)",
    "docstring": "%prog merge folder1 ...\n\n    Consolidate split contents in the folders. The folders can be generated by\n    the split() process and several samples may be in separate fastq files. This\n    program merges them."
  },
  {
    "code": "def _stop_ubridge(self):\n        if self._ubridge_hypervisor and self._ubridge_hypervisor.is_running():\n            log.info(\"Stopping uBridge hypervisor {}:{}\".format(self._ubridge_hypervisor.host, self._ubridge_hypervisor.port))\n            yield from self._ubridge_hypervisor.stop()\n        self._ubridge_hypervisor = None",
    "docstring": "Stops uBridge."
  },
  {
    "code": "def is_deb_package_installed(pkg):\n    with settings(hide('warnings', 'running', 'stdout', 'stderr'),\n                  warn_only=True, capture=True):\n        result = sudo('dpkg-query -l \"%s\" | grep -q ^.i' % pkg)\n        return not bool(result.return_code)",
    "docstring": "checks if a particular deb package is installed"
  },
  {
    "code": "def numbering_part(self):\n        try:\n            return self.part_related_by(RT.NUMBERING)\n        except KeyError:\n            numbering_part = NumberingPart.new()\n            self.relate_to(numbering_part, RT.NUMBERING)\n            return numbering_part",
    "docstring": "A |NumberingPart| object providing access to the numbering\n        definitions for this document. Creates an empty numbering part if one\n        is not present."
  },
  {
    "code": "def solidangle_errorprop(twotheta, dtwotheta, sampletodetectordistance, dsampletodetectordistance, pixelsize=None):\n    SAC = solidangle(twotheta, sampletodetectordistance, pixelsize)\n    if pixelsize is None:\n        pixelsize = 1\n    return (SAC,\n            (sampletodetectordistance * (4 * dsampletodetectordistance ** 2 * np.cos(twotheta) ** 2 +\n                                        9 * dtwotheta ** 2 * sampletodetectordistance ** 2 * np.sin(twotheta) ** 2) ** 0.5\n             / np.cos(twotheta) ** 4) / pixelsize ** 2)",
    "docstring": "Solid-angle correction for two-dimensional SAS images with error propagation\n\n    Inputs:\n        twotheta: matrix of two-theta values\n        dtwotheta: matrix of absolute error of two-theta values\n        sampletodetectordistance: sample-to-detector distance\n        dsampletodetectordistance: absolute error of sample-to-detector distance\n\n    Outputs two matrices of the same shape as twotheta. The scattering intensity\n        matrix should be multiplied by the first one. The second one is the propagated\n        error of the first one."
  },
  {
    "code": "async def process_name(message: types.Message, state: FSMContext):\n    async with state.proxy() as data:\n        data['name'] = message.text\n    await Form.next()\n    await message.reply(\"How old are you?\")",
    "docstring": "Process user name"
  },
  {
    "code": "def _update(self, data):\n      self.bullet = data['bullet']\n      self.level = data['level']\n      self.text = WikiText(data['text_raw'],\n                           data['text_rendered'])",
    "docstring": "Update the line using the blob of json-parsed data directly from the\n      API."
  },
  {
    "code": "def load_probe(name):\n    if op.exists(name):\n        path = name\n    else:\n        curdir = op.realpath(op.dirname(__file__))\n        path = op.join(curdir, 'probes/{}.prb'.format(name))\n    if not op.exists(path):\n        raise IOError(\"The probe `{}` cannot be found.\".format(name))\n    return MEA(probe=_read_python(path))",
    "docstring": "Load one of the built-in probes."
  },
  {
    "code": "def release(self, force=False):\n\t\tD = self.__class__\n\t\tcollection = self.get_collection()\n\t\tidentity = self.Lock()\n\t\tquery = D.id == self\n\t\tif not force:\n\t\t\tquery &= D.lock.instance == identity.instance\n\t\tprevious = collection.find_one_and_update(query, {'$unset': {~D.lock: True}}, {~D.lock: True})\n\t\tif previous is None:\n\t\t\tlock = getattr(self.find_one(self, projection={~D.lock: True}), 'lock', None)\n\t\t\traise self.Locked(\"Unable to release lock.\", lock)\n\t\tlock = self.Lock.from_mongo(previous[~D.lock])\n\t\tif lock and lock.expires <= identity.time:\n\t\t\tlock.expired(self)\n\t\tidentity.released(self, force)",
    "docstring": "Release an exclusive lock on this integration task.\n\t\t\n\t\tUnless forcing, if we are not the current owners of the lock a Locked exception will be raised."
  },
  {
    "code": "def is_same_transform(matrix0, matrix1):\n    matrix0 = np.array(matrix0, dtype=np.float64, copy=True)\n    matrix0 /= matrix0[3, 3]\n    matrix1 = np.array(matrix1, dtype=np.float64, copy=True)\n    matrix1 /= matrix1[3, 3]\n    return np.allclose(matrix0, matrix1)",
    "docstring": "Return True if two matrices perform same transformation.\n\n    >>> is_same_transform(np.identity(4), np.identity(4))\n    True\n    >>> is_same_transform(np.identity(4), random_rotation_matrix())\n    False"
  },
  {
    "code": "def AddATR(self, readernode, atr):\n        capchild = self.AppendItem(readernode, atr)\n        self.SetPyData(capchild, None)\n        self.SetItemImage(\n            capchild, self.cardimageindex, wx.TreeItemIcon_Normal)\n        self.SetItemImage(\n            capchild, self.cardimageindex, wx.TreeItemIcon_Expanded)\n        self.Expand(capchild)\n        return capchild",
    "docstring": "Add an ATR to a reader node."
  },
  {
    "code": "def decrease_step(self) -> str:\n        if self._steps_index > 0:\n            self._steps_index = self._steps_index - 1\n        return 'step: {}'.format(self.current_step())",
    "docstring": "Decrease the jog resolution without overrunning the list of values"
  },
  {
    "code": "def authenticate_admin(self, transport, account_name, password):\n        Authenticator.authenticate_admin(self, transport, account_name, password)\n        auth_token = AuthToken()\n        auth_token.account_name = account_name\n        params = {sconstant.E_NAME: account_name,\n                  sconstant.E_PASSWORD: password}\n        self.log.debug('Authenticating admin %s' % account_name)\n        try:\n            res = transport.invoke(zconstant.NS_ZIMBRA_ADMIN_URL,\n                                   sconstant.AuthRequest,\n                                   params,\n                                   auth_token)\n        except SoapException as exc:\n            raise AuthException(unicode(exc), exc)\n        auth_token.token = res.authToken\n        auth_token.session_id = res.sessionId\n        self.log.info('Authenticated admin %s, session id %s'\n                      % (account_name, auth_token.session_id))\n        return auth_token",
    "docstring": "Authenticates administrator using username and password."
  },
  {
    "code": "def AIC_compare(aic_list):\n    aic_values = np.array(aic_list)\n    minimum = np.min(aic_values)\n    delta = aic_values - minimum\n    values = np.exp(-delta / 2)\n    weights = values / np.sum(values)\n    return delta, weights",
    "docstring": "Calculates delta AIC and AIC weights from a list of AIC values\n\n    Parameters\n    -----------------\n    aic_list : iterable\n        AIC values from set of candidat models\n\n    Returns\n    -------------\n    tuple\n        First element contains the delta AIC values, second element contains\n        the relative AIC weights.\n\n    Notes\n    -----\n    AIC weights can be interpreted as the probability that a given model is the\n    best model in the set.\n\n    Examples\n    --------\n\n    >>> # Generate random data\n    >>> rand_samp = md.nbinom_ztrunc.rvs(20, 0.5, size=100)\n\n    >>> # Fit Zero-truncated NBD (Full model)\n    >>> mle_nbd = md.nbinom_ztrunc.fit_mle(rand_samp)\n\n    >>> # Fit a logseries (limiting case of Zero-truncated NBD, reduced model)\n    >>> mle_logser = md.logser.fit_mle(rand_samp)\n\n    >>> # Get AIC for ztrunc_nbinom\n    >>> nbd_aic = comp.AIC(rand_samp, md.nbinom_ztrunc(*mle_nbd))\n\n    >>> # Get AIC for logser\n    >>> logser_aic = comp.AIC(rand_samp, md.logser(*mle_logser))\n\n    >>> # Make AIC list and get weights\n    >>> aic_list = [nbd_aic, logser_aic]\n    >>> comp.AIC_compare(aic_list)\n    (array([  0.        ,  19.11806518]),\n    array([  9.99929444e-01,   7.05560486e-05]))\n\n    >>> # Zero-truncated NBD is a far superior model based on AIC weights"
  },
  {
    "code": "def getCachedOrUpdatedValue(self, key, channel=None):\n        if channel:\n            return self._hmchannels[channel].getCachedOrUpdatedValue(key)\n        try:\n            return self._VALUES[key]\n        except KeyError:\n            value = self._VALUES[key] = self.getValue(key)\n            return value",
    "docstring": "Gets the channel's value with the given key.\n\n        If the key is not found in the cache, the value is queried from the host.\n        If 'channel' is given, the respective channel's value is returned."
  },
  {
    "code": "async def get(self) -> InfoDict:\n        if self._seen_kork:\n            raise AnalysisComplete()\n        info = await self._queue.get()\n        if not info:\n            self._seen_kork = True\n            await self._finished\n            raise AnalysisComplete()\n        return info",
    "docstring": "Waits for the next dictionary of information from the engine and\n        returns it.\n\n        It might be more convenient to use ``async for info in analysis: ...``.\n\n        :raises: :exc:`chess.engine.AnalysisComplete` if the analysis is\n            complete (or has been stopped) and all information has been\n            consumed. Use :func:`~chess.engine.AnalysisResult.next()` if you\n            prefer to get ``None`` instead of an exception."
  },
  {
    "code": "def reload(script, input, output):\n    script = Path(script).expand().abspath()\n    output = Path(output).expand().abspath()\n    input = input if isinstance(input, (list, tuple)) else [input]\n    output.makedirs_p()\n    _script_reload(script, input, output)",
    "docstring": "reloads the generator script when the script files\n    or the input files changes"
  },
  {
    "code": "def as_completed(jobs):\n  jobs = tuple(jobs)\n  event = threading.Event()\n  callback = lambda f, ev: event.set()\n  [job.add_listener(Job.SUCCESS, callback, once=True) for job in jobs]\n  [job.add_listener(Job.ERROR, callback, once=True) for job in jobs]\n  while jobs:\n    event.wait()\n    event.clear()\n    jobs, finished = split_list_by(jobs, lambda x: x.finished)\n    for job in finished:\n      yield job",
    "docstring": "Generator function that yields the jobs in order of their\n  completion. Attaches a new listener to each job."
  },
  {
    "code": "def read(self, pos, size, **kwargs):\n        data, realsize = self.read_data(size, **kwargs)\n        if not self.state.solver.is_true(realsize == 0):\n            self.state.memory.store(pos, data, size=realsize)\n        return realsize",
    "docstring": "Reads some data from the file, storing it into memory.\n\n        :param pos:     The address to write the read data into memory\n        :param size:    The requested length of the read\n        :return:        The real length of the read"
  },
  {
    "code": "def _clear(self):\n        draw = ImageDraw.Draw(self._background_image)\n        draw.rectangle(self._device.bounding_box,\n                       fill=\"black\")\n        del draw",
    "docstring": "Helper that clears the composition."
  },
  {
    "code": "def dtstr_to_datetime(dtstr, to_tz=None, fail_silently=True):\n    try:\n        dt = datetime.datetime.utcfromtimestamp(int(dtstr, 36) / 1e3)\n        if to_tz:\n            dt = timezone.make_aware(dt, timezone=pytz.UTC)\n            if to_tz != pytz.UTC:\n                dt = dt.astimezone(to_tz)\n        return dt\n    except ValueError, e:\n        if not fail_silently:\n            raise e\n        return None",
    "docstring": "Convert result from datetime_to_dtstr to datetime in timezone UTC0."
  },
  {
    "code": "def download_data_dictionary(request, dataset_id):\n    dataset = Dataset.objects.get(pk=dataset_id)\n    dataDict = dataset.data_dictionary\n    fields = DataDictionaryField.objects.filter(\n        parent_dict=dataDict\n    ).order_by('columnIndex')\n    response = HttpResponse(content_type='text/csv')\n    csvName = slugify(dataset.title + ' data dict') + '.csv'\n    response['Content-Disposition'] = 'attachment; filename=%s' % (csvName)\n    csvWriter = writer(response)\n    metaHeader = [\n        'Data Dictionary for {0} prepared by {1}'.format(\n            dataset.title,\n            dataset.uploaded_by\n        )\n    ]\n    csvWriter.writerow(metaHeader)\n    trueHeader = ['Column Index', 'Heading', 'Description', 'Data Type']\n    csvWriter.writerow(trueHeader)\n    for field in fields:\n        mappedIndex = field.COLUMN_INDEX_CHOICES[field.columnIndex-1][1]\n        csvWriter.writerow(\n            [mappedIndex, field.heading, field.description, field.dataType]\n        )\n    return response",
    "docstring": "Generates and returns compiled data dictionary from database.\n\n    Returned as a CSV response."
  },
  {
    "code": "def adam7_generate(width, height):\n    for xstart, ystart, xstep, ystep in adam7:\n        if xstart >= width:\n            continue\n        yield ((xstart, y, xstep) for y in range(ystart, height, ystep))",
    "docstring": "Generate the coordinates for the reduced scanlines\n    of an Adam7 interlaced image\n    of size `width` by `height` pixels.\n\n    Yields a generator for each pass,\n    and each pass generator yields a series of (x, y, xstep) triples,\n    each one identifying a reduced scanline consisting of\n    pixels starting at (x, y) and taking every xstep pixel to the right."
  },
  {
    "code": "def calculate_equinoxes(self, year, timezone='UTC'):\n        tz = pytz.timezone(timezone)\n        d1 = ephem.next_equinox(str(year))\n        d = ephem.Date(str(d1))\n        equinox1 = d.datetime() + tz.utcoffset(d.datetime())\n        d2 = ephem.next_equinox(d1)\n        d = ephem.Date(str(d2))\n        equinox2 = d.datetime() + tz.utcoffset(d.datetime())\n        return (equinox1.date(), equinox2.date())",
    "docstring": "calculate equinox with time zone"
  },
  {
    "code": "def segment_to_vector(self, seg):\n        ft_dict = {ft: val for (val, ft) in self.fts(seg)}\n        return [ft_dict[name] for name in self.names]",
    "docstring": "Given a Unicode IPA segment, return a list of feature specificiations\n        in cannonical order.\n\n        Args:\n            seg (unicode): IPA consonant or vowel\n\n        Returns:\n            list: feature specifications ('+'/'-'/'0') in the order from\n            `FeatureTable.names`"
  },
  {
    "code": "def get_prefixes(self, query):\n        try:\n            res = Prefix.smart_search(query, {})\n        except socket.error:\n            print >> sys.stderr, \"Connection refused, please check hostname & port\"\n            sys.exit(1)\n        except xmlrpclib.ProtocolError:\n            print >> sys.stderr, \"Authentication failed, please check your username / password\"\n            sys.exit(1)\n        for p in res['result']:\n            p.prefix_ipy = IPy.IP(p.prefix)\n            self.prefixes.append(p)",
    "docstring": "Get prefix data from NIPAP"
  },
  {
    "code": "def to_paginated_list(self, result, _ns, _operation, **kwargs):\n        items, context = self.parse_result(result)\n        headers = dict()\n        paginated_list = PaginatedList(\n            items=items,\n            _page=self,\n            _ns=_ns,\n            _operation=_operation,\n            _context=context,\n        )\n        return paginated_list, headers",
    "docstring": "Convert a controller result to a paginated list.\n\n        The result format is assumed to meet the contract of this page class's `parse_result` function."
  },
  {
    "code": "def _create_job(self, mapping):\n        job_id = self.bulk.create_insert_job(mapping[\"sf_object\"], contentType=\"CSV\")\n        self.logger.info(\"  Created bulk job {}\".format(job_id))\n        local_ids_for_batch = {}\n        for batch_file, local_ids in self._get_batches(mapping):\n            batch_id = self.bulk.post_batch(job_id, batch_file)\n            local_ids_for_batch[batch_id] = local_ids\n            self.logger.info(\"    Uploaded batch {}\".format(batch_id))\n        self.bulk.close_job(job_id)\n        return job_id, local_ids_for_batch",
    "docstring": "Initiate a bulk insert and upload batches to run in parallel."
  },
  {
    "code": "def get_entry_view(self, key):\n        check_not_none(key, \"key can't be None\")\n        key_data = self._to_data(key)\n        return self._encode_invoke_on_key(map_get_entry_view_codec, key_data, key=key_data, thread_id=thread_id())",
    "docstring": "Returns the EntryView for the specified key.\n\n        **Warning:\n        This method returns a clone of original mapping, modifying the returned value does not change the actual value\n        in the map. One should put modified value back to make changes visible to all nodes.**\n\n        **Warning 2: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations\n        of __hash__ and __eq__ defined in key's class.**\n\n        :param key: (object), the key of the entry.\n        :return: (EntryView), EntryView of the specified key.\n\n        .. seealso:: :class:`~hazelcast.core.EntryView` for more info about EntryView."
  },
  {
    "code": "def font_extents(self):\n        extents = ffi.new('cairo_font_extents_t *')\n        cairo.cairo_font_extents(self._pointer, extents)\n        self._check_status()\n        return (\n            extents.ascent, extents.descent, extents.height,\n            extents.max_x_advance, extents.max_y_advance)",
    "docstring": "Return the extents of the currently selected font.\n\n        Values are given in the current user-space coordinate system.\n\n        Because font metrics are in user-space coordinates, they are mostly,\n        but not entirely, independent of the current transformation matrix.\n        If you call :meth:`context.scale(2) <scale>`,\n        text will be drawn twice as big,\n        but the reported text extents will not be doubled.\n        They will change slightly due to hinting\n        (so you can't assume that metrics are independent\n        of the transformation matrix),\n        but otherwise will remain unchanged.\n\n        :returns:\n            A ``(ascent, descent, height, max_x_advance, max_y_advance)``\n            tuple of floats.\n\n        :obj:`ascent`\n            The distance that the font extends above the baseline.\n            Note that this is not always exactly equal to\n            the maximum of the extents of all the glyphs in the font,\n            but rather is picked to express the font designer's intent\n            as to how the font should align with elements above it.\n        :obj:`descent`\n            The distance that the font extends below the baseline.\n            This value is positive for typical fonts\n            that include portions below the baseline.\n            Note that this is not always exactly equal\n            to the maximum of the extents of all the glyphs in the font,\n            but rather is picked to express the font designer's intent\n            as to how the font should align with elements below it.\n        :obj:`height`\n            The recommended vertical distance between baselines\n            when setting consecutive lines of text with the font.\n            This is greater than ``ascent + descent``\n            by a quantity known as the line spacing or external leading.\n            When space is at a premium, most fonts can be set\n            with only a distance of ``ascent + descent`` between lines.\n        :obj:`max_x_advance`\n            The maximum distance in the X direction\n            that the origin is advanced for any glyph in the font.\n        :obj:`max_y_advance`\n            The maximum distance in the Y direction\n            that the origin is advanced for any glyph in the font.\n            This will be zero for normal fonts used for horizontal writing.\n            (The scripts of East Asia are sometimes written vertically.)"
  },
  {
    "code": "def get_item_query_session_for_bank(self, bank_id):\n        if not self.supports_item_query():\n            raise errors.Unimplemented()\n        return sessions.ItemQuerySession(bank_id, runtime=self._runtime)",
    "docstring": "Gets the ``OsidSession`` associated with the item query service for the given bank.\n\n        arg:    bank_id (osid.id.Id): the ``Id`` of the bank\n        return: (osid.assessment.ItemQuerySession) - ``an\n                _item_query_session``\n        raise:  NotFound - ``bank_id`` not found\n        raise:  NullArgument - ``bank_id`` is ``null``\n        raise:  OperationFailed - ``unable to complete request``\n        raise:  Unimplemented - ``supports_item_query()`` or\n                ``supports_visible_federation()`` is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_item_query()`` and ``supports_visible_federation()``\n        are ``true``.*"
  },
  {
    "code": "def init_layer(self):\n        self.layer = self.vector.GetLayer()\n        self.__features = [None] * self.nfeatures",
    "docstring": "initialize a layer object\n\n        Returns\n        -------"
  },
  {
    "code": "def _create_dataset(\n            self, group, chunk_size, compression, compression_opts):\n        if chunk_size == 'auto':\n            chunks = True\n        else:\n            per_chunk = (\n                nb_per_chunk(20, 1, chunk_size) if self.dtype == np.dtype('O')\n                else nb_per_chunk(\n                        np.dtype(self.dtype).itemsize, 1, chunk_size))\n            chunks = (per_chunk,)\n        shape = (0,)\n        maxshape = (None,)\n        group.create_dataset(\n            self.name, shape, dtype=self.dtype,\n            chunks=chunks, maxshape=maxshape, compression=compression,\n            compression_opts=compression_opts)",
    "docstring": "Create an empty dataset in a group."
  },
  {
    "code": "def update(self, item):\n        if item.matrix not in self.data:\n            self.data[item.matrix] = []\n        result = Select(self.data[item.matrix]).where(\n            lambda entry: entry.stage == item.stage).build()\n        if len(result) > 0:\n            stage = result[0]\n            stage.status = item.status\n            stage.add(item.timestamp, item.information)\n        else:\n            stage = CollectorStage(stage=item.stage, status=item.status)\n            stage.add(item.timestamp, item.information)\n            self.data[item.matrix].append(stage)",
    "docstring": "Add a collector item.\n\n        Args:\n            item (CollectorUpdate): event data like stage, timestampe and status."
  },
  {
    "code": "def get_mimetype(path):\n        filename = os.path.split(path)[1]\n        mimetype = mimetypes.guess_type(filename)[0]\n        if mimetype is None:\n            mimetype = 'text/x-plain'\n        _logger().debug('mimetype detected: %s', mimetype)\n        return mimetype",
    "docstring": "Guesses the mime type of a file. If mime type cannot be detected, plain\n        text is assumed.\n\n        :param path: path of the file\n        :return: the corresponding mime type."
  },
  {
    "code": "def ssl_server_options():\n    cafile = options.ssl_ca_cert\n    keyfile = options.ssl_key\n    certfile = options.ssl_cert\n    verify_mode = options.ssl_cert_reqs\n    try:\n        context = ssl.create_default_context(\n            purpose=ssl.Purpose.CLIENT_AUTH, cafile=cafile)\n        context.load_cert_chain(certfile=certfile, keyfile=keyfile)\n        context.verify_mode = verify_mode\n        return context\n    except AttributeError:\n        ssl_options = {\n            'ca_certs': cafile,\n            'keyfile': keyfile,\n            'certfile': certfile,\n            'cert_reqs': verify_mode\n        }\n        return ssl_options",
    "docstring": "ssl options for tornado https server\n    these options are defined in each application's default.conf file\n    if left empty, use the self generated keys and certificates included\n    in this package.\n    this function is backward compatible with python version lower than\n    2.7.9 where ssl.SSLContext is not available."
  },
  {
    "code": "def stop_polling(self):\n        if hasattr(self, '_polling') and self._polling:\n            log.info('Stop polling...')\n            self._polling = False",
    "docstring": "Break long-polling process.\n\n        :return:"
  },
  {
    "code": "def click_element_at_coordinates(self, coordinate_X, coordinate_Y):\r\n        self._info(\"Pressing at (%s, %s).\" % (coordinate_X, coordinate_Y))\r\n        driver = self._current_application()\r\n        action = TouchAction(driver)\r\n        action.press(x=coordinate_X, y=coordinate_Y).release().perform()",
    "docstring": "click element at a certain coordinate"
  },
  {
    "code": "def make_relationship(self, relator,\n                          direction=\n                            RELATIONSHIP_DIRECTIONS.BIDIRECTIONAL):\n        if IEntity.providedBy(relator):\n            rel = DomainRelationship(relator, self,\n                                     direction=direction)\n        elif IResource.providedBy(relator):\n            rel = ResourceRelationship(relator, self,\n                                       direction=direction)\n        else:\n            raise ValueError('Invalid relator argument \"%s\" for '\n                             'relationship; must provide IEntity or '\n                             'IResource.' % relator)\n        return rel",
    "docstring": "Create a relationship object for this attribute from the given\n        relator and relationship direction."
  },
  {
    "code": "def get_resource_retriever(url):\n    if url.startswith('http://') or url.startswith('https://'):\n        return HttpResourceRetriever(url)\n    else:\n        raise ValueError('Unsupported scheme in url: %s' % url)",
    "docstring": "Get the appropriate retriever object for the specified url based on url scheme.\n    Makes assumption that HTTP urls do not require any special authorization.\n\n    For HTTP urls: returns HTTPResourceRetriever\n    For s3:// urls returns S3ResourceRetriever\n\n    :param url: url of the resource to be retrieved\n    :return: ResourceRetriever object"
  },
  {
    "code": "def union(self, x, y):\n        repr_x = self.find(x)\n        repr_y = self.find(y)\n        if repr_x == repr_y:\n            return False\n        if self.rank[repr_x] == self.rank[repr_y]:\n            self.rank[repr_x] += 1\n            self.up[repr_y] = repr_x\n        elif self.rank[repr_x] > self.rank[repr_y]:\n            self.up[repr_y] = repr_x\n        else:\n            self.up[repr_x] = repr_y\n        return True",
    "docstring": "Merges part that contain x and part containing y\n\n        :returns: False if x, y are already in same part\n        :complexity: O(inverse_ackerman(n))"
  },
  {
    "code": "def _publish_date(self, item):\n        url = item['url']\n        html = deepcopy(item['spider_response'].body)\n        publish_date = None\n        try:\n            if html is None:\n                request = urllib2.Request(url)\n                html = urllib2.build_opener().open(request).read()\n            html = BeautifulSoup(html, \"lxml\")\n            publish_date = self._extract_from_json(html)\n            if publish_date is None:\n                publish_date = self._extract_from_meta(html)\n            if publish_date is None:\n                publish_date = self._extract_from_html_tag(html)\n            if publish_date is None:\n                publish_date = self._extract_from_url(url)\n        except Exception as e:\n            pass\n        return publish_date",
    "docstring": "Returns the publish_date of the extracted article."
  },
  {
    "code": "def get_base(self):\n    if self._type == 'query':\n      return self._observable.get_query_base()\n    return self._observable.get_target_base()",
    "docstring": "Get the single base at this position.\n\n    :returns: base\n    :rtype: char"
  },
  {
    "code": "def check_key(key, allowed):\n    if key in allowed:\n        return True\n    for pattern in allowed:\n        if fnmatch(key, pattern):\n            return True\n    return False",
    "docstring": "Validate that the specified key is allowed according the provided\n    list of patterns."
  },
  {
    "code": "def _gen_ticket(prefix=None, lg=settings.CAS_TICKET_LEN):\n    random_part = u''.join(\n        random.choice(\n            string.ascii_letters + string.digits\n        ) for _ in range(lg - len(prefix or \"\") - 1)\n    )\n    if prefix is not None:\n        return u'%s-%s' % (prefix, random_part)\n    else:\n        return random_part",
    "docstring": "Generate a ticket with prefix ``prefix`` and length ``lg``\n\n        :param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU)\n        :param int lg: The length of the generated ticket (with the prefix)\n        :return: A randomlly generated ticket of length ``lg``\n        :rtype: unicode"
  },
  {
    "code": "def by_occupied_housing_units(self,\n                                  lower=-1,\n                                  upper=2 ** 31,\n                                  zipcode_type=ZipcodeType.Standard,\n                                  sort_by=SimpleZipcode.occupied_housing_units.name,\n                                  ascending=False,\n                                  returns=DEFAULT_LIMIT):\n        return self.query(\n            occupied_housing_units_lower=lower,\n            occupied_housing_units_upper=upper,\n            sort_by=sort_by, zipcode_type=zipcode_type,\n            ascending=ascending, returns=returns,\n        )",
    "docstring": "Search zipcode information by occupied house of units."
  },
  {
    "code": "def add_bookmark(self, time):\n        if self.annot is None:\n            msg = 'No score file loaded'\n            lg.debug(msg)\n            error_dialog = QErrorMessage()\n            error_dialog.setWindowTitle('Error adding bookmark')\n            error_dialog.showMessage(msg)\n            error_dialog.exec()\n            return\n        answer = QInputDialog.getText(self, 'New Bookmark',\n                                      'Enter bookmark\\'s name')\n        if answer[1]:\n            name = answer[0]\n            self.annot.add_bookmark(name, time)\n            lg.info('Added Bookmark ' + name + 'at ' + str(time))\n        self.update_annotations()",
    "docstring": "Run this function when user adds a new bookmark.\n\n        Parameters\n        ----------\n        time : tuple of float\n            start and end of the new bookmark, in s"
  },
  {
    "code": "def fetch_cvparams_values_from_subel(base, subelname, paramnames, ns):\n    sub_el = basereader.find_element_xpath(base, subelname, ns)\n    cvparams = get_all_cvparams(sub_el, ns)\n    output = []\n    for param in paramnames:\n        output.append(fetch_cvparam_value_by_name(cvparams, param))\n    return output",
    "docstring": "Searches a base element for subelement by name, then takes the\n    cvParams of that subelement and returns the values as a list\n    for the paramnames that match. Value order in list equals input\n    paramnames order."
  },
  {
    "code": "def query_filter(query):\n    try:\n        return {'operation': int(query)}\n    except ValueError:\n        pass\n    if isinstance(query, string_types):\n        query = query.strip()\n        for operation in KNOWN_OPERATIONS:\n            if query.startswith(operation):\n                query = \"%s %s\" % (operation, query[len(operation):].strip())\n                return {'operation': query}\n        if query.startswith('*') and query.endswith('*'):\n            query = \"*= %s\" % query.strip('*')\n        elif query.startswith('*'):\n            query = \"$= %s\" % query.strip('*')\n        elif query.endswith('*'):\n            query = \"^= %s\" % query.strip('*')\n        else:\n            query = \"_= %s\" % query\n    return {'operation': query}",
    "docstring": "Translate a query-style string to a 'filter'.\n\n    Query can be the following formats:\n\n    Case Insensitive\n      'value' OR '*= value'    Contains\n      'value*' OR '^= value'   Begins with value\n      '*value' OR '$= value'   Ends with value\n      '*value*' OR '_= value'  Contains value\n\n    Case Sensitive\n      '~ value'   Contains\n      '!~ value'  Does not contain\n      '> value'   Greater than value\n      '< value'   Less than value\n      '>= value'  Greater than or equal to value\n      '<= value'  Less than or equal to value\n\n    :param string query: query string"
  },
  {
    "code": "def midPoint(self, point):\n        x = (self.x + point.x)/2.0\n        y = (self.y + point.y)/2.0\n        z = (self.z + point.z)/2.0\n        return MapPoint(x,y,z)",
    "docstring": "identify the midpoint between two mapPoints"
  },
  {
    "code": "def legacy_signature(**kwargs_mapping):\n    def signature_decorator(f):\n        @wraps(f)\n        def wrapper(*args, **kwargs):\n            redirected_kwargs = {\n                kwargs_mapping[k] if k in kwargs_mapping else k: v\n                for k, v in kwargs.items()\n            }\n            return f(*args, **redirected_kwargs)\n        return wrapper\n    return signature_decorator",
    "docstring": "This decorator makes it possible to call a function using old argument names\n    when they are passed as keyword arguments.\n\n    @legacy_signature(old_arg1='arg1', old_arg2='arg2')\n    def func(arg1, arg2=1):\n        return arg1 + arg2\n\n    func(old_arg1=1) == 2\n    func(old_arg1=1, old_arg2=2) == 3"
  },
  {
    "code": "def on_hover(self, callback, remove=False):\n        self._hover_callbacks.register_callback(callback, remove=remove)",
    "docstring": "The hover callback takes an unpacked set of keyword arguments."
  },
  {
    "code": "def longitude(self, longitude):\n        if not (-180 <= longitude <= 180):\n            raise ValueError('longitude was {}, but has to be in [-180, 180]'\n                             .format(longitude))\n        self._longitude = longitude",
    "docstring": "Setter for longitude."
  },
  {
    "code": "def get_invocation_command_nodefault(\n    toolset, tool, user_provided_command=[], additional_paths=[], path_last=False):\n    assert isinstance(toolset, basestring)\n    assert isinstance(tool, basestring)\n    assert is_iterable_typed(user_provided_command, basestring)\n    assert is_iterable_typed(additional_paths, basestring) or additional_paths is None\n    assert isinstance(path_last, (int, bool))\n    if not user_provided_command:\n        command = find_tool(tool, additional_paths, path_last)\n        if not command and __debug_configuration:\n            print \"warning: toolset\", toolset, \"initialization: can't find tool, tool\"\n    else:\n        command = check_tool(user_provided_command)\n        if not command and __debug_configuration:\n            print \"warning: toolset\", toolset, \"initialization:\"\n            print \"warning: can't find user-provided command\", user_provided_command\n            command = []\n        if command:\n            command = ' '.join(command)\n    return command",
    "docstring": "A helper rule to get the command to invoke some tool. If\n        'user-provided-command' is not given, tries to find binary named 'tool' in\n        PATH and in the passed 'additional-path'. Otherwise, verifies that the first\n        element of 'user-provided-command' is an existing program.\n\n        This rule returns the command to be used when invoking the tool. If we can't\n        find the tool, a warning is issued. If 'path-last' is specified, PATH is\n        checked after 'additional-paths' when searching for 'tool'."
  },
  {
    "code": "def setDefaultColorRamp(self, colorRampEnum=ColorRampEnum.COLOR_RAMP_HUE):\n        self._colorRamp = ColorRampGenerator.generateDefaultColorRamp(colorRampEnum)",
    "docstring": "Returns the color ramp as a list of RGB tuples"
  },
  {
    "code": "def unshare_project(project_id, usernames,**kwargs):\n    user_id = kwargs.get('user_id')\n    proj_i = _get_project(project_id)\n    proj_i.check_share_permission(user_id)\n    for username in usernames:\n        user_i = _get_user(username)\n        proj_i.unset_owner(user_i.id, write=write, share=share)\n    db.DBSession.flush()",
    "docstring": "Un-share a project with a list of users, identified by their usernames."
  },
  {
    "code": "def close_multicast_socket(sock, address):\n    if sock is None:\n        return\n    if address:\n        mreq = make_mreq(sock.family, address)\n        if sock.family == socket.AF_INET:\n            sock.setsockopt(socket.IPPROTO_IP, socket.IP_DROP_MEMBERSHIP, mreq)\n        elif sock.family == socket.AF_INET6:\n            sock.setsockopt(ipproto_ipv6(), socket.IPV6_LEAVE_GROUP, mreq)\n    sock.close()",
    "docstring": "Cleans up the given multicast socket.\n    Unregisters it of the multicast group.\n\n    Parameters should be the result of create_multicast_socket\n\n    :param sock: A multicast socket\n    :param address: The multicast address used by the socket"
  },
  {
    "code": "def get_source_by_name(self, name):\n        srcs = self.get_sources_by_name(name)\n        if len(srcs) == 1:\n            return srcs[0]\n        elif len(srcs) == 0:\n            raise Exception('No source matching name: ' + name)\n        elif len(srcs) > 1:\n            raise Exception('Multiple sources matching name: ' + name)",
    "docstring": "Return a single source in the ROI with the given name.  The\n        input name string can match any of the strings in the names\n        property of the source object.  Case and whitespace are\n        ignored when matching name strings.  If no sources are found\n        or multiple sources then an exception is thrown.\n\n        Parameters\n        ----------\n        name : str \n           Name string.\n\n        Returns\n        -------\n        srcs : `~fermipy.roi_model.Model`\n           A source object."
  },
  {
    "code": "def flush(self):\n        if self.triggered and len(self.buffer) > 0:\n            text = []\n            for record in self.buffer:\n                terminator = getattr(record, 'terminator', '\\n')\n                s = self.format(record)\n                if terminator is not None:\n                    text.append(s + terminator)\n                else:\n                    text.append(s)\n            msg = MIMEText(''.join(text))\n            msg['From'] = self.fromAddr\n            msg['To'] = self.toAddr\n            msg['Subject'] = self.subject\n            smtp = smtplib.SMTP('localhost')\n            smtp.sendmail(self.fromAddr, [self.toAddr], msg.as_string())\n            smtp.quit()\n        self.buffer = []",
    "docstring": "Send messages by e-mail.\n\n        The sending of messages is suppressed if a trigger severity\n        level has been set and none of the received messages was at\n        that level or above. In that case the messages are\n        discarded. Empty e-mails are discarded."
  },
  {
    "code": "def reset_default_props(**kwargs):\n    global _DEFAULT_PROPS\n    pcycle = plt.rcParams['axes.prop_cycle']\n    _DEFAULT_PROPS = {\n        'color': itertools.cycle(_get_standard_colors(**kwargs))\n        if len(kwargs) > 0 else itertools.cycle([x['color'] for x in pcycle]),\n        'marker': itertools.cycle(['o', 'x', '.', '+', '*']),\n        'linestyle': itertools.cycle(['-', '--', '-.', ':']),\n    }",
    "docstring": "Reset properties to initial cycle point"
  },
  {
    "code": "def reset(self):\n        for key in list(self.keys()): self.iterators[key] = _itertools.cycle(self[key])\n        return self",
    "docstring": "Resets the style cycle."
  },
  {
    "code": "def get_object(self, view_kwargs, qs=None):\n        self.before_get_object(view_kwargs)\n        id_field = getattr(self, 'id_field', inspect(self.model).primary_key[0].key)\n        try:\n            filter_field = getattr(self.model, id_field)\n        except Exception:\n            raise Exception(\"{} has no attribute {}\".format(self.model.__name__, id_field))\n        url_field = getattr(self, 'url_field', 'id')\n        filter_value = view_kwargs[url_field]\n        query = self.retrieve_object_query(view_kwargs, filter_field, filter_value)\n        if qs is not None:\n            query = self.eagerload_includes(query, qs)\n        try:\n            obj = query.one()\n        except NoResultFound:\n            obj = None\n        self.after_get_object(obj, view_kwargs)\n        return obj",
    "docstring": "Retrieve an object through sqlalchemy\n\n        :params dict view_kwargs: kwargs from the resource view\n        :return DeclarativeMeta: an object from sqlalchemy"
  },
  {
    "code": "def stop_workers(self, _join_arbiter=True):\n        self._must_stop.set()\n        self._workers.stop()\n        self._result_notifier.join()\n        self._broker.stop()\n        if _join_arbiter:\n            self._arbiter.join()\n        self._reset()",
    "docstring": "Stop the workers and wait for them to terminate."
  },
  {
    "code": "def resume_trial(self, trial):\n        assert trial.status == Trial.PAUSED, trial.status\n        self.start_trial(trial)",
    "docstring": "Resumes PAUSED trials. This is a blocking call."
  },
  {
    "code": "def RemoveEventHandler(self, wb):\n\t\tfrom UcsBase import WriteUcsWarning\n\t\tif wb in self._wbs:\n\t\t\tself._remove_watch_block(wb)\n\t\telse:\n\t\t\tWriteUcsWarning(\"Event handler not found\")",
    "docstring": "Removes an event handler."
  },
  {
    "code": "async def shutdown(self):\n        if self.log_output:\n            logging.info('Shutting down ...')\n        else:\n            print('Shutting down ...')\n        await self.send_reset()\n        try:\n            self.loop.stop()\n        except:\n            pass\n        try:\n            self.loop.close()\n        except:\n            pass\n        sys.exit(0)",
    "docstring": "This method attempts an orderly shutdown\n        If any exceptions are thrown, just ignore them.\n\n        :returns: No return value"
  },
  {
    "code": "def clone_repo(self):\n        tempdir_path = tempfile.mkdtemp()\n        if self.args.git:\n            self.log.debug('Cloning git source repository from %s to %s',\n                           self.source, tempdir_path)\n            self.sh('git clone', self.source, tempdir_path)\n        else:\n            raise NotImplementedError('Unknown repo type')\n        self.source = tempdir_path",
    "docstring": "Clone a repository containing the dotfiles source."
  },
  {
    "code": "def create_pipe(backend_p):\n        return Zsock(lib.zsys_create_pipe(byref(zsock_p.from_param(backend_p))), False)",
    "docstring": "Create a pipe, which consists of two PAIR sockets connected over inproc.\nThe pipe is configured to use the zsys_pipehwm setting. Returns the\nfrontend socket successful, NULL if failed."
  },
  {
    "code": "def config():\n    cfg = ConfigParser()\n    cfg.read(os.path.join(os.path.dirname(os.path.realpath(ips_vagrant.__file__)), 'config/ipsv.conf'))\n    return cfg",
    "docstring": "Load system configuration\n    @rtype: ConfigParser"
  },
  {
    "code": "async def sound(dev: Device, target, value):\n    if target and value:\n        click.echo(\"Setting %s to %s\" % (target, value))\n        click.echo(await dev.set_sound_settings(target, value))\n    print_settings(await dev.get_sound_settings())",
    "docstring": "Get or set sound settings."
  },
  {
    "code": "def Gaussian_filter(x, sigma, norm=True):\n    r\n    x = check_float(x)\n    sigma = check_float(sigma)\n    val = np.exp(-0.5 * (x / sigma) ** 2)\n    if norm:\n        return val / (np.sqrt(2 * np.pi) * sigma)\n    else:\n        return val",
    "docstring": "r\"\"\"Gaussian filter\n\n    This method implements a Gaussian filter.\n\n    Parameters\n    ----------\n    x : float\n        Input data point\n    sigma : float\n        Standard deviation (filter scale)\n    norm : bool\n        Option to return normalised data. Default (norm=True)\n\n    Returns\n    -------\n    float Gaussian filtered data point\n\n    Examples\n    --------\n    >>> from modopt.signal.filter import Gaussian_filter\n    >>> Gaussian_filter(1, 1)\n    0.24197072451914337\n\n    >>> Gaussian_filter(1, 1, False)\n    0.60653065971263342"
  },
  {
    "code": "def sample(self, bqm, beta_range=None, num_reads=10, num_sweeps=1000):\n        if not isinstance(num_reads, int):\n            raise TypeError(\"'samples' should be a positive integer\")\n        if num_reads < 1:\n            raise ValueError(\"'samples' should be a positive integer\")\n        h, J, offset = bqm.to_ising()\n        samples = []\n        energies = []\n        for __ in range(num_reads):\n            sample, energy = ising_simulated_annealing(h, J, beta_range, num_sweeps)\n            samples.append(sample)\n            energies.append(energy)\n        response = SampleSet.from_samples(samples, Vartype.SPIN, energies)\n        response.change_vartype(bqm.vartype, offset, inplace=True)\n        return response",
    "docstring": "Sample from low-energy spin states using simulated annealing.\n\n        Args:\n            bqm (:obj:`.BinaryQuadraticModel`):\n                Binary quadratic model to be sampled from.\n\n            beta_range (tuple, optional): Beginning and end of the beta schedule\n                (beta is the inverse temperature) as a 2-tuple. The schedule is applied\n                linearly in beta. Default is chosen based on the total bias associated\n                with each node.\n\n            num_reads (int, optional, default=10):\n                Number of reads. Each sample is the result of a single run of\n                the simulated annealing algorithm.\n\n            num_sweeps (int, optional, default=1000):\n                Number of sweeps or steps.\n\n        Returns:\n            :obj:`.SampleSet`\n\n        Note:\n            This is a reference implementation, not optimized for speed\n            and therefore not an appropriate sampler for benchmarking."
  },
  {
    "code": "def getPWMFrequency(self, device=DEFAULT_DEVICE_ID, message=True):\n        return self._getPWMFrequency(device, message)",
    "docstring": "Get the motor shutdown on error status stored on the hardware device.\n\n        :Keywords:\n          device : `int`\n            The device is the integer number of the hardware devices ID and\n            is only used with the Pololu Protocol. Defaults to the hardware's\n            default value.\n          message : `bool`\n            If set to `True` a text message will be returned, if set to `False`\n            the integer stored in the Qik will be returned.\n\n        :Returns:\n          A text message or an int. See the `message` parameter above."
  },
  {
    "code": "def parse_pdb_ligand_info(self, pdb_ligand_info):\n        mtchs = re.findall('(<ligand.*?</ligand>)', pdb_ligand_info, re.DOTALL)\n        for m in mtchs:\n            if m.upper().find('CHEMICALID=\"{0}\"'.format(self.PDBCode.upper())) != -1:\n                ligand_type = re.match('<ligand.*?\\stype=\"(.*?)\".*?>', m, re.DOTALL)\n                if ligand_type:\n                    self.LigandType = ligand_type.group(1)",
    "docstring": "This only parses the ligand type as all the other information should be in the .cif file. The XML file has\n           proper capitalization whereas the .cif file uses all caps for the ligand type."
  },
  {
    "code": "def edit_imagefindpars():\n    teal.teal(imagefindpars.__taskname__, returnAs=None,\n              autoClose=True, loadOnly=False, canExecute=False)",
    "docstring": "Allows the user to edit the imagefindpars configObj in a TEAL GUI"
  },
  {
    "code": "def count(self, path):\n        try:\n            res = self.get_bite().count(self.list_path(path)).next()\n            dir_count = res['directoryCount']\n            file_count = res['fileCount']\n            content_size = res['spaceConsumed']\n        except StopIteration:\n            dir_count = file_count = content_size = 0\n        return {'content_size': content_size, 'dir_count': dir_count,\n                'file_count': file_count}",
    "docstring": "Use snakebite.count, if available.\n\n        :param path: directory to count the contents of\n        :type path: string\n        :return: dictionary with content_size, dir_count and file_count keys"
  },
  {
    "code": "def _boosted_value(name, action, key, value, boost):\n    if boost is not None:\n        value_key = 'query' if action in MATCH_ACTIONS else 'value'\n        return {name: {'boost': boost, value_key: value}}\n    return {name: value}",
    "docstring": "Boost a value if we should in _process_queries"
  },
  {
    "code": "def search_file(search_root, search_filename,\n                    instance_relative_root=False):\n        if instance_relative_root:\n            search_root = os.path.join(current_app.instance_path, search_root)\n        file_path = None\n        file_ext = None\n        for file in os.listdir(search_root):\n            filename, ext = os.path.splitext(file)\n            if filename == search_filename and ext and ext != '.':\n                file_path = os.path.join(search_root, filename + ext)\n                file_ext = ext[1:]\n                break\n        return file_path, file_ext",
    "docstring": "Search for a filename in a specific search root dir.\n\n        :param search_root: root dir to search\n        :param search_filename: filename to search (no extension)\n        :param instance_relative_root: search root is relative to instance path\n        :return: tuple(full_file_path, extension without heading dot)"
  },
  {
    "code": "def map_tree(visitor, tree):\n    newn = [map_tree(visitor, node) for node in tree.nodes]\n    return visitor(tree, newn)",
    "docstring": "Apply function to nodes"
  },
  {
    "code": "def get_initial(self, form, name):\n        if hasattr(form, 'initial'):\n            return form.initial.get(name, None)\n        return None",
    "docstring": "Get the initial data that got passed into the superform for this\n        composite field. It should return ``None`` if no initial values where\n        given."
  },
  {
    "code": "def tidy(fnames):\n    for fname in fnames:\n        try:\n            node = nrml.read(fname)\n        except ValueError as err:\n            print(err)\n            return\n        with open(fname + '.bak', 'wb') as f:\n            f.write(open(fname, 'rb').read())\n        with open(fname, 'wb') as f:\n            nrml.write(node.nodes, f, writers.FIVEDIGITS, xmlns=node['xmlns'])\n        print('Reformatted %s, original left in %s.bak' % (fname, fname))",
    "docstring": "Reformat a NRML file in a canonical form. That also means reducing the\n    precision of the floats to a standard value. If the file is invalid,\n    a clear error message is shown."
  },
  {
    "code": "def children(self):\n        children = []\n        child_nodes = getattr(self.parsed_response, 'Children')\n        for child in getattr(child_nodes, 'BrowseNode', []):\n            children.append(AmazonBrowseNode(child))\n        return children",
    "docstring": "This browse node's children in the browse node tree.\n\n    :return:\n    A list of this browse node's children in the browse node tree."
  },
  {
    "code": "def add_pr_curve(self, tag, labels, predictions, num_thresholds,\n                     global_step=None, weights=None):\n        if num_thresholds < 2:\n            raise ValueError('num_thresholds must be >= 2')\n        labels = _make_numpy_array(labels)\n        predictions = _make_numpy_array(predictions)\n        self._file_writer.add_summary(pr_curve_summary(tag, labels, predictions,\n                                                       num_thresholds, weights), global_step)",
    "docstring": "Adds precision-recall curve.\n\n        Note: This function internally calls `asnumpy()` for MXNet `NDArray` inputs.\n        Since `asnumpy()` is a blocking function call, this function would block the main\n        thread till it returns. It may consequently affect the performance of async execution\n        of the MXNet engine.\n\n        Parameters\n        ----------\n            tag : str\n                A tag attached to the summary. Used by TensorBoard for organization.\n            labels : MXNet `NDArray` or `numpy.ndarray`.\n                The ground truth values. A tensor of 0/1 values with arbitrary shape.\n            predictions : MXNet `NDArray` or `numpy.ndarray`.\n                A float32 tensor whose values are in the range `[0, 1]`. Dimensions must match\n                those of `labels`.\n            num_thresholds : int\n                Number of thresholds, evenly distributed in `[0, 1]`, to compute PR metrics for.\n                Should be `>= 2`. This value should be a constant integer value, not a tensor\n                that stores an integer.\n                The thresholds for computing the pr curves are calculated in the following way:\n                `width = 1.0 / (num_thresholds - 1),\n                thresholds = [0.0, 1*width, 2*width, 3*width, ..., 1.0]`.\n            global_step : int\n                Global step value to record.\n            weights : MXNet `NDArray` or `numpy.ndarray`.\n                Optional float32 tensor. Individual counts are multiplied by this value.\n                This tensor must be either the same shape as or broadcastable to the `labels`\n                tensor."
  },
  {
    "code": "def get_folders(self):\n        endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/'\n        r = requests.get(endpoint, headers=self._headers)\n        if check_response(r):\n            return Folder._json_to_folders(self, r.json())",
    "docstring": "Returns a list of all folders for this account\n\n            Returns:\n                List[:class:`Folder <pyOutlook.core.folder.Folder>`]"
  },
  {
    "code": "def error(message, code=1):\n    if message:\n        print('ERROR: {0}'.format(message), file=sys.stderr)\n    else:\n        print(file=sys.stderr)\n    sys.exit(code)",
    "docstring": "Prints an error message to stderr and exits with a status of 1 by default."
  },
  {
    "code": "def open(self, page, parms=None, payload=None, HTTPrequest=None ):\n        response = self.open_raw( page, parms, payload, HTTPrequest )\n        return response.read()",
    "docstring": "Opens a page from the server with optional content.  Returns the string response."
  },
  {
    "code": "def default_preference_list(self, prefs):\n        prefs = _check_preferences(prefs)\n        if prefs is not None:\n            self._prefs = prefs",
    "docstring": "Set the default preference list.\n\n        :param str prefs: A string containing the default preferences for\n                          ciphers, digests, and compression algorithms."
  },
  {
    "code": "def createStaticLibBuilder(env):\n    try:\n        static_lib = env['BUILDERS']['StaticLibrary']\n    except KeyError:\n        action_list = [ SCons.Action.Action(\"$ARCOM\", \"$ARCOMSTR\") ]\n        if env.get('RANLIB',False) or env.Detect('ranlib'):\n            ranlib_action = SCons.Action.Action(\"$RANLIBCOM\", \"$RANLIBCOMSTR\")\n            action_list.append(ranlib_action)\n        static_lib = SCons.Builder.Builder(action = action_list,\n                                           emitter = '$LIBEMITTER',\n                                           prefix = '$LIBPREFIX',\n                                           suffix = '$LIBSUFFIX',\n                                           src_suffix = '$OBJSUFFIX',\n                                           src_builder = 'StaticObject')\n        env['BUILDERS']['StaticLibrary'] = static_lib\n        env['BUILDERS']['Library'] = static_lib\n    return static_lib",
    "docstring": "This is a utility function that creates the StaticLibrary\n    Builder in an Environment if it is not there already.\n\n    If it is already there, we return the existing one."
  },
  {
    "code": "def raise_for_missing_namespace(self, line: str, position: int, namespace: str, name: str) -> None:\n        if not self.has_namespace(namespace):\n            raise UndefinedNamespaceWarning(self.get_line_number(), line, position, namespace, name)",
    "docstring": "Raise an exception if the namespace is not defined."
  },
  {
    "code": "def is_empty(value, msg=None, except_=None, inc_zeros=True):\n    if hasattr(value, 'empty'):\n        value = not bool(value.empty)\n    elif inc_zeros and value in ZEROS:\n        value = True\n    else:\n        pass\n    _is_null = is_null(value, except_=False)\n    result = bool(_is_null or not value)\n    if except_:\n        return is_true(result, msg=msg, except_=except_)\n    else:\n        return bool(result)",
    "docstring": "is defined, but null or empty like value"
  },
  {
    "code": "def update(self, other):\n        if not isinstance(other, CtsTextgroupMetadata):\n            raise TypeError(\"Cannot add %s to CtsTextgroupMetadata\" % type(other))\n        elif str(self.urn) != str(other.urn):\n            raise InvalidURN(\"Cannot add CtsTextgroupMetadata %s to CtsTextgroupMetadata %s \" % (self.urn, other.urn))\n        for urn, work in other.works.items():\n            if urn in self.works:\n                self.works[urn].update(deepcopy(work))\n            else:\n                self.works[urn] = deepcopy(work)\n            self.works[urn].parent = self\n            self.works[urn].resource = None\n        return self",
    "docstring": "Merge two Textgroup Objects.\n\n        - Original (left Object) keeps his parent.\n        - Added document merges with work if it already exists\n\n        :param other: Textgroup object\n        :type other: CtsTextgroupMetadata\n        :return: Textgroup Object\n        :rtype: CtsTextgroupMetadata"
  },
  {
    "code": "def discover() -> List[Tuple[str, str]]:\n    if IS_ROBOT and os.path.isdir('/dev/modules'):\n        devices = os.listdir('/dev/modules')\n    else:\n        devices = []\n    discovered_modules = []\n    module_port_regex = re.compile('|'.join(MODULE_TYPES.keys()), re.I)\n    for port in devices:\n        match = module_port_regex.search(port)\n        if match:\n            name = match.group().lower()\n            if name not in MODULE_TYPES:\n                log.warning(\"Unexpected module connected: {} on {}\"\n                            .format(name, port))\n                continue\n            absolute_port = '/dev/modules/{}'.format(port)\n            discovered_modules.append((absolute_port, name))\n    log.info('Discovered modules: {}'.format(discovered_modules))\n    return discovered_modules",
    "docstring": "Scan for connected modules and instantiate handler classes"
  },
  {
    "code": "def run_pipeline(pipeline,\n                 context,\n                 pipeline_context_input=None,\n                 parse_input=True):\n    logger.debug(\"starting\")\n    try:\n        if parse_input:\n            logger.debug(\"executing context_parser\")\n            prepare_context(pipeline=pipeline,\n                            context_in_string=pipeline_context_input,\n                            context=context)\n        else:\n            logger.debug(\"skipping context_parser\")\n        pypyr.stepsrunner.run_step_group(\n            pipeline_definition=pipeline,\n            step_group_name='steps',\n            context=context)\n        logger.debug(\"pipeline steps complete. Running on_success steps now.\")\n        pypyr.stepsrunner.run_step_group(\n            pipeline_definition=pipeline,\n            step_group_name='on_success',\n            context=context)\n    except Exception:\n        logger.error(\"Something went wrong. Will now try to run on_failure.\")\n        pypyr.stepsrunner.run_failure_step_group(\n            pipeline=pipeline,\n            context=context)\n        logger.debug(\"Raising original exception to caller.\")\n        raise\n    logger.debug(\"done\")",
    "docstring": "Run the specified pypyr pipeline.\n\n    This function runs the actual pipeline. If you are running another\n    pipeline from within a pipeline, call this, not main(). Do call main()\n    instead for your 1st pipeline if there are pipelines calling pipelines.\n\n    Pipeline and context should be already loaded.\n\n    Args:\n        pipeline (dict): Dictionary representing the pipeline.\n        context (pypyr.context.Context): Reusable context object.\n        pipeline_context_input (str): Initialize the pypyr context with this\n                                string.\n        parse_input (bool): run context_parser in pipeline.\n\n    Returns:\n        None"
  },
  {
    "code": "def pretty_polyfit_plot(x, y, deg=1, xlabel=None, ylabel=None, **kwargs):\n    plt = pretty_plot(**kwargs)\n    pp = np.polyfit(x, y, deg)\n    xp = np.linspace(min(x), max(x), 200)\n    plt.plot(xp, np.polyval(pp, xp), 'k--', x, y, 'o')\n    if xlabel:\n        plt.xlabel(xlabel)\n    if ylabel:\n        plt.ylabel(ylabel)\n    return plt",
    "docstring": "Convenience method to plot data with trend lines based on polynomial fit.\n\n    Args:\n        x: Sequence of x data.\n        y: Sequence of y data.\n        deg (int): Degree of polynomial. Defaults to 1.\n        xlabel (str): Label for x-axis.\n        ylabel (str): Label for y-axis.\n        \\\\*\\\\*kwargs: Keyword args passed to pretty_plot.\n\n    Returns:\n        matplotlib.pyplot object."
  },
  {
    "code": "def DEFAULT_NULLVALUE(test):\n    return False if isinstance(test,bool) \\\n           else 0 if isinstance(test,int) \\\n           else 0.0 if isinstance(test,float) \\\n           else ''",
    "docstring": "Returns a null value for each of various kinds of test values.\n\n    **Parameters**\n\n            **test** :  bool, int, float or string\n\n                    Value to test.\n\n\n    **Returns**\n            **null** :  element in `[False, 0, 0.0, '']`\n\n                    Null value corresponding to the given test value:\n\n                    *   if `test` is a `bool`, return `False`\n                    *   else if `test` is an `int`, return `0`\n                    *   else if `test` is a `float`, return `0.0`\n                    *   else `test` is a `str`, return `''`"
  },
  {
    "code": "def fit(self, sequences, y=None):\n        super(BACE, self).fit(sequences, y=y)\n        if self.n_macrostates is not None:\n            self._do_lumping()\n        else:\n            raise RuntimeError('n_macrostates must not be None to fit')\n        return self",
    "docstring": "Fit a BACE lumping model using a sequence of cluster assignments.\n\n        Parameters\n        ----------\n        sequences : list(np.ndarray(dtype='int'))\n            List of arrays of cluster assignments\n        y : None\n            Unused, present for sklearn compatibility only.\n\n        Returns\n        -------\n        self"
  },
  {
    "code": "def _handle_join_dags(self, request):\n        if request.payload['names'] is None:\n            send_response = len(self._dags_running) <= 1\n        else:\n            send_response = all([name not in self._dags_running.keys()\n                                 for name in request.payload['names']])\n        if send_response:\n            return Response(success=True, uid=request.uid)\n        else:\n            return None",
    "docstring": "The handler for the join_dags request.\n\n        If dag names are given in the payload only return a valid Response if none of\n        the dags specified by the names are running anymore. If no dag names are given,\n        wait for all dags except one, which by design is the one that issued the request,\n        to be finished.\n\n        Args:\n            request (Request): Reference to a request object containing the\n                               incoming request.\n\n        Returns:\n            Response: A response object containing the following fields:\n                          - success: True if all dags the request was waiting for have\n                                     completed."
  },
  {
    "code": "def as_dict(self):\n        out = {}\n        for prop in self:\n            propval = getattr(self, prop)\n            if hasattr(propval, 'for_json'):\n                out[prop] = propval.for_json()\n            elif isinstance(propval, list):\n                out[prop] = [getattr(x, 'for_json', lambda:x)() for x in propval]\n            elif isinstance(propval, (ProtocolBase, LiteralValue)):\n                out[prop] = propval.as_dict()\n            elif propval is not None:\n                out[prop] = propval\n        return out",
    "docstring": "Return a dictionary containing the current values\n        of the object.\n\n        Returns:\n            (dict): The object represented as a dictionary"
  },
  {
    "code": "def list_udfs(self, database=None, like=None):\n        if not database:\n            database = self.current_database\n        statement = ddl.ListFunction(database, like=like, aggregate=False)\n        with self._execute(statement, results=True) as cur:\n            result = self._get_udfs(cur, udf.ImpalaUDF)\n        return result",
    "docstring": "Lists all UDFs associated with given database\n\n        Parameters\n        ----------\n        database : string\n        like : string for searching (optional)"
  },
  {
    "code": "def get_query_cache_key(compiler):\n    sql, params = compiler.as_sql()\n    check_parameter_types(params)\n    cache_key = '%s:%s:%s' % (compiler.using, sql,\n                              [text_type(p) for p in params])\n    return sha1(cache_key.encode('utf-8')).hexdigest()",
    "docstring": "Generates a cache key from a SQLCompiler.\n\n    This cache key is specific to the SQL query and its context\n    (which database is used).  The same query in the same context\n    (= the same database) must generate the same cache key.\n\n    :arg compiler: A SQLCompiler that will generate the SQL query\n    :type compiler: django.db.models.sql.compiler.SQLCompiler\n    :return: A cache key\n    :rtype: int"
  },
  {
    "code": "def extract_feature_dependent_feature(self, extractor, force_extraction=False, verbose=0, add_args=None,\n                                          custom_name=None):\n        if self._prepopulated is False:\n            raise errors.EmptyDatabase(self.dbpath)\n        else:\n            return extract_feature_dependent_feature_base(self.dbpath, self.path_to_set, self._set_object, extractor,\n                                                          force_extraction, verbose, add_args, custom_name)",
    "docstring": "Extracts a feature which may be dependent on other features and stores it in the database\n\n        Parameters\n        ----------\n        extractor : function, which takes the path of a data point, a dictionary of all other features and *args as\n        parameters and returns a feature\n        force_extraction : boolean, if True - will re-extract feature even if a feature with this name already\n        exists in the database, otherwise, will only extract if the feature doesn't exist in the database.\n        default value: False\n        verbose : int, if bigger than 0, will print the current number of the file for which data is being extracted\n        add_args : optional arguments for the extractor (list/dictionary/tuple/whatever). if None, the\n        extractor should take only one input argument - the file path. default value: None\n        custom_name : string, optional name for the feature (it will be stored in the database with the custom_name\n        instead of extractor function name). if None, the extractor function name will be used. default value: None\n\n        Returns\n        -------\n        None"
  },
  {
    "code": "def empty_bar_plot(ax):\n    plt.sca(ax)\n    plt.setp(plt.gca(),xticks=[],xticklabels=[]) \n    return ax",
    "docstring": "Delete all axis ticks and labels"
  },
  {
    "code": "def register_file(self, filepath, creator, status=FileStatus.no_file, flags=FileFlags.no_flags):\n        try:\n            file_handle = self.get_handle(filepath)\n            raise KeyError(\"File %s already exists in archive\" % filepath)\n        except KeyError:\n            pass\n        localpath = self._get_localpath(filepath)\n        if status == FileStatus.exists:\n            fullpath = self._get_fullpath(filepath)\n            if not os.path.exists(fullpath):\n                print(\"register_file called on called on mising file %s\" % fullpath)\n                status = FileStatus.missing\n                timestamp = 0\n            else:\n                timestamp = int(os.stat(fullpath).st_mtime)\n        else:\n            timestamp = 0\n        key = len(self._table) + 1\n        file_handle = FileHandle(path=localpath,\n                                 key=key,\n                                 creator=creator,\n                                 timestamp=timestamp,\n                                 status=status,\n                                 flags=flags)\n        file_handle.append_to_table(self._table)\n        self._cache[localpath] = file_handle\n        return file_handle",
    "docstring": "Register a file in the archive.\n\n        If the file already exists, this raises a `KeyError`\n\n        Parameters\n        ----------\n\n        filepath : str\n            The path to the file\n        creatror : int\n            A unique key for the job that created this file\n        status   : `FileStatus`\n            Enumeration giving current status of file\n        flags   : `FileFlags`\n            Enumeration giving flags set on this file\n\n        Returns `FileHandle`"
  },
  {
    "code": "def describe(self):\n        return {\n            \"name\": self.name,\n            \"params\": self.params,\n            \"returns\": self.returns,\n            \"description\": self.description,\n        }",
    "docstring": "Describes the method.\n\n        :return: Description\n        :rtype: dict[str, object]"
  },
  {
    "code": "def calc(self, x:Image, *args:Any, **kwargs:Any)->Image:\n        \"Apply to image `x`, wrapping it if necessary.\"\n        if self._wrap: return getattr(x, self._wrap)(self.func, *args, **kwargs)\n        else:          return self.func(x, *args, **kwargs)",
    "docstring": "Apply to image `x`, wrapping it if necessary."
  },
  {
    "code": "def _verify_credentials(self):\n        r = requests.get(self.apiurl + \"account/verify_credentials.xml\",\n                         auth=HTTPBasicAuth(self._username, self._password),\n                         headers=self.header)\n        if r.status_code != 200:\n            raise UserLoginFailed(\"Username or Password incorrect.\")",
    "docstring": "An internal method that verifies the credentials given at instantiation.\n\n        :raises: :class:`Pymoe.errors.UserLoginFailed`"
  },
  {
    "code": "def ConnectNoSSL(host='localhost', port=443, user='root', pwd='',\n                 service=\"hostd\", adapter=\"SOAP\", namespace=None, path=\"/sdk\",\n                 version=None, keyFile=None, certFile=None, thumbprint=None,\n                 b64token=None, mechanism='userpass'):\n   if hasattr(ssl, '_create_unverified_context'):\n      sslContext = ssl._create_unverified_context()\n   else:\n      sslContext = None\n   return Connect(host=host,\n                  port=port,\n                  user=user,\n                  pwd=pwd,\n                  service=service,\n                  adapter=adapter,\n                  namespace=namespace,\n                  path=path,\n                  version=version,\n                  keyFile=keyFile,\n                  certFile=certFile,\n                  thumbprint=thumbprint,\n                  sslContext=sslContext,\n                  b64token=b64token,\n                  mechanism=mechanism)",
    "docstring": "Provides a standard method for connecting to a specified server without SSL\n   verification. Useful when connecting to servers with self-signed certificates\n   or when you wish to ignore SSL altogether. Will attempt to create an unverified\n   SSL context and then connect via the Connect method."
  },
  {
    "code": "def load_and_print_resfile(filename, info_dict=None):\n    if info_dict is None:\n        info_dict = dict()\n        info_dict[\"mass\"] = 1.23\n        info_dict[\"nom_cap\"] = 3600\n        info_dict[\"tot_mass\"] = 2.33\n    d = CellpyData()\n    print(\"filename:\", filename)\n    print(\"info_dict in:\", end=' ')\n    print(info_dict)\n    d.from_raw(filename)\n    d.set_mass(info_dict[\"mass\"])\n    d.make_step_table()\n    d.make_summary()\n    for test in d.datasets:\n        print(\"newtest\")\n        print(test)\n    return info_dict",
    "docstring": "Load a raw data file and print information.\n\n    Args:\n        filename (str): name of the resfile.\n        info_dict (dict):\n\n    Returns:\n        info (str): string describing something."
  },
  {
    "code": "def is_templatetags_module_valid_constant(node):\n    if node.name not in ('register', ):\n        return False\n    parent = node.parent\n    while not isinstance(parent, Module):\n        parent = parent.parent\n    if \"templatetags.\" not in parent.name:\n        return False\n    return True",
    "docstring": "Suppress warnings for valid constants in templatetags module."
  },
  {
    "code": "def split_next_and_previous_event_columns(self, requested_columns):\n        def next_or_previous(c):\n            if c in self.next_value_columns:\n                return 'next'\n            elif c in self.previous_value_columns:\n                return 'previous'\n            raise ValueError(\n                \"{c} not found in next_value_columns \"\n                \"or previous_value_columns\".format(c=c)\n            )\n        groups = groupby(next_or_previous, requested_columns)\n        return groups.get('next', ()), groups.get('previous', ())",
    "docstring": "Split requested columns into columns that should load the next known\n        value and columns that should load the previous known value.\n\n        Parameters\n        ----------\n        requested_columns : iterable[BoundColumn]\n\n        Returns\n        -------\n        next_cols, previous_cols : iterable[BoundColumn], iterable[BoundColumn]\n            ``requested_columns``, partitioned into sub-sequences based on\n            whether the column should produce values from the next event or the\n            previous event"
  },
  {
    "code": "def on_tape(*files):\n    for path in files:\n        try:\n            if os.stat(path).st_blocks == 0:\n                return True\n        except AttributeError:\n            return False\n    return False",
    "docstring": "Determine whether any of the given files are on tape\n\n    Parameters\n    ----------\n    *files : `str`\n        one or more paths to GWF files\n\n    Returns\n    -------\n    True/False : `bool`\n        `True` if any of the files are determined to be on tape,\n        otherwise `False`"
  },
  {
    "code": "def _add_default_entries(input_dict, defaults_dict):\n    for key, value in defaults_dict.iteritems():\n        if key == 'patients':\n            print('Cannot default `patients`.')\n            continue\n        if isinstance(value, dict):\n            if key not in input_dict or input_dict[key] is None:\n                input_dict[key] = value\n            else:\n                r = _add_default_entries(input_dict.get(key, {}), value)\n                input_dict[key] = r\n        else:\n            if key not in input_dict or input_dict[key] is None:\n                input_dict[key] = value\n    return input_dict",
    "docstring": "Add the entries in defaults dict into input_dict if they don't exist in input_dict\n\n    This is based on the accepted answer at\n    http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth\n\n    :param dict input_dict: The dict to be updated\n    :param dict defaults_dict: Dict containing the defaults for entries in input_dict\n    :return: updated dict\n    :rtype: dict"
  },
  {
    "code": "def scan(cls, filter_builder=None, **scan_filter):\n        scan_kwargs = {'scan_filter': build_condition(scan_filter)}\n        if filter_builder:\n            cls._build_filter_expression(filter_builder, scan_kwargs)\n        return ResultSet(cls, 'scan', scan_kwargs)",
    "docstring": "High level scan API.\n\n        :param filter_builder: filter expression builder.\n        :type filter_builder: :class:`~bynamodb.filterexps.Operator`"
  },
  {
    "code": "def update_dict(d, u):\n    for key, val in u.items():\n        if isinstance(val, collections.Mapping):\n            d[key] = update_dict(d.get(key, {}), val)\n        else:\n            d[key] = u[key]\n    return d",
    "docstring": "Recursively updates nested dict d from nested dict u"
  },
  {
    "code": "def handle_exception (self):\n        etype, evalue = sys.exc_info()[:2]\n        log.debug(LOG_CHECK, \"Error in %s: %s %s\", self.url, etype, evalue, exception=True)\n        if (etype in ExcNoCacheList) or \\\n           (etype == socket.error and evalue.args[0]==errno.EBADF) or \\\n            not evalue:\n            self.caching = False\n        errmsg = unicode(etype.__name__)\n        uvalue = strformat.unicode_safe(evalue)\n        if uvalue:\n            errmsg += u\": %s\" % uvalue\n        return strformat.limit(errmsg, length=240)",
    "docstring": "An exception occurred. Log it and set the cache flag."
  },
  {
    "code": "def poll_results_check(self):\n        if not self.consumers:\n            LOGGER.debug('Skipping poll results check, no consumers')\n            return\n        LOGGER.debug('Checking for poll results')\n        while True:\n            try:\n                stats = self.stats_queue.get(False)\n            except queue.Empty:\n                break\n            try:\n                self.poll_data['processes'].remove(stats['name'])\n            except ValueError:\n                pass\n            self.collect_results(stats)\n        if self.poll_data['processes']:\n            LOGGER.warning('Did not receive results from %r',\n                           self.poll_data['processes'])",
    "docstring": "Check the polling results by checking to see if the stats queue is\n        empty. If it is not, try and collect stats. If it is set a timer to\n        call ourselves in _POLL_RESULTS_INTERVAL."
  },
  {
    "code": "def find_line_beginning(strings: Sequence[str],\n                        linestart: Optional[str]) -> int:\n    if linestart is None:\n        for i in range(len(strings)):\n            if is_empty_string(strings[i]):\n                return i\n        return -1\n    for i in range(len(strings)):\n        if strings[i].find(linestart) == 0:\n            return i\n    return -1",
    "docstring": "Finds the index of the line in ``strings`` that begins with ``linestart``,\n    or ``-1`` if none is found.\n\n    If ``linestart is None``, match an empty line."
  },
  {
    "code": "def turn_right(self, angle_degrees, rate=RATE):\n        flight_time = angle_degrees / rate\n        self.start_turn_right(rate)\n        time.sleep(flight_time)\n        self.stop()",
    "docstring": "Turn to the right, staying on the spot\n\n        :param angle_degrees: How far to turn (degrees)\n        :param rate: The trurning speed (degrees/second)\n        :return:"
  },
  {
    "code": "def find_files_cmd(data_path, minutes, start_time, end_time):\n    if minutes:\n        return FIND_MINUTES_COMMAND.format(\n            data_path=data_path,\n            minutes=minutes,\n        )\n    if start_time:\n        if end_time:\n            return FIND_RANGE_COMMAND.format(\n                data_path=data_path,\n                start_time=start_time,\n                end_time=end_time,\n            )\n        else:\n            return FIND_START_COMMAND.format(\n                data_path=data_path,\n                start_time=start_time,\n            )",
    "docstring": "Find the log files depending on their modification time.\n\n    :param data_path: the path to the Kafka data directory\n    :type data_path: str\n    :param minutes: check the files modified in the last N minutes\n    :type minutes: int\n    :param start_time: check the files modified after start_time\n    :type start_time: str\n    :param end_time: check the files modified before end_time\n    :type end_time: str\n    :returns: the find command\n    :rtype: str"
  },
  {
    "code": "def queries():\n    query = request.form['query']\n    name = request.form.get('name')\n    app.db.add_gemini_query(name, query)\n    return redirect(request.referrer)",
    "docstring": "Store a new GEMINI query."
  },
  {
    "code": "def _pfp__set_value(self, value):\n        if self._pfp__frozen:\n            raise errors.UnmodifiableConst()\n        if len(value) != len(self._pfp__children):\n            raise errors.PfpError(\"struct initialization has wrong number of members\")\n        for x in six.moves.range(len(self._pfp__children)):\n            self._pfp__children[x]._pfp__set_value(value[x])",
    "docstring": "Initialize the struct. Value should be an array of\n        fields, one each for each struct member.\n\n        :value: An array of fields to initialize the struct with\n        :returns: None"
  },
  {
    "code": "def apply_log(a: tuple, func: Callable[[Any], Tuple[Any, Log]]) -> Tuple[Any, Log]:\n        value, log = a\n        new, entry = func(value)\n        return new, log + entry",
    "docstring": "Apply a function to a value with a log.\n\n        Helper function to apply a function to a value with a log tuple."
  },
  {
    "code": "def _request(self, url, params=None, timeout=10):\n        rsp = self._session.get(url, params=params, timeout=timeout)\n        rsp.raise_for_status()\n        return rsp.text.strip()",
    "docstring": "Send a request with parameters."
  },
  {
    "code": "def parse_soap_enveloped_saml_thingy(text, expected_tags):\n    envelope = defusedxml.ElementTree.fromstring(text)\n    assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE\n    assert len(envelope) >= 1\n    body = None\n    for part in envelope:\n        if part.tag == '{%s}Body' % soapenv.NAMESPACE:\n            assert len(part) == 1\n            body = part\n            break\n    if body is None:\n        return \"\"\n    saml_part = body[0]\n    if saml_part.tag in expected_tags:\n        return ElementTree.tostring(saml_part, encoding=\"UTF-8\")\n    else:\n        raise WrongMessageType(\"Was '%s' expected one of %s\" % (saml_part.tag,\n                                                                expected_tags))",
    "docstring": "Parses a SOAP enveloped SAML thing and returns the thing as\n    a string.\n\n    :param text: The SOAP object as XML string\n    :param expected_tags: What the tag of the SAML thingy is expected to be.\n    :return: SAML thingy as a string"
  },
  {
    "code": "def __stopOpenThread(self):\n        print 'call stopOpenThread'\n        try:\n            if self.__sendCommand('thread stop')[0] == 'Done':\n                return self.__sendCommand('ifconfig down')[0] == 'Done'\n            else:\n                return False\n        except Exception, e:\n            ModuleHelper.WriteIntoDebugLogger(\"stopOpenThread() Error: \" + str(e))",
    "docstring": "stop OpenThread stack\n\n        Returns:\n            True: successful to stop OpenThread stack and thread interface down\n            False: fail to stop OpenThread stack"
  },
  {
    "code": "def wndifd(a, b):\n    assert isinstance(a, stypes.SpiceCell)\n    assert isinstance(b, stypes.SpiceCell)\n    assert a.dtype == 1\n    assert b.dtype == 1\n    c = stypes.SpiceCell.double(a.size + b.size)\n    libspice.wndifd_c(ctypes.byref(a), ctypes.byref(b), ctypes.byref(c))\n    return c",
    "docstring": "Place the difference of two double precision windows into\n    a third window.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wndifd_c.html\n\n    :param a: Input window A. \n    :type a: spiceypy.utils.support_types.SpiceCell\n    :param b: Input window B. \n    :type b: spiceypy.utils.support_types.SpiceCell\n    :return: Difference of a and b.\n    :rtype: spiceypy.utils.support_types.SpiceCell"
  },
  {
    "code": "def import_path(path):\n    sys.path.insert(0, \".\")\n    parts = path.split(\".\")\n    module = None\n    for i in range(1, len(parts)+1):\n        if module is not None and hasattr(module, parts[i-1]):\n            try:\n                return _import_attributes(module, parts[i-1:])\n            except AttributeError:\n                pass\n        module_path = \".\".join(parts[0:i])\n        module = importlib.import_module(module_path)\n    return module",
    "docstring": "Imports any valid python module or attribute path as though it were a\n    module\n\n    :Example:\n        >>> from yamlconf import import_path\n        >>> from my_package.my_module.my_submodule import attribute\n        >>> attribute.sub_attribute == \\\n        ...     import_path(\"y_package.my_module.my_submodule.attribute.sub_attribute\")\n        True\n        >>>\n\n    :Parameters:\n        path : `str`\n            A valid python path that crosses modules and/or attributes"
  },
  {
    "code": "def get_entity_mm():\n    type_builtins = {\n            'integer': SimpleType(None, 'integer'),\n            'string': SimpleType(None, 'string')\n    }\n    entity_mm = metamodel_from_file(join(this_folder, 'entity.tx'),\n                                    classes=[SimpleType],\n                                    builtins=type_builtins)\n    return entity_mm",
    "docstring": "Builds and returns a meta-model for Entity language."
  },
  {
    "code": "def matrix_product(mat1, mat2):\n    return np.dot(mat2.T, mat1.T).T",
    "docstring": "Compute the product of two Fortran contiguous matrices.\n\n    This is to avoid the overhead of NumPy converting to C-contiguous\n    before computing a matrix product.\n\n    Does so via ``A B = (B^T A^T)^T`` since ``B^T`` and ``A^T`` will be\n    C-contiguous without a copy, then the product ``P = B^T A^T`` will\n    be C-contiguous and we can return the view ``P^T`` without a copy.\n\n    Args:\n        mat1 (numpy.ndarray): The left-hand side matrix.\n        mat2 (numpy.ndarray): The right-hand side matrix.\n\n    Returns:\n        numpy.ndarray: The product of the two matrices."
  },
  {
    "code": "def extract_patch_images(f, which_set):\n    if which_set not in ('train', 'valid', 'test'):\n        raise ValueError('which_set must be one of train, valid, or test')\n    which_set = 'val' if which_set == 'valid' else which_set\n    patch_images = {}\n    with tar_open(f) as tar:\n        for info_obj in tar:\n            if not info_obj.name.endswith('.JPEG'):\n                continue\n            tokens = info_obj.name.split('/')\n            file_which_set = tokens[-2]\n            if file_which_set != which_set:\n                continue\n            filename = tokens[-1]\n            patch_images[filename] = tar.extractfile(info_obj.name).read()\n    return patch_images",
    "docstring": "Extracts a dict of the \"patch images\" for ILSVRC2010.\n\n    Parameters\n    ----------\n    f : str or file-like object\n        The filename or file-handle to the patch images TAR file.\n    which_set : str\n        Which set of images to extract. One of 'train', 'valid', 'test'.\n\n    Returns\n    -------\n    dict\n        A dictionary contains a mapping of filenames (without path) to a\n        bytes object containing the replacement image.\n\n    Notes\n    -----\n    Certain images in the distributed archives are blank, or display\n    an \"image not available\" banner. A separate TAR file of\n    \"patch images\" is distributed with the corrected versions of\n    these. It is this archive that this function is intended to read."
  },
  {
    "code": "def to_dict(self):\n        return dict({'title': self.title,\n                     'album': self.album,\n                     'year': self.year,\n                     'lyrics': self.lyrics,\n                     'image': self.song_art_image_url})",
    "docstring": "Create a dictionary from the song object\n        Used in save_lyrics to create json object\n\n        :return: Dictionary"
  },
  {
    "code": "def wishart_pfaffian(self):\n        return np.array(\n            [Pfaffian(self, val).value for i, val in np.ndenumerate(self._chisq)]\n        ).reshape(self._chisq.shape)",
    "docstring": "ndarray of wishart pfaffian CDF, before normalization"
  },
  {
    "code": "def get_instance_id(self, instance):\n        \" Returns instance pk even if multiple instances were passed to RichTextField. \"\n        if type(instance) in [list, tuple]:\n            core_signals.request_finished.connect(receiver=RichTextField.reset_instance_counter_listener)\n            if RichTextField.__inst_counter >= len(instance):\n                return None\n            else:\n                obj_id = self.instance[ RichTextField.__inst_counter ].pk\n            RichTextField.__inst_counter += 1\n        else:\n            obj_id = instance.pk\n        return obj_id",
    "docstring": "Returns instance pk even if multiple instances were passed to RichTextField."
  },
  {
    "code": "def connection(self):\n        if self._connections:\n            if not self._connections.acquire(self._blocking):\n                raise TooManyConnections\n        try:\n            con = self._cache.get(0)\n        except Empty:\n            con = self.steady_connection()\n        return PooledPgConnection(self, con)",
    "docstring": "Get a steady, cached PostgreSQL connection from the pool."
  },
  {
    "code": "def run_coroutine_threadsafe(coro, loop):\n    if not asyncio.iscoroutine(coro):\n        raise TypeError('A coroutine object is required')\n    future = concurrent.futures.Future()\n    def callback():\n        try:\n            _chain_future(asyncio.ensure_future(coro, loop=loop), future)\n        except Exception as exc:\n            if future.set_running_or_notify_cancel():\n                future.set_exception(exc)\n            raise\n    loop.call_soon_threadsafe(callback)\n    return future",
    "docstring": "Submit a coroutine object to a given event loop.\n    Return a concurrent.futures.Future to access the result."
  },
  {
    "code": "def get_template(cls, message, messenger):\n        template = message.context.get('tpl', None)\n        if template:\n            return template\n        if cls.template is None:\n            cls.template = 'sitemessage/messages/%s__%s.%s' % (\n                cls.get_alias(), messenger.get_alias(), cls.template_ext\n            )\n        return cls.template",
    "docstring": "Get a template path to compile a message.\n\n        1. `tpl` field of message context;\n        2. `template` field of message class;\n        3. deduced from message, messenger data and `template_ext` message type field\n           (e.g. `sitemessage/messages/plain__smtp.txt` for `plain` message type).\n\n        :param Message message: Message model\n        :param MessengerBase messenger: a MessengerBase heir\n        :return: str\n        :rtype: str"
  },
  {
    "code": "def _return(self, ary):\n        if isinstance(ary, Array):\n            return ary\n        return Array(ary, copy=False)",
    "docstring": "Wrap the ary to return an Array type"
  },
  {
    "code": "def addToService(self, service, namespace=None, seperator='.'):\n        if namespace is None:\n            namespace = []\n        if isinstance(namespace, basestring):\n            namespace = [namespace]\n        for n, m in inspect.getmembers(self, inspect.ismethod):\n            if hasattr(m, 'export_rpc'):\n                try:\n                    name = seperator.join(namespace + m.export_rpc)\n                except TypeError:\n                    name = seperator.join(namespace + [m.export_rpc])\n                service.add(m, name)",
    "docstring": "Add this Handler's exported methods to an RPC Service instance."
  },
  {
    "code": "def save(self):\n        e = self.editor\n        self._style = e.current_style\n        self._show_line_numbers = e.show_line_numbers\n        self._highlight_search = e.highlight_search\n        self._show_ruler = e.show_ruler\n        self._relative_number = e.relative_number\n        self._cursorcolumn = e.cursorcolumn\n        self._cursorline = e.cursorline\n        self._colorcolumn = e.colorcolumn",
    "docstring": "Back up current editor state."
  },
  {
    "code": "def run_on(*, event: str):\n        def decorator(callback):\n            @functools.wraps(callback)\n            def decorator_wrapper():\n                RTMClient.on(event=event, callback=callback)\n            return decorator_wrapper()\n        return decorator",
    "docstring": "A decorator to store and link a callback to an event."
  },
  {
    "code": "def get_xml_string_with_self_contained_assertion_within_encrypted_assertion(\n            self, assertion_tag):\n        prefix_map = self.get_prefix_map(\n            [self.encrypted_assertion._to_element_tree().find(assertion_tag)])\n        tree = self._to_element_tree()\n        self.set_prefixes(\n            tree.find(\n                self.encrypted_assertion._to_element_tree().tag).find(\n                assertion_tag), prefix_map)\n        return ElementTree.tostring(tree, encoding=\"UTF-8\").decode('utf-8')",
    "docstring": "Makes a encrypted assertion only containing self contained\n        namespaces.\n\n        :param assertion_tag: Tag for the assertion to be transformed.\n        :return: A new samlp.Resonse in string representation."
  },
  {
    "code": "def plot_degbandshalffill():\n    ulim = [3.45, 5.15, 6.85, 8.55]\n    bands = range(1, 5)\n    for band, u_int in zip(bands, ulim):\n        name = 'Z_half_'+str(band)+'band'\n        dop = [0.5]\n        data = ssplt.calc_z(band, dop, np.arange(0, u_int, 0.1),0., name)\n        plt.plot(data['u_int'], data['zeta'][0, :, 0], label='$N={}$'.format(str(band)))\n    ssplt.label_saves('Z_half_multiorb.png')",
    "docstring": "Plot of Quasiparticle weight for degenerate\n       half-filled bands, showing the Mott transition"
  },
  {
    "code": "def deactivate(self):\n        if lib.EnvDeactivateRouter(self._env, self._name.encode()) == 0:\n            raise RuntimeError(\"Unable to deactivate router %s\" % self._name)",
    "docstring": "Deactivate the Router."
  },
  {
    "code": "def print_subprocess_output(subp):\n    if subp:\n        if subp.errorcode != 0:\n            print('<error errorcode=\"%s\">' % str(subp.errorcode))\n            print(subp.stderr)\n            print(\"</error>\")\n            print_tag('stdout', '\\n%s\\n' % subp.stdout)\n        else:\n            print_tag('success', '\\n%s\\n' % subp.stdout)\n            print_tag('warnings', '\\n%s\\n' % subp.stderr)",
    "docstring": "Prints the stdout and stderr output."
  },
  {
    "code": "def parse_qs(self, qs):\n        qs_state = urllib2.urlparse.parse_qs(qs)\n        ret = {}\n        for qs_var, qs_value_list in qs_state.items():\n            if len(qs_value_list) > 1:\n                return None\n            ret[qs_var] = qs_value_list[0]\n        return ret",
    "docstring": "Parse query string, but enforce one instance of each variable.\n        Return a dict with the variables on success\n        Return None on parse error"
  },
  {
    "code": "def generate(env):\n    fortran.generate(env)\n    env['FORTRAN']        = 'f90'\n    env['FORTRANCOM']     = '$FORTRAN $FORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}'\n    env['FORTRANPPCOM']   = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}'\n    env['SHFORTRANCOM']   = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}'\n    env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}'\n    env['OBJSUFFIX']      = '.obj'\n    env['FORTRANMODDIR'] = '${TARGET.dir}'\n    env['FORTRANMODDIRPREFIX'] = '/module:'\n    env['FORTRANMODDIRSUFFIX'] = ''",
    "docstring": "Add Builders and construction variables for compaq visual fortran to an Environment."
  },
  {
    "code": "def _get_instance_changes(current, state):\n    current_keys = set(current.keys())\n    state_keys = set(state.keys())\n    changed = salt.utils.data.compare_dicts(current, state)\n    for change in salt.utils.data.compare_dicts(current, state):\n        if change in changed and changed[change]['old'] == \"\":\n            del changed[change]\n        if change in changed and changed[change]['new'] == \"\":\n            del changed[change]\n    return changed",
    "docstring": "get modified properties"
  },
  {
    "code": "def find(self, oid):\n        if not isinstance(oid, Oid):\n            raise TypeError(\"Need crytypescrypto.oid.Oid as argument\")\n        found = []\n        index = -1\n        end = len(self)\n        while True:\n            index = libcrypto.X509_get_ext_by_NID(self.cert.cert, oid.nid,\n                                                  index)\n            if index >= end or index < 0:\n                break\n            found.append(self[index])\n        return found",
    "docstring": "Return list of extensions with given Oid"
  },
  {
    "code": "def set_working_directory(self, dirname):\r\n        if dirname:\r\n            self.main.workingdirectory.chdir(dirname, refresh_explorer=True,\r\n                                             refresh_console=False)",
    "docstring": "Set current working directory.\r\n        In the workingdirectory and explorer plugins."
  },
  {
    "code": "def off_policy_train_batch(self, batch_info: BatchInfo):\n        self.model.train()\n        rollout = self.env_roller.sample(batch_info, self.model, self.settings.number_of_steps).to_device(self.device)\n        batch_result = self.algo.optimizer_step(\n            batch_info=batch_info,\n            device=self.device,\n            model=self.model,\n            rollout=rollout\n        )\n        batch_info['sub_batch_data'].append(batch_result)",
    "docstring": "Perform an 'off-policy' training step of sampling the replay buffer and gradient descent"
  },
  {
    "code": "def mock_server_receive_request(client, server):\n    header = mock_server_receive(client, 16)\n    length = _UNPACK_INT(header[:4])[0]\n    request_id = _UNPACK_INT(header[4:8])[0]\n    opcode = _UNPACK_INT(header[12:])[0]\n    msg_bytes = mock_server_receive(client, length - 16)\n    if opcode not in OPCODES:\n        raise NotImplementedError(\"Don't know how to unpack opcode %d yet\"\n                                  % opcode)\n    return OPCODES[opcode].unpack(msg_bytes, client, server, request_id)",
    "docstring": "Take a client socket and return a Request."
  },
  {
    "code": "def get_factor_nodes(self):\n        self.check_model()\n        variable_nodes = self.get_variable_nodes()\n        factor_nodes = set(self.nodes()) - set(variable_nodes)\n        return list(factor_nodes)",
    "docstring": "Returns factors nodes present in the graph.\n\n        Before calling this method make sure that all the factors are added\n        properly.\n\n        Examples\n        --------\n        >>> from pgmpy.models import FactorGraph\n        >>> from pgmpy.factors.discrete import DiscreteFactor\n        >>> G = FactorGraph()\n        >>> G.add_nodes_from(['a', 'b', 'c'])\n        >>> phi1 = DiscreteFactor(['a', 'b'], [2, 2], np.random.rand(4))\n        >>> phi2 = DiscreteFactor(['b', 'c'], [2, 2], np.random.rand(4))\n        >>> G.add_nodes_from([phi1, phi2])\n        >>> G.add_factors(phi1, phi2)\n        >>> G.add_edges_from([('a', phi1), ('b', phi1),\n        ...                   ('b', phi2), ('c', phi2)])\n        >>> G.get_factor_nodes()\n        [<DiscreteFactor representing phi(b:2, c:2) at 0x4b8c7f0>,\n         <DiscreteFactor representing phi(a:2, b:2) at 0x4b8c5b0>]"
  },
  {
    "code": "def salience(self, salience):\n        lib.EnvSetActivationSalience(self._env, self._act, salience)",
    "docstring": "Activation salience value."
  },
  {
    "code": "def define_from_header(cls, image_header):\n        self = CsuConfiguration()\n        self._csu_bar_left = []\n        self._csu_bar_right = []\n        self._csu_bar_slit_center = []\n        self._csu_bar_slit_width = []\n        for i in range(EMIR_NBARS):\n            ibar = i + 1\n            keyword = 'CSUP{}'.format(ibar)\n            if keyword in image_header:\n                self._csu_bar_left.append(image_header[keyword])\n            else:\n                raise ValueError(\"Expected keyword \" + keyword + \" not found!\")\n            keyword = 'CSUP{}'.format(ibar + EMIR_NBARS)\n            if keyword in image_header:\n                self._csu_bar_right.append(341.5 - image_header[keyword])\n            else:\n                raise ValueError(\"Expected keyword \" + keyword + \" not found!\")\n            self._csu_bar_slit_center.append(\n                (self._csu_bar_left[i] + self._csu_bar_right[i]) / 2\n            )\n            self._csu_bar_slit_width.append(\n                self._csu_bar_right[i] - self._csu_bar_left[i]\n            )\n        return self",
    "docstring": "Define class members directly from FITS header.\n\n        Parameters\n        ----------\n        image_header : instance of hdulist.header\n            Header content from a FITS file."
  },
  {
    "code": "def write(self, config_dir=None, config_name=None, codec=None):\n        if not config_dir:\n            config_dir = self._meta_config_dir\n            if not config_dir:\n                raise IOError(\"config_dir not set\")\n        if not config_name:\n            config_name = self._defaults.get('config_name', None)\n        if not config_name:\n            raise KeyError('config_name not set')\n        if codec:\n            codec = munge.get_codec(codec)()\n        else:\n            codec = munge.get_codec(self._defaults['codec'])()\n        config_dir = os.path.expanduser(config_dir)\n        if not os.path.exists(config_dir):\n            os.mkdir(config_dir)\n        codec.dumpu(self.data, os.path.join(config_dir, 'config.' + codec.extension))",
    "docstring": "writes config to config_dir using config_name"
  },
  {
    "code": "def fnames(self, names):\n        names = list(names[:len(self._fnames)])\n        self._fnames = names + self._fnames[len(names):]",
    "docstring": "Ensure constant size of fnames"
  },
  {
    "code": "def waveform_image(mediafile, xy_size, outdir=None, center_color=None, outer_color=None, bg_color=None):\n    try:\n        import waveform\n    except ImportError, exc:\n        raise ImportError(\"%s [get it at https://github.com/superjoe30/PyWaveform]\" % exc)\n    outdir = outdir or os.path.dirname(mediafile)\n    outfile = os.path.join(outdir, os.path.splitext(os.path.basename(mediafile))[0] + \".png\")\n    with transcode.to_wav(mediafile) as wavfile:\n        waveform.draw(wavfile, outfile, xy_size, \n            bgColor=bg_color or WAVE_BG_COLOR,\n            fgGradientCenter=center_color or WAVE_CENTER_COLOR, \n            fgGradientOuter=outer_color or WAVE_OUTER_COLOR)\n    return outfile",
    "docstring": "Create waveform image from audio data.\n        Return path to created image file."
  },
  {
    "code": "def _listen_inbox_messages(self):\n        inbox_queue = Queue(maxsize=self._n_jobs * 4)\n        threads = []\n        try:\n            for i in range(self._n_jobs):\n                t = BotQueueWorker(name='InboxThread-t-{}'.format(i),\n                                   jobs=inbox_queue,\n                                   target=self._process_inbox_message)\n                t.start()\n                self._threads.append(t)\n            for message in self._reddit.inbox.stream():\n                if self._stop:\n                    self._do_stop(inbox_queue, threads)\n                    break\n                inbox_queue.put(message)\n            self.log.debug('Listen inbox stopped')\n        except Exception as e:\n            self._do_stop(inbox_queue, threads)\n            self.log.error('Exception while listening to inbox:')\n            self.log.error(str(e))\n            self.log.error('Waiting for 10 minutes and trying again.')\n            time.sleep(10 * 60)\n            self._listen_inbox_messages()",
    "docstring": "Start listening to messages, using a separate thread."
  },
  {
    "code": "def serialize_dict(self, msg_dict):\n        serialized = json.dumps(msg_dict, namedtuple_as_object=False)\n        if PY2:\n            serialized = serialized.decode(\"utf-8\")\n        serialized = \"{}\\nend\\n\".format(serialized)\n        return serialized",
    "docstring": "Serialize to JSON a message dictionary."
  },
  {
    "code": "def path(self, filename):\n        if not self.backend.root:\n            raise OperationNotSupported(\n                'Direct file access is not supported by ' +\n                self.backend.__class__.__name__\n            )\n        return os.path.join(self.backend.root, filename)",
    "docstring": "This returns the absolute path of a file uploaded to this set. It\n        doesn't actually check whether said file exists.\n\n        :param filename: The filename to return the path for.\n        :param folder: The subfolder within the upload set previously used\n                       to save to.\n\n        :raises OperationNotSupported: when the backenddoesn't support direct file access"
  },
  {
    "code": "def set_if_empty(self, param, default):\n        if not self.has(param):\n            self.set(param, default)",
    "docstring": "Set the parameter to the default if it doesn't exist"
  },
  {
    "code": "def store(self, database, validate=True, role=None):\n        if validate:\n            self.validate()\n        self._id, self._rev = database.save(self.to_primitive(role=role))\n        return self",
    "docstring": "Store the document in the given database.\n\n        :param database: the `Database` object source for storing the document.\n        :return: an updated instance of `Document` / self."
  },
  {
    "code": "def is_valid_package_name(name, raise_error=False):\n    is_valid = PACKAGE_NAME_REGEX.match(name)\n    if raise_error and not is_valid:\n        raise PackageRequestError(\"Not a valid package name: %r\" % name)\n    return is_valid",
    "docstring": "Test the validity of a package name string.\n\n    Args:\n        name (str): Name to test.\n        raise_error (bool): If True, raise an exception on failure\n\n    Returns:\n        bool."
  },
  {
    "code": "def num(value):\n    if re_hex_num.match(value):\n        return int(value, base=16)\n    else:\n        return int(value)",
    "docstring": "Convert a value from one of several bases to an int."
  },
  {
    "code": "def metadata_response(self, request, full_url, headers):\n        parsed_url = urlparse(full_url)\n        tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)\n        credentials = dict(\n            AccessKeyId=\"test-key\",\n            SecretAccessKey=\"test-secret-key\",\n            Token=\"test-session-token\",\n            Expiration=tomorrow.strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n        )\n        path = parsed_url.path\n        meta_data_prefix = \"/latest/meta-data/\"\n        if path.startswith(meta_data_prefix):\n            path = path[len(meta_data_prefix):]\n        if path == '':\n            result = 'iam'\n        elif path == 'iam':\n            result = json.dumps({\n                'security-credentials': {\n                    'default-role': credentials\n                }\n            })\n        elif path == 'iam/security-credentials/':\n            result = 'default-role'\n        elif path == 'iam/security-credentials/default-role':\n            result = json.dumps(credentials)\n        else:\n            raise NotImplementedError(\n                \"The {0} metadata path has not been implemented\".format(path))\n        return 200, headers, result",
    "docstring": "Mock response for localhost metadata\n\n        http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html"
  },
  {
    "code": "def prettify_json(json_string):\n    try:\n        data = json.loads(json_string)\n        html = '<pre>' + json.dumps(data, sort_keys=True, indent=4) + '</pre>'\n    except:\n        html = json_string\n    return mark_safe(html)",
    "docstring": "Given a JSON string, it returns it as a\n    safe formatted HTML"
  },
  {
    "code": "def get_short_help_str(self, limit=45):\n        return self.short_help or self.help and make_default_short_help(self.help, limit) or ''",
    "docstring": "Gets short help for the command or makes it by shortening the long help string."
  },
  {
    "code": "def list_controls(self, limit=500, offset=0):\n        return self.__list(R_CONTROL, limit=limit, offset=offset)['controls']",
    "docstring": "List `all` the controls on this Thing.\n\n        Returns QAPI list function payload\n\n        Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)\n        containing the error if the infrastructure detects a problem\n\n        Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)\n        if there is a communications problem between you and the infrastructure\n\n        `limit` (optional) (integer) Return this many Point details\n\n        `offset` (optional) (integer) Return Point details starting at this offset"
  },
  {
    "code": "def remove_empty_files(root_directory, dry_run=False, ignore_errors=True,\n                       enable_scandir=False):\n    file_list = []\n    for root, directories, files in _walk(root_directory,\n                                          enable_scandir=enable_scandir):\n        for file_name in files:\n            file_path = join_paths(root, file_name, strict=True)\n            if os.path.isfile(file_path) and not os.path.getsize(file_path):\n                if file_hash(file_path) == variables.hashes.empty_file.md5:\n                    file_list.append(file_path)\n    file_list = sorted(set(file_list))\n    if not dry_run:\n        for afile in file_list:\n            try:\n                os.unlink(afile)\n            except OSError as err:\n                if ignore_errors:\n                    logger.info(\"File {0} could not be deleted\".format(afile))\n                else:\n                    raise err\n    return file_list",
    "docstring": "Remove all empty files from a path. Returns list of the empty files removed.\n\n    :param root_directory: base directory to start at\n    :param dry_run: just return a list of what would be removed\n    :param ignore_errors: Permissions are a pain, just ignore if you blocked\n    :param enable_scandir: on python < 3.5 enable external scandir package\n    :return: list of removed files"
  },
  {
    "code": "def _is_second_run():\n    tracker_path = _get_not_configured_usage_tracker_path()\n    if not tracker_path.exists():\n        return False\n    current_pid = _get_shell_pid()\n    with tracker_path.open('r') as tracker:\n        try:\n            info = json.load(tracker)\n        except ValueError:\n            return False\n    if not (isinstance(info, dict) and info.get('pid') == current_pid):\n        return False\n    return (_get_previous_command() == 'fuck' or\n            time.time() - info.get('time', 0) < const.CONFIGURATION_TIMEOUT)",
    "docstring": "Returns `True` when we know that `fuck` called second time."
  },
  {
    "code": "def get_results(self, *, block=False, timeout=None):\n        deadline = None\n        if timeout:\n            deadline = time.monotonic() + timeout / 1000\n        for child in self.children:\n            if deadline:\n                timeout = max(0, int((deadline - time.monotonic()) * 1000))\n            if isinstance(child, group):\n                yield list(child.get_results(block=block, timeout=timeout))\n            else:\n                yield child.get_result(block=block, timeout=timeout)",
    "docstring": "Get the results of each job in the group.\n\n        Parameters:\n          block(bool): Whether or not to block until the results are stored.\n          timeout(int): The maximum amount of time, in milliseconds,\n            to wait for results when block is True.  Defaults to 10\n            seconds.\n\n        Raises:\n          ResultMissing: When block is False and the results aren't set.\n          ResultTimeout: When waiting for results times out.\n\n        Returns:\n          A result generator."
  },
  {
    "code": "def list(self, toa=None, show_history=False):\n        if not toa:\n            toa = time.mktime(datetime.datetime.now().timetuple())\n        query = {\n            \"$query\": {\n                \"master_id\": self.master_id,\n                \"processed\": show_history,\n                \"toa\" : {\"$lte\" : toa}\n            },\n            \"$orderby\": {\n                \"toa\": 1\n            }\n        }\n        revisions = yield self.revisions.find(query)\n        raise Return(revisions)",
    "docstring": "Return all revisions for this stack\n\n        :param int toa: The time of action as a UTC timestamp\n        :param bool show_history: Whether to show historical revisions"
  },
  {
    "code": "def set_field(self, field_name, field_val=None):\n        field_name = self._normalize_field_name(field_name)\n        self.fields_set.append(field_name, [field_name, field_val])\n        return self",
    "docstring": "set a field into .fields attribute\n\n        n insert/update queries, these are the fields that will be inserted/updated into the db"
  },
  {
    "code": "def get_formset(self, request, obj=None, **kwargs):\n        def _placeholder_initial(p):\n            return {\n                'slot': p.slot,\n                'title': p.title,\n                'role': p.role,\n            }\n        initial = []\n        if request.method == \"GET\":\n            placeholder_admin = self._get_parent_modeladmin()\n            data = placeholder_admin.get_placeholder_data(request, obj)\n            initial = [_placeholder_initial(d) for d in data]\n        FormSetClass = super(PlaceholderEditorInline, self).get_formset(request, obj, **kwargs)\n        FormSetClass.__init__ = curry(FormSetClass.__init__, initial=initial)\n        return FormSetClass",
    "docstring": "Pre-populate formset with the initial placeholders to display."
  },
  {
    "code": "def generic_combine(method, arrays, masks=None, dtype=None,\n                    out=None, zeros=None, scales=None, weights=None):\n    arrays = [numpy.asarray(arr, dtype=dtype) for arr in arrays]\n    if masks is not None:\n        masks = [numpy.asarray(msk) for msk in masks]\n    if out is None:\n        try:\n            outshape = (3,) + tuple(arrays[0].shape)\n            out = numpy.zeros(outshape, dtype)\n        except AttributeError:\n            raise TypeError('First element in arrays does '\n                            'not have .shape attribute')\n    else:\n        out = numpy.asanyarray(out)\n    intl_combine.generic_combine(\n        method, arrays,\n        out[0], out[1], out[2],\n        masks, zeros, scales, weights\n    )\n    return out",
    "docstring": "Stack arrays using different methods.\n\n    :param method: the combination method\n    :type method: PyCObject\n    :param arrays: a list of arrays\n    :param masks: a list of mask arrays, True values are masked\n    :param dtype: data type of the output\n    :param zeros:\n    :param scales:\n    :param weights:\n    :return: median, variance of the median and number of points stored"
  },
  {
    "code": "def _init_regs_random(self):\n        values = set()\n        while len(values) != len(self._arch_regs_parent):\n            values.add(random.randint(0, 2**self._arch_info.operand_size - 1))\n        values = list(values)\n        regs = {}\n        for idx, reg in enumerate(self._arch_regs_parent):\n            regs[reg] = values[idx] & (2**self._arch_regs_size[reg] - 1)\n        return regs",
    "docstring": "Initialize register with random values."
  },
  {
    "code": "def set_knowledge_category(self, grade_id):\n        if self.get_knowledge_category_metadata().is_read_only():\n            raise errors.NoAccess()\n        if not self._is_valid_id(grade_id):\n            raise errors.InvalidArgument()\n        self._my_map['knowledgeCategoryId'] = str(grade_id)",
    "docstring": "Sets the knowledge category.\n\n        arg:    grade_id (osid.id.Id): the new knowledge category\n        raise:  InvalidArgument - ``grade_id`` is invalid\n        raise:  NoAccess - ``grade_id`` cannot be modified\n        raise:  NullArgument - ``grade_id`` is ``null``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_report_raw(year, report_type):\n    if not is_valid_report_type(report_type):\n        msg = '%s is not a valid report type.' % report_type\n        raise ValueError(msg)\n    url = get_url(year, report_type)\n    raw_contents = get_zipped_file(url)\n    return csv.DictReader(cStringIO.StringIO(raw_contents))",
    "docstring": "Download and extract a CO-TRACER report.\n\n    Generate a URL for the given report, download the corresponding archive,\n    extract the CSV report, and interpret it using the standard CSV library.\n\n    @param year: The year for which data should be downloaded.\n    @type year: int\n    @param report_type: The type of report that should be downloaded. Should be\n        one of the strings in constants.REPORT_TYPES.\n    @type report_type: str\n    @return: A DictReader with the loaded data. Note that this data has not\n        been interpreted so data fields like floating point values, dates, and\n        boolean values are still strings.\n    @rtype: csv.DictReader"
  },
  {
    "code": "def fetch_mood_station(self, station_id, terr=KKBOXTerritory.TAIWAN):\n        url = 'https://api.kkbox.com/v1.1/mood-stations/%s' % station_id\n        url += '?' + url_parse.urlencode({'territory': terr})\n        return self.http._post_data(url, None, self.http._headers_with_access_token())",
    "docstring": "Fetches a mood station by given ID.\n\n        :param station_id: the station ID\n        :param terr: the current territory.\n        :return: API response.\n        :rtype: dict\n\n        See `https://docs-en.kkbox.codes/v1.1/reference#moodstations-station_id`."
  },
  {
    "code": "def main():\n    listname = sys.argv[2]\n    hostname = sys.argv[1]\n    mlist = MailList.MailList(listname, lock=False)\n    f = StringIO(sys.stdin.read())\n    msg = email.message_from_file(f, Message.Message)\n    h = HyperArch.HyperArchive(mlist)\n    sequence = h.sequence\n    h.processUnixMailbox(f)\n    f.close()\n    archive = h.archive\n    msgno = '%06d' % sequence\n    filename = msgno + '.html'\n    filepath = os.path.join(h.basedir, archive, filename)\n    h.close()\n    url = '%s%s/%s' % (mlist.GetBaseArchiveURL(), archive, filename)\n    ext_process(listname, hostname, url, filepath, msg)",
    "docstring": "This is the mainline.\n\n    It first invokes the pipermail archiver to add the message to the archive,\n    then calls the function above to do whatever with the archived message\n    after it's URL and path are known."
  },
  {
    "code": "def first_order_score(y, mean, scale, shape, skewness):\n        return (y-mean)/np.power(scale,2)",
    "docstring": "GAS Normal Update term using gradient only - native Python function\n\n        Parameters\n        ----------\n        y : float\n            datapoint for the time series\n\n        mean : float\n            location parameter for the Normal distribution\n\n        scale : float\n            scale parameter for the Normal distribution\n\n        shape : float\n            tail thickness parameter for the Normal distribution\n\n        skewness : float\n            skewness parameter for the Normal distribution\n\n        Returns\n        ----------\n        - Score of the Normal family"
  },
  {
    "code": "def _preprocess_data(self, data):\n        original_type = data.dtype\n        if len(data.shape) == 1:\n            data = data[:, np.newaxis, np.newaxis]\n        elif len(data.shape) == 2:\n            data = data[:, :, np.newaxis]\n        elif len(data.shape) == 0 or len(data.shape) > 3:\n            raise ValueError(\n                'Illegal data array passed to image. Must be 1, 2, or 3 dimensional numpy array')\n        return data.astype(original_type)",
    "docstring": "Converts a data array to the preferred 3D structure.\n\n        Parameters\n        ----------\n        data : :obj:`numpy.ndarray`\n            The data to process.\n\n        Returns\n        -------\n        :obj:`numpy.ndarray`\n            The data re-formatted (if needed) as a 3D matrix\n\n        Raises\n        ------\n        ValueError\n            If the data is not 1, 2, or 3D to begin with."
  },
  {
    "code": "def DeregisterBlockchain():\n        Blockchain.SECONDS_PER_BLOCK = 15\n        Blockchain.DECREMENT_INTERVAL = 2000000\n        Blockchain.GENERATION_AMOUNT = [8, 7, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n        Blockchain._blockchain = None\n        Blockchain._validators = []\n        Blockchain._genesis_block = None\n        Blockchain._instance = None\n        Blockchain._blockrequests = set()\n        Blockchain._paused = False\n        Blockchain.BlockSearchTries = 0\n        Blockchain.CACHELIM = 4000\n        Blockchain.CMISSLIM = 5\n        Blockchain.LOOPTIME = .1\n        Blockchain.PersistCompleted = Events()\n        Blockchain.Notify = Events()\n        Blockchain._instance = None",
    "docstring": "Remove the default blockchain instance."
  },
  {
    "code": "def remove_device(self, request):\n        devices = self.__get_u2f_devices()\n        for i in range(len(devices)):\n            if devices[i]['keyHandle'] == request['id']:\n                del devices[i]\n                self.__save_u2f_devices(devices)\n                return {\n                    'status'  : 'ok', \n                    'message' : 'Successfully deleted your device!'\n                }\n        return {\n            'status' : 'failed', \n            'error'  : 'No device with such an id been found!'\n        }",
    "docstring": "Removes device specified by id"
  },
  {
    "code": "def Error(self, backtrace, client_id=None):\n    logging.error(\"Hunt Error: %s\", backtrace)\n    self.hunt_obj.LogClientError(client_id, backtrace=backtrace)",
    "docstring": "Logs an error for a client but does not terminate the hunt."
  },
  {
    "code": "def git_version(short: 'Get short hash' = True, show: 'Print version to stdout' = False):\n    result = local(\n        ['git', 'rev-parse', '--is-inside-work-tree'],\n        stdout='hide', stderr='hide', echo=False, raise_on_error=False)\n    if not result:\n        return None\n    result = local(\n        ['git', 'describe', '--exact-match'],\n        stdout='capture', stderr='hide', echo=False, raise_on_error=False)\n    if result:\n        return result.stdout\n    result = local(\n        ['git', 'rev-parse', '--short' if short else None, 'HEAD'],\n        stdout='capture', stderr='hide', echo=False, raise_on_error=False)\n    if result:\n        version = result.stdout.strip()\n        if show:\n            print(version)\n        return version\n    return None",
    "docstring": "Get tag associated with HEAD; fall back to SHA1.\n\n    If HEAD is tagged, return the tag name; otherwise fall back to\n    HEAD's short SHA1 hash.\n\n    .. note:: Only annotated tags are considered.\n\n    .. note:: The output isn't shown by default. To show it, pass the\n        ``--show`` flag."
  },
  {
    "code": "def to_array(self):\n        dt = np.dtype(list(zip(self.labels, (c.dtype for c in self.columns))))\n        arr = np.empty_like(self.columns[0], dt)\n        for label in self.labels:\n            arr[label] = self[label]\n        return arr",
    "docstring": "Convert the table to a structured NumPy array."
  },
  {
    "code": "def _load_id_or_insert(self, session):\n        if self.id is None:\n            stable_id = self.get_stable_id()\n            id = session.execute(\n                select([Context.id]).where(Context.stable_id == stable_id)\n            ).first()\n            if id is None:\n                self.id = session.execute(\n                    Context.__table__.insert(),\n                    {\"type\": self._get_table().__tablename__, \"stable_id\": stable_id},\n                ).inserted_primary_key[0]\n                insert_args = self._get_insert_args()\n                insert_args[\"id\"] = self.id\n                return insert_args\n            else:\n                self.id = id[0]",
    "docstring": "Load the id of the temporary context if it exists or return insert args.\n\n        As a side effect, this also inserts the Context object for the stableid.\n\n        :return: The record of the temporary context to insert.\n        :rtype: dict"
  },
  {
    "code": "def macro2micro(self, macro_indices):\n        def from_partition(partition, macro_indices):\n            micro_indices = itertools.chain.from_iterable(\n                partition[i] for i in macro_indices)\n            return tuple(sorted(micro_indices))\n        if self.blackbox and self.coarse_grain:\n            cg_micro_indices = from_partition(self.coarse_grain.partition,\n                                              macro_indices)\n            return from_partition(self.blackbox.partition,\n                                  reindex(cg_micro_indices))\n        elif self.blackbox:\n            return from_partition(self.blackbox.partition, macro_indices)\n        elif self.coarse_grain:\n            return from_partition(self.coarse_grain.partition, macro_indices)\n        return macro_indices",
    "docstring": "Return all micro indices which compose the elements specified by\n        ``macro_indices``."
  },
  {
    "code": "def as_json(data, **kwargs):\n    if 'sort_keys' not in kwargs:\n        kwargs['sort_keys'] = False\n    if 'ensure_ascii' not in kwargs:\n        kwargs['ensure_ascii'] = False\n    data = json.dumps(data, **kwargs)\n    return data",
    "docstring": "Writes data as json.\n\n    :param dict data: data to convert to json\n    :param kwargs kwargs: kwargs for json dumps\n    :return: json string\n    :rtype: str"
  },
  {
    "code": "def list_subscribers(self, list_id):\n        return [User(user._json) for user in self._client.list_subscribers(list_id=list_id)]",
    "docstring": "List subscribers of a list\n\n        :param list_id: list ID number\n        :return: :class:`~responsebot.models.User` object"
  },
  {
    "code": "def copy_script(self, filename, id_=-1):\n        self._copy(filename, id_=id_, file_type=SCRIPT_FILE_TYPE)",
    "docstring": "Copy a script to the distribution server.\n\n        Args:\n            filename: Full path to file to upload.\n            id_: ID of Script object to associate with, or -1 for new\n                Script (default)."
  },
  {
    "code": "def seal(mock):\n    _frankeinstainize(mock)\n    for attr in dir(mock):\n        try:\n            m = getattr(mock, attr)\n        except AttributeError:\n            continue\n        if not isinstance(m, NonCallableMock):\n            continue\n        if m._mock_new_parent is mock:\n            seal(m)",
    "docstring": "Disable the automatic generation of \"submocks\"\n\n    Given an input Mock, seals it to ensure no further mocks will be generated\n    when accessing an attribute that was not already defined.\n\n    Submocks are defined as all mocks which were created DIRECTLY from the\n    parent. If a mock is assigned to an attribute of an existing mock,\n    it is not considered a submock."
  },
  {
    "code": "def _get_observer_fun(self, prop_name):\n        def _observer_fun(self, model, old, new):\n            if self._itsme:\n                return\n            self._on_prop_changed()\n        _observer_fun.__name__ = \"property_%s_value_change\" % prop_name\n        return _observer_fun",
    "docstring": "This is the code for an value change observer"
  },
  {
    "code": "def _replace_token_range(tokens, start, end, replacement):\n    tokens = tokens[:start] + replacement + tokens[end:]\n    return tokens",
    "docstring": "For a range indicated from start to end, replace with replacement."
  },
  {
    "code": "def raises(cls, sender, attrname, error, args=ANYTHING, kwargs=ANYTHING):\n        \"An alternative constructor which raises the given error\"\n        def raise_error():\n            raise error\n        return cls(sender, attrname, returns=Invoke(raise_error), args=ANYTHING, kwargs=ANYTHING)",
    "docstring": "An alternative constructor which raises the given error"
  },
  {
    "code": "def consume(self, queue, consumer, consumer_tag='', no_local=False,\n                no_ack=True, exclusive=False, nowait=True, ticket=None,\n                cb=None):\n        nowait = nowait and self.allow_nowait() and not cb\n        if nowait and consumer_tag == '':\n            consumer_tag = self._generate_consumer_tag()\n        args = Writer()\n        args.write_short(ticket or self.default_ticket).\\\n            write_shortstr(queue).\\\n            write_shortstr(consumer_tag).\\\n            write_bits(no_local, no_ack, exclusive, nowait).\\\n            write_table({})\n        self.send_frame(MethodFrame(self.channel_id, 60, 20, args))\n        if not nowait:\n            self._pending_consumers.append((consumer, cb))\n            self.channel.add_synchronous_cb(self._recv_consume_ok)\n        else:\n            self._consumer_cb[consumer_tag] = consumer",
    "docstring": "Start a queue consumer. If `cb` is supplied, will be called when\n        broker confirms that consumer is registered."
  },
  {
    "code": "def terminal(self, out=None, border=None):\n        for qrcode in self:\n            qrcode.terminal(out=out, border=border)",
    "docstring": "\\\n        Serializes the sequence of QR Codes as ANSI escape code.\n\n        See :py:meth:`QRCode.terminal()` for details."
  },
  {
    "code": "def init_repo(path):\n    sh(\"git clone %s %s\"%(pages_repo, path))\n    here = os.getcwd()\n    cd(path)\n    sh('git checkout gh-pages')\n    cd(here)",
    "docstring": "clone the gh-pages repo if we haven't already."
  },
  {
    "code": "def read_data_types(self):\n        return {\n            'Binary': self.read_binary,\n            'BinaryArray': self.read_binary_array,\n            'KeyValue': self.read_key_value,\n            'KeyValueArray': self.read_key_value_array,\n            'String': self.read_string,\n            'StringArray': self.read_string_array,\n            'TCEntity': self.read_tc_entity,\n            'TCEntityArray': self.read_tc_entity_array,\n        }",
    "docstring": "Map of standard playbook variable types to read method."
  },
  {
    "code": "def declareAsOntology(self, graph):\n        model = Model(graph)\n        ontology_file_id = 'MonarchData:' + self.name + \".ttl\"\n        model.addOntologyDeclaration(ontology_file_id)\n        cur_time = datetime.now()\n        t_string = cur_time.strftime(\"%Y-%m-%d\")\n        ontology_version = t_string\n        archive_url = 'MonarchArchive:' + 'ttl/' + self.name + '.ttl'\n        model.addOWLVersionIRI(ontology_file_id, archive_url)\n        model.addOWLVersionInfo(ontology_file_id, ontology_version)",
    "docstring": "The file we output needs to be declared as an ontology,\n        including it's version information.\n\n        TEC: I am not convinced dipper reformating external data as RDF triples\n        makes an OWL ontology (nor that it should be considered a goal).\n\n        Proper ontologies are built by ontologists. Dipper reformats data\n        and anotates/decorates it with a minimal set of carefully arranged\n        terms drawn from from multiple proper ontologies.\n        Which allows the whole (dipper's RDF triples and parent ontologies)\n        to function as a single ontology we can reason over when combined\n        in a store such as SciGraph.\n\n        Including more than the minimal ontological terms in dipper's RDF\n        output constitutes a liability as it allows greater divergence\n        between dipper artifacts and the proper ontologies.\n\n        Further information will be augmented in the dataset object.\n        :param version:\n        :return:"
  },
  {
    "code": "def set_hex_color(self, color, *, index=0, transition_time=None):\n        values = {\n            ATTR_LIGHT_COLOR_HEX: color,\n        }\n        if transition_time is not None:\n            values[ATTR_TRANSITION_TIME] = transition_time\n        return self.set_values(values, index=index)",
    "docstring": "Set hex color of the light."
  },
  {
    "code": "def by_month(self, chamber, year=None, month=None):\n        check_chamber(chamber)\n        now = datetime.datetime.now()\n        year = year or now.year\n        month = month or now.month\n        path = \"{chamber}/votes/{year}/{month}.json\".format(\n            chamber=chamber, year=year, month=month)\n        return self.fetch(path, parse=lambda r: r['results'])",
    "docstring": "Return votes for a single month, defaulting to the current month."
  },
  {
    "code": "def centroids(self, instrument, min_abundance=1e-4, points_per_fwhm=25):\n        assert self.ptr != ffi.NULL\n        centroids = ims.spectrum_envelope_centroids(self.ptr, instrument.ptr,\n                                                    min_abundance, points_per_fwhm)\n        return _new_spectrum(CentroidedSpectrum, centroids)",
    "docstring": "Estimates centroided peaks for a given instrument model.\n\n        :param instrument: instrument model\n        :param min_abundance: minimum abundance for including a peak\n        :param points_per_fwhm: grid density used for envelope calculation\n        :returns: peaks visible with the instrument used\n        :rtype: TheoreticalSpectrum"
  },
  {
    "code": "def _parse_quoted_key(self):\n        quote_style = self._current\n        key_type = None\n        dotted = False\n        for t in KeyType:\n            if t.value == quote_style:\n                key_type = t\n                break\n        if key_type is None:\n            raise RuntimeError(\"Should not have entered _parse_quoted_key()\")\n        self.inc()\n        self.mark()\n        while self._current != quote_style and self.inc():\n            pass\n        key = self.extract()\n        if self._current == \".\":\n            self.inc()\n            dotted = True\n            key += \".\" + self._parse_key().as_string()\n            key_type = KeyType.Bare\n        else:\n            self.inc()\n        return Key(key, key_type, \"\", dotted)",
    "docstring": "Parses a key enclosed in either single or double quotes."
  },
  {
    "code": "def manage(self):\n        hookenv._run_atstart()\n        try:\n            hook_name = hookenv.hook_name()\n            if hook_name == 'stop':\n                self.stop_services()\n            else:\n                self.reconfigure_services()\n                self.provide_data()\n        except SystemExit as x:\n            if x.code is None or x.code == 0:\n                hookenv._run_atexit()\n        hookenv._run_atexit()",
    "docstring": "Handle the current hook by doing The Right Thing with the registered services."
  },
  {
    "code": "def get_profile_ports(self, **kwargs):\n        uri = self._helper.build_uri_with_query_string(kwargs, '/profile-ports')\n        return self._helper.do_get(uri)",
    "docstring": "Retrieves the port model associated with a server or server hardware type and enclosure group.\n\n        Args:\n            enclosureGroupUri (str):\n                The URI of the enclosure group associated with the resource.\n            serverHardwareTypeUri (str):\n                The URI of the server hardware type associated with the resource.\n            serverHardwareUri (str):\n                The URI of the server hardware associated with the resource.\n\n        Returns:\n            dict: Profile port."
  },
  {
    "code": "def start(ctx, alias, description, f):\n    today = datetime.date.today()\n    try:\n        timesheet_collection = get_timesheet_collection_for_context(ctx, f)\n    except ParseError as e:\n        ctx.obj['view'].err(e)\n        return\n    t = timesheet_collection.latest()\n    today_entries = t.entries.filter(date=today)\n    if(today in today_entries and today_entries[today]\n            and isinstance(today_entries[today][-1].duration, tuple)\n            and today_entries[today][-1].duration[1] is not None):\n        new_entry_start_time = today_entries[today][-1].duration[1]\n    else:\n        new_entry_start_time = datetime.datetime.now()\n    description = ' '.join(description) if description else '?'\n    duration = (new_entry_start_time, None)\n    e = Entry(alias, duration, description)\n    t.entries[today].append(e)\n    t.save()",
    "docstring": "Use it when you start working on the given activity. This will add the\n    activity and the current time to your entries file. When you're finished,\n    use the stop command."
  },
  {
    "code": "def update_assessment_taken(self, assessment_taken_form):\n        collection = JSONClientValidated('assessment',\n                                         collection='AssessmentTaken',\n                                         runtime=self._runtime)\n        if not isinstance(assessment_taken_form, ABCAssessmentTakenForm):\n            raise errors.InvalidArgument('argument type is not an AssessmentTakenForm')\n        if not assessment_taken_form.is_for_update():\n            raise errors.InvalidArgument('the AssessmentTakenForm is for update only, not create')\n        try:\n            if self._forms[assessment_taken_form.get_id().get_identifier()] == UPDATED:\n                raise errors.IllegalState('assessment_taken_form already used in an update transaction')\n        except KeyError:\n            raise errors.Unsupported('assessment_taken_form did not originate from this session')\n        if not assessment_taken_form.is_valid():\n            raise errors.InvalidArgument('one or more of the form elements is invalid')\n        collection.save(assessment_taken_form._my_map)\n        self._forms[assessment_taken_form.get_id().get_identifier()] = UPDATED\n        return objects.AssessmentTaken(\n            osid_object_map=assessment_taken_form._my_map,\n            runtime=self._runtime,\n            proxy=self._proxy)",
    "docstring": "Updates an existing assessment taken.\n\n        arg:    assessment_taken_form\n                (osid.assessment.AssessmentTakenForm): the form\n                containing the elements to be updated\n        raise:  IllegalState - ``assessment_taken_form`` already used in\n                an update transaction\n        raise:  InvalidArgument - the form contains an invalid value\n        raise:  NullArgument - ``assessment_taken_form`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure occurred\n        raise:  Unsupported - ``assessment_offered_form`` did not\n                originate from\n                ``get_assessment_taken_form_for_update()``\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def ExpireObject(self, key):\n    node = self._hash.pop(key, None)\n    if node:\n      self._age.Unlink(node)\n      self.KillObject(node.data)\n      return node.data",
    "docstring": "Expire a specific object from cache."
  },
  {
    "code": "def open_link(self):\n        data = self.get_selected_item()\n        if data['url_type'] == 'selfpost':\n            self.open_submission()\n        elif data['url_type'] == 'x-post subreddit':\n            self.refresh_content(order='ignore', name=data['xpost_subreddit'])\n        elif data['url_type'] == 'x-post submission':\n            self.open_submission(url=data['url_full'])\n            self.config.history.add(data['url_full'])\n        else:\n            self.term.open_link(data['url_full'])\n            self.config.history.add(data['url_full'])",
    "docstring": "Open a link with the webbrowser"
  },
  {
    "code": "def set_dimensions(self, variables, unlimited_dims=None):\n        if unlimited_dims is None:\n            unlimited_dims = set()\n        existing_dims = self.get_dimensions()\n        dims = OrderedDict()\n        for v in unlimited_dims:\n            dims[v] = None\n        for v in variables.values():\n            dims.update(dict(zip(v.dims, v.shape)))\n        for dim, length in dims.items():\n            if dim in existing_dims and length != existing_dims[dim]:\n                raise ValueError(\n                    \"Unable to update size for existing dimension\"\n                    \"%r (%d != %d)\" % (dim, length, existing_dims[dim]))\n            elif dim not in existing_dims:\n                is_unlimited = dim in unlimited_dims\n                self.set_dimension(dim, length, is_unlimited)",
    "docstring": "This provides a centralized method to set the dimensions on the data\n        store.\n\n        Parameters\n        ----------\n        variables : dict-like\n            Dictionary of key/value (variable name / xr.Variable) pairs\n        unlimited_dims : list-like\n            List of dimension names that should be treated as unlimited\n            dimensions."
  },
  {
    "code": "def generate_admin_metadata(name, creator_username=None):\n    if not dtoolcore.utils.name_is_valid(name):\n        raise(DtoolCoreInvalidNameError())\n    if creator_username is None:\n        creator_username = dtoolcore.utils.getuser()\n    datetime_obj = datetime.datetime.utcnow()\n    admin_metadata = {\n        \"uuid\": str(uuid.uuid4()),\n        \"dtoolcore_version\": __version__,\n        \"name\": name,\n        \"type\": \"protodataset\",\n        \"creator_username\": creator_username,\n        \"created_at\": dtoolcore.utils.timestamp(datetime_obj)\n    }\n    return admin_metadata",
    "docstring": "Return admin metadata as a dictionary."
  },
  {
    "code": "def get_encoded_query_params(self):\n        get_data = encode_items(self.request.GET.lists())\n        return urlencode(get_data)",
    "docstring": "Return encoded query params to be used in proxied request"
  },
  {
    "code": "def _db_to_python(db_data: dict, table: LdapObjectClass, dn: str) -> LdapObject:\n    fields = table.get_fields()\n    python_data = table({\n        name: field.to_python(db_data[name])\n        for name, field in fields.items()\n        if field.db_field\n    })\n    python_data = python_data.merge({\n        'dn': dn,\n    })\n    return python_data",
    "docstring": "Convert a DbDate object to a LdapObject."
  },
  {
    "code": "def get_text_for_repeated_menu_item(\n        self, request=None, current_site=None, original_menu_tag='', **kwargs\n    ):\n        source_field_name = settings.PAGE_FIELD_FOR_MENU_ITEM_TEXT\n        return self.repeated_item_text or getattr(\n            self, source_field_name, self.title\n        )",
    "docstring": "Return the a string to use as 'text' for this page when it is being\n        included as a 'repeated' menu item in a menu. You might want to\n        override this method if you're creating a multilingual site and you\n        have different translations of 'repeated_item_text' that you wish to\n        surface."
  },
  {
    "code": "async def debug_command_message(self, message, context):\n        conn_string = message.get('connection_string')\n        command = message.get('command')\n        args = message.get('args')\n        client_id = context.user_data\n        result = await self.debug(client_id, conn_string, command, args)\n        return result",
    "docstring": "Handle a debug message.\n\n        See :meth:`AbstractDeviceAdapter.debug`."
  },
  {
    "code": "def getMeta(self, uri):\n        action = urlparse(uri).path\n        mediaKey = self.cacheKey + '_meta_' + action\n        mediaKey = mediaKey.replace(' ', '__')\n        meta = cache.get(mediaKey, None)\n        if not meta:\n            r = self.doQuery('meta/' + uri)\n            if r.status_code == 200:\n                meta = r.json()\n            if 'expire' not in r.headers:\n                expire = 5 * 60\n            else:\n                expire = int((parser.parse(r.headers['expire']) - datetime.datetime.now(tzutc())).total_seconds())\n            if expire > 0:\n                cache.set(mediaKey, meta, expire)\n        return meta",
    "docstring": "Return meta information about an action. Cache the result as specified by the server"
  },
  {
    "code": "def sensor_id(self):\n        if hasattr(self, '_sensor_id'):\n            return self._sensor_id\n        relationships = self._json_data.get('relationships')\n        sensor_id = relationships.get('sensor').get('data').get('id')\n        self._sensor_id = sensor_id\n        return sensor_id",
    "docstring": "The id of the sensor of this data point.\n\n        Returns:\n\n            The id of the sensor that generated this datapoint. Will\n            throw an AttributeError if no sensor id was found in the\n            underlyign data."
  },
  {
    "code": "def set_illuminant(self, illuminant):\n        illuminant = illuminant.lower()\n        if illuminant not in color_constants.ILLUMINANTS[self.observer]:\n            raise InvalidIlluminantError(illuminant)\n        self.illuminant = illuminant",
    "docstring": "Validates and sets the color's illuminant.\n\n        .. note:: This only changes the illuminant. It does no conversion\n            of the color's coordinates. For this, you'll want to refer to\n            :py:meth:`XYZColor.apply_adaptation <colormath.color_objects.XYZColor.apply_adaptation>`.\n\n        .. tip:: Call this after setting your observer.\n\n        :param str illuminant: One of the various illuminants."
  },
  {
    "code": "def can_import(self, file_uris, current_doc=None):\n        if len(file_uris) <= 0:\n            return False\n        for file_uri in file_uris:\n            file_uri = self.fs.safe(file_uri)\n            if not self.check_file_type(file_uri):\n                return False\n        return True",
    "docstring": "Check that the specified file looks like an image supported by PIL"
  },
  {
    "code": "def _make_attr_element_from_typeattr(parent, type_attr_i):\n    attr = _make_attr_element(parent, type_attr_i.attr)\n    if type_attr_i.unit_id is not None:\n        attr_unit    = etree.SubElement(attr, 'unit')\n        attr_unit.text = units.get_unit(type_attr_i.unit_id).abbreviation\n    attr_is_var    = etree.SubElement(attr, 'is_var')\n    attr_is_var.text = type_attr_i.attr_is_var\n    if type_attr_i.data_type is not None:\n        attr_data_type    = etree.SubElement(attr, 'data_type')\n        attr_data_type.text = type_attr_i.data_type\n    if type_attr_i.data_restriction is not None:\n        attr_data_restriction    = etree.SubElement(attr, 'restrictions')\n        attr_data_restriction.text = type_attr_i.data_restriction\n    return attr",
    "docstring": "General function to add an attribute element to a resource element.\n        resource_attr_i can also e a type_attr if being called from get_tempalte_as_xml"
  },
  {
    "code": "def format_str(self):\n        if self.static:\n            return self.route.replace('%','%%')\n        out, i = '', 0\n        for token, value in self.tokens():\n            if token == 'TXT': out += value.replace('%','%%')\n            elif token == 'ANON': out += '%%(anon%d)s' % i; i+=1\n            elif token == 'VAR': out += '%%(%s)s' % value[1]\n        return out",
    "docstring": "Return a format string with named fields."
  },
  {
    "code": "def bind_df_model(model_fit, arima_results):\n    if not hasattr(arima_results, 'df_model'):\n        df_model = model_fit.k_exog + model_fit.k_trend + \\\n            model_fit.k_ar + model_fit.k_ma + \\\n            model_fit.k_seasonal_ar + model_fit.k_seasonal_ma\n        setattr(arima_results, 'df_model', df_model)",
    "docstring": "Set model degrees of freedom.\n\n    Older versions of statsmodels don't handle this issue. Sets the\n    model degrees of freedom in place if not already present.\n\n    Parameters\n    ----------\n    model_fit : ARMA, ARIMA or SARIMAX\n        The fitted model.\n\n    arima_results : ModelResultsWrapper\n        The results wrapper."
  },
  {
    "code": "def update_unit(unit, **kwargs):\n    try:\n        db_unit = db.DBSession.query(Unit).join(Dimension).filter(Unit.id==unit[\"id\"]).filter().one()\n        db_unit.name = unit[\"name\"]\n        db_unit.abbreviation = unit.abbreviation\n        db_unit.description = unit.description\n        db_unit.lf = unit[\"lf\"]\n        db_unit.cf = unit[\"cf\"]\n        if \"project_id\" in unit and unit['project_id'] is not None and unit['project_id'] != \"\":\n            db_unit.project_id = unit[\"project_id\"]\n    except NoResultFound:\n        raise ResourceNotFoundError(\"Unit (ID=%s) does not exist\"%(unit[\"id\"]))\n    db.DBSession.flush()\n    return JSONObject(db_unit)",
    "docstring": "Update a unit in the DB.\n        Raises and exception if the unit does not exist"
  },
  {
    "code": "def choices_from_enum(source: Enum) -> Tuple[Tuple[Any, str], ...]:\n    result = tuple((s.value, s.name.title()) for s in source)\n    return result",
    "docstring": "Makes tuple to use in Django's Fields ``choices`` attribute.\n    Enum members names will be titles for the choices.\n\n    :param source: Enum to process.\n    :return: Tuple to put into ``choices``"
  },
  {
    "code": "def el_to_path_vector(el):\n    path = []\n    while el.parent:\n        path.append(el)\n        el = el.parent\n    return list(reversed(path + [el]))",
    "docstring": "Convert `el` to vector of foregoing elements.\n\n    Attr:\n        el (obj): Double-linked HTMLElement instance.\n\n    Returns:\n        list: HTMLElements which considered as path from root to `el`."
  },
  {
    "code": "def get_word_under_cursor(self, WORD=False):\n        start, end = self.find_boundaries_of_current_word(WORD=WORD)\n        return self.text[self.cursor_position + start: self.cursor_position + end]",
    "docstring": "Return the word, currently below the cursor.\n        This returns an empty string when the cursor is on a whitespace region."
  },
  {
    "code": "def _get_start_end(parts, index=7):\n    start = parts[1]\n    end = [x.split(\"=\")[-1] for x in parts[index].split(\";\") if x.startswith(\"END=\")]\n    if end:\n        end = end[0]\n        return start, end\n    return None, None",
    "docstring": "Retrieve start and end for a VCF record, skips BNDs without END coords"
  },
  {
    "code": "def update(self):\n        for s in self.sensors:\n            s.position = self.io.get_object_position(object_name=s.name)\n            s.orientation = self.io.get_object_orientation(object_name=s.name)",
    "docstring": "Updates the position and orientation of the tracked objects."
  },
  {
    "code": "def generate_transaction_id(stmt_line):\n    return str(abs(hash((stmt_line.date,\n                         stmt_line.memo,\n                         stmt_line.amount))))",
    "docstring": "Generate pseudo-unique id for given statement line.\n\n    This function can be used in statement parsers when real transaction id is\n    not available in source statement."
  },
  {
    "code": "def _combine_attribute(attr_1, attr_2, len_1, len_2):\n        if isinstance(attr_1, list) or isinstance(attr_2, list):\n            attribute = np.concatenate((attr_1, attr_2), axis=0)\n            attribute_changes = True\n        else:\n            if isinstance(attr_1, list) and isinstance(attr_2, list) and np.allclose(attr_1, attr_2):\n                attribute = attr_1\n                attribute_changes = False\n            else:\n                attribute = [attr_1.copy()] * len_1 if type(attr_1) != list else attr_1.copy()\n                attribute.extend([attr_2.copy()] * len_2 if type(attr_2 != list) else attr_2.copy())\n                attribute_changes = True\n        return attribute, attribute_changes",
    "docstring": "Helper function to combine trajectory properties such as site_properties or lattice"
  },
  {
    "code": "def add(self, *args, **kwargs):\n        check_uniqueness = kwargs.pop('check_uniqueness', False)\n        args = self.prepare_args(args)\n        for index in self._indexes:\n            index.add(*args, check_uniqueness=check_uniqueness and index.handle_uniqueness, **kwargs)\n            if check_uniqueness and index.handle_uniqueness:\n                check_uniqueness = False",
    "docstring": "Add the instance tied to the field to all the indexes\n\n        For the parameters, seen BaseIndex.add"
  },
  {
    "code": "def create(cls, jobStore, leaderPath):\n        pathHash = cls._pathHash(leaderPath)\n        contentHash = hashlib.md5()\n        with cls._load(leaderPath) as src:\n            with jobStore.writeSharedFileStream(sharedFileName=pathHash, isProtected=False) as dst:\n                userScript = src.read()\n                contentHash.update(userScript)\n                dst.write(userScript)\n        return cls(name=os.path.basename(leaderPath),\n                   pathHash=pathHash,\n                   url=jobStore.getSharedPublicUrl(sharedFileName=pathHash),\n                   contentHash=contentHash.hexdigest())",
    "docstring": "Saves the content of the file or directory at the given path to the given job store\n        and returns a resource object representing that content for the purpose of obtaining it\n        again at a generic, public URL. This method should be invoked on the leader node.\n\n        :param toil.jobStores.abstractJobStore.AbstractJobStore jobStore:\n\n        :param str leaderPath:\n\n        :rtype: Resource"
  },
  {
    "code": "def assets(self) -> List[Asset]:\n        return list(filter(is_element(Asset), self.content))",
    "docstring": "Returns the assets in the transaction."
  },
  {
    "code": "def construct(cls, attempt_number, value, has_exception):\n        fut = cls(attempt_number)\n        if has_exception:\n            fut.set_exception(value)\n        else:\n            fut.set_result(value)\n        return fut",
    "docstring": "Construct a new Future object."
  },
  {
    "code": "def _format_nsn(number, metadata, num_format, carrier_code=None):\n    intl_number_formats = metadata.intl_number_format\n    if (len(intl_number_formats) == 0 or\n        num_format == PhoneNumberFormat.NATIONAL):\n        available_formats = metadata.number_format\n    else:\n        available_formats = metadata.intl_number_format\n    formatting_pattern = _choose_formatting_pattern_for_number(available_formats, number)\n    if formatting_pattern is None:\n        return number\n    else:\n        return _format_nsn_using_pattern(number, formatting_pattern, num_format, carrier_code)",
    "docstring": "Format a national number."
  },
  {
    "code": "def get_all_parts(self, max_parts=None, part_number_marker=None):\n        self._parts = []\n        query_args = 'uploadId=%s' % self.id\n        if max_parts:\n            query_args += '&max-parts=%d' % max_parts\n        if part_number_marker:\n            query_args += '&part-number-marker=%s' % part_number_marker\n        response = self.bucket.connection.make_request('GET', self.bucket.name,\n                                                       self.key_name,\n                                                       query_args=query_args)\n        body = response.read()\n        if response.status == 200:\n            h = handler.XmlHandler(self, self)\n            xml.sax.parseString(body, h)\n            return self._parts",
    "docstring": "Return the uploaded parts of this MultiPart Upload.  This is\n        a lower-level method that requires you to manually page through\n        results.  To simplify this process, you can just use the\n        object itself as an iterator and it will automatically handle\n        all of the paging with S3."
  },
  {
    "code": "def _create_trustdb(cls):\n    trustdb = os.path.join(cls.homedir, 'trustdb.gpg')\n    if not os.path.isfile(trustdb):\n        log.info(\"GnuPG complained that your trustdb file was missing. %s\"\n                 % \"This is likely due to changing to a new homedir.\")\n        log.info(\"Creating trustdb.gpg file in your GnuPG homedir.\")\n        cls.fix_trustdb(trustdb)",
    "docstring": "Create the trustdb file in our homedir, if it doesn't exist."
  },
  {
    "code": "def create_channel(\n        target: str,\n        options: Optional[List[Tuple[str, Any]]] = None,\n        interceptors: Optional[List[ClientInterceptor]] = None,\n) -> grpc.Channel:\n    options = (options or []) + [\n        (\"grpc.max_send_message_length\", grpc_max_msg_size),\n        (\"grpc.max_receive_message_length\", grpc_max_msg_size),\n    ]\n    interceptors = interceptors or []\n    channel = grpc.insecure_channel(target, options)\n    return grpc.intercept_channel(channel, *interceptors)",
    "docstring": "Creates a gRPC channel\n\n    The gRPC channel is created with the provided options and intercepts each\n    invocation via the provided interceptors.\n\n    The created channel is configured with the following default options:\n        - \"grpc.max_send_message_length\": 100MB,\n        - \"grpc.max_receive_message_length\": 100MB.\n\n    :param target: the server address.\n    :param options: optional list of key-value pairs to configure the channel.\n    :param interceptors: optional list of client interceptors.\n    :returns: a gRPC channel."
  },
  {
    "code": "def set_position(self, position):\n        if position > self._duration():\n            return\n        position_ns = position * _NANOSEC_MULT\n        self._manager[ATTR_POSITION] = position\n        self._player.seek_simple(_FORMAT_TIME, Gst.SeekFlags.FLUSH, position_ns)",
    "docstring": "Set media position."
  },
  {
    "code": "def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):\n    append_memory_pdf_to_writer(input_pdf=input_pdf,\n                                writer=output_writer)",
    "docstring": "Appends a PDF to a pyPDF writer. Legacy interface."
  },
  {
    "code": "def browse_in_qt5_ui(self):\n        self._render_type = \"browse\"\n        self._tree.show(tree_style=self._get_tree_style())",
    "docstring": "Browse and edit the SubjectInfo in a simple Qt5 based UI."
  },
  {
    "code": "def find_conflicts_within_selection_set(\n    context: ValidationContext,\n    cached_fields_and_fragment_names: Dict,\n    compared_fragment_pairs: \"PairSet\",\n    parent_type: Optional[GraphQLNamedType],\n    selection_set: SelectionSetNode,\n) -> List[Conflict]:\n    conflicts: List[Conflict] = []\n    field_map, fragment_names = get_fields_and_fragment_names(\n        context, cached_fields_and_fragment_names, parent_type, selection_set\n    )\n    collect_conflicts_within(\n        context,\n        conflicts,\n        cached_fields_and_fragment_names,\n        compared_fragment_pairs,\n        field_map,\n    )\n    if fragment_names:\n        compared_fragments: Set[str] = set()\n        for i, fragment_name in enumerate(fragment_names):\n            collect_conflicts_between_fields_and_fragment(\n                context,\n                conflicts,\n                cached_fields_and_fragment_names,\n                compared_fragments,\n                compared_fragment_pairs,\n                False,\n                field_map,\n                fragment_name,\n            )\n            for other_fragment_name in fragment_names[i + 1 :]:\n                collect_conflicts_between_fragments(\n                    context,\n                    conflicts,\n                    cached_fields_and_fragment_names,\n                    compared_fragment_pairs,\n                    False,\n                    fragment_name,\n                    other_fragment_name,\n                )\n    return conflicts",
    "docstring": "Find conflicts within selection set.\n\n    Find all conflicts found \"within\" a selection set, including those found via\n    spreading in fragments.\n\n    Called when visiting each SelectionSet in the GraphQL Document."
  },
  {
    "code": "def deletesshkey(self, key_id):\n        request = requests.delete(\n            '{0}/{1}'.format(self.keys_url, key_id), headers=self.headers,\n            verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)\n        if request.content == b'null':\n            return False\n        else:\n            return True",
    "docstring": "Deletes an sshkey for the current user identified by id\n\n        :param key_id: the id of the key\n        :return: False if it didn't delete it, True if it was deleted"
  },
  {
    "code": "def get_correlated_report_ids(self, indicators):\n        params = {'indicators': indicators}\n        resp = self._client.get(\"reports/correlate\", params=params)\n        return resp.json()",
    "docstring": "DEPRECATED!\n        Retrieves a list of the IDs of all TruSTAR reports that contain the searched indicators.\n\n        :param indicators: A list of indicator values to retrieve correlated reports for.\n        :return: The list of IDs of reports that correlated.\n\n        Example:\n\n        >>> report_ids = ts.get_correlated_report_ids([\"wannacry\", \"www.evil.com\"])\n        >>> print(report_ids)\n        [\"e3bc6921-e2c8-42eb-829e-eea8da2d3f36\", \"4d04804f-ff82-4a0b-8586-c42aef2f6f73\"]"
  },
  {
    "code": "def read_string(self, key, embedded=True):\n        data = None\n        if key is not None:\n            key_type = self.variable_type(key)\n            data = self.db.read(key.strip())\n            if data is not None:\n                try:\n                    data = json.loads(data)\n                    if embedded:\n                        data = self.read_embedded(data, key_type)\n                    if data is not None:\n                        data = u'{}'.format(data)\n                except ValueError as e:\n                    err = u'Failed loading JSON data ({}). Error: ({})'.format(data, e)\n                    self.tcex.log.error(err)\n        else:\n            self.tcex.log.warning(u'The key field was None.')\n        return data",
    "docstring": "Read method of CRUD operation for string data.\n\n        Args:\n            key (string): The variable to read from the DB.\n            embedded (boolean): Resolve embedded variables.\n\n        Returns:\n            (string): Results retrieved from DB."
  },
  {
    "code": "def update_energy(self, bypass_check=False):\n        for outlet in self.outlets:\n            outlet.update_energy(bypass_check)",
    "docstring": "Fetch updated energy information about devices"
  },
  {
    "code": "def register_observer(self, observer, events=None):\n        if events is not None and not isinstance(events, (tuple, list)):\n            events = (events,)\n        if observer in self._observers:\n            LOG.warning(\"Observer '%r' already registered, overwriting for events\"\n                        \" %r\", observer, events)\n        self._observers[observer] = events",
    "docstring": "Register a listener function.\n\n        :param observer: external listener function\n        :param events: tuple or list of relevant events (default=None)"
  },
  {
    "code": "def delete_bigger(self):\n        logger.info(\n            \"Deleting all mails strictly bigger than {} bytes...\".format(\n                self.smallest_size))\n        candidates = [\n            mail for mail in self.pool\n            if mail.size > self.smallest_size]\n        if len(candidates) == self.size:\n            logger.warning(\n                \"Skip deletion: all {} mails share the same size.\"\n                \"\".format(self.size))\n        logger.info(\n            \"{} candidates found for deletion.\".format(len(candidates)))\n        for mail in candidates:\n            self.delete(mail)",
    "docstring": "Delete all bigger duplicates.\n\n        Only keeps the subset sharing the smallest size."
  },
  {
    "code": "def history(self, **kwargs):\n        url_str = self.base_url + '/%s/state-history' % kwargs['alarm_id']\n        del kwargs['alarm_id']\n        if kwargs:\n            url_str = url_str + '?%s' % parse.urlencode(kwargs, True)\n        resp = self.client.list(url_str)\n        return resp['elements'] if type(resp) is dict else resp",
    "docstring": "History of a specific alarm."
  },
  {
    "code": "def ajax_login_required(view_func):\n    @wraps(view_func, assigned=available_attrs(view_func))\n    def _wrapped_view(request, *args, **kwargs):\n        if request.is_ajax():\n            if request.user.is_authenticated():\n                return view_func(request, *args, **kwargs)\n            else:\n                response = http.HttpResponse()\n                response['X-Django-Requires-Auth'] = True\n                response['X-Django-Login-Url'] = settings.LOGIN_URL\n                return response\n        else:\n            return login_required(view_func)(request, *args, **kwargs)\n    return _wrapped_view",
    "docstring": "Handle non-authenticated users differently if it is an AJAX request."
  },
  {
    "code": "def update_stack(self, fqn, template, old_parameters, parameters, tags,\n                     force_interactive=False, force_change_set=False,\n                     stack_policy=None, **kwargs):\n        logger.debug(\"Attempting to update stack %s:\", fqn)\n        logger.debug(\"    parameters: %s\", parameters)\n        logger.debug(\"    tags: %s\", tags)\n        if template.url:\n            logger.debug(\"    template_url: %s\", template.url)\n        else:\n            logger.debug(\"    no template url, uploading template directly.\")\n        update_method = self.select_update_method(force_interactive,\n                                                  force_change_set)\n        return update_method(fqn, template, old_parameters, parameters,\n                             stack_policy=stack_policy, tags=tags, **kwargs)",
    "docstring": "Update a Cloudformation stack.\n\n        Args:\n            fqn (str): The fully qualified name of the Cloudformation stack.\n            template (:class:`stacker.providers.base.Template`): A Template\n                object to use when updating the stack.\n            old_parameters (list): A list of dictionaries that defines the\n                parameter list on the existing Cloudformation stack.\n            parameters (list): A list of dictionaries that defines the\n                parameter list to be applied to the Cloudformation stack.\n            tags (list): A list of dictionaries that defines the tags\n                that should be applied to the Cloudformation stack.\n            force_interactive (bool): A flag that indicates whether the update\n                should be interactive. If set to True, interactive mode will\n                be used no matter if the provider is in interactive mode or\n                not. False will follow the behavior of the provider.\n            force_change_set (bool): A flag that indicates whether the update\n                must be executed with a change set.\n            stack_policy (:class:`stacker.providers.base.Template`): A template\n                object representing a stack policy."
  },
  {
    "code": "def set_cache_url (self):\n        self.cache_url = urlutil.urlunsplit(self.urlparts[:4]+[u''])\n        if self.cache_url is not None:\n            assert isinstance(self.cache_url, unicode), repr(self.cache_url)",
    "docstring": "Set the URL to be used for caching."
  },
  {
    "code": "def to_dict(self):\n        if not self.url:\n            return None\n        return {\n            'url': self.url,\n            'width': self.width,\n            'height': self.height\n        }",
    "docstring": "Convert Image into raw dictionary data."
  },
  {
    "code": "def cartesian_to_homogeneous_vectors(cartesian_vector, matrix_type=\"numpy\"):\n    dimension_x = cartesian_vector.shape[0]\n    if matrix_type == \"numpy\":\n        homogeneous_vector = np.zeros(dimension_x + 1)\n        homogeneous_vector[-1] = 1\n        homogeneous_vector[:-1] = cartesian_vector\n    return homogeneous_vector",
    "docstring": "Converts a cartesian vector to an homogenous vector"
  },
  {
    "code": "def should_run(self):\n        should_run = True\n        config = self.target or self.source\n        if config.has('systems'):\n            should_run = False\n            valid_systems = [s.lower() for s in config.get('systems').split(\",\")]\n            for system_type, param in [('is_osx', 'osx'),\n                                       ('is_debian', 'debian')]:\n                if param in valid_systems and getattr(system, system_type)():\n                    should_run = True\n        return should_run",
    "docstring": "Returns true if the feature should run"
  },
  {
    "code": "def get_by_path(path, first=False):\n    api = get_api()\n    cur_res = api\n    parts = path.split(':')\n    for part in parts:\n        res = getattr(cur_res, part, None)\n        if not res:\n            res = find_by_name(cur_res, part)\n        cur_res = res\n    index = getattr(cur_res, 'index', None)\n    if index:\n        return index()\n    return cur_res",
    "docstring": "Search for resources using colon-separated path notation.\n\n    E.g.::\n\n        path = 'deployments:production:servers:haproxy'\n        haproxies = get_by_path(path)\n\n    :param bool first: Always use the first returned match for all intermediate\n        searches along the path.  If this is ``False`` and an intermediate\n        search returns multiple hits, an exception is raised."
  },
  {
    "code": "def has_parent(self, router):\n        parent = self\n        while parent and parent is not router:\n            parent = parent._parent\n        return parent is not None",
    "docstring": "Check if ``router`` is ``self`` or a parent or ``self``"
  },
  {
    "code": "def cluster_number(self, data, maxgap): \n        data.sort()\n        groups = [[data[0]]]\n        for x in data[1:]:\n            if abs(x - groups[-1][-1]) <= maxgap:\n                groups[-1].append(x)\n            else:\n                groups.append([x])\n        return groups",
    "docstring": "General function that clusters numbers.\n\n        Args\n            data (list): list of integers.\n            maxgap (int): max gap between numbers in the cluster."
  },
  {
    "code": "def reject(lst, *values):\n    lst = List.from_maybe(lst)\n    values = frozenset(List.from_maybe_starargs(values))\n    ret = []\n    for item in lst:\n        if item not in values:\n            ret.append(item)\n    return List(ret, use_comma=lst.use_comma)",
    "docstring": "Removes the given values from the list"
  },
  {
    "code": "def ttr(self, kloc, acc=10**3, verbose=1):\n        kloc = numpy.asarray(kloc, dtype=int)\n        shape = kloc.shape\n        kloc = kloc.reshape(len(self), -1)\n        cache = {}\n        out = [evaluation.evaluate_recurrence_coefficients(self, k)\n               for k in kloc.T]\n        out = numpy.array(out).T\n        return out.reshape((2,)+shape)",
    "docstring": "Three terms relation's coefficient generator\n\n        Args:\n            k (numpy.ndarray, int):\n                The order of the coefficients.\n            acc (int):\n                Accuracy of discretized Stieltjes if analytical methods are\n                unavailable.\n\n        Returns:\n            (Recurrence coefficients):\n                Where out[0] is the first (A) and out[1] is the second\n                coefficient With ``out.shape==(2,)+k.shape``."
  },
  {
    "code": "def Get(self):\n    args = user_management_pb2.ApiGetGrrUserArgs(username=self.username)\n    data = self._context.SendRequest(\"GetGrrUser\", args)\n    return GrrUser(data=data, context=self._context)",
    "docstring": "Fetches user's data and returns it wrapped in a Grruser object."
  },
  {
    "code": "def get_filename(disposition):\n    if disposition:\n        params = [param.strip() for param in disposition.split(';')[1:]]\n        for param in params:\n            if '=' in param:\n                name, value = param.split('=', 1)\n                if name == 'filename':\n                    return value.strip('\"')",
    "docstring": "Parse Content-Disposition header to pull out the filename bit.\n\n    See: http://tools.ietf.org/html/rfc2616#section-19.5.1"
  },
  {
    "code": "def jsoned(struct, wrap=True, meta=None, struct_key='result', pre_render_callback=None):\n    return _json.dumps(\n        structured(\n            struct, wrap=wrap, meta=meta, struct_key=struct_key,\n            pre_render_callback=pre_render_callback),\n        default=json_encoder)",
    "docstring": "Provides a json dump of the struct\n\n    Args:\n        struct: The data to dump\n        wrap (bool, optional): Specify whether to wrap the\n            struct in an enclosing dict\n        struct_key (str, optional): The string key which will\n            contain the struct in the result dict\n        meta (dict, optional): An optional dictonary to merge\n            with the output dictionary.\n\n    Examples:\n\n        >>> jsoned([3,4,5])\n        ... '{\"status\": \"success\", \"result\": [3, 4, 5]}'\n\n        >>> jsoned([3,4,5], wrap=False)\n        ... '[3, 4, 5]'"
  },
  {
    "code": "def account_info(self):\n        response = self._post(self.apiurl + \"/v2/account/info\", data={'apikey': self.apikey})\n        return self._raise_or_extract(response)",
    "docstring": "Only available on Joe Sandbox Cloud\n\n        Show information about the account."
  },
  {
    "code": "def set_timestamp(self, time: Union[str, datetime.datetime] = None,\n                      now: bool = False) -> None:\n        if now:\n            self.timestamp = str(datetime.datetime.utcnow())\n        else:\n            self.timestamp = str(time)",
    "docstring": "Sets the timestamp of the embed.\n\n        Parameters\n        ----------\n        time: str or :class:`datetime.datetime`\n            The ``ISO 8601`` timestamp from the embed.\n\n        now: bool\n            Defaults to :class:`False`.\n            If set to :class:`True` the current time is used for the timestamp."
  },
  {
    "code": "def _init_datastore_v3_stub(self, **stub_kwargs):\n        task_args = dict(datastore_file=self._data_path)\n        task_args.update(stub_kwargs)\n        self.testbed.init_datastore_v3_stub(**task_args)",
    "docstring": "Initializes the datastore stub using nosegae config magic"
  },
  {
    "code": "def get_cpds(self):\n        cpds = self.model.get_cpds()\n        tables = {}\n        for cpd in cpds:\n            tables[cpd.variable] = cpd.values.ravel()\n        return tables",
    "docstring": "Adds tables to BIF\n\n        Returns\n        -------\n        dict: dict of type {variable: array}\n\n        Example\n        -------\n        >>> from pgmpy.readwrite import BIFReader, BIFWriter\n        >>> model = BIFReader('dog-problem.bif').get_model()\n        >>> writer = BIFWriter(model)\n        >>> writer.get_cpds()\n        {'bowel-problem': array([ 0.01,  0.99]),\n         'dog-out': array([ 0.99,  0.97,  0.9 ,  0.3 ,  0.01,  0.03,  0.1 ,  0.7 ]),\n         'family-out': array([ 0.15,  0.85]),\n         'hear-bark': array([ 0.7 ,  0.01,  0.3 ,  0.99]),\n         'light-on': array([ 0.6 ,  0.05,  0.4 ,  0.95])}"
  },
  {
    "code": "def get_internal_angles(self):\n        angles = []\n        for elx, elz in zip(self.grid['x'], self.grid['z']):\n            el_angles = []\n            xy = np.vstack((elx, elz))\n            for i in range(0, elx.size):\n                i1 = (i - 1) % elx.size\n                i2 = (i + 1) % elx.size\n                a = (xy[:, i] - xy[:, i1])\n                b = (xy[:, i2] - xy[:, i])\n                angle = np.pi - np.arctan2(\n                    a[0] * b[1] - a[1] * b[0],\n                    a[0] * b[0] + a[1] * b[1]\n                )\n                el_angles.append(angle * 180 / np.pi)\n            angles.append(el_angles)\n        return np.array(angles)",
    "docstring": "Compute all internal angles of the grid\n\n        Returns\n        -------\n        numpy.ndarray\n            NxK array with N the number of elements, and K the number of nodes,\n            filled with the internal angles in degrees"
  },
  {
    "code": "def create_object(cls, members):\n    obj = cls.__new__(cls)\n    obj.__dict__ = members\n    return obj",
    "docstring": "Promise an object of class `cls` with content `members`."
  },
  {
    "code": "def main():\n    logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n    parser = argparse.ArgumentParser(\n        description='Test the SMA webconnect library.')\n    parser.add_argument(\n        'ip', type=str, help='IP address of the Webconnect module')\n    parser.add_argument(\n        'user', help='installer/user')\n    parser.add_argument(\n        'password', help='Installer password')\n    args = parser.parse_args()\n    loop = asyncio.get_event_loop()\n    def _shutdown(*_):\n        VAR['running'] = False\n    signal.signal(signal.SIGINT, _shutdown)\n    loop.run_until_complete(main_loop(\n        loop, user=args.user, password=args.password, ip=args.ip))",
    "docstring": "Main example."
  },
  {
    "code": "def delete(self, event):\n        super(CeleryReceiver, self).delete(event)\n        AsyncResult(event.id).revoke(terminate=True)",
    "docstring": "Abort running task if it exists."
  },
  {
    "code": "def create(self, repo_name, scm='git', private=True, **kwargs):\n        url = self.bitbucket.url('CREATE_REPO')\n        return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, name=repo_name, scm=scm, is_private=private, **kwargs)",
    "docstring": "Creates a new repository on own Bitbucket account and return it."
  },
  {
    "code": "def unpack_source_dists(self, arguments, use_wheels=False):\n        unpack_timer = Timer()\n        logger.info(\"Unpacking distribution(s) ..\")\n        with PatchedAttribute(pip_install_module, 'PackageFinder', CustomPackageFinder):\n            requirements = self.get_pip_requirement_set(arguments, use_remote_index=False, use_wheels=use_wheels)\n            logger.info(\"Finished unpacking %s in %s.\", pluralize(len(requirements), \"distribution\"), unpack_timer)\n            return requirements",
    "docstring": "Find and unpack local source distributions and discover their metadata.\n\n        :param arguments: The command line arguments to ``pip install ...`` (a\n                          list of strings).\n        :param use_wheels: Whether pip and pip-accel are allowed to use wheels_\n                           (:data:`False` by default for backwards compatibility\n                           with callers that use pip-accel as a Python API).\n        :returns: A list of :class:`pip_accel.req.Requirement` objects.\n        :raises: Any exceptions raised by pip, for example\n                 :exc:`pip.exceptions.DistributionNotFound` when not all\n                 requirements can be satisfied.\n\n        This function checks whether there are local source distributions\n        available for all requirements, unpacks the source distribution\n        archives and finds the names and versions of the requirements. By using\n        the ``pip install --download`` command we avoid reimplementing the\n        following pip features:\n\n        - Parsing of ``requirements.txt`` (including recursive parsing).\n        - Resolution of possibly conflicting pinned requirements.\n        - Unpacking source distributions in multiple formats.\n        - Finding the name & version of a given source distribution."
  },
  {
    "code": "def _eval_args(args):\n    res = []\n    for arg in args:\n        if not isinstance(arg, tuple):\n            res.append(arg)\n        elif is_callable_type(arg[0]):\n            callable_args = _eval_args(arg[1:])\n            if len(arg) == 2:\n                res.append(Callable[[], callable_args[0]])\n            elif arg[1] is Ellipsis:\n                res.append(Callable[..., callable_args[1]])\n            else:\n                res.append(Callable[list(callable_args[:-1]), callable_args[-1]])\n        else:\n            res.append(type(arg[0]).__getitem__(arg[0], _eval_args(arg[1:])))\n    return tuple(res)",
    "docstring": "Internal helper for get_args."
  },
  {
    "code": "def is_item_public(self, permission_name, view_name):\n        permissions = self.get_public_permissions()\n        if permissions:\n            for i in permissions:\n                if (view_name == i.view_menu.name) and (\n                    permission_name == i.permission.name\n                ):\n                    return True\n            return False\n        else:\n            return False",
    "docstring": "Check if view has public permissions\n\n            :param permission_name:\n                the permission: can_show, can_edit...\n            :param view_name:\n                the name of the class view (child of BaseView)"
  },
  {
    "code": "def get_slice_nodes(self, time_slice=0):\n        if not isinstance(time_slice, int) or time_slice < 0:\n            raise ValueError(\"The timeslice should be a positive value greater than or equal to zero\")\n        return [(node, time_slice) for node in self._nodes()]",
    "docstring": "Returns the nodes present in a particular timeslice\n\n        Parameters\n        ----------\n        time_slice:int\n                The timeslice should be a positive value greater than or equal to zero\n\n        Examples\n        --------\n        >>> from pgmpy.models import DynamicBayesianNetwork as DBN\n        >>> dbn = DBN()\n        >>> dbn.add_nodes_from(['D', 'G', 'I', 'S', 'L'])\n        >>> dbn.add_edges_from([(('D', 0),('G', 0)),(('I', 0),('G', 0)),(('G', 0),('L', 0)),(('D', 0),('D', 1))])\n        >>> dbn.get_slice_nodes()"
  },
  {
    "code": "def remove_wirevector(self, wirevector):\n        self.wirevector_set.remove(wirevector)\n        del self.wirevector_by_name[wirevector.name]",
    "docstring": "Remove a wirevector object to the block."
  },
  {
    "code": "def refine_cand(candsfile, candloc=[], candnum=-1, threshold=0, scaledm=2.1, scalepix=2, scaleuv=1.0, chans=[], returndata=False):\n    if candnum >= 0:\n        candlocs, candprops, d0 = pc.read_candidates(candsfile, snrmin=threshold, returnstate=True)\n        candloc = candlocs[candnum]\n        candprop = candprops[candnum]\n        logger.info('Refining cand {0} with features {1}'.format(candloc, candprop))\n        values = rt.pipeline_refine(d0, candloc, scaledm=scaledm, scalepix=scalepix, scaleuv=scaleuv, chans=chans, returndata=returndata)\n        return values\n    elif candloc:\n        logger.info('Refining cand {0}'.format(candloc))\n        d0 = pickle.load(open(candsfile, 'r'))\n        values = rt.pipeline_refine(d0, candloc, scaledm=scaledm, scalepix=scalepix, scaleuv=scaleuv, chans=chans, returndata=returndata)\n        return d, cands\n    else:\n        return None",
    "docstring": "Helper function to interact with merged cands file and refine analysis\n\n    candsfile is merged pkl file\n    candloc (scan, segment, candint, dmind, dtind, beamnum) is as above.\n    if no candloc, then it prints out cands above threshold."
  },
  {
    "code": "def shared_prefix(args):\n    i = 0\n    while i < min(map(len, args)):\n        if len(set(map(operator.itemgetter(i), args))) != 1:\n            break\n        i += 1\n    return args[0][:i]",
    "docstring": "Find the shared prefix between the strings.\n\n    For instance:\n\n        sharedPrefix(['blahblah', 'blahwhat'])\n\n    returns 'blah'."
  },
  {
    "code": "def break_around_binary_operator(logical_line, tokens):\n    r\n    def is_binary_operator(token_type, text):\n        return ((token_type == tokenize.OP or text in ['and', 'or']) and\n                text not in \"()[]{},:.;@=%~\")\n    line_break = False\n    unary_context = True\n    previous_token_type = None\n    previous_text = None\n    for token_type, text, start, end, line in tokens:\n        if token_type == tokenize.COMMENT:\n            continue\n        if ('\\n' in text or '\\r' in text) and token_type != tokenize.STRING:\n            line_break = True\n        else:\n            if (is_binary_operator(token_type, text) and line_break and\n                    not unary_context and\n                    not is_binary_operator(previous_token_type,\n                                           previous_text)):\n                yield start, \"W503 line break before binary operator\"\n            unary_context = text in '([{,;'\n            line_break = False\n            previous_token_type = token_type\n            previous_text = text",
    "docstring": "r\"\"\"\n    Avoid breaks before binary operators.\n\n    The preferred place to break around a binary operator is after the\n    operator, not before it.\n\n    W503: (width == 0\\n + height == 0)\n    W503: (width == 0\\n and height == 0)\n\n    Okay: (width == 0 +\\n height == 0)\n    Okay: foo(\\n    -x)\n    Okay: foo(x\\n    [])\n    Okay: x = '''\\n''' + ''\n    Okay: foo(x,\\n    -y)\n    Okay: foo(x,  # comment\\n    -y)\n    Okay: var = (1 &\\n       ~2)\n    Okay: var = (1 /\\n       -2)\n    Okay: var = (1 +\\n       -1 +\\n       -2)"
  },
  {
    "code": "def keypress(self, size, key):\n        key = self.__super.keypress(size, key)\n        if key:\n            key = self.unhandled_keys(size, key)\n        return key",
    "docstring": "allow subclasses to intercept keystrokes"
  },
  {
    "code": "def __equalize_densities(self,nominal_bounds,nominal_density):\n        left,bottom,right,top = nominal_bounds.lbrt()\n        width = right-left; height = top-bottom\n        center_y = bottom + height/2.0\n        true_density = int(nominal_density*(width))/float(width)\n        n_cells = round(height*true_density,0)\n        adjusted_half_height = n_cells/true_density/2.0\n        return (BoundingBox(points=((left, center_y-adjusted_half_height),\n                                    (right, center_y+adjusted_half_height))),\n                true_density)",
    "docstring": "Calculate the true density along x, and adjust the top and\n        bottom bounds so that the density along y will be equal.\n\n        Returns (adjusted_bounds, true_density)"
  },
  {
    "code": "def v_reference_leaf_leafref(ctx, stmt):\n    if (hasattr(stmt, 'i_leafref') and\n        stmt.i_leafref is not None and\n        stmt.i_leafref_expanded is False):\n        path_type_spec = stmt.i_leafref\n        not_req_inst = not(path_type_spec.require_instance)\n        x = validate_leafref_path(ctx, stmt,\n                                  path_type_spec.path_spec,\n                                  path_type_spec.path_,\n                                  accept_non_config_target=not_req_inst\n        )\n        if x is None:\n            return\n        ptr, expanded_path, path_list = x\n        path_type_spec.i_target_node = ptr\n        path_type_spec.i_expanded_path = expanded_path\n        path_type_spec.i_path_list = path_list\n        stmt.i_leafref_expanded = True\n        if ptr is not None:\n            chk_status(ctx, stmt, ptr)\n            stmt.i_leafref_ptr = (ptr, path_type_spec.pos)",
    "docstring": "Verify that all leafrefs in a leaf or leaf-list have correct path"
  },
  {
    "code": "def _artifact_base(self):\n        if '_artifact_base' not in self._memo:\n            for artifact in self._artifacts:\n                if self.re_target.search(artifact['name']) is not None:\n                    artifact_base = os.path.splitext(artifact['name'])[0]\n                    break\n            else:\n                raise FetcherException('Could not find build info in artifacts')\n            self._memo['_artifact_base'] = artifact_base\n        return self._memo['_artifact_base']",
    "docstring": "Build the artifact basename\n        Builds are base.tar.bz2, info is base.json, shell is base.jsshell.zip..."
  },
  {
    "code": "def grid_coords_from_corners(upper_left_corner, lower_right_corner, size):\n    assert upper_left_corner.wkt == lower_right_corner.wkt\n    geotransform = np.array([upper_left_corner.lon, -(upper_left_corner.lon - lower_right_corner.lon) / float(size[1]), 0,\n                            upper_left_corner.lat, 0, -(upper_left_corner.lat - lower_right_corner.lat) / float(size[0])])\n    return GridCoordinates(geotransform=geotransform,\n                               wkt=upper_left_corner.wkt,\n                               y_size=size[0],\n                               x_size=size[1])",
    "docstring": "Points are the outer edges of the UL and LR pixels. Size is rows, columns.\n    GC projection type is taken from Points."
  },
  {
    "code": "def init(self):\n        try:\n            start_http_server(port=int(self.port), addr=self.host)\n        except Exception as e:\n            logger.critical(\"Can not start Prometheus exporter on {}:{} ({})\".format(self.host, self.port, e))\n            sys.exit(2)\n        else:\n            logger.info(\"Start Prometheus exporter on {}:{}\".format(self.host, self.port))",
    "docstring": "Init the Prometheus Exporter"
  },
  {
    "code": "def patch_worker_run_task():\n    _run_task = luigi.worker.Worker._run_task\n    def run_task(self, task_id):\n        task = self._scheduled_tasks[task_id]\n        task._worker_id = self._id\n        task._worker_task = self._first_task\n        try:\n            _run_task(self, task_id)\n        finally:\n            task._worker_id = None\n            task._worker_task = None\n        if os.getenv(\"LAW_SANDBOX_SWITCHED\") == \"1\":\n            self._start_phasing_out()\n    luigi.worker.Worker._run_task = run_task",
    "docstring": "Patches the ``luigi.worker.Worker._run_task`` method to store the worker id and the id of its\n    first task in the task. This information is required by the sandboxing mechanism"
  },
  {
    "code": "def resolve_extensions(bot: commands.Bot, name: str) -> list:\n    if name.endswith('.*'):\n        module_parts = name[:-2].split('.')\n        path = pathlib.Path(module_parts.pop(0))\n        for part in module_parts:\n            path = path / part\n        return find_extensions_in(path)\n    if name == '~':\n        return list(bot.extensions.keys())\n    return [name]",
    "docstring": "Tries to resolve extension queries into a list of extension names."
  },
  {
    "code": "def _complete_history(self, cmd, args, text):\n        if args:\n            return\n        return [ x for x in { 'clear', 'clearall' } \\\n                if x.startswith(text) ]",
    "docstring": "Find candidates for the 'history' command."
  },
  {
    "code": "def next_free_pos(self, address):\n        idx = self._search(address)\n        if idx < len(self._list) and self._list[idx].start <= address < self._list[idx].end:\n            i = idx\n            while i + 1 < len(self._list) and self._list[i].end == self._list[i + 1].start:\n                i += 1\n            if i == len(self._list):\n                return self._list[-1].end\n            return self._list[i].end\n        return address",
    "docstring": "Returns the next free position with respect to an address, including that address itself\n\n        :param address: The address to begin the search with (including itself)\n        :return: The next free position"
  },
  {
    "code": "def _check_content(self, content_str):\n        if self.do_content_check:\n            space_ratio = float(content_str.count(' '))/len(content_str)\n            if space_ratio > self.max_space_ratio:\n                return \"space-ratio: %f > %f\" % (space_ratio,\n                                                 self.max_space_ratio)\n            if len(content_str) > self.input_character_limit:\n                return \"too long: %d > %d\" % (len(content_str),\n                                              self.input_character_limit)\n        return None",
    "docstring": "Check if the content is likely to be successfully read."
  },
  {
    "code": "def pcapname(dev):\n    if isinstance(dev, NetworkInterface):\n        if dev.is_invalid():\n            return None\n        return dev.pcap_name\n    try:\n        return IFACES.dev_from_name(dev).pcap_name\n    except ValueError:\n        return IFACES.dev_from_pcapname(dev).pcap_name",
    "docstring": "Get the device pcap name by device name or Scapy NetworkInterface"
  },
  {
    "code": "def getEyeOutputViewport(self, eEye):\n        fn = self.function_table.getEyeOutputViewport\n        pnX = c_uint32()\n        pnY = c_uint32()\n        pnWidth = c_uint32()\n        pnHeight = c_uint32()\n        fn(eEye, byref(pnX), byref(pnY), byref(pnWidth), byref(pnHeight))\n        return pnX.value, pnY.value, pnWidth.value, pnHeight.value",
    "docstring": "Gets the viewport in the frame buffer to draw the output of the distortion into"
  },
  {
    "code": "def pct_decode(s):\n    if s is None:\n        return None\n    elif not isinstance(s, unicode):\n        s = str(s)\n    else:\n        s = s.encode('utf8')\n    return PERCENT_CODE_SUB(lambda mo: chr(int(mo.group(0)[1:], 16)), s)",
    "docstring": "Return the percent-decoded version of string s.\n\n    >>> pct_decode('%43%6F%75%63%6F%75%2C%20%6A%65%20%73%75%69%73%20%63%6F%6E%76%69%76%69%61%6C')\n    'Coucou, je suis convivial'\n    >>> pct_decode('')\n    ''\n    >>> pct_decode('%2525')\n    '%25'"
  },
  {
    "code": "def get(cls, id_):\n        with db.session.no_autoflush:\n            query = cls.dbmodel.query.filter_by(id=id_)\n            try:\n                model = query.one()\n            except NoResultFound:\n                raise WorkflowsMissingObject(\"No object for for id {0}\".format(\n                    id_\n                ))\n            return cls(model)",
    "docstring": "Return a workflow object from id."
  },
  {
    "code": "def get(self, key, defaultValue=None):\n        if defaultValue is None:\n            if self._jconf is not None:\n                if not self._jconf.contains(key):\n                    return None\n                return self._jconf.get(key)\n            else:\n                if key not in self._conf:\n                    return None\n                return self._conf[key]\n        else:\n            if self._jconf is not None:\n                return self._jconf.get(key, defaultValue)\n            else:\n                return self._conf.get(key, defaultValue)",
    "docstring": "Get the configured value for some key, or return a default otherwise."
  },
  {
    "code": "def local_lambda_runner(self):\n        layer_downloader = LayerDownloader(self._layer_cache_basedir, self.get_cwd())\n        image_builder = LambdaImage(layer_downloader,\n                                    self._skip_pull_image,\n                                    self._force_image_build)\n        lambda_runtime = LambdaRuntime(self._container_manager, image_builder)\n        return LocalLambdaRunner(local_runtime=lambda_runtime,\n                                 function_provider=self._function_provider,\n                                 cwd=self.get_cwd(),\n                                 env_vars_values=self._env_vars_value,\n                                 debug_context=self._debug_context)",
    "docstring": "Returns an instance of the runner capable of running Lambda functions locally\n\n        :return samcli.commands.local.lib.local_lambda.LocalLambdaRunner: Runner configured to run Lambda functions\n            locally"
  },
  {
    "code": "def set_hook(fn, key, **kwargs):\n    if fn is None:\n        return functools.partial(set_hook, key=key, **kwargs)\n    try:\n        hook_config = fn.__marshmallow_hook__\n    except AttributeError:\n        fn.__marshmallow_hook__ = hook_config = {}\n    hook_config[key] = kwargs\n    return fn",
    "docstring": "Mark decorated function as a hook to be picked up later.\n\n    .. note::\n        Currently only works with functions and instance methods. Class and\n        static methods are not supported.\n\n    :return: Decorated function if supplied, else this decorator with its args\n        bound."
  },
  {
    "code": "def slave_envs(self):\n        if self.hostIP == 'dns':\n            host = socket.gethostname()\n        elif self.hostIP == 'ip':\n            host = socket.gethostbyname(socket.getfqdn())\n        else:\n            host = self.hostIP\n        return {'rabit_tracker_uri': host,\n                'rabit_tracker_port': self.port}",
    "docstring": "get enviroment variables for slaves\n        can be passed in as args or envs"
  },
  {
    "code": "def boost(self, boost):\n        _LOGGER.debug(\"Setting boost mode: %s\", boost)\n        value = struct.pack('BB', PROP_BOOST, bool(boost))\n        self._conn.make_request(PROP_WRITE_HANDLE, value)",
    "docstring": "Sets boost mode."
  },
  {
    "code": "def opcode_list(self, script):\n        opcodes = []\n        new_pc = 0\n        try:\n            for opcode, data, pc, new_pc in self.get_opcodes(script):\n                opcodes.append(self.disassemble_for_opcode_data(opcode, data))\n        except ScriptError:\n            opcodes.append(binascii.hexlify(script[new_pc:]).decode(\"utf8\"))\n        return opcodes",
    "docstring": "Disassemble the given script. Returns a list of opcodes."
  },
  {
    "code": "def add_option(self, section, option, value=None):\n        if not self.config.has_section(section):\n            message = self.add_section(section)\n            if not message[0]:\n                return message\n        if not self.config.has_option(section, option):\n            if value:\n                self.config.set(section, option, value)\n            else:\n                self.config.set(section, option)\n            return(True, self.config.options(section))\n        return(False, 'Option: {} already exists @ {}'.format(option, section))",
    "docstring": "Creates an option for a section. If the section does\n        not exist, it will create the section."
  },
  {
    "code": "def request(self, account, amount):\n        return self._keeper.dispenser.request_tokens(amount, account)",
    "docstring": "Request a number of tokens to be minted and transfered to `account`\n\n        :param account: Account instance requesting the tokens\n        :param amount: int number of tokens to request\n        :return: bool"
  },
  {
    "code": "def update_image_digest(self, image, platform, digest):\n        image_name_tag = self._key(image)\n        image_name = image.to_str(tag=False)\n        name_digest = '{}@{}'.format(image_name, digest)\n        image_digests = self._images_digests.setdefault(image_name_tag, {})\n        image_digests[platform] = name_digest",
    "docstring": "Update parent image digest for specific platform\n\n        :param ImageName image: image\n        :param str platform: name of the platform/arch (x86_64, ppc64le, ...)\n        :param str digest: digest of the specified image (sha256:...)"
  },
  {
    "code": "def filter_mean(matrix, top):\n    assert isinstance(matrix, ExpMatrix)\n    assert isinstance(top, int)\n    if top >= matrix.p:\n        logger.warning('Gene expression filter with `top` parameter that is '\n                       '>= the number of genes!')\n        top = matrix.p\n    a = np.argsort(np.mean(matrix.X, axis=1))\n    a = a[::-1]\n    sel = np.zeros(matrix.p, dtype=np.bool_)\n    sel[a[:top]] = True\n    matrix = matrix.loc[sel]\n    return matrix",
    "docstring": "Filter genes in an expression matrix by mean expression.\n\n    Parameters\n    ----------\n    matrix: ExpMatrix\n        The expression matrix.\n    top: int\n        The number of genes to retain.\n\n    Returns\n    -------\n    ExpMatrix\n        The filtered expression matrix."
  },
  {
    "code": "def _set_attachments(self, value):\n        if value is None:\n            setattr(self, '_PMMail__attachments', [])\n        elif isinstance(value, list):\n            setattr(self, '_PMMail__attachments', value)\n        else:\n            raise TypeError('Attachments must be a list')",
    "docstring": "A special set function to ensure\n        we're setting with a list"
  },
  {
    "code": "def save_to_filename(self, file_name, sep='\\n'):\n        fp = open(file_name, 'wb')\n        n = self.save_to_file(fp, sep)\n        fp.close()\n        return n",
    "docstring": "Read all messages from the queue and persist them to local file.\n        Messages are written to the file and the 'sep' string is written\n        in between messages.  Messages are deleted from the queue after\n        being written to the file.\n        Returns the number of messages saved."
  },
  {
    "code": "def remaining_quota(self, remaining_quota):\n        if remaining_quota is None:\n            raise ValueError(\"Invalid value for `remaining_quota`, must not be `None`\")\n        if remaining_quota is not None and remaining_quota < 0:\n            raise ValueError(\"Invalid value for `remaining_quota`, must be a value greater than or equal to `0`\")\n        self._remaining_quota = remaining_quota",
    "docstring": "Sets the remaining_quota of this ServicePackageMetadata.\n        Current available service package quota.\n\n        :param remaining_quota: The remaining_quota of this ServicePackageMetadata.\n        :type: int"
  },
  {
    "code": "def get_resource_solvers(self, resource):\n        solvers_classes = [s for s in self.resource_solver_classes if s.can_solve(resource)]\n        if solvers_classes:\n            solvers = []\n            for solver_class in solvers_classes:\n                if solver_class not in self._resource_solvers_cache:\n                    self._resource_solvers_cache[solver_class] = solver_class(self)\n                solvers.append(self._resource_solvers_cache[solver_class])\n            return solvers\n        raise SolverNotFound(self, resource)",
    "docstring": "Returns the resource solvers that can solve the given resource.\n\n        Arguments\n        ---------\n        resource : dataql.resources.Resource\n            An instance of a subclass of ``Resource`` for which we want to get the solver\n            classes that can solve it.\n\n        Returns\n        -------\n        list\n            The list of resource solvers instances that can solve the given resource.\n\n        Raises\n        ------\n        dataql.solvers.exceptions.SolverNotFound\n            When no solver is able to solve the given resource.\n\n        Example\n        -------\n\n        >>> from dataql.resources import Field, List\n        >>> registry = Registry()\n        >>> registry.get_resource_solvers(Field(name='foo'))\n        [<AttributeSolver>]\n        >>> registry.get_resource_solvers(List(name='foo'))\n        [<ListSolver>]\n        >>> registry.get_resource_solvers(None) # doctest: +ELLIPSIS\n        Traceback (most recent call last):\n        dataql.solvers.exceptions.SolverNotFound: No solvers found for this kind of object:..."
  },
  {
    "code": "def calc_Cmin(mh, mc, Cph, Cpc):\n    r\n    Ch = mh*Cph\n    Cc = mc*Cpc\n    return min(Ch, Cc)",
    "docstring": "r'''Returns the heat capacity rate for the minimum stream\n    having flows `mh` and `mc`, with averaged heat capacities `Cph` and `Cpc`.\n\n    .. math::\n        C_c = m_cC_{p,c}\n\n        C_h = m_h C_{p,h}\n\n        C_{min} = \\min(C_c, C_h)\n\n    Parameters\n    ----------\n    mh : float\n        Mass flow rate of hot stream, [kg/s]\n    mc : float\n        Mass flow rate of cold stream, [kg/s]\n    Cph : float\n        Averaged heat capacity of hot stream, [J/kg/K]\n    Cpc : float\n        Averaged heat capacity of cold stream, [J/kg/K]\n\n    Returns\n    -------\n    Cmin : float\n        The heat capacity rate of the smaller fluid, [W/K]\n\n    Notes\n    -----\n    Used with the effectiveness method for heat exchanger design.\n    Technically, it doesn't matter if the hot and cold streams are in the right\n    order for the input, but it is easiest to use this function when the order\n    is specified.\n\n    Examples\n    --------\n    >>> calc_Cmin(mh=22., mc=5.5, Cph=2200, Cpc=4400.)\n    24200.0\n\n    References\n    ----------\n    .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n       David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n       Wiley, 2011."
  },
  {
    "code": "def bucket_ops(bid, api=\"\"):\n    try:\n        yield 42\n    except ClientError as e:\n        code = e.response['Error']['Code']\n        log.info(\n            \"bucket error bucket:%s error:%s\",\n            bid,\n            e.response['Error']['Code'])\n        if code == \"NoSuchBucket\":\n            pass\n        elif code == 'AccessDenied':\n            connection.sadd('buckets-denied', bid)\n        else:\n            connection.hset(\n                'buckets-unknown-errors',\n                bid,\n                \"%s:%s\" % (api, e.response['Error']['Code']))\n    except Exception as e:\n        connection.hset(\n            'buckets-unknown-errors',\n            bid,\n            \"%s:%s\" % (api, str(e)))\n        raise",
    "docstring": "Context manager for dealing with s3 errors in one place\n\n    bid: bucket_id in form of account_name:bucket_name"
  },
  {
    "code": "def renew_secret(client, creds, opt):\n    if opt.reuse_token:\n        return\n    seconds = grok_seconds(opt.lease)\n    if not seconds:\n        raise aomi.exceptions.AomiCommand(\"invalid lease %s\" % opt.lease)\n    renew = None\n    if client.version:\n        v_bits = client.version.split('.')\n        if int(v_bits[0]) == 0 and \\\n           int(v_bits[1]) <= 8 and \\\n           int(v_bits[2]) <= 0:\n            r_obj = {\n                'increment': seconds\n            }\n            r_path = \"v1/sys/renew/{0}\".format(creds['lease_id'])\n            renew = client._post(r_path, json=r_obj).json()\n    if not renew:\n        renew = client.renew_secret(creds['lease_id'], seconds)\n    if not renew or (seconds - renew['lease_duration'] >= 5):\n        client.revoke_self_token()\n        e_msg = 'Unable to renew with desired lease'\n        raise aomi.exceptions.VaultConstraint(e_msg)",
    "docstring": "Renews a secret. This will occur unless the user has\n    specified on the command line that it is not neccesary"
  },
  {
    "code": "def colors_to_materials(colors, count=None):\n    rgba = to_rgba(colors)\n    if util.is_shape(rgba, (4,)) and count is not None:\n        diffuse = rgba.reshape((-1, 4))\n        index = np.zeros(count, dtype=np.int)\n    elif util.is_shape(rgba, (-1, 4)):\n        unique, index = grouping.unique_rows(rgba)\n        diffuse = rgba[unique]\n    else:\n        raise ValueError('Colors not convertible!')\n    return diffuse, index",
    "docstring": "Convert a list of colors into a list of unique materials\n    and material indexes.\n\n    Parameters\n    -----------\n    colors : (n, 3) or (n, 4) float\n      RGB or RGBA colors\n    count : int\n      Number of entities to apply color to\n\n    Returns\n    -----------\n    diffuse : (m, 4) int\n      Colors\n    index : (count,) int\n      Index of each color"
  },
  {
    "code": "def label(self, name, value, cluster_ids=None):\n        if cluster_ids is None:\n            cluster_ids = self.cluster_view.selected\n        if not hasattr(cluster_ids, '__len__'):\n            cluster_ids = [cluster_ids]\n        if len(cluster_ids) == 0:\n            return\n        self.cluster_meta.set(name, cluster_ids, value)\n        self._global_history.action(self.cluster_meta)",
    "docstring": "Assign a label to clusters.\n\n        Example: `quality 3`"
  },
  {
    "code": "def create_virtualenv(venv_dir, use_venv_module=True):\n        if not use_venv_module:\n            try:\n                check_call(['virtualenv', venv_dir, '--no-site-packages'])\n            except OSError:\n                raise Exception('You probably dont have virtualenv installed: sudo apt-get install python-virtualenv')\n        else:\n            check_call([sys.executable or 'python', '-m', 'venv', venv_dir])",
    "docstring": "creates a new virtualenv in venv_dir\n\n        By default, the built-in venv module is used.\n        On older versions of python, you may set use_venv_module to False to use virtualenv"
  },
  {
    "code": "def to_parfiles(self,prefix):\n        if self.isnull().values.any():\n            warnings.warn(\"NaN in par ensemble\",PyemuWarning)\n        if self.istransformed:\n            self._back_transform(inplace=True)\n        par_df = self.pst.parameter_data.loc[:,\n                 [\"parnme\",\"parval1\",\"scale\",\"offset\"]].copy()\n        for real in self.index:\n            par_file = \"{0}{1}.par\".format(prefix,real)\n            par_df.loc[:,\"parval1\"] =self.loc[real,:]\n            write_parfile(par_df,par_file)",
    "docstring": "write the parameter ensemble to PEST-style parameter files\n\n        Parameters\n        ----------\n        prefix: str\n            file prefix for par files\n\n        Note\n        ----\n        this function back-transforms inplace with respect to\n        log10 before writing"
  },
  {
    "code": "def print_long(filename, stat, print_func):\n    size = stat_size(stat)\n    mtime = stat_mtime(stat)\n    file_mtime = time.localtime(mtime)\n    curr_time = time.time()\n    if mtime > (curr_time + SIX_MONTHS) or mtime < (curr_time - SIX_MONTHS):\n        print_func('%6d %s %2d %04d  %s' % (size, MONTH[file_mtime[1]],\n                                            file_mtime[2], file_mtime[0],\n                                            decorated_filename(filename, stat)))\n    else:\n        print_func('%6d %s %2d %02d:%02d %s' % (size, MONTH[file_mtime[1]],\n                                                file_mtime[2], file_mtime[3], file_mtime[4],\n                                                decorated_filename(filename, stat)))",
    "docstring": "Prints detailed information about the file passed in."
  },
  {
    "code": "def and_raises(self, *errors):\n        \"Expects an error or more to be raised from the given expectation.\"\n        for error in errors:\n            self.__expect(Expectation.raises, error)",
    "docstring": "Expects an error or more to be raised from the given expectation."
  },
  {
    "code": "def set_join_rule(self, room_id, join_rule):\n        content = {\n            \"join_rule\": join_rule\n        }\n        return self.send_state_event(room_id, \"m.room.join_rules\", content)",
    "docstring": "Set the rule for users wishing to join the room.\n\n        Args:\n            room_id(str): The room to set the rules for.\n            join_rule(str): The chosen rule. One of: [\"public\", \"knock\",\n                \"invite\", \"private\"]"
  },
  {
    "code": "def _correctIsotopeImpurities(matrix, intensities):\n    correctedIntensities, _ = scipy.optimize.nnls(matrix, intensities)\n    return correctedIntensities",
    "docstring": "Corrects observed reporter ion intensities for isotope impurities.\n\n    :params matrix: a matrix (2d nested list) containing numbers, each isobaric\n        channel must be present as a COLUMN. Use maspy.isobar._transposeMatrix()\n        if channels are written in rows.\n    :param intensities: numpy array of observed reporter ion intensities.\n    :returns: a numpy array of reporter ion intensities corrected for isotope\n        impurities."
  },
  {
    "code": "def _get_stddevs(self, C, stddev_types, mag, num_sites):\n        stddevs = []\n        for _ in stddev_types:\n            if mag < 7.16:\n                sigma = C['c11'] + C['c12'] * mag\n            elif mag >= 7.16:\n                sigma = C['c13']\n            stddevs.append(np.zeros(num_sites) + sigma)\n        return stddevs",
    "docstring": "Return total standard deviation as for equation 35, page 1021."
  },
  {
    "code": "def add_device_callback(self, devices, callback):\n        if not devices:\n            return False\n        if not isinstance(devices, (tuple, list)):\n            devices = [devices]\n        for device in devices:\n            device_id = device\n            if isinstance(device, AbodeDevice):\n                device_id = device.device_id\n            if not self._abode.get_device(device_id):\n                raise AbodeException((ERROR.EVENT_DEVICE_INVALID))\n            _LOGGER.debug(\n                \"Subscribing to updated for device_id: %s\", device_id)\n            self._device_callbacks[device_id].append((callback))\n        return True",
    "docstring": "Register a device callback."
  },
  {
    "code": "def putnotify(self, name, *args):\n        self.queues[name][0].put(*args)\n        self.queues[name][1].set()",
    "docstring": "Puts data into queue and alerts listeners"
  },
  {
    "code": "def get_user(self, name):\n        users = self.data['users']\n        for user in users:\n            if user['name'] == name:\n                return user\n        raise KubeConfError(\"user name not found.\")",
    "docstring": "Get user from kubeconfig."
  },
  {
    "code": "def alterar(self, id_script_type, type, description):\n        if not is_valid_int_param(id_script_type):\n            raise InvalidParameterError(\n                u'The identifier of Script Type is invalid or was not informed.')\n        script_type_map = dict()\n        script_type_map['type'] = type\n        script_type_map['description'] = description\n        url = 'scripttype/' + str(id_script_type) + '/'\n        code, xml = self.submit({'script_type': script_type_map}, 'PUT', url)\n        return self.response(code, xml)",
    "docstring": "Change Script Type from by the identifier.\n\n        :param id_script_type: Identifier of the Script Type. Integer value and greater than zero.\n        :param type: Script Type type. String with a minimum 3 and maximum of 40 characters\n        :param description: Script Type description. String with a minimum 3 and maximum of 100 characters\n\n        :return: None\n\n        :raise InvalidParameterError: The identifier of Script Type, type or description is null and invalid.\n        :raise TipoRoteiroNaoExisteError: Script Type not registered.\n        :raise NomeTipoRoteiroDuplicadoError: Type script already registered with informed.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def save_performance(db, job_id, records):\n    rows = [(job_id, rec['operation'], rec['time_sec'], rec['memory_mb'],\n             int(rec['counts'])) for rec in records]\n    db.insert('performance',\n              'job_id operation time_sec memory_mb counts'.split(), rows)",
    "docstring": "Save in the database the performance information about the given job.\n\n    :param db: a :class:`openquake.server.dbapi.Db` instance\n    :param job_id: a job ID\n    :param records: a list of performance records"
  },
  {
    "code": "def map(self, map_fn, desc=None):\n        if desc is None:\n            desc = getattr(map_fn, '__name__', '')\n        desc = u'map({})'.format(desc)\n        return self.transform(lambda xs: (map_fn(x) for x in xs), desc=desc)",
    "docstring": "Return a copy of this query, with the values mapped through `map_fn`.\n\n        Args:\n            map_fn (callable): A callable that takes a single argument and returns a new value.\n\n        Keyword Args:\n            desc (str): A description of the mapping transform, for use in log message.\n                Defaults to the name of the map function.\n\n        Returns:\n            Query"
  },
  {
    "code": "def pyxwriter(self):\n        model = self.Model()\n        if hasattr(self, 'Parameters'):\n            model.parameters = self.Parameters(vars(self))\n        else:\n            model.parameters = parametertools.Parameters(vars(self))\n        if hasattr(self, 'Sequences'):\n            model.sequences = self.Sequences(model=model, **vars(self))\n        else:\n            model.sequences = sequencetools.Sequences(model=model,\n                                                      **vars(self))\n        return PyxWriter(self, model, self.pyxfilepath)",
    "docstring": "Update the pyx file."
  },
  {
    "code": "def exponential_backoff(self):\n        last_service_switch = self._service_starttime\n        if not last_service_switch:\n            return\n        time_since_last_switch = time.time() - last_service_switch\n        if not self._service_rapidstarts:\n            self._service_rapidstarts = 0\n        minimum_wait = 0.1 * (2 ** self._service_rapidstarts)\n        minimum_wait = min(5, minimum_wait)\n        if time_since_last_switch > 10:\n            self._service_rapidstarts = 0\n            return\n        self._service_rapidstarts += 1\n        self.log.debug(\"Slowing down service starts (%.1f seconds)\", minimum_wait)\n        time.sleep(minimum_wait)",
    "docstring": "A function that keeps waiting longer and longer the more rapidly it is called.\n        It can be used to increasingly slow down service starts when they keep failing."
  },
  {
    "code": "def create(cls, data, id_=None, **kwargs):\n        r\n        from .models import RecordMetadata\n        with db.session.begin_nested():\n            record = cls(data)\n            before_record_insert.send(\n                current_app._get_current_object(),\n                record=record\n            )\n            record.validate(**kwargs)\n            record.model = RecordMetadata(id=id_, json=record)\n            db.session.add(record.model)\n        after_record_insert.send(\n            current_app._get_current_object(),\n            record=record\n        )\n        return record",
    "docstring": "r\"\"\"Create a new record instance and store it in the database.\n\n        #. Send a signal :data:`invenio_records.signals.before_record_insert`\n           with the new record as parameter.\n\n        #. Validate the new record data.\n\n        #. Add the new record in the database.\n\n        #. Send a signal :data:`invenio_records.signals.after_record_insert`\n           with the new created record as parameter.\n\n        :Keyword Arguments:\n          * **format_checker** --\n            An instance of the class :class:`jsonschema.FormatChecker`, which\n            contains validation rules for formats. See\n            :func:`~invenio_records.api.RecordBase.validate` for more details.\n\n          * **validator** --\n            A :class:`jsonschema.IValidator` class that will be used to\n            validate the record. See\n            :func:`~invenio_records.api.RecordBase.validate` for more details.\n\n        :param data: Dict with the record metadata.\n        :param id_: Specify a UUID to use for the new record, instead of\n                    automatically generated.\n        :returns: A new :class:`Record` instance."
  },
  {
    "code": "def authenticate(self, transport, account_name, password):\n        if not isinstance(transport, ZimbraClientTransport):\n            raise ZimbraClientException('Invalid transport')\n        if util.empty(account_name):\n            raise AuthException('Empty account name')",
    "docstring": "Authenticates account, if no password given tries to pre-authenticate.\n        @param transport: transport to use for method calls\n        @param account_name: account name\n        @param password: account password\n        @return: AuthToken if authentication succeeded\n        @raise AuthException: if authentication fails"
  },
  {
    "code": "def generate_page(self, path, template, **kwargs):\n\t\tdirectory = None\n\t\tif kwargs.get('page'):\n\t\t\tdirectory = kwargs['page'].dir\n\t\tpath = self._get_dist_path(path, directory=directory)\n\t\tif not path.endswith('.html'):\n\t\t\tpath = path + '.html'\n\t\tif not os.path.isdir(os.path.dirname(path)):\n\t\t\tos.makedirs(os.path.dirname(path))\n\t\thtml = self._get_template(template).render(**kwargs)\n\t\twith open(path, 'w+') as file:\n\t\t\tfile.write(html)",
    "docstring": "Generate the HTML for a single page. You usually don't need to call this\n\t\tmethod manually, it is used by a lot of other, more end-user friendly\n\t\tmethods.\n\n\t\tArgs:\n\t\t  path (str): Where to place the page relative to the root URL. Usually\n\t\t    something like \"index\", \"about-me\", \"projects/example\", etc.\n\t\t  template (str): Which jinja template to use to render the page.\n\t\t  **kwargs: Kwargs will be passed on to the jinja template. Also, if\n\t\t    the `page` kwarg is passed, its directory attribute will be\n\t\t    prepended to the path."
  },
  {
    "code": "def hist(self, by=None, bins=10, **kwds):\n        return self(kind='hist', by=by, bins=bins, **kwds)",
    "docstring": "Draw one histogram of the DataFrame's columns.\n\n        A histogram is a representation of the distribution of data.\n        This function groups the values of all given Series in the DataFrame\n        into bins and draws all bins in one :class:`matplotlib.axes.Axes`.\n        This is useful when the DataFrame's Series are in a similar scale.\n\n        Parameters\n        ----------\n        by : str or sequence, optional\n            Column in the DataFrame to group by.\n        bins : int, default 10\n            Number of histogram bins to be used.\n        **kwds\n            Additional keyword arguments are documented in\n            :meth:`DataFrame.plot`.\n\n        Returns\n        -------\n        class:`matplotlib.AxesSubplot`\n            Return a histogram plot.\n\n        See Also\n        --------\n        DataFrame.hist : Draw histograms per DataFrame's Series.\n        Series.hist : Draw a histogram with Series' data.\n\n        Examples\n        --------\n        When we draw a dice 6000 times, we expect to get each value around 1000\n        times. But when we draw two dices and sum the result, the distribution\n        is going to be quite different. A histogram illustrates those\n        distributions.\n\n        .. plot::\n            :context: close-figs\n\n            >>> df = pd.DataFrame(\n            ...     np.random.randint(1, 7, 6000),\n            ...     columns = ['one'])\n            >>> df['two'] = df['one'] + np.random.randint(1, 7, 6000)\n            >>> ax = df.plot.hist(bins=12, alpha=0.5)"
  },
  {
    "code": "def undisplayable_info(obj, html=False):\n    \"Generate helpful message regarding an undisplayable object\"\n    collate = '<tt>collate</tt>' if html else 'collate'\n    info = \"For more information, please consult the Composing Data tutorial (http://git.io/vtIQh)\"\n    if isinstance(obj, HoloMap):\n        error = \"HoloMap of %s objects cannot be displayed.\" % obj.type.__name__\n        remedy = \"Please call the %s method to generate a displayable object\" % collate\n    elif isinstance(obj, Layout):\n        error = \"Layout containing HoloMaps of Layout or GridSpace objects cannot be displayed.\"\n        remedy = \"Please call the %s method on the appropriate elements.\" % collate\n    elif isinstance(obj, GridSpace):\n        error = \"GridSpace containing HoloMaps of Layouts cannot be displayed.\"\n        remedy = \"Please call the %s method on the appropriate elements.\" % collate\n    if not html:\n        return '\\n'.join([error, remedy, info])\n    else:\n        return \"<center>{msg}</center>\".format(msg=('<br>'.join(\n            ['<b>%s</b>' % error, remedy, '<i>%s</i>' % info])))",
    "docstring": "Generate helpful message regarding an undisplayable object"
  },
  {
    "code": "def lookup_url(self, url):\n        if type(url) is not str:\n            url = url.encode('utf8')\n        if not url.strip():\n            raise ValueError(\"Empty input string.\")\n        url_hashes = URL(url).hashes\n        try:\n            list_names = self._lookup_hashes(url_hashes)\n            self.storage.commit()\n        except Exception:\n            self.storage.rollback()\n            raise\n        if list_names:\n            return list_names\n        return None",
    "docstring": "Look up specified URL in Safe Browsing threat lists."
  },
  {
    "code": "def _memory_profile(with_gc=False):\n    import utool as ut\n    if with_gc:\n        garbage_collect()\n    import guppy\n    hp = guppy.hpy()\n    print('[hpy] Waiting for heap output...')\n    heap_output = hp.heap()\n    print(heap_output)\n    print('[hpy] total heap size: ' + ut.byte_str2(heap_output.size))\n    ut.util_resources.memstats()",
    "docstring": "Helper for memory debugging. Mostly just a namespace where I experiment with\n    guppy and heapy.\n\n    References:\n        http://stackoverflow.com/questions/2629680/deciding-between-subprocess-multiprocessing-and-thread-in-python\n\n    Reset Numpy Memory::\n        %reset out\n        %reset array"
  },
  {
    "code": "def list_bindings_for_vhost(self, vhost):\n        return self._api_get('/api/bindings/{}'.format(\n            urllib.parse.quote_plus(vhost)\n        ))",
    "docstring": "A list of all bindings in a given virtual host.\n\n        :param vhost: The vhost name\n        :type vhost: str"
  },
  {
    "code": "def get_field_errors(self, field):\n        identifier = format_html('{0}[\\'{1}\\']', self.form_name, field.name)\n        errors = self.errors.get(field.html_name, [])\n        return self.error_class([SafeTuple(\n            (identifier, self.field_error_css_classes, '$pristine', '$pristine', 'invalid', e)) for e in errors])",
    "docstring": "Return server side errors. Shall be overridden by derived forms to add their\n        extra errors for AngularJS."
  },
  {
    "code": "def forw_dfs(self, start, end=None):\n        return list(self.iterdfs(start, end, forward=True))",
    "docstring": "Returns a list of nodes in some forward DFS order.\n\n        Starting with the start node the depth first search proceeds along\n        outgoing edges."
  },
  {
    "code": "def add_device_not_active_callback(self, callback):\n        _LOGGER.debug('Added new callback %s ', callback)\n        self._cb_device_not_active.append(callback)",
    "docstring": "Register callback to be invoked when a device is not responding."
  },
  {
    "code": "def children(self, node, relations=None):\n        g = self.get_graph()\n        if node in g:\n            children = list(g.successors(node))\n            if relations is None:\n                return children\n            else:\n                rset = set(relations)\n                return [c for c in children if len(self.child_parent_relations(c, node, graph=g).intersection(rset)) > 0 ]\n        else:\n            return []",
    "docstring": "Return all direct children of specified node.\n\n        Wraps networkx by default.\n\n        Arguments\n        ---------\n\n        node: string\n\n           identifier for node in ontology\n\n        relations: list of strings\n\n           list of relation (object property) IDs used to filter"
  },
  {
    "code": "def run(self):\n        states = open(self.states, 'r').read().splitlines()\n        for state in states:\n            url = self.build_url(state)\n            log = \"Downloading State < {0} > from < {1} >\"\n            logging.info(log.format(state, url))\n            tmp = self.download(self.output, url, self.overwrite)\n            self.s3.store(self.extract(tmp, self.tmp2poi(tmp)))",
    "docstring": "For each state in states file build url and download file"
  },
  {
    "code": "def _scalar_operations(self, axis, scalar, func):\n        if isinstance(scalar, (list, np.ndarray, pandas.Series)):\n            new_index = self.index if axis == 0 else self.columns\n            def list_like_op(df):\n                if axis == 0:\n                    df.index = new_index\n                else:\n                    df.columns = new_index\n                return func(df)\n            new_data = self._map_across_full_axis(\n                axis, self._prepare_method(list_like_op)\n            )\n            return self.__constructor__(new_data, self.index, self.columns)\n        else:\n            return self._map_partitions(self._prepare_method(func))",
    "docstring": "Handler for mapping scalar operations across a Manager.\n\n        Args:\n            axis: The axis index object to execute the function on.\n            scalar: The scalar value to map.\n            func: The function to use on the Manager with the scalar.\n\n        Returns:\n            A new QueryCompiler with updated data and new index."
  },
  {
    "code": "def repo_name(self):\n        ds = [[x.repo_name] for x in self.repos]\n        df = pd.DataFrame(ds, columns=['repository'])\n        return df",
    "docstring": "Returns a DataFrame of the repo names present in this project directory\n\n        :return: DataFrame"
  },
  {
    "code": "def _load_from_file(self, filename):\n    if not tf.gfile.Exists(filename):\n      raise ValueError(\"File %s not found\" % filename)\n    with tf.gfile.Open(filename) as f:\n      self._load_from_file_object(f)",
    "docstring": "Load from a vocab file."
  },
  {
    "code": "def _do_add_floating_ip_asr1k(self, floating_ip, fixed_ip, vrf,\n                                  ex_gw_port):\n        vlan = ex_gw_port['hosting_info']['segmentation_id']\n        hsrp_grp = ex_gw_port[ha.HA_INFO]['group']\n        LOG.debug(\"add floating_ip: %(fip)s, fixed_ip: %(fixed_ip)s, \"\n                  \"vrf: %(vrf)s, ex_gw_port: %(port)s\",\n                  {'fip': floating_ip, 'fixed_ip': fixed_ip, 'vrf': vrf,\n                   'port': ex_gw_port})\n        confstr = (asr1k_snippets.SET_STATIC_SRC_TRL_NO_VRF_MATCH %\n            (fixed_ip, floating_ip, vrf, hsrp_grp, vlan))\n        self._edit_running_config(confstr, 'SET_STATIC_SRC_TRL_NO_VRF_MATCH')",
    "docstring": "To implement a floating ip, an ip static nat is configured in the\n        underlying router ex_gw_port contains data to derive the vlan\n        associated with related subnet for the fixed ip.  The vlan in turn\n        is applied to the redundancy parameter for setting the IP NAT."
  },
  {
    "code": "def autodiscover():\n    import copy\n    from django.conf import settings\n    from django.utils.importlib import import_module\n    for app in settings.INSTALLED_APPS:\n        before_import_registry = copy.copy(gargoyle._registry)\n        try:\n            import_module('%s.gargoyle' % app)\n        except:\n            gargoyle._registry = before_import_registry\n    __import__('gargoyle.builtins')",
    "docstring": "Auto-discover INSTALLED_APPS admin.py modules and fail silently when\n    not present. This forces an import on them to register any admin bits they\n    may want."
  },
  {
    "code": "def length_curve(obj):\n    if not isinstance(obj, abstract.Curve):\n        raise GeomdlException(\"Input shape must be an instance of abstract.Curve class\")\n    length = 0.0\n    evalpts = obj.evalpts\n    num_evalpts = len(obj.evalpts)\n    for idx in range(num_evalpts - 1):\n        length += linalg.point_distance(evalpts[idx], evalpts[idx + 1])\n    return length",
    "docstring": "Computes the approximate length of the parametric curve.\n\n    Uses the following equation to compute the approximate length:\n\n    .. math::\n\n        \\\\sum_{i=0}^{n-1} \\\\sqrt{P_{i + 1}^2-P_{i}^2}\n\n    where :math:`n` is number of evaluated curve points and :math:`P` is the n-dimensional point.\n\n    :param obj: input curve\n    :type obj: abstract.Curve\n    :return: length\n    :rtype: float"
  },
  {
    "code": "def umount(self, forced=True):\n        for child in self._children:\n            if hasattr(child, \"umount\"):\n                child.umount(forced)",
    "docstring": "Umount all mountable distribution points.\n\n        Defaults to using forced method."
  },
  {
    "code": "def get_nmr_prize_pool(self, round_num=0, tournament=1):\n        tournaments = self.get_competitions(tournament)\n        tournaments.sort(key=lambda t: t['number'])\n        if round_num == 0:\n            t = tournaments[-1]\n        else:\n            tournaments = [t for t in tournaments if t['number'] == round_num]\n            if len(tournaments) == 0:\n                raise ValueError(\"invalid round number\")\n            t = tournaments[0]\n        return t['prizePoolNmr']",
    "docstring": "Get NMR prize pool for the given round and tournament.\n\n        Args:\n            round_num (int, optional): The round you are interested in,\n                defaults to current round.\n            tournament (int, optional): ID of the tournament, defaults to 1\n\n        Returns:\n            decimal.Decimal: prize pool in NMR\n\n        Raises:\n            Value Error: in case of invalid round number"
  },
  {
    "code": "def remove_behaviour(self, behaviour):\n        if not self.has_behaviour(behaviour):\n            raise ValueError(\"This behaviour is not registered\")\n        index = self.behaviours.index(behaviour)\n        self.behaviours[index].kill()\n        self.behaviours.pop(index)",
    "docstring": "Removes a behaviour from the agent.\n        The behaviour is first killed.\n\n        Args:\n          behaviour (spade.behaviour.CyclicBehaviour): the behaviour instance to be removed"
  },
  {
    "code": "def simple_state_machine():\n    from random import random\n    from furious.async import Async\n    number = random()\n    logging.info('Generating a number... %s', number)\n    if number > 0.25:\n        logging.info('Continuing to do stuff.')\n        return Async(target=simple_state_machine)\n    return number",
    "docstring": "Pick a number, if it is more than some cuttoff continue the chain."
  },
  {
    "code": "def listEverything(matching=False):\n    pages=pageNames()\n    if matching:\n        pages=[x for x in pages if matching in x]\n    for i,page in enumerate(pages):\n        pages[i]=\"%s%s (%s)\"%(pageFolder(page),page,getPageType(page))\n    print(\"\\n\".join(sorted(pages)))",
    "docstring": "Prints every page in the project to the console.\n\n    Args:\n        matching (str, optional): if given, only return names with this string in it"
  },
  {
    "code": "def _generate_examples(self, images_dir_path, csv_path=None, csv_usage=None):\n    if csv_path:\n      with tf.io.gfile.GFile(csv_path) as csv_f:\n        reader = csv.DictReader(csv_f)\n        data = [(row[\"image\"], int(row[\"level\"]))\n                for row in reader\n                if csv_usage is None or row[\"Usage\"] == csv_usage]\n    else:\n      data = [(fname[:-5], -1)\n              for fname in tf.io.gfile.listdir(images_dir_path)\n              if fname.endswith(\".jpeg\")]\n    for name, label in data:\n      yield {\n          \"name\": name,\n          \"image\": _resize_image_if_necessary(\n              tf.io.gfile.GFile(\"%s/%s.jpeg\" % (images_dir_path, name),\n                                mode=\"rb\"),\n              target_pixels=self.builder_config.target_pixels),\n          \"label\": label,\n      }",
    "docstring": "Yields Example instances from given CSV.\n\n    Args:\n      images_dir_path: path to dir in which images are stored.\n      csv_path: optional, path to csv file with two columns: name of image and\n        label. If not provided, just scan image directory, don't set labels.\n      csv_usage: optional, subset of examples from the csv file to use based on\n        the \"Usage\" column from the csv."
  },
  {
    "code": "def _deregister_config_file(self, key):\n        state = self.__load_state()\n        if 'remove_configs' not in state:\n            state['remove_configs'] = {}\n        state['remove_configs'][key] = (state['config_files'].pop(key))\n        self.__dump_state(state)",
    "docstring": "Deregister a previously registered config file.  The caller should\n        ensure that it was previously registered."
  },
  {
    "code": "def solve(self, solver=None, solverparameters=None):\n        if self.F is None:\n            raise Exception(\"Relaxation is not generated yet. Call \"\n                            \"'SdpRelaxation.get_relaxation' first\")\n        solve_sdp(self, solver, solverparameters)",
    "docstring": "Call a solver on the SDP relaxation. Upon successful solution, it\n        returns the primal and dual objective values along with the solution\n        matrices. It also sets these values in the `sdpRelaxation` object,\n        along with some status information.\n\n        :param sdpRelaxation: The SDP relaxation to be solved.\n        :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`.\n        :param solver: The solver to be called, either `None`, \"sdpa\", \"mosek\",\n                       \"cvxpy\", \"scs\", or \"cvxopt\". The default is `None`,\n                       which triggers autodetect.\n        :type solver: str.\n        :param solverparameters: Parameters to be passed to the solver. Actual\n                                 options depend on the solver:\n\n                                 SDPA:\n\n                                   - `\"executable\"`:\n                                     Specify the executable for SDPA. E.g.,\n                                     `\"executable\":\"/usr/local/bin/sdpa\"`, or\n                                     `\"executable\":\"sdpa_gmp\"`\n                                   - `\"paramsfile\"`: Specify the parameter file\n\n                                 Mosek:\n                                 Refer to the Mosek documentation. All\n                                 arguments are passed on.\n\n                                 Cvxopt:\n                                 Refer to the PICOS documentation. All\n                                 arguments are passed on.\n\n                                 Cvxpy:\n                                 Refer to the Cvxpy documentation. All\n                                 arguments are passed on.\n\n                                 SCS:\n                                 Refer to the Cvxpy documentation. All\n                                 arguments are passed on.\n\n        :type solverparameters: dict of str."
  },
  {
    "code": "def nan_empty(self, col: str):\n        try:\n            self.df[col] = self.df[col].replace('', nan)\n            self.ok(\"Filled empty values with nan in column \" + col)\n        except Exception as e:\n            self.err(e, \"Can not fill empty values with nan\")",
    "docstring": "Fill empty values with NaN values\n\n        :param col: name of the colum\n        :type col: str\n\n        :example: ``ds.nan_empty(\"mycol\")``"
  },
  {
    "code": "def set_size(self, w, h):\n        self.attributes['width'] = str(w)\n        self.attributes['height'] = str(h)",
    "docstring": "Sets the rectangle size.\n\n        Args:\n            w (int): width of the rectangle\n            h (int): height of the rectangle"
  },
  {
    "code": "def get(self, request, *args, **kwargs):\n        serializer_class = self.get_serializer_class()\n        context = self.get_serializer_context()\n        services = []\n        for service_type in SERVICES.keys():\n            services.append(\n                serializer_class(\n                    object(),\n                    context=context,\n                    service_type=service_type\n                ).data\n            )\n        return Response(services)",
    "docstring": "return list of open 311 services"
  },
  {
    "code": "def list_servers(backend, socket=DEFAULT_SOCKET_URL, objectify=False):\n    ha_conn = _get_conn(socket)\n    ha_cmd = haproxy.cmds.listServers(backend=backend)\n    return ha_conn.sendCmd(ha_cmd, objectify=objectify)",
    "docstring": "List servers in haproxy backend.\n\n    backend\n        haproxy backend\n\n    socket\n        haproxy stats socket, default ``/var/run/haproxy.sock``\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' haproxy.list_servers mysql"
  },
  {
    "code": "def trim_seqs(input_seqs, trim_len, left_trim_len):\n    logger = logging.getLogger(__name__)\n    okseqs = 0\n    totseqs = 0\n    if trim_len < -1:\n        raise ValueError(\"Invalid trim_len: %d\" % trim_len)\n    for label, seq in input_seqs:\n        totseqs += 1\n        if trim_len == -1:\n            okseqs += 1\n            yield label, seq\n        elif len(seq) >= trim_len:\n            okseqs += 1\n            yield label, seq[left_trim_len:trim_len]\n    if okseqs < 0.01*totseqs:\n        logger = logging.getLogger(__name__)\n        errmsg = 'Vast majority of sequences (%d / %d) are shorter ' \\\n                 'than the trim length (%d). ' \\\n                 'Are you using the correct -t trim length?' \\\n                 % (totseqs-okseqs, totseqs, trim_len)\n        logger.warn(errmsg)\n        warnings.warn(errmsg, UserWarning)\n    else:\n        logger.debug('trimmed to length %d (%d / %d remaining)'\n                     % (trim_len, okseqs, totseqs))",
    "docstring": "Trim FASTA sequences to specified length.\n\n    Parameters\n    ----------\n    input_seqs : iterable of (str, str)\n        The list of input sequences in (label, sequence) format\n    trim_len : int\n        Sequence trimming length. Specify a value of -1 to disable trimming.\n    left_trim_len : int\n        Sequence trimming from the 5' end. A value of 0 will disable this trim.\n\n\n    Returns\n    -------\n    Generator of (str, str)\n        The trimmed sequences in (label, sequence) format"
  },
  {
    "code": "def getPagePixmap(doc, pno, matrix = None, colorspace = csRGB,\n                  clip = None, alpha = True):\n    return doc[pno].getPixmap(matrix = matrix, colorspace = colorspace,\n                          clip = clip, alpha = alpha)",
    "docstring": "Create pixmap of document page by page number.\n\n    Notes:\n        Convenience function calling page.getPixmap.\n    Args:\n        pno: (int) page number\n        matrix: Matrix for transformation (default: Identity).\n        colorspace: (str/Colorspace) rgb, rgb, gray - case ignored, default csRGB.\n        clip: (irect-like) restrict rendering to this area.\n        alpha: (bool) include alpha channel"
  },
  {
    "code": "def varexp(line):\n    ip = get_ipython()\n    funcname, name = line.split()\n    try:\n        import guiqwt.pyplot as pyplot\n    except:\n        import matplotlib.pyplot as pyplot\n    __fig__ = pyplot.figure();\n    __items__ = getattr(pyplot, funcname[2:])(ip.user_ns[name])\n    pyplot.show()\n    del __fig__, __items__",
    "docstring": "Spyder's variable explorer magic\n\n    Used to generate plots, histograms and images of the variables displayed\n    on it."
  },
  {
    "code": "def write_attribute_adj_list(self, path):\n        att_mappings = self.get_attribute_mappings()\n        with open(path, mode=\"w\") as file:\n            for k, v in att_mappings.items():\n                print(\"{} {}\".format(k, \" \".join(str(e) for e in v)), file=file)",
    "docstring": "Write the bipartite attribute graph to a file.\n\n        :param str path: Path to the output file."
  },
  {
    "code": "def tab_insert(self, e):\n        u\r\n        cursor = min(self.l_buffer.point, len(self.l_buffer.line_buffer))\r\n        ws = ' ' * (self.tabstop - (cursor % self.tabstop))\r\n        self.insert_text(ws)\r\n        self.finalize()",
    "docstring": "u'''Insert a tab character."
  },
  {
    "code": "def time_segments_aggregate(X, interval, time_column, method=['mean']):\n    if isinstance(X, np.ndarray):\n        X = pd.DataFrame(X)\n    X = X.sort_values(time_column).set_index(time_column)\n    if isinstance(method, str):\n        method = [method]\n    start_ts = X.index.values[0]\n    max_ts = X.index.values[-1]\n    values = list()\n    index = list()\n    while start_ts <= max_ts:\n        end_ts = start_ts + interval\n        subset = X.loc[start_ts:end_ts - 1]\n        aggregated = [\n            getattr(subset, agg)(skipna=True).values\n            for agg in method\n        ]\n        values.append(np.concatenate(aggregated))\n        index.append(start_ts)\n        start_ts = end_ts\n    return np.asarray(values), np.asarray(index)",
    "docstring": "Aggregate values over fixed length time segments."
  },
  {
    "code": "def fabrics(self):\n        if not self.__fabrics:\n            self.__fabrics = Fabrics(self.__connection)\n        return self.__fabrics",
    "docstring": "Gets the Fabrics API client.\n\n        Returns:\n            Fabrics:"
  },
  {
    "code": "def real(prompt=None, empty=False):\n    s = _prompt_input(prompt)\n    if empty and not s:\n        return None\n    else:\n        try:\n            return float(s)\n        except ValueError:\n            return real(prompt=prompt, empty=empty)",
    "docstring": "Prompt a real number.\n\n    Parameters\n    ----------\n    prompt : str, optional\n        Use an alternative prompt.\n    empty : bool, optional\n        Allow an empty response.\n\n    Returns\n    -------\n    float or None\n        A float if the user entered a valid real number.\n        None if the user pressed only Enter and ``empty`` was True."
  },
  {
    "code": "def form_valid(self, form):\n        instance = form.save(commit=False)\n        if hasattr(self.request, 'user'):\n            instance.user = self.request.user\n        if settings.CONTACT_FORM_FILTER_MESSAGE:\n            instance.message = bleach.clean(\n                instance.message,\n                tags=settings.CONTACT_FORM_ALLOWED_MESSAGE_TAGS,\n                strip=settings.CONTACT_FORM_STRIP_MESSAGE\n            )\n        instance.ip = get_user_ip(self.request)\n        instance.site = self.site\n        instance.save()\n        if settings.CONTACT_FORM_USE_SIGNALS:\n            contact_form_valid.send(\n                sender=self,\n                event=self.valid_event,\n                ip=instance.ip,\n                site=self.site,\n                sender_name=instance.sender_name,\n                sender_email=instance.sender_email,\n                email=instance.subject.department.email,\n                subject=instance.subject.title,\n                message=instance.message\n            )\n        return super(ContactFormView, self).form_valid(form)",
    "docstring": "This is what's called when the form is valid."
  },
  {
    "code": "def is_same_as(df, df_to_compare, **kwargs):\n    try:\n        tm.assert_frame_equal(df, df_to_compare, **kwargs)\n    except AssertionError as exc:\n        six.raise_from(AssertionError(\"DataFrames are not equal\"), exc)\n    return df",
    "docstring": "Assert that two pandas dataframes are the equal\n\n    Parameters\n    ==========\n    df : pandas DataFrame\n    df_to_compare : pandas DataFrame\n    **kwargs : dict\n        keyword arguments passed through to panda's ``assert_frame_equal``\n\n    Returns\n    =======\n    df : DataFrame"
  },
  {
    "code": "def _get_default_retry_params():\n  default = getattr(_thread_local_settings, 'default_retry_params', None)\n  if default is None or not default.belong_to_current_request():\n    return RetryParams()\n  else:\n    return copy.copy(default)",
    "docstring": "Get default RetryParams for current request and current thread.\n\n  Returns:\n    A new instance of the default RetryParams."
  },
  {
    "code": "def normalize(text, lowercase=True, collapse=True, latinize=False, ascii=False,\n              encoding_default='utf-8', encoding=None,\n              replace_categories=UNICODE_CATEGORIES):\n    text = stringify(text, encoding_default=encoding_default,\n                     encoding=encoding)\n    if text is None:\n        return\n    if lowercase:\n        text = text.lower()\n    if ascii:\n        text = ascii_text(text)\n    elif latinize:\n        text = latinize_text(text)\n    if text is None:\n        return\n    text = category_replace(text, replace_categories)\n    if collapse:\n        text = collapse_spaces(text)\n    return text",
    "docstring": "The main normalization function for text.\n\n    This will take a string and apply a set of transformations to it so\n    that it can be processed more easily afterwards. Arguments:\n\n    * ``lowercase``: not very mysterious.\n    * ``collapse``: replace multiple whitespace-like characters with a\n      single whitespace. This is especially useful with category replacement\n      which can lead to a lot of whitespace.\n    * ``decompose``: apply a unicode normalization (NFKD) to separate\n      simple characters and their diacritics.\n    * ``replace_categories``: This will perform a replacement of whole\n      classes of unicode characters (e.g. symbols, marks, numbers) with a\n      given character. It is used to replace any non-text elements of the\n      input string."
  },
  {
    "code": "def decode(self, key):\n        key = BucketKey.decode(key)\n        if key.uuid != self.uuid:\n            raise ValueError(\"%s is not a bucket corresponding to this limit\" %\n                             key)\n        return key.params",
    "docstring": "Given a bucket key, compute the parameters used to compute\n        that key.\n\n        Note: Deprecated.  Use BucketKey.decode() instead.\n\n        :param key: The bucket key.  Note that the UUID must match the\n                    UUID of this limit; a ValueError will be raised if\n                    this is not the case."
  },
  {
    "code": "def preloop(self):\n        if not self.parser:\n            self.stdout.write(\"Welcome to imagemounter {version}\".format(version=__version__))\n            self.stdout.write(\"\\n\")\n            self.parser = ImageParser()\n            for p in self.args.paths:\n                self.onecmd('disk \"{}\"'.format(p))",
    "docstring": "if the parser is not already set, loads the parser."
  },
  {
    "code": "def install_requirements(self, path, index=None):\n        cmd = 'install -r {0}'.format(path)\n        if index:\n            cmd = 'install --index-url {0} -r {1}'.format(index, path)\n        self.pip(cmd)",
    "docstring": "Install packages from a requirements.txt file.\n\n        Args:\n            path (str): The path to the requirements file.\n            index (str): The URL for a pypi index to use."
  },
  {
    "code": "def get_entry_compact_text_repr(entry, entries):\n    text = get_shortest_text_value(entry)\n    if text is not None:\n        return text\n    else:\n        sources = get_sourced_from(entry)\n        if sources is not None:\n            texts = []\n            for source in sources:\n                source_entry = entries[source]\n                texts.append(get_shortest_text_value(source_entry))\n            return get_shortest_string(texts)",
    "docstring": "If the entry has a text value, return that.\n    If the entry has a source_from value, return the text value of the source.\n    Otherwise, return None."
  },
  {
    "code": "def write(self, data):\n        _complain_ifclosed(self.closed)\n        if self.__encoding:\n            self.f.write(data.encode(self.__encoding, self.__errors))\n            return len(data)\n        else:\n            return self.f.write(data)",
    "docstring": "Write ``data`` to the file.\n\n        :type data: bytes\n        :param data: the data to be written to the file\n        :rtype: int\n        :return: the number of bytes written"
  },
  {
    "code": "def clean(cls, path):\n        for pth in os.listdir(path):\n            pth = os.path.abspath(os.path.join(path, pth))\n            if os.path.isdir(pth):\n                logger.debug('Removing directory %s' % pth)\n                shutil.rmtree(pth)\n            else:\n                logger.debug('Removing file %s' % pth)\n                os.remove(pth)",
    "docstring": "Clean up all the files in a provided path"
  },
  {
    "code": "def match(self, name):\n\t\tif (self.ns + self.name).startswith(name):\n\t\t\treturn True\n\t\tfor alias in self.aliases:\n\t\t\tif (self.ns + alias).startswith(name):\n\t\t\t\treturn True",
    "docstring": "Compare an argument string to the task name."
  },
  {
    "code": "def run(self):\n        self._listening_sock, self._address = (\n            bind_domain_socket(self._address)\n            if self._uds_path\n            else bind_tcp_socket(self._address))\n        if self._ssl:\n            certfile = os.path.join(os.path.dirname(__file__), 'server.pem')\n            self._listening_sock = _ssl.wrap_socket(\n                self._listening_sock,\n                certfile=certfile,\n                server_side=True)\n        self._accept_thread = threading.Thread(target=self._accept_loop)\n        self._accept_thread.daemon = True\n        self._accept_thread.start()\n        return self.port",
    "docstring": "Begin serving. Returns the bound port, or 0 for domain socket."
  },
  {
    "code": "def alterar(self, id_divisiondc, name):\n        if not is_valid_int_param(id_divisiondc):\n            raise InvalidParameterError(\n                u'The identifier of Division Dc is invalid or was not informed.')\n        url = 'divisiondc/' + str(id_divisiondc) + '/'\n        division_dc_map = dict()\n        division_dc_map['name'] = name\n        code, xml = self.submit({'division_dc': division_dc_map}, 'PUT', url)\n        return self.response(code, xml)",
    "docstring": "Change Division Dc from by the identifier.\n\n        :param id_divisiondc: Identifier of the Division Dc. Integer value and greater than zero.\n        :param name: Division Dc name. String with a minimum 2 and maximum of 80 characters\n\n        :return: None\n\n        :raise InvalidParameterError: The identifier of Division Dc or name is null and invalid.\n        :raise NomeDivisaoDcDuplicadoError: There is already a registered Division Dc with the value of name.\n        :raise DivisaoDcNaoExisteError: Division Dc not registered.\n        :raise DataBaseError: Networkapi failed to access the database.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def _connect_lxd(spec):\n    return {\n        'method': 'lxd',\n        'kwargs': {\n            'container': spec.remote_addr(),\n            'python_path': spec.python_path(),\n            'lxc_path': spec.mitogen_lxc_path(),\n            'connect_timeout': spec.ansible_ssh_timeout() or spec.timeout(),\n            'remote_name': get_remote_name(spec),\n        }\n    }",
    "docstring": "Return ContextService arguments for an LXD container connection."
  },
  {
    "code": "def parse_lint_result(lint_result_path, manifest_path):\n    unused_string_pattern = re.compile('The resource `R\\.string\\.([^`]+)` appears to be unused')\n    mainfest_string_refs = get_manifest_string_refs(manifest_path)\n    root = etree.parse(lint_result_path).getroot()\n    issues = []\n    for issue_xml in root.findall('.//issue[@id=\"UnusedResources\"]'):\n        message = issue_xml.get('message')\n        unused_string = re.match(unused_string_pattern, issue_xml.get('message'))\n        has_string_in_manifest = unused_string and unused_string.group(1) in mainfest_string_refs\n        if not has_string_in_manifest:\n            issues.extend(_get_issues_from_location(UnusedResourceIssue,\n                                                    issue_xml.findall('location'),\n                                                    message))\n    for issue_xml in root.findall('.//issue[@id=\"ExtraTranslation\"]'):\n        message = issue_xml.get('message')\n        if re.findall(ExtraTranslationIssue.pattern, message):\n            issues.extend(_get_issues_from_location(ExtraTranslationIssue,\n                                                    issue_xml.findall('location'),\n                                                    message))\n    return issues",
    "docstring": "Parse lint-result.xml and create Issue for every problem found except unused strings referenced in AndroidManifest"
  },
  {
    "code": "def add_authorizers(self, authorizers):\n        self.security_definitions = self.security_definitions or {}\n        for authorizer_name, authorizer in authorizers.items():\n            self.security_definitions[authorizer_name] = authorizer.generate_swagger()",
    "docstring": "Add Authorizer definitions to the securityDefinitions part of Swagger.\n\n        :param list authorizers: List of Authorizer configurations which get translated to securityDefinitions."
  },
  {
    "code": "def delete_dcnm_out_nwk(self, tenant_id, fw_dict, is_fw_virt=False):\n        tenant_name = fw_dict.get('tenant_name')\n        ret = self._delete_service_nwk(tenant_id, tenant_name, 'out')\n        if ret:\n            res = fw_const.DCNM_OUT_NETWORK_DEL_SUCCESS\n            LOG.info(\"out Service network deleted for tenant %s\",\n                     tenant_id)\n        else:\n            res = fw_const.DCNM_OUT_NETWORK_DEL_FAIL\n            LOG.info(\"out Service network deleted failed for tenant %s\",\n                     tenant_id)\n        self.update_fw_db_result(tenant_id, dcnm_status=res)\n        return ret",
    "docstring": "Delete the DCNM OUT network and update the result."
  },
  {
    "code": "def reportDeprecatedWorkerNameUsage(message, stacklevel=None, filename=None,\n                                    lineno=None):\n    if filename is None:\n        if stacklevel is None:\n            stacklevel = 3\n        else:\n            stacklevel += 2\n        warnings.warn(DeprecatedWorkerNameWarning(message), None, stacklevel)\n    else:\n        assert stacklevel is None\n        if lineno is None:\n            lineno = 0\n        warnings.warn_explicit(\n            DeprecatedWorkerNameWarning(message),\n            DeprecatedWorkerNameWarning,\n            filename, lineno)",
    "docstring": "Hook that is ran when old API name is used.\n\n    :param stacklevel: stack level relative to the caller's frame.\n    Defaults to caller of the caller of this function."
  },
  {
    "code": "def copy_attr(f1, f2):\n    copyit = lambda x: not hasattr(f2, x) and x[:10] == 'PACKAGING_'\n    if f1._tags:\n        pattrs = [tag for tag in f1._tags if copyit(tag)]\n        for attr in pattrs:\n            f2.Tag(attr, f1.GetTag(attr))",
    "docstring": "copies the special packaging file attributes from f1 to f2."
  },
  {
    "code": "def elliconstraint(self, x, cfac=1e8, tough=True, cond=1e6):\n        N = len(x)\n        f = sum(cond**(np.arange(N)[-1::-1] / (N - 1)) * x**2)\n        cvals = (x[0] + 1,\n                 x[0] + 1 + 100 * x[1],\n                 x[0] + 1 - 100 * x[1])\n        if tough:\n            f += cfac * sum(max(0, c) for c in cvals)\n        else:\n            f += cfac * sum(max(0, c + 1e-3)**2 for c in cvals)\n        return f",
    "docstring": "ellipsoid test objective function with \"constraints\""
  },
  {
    "code": "def skull_strip(dset,suffix='_ns',prefix=None,unifize=True):\n    if prefix==None:\n        prefix = nl.suffix(dset,suffix)\n    unifize_dset = nl.suffix(dset,'_u')\n    cmd = bet2 if bet2 else 'bet2'\n    if unifize:\n        info = nl.dset_info(dset)\n        if info==None:\n            nl.notify('Error: could not read info for dset %s' % dset,level=nl.level.error)\n            return False\n        cmd = os.path.join(fsl_dir,cmd) if fsl_dir else cmd\n        cutoff_value = nl.max(dset) * 0.05\n        nl.run(['3dUnifize','-prefix',unifize_dset,nl.calc(dset,'step(a-%f)*a' % cutoff_value)],products=unifize_dset)\n    else:\n        unifize_dset = dset\n    nl.run([cmd,unifize_dset,prefix,'-w',0.5],products=prefix)",
    "docstring": "use bet to strip skull from given anatomy"
  },
  {
    "code": "def new_reply(cls, thread, user, content):\n        msg = cls.objects.create(thread=thread, sender=user, content=content)\n        thread.userthread_set.exclude(user=user).update(deleted=False, unread=True)\n        thread.userthread_set.filter(user=user).update(deleted=False, unread=False)\n        message_sent.send(sender=cls, message=msg, thread=thread, reply=True)\n        return msg",
    "docstring": "Create a new reply for an existing Thread.\n\n        Mark thread as unread for all other participants, and\n        mark thread as read by replier."
  },
  {
    "code": "def _guess_cmd_name(self, cmd):\n        if cmd[0] == 'zcat' and 'bowtie' in cmd:\n            return 'bowtie'\n        if cmd[0] == 'samtools':\n            return ' '.join(cmd[0:2])\n        if cmd[0] == 'java':\n            jars = [s for s in cmd if '.jar' in s]\n            return os.path.basename(jars[0].replace('.jar', ''))\n        return cmd[0]",
    "docstring": "Manually guess some known command names, where we can\n        do a better job than the automatic parsing."
  },
  {
    "code": "def oneImageNLF(img, img2=None, signal=None):\r\n    x, y, weights, signal = calcNLF(img, img2, signal)\r\n    _, fn, _ = _evaluate(x, y, weights)\r\n    return fn, signal",
    "docstring": "Estimate the NLF from one or two images of the same kind"
  },
  {
    "code": "def _is_simple_type(value):\n    return isinstance(value, six.string_types) or isinstance(value, int) or isinstance(value, float) or isinstance(value, bool)",
    "docstring": "Returns True, if the given parameter value is an instance of either\n    int, str, float or bool."
  },
  {
    "code": "def qnm_freq_decay(f_0, tau, decay):\n    q_0 = pi * f_0 * tau\n    alpha = 1. / decay\n    alpha_sq = 1. / decay / decay\n    q_sq = (alpha_sq + 4*q_0*q_0 + alpha*numpy.sqrt(alpha_sq + 16*q_0*q_0)) / 4.\n    return numpy.sqrt(q_sq) / pi / tau",
    "docstring": "Return the frequency at which the amplitude of the\n    ringdown falls to decay of the peak amplitude.\n\n    Parameters\n    ----------\n    f_0 : float\n        The ringdown-frequency, which gives the peak amplitude.\n    tau : float\n        The damping time of the sinusoid.\n    decay: float\n        The fraction of the peak amplitude.\n\n    Returns\n    -------\n    f_decay: float\n        The frequency at which the amplitude of the frequency-domain\n        ringdown falls to decay of the peak amplitude."
  },
  {
    "code": "def _maximization(self, X):\n        for i in range(self.k):\n            resp = np.expand_dims(self.responsibility[:, i], axis=1)\n            mean = (resp * X).sum(axis=0) / resp.sum()\n            covariance = (X - mean).T.dot((X - mean) * resp) / resp.sum()\n            self.parameters[i][\"mean\"], self.parameters[i][\"cov\"] = mean, covariance\n        n_samples = np.shape(X)[0]\n        self.priors = self.responsibility.sum(axis=0) / n_samples",
    "docstring": "Update the parameters and priors"
  },
  {
    "code": "def get_info(self, symbol):\n        sym = self._get_symbol_info(symbol)\n        if not sym:\n            raise NoDataFoundException(\"Symbol does not exist.\")\n        ret = {}\n        ret['chunk_count'] = sym[CHUNK_COUNT]\n        ret['len'] = sym[LEN]\n        ret['appended_rows'] = sym[APPEND_COUNT]\n        ret['metadata'] = sym[METADATA] if METADATA in sym else None\n        ret['chunker'] = sym[CHUNKER]\n        ret['chunk_size'] = sym[CHUNK_SIZE] if CHUNK_SIZE in sym else 0\n        ret['serializer'] = sym[SERIALIZER]\n        return ret",
    "docstring": "Returns information about the symbol, in a dictionary\n\n        Parameters\n        ----------\n        symbol: str\n            the symbol for the given item in the DB\n\n        Returns\n        -------\n        dictionary"
  },
  {
    "code": "def _DownloadScript(self, url, dest_dir):\n    if url.startswith(r'gs://'):\n      url = re.sub('^gs://', 'https://storage.googleapis.com/', url)\n      return self._DownloadAuthUrl(url, dest_dir)\n    header = r'http[s]?://'\n    domain = r'storage\\.googleapis\\.com'\n    bucket = r'(?P<bucket>[a-z0-9][-_.a-z0-9]*[a-z0-9])'\n    obj = r'(?P<obj>[^\\*\\?]+)'\n    gs_regex = re.compile(r'\\A%s%s\\.%s/%s\\Z' % (header, bucket, domain, obj))\n    match = gs_regex.match(url)\n    if match:\n      return self._DownloadAuthUrl(url, dest_dir)\n    gs_regex = re.compile(\n        r'\\A%s(commondata)?%s/%s/%s\\Z' % (header, domain, bucket, obj))\n    match = gs_regex.match(url)\n    if match:\n      return self._DownloadAuthUrl(url, dest_dir)\n    return self._DownloadUrl(url, dest_dir)",
    "docstring": "Download the contents of the URL to the destination.\n\n    Args:\n      url: string, the URL to download.\n      dest_dir: string, the path to a directory for storing metadata scripts.\n\n    Returns:\n      string, the path to the file storing the metadata script."
  },
  {
    "code": "def GetSqlValuesTuple(self, trip_id):\n    result = []\n    for fn in self._SQL_FIELD_NAMES:\n      if fn == 'trip_id':\n        result.append(trip_id)\n      else:\n        result.append(getattr(self, fn))\n    return tuple(result)",
    "docstring": "Return a tuple that outputs a row of _FIELD_NAMES to be written to a\n       SQLite database.\n\n    Arguments:\n        trip_id: The trip_id of the trip to which this StopTime corresponds.\n                 It must be provided, as it is not stored in StopTime."
  },
  {
    "code": "def flush(self, using=None, **kwargs):\n        return self._get_connection(using).indices.flush(index=self._name, **kwargs)",
    "docstring": "Preforms a flush operation on the index.\n\n        Any additional keyword arguments will be passed to\n        ``Elasticsearch.indices.flush`` unchanged."
  },
  {
    "code": "def device_info(self):\n        return {\n            'family': self.family,\n            'platform': self.platform,\n            'os_type': self.os_type,\n            'os_version': self.os_version,\n            'udi': self.udi,\n            'driver_name': self.driver.platform,\n            'mode': self.mode,\n            'is_console': self.is_console,\n            'is_target': self.is_target,\n            'hostname': self.hostname,\n        }",
    "docstring": "Return device info dict."
  },
  {
    "code": "def save_snapshot(self, si, logger, vm_uuid, snapshot_name, save_memory):\n        vm = self.pyvmomi_service.find_by_uuid(si, vm_uuid)\n        snapshot_path_to_be_created = SaveSnapshotCommand._get_snapshot_name_to_be_created(snapshot_name, vm)\n        save_vm_memory_to_snapshot = SaveSnapshotCommand._get_save_vm_memory_to_snapshot(save_memory)\n        SaveSnapshotCommand._verify_snapshot_uniquness(snapshot_path_to_be_created, vm)\n        task = self._create_snapshot(logger, snapshot_name, vm, save_vm_memory_to_snapshot)\n        self.task_waiter.wait_for_task(task=task, logger=logger, action_name='Create Snapshot')\n        return snapshot_path_to_be_created",
    "docstring": "Creates a snapshot of the current state of the virtual machine\n\n        :param vim.ServiceInstance si: py_vmomi service instance\n        :type si: vim.ServiceInstance\n        :param logger: Logger\n        :type logger: cloudshell.core.logger.qs_logger.get_qs_logger\n        :param vm_uuid: UUID of the virtual machine\n        :type vm_uuid: str\n        :param snapshot_name: Snapshot name to save the snapshot to\n        :type snapshot_name: str\n        :param save_memory: Snapshot the virtual machine's memory. Lookup, Yes / No\n        :type save_memory: str"
  },
  {
    "code": "def render_pep440(vcs):\n    if vcs is None:\n        return None\n    tags = vcs.split('-')\n    if len(tags) == 1:\n        return tags[0]\n    else:\n        return tags[0] + '+' + '.'.join(tags[1:])",
    "docstring": "Convert git release tag into a form that is PEP440 compliant."
  },
  {
    "code": "def plan_scripts(self):\n        if not self.__plan_scripts:\n            self.__plan_scripts = PlanScripts(self.__connection)\n        return self.__plan_scripts",
    "docstring": "Gets the Plan Scripts API client.\n\n        Returns:\n            PlanScripts:"
  },
  {
    "code": "def method(self, returns, **parameter_types):\n        @wrapt.decorator\n        def type_check_wrapper(method, instance, args, kwargs):\n            if instance is not None:\n                raise Exception(\"Instance shouldn't be set.\")\n            parameter_names = inspect.getargspec(method).args\n            defaults = inspect.getargspec(method).defaults\n            parameters = self._collect_parameters(parameter_names, args, kwargs, defaults)\n            parameter_checker.check_types(parameters, parameter_types, self._strict_floats)\n            result = method(*args, **kwargs)\n            parameter_checker.check_return_type(result, returns, self._strict_floats)\n            return result\n        def register_method(method):\n            parameter_names = inspect.getargspec(method).args\n            parameter_checker.check_type_declaration(parameter_names, parameter_types)\n            wrapped_method = type_check_wrapper(method, None, None, None)\n            fully_qualified_name = \"{}.{}\".format(method.__module__, method.__name__)\n            self.register(fully_qualified_name, wrapped_method,\n                          MethodSignature.create(parameter_names, parameter_types, returns))\n            return wrapped_method\n        return register_method",
    "docstring": "Syntactic sugar for registering a method\n\n        Example:\n\n            >>> registry = Registry()\n            >>> @registry.method(returns=int, x=int, y=int)\n            ... def add(x, y):\n            ...     return x + y\n\n        :param returns: The method's return type\n        :type returns: type\n        :param parameter_types: The types of the method's parameters\n        :type parameter_types: dict[str, type]\n\n        .. versionadded:: 0.1.0"
  },
  {
    "code": "def write_sources_file():\n    file_content = (\n        'schemes: '\n        'https://github.com/chriskempson/base16-schemes-source.git\\n'\n        'templates: '\n        'https://github.com/chriskempson/base16-templates-source.git'\n    )\n    file_path = rel_to_cwd('sources.yaml')\n    with open(file_path, 'w') as file_:\n        file_.write(file_content)",
    "docstring": "Write a sources.yaml file to current working dir."
  },
  {
    "code": "def serialize(node, stream=None, Dumper=Dumper, **kwds):\n    return serialize_all([node], stream, Dumper=Dumper, **kwds)",
    "docstring": "Serialize a representation tree into a YAML stream.\n    If stream is None, return the produced string instead."
  },
  {
    "code": "def resolve_variables(variables, context, provider):\n    for variable in variables:\n        variable.resolve(context, provider)",
    "docstring": "Given a list of variables, resolve all of them.\n\n    Args:\n        variables (list of :class:`stacker.variables.Variable`): list of\n            variables\n        context (:class:`stacker.context.Context`): stacker context\n        provider (:class:`stacker.provider.base.BaseProvider`): subclass of the\n            base provider"
  },
  {
    "code": "def is_left(point0, point1, point2):\n    return ((point1[0] - point0[0]) * (point2[1] - point0[1])) - ((point2[0] - point0[0]) * (point1[1] - point0[1]))",
    "docstring": "Tests if a point is Left|On|Right of an infinite line.\n\n    Ported from the C++ version: on http://geomalgorithms.com/a03-_inclusion.html\n\n    .. note:: This implementation only works in 2-dimensional space.\n\n    :param point0: Point P0\n    :param point1: Point P1\n    :param point2: Point P2\n    :return:\n        >0 for P2 left of the line through P0 and P1\n        =0 for P2 on the line\n        <0 for P2 right of the line"
  },
  {
    "code": "def sign(self, consumer_secret, access_token_secret, method, url,\n             oauth_params, req_kwargs):\n        key = self._escape(consumer_secret) + b'&'\n        if access_token_secret:\n            key += self._escape(access_token_secret)\n        return key.decode()",
    "docstring": "Sign request using PLAINTEXT method.\n\n        :param consumer_secret: Consumer secret.\n        :type consumer_secret: str\n        :param access_token_secret: Access token secret (optional).\n        :type access_token_secret: str\n        :param method: Unused\n        :type method: str\n        :param url: Unused\n        :type url: str\n        :param oauth_params: Unused\n        :type oauth_params: dict\n        :param req_kwargs: Unused\n        :type req_kwargs: dict"
  },
  {
    "code": "def build_log_presenters(service_names, monochrome):\n    prefix_width = max_name_width(service_names)\n    def no_color(text):\n        return text\n    for color_func in cycle([no_color] if monochrome else colors.rainbow()):\n        yield LogPresenter(prefix_width, color_func)",
    "docstring": "Return an iterable of functions.\n\n    Each function can be used to format the logs output of a container."
  },
  {
    "code": "def get_xname(self, var, coords=None):\n        if coords is not None:\n            coord = self.get_variable_by_axis(var, 'x', coords)\n            if coord is not None and coord.name in var.dims:\n                return coord.name\n        dimlist = list(self.x.intersection(var.dims))\n        if dimlist:\n            if len(dimlist) > 1:\n                warn(\"Found multiple matches for x coordinate in the variable:\"\n                     \"%s. I use %s\" % (', '.join(dimlist), dimlist[0]),\n                     PsyPlotRuntimeWarning)\n            return dimlist[0]\n        return var.dims[-1]",
    "docstring": "Get the name of the x-dimension\n\n        This method gives the name of the x-dimension (which is not necessarily\n        the name of the coordinate if the variable has a coordinate attribute)\n\n        Parameters\n        ----------\n        var: xarray.Variables\n            The variable to get the dimension for\n        coords: dict\n            The coordinates to use for checking the axis attribute. If None,\n            they are not used\n\n        Returns\n        -------\n        str\n            The coordinate name\n\n        See Also\n        --------\n        get_x"
  },
  {
    "code": "def process_file(filename, interval=None, lazy=False):\n    mp = MedscanProcessor()\n    mp.process_csxml_file(filename, interval, lazy)\n    return mp",
    "docstring": "Process a CSXML file for its relevant information.\n\n    Consider running the fix_csxml_character_encoding.py script in\n    indra/sources/medscan to fix any encoding issues in the input file before\n    processing.\n\n    Attributes\n    ----------\n    filename : str\n        The csxml file, containing Medscan XML, to process\n    interval : (start, end) or None\n        Select the interval of documents to read, starting with the\n        `start`th document and ending before the `end`th document. If\n        either is None, the value is considered undefined. If the value\n        exceeds the bounds of available documents, it will simply be\n        ignored.\n    lazy : bool\n        If True, the statements will not be generated immediately, but rather\n        a generator will be formulated, and statements can be retrieved by\n        using `iter_statements`. If False, the `statements` attribute will be\n        populated immediately. Default is False.\n\n    Returns\n    -------\n    mp : MedscanProcessor\n        A MedscanProcessor object containing extracted statements"
  },
  {
    "code": "def stream(func):\n    @wraps(func)\n    def wrapped(manager, *args, **kwargs):\n        offset, limit = kwargs.pop('_offset', None), kwargs.pop('_limit', None)\n        qs = func(manager, *args, **kwargs)\n        if isinstance(qs, dict):\n            qs = manager.public(**qs)\n        elif isinstance(qs, (list, tuple)):\n            qs = manager.public(*qs)\n        if offset or limit:\n            qs = qs[offset:limit]\n        return qs.fetch_generic_relations()\n    return wrapped",
    "docstring": "Stream decorator to be applied to methods of an ``ActionManager`` subclass\n\n    Syntax::\n\n        from actstream.decorators import stream\n        from actstream.managers import ActionManager\n\n        class MyManager(ActionManager):\n            @stream\n            def foobar(self, ...):\n                ..."
  },
  {
    "code": "def collmat(self, tau, deriv_order=0):\n        dummy = self.__call__(0.)\n        nbasis = dummy.shape[0]\n        tau = np.atleast_1d(tau)\n        if tau.ndim > 1:\n            raise ValueError(\"tau must be a list or a rank-1 array\")\n        A = np.empty( (tau.shape[0], nbasis), dtype=dummy.dtype )\n        f = self.diff(order=deriv_order)\n        for i,taui in enumerate(tau):\n            A[i,:] = f(taui)\n        return np.squeeze(A)",
    "docstring": "Compute collocation matrix.\n\nParameters:\n    tau:\n        Python list or rank-1 array, collocation sites\n    deriv_order:\n        int, >=0, order of derivative for which to compute the collocation matrix.\n        The default is 0, which means the function value itself.\n\nReturns:\n    A:\n        if len(tau) > 1, rank-2 array such that\n            A[i,j] = D**deriv_order B_j(tau[i])\n        where\n            D**k  = kth derivative (0 for function value itself)\n\n        if len(tau) == 1, rank-1 array such that\n            A[j]   = D**deriv_order B_j(tau)\n\nExample:\n    If the coefficients of a spline function are given in the vector c, then::\n\n        np.sum( A*c, axis=-1 )\n\n    will give a rank-1 array of function values at the sites tau[i] that were supplied\n    to `collmat`.\n\n    Similarly for derivatives (if the supplied `deriv_order`> 0)."
  },
  {
    "code": "def require_minimum_pandas_version():\n    minimum_pandas_version = \"0.19.2\"\n    from distutils.version import LooseVersion\n    try:\n        import pandas\n        have_pandas = True\n    except ImportError:\n        have_pandas = False\n    if not have_pandas:\n        raise ImportError(\"Pandas >= %s must be installed; however, \"\n                          \"it was not found.\" % minimum_pandas_version)\n    if LooseVersion(pandas.__version__) < LooseVersion(minimum_pandas_version):\n        raise ImportError(\"Pandas >= %s must be installed; however, \"\n                          \"your version was %s.\" % (minimum_pandas_version, pandas.__version__))",
    "docstring": "Raise ImportError if minimum version of Pandas is not installed"
  },
  {
    "code": "def get_timestamp(self, **kwargs):\n        timestamp = kwargs.get('timestamp')\n        if not timestamp:\n            now = datetime.datetime.utcnow()\n            timestamp = now.strftime(\"%Y-%m-%dT%H:%M:%S\") + \".%03d\" % (now.microsecond / 1000) + \"Z\"\n        return timestamp",
    "docstring": "Retrieves the timestamp for a given set of data"
  },
  {
    "code": "def EscapeWildcards(string):\n  precondition.AssertType(string, Text)\n  return string.replace(\"%\", r\"\\%\").replace(\"_\", r\"\\_\")",
    "docstring": "Escapes wildcard characters for strings intended to be used with `LIKE`.\n\n  Databases don't automatically escape wildcard characters ('%', '_'), so any\n  non-literal string that is passed to `LIKE` and is expected to match literally\n  has to be manually escaped.\n\n  Args:\n    string: A string to escape.\n\n  Returns:\n    An escaped string."
  },
  {
    "code": "def _replace_global_vars(xs, global_vars):\n    if isinstance(xs, (list, tuple)):\n        return [_replace_global_vars(x) for x in xs]\n    elif isinstance(xs, dict):\n        final = {}\n        for k, v in xs.items():\n            if isinstance(v, six.string_types) and v in global_vars:\n                v = global_vars[v]\n            final[k] = v\n        return final\n    else:\n        return xs",
    "docstring": "Replace globally shared names from input header with value.\n\n    The value of the `algorithm` item may be a pointer to a real\n    file specified in the `global` section. If found, replace with\n    the full value."
  },
  {
    "code": "def _gist_is_preset(repo):\n    _, gistid = repo.split(\"/\")\n    gist_template = \"https://api.github.com/gists/{}\"\n    gist_path = gist_template.format(gistid)\n    response = get(gist_path)\n    if response.status_code == 404:\n        return False\n    try:\n        data = response.json()\n    except:\n        return False\n    files = data.get(\"files\", {})\n    package = files.get(\"package.json\", {})\n    try:\n        content = json.loads(package.get(\"content\", \"\"))\n    except:\n        return False\n    if content.get(\"type\") != \"bepreset\":\n        return False\n    return True",
    "docstring": "Evaluate whether gist is a be package\n\n    Arguments:\n        gist (str): username/id pair e.g. mottosso/2bb4651a05af85711cde"
  },
  {
    "code": "def set_ifo_tag(self,ifo_tag,pass_to_command_line=True):\n    self.__ifo_tag = ifo_tag\n    if pass_to_command_line:\n      self.add_var_opt('ifo-tag', ifo_tag)",
    "docstring": "Set the ifo tag that is passed to the analysis code.\n    @param ifo_tag: a string to identify one or more IFOs\n    @bool pass_to_command_line: add ifo-tag as a variable option."
  },
  {
    "code": "def get_maximum_score_metadata(self):\n        metadata = dict(self._mdata['maximum_score'])\n        metadata.update({'existing_cardinal_values': self._my_map['maximumScore']})\n        return Metadata(**metadata)",
    "docstring": "Gets the metadata for the maximum score.\n\n        return: (osid.Metadata) - metadata for the maximum score\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _valid_request_body(\n            self, cert_chain, signature, serialized_request_env):\n        decoded_signature = base64.b64decode(signature)\n        public_key = cert_chain.public_key()\n        request_env_bytes = serialized_request_env.encode(CHARACTER_ENCODING)\n        try:\n            public_key.verify(\n                decoded_signature, request_env_bytes,\n                self._padding, self._hash_algorithm)\n        except InvalidSignature as e:\n            raise VerificationException(\"Request body is not valid\", e)",
    "docstring": "Validate the request body hash with signature.\n\n        This method checks if the hash value of the request body\n        matches with the hash value of the signature, decrypted using\n        certificate chain. A\n        :py:class:`VerificationException` is raised if there is a\n        mismatch.\n\n        :param cert_chain: Certificate chain to be validated\n        :type cert_chain: cryptography.x509.Certificate\n        :param signature: Encrypted signature of the request\n        :type: str\n        :param serialized_request_env: Raw request body\n        :type: str\n        :raises: :py:class:`VerificationException` if certificate is\n            not valid"
  },
  {
    "code": "def alias_delete(indices, aliases, hosts=None, body=None, profile=None, source=None):\n    es = _get_instance(hosts, profile)\n    if source and body:\n        message = 'Either body or source should be specified but not both.'\n        raise SaltInvocationError(message)\n    if source:\n        body = __salt__['cp.get_file_str'](\n                  source,\n                  saltenv=__opts__.get('saltenv', 'base'))\n    try:\n        result = es.indices.delete_alias(index=indices, name=aliases)\n        return result.get('acknowledged', False)\n    except elasticsearch.exceptions.NotFoundError:\n        return True\n    except elasticsearch.TransportError as e:\n        raise CommandExecutionError(\"Cannot delete alias {0} in index {1}, server returned code {2} with message {3}\".format(aliases, indices, e.status_code, e.error))",
    "docstring": "Delete an alias of an index\n\n    indices\n        Single or multiple indices separated by comma, use _all to perform the operation on all indices.\n    aliases\n        Alias names separated by comma\n\n    CLI example::\n\n        salt myminion elasticsearch.alias_delete testindex_v1 testindex"
  },
  {
    "code": "def config_get(args):\n    r = fapi.get_workspace_config(args.project, args.workspace,\n                                        args.namespace, args.config)\n    fapi._check_response_code(r, 200)\n    return json.dumps(r.json(), indent=4, separators=(',', ': '),\n                      sort_keys=True, ensure_ascii=False)",
    "docstring": "Retrieve a method config from a workspace, send stdout"
  },
  {
    "code": "def iter_batches(iterable, batch_size):\n    sourceiter = iter(iterable)\n    while True:\n        batchiter = islice(sourceiter, batch_size)\n        yield chain([batchiter.next()], batchiter)",
    "docstring": "Given a sequence or iterable, yield batches from that iterable until it\n    runs out. Note that this function returns a generator, and also each\n    batch will be a generator.\n\n    :param iterable: The sequence or iterable to split into batches\n    :param int batch_size: The number of elements of `iterable` to iterate over\n        in each batch\n\n    >>> batches = iter_batches('abcdefghijkl', batch_size=5)\n    >>> list(next(batches))\n    ['a', 'b', 'c', 'd', 'e']\n    >>> list(next(batches))\n    ['f', 'g', 'h', 'i', 'j']\n    >>> list(next(batches))\n    ['k', 'l']\n    >>> list(next(batches))\n    Traceback (most recent call last):\n        ...\n    StopIteration\n\n    Warning: It is important to iterate completely over each batch before\n    requesting the next, or batch sizes will be truncated to 1. For example,\n    making a list of all batches before asking for the contents of each\n    will not work:\n\n    >>> batches = list(iter_batches('abcdefghijkl', batch_size=5))\n    >>> len(batches)\n    12\n    >>> list(batches[0])\n    ['a']\n\n    However, making a list of each individual batch as it is received will\n    produce expected behavior (as shown in the first example)."
  },
  {
    "code": "def get_scan(self, source_id, scan_id):\n        target_url = self.client.get_url('SCAN', 'GET', 'single', {'source_id': source_id, 'scan_id': scan_id})\n        return self.client.get_manager(Scan)._get(target_url)",
    "docstring": "Get a Scan object\n\n        :rtype: Scan"
  },
  {
    "code": "def _load_start_paths(self):\n        \" Start the Read-Eval-Print Loop. \"\n        if self._startup_paths:\n            for path in self._startup_paths:\n                if os.path.exists(path):\n                    with open(path, 'rb') as f:\n                        code = compile(f.read(), path, 'exec')\n                        six.exec_(code, self.get_globals(), self.get_locals())\n                else:\n                    output = self.app.output\n                    output.write('WARNING | File not found: {}\\n\\n'.format(path))",
    "docstring": "Start the Read-Eval-Print Loop."
  },
  {
    "code": "def __redirect_stdio_emit(self, value):\r\n        parent = self.parent()\r\n        while parent is not None:\r\n            try:\r\n                parent.redirect_stdio.emit(value)\r\n            except AttributeError:\r\n                parent = parent.parent()\r\n            else:\r\n                break",
    "docstring": "Searches through the parent tree to see if it is possible to emit the\r\n        redirect_stdio signal.\r\n        This logic allows to test the SearchInComboBox select_directory method\r\n        outside of the FindInFiles plugin."
  },
  {
    "code": "def update_configurable(self, configurable_class, name, config):\n        configurable_class_name = configurable_class.__name__.lower()\n        logger.info(\n            \"updating %s: '%s'\", configurable_class_name, name\n        )\n        registry = self.registry_for(configurable_class)\n        if name not in registry:\n            logger.warn(\n                \"Tried to update unknown %s: '%s'\",\n                configurable_class_name, name\n            )\n            self.add_configurable(\n                configurable_class,\n                configurable_class.from_config(name, config)\n            )\n            return\n        registry[name].apply_config(config)\n        hook = self.hook_for(configurable_class, \"update\")\n        if not hook:\n            return\n        def done(f):\n            try:\n                f.result()\n            except Exception:\n                logger.exception(\"Error updating configurable '%s'\", name)\n        self.work_pool.submit(hook, name, config).add_done_callback(done)",
    "docstring": "Callback fired when a configurable instance is updated.\n\n        Looks up the existing configurable in the proper \"registry\" and\n        `apply_config()` is called on it.\n\n        If a method named \"on_<configurable classname>_update\" is defined it\n        is called in the work pool and passed the configurable's name, the old\n        config and the new config.\n\n        If the updated configurable is not present, `add_configurable()` is\n        called instead."
  },
  {
    "code": "def mkdir(path, create_parent=True, check_if_exists=False):\n    cmd = _format_cmd('mkdir', path, _p=create_parent)\n    if check_if_exists:\n        return 'if [[ ! -d {0} ]]; then {1}; fi'.format(path, cmd)\n    return cmd",
    "docstring": "Generates a unix command line for creating a directory.\n\n    :param path: Directory path.\n    :type path: unicode | str\n    :param create_parent: Create parent directories, if necessary. Default is ``True``.\n    :type create_parent: bool\n    :param check_if_exists: Prepend a check if the directory exists; in that case, the command is not run.\n      Default is ``False``.\n    :type check_if_exists: bool\n    :return: Unix shell command line.\n    :rtype: unicode | str"
  },
  {
    "code": "def get_config(self, retrieve=\"all\"):\n        get_startup = retrieve == \"all\" or retrieve == \"startup\"\n        get_running = retrieve == \"all\" or retrieve == \"running\"\n        get_candidate = retrieve == \"all\" or retrieve == \"candidate\"\n        if retrieve == \"all\" or get_running:\n            result = self._execute_command_with_vdom('show')\n            text_result = '\\n'.join(result)\n            return {\n                'startup': u\"\",\n                'running': py23_compat.text_type(text_result),\n                'candidate': u\"\",\n            }\n        elif get_startup or get_candidate:\n            return {\n                'startup': u\"\",\n                'running': u\"\",\n                'candidate': u\"\",\n            }",
    "docstring": "get_config implementation for FortiOS."
  },
  {
    "code": "def get_router_id(self, tenant_id, tenant_name):\n        router_id = None\n        if tenant_id in self.tenant_dict:\n            router_id = self.tenant_dict.get(tenant_id).get('router_id')\n        if not router_id:\n            router_list = self.os_helper.get_rtr_by_name(\n                'FW_RTR_' + tenant_name)\n            if len(router_list) > 0:\n                router_id = router_list[0].get('id')\n        return router_id",
    "docstring": "Retrieve the router ID."
  },
  {
    "code": "def read(self, path, environ):\n        try:\n            inp = open(path, 'rb')\n        except FileNotFoundError as error:\n            if error.errno != 2:\n                raise\n            return None\n        parsing = parse_vexrc(inp, environ)\n        for heading, key, value in parsing:\n            heading = self.default_heading if heading is None else heading\n            if heading not in self.headings:\n                self.headings[heading] = OrderedDict()\n            self.headings[heading][key] = value\n        parsing.close()",
    "docstring": "Read data from file into this vexrc instance."
  },
  {
    "code": "def as_view(cls, **initkwargs):\n        if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):\n            def force_evaluation():\n                raise RuntimeError(\n                    'Do not evaluate the `.queryset` attribute directly, '\n                    'as the result will be cached and reused between requests. '\n                    'Use `.all()` or call `.get_queryset()` instead.'\n                )\n            cls.queryset._fetch_all = force_evaluation\n            cls.queryset._result_iter = force_evaluation\n        view = super(RestView, cls).as_view(**initkwargs)\n        view.cls = cls\n        return csrf_exempt(view)",
    "docstring": "Store the original class on the view function.\n\n        This allows us to discover information about the view when we do URL\n        reverse lookups.  Used for breadcrumb generation."
  },
  {
    "code": "def by_name(self, name, archived=False, limit=None, page=None):\n        if not archived:\n            path = _path(self.adapter)\n        else:\n            path = _path(self.adapter, 'archived')\n        return self._get(path, name=name, limit=limit, page=page)",
    "docstring": "get adapter data by name."
  },
  {
    "code": "def detach(gandi, resource, background, force):\n    resource = sorted(tuple(set(resource)))\n    if not force:\n        proceed = click.confirm('Are you sure you want to detach %s?' %\n                                ', '.join(resource))\n        if not proceed:\n            return\n    result = gandi.disk.detach(resource, background)\n    if background:\n        gandi.pretty_echo(result)\n    return result",
    "docstring": "Detach disks from currectly attached vm.\n\n    Resource can be a disk name, or ID"
  },
  {
    "code": "def get_backend_tfvars_file(path, environment, region):\n    backend_filenames = gen_backend_tfvars_files(environment, region)\n    for name in backend_filenames:\n        if os.path.isfile(os.path.join(path, name)):\n            return name\n    return backend_filenames[-1]",
    "docstring": "Determine Terraform backend file."
  },
  {
    "code": "def end(self):\n        if self.lastUrl is not None:\n            self.html.write(u'</li>\\n')\n        if self.lastComic is not None:\n            self.html.write(u'</ul>\\n')\n        self.html.write(u'</ul>\\n')\n        self.addNavLinks()\n        self.html.close()",
    "docstring": "End HTML output."
  },
  {
    "code": "def _lock(self, url: str, name: str, hash_: str):\n        self._new_lock.append({\n            'url': url,\n            'name': name,\n            'hash': hash_,\n        })\n        self._stale_files.pop(name, None)",
    "docstring": "Add details of the files downloaded to _new_lock so they can be saved to the lock file.\n        Also remove path from _stale_files, whatever remains at the end therefore is stale and can be deleted."
  },
  {
    "code": "def slack_user(request, api_data):\n    if request.user.is_anonymous:\n        return request, api_data\n    data = deepcopy(api_data)\n    slacker, _ = SlackUser.objects.get_or_create(slacker=request.user)\n    slacker.access_token = data.pop('access_token')\n    slacker.extras = data\n    slacker.save()\n    messages.add_message(request, messages.SUCCESS, 'Your account has been successfully updated with '\n                                                    'Slack. You can share your messages within your slack '\n                                                    'domain.')\n    return request, api_data",
    "docstring": "Pipeline for backward compatibility prior to 1.0.0 version.\n    In case if you're willing maintain `slack_user` table."
  },
  {
    "code": "def _build_amps_list(self, amp_value, processlist):\n        ret = []\n        try:\n            for p in processlist:\n                add_it = False\n                if (re.search(amp_value.regex(), p['name']) is not None):\n                    add_it = True\n                else:\n                    for c in p['cmdline']:\n                        if (re.search(amp_value.regex(), c) is not None):\n                            add_it = True\n                            break\n                if add_it:\n                    ret.append({'pid': p['pid'],\n                                'cpu_percent': p['cpu_percent'],\n                                'memory_percent': p['memory_percent']})\n        except (TypeError, KeyError) as e:\n            logger.debug(\"Can not build AMPS list ({})\".format(e))\n        return ret",
    "docstring": "Return the AMPS process list according to the amp_value\n\n        Search application monitored processes by a regular expression"
  },
  {
    "code": "def map_seqprop_resnums_to_seqprop_resnums(self, resnums, seqprop1, seqprop2):\n        resnums = ssbio.utils.force_list(resnums)\n        alignment = self._get_seqprop_to_seqprop_alignment(seqprop1=seqprop1, seqprop2=seqprop2)\n        mapped = ssbio.protein.sequence.utils.alignment.map_resnum_a_to_resnum_b(resnums=resnums,\n                                                                                 a_aln=alignment[0],\n                                                                                 b_aln=alignment[1])\n        return mapped",
    "docstring": "Map a residue number in any SeqProp to another SeqProp using the pairwise alignment information.\n\n        Args:\n            resnums (int, list): Residue numbers in seqprop1\n            seqprop1 (SeqProp): SeqProp object the resnums match to\n            seqprop2 (SeqProp): SeqProp object you want to map the resnums to\n\n        Returns:\n            dict: Mapping of seqprop1 residue numbers to seqprop2 residue numbers. If mappings don't exist in this\n            dictionary, that means the residue number cannot be mapped according to alignment!"
  },
  {
    "code": "def up(self) -> \"InstanceNode\":\n        ts = max(self.timestamp, self.parinst.timestamp)\n        return self.parinst._copy(self._zip(), ts)",
    "docstring": "Return an instance node corresponding to the receiver's parent.\n\n        Raises:\n            NonexistentInstance: If there is no parent."
  },
  {
    "code": "def Name(self, number):\n    if number in self._enum_type.values_by_number:\n      return self._enum_type.values_by_number[number].name\n    raise ValueError('Enum %s has no name defined for value %d' % (\n        self._enum_type.name, number))",
    "docstring": "Returns a string containing the name of an enum value."
  },
  {
    "code": "def _dispatch(self, textgroup, directory):\n        self.dispatcher.dispatch(textgroup, path=directory)",
    "docstring": "Sparql dispatcher do not need to dispatch works, as the link is DB stored through Textgroup\n\n        :param textgroup: A Textgroup object\n        :param directory: The path in which we found the textgroup\n        :return:"
  },
  {
    "code": "def display_string_dump(self, section_spec):\r\n        section = _section_from_spec(self.elf_file, section_spec)\r\n        if section is None:\r\n            print(\"Section '%s' does not exist in the file!\" % section_spec)\r\n            return None\r\n        data = section.data()\r\n        dataptr = 0\r\n        strs = []\r\n        while dataptr < len(data):\r\n            while dataptr < len(data) and not 32 <= byte2int(data[dataptr]) <= 127:\r\n                dataptr += 1\r\n            if dataptr >= len(data):\r\n                break\r\n            endptr = dataptr\r\n            while endptr < len(data) and byte2int(data[endptr]) != 0:\r\n                endptr += 1\r\n            strs.append(binascii.b2a_hex(\r\n                data[dataptr:endptr]).decode().upper())\r\n            dataptr = endptr\r\n        return strs",
    "docstring": "Display a strings dump of a section. section_spec is either a\r\n            section number or a name."
  },
  {
    "code": "def _get_alm_disp_fc3(disp_dataset):\n    natom = disp_dataset['natom']\n    ndisp = len(disp_dataset['first_atoms'])\n    for disp1 in disp_dataset['first_atoms']:\n        ndisp += len(disp1['second_atoms'])\n    disp = np.zeros((ndisp, natom, 3), dtype='double', order='C')\n    indices = []\n    count = 0\n    for disp1 in disp_dataset['first_atoms']:\n        indices.append(count)\n        disp[count, disp1['number']] = disp1['displacement']\n        count += 1\n    for disp1 in disp_dataset['first_atoms']:\n        for disp2 in disp1['second_atoms']:\n            if 'included' in disp2:\n                if disp2['included']:\n                    indices.append(count)\n            else:\n                indices.append(count)\n            disp[count, disp1['number']] = disp1['displacement']\n            disp[count, disp2['number']] = disp2['displacement']\n            count += 1\n    return disp, indices",
    "docstring": "Create displacements of atoms for ALM input\n\n    Note\n    ----\n    Dipslacements of all atoms in supercells for all displacement\n    configurations in phono3py are returned, i.e., most of\n    displacements are zero. Only the configurations with 'included' ==\n    True are included in the list of indices that is returned, too.\n\n    Parameters\n    ----------\n    disp_dataset : dict\n        Displacement dataset that may be obtained by\n        file_IO.parse_disp_fc3_yaml.\n\n    Returns\n    -------\n    disp : ndarray\n        Displacements of atoms in supercells of all displacement\n        configurations.\n        shape=(ndisp, natom, 3)\n        dtype='double'\n    indices : list of int\n        The indices of the displacement configurations with 'included' == True."
  },
  {
    "code": "def setRegisterNumbersForTemporaries(ast, start):\n    seen = 0\n    signature = ''\n    aliases = []\n    for node in ast.postorderWalk():\n        if node.astType == 'alias':\n            aliases.append(node)\n            node = node.value\n        if node.reg.immediate:\n            node.reg.n = node.value\n            continue\n        reg = node.reg\n        if reg.n is None:\n            reg.n = start + seen\n            seen += 1\n            signature += reg.node.typecode()\n    for node in aliases:\n        node.reg = node.value.reg\n    return start + seen, signature",
    "docstring": "Assign register numbers for temporary registers, keeping track of\n    aliases and handling immediate operands."
  },
  {
    "code": "def get_text_path(self):\n        for res in self.dsDoc['dataResources']:\n            resPath = res['resPath']\n            resType = res['resType']\n            isCollection = res['isCollection']\n            if resType == 'text' and isCollection:\n                return os.path.join(self.dsHome, resPath)\n        raise RuntimeError('could not find learningData file the dataset')",
    "docstring": "Returns the path of the directory containing text if they exist in this dataset."
  },
  {
    "code": "def ssh_compute_remove(public_key, application_name, user=None):\n    if not (os.path.isfile(authorized_keys(application_name, user)) or\n            os.path.isfile(known_hosts(application_name, user))):\n        return\n    keys = ssh_authorized_keys_lines(application_name, user=None)\n    keys = [k.strip() for k in keys]\n    if public_key not in keys:\n        return\n    [keys.remove(key) for key in keys if key == public_key]\n    with open(authorized_keys(application_name, user), 'w') as _keys:\n        keys = '\\n'.join(keys)\n        if not keys.endswith('\\n'):\n            keys += '\\n'\n        _keys.write(keys)",
    "docstring": "Remove given public key from authorized_keys file.\n\n    :param public_key: Public key.\n    :type public_key: str\n    :param application_name: Name of application eg nova-compute-something\n    :type application_name: str\n    :param user: The user that the ssh asserts are for.\n    :type user: str"
  },
  {
    "code": "def update_in_hdx(self):\n        capacity = self.data.get('capacity')\n        if capacity is not None:\n            del self.data['capacity']\n        self._update_in_hdx('user', 'id')\n        if capacity is not None:\n            self.data['capacity'] = capacity",
    "docstring": "Check if user exists in HDX and if so, update user\n\n        Returns:\n            None"
  },
  {
    "code": "def bounding_box_as_binary_map(alpha, threshold=0.1):\n    bb = bounding_box(alpha)\n    x = np.zeros(alpha.shape, dtype=np.bool_)\n    x[bb[0]:bb[2], bb[1]:bb[3]] = 1\n    return x",
    "docstring": "Similar to `bounding_box`, except returns the bounding box as a\n    binary map the same size as the input.\n\n    Same parameters as `bounding_box`.\n\n    Returns\n    -------\n    binary_map : ndarray, ndim=2, dtype=np.bool_\n        Binary map with True if object and False if background."
  },
  {
    "code": "def get_cytoband_names():\n    return [\n        n.replace(\".json.gz\", \"\")\n        for n in pkg_resources.resource_listdir(__name__, _data_dir)\n        if n.endswith(\".json.gz\")\n    ]",
    "docstring": "Returns the names of available cytoband data files\n\n    >> get_cytoband_names()\n    ['ucsc-hg38', 'ucsc-hg19']"
  },
  {
    "code": "def extract(cls, extractor, typ):\n        schema = {\n            \"title\": typ.__name__,\n            \"type\": \"object\",\n            \"properties\": {},\n            \"required\": []\n        }\n        for attribute in attr.fields(typ):\n            details = cls._extract_attribute(extractor, attribute)\n            if details.is_required:\n                schema[\"required\"].append(details.name)\n            schema[\"properties\"][details.name] = details.schema\n        return schema",
    "docstring": "take an attrs based class, and convert it\n        to jsonschema."
  },
  {
    "code": "def clean_buckets(self, hash_name):\n        bucket_keys = self._iter_bucket_keys(hash_name)\n        self.redis_object.delete(*bucket_keys)",
    "docstring": "Removes all buckets and their content for specified hash."
  },
  {
    "code": "def construct_xray_header(headers):\n    header_str = headers.get(http.XRAY_HEADER) or headers.get(http.ALT_XRAY_HEADER)\n    if header_str:\n        return TraceHeader.from_header_str(header_str)\n    else:\n        return TraceHeader()",
    "docstring": "Construct a ``TraceHeader`` object from dictionary headers\n    of the incoming request. This method should always return\n    a ``TraceHeader`` object regardless of tracing header's presence\n    in the incoming request."
  },
  {
    "code": "def filter(self, record):\n        if isinstance(record.msg, basestring):\n            message = record.msg.lower()\n            if all(kw in message for kw in self.KEYWORDS):\n                record.levelname = 'DEBUG'\n                record.levelno = logging.DEBUG\n        return 1",
    "docstring": "Change the severity of selected log records."
  },
  {
    "code": "def declares_namespace_package(filename):\n  import ast\n  with open(filename) as fp:\n    init_py = ast.parse(fp.read(), filename)\n  calls = [node for node in ast.walk(init_py) if isinstance(node, ast.Call)]\n  for call in calls:\n    if len(call.args) != 1:\n      continue\n    if isinstance(call.func, ast.Attribute) and call.func.attr != 'declare_namespace':\n      continue\n    if isinstance(call.func, ast.Name) and call.func.id != 'declare_namespace':\n      continue\n    if isinstance(call.args[0], ast.Name) and call.args[0].id == '__name__':\n      return True\n  return False",
    "docstring": "Given a filename, walk its ast and determine if it declares a namespace package."
  },
  {
    "code": "def _validate_namespace(self, namespace):\n        if self._namespace_regex.fullmatch(namespace) is None:\n            LOGGER.debug('Invalid namespace: %s', namespace)\n            raise _ResponseFailed(self._status.INVALID_ADDRESS)",
    "docstring": "Validates a namespace, raising a ResponseFailed error if invalid.\n\n        Args:\n            state_root (str): The state_root to validate\n\n        Raises:\n            ResponseFailed: The state_root was invalid, and a status of\n                INVALID_ROOT will be sent with the response."
  },
  {
    "code": "def do_IAmRequest(self, apdu):\n        if _debug: WhoIsIAmServices._debug(\"do_IAmRequest %r\", apdu)\n        if apdu.iAmDeviceIdentifier is None:\n            raise MissingRequiredParameter(\"iAmDeviceIdentifier required\")\n        if apdu.maxAPDULengthAccepted is None:\n            raise MissingRequiredParameter(\"maxAPDULengthAccepted required\")\n        if apdu.segmentationSupported is None:\n            raise MissingRequiredParameter(\"segmentationSupported required\")\n        if apdu.vendorID is None:\n            raise MissingRequiredParameter(\"vendorID required\")\n        device_instance = apdu.iAmDeviceIdentifier[1]\n        if _debug: WhoIsIAmServices._debug(\"    - device_instance: %r\", device_instance)\n        device_address = apdu.pduSource\n        if _debug: WhoIsIAmServices._debug(\"    - device_address: %r\", device_address)",
    "docstring": "Respond to an I-Am request."
  },
  {
    "code": "def DbGetDeviceFamilyList(self, argin):\n        self._log.debug(\"In DbGetDeviceFamilyList()\")\n        argin = replace_wildcard(argin)\n        return self.db.get_device_family_list(argin)",
    "docstring": "Get a list of device name families for device name matching the\n        specified wildcard\n\n        :param argin: The wildcard\n        :type: tango.DevString\n        :return: Family list\n        :rtype: tango.DevVarStringArray"
  },
  {
    "code": "def fetch(elastic, backend, limit=None, search_after_value=None, scroll=True):\n    logging.debug(\"Creating a elastic items generator.\")\n    elastic_scroll_id = None\n    search_after = search_after_value\n    while True:\n        if scroll:\n            rjson = get_elastic_items(elastic, elastic_scroll_id, limit)\n        else:\n            rjson = get_elastic_items_search(elastic, search_after, limit)\n        if rjson and \"_scroll_id\" in rjson:\n            elastic_scroll_id = rjson[\"_scroll_id\"]\n        if rjson and \"hits\" in rjson:\n            if not rjson[\"hits\"][\"hits\"]:\n                break\n            for hit in rjson[\"hits\"][\"hits\"]:\n                item = hit['_source']\n                if 'sort' in hit:\n                    search_after = hit['sort']\n                try:\n                    backend._fix_item(item)\n                except Exception:\n                    pass\n                yield item\n        else:\n            logging.error(\"No results found from %s\", elastic.index_url)\n            break\n    return",
    "docstring": "Fetch the items from raw or enriched index"
  },
  {
    "code": "def create_auth_group(sender, instance, created, **kwargs):\n    if created:\n        AuthGroup.objects.create(group=instance)",
    "docstring": "Creates the AuthGroup model when a group is created"
  },
  {
    "code": "def cache_key(self):\n        return '%s:%s' % (super(EntryPublishedVectorBuilder, self).cache_key,\n                          Site.objects.get_current().pk)",
    "docstring": "Key for the cache handling current site."
  },
  {
    "code": "def setDatastreamState(self, pid, dsID, dsState):\n        http_args = {'dsState' : dsState}\n        url = 'objects/%(pid)s/datastreams/%(dsid)s' % {'pid': pid, 'dsid': dsID}\n        response = self.put(url, params=http_args)\n        return response.status_code == requests.codes.ok",
    "docstring": "Update datastream state.\n\n        :param pid: object pid\n        :param dsID: datastream id\n        :param dsState: datastream state\n        :returns: boolean success"
  },
  {
    "code": "def reverse_iterator(self, symbol, chunk_range=None):\n        sym = self._get_symbol_info(symbol)\n        if not sym:\n            raise NoDataFoundException(\"Symbol does not exist.\")\n        c = CHUNKER_MAP[sym[CHUNKER]]\n        for chunk in list(self.get_chunk_ranges(symbol, chunk_range=chunk_range, reverse=True)):\n            yield self.read(symbol, chunk_range=c.to_range(chunk[0], chunk[1]))",
    "docstring": "Returns a generator that accesses each chunk in descending order\n\n        Parameters\n        ----------\n        symbol: str\n            the symbol for the given item in the DB\n        chunk_range: None, or a range object\n            allows you to subset the chunks by range\n\n        Returns\n        -------\n        generator"
  },
  {
    "code": "def _get_assignment_target_end(self, ast_module):\n        if len(ast_module.body) > 1:\n            raise ValueError(\"More than one expression or assignment.\")\n        elif len(ast_module.body) > 0 and \\\n                type(ast_module.body[0]) is ast.Assign:\n            if len(ast_module.body[0].targets) != 1:\n                raise ValueError(\"More than one assignment target.\")\n            else:\n                return len(ast_module.body[0].targets[0].id)\n        return -1",
    "docstring": "Returns position of 1st char after assignment traget.\n\n        If there is no assignment, -1 is returned\n\n        If there are more than one of any ( expressions or assigments)\n        then a ValueError is raised."
  },
  {
    "code": "def my_main(context):\n    print('starting MyApp...')\n    if context['debug']:\n        print('Context:')\n        for k in context:\n            print('Key: {}\\nValue: {}'.format(k, context[k]))\n        print('Done!')\n    return 0",
    "docstring": "The starting point for your app."
  },
  {
    "code": "def get(self, id):\n        schema = PackageSchema()\n        resp = self.service.get_id(self.base, id)\n        return self.service.decode(schema, resp)",
    "docstring": "Get a package.\n\n        :param id: Package ID as an int.\n        :return: :class:`packages.Package <packages.Package>` object\n        :rtype: packages.Package"
  },
  {
    "code": "def deactivate_mfa_device(self, user_name, serial_number):\n        params = {'UserName' : user_name,\n                  'SerialNumber' : serial_number}\n        return self.get_response('DeactivateMFADevice', params)",
    "docstring": "Deactivates the specified MFA device and removes it from\n        association with the user.\n\n        :type user_name: string\n        :param user_name: The username of the user\n        \n        :type serial_number: string\n        :param seriasl_number: The serial number which uniquely identifies\n                               the MFA device."
  },
  {
    "code": "def modify_identity(self, identity, **kwargs):\n        if isinstance(identity, zobjects.Identity):\n            self.request('ModifyIdentity', {'identity': identity._full_data})\n            return self.get_identities(identity=identity.name)[0]\n        else:\n            attrs = []\n            for attr, value in kwargs.items():\n                attrs.append({\n                    'name': attr,\n                    '_content': value\n                })\n            self.request('ModifyIdentity', {\n                'identity': {\n                    'name': identity,\n                    'a': attrs\n                }\n            })\n            return self.get_identities(identity=identity)[0]",
    "docstring": "Modify some attributes of an identity or its name.\n\n        :param: identity a zobjects.Identity with `id` set (mandatory). Also\n               set items you want to modify/set and/or the `name` attribute to\n               rename the identity.\n               Can also take the name in string and then attributes to modify\n        :returns: zobjects.Identity object"
  },
  {
    "code": "def find_link(self, device):\n        for i in range(len(self.mpstate.mav_master)):\n            conn = self.mpstate.mav_master[i]\n            if (str(i) == device or\n                conn.address == device or\n                getattr(conn, 'label', None) == device):\n                return i\n        return None",
    "docstring": "find a device based on number, name or label"
  },
  {
    "code": "def move_transition_point(self, fragment_index, value):\n        self.log(u\"Called move_transition_point with\")\n        self.log([u\"  fragment_index %d\", fragment_index])\n        self.log([u\"  value          %.3f\", value])\n        if (fragment_index < 0) or (fragment_index > (len(self) - 3)):\n            self.log(u\"Bad fragment_index, returning\")\n            return\n        current_interval = self[fragment_index].interval\n        next_interval = self[fragment_index + 1].interval\n        if value > next_interval.end:\n            self.log(u\"Bad value, returning\")\n            return\n        if not current_interval.is_non_zero_before_non_zero(next_interval):\n            self.log(u\"Bad interval configuration, returning\")\n            return\n        current_interval.end = value\n        next_interval.begin = value\n        self.log(u\"Moved transition point\")",
    "docstring": "Change the transition point between fragment ``fragment_index``\n        and the next fragment to the time value ``value``.\n\n        This method fails silently\n        (without changing the fragment list)\n        if at least one of the following conditions holds:\n\n        * ``fragment_index`` is negative\n        * ``fragment_index`` is the last or the second-to-last\n        * ``value`` is after the current end of the next fragment\n        * the current fragment and the next one are not adjacent and both proper intervals (not zero length)\n\n        The above conditions ensure that the move makes sense\n        and that it keeps the list satisfying the constraints.\n\n        :param int fragment_index: the fragment index whose end should be moved\n        :param value: the new transition point\n        :type  value: :class:`~aeneas.exacttiming.TimeValue`"
  },
  {
    "code": "def assert_allowed(request, level, pid):\n    if not d1_gmn.app.models.ScienceObject.objects.filter(pid__did=pid).exists():\n        raise d1_common.types.exceptions.NotFound(\n            0,\n            'Attempted to perform operation on non-existing object. pid=\"{}\"'.format(\n                pid\n            ),\n        )\n    if not is_allowed(request, level, pid):\n        raise d1_common.types.exceptions.NotAuthorized(\n            0,\n            'Operation is denied. level=\"{}\", pid=\"{}\", active_subjects=\"{}\"'.format(\n                level_to_action(level), pid, format_active_subjects(request)\n            ),\n        )",
    "docstring": "Assert that one or more subjects are allowed to perform action on object.\n\n    Raise NotAuthorized if object exists and subject is not allowed. Raise NotFound if\n    object does not exist."
  },
  {
    "code": "def rename(self, name):\n        if name is None:\n            raise Exception(\"name (%s) not-valid\" % (name,))\n        self.prefix, self.name = splitPrefix(name)",
    "docstring": "Rename the element.\n\n        @param name: A new name for the element.\n        @type name: basestring"
  },
  {
    "code": "def applicationinsights_mgmt_plane_client(cli_ctx, _, subscription=None):\n    from .vendored_sdks.mgmt_applicationinsights import ApplicationInsightsManagementClient\n    from azure.cli.core._profile import Profile\n    profile = Profile(cli_ctx=cli_ctx)\n    if subscription:\n        cred, _, _ = profile.get_login_credentials(subscription_id=subscription)\n        return ApplicationInsightsManagementClient(\n            cred,\n            subscription\n        )\n    cred, sub_id, _ = profile.get_login_credentials()\n    return ApplicationInsightsManagementClient(\n        cred,\n        sub_id\n    )",
    "docstring": "Initialize Log Analytics mgmt client for use with CLI."
  },
  {
    "code": "def get_comments_of_incoming_per_page(self, incoming_id, per_page=1000, page=1):\n        return self._get_resource_per_page(\n            resource=INCOMING_COMMENTS,\n            per_page=per_page,\n            page=page,\n            params={'incoming_id': incoming_id},\n        )",
    "docstring": "Get comments of incoming per page\n\n        :param incoming_id: the incoming id\n        :param per_page: How many objects per page. Default: 1000\n        :param page: Which page. Default: 1\n        :return: list"
  },
  {
    "code": "def which(exe):\n    def wrapper(function):\n        def wrapped(*args, **kwargs):\n            if salt.utils.path.which(exe) is None:\n                raise CommandNotFoundError(\n                    'The \\'{0}\\' binary was not found in $PATH.'.format(exe)\n                )\n            return function(*args, **kwargs)\n        return identical_signature_wrapper(function, wrapped)\n    return wrapper",
    "docstring": "Decorator wrapper for salt.utils.path.which"
  },
  {
    "code": "def register_lists(self, category_lists, lists_init_kwargs=None, editor_init_kwargs=None):\n        lists_init_kwargs = lists_init_kwargs or {}\n        editor_init_kwargs = editor_init_kwargs or {}\n        for lst in category_lists:\n            if isinstance(lst, string_types):\n                lst = self.list_cls(lst, **lists_init_kwargs)\n            elif not isinstance(lst, CategoryList):\n                raise SitecatsConfigurationError(\n                    '`CategoryRequestHandler.register_lists()` accepts only '\n                    '`CategoryList` objects or category aliases.'\n                )\n            if self._obj:\n                lst.set_obj(self._obj)\n            for name, val in lists_init_kwargs.items():\n                setattr(lst, name, val)\n            lst.enable_editor(**editor_init_kwargs)\n            self._lists[lst.get_id()] = lst",
    "docstring": "Registers CategoryList objects to handle their requests.\n\n        :param list category_lists: CategoryList objects\n        :param dict lists_init_kwargs: Attributes to apply to each of CategoryList objects"
  },
  {
    "code": "def get_command_class(self, cmd):\n        try:\n            cmdpath = self.registry[cmd]\n        except KeyError:\n            raise CommandError(\"No such command %r\" % cmd)\n        if isinstance(cmdpath, basestring):\n            Command = import_class(cmdpath)\n        else:\n            Command = cmdpath\n        return Command",
    "docstring": "Returns command class from the registry for a given ``cmd``.\n\n        :param cmd: command to run (key at the registry)"
  },
  {
    "code": "def resume(config_path: str, restore_from: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None:\n    config = None\n    try:\n        config_path = find_config(config_path)\n        restore_from = restore_from or path.dirname(config_path)\n        config = load_config(config_file=config_path, additional_args=cl_arguments)\n        validate_config(config)\n        logging.debug('\\tLoaded config: %s', config)\n    except Exception as ex:\n        fallback('Loading config failed', ex)\n    run(config=config, output_root=output_root, restore_from=restore_from)",
    "docstring": "Load config from the directory specified and start the training.\n\n    :param config_path: path to the config file or the directory in which it is stored\n    :param restore_from: backend-specific path to the already trained model to be restored from.\n                         If ``None`` is passed, it is inferred from the configuration file location as the directory\n                         it is located in.\n    :param cl_arguments: additional command line arguments which will update the configuration\n    :param output_root: output root in which the training directory will be created"
  },
  {
    "code": "def view_on_site(self, request, content_type_id, object_id):\n        try:\n            content_type = ContentType.objects.get(pk=content_type_id)\n            if not content_type.model_class():\n                raise Http404(_(\"Content type %(ct_id)s object has no associated model\") % {\n                    'ct_id': content_type_id,\n                })\n            obj = content_type.get_object_for_this_type(pk=object_id)\n        except (ObjectDoesNotExist, ValueError):\n            raise Http404(_(\"Content type %(ct_id)s object %(obj_id)s doesn't exist\") % {\n                'ct_id': content_type_id,\n                'obj_id': object_id,\n            })\n        try:\n            get_absolute_url = obj.get_absolute_url\n        except AttributeError:\n            raise Http404(_(\"%(ct_name)s objects don't have a get_absolute_url() method\") % {\n                'ct_name': content_type.name,\n            })\n        absurl = get_absolute_url()\n        return HttpResponseRedirect(absurl)",
    "docstring": "Redirect to an object's page based on a content-type ID and an object ID."
  },
  {
    "code": "def authorizer(self, schemes, resource, action, request_args):\n        if not schemes:\n            return u'', u''\n        for scheme in schemes:\n            if scheme in self.schemes and self.has_auth_params(scheme):\n                cred = Context.format_auth_params(self.schemes[scheme][u'params'])\n                if hasattr(self, 'mfa_token'):\n                    cred = '{}, mfa_token=\"{}\"'.format(cred, self.mfa_token)\n                return scheme, cred\n        raise AuthenticationError(self, schemes)",
    "docstring": "Construct the Authorization header for a request.\n\n        Args:\n          schemes (list of str): Authentication schemes supported for the\n            requested action.\n          resource (str): Object upon which an action is being performed.\n          action (str): Action being performed.\n          request_args (list of str): Arguments passed to the action call.\n\n        Returns:\n          (str, str) A tuple of the auth scheme satisfied, and the credential\n            for the Authorization header or empty strings if none could be\n            satisfied."
  },
  {
    "code": "def check_valid(self, get_params):\n        if self.commands._if:\n            return self.commands._if.check_valid(get_params)",
    "docstring": "see if the if condition for a block is valid"
  },
  {
    "code": "def close_async(self):\n        if self._stream is None or self._stream.closed():\n            self._stream = None\n            return\n        send_data = struct.pack('<i', 1) + int2byte(COMMAND.COM_QUIT)\n        yield self._stream.write(send_data)\n        self.close()",
    "docstring": "Send the quit message and close the socket"
  },
  {
    "code": "def create(self, parties):\n        assert parties > 0, \"parties must be a positive integer.\"\n        return self.backend.add(self.key, parties, self.ttl)",
    "docstring": "Create the barrier for the given number of parties.\n\n        Parameters:\n          parties(int): The number of parties to wait for.\n\n        Returns:\n          bool: Whether or not the new barrier was successfully created."
  },
  {
    "code": "def run(self):\n        _, test_data = self.data.load(train=False, test=True)\n        try:\n            self.model.fit_generator(\n                self.samples_to_batches(self.generate_samples(), self.args.batch_size), steps_per_epoch=self.args.steps_per_epoch,\n                epochs=self.epoch + self.args.epochs, validation_data=test_data,\n                callbacks=self.callbacks, initial_epoch=self.epoch\n            )\n        finally:\n            self.model.save(self.args.model)\n            save_params(self.args.model)",
    "docstring": "Train the model on randomly generated batches"
  },
  {
    "code": "def get_indicator(self, resource):\n        path = resource.real_path\n        if os.name != 'posix' and os.path.isdir(path):\n            return (os.path.getmtime(path),\n                    len(os.listdir(path)),\n                    os.path.getsize(path))\n        return (os.path.getmtime(path),\n                os.path.getsize(path))",
    "docstring": "Return the modification time and size of a `Resource`."
  },
  {
    "code": "def assembly_plus_protons(input_file, path=True, pdb_name=None,\n                          save_output=False, force_save=False):\n    from ampal.pdb_parser import convert_pdb_to_ampal\n    if path:\n        input_path = Path(input_file)\n        if not pdb_name:\n            pdb_name = input_path.stem[:4]\n        reduced_path = reduce_output_path(path=input_path)\n        if reduced_path.exists() and not save_output and not force_save:\n            reduced_assembly = convert_pdb_to_ampal(\n                str(reduced_path), pdb_id=pdb_name)\n            return reduced_assembly\n    if save_output:\n        reduced_path = output_reduce(\n            input_file, path=path, pdb_name=pdb_name, force=force_save)\n        reduced_assembly = convert_pdb_to_ampal(str(reduced_path), path=True)\n    else:\n        reduce_mmol, reduce_message = run_reduce(input_file, path=path)\n        if not reduce_mmol:\n            return None\n        reduced_assembly = convert_pdb_to_ampal(\n            reduce_mmol, path=False, pdb_id=pdb_name)\n    return reduced_assembly",
    "docstring": "Returns an Assembly with protons added by Reduce.\n\n    Notes\n    -----\n    Looks for a pre-existing Reduce output in the standard location before\n    running Reduce. If the protein contains oligosaccharides or glycans,\n    use reduce_correct_carbohydrates.\n\n    Parameters\n    ----------\n    input_file : str or pathlib.Path\n        Location of file to be converted to Assembly or PDB file as string.\n    path : bool\n        Whether we are looking at a file or a pdb string. Defaults to file.\n    pdb_name : str\n        PDB ID of protein. Required if providing string not path.\n    save_output : bool\n        If True will save the generated assembly.\n    force_save : bool\n        If True will overwrite existing reduced assembly.\n\n    Returns\n    -------\n    reduced_assembly : AMPAL Assembly\n        Assembly of protein with protons added by Reduce."
  },
  {
    "code": "def list(self, cur_p=''):\n        current_page_number = int(cur_p) if cur_p else 1\n        current_page_number = 1 if current_page_number < 1 else current_page_number\n        kwd = {\n            'current_page': current_page_number\n        }\n        recs = MEntity.get_all_pager(current_page_num=current_page_number)\n        self.render('misc/entity/entity_list.html',\n                    imgs=recs,\n                    cfg=config.CMS_CFG,\n                    kwd=kwd,\n                    userinfo=self.userinfo)",
    "docstring": "Lists of the entities."
  },
  {
    "code": "def _neighbors_graph(self, **params) -> Dict:\n        response = self._get_response(\"graph/neighbors\", format=\"json\", **params)\n        return response.json()",
    "docstring": "Get neighbors of a node\n\n        parameters are directly passed through to SciGraph: e.g. depth, relationshipType"
  },
  {
    "code": "def reload_accelerators(self, *args):\n        if self.accel_group:\n            self.guake.window.remove_accel_group(self.accel_group)\n        self.accel_group = Gtk.AccelGroup()\n        self.guake.window.add_accel_group(self.accel_group)\n        self.load_accelerators()",
    "docstring": "Reassign an accel_group to guake main window and guake\n        context menu and calls the load_accelerators method."
  },
  {
    "code": "def walk_dir(path, args, state):\n    if args.debug:\n        sys.stderr.write(\"Walking %s\\n\" % path)\n    for root, _dirs, files in os.walk(path):\n        if not safe_process_files(root, files, args, state):\n            return False\n        if state.should_quit():\n            return False\n    return True",
    "docstring": "Check all files in `path' to see if there is any requests that\n    we should send out on the bus."
  },
  {
    "code": "def concentric_hexagons(radius, start=(0, 0)):\n    x, y = start\n    yield (x, y)\n    for r in range(1, radius + 1):\n        y -= 1\n        for dx, dy in [(1, 1), (0, 1), (-1, 0), (-1, -1), (0, -1), (1, 0)]:\n            for _ in range(r):\n                yield (x, y)\n                x += dx\n                y += dy",
    "docstring": "A generator which produces coordinates of concentric rings of hexagons.\n\n    Parameters\n    ----------\n    radius : int\n        Number of layers to produce (0 is just one hexagon)\n    start : (x, y)\n        The coordinate of the central hexagon."
  },
  {
    "code": "def get(request):\n    res = Result()\n    obj, created = UserPref.objects.get_or_create(user=request.user, defaults={'data': json.dumps(DefaultPrefs.copy())})\n    data = obj.json()\n    data['subscriptions'] = [_.json() for _ in GallerySubscription.objects.filter(user=request.user)]\n    res.append(data)\n    return JsonResponse(res.asDict())",
    "docstring": "Gets the currently logged in users preferences\n\n    :returns: json"
  },
  {
    "code": "def init_all_objects(self, data, target=None, single_result=True):\n        if single_result:\n            return self.init_target_object(target, data)\n        return list(self.expand_models(target, data))",
    "docstring": "Initializes model instances from given data.\n        Returns single instance if single_result=True."
  },
  {
    "code": "def _escape(self, value):\n        if isinstance(value, SafeString):\n            return value\n        return shellescape.quote(value)",
    "docstring": "Escape given value unless it is safe."
  },
  {
    "code": "def clone(name, new_name, linked=False, template=False, runas=None):\n    args = [salt.utils.data.decode(name), '--name', salt.utils.data.decode(new_name)]\n    if linked:\n        args.append('--linked')\n    if template:\n        args.append('--template')\n    return prlctl('clone', args, runas=runas)",
    "docstring": "Clone a VM\n\n    .. versionadded:: 2016.11.0\n\n    :param str name:\n        Name/ID of VM to clone\n\n    :param str new_name:\n        Name of the new VM\n\n    :param bool linked:\n        Create a linked virtual machine.\n\n    :param bool template:\n        Create a virtual machine template instead of a real virtual machine.\n\n    :param str runas:\n        The user that the prlctl command will be run as\n\n    Example:\n\n    .. code-block:: bash\n\n        salt '*' parallels.clone macvm macvm_new runas=macdev\n        salt '*' parallels.clone macvm macvm_templ template=True runas=macdev"
  },
  {
    "code": "def _ExtractYahooSearchQuery(self, url):\n    if 'p=' not in url:\n      return None\n    _, _, line = url.partition('p=')\n    before_and, _, _ = line.partition('&')\n    if not before_and:\n      return None\n    yahoo_search_url = before_and.split()[0]\n    return yahoo_search_url.replace('+', ' ')",
    "docstring": "Extracts a search query from a Yahoo search URL.\n\n    Examples:\n      https://search.yahoo.com/search?p=query\n      https://search.yahoo.com/search;?p=query\n\n    Args:\n      url (str): URL.\n\n    Returns:\n      str: search query or None if no query was found."
  },
  {
    "code": "def append(self, data):\n        for k in self._entries.keys():\n            self._entries[k].append(data._entries[k])",
    "docstring": "Append a Data instance to self"
  },
  {
    "code": "def blocking_start(self, waiting_func=None):\n        self.logger.debug('threadless start')\n        try:\n            for job_params in self._get_iterator():\n                self.config.logger.debug('received %r', job_params)\n                self.quit_check()\n                if job_params is None:\n                    if self.config.quit_on_empty_queue:\n                        raise KeyboardInterrupt\n                    self.logger.info(\"there is nothing to do.  Sleeping \"\n                                     \"for %d seconds\" %\n                                     self.config.idle_delay)\n                    self._responsive_sleep(self.config.idle_delay)\n                    continue\n                self.quit_check()\n                try:\n                    args, kwargs = job_params\n                except ValueError:\n                    args = job_params\n                    kwargs = {}\n                try:\n                    self.task_func(*args, **kwargs)\n                except Exception:\n                    self.config.logger.error(\"Error in processing a job\",\n                                             exc_info=True)\n        except KeyboardInterrupt:\n            self.logger.debug('queuingThread gets quit request')\n        finally:\n            self.quit = True\n            self.logger.debug(\"ThreadlessTaskManager dies quietly\")",
    "docstring": "this function starts the task manager running to do tasks.  The\n        waiting_func is normally used to do something while other threads\n        are running, but here we don't have other threads.  So the waiting\n        func will never get called.  I can see wanting this function to be\n        called at least once after the end of the task loop."
  },
  {
    "code": "def encrypt(self, mesg):\n        seqn = next(self._tx_sn)\n        rv = self._tx_tinh.enc(s_msgpack.en((seqn, mesg)))\n        return rv",
    "docstring": "Wrap a message with a sequence number and encrypt it.\n\n        Args:\n            mesg: The mesg to encrypt.\n\n        Returns:\n            bytes: The encrypted message."
  },
  {
    "code": "def get_func_task_path(func):\n    module_path = inspect.getmodule(func).__name__\n    task_path = '{module_path}.{func_name}'.format(\n                                        module_path=module_path,\n                                        func_name=func.__name__\n                                    )\n    return task_path",
    "docstring": "Format the modular task path for a function via inspection."
  },
  {
    "code": "def should_see_in_seconds(self, text, timeout):\n    def check_element():\n        assert contains_content(world.browser, text), \\\n            \"Expected element with the given text.\"\n    wait_for(check_element)(timeout=int(timeout))",
    "docstring": "Assert provided text is visible within n seconds.\n\n    Be aware this text could be anywhere on the screen. Also be aware that\n    it might cross several HTML nodes. No determination is made between\n    block and inline nodes. Whitespace can be affected."
  },
  {
    "code": "def backtrack(self, decision_level):\n        self._backtracking = True\n        packages = set()\n        while self._assignments[-1].decision_level > decision_level:\n            removed = self._assignments.pop(-1)\n            packages.add(removed.dependency.name)\n            if removed.is_decision():\n                del self._decisions[removed.dependency.name]\n        for package in packages:\n            if package in self._positive:\n                del self._positive[package]\n            if package in self._negative:\n                del self._negative[package]\n        for assignment in self._assignments:\n            if assignment.dependency.name in packages:\n                self._register(assignment)",
    "docstring": "Resets the current decision level to decision_level, and removes all\n        assignments made after that level."
  },
  {
    "code": "def make_driver(loop=None):\n    loop = loop or asyncio.get_event_loop()\n    def stop(i = None):\n        loop.stop()\n    def driver(sink):\n        sink.control.subscribe(\n            on_next=stop,\n            on_error=stop,\n            on_completed=stop)\n        return None\n    return Component(call=driver, input=Sink)",
    "docstring": "Returns a stop driver. \n    \n    The optional loop argument can be provided to use the driver in another \n    loop than the default one.\n\n    Parameters\n    -----------\n    loop: BaseEventLoop\n        The event loop to use instead of the default one."
  },
  {
    "code": "def processCommit(self, commit: Commit, sender: str) -> None:\n        self.logger.debug(\"{} received COMMIT{} from {}\".format(\n            self, (commit.viewNo, commit.ppSeqNo), sender))\n        if self.validateCommit(commit, sender):\n            self.stats.inc(TPCStat.CommitRcvd)\n            self.addToCommits(commit, sender)\n            self.logger.debug(\"{} processed incoming COMMIT{}\".format(\n                self, (commit.viewNo, commit.ppSeqNo)))",
    "docstring": "Validate and process the COMMIT specified.\n        If validation is successful, return the message to the node.\n\n        :param commit: an incoming COMMIT message\n        :param sender: name of the node that sent the COMMIT"
  },
  {
    "code": "def process_json_file(file_name):\n    with open(file_name, 'rt') as fh:\n        pybel_graph = pybel.from_json_file(fh, False)\n    return process_pybel_graph(pybel_graph)",
    "docstring": "Return a PybelProcessor by processing a Node-Link JSON file.\n\n    For more information on this format, see:\n    http://pybel.readthedocs.io/en/latest/io.html#node-link-json\n\n    Parameters\n    ----------\n    file_name : str\n        The path to a Node-Link JSON file.\n\n    Returns\n    -------\n    bp : PybelProcessor\n        A PybelProcessor object which contains INDRA Statements in\n        bp.statements."
  },
  {
    "code": "def _float(value):\n    if \"[\" in value:\n        value, sep, unit = value.partition(\"[\")\n        unit = sep + unit\n        if unit in (\"[km]\", \"[km/s]\"):\n            multiplier = 1000\n        elif unit == \"[s]\":\n            multiplier = 1\n        else:\n            raise ValueError(\"Unknown unit for this field\", unit)\n    else:\n        multiplier = 1000\n    return float(value) * multiplier",
    "docstring": "Conversion of state vector field, with automatic unit handling"
  },
  {
    "code": "def _install_eslint(self, bootstrap_dir):\n    with pushd(bootstrap_dir):\n      result, install_command = self.install_module(\n        package_manager=self.node_distribution.get_package_manager(package_manager=PACKAGE_MANAGER_YARNPKG),\n        workunit_name=self.INSTALL_JAVASCRIPTSTYLE_TARGET_NAME,\n        workunit_labels=[WorkUnitLabel.PREP])\n      if result != 0:\n        raise TaskError('Failed to install ESLint\\n'\n                        '\\t{} failed with exit code {}'.format(install_command, result))\n    self.context.log.debug('Successfully installed ESLint to {}'.format(bootstrap_dir))\n    return bootstrap_dir",
    "docstring": "Install the ESLint distribution.\n\n    :rtype: string"
  },
  {
    "code": "def _expand(template, seq):\n    if is_text(template):\n        return _simple_expand(template, seq)\n    elif is_data(template):\n        template = wrap(template)\n        assert template[\"from\"], \"Expecting template to have 'from' attribute\"\n        assert template.template, \"Expecting template to have 'template' attribute\"\n        data = seq[-1][template[\"from\"]]\n        output = []\n        for d in data:\n            s = seq + (d,)\n            output.append(_expand(template.template, s))\n        return coalesce(template.separator, \"\").join(output)\n    elif is_list(template):\n        return \"\".join(_expand(t, seq) for t in template)\n    else:\n        if not _Log:\n            _late_import()\n        _Log.error(\"can not handle\")",
    "docstring": "seq IS TUPLE OF OBJECTS IN PATH ORDER INTO THE DATA TREE"
  },
  {
    "code": "def reducer_metro(self, metro, values):\n        lookup = CachedLookup(precision=POI_GEOHASH_PRECISION)\n        for i, value in enumerate(values):\n            type_tag, lonlat, data = value\n            if type_tag == 1:\n                lookup.insert(i, dict(\n                    geometry=dict(type='Point', coordinates=project(lonlat)),\n                    properties=dict(tags=data)\n                ))\n            else:\n                if not lookup.data_store:\n                    return\n                poi_names = []\n                kwargs = dict(buffer_size=POI_DISTANCE, multiple=True)\n                for poi in lookup.get(lonlat, **kwargs):\n                    has_tag = [ tag in poi['tags'] for tag in POI_TAGS ]\n                    if any(has_tag) and 'name' in poi['tags']:\n                        poi_names.append(poi['tags']['name'])\n                for poi in set(poi_names):\n                    yield (metro, poi), 1",
    "docstring": "Output tags of POI locations nearby tweet locations\n\n        Values will be sorted coming into reducer.\n        First element in each value tuple will be either 1 (osm POI) or 2 (geotweet).\n        Build a spatial index with POI records.\n        For each tweet lookup nearby POI, and emit tag values for predefined tags."
  },
  {
    "code": "def name(self):\n    if not hasattr(self, \"_name\"):\n      self._name = \"{}_hub_module_embedding\".format(self.key)\n    return self._name",
    "docstring": "Returns string. Used for variable_scope and naming."
  },
  {
    "code": "def command(self, regexp):\n        def decorator(fn):\n            self.add_command(regexp, fn)\n            return fn\n        return decorator",
    "docstring": "Register a new command\n\n        :param str regexp: Regular expression matching the command to register\n\n        :Example:\n\n        >>> @bot.command(r\"/echo (.+)\")\n        >>> def echo(chat, match):\n        >>>     return chat.reply(match.group(1))"
  },
  {
    "code": "def convert_roipooling(node, **kwargs):\n    name, input_nodes, attrs = get_inputs(node, kwargs)\n    pooled_shape = convert_string_to_list(attrs.get('pooled_size'))\n    scale = float(attrs.get(\"spatial_scale\"))\n    node = onnx.helper.make_node(\n        'MaxRoiPool',\n        input_nodes,\n        [name],\n        pooled_shape=pooled_shape,\n        spatial_scale=scale,\n        name=name\n    )\n    return [node]",
    "docstring": "Map MXNet's ROIPooling operator attributes to onnx's MaxRoiPool\n    operator and return the created node."
  },
  {
    "code": "def com_google_fonts_check_metadata_nameid_family_and_full_names(ttFont, font_metadata):\n  from fontbakery.utils import get_name_entry_strings\n  font_familynames = get_name_entry_strings(ttFont, NameID.TYPOGRAPHIC_FAMILY_NAME)\n  if font_familynames:\n      font_familyname = font_familynames[0]\n  else:\n      font_familyname = get_name_entry_strings(ttFont, NameID.FONT_FAMILY_NAME)[0]\n  font_fullname = get_name_entry_strings(ttFont, NameID.FULL_FONT_NAME)[0]\n  if font_fullname != font_metadata.full_name:\n    yield FAIL, Message(\"fullname-mismatch\",\n                        (\"METADATA.pb: Fullname (\\\"{}\\\")\"\n                         \" does not match name table\"\n                         \" entry \\\"{}\\\" !\").format(font_metadata.full_name,\n                                                   font_fullname))\n  elif font_familyname != font_metadata.name:\n    yield FAIL, Message(\"familyname-mismatch\",\n                        (\"METADATA.pb Family name \\\"{}\\\")\"\n                         \" does not match name table\"\n                         \" entry \\\"{}\\\" !\").format(font_metadata.name,\n                                                   font_familyname))\n  else:\n    yield PASS, (\"METADATA.pb familyname and fullName fields\"\n                 \" match corresponding name table entries.\")",
    "docstring": "METADATA.pb font.name and font.full_name fields match\n     the values declared on the name table?"
  },
  {
    "code": "def generate_http_basic_token(username, password):\n    token = base64.b64encode('{}:{}'.format(username, password).encode('utf-8')).decode('utf-8')\n    return token",
    "docstring": "Generates a HTTP basic token from username and password\n\n    Returns a token string (not a byte)"
  },
  {
    "code": "def user_id_partition_keygen(request_envelope):\n    try:\n        user_id = request_envelope.context.system.user.user_id\n        return user_id\n    except AttributeError:\n        raise PersistenceException(\"Couldn't retrieve user id from request \"\n                                   \"envelope, for partition key use\")",
    "docstring": "Retrieve user id from request envelope, to use as partition key.\n\n    :param request_envelope: Request Envelope passed during skill\n        invocation\n    :type request_envelope: ask_sdk_model.RequestEnvelope\n    :return: User Id retrieved from request envelope\n    :rtype: str\n    :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`"
  },
  {
    "code": "def list_runners(*args):\n    run_ = salt.runner.Runner(__opts__)\n    runners = set()\n    if not args:\n        for func in run_.functions:\n            runners.add(func.split('.')[0])\n        return sorted(runners)\n    for module in args:\n        if '*' in module:\n            for func in fnmatch.filter(run_.functions, module):\n                runners.add(func.split('.')[0])\n        else:\n            for func in run_.functions:\n                mod_test = func.split('.')[0]\n                if mod_test == module:\n                    runners.add(mod_test)\n    return sorted(runners)",
    "docstring": "List the runners loaded on the minion\n\n    .. versionadded:: 2014.7.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' sys.list_runners\n\n    Runner names can be specified as globs.\n\n    .. versionadded:: 2015.5.0\n\n    .. code-block:: bash\n\n        salt '*' sys.list_runners 'm*'"
  },
  {
    "code": "def listen(timeout=6.0, port=BOOT_PORT):\n    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n    s.bind(('0.0.0.0', port))\n    s.settimeout(timeout)\n    try:\n        message, (ipaddr, port) = s.recvfrom(512)\n        return ipaddr\n    except socket.timeout:\n        return None",
    "docstring": "Listen for a 'ping' broadcast message from an unbooted SpiNNaker board.\n\n    Unbooted SpiNNaker boards send out a UDP broadcast message every 4-ish\n    seconds on port 54321. This function listens for such messages and reports\n    the IP address that it came from.\n\n    Parameters\n    ----------\n    timeout : float\n        Number of seconds to wait for a message to arrive.\n    port : int\n        The port number to listen on.\n\n    Returns\n    -------\n    str or None\n        The IP address of the SpiNNaker board from which a ping was received or\n        None if no ping was observed."
  },
  {
    "code": "def parallel(processes, threads):\n    pool = multithread(threads)\n    pool.map(run_process, processes)\n    pool.close()\n    pool.join()",
    "docstring": "execute jobs in processes using N threads"
  },
  {
    "code": "def ems(self, value: int) -> 'Gap':\n        raise_not_number(value)\n        self.gap = '{}em'.format(value)\n        return self",
    "docstring": "Set the margin in ems."
  },
  {
    "code": "def weld_iloc_indices_with_missing(array, weld_type, indices):\n    weld_obj = create_empty_weld_object()\n    weld_obj_id_array = get_weld_obj_id(weld_obj, array)\n    weld_obj_id_indices = get_weld_obj_id(weld_obj, indices)\n    missing_literal = default_missing_data_literal(weld_type)\n    if weld_type == WeldVec(WeldChar()):\n        missing_literal = get_weld_obj_id(weld_obj, missing_literal)\n    weld_template =\n    weld_obj.weld_code = weld_template.format(array=weld_obj_id_array,\n                                              indices=weld_obj_id_indices,\n                                              type=weld_type,\n                                              missing=missing_literal)\n    return weld_obj",
    "docstring": "Retrieve the values at indices. Indices greater than array length get replaced with\n    a corresponding-type missing value literal.\n\n    Parameters\n    ----------\n    array : numpy.ndarray or WeldObject\n        Input data. Assumed to be bool data.\n    weld_type : WeldType\n        The WeldType of the array data.\n    indices : numpy.ndarray or WeldObject\n        The indices to lookup.\n\n    Returns\n    -------\n    WeldObject\n        Representation of this computation."
  },
  {
    "code": "def reverse(self, points, **kwargs):\n        if isinstance(points, list):\n            return self.batch_reverse(points, **kwargs)\n        if self.order == \"lat\":\n            x, y = points\n        else:\n            y, x = points\n        return self.reverse_point(x, y, **kwargs)",
    "docstring": "General method for reversing addresses, either a single address or\n        multiple.\n\n        *args should either be a longitude/latitude pair or a list of\n        such pairs::\n\n        >>> multiple_locations = reverse([(40, -19), (43, 112)])\n        >>> single_location = reverse((40, -19))"
  },
  {
    "code": "def import_env(*envs):\n    'import environment variables from host'\n    for env in envs:\n        parts = env.split(':', 1)\n        if len(parts) == 1:\n            export_as = env\n        else:\n            env, export_as = parts\n        env_val = os.environ.get(env)\n        if env_val is not None:\n            yield '{}={}'.format(export_as, shlex.quote(env_val))",
    "docstring": "import environment variables from host"
  },
  {
    "code": "def skip(roman_numeral, skip=1):\n    i = numerals.index(roman_numeral) + skip\n    return numerals[i % 7]",
    "docstring": "Skip the given places to the next roman numeral.\n\n    Examples:\n    >>> skip('I')\n    'II'\n    >>> skip('VII')\n    'I'\n    >>> skip('I', 2)\n    'III'"
  },
  {
    "code": "def _construct_from_json(self, rec):\n        self.delete()\n        for required_key in ['dagobah_id', 'created_jobs']:\n            setattr(self, required_key, rec[required_key])\n        for job_json in rec.get('jobs', []):\n            self._add_job_from_spec(job_json)\n        self.commit(cascade=True)",
    "docstring": "Construct this Dagobah instance from a JSON document."
  },
  {
    "code": "def bootstrap(self, mc_bit=0x10, seed=None):\n        if seed is not None: np.random.seed(seed)\n        data = copy.deepcopy(self.data)\n        idx = np.random.randint(0,len(data),len(data))\n        data[self.config['catalog']['mag_1_field']][:] = self.mag_1[idx]\n        data[self.config['catalog']['mag_err_1_field']][:] = self.mag_err_1[idx]\n        data[self.config['catalog']['mag_2_field']][:] = self.mag_2[idx]\n        data[self.config['catalog']['mag_err_2_field']][:] = self.mag_err_2[idx]\n        data[self.config['catalog']['mc_source_id_field']][:] |= mc_bit\n        return Catalog(self.config, data=data)",
    "docstring": "Return a random catalog by boostrapping the colors of the objects in the current catalog."
  },
  {
    "code": "def _keys(expr):\n    if isinstance(expr, SequenceExpr):\n        dtype = expr.data_type\n    else:\n        dtype = expr.value_type\n    return composite_op(expr, DictKeys, df_types.List(dtype.key_type))",
    "docstring": "Retrieve keys of a dict\n\n    :param expr: dict sequence / scalar\n    :return:"
  },
  {
    "code": "def delete_by_id(self, webhook, params={}, **options): \n        path = \"/webhooks/%s\" % (webhook)\n        return self.client.delete(path, params, **options)",
    "docstring": "This method permanently removes a webhook. Note that it may be possible\n        to receive a request that was already in flight after deleting the\n        webhook, but no further requests will be issued.\n\n        Parameters\n        ----------\n        webhook : {Id} The webhook to delete."
  },
  {
    "code": "def as_dot(self) -> str:\n        return nx.drawing.nx_pydot.to_pydot(self._graph).to_string()",
    "docstring": "Return as a string the dot version of the graph."
  },
  {
    "code": "def _extract(self):\n        self.log.debug(\"Extracting emails from text content\")\n        for item in self.data:\n            emails = extract_emails(item, self.domain, self.fuzzy)\n            self.results.extend(emails)\n        self.log.debug(\"Email extraction completed\")\n        return list(set(self.results))",
    "docstring": "Extract email addresses from results.\n\n        Text content from all crawled pages are ran through a simple email\n        extractor. Data is cleaned prior to running pattern expressions."
  },
  {
    "code": "def dfs_back_edges(graph, start_node):\n    visited = set()\n    finished = set()\n    def _dfs_back_edges_core(node):\n        visited.add(node)\n        for child in iter(graph[node]):\n            if child not in finished:\n                if child in  visited:\n                    yield node, child\n                else:\n                    for s,t in _dfs_back_edges_core(child):\n                        yield s,t\n        finished.add(node)\n    for s,t in _dfs_back_edges_core(start_node):\n        yield s,t",
    "docstring": "Do a DFS traversal of the graph, and return with the back edges.\n\n    Note: This is just a naive recursive implementation, feel free to replace it.\n    I couldn't find anything in networkx to do this functionality. Although the\n    name suggest it, but `dfs_labeled_edges` is doing something different.\n\n    :param graph:       The graph to traverse.\n    :param node:        The node where to start the traversal\n    :returns:           An iterator of 'backward' edges"
  },
  {
    "code": "def remove_object(self, bucket_name, object_name):\n        is_valid_bucket_name(bucket_name)\n        is_non_empty_string(object_name)\n        self._url_open('DELETE', bucket_name=bucket_name,\n                       object_name=object_name)",
    "docstring": "Remove an object from the bucket.\n\n        :param bucket_name: Bucket of object to remove\n        :param object_name: Name of object to remove\n        :return: None"
  },
  {
    "code": "def load(self):\n        hdf_filename = os.path.join(self._dump_dirname, 'result.h5')\n        if os.path.isfile(hdf_filename):\n            store = pd.HDFStore(hdf_filename, mode='r')\n            keys = store.keys()\n            if keys == ['/df']:\n                self.result = store['df']\n            else:\n                if set(keys) == set(map(lambda i: '/%s' % i, range(len(keys)))):\n                    self.result = [store[str(k)] for k in range(len(keys))]\n                else:\n                    self.result = {k[1:]: store[k] for k in keys}\n        else:\n            self.result = joblib.load(\n                    os.path.join(self._output_dirname, 'dump', 'result.pkl'))",
    "docstring": "Load this step's result from its dump directory"
  },
  {
    "code": "def save(self, fname):\n        try:\n            with open(fname, \"w\") as f:\n                f.write(str(self))\n        except Exception as ex:\n            print('ERROR = cant save grid results to ' + fname + str(ex))",
    "docstring": "saves a grid to file as ASCII text"
  },
  {
    "code": "def ProcessMessages(self, msgs=None, token=None):\n    if not data_store.AFF4Enabled():\n      return\n    filestore_fd = aff4.FACTORY.Create(\n        legacy_filestore.FileStore.PATH,\n        legacy_filestore.FileStore,\n        mode=\"w\",\n        token=token)\n    for vfs_urn in msgs:\n      with aff4.FACTORY.Open(vfs_urn, mode=\"rw\", token=token) as vfs_fd:\n        try:\n          filestore_fd.AddFile(vfs_fd)\n        except Exception as e:\n          logging.exception(\"Exception while adding file to filestore: %s\", e)",
    "docstring": "Process the new file and add to the file store."
  },
  {
    "code": "def baseglob(pat, base):\n    return [f for f in glob(pat) if f.startswith(base)]",
    "docstring": "Given a pattern and a base, return files that match the glob pattern\n    and also contain the base."
  },
  {
    "code": "def patch_stdout_context(self, raw=False, patch_stdout=True, patch_stderr=True):\n        return _PatchStdoutContext(\n            self.stdout_proxy(raw=raw),\n            patch_stdout=patch_stdout, patch_stderr=patch_stderr)",
    "docstring": "Return a context manager that will replace ``sys.stdout`` with a proxy\n        that makes sure that all printed text will appear above the prompt, and\n        that it doesn't destroy the output from the renderer.\n\n        :param patch_stdout: Replace `sys.stdout`.\n        :param patch_stderr: Replace `sys.stderr`."
  },
  {
    "code": "def _get_redis_server(opts=None):\n    global REDIS_SERVER\n    if REDIS_SERVER:\n        return REDIS_SERVER\n    if not opts:\n        opts = _get_redis_cache_opts()\n    if opts['cluster_mode']:\n        REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'],\n                                          skip_full_coverage_check=opts['skip_full_coverage_check'])\n    else:\n        REDIS_SERVER = redis.StrictRedis(opts['host'],\n                                   opts['port'],\n                                   unix_socket_path=opts['unix_socket_path'],\n                                   db=opts['db'],\n                                   password=opts['password'])\n    return REDIS_SERVER",
    "docstring": "Return the Redis server instance.\n    Caching the object instance."
  },
  {
    "code": "def get_institutes_trend_graph_urls(start, end):\n    graph_list = []\n    for institute in Institute.objects.all():\n        urls = get_institute_trend_graph_url(institute, start, end)\n        urls['institute'] = institute\n        graph_list.append(urls)\n    return graph_list",
    "docstring": "Get all institute trend graphs."
  },
  {
    "code": "def _chance(solution, pdf):\n    return _prod([1.0 - abs(bit - p) for bit, p in zip(solution, pdf)])",
    "docstring": "Return the chance of obtaining a solution from a pdf.\n\n    The probability of many independant weighted \"coin flips\" (one for each bit)"
  },
  {
    "code": "def _get_stddevs(self, C, stddev_types, num_sites):\n        sigma_inter = C['tau'] + np.zeros(num_sites)\n        sigma_intra = C['sigma'] + np.zeros(num_sites)\n        std = []\n        for stddev_type in stddev_types:\n            if stddev_type == const.StdDev.TOTAL:\n                std += [np.sqrt(sigma_intra**2 + sigma_inter**2)]\n            elif stddev_type == const.StdDev.INTRA_EVENT:\n                std.append(sigma_intra)\n            elif stddev_type == const.StdDev.INTER_EVENT:\n                std.append(sigma_inter)\n        return std",
    "docstring": "Return total standard deviation as described in paragraph 5.2 pag 200."
  },
  {
    "code": "def mean_pressure_weighted(pressure, *args, **kwargs):\n    r\n    heights = kwargs.pop('heights', None)\n    bottom = kwargs.pop('bottom', None)\n    depth = kwargs.pop('depth', None)\n    ret = []\n    layer_arg = get_layer(pressure, *args, heights=heights,\n                          bottom=bottom, depth=depth)\n    layer_p = layer_arg[0]\n    layer_arg = layer_arg[1:]\n    pres_int = 0.5 * (layer_p[-1].magnitude**2 - layer_p[0].magnitude**2)\n    for i, datavar in enumerate(args):\n        arg_mean = np.trapz(layer_arg[i] * layer_p, x=layer_p) / pres_int\n        ret.append(arg_mean * datavar.units)\n    return ret",
    "docstring": "r\"\"\"Calculate pressure-weighted mean of an arbitrary variable through a layer.\n\n    Layer top and bottom specified in height or pressure.\n\n    Parameters\n    ----------\n    pressure : `pint.Quantity`\n        Atmospheric pressure profile\n    *args : `pint.Quantity`\n        Parameters for which the pressure-weighted mean is to be calculated.\n    heights : `pint.Quantity`, optional\n        Heights from sounding. Standard atmosphere heights assumed (if needed)\n        if no heights are given.\n    bottom: `pint.Quantity`, optional\n        The bottom of the layer in either the provided height coordinate\n        or in pressure. Don't provide in meters AGL unless the provided\n        height coordinate is meters AGL. Default is the first observation,\n        assumed to be the surface.\n    depth: `pint.Quantity`, optional\n        The depth of the layer in meters or hPa.\n\n    Returns\n    -------\n    `pint.Quantity`\n        u_mean: u-component of layer mean wind.\n    `pint.Quantity`\n        v_mean: v-component of layer mean wind."
  },
  {
    "code": "def settings(**kwargs):\n    from pyemma import config\n    old_settings = {}\n    try:\n        for k, v in kwargs.items():\n            old_settings[k] = getattr(config, k)\n            setattr(config, k, v)\n        yield\n    finally:\n        for k, v in old_settings.items():\n            setattr(config, k, v)",
    "docstring": "apply given PyEMMA config values temporarily within the given context."
  },
  {
    "code": "def register (g):\n    assert isinstance(g, Generator)\n    id = g.id()\n    __generators [id] = g\n    for t in sequence.unique(g.target_types()):\n        __type_to_generators.setdefault(t, []).append(g)\n    base = id.split ('.', 100) [0]\n    __generators_for_toolset.setdefault(base, []).append(g)\n    invalidate_extendable_viable_source_target_type_cache()",
    "docstring": "Registers new generator instance 'g'."
  },
  {
    "code": "def mdaZeros(shap, dtype=numpy.float, mask=None):\n    res = MaskedDistArray(shap, dtype)\n    res[:] = 0\n    res.mask = mask\n    return res",
    "docstring": "Zero constructor for masked distributed array\n    @param shap the shape of the array\n    @param dtype the numpy data type\n    @param mask mask array (or None if all data elements are valid)"
  },
  {
    "code": "def netHours(self):\n        if self.specifiedHours is not None:\n            return self.specifiedHours\n        elif self.category in [getConstant('general__eventStaffCategoryAssistant'),getConstant('general__eventStaffCategoryInstructor')]:\n            return self.event.duration - sum([sub.netHours for sub in self.replacementFor.all()])\n        else:\n            return sum([x.duration for x in self.occurrences.filter(cancelled=False)])",
    "docstring": "For regular event staff, this is the net hours worked for financial purposes.\n        For Instructors, netHours is caclulated net of any substitutes."
  },
  {
    "code": "def We(self):\n        We = trapz_loglog(self._gam * self._nelec, self._gam * mec2)\n        return We",
    "docstring": "Total energy in electrons used for the radiative calculation"
  },
  {
    "code": "def make_pre_build_hook(extra_compiler_config_params):\n    def pre_build_hook(build_context, target):\n        target.compiler_config = CompilerConfig(\n            build_context, target, extra_compiler_config_params)\n        target.props._internal_dict_['compiler_config'] = (\n            target.compiler_config.as_dict())\n    return pre_build_hook",
    "docstring": "Return a pre-build hook function for C++ builders.\n\n    When called, during graph build, it computes and stores the compiler-config\n    object on the target, as well as adding it to the internal_dict prop for\n    hashing purposes."
  },
  {
    "code": "def calculate(self, order, transaction):\n        cost_per_share = transaction.price * self.cost_per_dollar\n        return abs(transaction.amount) * cost_per_share",
    "docstring": "Pay commission based on dollar value of shares."
  },
  {
    "code": "def tuple(self, r):\n        m, n, t = self.args\n        r, k = divmod(r, t)\n        r, u = divmod(r, 2)\n        i, j = divmod(r, n)\n        return i, j, u, k",
    "docstring": "Converts the linear_index `q` into an chimera_index\n\n        Parameters\n        ----------\n        r : int\n            The linear_index node label    \n\n        Returns\n        -------\n        q : tuple\n            The chimera_index node label corresponding to r"
  },
  {
    "code": "def read(self, num_bytes):\n        self.check_pyb()\n        try:\n            return self.pyb.serial.read(num_bytes)\n        except (serial.serialutil.SerialException, TypeError):\n            self.close()\n            raise DeviceError('serial port %s closed' % self.dev_name_short)",
    "docstring": "Reads data from the pyboard over the serial port."
  },
  {
    "code": "def callback(self, timestamp, event_type, payload):\n        try:\n            data = (event_type, payload)\n            LOG.debug('RX NOTIFICATION ==>\\nevent_type: %(event)s, '\n                      'payload: %(payload)s\\n', (\n                          {'event': event_type, 'payload': payload}))\n            if 'create' in event_type:\n                pri = self._create_pri\n            elif 'delete' in event_type:\n                pri = self._delete_pri\n            elif 'update' in event_type:\n                pri = self._update_pri\n            else:\n                pri = self._delete_pri\n            self._pq.put((pri, timestamp, data))\n        except Exception as exc:\n            LOG.exception('Error: %(err)s for event %(event)s',\n                          {'err': str(exc), 'event': event_type})",
    "docstring": "Callback method for processing events in notification queue.\n\n        :param timestamp: time the message is received.\n        :param event_type: event type in the notification queue such as\n                           identity.project.created, identity.project.deleted.\n        :param payload: Contains information of an event"
  },
  {
    "code": "def Pop(self, index=0):\n    if index < 0:\n      index += len(self)\n    if index == 0:\n      result = self.__class__()\n      result.SetRawData(self.GetRawData())\n      self.SetRawData(self.nested_path.GetRawData())\n    else:\n      previous = self[index - 1]\n      result = previous.nested_path\n      previous.nested_path = result.nested_path\n    result.nested_path = None\n    return result",
    "docstring": "Removes and returns the pathspec at the specified index."
  },
  {
    "code": "def writeint2dnorm(filename, Intensity, Error=None):\n    whattosave = {'Intensity': Intensity}\n    if Error is not None:\n        whattosave['Error'] = Error\n    if filename.upper().endswith('.NPZ'):\n        np.savez(filename, **whattosave)\n    elif filename.upper().endswith('.MAT'):\n        scipy.io.savemat(filename, whattosave)\n    else:\n        np.savetxt(filename, Intensity)\n        if Error is not None:\n            name, ext = os.path.splitext(filename)\n            np.savetxt(name + '_error' + ext, Error)",
    "docstring": "Save the intensity and error matrices to a file\n\n    Inputs\n    ------\n    filename: string\n        the name of the file\n    Intensity: np.ndarray\n        the intensity matrix\n    Error: np.ndarray, optional\n        the error matrix (can be ``None``, if no error matrix is to be saved)\n\n    Output\n    ------\n    None"
  },
  {
    "code": "def tokenize_by_number(s):\n    r = find_number(s)\n    if r == None:\n        return [ s ]\n    else:\n        tokens = []\n        if r[0] > 0:\n            tokens.append(s[0:r[0]])\n        tokens.append( float(s[r[0]:r[1]]) )\n        if r[1] < len(s):\n            tokens.extend(tokenize_by_number(s[r[1]:]))\n        return tokens\n    assert False",
    "docstring": "splits a string into a list of tokens\n        each is either a string containing no numbers\n        or a float"
  },
  {
    "code": "def reset(self):\n        \"Close the current failed connection and prepare for a new one\"\n        log.info(\"resetting client\")\n        rpc_client = self._rpc_client\n        self._addrs.append(self._peer.addr)\n        self.__init__(self._addrs)\n        self._rpc_client = rpc_client\n        self._dispatcher.rpc_client = rpc_client\n        rpc_client._client = weakref.ref(self)",
    "docstring": "Close the current failed connection and prepare for a new one"
  },
  {
    "code": "def config_delete(args):\n    r = fapi.delete_workspace_config(args.project, args.workspace,\n                                        args.namespace, args.config)\n    fapi._check_response_code(r, [200,204])\n    return r.text if r.text else None",
    "docstring": "Remove a method config from a workspace"
  },
  {
    "code": "def remove(coll, value):\n    coll_class = coll.__class__\n    return coll_class(x for x in coll if x != value)",
    "docstring": "Remove all the occurrences of a given value\n\n    :param coll: a collection\n    :param value: the value to remove\n    :returns: a list\n\n    >>> data = ('NA', 0, 1, 'NA', 1, 2, 3, 'NA', 5)\n    >>> remove(data, 'NA')\n    (0, 1, 1, 2, 3, 5)"
  },
  {
    "code": "def deactivate(self, node_id):\n        node = self.node_list[node_id]\n        self.node_list[node_id] = node._replace(active=False)",
    "docstring": "Deactivate the node identified by node_id.\n\n        Deactivates the node corresponding to node_id, which means that\n        it can never be the output of a nearest_point query.\n\n        Note:\n            The node is not removed from the tree, its data is steel available.\n\n        Args:\n            node_id (int): The node identifier (given to the user after\n                its insertion)."
  },
  {
    "code": "def __set_document_signals(self):\n        self.document().contentsChanged.connect(self.contents_changed.emit)\n        self.document().contentsChanged.connect(self.__document__contents_changed)\n        self.document().modificationChanged.connect(self.modification_changed.emit)\n        self.document().modificationChanged.connect(self.__document__modification_changed)",
    "docstring": "Connects the editor document signals."
  },
  {
    "code": "def root(reference_labels, estimated_labels):\n    validate(reference_labels, estimated_labels)\n    ref_roots, ref_semitones = encode_many(reference_labels, False)[:2]\n    est_roots = encode_many(estimated_labels, False)[0]\n    comparison_scores = (ref_roots == est_roots).astype(np.float)\n    comparison_scores[np.any(ref_semitones < 0, axis=1)] = -1.0\n    return comparison_scores",
    "docstring": "Compare chords according to roots.\n\n    Examples\n    --------\n    >>> (ref_intervals,\n    ...  ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')\n    >>> (est_intervals,\n    ...  est_labels) = mir_eval.io.load_labeled_intervals('est.lab')\n    >>> est_intervals, est_labels = mir_eval.util.adjust_intervals(\n    ...     est_intervals, est_labels, ref_intervals.min(),\n    ...     ref_intervals.max(), mir_eval.chord.NO_CHORD,\n    ...     mir_eval.chord.NO_CHORD)\n    >>> (intervals,\n    ...  ref_labels,\n    ...  est_labels) = mir_eval.util.merge_labeled_intervals(\n    ...      ref_intervals, ref_labels, est_intervals, est_labels)\n    >>> durations = mir_eval.util.intervals_to_durations(intervals)\n    >>> comparisons = mir_eval.chord.root(ref_labels, est_labels)\n    >>> score = mir_eval.chord.weighted_accuracy(comparisons, durations)\n\n    Parameters\n    ----------\n    reference_labels : list, len=n\n        Reference chord labels to score against.\n    estimated_labels : list, len=n\n        Estimated chord labels to score against.\n\n    Returns\n    -------\n    comparison_scores : np.ndarray, shape=(n,), dtype=float\n        Comparison scores, in [0.0, 1.0], or -1 if the comparison is out of\n        gamut."
  },
  {
    "code": "def is_deletion(self):\n        return (len(self.ref) > len(self.alt)) and self.ref.startswith(self.alt)",
    "docstring": "Does this variant represent the deletion of nucleotides from the\n        reference genome?"
  },
  {
    "code": "def query_by_account(self, account_id, end_time=None, start_time=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"account_id\"] = account_id\r\n        if start_time is not None:\r\n            params[\"start_time\"] = start_time\r\n        if end_time is not None:\r\n            params[\"end_time\"] = end_time\r\n        self.logger.debug(\"GET /api/v1/audit/authentication/accounts/{account_id} with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"GET\", \"/api/v1/audit/authentication/accounts/{account_id}\".format(**path), data=data, params=params, no_data=True)",
    "docstring": "Query by account.\r\n\r\n        List authentication events for a given account."
  },
  {
    "code": "def clear_build_directory(self):\n        stat = os.stat(self.build_directory)\n        shutil.rmtree(self.build_directory)\n        os.makedirs(self.build_directory, stat.st_mode)",
    "docstring": "Clear the build directory where pip unpacks the source distribution archives."
  },
  {
    "code": "def _merge(self, value):\n        if value is not None and not isinstance(value, dict):\n            return value\n        if not self._pairs:\n            return {}\n        collected = {}\n        for k_validator, v_validator in self._pairs:\n            k_default = k_validator.get_default_for(None)\n            if k_default is None:\n                continue\n            if value:\n                v_for_this_k = value.get(k_default)\n            else:\n                v_for_this_k = None\n            v_default = v_validator.get_default_for(v_for_this_k)\n            collected.update({k_default: v_default})\n        if value:\n            for k, v in value.items():\n                if k not in collected:\n                    collected[k] = v\n        return collected",
    "docstring": "Returns a dictionary based on `value` with each value recursively\n        merged with `spec`."
  },
  {
    "code": "def etcd(url=DEFAULT_URL, mock=False, **kwargs):\n    if mock:\n        from etc.adapters.mock import MockAdapter\n        adapter_class = MockAdapter\n    else:\n        from etc.adapters.etcd import EtcdAdapter\n        adapter_class = EtcdAdapter\n    return Client(adapter_class(url, **kwargs))",
    "docstring": "Creates an etcd client."
  },
  {
    "code": "def get_by_name(opname, operators):\n    ret_op_classes = [op for op in operators if op.__name__ == opname]\n    if len(ret_op_classes) == 0:\n        raise TypeError('Cannot found operator {} in operator dictionary'.format(opname))\n    elif len(ret_op_classes) > 1:\n        raise ValueError(\n            'Found duplicate operators {} in operator dictionary. Please check '\n            'your dictionary file.'.format(opname)\n        )\n    ret_op_class = ret_op_classes[0]\n    return ret_op_class",
    "docstring": "Return operator class instance by name.\n\n    Parameters\n    ----------\n    opname: str\n        Name of the sklearn class that belongs to a TPOT operator\n    operators: list\n        List of operator classes from operator library\n\n    Returns\n    -------\n    ret_op_class: class\n        An operator class"
  },
  {
    "code": "def is_iterable(maybe_iter, unless=(string_types, dict)):\n    try:\n        iter(maybe_iter)\n    except TypeError:\n        return False\n    return not isinstance(maybe_iter, unless)",
    "docstring": "Return whether ``maybe_iter`` is an iterable, unless it's an instance of one\n    of the base class, or tuple of base classes, given in ``unless``.\n\n    Example::\n\n        >>> is_iterable('foo')\n        False\n        >>> is_iterable(['foo'])\n        True\n        >>> is_iterable(['foo'], unless=list)\n        False\n        >>> is_iterable(xrange(5))\n        True"
  },
  {
    "code": "def turn_on_nightlight(self):\n        body = helpers.req_body(self.manager, 'devicestatus')\n        body['uuid'] = self.uuid\n        body['mode'] = 'auto'\n        response, _ = helpers.call_api(\n            '/15a/v1/device/nightlightstatus',\n            'put',\n            headers=helpers.req_headers(self.manager),\n            json=body\n        )\n        return helpers.check_response(response, '15a_ntlight')",
    "docstring": "Turn on nightlight"
  },
  {
    "code": "def get_assignable_repository_ids(self, repository_id):\n        mgr = self._get_provider_manager('REPOSITORY', local=True)\n        lookup_session = mgr.get_repository_lookup_session(proxy=self._proxy)\n        repositories = lookup_session.get_repositories()\n        id_list = []\n        for repository in repositories:\n            id_list.append(repository.get_id())\n        return IdList(id_list)",
    "docstring": "Gets a list of repositories including and under the given repository node in which any asset can be assigned.\n\n        arg:    repository_id (osid.id.Id): the ``Id`` of the\n                ``Repository``\n        return: (osid.id.IdList) - list of assignable repository ``Ids``\n        raise:  NullArgument - ``repository_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def _populate_comptparms(self, img_array):\n        if img_array.dtype == np.uint8:\n            comp_prec = 8\n        else:\n            comp_prec = 16\n        numrows, numcols, num_comps = img_array.shape\n        if version.openjpeg_version_tuple[0] == 1:\n            comptparms = (opj.ImageComptParmType * num_comps)()\n        else:\n            comptparms = (opj2.ImageComptParmType * num_comps)()\n        for j in range(num_comps):\n            comptparms[j].dx = self._cparams.subsampling_dx\n            comptparms[j].dy = self._cparams.subsampling_dy\n            comptparms[j].w = numcols\n            comptparms[j].h = numrows\n            comptparms[j].x0 = self._cparams.image_offset_x0\n            comptparms[j].y0 = self._cparams.image_offset_y0\n            comptparms[j].prec = comp_prec\n            comptparms[j].bpp = comp_prec\n            comptparms[j].sgnd = 0\n        self._comptparms = comptparms",
    "docstring": "Instantiate and populate comptparms structure.\n\n        This structure defines the image components.\n\n        Parameters\n        ----------\n        img_array : ndarray\n            Image data to be written to file."
  },
  {
    "code": "def _parse_xml(self, xml):\n        vms(\"Parsing <static> XML child tag.\", 2)\n        for child in xml:\n            if \"path\" in child.attrib and \"target\" in child.attrib:\n                if child.tag == \"file\":\n                    self.files.append({\"source\": child.attrib[\"path\"],\n                                       \"target\": child.attrib[\"target\"]})\n                elif child.tag == \"folder\":\n                    self.folders.append({\"source\": child.attrib[\"path\"],\n                                         \"target\": child.attrib[\"target\"]})",
    "docstring": "Extracts objects representing and interacting with the settings in the\n        xml tag."
  },
  {
    "code": "def execute_scenario(scenario):\n    for action in scenario.sequence:\n        execute_subcommand(scenario.config, action)\n    if 'destroy' in scenario.sequence:\n        scenario.prune()",
    "docstring": "Execute each command in the given scenario's configured sequence.\n\n    :param scenario: The scenario to execute.\n    :returns: None"
  },
  {
    "code": "def pick_tile_size(self, seg_size, data_lengths, valid_chunks, valid_lengths):\n        if len(valid_lengths) == 1:\n            return data_lengths[0], valid_chunks[0], valid_lengths[0]\n        else:\n            target_size = seg_size / 3\n            pick, pick_diff = 0, abs(valid_lengths[0] - target_size)\n            for i, size in enumerate(valid_lengths):\n                if abs(size - target_size) < pick_diff:\n                    pick, pick_diff  = i, abs(size - target_size)\n            return data_lengths[pick], valid_chunks[pick], valid_lengths[pick]",
    "docstring": "Choose job tiles size based on science segment length"
  },
  {
    "code": "def is_refreshable_url(self, request):\n        backend_session = request.session.get(BACKEND_SESSION_KEY)\n        is_oidc_enabled = True\n        if backend_session:\n            auth_backend = import_string(backend_session)\n            is_oidc_enabled = issubclass(auth_backend, OIDCAuthenticationBackend)\n        return (\n            request.method == 'GET' and\n            is_authenticated(request.user) and\n            is_oidc_enabled and\n            request.path not in self.exempt_urls\n        )",
    "docstring": "Takes a request and returns whether it triggers a refresh examination\n\n        :arg HttpRequest request:\n\n        :returns: boolean"
  },
  {
    "code": "def broadcast(self, channel, event, data):\n        payload = self._server.serialize_event(event, data)\n        for socket_id in self.subscriptions.get(channel, ()):\n            rv = self._server.sockets.get(socket_id)\n            if rv is not None:\n                rv.socket.send(payload)",
    "docstring": "Broadcasts an event to all sockets listening on a channel."
  },
  {
    "code": "def configure(cls, **kwargs):\n        attrs = {}\n        for key in ('prefix', 'handle_uniqueness', 'key'):\n            if key in kwargs:\n                attrs[key] = kwargs.pop(key)\n        if 'transform' in kwargs:\n            attrs['transform'] = staticmethod(kwargs.pop('transform'))\n        name = kwargs.pop('name', None)\n        if kwargs:\n            raise TypeError('%s.configure only accepts these named arguments: %s' % (\n                cls.__name__,\n                ', '.join(('prefix', 'transform', 'handle_uniqueness', 'key', 'name')),\n            ))\n        return type((str if PY3 else oldstr)(name or cls.__name__), (cls, ), attrs)",
    "docstring": "Create a new index class with the given info\n\n        This allow to avoid creating a new class when only few changes are\n        to be made\n\n        Parameters\n        ----------\n        kwargs: dict\n            prefix: str\n                The string part to use in the collection, before the normal suffix.\n                For example `foo` to filter on `myfiled__foo__eq=`\n                This prefix will also be used by the indexes to store the data at\n                a different place than the same index without prefix.\n            transform: callable\n                A function that will transform the value to be used as the reference\n                for the index, before the call to `normalize_value`.\n                If can be extraction of a date, or any computation.\n                The filter in the collection will then have to use a transformed value,\n                for example `birth_date__year=1976` if the transform take a date and\n                transform it to a year.\n            handle_uniqueness: bool\n                To make the index handle or not the uniqueness\n            key: str\n                To override the key used by the index. Two indexes for the same field of\n                the same type must not have the same key or data will be saved at the same place.\n                Note that the default key is None for `EqualIndex`, `text-range` for\n                `TextRangeIndex` and `number-range` for `NumberRangeIndex`\n            name: str\n                The name of the new multi-index class. If not set, it will be the same\n                as the current class\n\n        Returns\n        -------\n        type\n            A new class based on `cls`, with the new attributes set"
  },
  {
    "code": "def _forbidden(self, path, value):\n    if path[0] == '/':\n      path = path[1:]\n    for rule in reversed(self.rules):\n      if isinstance(rule[1], six.string_types):\n        if fnmatch(path, rule[1]):\n          return not rule[0]\n      elif rule[1](path, value):\n        return not rule[0]\n    return True",
    "docstring": "Is a stat forbidden? Goes through the rules to find one that\n    applies. Chronologically newer rules are higher-precedence than\n    older ones. If no rule applies, the stat is forbidden by default."
  },
  {
    "code": "def parse_attribute_map(filenames):\n    forward = {}\n    backward = {}\n    for filename in filenames:\n        with open(filename) as fp:\n            for line in fp:\n                (name, friendly_name, name_format) = line.strip().split()\n                forward[(name, name_format)] = friendly_name\n                backward[friendly_name] = (name, name_format)\n    return forward, backward",
    "docstring": "Expects a file with each line being composed of the oid for the attribute\n    exactly one space, a user friendly name of the attribute and then\n    the type specification of the name.\n\n    :param filenames: List of filenames on mapfiles.\n    :return: A 2-tuple, one dictionary with the oid as keys and the friendly\n        names as values, the other one the other way around."
  },
  {
    "code": "def matches(self, query):\n        thread_query = 'thread:{tid} AND {subquery}'.format(tid=self._id,\n                                                            subquery=query)\n        num_matches = self._dbman.count_messages(thread_query)\n        return num_matches > 0",
    "docstring": "Check if this thread matches the given notmuch query.\n\n        :param query: The query to check against\n        :type query: string\n        :returns: True if this thread matches the given query, False otherwise\n        :rtype: bool"
  },
  {
    "code": "def setup(app):\n    import sphinxcontrib_django.docstrings\n    import sphinxcontrib_django.roles\n    sphinxcontrib_django.docstrings.setup(app)\n    sphinxcontrib_django.roles.setup(app)",
    "docstring": "Allow this module to be used as sphinx extension.\n    This attaches the Sphinx hooks.\n\n    :type app: sphinx.application.Sphinx"
  },
  {
    "code": "def from_dict(cls, dictionary):\n        cookbooks = set()\n        sources = set()\n        other = set()\n        groups = [sources, cookbooks, other]\n        for key, val in dictionary.items():\n            if key == 'cookbook':\n                cookbooks.update({cls.cookbook_statement(cbn, meta)\n                                  for cbn, meta in val.items()})\n            elif key == 'source':\n                sources.update({\"source '%s'\" % src for src in val})\n            elif key == 'metadata':\n                other.add('metadata')\n        body = ''\n        for group in groups:\n            if group:\n                body += '\\n'\n            body += '\\n'.join(group)\n        return cls.from_string(body)",
    "docstring": "Create a Berksfile instance from a dict."
  },
  {
    "code": "def many(self):\n        for i in self.tc_requests.many(self.api_type, None, self.api_entity):\n            yield i",
    "docstring": "Gets all of the owners available.\n\n        Args:"
  },
  {
    "code": "def create_mixin(self):\n        _builder = self\n        class CustomModelMixin(object):\n            @cached_property\n            def _content_type(self):\n                return ContentType.objects.get_for_model(self)\n            @classmethod\n            def get_model_custom_fields(cls):\n                return _builder.fields_model_class.objects.filter(content_type=ContentType.objects.get_for_model(cls))\n            def get_custom_fields(self):\n                return _builder.fields_model_class.objects.filter(content_type=self._content_type)\n            def get_custom_value(self, field):\n                return _builder.values_model_class.objects.get(custom_field=field,\n                                                               content_type=self._content_type,\n                                                               object_id=self.pk)\n            def set_custom_value(self, field, value):\n                custom_value, created = \\\n                    _builder.values_model_class.objects.get_or_create(custom_field=field,\n                                                                      content_type=self._content_type,\n                                                                      object_id=self.pk)\n                custom_value.value = value\n                custom_value.full_clean()\n                custom_value.save()\n                return custom_value\n        return CustomModelMixin",
    "docstring": "This will create the custom Model Mixin to attach to your custom field\n        enabled model.\n\n        :return:"
  },
  {
    "code": "def undobutton_action(self):\n        if len(self.history) > 1:\n            old = self.history.pop(-1)\n            self.selection_array = old\n            self.mask.set_data(old)\n            self.fig.canvas.draw_idle()",
    "docstring": "when undo is clicked, revert the thematic map to the previous state"
  },
  {
    "code": "def create(cls, repo, path, ref='HEAD', message=None, force=False, **kwargs):\n        args = (path, ref)\n        if message:\n            kwargs['m'] = message\n        if force:\n            kwargs['f'] = True\n        repo.git.tag(*args, **kwargs)\n        return TagReference(repo, \"%s/%s\" % (cls._common_path_default, path))",
    "docstring": "Create a new tag reference.\n\n        :param path:\n            The name of the tag, i.e. 1.0 or releases/1.0.\n            The prefix refs/tags is implied\n\n        :param ref:\n            A reference to the object you want to tag. It can be a commit, tree or\n            blob.\n\n        :param message:\n            If not None, the message will be used in your tag object. This will also\n            create an additional tag object that allows to obtain that information, i.e.::\n\n                tagref.tag.message\n\n        :param force:\n            If True, to force creation of a tag even though that tag already exists.\n\n        :param kwargs:\n            Additional keyword arguments to be passed to git-tag\n\n        :return: A new TagReference"
  },
  {
    "code": "def from_filename(self, filename):\n        i = len(self.base_directory)\n        if filename[:i] != self.base_directory:\n            raise ValueError('Filename needs to start with \"%s\";\\nyou passed \"%s\".' % (self.base_directory, filename))\n        if filename.endswith(self.extension):\n            if len(self.extension) > 0:\n                j = -len(self.extension)\n            else:\n                j = None\n            return self.key_transformer.from_path(tuple(filename[i:j].strip('/').split('/')))",
    "docstring": "Convert an absolute filename into key."
  },
  {
    "code": "def configure(self, options, conf):\n        super(LeakDetectorPlugin, self).configure(options, conf)\n        if options.leak_detector_level:\n            self.reporting_level = int(options.leak_detector_level)\n        self.report_delta = options.leak_detector_report_delta\n        self.patch_mock = options.leak_detector_patch_mock\n        self.ignore_patterns = options.leak_detector_ignore_patterns\n        self.save_traceback = options.leak_detector_save_traceback\n        self.multiprocessing_enabled = bool(getattr(options, 'multiprocess_workers', False))",
    "docstring": "Configure plugin."
  },
  {
    "code": "def get_submit_args(args):\n    submit_args = dict(\n        testrun_id=args.testrun_id,\n        user=args.user,\n        password=args.password,\n        no_verify=args.no_verify,\n        verify_timeout=args.verify_timeout,\n        log_file=args.job_log,\n        dry_run=args.dry_run,\n    )\n    submit_args = {k: v for k, v in submit_args.items() if v is not None}\n    return Box(submit_args, frozen_box=True, default_box=True)",
    "docstring": "Gets arguments for the `submit_and_verify` method."
  },
  {
    "code": "def serialize_job(job):\n    d = dict(\n        id=job.get_id(),\n        uri=url_for('jobs.get_job', job_id=job.get_id(), _external=True),\n        status=job.get_status(),\n        result=job.result\n    )\n    return d",
    "docstring": "Return a dictionary representing the job."
  },
  {
    "code": "def _process_terminal_state(self, job_record):\n        msg = 'Job {0} for {1}@{2} is in the terminal state {3}, ' \\\n              'and is no further govern by the State Machine {4}' \\\n              .format(job_record.db_id, job_record.process_name, job_record.timeperiod, job_record.state, self.name)\n        self._log_message(WARNING, job_record.process_name, job_record.timeperiod, msg)",
    "docstring": "method logs a warning message notifying that the job is no longer govern by this state machine"
  },
  {
    "code": "def _startup(cls):\n        for endpoint_name in sorted(hookenv.relation_types()):\n            relf = relation_factory(endpoint_name)\n            if not relf or not issubclass(relf, cls):\n                continue\n            rids = sorted(hookenv.relation_ids(endpoint_name))\n            rids = ['{}:{}'.format(endpoint_name, rid) if ':' not in rid\n                    else rid for rid in rids]\n            endpoint = relf(endpoint_name, rids)\n            cls._endpoints[endpoint_name] = endpoint\n            endpoint.register_triggers()\n            endpoint._manage_departed()\n            endpoint._manage_flags()\n            for relation in endpoint.relations:\n                hookenv.atexit(relation._flush_data)",
    "docstring": "Create Endpoint instances and manage automatic flags."
  },
  {
    "code": "def get_storage(path=None, options=None):\n    path = path or settings.STORAGE\n    options = options or settings.STORAGE_OPTIONS\n    if not path:\n        raise ImproperlyConfigured('You must specify a storage class using '\n                                   'DBBACKUP_STORAGE settings.')\n    return Storage(path, **options)",
    "docstring": "Get the specified storage configured with options.\n\n    :param path: Path in Python dot style to module containing the storage\n                 class. If empty settings.DBBACKUP_STORAGE will be used.\n    :type path: ``str``\n\n    :param options: Parameters for configure the storage, if empty\n                    settings.DBBACKUP_STORAGE_OPTIONS will be used.\n    :type options: ``dict``\n\n    :return: Storage configured\n    :rtype: :class:`.Storage`"
  },
  {
    "code": "def _reset(self):\n        self._in_declare = False\n        self._is_create = False\n        self._begin_depth = 0\n        self.consume_ws = False\n        self.tokens = []\n        self.level = 0",
    "docstring": "Set the filter attributes to its default values"
  },
  {
    "code": "def validate(self):\n        for key, val in self.grammar.items():\n            try:\n                setattr(self, key, val)\n            except ValueError as e:\n                raise ValidationError('invalid contents: ' + e.args[0])",
    "docstring": "Validate the contents of the object.\n\n        This calls ``setattr`` for each of the class's grammar properties. It\n        will catch ``ValueError``s raised by the grammar property's setters\n        and re-raise them as :class:`ValidationError`."
  },
  {
    "code": "def get_assessment_part_items(self, assessment_part_id):\n        mgr = self._get_provider_manager('ASSESSMENT_AUTHORING', local=True)\n        lookup_session = mgr.get_assessment_part_lookup_session(proxy=self._proxy)\n        if self._catalog_view == ISOLATED:\n            lookup_session.use_isolated_bank_view()\n        else:\n            lookup_session.use_federated_bank_view()\n        item_ids = lookup_session.get_assessment_part(assessment_part_id).get_item_ids()\n        mgr = self._get_provider_manager('ASSESSMENT')\n        lookup_session = mgr.get_item_lookup_session(proxy=self._proxy)\n        lookup_session.use_federated_bank_view()\n        return lookup_session.get_items_by_ids(item_ids)",
    "docstring": "Gets the list of items mapped to the given ``AssessmentPart``.\n\n        In plenary mode, the returned list contains all known items or\n        an error results. Otherwise, the returned list may contain only\n        those items that are accessible through this session.\n\n        arg:    assessment_part_id (osid.id.Id): ``Id`` of the\n                ``AssessmentPart``\n        return: (osid.assessment.ItemList) - list of items\n        raise:  NotFound - ``assessment_part_id`` not found\n        raise:  NullArgument - ``assessment_part_id`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method is must be implemented.*"
  },
  {
    "code": "def main(args=None):\n    parser = argparse.ArgumentParser(\n        description='Extracts metadata from a Fuel-converted HDF5 file.')\n    parser.add_argument(\"filename\", help=\"HDF5 file to analyze\")\n    args = parser.parse_args()\n    with h5py.File(args.filename, 'r') as h5file:\n        interface_version = h5file.attrs.get('h5py_interface_version', 'N/A')\n        fuel_convert_version = h5file.attrs.get('fuel_convert_version', 'N/A')\n        fuel_convert_command = h5file.attrs.get('fuel_convert_command', 'N/A')\n    message_prefix = message_prefix_template.format(\n        os.path.basename(args.filename))\n    message_body = message_body_template.format(\n        fuel_convert_command, interface_version, fuel_convert_version)\n    message = ''.join(['\\n', message_prefix, '\\n', '=' * len(message_prefix),\n                       message_body])\n    print(message)",
    "docstring": "Entry point for `fuel-info` script.\n\n    This function can also be imported and used from Python.\n\n    Parameters\n    ----------\n    args : iterable, optional (default: None)\n        A list of arguments that will be passed to Fuel's information\n        utility. If this argument is not specified, `sys.argv[1:]` will\n        be used."
  },
  {
    "code": "def deepcopy_strip(item):\n    if isinstance(item, MutableMapping):\n        return {k: deepcopy_strip(v) for k, v in iteritems(item)}\n    if isinstance(item, MutableSequence):\n        return [deepcopy_strip(k) for k in item]\n    return item",
    "docstring": "Make a deep copy of list and dict objects.\n\n    Intentionally do not copy attributes.  This is to discard CommentedMap and\n    CommentedSeq metadata which is very expensive with regular copy.deepcopy."
  },
  {
    "code": "def predict(self, data):\n        with log_start_finish('_FakeRegressionResults prediction', logger):\n            model_design = dmatrix(\n                self._rhs, data=data, return_type='dataframe')\n            return model_design.dot(self.params).values",
    "docstring": "Predict new values by running data through the fit model.\n\n        Parameters\n        ----------\n        data : pandas.DataFrame\n            Table with columns corresponding to the RHS of `model_expression`.\n\n        Returns\n        -------\n        predicted : ndarray\n            Array of predicted values."
  },
  {
    "code": "def generate_dict_schema(size, valid):\n    schema = {}\n    generator_items = []\n    for i in range(0, size):\n        while True:\n            key_schema,   key_generator   = generate_random_schema(valid)\n            if key_schema not in schema:\n                break\n        value_schema, value_generator = generate_random_schema(valid)\n        schema[key_schema] = value_schema\n        generator_items.append((key_generator, value_generator))\n    generator = ({next(k_gen): next(v_gen) for k_gen, v_gen in generator_items} for i in itertools.count())\n    return schema, generator",
    "docstring": "Generate a schema dict of size `size` using library `lib`.\n\n    In addition, it returns samples generator\n\n    :param size: Schema size\n    :type size: int\n    :param samples: The number of samples to generate\n    :type samples: int\n    :param valid: Generate valid samples?\n    :type valid: bool\n    :returns"
  },
  {
    "code": "def get_mapping(version=1, exported_at=None, app_name=None):\n    if exported_at is None:\n        exported_at = timezone.now()\n    app_name = app_name or settings.HEROKU_CONNECT_APP_NAME\n    return {\n        'version': version,\n        'connection': {\n            'organization_id': settings.HEROKU_CONNECT_ORGANIZATION_ID,\n            'app_name': app_name,\n            'exported_at': exported_at.isoformat(),\n        },\n        'mappings': [\n            model.get_heroku_connect_mapping()\n            for model in get_heroku_connect_models()\n        ]\n    }",
    "docstring": "Return Heroku Connect mapping for the entire project.\n\n    Args:\n        version (int): Version of the Heroku Connect mapping, default: ``1``.\n        exported_at (datetime.datetime): Time the export was created, default is ``now()``.\n        app_name (str): Name of Heroku application associated with Heroku Connect the add-on.\n\n    Returns:\n        dict: Heroku Connect mapping.\n\n    Note:\n        The version does not need to be incremented. Exports from the Heroku Connect\n        website will always have the version number ``1``."
  },
  {
    "code": "def aggregate(self, other=None):\n        if not self.status:\n            return self\n        if not other:\n            return self\n        if not other.status:\n            return other\n        return Value(True, other.index, self.value + other.value, None)",
    "docstring": "collect the furthest failure from self and other."
  },
  {
    "code": "def require_Gtk(min_version=2):\n    if not _in_X:\n        raise RuntimeError('Not in X session.')\n    if _has_Gtk < min_version:\n        raise RuntimeError('Module gi.repository.Gtk not available!')\n    if _has_Gtk == 2:\n        logging.getLogger(__name__).warn(\n            _(\"Missing runtime dependency GTK 3. Falling back to GTK 2 \"\n              \"for password prompt\"))\n    from gi.repository import Gtk\n    if not Gtk.init_check(None)[0]:\n        raise RuntimeError(_(\"X server not connected!\"))\n    return Gtk",
    "docstring": "Make sure Gtk is properly initialized.\n\n    :raises RuntimeError: if Gtk can not be properly initialized"
  },
  {
    "code": "def create(self, *args, **kwargs):\n        try:\n            return super(CloudBlockStorageManager, self).create(*args,\n                    **kwargs)\n        except exc.BadRequest as e:\n            msg = e.message\n            if \"Clones currently must be >= original volume size\" in msg:\n                raise exc.VolumeCloneTooSmall(msg)\n            else:\n                raise",
    "docstring": "Catches errors that may be returned, and raises more informational\n        exceptions."
  },
  {
    "code": "def initialize(log_file, project_dir=None, debug=False):\n    print_splash()\n    log.setup_logging(log_file, print_log_location=False, debug=debug)\n    logger = log.get_logger('pipeline')\n    if project_dir is not None:\n        make_dir(os.path.normpath(project_dir))\n        logger.info('PROJECT DIRECTORY: {}'.format(project_dir))\n        logger.info('')\n    logger.info('LOG LOCATION: {}'.format(log_file))\n    print('')\n    return logger",
    "docstring": "Initializes an AbTools pipeline.\n\n    Initialization includes printing the AbTools splash, setting up logging,\n    creating the project directory, and logging both the project directory\n    and the log location.\n\n    Args:\n\n        log_file (str): Path to the log file. Required.\n\n        project_dir (str): Path to the project directory. If not provided,\n            the project directory won't be created and the location won't be logged.\n\n        debug (bool): If ``True``, the logging level will be set to ``logging.DEBUG``.\n            Default is ``FALSE``, which logs at ``logging.INFO``.\n\n    Returns:\n\n        logger"
  },
  {
    "code": "def get_status(self, instance):\n        status_key, status = self._get_status(instance)\n        if status['state'] in ['complete', 'error']:\n            cache.delete(status_key)\n        return status",
    "docstring": "Retrives a status of a field from cache. Fields in state 'error' and\n        'complete' will not retain the status after the call."
  },
  {
    "code": "def get_timestamp_expression(self, time_grain):\n        label = utils.DTTM_ALIAS\n        db = self.table.database\n        pdf = self.python_date_format\n        is_epoch = pdf in ('epoch_s', 'epoch_ms')\n        if not self.expression and not time_grain and not is_epoch:\n            sqla_col = column(self.column_name, type_=DateTime)\n            return self.table.make_sqla_column_compatible(sqla_col, label)\n        grain = None\n        if time_grain:\n            grain = db.grains_dict().get(time_grain)\n            if not grain:\n                raise NotImplementedError(\n                    f'No grain spec for {time_grain} for database {db.database_name}')\n        col = db.db_engine_spec.get_timestamp_column(self.expression, self.column_name)\n        expr = db.db_engine_spec.get_time_expr(col, pdf, time_grain, grain)\n        sqla_col = literal_column(expr, type_=DateTime)\n        return self.table.make_sqla_column_compatible(sqla_col, label)",
    "docstring": "Getting the time component of the query"
  },
  {
    "code": "def expire_hit(self, hit_id):\n        try:\n            self.mturk.update_expiration_for_hit(HITId=hit_id, ExpireAt=0)\n        except Exception as ex:\n            raise MTurkServiceException(\n                \"Failed to expire HIT {}: {}\".format(hit_id, str(ex))\n            )\n        return True",
    "docstring": "Expire a HIT, which will change its status to \"Reviewable\",\n        allowing it to be deleted."
  },
  {
    "code": "def plot(self, plot_grouped=False):\n        cumulative_detections(\n            detections=self.detections, plot_grouped=plot_grouped)",
    "docstring": "Plot the cumulative number of detections in time.\n\n        .. rubric:: Example\n\n        >>> family = Family(\n        ...     template=Template(name='a'), detections=[\n        ...     Detection(template_name='a', detect_time=UTCDateTime(0) + 200,\n        ...               no_chans=8, detect_val=4.2, threshold=1.2,\n        ...               typeofdet='corr', threshold_type='MAD',\n        ...               threshold_input=8.0),\n        ...     Detection(template_name='a', detect_time=UTCDateTime(0),\n        ...               no_chans=8, detect_val=4.5, threshold=1.2,\n        ...               typeofdet='corr', threshold_type='MAD',\n        ...               threshold_input=8.0),\n        ...     Detection(template_name='a', detect_time=UTCDateTime(0) + 10,\n        ...               no_chans=8, detect_val=4.5, threshold=1.2,\n        ...               typeofdet='corr', threshold_type='MAD',\n        ...               threshold_input=8.0)])\n        >>> family.plot(plot_grouped=True)  # doctest: +SKIP\n\n        .. plot::\n\n            from eqcorrscan.core.match_filter import Family, Template\n            from eqcorrscan.core.match_filter import Detection\n            from obspy import UTCDateTime\n            family = Family(\n                template=Template(name='a'), detections=[\n                Detection(template_name='a', detect_time=UTCDateTime(0) + 200,\n                          no_chans=8, detect_val=4.2, threshold=1.2,\n                          typeofdet='corr', threshold_type='MAD',\n                          threshold_input=8.0),\n                Detection(template_name='a', detect_time=UTCDateTime(0),\n                          no_chans=8, detect_val=4.5, threshold=1.2,\n                          typeofdet='corr', threshold_type='MAD',\n                          threshold_input=8.0),\n                Detection(template_name='a', detect_time=UTCDateTime(0) + 10,\n                          no_chans=8, detect_val=4.5, threshold=1.2,\n                          typeofdet='corr', threshold_type='MAD',\n                          threshold_input=8.0)])\n            family.plot(plot_grouped=True)"
  },
  {
    "code": "def dist_sq(self, other=None):\n        v = self - other if other else self\n        return sum(map(lambda a: a * a, v))",
    "docstring": "For fast length comparison"
  },
  {
    "code": "def _add_ce_record(self, curr_dr_len, thislen):\n        if self.dr_entries.ce_record is None:\n            self.dr_entries.ce_record = RRCERecord()\n            self.dr_entries.ce_record.new()\n            curr_dr_len += RRCERecord.length()\n        self.dr_entries.ce_record.add_record(thislen)\n        return curr_dr_len",
    "docstring": "An internal method to add a new length to a Continuation Entry.  If the\n        Continuation Entry does not yet exist, this method creates it.\n\n        Parameters:\n         curr_dr_len - The current Directory Record length.\n         thislen - The new length to add to the Continuation Entry.\n        Returns:\n         An integer representing the current directory record length after\n         adding the Continuation Entry."
  },
  {
    "code": "def _find_image_id(self, image_id):\n        if not self._images:\n            connection = self._connect()\n            self._images = connection.get_all_images()\n        image_id_cloud = None\n        for i in self._images:\n            if i.id == image_id or i.name == image_id:\n                image_id_cloud = i.id\n                break\n        if image_id_cloud:\n            return image_id_cloud\n        else:\n            raise ImageError(\n                \"Could not find given image id `%s`\" % image_id)",
    "docstring": "Finds an image id to a given id or name.\n\n        :param str image_id: name or id of image\n        :return: str - identifier of image"
  },
  {
    "code": "def new_from_url(cls, url, verify=True):\n        response = requests.get(url, verify=verify, timeout=2.5)\n        return cls.new_from_response(response)",
    "docstring": "Constructs a new WebPage object for the URL,\n        using the `requests` module to fetch the HTML.\n\n        Parameters\n        ----------\n\n        url : str\n        verify: bool"
  },
  {
    "code": "def set_margins(self, top=None, bottom=None):\n        if (top is None or top == 0) and bottom is None:\n            self.margins = None\n            return\n        margins = self.margins or Margins(0, self.lines - 1)\n        if top is None:\n            top = margins.top\n        else:\n            top = max(0, min(top - 1, self.lines - 1))\n        if bottom is None:\n            bottom = margins.bottom\n        else:\n            bottom = max(0, min(bottom - 1, self.lines - 1))\n        if bottom - top >= 1:\n            self.margins = Margins(top, bottom)\n            self.cursor_position()",
    "docstring": "Select top and bottom margins for the scrolling region.\n\n        :param int top: the smallest line number that is scrolled.\n        :param int bottom: the biggest line number that is scrolled."
  },
  {
    "code": "def _AbortJoin(self, timeout=None):\n    for pid, process in iter(self._processes_per_pid.items()):\n      logger.debug('Waiting for process: {0:s} (PID: {1:d}).'.format(\n          process.name, pid))\n      process.join(timeout=timeout)\n      if not process.is_alive():\n        logger.debug('Process {0:s} (PID: {1:d}) stopped.'.format(\n            process.name, pid))",
    "docstring": "Aborts all registered processes by joining with the parent process.\n\n    Args:\n      timeout (int): number of seconds to wait for processes to join, where\n          None represents no timeout."
  },
  {
    "code": "def _clone(self):\n        cloned_self = self.__class__(\n            *self.flat_path, project=self.project, namespace=self.namespace\n        )\n        cloned_self._parent = self._parent\n        return cloned_self",
    "docstring": "Duplicates the Key.\n\n        Most attributes are simple types, so don't require copying. Other\n        attributes like ``parent`` are long-lived and so we re-use them.\n\n        :rtype: :class:`google.cloud.datastore.key.Key`\n        :returns: A new ``Key`` instance with the same data as the current one."
  },
  {
    "code": "def set_ownership(self):\n        assert self.section is not None\n        for t in self.children:\n            t.parent = self\n            t._section = self.section\n            t.doc = self.doc\n            t.set_ownership()",
    "docstring": "Recursivelt set the parent, section and doc for a children"
  },
  {
    "code": "def get_version_info():\n    from astropy import __version__\n    astropy_version = __version__\n    from photutils import __version__\n    photutils_version = __version__\n    return 'astropy: {0}, photutils: {1}'.format(astropy_version,\n                                                 photutils_version)",
    "docstring": "Return astropy and photutils versions.\n\n    Returns\n    -------\n    result : str\n        The astropy and photutils versions."
  },
  {
    "code": "def is_rotation(self, other):\n        if len(self) != len(other):\n            return False\n        for i in range(len(self)):\n            if self.rotate(i) == other:\n                return True\n        return False",
    "docstring": "Determine whether two sequences are the same, just at different\n        rotations.\n\n        :param other: The sequence to check for rotational equality.\n        :type other: coral.sequence._sequence.Sequence"
  },
  {
    "code": "def evaluate_binop_comparison(self, operation, left, right, **kwargs):\n        if not operation in self.binops_comparison:\n            raise ValueError(\"Invalid comparison binary operation '{}'\".format(operation))\n        if left is None or right is None:\n            return None\n        if not isinstance(left, (list, ListIP)):\n            left = [left]\n        if not isinstance(right, (list, ListIP)):\n            right = [right]\n        if not left or not right:\n            return None\n        if operation in ['OP_IS']:\n            res = self.binops_comparison[operation](left, right)\n            if res:\n                return True\n        elif operation in ['OP_IN']:\n            for iteml in left:\n                res = self.binops_comparison[operation](iteml, right)\n                if res:\n                    return True\n        else:\n            for iteml in left:\n                if iteml is None:\n                    continue\n                for itemr in right:\n                    if itemr is None:\n                        continue\n                    res = self.binops_comparison[operation](iteml, itemr)\n                    if res:\n                        return True\n        return False",
    "docstring": "Evaluate given comparison binary operation with given operands."
  },
  {
    "code": "def is_locked(self, key):\n        check_not_none(key, \"key can't be None\")\n        key_data = self._to_data(key)\n        return self._encode_invoke_on_key(map_is_locked_codec, key_data, key=key_data)",
    "docstring": "Checks the lock for the specified key. If the lock is acquired, it returns ``true``. Otherwise, it returns ``false``.\n\n        **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations\n        of __hash__ and __eq__ defined in key's class.**\n\n        :param key: (object), the key that is checked for lock\n        :return: (bool), ``true`` if lock is acquired, ``false`` otherwise."
  },
  {
    "code": "def _read_config(self):\n        try:\n            self.config = self.componentmodel.find_one(\n                {'name': self.uniquename})\n        except ServerSelectionTimeoutError:\n            self.log(\"No database access! Check if mongodb is running \"\n                     \"correctly.\", lvl=critical)\n        if self.config:\n            self.log(\"Configuration read.\", lvl=verbose)\n        else:\n            self.log(\"No configuration found.\", lvl=warn)",
    "docstring": "Read this component's configuration from the database"
  },
  {
    "code": "def repr2_json(obj_, **kwargs):\n    import utool as ut\n    kwargs['trailing_sep'] = False\n    json_str = ut.repr2(obj_, **kwargs)\n    json_str = str(json_str.replace('\\'', '\"'))\n    json_str = json_str.replace('(', '[')\n    json_str = json_str.replace(')', ']')\n    json_str = json_str.replace('None', 'null')\n    return json_str",
    "docstring": "hack for json reprs"
  },
  {
    "code": "def rejoin(self, group_id):\n        url = utils.urljoin(self.url, 'join')\n        payload = {'group_id': group_id}\n        response = self.session.post(url, json=payload)\n        return Group(self, **response.data)",
    "docstring": "Rejoin a former group.\n\n        :param str group_id: the group_id of a group\n        :return: the group\n        :rtype: :class:`~groupy.api.groups.Group`"
  },
  {
    "code": "def _repeat_length(cls, part):\n        repeat_len = len(part)\n        if repeat_len == 0:\n            return repeat_len\n        first_digit = part[0]\n        limit = repeat_len // 2 + 1\n        indices = (i for i in range(1, limit) if part[i] == first_digit)\n        for index in indices:\n            (quot, rem) = divmod(repeat_len, index)\n            if rem == 0:\n                first_chunk = part[0:index]\n                if all(first_chunk == part[x:x + index] \\\n                   for x in range(index, quot * index, index)):\n                    return index\n        return repeat_len",
    "docstring": "The length of the repeated portions of ``part``.\n\n        :param part: a number\n        :type part: list of int\n        :returns: the first index at which part repeats\n        :rtype: int\n\n        If part does not repeat, result is the length of part.\n\n        Complexity: O(len(part)^2)"
  },
  {
    "code": "def _updateTargetFromNode(self):\n        if not self.autoRangeCti or not self.autoRangeCti.configValue:\n            padding = 0\n        elif self.paddingCti.configValue == -1:\n            padding = None\n        else:\n            padding = self.paddingCti.configValue / 100\n        targetRange = self.calculateRange()\n        if not np.all(np.isfinite(targetRange)):\n            logger.warn(\"New target range is not finite. Plot range not updated\")\n            return\n        self.setTargetRange(targetRange, padding=padding)",
    "docstring": "Applies the configuration to the target axis."
  },
  {
    "code": "def get_archive_name(self):\n        name = self.get_local_name().split('.')[0]\n        case = self.case_id\n        label = self.commons['cmdlineopts'].label\n        date = ''\n        rand = ''.join(random.choice(string.ascii_lowercase) for x in range(7))\n        if self.name_pattern == 'legacy':\n            nstr = \"sosreport-{name}{case}{date}\"\n            case = '.' + case if case else ''\n            date = '-%Y%m%d%H%M%S'\n        elif self.name_pattern == 'friendly':\n            nstr = \"sosreport-{name}{label}{case}{date}-{rand}\"\n            case = '-' + case if case else ''\n            label = '-' + label if label else ''\n            date = '-%Y-%m-%d'\n        else:\n            nstr = self.name_pattern\n        nstr = nstr.format(\n            name=name,\n            label=label,\n            case=case,\n            date=date,\n            rand=rand\n        )\n        return self.sanitize_filename(time.strftime(nstr))",
    "docstring": "This function should return the filename of the archive without the\n        extension.\n\n        This uses the policy's name_pattern attribute to determine the name.\n        There are two pre-defined naming patterns - 'legacy' and 'friendly'\n        that give names like the following:\n\n        legacy - 'sosreport-tux.123456-20171224185433'\n        friendly - 'sosreport-tux-mylabel-123456-2017-12-24-ezcfcop.tar.xz'\n\n        A custom name_pattern can be used by a policy provided that it\n        defines name_pattern using a format() style string substitution.\n\n        Usable substitutions are:\n\n            name  - the short hostname of the system\n            label - the label given by --label\n            case  - the case id given by --case-id or --ticker-number\n            rand  - a random string of 7 alpha characters\n\n        Note that if a datestamp is needed, the substring should be set\n        in the name_pattern in the format accepted by strftime()."
  },
  {
    "code": "def get_health(self, consumers=2, messages=100):\n        data = {'consumers': consumers, 'messages': messages}\n        try:\n            self._request('GET', '/health', data=json.dumps(data))\n            return True\n        except SensuAPIException:\n            return False",
    "docstring": "Returns health information on transport & Redis connections."
  },
  {
    "code": "def _sanitizer(self, obj):\n        if isinstance(obj, datetime.datetime):\n            return obj.isoformat()\n        if hasattr(obj, \"to_dict\"):\n            return obj.to_dict()\n        return obj",
    "docstring": "Sanitizer method that will be passed to json.dumps."
  },
  {
    "code": "def baseimage(self, new_image):\n        images = self.parent_images or [None]\n        images[-1] = new_image\n        self.parent_images = images",
    "docstring": "change image of final stage FROM instruction"
  },
  {
    "code": "def lock(self) -> asyncio.Lock:\n        if self.lock_key not in self.request.custom_content:\n            self.request.custom_content[self.lock_key] = asyncio.Lock()\n        return self.request.custom_content[self.lock_key]",
    "docstring": "Return and generate if required the lock for this request."
  },
  {
    "code": "def hacking_no_author_tags(physical_line):\n    for regex in AUTHOR_TAG_RE:\n        if regex.match(physical_line):\n            physical_line = physical_line.lower()\n            pos = physical_line.find('moduleauthor')\n            if pos < 0:\n                pos = physical_line.find('author')\n            return (pos, \"H105: Don't use author tags\")",
    "docstring": "Check that no author tags are used.\n\n    H105 don't use author tags"
  },
  {
    "code": "def stop(self) -> None:\n        if self._stopped:\n            return\n        self._stopped = True\n        for fd, sock in self._sockets.items():\n            assert sock.fileno() == fd\n            self._handlers.pop(fd)()\n            sock.close()",
    "docstring": "Stops listening for new connections.\n\n        Requests currently in progress may still continue after the\n        server is stopped."
  },
  {
    "code": "def filter_roidb(self):\n        num_roidb = len(self._roidb)\n        self._roidb = [roi_rec for roi_rec in self._roidb if len(roi_rec['gt_classes'])]\n        num_after = len(self._roidb)\n        logger.info('filter roidb: {} -> {}'.format(num_roidb, num_after))",
    "docstring": "Remove images without usable rois"
  },
  {
    "code": "def get_assessment_bank_assignment_session(self, proxy):\n        if not self.supports_assessment_bank_assignment():\n            raise errors.Unimplemented()\n        return sessions.AssessmentBankAssignmentSession(proxy=proxy, runtime=self._runtime)",
    "docstring": "Gets the ``OsidSession`` associated with the assessment bank assignment service.\n\n        arg:    proxy (osid.proxy.Proxy): a proxy\n        return: (osid.assessment.AssessmentBankAssignmentSession) - an\n                ``AssessmentBankAssignmentSession``\n        raise:  NullArgument - ``proxy`` is ``null``\n        raise:  OperationFailed - unable to complete request\n        raise:  Unimplemented -\n                ``supports_assessment_bank_assignment()`` is ``false``\n        *compliance: optional -- This method must be implemented if\n        ``supports_assessment_bank_assignment()`` is ``true``.*"
  },
  {
    "code": "def length(cls, dataset):\n        return np.product([len(d.points) for d in dataset.data.coords(dim_coords=True)], dtype=np.intp)",
    "docstring": "Returns the total number of samples in the dataset."
  },
  {
    "code": "def _filter_seqs(fn):\n    out_file = op.splitext(fn)[0] + \"_unique.fa\"\n    idx = 0\n    if not file_exists(out_file):\n        with open(out_file, 'w') as out_handle:\n            with open(fn) as in_handle:\n                for line in in_handle:\n                    if line.startswith(\"@\") or line.startswith(\">\"):\n                        fixed_name = _make_unique(line.strip(), idx)\n                        seq = in_handle.next().strip()\n                        counts = _get_freq(fixed_name)\n                        if len(seq) < 26 and (counts > 1 or counts == 0):\n                            idx += 1\n                            print(fixed_name, file=out_handle, end=\"\\n\")\n                            print(seq, file=out_handle, end=\"\\n\")\n                        if line.startswith(\"@\"):\n                            in_handle.next()\n                            in_handle.next()\n    return out_file",
    "docstring": "Convert names of sequences to unique ids"
  },
  {
    "code": "def save(self, *args, **kwargs):\n        self.type = INTERFACE_TYPES.get('ethernet')\n        super(Ethernet, self).save(*args, **kwargs)",
    "docstring": "automatically set Interface.type to ethernet"
  },
  {
    "code": "def observed(cls, _func):\n        def wrapper(*args, **kwargs):\n            self = args[0]\n            assert(isinstance(self, Observable))\n            self._notify_method_before(self, _func.__name__, args, kwargs)\n            res = _func(*args, **kwargs)\n            self._notify_method_after(self, _func.__name__, res, args, kwargs)\n            return res\n        return wrapper",
    "docstring": "Decorate methods to be observable. If they are called on an instance\n        stored in a property, the model will emit before and after\n        notifications."
  },
  {
    "code": "def table(self):\n        if self._table is None:\n            column_names = []\n            for fileid in self.header.file_ids:\n                for column_name in self.header.column_names:\n                    column_names.append(\"{}_{}\".format(column_name, fileid))\n                column_names.append(\"ZP_{}\".format(fileid))\n            if len(column_names) > 0:\n                self._table = Table(names=column_names)\n            else:\n                self._table = Table()\n        return self._table",
    "docstring": "The astropy.table.Table object that will contain the data result\n        @rtype: Table\n        @return: data table"
  },
  {
    "code": "def list_nodes_min(conn=None, call=None):\n    if call == 'action':\n        raise SaltCloudSystemExit(\n            'The list_nodes_min function must be called with -f or --function.'\n        )\n    if conn is None:\n        conn = get_conn()\n    ret = {}\n    for node in conn.list_servers(bare=True):\n        ret[node.name] = {'id': node.id, 'state': node.status}\n    return ret",
    "docstring": "Return a list of VMs with minimal information\n\n    CLI Example\n\n    .. code-block:: bash\n\n        salt-cloud -f list_nodes_min myopenstack"
  },
  {
    "code": "def import_certificate(self, certificate_data, bay_number=None):\n        uri = \"{}/https/certificaterequest\".format(self.data['uri'])\n        if bay_number:\n            uri += \"?bayNumber=%d\" % (bay_number)\n        headers = {'Content-Type': 'application/json'}\n        return self._helper.do_put(uri, certificate_data, -1, headers)",
    "docstring": "Imports a signed server certificate into the enclosure.\n\n        Args:\n            certificate_data: Dictionary with Signed certificate and type.\n            bay_number: OA to which the signed certificate will be imported.\n\n        Returns:\n            Enclosure."
  },
  {
    "code": "def move_up(self):\n        old_index = self.current_index\n        self.current_index -= 1\n        self.__wrap_index()\n        self.__handle_selections(old_index, self.current_index)",
    "docstring": "Try to select the button above the currently selected one.\n        If a button is not there, wrap down to the bottom of the menu and select the last button."
  },
  {
    "code": "def send_audio(chat_id, audio,\n               caption=None, duration=None, performer=None, title=None, reply_to_message_id=None, reply_markup=None,\n               disable_notification=False, parse_mode=None, **kwargs):\n    files = None\n    if isinstance(audio, InputFile):\n        files = [audio]\n        audio = None\n    elif not isinstance(audio, str):\n        raise Exception('audio must be instance of InputFile or str')\n    params = dict(\n        chat_id=chat_id,\n        audio=audio\n    )\n    params.update(\n        _clean_params(\n            caption=caption,\n            duration=duration,\n            performer=performer,\n            title=title,\n            reply_to_message_id=reply_to_message_id,\n            reply_markup=reply_markup,\n            disable_notification=disable_notification,\n            parse_mode=parse_mode,\n        )\n    )\n    return TelegramBotRPCRequest('sendAudio', params=params, files=files, on_result=Message.from_result, **kwargs)",
    "docstring": "Use this method to send audio files, if you want Telegram clients to display them in the music player.\n\n    Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send audio\n    files of up to 50 MB in size, this limit may be changed in the future.\n\n    For backward compatibility, when the fields title and performer are both empty and the mime-type of the file to\n    be sent is not audio/mpeg, the file will be sent as a playable voice message. For this to work, the audio must\n    be in an .ogg file encoded with OPUS. This behavior will be phased out in the future. For sending voice\n    messages, use the sendVoice method instead.\n\n    :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)\n    :param audio: Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended),\n                  pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data.\n    :param caption: Audio caption, 0-200 characters\n    :param duration: Duration of the audio in seconds\n    :param performer: Performer\n    :param title: Track name\n    :param reply_to_message_id: If the message is a reply, ID of the original message\n    :param reply_markup: Additional interface options. A JSON-serialized object for a custom reply keyboard,\n    :param disable_notification: Sends the message silently. iOS users will not receive a notification, Android users\n                                 will receive a notification with no sound. Other apps coming soon.\n    :param parse_mode: Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline\n                      URLs in your bot's message.\n    :param kwargs: Args that get passed down to :class:`TelegramBotRPCRequest`\n\n    :type chat_id: int or str\n    :type audio: InputFile or str\n    :type caption: str\n    :type duration: int\n    :type performer: str\n    :type title: str\n    :type reply_to_message_id: int\n    :type reply_markup: ReplyKeyboardMarkup or ReplyKeyboardHide or ForceReply\n    :type parse_mode: str\n\n    :returns: On success, the sent Message is returned.\n    :rtype: TelegramBotRPCRequest"
  },
  {
    "code": "def create_stream(self, uidList=[]):\n        req_hook = 'pod/v1/im/create'\n        req_args = json.dumps(uidList)\n        status_code, response = self.__rest__.POST_query(req_hook, req_args)\n        self.logger.debug('%s: %s' % (status_code, response))\n        return status_code, response",
    "docstring": "create a stream"
  },
  {
    "code": "def get_batch_unlock(\n        end_state: NettingChannelEndState,\n) -> Optional[MerkleTreeLeaves]:\n    if len(end_state.merkletree.layers[LEAVES]) == 0:\n        return None\n    lockhashes_to_locks = dict()\n    lockhashes_to_locks.update({\n        lock.lockhash: lock\n        for secrethash, lock in end_state.secrethashes_to_lockedlocks.items()\n    })\n    lockhashes_to_locks.update({\n        proof.lock.lockhash: proof.lock\n        for secrethash, proof in end_state.secrethashes_to_unlockedlocks.items()\n    })\n    lockhashes_to_locks.update({\n        proof.lock.lockhash: proof.lock\n        for secrethash, proof in end_state.secrethashes_to_onchain_unlockedlocks.items()\n    })\n    ordered_locks = [\n        lockhashes_to_locks[LockHash(lockhash)]\n        for lockhash in end_state.merkletree.layers[LEAVES]\n    ]\n    return cast(MerkleTreeLeaves, ordered_locks)",
    "docstring": "Unlock proof for an entire merkle tree of pending locks\n\n    The unlock proof contains all the merkle tree data, tightly packed, needed by the token\n    network contract to verify the secret expiry and calculate the token amounts to transfer."
  },
  {
    "code": "def replace(self, year=None, month=None, day=None, hour=None, minute=None,\n                second=None, microsecond=None, tzinfo=None):\n        if year is None:\n            year = self.year\n        if month is None:\n            month = self.month\n        if day is None:\n            day = self.day\n        if hour is None:\n            hour = self.hour\n        if minute is None:\n            minute = self.minute\n        if second is None:\n            second = self.second\n        if microsecond is None:\n            microsecond = self.microsecond\n        if tzinfo is None:\n            tzinfo = self.tzinfo\n        if year > 0:\n            cls = datetime\n        else:\n            cls = extended_datetime\n        return cls(\n            year,\n            month,\n            day,\n            hour,\n            minute,\n            second,\n            microsecond,\n            tzinfo\n        )",
    "docstring": "Returns a new datetime.datetime or asn1crypto.util.extended_datetime\n        object with the specified components replaced\n\n        :return:\n            A datetime.datetime or asn1crypto.util.extended_datetime object"
  },
  {
    "code": "def execution_timer(value):\n    def _invoke(method, key_arg_position, *args, **kwargs):\n        start_time = time.time()\n        result = method(*args, **kwargs)\n        duration = time.time() - start_time\n        key = [method.func_name]\n        if key_arg_position is not None:\n            key.append(args[key_arg_position])\n        add_timing('.'.join(key), value=duration)\n        return result\n    if type(value) is types.FunctionType:\n        def wrapper(*args, **kwargs):\n            return _invoke(value, None, *args, **kwargs)\n        return wrapper\n    else:\n        def duration_decorator(func):\n            def wrapper(*args, **kwargs):\n                return _invoke(func, value, *args, **kwargs)\n            return wrapper\n        return duration_decorator",
    "docstring": "The ``execution_timer`` decorator allows for easy instrumentation of\n    the duration of function calls, using the method name in the key.\n\n    The following example would add duration timing with the key ``my_function``\n\n    .. code: python\n\n        @statsd.execution_timer\n        def my_function(foo):\n            pass\n\n\n    You can also have include a string argument value passed to your method as\n    part of the key. Pass the index offset of the arguments to specify the\n    argument number to use. In the following example, the key would be\n    ``my_function.baz``:\n\n    .. code:python\n\n        @statsd.execution_timer(2)\n        def my_function(foo, bar, 'baz'):\n            pass"
  },
  {
    "code": "def Conditional(self, i, j, val, name=''):\n        pmf = Pmf(name=name)\n        for vs, prob in self.Items():\n            if vs[j] != val: continue\n            pmf.Incr(vs[i], prob)\n        pmf.Normalize()\n        return pmf",
    "docstring": "Gets the conditional distribution of the indicated variable.\n\n        Distribution of vs[i], conditioned on vs[j] = val.\n\n        i: index of the variable we want\n        j: which variable is conditioned on\n        val: the value the jth variable has to have\n\n        Returns: Pmf"
  },
  {
    "code": "def gist(self, id_num):\n        url = self._build_url('gists', str(id_num))\n        json = self._json(self._get(url), 200)\n        return Gist(json, self) if json else None",
    "docstring": "Gets the gist using the specified id number.\n\n        :param int id_num: (required), unique id of the gist\n        :returns: :class:`Gist <github3.gists.Gist>`"
  },
  {
    "code": "def expand(self, other):\n        if not isinstance(other, Result):\n            raise ValueError(\"Provided argument has to be instance of overpy:Result()\")\n        other_collection_map = {Node: other.nodes, Way: other.ways, Relation: other.relations, Area: other.areas}\n        for element_type, own_collection in self._class_collection_map.items():\n            for element in other_collection_map[element_type]:\n                if is_valid_type(element, element_type) and element.id not in own_collection:\n                    own_collection[element.id] = element",
    "docstring": "Add all elements from an other result to the list of elements of this result object.\n\n        It is used by the auto resolve feature.\n\n        :param other: Expand the result with the elements from this result.\n        :type other: overpy.Result\n        :raises ValueError: If provided parameter is not instance of :class:`overpy.Result`"
  },
  {
    "code": "def get_idxs(exprs):\n    idxs = set()\n    for expr in (exprs):\n        for i in expr.find(sympy.Idx):\n            idxs.add(i)\n    return sorted(idxs, key=str)",
    "docstring": "Finds sympy.tensor.indexed.Idx instances and returns them."
  },
  {
    "code": "def ossos_release_with_metadata():\n    discoveries = []\n    observations = ossos_discoveries()\n    for obj in observations:\n        discov = [n for n in obj[0].mpc_observations if n.discovery.is_discovery][0]\n        tno = parameters.tno()\n        tno.dist = obj[1].distance\n        tno.ra_discov = discov.coordinate.ra.degrees\n        tno.mag = discov.mag\n        tno.name = discov.provisional_name\n        discoveries.append(tno)\n    return discoveries",
    "docstring": "Wrap the objects from the Version Releases together with the objects instantiated from fitting their mpc lines"
  },
  {
    "code": "def delete_object(self, obj, view_kwargs):\n        if obj is None:\n            url_field = getattr(self, 'url_field', 'id')\n            filter_value = view_kwargs[url_field]\n            raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),\n                                 source={'parameter': url_field})\n        self.before_delete_object(obj, view_kwargs)\n        self.session.delete(obj)\n        try:\n            self.session.commit()\n        except JsonApiException as e:\n            self.session.rollback()\n            raise e\n        except Exception as e:\n            self.session.rollback()\n            raise JsonApiException(\"Delete object error: \" + str(e))\n        self.after_delete_object(obj, view_kwargs)",
    "docstring": "Delete an object through sqlalchemy\n\n        :param DeclarativeMeta item: an item from sqlalchemy\n        :param dict view_kwargs: kwargs from the resource view"
  },
  {
    "code": "def log(self, message, level=None):\n        level = _STORM_LOG_LEVELS.get(level, _STORM_LOG_INFO)\n        self.send_message({\"command\": \"log\", \"msg\": str(message), \"level\": level})",
    "docstring": "Log a message to Storm optionally providing a logging level.\n\n        :param message: the log message to send to Storm.\n        :type message: str\n        :param level: the logging level that Storm should use when writing the\n                      ``message``. Can be one of: trace, debug, info, warn, or\n                      error (default: ``info``).\n        :type level: str\n\n        .. warning::\n\n          This will send your message to Storm regardless of what level you\n          specify.  In almost all cases, you are better of using\n          ``Component.logger`` and not setting ``pystorm.log.path``, because\n          that will use a :class:`pystorm.component.StormHandler` to do the\n          filtering on the Python side (instead of on the Java side after taking\n          the time to serialize your message and send it to Storm)."
  },
  {
    "code": "def delete_job(self, id, jobstore=None):\n        warnings.warn('delete_job has been deprecated, use remove_job instead.', DeprecationWarning)\n        self.remove_job(id, jobstore)",
    "docstring": "DEPRECATED, use remove_job instead.\n\n        Remove a job, preventing it from being run any more.\n\n        :param str id: the identifier of the job\n        :param str jobstore: alias of the job store that contains the job"
  },
  {
    "code": "def compute_tls13_traffic_secrets(self):\n        hkdf = self.prcs.hkdf\n        self.tls13_master_secret = hkdf.extract(self.tls13_handshake_secret,\n                                                None)\n        cts0 = hkdf.derive_secret(self.tls13_master_secret,\n                                  b\"client application traffic secret\",\n                                  b\"\".join(self.handshake_messages))\n        self.tls13_derived_secrets[\"client_traffic_secrets\"] = [cts0]\n        sts0 = hkdf.derive_secret(self.tls13_master_secret,\n                                  b\"server application traffic secret\",\n                                  b\"\".join(self.handshake_messages))\n        self.tls13_derived_secrets[\"server_traffic_secrets\"] = [sts0]\n        es = hkdf.derive_secret(self.tls13_master_secret,\n                                b\"exporter master secret\",\n                                b\"\".join(self.handshake_messages))\n        self.tls13_derived_secrets[\"exporter_secret\"] = es\n        if self.connection_end == \"server\":\n            self.pwcs.tls13_derive_keys(sts0)\n        elif self.connection_end == \"client\":\n            self.prcs.tls13_derive_keys(sts0)",
    "docstring": "Ciphers key and IV are updated accordingly for Application data.\n        self.handshake_messages should be ClientHello...ServerFinished."
  },
  {
    "code": "def get_authorization_url(self):\n        return self._format_url(\n            OAUTH2_ROOT + 'authorize',\n            query = {\n                'response_type': 'code',\n                'client_id': self.client.get('client_id', ''),\n                'redirect_uri': self.client.get('redirect_uri', '')\n            })",
    "docstring": "Get the authorization Url for the current client."
  },
  {
    "code": "def _activate_texture(mesh, name):\n        if name == True or isinstance(name, int):\n            keys = list(mesh.textures.keys())\n            idx = 0 if not isinstance(name, int) or name == True else name\n            if idx > len(keys):\n                idx = 0\n            try:\n                name = keys[idx]\n            except IndexError:\n                logging.warning('No textures associated with input mesh.')\n                return None\n        try:\n            texture = mesh.textures[name]\n        except KeyError:\n            logging.warning('Texture ({}) not associated with this dataset'.format(name))\n            texture = None\n        else:\n            if name in mesh.scalar_names:\n                old_tcoord = mesh.GetPointData().GetTCoords()\n                mesh.GetPointData().SetTCoords(mesh.GetPointData().GetArray(name))\n                mesh.GetPointData().AddArray(old_tcoord)\n                mesh.Modified()\n        return texture",
    "docstring": "Grab a texture and update the active texture coordinates. This makes\n        sure to not destroy old texture coordinates\n\n        Parameters\n        ----------\n        name : str\n            The name of the texture and texture coordinates to activate\n\n        Return\n        ------\n        vtk.vtkTexture : The active texture"
  },
  {
    "code": "def get_user_flagger():\n    user_klass = get_user_model()\n    try:\n        user = user_klass.objects.get(pk=COMMENT_FLAG_USER_ID)\n    except user_klass.DoesNotExist:\n        try:\n            user = user_klass.objects.get(\n                **{user_klass.USERNAME_FIELD: FLAGGER_USERNAME})\n        except user_klass.DoesNotExist:\n            user = user_klass.objects.create_user(FLAGGER_USERNAME)\n    return user",
    "docstring": "Return an User instance used by the system\n    when flagging a comment as trackback or pingback."
  },
  {
    "code": "def get_by_location(cls, location, include_deactivated=False):\n        if include_deactivated:\n            view = views.service_location\n        else:\n            view = views.active_service_location\n        result = yield view.first(key=location, include_docs=True)\n        parent = cls.parent_resource(**result['doc'])\n        raise Return(cls(parent=parent, **result['value']))",
    "docstring": "Get a service by it's location"
  },
  {
    "code": "def get_quoted_columns(self, platform):\n        columns = []\n        for column in self._columns.values():\n            columns.append(column.get_quoted_name(platform))\n        return columns",
    "docstring": "Returns the quoted representation of the column names\n        the constraint is associated with.\n\n        But only if they were defined with one or a column name\n        is a keyword reserved by the platform.\n        Otherwise the plain unquoted value as inserted is returned.\n\n        :param platform: The platform to use for quotation.\n        :type platform: Platform\n\n        :rtype: list"
  },
  {
    "code": "def view(location, browser=None, new=\"same\", autoraise=True):\n        try:\n            new = { \"same\": 0, \"window\": 1, \"tab\": 2 }[new]\n        except KeyError:\n            raise RuntimeError(\"invalid 'new' value passed to view: %r, valid values are: 'same', 'window', or 'tab'\" % new)\n        if location.startswith(\"http\"):\n            url = location\n        else:\n            url = \"file://\" + abspath(location)\n        try:\n            controller = get_browser_controller(browser)\n            controller.open(url, new=new, autoraise=autoraise)\n        except (SystemExit, KeyboardInterrupt):\n            raise\n        except:\n            pass",
    "docstring": "Open a browser to view the specified location.\n\n        Args:\n            location (str) : Location to open\n                If location does not begin with \"http:\" it is assumed\n                to be a file path on the local filesystem.\n            browser (str or None) : what browser to use (default: None)\n                If ``None``, use the system default browser.\n            new (str) : How to open the location. Valid values are:\n\n                ``'same'`` - open in the current tab\n\n                ``'tab'`` - open a new tab in the current window\n\n                ``'window'`` - open in a new window\n            autoraise (bool) : Whether to automatically raise the location\n                in a new browser window (default: True)\n\n        Returns:\n            None"
  },
  {
    "code": "def _init_typedef(self, typedef_curr, name, lnum):\n        if typedef_curr is None:\n            return TypeDef()\n        msg = \"PREVIOUS {REC} WAS NOT TERMINATED AS EXPECTED\".format(REC=name)\n        self._die(msg, lnum)",
    "docstring": "Initialize new typedef and perform checks."
  },
  {
    "code": "def tagsOf(self, obj):\n        return self.store.query(\n            Tag,\n            AND(Tag.catalog == self,\n                Tag.object == obj)).getColumn(\"name\")",
    "docstring": "Return an iterator of unicode strings - the tag names which apply to\n        the given object."
  },
  {
    "code": "def benchmark():\n    pool_size = multiprocessing.cpu_count() - 1\n    if pool_size < 1:\n        pool_size = 1\n    pool = multiprocessing.Pool(processes=pool_size, maxtasksperchild=1)\n    results = pool.imap_unordered(run_scenario, Benchmark.scenarii)\n    pool.close()\n    pool.join()\n    benchmark = Benchmark()\n    benchmark.load_csv()\n    benchmark.add(results)\n    benchmark.save_csv()",
    "docstring": "Run a benchmarking suite and measure time taken by the solver.\n\n    Each scenario is run in an isolated process, and results are appended to\n    CSV file."
  },
  {
    "code": "def forward(self, input_tensor):\n        ones = input_tensor.data.new_ones(input_tensor.shape[0], input_tensor.shape[-1])\n        dropout_mask = torch.nn.functional.dropout(ones, self.p, self.training, inplace=False)\n        if self.inplace:\n            input_tensor *= dropout_mask.unsqueeze(1)\n            return None\n        else:\n            return dropout_mask.unsqueeze(1) * input_tensor",
    "docstring": "Apply dropout to input tensor.\n\n        Parameters\n        ----------\n        input_tensor: ``torch.FloatTensor``\n            A tensor of shape ``(batch_size, num_timesteps, embedding_dim)``\n\n        Returns\n        -------\n        output: ``torch.FloatTensor``\n            A tensor of shape ``(batch_size, num_timesteps, embedding_dim)`` with dropout applied."
  },
  {
    "code": "def is_type_I_branch(u, v, dfs_data):\n    if u != a(v, dfs_data):\n        return False\n    if u == L2(v, dfs_data):\n        return True\n    return False",
    "docstring": "Determines whether a branch uv is a type I branch."
  },
  {
    "code": "def extract_name_max_chars(name, max_chars=64, blank=\" \"):\n    new_name = name.strip()\n    if len(new_name) > max_chars:\n        new_name = new_name[:max_chars]\n        if new_name.rfind(blank) > 0:\n            new_name = new_name[:new_name.rfind(blank)]\n    return new_name",
    "docstring": "Extracts max chars in name truncated to nearest word\n\n    :param name: path to edit\n    :param max_chars: max chars of new name\n    :param blank: char that represents the blank between words\n    :return: Name edited to contain at most max_chars"
  },
  {
    "code": "def tridi_inverse_iteration(d, e, w, x0=None, rtol=1e-8):\n    eig_diag = d - w\n    if x0 is None:\n        x0 = np.random.randn(len(d))\n    x_prev = np.zeros_like(x0)\n    norm_x = np.linalg.norm(x0)\n    x0 /= norm_x\n    while np.linalg.norm(np.abs(x0) - np.abs(x_prev)) > rtol:\n        x_prev = x0.copy()\n        tridisolve(eig_diag, e, x0)\n        norm_x = np.linalg.norm(x0)\n        x0 /= norm_x\n    return x0",
    "docstring": "Perform an inverse iteration to find the eigenvector corresponding\n    to the given eigenvalue in a symmetric tridiagonal system.\n\n    Parameters\n    ----------\n\n    d : ndarray\n      main diagonal of the tridiagonal system\n    e : ndarray\n      offdiagonal stored in e[:-1]\n    w : float\n      eigenvalue of the eigenvector\n    x0 : ndarray\n      initial point to start the iteration\n    rtol : float\n      tolerance for the norm of the difference of iterates\n\n    Returns\n    -------\n\n    e : ndarray\n      The converged eigenvector"
  },
  {
    "code": "def process_temporary_file(self, tmp_file):\n        if len(tmp_file.filename) > 100:\n            base_filename = tmp_file.filename[:tmp_file.filename.rfind(\".\")]\n            tmp_file.filename = \"%s.%s\" % (base_filename[:99-len(tmp_file.extension)], tmp_file.extension)\n        tmp_file.save()\n        data = {\n            'uuid': str(tmp_file.uuid)\n        }\n        response = HttpResponse(json.dumps(data), status=201)\n        response['Content-type'] = \"text/plain\"\n        return response",
    "docstring": "Truncates the filename if necessary, saves the model, and returns a response"
  },
  {
    "code": "def overlay_depth(obj):\n    if isinstance(obj, DynamicMap):\n        if isinstance(obj.last, CompositeOverlay):\n            return len(obj.last)\n        elif obj.last is None:\n            return None\n        return 1\n    else:\n        return 1",
    "docstring": "Computes the depth of a DynamicMap overlay if it can be determined\n    otherwise return None."
  },
  {
    "code": "def encode_categorical(table, columns=None, **kwargs):\n    if isinstance(table, pandas.Series):\n        if not is_categorical_dtype(table.dtype) and not table.dtype.char == \"O\":\n            raise TypeError(\"series must be of categorical dtype, but was {}\".format(table.dtype))\n        return _encode_categorical_series(table, **kwargs)\n    def _is_categorical_or_object(series):\n        return is_categorical_dtype(series.dtype) or series.dtype.char == \"O\"\n    if columns is None:\n        columns_to_encode = {nam for nam, s in table.iteritems() if _is_categorical_or_object(s)}\n    else:\n        columns_to_encode = set(columns)\n    items = []\n    for name, series in table.iteritems():\n        if name in columns_to_encode:\n            series = _encode_categorical_series(series, **kwargs)\n            if series is None:\n                continue\n        items.append(series)\n    new_table = pandas.concat(items, axis=1, copy=False)\n    return new_table",
    "docstring": "Encode categorical columns with `M` categories into `M-1` columns according\n    to the one-hot scheme.\n\n    Parameters\n    ----------\n    table : pandas.DataFrame\n        Table with categorical columns to encode.\n\n    columns : list-like, optional, default: None\n        Column names in the DataFrame to be encoded.\n        If `columns` is None then all the columns with\n        `object` or `category` dtype will be converted.\n\n    allow_drop : boolean, optional, default: True\n        Whether to allow dropping categorical columns that only consist\n        of a single category.\n\n    Returns\n    -------\n    encoded : pandas.DataFrame\n        Table with categorical columns encoded as numeric.\n        Numeric columns in the input table remain unchanged."
  },
  {
    "code": "def example_bigbeds():\n    hits = []\n    d = data_dir()\n    for fn in os.listdir(d):\n        fn = os.path.join(d, fn)\n        if os.path.splitext(fn)[-1] == '.bigBed':\n            hits.append(os.path.abspath(fn))\n    return hits",
    "docstring": "Returns list of example bigBed files"
  },
  {
    "code": "def _file_model_from_path(self, path, content=False, format=None):\n        model = base_model(path)\n        model[\"type\"] = \"file\"\n        if self.fs.isfile(path):\n            model[\"last_modified\"] = model[\"created\"] = self.fs.lstat(path)[\"ST_MTIME\"]\n        else:\n            model[\"last_modified\"] = model[\"created\"] = DUMMY_CREATED_DATE\n        if content:\n            try:\n                content = self.fs.read(path)\n            except NoSuchFile as e:\n                self.no_such_entity(e.path)\n            except GenericFSError as e:\n                self.do_error(str(e), 500)\n            model[\"format\"] = format or \"text\"\n            model[\"content\"] = content\n            model[\"mimetype\"] = mimetypes.guess_type(path)[0] or \"text/plain\"\n            if format == \"base64\":\n                model[\"format\"] = format or \"base64\"\n                from base64 import b64decode\n                model[\"content\"] = b64decode(content)\n        return model",
    "docstring": "Build a file model from database record."
  },
  {
    "code": "def cool_paginate(context, **kwargs) -> dict:\n    names = (\n        'size',\n        'next_name',\n        'previous_name',\n        'elastic',\n        'page_obj',\n    )\n    return_dict = {name: value for name, value in zip(names, map(kwargs.get, names))}\n    if context.get('request'):\n        return_dict['request'] = context['request']\n    else:\n        raise RequestNotExists(\n            'Unable to find request in your template context,'\n            'please make sure that you have the request context processor enabled'\n        )\n    if not return_dict.get('page_obj'):\n        if context.get('page_obj'):\n            return_dict['page_obj'] = context['page_obj']\n        else:\n            raise PageNotSpecified(\n                'You customized paginator standard name, '\n                \"but haven't specified it in {% cool_paginate %} tag.\"\n            )\n    if not return_dict.get('elastic'):\n        return_dict['elastic'] = getattr(settings, 'COOL_PAGINATOR_ELASTIC', 10)\n    return return_dict",
    "docstring": "Main function for pagination process."
  },
  {
    "code": "def autocommit(f):\n    \"A decorator to commit to the storage if autocommit is set to True.\"\n    @wraps(f)\n    def wrapper(self, *args, **kwargs):\n        result = f(self, *args, **kwargs)\n        if self._meta.commit_ready():\n            self.commit()\n        return result\n    return wrapper",
    "docstring": "A decorator to commit to the storage if autocommit is set to True."
  },
  {
    "code": "def check_nonstandard_section_name(self):\n        std_sections = ['.text', '.bss', '.rdata', '.data', '.rsrc', '.edata', '.idata',\n                        '.pdata', '.debug', '.reloc', '.stab', '.stabstr', '.tls',\n                        '.crt', '.gnu_deb', '.eh_fram', '.exptbl', '.rodata']\n        for i in range(200):\n            std_sections.append('/'+str(i))\n        non_std_sections = []\n        for section in self.pefile_handle.sections:\n            name = convert_to_ascii_null_term(section.Name).lower()\n            if (name not in std_sections):\n                non_std_sections.append(name)\n        if non_std_sections:\n            return{'description': 'Section(s) with a non-standard name, tamper indication', \n                   'severity': 3, 'category': 'MALFORMED', 'attributes': non_std_sections}\n        return None",
    "docstring": "Checking for an non-standard section name"
  },
  {
    "code": "def stderr_with_input(cmd, stdin):\n    handle, gpg_stderr = stderr_handle()\n    LOGGER.debug(\"GPG command %s\", ' '.join(cmd))\n    try:\n        gpg_proc = subprocess.Popen(cmd,\n                                    stdout=subprocess.PIPE,\n                                    stdin=subprocess.PIPE,\n                                    stderr=gpg_stderr)\n        output, _err = gpg_proc.communicate(polite_bytes(stdin))\n        if handle:\n            handle.close()\n        return output\n    except subprocess.CalledProcessError as exception:\n        return gpg_error(exception, 'GPG variable encryption error')\n    except OSError as exception:\n        raise CryptoritoError(\"File %s not found\" % exception.filename)",
    "docstring": "Runs a command, passing something in stdin, and returning\n    whatever came out from stdout"
  },
  {
    "code": "def resolve_all(self, import_items):\n        for import_item in import_items:\n            try:\n                yield self.resolve_import(import_item)\n            except ImportException as err:\n                logging.info('unknown module %s', err.module_name)",
    "docstring": "Resolves a list of imports.\n\n        Yields filenames."
  },
  {
    "code": "def transfers_complete(self):\n        for transfer in self.transfers:\n            if not transfer.is_complete:\n                error = {\n                    'errorcode': 4003,\n                    'errormessage': 'You must complete transfer before logout.'\n                    }\n                hellraiser(error)",
    "docstring": "Check if all transfers are completed."
  },
  {
    "code": "def kill(self, dwExitCode = 0):\n        hThread = self.get_handle(win32.THREAD_TERMINATE)\n        win32.TerminateThread(hThread, dwExitCode)\n        if self.pInjectedMemory is not None:\n            try:\n                self.get_process().free(self.pInjectedMemory)\n                self.pInjectedMemory = None\n            except Exception:\n                pass",
    "docstring": "Terminates the thread execution.\n\n        @note: If the C{lpInjectedMemory} member contains a valid pointer,\n        the memory is freed.\n\n        @type  dwExitCode: int\n        @param dwExitCode: (Optional) Thread exit code."
  },
  {
    "code": "def prune(self, whole=False, keys=[], names=[], filters=[]):\n        for node in self.climb(whole):\n            if not all([key in node.data for key in keys]):\n                continue\n            if names and not any(\n                    [re.search(name, node.name) for name in names]):\n                continue\n            try:\n                if not all([utils.filter(filter, node.data, regexp=True)\n                        for filter in filters]):\n                    continue\n            except utils.FilterError:\n                continue\n            yield node",
    "docstring": "Filter tree nodes based on given criteria"
  },
  {
    "code": "def transformer_image_decoder(targets,\n                              encoder_output,\n                              ed_attention_bias,\n                              hparams,\n                              name=None):\n  with tf.variable_scope(name, default_name=\"transformer_dec\"):\n    batch_size = common_layers.shape_list(targets)[0]\n    targets = tf.reshape(targets, [batch_size,\n                                   hparams.img_len,\n                                   hparams.img_len,\n                                   hparams.num_channels * hparams.hidden_size])\n    decoder_input, _, _ = cia.prepare_decoder(targets, hparams)\n    decoder_output = cia.transformer_decoder_layers(\n        decoder_input,\n        encoder_output,\n        hparams.num_decoder_layers or hparams.num_hidden_layers,\n        hparams,\n        attention_type=hparams.dec_attention_type,\n        encoder_decoder_attention_bias=ed_attention_bias,\n        name=\"decoder\")\n    decoder_output = tf.reshape(decoder_output,\n                                [batch_size,\n                                 hparams.img_len,\n                                 hparams.img_len * hparams.num_channels,\n                                 hparams.hidden_size])\n    return decoder_output",
    "docstring": "Transformer image decoder over targets with local attention.\n\n  Args:\n    targets: Tensor of shape [batch, ...], and whose size is batch * height *\n      width * hparams.num_channels * hparams.hidden_size.\n    encoder_output: Tensor of shape [batch, length_kv, hparams.hidden_size].\n    ed_attention_bias: Tensor which broadcasts with shape [batch,\n      hparams.num_heads, length_q, length_kv]. Encoder-decoder attention bias.\n    hparams: HParams.\n    name: string, variable scope.\n\n  Returns:\n    Tensor of shape [batch, height, width * hparams.num_channels,\n    hparams.hidden_size]."
  },
  {
    "code": "def s_supply(self, bus):\n        Sg = array([complex(g.p, g.q) for g in self.generators if\n                   (g.bus == bus) and not g.is_load], dtype=complex64)\n        if len(Sg):\n            return sum(Sg)\n        else:\n            return 0 + 0j",
    "docstring": "Returns the total complex power generation capacity."
  },
  {
    "code": "def from_string(contents):\n        lines = contents.split(\"\\n\")\n        num_sites = int(lines[0])\n        coords = []\n        sp = []\n        prop = []\n        coord_patt = re.compile(\n            r\"(\\w+)\\s+([0-9\\-\\.]+)\\s+([0-9\\-\\.]+)\\s+([0-9\\-\\.]+)\\s+\" +\n            r\"([0-9\\-\\.]+)\"\n        )\n        for i in range(2, 2 + num_sites):\n            m = coord_patt.search(lines[i])\n            if m:\n                sp.append(m.group(1))\n                coords.append([float(j)\n                               for j in [m.group(i) for i in [3, 4, 2]]])\n                prop.append(float(m.group(5)))\n        return ZeoVoronoiXYZ(\n            Molecule(sp, coords, site_properties={'voronoi_radius': prop})\n        )",
    "docstring": "Creates Zeo++ Voronoi XYZ object from a string.\n        from_string method of XYZ class is being redefined.\n\n        Args:\n            contents: String representing Zeo++ Voronoi XYZ file.\n\n        Returns:\n            ZeoVoronoiXYZ object"
  },
  {
    "code": "def disconnect_network_gateway(self, gateway_id, body=None):\n        base_uri = self.network_gateway_path % gateway_id\n        return self.put(\"%s/disconnect_network\" % base_uri, body=body)",
    "docstring": "Disconnect a network from the specified gateway."
  },
  {
    "code": "def process_data_config_section(config, data_config):\n    if 'connectors' in data_config:\n        for connector in data_config['connectors']:\n            config.data['connectors'][\n                connector['name']] = get_config_from_package(\n                connector['class'])\n    if 'sources' in data_config:\n        if data_config['sources']:\n            for source in data_config['sources']:\n                config.data['sources'][source['name']] = source\n                del config.data['sources'][source['name']]['name']",
    "docstring": "Processes the data configuration section from the configuration\n    data dict.\n\n    :param config: The config reference of the object that will hold the\n    configuration data from the config_data.\n    :param data_config: Data configuration section from a config data dict."
  },
  {
    "code": "def set_status(self, status):\n        if self._json_state['control_url']:\n            url = CONST.BASE_URL + self._json_state['control_url']\n            status_data = {\n                'status': str(status)\n            }\n            response = self._abode.send_request(\n                method=\"put\", url=url, data=status_data)\n            response_object = json.loads(response.text)\n            _LOGGER.debug(\"Set Status Response: %s\", response.text)\n            if response_object['id'] != self.device_id:\n                raise AbodeException((ERROR.SET_STATUS_DEV_ID))\n            if response_object['status'] != str(status):\n                raise AbodeException((ERROR.SET_STATUS_STATE))\n            _LOGGER.info(\"Set device %s status to: %s\", self.device_id, status)\n            return True\n        return False",
    "docstring": "Set device status."
  },
  {
    "code": "def statistics(self, start=None, end=None, namespace=None):\n        return self.make_context(start=start, end=end,\n                                 namespace=namespace).statistics()",
    "docstring": "Get write statistics for the specified namespace and date range"
  },
  {
    "code": "def main():\n    description = 'Letter - a commandline interface'\n    parser = argparse.ArgumentParser(description=description)\n    parser.add_argument('--gmail', action='store_true', help='Send via Gmail', )\n    args = parser.parse_args()\n    to       = raw_input('To address > ')\n    subject  = raw_input('Subject > ')\n    body     = raw_input('Your Message > ')\n    if args.gmail:\n        user = fromaddr = raw_input('Gmail Address > ')\n        pw   = getpass.getpass()\n        postie = letter.GmailPostman(user=user, pw=pw)\n    else:\n        postie = letter.Postman()\n        fromaddr = raw_input('From address > ')\n    class Message(letter.Letter):\n        Postie     = postie\n        From       = fromaddr\n        To         = to\n        Subject    = subject\n        Body       = body\n    return 0",
    "docstring": "Do the things!\n\n\n    Return: 0\n    Exceptions:"
  },
  {
    "code": "def _check_underflow(self, n):\n        if self._pos + n > self._end_pos:\n            raise self.BufferUnderflow()",
    "docstring": "Raise BufferUnderflow if there's not enough bytes to satisfy\n        the request."
  },
  {
    "code": "def create_folder_structure(self):\n        self.info_file, directories = create_folder_structure(self.project,\n                                                              self.name)\n        self.project_dir, self.batch_dir, self.raw_dir = directories\n        logger.debug(\"create folders:\" + str(directories))",
    "docstring": "Creates a folder structure based on the project and batch name.\n\n        Project - Batch-name - Raw-data-dir\n\n        The info_df JSON-file will be stored in the Project folder.\n        The summary-files will be saved in the Batch-name folder.\n        The raw data (including exported cycles and ica-data) will be saved to\n        the Raw-data-dir."
  },
  {
    "code": "def stop_artifact_creation(self, id_or_uri, task_uri):\n        data = {\n            \"taskUri\": task_uri\n        }\n        uri = self.URI + '/' + extract_id_from_uri(id_or_uri) + self.STOP_CREATION_PATH\n        return self._client.update(data, uri=uri)",
    "docstring": "Stops creation of the selected Artifact Bundle.\n\n        Args:\n            id_or_uri: ID or URI of the Artifact Bundle.\n            task_uri: Task URI associated with the Artifact Bundle.\n\n        Returns:\n            string:"
  },
  {
    "code": "def exists(self, queue_name, timeout=None):\n        try:\n            self.get_queue_metadata(queue_name, timeout=timeout)\n            return True\n        except AzureHttpError as ex:\n            _dont_fail_not_exist(ex)\n            return False",
    "docstring": "Returns a boolean indicating whether the queue exists.\n\n        :param str queue_name:\n            The name of queue to check for existence.\n        :param int timeout:\n            The server timeout, expressed in seconds.\n        :return: A boolean indicating whether the queue exists.\n        :rtype: bool"
  },
  {
    "code": "def get_municipalities(self):\n        return sorted(list(set([\n            location.municipality for location in self.get_locations().values()\n        ])))",
    "docstring": "Return the list of unique municipalities, sorted by name."
  },
  {
    "code": "def setpurpose(self, purpose):\n        if isinstance(purpose, str):\n            purp_no = libcrypto.X509_PURPOSE_get_by_sname(purpose)\n            if purp_no <= 0:\n                raise X509Error(\"Invalid certificate purpose '%s'\" % purpose)\n        elif isinstance(purpose, int):\n            purp_no = purpose\n        if libcrypto.X509_STORE_set_purpose(self.store, purp_no) <= 0:\n            raise X509Error(\"cannot set purpose\")",
    "docstring": "Sets certificate purpose which verified certificate should match\n        @param purpose - number from 1 to 9 or standard strind defined\n                         in Openssl\n        possible strings - sslcient,sslserver, nssslserver, smimesign,i\n                         smimeencrypt, crlsign, any, ocsphelper"
  },
  {
    "code": "def _create(self, cache_file):\n        conn = sqlite3.connect(cache_file)\n        cur = conn.cursor()\n        cur.execute(\"PRAGMA foreign_keys = ON\")\n        cur.execute(\n)\n        cur.execute(\n)\n        conn.commit()\n        conn.close()",
    "docstring": "Create the tables needed to store the information."
  },
  {
    "code": "def intersection(a, b, scale=1):\n    try:\n        a1, a2 = a\n    except TypeError:\n        a1 = a.start\n        a2 = a.stop\n    try:\n        b1, b2 = b\n    except TypeError:\n        b1 = b.start\n        b2 = b.stop\n    if a2 <= b1:\n        return None\n    if a1 >= b2:\n        return None\n    if a2 <= b2:\n        if a1 <= b1:\n            return slice(b1 * scale, a2 * scale)\n        else:\n            return slice(a1 * scale, a2 * scale)\n    else:\n        if a1 <= b1:\n            return slice(b1 * scale, b2 * scale)\n        else:\n            return slice(a1 * scale, b2 * scale)",
    "docstring": "Intersection between two segments."
  },
  {
    "code": "def get_calendar(self, name):\n        canonical_name = self.resolve_alias(name)\n        try:\n            return self._calendars[canonical_name]\n        except KeyError:\n            pass\n        try:\n            factory = self._calendar_factories[canonical_name]\n        except KeyError:\n            raise InvalidCalendarName(calendar_name=name)\n        calendar = self._calendars[canonical_name] = factory()\n        return calendar",
    "docstring": "Retrieves an instance of an TradingCalendar whose name is given.\n\n        Parameters\n        ----------\n        name : str\n            The name of the TradingCalendar to be retrieved.\n\n        Returns\n        -------\n        calendar : calendars.TradingCalendar\n            The desired calendar."
  },
  {
    "code": "def trsm(self,B,trans='N'):\n        r\n        if trans=='N':\n            cp.trsm(self._L0,B)\n            pftrsm(self._V,self._L,self._B,B,trans='N')\n        elif trans=='T':\n            pftrsm(self._V,self._L,self._B,B,trans='T')\n            cp.trsm(self._L0,B,trans='T')\n        elif type(trans) is str:\n            raise ValueError(\"trans must be 'N' or 'T'\")\n        else:\n            raise TypeError(\"trans must be 'N' or 'T'\")\n        return",
    "docstring": "r\"\"\"\n        Solves a triangular system of equations with multiple righthand\n        sides. Computes\n\n        .. math::\n\n            B &:= L^{-1} B  \\text{ if trans is 'N'}\n\n           B &:= L^{-T} B  \\text{ if trans is 'T'}"
  },
  {
    "code": "def symlink(self, source, dest):\n        dest = self._adjust_cwd(dest)\n        self._log(DEBUG, \"symlink({!r}, {!r})\".format(source, dest))\n        source = b(source)\n        self._request(CMD_SYMLINK, source, dest)",
    "docstring": "Create a symbolic link to the ``source`` path at ``destination``.\n\n        :param str source: path of the original file\n        :param str dest: path of the newly created symlink"
  },
  {
    "code": "def parse_html(html):\n    paragraphs = re.split(\"</?p[^>]*>\", html)\n    paragraphs = [re.split(\"<br */?>\", p) for p in paragraphs if p]\n    return [[get_text(l) for l in p] for p in paragraphs]",
    "docstring": "Attempt to convert html to plain text while keeping line breaks.\n    Returns a list of paragraphs, each being a list of lines."
  },
  {
    "code": "def send_confirm_password_email(person):\n    url = '%s/profile/login/%s/' % (\n        settings.REGISTRATION_BASE_URL, person.username)\n    context = CONTEXT.copy()\n    context.update({\n        'url': url,\n        'receiver': person,\n    })\n    to_email = person.email\n    subject, body = render_email('confirm_password', context)\n    send_mail(subject, body, settings.ACCOUNTS_EMAIL, [to_email])",
    "docstring": "Sends an email to user allowing them to confirm their password."
  },
  {
    "code": "def to_pandas_series_rdd(self):\n        pd_index = self.index().to_pandas_index()\n        return self.map(lambda x: (x[0], pd.Series(x[1], pd_index)))",
    "docstring": "Returns an RDD of Pandas Series objects indexed with Pandas DatetimeIndexes"
  },
  {
    "code": "def query(input, representation, resolvers=None, **kwargs):\n    apiurl = API_BASE+'/%s/%s/xml' % (urlquote(input), representation)\n    if resolvers:\n        kwargs['resolver'] = \",\".join(resolvers)\n    if kwargs:\n        apiurl+= '?%s' % urlencode(kwargs)\n    result = []\n    try:\n        tree = ET.parse(urlopen(apiurl))\n        for data in tree.findall(\".//data\"):\n            datadict = {'resolver':data.attrib['resolver'],\n                        'notation':data.attrib['notation'],\n                        'value':[]}\n            for item in data.findall(\"item\"):\n                datadict['value'].append(item.text)\n            if len(datadict['value']) == 1:\n                datadict['value'] = datadict['value'][0]\n            result.append(datadict)\n    except HTTPError:\n        pass\n    return result if result else None",
    "docstring": "Get all results for resolving input to the specified output representation"
  },
  {
    "code": "def _init_loaders(self) -> None:\n        for loader in settings.I18N_TRANSLATION_LOADERS:\n            loader_class = import_class(loader['loader'])\n            instance = loader_class()\n            instance.on_update(self.update)\n            run(instance.load(**loader['params']))",
    "docstring": "This creates the loaders instances and subscribes to their updates."
  },
  {
    "code": "def get_all(self, inactive='', email_filter='', tag='', count=25, offset=0):\n        self._check_values()\n        params = '?inactive=' + inactive + '&emailFilter=' + email_filter +'&tag=' + tag\n        params += '&count=' + str(count) + '&offset=' + str(offset)\n        req = Request(\n            __POSTMARK_URL__ + 'bounces' + params,\n            None,\n            {\n                'Accept': 'application/json',\n                'Content-Type': 'application/json',\n                'X-Postmark-Server-Token': self.__api_key,\n                'User-agent': self.__user_agent\n            }\n        )\n        try:\n            result = urlopen(req)\n            with closing(result):\n                if result.code == 200:\n                    return json.loads(result.read())\n                else:\n                    raise PMMailSendException('Return code %d: %s' % (result.code, result.msg))\n        except HTTPError as err:\n            return err",
    "docstring": "Fetches a portion of bounces according to the specified input criteria. The count and offset\n        parameters are mandatory. You should never retrieve all bounces as that could be excessively\n        slow for your application. To know how many bounces you have, you need to request a portion\n        first, usually the first page, and the service will return the count in the TotalCount property\n        of the response."
  },
  {
    "code": "def _get_mean(self, imt, mag, hypo_depth, rrup, d):\n        mag = min(mag, 8.3)\n        if imt.name == 'PGV':\n            mean = (\n                0.58 * mag +\n                0.0038 * hypo_depth +\n                d -\n                1.29 -\n                np.log10(rrup + 0.0028 * 10 ** (0.5 * mag)) -\n                0.002 * rrup\n            )\n        else:\n            mean = (\n                0.50 * mag +\n                0.0043 * hypo_depth +\n                d +\n                0.61 -\n                np.log10(rrup + 0.0055 * 10 ** (0.5 * mag)) -\n                0.003 * rrup\n            )\n            mean = np.log10(10**(mean)/(g*100))\n        return mean",
    "docstring": "Return mean value as defined in equation 3.5.1-1 page 148"
  },
  {
    "code": "def backend_add(cls, name, backend):\n        oper = cls.call(\n            'hosting.rproxy.server.create', cls.usable_id(name), backend)\n        cls.echo('Adding backend %s:%s into webaccelerator' %\n                 (backend['ip'], backend['port']))\n        cls.display_progress(oper)\n        cls.echo('Backend added')\n        return oper",
    "docstring": "Add a backend into a webaccelerator"
  },
  {
    "code": "def trim_disconnected_blobs(im, inlets):\n    r\n    temp = sp.zeros_like(im)\n    temp[inlets] = True\n    labels, N = spim.label(im + temp)\n    im = im ^ (clear_border(labels=labels) > 0)\n    return im",
    "docstring": "r\"\"\"\n    Removes foreground voxels not connected to specified inlets\n\n    Parameters\n    ----------\n    im : ND-array\n        The array to be trimmed\n    inlets : ND-array of tuple of indices\n        The locations of the inlets.  Any voxels *not* connected directly to\n        the inlets will be trimmed\n\n    Returns\n    -------\n    image : ND-array\n        An array of the same shape as ``im``, but with all foreground\n        voxels not connected to the ``inlets`` removed."
  },
  {
    "code": "def set_recursion_limit(limit):\n    if limit < minimum_recursion_limit:\n        raise CoconutException(\"--recursion-limit must be at least \" + str(minimum_recursion_limit))\n    sys.setrecursionlimit(limit)",
    "docstring": "Set the Python recursion limit."
  },
  {
    "code": "def graph_branches_from_node(self, node):\n        branches = []\n        branches_dict = self._graph.adj[node]\n        for branch in branches_dict.items():\n            branches.append(branch)\n        return sorted(branches, key=lambda _: repr(_))",
    "docstring": "Returns branches that are connected to `node`\n\n        Args\n        ----\n        node: GridDing0\n            Ding0 object (member of graph)\n        \n        Returns\n        -------\n        :any:`list`\n            List of tuples (node in :obj:`GridDing0`, branch in :obj:`BranchDing0`) ::\n            \n                (node , branch_0 ),\n                ...,\n                (node , branch_N ),"
  },
  {
    "code": "def diff_commonOverlap(self, text1, text2):\n    text1_length = len(text1)\n    text2_length = len(text2)\n    if text1_length == 0 or text2_length == 0:\n      return 0\n    if text1_length > text2_length:\n      text1 = text1[-text2_length:]\n    elif text1_length < text2_length:\n      text2 = text2[:text1_length]\n    text_length = min(text1_length, text2_length)\n    if text1 == text2:\n      return text_length\n    best = 0\n    length = 1\n    while True:\n      pattern = text1[-length:]\n      found = text2.find(pattern)\n      if found == -1:\n        return best\n      length += found\n      if found == 0 or text1[-length:] == text2[:length]:\n        best = length\n        length += 1",
    "docstring": "Determine if the suffix of one string is the prefix of another.\n\n    Args:\n      text1 First string.\n      text2 Second string.\n\n    Returns:\n      The number of characters common to the end of the first\n      string and the start of the second string."
  },
  {
    "code": "def zscan(self, name, cursor='0', match=None, count=10):\n        def value_function():\n            values = self.zrange(name, 0, -1, withscores=True)\n            values.sort(key=lambda x: x[1])\n            return values\n        return self._common_scan(value_function, cursor=cursor, match=match, count=count, key=lambda v: v[0])",
    "docstring": "Emulate zscan."
  },
  {
    "code": "def indication(self, pdu):\n        if _debug: UDPDirector._debug(\"indication %r\", pdu)\n        addr = pdu.pduDestination\n        peer = self.peers.get(addr, None)\n        if not peer:\n            peer = self.actorClass(self, addr)\n        peer.indication(pdu)",
    "docstring": "Client requests are queued for delivery."
  },
  {
    "code": "def duplicate_statements(model, oldorigin, neworigin, rfilter=None):\n    for o, r, t, a in model.match(oldorigin):\n        if rfilter is None or rfilter(o, r, t, a):\n            model.add(I(neworigin), r, t, a)\n    return",
    "docstring": "Take links with a given origin, and create duplicate links with the same information but a new origin\n\n    :param model: Versa model to be updated\n    :param oldres: resource IRI to be duplicated\n    :param newres: origin resource IRI for duplication\n    :return: None"
  },
  {
    "code": "def _create_listening_stream(self, pull_addr):\n        sock = self._zmq_context.socket(zmq.PULL)\n        sock.connect(pull_addr)\n        stream = ZMQStream(sock, io_loop=self.io_loop)\n        return stream",
    "docstring": "Create a stream listening for Requests. The `self._recv_callback`\n        method is asociated with incoming requests."
  },
  {
    "code": "def queueStream(self, rdds, oneAtATime=True, default=None):\n        deserializer = QueueStreamDeserializer(self._context)\n        if default is not None:\n            default = deserializer(default)\n        if Queue is False:\n            log.error('Run \"pip install tornado\" to install tornado.')\n        q = Queue()\n        for i in rdds:\n            q.put(i)\n        qstream = QueueStream(q, oneAtATime, default)\n        return DStream(qstream, self, deserializer)",
    "docstring": "Create stream iterable over RDDs.\n\n        :param rdds: Iterable over RDDs or lists.\n        :param oneAtATime: Process one at a time or all.\n        :param default: If no more RDDs in ``rdds``, return this. Can be None.\n        :rtype: DStream\n\n\n        Example:\n\n        >>> import pysparkling\n        >>> sc = pysparkling.Context()\n        >>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)\n        >>> (\n        ...     ssc\n        ...     .queueStream([[4], [2], [7]])\n        ...     .foreachRDD(lambda rdd: print(rdd.collect()))\n        ... )\n        >>> ssc.start()\n        >>> ssc.awaitTermination(0.35)\n        [4]\n        [2]\n        [7]\n\n\n        Example testing the default value:\n\n        >>> import pysparkling\n        >>> sc = pysparkling.Context()\n        >>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)\n        >>> (\n        ...     ssc\n        ...     .queueStream([[4], [2]], default=['placeholder'])\n        ...     .foreachRDD(lambda rdd: print(rdd.collect()))\n        ... )\n        >>> ssc.start()\n        >>> ssc.awaitTermination(0.35)\n        [4]\n        [2]\n        ['placeholder']"
  },
  {
    "code": "def _structure_dict(self, obj, cl):\n        if is_bare(cl) or cl.__args__ == (Any, Any):\n            return dict(obj)\n        else:\n            key_type, val_type = cl.__args__\n            if key_type is Any:\n                val_conv = self._structure_func.dispatch(val_type)\n                return {k: val_conv(v, val_type) for k, v in obj.items()}\n            elif val_type is Any:\n                key_conv = self._structure_func.dispatch(key_type)\n                return {key_conv(k, key_type): v for k, v in obj.items()}\n            else:\n                key_conv = self._structure_func.dispatch(key_type)\n                val_conv = self._structure_func.dispatch(val_type)\n                return {\n                    key_conv(k, key_type): val_conv(v, val_type)\n                    for k, v in obj.items()\n                }",
    "docstring": "Convert a mapping into a potentially generic dict."
  },
  {
    "code": "def relativize_path(path, base, os_sep=os.sep):\n    if not check_base(path, base, os_sep):\n        raise OutsideDirectoryBase(\"%r is not under %r\" % (path, base))\n    prefix_len = len(base)\n    if not base.endswith(os_sep):\n        prefix_len += len(os_sep)\n    return path[prefix_len:]",
    "docstring": "Make absolute path relative to an absolute base.\n\n    :param path: absolute path\n    :type path: str\n    :param base: absolute base path\n    :type base: str\n    :param os_sep: path component separator, defaults to current OS separator\n    :type os_sep: str\n    :return: relative path\n    :rtype: str or unicode\n    :raises OutsideDirectoryBase: if path is not below base"
  },
  {
    "code": "def add(self, name, handler, group_by=None, aggregator=None):\n        assert self.batch is not None, \"No active batch, call start() first\"\n        items = self.batch.setdefault(name, collections.OrderedDict())\n        if group_by is None:\n            items.setdefault(group_by, []).append((None, handler))\n        elif aggregator is not None:\n            agg = items.get(group_by, [(None, None)])[0][0]\n            items[group_by] = [(aggregator(agg), handler)]\n        else:\n            items[group_by] = [(None, handler)]",
    "docstring": "Add a new handler to the current batch."
  },
  {
    "code": "def nodes_walker(node, ascendants=False):\n    attribute = \"children\" if not ascendants else \"parent\"\n    if not hasattr(node, attribute):\n        return\n    elements = getattr(node, attribute)\n    elements = elements if isinstance(elements, list) else [elements]\n    for element in elements:\n        yield element\n        if not hasattr(element, attribute):\n            continue\n        if not getattr(element, attribute):\n            continue\n        for sub_element in nodes_walker(element, ascendants=ascendants):\n            yield sub_element",
    "docstring": "Defines a generator used to walk into Nodes hierarchy.\n\n    Usage::\n\n        >>> node_a = AbstractCompositeNode(\"MyNodeA\")\n        >>> node_b = AbstractCompositeNode(\"MyNodeB\", node_a)\n        >>> node_c = AbstractCompositeNode(\"MyNodeC\", node_a)\n        >>> node_d = AbstractCompositeNode(\"MyNodeD\", node_b)\n        >>> node_e = AbstractCompositeNode(\"MyNodeE\", node_b)\n        >>> node_f = AbstractCompositeNode(\"MyNodeF\", node_d)\n        >>> node_g = AbstractCompositeNode(\"MyNodeG\", node_f)\n        >>> node_h = AbstractCompositeNode(\"MyNodeH\", node_g)\n        >>> for node in nodes_walker(node_a):\n        ...\tprint node.name\n        MyNodeB\n        MyNodeD\n        MyNodeF\n        MyNodeG\n        MyNodeH\n        MyNodeE\n        MyNodeC\n\n    :param node: Node to walk.\n    :type node: AbstractCompositeNode\n    :param ascendants: Ascendants instead of descendants will be yielded.\n    :type ascendants: bool\n    :return: Node.\n    :rtype: AbstractNode or AbstractCompositeNode"
  },
  {
    "code": "def create_raw(self, key, value):\n        data = None\n        if key is not None and value is not None:\n            data = self.db.create(key.strip(), value)\n        else:\n            self.tcex.log.warning(u'The key or value field was None.')\n        return data",
    "docstring": "Create method of CRUD operation for raw data.\n\n        Args:\n            key (string): The variable to write to the DB.\n            value (any): The data to write to the DB.\n\n        Returns:\n            (string): Result of DB write."
  },
  {
    "code": "def url(self):\n        url = \"https://api.darksky.net/forecast/{key}/{lat},{lon}\".format(key=self.api_key,\n                                                                          lat=self.latitude,\n                                                                          lon=self.longitude)\n        if isinstance(self._date, datetime):\n            url += \",{:%Y-%m-%dT%H:%M:%S}\".format(self._date)\n        url += \"?units={}\".format(self.units)\n        if self.lang != \"auto\":\n            url += \"&lang={}\".format(self.lang)\n        if len(self._exclude) > 0:\n            url += \"&exclude=\"\n            for e in self._exclude:\n                url += \"{},\".format(e)\n            url = url.strip(\",\")\n        if self._extend:\n            url += \"&extend=hourly\"\n        return url",
    "docstring": "Build and returns a URL used to make a Dark Sky API call."
  },
  {
    "code": "def handle(self, **options):\n        super(Command, self).handle(**options)\n        return \"{} static file{} copied.\".format(\n            self.num_copied_files,\n            '' if self.num_copied_files == 1 else 's')",
    "docstring": "Override handle to supress summary output"
  },
  {
    "code": "def metric(self, measurement_name, values, tags=None, timestamp=None):\n        if not measurement_name or values in (None, {}):\n            return\n        tags = tags or {}\n        all_tags = dict(self.tags, **tags)\n        line = Line(measurement_name, values, all_tags, timestamp)\n        self.send(line.to_line_protocol())",
    "docstring": "Append global tags configured for the client to the tags given then\n        converts the data into InfluxDB Line protocol and sends to to socket"
  },
  {
    "code": "def add_singles(self, results):\n        logging.info('BKG Coincs %s stored %s bytes',\n                     len(self.coincs), self.coincs.nbytes)\n        valid_ifos = [k for k in results.keys() if results[k] and k in self.ifos]\n        if len(valid_ifos) == 0: return {}\n        self._add_singles_to_buffer(results, ifos=valid_ifos)\n        _, coinc_results = self._find_coincs(results, ifos=valid_ifos)\n        if len(valid_ifos) == 2:\n            coinc_results['coinc_possible'] = True\n        return coinc_results",
    "docstring": "Add singles to the bacckground estimate and find candidates\n\n        Parameters\n        ----------\n        results: dict of arrays\n            Dictionary of dictionaries indexed by ifo and keys such as 'snr',\n            'chisq', etc. The specific format it determined by the\n            LiveBatchMatchedFilter class.\n\n        Returns\n        -------\n        coinc_results: dict of arrays\n            A dictionary of arrays containing the coincident results."
  },
  {
    "code": "def trainRegressor(cls, data, categoricalFeaturesInfo,\n                       impurity=\"variance\", maxDepth=5, maxBins=32, minInstancesPerNode=1,\n                       minInfoGain=0.0):\n        return cls._train(data, \"regression\", 0, categoricalFeaturesInfo,\n                          impurity, maxDepth, maxBins, minInstancesPerNode, minInfoGain)",
    "docstring": "Train a decision tree model for regression.\n\n        :param data:\n          Training data: RDD of LabeledPoint. Labels are real numbers.\n        :param categoricalFeaturesInfo:\n          Map storing arity of categorical features. An entry (n -> k)\n          indicates that feature n is categorical with k categories\n          indexed from 0: {0, 1, ..., k-1}.\n        :param impurity:\n          Criterion used for information gain calculation.\n          The only supported value for regression is \"variance\".\n          (default: \"variance\")\n        :param maxDepth:\n          Maximum depth of tree (e.g. depth 0 means 1 leaf node, depth 1\n          means 1 internal node + 2 leaf nodes).\n          (default: 5)\n        :param maxBins:\n          Number of bins used for finding splits at each node.\n          (default: 32)\n        :param minInstancesPerNode:\n          Minimum number of instances required at child nodes to create\n          the parent split.\n          (default: 1)\n        :param minInfoGain:\n          Minimum info gain required to create a split.\n          (default: 0.0)\n        :return:\n          DecisionTreeModel.\n\n        Example usage:\n\n        >>> from pyspark.mllib.regression import LabeledPoint\n        >>> from pyspark.mllib.tree import DecisionTree\n        >>> from pyspark.mllib.linalg import SparseVector\n        >>>\n        >>> sparse_data = [\n        ...     LabeledPoint(0.0, SparseVector(2, {0: 0.0})),\n        ...     LabeledPoint(1.0, SparseVector(2, {1: 1.0})),\n        ...     LabeledPoint(0.0, SparseVector(2, {0: 0.0})),\n        ...     LabeledPoint(1.0, SparseVector(2, {1: 2.0}))\n        ... ]\n        >>>\n        >>> model = DecisionTree.trainRegressor(sc.parallelize(sparse_data), {})\n        >>> model.predict(SparseVector(2, {1: 1.0}))\n        1.0\n        >>> model.predict(SparseVector(2, {1: 0.0}))\n        0.0\n        >>> rdd = sc.parallelize([[0.0, 1.0], [0.0, 0.0]])\n        >>> model.predict(rdd).collect()\n        [1.0, 0.0]"
  },
  {
    "code": "def load_dependencies(req, history=None):\n    if history is None:\n        history = set()\n    dist = pkg_resources.get_distribution(req)\n    spec = dict(\n        requirement=str(req),\n        resolved=str(dist),\n    )\n    if req not in history:\n        history.add(req)\n        extras = parse_extras(req)\n        depends = [\n            load_dependencies(dep, history=history)\n            for dep in dist.requires(extras=extras)\n        ]\n        if depends:\n            spec.update(depends=depends)\n    return spec",
    "docstring": "Load the dependency tree as a Python object tree,\n    suitable for JSON serialization.\n\n    >>> deps = load_dependencies('jaraco.packaging')\n    >>> import json\n    >>> doc = json.dumps(deps)"
  },
  {
    "code": "def GUIDToStr(g):\n    try:\n        dat = uuid.UUID(bytes_le=bytes(g))\n    except:\n        dat = uuid.UUID(bytes_le=''.join(map(chr, g)))\n    return '{' + str(dat).upper() + '}'",
    "docstring": "Converts a GUID sequence of bytes into a string.\n\n    >>> GUIDToStr([103,22,79,173,  117,234,  36,65,\n    ...            132, 212, 100, 27, 59, 25, 124, 101])\n    '{AD4F1667-EA75-4124-84D4-641B3B197C65}'"
  },
  {
    "code": "def shoelace_for_area(nodes):\n    r\n    _, num_nodes = nodes.shape\n    if num_nodes == 2:\n        shoelace = SHOELACE_LINEAR\n        scale_factor = 2.0\n    elif num_nodes == 3:\n        shoelace = SHOELACE_QUADRATIC\n        scale_factor = 6.0\n    elif num_nodes == 4:\n        shoelace = SHOELACE_CUBIC\n        scale_factor = 20.0\n    elif num_nodes == 5:\n        shoelace = SHOELACE_QUARTIC\n        scale_factor = 70.0\n    else:\n        raise _helpers.UnsupportedDegree(num_nodes - 1, supported=(1, 2, 3, 4))\n    result = 0.0\n    for multiplier, index1, index2 in shoelace:\n        result += multiplier * (\n            nodes[0, index1] * nodes[1, index2]\n            - nodes[1, index1] * nodes[0, index2]\n        )\n    return result / scale_factor",
    "docstring": "r\"\"\"Compute an auxiliary \"shoelace\" sum used to compute area.\n\n    .. note::\n\n       This is a helper for :func:`_compute_area`.\n\n    Defining :math:`\\left[i, j\\right] = x_i y_j - y_i x_j` as a shoelace\n    term illuminates the name of this helper. On a degree one curve, this\n    function will return\n\n    .. math::\n\n       \\frac{1}{2}\\left[0, 1\\right].\n\n    on a degree two curve it will return\n\n    .. math::\n\n       \\frac{1}{6}\\left(2 \\left[0, 1\\right] + 2 \\left[1, 2\\right] +\n           \\left[0, 2\\right]\\right)\n\n    and so on.\n\n    For a given :math:`\\left[i, j\\right]`, the coefficient comes from\n    integrating :math:`b_{i, d}, b_{j, d}` on :math:`\\left[0, 1\\right]` (where\n    :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials).\n\n    Returns:\n        float: The computed sum of shoelace terms.\n\n    Raises:\n        .UnsupportedDegree: If the degree is not 1, 2, 3 or 4."
  },
  {
    "code": "def split_ls(func):\n    @wraps(func)\n    def wrapper(self, files, silent=True, exclude_deleted=False):\n        if not isinstance(files, (tuple, list)):\n            files = [files]\n        counter = 0\n        index = 0\n        results = []\n        while files:\n            if index >= len(files):\n                results += func(self, files, silent, exclude_deleted)\n                break\n            length = len(str(files[index]))\n            if length + counter > CHAR_LIMIT:\n                runfiles = files[:index]\n                files = files[index:]\n                counter = 0\n                index = 0\n                results += func(self, runfiles, silent, exclude_deleted)\n                runfiles = None\n                del runfiles\n            else:\n                index += 1\n                counter += length\n        return results\n    return wrapper",
    "docstring": "Decorator to split files into manageable chunks as not to exceed the windows cmd limit\n\n    :param func: Function to call for each chunk\n    :type func: :py:class:Function"
  },
  {
    "code": "def remote_chassis_id_mac_uneq_store(self, remote_chassis_id_mac):\n        if remote_chassis_id_mac != self.remote_chassis_id_mac:\n            self.remote_chassis_id_mac = remote_chassis_id_mac\n            return True\n        return False",
    "docstring": "This function saves the Chassis MAC, if different from stored."
  },
  {
    "code": "def standardise_quotes(self, val):\n        if self._in_quotes(val, self.altquote):\n            middle = self.remove_quotes(val)\n            val = self.add_quotes(middle)\n        return self.escape_quotes(val)",
    "docstring": "Change the quotes used to wrap a value to the pprint default\n        E.g. \"val\" to 'val' or 'val' to \"val\""
  },
  {
    "code": "def predict(self, X):\n        Xt, _, _ = self._transform(X)\n        return self._final_estimator.predict(Xt)",
    "docstring": "Apply transforms to the data, and predict with the final estimator\n\n        Parameters\n        ----------\n        X : iterable\n            Data to predict on. Must fulfill input requirements of first step\n            of the pipeline.\n\n        Returns\n        -------\n        yp : array-like\n            Predicted transformed target"
  },
  {
    "code": "def toggle_deriv(self, evt=None, value=None):\n        \"toggle derivative of data\"\n        if value is None:\n            self.conf.data_deriv = not self.conf.data_deriv\n            expr = self.conf.data_expr or ''\n            if self.conf.data_deriv:\n                expr = \"deriv(%s)\" % expr\n            self.write_message(\"plotting %s\" % expr, panel=0)\n            self.conf.process_data()",
    "docstring": "toggle derivative of data"
  },
  {
    "code": "def register(template_class,*extensions):\n\t\tfor ext in extensions:\n\t\t\text = normalize(ext)\n\t\t\tif not Lean.template_mappings.has_key(ext):\n\t\t\t\tLean.template_mappings[ext] = []\n\t\t\tLean.template_mappings[ext].insert(0,template_class)\n\t\t\tLean.template_mappings[ext] = unique(Lean.template_mappings[ext])",
    "docstring": "Register a template for a given extension or range of extensions"
  },
  {
    "code": "def create_hparams():\n  if FLAGS.use_tpu and \"tpu\" not in FLAGS.hparams_set:\n    tf.logging.warn(\"Not all hyperparameter sets work on TPU. \"\n                    \"Prefer hparams_sets with a '_tpu' suffix, \"\n                    \"e.g. transformer_tpu, if available for your model.\")\n  hparams_path = os.path.join(FLAGS.output_dir, \"hparams.json\")\n  return trainer_lib.create_hparams(FLAGS.hparams_set, FLAGS.hparams,\n                                    hparams_path=hparams_path)",
    "docstring": "Create hparams."
  },
  {
    "code": "def showDosHeaderData(peInstance):\n    dosFields = peInstance.dosHeader.getFields()\n    print \"[+] IMAGE_DOS_HEADER values:\\n\"\n    for field in dosFields:\n        if isinstance(dosFields[field],  datatypes.Array):\n            print \"--> %s - Array of length %d\" % (field,  len(dosFields[field]))\n            counter = 0\n            for element in dosFields[field]:\n                print \"[%d] 0x%08x\" % (counter,  element.value)\n                counter += 1\n        else:\n            print \"--> %s = 0x%08x\" % (field,  dosFields[field].value)",
    "docstring": "Prints IMAGE_DOS_HEADER fields."
  },
  {
    "code": "def consts(self):\n        consts = []\n        append_const = consts.append\n        for instr in self.instrs:\n            if isinstance(instr, LOAD_CONST) and instr.arg not in consts:\n                append_const(instr.arg)\n        return tuple(consts)",
    "docstring": "The constants referenced in this code object."
  },
  {
    "code": "def input(self):\n        if self._input is None:\n            input_file = self.environ['wsgi.input']\n            content_length = self.content_length or 0\n            self._input = WsgiInput(input_file, self.content_length)\n        return self._input",
    "docstring": "Returns a file-like object representing the request body."
  },
  {
    "code": "def readme(fname):\n    md = open(os.path.join(os.path.dirname(__file__), fname)).read()\n    output = md\n    try:\n        import pypandoc\n        output = pypandoc.convert(md, 'rst', format='md')\n    except ImportError:\n        pass\n    return output",
    "docstring": "Reads a markdown file and returns the contents formatted as rst"
  },
  {
    "code": "def get_feedback(self, question_id):\n        response = self.get_response(question_id)\n        item = self._get_item(response.get_item_id())\n        if response.is_answered():\n            try:\n                return item.get_feedback_for_response(response)\n            except errors.IllegalState:\n                pass\n        else:\n            return item.get_feedback()",
    "docstring": "get feedback for item"
  },
  {
    "code": "def precipitable_water(dewpt, pressure, bottom=None, top=None):\n    r\n    sort_inds = np.argsort(pressure)[::-1]\n    pressure = pressure[sort_inds]\n    dewpt = dewpt[sort_inds]\n    if top is None:\n        top = np.nanmin(pressure) * pressure.units\n    if bottom is None:\n        bottom = np.nanmax(pressure) * pressure.units\n    pres_layer, dewpt_layer = get_layer(pressure, dewpt, bottom=bottom, depth=bottom - top)\n    w = mixing_ratio(saturation_vapor_pressure(dewpt_layer), pres_layer)\n    pw = -1. * (np.trapz(w.magnitude, pres_layer.magnitude) * (w.units * pres_layer.units)\n                / (mpconsts.g * mpconsts.rho_l))\n    return pw.to('millimeters')",
    "docstring": "r\"\"\"Calculate precipitable water through the depth of a sounding.\n\n    Formula used is:\n\n    .. math::  -\\frac{1}{\\rho_l g} \\int\\limits_{p_\\text{bottom}}^{p_\\text{top}} r dp\n\n    from [Salby1996]_, p. 28.\n\n    Parameters\n    ----------\n    dewpt : `pint.Quantity`\n        Atmospheric dewpoint profile\n    pressure : `pint.Quantity`\n        Atmospheric pressure profile\n    bottom: `pint.Quantity`, optional\n        Bottom of the layer, specified in pressure. Defaults to None (highest pressure).\n    top: `pint.Quantity`, optional\n        The top of the layer, specified in pressure. Defaults to None (lowest pressure).\n\n    Returns\n    -------\n    `pint.Quantity`\n        The precipitable water in the layer"
  },
  {
    "code": "def _metatile_contents_equal(zip_1, zip_2):\n    names_1 = set(zip_1.namelist())\n    names_2 = set(zip_2.namelist())\n    if names_1 != names_2:\n        return False\n    for n in names_1:\n        bytes_1 = zip_1.read(n)\n        bytes_2 = zip_2.read(n)\n        if bytes_1 != bytes_2:\n            return False\n    return True",
    "docstring": "Given two open zip files as arguments, this returns True if the zips\n    both contain the same set of files, having the same names, and each\n    file within the zip is byte-wise identical to the one with the same\n    name in the other zip."
  },
  {
    "code": "def append(self, result):\n        if isinstance(result, Result):\n            self.data.append(result)\n        elif isinstance(result, ResultList):\n            self.data += result.data\n        else:\n            raise TypeError('unknown result type')",
    "docstring": "Append a new Result to the list.\n\n        :param result: Result to append\n        :return: Nothing\n        :raises: TypeError if result is not Result or ResultList"
  },
  {
    "code": "def exact_or_minor_exe_version_match(executable_name,\n                                     exe_version_tuples,\n                                     version):\n    exe = exact_exe_version_match(executable_name,\n                                  exe_version_tuples,\n                                  version)\n    if not exe:\n        exe = minor_exe_version_match(executable_name,\n                                      exe_version_tuples,\n                                      version)\n    return exe",
    "docstring": "IF there is an exact match then use it\n     OTHERWISE try to find a minor version match"
  },
  {
    "code": "def kogge_stone_add(A, B, cin=0):\n    if len(A) != len(B):\n        raise ValueError(\"expected A and B to be equal length\")\n    N = len(A)\n    gs = [A[i] & B[i] for i in range(N)]\n    ps = [A[i] ^ B[i] for i in range(N)]\n    for i in range(clog2(N)):\n        start = 1 << i\n        for j in range(start, N):\n            gs[j] = gs[j] | ps[j] & gs[j-start]\n            ps[j] = ps[j] & ps[j-start]\n    ss = [A[0] ^ B[0] ^ cin]\n    ss += [A[i] ^ B[i] ^ gs[i-1] for i in range(1, N)]\n    return farray(ss), farray(gs)",
    "docstring": "Return symbolic logic for an N-bit Kogge-Stone adder."
  },
  {
    "code": "def run_normalization(self):\n        for index, media_file in enumerate(\n                tqdm(\n                    self.media_files,\n                    desc=\"File\",\n                    disable=not self.progress,\n                    position=0\n                )):\n            logger.info(\"Normalizing file {} ({} of {})\".format(media_file, index + 1, self.file_count))\n            media_file.run_normalization()\n            logger.info(\"Normalized file written to {}\".format(media_file.output_file))",
    "docstring": "Run the normalization procedures"
  },
  {
    "code": "def stats(self):\n        data = Counter()\n        for name, value, aggregated in self.raw:\n            if aggregated:\n                data['%s.max' % name] = max(data['%s.max' % name], value)\n                data['%s.total' % name] += value\n            else:\n                data[name] = value\n        return sorted(data.items())",
    "docstring": "Stats that have been aggregated appropriately."
  },
  {
    "code": "def parse_xhtml_notes(entry):\n    for note in entry.xml_notes.itertext():\n        m = re.match(r'^([^:]+):(.+)$', note)\n        if m:\n            key, value = m.groups()\n            key = key.strip().lower().replace(' ', '_')\n            value = value.strip()\n            m = re.match(r'^\"(.*)\"$', value)\n            if m:\n                value = m.group(1)\n            if value != '':\n                yield key, value",
    "docstring": "Yield key, value pairs parsed from the XHTML notes section.\n\n    Each key, value pair must be defined in its own text block, e.g.\n    ``<p>key: value</p><p>key2: value2</p>``. The key and value must be\n    separated by a colon. Whitespace is stripped from both key and value, and\n    quotes are removed from values if present. The key is normalized by\n    conversion to lower case and spaces replaced with underscores.\n\n    Args:\n        entry: :class:`_SBMLEntry`."
  },
  {
    "code": "def confusion_matrix(self, slice_size:int=1):\n        \"Confusion matrix as an `np.ndarray`.\"\n        x=torch.arange(0,self.data.c)\n        if slice_size is None: cm = ((self.pred_class==x[:,None]) & (self.y_true==x[:,None,None])).sum(2)\n        else:\n            cm = torch.zeros(self.data.c, self.data.c, dtype=x.dtype)\n            for i in range(0, self.y_true.shape[0], slice_size):\n                cm_slice = ((self.pred_class[i:i+slice_size]==x[:,None])\n                            & (self.y_true[i:i+slice_size]==x[:,None,None])).sum(2)\n                torch.add(cm, cm_slice, out=cm)\n        return to_np(cm)",
    "docstring": "Confusion matrix as an `np.ndarray`."
  },
  {
    "code": "def tile_exists(bounds, tile_z, tile_x, tile_y):\n    mintile = mercantile.tile(bounds[0], bounds[3], tile_z)\n    maxtile = mercantile.tile(bounds[2], bounds[1], tile_z)\n    return (\n        (tile_x <= maxtile.x + 1)\n        and (tile_x >= mintile.x)\n        and (tile_y <= maxtile.y + 1)\n        and (tile_y >= mintile.y)\n    )",
    "docstring": "Check if a mercatile tile is inside a given bounds.\n\n    Attributes\n    ----------\n    bounds : list\n        WGS84 bounds (left, bottom, right, top).\n    x : int\n        Mercator tile Y index.\n    y : int\n        Mercator tile Y index.\n    z : int\n        Mercator tile ZOOM level.\n\n    Returns\n    -------\n    out : boolean\n        if True, the z-x-y mercator tile in inside the bounds."
  },
  {
    "code": "def timesync_send(self, tc1, ts1, force_mavlink1=False):\n                return self.send(self.timesync_encode(tc1, ts1), force_mavlink1=force_mavlink1)",
    "docstring": "Time synchronization message.\n\n                tc1                       : Time sync timestamp 1 (int64_t)\n                ts1                       : Time sync timestamp 2 (int64_t)"
  },
  {
    "code": "def getStateIndex(self,state):\n        statecodes = self.getStateCode(state)\n        return np.searchsorted(self.codes,statecodes).astype(int)",
    "docstring": "Returns the index of a state by calculating the state code and searching for this code a sorted list.\n        Can be called on multiple states at once."
  },
  {
    "code": "def _merge_list_of_dict(first, second, prepend=True):\n    first = _cleanup(first)\n    second = _cleanup(second)\n    if not first and not second:\n        return []\n    if not first and second:\n        return second\n    if first and not second:\n        return first\n    overlaps = []\n    merged = []\n    appended = []\n    for ele in first:\n        if _lookup_element(second, ele.keys()[0]):\n            overlaps.append(ele)\n        elif prepend:\n            merged.append(ele)\n        elif not prepend:\n            appended.append(ele)\n    for ele in second:\n        ele_key = ele.keys()[0]\n        if _lookup_element(overlaps, ele_key):\n            ele_val_first = _lookup_element(first, ele_key)\n            merged.append({ele_key: ele_val_first})\n        else:\n            merged.append(ele)\n    if not prepend:\n        merged.extend(appended)\n    return merged",
    "docstring": "Merge lists of dictionaries.\n    Each element of the list is a dictionary having one single key.\n    That key is then used as unique lookup.\n    The first element list has higher priority than the second.\n    When there's an overlap between the two lists,\n    it won't change the position, but the content."
  },
  {
    "code": "def begin(self):\n        if not self._multi_use:\n            raise ValueError(\"Cannot call 'begin' on single-use snapshots\")\n        if self._transaction_id is not None:\n            raise ValueError(\"Read-only transaction already begun\")\n        if self._read_request_count > 0:\n            raise ValueError(\"Read-only transaction already pending\")\n        database = self._session._database\n        api = database.spanner_api\n        metadata = _metadata_with_prefix(database.name)\n        txn_selector = self._make_txn_selector()\n        response = api.begin_transaction(\n            self._session.name, txn_selector.begin, metadata=metadata\n        )\n        self._transaction_id = response.id\n        return self._transaction_id",
    "docstring": "Begin a read-only transaction on the database.\n\n        :rtype: bytes\n        :returns: the ID for the newly-begun transaction.\n\n        :raises ValueError:\n            if the transaction is already begun, committed, or rolled back."
  },
  {
    "code": "def grandparent_path(self):\n        return os.path.basename(os.path.join(self.path, '../..'))",
    "docstring": "return grandparent's path string"
  },
  {
    "code": "def product(self, *products):\n        r\n        for product in products:\n            self._product.append(product)\n        return self",
    "docstring": "r\"\"\"\n            When search is called, it will limit the results to items in a Product.\n\n            :param product: items passed in will be turned into a list\n            :returns: :class:`Search`"
  },
  {
    "code": "def execute(self):\n        self.print_info()\n        if (self._config.state.prepared\n                and not self._config.command_args.get('force')):\n            msg = 'Skipping, instances already prepared.'\n            LOG.warn(msg)\n            return\n        if not self._config.provisioner.playbooks.prepare:\n            msg = 'Skipping, prepare playbook not configured.'\n            LOG.warn(msg)\n            return\n        self._config.provisioner.prepare()\n        self._config.state.change_state('prepared', True)",
    "docstring": "Execute the actions necessary to prepare the instances and returns\n        None.\n\n        :return: None"
  },
  {
    "code": "def to_pickle(self, filename):\n        with open(filename, 'wb') as f:\n            pickle.dump(self, f)",
    "docstring": "Save Camera to a pickle file, given a filename."
  },
  {
    "code": "def write_results(self, filename):\n        with self.io(filename, 'a') as fp:\n            fp.write_samples(self.samples, self.model.variable_params,\n                             last_iteration=self.niterations)\n            fp.write_samples(self.model_stats,\n                             last_iteration=self.niterations)\n            fp.write_acceptance_fraction(self._sampler.acceptance_fraction)\n            fp.write_random_state(state=self._sampler.random_state)",
    "docstring": "Writes samples, model stats, acceptance fraction, and random state\n        to the given file.\n\n        Parameters\n        -----------\n        filename : str\n            The file to write to. The file is opened using the ``io`` class\n            in an an append state."
  },
  {
    "code": "def get_lonlats(self, navid, nav_info, lon_out=None, lat_out=None):\n        lon_key = 'lon'\n        valid_min = self[lon_key + '/attr/valid_min']\n        valid_max = self[lon_key + '/attr/valid_max']\n        lon_out.data[:] = self[lon_key][::-1]\n        lon_out.mask[:] = (lon_out < valid_min) | (lon_out > valid_max)\n        lat_key = 'lat'\n        valid_min = self[lat_key + '/attr/valid_min']\n        valid_max = self[lat_key + '/attr/valid_max']\n        lat_out.data[:] = self[lat_key][::-1]\n        lat_out.mask[:] = (lat_out < valid_min) | (lat_out > valid_max)\n        return {}",
    "docstring": "Load an area."
  },
  {
    "code": "def SetColumns( self, columns, sortOrder=None ):\n        self.columns = columns \n        self.sortOrder = [(x.defaultOrder,x) for x in self.columns if x.sortDefault]\n        self.CreateColumns()",
    "docstring": "Set columns to a set of values other than the originals and recreates column controls"
  },
  {
    "code": "def _create_clone(self, parent, part, **kwargs):\n        if part.category == Category.MODEL:\n            select_action = 'clone_model'\n        else:\n            select_action = 'clone_instance'\n        data = {\n            \"part\": part.id,\n            \"parent\": parent.id,\n            \"suppress_kevents\": kwargs.pop('suppress_kevents', None)\n        }\n        query_params = kwargs\n        query_params['select_action'] = select_action\n        response = self._request('POST', self._build_url('parts'),\n                                 params=query_params,\n                                 data=data)\n        if response.status_code != requests.codes.created:\n            raise APIError(\"Could not clone part, {}: {}\".format(str(response), response.content))\n        return Part(response.json()['results'][0], client=self)",
    "docstring": "Create a new `Part` clone under the `Parent`.\n\n        .. versionadded:: 2.3\n\n        :param parent: parent part\n        :type parent: :class:`models.Part`\n        :param part: part to be cloned\n        :type part: :class:`models.Part`\n        :param kwargs: (optional) additional keyword=value arguments\n        :type kwargs: dict\n        :return: cloned :class:`models.Part`\n        :raises APIError: if the `Part` could not be cloned"
  },
  {
    "code": "def pre_state(*raw_state: GeneralState, filler: Dict[str, Any]) -> None:\n    @wraps(pre_state)\n    def _pre_state(filler: Dict[str, Any]) -> Dict[str, Any]:\n        test_name = get_test_name(filler)\n        old_pre_state = filler[test_name].get(\"pre_state\", {})\n        pre_state = normalize_state(raw_state)\n        defaults = {address: {\n            \"balance\": 0,\n            \"nonce\": 0,\n            \"code\": b\"\",\n            \"storage\": {},\n        } for address in pre_state}\n        new_pre_state = deep_merge(defaults, old_pre_state, pre_state)\n        return assoc_in(filler, [test_name, \"pre\"], new_pre_state)",
    "docstring": "Specify the state prior to the test execution. Multiple invocations don't override\n    the state but extend it instead.\n\n    In general, the elements of `state_definitions` are nested dictionaries of the following form:\n\n    .. code-block:: python\n\n        {\n            address: {\n                \"nonce\": <account nonce>,\n                \"balance\": <account balance>,\n                \"code\": <account code>,\n                \"storage\": {\n                    <storage slot>: <storage value>\n                }\n            }\n        }\n\n    To avoid unnecessary nesting especially if only few fields per account are specified, the\n    following and similar formats are possible as well:\n\n    .. code-block:: python\n\n        (address, \"balance\", <account balance>)\n        (address, \"storage\", <storage slot>, <storage value>)\n        (address, \"storage\", {<storage slot>: <storage value>})\n        (address, {\"balance\", <account balance>})"
  },
  {
    "code": "def add_text(self, reference_id, text):\n        self.add_words(reference_id, self._tokenize(text))",
    "docstring": "\\\n        Adds the words from the provided text to the corpus.\n\n        The string will be tokenized.\n\n        `reference_id`\n            The reference identifier of the cable.\n        `text`\n            An string."
  },
  {
    "code": "def copy(self, key):\n        copy = List(key, self.db)\n        copy.clear()\n        copy.extend(self)\n        return copy",
    "docstring": "Copy the list to a new list.\n\n        WARNING: If key exists, it clears it before copying."
  },
  {
    "code": "def self_aware(fn):\n    if isgeneratorfunction(fn):\n        @wraps(fn)\n        def wrapper(*a,**k):\n            generator = fn(*a,**k)\n            if hasattr(\n                generator, \n                'gi_frame'\n            ) and hasattr(\n                generator.gi_frame, \n                'f_builtins'\n            ) and hasattr(\n                generator.gi_frame.f_builtins, \n                '__setitem__'\n            ):\n                generator.gi_frame.f_builtins[\n                    'self'\n                ] = generator\n        return wrapper\n    else:\n        fn=strict_globals(**fn.__globals__)(fn)\n        fn.__globals__['self']=fn\n        return fn",
    "docstring": "decorating a function with this allows it to \n        refer to itself as 'self' inside the function\n        body."
  },
  {
    "code": "def read_image(img_spec, bkground_thresh, ensure_num_dim=3):\n    img = load_image_from_disk(img_spec)\n    if not np.issubdtype(img.dtype, np.floating):\n        img = img.astype('float32')\n    if ensure_num_dim == 3:\n        img = check_image_is_3d(img)\n    elif ensure_num_dim == 4:\n        img = check_image_is_4d(img)\n    return threshold_image(img, bkground_thresh)",
    "docstring": "Image reader, with additional checks on size.\n\n    Can optionally remove stray values close to zero (smaller than 5 %ile)."
  },
  {
    "code": "def saturation_equivalent_potential_temperature(pressure, temperature):\n    r\n    t = temperature.to('kelvin').magnitude\n    p = pressure.to('hPa').magnitude\n    e = saturation_vapor_pressure(temperature).to('hPa').magnitude\n    r = saturation_mixing_ratio(pressure, temperature).magnitude\n    th_l = t * (1000 / (p - e)) ** mpconsts.kappa\n    th_es = th_l * np.exp((3036. / t - 1.78) * r * (1 + 0.448 * r))\n    return th_es * units.kelvin",
    "docstring": "r\"\"\"Calculate saturation equivalent potential temperature.\n\n    This calculation must be given an air parcel's pressure and temperature.\n    The implementation uses the formula outlined in [Bolton1980]_ for the\n    equivalent potential temperature, and assumes a saturated process.\n\n    First, because we assume a saturated process, the temperature at the LCL is\n    equivalent to the current temperature. Therefore the following equation\n\n    .. math:: T_{L}=\\frac{1}{\\frac{1}{T_{D}-56}+\\frac{ln(T_{K}/T_{D})}{800}}+56\n\n    reduces to\n\n    .. math:: T_{L} = T_{K}\n\n    Then the potential temperature at the temperature/LCL is calculated:\n\n    .. math:: \\theta_{DL}=T_{K}\\left(\\frac{1000}{p-e}\\right)^k\n              \\left(\\frac{T_{K}}{T_{L}}\\right)^{.28r}\n\n    However, because\n\n    .. math:: T_{L} = T_{K}\n\n    it follows that\n\n    .. math:: \\theta_{DL}=T_{K}\\left(\\frac{1000}{p-e}\\right)^k\n\n    Both of these are used to calculate the final equivalent potential temperature:\n\n    .. math:: \\theta_{E}=\\theta_{DL}\\exp\\left[\\left(\\frac{3036.}{T_{K}}\n                                              -1.78\\right)*r(1+.448r)\\right]\n\n    Parameters\n    ----------\n    pressure: `pint.Quantity`\n        Total atmospheric pressure\n    temperature: `pint.Quantity`\n        Temperature of parcel\n\n    Returns\n    -------\n    `pint.Quantity`\n        The saturation equivalent potential temperature of the parcel\n\n    Notes\n    -----\n    [Bolton1980]_ formula for Theta-e is used (for saturated case), since according to\n    [DaviesJones2009]_ it is the most accurate non-iterative formulation\n    available."
  },
  {
    "code": "def execute_action_list(obj, target, kw):\n    env = obj.get_build_env()\n    kw = obj.get_kw(kw)\n    status = 0\n    for act in obj.get_action_list():\n        args = ([], [], env)\n        status = act(*args, **kw)\n        if isinstance(status, SCons.Errors.BuildError):\n            status.executor = obj\n            raise status\n        elif status:\n            msg = \"Error %s\" % status\n            raise SCons.Errors.BuildError(\n                errstr=msg, \n                node=obj.batches[0].targets,\n                executor=obj, \n                action=act)\n    return status",
    "docstring": "Actually execute the action list."
  },
  {
    "code": "def detx(self, det_id, t0set=None, calibration=None):\n        url = 'detx/{0}?'.format(det_id)\n        if t0set is not None:\n            url += '&t0set=' + t0set\n        if calibration is not None:\n            url += '&calibrid=' + calibration\n        detx = self._get_content(url)\n        return detx",
    "docstring": "Retrieve the detector file for given detector id\n\n        If t0set is given, append the calibration data."
  },
  {
    "code": "def update_lbaas_l7rule(self, l7rule, l7policy, body=None):\n        return self.put(self.lbaas_l7rule_path % (l7policy, l7rule),\n                        body=body)",
    "docstring": "Updates L7 rule."
  },
  {
    "code": "def _unpickle_panel_compat(self, state):\n        from pandas.io.pickle import _unpickle_array\n        _unpickle = _unpickle_array\n        vals, items, major, minor = state\n        items = _unpickle(items)\n        major = _unpickle(major)\n        minor = _unpickle(minor)\n        values = _unpickle(vals)\n        wp = Panel(values, items, major, minor)\n        self._data = wp._data",
    "docstring": "Unpickle the panel."
  },
  {
    "code": "def readin_volt(filename):\n    with open(filename, 'r') as fid:\n        content = np.loadtxt(fid, skiprows=1, usecols=[0, 1, 2])\n        volt = content[:, 2]\n        elecs = content[:, 0:2]\n    return elecs, volt",
    "docstring": "Read in measurement data from a volt.dat file and return electrodes and\n    measured resistance."
  },
  {
    "code": "def start(self):\n        if not self._thread:\n            logging.info(\"Starting asterisk mbox thread\")\n            try:\n                while True:\n                    self.signal.get(False)\n            except queue.Empty:\n                pass\n            self._thread = threading.Thread(target=self._loop)\n            self._thread.setDaemon(True)\n            self._thread.start()",
    "docstring": "Start thread."
  },
  {
    "code": "def __convert_env(env, encoding):\n    d = dict(os.environ, **(oget(env, {})))\n    if not SHOULD_NOT_ENCODE_ARGS:\n        return dict((k.encode(encoding), v.encode(encoding)) for k, v in d.items())\n    else:\n        return d",
    "docstring": "Environment variables should be bytes not unicode on Windows."
  },
  {
    "code": "def del_qos(self, port_name):\n        command = ovs_vsctl.VSCtlCommand(\n            'del-qos',\n            [port_name])\n        self.run_command([command])",
    "docstring": "Deletes the Qos rule on the given port."
  },
  {
    "code": "def update(self):\n        self.info.display_dataset()\n        self.overview.update()\n        self.labels.update(labels=self.info.dataset.header['chan_name'])\n        self.channels.update()\n        try:\n            self.info.markers = self.info.dataset.read_markers()\n        except FileNotFoundError:\n            lg.info('No notes/markers present in the header of the file')\n        else:\n            self.notes.update_dataset_marker()",
    "docstring": "Once you open a dataset, it activates all the widgets."
  },
  {
    "code": "def create(self,params=None, headers=None):\n        path = '/creditor_bank_accounts'\n        if params is not None:\n            params = {self._envelope_key(): params}\n        try:\n          response = self._perform_request('POST', path, params, headers,\n                                            retry_failures=True)\n        except errors.IdempotentCreationConflictError as err:\n          return self.get(identity=err.conflicting_resource_id,\n                          params=params,\n                          headers=headers)\n        return self._resource_for(response)",
    "docstring": "Create a creditor bank account.\n\n        Creates a new creditor bank account object.\n\n        Args:\n              params (dict, optional): Request body.\n\n        Returns:\n              ListResponse of CreditorBankAccount instances"
  },
  {
    "code": "def get_notebook_url(self):\n        url = self._client._build_url('service_execution_notebook_url', service_execution_id=self.id)\n        response = self._client._request('GET', url, params=dict(format='json'))\n        if response.status_code != requests.codes.ok:\n            raise APIError(\"Could not retrieve notebook url '{}': {}\".format(self, response))\n        data = response.json()\n        url = data.get('results')[0].get('url')\n        return url",
    "docstring": "Get the url of the notebook, if the notebook is executed in interactive mode.\n\n        .. versionadded:: 1.13\n\n        :return: full url to the interactive running notebook as `basestring`\n        :raises APIError: when the url cannot be retrieved."
  },
  {
    "code": "def union_overlapping(intervals):\n    disjoint_intervals = []\n    for interval in intervals:\n        if disjoint_intervals and disjoint_intervals[-1].overlaps(interval):\n            disjoint_intervals[-1] = disjoint_intervals[-1].union(interval)\n        else:\n            disjoint_intervals.append(interval)\n    return disjoint_intervals",
    "docstring": "Union any overlapping intervals in the given set."
  },
  {
    "code": "def from_url(cls, db_url=ALL_SETS_ZIP_URL):\n        r = requests.get(db_url)\n        r.raise_for_status()\n        if r.headers['content-type'] == 'application/json':\n            return cls(json.loads(r.text))\n        if r.headers['content-type'] == 'application/zip':\n            with zipfile.ZipFile(six.BytesIO(r.content), 'r') as zf:\n                names = zf.namelist()\n                assert len(names) == 1, 'One datafile in ZIP'\n                return cls.from_file(io.TextIOWrapper(\n                    zf.open(names[0]),\n                    encoding='utf8'))",
    "docstring": "Load card data from a URL.\n\n        Uses :func:`requests.get` to fetch card data. Also handles zipfiles.\n\n        :param db_url: URL to fetch.\n        :return: A new :class:`~mtgjson.CardDb` instance."
  },
  {
    "code": "def _delete(self, *criterion):\n        with self.flushing():\n            count = self._query(*criterion).delete()\n        if count == 0:\n            raise ModelNotFoundError\n        return True",
    "docstring": "Delete a model by some criterion.\n\n        Avoids race-condition check-then-delete logic by checking the count of affected rows.\n\n        :raises `ResourceNotFound` if the row cannot be deleted."
  },
  {
    "code": "def _AddEdge(self, start_node, end_node):\n    self.graph[start_node].outgoing.append(end_node)\n    if end_node in self.graph:\n      self.graph[end_node].incoming.append(start_node)",
    "docstring": "Add a directed edge to the graph.\n\n    Add the end to the list of outgoing nodes of the start and the start to the\n    list of incoming nodes of the end node.\n\n    Args:\n      start_node: name of the start node\n      end_node: name of the end node"
  },
  {
    "code": "def worker_loop_v1(dataset, key_queue, data_queue, batchify_fn):\n    while True:\n        idx, samples = key_queue.get()\n        if idx is None:\n            break\n        batch = batchify_fn([dataset[i] for i in samples])\n        data_queue.put((idx, batch))",
    "docstring": "Worker loop for multiprocessing DataLoader."
  },
  {
    "code": "def drop_all(self):\n        self.drop(self.get_table_names())\n        if self.persistent:\n            with self._lock:\n                try:\n                    dbfolder = os.path.join(self.root_dir, self.name)\n                    if os.path.exists(dbfolder) and not os.listdir(dbfolder):\n                        rmtree(dbfolder)\n                except (IOError, WindowsError):\n                    self._print('Failed to delete folder %s when dropping database' % self.name)\n                finally:\n                    del self",
    "docstring": "Drops all tables from this database"
  },
  {
    "code": "def login(self, **kwargs):\n    if 'signed_username' in kwargs:\n      apiToken = kwargs['signed_username']\n      if kwargs.get('authenticate', False):\n        self._checkReturn(requests.get(\"{}/users?signed_username={}\".format(self.url, apiToken)))\n      self.signedUsername = apiToken\n    else:\n      auth = (kwargs['user_id'], kwargs['token'])\n      self.signedUsername = self._checkReturn(requests.get(\"{}/users/login\".format(self.url), auth=auth))[\n        'signed_username']",
    "docstring": "Logs the current user into the server with the passed in credentials. If successful the apiToken will be changed to match the passed in credentials.\n\n    :param apiToken: use the passed apiToken to authenticate\n    :param user_id: optional instead of apiToken, must be passed with token\n    :param token: optional instead of apiToken, must be passed with user_id\n    :param authenticate: only valid with apiToken. Force a call to the server to authenticate the passed credentials.\n    :return:"
  },
  {
    "code": "def copy(self):\n        result = copy.deepcopy(self)\n        result._cache.clear()\n        return result",
    "docstring": "Return a copy of the Primitive object."
  },
  {
    "code": "def process_unknown_arguments(unknowns):\n    result = argparse.Namespace()\n    result.extra_control = {}\n    for unknown in unknowns:\n        prefix = '--parameter-'\n        if unknown.startswith(prefix):\n            values = unknown.split('=')\n            if len(values) == 2:\n                key = values[0][len(prefix):]\n                val = values[1]\n                if key:\n                    result.extra_control[key] = val\n    return result",
    "docstring": "Process arguments unknown to the parser"
  },
  {
    "code": "def _handle_subscription(self, topics):\n        if not isinstance(topics, list):\n            topics = [topics]\n        for topic in topics:\n            topic_levels = topic.split('/')\n            try:\n                qos = int(topic_levels[-2])\n            except ValueError:\n                qos = 0\n            try:\n                _LOGGER.debug('Subscribing to: %s, qos: %s', topic, qos)\n                self._sub_callback(topic, self.recv, qos)\n            except Exception as exception:\n                _LOGGER.exception(\n                    'Subscribe to %s failed: %s', topic, exception)",
    "docstring": "Handle subscription of topics."
  },
  {
    "code": "def get_observation(observation_id: int) -> Dict[str, Any]:\n    r = get_observations(params={'id': observation_id})\n    if r['results']:\n        return r['results'][0]\n    raise ObservationNotFound()",
    "docstring": "Get details about an observation.\n\n    :param observation_id:\n    :returns: a dict with details on the observation\n    :raises: ObservationNotFound"
  },
  {
    "code": "def _boundary_value(self) -> str:\n        value = self._boundary\n        if re.match(self._valid_tchar_regex, value):\n            return value.decode('ascii')\n        if re.search(self._invalid_qdtext_char_regex, value):\n            raise ValueError(\"boundary value contains invalid characters\")\n        quoted_value_content = value.replace(b'\\\\', b'\\\\\\\\')\n        quoted_value_content = quoted_value_content.replace(b'\"', b'\\\\\"')\n        return '\"' + quoted_value_content.decode('ascii') + '\"'",
    "docstring": "Wrap boundary parameter value in quotes, if necessary.\n\n        Reads self.boundary and returns a unicode sting."
  },
  {
    "code": "def _marshal_claims(self, query_claims):\n        claims = reduce_claims(query_claims)\n        self.data['claims'] = claims\n        entities = set()\n        for eid in claims:\n            if self.user_labels:\n                if eid in self.user_labels or eid == 'P31':\n                    entities.add(eid)\n                else:\n                    continue\n            else:\n                entities.add(eid)\n            for val in claims[eid]:\n                if utils.is_text(val) and re.match(r'^Q\\d+$', val):\n                    entities.add(val)\n        self.data['entities'] = list(entities)",
    "docstring": "set Wikidata entities from query claims"
  },
  {
    "code": "def entries_published(queryset):\n    now = timezone.now()\n    return queryset.filter(\n        models.Q(start_publication__lte=now) |\n        models.Q(start_publication=None),\n        models.Q(end_publication__gt=now) |\n        models.Q(end_publication=None),\n        status=PUBLISHED, sites=Site.objects.get_current())",
    "docstring": "Return only the entries published."
  },
  {
    "code": "def get_last_version(self, filename):\n        def ok(doc):\n            if doc is None:\n                raise NoFile(\"TxMongo: no file in gridfs with filename {0}\".format(repr(filename)))\n            return GridOut(self.__collection, doc)\n        return self.__files.find_one({\"filename\": filename},\n                                     filter = filter.sort(DESCENDING(\"uploadDate\"))).addCallback(ok)",
    "docstring": "Get a file from GridFS by ``\"filename\"``.\n\n        Returns the most recently uploaded file in GridFS with the\n        name `filename` as an instance of\n        :class:`~gridfs.grid_file.GridOut`. Raises\n        :class:`~gridfs.errors.NoFile` if no such file exists.\n\n        An index on ``{filename: 1, uploadDate: -1}`` will\n        automatically be created when this method is called the first\n        time.\n\n        :Parameters:\n          - `filename`: ``\"filename\"`` of the file to get\n\n        .. versionadded:: 1.6"
  },
  {
    "code": "def _users_watching(self, **kwargs):\n        return self._users_watching_by_filter(object_id=self.instance.pk,\n                                              **kwargs)",
    "docstring": "Return users watching this instance."
  },
  {
    "code": "def _download_raw(self, url=None):\n        if url is None:\n            url = self.url\n        req = request.Request(url, headers=self.HEADERS_PLAIN)\n        return request.urlopen(req).read().decode(\"utf8\")",
    "docstring": "Download content from URL directly."
  },
  {
    "code": "def configuration_list_all(self, environment_id):\n        data = dict()\n        data[\"environment_id\"] = environment_id\n        url = (\"environment/configuration/list/%(environment_id)s/\" % data)\n        code, xml = self.submit(None, 'GET', url)\n        return self.response(code, xml, force_list=['lists_configuration'])",
    "docstring": "List all prefix configurations by environment in DB\n\n        :return: Following dictionary:\n\n        ::\n\n            {'lists_configuration': [{\n            'id': <id_ipconfig>,\n            'subnet': <subnet>,\n            'type': <type>,\n            'new_prefix': <new_prefix>,\n            }, ... ]}\n\n\n        :raise InvalidValueError: Invalid ID for Environment.\n        :raise AmbienteNotFoundError: Environment not registered.\n        :raise DataBaseError: Failed into networkapi access data base.\n        :raise XMLError: Networkapi failed to generate the XML response."
  },
  {
    "code": "def delete(self):\n        config = self.get()\n        if not config:\n            return True\n        command = 'no router ospf {}'.format(config['ospf_process_id'])\n        return self.configure(command)",
    "docstring": "Removes the entire ospf process from the running configuration\n\n           Args:\n               None\n           Returns:\n               bool: True if the command completed succssfully"
  },
  {
    "code": "def convert_html_entities(text_string):\n    if text_string is None or text_string == \"\":\n        return \"\"\n    elif isinstance(text_string, str):\n        return html.unescape(text_string).replace(\"&quot;\", \"'\")\n    else:\n        raise InputError(\"string not passed as argument for text_string\")",
    "docstring": "Converts HTML5 character references within text_string to their corresponding unicode characters\n    and returns converted string as type str.\n\n    Keyword argument:\n\n    - text_string: string instance\n\n    Exceptions raised:\n\n    - InputError: occurs should a non-string argument be passed"
  },
  {
    "code": "def markup_join(seq):\n    buf = []\n    iterator = imap(soft_unicode, seq)\n    for arg in iterator:\n        buf.append(arg)\n        if hasattr(arg, '__html__'):\n            return Markup(u'').join(chain(buf, iterator))\n    return concat(buf)",
    "docstring": "Concatenation that escapes if necessary and converts to unicode."
  },
  {
    "code": "def b64decode(foo, *args):\n    'Only here for consistency with the above.'\n    if isinstance(foo, str):\n        foo = foo.encode('utf8')\n    return base64.b64decode(foo, *args)",
    "docstring": "Only here for consistency with the above."
  },
  {
    "code": "def update_work_as_completed(self, worker_id, work_id, other_values=None,\n                               error=None):\n    client = self._datastore_client\n    try:\n      with client.transaction() as transaction:\n        work_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id,\n                              KIND_WORK, work_id)\n        work_entity = client.get(work_key, transaction=transaction)\n        if work_entity['claimed_worker_id'] != worker_id:\n          return False\n        work_entity['is_completed'] = True\n        if other_values:\n          work_entity.update(other_values)\n        if error:\n          work_entity['error'] = text_type(error)\n        transaction.put(work_entity)\n    except Exception:\n      return False\n    return True",
    "docstring": "Updates work piece in datastore as completed.\n\n    Args:\n      worker_id: ID of the worker which did the work\n      work_id: ID of the work which was done\n      other_values: dictionary with additonal values which should be saved\n        with the work piece\n      error: if not None then error occurred during computation of the work\n        piece. In such case work will be marked as completed with error.\n\n    Returns:\n      whether work was successfully updated"
  },
  {
    "code": "def set_shortcut(self, name, shortcut):\n        name = self.__normalize_name(name)\n        action = self.get_action(name)\n        if not action:\n            return\n        action.setShortcut(QKeySequence(shortcut))\n        return True",
    "docstring": "Sets given action shortcut.\n\n        :param name: Action to set the shortcut.\n        :type name: unicode\n        :param shortcut: Shortcut to set.\n        :type shortcut: unicode\n        :return: Method success.\n        :rtype: bool"
  },
  {
    "code": "def fetchJobStoreFiles(jobStore, options):\n    for jobStoreFile in options.fetch:\n        jobStoreHits = recursiveGlob(directoryname=options.jobStore,\n                                     glob_pattern=jobStoreFile)\n        for jobStoreFileID in jobStoreHits:\n            logger.debug(\"Copying job store file: %s to %s\",\n                        jobStoreFileID,\n                        options.localFilePath[0])\n            jobStore.readFile(jobStoreFileID,\n                              os.path.join(options.localFilePath[0],\n                              os.path.basename(jobStoreFileID)),\n                              symlink=options.useSymlinks)",
    "docstring": "Takes a list of file names as glob patterns, searches for these within a\n    given directory, and attempts to take all of the files found and copy them\n    into options.localFilePath.\n\n    :param jobStore: A fileJobStore object.\n    :param options.fetch: List of file glob patterns to search\n        for in the jobStore and copy into options.localFilePath.\n    :param options.localFilePath: Local directory to copy files into.\n    :param options.jobStore: The path to the jobStore directory."
  },
  {
    "code": "def get_service_name(*args):\n    raw_services = _get_services()\n    services = dict()\n    for raw_service in raw_services:\n        if args:\n            if raw_service['DisplayName'] in args or \\\n                    raw_service['ServiceName'] in args or \\\n                    raw_service['ServiceName'].lower() in args:\n                services[raw_service['DisplayName']] = raw_service['ServiceName']\n        else:\n            services[raw_service['DisplayName']] = raw_service['ServiceName']\n    return services",
    "docstring": "The Display Name is what is displayed in Windows when services.msc is\n    executed.  Each Display Name has an associated Service Name which is the\n    actual name of the service.  This function allows you to discover the\n    Service Name by returning a dictionary of Display Names and Service Names,\n    or filter by adding arguments of Display Names.\n\n    If no args are passed, return a dict of all services where the keys are the\n    service Display Names and the values are the Service Names.\n\n    If arguments are passed, create a dict of Display Names and Service Names\n\n    Returns:\n        dict: A dictionary of display names and service names\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt '*' service.get_service_name\n        salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client'"
  },
  {
    "code": "def _identify_all(header, footer, ext=None):\n    matches = list()\n    for magic_row in magic_header_array:\n        start = magic_row.offset\n        end = magic_row.offset + len(magic_row.byte_match)\n        if end > len(header):\n            continue\n        if header[start:end] == magic_row.byte_match:\n            matches.append(magic_row)\n    for magic_row in magic_footer_array:\n        start = magic_row.offset\n        if footer[start:] == magic_row.byte_match:\n            matches.append(magic_row)\n    if not matches:\n        raise PureError(\"Could not identify file\")\n    return _confidence(matches, ext)",
    "docstring": "Attempt to identify 'data' by its magic numbers"
  },
  {
    "code": "def do_list(self, line):\n        repo_names = self.network.repo_names\n        print('Known repos:')\n        print('    ' + '\\n    '.join(repo_names))",
    "docstring": "List known repos"
  },
  {
    "code": "def create_version_model(self, task, releasetype, descriptor):\n        rootdata = treemodel.ListItemData(['Version', 'Releasetype', 'Path'])\n        rootitem = treemodel.TreeItem(rootdata)\n        for tf in task.taskfile_set.filter(releasetype=releasetype, descriptor=descriptor).order_by('-version'):\n            tfdata = djitemdata.TaskFileItemData(tf)\n            tfitem = treemodel.TreeItem(tfdata, rootitem)\n            for note in tf.notes.all():\n                notedata = djitemdata.NoteItemData(note)\n                treemodel.TreeItem(notedata, tfitem)\n        versionmodel = treemodel.TreeModel(rootitem)\n        return versionmodel",
    "docstring": "Create and return a new model that represents taskfiles for the given task, releasetpye and descriptor\n\n        :param task: the task of the taskfiles\n        :type task: :class:`djadapter.models.Task`\n        :param releasetype: the releasetype\n        :type releasetype: str\n        :param descriptor: the descirptor\n        :type descriptor: str|None\n        :returns: the created tree model\n        :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel`\n        :raises: None"
  },
  {
    "code": "def _dict_to_report_line(cls, report_dict):\n        return '\\t'.join([str(report_dict[x]) for x in report.columns])",
    "docstring": "Takes a report_dict as input and returns a report line"
  },
  {
    "code": "def append_rally_point(self, p):\n        if (self.rally_count() > 9):\n           print(\"Can't have more than 10 rally points, not adding.\")\n           return\n        self.rally_points.append(p)\n        self.reindex()",
    "docstring": "add rallypoint to end of list"
  },
  {
    "code": "def issuetypes(accountable, project_key):\n    projects = accountable.issue_types(project_key)\n    headers = sorted(['id', 'name', 'description'])\n    rows = []\n    for key, issue_types in sorted(projects.items()):\n        for issue_type in issue_types:\n            rows.append(\n                [key] + [v for k, v in sorted(issue_type.items())\n                         if k in headers]\n            )\n    rows.insert(0, ['project_key'] + headers)\n    print_table(SingleTable(rows))",
    "docstring": "List all issue types. Optional parameter to list issue types by a given\n    project."
  },
  {
    "code": "def _scalar2array(d):\n    da = {}\n    for k, v in d.items():\n        if '_' not in k:\n            da[k] = v\n        else:\n            name = ''.join(k.split('_')[:-1])\n            ind = k.split('_')[-1]\n            dim = len(ind)\n            if name not in da:\n                shape = tuple(3 for i in range(dim))\n                da[name] = np.empty(shape, dtype=complex)\n                da[name][:] = np.nan\n            da[name][tuple(int(i) - 1 for i in ind)] = v\n    return da",
    "docstring": "Convert a dictionary with scalar elements and string indices '_1234'\n    to a dictionary of arrays. Unspecified entries are np.nan."
  },
  {
    "code": "def ensure_file(path):\n        try:\n            exists = isfile(path)\n            if not exists:\n                with open(path, 'w+') as fname:\n                    fname.write('initialized')\n                return (True, path)\n            return (True, 'exists')\n        except OSError as e:\n            return (False, e)",
    "docstring": "Checks if file exists, if fails, tries to create file"
  },
  {
    "code": "def _get_keycache(self, parentity, branch, turn, tick, *, forward):\n        lru_append(self.keycache, self._kc_lru, (parentity+(branch,), turn, tick), KEYCACHE_MAXSIZE)\n        return self._get_keycachelike(\n            self.keycache, self.keys, self._get_adds_dels,\n            parentity, branch, turn, tick, forward=forward\n        )",
    "docstring": "Get a frozenset of keys that exist in the entity at the moment.\n\n        With ``forward=True``, enable an optimization that copies old key sets\n        forward and updates them."
  },
  {
    "code": "def write_pruned_iocs(self, directory=None, pruned_source=None):\n        if pruned_source is None:\n            pruned_source = self.pruned_11_iocs\n        if len(pruned_source) < 1:\n            log.error('no iocs available to write out')\n            return False\n        if not directory:\n            directory = os.getcwd()\n        if os.path.isfile(directory):\n            log.error('cannot writes iocs to a directory')\n            return False\n        utils.safe_makedirs(directory)\n        output_dir = os.path.abspath(directory)\n        for iocid in pruned_source:\n            ioc_obj = self.iocs_10[iocid]\n            ioc_obj.write_ioc_to_file(output_dir=output_dir, force=True)\n        return True",
    "docstring": "Writes IOCs to a directory that have been pruned of some or all IOCs.\n\n        :param directory: Directory to write IOCs to.  If not provided, the current working directory is used.\n        :param pruned_source: Iterable containing a set of iocids.  Defaults to self.iocs_10.\n        :return:"
  },
  {
    "code": "def update(self):\n        for node in self.get_all_nodes():\n            try:\n                node.update_ips()\n                if node.ips and \\\n                        not (node.preferred_ip and \\\n                                         node.preferred_ip in node.ips):\n                    node.connect()\n            except InstanceError as ex:\n                log.warning(\"Ignoring error updating information on node %s: %s\",\n                            node, ex)\n        self.repository.save_or_update(self)",
    "docstring": "Update connection information of all nodes in this cluster.\n\n        It happens, for example, that public ip's are not available\n        immediately, therefore calling this method might help."
  },
  {
    "code": "def run(config, clear_opt=False):\n    flickr = flickrapi.FlickrAPI(config.get('walls', 'api_key'),\n                                 config.get('walls', 'api_secret'))\n    width = config.getint('walls', 'width')\n    height = config.getint('walls', 'height')\n    if clear_opt:\n        clear_dir(os.path.expanduser(config.get('walls', 'image_dir')))\n    tags = config.get('walls', 'tags')\n    for photo in flickr.walk(tags=tags, format='etree'):\n        try:\n            photo_url = smallest_url(flickr, photo.get('id'), width, height)\n            if photo_url:\n                break\n        except (KeyError, ValueError, TypeError):\n            stderr_and_exit('Unexpected data from Flickr.\\n')\n    else:\n        stderr_and_exit('No matching photos found.\\n')\n    dest = os.path.expanduser(config.get('walls', 'image_dir'))\n    try:\n        download(photo_url, dest)\n    except IOError:\n        stderr_and_exit('Error downloading image.\\n')",
    "docstring": "Find an image and download it."
  },
  {
    "code": "def get_all_snapshots(self, snapshot_ids=None,\n                          owner=None, restorable_by=None,\n                          filters=None):\n        params = {}\n        if snapshot_ids:\n            self.build_list_params(params, snapshot_ids, 'SnapshotId')\n        if owner:\n            params['Owner'] = owner\n        if restorable_by:\n            params['RestorableBy'] = restorable_by\n        if filters:\n            self.build_filter_params(params, filters)\n        return self.get_list('DescribeSnapshots', params,\n                             [('item', Snapshot)], verb='POST')",
    "docstring": "Get all EBS Snapshots associated with the current credentials.\n\n        :type snapshot_ids: list\n        :param snapshot_ids: Optional list of snapshot ids.  If this list is\n                             present, only the Snapshots associated with\n                             these snapshot ids will be returned.\n\n        :type owner: str\n        :param owner: If present, only the snapshots owned by the specified user\n                      will be returned.  Valid values are:\n\n                      * self\n                      * amazon\n                      * AWS Account ID\n\n        :type restorable_by: str\n        :param restorable_by: If present, only the snapshots that are restorable\n                              by the specified account id will be returned.\n\n        :type filters: dict\n        :param filters: Optional filters that can be used to limit\n                        the results returned.  Filters are provided\n                        in the form of a dictionary consisting of\n                        filter names as the key and filter values\n                        as the value.  The set of allowable filter\n                        names/values is dependent on the request\n                        being performed.  Check the EC2 API guide\n                        for details.\n\n        :rtype: list of :class:`boto.ec2.snapshot.Snapshot`\n        :return: The requested Snapshot objects"
  },
  {
    "code": "def _ostaunicode(src):\n    if have_py_3:\n        bytename = src\n    else:\n        bytename = src.decode('utf-8')\n    try:\n        enc = bytename.encode('latin-1')\n        encbyte = b'\\x08'\n    except (UnicodeEncodeError, UnicodeDecodeError):\n        enc = bytename.encode('utf-16_be')\n        encbyte = b'\\x10'\n    return encbyte + enc",
    "docstring": "Internal function to create an OSTA byte string from a source string."
  },
  {
    "code": "def virtual_temperature(temperature, mixing, molecular_weight_ratio=mpconsts.epsilon):\n    r\n    return temperature * ((mixing + molecular_weight_ratio)\n                          / (molecular_weight_ratio * (1 + mixing)))",
    "docstring": "r\"\"\"Calculate virtual temperature.\n\n    This calculation must be given an air parcel's temperature and mixing ratio.\n    The implementation uses the formula outlined in [Hobbs2006]_ pg.80.\n\n    Parameters\n    ----------\n    temperature: `pint.Quantity`\n        The temperature\n    mixing : `pint.Quantity`\n        dimensionless mass mixing ratio\n    molecular_weight_ratio : `pint.Quantity` or float, optional\n        The ratio of the molecular weight of the constituent gas to that assumed\n        for air. Defaults to the ratio for water vapor to dry air.\n        (:math:`\\epsilon\\approx0.622`).\n\n    Returns\n    -------\n    `pint.Quantity`\n        The corresponding virtual temperature of the parcel\n\n    Notes\n    -----\n    .. math:: T_v = T \\frac{\\text{w} + \\epsilon}{\\epsilon\\,(1 + \\text{w})}"
  },
  {
    "code": "def check_validation(self, cert):\n        if self.certificate_registry.is_ca(cert) and cert.signature not in self._validate_map:\n            self._validate_map[cert.signature] = ValidationPath(cert)\n        return self._validate_map.get(cert.signature)",
    "docstring": "Checks to see if a certificate has been validated, and if so, returns\n        the ValidationPath used to validate it.\n\n        :param cert:\n            An asn1crypto.x509.Certificate object\n\n        :return:\n            None if not validated, or a certvalidator.path.ValidationPath\n            object of the validation path"
  },
  {
    "code": "def gene_list(self, list_id):\n        return self.query(GeneList).filter_by(list_id=list_id).first()",
    "docstring": "Get a gene list from the database."
  },
  {
    "code": "def build_news(ctx, draft=False, yes=False):\n    report.info(ctx, \"docs.build-news\", \"building changelog from news fragments\")\n    build_command = f\"towncrier --version {ctx.metadata['version']}\"\n    if draft:\n        report.warn(\n            ctx,\n            \"docs.build-news\",\n            \"building changelog as draft (results are written to stdout)\",\n        )\n        build_command += \" --draft\"\n    elif yes:\n        report.warn(\n            ctx, \"docs.build-news\", \"removing news files without user confirmation (-y)\"\n        )\n        build_command += \" --yes\"\n    ctx.run(build_command, hide=None)",
    "docstring": "Build towncrier newsfragments."
  },
  {
    "code": "def reset(self):\n        for shard_id in self._shards:\n            if self._shards[shard_id].get('isReplicaSet'):\n                singleton = ReplicaSets()\n            elif self._shards[shard_id].get('isServer'):\n                singleton = Servers()\n            singleton.command(self._shards[shard_id]['_id'], 'reset')\n        for config_id in self._configsvrs:\n            self.configdb_singleton.command(config_id, 'reset')\n        for router_id in self._routers:\n            Servers().command(router_id, 'reset')\n        return self.info()",
    "docstring": "Ensure all shards, configs, and routers are running and available."
  },
  {
    "code": "def connect(self, host, port, name=None):\n        client = self._clients.get(name)\n        client.connect_to(host, port)",
    "docstring": "Connects a client to given `host` and `port`. If client `name` is not\n        given then connects the latest client.\n\n        Examples:\n        | Connect | 127.0.0.1 | 8080 |\n        | Connect | 127.0.0.1 | 8080 | Client1 |"
  },
  {
    "code": "def count(self, eventRegistry):\n        self.setRequestedResult(RequestEventsInfo())\n        res = eventRegistry.execQuery(self)\n        if \"error\" in res:\n            print(res[\"error\"])\n        count = res.get(\"events\", {}).get(\"totalResults\", 0)\n        return count",
    "docstring": "return the number of events that match the criteria"
  },
  {
    "code": "def new(self, dev_t_high, dev_t_low):\n        if self._initialized:\n            raise pycdlibexception.PyCdlibInternalError('PN record already initialized!')\n        self.dev_t_high = dev_t_high\n        self.dev_t_low = dev_t_low\n        self._initialized = True",
    "docstring": "Create a new Rock Ridge POSIX device number record.\n\n        Parameters:\n         dev_t_high - The high-order 32-bits of the device number.\n         dev_t_low - The low-order 32-bits of the device number.\n        Returns:\n         Nothing."
  },
  {
    "code": "def extract_image_size(self):\n        width, _ = self._extract_alternative_fields(\n            ['Image ImageWidth', 'EXIF ExifImageWidth'], -1, int)\n        height, _ = self._extract_alternative_fields(\n            ['Image ImageLength', 'EXIF ExifImageLength'], -1, int)\n        return width, height",
    "docstring": "Extract image height and width"
  },
  {
    "code": "def export_file(file_path):\n    if not os.path.isfile(file_path):\n        return error(\"Referenced file does not exist: '{}'.\".format(file_path))\n    return \"export {}\".format(file_path)",
    "docstring": "Prepend the given parameter with ``export``"
  },
  {
    "code": "def make_archive(self, path):\n        zf = zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED)\n        for dirpath, dirnames, filenames in os.walk(self.path):\n            relative_path = dirpath[len(self.path) + 1:]\n            if relative_path and not self._ignore(relative_path):\n                zf.write(dirpath, relative_path)\n            for name in filenames:\n                archive_name = os.path.join(relative_path, name)\n                if not self._ignore(archive_name):\n                    real_path = os.path.join(dirpath, name)\n                    self._check_type(real_path)\n                    if os.path.islink(real_path):\n                        self._check_link(real_path)\n                        self._write_symlink(\n                            zf, os.readlink(real_path), archive_name)\n                    else:\n                        zf.write(real_path, archive_name)\n        zf.close()\n        return path",
    "docstring": "Create archive of directory and write to ``path``.\n\n        :param path: Path to archive\n\n        Ignored::\n\n            * build/* - This is used for packing the charm itself and any\n                          similar tasks.\n            * */.*    - Hidden files are all ignored for now.  This will most\n                          likely be changed into a specific ignore list\n                          (.bzr, etc)"
  },
  {
    "code": "def timescales_(self):\n        u, lv, rv = self._get_eigensystem()\n        with np.errstate(invalid='ignore', divide='ignore'):\n            timescales = - self.lag_time / np.log(u[1:])\n        return timescales",
    "docstring": "Implied relaxation timescales of the model.\n\n        The relaxation of any initial distribution towards equilibrium is\n        given, according to this model, by a sum of terms -- each corresponding\n        to the relaxation along a specific direction (eigenvector) in state\n        space -- which decay exponentially in time. See equation 19. from [1].\n\n        Returns\n        -------\n        timescales : array-like, shape = (n_timescales,)\n            The longest implied relaxation timescales of the model, expressed\n            in units of time-step between indices in the source data supplied\n            to ``fit()``.\n\n        References\n        ----------\n        .. [1] Prinz, Jan-Hendrik, et al. \"Markov models of molecular kinetics:\n        Generation and validation.\" J. Chem. Phys. 134.17 (2011): 174105."
  },
  {
    "code": "def get_remote_info(url_id):\n    try:\n        data = _send_request(url_id)\n    except Exception as e:\n        sys.stderr.write(\"Seeder GET error: \")\n        sys.stderr.write(str(e.message))\n        return None\n    return _convert_to_wakat_format(data)",
    "docstring": "Download data and convert them to dict used in frontend.\n\n    Args:\n        url_id (str): ID used as identification in Seeder.\n\n    Returns:\n        dict: Dict with data for frontend or None in case of error."
  },
  {
    "code": "def update(self, item):\n        self.model.set(self._iter_for(item), 0, item)",
    "docstring": "Manually update an item's display in the list\n\n        :param item: The item to be updated."
  },
  {
    "code": "def render_js_code(self, id_, *args, **kwargs):\n        if id_:\n            options = self.render_select2_options_code(\n                    dict(self.get_options()), id_)\n            return mark_safe(self.html.format(id=id_, options=options))\n        return u''",
    "docstring": "Render html container for Select2 widget with options."
  },
  {
    "code": "def wildcard_allowed_principals(self, pattern=None):\n        wildcard_allowed = []\n        for statement in self.statements:\n            if statement.wildcard_principals(pattern) and statement.effect == \"Allow\":\n                wildcard_allowed.append(statement)\n        return wildcard_allowed",
    "docstring": "Find statements which allow wildcard principals.\n\n        A pattern can be specified for the wildcard principal"
  },
  {
    "code": "def to_content_range_header(self, length):\n        range_for_length = self.range_for_length(length)\n        if range_for_length is not None:\n            return \"%s %d-%d/%d\" % (\n                self.units,\n                range_for_length[0],\n                range_for_length[1] - 1,\n                length,\n            )\n        return None",
    "docstring": "Converts the object into `Content-Range` HTTP header,\n        based on given length"
  },
  {
    "code": "def _concat(self, egdfs):\n        egdfs = list(egdfs)\n        edata = pd.concat(egdfs, axis=0, ignore_index=False, copy=False)\n        one2one = (\n            self.keep_index and\n            not any(edata.index.duplicated()) and\n            len(edata.index) == len(self.data.index))\n        if one2one:\n            edata = edata.sort_index()\n        else:\n            edata.reset_index(drop=True, inplace=True)\n        if self.keep_groups and self.groups:\n            edata = GroupedDataFrame(edata, groups=self.groups)\n        return edata",
    "docstring": "Concatenate evaluated group dataframes\n\n        Parameters\n        ----------\n        egdfs : iterable\n            Evaluated dataframes\n\n        Returns\n        -------\n        edata : pandas.DataFrame\n            Evaluated data"
  },
  {
    "code": "async def get_state_json(\n            self,\n            rr_state_builder: Callable[['Verifier', str, int], Awaitable[Tuple[str, int]]],\n            fro: int,\n            to: int) -> (str, int):\n        LOGGER.debug(\n            'RevoCacheEntry.get_state_json >>> rr_state_builder: %s, fro: %s, to: %s',\n            rr_state_builder.__name__,\n            fro,\n            to)\n        rv = await self._get_update(rr_state_builder, fro, to, False)\n        LOGGER.debug('RevoCacheEntry.get_state_json <<< %s', rv)\n        return rv",
    "docstring": "Get rev reg state json, and its timestamp on the distributed ledger,\n        from cached rev reg state frames list or distributed ledger,\n        updating cache as necessary.\n\n        Raise BadRevStateTime if caller asks for a state in the future.\n\n        On return of any previously existing rev reg state frame, always update its query time beforehand.\n\n        :param rr_state_builder: callback to build rev reg state if need be (specify anchor instance's\n            _build_rr_state())\n        :param fro: least time (epoch seconds) of interest; lower-bounds 'to' on frame housing return data\n        :param to: greatest time (epoch seconds) of interest; upper-bounds returned revocation state timestamp\n        :return: rev reg state json and ledger timestamp (epoch seconds)"
  },
  {
    "code": "def append(self, p_todo, p_string):\n        if len(p_string) > 0:\n            new_text = p_todo.source() + ' ' + p_string\n            p_todo.set_source_text(new_text)\n            self._update_todo_ids()\n            self.dirty = True",
    "docstring": "Appends a text to the todo, specified by its number.\n        The todo will be parsed again, such that tags and projects in de\n        appended string are processed."
  },
  {
    "code": "def from_gtp(gtpc):\n    gtpc = gtpc.upper()\n    if gtpc == 'PASS':\n        return None\n    col = _GTP_COLUMNS.index(gtpc[0])\n    row_from_bottom = int(gtpc[1:])\n    return go.N - row_from_bottom, col",
    "docstring": "Converts from a GTP coordinate to a Minigo coordinate."
  },
  {
    "code": "def zoom_bbox(self, bbox):\n        try:\n            bbox.transform(self.map.srs)\n        except gdal.GDALException:\n            pass\n        else:\n            self.map.zoom_to_box(mapnik.Box2d(*bbox.extent))",
    "docstring": "Zoom map to geometry extent.\n\n        Arguments:\n        bbox -- OGRGeometry polygon to zoom map extent"
  },
  {
    "code": "def lookup(self, iterable, gather=False):\n        for result in self.root.lookup(iterable,\n                                       gather=gather,\n                                       edit_distance=0,\n                                       max_edit_distance=self.max_edit_distance,\n                                       match_threshold=self.match_threshold):\n            yield result",
    "docstring": "Call the lookup on the root node with the given parameters.\n\n        Args\n            iterable(index or key): Used to retrive nodes from tree\n            gather(bool): this is passed down to the root node lookup\n\n        Notes:\n            max_edit_distance and match_threshold come from the init"
  },
  {
    "code": "def flatten(inputs, scope=None):\n  if len(inputs.get_shape()) < 2:\n    raise ValueError('Inputs must be have a least 2 dimensions')\n  dims = inputs.get_shape()[1:]\n  k = dims.num_elements()\n  with tf.name_scope(scope, 'Flatten', [inputs]):\n    return tf.reshape(inputs, [-1, k])",
    "docstring": "Flattens the input while maintaining the batch_size.\n\n    Assumes that the first dimension represents the batch.\n\n  Args:\n    inputs: a tensor of size [batch_size, ...].\n    scope: Optional scope for name_scope.\n\n  Returns:\n    a flattened tensor with shape [batch_size, k].\n  Raises:\n    ValueError: if inputs.shape is wrong."
  },
  {
    "code": "def parse(s):\n    r\n    stuff = []\n    rest = s\n    while True:\n        front, token, rest = peel_off_esc_code(rest)\n        if front:\n            stuff.append(front)\n        if token:\n            try:\n                tok = token_type(token)\n                if tok:\n                    stuff.extend(tok)\n            except ValueError:\n                raise ValueError(\"Can't parse escape sequence: %r %r %r %r\" % (s, repr(front), token, repr(rest)))\n        if not rest:\n            break\n    return stuff",
    "docstring": "r\"\"\"\n    Returns a list of strings or format dictionaries to describe the strings.\n\n    May raise a ValueError if it can't be parsed.\n\n    >>> parse(\">>> []\")\n    ['>>> []']\n    >>> #parse(\"\\x1b[33m[\\x1b[39m\\x1b[33m]\\x1b[39m\\x1b[33m[\\x1b[39m\\x1b[33m]\\x1b[39m\\x1b[33m[\\x1b[39m\\x1b[33m]\\x1b[39m\\x1b[33m[\\x1b[39m\")"
  },
  {
    "code": "def save(self, *args, **kwargs):\n        letter = getattr(self, \"block_letter\", None)\n        if letter and len(letter) >= 1:\n            self.block_letter = letter[:1].upper() + letter[1:]\n        super(EighthBlock, self).save(*args, **kwargs)",
    "docstring": "Capitalize the first letter of the block name."
  },
  {
    "code": "def compose(self, mapping):\n        items = [f.compose(mapping) for f in self._items]\n        return self.__class__(items, self.shape, self.ftype)",
    "docstring": "Apply the ``compose`` method to all functions.\n\n        Returns a new farray."
  },
  {
    "code": "def render(self, context):\n        user = self._get_value(self.user_key, context)\n        feature = self._get_value(self.feature, context)\n        if feature is None:\n            return ''\n        allowed = show_feature(user, feature)\n        return self.nodelist.render(context) if allowed else ''",
    "docstring": "Handle the actual rendering."
  },
  {
    "code": "def synchronizeLayout(primary, secondary, surface_size):\n    primary.configure_bound(surface_size)\n    secondary.configure_bound(surface_size)\n    if (primary.key_size < secondary.key_size):\n        logging.warning('Normalizing key size from secondary to primary')\n        secondary.key_size = primary.key_size\n    elif (primary.key_size > secondary.key_size):\n        logging.warning('Normalizing key size from primary to secondary')\n        primary.key_size = secondary.key_size\n    if (primary.size[1] > secondary.size[1]):\n        logging.warning('Normalizing layout size from secondary to primary')\n        secondary.set_size(primary.size, surface_size)\n    elif (primary.size[1] < secondary.size[1]):\n        logging.warning('Normalizing layout size from primary to secondary')\n        primary.set_size(secondary.size, surface_size)",
    "docstring": "Synchronizes given layouts by normalizing height by using\n    max height of given layouts to avoid transistion dirty effects.\n\n    :param primary: Primary layout used.\n    :param secondary: Secondary layout used.\n    :param surface_size: Target surface size on which layout will be displayed."
  },
  {
    "code": "def save_project(self, project, filename=''):\n        r\n        if filename == '':\n            filename = project.name\n        filename = self._parse_filename(filename=filename, ext='pnm')\n        d = {project.name: project}\n        with open(filename, 'wb') as f:\n            pickle.dump(d, f)",
    "docstring": "r\"\"\"\n        Saves given Project to a 'pnm' file\n\n        This will include all of associated objects, including algorithms.\n\n        Parameters\n        ----------\n        project : OpenPNM Project\n            The project to save.\n\n        filename : string, optional\n            If no filename is given, the given project name is used. See Notes\n            for more information.\n\n        See Also\n        --------\n        save_workspace\n\n        Notes\n        -----\n        The filename can be a string such as 'saved_file.pnm'.  The string can\n        include absolute path such as 'C:\\networks\\saved_file.pnm', or can\n        be a relative path such as '..\\..\\saved_file.pnm', which will look\n        2 directories above the current working directory.  Can also be a\n        path object object such as that produced by ``pathlib`` or\n        ``os.path`` in the Python standard library."
  },
  {
    "code": "def real_space(self):\n        if not is_numeric_dtype(self.dtype):\n            raise ValueError(\n                '`real_space` not defined for non-numeric `dtype`')\n        return self.astype(self.real_dtype)",
    "docstring": "The space corresponding to this space's `real_dtype`.\n\n        Raises\n        ------\n        ValueError\n            If `dtype` is not a numeric data type."
  },
  {
    "code": "def __update_paths(self, settings):\n        if not isinstance(settings, dict):\n            return\n        if 'custom_base_path' in settings:\n            base_path = settings['custom_base_path']\n            base_path = join(dirname(__file__), base_path)\n            self.__load_paths(base_path)",
    "docstring": "Set custom paths if necessary"
  },
  {
    "code": "def ms_cutall(self, viewer, event, data_x, data_y):\n        if not self.cancut:\n            return True\n        x, y = self.get_win_xy(viewer)\n        if event.state == 'move':\n            self._cutboth_xy(viewer, x, y)\n        elif event.state == 'down':\n            self._start_x, self._start_y = x, y\n            image = viewer.get_image()\n            self._loval, self._hival = viewer.autocuts.calc_cut_levels(image)\n        else:\n            viewer.onscreen_message(None)\n        return True",
    "docstring": "An interactive way to set the low AND high cut levels."
  },
  {
    "code": "def _parse_box_list(self, output):\n        boxes = []\n        name = provider = version = None\n        for timestamp, target, kind, data in self._parse_machine_readable_output(output):\n            if kind == 'box-name':\n                if name is not None:\n                    boxes.append(Box(name=name, provider=provider, version=version))\n                name = data\n                provider = version = None\n            elif kind == 'box-provider':\n                provider = data\n            elif kind == 'box-version':\n                version = data\n        if name is not None:\n            boxes.append(Box(name=name, provider=provider, version=version))\n        return boxes",
    "docstring": "Remove Vagrant usage for unit testing"
  },
  {
    "code": "def isempty(path):\n    if op.isdir(path):\n        return [] == os.listdir(path)\n    elif op.isfile(path):\n        return 0 == os.stat(path).st_size\n    return None",
    "docstring": "Returns True if the given file or directory path is empty.\n\n    **Examples**:\n    ::\n        auxly.filesys.isempty(\"foo.txt\")  # Works on files...\n        auxly.filesys.isempty(\"bar\")  # ...or directories!"
  },
  {
    "code": "def start(self):\n        self.streams.append(sys.stdout)\n        sys.stdout = self.stream",
    "docstring": "Activate the TypingStream on stdout"
  },
  {
    "code": "def output_package(dist):\n        if dist_is_editable(dist):\n            return '%s (%s, %s)' % (\n                dist.project_name,\n                dist.version,\n                dist.location,\n            )\n        return '%s (%s)' % (dist.project_name, dist.version)",
    "docstring": "Return string displaying package information."
  },
  {
    "code": "def _regressor_names(con_name, hrf_model, fir_delays=None):\n    if hrf_model in ['glover', 'spm', None]:\n        return [con_name]\n    elif hrf_model in [\"glover + derivative\", 'spm + derivative']:\n        return [con_name, con_name + \"_derivative\"]\n    elif hrf_model in ['spm + derivative + dispersion',\n                       'glover + derivative + dispersion']:\n        return [con_name, con_name + \"_derivative\", con_name + \"_dispersion\"]\n    elif hrf_model == 'fir':\n        return [con_name + \"_delay_%d\" % i for i in fir_delays]",
    "docstring": "Returns a list of regressor names, computed from con-name and hrf type\n\n    Parameters\n    ----------\n    con_name: string\n        identifier of the condition\n\n    hrf_model: string or None,\n       hrf model chosen\n\n    fir_delays: 1D array_like, optional,\n        Delays used in case of an FIR model\n\n    Returns\n    -------\n    names: list of strings,\n        regressor names"
  },
  {
    "code": "def page(self, end=values.unset, start=values.unset, page_token=values.unset,\n             page_number=values.unset, page_size=values.unset):\n        params = values.of({\n            'End': serialize.iso8601_datetime(end),\n            'Start': serialize.iso8601_datetime(start),\n            'PageToken': page_token,\n            'Page': page_number,\n            'PageSize': page_size,\n        })\n        response = self._version.page(\n            'GET',\n            self._uri,\n            params=params,\n        )\n        return DataSessionPage(self._version, response, self._solution)",
    "docstring": "Retrieve a single page of DataSessionInstance records from the API.\n        Request is executed immediately\n\n        :param datetime end: The end\n        :param datetime start: The start\n        :param str page_token: PageToken provided by the API\n        :param int page_number: Page Number, this value is simply for client state\n        :param int page_size: Number of records to return, defaults to 50\n\n        :returns: Page of DataSessionInstance\n        :rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionPage"
  },
  {
    "code": "def get_blocked(self):\n        url = self.reddit_session.config['blocked']\n        return self.reddit_session.request_json(url)",
    "docstring": "Return a UserList of Redditors with whom the user has blocked."
  },
  {
    "code": "def _id_to_subword(self, subword_id):\n    if subword_id < 0 or subword_id >= (self.vocab_size - 1):\n      raise ValueError(\"Received id %d which is invalid. Ids must be within \"\n                       \"[0, %d).\" % (subword_id + 1, self.vocab_size))\n    if 0 <= subword_id < len(self._subwords):\n      return self._subwords[subword_id]\n    else:\n      offset = len(self._subwords)\n      subword_id -= offset\n      bytestr = bytes(bytearray([subword_id]))\n      return bytestr",
    "docstring": "Converts a subword integer ID to a subword string."
  },
  {
    "code": "def find_entry_name_of_alias(self, alias):\n        if alias in self.aliases:\n            name = self.aliases[alias]\n            if name in self.entries:\n                return name\n            else:\n                for name, entry in self.entries.items():\n                    aliases = entry.get_aliases(includename=False)\n                    if alias in aliases:\n                        if (ENTRY.DISTINCT_FROM not in entry or\n                                alias not in entry[ENTRY.DISTINCT_FROM]):\n                            return name\n        return None",
    "docstring": "Return the first entry name with the given 'alias' included in its\n        list of aliases.\n\n        Returns\n        -------\n        name of matching entry (str) or 'None' if no matches"
  },
  {
    "code": "def __SetDefaultUploadStrategy(self, upload_config, http_request):\n        if upload_config.resumable_path is None:\n            self.strategy = SIMPLE_UPLOAD\n        if self.strategy is not None:\n            return\n        strategy = SIMPLE_UPLOAD\n        if (self.total_size is not None and\n                self.total_size > _RESUMABLE_UPLOAD_THRESHOLD):\n            strategy = RESUMABLE_UPLOAD\n        if http_request.body and not upload_config.simple_multipart:\n            strategy = RESUMABLE_UPLOAD\n        if not upload_config.simple_path:\n            strategy = RESUMABLE_UPLOAD\n        self.strategy = strategy",
    "docstring": "Determine and set the default upload strategy for this upload.\n\n        We generally prefer simple or multipart, unless we're forced to\n        use resumable. This happens when any of (1) the upload is too\n        large, (2) the simple endpoint doesn't support multipart requests\n        and we have metadata, or (3) there is no simple upload endpoint.\n\n        Args:\n          upload_config: Configuration for the upload endpoint.\n          http_request: The associated http request.\n\n        Returns:\n          None."
  },
  {
    "code": "def _is_interactive(self):\n        return not (\n            self.realworld and (dt.date.today() > self.datetime.date()))",
    "docstring": "Prevent middlewares and orders to work outside live mode"
  },
  {
    "code": "def cancelUpdate(self):\n        key = '/library/sections/%s/refresh' % self.key\n        self._server.query(key, method=self._server._session.delete)",
    "docstring": "Cancel update of this Library Section."
  },
  {
    "code": "def mediatype_create(name, mediatype, **kwargs):\n    conn_args = _login(**kwargs)\n    ret = {}\n    try:\n        if conn_args:\n            method = 'mediatype.create'\n            params = {\"description\": name}\n            params['type'] = mediatype\n            params = _params_extend(params, _ignore_name=True, **kwargs)\n            ret = _query(method, params, conn_args['url'], conn_args['auth'])\n            return ret['result']['mediatypeid']\n        else:\n            raise KeyError\n    except KeyError:\n        return ret",
    "docstring": "Create new mediatype\n\n    .. note::\n        This function accepts all standard mediatype properties: keyword\n        argument names differ depending on your zabbix version, see here__.\n\n        .. __: https://www.zabbix.com/documentation/3.0/manual/api/reference/mediatype/object\n\n    :param mediatype: media type - 0: email, 1: script, 2: sms, 3: Jabber, 100: Ez Texting\n    :param exec_path: exec path - Required for script and Ez Texting types, see Zabbix API docs\n    :param gsm_modem: exec path - Required for sms type, see Zabbix API docs\n    :param smtp_email: email address from which notifications will be sent, required for email type\n    :param smtp_helo: SMTP HELO, required for email type\n    :param smtp_server: SMTP server, required for email type\n    :param status: whether the media type is enabled - 0: enabled, 1: disabled\n    :param username: authentication user, required for Jabber and Ez Texting types\n    :param passwd: authentication password, required for Jabber and Ez Texting types\n    :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)\n    :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)\n    :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)\n\n    return: ID of the created mediatype.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' zabbix.mediatype_create 'Email' 0 smtp_email='noreply@example.com'\n        smtp_server='mailserver.example.com' smtp_helo='zabbix.example.com'"
  },
  {
    "code": "def sojourn_time(p):\n    p = np.asarray(p)\n    pii = p.diagonal()\n    if not (1 - pii).all():\n        print(\"Sojourn times are infinite for absorbing states!\")\n    return 1 / (1 - pii)",
    "docstring": "Calculate sojourn time based on a given transition probability matrix.\n\n    Parameters\n    ----------\n    p        : array\n               (k, k), a Markov transition probability matrix.\n\n    Returns\n    -------\n             : array\n               (k, ), sojourn times. Each element is the expected time a Markov\n               chain spends in each states before leaving that state.\n\n    Notes\n    -----\n    Refer to :cite:`Ibe2009` for more details on sojourn times for Markov\n    chains.\n\n    Examples\n    --------\n    >>> from giddy.markov import sojourn_time\n    >>> import numpy as np\n    >>> p = np.array([[.5, .25, .25], [.5, 0, .5], [.25, .25, .5]])\n    >>> sojourn_time(p)\n    array([2., 1., 2.])"
  },
  {
    "code": "def trace_in_process_link(self, link_bytes):\n        return tracers.InProcessLinkTracer(self._nsdk,\n                                           self._nsdk.trace_in_process_link(link_bytes))",
    "docstring": "Creates a tracer for tracing asynchronous related processing in the same process.\n\n        For more information see :meth:`create_in_process_link`.\n\n        :param bytes link_bytes: An in-process link created using :meth:`create_in_process_link`.\n\n        :rtype: tracers.InProcessLinkTracer\n\n        .. versionadded:: 1.1.0"
  },
  {
    "code": "def create_environment(self, name, default=False, zone=None):\n        from qubell.api.private.environment import Environment\n        return Environment.new(organization=self, name=name, zone_id=zone, default=default, router=self._router)",
    "docstring": "Creates environment and returns Environment object."
  },
  {
    "code": "async def _do(self, ctx, times: int, *, command):\n        msg = copy.copy(ctx.message)\n        msg.content = command\n        for i in range(times):\n            await self.bot.process_commands(msg)",
    "docstring": "Repeats a command a specified number of times."
  },
  {
    "code": "def flatten(self):\n        args = list(self.args)\n        i = 0\n        for arg in self.args:\n            if isinstance(arg, self.__class__):\n                args[i:i + 1] = arg.args\n                i += len(arg.args)\n            else:\n                i += 1\n        return self.__class__(*args)",
    "docstring": "Return a new expression where nested terms of this expression are\n        flattened as far as possible.\n\n        E.g. A & (B & C) becomes A & B & C."
  },
  {
    "code": "def parse(self, data_model, crit):\n        tables = pd.DataFrame(data_model)\n        data_model = {}\n        for table_name in tables.columns:\n            data_model[table_name] = pd.DataFrame(tables[table_name]['columns']).T\n            data_model[table_name] = data_model[table_name].where((pd.notnull(data_model[table_name])), None)\n        zipped = list(zip(crit.keys(), crit.values()))\n        crit_map = pd.DataFrame(zipped)\n        crit_map.index = crit_map[0]\n        crit_map.drop(0, axis='columns', inplace=True)\n        crit_map.rename({1: 'criteria_map'}, axis='columns', inplace=True)\n        crit_map.index.rename(\"\", inplace=True)\n        for table_name in ['measurements', 'specimens', 'samples', 'sites', 'locations',\n                           'contribution', 'criteria', 'images', 'ages']:\n            crit_map.loc[table_name] = np.nan\n        return data_model, crit_map",
    "docstring": "Take the relevant pieces of the data model json\n        and parse into data model and criteria map.\n\n        Parameters\n        ----------\n        data_model : data model piece of json (nested dicts)\n        crit : criteria map piece of json (nested dicts)\n\n        Returns\n        ----------\n        data_model : dictionary of DataFrames\n        crit_map : DataFrame"
  },
  {
    "code": "def signup_verify(request, uidb36=None, token=None):\n    user = authenticate(uidb36=uidb36, token=token, is_active=False)\n    if user is not None:\n        user.is_active = True\n        user.save()\n        auth_login(request, user)\n        info(request, _(\"Successfully signed up\"))\n        return login_redirect(request)\n    else:\n        error(request, _(\"The link you clicked is no longer valid.\"))\n        return redirect(\"/\")",
    "docstring": "View for the link in the verification email sent to a new user\n    when they create an account and ``ACCOUNTS_VERIFICATION_REQUIRED``\n    is set to ``True``. Activates the user and logs them in,\n    redirecting to the URL they tried to access when signing up."
  },
  {
    "code": "def _prepare_value(val, maxlen=50, notype=False):\n    if val is None or val is True or val is False:\n        return str(val)\n    sval = repr(val)\n    sval = sval.replace(\"\\n\", \" \").replace(\"\\t\", \" \").replace(\"`\", \"'\")\n    if len(sval) > maxlen:\n        sval = sval[:maxlen - 4] + \"...\" + sval[-1]\n    if notype:\n        return sval\n    else:\n        tval = checker_for_type(type(val)).name()\n        return \"%s of type %s\" % (sval, tval)",
    "docstring": "Stringify value `val`, ensuring that it is not too long."
  },
  {
    "code": "def dimod_object_hook(obj):\n    if _is_sampleset_v2(obj):\n        return SampleSet.from_serializable(obj)\n    elif _is_bqm_v2(obj):\n        return BinaryQuadraticModel.from_serializable(obj)\n    return obj",
    "docstring": "JSON-decoding for dimod objects.\n\n    See Also:\n        :class:`json.JSONDecoder` for using custom decoders."
  },
  {
    "code": "def template_string(\n    task: Task, template: str, jinja_filters: FiltersDict = None, **kwargs: Any\n) -> Result:\n    jinja_filters = jinja_filters or {} or task.nornir.config.jinja2.filters\n    text = jinja_helper.render_from_string(\n        template=template, host=task.host, jinja_filters=jinja_filters, **kwargs\n    )\n    return Result(host=task.host, result=text)",
    "docstring": "Renders a string with jinja2. All the host data is available in the template\n\n    Arguments:\n        template (string): template string\n        jinja_filters (dict): jinja filters to enable. Defaults to nornir.config.jinja2.filters\n        **kwargs: additional data to pass to the template\n\n    Returns:\n        Result object with the following attributes set:\n          * result (``string``): rendered string"
  },
  {
    "code": "def raster_reclassify(srcfile, v_dict, dstfile, gdaltype=GDT_Float32):\n        src_r = RasterUtilClass.read_raster(srcfile)\n        src_data = src_r.data\n        dst_data = numpy.copy(src_data)\n        if gdaltype == GDT_Float32 and src_r.dataType != GDT_Float32:\n            gdaltype = src_r.dataType\n        no_data = src_r.noDataValue\n        new_no_data = DEFAULT_NODATA\n        if gdaltype in [GDT_Unknown, GDT_Byte, GDT_UInt16, GDT_UInt32]:\n            new_no_data = 0\n        if not MathClass.floatequal(new_no_data, src_r.noDataValue):\n            if src_r.noDataValue not in v_dict:\n                v_dict[src_r.noDataValue] = new_no_data\n                no_data = new_no_data\n        for (k, v) in iteritems(v_dict):\n            dst_data[src_data == k] = v\n        RasterUtilClass.write_gtiff_file(dstfile, src_r.nRows, src_r.nCols, dst_data,\n                                         src_r.geotrans, src_r.srs, no_data, gdaltype)",
    "docstring": "Reclassify raster by given classifier dict.\n\n        Args:\n            srcfile: source raster file.\n            v_dict: classifier dict.\n            dstfile: destination file path.\n            gdaltype (:obj:`pygeoc.raster.GDALDataType`): GDT_Float32 as default."
  },
  {
    "code": "def kernel_command_line(self, kernel_command_line):\n        log.info('QEMU VM \"{name}\" [{id}] has set the QEMU kernel command line to {kernel_command_line}'.format(name=self._name,\n                                                                                                                id=self._id,\n                                                                                                                kernel_command_line=kernel_command_line))\n        self._kernel_command_line = kernel_command_line",
    "docstring": "Sets the kernel command line for this QEMU VM.\n\n        :param kernel_command_line: QEMU kernel command line"
  },
  {
    "code": "def post_task(task_data, task_uri='/tasks'):\n    url = '{}/{}'.format(API_URL, task_uri.lstrip('/'))\n    if isinstance(task_data, str):\n        task_json = task_data\n    else:\n        task_json = json.dumps(task_data)\n    resp = requests.post(url, data=task_json, headers=HEADERS, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)\n    resp_json = resp.json()\n    LOG.debug(resp_json)\n    assert resp.ok, 'Spinnaker communication error: {0}'.format(resp.text)\n    return resp_json['ref']",
    "docstring": "Create Spinnaker Task.\n\n    Args:\n        task_data (str): Task JSON definition.\n\n    Returns:\n        str: Spinnaker Task ID.\n\n    Raises:\n        AssertionError: Error response from Spinnaker."
  },
  {
    "code": "def _get_md_files(self):\n        all_f = _all_files_matching_ext(os.getcwd(), \"md\")\n        exclusions = [\n            \"*.egg/*\",\n            \"*.eggs/*\",\n            \"*build/*\"\n        ] + self.exclusions\n        return sorted([f for f in all_f if not _is_excluded(f, exclusions)])",
    "docstring": "Get all markdown files."
  },
  {
    "code": "def plot_posterior_contour(self, idx_param1=0, idx_param2=1, res1=100, res2=100, smoothing=0.01):\n        return plt.contour(*self.posterior_mesh(idx_param1, idx_param2, res1, res2, smoothing))",
    "docstring": "Plots a contour of the kernel density estimation\n        of a 2D projection of the current posterior distribution.\n\n        :param int idx_param1: Parameter to be treated as :math:`x` when\n            plotting.\n        :param int idx_param2: Parameter to be treated as :math:`y` when\n            plotting.\n        :param int res1: Resolution along the :math:`x` direction.\n        :param int res2: Resolution along the :math:`y` direction.\n        :param float smoothing: Standard deviation of the Gaussian kernel\n            used to smooth the particle approximation to the current posterior.\n\n        .. seealso::\n\n            :meth:`SMCUpdater.posterior_mesh`"
  },
  {
    "code": "def getItem(self, index, altItem=None):\n        if index.isValid():\n            item = index.internalPointer()\n            if item:\n                return item\n        return altItem",
    "docstring": "Returns the TreeItem for the given index. Returns the altItem if the index is invalid."
  },
  {
    "code": "def run_qpoints(self,\n                    q_points,\n                    with_eigenvectors=False,\n                    with_group_velocities=False,\n                    with_dynamical_matrices=False,\n                    nac_q_direction=None):\n        if self._dynamical_matrix is None:\n            msg = (\"Dynamical matrix has not yet built.\")\n            raise RuntimeError(msg)\n        if with_group_velocities:\n            if self._group_velocity is None:\n                self._set_group_velocity()\n            group_velocity = self._group_velocity\n        else:\n            group_velocity = None\n        self._qpoints = QpointsPhonon(\n            np.reshape(q_points, (-1, 3)),\n            self._dynamical_matrix,\n            nac_q_direction=nac_q_direction,\n            with_eigenvectors=with_eigenvectors,\n            group_velocity=group_velocity,\n            with_dynamical_matrices=with_dynamical_matrices,\n            factor=self._factor)",
    "docstring": "Phonon calculations on q-points.\n\n        Parameters\n        ----------\n        q_points: array_like or float, optional\n            q-points in reduced coordinates.\n            dtype='double', shape=(q-points, 3)\n        with_eigenvectors: bool, optional\n            Eigenvectors are stored by setting True. Default False.\n        with_group_velocities : bool, optional\n            Group velocities are calculated by setting True. Default is False.\n        with_dynamical_matrices : bool, optional\n            Calculated dynamical matrices are stored by setting True.\n            Default is False.\n        nac_q_direction : array_like\n            q=(0,0,0) is replaced by q=epsilon * nac_q_direction where epsilon\n            is infinitsimal for non-analytical term correction. This is used,\n            e.g., to observe LO-TO splitting,"
  },
  {
    "code": "def get_image_upload_to(self, filename):\n        dummy, ext = os.path.splitext(filename)\n        return os.path.join(\n            machina_settings.FORUM_IMAGE_UPLOAD_TO,\n            '{id}{ext}'.format(id=str(uuid.uuid4()).replace('-', ''), ext=ext),\n        )",
    "docstring": "Returns the path to upload a new associated image to."
  },
  {
    "code": "def update_credit_note(self, credit_note_id, credit_note_dict):\n        return self._create_put_request(resource=CREDIT_NOTES, billomat_id=credit_note_id, send_data=credit_note_dict)",
    "docstring": "Updates a credit note\n\n        :param credit_note_id: the credit note id\n        :param credit_note_dict: dict\n        :return: dict"
  },
  {
    "code": "def _parse_options(options: List[str]) -> Dict[str, str]:\n    try:\n        return dict(i.split('=', maxsplit=1) for i in options)\n    except ValueError:\n        raise ArgumentError(\n            f'Option must be in format <key>=<value>, got: {options}')",
    "docstring": "Parse repeatable CLI options\n\n    >>> opts = _parse_options(['cluster.name=foo', 'CRATE_JAVA_OPTS=\"-Dxy=foo\"'])\n    >>> print(json.dumps(opts, sort_keys=True))\n    {\"CRATE_JAVA_OPTS\": \"\\\\\"-Dxy=foo\\\\\"\", \"cluster.name\": \"foo\"}"
  },
  {
    "code": "def set_toolBox_height(tool_box, height=32):\n    for button in tool_box.findChildren(QAbstractButton):\n        button.setMinimumHeight(height)\n    return True",
    "docstring": "Sets given height to given QToolBox widget.\n\n    :param toolbox: ToolBox.\n    :type toolbox: QToolBox\n    :param height: Height.\n    :type height: int\n    :return: Definition success.\n    :rtype: bool"
  },
  {
    "code": "def post_message(self, msg):\n        super(mavlogfile, self).post_message(msg)\n        if self.planner_format:\n            self.f.read(1)\n        self.timestamp = msg._timestamp\n        self._last_message = msg\n        if msg.get_type() != \"BAD_DATA\":\n            self._last_timestamp = msg._timestamp\n        msg._link = self._link",
    "docstring": "add timestamp to message"
  },
  {
    "code": "def wrap_generator(func):\n    async def _wrapped(*a, **k):\n        r, ret = None, []\n        gen = func(*a, **k)\n        while True:\n            try:\n                item = gen.send(r)\n            except StopIteration:\n                break\n            if inspect.isawaitable(item):\n                r = await item\n            else:\n                r = item\n            ret.append(r)\n        if len(ret) == 1:\n            return ret.pop()\n        return ret\n    return _wrapped",
    "docstring": "Decorator to convert a generator function to an async function which collects\n    and returns generator results, returning a list if there are multiple results"
  },
  {
    "code": "def force_lazy_import(name):\n  obj = import_object(name)\n  module_items = list(getattr(obj, '__dict__', {}).items())\n  for key, value in module_items:\n    if getattr(value, '__module__', None):\n        import_object(name + '.' + key)",
    "docstring": "Import any modules off of \"name\" by iterating a new list rather than a generator so that this\n  library works with lazy imports."
  },
  {
    "code": "def to_adb_message(self, data):\n    message = AdbMessage(AdbMessage.WIRE_TO_CMD.get(self.cmd),\n                         self.arg0, self.arg1, data)\n    if (len(data) != self.data_length or\n        message.data_crc32 != self.data_checksum):\n      raise usb_exceptions.AdbDataIntegrityError(\n          '%s (%s) received invalid data: %s', message, self, repr(data))\n    return message",
    "docstring": "Turn the data into an ADB message."
  },
  {
    "code": "def default_value(self, default_value):\n        if default_value not in self.default_values:\n            if len(self.default_labels) == len(self.default_values):\n                self.default_values[-1] = default_value\n            else:\n                self.default_values.append(default_value)\n        self._default_value = default_value",
    "docstring": "Setter for default_value.\n\n        :param default_value: The default value.\n        :type default_value: object"
  },
  {
    "code": "def channel(self, channel_id=None):\n        if channel_id in self.channels:\n            return self.channels[channel_id]\n        return Channel(self, channel_id)",
    "docstring": "Fetch a Channel object identified by the numeric channel_id, or\n        create that object if it doesn't already exist."
  },
  {
    "code": "def put(request, obj_id=None):\n    res = Result()\n    data = request.PUT or json.loads(request.body)['body']\n    if obj_id:\n        tag = Tag.objects.get(pk=obj_id)\n        tag.name = data.get('name', tag.name)\n        tag.artist = data.get('artist', tag.artist)\n        tag.save()\n    else:\n        tags = [_ for _ in data.get('tags', '').split(',') if _]\n        guids = [_ for _ in data.get('guids', '').split(',') if _]\n        _manageTags(tags, guids)\n    return JsonResponse(res.asDict())",
    "docstring": "Adds tags from objects resolved from guids\n\n    :param tags: Tags to add\n    :type tags: list\n    :param guids: Guids to add tags from\n    :type guids: list\n    :returns: json"
  },
  {
    "code": "def _internal_function_call(self, call_conf):\n        def stub(*args, **kwargs):\n            message = 'Function {} is not available'.format(call_conf['fun'])\n            self.out.error(message)\n            log.debug(\n                'Attempt to run \"%s\" with %s arguments and %s parameters.',\n                call_conf['fun'], call_conf['arg'], call_conf['kwargs']\n            )\n            return message\n        return getattr(salt.cli.support.intfunc,\n                       call_conf['fun'], stub)(self.collector,\n                                               *call_conf['arg'],\n                                               **call_conf['kwargs'])",
    "docstring": "Call internal function.\n\n        :param call_conf:\n        :return:"
  },
  {
    "code": "def validate_json_field(dist, attr, value):\n    try:\n        is_json_compat(value)\n    except ValueError as e:\n        raise DistutilsSetupError(\"%r %s\" % (attr, e))\n    return True",
    "docstring": "Check for json validity."
  },
  {
    "code": "def remove(self, parent, child):\n        self.remove_links(parent, (child,))\n        if parent not in self and parent in self._parent_to_not_ok:\n            del self._parent_to_not_ok[parent]\n        if child not in self and child in self._parent_to_not_ok:\n            del self._parent_to_not_ok[child]",
    "docstring": "Remove a dependency between parent and child.\n\n        Parameters\n        ----------\n        parent : boolean instance of :class:`katcp.Sensor`\n            The sensor that used to depend on child.\n        child : boolean instance of :class:`katcp.Sensor` or None\n            The sensor parent used to depend on."
  },
  {
    "code": "def queue_scan_command(self, server_info: ServerConnectivityInfo, scan_command: PluginScanCommand) -> None:\n        self._check_and_create_process(server_info.hostname)\n        self._queued_tasks_nb += 1\n        if scan_command.is_aggressive:\n            self._hostname_queues_dict[server_info.hostname].put((server_info, scan_command))\n        else:\n            self._task_queue.put((server_info, scan_command))",
    "docstring": "Queue a scan command targeting a specific server.\n\n        Args:\n            server_info: The server's connectivity information. The test_connectivity_to_server() method must have been\n                called first to ensure that the server is online and accessible.\n            scan_command: The scan command to run against this server."
  },
  {
    "code": "def get_config_window_bounds(self):\n        bounds_x = int(self.config.get_optional('Driver', 'bounds_x') or 0)\n        bounds_y = int(self.config.get_optional('Driver', 'bounds_y') or 0)\n        monitor_index = int(self.config.get_optional('Driver', 'monitor') or -1)\n        if monitor_index > -1:\n            try:\n                monitor = screeninfo.get_monitors()[monitor_index]\n                bounds_x += monitor.x\n                bounds_y += monitor.y\n            except NotImplementedError:\n                self.logger.warn('Current environment doesn\\'t support get_monitors')\n        return bounds_x, bounds_y",
    "docstring": "Reads bounds from config and, if monitor is specified, modify the values to match with the specified monitor\n\n        :return: coords X and Y where set the browser window."
  },
  {
    "code": "def wnsumd(window):\n    assert isinstance(window, stypes.SpiceCell)\n    assert window.dtype == 1\n    meas = ctypes.c_double()\n    avg = ctypes.c_double()\n    stddev = ctypes.c_double()\n    shortest = ctypes.c_int()\n    longest = ctypes.c_int()\n    libspice.wnsumd_c(ctypes.byref(window), ctypes.byref(meas),\n                      ctypes.byref(avg), ctypes.byref(stddev),\n                      ctypes.byref(shortest), ctypes.byref(longest))\n    return meas.value, avg.value, stddev.value, shortest.value, longest.value",
    "docstring": "Summarize the contents of a double precision window.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnsumd_c.html\n\n    :param window: Window to be summarized. \n    :type window: spiceypy.utils.support_types.SpiceCell\n    :return:\n            Total measure of intervals in window,\n            Average measure, Standard deviation,\n            Location of shortest interval,\n            Location of longest interval.\n    :rtype: tuple"
  },
  {
    "code": "def start(self):\n        origin = inspect.stack()[1][0]\n        self.reset()\n        self._start_tracer(origin)",
    "docstring": "Start collecting trace information."
  },
  {
    "code": "def build_binary_op(self, op, other):\n        if isinstance(other, NumericalExpression):\n            self_expr, other_expr, new_inputs = self._merge_expressions(other)\n        elif isinstance(other, Term):\n            self_expr = self._expr\n            new_inputs, other_idx = _ensure_element(self.inputs, other)\n            other_expr = \"x_%d\" % other_idx\n        elif isinstance(other, Number):\n            self_expr = self._expr\n            other_expr = str(other)\n            new_inputs = self.inputs\n        else:\n            raise BadBinaryOperator(op, other)\n        return self_expr, other_expr, new_inputs",
    "docstring": "Compute new expression strings and a new inputs tuple for combining\n        self and other with a binary operator."
  },
  {
    "code": "def on_save(self, event):\n        dlg = wx.FileDialog(None, self.settings.get_title(), '', \"\", '*.*',\n                            wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)\n        if dlg.ShowModal() == wx.ID_OK:\n            self.settings.save(dlg.GetPath())",
    "docstring": "called on save button"
  },
  {
    "code": "def _ewp_flags_set(self, ewp_dic_subset, project_dic, flag_type, flag_dic):\n        try:\n            if flag_type in project_dic['misc'].keys():\n                index_option = self._get_option(ewp_dic_subset, flag_dic['enable'])\n                self._set_option(ewp_dic_subset[index_option], '1')\n                index_option = self._get_option(ewp_dic_subset, flag_dic['set'])\n                if type(ewp_dic_subset[index_option]['state']) != list:\n                    previous_state = ewp_dic_subset[index_option]['state']\n                    ewp_dic_subset[index_option]['state'] = []\n                    ewp_dic_subset[index_option]['state'].append(previous_state)\n                for item in project_dic['misc'][flag_type]:\n                    ewp_dic_subset[index_option]['state'].append(item)\n        except KeyError:\n            return",
    "docstring": "Flags from misc to set to ewp project"
  },
  {
    "code": "def getGenomeList() :\n\timport rabaDB.filters as rfilt\n\tf = rfilt.RabaQuery(Genome_Raba)\n\tnames = []\n\tfor g in f.iterRun() :\n\t\tnames.append(g.name)\n\treturn names",
    "docstring": "Return the names of all imported genomes"
  },
  {
    "code": "def fit(fqdn, result, *argl, **argd):\n    global _machines\n    out = None\n    if len(argl) > 0:\n        machine = argl[0]\n        key = id(machine)\n        _machines[key] = (machine, argl[0], argl[1])\n        if isclassifier(machine):\n            out = classify_fit(fqdn, result, *argl, **argd)\n        elif isregressor(machine):\n            out = regress_fit(fqdn, result, *argl, **argd)\n    return out",
    "docstring": "Analyzes the result of a generic fit operation performed by `sklearn`.\n\n    Args:\n        fqdn (str): full-qualified name of the method that was called.\n        result: result of calling the method with `fqdn`.\n        argl (tuple): positional arguments passed to the method call.\n        argd (dict): keyword arguments passed to the method call."
  },
  {
    "code": "def save_assessment_offered(self, assessment_offered_form, *args, **kwargs):\n        if assessment_offered_form.is_for_update():\n            return self.update_assessment_offered(assessment_offered_form, *args, **kwargs)\n        else:\n            return self.create_assessment_offered(assessment_offered_form, *args, **kwargs)",
    "docstring": "Pass through to provider AssessmentOfferedAdminSession.update_assessment_offered"
  },
  {
    "code": "def pop_events(self, regex_pattern, timeout):\n        if not self.started:\n            raise IllegalStateError(\n                \"Dispatcher needs to be started before popping.\")\n        deadline = time.time() + timeout\n        while True:\n            results = self._match_and_pop(regex_pattern)\n            if len(results) != 0 or time.time() > deadline:\n                break\n            time.sleep(1)\n        if len(results) == 0:\n            raise queue.Empty('Timeout after {}s waiting for event: {}'.format(\n                timeout, regex_pattern))\n        return sorted(results, key=lambda event: event['time'])",
    "docstring": "Pop events whose names match a regex pattern.\n\n        If such event(s) exist, pop one event from each event queue that\n        satisfies the condition. Otherwise, wait for an event that satisfies\n        the condition to occur, with timeout.\n\n        Results are sorted by timestamp in ascending order.\n\n        Args:\n            regex_pattern: The regular expression pattern that an event name\n                should match in order to be popped.\n            timeout: Number of seconds to wait for events in case no event\n                matching the condition exits when the function is called.\n\n        Returns:\n            Events whose names match a regex pattern.\n            Empty if none exist and the wait timed out.\n\n        Raises:\n            IllegalStateError: Raised if pop is called before the dispatcher\n                starts polling.\n            queue.Empty: Raised if no event was found before time out."
  },
  {
    "code": "def assert_looks_like(first, second, msg=None):\n    first = _re.sub(\"\\s+\", \" \", first.strip())\n    second = _re.sub(\"\\s+\", \" \", second.strip())\n    if first != second:\n        raise AssertionError(msg or \"%r does not look like %r\" % (first, second))",
    "docstring": "Compare two strings if all contiguous whitespace is coalesced."
  },
  {
    "code": "def _collect_infos(dirname):\n    for r, _ds, fs in walk(dirname):\n        if not islink(r) and r != dirname:\n            i = ZipInfo()\n            i.filename = join(relpath(r, dirname), \"\")\n            i.file_size = 0\n            i.compress_size = 0\n            i.CRC = 0\n            yield i.filename, i\n        for f in fs:\n            df = join(r, f)\n            relfn = relpath(join(r, f), dirname)\n            if islink(df):\n                pass\n            elif isfile(df):\n                i = ZipInfo()\n                i.filename = relfn\n                i.file_size = getsize(df)\n                i.compress_size = i.file_size\n                i.CRC = file_crc32(df)\n                yield i.filename, i\n            else:\n                pass",
    "docstring": "Utility function used by ExplodedZipFile to generate ZipInfo\n    entries for all of the files and directories under dirname"
  },
  {
    "code": "def needs_fully_loaded(method):\n    @functools.wraps(method)\n    def inner(self, *args, **kwargs):\n        if not self.fully_loaded:\n            loaded_yaml = yaml_loader.YamlLoader.load_yaml_by_path(self.path)\n            self.parsed_yaml = loaded_yaml\n            self.fully_loaded = True\n        return method(self, *args, **kwargs)\n    return inner",
    "docstring": "Wraps all publicly callable methods of YamlAssistant. If the assistant was loaded\n    from cache, this decorator will fully load it first time a publicly callable method\n    is used."
  },
  {
    "code": "def _extract_subdomain(host):\n        host = host.split(':')[0]\n        try:\n            socket.inet_aton(host)\n        except socket.error:\n            return '.'.join(host.split('.')[:-2])",
    "docstring": "Returns a subdomain from a host. This host is typically the\n        HTTP_HOST request envvar.  If the host is an IP address, `None` is\n        returned\n\n        :param host: Request's target host"
  },
  {
    "code": "def get_cur_file_size(fp, position_to_eof=False):\n    if not position_to_eof:\n        cur_pos = fp.tell()\n    fp.seek(0, os.SEEK_END)\n    cur_file_size = fp.tell()\n    if not position_to_eof:\n        fp.seek(cur_pos, os.SEEK_SET)\n    return cur_file_size",
    "docstring": "Returns size of file, optionally leaving fp positioned at EOF."
  },
  {
    "code": "def _get_local_files(local_dir, pattern=''):\n    local_files = {}\n    if pattern:\n        cwd = os.getcwd()\n        os.chdir(local_dir)\n        patterns = pattern.split('|')\n        local_list = set([])\n        for p in patterns: local_list = local_list | set(glob(p))\n        for path in local_list:\n            dir, file = os.path.split(path)\n            if os.path.isfile(path):\n                local_files[dir] = local_files.get(dir,[])+[file]\n            elif os.path.isdir(path):\n                local_files[file] = local_files.get(dir,[])\n        os.chdir(cwd)\n    return local_files",
    "docstring": "Returns a dictionary with directories as keys, and filenames as values\n    for filenames matching the glob ``pattern`` under the ``local_dir``\n    ``pattern can contain the Boolean OR | to evaluated multiple patterns into\n    a combined set."
  },
  {
    "code": "def _sort_policy(doc):\n    if isinstance(doc, list):\n        return sorted([_sort_policy(i) for i in doc])\n    elif isinstance(doc, (dict, OrderedDict)):\n        return dict([(k, _sort_policy(v)) for k, v in six.iteritems(doc)])\n    return doc",
    "docstring": "List-type sub-items in policies don't happen to be order-sensitive, but\n    compare operations will render them unequal, leading to non-idempotent\n    state runs.  We'll sort any list-type subitems before comparison to reduce\n    the likelihood of false negatives."
  },
  {
    "code": "def parse (cls, line, lineno, log, cmddict=None):\n    delay = -1\n    token = line.split()[0]\n    start = line.find(token)\n    pos   = SeqPos(line, lineno, start + 1, start + len(token))\n    try:\n      delay = float(token)\n    except ValueError:\n      msg = 'String \"%s\" could not be interpreted as a numeric time delay.'\n      log.error(msg % token, pos)\n    return cls(delay, pos)",
    "docstring": "Parses the SeqDelay from a line of text.  Warning and error\n    messages are logged via the SeqMsgLog log."
  },
  {
    "code": "def to_dict(self, data=True):\n        d = self.variable.to_dict(data=data)\n        d.update({'coords': {}, 'name': self.name})\n        for k in self.coords:\n            d['coords'][k] = self.coords[k].variable.to_dict(data=data)\n        return d",
    "docstring": "Convert this xarray.DataArray into a dictionary following xarray\n        naming conventions.\n\n        Converts all variables and attributes to native Python objects.\n        Useful for coverting to json. To avoid datetime incompatibility\n        use decode_times=False kwarg in xarrray.open_dataset.\n\n        Parameters\n        ----------\n        data : bool, optional\n            Whether to include the actual data in the dictionary. When set to\n            False, returns just the schema.\n\n        See also\n        --------\n        DataArray.from_dict"
  },
  {
    "code": "def _init_cfg_interfaces(self, cb, intf_list=None, all_intf=True):\n        if not all_intf:\n            self.intf_list = intf_list\n        else:\n            self.intf_list = sys_utils.get_all_run_phy_intf()\n        self.cb = cb\n        self.intf_attr = {}\n        self.cfg_lldp_interface_list(self.intf_list)",
    "docstring": "Configure the interfaces during init time."
  },
  {
    "code": "def keys(self, namespace, prefix=None, limit=None, offset=None):\n        params = [namespace]\n        query = 'SELECT key FROM gauged_keys WHERE namespace = %s'\n        if prefix is not None:\n            query += ' AND key LIKE %s'\n            params.append(prefix + '%')\n        if limit is not None:\n            query += ' LIMIT %s'\n            params.append(limit)\n        if offset is not None:\n            query += ' OFFSET %s'\n            params.append(offset)\n        cursor = self.cursor\n        cursor.execute(query, params)\n        return [key for key, in cursor]",
    "docstring": "Get keys from a namespace"
  },
  {
    "code": "def _split_ns_command(cmd_token):\n    namespace = None\n    cmd_split = cmd_token.split(\".\", 1)\n    if len(cmd_split) == 1:\n        command = cmd_split[0]\n    else:\n        namespace = cmd_split[0]\n        command = cmd_split[1]\n    if not namespace:\n        namespace = \"\"\n    return namespace.lower(), command.lower()",
    "docstring": "Extracts the name space and the command name of the given command token.\n\n    :param cmd_token: The command token\n    :return: The extracted (name space, command) tuple"
  },
  {
    "code": "def read(self, path, filename=None, offset=None, size=-1):\n        storageScheme, key = self.getkey(path, filename=filename)\n        if offset or (size > -1):\n            if not offset:\n                offset = 0\n            if size > -1:\n                sizeStr = offset + size - 1\n            else:\n                sizeStr = \"\"\n            headers = {\"Range\": \"bytes=%d-%s\" % (offset, sizeStr)}\n            return key.get_contents_as_string(headers=headers)\n        else:\n            return key.get_contents_as_string()",
    "docstring": "Read a file specified by path."
  },
  {
    "code": "def load_shared_data(path: typing.Union[str, None]) -> dict:\n    if path is None:\n        return dict()\n    if not os.path.exists(path):\n        raise FileNotFoundError('No such shared data file \"{}\"'.format(path))\n    try:\n        with open(path, 'r') as fp:\n            data = json.load(fp)\n    except Exception:\n        raise IOError('Unable to read shared data file \"{}\"'.format(path))\n    if not isinstance(data, dict):\n        raise ValueError('Shared data must load into a dictionary object')\n    return data",
    "docstring": "Load shared data from a JSON file stored on disk"
  },
  {
    "code": "def drawHUD(self):\n        self.win.move(self.height - 2, self.x_pad)\n        self.win.clrtoeol()\n        self.win.box()\n        self.addstr(2, self.x_pad + 1, \"Population: %i\" % len(self.grid))\n        self.addstr(3, self.x_pad + 1, \"Generation: %s\" % self.current_gen)\n        self.addstr(3, self.x_grid - 21, \"s: start    p: pause\")\n        self.addstr(2, self.x_grid - 21, \"r: restart  q: quit\")",
    "docstring": "Draw information on population size and current generation"
  },
  {
    "code": "def tile_y_size(self, zoom):\n        warnings.warn(DeprecationWarning(\"tile_y_size is deprecated\"))\n        validate_zoom(zoom)\n        return round(self.y_size / self.matrix_height(zoom), ROUND)",
    "docstring": "Height of a tile in SRID units at zoom level.\n\n        - zoom: zoom level"
  },
  {
    "code": "def load_fixture(fixture_file):\n    utils.check_for_local_server()\n    local_url = config[\"local_server\"][\"url\"]\n    server = Server(local_url)\n    fixture = json.load(fixture_file)\n    for db_name, _items in fixture.items():\n        db = server[db_name]\n        with click.progressbar(\n            _items, label=db_name, length=len(_items)\n        ) as items:\n            for item in items:\n                item_id = item[\"_id\"]\n                if item_id in db:\n                    old_item = db[item_id]\n                    item[\"_rev\"] = old_item[\"_rev\"]\n                    if item == old_item:\n                        continue\n                db[item_id] = item",
    "docstring": "Populate the database from a JSON file. Reads the JSON file FIXTURE_FILE\n    and uses it to populate the database. Fuxture files should consist of a\n    dictionary mapping database names to arrays of objects to store in those\n    databases."
  },
  {
    "code": "def print_mem(unit=\"MB\"):\n    try:\n        import psutil\n        B = float(psutil.Process(os.getpid()).memory_info().vms)\n        KB = B / 1024\n        MB = KB / 1024\n        GB = MB / 1024\n        result = vars()[unit]\n        print_info(\"memory usage: %.2f(%s)\" % (result, unit))\n        return result\n    except ImportError:\n        print_info(\"pip install psutil first.\")",
    "docstring": "Show the proc-mem-cost with psutil, use this only for lazinesssss.\n\n    :param unit: B, KB, MB, GB."
  },
  {
    "code": "def item(self, name, fuzzy_threshold=100):\n        match = process.extractOne(\n            name,\n            self._items.keys(),\n            score_cutoff=(fuzzy_threshold-1),\n        )\n        if match:\n            exact_name = match[0]\n            item = self._items[exact_name]\n            item.decrypt_with(self)\n            return item\n        else:\n            return None",
    "docstring": "Extract a password from an unlocked Keychain using fuzzy\n        matching. ``fuzzy_threshold`` can be an integer between 0 and\n        100, where 100 is an exact match."
  },
  {
    "code": "def set_affinity(pid, cpuset):\n    _cpuset = cpu_set_t()\n    __CPU_ZERO(_cpuset)\n    for i in cpuset:\n        if i in range(0, sizeof(cpu_set_t) * 8):\n            __CPU_SET(i, _cpuset)\n    if libnuma.sched_setaffinity(pid, sizeof(cpu_set_t), byref(_cpuset)) < 0:\n        raise RuntimeError()",
    "docstring": "Sets  the  CPU  affinity  mask of the process whose ID is pid to the value specified by mask.\n\n    If pid is zero, then the calling process is used.\n\n    @param pid: process PID (0 == current process)\n    @type pid: C{int}\n    @param cpuset: set of CPU ids\n    @type cpuset: C{set}"
  },
  {
    "code": "def _get_rnn_layer(mode, num_layers, input_size, hidden_size, dropout, weight_dropout):\n    if mode == 'rnn_relu':\n        rnn_block = functools.partial(rnn.RNN, activation='relu')\n    elif mode == 'rnn_tanh':\n        rnn_block = functools.partial(rnn.RNN, activation='tanh')\n    elif mode == 'lstm':\n        rnn_block = rnn.LSTM\n    elif mode == 'gru':\n        rnn_block = rnn.GRU\n    block = rnn_block(hidden_size, num_layers, dropout=dropout,\n                      input_size=input_size)\n    if weight_dropout:\n        apply_weight_drop(block, '.*h2h_weight', rate=weight_dropout)\n    return block",
    "docstring": "create rnn layer given specs"
  },
  {
    "code": "def get_new_term_doc_mat(self, doc_domains):\n\t\tassert len(doc_domains) == self.term_doc_matrix.get_num_docs()\n\t\tdoc_domain_set = set(doc_domains)\n\t\tnum_terms = self.term_doc_matrix.get_num_terms()\n\t\tnum_domains = len(doc_domain_set)\n\t\tdomain_mat = lil_matrix((num_domains, num_terms), dtype=int)\n\t\tX = self.term_doc_matrix.get_term_doc_mat()\n\t\tfor i, domain in enumerate(doc_domain_set):\n\t\t\tdomain_mat[i, :] = X[np.array(doc_domains == domain)].sum(axis=0)\n\t\treturn domain_mat.tocsr()",
    "docstring": "Combines documents together that are in the same domain\n\n\t\tParameters\n\t\t----------\n\t\tdoc_domains : array-like\n\n\t\tReturns\n\t\t-------\n\t\tscipy.sparse.csr_matrix"
  },
  {
    "code": "def _compute(self, feed_dict, shard):\n        try:\n            descriptor, enq = self._tfrun(self._tf_expr[shard], feed_dict=feed_dict)\n            self._inputs_waiting.decrement(shard)\n        except Exception as e:\n            montblanc.log.exception(\"Compute Exception\")\n            raise",
    "docstring": "Call the tensorflow compute"
  },
  {
    "code": "def interface(self, value):\n        self._interface = value\n        if isinstance(value, int):\n            self._device_number = value\n        else:\n            self._serial_number = value",
    "docstring": "Sets the interface used to connect to the device.\n\n        :param value: may specify either the serial number or the device index\n        :type value: string or int"
  },
  {
    "code": "def codemirror_field_css_assets(*args):\n    manifesto = CodemirrorAssetTagRender()\n    manifesto.register_from_fields(*args)\n    return mark_safe(manifesto.css_html())",
    "docstring": "Tag to render CodeMirror CSS assets needed for all given fields.\n\n    Example:\n        ::\n\n        {% load djangocodemirror_tags %}\n        {% codemirror_field_css_assets form.myfield1 form.myfield2 %}"
  },
  {
    "code": "def fix_timezone_separator(cls, timestr):\n        tz_sep = cls.TIMEZONE_SEPARATOR.match(timestr)\n        if tz_sep is not None:\n            return tz_sep.group(1) + tz_sep.group(2) + ':' + tz_sep.group(3)\n        return timestr",
    "docstring": "Replace invalid timezone separator to prevent\n        `dateutil.parser.parse` to raise.\n\n        :return: the new string if invalid separators were found,\n                 `None` otherwise"
  },
  {
    "code": "def add_package(\n    self,\n    package,\n    node_paths=None, \n    type_option=PackageInstallationTypeOption.PROD,\n    version_option=None):\n    args=self._get_add_package_args(\n      package,\n      type_option=type_option,\n      version_option=version_option)\n    return self.run_command(args=args, node_paths=node_paths)",
    "docstring": "Returns a command that when executed will add a node package to current node module.\n\n    :param package: string.  A valid npm/yarn package description.  The accepted forms are\n      package-name, package-name@version, package-name@tag, file:/folder, file:/path/to.tgz\n      https://url/to.tgz\n    :param node_paths: A list of path that should be included in $PATH when\n      running the script.\n    :param type_option: A value from PackageInstallationTypeOption that indicates the type\n      of package to be installed. Default to 'prod', which is a production dependency.\n    :param version_option: A value from PackageInstallationVersionOption that indicates how\n      to match version. Default to None, which uses package manager default."
  },
  {
    "code": "def run(self):\n        with utils.ChangeDir(self.dirname):\n            sys.path.insert(0, self.dirname)\n            sys.argv[1:] = self.args\n            runpy.run_module(self.not_suffixed(self.filename),\n                             run_name='__main__',\n                             alter_sys=True)",
    "docstring": "Executes the code of the specified module."
  },
  {
    "code": "def configure(self, args):\n        for plug in self._plugins:\n            plug_name = self.plugin_name(plug)\n            plug.enabled = getattr(args, \"plugin_%s\" % plug_name, False)\n            if plug.enabled and getattr(plug, \"configure\", None):\n                if callable(getattr(plug, \"configure\", None)):\n                    plug.configure(args)\n        LOG.debug(\"Available plugins: %s\", self._plugins)\n        self.plugins = [plugin for plugin in self._plugins if getattr(plugin, \"enabled\", False)]\n        LOG.debug(\"Enabled plugins: %s\", self.plugins)",
    "docstring": "Configure the set of plugins with the given args.\n\n        After configuration, disabled plugins are removed from the plugins list."
  },
  {
    "code": "def setHandler(self,handler,cbfn):\n\t\tif handler == \"async-responses\":\n\t\t\tself.async_responses_callback = cbfn\n\t\telif handler == \"registrations-expired\":\n\t\t\tself.registrations_expired_callback = cbfn\n\t\telif handler == \"de-registrations\":\n\t\t\tself.de_registrations_callback = cbfn\n\t\telif handler == \"reg-updates\":\n\t\t\tself.reg_updates_callback = cbfn\n\t\telif handler == \"registrations\":\n\t\t\tself.registrations_callback = cbfn\n\t\telif handler == \"notifications\":\n\t\t\tself.notifications_callback = cbfn\n\t\telse:\n\t\t\tself.log.warn(\"'%s' is not a legitimate notification channel option. Please check your spelling.\",handler)",
    "docstring": "Register a handler for a particular notification type.\n\t\tThese are the types of notifications that are acceptable. \n\t\t\n\t\t| 'async-responses'\n\t\t| 'registrations-expired'\n\t\t| 'de-registrations'\n\t\t| 'reg-updates'\n\t\t| 'registrations'\n\t\t| 'notifications'\n\n\t\t:param str handler: name of the notification type\n\t\t:param fnptr cbfn: function to pass the notification channel messages to.\n\t\t:return: Nothing."
  },
  {
    "code": "def banner(message, width=30, style='banner', out=sys.stdout):\n    out.write(header([message], width=max(width, len(message)), style=style) + '\\n')\n    out.flush()",
    "docstring": "Prints a banner message\n\n    Parameters\n    ----------\n    message : string\n        The message to print in the banner\n\n    width : int\n        The minimum width of the banner (Default: 30)\n\n    style : string\n        A line formatting style (Default: 'banner')\n\n    out : writer\n        An object that has write() and flush() methods (Default: sys.stdout)"
  },
  {
    "code": "def login_required(self, f):\n        @wraps(f)\n        def wrapped_f(*args, **kwargs):\n            if current_user.anonymous:\n                msg = (\"Rejected User '%s access to '%s' as user\"\n                       \" could not be authenticated.\")\n                self.logger.warn(msg % (\n                    current_user.user_id,\n                    request.path\n                ))\n                raise FlaskKeystoneUnauthorized()\n            return f(*args, **kwargs)\n        return wrapped_f",
    "docstring": "Require a user to be validated by Identity to access an endpoint.\n\n        :raises: FlaskKeystoneUnauthorized\n\n        This method will gate a particular endpoint to only be accessed by\n        :class:`FlaskKeystone.User`'s. This means that a valid token will need\n        to be passed to grant access. If a User is not authenticated,\n        a FlaskKeystoneUnauthorized will be thrown, resulting in a 401 response\n        to the client."
  },
  {
    "code": "def tune(self, verbose=None):\n        if not self._tune:\n            return False\n        else:\n            self.w_tune.append(\n                abs(self.stochastic.last_value - self.stochastic.value))\n            self.w = 2 * (sum(self.w_tune) / len(self.w_tune))\n            return True",
    "docstring": "Tuning initial slice width parameter"
  },
  {
    "code": "def on(event, *args, **kwargs):\n    def wrapper(func):\n        for i, arg in args:\n            kwargs[i] = arg\n        func.event = Event(event, kwargs)\n        return func\n    return wrapper",
    "docstring": "Event method wrapper for bot mixins. When a bot is constructed,\n    its metaclass inspects all members of all base classes, and\n    looks for methods marked with an event attribute which is assigned\n    via this wrapper. It then stores all the methods in a dict\n    that maps event names to lists of these methods, which are each\n    called when the event occurs."
  },
  {
    "code": "def _default_format(self, occur):\n        if self.text or self.children:\n            return self.start_tag() + \"%s\" + self.end_tag()\n        return self.start_tag(empty=True)",
    "docstring": "Return the default serialization format."
  },
  {
    "code": "def _open(filename=None, mode='r'):\n    if not filename or filename == '-':\n        if not mode or 'r' in mode:\n            file = sys.stdin\n        elif 'w' in mode:\n            file = sys.stdout\n        else:\n            raise ValueError('Invalid mode for file: {}'.format(mode))\n    else:\n        file = open(filename, mode)\n    try:\n        yield file\n    finally:\n        if file not in (sys.stdin, sys.stdout):\n            file.close()",
    "docstring": "Open a file or ``sys.stdout`` depending on the provided filename.\n\n    Args:\n        filename (str): The path to the file that should be opened. If\n            ``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is\n            returned depending on the desired mode. Defaults to ``None``.\n        mode (str): The mode that should be used to open the file.\n\n    Yields:\n        A file handle."
  },
  {
    "code": "def command(self, function=None, prefix=None, unobserved=False):\n        captured_f = self.capture(function, prefix=prefix)\n        captured_f.unobserved = unobserved\n        self.commands[function.__name__] = captured_f\n        return captured_f",
    "docstring": "Decorator to define a new command for this Ingredient or Experiment.\n\n        The name of the command will be the name of the function. It can be\n        called from the command-line or by using the run_command function.\n\n        Commands are automatically also captured functions.\n\n        The command can be given a prefix, to restrict its configuration space\n        to a subtree. (see ``capture`` for more information)\n\n        A command can be made unobserved (i.e. ignoring all observers) by\n        passing the unobserved=True keyword argument."
  },
  {
    "code": "def config(self, charm_id, channel=None):\n        url = '{}/{}/meta/charm-config'.format(self.url, _get_path(charm_id))\n        data = self._get(_add_channel(url, channel))\n        return data.json()",
    "docstring": "Get the config data for a charm.\n\n        @param charm_id The charm's id.\n        @param channel Optional channel name."
  },
  {
    "code": "def ApplyPluginToMultiTypeCollection(plugin, output_collection,\n                                     source_urn=None):\n  for chunk in plugin.Start():\n    yield chunk\n  for stored_type_name in sorted(output_collection.ListStoredTypes()):\n    stored_cls = rdfvalue.RDFValue.classes[stored_type_name]\n    def GetValues():\n      for timestamp, value in output_collection.ScanByType(stored_type_name):\n        _ = timestamp\n        if source_urn:\n          value.source = source_urn\n        yield value\n    for chunk in plugin.ProcessValues(stored_cls, GetValues):\n      yield chunk\n  for chunk in plugin.Finish():\n    yield chunk",
    "docstring": "Applies instant output plugin to a multi-type collection.\n\n  Args:\n    plugin: InstantOutputPlugin instance.\n    output_collection: MultiTypeCollection instance.\n    source_urn: If not None, override source_urn for collection items. This has\n      to be used when exporting flow results - their GrrMessages don't have\n      \"source\" attribute set.\n\n  Yields:\n    Bytes chunks, as generated by the plugin."
  },
  {
    "code": "def plot_state_histogram(self, ax):\n        title = \"Estimated state\"\n        nqc = int(round(np.log2(self.rho_est.data.shape[0])))\n        labels = ut.basis_labels(nqc)\n        return ut.state_histogram(self.rho_est, ax, title)",
    "docstring": "Visualize the complex matrix elements of the estimated state.\n\n        :param matplotlib.Axes ax: A matplotlib Axes object to plot into."
  },
  {
    "code": "def _build_xpath_expr(attrs):\n    if 'class_' in attrs:\n        attrs['class'] = attrs.pop('class_')\n    s = [\"@{key}={val!r}\".format(key=k, val=v) for k, v in attrs.items()]\n    return '[{expr}]'.format(expr=' and '.join(s))",
    "docstring": "Build an xpath expression to simulate bs4's ability to pass in kwargs to\n    search for attributes when using the lxml parser.\n\n    Parameters\n    ----------\n    attrs : dict\n        A dict of HTML attributes. These are NOT checked for validity.\n\n    Returns\n    -------\n    expr : unicode\n        An XPath expression that checks for the given HTML attributes."
  },
  {
    "code": "def normalize_missing(xs):\n    if isinstance(xs, dict):\n        for k, v in xs.items():\n            xs[k] = normalize_missing(v)\n    elif isinstance(xs, (list, tuple)):\n        xs = [normalize_missing(x) for x in xs]\n    elif isinstance(xs, six.string_types):\n        if xs.lower() in [\"none\", \"null\"]:\n            xs = None\n        elif xs.lower() == \"true\":\n            xs = True\n        elif xs.lower() == \"false\":\n            xs = False\n    return xs",
    "docstring": "Normalize missing values to avoid string 'None' inputs."
  },
  {
    "code": "def literalize(self):\n        if self.isliteral:\n            return self\n        args = tuple(arg.literalize() for arg in self.args)\n        if all(arg is self.args[i] for i, arg in enumerate(args)):\n            return self\n        return self.__class__(*args)",
    "docstring": "Return an expression where NOTs are only occurring as literals.\n        Applied recursively to subexpressions."
  },
  {
    "code": "def LoadFromFile(cls, script_path):\n        _name, dev = ComponentRegistry().load_extension(script_path, class_filter=VirtualTile, unique=True)\n        return dev",
    "docstring": "Import a virtual tile from a file rather than an installed module\n\n        script_path must point to a python file ending in .py that contains exactly one\n        VirtualTile class definition.  That class is loaded and executed as if it\n        were installed.\n\n        To facilitate development, if there is a proxy object defined in the same\n        file, it is also added to the HardwareManager proxy registry so that it\n        can be found and used with the device.\n\n        Args:\n            script_path (string): The path to the script to load\n\n        Returns:\n            VirtualTile: A subclass of VirtualTile that was loaded from script_path"
  },
  {
    "code": "def save_config(self):\n        if not os.path.exists(self._conf_dir):\n            os.makedirs(self._conf_dir)\n        conf_file = os.path.join(self._conf_dir, \"dql.json\")\n        with open(conf_file, \"w\") as ofile:\n            json.dump(self.conf, ofile, indent=2)",
    "docstring": "Save the conf file"
  },
  {
    "code": "def get_broks_from_satellites(self):\n        for satellites in [self.conf.brokers, self.conf.schedulers,\n                           self.conf.pollers, self.conf.reactionners, self.conf.receivers]:\n            for satellite in satellites:\n                if not satellite.reachable:\n                    continue\n                logger.debug(\"Getting broks from: %s\", satellite.name)\n                new_broks = satellite.get_and_clear_broks()\n                if new_broks:\n                    logger.debug(\"Got %d broks from: %s\", len(new_broks), satellite.name)\n                for brok in new_broks:\n                    self.add(brok)",
    "docstring": "Get broks from my all internal satellite links\n\n        The arbiter get the broks from ALL the known satellites\n\n        :return: None"
  },
  {
    "code": "def get_diagonalizing_basis(list_of_pauli_terms):\n    qubit_ops = set(reduce(lambda x, y: x + y,\n                       [list(term._ops.items()) for term in list_of_pauli_terms]))\n    qubit_ops = sorted(list(qubit_ops), key=lambda x: x[0])\n    return PauliTerm.from_list(list(map(lambda x: tuple(reversed(x)), qubit_ops)))",
    "docstring": "Find the Pauli Term with the most non-identity terms\n\n    :param list_of_pauli_terms: List of Pauli terms to check\n    :return: The highest weight Pauli Term\n    :rtype: PauliTerm"
  },
  {
    "code": "def convert_coordinates(self, points, axisorder='blr'):\n        return convert_coordinates_sequence(points,self._boundary_scale,\n                                            self._axis_limits, axisorder)",
    "docstring": "Convert data coordinates to simplex coordinates for plotting\n        in the case that axis limits have been applied."
  },
  {
    "code": "def _get_column_dtype(llwcol):\n    try:\n        dtype = llwcol.dtype\n        if dtype is numpy.dtype('O'):\n            raise AttributeError\n        return dtype\n    except AttributeError:\n        try:\n            llwtype = llwcol.parentNode.validcolumns[llwcol.Name]\n        except AttributeError:\n            try:\n                return type(llwcol[0])\n            except IndexError:\n                return None\n        else:\n            from ligo.lw.types import (ToPyType, ToNumPyType)\n            try:\n                return ToNumPyType[llwtype]\n            except KeyError:\n                return ToPyType[llwtype]",
    "docstring": "Get the data type of a LIGO_LW `Column`\n\n    Parameters\n    ----------\n    llwcol : :class:`~ligo.lw.table.Column`, `numpy.ndarray`, iterable\n        a LIGO_LW column, a numpy array, or an iterable\n\n    Returns\n    -------\n    dtype : `type`, None\n        the object data type for values in the given column, `None` is\n        returned if ``llwcol`` is a `numpy.ndarray` with `numpy.object_`\n        dtype, or no data type can be parsed (e.g. empty list)"
  },
  {
    "code": "def search_results_total(html, xpath, check, delimiter):\n    for container in html.findall(xpath):\n        if check in container.findtext('.'):\n            text = container.findtext('.').split(delimiter)\n            total = int(text[-1].strip())\n            return total",
    "docstring": "Get the total number of results from the DOM of a search index."
  },
  {
    "code": "def set_replication_enabled(status, host=None, core_name=None):\n    if not _is_master() and _get_none_or_value(host) is None:\n        return _get_return_dict(False,\n                errors=['Only minions configured as master can run this'])\n    cmd = 'enablereplication' if status else 'disablereplication'\n    if _get_none_or_value(core_name) is None and _check_for_cores():\n        ret = _get_return_dict()\n        success = True\n        for name in __opts__['solr.cores']:\n            resp = set_replication_enabled(status, host, name)\n            if not resp['success']:\n                success = False\n            data = {name: {'data': resp['data']}}\n            ret = _update_return_dict(ret, success, data,\n                    resp['errors'], resp['warnings'])\n        return ret\n    else:\n        if status:\n            return _replication_request(cmd, host=host, core_name=core_name)\n        else:\n            return _replication_request(cmd, host=host, core_name=core_name)",
    "docstring": "MASTER ONLY\n    Sets the master to ignore poll requests from the slaves. Useful when you\n    don't want the slaves replicating during indexing or when clearing the\n    index.\n\n    status : boolean\n        Sets the replication status to the specified state.\n    host : str (None)\n        The solr host to query. __opts__['host'] is default.\n\n    core_name : str (None)\n        The name of the solr core if using cores. Leave this blank if you are\n        not using cores or if you want to set the status on all cores.\n\n    Return : dict<str,obj>::\n\n        {'success':boolean, 'data':dict, 'errors':list, 'warnings':list}\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' solr.set_replication_enabled false, None, music"
  },
  {
    "code": "def eps(self, file, scale=1, module_color=(0, 0, 0),\n            background=None, quiet_zone=4):\n        builder._eps(self.code, self.version, file, scale, module_color,\n                     background, quiet_zone)",
    "docstring": "This method writes the QR code out as an EPS document. The\n        code is drawn by only writing the data modules corresponding to a 1.\n        They are drawn using a line, such that contiguous modules in a row\n        are drawn with a single line.\n\n        The *file* parameter is used to specify where to write the document\n        to. It can either be a writable (text) stream or a file path.\n\n        The *scale* parameter sets how large to draw a single module. By\n        default one point (1/72 inch) is used to draw a single module. This may\n        make the code to small to be read efficiently. Increasing the scale\n        will make the code larger. This method will accept fractional scales\n        (e.g. 2.5).\n\n        The *module_color* parameter sets the color of the data modules. The\n        *background* parameter sets the background (page) color to use. They\n        are specified as either a triple of floats, e.g. (0.5, 0.5, 0.5), or a\n        triple of integers, e.g. (128, 128, 128). The default *module_color* is\n        black. The default *background* color is no background at all.\n\n        The *quiet_zone* parameter sets how large to draw the border around\n        the code. As per the standard, the default value is 4 modules.\n\n        Examples:\n            >>> qr = pyqrcode.create('Hello world')\n            >>> qr.eps('hello-world.eps', scale=2.5, module_color='#36C')\n            >>> qr.eps('hello-world2.eps', background='#eee')\n            >>> out = io.StringIO()\n            >>> qr.eps(out, module_color=(.4, .4, .4))"
  },
  {
    "code": "def ec2_credentials_create(user_id=None, name=None,\n                           tenant_id=None, tenant=None,\n                           profile=None, **connection_args):\n    kstone = auth(profile, **connection_args)\n    if name:\n        user_id = user_get(name=name, profile=profile,\n                           **connection_args)[name]['id']\n    if not user_id:\n        return {'Error': 'Could not resolve User ID'}\n    if tenant:\n        tenant_id = tenant_get(name=tenant, profile=profile,\n                               **connection_args)[tenant]['id']\n    if not tenant_id:\n        return {'Error': 'Could not resolve Tenant ID'}\n    newec2 = kstone.ec2.create(user_id, tenant_id)\n    return {'access': newec2.access,\n            'secret': newec2.secret,\n            'tenant_id': newec2.tenant_id,\n            'user_id': newec2.user_id}",
    "docstring": "Create EC2-compatible credentials for user per tenant\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt '*' keystone.ec2_credentials_create name=admin tenant=admin\n\n        salt '*' keystone.ec2_credentials_create \\\n        user_id=c965f79c4f864eaaa9c3b41904e67082 \\\n        tenant_id=722787eb540849158668370dc627ec5f"
  },
  {
    "code": "def create_graphics(self):\n        rnftools.utils.shell('\"{}\" \"{}\"'.format(\"gnuplot\", self._gp_fn))\n        if self.render_pdf_method is not None:\n            svg_fn = self._svg_fn\n            pdf_fn = self._pdf_fn\n            svg42pdf(svg_fn, pdf_fn, method=self.render_pdf_method)",
    "docstring": "Create images related to this BAM file using GnuPlot."
  },
  {
    "code": "def list_(prefix='', region=None, key=None, keyid=None, profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    def extract_name(queue_url):\n        return _urlparse(queue_url).path.split('/')[2]\n    try:\n        r = conn.list_queues(QueueNamePrefix=prefix)\n        urls = r.get('QueueUrls', [])\n        return {'result': [extract_name(url) for url in urls]}\n    except botocore.exceptions.ClientError as e:\n        return {'error': __utils__['boto3.get_error'](e)}",
    "docstring": "Return a list of the names of all visible queues.\n\n    .. versionadded:: 2016.11.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt myminion boto_sqs.list region=us-east-1"
  },
  {
    "code": "def display_info(self):\n        if self.moc is None:\n            print('No MOC information present')\n            return\n        if self.moc.name is not None:\n            print('Name:', self.moc.name)\n        if self.moc.id is not None:\n            print('Identifier:', self.moc.id)\n        print('Order:', self.moc.order)\n        print('Cells:', self.moc.cells)\n        print('Area:', self.moc.area_sq_deg, 'square degrees')",
    "docstring": "Display basic information about the running MOC."
  },
  {
    "code": "def open(self, print_matlab_welcome=False):\n        if self.process and not self.process.returncode:\n            raise MatlabConnectionError('Matlab(TM) process is still active. Use close to '\n                                            'close it')\n        self.process = subprocess.Popen(\n                [self.matlab_process_path, '-nojvm', '-nodesktop'],\n                stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        flags = fcntl.fcntl(self.process.stdout, fcntl.F_GETFL)\n        fcntl.fcntl(self.process.stdout, fcntl.F_SETFL, flags| os.O_NONBLOCK)\n        if print_matlab_welcome:\n            self._sync_output()\n        else:\n            self._sync_output(None)",
    "docstring": "Opens the matlab process."
  },
  {
    "code": "def createNode(self, cls, name, *args, **kw):\n        m = self.findNode(name)\n        if m is None:\n            m = cls(name, *args, **kw)\n            self.addNode(m)\n        return m",
    "docstring": "Add a node of type cls to the graph if it does not already exist\n        by the given name"
  },
  {
    "code": "def _query(self, text):\n        params = (\n            ('v', self.api_version),\n            ('query', text),\n            ('lang', self.language),\n            ('sessionId', self.session_id),\n            ('timezone', self.timezone),\n        )\n        if self.query_response:\n            self.previous_query_response = self.query_response\n        self.query_response = result = self.session.get(url=self.query_url, params=params).json()\n        return result",
    "docstring": "Takes natural language text and information as query parameters and returns information as JSON."
  },
  {
    "code": "def fn_std(self, a, axis=None):\n        return numpy.nanstd(self._to_ndarray(a), axis=axis)",
    "docstring": "Compute the standard deviation of an array, ignoring NaNs.\n\n        :param a: The array.\n        :return: The standard deviation of the array."
  },
  {
    "code": "def set_level(self, level):\n        for handler in self.__coloredlogs_handlers:\n            handler.setLevel(level=level)\n        self.logger.setLevel(level=level)",
    "docstring": "Set the logging level of this logger.\n\n        :param level: must be an int or a str."
  },
  {
    "code": "def get_clusters(self, platform, retry_contexts, all_clusters):\n        possible_cluster_info = {}\n        candidates = set(copy.copy(all_clusters))\n        while candidates and not possible_cluster_info:\n            wait_for_any_cluster(retry_contexts)\n            for cluster in sorted(candidates, key=attrgetter('priority')):\n                ctx = retry_contexts[cluster.name]\n                if ctx.in_retry_wait:\n                    continue\n                if ctx.failed:\n                    continue\n                try:\n                    cluster_info = self.get_cluster_info(cluster, platform)\n                    possible_cluster_info[cluster] = cluster_info\n                except OsbsException:\n                    ctx.try_again_later(self.find_cluster_retry_delay)\n            candidates -= set([c for c in candidates if retry_contexts[c.name].failed])\n        ret = sorted(possible_cluster_info.values(), key=lambda c: c.cluster.priority)\n        ret = sorted(ret, key=lambda c: c.load)\n        return ret",
    "docstring": "return clusters sorted by load."
  },
  {
    "code": "def cmd_tr(self, x=None, y=None, xy=None, ch=None):\n        viewer = self.get_viewer(ch)\n        if viewer is None:\n            self.log(\"No current viewer/channel.\")\n            return\n        fx, fy, sxy = viewer.get_transforms()\n        if x is None and y is None and xy is None:\n            self.log(\"x=%s y=%s xy=%s\" % (fx, fy, sxy))\n        else:\n            if x is None:\n                x = fx\n            else:\n                x = (x != 0)\n            if y is None:\n                y = fy\n            else:\n                y = (y != 0)\n            if xy is None:\n                xy = sxy\n            else:\n                xy = (xy != 0)\n            viewer.transform(x, y, xy)",
    "docstring": "tr x=0|1 y=0|1 xy=0|1 ch=chname\n\n        Transform the image for the given viewer/channel by flipping\n        (x=1 and/or y=1) or swapping axes (xy=1).\n        If no value is given, reports the current rotation."
  },
  {
    "code": "def report(self, name, **kwargs):\n        group_obj = Report(name, **kwargs)\n        return self._group(group_obj)",
    "docstring": "Add Report data to Batch object.\n\n        Args:\n            name (str): The name for this Group.\n            file_name (str): The name for the attached file for this Group.\n            date_added (str, kwargs): The date timestamp the Indicator was created.\n            file_content (str;method, kwargs): The file contents or callback method to retrieve\n                file content.\n            publish_date (str, kwargs): The publish datetime expression for this Group.\n            xid (str, kwargs): The external id for this Group.\n\n        Returns:\n            obj: An instance of Report."
  },
  {
    "code": "def override_temp(replacement):\n    pkg_resources.py31compat.makedirs(replacement, exist_ok=True)\n    saved = tempfile.tempdir\n    tempfile.tempdir = replacement\n    try:\n        yield\n    finally:\n        tempfile.tempdir = saved",
    "docstring": "Monkey-patch tempfile.tempdir with replacement, ensuring it exists"
  },
  {
    "code": "def checkASN(filename):\n    extnType = filename[filename.rfind('_')+1:filename.rfind('.')]\n    if isValidAssocExtn(extnType):\n        return True\n    else:\n        return False",
    "docstring": "Determine if the filename provided to the function belongs to\n    an association.\n\n    Parameters\n    ----------\n    filename: string\n\n    Returns\n    -------\n    validASN  : boolean value"
  },
  {
    "code": "def get_state(self):\n        D = {}\n        for key in self._state_props:\n            D[key] = getattr(self, key)\n        return D",
    "docstring": "Get the current view state of the camera\n\n        Returns a dict of key-value pairs. The exact keys depend on the\n        camera. Can be passed to set_state() (of this or another camera\n        of the same type) to reproduce the state."
  },
  {
    "code": "def __get_connection_info():\n    conn_info = {}\n    try:\n        conn_info['hostname'] = __opts__['mysql_auth']['hostname']\n        conn_info['username'] = __opts__['mysql_auth']['username']\n        conn_info['password'] = __opts__['mysql_auth']['password']\n        conn_info['database'] = __opts__['mysql_auth']['database']\n        conn_info['auth_sql'] = __opts__['mysql_auth']['auth_sql']\n    except KeyError as e:\n        log.error('%s does not exist', e)\n        return None\n    return conn_info",
    "docstring": "Grab MySQL Connection Details"
  },
  {
    "code": "def ancestor(self, index):\n        if not isinstance(index, int):\n            self.log_exc(u\"index is not an integer\", None, True, TypeError)\n        if index < 0:\n            self.log_exc(u\"index cannot be negative\", None, True, ValueError)\n        parent_node = self\n        for i in range(index):\n            if parent_node is None:\n                break\n            parent_node = parent_node.parent\n        return parent_node",
    "docstring": "Return the ``index``-th ancestor.\n\n        The 0-th ancestor is the node itself,\n        the 1-th ancestor is its parent node,\n        etc.\n\n        :param int index: the number of levels to go up\n        :rtype: :class:`~aeneas.tree.Tree`\n        :raises: TypeError if ``index`` is not an int\n        :raises: ValueError if ``index`` is negative"
  },
  {
    "code": "def delete(python_data: LdapObject, database: Optional[Database] = None) -> None:\n    dn = python_data.get_as_single('dn')\n    assert dn is not None\n    database = get_database(database)\n    connection = database.connection\n    connection.delete(dn)",
    "docstring": "Delete a LdapObject from the database."
  },
  {
    "code": "def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None,\n                   profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    r = {}\n    try:\n        key_policy = conn.get_key_policy(key_id, policy_name)\n        r['key_policy'] = salt.serializers.json.deserialize(\n            key_policy['Policy'],\n            object_pairs_hook=odict.OrderedDict\n        )\n    except boto.exception.BotoServerError as e:\n        r['error'] = __utils__['boto.get_error'](e)\n    return r",
    "docstring": "Get the policy for the specified key.\n\n    CLI example::\n\n        salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy"
  },
  {
    "code": "def wncomd(left, right, window):\n    assert isinstance(window, stypes.SpiceCell)\n    assert window.dtype == 1\n    left = ctypes.c_double(left)\n    right = ctypes.c_double(right)\n    result = stypes.SpiceCell.double(window.size)\n    libspice.wncomd_c(left, right, ctypes.byref(window), result)\n    return result",
    "docstring": "Determine the complement of a double precision window with\n    respect to a specified interval.\n\n    http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wncomd_c.html\n\n    :param left: left endpoints of complement interval. \n    :type left: float\n    :param right: right endpoints of complement interval. \n    :type right: float\n    :param window: Input window \n    :type window: spiceypy.utils.support_types.SpiceCell\n    :return: Complement of window with respect to left and right.\n    :rtype: spiceypy.utils.support_types.SpiceCell"
  },
  {
    "code": "def decode_header(header, normalize=False):\n    regex = r'\"(=\\?.+?\\?.+?\\?[^ ?]+\\?=)\"'\n    value = re.sub(regex, r'\\1', header)\n    logging.debug(\"unquoted header: |%s|\", value)\n    valuelist = email.header.decode_header(value)\n    decoded_list = []\n    for v, enc in valuelist:\n        v = string_decode(v, enc)\n        decoded_list.append(string_sanitize(v))\n    value = ''.join(decoded_list)\n    if normalize:\n        value = re.sub(r'\\n\\s+', r' ', value)\n    return value",
    "docstring": "decode a header value to a unicode string\n\n    values are usually a mixture of different substrings\n    encoded in quoted printable using different encodings.\n    This turns it into a single unicode string\n\n    :param header: the header value\n    :type header: str\n    :param normalize: replace trailing spaces after newlines\n    :type normalize: bool\n    :rtype: str"
  },
  {
    "code": "def sitespeptidesproteins(df, site_localization_probability=0.75):\n    sites = filters.filter_localization_probability(df, site_localization_probability)['Sequence window']\n    peptides = set(df['Sequence window'])\n    proteins = set([str(p).split(';')[0] for p in df['Proteins']])\n    return len(sites), len(peptides), len(proteins)",
    "docstring": "Generate summary count of modified sites, peptides and proteins in a processed dataset ``DataFrame``.\n\n    Returns the number of sites, peptides and proteins as calculated as follows:\n\n    - `sites` (>0.75; or specified site localization probability) count of all sites > threshold\n    - `peptides` the set of `Sequence windows` in the dataset (unique peptides)\n    - `proteins` the set of unique leading proteins in the dataset\n\n    :param df: Pandas ``DataFrame`` of processed data\n    :param site_localization_probability: ``float`` site localization probability threshold (for sites calculation)\n    :return: ``tuple`` of ``int``, containing sites, peptides, proteins"
  },
  {
    "code": "def register(cls, *args, **kwargs):\n        if cls.app is None:\n            return register(*args, handler=cls, **kwargs)\n        return cls.app.register(*args, handler=cls, **kwargs)",
    "docstring": "Register view to handler."
  },
  {
    "code": "def get_merged_filter(self):\n        track = set()\n        follow = set()\n        for handler in self.handlers:\n            track.update(handler.filter.track)\n            follow.update(handler.filter.follow)\n        return TweetFilter(track=list(track), follow=list(follow))",
    "docstring": "Return merged filter from list of handlers\n\n        :return: merged filter\n        :rtype: :class:`~responsebot.models.TweetFilter`"
  },
  {
    "code": "def parse_PISCES_output(pisces_output, path=False):\n    pisces_dict = {}\n    if path:\n        pisces_path = Path(pisces_output)\n        pisces_content = pisces_path.read_text().splitlines()[1:]\n    else:\n        pisces_content = pisces_output.splitlines()[1:]\n    for line in pisces_content:\n        pdb = line.split()[0][:4].lower()\n        chain = line.split()[0][-1]\n        pdb_dict = {'length': line.split()[1],\n                    'method': line.split()[2],\n                    'resolution': line.split()[3],\n                    'R-factor': line.split()[4],\n                    'R-free': line.split()[5]}\n        if pdb in pisces_dict:\n            pisces_dict[pdb]['chains'].append(chain)\n        else:\n            pdb_dict['chains'] = [chain]\n            pisces_dict[pdb] = pdb_dict\n    return pisces_dict",
    "docstring": "Takes the output list of a PISCES cull and returns in a usable dictionary.\n\n    Notes\n    -----\n    Designed for outputs of protein sequence redundancy culls conducted using the PISCES server.\n    http://dunbrack.fccc.edu/PISCES.php\n    G. Wang and R. L. Dunbrack, Jr. PISCES: a protein sequence culling server. Bioinformatics, 19:1589-1591, 2003.\n\n    Parameters\n    ----------\n    pisces_output : str or path\n        Output list of non-redundant protein chains from PISCES, or path to text file.\n    path : bool\n        True if path given rather than string.\n\n    Returns\n    -------\n    pisces_dict : dict\n        Data output by PISCES in dictionary form."
  },
  {
    "code": "def get_sequence_rules(self):\n        collection = JSONClientValidated('assessment_authoring',\n                                         collection='SequenceRule',\n                                         runtime=self._runtime)\n        result = collection.find(self._view_filter()).sort('_id', DESCENDING)\n        return objects.SequenceRuleList(result, runtime=self._runtime, proxy=self._proxy)",
    "docstring": "Gets all ``SequenceRules``.\n\n        return: (osid.assessment.authoring.SequenceRuleList) - the\n                returned ``SequenceRule`` list\n        raise:  OperationFailed - unable to complete request\n        raise:  PermissionDenied - authorization failure\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def shell_process(command, input_data=None, background=False, exitcode=False):\n    data = None\n    try:\n        kwargs = {\n            'shell': isinstance(command, basestring),\n            'stdout': subprocess.PIPE,\n            'stderr': subprocess.PIPE\n        }\n        if not input_data is None:\n            kwargs['stdin'] = subprocess.PIPE\n        proc = subprocess.Popen(command, **kwargs)\n        if not background:\n            output, _ = proc.communicate(input_data)\n            retcode = proc.returncode\n            if retcode == 0:\n                data = str(output).rstrip()\n        else:\n            retcode = None\n            if input_data:\n                raise TypeError(u'Backgrounded does not support input data.')\n    except OSError as exc:\n        retcode = -exc.errno\n    if exitcode:\n        return data, retcode\n    else:\n        return data",
    "docstring": "Shells a process with the given shell command.\n\n        `command`\n            Shell command to spawn.\n        `input_data`\n            String to pipe to process as input.\n        `background`\n            Set to ``True`` to fork process into background.\n            NOTE: This exits immediately with no result returned.\n        `exitcode`\n            Set to ``True`` to also return process exit status code.\n\n        if `exitcode` is ``False``, then this returns output string from\n        process or ``None`` if it failed.\n\n        otherwise, this returns a tuple with output string from process or\n        ``None`` if it failed and the exit status code.\n\n            Example::\n                (``None``, 1) <-- failed\n                ('Some data', 0) <-- success"
  },
  {
    "code": "def push(item, remote_addr, trg_queue, protocol=u'jsonrpc'):\n    if protocol == u'jsonrpc':\n        try:\n            server = Server(remote_addr, encoding=_c.FSQ_CHARSET)\n            return server.enqueue(item.id, trg_queue, item.item.read())\n        except Exception, e:\n            raise FSQPushError(e)\n    raise ValueError('Unknown protocol: {0}'.format(protocol))",
    "docstring": "Enqueue an FSQWorkItem at a remote queue"
  },
  {
    "code": "def get_global_shelf_fpath(appname='default', ensure=False):\n    global_cache_dir = get_global_cache_dir(appname, ensure=ensure)\n    shelf_fpath = join(global_cache_dir, meta_util_constants.global_cache_fname)\n    return shelf_fpath",
    "docstring": "Returns the filepath to the global shelf"
  },
  {
    "code": "def _add_plots_to_output(out, data):\n    out[\"plot\"] = {}\n    diagram_plot = _add_diagram_plot(out, data)\n    if diagram_plot:\n        out[\"plot\"][\"diagram\"] = diagram_plot\n    scatter = _add_scatter_plot(out, data)\n    if scatter:\n        out[\"plot\"][\"scatter\"] = scatter\n    scatter_global = _add_global_scatter_plot(out, data)\n    if scatter_global:\n        out[\"plot\"][\"scatter_global\"] = scatter_global\n    return out",
    "docstring": "Add CNVkit plots summarizing called copy number values."
  },
  {
    "code": "def partof(self, ns1, id1, ns2, id2):\n        rel_fun = lambda node, graph: self.partof_objects(node)\n        return self.directly_or_indirectly_related(ns1, id1, ns2, id2,\n                                                   self.partof_closure,\n                                                   rel_fun)",
    "docstring": "Return True if one entity is \"partof\" another.\n\n        Parameters\n        ----------\n        ns1 : str\n            Namespace code for an entity.\n        id1 : str\n            URI for an entity.\n        ns2 : str\n            Namespace code for an entity.\n        id2 : str\n            URI for an entity.\n\n        Returns\n        -------\n        bool\n            True if t1 has a \"partof\" relationship with t2, either directly or\n            through a series of intermediates; False otherwise."
  },
  {
    "code": "def get_dataset(self, X, y=None):\n        if is_dataset(X):\n            return X\n        dataset = self.dataset\n        is_initialized = not callable(dataset)\n        kwargs = self._get_params_for('dataset')\n        if kwargs and is_initialized:\n            raise TypeError(\"Trying to pass an initialized Dataset while \"\n                            \"passing Dataset arguments ({}) is not \"\n                            \"allowed.\".format(kwargs))\n        if is_initialized:\n            return dataset\n        return dataset(X, y, **kwargs)",
    "docstring": "Get a dataset that contains the input data and is passed to\n        the iterator.\n\n        Override this if you want to initialize your dataset\n        differently.\n\n        Parameters\n        ----------\n        X : input data, compatible with skorch.dataset.Dataset\n          By default, you should be able to pass:\n\n            * numpy arrays\n            * torch tensors\n            * pandas DataFrame or Series\n            * scipy sparse CSR matrices\n            * a dictionary of the former three\n            * a list/tuple of the former three\n            * a Dataset\n\n          If this doesn't work with your data, you have to pass a\n          ``Dataset`` that can deal with the data.\n\n        y : target data, compatible with skorch.dataset.Dataset\n          The same data types as for ``X`` are supported. If your X is\n          a Dataset that contains the target, ``y`` may be set to\n          None.\n\n        Returns\n        -------\n        dataset\n          The initialized dataset."
  },
  {
    "code": "def get(cls, pid_value, pid_type=None, **kwargs):\n        return cls(\n            PersistentIdentifier.get(pid_type or cls.pid_type, pid_value,\n                                     pid_provider=cls.pid_provider),\n            **kwargs)",
    "docstring": "Get a persistent identifier for this provider.\n\n        :param pid_type: Persistent identifier type. (Default: configured\n            :attr:`invenio_pidstore.providers.base.BaseProvider.pid_type`)\n        :param pid_value: Persistent identifier value.\n        :param kwargs: See\n            :meth:`invenio_pidstore.providers.base.BaseProvider` required\n            initialization properties.\n        :returns: A :class:`invenio_pidstore.providers.base.BaseProvider`\n            instance."
  },
  {
    "code": "def getBlocks(sentences, n):\n    blocks = []\n    for i in range(0, len(sentences), n):\n        blocks.append(sentences[i:(i+n)])\n    return blocks",
    "docstring": "Get blocks of n sentences together.\n\n    :param sentences: List of strings where  each string is a sentence.\n    :type sentences: list\n    :param n: Maximum blocksize for sentences, i.e. a block will be composed of\n              ``n`` sentences.\n    :type n: int.\n\n    :returns: Blocks of n sentences.\n    :rtype: list-of-lists\n\n    .. code-block:: python\n\n                    import rnlp\n\n                    example = \"Hello there. How are you? I am fine.\"\n\n                    sentences = rnlp.getSentences(example)\n                    # ['Hello there', 'How are you', 'I am fine']\n\n                    blocks = rnlp.getBlocks(sentences, 2)\n                    # with 1: [['Hello there'], ['How are you'], ['I am fine']]\n                    # with 2: [['Hello there', 'How are you'], ['I am fine']]\n                    # with 3: [['Hello there', 'How are you', 'I am fine']]"
  },
  {
    "code": "def _rel_path(self, path, basepath=None):\n        basepath = basepath or self.src_dir\n        return path[len(basepath) + 1:]",
    "docstring": "trim off basepath"
  },
  {
    "code": "def cal_k_bm3(p, k):\n    v = cal_v_bm3(p, k)\n    return cal_k_bm3_from_v(v, k)",
    "docstring": "calculate bulk modulus\n\n    :param p: pressure\n    :param k: [v0, k0, k0p]\n    :return: bulk modulus at high pressure"
  },
  {
    "code": "def LaplaceCentreWeight(self):\n        sz = [1,] * self.S.ndim\n        for ax in self.axes:\n            sz[ax] = self.S.shape[ax]\n        lcw = 2*len(self.axes)*np.ones(sz, dtype=self.dtype)\n        for ax in self.axes:\n            lcw[(slice(None),)*ax + ([0, -1],)] -= 1.0\n        return lcw",
    "docstring": "Centre weighting matrix for TV Laplacian."
  },
  {
    "code": "def new_filename(data, file_kind, ext):\n    nb_key = file_kind + \"number\"\n    if nb_key not in data.keys():\n        data[nb_key] = -1\n    if not data[\"override externals\"]:\n        file_exists = True\n        while file_exists:\n            data[nb_key] = data[nb_key] + 1\n            filename, name = _gen_filename(data, nb_key, ext)\n            file_exists = os.path.isfile(filename)\n    else:\n        data[nb_key] = data[nb_key] + 1\n        filename, name = _gen_filename(data, nb_key, ext)\n    if data[\"rel data path\"]:\n        rel_filepath = posixpath.join(data[\"rel data path\"], name)\n    else:\n        rel_filepath = name\n    return filename, rel_filepath",
    "docstring": "Returns an available filename.\n\n    :param file_kind: Name under which numbering is recorded, such as 'img' or\n                      'table'.\n    :type file_kind: str\n\n    :param ext: Filename extension.\n    :type ext: str\n\n    :returns: (filename, rel_filepath) where filename is a path in the\n              filesystem and rel_filepath is the path to be used in the tex\n              code."
  },
  {
    "code": "def get_fallback_languages():\n    lang = translation.get_language()\n    fallback_list = settings.FALLBACK_LANGUAGES.get(lang, None)\n    if fallback_list:\n        return fallback_list\n    return settings.FALLBACK_LANGUAGES.get(lang[:2], [])",
    "docstring": "Retrieve the fallback languages from the settings.py"
  },
  {
    "code": "def error(self, argparser, target, message):\n        warnings.warn(\n            'Runtime.error is deprecated and will be removed by calmjs-4.0.0',\n            DeprecationWarning)\n        details = self.get_argparser_details(argparser)\n        argparser = details.subparsers[target] if details else self.argparser\n        argparser.error(message)",
    "docstring": "This was used as part of the original non-recursive lookup for\n        the target parser."
  },
  {
    "code": "def has_changed(self, field_name: str = None) -> bool:\n        changed = self._diff_with_initial.keys()\n        if self._meta.get_field(field_name).get_internal_type() == 'ForeignKey':\n            if not field_name.endswith('_id'):\n                field_name = field_name+'_id'\n        if field_name in changed:\n            return True\n        return False",
    "docstring": "Check if a field has changed since the model was instantiated."
  },
  {
    "code": "def spec(self, name):\n        if isinstance(name, (BaseData, Parameter)):\n            name = name.name\n        if name in self._param_specs:\n            return self._param_specs[name]\n        else:\n            return self.bound_spec(name)",
    "docstring": "Returns either the input corresponding to a fileset or field\n        field spec or a spec or parameter that has either\n        been passed to the study as an input or can be derived.\n\n        Parameters\n        ----------\n        name : Str | BaseData | Parameter\n            A parameter, fileset or field or name of one"
  },
  {
    "code": "def _normalize_value_ms(cls, value):\n        value = round(value / 1000) * 1000\n        sorted_units = sorted(cls.UNITS_IN_MILLISECONDS.items(),\n                              key=lambda x: x[1], reverse=True)\n        for unit, unit_in_ms in sorted_units:\n            unit_value = value / unit_in_ms\n            if unit_value.is_integer():\n                return int(unit_value), unit\n        return value, MILLISECOND",
    "docstring": "Normalize a value in ms to the largest unit possible without decimal places.\n\n        Note that this ignores fractions of a second and always returns a value _at least_\n        in seconds.\n\n        :return: the normalized value and unit name\n        :rtype: Tuple[Union[int, float], str]"
  },
  {
    "code": "def alerts(self):\n        endpoint = '/'.join((self.endpoint, self.id, 'alerts'))\n        return self.alertFactory.find(\n            endpoint=endpoint,\n            api_key=self.api_key,\n        )",
    "docstring": "Query for alerts attached to this incident."
  },
  {
    "code": "def _format_default(client, value):\n    if isinstance(value, File):\n        return os.path.relpath(\n            str((client.workflow_path / value.path).resolve())\n        )\n    return value",
    "docstring": "Format default values."
  },
  {
    "code": "def fft(a, n=None, axis=-1, norm=None):\n    output = mkl_fft.fft(a, n, axis)\n    if _unitary(norm):\n        output *= 1 / sqrt(output.shape[axis])\n    return output",
    "docstring": "Compute the one-dimensional discrete Fourier Transform.\n\n    This function computes the one-dimensional *n*-point discrete Fourier\n    Transform (DFT) with the efficient Fast Fourier Transform (FFT)\n    algorithm [CT].\n\n    Parameters\n    ----------\n    a : array_like\n        Input array, can be complex.\n    n : int, optional\n        Length of the transformed axis of the output.\n        If `n` is smaller than the length of the input, the input is cropped.\n        If it is larger, the input is padded with zeros.  If `n` is not given,\n        the length of the input along the axis specified by `axis` is used.\n    axis : int, optional\n        Axis over which to compute the FFT.  If not given, the last axis is\n        used.\n    norm : {None, \"ortho\"}, optional\n        .. versionadded:: 1.10.0\n        Normalization mode (see `numpy.fft`). Default is None.\n\n    Returns\n    -------\n    out : complex ndarray\n        The truncated or zero-padded input, transformed along the axis\n        indicated by `axis`, or the last one if `axis` is not specified.\n\n    Raises\n    ------\n    IndexError\n        if `axes` is larger than the last axis of `a`.\n\n    See Also\n    --------\n    numpy.fft : for definition of the DFT and conventions used.\n    ifft : The inverse of `fft`.\n    fft2 : The two-dimensional FFT.\n    fftn : The *n*-dimensional FFT.\n    rfftn : The *n*-dimensional FFT of real input.\n    fftfreq : Frequency bins for given FFT parameters.\n\n    Notes\n    -----\n    FFT (Fast Fourier Transform) refers to a way the discrete Fourier\n    Transform (DFT) can be calculated efficiently, by using symmetries in the\n    calculated terms.  The symmetry is highest when `n` is a power of 2, and\n    the transform is therefore most efficient for these sizes.\n\n    The DFT is defined, with the conventions used in this implementation, in\n    the documentation for the `numpy.fft` module.\n\n    References\n    ----------\n    .. [CT] Cooley, James W., and John W. Tukey, 1965, \"An algorithm for the\n            machine calculation of complex Fourier series,\" *Math. Comput.*\n            19: 297-301.\n\n    Examples\n    --------\n    >>> np.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))\n    array([ -3.44505240e-16 +1.14383329e-17j,\n             8.00000000e+00 -5.71092652e-15j,\n             2.33482938e-16 +1.22460635e-16j,\n             1.64863782e-15 +1.77635684e-15j,\n             9.95839695e-17 +2.33482938e-16j,\n             0.00000000e+00 +1.66837030e-15j,\n             1.14383329e-17 +1.22460635e-16j,\n             -1.64863782e-15 +1.77635684e-15j])\n\n    >>> import matplotlib.pyplot as plt\n    >>> t = np.arange(256)\n    >>> sp = np.fft.fft(np.sin(t))\n    >>> freq = np.fft.fftfreq(t.shape[-1])\n    >>> plt.plot(freq, sp.real, freq, sp.imag)\n    [<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>]\n    >>> plt.show()\n\n    In this example, real input has an FFT which is Hermitian, i.e., symmetric\n    in the real part and anti-symmetric in the imaginary part, as described in\n    the `numpy.fft` documentation."
  },
  {
    "code": "def sign(self, msg, key):\n        h = hmac.HMAC(key, self.algorithm(), default_backend())\n        h.update(msg)\n        return h.finalize()",
    "docstring": "Create a signature over a message as defined in RFC7515 using a\n        symmetric key\n\n        :param msg: The message\n        :param key: The key\n        :return: A signature"
  },
  {
    "code": "def default_start():\n    (config, daemon, pidfile, startup, fork) = parsearg()\n    if config is None:\n        if os.path.isfile('/etc/vlcp.conf'):\n            config = '/etc/vlcp.conf'\n        else:\n            print('/etc/vlcp.conf is not found; start without configurations.')\n    elif not config:\n        config = None\n    main(config, startup, daemon, pidfile, fork)",
    "docstring": "Use `sys.argv` for starting parameters. This is the entry-point of `vlcp-start`"
  },
  {
    "code": "def add_context_menu_items(self, items, replace_items=False):\n        for label, action in items:\n            assert isinstance(label, basestring)\n            assert isinstance(action, basestring)\n        if replace_items:\n            self._context_menu_items = []\n        self._context_menu_items.extend(items)\n        self._listitem.addContextMenuItems(items, replace_items)",
    "docstring": "Adds context menu items. If replace_items is True all\n        previous context menu items will be removed."
  },
  {
    "code": "def _assert_can_do_op(self, value):\n        if not is_scalar(value):\n            msg = \"'value' must be a scalar, passed: {0}\"\n            raise TypeError(msg.format(type(value).__name__))",
    "docstring": "Check value is valid for scalar op."
  },
  {
    "code": "def pwgen(length=None):\n    if length is None:\n        length = random.choice(range(35, 45))\n    alphanumeric_chars = [\n        l for l in (string.ascii_letters + string.digits)\n        if l not in 'l0QD1vAEIOUaeiou']\n    random_generator = random.SystemRandom()\n    random_chars = [\n        random_generator.choice(alphanumeric_chars) for _ in range(length)]\n    return(''.join(random_chars))",
    "docstring": "Generate a random pasword."
  },
  {
    "code": "def _unsubscribe_myself(self):\n        url = UNSUBSCRIBE_ENDPOINT\n        return self._session.query(url, method='GET', raw=True, stream=False)",
    "docstring": "Unsubscribe this base station for all events."
  },
  {
    "code": "def make_frequency_series(vec):\n    if isinstance(vec, FrequencySeries):\n        return vec\n    if isinstance(vec, TimeSeries):\n        N = len(vec)\n        n = N/2+1\n        delta_f = 1.0 / N / vec.delta_t\n        vectilde =  FrequencySeries(zeros(n, dtype=complex_same_precision_as(vec)),\n                                    delta_f=delta_f, copy=False)\n        fft(vec, vectilde)\n        return vectilde\n    else:\n        raise TypeError(\"Can only convert a TimeSeries to a FrequencySeries\")",
    "docstring": "Return a frequency series of the input vector.\n\n    If the input is a frequency series it is returned, else if the input\n    vector is a real time series it is fourier transformed and returned as a\n    frequency series.\n\n    Parameters\n    ----------\n    vector : TimeSeries or FrequencySeries\n\n    Returns\n    -------\n    Frequency Series: FrequencySeries\n        A frequency domain version of the input vector."
  },
  {
    "code": "def create_args(line, namespace):\n    args = []\n    for arg in shlex.split(line):\n      if not arg:\n         continue\n      if arg[0] == '$':\n        var_name = arg[1:]\n        if var_name in namespace:\n          args.append((namespace[var_name]))\n        else:\n          raise Exception('Undefined variable referenced in command line: %s' % arg)\n      else:\n        args.append(arg)\n    return args",
    "docstring": "Expand any meta-variable references in the argument list."
  },
  {
    "code": "def open(self, filename, mode='r', **kwargs):\n        if 'r' in mode and not self.backend.exists(filename):\n            raise FileNotFound(filename)\n        return self.backend.open(filename, mode, **kwargs)",
    "docstring": "Open the file and return a file-like object.\n\n        :param str filename: The storage root-relative filename\n        :param str mode: The open mode (``(r|w)b?``)\n        :raises FileNotFound: If trying to read a file that does not exists"
  },
  {
    "code": "def _get_queue_for_the_action(self, action):\n        mod = getattr(action, 'module_type', 'fork')\n        queues = list(self.q_by_mod[mod].items())\n        if not queues:\n            return (0, None)\n        self.rr_qid = (self.rr_qid + 1) % len(queues)\n        (worker_id, queue) = queues[self.rr_qid]\n        return (worker_id, queue)",
    "docstring": "Find action queue for the action depending on the module.\n        The id is found with action modulo on action id\n\n        :param a: the action that need action queue to be assigned\n        :type action: object\n        :return: worker id and queue. (0, None) if no queue for the module_type\n        :rtype: tuple"
  },
  {
    "code": "def search_associations_go(\n        subject_category=None,\n        object_category=None,\n        relation=None,\n        subject=None,\n        **kwargs):\n    go_golr_url = \"http://golr.geneontology.org/solr/\"\n    go_solr = pysolr.Solr(go_golr_url, timeout=5)\n    go_solr.get_session().headers['User-Agent'] = get_user_agent(caller_name=__name__)\n    return search_associations(subject_category,\n                               object_category,\n                               relation,\n                               subject,\n                               solr=go_solr,\n                               field_mapping=goassoc_fieldmap(),\n                               **kwargs)",
    "docstring": "Perform association search using Monarch golr"
  },
  {
    "code": "def print_token(self, token_node_index):\n        err_msg = \"The given node is not a token node.\"\n        assert isinstance(self.nodes[token_node_index], TokenNode), err_msg\n        onset = self.nodes[token_node_index].onset\n        offset = self.nodes[token_node_index].offset\n        return self.text[onset:offset]",
    "docstring": "returns the string representation of a token."
  },
  {
    "code": "def regexer_for_targets(targets):\n    for target in targets:\n        path, file_ext = os.path.splitext(target)\n        regexer = config.regexers[file_ext]\n        yield target, regexer",
    "docstring": "Pairs up target files with their correct regex"
  },
  {
    "code": "def write(self,\n              equities=None,\n              futures=None,\n              exchanges=None,\n              root_symbols=None,\n              equity_supplementary_mappings=None,\n              chunk_size=DEFAULT_CHUNK_SIZE):\n        if exchanges is None:\n            exchange_names = [\n                df['exchange']\n                for df in (equities, futures, root_symbols)\n                if df is not None\n            ]\n            if exchange_names:\n                exchanges = pd.DataFrame({\n                    'exchange': pd.concat(exchange_names).unique(),\n                })\n        data = self._load_data(\n            equities if equities is not None else pd.DataFrame(),\n            futures if futures is not None else pd.DataFrame(),\n            exchanges if exchanges is not None else pd.DataFrame(),\n            root_symbols if root_symbols is not None else pd.DataFrame(),\n            (\n                equity_supplementary_mappings\n                if equity_supplementary_mappings is not None\n                else pd.DataFrame()\n            ),\n        )\n        self._real_write(\n            equities=data.equities,\n            equity_symbol_mappings=data.equities_mappings,\n            equity_supplementary_mappings=data.equity_supplementary_mappings,\n            futures=data.futures,\n            root_symbols=data.root_symbols,\n            exchanges=data.exchanges,\n            chunk_size=chunk_size,\n        )",
    "docstring": "Write asset metadata to a sqlite database.\n\n        Parameters\n        ----------\n        equities : pd.DataFrame, optional\n            The equity metadata. The columns for this dataframe are:\n\n              symbol : str\n                  The ticker symbol for this equity.\n              asset_name : str\n                  The full name for this asset.\n              start_date : datetime\n                  The date when this asset was created.\n              end_date : datetime, optional\n                  The last date we have trade data for this asset.\n              first_traded : datetime, optional\n                  The first date we have trade data for this asset.\n              auto_close_date : datetime, optional\n                  The date on which to close any positions in this asset.\n              exchange : str\n                  The exchange where this asset is traded.\n\n            The index of this dataframe should contain the sids.\n        futures : pd.DataFrame, optional\n            The future contract metadata. The columns for this dataframe are:\n\n              symbol : str\n                  The ticker symbol for this futures contract.\n              root_symbol : str\n                  The root symbol, or the symbol with the expiration stripped\n                  out.\n              asset_name : str\n                  The full name for this asset.\n              start_date : datetime, optional\n                  The date when this asset was created.\n              end_date : datetime, optional\n                  The last date we have trade data for this asset.\n              first_traded : datetime, optional\n                  The first date we have trade data for this asset.\n              exchange : str\n                  The exchange where this asset is traded.\n              notice_date : datetime\n                  The date when the owner of the contract may be forced\n                  to take physical delivery of the contract's asset.\n              expiration_date : datetime\n                  The date when the contract expires.\n              auto_close_date : datetime\n                  The date when the broker will automatically close any\n                  positions in this contract.\n              tick_size : float\n                  The minimum price movement of the contract.\n              multiplier: float\n                  The amount of the underlying asset represented by this\n                  contract.\n        exchanges : pd.DataFrame, optional\n            The exchanges where assets can be traded. The columns of this\n            dataframe are:\n\n              exchange : str\n                  The full name of the exchange.\n              canonical_name : str\n                  The canonical name of the exchange.\n              country_code : str\n                  The ISO 3166 alpha-2 country code of the exchange.\n        root_symbols : pd.DataFrame, optional\n            The root symbols for the futures contracts. The columns for this\n            dataframe are:\n\n              root_symbol : str\n                  The root symbol name.\n              root_symbol_id : int\n                  The unique id for this root symbol.\n              sector : string, optional\n                  The sector of this root symbol.\n              description : string, optional\n                  A short description of this root symbol.\n              exchange : str\n                  The exchange where this root symbol is traded.\n        equity_supplementary_mappings : pd.DataFrame, optional\n            Additional mappings from values of abitrary type to assets.\n        chunk_size : int, optional\n            The amount of rows to write to the SQLite table at once.\n            This defaults to the default number of bind params in sqlite.\n            If you have compiled sqlite3 with more bind or less params you may\n            want to pass that value here.\n\n        See Also\n        --------\n        zipline.assets.asset_finder"
  },
  {
    "code": "def namedb_is_name_zonefile_hash(cur, name, zonefile_hash):\n    select_query = 'SELECT COUNT(value_hash) FROM history WHERE history_id = ? AND value_hash = ?'\n    select_args = (name,zonefile_hash)\n    rows = namedb_query_execute(cur, select_query, select_args)\n    count = None\n    for r in rows:\n        count = r['COUNT(value_hash)']\n        break\n    return count > 0",
    "docstring": "Determine if a zone file hash was sent by a name.\n    Return True if so, false if not"
  },
  {
    "code": "def decode_mysql_literal(text):\n    if MYSQL_NULL_PATTERN.match(text):\n        return None\n    if MYSQL_BOOLEAN_PATTERN.match(text):\n        return text.lower() == \"true\"\n    if MYSQL_FLOAT_PATTERN.match(text):\n        return float(text)\n    if MYSQL_INT_PATTERN.match(text):\n        return int(text)\n    if MYSQL_STRING_PATTERN.match(text):\n        return decode_mysql_string_literal(text)\n    raise ValueError(\"Unable to decode given value: %r\" % (text,))",
    "docstring": "Attempts to decode given MySQL literal into Python value.\n\n    :param text: Value to be decoded, as MySQL literal.\n    :type text: str\n\n    :return: Python version of the given MySQL literal.\n    :rtype: any"
  },
  {
    "code": "def importPreflibFile(self, fileName):\n        elecFileObj = open(fileName, 'r')\n        self.candMap, rankMaps, wmgMapsCounts, self.numVoters = prefpy_io.read_election_file(elecFileObj)\n        elecFileObj.close()\n        self.numCands = len(self.candMap.keys())\n        self.preferences = []\n        for i in range(0, len(rankMaps)):\n            wmgMap = self.genWmgMapFromRankMap(rankMaps[i])\n            self.preferences.append(Preference(wmgMap, wmgMapsCounts[i]))",
    "docstring": "Imports a preflib format file that contains all the information of a Profile. This function\n        will completely override all members of the current Profile object. Currently, we assume \n        that in an election where incomplete ordering are allowed, if a voter ranks only one \n        candidate, then the voter did not prefer any candidates over another. This may lead to some\n        discrepancies when importing and exporting a .toi preflib file or a .soi preflib file.\n\n        :ivar str fileName: The name of the input file to be imported."
  },
  {
    "code": "def get_locale_choices(locale_dir):\n        file_name_s = os.listdir(locale_dir)\n        choice_s = []\n        for file_name in file_name_s:\n            if file_name.endswith(I18n.TT_FILE_EXT_STXT):\n                file_name_noext, _ = os.path.splitext(file_name)\n                if file_name_noext:\n                    choice_s.append(file_name_noext)\n        choice_s = sorted(choice_s)\n        return choice_s",
    "docstring": "Get a list of locale file names in the given locale dir."
  },
  {
    "code": "def __prepare_info_from_dicomdir_file(self, writedicomdirfile=True):\n        createdcmdir = True\n        dicomdirfile = os.path.join(self.dirpath, self.dicomdir_filename)\n        ftype = 'pickle'\n        if os.path.exists(dicomdirfile):\n            try:\n                dcmdirplus = misc.obj_from_file(dicomdirfile, ftype)\n                if dcmdirplus['version'] == __version__:\n                    createdcmdir = False\n                dcmdir = dcmdirplus['filesinfo']\n            except Exception:\n                logger.debug('Found dicomdir.pkl with wrong version')\n                createdcmdir = True\n        if createdcmdir or self.force_create_dicomdir:\n            dcmdirplus = self._create_dicomdir_info()\n            dcmdir = dcmdirplus['filesinfo']\n            if (writedicomdirfile) and len(dcmdir) > 0:\n                try:\n                    misc.obj_to_file(dcmdirplus, dicomdirfile, ftype)\n                except:\n                    logger.warning('Cannot write dcmdir file')\n                    traceback.print_exc()\n        dcmdir = dcmdirplus['filesinfo']\n        self.dcmdirplus = dcmdirplus\n        self.files_with_info = dcmdir\n        return dcmdir",
    "docstring": "Check if exists dicomdir file and load it or cerate it\n\n        dcmdir = get_dir(dirpath)\n\n        dcmdir: list with filenames, SeriesNumber and SliceLocation"
  },
  {
    "code": "def tilt_residual(params, data, mask):\n    bg = tilt_model(params, shape=data.shape)\n    res = (data - bg)[mask]\n    return res.flatten()",
    "docstring": "lmfit tilt residuals"
  },
  {
    "code": "def _try_to_compute_deterministic_class_id(cls, depth=5):\n    class_id = pickle.dumps(cls)\n    for _ in range(depth):\n        new_class_id = pickle.dumps(pickle.loads(class_id))\n        if new_class_id == class_id:\n            return hashlib.sha1(new_class_id).digest()\n        class_id = new_class_id\n    logger.warning(\n        \"WARNING: Could not produce a deterministic class ID for class \"\n        \"{}\".format(cls))\n    return hashlib.sha1(new_class_id).digest()",
    "docstring": "Attempt to produce a deterministic class ID for a given class.\n\n    The goal here is for the class ID to be the same when this is run on\n    different worker processes. Pickling, loading, and pickling again seems to\n    produce more consistent results than simply pickling. This is a bit crazy\n    and could cause problems, in which case we should revert it and figure out\n    something better.\n\n    Args:\n        cls: The class to produce an ID for.\n        depth: The number of times to repeatedly try to load and dump the\n            string while trying to reach a fixed point.\n\n    Returns:\n        A class ID for this class. We attempt to make the class ID the same\n            when this function is run on different workers, but that is not\n            guaranteed.\n\n    Raises:\n        Exception: This could raise an exception if cloudpickle raises an\n            exception."
  },
  {
    "code": "def _get_float(data, position, dummy0, dummy1, dummy2):\n    end = position + 8\n    return _UNPACK_FLOAT(data[position:end])[0], end",
    "docstring": "Decode a BSON double to python float."
  },
  {
    "code": "def apply_boundary_conditions(self, **kwargs):\n        polarval = kwargs[self._polar_angle]\n        azval = kwargs[self._azimuthal_angle]\n        polarval = self._polardist._domain.apply_conditions(polarval)\n        azval = self._azimuthaldist._domain.apply_conditions(azval)\n        polarval = self._bounds[self._polar_angle].apply_conditions(polarval)\n        azval = self._bounds[self._azimuthal_angle].apply_conditions(azval)\n        return {self._polar_angle: polarval, self._azimuthal_angle: azval}",
    "docstring": "Maps the given values to be within the domain of the azimuthal and\n        polar angles, before applying any other boundary conditions.\n\n        Parameters\n        ----------\n        \\**kwargs :\n            The keyword args must include values for both the azimuthal and\n            polar angle, using the names they were initilialized with. For\n            example, if `polar_angle='theta'` and `azimuthal_angle=`phi`, then\n            the keyword args must be `theta={val1}, phi={val2}`.\n\n        Returns\n        -------\n        dict\n            A dictionary of the parameter names and the conditioned values."
  },
  {
    "code": "def by_median_home_value(self,\n                             lower=-1,\n                             upper=2 ** 31,\n                             zipcode_type=ZipcodeType.Standard,\n                             sort_by=SimpleZipcode.median_home_value.name,\n                             ascending=False,\n                             returns=DEFAULT_LIMIT):\n        return self.query(\n            median_home_value_lower=lower,\n            median_home_value_upper=upper,\n            sort_by=sort_by, zipcode_type=zipcode_type,\n            ascending=ascending, returns=returns,\n        )",
    "docstring": "Search zipcode information by median home value."
  },
  {
    "code": "def pivot_wavelength(self):\n        wl = self.registry._pivot_wavelengths.get((self.telescope, self.band))\n        if wl is not None:\n            return wl\n        wl = self.calc_pivot_wavelength()\n        self.registry.register_pivot_wavelength(self.telescope, self.band, wl)\n        return wl",
    "docstring": "Get the bandpass' pivot wavelength.\n\n        Unlike calc_pivot_wavelength(), this function will use a cached\n        value if available."
  },
  {
    "code": "def get_last(self):\n        query = self.table().where('batch', self.get_last_batch_number())\n        return query.order_by('migration', 'desc').get()",
    "docstring": "Get the last migration batch.\n\n        :rtype: list"
  },
  {
    "code": "def add(self, document_data, document_id=None):\n        if document_id is None:\n            parent_path, expected_prefix = self._parent_info()\n            document_pb = document_pb2.Document()\n            created_document_pb = self._client._firestore_api.create_document(\n                parent_path,\n                collection_id=self.id,\n                document_id=None,\n                document=document_pb,\n                mask=None,\n                metadata=self._client._rpc_metadata,\n            )\n            new_document_id = _helpers.get_doc_id(created_document_pb, expected_prefix)\n            document_ref = self.document(new_document_id)\n            set_result = document_ref.set(document_data)\n            return set_result.update_time, document_ref\n        else:\n            document_ref = self.document(document_id)\n            write_result = document_ref.create(document_data)\n            return write_result.update_time, document_ref",
    "docstring": "Create a document in the Firestore database with the provided data.\n\n        Args:\n            document_data (dict): Property names and values to use for\n                creating the document.\n            document_id (Optional[str]): The document identifier within the\n                current collection. If not provided, an ID will be\n                automatically assigned by the server (the assigned ID will be\n                a random 20 character string composed of digits,\n                uppercase and lowercase letters).\n\n        Returns:\n            Tuple[google.protobuf.timestamp_pb2.Timestamp, \\\n                ~.firestore_v1beta1.document.DocumentReference]: Pair of\n\n            * The ``update_time`` when the document was created (or\n              overwritten).\n            * A document reference for the created document.\n\n        Raises:\n            ~google.cloud.exceptions.Conflict: If ``document_id`` is provided\n                and the document already exists."
  },
  {
    "code": "def query_by_student(self, student_id, end_time=None, start_time=None):\r\n        path = {}\r\n        data = {}\r\n        params = {}\r\n        path[\"student_id\"] = student_id\r\n        if start_time is not None:\r\n            params[\"start_time\"] = start_time\r\n        if end_time is not None:\r\n            params[\"end_time\"] = end_time\r\n        self.logger.debug(\"GET /api/v1/audit/grade_change/students/{student_id} with query params: {params} and form data: {data}\".format(params=params, data=data, **path))\r\n        return self.generic_request(\"GET\", \"/api/v1/audit/grade_change/students/{student_id}\".format(**path), data=data, params=params, all_pages=True)",
    "docstring": "Query by student.\r\n\r\n        List grade change events for a given student."
  },
  {
    "code": "def retrieve_customer(self, handle, with_additional_data=False):\n        response = self.request(E.retrieveCustomerRequest(\n            E.handle(handle),\n            E.withAdditionalData(int(with_additional_data)),\n        ))\n        return response.as_model(Customer)",
    "docstring": "Retrieve information of an existing customer."
  },
  {
    "code": "def clear_list_value(self, value):\n        if not value:\n            return self.empty_value\n        if self.clean_empty:\n            value = [v for v in value if v]\n        return value or self.empty_value",
    "docstring": "Clean the argument value to eliminate None or Falsy values if needed."
  },
  {
    "code": "def _wire_events(self):\n        self._device.on_open += self._on_open\n        self._device.on_close += self._on_close\n        self._device.on_read += self._on_read\n        self._device.on_write += self._on_write\n        self._zonetracker.on_fault += self._on_zone_fault\n        self._zonetracker.on_restore += self._on_zone_restore",
    "docstring": "Wires up the internal device events."
  },
  {
    "code": "def reward_bonus(self, assignment_id, amount, reason):\n        try:\n            return self.mturkservice.grant_bonus(assignment_id, amount, reason)\n        except MTurkServiceException as ex:\n            logger.exception(str(ex))",
    "docstring": "Reward the Turker for a specified assignment with a bonus."
  },
  {
    "code": "def inspect_select_calculation(self):\n        try:\n            node = self.ctx.cif_select\n            self.ctx.cif = node.outputs.cif\n        except exceptions.NotExistent:\n            self.report('aborting: CifSelectCalculation<{}> did not return the required cif output'.format(node.uuid))\n            return self.exit_codes.ERROR_CIF_SELECT_FAILED",
    "docstring": "Inspect the result of the CifSelectCalculation, verifying that it produced a CifData output node."
  },
  {
    "code": "def from_chords(self, chords, duration=1):\n        tun = self.get_tuning()\n        def add_chord(chord, duration):\n            if type(chord) == list:\n                for c in chord:\n                    add_chord(c, duration * 2)\n            else:\n                chord = NoteContainer().from_chord(chord)\n                if tun:\n                    chord = tun.find_chord_fingering(chord,\n                            return_best_as_NoteContainer=True)\n                if not self.add_notes(chord, duration):\n                    dur = self.bars[-1].value_left()\n                    self.add_notes(chord, dur)\n                    self.add_notes(chord, value.subtract(duration, dur))\n        for c in chords:\n            if c is not None:\n                add_chord(c, duration)\n            else:\n                self.add_notes(None, duration)\n        return self",
    "docstring": "Add chords to the Track.\n\n        The given chords should be a list of shorthand strings or list of\n        list of shorthand strings, etc.\n\n        Each sublist divides the value by 2.\n\n        If a tuning is set, chords will be expanded so they have a proper\n        fingering.\n\n        Example:\n        >>> t = Track().from_chords(['C', ['Am', 'Dm'], 'G7', 'C#'], 1)"
  },
  {
    "code": "def extract_coverage(self, container: Container) -> FileLineSet:\n        uid = container.uid\n        r = self.__api.post('containers/{}/read-coverage'.format(uid))\n        if r.status_code == 200:\n            return FileLineSet.from_dict(r.json())\n        self.__api.handle_erroneous_response(r)",
    "docstring": "Extracts a report of the lines that have been executed since the last\n        time that a coverage report was extracted."
  },
  {
    "code": "def size_r_img_inches(width, height):\n    aspect_ratio = height / (1.0 * width)\n    return R_IMAGE_SIZE, round(aspect_ratio * R_IMAGE_SIZE, 2)",
    "docstring": "Compute the width and height for an R image for display in IPython\n\n    Neight width nor height can be null but should be integer pixel values > 0.\n\n    Returns a tuple of (width, height) that should be used by ggsave in R to\n    produce an appropriately sized jpeg/png/pdf image with the right aspect\n    ratio.  The returned values are in inches."
  },
  {
    "code": "def package_releases(self, project_name):\n        try:\n            return self._connection.package_releases(project_name)\n        except Exception as err:\n            raise PyPIClientError(err)",
    "docstring": "Retrieve the versions from PyPI by ``project_name``.\n\n        Args:\n            project_name (str): The name of the project we wish to retrieve\n                the versions of.\n\n        Returns:\n            list: Of string versions."
  },
  {
    "code": "def get_remote_port_id_local(self, tlv_data):\n        ret, parsed_val = self._check_common_tlv_format(\n            tlv_data, \"Local:\", \"Port ID TLV\")\n        if not ret:\n            return None\n        local = parsed_val[1].split('\\n')\n        return local[0].strip()",
    "docstring": "Returns Remote Port ID Local from the TLV."
  },
  {
    "code": "def _generate_badges(self):\n        daycount = self._stats.downloads_per_day\n        day = self._generate_badge('Downloads', '%d/day' % daycount)\n        self._badges['per-day'] = day\n        weekcount = self._stats.downloads_per_week\n        if weekcount is None:\n            return\n        week = self._generate_badge('Downloads', '%d/week' % weekcount)\n        self._badges['per-week'] = week\n        monthcount = self._stats.downloads_per_month\n        if monthcount is None:\n            return\n        month = self._generate_badge('Downloads', '%d/month' % monthcount)\n        self._badges['per-month'] = month",
    "docstring": "Generate download badges. Append them to ``self._badges``."
  },
  {
    "code": "def _init_add_goid_alt(self):\n        goid_alts = set()\n        go2cnt_add = {}\n        aspect_counts = self.aspect_counts\n        gocnts = self.gocnts\n        go2obj = self.go2obj\n        for go_id, cnt in gocnts.items():\n            goobj = go2obj[go_id]\n            assert cnt, \"NO TERM COUNTS FOR {GO}\".format(GO=goobj.item_id)\n            if go_id != goobj.item_id:\n                go2cnt_add[goobj.item_id] = cnt\n            goid_alts |= goobj.alt_ids\n            aspect_counts[goobj.namespace] += cnt\n        for goid, cnt in go2cnt_add.items():\n            gocnts[goid] = cnt\n        for alt_goid in goid_alts.difference(gocnts):\n            goobj = go2obj[alt_goid]\n            cnt = gocnts[goobj.item_id]\n            assert cnt, \"NO TERM COUNTS FOR ALT_ID({GOa}) ID({GO}): {NAME}\".format(\n                GOa=alt_goid, GO=goobj.item_id, NAME=goobj.name)\n            gocnts[alt_goid] = cnt",
    "docstring": "Add alternate GO IDs to term counts."
  },
  {
    "code": "def on_resolve(target, func, *args, **kwargs):\n    return _register_hook(ON_RESOLVE, target, func, *args, **kwargs)",
    "docstring": "Register a resolution hook."
  },
  {
    "code": "def toggleDrawingSensitive(self, drawing=True):\n        self.actions.editMode.setEnabled(not drawing)\n        if not drawing and self.beginner():\n            print('Cancel creation.')\n            self.canvas.setEditing(True)\n            self.canvas.restoreCursor()\n            self.actions.create.setEnabled(True)",
    "docstring": "In the middle of drawing, toggling between modes should be disabled."
  },
  {
    "code": "def angle2vecs(vec1, vec2):\n    dot = np.dot(vec1, vec2)\n    vec1_modulus = np.sqrt(np.multiply(vec1, vec1).sum())\n    vec2_modulus = np.sqrt(np.multiply(vec2, vec2).sum())\n    if (vec1_modulus * vec2_modulus) == 0:\n        cos_angle = 1\n    else: cos_angle = dot / (vec1_modulus * vec2_modulus)\n    return math.degrees(acos(cos_angle))",
    "docstring": "angle between two vectors"
  },
  {
    "code": "def _update_prx(self):\n        qx = scipy.ones(N_CODON, dtype='float')\n        for j in range(3):\n            for w in range(N_NT):\n                qx[CODON_NT[j][w]] *= self.phi[w]\n        frx = self.pi_codon**self.beta\n        self.prx = frx * qx\n        with scipy.errstate(divide='raise', under='raise', over='raise',\n                invalid='raise'):\n            for r in range(self.nsites):\n                self.prx[r] /= self.prx[r].sum()",
    "docstring": "Update `prx` from `phi`, `pi_codon`, and `beta`."
  },
  {
    "code": "def fmt_transition(t):\n    return \"Transition({} {} {})\".format(\n        fmt_mechanism(t.cause_indices, t.node_labels),\n        ARROW_RIGHT,\n        fmt_mechanism(t.effect_indices, t.node_labels))",
    "docstring": "Format a |Transition|."
  },
  {
    "code": "def delete(self):\n        response = self._client._request('DELETE', self._client._build_url('service', service_id=self.id))\n        if response.status_code != requests.codes.no_content:\n            raise APIError(\"Could not delete service: {} with id {}\".format(self.name, self.id))",
    "docstring": "Delete this service.\n\n        :raises APIError: if delete was not succesfull."
  },
  {
    "code": "def update(self, **args):\n        data = json.dumps(args)\n        r = requests.put(\n            \"https://kippt.com/api/clips/%s\" % (self.id),\n            headers=self.kippt.header,\n            data=data)\n        return (r.json())",
    "docstring": "Updates a Clip.\n\n        Parameters:\n        - args Dictionary of other fields\n\n        Accepted fields can be found here:\n            https://github.com/kippt/api-documentation/blob/master/objects/clip.md"
  },
  {
    "code": "def _collapse_header(self, header):\n        out = []\n        for i, h in enumerate(header):\n            if h.startswith(self._col_quals):\n                out[-1].append(i)\n            else:\n                out.append([i])\n        return out",
    "docstring": "Combine header columns into related groups."
  },
  {
    "code": "def set(self, code):\n        if self.update:\n            self.vertices_substitution_dict, self.edges_substitution_dict, self.match_info\\\n                = self.match.get_variables_substitution_dictionaries(self.g, self.matching_graph)\n        try:\n            self.matching_graph = self.__apply_code_to_graph(code, self.matching_graph)\n        except:\n            pass\n        try:\n            code = self.__substitute_names_in_code(code)\n            self.g = self.__apply_code_to_graph(code, self.g)\n        except:\n            pass\n        return True",
    "docstring": "Executes the code and apply it to the self.g\n\n        :param code: the LISP code to execute\n        :return: True/False, depending on the result of the LISP code"
  },
  {
    "code": "def delete_session(self, ticket):\n        assert isinstance(self.session_storage_adapter, CASSessionAdapter)\n        logging.debug('[CAS] Deleting session for ticket {}'.format(ticket))\n        self.session_storage_adapter.delete(ticket)",
    "docstring": "Delete a session record associated with a service ticket."
  },
  {
    "code": "def display_arr(screen, arr, video_size, transpose):\n    if transpose:\n        pyg_img = pygame.surfarray.make_surface(arr.swapaxes(0, 1))\n    else:\n        pyg_img = arr\n    pyg_img = pygame.transform.scale(pyg_img, video_size)\n    screen.blit(pyg_img, (0, 0))",
    "docstring": "Display an image to the pygame screen.\n\n    Args:\n        screen (pygame.Surface): the pygame surface to write frames to\n        arr (np.ndarray): numpy array representing a single frame of gameplay\n        video_size (tuple): the size to render the frame as\n        transpose (bool): whether to transpose the frame before displaying\n\n    Returns:\n        None"
  },
  {
    "code": "def _caveat_v1_to_dict(c):\n    serialized = {}\n    if len(c.caveat_id) > 0:\n        serialized['cid'] = c.caveat_id\n    if c.verification_key_id:\n        serialized['vid'] = utils.raw_urlsafe_b64encode(\n            c.verification_key_id).decode('utf-8')\n    if c.location:\n        serialized['cl'] = c.location\n    return serialized",
    "docstring": "Return a caveat as a dictionary for export as the JSON\n    macaroon v1 format."
  },
  {
    "code": "def _sumDiceRolls(self, rollList):\n        if isinstance(rollList, RollList):\n            self.rolls.append(rollList)\n            return rollList.sum()\n        else:\n            return rollList",
    "docstring": "convert from dice roll structure to a single integer result"
  },
  {
    "code": "def _peek(self, *types):\n        tok = self._scanner.token(self._pos, types)\n        return tok[2]",
    "docstring": "Returns the token type for lookahead; if there are any args\n        then the list of args is the set of token types to allow"
  },
  {
    "code": "def remove_from_tor(self, protocol):\n        r = yield protocol.queue_command('DEL_ONION %s' % self.hostname[:-6])\n        if r.strip() != 'OK':\n            raise RuntimeError('Failed to remove hidden service: \"%s\".' % r)",
    "docstring": "Returns a Deferred which fires with None"
  },
  {
    "code": "def remove_autosave_file(self, fileinfo):\n        filename = fileinfo.filename\n        if filename not in self.name_mapping:\n            return\n        autosave_filename = self.name_mapping[filename]\n        try:\n            os.remove(autosave_filename)\n        except EnvironmentError as error:\n            action = (_('Error while removing autosave file {}')\n                      .format(autosave_filename))\n            msgbox = AutosaveErrorDialog(action, error)\n            msgbox.exec_if_enabled()\n        del self.name_mapping[filename]\n        self.stack.sig_option_changed.emit(\n                'autosave_mapping', self.name_mapping)\n        logger.debug('Removing autosave file %s', autosave_filename)",
    "docstring": "Remove autosave file for specified file.\n\n        This function also updates `self.autosave_mapping` and clears the\n        `changed_since_autosave` flag."
  },
  {
    "code": "def show_instance(name, call=None):\n    if call != 'action':\n        raise SaltCloudException(\n            'The show_instance action must be called with -a or --action.'\n        )\n    node_id = get_linode_id_from_name(name)\n    node_data = get_linode(kwargs={'linode_id': node_id})\n    ips = get_ips(node_id)\n    state = int(node_data['STATUS'])\n    ret = {'id': node_data['LINODEID'],\n           'image': node_data['DISTRIBUTIONVENDOR'],\n           'name': node_data['LABEL'],\n           'size': node_data['TOTALRAM'],\n           'state': _get_status_descr_by_id(state),\n           'private_ips': ips['private_ips'],\n           'public_ips': ips['public_ips']}\n    return ret",
    "docstring": "Displays details about a particular Linode VM. Either a name or a linode_id must\n    be provided.\n\n    .. versionadded:: 2015.8.0\n\n    name\n        The name of the VM for which to display details.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt-cloud -a show_instance vm_name\n\n    .. note::\n\n        The ``image`` label only displays information about the VM's distribution vendor,\n        such as \"Debian\" or \"RHEL\" and does not display the actual image name. This is\n        due to a limitation of the Linode API."
  },
  {
    "code": "def is_in_current_deployment(server, extra_prefix=\"\"):\n    return re.match(r\"^%s\" % '-'.join([DEFAULT_PREFIX, extra_prefix]),\n                    server.name) is not None",
    "docstring": "Check if an existing server in the system take part to\n    the current deployment"
  },
  {
    "code": "def object_factory(api, api_version, kind):\n    resource_list = api.resource_list(api_version)\n    resource = next((resource for resource in resource_list[\"resources\"] if resource[\"kind\"] == kind), None)\n    base = NamespacedAPIObject if resource[\"namespaced\"] else APIObject\n    return type(kind, (base,), {\n        \"version\": api_version,\n        \"endpoint\": resource[\"name\"],\n        \"kind\": kind\n    })",
    "docstring": "Dynamically builds a Python class for the given Kubernetes object in an API.\n\n    For example:\n\n        api = pykube.HTTPClient(...)\n        NetworkPolicy = pykube.object_factory(api, \"networking.k8s.io/v1\", \"NetworkPolicy\")\n\n    This enables construction of any Kubernetes object kind without explicit support\n    from pykube.\n\n    Currently, the HTTPClient passed to this function will not be bound to the returned type.\n    It is planned to fix this, but in the mean time pass it as you would normally."
  },
  {
    "code": "def remove_diagonal(S):\n    if not isspmatrix_csr(S):\n        raise TypeError('expected csr_matrix')\n    if S.shape[0] != S.shape[1]:\n        raise ValueError('expected square matrix, shape=%s' % (S.shape,))\n    S = coo_matrix(S)\n    mask = S.row != S.col\n    S.row = S.row[mask]\n    S.col = S.col[mask]\n    S.data = S.data[mask]\n    return S.tocsr()",
    "docstring": "Remove the diagonal of the matrix S.\n\n    Parameters\n    ----------\n    S : csr_matrix\n        Square matrix\n\n    Returns\n    -------\n    S : csr_matrix\n        Strength matrix with the diagonal removed\n\n    Notes\n    -----\n    This is needed by all the splitting routines which operate on matrix graphs\n    with an assumed zero diagonal\n\n\n    Examples\n    --------\n    >>> from pyamg.gallery import poisson\n    >>> from pyamg.util.utils import remove_diagonal\n    >>> A = poisson( (4,), format='csr' )\n    >>> C = remove_diagonal(A)\n    >>> C.todense()\n    matrix([[ 0., -1.,  0.,  0.],\n            [-1.,  0., -1.,  0.],\n            [ 0., -1.,  0., -1.],\n            [ 0.,  0., -1.,  0.]])"
  },
  {
    "code": "def size(self):\n    import tensorflow as tf\n    if self._size is None:\n      self._size = 0\n      options = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.GZIP)\n      for tfexample_file in self.files:\n        self._size += sum(1 for x\n                          in tf.python_io.tf_record_iterator(tfexample_file, options=options))\n    return self._size",
    "docstring": "The number of instances in the data. If the underlying data source changes,\n       it may be outdated."
  },
  {
    "code": "def insert(self, index, item):\n        super(ObservableList, self).insert(index, item)\n        length = len(self)\n        if index >= length:\n            index = length - 1\n        elif index < 0:\n            index += length - 1\n            if index < 0:\n                index = 0\n        self._notify_add_at(index)",
    "docstring": "See list.insert."
  },
  {
    "code": "def expectation(self, operator: Union[PauliTerm, PauliSum]):\n        if not isinstance(operator, PauliSum):\n            operator = PauliSum([operator])\n        return sum(_term_expectation(self.wf, term, n_qubits=self.n_qubits) for term in operator)",
    "docstring": "Compute the expectation of an operator.\n\n        :param operator: The operator\n        :return: The operator's expectation value"
  },
  {
    "code": "def pp(i, base=1024):\n    degree = 0\n    pattern = \"%4d     %s\"\n    while i > base:\n        pattern = \"%7.2f %s\"\n        i = i / float(base)\n        degree += 1\n    scales = ['B', 'KB', 'MB', 'GB', 'TB', 'EB']\n    return pattern % (i, scales[degree])",
    "docstring": "Pretty-print the integer `i` as a human-readable size representation."
  },
  {
    "code": "def _original_images(self, **kwargs):\n        def test(image):\n            if not image.original:\n                return False\n            for filter, value in kwargs.items():\n                if getattr(image, filter) != value:\n                    return False\n            return True\n        if Session.object_session(self.instance) is None:\n            images = []\n            for image, store in self._stored_images:\n                if test(image):\n                    images.append(image)\n            state = instance_state(self.instance)\n            try:\n                added = state.committed_state[self.attr.key].added_items\n            except KeyError:\n                pass\n            else:\n                for image in added:\n                    if test(image):\n                        images.append(image)\n            if self.session:\n                for image in self.session.new:\n                    if test(image):\n                        images.append(image)\n        else:\n            query = self.filter_by(original=True, **kwargs)\n            images = query.all()\n        return images",
    "docstring": "A list of the original images.\n\n        :returns: A list of the original images.\n        :rtype: :class:`typing.Sequence`\\ [:class:`Image`]"
  },
  {
    "code": "def base64_b64decode(instr):\n    decoded = base64.b64decode(salt.utils.stringutils.to_bytes(instr))\n    try:\n        return salt.utils.stringutils.to_unicode(\n            decoded,\n            encoding='utf8' if salt.utils.platform.is_windows() else None\n        )\n    except UnicodeDecodeError:\n        return decoded",
    "docstring": "Decode a base64-encoded string using the \"modern\" Python interface."
  },
  {
    "code": "async def get_analog_map(self):\n        current_time = time.time()\n        if self.query_reply_data.get(\n                PrivateConstants.ANALOG_MAPPING_RESPONSE) is None:\n            await self._send_sysex(PrivateConstants.ANALOG_MAPPING_QUERY)\n            while self.query_reply_data.get(\n                    PrivateConstants.ANALOG_MAPPING_RESPONSE) is None:\n                elapsed_time = time.time()\n                if elapsed_time - current_time > 4:\n                    return None\n                await asyncio.sleep(self.sleep_tune)\n        return self.query_reply_data.get(\n            PrivateConstants.ANALOG_MAPPING_RESPONSE)",
    "docstring": "This method requests a Firmata analog map query and returns the results.\n\n        :returns: An analog map response or None if a timeout occurs"
  },
  {
    "code": "def list_documents(self, limit=None):\n        limit_str = ''\n        if limit:\n            try:\n                limit_str = 'LIMIT {}'.format(int(limit))\n            except (TypeError, ValueError):\n                pass\n        query = ('SELECT identifier FROM identifier_index ' + limit_str)\n        for row in self.backend.library.database.connection.execute(query).fetchall():\n            yield row['identifier']",
    "docstring": "Generates vids of all indexed identifiers.\n\n        Args:\n            limit (int, optional): If not empty, the maximum number of results to return\n\n        Generates:\n            str: vid of the document."
  },
  {
    "code": "def reset(self):\n        \"Initialises all needed variables to default values\"\n        self.metadata = {}\n        self.items = []\n        self.spine = []\n        self.guide = []\n        self.pages = []\n        self.toc = []\n        self.bindings = []\n        self.IDENTIFIER_ID = 'id'\n        self.FOLDER_NAME = 'EPUB'\n        self._id_html = 0\n        self._id_image = 0\n        self._id_static = 0\n        self.title = ''\n        self.language = 'en'\n        self.direction = None\n        self.templates = {\n            'ncx': NCX_XML,\n            'nav': NAV_XML,\n            'chapter': CHAPTER_XML,\n            'cover': COVER_XML\n        }\n        self.add_metadata('OPF', 'generator', '', {\n            'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])\n        })\n        self.set_identifier(str(uuid.uuid4()))\n        self.prefixes = []\n        self.namespaces = {}",
    "docstring": "Initialises all needed variables to default values"
  },
  {
    "code": "def previous(self, day_of_week=None):\n        if day_of_week is None:\n            day_of_week = self.day_of_week\n        if day_of_week < SUNDAY or day_of_week > SATURDAY:\n            raise ValueError(\"Invalid day of week\")\n        dt = self.subtract(days=1)\n        while dt.day_of_week != day_of_week:\n            dt = dt.subtract(days=1)\n        return dt",
    "docstring": "Modify to the previous occurrence of a given day of the week.\n        If no day_of_week is provided, modify to the previous occurrence\n        of the current day of the week.  Use the supplied consts\n        to indicate the desired day_of_week, ex. pendulum.MONDAY.\n\n        :param day_of_week: The previous day of week to reset to.\n        :type day_of_week: int or None\n\n        :rtype: Date"
  },
  {
    "code": "def AddMapping(self, filename, new_mapping):\n    for field in self._REQUIRED_MAPPING_FIELDS:\n      if field not in new_mapping:\n        raise problems.InvalidMapping(field)\n    if filename in self.GetKnownFilenames():\n      raise problems.DuplicateMapping(filename)\n    self._file_mapping[filename] = new_mapping",
    "docstring": "Adds an entry to the list of known filenames.\n\n    Args:\n        filename: The filename whose mapping is being added.\n        new_mapping: A dictionary with the mapping to add. Must contain all\n            fields in _REQUIRED_MAPPING_FIELDS.\n    Raises:\n        DuplicateMapping if the filename already exists in the mapping\n        InvalidMapping if not all required fields are present"
  },
  {
    "code": "def format_file_path(filepath):\n    try:\n        is_windows_network_mount = WINDOWS_NETWORK_MOUNT_PATTERN.match(filepath)\n        filepath = os.path.realpath(os.path.abspath(filepath))\n        filepath = re.sub(BACKSLASH_REPLACE_PATTERN, '/', filepath)\n        is_windows_drive = WINDOWS_DRIVE_PATTERN.match(filepath)\n        if is_windows_drive:\n            filepath = filepath.capitalize()\n        if is_windows_network_mount:\n            filepath = '/' + filepath\n    except:\n        pass\n    return filepath",
    "docstring": "Formats a path as absolute and with the correct platform separator."
  },
  {
    "code": "def _validate_auth(self, path, obj, _):\n        errs = []\n        if obj.type == 'apiKey':\n            if not obj.passAs:\n                errs.append('need \"passAs\" for apiKey')\n            if not obj.keyname:\n                errs.append('need \"keyname\" for apiKey')\n        elif obj.type == 'oauth2':\n            if not obj.grantTypes:\n                errs.append('need \"grantTypes\" for oauth2')\n        return path, obj.__class__.__name__, errs",
    "docstring": "validate that apiKey and oauth2 requirements"
  },
  {
    "code": "def concretize_load_idx(self, idx, strategies=None):\n        if isinstance(idx, int):\n            return [idx]\n        elif not self.state.solver.symbolic(idx):\n            return [self.state.solver.eval(idx)]\n        strategies = self.load_strategies if strategies is None else strategies\n        return self._apply_concretization_strategies(idx, strategies, 'load')",
    "docstring": "Concretizes a load index.\n\n        :param idx:             An expression for the index.\n        :param strategies:      A list of concretization strategies (to override the default).\n        :param min_idx:         Minimum value for a concretized index (inclusive).\n        :param max_idx:         Maximum value for a concretized index (exclusive).\n        :returns:               A list of concrete indexes."
  },
  {
    "code": "def update_ff(self, ff, mol2=False, force_ff_assign=False):\n        aff = False\n        if force_ff_assign:\n            aff = True\n        elif 'assigned_ff' not in self.tags:\n            aff = True\n        elif not self.tags['assigned_ff']:\n            aff = True\n        if aff:\n            self.assign_force_field(ff, mol2=mol2)\n        return",
    "docstring": "Manages assigning the force field parameters.\n\n        The aim of this method is to avoid unnecessary assignment of the\n        force field.\n\n        Parameters\n        ----------\n        ff: BuffForceField\n            The force field to be used for scoring.\n        mol2: bool, optional\n            If true, mol2 style labels will also be used.\n        force_ff_assign: bool, optional\n            If true, the force field will be completely reassigned, ignoring the\n            cached parameters."
  },
  {
    "code": "def Fierz_to_Bern_chrom(C, dd, parameters):\n    e = sqrt(4 * pi * parameters['alpha_e'])\n    gs = sqrt(4 * pi * parameters['alpha_s'])\n    if dd == 'sb' or dd == 'db':\n        mq = parameters['m_b']\n    elif dd == 'ds':\n        mq = parameters['m_s']\n    else:\n        KeyError(\"Not sure what to do with quark mass for flavour {}\".format(dd))\n    return {\n        '7gamma' + dd : gs**2 / e / mq * C['F7gamma' + dd ],\n        '8g' + dd : gs / mq * C['F8g' + dd ],\n        '7pgamma' + dd : gs**2 / e /mq * C['F7pgamma' + dd],\n        '8pg' + dd : gs / mq * C['F8pg' + dd]\n            }",
    "docstring": "From Fierz to chromomagnetic Bern basis for Class V.\n    dd should be of the form 'sb', 'ds' etc."
  },
  {
    "code": "def is_cached(self, link):\n        if link is None:\n            return False\n        elif hasattr(link, 'uri'):\n            return link.uri in self.id_map\n        else:\n            return link in self.id_map",
    "docstring": "Returns whether the current navigator is cached. Intended\n        to be overwritten and customized by subclasses."
  },
  {
    "code": "def reconnect(connection):\n    if isinstance(connection, FflConnection):\n        return type(connection)(connection.ffldir)\n    kw = {'context': connection._context} if connection.port != 80 else {}\n    return connection.__class__(connection.host, port=connection.port, **kw)",
    "docstring": "Open a new datafind connection based on an existing connection\n\n    This is required because of https://git.ligo.org/lscsoft/glue/issues/1\n\n    Parameters\n    ----------\n    connection : :class:`~gwdatafind.http.HTTPConnection` or `FflConnection`\n        a connection object (doesn't need to be open)\n\n    Returns\n    -------\n    newconn : :class:`~gwdatafind.http.HTTPConnection` or `FflConnection`\n        the new open connection to the same `host:port` server"
  },
  {
    "code": "def write_csv_header(mol, csv_writer):\n    line = []\n    line.append('id')\n    line.append('status')\n    queryList = mol.properties.keys()\n    for queryLabel in queryList:\n        line.append(queryLabel)\n    csv_writer.writerow(line)",
    "docstring": "Write the csv header"
  },
  {
    "code": "def HasColumn(self, table_name, column_name):\n    if not self._connection:\n      raise IOError('Not opened.')\n    if not column_name:\n      return False\n    table_name = table_name.lower()\n    column_names = self._column_names_per_table.get(table_name, None)\n    if column_names is None:\n      column_names = []\n      self._cursor.execute(self._HAS_COLUMN_QUERY.format(table_name))\n      for row in self._cursor.fetchall():\n        if not row[1]:\n          continue\n        row_column_name = row[1]\n        if isinstance(row_column_name, bytes):\n          row_column_name = row_column_name.decode('utf-8')\n        column_names.append(row_column_name.lower())\n      self._column_names_per_table[table_name] = column_names\n    column_name = column_name.lower()\n    return column_name in column_names",
    "docstring": "Determines if a specific column exists.\n\n    Args:\n      table_name (str): name of the table.\n      column_name (str): name of the column.\n\n    Returns:\n      bool: True if the column exists.\n\n    Raises:\n      IOError: if the database file is not opened.\n      OSError: if the database file is not opened."
  },
  {
    "code": "def show_syspath(self):\r\n        editor = CollectionsEditor(parent=self)\r\n        editor.setup(sys.path, title=\"sys.path\", readonly=True,\r\n                     width=600, icon=ima.icon('syspath'))\r\n        self.dialog_manager.show(editor)",
    "docstring": "Show sys.path"
  },
  {
    "code": "async def restart_walk(self):\n        if not self._restartwalk:\n            self._restartwalk = True\n            await self.wait_for_send(FlowUpdaterNotification(self, FlowUpdaterNotification.STARTWALK))",
    "docstring": "Force a re-walk"
  },
  {
    "code": "def source(self, source):\n        BaseView.source.fset(self, source)\n        if self.main_pane:\n            self.main_pane.object = self.contents\n            self.label_pane.object = self.label",
    "docstring": "When the source gets updated, update the pane object"
  },
  {
    "code": "def _GetAuthCookie(self, auth_token):\n\t\tcontinue_location = \"http://localhost/\"\n\t\targs = {\"continue\": continue_location, \"auth\": auth_token}\n\t\treq = self._CreateRequest(\"https://%s/_ah/login?%s\" % (self.host, urllib.urlencode(args)))\n\t\ttry:\n\t\t\tresponse = self.opener.open(req)\n\t\texcept urllib2.HTTPError, e:\n\t\t\tresponse = e\n\t\tif (response.code != 302 or\n\t\t\t\tresponse.info()[\"location\"] != continue_location):\n\t\t\traise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp)\n\t\tself.authenticated = True",
    "docstring": "Fetches authentication cookies for an authentication token.\n\n\t\tArgs:\n\t\t\tauth_token: The authentication token returned by ClientLogin.\n\n\t\tRaises:\n\t\t\tHTTPError: If there was an error fetching the authentication cookies."
  },
  {
    "code": "def distribution(self, start=None, end=None, normalized=True, mask=None):\n        start, end, mask = self._check_boundaries(start, end, mask=mask)\n        counter = histogram.Histogram()\n        for start, end, _ in mask.iterperiods(value=True):\n            for t0, t1, value in self.iterperiods(start, end):\n                duration = utils.duration_to_number(\n                    t1 - t0,\n                    units='seconds',\n                )\n                try:\n                    counter[value] += duration\n                except histogram.UnorderableElements as e:\n                    counter = histogram.Histogram.from_dict(\n                        dict(counter), key=hash)\n                    counter[value] += duration\n        if normalized:\n            return counter.normalized()\n        else:\n            return counter",
    "docstring": "Calculate the distribution of values over the given time range from\n        `start` to `end`.\n\n        Args:\n\n            start (orderable, optional): The lower time bound of\n                when to calculate the distribution. By default, the\n                first time point will be used.\n\n            end (orderable, optional): The upper time bound of\n                when to calculate the distribution. By default, the\n                last time point will be used.\n\n            normalized (bool): If True, distribution will sum to\n                one. If False and the time values of the TimeSeries\n                are datetimes, the units will be seconds.\n\n            mask (:obj:`TimeSeries`, optional): A\n                domain on which to calculate the distribution.\n\n        Returns:\n\n            :obj:`Histogram` with the results."
  },
  {
    "code": "def query(self, design, view, use_devmode=False, **kwargs):\n        design = self._mk_devmode(design, use_devmode)\n        itercls = kwargs.pop('itercls', View)\n        return itercls(self, design, view, **kwargs)",
    "docstring": "Query a pre-defined MapReduce view, passing parameters.\n\n        This method executes a view on the cluster. It accepts various\n        parameters for the view and returns an iterable object\n        (specifically, a :class:`~.View`).\n\n        :param string design: The design document\n        :param string view: The view function contained within the design\n            document\n        :param boolean use_devmode: Whether the view name should be\n            transformed into a development-mode view. See documentation\n            on :meth:`~.BucketManager.design_create` for more\n            explanation.\n        :param kwargs: Extra arguments passed to the :class:`~.View`\n            object constructor.\n        :param kwargs: Additional parameters passed to the\n            :class:`~.View` constructor. See that class'\n            documentation for accepted parameters.\n\n        .. seealso::\n\n            :class:`~.View`\n                contains more extensive documentation and examples\n\n            :class:`couchbase.views.params.Query`\n                contains documentation on the available query options\n\n            :class:`~.SpatialQuery`\n                contains documentation on the available query options\n                for Geospatial views.\n\n        .. note::\n\n            To query a spatial view, you must explicitly use the\n            :class:`.SpatialQuery`. Passing key-value view parameters\n            in ``kwargs`` is not supported for spatial views."
  },
  {
    "code": "def get_container_names(self):\n        current_containers = self.containers(all=True)\n        return set(c_name[1:] for c in current_containers for c_name in c['Names'])",
    "docstring": "Fetches names of all present containers from Docker.\n\n        :return: All container names.\n        :rtype: set"
  },
  {
    "code": "def search_index_simple(self,index,key,search_term):\n        request = self.session\n        url = 'http://%s:%s/%s/_search?q=%s:%s' % (self.host,self.port,index,key,search_term)\n        response = request.get(url)\n        return response",
    "docstring": "Search the index using a simple key and search_term\n        @param index Name of the index\n        @param key Search Key\n        @param search_term The term to be searched for"
  },
  {
    "code": "def cls_get_by_name(cls, name):\n    try:\n        val = getattr(cls, name)\n    except AttributeError:\n        for attr in (a for a in dir(cls) if not a.startswith('_')):\n            try:\n                val = getattr(cls, attr)\n            except AttributeError:\n                continue\n            valname = getattr(val, 'name', None)\n            if valname == name:\n                return val\n        else:\n            raise ValueError('No {} with that name: {}'.format(\n                cls.__name__,\n                name,\n            ))\n    else:\n        return val",
    "docstring": "Return a class attribute by searching the attributes `name` attribute."
  },
  {
    "code": "def login_service_description(self):\n        label = 'Login to ' + self.name\n        if (self.auth_type):\n            label = label + ' (' + self.auth_type + ')'\n        desc = {\"@id\": self.login_uri,\n                \"profile\": self.profile_base + self.auth_pattern,\n                \"label\": label}\n        if (self.header):\n            desc['header'] = self.header\n        if (self.description):\n            desc['description'] = self.description\n        return desc",
    "docstring": "Login service description.\n\n        The login service description _MUST_ include the token service\n        description. The authentication pattern is indicated via the\n        profile URI which is built using self.auth_pattern."
  },
  {
    "code": "def compute_nats_and_bits_per_dim(data_dim,\n                                  latent_dim,\n                                  average_reconstruction,\n                                  average_prior):\n  with tf.name_scope(None, default_name=\"compute_nats_per_dim\"):\n    data_dim = tf.cast(data_dim, average_reconstruction.dtype)\n    latent_dim = tf.cast(latent_dim, average_prior.dtype)\n    negative_log_likelihood = data_dim * average_reconstruction\n    negative_log_prior = latent_dim * average_prior\n    negative_elbo = negative_log_likelihood + negative_log_prior\n    nats_per_dim = tf.divide(negative_elbo, data_dim, name=\"nats_per_dim\")\n    bits_per_dim = tf.divide(nats_per_dim, tf.log(2.), name=\"bits_per_dim\")\n    return nats_per_dim, bits_per_dim",
    "docstring": "Computes negative ELBO, which is an upper bound on the negative likelihood.\n\n  Args:\n    data_dim: int-like indicating data dimensionality.\n    latent_dim: int-like indicating latent dimensionality.\n    average_reconstruction: Scalar Tensor indicating the reconstruction cost\n      averaged over all data dimensions and any data batches.\n    average_prior: Scalar Tensor indicating the negative log-prior probability\n      averaged over all latent dimensions and any data batches.\n\n  Returns:\n    Tuple of scalar Tensors, representing the nats and bits per data dimension\n    (e.g., subpixels) respectively."
  },
  {
    "code": "def sendContact(self, context={}):\n    for recipient in self.recipients:\n      super(ContactFormMail, self).__init__(recipient, self.async)\n      self.sendEmail('contactForm', 'New contact form message', context)",
    "docstring": "Send contact form message to single or multiple recipients"
  },
  {
    "code": "def _build_matches(matches, uuids, no_filtered, fastmode=False):\n    result = []\n    for m in matches:\n        mk = m[0].uuid if not fastmode else m[0]\n        subset = [uuids[mk]]\n        for id_ in m[1:]:\n            uk = id_.uuid if not fastmode else id_\n            u = uuids[uk]\n            if u not in subset:\n                subset.append(u)\n        result.append(subset)\n    result += no_filtered\n    result.sort(key=len, reverse=True)\n    sresult = []\n    for r in result:\n        r.sort(key=lambda id_: id_.uuid)\n        sresult.append(r)\n    return sresult",
    "docstring": "Build a list with matching subsets"
  },
  {
    "code": "def has_adjacent_leaves_only(self):\n        leaves = self.leaves()\n        for i in range(len(leaves) - 1):\n            current_interval = leaves[i].interval\n            next_interval = leaves[i + 1].interval\n            if not current_interval.is_adjacent_before(next_interval):\n                return False\n        return True",
    "docstring": "Return ``True`` if the sync map fragments\n        which are the leaves of the sync map tree\n        are all adjacent.\n\n        :rtype: bool\n\n        .. versionadded:: 1.7.0"
  },
  {
    "code": "def   define_zip_index_for_species(names_ppn_world,\n                                   number_names_ppn_world):\n    global cl\n    cl={}\n    for a,b in zip(names_ppn_world,number_names_ppn_world):\n        cl[a] = b",
    "docstring": "This just give back cl, that is the original index as it is read from files from a data file."
  },
  {
    "code": "def send_msg_multi(name,\n                   profile,\n                   recipients=None,\n                   rooms=None):\n    ret = {'name': name,\n           'changes': {},\n           'result': None,\n           'comment': ''}\n    if recipients is None and rooms is None:\n        ret['comment'] = \"Recipients and rooms are empty, no need to send\"\n        return ret\n    comment = ''\n    if recipients:\n        comment += ' users {0}'.format(recipients)\n    if rooms:\n        comment += ' rooms {0}'.format(rooms)\n    comment += ', message: {0}'.format(name)\n    if __opts__['test']:\n        ret['comment'] = 'Need to send' + comment\n        return ret\n    __salt__['xmpp.send_msg_multi'](\n        message=name,\n        recipients=recipients,\n        rooms=rooms,\n        profile=profile,\n    )\n    ret['result'] = True\n    ret['comment'] = 'Sent message to' + comment\n    return ret",
    "docstring": "Send a message to an list of recipients or rooms\n\n    .. code-block:: yaml\n\n        server-warning-message:\n          xmpp.send_msg:\n            - name: 'This is a server warning message'\n            - profile: my-xmpp-account\n            - recipients:\n              - admins@xmpp.example.com/salt\n            - rooms:\n              - qa@conference.xmpp.example.com\n\n    name\n        The message to send to the XMPP user"
  },
  {
    "code": "def subgraph(self, nodes):\n        adj_matrix = self.csgraph[np.ix_(nodes, nodes)]\n        weighted = True\n        if self.node_labels is not None:\n            node_labels = self.node_labels[nodes]\n        else:\n            node_labels = None\n        return DiGraph(adj_matrix, weighted=weighted, node_labels=node_labels)",
    "docstring": "Return the subgraph consisting of the given nodes and edges\n        between thses nodes.\n\n        Parameters\n        ----------\n        nodes : array_like(int, ndim=1)\n           Array of node indices.\n\n        Returns\n        -------\n        DiGraph\n            A DiGraph representing the subgraph."
  },
  {
    "code": "def _index_key_for(self, att, value=None):\n        if value is None:\n            value = getattr(self, att)\n            if callable(value):\n                value = value()\n        if value is None:\n            return None\n        if att not in self.lists:\n            return self._get_index_key_for_non_list_attr(att, value)\n        else:\n            return self._tuple_for_index_key_attr_list(att, value)",
    "docstring": "Returns a key based on the attribute and its value.\n\n        The key is used for indexing."
  },
  {
    "code": "def cli(env):\n    mgr = SoftLayer.EventLogManager(env.client)\n    event_log_types = mgr.get_event_log_types()\n    table = formatting.Table(COLUMNS)\n    for event_log_type in event_log_types:\n        table.add_row([event_log_type])\n    env.fout(table)",
    "docstring": "Get Event Log Types"
  },
  {
    "code": "def check_roundoff(self, rtol=0.25, atol=1e-6):\n        psdev = _gvar.sdev(self.p.flat)\n        paltsdev = _gvar.sdev(self.palt.flat)\n        if not numpy.allclose(psdev, paltsdev, rtol=rtol, atol=atol):\n            warnings.warn(\"Possible roundoff errors in fit.p; try svd cut.\")",
    "docstring": "Check for roundoff errors in fit.p.\n\n        Compares standard deviations from fit.p and fit.palt to see if they\n        agree to within relative tolerance ``rtol`` and absolute tolerance\n        ``atol``. Generates a warning if they do not (in which\n        case an SVD cut might be advisable)."
  },
  {
    "code": "def _apply_to_data(data, func, unpack_dict=False):\n    apply_ = partial(_apply_to_data, func=func, unpack_dict=unpack_dict)\n    if isinstance(data, dict):\n        if unpack_dict:\n            return [apply_(v) for v in data.values()]\n        return {k: apply_(v) for k, v in data.items()}\n    if isinstance(data, (list, tuple)):\n        try:\n            return [apply_(x) for x in data]\n        except TypeError:\n            return func(data)\n    return func(data)",
    "docstring": "Apply a function to data, trying to unpack different data\n    types."
  },
  {
    "code": "def publish_server_closed(self, server_address, topology_id):\n        event = ServerClosedEvent(server_address, topology_id)\n        for subscriber in self.__server_listeners:\n            try:\n                subscriber.closed(event)\n            except Exception:\n                _handle_exception()",
    "docstring": "Publish a ServerClosedEvent to all server listeners.\n\n        :Parameters:\n         - `server_address`: The address (host/port pair) of the server.\n         - `topology_id`: A unique identifier for the topology this server\n           is a part of."
  },
  {
    "code": "def fromDictionary(value):\n        if isinstance(value, dict):\n            pp = PortalParameters()\n            for k,v in value.items():\n                setattr(pp, \"_%s\" % k, v)\n            return pp\n        else:\n            raise AttributeError(\"Invalid input.\")",
    "docstring": "creates the portal properties object from a dictionary"
  },
  {
    "code": "def request_uplink_info(self, context, agent):\n        LOG.debug('request_uplink_info from %(agent)s', {'agent': agent})\n        event_type = 'agent.request.uplink'\n        payload = {'agent': agent}\n        timestamp = time.ctime()\n        data = (event_type, payload)\n        pri = self.obj.PRI_LOW_START + 1\n        self.obj.pqueue.put((pri, timestamp, data))\n        LOG.debug('Added request uplink info into queue.')\n        return 0",
    "docstring": "Process uplink message from an agent."
  },
  {
    "code": "def command(cmd):\n    status, out = commands.getstatusoutput(cmd)\n    if status is not 0:\n        logger.error(\"Something went wrong:\")\n        logger.error(out)\n        raise SdistCreationError()\n    return out",
    "docstring": "Execute command and raise an exception upon an error.\n\n      >>> 'README' in command('ls')\n      True\n      >>> command('nonexistingcommand')  #doctest: +ELLIPSIS\n      Traceback (most recent call last):\n      ...\n      SdistCreationError"
  },
  {
    "code": "def future(self,\n               request_iterator,\n               timeout=None,\n               metadata=None,\n               credentials=None):\n        return _utils.wrap_future_call(\n                    self._inner.future(\n                        _utils.WrappedAsyncIterator(request_iterator, self._loop),\n                        timeout,\n                        metadata,\n                        credentials\n                    ),\n                    self._loop,\n                    self._executor)",
    "docstring": "Asynchronously invokes the underlying RPC on the client.\n\n    Args:\n      request_iterator: An ASYNC iterator that yields request values for the RPC.\n      timeout: An optional duration of time in seconds to allow for the RPC.\n               If None, the timeout is considered infinite.\n      metadata: Optional :term:`metadata` to be transmitted to the\n        service-side of the RPC.\n      credentials: An optional CallCredentials for the RPC.\n\n    Returns:\n        An object that is both a Call for the RPC and a Future. In the event of\n        RPC completion, the return Call-Future's result value will be the\n        response message of the RPC. Should the event terminate with non-OK\n        status, the returned Call-Future's exception value will be an RpcError."
  },
  {
    "code": "def unset(ctx, key):\n    file = ctx.obj['FILE']\n    quote = ctx.obj['QUOTE']\n    success, key = unset_key(file, key, quote)\n    if success:\n        click.echo(\"Successfully removed %s\" % key)\n    else:\n        exit(1)",
    "docstring": "Removes the given key."
  },
  {
    "code": "def score_kmer(self, kmer):\n        if len(kmer) != len(self.pwm):\n            raise Exception(\"incorrect k-mer length\")\n        score = 0.0\n        d = {\"A\":0, \"C\":1, \"G\":2, \"T\":3}\n        for nuc, row in zip(kmer.upper(), self.pwm):\n            score += log(row[d[nuc]] / 0.25 + 0.01)\n        return score",
    "docstring": "Calculate the log-odds score for a specific k-mer.\n\n        Parameters\n        ----------\n        kmer : str\n            String representing a kmer. Should be the same length as the motif.\n        \n        Returns\n        -------\n        score : float\n            Log-odd score."
  },
  {
    "code": "def decode_vlqs(s):\n    ints = []\n    i = 0\n    shift = 0\n    for c in s:\n        raw = B64_INT[c]\n        cont = VLQ_CONT & raw\n        i = ((VLQ_BASE_MASK & raw) << shift) | i\n        shift += VLQ_SHIFT\n        if not cont:\n            sign = -1 if 1 & i else 1\n            ints.append((i >> 1) * sign)\n            i = 0\n            shift = 0\n    return tuple(ints)",
    "docstring": "Decode str `s` into a list of integers."
  },
  {
    "code": "def _tweak_lane(lane_details, dname):\n    tweak_config_file = os.path.join(dname, \"lane_config.yaml\")\n    if os.path.exists(tweak_config_file):\n        with open(tweak_config_file) as in_handle:\n            tweak_config = yaml.safe_load(in_handle)\n        if tweak_config.get(\"uniquify_lanes\"):\n            out = []\n            for ld in lane_details:\n                ld[\"name\"] = \"%s-%s\" % (ld[\"name\"], ld[\"lane\"])\n                out.append(ld)\n            return out\n    return lane_details",
    "docstring": "Potentially tweak lane information to handle custom processing, reading a lane_config.yaml file."
  },
  {
    "code": "def _recurse_find_trace(self, structure, item, trace=[]):\n        try:\n            i = structure.index(item)\n        except ValueError:\n            for j,substructure in enumerate(structure):\n                if isinstance(substructure, list):\n                    return self._recurse_find_trace(substructure, item, trace+[j])\n        else:\n            return trace+[i]",
    "docstring": "given a nested structure from _parse_repr and find the trace route to get to item"
  },
  {
    "code": "def _previewFile(self):\n        dataFrame = self._loadCSVDataFrame()\n        dataFrameModel = DataFrameModel(dataFrame, filePath=self._filename)\n        dataFrameModel.enableEditing(True)\n        self._previewTableView.setModel(dataFrameModel)\n        columnModel = dataFrameModel.columnDtypeModel()\n        columnModel.changeFailed.connect(self.updateStatusBar)\n        self._datatypeTableView.setModel(columnModel)",
    "docstring": "Updates the preview widgets with new models for both tab panes."
  },
  {
    "code": "def check_vtech(text):\n    err = \"institution.vtech\"\n    msg = \"Incorrect name. Use '{}' instead of '{}'.\"\n    institution = [\n        [\"Virginia Polytechnic Institute and State University\",\n         [\"Virginia Polytechnic and State University\"]],\n    ]\n    return preferred_forms_check(text, institution, err, msg)",
    "docstring": "Suggest the correct name.\n\n    source: Virginia Tech Division of Student Affairs\n    source_url: http://bit.ly/2en1zbv"
  },
  {
    "code": "def update_collisions(self):\n        if not self.mode['items'] or len(self.mode['items']) == 0: return\n        self.collman.clear()\n        for z, node in self.children:\n            if hasattr(node, 'cshape') and type(node.cshape) == cm.CircleShape:\n                self.collman.add(node)\n        for other in self.collman.iter_colliding(self.player):\n            typeball = other.btype\n            self.logger.debug('collision', typeball)\n            if other.removable:\n                self.to_remove.append(other)\n            self.reward_item(typeball)\n        self.remove_items()",
    "docstring": "Test player for collisions with items"
  },
  {
    "code": "def list_nodes_full(**kwargs):\n    nodes = _query('server/list')\n    ret = {}\n    for node in nodes:\n        name = nodes[node]['label']\n        ret[name] = nodes[node].copy()\n        ret[name]['id'] = node\n        ret[name]['image'] = nodes[node]['os']\n        ret[name]['size'] = nodes[node]['VPSPLANID']\n        ret[name]['state'] = nodes[node]['status']\n        ret[name]['private_ips'] = nodes[node]['internal_ip']\n        ret[name]['public_ips'] = nodes[node]['main_ip']\n    return ret",
    "docstring": "Return all data on nodes"
  },
  {
    "code": "def unfreeze(name, path=None, use_vt=None):\n    _ensure_exists(name, path=path)\n    if state(name, path=path) == 'stopped':\n        raise CommandExecutionError(\n            'Container \\'{0}\\' is stopped'.format(name)\n        )\n    cmd = 'lxc-unfreeze'\n    if path:\n        cmd += ' -P {0}'.format(pipes.quote(path))\n    return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)",
    "docstring": "Unfreeze the named container.\n\n    path\n        path to the container parent directory\n        default: /var/lib/lxc (system)\n\n        .. versionadded:: 2015.8.0\n\n    use_vt\n        run the command through VT\n\n        .. versionadded:: 2015.8.0\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' lxc.unfreeze name"
  },
  {
    "code": "def find_method(self, decl):\n        name = decl.name\n        method = None\n        try:\n            method = getattr(self, u'do_{}'.format(\n                             (name).replace('-', '_')))\n        except AttributeError:\n            if name.startswith('data-'):\n                method = getattr(self, 'do_data_any')\n            elif name.startswith('attr-'):\n                method = getattr(self, 'do_attr_any')\n            else:\n                log(WARN, u'Missing method {}'.format(\n                                 (name).replace('-', '_')).encode('utf-8'))\n        if method:\n            self.record_coverage_line(decl.source_line)\n            return method\n        else:\n            return lambda x, y, z: None",
    "docstring": "Find class method to call for declaration based on name."
  },
  {
    "code": "def aggregated_records(all_records, key_fields=KEY_FIELDS):\n    flow_table = defaultdict(_FlowStats)\n    for flow_record in all_records:\n        key = tuple(getattr(flow_record, attr) for attr in key_fields)\n        if any(x is None for x in key):\n            continue\n        flow_table[key].update(flow_record)\n    for key in flow_table:\n        item = {k: v for k, v in zip(key_fields, key)}\n        item.update(flow_table[key].to_dict())\n        yield item",
    "docstring": "Yield dicts that correspond to aggregates of the flow records given by\n    the sequence of FlowRecords in `all_records`. Skips incomplete records.\n    This will consume the `all_records` iterator, and requires enough memory to\n    be able to read it entirely.\n    `key_fields` optionally contains the fields over which to aggregate. By\n    default it's the typical flow 5-tuple."
  },
  {
    "code": "def clone(self, source_id, backup_id, size,\n              volume_id=None, source_host=None):\n        volume_id = volume_id or str(uuid.uuid4())\n        return self.http_put('/volumes/%s' % volume_id,\n                             params=self.unused({\n                                 'source_host': source_host,\n                                 'source_volume_id': source_id,\n                                 'backup_id': backup_id,\n                                 'size': size\n                             }))",
    "docstring": "create a volume then clone the contents of\n        the backup into the new volume"
  },
  {
    "code": "def set_rule_name(self, rule_name):\n        if not self.aws.get('xray', None):\n            self.aws['xray'] = {}\n        self.aws['xray']['sampling_rule_name'] = rule_name",
    "docstring": "Add the matched centralized sampling rule name\n        if a segment is sampled because of that rule.\n        This method should be only used by the recorder."
  },
  {
    "code": "def i32(self, name, value=None, align=None):\n        self.int(4, name, value, align)",
    "docstring": "Add an 32 byte integer field to template.\n\n        This is an convenience method that simply calls `Int` keyword with predefined length."
  },
  {
    "code": "def limit_mem(limit=(4 * 1024**3)):\n    \"Set soft memory limit\"\n    rsrc = resource.RLIMIT_DATA\n    soft, hard = resource.getrlimit(rsrc)\n    resource.setrlimit(rsrc, (limit, hard))\n    softnew, _ = resource.getrlimit(rsrc)\n    assert softnew == limit\n    _log = logging.getLogger(__name__)\n    _log.debug('Set soft memory limit: %s => %s', soft, softnew)",
    "docstring": "Set soft memory limit"
  },
  {
    "code": "def read_config(ip, mac):\n    click.echo(\"Read configuration from %s\" % ip)\n    request = requests.get(\n        'http://{}/{}/{}/'.format(ip, URI, mac), timeout=TIMEOUT)\n    print(request.json())",
    "docstring": "Read the current configuration of a myStrom device."
  },
  {
    "code": "def prepare_function_symbol(self, symbol_name, basic_addr=None):\n        if basic_addr is None:\n            basic_addr = self.project.loader.extern_object.get_pseudo_addr(symbol_name)\n        return basic_addr, basic_addr",
    "docstring": "Prepare the address space with the data necessary to perform relocations pointing to the given symbol\n\n        Returns a 2-tuple. The first item is the address of the function code, the second is the address of the\n        relocation target."
  },
  {
    "code": "def main():\n    parser = build_parser()\n    Job.Runner.addToilOptions(parser)\n    args = parser.parse_args()\n    inputs = {'config': args.config,\n              'config_fastq': args.config_fastq,\n              'input': args.input,\n              'unc.bed': args.unc,\n              'hg19.transcripts.fa': args.fasta,\n              'composite_exons.bed': args.composite_exons,\n              'normalize.pl': args.normalize,\n              'output_dir': args.output_dir,\n              'rsem_ref.zip': args.rsem_ref,\n              'chromosomes.zip': args.chromosomes,\n              'ebwt.zip': args.ebwt,\n              'ssec': args.ssec,\n              's3_dir': args.s3_dir,\n              'sudo': args.sudo,\n              'single_end_reads': args.single_end_reads,\n              'upload_bam_to_s3': args.upload_bam_to_s3,\n              'uuid': None,\n              'sample.tar': None,\n              'cpu_count': None}\n    Job.Runner.startToil(Job.wrapJobFn(download_shared_files, inputs), args)",
    "docstring": "This is a Toil pipeline for the UNC best practice RNA-Seq analysis.\n    RNA-seq fastqs are combined, aligned, sorted, filtered, and quantified.\n\n    Please read the README.md located in the same directory."
  },
  {
    "code": "def dir2zip(in_dir, zip_fname):\n    z = zipfile.ZipFile(zip_fname, 'w',\n                        compression=zipfile.ZIP_DEFLATED)\n    for root, dirs, files in os.walk(in_dir):\n        for file in files:\n            in_fname = pjoin(root, file)\n            in_stat = os.stat(in_fname)\n            info = zipfile.ZipInfo(in_fname)\n            info.filename = relpath(in_fname, in_dir)\n            if os.path.sep == '\\\\':\n                info.filename = relpath(in_fname, in_dir).replace('\\\\', '/')\n            info.date_time = time.localtime(in_stat.st_mtime)\n            perms = stat.S_IMODE(in_stat.st_mode) | stat.S_IFREG\n            info.external_attr = perms << 16\n            with open_readable(in_fname, 'rb') as fobj:\n                contents = fobj.read()\n            z.writestr(info, contents, zipfile.ZIP_DEFLATED)\n    z.close()",
    "docstring": "Make a zip file `zip_fname` with contents of directory `in_dir`\n\n    The recorded filenames are relative to `in_dir`, so doing a standard zip\n    unpack of the resulting `zip_fname` in an empty directory will result in\n    the original directory contents.\n\n    Parameters\n    ----------\n    in_dir : str\n        Directory path containing files to go in the zip archive\n    zip_fname : str\n        Filename of zip archive to write"
  },
  {
    "code": "def __get_wbfmt_usrfld(self, data_nt):\n        if self.ntfld_wbfmt is not None:\n            if isinstance(self.ntfld_wbfmt, str):\n                ntval = getattr(data_nt, self.ntfld_wbfmt, None)\n                if ntval is not None:\n                    return self.fmtname2wbfmtobj.get(ntval, None)",
    "docstring": "Return format for text cell from namedtuple field specified by 'ntfld_wbfmt"
  },
  {
    "code": "def activate(self, ideSettings, ideGlobalData):\n        WizardInterface.activate(self, ideSettings, ideGlobalData)\n        self.__where = self.__getConfiguredWhere()\n        self.ide.editorsManager.sigTabClosed.connect(self.__collectGarbage)\n        self.ide.project.sigProjectChanged.connect(self.__collectGarbage)",
    "docstring": "Activates the plugin.\n\n        The plugin may override the method to do specific\n        plugin activation handling.\n\n        ideSettings - reference to the IDE Settings singleton\n                      see codimension/src/utils/settings.py\n        ideGlobalData - reference to the IDE global settings\n                        see codimension/src/utils/globals.py\n\n        Note: if overriden do not forget to call the\n              base class activate()"
  },
  {
    "code": "def orphans_single(default_exec=False):\n    if not default_exec and executable.endswith('uwsgi'):\n        _executable = executable[:-5] + 'python'\n    else:\n        _executable = executable\n    p = subprocess.Popen([_executable, '-m', 'nikola', 'orphans'],\n                         stdout=subprocess.PIPE)\n    p.wait()\n    files = [l.strip().decode('utf-8') for l in p.stdout.readlines()]\n    for f in files:\n        if f:\n            os.unlink(f)\n    out = '\\n'.join(files)\n    return p.returncode, out",
    "docstring": "Remove all orphans in the site, in the single user-mode."
  },
  {
    "code": "def _CreateImage(media_service, opener, url):\n  image_data = opener.open(url).read().decode('utf-8')\n  image = {\n      'type': 'IMAGE',\n      'data': image_data,\n      'xsi_type': 'Image'\n  }\n  return media_service.upload(image)[0]",
    "docstring": "Creates an image and uploads it to the server.\n\n  Args:\n    media_service: a SudsServiceProxy instance for AdWords's MediaService.\n    opener: an OpenerDirector instance.\n    url: a str URL used to load image data.\n\n  Returns:\n    The image that was successfully uploaded."
  },
  {
    "code": "def get_apps_tools():\n    tools_paths = {}\n    for app_config in apps.get_app_configs():\n        proc_path = os.path.join(app_config.path, 'tools')\n        if os.path.isdir(proc_path):\n            tools_paths[app_config.name] = proc_path\n    custom_tools_paths = getattr(settings, 'RESOLWE_CUSTOM_TOOLS_PATHS', [])\n    if not isinstance(custom_tools_paths, list):\n        raise KeyError(\"`RESOLWE_CUSTOM_TOOLS_PATHS` setting must be a list.\")\n    for seq, custom_path in enumerate(custom_tools_paths):\n        custom_key = '_custom_{}'.format(seq)\n        tools_paths[custom_key] = custom_path\n    return tools_paths",
    "docstring": "Get applications' tools and their paths.\n\n    Return a dict with application names as keys and paths to tools'\n    directories as values. Applications without tools are omitted."
  },
  {
    "code": "def _postcheck(self, network, feedin):\n        curtailment = network.timeseries.curtailment\n        gen_repr = [repr(_) for _ in curtailment.columns]\n        feedin_repr = feedin.loc[:, gen_repr]\n        curtailment_repr = curtailment\n        curtailment_repr.columns = gen_repr\n        if not ((feedin_repr - curtailment_repr) > -1e-1).all().all():\n            message = 'Curtailment exceeds feed-in.'\n            logging.error(message)\n            raise TypeError(message)",
    "docstring": "Raises an error if the curtailment of a generator exceeds the\n        feed-in of that generator at any time step.\n\n        Parameters\n        -----------\n        network : :class:`~.grid.network.Network`\n        feedin : :pandas:`pandas.DataFrame<dataframe>`\n            DataFrame with feed-in time series in kW. Columns of the dataframe\n            are :class:`~.grid.components.GeneratorFluctuating`, index is\n            time index."
  },
  {
    "code": "def accuracy(current, predicted):\n  acc = 0\n  if np.count_nonzero(predicted) > 0:\n    acc = float(np.dot(current, predicted))/float(np.count_nonzero(predicted))\n  return acc",
    "docstring": "Computes the accuracy of the TM at time-step t based on the prediction\n  at time-step t-1 and the current active columns at time-step t.\n  \n  @param current (array) binary vector containing current active columns\n  @param predicted (array) binary vector containing predicted active columns  \n  @return acc (float) prediction accuracy of the TM at time-step t"
  },
  {
    "code": "def preflightInfo(info):\n    missingRequired = set()\n    missingRecommended = set()\n    for attr in requiredAttributes:\n        if not hasattr(info, attr) or getattr(info, attr) is None:\n            missingRequired.add(attr)\n    for attr in recommendedAttributes:\n        if not hasattr(info, attr) or getattr(info, attr) is None:\n            missingRecommended.add(attr)\n    return dict(missingRequired=missingRequired, missingRecommended=missingRecommended)",
    "docstring": "Returns a dict containing two items. The value for each\n    item will be a list of info attribute names.\n\n    ==================  ===\n    missingRequired     Required data that is missing.\n    missingRecommended  Recommended data that is missing.\n    ==================  ==="
  },
  {
    "code": "def cli(env, volume_id, reason, immediate):\n    file_storage_manager = SoftLayer.FileStorageManager(env.client)\n    if not (env.skip_confirmations or formatting.no_going_back(volume_id)):\n        raise exceptions.CLIAbort('Aborted')\n    cancelled = file_storage_manager.cancel_snapshot_space(\n        volume_id, reason, immediate)\n    if cancelled:\n        if immediate:\n            click.echo('File volume with id %s has been marked'\n                       ' for immediate snapshot cancellation' % volume_id)\n        else:\n            click.echo('File volume with id %s has been marked'\n                       ' for snapshot cancellation' % volume_id)\n    else:\n        click.echo('Unable to cancel snapshot space for file volume %s'\n                   % volume_id)",
    "docstring": "Cancel existing snapshot space for a given volume."
  },
  {
    "code": "def wheel(self, direction, steps):\n        self._lock.acquire()\n        if direction == 1:\n            wheel_moved = steps\n        elif direction == 0:\n            wheel_moved = -1*steps\n        else:\n            raise ValueError(\"Expected direction to be 1 or 0\")\n        self._lock.release()\n        return mouse.wheel(wheel_moved)",
    "docstring": "Clicks the wheel the specified number of steps in the given direction.\n\n        Use Mouse.WHEEL_DOWN, Mouse.WHEEL_UP"
  },
  {
    "code": "def update_user_info(self, **kwargs):\n        if kwargs:\n            self.config.update(kwargs)\n        method, url = get_URL('user_update')\n        res = getattr(self.session, method)(url, params=self.config)\n        if res.status_code == 200:\n            return True\n        hellraiser(res)",
    "docstring": "Update user info and settings.\n\n        :param \\*\\*kwargs: settings to be merged with\n         :func:`User.get_configfile` setings and sent to Filemail.\n        :rtype: ``bool``"
  },
  {
    "code": "def broadcast(self):\n        log.debug(\"Broadcasting M-SEARCH to %s:%s\", self.mcast_ip, self.mcast_port)\n        request = '\\r\\n'.join((\"M-SEARCH * HTTP/1.1\",\n                               \"HOST:{mcast_ip}:{mcast_port}\",\n                               \"ST:upnp:rootdevice\",\n                               \"MX:2\",\n                               'MAN:\"ssdp:discover\"',\n                               \"\", \"\")).format(**self.__dict__)\n        self.server.sendto(request.encode(), (self.mcast_ip, self.mcast_port))",
    "docstring": "Send a multicast M-SEARCH request asking for devices to report in."
  },
  {
    "code": "def get_last_nonce(app, key, nonce):\n    uk = ses.query(um.UserKey).filter(um.UserKey.key==key)\\\n            .filter(um.UserKey.last_nonce<nonce * 1000).first()\n    if not uk:\n        return None\n    lastnonce = copy.copy(uk.last_nonce)\n    uk.last_nonce = nonce * 1000\n    try:\n        ses.commit()\n    except Exception as e:\n        current_app.logger.exception(e)\n        ses.rollback()\n        ses.flush()\n    return lastnonce",
    "docstring": "Get the last_nonce used by the given key from the SQLAlchemy database.\n    Update the last_nonce to nonce at the same time.\n\n    :param str key: the public key the nonce belongs to\n    :param int nonce: the last nonce used by this key"
  },
  {
    "code": "def add_item(self, alias, item):\n        if not isinstance(alias, six.string_types):\n            raise TypeError('Item name must be a string, got a {!r}'.format(type(alias)))\n        item = copy.deepcopy(item)\n        if item.name is not_set:\n            item.name = alias\n        if self.settings.str_path_separator in item.name:\n            raise ValueError(\n                'Item name must not contain str_path_separator which is configured for this Config -- {!r} -- '\n                'but {!r} does.'.format(self.settings.str_path_separator, item)\n            )\n        self._tree[item.name] = item\n        if item.name != alias:\n            if self.settings.str_path_separator in alias:\n                raise ValueError(\n                    'Item alias must not contain str_path_separator which is configured for this Config -- {!r} --'\n                    'but {!r} used for {!r} does.'.format(self.settings.str_path_separator, alias, item)\n                )\n            self._tree[alias] = item\n        item._section = self\n        self.dispatch_event(self.hooks.item_added_to_section, alias=alias, section=self, subject=item)",
    "docstring": "Add a config item to this section."
  },
  {
    "code": "def lexeme(self, verb, parse=True):\n        a = []\n        b = self.lemma(verb, parse=parse)\n        if b in self:\n            a = [x for x in self[b] if x != \"\"]\n        elif parse is True:\n            a = self.find_lexeme(b)\n        u = []; [u.append(x) for x in a if x not in u]\n        return u",
    "docstring": "Returns a list of all possible inflections of the given verb."
  },
  {
    "code": "def unwrap(self, value, session=None):\n        self.validate_unwrap(value)\n        return set([self.item_type.unwrap(v, session=session) for v in value])",
    "docstring": "Unwraps the elements of ``value`` using ``SetField.item_type`` and\n            returns them in a set"
  },
  {
    "code": "def get_subscriber_queue(self, event_types=None):\n        try:\n            self.started_queue.get(timeout=1)\n            raise RuntimeError('Cannot create a new subscriber queue while Exchange is running.')\n        except Empty:\n            pass\n        if event_types is None:\n            event_types = EventTypes.ALL\n        queue = Queue()\n        self.queues[event_types].append(queue)\n        return queue",
    "docstring": "Create a new queue for a specific combination of event types\n        and return it.\n\n        Returns:\n            a :class:`multiprocessing.Queue`.\n        Raises:\n            RuntimeError if called after `run`"
  },
  {
    "code": "def is_valid_schedule(schedule, events, slots):\n    if len(schedule) == 0:\n        return False\n    array = converter.schedule_to_array(schedule, events, slots)\n    return is_valid_array(array, events, slots)",
    "docstring": "Take a schedule and return whether it is a valid solution for the\n    given constraints\n\n    Parameters\n    ----------\n        schedule : list or tuple\n            a schedule in schedule form\n        events : list or tuple\n            of resources.Event instances\n        slots : list or tuple\n            of resources.Slot instances\n\n    Returns\n    -------\n        bool\n            True if schedule is a valid solution"
  },
  {
    "code": "def upload_file(self, dataset_key, name, file_metadata={}, **kwargs):\n        owner_id, dataset_id = parse_dataset_key(dataset_key)\n        try:\n            self._uploads_api.upload_file(owner_id, dataset_id, name, **kwargs)\n            if file_metadata:\n                self.update_dataset(dataset_key, files=file_metadata)\n        except _swagger.rest.ApiException as e:\n            raise RestApiError(cause=e)",
    "docstring": "Upload one file to a dataset\n\n        :param dataset_key: Dataset identifier, in the form of owner/id\n        :type dataset_key: str\n        :param name: Name/path for files stored in the local filesystem\n        :type name: str\n        :param expand_archives: Boolean value to indicate files should be\n        expanded upon upload\n        :type expand_archive: bool optional\n        :param files_metadata: Dict containing the name of files and metadata\n        Uses file name as a dict containing File description, labels and\n        source URLs to add or update\n        :type files_metadata: dict optional\n        :raises RestApiException: If a server error occurs\n\n        Examples\n        --------\n        >>> import datadotworld as dw\n        >>> api_client = dw.api_client()\n        >>> api_client.upload_file(\n        ...     'username/test-dataset',\n        ...     'example.csv')  # doctest: +SKIP"
  },
  {
    "code": "def render_description_meta_tag(context, is_og=False):\n    request = context['request']\n    content = ''\n    if context.get('object'):\n        try:\n            content = context['object'].get_meta_description()\n        except AttributeError:\n            pass\n    elif context.get('meta_tagger'):\n        content = context['meta_tagger'].get('description')\n    if not content:\n        try:\n            content = request.current_page.get_meta_description()\n        except (AttributeError, NoReverseMatch):\n            pass\n    if content:\n        return mark_safe('<meta {attr_name}=\"{tag_name}\" content=\"{content}\">'.format(\n            attr_name='name' if not is_og else 'property',\n            tag_name='description' if not is_og else 'og:description',\n            content=content\n        ))\n    else:\n        return ''",
    "docstring": "Returns the description as meta or open graph tag."
  },
  {
    "code": "def getOntology(self, id_):\n        if id_ not in self._ontologyIdMap:\n            raise exceptions.OntologyNotFoundException(id_)\n        return self._ontologyIdMap[id_]",
    "docstring": "Returns the ontology with the specified ID."
  },
  {
    "code": "def repl_update(self, config):\n        cfg = config.copy()\n        cfg['version'] += 1\n        try:\n            result = self.run_command(\"replSetReconfig\", cfg)\n            if int(result.get('ok', 0)) != 1:\n                return False\n        except pymongo.errors.AutoReconnect:\n            self.update_server_map(cfg)\n        self.waiting_member_state()\n        self.waiting_config_state()\n        return self.connection() and True",
    "docstring": "Reconfig Replicaset with new config"
  },
  {
    "code": "def reload(self, callback=None, errback=None):\n        return self.load(reload=True, callback=callback, errback=errback)",
    "docstring": "Reload record data from the API."
  },
  {
    "code": "def HandleAccounts(self, result):\n    self.logger.debug('Checking for changes to user accounts.')\n    configured_users = self.utils.GetConfiguredUsers()\n    enable_oslogin = self._GetEnableOsLoginValue(result)\n    enable_two_factor = self._GetEnableTwoFactorValue(result)\n    if enable_oslogin:\n      desired_users = {}\n      self.oslogin.UpdateOsLogin(True, two_factor_desired=enable_two_factor)\n    else:\n      desired_users = self._GetAccountsData(result)\n      self.oslogin.UpdateOsLogin(False)\n    remove_users = sorted(set(configured_users) - set(desired_users.keys()))\n    self._UpdateUsers(desired_users)\n    self._RemoveUsers(remove_users)\n    self.utils.SetConfiguredUsers(desired_users.keys())",
    "docstring": "Called when there are changes to the contents of the metadata server.\n\n    Args:\n      result: json, the deserialized contents of the metadata server."
  },
  {
    "code": "def default(self, meth):\n        if self._default is not NOTHING:\n            raise DefaultAlreadySetError()\n        self._default = Factory(meth, takes_self=True)\n        return meth",
    "docstring": "Decorator that allows to set the default for an attribute.\n\n        Returns *meth* unchanged.\n\n        :raises DefaultAlreadySetError: If default has been set before.\n\n        .. versionadded:: 17.1.0"
  },
  {
    "code": "def put(self, content_bytes):\n        derived_path = self.context.request.url\n        over_max, content_size = self.content_size_exceeded_max(content_bytes)\n        logger.debug('[{log_prefix}] content size in bytes: {size}'\n            ' | is over max? {over_max} | skip storage? {skip}'.format(\n            log_prefix=LOG_PREFIX, size=content_size, over_max=over_max,\n            skip=self.skip_storage()))\n        if (over_max and self.skip_storage()):\n            logger.debug('[{log_prefix}] skipping storage: {content_size} '\n                           'exceeds item_size_max of {max_size}'.format(\n                           log_prefix=LOG_PREFIX, content_size=content_size,\n                           max_size=self.item_size_max()))\n            return None\n        self.storage.set(\n            self.timestamp_key_for(derived_path), datetime.utcnow(),\n            time=self.context.config.RESULT_STORAGE_EXPIRATION_SECONDS\n        )\n        self.storage.set(\n            self.result_key_for(derived_path), content_bytes,\n            time=self.context.config.RESULT_STORAGE_EXPIRATION_SECONDS\n        )\n        return derived_path",
    "docstring": "Save the `bytes` under a key derived from `path` in Memcache.\n\n        :return: A string representing the content path if it is stored.\n        :rettype: string or None"
  },
  {
    "code": "def angle_to_name(angle, segments=8, abbr=False):\n    if segments == 4:\n        string = COMPASS_NAMES[int((angle + 45) / 90) % 4 * 2]\n    elif segments == 8:\n        string = COMPASS_NAMES[int((angle + 22.5) / 45) % 8 * 2]\n    elif segments == 16:\n        string = COMPASS_NAMES[int((angle + 11.25) / 22.5) % 16]\n    else:\n        raise ValueError('Segments parameter must be 4, 8 or 16 not %r'\n                         % segments)\n    if abbr:\n        return ''.join(i[0].capitalize() for i in string.split('-'))\n    else:\n        return string",
    "docstring": "Convert angle in to direction name.\n\n    Args:\n        angle (float): Angle in degrees to convert to direction name\n        segments (int): Number of segments to split compass in to\n        abbr (bool): Whether to return abbreviated direction string\n\n    Returns:\n        str: Direction name for ``angle``"
  },
  {
    "code": "def _eratosthenes():\n    d = {}\n    for q in count(2):\n        p = d.pop(q, None)\n        if p is None:\n            yield q\n            d[q * q] = q\n        else:\n            x = p + q\n            while x in d:\n                x += p\n            d[x] = p",
    "docstring": "Yields the sequence of prime numbers via the Sieve of Eratosthenes."
  },
  {
    "code": "def RetrievePluginAsset(self, plugin_name, asset_name):\n    return plugin_asset_util.RetrieveAsset(self.path, plugin_name, asset_name)",
    "docstring": "Return the contents of a given plugin asset.\n\n    Args:\n      plugin_name: The string name of a plugin.\n      asset_name: The string name of an asset.\n\n    Returns:\n      The string contents of the plugin asset.\n\n    Raises:\n      KeyError: If the asset is not available."
  },
  {
    "code": "def normalize(self):\n\t\tfor i, (_, amplitude, phase) in enumerate(self.model):\n\t\t\tif amplitude < 0:\n\t\t\t\tself.model['amplitude'][i] = -amplitude\n\t\t\t\tself.model['phase'][i] = phase + 180.0\n\t\t\tself.model['phase'][i] = np.mod(self.model['phase'][i], 360.0)",
    "docstring": "Adapt self.model so that amplitudes are positive and phases are in [0,360) as per convention"
  },
  {
    "code": "def ack(self, msg):\n        message_id = msg['headers']['message-id']\n        subscription = msg['headers']['subscription']\n        transaction_id = None\n        if 'transaction-id' in msg['headers']:\n            transaction_id = msg['headers']['transaction-id']\n        return ack(message_id, subscription, transaction_id)",
    "docstring": "Called when a MESSAGE has been received.\n\n        Override this method to handle received messages.\n\n        This function will generate an acknowledge message\n        for the given message and transaction (if present)."
  },
  {
    "code": "def build_dependencies(self):\n        for m in self.modules:\n            m.build_dependencies()\n        for p in self.packages:\n            p.build_dependencies()",
    "docstring": "Recursively build the dependencies for sub-modules and sub-packages.\n\n        Iterate on node's modules then packages and call their\n        build_dependencies methods."
  },
  {
    "code": "def submit(self, spec):\n        spec = ApplicationSpec._from_any(spec)\n        resp = self._call('submit', spec.to_protobuf())\n        return resp.id",
    "docstring": "Submit a new skein application.\n\n        Parameters\n        ----------\n        spec : ApplicationSpec, str, or dict\n            A description of the application to run. Can be an\n            ``ApplicationSpec`` object, a path to a yaml/json file, or a\n            dictionary description of an application specification.\n\n        Returns\n        -------\n        app_id : str\n            The id of the submitted application."
  },
  {
    "code": "def snapshot_list(self):\n        NO_SNAPSHOTS_TAKEN = 'No snapshots have been taken yet!'\n        output = self._run_vagrant_command(['snapshot', 'list'])\n        if NO_SNAPSHOTS_TAKEN in output:\n            return []\n        else:\n            return output.splitlines()",
    "docstring": "This command will list all the snapshots taken."
  },
  {
    "code": "def create_app_from_yml(path):\n    try:\n        with open(path, \"rt\", encoding=\"UTF-8\") as f:\n            try:\n                interpolated = io.StringIO(f.read() % {\n                    \"here\": os.path.abspath(os.path.dirname(path))})\n                interpolated.name = f.name\n                conf = yaml.safe_load(interpolated)\n            except yaml.YAMLError as exc:\n                raise RuntimeError(\n                    \"Cannot parse a configuration file. Context: \" + str(exc))\n    except FileNotFoundError:\n        conf = {\"metadata\": None, \"pipes\": {}}\n    return core.create_app(conf[\"metadata\"], pipes=conf[\"pipes\"])",
    "docstring": "Return an application instance created from YAML."
  },
  {
    "code": "def request_access_token(self, params):\n        return self.request(self.access_token_url, method=\"GET\", params=params)",
    "docstring": "Foursquare does not accept POST requests to retrieve an access token,\n        so we'll be doing a GET request instead."
  },
  {
    "code": "def from_wif_or_ewif_hex(wif_hex: str, password: Optional[str] = None) -> SigningKeyType:\n        wif_bytes = Base58Encoder.decode(wif_hex)\n        fi = wif_bytes[0:1]\n        if fi == b\"\\x01\":\n            return SigningKey.from_wif_hex(wif_hex)\n        elif fi == b\"\\x02\" and password is not None:\n            return SigningKey.from_ewif_hex(wif_hex, password)\n        else:\n            raise Exception(\"Error: Bad format: not WIF nor EWIF\")",
    "docstring": "Return SigningKey instance from Duniter WIF or EWIF in hexadecimal format\n\n        :param wif_hex: WIF or EWIF string in hexadecimal format\n        :param password: Password of EWIF encrypted seed"
  },
  {
    "code": "def tar_open(f):\n    if isinstance(f, six.string_types):\n        return tarfile.open(name=f)\n    else:\n        return tarfile.open(fileobj=f)",
    "docstring": "Open either a filename or a file-like object as a TarFile.\n\n    Parameters\n    ----------\n    f : str or file-like object\n        The filename or file-like object from which to read.\n\n    Returns\n    -------\n    TarFile\n        A `TarFile` instance."
  },
  {
    "code": "def slice_target(self,chr,start,end):\n     trng = Bed(chr,start,end)\n     nrngs = []\n     for r in self._rngs:\n        i = r.intersect(trng)\n        if not i: continue\n        nrngs.append(i)\n     if len(nrngs) == 0: return None\n     return MappingGeneric(nrngs,self._options)",
    "docstring": "Slice the mapping by the target coordinate\n        \n        First coordinate is 0-indexed start\n        Second coordinate is 1-indexed finish"
  },
  {
    "code": "def status_charge():\n    data = status()\n    if 'BCHARGE' in data:\n        charge = data['BCHARGE'].split()\n        if charge[1].lower() == 'percent':\n            return float(charge[0])\n    return {'Error': 'Load not available.'}",
    "docstring": "Return battery charge\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' apcups.status_charge"
  },
  {
    "code": "def cmd_posvel(self, args):\n        ignoremask = 511\n        latlon = None\n        try:\n            latlon = self.module('map').click_position\n        except Exception:\n            pass\n        if latlon is None:\n            print (\"set latlon to zeros\")\n            latlon = [0, 0]\n        else:\n            ignoremask = ignoremask & 504\n            print (\"found latlon\", ignoremask)\n        vN = 0\n        vE = 0\n        vD = 0\n        if (len(args) == 3):\n            vN = float(args[0])\n            vE = float(args[1])\n            vD = float(args[2])\n            ignoremask = ignoremask & 455\n        print (\"ignoremask\",ignoremask)\n        print (latlon)\n        self.master.mav.set_position_target_global_int_send(\n            0,\n            1,\n            0,\n            mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT,\n            ignoremask,\n            int(latlon[0] * 1e7),\n            int(latlon[1] * 1e7),\n            10,\n            vN, vE, vD,\n            0, 0, 0,\n            0, 0)",
    "docstring": "posvel mapclick vN vE vD"
  },
  {
    "code": "def scale_joint_sfs(s):\n    i = np.arange(s.shape[0])[:, None]\n    j = np.arange(s.shape[1])[None, :]\n    out = (s * i) * j\n    return out",
    "docstring": "Scale a joint site frequency spectrum.\n\n    Parameters\n    ----------\n    s : array_like, int, shape (n1, n2)\n        Joint site frequency spectrum.\n\n    Returns\n    -------\n    joint_sfs_scaled : ndarray, int, shape (n1, n2)\n        Scaled joint site frequency spectrum."
  },
  {
    "code": "def register_on_machine_registered(self, callback):\n        event_type = library.VBoxEventType.on_machine_registered\n        return self.event_source.register_callback(callback, event_type)",
    "docstring": "Set the callback function to consume on machine registered events.\n\n        Callback receives a IMachineRegisteredEvent object.\n\n        Returns the callback_id"
  },
  {
    "code": "def get_all_launch_configurations(region=None, key=None, keyid=None,\n                                  profile=None):\n    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n    retries = 30\n    while True:\n        try:\n            return conn.get_all_launch_configurations()\n        except boto.exception.BotoServerError as e:\n            if retries and e.code == 'Throttling':\n                log.debug('Throttled by AWS API, retrying in 5 seconds...')\n                time.sleep(5)\n                retries -= 1\n                continue\n            log.error(e)\n            return []",
    "docstring": "Fetch and return all Launch Configuration with details.\n\n    CLI example::\n\n        salt myminion boto_asg.get_all_launch_configurations"
  },
  {
    "code": "def get_escalation_policies(profile='pagerduty', subdomain=None, api_key=None):\n    return _list_items(\n        'escalation_policies',\n        'id',\n        profile=profile,\n        subdomain=subdomain,\n        api_key=api_key,\n    )",
    "docstring": "List escalation_policies belonging to this account\n\n    CLI Example:\n\n        salt myminion pagerduty.get_escalation_policies"
  },
  {
    "code": "def cache(self):\n        if not self._cache:\n            use_cache = getattr(settings, 'USE_DRF_INSTANCE_CACHE', True)\n            if use_cache:\n                from django.core.cache import cache\n                self._cache = cache\n        return self._cache",
    "docstring": "Get the Django cache interface.\n\n        This allows disabling the cache with\n        settings.USE_DRF_INSTANCE_CACHE=False.  It also delays import so that\n        Django Debug Toolbar will record cache requests."
  },
  {
    "code": "def get_all_args(fn) -> list:\n    sig = inspect.signature(fn)\n    return list(sig.parameters)",
    "docstring": "Returns a list of all arguments for the function fn.\n\n    >>> def foo(x, y, z=100): return x + y + z\n    >>> get_all_args(foo)\n    ['x', 'y', 'z']"
  },
  {
    "code": "def qs_for_ip(cls, ip_str):\n        ip = int(netaddr.IPAddress(ip_str))\n        if ip > 4294967295:\n            return cls.objects.none()\n        ip_range_query = {\n            'start__lte': ip,\n            'stop__gte': ip\n        }\n        return cls.objects.filter(**ip_range_query)",
    "docstring": "Returns a queryset with matching IPNetwork objects for the given IP."
  },
  {
    "code": "def UpdateClientsFromFleetspeak(clients):\n  if not fleetspeak_connector.CONN or not fleetspeak_connector.CONN.outgoing:\n    return\n  id_map = {}\n  for client in clients:\n    if client.fleetspeak_enabled:\n      id_map[fleetspeak_utils.GRRIDToFleetspeakID(client.client_id)] = client\n  if not id_map:\n    return\n  res = fleetspeak_connector.CONN.outgoing.ListClients(\n      admin_pb2.ListClientsRequest(client_ids=list(iterkeys(id_map))))\n  for read in res.clients:\n    api_client = id_map[read.client_id]\n    api_client.last_seen_at = fleetspeak_utils.TSToRDFDatetime(\n        read.last_contact_time)\n    api_client.last_clock = fleetspeak_utils.TSToRDFDatetime(read.last_clock)",
    "docstring": "Updates ApiClient records to include info from Fleetspeak."
  },
  {
    "code": "def dtypes(self):\n        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]",
    "docstring": "Returns all column names and their data types as a list.\n\n        >>> df.dtypes\n        [('age', 'int'), ('name', 'string')]"
  },
  {
    "code": "def add_row(self, row_data, resize_x=True):\n        if not resize_x:\n            self._check_row_size(row_data)\n        self.body(Tr()(Td()(cell) for cell in row_data))\n        return self",
    "docstring": "Adds a row at the end of the table"
  },
  {
    "code": "def createManager(self, services, yadis_url=None):\n        key = self.getSessionKey()\n        if self.getManager():\n            raise KeyError('There is already a %r manager for %r' %\n                           (key, self.url))\n        if not services:\n            return None\n        manager = YadisServiceManager(self.url, yadis_url, services, key)\n        manager.store(self.session)\n        return manager",
    "docstring": "Create a new YadisService Manager for this starting URL and\n        suffix, and store it in the session.\n\n        @raises KeyError: When I already have a manager.\n\n        @return: A new YadisServiceManager or None"
  },
  {
    "code": "def reind_proc(self, inputstring, **kwargs):\n        out = []\n        level = 0\n        for line in inputstring.splitlines():\n            line, comment = split_comment(line.strip())\n            indent, line = split_leading_indent(line)\n            level += ind_change(indent)\n            if line:\n                line = \" \" * self.tabideal * level + line\n            line, indent = split_trailing_indent(line)\n            level += ind_change(indent)\n            line = (line + comment).rstrip()\n            out.append(line)\n        if level != 0:\n            complain(CoconutInternalException(\"non-zero final indentation level\", level))\n        return \"\\n\".join(out)",
    "docstring": "Add back indentation."
  },
  {
    "code": "def validate_row_lengths(fields,\n                         data\n                         ):\n    for i, row in enumerate(data):\n        if len(fields) != len(row):\n            msg = 'Row {} has {} entries when {} are expected.'.format(\n                i, len(row), len(fields))\n            raise FormatError(msg)",
    "docstring": "Validate the `data` row lengths according to the specification\n        in `fields`.\n\n        :param fields: The `FieldSpec` objects forming the\n            specification.\n        :param data: The rows to check.\n        :raises FormatError: When the number of entries in a row does\n            not match expectation."
  },
  {
    "code": "def get_resource_path(name, raise_exception=False):\n    if not RuntimeGlobals.resources_directories:\n        RuntimeGlobals.resources_directories.append(\n            os.path.normpath(os.path.join(umbra.__path__[0], Constants.resources_directory)))\n    for path in RuntimeGlobals.resources_directories:\n        path = os.path.join(path, name)\n        if foundations.common.path_exists(path):\n            LOGGER.debug(\"> '{0}' resource path: '{1}'.\".format(name, path))\n            return path\n    if raise_exception:\n        raise umbra.exceptions.ResourceExistsError(\n            \"{0} | No resource file path found for '{1}' name!\".format(__name__, name))",
    "docstring": "Returns the resource file path matching the given name.\n\n    :param name: Resource name.\n    :type name: unicode\n    :param raise_exception: Raise the exception.\n    :type raise_exception: bool\n    :return: Resource path.\n    :rtype: unicode"
  },
  {
    "code": "def b58check_encode(bin_s, version_byte=0):\n    bin_s = chr(int(version_byte)) + bin_s\n    num_leading_zeros = len(re.match(r'^\\x00*', bin_s).group(0))\n    bin_s = bin_s + bin_checksum(bin_s)\n    hex_s = hexlify(bin_s)\n    b58_s = change_charset(hex_s, HEX_KEYSPACE, B58_KEYSPACE)\n    return B58_KEYSPACE[0] * num_leading_zeros + b58_s",
    "docstring": "Takes in a binary string and converts it to a base 58 check string."
  },
  {
    "code": "def is_sub_plate(self, other):\n        if all(v in set(other.values) for v in self.values):\n            return True\n        if all(any(all(spv in m for spv in v) for m in map(set, other.values)) for v in self.values):\n            return True\n        if other in self.ancestor_plates:\n            return True\n        return False",
    "docstring": "Determines if this plate is a sub-plate of another plate -\n        i.e. has the same meta data but a restricted set of values\n\n        :param other: The other plate\n        :return: True if this plate is a sub-plate of the other plate"
  },
  {
    "code": "def _bsecurate_cli_view_graph(args):\n    curate.view_graph(args.basis, args.version, args.data_dir)\n    return ''",
    "docstring": "Handles the view-graph subcommand"
  },
  {
    "code": "def get(self, request, hook_id):\n        try:\n            bot = caching.get_or_set(MessengerBot, hook_id)\n        except MessengerBot.DoesNotExist:\n            logger.warning(\"Hook id %s not associated to a bot\" % hook_id)\n            return Response(status=status.HTTP_404_NOT_FOUND)\n        if request.query_params.get('hub.verify_token') == str(bot.id):\n            return Response(int(request.query_params.get('hub.challenge')))\n        return Response('Error, wrong validation token')",
    "docstring": "Verify token when configuring webhook from facebook dev.\n        \n        MessengerBot.id is used for verification"
  },
  {
    "code": "def path_is_known_executable(path):\n    return (\n        path_is_executable(path)\n        or os.access(str(path), os.R_OK)\n        and path.suffix in KNOWN_EXTS\n    )",
    "docstring": "Returns whether a given path is a known executable from known executable extensions\n    or has the executable bit toggled.\n\n    :param path: The path to the target executable.\n    :type path: :class:`~vistir.compat.Path`\n    :return: True if the path has chmod +x, or is a readable, known executable extension.\n    :rtype: bool"
  },
  {
    "code": "def get_readable_forums(self, forums, user):\n        if user.is_superuser:\n            return forums\n        readable_forums = self._get_forums_for_user(\n            user, ['can_read_forum', ], use_tree_hierarchy=True)\n        return forums.filter(id__in=[f.id for f in readable_forums]) \\\n            if isinstance(forums, (models.Manager, models.QuerySet)) \\\n            else list(filter(lambda f: f in readable_forums, forums))",
    "docstring": "Returns a queryset of forums that can be read by the considered user."
  },
  {
    "code": "def get_index(binstr, end_index=160):\n    res = -1\n    try:\n        res = binstr.index('1') + 1\n    except ValueError:\n        res = end_index\n    return res",
    "docstring": "Return the position of the first 1 bit\n    from the left in the word until end_index\n\n    :param binstr:\n    :param end_index:\n    :return:"
  },
  {
    "code": "def get_trust(self):\n        if not bool(self._my_map['trustId']):\n            raise errors.IllegalState('this Authorization has no trust')\n        mgr = self._get_provider_manager('AUTHENTICATION.PROCESS')\n        if not mgr.supports_trust_lookup():\n            raise errors.OperationFailed('Authentication.Process does not support Trust lookup')\n        lookup_session = mgr.get_trust_lookup_session(proxy=getattr(self, \"_proxy\", None))\n        lookup_session.use_federated_agency_view()\n        osid_object = lookup_session.get_trust(self.get_trust_id())\n        return osid_object",
    "docstring": "Gets the ``Trust`` for this authorization.\n\n        return: (osid.authentication.process.Trust) - the ``Trust``\n        raise:  IllegalState - ``has_trust()`` is ``false``\n        raise:  OperationFailed - unable to complete request\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_acl_on(request):\n    acl_on = settings.ACL_ON\n    if settings.LOCKDOWN and hasattr(request, 'user'):\n        if request.user.is_superuser:\n            acl_on = False\n    return acl_on",
    "docstring": "Returns `True` if ACL should be honorated, returns otherwise `False`."
  },
  {
    "code": "def _precompile_substitution(self, kind, pattern):\n        if pattern not in self._regexc[kind]:\n            qm = re.escape(pattern)\n            self._regexc[kind][pattern] = {\n                \"qm\": qm,\n                \"sub1\": re.compile(r'^' + qm + r'$'),\n                \"sub2\": re.compile(r'^' + qm + r'(\\W+)'),\n                \"sub3\": re.compile(r'(\\W+)' + qm + r'(\\W+)'),\n                \"sub4\": re.compile(r'(\\W+)' + qm + r'$'),\n            }",
    "docstring": "Pre-compile the regexp for a substitution pattern.\n\n        This will speed up the substitutions that happen at the beginning of\n        the reply fetching process. With the default brain, this took the\n        time for _substitute down from 0.08s to 0.02s\n\n        :param str kind: One of ``sub``, ``person``.\n        :param str pattern: The substitution pattern."
  },
  {
    "code": "def And(*args: Union[Bool, bool]) -> Bool:\n    union = []\n    args_list = [arg if isinstance(arg, Bool) else Bool(arg) for arg in args]\n    for arg in args_list:\n        union.append(arg.annotations)\n    return Bool(z3.And([a.raw for a in args_list]), union)",
    "docstring": "Create an And expression."
  },
  {
    "code": "def weight_decay(decay_rate, var_list, skip_biases=True):\n  if not decay_rate:\n    return 0.\n  tf.logging.info(\"Applying weight decay, decay_rate: %0.5f\", decay_rate)\n  weight_decays = []\n  for v in var_list:\n    is_bias = len(v.shape.as_list()) == 1 and v.name.endswith(\"bias:0\")\n    if not (skip_biases and is_bias):\n      with tf.device(v.device):\n        v_loss = tf.nn.l2_loss(v)\n      weight_decays.append(v_loss)\n  return tf.add_n(weight_decays) * decay_rate",
    "docstring": "Apply weight decay to vars in var_list."
  },
  {
    "code": "def get_option_choices(opt_name, opt_value, default_value, all_choices):\n    choices = []\n    if isinstance(opt_value, six.string_types):\n        choices = [opt_value]\n    elif isinstance(opt_value, (list, tuple)):\n        choices = list(opt_value)\n    elif opt_value is None:\n        choices = default_value\n    else:\n        raise InvalidOption('Option %s has invalid'\n                            ' value: %s' % (opt_name, opt_value))\n    if 'all' in choices:\n        choices = all_choices\n    for item in choices:\n        if item not in all_choices:\n            raise InvalidOption('Choices of option %s contains invalid'\n                                ' item: %s' % (opt_name, item))\n    return choices",
    "docstring": "Generate possible choices for the option `opt_name`\n    limited to `opt_value` value with default value\n    as `default_value`"
  },
  {
    "code": "def _parse_version(self, line):\n        version_string = line.split(' ')[1]\n        version_list = version_string.split('.')\n        major_version = ''.join([version_list[0], version_list[1]])\n        release_num = ''.join([version_list[2].rstrip(), \"-03\"])\n        return (major_version, release_num)",
    "docstring": "There's a magic suffix to the release version, currently it's -03, but\n        it increments seemingly randomly."
  },
  {
    "code": "async def get_checkpoint_async(self, partition_id):\n        lease = await self.get_lease_async(partition_id)\n        checkpoint = None\n        if lease:\n            if lease.offset:\n                checkpoint = Checkpoint(partition_id, lease.offset,\n                                        lease.sequence_number)\n        return checkpoint",
    "docstring": "Get the checkpoint data associated with the given partition.\n        Could return null if no checkpoint has been created for that partition.\n\n        :param partition_id: The partition ID.\n        :type partition_id: str\n        :return: Given partition checkpoint info, or `None` if none has been previously stored.\n        :rtype: ~azure.eventprocessorhost.checkpoint.Checkpoint"
  },
  {
    "code": "def data_complete(datadir, sitedir, get_container_name):\n    if any(not path.isdir(sitedir + x)\n            for x in ('/files', '/run', '/solr')):\n        return False\n    if docker.is_boot2docker():\n        return all(docker.inspect_container(get_container_name(x))\n                for x in ('pgdata', 'venv'))\n    return path.isdir(datadir + '/venv') and path.isdir(sitedir + '/postgres')",
    "docstring": "Return True if the directories and containers we're expecting\n    are present in datadir, sitedir and containers"
  },
  {
    "code": "def get_extents(self):\n        extents = ffi.new('cairo_rectangle_t *')\n        if cairo.cairo_recording_surface_get_extents(self._pointer, extents):\n            return (extents.x, extents.y, extents.width, extents.height)",
    "docstring": "Return the extents of the recording-surface.\n\n        :returns:\n            A ``(x, y, width, height)`` tuple of floats,\n            or :obj:`None` if the surface is unbounded.\n\n        *New in cairo 1.12*"
  },
  {
    "code": "def certify_tuple(value, certifier=None, min_len=None, max_len=None, required=True, schema=None):\n    certify_iterable(\n        value=value,\n        types=tuple([tuple]),\n        certifier=certifier,\n        min_len=min_len,\n        max_len=max_len,\n        schema=schema,\n        required=required,\n    )",
    "docstring": "Validates a tuple, checking it against an optional schema.\n\n    The schema should be a list of expected values replaced by functions which will be called to\n    with the corresponding value in the input.\n\n    A simple example:\n\n        >>> certifier = certify_tuple(schema=(\n        ...     certify_key(kind='Model'),\n        ...     certify_int(min=0),\n        ...     ))\n        >>> certifier((self.key, self.count))\n\n    :param tuple value:\n        The value to be certified.\n    :param func certifier:\n        A function to be called on each value in the iterable to check that it is valid.\n    :param int min_len:\n        The minimum acceptable length for the iterable.  If None, the minimum length is not checked.\n    :param int max_len:\n        The maximum acceptable length for the iterable.  If None, the maximum length is not checked.\n    :param bool required:\n        Whether the value can't be `None`. Defaults to True.\n    :param tuple schema:\n        The schema against which the value should be checked.\n        For single-item tuple make sure to add comma at the end of schema tuple, that is,\n        for example: schema=(certify_int(),)\n    :return:\n        The certified tuple.\n    :rtype:\n        tuple\n    :raises CertifierTypeError:\n        The type is invalid\n    :raises CertifierValueError:\n        The valid is invalid"
  },
  {
    "code": "def get_boundaries(self, filter_type, value):\n        assert filter_type in self.handled_suffixes\n        start = '-'\n        end = '+'\n        exclude = None\n        if filter_type in (None, 'eq'):\n            start = u'[%s%s' % (value, self.separator)\n            end = start.encode('utf-8') + b'\\xff'\n        elif filter_type == 'gt':\n            start = u'(%s' % value\n            exclude = value\n        elif filter_type == 'gte':\n            start = u'[%s' % value\n        elif filter_type == 'lt':\n            end = u'(%s' % value\n            exclude = value\n        elif filter_type == 'lte':\n            end = u'[%s%s' % (value, self.separator)\n            end = end.encode('utf-8') + b'\\xff'\n        elif filter_type == 'startswith':\n            start = u'[%s' % value\n            end = start.encode('utf-8') + b'\\xff'\n        return start, end, exclude",
    "docstring": "Compute the boundaries to pass to zrangebylex depending of the filter type\n\n        The third return value, ``exclude`` is ``None`` except for the filters\n        `lt` and `gt` because we cannot explicitly exclude it when\n         querying the sorted-set\n\n        For the parameters, see BaseRangeIndex.store\n\n        Notes\n        -----\n        For zrangebylex:\n        - `(` means \"not included\"\n        - `[` means \"included\"\n        - `\\xff` is the last char, it allows to say \"starting with\"\n        - `-` alone means \"from the very beginning\"\n        - `+` alone means \"to the very end\""
  },
  {
    "code": "def get_impala_queries(self, start_time, end_time, filter_str=\"\", limit=100,\n     offset=0):\n    params = {\n      'from':   start_time.isoformat(),\n      'to':     end_time.isoformat(),\n      'filter': filter_str,\n      'limit':  limit,\n      'offset': offset,\n    }\n    return self._get(\"impalaQueries\", ApiImpalaQueryResponse,\n        params=params, api_version=4)",
    "docstring": "Returns a list of queries that satisfy the filter\n\n    @type start_time: datetime.datetime. Note that the datetime must either be\n                      time zone aware or specified in the server time zone. See\n                      the python datetime documentation for more details about\n                      python's time zone handling.\n    @param start_time: Queries must have ended after this time\n    @type end_time: datetime.datetime. Note that the datetime must either be\n                    time zone aware or specified in the server time zone. See\n                    the python datetime documentation for more details about\n                    python's time zone handling.\n    @param end_time: Queries must have started before this time\n    @param filter_str: A filter to apply to the queries. For example:\n                       'user = root and queryDuration > 5s'\n    @param limit: The maximum number of results to return\n    @param offset: The offset into the return list\n    @since: API v4"
  },
  {
    "code": "def unweave(\n    target, advices=None, pointcut=None, ctx=None, depth=1, public=False,\n):\n    if advices is not None:\n        if isroutine(advices):\n            advices = [advices]\n    if pointcut is None or callable(pointcut):\n        pass\n    elif isinstance(pointcut, string_types):\n        pointcut = _namematcher(pointcut)\n    else:\n        error_msg = \"Wrong pointcut to check weaving on {0}.\".format(target)\n        advice_msg = \"Must be None, or be a str or a function/method.\"\n        right_msg = \"Not {0}\".format(type(pointcut))\n        raise AdviceError(\n            \"{0} {1} {2}\".format(error_msg, advice_msg, right_msg)\n        )\n    if ctx is None:\n        ctx = find_ctx(target)\n    _unweave(\n        target=target, advices=advices, pointcut=pointcut,\n        ctx=ctx,\n        depth=depth, depth_predicate=_publiccallable if public else callable\n    )",
    "docstring": "Unweave advices on target with input pointcut.\n\n    :param callable target: target from where checking pointcut and\n        weaving advices.\n\n    :param pointcut: condition for weaving advices on joinpointe.\n        The condition depends on its type.\n    :type pointcut:\n        - NoneType: advices are weaved on target.\n        - str: target name is compared to pointcut regex.\n        - function: called with target in parameter, if True, advices will\n            be weaved on target.\n\n    :param ctx: target ctx (class or instance).\n    :param int depth: class weaving depthing.\n    :param bool public: (default True) weave only on public members\n\n    :return: the intercepted functions created from input target."
  },
  {
    "code": "def decorate(*reversed_views):\n    fns = reversed_views[::-1]\n    view = fns[0]\n    for wrapper in fns[1:]:\n        view = wrapper(view)\n    return view",
    "docstring": "provide a syntax decorating views without nested calls.\n\n    instead of:\n    json_api_call(etag(<hash_fn>)(<view_fn>)))\n\n    you can write:\n    decorate(json_api_call, etag(<hash_fn>), <view_fn>)"
  },
  {
    "code": "def _open(self, skip=0):\n        usb_device = self._get_usb_device(skip)\n        if usb_device:\n            usb_conf = usb_device.configurations[0]\n            self._usb_int = usb_conf.interfaces[0][0]\n        else:\n            raise YubiKeyUSBHIDError('No USB YubiKey found')\n        try:\n            self._usb_handle = usb_device.open()\n            self._usb_handle.detachKernelDriver(0)\n        except Exception as error:\n            if 'could not detach kernel driver from interface' in str(error):\n                self._debug('The in-kernel-HID driver has already been detached\\n')\n            else:\n                self._debug(\"detachKernelDriver not supported!\\n\")\n        try:\n            self._usb_handle.setConfiguration(1)\n        except usb.USBError:\n            self._debug(\"Unable to set configuration, ignoring...\\n\")\n        self._usb_handle.claimInterface(self._usb_int)\n        return True",
    "docstring": "Perform HID initialization"
  },
  {
    "code": "def update_readme_for_modules(modules):\n    readme = parse_readme()\n    module_docstrings = core_module_docstrings()\n    if modules == [\"__all__\"]:\n        modules = core_module_docstrings().keys()\n    for module in modules:\n        if module in module_docstrings:\n            print_stderr(\"Updating README.md for module {}\".format(module))\n            readme[module] = module_docstrings[module]\n        else:\n            print_stderr(\"Module {} not in core modules\".format(module))\n    readme_file = os.path.join(modules_directory(), \"README.md\")\n    with open(readme_file, \"w\") as f:\n        f.write(create_readme(readme))",
    "docstring": "Update README.md updating the sections for the module names listed."
  },
  {
    "code": "async def get_bluetooth_settings(self) -> List[Setting]:\n        bt = await self.services[\"avContent\"][\"getBluetoothSettings\"]({})\n        return [Setting.make(**x) for x in bt]",
    "docstring": "Get bluetooth settings."
  },
  {
    "code": "def run_model(t_output_every, output_dir=None, m=None, force_resume=True,\n              **iterate_args):\n    r = runner.Runner(output_dir, m, force_resume)\n    print(r)\n    r.iterate(t_output_every=t_output_every, **iterate_args)\n    return r",
    "docstring": "Convenience function to combine making a Runner object, and\n    running it for some time.\n\n    Parameters\n    ----------\n    m: Model\n        Model to run.\n    iterate_args:\n        Arguments to pass to :meth:`Runner.iterate`.\n    Others:\n        see :class:`Runner`.\n\n    Returns\n    -------\n    r: Runner\n        runner object after it has finished running for the required time."
  },
  {
    "code": "def paste(location):\n\tcopyData = settings.getDataFile()\n\tif not location:\n\t\tlocation = \".\"\n\ttry:\n\t\tdata = pickle.load(open(copyData, \"rb\"))\n\t\tspeech.speak(\"Pasting \" + data[\"copyLocation\"] + \" to current directory.\")\n\texcept:\n\t\tspeech.fail(\"It doesn't look like you've copied anything yet.\")\n\t\tspeech.fail(\"Type 'hallie copy <file>' to copy a file or folder.\")\n\t\treturn\n\tprocess, error = subprocess.Popen([\"cp\", \"-r\", data[\"copyLocation\"], location], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()\n\tif \"denied\" in process:\n\t\tspeech.fail(\"Unable to paste your file successfully. This is most likely due to a permission issue. You can try to run me as sudo!\")",
    "docstring": "paste a file or directory that has been previously copied"
  },
  {
    "code": "def redis_from_url(url):\n    import redis\n    url = url or \"\"\n    parsed_url = urlparse(url)\n    if parsed_url.scheme != \"redis\":\n        return None\n    kwargs = {}\n    match = PASS_HOST_PORT.match(parsed_url.netloc)\n    if match.group('password') is not None:\n        kwargs['password'] = match.group('password')\n    if match.group('host') is not None:\n        kwargs['host'] = match.group('host')\n    if match.group('port') is not None:\n        kwargs['port'] = int(match.group('port'))\n    if len(parsed_url.path) > 1:\n        kwargs['db'] = int(parsed_url.path[1:])\n    return redis.StrictRedis(**kwargs)",
    "docstring": "Converts a redis URL used by celery into a `redis.Redis` object."
  },
  {
    "code": "def entries(self):\n        return ContentTypeEntriesProxy(self._client, self.space.id, self._environment_id, self.id)",
    "docstring": "Provides access to entry management methods for the given content type.\n\n        API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/entries\n\n        :return: :class:`ContentTypeEntriesProxy <contentful_management.content_type_entries_proxy.ContentTypeEntriesProxy>` object.\n        :rtype: contentful.content_type_entries_proxy.ContentTypeEntriesProxy\n\n        Usage:\n\n            >>> content_type_entries_proxy = content_type.entries()\n            <ContentTypeEntriesProxy space_id=\"cfexampleapi\" environment_id=\"master\" content_type_id=\"cat\">"
  },
  {
    "code": "def forward(self, inputs, lengths):\n        x = self.embedder(inputs)\n        x = self.dropout(x)\n        x = pack_padded_sequence(x, lengths.cpu().numpy(),\n                                 batch_first=self.batch_first)\n        x, _ = self.rnn_layers[0](x)\n        x, _ = pad_packed_sequence(x, batch_first=self.batch_first)\n        x = self.dropout(x)\n        x, _ = self.rnn_layers[1](x)\n        for i in range(2, len(self.rnn_layers)):\n            residual = x\n            x = self.dropout(x)\n            x, _ = self.rnn_layers[i](x)\n            x = x + residual\n        return x",
    "docstring": "Execute the encoder.\n\n        :param inputs: tensor with indices from the vocabulary\n        :param lengths: vector with sequence lengths (excluding padding)\n\n        returns: tensor with encoded sequences"
  },
  {
    "code": "def part(self, *args, **kwargs):\n        _parts = self.parts(*args, **kwargs)\n        if len(_parts) == 0:\n            raise NotFoundError(\"No part fits criteria\")\n        if len(_parts) != 1:\n            raise MultipleFoundError(\"Multiple parts fit criteria\")\n        return _parts[0]",
    "docstring": "Retrieve single KE-chain part.\n\n        Uses the same interface as the :func:`parts` method but returns only a single pykechain :class:`models.Part`\n        instance.\n\n        If additional `keyword=value` arguments are provided, these are added to the request parameters. Please\n        refer to the documentation of the KE-chain API for additional query parameters.\n\n        :return: a single :class:`models.Part`\n        :raises NotFoundError: When no `Part` is found\n        :raises MultipleFoundError: When more than a single `Part` is found"
  },
  {
    "code": "def addPort(n: LNode, intf: Interface):\n    d = PortTypeFromDir(intf._direction)\n    ext_p = LayoutExternalPort(\n        n, name=intf._name, direction=d, node2lnode=n._node2lnode)\n    ext_p.originObj = originObjOfPort(intf)\n    n.children.append(ext_p)\n    addPortToLNode(ext_p, intf, reverseDirection=True)\n    return ext_p",
    "docstring": "Add LayoutExternalPort for interface"
  },
  {
    "code": "def main():\r\n    from spyder.utils.qthelpers import qapplication\r\n    app = qapplication()\r\n    if os.name == 'nt':\r\n        dialog = WinUserEnvDialog()\r\n    else:\r\n        dialog = EnvDialog()\r\n    dialog.show()\r\n    app.exec_()",
    "docstring": "Run Windows environment variable editor"
  },
  {
    "code": "def footprints_from_address(address, distance, footprint_type='building', retain_invalid=False):\n    point = geocode(query=address)\n    return footprints_from_point(point, distance, footprint_type=footprint_type, \n                                 retain_invalid=retain_invalid)",
    "docstring": "Get footprints within some distance north, south, east, and west of\n    an address.\n\n    Parameters\n    ----------\n    address : string\n        the address to geocode to a lat-long point\n    distance : numeric\n        distance in meters\n    footprint_type : string\n        type of footprint to be downloaded. OSM tag key e.g. 'building', 'landuse', 'place', etc.\n    retain_invalid : bool\n        if False discard any footprints with an invalid geometry\n\n    Returns\n    -------\n    GeoDataFrame"
  },
  {
    "code": "def list_repos(self, envs=[], query='/repositories/'):\n        juicer.utils.Log.log_debug(\n                \"List Repos In: %s\", \", \".join(envs))\n        repo_lists = {}\n        for env in envs:\n            repo_lists[env] = []\n        for env in envs:\n            _r = self.connectors[env].get(query)\n            if _r.status_code == Constants.PULP_GET_OK:\n                for repo in juicer.utils.load_json_str(_r.content):\n                    if re.match(\".*-{0}$\".format(env), repo['id']):\n                        repo_lists[env].append(repo['display_name'])\n            else:\n                _r.raise_for_status()\n        return repo_lists",
    "docstring": "List repositories in specified environments"
  },
  {
    "code": "def get_dweets_for(thing_name, key=None, session=None):\n    if key is not None:\n        params = {'key': key}\n    else:\n        params = None\n    return _request('get', '/get/dweets/for/{0}'.format(thing_name), params=params, session=None)",
    "docstring": "Read all the dweets for a dweeter"
  },
  {
    "code": "def map(self, func, *columns):\n        if not columns:\n            return map(func, self.rows)\n        else:\n            values = (self.values(column) for column in columns)\n            result = [map(func, v) for v in values]\n            if len(columns) == 1:\n                return result[0]\n            else:\n                return result",
    "docstring": "Map a function to rows, or to given columns"
  },
  {
    "code": "def set_elapsed_time(self, client):\r\n        related_clients = self.get_related_clients(client)\r\n        for cl in related_clients:\r\n            if cl.timer is not None:\r\n                client.create_time_label()\r\n                client.t0 = cl.t0\r\n                client.timer.timeout.connect(client.show_time)\r\n                client.timer.start(1000)\r\n                break",
    "docstring": "Set elapsed time for slave clients."
  },
  {
    "code": "def get_welcome_response():\n    session_attributes = {}\n    card_title = \"Welcome\"\n    speech_output = \"Welcome to the Alexa Skills Kit sample. \" \\\n                    \"Please tell me your favorite color by saying, \" \\\n                    \"my favorite color is red\"\n    reprompt_text = \"Please tell me your favorite color by saying, \" \\\n                    \"my favorite color is red.\"\n    should_end_session = False\n    return build_response(session_attributes, build_speechlet_response(\n        card_title, speech_output, reprompt_text, should_end_session))",
    "docstring": "If we wanted to initialize the session to have some attributes we could\n    add those here"
  },
  {
    "code": "def extract_ids(text, extractors):\n    for extractor in extractors:\n        for id in extractor.extract(text):\n            yield id",
    "docstring": "Uses `extractors` to extract citation identifiers from a text.\n\n    :Parameters:\n        text : str\n            The text to process\n        extractors : `list`(`extractor`)\n            A list of extractors to apply to the text\n\n    :Returns:\n        `iterable` -- a generator of extracted identifiers"
  },
  {
    "code": "def render_template(template_name, template_getter=get_app_template):\n    def wrapper(func):\n        template = template_getter(template_name)\n        def _wraped(self, request, context, *args, **kwargs):\n            res = func(self, request, context, *args, **kwargs)\n            if isinstance(res, dict):\n                return template.render(**res)\n            else:\n                return res\n        return _wraped\n    return wrapper",
    "docstring": "Decorator to specify which template to use for Wrapped Views.\n\n    It will return string rendered by specified template and\n    returned dictionary from wrapped views as a context for template.\n    The returned value was not dictionary, it does nothing,\n    just returns the result."
  },
  {
    "code": "def load(self, rule_type, quiet = False):\n        if self.filename and os.path.exists(self.filename):\n            try:\n                with open(self.filename, 'rt') as f:\n                    ruleset = json.load(f)\n                    self.about = ruleset['about'] if 'about' in ruleset else ''\n                    self.rules = {}\n                    for filename in ruleset['rules']:\n                        self.rules[filename] = []\n                        for rule in ruleset['rules'][filename]:\n                            self.handle_rule_versions(filename, rule_type, rule)\n            except Exception as e:\n                printException(e)\n                printError('Error: ruleset file %s contains malformed JSON.' % self.filename)\n                self.rules = []\n                self.about = ''\n        else:\n            self.rules = []\n            if not quiet:\n                printError('Error: the file %s does not exist.' % self.filename)",
    "docstring": "Open a JSON file definiting a ruleset and load it into a Ruleset object\n\n        :param quiet:\n        :return:"
  },
  {
    "code": "def set_widgets(self):\n        if self.parent.aggregation_layer:\n            aggr = self.parent.aggregation_layer.name()\n        else:\n            aggr = self.tr('no aggregation')\n        html = self.tr('Please ensure the following information '\n                       'is correct and press Run.')\n        html += '<br/><table cellspacing=\"4\">'\n        html += ('<tr>'\n                 '  <td><b>%s</b></td><td></td><td>%s</td>'\n                 '</tr><tr>'\n                 '  <td><b>%s</b></td><td></td><td>%s</td>'\n                 '</tr><tr>'\n                 '  <td><b>%s</b></td><td></td><td>%s</td>'\n                 '</tr><tr>'\n                 '  <td colspan=\"3\"></td>'\n                 '</tr>' % (\n                     self.tr('hazard layer').capitalize().replace(\n                         ' ', '&nbsp;'),\n                     self.parent.hazard_layer.name(),\n                     self.tr('exposure layer').capitalize().replace(\n                         ' ', '&nbsp;'),\n                     self.parent.exposure_layer.name(),\n                     self.tr('aggregation layer').capitalize().replace(\n                         ' ', '&nbsp;'), aggr))\n        self.lblSummary.setText(html)",
    "docstring": "Set widgets on the Summary tab."
  },
  {
    "code": "def save(self):\n        \"Saves the state to the state file\"\n        with open(self.state_file, \"w\") as fh:\n            json.dump({\n                \"hosts\": self.hosts,\n                \"stats\": self.stats,\n            }, fh)",
    "docstring": "Saves the state to the state file"
  },
  {
    "code": "def add(self, email):\n        if email not in self._collaborators:\n            self._collaborators[email] = ShareRequestValue.Add\n        self._dirty = True",
    "docstring": "Add a collaborator.\n\n        Args:\n            str : Collaborator email address."
  },
  {
    "code": "def _message(self, request_cls, destination=None, message_id=0,\n                 consent=None, extensions=None, sign=False, sign_prepare=False,\n                 nsprefix=None, sign_alg=None, digest_alg=None, **kwargs):\n        if not message_id:\n            message_id = sid()\n        for key, val in self.message_args(message_id).items():\n            if key not in kwargs:\n                kwargs[key] = val\n        req = request_cls(**kwargs)\n        if destination:\n            req.destination = destination\n        if consent:\n            req.consent = \"true\"\n        if extensions:\n            req.extensions = extensions\n        if nsprefix:\n            req.register_prefix(nsprefix)\n        if self.msg_cb:\n            req = self.msg_cb(req)\n        reqid = req.id\n        if sign:\n            return reqid, self.sign(req, sign_prepare=sign_prepare,\n                                    sign_alg=sign_alg, digest_alg=digest_alg)\n        else:\n            logger.info(\"REQUEST: %s\", req)\n            return reqid, req",
    "docstring": "Some parameters appear in all requests so simplify by doing\n        it in one place\n\n        :param request_cls: The specific request type\n        :param destination: The recipient\n        :param message_id: A message identifier\n        :param consent: Whether the principal have given her consent\n        :param extensions: Possible extensions\n        :param sign: Whether the request should be signed or not.\n        :param sign_prepare: Whether the signature should be prepared or not.\n        :param kwargs: Key word arguments specific to one request type\n        :return: A tuple containing the request ID and an instance of the\n            request_cls"
  },
  {
    "code": "def create_page(slug, post_data):\n        logger.info('Call create Page')\n        if MWiki.get_by_uid(slug):\n            return False\n        title = post_data['title'].strip()\n        if len(title) < 2:\n            return False\n        return MWiki.__create_rec(slug, '2', post_data=post_data)",
    "docstring": "The page would be created with slug."
  },
  {
    "code": "def acquire(self):\n        start_time = time.time()\n        while True:\n            try:\n                self.fd = os.open(self.lockfile,\n                                  os.O_CREAT | os.O_EXCL | os.O_RDWR)\n                break\n            except (OSError,) as e:\n                if e.errno != errno.EEXIST:\n                    raise\n                if (time.time() - start_time) >= self.timeout:\n                    raise FileLockException(\"%s: Timeout occured.\" %\n                                            self.lockfile)\n                time.sleep(self.delay)\n        self.is_locked = True",
    "docstring": "Acquire the lock, if possible. If the lock is in use, it check again\n        every `delay` seconds. It does this until it either gets the lock or\n        exceeds `timeout` number of seconds, in which case it throws\n        an exception."
  },
  {
    "code": "def _terminate(self):\n        def generate_body():\n            d = defer.succeed(None)\n            d.addBoth(defer.drop_param, self.agent.shutdown_agent)\n            d.addBoth(lambda _: self.delete_document(self._descriptor))\n            return d\n        return self._terminate_procedure(generate_body)",
    "docstring": "Shutdown agent gently removing the descriptor and\n        notifying partners."
  },
  {
    "code": "def replace_in_files(search, replace, depth=0, paths=None, confirm=True):\n    if paths==None:\n        paths = _s.dialogs.MultipleFiles('DIS AND DAT|*.*')\n    if paths == []: return\n    for path in paths:\n        lines = read_lines(path)\n        if depth: N=min(len(lines),depth)\n        else:     N=len(lines)\n        for n in range(0,N):\n            if lines[n].find(search) >= 0:\n                lines[n] = lines[n].replace(search,replace)\n                print(path.split(_os.path.pathsep)[-1]+ ': \"'+lines[n]+'\"')\n        if not confirm:\n            _os.rename(path, path+\".backup\")\n            write_to_file(path, join(lines, ''))\n    if confirm:\n        if input(\"yes? \")==\"yes\":\n            replace_in_files(search,replace,depth,paths,False)\n    return",
    "docstring": "Does a line-by-line search and replace, but only up to the \"depth\" line."
  },
  {
    "code": "def cache_property(key, empty, type):\n    return property(lambda x: x._get_cache_value(key, empty, type),\n                    lambda x, v: x._set_cache_value(key, v, type),\n                    lambda x: x._del_cache_value(key),\n                    'accessor for %r' % key)",
    "docstring": "Return a new property object for a cache header.  Useful if you\n    want to add support for a cache extension in a subclass."
  },
  {
    "code": "def send_email(self, msg, tag=None):\n        try:\n            return self._send_email(msg, tag)\n        except:\n            self.exceptions.append(straceback())\n            return -2",
    "docstring": "Send an e-mail before completing the shutdown.\n        Returns 0 if success."
  },
  {
    "code": "def clean_readme(fname):\n    with codecs.open(fname, 'r', 'utf-8') as f:\n        return ''.join(\n            re.sub(r':\\w+:`([^`]+?)( <[^<>]+>)?`', r'``\\1``', line)\n            for line in f\n            if not (line.startswith('.. currentmodule') or line.startswith('.. toctree'))\n        )",
    "docstring": "Cleanup README.rst for proper PyPI formatting."
  },
  {
    "code": "def appendAnchor(self, name=None, position=None, color=None, anchor=None):\n        identifier = None\n        if anchor is not None:\n            anchor = normalizers.normalizeAnchor(anchor)\n            if name is None:\n                name = anchor.name\n            if position is None:\n                position = anchor.position\n            if color is None:\n                color = anchor.color\n            if anchor.identifier is not None:\n                existing = set([a.identifier for a in self.anchors if a.identifier is not None])\n                if anchor.identifier not in existing:\n                    identifier = anchor.identifier\n        name = normalizers.normalizeAnchorName(name)\n        position = normalizers.normalizeCoordinateTuple(position)\n        if color is not None:\n            color = normalizers.normalizeColor(color)\n        identifier = normalizers.normalizeIdentifier(identifier)\n        return self._appendAnchor(name, position=position, color=color, identifier=identifier)",
    "docstring": "Append an anchor to this glyph.\n\n            >>> anchor = glyph.appendAnchor(\"top\", (10, 20))\n\n        This will return a :class:`BaseAnchor` object representing\n        the new anchor in the glyph. ``name`` indicated the name to\n        be assigned to the anchor. It must be a :ref:`type-string`\n        or ``None``. ``position`` indicates the x and y location\n        to be applied to the anchor. It must be a\n        :ref:`type-coordinate` value. ``color`` indicates the color\n        to be applied to the anchor. It must be a :ref:`type-color`\n        or ``None``.\n\n            >>> anchor = glyph.appendAnchor(\"top\", (10, 20), color=(1, 0, 0, 1))\n\n        ``anchor`` may be a :class:`BaseAnchor` object from which\n        attribute values will be copied. If ``name``, ``position``\n        or ``color`` are specified as arguments, those values will\n        be used instead of the values in the given anchor object."
  },
  {
    "code": "def _removepkg(self, package):\n        try:\n            subprocess.call(\"removepkg {0} {1}\".format(self.flag, package),\n                            shell=True)\n            if os.path.isfile(self.dep_path + package):\n                os.remove(self.dep_path + package)\n        except subprocess.CalledProcessError as er:\n            print(er)\n            raise SystemExit()",
    "docstring": "removepkg Slackware command"
  },
  {
    "code": "def kill(self, id, signal=signal.SIGTERM):\n        args = {\n            'id': id,\n            'signal': int(signal),\n        }\n        self._kill_chk.check(args)\n        return self._client.json('job.kill', args)",
    "docstring": "Kill a job with given id\n\n        :WARNING: beware of what u kill, if u killed redis for example core0 or coreX won't be reachable\n\n        :param id: job id to kill"
  },
  {
    "code": "def get_all_nodes(self, addr, is_syscall=None, anyaddr=False):\n        results = [ ]\n        for cfg_node in self.graph.nodes():\n            if cfg_node.addr == addr or (anyaddr and\n                                         cfg_node.size is not None and\n                                         cfg_node.addr <= addr < (cfg_node.addr + cfg_node.size)\n                                         ):\n                if is_syscall and cfg_node.is_syscall:\n                    results.append(cfg_node)\n                elif is_syscall is False and not cfg_node.is_syscall:\n                    results.append(cfg_node)\n                else:\n                    results.append(cfg_node)\n        return results",
    "docstring": "Get all CFGNodes whose address is the specified one.\n\n        :param addr:       Address of the node\n        :param is_syscall: True returns the syscall node, False returns the normal CFGNode, None returns both\n        :return:           all CFGNodes"
  },
  {
    "code": "def get_remote_chassis_id_mac(self, tlv_data):\n        ret, parsed_val = self._check_common_tlv_format(\n            tlv_data, \"MAC:\", \"Chassis ID TLV\")\n        if not ret:\n            return None\n        mac = parsed_val[1].split('\\n')\n        return mac[0].strip()",
    "docstring": "Returns Remote Chassis ID MAC from the TLV."
  },
  {
    "code": "def to_dict(self):\n        ret = merge_dicts(self.__attributes__, self.__relations__, self.__fields__)\n        ret = {k : v.value for k,v in ret.items()}\n        ret['maps'] = {k : v.value for k,v in self.maps.items()}\n        return ret",
    "docstring": "Return a dict representing the ChemicalEntity that can be read back\n        using from_dict."
  },
  {
    "code": "def all_props(self):\n        d = self.arg_props\n        d.update(self.props)\n        return d",
    "docstring": "Return a dictionary with the values of all children, and place holders for all of the section\n        argumemts. It combines props and arg_props"
  },
  {
    "code": "def is_transition_matrix(T, tol=1e-12):\n    r\n    T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric')\n    if _issparse(T):\n        return sparse.assessment.is_transition_matrix(T, tol)\n    else:\n        return dense.assessment.is_transition_matrix(T, tol)",
    "docstring": "r\"\"\"Check if the given matrix is a transition matrix.\n\n    Parameters\n    ----------\n    T : (M, M) ndarray or scipy.sparse matrix\n        Matrix to check\n    tol : float (optional)\n        Floating point tolerance to check with\n\n    Returns\n    -------\n    is_transition_matrix : bool\n        True, if T is a valid transition matrix, False otherwise\n\n    Notes\n    -----\n    A valid transition matrix :math:`P=(p_{ij})` has non-negative\n    elements, :math:`p_{ij} \\geq 0`, and elements of each row sum up\n    to one, :math:`\\sum_j p_{ij} = 1`. Matrices wit this property are\n    also called stochastic matrices.\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> from msmtools.analysis import is_transition_matrix\n\n    >>> A = np.array([[0.4, 0.5, 0.3], [0.2, 0.4, 0.4], [-1, 1, 1]])\n    >>> is_transition_matrix(A)\n    False\n\n    >>> T = np.array([[0.9, 0.1, 0.0], [0.5, 0.0, 0.5], [0.0, 0.1, 0.9]])\n    >>> is_transition_matrix(T)\n    True"
  },
  {
    "code": "def _error_is_decreasing(self, last_error):\n        current_error = self._compute_error()\n        is_decreasing = current_error < last_error\n        return is_decreasing, current_error",
    "docstring": "True if current error is less than last_error."
  },
  {
    "code": "def transform(self, trajs_tuple, y=None):\n        return [self.partial_transform(traj_zip)\n                for traj_zip in zip(*trajs_tuple)]",
    "docstring": "Featurize a several trajectories.\n\n        Parameters\n        ----------\n        traj_list : list(mdtraj.Trajectory)\n            Trajectories to be featurized.\n\n        Returns\n        -------\n        features : list(np.ndarray), length = len(traj_list)\n            The featurized trajectories.  features[i] is the featurized\n            version of traj_list[i] and has shape\n            (n_samples_i, n_features)"
  },
  {
    "code": "def is_merge_origin(self):\n        if self.gridSpan > 1 and not self.vMerge:\n            return True\n        if self.rowSpan > 1 and not self.hMerge:\n            return True\n        return False",
    "docstring": "True if cell is top-left in merged cell range."
  },
  {
    "code": "def __wrap_with_tuple(self) -> tuple:\n        l = list()\n        length = len(self.data)\n        while self.idx < length:\n            l.append(self.__parse())\n        return tuple(l)",
    "docstring": "Returns a tuple of all nested bencode elements."
  },
  {
    "code": "def get_feature_subset(self, subset_idx):\n        subset_idx = np.asarray(subset_idx)\n        if not (max(subset_idx) < self.__num_features) and (min(subset_idx) >= 0):\n            raise UnboundLocalError('indices out of range for the dataset. '\n                                    'Max index: {} Min index : 0'.format(\n                self.__num_features))\n        sub_data = {sample: features[subset_idx] for sample, features in\n                    self.__data.items()}\n        new_descr = 'Subset features derived from: \\n ' + self.__description\n        subdataset = MLDataset(data=sub_data,\n                               labels=self.__labels, classes=self.__classes,\n                               description=new_descr,\n                               feature_names=self.__feature_names[subset_idx])\n        return subdataset",
    "docstring": "Returns the subset of features indexed numerically.\n\n        Parameters\n        ----------\n        subset_idx : list, ndarray\n            List of indices to features to be returned\n\n        Returns\n        -------\n        MLDataset : MLDataset\n            with subset of features requested.\n\n        Raises\n        ------\n        UnboundLocalError\n            If input indices are out of bounds for the dataset."
  },
  {
    "code": "def LengthMeters(self):\n    assert(len(self._points) > 0)\n    length = 0\n    for i in range(0, len(self._points) - 1):\n      length += self._points[i].GetDistanceMeters(self._points[i+1])\n    return length",
    "docstring": "Return length of this polyline in meters."
  },
  {
    "code": "def dedent_block_string_value(raw_string: str) -> str:\n    lines = raw_string.splitlines()\n    common_indent = None\n    for line in lines[1:]:\n        indent = leading_whitespace(line)\n        if indent < len(line) and (common_indent is None or indent < common_indent):\n            common_indent = indent\n        if common_indent == 0:\n            break\n    if common_indent:\n        lines[1:] = [line[common_indent:] for line in lines[1:]]\n    while lines and not lines[0].strip():\n        lines = lines[1:]\n    while lines and not lines[-1].strip():\n        lines = lines[:-1]\n    return \"\\n\".join(lines)",
    "docstring": "Produce the value of a block string from its parsed raw value.\n\n    Similar to CoffeeScript's block string, Python's docstring trim or Ruby's\n    strip_heredoc.\n\n    This implements the GraphQL spec's BlockStringValue() static algorithm."
  },
  {
    "code": "def _gate_name(self, gate):\n        try:\n            name = gate.tex_str()\n        except AttributeError:\n            name = str(gate)\n        return name",
    "docstring": "Return the string representation of the gate.\n\n        Tries to use gate.tex_str and, if that is not available, uses str(gate)\n        instead.\n\n        :param string gate: Gate object of which to get the name / LaTeX representation.\n        :return: LaTeX gate name.\n        :rtype: string"
  },
  {
    "code": "def _add_to_dict(t, container, name, value):\n    if name in container:\n        raise Exception(\"%s '%s' already exists\" % (t, name))\n    else:\n        container[name] = value",
    "docstring": "Adds an item to a dictionary, or raises an exception if an item with the\n    specified key already exists in the dictionary."
  },
  {
    "code": "def run(self, executable: Executable,\n            memory_map: Dict[str, List[Union[int, float]]] = None) -> np.ndarray:\n        self.qam.load(executable)\n        if memory_map:\n            for region_name, values_list in memory_map.items():\n                for offset, value in enumerate(values_list):\n                    self.qam.write_memory(region_name=region_name, offset=offset, value=value)\n        return self.qam.run() \\\n            .wait() \\\n            .read_memory(region_name='ro')",
    "docstring": "Run a quil executable. If the executable contains declared parameters, then a memory\n        map must be provided, which defines the runtime values of these parameters.\n\n        :param executable: The program to run. You are responsible for compiling this first.\n        :param memory_map: The mapping of declared parameters to their values. The values\n            are a list of floats or integers.\n        :return: A numpy array of shape (trials, len(ro-register)) that contains 0s and 1s."
  },
  {
    "code": "def repeat(self, repeats, *args, **kwargs):\n        nv.validate_repeat(args, kwargs)\n        values = self._data.repeat(repeats)\n        return type(self)(values.view('i8'), dtype=self.dtype)",
    "docstring": "Repeat elements of an array.\n\n        See Also\n        --------\n        numpy.ndarray.repeat"
  },
  {
    "code": "def identifier_md5(self):\n        as_int = (self.identifier * 1e4).astype(np.int64)\n        hashed = util.md5_object(as_int.tostring(order='C'))\n        return hashed",
    "docstring": "Return an MD5 of the identifier"
  },
  {
    "code": "def parse_host(entity, default_port=DEFAULT_PORT):\n    host = entity\n    port = default_port\n    if entity[0] == '[':\n        host, port = parse_ipv6_literal_host(entity, default_port)\n    elif entity.endswith(\".sock\"):\n        return entity, default_port\n    elif entity.find(':') != -1:\n        if entity.count(':') > 1:\n            raise ValueError(\"Reserved characters such as ':' must be \"\n                             \"escaped according RFC 2396. An IPv6 \"\n                             \"address literal must be enclosed in '[' \"\n                             \"and ']' according to RFC 2732.\")\n        host, port = host.split(':', 1)\n    if isinstance(port, string_type):\n        if not port.isdigit() or int(port) > 65535 or int(port) <= 0:\n            raise ValueError(\"Port must be an integer between 0 and 65535: %s\"\n                             % (port,))\n        port = int(port)\n    return host.lower(), port",
    "docstring": "Validates a host string\n\n    Returns a 2-tuple of host followed by port where port is default_port\n    if it wasn't specified in the string.\n\n    :Parameters:\n        - `entity`: A host or host:port string where host could be a\n                    hostname or IP address.\n        - `default_port`: The port number to use when one wasn't\n                          specified in entity."
  },
  {
    "code": "def execute_request(conn, classname, max_open, max_pull):\n    start = ElapsedTimer()\n    result = conn.OpenEnumerateInstances(classname,\n                                         MaxObjectCount=max_open)\n    print('open rtn eos=%s context=%s, count=%s time=%s ms' %\n          (result.eos, result.context, len(result.instances),\n           start.elapsed_ms()))\n    insts = result.instances\n    pull_count = 0\n    while not result.eos:\n        pull_count += 1\n        op_start = ElapsedTimer()\n        result = conn.PullInstancesWithPath(result.context,\n                                            MaxObjectCount=max_pull)\n        insts.extend(result.instances)\n        print('pull rtn eos=%s context=%s, insts=%s time=%s ms' %\n              (result.eos, result.context, len(result.instances),\n               op_start.elapsed_ms()))\n    print('Result instance count=%s pull count=%s time=%.2f sec' % \\\n          (len(insts), pull_count, start.elapsed_sec()))\n    return insts",
    "docstring": "Enumerate instances defined by the function's\n        classname argument using the OpenEnumerateInstances and\n        PullInstancesWithPath.\n\n        * classname - Classname for the enumeration.\n\n        * max_open - defines the maximum number of instances\n          for the server to return for the open\n\n        *max_pull defines the maximum number of instances for the\n          WBEM server to return for each pull operation.\n\n        Displays results of each open or pull operation including\n        size, return parameters, and time to execute.\n\n        Any exception exits the function."
  },
  {
    "code": "def use(wcspkg, raise_err=True):\n    global coord_types, wcs_configured, WCS\n    if wcspkg not in common.custom_wcs:\n        modname = 'wcs_%s' % (wcspkg)\n        path = os.path.join(wcs_home, '%s.py' % (modname))\n        try:\n            my_import(modname, path)\n        except ImportError:\n            return False\n    if wcspkg in common.custom_wcs:\n        bnch = common.custom_wcs[wcspkg]\n        WCS = bnch.wrapper_class\n        coord_types = bnch.coord_types\n        wcs_configured = True\n        return True\n    return False",
    "docstring": "Choose WCS package."
  },
  {
    "code": "def normalize(self) -> 'State':\n        tensor = self.tensor / bk.ccast(bk.sqrt(self.norm()))\n        return State(tensor, self.qubits, self._memory)",
    "docstring": "Normalize the state"
  },
  {
    "code": "def base64url_decode(input):\n    rem = len(input) % 4\n    if rem > 0:\n        input += b'=' * (4 - rem)\n    return base64.urlsafe_b64decode(input)",
    "docstring": "Helper method to base64url_decode a string.\n\n    Args:\n        input (str): A base64url_encoded string to decode."
  },
  {
    "code": "def get_coord_line_number(self,coord):\n    if coord[0] in self._coords:\n      if coord[1] in self._coords[coord[0]]:\n        return self._coords[coord[0]][coord[1]]\n    return None",
    "docstring": "return the one-indexed line number given the coordinates"
  },
  {
    "code": "def serialize(self, value, **kwargs):\n        if types.Type.is_type(self.attr_type):\n            try:\n                value = self.accessor.get(value, **kwargs)\n            except (AttributeError, KeyError):\n                if not hasattr(self, \"default\") and self.required:\n                    raise\n                value = self.default() if callable(self.default) else self.default\n            return self.attr_type.serialize(value, **_get_context(self._attr_type_serialize_argspec, kwargs))\n        return self.attr_type",
    "docstring": "Serialize the attribute of the input data.\n\n        Gets the attribute value with accessor and converts it using the\n        type serialization. Schema will place this serialized value into\n        corresponding compartment of the HAL structure with the name of the\n        attribute as a key.\n\n        :param value: Value to get the attribute value from.\n        :return: Serialized attribute value."
  },
  {
    "code": "def log_transform(rates):\n    transformed = []\n    for key in ['missense', 'nonsense', 'splice_lof', 'splice_region',\n            'synonymous']:\n        try:\n            value = math.log10(rates[key])\n        except ValueError:\n            value = \"NA\"\n        except KeyError:\n            continue\n        transformed.append(value)\n    return '\\t'.join(map(str, transformed))",
    "docstring": "log transform a numeric value, unless it is zero, or negative"
  },
  {
    "code": "def stayOpen(self):\r\n        if not self._wantToClose:\r\n            self.show()\r\n            self.setGeometry(self._geometry)",
    "docstring": "optional dialog restore"
  },
  {
    "code": "def get_val_by_text(root,search):\n    found_flag = False\n    for el in root.iter():\n        if found_flag:\n            return(el)\n        if el.text == search:\n            found_flag = True",
    "docstring": "From MeasYaps XML root find next sibling of node matching 'search'.\n\n    MeasYaps looks like:\n    <value>Key</value>\n    <value>Value</value>\n    Thus 'search' is the Key and we want to find the node that has the Value.\n    We return the node containing the desired Value.\n\n    Arguments:\n    root            (Element) root XML node (xml.etree.ElementTree Element)\n\n    search          (String) String to match Element.text"
  },
  {
    "code": "def group_citation_edges(edges: Iterable[EdgeTuple]) -> Iterable[Tuple[str, Iterable[EdgeTuple]]]:\n    return itt.groupby(edges, key=_citation_sort_key)",
    "docstring": "Return an iterator over pairs of citation values and their corresponding edge iterators."
  },
  {
    "code": "def weld_filter(array, weld_type, bool_array):\n    obj_id, weld_obj = create_weld_object(array)\n    bool_obj_id = get_weld_obj_id(weld_obj, bool_array)\n    weld_template =\n    weld_obj.weld_code = weld_template.format(array=obj_id,\n                                              bool_array=bool_obj_id,\n                                              type=weld_type)\n    return weld_obj",
    "docstring": "Returns a new array only with the elements with a corresponding True in bool_array.\n\n    Parameters\n    ----------\n    array : numpy.ndarray or WeldObject\n        Input data.\n    weld_type : WeldType\n        Type of the elements in the input array.\n    bool_array : numpy.ndarray or WeldObject\n        Array of bool with True for elements in array desired in the result array.\n\n    Returns\n    -------\n    WeldObject\n        Representation of this computation."
  },
  {
    "code": "def mark_running(self):\n    with self._lock:\n      self._set_state(self._RUNNING, self._PAUSED)",
    "docstring": "Moves the service to the Running state.\n\n    Raises if the service is not currently in the Paused state."
  },
  {
    "code": "def readline(self, size=-1):\n        if self.closed:\n            raise ValueError(\"I/O operation on closed file\")\n        pos = self.buffer.find(b\"\\n\") + 1\n        if pos == 0:\n            while True:\n                buf = self.fileobj.read(self.blocksize)\n                self.buffer += buf\n                if not buf or b\"\\n\" in buf:\n                    pos = self.buffer.find(b\"\\n\") + 1\n                    if pos == 0:\n                        pos = len(self.buffer)\n                    break\n        if size != -1:\n            pos = min(size, pos)\n        buf = self.buffer[:pos]\n        self.buffer = self.buffer[pos:]\n        self.position += len(buf)\n        return buf",
    "docstring": "Read one entire line from the file. If size is present\n           and non-negative, return a string with at most that\n           size, which may be an incomplete line."
  },
  {
    "code": "def runContainer(image, **kwargs):\n    container = None\n    try:\n        container = client.containers.run(image, **kwargs)\n        if \"name\" in kwargs.keys():\n          print(\"Container\", kwargs[\"name\"], \"is now running.\")\n    except ContainerError as exc:\n        eprint(\"Failed to run container\")\n        raise exc\n    except ImageNotFound as exc:\n        eprint(\"Failed to find image to run as a docker container\")\n        raise exc\n    except APIError as exc:\n        eprint(\"Unhandled error\")\n        raise exc\n    return container",
    "docstring": "Run a docker container using a given image; passing keyword arguments\n    documented to be accepted by docker's client.containers.run function\n    No extra side effects. Handles and reraises ContainerError, ImageNotFound,\n    and APIError exceptions."
  },
  {
    "code": "def get_instance(self, payload):\n        return WorkerChannelInstance(\n            self._version,\n            payload,\n            workspace_sid=self._solution['workspace_sid'],\n            worker_sid=self._solution['worker_sid'],\n        )",
    "docstring": "Build an instance of WorkerChannelInstance\n\n        :param dict payload: Payload response from the API\n\n        :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance\n        :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelInstance"
  },
  {
    "code": "def load(cls, path, name):\n        filepath = aux.joinpath(path, name + '.proteindb')\n        with zipfile.ZipFile(filepath, 'r', allowZip64=True) as containerZip:\n            proteinsString = io.TextIOWrapper(containerZip.open('proteins'),\n                                              encoding='utf-8'\n                                              ).read()\n            peptidesString = io.TextIOWrapper(containerZip.open('peptides'),\n                                              encoding='utf-8'\n                                              ).read()\n            infoString = io.TextIOWrapper(containerZip.open('info'),\n                                          encoding='utf-8'\n                                          ).read()\n        newInstance = cls()\n        newInstance.proteins = json.loads(proteinsString,\n                                          object_hook=ProteinSequence.jsonHook)\n        newInstance.peptides = json.loads(peptidesString,\n                                          object_hook=PeptideSequence.jsonHook)\n        newInstance.info.update(json.loads(infoString))\n        return newInstance",
    "docstring": "Imports the specified ``proteindb`` file from the hard disk.\n\n        :param path: filedirectory of the ``proteindb`` file\n        :param name: filename without the file extension \".proteindb\"\n\n        .. note:: this generates rather large files, which actually take longer\n            to import than to newly generate. Maybe saving / loading should be\n            limited to the protein database whitout in silico digestion\n            information."
  },
  {
    "code": "def tangent_lineation_plot(ax, strikes, dips, rakes):\n    rake_x, rake_y = mplstereonet.rake(strikes, dips, rakes)\n    mag = np.hypot(rake_x, rake_y)\n    u, v = -rake_x / mag, -rake_y / mag\n    pole_x, pole_y = mplstereonet.pole(strikes, dips)\n    arrows = ax.quiver(pole_x, pole_y, u, v, width=1, headwidth=4, units='dots',\n                       pivot='middle')\n    return arrows",
    "docstring": "Makes a tangent lineation plot for normal faults with the given strikes,\n    dips, and rakes."
  },
  {
    "code": "def directed_tripartition(seq):\n    for a, b, c in directed_tripartition_indices(len(seq)):\n        yield (tuple(seq[i] for i in a),\n               tuple(seq[j] for j in b),\n               tuple(seq[k] for k in c))",
    "docstring": "Generator over all directed tripartitions of a sequence.\n\n    Args:\n        seq (Iterable): a sequence.\n\n    Yields:\n        tuple[tuple]: A tripartition of ``seq``.\n\n    Example:\n        >>> seq = (2, 5)\n        >>> list(directed_tripartition(seq))  # doctest: +NORMALIZE_WHITESPACE\n        [((2, 5), (), ()),\n         ((2,), (5,), ()),\n         ((2,), (), (5,)),\n         ((5,), (2,), ()),\n         ((), (2, 5), ()),\n         ((), (2,), (5,)),\n         ((5,), (), (2,)),\n         ((), (5,), (2,)),\n         ((), (), (2, 5))]"
  },
  {
    "code": "def create_domain(provider, context, **kwargs):\n    session = get_session(provider.region)\n    client = session.client(\"route53\")\n    domain = kwargs.get(\"domain\")\n    if not domain:\n        logger.error(\"domain argument or BaseDomain variable not provided.\")\n        return False\n    zone_id = create_route53_zone(client, domain)\n    return {\"domain\": domain, \"zone_id\": zone_id}",
    "docstring": "Create a domain within route53.\n\n    Args:\n        provider (:class:`stacker.providers.base.BaseProvider`): provider\n            instance\n        context (:class:`stacker.context.Context`): context instance\n\n    Returns: boolean for whether or not the hook succeeded."
  },
  {
    "code": "def decode_cert(cert):\n    ret_dict = {}\n    subject_xname = X509_get_subject_name(cert.value)\n    ret_dict[\"subject\"] = _create_tuple_for_X509_NAME(subject_xname)\n    notAfter = X509_get_notAfter(cert.value)\n    ret_dict[\"notAfter\"] = ASN1_TIME_print(notAfter)\n    peer_alt_names = _get_peer_alt_names(cert)\n    if peer_alt_names is not None:\n        ret_dict[\"subjectAltName\"] = peer_alt_names\n    return ret_dict",
    "docstring": "Convert an X509 certificate into a Python dictionary\n\n    This function converts the given X509 certificate into a Python dictionary\n    in the manner established by the Python standard library's ssl module."
  },
  {
    "code": "def run_suite(case, config, summary):\n    m = _load_case_module(case, config)\n    result = m.run(case, config)\n    summary[case] = _summarize_result(m, result)\n    _print_summary(m, case, summary)\n    if result['Type'] == 'Book':\n        for name, page in six.iteritems(result['Data']):\n            functions.create_page_from_template(\"validation.html\",\n                                                os.path.join(livvkit.index_dir, \"validation\", name + \".html\"))\n            functions.write_json(page, os.path.join(livvkit.output_dir, \"validation\"), name + \".json\")\n    else:\n        functions.create_page_from_template(\"validation.html\",\n                                            os.path.join(livvkit.index_dir, \"validation\", case + \".html\"))\n        functions.write_json(result, os.path.join(livvkit.output_dir, \"validation\"), case + \".json\")",
    "docstring": "Run the full suite of validation tests"
  },
  {
    "code": "def _dscl(cmd, ctype='create'):\n    if __grains__['osrelease_info'] < (10, 8):\n        source, noderoot = '.', ''\n    else:\n        source, noderoot = 'localhost', '/Local/Default'\n    if noderoot:\n        cmd[0] = noderoot + cmd[0]\n    return __salt__['cmd.run_all'](\n        ['dscl', source, '-' + ctype] + cmd,\n        output_loglevel='quiet' if ctype == 'passwd' else 'debug',\n        python_shell=False\n    )",
    "docstring": "Run a dscl -create command"
  },
  {
    "code": "def parse_netloc(scheme, netloc):\n    auth, _netloc = netloc.split('@')\n    sender, token = auth.split(':')\n    if ':' in _netloc:\n        domain, port = _netloc.split(':')\n        port = int(port)\n    else:\n        domain = _netloc\n        if scheme == 'https':\n            port = 443\n        else:\n            port = 80\n    return dict(sender=sender, token=token, domain=domain, port=port)",
    "docstring": "Parse netloc string."
  },
  {
    "code": "def inflate(deflated_vector):\n    dv = json.loads(deflated_vector)\n    result = np.zeros(5555)\n    for n in dv['indices']:\n        result[int(n)] = dv['indices'][n]\n    return result",
    "docstring": "Given a defalated vector, inflate it into a np array and return it"
  },
  {
    "code": "def check_git():\n    try:\n        with open(os.devnull, \"wb\") as devnull:\n            subprocess.check_call([\"git\", \"--version\"], stdout=devnull, stderr=devnull)\n    except:\n        raise RuntimeError(\"Please make sure git is installed and on your path.\")",
    "docstring": "Check if git command is available."
  },
  {
    "code": "def _factorize_from_iterables(iterables):\n    if len(iterables) == 0:\n        return [[], []]\n    return map(list, lzip(*[_factorize_from_iterable(it) for it in iterables]))",
    "docstring": "A higher-level wrapper over `_factorize_from_iterable`.\n\n    *This is an internal function*\n\n    Parameters\n    ----------\n    iterables : list-like of list-likes\n\n    Returns\n    -------\n    codes_list : list of ndarrays\n    categories_list : list of Indexes\n\n    Notes\n    -----\n    See `_factorize_from_iterable` for more info."
  },
  {
    "code": "def sleep(self, unique_id, delay, configs=None):\n    self.pause(unique_id, configs)\n    time.sleep(delay)\n    self.resume(unique_id, configs)",
    "docstring": "Pauses the process for the specified delay and then resumes it\n\n    :Parameter unique_id: the name of the process\n    :Parameter delay: delay time in seconds"
  },
  {
    "code": "def ext_publish(self, instance, loop, *args, **kwargs):\n        if self.external_signaller is not None:\n            return self.external_signaller.publish_signal(self, instance, loop,\n                                                          args, kwargs)",
    "docstring": "If 'external_signaller' is defined, calls it's publish method to\n        notify external event systems.\n\n        This is for internal usage only, but it's doumented because it's part\n        of the interface with external notification systems."
  },
  {
    "code": "def load_suite_from_stdin(self):\n        suite = unittest.TestSuite()\n        rules = Rules(\"stream\", suite)\n        line_generator = self._parser.parse_stdin()\n        return self._load_lines(\"stream\", line_generator, suite, rules)",
    "docstring": "Load a test suite with test lines from the TAP stream on STDIN.\n\n        :returns: A ``unittest.TestSuite`` instance"
  },
  {
    "code": "def GetEntries(self, parser_mediator, match=None, **unused_kwargs):\n    if 'RememberedNetworks' not in match:\n      return\n    for wifi in match['RememberedNetworks']:\n      ssid = wifi.get('SSIDString', 'UNKNOWN_SSID')\n      security_type = wifi.get('SecurityType', 'UNKNOWN_SECURITY_TYPE')\n      event_data = plist_event.PlistTimeEventData()\n      event_data.desc = (\n          '[WiFi] Connected to network: <{0:s}> using security {1:s}').format(\n              ssid, security_type)\n      event_data.key = 'item'\n      event_data.root = '/RememberedNetworks'\n      datetime_value = wifi.get('LastConnected', None)\n      if datetime_value:\n        event = time_events.PythonDatetimeEvent(\n            datetime_value, definitions.TIME_DESCRIPTION_WRITTEN)\n      else:\n        date_time = dfdatetime_semantic_time.SemanticTime('Not set')\n        event = time_events.DateTimeValuesEvent(\n            date_time, definitions.TIME_DESCRIPTION_NOT_A_TIME)\n      parser_mediator.ProduceEventWithEventData(event, event_data)",
    "docstring": "Extracts relevant Airport entries.\n\n    Args:\n      parser_mediator (ParserMediator): mediates interactions between parsers\n          and other components, such as storage and dfvfs.\n      match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS."
  },
  {
    "code": "def main():\n    try:\n        command = sys.argv[1]\n    except IndexError:\n        return error_message()\n    try:\n        module = importlib.import_module('i18n.%s' % command)\n        module.main.args = sys.argv[2:]\n    except (ImportError, AttributeError):\n        return error_message()\n    return module.main()",
    "docstring": "Executes the given command. Returns error_message if command is not valid.\n\n    Returns:\n        Output of the given command or error message if command is not valid."
  },
  {
    "code": "def abort (aggregate):\n    while True:\n        try:\n            aggregate.abort()\n            aggregate.finish()\n            aggregate.end_log_output(interrupt=True)\n            break\n        except KeyboardInterrupt:\n            log.warn(LOG_CHECK, _(\"user abort; force shutdown\"))\n            aggregate.end_log_output(interrupt=True)\n            abort_now()",
    "docstring": "Helper function to ensure a clean shutdown."
  },
  {
    "code": "def ned2geodetic(n: float, e: float, d: float,\n                 lat0: float, lon0: float, h0: float,\n                 ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]:\n    x, y, z = enu2ecef(e, n, -d, lat0, lon0, h0, ell, deg=deg)\n    return ecef2geodetic(x, y, z, ell, deg=deg)",
    "docstring": "Converts North, East, Down to target latitude, longitude, altitude\n\n    Parameters\n    ----------\n\n    n : float or numpy.ndarray of float\n        North NED coordinate (meters)\n    e : float or numpy.ndarray of float\n        East NED coordinate (meters)\n    d : float or numpy.ndarray of float\n        Down NED coordinate (meters)\n    lat0 : float\n        Observer geodetic latitude\n    lon0 : float\n        Observer geodetic longitude\n    h0 : float\n         observer altitude above geodetic ellipsoid (meters)\n    ell : Ellipsoid, optional\n          reference ellipsoid\n    deg : bool, optional\n          degrees input/output  (False: radians in/out)\n\n    Results\n    -------\n\n    lat : float\n        target geodetic latitude\n    lon : float\n        target geodetic longitude\n    h : float\n        target altitude above geodetic ellipsoid (meters)"
  },
  {
    "code": "def configure(self, sbi_config: str):\n        config_dict = json.loads(sbi_config)\n        self.debug_stream('SBI configuration:\\n%s',\n                          json.dumps(config_dict, indent=2))\n        try:\n            sbi = Subarray(self.get_name()).configure_sbi(config_dict)\n        except jsonschema.exceptions.ValidationError as error:\n            return json.dumps(dict(path=error.absolute_path.__str__(),\n                                   schema_path=error.schema_path.__str__(),\n                                   message=error.message), indent=2)\n        except RuntimeError as error:\n            return json.dumps(dict(error=str(error)), indent=2)\n        return 'Accepted SBI: {}'.format(sbi.id)",
    "docstring": "Configure an SBI for this subarray.\n\n        Args:\n            sbi_config (str): SBI configuration JSON\n\n        Returns:\n            str,"
  },
  {
    "code": "def get_marshmallow_schema_name(self, plugin, schema):\n        try:\n            return plugin.openapi.refs[schema]\n        except KeyError:\n            plugin.spec.definition(schema.__name__, schema=schema)\n            return schema.__name__",
    "docstring": "Get the schema name.\n\n        If the schema doesn't exist, create it."
  },
  {
    "code": "def listen(self):\n        import select\n        while self.connected:\n            r, w, e = select.select((self.ws.sock, ), (), ())\n            if r:\n                self.on_message()\n            elif e:\n                self.subscriber.on_sock_error(e)\n        self.disconnect()",
    "docstring": "Set up a quick connection. Returns on disconnect.\n\n        After calling `connect()`, this waits for messages from the server\n        using `select`, and notifies the subscriber of any events."
  },
  {
    "code": "def update_index(self, name, value):\n        kwargs = {}\n        kwargs['index.' + name] = value if isinstance(value, basestring) else json.dumps(value)\n        return self.post(**kwargs)",
    "docstring": "Changes the definition of a KV Store index.\n\n        :param name: name of index to change\n        :type name: ``string``\n        :param value: new index definition\n        :type value: ``dict`` or ``string``\n\n        :return: Result of POST request"
  },
  {
    "code": "def Sample(self, tasks_status):\n    sample_time = time.time()\n    sample = '{0:f}\\t{1:d}\\t{2:d}\\t{3:d}\\t{4:d}\\t{5:d}\\n'.format(\n        sample_time, tasks_status.number_of_queued_tasks,\n        tasks_status.number_of_tasks_processing,\n        tasks_status.number_of_tasks_pending_merge,\n        tasks_status.number_of_abandoned_tasks,\n        tasks_status.total_number_of_tasks)\n    self._WritesString(sample)",
    "docstring": "Takes a sample of the status of queued tasks for profiling.\n\n    Args:\n      tasks_status (TasksStatus): status information about tasks."
  },
  {
    "code": "def load(config_path: str):\n    if os.path.splitext(config_path)[1] in ('.yaml', '.yml'):\n        _ = load_yaml_configuration(config_path, translator=PipelineTranslator())\n    elif os.path.splitext(config_path)[1] == '.py':\n        _ = load_python_configuration(config_path)\n    else:\n        raise ValueError('Unknown configuration extension: %r' % os.path.splitext(config_path)[1])\n    yield",
    "docstring": "Load a configuration and keep it alive for the given context\n\n    :param config_path: path to a configuration file"
  },
  {
    "code": "def _deserialize(x, elementType, compress, relicReadBinFunc):\n    b = (c_ubyte*len(x))(*bytearray(x))\n    flag = c_int(compress)\n    result = elementType()\n    relicReadBinFunc(byref(result), byref(b), len(x), flag)\n    return result",
    "docstring": "Deserializes a bytearray @x, into an @element of the correct type,\n    using the a relic read_bin function and the specified @compressed flag.\n    This is the underlying implementation for deserialize G1, G2, and Gt."
  },
  {
    "code": "def _reset(self):\n        with self._lock:\n            self.stop()\n            self.start()\n            for svc_ref in self.get_bindings():\n                if not self.requirement.filter.matches(\n                    svc_ref.get_properties()\n                ):\n                    self.on_service_departure(svc_ref)",
    "docstring": "Called when the filter has been changed"
  },
  {
    "code": "def find_key_by_email(self, email, secret=False):\n        for key in self.list_keys(secret=secret):\n            for uid in key['uids']:\n                if re.search(email, uid):\n                    return key\n        raise LookupError(\"GnuPG public key for email %s not found!\" % email)",
    "docstring": "Find user's key based on their email address.\n\n        :param str email: The email address to search for.\n        :param bool secret: If True, search through secret keyring."
  },
  {
    "code": "def _fire_ipopo_event(self, kind, factory_name, instance_name=None):\n        with self.__listeners_lock:\n            listeners = self.__listeners[:]\n        for listener in listeners:\n            try:\n                listener.handle_ipopo_event(\n                    constants.IPopoEvent(kind, factory_name, instance_name)\n                )\n            except:\n                _logger.exception(\"Error calling an iPOPO event handler\")",
    "docstring": "Triggers an iPOPO event\n\n        :param kind: Kind of event\n        :param factory_name: Name of the factory associated to the event\n        :param instance_name: Name of the component instance associated to the\n                              event"
  },
  {
    "code": "def load(theTask, canExecute=True, strict=True, defaults=False):\n    return teal(theTask, parent=None, loadOnly=True, returnAs=\"dict\",\n                canExecute=canExecute, strict=strict, errorsToTerm=True,\n                defaults=defaults)",
    "docstring": "Shortcut to load TEAL .cfg files for non-GUI access where\n    loadOnly=True."
  },
  {
    "code": "def OSXEnumerateRunningServicesFromClient(args):\n  del args\n  osx_version = client_utils_osx.OSXVersion()\n  version_array = osx_version.VersionAsMajorMinor()\n  if version_array[:2] < [10, 6]:\n    raise UnsupportedOSVersionError(\n        \"ServiceManagement API unsupported on < 10.6. This client is %s\" %\n        osx_version.VersionString())\n  launchd_list = GetRunningLaunchDaemons()\n  parser = osx_launchd.OSXLaunchdJobDict(launchd_list)\n  for job in parser.Parse():\n    response = CreateServiceProto(job)\n    yield response",
    "docstring": "Get running launchd jobs.\n\n  Args:\n    args: Unused.\n\n  Yields:\n    `rdf_client.OSXServiceInformation` instances.\n\n  Raises:\n      UnsupportedOSVersionError: for OS X earlier than 10.6."
  },
  {
    "code": "def listdir(self, name, **kwargs):\n        assert self._is_s3(name), \"name must be in form s3://bucket/prefix/\"\n        if not name.endswith('/'):\n            name += \"/\"\n        return self.list(name, delimiter='/', **kwargs)",
    "docstring": "Returns a list of the files under the specified path.\n\n        This is different from list as it will only give you files under the\n        current directory, much like ls.\n\n        name must be in the form of `s3://bucket/prefix/`\n\n        Parameters\n        ----------\n        keys: optional\n            if True then this will return the actual boto keys for files\n            that are encountered\n        objects: optional\n            if True then this will return the actual boto objects for\n            files or prefixes that are encountered"
  },
  {
    "code": "def load(self):\n        self._validate()\n        self._logger.logging_load()\n        self.encoding = get_file_encoding(self.source, self.encoding)\n        with io.open(self.source, \"r\", encoding=self.encoding) as fp:\n            formatter = MediaWikiTableFormatter(fp.read())\n        formatter.accept(self)\n        return formatter.to_table_data()",
    "docstring": "Extract tabular data as |TableData| instances from a MediaWiki file.\n        |load_source_desc_file|\n\n        :return:\n            Loaded table data iterator.\n            |load_table_name_desc|\n\n            ===================  ==============================================\n            Format specifier     Value after the replacement\n            ===================  ==============================================\n            ``%(filename)s``     |filename_desc|\n            ``%(key)s``          | This replaced to:\n                                 | **(1)** ``caption`` mark of the table\n                                 | **(2)** ``%(format_name)s%(format_id)s``\n                                 | if ``caption`` mark not included\n                                 | in the table.\n            ``%(format_name)s``  ``\"mediawiki\"``\n            ``%(format_id)s``    |format_id_desc|\n            ``%(global_id)s``    |global_id|\n            ===================  ==============================================\n        :rtype: |TableData| iterator\n        :raises pytablereader.DataError:\n            If the MediaWiki data is invalid or empty."
  },
  {
    "code": "def request(self, source=\"candidate\"):\n        node = new_ele(\"validate\")\n        if type(source) is str:\n            src = util.datastore_or_url(\"source\", source, self._assert)\n        else:\n            validated_element(source, (\"config\", qualify(\"config\")))\n            src = new_ele(\"source\")\n            src.append(source)\n        node.append(src)\n        return self._request(node)",
    "docstring": "Validate the contents of the specified configuration.\n\n        *source* is the name of the configuration datastore being validated or `config` element containing the configuration subtree to be validated\n\n        :seealso: :ref:`srctarget_params`"
  },
  {
    "code": "def random_val(index, tune_params):\n    key = list(tune_params.keys())[index]\n    return random.choice(tune_params[key])",
    "docstring": "return a random value for a parameter"
  },
  {
    "code": "def lower_coerce_type_block_type_data(ir_blocks, type_equivalence_hints):\n    allowed_key_type_spec = (GraphQLInterfaceType, GraphQLObjectType)\n    allowed_value_type_spec = GraphQLUnionType\n    for key, value in six.iteritems(type_equivalence_hints):\n        if (not isinstance(key, allowed_key_type_spec) or\n                not isinstance(value, allowed_value_type_spec)):\n            msg = (u'Invalid type equivalence hints received! Hint {} ({}) -> {} ({}) '\n                   u'was unexpected, expected a hint in the form '\n                   u'GraphQLInterfaceType -> GraphQLUnionType or '\n                   u'GraphQLObjectType -> GraphQLUnionType'.format(key.name, str(type(key)),\n                                                                   value.name, str(type(value))))\n            raise GraphQLCompilationError(msg)\n    equivalent_type_names = {\n        key.name: {x.name for x in value.types}\n        for key, value in six.iteritems(type_equivalence_hints)\n    }\n    new_ir_blocks = []\n    for block in ir_blocks:\n        new_block = block\n        if isinstance(block, CoerceType):\n            target_class = get_only_element_from_collection(block.target_class)\n            if target_class in equivalent_type_names:\n                new_block = CoerceType(equivalent_type_names[target_class])\n        new_ir_blocks.append(new_block)\n    return new_ir_blocks",
    "docstring": "Rewrite CoerceType blocks to explicitly state which types are allowed in the coercion."
  },
  {
    "code": "def _register_callback(cnx, tag_prefix, obj, event, real_id):\n    libvirt_name = real_id\n    if real_id is None:\n        libvirt_name = 'VIR_{0}_EVENT_ID_{1}'.format(obj, event).upper()\n    if not hasattr(libvirt, libvirt_name):\n        log.warning('Skipping \"%s/%s\" events: libvirt too old', obj, event)\n        return None\n    libvirt_id = getattr(libvirt, libvirt_name)\n    callback_name = \"_{0}_event_{1}_cb\".format(obj, event)\n    callback = globals().get(callback_name, None)\n    if callback is None:\n        log.error('Missing function %s in engine', callback_name)\n        return None\n    register = getattr(cnx, REGISTER_FUNCTIONS[obj])\n    return register(None, libvirt_id, callback,\n                    {'prefix': tag_prefix,\n                     'object': obj,\n                     'event': event})",
    "docstring": "Helper function registering a callback\n\n    :param cnx: libvirt connection\n    :param tag_prefix: salt event tag prefix to use\n    :param obj: the libvirt object name for the event. Needs to\n                be one of the REGISTER_FUNCTIONS keys.\n    :param event: the event type name.\n    :param real_id: the libvirt name of an alternative event id to use or None\n\n    :rtype integer value needed to deregister the callback"
  },
  {
    "code": "def _cnf_formula(lexer, varname, nvars, nclauses):\n    clauses = _clauses(lexer, varname, nvars)\n    if len(clauses) < nclauses:\n        fstr = \"formula has fewer than {} clauses\"\n        raise Error(fstr.format(nclauses))\n    if len(clauses) > nclauses:\n        fstr = \"formula has more than {} clauses\"\n        raise Error(fstr.format(nclauses))\n    return ('and', ) + clauses",
    "docstring": "Return a DIMACS CNF formula."
  },
  {
    "code": "def reset_actions(self):\n        if self._driver.w3c:\n            self.w3c_actions.clear_actions()\n        self._actions = []",
    "docstring": "Clears actions that are already stored locally and on the remote end"
  },
  {
    "code": "def register_app(self, app=None):\n        app = app or self.options['DEFAULT_APP']\n        if not app:\n            raise ImproperlyConfigured('An app name is required because DEFAULT_APP is empty - please use a '\n                                        'valid app name or set the DEFAULT_APP in settings')\n        if isinstance(app, str):\n            app = apps.get_app_config(app)\n        with self.registration_lock:\n            if app.name in self.registered_apps:\n                return\n            self.registered_apps[app.name] = app\n            self.engine.get_template_loader(app, 'templates', create=True)\n            self.engine.get_template_loader(app, 'scripts', create=True)\n            self.engine.get_template_loader(app, 'styles', create=True)\n            if self.options['SIGNALS']:\n                dmp_signal_register_app.send(sender=self, app_config=app)",
    "docstring": "Registers an app as a \"DMP-enabled\" app.  Normally, DMP does this\n        automatically when included in urls.py.\n\n        If app is None, the DEFAULT_APP is registered."
  },
  {
    "code": "def getfields(comm):\n    fields = []\n    for field in comm:\n        if 'field' in field:\n            fields.append(field)\n    return fields",
    "docstring": "get all the fields that have the key 'field'"
  },
  {
    "code": "def _check_aligned_header(self, data_type, unit):\n        if data_type is not None:\n            assert isinstance(data_type, DataTypeBase), \\\n                'data_type must be a Ladybug DataType. Got {}'.format(type(data_type))\n            if unit is None:\n                unit = data_type.units[0]\n        else:\n            data_type = self.header.data_type\n            unit = unit or self.header.unit\n        return Header(data_type, unit, self.header.analysis_period, self.header.metadata)",
    "docstring": "Check the header inputs whenever get_aligned_collection is called."
  },
  {
    "code": "def get_fk_popup_field(cls, *args, **kwargs):\n        kwargs['popup_name'] = cls.get_class_verbose_name()\n        kwargs['permissions_required'] = cls.permissions_required\n        if cls.template_name_fk is not None:\n            kwargs['template_name'] = cls.template_name_fk\n        return ForeignKeyWidget('{}_popup_create'.format(cls.get_class_name()), *args, **kwargs)",
    "docstring": "generate fk field related to class wait popup crud"
  },
  {
    "code": "def read_plain_int64(file_obj, count):\n    return struct.unpack(\"<{}q\".format(count).encode(\"utf-8\"), file_obj.read(8 * count))",
    "docstring": "Read `count` 64-bit ints using the plain encoding."
  },
  {
    "code": "def get_dir(path_name, *, greedy=False, override=None, identity=None):\n    if identity is None:\n        identity = identify(path_name, override=override)\n    path_name = os.path.normpath(path_name)\n    if greedy and identity == ISDIR:\n        return path_name\n    else:\n        return os.path.dirname(path_name)",
    "docstring": "Gets the directory path of the given path name. If the argument 'greedy'\n    is specified as True, then if the path name represents a directory itself,\n    the function will return the whole path"
  },
  {
    "code": "def get_deploy_data(self):\n        if self.state and self.state.deploy_data:\n            return self.state.deploy_data\n        return {}",
    "docstring": "Gets any default data attached to the current deploy, if any."
  },
  {
    "code": "def create_sphere_around_elec(xyz, template_mri, distance=8, freesurfer=None):\n    if freesurfer is None:\n        shift = 0\n    else:\n        shift = freesurfer.surface_ras_shift\n    if isinstance(template_mri, str) or isinstance(template_mri, Path):\n        template_mri = nload(str(template_mri))\n    mask = zeros(template_mri.shape, dtype='bool')\n    for vox in ndindex(template_mri.shape):\n        vox_ras = apply_affine(template_mri.affine, vox) - shift\n        if norm(xyz - vox_ras) <= distance:\n            mask[vox] = True\n    return mask",
    "docstring": "Create an MRI mask around an electrode location,\n\n    Parameters\n    ----------\n    xyz : ndarray\n        3x0 array\n    template_mri : path or str (as path) or nibabel.Nifti\n        (path to) MRI to be used as template\n    distance : float\n        distance in mm between electrode and selected voxels\n    freesurfer : instance of Freesurfer\n        to adjust RAS coordinates, see Notes\n\n    Returns\n    -------\n    3d bool ndarray\n        mask where True voxels are within selected distance to the electrode\n\n    Notes\n    -----\n    Freesurfer uses two coordinate systems: one for volumes (\"RAS\") and one for\n    surfaces (\"tkReg\", \"tkRAS\", and \"Surface RAS\"), so the electrodes might be\n    stored in one of the two systems. If the electrodes are in surface\n    coordinates (f.e. if you can plot surface and electrodes in the same space),\n    then you need to convert the coordinate system. This is done by passing an\n    instance of Freesurfer."
  },
  {
    "code": "def _sync_notes(self, notes_json):\n        for note_json in notes_json:\n            note_id = note_json['id']\n            task_id = note_json['item_id']\n            if task_id not in self.tasks:\n                continue\n            task = self.tasks[task_id]\n            self.notes[note_id] = Note(note_json, task)",
    "docstring": "Populate the user's notes from a JSON encoded list."
  },
  {
    "code": "def ctcp(self, target, message, nowait=False):\n        if target and message:\n            messages = utils.split_message(message, self.config.max_length)\n            f = None\n            for message in messages:\n                f = self.send_line('PRIVMSG %s :\\x01%s\\x01' % (target,\n                                                               message),\n                                   nowait=nowait)\n            return f",
    "docstring": "send a ctcp to target"
  },
  {
    "code": "def get_ecf_props(ep_id, ep_id_ns, rsvc_id=None, ep_ts=None):\n    results = {}\n    if not ep_id:\n        raise ArgumentError(\"ep_id\", \"ep_id must be a valid endpoint id\")\n    results[ECF_ENDPOINT_ID] = ep_id\n    if not ep_id_ns:\n        raise ArgumentError(\"ep_id_ns\", \"ep_id_ns must be a valid namespace\")\n    results[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = ep_id_ns\n    if not rsvc_id:\n        rsvc_id = get_next_rsid()\n    results[ECF_RSVC_ID] = rsvc_id\n    if not ep_ts:\n        ep_ts = time_since_epoch()\n    results[ECF_ENDPOINT_TIMESTAMP] = ep_ts\n    return results",
    "docstring": "Prepares the ECF properties\n\n    :param ep_id: Endpoint ID\n    :param ep_id_ns: Namespace of the Endpoint ID\n    :param rsvc_id: Remote service ID\n    :param ep_ts: Timestamp of the endpoint\n    :return: A dictionary of ECF properties"
  },
  {
    "code": "def get_data_from_request():\n    return {\n        'request': {\n            'url': '%s://%s%s' % (web.ctx['protocol'], web.ctx['host'], web.ctx['path']),\n            'query_string': web.ctx.query,\n            'method': web.ctx.method,\n            'data': web.data(),\n            'headers': dict(get_headers(web.ctx.environ)),\n            'env': dict(get_environ(web.ctx.environ)),\n        }\n    }",
    "docstring": "Returns request data extracted from web.ctx."
  },
  {
    "code": "def parametrized_unbottleneck(x, hidden_size, hparams):\n  if hparams.bottleneck_kind == \"tanh_discrete\":\n    return tanh_discrete_unbottleneck(x, hidden_size)\n  if hparams.bottleneck_kind == \"isemhash\":\n    return isemhash_unbottleneck(x, hidden_size,\n                                 hparams.isemhash_filter_size_multiplier)\n  if hparams.bottleneck_kind in [\"vq\", \"em\", \"gumbel_softmax\"]:\n    return vq_discrete_unbottleneck(x, hidden_size)\n  raise ValueError(\n      \"Unsupported hparams.bottleneck_kind %s\" % hparams.bottleneck_kind)",
    "docstring": "Meta-function calling all the above un-bottlenecks with hparams."
  },
  {
    "code": "def predict(self, mllib_data):\n        if isinstance(mllib_data, pyspark.mllib.linalg.Matrix):\n            return to_matrix(self._master_network.predict(from_matrix(mllib_data)))\n        elif isinstance(mllib_data, pyspark.mllib.linalg.Vector):\n            return to_vector(self._master_network.predict(from_vector(mllib_data)))\n        else:\n            raise ValueError(\n                'Provide either an MLLib matrix or vector, got {}'.format(mllib_data.__name__))",
    "docstring": "Predict probabilities for an RDD of features"
  },
  {
    "code": "def drop_field(app_name, model_name, field_name):\n    app_config = apps.get_app_config(app_name)\n    model = app_config.get_model(model_name)\n    field = model._meta.get_field(field_name)\n    with connection.schema_editor() as schema_editor:\n        schema_editor.remove_field(model, field)",
    "docstring": "Drop the given field from the app's model"
  },
  {
    "code": "def _glob_pjoin(*parts):\n    if parts[0] in ('.', ''):\n        parts = parts[1:]\n    return pjoin(*parts).replace(os.sep, '/')",
    "docstring": "Join paths for glob processing"
  },
  {
    "code": "def _add_missing_routes(route_spec, failed_ips, questionable_ips,\n                        chosen_routers, vpc_info, con, routes_in_rts):\n    for dcidr, hosts in route_spec.items():\n        new_router_ip = chosen_routers.get(dcidr)\n        for rt_id, dcidr_list in routes_in_rts.items():\n            if dcidr not in dcidr_list:\n                if not new_router_ip:\n                    new_router_ip = _choose_different_host(None, hosts,\n                                                           failed_ips,\n                                                           questionable_ips)\n                    if not new_router_ip:\n                        logging.warning(\"--- cannot find available target \"\n                                        \"for route addition %s! \"\n                                        \"Nothing I can do...\" % (dcidr))\n                        break\n                _add_new_route(dcidr, new_router_ip, vpc_info, con, rt_id)",
    "docstring": "Iterate over route spec and add all the routes we haven't set yet.\n\n    This relies on being told what routes we HAVE already. This is passed\n    in via the routes_in_rts dict.\n\n    Furthermore, some routes may be set in some RTs, but not in others. In that\n    case, we may already have seen which router was chosen for a certain route.\n    This information is passed in via the chosen_routers dict. We should choose\n    routers that were used before."
  },
  {
    "code": "def sanity_check_insdcio(handle, id_marker, fake_id_line):\n    found_id = False\n    found_end_marker = False\n    for line in handle:\n        line = line.strip()\n        if not line:\n            continue\n        if line.startswith(id_marker):\n            found_id = True\n            break\n        if line.startswith('//'):\n            found_end_marker = True\n            break\n    handle.seek(0)\n    if found_id:\n        return handle\n    if not found_end_marker:\n        return handle\n    new_handle = StringIO()\n    new_handle.write(\"%s\\n\" % fake_id_line)\n    new_handle.write(handle.read())\n    new_handle.seek(0)\n    return new_handle",
    "docstring": "Sanity check for insdcio style files"
  },
  {
    "code": "def publish_and_get_event(self, resource):\n        l_subscribed = False\n        this_event = None\n        if not self.__subscribed:\n            self._get_event_stream()\n            self._subscribe_myself()\n            l_subscribed = True\n        status = self.publish(\n            action='get',\n            resource=resource,\n            mode=None,\n            publish_response=False)\n        if status == 'success':\n            i = 0\n            while not this_event and i < 2:\n                self.__event_handle.wait(5.0)\n                self.__event_handle.clear()\n                _LOGGER.debug(\"Instance %s resource: %s\", str(i), resource)\n                for event in self.__events:\n                    if event['resource'] == resource:\n                        this_event = event\n                        self.__events.remove(event)\n                        break\n                i = i + 1\n        if l_subscribed:\n            self._unsubscribe_myself()\n            self._close_event_stream()\n            l_subscribed = False\n        return this_event",
    "docstring": "Publish and get the event from base station."
  },
  {
    "code": "def fail_connection(self, code: int = 1006, reason: str = \"\") -> None:\n        logger.debug(\n            \"%s ! failing %s WebSocket connection with code %d\",\n            self.side,\n            self.state.name,\n            code,\n        )\n        if hasattr(self, \"transfer_data_task\"):\n            self.transfer_data_task.cancel()\n        if code != 1006 and self.state is State.OPEN:\n            frame_data = serialize_close(code, reason)\n            self.state = State.CLOSING\n            logger.debug(\"%s - state = CLOSING\", self.side)\n            frame = Frame(True, OP_CLOSE, frame_data)\n            logger.debug(\"%s > %r\", self.side, frame)\n            frame.write(\n                self.writer.write, mask=self.is_client, extensions=self.extensions\n            )\n        if not hasattr(self, \"close_connection_task\"):\n            self.close_connection_task = self.loop.create_task(self.close_connection())",
    "docstring": "7.1.7. Fail the WebSocket Connection\n\n        This requires:\n\n        1. Stopping all processing of incoming data, which means cancelling\n           :attr:`transfer_data_task`. The close code will be 1006 unless a\n           close frame was received earlier.\n\n        2. Sending a close frame with an appropriate code if the opening\n           handshake succeeded and the other side is likely to process it.\n\n        3. Closing the connection. :meth:`close_connection` takes care of\n           this once :attr:`transfer_data_task` exits after being canceled.\n\n        (The specification describes these steps in the opposite order.)"
  },
  {
    "code": "def reflect_image(image, axis=None, tx=None, metric='mattes'):\n    if axis is None:\n        axis = image.dimension - 1\n    if (axis > image.dimension) or (axis < 0):\n        axis = image.dimension - 1\n    rflct = mktemp(suffix='.mat')\n    libfn = utils.get_lib_fn('reflectionMatrix%s'%image._libsuffix)\n    libfn(image.pointer, axis, rflct)\n    if tx is not None:\n        rfi = registration(image, image, type_of_transform=tx,\n                            syn_metric=metric, outprefix=mktemp(),\n                            initial_transform=rflct)\n        return rfi\n    else:\n        return apply_transforms(image, image, rflct)",
    "docstring": "Reflect an image along an axis\n\n    ANTsR function: `reflectImage`\n\n    Arguments\n    ---------\n    image : ANTsImage\n        image to reflect\n    \n    axis : integer (optional)\n        which dimension to reflect across, numbered from 0 to imageDimension-1\n    \n    tx : string (optional)\n        transformation type to estimate after reflection\n    \n    metric : string  \n        similarity metric for image registration. see antsRegistration.\n    \n    Returns\n    -------\n    ANTsImage\n\n    Example\n    -------\n    >>> import ants\n    >>> fi = ants.image_read( ants.get_ants_data('r16'), 'float' )\n    >>> axis = 2\n    >>> asym = ants.reflect_image(fi, axis, 'Affine')['warpedmovout']\n    >>> asym = asym - fi"
  },
  {
    "code": "def expected_peer_units():\n    if not has_juju_version(\"2.4.0\"):\n        raise NotImplementedError(\"goal-state\")\n    _goal_state = goal_state()\n    return (key for key in _goal_state['units']\n            if '/' in key and key != local_unit())",
    "docstring": "Get a generator for units we expect to join peer relation based on\n    goal-state.\n\n    The local unit is excluded from the result to make it easy to gauge\n    completion of all peers joining the relation with existing hook tools.\n\n    Example usage:\n    log('peer {} of {} joined peer relation'\n        .format(len(related_units()),\n                len(list(expected_peer_units()))))\n\n    This function will raise NotImplementedError if used with juju versions\n    without goal-state support.\n\n    :returns: iterator\n    :rtype: types.GeneratorType\n    :raises: NotImplementedError"
  },
  {
    "code": "def from_wif_or_ewif_file(path: str, password: Optional[str] = None) -> SigningKeyType:\n        with open(path, 'r') as fh:\n            wif_content = fh.read()\n        regex = compile('Data: ([1-9A-HJ-NP-Za-km-z]+)', MULTILINE)\n        match = search(regex, wif_content)\n        if not match:\n            raise Exception('Error: Bad format WIF or EWIF v1 file')\n        wif_hex = match.groups()[0]\n        return SigningKey.from_wif_or_ewif_hex(wif_hex, password)",
    "docstring": "Return SigningKey instance from Duniter WIF or EWIF file\n\n        :param path: Path to WIF of EWIF file\n        :param password: Password needed for EWIF file"
  },
  {
    "code": "def delete(self, key):\n        self._get_table()\n        self.table.delete_item(key=key)\n        log.debug(\"Deleted item at key '%s'\" % (key))",
    "docstring": "If this key exists, delete it"
  },
  {
    "code": "def clean(self):\n        result = super(User, self).clean()\n        result['verified'] = 'verification_hash' not in self._resource\n        return result",
    "docstring": "Verified value is derived from whether user has a verification hash"
  },
  {
    "code": "def set_image(self, image):\n        imwidth, imheight = image.size\n        if imwidth != 8 or imheight != 16:\n            raise ValueError('Image must be an 8x16 pixels in size.')\n        pix = image.convert('1').load()\n        for x in xrange(8):\n            for y in xrange(16):\n                color = pix[(x, y)]\n                if color == 0:\n                    self.set_pixel(x, y, 0)\n                else:\n                    self.set_pixel(x, y, 1)",
    "docstring": "Set display buffer to Python Image Library image.  Image will be converted\n        to 1 bit color and non-zero color values will light the LEDs."
  },
  {
    "code": "def info(gandi, resource):\n    output_keys = ['ip', 'state', 'dc', 'type', 'vm', 'reverse']\n    datacenters = gandi.datacenter.list()\n    ip = gandi.ip.info(resource)\n    iface = gandi.iface.info(ip['iface_id'])\n    vms = None\n    if iface.get('vm_id'):\n        vm = gandi.iaas.info(iface['vm_id'])\n        vms = {vm['id']: vm}\n    output_ip(gandi, ip, datacenters, vms, {iface['id']: iface},\n              output_keys)\n    return ip",
    "docstring": "Display information about an ip.\n\n    Resource can be an ip or id."
  },
  {
    "code": "def get_tilt(cont):\n    if isinstance(cont, np.ndarray):\n        cont = [cont]\n        ret_list = False\n    else:\n        ret_list = True\n    length = len(cont)\n    tilt = np.zeros(length, dtype=float) * np.nan\n    for ii in range(length):\n        moments = cont_moments_cv(cont[ii])\n        if moments is not None:\n            oii = 0.5 * np.arctan2(2 * moments['mu11'],\n                                   moments['mu02'] - moments['mu20'])\n            tilt[ii] = oii + np.pi/2\n    tilt = np.mod(tilt, np.pi)\n    tilt[tilt > np.pi/2] -= np.pi\n    tilt = np.abs(tilt)\n    if not ret_list:\n        tilt = tilt[0]\n    return tilt",
    "docstring": "Compute tilt of raw contour relative to channel axis\n\n    Parameters\n    ----------\n    cont: ndarray or list of ndarrays of shape (N,2)\n        A 2D array that holds the contour of an event (in pixels)\n        e.g. obtained using `mm.contour` where  `mm` is an instance\n        of `RTDCBase`. The first and second columns of `cont`\n        correspond to the x- and y-coordinates of the contour.\n\n    Returns\n    -------\n    tilt: float or ndarray of size N\n        Tilt of the contour in the interval [0, PI/2]\n\n    References\n    ----------\n    - `<https://en.wikipedia.org/wiki/Image_moment#Examples_2>`__"
  },
  {
    "code": "def create_scraper(cls, sess=None, **kwargs):\n        scraper = cls(**kwargs)\n        if sess:\n            attrs = [\"auth\", \"cert\", \"cookies\", \"headers\", \"hooks\", \"params\", \"proxies\", \"data\"]\n            for attr in attrs:\n                val = getattr(sess, attr, None)\n                if val:\n                    setattr(scraper, attr, val)\n        return scraper",
    "docstring": "Convenience function for creating a ready-to-go CloudflareScraper object."
  },
  {
    "code": "def transform_conf_module(cls):\n  global CONF_NODE\n  if cls.name == 'openhtf.conf':\n    cls._locals.update(cls.locals['Configuration'][0].locals)\n    CONF_NODE = cls\n    CONF_LOCALS.update(cls.locals)",
    "docstring": "Transform usages of the conf module by updating locals."
  },
  {
    "code": "def length(self, t0=0, t1=1, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH):\n        assert 0 <= t0 <= 1 and 0 <= t1 <= 1\n        if _quad_available:\n            return quad(lambda tau: abs(self.derivative(tau)), t0, t1,\n                        epsabs=error, limit=1000)[0]\n        else:\n            return segment_length(self, t0, t1, self.point(t0), self.point(t1),\n                                  error, min_depth, 0)",
    "docstring": "The length of an elliptical large_arc segment requires numerical\n        integration, and in that case it's simpler to just do a geometric\n        approximation, as for cubic bezier curves."
  },
  {
    "code": "def getValueByName(node, name):\n    try:\n        value = node.xpath(\"*[local-name() = '%s']\" % name)[0].text.strip()\n    except:\n        return None\n    return value",
    "docstring": "A helper function to pull the values out of those annoying namespace\n    prefixed tags"
  },
  {
    "code": "def encode_id_header(resource):\n    if not hasattr(resource, \"id\"):\n        return {}\n    return {\n        \"X-{}-Id\".format(\n            camelize(name_for(resource))\n        ): str(resource.id),\n    }",
    "docstring": "Generate a header for a newly created resource.\n\n    Assume `id` attribute convention."
  },
  {
    "code": "def mk_fmtfld(nt_item, joinchr=\" \", eol=\"\\n\"):\n    fldstrs = []\n    fld2fmt = {\n        'hdrgo' : lambda f: \"{{{FLD}:1,}}\".format(FLD=f),\n        'dcnt' : lambda f: \"{{{FLD}:6,}}\".format(FLD=f),\n        'level' : lambda f: \"L{{{FLD}:02,}}\".format(FLD=f),\n        'depth' : lambda f: \"D{{{FLD}:02,}}\".format(FLD=f),\n    }\n    for fld in nt_item._fields:\n        if fld in fld2fmt:\n            val = fld2fmt[fld](fld)\n        else:\n            val = \"{{{FLD}}}\".format(FLD=fld)\n        fldstrs.append(val)\n    return \"{LINE}{EOL}\".format(LINE=joinchr.join(fldstrs), EOL=eol)",
    "docstring": "Given a namedtuple, return a format_field string."
  },
  {
    "code": "def namespace(self):\n        if self.prefix is None:\n            return Namespace.default\n        else:\n            return self.resolvePrefix(self.prefix)",
    "docstring": "Get the attributes namespace.  This may either be the namespace\n        defined by an optional prefix, or its parent's namespace.\n        @return: The attribute's namespace\n        @rtype: (I{prefix}, I{name})"
  },
  {
    "code": "def _writeString(self, obj, use_reference=True):\n        string = to_bytes(obj, \"utf-8\")\n        if use_reference and isinstance(obj, JavaString):\n            try:\n                idx = self.references.index(obj)\n            except ValueError:\n                self.references.append(obj)\n                logging.debug(\n                    \"*** Adding ref 0x%X for string: %s\",\n                    len(self.references) - 1 + self.BASE_REFERENCE_IDX,\n                    obj,\n                )\n                self._writeStruct(\">H\", 2, (len(string),))\n                self.object_stream.write(string)\n            else:\n                logging.debug(\n                    \"*** Reusing ref 0x%X for string: %s\",\n                    idx + self.BASE_REFERENCE_IDX,\n                    obj,\n                )\n                self.write_reference(idx)\n        else:\n            self._writeStruct(\">H\", 2, (len(string),))\n            self.object_stream.write(string)",
    "docstring": "Appends a string to the serialization stream\n\n        :param obj: String to serialize\n        :param use_reference: If True, allow writing a reference"
  },
  {
    "code": "def registerHandler(self, fh):\n        self.fds.add(fh)\n        self.atime = int(time())\n        self.lock.acquire()\n        try:\n            if (0, self.filesize) not in self.avail and self.preferences['stream'] is False:\n                Downloader.fetch(self, None, fh)\n        except requests.exceptions.ConnectionError:\n            raise ConnectionError\n        finally:\n            self.lock.release()",
    "docstring": "Register new file descriptor.\n\n        Parameters\n        ----------\n        fh : int\n            File descriptor."
  },
  {
    "code": "def get_and_write_raw(self, url: str, filename: str) -> None:\n        self.write_raw(self.get_raw(url), filename)",
    "docstring": "Downloads and writes anonymously-requested raw data into a file.\n\n        :raises QueryReturnedNotFoundException: When the server responds with a 404.\n        :raises QueryReturnedForbiddenException: When the server responds with a 403.\n        :raises ConnectionException: When download repeatedly failed."
  },
  {
    "code": "def maybe_print_as_json(opts, data, page_info=None):\n    if opts.output not in (\"json\", \"pretty_json\"):\n        return False\n    root = {\"data\": data}\n    if page_info is not None and page_info.is_valid:\n        meta = root[\"meta\"] = {}\n        meta[\"pagination\"] = page_info.as_dict(num_results=len(data))\n    if opts.output == \"pretty_json\":\n        dump = json.dumps(root, indent=4, sort_keys=True)\n    else:\n        dump = json.dumps(root, sort_keys=True)\n    click.echo(dump)\n    return True",
    "docstring": "Maybe print data as JSON."
  },
  {
    "code": "def most_mergeable(self, states):\n        histories = set(self.get_ref(s.history) for s in states)\n        for n in networkx.algorithms.dfs_postorder_nodes(self._graph):\n            intersection = histories.intersection(self.all_successors(n))\n            if len(intersection) > 1:\n                return (\n                    [ s for s in states if self.get_ref(s.history) in intersection ],\n                    n(),\n                    [ s for s in states if self.get_ref(s.history) not in intersection ]\n                )\n        return set(), None, states",
    "docstring": "Find the \"most mergeable\" set of states from those provided.\n\n        :param states: a list of states\n        :returns: a tuple of: (a list of states to merge, those states' common history, a list of states to not merge yet)"
  },
  {
    "code": "def get_last_activity(session):\n    try:\n        return datetime.strptime(session['_session_security'],\n                '%Y-%m-%dT%H:%M:%S.%f')\n    except AttributeError:\n        return datetime.now()\n    except TypeError:\n        return datetime.now()",
    "docstring": "Get the last activity datetime string from the session and return the\n    python datetime object."
  },
  {
    "code": "def check_user(user, password):\n    return ((user == attowiki.user or attowiki.user is None) and\n            (password == attowiki.password or attowiki.password is None))",
    "docstring": "check the auth for user and password."
  },
  {
    "code": "def extract_payload(self, request, verify=True, *args, **kwargs):\n        payload = self._verify(\n            request, return_payload=True, verify=verify, *args, **kwargs\n        )\n        return payload",
    "docstring": "Extract a payload from a request object."
  },
  {
    "code": "def _run_pyshark(self, pyshark):\n        if self._exlyr != 'None' or self._exptl != 'null':\n            warnings.warn(\"'Extractor(engine=pyshark)' does not support protocol and layer threshold; \"\n                          f\"'layer={self._exlyr}' and 'protocol={self._exptl}' ignored\",\n                          AttributeWarning, stacklevel=stacklevel())\n        if (self._ipv4 or self._ipv6 or self._tcp):\n            self._ipv4 = self._ipv6 = self._tcp = False\n            self._reasm = [None] * 3\n            warnings.warn(\"'Extractor(engine=pyshark)' object dose not support reassembly; \"\n                          f\"so 'ipv4={self._ipv4}', 'ipv6={self._ipv6}' and 'tcp={self._tcp}' will be ignored\",\n                          AttributeWarning, stacklevel=stacklevel())\n        self._expkg = pyshark\n        self._extmp = iter(pyshark.FileCapture(self._ifnm, keep_packets=False))\n        self.record_frames()",
    "docstring": "Call pyshark.FileCapture to extract PCAP files."
  },
  {
    "code": "def start(self):\n        if self.greenlet:\n            raise RuntimeError(f'Greenlet {self.greenlet!r} already started')\n        pristine = (\n            not self.greenlet.dead and\n            tuple(self.greenlet.args) == tuple(self.args) and\n            self.greenlet.kwargs == self.kwargs\n        )\n        if not pristine:\n            self.greenlet = Greenlet(self._run, *self.args, **self.kwargs)\n            self.greenlet.name = f'{self.__class__.__name__}|{self.greenlet.name}'\n        self.greenlet.start()",
    "docstring": "Synchronously start task\n\n        Reimplements in children an call super().start() at end to start _run()\n        Start-time exceptions may be raised"
  },
  {
    "code": "def GetInstances(r, bulk=False):\n    if bulk:\n        return r.request(\"get\", \"/2/instances\", query={\"bulk\": 1})\n    else:\n        instances = r.request(\"get\", \"/2/instances\")\n        return r.applier(itemgetters(\"id\"), instances)",
    "docstring": "Gets information about instances on the cluster.\n\n    @type bulk: bool\n    @param bulk: whether to return all information about all instances\n\n    @rtype: list of dict or list of str\n    @return: if bulk is True, info about the instances, else a list of instances"
  },
  {
    "code": "def quasiparticle_weight(self):\n        return np.array([self.expected(op)**2 for op in self.oper['O']])",
    "docstring": "Calculates quasiparticle weight"
  },
  {
    "code": "def set_redraw_lag(self, lag_sec):\n        self.defer_redraw = (lag_sec > 0.0)\n        if self.defer_redraw:\n            self.defer_lagtime = lag_sec",
    "docstring": "Set lag time for redrawing the canvas.\n\n        Parameters\n        ----------\n        lag_sec : float\n            Number of seconds to wait."
  },
  {
    "code": "def unarchive_user(self, user_id):\n        url = self.record_url + \"/unarchive\"\n        res = requests.patch(url=url, json={\"user_id\": user_id}, headers=HEADERS, verify=False)\n        self.write_response_html_to_file(res,\"bob.html\")\n        res.raise_for_status()",
    "docstring": "Unarchives the user with the specified user ID.\n\n        Args:\n            user_id: `int`. The ID of the user to unarchive.\n\n        Returns:\n            `NoneType`: None."
  },
  {
    "code": "def is_expired(self):\n        expires = self.expires_at\n        if expires is not None:\n            return expires <= datetime.utcnow()\n        return False",
    "docstring": "``True`` if this key is expired, otherwise ``False``"
  },
  {
    "code": "def close_stream(self):\n        if self.fout:\n            fout = self.fout\n            fout_fn = self.fout_fn\n            self.fout.flush()\n            self.fout.close()\n            self.fout = None\n            self.fout_fn = None\n            return fout_fn",
    "docstring": "Terminates an open stream and returns the filename\n        of the file containing the streamed data."
  },
  {
    "code": "def _send_and_reconnect(self, message):\n        try:\n            self.socket.sendall(message.encode(\"ascii\"))\n        except (AttributeError, socket.error):\n            if not self.autoreconnect():\n                raise\n            else:\n                self.socket.sendall(message.encode(\"ascii\"))",
    "docstring": "Send _message_ to Graphite Server and attempt reconnect on failure.\n\n        If _autoreconnect_ was specified, attempt to reconnect if first send\n        fails.\n\n        :raises AttributeError: When the socket has not been set.\n        :raises socket.error: When the socket connection is no longer valid."
  },
  {
    "code": "def check_for_debug(supernova_args, nova_args):\n    if supernova_args['debug'] and supernova_args['executable'] == 'heat':\n        nova_args.insert(0, '-d ')\n    elif supernova_args['debug']:\n        nova_args.insert(0, '--debug ')\n    return nova_args",
    "docstring": "If the user wanted to run the executable with debugging enabled, we need\n    to apply the correct arguments to the executable.\n\n    Heat is a corner case since it uses -d instead of --debug."
  },
  {
    "code": "def _set_rules(self, rules: dict, overwrite=True):\n        if not isinstance(rules, dict):\n            raise TypeError('rules must be an instance of dict or Rules,'\n                            'got %r instead' % type(rules))\n        if overwrite:\n            self.rules = Rules(rules, self.default_rule)\n        else:\n            self.rules.update(rules)",
    "docstring": "Created a new Rules object based on the provided dict of rules."
  },
  {
    "code": "def my_version():\n    if os.path.exists(resource_filename(__name__, 'version')):\n        return resource_string(__name__, 'version')\n    return open(os.path.join(os.path.dirname(__file__),\n                             \"..\", \"version\")).read()",
    "docstring": "Return the version, checking both packaged and development locations"
  },
  {
    "code": "def deb64_app(parser, cmd, args):\n    parser.add_argument('value', help='the value to base64 decode, read from stdin if omitted', nargs='?')\n    args = parser.parse_args(args)\n    return deb64(pwnypack.main.string_value_or_stdin(args.value))",
    "docstring": "base64 decode a value."
  },
  {
    "code": "def get_candidates(self):\n        candidate_elections = CandidateElection.objects.filter(election=self)\n        return [ce.candidate for ce in candidate_elections]",
    "docstring": "Get all CandidateElections for this election."
  },
  {
    "code": "def _decompress_data(self, data):\n        if self._decompressor:\n            try:\n                return self._decompressor.decompress(data)\n            except zlib.error as error:\n                raise ProtocolError(\n                    'zlib error: {0}.'.format(error)\n                ) from error\n        else:\n            return data",
    "docstring": "Decompress the given data and return the uncompressed data."
  },
  {
    "code": "def pystdlib():\r\n    curver = '.'.join(str(x) for x in sys.version_info[:2])\r\n    return (set(stdlib_list.stdlib_list(curver)) | {\r\n        '_LWPCookieJar', '_MozillaCookieJar', '_abcoll', 'email._parseaddr',\r\n        'email.base64mime', 'email.feedparser', 'email.quoprimime',\r\n        'encodings', 'genericpath', 'ntpath', 'nturl2path', 'os2emxpath',\r\n        'posixpath', 'sre_compile', 'sre_parse', 'unittest.case',\r\n        'unittest.loader', 'unittest.main', 'unittest.result',\r\n        'unittest.runner', 'unittest.signals', 'unittest.suite',\r\n        'unittest.util', '_threading_local', 'sre_constants', 'strop',\r\n        'repr', 'opcode', 'nt', 'encodings.aliases',\r\n        '_bisect', '_codecs', '_collections', '_functools', '_hashlib',\r\n        '_heapq', '_io', '_locale', '_LWPCookieJar', '_md5',\r\n        '_MozillaCookieJar', '_random', '_sha', '_sha256', '_sha512',\r\n        '_socket', '_sre', '_ssl', '_struct', '_subprocess',\r\n        '_threading_local', '_warnings', '_weakref', '_weakrefset',\r\n        '_winreg'\r\n    }) - {'__main__'}",
    "docstring": "Return a set of all module-names in the Python standard library."
  },
  {
    "code": "def clusterQueues(self):\n        servers = yield self.getClusterServers()\n        queues = {}\n        for sname in servers:\n            qs = yield self.get('rhumba.server.%s.queues' % sname)\n            uuid = yield self.get('rhumba.server.%s.uuid' % sname)\n            qs = json.loads(qs)\n            for q in qs:\n                if q not in queues:\n                    queues[q] = []\n                queues[q].append({'host': sname, 'uuid': uuid})\n        defer.returnValue(queues)",
    "docstring": "Return a dict of queues in cluster and servers running them"
  },
  {
    "code": "def bind_env(self, *input_):\n        if len(input_) == 0:\n            return \"bind_env missing key to bind to\"\n        key = input_[0].lower()\n        if len(input_) == 1:\n            env_key = self._merge_with_env_prefix(key)\n        else:\n            env_key = input_[1]\n        self._env[key] = env_key\n        if self._key_delimiter in key:\n            parts = input_[0].split(self._key_delimiter)\n            env_info = {\n                \"path\": parts[1:-1],\n                \"final_key\": parts[-1],\n                \"env_key\": env_key\n            }\n            if self._env.get(parts[0]) is None:\n                self._env[parts[0]] = [env_info]\n            else:\n                self._env[parts[0]].append(env_info)\n        return None",
    "docstring": "Binds a Vyper key to a ENV variable.\n        ENV variables are case sensitive.\n        If only a key is provided, it will use the env key matching the key,\n        uppercased.\n        `env_prefix` will be used when set when env name is not provided."
  },
  {
    "code": "def parse(yaml, validate=True):\n    data = read_yaml(yaml)\n    if validate:\n        from .validation import validate\n        validate(data, raise_exc=True)\n    return Config.parse(data)",
    "docstring": "Parse the given YAML data into a `Config` object, optionally validating it first.\n\n    :param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)\n    :type yaml: list|dict|str|file\n    :param validate: Whether to validate the data before attempting to parse it.\n    :type validate: bool\n    :return: Config object\n    :rtype: valohai_yaml.objs.Config"
  },
  {
    "code": "def get(self, request, *args, **kwargs):\n        measurements = Measurement.objects.all()    \n        return data_csv(self.request, measurements)",
    "docstring": "The queryset returns all measurement objects"
  },
  {
    "code": "def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata):\n        if type(rdata) is not list:\n            rdata = [rdata]\n        rrset = {\"ttl\": ttl, \"rdata\": rdata}\n        return self.rest_api_connection.post(\"/v1/zones/\" + zone_name + \"/rrsets/\" + rtype + \"/\" + owner_name, json.dumps(rrset))",
    "docstring": "Creates a new RRSet in the specified zone.\n\n        Arguments:\n        zone_name -- The zone that will contain the new RRSet.  The trailing dot is optional.\n        rtype -- The type of the RRSet.  This can be numeric (1) or\n                 if a well-known name is defined for the type (A), you can use it instead.\n        owner_name -- The owner name for the RRSet.\n                      If no trailing dot is supplied, the owner_name is assumed to be relative (foo).\n                      If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.)\n        ttl -- The TTL value for the RRSet.\n        rdata -- The BIND data for the RRSet as a string.\n                 If there is a single resource record in the RRSet, you can pass in the single string.\n                 If there are multiple resource records  in this RRSet, pass in a list of strings."
  },
  {
    "code": "def string_literal(content):\n    if '\"' in content and \"'\" in content:\n        raise ValueError(\"Cannot represent this string in XPath\")\n    if '\"' in content:\n        content = \"'%s'\" % content\n    else:\n        content = '\"%s\"' % content\n    return content",
    "docstring": "Choose a string literal that can wrap our string.\n\n    If your string contains a ``\\'`` the result will be wrapped in ``\\\"``.\n    If your string contains a ``\\\"`` the result will be wrapped in ``\\'``.\n\n    Cannot currently handle strings which contain both ``\\\"`` and ``\\'``."
  },
  {
    "code": "def verifymessage(self, address, signature, message):\n        return self.req(\"verifymessage\", [address, signature, message])",
    "docstring": "Verify a signed message."
  },
  {
    "code": "def create_followup(self, post, content, anonymous=False):\n        try:\n            cid = post[\"id\"]\n        except KeyError:\n            cid = post\n        params = {\n            \"cid\": cid,\n            \"type\": \"followup\",\n            \"subject\": content,\n            \"content\": \"\",\n            \"anonymous\": \"yes\" if anonymous else \"no\",\n        }\n        return self._rpc.content_create(params)",
    "docstring": "Create a follow-up on a post `post`.\n\n        It seems like if the post has `<p>` tags, then it's treated as HTML,\n        but is treated as text otherwise. You'll want to provide `content`\n        accordingly.\n\n        :type  post: dict|str|int\n        :param post: Either the post dict returned by another API method, or\n            the `cid` field of that post.\n        :type  content: str\n        :param content: The content of the followup.\n        :type  anonymous: bool\n        :param anonymous: Whether or not to post anonymously.\n        :rtype: dict\n        :returns: Dictionary with information about the created follow-up."
  },
  {
    "code": "def __replace_within_document(self, document, occurrences, replacement_pattern):\n        cursor = QTextCursor(document)\n        cursor.beginEditBlock()\n        offset = count = 0\n        for occurence in sorted(occurrences, key=lambda x: x.position):\n            cursor.setPosition(offset + occurence.position, QTextCursor.MoveAnchor)\n            cursor.setPosition(offset + occurence.position + occurence.length, QTextCursor.KeepAnchor)\n            cursor.insertText(replacement_pattern)\n            offset += len(replacement_pattern) - occurence.length\n            count += 1\n        cursor.endEditBlock()\n        return count",
    "docstring": "Replaces given pattern occurrences in given document using given settings.\n\n        :param document: Document.\n        :type document: QTextDocument\n        :param replacement_pattern: Replacement pattern.\n        :type replacement_pattern: unicode\n        :return: Replaced occurrences count.\n        :rtype: int"
  },
  {
    "code": "def RfiltersBM(dataset,database,host=rbiomart_host):\n    biomaRt = importr(\"biomaRt\")\n    ensemblMart=biomaRt.useMart(database, host=host)\n    ensembl=biomaRt.useDataset(dataset, mart=ensemblMart)\n    print(biomaRt.listFilters(ensembl))",
    "docstring": "Lists BioMart filters through a RPY2 connection.\n\n    :param dataset: a dataset listed in RdatasetsBM()\n    :param database: a database listed in RdatabasesBM()\n    :param host: address of the host server, default='www.ensembl.org'\n\n    :returns: nothing"
  },
  {
    "code": "def pairwise_ellpitical_binary(sources, eps, far=None):\n    if far is None:\n        far = max(a.a/3600 for a in sources)\n    l = len(sources)\n    distances = np.zeros((l, l), dtype=bool)\n    for i in range(l):\n        for j in range(i, l):\n            if i == j:\n                distances[i, j] = False\n                continue\n            src1 = sources[i]\n            src2 = sources[j]\n            if src2.dec - src1.dec > far:\n                break\n            if abs(src2.ra - src1.ra)*np.cos(np.radians(src1.dec)) > far:\n                continue\n            distances[i, j] = norm_dist(src1, src2) > eps\n            distances[j, i] = distances[i, j]\n    return distances",
    "docstring": "Do a pairwise comparison of all sources and determine if they have a normalized distance within\n    eps.\n\n    Form this into a matrix of shape NxN.\n\n\n    Parameters\n    ----------\n    sources : list\n        A list of sources (objects with parameters: ra,dec,a,b,pa)\n\n    eps : float\n        Normalised distance constraint.\n\n    far : float\n        If sources have a dec that differs by more than this amount then they are considered to be not matched.\n        This is a short-cut around performing GCD calculations.\n\n    Returns\n    -------\n    prob : numpy.ndarray\n        A 2d array of True/False.\n\n    See Also\n    --------\n    :func:`AegeanTools.cluster.norm_dist`"
  },
  {
    "code": "def low_limit(self) -> Optional[Union[int, float]]:\n        return self._get_field_value(SpecialDevice.PROP_LOW_LIMIT)",
    "docstring": "Low limit setting for a special sensor.\n\n        For LS-10/LS-20 base units this is the alarm low limit.\n        For LS-30 base units, this is either alarm OR control low limit,\n        as indicated by special_status ControlAlarm bit flag."
  },
  {
    "code": "def status(self, status_in):\n        if isinstance(status_in, PIDStatus):\n            status_in = [status_in, ]\n        return self.filter(\n            self._filtered_pid_class.status.in_(status_in)\n        )",
    "docstring": "Filter the PIDs based on their status."
  },
  {
    "code": "def addon_name(self):\n        with self.selenium.context(self.selenium.CONTEXT_CHROME):\n            el = self.find_description()\n            return el.find_element(By.CSS_SELECTOR, \"b\").text",
    "docstring": "Provide access to the add-on name.\n\n        Returns:\n            str: Add-on name."
  },
  {
    "code": "def escape(string, escape_pattern):\n    try:\n        return string.translate(escape_pattern)\n    except AttributeError:\n        warnings.warn(\"Non-string-like data passed. \"\n                      \"Attempting to convert to 'str'.\")\n        return str(string).translate(tag_escape)",
    "docstring": "Assistant function for string escaping"
  },
  {
    "code": "def find_methods(self, classname=\".*\", methodname=\".*\", descriptor=\".*\",\n            accessflags=\".*\", no_external=False):\n        for cname, c in self.classes.items():\n            if re.match(classname, cname):\n                for m in c.get_methods():\n                    z = m.get_method()\n                    if no_external and isinstance(z, ExternalMethod):\n                        continue\n                    if re.match(methodname, z.get_name()) and \\\n                       re.match(descriptor, z.get_descriptor()) and \\\n                       re.match(accessflags, z.get_access_flags_string()):\n                        yield m",
    "docstring": "Find a method by name using regular expression.\n        This method will return all MethodClassAnalysis objects, which match the\n        classname, methodname, descriptor and accessflags of the method.\n\n        :param classname: regular expression for the classname\n        :param methodname: regular expression for the method name\n        :param descriptor: regular expression for the descriptor\n        :param accessflags: regular expression for the accessflags\n        :param no_external: Remove external method from the output (default False)\n        :rtype: generator of `MethodClassAnalysis`"
  },
  {
    "code": "def hashVariantAnnotation(cls, gaVariant, gaVariantAnnotation):\n        treffs = [treff.id for treff in gaVariantAnnotation.transcript_effects]\n        return hashlib.md5(\n            \"{}\\t{}\\t{}\\t\".format(\n                gaVariant.reference_bases, tuple(gaVariant.alternate_bases),\n                treffs)\n            ).hexdigest()",
    "docstring": "Produces an MD5 hash of the gaVariant and gaVariantAnnotation objects"
  },
  {
    "code": "def fetch(sequence, time='hour'):\n    import StringIO\n    import gzip\n    import requests\n    if time not in ['minute','hour','day']:\n        raise ValueError('The supplied type of replication file does not exist.')\n    sqn = str(sequence).zfill(9)\n    url = \"https://planet.osm.org/replication/%s/%s/%s/%s.osc.gz\" %\\\n          (time, sqn[0:3], sqn[3:6], sqn[6:9])\n    content = requests.get(url)\n    if content.status_code == 404:\n        raise EnvironmentError('Diff file cannot be found.')\n    content = StringIO.StringIO(content.content)\n    data_stream = gzip.GzipFile(fileobj=content)\n    return data_stream",
    "docstring": "Fetch an OpenStreetMap diff file.\n\n    Parameters\n    ----------\n    sequence : string or integer\n        Diff file sequence desired. Maximum of 9 characters allowed. The value\n        should follow the two directory and file name structure from the site,\n        e.g. https://planet.osm.org/replication/hour/NNN/NNN/NNN.osc.gz (with\n        leading zeros optional).\n\n    time : {'minute', 'hour', or 'day'}, optional\n        Denotes the diff file time granulation to be downloaded. The value\n        must be a valid directory at https://planet.osm.org/replication/.\n\n    Returns\n    -------\n    data_stream : class\n        A file-like class containing a decompressed data stream from the\n        fetched diff file in string format."
  },
  {
    "code": "def _increment_current_byte(self):\n        if self.tape[self.pointer] is None:\n            self.tape[self.pointer] = 1\n        elif self.tape[self.pointer] == self.MAX_CELL_SIZE:\n            self.tape[self.pointer] = self.MIN_CELL_SIZE\n        else:\n            self.tape[self.pointer] += 1",
    "docstring": "Increments the value of the current byte at the pointer. If the result is over 255,\n        then it will overflow to 0"
  },
  {
    "code": "def is_binary_operator(oper):\n    symbols = [\n        ',', '()', '[]', '!=', '%', '%=', '&', '&&', '&=', '*', '*=', '+',\n        '+=', '-', '-=', '->', '->*', '/', '/=', '<', '<<', '<<=', '<=', '=',\n        '==', '>', '>=', '>>', '>>=', '^', '^=', '|', '|=', '||']\n    if not isinstance(oper, calldef_members.operator_t):\n        return False\n    if oper.symbol not in symbols:\n        return False\n    if isinstance(oper, calldef_members.member_operator_t):\n        if len(oper.arguments) == 1:\n            return True\n        return False\n    if len(oper.arguments) == 2:\n        return True\n    return False",
    "docstring": "returns True, if operator is binary operator, otherwise False"
  },
  {
    "code": "def listen(self, message_consumer):\n        while not self._rfile.closed:\n            request_str = self._read_message()\n            if request_str is None:\n                break\n            try:\n                message_consumer(json.loads(request_str.decode('utf-8')))\n            except ValueError:\n                log.exception(\"Failed to parse JSON message %s\", request_str)\n                continue",
    "docstring": "Blocking call to listen for messages on the rfile.\n\n        Args:\n            message_consumer (fn): function that is passed each message as it is read off the socket."
  },
  {
    "code": "def _validate_initial_centers(initial_centers):\n    if not (isinstance(initial_centers, _SFrame)):\n        raise TypeError(\"Input 'initial_centers' must be an SFrame.\")\n    if initial_centers.num_rows() == 0 or initial_centers.num_columns() == 0:\n        raise ValueError(\"An 'initial_centers' argument is provided \" +\n                         \"but has no data.\")",
    "docstring": "Validate the initial centers.\n\n    Parameters\n    ----------\n    initial_centers : SFrame\n        Initial cluster center locations, in SFrame form."
  },
  {
    "code": "def clone(self):\n        temp = self.__class__()\n        temp.base = self.base\n        return temp",
    "docstring": "Return a new bitfield with the same value.\n        \n        The returned value is a copy, and so is no longer linked to the\n        original bitfield.  This is important when the original is located\n        at anything other than normal memory, with accesses to it either\n        slow or having side effects.  Creating a clone, and working\n        against that clone, means that only one read will occur."
  },
  {
    "code": "def call_only_once(func):\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        self = args[0]\n        assert func.__name__ in dir(self), \"call_only_once can only be used on method or property!\"\n        if not hasattr(self, '_CALL_ONLY_ONCE_CACHE'):\n            cache = self._CALL_ONLY_ONCE_CACHE = set()\n        else:\n            cache = self._CALL_ONLY_ONCE_CACHE\n        cls = type(self)\n        is_method = inspect.isfunction(getattr(cls, func.__name__))\n        assert func not in cache, \\\n            \"{} {}.{} can only be called once per object!\".format(\n                'Method' if is_method else 'Property',\n                cls.__name__, func.__name__)\n        cache.add(func)\n        return func(*args, **kwargs)\n    return wrapper",
    "docstring": "Decorate a method or property of a class, so that this method can only\n    be called once for every instance.\n    Calling it more than once will result in exception."
  },
  {
    "code": "def normalize_filepath(filepath):\n    r\n    filename = os.path.basename(filepath)\n    dirpath = filepath[:-len(filename)]\n    cre_controlspace = re.compile(r'[\\t\\r\\n\\f]+')\n    new_filename = cre_controlspace.sub('', filename)\n    if not new_filename == filename:\n        logger.warning('Stripping whitespace from filename: {} => {}'.format(\n            repr(filename), repr(new_filename)))\n        filename = new_filename\n    filename = filename.lower()\n    filename = normalize_ext(filename)\n    if dirpath:\n        dirpath = dirpath[:-1]\n        return os.path.join(dirpath, filename)\n    return filename",
    "docstring": "r\"\"\" Lowercase the filename and ext, expanding extensions like .tgz to .tar.gz.\n\n    >>> normalize_filepath('/Hello_World.txt\\n')\n    'hello_world.txt'\n    >>> normalize_filepath('NLPIA/src/nlpia/bigdata/Goog New 300Dneg\\f.bIn\\n.GZ')\n    'NLPIA/src/nlpia/bigdata/goog new 300dneg.bin.gz'"
  },
  {
    "code": "def connectToMissing(self) -> set:\n        missing = self.reconcileNodeReg()\n        if not missing:\n            return missing\n        logger.info(\"{}{} found the following missing connections: {}\".\n                    format(CONNECTION_PREFIX, self, \", \".join(missing)))\n        for name in missing:\n            try:\n                self.connect(name, ha=self.registry[name])\n            except (ValueError, KeyError, PublicKeyNotFoundOnDisk, VerKeyNotFoundOnDisk) as ex:\n                logger.warning('{}{} cannot connect to {} due to {}'.\n                               format(CONNECTION_PREFIX, self, name, ex))\n        return missing",
    "docstring": "Try to connect to the missing nodes"
  },
  {
    "code": "def deviance(self, endog, mu, freq_weights=1., scale=1.):\n        r\n        endog_mu = self._clean(endog/mu)\n        return 2*np.sum(freq_weights*((endog-mu)/mu-np.log(endog_mu)))",
    "docstring": "r\"\"\"\n        Gamma deviance function\n\n        Parameters\n        -----------\n        endog : array-like\n            Endogenous response variable\n        mu : array-like\n            Fitted mean response variable\n        freq_weights : array-like\n            1d array of frequency weights. The default is 1.\n        scale : float, optional\n            An optional scale argument. The default is 1.\n\n        Returns\n        -------\n        deviance : float\n            Deviance function as defined below"
  },
  {
    "code": "def ret_list_minions(self):\n        tgt = _tgt_set(self.tgt)\n        return self._ret_minions(tgt.intersection)",
    "docstring": "Return minions that match via list"
  },
  {
    "code": "def update(self, **kwargs):\n    for key, value in kwargs.items():\n      setattr(self, key, value)",
    "docstring": "Creates or updates a property for the instance for each parameter."
  },
  {
    "code": "def merge_all_sections(prnt_sctns, child_sctns, style):\n    doc = []\n    prnt_only_raises = prnt_sctns[\"Raises\"] and not (prnt_sctns[\"Returns\"] or prnt_sctns[\"Yields\"])\n    if prnt_only_raises and (child_sctns[\"Returns\"] or child_sctns[\"Yields\"]):\n        prnt_sctns[\"Raises\"] = None\n    for key in prnt_sctns:\n        sect = merge_section(key, prnt_sctns[key], child_sctns[key], style)\n        if sect is not None:\n            doc.append(sect)\n    return \"\\n\\n\".join(doc) if doc else None",
    "docstring": "Merge the doc-sections of the parent's and child's attribute into a single docstring.\n\n        Parameters\n        ----------\n        prnt_sctns: OrderedDict[str, Union[None,str]]\n        child_sctns: OrderedDict[str, Union[None,str]]\n\n        Returns\n        -------\n        str\n            Output docstring of the merged docstrings."
  },
  {
    "code": "def default(self):\n        if ZONE_NAME:\n            log.info(\"Getting or creating default environment for zone with name '{0}'\".format(DEFAULT_ENV_NAME()))\n            zone_id = self.organization.zones[ZONE_NAME].id\n            return self.organization.get_or_create_environment(name=DEFAULT_ENV_NAME(), zone=zone_id)\n        def_envs = [env_j[\"id\"] for env_j in self.json() if env_j[\"isDefault\"]]\n        if len(def_envs) > 1:\n            log.warning('Found more than one default environment. Picking last.')\n            return self[def_envs[-1]]\n        elif len(def_envs) == 1:\n            return self[def_envs[0]]\n        raise exceptions.NotFoundError('Unable to get default environment')",
    "docstring": "Returns environment marked as default.\n            When Zone is set marked default makes no sense, special env with proper Zone is returned."
  },
  {
    "code": "def add_items_to_message(msg, log_dict):\n    out = msg\n    for key, value in log_dict.items():\n        out += \" {}={}\".format(key, value)\n    return out",
    "docstring": "Utility function to add dictionary items to a log message."
  },
  {
    "code": "def is_already_locked(request, get_username=get_username_from_request, username=None):\n    user_blocked = is_user_already_locked(username or get_username(request))\n    ip_blocked = is_source_ip_already_locked(get_ip(request))\n    if config.LOCKOUT_BY_IP_USERNAME:\n        return ip_blocked and user_blocked\n    return ip_blocked or user_blocked",
    "docstring": "Parse the username & IP from the request, and see if it's\n    already locked."
  },
  {
    "code": "def load(self, json_file):\n        cart_file = os.path.join(CART_LOCATION, json_file)\n        try:\n            cart_body = juicer.utils.read_json_document(cart_file)\n        except IOError as e:\n            juicer.utils.Log.log_error('an error occured while accessing %s:' %\n                    cart_file)\n            raise JuicerError(e.message)\n        self.cart_name = cart_body['_id']\n        if cart_body['current_env'] == '':\n                self.current_env = juicer.utils.get_login_info()[1]['start_in']\n        else:\n            self.current_env = cart_body['current_env']\n        for repo, items in cart_body['repos_items'].iteritems():\n            self.add_repo(repo, items)",
    "docstring": "Build a cart from a json file"
  },
  {
    "code": "def _remove_unit_rule(g, rule):\n    new_rules = [x for x in g.rules if x != rule]\n    refs = [x for x in g.rules if x.lhs == rule.rhs[0]]\n    new_rules += [build_unit_skiprule(rule, ref) for ref in refs]\n    return Grammar(new_rules)",
    "docstring": "Removes 'rule' from 'g' without changing the langugage produced by 'g'."
  },
  {
    "code": "def to_obj(self, ns_info=None):\n        if ns_info:\n            ns_info.collect(self)\n        if not hasattr(self, \"_binding_class\"):\n            return None\n        entity_obj = self._binding_class()\n        for field, val in six.iteritems(self._fields):\n            if isinstance(val, EntityList) and len(val) == 0:\n                val = None\n            elif field.multiple:\n                if val:\n                    val = [_objectify(field, x, ns_info) for x in val]\n                else:\n                    val = []\n            else:\n                val = _objectify(field, val, ns_info)\n            setattr(entity_obj, field.name, val)\n        self._finalize_obj(entity_obj)\n        return entity_obj",
    "docstring": "Convert to a GenerateDS binding object.\n\n        Subclasses can override this function.\n\n        Returns:\n            An instance of this Entity's ``_binding_class`` with properties\n            set from this Entity."
  },
  {
    "code": "def hpo_genes(phenotype_ids, username, password):\n    if phenotype_ids:\n        try:\n            results = query_phenomizer.query(username, password, phenotype_ids)\n            return [result for result in results\n                    if result['p_value'] is not None]\n        except SystemExit, RuntimeError:\n            pass\n    return None",
    "docstring": "Return list of HGNC symbols matching HPO phenotype ids.\n\n    Args:\n        phenotype_ids (list): list of phenotype ids\n        username (str): username to connect to phenomizer\n        password (str): password to connect to phenomizer\n\n    Returns:\n        query_result: a list of dictionaries on the form\n        {\n            'p_value': float,\n            'gene_id': str,\n            'omim_id': int,\n            'orphanet_id': int,\n            'decipher_id': int,\n            'any_id': int,\n            'mode_of_inheritance': str,\n            'description': str,\n            'raw_line': str\n        }"
  },
  {
    "code": "def get_broadcast_transactions(coin_symbol='btc', limit=10, api_key=None):\n    url = make_url(coin_symbol, 'txs')\n    params = {}\n    if api_key:\n        params['token'] = api_key\n    if limit:\n        params['limit'] = limit\n    r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)\n    response_dict = get_valid_json(r)\n    unconfirmed_txs = []\n    for unconfirmed_tx in response_dict:\n        unconfirmed_tx['received'] = parser.parse(unconfirmed_tx['received'])\n        unconfirmed_txs.append(unconfirmed_tx)\n    return unconfirmed_txs",
    "docstring": "Get a list of broadcast but unconfirmed transactions\n    Similar to bitcoind's getrawmempool method"
  },
  {
    "code": "def OnCellSelected(self, event):\n        key = row, col, tab = event.Row, event.Col, self.grid.current_table\n        cell_attributes = self.grid.code_array.cell_attributes\n        merging_cell = cell_attributes.get_merging_cell(key)\n        if merging_cell is not None and merging_cell != key:\n            post_command_event(self.grid, self.grid.GotoCellMsg,\n                               key=merging_cell)\n            if cell_attributes[merging_cell][\"button_cell\"]:\n                self.grid.EnableCellEditControl()\n            return\n        if not self.grid.IsEditable():\n            return\n        self.grid.ForceRefresh()\n        self.grid.lock_entry_line(\n            self.grid.code_array.cell_attributes[key][\"locked\"])\n        self.grid.update_entry_line(key)\n        self.grid.update_attribute_toolbar(key)\n        self.grid._last_selected_cell = key\n        event.Skip()",
    "docstring": "Cell selection event handler"
  },
  {
    "code": "def generateDHCPOptionsTemplate(self, address_family):\n        from ns1.ipam import DHCPOptions\n        options = {}\n        for option in DHCPOptions.OPTIONS[address_family]:\n            options[option] = \"\"\n        return options",
    "docstring": "Generate boilerplate dictionary to hold dhcp options\n\n        :param str address_family: dhcpv4 or dhcpv6\n        :return: dict containing valid option set for address family"
  },
  {
    "code": "def doseigs(s):\n    A = s2a(s)\n    tau, V = tauV(A)\n    Vdirs = []\n    for v in V:\n        Vdir = cart2dir(v)\n        if Vdir[1] < 0:\n            Vdir[1] = -Vdir[1]\n            Vdir[0] = (Vdir[0] + 180.) % 360.\n        Vdirs.append([Vdir[0], Vdir[1]])\n    return tau, Vdirs",
    "docstring": "convert s format for eigenvalues and eigenvectors\n\n    Parameters\n    __________\n    s=[x11,x22,x33,x12,x23,x13] : the six tensor elements\n\n    Return\n    __________\n        tau : [t1,t2,t3]\n           tau is an list of eigenvalues in decreasing order:\n        V : [[V1_dec,V1_inc],[V2_dec,V2_inc],[V3_dec,V3_inc]]\n            is an list of the eigenvector directions"
  },
  {
    "code": "def crc_ihex(hexstr):\n    crc = sum(bytearray(binascii.unhexlify(hexstr)))\n    crc &= 0xff\n    crc = ((~crc + 1) & 0xff)\n    return crc",
    "docstring": "Calculate the CRC for given Intel HEX hexstring."
  },
  {
    "code": "def maximum_size_estimated(self, sz):\n        if not isinstance(sz, str):\n            sz = str(sz)\n        self._attributes[\"sz\"] = sz",
    "docstring": "Set the CoRE Link Format sz attribute of the resource.\n\n        :param sz: the CoRE Link Format sz attribute"
  },
  {
    "code": "def get_works(self):\n        Work = self._session.get_class(surf.ns.EFRBROO['F1_Work'])\n        return list(Work.all())",
    "docstring": "Return the author's works.\n\n        :return: a list of `HucitWork` instances."
  },
  {
    "code": "def id(self):\n        def normalize(distro_id, table):\n            distro_id = distro_id.lower().replace(' ', '_')\n            return table.get(distro_id, distro_id)\n        distro_id = self.os_release_attr('id')\n        if distro_id:\n            return normalize(distro_id, NORMALIZED_OS_ID)\n        distro_id = self.lsb_release_attr('distributor_id')\n        if distro_id:\n            return normalize(distro_id, NORMALIZED_LSB_ID)\n        distro_id = self.distro_release_attr('id')\n        if distro_id:\n            return normalize(distro_id, NORMALIZED_DISTRO_ID)\n        distro_id = self.uname_attr('id')\n        if distro_id:\n            return normalize(distro_id, NORMALIZED_DISTRO_ID)\n        return ''",
    "docstring": "Return the distro ID of the OS distribution, as a string.\n\n        For details, see :func:`distro.id`."
  },
  {
    "code": "def startswith(text, ignore_case=True):\n        if ignore_case:\n            compiled = re.compile(\n                \"^%s\" % text.replace(\"\\\\\", \"\\\\\\\\\"), re.IGNORECASE)\n        else:\n            compiled = re.compile(\"^%s\" % text.replace(\"\\\\\", \"\\\\\\\\\"))\n        return {\"$regex\": compiled}",
    "docstring": "Test if a string-field start with ``text``.\n\n        Example::\n\n            filters = {\"path\": Text.startswith(r\"C:\\\\\")}"
  },
  {
    "code": "def try_acquire(self, permits=1, timeout=0):\n        check_not_negative(permits, \"Permits cannot be negative!\")\n        return self._encode_invoke(semaphore_try_acquire_codec, permits=permits, timeout=to_millis(timeout))",
    "docstring": "Tries to acquire one or the given number of permits, if they are available, and returns immediately, with the\n        value ``true``, reducing the number of available permits by the given amount.\n\n        If there are insufficient permits and a timeout is provided, the current thread becomes disabled for thread\n        scheduling purposes and lies dormant until one of following happens:\n            * some other thread invokes the release() method for this semaphore and the current thread is next to be\n            assigned a permit, or\n            * some other thread interrupts the current thread, or\n            * the specified waiting time elapses.\n\n        If there are insufficient permits and no timeout is provided, this method will return immediately with the value\n        ``false`` and the number of available permits is unchanged.\n\n        :param permits: (int), the number of permits to acquire (optional).\n        :param timeout: (long), the maximum time in seconds to wait for the permit(s) (optional).\n        :return: (bool), ``true`` if desired amount of permits was acquired, ``false`` otherwise."
  },
  {
    "code": "def p0(self):\n        if self._p0 is None:\n            raise ValueError(\"initial positions not set; run set_p0\")\n        p0 = {param: self._p0[..., k]\n              for (k, param) in enumerate(self.sampling_params)}\n        return p0",
    "docstring": "A dictionary of the initial position of the walkers.\n\n        This is set by using ``set_p0``. If not set yet, a ``ValueError`` is\n        raised when the attribute is accessed."
  },
  {
    "code": "def imethodcallPayload(self, methodname, localnsp, **kwargs):\n        param_list = [pywbem.IPARAMVALUE(x[0], pywbem.tocimxml(x[1]))\n                      for x in kwargs.items()]\n        payload = cim_xml.CIM(\n            cim_xml.MESSAGE(\n                cim_xml.SIMPLEREQ(\n                    cim_xml.IMETHODCALL(\n                        methodname,\n                        cim_xml.LOCALNAMESPACEPATH(\n                            [cim_xml.NAMESPACE(ns)\n                             for ns in localnsp.split('/')]),\n                        param_list)),\n                '1001', '1.0'),\n            '2.0', '2.0')\n        return self.xml_header + payload.toxml()",
    "docstring": "Generate the XML payload for an intrinsic methodcall."
  },
  {
    "code": "def getProvIden(self, provstack):\n        iden = _providen(provstack)\n        misc, frames = provstack\n        dictframes = [(typ, {k: v for (k, v) in info}) for (typ, info) in frames]\n        bytz = s_msgpack.en((misc, dictframes))\n        didwrite = self.slab.put(iden, bytz, overwrite=False, db=self.db)\n        if didwrite:\n            self.provseq.save([iden])\n        return iden",
    "docstring": "Returns the iden corresponding to a provenance stack and stores if it hasn't seen it before"
  },
  {
    "code": "def scene_velocity(frames):\n        reader = MessageReader(frames)\n        results = reader.string(\"command\").uint32(\"scene_id\").uint32(\"velocity\").assert_end().get()\n        if results.command != \"scene.velocity\":\n            raise MessageParserError(\"Command is not 'scene.velocity'\")\n        return (results.scene_id, results.velocity/1000)",
    "docstring": "parse a scene.velocity message"
  },
  {
    "code": "def available():\n    proc = popen_multiple(\n        COMMANDS,\n        ['-version'],\n        stdout=subprocess.PIPE,\n        stderr=subprocess.PIPE,\n        creationflags=PROC_FLAGS,\n    )\n    proc.wait()\n    return (proc.returncode == 0)",
    "docstring": "Detect if the FFmpeg backend can be used on this system."
  },
  {
    "code": "def parse_geometry(geometry, ratio=None):\n    if \"%\" not in geometry:\n        return xy_geometry_parser(geometry, ratio)\n    return float(geometry.strip(\"%\")) / 100.0",
    "docstring": "Enhanced parse_geometry parser with percentage support."
  },
  {
    "code": "def set(self, key, value, expires=None, future=None):\n        with self._lock:\n            try:\n                self._dict[key].set(value, expires=expires, future=future)\n            except KeyError:\n                self._dict[key] = moment(value, expires=expires, future=future, lock=self._lock)\n            return value",
    "docstring": "Set a value"
  },
  {
    "code": "def updateAARText(self):\n        'Updates the displayed airspeed, altitude, climb rate Text'\n        self.airspeedText.set_text('AR:   %.1f m/s' % self.airspeed)\n        self.altitudeText.set_text('ALT: %.1f m   ' % self.relAlt)\n        self.climbRateText.set_text('CR:   %.1f m/s' % self.climbRate)",
    "docstring": "Updates the displayed airspeed, altitude, climb rate Text"
  },
  {
    "code": "def receive(self, sequence, args):\n        if not self._reorder:\n            self._callback(*args)\n            return\n        if self._next_expected is not None and sequence < self._next_expected:\n            print(\"Dropping out of order packet, seq=%d\" % sequence)\n            return\n        self._out_of_order.append((sequence, args))\n        self._out_of_order.sort(key=lambda x: x[0])\n        while len(self._out_of_order) > 0:\n            seq, args = self._out_of_order[0]\n            if self._next_expected is not None and seq != self._next_expected:\n                return\n            self._callback(*args)\n            self._out_of_order.pop(0)\n            self._next_expected = seq+1",
    "docstring": "Receive one packet\n\n        If the sequence number is one we've already seen before, it is dropped.\n\n        If it is not the next expected sequence number, it is put into the\n        _out_of_order queue to be processed once the holes in sequence number\n        are filled in.\n\n        Args:\n            sequence (int): The sequence number of the received packet\n            args (list): The list of packet contents that will be passed to callback\n                as callback(*args)"
  },
  {
    "code": "def list_buckets(\n        self,\n        max_results=None,\n        page_token=None,\n        prefix=None,\n        projection=\"noAcl\",\n        fields=None,\n        project=None,\n    ):\n        if project is None:\n            project = self.project\n        if project is None:\n            raise ValueError(\"Client project not set:  pass an explicit project.\")\n        extra_params = {\"project\": project}\n        if prefix is not None:\n            extra_params[\"prefix\"] = prefix\n        extra_params[\"projection\"] = projection\n        if fields is not None:\n            extra_params[\"fields\"] = fields\n        return page_iterator.HTTPIterator(\n            client=self,\n            api_request=self._connection.api_request,\n            path=\"/b\",\n            item_to_value=_item_to_bucket,\n            page_token=page_token,\n            max_results=max_results,\n            extra_params=extra_params,\n        )",
    "docstring": "Get all buckets in the project associated to the client.\n\n        This will not populate the list of blobs available in each\n        bucket.\n\n        .. literalinclude:: snippets.py\n            :start-after: [START list_buckets]\n            :end-before: [END list_buckets]\n\n        This implements \"storage.buckets.list\".\n\n        :type max_results: int\n        :param max_results: Optional. The maximum number of buckets to return.\n\n        :type page_token: str\n        :param page_token:\n            Optional. If present, return the next batch of buckets, using the\n            value, which must correspond to the ``nextPageToken`` value\n            returned in the previous response.  Deprecated: use the ``pages``\n            property of the returned iterator instead of manually passing the\n            token.\n\n        :type prefix: str\n        :param prefix: Optional. Filter results to buckets whose names begin\n                       with this prefix.\n\n        :type projection: str\n        :param projection:\n            (Optional) Specifies the set of properties to return. If used, must\n            be 'full' or 'noAcl'. Defaults to 'noAcl'.\n\n        :type fields: str\n        :param fields:\n            (Optional) Selector specifying which fields to include in a partial\n            response. Must be a list of fields. For example to get a partial\n            response with just the next page token and the language of each\n            bucket returned: 'items/id,nextPageToken'\n\n        :type project: str\n        :param project: (Optional) the project whose buckets are to be listed.\n                        If not passed, uses the project set on the client.\n\n        :rtype: :class:`~google.api_core.page_iterator.Iterator`\n        :raises ValueError: if both ``project`` is ``None`` and the client's\n                            project is also ``None``.\n        :returns: Iterator of all :class:`~google.cloud.storage.bucket.Bucket`\n                  belonging to this project."
  },
  {
    "code": "def remote_pdb_handler(signum, frame):\n    try:\n        from remote_pdb import RemotePdb\n        rdb = RemotePdb(host=\"127.0.0.1\", port=0)\n        rdb.set_trace(frame=frame)\n    except ImportError:\n        log.warning(\n            \"remote_pdb unavailable.  Please install remote_pdb to \"\n            \"allow remote debugging.\"\n        )\n    signal.signal(signum, remote_pdb_handler)",
    "docstring": "Handler to drop us into a remote debugger upon receiving SIGUSR1"
  },
  {
    "code": "def _read_header(filename):\n    with filename.open('rb') as f:\n        h = f.read(HDR_LENGTH).decode()\n        header = {}\n        for line in h.split('\\n'):\n            if '=' in line:\n                key, value = line.split(' = ')\n                key = key.strip()[7:]\n                value = value.strip()[:-1]\n                header[key] = value\n    return header",
    "docstring": "Read the text header for each file\n\n    Parameters\n    ----------\n    channel_file : Path\n        path to single filename with the header\n\n    Returns\n    -------\n    dict\n        header"
  },
  {
    "code": "def make_response(response):\n    if isinstance(response, unicode) or \\\n            isinstance(response, str):\n        response = (response, 'text/html')\n    return response",
    "docstring": "Make response tuple\n\n    Potential features to be added\n      - Parameters validation"
  },
  {
    "code": "def delete_vlan_entry(self, vlan_id):\n        with self.session.begin(subtransactions=True):\n            try:\n                self.session.query(ucsm_model.PortProfile).filter_by(\n                    vlan_id=vlan_id).delete()\n            except orm.exc.NoResultFound:\n                return",
    "docstring": "Deletes entry for a vlan_id if it exists."
  },
  {
    "code": "def has_group(user, group_name):\r\n    if user.groups.filter(name=group_name).exists():\r\n        return True\r\n    return False",
    "docstring": "This allows specification group-based permissions in templates.\r\n    In most instances, creating model-based permissions and giving\r\n    them to the desired group is preferable."
  },
  {
    "code": "def getFilepaths(self, filename):\n        return (os.path.join(os.environ['HOME'], filename),\n                os.path.join(self.mackup.mackup_folder, filename))",
    "docstring": "Get home and mackup filepaths for given file\n\n        Args:\n            filename (str)\n\n        Returns:\n            home_filepath, mackup_filepath (str, str)"
  },
  {
    "code": "def get_sources(self, plate, plate_value, sources=None):\n        if sources is None:\n            sources = []\n        if self.sources:\n            for si, source in enumerate(self.sources):\n                if len(source.streams) == 1 and None in source.streams:\n                    sources.append(source.streams[None])\n                elif plate_value in source.streams:\n                    sources.append(source.streams[plate_value])\n                else:\n                    pass\n        if not plate.is_root:\n            parent_plate_value = tuple(pv for pv in plate_value if pv[0] != plate.meta_data_id)\n            sources = self.get_sources(plate.parent, parent_plate_value, sources)\n        return sources",
    "docstring": "Gets the source streams for a given plate value on a plate.\n        Also populates with source streams that are valid for the parent plates of this plate,\n        with the appropriate meta-data for the parent plate.\n\n        :param plate: The plate being operated on\n        :param plate_value: The specific plate value of interest\n        :param sources: The currently found sources (for recursion)\n        :return: The appropriate source streams\n        :type plate: Plate\n        :type plate_value: tuple\n        :type sources: list[Stream] | None"
  },
  {
    "code": "def _get_by_id(cls, id, parent=None, **ctx_options):\n    return cls._get_by_id_async(id, parent=parent, **ctx_options).get_result()",
    "docstring": "Returns an instance of Model class by ID.\n\n    This is really just a shorthand for Key(cls, id, ...).get().\n\n    Args:\n      id: A string or integer key ID.\n      parent: Optional parent key of the model to get.\n      namespace: Optional namespace.\n      app: Optional app ID.\n      **ctx_options: Context options.\n\n    Returns:\n      A model instance or None if not found."
  },
  {
    "code": "def deriv2(self,p):\n        numer = -(1 + 2 * self.alpha * p)\n        denom = (p + self.alpha * p**2)**2\n        return numer / denom",
    "docstring": "Second derivative of the negative binomial link function.\n\n        Parameters\n        ----------\n        p : array-like\n            Mean parameters\n\n        Returns\n        -------\n        g''(p) : array\n            The second derivative of the negative binomial transform link\n            function\n\n        Notes\n        -----\n        g''(x) = -(1+2*alpha*x)/(x+alpha*x^2)^2"
  },
  {
    "code": "def dewpoint_temperature(temp, hum):\n    assert(temp.shape == hum.shape)\n    vap_press = vapor_pressure(temp, hum)\n    positives = np.array(temp >= 273.15)\n    dewpoint_temp = temp.copy() * np.nan\n    dewpoint_temp[positives] = 243.12 * np.log(vap_press[positives] / 6.112) / (17.62 - np.log(vap_press[positives] / 6.112))\n    dewpoint_temp[~positives] = 272.62 * np.log(vap_press[~positives] / 6.112) / (22.46 - np.log(vap_press[~positives] / 6.112))\n    return dewpoint_temp + 273.15",
    "docstring": "computes the dewpoint temperature\n\n    Parameters\n    ----\n    temp :      temperature [K]\n    hum :       relative humidity\n    \n\n    Returns\n        dewpoint temperature in K"
  },
  {
    "code": "def __argument(self, ttype, tvalue):\n        if ttype in [\"multiline\", \"string\"]:\n            return self.__curcommand.check_next_arg(\"string\", tvalue.decode(\"utf-8\"))\n        if ttype in [\"number\", \"tag\"]:\n            return self.__curcommand.check_next_arg(ttype, tvalue.decode(\"ascii\"))\n        if ttype == \"left_bracket\":\n            self.__cstate = self.__stringlist\n            self.__curstringlist = []\n            self.__set_expected(\"string\")\n            return True\n        condition = (\n            ttype in [\"left_cbracket\", \"comma\"] and\n            self.__curcommand.non_deterministic_args\n        )\n        if condition:\n            self.__curcommand.reassign_arguments()\n            self.lexer.pos -= 1\n            return True\n        return False",
    "docstring": "Argument parsing method\n\n        This method acts as an entry point for 'argument' parsing.\n\n        Syntax:\n            string-list / number / tag\n\n        :param ttype: current token type\n        :param tvalue: current token value\n        :return: False if an error is encountered, True otherwise"
  },
  {
    "code": "def get(self):\n        data = dict()\n        for label, entry in zip(self.keys, self.values):\n            data[label.cget('text')] = entry.get()\n        return data",
    "docstring": "Retrieve the GUI elements for program use.\n\n        :return: a dictionary containing all \\\n        of the data from the key/value entries"
  },
  {
    "code": "def ListOf(element_type, element_none_value=None):\n    from pyws.functions.args.types import TypeFactory\n    element_type = TypeFactory(element_type)\n    return type(element_type.__name__ + 'List', (List,), {\n        'element_type': element_type,\n        'element_none_value': element_none_value})",
    "docstring": "This function creates a list type with element type ``element_type`` and an\n    empty element value ``element_none_value``.\n\n    >>> from pyws.functions.args import Integer, ListOf\n    >>> lst = ListOf(int)\n    >>> issubclass(lst, List)\n    True\n    >>> lst.__name__\n    'IntegerList'\n    >>> lst.element_type == Integer\n    True"
  },
  {
    "code": "def read_locations(filename):\n    data = ConfigParser()\n    if filename == '-':\n        data.read_file(sys.stdin)\n    else:\n        data.read(filename)\n    if not data.sections():\n        logging.debug('Config file is empty')\n    locations = {}\n    for name in data.sections():\n        if data.has_option(name, 'locator'):\n            latitude, longitude = utils.from_grid_locator(data.get(name,\n                                                                   'locator'))\n        else:\n            latitude = data.getfloat(name, 'latitude')\n            longitude = data.getfloat(name, 'longitude')\n        locations[name] = (latitude, longitude)\n    return locations",
    "docstring": "Pull locations from a user's config file.\n\n    Args:\n        filename (str): Config file to parse\n\n    Returns:\n        dict: List of locations from config file"
  },
  {
    "code": "def make_directory(path):\n        try:\n            makedirs(path)\n            logging.debug('Directory created: {0}'.format(path))\n        except OSError as e:\n            if e.errno != errno.EEXIST:\n                raise",
    "docstring": "Create directory if that not exists."
  },
  {
    "code": "def _get_description(self, args: Tuple, kwargs: Dict[str, Any]) -> Dict[str, Any]:\n        return {\n            'id': uuid1().hex,\n            'args': args,\n            'kwargs': kwargs,\n            'module': self._module_name,\n            'function': self.f.__name__,\n            'sender_hostname': socket.gethostname(),\n            'sender_pid': os.getpid(),\n            'sender_cmd': ' '.join(sys.argv),\n            'sender_timestamp': datetime.utcnow().isoformat()[:19],\n        }",
    "docstring": "Return the dictionary to be sent to the queue."
  },
  {
    "code": "def fromOctetString(cls, value, internalFormat=False, prepend=None, padding=0):\n        value = SizedInteger(integer.from_bytes(value) >> padding).setBitLength(len(value) * 8 - padding)\n        if prepend is not None:\n            value = SizedInteger(\n                (SizedInteger(prepend) << len(value)) | value\n            ).setBitLength(len(prepend) + len(value))\n        if not internalFormat:\n            value = cls(value)\n        return value",
    "docstring": "Create a |ASN.1| object initialized from a string.\n\n        Parameters\n        ----------\n        value: :class:`str` (Py2) or :class:`bytes` (Py3)\n            Text string like '\\\\\\\\x01\\\\\\\\xff' (Py2) or b'\\\\\\\\x01\\\\\\\\xff' (Py3)"
  },
  {
    "code": "def release(ctx, deploy=False, test=False, version=''):\n    if test:\n        run(\"python setup.py check\")\n        run(\"python setup.py register sdist upload --dry-run\")\n    if deploy:\n        run(\"python setup.py check\")\n        if version:\n            run(\"git checkout master\")\n            run(\"git tag -a v{ver} -m 'v{ver}'\".format(ver=version))\n            run(\"git push\")\n            run(\"git push origin --tags\")\n            run(\"python setup.py sdist bdist_wheel\")\n            run(\"twine upload --skip-existing dist/*\")\n    else:\n        print(\"- Have you updated the version?\")\n        print(\"- Have you updated CHANGELOG.md, README.md, and AUTHORS.md?\")\n        print(\"- Have you fixed any last minute bugs?\")\n        print(\"- Have you merged changes for release into the master branch?\")\n        print(\"If you answered yes to all of the above questions,\")\n        print(\"then run `inv release --deploy -vX.YY.ZZ` to:\")\n        print(\"- Checkout master\")\n        print(\"- Tag the git release with provided vX.YY.ZZ version\")\n        print(\"- Push the master branch and tags to repo\")",
    "docstring": "Tag release, run Travis-CI, and deploy to PyPI"
  },
  {
    "code": "def dumps(d, indent=4, spacer=\" \", quote='\"', newlinechar=\"\\n\", end_comment=False, **kwargs):\n    return _pprint(d, indent, spacer, quote, newlinechar, end_comment, **kwargs)",
    "docstring": "Output a Mapfile dictionary as a string\n\n    Parameters\n    ----------\n\n    d: dict\n        A Python dictionary based on the the mappyfile schema\n    indent: int\n        The number of ``spacer`` characters to indent structures in the Mapfile\n    spacer: string\n        The character to use for indenting structures in the Mapfile. Typically\n        spaces or tab characters (``\\\\t``)\n    quote: string\n        The quote character to use in the Mapfile (double or single quotes)\n    newlinechar: string\n        The character used to insert newlines in the Mapfile\n    end_comment: bool\n        Add a comment with the block type at each closing END\n        statement e.g. END # MAP\n\n    Returns\n    -------\n\n    string\n          The Mapfile as a string\n\n    Example\n    -------\n\n    To open a Mapfile from a string, and then print it back out\n    as a string using tabs::\n\n        s = '''MAP NAME \"TEST\" END'''\n\n        d = mappyfile.loads(s)\n        print(mappyfile.dumps(d, indent=1, spacer=\"\\\\t\"))"
  },
  {
    "code": "def collect_publications(self):\n        pubs = list(self.sub_publications)\n        for sub_tree in self.sub_trees:\n            pubs.extend(sub_tree.collect_publications())\n        return pubs",
    "docstring": "Recursively collect list of all publications referenced in this\n        tree and all sub-trees.\n\n        Returns:\n            list: List of UUID strings."
  },
  {
    "code": "def _combine_nt_vals(lst0_lstn, flds, dflt_null):\n    vals = []\n    for fld in flds:\n        fld_seen = False\n        for nt_curr in lst0_lstn:\n            if hasattr(nt_curr, fld):\n                vals.append(getattr(nt_curr, fld))\n                fld_seen = True\n                break\n        if fld_seen is False:\n            vals.append(dflt_null)\n    return vals",
    "docstring": "Given a list of lists of nts, return a single namedtuple."
  },
  {
    "code": "def value(self):\n        result = self._value\n        if result is None and self._svalue is not None:\n            try:\n                result = self._value = self.resolve()\n            except Exception as e:\n                reraise(\n                    Parameter.Error,\n                    Parameter.Error('Call the method \"resolve\" first.')\n                )\n        return result",
    "docstring": "Get parameter value.\n\n        If this cached value is None and this serialized value is not None,\n        calculate the new value from the serialized one.\n\n        :return: parameter value.\n        :raises: TypeError if serialized value is not an instance of self ptype\n            . ParserError if parsing step raised an error."
  },
  {
    "code": "def rsum(self, time_period: str, num_col: str=\"Number\", dateindex: str=None):\n\t\ttry:\n\t\t\tdf = self._resample_(\"sum\", time_period,\n\t\t\t\t\t\t\t\t num_col, dateindex)\n\t\t\tself.df = df\n\t\t\tif df is None:\n\t\t\t\tself.err(\"Can not sum data\")\n\t\texcept Exceptions as e:\n\t\t\tself.err(e, \"Can not sum data\")",
    "docstring": "Resample and add a sum the main dataframe to a time period\n\n\t\t:param time_period: unit + period: periods are Y, M, D, H, Min, S\n\t\t:param time_period: str\n\t\t:param num_col: number of the new column, defaults to \"Number\"\n\t\t:param num_col: str, optional\n\t\t:param dateindex: column name to use as date index, defaults to None\n\t\t:param dateindex: str, optional\n\n\t\t:example: ``ds.rsum(\"1D\")``"
  },
  {
    "code": "def _seek_to_extent(self, extent):\n        self._cdfp.seek(extent * self.pvd.logical_block_size())",
    "docstring": "An internal method to seek to a particular extent on the input ISO.\n\n        Parameters:\n         extent - The extent to seek to.\n        Returns:\n         Nothing."
  },
  {
    "code": "def port_manager(self):\n        if self._port_manager is None:\n            self._port_manager = PortManager.instance()\n        return self._port_manager",
    "docstring": "Returns the port manager.\n\n        :returns: Port manager"
  },
  {
    "code": "def pack(self):\n        self.headers.setdefault('content-length', len(self.body))\n        headerparts = (\"{0}:{1}\\n\".format(key, value)\n                       for key, value in self.headers.items())\n        return six.b(\"{0}\\n{1}\\n\".format(self.cmd, \"\".join(headerparts))) + (self.body if isinstance(self.body, six.binary_type) else six.b(self.body)) + six.b('\\x00')",
    "docstring": "Create a string representation from object state.\n\n        @return: The string (bytes) for this stomp frame.\n        @rtype: C{str}"
  },
  {
    "code": "def devices(self):\n        devices = []\n        count = self.lib.tdGetNumberOfDevices()\n        for i in range(count):\n            device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)\n            devices.append(device)\n        return devices",
    "docstring": "Return all known devices.\n\n        :return: list of :class:`Device` or :class:`DeviceGroup` instances."
  },
  {
    "code": "def run(self):\n        self._initialize_run()\n        stimuli = self.protocol_model.allTests()\n        self.acq_thread = threading.Thread(target=self._worker, \n                                           args=(stimuli,), )\n        if self.save_data:\n            info = {'calibration_used': self.calname, 'calibration_range': self.cal_frange}\n            self.datafile.set_metadata(self.current_dataset_name, info)\n        self.start_time = time.time()\n        self.last_tick = self.start_time - (self.interval/1000)\n        self.acq_thread.start()\n        return self.acq_thread",
    "docstring": "Runs the acquisition"
  },
  {
    "code": "def get_legacy_storage_path(self):\n        config_dir = os.path.dirname(\n            self.py3_wrapper.config.get(\"i3status_config_path\", \"/tmp\")\n        )\n        storage_path = os.path.join(config_dir, \"py3status.data\")\n        if os.path.exists(storage_path):\n            return storage_path\n        else:\n            return None",
    "docstring": "Detect and return existing legacy storage path."
  },
  {
    "code": "def _get_rest_doc(self, request, start_response):\n    api = request.body_json['api']\n    version = request.body_json['version']\n    generator = discovery_generator.DiscoveryGenerator(request=request)\n    services = [s for s in self._backend.api_services if\n                s.api_info.name == api and s.api_info.api_version == version]\n    doc = generator.pretty_print_config_to_json(services)\n    if not doc:\n      error_msg = ('Failed to convert .api to discovery doc for '\n                   'version %s of api %s') % (version, api)\n      _logger.error('%s', error_msg)\n      return util.send_wsgi_error_response(error_msg, start_response)\n    return self._send_success_response(doc, start_response)",
    "docstring": "Sends back HTTP response with API directory.\n\n    This calls start_response and returns the response body.  It will return\n    the discovery doc for the requested api/version.\n\n    Args:\n      request: An ApiRequest, the transformed request sent to the Discovery API.\n      start_response: A function with semantics defined in PEP-333.\n\n    Returns:\n      A string, the response body."
  },
  {
    "code": "def set_status(self, status):\n        self.status = status\n        for callback in self._update_status_callbacks:\n            callback(self)",
    "docstring": "Save the new status and call all defined callbacks"
  },
  {
    "code": "def __plain_bfs(adj, source):\n        seen = set()\n        nextlevel = {source}\n        while nextlevel:\n            thislevel = nextlevel\n            nextlevel = set()\n            for v in thislevel:\n                if v not in seen:\n                    yield v\n                    seen.add(v)\n                    nextlevel.update(adj[v])",
    "docstring": "modified NX fast BFS node generator"
  },
  {
    "code": "def compose_capability(base, *classes):\n    if _debug: compose_capability._debug(\"compose_capability %r %r\", base, classes)\n    if not issubclass(base, Collector):\n        raise TypeError(\"base must be a subclass of Collector\")\n    for cls in classes:\n        if not issubclass(cls, Capability):\n            raise TypeError(\"%s is not a Capability subclass\" % (cls,))\n    bases = (base,) + classes\n    name = base.__name__\n    for cls in classes:\n        name += '+' + cls.__name__\n    return type(name, bases, {})",
    "docstring": "Create a new class starting with the base and adding capabilities."
  },
  {
    "code": "def tableNames(self, dbName=None):\n        if dbName is None:\n            return [name for name in self._ssql_ctx.tableNames()]\n        else:\n            return [name for name in self._ssql_ctx.tableNames(dbName)]",
    "docstring": "Returns a list of names of tables in the database ``dbName``.\n\n        :param dbName: string, name of the database to use. Default to the current database.\n        :return: list of table names, in string\n\n        >>> sqlContext.registerDataFrameAsTable(df, \"table1\")\n        >>> \"table1\" in sqlContext.tableNames()\n        True\n        >>> \"table1\" in sqlContext.tableNames(\"default\")\n        True"
  },
  {
    "code": "def on(self, val=None):\n        if val is False:\n            raise ParameterError(\"Turning the ValuedParameter on with value \"\n                                 \"False is the same as turning it off. Use \"\n                                 \"another value.\")\n        elif self.IsPath:\n            self.Value = FilePath(val)\n        else:\n            self.Value = val",
    "docstring": "Turns the MixedParameter ON by setting its Value to val\n\n        An attempt to turn the parameter on with value 'False' will result\n            in an error, since this is the same as turning the parameter off.\n\n        Turning the MixedParameter ON without a value or with value 'None'\n            will let the parameter behave as a flag."
  },
  {
    "code": "def add_paths_argument(cls, group, argname, dest=None, help_=None):\n        prefixed = '%s-%s' % (cls.argument_prefix, argname)\n        if dest is None:\n            dest = prefixed.replace('-', '_')\n            final_dest = dest[len(cls.argument_prefix) + 1:]\n        else:\n            final_dest = dest\n            dest = '%s_%s' % (cls.argument_prefix, dest)\n        group.add_argument('--%s' % prefixed, action='store', nargs='+',\n                           dest=dest, help=help_)\n        cls.paths_arguments[dest] = final_dest",
    "docstring": "Subclasses may call this to expose a paths argument.\n\n        Args:\n            group: arparse.ArgumentGroup, the extension argument group\n            argname: str, the name of the argument, will be namespaced.\n            dest: str, similar to the `dest` argument of\n                `argparse.ArgumentParser.add_argument`, will be namespaced.\n            help_: str, similar to the `help` argument of\n                `argparse.ArgumentParser.add_argument`."
  },
  {
    "code": "def items(self):\n        request = get(str(self.url), headers={'User-Agent' : \"Magic Browser\",\"origin_req_host\" : \"thepiratebay.se\"})\n        root = html.fromstring(request.text)\n        items = [self._build_torrent(row) for row in\n                 self._get_torrent_rows(root)]\n        for item in items:\n            yield item",
    "docstring": "Request URL and parse response. Yield a ``Torrent`` for every torrent\n        on page."
  },
  {
    "code": "def local_scope(self):\n        self.scope = self.scope.new_child()\n        try:\n            yield self.scope\n        finally:\n            self.scope = self.scope.parents",
    "docstring": "Assign symbols to local variables."
  },
  {
    "code": "def main(argv):\n  p = argparse.ArgumentParser()\n  p.add_argument('-s', '--scope', nargs='+')\n  p.add_argument('-o', '--oauth-service', default='google')\n  p.add_argument('-i', '--client-id')\n  p.add_argument('-x', '--client-secret')\n  p.add_argument('-r', '--redirect-uri')\n  p.add_argument('-f', '--client-secrets')\n  args = p.parse_args(argv)\n  client_args = (args.client_id, args.client_secret, args.client_id)\n  if any(client_args) and not all(client_args):\n    print('Must provide none of client-id, client-secret and redirect-uri;'\n          ' or all of them.')\n    p.print_usage()\n    return 1\n  print args.scope\n  if not args.scope:\n    print('Scope must be provided.')\n    p.print_usage()\n    return 1\n  config = WizardClientConfig()\n  config.scope = ' '.join(args.scope)\n  print(run_local(UserOAuth2(config))['access_token'])\n  return 0",
    "docstring": "Entry point for command line script to perform OAuth 2.0."
  },
  {
    "code": "def compute_hash(func, string):\n    h = func()\n    h.update(string)\n    return h.hexdigest()",
    "docstring": "compute hash of string using given hash function"
  },
  {
    "code": "def _split_repo_str(repo):\n    split = sourceslist.SourceEntry(repo)\n    return split.type, split.architectures, split.uri, split.dist, split.comps",
    "docstring": "Return APT source entry as a tuple."
  },
  {
    "code": "def intersect(self, range_):\n        self.solver.intersection_broad_tests_count += 1\n        if range_.is_any():\n            return self\n        if self.solver.optimised:\n            if range_ in self.been_intersected_with:\n                return self\n        if self.pr:\n            self.pr.passive(\"intersecting %s wrt range '%s'...\", self, range_)\n        self.solver.intersection_tests_count += 1\n        with self.solver.timed(self.solver.intersection_time):\n            entries = [x for x in self.entries if x.version in range_]\n        if not entries:\n            return None\n        elif len(entries) < len(self.entries):\n            copy_ = self._copy(entries)\n            copy_.been_intersected_with.add(range_)\n            return copy_\n        else:\n            self.been_intersected_with.add(range_)\n            return self",
    "docstring": "Remove variants whose version fall outside of the given range."
  },
  {
    "code": "def unsigned_request(self, path, payload=None):\n    headers = {\"content-type\": \"application/json\", \"accept\": \"application/json\", \"X-accept-version\": \"2.0.0\"}\n    try:\n      if payload:\n        response = requests.post(self.uri + path, verify=self.verify, data=json.dumps(payload), headers=headers)\n      else:\n        response = requests.get(self.uri + path, verify=self.verify, headers=headers)\n    except Exception as pro:\n      raise BitPayConnectionError('Connection refused')\n    return response",
    "docstring": "generic bitpay usigned wrapper\n    passing a payload will do a POST, otherwise a GET"
  },
  {
    "code": "def command_line_runner():\n    parser = get_parser()\n    args = vars(parser.parse_args())\n    if args['version']:\n        print(__version__)\n        return\n    if args['clear_cache']:\n        utils.clear_cache()\n        print('Cleared {0}.'.format(utils.CACHE_DIR))\n        return\n    if not args['query']:\n        parser.print_help()\n        return\n    if not os.getenv('SCRAPE_DISABLE_CACHE'):\n        utils.enable_cache()\n    if os.getenv('SCRAPE_DISABLE_IMGS'):\n        args['no_images'] = True\n    prompt_filetype(args)\n    prompt_save_images(args)\n    scrape(args)",
    "docstring": "Handle command-line interaction."
  },
  {
    "code": "def _firestore_api(self):\n        if self._firestore_api_internal is None:\n            self._firestore_api_internal = firestore_client.FirestoreClient(\n                credentials=self._credentials\n            )\n        return self._firestore_api_internal",
    "docstring": "Lazy-loading getter GAPIC Firestore API.\n\n        Returns:\n            ~.gapic.firestore.v1beta1.firestore_client.FirestoreClient: The\n            GAPIC client with the credentials of the current client."
  },
  {
    "code": "def request_halt(self, req, msg):\n        f = Future()\n        @gen.coroutine\n        def _halt():\n            req.reply(\"ok\")\n            yield gen.moment\n            self.stop(timeout=None)\n            raise AsyncReply\n        self.ioloop.add_callback(lambda: chain_future(_halt(), f))\n        return f",
    "docstring": "Halt the device server.\n\n        Returns\n        -------\n        success : {'ok', 'fail'}\n            Whether scheduling the halt succeeded.\n\n        Examples\n        --------\n        ::\n\n            ?halt\n            !halt ok"
  },
  {
    "code": "def get_devices(self):\n        devices = []\n        for element in self.get_device_elements():\n            device = FritzhomeDevice(self, node=element)\n            devices.append(device)\n        return devices",
    "docstring": "Get the list of all known devices."
  },
  {
    "code": "def retrieve_all(self, subset=None):\n        get_object = self.factory.get_object\n        obj_class = self.obj_class\n        full_objects = [get_object(obj_class, list_obj.id, subset) for list_obj\n                        in self]\n        return JSSObjectList(self.factory, obj_class, full_objects)",
    "docstring": "Return a list of all JSSListData elements as full JSSObjects.\n\n        This can take a long time given a large number of objects,\n        and depending on the size of each object. Subsetting to only\n        include the data you need can improve performance.\n\n        Args:\n            subset: For objects which support it, a list of sub-tags to\n                request, or an \"&\" delimited string, (e.g.\n                \"general&purchasing\").  Default to None."
  },
  {
    "code": "def save(self, filename):\n        options = conf.lib.clang_defaultSaveOptions(self)\n        result = int(conf.lib.clang_saveTranslationUnit(self, filename,\n                                                        options))\n        if result != 0:\n            raise TranslationUnitSaveError(result,\n                'Error saving TranslationUnit.')",
    "docstring": "Saves the TranslationUnit to a file.\n\n        This is equivalent to passing -emit-ast to the clang frontend. The\n        saved file can be loaded back into a TranslationUnit. Or, if it\n        corresponds to a header, it can be used as a pre-compiled header file.\n\n        If an error occurs while saving, a TranslationUnitSaveError is raised.\n        If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means\n        the constructed TranslationUnit was not valid at time of save. In this\n        case, the reason(s) why should be available via\n        TranslationUnit.diagnostics().\n\n        filename -- The path to save the translation unit to."
  },
  {
    "code": "def mutualReceptions(self, idA, idB):\n        AB = self.receives(idA, idB)\n        BA = self.receives(idB, idA)\n        return [(a,b) for a in AB for b in BA]",
    "docstring": "Returns all pairs of dignities in mutual reception."
  },
  {
    "code": "def parse_problem(self, problem_content):\n        del problem_content[\"@order\"]\n        return self.task_factory.get_problem_types().get(problem_content[\"type\"]).parse_problem(problem_content)",
    "docstring": "Parses a problem, modifying some data"
  },
  {
    "code": "def _autodiscover(self):\n        if not getattr(self, '_registerable_class', None):\n            raise ImproperlyConfigured('You must set a '\n                                       '\"_registerable_class\" property '\n                                       'in order to use autodiscovery.')\n        for mod_name in ('dashboard', 'panel'):\n            for app in settings.INSTALLED_APPS:\n                mod = import_module(app)\n                try:\n                    before_import_registry = copy.copy(self._registry)\n                    import_module('%s.%s' % (app, mod_name))\n                except Exception:\n                    self._registry = before_import_registry\n                    if module_has_submodule(mod, mod_name):\n                        raise",
    "docstring": "Discovers modules to register from ``settings.INSTALLED_APPS``.\n\n        This makes sure that the appropriate modules get imported to register\n        themselves with Horizon."
  },
  {
    "code": "def load_tag_library(libname):\n    from django.template.backends.django import get_installed_libraries\n    from django.template.library import InvalidTemplateLibrary\n    try:\n        lib = get_installed_libraries()[libname]\n        lib = importlib.import_module(lib).register\n        return lib\n    except (InvalidTemplateLibrary, KeyError):\n        return None",
    "docstring": "Load a templatetag library on multiple Django versions.\n\n    Returns None if the library isn't loaded."
  },
  {
    "code": "def _get_generic_schema(self):\n        schema = Schema(\n            identifier=ID(stored=True),\n            type=ID(stored=True),\n            name=NGRAM(phrase=True, stored=True, minsize=2, maxsize=8))\n        return schema",
    "docstring": "Returns whoosh's generic schema."
  },
  {
    "code": "def spin1x_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s):\n    phi1 = phi1_from_phi_a_phi_s(phi_a, phi_s)\n    return xi1 * numpy.cos(phi1)",
    "docstring": "Returns x-component spin for primary mass."
  },
  {
    "code": "def serialize(\n            self,\n            value,\n            state\n    ):\n        if not value and self.required:\n            state.raise_error(\n                MissingValue, 'Missing required aggregate \"{}\"'.format(self.element_path)\n            )\n        start_element, end_element = _element_path_create_new(self.element_path)\n        self._serialize(end_element, value, state)\n        return start_element",
    "docstring": "Serialize the value to a new element and return the element."
  },
  {
    "code": "def upgrade_account(self, account=None, **kwargs):\n        if not account:\n            if \"default_account\" in self.config:\n                account = self.config[\"default_account\"]\n        if not account:\n            raise ValueError(\"You need to provide an account\")\n        account = Account(account, blockchain_instance=self)\n        op = operations.Account_upgrade(\n            **{\n                \"fee\": {\"amount\": 0, \"asset_id\": \"1.3.0\"},\n                \"account_to_upgrade\": account[\"id\"],\n                \"upgrade_to_lifetime_member\": True,\n                \"prefix\": self.prefix,\n            }\n        )\n        return self.finalizeOp(op, account[\"name\"], \"active\", **kwargs)",
    "docstring": "Upgrade an account to Lifetime membership\n\n            :param str account: (optional) the account to allow access\n                to (defaults to ``default_account``)"
  },
  {
    "code": "def add(workflow_definition: dict, templates_root: str):\n    schema_path = join(dirname(__file__), 'schema', 'workflow_definition.json')\n    with open(schema_path, 'r') as file:\n        schema = json.loads(file.read())\n    jsonschema.validate(workflow_definition, schema)\n    _id = workflow_definition['id']\n    _version = workflow_definition['version']\n    _load_templates(workflow_definition, templates_root)\n    workflow_id = workflow_definition['id']\n    version = workflow_definition['version']\n    name = \"workflow_definitions:{}:{}\".format(workflow_id, version)\n    if DB.get_keys(name):\n        raise KeyError('Workflow definition already exists: {}'.format(name))\n    DB.save_dict(name, workflow_definition, hierarchical=False)",
    "docstring": "Add a workflow definition to the Configuration Database.\n\n    Templates are expected to be found in a directory tree with the following\n    structure:\n\n        - workflow_id:\n            |- workflow_version\n                |- stage_id\n                    |- stage_version\n                        |- <templates>\n\n    Args:\n        workflow_definition (dict): Workflow definition.\n        templates_root (str): Workflow templates root path"
  },
  {
    "code": "def to_hg_scheme_url(cls, url):\n        regexes = cls._get_url_scheme_regexes()\n        for scheme_key, pattern, regex in regexes:\n            match = regex.match(url)\n            if match is not None:\n                groups = match.groups()\n                if len(groups) == 2:\n                    return u''.join(\n                        scheme_key,\n                        '://',\n                        pattern.replace('{1}', groups[0]),\n                        groups[1])\n                elif len(groups) == 1:\n                    return u''.join(\n                        scheme_key,\n                        '://',\n                        pattern,\n                        groups[0])",
    "docstring": "Convert a URL to local mercurial URL schemes\n\n        Args:\n            url (str): URL to map to local mercurial URL schemes\n\n        example::\n\n            # schemes.gh = git://github.com/\n            >> remote_url = git://github.com/westurner/dotfiles'\n            >> to_hg_scheme_url(remote_url)\n            << gh://westurner/dotfiles"
  },
  {
    "code": "def get_repo_parent(path):\n    if is_repo(path):\n        return Local(path)\n    elif not os.path.isdir(path):\n        _rel = ''\n        while path and path != '/':\n            if is_repo(path):\n                return Local(path)\n            else:\n                _rel = os.path.join(os.path.basename(path), _rel)\n                path = os.path.dirname(path)\n        return path",
    "docstring": "Returns parent repo or input path if none found.\n\n    :return: grit.Local or path"
  },
  {
    "code": "def sortByIndex(self, index):\r\n        self.table_level.horizontalHeader().setSortIndicatorShown(True)\r\n        sort_order = self.table_level.horizontalHeader().sortIndicatorOrder()\r\n        self.table_index.model().sort(index, sort_order)\r\n        self._sort_update()",
    "docstring": "Implement a Index sort."
  },
  {
    "code": "def __log_number_of_constants(self):\n        n_id = len(self._labels)\n        n_widths = len(self._constants) - n_id\n        self._io.writeln('')\n        self._io.text('Number of constants based on column widths: {0}'.format(n_widths))\n        self._io.text('Number of constants based on database IDs : {0}'.format(n_id))",
    "docstring": "Logs the number of constants generated."
  },
  {
    "code": "def get_geotiff_area_def(filename, crs):\n    from osgeo import gdal\n    from pyresample.geometry import AreaDefinition\n    from pyresample.utils import proj4_str_to_dict\n    fid = gdal.Open(filename)\n    geo_transform = fid.GetGeoTransform()\n    pcs_id = fid.GetProjection().split('\"')[1]\n    min_x = geo_transform[0]\n    max_y = geo_transform[3]\n    x_size = fid.RasterXSize\n    y_size = fid.RasterYSize\n    max_x = min_x + geo_transform[1] * x_size\n    min_y = max_y + geo_transform[5] * y_size\n    area_extent = [min_x, min_y, max_x, max_y]\n    area_def = AreaDefinition('geotiff_area', pcs_id, pcs_id,\n                              proj4_str_to_dict(crs),\n                              x_size, y_size, area_extent)\n    return area_def",
    "docstring": "Read area definition from a geotiff."
  },
  {
    "code": "def masked_middle_mfcc(self):\n        begin, end = self._masked_middle_begin_end()\n        return (self.masked_mfcc)[:, begin:end]",
    "docstring": "Return the MFCC speech frames\n        in the MIDDLE portion of the wave.\n\n        :rtype: :class:`numpy.ndarray` (2D)"
  },
  {
    "code": "async def get_speaker_settings(self) -> List[Setting]:\n        speaker_settings = await self.services[\"audio\"][\"getSpeakerSettings\"]({})\n        return [Setting.make(**x) for x in speaker_settings]",
    "docstring": "Return speaker settings."
  },
  {
    "code": "def exists(self):\n        client = self._instance._client\n        try:\n            client.instance_admin_client.get_cluster(name=self.name)\n            return True\n        except NotFound:\n            return False",
    "docstring": "Check whether the cluster already exists.\n\n        For example:\n\n        .. literalinclude:: snippets.py\n            :start-after: [START bigtable_check_cluster_exists]\n            :end-before: [END bigtable_check_cluster_exists]\n\n        :rtype: bool\n        :returns: True if the table exists, else False."
  },
  {
    "code": "def get_owner_asset_ids(self, address):\n        block_filter = self._get_event_filter(owner=address)\n        log_items = block_filter.get_all_entries(max_tries=5)\n        did_list = []\n        for log_i in log_items:\n            did_list.append(id_to_did(log_i.args['_did']))\n        return did_list",
    "docstring": "Get the list of assets owned by an address owner.\n\n        :param address: ethereum account address, hex str\n        :return:"
  },
  {
    "code": "def people(self):\n        if self.cache['people']: return self.cache['people']\n        people_xml = self.bc.people_within_project(self.id)\n        for person_node in ET.fromstring(people_xml).findall('person'):\n            p = Person(person_node)\n            self.cache['people'][p.id] = p\n        return self.cache['people']",
    "docstring": "Dictionary of people on the project, keyed by id"
  },
  {
    "code": "def get_methods(*objs):\n    return set(\n        attr\n        for obj in objs\n        for attr in dir(obj)\n        if not attr.startswith('_') and callable(getattr(obj, attr))\n    )",
    "docstring": "Return the names of all callable attributes of an object"
  },
  {
    "code": "def reference(cls, value):\n        from sqlpuzzle._common.utils import force_text\n        value = force_text(value)\n        parts = re.split(r'{quote}([^{quote}]+){quote}|\\.'.format(quote=cls.reference_quote), value)\n        parts = ('{quote}{i}{quote}'.format(quote=cls.reference_quote, i=i) if i != '*' else i for i in parts if i)\n        return '.'.join(parts)",
    "docstring": "Convert as reference on column.\n        table => \"table\"\n        table.column => \"table\".\"column\"\n        db.table.column => \"db\".\"table\".\"column\"\n        table.\"col.umn\" => \"table\".\"col.umn\"\n        \"table\".\"col.umn\" => \"table\".\"col.umn\""
  },
  {
    "code": "def connection_factory_absent(name, both=True, server=None):\n    ret = {'name': name, 'result': None, 'comment': None, 'changes': {}}\n    pool_name = '{0}-Connection-Pool'.format(name)\n    pool_ret = _do_element_absent(pool_name, 'connector_c_pool', {'cascade': both}, server)\n    if not pool_ret['error']:\n        if __opts__['test'] and pool_ret['delete']:\n            ret['comment'] = 'Connection Factory set to be deleted'\n        elif pool_ret['delete']:\n            ret['result'] = True\n            ret['comment'] = 'Connection Factory deleted'\n        else:\n            ret['result'] = True\n            ret['comment'] = 'Connection Factory doesn\\'t exist'\n    else:\n        ret['result'] = False\n        ret['comment'] = 'Error: {0}'.format(pool_ret['error'])\n    return ret",
    "docstring": "Ensures the transaction factory is absent.\n\n    name\n        Name of the connection factory\n\n    both\n        Delete both the pool and the resource, defaults to ``true``"
  },
  {
    "code": "def get_mailbox_stats(self):\n        resp = self.request_single('GetMailboxStats')\n        ret = {}\n        for k, v in resp.items():\n            ret[k] = int(v)\n        return ret",
    "docstring": "Get global stats about mailboxes\n\n        Parses <stats numMboxes=\"6\" totalSize=\"141077\"/>\n\n        :returns: dict with stats"
  },
  {
    "code": "def queryEx(self, viewcls, *args, **kwargs):\n        kwargs['itercls'] = viewcls\n        o = super(AsyncBucket, self).query(*args, **kwargs)\n        if not self.connected:\n            self.connect().addCallback(lambda x: o.start())\n        else:\n            o.start()\n        return o",
    "docstring": "Query a view, with the ``viewcls`` instance receiving events\n        of the query as they arrive.\n\n        :param type viewcls: A class (derived from :class:`AsyncViewBase`)\n          to instantiate\n\n        Other arguments are passed to the standard `query` method.\n\n        This functions exactly like the :meth:`~couchbase.asynchronous.AsyncBucket.query`\n        method, except it automatically schedules operations if the connection\n        has not yet been negotiated."
  },
  {
    "code": "def import_name(mod_name):\n    try:\n        mod_obj_old = sys.modules[mod_name]\n    except KeyError:\n        mod_obj_old = None\n    if mod_obj_old is not None:\n        return mod_obj_old\n    __import__(mod_name)\n    mod_obj = sys.modules[mod_name]\n    return mod_obj",
    "docstring": "Import a module by module name.\n\n    @param mod_name: module name."
  },
  {
    "code": "def login(self, username, *, token=None):\n\t\tself._username = username\n\t\tself._oauth(username, token=token)\n\t\treturn self.is_authenticated",
    "docstring": "Log in to Google Music.\n\n\t\tParameters:\n\t\t\tusername (str, Optional): Your Google Music username.\n\t\t\t\tUsed for keeping stored OAuth tokens for multiple accounts separate.\n\t\t\tdevice_id (str, Optional): A mobile device ID or music manager uploader ID.\n\t\t\t\tDefault: MAC address is used.\n\t\t\ttoken (dict, Optional): An OAuth token compatible with ``requests-oauthlib``.\n\n\t\tReturns:\n\t\t\tbool: ``True`` if successfully authenticated, ``False`` if not."
  },
  {
    "code": "def move(self, target, pos=None):\n        if self.outline != target.outline:\n            raise IntegrityError('Elements must be from the same outline!')\n        tree_manipulation.send(\n            sender=self.__class__,\n            instance=self,\n            action='move',\n            target_node_type=None,\n            target_node=target,\n            pos=pos\n        )\n        return super().move(target, pos)",
    "docstring": "An override of the treebeard api in order to send a signal in advance."
  },
  {
    "code": "def createmergerequest(self, project_id, sourcebranch, targetbranch,\n                           title, target_project_id=None, assignee_id=None):\n        data = {\n            'source_branch': sourcebranch,\n            'target_branch': targetbranch,\n            'title': title,\n            'assignee_id': assignee_id,\n            'target_project_id': target_project_id\n        }\n        request = requests.post(\n            '{0}/{1}/merge_requests'.format(self.projects_url, project_id),\n            data=data, headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)\n        if request.status_code == 201:\n            return request.json()\n        else:\n            return False",
    "docstring": "Create a new merge request.\n\n        :param project_id: ID of the project originating the merge request\n        :param sourcebranch: name of the branch to merge from\n        :param targetbranch: name of the branch to merge to\n        :param title: Title of the merge request\n        :param assignee_id: Assignee user ID\n        :return: dict of the new merge request"
  },
  {
    "code": "def fopenat_rw(base_fd, path):\n    return os.fdopen(openat(base_fd, path, os.O_RDWR), 'rb+')",
    "docstring": "Does openat read-write, then does fdopen to get a file object"
  },
  {
    "code": "def db_create(name, character_set=None, collate=None, **connection_args):\n    if db_exists(name, **connection_args):\n        log.info('DB \\'%s\\' already exists', name)\n        return False\n    dbc = _connect(**connection_args)\n    if dbc is None:\n        return False\n    cur = dbc.cursor()\n    s_name = quote_identifier(name)\n    qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)\n    args = {}\n    if character_set is not None:\n        qry += ' CHARACTER SET %(character_set)s'\n        args['character_set'] = character_set\n    if collate is not None:\n        qry += ' COLLATE %(collate)s'\n        args['collate'] = collate\n    qry += ';'\n    try:\n        if _execute(cur, qry, args):\n            log.info('DB \\'%s\\' created', name)\n            return True\n    except MySQLdb.OperationalError as exc:\n        err = 'MySQL Error {0}: {1}'.format(*exc.args)\n        __context__['mysql.error'] = err\n        log.error(err)\n    return False",
    "docstring": "Adds a databases to the MySQL server.\n\n    name\n        The name of the database to manage\n\n    character_set\n        The character set, if left empty the MySQL default will be used\n\n    collate\n        The collation, if left empty the MySQL default will be used\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' mysql.db_create 'dbname'\n        salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'"
  },
  {
    "code": "def from_tree(cls, repo, *treeish, **kwargs):\n        if len(treeish) == 0 or len(treeish) > 3:\n            raise ValueError(\"Please specify between 1 and 3 treeish, got %i\" % len(treeish))\n        arg_list = []\n        if len(treeish) > 1:\n            arg_list.append(\"--reset\")\n            arg_list.append(\"--aggressive\")\n        tmp_index = tempfile.mktemp('', '', repo.git_dir)\n        arg_list.append(\"--index-output=%s\" % tmp_index)\n        arg_list.extend(treeish)\n        index_handler = TemporaryFileSwap(join_path_native(repo.git_dir, 'index'))\n        try:\n            repo.git.read_tree(*arg_list, **kwargs)\n            index = cls(repo, tmp_index)\n            index.entries\n            del(index_handler)\n        finally:\n            if osp.exists(tmp_index):\n                os.remove(tmp_index)\n        return index",
    "docstring": "Merge the given treeish revisions into a new index which is returned.\n        The original index will remain unaltered\n\n        :param repo:\n            The repository treeish are located in.\n\n        :param treeish:\n            One, two or three Tree Objects, Commits or 40 byte hexshas. The result\n            changes according to the amount of trees.\n            If 1 Tree is given, it will just be read into a new index\n            If 2 Trees are given, they will be merged into a new index using a\n            two way merge algorithm. Tree 1 is the 'current' tree, tree 2 is the 'other'\n            one. It behaves like a fast-forward.\n            If 3 Trees are given, a 3-way merge will be performed with the first tree\n            being the common ancestor of tree 2 and tree 3. Tree 2 is the 'current' tree,\n            tree 3 is the 'other' one\n\n        :param kwargs:\n            Additional arguments passed to git-read-tree\n\n        :return:\n            New IndexFile instance. It will point to a temporary index location which\n            does not exist anymore. If you intend to write such a merged Index, supply\n            an alternate file_path to its 'write' method.\n\n        :note:\n            In the three-way merge case, --aggressive will be specified to automatically\n            resolve more cases in a commonly correct manner. Specify trivial=True as kwarg\n            to override that.\n\n            As the underlying git-read-tree command takes into account the current index,\n            it will be temporarily moved out of the way to assure there are no unsuspected\n            interferences."
  },
  {
    "code": "def create(self, Name, Subject, HtmlBody=None, TextBody=None, Alias=None):\n        assert TextBody or HtmlBody, \"Provide either email TextBody or HtmlBody or both\"\n        data = {\"Name\": Name, \"Subject\": Subject, \"HtmlBody\": HtmlBody, \"TextBody\": TextBody, \"Alias\": Alias}\n        return self._init_instance(self.call(\"POST\", \"/templates\", data=data))",
    "docstring": "Creates a template.\n\n        :param Name: Name of template\n        :param Subject: The content to use for the Subject when this template is used to send email.\n        :param HtmlBody: The content to use for the HtmlBody when this template is used to send email.\n        :param TextBody: The content to use for the HtmlBody when this template is used to send email.\n        :return:"
  },
  {
    "code": "def _process_change(self, server_description):\n        td_old = self._description\n        if self._publish_server:\n            old_server_description = td_old._server_descriptions[\n                server_description.address]\n            self._events.put((\n                self._listeners.publish_server_description_changed,\n                (old_server_description, server_description,\n                 server_description.address, self._topology_id)))\n        self._description = updated_topology_description(\n            self._description, server_description)\n        self._update_servers()\n        self._receive_cluster_time_no_lock(server_description.cluster_time)\n        if self._publish_tp:\n            self._events.put((\n                self._listeners.publish_topology_description_changed,\n                (td_old, self._description, self._topology_id)))\n        self._condition.notify_all()",
    "docstring": "Process a new ServerDescription on an opened topology.\n\n        Hold the lock when calling this."
  },
  {
    "code": "def stop(self):\n        yield from self._stop_ubridge()\n        if self._nvram_watcher:\n            self._nvram_watcher.close()\n            self._nvram_watcher = None\n        if self._telnet_server:\n            self._telnet_server.close()\n            self._telnet_server = None\n        if self.is_running():\n            self._terminate_process_iou()\n            if self._iou_process.returncode is None:\n                try:\n                    yield from gns3server.utils.asyncio.wait_for_process_termination(self._iou_process, timeout=3)\n                except asyncio.TimeoutError:\n                    if self._iou_process.returncode is None:\n                        log.warning(\"IOU process {} is still running... killing it\".format(self._iou_process.pid))\n                        try:\n                            self._iou_process.kill()\n                        except ProcessLookupError:\n                            pass\n            self._iou_process = None\n        self._started = False\n        self.save_configs()",
    "docstring": "Stops the IOU process."
  },
  {
    "code": "def mul(name, num, minimum=0, maximum=0, ref=None):\n    return calc(\n        name=name,\n        num=num,\n        oper='mul',\n        minimum=minimum,\n        maximum=maximum,\n        ref=ref\n    )",
    "docstring": "Multiplies together the ``num`` most recent values. Requires a list.\n\n    USAGE:\n\n    .. code-block:: yaml\n\n        foo:\n          calc.mul:\n            - name: myregentry\n            - num: 5"
  },
  {
    "code": "def get_activity_comments(self, activity_id, markdown=False, limit=None):\n        result_fetcher = functools.partial(self.protocol.get, '/activities/{id}/comments',\n                                           id=activity_id, markdown=int(markdown))\n        return BatchedResultsIterator(entity=model.ActivityComment,\n                                      bind_client=self,\n                                      result_fetcher=result_fetcher,\n                                      limit=limit)",
    "docstring": "Gets the comments for an activity.\n\n        http://strava.github.io/api/v3/comments/#list\n\n        :param activity_id: The activity for which to fetch comments.\n        :type activity_id: int\n\n        :param markdown: Whether to include markdown in comments (default is false/filterout).\n        :type markdown: bool\n\n        :param limit: Max rows to return (default unlimited).\n        :type limit: int\n\n        :return: An iterator of :class:`stravalib.model.ActivityComment` objects.\n        :rtype: :class:`BatchedResultsIterator`"
  },
  {
    "code": "def destroy_list(self, list_id):\n        return List(tweepy_list_to_json(self._client.destroy_list(list_id=list_id)))",
    "docstring": "Destroy a list\n\n        :param list_id: list ID number\n        :return: The destroyed list object\n        :rtype: :class:`~responsebot.models.List`"
  },
  {
    "code": "def set_stripe_api_version(version=None, validate=True):\n\tversion = version or get_stripe_api_version()\n\tif validate:\n\t\tvalid = validate_stripe_api_version(version)\n\t\tif not valid:\n\t\t\traise ValueError(\"Bad stripe API version: {}\".format(version))\n\tstripe.api_version = version",
    "docstring": "Set the desired API version to use for Stripe requests.\n\n\t:param version: The version to set for the Stripe API.\n\t:type version: ``str``\n\t:param validate: If True validate the value for the specified version).\n\t:type validate: ``bool``"
  },
  {
    "code": "def which(path, jail=None, chroot=None, root=None, origin=False, quiet=False):\n    opts = ''\n    if quiet:\n        opts += 'q'\n    if origin:\n        opts += 'o'\n    cmd = _pkg(jail, chroot, root)\n    cmd.append('which')\n    if opts:\n        cmd.append('-' + opts)\n    cmd.append(path)\n    return __salt__['cmd.run'](\n        cmd,\n        output_loglevel='trace',\n        python_shell=False\n    )",
    "docstring": "Displays which package installed a specific file\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' pkg.which <file name>\n\n    jail\n        Perform the check in the specified jail\n\n        CLI Example:\n\n        .. code-block:: bash\n\n            salt '*' pkg.which <file name> jail=<jail name or id>\n\n    chroot\n        Perform the check in the specified chroot (ignored if ``jail`` is\n        specified)\n\n    root\n        Perform the check in the specified root (ignored if ``jail`` is\n        specified)\n\n        CLI Example:\n\n        .. code-block:: bash\n\n            salt '*' pkg.which <file name> chroot=/path/to/chroot\n\n\n    origin\n        Shows the origin of the package instead of name-version.\n\n        CLI Example:\n\n        .. code-block:: bash\n\n            salt '*' pkg.which <file name> origin=True\n\n    quiet\n        Quiet output.\n\n        CLI Example:\n\n        .. code-block:: bash\n\n            salt '*' pkg.which <file name> quiet=True"
  },
  {
    "code": "def set_shutter_level(self, level=0.0):\n        data = {\"channelIndex\": 1, \"deviceId\": self.id, \"shutterLevel\": level}\n        return self._restCall(\"device/control/setShutterLevel\", body=json.dumps(data))",
    "docstring": "sets the shutter level\n\n        Args:\n            level(float): the new level of the shutter. 0.0 = open, 1.0 = closed\n        Returns:\n            the result of the _restCall"
  },
  {
    "code": "def fq_merge(R1, R2):\n    c = itertools.cycle([1, 2, 3, 4])\n    for r1, r2 in zip(R1, R2):\n        n = next(c)\n        if n == 1:\n            pair = [[], []]\n        pair[0].append(r1.strip())\n        pair[1].append(r2.strip())\n        if n == 4:\n            yield pair",
    "docstring": "merge separate fastq files"
  },
  {
    "code": "def cut_from_chain(sciobj_model):\n    if _is_head(sciobj_model):\n        old_pid = sciobj_model.obsoletes.did\n        _cut_head_from_chain(sciobj_model)\n    elif _is_tail(sciobj_model):\n        old_pid = sciobj_model.obsoleted_by.did\n        _cut_tail_from_chain(sciobj_model)\n    else:\n        old_pid = sciobj_model.obsoleted_by.did\n        _cut_embedded_from_chain(sciobj_model)\n    _update_sid_to_last_existing_pid_map(old_pid)",
    "docstring": "Remove an object from a revision chain.\n\n    The object can be at any location in the chain, including the head or tail.\n\n    Preconditions:\n    - The object with the pid is verified to exist and to be a member of an\n    revision chain. E.g., with:\n\n    d1_gmn.app.views.asserts.is_existing_object(pid)\n    d1_gmn.app.views.asserts.is_in_revision_chain(pid)\n\n    Postconditions:\n    - The given object is a standalone object with empty obsoletes, obsoletedBy and\n      seriesId fields.\n    - The previously adjacent objects in the chain are adjusted to close any gap that\n      was created or remove dangling reference at the head or tail.\n    - If the object was the last object in the chain and the chain has a SID, the SID\n      reference is shifted over to the new last object in the chain."
  },
  {
    "code": "def getTriples(pointing):\n    sql=\"SELECT id FROM triples t join triple_members m ON t.id=m.triple\"\n    sql+=\" join bucket.exposure e on e.expnum=m.expnum \"\n    sql+=\" WHERE pointing=%s  group by id  order by e.expnum  \"\n    cfeps.execute(sql, ( pointing, ) )\n    return(cfeps.fetchall())",
    "docstring": "Get all triples of a specified pointing ID.\n\n    Defaults is to return a complete list triples."
  },
  {
    "code": "def _from_python_type(self, obj, field, pytype):\n        json_schema = {\n            'title': field.attribute or field.name,\n        }\n        for key, val in TYPE_MAP[pytype].items():\n            json_schema[key] = val\n        if field.dump_only:\n            json_schema['readonly'] = True\n        if field.default is not missing:\n            json_schema['default'] = field.default\n        metadata = field.metadata.get('metadata', {})\n        metadata.update(field.metadata)\n        for md_key, md_val in metadata.items():\n            if md_key == 'metadata':\n                continue\n            json_schema[md_key] = md_val\n        if isinstance(field, fields.List):\n            json_schema['items'] = self._get_schema_for_field(\n                obj, field.container\n            )\n        return json_schema",
    "docstring": "Get schema definition from python type."
  },
  {
    "code": "def load_model(model_name, epoch_num, data_shapes, label_shapes, label_names, gpus=''):\n    sym, arg_params, aux_params = mx.model.load_checkpoint(model_name, epoch_num)\n    mod = create_module(sym, data_shapes, label_shapes, label_names, gpus)\n    mod.set_params(\n        arg_params=arg_params,\n        aux_params=aux_params,\n        allow_missing=True\n    )\n    return mod",
    "docstring": "Returns a module loaded with the provided model.\n\n    Parameters\n    ----------\n    model_name: str\n        Prefix of the MXNet model name as stored on the local directory.\n\n    epoch_num : int\n        Epoch number of model we would like to load.\n\n    input_shape: tuple\n        The shape of the input data in the form of (batch_size, channels, height, width)\n\n    files: list of strings\n        List of URLs pertaining to files that need to be downloaded in order to use the model.\n\n    data_shapes: list of tuples.\n        List of tuples where each tuple is a pair of input variable name and its shape.\n\n    label_shapes: list of (str, tuple)\n        Typically is ``data_iter.provide_label``.\n\n    label_names: list of str\n        Name of the output labels in the MXNet symbolic graph.\n\n    gpus: str\n        Comma separated string of gpu ids on which inferences are executed. E.g. 3,5,6 would refer to GPUs 3, 5 and 6.\n        If empty, we use CPU.\n\n    Returns\n    -------\n    MXNet module"
  },
  {
    "code": "def prttex_summary_cnts_all(self, prt=sys.stdout):\n        cnts = self.get_cnts_levels_depths_recs(set(self.obo.values()))\n        self._prttex_summary_cnts(prt, cnts)",
    "docstring": "Print LaTeX format summary of level and depth counts for all active GO Terms."
  },
  {
    "code": "def createUsageReport(self,\n                          reportname,\n                          queries,\n                          metadata,\n                          since=\"LAST_DAY\",\n                          fromValue=None,\n                          toValue=None,\n                          aggregationInterval=None\n                          ):\n        url = self._url + \"/add\"\n        params = {\n            \"f\" : \"json\",\n            \"usagereport\": {\n            \"reportname\" : reportname,\n            \"since\" : since,\n            \"metadata\" : metadata}\n        }\n        if isinstance(queries, dict):\n            params[\"usagereport\"][\"queries\"] = [queries]\n        elif isinstance(queries, list):\n            params[\"usagereport\"][\"queries\"] = queries\n        if aggregationInterval is not None:\n            params[\"usagereport\"]['aggregationInterval'] = aggregationInterval\n        if since.lower() == \"custom\":\n            params[\"usagereport\"]['to'] = toValue\n            params[\"usagereport\"]['from'] = fromValue\n        res =  self._post(url=url,\n                             param_dict=params,\n                             securityHandler=self._securityHandler,\n                             proxy_port=self._proxy_port,\n                             proxy_url=self._proxy_url)\n        self.__init()\n        return res",
    "docstring": "Creates a new usage report. A usage report is created by submitting\n        a JSON representation of the usage report to this operation.\n\n        Inputs:\n           reportname - the unique name of the report\n           since - the time duration of the report. The supported values\n              are: LAST_DAY, LAST_WEEK, LAST_MONTH, LAST_YEAR, CUSTOM\n              LAST_DAY represents a time range spanning the previous 24\n                 hours.\n              LAST_WEEK represents a time range spanning the previous 7\n                 days.\n              LAST_MONTH represents a time range spanning the previous 30\n                 days.\n              LAST_YEAR represents a time range spanning the previous 365\n                 days.\n              CUSTOM represents a time range that is specified using the\n                 from and to parameters.\n           fromValue - optional value - The timestamp (milliseconds since\n              UNIX epoch, namely January 1, 1970, 00:00:00 GMT) for the\n              beginning period of the report. Only valid when since is\n              CUSTOM\n           toValue - optional value - The timestamp (milliseconds since\n              UNIX epoch, namely January 1, 1970, 00:00:00 GMT) for the\n              ending period of the report.Only valid when since is\n              CUSTOM.\n           aggregationInterval - Optional. Aggregation interval in minutes.\n              Server metrics are aggregated and returned for time slices\n              aggregated using the specified aggregation interval. The time\n              range for the report, specified using the since parameter\n              (and from and to when since is CUSTOM) is split into multiple\n              slices, each covering an aggregation interval. Server metrics\n              are then aggregated for each time slice and returned as data\n              points in the report data.\n              When the aggregationInterval is not specified, the following\n              defaults are used:\n                 LAST_DAY: 30 minutes\n                 LAST_WEEK: 4 hours\n                 LAST_MONTH: 24 hours\n                 LAST_YEAR: 1 week\n                 CUSTOM: 30 minutes up to 1 day, 4 hours up to 1 week, 1\n                 day up to 30 days, and 1 week for longer periods.\n             If the samplingInterval specified in Usage Reports Settings is\n             more than the aggregationInterval, the samplingInterval is\n             used instead.\n           queries - A list of queries for which to generate the report.\n              You need to specify the list as an array of JSON objects\n              representing the queries. Each query specifies the list of\n              metrics to be queries for a given set of resourceURIs.\n              The queries parameter has the following sub-parameters:\n                 resourceURIs - Comma separated list of resource URIs for\n                 which to report metrics. Specifies services or folders\n                 for which to gather metrics.\n                    The resourceURI is formatted as below:\n                       services/ - Entire Site\n                       services/Folder/  - Folder within a Site. Reports\n                         metrics aggregated across all services within that\n                         Folder and Sub-Folders.\n                       services/Folder/ServiceName.ServiceType - Service in\n                         a specified folder, for example:\n                         services/Map_bv_999.MapServer.\n                       services/ServiceName.ServiceType - Service in the\n                         root folder, for example: Map_bv_999.MapServer.\n                 metrics - Comma separated list of metrics to be reported.\n                   Supported metrics are:\n                    RequestCount - the number of requests received\n                    RequestsFailed - the number of requests that failed\n                    RequestsTimedOut - the number of requests that timed out\n                    RequestMaxResponseTime - the maximum response time\n                    RequestAvgResponseTime - the average response time\n                    ServiceActiveInstances - the maximum number of active\n                      (running) service instances sampled at 1 minute\n                      intervals, for a specified service\n           metadata - Can be any JSON Object. Typically used for storing\n              presentation tier data for the usage report, such as report\n              title, colors, line-styles, etc. Also used to denote\n              visibility in ArcGIS Server Manager for reports created with\n              the Administrator Directory. To make any report created in\n              the Administrator Directory visible to Manager, include\n              \"managerReport\":true in the metadata JSON object. When this\n              value is not set (default), reports are not visible in\n              Manager. This behavior can be extended to any client that\n              wants to interact with the Administrator Directory. Any\n              user-created value will need to be processed by the client.\n\n        Example:\n        >>> queryObj = [{\n           \"resourceURIs\": [\"services/Map_bv_999.MapServer\"],\n           \"metrics\": [\"RequestCount\"]\n        }]\n        >>> obj.createReport(\n           reportname=\"SampleReport\",\n           queries=queryObj,\n           metadata=\"This could be any String or JSON Object.\",\n           since=\"LAST_DAY\"\n        )"
  },
  {
    "code": "def wsgi(self, environ, start_response):\n        request = Request(environ)\n        ctx = Context(request)\n        try:\n            try:\n                response = self(request, ctx)\n                ctx._run_callbacks('finalize', (request, response))\n                response = response.conditional_to(request)\n            except HTTPException as e:\n                response = e.response\n            except Exception:\n                self.handle_error(request, ctx)\n                response = InternalServerError().response\n            response.add_callback(lambda: ctx._run_callbacks('close'))\n            return response(environ, start_response)\n        finally:\n            ctx._run_callbacks('teardown', log_errors=True)",
    "docstring": "Implements the mapper's WSGI interface."
  },
  {
    "code": "def save_boolean_setting(self, key, check_box):\n        set_setting(key, check_box.isChecked(), qsettings=self.settings)",
    "docstring": "Save boolean setting according to check_box state.\n\n        :param key: Key to retrieve setting value.\n        :type key: str\n\n        :param check_box: Check box to show and set the setting.\n        :type check_box: PyQt5.QtWidgets.QCheckBox.QCheckBox"
  },
  {
    "code": "def do_create_tool_item(self):\n        proxy = SpinToolItem(*self._args_for_toolitem)\n        self.connect_proxy(proxy)\n        return proxy",
    "docstring": "This is called by the UIManager when it is time to\n        instantiate the proxy"
  },
  {
    "code": "def set_locs(self, locs):\n        'Sets the locations of the ticks'\n        _check_implicitly_registered()\n        self.locs = locs\n        (vmin, vmax) = vi = tuple(self.axis.get_view_interval())\n        if vi != self.plot_obj.view_interval:\n            self.plot_obj.date_axis_info = None\n        self.plot_obj.view_interval = vi\n        if vmax < vmin:\n            (vmin, vmax) = (vmax, vmin)\n        self._set_default_format(vmin, vmax)",
    "docstring": "Sets the locations of the ticks"
  },
  {
    "code": "def location(args):\n    fastafile = args.fastafile\n    pwmfile = args.pwmfile\n    lwidth = args.width\n    if not lwidth:\n        f = Fasta(fastafile)\n        lwidth = len(f.items()[0][1])\n        f = None\n    jobs = []\n    motifs = pwmfile_to_motifs(pwmfile)\n    ids = [motif.id for motif in motifs]\n    if args.ids:\n        ids = args.ids.split(\",\")\n    n_cpus = int(MotifConfig().get_default_params()[\"ncpus\"])\n    pool = Pool(processes=n_cpus, maxtasksperchild=1000) \n    for motif in motifs:\n        if motif.id in ids:\n            outfile = os.path.join(\"%s_histogram\" % motif.id)\n            jobs.append(\n                    pool.apply_async(\n                        motif_localization, \n                        (fastafile,motif,lwidth,outfile, args.cutoff)\n                        ))\n    for job in jobs:\n        job.get()",
    "docstring": "Creates histrogram of motif location.\n\n    Parameters\n    ----------\n    args : argparse object\n        Command line arguments."
  },
  {
    "code": "def getFileObjects(self):\n        files = {'project-file': self,\n                 'mapping-table-file': self.mapTableFile,\n                 'channel-input-file': self.channelInputFile,\n                 'precipitation-file': self.precipFile,\n                 'storm-pipe-network-file': self.stormPipeNetworkFile,\n                 'hmet-file': self.hmetFile,\n                 'nwsrfs-file': self.nwsrfsFile,\n                 'orographic-gage-file': self.orographicGageFile,\n                 'grid-pipe-file': self.gridPipeFile,\n                 'grid-stream-file': self.gridStreamFile,\n                 'time-series-file': self.timeSeriesFiles,\n                 'projection-file': self.projectionFile,\n                 'replace-parameters-file': self.replaceParamFile,\n                 'replace-value-file': self.replaceValFile,\n                 'output-location-file': self.outputLocationFiles,\n                 'maps': self.maps,\n                 'link-node-datasets-file': self.linkNodeDatasets}\n        return files",
    "docstring": "Retrieve a dictionary of file objects.\n\n        This is a utility method that can be used to programmatically access the GsshaPy file objects. Use this method\n        in conjunction with the getFileKeys method to access only files that have been read into the database.\n\n        Returns:\n            dict: Dictionary with human readable keys and values of GsshaPy file object instances. Files that have not\n            been read into the database will have a value of None."
  },
  {
    "code": "def convert_to_match_query(ir_blocks):\n    output_block = ir_blocks[-1]\n    if not isinstance(output_block, ConstructResult):\n        raise AssertionError(u'Expected last IR block to be ConstructResult, found: '\n                             u'{} {}'.format(output_block, ir_blocks))\n    ir_except_output = ir_blocks[:-1]\n    folds, ir_except_output_and_folds = extract_folds_from_ir_blocks(ir_except_output)\n    global_operation_ir_blocks_tuple = _extract_global_operations(ir_except_output_and_folds)\n    global_operation_blocks, pruned_ir_blocks = global_operation_ir_blocks_tuple\n    if len(global_operation_blocks) > 1:\n        raise AssertionError(u'Received IR blocks with multiple global operation blocks. Only one '\n                             u'is allowed: {} {}'.format(global_operation_blocks, ir_blocks))\n    if len(global_operation_blocks) == 1:\n        if not isinstance(global_operation_blocks[0], Filter):\n            raise AssertionError(u'Received non-Filter global operation block. {}'\n                                 .format(global_operation_blocks[0]))\n        where_block = global_operation_blocks[0]\n    else:\n        where_block = None\n    match_steps = _split_ir_into_match_steps(pruned_ir_blocks)\n    match_traversals = _split_match_steps_into_match_traversals(match_steps)\n    return MatchQuery(\n        match_traversals=match_traversals,\n        folds=folds,\n        output_block=output_block,\n        where_block=where_block,\n    )",
    "docstring": "Convert the list of IR blocks into a MatchQuery object, for easier manipulation."
  },
  {
    "code": "def AddPorts(self,ports):\n\t\tfor port in ports:\n\t\t\tif 'port_to' in port:  self.ports.append(Port(self,port['protocol'],port['port'],port['port_to']))\n\t\t\telse:  self.ports.append(Port(self,port['protocol'],port['port']))\n\t\treturn(self.Update())",
    "docstring": "Create one or more port access policies.\n\n\t\tInclude a list of dicts with protocol, port, and port_to (optional - for range) keys.\n\n\t\t>>> clc.v2.Server(\"WA1BTDIX01\").PublicIPs().public_ips[0]\n\t\t\t\t.AddPorts([{'protocol': 'TCP', 'port': '80' },\n\t\t\t\t           {'protocol': 'UDP', 'port': '10000', 'port_to': '15000'}]).WaitUntilComplete()\n\t\t0"
  },
  {
    "code": "def remove_all_cts_records_by(file_name, crypto_idfp):\n    db = XonoticDB.load_path(file_name)\n    db.remove_all_cts_records_by(crypto_idfp)\n    db.save(file_name)",
    "docstring": "Remove all cts records set by player with CRYPTO_IDFP"
  },
  {
    "code": "def CreateNetworkConnectivityTauDEMTree(network_connectivity_tree_file,\n                                        out_csv_file):\n    stream_id_array = []\n    next_down_id_array = []\n    with open_csv(network_connectivity_tree_file, \"r\") as csvfile:\n        for row in csvfile:\n            split_row = row.split()\n            stream_id_array.append(split_row[0].strip())\n            next_down_id_array.append(split_row[3].strip())\n    stream_id_array = np.array(stream_id_array, dtype=np.int32)\n    next_down_id_array = np.array(next_down_id_array, dtype=np.int32)\n    StreamIDNextDownIDToConnectivity(stream_id_array,\n                                     next_down_id_array,\n                                     out_csv_file)",
    "docstring": "Creates Network Connectivity input CSV file for RAPID\n    based on the TauDEM network connectivity tree file"
  },
  {
    "code": "def get_region_for_chip(x, y, level=3):\n    shift = 6 - 2*level\n    bit = ((x >> shift) & 3) + 4*((y >> shift) & 3)\n    mask = 0xffff ^ ((4 << shift) - 1)\n    nx = x & mask\n    ny = y & mask\n    region = (nx << 24) | (ny << 16) | (level << 16) | (1 << bit)\n    return region",
    "docstring": "Get the region word for the given chip co-ordinates.\n\n    Parameters\n    ----------\n    x : int\n        x co-ordinate\n    y : int\n        y co-ordinate\n    level : int\n        Level of region to build. 0 is the most coarse and 3 is the finest.\n        When 3 is used the specified region will ONLY select the given chip,\n        for other regions surrounding chips will also be selected.\n\n    Returns\n    -------\n    int\n        A 32-bit value representing the co-ordinates of the chunk of SpiNNaker\n        chips that should be selected and the blocks within this chunk that are\n        selected.  As long as bits (31:16) are the same these values may be\n        OR-ed together to increase the number of sub-blocks selected."
  },
  {
    "code": "def _run(self):\n        for node in self.node.relatives:\n            launch_node_task(node)\n        for node in self.node.relatives:\n            self.wait_and_join(node.task)\n        if self.node.parent:\n            while not self.node.parent.task.siblings_permission:\n                time.sleep(self._polling_time)\n        self.has_started = True\n        self.main()\n        self.siblings_permission = True\n        for node in self.node.siblings:\n            launch_node_task(node)\n        for node in self.node.siblings:\n            self.wait_and_join(node.task)\n        self.finished_at = time.time()\n        self.scheduler.notify_execution(self)\n        self.has_finished = True",
    "docstring": "Run the task respecting dependencies"
  },
  {
    "code": "def print_item_callback(item):\n    print('&listen [{}, {}={}]'.format(\n        item.get('cmd', ''),\n        item.get('id', ''),\n        item.get('data', '')))",
    "docstring": "Print an item callback, used by &listen."
  },
  {
    "code": "def crypto_box_keypair():\n    pk = ffi.new(\"unsigned char[]\", crypto_box_PUBLICKEYBYTES)\n    sk = ffi.new(\"unsigned char[]\", crypto_box_SECRETKEYBYTES)\n    rc = lib.crypto_box_keypair(pk, sk)\n    ensure(rc == 0,\n           'Unexpected library error',\n           raising=exc.RuntimeError)\n    return (\n        ffi.buffer(pk, crypto_box_PUBLICKEYBYTES)[:],\n        ffi.buffer(sk, crypto_box_SECRETKEYBYTES)[:],\n    )",
    "docstring": "Returns a randomly generated public and secret key.\n\n    :rtype: (bytes(public_key), bytes(secret_key))"
  },
  {
    "code": "def _get_property_values_with_defaults(self, classname, property_values):\n        final_values = self.get_default_property_values(classname)\n        final_values.update(property_values)\n        return final_values",
    "docstring": "Return the property values for the class, with default values applied where needed."
  },
  {
    "code": "def _sanity_check_registered_locations_parent_locations(query_metadata_table):\n    for location, location_info in query_metadata_table.registered_locations:\n        if (location != query_metadata_table.root_location and\n                not query_metadata_table.root_location.is_revisited_at(location)):\n            if location_info.parent_location is None:\n                raise AssertionError(u'Found a location that is not the root location of the query '\n                                     u'or a revisit of the root, but does not have a parent: '\n                                     u'{} {}'.format(location, location_info))\n        if location_info.parent_location is not None:\n            query_metadata_table.get_location_info(location_info.parent_location)",
    "docstring": "Assert that all registered locations' parent locations are also registered."
  },
  {
    "code": "def log(msg, level=0):\n    red = '\\033[91m'\n    endc = '\\033[0m'\n    cfg = {\n        'version': 1,\n        'disable_existing_loggers': False,\n        'formatters': {\n            'stdout': {\n                'format': '[%(levelname)s]: %(asctime)s - %(message)s',\n                'datefmt': '%x %X'\n            },\n            'stderr': {\n                'format': red + '[%(levelname)s]: %(asctime)s - %(message)s' + endc,\n                'datefmt': '%x %X'\n            }\n        },\n        'handlers': {\n            'stdout': {\n                'class': 'logging.StreamHandler',\n                'level': 'DEBUG',\n                'formatter': 'stdout'\n            },\n            'stderr': {\n                'class': 'logging.StreamHandler',\n                'level': 'ERROR',\n                'formatter': 'stderr'\n            }\n        },\n        'loggers': {\n            'info': {\n                'handlers': ['stdout'],\n                'level': 'INFO',\n                'propagate': True\n            },\n            'error': {\n                'handlers': ['stderr'],\n                'level': 'ERROR',\n                'propagate': False\n            }\n        }\n    }\n    dictConfig(cfg)\n    lg = 'info' if level == 0 else 'error'\n    lvl = 20 if level == 0 else 40\n    logger = logging.getLogger(lg)\n    logger.log(lvl, msg)",
    "docstring": "Logs a message to the console, with optional level paramater\n\n    Args:\n        - msg (str): message to send to console\n        - level (int): log level; 0 for info, 1 for error (default = 0)"
  },
  {
    "code": "def _cutout(x, n_holes:uniform_int=1, length:uniform_int=40):\n    \"Cut out `n_holes` number of square holes of size `length` in image at random locations.\"\n    h,w = x.shape[1:]\n    for n in range(n_holes):\n        h_y = np.random.randint(0, h)\n        h_x = np.random.randint(0, w)\n        y1 = int(np.clip(h_y - length / 2, 0, h))\n        y2 = int(np.clip(h_y + length / 2, 0, h))\n        x1 = int(np.clip(h_x - length / 2, 0, w))\n        x2 = int(np.clip(h_x + length / 2, 0, w))\n        x[:, y1:y2, x1:x2] = 0\n    return x",
    "docstring": "Cut out `n_holes` number of square holes of size `length` in image at random locations."
  },
  {
    "code": "def describe(self):\n        return OrderedDict([\n            (name, field.describe())\n            for name, field in self.fields.items()\n        ])",
    "docstring": "Describe all serialized fields.\n\n        It returns dictionary of all fields description defined for this\n        serializer using their own ``describe()`` methods with respect to order\n        in which they are defined as class attributes.\n\n        Returns:\n            OrderedDict: serializer description"
  },
  {
    "code": "def endpoint_create(service, publicurl=None, internalurl=None, adminurl=None,\n                    region=None, profile=None, url=None, interface=None, **connection_args):\n    kstone = auth(profile, **connection_args)\n    keystone_service = service_get(name=service, profile=profile,\n                                   **connection_args)\n    if not keystone_service or 'Error' in keystone_service:\n        return {'Error': 'Could not find the specified service'}\n    if _OS_IDENTITY_API_VERSION > 2:\n        kstone.endpoints.create(service=keystone_service[service]['id'],\n                                region_id=region,\n                                url=url,\n                                interface=interface)\n    else:\n        kstone.endpoints.create(region=region,\n                                service_id=keystone_service[service]['id'],\n                                publicurl=publicurl,\n                                adminurl=adminurl,\n                                internalurl=internalurl)\n    return endpoint_get(service, region, profile, interface, **connection_args)",
    "docstring": "Create an endpoint for an Openstack service\n\n    CLI Examples:\n\n    .. code-block:: bash\n\n        salt 'v2' keystone.endpoint_create nova 'http://public/url' 'http://internal/url' 'http://adminurl/url' region\n\n        salt 'v3' keystone.endpoint_create nova url='http://public/url' interface='public' region='RegionOne'"
  },
  {
    "code": "def ScanForVolumeSystem(self, source_path_spec):\n    if source_path_spec.type_indicator == definitions.TYPE_INDICATOR_VSHADOW:\n      return None\n    if source_path_spec.IsVolumeSystemRoot():\n      return source_path_spec\n    if source_path_spec.type_indicator == (\n        definitions.TYPE_INDICATOR_APFS_CONTAINER):\n      return None\n    try:\n      type_indicators = analyzer.Analyzer.GetVolumeSystemTypeIndicators(\n          source_path_spec, resolver_context=self._resolver_context)\n    except (IOError, RuntimeError) as exception:\n      raise errors.BackEndError((\n          'Unable to process source path specification with error: '\n          '{0!s}').format(exception))\n    if not type_indicators:\n      return None\n    if len(type_indicators) > 1:\n      raise errors.BackEndError(\n          'Unsupported source found more than one volume system types.')\n    if (type_indicators[0] == definitions.TYPE_INDICATOR_TSK_PARTITION and\n        source_path_spec.type_indicator in [\n            definitions.TYPE_INDICATOR_TSK_PARTITION]):\n      return None\n    if type_indicators[0] in definitions.VOLUME_SYSTEM_TYPE_INDICATORS:\n      return path_spec_factory.Factory.NewPathSpec(\n          type_indicators[0], location='/', parent=source_path_spec)\n    return path_spec_factory.Factory.NewPathSpec(\n        type_indicators[0], parent=source_path_spec)",
    "docstring": "Scans the path specification for a supported volume system format.\n\n    Args:\n      source_path_spec (PathSpec): source path specification.\n\n    Returns:\n      PathSpec: volume system path specification or None if no supported volume\n          system type was found.\n\n    Raises:\n      BackEndError: if the source cannot be scanned or more than one volume\n          system type is found."
  },
  {
    "code": "def AddMethod(self, interface, name, in_sig, out_sig, code):\n        if not interface:\n            interface = self.interface\n        n_args = len(dbus.Signature(in_sig))\n        method = lambda self, *args, **kwargs: DBusMockObject.mock_method(\n            self, interface, name, in_sig, *args, **kwargs)\n        dbus_method = dbus.service.method(interface,\n                                          out_signature=out_sig)(method)\n        dbus_method.__name__ = str(name)\n        dbus_method._dbus_in_signature = in_sig\n        dbus_method._dbus_args = ['arg%i' % i for i in range(1, n_args + 1)]\n        if interface == self.interface:\n            setattr(self.__class__, name, dbus_method)\n        self.methods.setdefault(interface, {})[str(name)] = (in_sig, out_sig, code, dbus_method)",
    "docstring": "Add a method to this object\n\n        interface: D-Bus interface to add this to. For convenience you can\n                   specify '' here to add the method to the object's main\n                   interface (as specified on construction).\n        name: Name of the method\n        in_sig: Signature of input arguments; for example \"ias\" for a method\n                that takes an int32 and a string array as arguments; see\n                http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-signatures\n        out_sig: Signature of output arguments; for example \"s\" for a method\n                 that returns a string; use '' for methods that do not return\n                 anything.\n        code: Python 3 code to run in the method call; you have access to the\n              arguments through the \"args\" list, and can set the return value\n              by assigning a value to the \"ret\" variable. You can also read the\n              global \"objects\" variable, which is a dictionary mapping object\n              paths to DBusMockObject instances.\n\n              For keeping state across method calls, you are free to use normal\n              Python members of the \"self\" object, which will be persistent for\n              the whole mock's life time. E. g. you can have a method with\n              \"self.my_state = True\", and another method that returns it with\n              \"ret = self.my_state\".\n\n              When specifying '', the method will not do anything (except\n              logging) and return None."
  },
  {
    "code": "def decrypt_seal(self, data: bytes) -> bytes:\n        curve25519_public_key = libnacl.crypto_sign_ed25519_pk_to_curve25519(self.vk)\n        curve25519_secret_key = libnacl.crypto_sign_ed25519_sk_to_curve25519(self.sk)\n        return libnacl.crypto_box_seal_open(data, curve25519_public_key, curve25519_secret_key)",
    "docstring": "Decrypt bytes data with a curve25519 version of the ed25519 key pair\n\n        :param data: Encrypted data\n\n        :return:"
  },
  {
    "code": "def get_context_arguments(self):\n        cargs = {}\n        for context in self.__context_stack:\n            cargs.update(context.context_arguments)\n        return cargs",
    "docstring": "Return a dictionary containing the current context arguments."
  },
  {
    "code": "def _get_toc_reference(app, node, toc, docname):\n    if isinstance(node, nodes.section) and isinstance(node.parent, nodes.document):\n        ref_id = docname\n        toc_reference = _find_toc_node(toc, ref_id, nodes.section)\n    elif isinstance(node, nodes.section):\n        ref_id = node.attributes[\"ids\"][0]\n        toc_reference = _find_toc_node(toc, ref_id, nodes.section)\n    else:\n        try:\n            ref_id = node.children[0].attributes[\"ids\"][0]\n            toc_reference = _find_toc_node(toc, ref_id, addnodes.desc)\n        except (KeyError, IndexError) as e:\n            LOGGER.warning(\"Invalid desc node: %s\" % e)\n            toc_reference = None\n    return toc_reference",
    "docstring": "Logic that understands maps a specific node to it's part of the toctree.\n\n    It takes a specific incoming ``node``,\n    and returns the actual TOC Tree node that is said reference."
  },
  {
    "code": "def shutdown(self):\n        inputQueue = self.inputQueue\n        self.inputQueue = None\n        for i in range(self.numWorkers):\n            inputQueue.put(None)\n        for thread in self.workerThreads:\n            thread.join()\n        BatchSystemSupport.workerCleanup(self.workerCleanupInfo)",
    "docstring": "Cleanly terminate worker threads. Add sentinels to inputQueue equal to maxThreads. Join\n        all worker threads."
  },
  {
    "code": "def _calf(self, spec):\n        self.prepare(spec)\n        self.compile(spec)\n        self.assemble(spec)\n        self.link(spec)\n        self.finalize(spec)",
    "docstring": "The main call, assuming the base spec is prepared.\n\n        Also, no advices will be triggered."
  },
  {
    "code": "def reorient_wf(name='ReorientWorkflow'):\n    workflow = pe.Workflow(name=name)\n    inputnode = pe.Node(niu.IdentityInterface(fields=['in_file']),\n                        name='inputnode')\n    outputnode = pe.Node(niu.IdentityInterface(\n        fields=['out_file']), name='outputnode')\n    deoblique = pe.Node(afni.Refit(deoblique=True), name='deoblique')\n    reorient = pe.Node(afni.Resample(\n        orientation='RPI', outputtype='NIFTI_GZ'), name='reorient')\n    workflow.connect([\n        (inputnode, deoblique, [('in_file', 'in_file')]),\n        (deoblique, reorient, [('out_file', 'in_file')]),\n        (reorient, outputnode, [('out_file', 'out_file')])\n    ])\n    return workflow",
    "docstring": "A workflow to reorient images to 'RPI' orientation"
  },
  {
    "code": "def convert(self):\n        if self.downloaded is False:\n            raise serror(\"Track not downloaded, can't convert file..\")\n        filetype = magic.from_file(self.filepath, mime=True)\n        if filetype == \"audio/mpeg\":\n            print(\"File is already in mp3 format. Skipping convert.\")\n            return False\n        rootpath = os.path.dirname(os.path.dirname(self.filepath))\n        backupdir = rootpath + \"/backups/\" + self.get(\"username\")\n        if not os.path.exists(backupdir):\n            os.makedirs(backupdir)\n        backupfile = \"%s/%s%s\" % (\n            backupdir,\n            self.gen_filename(),\n            self.get_file_extension(self.filepath))\n        newfile = \"%s.mp3\" % self.filename_without_extension()\n        os.rename(self.filepath, backupfile)\n        self.filepath = newfile\n        print(\"Converting to %s..\" % newfile)\n        song = AudioSegment.from_file(backupfile)\n        return song.export(newfile, format=\"mp3\")",
    "docstring": "Convert file in mp3 format."
  },
  {
    "code": "def readFromFile(self, filename):\r\n        s = dict(np.load(filename))\r\n        try:\r\n            self.coeffs = s['coeffs'][()]\r\n        except KeyError:\r\n            self.coeffs = s\r\n        try:\r\n            self.opts = s['opts'][()]\r\n        except KeyError:\r\n            pass\r\n        return self.coeffs",
    "docstring": "read the distortion coeffs from file"
  },
  {
    "code": "def dollars_to_math(source):\n    r\n    s = \"\\n\".join(source)\n    if s.find(\"$\") == -1:\n        return\n    global _data\n    _data = {}\n    def repl(matchobj):\n        global _data\n        s = matchobj.group(0)\n        t = \"___XXX_REPL_%d___\" % len(_data)\n        _data[t] = s\n        return t\n    s = re.sub(r\"({[^{}$]*\\$[^{}$]*\\$[^{}]*})\", repl, s)\n    dollars = re.compile(r\"(?<!\\$)(?<!\\\\)\\$([^\\$]+?)\\$\")\n    slashdollar = re.compile(r\"\\\\\\$\")\n    s = dollars.sub(r\":math:`\\1`\", s)\n    s = slashdollar.sub(r\"$\", s)\n    for r in _data:\n        s = s.replace(r, _data[r])\n    source[:] = [s]",
    "docstring": "r\"\"\"\n    Replace dollar signs with backticks.\n\n    More precisely, do a regular expression search.  Replace a plain\n    dollar sign ($) by a backtick (`).  Replace an escaped dollar sign\n    (\\$) by a dollar sign ($).  Don't change a dollar sign preceded or\n    followed by a backtick (`$ or $`), because of strings like\n    \"``$HOME``\".  Don't make any changes on lines starting with\n    spaces, because those are indented and hence part of a block of\n    code or examples.\n\n    This also doesn't replaces dollar signs enclosed in curly braces,\n    to avoid nested math environments, such as ::\n\n      $f(n) = 0 \\text{ if $n$ is prime}$\n\n    Thus the above line would get changed to\n\n      `f(n) = 0 \\text{ if $n$ is prime}`"
  },
  {
    "code": "def _merge_map(key, values, partial):\n  proto = kv_pb.KeyValues()\n  proto.set_key(key)\n  proto.value_list().extend(values)\n  yield proto.Encode()",
    "docstring": "A map function used in merge phase.\n\n  Stores (key, values) into KeyValues proto and yields its serialization.\n\n  Args:\n    key: values key.\n    values: values themselves.\n    partial: True if more values for this key will follow. False otherwise.\n\n  Yields:\n    The proto."
  },
  {
    "code": "def get_distributed_seismicity_source_nodes(source):\n    source_nodes = []\n    source_nodes.append(\n        Node(\"magScaleRel\",\n             text=source.magnitude_scaling_relationship.__class__.__name__))\n    source_nodes.append(\n        Node(\"ruptAspectRatio\", text=source.rupture_aspect_ratio))\n    source_nodes.append(obj_to_node(source.mfd))\n    source_nodes.append(\n        build_nodal_plane_dist(source.nodal_plane_distribution))\n    source_nodes.append(\n        build_hypo_depth_dist(source.hypocenter_distribution))\n    return source_nodes",
    "docstring": "Returns list of nodes of attributes common to all distributed seismicity\n    source classes\n\n    :param source:\n        Seismic source as instance of :class:\n        `openquake.hazardlib.source.area.AreaSource` or :class:\n        `openquake.hazardlib.source.point.PointSource`\n    :returns:\n        List of instances of :class:`openquake.baselib.node.Node`"
  },
  {
    "code": "def classname(self):\n        cls = javabridge.call(self.jobject, \"getClass\", \"()Ljava/lang/Class;\")\n        return javabridge.call(cls, \"getName\", \"()Ljava/lang/String;\")",
    "docstring": "Returns the Java classname in dot-notation.\n\n        :return: the Java classname\n        :rtype: str"
  },
  {
    "code": "def find_module(self, name):\n        defmodule = lib.EnvFindDefmodule(self._env, name.encode())\n        if defmodule == ffi.NULL:\n            raise LookupError(\"Module '%s' not found\" % name)\n        return Module(self._env, defmodule)",
    "docstring": "Find the Module by its name."
  },
  {
    "code": "def StrikeDip(n, e, u):\n    r2d = 180 / np.pi\n    if u < 0:\n        n = -n\n        e = -e\n        u = -u\n    strike = np.arctan2(e, n) * r2d\n    strike = strike - 90\n    while strike >= 360:\n        strike = strike - 360\n    while strike < 0:\n        strike = strike + 360\n    x = np.sqrt(np.power(n, 2) + np.power(e, 2))\n    dip = np.arctan2(x, u) * r2d\n    return (strike, dip)",
    "docstring": "Finds strike and dip of plane given normal vector having components n, e,\n    and u.\n\n    Adapted from MATLAB script\n    `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_\n    written by Andy Michael and Oliver Boyd."
  },
  {
    "code": "def synergy_to_datetime(time_qualifier, timeperiod):\n    if time_qualifier == QUALIFIER_HOURLY:\n        date_format = SYNERGY_HOURLY_PATTERN\n    elif time_qualifier == QUALIFIER_DAILY:\n        date_format = SYNERGY_DAILY_PATTERN\n    elif time_qualifier == QUALIFIER_MONTHLY:\n        date_format = SYNERGY_MONTHLY_PATTERN\n    elif time_qualifier == QUALIFIER_YEARLY:\n        date_format = SYNERGY_YEARLY_PATTERN\n    elif time_qualifier == QUALIFIER_REAL_TIME:\n        date_format = SYNERGY_SESSION_PATTERN\n    else:\n        raise ValueError('unknown time qualifier: {0}'.format(time_qualifier))\n    return datetime.strptime(timeperiod, date_format).replace(tzinfo=None)",
    "docstring": "method receives timeperiod in Synergy format YYYYMMDDHH and convert it to UTC _naive_ datetime"
  },
  {
    "code": "def verify_login(user, password=None, **connection_args):\n    connection_args['connection_user'] = user\n    connection_args['connection_pass'] = password\n    dbc = _connect(**connection_args)\n    if dbc is None:\n        if 'mysql.error' in __context__:\n            del __context__['mysql.error']\n        return False\n    return True",
    "docstring": "Attempt to login using the provided credentials.\n    If successful, return true.  Otherwise, return False.\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' mysql.verify_login root password"
  },
  {
    "code": "def state_counts(gamma, T, out=None):\n    return np.sum(gamma[0:T], axis=0, out=out)",
    "docstring": "Sum the probabilities of being in state i to time t\n\n    Parameters\n    ----------\n    gamma : ndarray((T,N), dtype = float), optional, default = None\n        gamma[t,i] is the probabilty at time t to be in state i !\n    T : int\n        number of time steps\n\n    Returns\n    -------\n    count : numpy.array shape (N)\n            count[i] is the summed probabilty to be in state i !\n\n    See Also\n    --------\n    state_probabilities : to calculate `gamma`"
  },
  {
    "code": "def moments(self):\n        moment1 = statstools.calc_mean_time(self.delays, self.coefs)\n        moment2 = statstools.calc_mean_time_deviation(\n            self.delays, self.coefs, moment1)\n        return numpy.array([moment1, moment2])",
    "docstring": "The first two time delay weighted statistical moments of the\n        MA coefficients."
  },
  {
    "code": "def is_tagged(required_tags, has_tags):\n    if not required_tags and not has_tags:\n        return True\n    elif not required_tags:\n        return False\n    found_tags = []\n    for tag in required_tags:\n        if tag in has_tags:\n            found_tags.append(tag)\n    return len(found_tags) == len(required_tags)",
    "docstring": "Checks if tags match"
  },
  {
    "code": "def dist(self, other):\n    dx = self.x - other.x\n    dy = self.y - other.y\n    return math.sqrt(dx**2 + dy**2)",
    "docstring": "Distance to some other point."
  },
  {
    "code": "def _check_not_empty(string):\n    string = string.strip()\n    if len(string) == 0:\n        message = 'The string should not be empty'\n        raise pp.ParseException(message)",
    "docstring": "Checks that the string is not empty.\n\n    If it is empty an exception is raised, stopping the validation.\n\n    This is used for compulsory alphanumeric fields.\n\n    :param string: the field value"
  },
  {
    "code": "def activate(lang=None):\n    if lang is None:\n        lang = locale.getlocale()[0]\n    tr = gettext.translation(\"argparse\", os.path.join(locpath, \"locale\"),\n                             [lang], fallback=True)\n    argparse._ = tr.gettext\n    argparse.ngettext = tr.ngettext",
    "docstring": "Activate a translation for lang.\n\nIf lang is None, then the language of locale.getdefaultlocale() is used.\nIf the translation file does not exist, the original messages will be used."
  },
  {
    "code": "def getOutputName(self,name):\n        val = self.outputNames[name]\n        if self.inmemory:\n            val = self.virtualOutputs[val]\n        return val",
    "docstring": "Return the name of the file or PyFITS object associated with that\n        name, depending on the setting of self.inmemory."
  },
  {
    "code": "def delete_policy(self, pol_id):\n        if pol_id not in self.policies:\n            LOG.error(\"Invalid policy %s\", pol_id)\n            return\n        del self.policies[pol_id]\n        self.policy_cnt -= 1",
    "docstring": "Deletes the policy from the local dictionary."
  },
  {
    "code": "def _get_system(model_folder):\n    model_description_file = os.path.join(model_folder, \"info.yml\")\n    if not os.path.isfile(model_description_file):\n        logging.error(\"You are probably not in the folder of a model, because \"\n                      \"%s is not a file. (-m argument)\",\n                      model_description_file)\n        sys.exit(-1)\n    with open(model_description_file, 'r') as ymlfile:\n        model_desc = yaml.load(ymlfile)\n    feature_desc = _get_description(model_desc)\n    preprocessing_desc = _get_description(feature_desc)\n    return (preprocessing_desc, feature_desc, model_desc)",
    "docstring": "Return the preprocessing description, the feature description and the\n       model description."
  },
  {
    "code": "def elapsed(self):\n        dt = 0\n        for ss in self.starts_and_stops[:-1]:\n            dt += (ss['stop'] - ss['start']).total_seconds()\n        ss = self.starts_and_stops[-1]\n        if ss['stop']:\n            dt += (ss['stop'] - ss['start']).total_seconds()\n        else:\n            dt += (doublethink.utcnow() - ss['start']).total_seconds()\n        return dt",
    "docstring": "Returns elapsed crawl time as a float in seconds.\n\n        This metric includes all the time that a site was in active rotation,\n        including any time it spent waiting for its turn to be brozzled.\n\n        In contrast `Site.active_brozzling_time` only counts time when a\n        brozzler worker claimed the site and was actively brozzling it."
  },
  {
    "code": "def smartread(path):\n    with open(path, \"rb\") as f:\n        content = f.read()\n        result = chardet.detect(content)\n        return content.decode(result[\"encoding\"])",
    "docstring": "Read text from file, automatically detect encoding. ``chardet`` required."
  },
  {
    "code": "def powerDown(self, powerup, interface=None):\n        if interface is None:\n            for interface, priority in powerup._getPowerupInterfaces():\n                self.powerDown(powerup, interface)\n        else:\n            for cable in self.store.query(_PowerupConnector,\n                                          AND(_PowerupConnector.item == self,\n                                              _PowerupConnector.interface == unicode(qual(interface)),\n                                              _PowerupConnector.powerup == powerup)):\n                cable.deleteFromStore()\n                return\n            raise ValueError(\"Not powered up for %r with %r\" % (interface,\n                                                                powerup))",
    "docstring": "Remove a powerup.\n\n        If no interface is specified, and the type of the object being\n        installed has a \"powerupInterfaces\" attribute (containing\n        either a sequence of interfaces, or a sequence of (interface,\n        priority) tuples), the target will be powered down with this\n        object on those interfaces.\n\n        If this object has a \"__getPowerupInterfaces__\" method, it\n        will be called with an iterable of (interface, priority)\n        tuples. The iterable of (interface, priority) tuples it\n        returns will then be uninstalled.\n\n        (Note particularly that if powerups are added or removed to the\n        collection described above between calls to powerUp and powerDown, more\n        powerups or less will be removed than were installed.)"
  },
  {
    "code": "def remove_file_data(file_id, silent=True):\n    try:\n        f = FileInstance.get(file_id)\n        if not f.writable:\n            return\n        f.delete()\n        db.session.commit()\n        f.storage().delete()\n    except IntegrityError:\n        if not silent:\n            raise",
    "docstring": "Remove file instance and associated data.\n\n    :param file_id: The :class:`invenio_files_rest.models.FileInstance` ID.\n    :param silent: It stops propagation of a possible arised IntegrityError\n        exception. (Default: ``True``)\n    :raises sqlalchemy.exc.IntegrityError: Raised if the database removal goes\n        wrong and silent is set to ``False``."
  },
  {
    "code": "def validate_properties(self):\n        for name, property_type in self.property_types.items():\n            value = getattr(self, name)\n            if property_type.supports_intrinsics and self._is_intrinsic_function(value):\n                continue\n            if value is None:\n                if property_type.required:\n                    raise InvalidResourceException(\n                        self.logical_id,\n                        \"Missing required property '{property_name}'.\".format(property_name=name))\n            elif not property_type.validate(value, should_raise=False):\n                raise InvalidResourceException(\n                    self.logical_id,\n                    \"Type of property '{property_name}' is invalid.\".format(property_name=name))",
    "docstring": "Validates that the required properties for this Resource have been populated, and that all properties have\n        valid values.\n\n        :returns: True if all properties are valid\n        :rtype: bool\n        :raises TypeError: if any properties are invalid"
  },
  {
    "code": "def shape(self):\n        if self._shape is None:\n            self._populate_from_rasterio_object(read_image=False)\n        return self._shape",
    "docstring": "Raster shape."
  },
  {
    "code": "def getInfoMutator(self):\n        if self._infoMutator:\n            return self._infoMutator\n        infoItems = []\n        for sourceDescriptor in self.sources:\n            if sourceDescriptor.layerName is not None:\n                continue\n            loc = Location(sourceDescriptor.location)\n            sourceFont = self.fonts[sourceDescriptor.name]\n            if sourceFont is None:\n                continue\n            if hasattr(sourceFont.info, \"toMathInfo\"):\n                infoItems.append((loc, sourceFont.info.toMathInfo()))\n            else:\n                infoItems.append((loc, self.mathInfoClass(sourceFont.info)))\n        bias, self._infoMutator = self.getVariationModel(infoItems, axes=self.serializedAxes, bias=self.newDefaultLocation())\n        return self._infoMutator",
    "docstring": "Returns a info mutator"
  },
  {
    "code": "def read_login(collector, image, **kwargs):\n    docker_api = collector.configuration[\"harpoon\"].docker_api\n    collector.configuration[\"authentication\"].login(docker_api, image, is_pushing=False, global_docker=True)",
    "docstring": "Login to a docker registry with read permissions"
  },
  {
    "code": "def get_provider_links(self):\n        if not bool(self._my_map['providerLinkIds']):\n            raise errors.IllegalState('no providerLinkIds')\n        mgr = self._get_provider_manager('RESOURCE')\n        if not mgr.supports_resource_lookup():\n            raise errors.OperationFailed('Resource does not support Resource lookup')\n        lookup_session = mgr.get_resource_lookup_session(proxy=getattr(self, \"_proxy\", None))\n        lookup_session.use_federated_bin_view()\n        return lookup_session.get_resources_by_ids(self.get_provider_link_ids())",
    "docstring": "Gets the ``Resources`` representing the source of this asset in order from the most recent provider to the originating source.\n\n        return: (osid.resource.ResourceList) - the provider chain\n        raise:  OperationFailed - unable to complete request\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def match_serializers(self, serializers, default_media_type):\n        return self._match_serializers_by_query_arg(serializers) or self.\\\n            _match_serializers_by_accept_headers(serializers,\n                                                 default_media_type)",
    "docstring": "Choose serializer for a given request based on query arg or headers.\n\n        Checks if query arg `format` (by default) is present and tries to match\n        the serializer based on the arg value, by resolving the mimetype mapped\n        to the arg value.\n        Otherwise, chooses the serializer by retrieving the best quality\n        `Accept` headers and matching its value (mimetype).\n\n        :param serializers: Dictionary of serializers.\n        :param default_media_type: The default media type.\n        :returns: Best matching serializer based on `format` query arg first,\n            then client `Accept` headers or None if no matching serializer."
  },
  {
    "code": "def _get_flux_bounds(self, r_id, model, flux_limits, equation):\n        if r_id not in flux_limits or flux_limits[r_id][0] is None:\n            if equation.direction == Direction.Forward:\n                lower = 0\n            else:\n                lower = -model.default_flux_limit\n        else:\n            lower = flux_limits[r_id][0]\n        if r_id not in flux_limits or flux_limits[r_id][1] is None:\n            if equation.direction == Direction.Reverse:\n                upper = 0\n            else:\n                upper = model.default_flux_limit\n        else:\n            upper = flux_limits[r_id][1]\n        if lower % 1 == 0:\n            lower = int(lower)\n        if upper % 1 == 0:\n            upper = int(upper)\n        return text_type(lower), text_type(upper)",
    "docstring": "Read reaction's limits to set up strings for limits in the output file."
  },
  {
    "code": "def canonicalize(parsed_op):\n    assert 'op' in parsed_op\n    assert len(parsed_op['op']) == 2\n    if parsed_op['op'][1] == TRANSFER_KEEP_DATA:\n        parsed_op['keep_data'] = True\n    elif parsed_op['op'][1] == TRANSFER_REMOVE_DATA:\n        parsed_op['keep_data'] = False\n    else:\n        raise ValueError(\"Invalid op '{}'\".format(parsed_op['op']))\n    return parsed_op",
    "docstring": "Get the \"canonical form\" of this operation, putting it into a form where it can be serialized\n    to form a consensus hash.  This method is meant to preserve compatibility across blockstackd releases.\n\n    For NAME_TRANSFER, this means:\n    * add 'keep_data' flag"
  },
  {
    "code": "def delete_cookie(self, key, **kwargs):\n        kwargs['max_age'] = -1\n        kwargs['expires'] = 0\n        self.set_cookie(key, '', **kwargs)",
    "docstring": "Delete a cookie. Be sure to use the same `domain` and `path`\n            parameters as used to create the cookie."
  },
  {
    "code": "def compose(self, sources, client=None):\n        client = self._require_client(client)\n        query_params = {}\n        if self.user_project is not None:\n            query_params[\"userProject\"] = self.user_project\n        request = {\n            \"sourceObjects\": [{\"name\": source.name} for source in sources],\n            \"destination\": self._properties.copy(),\n        }\n        api_response = client._connection.api_request(\n            method=\"POST\",\n            path=self.path + \"/compose\",\n            query_params=query_params,\n            data=request,\n            _target_object=self,\n        )\n        self._set_properties(api_response)",
    "docstring": "Concatenate source blobs into this one.\n\n        If :attr:`user_project` is set on the bucket, bills the API request\n        to that project.\n\n        :type sources: list of :class:`Blob`\n        :param sources: blobs whose contents will be composed into this blob.\n\n        :type client: :class:`~google.cloud.storage.client.Client` or\n                      ``NoneType``\n        :param client: Optional. The client to use.  If not passed, falls back\n                       to the ``client`` stored on the blob's bucket."
  },
  {
    "code": "def filter_records(self, records):\n        for record in records:\n            try:\n                filtered = self.filter_record(record)\n                assert (filtered)\n                if filtered.seq == record.seq:\n                    self.passed_unchanged += 1\n                else:\n                    self.passed_changed += 1\n                yield filtered\n            except FailedFilter as e:\n                self.failed += 1\n                v = e.value\n                if self.listener:\n                    self.listener(\n                        'failed_filter',\n                        record,\n                        filter_name=self.name,\n                        value=v)",
    "docstring": "Apply the filter to records"
  },
  {
    "code": "def fixPoint(self, plotterPoint, canvasPoint):\n        'adjust visibleBox.xymin so that canvasPoint is plotted at plotterPoint'\n        self.visibleBox.xmin = canvasPoint.x - self.canvasW(plotterPoint.x-self.plotviewBox.xmin)\n        self.visibleBox.ymin = canvasPoint.y - self.canvasH(plotterPoint.y-self.plotviewBox.ymin)\n        self.refresh()",
    "docstring": "adjust visibleBox.xymin so that canvasPoint is plotted at plotterPoint"
  },
  {
    "code": "def _skip_frame(self):\n        self._get_line()\n        num_atoms = int(self._get_line())\n        if self.num_atoms is not None and self.num_atoms != num_atoms:\n            raise ValueError(\"The number of atoms must be the same over the entire file.\")\n        for i in range(num_atoms+1):\n            self._get_line()",
    "docstring": "Skip one frame"
  },
  {
    "code": "def _parameterize_string(raw):\n    parts = []\n    s_index = 0\n    for match in _PARAMETER_PATTERN.finditer(raw):\n        parts.append(raw[s_index:match.start()])\n        parts.append({u\"Ref\": match.group(1)})\n        s_index = match.end()\n    if not parts:\n        return GenericHelperFn(raw)\n    parts.append(raw[s_index:])\n    return GenericHelperFn({u\"Fn::Join\": [u\"\", parts]})",
    "docstring": "Substitute placeholders in a string using CloudFormation references\n\n    Args:\n        raw (`str`): String to be processed. Byte strings are not\n        supported; decode them before passing them to this function.\n\n    Returns:\n        `str` | :class:`troposphere.GenericHelperFn`: An expression with\n            placeholders from the input replaced, suitable to be passed to\n            Troposphere to be included in CloudFormation template. This will\n            be the input string without modification if no substitutions are\n            found, and a composition of CloudFormation calls otherwise."
  },
  {
    "code": "def getresponse(self):\n        if self.__response and self.__response.isclosed():\n            self.__response = None\n        if self.__state != _CS_REQ_SENT or self.__response:\n            raise ResponseNotReady(self.__state)\n        if self.debuglevel > 0:\n            response = self.response_class(self.sock, self.debuglevel,\n                                           method=self._method)\n        else:\n            response = self.response_class(self.sock, method=self._method)\n        response.begin()\n        assert response.will_close != _UNKNOWN\n        self.__state = _CS_IDLE\n        if response.will_close:\n            self.close()\n        else:\n            self.__response = response\n        return response",
    "docstring": "Get the response from the server.\n\n        If the HTTPConnection is in the correct state, returns an\n        instance of HTTPResponse or of whatever object is returned by\n        class the response_class variable.\n\n        If a request has not been sent or if a previous response has\n        not be handled, ResponseNotReady is raised.  If the HTTP\n        response indicates that the connection should be closed, then\n        it will be closed before the response is returned.  When the\n        connection is closed, the underlying socket is closed."
  },
  {
    "code": "def default_channel_ops(nqubits):\n    for gates in cartesian_product(TOMOGRAPHY_GATES.values(), repeat=nqubits):\n        yield qt.tensor(*gates)",
    "docstring": "Generate the tomographic pre- and post-rotations of any number of qubits as qutip operators.\n\n    :param int nqubits: The number of qubits to perform tomography on.\n    :return: Qutip object corresponding to the tomographic rotation.\n    :rtype: Qobj"
  },
  {
    "code": "def deserialize_basic(self, attr, data_type):\n        if isinstance(attr, ET.Element):\n            attr = attr.text\n            if not attr:\n                if data_type == \"str\":\n                    return ''\n                else:\n                    return None\n        if data_type == 'bool':\n            if attr in [True, False, 1, 0]:\n                return bool(attr)\n            elif isinstance(attr, basestring):\n                if attr.lower() in ['true', '1']:\n                    return True\n                elif attr.lower() in ['false', '0']:\n                    return False\n            raise TypeError(\"Invalid boolean value: {}\".format(attr))\n        if data_type == 'str':\n            return self.deserialize_unicode(attr)\n        return eval(data_type)(attr)",
    "docstring": "Deserialize baisc builtin data type from string.\n        Will attempt to convert to str, int, float and bool.\n        This function will also accept '1', '0', 'true' and 'false' as\n        valid bool values.\n\n        :param str attr: response string to be deserialized.\n        :param str data_type: deserialization data type.\n        :rtype: str, int, float or bool\n        :raises: TypeError if string format is not valid."
  },
  {
    "code": "def unwrap(self):\n        if self.algorithm == 'rsa':\n            return self['private_key'].parsed\n        if self.algorithm == 'dsa':\n            params = self['private_key_algorithm']['parameters']\n            return DSAPrivateKey({\n                'version': 0,\n                'p': params['p'],\n                'q': params['q'],\n                'g': params['g'],\n                'public_key': self.public_key,\n                'private_key': self['private_key'].parsed,\n            })\n        if self.algorithm == 'ec':\n            output = self['private_key'].parsed\n            output['parameters'] = self['private_key_algorithm']['parameters']\n            output['public_key'] = self.public_key\n            return output",
    "docstring": "Unwraps the private key into an RSAPrivateKey, DSAPrivateKey or\n        ECPrivateKey object\n\n        :return:\n            An RSAPrivateKey, DSAPrivateKey or ECPrivateKey object"
  },
  {
    "code": "def GetAPFSVolumeByPathSpec(self, path_spec):\n    volume_index = apfs_helper.APFSContainerPathSpecGetVolumeIndex(path_spec)\n    if volume_index is None:\n      return None\n    return self._fsapfs_container.get_volume(volume_index)",
    "docstring": "Retrieves an APFS volume for a path specification.\n\n    Args:\n      path_spec (PathSpec): path specification.\n\n    Returns:\n      pyfsapfs.volume: an APFS volume or None if not available."
  },
  {
    "code": "def selection_r(acquisition_function,\n                samples_y_aggregation,\n                x_bounds,\n                x_types,\n                regressor_gp,\n                num_starting_points=100,\n                minimize_constraints_fun=None):\n    minimize_starting_points = [lib_data.rand(x_bounds, x_types) \\\n                                    for i in range(0, num_starting_points)]\n    outputs = selection(acquisition_function, samples_y_aggregation,\n                        x_bounds, x_types, regressor_gp,\n                        minimize_starting_points,\n                        minimize_constraints_fun=minimize_constraints_fun)\n    return outputs",
    "docstring": "Selecte R value"
  },
  {
    "code": "def _get_vlanid(self, context):\n        segment = context.bottom_bound_segment\n        if segment and self.check_segment(segment):\n            return segment.get(api.SEGMENTATION_ID)",
    "docstring": "Returns vlan_id associated with a bound VLAN segment."
  },
  {
    "code": "def get(self, id=None, name=None):\n        if not (id is None) ^ (name is None):\n            raise ValueError(\"Either id or name must be set (but not both!)\")\n        if id is not None:\n            return super(TaskQueueManager, self).get(id=id)\n        return self.list(filters={\"name\": name})[0]",
    "docstring": "Get a task queue.\n\n        Either the id xor the name of the task type must be specified.\n\n        Args:\n            id (int, optional): The id of the task type to get.\n            name (str, optional): The name of the task type to get.\n\n        Returns:\n            :class:`saltant.models.task_queue.TaskQueue`:\n                A task queue model instance representing the task queue\n                requested.\n\n        Raises:\n            ValueError: Neither id nor name were set *or* both id and\n                name were set."
  },
  {
    "code": "def __walk_rec(self, top, rec):\n        if not rec or os.path.islink(top) or not os.path.isdir(top):\n            yield top\n        else:\n            for root, dirs, files in os.walk(top):\n                yield root",
    "docstring": "Yields each subdirectories of top, doesn't follow symlinks.\n        If rec is false, only yield top.\n\n        @param top: root directory.\n        @type top: string\n        @param rec: recursive flag.\n        @type rec: bool\n        @return: path of one subdirectory.\n        @rtype: string"
  },
  {
    "code": "def intSize(self, obj):\n        if obj < 0:\n            return 8\n        elif obj <= 0xFF:\n            return 1\n        elif obj <= 0xFFFF:\n            return 2\n        elif obj <= 0xFFFFFFFF:\n            return 4\n        elif obj <= 0x7FFFFFFFFFFFFFFF:\n            return 8\n        elif obj <= 0xffffffffffffffff:\n            return 16\n        else:\n            raise InvalidPlistException(\"Core Foundation can't handle integers with size greater than 8 bytes.\")",
    "docstring": "Returns the number of bytes necessary to store the given integer."
  },
  {
    "code": "def _final_frame_length(header, final_frame_bytes):\n    final_frame_length = 4\n    final_frame_length += 4\n    final_frame_length += header.algorithm.iv_len\n    final_frame_length += 4\n    final_frame_length += final_frame_bytes\n    final_frame_length += header.algorithm.auth_len\n    return final_frame_length",
    "docstring": "Calculates the length of a final ciphertext frame, given a complete header\n    and the number of bytes of ciphertext in the final frame.\n\n    :param header: Complete message header object\n    :type header: aws_encryption_sdk.structures.MessageHeader\n    :param int final_frame_bytes: Bytes of ciphertext in the final frame\n    :rtype: int"
  },
  {
    "code": "def setDriftLength(self, x):\n        if x != self.getDriftLength():\n            self._setDriftList(x)\n            self.refresh = True",
    "docstring": "set lengths for drift sections\n\n        :param x: single double or list\n        :return: None\n\n        :Example:\n\n        >>> import beamline\n        >>> chi = beamline.mathutils.Chicane(bend_length=1,bend_field=0.5,drift_length=1,gamma=1000)\n        >>> chi.getMatrix()\n        >>> r56 = chi.getR(5,6)  # r56 = -0.432\n        >>> chi.setDriftLength([2,4,2])\n        >>> # same effect (to R56) as ``chi.setDriftLength([2,4])`` or ``chi.setDriftLength([2])``\n        >>> # or ``chi.setDriftLength(2)``\n        >>> r56 = chi.getR(5,6)  # r56 = -0.620"
  },
  {
    "code": "def bind_port(self, context):\n        port = context.current\n        log_context(\"bind_port: port\", port)\n        for segment in context.segments_to_bind:\n            physnet = segment.get(driver_api.PHYSICAL_NETWORK)\n            segment_type = segment[driver_api.NETWORK_TYPE]\n            if not physnet:\n                if (segment_type == n_const.TYPE_VXLAN and self.manage_fabric):\n                    if self._bind_fabric(context, segment):\n                        continue\n            elif (port.get(portbindings.VNIC_TYPE)\n                    == portbindings.VNIC_BAREMETAL):\n                if (not self.managed_physnets or\n                        physnet in self.managed_physnets):\n                    if self._bind_baremetal_port(context, segment):\n                        continue\n            LOG.debug(\"Arista mech driver unable to bind port %(port)s to \"\n                      \"%(seg_type)s segment on physical_network %(physnet)s\",\n                      {'port': port.get('id'), 'seg_type': segment_type,\n                       'physnet': physnet})",
    "docstring": "Bind port to a network segment.\n\n        Provisioning request to Arista Hardware to plug a host\n        into appropriate network is done when the port is created\n        this simply tells the ML2 Plugin that we are binding the port"
  },
  {
    "code": "def get_machines_by_groups(self, groups):\n        if not isinstance(groups, list):\n            raise TypeError(\"groups can only be an instance of type list\")\n        for a in groups[:10]:\n            if not isinstance(a, basestring):\n                raise TypeError(\n                        \"array can only contain objects of type basestring\")\n        machines = self._call(\"getMachinesByGroups\",\n                     in_p=[groups])\n        machines = [IMachine(a) for a in machines]\n        return machines",
    "docstring": "Gets all machine references which are in one of the specified groups.\n\n        in groups of type str\n            What groups to match. The usual group list rules apply, i.e.\n            passing an empty list will match VMs in the toplevel group, likewise\n            the empty string.\n\n        return machines of type :class:`IMachine`\n            All machines which matched."
  },
  {
    "code": "def _digitize_lons(lons, lon_bins):\n    if cross_idl(lon_bins[0], lon_bins[-1]):\n        idx = numpy.zeros_like(lons, dtype=numpy.int)\n        for i_lon in range(len(lon_bins) - 1):\n            extents = get_longitudinal_extent(lons, lon_bins[i_lon + 1])\n            lon_idx = extents > 0\n            if i_lon != 0:\n                extents = get_longitudinal_extent(lon_bins[i_lon], lons)\n                lon_idx &= extents >= 0\n            idx[lon_idx] = i_lon\n        return numpy.array(idx)\n    else:\n        return numpy.digitize(lons, lon_bins) - 1",
    "docstring": "Return indices of the bins to which each value in lons belongs.\n    Takes into account the case in which longitude values cross the\n    international date line.\n\n    :parameter lons:\n        An instance of `numpy.ndarray`.\n    :parameter lons_bins:\n        An instance of `numpy.ndarray`."
  },
  {
    "code": "def parse(self, string, evaluate_result=True):\n        m = self._match_re.match(string)\n        if m is None:\n            return None\n        if evaluate_result:\n            return self.evaluate_result(m)\n        else:\n            return Match(self, m)",
    "docstring": "Match my format to the string exactly.\n\n        Return a Result or Match instance or None if there's no match."
  },
  {
    "code": "def validate(self, url):\n        if not url.startswith('http') or not 'github' in url:\n            bot.error('Test of preview must be given a Github repostitory.')\n            return False\n        if not self._validate_preview(url):\n            return False\n        return True",
    "docstring": "takes in a Github repository for validation of preview and \n            runtime (and possibly tests passing?"
  },
  {
    "code": "def read_message(self):\n        msg = \"\"\n        num_blank_lines = 0\n        while True:\n            with self._reader_lock:\n                line = self.input_stream.readline()\n            if line == \"end\\n\":\n                break\n            elif line == \"\":\n                raise StormWentAwayError()\n            elif line == \"\\n\":\n                num_blank_lines += 1\n                if num_blank_lines % 1000 == 0:\n                    log.warn(\n                        \"While trying to read a command or pending task \"\n                        \"ID, Storm has instead sent %s '\\\\n' messages.\",\n                        num_blank_lines,\n                    )\n                continue\n            msg = \"{}{}\\n\".format(msg, line[0:-1])\n        try:\n            return json.loads(msg)\n        except Exception:\n            log.error(\"JSON decode error for message: %r\", msg, exc_info=True)\n            raise",
    "docstring": "The Storm multilang protocol consists of JSON messages followed by\n        a newline and \"end\\n\".\n\n        All of Storm's messages (for either bolts or spouts) should be of the\n        form::\n\n            '<command or task_id form prior emit>\\\\nend\\\\n'\n\n        Command example, an incoming Tuple to a bolt::\n\n            '{ \"id\": \"-6955786537413359385\",  \"comp\": \"1\", \"stream\": \"1\", \"task\": 9, \"tuple\": [\"snow white and the seven dwarfs\", \"field2\", 3]}\\\\nend\\\\n'\n\n        Command example for a spout to emit its next Tuple::\n\n            '{\"command\": \"next\"}\\\\nend\\\\n'\n\n        Example, the task IDs a prior emit was sent to::\n\n            '[12, 22, 24]\\\\nend\\\\n'\n\n        The edge case of where we read ``''`` from ``input_stream`` indicating\n        EOF, usually means that communication with the supervisor has been\n        severed."
  },
  {
    "code": "def get_grouped_indices(self, voigt=False, **kwargs):\n        if voigt:\n            array = self.voigt\n        else:\n            array = self\n        indices = list(itertools.product(*[range(n) for n in array.shape]))\n        remaining = indices.copy()\n        grouped = [list(zip(*np.where(np.isclose(array, 0, **kwargs))))]\n        remaining = [i for i in remaining if i not in grouped[0]]\n        while remaining:\n            new = list(zip(*np.where(np.isclose(\n                array, array[remaining[0]], **kwargs))))\n            grouped.append(new)\n            remaining = [i for i in remaining if i not in new]\n        return [g for g in grouped if g]",
    "docstring": "Gets index sets for equivalent tensor values\n\n        Args:\n            voigt (bool): whether to get grouped indices\n                of voigt or full notation tensor, defaults\n                to false\n            **kwargs: keyword args for np.isclose.  Can take atol\n                and rtol for absolute and relative tolerance, e. g.\n\n                >>> tensor.group_array_indices(atol=1e-8)\n\n                or\n\n                >>> tensor.group_array_indices(rtol=1e-5)\n\n        Returns:\n            list of index groups where tensor values are equivalent to\n            within tolerances"
  },
  {
    "code": "def _client_connection(self, conn, addr):\n        log.debug('Established connection with %s:%d', addr[0], addr[1])\n        conn.settimeout(self.socket_timeout)\n        try:\n            while self.__up:\n                msg = conn.recv(self.buffer_size)\n                if not msg:\n                    continue\n                log.debug('[%s] Received %s from %s. Adding in the queue', time.time(), msg, addr)\n                self.buffer.put((msg, '{}:{}'.format(addr[0], addr[1])))\n        except socket.timeout:\n            if not self.__up:\n                return\n            log.debug('Connection %s:%d timed out', addr[1], addr[0])\n            raise ListenerException('Connection %s:%d timed out' % addr)\n        finally:\n            log.debug('Closing connection with %s', addr)\n            conn.close()",
    "docstring": "Handle the connecition with one client."
  },
  {
    "code": "def elekta_icon_fbp(ray_transform,\n                    padding=False, filter_type='Hann', frequency_scaling=0.6,\n                    parker_weighting=True):\n    fbp_op = odl.tomo.fbp_op(ray_transform,\n                             padding=padding,\n                             filter_type=filter_type,\n                             frequency_scaling=frequency_scaling)\n    if parker_weighting:\n        parker_weighting = odl.tomo.parker_weighting(ray_transform)\n        fbp_op = fbp_op * parker_weighting\n    return fbp_op",
    "docstring": "Approximation of the FDK reconstruction used in the Elekta Icon.\n\n    Parameters\n    ----------\n    ray_transform : `RayTransform`\n        The ray transform to be used, should have an Elekta Icon geometry.\n    padding : bool, optional\n        Whether the FBP filter should use padding, increases memory use\n        significantly.\n    filter_type : str, optional\n        Type of filter to apply in the FBP filter.\n    frequency_scaling : float, optional\n        Frequency scaling for FBP filter.\n    parker_weighting : bool, optional\n        Whether Parker weighting should be applied to compensate for partial\n        scan.\n\n    Returns\n    -------\n    elekta_icon_fbp : `DiscreteLp`\n\n    Examples\n    --------\n    Create default FBP for default geometry:\n\n    >>> from odl.contrib import tomo\n    >>> geometry = tomo.elekta_icon_geometry()\n    >>> space = tomo.elekta_icon_space()\n    >>> ray_transform = odl.tomo.RayTransform(space, geometry)\n    >>> fbp_op = tomo.elekta_icon_fbp(ray_transform)"
  },
  {
    "code": "def calculate_first_digit(number):\n    sum = 0\n    if len(number) == 9:\n        weights = CPF_WEIGHTS[0]\n    else:\n        weights = CNPJ_WEIGHTS[0]\n    for i in range(len(number)):\n        sum = sum + int(number[i]) * weights[i]\n    rest_division = sum % DIVISOR\n    if rest_division < 2:\n        return '0'\n    return str(11 - rest_division)",
    "docstring": "This function calculates the first check digit of a\n        cpf or cnpj.\n\n        :param number: cpf (length 9) or cnpf (length 12) \n            string to check the first digit. Only numbers.\n        :type number: string\n        :returns: string -- the first digit"
  },
  {
    "code": "def reset(self, base=0, item=0, leng=None, refs=None,\n                                    both=True, kind=None, type=None):\n        if base < 0:\n            raise ValueError('invalid option: %s=%r' % ('base', base))\n        else:\n            self.base = base\n        if item < 0:\n            raise ValueError('invalid option: %s=%r' % ('item', item))\n        else:\n            self.item = item\n        if leng in _all_lengs:\n            self.leng = leng\n        else:\n            raise ValueError('invalid option: %s=%r' % ('leng', leng))\n        if refs in _all_refs:\n            self.refs = refs\n        else:\n            raise ValueError('invalid option: %s=%r' % ('refs', refs))\n        if both in (False, True):\n            self.both = both\n        else:\n            raise ValueError('invalid option: %s=%r' % ('both', both))\n        if kind in _all_kinds:\n            self.kind = kind\n        else:\n            raise ValueError('invalid option: %s=%r' % ('kind', kind))\n        self.type = type",
    "docstring": "Reset all specified attributes."
  },
  {
    "code": "def is_almost_simplicial(G, n):\n    for w in G[n]:\n        if all(u in G[v] for u, v in itertools.combinations(G[n], 2) if u != w and v != w):\n            return True\n    return False",
    "docstring": "Determines whether a node n in G is almost simplicial.\n\n    Parameters\n    ----------\n    G : NetworkX graph\n        The graph on which to check whether node n is almost simplicial.\n    n : node\n        A node in graph G.\n\n    Returns\n    -------\n    is_almost_simplicial : bool\n        True if all but one of its neighbors induce a clique\n\n    Examples\n    --------\n    This example checks whether node 0 is simplicial or almost simplicial for\n    a :math:`K_5` complete graph with one edge removed.\n\n    >>> import dwave_networkx as dnx\n    >>> import networkx as nx\n    >>> K_5 = nx.complete_graph(5)\n    >>> K_5.remove_edge(1,3)\n    >>> dnx.is_simplicial(K_5, 0)\n    False\n    >>> dnx.is_almost_simplicial(K_5, 0)\n    True"
  },
  {
    "code": "def get_filter(self):\n        q = self.q().select('name').expand('filter')\n        response = self.session.get(self.build_url(''), params=q.as_params())\n        if not response:\n            return None\n        data = response.json()\n        return data.get('criteria', None)",
    "docstring": "Returns the filter applie to this column"
  },
  {
    "code": "def analyse_text(text):\n        if re.match(r'^\\s*REBOL\\s*\\[', text, re.IGNORECASE):\n            return 1.0\n        elif re.search(r'\\s*REBOL\\s*[', text, re.IGNORECASE):\n            return 0.5",
    "docstring": "Check if code contains REBOL header and so it probably not R code"
  },
  {
    "code": "def _parse_flowcontrol_receive(self, config):\n        value = 'off'\n        match = re.search(r'flowcontrol receive (\\w+)$', config, re.M)\n        if match:\n            value = match.group(1)\n        return dict(flowcontrol_receive=value)",
    "docstring": "Scans the config block and returns the flowcontrol receive value\n\n        Args:\n            config (str): The interface config block to scan\n\n        Returns:\n            dict: Returns a dict object with the flowcontrol receive value\n                retrieved from the config block.  The returned dict object\n                is intended to be merged into the interface resource dict"
  },
  {
    "code": "def hist(darray, figsize=None, size=None, aspect=None, ax=None, **kwargs):\n    ax = get_axis(figsize, size, aspect, ax)\n    xincrease = kwargs.pop('xincrease', None)\n    yincrease = kwargs.pop('yincrease', None)\n    xscale = kwargs.pop('xscale', None)\n    yscale = kwargs.pop('yscale', None)\n    xticks = kwargs.pop('xticks', None)\n    yticks = kwargs.pop('yticks', None)\n    xlim = kwargs.pop('xlim', None)\n    ylim = kwargs.pop('ylim', None)\n    no_nan = np.ravel(darray.values)\n    no_nan = no_nan[pd.notnull(no_nan)]\n    primitive = ax.hist(no_nan, **kwargs)\n    ax.set_title('Histogram')\n    ax.set_xlabel(label_from_attrs(darray))\n    _update_axes(ax, xincrease, yincrease, xscale, yscale,\n                 xticks, yticks, xlim, ylim)\n    return primitive",
    "docstring": "Histogram of DataArray\n\n    Wraps :func:`matplotlib:matplotlib.pyplot.hist`\n\n    Plots N dimensional arrays by first flattening the array.\n\n    Parameters\n    ----------\n    darray : DataArray\n        Can be any dimension\n    figsize : tuple, optional\n        A tuple (width, height) of the figure in inches.\n        Mutually exclusive with ``size`` and ``ax``.\n    aspect : scalar, optional\n        Aspect ratio of plot, so that ``aspect * size`` gives the width in\n        inches. Only used if a ``size`` is provided.\n    size : scalar, optional\n        If provided, create a new figure for the plot with the given size.\n        Height (in inches) of each plot. See also: ``aspect``.\n    ax : matplotlib axes object, optional\n        Axis on which to plot this figure. By default, use the current axis.\n        Mutually exclusive with ``size`` and ``figsize``.\n    **kwargs : optional\n        Additional keyword arguments to matplotlib.pyplot.hist"
  },
  {
    "code": "def _module_callers(parser, modname, result):\n    if modname in result:\n        return\n    module = parser.get(modname)\n    mresult = {}\n    if module is not None:\n        for xname, xinst in module.executables():\n            _exec_callers(xinst, mresult)\n        result[modname] = mresult\n        for depkey in module.dependencies:\n            depmod = depkey.split('.')[0].lower()\n            _module_callers(parser, depmod, result)",
    "docstring": "Adds any calls to executables contained in the specified module."
  },
  {
    "code": "def function_application(func):\n    if func not in NUMEXPR_MATH_FUNCS:\n        raise ValueError(\"Unsupported mathematical function '%s'\" % func)\n    @with_doc(func)\n    @with_name(func)\n    def mathfunc(self):\n        if isinstance(self, NumericalExpression):\n            return NumExprFactor(\n                \"{func}({expr})\".format(func=func, expr=self._expr),\n                self.inputs,\n                dtype=float64_dtype,\n            )\n        else:\n            return NumExprFactor(\n                \"{func}(x_0)\".format(func=func),\n                (self,),\n                dtype=float64_dtype,\n            )\n    return mathfunc",
    "docstring": "Factory function for producing function application methods for Factor\n    subclasses."
  },
  {
    "code": "def store(self, stream, linesep=os.linesep):\n        for k, v in self.items():\n            write_key_val(stream, k, v, linesep)\n        stream.write(linesep.encode('utf-8'))",
    "docstring": "Serialize this section and write it to a binary stream"
  },
  {
    "code": "def isAboveUpperDetectionLimit(self):\n        if self.isUpperDetectionLimit():\n            return True\n        result = self.getResult()\n        if result and str(result).strip().startswith(UDL):\n            return True\n        if api.is_floatable(result):\n            return api.to_float(result) > self.getUpperDetectionLimit()\n        return False",
    "docstring": "Returns True if the result is above the Upper Detection Limit or\n        if Upper Detection Limit has been manually set"
  },
  {
    "code": "def _non_blocking_wrapper(self, method, *args, **kwargs):\n    exceptions = []\n    def task_run(task):\n      try:\n        getattr(task, method)(*args, **kwargs)\n      except Exception as e:\n        exceptions.append(e)\n    threads = [threading.Thread(name=f'task_{method}_{i}',\n                                target=task_run, args=[t])\n               for i, t in enumerate(self.tasks)]\n    for thread in threads:\n      thread.start()\n    for thread in threads:\n      thread.join()\n    if exceptions:\n      raise exceptions[0]",
    "docstring": "Runs given method on every task in the job. Blocks until all tasks finish. Propagates exception from first\n    failed task."
  },
  {
    "code": "def request_help(self, req, msg):\n        if not msg.arguments:\n            for name, method in sorted(self._request_handlers.items()):\n                doc = method.__doc__\n                req.inform(name, doc)\n            num_methods = len(self._request_handlers)\n            return req.make_reply(\"ok\", str(num_methods))\n        else:\n            name = msg.arguments[0]\n            if name in self._request_handlers:\n                method = self._request_handlers[name]\n                doc = method.__doc__.strip()\n                req.inform(name, doc)\n                return req.make_reply(\"ok\", \"1\")\n            return req.make_reply(\"fail\", \"Unknown request method.\")",
    "docstring": "Return help on the available requests.\n\n        Return a description of the available requests using a sequence of\n        #help informs.\n\n        Parameters\n        ----------\n        request : str, optional\n            The name of the request to return help for (the default is to\n            return help for all requests).\n\n        Informs\n        -------\n        request : str\n            The name of a request.\n        description : str\n            Documentation for the named request.\n\n        Returns\n        -------\n        success : {'ok', 'fail'}\n            Whether sending the help succeeded.\n        informs : int\n            Number of #help inform messages sent.\n\n        Examples\n        --------\n        ::\n\n            ?help\n            #help halt ...description...\n            #help help ...description...\n            ...\n            !help ok 5\n\n            ?help halt\n            #help halt ...description...\n            !help ok 1"
  },
  {
    "code": "def _repr_html_():\n    from bonobo.commands.version import get_versions\n    return (\n        '<div style=\"padding: 8px;\">'\n        '  <div style=\"float: left; width: 20px; height: 20px;\">{}</div>'\n        '  <pre style=\"white-space: nowrap; padding-left: 8px\">{}</pre>'\n        \"</div>\"\n    ).format(__logo__, \"<br/>\".join(get_versions(all=True)))",
    "docstring": "This allows to easily display a version snippet in Jupyter."
  },
  {
    "code": "def get_master_status(**connection_args):\n    mod = sys._getframe().f_code.co_name\n    log.debug('%s<--', mod)\n    conn = _connect(**connection_args)\n    if conn is None:\n        return []\n    rtnv = __do_query_into_hash(conn, \"SHOW MASTER STATUS\")\n    conn.close()\n    if not rtnv:\n        rtnv.append([])\n    log.debug('%s-->%s', mod, len(rtnv[0]))\n    return rtnv[0]",
    "docstring": "Retrieves the master status from the minion.\n\n    Returns::\n\n        {'host.domain.com': {'Binlog_Do_DB': '',\n                         'Binlog_Ignore_DB': '',\n                         'File': 'mysql-bin.000021',\n                         'Position': 107}}\n\n    CLI Example:\n\n    .. code-block:: bash\n\n        salt '*' mysql.get_master_status"
  },
  {
    "code": "def _merge_report(self, target, new):\n        time = None\n        if 'ts' in new['parsed']:\n            time = new['parsed']['ts']\n        if (target.get('lastSeenDate', None) and\n                time and\n                    target['lastSeenDate'] < time):\n            target['lastSeenDate'] = time\n        query_millis = int(new['parsed']['stats']['millis'])\n        target['stats']['totalTimeMillis'] += query_millis\n        target['stats']['count'] += 1\n        target['stats']['avgTimeMillis'] = target['stats']['totalTimeMillis'] / target['stats']['count']",
    "docstring": "Merges a new report into the target report"
  },
  {
    "code": "def _handle_github(self):\n        value = click.prompt(\n            _BUG + click.style(\n                '1. Open an issue by typing \"open\";\\n',\n                fg='green',\n            ) + click.style(\n                '2. Print human-readable information by typing '\n                '\"print\";\\n',\n                fg='yellow',\n            ) + click.style(\n                '3. See the full traceback without submitting details '\n                '(default: \"ignore\").\\n\\n',\n                fg='red',\n            ) + 'Please select an action by typing its name',\n            type=click.Choice([\n                'open',\n                'print',\n                'ignore',\n            ], ),\n            default='ignore',\n        )\n        getattr(self, '_process_' + value)()",
    "docstring": "Handle exception and submit it as GitHub issue."
  },
  {
    "code": "def inertial_advective_wind(u, v, u_geostrophic, v_geostrophic, dx, dy, lats):\n    r\n    f = coriolis_parameter(lats)\n    dugdy, dugdx = gradient(u_geostrophic, deltas=(dy, dx), axes=(-2, -1))\n    dvgdy, dvgdx = gradient(v_geostrophic, deltas=(dy, dx), axes=(-2, -1))\n    u_component = -(u * dvgdx + v * dvgdy) / f\n    v_component = (u * dugdx + v * dugdy) / f\n    return u_component, v_component",
    "docstring": "r\"\"\"Calculate the inertial advective wind.\n\n    .. math:: \\frac{\\hat k}{f} \\times (\\vec V \\cdot \\nabla)\\hat V_g\n\n    .. math:: \\frac{\\hat k}{f} \\times \\left[ \\left( u \\frac{\\partial u_g}{\\partial x} + v\n              \\frac{\\partial u_g}{\\partial y} \\right) \\hat i + \\left( u \\frac{\\partial v_g}\n              {\\partial x} + v \\frac{\\partial v_g}{\\partial y} \\right) \\hat j \\right]\n\n    .. math:: \\left[ -\\frac{1}{f}\\left(u \\frac{\\partial v_g}{\\partial x} + v\n              \\frac{\\partial v_g}{\\partial y} \\right) \\right] \\hat i + \\left[ \\frac{1}{f}\n              \\left( u \\frac{\\partial u_g}{\\partial x} + v \\frac{\\partial u_g}{\\partial y}\n              \\right) \\right] \\hat j\n\n    This formula is based on equation 27 of [Rochette2006]_.\n\n    Parameters\n    ----------\n    u : (M, N) ndarray\n        x component of the advecting wind\n    v : (M, N) ndarray\n        y component of the advecting wind\n    u_geostrophic : (M, N) ndarray\n        x component of the geostrophic (advected) wind\n    v_geostrophic : (M, N) ndarray\n        y component of the geostrophic (advected) wind\n    dx : float or ndarray\n        The grid spacing(s) in the x-direction. If an array, there should be one item less than\n        the size of `u` along the applicable axis.\n    dy : float or ndarray\n        The grid spacing(s) in the y-direction. If an array, there should be one item less than\n        the size of `u` along the applicable axis.\n    lats : (M, N) ndarray\n        latitudes of the wind data in radians or with appropriate unit information attached\n\n    Returns\n    -------\n    (M, N) ndarray\n        x component of inertial advective wind\n    (M, N) ndarray\n        y component of inertial advective wind\n\n    Notes\n    -----\n    Many forms of the inertial advective wind assume the advecting and advected\n    wind to both be the geostrophic wind. To do so, pass the x and y components\n    of the geostrophic with for u and u_geostrophic/v and v_geostrophic.\n\n    If inputs have more than two dimensions, they are assumed to have either leading dimensions\n    of (x, y) or trailing dimensions of (y, x), depending on the value of ``dim_order``."
  },
  {
    "code": "def _parse_and_sort_accept_header(accept_header):\n    return sorted([_split_into_mimetype_and_priority(x) for x in accept_header.split(',')],\n                  key=lambda x: x[1], reverse=True)",
    "docstring": "Parse and sort the accept header items.\n\n    >>> _parse_and_sort_accept_header('application/json;q=0.5, text/*')\n    [('text/*', 1.0), ('application/json', 0.5)]"
  },
  {
    "code": "def visit_setcomp(self, node, parent):\n        newnode = nodes.SetComp(node.lineno, node.col_offset, parent)\n        newnode.postinit(\n            self.visit(node.elt, newnode),\n            [self.visit(child, newnode) for child in node.generators],\n        )\n        return newnode",
    "docstring": "visit a SetComp node by returning a fresh instance of it"
  },
  {
    "code": "def MetaGraph(self):\n    if self._meta_graph is None:\n      raise ValueError('There is no metagraph in this EventAccumulator')\n    meta_graph = meta_graph_pb2.MetaGraphDef()\n    meta_graph.ParseFromString(self._meta_graph)\n    return meta_graph",
    "docstring": "Return the metagraph definition, if there is one.\n\n    Raises:\n      ValueError: If there is no metagraph for this run.\n\n    Returns:\n      The `meta_graph_def` proto."
  },
  {
    "code": "def global_exception_handler(handler):\n    if not hasattr(handler, \"__call__\"):\n        raise TypeError(\"exception handlers must be callable\")\n    log.info(\"setting a new global exception handler\")\n    state.global_exception_handlers.append(weakref.ref(handler))\n    return handler",
    "docstring": "add a callback for when an exception goes uncaught in any greenlet\n\n    :param handler:\n        the callback function. must be a function taking 3 arguments:\n\n        - ``klass`` the exception class\n        - ``exc`` the exception instance\n        - ``tb`` the traceback object\n    :type handler: function\n\n    Note also that the callback is only held by a weakref, so if all other refs\n    to the function are lost it will stop handling greenlets' exceptions"
  },
  {
    "code": "def get_or_none(cls, video_id, language_code):\n        try:\n            transcript = cls.objects.get(video__edx_video_id=video_id, language_code=language_code)\n        except cls.DoesNotExist:\n            transcript = None\n        return transcript",
    "docstring": "Returns a data model object if found or none otherwise.\n\n        Arguments:\n            video_id(unicode): video id to which transcript may be associated\n            language_code(unicode): language of the requested transcript"
  },
  {
    "code": "def make_response(self,\n                      data: Any = None,\n                      **kwargs: Any) -> Any:\n        r\n        if not self._valid_request:\n            logger.error('Request not validated, cannot make response')\n            raise self.make_error('Request not validated before, cannot make '\n                                  'response')\n        if data is None and self.response_factory is None:\n            logger.error('Response data omit, but no response factory is used')\n            raise self.make_error('Response data could be omitted only when '\n                                  'response factory is used')\n        response_schema = getattr(self.module, 'response', None)\n        if response_schema is not None:\n            self._validate(data, response_schema)\n        if self.response_factory is not None:\n            return self.response_factory(\n                *([data] if data is not None else []),\n                **kwargs)\n        return data",
    "docstring": "r\"\"\"Validate response data and wrap it inside response factory.\n\n        :param data: Response data. Could be ommited.\n        :param \\*\\*kwargs: Keyword arguments to be passed to response factory."
  },
  {
    "code": "def encodeSentence(self, *words):\n        encoded = map(self.encodeWord, words)\n        encoded = b''.join(encoded)\n        encoded += b'\\x00'\n        return encoded",
    "docstring": "Encode given sentence in API format.\n\n        :param words: Words to endoce.\n        :returns: Encoded sentence."
  },
  {
    "code": "def json_2_text(inp, out, verbose = False):\n    for root, dirs, filenames in os.walk(inp):\n        for f in filenames:\n            log = codecs.open(os.path.join(root, f), 'r')\n            j_obj = json.load(log)\n            j_obj = json_format(j_obj)\n            textWriter(j_obj, out, verbose)",
    "docstring": "Convert a Wikipedia article to Text object.\n    Concatenates the sections in wikipedia file and rearranges other information so it\n    can be interpreted as a Text object.\n\n    Links and other elements with start and end positions are annotated\n    as layers.\n\n    Parameters\n    ----------\n    inp: directory of parsed et.wikipedia articles in json format\n\n    out: output directory of .txt files\n\n    verbose: if True, prints every article title and total count of converted files\n             if False prints every 50th count\n    Returns\n    -------\n    estnltk.text.Text\n        The Text object."
  },
  {
    "code": "def register(self, notification_cls=None):\n        self.loaded = True\n        display_names = [n.display_name for n in self.registry.values()]\n        if (\n            notification_cls.name not in self.registry\n            and notification_cls.display_name not in display_names\n        ):\n            self.registry.update({notification_cls.name: notification_cls})\n            models = getattr(notification_cls, \"models\", [])\n            if not models and getattr(notification_cls, \"model\", None):\n                models = [getattr(notification_cls, \"model\")]\n            for model in models:\n                try:\n                    if notification_cls.name not in [\n                        n.name for n in self.models[model]\n                    ]:\n                        self.models[model].append(notification_cls)\n                except KeyError:\n                    self.models.update({model: [notification_cls]})\n        else:\n            raise AlreadyRegistered(\n                f\"Notification {notification_cls.name}: \"\n                f\"{notification_cls.display_name} is already registered.\"\n            )",
    "docstring": "Registers a Notification class unique by name."
  },
  {
    "code": "def fetch(self, url, body=None, headers=None):\n        if body:\n            method = 'POST'\n        else:\n            method = 'GET'\n        if headers is None:\n            headers = {}\n        if not (url.startswith('http://') or url.startswith('https://')):\n            raise ValueError('URL is not a HTTP URL: %r' % (url,))\n        httplib2_response, content = self.httplib2.request(\n            url, method, body=body, headers=headers)\n        try:\n            final_url = httplib2_response['content-location']\n        except KeyError:\n            assert not httplib2_response.previous\n            assert httplib2_response.status != 200\n            final_url = url\n        return HTTPResponse(\n            body=content,\n            final_url=final_url,\n            headers=dict(httplib2_response.items()),\n            status=httplib2_response.status,\n            )",
    "docstring": "Perform an HTTP request\n\n        @raises Exception: Any exception that can be raised by httplib2\n\n        @see: C{L{HTTPFetcher.fetch}}"
  },
  {
    "code": "def add(self, scene):\n        if not isinstance(scene, Scene):\n            raise TypeError()\n        self.__scenes.append(scene)",
    "docstring": "Add scene."
  },
  {
    "code": "def _find_ancillary_vars(self, ds, refresh=False):\n        if self._ancillary_vars.get(ds, None) and refresh is False:\n            return self._ancillary_vars[ds]\n        self._ancillary_vars[ds] = []\n        for name, var in ds.variables.items():\n            if hasattr(var, 'ancillary_variables'):\n                for anc_name in var.ancillary_variables.split(\" \"):\n                    if anc_name in ds.variables:\n                        self._ancillary_vars[ds].append(anc_name)\n            if hasattr(var, 'grid_mapping'):\n                gm_name = var.grid_mapping\n                if gm_name in ds.variables:\n                    self._ancillary_vars[ds].append(gm_name)\n        return self._ancillary_vars[ds]",
    "docstring": "Returns a list of variable names that are defined as ancillary\n        variables in the dataset ds.\n\n        An ancillary variable generally is a metadata container and referenced\n        from other variables via a string reference in an attribute.\n\n        - via ancillary_variables (3.4)\n        - \"grid mapping var\" (5.6)\n        - TODO: more?\n\n        The result is cached by the passed in dataset object inside of this\n        checker. Pass refresh=True to redo the cached value.\n\n        :param netCDF4.Dataset ds: An open netCDF dataset\n        :param bool refresh: if refresh is set to True, the cache is\n                             invalidated.\n        :rtype: list\n        :return: List of variable names (str) that are defined as ancillary\n                 variables in the dataset ds."
  },
  {
    "code": "def markInputline( self, markerString = \">!<\" ):\n        line_str = self.line\n        line_column = self.column - 1\n        if markerString:\n            line_str = \"\".join((line_str[:line_column],\n                                markerString, line_str[line_column:]))\n        return line_str.strip()",
    "docstring": "Extracts the exception line from the input string, and marks\n           the location of the exception with a special symbol."
  },
  {
    "code": "def wr_tsv(self, fout_tsv):\n        with open(fout_tsv, 'w') as prt:\n            kws_tsv = {\n                'fld2fmt': {f:'{:8.2e}' for f in self.flds_cur if f[:2] == 'p_'},\n                'prt_flds':self.flds_cur}\n            prt_tsv_sections(prt, self.desc2nts['sections'], **kws_tsv)\n            print(\"  WROTE: {TSV}\".format(TSV=fout_tsv))",
    "docstring": "Print grouped GOEA results into a tab-separated file."
  },
  {
    "code": "def geometry_identifiers(self):\n        identifiers = {mesh.identifier_md5: name\n                       for name, mesh in self.geometry.items()}\n        return identifiers",
    "docstring": "Look up geometries by identifier MD5\n\n        Returns\n        ---------\n        identifiers: dict, identifier md5: key in self.geometry"
  },
  {
    "code": "def place_oceans_at_map_borders(world):\n    ocean_border = int(min(30, max(world.width / 5, world.height / 5)))\n    def place_ocean(x, y, i):\n        world.layers['elevation'].data[y, x] = \\\n            (world.layers['elevation'].data[y, x] * i) / ocean_border\n    for x in range(world.width):\n        for i in range(ocean_border):\n            place_ocean(x, i, i)\n            place_ocean(x, world.height - i - 1, i)\n    for y in range(world.height):\n        for i in range(ocean_border):\n            place_ocean(i, y, i)\n            place_ocean(world.width - i - 1, y, i)",
    "docstring": "Lower the elevation near the border of the map"
  },
  {
    "code": "def spread_stats(stats, spreader=False):\n    spread = spread_t() if spreader else True\n    descendants = deque(stats)\n    while descendants:\n        _stats = descendants.popleft()\n        if spreader:\n            spread.clear()\n            yield _stats, spread\n        else:\n            yield _stats\n        if spread:\n            descendants.extend(_stats)",
    "docstring": "Iterates all descendant statistics under the given root statistics.\n\n    When ``spreader=True``, each iteration yields a descendant statistics and\n    `spread()` function together.  You should call `spread()` if you want to\n    spread the yielded statistics also."
  },
  {
    "code": "def filter_channels_by_status(\n        channel_states: List[NettingChannelState],\n        exclude_states: Optional[List[str]] = None,\n) -> List[NettingChannelState]:\n    if exclude_states is None:\n        exclude_states = []\n    states = []\n    for channel_state in channel_states:\n        if channel.get_status(channel_state) not in exclude_states:\n            states.append(channel_state)\n    return states",
    "docstring": "Filter the list of channels by excluding ones\n    for which the state exists in `exclude_states`."
  },
  {
    "code": "def add_environment_vars(config: MutableMapping[str, Any]):\n    for e in os.environ:\n        if re.match(\"BELBIO_\", e):\n            val = os.environ.get(e)\n            if val:\n                e.replace(\"BELBIO_\", \"\")\n                env_keys = e.lower().split(\"__\")\n                if len(env_keys) > 1:\n                    joined = '\"][\"'.join(env_keys)\n                    eval_config = f'config[\"{joined}\"] = val'\n                    try:\n                        eval(eval_config)\n                    except Exception as exc:\n                        log.warn(\"Cannot process {e} into config\")\n                else:\n                    config[env_keys[0]] = val",
    "docstring": "Override config with environment variables\n\n    Environment variables have to be prefixed with BELBIO_\n    which will be stripped before splitting on '__' and lower-casing\n    the environment variable name that is left into keys for the\n    config dictionary.\n\n    Example:\n        BELBIO_BEL_API__SERVERS__API_URL=http://api.bel.bio\n        1. BELBIO_BEL_API__SERVERS__API_URL ==> BEL_API__SERVERS__API_URL\n        2. BEL_API__SERVERS__API_URL ==> bel_api__servers__api_url\n        3. bel_api__servers__api_url ==> [bel_api, servers, api_url]\n        4. [bel_api, servers, api_url] ==> config['bel_api']['servers']['api_url'] = http://api.bel.bio"
  },
  {
    "code": "def get_db_versions(self, conn):\n        curs = conn.cursor()\n        query = 'select version from {}'.format(self.version_table)\n        try:\n            curs.execute(query)\n            return set(version for version, in curs.fetchall())\n        except:\n            raise VersioningNotInstalled('Run oq engine --upgrade-db')",
    "docstring": "Get all the versions stored in the database as a set.\n\n        :param conn: a DB API 2 connection"
  },
  {
    "code": "def _fingerprint(public_key, fingerprint_hash_type):\n    if fingerprint_hash_type:\n        hash_type = fingerprint_hash_type.lower()\n    else:\n        hash_type = 'sha256'\n    try:\n        hash_func = getattr(hashlib, hash_type)\n    except AttributeError:\n        raise CommandExecutionError(\n            'The fingerprint_hash_type {0} is not supported.'.format(\n                hash_type\n            )\n        )\n    try:\n        if six.PY2:\n            raw_key = public_key.decode('base64')\n        else:\n            raw_key = base64.b64decode(public_key, validate=True)\n    except binascii.Error:\n        return None\n    ret = hash_func(raw_key).hexdigest()\n    chunks = [ret[i:i + 2] for i in range(0, len(ret), 2)]\n    return ':'.join(chunks)",
    "docstring": "Return a public key fingerprint based on its base64-encoded representation\n\n    The fingerprint string is formatted according to RFC 4716 (ch.4), that is,\n    in the form \"xx:xx:...:xx\"\n\n    If the key is invalid (incorrect base64 string), return None\n\n    public_key\n        The public key to return the fingerprint for\n\n    fingerprint_hash_type\n        The public key fingerprint hash type that the public key fingerprint\n        was originally hashed with. This defaults to ``sha256`` if not specified.\n\n        .. versionadded:: 2016.11.4\n        .. versionchanged:: 2017.7.0: default changed from ``md5`` to ``sha256``"
  },
  {
    "code": "def add_node_from_appliance(self, appliance_id, x=0, y=0, compute_id=None):\n        try:\n            template = self.controller.appliances[appliance_id].data\n        except KeyError:\n            msg = \"Appliance {} doesn't exist\".format(appliance_id)\n            log.error(msg)\n            raise aiohttp.web.HTTPNotFound(text=msg)\n        template[\"x\"] = x\n        template[\"y\"] = y\n        node_type = template.pop(\"node_type\")\n        compute = self.controller.get_compute(template.pop(\"server\", compute_id))\n        name = template.pop(\"name\")\n        default_name_format = template.pop(\"default_name_format\", \"{name}-{0}\")\n        name = default_name_format.replace(\"{name}\", name)\n        node_id = str(uuid.uuid4())\n        node = yield from self.add_node(compute, name, node_id, node_type=node_type, **template)\n        return node",
    "docstring": "Create a node from an appliance"
  },
  {
    "code": "def LoadPlugins(cls):\n        if cls.PLUGINS_LOADED:\n            return\n        reg = ComponentRegistry()\n        for _, record in reg.load_extensions('iotile.update_record'):\n            cls.RegisterRecordType(record)\n        cls.PLUGINS_LOADED = True",
    "docstring": "Load all registered iotile.update_record plugins."
  },
  {
    "code": "def parse_barcode_file(fp, primer=None, header=False):\n    tr = trie.trie()\n    reader = csv.reader(fp)\n    if header:\n        next(reader)\n    records = (record for record in reader if record)\n    for record in records:\n        specimen, barcode = record[:2]\n        if primer is not None:\n            pr = primer\n        else:\n            pr = record[2]\n        for sequence in all_unambiguous(barcode + pr):\n            if sequence in tr:\n                raise ValueError(\"Duplicate sample: {0}, {1} both have {2}\",\n                                 specimen, tr[sequence], sequence)\n            logging.info('%s->%s', sequence, specimen)\n            tr[sequence] = specimen\n    return tr",
    "docstring": "Load label, barcode, primer records from a CSV file.\n\n    Returns a map from barcode -> label\n\n    Any additional columns are ignored"
  },
  {
    "code": "def pois_from_address(address, distance, amenities=None):\n    point = geocode(query=address)\n    return pois_from_point(point=point, amenities=amenities, distance=distance)",
    "docstring": "Get OSM points of Interests within some distance north, south, east, and west of\n    an address.\n\n    Parameters\n    ----------\n    address : string\n        the address to geocode to a lat-long point\n    distance : numeric\n        distance in meters\n    amenities : list\n        List of amenities that will be used for finding the POIs from the selected area. See available \n        amenities from: http://wiki.openstreetmap.org/wiki/Key:amenity\n\n    Returns\n    -------\n    GeoDataFrame"
  },
  {
    "code": "def memoize(func):\n    @wraps(func)\n    def memoizer(self):\n        if not hasattr(self, '_cache'):\n            self._cache = {}\n        if func.__name__ not in self._cache:\n            self._cache[func.__name__] = func(self)\n        return self._cache[func.__name__]\n    return memoizer",
    "docstring": "Memoize a method that should return the same result every time on a\n    given instance."
  },
  {
    "code": "def setupTable_glyf(self):\n        if not {\"glyf\", \"loca\"}.issubset(self.tables):\n            return\n        self.otf[\"loca\"] = newTable(\"loca\")\n        self.otf[\"glyf\"] = glyf = newTable(\"glyf\")\n        glyf.glyphs = {}\n        glyf.glyphOrder = self.glyphOrder\n        hmtx = self.otf.get(\"hmtx\")\n        allGlyphs = self.allGlyphs\n        for name in self.glyphOrder:\n            glyph = allGlyphs[name]\n            pen = TTGlyphPen(allGlyphs)\n            try:\n                glyph.draw(pen)\n            except NotImplementedError:\n                logger.error(\"%r has invalid curve format; skipped\", name)\n                ttGlyph = Glyph()\n            else:\n                ttGlyph = pen.glyph()\n                if (\n                    ttGlyph.isComposite()\n                    and hmtx is not None\n                    and self.autoUseMyMetrics\n                ):\n                    self.autoUseMyMetrics(ttGlyph, name, hmtx)\n            glyf[name] = ttGlyph",
    "docstring": "Make the glyf table."
  },
  {
    "code": "def get_item(self):\n        try:\n            item_lookup_session = get_item_lookup_session(runtime=self._runtime, proxy=self._proxy)\n            item_lookup_session.use_federated_bank_view()\n            item = item_lookup_session.get_item(self._item_id)\n        except errors.NotFound:\n            if self._section is not None:\n                question = self._section.get_question(self._item_id)\n                ils = self._section._get_item_lookup_session()\n                real_item_id = Id(question._my_map['itemId'])\n                item = ils.get_item(real_item_id)\n            else:\n                raise errors.NotFound()\n        return item.get_question()",
    "docstring": "Gets the ``Item``.\n\n        return: (osid.assessment.Item) - the assessment item\n        *compliance: mandatory -- This method must be implemented.*"
  },
  {
    "code": "def get_positions(self, attr=None):\n        pos = self.parent.get_positions(self)\n        try:\n            if attr is not None:\n                attr = attr.replace(\"quantity\", \"position\")\n            return pos[attr]\n        except Exception as e:\n            return pos",
    "docstring": "Get the positions data for the instrument\n\n        :Optional:\n            attr : string\n                Position attribute to get\n                (optional attributes: symbol, position, avgCost, account)\n\n        :Retruns:\n            positions : dict (positions) / float/str (attribute)\n                positions data for the instrument"
  },
  {
    "code": "def _print_divide(self):\n        for space in self.AttributesLength:\n            self.StrTable += \"+ \" + \"- \" * space\n        self.StrTable += \"+\" + \"\\n\"",
    "docstring": "Prints all those table line dividers."
  },
  {
    "code": "def removeIndividual(self):\n        self._openRepo()\n        dataset = self._repo.getDatasetByName(self._args.datasetName)\n        individual = dataset.getIndividualByName(self._args.individualName)\n        def func():\n            self._updateRepo(self._repo.removeIndividual, individual)\n        self._confirmDelete(\"Individual\", individual.getLocalId(), func)",
    "docstring": "Removes an individual from this repo"
  },
  {
    "code": "def collect_summands(cls, ops, kwargs):\n    from qnet.algebra.core.abstract_quantum_algebra import (\n        ScalarTimesQuantumExpression)\n    coeff_map = OrderedDict()\n    for op in ops:\n        if isinstance(op, ScalarTimesQuantumExpression):\n            coeff, term = op.coeff, op.term\n        else:\n            coeff, term = 1, op\n        if term in coeff_map:\n            coeff_map[term] += coeff\n        else:\n            coeff_map[term] = coeff\n    fops = []\n    for (term, coeff) in coeff_map.items():\n        op = coeff * term\n        if not op.is_zero:\n            fops.append(op)\n    if len(fops) == 0:\n        return cls._zero\n    elif len(fops) == 1:\n        return fops[0]\n    else:\n        return tuple(fops), kwargs",
    "docstring": "Collect summands that occur multiple times into a single summand\n\n    Also filters out zero-summands.\n\n    Example:\n        >>> A, B, C = (OperatorSymbol(s, hs=0) for s in ('A', 'B', 'C'))\n        >>> collect_summands(\n        ...     OperatorPlus, (A, B, C, ZeroOperator, 2 * A, B, -C) , {})\n        ((3 * A^(0), 2 * B^(0)), {})\n        >>> collect_summands(OperatorPlus, (A, -A), {})\n        ZeroOperator\n        >>> collect_summands(OperatorPlus, (B, A, -B), {})\n        A^(0)"
  },
  {
    "code": "def reset_image_attribute(self, image_id, attribute='launchPermission'):\n        params = {'ImageId' : image_id,\n                  'Attribute' : attribute}\n        return self.get_status('ResetImageAttribute', params, verb='POST')",
    "docstring": "Resets an attribute of an AMI to its default value.\n\n        :type image_id: string\n        :param image_id: ID of the AMI for which an attribute will be described\n\n        :type attribute: string\n        :param attribute: The attribute to reset\n\n        :rtype: bool\n        :return: Whether the operation succeeded or not"
  },
  {
    "code": "def get_file_client(opts, pillar=False):\n    client = opts.get('file_client', 'remote')\n    if pillar and client == 'local':\n        client = 'pillar'\n    return {\n        'remote': RemoteClient,\n        'local': FSClient,\n        'pillar': PillarClient,\n    }.get(client, RemoteClient)(opts)",
    "docstring": "Read in the ``file_client`` option and return the correct type of file\n    server"
  },
  {
    "code": "def filter(self,\n               predicate: Callable[[FileLine], 'FileLineSet']\n               ) -> 'FileLineSet':\n        filtered = [fileline for fileline in self if predicate(fileline)]\n        return FileLineSet.from_list(filtered)",
    "docstring": "Returns a subset of the file lines within this set that satisfy a given\n        filtering criterion."
  },
  {
    "code": "def normalize_job_id(job_id):\n\tif not isinstance(job_id, uuid.UUID):\n\t\tjob_id = uuid.UUID(job_id)\n\treturn job_id",
    "docstring": "Convert a value to a job id.\n\n\t:param job_id: Value to convert.\n\t:type job_id: int, str\n\t:return: The job id.\n\t:rtype: :py:class:`uuid.UUID`"
  },
  {
    "code": "def clean_previous_run(self):\n        super(Alignak, self).clean_previous_run()\n        self.pollers.clear()\n        self.reactionners.clear()\n        self.brokers.clear()",
    "docstring": "Clean variables from previous configuration\n\n        :return: None"
  },
  {
    "code": "def _pb_timestamp_to_datetime(timestamp_pb):\n    return _EPOCH + datetime.timedelta(\n        seconds=timestamp_pb.seconds, microseconds=(timestamp_pb.nanos / 1000.0)\n    )",
    "docstring": "Convert a Timestamp protobuf to a datetime object.\n\n    :type timestamp_pb: :class:`google.protobuf.timestamp_pb2.Timestamp`\n    :param timestamp_pb: A Google returned timestamp protobuf.\n\n    :rtype: :class:`datetime.datetime`\n    :returns: A UTC datetime object converted from a protobuf timestamp."
  },
  {
    "code": "def _drop_gracefully(self):\n    shard_id = self.request.headers[util._MR_SHARD_ID_TASK_HEADER]\n    mr_id = self.request.headers[util._MR_ID_TASK_HEADER]\n    shard_state, mr_state = db.get([\n        model.ShardState.get_key_by_shard_id(shard_id),\n        model.MapreduceState.get_key_by_job_id(mr_id)])\n    if shard_state and shard_state.active:\n      shard_state.set_for_failure()\n      config = util.create_datastore_write_config(mr_state.mapreduce_spec)\n      shard_state.put(config=config)",
    "docstring": "Drop worker task gracefully.\n\n    Set current shard_state to failed. Controller logic will take care of\n    other shards and the entire MR."
  },
  {
    "code": "def track_parallel(items, sub_type):\n    out = []\n    for i, args in enumerate(items):\n        item_i, item = _get_provitem_from_args(args)\n        if item:\n            sub_entity = \"%s.%s.%s\" % (item[\"provenance\"][\"entity\"], sub_type, i)\n            item[\"provenance\"][\"entity\"] = sub_entity\n            args = list(args)\n            args[item_i] = item\n        out.append(args)\n    return out",
    "docstring": "Create entity identifiers to trace the given items in sub-commands.\n\n    Helps handle nesting in parallel program execution:\n\n    run id => sub-section id => parallel ids"
  },
  {
    "code": "def find_external_metabolites(model):\n    ex_comp = find_external_compartment(model)\n    return [met for met in model.metabolites if met.compartment == ex_comp]",
    "docstring": "Return all metabolites in the external compartment."
  },
  {
    "code": "def access_keys(opts):\n    keys = {}\n    publisher_acl = opts['publisher_acl']\n    acl_users = set(publisher_acl.keys())\n    if opts.get('user'):\n        acl_users.add(opts['user'])\n    acl_users.add(salt.utils.user.get_user())\n    for user in acl_users:\n        log.info('Preparing the %s key for local communication', user)\n        key = mk_key(opts, user)\n        if key is not None:\n            keys[user] = key\n    if opts['client_acl_verify'] and HAS_PWD:\n        log.profile('Beginning pwd.getpwall() call in masterapi access_keys function')\n        for user in pwd.getpwall():\n            user = user.pw_name\n            if user not in keys and salt.utils.stringutils.check_whitelist_blacklist(user, whitelist=acl_users):\n                keys[user] = mk_key(opts, user)\n        log.profile('End pwd.getpwall() call in masterapi access_keys function')\n    return keys",
    "docstring": "A key needs to be placed in the filesystem with permissions 0400 so\n    clients are required to run as root."
  },
  {
    "code": "def FindFileContainingSymbol(self, symbol):\n    symbol = _NormalizeFullyQualifiedName(symbol)\n    try:\n      return self._descriptors[symbol].file\n    except KeyError:\n      pass\n    try:\n      return self._enum_descriptors[symbol].file\n    except KeyError:\n      pass\n    try:\n      return self._FindFileContainingSymbolInDb(symbol)\n    except KeyError:\n      pass\n    try:\n      return self._file_desc_by_toplevel_extension[symbol]\n    except KeyError:\n      pass\n    message_name, _, extension_name = symbol.rpartition('.')\n    try:\n      message = self.FindMessageTypeByName(message_name)\n      assert message.extensions_by_name[extension_name]\n      return message.file\n    except KeyError:\n      raise KeyError('Cannot find a file containing %s' % symbol)",
    "docstring": "Gets the FileDescriptor for the file containing the specified symbol.\n\n    Args:\n      symbol: The name of the symbol to search for.\n\n    Returns:\n      A FileDescriptor that contains the specified symbol.\n\n    Raises:\n      KeyError: if the file cannot be found in the pool."
  },
  {
    "code": "def _add_junction(item):\n    type_, channels = _expand_one_key_dictionary(item)\n    junction = UnnamedStatement(type='junction')\n    for item in channels:\n        type_, value = _expand_one_key_dictionary(item)\n        channel = UnnamedStatement(type='channel')\n        for val in value:\n            if _is_reference(val):\n                _add_reference(val, channel)\n            elif _is_inline_definition(val):\n                _add_inline_definition(val, channel)\n        junction.add_child(channel)\n    _current_statement.add_child(junction)",
    "docstring": "Adds a junction to the _current_statement."
  },
  {
    "code": "def _processEscapeSequences(replaceText):\n    def _replaceFunc(escapeMatchObject):\n        char = escapeMatchObject.group(0)[1]\n        if char in _escapeSequences:\n            return _escapeSequences[char]\n        return escapeMatchObject.group(0)\n    return _seqReplacer.sub(_replaceFunc, replaceText)",
    "docstring": "Replace symbols like \\n \\\\, etc"
  },
  {
    "code": "def get_channel(self, name):\n        return self._api_get('/api/channels/{0}'.format(\n            urllib.parse.quote_plus(name)\n        ))",
    "docstring": "Details about an individual channel.\n\n        :param name: The channel name\n        :type name: str"
  },
  {
    "code": "def geocode(self):\n        submit_set = []\n        data_map = {}\n        for address, o in self.gen:\n            submit_set.append(address)\n            data_map[address] = o\n            if len(submit_set) >= self.submit_size:\n                results = self._send(submit_set)\n                submit_set = []\n                for k, result in results.items():\n                    o = data_map[k]\n                    yield (k, result, o)\n        if len(submit_set) > 0:\n            results = self._send(submit_set)\n            for k, result in results.items():\n                o = data_map[k]\n                yield (k, result, o)",
    "docstring": "A Generator that reads from the address generators and returns\n        geocode results.\n\n        The generator yields ( address, geocode_results, object)"
  },
  {
    "code": "def IsEquivalent(self, other):\n    if self.name and other.name:\n      return self.name == other.name\n    if self.name:\n      self_family, self_version_tuple = self._FAMILY_AND_VERSION_PER_NAME.get(\n          self.name, self._DEFAULT_FAMILY_AND_VERSION)\n      return (\n          self_family == other.family and\n          self_version_tuple == other.version_tuple)\n    if self.family and self.version:\n      if other.name:\n        other_family, other_version_tuple = (\n            self._FAMILY_AND_VERSION_PER_NAME.get(\n                other.name, self._DEFAULT_FAMILY_AND_VERSION))\n      else:\n        other_family = other.family\n        other_version_tuple = other.version_tuple\n      return (\n          self.family == other_family and\n          self.version_tuple == other_version_tuple)\n    if self.family:\n      if other.name:\n        other_family, _ = self._FAMILY_AND_VERSION_PER_NAME.get(\n            other.name, self._DEFAULT_FAMILY_AND_VERSION)\n      else:\n        other_family = other.family\n      return self.family == other_family\n    return False",
    "docstring": "Determines if 2 operating system artifacts are equivalent.\n\n    This function compares the operating systems based in order of:\n    * name derived from product\n    * family and version\n    * family\n\n    Args:\n      other (OperatingSystemArtifact): operating system artifact attribute\n          container to compare with.\n\n    Returns:\n      bool: True if the operating systems are considered equivalent, False if\n          the most specific criteria do no match, or no criteria are available."
  },
  {
    "code": "def graph_to_gluon(self, graph, ctx):\n        sym, arg_params, aux_params = self.from_onnx(graph)\n        metadata = self.get_graph_metadata(graph)\n        data_names = [input_tensor[0] for input_tensor in metadata['input_tensor_data']]\n        data_inputs = [symbol.var(data_name) for data_name in data_names]\n        from ....gluon import SymbolBlock\n        net = SymbolBlock(outputs=sym, inputs=data_inputs)\n        net_params = net.collect_params()\n        for param in arg_params:\n            if param in net_params:\n                net_params[param].shape = arg_params[param].shape\n                net_params[param]._load_init(arg_params[param], ctx=ctx)\n        for param in aux_params:\n            if param in net_params:\n                net_params[param].shape = aux_params[param].shape\n                net_params[param]._load_init(aux_params[param], ctx=ctx)\n        return net",
    "docstring": "Construct SymbolBlock from onnx graph.\n\n        Parameters\n        ----------\n        graph : onnx protobuf object\n            The loaded onnx graph\n        ctx : Context or list of Context\n            Loads the model into one or many context(s).\n\n        Returns\n        -------\n        sym_block :gluon.nn.SymbolBlock\n            The returned gluon SymbolBlock"
  },
  {
    "code": "def filepaths(self) -> List[str]:\n        path = self.currentpath\n        return [os.path.join(path, name) for name in self.filenames]",
    "docstring": "Absolute path names of the files contained in the current\n        working directory.\n\n        Files names starting with underscores are ignored:\n\n        >>> from hydpy.core.filetools import FileManager\n        >>> filemanager = FileManager()\n        >>> filemanager.BASEDIR = 'basename'\n        >>> filemanager.projectdir = 'projectname'\n        >>> from hydpy import repr_, TestIO\n        >>> with TestIO():\n        ...     filemanager.currentdir = 'testdir'\n        ...     open('projectname/basename/testdir/file1.txt', 'w').close()\n        ...     open('projectname/basename/testdir/file2.npy', 'w').close()\n        ...     open('projectname/basename/testdir/_file1.nc', 'w').close()\n        ...     for filepath in filemanager.filepaths:\n        ...         repr_(filepath)    # doctest: +ELLIPSIS\n        '...hydpy/tests/iotesting/projectname/basename/testdir/file1.txt'\n        '...hydpy/tests/iotesting/projectname/basename/testdir/file2.npy'"
  },
  {
    "code": "def echo_utc(string):\n    from datetime import datetime\n    click.echo('{} | {}'.format(datetime.utcnow().isoformat(), string))",
    "docstring": "Echo the string to standard out, prefixed with the current date and time in UTC format.\n\n    :param string: string to echo"
  },
  {
    "code": "def interested_in(self):\n        genders = []\n        for gender in self.cache['interested_in']:\n            genders.append(gender)\n        return genders",
    "docstring": "A list of strings describing the genders the user is interested in."
  },
  {
    "code": "def get_depts(self, dept_name=None):\r\n        depts = self.json_response.get(\"department\", None)\r\n        params = self.kwargs.get(\"params\", None)\r\n        fetch_child = params.get(\"fetch_child\", True) if params else True\r\n        if dept_name is not None:\r\n            depts = [dept for dept in depts if dept[\"name\"] == dept_name]\r\n        depts = [{\"id\": dept[\"id\"], \"name\": dept[\"name\"]} for dept in depts]\r\n        self.logger.info(\"%s\\t%s\" % (self.request_method, self.request_url))\r\n        return depts if fetch_child else depts[0]",
    "docstring": "Method to get department by name."
  },
  {
    "code": "def stop_recording_skipped(cls):\n        if cls._errors_recorded is None:\n            raise Exception('Cannot stop recording before it is started')\n        recorded = cls._errors_recorded[:]\n        cls._errors_recorded = None\n        return recorded",
    "docstring": "Stop collecting OptionErrors recorded with the\n        record_skipped_option method and return them"
  },
  {
    "code": "def make_epub_base(location):\n    log.info('Making EPUB base files in {0}'.format(location))\n    with open(os.path.join(location, 'mimetype'), 'w') as out:\n        out.write('application/epub+zip')\n    os.mkdir(os.path.join(location, 'META-INF'))\n    os.mkdir(os.path.join(location, 'EPUB'))\n    os.mkdir(os.path.join(location, 'EPUB', 'css'))\n    with open(os.path.join(location, 'META-INF', 'container.xml'), 'w') as out:\n        out.write(\n)\n    with open(os.path.join(location, 'EPUB', 'css', 'default.css') ,'wb') as out:\n        out.write(bytes(DEFAULT_CSS, 'UTF-8'))",
    "docstring": "Creates the base structure for an EPUB file in a specified location.\n\n    This function creates constant components for the structure of the EPUB in\n    a specified directory location.\n\n    Parameters\n    ----------\n    location : str\n        A path string to a local directory in which the EPUB is to be built"
  },
  {
    "code": "def get_iter(self, times, seconds, chunk_size=2000):\n        def entry_generator():\n            with ConstantRateLimit(times, seconds, sleep_func=self._steam.sleep) as r:\n                for entries in chunks(self, chunk_size):\n                    if not entries:\n                        return\n                    for entry in entries:\n                        yield entry\n                    r.wait()\n        return entry_generator()",
    "docstring": "Make a iterator over the entries\n\n        See :class:`steam.util.throttle.ConstantRateLimit` for ``times`` and ``seconds`` parameters.\n\n        :param chunk_size: number of entries per request\n        :type chunk_size: :class:`int`\n        :returns: generator object\n        :rtype: :class:`generator`\n\n        The iterator essentially buffers ``chuck_size`` number of entries, and ensures\n        we are not sending messages too fast.\n        For example, the ``__iter__`` method on this class uses ``get_iter(1, 1, 2000)``"
  },
  {
    "code": "def render_document(template_name, data_name, output_name):\n    env = Environment(loader=PackageLoader('aide_document'))\n    with open(output_name, 'w') as output_file:\n        output = env.get_template(template_name).render(yaml.load(open(data_name)))\n        output_file.write(output)",
    "docstring": "Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file.\n\n    Parameters\n    ==========\n    template_name : String\n        Exact name of the MarkDown template file from the aide_document/templates folder. Do not use the file path.\n    data_name : String\n        Relative file path from where this method is called to the location of the YAML data file to be used.\n    output_name : String\n        Relative file path from where this method is called to the location to which the output file is written.\n    \n    Examples\n    ========\n    Suppose we have template.md in aide_document and a directory as follows:\n    data/\n        params.yaml\n\n    To render the document:\n    >>> from aide_document import combine\n    >>> combine.render_document('template.md', 'data/params.yaml', 'data/output.md')\n\n    This will then combine the data and template files and write to a new output file within data/."
  },
  {
    "code": "def at_depth(self, level):\n        return Zconfig(lib.zconfig_at_depth(self._as_parameter_, level), False)",
    "docstring": "Locate the last config item at a specified depth"
  },
  {
    "code": "def add_entry(self, net_type, cn, addresses):\n        self.entries.append({\n            'cn': cn,\n            'addresses': addresses})",
    "docstring": "Add a request to the batch\n\n        :param net_type: str netwrok space name request is for\n        :param cn: str Canonical Name for certificate\n        :param addresses: [] List of addresses to be used as SANs"
  },
  {
    "code": "def set_file_filters(self, file_filters):\n        file_filters = util.return_list(file_filters)\n        self.file_filters = file_filters",
    "docstring": "Sets internal file filters to `file_filters` by tossing old state.\n        `file_filters` can be single object or iterable."
  },
  {
    "code": "def search(ctx, tags, prefix=None):\n    _generate_api(ctx)\n    for i, match in enumerate(ctx.obj.api.search(*tags, prefix=prefix)):\n        click.echo(match, nl=False)\n        print('')",
    "docstring": "List all archives matching tag search criteria"
  },
  {
    "code": "def update(self, argv):\n        if len(argv) == 0: \n            error(\"Command requires an index name\", 2)\n        name = argv[0]\n        if name not in self.service.indexes:\n            error(\"Index '%s' does not exist\" % name, 2)\n        index = self.service.indexes[name]\n        fields = self.service.indexes.itemmeta().fields.optional\n        rules = dict([(field, {'flags': [\"--%s\" % field]}) for field in fields])\n        opts = cmdline(argv, rules)\n        index.update(**opts.kwargs)",
    "docstring": "Update an index according to the given argument vector."
  },
  {
    "code": "def set_version(version):\n    global UNIVERSION\n    global UNIVERSION_INFO\n    if version is None:\n        version = unicodedata.unidata_version\n    UNIVERSION = version\n    UNIVERSION_INFO = tuple([int(x) for x in UNIVERSION.split('.')])",
    "docstring": "Set version."
  },
  {
    "code": "def on_key_down(self, event):\n        keycode = event.GetKeyCode()\n        meta_down = event.MetaDown() or event.GetCmdDown()\n        if keycode == 86 and meta_down:\n            self.do_fit(event)",
    "docstring": "If user does command v,\n        re-size window in case pasting has changed the content size."
  },
  {
    "code": "def _gcs_list_keys(bucket, pattern):\n  data = [{'Name': obj.metadata.name,\n           'Type': obj.metadata.content_type,\n           'Size': obj.metadata.size,\n           'Updated': obj.metadata.updated_on}\n          for obj in _gcs_get_keys(bucket, pattern)]\n  return google.datalab.utils.commands.render_dictionary(data, ['Name', 'Type', 'Size', 'Updated'])",
    "docstring": "List all Google Cloud Storage keys in a specified bucket that match a pattern."
  },
  {
    "code": "def _metric_value(value_str, metric_type):\n    if metric_type in (int, float):\n        try:\n            return metric_type(value_str)\n        except ValueError:\n            raise ValueError(\"Invalid {} metric value: {!r}\".\n                             format(metric_type.__class__.__name__, value_str))\n    elif metric_type is six.text_type:\n        return value_str.strip('\"').encode('utf-8').decode('unicode_escape')\n    else:\n        assert metric_type is bool\n        lower_str = value_str.lower()\n        if lower_str == 'true':\n            return True\n        elif lower_str == 'false':\n            return False\n        else:\n            raise ValueError(\"Invalid boolean metric value: {!r}\".\n                             format(value_str))",
    "docstring": "Return a Python-typed metric value from a metric value string."
  },
  {
    "code": "def get_current():\n    global current\n    if exists( SETTINGSFILE ):\n        f = open( SETTINGSFILE ).read()\n        current = re.findall('config[^\\s]+.+', f)[1].split('/')[-1]\n        return current\n    else:\n        return \"** Not Set **\"",
    "docstring": "return current Xresources color theme"
  },
  {
    "code": "def status(queue, munin, munin_config):\n    if munin_config:\n        return status_print_config(queue)\n    queues = get_queues(queue)\n    for queue in queues:\n        status_print_queue(queue, munin=munin)\n    if not munin:\n        print('-' * 40)",
    "docstring": "List queued tasks aggregated by name"
  },
  {
    "code": "def DeactivateCard(self, card):\n        if hasattr(card, 'connection'):\n            card.connection.disconnect()\n            if None != self.parent.apdutracerpanel:\n                card.connection.deleteObserver(self.parent.apdutracerpanel)\n            delattr(card, 'connection')\n        self.dialogpanel.OnDeactivateCard(card)",
    "docstring": "Deactivate a card."
  },
  {
    "code": "def set_motion_detect(self, enable):\n        if enable:\n            return api.request_motion_detection_enable(self.sync.blink,\n                                                       self.network_id,\n                                                       self.camera_id)\n        return api.request_motion_detection_disable(self.sync.blink,\n                                                    self.network_id,\n                                                    self.camera_id)",
    "docstring": "Set motion detection."
  },
  {
    "code": "def lint(filename, lines, config):\n    _, ext = os.path.splitext(filename)\n    if ext in config:\n        output = collections.defaultdict(list)\n        for linter in config[ext]:\n            linter_output = linter(filename, lines)\n            for category, values in linter_output[filename].items():\n                output[category].extend(values)\n        if 'comments' in output:\n            output['comments'] = sorted(\n                output['comments'],\n                key=lambda x: (x.get('line', -1), x.get('column', -1)))\n        return {filename: dict(output)}\n    else:\n        return {\n            filename: {\n                'skipped': [\n                    'no linter is defined or enabled for files'\n                    ' with extension \"%s\"' % ext\n                ]\n            }\n        }",
    "docstring": "Lints a file.\n\n    Args:\n        filename: string: filename to lint.\n        lines: list[int]|None: list of lines that we want to capture. If None,\n          then all lines will be captured.\n        config: dict[string: linter]: mapping from extension to a linter\n          function.\n\n    Returns: dict: if there were errors running the command then the field\n      'error' will have the reasons in a list. if the lint process was skipped,\n      then a field 'skipped' will be set with the reasons. Otherwise, the field\n      'comments' will have the messages."
  },
  {
    "code": "def socket(self):\n        if not hasattr(self, '_socket'):\n            self._socket = self.context.socket(zmq.REQ)\n            if hasattr(zmq, 'RECONNECT_IVL_MAX'):\n                self._socket.setsockopt(\n                    zmq.RECONNECT_IVL_MAX, 5000\n                )\n            self._set_tcp_keepalive()\n            if self.master.startswith('tcp://['):\n                if hasattr(zmq, 'IPV6'):\n                    self._socket.setsockopt(zmq.IPV6, 1)\n                elif hasattr(zmq, 'IPV4ONLY'):\n                    self._socket.setsockopt(zmq.IPV4ONLY, 0)\n            self._socket.linger = self.linger\n            if self.id_:\n                self._socket.setsockopt(zmq.IDENTITY, self.id_)\n            self._socket.connect(self.master)\n        return self._socket",
    "docstring": "Lazily create the socket."
  },
  {
    "code": "def relation_completions(\n    completion_text: str, bel_spec: BELSpec, bel_fmt: str, size: int\n) -> list:\n    if bel_fmt == \"short\":\n        relation_list = bel_spec[\"relations\"][\"list_short\"]\n    else:\n        relation_list = bel_spec[\"relations\"][\"list_long\"]\n    matches = []\n    for r in relation_list:\n        if re.match(completion_text, r):\n            matches.append(r)\n    replace_list = []\n    for match in matches:\n        highlight = match.replace(completion_text, f\"<em>{completion_text}</em>\")\n        replace_list.append(\n            {\n                \"replacement\": match,\n                \"label\": match,\n                \"highlight\": highlight,\n                \"type\": \"Relation\",\n            }\n        )\n    return replace_list[:size]",
    "docstring": "Filter BEL relations by prefix\n\n    Args:\n        prefix: completion string\n        bel_fmt: short, medium, long BEL formats\n        spec: BEL specification\n\n    Returns:\n        list: list of BEL relations that match prefix"
  },
  {
    "code": "def msg_debug(message):\n    if _log_lvl == logging.DEBUG:\n        to_stdout(\" (*) {message}\".format(message=message), colorf=cyan)\n        if _logger:\n            _logger.debug(message)",
    "docstring": "Log a debug message\n\n    :param message: the message to be logged"
  },
  {
    "code": "def load_session(fname=None):\n    if fname is None:\n        fname = conf.session\n    try:\n        s = six.moves.cPickle.load(gzip.open(fname, \"rb\"))\n    except IOError:\n        try:\n            s = six.moves.cPickle.load(open(fname, \"rb\"))\n        except IOError:\n            raise\n    scapy_session = six.moves.builtins.__dict__[\"scapy_session\"]\n    scapy_session.clear()\n    scapy_session.update(s)\n    update_ipython_session(scapy_session)\n    log_loading.info(\"Loaded session [%s]\" % fname)",
    "docstring": "Load current Scapy session from the file specified in the fname arg.\n    This will erase any existing session.\n\n    params:\n     - fname: file to load the scapy session from"
  },
  {
    "code": "def _convert_data(self, data, data_type, num_recs, num_values, num_elems):\n        if (data_type == 51 or data_type == 52):\n            return [data[i:i+num_elems].decode('utf-8') for i in\n                    range(0, num_recs*num_values*num_elems, num_elems)]\n        else:\n            tofrom = self._convert_option()\n            dt_string = self._convert_type(data_type)\n            form = tofrom + str(num_recs*num_values*num_elems) + dt_string\n            value_len = CDF._type_size(data_type, num_elems)\n            return list(struct.unpack_from(form,\n                                           data[0:num_recs*num_values*value_len]))",
    "docstring": "Converts data to the appropriate type using the struct.unpack method,\n        rather than using numpy."
  }
]